diff --git a/components/external/SQLite-3.8.1/Makefile.arm-wince-mingw32ce-gcc b/components/external/SQLite-3.8.1/Makefile.arm-wince-mingw32ce-gcc new file mode 100644 index 0000000000000000000000000000000000000000..323b7ea482f4929621c2f4d8ac749e175ea4c92f --- /dev/null +++ b/components/external/SQLite-3.8.1/Makefile.arm-wince-mingw32ce-gcc @@ -0,0 +1,138 @@ +#!/usr/make +# +# Makefile for SQLITE +# +# This is a template makefile for SQLite. Most people prefer to +# use the autoconf generated "configure" script to generate the +# makefile automatically. But that does not work for everybody +# and in every situation. If you are having problems with the +# "configure" script, you might want to try this makefile as an +# alternative. Create a copy of this file, edit the parameters +# below and type "make". +# + +#### The directory where to find the mingw32ce tools +MINGW32CE = /opt/mingw32ce/bin + +#### The target prefix of the mingw32ce tools +TARGET = arm-wince-mingw32ce + +#### The toplevel directory of the source tree. This is the directory +# that contains this "Makefile.in" and the "configure.in" script. +# +TOP = ../sqlite + +#### C Compiler and options for use in building executables that +# will run on the platform that is doing the build. +# +BCC = gcc -g -O2 +#BCC = /opt/ancic/bin/c89 -0 + +#### If the target operating system supports the "usleep()" system +# call, then define the HAVE_USLEEP macro for all C modules. +# +USLEEP = +#USLEEP = -DHAVE_USLEEP=1 + +#### If you want the SQLite library to be safe for use within a +# multi-threaded program, then define the following macro +# appropriately: +# +THREADSAFE = -DTHREADSAFE=1 +#THREADSAFE = -DTHREADSAFE=0 + +#### Specify any extra linker options needed to make the library +# thread safe +# +#THREADLIB = -lpthread +THREADLIB = + +#### Specify any extra libraries needed to access required functions. +# +#TLIBS = -lrt # fdatasync on Solaris 8 +TLIBS = + +#### Leave SQLITE_DEBUG undefined for maximum speed. Use SQLITE_DEBUG=1 +# to check for memory leaks. Use SQLITE_DEBUG=2 to print a log of all +# malloc()s and free()s in order to track down memory leaks. +# +# SQLite uses some expensive assert() statements in the inner loop. +# You can make the library go almost twice as fast if you compile +# with -DNDEBUG=1 +# +#OPTS = -DSQLITE_DEBUG=2 +#OPTS = -DSQLITE_DEBUG=1 +#OPTS = +OPTS = -DNDEBUG=1 -DSQLITE_OS_WIN=1 -D_WIN32_WCE=1 +#OPTS += -DHAVE_FDATASYNC=1 + +#### The suffix to add to executable files. ".exe" for windows. +# Nothing for unix. +# +EXE = .exe +#EXE = + +#### C Compile and options for use in building executables that +# will run on the target platform. This is usually the same +# as BCC, unless you are cross-compiling. +# +#TCC = gcc -O6 +#TCC = gcc -g -O0 -Wall +#TCC = gcc -g -O0 -Wall -fprofile-arcs -ftest-coverage +#TCC = /opt/mingw/bin/i386-mingw32-gcc -O6 +TCC = $(MINGW32CE)/$(TARGET)-gcc -O2 +#TCC = /opt/ansic/bin/c89 -O +z -Wl,-a,archive + +#### Tools used to build a static library. +# +#AR = ar cr +#AR = /opt/mingw/bin/i386-mingw32-ar cr +AR = $(MINGW32CE)/$(TARGET)-ar cr +#RANLIB = ranlib +#RANLIB = /opt/mingw/bin/i386-mingw32-ranlib +RANLIB = $(MINGW32CE)/$(TARGET)-ranlib + +#MKSHLIB = gcc -shared +#SO = so +#SHPREFIX = lib +MKSHLIB = $(MINGW32CE)/$(TARGET)-gcc -shared +SO = dll +SHPREFIX = + +#### Extra compiler options needed for programs that use the TCL library. +# +#TCL_FLAGS = +#TCL_FLAGS = -DSTATIC_BUILD=1 +TCL_FLAGS = -I/home/drh/tcltk/8.5linux +#TCL_FLAGS = -I/home/drh/tcltk/8.5win -DSTATIC_BUILD=1 +#TCL_FLAGS = -I/home/drh/tcltk/8.3hpux + +#### Linker options needed to link against the TCL library. +# +#LIBTCL = -ltcl -lm -ldl +LIBTCL = /home/drh/tcltk/8.5linux/libtcl8.5g.a -lm -ldl +#LIBTCL = /home/drh/tcltk/8.5win/libtcl85s.a -lmsvcrt +#LIBTCL = /home/drh/tcltk/8.3hpux/libtcl8.3.a -ldld -lm -lc + +#### Additional objects for SQLite library when TCL support is enabled. +TCLOBJ = +#TCLOBJ = tclsqlite.o + +#### Compiler options needed for programs that use the readline() library. +# +READLINE_FLAGS = +#READLINE_FLAGS = -DHAVE_READLINE=1 -I/usr/include/readline + +#### Linker options needed by programs using readline() must link against. +# +LIBREADLINE = +#LIBREADLINE = -static -lreadline -ltermcap + +#### Which "awk" program provides nawk compatibilty +# +# NAWK = nawk +NAWK = awk + +# You should not have to change anything below this line +############################################################################### +include $(TOP)/main.mk diff --git a/components/external/SQLite-3.8.1/Makefile.in b/components/external/SQLite-3.8.1/Makefile.in new file mode 100644 index 0000000000000000000000000000000000000000..f01cae05e7b2dcf3ebcc965eccedb800c4b05f32 --- /dev/null +++ b/components/external/SQLite-3.8.1/Makefile.in @@ -0,0 +1,996 @@ +#!/usr/make +# +# Makefile for SQLITE +# +# This makefile is suppose to be configured automatically using the +# autoconf. But if that does not work for you, you can configure +# the makefile manually. Just set the parameters below to values that +# work well for your system. +# +# If the configure script does not work out-of-the-box, you might +# be able to get it to work by giving it some hints. See the comment +# at the beginning of configure.in for additional information. +# + +# The toplevel directory of the source tree. This is the directory +# that contains this "Makefile.in" and the "configure.in" script. +# +TOP = @srcdir@ + +# C Compiler and options for use in building executables that +# will run on the platform that is doing the build. +# +BCC = @BUILD_CC@ @BUILD_CFLAGS@ + +# C Compile and options for use in building executables that +# will run on the target platform. (BCC and TCC are usually the +# same unless your are cross-compiling.) +# +TCC = @CC@ @CPPFLAGS@ @CFLAGS@ -I. -I${TOP}/src -I${TOP}/ext/rtree + +# Define this for the autoconf-based build, so that the code knows it can +# include the generated config.h +# +TCC += -D_HAVE_SQLITE_CONFIG_H -DBUILD_sqlite + +# Define -DNDEBUG to compile without debugging (i.e., for production usage) +# Omitting the define will cause extra debugging code to be inserted and +# includes extra comments when "EXPLAIN stmt" is used. +# +TCC += @TARGET_DEBUG@ @XTHREADCONNECT@ + +# Compiler options needed for programs that use the TCL library. +# +TCC += @TCL_INCLUDE_SPEC@ + +# The library that programs using TCL must link against. +# +LIBTCL = @TCL_LIB_SPEC@ + +# Compiler options needed for programs that use the readline() library. +# +READLINE_FLAGS = -DHAVE_READLINE=@TARGET_HAVE_READLINE@ @TARGET_READLINE_INC@ + +# The library that programs using readline() must link against. +# +LIBREADLINE = @TARGET_READLINE_LIBS@ + +# Should the database engine be compiled threadsafe +# +TCC += -DSQLITE_THREADSAFE=@SQLITE_THREADSAFE@ + +# Any target libraries which libsqlite must be linked against +# +TLIBS = @LIBS@ + +# Flags controlling use of the in memory btree implementation +# +# SQLITE_TEMP_STORE is 0 to force temporary tables to be in a file, 1 to +# default to file, 2 to default to memory, and 3 to force temporary +# tables to always be in memory. +# +TEMP_STORE = -DSQLITE_TEMP_STORE=@TEMP_STORE@ + +# Enable/disable loadable extensions, and other optional features +# based on configuration. (-DSQLITE_OMIT*, -DSQLITE_ENABLE*). +# The same set of OMIT and ENABLE flags should be passed to the +# LEMON parser generator and the mkkeywordhash tool as well. +OPT_FEATURE_FLAGS = @OPT_FEATURE_FLAGS@ + +TCC += $(OPT_FEATURE_FLAGS) + +# Add in any optional parameters specified on the make commane line +# ie. make "OPTS=-DSQLITE_ENABLE_FOO=1 -DSQLITE_OMIT_FOO=1". +TCC += $(OPTS) + +# Version numbers and release number for the SQLite being compiled. +# +VERSION = @VERSION@ +VERSION_NUMBER = @VERSION_NUMBER@ +RELEASE = @RELEASE@ + +# Filename extensions +# +BEXE = @BUILD_EXEEXT@ +TEXE = @TARGET_EXEEXT@ + +# The following variable is "1" if the configure script was able to locate +# the tclConfig.sh file. It is an empty string otherwise. When this +# variable is "1", the TCL extension library (libtclsqlite3.so) is built +# and installed. +# +HAVE_TCL = @HAVE_TCL@ + +# This is the command to use for tclsh - normally just "tclsh", but we may +# know the specific version we want to use +# +TCLSH_CMD = @TCLSH_CMD@ + +# Where do we want to install the tcl plugin +# +TCLLIBDIR = @TCLLIBDIR@ + +# The suffix used on shared libraries. Ex: ".dll", ".so", ".dylib" +# +SHLIB_SUFFIX = @TCL_SHLIB_SUFFIX@ + +# If gcov support was enabled by the configure script, add the appropriate +# flags here. It's not always as easy as just having the user add the right +# CFLAGS / LDFLAGS, because libtool wants to use CFLAGS when linking, which +# causes build errors with -fprofile-arcs -ftest-coverage with some GCCs. +# Supposedly GCC does the right thing if you use --coverage, but in +# practice it still fails. See: +# +# http://www.mail-archive.com/debian-gcc@lists.debian.org/msg26197.html +# +# for more info. +# +GCOV_CFLAGS1 = -DSQLITE_COVERAGE_TEST=1 -fprofile-arcs -ftest-coverage +GCOV_LDFLAGS1 = -lgcov +USE_GCOV = @USE_GCOV@ +LTCOMPILE_EXTRAS += $(GCOV_CFLAGS$(USE_GCOV)) +LTLINK_EXTRAS += $(GCOV_LDFLAGS$(USE_GCOV)) + + +# The directory into which to store package information for + +# Some standard variables and programs +# +prefix = @prefix@ +exec_prefix = @exec_prefix@ +libdir = @libdir@ +pkgconfigdir = $(libdir)/pkgconfig +bindir = @bindir@ +includedir = @includedir@ +INSTALL = @INSTALL@ +LIBTOOL = ./libtool +ALLOWRELEASE = @ALLOWRELEASE@ + +# libtool compile/link/install +LTCOMPILE = $(LIBTOOL) --mode=compile --tag=CC $(TCC) $(LTCOMPILE_EXTRAS) +LTLINK = $(LIBTOOL) --mode=link $(TCC) $(LTCOMPILE_EXTRAS) @LDFLAGS@ $(LTLINK_EXTRAS) +LTINSTALL = $(LIBTOOL) --mode=install $(INSTALL) + +# nawk compatible awk. +NAWK = @AWK@ + +# You should not have to change anything below this line +############################################################################### + +USE_AMALGAMATION = @USE_AMALGAMATION@ + +# Object files for the SQLite library (non-amalgamation). +# +LIBOBJS0 = alter.lo analyze.lo attach.lo auth.lo \ + backup.lo bitvec.lo btmutex.lo btree.lo build.lo \ + callback.lo complete.lo ctime.lo date.lo delete.lo \ + expr.lo fault.lo fkey.lo \ + fts3.lo fts3_aux.lo fts3_expr.lo fts3_hash.lo fts3_icu.lo \ + fts3_porter.lo fts3_snippet.lo fts3_tokenizer.lo fts3_tokenizer1.lo \ + fts3_tokenize_vtab.lo \ + fts3_unicode.lo fts3_unicode2.lo fts3_write.lo \ + func.lo global.lo hash.lo \ + icu.lo insert.lo journal.lo legacy.lo loadext.lo \ + main.lo malloc.lo mem0.lo mem1.lo mem2.lo mem3.lo mem5.lo \ + memjournal.lo \ + mutex.lo mutex_noop.lo mutex_unix.lo mutex_w32.lo \ + notify.lo opcodes.lo os.lo os_unix.lo os_win.lo \ + pager.lo parse.lo pcache.lo pcache1.lo pragma.lo prepare.lo printf.lo \ + random.lo resolve.lo rowset.lo rtree.lo select.lo status.lo \ + table.lo tokenize.lo trigger.lo \ + update.lo util.lo vacuum.lo \ + vdbe.lo vdbeapi.lo vdbeaux.lo vdbeblob.lo vdbemem.lo vdbesort.lo \ + vdbetrace.lo wal.lo walker.lo where.lo utf.lo vtab.lo + +# Object files for the amalgamation. +# +LIBOBJS1 = sqlite3.lo + +# Determine the real value of LIBOBJ based on the 'configure' script +# +LIBOBJ = $(LIBOBJS$(USE_AMALGAMATION)) + + +# All of the source code files. +# +SRC = \ + $(TOP)/src/alter.c \ + $(TOP)/src/analyze.c \ + $(TOP)/src/attach.c \ + $(TOP)/src/auth.c \ + $(TOP)/src/backup.c \ + $(TOP)/src/bitvec.c \ + $(TOP)/src/btmutex.c \ + $(TOP)/src/btree.c \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/build.c \ + $(TOP)/src/callback.c \ + $(TOP)/src/complete.c \ + $(TOP)/src/ctime.c \ + $(TOP)/src/date.c \ + $(TOP)/src/delete.c \ + $(TOP)/src/expr.c \ + $(TOP)/src/fault.c \ + $(TOP)/src/fkey.c \ + $(TOP)/src/func.c \ + $(TOP)/src/global.c \ + $(TOP)/src/hash.c \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + $(TOP)/src/insert.c \ + $(TOP)/src/journal.c \ + $(TOP)/src/legacy.c \ + $(TOP)/src/loadext.c \ + $(TOP)/src/main.c \ + $(TOP)/src/malloc.c \ + $(TOP)/src/mem0.c \ + $(TOP)/src/mem1.c \ + $(TOP)/src/mem2.c \ + $(TOP)/src/mem3.c \ + $(TOP)/src/mem5.c \ + $(TOP)/src/memjournal.c \ + $(TOP)/src/mutex.c \ + $(TOP)/src/mutex.h \ + $(TOP)/src/mutex_noop.c \ + $(TOP)/src/mutex_unix.c \ + $(TOP)/src/mutex_w32.c \ + $(TOP)/src/notify.c \ + $(TOP)/src/os.c \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/os_unix.c \ + $(TOP)/src/os_win.c \ + $(TOP)/src/pager.c \ + $(TOP)/src/pager.h \ + $(TOP)/src/parse.y \ + $(TOP)/src/pcache.c \ + $(TOP)/src/pcache.h \ + $(TOP)/src/pcache1.c \ + $(TOP)/src/pragma.c \ + $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c \ + $(TOP)/src/random.c \ + $(TOP)/src/resolve.c \ + $(TOP)/src/rowset.c \ + $(TOP)/src/select.c \ + $(TOP)/src/status.c \ + $(TOP)/src/shell.c \ + $(TOP)/src/sqlite.h.in \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/table.c \ + $(TOP)/src/tclsqlite.c \ + $(TOP)/src/tokenize.c \ + $(TOP)/src/trigger.c \ + $(TOP)/src/utf.c \ + $(TOP)/src/update.c \ + $(TOP)/src/util.c \ + $(TOP)/src/vacuum.c \ + $(TOP)/src/vdbe.c \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeapi.c \ + $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbeblob.c \ + $(TOP)/src/vdbemem.c \ + $(TOP)/src/vdbesort.c \ + $(TOP)/src/vdbetrace.c \ + $(TOP)/src/vdbeInt.h \ + $(TOP)/src/vtab.c \ + $(TOP)/src/wal.c \ + $(TOP)/src/wal.h \ + $(TOP)/src/walker.c \ + $(TOP)/src/where.c + +# Source code for extensions +# +SRC += \ + $(TOP)/ext/fts1/fts1.c \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.c \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_porter.c \ + $(TOP)/ext/fts1/fts1_tokenizer.h \ + $(TOP)/ext/fts1/fts1_tokenizer1.c +SRC += \ + $(TOP)/ext/fts2/fts2.c \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.c \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_icu.c \ + $(TOP)/ext/fts2/fts2_porter.c \ + $(TOP)/ext/fts2/fts2_tokenizer.h \ + $(TOP)/ext/fts2/fts2_tokenizer.c \ + $(TOP)/ext/fts2/fts2_tokenizer1.c +SRC += \ + $(TOP)/ext/fts3/fts3.c \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3Int.h \ + $(TOP)/ext/fts3/fts3_aux.c \ + $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_hash.c \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_icu.c \ + $(TOP)/ext/fts3/fts3_porter.c \ + $(TOP)/ext/fts3/fts3_snippet.c \ + $(TOP)/ext/fts3/fts3_tokenizer.h \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/fts3/fts3_tokenizer1.c \ + $(TOP)/ext/fts3/fts3_tokenize_vtab.c \ + $(TOP)/ext/fts3/fts3_unicode.c \ + $(TOP)/ext/fts3/fts3_unicode2.c \ + $(TOP)/ext/fts3/fts3_write.c +SRC += \ + $(TOP)/ext/icu/sqliteicu.h \ + $(TOP)/ext/icu/icu.c +SRC += \ + $(TOP)/ext/rtree/rtree.h \ + $(TOP)/ext/rtree/rtree.c + + +# Generated source code files +# +SRC += \ + keywordhash.h \ + opcodes.c \ + opcodes.h \ + parse.c \ + parse.h \ + config.h \ + sqlite3.h + +# Source code to the test files. +# +TESTSRC = \ + $(TOP)/src/test1.c \ + $(TOP)/src/test2.c \ + $(TOP)/src/test3.c \ + $(TOP)/src/test4.c \ + $(TOP)/src/test5.c \ + $(TOP)/src/test6.c \ + $(TOP)/src/test7.c \ + $(TOP)/src/test8.c \ + $(TOP)/src/test9.c \ + $(TOP)/src/test_autoext.c \ + $(TOP)/src/test_async.c \ + $(TOP)/src/test_backup.c \ + $(TOP)/src/test_btree.c \ + $(TOP)/src/test_config.c \ + $(TOP)/src/test_demovfs.c \ + $(TOP)/src/test_devsym.c \ + $(TOP)/src/test_fs.c \ + $(TOP)/src/test_func.c \ + $(TOP)/src/test_hexio.c \ + $(TOP)/src/test_init.c \ + $(TOP)/src/test_intarray.c \ + $(TOP)/src/test_journal.c \ + $(TOP)/src/test_malloc.c \ + $(TOP)/src/test_multiplex.c \ + $(TOP)/src/test_mutex.c \ + $(TOP)/src/test_onefile.c \ + $(TOP)/src/test_osinst.c \ + $(TOP)/src/test_pcache.c \ + $(TOP)/src/test_quota.c \ + $(TOP)/src/test_rtree.c \ + $(TOP)/src/test_schema.c \ + $(TOP)/src/test_server.c \ + $(TOP)/src/test_superlock.c \ + $(TOP)/src/test_syscall.c \ + $(TOP)/src/test_stat.c \ + $(TOP)/src/test_tclvar.c \ + $(TOP)/src/test_thread.c \ + $(TOP)/src/test_vfs.c \ + $(TOP)/src/test_wsd.c \ + $(TOP)/ext/fts3/fts3_term.c \ + $(TOP)/ext/fts3/fts3_test.c + +# Statically linked extensions +# +TESTSRC += \ + $(TOP)/ext/misc/amatch.c \ + $(TOP)/ext/misc/closure.c \ + $(TOP)/ext/misc/fuzzer.c \ + $(TOP)/ext/misc/ieee754.c \ + $(TOP)/ext/misc/nextchar.c \ + $(TOP)/ext/misc/percentile.c \ + $(TOP)/ext/misc/regexp.c \ + $(TOP)/ext/misc/spellfix.c \ + $(TOP)/ext/misc/totype.c \ + $(TOP)/ext/misc/wholenumber.c + +# Source code to the library files needed by the test fixture +# +TESTSRC2 = \ + $(TOP)/src/attach.c \ + $(TOP)/src/backup.c \ + $(TOP)/src/bitvec.c \ + $(TOP)/src/btree.c \ + $(TOP)/src/build.c \ + $(TOP)/src/ctime.c \ + $(TOP)/src/date.c \ + $(TOP)/src/expr.c \ + $(TOP)/src/func.c \ + $(TOP)/src/insert.c \ + $(TOP)/src/wal.c \ + $(TOP)/src/main.c \ + $(TOP)/src/mem5.c \ + $(TOP)/src/os.c \ + $(TOP)/src/os_unix.c \ + $(TOP)/src/os_win.c \ + $(TOP)/src/pager.c \ + $(TOP)/src/pragma.c \ + $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c \ + $(TOP)/src/random.c \ + $(TOP)/src/pcache.c \ + $(TOP)/src/pcache1.c \ + $(TOP)/src/select.c \ + $(TOP)/src/tokenize.c \ + $(TOP)/src/utf.c \ + $(TOP)/src/util.c \ + $(TOP)/src/vdbeapi.c \ + $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbe.c \ + $(TOP)/src/vdbemem.c \ + $(TOP)/src/vdbetrace.c \ + $(TOP)/src/where.c \ + parse.c \ + $(TOP)/ext/fts3/fts3.c \ + $(TOP)/ext/fts3/fts3_aux.c \ + $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_term.c \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/fts3/fts3_write.c \ + $(TOP)/ext/async/sqlite3async.c + +# Header files used by all library source files. +# +HDR = \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + keywordhash.h \ + $(TOP)/src/mutex.h \ + opcodes.h \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/pager.h \ + $(TOP)/src/pcache.h \ + parse.h \ + sqlite3.h \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeInt.h \ + config.h + +# Header files used by extensions +# +EXTHDR += \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3Int.h \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_tokenizer.h +EXTHDR += \ + $(TOP)/ext/rtree/rtree.h +EXTHDR += \ + $(TOP)/ext/icu/sqliteicu.h +EXTHDR += \ + $(TOP)/ext/rtree/sqlite3rtree.h + +# This is the default Makefile target. The objects listed here +# are what get build when you type just "make" with no arguments. +# +all: sqlite3.h libsqlite3.la sqlite3$(TEXE) $(HAVE_TCL:1=libtclsqlite3.la) + +Makefile: $(TOP)/Makefile.in + ./config.status + +sqlite3.pc: $(TOP)/sqlite3.pc.in + ./config.status + +libsqlite3.la: $(LIBOBJ) + $(LTLINK) -no-undefined -o $@ $(LIBOBJ) $(TLIBS) \ + ${ALLOWRELEASE} -rpath "$(libdir)" -version-info "8:6:8" + +libtclsqlite3.la: tclsqlite.lo libsqlite3.la + $(LTLINK) -no-undefined -o $@ tclsqlite.lo \ + libsqlite3.la @TCL_STUB_LIB_SPEC@ $(TLIBS) \ + -rpath "$(TCLLIBDIR)" \ + -version-info "8:6:8" \ + -avoid-version + +sqlite3$(TEXE): $(TOP)/src/shell.c libsqlite3.la sqlite3.h + $(LTLINK) $(READLINE_FLAGS) \ + -o $@ $(TOP)/src/shell.c libsqlite3.la \ + $(LIBREADLINE) $(TLIBS) -rpath "$(libdir)" + +mptester$(EXE): sqlite3.c $(TOP)/mptest/mptest.c + $(LTLINK) -o $@ -I. $(TOP)/mptest/mptest.c sqlite3.c \ + $(TLIBS) -rpath "$(libdir)" + + +# This target creates a directory named "tsrc" and fills it with +# copies of all of the C source code and header files needed to +# build on the target system. Some of the C source code and header +# files are automatically generated. This target takes care of +# all that automatic generation. +# +.target_source: $(SRC) $(TOP)/tool/vdbe-compress.tcl + rm -rf tsrc + mkdir tsrc + cp -f $(SRC) tsrc + rm tsrc/sqlite.h.in tsrc/parse.y + $(TCLSH_CMD) $(TOP)/tool/vdbe-compress.tcl vdbe.new + mv vdbe.new tsrc/vdbe.c + touch .target_source + +sqlite3.c: .target_source $(TOP)/tool/mksqlite3c.tcl + $(TCLSH_CMD) $(TOP)/tool/mksqlite3c.tcl + cp tsrc/shell.c tsrc/sqlite3ext.h . + +tclsqlite3.c: sqlite3.c + echo '#ifndef USE_SYSTEM_SQLITE' >tclsqlite3.c + cat sqlite3.c >>tclsqlite3.c + echo '#endif /* USE_SYSTEM_SQLITE */' >>tclsqlite3.c + cat $(TOP)/src/tclsqlite.c >>tclsqlite3.c + +sqlite3-all.c: sqlite3.c $(TOP)/tool/split-sqlite3c.tcl + $(TCLSH_CMD) $(TOP)/tool/split-sqlite3c.tcl + +# Rule to build the amalgamation +# +sqlite3.lo: sqlite3.c + $(LTCOMPILE) $(TEMP_STORE) -c sqlite3.c + +# Rules to build the LEMON compiler generator +# +lemon$(BEXE): $(TOP)/tool/lemon.c $(TOP)/src/lempar.c + $(BCC) -o $@ $(TOP)/tool/lemon.c + cp $(TOP)/src/lempar.c . + +# Rules to build individual *.o files from generated *.c files. This +# applies to: +# +# parse.o +# opcodes.o +# +parse.lo: parse.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c parse.c + +opcodes.lo: opcodes.c + $(LTCOMPILE) $(TEMP_STORE) -c opcodes.c + +# Rules to build individual *.o files from files in the src directory. +# +alter.lo: $(TOP)/src/alter.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/alter.c + +analyze.lo: $(TOP)/src/analyze.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/analyze.c + +attach.lo: $(TOP)/src/attach.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/attach.c + +auth.lo: $(TOP)/src/auth.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/auth.c + +backup.lo: $(TOP)/src/backup.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/backup.c + +bitvec.lo: $(TOP)/src/bitvec.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/bitvec.c + +btmutex.lo: $(TOP)/src/btmutex.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/btmutex.c + +btree.lo: $(TOP)/src/btree.c $(HDR) $(TOP)/src/pager.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/btree.c + +build.lo: $(TOP)/src/build.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/build.c + +callback.lo: $(TOP)/src/callback.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/callback.c + +complete.lo: $(TOP)/src/complete.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/complete.c + +ctime.lo: $(TOP)/src/ctime.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/ctime.c + +date.lo: $(TOP)/src/date.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/date.c + +delete.lo: $(TOP)/src/delete.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/delete.c + +expr.lo: $(TOP)/src/expr.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/expr.c + +fault.lo: $(TOP)/src/fault.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/fault.c + +fkey.lo: $(TOP)/src/fkey.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/fkey.c + +func.lo: $(TOP)/src/func.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/func.c + +global.lo: $(TOP)/src/global.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/global.c + +hash.lo: $(TOP)/src/hash.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/hash.c + +insert.lo: $(TOP)/src/insert.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/insert.c + +journal.lo: $(TOP)/src/journal.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/journal.c + +legacy.lo: $(TOP)/src/legacy.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/legacy.c + +loadext.lo: $(TOP)/src/loadext.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/loadext.c + +main.lo: $(TOP)/src/main.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/main.c + +malloc.lo: $(TOP)/src/malloc.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/malloc.c + +mem0.lo: $(TOP)/src/mem0.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem0.c + +mem1.lo: $(TOP)/src/mem1.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem1.c + +mem2.lo: $(TOP)/src/mem2.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem2.c + +mem3.lo: $(TOP)/src/mem3.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem3.c + +mem5.lo: $(TOP)/src/mem5.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem5.c + +memjournal.lo: $(TOP)/src/memjournal.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/memjournal.c + +mutex.lo: $(TOP)/src/mutex.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex.c + +mutex_noop.lo: $(TOP)/src/mutex_noop.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_noop.c + +mutex_unix.lo: $(TOP)/src/mutex_unix.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_unix.c + +mutex_w32.lo: $(TOP)/src/mutex_w32.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_w32.c + +notify.lo: $(TOP)/src/notify.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/notify.c + +pager.lo: $(TOP)/src/pager.c $(HDR) $(TOP)/src/pager.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pager.c + +pcache.lo: $(TOP)/src/pcache.c $(HDR) $(TOP)/src/pcache.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pcache.c + +pcache1.lo: $(TOP)/src/pcache1.c $(HDR) $(TOP)/src/pcache.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pcache1.c + +os.lo: $(TOP)/src/os.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os.c + +os_unix.lo: $(TOP)/src/os_unix.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_unix.c + +os_win.lo: $(TOP)/src/os_win.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_win.c + +pragma.lo: $(TOP)/src/pragma.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pragma.c + +prepare.lo: $(TOP)/src/prepare.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/prepare.c + +printf.lo: $(TOP)/src/printf.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/printf.c + +random.lo: $(TOP)/src/random.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/random.c + +resolve.lo: $(TOP)/src/resolve.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/resolve.c + +rowset.lo: $(TOP)/src/rowset.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/rowset.c + +select.lo: $(TOP)/src/select.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/select.c + +status.lo: $(TOP)/src/status.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/status.c + +table.lo: $(TOP)/src/table.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/table.c + +tokenize.lo: $(TOP)/src/tokenize.c keywordhash.h $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/tokenize.c + +trigger.lo: $(TOP)/src/trigger.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/trigger.c + +update.lo: $(TOP)/src/update.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/update.c + +utf.lo: $(TOP)/src/utf.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/utf.c + +util.lo: $(TOP)/src/util.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/util.c + +vacuum.lo: $(TOP)/src/vacuum.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vacuum.c + +vdbe.lo: $(TOP)/src/vdbe.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbe.c + +vdbeapi.lo: $(TOP)/src/vdbeapi.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeapi.c + +vdbeaux.lo: $(TOP)/src/vdbeaux.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeaux.c + +vdbeblob.lo: $(TOP)/src/vdbeblob.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeblob.c + +vdbemem.lo: $(TOP)/src/vdbemem.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbemem.c + +vdbesort.lo: $(TOP)/src/vdbesort.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbesort.c + +vdbetrace.lo: $(TOP)/src/vdbetrace.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbetrace.c + +vtab.lo: $(TOP)/src/vtab.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vtab.c + +wal.lo: $(TOP)/src/wal.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/wal.c + +walker.lo: $(TOP)/src/walker.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/walker.c + +where.lo: $(TOP)/src/where.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/where.c + +tclsqlite.lo: $(TOP)/src/tclsqlite.c $(HDR) + $(LTCOMPILE) -DUSE_TCL_STUBS=1 -c $(TOP)/src/tclsqlite.c + +tclsqlite-shell.lo: $(TOP)/src/tclsqlite.c $(HDR) + $(LTCOMPILE) -DTCLSH=1 -o $@ -c $(TOP)/src/tclsqlite.c + +tclsqlite-stubs.lo: $(TOP)/src/tclsqlite.c $(HDR) + $(LTCOMPILE) -DUSE_TCL_STUBS=1 -o $@ -c $(TOP)/src/tclsqlite.c + +tclsqlite3$(TEXE): tclsqlite-shell.lo libsqlite3.la + $(LTLINK) -o $@ tclsqlite-shell.lo \ + libsqlite3.la $(LIBTCL) + +# Rules to build opcodes.c and opcodes.h +# +opcodes.c: opcodes.h $(TOP)/mkopcodec.awk + $(NAWK) -f $(TOP)/mkopcodec.awk opcodes.h >opcodes.c + +opcodes.h: parse.h $(TOP)/src/vdbe.c $(TOP)/mkopcodeh.awk + cat parse.h $(TOP)/src/vdbe.c | $(NAWK) -f $(TOP)/mkopcodeh.awk >opcodes.h + +# Rules to build parse.c and parse.h - the outputs of lemon. +# +parse.h: parse.c + +parse.c: $(TOP)/src/parse.y lemon$(BEXE) $(TOP)/addopcodes.awk + cp $(TOP)/src/parse.y . + rm -f parse.h + ./lemon$(BEXE) $(OPT_FEATURE_FLAGS) $(OPTS) parse.y + mv parse.h parse.h.temp + $(NAWK) -f $(TOP)/addopcodes.awk parse.h.temp >parse.h + +sqlite3.h: $(TOP)/src/sqlite.h.in $(TOP)/manifest.uuid $(TOP)/VERSION + $(TCLSH_CMD) $(TOP)/tool/mksqlite3h.tcl $(TOP) >sqlite3.h + +keywordhash.h: $(TOP)/tool/mkkeywordhash.c + $(BCC) -o mkkeywordhash$(BEXE) $(OPT_FEATURE_FLAGS) $(OPTS) $(TOP)/tool/mkkeywordhash.c + ./mkkeywordhash$(BEXE) >keywordhash.h + + + +# Rules to build the extension objects. +# +icu.lo: $(TOP)/ext/icu/icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/icu/icu.c + +fts2.lo: $(TOP)/ext/fts2/fts2.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2.c + +fts2_hash.lo: $(TOP)/ext/fts2/fts2_hash.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_hash.c + +fts2_icu.lo: $(TOP)/ext/fts2/fts2_icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_icu.c + +fts2_porter.lo: $(TOP)/ext/fts2/fts2_porter.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_porter.c + +fts2_tokenizer.lo: $(TOP)/ext/fts2/fts2_tokenizer.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer.c + +fts2_tokenizer1.lo: $(TOP)/ext/fts2/fts2_tokenizer1.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer1.c + +fts3.lo: $(TOP)/ext/fts3/fts3.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3.c + +fts3_aux.lo: $(TOP)/ext/fts3/fts3_aux.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_aux.c + +fts3_expr.lo: $(TOP)/ext/fts3/fts3_expr.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_expr.c + +fts3_hash.lo: $(TOP)/ext/fts3/fts3_hash.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_hash.c + +fts3_icu.lo: $(TOP)/ext/fts3/fts3_icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_icu.c + +fts3_porter.lo: $(TOP)/ext/fts3/fts3_porter.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_porter.c + +fts3_snippet.lo: $(TOP)/ext/fts3/fts3_snippet.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_snippet.c + +fts3_tokenizer.lo: $(TOP)/ext/fts3/fts3_tokenizer.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer.c + +fts3_tokenizer1.lo: $(TOP)/ext/fts3/fts3_tokenizer1.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer1.c + +fts3_tokenize_vtab.lo: $(TOP)/ext/fts3/fts3_tokenize_vtab.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenize_vtab.c + +fts3_unicode.lo: $(TOP)/ext/fts3/fts3_unicode.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_unicode.c + +fts3_unicode2.lo: $(TOP)/ext/fts3/fts3_unicode2.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_unicode2.c + +fts3_write.lo: $(TOP)/ext/fts3/fts3_write.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_write.c + +rtree.lo: $(TOP)/ext/rtree/rtree.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/rtree/rtree.c + + +# Rules to build the 'testfixture' application. +# +# If using the amalgamation, use sqlite3.c directly to build the test +# fixture. Otherwise link against libsqlite3.la. (This distinction is +# necessary because the test fixture requires non-API symbols which are +# hidden when the library is built via the amalgamation). +# +TESTFIXTURE_FLAGS = -DTCLSH=1 -DSQLITE_TEST=1 -DSQLITE_CRASH_TEST=1 +TESTFIXTURE_FLAGS += -DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE +TESTFIXTURE_FLAGS += -DBUILD_sqlite + +TESTFIXTURE_SRC0 = $(TESTSRC2) libsqlite3.la +TESTFIXTURE_SRC1 = sqlite3.c +TESTFIXTURE_SRC = $(TESTSRC) $(TOP)/src/tclsqlite.c +TESTFIXTURE_SRC += $(TESTFIXTURE_SRC$(USE_AMALGAMATION)) + +testfixture$(TEXE): $(TESTFIXTURE_SRC) + $(LTLINK) -DSQLITE_NO_SYNC=1 $(TEMP_STORE) $(TESTFIXTURE_FLAGS) \ + -o $@ $(TESTFIXTURE_SRC) $(LIBTCL) $(TLIBS) + + +fulltest: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/all.test + +soaktest: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/all.test -soak=1 + +fulltestonly: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/full.test + +test: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/veryquick.test + +sqlite3_analyzer.c: sqlite3.c $(TOP)/src/test_stat.c $(TOP)/src/tclsqlite.c $(TOP)/tool/spaceanal.tcl + echo "#define TCLSH 2" > $@ + cat sqlite3.c $(TOP)/src/test_stat.c $(TOP)/src/tclsqlite.c >> $@ + echo "static const char *tclsh_main_loop(void){" >> $@ + echo "static const char *zMainloop = " >> $@ + $(NAWK) -f $(TOP)/tool/tostr.awk $(TOP)/tool/spaceanal.tcl >> $@ + echo "; return zMainloop; }" >> $@ + +sqlite3_analyzer$(TEXE): sqlite3_analyzer.c + $(LTLINK) sqlite3_analyzer.c -o $@ $(LIBTCL) $(TLIBS) + +# Standard install and cleanup targets +# +lib_install: libsqlite3.la + $(INSTALL) -d $(DESTDIR)$(libdir) + $(LTINSTALL) libsqlite3.la $(DESTDIR)$(libdir) + +install: sqlite3$(BEXE) lib_install sqlite3.h sqlite3.pc ${HAVE_TCL:1=tcl_install} + $(INSTALL) -d $(DESTDIR)$(bindir) + $(LTINSTALL) sqlite3$(BEXE) $(DESTDIR)$(bindir) + $(INSTALL) -d $(DESTDIR)$(includedir) + $(INSTALL) -m 0644 sqlite3.h $(DESTDIR)$(includedir) + $(INSTALL) -m 0644 $(TOP)/src/sqlite3ext.h $(DESTDIR)$(includedir) + $(INSTALL) -d $(DESTDIR)$(pkgconfigdir) + $(INSTALL) -m 0644 sqlite3.pc $(DESTDIR)$(pkgconfigdir) + +pkgIndex.tcl: + echo 'package ifneeded sqlite3 $(RELEASE) [list load $(TCLLIBDIR)/libtclsqlite3.so sqlite3]' > $@ +tcl_install: lib_install libtclsqlite3.la pkgIndex.tcl + $(INSTALL) -d $(DESTDIR)$(TCLLIBDIR) + $(LTINSTALL) libtclsqlite3.la $(DESTDIR)$(TCLLIBDIR) + rm -f $(DESTDIR)$(TCLLIBDIR)/libtclsqlite3.la $(DESTDIR)$(TCLLIBDIR)/libtclsqlite3.a + $(INSTALL) -m 0644 pkgIndex.tcl $(DESTDIR)$(TCLLIBDIR) + +clean: + rm -f *.lo *.la *.o sqlite3$(TEXE) libsqlite3.la + rm -f sqlite3.h opcodes.* + rm -rf .libs .deps + rm -f lemon$(BEXE) lempar.c parse.* sqlite*.tar.gz + rm -f mkkeywordhash$(BEXE) keywordhash.h + rm -f *.da *.bb *.bbg gmon.out + rm -rf quota2a quota2b quota2c + rm -rf tsrc .target_source + rm -f tclsqlite3$(TEXE) + rm -f testfixture$(TEXE) test.db + rm -f sqlite3.dll sqlite3.lib sqlite3.exp sqlite3.def + rm -f sqlite3.c + rm -f sqlite3rc.h + rm -f shell.c sqlite3ext.h + rm -f sqlite3_analyzer$(TEXE) sqlite3_analyzer.c + rm -f sqlite-*-output.vsix + rm -f mptester mptester.exe + +distclean: clean + rm -f config.log config.status libtool Makefile sqlite3.pc + +# +# Windows section +# +dll: sqlite3.dll + +REAL_LIBOBJ = $(LIBOBJ:%.lo=.libs/%.o) + +$(REAL_LIBOBJ): $(LIBOBJ) + +sqlite3.def: $(REAL_LIBOBJ) + echo 'EXPORTS' >sqlite3.def + nm $(REAL_LIBOBJ) | grep ' T ' | grep ' _sqlite3_' \ + | sed 's/^.* _//' >>sqlite3.def + +sqlite3.dll: $(REAL_LIBOBJ) sqlite3.def + $(TCC) -shared -o $@ sqlite3.def \ + -Wl,"--strip-all" $(REAL_LIBOBJ) diff --git a/components/external/SQLite-3.8.1/Makefile.linux-gcc b/components/external/SQLite-3.8.1/Makefile.linux-gcc new file mode 100644 index 0000000000000000000000000000000000000000..1c9f24f4baf710a5f27ae553f463a4e6aa4bdad5 --- /dev/null +++ b/components/external/SQLite-3.8.1/Makefile.linux-gcc @@ -0,0 +1,128 @@ +#!/usr/make +# +# Makefile for SQLITE +# +# This is a template makefile for SQLite. Most people prefer to +# use the autoconf generated "configure" script to generate the +# makefile automatically. But that does not work for everybody +# and in every situation. If you are having problems with the +# "configure" script, you might want to try this makefile as an +# alternative. Create a copy of this file, edit the parameters +# below and type "make". +# + +#### The toplevel directory of the source tree. This is the directory +# that contains this "Makefile.in" and the "configure.in" script. +# +TOP = ../sqlite + +#### C Compiler and options for use in building executables that +# will run on the platform that is doing the build. +# +BCC = gcc -g -O2 +#BCC = /opt/ancic/bin/c89 -0 + +#### If the target operating system supports the "usleep()" system +# call, then define the HAVE_USLEEP macro for all C modules. +# +#USLEEP = +USLEEP = -DHAVE_USLEEP=1 + +#### If you want the SQLite library to be safe for use within a +# multi-threaded program, then define the following macro +# appropriately: +# +#THREADSAFE = -DTHREADSAFE=1 +THREADSAFE = -DTHREADSAFE=0 + +#### Specify any extra linker options needed to make the library +# thread safe +# +#THREADLIB = -lpthread +THREADLIB = + +#### Specify any extra libraries needed to access required functions. +# +#TLIBS = -lrt # fdatasync on Solaris 8 +TLIBS = + +#### Leave SQLITE_DEBUG undefined for maximum speed. Use SQLITE_DEBUG=1 +# to check for memory leaks. Use SQLITE_DEBUG=2 to print a log of all +# malloc()s and free()s in order to track down memory leaks. +# +# SQLite uses some expensive assert() statements in the inner loop. +# You can make the library go almost twice as fast if you compile +# with -DNDEBUG=1 +# +#OPTS = -DSQLITE_DEBUG=2 +#OPTS = -DSQLITE_DEBUG=1 +#OPTS = +OPTS = -DNDEBUG=1 +OPTS += -DHAVE_FDATASYNC=1 + +#### The suffix to add to executable files. ".exe" for windows. +# Nothing for unix. +# +#EXE = .exe +EXE = + +#### C Compile and options for use in building executables that +# will run on the target platform. This is usually the same +# as BCC, unless you are cross-compiling. +# +TCC = gcc -O6 +#TCC = gcc -g -O0 -Wall +#TCC = gcc -g -O0 -Wall -fprofile-arcs -ftest-coverage +#TCC = /opt/mingw/bin/i386-mingw32-gcc -O6 +#TCC = /opt/ansic/bin/c89 -O +z -Wl,-a,archive + +#### Tools used to build a static library. +# +AR = ar cr +#AR = /opt/mingw/bin/i386-mingw32-ar cr +RANLIB = ranlib +#RANLIB = /opt/mingw/bin/i386-mingw32-ranlib + +MKSHLIB = gcc -shared +SO = so +SHPREFIX = lib +# SO = dll +# SHPREFIX = + +#### Extra compiler options needed for programs that use the TCL library. +# +#TCL_FLAGS = +#TCL_FLAGS = -DSTATIC_BUILD=1 +TCL_FLAGS = -I/home/drh/tcltk/8.5linux +#TCL_FLAGS = -I/home/drh/tcltk/8.5win -DSTATIC_BUILD=1 +#TCL_FLAGS = -I/home/drh/tcltk/8.3hpux + +#### Linker options needed to link against the TCL library. +# +#LIBTCL = -ltcl -lm -ldl +LIBTCL = /home/drh/tcltk/8.5linux/libtcl8.5g.a -lm -ldl +#LIBTCL = /home/drh/tcltk/8.5win/libtcl85s.a -lmsvcrt +#LIBTCL = /home/drh/tcltk/8.3hpux/libtcl8.3.a -ldld -lm -lc + +#### Additional objects for SQLite library when TCL support is enabled. +#TCLOBJ = +TCLOBJ = tclsqlite.o + +#### Compiler options needed for programs that use the readline() library. +# +READLINE_FLAGS = +#READLINE_FLAGS = -DHAVE_READLINE=1 -I/usr/include/readline + +#### Linker options needed by programs using readline() must link against. +# +LIBREADLINE = +#LIBREADLINE = -static -lreadline -ltermcap + +#### Which "awk" program provides nawk compatibilty +# +# NAWK = nawk +NAWK = awk + +# You should not have to change anything below this line +############################################################################### +include $(TOP)/main.mk diff --git a/components/external/SQLite-3.8.1/Makefile.msc b/components/external/SQLite-3.8.1/Makefile.msc new file mode 100644 index 0000000000000000000000000000000000000000..b9aeea334b8b02f226a6ca33124e6cdac05f43dc --- /dev/null +++ b/components/external/SQLite-3.8.1/Makefile.msc @@ -0,0 +1,1369 @@ +# +# nmake Makefile for SQLite +# + +# The toplevel directory of the source tree. This is the directory +# that contains this "Makefile.msc". +# +TOP = . + +# Set this non-0 to create and use the SQLite amalgamation file. +# +!IFNDEF USE_AMALGAMATION +USE_AMALGAMATION = 1 +!ENDIF + +# Set this non-0 to split the SQLite amalgamation file into chunks to +# be used for debugging with Visual Studio. +# +!IFNDEF SPLIT_AMALGAMATION +SPLIT_AMALGAMATION = 0 +!ENDIF + +# Set this non-0 to use the International Components for Unicode (ICU). +# +!IFNDEF USE_ICU +USE_ICU = 0 +!ENDIF + +# Set this non-0 to dynamically link to the MSVC runtime library. +# +!IFNDEF USE_CRT_DLL +USE_CRT_DLL = 0 +!ENDIF + +# Set this non-0 to generate assembly code listings for the source code +# files. +# +!IFNDEF USE_LISTINGS +USE_LISTINGS = 0 +!ENDIF + +# Set this non-0 to attempt setting the native compiler automatically +# for cross-compiling the command line tools needed during the compilation +# process. +# +!IFNDEF XCOMPILE +XCOMPILE = 0 +!ENDIF + +# Set this non-0 to use the native libraries paths for cross-compiling +# the command line tools needed during the compilation process. +# +!IFNDEF USE_NATIVE_LIBPATHS +USE_NATIVE_LIBPATHS = 0 +!ENDIF + +# Set this 0 to skip the compiling and embedding of version resources. +# +!IFNDEF USE_RC +USE_RC = 1 +!ENDIF + +# Set this non-0 to compile binaries suitable for the WinRT environment. +# This setting does not apply to any binaries that require Tcl to operate +# properly (i.e. the text fixture, etc). +# +!IFNDEF FOR_WINRT +FOR_WINRT = 0 +!ENDIF + +# Set this non-0 to skip attempting to look for and/or link with the Tcl +# runtime library. +# +!IFNDEF NO_TCL +NO_TCL = 0 +!ENDIF + +# Set this to non-0 to create and use PDBs. +# +!IFNDEF SYMBOLS +SYMBOLS = 1 +!ENDIF + +# Set this to non-0 to use the SQLite debugging heap subsystem. +# +!IFNDEF MEMDEBUG +MEMDEBUG = 0 +!ENDIF + +# Set this to non-0 to use the Win32 native heap subsystem. +# +!IFNDEF WIN32HEAP +WIN32HEAP = 0 +!ENDIF + +# Set this to one of the following values to enable various debugging +# features. Each level includes the debugging options from the previous +# levels. Currently, the recognized values for DEBUG are: +# +# 0 == NDEBUG: Disables assert() and other runtime diagnostics. +# 1 == Disables NDEBUG and all optimizations and then enables PDBs. +# 2 == SQLITE_DEBUG: Enables various diagnostics messages and code. +# 3 == SQLITE_WIN32_MALLOC_VALIDATE: Validate the Win32 native heap per call. +# 4 == SQLITE_DEBUG_OS_TRACE: Enables output from the OSTRACE() macros. +# 5 == SQLITE_ENABLE_IOTRACE: Enables output from the IOTRACE() macros. +# +!IFNDEF DEBUG +DEBUG = 0 +!ENDIF + +# Enable use of available compiler optimizations? Normally, this should be +# non-zero. Setting this to zero, thus disabling all compiler optimizations, +# can be useful for testing. +# +!IFNDEF OPTIMIZATIONS +OPTIMIZATIONS = 2 +!ENDIF + +# Check for the predefined command macro CC. This should point to the compiler +# binary for the target platform. If it is not defined, simply define it to +# the legacy default value 'cl.exe'. +# +!IFNDEF CC +CC = cl.exe +!ENDIF + +# Check for the command macro LD. This should point to the linker binary for +# the target platform. If it is not defined, simply define it to the legacy +# default value 'link.exe'. +# +!IFNDEF LD +LD = link.exe +!ENDIF + +# Check for the predefined command macro RC. This should point to the resource +# compiler binary for the target platform. If it is not defined, simply define +# it to the legacy default value 'rc.exe'. +# +!IFNDEF RC +RC = rc.exe +!ENDIF + +# Check for the command macro NCC. This should point to the compiler binary +# for the platform the compilation process is taking place on. If it is not +# defined, simply define it to have the same value as the CC macro. When +# cross-compiling, it is suggested that this macro be modified via the command +# line (since nmake itself does not provide a built-in method to guess it). +# For example, to use the x86 compiler when cross-compiling for x64, a command +# line similar to the following could be used (all on one line): +# +# nmake /f Makefile.msc sqlite3.dll +# XCOMPILE=1 USE_NATIVE_LIBPATHS=1 +# +# Alternatively, the full path and file name to the compiler binary for the +# platform the compilation process is taking place may be specified (all on +# one line): +# +# nmake /f Makefile.msc sqlite3.dll +# "NCC=""%VCINSTALLDIR%\bin\cl.exe""" +# USE_NATIVE_LIBPATHS=1 +# +!IFDEF NCC +NCC = $(NCC:\\=\) +!ELSEIF $(XCOMPILE)!=0 +NCC = "$(VCINSTALLDIR)\bin\cl.exe" +NCC = $(NCC:\\=\) +!ELSE +NCC = $(CC) +!ENDIF + +# Check for the MSVC runtime library path macro. Othertise, this +# value will default to the 'lib' directory underneath the MSVC +# installation directory. +# +!IFNDEF NCRTLIBPATH +NCRTLIBPATH = $(VCINSTALLDIR)\lib +!ENDIF + +NCRTLIBPATH = $(NCRTLIBPATH:\\=\) + +# Check for the Platform SDK library path macro. Othertise, this +# value will default to the 'lib' directory underneath the Windows +# SDK installation directory (the environment variable used appears +# to be available when using Visual C++ 2008 or later via the +# command line). +# +!IFNDEF NSDKLIBPATH +NSDKLIBPATH = $(WINDOWSSDKDIR)\lib +!ENDIF + +NSDKLIBPATH = $(NSDKLIBPATH:\\=\) + +# C compiler and options for use in building executables that +# will run on the platform that is doing the build. +# +BCC = $(NCC) -W3 + +# Check if assembly code listings should be generated for the source +# code files to be compiled. +# +!IF $(USE_LISTINGS)!=0 +BCC = $(BCC) -FAcs +!ENDIF + +# Check if the native library paths should be used when compiling +# the command line tools used during the compilation process. If +# so, set the necessary macro now. +# +!IF $(USE_NATIVE_LIBPATHS)!=0 +NLTLIBPATHS = "/LIBPATH:$(NCRTLIBPATH)" "/LIBPATH:$(NSDKLIBPATH)" +!ENDIF + +# C compiler and options for use in building executables that +# will run on the target platform. (BCC and TCC are usually the +# same unless your are cross-compiling.) +# +TCC = $(CC) -W3 -DSQLITE_OS_WIN=1 -I$(TOP) -I$(TOP)\src -fp:precise +RCC = $(RC) -DSQLITE_OS_WIN=1 -I$(TOP) -I$(TOP)\src + +# Check if assembly code listings should be generated for the source +# code files to be compiled. +# +!IF $(USE_LISTINGS)!=0 +TCC = $(TCC) -FAcs +!ENDIF + +# When compiling the library for use in the WinRT environment, +# the following compile-time options must be used as well to +# disable use of Win32 APIs that are not available and to enable +# use of Win32 APIs that are specific to Windows 8 and/or WinRT. +# +!IF $(FOR_WINRT)!=0 +TCC = $(TCC) -DSQLITE_OS_WINRT=1 +RCC = $(RCC) -DSQLITE_OS_WINRT=1 +TCC = $(TCC) -DWINAPI_FAMILY=WINAPI_FAMILY_APP +RCC = $(RCC) -DWINAPI_FAMILY=WINAPI_FAMILY_APP +!ENDIF + +# Also, we need to dynamically link to the correct MSVC runtime +# when compiling for WinRT (e.g. debug or release) OR if the +# USE_CRT_DLL option is set to force dynamically linking to the +# MSVC runtime library. +# +!IF $(FOR_WINRT)!=0 || $(USE_CRT_DLL)!=0 +!IF $(DEBUG)>0 +TCC = $(TCC) -MDd +BCC = $(BCC) -MDd +!ELSE +TCC = $(TCC) -MD +BCC = $(BCC) -MD +!ENDIF +!ELSE +!IF $(DEBUG)>0 +TCC = $(TCC) -MTd +BCC = $(BCC) -MTd +!ELSE +TCC = $(TCC) -MT +BCC = $(BCC) -MT +!ENDIF +!ENDIF + +# The mksqlite3c.tcl and mksqlite3h.tcl scripts will pull in +# any extension header files by default. For non-amalgamation +# builds, we need to make sure the compiler can find these. +# +!IF $(USE_AMALGAMATION)==0 +TCC = $(TCC) -I$(TOP)\ext\fts3 +RCC = $(RCC) -I$(TOP)\ext\fts3 +TCC = $(TCC) -I$(TOP)\ext\rtree +RCC = $(RCC) -I$(TOP)\ext\rtree +!ENDIF + +# Define -DNDEBUG to compile without debugging (i.e., for production usage) +# Omitting the define will cause extra debugging code to be inserted and +# includes extra comments when "EXPLAIN stmt" is used. +# +!IF $(DEBUG)==0 +TCC = $(TCC) -DNDEBUG +BCC = $(BCC) -DNDEBUG +RCC = $(RCC) -DNDEBUG +!ENDIF + +!IF $(DEBUG)>1 +TCC = $(TCC) -DSQLITE_DEBUG +RCC = $(RCC) -DSQLITE_DEBUG +!ENDIF + +!IF $(DEBUG)>3 +TCC = $(TCC) -DSQLITE_DEBUG_OS_TRACE=1 +RCC = $(RCC) -DSQLITE_DEBUG_OS_TRACE=1 +!ENDIF + +!IF $(DEBUG)>4 +TCC = $(TCC) -DSQLITE_ENABLE_IOTRACE +RCC = $(RCC) -DSQLITE_ENABLE_IOTRACE +!ENDIF + +# +# Prevent warnings about "insecure" MSVC runtime library functions +# being used. +# +TCC = $(TCC) -D_CRT_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS +BCC = $(BCC) -D_CRT_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS +RCC = $(RCC) -D_CRT_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS + +# +# Prevent warnings about "deprecated" POSIX functions being used. +# +TCC = $(TCC) -D_CRT_NONSTDC_NO_DEPRECATE -D_CRT_NONSTDC_NO_WARNINGS +BCC = $(BCC) -D_CRT_NONSTDC_NO_DEPRECATE -D_CRT_NONSTDC_NO_WARNINGS +RCC = $(RCC) -D_CRT_NONSTDC_NO_DEPRECATE -D_CRT_NONSTDC_NO_WARNINGS + +# +# Use the SQLite debugging heap subsystem? +# +!IF $(MEMDEBUG)!=0 +TCC = $(TCC) -DSQLITE_MEMDEBUG=1 +RCC = $(RCC) -DSQLITE_MEMDEBUG=1 + +# +# Use native Win32 heap subsystem instead of malloc/free? +# +!ELSEIF $(WIN32HEAP)!=0 +TCC = $(TCC) -DSQLITE_WIN32_MALLOC=1 +RCC = $(RCC) -DSQLITE_WIN32_MALLOC=1 + +# +# Validate the heap on every call into the native Win32 heap subsystem? +# +!IF $(DEBUG)>2 +TCC = $(TCC) -DSQLITE_WIN32_MALLOC_VALIDATE=1 +RCC = $(RCC) -DSQLITE_WIN32_MALLOC_VALIDATE=1 +!ENDIF +!ENDIF + +# The locations of the Tcl header and library files. Also, the library that +# non-stubs enabled programs using Tcl must link against. These variables +# (TCLINCDIR, TCLLIBDIR, and LIBTCL) may be overridden via the environment +# prior to running nmake in order to match the actual installed location and +# version on this machine. +# +!IFNDEF TCLINCDIR +TCLINCDIR = c:\tcl\include +!ENDIF + +!IFNDEF TCLLIBDIR +TCLLIBDIR = c:\tcl\lib +!ENDIF + +!IFNDEF LIBTCL +LIBTCL = tcl85.lib +!ENDIF + +# The locations of the ICU header and library files. These variables +# (ICUINCDIR, ICULIBDIR, and LIBICU) may be overridden via the environment +# prior to running nmake in order to match the actual installed location on +# this machine. +# +!IFNDEF ICUINCDIR +ICUINCDIR = c:\icu\include +!ENDIF + +!IFNDEF ICULIBDIR +ICULIBDIR = c:\icu\lib +!ENDIF + +!IFNDEF LIBICU +LIBICU = icuuc.lib icuin.lib +!ENDIF + +# This is the command to use for tclsh - normally just "tclsh", but we may +# know the specific version we want to use. This variable (TCLSH_CMD) may be +# overridden via the environment prior to running nmake in order to select a +# specific Tcl shell to use. +# +!IFNDEF TCLSH_CMD +TCLSH_CMD = tclsh85 +!ENDIF + +# Compiler options needed for programs that use the readline() library. +# +!IFNDEF READLINE_FLAGS +READLINE_FLAGS = -DHAVE_READLINE=0 +!ENDIF + +# The library that programs using readline() must link against. +# +!IFNDEF LIBREADLINE +LIBREADLINE = +!ENDIF + +# Should the database engine be compiled threadsafe +# +TCC = $(TCC) -DSQLITE_THREADSAFE=1 +RCC = $(RCC) -DSQLITE_THREADSAFE=1 + +# Do threads override each others locks by default (1), or do we test (-1) +# +TCC = $(TCC) -DSQLITE_THREAD_OVERRIDE_LOCK=-1 +RCC = $(RCC) -DSQLITE_THREAD_OVERRIDE_LOCK=-1 + +# Any target libraries which libsqlite must be linked against +# +!IFNDEF TLIBS +TLIBS = +!ENDIF + +# Flags controlling use of the in memory btree implementation +# +# SQLITE_TEMP_STORE is 0 to force temporary tables to be in a file, 1 to +# default to file, 2 to default to memory, and 3 to force temporary +# tables to always be in memory. +# +TCC = $(TCC) -DSQLITE_TEMP_STORE=1 +RCC = $(RCC) -DSQLITE_TEMP_STORE=1 + +# Enable/disable loadable extensions, and other optional features +# based on configuration. (-DSQLITE_OMIT*, -DSQLITE_ENABLE*). +# The same set of OMIT and ENABLE flags should be passed to the +# LEMON parser generator and the mkkeywordhash tool as well. + +# BEGIN standard options +OPT_FEATURE_FLAGS = $(OPT_FEATURE_FLAGS) -DSQLITE_ENABLE_FTS3=1 +OPT_FEATURE_FLAGS = $(OPT_FEATURE_FLAGS) -DSQLITE_ENABLE_RTREE=1 +OPT_FEATURE_FLAGS = $(OPT_FEATURE_FLAGS) -DSQLITE_ENABLE_COLUMN_METADATA=1 +# END standard options + +# BEGIN required Windows option +OPT_FEATURE_FLAGS = $(OPT_FEATURE_FLAGS) -DSQLITE_MAX_TRIGGER_DEPTH=100 +# END required Windows option + +TCC = $(TCC) $(OPT_FEATURE_FLAGS) +RCC = $(RCC) $(OPT_FEATURE_FLAGS) + +# Add in any optional parameters specified on the make commane line +# ie. make "OPTS=-DSQLITE_ENABLE_FOO=1 -DSQLITE_OMIT_FOO=1". +TCC = $(TCC) $(OPTS) +RCC = $(RCC) $(OPTS) + +# If compiling for debugging, add some defines. +!IF $(DEBUG)>0 +TCC = $(TCC) -D_DEBUG +BCC = $(BCC) -D_DEBUG +RCC = $(RCC) -D_DEBUG +!ENDIF + +# If optimizations are enabled or disabled (either implicitly or +# explicitly), add the necessary flags. +!IF $(DEBUG)>0 || $(OPTIMIZATIONS)==0 +TCC = $(TCC) -Od +BCC = $(BCC) -Od +!ELSEIF $(OPTIMIZATIONS)>=3 +TCC = $(TCC) -Ox +BCC = $(BCC) -Ox +!ELSEIF $(OPTIMIZATIONS)==2 +TCC = $(TCC) -O2 +BCC = $(BCC) -O2 +!ELSEIF $(OPTIMIZATIONS)==1 +TCC = $(TCC) -O1 +BCC = $(BCC) -O1 +!ENDIF + +# If symbols are enabled (or compiling for debugging), enable PDBs. +!IF $(DEBUG)>0 || $(SYMBOLS)!=0 +TCC = $(TCC) -Zi +BCC = $(BCC) -Zi +!ENDIF + +# If ICU support is enabled, add the compiler options for it. +!IF $(USE_ICU)!=0 +TCC = $(TCC) -DSQLITE_ENABLE_ICU=1 +RCC = $(RCC) -DSQLITE_ENABLE_ICU=1 +TCC = $(TCC) -I$(TOP)\ext\icu +RCC = $(RCC) -I$(TOP)\ext\icu +TCC = $(TCC) -I$(ICUINCDIR) +RCC = $(RCC) -I$(ICUINCDIR) +!ENDIF + +# Command line prefixes for compiling code, compiling resources, +# linking, etc. +LTCOMPILE = $(TCC) -Fo$@ +LTRCOMPILE = $(RCC) -r +LTLIB = lib.exe +LTLINK = $(TCC) -Fe$@ + +# If a platform was set, force the linker to target that. +# Note that the vcvars*.bat family of batch files typically +# set this for you. Otherwise, the linker will attempt +# to deduce the binary type based on the object files. +!IFDEF PLATFORM +LTLINKOPTS = /MACHINE:$(PLATFORM) +LTLIBOPTS = /MACHINE:$(PLATFORM) +!ENDIF + +# When compiling for use in the WinRT environment, the following +# linker option must be used to mark the executable as runnable +# only in the context of an application container. +# +!IF $(FOR_WINRT)!=0 +LTLINKOPTS = $(LTLINKOPTS) /APPCONTAINER +!IF "$(VISUALSTUDIOVERSION)"=="12.0" +!IF "$(PLATFORM)"=="x86" +LTLINKOPTS = $(LTLINKOPTS) "/LIBPATH:$(VCINSTALLDIR)\lib\store" +!ELSEIF "$(PLATFORM)"=="x64" +LTLINKOPTS = $(LTLINKOPTS) "/LIBPATH:$(VCINSTALLDIR)\lib\store\amd64" +!ELSEIF "$(PLATFORM)"=="ARM" +LTLINKOPTS = $(LTLINKOPTS) "/LIBPATH:$(VCINSTALLDIR)\lib\store\arm" +!ELSE +LTLINKOPTS = $(LTLINKOPTS) "/LIBPATH:$(VCINSTALLDIR)\lib\store" +!ENDIF +!ENDIF +!ENDIF + +# If either debugging or symbols are enabled, enable PDBs. +!IF $(DEBUG)>0 || $(SYMBOLS)!=0 +LDFLAGS = /DEBUG +!ENDIF + +# Start with the Tcl related linker options. +!IF $(NO_TCL)==0 +LTLIBPATHS = /LIBPATH:$(TCLLIBDIR) +LTLIBS = $(LIBTCL) +!ENDIF + +# If ICU support is enabled, add the linker options for it. +!IF $(USE_ICU)!=0 +LTLIBPATHS = $(LTLIBPATHS) /LIBPATH:$(ICULIBDIR) +LTLIBS = $(LTLIBS) $(LIBICU) +!ENDIF + +# nawk compatible awk. +!IFNDEF NAWK +NAWK = gawk.exe +!ENDIF + +# You should not have to change anything below this line +############################################################################### + +# Object files for the SQLite library (non-amalgamation). +# +LIBOBJS0 = vdbe.lo parse.lo alter.lo analyze.lo attach.lo auth.lo \ + backup.lo bitvec.lo btmutex.lo btree.lo build.lo \ + callback.lo complete.lo ctime.lo date.lo delete.lo \ + expr.lo fault.lo fkey.lo \ + fts3.lo fts3_aux.lo fts3_expr.lo fts3_hash.lo fts3_icu.lo \ + fts3_porter.lo fts3_snippet.lo fts3_tokenizer.lo fts3_tokenizer1.lo \ + fts3_tokenize_vtab.lo fts3_unicode.lo fts3_unicode2.lo fts3_write.lo \ + func.lo global.lo hash.lo \ + icu.lo insert.lo journal.lo legacy.lo loadext.lo \ + main.lo malloc.lo mem0.lo mem1.lo mem2.lo mem3.lo mem5.lo \ + memjournal.lo \ + mutex.lo mutex_noop.lo mutex_unix.lo mutex_w32.lo \ + notify.lo opcodes.lo os.lo os_unix.lo os_win.lo \ + pager.lo pcache.lo pcache1.lo pragma.lo prepare.lo printf.lo \ + random.lo resolve.lo rowset.lo rtree.lo select.lo status.lo \ + table.lo tokenize.lo trigger.lo \ + update.lo util.lo vacuum.lo \ + vdbeapi.lo vdbeaux.lo vdbeblob.lo vdbemem.lo vdbesort.lo \ + vdbetrace.lo wal.lo walker.lo where.lo utf.lo vtab.lo + +# Object files for the amalgamation. +# +LIBOBJS1 = sqlite3.lo + +# Determine the real value of LIBOBJ based on the 'configure' script +# +!IF $(USE_AMALGAMATION)==0 +LIBOBJ = $(LIBOBJS0) +!ELSE +LIBOBJ = $(LIBOBJS1) +!ENDIF + +# Determine if embedded resource compilation and usage are enabled. +# +!IF $(USE_RC)!=0 +LIBRESOBJS = sqlite3res.lo +!ELSE +LIBRESOBJS = +!ENDIF + +# All of the source code files. +# +SRC = \ + $(TOP)\src\alter.c \ + $(TOP)\src\analyze.c \ + $(TOP)\src\attach.c \ + $(TOP)\src\auth.c \ + $(TOP)\src\backup.c \ + $(TOP)\src\bitvec.c \ + $(TOP)\src\btmutex.c \ + $(TOP)\src\btree.c \ + $(TOP)\src\btree.h \ + $(TOP)\src\btreeInt.h \ + $(TOP)\src\build.c \ + $(TOP)\src\callback.c \ + $(TOP)\src\complete.c \ + $(TOP)\src\ctime.c \ + $(TOP)\src\date.c \ + $(TOP)\src\delete.c \ + $(TOP)\src\expr.c \ + $(TOP)\src\fault.c \ + $(TOP)\src\fkey.c \ + $(TOP)\src\func.c \ + $(TOP)\src\global.c \ + $(TOP)\src\hash.c \ + $(TOP)\src\hash.h \ + $(TOP)\src\hwtime.h \ + $(TOP)\src\insert.c \ + $(TOP)\src\journal.c \ + $(TOP)\src\legacy.c \ + $(TOP)\src\loadext.c \ + $(TOP)\src\main.c \ + $(TOP)\src\malloc.c \ + $(TOP)\src\mem0.c \ + $(TOP)\src\mem1.c \ + $(TOP)\src\mem2.c \ + $(TOP)\src\mem3.c \ + $(TOP)\src\mem5.c \ + $(TOP)\src\memjournal.c \ + $(TOP)\src\mutex.c \ + $(TOP)\src\mutex.h \ + $(TOP)\src\mutex_noop.c \ + $(TOP)\src\mutex_unix.c \ + $(TOP)\src\mutex_w32.c \ + $(TOP)\src\notify.c \ + $(TOP)\src\os.c \ + $(TOP)\src\os.h \ + $(TOP)\src\os_common.h \ + $(TOP)\src\os_unix.c \ + $(TOP)\src\os_win.c \ + $(TOP)\src\pager.c \ + $(TOP)\src\pager.h \ + $(TOP)\src\parse.y \ + $(TOP)\src\pcache.c \ + $(TOP)\src\pcache.h \ + $(TOP)\src\pcache1.c \ + $(TOP)\src\pragma.c \ + $(TOP)\src\prepare.c \ + $(TOP)\src\printf.c \ + $(TOP)\src\random.c \ + $(TOP)\src\resolve.c \ + $(TOP)\src\rowset.c \ + $(TOP)\src\select.c \ + $(TOP)\src\status.c \ + $(TOP)\src\shell.c \ + $(TOP)\src\sqlite.h.in \ + $(TOP)\src\sqlite3ext.h \ + $(TOP)\src\sqliteInt.h \ + $(TOP)\src\sqliteLimit.h \ + $(TOP)\src\table.c \ + $(TOP)\src\tclsqlite.c \ + $(TOP)\src\tokenize.c \ + $(TOP)\src\trigger.c \ + $(TOP)\src\utf.c \ + $(TOP)\src\update.c \ + $(TOP)\src\util.c \ + $(TOP)\src\vacuum.c \ + $(TOP)\src\vdbe.c \ + $(TOP)\src\vdbe.h \ + $(TOP)\src\vdbeapi.c \ + $(TOP)\src\vdbeaux.c \ + $(TOP)\src\vdbeblob.c \ + $(TOP)\src\vdbemem.c \ + $(TOP)\src\vdbesort.c \ + $(TOP)\src\vdbetrace.c \ + $(TOP)\src\vdbeInt.h \ + $(TOP)\src\vtab.c \ + $(TOP)\src\wal.c \ + $(TOP)\src\wal.h \ + $(TOP)\src\walker.c \ + $(TOP)\src\where.c + +# Source code for extensions +# +SRC = $(SRC) \ + $(TOP)\ext\fts1\fts1.c \ + $(TOP)\ext\fts1\fts1.h \ + $(TOP)\ext\fts1\fts1_hash.c \ + $(TOP)\ext\fts1\fts1_hash.h \ + $(TOP)\ext\fts1\fts1_porter.c \ + $(TOP)\ext\fts1\fts1_tokenizer.h \ + $(TOP)\ext\fts1\fts1_tokenizer1.c +SRC = $(SRC) \ + $(TOP)\ext\fts2\fts2.c \ + $(TOP)\ext\fts2\fts2.h \ + $(TOP)\ext\fts2\fts2_hash.c \ + $(TOP)\ext\fts2\fts2_hash.h \ + $(TOP)\ext\fts2\fts2_icu.c \ + $(TOP)\ext\fts2\fts2_porter.c \ + $(TOP)\ext\fts2\fts2_tokenizer.h \ + $(TOP)\ext\fts2\fts2_tokenizer.c \ + $(TOP)\ext\fts2\fts2_tokenizer1.c +SRC = $(SRC) \ + $(TOP)\ext\fts3\fts3.c \ + $(TOP)\ext\fts3\fts3.h \ + $(TOP)\ext\fts3\fts3Int.h \ + $(TOP)\ext\fts3\fts3_aux.c \ + $(TOP)\ext\fts3\fts3_expr.c \ + $(TOP)\ext\fts3\fts3_hash.c \ + $(TOP)\ext\fts3\fts3_hash.h \ + $(TOP)\ext\fts3\fts3_icu.c \ + $(TOP)\ext\fts3\fts3_porter.c \ + $(TOP)\ext\fts3\fts3_snippet.c \ + $(TOP)\ext\fts3\fts3_tokenizer.h \ + $(TOP)\ext\fts3\fts3_tokenizer.c \ + $(TOP)\ext\fts3\fts3_tokenizer1.c \ + $(TOP)\ext\fts3\fts3_tokenize_vtab.c \ + $(TOP)\ext\fts3\fts3_unicode.c \ + $(TOP)\ext\fts3\fts3_unicode2.c \ + $(TOP)\ext\fts3\fts3_write.c +SRC = $(SRC) \ + $(TOP)\ext\icu\sqliteicu.h \ + $(TOP)\ext\icu\icu.c +SRC = $(SRC) \ + $(TOP)\ext\rtree\rtree.h \ + $(TOP)\ext\rtree\rtree.c + + +# Generated source code files +# +SRC = $(SRC) \ + keywordhash.h \ + opcodes.c \ + opcodes.h \ + parse.c \ + parse.h \ + sqlite3.h + +# Source code to the test files. +# +TESTSRC = \ + $(TOP)\src\test1.c \ + $(TOP)\src\test2.c \ + $(TOP)\src\test3.c \ + $(TOP)\src\test4.c \ + $(TOP)\src\test5.c \ + $(TOP)\src\test6.c \ + $(TOP)\src\test7.c \ + $(TOP)\src\test8.c \ + $(TOP)\src\test9.c \ + $(TOP)\src\test_autoext.c \ + $(TOP)\src\test_async.c \ + $(TOP)\src\test_backup.c \ + $(TOP)\src\test_btree.c \ + $(TOP)\src\test_config.c \ + $(TOP)\src\test_demovfs.c \ + $(TOP)\src\test_devsym.c \ + $(TOP)\src\test_fs.c \ + $(TOP)\src\test_func.c \ + $(TOP)\src\test_hexio.c \ + $(TOP)\src\test_init.c \ + $(TOP)\src\test_intarray.c \ + $(TOP)\src\test_journal.c \ + $(TOP)\src\test_malloc.c \ + $(TOP)\src\test_multiplex.c \ + $(TOP)\src\test_mutex.c \ + $(TOP)\src\test_onefile.c \ + $(TOP)\src\test_osinst.c \ + $(TOP)\src\test_pcache.c \ + $(TOP)\src\test_quota.c \ + $(TOP)\src\test_rtree.c \ + $(TOP)\src\test_schema.c \ + $(TOP)\src\test_server.c \ + $(TOP)\src\test_superlock.c \ + $(TOP)\src\test_syscall.c \ + $(TOP)\src\test_stat.c \ + $(TOP)\src\test_tclvar.c \ + $(TOP)\src\test_thread.c \ + $(TOP)\src\test_vfs.c \ + $(TOP)\src\test_wsd.c \ + $(TOP)\ext\fts3\fts3_term.c \ + $(TOP)\ext\fts3\fts3_test.c + +# Statically linked extensions +# +TESTEXT = \ + $(TOP)\ext\misc\amatch.c \ + $(TOP)\ext\misc\closure.c \ + $(TOP)\ext\misc\fuzzer.c \ + $(TOP)\ext\misc\ieee754.c \ + $(TOP)\ext\misc\nextchar.c \ + $(TOP)\ext\misc\percentile.c \ + $(TOP)\ext\misc\regexp.c \ + $(TOP)\ext\misc\spellfix.c \ + $(TOP)\ext\misc\totype.c \ + $(TOP)\ext\misc\wholenumber.c + + +# Source code to the library files needed by the test fixture +# +TESTSRC2 = \ + $(TOP)\src\attach.c \ + $(TOP)\src\backup.c \ + $(TOP)\src\bitvec.c \ + $(TOP)\src\btree.c \ + $(TOP)\src\build.c \ + $(TOP)\src\ctime.c \ + $(TOP)\src\date.c \ + $(TOP)\src\expr.c \ + $(TOP)\src\func.c \ + $(TOP)\src\insert.c \ + $(TOP)\src\wal.c \ + $(TOP)\src\main.c \ + $(TOP)\src\mem5.c \ + $(TOP)\src\os.c \ + $(TOP)\src\os_unix.c \ + $(TOP)\src\os_win.c \ + $(TOP)\src\pager.c \ + $(TOP)\src\pragma.c \ + $(TOP)\src\prepare.c \ + $(TOP)\src\printf.c \ + $(TOP)\src\random.c \ + $(TOP)\src\pcache.c \ + $(TOP)\src\pcache1.c \ + $(TOP)\src\select.c \ + $(TOP)\src\tokenize.c \ + $(TOP)\src\utf.c \ + $(TOP)\src\util.c \ + $(TOP)\src\vdbeapi.c \ + $(TOP)\src\vdbeaux.c \ + $(TOP)\src\vdbe.c \ + $(TOP)\src\vdbemem.c \ + $(TOP)\src\vdbesort.c \ + $(TOP)\src\vdbetrace.c \ + $(TOP)\src\where.c \ + parse.c \ + $(TOP)\ext\fts3\fts3.c \ + $(TOP)\ext\fts3\fts3_aux.c \ + $(TOP)\ext\fts3\fts3_expr.c \ + $(TOP)\ext\fts3\fts3_tokenizer.c \ + $(TOP)\ext\fts3\fts3_tokenize_vtab.c \ + $(TOP)\ext\fts3\fts3_unicode.c \ + $(TOP)\ext\fts3\fts3_unicode2.c \ + $(TOP)\ext\fts3\fts3_write.c \ + $(TOP)\ext\async\sqlite3async.c + +# Header files used by all library source files. +# +HDR = \ + $(TOP)\src\btree.h \ + $(TOP)\src\btreeInt.h \ + $(TOP)\src\hash.h \ + $(TOP)\src\hwtime.h \ + keywordhash.h \ + $(TOP)\src\mutex.h \ + opcodes.h \ + $(TOP)\src\os.h \ + $(TOP)\src\os_common.h \ + $(TOP)\src\pager.h \ + $(TOP)\src\pcache.h \ + parse.h \ + sqlite3.h \ + $(TOP)\src\sqlite3ext.h \ + $(TOP)\src\sqliteInt.h \ + $(TOP)\src\sqliteLimit.h \ + $(TOP)\src\vdbe.h \ + $(TOP)\src\vdbeInt.h + +# Header files used by extensions +# +EXTHDR = $(EXTHDR) \ + $(TOP)\ext\fts1\fts1.h \ + $(TOP)\ext\fts1\fts1_hash.h \ + $(TOP)\ext\fts1\fts1_tokenizer.h +EXTHDR = $(EXTHDR) \ + $(TOP)\ext\fts2\fts2.h \ + $(TOP)\ext\fts2\fts2_hash.h \ + $(TOP)\ext\fts2\fts2_tokenizer.h +EXTHDR = $(EXTHDR) \ + $(TOP)\ext\fts3\fts3.h \ + $(TOP)\ext\fts3\fts3Int.h \ + $(TOP)\ext\fts3\fts3_hash.h \ + $(TOP)\ext\fts3\fts3_tokenizer.h +EXTHDR = $(EXTHDR) \ + $(TOP)\ext\rtree\rtree.h +EXTHDR = $(EXTHDR) \ + $(TOP)\ext\icu\sqliteicu.h +EXTHDR = $(EXTHDR) \ + $(TOP)\ext\rtree\sqlite3rtree.h + +# This is the default Makefile target. The objects listed here +# are what get build when you type just "make" with no arguments. +# +all: dll libsqlite3.lib sqlite3.exe libtclsqlite3.lib + +libsqlite3.lib: $(LIBOBJ) + $(LTLIB) $(LTLIBOPTS) /OUT:$@ $(LIBOBJ) $(TLIBS) + +libtclsqlite3.lib: tclsqlite.lo libsqlite3.lib + $(LTLIB) $(LTLIBOPTS) $(LTLIBPATHS) /OUT:$@ tclsqlite.lo libsqlite3.lib $(LIBTCL:tcl=tclstub) $(TLIBS) + +sqlite3.exe: $(TOP)\src\shell.c libsqlite3.lib $(LIBRESOBJS) sqlite3.h + $(LTLINK) $(READLINE_FLAGS) \ + $(TOP)\src\shell.c \ + /link $(LTLINKOPTS) $(LTLIBPATHS) libsqlite3.lib $(LIBRESOBJS) $(LIBREADLINE) $(LTLIBS) $(TLIBS) + +mptester.exe: $(TOP)\mptest\mptest.c libsqlite3.lib $(LIBRESOBJS) sqlite3.h + $(LTLINK) $(TOP)\mptest\mptest.c \ + /link $(LTLINKOPTS) $(LTLIBPATHS) libsqlite3.lib $(LIBRESOBJS) $(LIBREADLINE) $(LTLIBS) $(TLIBS) + +# This target creates a directory named "tsrc" and fills it with +# copies of all of the C source code and header files needed to +# build on the target system. Some of the C source code and header +# files are automatically generated. This target takes care of +# all that automatic generation. +# +.target_source: $(SRC) $(TOP)\tool\vdbe-compress.tcl + -rmdir /S/Q tsrc + -mkdir tsrc + for %i in ($(SRC)) do copy /Y %i tsrc + del /Q tsrc\sqlite.h.in tsrc\parse.y + $(TCLSH_CMD) $(TOP)\tool\vdbe-compress.tcl < tsrc\vdbe.c > vdbe.new + move vdbe.new tsrc\vdbe.c + echo > .target_source + +sqlite3.c: .target_source $(TOP)\tool\mksqlite3c.tcl + $(TCLSH_CMD) $(TOP)\tool\mksqlite3c.tcl + copy tsrc\shell.c . + copy tsrc\sqlite3ext.h . + +sqlite3-all.c: sqlite3.c $(TOP)\tool\split-sqlite3c.tcl + $(TCLSH_CMD) $(TOP)\tool\split-sqlite3c.tcl + +# Set the source code file to be used by executables and libraries when +# they need the amalgamation. +# +!IF $(SPLIT_AMALGAMATION)!=0 +SQLITE3C = sqlite3-all.c +!ELSE +SQLITE3C = sqlite3.c +!ENDIF + +# Rule to build the amalgamation +# +sqlite3.lo: $(SQLITE3C) + $(LTCOMPILE) -c $(SQLITE3C) + +# Rules to build the LEMON compiler generator +# +lempar.c: $(TOP)\src\lempar.c + copy $(TOP)\src\lempar.c . + +lemon.exe: $(TOP)\tool\lemon.c lempar.c + $(BCC) -Daccess=_access -Fe$@ $(TOP)\tool\lemon.c /link $(NLTLIBPATHS) + +# Rules to build individual *.lo files from generated *.c files. This +# applies to: +# +# parse.lo +# opcodes.lo +# +parse.lo: parse.c $(HDR) + $(LTCOMPILE) -c parse.c + +opcodes.lo: opcodes.c + $(LTCOMPILE) -c opcodes.c + +# Rule to build the Win32 resources object file. +# +!IF $(USE_RC)!=0 +$(LIBRESOBJS): $(TOP)\src\sqlite3.rc $(HDR) + echo #ifndef SQLITE_RESOURCE_VERSION > sqlite3rc.h + for /F %%V in ('type "$(TOP)\VERSION"') do ( \ + echo #define SQLITE_RESOURCE_VERSION %%V \ + | $(NAWK) "/.*/ { gsub(/[.]/,\",\");print }" >> sqlite3rc.h \ + ) + echo #endif >> sqlite3rc.h + $(LTRCOMPILE) -fo $(LIBRESOBJS) $(TOP)\src\sqlite3.rc +!ENDIF + +# Rules to build individual *.lo files from files in the src directory. +# +alter.lo: $(TOP)\src\alter.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\alter.c + +analyze.lo: $(TOP)\src\analyze.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\analyze.c + +attach.lo: $(TOP)\src\attach.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\attach.c + +auth.lo: $(TOP)\src\auth.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\auth.c + +backup.lo: $(TOP)\src\backup.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\backup.c + +bitvec.lo: $(TOP)\src\bitvec.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\bitvec.c + +btmutex.lo: $(TOP)\src\btmutex.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\btmutex.c + +btree.lo: $(TOP)\src\btree.c $(HDR) $(TOP)\src\pager.h + $(LTCOMPILE) -c $(TOP)\src\btree.c + +build.lo: $(TOP)\src\build.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\build.c + +callback.lo: $(TOP)\src\callback.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\callback.c + +complete.lo: $(TOP)\src\complete.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\complete.c + +ctime.lo: $(TOP)\src\ctime.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\ctime.c + +date.lo: $(TOP)\src\date.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\date.c + +delete.lo: $(TOP)\src\delete.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\delete.c + +expr.lo: $(TOP)\src\expr.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\expr.c + +fault.lo: $(TOP)\src\fault.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\fault.c + +fkey.lo: $(TOP)\src\fkey.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\fkey.c + +func.lo: $(TOP)\src\func.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\func.c + +global.lo: $(TOP)\src\global.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\global.c + +hash.lo: $(TOP)\src\hash.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\hash.c + +insert.lo: $(TOP)\src\insert.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\insert.c + +journal.lo: $(TOP)\src\journal.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\journal.c + +legacy.lo: $(TOP)\src\legacy.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\legacy.c + +loadext.lo: $(TOP)\src\loadext.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\loadext.c + +main.lo: $(TOP)\src\main.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\main.c + +malloc.lo: $(TOP)\src\malloc.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\malloc.c + +mem0.lo: $(TOP)\src\mem0.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\mem0.c + +mem1.lo: $(TOP)\src\mem1.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\mem1.c + +mem2.lo: $(TOP)\src\mem2.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\mem2.c + +mem3.lo: $(TOP)\src\mem3.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\mem3.c + +mem5.lo: $(TOP)\src\mem5.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\mem5.c + +memjournal.lo: $(TOP)\src\memjournal.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\memjournal.c + +mutex.lo: $(TOP)\src\mutex.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\mutex.c + +mutex_noop.lo: $(TOP)\src\mutex_noop.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\mutex_noop.c + +mutex_unix.lo: $(TOP)\src\mutex_unix.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\mutex_unix.c + +mutex_w32.lo: $(TOP)\src\mutex_w32.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\mutex_w32.c + +notify.lo: $(TOP)\src\notify.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\notify.c + +pager.lo: $(TOP)\src\pager.c $(HDR) $(TOP)\src\pager.h + $(LTCOMPILE) -c $(TOP)\src\pager.c + +pcache.lo: $(TOP)\src\pcache.c $(HDR) $(TOP)\src\pcache.h + $(LTCOMPILE) -c $(TOP)\src\pcache.c + +pcache1.lo: $(TOP)\src\pcache1.c $(HDR) $(TOP)\src\pcache.h + $(LTCOMPILE) -c $(TOP)\src\pcache1.c + +os.lo: $(TOP)\src\os.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\os.c + +os_unix.lo: $(TOP)\src\os_unix.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\os_unix.c + +os_win.lo: $(TOP)\src\os_win.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\os_win.c + +pragma.lo: $(TOP)\src\pragma.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\pragma.c + +prepare.lo: $(TOP)\src\prepare.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\prepare.c + +printf.lo: $(TOP)\src\printf.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\printf.c + +random.lo: $(TOP)\src\random.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\random.c + +resolve.lo: $(TOP)\src\resolve.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\resolve.c + +rowset.lo: $(TOP)\src\rowset.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\rowset.c + +select.lo: $(TOP)\src\select.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\select.c + +status.lo: $(TOP)\src\status.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\status.c + +table.lo: $(TOP)\src\table.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\table.c + +tokenize.lo: $(TOP)\src\tokenize.c keywordhash.h $(HDR) + $(LTCOMPILE) -c $(TOP)\src\tokenize.c + +trigger.lo: $(TOP)\src\trigger.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\trigger.c + +update.lo: $(TOP)\src\update.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\update.c + +utf.lo: $(TOP)\src\utf.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\utf.c + +util.lo: $(TOP)\src\util.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\util.c + +vacuum.lo: $(TOP)\src\vacuum.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\vacuum.c + +vdbe.lo: $(TOP)\src\vdbe.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\vdbe.c + +vdbeapi.lo: $(TOP)\src\vdbeapi.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\vdbeapi.c + +vdbeaux.lo: $(TOP)\src\vdbeaux.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\vdbeaux.c + +vdbeblob.lo: $(TOP)\src\vdbeblob.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\vdbeblob.c + +vdbemem.lo: $(TOP)\src\vdbemem.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\vdbemem.c + +vdbesort.lo: $(TOP)\src\vdbesort.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\vdbesort.c + +vdbetrace.lo: $(TOP)\src\vdbetrace.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\vdbetrace.c + +vtab.lo: $(TOP)\src\vtab.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\vtab.c + +wal.lo: $(TOP)\src\wal.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\wal.c + +walker.lo: $(TOP)\src\walker.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\walker.c + +where.lo: $(TOP)\src\where.c $(HDR) + $(LTCOMPILE) -c $(TOP)\src\where.c + +tclsqlite.lo: $(TOP)\src\tclsqlite.c $(HDR) + $(LTCOMPILE) -DUSE_TCL_STUBS=1 -DBUILD_sqlite -I$(TCLINCDIR) -c $(TOP)\src\tclsqlite.c + +tclsqlite-shell.lo: $(TOP)\src\tclsqlite.c $(HDR) + $(LTCOMPILE) -DTCLSH=1 -DBUILD_sqlite -I$(TCLINCDIR) -c $(TOP)\src\tclsqlite.c + +tclsqlite3.exe: tclsqlite-shell.lo libsqlite3.lib $(LIBRESOBJS) + $(LD) $(LDFLAGS) $(LTLINKOPTS) $(LTLIBPATHS) /OUT:$@ libsqlite3.lib tclsqlite-shell.lo $(LIBRESOBJS) $(LTLIBS) $(TLIBS) + +# Rules to build opcodes.c and opcodes.h +# +opcodes.c: opcodes.h $(TOP)\mkopcodec.awk + $(NAWK) -f $(TOP)\mkopcodec.awk opcodes.h > opcodes.c + +opcodes.h: parse.h $(TOP)\src\vdbe.c $(TOP)\mkopcodeh.awk + type parse.h $(TOP)\src\vdbe.c | $(NAWK) -f $(TOP)\mkopcodeh.awk > opcodes.h + +# Rules to build parse.c and parse.h - the outputs of lemon. +# +parse.h: parse.c + +parse.c: $(TOP)\src\parse.y lemon.exe $(TOP)\addopcodes.awk + del /Q parse.y parse.h parse.h.temp + copy $(TOP)\src\parse.y . + .\lemon.exe $(OPT_FEATURE_FLAGS) $(OPTS) parse.y + move parse.h parse.h.temp + $(NAWK) -f $(TOP)\addopcodes.awk parse.h.temp > parse.h + +sqlite3.h: $(TOP)\src\sqlite.h.in $(TOP)\manifest.uuid $(TOP)\VERSION + $(TCLSH_CMD) $(TOP)\tool\mksqlite3h.tcl $(TOP) > sqlite3.h + +mkkeywordhash.exe: $(TOP)\tool\mkkeywordhash.c + $(BCC) -Fe$@ $(OPT_FEATURE_FLAGS) $(OPTS) $(TOP)\tool\mkkeywordhash.c /link $(NLTLIBPATHS) + +keywordhash.h: $(TOP)\tool\mkkeywordhash.c mkkeywordhash.exe + .\mkkeywordhash.exe > keywordhash.h + + + +# Rules to build the extension objects. +# +icu.lo: $(TOP)\ext\icu\icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\icu\icu.c + +fts2.lo: $(TOP)\ext\fts2\fts2.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts2\fts2.c + +fts2_hash.lo: $(TOP)\ext\fts2\fts2_hash.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts2\fts2_hash.c + +fts2_icu.lo: $(TOP)\ext\fts2\fts2_icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts2\fts2_icu.c + +fts2_porter.lo: $(TOP)\ext\fts2\fts2_porter.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts2\fts2_porter.c + +fts2_tokenizer.lo: $(TOP)\ext\fts2\fts2_tokenizer.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts2\fts2_tokenizer.c + +fts2_tokenizer1.lo: $(TOP)\ext\fts2\fts2_tokenizer1.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts2\fts2_tokenizer1.c + +fts3.lo: $(TOP)\ext\fts3\fts3.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3.c + +fts3_aux.lo: $(TOP)\ext\fts3\fts3_aux.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_aux.c + +fts3_expr.lo: $(TOP)\ext\fts3\fts3_expr.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_expr.c + +fts3_hash.lo: $(TOP)\ext\fts3\fts3_hash.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_hash.c + +fts3_icu.lo: $(TOP)\ext\fts3\fts3_icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_icu.c + +fts3_snippet.lo: $(TOP)\ext\fts3\fts3_snippet.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_snippet.c + +fts3_porter.lo: $(TOP)\ext\fts3\fts3_porter.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_porter.c + +fts3_tokenizer.lo: $(TOP)\ext\fts3\fts3_tokenizer.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_tokenizer.c + +fts3_tokenizer1.lo: $(TOP)\ext\fts3\fts3_tokenizer1.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_tokenizer1.c + +fts3_tokenize_vtab.lo: $(TOP)\ext\fts3\fts3_tokenize_vtab.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_tokenize_vtab.c + +fts3_unicode.lo: $(TOP)\ext\fts3\fts3_unicode.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_unicode.c + +fts3_unicode2.lo: $(TOP)\ext\fts3\fts3_unicode2.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_unicode2.c + +fts3_write.lo: $(TOP)\ext\fts3\fts3_write.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\fts3\fts3_write.c + +rtree.lo: $(TOP)\ext\rtree\rtree.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)\ext\rtree\rtree.c + + +# Rules to build the 'testfixture' application. +# +# If using the amalgamation, use sqlite3.c directly to build the test +# fixture. Otherwise link against libsqlite3.lib. (This distinction is +# necessary because the test fixture requires non-API symbols which are +# hidden when the library is built via the amalgamation). +# +TESTFIXTURE_FLAGS = -DTCLSH=1 -DSQLITE_TEST=1 -DSQLITE_CRASH_TEST=1 +TESTFIXTURE_FLAGS = $(TESTFIXTURE_FLAGS) -DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE + +TESTFIXTURE_SRC0 = $(TESTEXT) $(TESTSRC2) libsqlite3.lib +TESTFIXTURE_SRC1 = $(TESTEXT) $(SQLITE3C) +!IF $(USE_AMALGAMATION)==0 +TESTFIXTURE_SRC = $(TESTSRC) $(TOP)\src\tclsqlite.c $(TESTFIXTURE_SRC0) +!ELSE +TESTFIXTURE_SRC = $(TESTSRC) $(TOP)\src\tclsqlite.c $(TESTFIXTURE_SRC1) +!ENDIF + +testfixture.exe: $(TESTFIXTURE_SRC) $(LIBRESOBJS) $(HDR) + $(LTLINK) -DSQLITE_NO_SYNC=1 $(TESTFIXTURE_FLAGS) \ + -DBUILD_sqlite -I$(TCLINCDIR) \ + $(TESTFIXTURE_SRC) \ + /link $(LTLINKOPTS) $(LTLIBPATHS) $(LIBRESOBJS) $(LTLIBS) $(TLIBS) + +fulltest: testfixture.exe sqlite3.exe + .\testfixture.exe $(TOP)\test\all.test + +soaktest: testfixture.exe sqlite3.exe + .\testfixture.exe $(TOP)\test\all.test -soak=1 + +fulltestonly: testfixture.exe sqlite3.exe + .\testfixture.exe $(TOP)\test\full.test + +queryplantest: testfixture.exe sqlite3.exe + .\testfixture.exe $(TOP)\test\permutations.test queryplanner + +test: testfixture.exe sqlite3.exe + .\testfixture.exe $(TOP)\test\veryquick.test + +sqlite3_analyzer.c: $(SQLITE3C) $(TOP)\src\test_stat.c $(TOP)\src\tclsqlite.c $(TOP)\tool\spaceanal.tcl + copy $(SQLITE3C) + $(TOP)\src\test_stat.c + $(TOP)\src\tclsqlite.c $@ + echo static const char *tclsh_main_loop(void){ >> $@ + echo static const char *zMainloop = >> $@ + $(NAWK) -f $(TOP)\tool\tostr.awk $(TOP)\tool\spaceanal.tcl >> $@ + echo ; return zMainloop; } >> $@ + +sqlite3_analyzer.exe: sqlite3_analyzer.c $(LIBRESOBJS) + $(LTLINK) -DBUILD_sqlite -DTCLSH=2 -I$(TCLINCDIR) sqlite3_analyzer.c \ + /link $(LTLINKOPTS) $(LTLIBPATHS) $(LIBRESOBJS) $(LTLIBS) $(TLIBS) + +clean: + del /Q *.lo *.ilk *.lib *.obj *.pdb sqlite3.exe libsqlite3.lib + del /Q *.cod *.da *.bb *.bbg gmon.out + del /Q sqlite3.h opcodes.c opcodes.h + del /Q lemon.exe lempar.c parse.* + del /Q mkkeywordhash.exe keywordhash.h + -rmdir /Q/S .deps + -rmdir /Q/S .libs + -rmdir /Q/S quota2a + -rmdir /Q/S quota2b + -rmdir /Q/S quota2c + -rmdir /Q/S tsrc + del /Q .target_source + del /Q tclsqlite3.exe tclsqlite3.exp + del /Q testfixture.exe testfixture.exp test.db + del /Q sqlite3.dll sqlite3.lib sqlite3.exp sqlite3.def + del /Q sqlite3.c sqlite3-*.c + del /Q sqlite3rc.h + del /Q shell.c sqlite3ext.h + del /Q sqlite3_analyzer.exe sqlite3_analyzer.exp sqlite3_analyzer.c + del /Q sqlite-*-output.vsix + del /Q mptester.exe + +# Dynamic link library section. +# +dll: sqlite3.dll + +sqlite3.def: libsqlite3.lib + echo EXPORTS > sqlite3.def + dumpbin /all libsqlite3.lib \ + | $(NAWK) "/ 1 _?sqlite3_/ { sub(/^.* _?/,\"\");print }" \ + | sort >> sqlite3.def + +sqlite3.dll: $(LIBOBJ) $(LIBRESOBJS) sqlite3.def + $(LD) $(LDFLAGS) $(LTLINKOPTS) $(LTLIBPATHS) /DLL /DEF:sqlite3.def /OUT:$@ $(LIBOBJ) $(LIBRESOBJS) $(LTLIBS) $(TLIBS) diff --git a/components/external/SQLite-3.8.1/Makefile.vxworks b/components/external/SQLite-3.8.1/Makefile.vxworks new file mode 100644 index 0000000000000000000000000000000000000000..c9058da3e52390668526be9217dcd8fa65295116 --- /dev/null +++ b/components/external/SQLite-3.8.1/Makefile.vxworks @@ -0,0 +1,667 @@ +#!/usr/make +# +# Makefile for SQLITE on VxWorks + +ifeq ($(FORCPU),) + FORCPU = SH32gnule +endif + +TOOL_FAMILY = gnu + +include $(WIND_USR)/tool/gnu/make.$(FORCPU) + +#### The toplevel directory of the source tree. This is the directory +# that contains this "Makefile.in" and the "configure.in" script. +# +TOP = . + +#### C Compiler and options for use in building executables that +# will run on the platform that is doing the build. +# +BCC = gcc -g -O2 +#BCC = /opt/ancic/bin/c89 -0 + +#### If the target operating system supports the "usleep()" system +# call, then define the HAVE_USLEEP macro for all C modules. +# +USLEEP = +#USLEEP = -DHAVE_USLEEP=1 + +#### If you want the SQLite library to be safe for use within a +# multi-threaded program, then define the following macro +# appropriately: +# +THREADSAFE = -DSQLITE_THREADSAFE=1 +#THREADSAFE = -DSQLITE_THREADSAFE=0 + +#### Specify any extra linker options needed to make the library +# thread safe +# +#THREADLIB = -lpthread +THREADLIB = + +#### Specify any extra libraries needed to access required functions. +# +ifeq ($(CPU),SH32) + # for SH4 shared library + TLIBS_SHARED += -L$(WIND_USR)/lib/sh/SH32/commonle/PIC +else + # for all other CPUs shared library + TLIBS_SHARED += $(LD_LINK_PATH_ATEND) $(LD_PARTIAL_LAST_FLAGS) +endif +# for static library +TLIBS += $(LD_LINK_PATH_ATEND) $(LD_PARTIAL_LAST_FLAGS) + +#### Leave SQLITE_DEBUG undefined for maximum speed. Use SQLITE_DEBUG=1 +# to check for memory leaks. Use SQLITE_DEBUG=2 to print a log of all +# malloc()s and free()s in order to track down memory leaks. +# +# SQLite uses some expensive assert() statements in the inner loop. +# You can make the library go almost twice as fast if you compile +# with -DNDEBUG=1 +# +#OPTS = -DSQLITE_DEBUG=2 +#OPTS = -DSQLITE_DEBUG=1 +#OPTS = +OPTS = -DNDEBUG=1 -DSQLITE_OS_UNIX=1 $(THREADSAFE) +OPTS += -DSQLITE_OMIT_LOAD_EXTENSION=1 +OPTS += -DSQLITE_ENABLE_LOCKING_STYLE=1 +OPTS += -DSQLITE_THREAD_OVERRIDE_LOCK=0 +OPTS += -DSQLITE_ENABLE_COLUMN_METADATA=1 +OPTS += -DHAVE_FDATASYNC=1 + +#### The suffix to add to executable files. ".exe" for windows. +# Nothing for unix. +# +EXE = .vxe +#EXE = + +#### C Compile and options for use in building executables that +# will run on the target platform. This is usually the same +# as BCC, unless you are cross-compiling. +# +#TCC = gcc -O6 +#TCC = gcc -g -O0 -Wall +#TCC = gcc -g -O0 -Wall -fprofile-arcs -ftest-coverage +#TCC = /opt/mingw/bin/i386-mingw32-gcc -O6 +TCC = $(CC) $(DEFINE_CC) -O2 -g -mrtp $(CC_ARCH_SPEC) -D_REENTRANT=1 -D_VX_CPU=_VX_$(CPU) -D_VX_TOOL_FAMILY=$(TOOL_FAMILY) -D_VX_TOOL=$(TOOL) +TCC += -I$(WIND_USR)/h -I$(WIND_USR)/h/wrn/coreip +#TCC = /opt/ansic/bin/c89 -O +z -Wl,-a,archive + +#TCC_SHARED = $(TCC) -fPIC +TCC_SHARED = $(TCC) + +#### Tools used to build a static library. +# +#ARX = ar cr +#ARX = /opt/mingw/bin/i386-mingw32-ar cr +AR += cr +#RANLIB = ranlib +#RANLIB = /opt/mingw/bin/i386-mingw32-ranlib + +#MKSHLIB = gcc -shared +#SO = so +#SHPREFIX = lib +MKSHLIB = $(CC) $(DEFINE_CC) -mrtp -shared $(CC_ARCH_SPEC) -D_VX_CPU=_VX_$(CPU) -D_VX_TOOL_FAMILY=$(TOOL_FAMILY) -D_VX_TOOL=$(TOOL) +SO = so +SHPREFIX = lib + +#### Extra compiler options needed for programs that use the TCL library. +# +#TCL_FLAGS = +#TCL_FLAGS = -DSTATIC_BUILD=1 +TCL_FLAGS = -I/home/drh/tcltk/8.5linux +#TCL_FLAGS = -I/home/drh/tcltk/8.5win -DSTATIC_BUILD=1 +#TCL_FLAGS = -I/home/drh/tcltk/8.3hpux + +#### Linker options needed to link against the TCL library. +# +#LIBTCL = -ltcl -lm -ldl +LIBTCL = /home/drh/tcltk/8.5linux/libtcl8.5g.a -lm -ldl +#LIBTCL = /home/drh/tcltk/8.5win/libtcl85s.a -lmsvcrt +#LIBTCL = /home/drh/tcltk/8.3hpux/libtcl8.3.a -ldld -lm -lc + +#### Additional objects for SQLite library when TCL support is enabled. +TCLOBJ = +#TCLOBJ = tclsqlite.o + +#### Compiler options needed for programs that use the readline() library. +# +READLINE_FLAGS = +#READLINE_FLAGS = -DHAVE_READLINE=1 -I/usr/include/readline + +#### Linker options needed by programs using readline() must link against. +# +LIBREADLINE = +#LIBREADLINE = -static -lreadline -ltermcap + +#### Which "awk" program provides nawk compatibilty +# +# NAWK = nawk +NAWK = awk + + +#### Pasted and adapted main.mk file +############################################################################### +# The following macros should be defined before this script is +# invoked: +# +# TOP The toplevel directory of the source tree. This is the +# directory that contains this "Makefile.in" and the +# "configure.in" script. +# +# BCC C Compiler and options for use in building executables that +# will run on the platform that is doing the build. +# +# THREADLIB Specify any extra linker options needed to make the library +# thread safe +# +# OPTS Extra compiler command-line options. +# +# EXE The suffix to add to executable files. ".exe" for windows +# and "" for Unix. +# +# TCC C Compiler and options for use in building executables that +# will run on the target platform. This is usually the same +# as BCC, unless you are cross-compiling. +# +# AR Tools used to build a static library. +# RANLIB +# +# TCL_FLAGS Extra compiler options needed for programs that use the +# TCL library. +# +# LIBTCL Linker options needed to link against the TCL library. +# +# READLINE_FLAGS Compiler options needed for programs that use the +# readline() library. +# +# LIBREADLINE Linker options needed by programs using readline() must +# link against. +# +# NAWK Nawk compatible awk program. Older (obsolete?) solaris +# systems need this to avoid using the original AT&T AWK. +# +# Once the macros above are defined, the rest of this make script will +# build the SQLite library and testing tools. +################################################################################ + +# This is how we compile +# +TCCX = $(TCC) $(OPTS) -I. -I$(TOP)/src -I$(TOP) +TCCX_SHARED = $(TCC_SHARED) $(OPTS) -I. -I$(TOP)/src -I$(TOP) \ + -I$(TOP)/ext/rtree -I$(TOP)/ext/icu -I$(TOP)/ext/fts3 \ + -I$(TOP)/ext/async + +# Object files for the SQLite library. +# +LIBOBJ+= alter.o analyze.o attach.o auth.o \ + backup.o bitvec.o btmutex.o btree.o build.o \ + callback.o complete.o date.o delete.o expr.o fault.o \ + fts3.o fts3_expr.o fts3_hash.o fts3_icu.o fts3_porter.o \ + fts3_tokenizer.o fts3_tokenizer1.o \ + func.o global.o hash.o \ + icu.o insert.o journal.o legacy.o loadext.o \ + main.o malloc.o mem0.o mem1.o mem2.o mem3.o mem5.o \ + memjournal.o \ + mutex.o mutex_noop.o mutex_unix.o mutex_w32.o \ + notify.o opcodes.o os.o os_unix.o os_win.o \ + pager.o parse.o pcache.o pcache1.o pragma.o prepare.o printf.o \ + random.o resolve.o rowset.o rtree.o select.o status.o \ + table.o tokenize.o trigger.o \ + update.o util.o vacuum.o \ + vdbe.o vdbeapi.o vdbeaux.o vdbeblob.o vdbemem.o \ + walker.o where.o utf.o vtab.o + + + +# All of the source code files. +# +SRC = \ + $(TOP)/src/alter.c \ + $(TOP)/src/analyze.c \ + $(TOP)/src/attach.c \ + $(TOP)/src/auth.c \ + $(TOP)/src/backup.c \ + $(TOP)/src/bitvec.c \ + $(TOP)/src/btmutex.c \ + $(TOP)/src/btree.c \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/build.c \ + $(TOP)/src/callback.c \ + $(TOP)/src/complete.c \ + $(TOP)/src/ctime.c \ + $(TOP)/src/date.c \ + $(TOP)/src/delete.c \ + $(TOP)/src/expr.c \ + $(TOP)/src/fault.c \ + $(TOP)/src/func.c \ + $(TOP)/src/global.c \ + $(TOP)/src/hash.c \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + $(TOP)/src/insert.c \ + $(TOP)/src/journal.c \ + $(TOP)/src/legacy.c \ + $(TOP)/src/loadext.c \ + $(TOP)/src/main.c \ + $(TOP)/src/malloc.c \ + $(TOP)/src/mem0.c \ + $(TOP)/src/mem1.c \ + $(TOP)/src/mem2.c \ + $(TOP)/src/mem3.c \ + $(TOP)/src/mem5.c \ + $(TOP)/src/memjournal.c \ + $(TOP)/src/mutex.c \ + $(TOP)/src/mutex.h \ + $(TOP)/src/mutex_noop.c \ + $(TOP)/src/mutex_unix.c \ + $(TOP)/src/mutex_w32.c \ + $(TOP)/src/notify.c \ + $(TOP)/src/os.c \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/os_unix.c \ + $(TOP)/src/os_win.c \ + $(TOP)/src/pager.c \ + $(TOP)/src/pager.h \ + $(TOP)/src/parse.y \ + $(TOP)/src/pcache.c \ + $(TOP)/src/pcache.h \ + $(TOP)/src/pcache1.c \ + $(TOP)/src/pragma.c \ + $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c \ + $(TOP)/src/random.c \ + $(TOP)/src/resolve.c \ + $(TOP)/src/rowset.c \ + $(TOP)/src/select.c \ + $(TOP)/src/status.c \ + $(TOP)/src/shell.c \ + $(TOP)/src/sqlite.h.in \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/table.c \ + $(TOP)/src/tclsqlite.c \ + $(TOP)/src/tokenize.c \ + $(TOP)/src/trigger.c \ + $(TOP)/src/utf.c \ + $(TOP)/src/update.c \ + $(TOP)/src/util.c \ + $(TOP)/src/vacuum.c \ + $(TOP)/src/vdbe.c \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeapi.c \ + $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbeblob.c \ + $(TOP)/src/vdbemem.c \ + $(TOP)/src/vdbeInt.h \ + $(TOP)/src/vtab.c \ + $(TOP)/src/walker.c \ + $(TOP)/src/where.c + +# Source code for extensions +# +SRC += \ + $(TOP)/ext/fts1/fts1.c \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.c \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_porter.c \ + $(TOP)/ext/fts1/fts1_tokenizer.h \ + $(TOP)/ext/fts1/fts1_tokenizer1.c +SRC += \ + $(TOP)/ext/fts2/fts2.c \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.c \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_icu.c \ + $(TOP)/ext/fts2/fts2_porter.c \ + $(TOP)/ext/fts2/fts2_tokenizer.h \ + $(TOP)/ext/fts2/fts2_tokenizer.c \ + $(TOP)/ext/fts2/fts2_tokenizer1.c +SRC += \ + $(TOP)/ext/fts3/fts3.c \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_expr.h \ + $(TOP)/ext/fts3/fts3_hash.c \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_icu.c \ + $(TOP)/ext/fts3/fts3_porter.c \ + $(TOP)/ext/fts3/fts3_tokenizer.h \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/fts3/fts3_tokenizer1.c +SRC += \ + $(TOP)/ext/icu/sqliteicu.h \ + $(TOP)/ext/icu/icu.c +SRC += \ + $(TOP)/ext/rtree/rtree.h \ + $(TOP)/ext/rtree/rtree.c + + +# Generated source code files +# +SRC += \ + keywordhash.h \ + opcodes.c \ + opcodes.h \ + parse.c \ + parse.h \ + sqlite3.h + + +# Source code to the test files. +# +TESTSRC = \ + $(TOP)/src/test1.c \ + $(TOP)/src/test2.c \ + $(TOP)/src/test3.c \ + $(TOP)/src/test4.c \ + $(TOP)/src/test5.c \ + $(TOP)/src/test6.c \ + $(TOP)/src/test7.c \ + $(TOP)/src/test8.c \ + $(TOP)/src/test9.c \ + $(TOP)/src/test_autoext.c \ + $(TOP)/src/test_async.c \ + $(TOP)/src/test_backup.c \ + $(TOP)/src/test_btree.c \ + $(TOP)/src/test_config.c \ + $(TOP)/src/test_devsym.c \ + $(TOP)/src/test_func.c \ + $(TOP)/src/test_hexio.c \ + $(TOP)/src/test_journal.c \ + $(TOP)/src/test_malloc.c \ + $(TOP)/src/test_md5.c \ + $(TOP)/src/test_mutex.c \ + $(TOP)/src/test_onefile.c \ + $(TOP)/src/test_osinst.c \ + $(TOP)/src/test_pcache.c \ + $(TOP)/src/test_schema.c \ + $(TOP)/src/test_server.c \ + $(TOP)/src/test_tclvar.c \ + $(TOP)/src/test_thread.c \ + $(TOP)/src/test_vfs.c \ + $(TOP)/src/test_wsd.c \ + +#TESTSRC += $(TOP)/ext/fts2/fts2_tokenizer.c +#TESTSRC += $(TOP)/ext/fts3/fts3_tokenizer.c + +TESTSRC2 = \ + $(TOP)/src/attach.c $(TOP)/src/backup.c $(TOP)/src/btree.c \ + $(TOP)/src/build.c $(TOP)/src/ctime.c $(TOP)/src/date.c \ + $(TOP)/src/expr.c $(TOP)/src/func.c $(TOP)/src/insert.c $(TOP)/src/os.c \ + $(TOP)/src/os_unix.c $(TOP)/src/os_win.c \ + $(TOP)/src/pager.c $(TOP)/src/pragma.c $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c $(TOP)/src/random.c $(TOP)/src/pcache.c \ + $(TOP)/src/pcache1.c $(TOP)/src/select.c $(TOP)/src/tokenize.c \ + $(TOP)/src/utf.c $(TOP)/src/util.c $(TOP)/src/vdbeapi.c $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbe.c $(TOP)/src/vdbemem.c $(TOP)/src/where.c parse.c \ + $(TOP)/ext/fts3/fts3.c $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/async/sqlite3async.c + +# Header files used by all library source files. +# +HDR = \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + keywordhash.h \ + $(TOP)/src/mutex.h \ + opcodes.h \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/pager.h \ + $(TOP)/src/pcache.h \ + parse.h \ + sqlite3.h \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeInt.h + +# Header files used by extensions +# +EXTHDR += \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3_expr.h \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_tokenizer.h +EXTHDR += \ + $(TOP)/ext/rtree/rtree.h +EXTHDR += \ + $(TOP)/ext/icu/sqliteicu.h + +# This is the default Makefile target. The objects listed here +# are what get build when you type just "make" with no arguments. +# +all: sqlite3.h libsqlite3.a sqlite3$(EXE) + +libsqlite3.a: $(LIBOBJ) + $(AR) libsqlite3.a $(LIBOBJ) + $(RANLIB) libsqlite3.a + +$(SHPREFIX)sqlite3.$(SO): $(LIBOBJ) + $(MKSHLIB) -o $(SHPREFIX)sqlite3.$(SO) $(LIBOBJ) $(TLIBS_SHARED) + +sqlite3$(EXE): $(TOP)/src/shell.c libsqlite3.a sqlite3.h + $(TCCX) $(READLINE_FLAGS) -o sqlite3$(EXE) \ + $(TOP)/src/shell.c \ + $(LIBREADLINE) $(TLIBS) $(THREADLIB) -L. -lsqlite3 + +# This target creates a directory named "tsrc" and fills it with +# copies of all of the C source code and header files needed to +# build on the target system. Some of the C source code and header +# files are automatically generated. This target takes care of +# all that automatic generation. +# +target_source: $(SRC) + rm -rf tsrc + mkdir tsrc + cp -f $(SRC) tsrc + rm tsrc/sqlite.h.in tsrc/parse.y + touch target_source + +sqlite3.c: target_source $(TOP)/tool/mksqlite3c.tcl + tclsh $(TOP)/tool/mksqlite3c.tcl + cp sqlite3.c tclsqlite3.c + cat $(TOP)/src/tclsqlite.c >>tclsqlite3.c + +fts2amal.c: target_source $(TOP)/ext/fts2/mkfts2amal.tcl + tclsh $(TOP)/ext/fts2/mkfts2amal.tcl + +fts3amal.c: target_source $(TOP)/ext/fts3/mkfts3amal.tcl + tclsh $(TOP)/ext/fts3/mkfts3amal.tcl + +# Rules to build the LEMON compiler generator +# +lemon: $(TOP)/tool/lemon.c $(TOP)/src/lempar.c + $(BCC) -o lemon $(TOP)/tool/lemon.c + cp $(TOP)/src/lempar.c . + +# Rules to build individual *.o files from generated *.c files. This +# applies to: +# +# parse.o +# opcodes.o +# +%.o: %.c $(HDR) + $(TCCX_SHARED) -c $< + +# Rules to build individual *.o files from files in the src directory. +# +%.o: $(TOP)/src/%.c $(HDR) + $(TCCX_SHARED) -c $< + +tclsqlite.o: $(TOP)/src/tclsqlite.c $(HDR) + $(TCCX_SHARED) $(TCL_FLAGS) -c $(TOP)/src/tclsqlite.c + + + +# Rules to build opcodes.c and opcodes.h +# +opcodes.c: opcodes.h $(TOP)/mkopcodec.awk + $(NAWK) -f $(TOP)/mkopcodec.awk opcodes.h >opcodes.c + +opcodes.h: parse.h $(TOP)/src/vdbe.c $(TOP)/mkopcodeh.awk + cat parse.h $(TOP)/src/vdbe.c | \ + $(NAWK) -f $(TOP)/mkopcodeh.awk >opcodes.h + +# Rules to build parse.c and parse.h - the outputs of lemon. +# +parse.h: parse.c + +parse.c: $(TOP)/src/parse.y lemon $(TOP)/addopcodes.awk + cp $(TOP)/src/parse.y . + rm -f parse.h + ./lemon $(OPTS) parse.y + mv parse.h parse.h.temp + awk -f $(TOP)/addopcodes.awk parse.h.temp >parse.h + +sqlite3.h: $(TOP)/src/sqlite.h.in + sed -e s/--VERS--/`cat ${TOP}/VERSION`/ \ + -e s/--VERSION-NUMBER--/`cat ${TOP}/VERSION | sed 's/[^0-9]/ /g' | $(NAWK) '{printf "%d%03d%03d",$$1,$$2,$$3}'`/ \ + $(TOP)/src/sqlite.h.in >sqlite3.h + +keywordhash.h: $(TOP)/tool/mkkeywordhash.c + $(BCC) -o mkkeywordhash $(OPTS) $(TOP)/tool/mkkeywordhash.c + ./mkkeywordhash >keywordhash.h + + + +# Rules to build the extension objects. +# +icu.o: $(TOP)/ext/icu/icu.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/icu/icu.c + +fts2.o: $(TOP)/ext/fts2/fts2.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2.c + +fts2_hash.o: $(TOP)/ext/fts2/fts2_hash.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_hash.c + +fts2_icu.o: $(TOP)/ext/fts2/fts2_icu.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_icu.c + +fts2_porter.o: $(TOP)/ext/fts2/fts2_porter.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_porter.c + +fts2_tokenizer.o: $(TOP)/ext/fts2/fts2_tokenizer.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer.c + +fts2_tokenizer1.o: $(TOP)/ext/fts2/fts2_tokenizer1.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer1.c + +fts3.o: $(TOP)/ext/fts3/fts3.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3.c + +fts3_expr.o: $(TOP)/ext/fts3/fts3_expr.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_expr.c + +fts3_hash.o: $(TOP)/ext/fts3/fts3_hash.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_hash.c + +fts3_icu.o: $(TOP)/ext/fts3/fts3_icu.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_icu.c + +fts3_porter.o: $(TOP)/ext/fts3/fts3_porter.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_porter.c + +fts3_tokenizer.o: $(TOP)/ext/fts3/fts3_tokenizer.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer.c + +fts3_tokenizer1.o: $(TOP)/ext/fts3/fts3_tokenizer1.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer1.c + +rtree.o: $(TOP)/ext/rtree/rtree.c $(HDR) $(EXTHDR) + $(TCCX_SHARED) -DSQLITE_CORE -c $(TOP)/ext/rtree/rtree.c + + +# Rules for building test programs and for running tests +# +tclsqlite3: $(TOP)/src/tclsqlite.c libsqlite3.a + $(TCCX_SHARED) $(TCL_FLAGS) -DTCLSH=1 -o tclsqlite3 \ + $(TOP)/src/tclsqlite.c libsqlite3.a $(LIBTCL) $(THREADLIB) + + +# Rules to build the 'testfixture' application. +# +TESTFIXTURE_FLAGS = -DTCLSH=1 -DSQLITE_TEST=1 -DSQLITE_CRASH_TEST=1 +TESTFIXTURE_FLAGS += -DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE + +testfixture$(EXE): $(TESTSRC2) libsqlite3.a $(TESTSRC) $(TOP)/src/tclsqlite.c + $(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS) \ + $(TESTSRC) $(TESTSRC2) $(TOP)/src/tclsqlite.c \ + -o testfixture$(EXE) $(LIBTCL) $(THREADLIB) libsqlite3.a + +amalgamation-testfixture$(EXE): sqlite3.c $(TESTSRC) $(TOP)/src/tclsqlite.c + $(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS) \ + $(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c \ + -o testfixture$(EXE) $(LIBTCL) $(THREADLIB) + +fts3-testfixture$(EXE): sqlite3.c fts3amal.c $(TESTSRC) $(TOP)/src/tclsqlite.c + $(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS) \ + -DSQLITE_ENABLE_FTS3=1 \ + $(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c fts3amal.c \ + -o testfixture$(EXE) $(LIBTCL) $(THREADLIB) + +fulltest: testfixture$(EXE) sqlite3$(EXE) + ./testfixture$(EXE) $(TOP)/test/all.test + +soaktest: testfixture$(EXE) sqlite3$(EXE) + ./testfixture$(EXE) $(TOP)/test/all.test -soak=1 + +fulltestonly: testfixture$(EXE) sqlite3$(EXE) + ./testfixture$(EXE) $(TOP)/test/full.test + +test: testfixture$(EXE) sqlite3$(EXE) + ./testfixture$(EXE) $(TOP)/test/veryquick.test + +sqlite3_analyzer$(EXE): $(TOP)/src/tclsqlite.c sqlite3.c $(TESTSRC) \ + $(TOP)/tool/spaceanal.tcl + sed \ + -e '/^#/d' \ + -e 's,\\,\\\\,g' \ + -e 's,",\\",g' \ + -e 's,^,",' \ + -e 's,$$,\\n",' \ + $(TOP)/tool/spaceanal.tcl >spaceanal_tcl.h + $(TCCX) $(TCL_FLAGS) $(TESTFIXTURE_FLAGS) \ + -DTCLSH=2 -DSQLITE_TEST=1 -DSQLITE_DEBUG=1 -DSQLITE_PRIVATE="" \ + $(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c \ + -o sqlite3_analyzer$(EXE) \ + $(LIBTCL) $(THREADLIB) + +TEST_EXTENSION = $(SHPREFIX)testloadext.$(SO) +$(TEST_EXTENSION): $(TOP)/src/test_loadext.c + $(MKSHLIB) $(TOP)/src/test_loadext.c -o $(TEST_EXTENSION) + +extensiontest: testfixture$(EXE) $(TEST_EXTENSION) + ./testfixture$(EXE) $(TOP)/test/loadext.test + +clean: + rm -f *.o sqlite3$(EXE) libsqlite3.a sqlite3.h opcodes.* + rm -f lemon lempar.c parse.* sqlite*.tar.gz mkkeywordhash keywordhash.h + rm -f $(PUBLISH) + rm -f *.da *.bb *.bbg gmon.out + rm -rf quota2a quota2b quota2c + rm -rf tsrc target_source + rm -f testloadext.dll libtestloadext.so + rm -f sqlite3.c fts?amal.c tclsqlite3.c + rm -f sqlite3rc.h + rm -f shell.c sqlite3ext.h + rm -f $(SHPREFIX)sqlite3.$(SO) diff --git a/components/external/SQLite-3.8.1/README b/components/external/SQLite-3.8.1/README new file mode 100644 index 0000000000000000000000000000000000000000..0d65e518f9f8fa98b190bd4e54cb1a325e7efc74 --- /dev/null +++ b/components/external/SQLite-3.8.1/README @@ -0,0 +1,39 @@ +This directory contains source code to + + SQLite: An Embeddable SQL Database Engine + +To compile the project, first create a directory in which to place +the build products. It is recommended, but not required, that the +build directory be separate from the source directory. Cd into the +build directory and then from the build directory run the configure +script found at the root of the source tree. Then run "make". + +For example: + + tar xzf sqlite.tar.gz ;# Unpack the source tree into "sqlite" + mkdir bld ;# Build will occur in a sibling directory + cd bld ;# Change to the build directory + ../sqlite/configure ;# Run the configure script + make ;# Run the makefile. + make install ;# (Optional) Install the build products + +The configure script uses autoconf 2.61 and libtool. If the configure +script does not work out for you, there is a generic makefile named +"Makefile.linux-gcc" in the top directory of the source tree that you +can copy and edit to suit your needs. Comments on the generic makefile +show what changes are needed. + +The linux binaries on the website are created using the generic makefile, +not the configure script. The windows binaries on the website are created +using MinGW32 configured as a cross-compiler running under Linux. For +details, see the ./publish.sh script at the top-level of the source tree. +The developers do not use teh configure script. + +SQLite does not require TCL to run, but a TCL installation is required +by the makefiles. SQLite contains a lot of generated code and TCL is +used to do much of that code generation. The makefile also requires +AWK. + +Contacts: + + http://www.sqlite.org/ diff --git a/components/external/SQLite-3.8.1/SConscript b/components/external/SQLite-3.8.1/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..0008c74ca3a4f0816197989a15d00dd4cde01805 --- /dev/null +++ b/components/external/SQLite-3.8.1/SConscript @@ -0,0 +1,14 @@ +Import('rtconfig') +import os +from building import * + +cwd = GetCurrentDir() + str(r'/SQLiteLib/') +src = Split(""" +SQLiteLib/sqlite3.c +SQLiteLib/test/test10.c +""") +CPPPATH = [cwd, str(Dir('#'))] + +group = DefineGroup('sqlite', src, depend = ['RT_USING_SQLITE'], CPPPATH = CPPPATH) + +Return('group') diff --git a/components/external/SQLite-3.8.1/SQLiteLib/README b/components/external/SQLite-3.8.1/SQLiteLib/README new file mode 100644 index 0000000000000000000000000000000000000000..6dc72c88808757f47097fdfe840b3303d7284f48 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/README @@ -0,0 +1,31 @@ +# SQLite on RT-Thread + +## 简介 +åˆå§‹ç‰ˆæœ¬åŸºäºŽSQLite 3.8.1版本,使用混åˆå•æ–‡ä»¶ç»“æž„æºä»£ç  + +测试方法: +1. + 在rtconfig.h中定义一下å®,并打开newlib组件 + /* + * SQLite compile macro + */ + #define RT_USING_SQLITE + #define SQLITE_MINIMUM_FILE_DESCRIPTOR 0 + #define SQLITE_OMIT_LOAD_EXTENSION 1 + #define SQLITE_OMIT_WAL + #define SQLITE_RTTHREAD_NO_WIDE 1 + #define SQLITE_ENABLE_LOCKING_STYLE 0 + #define SQLITE_DISABLE_LOCKING_STYLE 1 + #define SQLITE_TEMP_STORE 1 + #define SQLITE_THREADSAFE 1 + #define HAVE_READLINE 0 + #define NDEBUG + #define _HAVE_SQLITE_CONFIG_H + #define BUILD_sqlite + #define SQLITE_OS_OTHER 1 + #define SQLITE_OS_RTT 1 +2. + 用test目录下的test10.cæ¥è¿›è¡Œæµ‹è¯•. + 推è用mini2440bsp,因为æ¿å­çš„ram较大。 + +注æ„shell.c还没有移æ¤çš„。请ä¸è¦ä½¿ç”¨ã€‚ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/config.h b/components/external/SQLite-3.8.1/SQLiteLib/config.h new file mode 100644 index 0000000000000000000000000000000000000000..8b711f73a5c575e1e59df2a3ff7752295e30e7c7 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/config.h @@ -0,0 +1,114 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_DLFCN_H */ + +/* Define to 1 if you have the `fdatasync' function. */ +/* #undef HAVE_FDATASYNC */ + +/* Define to 1 if you have the `gmtime_r' function. */ +#define HAVE_GMTIME_R 1 + +/* Define to 1 if the system has the type `int16_t'. */ +#define HAVE_INT16_T 1 + +/* Define to 1 if the system has the type `int32_t'. */ +#define HAVE_INT32_T 1 + +/* Define to 1 if the system has the type `int64_t'. */ +#define HAVE_INT64_T 1 + +/* Define to 1 if the system has the type `int8_t'. */ +#define HAVE_INT8_T 1 + +/* Define to 1 if the system has the type `intptr_t'. */ +#define HAVE_INTPTR_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `localtime_r' function. */ +#define HAVE_LOCALTIME_R 1 + +/* Define to 1 if you have the `localtime_s' function. */ +/* #undef HAVE_LOCALTIME_S */ + +/* Define to 1 if you have the header file. */ +/* #define HAVE_MALLOC_H 0 */ + +/* Define to 1 if you have the `malloc_usable_size' function. */ +/* #define HAVE_MALLOC_USABLE_SIZE 0 */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_MEMORY_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_STRINGS_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if the system has the type `uint16_t'. */ +#define HAVE_UINT16_T 1 + +/* Define to 1 if the system has the type `uint32_t'. */ +#define HAVE_UINT32_T 1 + +/* Define to 1 if the system has the type `uint64_t'. */ +#define HAVE_UINT64_T 1 + +/* Define to 1 if the system has the type `uint8_t'. */ +#define HAVE_UINT8_T 1 + +/* Define to 1 if the system has the type `uintptr_t'. */ +#define HAVE_UINTPTR_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the `usleep' function. */ +/* #undef HAVE_USLEEP */ + +/* Define to 1 if you have the utime() library function. */ +/* #undef HAVE_UTIME */ + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#define LT_OBJDIR ".libs/" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "sqlite" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "sqlite 3.8.1" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "sqlite" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "3.8.1" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Number of bits in a file offset, on hosts where this is settable. */ +/* #undef _FILE_OFFSET_BITS */ + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/shell.c b/components/external/SQLite-3.8.1/SQLiteLib/shell.c new file mode 100644 index 0000000000000000000000000000000000000000..41ea56492e71884843a56a4c4c65ab18864e1f26 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/shell.c @@ -0,0 +1,3400 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code to implement the "sqlite" command line +** utility for accessing SQLite databases. +*/ +#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) +/* This needs to come before any includes for MSVC compiler */ +#define _CRT_SECURE_NO_WARNINGS +#endif + +/* +** Enable large-file support for fopen() and friends on unix. +*/ +#ifndef SQLITE_DISABLE_LFS +# define _LARGE_FILE 1 +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +# define _LARGEFILE_SOURCE 1 +#endif + +#include +#include +#include +#include +#include "sqlite3.h" +#include +#include + +#if !defined(_WIN32) && !defined(WIN32) +# include +# if !defined(__RTP__) && !defined(_WRS_KERNEL) +# include +# endif +# include +# include +#endif + +#ifdef HAVE_EDITLINE +# include +#endif +#if defined(HAVE_READLINE) && HAVE_READLINE==1 +# include +# include +#endif +#if !defined(HAVE_EDITLINE) && (!defined(HAVE_READLINE) || HAVE_READLINE!=1) +# define add_history(X) +# define read_history(X) +# define write_history(X) +# define stifle_history(X) +#endif + +#if defined(_WIN32) || defined(WIN32) +# include +#define isatty(h) _isatty(h) +#define access(f,m) _access((f),(m)) +#undef popen +#define popen _popen +#undef pclose +#define pclose _pclose +#else +/* Make sure isatty() has a prototype. +*/ +extern int isatty(int); + +/* popen and pclose are not C89 functions and so are sometimes omitted from +** the header */ +extern FILE *popen(const char*,const char*); +extern int pclose(FILE*); +#endif + +#if defined(_WIN32_WCE) +/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() + * thus we always assume that we have a console. That can be + * overridden with the -batch command line option. + */ +#define isatty(x) 1 +#endif + +/* True if the timer is enabled */ +static int enableTimer = 0; + +/* ctype macros that work with signed characters */ +#define IsSpace(X) isspace((unsigned char)X) +#define IsDigit(X) isdigit((unsigned char)X) +#define ToLower(X) (char)tolower((unsigned char)X) + +#if !defined(_WIN32) && !defined(WIN32) && !defined(_WRS_KERNEL) \ + && !defined(__minux) +#include +#include + +/* Saved resource information for the beginning of an operation */ +static struct rusage sBegin; + +/* +** Begin timing an operation +*/ +static void beginTimer(void){ + if( enableTimer ){ + getrusage(RUSAGE_SELF, &sBegin); + } +} + +/* Return the difference of two time_structs in seconds */ +static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ + return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + + (double)(pEnd->tv_sec - pStart->tv_sec); +} + +/* +** Print the timing results. +*/ +static void endTimer(void){ + if( enableTimer ){ + struct rusage sEnd; + getrusage(RUSAGE_SELF, &sEnd); + printf("CPU Time: user %f sys %f\n", + timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), + timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); + } +} + +#define BEGIN_TIMER beginTimer() +#define END_TIMER endTimer() +#define HAS_TIMER 1 + +#elif (defined(_WIN32) || defined(WIN32)) + +#include + +/* Saved resource information for the beginning of an operation */ +static HANDLE hProcess; +static FILETIME ftKernelBegin; +static FILETIME ftUserBegin; +typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME); +static GETPROCTIMES getProcessTimesAddr = NULL; + +/* +** Check to see if we have timer support. Return 1 if necessary +** support found (or found previously). +*/ +static int hasTimer(void){ + if( getProcessTimesAddr ){ + return 1; + } else { + /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions. + ** See if the version we are running on has it, and if it does, save off + ** a pointer to it and the current process handle. + */ + hProcess = GetCurrentProcess(); + if( hProcess ){ + HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); + if( NULL != hinstLib ){ + getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); + if( NULL != getProcessTimesAddr ){ + return 1; + } + FreeLibrary(hinstLib); + } + } + } + return 0; +} + +/* +** Begin timing an operation +*/ +static void beginTimer(void){ + if( enableTimer && getProcessTimesAddr ){ + FILETIME ftCreation, ftExit; + getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin); + } +} + +/* Return the difference of two FILETIME structs in seconds */ +static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ + sqlite_int64 i64Start = *((sqlite_int64 *) pStart); + sqlite_int64 i64End = *((sqlite_int64 *) pEnd); + return (double) ((i64End - i64Start) / 10000000.0); +} + +/* +** Print the timing results. +*/ +static void endTimer(void){ + if( enableTimer && getProcessTimesAddr){ + FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; + getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd); + printf("CPU Time: user %f sys %f\n", + timeDiff(&ftUserBegin, &ftUserEnd), + timeDiff(&ftKernelBegin, &ftKernelEnd)); + } +} + +#define BEGIN_TIMER beginTimer() +#define END_TIMER endTimer() +#define HAS_TIMER hasTimer() + +#else +#define BEGIN_TIMER +#define END_TIMER +#define HAS_TIMER 0 +#endif + +/* +** Used to prevent warnings about unused parameters +*/ +#define UNUSED_PARAMETER(x) (void)(x) + +/* +** If the following flag is set, then command execution stops +** at an error if we are not interactive. +*/ +static int bail_on_error = 0; + +/* +** Threat stdin as an interactive input if the following variable +** is true. Otherwise, assume stdin is connected to a file or pipe. +*/ +static int stdin_is_interactive = 1; + +/* +** The following is the open SQLite database. We make a pointer +** to this database a static variable so that it can be accessed +** by the SIGINT handler to interrupt database processing. +*/ +static sqlite3 *db = 0; + +/* +** True if an interrupt (Control-C) has been received. +*/ +static volatile int seenInterrupt = 0; + +/* +** This is the name of our program. It is set in main(), used +** in a number of other places, mostly for error messages. +*/ +static char *Argv0; + +/* +** Prompt strings. Initialized in main. Settable with +** .prompt main continue +*/ +static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ +static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ + +/* +** Write I/O traces to the following stream. +*/ +#ifdef SQLITE_ENABLE_IOTRACE +static FILE *iotrace = 0; +#endif + +/* +** This routine works like printf in that its first argument is a +** format string and subsequent arguments are values to be substituted +** in place of % fields. The result of formatting this string +** is written to iotrace. +*/ +#ifdef SQLITE_ENABLE_IOTRACE +static void iotracePrintf(const char *zFormat, ...){ + va_list ap; + char *z; + if( iotrace==0 ) return; + va_start(ap, zFormat); + z = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + fprintf(iotrace, "%s", z); + sqlite3_free(z); +} +#endif + + +/* +** Determines if a string is a number of not. +*/ +static int isNumber(const char *z, int *realnum){ + if( *z=='-' || *z=='+' ) z++; + if( !IsDigit(*z) ){ + return 0; + } + z++; + if( realnum ) *realnum = 0; + while( IsDigit(*z) ){ z++; } + if( *z=='.' ){ + z++; + if( !IsDigit(*z) ) return 0; + while( IsDigit(*z) ){ z++; } + if( realnum ) *realnum = 1; + } + if( *z=='e' || *z=='E' ){ + z++; + if( *z=='+' || *z=='-' ) z++; + if( !IsDigit(*z) ) return 0; + while( IsDigit(*z) ){ z++; } + if( realnum ) *realnum = 1; + } + return *z==0; +} + +/* +** A global char* and an SQL function to access its current value +** from within an SQL statement. This program used to use the +** sqlite_exec_printf() API to substitue a string into an SQL statement. +** The correct way to do this with sqlite3 is to use the bind API, but +** since the shell is built around the callback paradigm it would be a lot +** of work. Instead just use this hack, which is quite harmless. +*/ +static const char *zShellStatic = 0; +static void shellstaticFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + assert( 0==argc ); + assert( zShellStatic ); + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC); +} + + +/* +** This routine reads a line of text from FILE in, stores +** the text in memory obtained from malloc() and returns a pointer +** to the text. NULL is returned at end of file, or if malloc() +** fails. +** +** If zLine is not NULL then it is a malloced buffer returned from +** a previous call to this routine that may be reused. +*/ +static char *local_getline(char *zLine, FILE *in){ + int nLine = zLine==0 ? 0 : 100; + int n = 0; + + while( 1 ){ + if( n+100>nLine ){ + nLine = nLine*2 + 100; + zLine = realloc(zLine, nLine); + if( zLine==0 ) return 0; + } + if( fgets(&zLine[n], nLine - n, in)==0 ){ + if( n==0 ){ + free(zLine); + return 0; + } + zLine[n] = 0; + break; + } + while( zLine[n] ) n++; + if( n>0 && zLine[n-1]=='\n' ){ + n--; + if( n>0 && zLine[n-1]=='\r' ) n--; + zLine[n] = 0; + break; + } + } + return zLine; +} + +/* +** Retrieve a single line of input text. +** +** If in==0 then read from standard input and prompt before each line. +** If isContinuation is true, then a continuation prompt is appropriate. +** If isContinuation is zero, then the main prompt should be used. +** +** If zPrior is not NULL then it is a buffer from a prior call to this +** routine that can be reused. +** +** The result is stored in space obtained from malloc() and must either +** be freed by the caller or else passed back into this routine via the +** zPrior argument for reuse. +*/ +static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ + char *zPrompt; + char *zResult; + if( in!=0 ){ + zResult = local_getline(zPrior, in); + }else{ + zPrompt = isContinuation ? continuePrompt : mainPrompt; +#if defined(HAVE_READLINE) && HAVE_READLINE==1 + free(zPrior); + zResult = readline(zPrompt); + if( zResult && *zResult ) add_history(zResult); +#else + printf("%s", zPrompt); + fflush(stdout); + zResult = local_getline(zPrior, stdin); +#endif + } + return zResult; +} + +struct previous_mode_data { + int valid; /* Is there legit data in here? */ + int mode; + int showHeader; + int colWidth[100]; +}; + +/* +** An pointer to an instance of this structure is passed from +** the main program to the callback. This is used to communicate +** state and mode information. +*/ +struct callback_data { + sqlite3 *db; /* The database */ + int echoOn; /* True to echo input commands */ + int statsOn; /* True to display memory stats before each finalize */ + int cnt; /* Number of records displayed so far */ + FILE *out; /* Write results here */ + FILE *traceOut; /* Output for sqlite3_trace() */ + int nErr; /* Number of errors seen */ + int mode; /* An output mode setting */ + int writableSchema; /* True if PRAGMA writable_schema=ON */ + int showHeader; /* True to show column names in List or Column mode */ + char *zDestTable; /* Name of destination table when MODE_Insert */ + char separator[20]; /* Separator character for MODE_List */ + int colWidth[100]; /* Requested width of each column when in column mode*/ + int actualWidth[100]; /* Actual width of each column */ + char nullvalue[20]; /* The text to print when a NULL comes back from + ** the database */ + struct previous_mode_data explainPrev; + /* Holds the mode information just before + ** .explain ON */ + char outfile[FILENAME_MAX]; /* Filename for *out */ + const char *zDbFilename; /* name of the database file */ + const char *zVfs; /* Name of VFS to use */ + sqlite3_stmt *pStmt; /* Current statement if any. */ + FILE *pLog; /* Write log output here */ +}; + +/* +** These are the allowed modes. +*/ +#define MODE_Line 0 /* One column per line. Blank line between records */ +#define MODE_Column 1 /* One record per line in neat columns */ +#define MODE_List 2 /* One record per line with a separator */ +#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ +#define MODE_Html 4 /* Generate an XHTML table */ +#define MODE_Insert 5 /* Generate SQL "insert" statements */ +#define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */ +#define MODE_Csv 7 /* Quote strings, numbers are plain */ +#define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */ + +static const char *modeDescr[] = { + "line", + "column", + "list", + "semi", + "html", + "insert", + "tcl", + "csv", + "explain", +}; + +/* +** Number of elements in an array +*/ +#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) + +/* +** Compute a string length that is limited to what can be stored in +** lower 30 bits of a 32-bit signed integer. +*/ +static int strlen30(const char *z){ + const char *z2 = z; + while( *z2 ){ z2++; } + return 0x3fffffff & (int)(z2 - z); +} + +/* +** A callback for the sqlite3_log() interface. +*/ +static void shellLog(void *pArg, int iErrCode, const char *zMsg){ + struct callback_data *p = (struct callback_data*)pArg; + if( p->pLog==0 ) return; + fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg); + fflush(p->pLog); +} + +/* +** Output the given string as a hex-encoded blob (eg. X'1234' ) +*/ +static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ + int i; + char *zBlob = (char *)pBlob; + fprintf(out,"X'"); + for(i=0; i0 ){ + fprintf(out,"%.*s",i,z); + } + if( z[i]=='<' ){ + fprintf(out,"<"); + }else if( z[i]=='&' ){ + fprintf(out,"&"); + }else if( z[i]=='>' ){ + fprintf(out,">"); + }else if( z[i]=='\"' ){ + fprintf(out,"""); + }else if( z[i]=='\'' ){ + fprintf(out,"'"); + }else{ + break; + } + z += i + 1; + } +} + +/* +** If a field contains any character identified by a 1 in the following +** array, then the string must be quoted for CSV. +*/ +static const char needCsvQuote[] = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, +}; + +/* +** Output a single term of CSV. Actually, p->separator is used for +** the separator, which may or may not be a comma. p->nullvalue is +** the null value. Strings are quoted if necessary. +*/ +static void output_csv(struct callback_data *p, const char *z, int bSep){ + FILE *out = p->out; + if( z==0 ){ + fprintf(out,"%s",p->nullvalue); + }else{ + int i; + int nSep = strlen30(p->separator); + for(i=0; z[i]; i++){ + if( needCsvQuote[((unsigned char*)z)[i]] + || (z[i]==p->separator[0] && + (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){ + i = 0; + break; + } + } + if( i==0 ){ + putc('"', out); + for(i=0; z[i]; i++){ + if( z[i]=='"' ) putc('"', out); + putc(z[i], out); + } + putc('"', out); + }else{ + fprintf(out, "%s", z); + } + } + if( bSep ){ + fprintf(p->out, "%s", p->separator); + } +} + +#ifdef SIGINT +/* +** This routine runs when the user presses Ctrl-C +*/ +static void interrupt_handler(int NotUsed){ + UNUSED_PARAMETER(NotUsed); + seenInterrupt = 1; + if( db ) sqlite3_interrupt(db); +} +#endif + +/* +** This is the callback routine that the shell +** invokes for each row of a query result. +*/ +static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){ + int i; + struct callback_data *p = (struct callback_data*)pArg; + + switch( p->mode ){ + case MODE_Line: { + int w = 5; + if( azArg==0 ) break; + for(i=0; iw ) w = len; + } + if( p->cnt++>0 ) fprintf(p->out,"\n"); + for(i=0; iout,"%*s = %s\n", w, azCol[i], + azArg[i] ? azArg[i] : p->nullvalue); + } + break; + } + case MODE_Explain: + case MODE_Column: { + if( p->cnt++==0 ){ + for(i=0; icolWidth) ){ + w = p->colWidth[i]; + }else{ + w = 0; + } + if( w==0 ){ + w = strlen30(azCol[i] ? azCol[i] : ""); + if( w<10 ) w = 10; + n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue); + if( wactualWidth) ){ + p->actualWidth[i] = w; + } + if( p->showHeader ){ + if( w<0 ){ + fprintf(p->out,"%*.*s%s",-w,-w,azCol[i], i==nArg-1 ? "\n": " "); + }else{ + fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " "); + } + } + } + if( p->showHeader ){ + for(i=0; iactualWidth) ){ + w = p->actualWidth[i]; + if( w<0 ) w = -w; + }else{ + w = 10; + } + fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------" + "----------------------------------------------------------", + i==nArg-1 ? "\n": " "); + } + } + } + if( azArg==0 ) break; + for(i=0; iactualWidth) ){ + w = p->actualWidth[i]; + }else{ + w = 10; + } + if( p->mode==MODE_Explain && azArg[i] && + strlen30(azArg[i])>w ){ + w = strlen30(azArg[i]); + } + if( w<0 ){ + fprintf(p->out,"%*.*s%s",-w,-w, + azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " "); + }else{ + fprintf(p->out,"%-*.*s%s",w,w, + azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " "); + } + } + break; + } + case MODE_Semi: + case MODE_List: { + if( p->cnt++==0 && p->showHeader ){ + for(i=0; iout,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator); + } + } + if( azArg==0 ) break; + for(i=0; inullvalue; + fprintf(p->out, "%s", z); + if( iout, "%s", p->separator); + }else if( p->mode==MODE_Semi ){ + fprintf(p->out, ";\n"); + }else{ + fprintf(p->out, "\n"); + } + } + break; + } + case MODE_Html: { + if( p->cnt++==0 && p->showHeader ){ + fprintf(p->out,""); + for(i=0; iout,""); + output_html_string(p->out, azCol[i]); + fprintf(p->out,"\n"); + } + fprintf(p->out,"\n"); + } + if( azArg==0 ) break; + fprintf(p->out,""); + for(i=0; iout,""); + output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue); + fprintf(p->out,"\n"); + } + fprintf(p->out,"\n"); + break; + } + case MODE_Tcl: { + if( p->cnt++==0 && p->showHeader ){ + for(i=0; iout,azCol[i] ? azCol[i] : ""); + if(iout, "%s", p->separator); + } + fprintf(p->out,"\n"); + } + if( azArg==0 ) break; + for(i=0; iout, azArg[i] ? azArg[i] : p->nullvalue); + if(iout, "%s", p->separator); + } + fprintf(p->out,"\n"); + break; + } + case MODE_Csv: { + if( p->cnt++==0 && p->showHeader ){ + for(i=0; iout,"\n"); + } + if( azArg==0 ) break; + for(i=0; iout,"\n"); + break; + } + case MODE_Insert: { + p->cnt++; + if( azArg==0 ) break; + fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable); + for(i=0; i0 ? ",": ""; + if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ + fprintf(p->out,"%sNULL",zSep); + }else if( aiType && aiType[i]==SQLITE_TEXT ){ + if( zSep[0] ) fprintf(p->out,"%s",zSep); + output_quoted_string(p->out, azArg[i]); + }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){ + fprintf(p->out,"%s%s",zSep, azArg[i]); + }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ + const void *pBlob = sqlite3_column_blob(p->pStmt, i); + int nBlob = sqlite3_column_bytes(p->pStmt, i); + if( zSep[0] ) fprintf(p->out,"%s",zSep); + output_hex_blob(p->out, pBlob, nBlob); + }else if( isNumber(azArg[i], 0) ){ + fprintf(p->out,"%s%s",zSep, azArg[i]); + }else{ + if( zSep[0] ) fprintf(p->out,"%s",zSep); + output_quoted_string(p->out, azArg[i]); + } + } + fprintf(p->out,");\n"); + break; + } + } + return 0; +} + +/* +** This is the callback routine that the SQLite library +** invokes for each row of a query result. +*/ +static int callback(void *pArg, int nArg, char **azArg, char **azCol){ + /* since we don't have type info, call the shell_callback with a NULL value */ + return shell_callback(pArg, nArg, azArg, azCol, NULL); +} + +/* +** Set the destination table field of the callback_data structure to +** the name of the table given. Escape any quote characters in the +** table name. +*/ +static void set_table_name(struct callback_data *p, const char *zName){ + int i, n; + int needQuote; + char *z; + + if( p->zDestTable ){ + free(p->zDestTable); + p->zDestTable = 0; + } + if( zName==0 ) return; + needQuote = !isalpha((unsigned char)*zName) && *zName!='_'; + for(i=n=0; zName[i]; i++, n++){ + if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){ + needQuote = 1; + if( zName[i]=='\'' ) n++; + } + } + if( needQuote ) n += 2; + z = p->zDestTable = malloc( n+1 ); + if( z==0 ){ + fprintf(stderr,"Error: out of memory\n"); + exit(1); + } + n = 0; + if( needQuote ) z[n++] = '\''; + for(i=0; zName[i]; i++){ + z[n++] = zName[i]; + if( zName[i]=='\'' ) z[n++] = '\''; + } + if( needQuote ) z[n++] = '\''; + z[n] = 0; +} + +/* zIn is either a pointer to a NULL-terminated string in memory obtained +** from malloc(), or a NULL pointer. The string pointed to by zAppend is +** added to zIn, and the result returned in memory obtained from malloc(). +** zIn, if it was not NULL, is freed. +** +** If the third argument, quote, is not '\0', then it is used as a +** quote character for zAppend. +*/ +static char *appendText(char *zIn, char const *zAppend, char quote){ + int len; + int i; + int nAppend = strlen30(zAppend); + int nIn = (zIn?strlen30(zIn):0); + + len = nAppend+nIn+1; + if( quote ){ + len += 2; + for(i=0; idb, zSelect, -1, &pSelect, 0); + if( rc!=SQLITE_OK || !pSelect ){ + fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); + if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; + return rc; + } + rc = sqlite3_step(pSelect); + nResult = sqlite3_column_count(pSelect); + while( rc==SQLITE_ROW ){ + if( zFirstRow ){ + fprintf(p->out, "%s", zFirstRow); + zFirstRow = 0; + } + z = (const char*)sqlite3_column_text(pSelect, 0); + fprintf(p->out, "%s", z); + for(i=1; iout, ",%s", sqlite3_column_text(pSelect, i)); + } + if( z==0 ) z = ""; + while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; + if( z[0] ){ + fprintf(p->out, "\n;\n"); + }else{ + fprintf(p->out, ";\n"); + } + rc = sqlite3_step(pSelect); + } + rc = sqlite3_finalize(pSelect); + if( rc!=SQLITE_OK ){ + fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); + if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; + } + return rc; +} + +/* +** Allocate space and save off current error string. +*/ +static char *save_err_msg( + sqlite3 *db /* Database to query */ +){ + int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); + char *zErrMsg = sqlite3_malloc(nErrMsg); + if( zErrMsg ){ + memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); + } + return zErrMsg; +} + +/* +** Display memory stats. +*/ +static int display_stats( + sqlite3 *db, /* Database to query */ + struct callback_data *pArg, /* Pointer to struct callback_data */ + int bReset /* True to reset the stats */ +){ + int iCur; + int iHiwtr; + + if( pArg && pArg->out ){ + + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr); +/* +** Not currently used by the CLI. +** iHiwtr = iCur = -1; +** sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset); +** fprintf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr); +*/ + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); +/* +** Not currently used by the CLI. +** iHiwtr = iCur = -1; +** sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset); +** fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr); +*/ + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr); +#ifdef YYTRACKMAXSTACKDEPTH + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr); +#endif + } + + if( pArg && pArg->out && db ){ + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); + fprintf(pArg->out, "Page cache hits: %d\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); + fprintf(pArg->out, "Page cache misses: %d\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); + fprintf(pArg->out, "Page cache writes: %d\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur); + } + + if( pArg && pArg->out && db && pArg->pStmt ){ + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset); + fprintf(pArg->out, "Fullscan Steps: %d\n", iCur); + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); + fprintf(pArg->out, "Sort Operations: %d\n", iCur); + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset); + fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur); + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); + fprintf(pArg->out, "Virtual Machine Steps: %d\n", iCur); + } + + return 0; +} + +/* +** Execute a statement or set of statements. Print +** any result rows/columns depending on the current mode +** set via the supplied callback. +** +** This is very similar to SQLite's built-in sqlite3_exec() +** function except it takes a slightly different callback +** and callback data argument. +*/ +static int shell_exec( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */ + /* (not the same as sqlite3_exec) */ + struct callback_data *pArg, /* Pointer to struct callback_data */ + char **pzErrMsg /* Error msg written here */ +){ + sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ + int rc = SQLITE_OK; /* Return Code */ + int rc2; + const char *zLeftover; /* Tail of unprocessed SQL */ + + if( pzErrMsg ){ + *pzErrMsg = NULL; + } + + while( zSql[0] && (SQLITE_OK == rc) ){ + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); + if( SQLITE_OK != rc ){ + if( pzErrMsg ){ + *pzErrMsg = save_err_msg(db); + } + }else{ + if( !pStmt ){ + /* this happens for a comment or white-space */ + zSql = zLeftover; + while( IsSpace(zSql[0]) ) zSql++; + continue; + } + + /* save off the prepared statment handle and reset row count */ + if( pArg ){ + pArg->pStmt = pStmt; + pArg->cnt = 0; + } + + /* echo the sql statement if echo on */ + if( pArg && pArg->echoOn ){ + const char *zStmtSql = sqlite3_sql(pStmt); + fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); + } + + /* Output TESTCTRL_EXPLAIN text of requested */ + if( pArg && pArg->mode==MODE_Explain ){ + const char *zExplain = 0; + sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain); + if( zExplain && zExplain[0] ){ + fprintf(pArg->out, "%s", zExplain); + } + } + + /* perform the first step. this will tell us if we + ** have a result set or not and how wide it is. + */ + rc = sqlite3_step(pStmt); + /* if we have a result set... */ + if( SQLITE_ROW == rc ){ + /* if we have a callback... */ + if( xCallback ){ + /* allocate space for col name ptr, value ptr, and type */ + int nCol = sqlite3_column_count(pStmt); + void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1); + if( !pData ){ + rc = SQLITE_NOMEM; + }else{ + char **azCols = (char **)pData; /* Names of result columns */ + char **azVals = &azCols[nCol]; /* Results */ + int *aiTypes = (int *)&azVals[nCol]; /* Result types */ + int i, x; + assert(sizeof(int) <= sizeof(char *)); + /* save off ptrs to column names */ + for(i=0; imode==MODE_Insert ){ + azVals[i] = ""; + }else{ + azVals[i] = (char*)sqlite3_column_text(pStmt, i); + } + if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ + rc = SQLITE_NOMEM; + break; /* from for */ + } + } /* end for */ + + /* if data and types extracted successfully... */ + if( SQLITE_ROW == rc ){ + /* call the supplied callback with the result row data */ + if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){ + rc = SQLITE_ABORT; + }else{ + rc = sqlite3_step(pStmt); + } + } + } while( SQLITE_ROW == rc ); + sqlite3_free(pData); + } + }else{ + do{ + rc = sqlite3_step(pStmt); + } while( rc == SQLITE_ROW ); + } + } + + /* print usage stats if stats on */ + if( pArg && pArg->statsOn ){ + display_stats(db, pArg, 0); + } + + /* Finalize the statement just executed. If this fails, save a + ** copy of the error message. Otherwise, set zSql to point to the + ** next statement to execute. */ + rc2 = sqlite3_finalize(pStmt); + if( rc!=SQLITE_NOMEM ) rc = rc2; + if( rc==SQLITE_OK ){ + zSql = zLeftover; + while( IsSpace(zSql[0]) ) zSql++; + }else if( pzErrMsg ){ + *pzErrMsg = save_err_msg(db); + } + + /* clear saved stmt handle */ + if( pArg ){ + pArg->pStmt = NULL; + } + } + } /* end while */ + + return rc; +} + + +/* +** This is a different callback routine used for dumping the database. +** Each row received by this callback consists of a table name, +** the table type ("index" or "table") and SQL to create the table. +** This routine should print text sufficient to recreate the table. +*/ +static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ + int rc; + const char *zTable; + const char *zType; + const char *zSql; + const char *zPrepStmt = 0; + struct callback_data *p = (struct callback_data *)pArg; + + UNUSED_PARAMETER(azCol); + if( nArg!=3 ) return 1; + zTable = azArg[0]; + zType = azArg[1]; + zSql = azArg[2]; + + if( strcmp(zTable, "sqlite_sequence")==0 ){ + zPrepStmt = "DELETE FROM sqlite_sequence;\n"; + }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ + fprintf(p->out, "ANALYZE sqlite_master;\n"); + }else if( strncmp(zTable, "sqlite_", 7)==0 ){ + return 0; + }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ + char *zIns; + if( !p->writableSchema ){ + fprintf(p->out, "PRAGMA writable_schema=ON;\n"); + p->writableSchema = 1; + } + zIns = sqlite3_mprintf( + "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" + "VALUES('table','%q','%q',0,'%q');", + zTable, zTable, zSql); + fprintf(p->out, "%s\n", zIns); + sqlite3_free(zIns); + return 0; + }else{ + fprintf(p->out, "%s;\n", zSql); + } + + if( strcmp(zType, "table")==0 ){ + sqlite3_stmt *pTableInfo = 0; + char *zSelect = 0; + char *zTableInfo = 0; + char *zTmp = 0; + int nRow = 0; + + zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0); + zTableInfo = appendText(zTableInfo, zTable, '"'); + zTableInfo = appendText(zTableInfo, ");", 0); + + rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0); + free(zTableInfo); + if( rc!=SQLITE_OK || !pTableInfo ){ + return 1; + } + + zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0); + /* Always quote the table name, even if it appears to be pure ascii, + ** in case it is a keyword. Ex: INSERT INTO "table" ... */ + zTmp = appendText(zTmp, zTable, '"'); + if( zTmp ){ + zSelect = appendText(zSelect, zTmp, '\''); + free(zTmp); + } + zSelect = appendText(zSelect, " || ' VALUES(' || ", 0); + rc = sqlite3_step(pTableInfo); + while( rc==SQLITE_ROW ){ + const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1); + zSelect = appendText(zSelect, "quote(", 0); + zSelect = appendText(zSelect, zText, '"'); + rc = sqlite3_step(pTableInfo); + if( rc==SQLITE_ROW ){ + zSelect = appendText(zSelect, "), ", 0); + }else{ + zSelect = appendText(zSelect, ") ", 0); + } + nRow++; + } + rc = sqlite3_finalize(pTableInfo); + if( rc!=SQLITE_OK || nRow==0 ){ + free(zSelect); + return 1; + } + zSelect = appendText(zSelect, "|| ')' FROM ", 0); + zSelect = appendText(zSelect, zTable, '"'); + + rc = run_table_dump_query(p, zSelect, zPrepStmt); + if( rc==SQLITE_CORRUPT ){ + zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0); + run_table_dump_query(p, zSelect, 0); + } + free(zSelect); + } + return 0; +} + +/* +** Run zQuery. Use dump_callback() as the callback routine so that +** the contents of the query are output as SQL statements. +** +** If we get a SQLITE_CORRUPT error, rerun the query after appending +** "ORDER BY rowid DESC" to the end. +*/ +static int run_schema_dump_query( + struct callback_data *p, + const char *zQuery +){ + int rc; + char *zErr = 0; + rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); + if( rc==SQLITE_CORRUPT ){ + char *zQ2; + int len = strlen30(zQuery); + fprintf(p->out, "/****** CORRUPTION ERROR *******/\n"); + if( zErr ){ + fprintf(p->out, "/****** %s ******/\n", zErr); + sqlite3_free(zErr); + zErr = 0; + } + zQ2 = malloc( len+100 ); + if( zQ2==0 ) return rc; + sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); + rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); + if( rc ){ + fprintf(p->out, "/****** ERROR: %s ******/\n", zErr); + }else{ + rc = SQLITE_CORRUPT; + } + sqlite3_free(zErr); + free(zQ2); + } + return rc; +} + +/* +** Text of a help message +*/ +static char zHelp[] = + ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n" + ".bail ON|OFF Stop after hitting an error. Default OFF\n" + ".databases List names and files of attached databases\n" + ".dump ?TABLE? ... Dump the database in an SQL text format\n" + " If TABLE specified, only dump tables matching\n" + " LIKE pattern TABLE.\n" + ".echo ON|OFF Turn command echo on or off\n" + ".exit Exit this program\n" + ".explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off.\n" + " With no args, it turns EXPLAIN on.\n" + ".header(s) ON|OFF Turn display of headers on or off\n" + ".help Show this message\n" + ".import FILE TABLE Import data from FILE into TABLE\n" + ".indices ?TABLE? Show names of all indices\n" + " If TABLE specified, only show indices for tables\n" + " matching LIKE pattern TABLE.\n" +#ifdef SQLITE_ENABLE_IOTRACE + ".iotrace FILE Enable I/O diagnostic logging to FILE\n" +#endif +#ifndef SQLITE_OMIT_LOAD_EXTENSION + ".load FILE ?ENTRY? Load an extension library\n" +#endif + ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n" + ".mode MODE ?TABLE? Set output mode where MODE is one of:\n" + " csv Comma-separated values\n" + " column Left-aligned columns. (See .width)\n" + " html HTML code\n" + " insert SQL insert statements for TABLE\n" + " line One value per line\n" + " list Values delimited by .separator string\n" + " tabs Tab-separated values\n" + " tcl TCL list elements\n" + ".nullvalue STRING Use STRING in place of NULL values\n" + ".output FILENAME Send output to FILENAME\n" + ".output stdout Send output to the screen\n" + ".print STRING... Print literal STRING\n" + ".prompt MAIN CONTINUE Replace the standard prompts\n" + ".quit Exit this program\n" + ".read FILENAME Execute SQL in FILENAME\n" + ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n" + ".schema ?TABLE? Show the CREATE statements\n" + " If TABLE specified, only show tables matching\n" + " LIKE pattern TABLE.\n" + ".separator STRING Change separator used by output mode and .import\n" + ".show Show the current values for various settings\n" + ".stats ON|OFF Turn stats on or off\n" + ".tables ?TABLE? List names of tables\n" + " If TABLE specified, only list tables matching\n" + " LIKE pattern TABLE.\n" + ".timeout MS Try opening locked tables for MS milliseconds\n" + ".trace FILE|off Output each SQL statement as it is run\n" + ".vfsname ?AUX? Print the name of the VFS stack\n" + ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n" +; + +static char zTimerHelp[] = + ".timer ON|OFF Turn the CPU timer measurement on or off\n" +; + +/* Forward reference */ +static int process_input(struct callback_data *p, FILE *in); + +/* +** Make sure the database is open. If it is not, then open it. If +** the database fails to open, print an error message and exit. +*/ +static void open_db(struct callback_data *p){ + if( p->db==0 ){ + sqlite3_initialize(); + sqlite3_open(p->zDbFilename, &p->db); + db = p->db; + if( db && sqlite3_errcode(db)==SQLITE_OK ){ + sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0, + shellstaticFunc, 0, 0); + } + if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){ + fprintf(stderr,"Error: unable to open database \"%s\": %s\n", + p->zDbFilename, sqlite3_errmsg(db)); + exit(1); + } +#ifndef SQLITE_OMIT_LOAD_EXTENSION + sqlite3_enable_load_extension(p->db, 1); +#endif + } +} + +/* +** Do C-language style dequoting. +** +** \t -> tab +** \n -> newline +** \r -> carriage return +** \" -> " +** \NNN -> ascii character NNN in octal +** \\ -> backslash +*/ +static void resolve_backslashes(char *z){ + int i, j; + char c; + for(i=j=0; (c = z[i])!=0; i++, j++){ + if( c=='\\' ){ + c = z[++i]; + if( c=='n' ){ + c = '\n'; + }else if( c=='t' ){ + c = '\t'; + }else if( c=='r' ){ + c = '\r'; + }else if( c=='\\' ){ + c = '\\'; + }else if( c>='0' && c<='7' ){ + c -= '0'; + if( z[i+1]>='0' && z[i+1]<='7' ){ + i++; + c = (c<<3) + z[i] - '0'; + if( z[i+1]>='0' && z[i+1]<='7' ){ + i++; + c = (c<<3) + z[i] - '0'; + } + } + } + } + z[j] = c; + } + z[j] = 0; +} + +/* +** Return the value of a hexadecimal digit. Return -1 if the input +** is not a hex digit. +*/ +static int hexDigitValue(char c){ + if( c>='0' && c<='9' ) return c - '0'; + if( c>='a' && c<='f' ) return c - 'a' + 10; + if( c>='A' && c<='F' ) return c - 'A' + 10; + return -1; +} + +/* +** Interpret zArg as an integer value, possibly with suffixes. +*/ +static sqlite3_int64 integerValue(const char *zArg){ + sqlite3_int64 v = 0; + static const struct { char *zSuffix; int iMult; } aMult[] = { + { "KiB", 1024 }, + { "MiB", 1024*1024 }, + { "GiB", 1024*1024*1024 }, + { "KB", 1000 }, + { "MB", 1000000 }, + { "GB", 1000000000 }, + { "K", 1000 }, + { "M", 1000000 }, + { "G", 1000000000 }, + }; + int i; + int isNeg = 0; + if( zArg[0]=='-' ){ + isNeg = 1; + zArg++; + }else if( zArg[0]=='+' ){ + zArg++; + } + if( zArg[0]=='0' && zArg[1]=='x' ){ + int x; + zArg += 2; + while( (x = hexDigitValue(zArg[0]))>=0 ){ + v = (v<<4) + x; + zArg++; + } + }else{ + while( IsDigit(zArg[0]) ){ + v = v*10 + zArg[0] - '0'; + zArg++; + } + } + for(i=0; i=0; i++){} + }else{ + for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} + } + if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); + if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ + return 1; + } + if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ + return 0; + } + fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", + zArg); + return 0; +} + +/* +** Close an output file, assuming it is not stderr or stdout +*/ +static void output_file_close(FILE *f){ + if( f && f!=stdout && f!=stderr ) fclose(f); +} + +/* +** Try to open an output file. The names "stdout" and "stderr" are +** recognized and do the right thing. NULL is returned if the output +** filename is "off". +*/ +static FILE *output_file_open(const char *zFile){ + FILE *f; + if( strcmp(zFile,"stdout")==0 ){ + f = stdout; + }else if( strcmp(zFile, "stderr")==0 ){ + f = stderr; + }else if( strcmp(zFile, "off")==0 ){ + f = 0; + }else{ + f = fopen(zFile, "wb"); + if( f==0 ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); + } + } + return f; +} + +/* +** A routine for handling output from sqlite3_trace(). +*/ +static void sql_trace_callback(void *pArg, const char *z){ + FILE *f = (FILE*)pArg; + if( f ) fprintf(f, "%s\n", z); +} + +/* +** A no-op routine that runs with the ".breakpoint" doc-command. This is +** a useful spot to set a debugger breakpoint. +*/ +static void test_breakpoint(void){ + static int nCall = 0; + nCall++; +} + +/* +** An object used to read a CSV file +*/ +typedef struct CSVReader CSVReader; +struct CSVReader { + const char *zFile; /* Name of the input file */ + FILE *in; /* Read the CSV text from this input stream */ + char *z; /* Accumulated text for a field */ + int n; /* Number of bytes in z */ + int nAlloc; /* Space allocated for z[] */ + int nLine; /* Current line number */ + int cTerm; /* Character that terminated the most recent field */ + int cSeparator; /* The separator character. (Usually ",") */ +}; + +/* Append a single byte to z[] */ +static void csv_append_char(CSVReader *p, int c){ + if( p->n+1>=p->nAlloc ){ + p->nAlloc += p->nAlloc + 100; + p->z = sqlite3_realloc(p->z, p->nAlloc); + if( p->z==0 ){ + fprintf(stderr, "out of memory\n"); + exit(1); + } + } + p->z[p->n++] = (char)c; +} + +/* Read a single field of CSV text. Compatible with rfc4180 and extended +** with the option of having a separator other than ",". +** +** + Input comes from p->in. +** + Store results in p->z of length p->n. Space to hold p->z comes +** from sqlite3_malloc(). +** + Use p->cSep as the separator. The default is ",". +** + Keep track of the line number in p->nLine. +** + Store the character that terminates the field in p->cTerm. Store +** EOF on end-of-file. +** + Report syntax errors on stderr +*/ +static char *csv_read_one_field(CSVReader *p){ + int c, pc; + int cSep = p->cSeparator; + p->n = 0; + c = fgetc(p->in); + if( c==EOF || seenInterrupt ){ + p->cTerm = EOF; + return 0; + } + if( c=='"' ){ + int startLine = p->nLine; + int cQuote = c; + pc = 0; + while( 1 ){ + c = fgetc(p->in); + if( c=='\n' ) p->nLine++; + if( c==cQuote ){ + if( pc==cQuote ){ + pc = 0; + continue; + } + } + if( (c==cSep && pc==cQuote) + || (c=='\n' && pc==cQuote) + || (c=='\n' && pc=='\r' && p->n>=2 && p->z[p->n-2]==cQuote) + || (c==EOF && pc==cQuote) + ){ + do{ p->n--; }while( p->z[p->n]!=cQuote ); + p->cTerm = c; + break; + } + if( pc==cQuote && c!='\r' ){ + fprintf(stderr, "%s:%d: unescaped %c character\n", + p->zFile, p->nLine, cQuote); + } + if( c==EOF ){ + fprintf(stderr, "%s:%d: unterminated %c-quoted field\n", + p->zFile, startLine, cQuote); + p->cTerm = EOF; + break; + } + csv_append_char(p, c); + pc = c; + } + }else{ + while( c!=EOF && c!=cSep && c!='\n' ){ + csv_append_char(p, c); + c = fgetc(p->in); + } + if( c=='\n' ){ + p->nLine++; + if( p->n>1 && p->z[p->n-1]=='\r' ) p->n--; + } + p->cTerm = c; + } + if( p->z ) p->z[p->n] = 0; + return p->z; +} + +/* +** If an input line begins with "." then invoke this routine to +** process that line. +** +** Return 1 on error, 2 to exit, and 0 otherwise. +*/ +static int do_meta_command(char *zLine, struct callback_data *p){ + int i = 1; + int nArg = 0; + int n, c; + int rc = 0; + char *azArg[50]; + + /* Parse the input line into tokens. + */ + while( zLine[i] && nArg=3 && strncmp(azArg[0], "backup", n)==0 ){ + const char *zDestFile = 0; + const char *zDb = 0; + sqlite3 *pDest; + sqlite3_backup *pBackup; + int j; + for(j=1; jdb, zDb); + if( pBackup==0 ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); + sqlite3_close(pDest); + return 1; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = 0; + }else{ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); + rc = 1; + } + sqlite3_close(pDest); + }else + + if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){ + bail_on_error = booleanValue(azArg[1]); + }else + + /* The undocumented ".breakpoint" command causes a call to the no-op + ** routine named test_breakpoint(). + */ + if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ + test_breakpoint(); + }else + + if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){ + struct callback_data data; + char *zErrMsg = 0; + open_db(p); + memcpy(&data, p, sizeof(data)); + data.showHeader = 1; + data.mode = MODE_Column; + data.colWidth[0] = 3; + data.colWidth[1] = 15; + data.colWidth[2] = 58; + data.cnt = 0; + sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg); + if( zErrMsg ){ + fprintf(stderr,"Error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + rc = 1; + } + }else + + if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){ + open_db(p); + /* When playing back a "dump", the content might appear in an order + ** which causes immediate foreign key constraints to be violated. + ** So disable foreign-key constraint enforcement to prevent problems. */ + fprintf(p->out, "PRAGMA foreign_keys=OFF;\n"); + fprintf(p->out, "BEGIN TRANSACTION;\n"); + p->writableSchema = 0; + sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); + p->nErr = 0; + if( nArg==1 ){ + run_schema_dump_query(p, + "SELECT name, type, sql FROM sqlite_master " + "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" + ); + run_schema_dump_query(p, + "SELECT name, type, sql FROM sqlite_master " + "WHERE name=='sqlite_sequence'" + ); + run_table_dump_query(p, + "SELECT sql FROM sqlite_master " + "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 + ); + }else{ + int i; + for(i=1; iwritableSchema ){ + fprintf(p->out, "PRAGMA writable_schema=OFF;\n"); + p->writableSchema = 0; + } + sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); + sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); + fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n"); + }else + + if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){ + p->echoOn = booleanValue(azArg[1]); + }else + + if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ + if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); + rc = 2; + }else + + if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){ + int val = nArg>=2 ? booleanValue(azArg[1]) : 1; + if(val == 1) { + if(!p->explainPrev.valid) { + p->explainPrev.valid = 1; + p->explainPrev.mode = p->mode; + p->explainPrev.showHeader = p->showHeader; + memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth)); + } + /* We could put this code under the !p->explainValid + ** condition so that it does not execute if we are already in + ** explain mode. However, always executing it allows us an easy + ** was to reset to explain mode in case the user previously + ** did an .explain followed by a .width, .mode or .header + ** command. + */ + p->mode = MODE_Explain; + p->showHeader = 1; + memset(p->colWidth,0,ArraySize(p->colWidth)); + p->colWidth[0] = 4; /* addr */ + p->colWidth[1] = 13; /* opcode */ + p->colWidth[2] = 4; /* P1 */ + p->colWidth[3] = 4; /* P2 */ + p->colWidth[4] = 4; /* P3 */ + p->colWidth[5] = 13; /* P4 */ + p->colWidth[6] = 2; /* P5 */ + p->colWidth[7] = 13; /* Comment */ + }else if (p->explainPrev.valid) { + p->explainPrev.valid = 0; + p->mode = p->explainPrev.mode; + p->showHeader = p->explainPrev.showHeader; + memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth)); + } + }else + + if( c=='h' && (strncmp(azArg[0], "header", n)==0 || + strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){ + p->showHeader = booleanValue(azArg[1]); + }else + + if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ + fprintf(stderr,"%s",zHelp); + if( HAS_TIMER ){ + fprintf(stderr,"%s",zTimerHelp); + } + }else + + if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){ + char *zTable = azArg[2]; /* Insert data into this table */ + char *zFile = azArg[1]; /* Name of file to extra content from */ + sqlite3_stmt *pStmt = NULL; /* A statement */ + int nCol; /* Number of columns in the table */ + int nByte; /* Number of bytes in an SQL string */ + int i, j; /* Loop counters */ + int needCommit; /* True to COMMIT or ROLLBACK at end */ + int nSep; /* Number of bytes in p->separator[] */ + char *zSql; /* An SQL statement */ + CSVReader sCsv; /* Reader context */ + int (*xCloser)(FILE*); /* Procedure to close th3 connection */ + + seenInterrupt = 0; + memset(&sCsv, 0, sizeof(sCsv)); + open_db(p); + nSep = strlen30(p->separator); + if( nSep==0 ){ + fprintf(stderr, "Error: non-null separator required for import\n"); + return 1; + } + if( nSep>1 ){ + fprintf(stderr, "Error: multi-character separators not allowed" + " for import\n"); + return 1; + } + sCsv.zFile = zFile; + sCsv.nLine = 1; + if( sCsv.zFile[0]=='|' ){ + sCsv.in = popen(sCsv.zFile+1, "r"); + sCsv.zFile = ""; + xCloser = pclose; + }else{ + sCsv.in = fopen(sCsv.zFile, "rb"); + xCloser = fclose; + } + if( sCsv.in==0 ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); + return 1; + } + sCsv.cSeparator = p->separator[0]; + zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); + if( zSql==0 ){ + fprintf(stderr, "Error: out of memory\n"); + xCloser(sCsv.in); + return 1; + } + nByte = strlen30(zSql); + rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); + if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(db))==0 ){ + char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); + char cSep = '('; + while( csv_read_one_field(&sCsv) ){ + zCreate = sqlite3_mprintf("%z%c\n \"%s\" TEXT", zCreate, cSep, sCsv.z); + cSep = ','; + if( sCsv.cTerm!=sCsv.cSeparator ) break; + } + if( cSep=='(' ){ + sqlite3_free(zCreate); + sqlite3_free(sCsv.z); + xCloser(sCsv.in); + fprintf(stderr,"%s: empty file\n", sCsv.zFile); + return 1; + } + zCreate = sqlite3_mprintf("%z\n)", zCreate); + rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); + sqlite3_free(zCreate); + if( rc ){ + fprintf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, + sqlite3_errmsg(db)); + sqlite3_free(sCsv.z); + xCloser(sCsv.in); + return 1; + } + rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); + } + sqlite3_free(zSql); + if( rc ){ + if (pStmt) sqlite3_finalize(pStmt); + fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db)); + xCloser(sCsv.in); + return 1; + } + nCol = sqlite3_column_count(pStmt); + sqlite3_finalize(pStmt); + pStmt = 0; + if( nCol==0 ) return 0; /* no columns, no error */ + zSql = sqlite3_malloc( nByte*2 + 20 + nCol*2 ); + if( zSql==0 ){ + fprintf(stderr, "Error: out of memory\n"); + xCloser(sCsv.in); + return 1; + } + sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); + j = strlen30(zSql); + for(i=1; idb, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + if( rc ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); + if (pStmt) sqlite3_finalize(pStmt); + xCloser(sCsv.in); + return 1; + } + needCommit = sqlite3_get_autocommit(db); + if( needCommit ) sqlite3_exec(db, "BEGIN", 0, 0, 0); + do{ + int startLine = sCsv.nLine; + for(i=0; i=nCol ){ + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + if( rc!=SQLITE_OK ){ + fprintf(stderr, "%s:%d: INSERT failed: %s\n", sCsv.zFile, startLine, + sqlite3_errmsg(db)); + } + } + }while( sCsv.cTerm!=EOF ); + + xCloser(sCsv.in); + sqlite3_free(sCsv.z); + sqlite3_finalize(pStmt); + if( needCommit ) sqlite3_exec(db, "COMMIT", 0, 0, 0); + }else + + if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){ + struct callback_data data; + char *zErrMsg = 0; + open_db(p); + memcpy(&data, p, sizeof(data)); + data.showHeader = 0; + data.mode = MODE_List; + if( nArg==1 ){ + rc = sqlite3_exec(p->db, + "SELECT name FROM sqlite_master " + "WHERE type='index' AND name NOT LIKE 'sqlite_%' " + "UNION ALL " + "SELECT name FROM sqlite_temp_master " + "WHERE type='index' " + "ORDER BY 1", + callback, &data, &zErrMsg + ); + }else{ + zShellStatic = azArg[1]; + rc = sqlite3_exec(p->db, + "SELECT name FROM sqlite_master " + "WHERE type='index' AND tbl_name LIKE shellstatic() " + "UNION ALL " + "SELECT name FROM sqlite_temp_master " + "WHERE type='index' AND tbl_name LIKE shellstatic() " + "ORDER BY 1", + callback, &data, &zErrMsg + ); + zShellStatic = 0; + } + if( zErrMsg ){ + fprintf(stderr,"Error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + rc = 1; + }else if( rc != SQLITE_OK ){ + fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n"); + rc = 1; + } + }else + +#ifdef SQLITE_ENABLE_IOTRACE + if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ + extern void (*sqlite3IoTrace)(const char*, ...); + if( iotrace && iotrace!=stdout ) fclose(iotrace); + iotrace = 0; + if( nArg<2 ){ + sqlite3IoTrace = 0; + }else if( strcmp(azArg[1], "-")==0 ){ + sqlite3IoTrace = iotracePrintf; + iotrace = stdout; + }else{ + iotrace = fopen(azArg[1], "w"); + if( iotrace==0 ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); + sqlite3IoTrace = 0; + rc = 1; + }else{ + sqlite3IoTrace = iotracePrintf; + } + } + }else +#endif + +#ifndef SQLITE_OMIT_LOAD_EXTENSION + if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){ + const char *zFile, *zProc; + char *zErrMsg = 0; + zFile = azArg[1]; + zProc = nArg>=3 ? azArg[2] : 0; + open_db(p); + rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); + if( rc!=SQLITE_OK ){ + fprintf(stderr, "Error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + rc = 1; + } + }else +#endif + + if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){ + const char *zFile = azArg[1]; + output_file_close(p->pLog); + p->pLog = output_file_open(zFile); + }else + + if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){ + int n2 = strlen30(azArg[1]); + if( (n2==4 && strncmp(azArg[1],"line",n2)==0) + || + (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){ + p->mode = MODE_Line; + }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0) + || + (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){ + p->mode = MODE_Column; + }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){ + p->mode = MODE_List; + }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){ + p->mode = MODE_Html; + }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){ + p->mode = MODE_Tcl; + sqlite3_snprintf(sizeof(p->separator), p->separator, " "); + }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){ + p->mode = MODE_Csv; + sqlite3_snprintf(sizeof(p->separator), p->separator, ","); + }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){ + p->mode = MODE_List; + sqlite3_snprintf(sizeof(p->separator), p->separator, "\t"); + }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){ + p->mode = MODE_Insert; + set_table_name(p, "table"); + }else { + fprintf(stderr,"Error: mode should be one of: " + "column csv html insert line list tabs tcl\n"); + rc = 1; + } + }else + + if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){ + int n2 = strlen30(azArg[1]); + if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){ + p->mode = MODE_Insert; + set_table_name(p, azArg[2]); + }else { + fprintf(stderr, "Error: invalid arguments: " + " \"%s\". Enter \".help\" for help\n", azArg[2]); + rc = 1; + } + }else + + if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) { + sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue, + "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]); + }else + + if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){ + if( p->outfile[0]=='|' ){ + pclose(p->out); + }else{ + output_file_close(p->out); + } + p->outfile[0] = 0; + if( azArg[1][0]=='|' ){ + p->out = popen(&azArg[1][1], "w"); + if( p->out==0 ){ + fprintf(stderr,"Error: cannot open pipe \"%s\"\n", &azArg[1][1]); + p->out = stdout; + rc = 1; + }else{ + sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]); + } + }else{ + p->out = output_file_open(azArg[1]); + if( p->out==0 ){ + if( strcmp(azArg[1],"off")!=0 ){ + fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]); + } + p->out = stdout; + rc = 1; + } else { + sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]); + } + } + }else + + if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ + int i; + for(i=1; i1 ) fprintf(p->out, " "); + fprintf(p->out, "%s", azArg[i]); + } + fprintf(p->out, "\n"); + }else + + if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){ + if( nArg >= 2) { + strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); + } + if( nArg >= 3) { + strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); + } + }else + + if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){ + rc = 2; + }else + + if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){ + FILE *alt = fopen(azArg[1], "rb"); + if( alt==0 ){ + fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); + rc = 1; + }else{ + rc = process_input(p, alt); + fclose(alt); + } + }else + + if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){ + const char *zSrcFile; + const char *zDb; + sqlite3 *pSrc; + sqlite3_backup *pBackup; + int nTimeout = 0; + + if( nArg==2 ){ + zSrcFile = azArg[1]; + zDb = "main"; + }else{ + zSrcFile = azArg[2]; + zDb = azArg[1]; + } + rc = sqlite3_open(zSrcFile, &pSrc); + if( rc!=SQLITE_OK ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); + sqlite3_close(pSrc); + return 1; + } + open_db(p); + pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); + if( pBackup==0 ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); + sqlite3_close(pSrc); + return 1; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK + || rc==SQLITE_BUSY ){ + if( rc==SQLITE_BUSY ){ + if( nTimeout++ >= 3 ) break; + sqlite3_sleep(100); + } + } + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = 0; + }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ + fprintf(stderr, "Error: source database is busy\n"); + rc = 1; + }else{ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); + rc = 1; + } + sqlite3_close(pSrc); + }else + + if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){ + struct callback_data data; + char *zErrMsg = 0; + open_db(p); + memcpy(&data, p, sizeof(data)); + data.showHeader = 0; + data.mode = MODE_Semi; + if( nArg>1 ){ + int i; + for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]); + if( strcmp(azArg[1],"sqlite_master")==0 ){ + char *new_argv[2], *new_colv[2]; + new_argv[0] = "CREATE TABLE sqlite_master (\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")"; + new_argv[1] = 0; + new_colv[0] = "sql"; + new_colv[1] = 0; + callback(&data, 1, new_argv, new_colv); + rc = SQLITE_OK; + }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){ + char *new_argv[2], *new_colv[2]; + new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")"; + new_argv[1] = 0; + new_colv[0] = "sql"; + new_colv[1] = 0; + callback(&data, 1, new_argv, new_colv); + rc = SQLITE_OK; + }else{ + zShellStatic = azArg[1]; + rc = sqlite3_exec(p->db, + "SELECT sql FROM " + " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" + " FROM sqlite_master UNION ALL" + " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " + "WHERE lower(tbl_name) LIKE shellstatic()" + " AND type!='meta' AND sql NOTNULL " + "ORDER BY rowid", + callback, &data, &zErrMsg); + zShellStatic = 0; + } + }else{ + rc = sqlite3_exec(p->db, + "SELECT sql FROM " + " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" + " FROM sqlite_master UNION ALL" + " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " + "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'" + "ORDER BY rowid", + callback, &data, &zErrMsg + ); + } + if( zErrMsg ){ + fprintf(stderr,"Error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + rc = 1; + }else if( rc != SQLITE_OK ){ + fprintf(stderr,"Error: querying schema information\n"); + rc = 1; + }else{ + rc = 0; + } + }else + +#ifdef SQLITE_DEBUG + /* Undocumented commands for internal testing. Subject to change + ** without notice. */ + if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ + if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ + int i, v; + for(i=1; iout, "%s: %d 0x%x\n", azArg[i], v, v); + } + } + if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ + int i; sqlite3_int64 v; + for(i=1; iout, "%s", zBuf); + } + } + }else +#endif + + if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){ + sqlite3_snprintf(sizeof(p->separator), p->separator, + "%.*s", (int)sizeof(p->separator)-1, azArg[1]); + }else + + if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){ + int i; + fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off"); + fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off"); + fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off"); + fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]); + fprintf(p->out,"%9.9s: ", "nullvalue"); + output_c_string(p->out, p->nullvalue); + fprintf(p->out, "\n"); + fprintf(p->out,"%9.9s: %s\n","output", + strlen30(p->outfile) ? p->outfile : "stdout"); + fprintf(p->out,"%9.9s: ", "separator"); + output_c_string(p->out, p->separator); + fprintf(p->out, "\n"); + fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off"); + fprintf(p->out,"%9.9s: ","width"); + for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { + fprintf(p->out,"%d ",p->colWidth[i]); + } + fprintf(p->out,"\n"); + }else + + if( c=='s' && strncmp(azArg[0], "stats", n)==0 && nArg>1 && nArg<3 ){ + p->statsOn = booleanValue(azArg[1]); + }else + + if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){ + sqlite3_stmt *pStmt; + char **azResult; + int nRow, nAlloc; + char *zSql = 0; + int ii; + open_db(p); + rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); + if( rc ) return rc; + zSql = sqlite3_mprintf( + "SELECT name FROM sqlite_master" + " WHERE type IN ('table','view')" + " AND name NOT LIKE 'sqlite_%%'" + " AND name LIKE ?1"); + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); + if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue; + if( strcmp(zDbName,"temp")==0 ){ + zSql = sqlite3_mprintf( + "%z UNION ALL " + "SELECT 'temp.' || name FROM sqlite_temp_master" + " WHERE type IN ('table','view')" + " AND name NOT LIKE 'sqlite_%%'" + " AND name LIKE ?1", zSql); + }else{ + zSql = sqlite3_mprintf( + "%z UNION ALL " + "SELECT '%q.' || name FROM \"%w\".sqlite_master" + " WHERE type IN ('table','view')" + " AND name NOT LIKE 'sqlite_%%'" + " AND name LIKE ?1", zSql, zDbName, zDbName); + } + } + sqlite3_finalize(pStmt); + zSql = sqlite3_mprintf("%z ORDER BY 1", zSql); + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + if( rc ) return rc; + nRow = nAlloc = 0; + azResult = 0; + if( nArg>1 ){ + sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); + }else{ + sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); + } + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + if( nRow>=nAlloc ){ + char **azNew; + int n = nAlloc*2 + 10; + azNew = sqlite3_realloc(azResult, sizeof(azResult[0])*n); + if( azNew==0 ){ + fprintf(stderr, "Error: out of memory\n"); + break; + } + nAlloc = n; + azResult = azNew; + } + azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); + if( azResult[nRow] ) nRow++; + } + sqlite3_finalize(pStmt); + if( nRow>0 ){ + int len, maxlen = 0; + int i, j; + int nPrintCol, nPrintRow; + for(i=0; imaxlen ) maxlen = len; + } + nPrintCol = 80/(maxlen+2); + if( nPrintCol<1 ) nPrintCol = 1; + nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; + for(i=0; iout, "%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : ""); + } + fprintf(p->out, "\n"); + } + } + for(ii=0; ii=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){ + static const struct { + const char *zCtrlName; /* Name of a test-control option */ + int ctrlCode; /* Integer code for that option */ + } aCtrl[] = { + { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE }, + { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE }, + { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET }, + { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST }, + { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL }, + { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS }, + { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE }, + { "assert", SQLITE_TESTCTRL_ASSERT }, + { "always", SQLITE_TESTCTRL_ALWAYS }, + { "reserve", SQLITE_TESTCTRL_RESERVE }, + { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS }, + { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD }, + { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC }, + }; + int testctrl = -1; + int rc = 0; + int i, n; + open_db(p); + + /* convert testctrl text option to value. allow any unique prefix + ** of the option name, or a numerical value. */ + n = strlen30(azArg[1]); + for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){ + if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){ + if( testctrl<0 ){ + testctrl = aCtrl[i].ctrlCode; + }else{ + fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]); + testctrl = -1; + break; + } + } + } + if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]); + if( (testctrlSQLITE_TESTCTRL_LAST) ){ + fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]); + }else{ + switch(testctrl){ + + /* sqlite3_test_control(int, db, int) */ + case SQLITE_TESTCTRL_OPTIMIZATIONS: + case SQLITE_TESTCTRL_RESERVE: + if( nArg==3 ){ + int opt = (int)strtol(azArg[2], 0, 0); + rc = sqlite3_test_control(testctrl, p->db, opt); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single int option\n", + azArg[1]); + } + break; + + /* sqlite3_test_control(int) */ + case SQLITE_TESTCTRL_PRNG_SAVE: + case SQLITE_TESTCTRL_PRNG_RESTORE: + case SQLITE_TESTCTRL_PRNG_RESET: + if( nArg==2 ){ + rc = sqlite3_test_control(testctrl); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]); + } + break; + + /* sqlite3_test_control(int, uint) */ + case SQLITE_TESTCTRL_PENDING_BYTE: + if( nArg==3 ){ + unsigned int opt = (unsigned int)integerValue(azArg[2]); + rc = sqlite3_test_control(testctrl, opt); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single unsigned" + " int option\n", azArg[1]); + } + break; + + /* sqlite3_test_control(int, int) */ + case SQLITE_TESTCTRL_ASSERT: + case SQLITE_TESTCTRL_ALWAYS: + if( nArg==3 ){ + int opt = booleanValue(azArg[2]); + rc = sqlite3_test_control(testctrl, opt); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single int option\n", + azArg[1]); + } + break; + + /* sqlite3_test_control(int, char *) */ +#ifdef SQLITE_N_KEYWORD + case SQLITE_TESTCTRL_ISKEYWORD: + if( nArg==3 ){ + const char *opt = azArg[2]; + rc = sqlite3_test_control(testctrl, opt); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single char * option\n", + azArg[1]); + } + break; +#endif + + case SQLITE_TESTCTRL_BITVEC_TEST: + case SQLITE_TESTCTRL_FAULT_INSTALL: + case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: + case SQLITE_TESTCTRL_SCRATCHMALLOC: + default: + fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n", + azArg[1]); + break; + } + } + }else + + if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){ + open_db(p); + sqlite3_busy_timeout(p->db, (int)integerValue(azArg[1])); + }else + + if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 + && nArg==2 + ){ + enableTimer = booleanValue(azArg[1]); + }else + + if( c=='t' && strncmp(azArg[0], "trace", n)==0 && nArg>1 ){ + open_db(p); + output_file_close(p->traceOut); + p->traceOut = output_file_open(azArg[1]); +#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) + if( p->traceOut==0 ){ + sqlite3_trace(p->db, 0, 0); + }else{ + sqlite3_trace(p->db, sql_trace_callback, p->traceOut); + } +#endif + }else + + if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ + fprintf(p->out, "SQLite %s %s\n" /*extra-version-info*/, + sqlite3_libversion(), sqlite3_sourceid()); + }else + + if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ + const char *zDbName = nArg==2 ? azArg[1] : "main"; + char *zVfsName = 0; + if( p->db ){ + sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); + if( zVfsName ){ + fprintf(p->out, "%s\n", zVfsName); + sqlite3_free(zVfsName); + } + } + }else + +#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) + if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ + extern int sqlite3WhereTrace; + sqlite3WhereTrace = booleanValue(azArg[1]); + }else +#endif + + if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){ + int j; + assert( nArg<=ArraySize(azArg) ); + for(j=1; jcolWidth); j++){ + p->colWidth[j-1] = (int)integerValue(azArg[j]); + } + }else + + { + fprintf(stderr, "Error: unknown command or invalid arguments: " + " \"%s\". Enter \".help\" for help\n", azArg[0]); + rc = 1; + } + + return rc; +} + +/* +** Return TRUE if a semicolon occurs anywhere in the first N characters +** of string z[]. +*/ +static int line_contains_semicolon(const char *z, int N){ + int i; + for(i=0; iout); + zLine = one_input_line(in, zLine, nSql>0); + if( zLine==0 ){ + /* End of input */ + if( stdin_is_interactive ) printf("\n"); + break; + } + if( seenInterrupt ){ + if( in!=0 ) break; + seenInterrupt = 0; + } + lineno++; + if( nSql==0 && _all_whitespace(zLine) ) continue; + if( zLine && zLine[0]=='.' && nSql==0 ){ + if( p->echoOn ) printf("%s\n", zLine); + rc = do_meta_command(zLine, p); + if( rc==2 ){ /* exit requested */ + break; + }else if( rc ){ + errCnt++; + } + continue; + } + if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ + memcpy(zLine,";",2); + } + nLine = strlen30(zLine); + if( nSql+nLine+2>=nAlloc ){ + nAlloc = nSql+nLine+100; + zSql = realloc(zSql, nAlloc); + if( zSql==0 ){ + fprintf(stderr, "Error: out of memory\n"); + exit(1); + } + } + nSqlPrior = nSql; + if( nSql==0 ){ + int i; + for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} + assert( nAlloc>0 && zSql!=0 ); + memcpy(zSql, zLine+i, nLine+1-i); + startline = lineno; + nSql = nLine-i; + }else{ + zSql[nSql++] = '\n'; + memcpy(zSql+nSql, zLine, nLine+1); + nSql += nLine; + } + if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) + && sqlite3_complete(zSql) ){ + p->cnt = 0; + open_db(p); + BEGIN_TIMER; + rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg); + END_TIMER; + if( rc || zErrMsg ){ + char zPrefix[100]; + if( in!=0 || !stdin_is_interactive ){ + sqlite3_snprintf(sizeof(zPrefix), zPrefix, + "Error: near line %d:", startline); + }else{ + sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); + } + if( zErrMsg!=0 ){ + fprintf(stderr, "%s %s\n", zPrefix, zErrMsg); + sqlite3_free(zErrMsg); + zErrMsg = 0; + }else{ + fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); + } + errCnt++; + } + nSql = 0; + }else if( nSql && _all_whitespace(zSql) ){ + nSql = 0; + } + } + if( nSql ){ + if( !_all_whitespace(zSql) ){ + fprintf(stderr, "Error: incomplete SQL: %s\n", zSql); + } + free(zSql); + } + free(zLine); + return errCnt>0; +} + +/* +** Return a pathname which is the user's home directory. A +** 0 return indicates an error of some kind. +*/ +static char *find_home_dir(void){ + static char *home_dir = NULL; + if( home_dir ) return home_dir; + +#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL) + { + struct passwd *pwent; + uid_t uid = getuid(); + if( (pwent=getpwuid(uid)) != NULL) { + home_dir = pwent->pw_dir; + } + } +#endif + +#if defined(_WIN32_WCE) + /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() + */ + home_dir = "/"; +#else + +#if defined(_WIN32) || defined(WIN32) + if (!home_dir) { + home_dir = getenv("USERPROFILE"); + } +#endif + + if (!home_dir) { + home_dir = getenv("HOME"); + } + +#if defined(_WIN32) || defined(WIN32) + if (!home_dir) { + char *zDrive, *zPath; + int n; + zDrive = getenv("HOMEDRIVE"); + zPath = getenv("HOMEPATH"); + if( zDrive && zPath ){ + n = strlen30(zDrive) + strlen30(zPath) + 1; + home_dir = malloc( n ); + if( home_dir==0 ) return 0; + sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); + return home_dir; + } + home_dir = "c:\\"; + } +#endif + +#endif /* !_WIN32_WCE */ + + if( home_dir ){ + int n = strlen30(home_dir) + 1; + char *z = malloc( n ); + if( z ) memcpy(z, home_dir, n); + home_dir = z; + } + + return home_dir; +} + +/* +** Read input from the file given by sqliterc_override. Or if that +** parameter is NULL, take input from ~/.sqliterc +** +** Returns the number of errors. +*/ +static int process_sqliterc( + struct callback_data *p, /* Configuration data */ + const char *sqliterc_override /* Name of config file. NULL to use default */ +){ + char *home_dir = NULL; + const char *sqliterc = sqliterc_override; + char *zBuf = 0; + FILE *in = NULL; + int rc = 0; + + if (sqliterc == NULL) { + home_dir = find_home_dir(); + if( home_dir==0 ){ +#if !defined(__RTP__) && !defined(_WRS_KERNEL) + fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0); +#endif + return 1; + } + sqlite3_initialize(); + zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); + sqliterc = zBuf; + } + in = fopen(sqliterc,"rb"); + if( in ){ + if( stdin_is_interactive ){ + fprintf(stderr,"-- Loading resources from %s\n",sqliterc); + } + rc = process_input(p,in); + fclose(in); + } + sqlite3_free(zBuf); + return rc; +} + +/* +** Show available command line options +*/ +static const char zOptions[] = + " -bail stop after hitting an error\n" + " -batch force batch I/O\n" + " -column set output mode to 'column'\n" + " -cmd COMMAND run \"COMMAND\" before reading stdin\n" + " -csv set output mode to 'csv'\n" + " -echo print commands before execution\n" + " -init FILENAME read/process named file\n" + " -[no]header turn headers on or off\n" +#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) + " -heap SIZE Size of heap for memsys3 or memsys5\n" +#endif + " -help show this message\n" + " -html set output mode to HTML\n" + " -interactive force interactive I/O\n" + " -line set output mode to 'line'\n" + " -list set output mode to 'list'\n" + " -mmap N default mmap size set to N\n" +#ifdef SQLITE_ENABLE_MULTIPLEX + " -multiplex enable the multiplexor VFS\n" +#endif + " -nullvalue TEXT set text string for NULL values. Default ''\n" + " -separator SEP set output field separator. Default: '|'\n" + " -stats print memory stats before each finalize\n" + " -version show SQLite version\n" + " -vfs NAME use NAME as the default VFS\n" +#ifdef SQLITE_ENABLE_VFSTRACE + " -vfstrace enable tracing of all VFS calls\n" +#endif +; +static void usage(int showDetail){ + fprintf(stderr, + "Usage: %s [OPTIONS] FILENAME [SQL]\n" + "FILENAME is the name of an SQLite database. A new database is created\n" + "if the file does not previously exist.\n", Argv0); + if( showDetail ){ + fprintf(stderr, "OPTIONS include:\n%s", zOptions); + }else{ + fprintf(stderr, "Use the -help option for additional information\n"); + } + exit(1); +} + +/* +** Initialize the state information in data +*/ +static void main_init(struct callback_data *data) { + memset(data, 0, sizeof(*data)); + data->mode = MODE_List; + memcpy(data->separator,"|", 2); + data->showHeader = 0; + sqlite3_config(SQLITE_CONFIG_URI, 1); + sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); + sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); + sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); + sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); +} + +/* +** Get the argument to an --option. Throw an error and die if no argument +** is available. +*/ +static char *cmdline_option_value(int argc, char **argv, int i){ + if( i==argc ){ + fprintf(stderr, "%s: Error: missing argument to %s\n", + argv[0], argv[argc-1]); + exit(1); + } + return argv[i]; +} + +int main(int argc, char **argv){ + char *zErrMsg = 0; + struct callback_data data; + const char *zInitFile = 0; + char *zFirstCmd = 0; + int i; + int rc = 0; + + if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){ + fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", + sqlite3_sourceid(), SQLITE_SOURCE_ID); + exit(1); + } + Argv0 = argv[0]; + main_init(&data); + stdin_is_interactive = isatty(0); + + /* Make sure we have a valid signal handler early, before anything + ** else is done. + */ +#ifdef SIGINT + signal(SIGINT, interrupt_handler); +#endif + + /* Do an initial pass through the command-line argument to locate + ** the name of the database file, the name of the initialization file, + ** the size of the alternative malloc heap, + ** and the first command to execute. + */ + for(i=1; i0x7fff0000 ) szHeap = 0x7fff0000; + sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); +#endif +#ifdef SQLITE_ENABLE_VFSTRACE + }else if( strcmp(z,"-vfstrace")==0 ){ + extern int vfstrace_register( + const char *zTraceName, + const char *zOldVfsName, + int (*xOut)(const char*,void*), + void *pOutArg, + int makeDefault + ); + vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); +#endif +#ifdef SQLITE_ENABLE_MULTIPLEX + }else if( strcmp(z,"-multiplex")==0 ){ + extern int sqlite3_multiple_initialize(const char*,int); + sqlite3_multiplex_initialize(0, 1); +#endif + }else if( strcmp(z,"-mmap")==0 ){ + sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); + sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); + }else if( strcmp(z,"-vfs")==0 ){ + sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i)); + if( pVfs ){ + sqlite3_vfs_register(pVfs, 1); + }else{ + fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]); + exit(1); + } + } + } + if( data.zDbFilename==0 ){ +#ifndef SQLITE_OMIT_MEMORYDB + data.zDbFilename = ":memory:"; +#else + fprintf(stderr,"%s: Error: no database filename specified\n", Argv0); + return 1; +#endif + } + data.out = stdout; + + /* Go ahead and open the database file if it already exists. If the + ** file does not exist, delay opening it. This prevents empty database + ** files from being created if a user mistypes the database name argument + ** to the sqlite command-line tool. + */ + if( access(data.zDbFilename, 0)==0 ){ + open_db(&data); + } + + /* Process the initialization file if there is one. If no -init option + ** is given on the command line, look for a file named ~/.sqliterc and + ** try to process it. + */ + rc = process_sqliterc(&data,zInitFile); + if( rc>0 ){ + return rc; + } + + /* Make a second pass through the command-line argument and set + ** options. This second pass is delayed until after the initialization + ** file is processed so that the command-line arguments will override + ** settings in the initialization file. + */ + for(i=1; i /* Needed for the definition of va_list */ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif +#include + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +#ifndef SQLITE_API +# define SQLITE_API +#endif + + +/* +** These no-op macros are used in front of interfaces to mark those +** interfaces as either deprecated or experimental. New applications +** should not use deprecated interfaces - they are support for backwards +** compatibility only. Application writers should be aware that +** experimental interfaces are subject to change in point releases. +** +** These macros used to resolve to various kinds of compiler magic that +** would generate warning messages when they were used. But that +** compiler magic ended up generating such a flurry of bug reports +** that we have taken it all out and gone back to using simple +** noop macros. +*/ +#define SQLITE_DEPRECATED +#define SQLITE_EXPERIMENTAL + +/* +** Ensure these symbols were not defined by some previous header file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers +** +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header +** evaluates to a string literal that is the SQLite version in the +** format "X.Y.Z" where X is the major version number (always 3 for +** SQLite3) and Y is the minor version number and Z is the release number.)^ +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same +** numbers used in [SQLITE_VERSION].)^ +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also +** be larger than the release from which it is derived. Either Y will +** be held constant and Z will be incremented or else Y will be incremented +** and Z will be reset to zero. +** +** Since version 3.6.18, SQLite source code has been stored in the +** Fossil configuration management +** system. ^The SQLITE_SOURCE_ID macro evaluates to +** a string which identifies a particular check-in of SQLite +** within its configuration management system. ^The SQLITE_SOURCE_ID +** string contains the date and time of the check-in (UTC) and an SHA1 +** hash of the entire source tree. +** +** See also: [sqlite3_libversion()], +** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** [sqlite_version()] and [sqlite_source_id()]. +*/ +#define SQLITE_VERSION "3.8.1" +#define SQLITE_VERSION_NUMBER 3008001 +#define SQLITE_SOURCE_ID "2013-10-17 12:57:35 c78be6d786c19073b3a6730dfe3fb1be54f5657a" + +/* +** CAPI3REF: Run-Time Library Version Numbers +** KEYWORDS: sqlite3_version, sqlite3_sourceid +** +** These interfaces provide the same information as the [SQLITE_VERSION], +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros +** but are associated with the library instead of the header file. ^(Cautious +** programmers might include assert() statements in their application to +** verify that values returned by these interfaces match the macros in +** the header, and thus insure that the application is +** compiled with matching library and header files. +** +**
+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+** 
)^ +** +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The sqlite3_libversion() function returns a pointer to the +** to the sqlite3_version[] string constant. The sqlite3_libversion() +** function is provided for use in DLLs since DLL users usually do not have +** direct access to string constants within the DLL. ^The +** sqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns +** a pointer to a string constant whose value is the same as the +** [SQLITE_SOURCE_ID] C preprocessor macro. +** +** See also: [sqlite_version()] and [sqlite_source_id()]. +*/ +SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; +SQLITE_API const char *sqlite3_libversion(void); +SQLITE_API const char *sqlite3_sourceid(void); +SQLITE_API int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Run-Time Library Compilation Options Diagnostics +** +** ^The sqlite3_compileoption_used() function returns 0 or 1 +** indicating whether the specified option was defined at +** compile time. ^The SQLITE_ prefix may be omitted from the +** option name passed to sqlite3_compileoption_used(). +** +** ^The sqlite3_compileoption_get() function allows iterating +** over the list of options that were defined at compile time by +** returning the N-th compile time option string. ^If N is out of range, +** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** prefix is omitted from any strings returned by +** sqlite3_compileoption_get(). +** +** ^Support for the diagnostic functions sqlite3_compileoption_used() +** and sqlite3_compileoption_get() may be omitted by specifying the +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. +** +** See also: SQL functions [sqlite_compileoption_used()] and +** [sqlite_compileoption_get()] and the [compile_options pragma]. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +SQLITE_API int sqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *sqlite3_compileoption_get(int N); +#endif + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe +** +** ^The sqlite3_threadsafe() function returns zero if and only if +** SQLite was compiled with mutexing code omitted due to the +** [SQLITE_THREADSAFE] compile-time option being set to 0. +** +** SQLite can be compiled with or without mutexes. When +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes +** are enabled and SQLite is threadsafe. When the +** [SQLITE_THREADSAFE] macro is 0, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite concurrently from more than one thread. +** +** Enabling mutexes incurs a measurable performance penalty. +** So if speed is of utmost importance, it makes sense to disable +** the mutexes. But for maximum safety, mutexes should be enabled. +** ^The default behavior is for mutexes to be enabled. +** +** This interface can be used by an application to make sure that the +** version of SQLite that it is linking against was compiled with +** the desired setting of the [SQLITE_THREADSAFE] macro. +** +** This interface only reports on the compile-time mutex setting +** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but +** can be fully or partially disabled using a call to [sqlite3_config()] +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], +** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the +** sqlite3_threadsafe() function shows only the compile-time setting of +** thread safety, not any run-time changes to that setting made by +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() +** is unchanged by calls to sqlite3_config().)^ +** +** See the [threading mode] documentation for additional information. +*/ +SQLITE_API int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle +** KEYWORDS: {database connection} {database connections} +** +** Each open SQLite database is represented by a pointer to an instance of +** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] +** and [sqlite3_close_v2()] are its destructors. There are many other +** interfaces (such as +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on an +** sqlite3 object. +*/ +typedef struct sqlite3 sqlite3; + +/* +** CAPI3REF: 64-Bit Integer Types +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The sqlite_int64 and sqlite_uint64 types are supported for backwards +** compatibility only. +** +** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** between -9223372036854775808 and +9223372036854775807 inclusive. ^The +** sqlite3_uint64 and sqlite_uint64 types can store integer values +** between 0 and +18446744073709551615 inclusive. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection +** +** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors +** for the [sqlite3] object. +** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if +** the [sqlite3] object is successfully destroyed and all associated +** resources are deallocated. +** +** ^If the database connection is associated with unfinalized prepared +** statements or unfinished sqlite3_backup objects then sqlite3_close() +** will leave the database connection open and return [SQLITE_BUSY]. +** ^If sqlite3_close_v2() is called with unfinalized prepared statements +** and unfinished sqlite3_backups, then the database connection becomes +** an unusable "zombie" which will automatically be deallocated when the +** last prepared statement is finalized or the last sqlite3_backup is +** finished. The sqlite3_close_v2() interface is intended for use with +** host languages that are garbage collected, and where the order in which +** destructors are called is arbitrary. +** +** Applications should [sqlite3_finalize | finalize] all [prepared statements], +** [sqlite3_blob_close | close] all [BLOB handles], and +** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated +** with the [sqlite3] object prior to attempting to close the object. ^If +** sqlite3_close_v2() is called on a [database connection] that still has +** outstanding [prepared statements], [BLOB handles], and/or +** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation +** of resources is deferred until all [prepared statements], [BLOB handles], +** and [sqlite3_backup] objects are also destroyed. +** +** ^If an [sqlite3] object is destroyed while a transaction is open, +** the transaction is automatically rolled back. +** +** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] +** must be either a NULL +** pointer or an [sqlite3] object pointer obtained +** from [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()], and not previously closed. +** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer +** argument is a harmless no-op. +*/ +SQLITE_API int sqlite3_close(sqlite3*); +SQLITE_API int sqlite3_close_v2(sqlite3*); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface +** +** The sqlite3_exec() interface is a convenience wrapper around +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** that allows an application to run multiple statements of SQL +** without having to use a lot of C code. +** +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** semicolon-separate SQL statements passed into its 2nd argument, +** in the context of the [database connection] passed in as its 1st +** argument. ^If the callback function of the 3rd argument to +** sqlite3_exec() is not NULL, then it is invoked for each result row +** coming out of the evaluated SQL statements. ^The 4th argument to +** sqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to sqlite3_exec() +** is NULL, then no callback is ever invoked and result rows are +** ignored. +** +** ^If an error occurs while evaluating the SQL statements passed into +** sqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** is not NULL then any error message is written into memory obtained +** from [sqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [sqlite3_free()] +** on error message strings returned through the 5th parameter of +** of sqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** NULL before returning. +** +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** routine returns SQLITE_ABORT without invoking the callback again and +** without running any subsequent SQL statements. +** +** ^The 2nd argument to the sqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** callback is an array of pointers to strings obtained as if from +** [sqlite3_column_text()], one for each column. ^If an element of a +** result row is NULL then the corresponding string pointer for the +** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** sqlite3_exec() callback is an array of pointers to strings where each +** entry represents the name of corresponding result column as obtained +** from [sqlite3_column_name()]. +** +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** to an empty string, or a pointer that contains only whitespace and/or +** SQL comments, then no SQL statements are evaluated and the database +** is not changed. +** +** Restrictions: +** +**
    +**
  • The application must insure that the 1st parameter to sqlite3_exec() +** is a valid and open [database connection]. +**
  • The application must not close [database connection] specified by +** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +**
  • The application must not modify the SQL statement text passed into +** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +**
+*/ +SQLITE_API int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes +** KEYWORDS: SQLITE_OK {error code} {error codes} +** KEYWORDS: {result code} {result codes} +** +** Many SQLite functions return an integer result code from the set shown +** here in order to indicate success or failure. +** +** New error codes may be added in future versions of SQLite. +** +** See also: [SQLITE_IOERR_READ | extended result codes], +** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes]. +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ +#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes +** KEYWORDS: {extended error code} {extended error codes} +** KEYWORDS: {extended result code} {extended result codes} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that many of +** these result codes are too coarse-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. The extended result codes are enabled or disabled +** on a per database connection basis using the +** [sqlite3_extended_result_codes()] API. +** +** Some of the available extended result codes are listed here. +** One may expect the number of extended result codes will be expand +** over time. Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) +#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) +#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) +#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) +#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) +#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) +#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) +#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) +#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) +#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) +#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) +#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) +#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) +#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) +#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) +#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) +#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) +#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) +#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) +#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) +#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) +#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) +#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) +#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) +#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) +#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) +#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) +#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) +#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) +#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) +#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) +#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) +#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) +#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) +#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) +#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) + +/* +** CAPI3REF: Flags For File Open Operations +** +** These bit values are intended for use in the +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter to the [sqlite3_vfs.xOpen] method. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ +#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ +#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ +#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ + +/* Reserved: 0x00F00000 */ + +/* +** CAPI3REF: Device Characteristics +** +** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** object returns an integer which is a vector of these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that +** after reboot following a crash or power loss, the only bytes in a +** file that were written at the application level might have changed +** and that adjacent bytes, even bytes within the same sector are +** guaranteed to be unchanged. +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 +#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 + +/* +** CAPI3REF: File Locking Levels +** +** SQLite uses one of these integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags +** +** When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of +** these integer values as the second argument. +** +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. If the lower four bits of the flag +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. +** If the lower four bits equal SQLITE_SYNC_FULL, that means +** to use Mac OS X style fullsync instead of fsync(). +** +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL +** settings. The [synchronous pragma] determines when calls to the +** xSync VFS method occur and applies uniformly across all platforms. +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how +** energetic or rigorous or forceful the sync operations are and +** only make a difference on Mac OSX for the default SQLite code. +** (Third-party VFS implementations might also make the distinction +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the +** operating systems natively supported by SQLite, only Mac OSX +** cares about the difference.) +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + +/* +** CAPI3REF: OS Interface Open File Handle +** +** An [sqlite3_file] object represents an open file in the +** [sqlite3_vfs | OS interface layer]. Individual OS interface +** implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object +** +** Every file opened by the [sqlite3_vfs.xOpen] method populates an +** [sqlite3_file] object (or, more commonly, a subclass of the +** [sqlite3_file] object) with a pointer to an instance of this object. +** This object defines the methods used to perform various operations +** against the open file represented by the [sqlite3_file] object. +** +** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method +** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The +** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] +** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element +** to NULL. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] +** flag may be ORed in to indicate that only the data of the file +** and not its inode needs to be synced. +** +** The integer values to xLock() and xUnlock() are one of +**
    +**
  • [SQLITE_LOCK_NONE], +**
  • [SQLITE_LOCK_SHARED], +**
  • [SQLITE_LOCK_RESERVED], +**
  • [SQLITE_LOCK_PENDING], or +**
  • [SQLITE_LOCK_EXCLUSIVE]. +**
+** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method checks whether any database connection, +** either in this process or in some other process, is holding a RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false otherwise. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument is an +** integer opcode. The third argument is a generic pointer intended to +** point to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves all opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. VFS implementations should +** return [SQLITE_NOTFOUND] for file control opcodes that they do not +** recognize. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
    +**
  • [SQLITE_IOCAP_ATOMIC] +**
  • [SQLITE_IOCAP_ATOMIC512] +**
  • [SQLITE_IOCAP_ATOMIC1K] +**
  • [SQLITE_IOCAP_ATOMIC2K] +**
  • [SQLITE_IOCAP_ATOMIC4K] +**
  • [SQLITE_IOCAP_ATOMIC8K] +**
  • [SQLITE_IOCAP_ATOMIC16K] +**
  • [SQLITE_IOCAP_ATOMIC32K] +**
  • [SQLITE_IOCAP_ATOMIC64K] +**
  • [SQLITE_IOCAP_SAFE_APPEND] +**
  • [SQLITE_IOCAP_SEQUENTIAL] +**
+** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +** +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill +** in the unread portions of the buffer with zeros. A VFS that +** fails to zero-fill short reads might seem to work. However, +** failure to zero-fill short reads will eventually lead to +** database corruption. +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Methods above are valid for version 1 */ + int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(sqlite3_file*); + int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + /* Methods above are valid for version 2 */ + int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); + int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); + /* Methods above are valid for version 3 */ + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** interface. +** +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode causes the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +**
    +**
  • [[SQLITE_FCNTL_SIZE_HINT]] +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS +** layer a hint of how large the database file will grow to be during the +** current transaction. This hint is not guaranteed to be accurate but it +** is often close. The underlying VFS might choose to preallocate database +** file space based on this hint in order to help writes to the database +** file run faster. +** +**
  • [[SQLITE_FCNTL_CHUNK_SIZE]] +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS +** extends and truncates the database file in chunks of a size specified +** by the user. The fourth argument to [sqlite3_file_control()] should +** point to an integer (type int) containing the new chunk-size to use +** for the nominated database. Allocating database file space in large +** chunks (say 1MB at a time), may reduce file-system fragmentation and +** improve performance on some systems. +** +**
  • [[SQLITE_FCNTL_FILE_POINTER]] +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with a particular database +** connection. See the [sqlite3_file_control()] documentation for +** additional information. +** +**
  • [[SQLITE_FCNTL_SYNC_OMITTED]] +** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by +** SQLite and sent to all VFSes in place of a call to the xSync method +** when the database connection has [PRAGMA synchronous] set to OFF.)^ +** Some specialized VFSes need this signal in order to operate correctly +** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most +** VFSes do not need this signal and should silently ignore this opcode. +** Applications should not call [sqlite3_file_control()] with this +** opcode as doing so may disrupt the operation of the specialized VFSes +** that do require it. +** +**
  • [[SQLITE_FCNTL_WIN32_AV_RETRY]] +** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic +** retry counts and intervals for certain disk I/O operations for the +** windows [VFS] in order to provide robustness in the presence of +** anti-virus programs. By default, the windows VFS will retry file read, +** file write, and file delete operations up to 10 times, with a delay +** of 25 milliseconds before the first retry and with the delay increasing +** by an additional 25 milliseconds with each subsequent retry. This +** opcode allows these two values (10 retries and 25 milliseconds of delay) +** to be adjusted. The values are changed for all database connections +** within the same process. The argument is a pointer to an array of two +** integers where the first integer i the new retry count and the second +** integer is the delay. If either integer is negative, then the setting +** is not changed but instead the prior value of that setting is written +** into the array entry, allowing the current retry settings to be +** interrogated. The zDbName parameter is ignored. +** +**
  • [[SQLITE_FCNTL_PERSIST_WAL]] +** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the +** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary +** write ahead log and shared memory files used for transaction control +** are automatically deleted when the latest connection to the database +** closes. Setting persistent WAL mode causes those files to persist after +** close. Persisting the files is useful when other processes that do not +** have write permission on the directory containing the database file want +** to read the database file, as the WAL and shared memory files must exist +** in order for the database to be readable. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable persistent WAL mode or 1 to enable persistent +** WAL mode. If the integer is -1, then it is overwritten with the current +** WAL persistence setting. +** +**
  • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] +** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the +** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting +** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the +** xDeviceCharacteristics methods. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage +** mode. If the integer is -1, then it is overwritten with the current +** zero-damage mode setting. +** +**
  • [[SQLITE_FCNTL_OVERWRITE]] +** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening +** a write transaction to indicate that, unless it is rolled back for some +** reason, the entire database file will be overwritten by the current +** transaction. This is used by VACUUM operations. +** +**
  • [[SQLITE_FCNTL_VFSNAME]] +** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of +** all [VFSes] in the VFS stack. The names are of all VFS shims and the +** final bottom-level VFS are written into memory obtained from +** [sqlite3_malloc()] and the result is stored in the char* variable +** that the fourth parameter of [sqlite3_file_control()] points to. +** The caller is responsible for freeing the memory when done. As with +** all file-control actions, there is no guarantee that this will actually +** do anything. Callers should initialize the char* variable to a NULL +** pointer in case this file-control is not implemented. This file-control +** is intended for diagnostic use only. +** +**
  • [[SQLITE_FCNTL_PRAGMA]] +** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] +** file control is sent to the open [sqlite3_file] object corresponding +** to the database file to which the pragma statement refers. ^The argument +** to the [SQLITE_FCNTL_PRAGMA] file control is an array of +** pointers to strings (char**) in which the second element of the array +** is the name of the pragma and the third element is the argument to the +** pragma or NULL if the pragma has no argument. ^The handler for an +** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element +** of the char** argument point to a string obtained from [sqlite3_mprintf()] +** or the equivalent and that string will become the result of the pragma or +** the error message if the pragma fails. ^If the +** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal +** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] +** file control returns [SQLITE_OK], then the parser assumes that the +** VFS has handled the PRAGMA itself and the parser generates a no-op +** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns +** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means +** that the VFS encountered an error while handling the [PRAGMA] and the +** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] +** file control occurs at the beginning of pragma statement analysis and so +** it is able to override built-in [PRAGMA] statements. +** +**
  • [[SQLITE_FCNTL_BUSYHANDLER]] +** ^The [SQLITE_FCNTL_BUSYHANDLER] +** file-control may be invoked by SQLite on the database file handle +** shortly after it is opened in order to provide a custom VFS with access +** to the connections busy-handler callback. The argument is of type (void **) +** - an array of two (void *) values. The first (void *) actually points +** to a function of type (int (*)(void *)). In order to invoke the connections +** busy-handler, this function should be invoked with the second (void *) in +** the array as the only argument. If it returns non-zero, then the operation +** should be retried. If it returns zero, the custom VFS should abandon the +** current operation. +** +**
  • [[SQLITE_FCNTL_TEMPFILENAME]] +** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control +** to have SQLite generate a +** temporary filename using the same algorithm that is followed to generate +** temporary filenames for TEMP tables and other internal uses. The +** argument should be a char** which will be filled with the filename +** written into memory obtained from [sqlite3_malloc()]. The caller should +** invoke [sqlite3_free()] on the result to avoid a memory leak. +** +**
  • [[SQLITE_FCNTL_MMAP_SIZE]] +** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the +** maximum number of bytes that will be used for memory-mapped I/O. +** The argument is a pointer to a value of type sqlite3_int64 that +** is an advisory maximum number of bytes in the file to memory map. The +** pointer is overwritten with the old value. The limit is not changed if +** the value originally pointed to is negative, and so the current limit +** can be queried by passing in a pointer to a negative number. This +** file-control is used internally to implement [PRAGMA mmap_size]. +** +**
+*/ +#define SQLITE_FCNTL_LOCKSTATE 1 +#define SQLITE_GET_LOCKPROXYFILE 2 +#define SQLITE_SET_LOCKPROXYFILE 3 +#define SQLITE_LAST_ERRNO 4 +#define SQLITE_FCNTL_SIZE_HINT 5 +#define SQLITE_FCNTL_CHUNK_SIZE 6 +#define SQLITE_FCNTL_FILE_POINTER 7 +#define SQLITE_FCNTL_SYNC_OMITTED 8 +#define SQLITE_FCNTL_WIN32_AV_RETRY 9 +#define SQLITE_FCNTL_PERSIST_WAL 10 +#define SQLITE_FCNTL_OVERWRITE 11 +#define SQLITE_FCNTL_VFSNAME 12 +#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 +#define SQLITE_FCNTL_PRAGMA 14 +#define SQLITE_FCNTL_BUSYHANDLER 15 +#define SQLITE_FCNTL_TEMPFILENAME 16 +#define SQLITE_FCNTL_MMAP_SIZE 18 + +/* +** CAPI3REF: Mutex Handle +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object +** +** An instance of the sqlite3_vfs object defines the interface between +** the SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". See +** the [VFS | VFS documentation] for further information. +** +** The value of the iVersion field is initially 1 but may be larger in +** future versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. Note that the structure +** of the sqlite3_vfs object changes in the transaction between +** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not +** modified. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered sqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. Neither the application code nor the VFS +** implementation should use the pNext pointer. +** +** The pNext field is the only field in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** [[sqlite3_vfs.xOpen]] +** ^SQLite guarantees that the zFilename parameter to xOpen +** is either a NULL pointer or string obtained +** from xFullPathname() with an optional suffix added. +** ^If a suffix is added to the zFilename parameter, it will +** consist of a single "-" character followed by no more than +** 11 alphanumeric and/or "-" characters. +** ^SQLite further guarantees that +** the string will be valid and unchanged until xClose() is +** called. Because of the previous sentence, +** the [sqlite3_file] can safely store a pointer to the +** filename if it needs to remember the filename for some reason. +** If the zFilename parameter to xOpen is a NULL pointer then xOpen +** must invent its own temporary name for the file. ^Whenever the +** xFilename parameter is NULL it will also be the case that the +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. +** +** The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. +** +** ^(SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
    +**
  • [SQLITE_OPEN_MAIN_DB] +**
  • [SQLITE_OPEN_MAIN_JOURNAL] +**
  • [SQLITE_OPEN_TEMP_DB] +**
  • [SQLITE_OPEN_TEMP_JOURNAL] +**
  • [SQLITE_OPEN_TRANSIENT_DB] +**
  • [SQLITE_OPEN_SUBJOURNAL] +**
  • [SQLITE_OPEN_MASTER_JOURNAL] +**
  • [SQLITE_OPEN_WAL] +**
)^ +** +** The file I/O implementation can use the object type flags to +** change the way it deals with files. For example, an application +** that does not care about crash recovery or rollback might make +** the open of a journal file a no-op. Writes to this journal would +** also be no-ops, and any attempt to read the journal would return +** SQLITE_IOERR. Or the implementation might recognize that a database +** file will be doing page-aligned sector reads and writes in a random +** order and set up its I/O subsystem accordingly. +** +** SQLite might also add one of the following flags to the xOpen method: +** +**
    +**
  • [SQLITE_OPEN_DELETEONCLOSE] +**
  • [SQLITE_OPEN_EXCLUSIVE] +**
+** +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases and their journals, transient +** databases, and subjournals. +** +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction +** with the [SQLITE_OPEN_CREATE] flag, which are both directly +** analogous to the O_EXCL and O_CREAT flags of the POSIX open() +** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the +** SQLITE_OPEN_CREATE, is used to indicate that file should always +** be created, and that it is an error if it already exists. +** It is not used to indicate the file should be opened +** for exclusive access. +** +** ^At least szOsFile bytes of memory are allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. The xOpen method does not have to +** allocate the structure; it should just fill it in. Note that +** the xOpen method must set the sqlite3_file.pMethods to either +** a valid [sqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** element will be valid after xOpen returns regardless of the success +** or failure of the xOpen call. +** +** [[sqlite3_vfs.xAccess]] +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test whether a file is at least readable. The file can be a +** directory. +** +** ^SQLite will always allocate at least mxPathname+1 bytes for the +** output buffer xFullPathname. The exact size of the output buffer +** is also passed as a parameter to both methods. If the output buffer +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is +** handled as a fatal error by SQLite, vfs implementations should endeavor +** to prevent this by setting mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() +** interfaces are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. +** The xSleep() method causes the calling thread to sleep for at +** least the number of microseconds given. ^The xCurrentTime() +** method returns a Julian Day Number for the current date and time as +** a floating point value. +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian +** Day Number multiplied by 86400000 (the number of milliseconds in +** a 24-hour day). +** ^SQLite will use the xCurrentTimeInt64() method to get the current +** date and time if that method is available (if iVersion is 2 or +** greater and the function pointer is not NULL) and will fall back +** to xCurrentTime() if xCurrentTimeInt64() is unavailable. +** +** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces +** are not used by the SQLite core. These optional interfaces are provided +** by some VFSes to facilitate testing of the VFS code. By overriding +** system calls with functions under its control, a test program can +** simulate faults and error conditions that would otherwise be difficult +** or impossible to induce. The set of system calls that can be overridden +** varies from one VFS to another, and from one version of the same VFS to the +** next. Applications that use these interfaces must be prepared for any +** or all of these interfaces to be NULL or for their behavior to change +** from one release to the next. Applications must not attempt to access +** any of these methods if the iVersion of the VFS is less than 3. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +typedef void (*sqlite3_syscall_ptr)(void); +struct sqlite3_vfs { + int iVersion; /* Structure version number (currently 3) */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + int (*xGetLastError)(sqlite3_vfs*, int, char *); + /* + ** The methods above are in version 1 of the sqlite_vfs object + ** definition. Those that follow are added in version 2 or later + */ + int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + /* + ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + ** Those below are for version 3 and greater. + */ + int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); + sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); + const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); + /* + ** The methods above are in versions 1 through 3 of the sqlite_vfs object. + ** New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. + */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method +** +** These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. They determine +** what kind of permissions the xAccess method is looking for. +** With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks whether the file exists. +** With SQLITE_ACCESS_READWRITE, the xAccess method +** checks whether the named directory is both readable and writable +** (in other words, if files can be added, removed, and renamed within +** the directory). +** The SQLITE_ACCESS_READWRITE constant is currently used only by the +** [temp_store_directory pragma], though this could change in a future +** release of SQLite. +** With SQLITE_ACCESS_READ, the xAccess method +** checks whether the file is readable. The SQLITE_ACCESS_READ constant is +** currently unused, though it might be used in a future release of +** SQLite. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ +#define SQLITE_ACCESS_READ 2 /* Unused */ + +/* +** CAPI3REF: Flags for the xShmLock VFS method +** +** These integer constants define the various locking operations +** allowed by the xShmLock method of [sqlite3_io_methods]. The +** following are the only legal combinations of flags to the +** xShmLock method: +** +**
    +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE +**
+** +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as +** was given no the corresponding lock. +** +** The xShmLock method can transition between unlocked and SHARED or +** between unlocked and EXCLUSIVE. It cannot transition between SHARED +** and EXCLUSIVE. +*/ +#define SQLITE_SHM_UNLOCK 1 +#define SQLITE_SHM_LOCK 2 +#define SQLITE_SHM_SHARED 4 +#define SQLITE_SHM_EXCLUSIVE 8 + +/* +** CAPI3REF: Maximum xShmLock index +** +** The xShmLock method on [sqlite3_io_methods] may use values +** between 0 and this upper bound as its "offset" argument. +** The SQLite core will never attempt to acquire or release a +** lock outside of this range +*/ +#define SQLITE_SHM_NLOCK 8 + + +/* +** CAPI3REF: Initialize The SQLite Library +** +** ^The sqlite3_initialize() routine initializes the +** SQLite library. ^The sqlite3_shutdown() routine +** deallocates any resources that were allocated by sqlite3_initialize(). +** These routines are designed to aid in process initialization and +** shutdown on embedded systems. Workstation applications using +** SQLite normally do not need to invoke either of these routines. +** +** A call to sqlite3_initialize() is an "effective" call if it is +** the first time sqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time sqlite3_initialize() is invoked +** following a call to sqlite3_shutdown(). ^(Only an effective call +** of sqlite3_initialize() does any initialization. All other calls +** are harmless no-ops.)^ +** +** A call to sqlite3_shutdown() is an "effective" call if it is the first +** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only +** an effective call to sqlite3_shutdown() does any deinitialization. +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() +** is not. The sqlite3_shutdown() interface must only be called from a +** single thread. All open [database connections] must be closed and all +** other SQLite resources must be deallocated prior to invoking +** sqlite3_shutdown(). +** +** Among other things, ^sqlite3_initialize() will invoke +** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() +** will invoke sqlite3_os_end(). +** +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, sqlite3_initialize() is unable to initialize +** the library (perhaps it is unable to allocate a needed resource such +** as a mutex) it returns an [error code] other than [SQLITE_OK]. +** +** ^The sqlite3_initialize() routine is called internally by many other +** SQLite interfaces so that an application usually does not need to +** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] +** calls sqlite3_initialize() so the SQLite library will be automatically +** initialized when [sqlite3_open()] is called if it has not be initialized +** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] +** compile-time option, then the automatic calls to sqlite3_initialize() +** are omitted and the application must call sqlite3_initialize() directly +** prior to using any other SQLite interface. For maximum portability, +** it is recommended that applications always invoke sqlite3_initialize() +** directly prior to using any other SQLite interface. Future releases +** of SQLite may require this. In other words, the behavior exhibited +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the +** default behavior in some future release of SQLite. +** +** The sqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The sqlite3_os_end() +** routine undoes the effect of sqlite3_os_init(). Typical tasks +** performed by these routines include allocation or deallocation +** of static resources, initialization of global variables, +** setting up a default [sqlite3_vfs] module, or setting up +** a default configuration using [sqlite3_config()]. +** +** The application should never invoke either sqlite3_os_init() +** or sqlite3_os_end() directly. The application should only invoke +** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() +** interface is called automatically by sqlite3_initialize() and +** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate +** implementations for sqlite3_os_init() and sqlite3_os_end() +** are built into SQLite when it is compiled for Unix, Windows, or OS/2. +** When [custom builds | built for other platforms] +** (using the [SQLITE_OS_OTHER=1] compile-time +** option) the application must supply a suitable implementation for +** sqlite3_os_init() and sqlite3_os_end(). An application-supplied +** implementation of sqlite3_os_init() or sqlite3_os_end() +** must return [SQLITE_OK] on success and some other [error code] upon +** failure. +*/ +SQLITE_API int sqlite3_initialize(void); +SQLITE_API int sqlite3_shutdown(void); +SQLITE_API int sqlite3_os_init(void); +SQLITE_API int sqlite3_os_end(void); + +/* +** CAPI3REF: Configuring The SQLite Library +** +** The sqlite3_config() interface is used to make global configuration +** changes to SQLite in order to tune SQLite to the specific needs of +** the application. The default configuration is recommended for most +** applications and so this routine is usually not necessary. It is +** provided to support rare applications with unusual needs. +** +** The sqlite3_config() interface is not threadsafe. The application +** must insure that no other SQLite interfaces are invoked by other +** threads while sqlite3_config() is running. Furthermore, sqlite3_config() +** may only be invoked prior to library initialization using +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before +** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. +** Note, however, that ^sqlite3_config() can be called as part of the +** implementation of an application-defined [sqlite3_os_init()]. +** +** The first argument to sqlite3_config() is an integer +** [configuration option] that determines +** what property of SQLite is to be configured. Subsequent arguments +** vary depending on the [configuration option] +** in the first argument. +** +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^If the option is unknown or SQLite is unable to set the option +** then this routine returns a non-zero [error code]. +*/ +SQLITE_API int sqlite3_config(int, ...); + +/* +** CAPI3REF: Configure database connections +** +** The sqlite3_db_config() interface is used to make configuration +** changes to a [database connection]. The interface is similar to +** [sqlite3_config()] except that the changes apply to a single +** [database connection] (specified in the first argument). +** +** The second argument to sqlite3_db_config(D,V,...) is the +** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code +** that indicates what aspect of the [database connection] is being configured. +** Subsequent arguments vary depending on the configuration verb. +** +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** the call is considered successful. +*/ +SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Memory Allocation Routines +** +** An instance of this object defines the interface between SQLite +** and low-level memory allocation routines. +** +** This object is used in only one place in the SQLite interface. +** A pointer to an instance of this object is the argument to +** [sqlite3_config()] when the configuration option is +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. +** By creating an instance of this object +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** during configuration, an application can specify an alternative +** memory allocation subsystem for SQLite to use for all of its +** dynamic memory needs. +** +** Note that SQLite comes with several [built-in memory allocators] +** that are perfectly adequate for the overwhelming majority of applications +** and that this object is only useful to a tiny minority of applications +** with specialized memory allocation requirements. This object is +** also used during testing of SQLite in order to specify an alternative +** memory allocator that simulates memory out-of-memory conditions in +** order to verify that SQLite recovers gracefully from such +** conditions. +** +** The xMalloc, xRealloc, and xFree methods must work like the +** malloc(), realloc() and free() functions from the standard C library. +** ^SQLite guarantees that the second argument to +** xRealloc is always a value returned by a prior call to xRoundup. +** +** xSize should return the allocated size of a memory allocation +** previously obtained from xMalloc or xRealloc. The allocated size +** is always at least as big as the requested size but may be larger. +** +** The xRoundup method returns what would be the allocated size of +** a memory allocation given a particular requested size. Most memory +** allocators round up memory allocations at least to the next multiple +** of 8. Some allocators round up to a larger multiple or to a power of 2. +** Every memory allocation request coming in through [sqlite3_malloc()] +** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** that causes the corresponding memory allocation to fail. +** +** The xInit method initializes the memory allocator. (For example, +** it might allocate any require mutexes or initialize internal data +** structures. The xShutdown method is invoked (indirectly) by +** [sqlite3_shutdown()] and should deallocate any resources acquired +** by xInit. The pAppData pointer is used as the only parameter to +** xInit and xShutdown. +** +** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes +** the xInit method, so the xInit method need not be threadsafe. The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. For all other methods, SQLite +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which +** it is by default) and so the methods are automatically serialized. +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other +** methods must be threadsafe or else make their own arrangements for +** serialization. +** +** SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +*/ +typedef struct sqlite3_mem_methods sqlite3_mem_methods; +struct sqlite3_mem_methods { + void *(*xMalloc)(int); /* Memory allocation function */ + void (*xFree)(void*); /* Free a prior allocation */ + void *(*xRealloc)(void*,int); /* Resize an allocation */ + int (*xSize)(void*); /* Return the size of an allocation */ + int (*xRoundup)(int); /* Round up request size to allocation size */ + int (*xInit)(void*); /* Initialize the memory allocator */ + void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + void *pAppData; /* Argument to xInit() and xShutdown() */ +}; + +/* +** CAPI3REF: Configuration Options +** KEYWORDS: {configuration option} +** +** These constants are the available integer configuration options that +** can be passed as the first argument to the [sqlite3_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_config()] to make sure that +** the call worked. The [sqlite3_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+** [[SQLITE_CONFIG_SINGLETHREAD]]
SQLITE_CONFIG_SINGLETHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Single-thread. In other words, it disables +** all mutexing and puts SQLite into a mode where it can only be used +** by a single thread. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to change the [threading mode] from its default +** value of Single-thread and so [sqlite3_config()] will return +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD +** configuration option.
+** +** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Multi-thread. In other words, it disables +** mutexing on [database connection] and [prepared statement] objects. +** The application is responsible for serializing access to +** [database connections] and [prepared statements]. But other mutexes +** are enabled so that SQLite will be safe to use in a multi-threaded +** environment as long as no two threads attempt to use the same +** [database connection] at the same time. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Multi-thread [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_MULTITHREAD configuration option.
+** +** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Serialized. In other words, this option enables +** all mutexes including the recursive +** mutexes on [database connection] and [prepared statement] objects. +** In this mode (which is the default when SQLite is compiled with +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access +** to [database connections] and [prepared statements] so that the +** application is free to use the same [database connection] or the +** same [prepared statement] in different threads at the same time. +** ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Serialized [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_SERIALIZED configuration option.
+** +** [[SQLITE_CONFIG_MALLOC]]
SQLITE_CONFIG_MALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The argument specifies +** alternative low-level memory allocation routines to be used in place of +** the memory allocation routines built into SQLite.)^ ^SQLite makes +** its own private copy of the content of the [sqlite3_mem_methods] structure +** before the [sqlite3_config()] call returns.
+** +** [[SQLITE_CONFIG_GETMALLOC]]
SQLITE_CONFIG_GETMALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] +** structure is filled with the currently defined memory allocation routines.)^ +** This option can be used to overload the default memory allocation +** routines with a wrapper that simulations memory allocation failure or +** tracks memory usage, for example.
+** +** [[SQLITE_CONFIG_MEMSTATUS]]
SQLITE_CONFIG_MEMSTATUS
+**
^This option takes single argument of type int, interpreted as a +** boolean, which enables or disables the collection of memory allocation +** statistics. ^(When memory allocation statistics are disabled, the +** following SQLite interfaces become non-operational: +**
    +**
  • [sqlite3_memory_used()] +**
  • [sqlite3_memory_highwater()] +**
  • [sqlite3_soft_heap_limit64()] +**
  • [sqlite3_status()] +**
)^ +** ^Memory allocation statistics are enabled by default unless SQLite is +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory +** allocation statistics are disabled by default. +**
+** +** [[SQLITE_CONFIG_SCRATCH]]
SQLITE_CONFIG_SCRATCH
+**
^This option specifies a static memory buffer that SQLite can use for +** scratch memory. There are three arguments: A pointer an 8-byte +** aligned memory buffer from which the scratch allocations will be +** drawn, the size of each scratch allocation (sz), +** and the maximum number of scratch allocations (N). The sz +** argument must be a multiple of 16. +** The first argument must be a pointer to an 8-byte aligned buffer +** of at least sz*N bytes of memory. +** ^SQLite will use no more than two scratch buffers per thread. So +** N should be set to twice the expected maximum number of threads. +** ^SQLite will never require a scratch buffer that is more than 6 +** times the database page size. ^If SQLite needs needs additional +** scratch memory beyond what is provided by this configuration option, then +** [sqlite3_malloc()] will be used to obtain the memory needed.
+** +** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
+**
^This option specifies a static memory buffer that SQLite can use for +** the database page cache with the default page cache implementation. +** This configuration should not be used if an application-define page +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option. +** There are three arguments to this option: A pointer to 8-byte aligned +** memory, the size of each page buffer (sz), and the number of pages (N). +** The sz argument should be the size of the largest database page +** (a power of two between 512 and 32768) plus a little extra for each +** page header. ^The page header size is 20 to 40 bytes depending on +** the host architecture. ^It is harmless, apart from the wasted memory, +** to make sz a little too large. The first +** argument should point to an allocation of at least sz*N bytes of memory. +** ^SQLite will use the memory provided by the first argument to satisfy its +** memory needs for the first N pages that it adds to cache. ^If additional +** page cache memory is needed beyond what is provided by this option, then +** SQLite goes to [sqlite3_malloc()] for the additional storage space. +** The pointer in the first argument must +** be aligned to an 8-byte boundary or subsequent behavior of SQLite +** will be undefined.
+** +** [[SQLITE_CONFIG_HEAP]]
SQLITE_CONFIG_HEAP
+**
^This option specifies a static memory buffer that SQLite will use +** for all of its dynamic memory allocation needs beyond those provided +** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. +** There are three arguments: An 8-byte aligned pointer to the memory, +** the number of bytes in the memory buffer, and the minimum allocation size. +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts +** to using its default memory allocator (the system malloc() implementation), +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the +** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or +** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory +** allocator is engaged to handle all of SQLites memory allocation needs. +** The first pointer (the memory pointer) must be aligned to an 8-byte +** boundary or subsequent behavior of SQLite will be undefined. +** The minimum allocation size is capped at 2**12. Reasonable values +** for the minimum allocation size are 2**5 through 2**8.
+** +** [[SQLITE_CONFIG_MUTEX]]
SQLITE_CONFIG_MUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The argument specifies +** alternative low-level mutex routines to be used in place +** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the +** content of the [sqlite3_mutex_methods] structure before the call to +** [sqlite3_config()] returns. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_GETMUTEX]]
SQLITE_CONFIG_GETMUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The +** [sqlite3_mutex_methods] +** structure is filled with the currently defined mutex routines.)^ +** This option can be used to overload the default mutex allocation +** routines with a wrapper used to track mutex usage for performance +** profiling or testing, for example. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
+**
^(This option takes two arguments that determine the default +** memory allocation for the lookaside memory allocator on each +** [database connection]. The first argument is the +** size of each lookaside buffer slot and the second is the number of +** slots allocated to each database connection.)^ ^(This option sets the +** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] +** verb to [sqlite3_db_config()] can be used to change the lookaside +** configuration on individual connections.)^
+** +** [[SQLITE_CONFIG_PCACHE2]]
SQLITE_CONFIG_PCACHE2
+**
^(This option takes a single argument which is a pointer to +** an [sqlite3_pcache_methods2] object. This object specifies the interface +** to a custom page cache implementation.)^ ^SQLite makes a copy of the +** object and uses it for page cache memory allocations.
+** +** [[SQLITE_CONFIG_GETPCACHE2]]
SQLITE_CONFIG_GETPCACHE2
+**
^(This option takes a single argument which is a pointer to an +** [sqlite3_pcache_methods2] object. SQLite copies of the current +** page cache implementation into that object.)^
+** +** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
+**
The SQLITE_CONFIG_LOG option is used to configure the SQLite +** global [error log]. +** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a +** function with a call signature of void(*)(void*,int,const char*), +** and a pointer to void. ^If the function pointer is not NULL, it is +** invoked by [sqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is +** passed through as the first parameter to the application-defined logger +** function whenever that function is invoked. ^The second parameter to +** the logger function is a copy of the first parameter to the corresponding +** [sqlite3_log()] call and is intended to be a [result code] or an +** [extended result code]. ^The third parameter passed to the logger is +** log message after formatting via [sqlite3_snprintf()]. +** The SQLite logging interface is not reentrant; the logger function +** supplied by the application must not invoke any SQLite interface. +** In a multi-threaded application, the application-defined logger +** function must be threadsafe.
+** +** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI +**
^(This option takes a single argument of type int. If non-zero, then +** URI handling is globally enabled. If the parameter is zero, then URI handling +** is globally disabled.)^ ^If URI handling is globally enabled, all filenames +** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or +** specified as part of [ATTACH] commands are interpreted as URIs, regardless +** of whether or not the [SQLITE_OPEN_URI] flag is set when the database +** connection is opened. ^If it is globally disabled, filenames are +** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the +** database connection is opened. ^(By default, URI handling is globally +** disabled. The default value may be changed by compiling with the +** [SQLITE_USE_URI] symbol defined.)^ +** +** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
SQLITE_CONFIG_COVERING_INDEX_SCAN +**
^This option takes a single integer argument which is interpreted as +** a boolean in order to enable or disable the use of covering indices for +** full table scans in the query optimizer. ^The default setting is determined +** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" +** if that compile-time option is omitted. +** The ability to disable the use of covering indices for full table scans +** is because some incorrectly coded legacy applications might malfunction +** when the optimization is enabled. Providing the ability to +** disable the optimization allows the older, buggy application code to work +** without change even with newer versions of SQLite. +** +** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] +**
SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE +**
These options are obsolete and should not be used by new code. +** They are retained for backwards compatibility but are now no-ops. +**
+** +** [[SQLITE_CONFIG_SQLLOG]] +**
SQLITE_CONFIG_SQLLOG +**
This option is only available if sqlite is compiled with the +** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should +** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). +** The second should be of type (void*). The callback is invoked by the library +** in three separate circumstances, identified by the value passed as the +** fourth parameter. If the fourth parameter is 0, then the database connection +** passed as the second argument has just been opened. The third argument +** points to a buffer containing the name of the main database file. If the +** fourth parameter is 1, then the SQL statement that the third parameter +** points to has just been executed. Or, if the fourth parameter is 2, then +** the connection being passed as the second parameter is being closed. The +** third parameter is passed NULL In this case. An example of using this +** configuration option can be seen in the "test_sqllog.c" source file in +** the canonical SQLite source tree.
+** +** [[SQLITE_CONFIG_MMAP_SIZE]] +**
SQLITE_CONFIG_MMAP_SIZE +**
^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values +** that are the default mmap size limit (the default setting for +** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. +** ^The default setting can be overridden by each database connection using +** either the [PRAGMA mmap_size] command, or by using the +** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size +** cannot be changed at run-time. Nor may the maximum allowed mmap size +** exceed the compile-time maximum mmap size set by the +** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ +** ^If either argument to this option is negative, then that argument is +** changed to its compile-time default. +**
+*/ +#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ +#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ +#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ +#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ +#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ +#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ +#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ +#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ +#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ +#define SQLITE_CONFIG_PCACHE 14 /* no-op */ +#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ +#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ +#define SQLITE_CONFIG_URI 17 /* int */ +#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ +#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ +#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ + +/* +** CAPI3REF: Database Connection Configuration Options +** +** These constants are the available integer configuration options that +** can be passed as the second argument to the [sqlite3_db_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_db_config()] to make sure that +** the call worked. ^The [sqlite3_db_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+**
SQLITE_DBCONFIG_LOOKASIDE
+**
^This option takes three additional arguments that determine the +** [lookaside memory allocator] configuration for the [database connection]. +** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** pointer to a memory buffer to use for lookaside memory. +** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb +** may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the +** size of each lookaside buffer slot. ^The third argument is the number of +** slots. The size of the buffer in the first argument must be greater than +** or equal to the product of the second and third arguments. The buffer +** must be aligned to an 8-byte boundary. ^If the second argument to +** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally +** rounded down to the next smaller multiple of 8. ^(The lookaside memory +** configuration for a database connection can only be changed when that +** connection is not currently using lookaside memory, or in other words +** when the "current value" returned by +** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. +** Any attempt to change the lookaside memory configuration when lookaside +** memory is in use leaves the configuration unchanged and returns +** [SQLITE_BUSY].)^
+** +**
SQLITE_DBCONFIG_ENABLE_FKEY
+**
^This option is used to enable or disable the enforcement of +** [foreign key constraints]. There should be two additional arguments. +** The first argument is an integer which is 0 to disable FK enforcement, +** positive to enable FK enforcement or negative to leave FK enforcement +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether FK enforcement is off or on +** following this call. The second parameter may be a NULL pointer, in +** which case the FK enforcement setting is not reported back.
+** +**
SQLITE_DBCONFIG_ENABLE_TRIGGER
+**
^This option is used to enable or disable [CREATE TRIGGER | triggers]. +** There should be two additional arguments. +** The first argument is an integer which is 0 to disable triggers, +** positive to enable triggers or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether triggers are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the trigger setting is not reported back.
+** +**
+*/ +#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ +#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ + + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes +** +** ^The sqlite3_extended_result_codes() routine enables or disables the +** [extended result codes] feature of SQLite. ^The extended result +** codes are disabled by default for historical compatibility. +*/ +SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid +** +** ^Each entry in an SQLite table has a unique 64-bit signed +** integer key called the [ROWID | "rowid"]. ^The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. ^If +** the table has a column of type [INTEGER PRIMARY KEY] then that column +** is another alias for the rowid. +** +** ^This routine returns the [rowid] of the most recent +** successful [INSERT] into the database from the [database connection] +** in the first argument. ^As of SQLite version 3.7.7, this routines +** records the last insert rowid of both ordinary tables and [virtual tables]. +** ^If no successful [INSERT]s +** have ever occurred on that database connection, zero is returned. +** +** ^(If an [INSERT] occurs within a trigger or within a [virtual table] +** method, then this routine will return the [rowid] of the inserted +** row as long as the trigger or virtual table method is running. +** But once the trigger or virtual table method ends, the value returned +** by this routine reverts to what it was before the trigger or virtual +** table method began.)^ +** +** ^An [INSERT] that fails due to a constraint violation is not a +** successful [INSERT] and does not change the value returned by this +** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. ^(When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface.)^ +** +** ^For the purposes of this routine, an [INSERT] is considered to +** be successful even if it is subsequently rolled back. +** +** This function is accessible to SQL statements via the +** [last_insert_rowid() SQL function]. +** +** If a separate thread performs a new [INSERT] on the same +** database connection while the [sqlite3_last_insert_rowid()] +** function is running and thus changes the last insert [rowid], +** then the value returned by [sqlite3_last_insert_rowid()] is +** unpredictable and might not equal either the old or the new +** last insert [rowid]. +*/ +SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified +** +** ^This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the [database connection] specified by the first parameter. +** ^(Only changes that are directly specified by the [INSERT], [UPDATE], +** or [DELETE] statement are counted. Auxiliary changes caused by +** triggers or [foreign key actions] are not counted.)^ Use the +** [sqlite3_total_changes()] function to find the total number of changes +** including changes caused by triggers and foreign key actions. +** +** ^Changes to a view that are simulated by an [INSTEAD OF trigger] +** are not counted. Only real table changes are counted. +** +** ^(A "row change" is a change to a single row of a single table +** caused by an INSERT, DELETE, or UPDATE statement. Rows that +** are changed as side effects of [REPLACE] constraint resolution, +** rollback, ABORT processing, [DROP TABLE], or by any other +** mechanisms do not count as direct row changes.)^ +** +** A "trigger context" is a scope of execution that begins and +** ends with the script of a [CREATE TRIGGER | trigger]. +** Most SQL statements are +** evaluated outside of any trigger. This is the "top level" +** trigger context. If a trigger fires from the top level, a +** new trigger context is entered for the duration of that one +** trigger. Subtriggers create subcontexts for their duration. +** +** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does +** not create a new trigger context. +** +** ^This function returns the number of direct row changes in the +** most recent INSERT, UPDATE, or DELETE statement within the same +** trigger context. +** +** ^Thus, when called from the top level, this function returns the +** number of changes in the most recent INSERT, UPDATE, or DELETE +** that also occurred at the top level. ^(Within the body of a trigger, +** the sqlite3_changes() interface can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** However, the number returned does not include changes +** caused by subtriggers since those have their own context.)^ +** +** See also the [sqlite3_total_changes()] interface, the +** [count_changes pragma], and the [changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified +** +** ^This function returns the number of row changes caused by [INSERT], +** [UPDATE] or [DELETE] statements since the [database connection] was opened. +** ^(The count returned by sqlite3_total_changes() includes all changes +** from all [CREATE TRIGGER | trigger] contexts and changes made by +** [foreign key actions]. However, +** the count does not include changes used to implement [REPLACE] constraints, +** do rollbacks or ABORT processing, or [DROP TABLE] processing. The +** count does not include rows of views that fire an [INSTEAD OF trigger], +** though if the INSTEAD OF trigger makes changes of its own, those changes +** are counted.)^ +** ^The sqlite3_total_changes() function counts the changes as soon as +** the statement that makes them is completed (when the statement handle +** is passed to [sqlite3_reset()] or [sqlite3_finalize()]). +** +** See also the [sqlite3_changes()] interface, the +** [count_changes pragma], and the [total_changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query +** +** ^This function causes any pending database operation to abort and +** return at its earliest opportunity. This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** ^It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. But it +** is not safe to call this routine with a [database connection] that +** is closed or might close before sqlite3_interrupt() returns. +** +** ^If an SQL operation is very nearly finished at the time when +** sqlite3_interrupt() is called, then it might not have an opportunity +** to be interrupted and might continue to completion. +** +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE +** that is inside an explicit transaction, then the entire transaction +** will be rolled back automatically. +** +** ^The sqlite3_interrupt(D) call is in effect until all currently running +** SQL statements on [database connection] D complete. ^Any new SQL statements +** that are started after the sqlite3_interrupt() call and before the +** running statements reaches zero are interrupted as if they had been +** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the running statement count reaches zero are +** not effected by the sqlite3_interrupt(). +** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** SQL statements is a no-op and has no effect on SQL statements +** that are started after the sqlite3_interrupt() call returns. +** +** If the database connection closes while [sqlite3_interrupt()] +** is running then bad things will likely happen. +*/ +SQLITE_API void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete +** +** These routines are useful during command-line input to determine if the +** currently entered text seems to form a complete SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. ^These routines return 1 if the input string +** appears to be a complete SQL statement. ^A statement is judged to be +** complete if it ends with a semicolon token and is not a prefix of a +** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within +** string literals or quoted identifier names or comments are not +** independent tokens (they are part of the token in which they are +** embedded) and thus do not count as a statement terminator. ^Whitespace +** and comments that follow the final semicolon are ignored. +** +** ^These routines return 0 if the statement is incomplete. ^If a +** memory allocation fails, then SQLITE_NOMEM is returned. +** +** ^These routines do not parse the SQL statements thus +** will not detect syntactically incorrect SQL. +** +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked +** automatically by sqlite3_complete16(). If that initialization fails, +** then the return value from sqlite3_complete16() will be non-zero +** regardless of whether or not the input SQL is complete.)^ +** +** The input to [sqlite3_complete()] must be a zero-terminated +** UTF-8 string. +** +** The input to [sqlite3_complete16()] must be a zero-terminated +** UTF-16 string in native byte order. +*/ +SQLITE_API int sqlite3_complete(const char *sql); +SQLITE_API int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors +** +** ^This routine sets a callback function that might be invoked whenever +** an attempt is made to open a database table that another thread +** or process has locked. +** +** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. ^If the busy callback +** is not NULL, then the callback might be invoked with two arguments. +** +** ^The first argument to the busy handler is a copy of the void* pointer which +** is the third argument to sqlite3_busy_handler(). ^The second argument to +** the busy handler callback is the number of times that the busy handler has +** been invoked for this locking event. ^If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** ^If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that it will be invoked +** when there is lock contention. ^If SQLite determines that invoking the busy +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** ^The default busy callback is NULL. +** +** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. ^If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion +** forces an automatic rollback of the changes. See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** ^(There can only be a single busy handler defined for each +** [database connection]. Setting a new busy handler clears any +** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** will also set or clear the busy handler. +** +** The busy callback should not take any actions which modify the +** database connection that invoked the busy handler. Any such actions +** result in undefined behavior. +** +** A busy handler must not close the database connection +** or [prepared statement] that invoked the busy handler. +*/ +SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout +** +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** for a specified amount of time when a table is locked. ^The handler +** will sleep multiple times until at least "ms" milliseconds of sleeping +** have accumulated. ^After at least "ms" milliseconds of sleeping, +** the handler returns 0 which causes [sqlite3_step()] to return +** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** ^Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** ^(There can only be a single busy handler for a particular +** [database connection] any any given moment. If another busy handler +** was defined (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared.)^ +*/ +SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries +** +** This is a legacy interface that is preserved for backwards compatibility. +** Use of this interface is not recommended. +** +** Definition: A result table is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** The table conceptually has a number of rows and columns. But +** these numbers are not part of the result table itself. These +** numbers are obtained separately. Let N be the number of rows +** and M be the number of columns. +** +** A result table is an array of pointers to zero-terminated UTF-8 strings. +** There are (N+1)*M elements in the array. The first M pointers point +** to zero-terminated strings that contain the names of the columns. +** The remaining entries all point to query results. NULL values result +** in NULL pointers. All other values are in their UTF-8 zero-terminated +** string representation as returned by [sqlite3_column_text()]. +** +** A result table might consist of one or more memory allocations. +** It is not safe to pass a result table directly to [sqlite3_free()]. +** A result table should be deallocated using [sqlite3_free_table()]. +** +** ^(As an example of the result table format, suppose a query result +** is as follows: +** +**
+**        Name        | Age
+**        -----------------------
+**        Alice       | 43
+**        Bob         | 28
+**        Cindy       | 21
+** 
+** +** There are two column (M==2) and three rows (N==3). Thus the +** result table has 8 entries. Suppose the result table is stored +** in an array names azResult. Then azResult holds this content: +** +**
+**        azResult[0] = "Name";
+**        azResult[1] = "Age";
+**        azResult[2] = "Alice";
+**        azResult[3] = "43";
+**        azResult[4] = "Bob";
+**        azResult[5] = "28";
+**        azResult[6] = "Cindy";
+**        azResult[7] = "21";
+** 
)^ +** +** ^The sqlite3_get_table() function evaluates one or more +** semicolon-separated SQL statements in the zero-terminated UTF-8 +** string of its 2nd parameter and returns a result table to the +** pointer given in its 3rd parameter. +** +** After the application has finished with the result from sqlite3_get_table(), +** it must pass the result table pointer to sqlite3_free_table() in order to +** release the memory that was malloced. Because of the way the +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling +** function must not try to call [sqlite3_free()] directly. Only +** [sqlite3_free_table()] is able to release the memory properly and safely. +** +** The sqlite3_get_table() interface is implemented as a wrapper around +** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** to any internal data structures of SQLite. It uses only the public +** interface defined here. As a consequence, errors that occur in the +** wrapper layer outside of the internal [sqlite3_exec()] call are not +** reflected in subsequent calls to [sqlite3_errcode()] or +** [sqlite3_errmsg()]. +*/ +SQLITE_API int sqlite3_get_table( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + char ***pazResult, /* Results of the query */ + int *pnRow, /* Number of result rows written here */ + int *pnColumn, /* Number of result columns written here */ + char **pzErrmsg /* Error msg written here */ +); +SQLITE_API void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions +** +** These routines are work-alikes of the "printf()" family of functions +** from the standard C library. +** +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** The strings returned by these two routines should be +** released by [sqlite3_free()]. ^Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. Note that the order of the +** first two parameters is reversed from snprintf().)^ This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. ^(Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer.)^ We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. ^The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. So the longest string that can be completely +** written will be n-1 characters. +** +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf() formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** ^(The %q option works like %s in that it substitutes a nul-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal.)^ By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, assume the string variable zText contains text as follows: +** +**
+**  char *zText = "It's a happy day!";
+** 
+** +** One can use this text in an SQL statement as follows: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
+**  INSERT INTO table1 VALUES('It''s a happy day!')
+** 
+** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
+**  INSERT INTO table1 VALUES('It's a happy day!');
+** 
+** +** This second example is an SQL syntax error. As a general rule you should +** always use %q instead of %s when inserting text into a string literal. +** +** ^(The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Additionally, if the parameter in the +** argument list is a NULL pointer, %Q substitutes the text "NULL" (without +** single quotes).)^ So, for example, one could say: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** ^(The "%z" formatting option works like "%s" but with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string.)^ +*/ +SQLITE_API char *sqlite3_mprintf(const char*,...); +SQLITE_API char *sqlite3_vmprintf(const char*, va_list); +SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); + +/* +** CAPI3REF: Memory Allocation Subsystem +** +** The SQLite core uses these three routines for all of its own +** internal memory allocation needs. "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** Windows VFS uses native malloc() and free() for some operations. +** +** ^The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** ^If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. ^If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** ^Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. ^The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** +** ^(The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter.)^ ^ If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** ^If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** ^sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** ^If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** ^If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** ^The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary, or to a +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time +** option is used. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be used. +** +** Prior to SQLite version 3.7.10, the Windows OS interface layer called +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular Windows +** installation. Memory allocation errors were detected, but +** they were reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +** +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else pointers obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** not yet been released. +** +** The application must not read or write any part of +** a block of memory after it has been released using +** [sqlite3_free()] or [sqlite3_realloc()]. +*/ +SQLITE_API void *sqlite3_malloc(int); +SQLITE_API void *sqlite3_realloc(void*, int); +SQLITE_API void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** routines, which form the built-in memory allocation subsystem. +** +** ^The [sqlite3_memory_used()] routine returns the number of bytes +** of memory currently outstanding (malloced but not freed). +** ^The [sqlite3_memory_highwater()] routine returns the maximum +** value of [sqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [sqlite3_memory_used()] and +** [sqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [sqlite3_malloc()], +** but not overhead added by the any underlying system library +** routines that [sqlite3_malloc()] may call. +** +** ^The memory high-water mark is reset to the current value of +** [sqlite3_memory_used()] if and only if the parameter to +** [sqlite3_memory_highwater()] is true. ^The value returned +** by [sqlite3_memory_highwater(1)] is the high-water mark +** prior to the reset. +*/ +SQLITE_API sqlite3_int64 sqlite3_memory_used(void); +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Pseudo-Random Number Generator +** +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to +** select random [ROWID | ROWIDs] when inserting new records into a table that +** already uses the largest possible [ROWID]. The PRNG is also used for +** the build-in random() and randomblob() SQL functions. This interface allows +** applications to access the same PRNG for other purposes. +** +** ^A call to this routine stores N bytes of randomness into buffer P. +** +** ^The first time this routine is invoked (either internally or by +** the application) the PRNG is seeded using randomness obtained +** from the xRandomness method of the default [sqlite3_vfs] object. +** ^On all subsequent invocations, the pseudo-randomness is generated +** internally and without recourse to the [sqlite3_vfs] xRandomness +** method. +*/ +SQLITE_API void sqlite3_randomness(int N, void *P); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks +** +** ^This routine registers an authorizer callback with a particular +** [database connection], supplied in the first argument. +** ^The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. ^The authorizer callback should +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. ^If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. ^When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer will fail with an error message explaining that +** access is denied. +** +** ^The first parameter to the authorizer callback is a copy of the third +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** to the callback is an integer [SQLITE_COPY | action code] that specifies +** the particular action to be authorized. ^The third through sixth parameters +** to the callback are zero-terminated strings that contain additional +** details about the action to be authorized. +** +** ^If the action code is [SQLITE_READ] +** and the callback returns [SQLITE_IGNORE] then the +** [prepared statement] statement is constructed to substitute +** a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] +** return can be used to deny an untrusted user access to individual +** columns of a table. +** ^If the action code is [SQLITE_DELETE] and the callback returns +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the +** [truncate optimization] is disabled and all rows are deleted individually. +** +** An authorizer is used when [sqlite3_prepare | preparing] +** SQL statements from an untrusted source, to ensure that the SQL statements +** do not try to access data they are not allowed to see, or that they do not +** try to execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being [sqlite3_prepare | prepared] that +** disallows everything except [SELECT] statements. +** +** Applications that need to process SQL from untrusted sources +** might also consider lowering resource limits using [sqlite3_limit()] +** and limiting database size using the [max_page_count] [PRAGMA] +** in addition to using an authorizer. +** +** ^(Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call.)^ ^Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. +** +** The authorizer callback must not do anything that will modify +** the database connection that invoked the authorizer callback. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [sqlite3_step()] due to a +** schema change. Hence, the application should ensure that the +** correct authorizer callback remains in place during the [sqlite3_step()]. +** +** ^Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [sqlite3_step()], unless +** as stated in the previous paragraph, sqlite3_step() invokes +** sqlite3_prepare_v2() to reprepare a statement after a schema change. +*/ +SQLITE_API int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +** +** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code] +** from the [sqlite3_vtab_on_conflict()] interface. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorize certain SQL statement actions. The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. +** +** These action code values signify what kind of operation is to be +** authorized. The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. ^(The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* Operation NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* NULL Function Name */ +#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** ^The callback function registered by sqlite3_trace() is invoked at +** various times when an SQL statement is being run by [sqlite3_step()]. +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** SQL statement text as the statement first begins executing. +** ^(Additional sqlite3_trace() callbacks might occur +** as each triggered subprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger.)^ +** +** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit +** the length of [bound parameter] expansion in the output of sqlite3_trace(). +** +** ^The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. ^The profile callback contains +** the original statement text and an estimate of wall-clock time +** of how long that statement took to run. ^The profile callback +** time is in units of nanoseconds, however the current implementation +** is only capable of millisecond resolution so the six least significant +** digits in the time are meaningless. Future versions of SQLite +** might provide greater resolution on the profiler callback. The +** sqlite3_profile() function is considered experimental and is +** subject to change in future versions of SQLite. +*/ +SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks +** +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** function X to be invoked periodically during long running calls to +** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for +** database connection D. An example use for this +** interface is to keep a GUI updated during a large query. +** +** ^The parameter P is passed through as the only parameter to the +** callback function X. ^The parameter N is the approximate number of +** [virtual machine instructions] that are evaluated between successive +** invocations of the callback X. ^If N is less than one then the progress +** handler is disabled. +** +** ^Only a single progress handler may be defined at one time per +** [database connection]; setting a new progress handler cancels the +** old one. ^Setting parameter X to NULL disables the progress handler. +** ^The progress handler is also disabled by setting N to a value less +** than 1. +** +** ^If the progress callback returns non-zero, the operation is +** interrupted. This feature can be used to implement a +** "Cancel" button on a GUI progress dialog box. +** +** The progress handler callback must not do anything that will modify +** the database connection that invoked the progress handler. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +*/ +SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection +** +** ^These routines open an SQLite database file as specified by the +** filename argument. ^The filename argument is interpreted as UTF-8 for +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte +** order for sqlite3_open16(). ^(A [database connection] handle is usually +** returned in *ppDb, even if an error occurs. The only exception is that +** if SQLite is unable to allocate memory to hold the [sqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** object.)^ ^(If the database is opened (and/or created) successfully, then +** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error following a failure of any +** of the sqlite3_open() routines. +** +** ^The default encoding for the database will be UTF-8 if +** sqlite3_open() or sqlite3_open_v2() is called and +** UTF-16 in the native byte order if sqlite3_open16() is used. +** +** Whether or not an error occurs when it is opened, resources +** associated with the [database connection] handle should be released by +** passing it to [sqlite3_close()] when it is no longer required. +** +** The sqlite3_open_v2() interface works like sqlite3_open() +** except that it accepts two additional parameters for additional control +** over the new database connection. ^(The flags parameter to +** sqlite3_open_v2() can take one of +** the following three values, optionally combined with the +** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], +** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ +** +**
+** ^(
[SQLITE_OPEN_READONLY]
+**
The database is opened in read-only mode. If the database does not +** already exist, an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE]
+**
The database is opened for reading and writing if possible, or reading +** only if the file is write protected by the operating system. In either +** case the database must already exist, otherwise an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
+**
The database is opened for reading and writing, and is created if +** it does not already exist. This is the behavior that is always used for +** sqlite3_open() and sqlite3_open16().
)^ +**
+** +** If the 3rd parameter to sqlite3_open_v2() is not one of the +** combinations shown above optionally combined with other +** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] +** then the behavior is undefined. +** +** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection +** opens in the multi-thread [threading mode] as long as the single-thread +** mode has not been set at compile-time or start-time. ^If the +** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens +** in the serialized [threading mode] unless single-thread was +** previously selected at compile-time or start-time. +** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be +** eligible to use [shared cache mode], regardless of whether or not shared +** cache is enabled using [sqlite3_enable_shared_cache()]. ^The +** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not +** participate in [shared cache mode] even if it is enabled. +** +** ^The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system interface that +** the new database connection should use. ^If the fourth parameter is +** a NULL pointer then the default [sqlite3_vfs] object is used. +** +** ^If the filename is ":memory:", then a private, temporary in-memory database +** is created for the connection. ^This in-memory database will vanish when +** the database connection is closed. Future versions of SQLite might +** make use of additional special filenames that begin with the ":" character. +** It is recommended that when a database filename actually does begin with +** a ":" character you should prefix the filename with a pathname such as +** "./" to avoid ambiguity. +** +** ^If the filename is an empty string, then a private, temporary +** on-disk database will be created. ^This private database will be +** automatically deleted as soon as the database connection is closed. +** +** [[URI filenames in sqlite3_open()]]

URI Filenames

+** +** ^If [URI filename] interpretation is enabled, and the filename argument +** begins with "file:", then the filename is interpreted as a URI. ^URI +** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is +** set in the fourth argument to sqlite3_open_v2(), or if it has +** been enabled globally using the [SQLITE_CONFIG_URI] option with the +** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. +** As of SQLite version 3.7.7, URI filename interpretation is turned off +** by default, but future releases of SQLite might enable URI filename +** interpretation by default. See "[URI filenames]" for additional +** information. +** +** URI filenames are parsed according to RFC 3986. ^If the URI contains an +** authority, then it must be either an empty string or the string +** "localhost". ^If the authority is not an empty string or "localhost", an +** error is returned to the caller. ^The fragment component of a URI, if +** present, is ignored. +** +** ^SQLite uses the path component of the URI as the name of the disk file +** which contains the database. ^If the path begins with a '/' character, +** then it is interpreted as an absolute path. ^If the path does not begin +** with a '/' (meaning that the authority section is omitted from the URI) +** then the path is interpreted as a relative path. +** ^On windows, the first component of an absolute path +** is a drive specification (e.g. "C:"). +** +** [[core URI query parameters]] +** The query component of a URI may contain parameters that are interpreted +** either by SQLite itself, or by a [VFS | custom VFS implementation]. +** SQLite interprets the following three query parameters: +** +**
    +**
  • vfs: ^The "vfs" parameter may be used to specify the name of +** a VFS object that provides the operating system interface that should +** be used to access the database file on disk. ^If this option is set to +** an empty string the default VFS object is used. ^Specifying an unknown +** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is +** present, then the VFS specified by the option takes precedence over +** the value passed as the fourth parameter to sqlite3_open_v2(). +** +**
  • mode: ^(The mode parameter may be set to either "ro", "rw", +** "rwc", or "memory". Attempting to set it to any other value is +** an error)^. +** ^If "ro" is specified, then the database is opened for read-only +** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the +** third argument to sqlite3_open_v2(). ^If the mode option is set to +** "rw", then the database is opened for read-write (but not create) +** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had +** been set. ^Value "rwc" is equivalent to setting both +** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is +** set to "memory" then a pure [in-memory database] that never reads +** or writes from disk is used. ^It is an error to specify a value for +** the mode parameter that is less restrictive than that specified by +** the flags passed in the third parameter to sqlite3_open_v2(). +** +**
  • cache: ^The cache parameter may be set to either "shared" or +** "private". ^Setting it to "shared" is equivalent to setting the +** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to +** sqlite3_open_v2(). ^Setting the cache parameter to "private" is +** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. +** ^If sqlite3_open_v2() is used and the "cache" parameter is present in +** a URI filename, its value overrides any behavior requested by setting +** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. +**
+** +** ^Specifying an unknown parameter in the query component of a URI is not an +** error. Future versions of SQLite might understand additional query +** parameters. See "[query parameters with special meaning to SQLite]" for +** additional information. +** +** [[URI filename examples]]

URI filename examples

+** +**
+**
URI filenames Results +**
file:data.db +** Open the file "data.db" in the current directory. +**
file:/home/fred/data.db
+** file:///home/fred/data.db
+** file://localhost/home/fred/data.db
+** Open the database file "/home/fred/data.db". +**
file://darkstar/home/fred/data.db +** An error. "darkstar" is not a recognized authority. +**
+** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db +** Windows only: Open the file "data.db" on fred's desktop on drive +** C:. Note that the %20 escaping in this example is not strictly +** necessary - space characters can be used literally +** in URI filenames. +**
file:data.db?mode=ro&cache=private +** Open file "data.db" in the current directory for read-only access. +** Regardless of whether or not shared-cache mode is enabled by +** default, use a private cache. +**
file:/home/fred/data.db?vfs=unix-nolock +** Open file "/home/fred/data.db". Use the special VFS "unix-nolock". +**
file:data.db?mode=readonly +** An error. "readonly" is not a valid option for the "mode" parameter. +**
+** +** ^URI hexadecimal escape sequences (%HH) are supported within the path and +** query components of a URI. A hexadecimal escape sequence consists of a +** percent sign - "%" - followed by exactly two hexadecimal digits +** specifying an octet value. ^Before the path or query components of a +** URI filename are interpreted, they are encoded using UTF-8 and all +** hexadecimal escape sequences replaced by a single byte containing the +** corresponding octet. If this process generates an invalid UTF-8 encoding, +** the results are undefined. +** +** Note to Windows users: The encoding used for the filename argument +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** sqlite3_open() or sqlite3_open_v2(). +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various +** features that require the use of temporary files may fail. +** +** See also: [sqlite3_temp_directory] +*/ +SQLITE_API int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Obtain Values For URI Parameters +** +** These are utility routines, useful to VFS implementations, that check +** to see if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of that query parameter. +** +** If F is the database filename pointer passed into the xOpen() method of +** a VFS implementation when the flags parameter to xOpen() has one or +** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and +** P is the name of the query parameter, then +** sqlite3_uri_parameter(F,P) returns the value of the P +** parameter if it exists or a NULL pointer if P does not appear as a +** query parameter on F. If P is a query parameter of F +** has no explicit value, then sqlite3_uri_parameter(F,P) returns +** a pointer to an empty string. +** +** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean +** parameter and returns true (1) or false (0) according to the value +** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the +** value of query parameter P is one of "yes", "true", or "on" in any +** case or if the value begins with a non-zero number. The +** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of +** query parameter P is one of "no", "false", or "off" in any case or +** if the value begins with a numeric zero. If P is not a query +** parameter on F or if the value of P is does not match any of the +** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). +** +** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a +** 64-bit signed integer and returns that integer, or D if P does not +** exist. If the value of P is something other than an integer, then +** zero is returned. +** +** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and +** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and +** is not a database file pathname pointer that SQLite passed into the xOpen +** VFS method, then the behavior of this routine is undefined and probably +** undesirable. +*/ +SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); +SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); +SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); + + +/* +** CAPI3REF: Error Codes And Messages +** +** ^The sqlite3_errcode() interface returns the numeric [result code] or +** [extended result code] for the most recent failed sqlite3_* API call +** associated with a [database connection]. If a prior API call failed +** but the most recent API call succeeded, the return value from +** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode() +** interface is the same except that it always returns the +** [extended result code] even when extended result codes are +** disabled. +** +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF-8 or UTF-16 respectively. +** ^(Memory to hold the error message string is managed internally. +** The application does not need to worry about freeing the result. +** However, the error string might be overwritten or deallocated by +** subsequent calls to other SQLite interface functions.)^ +** +** ^The sqlite3_errstr() interface returns the English-language text +** that describes the [result code], as UTF-8. +** ^(Memory to hold the error message string is managed internally +** and must not be freed by the application)^. +** +** When the serialized [threading mode] is in use, it might be the +** case that a second error occurs on a separate thread in between +** the time of the first error and the call to these interfaces. +** When that happens, the second error will be reported since these +** interfaces always report the most recent result. To avoid +** this, each thread can obtain exclusive use of the [database connection] D +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** all calls to the interfaces listed here are completed. +** +** If an interface fails with SQLITE_MISUSE, that means the interface +** was invoked incorrectly by the application. In that case, the +** error code and message may or may not be set. +*/ +SQLITE_API int sqlite3_errcode(sqlite3 *db); +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); +SQLITE_API const char *sqlite3_errmsg(sqlite3*); +SQLITE_API const void *sqlite3_errmsg16(sqlite3*); +SQLITE_API const char *sqlite3_errstr(int); + +/* +** CAPI3REF: SQL Statement Object +** KEYWORDS: {prepared statement} {prepared statements} +** +** An instance of this object represents a single SQL statement. +** This object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
    +**
  1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
  2. Bind values to [host parameters] using the sqlite3_bind_*() +** interfaces. +**
  3. Run the SQL by calling [sqlite3_step()] one or more times. +**
  4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
  5. Destroy the object using [sqlite3_finalize()]. +**
+** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Run-time Limits +** +** ^(This interface allows the size of various constructs to be limited +** on a connection by connection basis. The first parameter is the +** [database connection] whose limit is to be set or queried. The +** second parameter is one of the [limit categories] that define a +** class of constructs to be size limited. The third parameter is the +** new limit for that construct.)^ +** +** ^If the new limit is a negative number, the limit is unchanged. +** ^(For each limit category SQLITE_LIMIT_NAME there is a +** [limits | hard upper bound] +** set at compile-time by a C preprocessor macro called +** [limits | SQLITE_MAX_NAME]. +** (The "_LIMIT_" in the name is changed to "_MAX_".))^ +** ^Attempts to increase a limit above its hard upper bound are +** silently truncated to the hard upper bound. +** +** ^Regardless of whether or not the limit was changed, the +** [sqlite3_limit()] interface returns the prior value of the limit. +** ^Hence, to find the current value of a limit without changing it, +** simply invoke this interface with the third parameter set to -1. +** +** Run-time limits are intended for use in applications that manage +** both their own internal database and also databases that are controlled +** by untrusted external sources. An example application might be a +** web browser that has its own databases for storing history and +** separate databases controlled by JavaScript applications downloaded +** off the Internet. The internal databases can be given the +** large, default limits. Databases managed by external sources can +** be given much smaller limits designed to prevent a denial of service +** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** interface to further control untrusted SQL. The size of the database +** created by an untrusted script can be contained using the +** [max_page_count] [PRAGMA]. +** +** New run-time limit categories may be added in future releases. +*/ +SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); + +/* +** CAPI3REF: Run-Time Limit Categories +** KEYWORDS: {limit category} {*limit categories} +** +** These constants define various performance limits +** that can be lowered at run-time using [sqlite3_limit()]. +** The synopsis of the meanings of the various limits is shown below. +** Additional information is available at [limits | Limits in SQLite]. +** +**
+** [[SQLITE_LIMIT_LENGTH]] ^(
SQLITE_LIMIT_LENGTH
+**
The maximum size of any string or BLOB or table row, in bytes.
)^ +** +** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
SQLITE_LIMIT_SQL_LENGTH
+**
The maximum length of an SQL statement, in bytes.
)^ +** +** [[SQLITE_LIMIT_COLUMN]] ^(
SQLITE_LIMIT_COLUMN
+**
The maximum number of columns in a table definition or in the +** result set of a [SELECT] or the maximum number of columns in an index +** or in an ORDER BY or GROUP BY clause.
)^ +** +** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
SQLITE_LIMIT_EXPR_DEPTH
+**
The maximum depth of the parse tree on any expression.
)^ +** +** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
SQLITE_LIMIT_COMPOUND_SELECT
+**
The maximum number of terms in a compound SELECT statement.
)^ +** +** [[SQLITE_LIMIT_VDBE_OP]] ^(
SQLITE_LIMIT_VDBE_OP
+**
The maximum number of instructions in a virtual machine program +** used to implement an SQL statement. This limit is not currently +** enforced, though that might be added in some future release of +** SQLite.
)^ +** +** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
SQLITE_LIMIT_FUNCTION_ARG
+**
The maximum number of arguments on a function.
)^ +** +** [[SQLITE_LIMIT_ATTACHED]] ^(
SQLITE_LIMIT_ATTACHED
+**
The maximum number of [ATTACH | attached databases].)^
+** +** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] +** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
+**
The maximum length of the pattern argument to the [LIKE] or +** [GLOB] operators.
)^ +** +** [[SQLITE_LIMIT_VARIABLE_NUMBER]] +** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
+**
The maximum index number of any [parameter] in an SQL statement.)^ +** +** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
SQLITE_LIMIT_TRIGGER_DEPTH
+**
The maximum depth of recursion for triggers.
)^ +**
+*/ +#define SQLITE_LIMIT_LENGTH 0 +#define SQLITE_LIMIT_SQL_LENGTH 1 +#define SQLITE_LIMIT_COLUMN 2 +#define SQLITE_LIMIT_EXPR_DEPTH 3 +#define SQLITE_LIMIT_COMPOUND_SELECT 4 +#define SQLITE_LIMIT_VDBE_OP 5 +#define SQLITE_LIMIT_FUNCTION_ARG 6 +#define SQLITE_LIMIT_ATTACHED 7 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 +#define SQLITE_LIMIT_VARIABLE_NUMBER 9 +#define SQLITE_LIMIT_TRIGGER_DEPTH 10 + +/* +** CAPI3REF: Compiling An SQL Statement +** KEYWORDS: {SQL statement compiler} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** The first argument, "db", is a [database connection] obtained from a +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or +** [sqlite3_open16()]. The database connection must not have been closed. +** +** The second argument, "zSql", is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. +** +** ^If the nByte argument is less than zero, then zSql is read up to the +** first zero terminator. ^If nByte is non-negative, then it is the maximum +** number of bytes read from zSql. ^When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** the nByte-th byte, whichever comes first. If the caller knows +** that the supplied string is nul-terminated, then there is a small +** performance advantage to be gained by passing an nByte parameter that +** is equal to the number of bytes in the input string including +** the nul-terminator bytes as this saves SQLite from having to +** make a copy of the input string. +** +** ^If pzTail is not NULL then *pzTail is made to point to the first byte +** past the end of the first SQL statement in zSql. These routines only +** compile the first statement in zSql, so *pzTail is left pointing to +** what remains uncompiled. +** +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be +** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** to NULL. ^If the input text contains no SQL (if the input is an empty +** string or a comment) then *ppStmt is set to NULL. +** The calling procedure is responsible for deleting the compiled +** SQL statement using [sqlite3_finalize()] after it has finished with it. +** ppStmt may not be NULL. +** +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** otherwise an [error code] is returned. +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** ^In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [sqlite3_step()] interface to +** behave differently in three ways: +** +**
    +**
  1. +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] +** retries will occur before sqlite3_step() gives up and returns an error. +**
  2. +** +**
  3. +** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** [error codes] or [extended error codes]. ^The legacy behavior was that +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [sqlite3_reset()] +** in order to find the underlying cause of the problem. With the "v2" prepare +** interfaces, the underlying reason for the error is returned immediately. +**
  4. +** +**
  5. +** ^If the specific value bound to [parameter | host parameter] in the +** WHERE clause might influence the choice of query plan for a statement, +** then the statement will be automatically recompiled, as if there had been +** a schema change, on the first [sqlite3_step()] call following any change +** to the [sqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of WHERE-clause [parameter] might influence the +** choice of query plan if the parameter is the left-hand side of a [LIKE] +** or [GLOB] operator or if the parameter is compared to an indexed column +** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. +** the +**
  6. +**
+*/ +SQLITE_API int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPI3REF: Retrieving Statement SQL +** +** ^This interface can be used to retrieve a saved copy of the original +** SQL text used to create a [prepared statement] if that statement was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. +*/ +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If An SQL Statement Writes The Database +** +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** and only if the [prepared statement] X makes no direct changes to +** the content of the database file. +** +** Note that [application-defined SQL functions] or +** [virtual tables] might change the database indirectly as a side effect. +** ^(For example, if an application defines a function "eval()" that +** calls [sqlite3_exec()], then the following SQL statement would +** change the database file through side-effects: +** +**
+**    SELECT eval('DELETE FROM t1') FROM t2;
+** 
+** +** But because the [SELECT] statement does not change the database file +** directly, sqlite3_stmt_readonly() would still return true.)^ +** +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** since the statements themselves do not actually modify the database but +** rather they control the timing of when other statements modify the +** database. ^The [ATTACH] and [DETACH] statements also cause +** sqlite3_stmt_readonly() to return true since, while those statements +** change the configuration of a database connection, they do not make +** changes to the content of the database files on disk. +*/ +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If A Prepared Statement Has Been Reset +** +** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the +** [prepared statement] S has been stepped at least once using +** [sqlite3_step(S)] but has not run to completion and/or has not +** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) +** interface returns false if S is a NULL pointer. If S is not a +** NULL pointer and is not a pointer to a valid [prepared statement] +** object, then the behavior is undefined and probably undesirable. +** +** This interface can be used in combination [sqlite3_next_stmt()] +** to locate all prepared statements associated with a database +** connection that are in need of being reset. This can be used, +** for example, in diagnostic routines to search for prepared +** statements that are holding a transaction open. +*/ +SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); + +/* +** CAPI3REF: Dynamically Typed Value Object +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** +** SQLite uses the sqlite3_value object to represent all values +** that can be stored in a database table. SQLite uses dynamic typing +** for the values it stores. ^Values stored in sqlite3_value objects +** can be integers, floating point values, strings, BLOBs, or NULL. +** +** An sqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected sqlite3_value. Other interfaces +** will accept either a protected or an unprotected sqlite3_value. +** Every interface that accepts sqlite3_value arguments specifies +** whether or not it requires a protected sqlite3_value. +** +** The terms "protected" and "unprotected" refer to whether or not +** a mutex is held. An internal mutex is held for a protected +** sqlite3_value object but no mutex is held for an unprotected +** sqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** or if SQLite is run in one of reduced mutex modes +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] +** then there is no distinction between protected and unprotected +** sqlite3_value objects and they can be used interchangeably. However, +** for maximum code portability it is recommended that applications +** still make the distinction between protected and unprotected +** sqlite3_value objects even when not strictly required. +** +** ^The sqlite3_value objects that are passed as parameters into the +** implementation of [application-defined SQL functions] are protected. +** ^The sqlite3_value object returned by +** [sqlite3_column_value()] is unprotected. +** Unprotected sqlite3_value objects may only be used with +** [sqlite3_result_value()] and [sqlite3_bind_value()]. +** The [sqlite3_value_blob | sqlite3_value_type()] family of +** interfaces require protected sqlite3_value objects. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. ^A pointer to an sqlite3_context object +** is always first parameter to [application-defined SQL functions]. +** The application-defined SQL function implementation will pass this +** pointer through into calls to [sqlite3_result_int | sqlite3_result()], +** [sqlite3_aggregate_context()], [sqlite3_user_data()], +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], +** and/or [sqlite3_set_auxdata()]. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements +** KEYWORDS: {host parameter} {host parameters} {host parameter name} +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** literals may be replaced by a [parameter] that matches one of following +** templates: +** +**
    +**
  • ? +**
  • ?NNN +**
  • :VVV +**
  • @VVV +**
  • $VVV +**
+** +** In the templates above, NNN represents an integer literal, +** and VVV represents an alphanumeric identifier.)^ ^The values of these +** parameters (also called "host parameter names" or "SQL parameters") +** can be set using the sqlite3_bind_*() routines defined here. +** +** ^The first argument to the sqlite3_bind_*() routines is always +** a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. +** +** ^The second argument is the index of the SQL parameter to be set. +** ^The leftmost SQL parameter has an index of 1. ^When the same named +** SQL parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** ^The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_index()] API if desired. ^The index +** for "?NNN" parameters is the value of NNN. +** ^The NNN value must be between 1 and the [sqlite3_limit()] +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). +** +** ^The third argument is the value to bind to the parameter. +** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter +** is ignored and the end result is the same as sqlite3_bind_null(). +** +** ^(In those routines that have a fourth argument, its value is the +** number of bytes in the parameter. To be clear: the value is the +** number of bytes in the value, not the number of characters.)^ +** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** is negative, then the length of the string is +** the number of bytes up to the first zero terminator. +** If the fourth parameter to sqlite3_bind_blob() is negative, then +** the behavior is undefined. +** If a non-negative fourth parameter is provided to sqlite3_bind_text() +** or sqlite3_bind_text16() then that parameter must be the byte offset +** where the NUL terminator would occur assuming the string were NUL +** terminated. If any NUL characters occur at byte offsets less than +** the value of the fourth parameter then the resulting string value will +** contain embedded NULs. The result of expressions involving strings +** with embedded NULs is undefined. +** +** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** string after SQLite has finished with it. ^The destructor is called +** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), +** sqlite3_bind_text(), or sqlite3_bind_text16() fails. +** ^If the fifth argument is +** the special value [SQLITE_STATIC], then SQLite assumes that the +** information is in static, unmanaged space and does not need to be freed. +** ^If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. +** +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeroes. ^A zeroblob uses a fixed amount of memory +** (just an integer to hold its size) while it is being processed. +** Zeroblobs are intended to serve as placeholders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | incremental BLOB I/O] routines. +** ^A negative value for the zeroblob results in a zero-length BLOB. +** +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** for the [prepared statement] or with a prepared statement for which +** [sqlite3_step()] has been called more recently than [sqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** routine is passed a [prepared statement] that has been finalized, the +** result is undefined and probably harmful. +** +** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Unbound parameters are interpreted as NULL. +** +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** [error code] if anything goes wrong. +** ^[SQLITE_RANGE] is returned if the parameter +** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. +** +** See also: [sqlite3_bind_parameter_count()], +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); +SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); +SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of SQL Parameters +** +** ^This routine can be used to find the number of [SQL parameters] +** in a [prepared statement]. SQL parameters are tokens of the +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as +** placeholders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** ^(This routine actually returns the index of the largest (rightmost) +** parameter. For all forms except ?NNN, this will correspond to the +** number of unique parameters. If parameters of the ?NNN form are used, +** there may be gaps in the list.)^ +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_name()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter +** +** ^The sqlite3_bind_parameter_name(P,N) interface returns +** the name of the N-th [SQL parameter] in the [prepared statement] P. +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" +** respectively. +** In other words, the initial ":" or "$" or "@" or "?" +** is included as part of the name.)^ +** ^Parameters of the form "?" without a following integer have no name +** and are referred to as "nameless" or "anonymous parameters". +** +** ^The first host parameter has an index of 1, not 0. +** +** ^If the value N is out of range or if the N-th parameter is +** nameless, then NULL is returned. ^The returned string is +** always in UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name +** +** ^Return the index of an SQL parameter given its name. ^The +** index value returned is suitable for use as the second +** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** is returned if no matching parameter is found. ^The parameter +** name must be given in UTF-8 even if the original statement +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement +** +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset +** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Use this routine to reset all host parameters to NULL. +*/ +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set +** +** ^Return the number of columns in the result set returned by the +** [prepared statement]. ^This routine returns 0 if pStmt is an SQL +** statement that does not return data (for example an [UPDATE]). +** +** See also: [sqlite3_data_count()] +*/ +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set +** +** ^These routines return the name assigned to a particular column +** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF-8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF-16 string. ^The first parameter is the [prepared statement] +** that implements the [SELECT] statement. ^The second parameter is the +** column number. ^The leftmost column is number 0. +** +** ^The returned string pointer is valid until either the [prepared statement] +** is destroyed by [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the next call to +** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** +** ^If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +** +** ^The name of a result column is the value of the "AS" clause for +** that column, if there is an AS clause. If there is no AS clause +** then the name of the column is unspecified and may change from +** one release of SQLite to the next. +*/ +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result +** +** ^These routines provide a means to determine the database, table, and +** table column that is the origin of a particular result column in +** [SELECT] statement. +** ^The name of the database or table or column can be returned as +** either a UTF-8 or UTF-16 string. ^The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. +** ^The returned string is valid until the [prepared statement] is destroyed +** using [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the same information is requested +** again in a different encoding. +** +** ^The names returned are the original un-aliased names of the +** database, table, and column. +** +** ^The first argument to these interfaces is a [prepared statement]. +** ^These functions return information about the Nth result column returned by +** the statement, where N is the second function argument. +** ^The left-most column is column 0 for these routines. +** +** ^If the Nth column returned by the statement is an expression or +** subquery and is not a column value, then all of these functions return +** NULL. ^These routine might also return NULL if a memory allocation error +** occurs. ^Otherwise, they return the name of the attached database, table, +** or column that query result column was extracted from. +** +** ^As with all other SQLite APIs, those whose names end with "16" return +** UTF-16 encoded strings and the other functions return UTF-8. +** +** ^These APIs are only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. +** +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +** +** If two or more threads call one or more +** [sqlite3_column_database_name | column metadata interfaces] +** for the same [prepared statement] and result column +** at the same time then the results are undefined. +*/ +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result +** +** ^(The first parameter is a [prepared statement]. +** If this statement is a [SELECT] statement and the Nth column of the +** returned result set of that [SELECT] is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned.)^ ^If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** ^The returned string is always UTF-8 encoded. +** +** ^(For example, given the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** and the following statement to be compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** this routine would return the string "VARIANT" for the second result +** column (i==1), and a NULL pointer for the first result column (i==0).)^ +** +** ^SQLite uses dynamic run-time typing. ^So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. ^Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement +** +** After a [prepared statement] has been prepared using either +** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** must be called one or more times to evaluate the statement. +** +** The details of the behavior of the sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** ^In the legacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** ^With the "v2" interface, any of the other [result codes] or +** [extended result codes] might be returned as well. +** +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. ^If the statement is a [COMMIT] +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a [COMMIT] and occurs within an +** explicit transaction then you should rollback the transaction before +** continuing. +** +** ^[SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] +** is returned each time a new row of data is ready for processing by the +** caller. The values may be accessed using the [column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** ^With the legacy interface, a more specific error code (for example, +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [prepared statement]. ^In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** For all versions of SQLite up to and including 3.6.23.1, a call to +** [sqlite3_reset()] was required after sqlite3_step() returned anything +** other than [SQLITE_ROW] before any subsequent invocation of +** sqlite3_step(). Failure to reset the prepared statement using +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began +** calling [sqlite3_reset()] automatically in this circumstance rather +** than returning [SQLITE_MISUSE]. This is not considered a compatibility +** break because any application that ever receives an SQLITE_MISUSE error +** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option +** can be used to restore the legacy behavior. +** +** Goofy Interface Alert: In the legacy interface, the sqlite3_step() +** API always returns a generic error code, [SQLITE_ERROR], following any +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** specific [error codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** then the more specific [error codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +SQLITE_API int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set +** +** ^The sqlite3_data_count(P) interface returns the number of columns in the +** current row of the result set of [prepared statement] P. +** ^If prepared statement P does not have results ready to return +** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of +** interfaces) then sqlite3_data_count(P) returns 0. +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** ^The sqlite3_data_count(P) routine returns 0 if the previous call to +** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) +** will return non-zero if previous call to [sqlite3_step](P) returned +** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] +** where it always returns zero since each step of that multi-step +** pragma returns 0 columns of data. +** +** See also: [sqlite3_column_count()] +*/ +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes +** KEYWORDS: SQLITE_TEXT +** +** ^(Every value in SQLite has one of five fundamental datatypes: +** +**
    +**
  • 64-bit signed integer +**
  • 64-bit IEEE floating point number +**
  • string +**
  • BLOB +**
  • NULL +**
)^ +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Result Values From A Query +** KEYWORDS: {column access functions} +** +** These routines form the "result set" interface. +** +** ^These routines return information about a single column of the current +** result row of a query. ^In every case the first argument is a pointer +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] +** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** and the second argument is the index of the column for which information +** should be returned. ^The leftmost column of the result set has the index 0. +** ^The number of columns in the result can be determined using +** [sqlite3_column_count()]. +** +** If the SQL statement does not currently point to a valid row, or if the +** column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** ^The sqlite3_column_type() routine returns the +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. ^The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** the string to UTF-16 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes16() uses +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** +** ^The values returned by [sqlite3_column_bytes()] and +** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** of the string. ^For clarity: the values returned by +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** bytes in the string, not the number of characters. +** +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even empty strings, are always zero-terminated. ^The return +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** ^The object returned by [sqlite3_column_value()] is an +** [unprotected sqlite3_value] object. An unprotected sqlite3_value object +** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. +** If the [unprotected sqlite3_value] object returned by +** [sqlite3_column_value()] is used in any other way, including calls +** to routines like [sqlite3_value_int()], [sqlite3_value_text()], +** or [sqlite3_value_bytes()], then the behavior is undefined. +** +** These routines attempt to convert the value where appropriate. ^For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to perform the +** conversion automatically. ^(The following table details the conversions +** that are applied: +** +**
+** +**
Internal
Type
Requested
Type
Conversion +** +**
NULL INTEGER Result is 0 +**
NULL FLOAT Result is 0.0 +**
NULL TEXT Result is NULL pointer +**
NULL BLOB Result is NULL pointer +**
INTEGER FLOAT Convert from integer to float +**
INTEGER TEXT ASCII rendering of the integer +**
INTEGER BLOB Same as INTEGER->TEXT +**
FLOAT INTEGER Convert from float to integer +**
FLOAT TEXT ASCII rendering of the float +**
FLOAT BLOB Same as FLOAT->TEXT +**
TEXT INTEGER Use atoi() +**
TEXT FLOAT Use atof() +**
TEXT BLOB No change +**
BLOB INTEGER Convert to TEXT then use atoi() +**
BLOB FLOAT Convert to TEXT then use atof() +**
BLOB TEXT Add a zero terminator if needed +**
+**
)^ +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** own equivalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
    +**
  • The initial content is a BLOB and sqlite3_column_text() or +** sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.
  • +**
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.
  • +**
  • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.
  • +**
+** +** ^Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer references will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometimes they +** are not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
    +**
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • +**
+** +** In other words, you should call sqlite3_column_text(), +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result +** into the desired format, then invoke sqlite3_column_bytes() or +** sqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to sqlite3_column_text() or sqlite3_column_blob() with calls to +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() +** with calls to sqlite3_column_bytes(). +** +** ^The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** ^(If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM].)^ +*/ +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object +** +** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^If the most recent evaluation of the statement encountered no errors +** or if the statement is never been evaluated, then sqlite3_finalize() returns +** SQLITE_OK. ^If the most recent evaluation of statement S failed, then +** sqlite3_finalize(S) returns the appropriate [error code] or +** [extended error code]. +** +** ^The sqlite3_finalize(S) routine can be called at any point during +** the life cycle of [prepared statement] S: +** before statement S is ever evaluated, after +** one or more calls to [sqlite3_reset()], or after any call +** to [sqlite3_step()] regardless of whether or not the statement has +** completed execution. +** +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** +** The application must finalize every [prepared statement] in order to avoid +** resource leaks. It is a grievous error for the application to try to use +** a prepared statement after it has been finalized. Any use of a prepared +** statement after it has been finalized can result in undefined and +** undesirable behavior such as segfaults and heap corruption. +*/ +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object +** +** The sqlite3_reset() function is called to reset a [prepared statement] +** object back to its initial state, ready to be re-executed. +** ^Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +** +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** back to the beginning of its program. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], +** or if [sqlite3_step(S)] has never before been called on S, +** then [sqlite3_reset(S)] returns [SQLITE_OK]. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S indicated an error, then +** [sqlite3_reset(S)] returns an appropriate [error code]. +** +** ^The [sqlite3_reset(S)] interface does not change the values +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +*/ +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions +** KEYWORDS: {function creation routines} +** KEYWORDS: {application-defined SQL function} +** KEYWORDS: {application-defined SQL functions} +** +** ^These functions (collectively known as "function creation routines") +** are used to add SQL functions or aggregates or to redefine the behavior +** of existing SQL functions or aggregates. The only differences between +** these routines are the text encoding expected for +** the second parameter (the name of the function being created) +** and the presence or absence of a destructor callback for +** the application data pointer. +** +** ^The first parameter is the [database connection] to which the SQL +** function is to be added. ^If an application uses more than one database +** connection then application-defined SQL functions must be added +** to each database connection separately. +** +** ^The second parameter is the name of the SQL function to be created or +** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 +** representation, exclusive of the zero-terminator. ^Note that the name +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. +** ^Any attempt to create a function with a longer name +** will result in [SQLITE_MISUSE] being returned. +** +** ^The third parameter (nArg) +** is the number of arguments that the SQL function or +** aggregate takes. ^If this parameter is -1, then the SQL function or +** aggregate may take any number of arguments between 0 and the limit +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** parameter is less than -1 or greater than 127 then the behavior is +** undefined. +** +** ^The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Every SQL function implementation must be able to work +** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. ^An application may +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** ^When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what text +** encoding is used, then the fourth argument should be [SQLITE_ANY]. +** +** ^(The fifth parameter is an arbitrary pointer. The implementation of the +** function can gain access to this pointer using [sqlite3_user_data()].)^ +** +** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL function or +** aggregate. ^A scalar SQL function requires an implementation of the xFunc +** callback only; NULL pointers must be passed as the xStep and xFinal +** parameters. ^An aggregate SQL function requires an implementation of xStep +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing +** SQL function or aggregate, pass NULL pointers for all three function +** callbacks. +** +** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, +** then it is destructor for the application data pointer. +** The destructor is invoked when the function is deleted, either by being +** overloaded or when the database connection closes.)^ +** ^The destructor is also invoked if the call to +** sqlite3_create_function_v2() fails. +** ^When the destructor callback of the tenth parameter is invoked, it +** is passed a single argument which is a copy of the application data +** pointer which was the fifth parameter to sqlite3_create_function_v2(). +** +** ^It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing preferred text encodings. ^SQLite will use +** the implementation that most closely matches the way in which the +** SQL function is used. ^A function implementation with a non-negative +** nArg parameter is a better match than a function implementation with +** a negative nArg. ^A function where the preferred text encoding +** matches the database encoding is a better +** match than a function where the encoding is different. +** ^A function where the encoding difference is between UTF16le and UTF16be +** is a closer match than a function where the encoding difference is +** between UTF8 and UTF16. +** +** ^Built-in functions may be overloaded by new application-defined functions. +** +** ^An application-defined function is permitted to call other +** SQLite interfaces. However, such calls must not +** close the database connection nor finalize or reset the prepared +** statement in which the function is running. +*/ +SQLITE_API int sqlite3_create_function( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*) +); + +/* +** CAPI3REF: Text Encodings +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Deprecated Functions +** DEPRECATED +** +** These functions are [deprecated]. In order to maintain +** backwards compatibility with older code, these functions continue +** to be supported. However, new applications should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you what they do. +*/ +#ifndef SQLITE_OMIT_DEPRECATED +SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); +SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); +SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), + void*,sqlite3_int64); +#endif + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 3rd parameter to these callbacks is an array of pointers to +** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work only with [protected sqlite3_value] objects. +** Any attempt to use these routines on an [unprotected sqlite3_value] +** object results in undefined behavior. +** +** ^These routines work just like the corresponding [column access functions] +** except that these routines take a single [protected sqlite3_value] object +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** +** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** in the native byte-order of the host machine. ^The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF-16 strings as big-endian and little-endian respectively. +** +** ^(The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words, if the value is a string that looks like a number) +** then the conversion is performed. Otherwise no conversion occurs. +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ +** +** Please pay particular attention to the fact that the pointer returned +** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the [sqlite3_value*] parameters. +*/ +SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); +SQLITE_API double sqlite3_value_double(sqlite3_value*); +SQLITE_API int sqlite3_value_int(sqlite3_value*); +SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); +SQLITE_API int sqlite3_value_type(sqlite3_value*); +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context +** +** Implementations of aggregate SQL functions use this +** routine to allocate memory for storing their state. +** +** ^The first time the sqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite +** allocates N of memory, zeroes out that memory, and returns a pointer +** to the new memory. ^On second and subsequent calls to +** sqlite3_aggregate_context() for the same aggregate function instance, +** the same buffer is returned. Sqlite3_aggregate_context() is normally +** called once for each invocation of the xStep callback and then one +** last time when the xFinal callback is invoked. ^(When no rows match +** an aggregate query, the xStep() callback of the aggregate function +** implementation is never called and xFinal() is called exactly once. +** In those cases, sqlite3_aggregate_context() might be called for the +** first time from within xFinal().)^ +** +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer +** when first called if N is less than or equal to zero or if a memory +** allocate error occurs. +** +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** determined by the N parameter on first successful call. Changing the +** value of N in subsequent call to sqlite3_aggregate_context() within +** the same aggregate function instance will not resize the memory +** allocation.)^ Within the xFinal callback, it is customary to set +** N=0 in calls to sqlite3_aggregate_context(C,N) so that no +** pointless memory allocations occur. +** +** ^SQLite automatically frees the memory allocated by +** sqlite3_aggregate_context() when the aggregate query concludes. +** +** The first parameter must be a copy of the +** [sqlite3_context | SQL function context] that is the first parameter +** to the xStep or xFinal callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions +** +** ^The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +** +** This routine must be called from the same thread in which +** the application-defined function is running. +*/ +SQLITE_API void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Database Connection For Functions +** +** ^The sqlite3_context_db_handle() interface returns a copy of +** the pointer to the [database connection] (the 1st parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +*/ +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data +** +** These functions may be used by (non-aggregate) SQL functions to +** associate metadata with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated metadata may be preserved. An example +** of where this might be useful is in a regular-expression matching +** function. The compiled version of the regular expression can be stored as +** metadata associated with the pattern string. +** Then as long as the pattern string remains the same, +** the compiled regular expression can be reused on multiple +** invocations of the same function. +** +** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. ^If there is no metadata +** associated with the function argument, this sqlite3_get_auxdata() interface +** returns a NULL pointer. +** +** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th +** argument of the application-defined function. ^Subsequent +** calls to sqlite3_get_auxdata(C,N) return P from the most recent +** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or +** NULL if the metadata has been discarded. +** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, +** SQLite will invoke the destructor function X with parameter P exactly +** once, when the metadata is discarded. +** SQLite is free to discard the metadata at any time, including:
    +**
  • when the corresponding function parameter changes, or +**
  • when [sqlite3_reset()] or [sqlite3_finalize()] is called for the +** SQL statement, or +**
  • when sqlite3_set_auxdata() is invoked again on the same parameter, or +**
  • during the original sqlite3_set_auxdata() call when a memory +** allocation error occurs.
)^ +** +** Note the last bullet in particular. The destructor X in +** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the +** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() +** should be called near the end of the function implementation and the +** function implementation should not make any use of P after +** sqlite3_set_auxdata() has been called. +** +** ^(In practice, metadata is preserved between function calls for +** function parameters that are compile-time constants, including literal +** values and [parameters] and expressions composed from the same.)^ +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); +SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior +** +** These are special values for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. ^The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the [parameter binding] family of +** functions used to bind values to host parameters in prepared statements. +** Refer to the [SQL parameter] documentation for additional information. +** +** ^The sqlite3_result_blob() interface sets the result from +** an application-defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** +** ^The sqlite3_result_zeroblob() interfaces set the result of +** the application-defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** ^The sqlite3_result_double() interface sets the result from +** an application-defined function to be a floating point value specified +** by its 2nd argument. +** +** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** ^SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. ^SQLite interprets the error +** message string from sqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from sqlite3_result_error16() as UTF-16 in native +** byte order. ^If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** ^If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** ^The sqlite3_result_error() and sqlite3_result_error16() +** routines make a private copy of the error message text before +** they return. Hence, the calling function can deallocate or +** modify the text after they return without harm. +** ^The sqlite3_result_error_code() function changes the error code +** returned by SQLite as a result of an error in a function. ^By default, +** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() +** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** +** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an +** error indicating that a string or BLOB is too long to represent. +** +** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an +** error indicating that a memory allocation failed. +** +** ^The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** ^The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** ^The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** ^The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** ^SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. If the 3rd parameter is non-negative, then it +** must be the byte offset into the string where the NUL terminator would +** appear if the string where NUL terminated. If any NUL characters occur +** in the string at a byte offset that is less than the value of the 3rd +** parameter, then the resulting string will contain embedded NULs and the +** result of expressions operating on strings with embedded NULs is undefined. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or BLOB result when it has +** finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces or to +** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** assumes that the text or BLOB result is in constant space and does not +** copy the content of the parameter nor call a destructor on the content +** when it has finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** ^The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the +** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that the [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** ^A [protected sqlite3_value] object may always be used where an +** [unprotected sqlite3_value] object is required, so either +** kind of [sqlite3_value] object can be used with this interface. +** +** If these routines are called from within the different thread +** than the one containing the application-defined function that received +** the [sqlite3_context] pointer, the results are undefined. +*/ +SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_double(sqlite3_context*, double); +SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); +SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); +SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +SQLITE_API void sqlite3_result_null(sqlite3_context*); +SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences +** +** ^These functions add, remove, or modify a [collation] associated +** with the [database connection] specified as the first argument. +** +** ^The name of the collation is a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for sqlite3_create_collation16(). +** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** considered to be the same name. +** +** ^(The third argument (eTextRep) must be one of the constants: +**
    +**
  • [SQLITE_UTF8], +**
  • [SQLITE_UTF16LE], +**
  • [SQLITE_UTF16BE], +**
  • [SQLITE_UTF16], or +**
  • [SQLITE_UTF16_ALIGNED]. +**
)^ +** ^The eTextRep argument determines the encoding of strings passed +** to the collating function callback, xCallback. +** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep +** force strings to be UTF16 with native byte order. +** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin +** on an even byte address. +** +** ^The fourth argument, pArg, is an application data pointer that is passed +** through as the first argument to the collating function callback. +** +** ^The fifth argument, xCallback, is a pointer to the collating function. +** ^Multiple collating functions can be registered using the same name but +** with different eTextRep parameters and SQLite will use whichever +** function requires the least amount of data transformation. +** ^If the xCallback argument is NULL then the collating function is +** deleted. ^When all collating functions having the same name are deleted, +** that collation is no longer usable. +** +** ^The collating function callback is invoked with a copy of the pArg +** application data pointer and with two strings in the encoding specified +** by the eTextRep argument. The collating function must return an +** integer that is negative, zero, or positive +** if the first string is less than, equal to, or greater than the second, +** respectively. A collating function must always return the same answer +** given the same inputs. If two or more collating functions are registered +** to the same collation name (using different eTextRep values) then all +** must give an equivalent answer when invoked with equivalent strings. +** The collating function must obey the following properties for all +** strings A, B, and C: +** +**
    +**
  1. If A==B then B==A. +**
  2. If A==B and B==C then A==C. +**
  3. If A<B THEN B>A. +**
  4. If A<B and B<C then A<C. +**
+** +** If a collating function fails any of the above constraints and that +** collating function is registered and used, then the behavior of SQLite +** is undefined. +** +** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** with the addition that the xDestroy callback is invoked on pArg when +** the collating function is deleted. +** ^Collating functions are deleted when they are overridden by later +** calls to the collation creation functions or when the +** [database connection] is closed using [sqlite3_close()]. +** +** ^The xDestroy callback is not called if the +** sqlite3_create_collation_v2() function fails. Applications that invoke +** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** check the return code and dispose of the application data pointer +** themselves rather than expecting SQLite to deal with it for them. +** This is different from every other SQLite interface. The inconsistency +** is unfortunate but cannot be changed without breaking backwards +** compatibility. +** +** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +*/ +SQLITE_API int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); +SQLITE_API int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +SQLITE_API int sqlite3_create_collation16( + sqlite3*, + const void *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks +** +** ^To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** [database connection] to be invoked whenever an undefined collation +** sequence is required. +** +** ^If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** the names are passed as UTF-16 in machine native byte order. +** ^A call to either function replaces the existing collation-needed callback. +** +** ^(When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). The second argument is the database +** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE], indicating the most desirable form of the collation +** sequence function required. The fourth parameter is the name of the +** required collation sequence.)^ +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +SQLITE_API int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +SQLITE_API int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +#ifdef SQLITE_HAS_CODEC +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); +SQLITE_API int sqlite3_key_v2( + sqlite3 *db, /* Database to be rekeyed */ + const char *zDbName, /* Name of the database */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); +SQLITE_API int sqlite3_rekey_v2( + sqlite3 *db, /* Database to be rekeyed */ + const char *zDbName, /* Name of the database */ + const void *pKey, int nKey /* The new key */ +); + +/* +** Specify the activation key for a SEE database. Unless +** activated, none of the SEE routines will work. +*/ +SQLITE_API void sqlite3_activate_see( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +#ifdef SQLITE_ENABLE_CEROD +/* +** Specify the activation key for a CEROD database. Unless +** activated, none of the CEROD routines will work. +*/ +SQLITE_API void sqlite3_activate_cerod( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +/* +** CAPI3REF: Suspend Execution For A Short Time +** +** The sqlite3_sleep() function causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** ^SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. If the xSleep() method +** of the default VFS is not implemented correctly, or not implemented at +** all, then the behavior of sqlite3_sleep() may deviate from the description +** in the previous paragraphs. +*/ +SQLITE_API int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all temporary files +** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** will be placed in that directory.)^ ^If this variable +** is a NULL pointer, then SQLite performs a search for an appropriate +** temporary file directory. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [temp_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [temp_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [temp_store_directory pragma] should be avoided. +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various +** features that require the use of temporary files may fail. Here is an +** example of how to do this using C++ with the Windows Runtime: +** +**
+** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
+**       TemporaryFolder->Path->Data();
+** char zPathBuf[MAX_PATH + 1];
+** memset(zPathBuf, 0, sizeof(zPathBuf));
+** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
+**       NULL, NULL);
+** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
+** 
+*/ +SQLITE_API char *sqlite3_temp_directory; + +/* +** CAPI3REF: Name Of The Folder Holding Database Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all database files +** specified with a relative pathname and created or accessed by +** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed +** to be relative to that directory.)^ ^If this variable is a NULL +** pointer, then SQLite assumes that all database files specified +** with a relative pathname are relative to the current directory +** for the process. Only the windows VFS makes use of this global +** variable; it is ignored by the unix VFS. +** +** Changing the value of this variable while a database connection is +** open can result in a corrupt database. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [data_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [data_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [data_store_directory pragma] should be avoided. +*/ +SQLITE_API char *sqlite3_data_directory; + +/* +** CAPI3REF: Test For Auto-Commit Mode +** KEYWORDS: {autocommit mode} +** +** ^The sqlite3_get_autocommit() interface returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. ^Autocommit mode is on by default. +** ^Autocommit mode is disabled by a [BEGIN] statement. +** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** +** If certain kinds of errors occur on a statement within a multi-statement +** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. The only way to +** find out whether SQLite automatically rolled back the transaction after +** an error is to use this function. +** +** If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. +*/ +SQLITE_API int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement +** +** ^The sqlite3_db_handle interface returns the [database connection] handle +** to which a [prepared statement] belongs. ^The [database connection] +** returned by sqlite3_db_handle is the same [database connection] +** that was the first argument +** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** create the statement in the first place. +*/ +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + +/* +** CAPI3REF: Return The Filename For A Database Connection +** +** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename +** associated with database N of connection D. ^The main database file +** has the name "main". If there is no attached database N on the database +** connection D, or if database N is a temporary or in-memory database, then +** a NULL pointer is returned. +** +** ^The filename returned by this function is the output of the +** xFullPathname method of the [VFS]. ^In other words, the filename +** will be an absolute pathname, even if the filename used +** to open the database originally was a URI or relative pathname. +*/ +SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Determine if a database is read-only +** +** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N +** of connection D is read-only, 0 if it is read/write, or -1 if N is not +** the name of a database on connection D. +*/ +SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Find the next prepared statement +** +** ^This interface returns a pointer to the next [prepared statement] after +** pStmt associated with the [database connection] pDb. ^If pStmt is NULL +** then this interface returns a pointer to the first prepared statement +** associated with the database connection pDb. ^If no prepared statement +** satisfies the conditions of this routine, it returns NULL. +** +** The [database connection] pointer D in a call to +** [sqlite3_next_stmt(D,S)] must refer to an open database +** connection and in particular must not be a NULL pointer. +*/ +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks +** +** ^The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is [COMMIT | committed]. +** ^Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** ^The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. +** ^Any callback set by a previous call to sqlite3_rollback_hook() +** for the same database connection is overridden. +** ^The pArg argument is passed through to the callback. +** ^If the callback on a commit hook function returns non-zero, +** then the commit is converted into a rollback. +** +** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** return the P argument from the previous call of the same function +** on the same [database connection] D, or NULL for +** the first call for each function on D. +** +** The commit and rollback hook callbacks are not reentrant. +** The callback implementation must not do anything that will modify +** the database connection that invoked the callback. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the commit +** or rollback hook in the first place. +** Note that running any other SQL statements, including SELECT statements, +** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify +** the database connections for the meaning of "modify" in this paragraph. +** +** ^Registering a NULL function disables the callback. +** +** ^When the commit hook callback routine returns zero, the [COMMIT] +** operation is allowed to continue normally. ^If the commit hook +** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. +** ^The rollback hook is invoked on a rollback that results from a commit +** hook returning non-zero, just as it would be with any other rollback. +** +** ^For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** ^The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** +** See also the [sqlite3_update_hook()] interface. +*/ +SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks +** +** ^The sqlite3_update_hook() interface registers a callback function +** with the [database connection] identified by the first argument +** to be invoked whenever a row is updated, inserted or deleted. +** ^Any callback set by a previous call to this function +** for the same database connection is overridden. +** +** ^The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** ^The first argument to the callback is a copy of the third argument +** to sqlite3_update_hook(). +** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], +** or [SQLITE_UPDATE], depending on the operation that caused the callback +** to be invoked. +** ^The third and fourth arguments to the callback contain pointers to the +** database and table name containing the affected row. +** ^The final callback parameter is the [rowid] of the row. +** ^In the case of an update, this is the [rowid] after the update takes place. +** +** ^(The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence).)^ +** +** ^In the current implementation, the update hook +** is not invoked when duplication rows are deleted because of an +** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook +** invoked when rows are deleted using the [truncate optimization]. +** The exceptions defined in this paragraph might change in a future +** release of SQLite. +** +** The update hook implementation must not do anything that will modify +** the database connection that invoked the update hook. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the update hook. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^The sqlite3_update_hook(D,C,P) function +** returns the P argument from the previous call +** on the same [database connection] D, or NULL for +** the first call on D. +** +** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] +** interfaces. +*/ +SQLITE_API void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache +** +** ^(This routine enables or disables the sharing of the database cache +** and schema data structures between [database connection | connections] +** to the same database. Sharing is enabled if the argument is true +** and disabled if the argument is false.)^ +** +** ^Cache sharing is enabled and disabled for an entire process. +** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, +** sharing was enabled or disabled for each thread separately. +** +** ^(The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** Existing database connections continue use the sharing mode +** that was in effect at the time they were opened.)^ +** +** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled +** successfully. An [error code] is returned otherwise.)^ +** +** ^Shared cache is disabled by default. But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +** +** This interface is threadsafe on processors where writing a +** 32-bit integer is atomic. +** +** See Also: [SQLite Shared-Cache Mode] +*/ +SQLITE_API int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory +** +** ^The sqlite3_release_memory() interface attempts to free N bytes +** of heap memory by deallocating non-essential memory allocations +** held by the database library. Memory used to cache database +** pages to improve performance is an example of non-essential memory. +** ^sqlite3_release_memory() returns the number of bytes actually freed, +** which might be more or less than the amount requested. +** ^The sqlite3_release_memory() routine is a no-op returning zero +** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** See also: [sqlite3_db_release_memory()] +*/ +SQLITE_API int sqlite3_release_memory(int); + +/* +** CAPI3REF: Free Memory Used By A Database Connection +** +** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap +** memory as possible from database connection D. Unlike the +** [sqlite3_release_memory()] interface, this interface is effect even +** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is +** omitted. +** +** See also: [sqlite3_release_memory()] +*/ +SQLITE_API int sqlite3_db_release_memory(sqlite3*); + +/* +** CAPI3REF: Impose A Limit On Heap Size +** +** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** soft limit on the amount of heap memory that may be allocated by SQLite. +** ^SQLite strives to keep heap memory utilization below the soft heap +** limit by reducing the number of pages held in the page cache +** as heap memory usages approaches the limit. +** ^The soft heap limit is "soft" because even though SQLite strives to stay +** below the limit, it will exceed the limit rather than generate +** an [SQLITE_NOMEM] error. In other words, the soft heap limit +** is advisory only. +** +** ^The return value from sqlite3_soft_heap_limit64() is the size of +** the soft heap limit prior to the call, or negative in the case of an +** error. ^If the argument N is negative +** then no change is made to the soft heap limit. Hence, the current +** size of the soft heap limit can be determined by invoking +** sqlite3_soft_heap_limit64() with a negative argument. +** +** ^If the argument N is zero then the soft heap limit is disabled. +** +** ^(The soft heap limit is not enforced in the current implementation +** if one or more of following conditions are true: +** +**
    +**
  • The soft heap limit is set to zero. +**
  • Memory accounting is disabled using a combination of the +** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. +**
  • An alternative page cache implementation is specified using +** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). +**
  • The page cache allocates from its own memory pool supplied +** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** from the heap. +**
)^ +** +** Beginning with SQLite version 3.7.3, the soft heap limit is enforced +** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] +** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], +** the soft heap limit is enforced on every memory allocation. Without +** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced +** when memory is allocated by the page cache. Testing suggests that because +** the page cache is the predominate memory user in SQLite, most +** applications will achieve adequate soft heap limit enforcement without +** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** The circumstances under which SQLite will enforce the soft heap limit may +** changes in future releases of SQLite. +*/ +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); + +/* +** CAPI3REF: Deprecated Soft Heap Limit Interface +** DEPRECATED +** +** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** interface. This routine is provided for historical compatibility +** only. All new applications should use the +** [sqlite3_soft_heap_limit64()] interface rather than this one. +*/ +SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); + + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table +** +** ^This routine returns metadata about a specific column of a specific +** database table accessible using the [database connection] handle +** passed as the first function argument. +** +** ^The column is identified by the second, third and fourth parameters to +** this function. ^The second parameter is either the name of the database +** (i.e. "main", "temp", or an attached database) containing the specified +** table or NULL. ^If it is NULL, then all attached databases are searched +** for the table using the same algorithm used by the database engine to +** resolve unqualified table references. +** +** ^The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** ^Metadata is returned by writing to the memory locations passed as the 5th +** and subsequent parameters to this function. ^Any of these arguments may be +** NULL, in which case the corresponding element of metadata is omitted. +** +** ^(
+** +**
Parameter Output
Type
Description +** +**
5th const char* Data type +**
6th const char* Name of default collation sequence +**
7th int True if column has a NOT NULL constraint +**
8th int True if column is part of the PRIMARY KEY +**
9th int True if column is [AUTOINCREMENT] +**
+**
)^ +** +** ^The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any SQLite API function. +** +** ^If the specified table is actually a view, an [error code] is returned. +** +** ^If the specified column is "rowid", "oid" or "_rowid_" and an +** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. ^(If there is no +** explicitly declared [INTEGER PRIMARY KEY] column, then the output +** parameters are set as follows: +** +**
+**     data type: "INTEGER"
+**     collation sequence: "BINARY"
+**     not null: 0
+**     primary key: 1
+**     auto increment: 0
+** 
)^ +** +** ^(This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an [error code] is returned and an error message left +** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^ +** +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +*/ +SQLITE_API int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension +** +** ^This interface loads an SQLite extension library from the named file. +** +** ^The sqlite3_load_extension() interface attempts to load an +** [SQLite extension] library contained in the file zFile. If +** the file cannot be loaded directly, attempts are made to load +** with various operating-system specific extensions added. +** So for example, if "samplelib" cannot be loaded, then names like +** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might +** be tried also. +** +** ^The entry point is zProc. +** ^(zProc may be 0, in which case SQLite will try to come up with an +** entry point name on its own. It first tries "sqlite3_extension_init". +** If that does not work, it constructs a name "sqlite3_X_init" where the +** X is consists of the lower-case equivalent of all ASCII alphabetic +** characters in the filename from the last "/" to the first following +** "." and omitting any initial "lib".)^ +** ^The sqlite3_load_extension() interface returns +** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** ^If an error occurs and pzErrMsg is not 0, then the +** [sqlite3_load_extension()] interface shall attempt to +** fill *pzErrMsg with error message text stored in memory +** obtained from [sqlite3_malloc()]. The calling function +** should free this memory by calling [sqlite3_free()]. +** +** ^Extension loading must be enabled using +** [sqlite3_enable_load_extension()] prior to calling this API, +** otherwise an error will be returned. +** +** See also the [load_extension() SQL function]. +*/ +SQLITE_API int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading +** +** ^So as not to open security holes in older applications that are +** unprepared to deal with [extension loading], and as a means of disabling +** [extension loading] while evaluating user-entered SQL, the following API +** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** +** ^Extension loading is off by default. +** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** to turn extension loading on and call it with onoff==0 to turn +** it back off again. +*/ +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Automatically Load Statically Linked Extensions +** +** ^This interface causes the xEntryPoint() function to be invoked for +** each new [database connection] that is created. The idea here is that +** xEntryPoint() is the entry point for a statically linked [SQLite extension] +** that is to be automatically loaded into all new database connections. +** +** ^(Even though the function prototype shows that xEntryPoint() takes +** no arguments and returns void, SQLite invokes xEntryPoint() with three +** arguments and expects and integer result as if the signature of the +** entry point where as follows: +** +**
+**    int xEntryPoint(
+**      sqlite3 *db,
+**      const char **pzErrMsg,
+**      const struct sqlite3_api_routines *pThunk
+**    );
+** 
)^ +** +** If the xEntryPoint routine encounters an error, it should make *pzErrMsg +** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg +** is NULL before calling the xEntryPoint(). ^SQLite will invoke +** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], +** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** +** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** on the list of automatic extensions is a harmless no-op. ^No entry point +** will be called more than once for each database connection that is opened. +** +** See also: [sqlite3_reset_auto_extension()] +** and [sqlite3_cancel_auto_extension()] +*/ +SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Cancel Automatic Extension Loading +** +** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the +** initialization routine X that was registered using a prior call to +** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] +** routine returns 1 if initialization routine X was successfully +** unregistered and it returns 0 if X was not on the list of initialization +** routines. +*/ +SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Reset Automatic Extension Loading +** +** ^This interface disables all automatic extensions previously +** registered using [sqlite3_auto_extension()]. +*/ +SQLITE_API void sqlite3_reset_auto_extension(void); + +/* +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** CAPI3REF: Virtual Table Object +** KEYWORDS: sqlite3_module {virtual table module} +** +** This structure, sometimes called a "virtual table module", +** defines the implementation of a [virtual tables]. +** This structure consists mostly of methods for the module. +** +** ^A virtual table module is created by filling in a persistent +** instance of this structure and passing a pointer to that instance +** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** ^The registration remains valid until it is replaced by a different +** module or until the [database connection] closes. The content +** of this structure must not change while it is registered with +** any database connection. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + /* The methods above are in version 1 of the sqlite_module object. Those + ** below are for version 2 and greater. */ + int (*xSavepoint)(sqlite3_vtab *pVTab, int); + int (*xRelease)(sqlite3_vtab *pVTab, int); + int (*xRollbackTo)(sqlite3_vtab *pVTab, int); +}; + +/* +** CAPI3REF: Virtual Table Indexing Information +** KEYWORDS: sqlite3_index_info +** +** The sqlite3_index_info structure and its substructures is used as part +** of the [virtual table] interface to +** pass information into and receive the reply from the [xBestIndex] +** method of a [virtual table module]. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** ^(The aConstraint[] array records WHERE clause constraints of the form: +** +**
column OP expr
+** +** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is +** stored in aConstraint[].op using one of the +** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ +** ^(The index of the column is stored in +** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot.)^ +** +** ^The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** ^The aConstraint[] array only reports WHERE clause terms that are +** relevant to the particular virtual table being queried. +** +** ^Information about the ORDER BY clause is stored in aOrderBy[]. +** ^Each term of aOrderBy records a column of the ORDER BY clause. +** +** The [xBestIndex] method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. ^If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite.)^ +** +** ^The idxNum and idxPtr values are recorded and passed into the +** [xFilter] method. +** ^[sqlite3_free()] is used to free idxPtr if and only if +** needToFreeIdxPtr is true. +** +** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** ^The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; + +/* +** CAPI3REF: Virtual Table Constraint Operator Codes +** +** These macros defined the allowed values for the +** [sqlite3_index_info].aConstraint[].op field. Each value represents +** an operator that is part of a constraint term in the wHERE clause of +** a query that uses a [virtual table]. +*/ +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** CAPI3REF: Register A Virtual Table Implementation +** +** ^These routines are used to register a new [virtual table module] name. +** ^Module names must be registered before +** creating a new [virtual table] using the module and before using a +** preexisting [virtual table] for the module. +** +** ^The module name is registered on the [database connection] specified +** by the first parameter. ^The name of the module is given by the +** second parameter. ^The third parameter is a pointer to +** the implementation of the [virtual table module]. ^The fourth +** parameter is an arbitrary client data pointer that is passed through +** into the [xCreate] and [xConnect] methods of the virtual table module +** when a new virtual table is be being created or reinitialized. +** +** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** is a pointer to a destructor for the pClientData. ^SQLite will +** invoke the destructor function (if it is not NULL) when SQLite +** no longer needs the pClientData pointer. ^The destructor will also +** be invoked if the call to sqlite3_create_module_v2() fails. +** ^The sqlite3_create_module() +** interface is equivalent to sqlite3_create_module_v2() with a NULL +** destructor. +*/ +SQLITE_API int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData /* Client data for xCreate/xConnect */ +); +SQLITE_API int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** CAPI3REF: Virtual Table Instance Object +** KEYWORDS: sqlite3_vtab +** +** Every [virtual table module] implementation uses a subclass +** of this object to describe a particular instance +** of the [virtual table]. Each subclass will +** be tailored to the specific needs of the module implementation. +** The purpose of this superclass is to define certain fields that are +** common to all module implementations. +** +** ^Virtual tables methods can set an error message by assigning a +** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [sqlite3_free()] +** prior to assigning a new string to zErrMsg. ^After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* NO LONGER USED */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Virtual Table Cursor Object +** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** +** Every [virtual table module] implementation uses a subclass of the +** following structure to describe cursors that point into the +** [virtual table] and are used +** to loop through the virtual table. Cursors are created using the +** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods +** of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Declare The Schema Of A Virtual Table +** +** ^The [xCreate] and [xConnect] methods of a +** [virtual table module] call this interface +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); + +/* +** CAPI3REF: Overload A Function For A Virtual Table +** +** ^(Virtual tables can provide alternative implementations of functions +** using the [xFindFunction] method of the [virtual table module]. +** But global versions of those functions +** must exist in order to be overloaded.)^ +** +** ^(This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created.)^ ^The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a placeholder function that can be overloaded +** by a [virtual table]. +*/ +SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB +** KEYWORDS: {BLOB handle} {BLOB handles} +** +** An instance of this object represents an open BLOB on which +** [sqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [sqlite3_blob_open()] +** and destroyed by [sqlite3_blob_close()]. +** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the BLOB. +** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O +** +** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located +** in row iRow, column zColumn, table zTable in database zDb; +** in other words, the same BLOB that would be selected by: +** +**
+**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
+** 
)^ +** +** ^If the flags parameter is non-zero, then the BLOB is opened for read +** and write access. ^If it is zero, the BLOB is opened for read access. +** ^It is not possible to open a column that is part of an index or primary +** key for writing. ^If [foreign key constraints] are enabled, it is +** not possible to open a column that is part of a [child key] for writing. +** +** ^Note that the database name is not the filename that contains +** the database but rather the symbolic name of the database that +** appears after the AS keyword when the database is connected using [ATTACH]. +** ^For the main database file, the database name is "main". +** ^For TEMP tables, the database name is "temp". +** +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written +** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set +** to be a null pointer.)^ +** ^This function sets the [database connection] error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related +** functions. ^Note that the *ppBlob variable is always initialized in a +** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob +** regardless of the success or failure of this routine. +** +** ^(If the row that a BLOB handle points to is modified by an +** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects +** then the BLOB handle is marked as "expired". +** This is true if any column of the row is changed, even a column +** other than the one the BLOB handle is open on.)^ +** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. +** ^(Changes written into a BLOB prior to the BLOB expiring are not +** rolled back by the expiration of the BLOB. Such changes will eventually +** commit if the transaction continues to completion.)^ +** +** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** the opened blob. ^The size of a blob may not be changed by this +** interface. Use the [UPDATE] SQL command to change the size of a +** blob. +** +** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** and the built-in [zeroblob] SQL function can be used, if desired, +** to create an empty, zero-filled blob in which to read or write using +** this interface. +** +** To avoid a resource leak, every open [BLOB handle] should eventually +** be released by a call to [sqlite3_blob_close()]. +*/ +SQLITE_API int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Move a BLOB Handle to a New Row +** +** ^This function is used to move an existing blob handle so that it points +** to a different row of the same database table. ^The new row is identified +** by the rowid value passed as the second argument. Only the row can be +** changed. ^The database, table and column on which the blob handle is open +** remain the same. Moving an existing blob handle to a new row can be +** faster than closing the existing handle and opening a new one. +** +** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** it must exist and there must be either a blob or text value stored in +** the nominated column.)^ ^If the new row is not present in the table, or if +** it does not contain a blob or text value, or if another error occurs, an +** SQLite error code is returned and the blob handle is considered aborted. +** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or +** [sqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** always returns zero. +** +** ^This function sets the database handle error code and message. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); + +/* +** CAPI3REF: Close A BLOB Handle +** +** ^Closes an open [BLOB handle]. +** +** ^Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in [autocommit mode]. +** ^If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. +** +** ^(Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. Any errors that occur during +** closing are reported as a non-zero return value.)^ +** +** ^(The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed.)^ +** +** ^Calling this routine with a null pointer (such as would be returned +** by a failed call to [sqlite3_blob_open()]) is a harmless no-op. +*/ +SQLITE_API int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB +** +** ^Returns the size in bytes of the BLOB accessible via the +** successfully opened [BLOB handle] in its only argument. ^The +** incremental blob I/O routines can only read or overwriting existing +** blob content; they cannot change the size of a blob. +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +*/ +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally +** +** ^(This function is used to read data from an open [BLOB handle] into a +** caller-supplied buffer. N bytes of data are copied into buffer Z +** from the open BLOB, starting at offset iOffset.)^ +** +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is +** less than zero, [SQLITE_ERROR] is returned and no data is read. +** ^The size of the blob (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to read from an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. +** +** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_write()]. +*/ +SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally +** +** ^This function is used to write data into an open [BLOB handle] from a +** caller-supplied buffer. ^N bytes of data are copied from the buffer Z +** into the open BLOB, starting at offset iOffset. +** +** ^If the [BLOB handle] passed as the first argument was not opened for +** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** this function returns [SQLITE_READONLY]. +** +** ^This function may only modify the contents of the BLOB; it is +** not possible to increase the size of a BLOB using this API. +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is written. ^If N is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** The size of the BLOB (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to write to an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred +** before the [BLOB handle] expired are not rolled back by the +** expiration of the handle, though of course those changes might +** have been overwritten by the statement that expired the BLOB handle +** or by other independent statements. +** +** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_read()]. +*/ +SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most SQLite builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^Names are case sensitive. +** ^Names are zero-terminated UTF-8 strings. +** ^If there is no match, a NULL pointer is returned. +** ^If zVfsName is NULL then the default VFS is returned. +** +** ^New VFSes are registered with sqlite3_vfs_register(). +** ^Each new VFS becomes the default VFS if the makeDflt flag is set. +** ^The same VFS can be registered multiple times without injury. +** ^To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. If two different VFSes with the +** same name are registered, the behavior is undefined. If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^(If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary.)^ +*/ +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. ^(The following +** implementations are available in the SQLite core: +** +**
    +**
  • SQLITE_MUTEX_PTHREADS +**
  • SQLITE_MUTEX_W32 +**
  • SQLITE_MUTEX_NOOP +**
)^ +** +** ^The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and +** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix +** and Windows. +** +** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. In this case the +** application must supply a custom mutex implementation using the +** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function +** before calling sqlite3_initialize() or any other public sqlite3_ +** function that calls sqlite3_initialize().)^ +** +** ^The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^If it returns NULL +** that means that a mutex could not be allocated. ^SQLite +** will unwind its stack and return an error. ^(The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_LRU2 +**
)^ +** +** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) +** cause sqlite3_mutex_alloc() to create +** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. ^SQLite will only request a recursive mutex in +** cases where it really needs one. ^If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return +** a pointer to a static preexisting mutex. ^Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. ^But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +** +** ^The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. ^SQLite is careful to deallocate every +** dynamic mutex that it allocates. The dynamic mutexes must not be in +** use when they are deallocated. Attempting to deallocate a static +** mutex results in undefined behavior. ^SQLite never deallocates +** a static mutex. +** +** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. ^If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** upon successful entry. ^(Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter.)^ ^(If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** SQLite will never exhibit +** such behavior in its own use of mutexes.)^ +** +** ^(Some systems (for example, Windows 95) do not support the operation +** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** will always return SQLITE_BUSY. The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^ +** +** ^The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. ^(The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. SQLite will +** never do either.)^ +** +** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or +** sqlite3_mutex_leave() is a NULL pointer, then all three routines +** behave as no-ops. +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Methods Object +** +** An instance of this structure defines the low-level routines +** used to allocate and use mutexes. +** +** Usually, the default mutex implementations provided by SQLite are +** sufficient, however the user has the option of substituting a custom +** implementation for specialized deployments or systems for which SQLite +** does not provide a suitable implementation. In this case, the user +** creates and populates an instance of this structure to pass +** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** Additionally, an instance of this structure can be used as an +** output variable when querying the system for the current mutex +** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. +** +** ^The xMutexInit method defined by this structure is invoked as +** part of system initialization by the sqlite3_initialize() function. +** ^The xMutexInit routine is called by SQLite exactly once for each +** effective call to [sqlite3_initialize()]. +** +** ^The xMutexEnd method defined by this structure is invoked as +** part of system shutdown by the sqlite3_shutdown() function. The +** implementation of this method is expected to release all outstanding +** resources obtained by the mutex methods implementation, especially +** those obtained by the xMutexInit method. ^The xMutexEnd() +** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** +** ^(The remaining seven methods defined by this structure (xMutexAlloc, +** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and +** xMutexNotheld) implement the following interfaces (respectively): +** +**
    +**
  • [sqlite3_mutex_alloc()]
  • +**
  • [sqlite3_mutex_free()]
  • +**
  • [sqlite3_mutex_enter()]
  • +**
  • [sqlite3_mutex_try()]
  • +**
  • [sqlite3_mutex_leave()]
  • +**
  • [sqlite3_mutex_held()]
  • +**
  • [sqlite3_mutex_notheld()]
  • +**
)^ +** +** The only difference is that the public sqlite3_XXX functions enumerated +** above silently ignore any invocations that pass a NULL pointer instead +** of a valid mutex handle. The implementations of the methods defined +** by this structure are not required to handle this case, the results +** of passing a NULL pointer instead of a valid mutex handle are undefined +** (i.e. it is acceptable to provide an implementation that segfaults if +** it is passed a NULL pointer). +** +** The xMutexInit() method must be threadsafe. ^It must be harmless to +** invoke xMutexInit() multiple times within the same process and without +** intervening calls to xMutexEnd(). Second and subsequent calls to +** xMutexInit() must be no-ops. +** +** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory +** allocation for a static mutex. ^However xMutexAlloc() may use SQLite +** memory allocation for a fast or recursive mutex. +** +** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** called, but only if the prior call to xMutexInit returned SQLITE_OK. +** If xMutexInit fails in any way, it is expected to clean up after itself +** prior to returning. +*/ +typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; +struct sqlite3_mutex_methods { + int (*xMutexInit)(void); + int (*xMutexEnd)(void); + sqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(sqlite3_mutex *); + void (*xMutexEnter)(sqlite3_mutex *); + int (*xMutexTry)(sqlite3_mutex *); + void (*xMutexLeave)(sqlite3_mutex *); + int (*xMutexHeld)(sqlite3_mutex *); + int (*xMutexNotheld)(sqlite3_mutex *); +}; + +/* +** CAPI3REF: Mutex Verification Routines +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. ^The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. ^The SQLite core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. ^External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** ^These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. +** +** ^The implementation is not required to provide versions of these +** routines that actually work. If the implementation does not provide working +** versions of these routines, it should at least provide stubs that always +** return true so that one does not get spurious assertion failures. +** +** ^If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. ^The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +#ifndef NDEBUG +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); +#endif + +/* +** CAPI3REF: Mutex Types +** +** The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. +** +** The set of static mutexes may change from one SQLite release to the +** next. Applications that override the built-in mutex logic must be +** prepared to accommodate additional static mutexes. +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ +#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ + +/* +** CAPI3REF: Retrieve the mutex for a database connection +** +** ^This interface returns a pointer the [sqlite3_mutex] object that +** serializes access to the [database connection] given in the argument +** when the [threading mode] is Serialized. +** ^If the [threading mode] is Single-thread or Multi-thread then this +** routine returns a NULL pointer. +*/ +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); + +/* +** CAPI3REF: Low-Level Control Of Database Files +** +** ^The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. ^The +** name of the database is "main" for the main database or "temp" for the +** TEMP database, or the name that appears after the AS keyword for +** databases that are added using the [ATTACH] SQL command. +** ^A NULL pointer can be used in place of "main" to refer to the +** main database file. +** ^The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. ^The return value of the xFileControl +** method becomes the return value of this routine. +** +** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes +** a pointer to the underlying [sqlite3_file] object to be written into +** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER +** case is a short-circuit path which does not actually invoke the +** underlying sqlite3_io_methods.xFileControl method. +** +** ^If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. ^This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. The underlying xFileControl method might +** also return SQLITE_ERROR. There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** CAPI3REF: Testing Interface +** +** ^The sqlite3_test_control() interface is used to read out internal +** state of SQLite and to inject faults into SQLite for testing +** purposes. ^The first parameter is an operation code that determines +** the number, meaning, and operation of all subsequent parameters. +** +** This interface is not for use by applications. It exists solely +** for verifying the correct operation of the SQLite library. Depending +** on how the SQLite library is compiled, this interface might not exist. +** +** The details of the operation codes, their meanings, the parameters +** they take, and what they do are all subject to change without notice. +** Unlike most of the SQLite API, this function is not guaranteed to +** operate consistently from one release to the next. +*/ +SQLITE_API int sqlite3_test_control(int op, ...); + +/* +** CAPI3REF: Testing Interface Operation Codes +** +** These constants are the valid operation code parameters used +** as the first argument to [sqlite3_test_control()]. +** +** These parameters and their meanings are subject to change +** without notice. These values are for testing purposes only. +** Applications should not use any of these parameters or the +** [sqlite3_test_control()] interface. +*/ +#define SQLITE_TESTCTRL_FIRST 5 +#define SQLITE_TESTCTRL_PRNG_SAVE 5 +#define SQLITE_TESTCTRL_PRNG_RESTORE 6 +#define SQLITE_TESTCTRL_PRNG_RESET 7 +#define SQLITE_TESTCTRL_BITVEC_TEST 8 +#define SQLITE_TESTCTRL_FAULT_INSTALL 9 +#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 +#define SQLITE_TESTCTRL_PENDING_BYTE 11 +#define SQLITE_TESTCTRL_ASSERT 12 +#define SQLITE_TESTCTRL_ALWAYS 13 +#define SQLITE_TESTCTRL_RESERVE 14 +#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 +#define SQLITE_TESTCTRL_ISKEYWORD 16 +#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 +#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 +#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 +#define SQLITE_TESTCTRL_LAST 19 + +/* +** CAPI3REF: SQLite Runtime Status +** +** ^This interface is used to retrieve runtime status information +** about the performance of SQLite, and optionally to reset various +** highwater marks. ^The first argument is an integer code for +** the specific parameter to measure. ^(Recognized integer codes +** are of the form [status parameters | SQLITE_STATUS_...].)^ +** ^The current value of the parameter is returned into *pCurrent. +** ^The highest recorded value is returned in *pHighwater. ^If the +** resetFlag is true, then the highest record value is reset after +** *pHighwater is written. ^(Some parameters do not record the highest +** value. For those parameters +** nothing is written into *pHighwater and the resetFlag is ignored.)^ +** ^(Other parameters record only the highwater mark and not the current +** value. For these latter parameters nothing is written into *pCurrent.)^ +** +** ^The sqlite3_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** This routine is threadsafe but is not atomic. This routine can be +** called while other threads are running the same or different SQLite +** interfaces. However the values returned in *pCurrent and +** *pHighwater reflect the status of SQLite at different points in time +** and it is possible that another thread might change the parameter +** in between the times when *pCurrent and *pHighwater are written. +** +** See also: [sqlite3_db_status()] +*/ +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); + + +/* +** CAPI3REF: Status Parameters +** KEYWORDS: {status parameters} +** +** These integer constants designate various run-time status parameters +** that can be returned by [sqlite3_status()]. +** +**
+** [[SQLITE_STATUS_MEMORY_USED]] ^(
SQLITE_STATUS_MEMORY_USED
+**
This parameter is the current amount of memory checked out +** using [sqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [sqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Scratch memory +** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache +** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in +** this parameter. The amount returned is the sum of the allocation +** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ +** +** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
SQLITE_STATUS_MALLOC_SIZE
+**
This parameter records the largest memory allocation request +** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** internal equivalents). Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
+**
This parameter records the number of separate memory allocations +** currently checked out.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
SQLITE_STATUS_PAGECACHE_USED
+**
This parameter returns the number of pages used out of the +** [pagecache memory allocator] that was configured using +** [SQLITE_CONFIG_PAGECACHE]. The +** value returned is in pages, not in bytes.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] +** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
+**
This parameter returns the number of bytes of page cache +** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] +** buffer and where forced to overflow to [sqlite3_malloc()]. The +** returned value includes allocations that overflowed because they +** where too large (they were larger than the "sz" parameter to +** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because +** no space was left in the page cache.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
SQLITE_STATUS_PAGECACHE_SIZE
+**
This parameter records the largest memory allocation request +** handed to [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_SCRATCH_USED]] ^(
SQLITE_STATUS_SCRATCH_USED
+**
This parameter returns the number of allocations used out of the +** [scratch memory allocator] configured using +** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not +** in bytes. Since a single thread may only have one scratch allocation +** outstanding at time, this parameter also reports the number of threads +** using scratch memory at the same time.
)^ +** +** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
+**
This parameter returns the number of bytes of scratch memory +** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] +** buffer and where forced to overflow to [sqlite3_malloc()]. The values +** returned include overflows because the requested allocation was too +** larger (that is, because the requested allocation was larger than the +** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer +** slots were available. +**
)^ +** +** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(
SQLITE_STATUS_SCRATCH_SIZE
+**
This parameter records the largest memory allocation request +** handed to [scratch memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_PARSER_STACK]] ^(
SQLITE_STATUS_PARSER_STACK
+**
This parameter records the deepest parser stack. It is only +** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ +**
+** +** New status parameters may be added from time to time. +*/ +#define SQLITE_STATUS_MEMORY_USED 0 +#define SQLITE_STATUS_PAGECACHE_USED 1 +#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 +#define SQLITE_STATUS_SCRATCH_USED 3 +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 +#define SQLITE_STATUS_MALLOC_SIZE 5 +#define SQLITE_STATUS_PARSER_STACK 6 +#define SQLITE_STATUS_PAGECACHE_SIZE 7 +#define SQLITE_STATUS_SCRATCH_SIZE 8 +#define SQLITE_STATUS_MALLOC_COUNT 9 + +/* +** CAPI3REF: Database Connection Status +** +** ^This interface is used to retrieve runtime status information +** about a single [database connection]. ^The first argument is the +** database connection object to be interrogated. ^The second argument +** is an integer constant, taken from the set of +** [SQLITE_DBSTATUS options], that +** determines the parameter to interrogate. The set of +** [SQLITE_DBSTATUS options] is likely +** to grow in future releases of SQLite. +** +** ^The current value of the requested parameter is written into *pCur +** and the highest instantaneous value is written into *pHiwtr. ^If +** the resetFlg is true, then the highest instantaneous value is +** reset back down to the current value. +** +** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +*/ +SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + +/* +** CAPI3REF: Status Parameters for database connections +** KEYWORDS: {SQLITE_DBSTATUS options} +** +** These constants are the available integer "verbs" that can be passed as +** the second argument to the [sqlite3_db_status()] interface. +** +** New verbs may be added in future releases of SQLite. Existing verbs +** might be discontinued. Applications should check the return code from +** [sqlite3_db_status()] to make sure that the call worked. +** The [sqlite3_db_status()] interface will return a non-zero error code +** if a discontinued or unsupported verb is invoked. +** +**
+** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
+**
This parameter returns the number of lookaside memory slots currently +** checked out.
)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
+**
This parameter returns the number malloc attempts that were +** satisfied using lookaside memory. Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to the amount of +** memory requested being larger than the lookaside slot size. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to all lookaside +** memory already being in use. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used by all pager caches associated with the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** +** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used to store the schema for all databases associated +** with the connection - main, temp, and any [ATTACH]-ed databases.)^ +** ^The full amount of memory used by the schemas is reported, even if the +** schema memory is shared with other database connections due to +** [shared cache mode] being enabled. +** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** +** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
+**
This parameter returns the approximate number of of bytes of heap +** and lookaside memory used by all prepared statements associated with +** the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
SQLITE_DBSTATUS_CACHE_HIT
+**
This parameter returns the number of pager cache hits that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
SQLITE_DBSTATUS_CACHE_MISS
+**
This parameter returns the number of pager cache misses that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
SQLITE_DBSTATUS_CACHE_WRITE
+**
This parameter returns the number of dirty cache entries that have +** been written to disk. Specifically, the number of pages written to the +** wal file in wal mode databases, or the number of pages written to the +** database file in rollback mode databases. Any pages written as part of +** transaction rollback or database recovery operations are not included. +** If an IO or other error occurs while writing a page to disk, the effect +** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The +** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. +**
+** +** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(
SQLITE_DBSTATUS_DEFERRED_FKS
+**
This parameter returns zero for the current value if and only if +** all foreign key constraints (deferred or immediate) have been +** resolved.)^ ^The highwater mark is always 0. +**
+**
+*/ +#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 +#define SQLITE_DBSTATUS_CACHE_USED 1 +#define SQLITE_DBSTATUS_SCHEMA_USED 2 +#define SQLITE_DBSTATUS_STMT_USED 3 +#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 +#define SQLITE_DBSTATUS_CACHE_HIT 7 +#define SQLITE_DBSTATUS_CACHE_MISS 8 +#define SQLITE_DBSTATUS_CACHE_WRITE 9 +#define SQLITE_DBSTATUS_DEFERRED_FKS 10 +#define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */ + + +/* +** CAPI3REF: Prepared Statement Status +** +** ^(Each prepared statement maintains various +** [SQLITE_STMTSTATUS counters] that measure the number +** of times it has performed specific operations.)^ These counters can +** be used to monitor the performance characteristics of the prepared +** statements. For example, if the number of table steps greatly exceeds +** the number of table searches or result rows, that would tend to indicate +** that the prepared statement is using a full table scan rather than +** an index. +** +** ^(This interface is used to retrieve and reset counter values from +** a [prepared statement]. The first argument is the prepared statement +** object to be interrogated. The second argument +** is an integer code for a specific [SQLITE_STMTSTATUS counter] +** to be interrogated.)^ +** ^The current value of the requested counter is returned. +** ^If the resetFlg is true, then the counter is reset to zero after this +** interface call returns. +** +** See also: [sqlite3_status()] and [sqlite3_db_status()]. +*/ +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + +/* +** CAPI3REF: Status Parameters for prepared statements +** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} +** +** These preprocessor macros define integer codes that name counter +** values associated with the [sqlite3_stmt_status()] interface. +** The meanings of the various counters are as follows: +** +**
+** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
SQLITE_STMTSTATUS_FULLSCAN_STEP
+**
^This is the number of times that SQLite has stepped forward in +** a table as part of a full table scan. Large numbers for this counter +** may indicate opportunities for performance improvement through +** careful use of indices.
+** +** [[SQLITE_STMTSTATUS_SORT]]
SQLITE_STMTSTATUS_SORT
+**
^This is the number of sort operations that have occurred. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance through careful use of indices.
+** +** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
+**
^This is the number of rows inserted into transient indices that +** were created automatically in order to help joins run faster. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance by adding permanent indices that do not +** need to be reinitialized each time the statement is run.
+** +** [[SQLITE_STMTSTATUS_VM_STEP]]
SQLITE_STMTSTATUS_VM_STEP
+**
^This is the number of virtual machine operations executed +** by the prepared statement if that number is less than or equal +** to 2147483647. The number of virtual machine operations can be +** used as a proxy for the total work done by the prepared statement. +** If the number of virtual machine operations exceeds 2147483647 +** then the value returned by this statement status code is undefined. +**
+**
+*/ +#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 +#define SQLITE_STMTSTATUS_SORT 2 +#define SQLITE_STMTSTATUS_AUTOINDEX 3 +#define SQLITE_STMTSTATUS_VM_STEP 4 + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache type is opaque. It is implemented by +** the pluggable module. The SQLite core has no knowledge of +** its size or internal structure and never deals with the +** sqlite3_pcache object except by holding and passing pointers +** to the object. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache sqlite3_pcache; + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache_page object represents a single page in the +** page cache. The page cache will allocate instances of this +** object. Various methods of the page cache use pointers to instances +** of this object as parameters or as their return value. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache_page sqlite3_pcache_page; +struct sqlite3_pcache_page { + void *pBuf; /* The content of the page */ + void *pExtra; /* Extra information associated with the page */ +}; + +/* +** CAPI3REF: Application Defined Page Cache. +** KEYWORDS: {page cache} +** +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can +** register an alternative page cache implementation by passing in an +** instance of the sqlite3_pcache_methods2 structure.)^ +** In many applications, most of the heap memory allocated by +** SQLite is used for the page cache. +** By implementing a +** custom page cache using this API, an application can better control +** the amount of memory consumed by SQLite, the way in which +** that memory is allocated and released, and the policies used to +** determine exactly which parts of a database file are cached and for +** how long. +** +** The alternative page cache mechanism is an +** extreme measure that is only needed by the most demanding applications. +** The built-in page cache is recommended for most uses. +** +** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an +** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** the application may discard the parameter after the call to +** [sqlite3_config()] returns.)^ +** +** [[the xInit() page cache method]] +** ^(The xInit() method is called once for each effective +** call to [sqlite3_initialize()])^ +** (usually only once during the lifetime of the process). ^(The xInit() +** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ +** The intent of the xInit() method is to set up global data structures +** required by the custom page cache implementation. +** ^(If the xInit() method is NULL, then the +** built-in default page cache is used instead of the application defined +** page cache.)^ +** +** [[the xShutdown() page cache method]] +** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** It can be used to clean up +** any outstanding resources before process shutdown, if required. +** ^The xShutdown() method may be NULL. +** +** ^SQLite automatically serializes calls to the xInit method, +** so the xInit method need not be threadsafe. ^The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. All other methods must be threadsafe +** in multithreaded applications. +** +** ^SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +** +** [[the xCreate() page cache methods]] +** ^SQLite invokes the xCreate() method to construct a new cache instance. +** SQLite will typically create one cache instance for each open database file, +** though this is not guaranteed. ^The +** first parameter, szPage, is the size in bytes of the pages that must +** be allocated by the cache. ^szPage will always a power of two. ^The +** second parameter szExtra is a number of bytes of extra storage +** associated with each page cache entry. ^The szExtra parameter will +** a number less than 250. SQLite will use the +** extra szExtra bytes on each page to store metadata about the underlying +** database page on disk. The value passed into szExtra depends +** on the SQLite version, the target platform, and how SQLite was compiled. +** ^The third argument to xCreate(), bPurgeable, is true if the cache being +** created will be used to cache database pages of a file stored on disk, or +** false if it is used for an in-memory database. The cache implementation +** does not have to do anything special based with the value of bPurgeable; +** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will +** never invoke xUnpin() except to deliberately delete a page. +** ^In other words, calls to xUnpin() on a cache with bPurgeable set to +** false will always have the "discard" flag set to true. +** ^Hence, a cache created with bPurgeable false will +** never contain any unpinned pages. +** +** [[the xCachesize() page cache method]] +** ^(The xCachesize() method may be called at any time by SQLite to set the +** suggested maximum cache-size (number of pages stored by) the cache +** instance passed as the first argument. This is the value configured using +** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable +** parameter, the implementation is not required to do anything with this +** value; it is advisory only. +** +** [[the xPagecount() page cache methods]] +** The xPagecount() method must return the number of pages currently +** stored in the cache, both pinned and unpinned. +** +** [[the xFetch() page cache methods]] +** The xFetch() method locates a page in the cache and returns a pointer to +** an sqlite3_pcache_page object associated with that page, or a NULL pointer. +** The pBuf element of the returned sqlite3_pcache_page object will be a +** pointer to a buffer of szPage bytes used to store the content of a +** single database page. The pExtra element of sqlite3_pcache_page will be +** a pointer to the szExtra bytes of extra storage that SQLite has requested +** for each entry in the page cache. +** +** The page to be fetched is determined by the key. ^The minimum key value +** is 1. After it has been retrieved using xFetch, the page is considered +** to be "pinned". +** +** If the requested page is already in the page cache, then the page cache +** implementation must return a pointer to the page buffer with its content +** intact. If the requested page is not already in the cache, then the +** cache implementation should use the value of the createFlag +** parameter to help it determined what action to take: +** +** +**
createFlag Behavior when page is not already in cache +**
0 Do not allocate a new page. Return NULL. +**
1 Allocate a new page if it easy and convenient to do so. +** Otherwise return NULL. +**
2 Make every effort to allocate a new page. Only return +** NULL if allocating a new page is effectively impossible. +**
+** +** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite +** will only use a createFlag of 2 after a prior call with a createFlag of 1 +** failed.)^ In between the to xFetch() calls, SQLite may +** attempt to unpin one or more cache pages by spilling the content of +** pinned pages to disk and synching the operating system disk cache. +** +** [[the xUnpin() page cache method]] +** ^xUnpin() is called by SQLite with a pointer to a currently pinned page +** as its second argument. If the third parameter, discard, is non-zero, +** then the page must be evicted from the cache. +** ^If the discard parameter is +** zero, then the page may be discarded or retained at the discretion of +** page cache implementation. ^The page cache implementation +** may choose to evict unpinned pages at any time. +** +** The cache must not perform any reference counting. A single +** call to xUnpin() unpins the page regardless of the number of prior calls +** to xFetch(). +** +** [[the xRekey() page cache methods]] +** The xRekey() method is used to change the key value associated with the +** page passed as the second argument. If the cache +** previously contains an entry associated with newKey, it must be +** discarded. ^Any prior cache entry associated with newKey is guaranteed not +** to be pinned. +** +** When SQLite calls the xTruncate() method, the cache must discard all +** existing cache entries with page numbers (keys) greater than or equal +** to the value of the iLimit parameter passed to xTruncate(). If any +** of these pages are pinned, they are implicitly unpinned, meaning that +** they can be safely discarded. +** +** [[the xDestroy() page cache method]] +** ^The xDestroy() method is used to delete a cache allocated by xCreate(). +** All resources associated with the specified cache should be freed. ^After +** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] +** handle invalid, and will not use it with any other sqlite3_pcache_methods2 +** functions. +** +** [[the xShrink() page cache method]] +** ^SQLite invokes the xShrink() method when it wants the page cache to +** free up as much of heap memory as possible. The page cache implementation +** is not obligated to free any memory, but well-behaved implementations should +** do their best. +*/ +typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; +struct sqlite3_pcache_methods2 { + int iVersion; + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); + void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, + unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); + void (*xShrink)(sqlite3_pcache*); +}; + +/* +** This is the obsolete pcache_methods object that has now been replaced +** by sqlite3_pcache_methods2. This object is not used by SQLite. It is +** retained in the header file for backwards compatibility only. +*/ +typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; +struct sqlite3_pcache_methods { + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, void*, int discard); + void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); +}; + + +/* +** CAPI3REF: Online Backup Object +** +** The sqlite3_backup object records state information about an ongoing +** online backup operation. ^The sqlite3_backup object is created by +** a call to [sqlite3_backup_init()] and is destroyed by a call to +** [sqlite3_backup_finish()]. +** +** See Also: [Using the SQLite Online Backup API] +*/ +typedef struct sqlite3_backup sqlite3_backup; + +/* +** CAPI3REF: Online Backup API. +** +** The backup API copies the content of one database into another. +** It is useful either for creating backups of databases or +** for copying in-memory databases to or from persistent files. +** +** See Also: [Using the SQLite Online Backup API] +** +** ^SQLite holds a write transaction open on the destination database file +** for the duration of the backup operation. +** ^The source database is read-locked only while it is being read; +** it is not locked continuously for the entire backup operation. +** ^Thus, the backup may be performed on a live source database without +** preventing other database connections from +** reading or writing to the source database while the backup is underway. +** +** ^(To perform a backup operation: +**
    +**
  1. sqlite3_backup_init() is called once to initialize the +** backup, +**
  2. sqlite3_backup_step() is called one or more times to transfer +** the data between the two databases, and finally +**
  3. sqlite3_backup_finish() is called to release all resources +** associated with the backup operation. +**
)^ +** There should be exactly one call to sqlite3_backup_finish() for each +** successful call to sqlite3_backup_init(). +** +** [[sqlite3_backup_init()]] sqlite3_backup_init() +** +** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** [database connection] associated with the destination database +** and the database name, respectively. +** ^The database name is "main" for the main database, "temp" for the +** temporary database, or the name specified after the AS keyword in +** an [ATTACH] statement for an attached database. +** ^The S and M arguments passed to +** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** and database name of the source database, respectively. +** ^The source and destination [database connections] (parameters S and D) +** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** an error. +** +** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** returned and an error code and error message are stored in the +** destination [database connection] D. +** ^The error code and message for the failed call to sqlite3_backup_init() +** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or +** [sqlite3_errmsg16()] functions. +** ^A successful call to sqlite3_backup_init() returns a pointer to an +** [sqlite3_backup] object. +** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and +** sqlite3_backup_finish() functions to perform the specified backup +** operation. +** +** [[sqlite3_backup_step()]] sqlite3_backup_step() +** +** ^Function sqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [sqlite3_backup] object B. +** ^If N is negative, all remaining source pages are copied. +** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** are still more pages to be copied, then the function returns [SQLITE_OK]. +** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** from source to destination, then it returns [SQLITE_DONE]. +** ^If an error occurs while running sqlite3_backup_step(B,N), +** then an [error code] is returned. ^As well as [SQLITE_OK] and +** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. +** +** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +**
    +**
  1. the destination database was opened read-only, or +**
  2. the destination database is using write-ahead-log journaling +** and the destination and source page sizes differ, or +**
  3. the destination database is an in-memory database and the +** destination and source page sizes differ. +**
)^ +** +** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then +** the [sqlite3_busy_handler | busy-handler function] +** is invoked (if one is specified). ^If the +** busy-handler returns non-zero before the lock is available, then +** [SQLITE_BUSY] is returned to the caller. ^In this case the call to +** sqlite3_backup_step() can be retried later. ^If the source +** [database connection] +** is being used to write to the source database when sqlite3_backup_step() +** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this +** case the call to sqlite3_backup_step() can be retried later on. ^(If +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or +** [SQLITE_READONLY] is returned, then +** there is no point in retrying the call to sqlite3_backup_step(). These +** errors are considered fatal.)^ The application must accept +** that the backup operation has failed and pass the backup operation handle +** to the sqlite3_backup_finish() to release associated resources. +** +** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** on the destination file. ^The exclusive lock is not released until either +** sqlite3_backup_finish() is called or the backup operation is complete +** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** sqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the sqlite3_backup_step() call. +** ^Because the source database is not locked between calls to +** sqlite3_backup_step(), the source database may be modified mid-way +** through the backup process. ^If the source database is modified by an +** external process or via a database connection other than the one being +** used by the backup operation, then the backup will be automatically +** restarted by the next call to sqlite3_backup_step(). ^If the source +** database is modified by the using the same database connection as is used +** by the backup operation, then the backup database is automatically +** updated at the same time. +** +** [[sqlite3_backup_finish()]] sqlite3_backup_finish() +** +** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** application wishes to abandon the backup operation, the application +** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). +** ^The sqlite3_backup_finish() interfaces releases all +** resources associated with the [sqlite3_backup] object. +** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** active write-transaction on the destination database is rolled back. +** The [sqlite3_backup] object is invalid +** and may not be used following a call to sqlite3_backup_finish(). +** +** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no +** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() completed. +** ^If an out-of-memory condition or IO error occurred during any prior +** sqlite3_backup_step() call on the same [sqlite3_backup] object, then +** sqlite3_backup_finish() returns the corresponding [error code]. +** +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** is not a permanent error and does not affect the return value of +** sqlite3_backup_finish(). +** +** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]] +** sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** +** ^Each call to sqlite3_backup_step() sets two values inside +** the [sqlite3_backup] object: the number of pages still to be backed +** up and the total number of pages in the source database file. +** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces +** retrieve these two values, respectively. +** +** ^The values returned by these functions are only updated by +** sqlite3_backup_step(). ^If the source database is modified during a backup +** operation, then the values are not updated to account for any extra +** pages that need to be updated or the size of the source database file +** changing. +** +** Concurrent Usage of Database Handles +** +** ^The source [database connection] may be used by the application for other +** purposes while a backup operation is underway or being initialized. +** ^If SQLite is compiled and configured to support threadsafe database +** connections, then the source database connection may be used concurrently +** from within other threads. +** +** However, the application must guarantee that the destination +** [database connection] is not passed to any other API (by any thread) after +** sqlite3_backup_init() is called and before the corresponding call to +** sqlite3_backup_finish(). SQLite does not currently check to see +** if the application incorrectly accesses the destination [database connection] +** and so no error code is reported, but the operations may malfunction +** nevertheless. Use of the destination database connection while a +** backup is in progress might also also cause a mutex deadlock. +** +** If running in [shared cache mode], the application must +** guarantee that the shared cache used by the destination database +** is not accessed while the backup is running. In practice this means +** that the application must guarantee that the disk file being +** backed up to is not accessed by any connection within the process, +** not just the specific connection that was passed to sqlite3_backup_init(). +** +** The [sqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to sqlite3_backup_step(). +** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** APIs are not strictly speaking threadsafe. If they are invoked at the +** same time as another thread is invoking sqlite3_backup_step() it is +** possible that they return invalid values. +*/ +SQLITE_API sqlite3_backup *sqlite3_backup_init( + sqlite3 *pDest, /* Destination database handle */ + const char *zDestName, /* Destination database name */ + sqlite3 *pSource, /* Source database handle */ + const char *zSourceName /* Source database name */ +); +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); + +/* +** CAPI3REF: Unlock Notification +** +** ^When running in shared-cache mode, a database operation may fail with +** an [SQLITE_LOCKED] error if the required locks on the shared-cache or +** individual tables within the shared-cache cannot be obtained. See +** [SQLite Shared-Cache Mode] for a description of shared-cache locking. +** ^This API may be used to register a callback that SQLite will invoke +** when the connection currently holding the required lock relinquishes it. +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. +** +** See Also: [Using the SQLite Unlock Notification Feature]. +** +** ^Shared-cache locks are released when a database connection concludes +** its current transaction, either by committing it or rolling it back. +** +** ^When a connection (known as the blocked connection) fails to obtain a +** shared-cache lock and SQLITE_LOCKED is returned to the caller, the +** identity of the database connection (the blocking connection) that +** has locked the required resource is stored internally. ^After an +** application receives an SQLITE_LOCKED error, it may call the +** sqlite3_unlock_notify() method with the blocked connection handle as +** the first argument to register for a callback that will be invoked +** when the blocking connections current transaction is concluded. ^The +** callback is invoked from within the [sqlite3_step] or [sqlite3_close] +** call that concludes the blocking connections transaction. +** +** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** there is a chance that the blocking connection will have already +** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** If this happens, then the specified callback is invoked immediately, +** from within the call to sqlite3_unlock_notify().)^ +** +** ^If the blocked connection is attempting to obtain a write-lock on a +** shared-cache table, and more than one other connection currently holds +** a read-lock on the same table, then SQLite arbitrarily selects one of +** the other connections to use as the blocking connection. +** +** ^(There may be at most one unlock-notify callback registered by a +** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection already has a registered unlock-notify callback, +** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** called with a NULL pointer as its second argument, then any existing +** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback may also be canceled by closing the blocked +** connection using [sqlite3_close()]. +** +** The unlock-notify callback is not reentrant. If an application invokes +** any sqlite3_xxx API functions from within an unlock-notify callback, a +** crash or deadlock may be the result. +** +** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** returns SQLITE_OK. +** +** Callback Invocation Details +** +** When an unlock-notify callback is registered, the application provides a +** single void* pointer that is passed to the callback when it is invoked. +** However, the signature of the callback function allows SQLite to pass +** it an array of void* context pointers. The first argument passed to +** an unlock-notify callback is a pointer to an array of void* pointers, +** and the second is the number of entries in the array. +** +** When a blocking connections transaction is concluded, there may be +** more than one blocked connection that has registered for an unlock-notify +** callback. ^If two or more such blocked connections have specified the +** same callback function, then instead of invoking the callback function +** multiple times, it is invoked once with the set of void* context pointers +** specified by the blocked connections bundled together into an array. +** This gives the application an opportunity to prioritize any actions +** related to the set of unblocked database connections. +** +** Deadlock Detection +** +** Assuming that after registering for an unlock-notify callback a +** database waits for the callback to be issued before taking any further +** action (a reasonable assumption), then using this API may cause the +** application to deadlock. For example, if connection X is waiting for +** connection Y's transaction to be concluded, and similarly connection +** Y is waiting on connection X's transaction, then neither connection +** will proceed and the system may remain deadlocked indefinitely. +** +** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to sqlite3_unlock_notify() would put the +** system in a deadlocked state, then SQLITE_LOCKED is returned and no +** unlock-notify callback is registered. The system is said to be in +** a deadlocked state if connection A has registered for an unlock-notify +** callback on the conclusion of connection B's transaction, and connection +** B has itself registered for an unlock-notify callback when connection +** A's transaction is concluded. ^Indirect deadlock is also detected, so +** the system is also considered to be deadlocked if connection B has +** registered for an unlock-notify callback on the conclusion of connection +** C's transaction, where connection C is waiting on connection A. ^Any +** number of levels of indirection are allowed. +** +** The "DROP TABLE" Exception +** +** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call sqlite3_unlock_notify(). There is however, +** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, +** SQLite checks if there are any currently executing SELECT statements +** that belong to the same connection. If there are, SQLITE_LOCKED is +** returned. In this case there is no "blocking connection", so invoking +** sqlite3_unlock_notify() results in the unlock-notify callback being +** invoked immediately. If the application then re-attempts the "DROP TABLE" +** or "DROP INDEX" query, an infinite loop might be the result. +** +** One way around this problem is to check the extended error code returned +** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in +** the special "DROP TABLE/INDEX" case, the extended error code is just +** SQLITE_LOCKED.)^ +*/ +SQLITE_API int sqlite3_unlock_notify( + sqlite3 *pBlocked, /* Waiting connection */ + void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ + void *pNotifyArg /* Argument to pass to xNotify */ +); + + +/* +** CAPI3REF: String Comparison +** +** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications +** and extensions to compare the contents of two buffers containing UTF-8 +** strings in a case-independent fashion, using the same definition of "case +** independence" that SQLite uses internally when comparing identifiers. +*/ +SQLITE_API int sqlite3_stricmp(const char *, const char *); +SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); + +/* +** CAPI3REF: String Globbing +* +** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches +** the glob pattern P, and it returns non-zero if string X does not match +** the glob pattern P. ^The definition of glob pattern matching used in +** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the +** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case +** sensitive. +** +** Note that this routine returns zero on a match and non-zero if the strings +** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +*/ +SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); + +/* +** CAPI3REF: Error Logging Interface +** +** ^The [sqlite3_log()] interface writes a message into the [error log] +** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^If logging is enabled, the zFormat string and subsequent arguments are +** used with [sqlite3_snprintf()] to generate the final output string. +** +** The sqlite3_log() interface is intended for use by extensions such as +** virtual tables, collating functions, and SQL functions. While there is +** nothing to prevent an application from calling sqlite3_log(), doing so +** is considered bad form. +** +** The zFormat string must not be NULL. +** +** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** will not use dynamically allocated memory. The log message is stored in +** a fixed-length buffer on the stack. If the log message is longer than +** a few hundred characters, it will be truncated to the length of the +** buffer. +*/ +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); + +/* +** CAPI3REF: Write-Ahead Log Commit Hook +** +** ^The [sqlite3_wal_hook()] function is used to register a callback that +** will be invoked each time a database connection commits data to a +** [write-ahead log] (i.e. whenever a transaction is committed in +** [journal_mode | journal_mode=WAL mode]). +** +** ^The callback is invoked by SQLite after the commit has taken place and +** the associated write-lock on the database released, so the implementation +** may read, write or [checkpoint] the database as required. +** +** ^The first parameter passed to the callback function when it is invoked +** is a copy of the third parameter passed to sqlite3_wal_hook() when +** registering the callback. ^The second is a copy of the database handle. +** ^The third parameter is the name of the database that was written to - +** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter +** is the number of pages currently in the write-ahead log file, +** including those that were just committed. +** +** The callback function should normally return [SQLITE_OK]. ^If an error +** code is returned, that error will propagate back up through the +** SQLite code base to cause the statement that provoked the callback +** to report an error, though the commit will have still occurred. If the +** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value +** that does not correspond to any valid SQLite error code, the results +** are undefined. +** +** A single database handle may have at most a single write-ahead log callback +** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** previously registered write-ahead log callback. ^Note that the +** [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will +** those overwrite any prior [sqlite3_wal_hook()] settings. +*/ +SQLITE_API void *sqlite3_wal_hook( + sqlite3*, + int(*)(void *,sqlite3*,const char*,int), + void* +); + +/* +** CAPI3REF: Configure an auto-checkpoint +** +** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [sqlite3_wal_hook()] that causes any database on [database connection] D +** to automatically [checkpoint] +** after committing a transaction if there are N or +** more frames in the [write-ahead log] file. ^Passing zero or +** a negative value as the nFrame parameter disables automatic +** checkpoints entirely. +** +** ^The callback registered by this function replaces any existing callback +** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback +** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** configured by this function. +** +** ^The [wal_autocheckpoint pragma] can be used to invoke this interface +** from SQL. +** +** ^Every new [database connection] defaults to having the auto-checkpoint +** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] +** pages. The use of this interface +** is only necessary if the default setting is found to be suboptimal +** for a particular application. +*/ +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); + +/* +** CAPI3REF: Checkpoint a database +** +** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X +** on [database connection] D to be [checkpointed]. ^If X is NULL or an +** empty string, then a checkpoint is run on all databases of +** connection D. ^If the database connection D is not in +** [WAL | write-ahead log mode] then this interface is a harmless no-op. +** +** ^The [wal_checkpoint pragma] can be used to invoke this interface +** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] can be used to cause this interface to be +** run whenever the WAL reaches a certain size threshold. +** +** See also: [sqlite3_wal_checkpoint_v2()] +*/ +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Checkpoint a database +** +** Run a checkpoint operation on WAL database zDb attached to database +** handle db. The specific operation is determined by the value of the +** eMode parameter: +** +**
+**
SQLITE_CHECKPOINT_PASSIVE
+** Checkpoint as many frames as possible without waiting for any database +** readers or writers to finish. Sync the db file if all frames in the log +** are checkpointed. This mode is the same as calling +** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked. +** +**
SQLITE_CHECKPOINT_FULL
+** This mode blocks (calls the busy-handler callback) until there is no +** database writer and all readers are reading from the most recent database +** snapshot. It then checkpoints all frames in the log file and syncs the +** database file. This call blocks database writers while it is running, +** but not database readers. +** +**
SQLITE_CHECKPOINT_RESTART
+** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after +** checkpointing the log file it blocks (calls the busy-handler callback) +** until all readers are reading from the database file only. This ensures +** that the next client to write to the database file restarts the log file +** from the beginning. This call blocks database writers while it is running, +** but not database readers. +**
+** +** If pnLog is not NULL, then *pnLog is set to the total number of frames in +** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to +** the total number of checkpointed frames (including any that were already +** checkpointed when this function is called). *pnLog and *pnCkpt may be +** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK. +** If no values are available because of an error, they are both set to -1 +** before returning to communicate this to the caller. +** +** All calls obtain an exclusive "checkpoint" lock on the database file. If +** any other process is running a checkpoint operation at the same time, the +** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a +** busy-handler configured, it will not be invoked in this case. +** +** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive +** "writer" lock on the database file. If the writer lock cannot be obtained +** immediately, and a busy-handler is configured, it is invoked and the writer +** lock retried until either the busy-handler returns 0 or the lock is +** successfully obtained. The busy-handler is also invoked while waiting for +** database readers as described above. If the busy-handler returns 0 before +** the writer lock is obtained or while waiting for database readers, the +** checkpoint operation proceeds from that point in the same way as +** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible +** without blocking any further. SQLITE_BUSY is returned in this case. +** +** If parameter zDb is NULL or points to a zero length string, then the +** specified operation is attempted on all WAL databases. In this case the +** values written to output parameters *pnLog and *pnCkpt are undefined. If +** an SQLITE_BUSY error is encountered when processing one or more of the +** attached WAL databases, the operation is still attempted on any remaining +** attached databases and SQLITE_BUSY is returned to the caller. If any other +** error occurs while processing an attached database, processing is abandoned +** and the error code returned to the caller immediately. If no error +** (SQLITE_BUSY or otherwise) is encountered while processing the attached +** databases, SQLITE_OK is returned. +** +** If database zDb is the name of an attached database that is not in WAL +** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If +** zDb is not NULL (or a zero length string) and is not the name of any +** attached database, SQLITE_ERROR is returned to the caller. +*/ +SQLITE_API int sqlite3_wal_checkpoint_v2( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + int *pnLog, /* OUT: Size of WAL log in frames */ + int *pnCkpt /* OUT: Total number of frames checkpointed */ +); + +/* +** CAPI3REF: Checkpoint operation parameters +** +** These constants can be used as the 3rd parameter to +** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()] +** documentation for additional information about the meaning and use of +** each of these values. +*/ +#define SQLITE_CHECKPOINT_PASSIVE 0 +#define SQLITE_CHECKPOINT_FULL 1 +#define SQLITE_CHECKPOINT_RESTART 2 + +/* +** CAPI3REF: Virtual Table Interface Configuration +** +** This function may be called by either the [xConnect] or [xCreate] method +** of a [virtual table] implementation to configure +** various facets of the virtual table interface. +** +** If this interface is invoked outside the context of an xConnect or +** xCreate virtual table method then the behavior is undefined. +** +** At present, there is only one option that may be configured using +** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options +** may be added in the future. +*/ +SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Virtual Table Configuration Options +** +** These macros define the various options to the +** [sqlite3_vtab_config()] interface that [virtual table] implementations +** can use to customize and optimize their behavior. +** +**
+**
SQLITE_VTAB_CONSTRAINT_SUPPORT +**
Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, +** where X is an integer. If X is zero, then the [virtual table] whose +** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not +** support constraints. In this configuration (which is the default) if +** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire +** statement is rolled back as if [ON CONFLICT | OR ABORT] had been +** specified as part of the users SQL statement, regardless of the actual +** ON CONFLICT mode specified. +** +** If X is non-zero, then the virtual table implementation guarantees +** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before +** any modifications to internal or persistent data structures have been made. +** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite +** is able to roll back a statement or database transaction, and abandon +** or continue processing the current SQL statement as appropriate. +** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns +** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode +** had been ABORT. +** +** Virtual table implementations that are required to handle OR REPLACE +** must do so within the [xUpdate] method. If a call to the +** [sqlite3_vtab_on_conflict()] function indicates that the current ON +** CONFLICT policy is REPLACE, the virtual table implementation should +** silently replace the appropriate rows within the xUpdate callback and +** return SQLITE_OK. Or, if this is not possible, it may return +** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT +** constraint handling. +**
+*/ +#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 + +/* +** CAPI3REF: Determine The Virtual Table Conflict Policy +** +** This function may only be called from within a call to the [xUpdate] method +** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The +** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], +** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode +** of the SQL statement that triggered the call to the [xUpdate] method of the +** [virtual table]. +*/ +SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); + +/* +** CAPI3REF: Conflict resolution modes +** +** These constants are returned by [sqlite3_vtab_on_conflict()] to +** inform a [virtual table] implementation what the [ON CONFLICT] mode +** is for the SQL statement being evaluated. +** +** Note that the [SQLITE_IGNORE] constant is also used as a potential +** return value from the [sqlite3_set_authorizer()] callback and that +** [SQLITE_ABORT] is also a [result code]. +*/ +#define SQLITE_ROLLBACK 1 +/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ +#define SQLITE_FAIL 3 +/* #define SQLITE_ABORT 4 // Also an error code */ +#define SQLITE_REPLACE 5 + + + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif /* _SQLITE3_H_ */ + +/* +** 2010 August 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ + +#ifndef _SQLITE3RTREE_H_ +#define _SQLITE3RTREE_H_ + + +#if 0 +extern "C" { +#endif + +typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; + +/* +** Register a geometry callback named zGeom that can be used as part of an +** R-Tree geometry query as follows: +** +** SELECT ... FROM WHERE MATCH $zGeom(... params ...) +*/ +SQLITE_API int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, +#ifdef SQLITE_RTREE_INT_ONLY + int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes), +#else + int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes), +#endif + void *pContext +); + + +/* +** A pointer to a structure of the following type is passed as the first +** argument to callbacks registered using rtree_geometry_callback(). +*/ +struct sqlite3_rtree_geometry { + void *pContext; /* Copy of pContext passed to s_r_g_c() */ + int nParam; /* Size of array aParam[] */ + double *aParam; /* Parameters passed to SQL geom function */ + void *pUser; /* Callback implementation user data */ + void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ +}; + + +#if 0 +} /* end of the 'extern "C"' block */ +#endif + +#endif /* ifndef _SQLITE3RTREE_H_ */ + + +/************** End of sqlite3.h *********************************************/ +/************** Begin file sqliteInt.h ***************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Internal interface definitions for SQLite. +** +*/ +#ifndef _SQLITEINT_H_ +#define _SQLITEINT_H_ + +/* +** These #defines should enable >2GB file support on POSIX if the +** underlying operating system supports it. If the OS lacks +** large file support, or if the OS is windows, these should be no-ops. +** +** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any +** system #includes. Hence, this block of code must be the very first +** code in all source files. +** +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch +** on the compiler command line. This is necessary if you are compiling +** on a recent machine (ex: Red Hat 7.2) but you want your code to work +** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 +** without this option, LFS is enable. But LFS does not exist in the kernel +** in Red Hat 6.0, so the code won't work. Hence, for maximum binary +** portability you should omit LFS. +** +** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. +*/ +#ifndef SQLITE_DISABLE_LFS +# define _LARGE_FILE 1 +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +# define _LARGEFILE_SOURCE 1 +#endif + +/* +** Include the configuration header output by 'configure' if we're using the +** autoconf-based build +*/ +#ifdef _HAVE_SQLITE_CONFIG_H +#include "config.h" +#endif + +/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ +/************** Begin file sqliteLimit.h *************************************/ +/* +** 2007 May 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file defines various limits of what SQLite can process. +*/ + +/* +** The maximum length of a TEXT or BLOB in bytes. This also +** limits the size of a row in a table or index. +** +** The hard limit is the ability of a 32-bit signed integer +** to count the size: 2^31-1 or 2147483647. +*/ +#ifndef SQLITE_MAX_LENGTH +# define SQLITE_MAX_LENGTH 1000000000 +#endif + +/* +** This is the maximum number of +** +** * Columns in a table +** * Columns in an index +** * Columns in a view +** * Terms in the SET clause of an UPDATE statement +** * Terms in the result set of a SELECT statement +** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. +** * Terms in the VALUES clause of an INSERT statement +** +** The hard upper limit here is 32676. Most database people will +** tell you that in a well-normalized database, you usually should +** not have more than a dozen or so columns in any table. And if +** that is the case, there is no point in having more than a few +** dozen values in any of the other situations described above. +*/ +#ifndef SQLITE_MAX_COLUMN +# define SQLITE_MAX_COLUMN 2000 +#endif + +/* +** The maximum length of a single SQL statement in bytes. +** +** It used to be the case that setting this value to zero would +** turn the limit off. That is no longer true. It is not possible +** to turn this limit off. +*/ +#ifndef SQLITE_MAX_SQL_LENGTH +# define SQLITE_MAX_SQL_LENGTH 1000000000 +#endif + +/* +** The maximum depth of an expression tree. This is limited to +** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might +** want to place more severe limits on the complexity of an +** expression. +** +** A value of 0 used to mean that the limit was not enforced. +** But that is no longer true. The limit is now strictly enforced +** at all times. +*/ +#ifndef SQLITE_MAX_EXPR_DEPTH +# define SQLITE_MAX_EXPR_DEPTH 1000 +#endif + +/* +** The maximum number of terms in a compound SELECT statement. +** The code generator for compound SELECT statements does one +** level of recursion for each term. A stack overflow can result +** if the number of terms is too large. In practice, most SQL +** never has more than 3 or 4 terms. Use a value of 0 to disable +** any limit on the number of terms in a compount SELECT. +*/ +#ifndef SQLITE_MAX_COMPOUND_SELECT +# define SQLITE_MAX_COMPOUND_SELECT 500 +#endif + +/* +** The maximum number of opcodes in a VDBE program. +** Not currently enforced. +*/ +#ifndef SQLITE_MAX_VDBE_OP +# define SQLITE_MAX_VDBE_OP 25000 +#endif + +/* +** The maximum number of arguments to an SQL function. +*/ +#ifndef SQLITE_MAX_FUNCTION_ARG +# define SQLITE_MAX_FUNCTION_ARG 127 +#endif + +/* +** The maximum number of in-memory pages to use for the main database +** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE +*/ +#ifndef SQLITE_DEFAULT_CACHE_SIZE +# define SQLITE_DEFAULT_CACHE_SIZE 2000 +#endif +#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE +# define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500 +#endif + +/* +** The default number of frames to accumulate in the log file before +** checkpointing the database in WAL mode. +*/ +#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT +# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000 +#endif + +/* +** The maximum number of attached databases. This must be between 0 +** and 62. The upper bound on 62 is because a 64-bit integer bitmap +** is used internally to track attached databases. +*/ +#ifndef SQLITE_MAX_ATTACHED +# define SQLITE_MAX_ATTACHED 10 +#endif + + +/* +** The maximum value of a ?nnn wildcard that the parser will accept. +*/ +#ifndef SQLITE_MAX_VARIABLE_NUMBER +# define SQLITE_MAX_VARIABLE_NUMBER 999 +#endif + +/* Maximum page size. The upper bound on this value is 65536. This a limit +** imposed by the use of 16-bit offsets within each page. +** +** Earlier versions of SQLite allowed the user to change this value at +** compile time. This is no longer permitted, on the grounds that it creates +** a library that is technically incompatible with an SQLite library +** compiled with a different limit. If a process operating on a database +** with a page-size of 65536 bytes crashes, then an instance of SQLite +** compiled with the default page-size limit will not be able to rollback +** the aborted transaction. This could lead to database corruption. +*/ +#ifdef SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_PAGE_SIZE +#endif +#define SQLITE_MAX_PAGE_SIZE 65536 + + +/* +** The default size of a database page. +*/ +#ifndef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE 1024 +#endif +#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + +/* +** Ordinarily, if no value is explicitly provided, SQLite creates databases +** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain +** device characteristics (sector-size and atomic write() support), +** SQLite may choose a larger value. This constant is the maximum value +** SQLite will choose on its own. +*/ +#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 +#endif +#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + + +/* +** Maximum number of pages in one database file. +** +** This is really just the default value for the max_page_count pragma. +** This value can be lowered (or raised) at run-time using that the +** max_page_count macro. +*/ +#ifndef SQLITE_MAX_PAGE_COUNT +# define SQLITE_MAX_PAGE_COUNT 1073741823 +#endif + +/* +** Maximum length (in bytes) of the pattern in a LIKE or GLOB +** operator. +*/ +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 +#endif + +/* +** Maximum depth of recursion for triggers. +** +** A value of 1 means that a trigger program will not be able to itself +** fire any triggers. A value of 0 means that no trigger programs at all +** may be executed. +*/ +#ifndef SQLITE_MAX_TRIGGER_DEPTH +# define SQLITE_MAX_TRIGGER_DEPTH 1000 +#endif + +/************** End of sqliteLimit.h *****************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + +/* Disable nuisance warnings on Borland compilers */ +#if defined(__BORLANDC__) +#pragma warn -rch /* unreachable code */ +#pragma warn -ccc /* Condition is always true or false */ +#pragma warn -aus /* Assigned value is never used */ +#pragma warn -csu /* Comparing signed and unsigned */ +#pragma warn -spa /* Suspicious pointer arithmetic */ +#endif + +/* Needed for various definitions... */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE +#endif + +#if defined(__OpenBSD__) && !defined(_BSD_SOURCE) +# define _BSD_SOURCE +#endif + +/* +** Include standard header files as necessary +*/ +#ifdef HAVE_STDINT_H +#include +#endif +#ifdef HAVE_INTTYPES_H +#include +#endif + +/* +** The following macros are used to cast pointers to integers and +** integers to pointers. The way you do this varies from one compiler +** to the next, so we have developed the following set of #if statements +** to generate appropriate macros for a wide range of compilers. +** +** The correct "ANSI" way to do this is to use the intptr_t type. +** Unfortunately, that typedef is not available on all compilers, or +** if it is available, it requires an #include of specific headers +** that vary from one machine to the next. +** +** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on +** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). +** So we have to define the macros in different ways depending on the +** compiler. +*/ +#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ +# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) +#elif !defined(__GNUC__) /* Works for compilers other than LLVM */ +# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) +# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) +#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ +# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) +#else /* Generates a warning - but it always works */ +# define SQLITE_INT_TO_PTR(X) ((void*)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(X)) +#endif + +/* +** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. +** 0 means mutexes are permanently disable and the library is never +** threadsafe. 1 means the library is serialized which is the highest +** level of threadsafety. 2 means the library is multithreaded - multiple +** threads can use SQLite as long as no two threads try to use the same +** database connection at the same time. +** +** Older versions of SQLite used an optional THREADSAFE macro. +** We support that for legacy. +*/ +#if !defined(SQLITE_THREADSAFE) +# if defined(THREADSAFE) +# define SQLITE_THREADSAFE THREADSAFE +# else +# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ +# endif +#endif + +/* +** Powersafe overwrite is on by default. But can be turned off using +** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option. +*/ +#ifndef SQLITE_POWERSAFE_OVERWRITE +# define SQLITE_POWERSAFE_OVERWRITE 1 +#endif + +/* +** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. +** It determines whether or not the features related to +** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can +** be overridden at runtime using the sqlite3_config() API. +*/ +#if !defined(SQLITE_DEFAULT_MEMSTATUS) +# define SQLITE_DEFAULT_MEMSTATUS 1 +#endif + +/* +** Exactly one of the following macros must be defined in order to +** specify which memory allocation subsystem to use. +** +** SQLITE_SYSTEM_MALLOC // Use normal system malloc() +** SQLITE_WIN32_MALLOC // Use Win32 native heap API +** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails +** SQLITE_MEMDEBUG // Debugging version of system malloc() +** +** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the +** assert() macro is enabled, each call into the Win32 native heap subsystem +** will cause HeapValidate to be called. If heap validation should fail, an +** assertion will be triggered. +** +** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as +** the default. +*/ +#if defined(SQLITE_SYSTEM_MALLOC) \ + + defined(SQLITE_WIN32_MALLOC) \ + + defined(SQLITE_ZERO_MALLOC) \ + + defined(SQLITE_MEMDEBUG)>1 +# error "Two or more of the following compile-time configuration options\ + are defined but at most one is allowed:\ + SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\ + SQLITE_ZERO_MALLOC" +#endif +#if defined(SQLITE_SYSTEM_MALLOC) \ + + defined(SQLITE_WIN32_MALLOC) \ + + defined(SQLITE_ZERO_MALLOC) \ + + defined(SQLITE_MEMDEBUG)==0 +# define SQLITE_SYSTEM_MALLOC 1 +#endif + +/* +** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the +** sizes of memory allocations below this value where possible. +*/ +#if !defined(SQLITE_MALLOC_SOFT_LIMIT) +# define SQLITE_MALLOC_SOFT_LIMIT 1024 +#endif + +/* +** We need to define _XOPEN_SOURCE as follows in order to enable +** recursive mutexes on most Unix systems and fchmod() on OpenBSD. +** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit +** it. +*/ +#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) +# define _XOPEN_SOURCE 600 +#endif + +/* +** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that +** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true, +** make it true by defining or undefining NDEBUG. +** +** Setting NDEBUG makes the code smaller and faster by disabling the +** assert() statements in the code. So we want the default action +** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG +** is set. Thus NDEBUG becomes an opt-in rather than an opt-out +** feature. +*/ +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif +#if defined(NDEBUG) && defined(SQLITE_DEBUG) +# undef NDEBUG +#endif + +/* +** The testcase() macro is used to aid in coverage testing. When +** doing coverage testing, the condition inside the argument to +** testcase() must be evaluated both true and false in order to +** get full branch coverage. The testcase() macro is inserted +** to help ensure adequate test coverage in places where simple +** condition/decision coverage is inadequate. For example, testcase() +** can be used to make sure boundary values are tested. For +** bitmask tests, testcase() can be used to make sure each bit +** is significant and used at least once. On switch statements +** where multiple cases go to the same block of code, testcase() +** can insure that all cases are evaluated. +** +*/ +#ifdef SQLITE_COVERAGE_TEST +SQLITE_PRIVATE void sqlite3Coverage(int); +# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } +#else +# define testcase(X) +#endif + +/* +** The TESTONLY macro is used to enclose variable declarations or +** other bits of code that are needed to support the arguments +** within testcase() and assert() macros. +*/ +#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) +# define TESTONLY(X) X +#else +# define TESTONLY(X) +#endif + +/* +** Sometimes we need a small amount of code such as a variable initialization +** to setup for a later assert() statement. We do not want this code to +** appear when assert() is disabled. The following macro is therefore +** used to contain that setup code. The "VVA" acronym stands for +** "Verification, Validation, and Accreditation". In other words, the +** code within VVA_ONLY() will only run during verification processes. +*/ +#ifndef NDEBUG +# define VVA_ONLY(X) X +#else +# define VVA_ONLY(X) +#endif + +/* +** The ALWAYS and NEVER macros surround boolean expressions which +** are intended to always be true or false, respectively. Such +** expressions could be omitted from the code completely. But they +** are included in a few cases in order to enhance the resilience +** of SQLite to unexpected behavior - to make the code "self-healing" +** or "ductile" rather than being "brittle" and crashing at the first +** hint of unplanned behavior. +** +** In other words, ALWAYS and NEVER are added for defensive code. +** +** When doing coverage testing ALWAYS and NEVER are hard-coded to +** be true and false so that the unreachable code they specify will +** not be counted as untested code. +*/ +#if defined(SQLITE_COVERAGE_TEST) +# define ALWAYS(X) (1) +# define NEVER(X) (0) +#elif !defined(NDEBUG) +# define ALWAYS(X) ((X)?1:(assert(0),0)) +# define NEVER(X) ((X)?(assert(0),1):0) +#else +# define ALWAYS(X) (X) +# define NEVER(X) (X) +#endif + +/* +** Return true (non-zero) if the input is a integer that is too large +** to fit in 32-bits. This macro is used inside of various testcase() +** macros to verify that we have tested SQLite for large-file support. +*/ +#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) + +/* +** The macro unlikely() is a hint that surrounds a boolean +** expression that is usually false. Macro likely() surrounds +** a boolean expression that is usually true. These hints could, +** in theory, be used by the compiler to generate better code, but +** currently they are just comments for human readers. +*/ +#define likely(X) (X) +#define unlikely(X) (X) + +/************** Include hash.h in the middle of sqliteInt.h ******************/ +/************** Begin file hash.h ********************************************/ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implementation +** used in SQLite. +*/ +#ifndef _SQLITE_HASH_H_ +#define _SQLITE_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct Hash Hash; +typedef struct HashElem HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, some of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +** +** All elements of the hash table are on a single doubly-linked list. +** Hash.first points to the head of this list. +** +** There are Hash.htsize buckets. Each bucket points to a spot in +** the global doubly-linked list. The contents of the bucket are the +** element pointed to plus the next _ht.count-1 elements in the list. +** +** Hash.htsize and Hash.ht may be zero. In that case lookup is done +** by a linear search of the global list. For small tables, the +** Hash.ht table is never allocated because if there are few elements +** in the table, it is faster to do a linear search than to manage +** the hash table. +*/ +struct Hash { + unsigned int htsize; /* Number of buckets in the hash table */ + unsigned int count; /* Number of entries in this table */ + HashElem *first; /* The first element of the array */ + struct _ht { /* the hash table */ + int count; /* Number of entries with this hash */ + HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct HashElem { + HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + const char *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +SQLITE_PRIVATE void sqlite3HashInit(Hash*); +SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData); +SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey); +SQLITE_PRIVATE void sqlite3HashClear(Hash*); + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** Hash h; +** HashElem *p; +** ... +** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ +** SomeStructure *pData = sqliteHashData(p); +** // do something with pData +** } +*/ +#define sqliteHashFirst(H) ((H)->first) +#define sqliteHashNext(E) ((E)->next) +#define sqliteHashData(E) ((E)->data) +/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ +/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ + +/* +** Number of entries in a hash table +*/ +/* #define sqliteHashCount(H) ((H)->count) // NOT USED */ + +#endif /* _SQLITE_HASH_H_ */ + +/************** End of hash.h ************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include parse.h in the middle of sqliteInt.h *****************/ +/************** Begin file parse.h *******************************************/ +#define TK_SEMI 1 +#define TK_EXPLAIN 2 +#define TK_QUERY 3 +#define TK_PLAN 4 +#define TK_BEGIN 5 +#define TK_TRANSACTION 6 +#define TK_DEFERRED 7 +#define TK_IMMEDIATE 8 +#define TK_EXCLUSIVE 9 +#define TK_COMMIT 10 +#define TK_END 11 +#define TK_ROLLBACK 12 +#define TK_SAVEPOINT 13 +#define TK_RELEASE 14 +#define TK_TO 15 +#define TK_TABLE 16 +#define TK_CREATE 17 +#define TK_IF 18 +#define TK_NOT 19 +#define TK_EXISTS 20 +#define TK_TEMP 21 +#define TK_LP 22 +#define TK_RP 23 +#define TK_AS 24 +#define TK_COMMA 25 +#define TK_ID 26 +#define TK_INDEXED 27 +#define TK_ABORT 28 +#define TK_ACTION 29 +#define TK_AFTER 30 +#define TK_ANALYZE 31 +#define TK_ASC 32 +#define TK_ATTACH 33 +#define TK_BEFORE 34 +#define TK_BY 35 +#define TK_CASCADE 36 +#define TK_CAST 37 +#define TK_COLUMNKW 38 +#define TK_CONFLICT 39 +#define TK_DATABASE 40 +#define TK_DESC 41 +#define TK_DETACH 42 +#define TK_EACH 43 +#define TK_FAIL 44 +#define TK_FOR 45 +#define TK_IGNORE 46 +#define TK_INITIALLY 47 +#define TK_INSTEAD 48 +#define TK_LIKE_KW 49 +#define TK_MATCH 50 +#define TK_NO 51 +#define TK_KEY 52 +#define TK_OF 53 +#define TK_OFFSET 54 +#define TK_PRAGMA 55 +#define TK_RAISE 56 +#define TK_REPLACE 57 +#define TK_RESTRICT 58 +#define TK_ROW 59 +#define TK_TRIGGER 60 +#define TK_VACUUM 61 +#define TK_VIEW 62 +#define TK_VIRTUAL 63 +#define TK_REINDEX 64 +#define TK_RENAME 65 +#define TK_CTIME_KW 66 +#define TK_ANY 67 +#define TK_OR 68 +#define TK_AND 69 +#define TK_IS 70 +#define TK_BETWEEN 71 +#define TK_IN 72 +#define TK_ISNULL 73 +#define TK_NOTNULL 74 +#define TK_NE 75 +#define TK_EQ 76 +#define TK_GT 77 +#define TK_LE 78 +#define TK_LT 79 +#define TK_GE 80 +#define TK_ESCAPE 81 +#define TK_BITAND 82 +#define TK_BITOR 83 +#define TK_LSHIFT 84 +#define TK_RSHIFT 85 +#define TK_PLUS 86 +#define TK_MINUS 87 +#define TK_STAR 88 +#define TK_SLASH 89 +#define TK_REM 90 +#define TK_CONCAT 91 +#define TK_COLLATE 92 +#define TK_BITNOT 93 +#define TK_STRING 94 +#define TK_JOIN_KW 95 +#define TK_CONSTRAINT 96 +#define TK_DEFAULT 97 +#define TK_NULL 98 +#define TK_PRIMARY 99 +#define TK_UNIQUE 100 +#define TK_CHECK 101 +#define TK_REFERENCES 102 +#define TK_AUTOINCR 103 +#define TK_ON 104 +#define TK_INSERT 105 +#define TK_DELETE 106 +#define TK_UPDATE 107 +#define TK_SET 108 +#define TK_DEFERRABLE 109 +#define TK_FOREIGN 110 +#define TK_DROP 111 +#define TK_UNION 112 +#define TK_ALL 113 +#define TK_EXCEPT 114 +#define TK_INTERSECT 115 +#define TK_SELECT 116 +#define TK_DISTINCT 117 +#define TK_DOT 118 +#define TK_FROM 119 +#define TK_JOIN 120 +#define TK_USING 121 +#define TK_ORDER 122 +#define TK_GROUP 123 +#define TK_HAVING 124 +#define TK_LIMIT 125 +#define TK_WHERE 126 +#define TK_INTO 127 +#define TK_VALUES 128 +#define TK_INTEGER 129 +#define TK_FLOAT 130 +#define TK_BLOB 131 +#define TK_REGISTER 132 +#define TK_VARIABLE 133 +#define TK_CASE 134 +#define TK_WHEN 135 +#define TK_THEN 136 +#define TK_ELSE 137 +#define TK_INDEX 138 +#define TK_ALTER 139 +#define TK_ADD 140 +#define TK_TO_TEXT 141 +#define TK_TO_BLOB 142 +#define TK_TO_NUMERIC 143 +#define TK_TO_INT 144 +#define TK_TO_REAL 145 +#define TK_ISNOT 146 +#define TK_END_OF_FILE 147 +#define TK_ILLEGAL 148 +#define TK_SPACE 149 +#define TK_UNCLOSED_STRING 150 +#define TK_FUNCTION 151 +#define TK_COLUMN 152 +#define TK_AGG_FUNCTION 153 +#define TK_AGG_COLUMN 154 +#define TK_CONST_FUNC 155 +#define TK_UMINUS 156 +#define TK_UPLUS 157 + +/************** End of parse.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +#include +#include +#include +#include +#include + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite_int64 +# define float sqlite_int64 +# define LONGDOUBLE_TYPE sqlite_int64 +# ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) +# endif +# define SQLITE_OMIT_DATETIME_FUNCS 1 +# define SQLITE_OMIT_TRACE 1 +# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT +# undef SQLITE_HAVE_ISNAN +#endif +#ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (1e99) +#endif + +/* +** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 +** afterward. Having this macro allows us to cause the C compiler +** to omit code used by TEMP tables without messy #ifndef statements. +*/ +#ifdef SQLITE_OMIT_TEMPDB +#define OMIT_TEMPDB 1 +#else +#define OMIT_TEMPDB 0 +#endif + +/* +** The "file format" number is an integer that is incremented whenever +** the VDBE-level file format changes. The following macros define the +** the default file format for new databases and the maximum file format +** that the library can read. +*/ +#define SQLITE_MAX_FILE_FORMAT 4 +#ifndef SQLITE_DEFAULT_FILE_FORMAT +# define SQLITE_DEFAULT_FILE_FORMAT 4 +#endif + +/* +** Determine whether triggers are recursive by default. This can be +** changed at run-time using a pragma. +*/ +#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS +# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 +#endif + +/* +** Provide a default value for SQLITE_TEMP_STORE in case it is not specified +** on the command-line +*/ +#ifndef SQLITE_TEMP_STORE +# define SQLITE_TEMP_STORE 1 +# define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */ +#endif + +/* +** GCC does not define the offsetof() macro so we'll have to do it +** ourselves. +*/ +#ifndef offsetof +#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) +#endif + +/* +** Macros to compute minimum and maximum of two numbers. +*/ +#define MIN(A,B) ((A)<(B)?(A):(B)) +#define MAX(A,B) ((A)>(B)?(A):(B)) + +/* +** Check to see if this machine uses EBCDIC. (Yes, believe it or +** not, there are still machines out there that use EBCDIC.) +*/ +#if 'A' == '\301' +# define SQLITE_EBCDIC 1 +#else +# define SQLITE_ASCII 1 +#endif + +/* +** Integers of known sizes. These typedefs might change for architectures +** where the sizes very. Preprocessor macros are available so that the +** types can be conveniently redefined at compile-type. Like this: +** +** cc '-DUINTPTR_TYPE=long long int' ... +*/ +#ifndef UINT32_TYPE +# ifdef HAVE_UINT32_T +# define UINT32_TYPE uint32_t +# else +# define UINT32_TYPE unsigned int +# endif +#endif +#ifndef UINT16_TYPE +# ifdef HAVE_UINT16_T +# define UINT16_TYPE uint16_t +# else +# define UINT16_TYPE unsigned short int +# endif +#endif +#ifndef INT16_TYPE +# ifdef HAVE_INT16_T +# define INT16_TYPE int16_t +# else +# define INT16_TYPE short int +# endif +#endif +#ifndef UINT8_TYPE +# ifdef HAVE_UINT8_T +# define UINT8_TYPE uint8_t +# else +# define UINT8_TYPE unsigned char +# endif +#endif +#ifndef INT8_TYPE +# ifdef HAVE_INT8_T +# define INT8_TYPE int8_t +# else +# define INT8_TYPE signed char +# endif +#endif +#ifndef LONGDOUBLE_TYPE +# define LONGDOUBLE_TYPE long double +#endif +typedef sqlite_int64 i64; /* 8-byte signed integer */ +typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ +typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ +typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ +typedef INT16_TYPE i16; /* 2-byte signed integer */ +typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ +typedef INT8_TYPE i8; /* 1-byte signed integer */ + +/* +** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value +** that can be stored in a u32 without loss of data. The value +** is 0x00000000ffffffff. But because of quirks of some compilers, we +** have to specify the value in the less intuitive manner shown: +*/ +#define SQLITE_MAX_U32 ((((u64)1)<<32)-1) + +/* +** The datatype used to store estimates of the number of rows in a +** table or index. This is an unsigned integer type. For 99.9% of +** the world, a 32-bit integer is sufficient. But a 64-bit integer +** can be used at compile-time if desired. +*/ +#ifdef SQLITE_64BIT_STATS + typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */ +#else + typedef u32 tRowcnt; /* 32-bit is the default */ +#endif + +/* +** Estimated quantities used for query planning are stored as 16-bit +** logarithms. For quantity X, the value stored is 10*log2(X). This +** gives a possible range of values of approximately 1.0e986 to 1e-986. +** But the allowed values are "grainy". Not every value is representable. +** For example, quantities 16 and 17 are both represented by a LogEst +** of 40. However, since LogEst quantatites are suppose to be estimates, +** not exact values, this imprecision is not a problem. +** +** "LogEst" is short for "Logarithimic Estimate". +** +** Examples: +** 1 -> 0 20 -> 43 10000 -> 132 +** 2 -> 10 25 -> 46 25000 -> 146 +** 3 -> 16 100 -> 66 1000000 -> 199 +** 4 -> 20 1000 -> 99 1048576 -> 200 +** 10 -> 33 1024 -> 100 4294967296 -> 320 +** +** The LogEst can be negative to indicate fractional values. +** Examples: +** +** 0.5 -> -10 0.1 -> -33 0.0625 -> -40 +*/ +typedef INT16_TYPE LogEst; + +/* +** Macros to determine whether the machine is big or little endian, +** evaluated at runtime. +*/ +#ifdef SQLITE_AMALGAMATION +SQLITE_PRIVATE const int sqlite3one = 1; +#else +SQLITE_PRIVATE const int sqlite3one; +#endif +#if defined(i386) || defined(__i386__) || defined(_M_IX86)\ + || defined(__x86_64) || defined(__x86_64__) +# define SQLITE_BIGENDIAN 0 +# define SQLITE_LITTLEENDIAN 1 +# define SQLITE_UTF16NATIVE SQLITE_UTF16LE +#else +# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) +# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) +# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) +#endif + +/* +** Constants for the largest and smallest possible 64-bit signed integers. +** These macros are designed to work correctly on both 32-bit and 64-bit +** compilers. +*/ +#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) +#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) + +/* +** Round up a number to the next larger multiple of 8. This is used +** to force 8-byte alignment on 64-bit architectures. +*/ +#define ROUND8(x) (((x)+7)&~7) + +/* +** Round down to the nearest multiple of 8 +*/ +#define ROUNDDOWN8(x) ((x)&~7) + +/* +** Assert that the pointer X is aligned to an 8-byte boundary. This +** macro is used only within assert() to verify that the code gets +** all alignment restrictions correct. +** +** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the +** underlying malloc() implemention might return us 4-byte aligned +** pointers. In that case, only verify 4-byte alignment. +*/ +#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) +#else +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) +#endif + +/* +** Disable MMAP on platforms where it is known to not work +*/ +#if defined(__OpenBSD__) || defined(__QNXNTO__) +# undef SQLITE_MAX_MMAP_SIZE +# define SQLITE_MAX_MMAP_SIZE 0 +#endif + +/* +** Default maximum size of memory used by memory-mapped I/O in the VFS +*/ +#ifdef __APPLE__ +# include +# if TARGET_OS_IPHONE +# undef SQLITE_MAX_MMAP_SIZE +# define SQLITE_MAX_MMAP_SIZE 0 +# endif +#endif +#ifndef SQLITE_MAX_MMAP_SIZE +# if defined(SQLITE_OS_RTTHREAD) +# define SQLITE_MAX_MMAP_SIZE 0 +# elif defined(__linux__) \ + || defined(_WIN32) \ + || (defined(__APPLE__) && defined(__MACH__)) \ + || defined(__sun) +# define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */ +# else +# define SQLITE_MAX_MMAP_SIZE 0 +# endif +# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */ +#endif + +/* +** The default MMAP_SIZE is zero on all platforms. Or, even if a larger +** default MMAP_SIZE is specified at compile-time, make sure that it does +** not exceed the maximum mmap size. +*/ +#ifndef SQLITE_DEFAULT_MMAP_SIZE +# define SQLITE_DEFAULT_MMAP_SIZE 0 +# define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */ +#endif +#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE +# undef SQLITE_DEFAULT_MMAP_SIZE +# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE +#endif + +/* +** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined. +** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also +** define SQLITE_ENABLE_STAT3_OR_STAT4 +*/ +#ifdef SQLITE_ENABLE_STAT4 +# undef SQLITE_ENABLE_STAT3 +# define SQLITE_ENABLE_STAT3_OR_STAT4 1 +#elif SQLITE_ENABLE_STAT3 +# define SQLITE_ENABLE_STAT3_OR_STAT4 1 +#elif SQLITE_ENABLE_STAT3_OR_STAT4 +# undef SQLITE_ENABLE_STAT3_OR_STAT4 +#endif + +/* +** An instance of the following structure is used to store the busy-handler +** callback for a given sqlite handle. +** +** The sqlite.busyHandler member of the sqlite struct contains the busy +** callback for the database handle. Each pager opened via the sqlite +** handle is passed a pointer to sqlite.busyHandler. The busy-handler +** callback is currently invoked only from within pager.c. +*/ +typedef struct BusyHandler BusyHandler; +struct BusyHandler { + int (*xFunc)(void *,int); /* The busy callback */ + void *pArg; /* First arg to busy callback */ + int nBusy; /* Incremented with each busy call */ +}; + +/* +** Name of the master database table. The master database table +** is a special table that holds the names and attributes of all +** user tables and indices. +*/ +#define MASTER_NAME "sqlite_master" +#define TEMP_MASTER_NAME "sqlite_temp_master" + +/* +** The root-page of the master database table. +*/ +#define MASTER_ROOT 1 + +/* +** The name of the schema table. +*/ +#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) + +/* +** A convenience macro that returns the number of elements in +** an array. +*/ +#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) + +/* +** Determine if the argument is a power of two +*/ +#define IsPowerOfTwo(X) (((X)&((X)-1))==0) + +/* +** The following value as a destructor means to use sqlite3DbFree(). +** The sqlite3DbFree() routine requires two parameters instead of the +** one parameter that destructors normally want. So we have to introduce +** this magic value that the code knows to handle differently. Any +** pointer will work here as long as it is distinct from SQLITE_STATIC +** and SQLITE_TRANSIENT. +*/ +#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize) + +/* +** When SQLITE_OMIT_WSD is defined, it means that the target platform does +** not support Writable Static Data (WSD) such as global and static variables. +** All variables must either be on the stack or dynamically allocated from +** the heap. When WSD is unsupported, the variable declarations scattered +** throughout the SQLite code must become constants instead. The SQLITE_WSD +** macro is used for this purpose. And instead of referencing the variable +** directly, we use its constant as a key to lookup the run-time allocated +** buffer that holds real variable. The constant is also the initializer +** for the run-time allocated buffer. +** +** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL +** macros become no-ops and have zero performance impact. +*/ +#ifdef SQLITE_OMIT_WSD + #define SQLITE_WSD const + #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) + #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) +SQLITE_API int sqlite3_wsd_init(int N, int J); +SQLITE_API void *sqlite3_wsd_find(void *K, int L); +#else + #define SQLITE_WSD + #define GLOBAL(t,v) v + #define sqlite3GlobalConfig sqlite3Config +#endif + +/* +** The following macros are used to suppress compiler warnings and to +** make it clear to human readers when a function parameter is deliberately +** left unused within the body of a function. This usually happens when +** a function is called via a function pointer. For example the +** implementation of an SQL aggregate step callback may not use the +** parameter indicating the number of arguments passed to the aggregate, +** if it knows that this is enforced elsewhere. +** +** When a function parameter is not used at all within the body of a function, +** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. +** However, these macros may also be used to suppress warnings related to +** parameters that may or may not be used depending on compilation options. +** For example those parameters only used in assert() statements. In these +** cases the parameters are named as per the usual conventions. +*/ +#define UNUSED_PARAMETER(x) (void)(x) +#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) + +/* +** Forward references to structures +*/ +typedef struct AggInfo AggInfo; +typedef struct AuthContext AuthContext; +typedef struct AutoincInfo AutoincInfo; +typedef struct Bitvec Bitvec; +typedef struct CollSeq CollSeq; +typedef struct Column Column; +typedef struct Db Db; +typedef struct Schema Schema; +typedef struct Expr Expr; +typedef struct ExprList ExprList; +typedef struct ExprSpan ExprSpan; +typedef struct FKey FKey; +typedef struct FuncDestructor FuncDestructor; +typedef struct FuncDef FuncDef; +typedef struct FuncDefHash FuncDefHash; +typedef struct IdList IdList; +typedef struct Index Index; +typedef struct IndexSample IndexSample; +typedef struct KeyClass KeyClass; +typedef struct KeyInfo KeyInfo; +typedef struct Lookaside Lookaside; +typedef struct LookasideSlot LookasideSlot; +typedef struct Module Module; +typedef struct NameContext NameContext; +typedef struct Parse Parse; +typedef struct RowSet RowSet; +typedef struct Savepoint Savepoint; +typedef struct Select Select; +typedef struct SelectDest SelectDest; +typedef struct SrcList SrcList; +typedef struct StrAccum StrAccum; +typedef struct Table Table; +typedef struct TableLock TableLock; +typedef struct Token Token; +typedef struct Trigger Trigger; +typedef struct TriggerPrg TriggerPrg; +typedef struct TriggerStep TriggerStep; +typedef struct UnpackedRecord UnpackedRecord; +typedef struct VTable VTable; +typedef struct VtabCtx VtabCtx; +typedef struct Walker Walker; +typedef struct WhereInfo WhereInfo; + +/* +** Defer sourcing vdbe.h and btree.h until after the "u8" and +** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque +** pointer types (i.e. FuncDef) defined above. +*/ +/************** Include btree.h in the middle of sqliteInt.h *****************/ +/************** Begin file btree.h *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite B-Tree file +** subsystem. See comments in the source code for a detailed description +** of what each interface routine does. +*/ +#ifndef _BTREE_H_ +#define _BTREE_H_ + +/* TODO: This definition is just included so other modules compile. It +** needs to be revisited. +*/ +#define SQLITE_N_BTREE_META 10 + +/* +** If defined as non-zero, auto-vacuum is enabled by default. Otherwise +** it must be turned on for each database using "PRAGMA auto_vacuum = 1". +*/ +#ifndef SQLITE_DEFAULT_AUTOVACUUM + #define SQLITE_DEFAULT_AUTOVACUUM 0 +#endif + +#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ +#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ +#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ + +/* +** Forward declarations of structure +*/ +typedef struct Btree Btree; +typedef struct BtCursor BtCursor; +typedef struct BtShared BtShared; + + +SQLITE_PRIVATE int sqlite3BtreeOpen( + sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ + const char *zFilename, /* Name of database file to open */ + sqlite3 *db, /* Associated database connection */ + Btree **ppBtree, /* Return open Btree* here */ + int flags, /* Flags */ + int vfsFlags /* Flags passed through to VFS open */ +); + +/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the +** following values. +** +** NOTE: These values must match the corresponding PAGER_ values in +** pager.h. +*/ +#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ +#define BTREE_MEMORY 2 /* This is an in-memory DB */ +#define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */ +#define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */ + +SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64); +SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned); +SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); +SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); +SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); +SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*); +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG) +SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p); +#endif +SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); +SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); +SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int); +SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); +SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); +SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); +SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); +SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); +SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); +SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); +SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); +SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); + +SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); +SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); +SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); + +SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); + +/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR +** of the flags shown below. +** +** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. +** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data +** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With +** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored +** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL +** indices.) +*/ +#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ +#define BTREE_BLOBKEY 2 /* Table has keys only - no data */ + +SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); +SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); +SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int); + +SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); +SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); + +SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); + +/* +** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta +** should be one of the following values. The integer values are assigned +** to constants so that the offset of the corresponding field in an +** SQLite database header may be found using the following formula: +** +** offset = 36 + (idx * 4) +** +** For example, the free-page-count field is located at byte offset 36 of +** the database file header. The incr-vacuum-flag field is located at +** byte offset 64 (== 36+4*7). +*/ +#define BTREE_FREE_PAGE_COUNT 0 +#define BTREE_SCHEMA_VERSION 1 +#define BTREE_FILE_FORMAT 2 +#define BTREE_DEFAULT_CACHE_SIZE 3 +#define BTREE_LARGEST_ROOT_PAGE 4 +#define BTREE_TEXT_ENCODING 5 +#define BTREE_USER_VERSION 6 +#define BTREE_INCR_VACUUM 7 +#define BTREE_APPLICATION_ID 8 + +/* +** Values that may be OR'd together to form the second argument of an +** sqlite3BtreeCursorHints() call. +*/ +#define BTREE_BULKLOAD 0x00000001 + +SQLITE_PRIVATE int sqlite3BtreeCursor( + Btree*, /* BTree containing table to open */ + int iTable, /* Index of root page */ + int wrFlag, /* 1 for writing. 0 for read-only */ + struct KeyInfo*, /* First argument to compare function */ + BtCursor *pCursor /* Space to write cursor structure */ +); +SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); +SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); + +SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( + BtCursor*, + UnpackedRecord *pUnKey, + i64 intKey, + int bias, + int *pRes +); +SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*); +SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey, + const void *pData, int nData, + int nZero, int bias, int seekResult); +SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize); +SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt); +SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt); +SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize); +SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64); +SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*); + +SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); +SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); + +SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *); +SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); +SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); +SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask); + +#ifndef NDEBUG +SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); +#endif + +#ifndef SQLITE_OMIT_BTREECOUNT +SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); +#endif + +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); +SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); +#endif + +#ifndef SQLITE_OMIT_WAL +SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); +#endif + +/* +** If we are not using shared cache, then there is no need to +** use mutexes to access the BtShared structures. So make the +** Enter and Leave procedures no-ops. +*/ +#ifndef SQLITE_OMIT_SHARED_CACHE +SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); +SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); +#else +# define sqlite3BtreeEnter(X) +# define sqlite3BtreeEnterAll(X) +#endif + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE +SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*); +SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); +SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); +SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); +SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); +#ifndef NDEBUG + /* These routines are used inside assert() statements only. */ +SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); +SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); +SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); +#endif +#else + +# define sqlite3BtreeSharable(X) 0 +# define sqlite3BtreeLeave(X) +# define sqlite3BtreeEnterCursor(X) +# define sqlite3BtreeLeaveCursor(X) +# define sqlite3BtreeLeaveAll(X) + +# define sqlite3BtreeHoldsMutex(X) 1 +# define sqlite3BtreeHoldsAllMutexes(X) 1 +# define sqlite3SchemaMutexHeld(X,Y,Z) 1 +#endif + + +#endif /* _BTREE_H_ */ + +/************** End of btree.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include vdbe.h in the middle of sqliteInt.h ******************/ +/************** Begin file vdbe.h ********************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Header file for the Virtual DataBase Engine (VDBE) +** +** This header defines the interface to the virtual database engine +** or VDBE. The VDBE implements an abstract machine that runs a +** simple program to access and modify the underlying database. +*/ +#ifndef _SQLITE_VDBE_H_ +#define _SQLITE_VDBE_H_ +/* #include */ + +/* +** A single VDBE is an opaque structure named "Vdbe". Only routines +** in the source file sqliteVdbe.c are allowed to see the insides +** of this structure. +*/ +typedef struct Vdbe Vdbe; + +/* +** The names of the following types declared in vdbeInt.h are required +** for the VdbeOp definition. +*/ +typedef struct Mem Mem; +typedef struct SubProgram SubProgram; + +/* +** A single instruction of the virtual machine has an opcode +** and as many as three operands. The instruction is recorded +** as an instance of the following structure: +*/ +struct VdbeOp { + u8 opcode; /* What operation to perform */ + signed char p4type; /* One of the P4_xxx constants for p4 */ + u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */ + u8 p5; /* Fifth parameter is an unsigned character */ + int p1; /* First operand */ + int p2; /* Second parameter (often the jump destination) */ + int p3; /* The third parameter */ + union { /* fourth parameter */ + int i; /* Integer value if p4type==P4_INT32 */ + void *p; /* Generic pointer */ + char *z; /* Pointer to data for string (char array) types */ + i64 *pI64; /* Used when p4type is P4_INT64 */ + double *pReal; /* Used when p4type is P4_REAL */ + FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ + CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ + Mem *pMem; /* Used when p4type is P4_MEM */ + VTable *pVtab; /* Used when p4type is P4_VTAB */ + KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ + int *ai; /* Used when p4type is P4_INTARRAY */ + SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ + int (*xAdvance)(BtCursor *, int *); + } p4; +#ifdef SQLITE_DEBUG + char *zComment; /* Comment to improve readability */ +#endif +#ifdef VDBE_PROFILE + int cnt; /* Number of times this instruction was executed */ + u64 cycles; /* Total time spent executing this instruction */ +#endif +}; +typedef struct VdbeOp VdbeOp; + + +/* +** A sub-routine used to implement a trigger program. +*/ +struct SubProgram { + VdbeOp *aOp; /* Array of opcodes for sub-program */ + int nOp; /* Elements in aOp[] */ + int nMem; /* Number of memory cells required */ + int nCsr; /* Number of cursors required */ + int nOnce; /* Number of OP_Once instructions */ + void *token; /* id that may be used to recursive triggers */ + SubProgram *pNext; /* Next sub-program already visited */ +}; + +/* +** A smaller version of VdbeOp used for the VdbeAddOpList() function because +** it takes up less space. +*/ +struct VdbeOpList { + u8 opcode; /* What operation to perform */ + signed char p1; /* First operand */ + signed char p2; /* Second parameter (often the jump destination) */ + signed char p3; /* Third parameter */ +}; +typedef struct VdbeOpList VdbeOpList; + +/* +** Allowed values of VdbeOp.p4type +*/ +#define P4_NOTUSED 0 /* The P4 parameter is not used */ +#define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ +#define P4_STATIC (-2) /* Pointer to a static string */ +#define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ +#define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ +#define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ +#define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ +#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */ +#define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ +#define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ +#define P4_REAL (-12) /* P4 is a 64-bit floating point value */ +#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ +#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ +#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ +#define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ +#define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */ + +/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure +** is made. That copy is freed when the Vdbe is finalized. But if the +** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still +** gets freed when the Vdbe is finalized so it still should be obtained +** from a single sqliteMalloc(). But no copy is made and the calling +** function should *not* try to free the KeyInfo. +*/ +#define P4_KEYINFO_HANDOFF (-16) +#define P4_KEYINFO_STATIC (-17) + +/* +** The Vdbe.aColName array contains 5n Mem structures, where n is the +** number of columns of data returned by the statement. +*/ +#define COLNAME_NAME 0 +#define COLNAME_DECLTYPE 1 +#define COLNAME_DATABASE 2 +#define COLNAME_TABLE 3 +#define COLNAME_COLUMN 4 +#ifdef SQLITE_ENABLE_COLUMN_METADATA +# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ +#else +# ifdef SQLITE_OMIT_DECLTYPE +# define COLNAME_N 1 /* Store only the name */ +# else +# define COLNAME_N 2 /* Store the name and decltype */ +# endif +#endif + +/* +** The following macro converts a relative address in the p2 field +** of a VdbeOp structure into a negative number so that +** sqlite3VdbeAddOpList() knows that the address is relative. Calling +** the macro again restores the address. +*/ +#define ADDR(X) (-1-(X)) + +/* +** The makefile scans the vdbe.c source file and creates the "opcodes.h" +** header file that defines a number for each opcode used by the VDBE. +*/ +/************** Include opcodes.h in the middle of vdbe.h ********************/ +/************** Begin file opcodes.h *****************************************/ +/* Automatically generated. Do not edit */ +/* See the mkopcodeh.awk script for details */ +#define OP_Function 1 +#define OP_Savepoint 2 +#define OP_AutoCommit 3 +#define OP_Transaction 4 +#define OP_SorterNext 5 +#define OP_Prev 6 +#define OP_Next 7 +#define OP_AggStep 8 +#define OP_Checkpoint 9 +#define OP_JournalMode 10 +#define OP_Vacuum 11 +#define OP_VFilter 12 +#define OP_VUpdate 13 +#define OP_Goto 14 +#define OP_Gosub 15 +#define OP_Return 16 +#define OP_Yield 17 +#define OP_HaltIfNull 18 +#define OP_Not 19 /* same as TK_NOT */ +#define OP_Halt 20 +#define OP_Integer 21 +#define OP_Int64 22 +#define OP_String 23 +#define OP_Null 24 +#define OP_Blob 25 +#define OP_Variable 26 +#define OP_Move 27 +#define OP_Copy 28 +#define OP_SCopy 29 +#define OP_ResultRow 30 +#define OP_CollSeq 31 +#define OP_AddImm 32 +#define OP_MustBeInt 33 +#define OP_RealAffinity 34 +#define OP_Permutation 35 +#define OP_Compare 36 +#define OP_Jump 37 +#define OP_Once 38 +#define OP_If 39 +#define OP_IfNot 40 +#define OP_Column 41 +#define OP_Affinity 42 +#define OP_MakeRecord 43 +#define OP_Count 44 +#define OP_ReadCookie 45 +#define OP_SetCookie 46 +#define OP_VerifyCookie 47 +#define OP_OpenRead 48 +#define OP_OpenWrite 49 +#define OP_OpenAutoindex 50 +#define OP_OpenEphemeral 51 +#define OP_SorterOpen 52 +#define OP_OpenPseudo 53 +#define OP_Close 54 +#define OP_SeekLt 55 +#define OP_SeekLe 56 +#define OP_SeekGe 57 +#define OP_SeekGt 58 +#define OP_Seek 59 +#define OP_NotFound 60 +#define OP_Found 61 +#define OP_IsUnique 62 +#define OP_NotExists 63 +#define OP_Sequence 64 +#define OP_NewRowid 65 +#define OP_Insert 66 +#define OP_InsertInt 67 +#define OP_Or 68 /* same as TK_OR */ +#define OP_And 69 /* same as TK_AND */ +#define OP_Delete 70 +#define OP_ResetCount 71 +#define OP_SorterCompare 72 +#define OP_IsNull 73 /* same as TK_ISNULL */ +#define OP_NotNull 74 /* same as TK_NOTNULL */ +#define OP_Ne 75 /* same as TK_NE */ +#define OP_Eq 76 /* same as TK_EQ */ +#define OP_Gt 77 /* same as TK_GT */ +#define OP_Le 78 /* same as TK_LE */ +#define OP_Lt 79 /* same as TK_LT */ +#define OP_Ge 80 /* same as TK_GE */ +#define OP_SorterData 81 +#define OP_BitAnd 82 /* same as TK_BITAND */ +#define OP_BitOr 83 /* same as TK_BITOR */ +#define OP_ShiftLeft 84 /* same as TK_LSHIFT */ +#define OP_ShiftRight 85 /* same as TK_RSHIFT */ +#define OP_Add 86 /* same as TK_PLUS */ +#define OP_Subtract 87 /* same as TK_MINUS */ +#define OP_Multiply 88 /* same as TK_STAR */ +#define OP_Divide 89 /* same as TK_SLASH */ +#define OP_Remainder 90 /* same as TK_REM */ +#define OP_Concat 91 /* same as TK_CONCAT */ +#define OP_RowKey 92 +#define OP_BitNot 93 /* same as TK_BITNOT */ +#define OP_String8 94 /* same as TK_STRING */ +#define OP_RowData 95 +#define OP_Rowid 96 +#define OP_NullRow 97 +#define OP_Last 98 +#define OP_SorterSort 99 +#define OP_Sort 100 +#define OP_Rewind 101 +#define OP_SorterInsert 102 +#define OP_IdxInsert 103 +#define OP_IdxDelete 104 +#define OP_IdxRowid 105 +#define OP_IdxLT 106 +#define OP_IdxGE 107 +#define OP_Destroy 108 +#define OP_Clear 109 +#define OP_CreateIndex 110 +#define OP_CreateTable 111 +#define OP_ParseSchema 112 +#define OP_LoadAnalysis 113 +#define OP_DropTable 114 +#define OP_DropIndex 115 +#define OP_DropTrigger 116 +#define OP_IntegrityCk 117 +#define OP_RowSetAdd 118 +#define OP_RowSetRead 119 +#define OP_RowSetTest 120 +#define OP_Program 121 +#define OP_Param 122 +#define OP_FkCounter 123 +#define OP_FkIfZero 124 +#define OP_MemMax 125 +#define OP_IfPos 126 +#define OP_IfNeg 127 +#define OP_IfZero 128 +#define OP_AggFinal 129 +#define OP_Real 130 /* same as TK_FLOAT */ +#define OP_IncrVacuum 131 +#define OP_Expire 132 +#define OP_TableLock 133 +#define OP_VBegin 134 +#define OP_VCreate 135 +#define OP_VDestroy 136 +#define OP_VOpen 137 +#define OP_VColumn 138 +#define OP_VNext 139 +#define OP_VRename 140 +#define OP_ToText 141 /* same as TK_TO_TEXT */ +#define OP_ToBlob 142 /* same as TK_TO_BLOB */ +#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/ +#define OP_ToInt 144 /* same as TK_TO_INT */ +#define OP_ToReal 145 /* same as TK_TO_REAL */ +#define OP_Pagecount 146 +#define OP_MaxPgcnt 147 +#define OP_Trace 148 +#define OP_Noop 149 +#define OP_Explain 150 + + +/* Properties such as "out2" or "jump" that are specified in +** comments following the "case" for each opcode in the vdbe.c +** are encoded into bitvectors as follows: +*/ +#define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */ +#define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */ +#define OPFLG_IN1 0x0004 /* in1: P1 is an input */ +#define OPFLG_IN2 0x0008 /* in2: P2 is an input */ +#define OPFLG_IN3 0x0010 /* in3: P3 is an input */ +#define OPFLG_OUT2 0x0020 /* out2: P2 is an output */ +#define OPFLG_OUT3 0x0040 /* out3: P3 is an output */ +#define OPFLG_INITIALIZER {\ +/* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\ +/* 8 */ 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x01, 0x01,\ +/* 16 */ 0x04, 0x04, 0x10, 0x24, 0x00, 0x02, 0x02, 0x02,\ +/* 24 */ 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x00, 0x00,\ +/* 32 */ 0x04, 0x05, 0x04, 0x00, 0x00, 0x01, 0x01, 0x05,\ +/* 40 */ 0x05, 0x00, 0x00, 0x00, 0x02, 0x02, 0x10, 0x00,\ +/* 48 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,\ +/* 56 */ 0x11, 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11,\ +/* 64 */ 0x02, 0x02, 0x00, 0x00, 0x4c, 0x4c, 0x00, 0x00,\ +/* 72 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\ +/* 80 */ 0x15, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\ +/* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x00, 0x24, 0x02, 0x00,\ +/* 96 */ 0x02, 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08,\ +/* 104 */ 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x02, 0x02,\ +/* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45,\ +/* 120 */ 0x15, 0x01, 0x02, 0x00, 0x01, 0x08, 0x05, 0x05,\ +/* 128 */ 0x05, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00,\ +/* 136 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x04, 0x04,\ +/* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,} + +/************** End of opcodes.h *********************************************/ +/************** Continuing where we left off in vdbe.h ***********************/ + +/* +** Prototypes for the VDBE interface. See comments on the implementation +** for a description of what each of these routines does. +*/ +SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*); +SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); +SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); +SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1); +SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2); +SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3); +SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); +SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); +SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr); +SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); +SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); +SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); +SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*); +SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); +SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); +SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*); +#endif +SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*); +SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); +SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); +SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); +SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); +SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); +SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); +SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8); +SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); +#ifndef SQLITE_OMIT_TRACE +SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*); +#endif + +SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); +SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); +SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **); + +#ifndef SQLITE_OMIT_TRIGGER +SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); +#endif + + +#ifndef NDEBUG +SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); +# define VdbeComment(X) sqlite3VdbeComment X +SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); +# define VdbeNoopComment(X) sqlite3VdbeNoopComment X +#else +# define VdbeComment(X) +# define VdbeNoopComment(X) +#endif + +#endif + +/************** End of vdbe.h ************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include pager.h in the middle of sqliteInt.h *****************/ +/************** Begin file pager.h *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. The page cache subsystem reads and writes a file a page +** at a time and provides a journal for rollback. +*/ + +#ifndef _PAGER_H_ +#define _PAGER_H_ + +/* +** Default maximum size for persistent journal files. A negative +** value means no limit. This value may be overridden using the +** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". +*/ +#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT + #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 +#endif + +/* +** The type used to represent a page number. The first page in a file +** is called page 1. 0 is used to represent "not a page". +*/ +typedef u32 Pgno; + +/* +** Each open file is managed by a separate instance of the "Pager" structure. +*/ +typedef struct Pager Pager; + +/* +** Handle type for pages. +*/ +typedef struct PgHdr DbPage; + +/* +** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is +** reserved for working around a windows/posix incompatibility). It is +** used in the journal to signify that the remainder of the journal file +** is devoted to storing a master journal name - there are no more pages to +** roll back. See comments for function writeMasterJournal() in pager.c +** for details. +*/ +#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) + +/* +** Allowed values for the flags parameter to sqlite3PagerOpen(). +** +** NOTE: These values must match the corresponding BTREE_ values in btree.h. +*/ +#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ +#define PAGER_MEMORY 0x0002 /* In-memory database */ + +/* +** Valid values for the second argument to sqlite3PagerLockingMode(). +*/ +#define PAGER_LOCKINGMODE_QUERY -1 +#define PAGER_LOCKINGMODE_NORMAL 0 +#define PAGER_LOCKINGMODE_EXCLUSIVE 1 + +/* +** Numeric constants that encode the journalmode. +*/ +#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ +#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ +#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ +#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ +#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ +#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ +#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ + +/* +** Flags that make up the mask passed to sqlite3PagerAcquire(). +*/ +#define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */ +#define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */ + +/* +** Flags for sqlite3PagerSetFlags() +*/ +#define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */ +#define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */ +#define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */ +#define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */ +#define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */ +#define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */ +#define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */ +#define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */ + +/* +** The remainder of this file contains the declarations of the functions +** that make up the Pager sub-system API. See source code comments for +** a detailed description of each routine. +*/ + +/* Open and close a Pager connection. */ +SQLITE_PRIVATE int sqlite3PagerOpen( + sqlite3_vfs*, + Pager **ppPager, + const char*, + int, + int, + int, + void(*)(DbPage*) +); +SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); + +/* Functions used to configure a Pager object. */ +SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); +SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int); +SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); +SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); +SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64); +SQLITE_PRIVATE void sqlite3PagerShrink(Pager*); +SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned); +SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); +SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int); +SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*); +SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*); +SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); +SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); + +/* Functions used to obtain and release page references. */ +SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); +#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) +SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); +SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); +SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); + +/* Operations on page references. */ +SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); +SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); +SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); +SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); +SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); +SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); + +/* Functions used to manage pager transactions and savepoints. */ +SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*); +SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); +SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); +SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); +SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); +SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); +SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); +SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); +SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); + +#ifndef SQLITE_OMIT_WAL +SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*); +SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); +SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager); +#endif + +#ifdef SQLITE_ENABLE_ZIPVFS +SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager); +#endif + +/* Functions used to query pager state and configuration. */ +SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); +SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); +SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*); +SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int); +SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*); +SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); +SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); +SQLITE_PRIVATE int sqlite3PagerNosync(Pager*); +SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); +SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); +SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *); +SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *); +SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *); + +/* Functions used to truncate the database file. */ +SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); + +#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) +SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *); +#endif + +/* Functions to support testing and debugging. */ +#if !defined(NDEBUG) || defined(SQLITE_TEST) +SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); +SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); +#endif +#ifdef SQLITE_TEST +SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); +SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); + void disable_simulated_io_errors(void); + void enable_simulated_io_errors(void); +#else +# define disable_simulated_io_errors() +# define enable_simulated_io_errors() +#endif + +#endif /* _PAGER_H_ */ + +/************** End of pager.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include pcache.h in the middle of sqliteInt.h ****************/ +/************** Begin file pcache.h ******************************************/ +/* +** 2008 August 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. +*/ + +#ifndef _PCACHE_H_ + +typedef struct PgHdr PgHdr; +typedef struct PCache PCache; + +/* +** Every page in the cache is controlled by an instance of the following +** structure. +*/ +struct PgHdr { + sqlite3_pcache_page *pPage; /* Pcache object page handle */ + void *pData; /* Page data */ + void *pExtra; /* Extra content */ + PgHdr *pDirty; /* Transient list of dirty pages */ + Pager *pPager; /* The pager this page is part of */ + Pgno pgno; /* Page number for this page */ +#ifdef SQLITE_CHECK_PAGES + u32 pageHash; /* Hash of page content */ +#endif + u16 flags; /* PGHDR flags defined below */ + + /********************************************************************** + ** Elements above are public. All that follows is private to pcache.c + ** and should not be accessed by other modules. + */ + i16 nRef; /* Number of users of this page */ + PCache *pCache; /* Cache that owns this page */ + + PgHdr *pDirtyNext; /* Next element in list of dirty pages */ + PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ +}; + +/* Bit values for PgHdr.flags */ +#define PGHDR_DIRTY 0x002 /* Page has changed */ +#define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before + ** writing this page to the database */ +#define PGHDR_NEED_READ 0x008 /* Content is unread */ +#define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */ +#define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */ + +#define PGHDR_MMAP 0x040 /* This is an mmap page object */ + +/* Initialize and shutdown the page cache subsystem */ +SQLITE_PRIVATE int sqlite3PcacheInitialize(void); +SQLITE_PRIVATE void sqlite3PcacheShutdown(void); + +/* Page cache buffer management: +** These routines implement SQLITE_CONFIG_PAGECACHE. +*/ +SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); + +/* Create a new pager cache. +** Under memory stress, invoke xStress to try to make pages clean. +** Only clean and unpinned pages can be reclaimed. +*/ +SQLITE_PRIVATE void sqlite3PcacheOpen( + int szPage, /* Size of every page */ + int szExtra, /* Extra space associated with each page */ + int bPurgeable, /* True if pages are on backing store */ + int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ + void *pStress, /* Argument to xStress */ + PCache *pToInit /* Preallocated space for the PCache */ +); + +/* Modify the page-size after the cache has been created. */ +SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int); + +/* Return the size in bytes of a PCache object. Used to preallocate +** storage space. +*/ +SQLITE_PRIVATE int sqlite3PcacheSize(void); + +/* One release per successful fetch. Page is pinned until released. +** Reference counted. +*/ +SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**); +SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); + +SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ +SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ +SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ +SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ + +/* Change a page number. Used by incr-vacuum. */ +SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); + +/* Remove all pages with pgno>x. Reset the cache if x==0 */ +SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); + +/* Get a list of all dirty pages in the cache, sorted by page number */ +SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); + +/* Reset and close the cache object */ +SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); + +/* Clear flags from pages of the page cache */ +SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); + +/* Discard the contents of the cache */ +SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); + +/* Return the total number of outstanding page references */ +SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); + +/* Increment the reference count of an existing page */ +SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); + +SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); + +/* Return the total number of pages stored in the cache */ +SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); + +#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) +/* Iterate through all dirty pages currently stored in the cache. This +** interface is only available if SQLITE_CHECK_PAGES is defined when the +** library is built. +*/ +SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); +#endif + +/* Set and get the suggested cache-size for the specified pager-cache. +** +** If no global maximum is configured, then the system attempts to limit +** the total number of pages cached by purgeable pager-caches to the sum +** of the suggested cache-sizes. +*/ +SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); +#endif + +/* Free up as much memory as possible from the page cache */ +SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*); + +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT +/* Try to return memory used by the pcache module to the main memory heap */ +SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); +#endif + +#ifdef SQLITE_TEST +SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); +#endif + +SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); + +#endif /* _PCACHE_H_ */ + +/************** End of pcache.h **********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + +/************** Include os.h in the middle of sqliteInt.h ********************/ +/************** Begin file os.h **********************************************/ +/* +** 2001 September 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file (together with is companion C source-code file +** "os.c") attempt to abstract the underlying operating system so that +** the SQLite library will work on both POSIX and windows systems. +** +** This header file is #include-ed by sqliteInt.h and thus ends up +** being included by every source file. +*/ +#ifndef _SQLITE_OS_H_ +#define _SQLITE_OS_H_ + +/* +** Figure out if we are dealing with Unix, Windows, or some other +** operating system. After the following block of preprocess macros, +** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER +** will defined to either 1 or 0. One of the four will be 1. The other +** three will be 0. +*/ +#if defined(SQLITE_OS_OTHER) +# if SQLITE_OS_OTHER==1 +# undef SQLITE_OS_UNIX +# define SQLITE_OS_UNIX 0 +# undef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# undef SQLITE_OS_RTTHREAD +# define SQLITE_OS_RTTHREAD 1 +# else +# undef SQLITE_OS_OTHER +# endif +#endif +#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) +# define SQLITE_OS_OTHER 0 +# ifndef SQLITE_OS_WIN +# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) +# define SQLITE_OS_WIN 1 +# define SQLITE_OS_UNIX 0 +# else +# define SQLITE_OS_WIN 0 +# define SQLITE_OS_UNIX 1 +# endif +# else +# define SQLITE_OS_UNIX 0 +# endif +#else +# ifndef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# endif +#endif + +#if SQLITE_OS_WIN +# include +#endif + +/* +** Determine if we are dealing with Windows NT. +** +** We ought to be able to determine if we are compiling for win98 or winNT +** using the _WIN32_WINNT macro as follows: +** +** #if defined(_WIN32_WINNT) +** # define SQLITE_OS_WINNT 1 +** #else +** # define SQLITE_OS_WINNT 0 +** #endif +** +** However, vs2005 does not set _WIN32_WINNT by default, as it ought to, +** so the above test does not work. We'll just assume that everything is +** winNT unless the programmer explicitly says otherwise by setting +** SQLITE_OS_WINNT to 0. +*/ +#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT) +# define SQLITE_OS_WINNT 1 +#endif + +/* +** Determine if we are dealing with WindowsCE - which has a much +** reduced API. +*/ +#if defined(_WIN32_WCE) +# define SQLITE_OS_WINCE 1 +#else +# define SQLITE_OS_WINCE 0 +#endif + +/* +** Determine if we are dealing with WinRT, which provides only a subset of +** the full Win32 API. +*/ +#if !defined(SQLITE_OS_WINRT) +# define SQLITE_OS_WINRT 0 +#endif + +/* If the SET_FULLSYNC macro is not defined above, then make it +** a no-op +*/ +#ifndef SET_FULLSYNC +# define SET_FULLSYNC(x,y) +#endif + +/* +** The default size of a disk sector +*/ +#ifndef SQLITE_DEFAULT_SECTOR_SIZE +# define SQLITE_DEFAULT_SECTOR_SIZE 4096 +#endif + +/* +** Temporary files are named starting with this prefix followed by 16 random +** alphanumeric characters, and no file extension. They are stored in the +** OS's standard temporary file directory, and are deleted prior to exit. +** If sqlite is being embedded in another program, you may wish to change the +** prefix to reflect your program's name, so that if your program exits +** prematurely, old temporary files can be easily identified. This can be done +** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. +** +** 2006-10-31: The default prefix used to be "sqlite_". But then +** Mcafee started using SQLite in their anti-virus product and it +** started putting files with the "sqlite" name in the c:/temp folder. +** This annoyed many windows users. Those users would then do a +** Google search for "sqlite", find the telephone numbers of the +** developers and call to wake them up at night and complain. +** For this reason, the default name prefix is changed to be "sqlite" +** spelled backwards. So the temp files are still identified, but +** anybody smart enough to figure out the code is also likely smart +** enough to know that calling the developer will not help get rid +** of the file. +*/ +#ifndef SQLITE_TEMP_FILE_PREFIX +# define SQLITE_TEMP_FILE_PREFIX "etilqs_" +#endif + +/* +** The following values may be passed as the second argument to +** sqlite3OsLock(). The various locks exhibit the following semantics: +** +** SHARED: Any number of processes may hold a SHARED lock simultaneously. +** RESERVED: A single process may hold a RESERVED lock on a file at +** any time. Other processes may hold and obtain new SHARED locks. +** PENDING: A single process may hold a PENDING lock on a file at +** any one time. Existing SHARED locks may persist, but no new +** SHARED locks may be obtained by other processes. +** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. +** +** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a +** process that requests an EXCLUSIVE lock may actually obtain a PENDING +** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to +** sqlite3OsLock(). +*/ +#define NO_LOCK 0 +#define SHARED_LOCK 1 +#define RESERVED_LOCK 2 +#define PENDING_LOCK 3 +#define EXCLUSIVE_LOCK 4 + +/* +** File Locking Notes: (Mostly about windows but also some info for Unix) +** +** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because +** those functions are not available. So we use only LockFile() and +** UnlockFile(). +** +** LockFile() prevents not just writing but also reading by other processes. +** A SHARED_LOCK is obtained by locking a single randomly-chosen +** byte out of a specific range of bytes. The lock byte is obtained at +** random so two separate readers can probably access the file at the +** same time, unless they are unlucky and choose the same lock byte. +** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. +** There can only be one writer. A RESERVED_LOCK is obtained by locking +** a single byte of the file that is designated as the reserved lock byte. +** A PENDING_LOCK is obtained by locking a designated byte different from +** the RESERVED_LOCK byte. +** +** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, +** which means we can use reader/writer locks. When reader/writer locks +** are used, the lock is placed on the same range of bytes that is used +** for probabilistic locking in Win95/98/ME. Hence, the locking scheme +** will support two or more Win95 readers or two or more WinNT readers. +** But a single Win95 reader will lock out all WinNT readers and a single +** WinNT reader will lock out all other Win95 readers. +** +** The following #defines specify the range of bytes used for locking. +** SHARED_SIZE is the number of bytes available in the pool from which +** a random byte is selected for a shared lock. The pool of bytes for +** shared locks begins at SHARED_FIRST. +** +** The same locking strategy and +** byte ranges are used for Unix. This leaves open the possiblity of having +** clients on win95, winNT, and unix all talking to the same shared file +** and all locking correctly. To do so would require that samba (or whatever +** tool is being used for file sharing) implements locks correctly between +** windows and unix. I'm guessing that isn't likely to happen, but by +** using the same locking range we are at least open to the possibility. +** +** Locking in windows is manditory. For this reason, we cannot store +** actual data in the bytes used for locking. The pager never allocates +** the pages involved in locking therefore. SHARED_SIZE is selected so +** that all locks will fit on a single page even at the minimum page size. +** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE +** is set high so that we don't have to allocate an unused page except +** for very large databases. But one should test the page skipping logic +** by setting PENDING_BYTE low and running the entire regression suite. +** +** Changing the value of PENDING_BYTE results in a subtly incompatible +** file format. Depending on how it is changed, you might not notice +** the incompatibility right away, even running a full regression test. +** The default location of PENDING_BYTE is the first byte past the +** 1GB boundary. +** +*/ +#ifdef SQLITE_OMIT_WSD +# define PENDING_BYTE (0x40000000) +#else +# define PENDING_BYTE sqlite3PendingByte +#endif +#define RESERVED_BYTE (PENDING_BYTE+1) +#define SHARED_FIRST (PENDING_BYTE+2) +#define SHARED_SIZE 510 + +/* +** Wrapper around OS specific sqlite3_os_init() function. +*/ +SQLITE_PRIVATE int sqlite3OsInit(void); + +/* +** Functions for accessing sqlite3_file methods +*/ +SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*); +SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); +SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); +SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); +SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); +SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); +SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); +SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*); +#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 +SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); +SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int); +SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int); +SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **); +SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *); + + +/* +** Functions for accessing sqlite3_vfs methods +*/ +SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); +SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); +SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); +SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); +SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); +SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); +SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); +SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); +SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); + +/* +** Convenience functions for opening and closing files using +** sqlite3_malloc() to obtain space for the file-handle structure. +*/ +SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); +SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); + +#endif /* _SQLITE_OS_H_ */ + +/************** End of os.h **************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include mutex.h in the middle of sqliteInt.h *****************/ +/************** Begin file mutex.h *******************************************/ +/* +** 2007 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the common header for all mutex implementations. +** The sqliteInt.h header #includes this file so that it is available +** to all source files. We break it out in an effort to keep the code +** better organized. +** +** NOTE: source files should *not* #include this header file directly. +** Source files should #include the sqliteInt.h file and let that file +** include this one indirectly. +*/ + + +/* +** Figure out what version of the code to use. The choices are +** +** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The +** mutexes implemention cannot be overridden +** at start-time. +** +** SQLITE_MUTEX_NOOP For single-threaded applications. No +** mutual exclusion is provided. But this +** implementation can be overridden at +** start-time. +** +** SQLITE_MUTEX_RTTHREAD For multi-threaded applications on rt-thread. +** +** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. +** +** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. +*/ +#if !SQLITE_THREADSAFE +# define SQLITE_MUTEX_OMIT +#endif +#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) +# if SQLITE_OS_UNIX +# define SQLITE_MUTEX_PTHREADS +# elif SQLITE_OS_WIN +# define SQLITE_MUTEX_W32 +# elif SQLITE_OS_RTTHREAD +# define SQLITE_MUTEX_RTTHREAD +# else +# define SQLITE_MUTEX_NOOP +# endif +#endif + +#ifdef SQLITE_MUTEX_OMIT +/* +** If this is a no-op implementation, implement everything as macros. +*/ +#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) +#define sqlite3_mutex_free(X) +#define sqlite3_mutex_enter(X) +#define sqlite3_mutex_try(X) SQLITE_OK +#define sqlite3_mutex_leave(X) +#define sqlite3_mutex_held(X) ((void)(X),1) +#define sqlite3_mutex_notheld(X) ((void)(X),1) +#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) +#define sqlite3MutexInit() SQLITE_OK +#define sqlite3MutexEnd() +#define MUTEX_LOGIC(X) +#else +#define MUTEX_LOGIC(X) X +#endif /* defined(SQLITE_MUTEX_OMIT) */ + +/************** End of mutex.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + + +/* +** Each database file to be accessed by the system is an instance +** of the following structure. There are normally two of these structures +** in the sqlite.aDb[] array. aDb[0] is the main database file and +** aDb[1] is the database file used to hold temporary tables. Additional +** databases may be attached. +*/ +struct Db { + char *zName; /* Name of this database */ + Btree *pBt; /* The B*Tree structure for this database file */ + u8 safety_level; /* How aggressive at syncing data to disk */ + Schema *pSchema; /* Pointer to database schema (possibly shared) */ +}; + +/* +** An instance of the following structure stores a database schema. +** +** Most Schema objects are associated with a Btree. The exception is +** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing. +** In shared cache mode, a single Schema object can be shared by multiple +** Btrees that refer to the same underlying BtShared object. +** +** Schema objects are automatically deallocated when the last Btree that +** references them is destroyed. The TEMP Schema is manually freed by +** sqlite3_close(). +* +** A thread must be holding a mutex on the corresponding Btree in order +** to access Schema content. This implies that the thread must also be +** holding a mutex on the sqlite3 connection pointer that owns the Btree. +** For a TEMP Schema, only the connection mutex is required. +*/ +struct Schema { + int schema_cookie; /* Database schema version number for this file */ + int iGeneration; /* Generation counter. Incremented with each change */ + Hash tblHash; /* All tables indexed by name */ + Hash idxHash; /* All (named) indices indexed by name */ + Hash trigHash; /* All triggers indexed by name */ + Hash fkeyHash; /* All foreign keys by referenced table name */ + Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ + u8 file_format; /* Schema format version for this file */ + u8 enc; /* Text encoding used by this database */ + u16 flags; /* Flags associated with this schema */ + int cache_size; /* Number of pages to use in the cache */ +}; + +/* +** These macros can be used to test, set, or clear bits in the +** Db.pSchema->flags field. +*/ +#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) +#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) +#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) +#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) + +/* +** Allowed values for the DB.pSchema->flags field. +** +** The DB_SchemaLoaded flag is set after the database schema has been +** read into internal hash tables. +** +** DB_UnresetViews means that one or more views have column names that +** have been filled out. If the schema changes, these column names might +** changes and so the view will need to be reset. +*/ +#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ +#define DB_UnresetViews 0x0002 /* Some views have defined column names */ +#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ + +/* +** The number of different kinds of things that can be limited +** using the sqlite3_limit() interface. +*/ +#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1) + +/* +** Lookaside malloc is a set of fixed-size buffers that can be used +** to satisfy small transient memory allocation requests for objects +** associated with a particular database connection. The use of +** lookaside malloc provides a significant performance enhancement +** (approx 10%) by avoiding numerous malloc/free requests while parsing +** SQL statements. +** +** The Lookaside structure holds configuration information about the +** lookaside malloc subsystem. Each available memory allocation in +** the lookaside subsystem is stored on a linked list of LookasideSlot +** objects. +** +** Lookaside allocations are only allowed for objects that are associated +** with a particular database connection. Hence, schema information cannot +** be stored in lookaside because in shared cache mode the schema information +** is shared by multiple database connections. Therefore, while parsing +** schema information, the Lookaside.bEnabled flag is cleared so that +** lookaside allocations are not used to construct the schema objects. +*/ +struct Lookaside { + u16 sz; /* Size of each buffer in bytes */ + u8 bEnabled; /* False to disable new lookaside allocations */ + u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ + int nOut; /* Number of buffers currently checked out */ + int mxOut; /* Highwater mark for nOut */ + int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ + LookasideSlot *pFree; /* List of available buffers */ + void *pStart; /* First byte of available memory space */ + void *pEnd; /* First byte past end of available space */ +}; +struct LookasideSlot { + LookasideSlot *pNext; /* Next buffer in the list of free buffers */ +}; + +/* +** A hash table for function definitions. +** +** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. +** Collisions are on the FuncDef.pHash chain. +*/ +struct FuncDefHash { + FuncDef *a[23]; /* Hash table for functions */ +}; + +/* +** Each database connection is an instance of the following structure. +*/ +struct sqlite3 { + sqlite3_vfs *pVfs; /* OS Interface */ + struct Vdbe *pVdbe; /* List of active virtual machines */ + CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ + sqlite3_mutex *mutex; /* Connection mutex */ + Db *aDb; /* All backends */ + int nDb; /* Number of backends currently in use */ + int flags; /* Miscellaneous flags. See below */ + i64 lastRowid; /* ROWID of most recent insert (see above) */ + i64 szMmap; /* Default mmap_size setting */ + unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ + int errCode; /* Most recent error code (SQLITE_*) */ + int errMask; /* & result codes with this before returning */ + u16 dbOptFlags; /* Flags to enable/disable optimizations */ + u8 autoCommit; /* The auto-commit flag. */ + u8 temp_store; /* 1: file 2: memory 0: default */ + u8 mallocFailed; /* True if we have seen a malloc failure */ + u8 dfltLockMode; /* Default locking-mode for attached dbs */ + signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ + u8 suppressErr; /* Do not issue error messages if true */ + u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ + u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ + int nextPagesize; /* Pagesize after VACUUM if >0 */ + u32 magic; /* Magic number for detect library misuse */ + int nChange; /* Value returned by sqlite3_changes() */ + int nTotalChange; /* Value returned by sqlite3_total_changes() */ + int aLimit[SQLITE_N_LIMIT]; /* Limits */ + struct sqlite3InitInfo { /* Information used during initialization */ + int newTnum; /* Rootpage of table being initialized */ + u8 iDb; /* Which db file is being initialized */ + u8 busy; /* TRUE if currently initializing */ + u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ + } init; + int nVdbeActive; /* Number of VDBEs currently running */ + int nVdbeRead; /* Number of active VDBEs that read or write */ + int nVdbeWrite; /* Number of active VDBEs that read and write */ + int nVdbeExec; /* Number of nested calls to VdbeExec() */ + int nExtension; /* Number of loaded extensions */ + void **aExtension; /* Array of shared library handles */ + void (*xTrace)(void*,const char*); /* Trace function */ + void *pTraceArg; /* Argument to the trace function */ + void (*xProfile)(void*,const char*,u64); /* Profiling function */ + void *pProfileArg; /* Argument to profile function */ + void *pCommitArg; /* Argument to xCommitCallback() */ + int (*xCommitCallback)(void*); /* Invoked at every commit. */ + void *pRollbackArg; /* Argument to xRollbackCallback() */ + void (*xRollbackCallback)(void*); /* Invoked at every commit. */ + void *pUpdateArg; + void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); +#ifndef SQLITE_OMIT_WAL + int (*xWalCallback)(void *, sqlite3 *, const char *, int); + void *pWalArg; +#endif + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); + void *pCollNeededArg; + sqlite3_value *pErr; /* Most recent error message */ + union { + volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ + double notUsed1; /* Spacer */ + } u1; + Lookaside lookaside; /* Lookaside malloc configuration */ +#ifndef SQLITE_OMIT_AUTHORIZATION + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); + /* Access authorization function */ + void *pAuthArg; /* 1st argument to the access auth function */ +#endif +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + int (*xProgress)(void *); /* The progress callback */ + void *pProgressArg; /* Argument to the progress callback */ + unsigned nProgressOps; /* Number of opcodes for progress callback */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + int nVTrans; /* Allocated size of aVTrans */ + Hash aModule; /* populated by sqlite3_create_module() */ + VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ + VTable **aVTrans; /* Virtual tables with open transactions */ + VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ +#endif + FuncDefHash aFunc; /* Hash table of connection functions */ + Hash aCollSeq; /* All collating sequences */ + BusyHandler busyHandler; /* Busy callback */ + Db aDbStatic[2]; /* Static space for the 2 default backends */ + Savepoint *pSavepoint; /* List of active savepoints */ + int busyTimeout; /* Busy handler timeout, in msec */ + int nSavepoint; /* Number of non-transaction savepoints */ + int nStatement; /* Number of nested statement-transactions */ + i64 nDeferredCons; /* Net deferred constraints this transaction. */ + i64 nDeferredImmCons; /* Net deferred immediate constraints */ + int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + /* The following variables are all protected by the STATIC_MASTER + ** mutex, not by sqlite3.mutex. They are used by code in notify.c. + ** + ** When X.pUnlockConnection==Y, that means that X is waiting for Y to + ** unlock so that it can proceed. + ** + ** When X.pBlockingConnection==Y, that means that something that X tried + ** tried to do recently failed with an SQLITE_LOCKED error due to locks + ** held by Y. + */ + sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ + sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ + void *pUnlockArg; /* Argument to xUnlockNotify */ + void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ + sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ +#endif +}; + +/* +** A macro to discover the encoding of a database. +*/ +#define ENC(db) ((db)->aDb[0].pSchema->enc) + +/* +** Possible values for the sqlite3.flags. +*/ +#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ +#define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */ +#define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */ +#define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */ +#define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */ +#define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */ +#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ +#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ + /* DELETE, or UPDATE and return */ + /* the count using a callback. */ +#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ + /* result set is empty */ +#define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */ +#define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */ +#define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */ +#define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */ +#define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */ +#define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */ +#define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */ +#define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */ +#define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */ +#define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */ +#define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */ +#define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */ +#define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */ +#define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */ +#define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */ +#define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */ +#define SQLITE_QueryOnly 0x02000000 /* Disable database changes */ + + +/* +** Bits of the sqlite3.dbOptFlags field that are used by the +** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to +** selectively disable various optimizations. +*/ +#define SQLITE_QueryFlattener 0x0001 /* Query flattening */ +#define SQLITE_ColumnCache 0x0002 /* Column cache */ +#define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */ +#define SQLITE_FactorOutConst 0x0008 /* Constant factoring */ +#define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */ +#define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */ +#define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */ +#define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */ +#define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */ +#define SQLITE_Transitive 0x0200 /* Transitive constraints */ +#define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */ +#define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */ +#define SQLITE_AdjustOutEst 0x1000 /* Adjust output estimates using WHERE */ +#define SQLITE_AllOpts 0xffff /* All optimizations */ + +/* +** Macros for testing whether or not optimizations are enabled or disabled. +*/ +#ifndef SQLITE_OMIT_BUILTIN_TEST +#define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0) +#define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0) +#else +#define OptimizationDisabled(db, mask) 0 +#define OptimizationEnabled(db, mask) 1 +#endif + +/* +** Possible values for the sqlite.magic field. +** The numbers are obtained at random and have no special meaning, other +** than being distinct from one another. +*/ +#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ +#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ +#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ +#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ +#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ +#define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */ + +/* +** Each SQL function is defined by an instance of the following +** structure. A pointer to this structure is stored in the sqlite.aFunc +** hash table. When multiple functions have the same name, the hash table +** points to a linked list of these structures. +*/ +struct FuncDef { + i16 nArg; /* Number of arguments. -1 means unlimited */ + u16 funcFlags; /* Some combination of SQLITE_FUNC_* */ + void *pUserData; /* User data parameter */ + FuncDef *pNext; /* Next function with same name */ + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ + void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ + void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */ + char *zName; /* SQL name of the function. */ + FuncDef *pHash; /* Next with a different name but the same hash */ + FuncDestructor *pDestructor; /* Reference counted destructor function */ +}; + +/* +** This structure encapsulates a user-function destructor callback (as +** configured using create_function_v2()) and a reference counter. When +** create_function_v2() is called to create a function with a destructor, +** a single object of this type is allocated. FuncDestructor.nRef is set to +** the number of FuncDef objects created (either 1 or 3, depending on whether +** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor +** member of each of the new FuncDef objects is set to point to the allocated +** FuncDestructor. +** +** Thereafter, when one of the FuncDef objects is deleted, the reference +** count on this object is decremented. When it reaches 0, the destructor +** is invoked and the FuncDestructor structure freed. +*/ +struct FuncDestructor { + int nRef; + void (*xDestroy)(void *); + void *pUserData; +}; + +/* +** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF +** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There +** are assert() statements in the code to verify this. +*/ +#define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */ +#define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */ +#define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */ +#define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */ +#define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */ +#define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */ +#define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */ +#define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */ +#define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */ +#define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */ + +/* +** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are +** used to create the initializers for the FuncDef structures. +** +** FUNCTION(zName, nArg, iArg, bNC, xFunc) +** Used to create a scalar function definition of a function zName +** implemented by C function xFunc that accepts nArg arguments. The +** value passed as iArg is cast to a (void*) and made available +** as the user-data (sqlite3_user_data()) for the function. If +** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. +** +** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) +** Used to create an aggregate function definition implemented by +** the C functions xStep and xFinal. The first four parameters +** are interpreted in the same way as the first 4 parameters to +** FUNCTION(). +** +** LIKEFUNC(zName, nArg, pArg, flags) +** Used to create a scalar function definition of a function zName +** that accepts nArg arguments and is implemented by a call to C +** function likeFunc. Argument pArg is cast to a (void *) and made +** available as the function user-data (sqlite3_user_data()). The +** FuncDef.flags variable is set to the value passed as the flags +** parameter. +*/ +#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} +#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \ + {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \ + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} +#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ + pArg, 0, xFunc, 0, 0, #zName, 0, 0} +#define LIKEFUNC(zName, nArg, arg, flags) \ + {nArg, SQLITE_UTF8|flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0} +#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ + {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \ + SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0} + +/* +** All current savepoints are stored in a linked list starting at +** sqlite3.pSavepoint. The first element in the list is the most recently +** opened savepoint. Savepoints are added to the list by the vdbe +** OP_Savepoint instruction. +*/ +struct Savepoint { + char *zName; /* Savepoint name (nul-terminated) */ + i64 nDeferredCons; /* Number of deferred fk violations */ + i64 nDeferredImmCons; /* Number of deferred imm fk. */ + Savepoint *pNext; /* Parent savepoint (if any) */ +}; + +/* +** The following are used as the second parameter to sqlite3Savepoint(), +** and as the P1 argument to the OP_Savepoint instruction. +*/ +#define SAVEPOINT_BEGIN 0 +#define SAVEPOINT_RELEASE 1 +#define SAVEPOINT_ROLLBACK 2 + + +/* +** Each SQLite module (virtual table definition) is defined by an +** instance of the following structure, stored in the sqlite3.aModule +** hash table. +*/ +struct Module { + const sqlite3_module *pModule; /* Callback pointers */ + const char *zName; /* Name passed to create_module() */ + void *pAux; /* pAux passed to create_module() */ + void (*xDestroy)(void *); /* Module destructor function */ +}; + +/* +** information about each column of an SQL table is held in an instance +** of this structure. +*/ +struct Column { + char *zName; /* Name of this column */ + Expr *pDflt; /* Default value of this column */ + char *zDflt; /* Original text of the default value */ + char *zType; /* Data type for this column */ + char *zColl; /* Collating sequence. If NULL, use the default */ + u8 notNull; /* An OE_ code for handling a NOT NULL constraint */ + char affinity; /* One of the SQLITE_AFF_... values */ + u8 szEst; /* Estimated size of this column. INT==1 */ + u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */ +}; + +/* Allowed values for Column.colFlags: +*/ +#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */ +#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */ + +/* +** A "Collating Sequence" is defined by an instance of the following +** structure. Conceptually, a collating sequence consists of a name and +** a comparison routine that defines the order of that sequence. +** +** If CollSeq.xCmp is NULL, it means that the +** collating sequence is undefined. Indices built on an undefined +** collating sequence may not be read or written. +*/ +struct CollSeq { + char *zName; /* Name of the collating sequence, UTF-8 encoded */ + u8 enc; /* Text encoding handled by xCmp() */ + void *pUser; /* First argument to xCmp() */ + int (*xCmp)(void*,int, const void*, int, const void*); + void (*xDel)(void*); /* Destructor for pUser */ +}; + +/* +** A sort order can be either ASC or DESC. +*/ +#define SQLITE_SO_ASC 0 /* Sort in ascending order */ +#define SQLITE_SO_DESC 1 /* Sort in ascending order */ + +/* +** Column affinity types. +** +** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and +** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve +** the speed a little by numbering the values consecutively. +** +** But rather than start with 0 or 1, we begin with 'a'. That way, +** when multiple affinity types are concatenated into a string and +** used as the P4 operand, they will be more readable. +** +** Note also that the numeric types are grouped together so that testing +** for a numeric type is a single comparison. +*/ +#define SQLITE_AFF_TEXT 'a' +#define SQLITE_AFF_NONE 'b' +#define SQLITE_AFF_NUMERIC 'c' +#define SQLITE_AFF_INTEGER 'd' +#define SQLITE_AFF_REAL 'e' + +#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) + +/* +** The SQLITE_AFF_MASK values masks off the significant bits of an +** affinity value. +*/ +#define SQLITE_AFF_MASK 0x67 + +/* +** Additional bit values that can be ORed with an affinity without +** changing the affinity. +*/ +#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ +#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ +#define SQLITE_NULLEQ 0x80 /* NULL=NULL */ + +/* +** An object of this type is created for each virtual table present in +** the database schema. +** +** If the database schema is shared, then there is one instance of this +** structure for each database connection (sqlite3*) that uses the shared +** schema. This is because each database connection requires its own unique +** instance of the sqlite3_vtab* handle used to access the virtual table +** implementation. sqlite3_vtab* handles can not be shared between +** database connections, even when the rest of the in-memory database +** schema is shared, as the implementation often stores the database +** connection handle passed to it via the xConnect() or xCreate() method +** during initialization internally. This database connection handle may +** then be used by the virtual table implementation to access real tables +** within the database. So that they appear as part of the callers +** transaction, these accesses need to be made via the same database +** connection as that used to execute SQL operations on the virtual table. +** +** All VTable objects that correspond to a single table in a shared +** database schema are initially stored in a linked-list pointed to by +** the Table.pVTable member variable of the corresponding Table object. +** When an sqlite3_prepare() operation is required to access the virtual +** table, it searches the list for the VTable that corresponds to the +** database connection doing the preparing so as to use the correct +** sqlite3_vtab* handle in the compiled query. +** +** When an in-memory Table object is deleted (for example when the +** schema is being reloaded for some reason), the VTable objects are not +** deleted and the sqlite3_vtab* handles are not xDisconnect()ed +** immediately. Instead, they are moved from the Table.pVTable list to +** another linked list headed by the sqlite3.pDisconnect member of the +** corresponding sqlite3 structure. They are then deleted/xDisconnected +** next time a statement is prepared using said sqlite3*. This is done +** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. +** Refer to comments above function sqlite3VtabUnlockList() for an +** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect +** list without holding the corresponding sqlite3.mutex mutex. +** +** The memory for objects of this type is always allocated by +** sqlite3DbMalloc(), using the connection handle stored in VTable.db as +** the first argument. +*/ +struct VTable { + sqlite3 *db; /* Database connection associated with this table */ + Module *pMod; /* Pointer to module implementation */ + sqlite3_vtab *pVtab; /* Pointer to vtab instance */ + int nRef; /* Number of pointers to this structure */ + u8 bConstraint; /* True if constraints are supported */ + int iSavepoint; /* Depth of the SAVEPOINT stack */ + VTable *pNext; /* Next in linked list (see above) */ +}; + +/* +** Each SQL table is represented in memory by an instance of the +** following structure. +** +** Table.zName is the name of the table. The case of the original +** CREATE TABLE statement is stored, but case is not significant for +** comparisons. +** +** Table.nCol is the number of columns in this table. Table.aCol is a +** pointer to an array of Column structures, one for each column. +** +** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of +** the column that is that key. Otherwise Table.iPKey is negative. Note +** that the datatype of the PRIMARY KEY must be INTEGER for this field to +** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of +** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid +** is generated for each row of the table. TF_HasPrimaryKey is set if +** the table has any PRIMARY KEY, INTEGER or otherwise. +** +** Table.tnum is the page number for the root BTree page of the table in the +** database file. If Table.iDb is the index of the database table backend +** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that +** holds temporary tables and indices. If TF_Ephemeral is set +** then the table is stored in a file that is automatically deleted +** when the VDBE cursor to the table is closed. In this case Table.tnum +** refers VDBE cursor number that holds the table open, not to the root +** page number. Transient tables are used to hold the results of a +** sub-query that appears instead of a real table name in the FROM clause +** of a SELECT statement. +*/ +struct Table { + char *zName; /* Name of the table or view */ + Column *aCol; /* Information about each column */ + Index *pIndex; /* List of SQL indexes on this table. */ + Select *pSelect; /* NULL for tables. Points to definition if a view. */ + FKey *pFKey; /* Linked list of all foreign keys in this table */ + char *zColAff; /* String defining the affinity of each column */ +#ifndef SQLITE_OMIT_CHECK + ExprList *pCheck; /* All CHECK constraints */ +#endif + tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */ + int tnum; /* Root BTree node for this table (see note above) */ + i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */ + i16 nCol; /* Number of columns in this table */ + u16 nRef; /* Number of pointers to this Table */ + LogEst szTabRow; /* Estimated size of each table row in bytes */ + u8 tabFlags; /* Mask of TF_* values */ + u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ +#ifndef SQLITE_OMIT_ALTERTABLE + int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + int nModuleArg; /* Number of arguments to the module */ + char **azModuleArg; /* Text of all module args. [0] is module name */ + VTable *pVTable; /* List of VTable objects. */ +#endif + Trigger *pTrigger; /* List of triggers stored in pSchema */ + Schema *pSchema; /* Schema that contains this table */ + Table *pNextZombie; /* Next on the Parse.pZombieTab list */ +}; + +/* +** Allowed values for Tabe.tabFlags. +*/ +#define TF_Readonly 0x01 /* Read-only system table */ +#define TF_Ephemeral 0x02 /* An ephemeral table */ +#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ +#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ +#define TF_Virtual 0x10 /* Is a virtual table */ + + +/* +** Test to see whether or not a table is a virtual table. This is +** done as a macro so that it will be optimized out when virtual +** table support is omitted from the build. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE +# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) +# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) +#else +# define IsVirtual(X) 0 +# define IsHiddenColumn(X) 0 +#endif + +/* +** Each foreign key constraint is an instance of the following structure. +** +** A foreign key is associated with two tables. The "from" table is +** the table that contains the REFERENCES clause that creates the foreign +** key. The "to" table is the table that is named in the REFERENCES clause. +** Consider this example: +** +** CREATE TABLE ex1( +** a INTEGER PRIMARY KEY, +** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) +** ); +** +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". +** +** Each REFERENCES clause generates an instance of the following structure +** which is attached to the from-table. The to-table need not exist when +** the from-table is created. The existence of the to-table is not checked. +*/ +struct FKey { + Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ + FKey *pNextFrom; /* Next foreign key in pFrom */ + char *zTo; /* Name of table that the key points to (aka: Parent) */ + FKey *pNextTo; /* Next foreign key on table named zTo */ + FKey *pPrevTo; /* Previous foreign key on table named zTo */ + int nCol; /* Number of columns in this key */ + /* EV: R-30323-21917 */ + u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ + u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ + Trigger *apTrigger[2]; /* Triggers for aAction[] actions */ + struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ + int iFrom; /* Index of column in pFrom */ + char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ + } aCol[1]; /* One entry for each of nCol column s */ +}; + +/* +** SQLite supports many different ways to resolve a constraint +** error. ROLLBACK processing means that a constraint violation +** causes the operation in process to fail and for the current transaction +** to be rolled back. ABORT processing means the operation in process +** fails and any prior changes from that one operation are backed out, +** but the transaction is not rolled back. FAIL processing means that +** the operation in progress stops and returns an error code. But prior +** changes due to the same operation are not backed out and no rollback +** occurs. IGNORE means that the particular row that caused the constraint +** error is not inserted or updated. Processing continues and no error +** is returned. REPLACE means that preexisting database rows that caused +** a UNIQUE constraint violation are removed so that the new insert or +** update can proceed. Processing continues and no error is reported. +** +** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. +** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the +** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign +** key is set to NULL. CASCADE means that a DELETE or UPDATE of the +** referenced table row is propagated into the row that holds the +** foreign key. +** +** The following symbolic values are used to record which type +** of action to take. +*/ +#define OE_None 0 /* There is no constraint to check */ +#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ +#define OE_Abort 2 /* Back out changes but do no rollback transaction */ +#define OE_Fail 3 /* Stop the operation but leave all prior changes */ +#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ +#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ + +#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ +#define OE_SetNull 7 /* Set the foreign key value to NULL */ +#define OE_SetDflt 8 /* Set the foreign key value to its default */ +#define OE_Cascade 9 /* Cascade the changes */ + +#define OE_Default 10 /* Do whatever the default action is */ + + +/* +** An instance of the following structure is passed as the first +** argument to sqlite3VdbeKeyCompare and is used to control the +** comparison of the two index keys. +** +** Note that aSortOrder[] and aColl[] have nField+1 slots. There +** are nField slots for the columns of an index then one extra slot +** for the rowid at the end. +*/ +struct KeyInfo { + sqlite3 *db; /* The database connection */ + u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ + u16 nField; /* Maximum index for aColl[] and aSortOrder[] */ + u8 *aSortOrder; /* Sort order for each column. */ + CollSeq *aColl[1]; /* Collating sequence for each term of the key */ +}; + +/* +** An instance of the following structure holds information about a +** single index record that has already been parsed out into individual +** values. +** +** A record is an object that contains one or more fields of data. +** Records are used to store the content of a table row and to store +** the key of an index. A blob encoding of a record is created by +** the OP_MakeRecord opcode of the VDBE and is disassembled by the +** OP_Column opcode. +** +** This structure holds a record that has already been disassembled +** into its constituent fields. +*/ +struct UnpackedRecord { + KeyInfo *pKeyInfo; /* Collation and sort-order information */ + u16 nField; /* Number of entries in apMem[] */ + u8 flags; /* Boolean settings. UNPACKED_... below */ + i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ + Mem *aMem; /* Values */ +}; + +/* +** Allowed values of UnpackedRecord.flags +*/ +#define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */ +#define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */ +#define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */ + +/* +** Each SQL index is represented in memory by an +** instance of the following structure. +** +** The columns of the table that are to be indexed are described +** by the aiColumn[] field of this structure. For example, suppose +** we have the following table and index: +** +** CREATE TABLE Ex1(c1 int, c2 int, c3 text); +** CREATE INDEX Ex2 ON Ex1(c3,c1); +** +** In the Table structure describing Ex1, nCol==3 because there are +** three columns in the table. In the Index structure describing +** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. +** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the +** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. +** The second column to be indexed (c1) has an index of 0 in +** Ex1.aCol[], hence Ex2.aiColumn[1]==0. +** +** The Index.onError field determines whether or not the indexed columns +** must be unique and what to do if they are not. When Index.onError=OE_None, +** it means this is not a unique index. Otherwise it is a unique index +** and the value of Index.onError indicate the which conflict resolution +** algorithm to employ whenever an attempt is made to insert a non-unique +** element. +*/ +struct Index { + char *zName; /* Name of this index */ + int *aiColumn; /* Which columns are used by this index. 1st is 0 */ + tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */ + Table *pTable; /* The SQL table being indexed */ + char *zColAff; /* String defining the affinity of each column */ + Index *pNext; /* The next index associated with the same table */ + Schema *pSchema; /* Schema containing this index */ + u8 *aSortOrder; /* for each column: True==DESC, False==ASC */ + char **azColl; /* Array of collation sequence names for index */ + Expr *pPartIdxWhere; /* WHERE clause for partial indices */ + int tnum; /* DB Page containing root of this index */ + LogEst szIdxRow; /* Estimated average row size in bytes */ + u16 nColumn; /* Number of columns in table used by this index */ + u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ + unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */ + unsigned bUnordered:1; /* Use this index for == or IN queries only */ + unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + int nSample; /* Number of elements in aSample[] */ + int nSampleCol; /* Size of IndexSample.anEq[] and so on */ + tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */ + IndexSample *aSample; /* Samples of the left-most key */ +#endif +}; + +/* +** Each sample stored in the sqlite_stat3 table is represented in memory +** using a structure of this type. See documentation at the top of the +** analyze.c source file for additional information. +*/ +struct IndexSample { + void *p; /* Pointer to sampled record */ + int n; /* Size of record in bytes */ + tRowcnt *anEq; /* Est. number of rows where the key equals this sample */ + tRowcnt *anLt; /* Est. number of rows where key is less than this sample */ + tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */ +}; + +/* +** Each token coming out of the lexer is an instance of +** this structure. Tokens are also used as part of an expression. +** +** Note if Token.z==0 then Token.dyn and Token.n are undefined and +** may contain random values. Do not make any assumptions about Token.dyn +** and Token.n when Token.z==0. +*/ +struct Token { + const char *z; /* Text of the token. Not NULL-terminated! */ + unsigned int n; /* Number of characters in this token */ +}; + +/* +** An instance of this structure contains information needed to generate +** code for a SELECT that contains aggregate functions. +** +** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a +** pointer to this structure. The Expr.iColumn field is the index in +** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate +** code for that node. +** +** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the +** original Select structure that describes the SELECT statement. These +** fields do not need to be freed when deallocating the AggInfo structure. +*/ +struct AggInfo { + u8 directMode; /* Direct rendering mode means take data directly + ** from source tables rather than from accumulators */ + u8 useSortingIdx; /* In direct mode, reference the sorting index rather + ** than the source table */ + int sortingIdx; /* Cursor number of the sorting index */ + int sortingIdxPTab; /* Cursor number of pseudo-table */ + int nSortingColumn; /* Number of columns in the sorting index */ + ExprList *pGroupBy; /* The group by clause */ + struct AggInfo_col { /* For each column used in source tables */ + Table *pTab; /* Source table */ + int iTable; /* Cursor number of the source table */ + int iColumn; /* Column number within the source table */ + int iSorterColumn; /* Column number in the sorting index */ + int iMem; /* Memory location that acts as accumulator */ + Expr *pExpr; /* The original expression */ + } *aCol; + int nColumn; /* Number of used entries in aCol[] */ + int nAccumulator; /* Number of columns that show through to the output. + ** Additional columns are used only as parameters to + ** aggregate functions */ + struct AggInfo_func { /* For each aggregate function */ + Expr *pExpr; /* Expression encoding the function */ + FuncDef *pFunc; /* The aggregate function implementation */ + int iMem; /* Memory location that acts as accumulator */ + int iDistinct; /* Ephemeral table used to enforce DISTINCT */ + } *aFunc; + int nFunc; /* Number of entries in aFunc[] */ +}; + +/* +** The datatype ynVar is a signed integer, either 16-bit or 32-bit. +** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater +** than 32767 we have to make it 32-bit. 16-bit is preferred because +** it uses less memory in the Expr object, which is a big memory user +** in systems with lots of prepared statements. And few applications +** need more than about 10 or 20 variables. But some extreme users want +** to have prepared statements with over 32767 variables, and for them +** the option is available (at compile-time). +*/ +#if SQLITE_MAX_VARIABLE_NUMBER<=32767 +typedef i16 ynVar; +#else +typedef int ynVar; +#endif + +/* +** Each node of an expression in the parse tree is an instance +** of this structure. +** +** Expr.op is the opcode. The integer parser token codes are reused +** as opcodes here. For example, the parser defines TK_GE to be an integer +** code representing the ">=" operator. This same integer code is reused +** to represent the greater-than-or-equal-to operator in the expression +** tree. +** +** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, +** or TK_STRING), then Expr.token contains the text of the SQL literal. If +** the expression is a variable (TK_VARIABLE), then Expr.token contains the +** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), +** then Expr.token contains the name of the function. +** +** Expr.pRight and Expr.pLeft are the left and right subexpressions of a +** binary operator. Either or both may be NULL. +** +** Expr.x.pList is a list of arguments if the expression is an SQL function, +** a CASE expression or an IN expression of the form " IN (, ...)". +** Expr.x.pSelect is used if the expression is a sub-select or an expression of +** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the +** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is +** valid. +** +** An expression of the form ID or ID.ID refers to a column in a table. +** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is +** the integer cursor number of a VDBE cursor pointing to that table and +** Expr.iColumn is the column number for the specific column. If the +** expression is used as a result in an aggregate SELECT, then the +** value is also stored in the Expr.iAgg column in the aggregate so that +** it can be accessed after all aggregates are computed. +** +** If the expression is an unbound variable marker (a question mark +** character '?' in the original SQL) then the Expr.iTable holds the index +** number for that variable. +** +** If the expression is a subquery then Expr.iColumn holds an integer +** register number containing the result of the subquery. If the +** subquery gives a constant result, then iTable is -1. If the subquery +** gives a different answer at different times during statement processing +** then iTable is the address of a subroutine that computes the subquery. +** +** If the Expr is of type OP_Column, and the table it is selecting from +** is a disk table or the "old.*" pseudo-table, then pTab points to the +** corresponding table definition. +** +** ALLOCATION NOTES: +** +** Expr objects can use a lot of memory space in database schema. To +** help reduce memory requirements, sometimes an Expr object will be +** truncated. And to reduce the number of memory allocations, sometimes +** two or more Expr objects will be stored in a single memory allocation, +** together with Expr.zToken strings. +** +** If the EP_Reduced and EP_TokenOnly flags are set when +** an Expr object is truncated. When EP_Reduced is set, then all +** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees +** are contained within the same memory allocation. Note, however, that +** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately +** allocated, regardless of whether or not EP_Reduced is set. +*/ +struct Expr { + u8 op; /* Operation performed by this node */ + char affinity; /* The affinity of the column or 0 if not a column */ + u32 flags; /* Various flags. EP_* See below */ + union { + char *zToken; /* Token value. Zero terminated and dequoted */ + int iValue; /* Non-negative integer value if EP_IntValue */ + } u; + + /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no + ** space is allocated for the fields below this point. An attempt to + ** access them will result in a segfault or malfunction. + *********************************************************************/ + + Expr *pLeft; /* Left subnode */ + Expr *pRight; /* Right subnode */ + union { + ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */ + Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */ + } x; + + /* If the EP_Reduced flag is set in the Expr.flags mask, then no + ** space is allocated for the fields below this point. An attempt to + ** access them will result in a segfault or malfunction. + *********************************************************************/ + +#if SQLITE_MAX_EXPR_DEPTH>0 + int nHeight; /* Height of the tree headed by this node */ +#endif + int iTable; /* TK_COLUMN: cursor number of table holding column + ** TK_REGISTER: register number + ** TK_TRIGGER: 1 -> new, 0 -> old + ** EP_Unlikely: 1000 times likelihood */ + ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid. + ** TK_VARIABLE: variable number (always >= 1). */ + i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */ + i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */ + u8 op2; /* TK_REGISTER: original value of Expr.op + ** TK_COLUMN: the value of p5 for OP_Column + ** TK_AGG_FUNCTION: nesting depth */ + AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */ + Table *pTab; /* Table for TK_COLUMN expressions. */ +}; + +/* +** The following are the meanings of bits in the Expr.flags field. +*/ +#define EP_FromJoin 0x000001 /* Originated in ON or USING clause of a join */ +#define EP_Agg 0x000002 /* Contains one or more aggregate functions */ +#define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */ +#define EP_Error 0x000008 /* Expression contains one or more errors */ +#define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */ +#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */ +#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */ +#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */ +#define EP_Collate 0x000100 /* Tree contains a TK_COLLATE opeartor */ +#define EP_FixedDest 0x000200 /* Result needed in a specific register */ +#define EP_IntValue 0x000400 /* Integer value contained in u.iValue */ +#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */ +#define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */ +#define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */ +#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */ +#define EP_Static 0x008000 /* Held in memory not obtained from malloc() */ +#define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */ +#define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */ +#define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */ + +/* +** These macros can be used to test, set, or clear bits in the +** Expr.flags field. +*/ +#define ExprHasProperty(E,P) (((E)->flags&(P))!=0) +#define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P)) +#define ExprSetProperty(E,P) (E)->flags|=(P) +#define ExprClearProperty(E,P) (E)->flags&=~(P) + +/* The ExprSetVVAProperty() macro is used for Verification, Validation, +** and Accreditation only. It works like ExprSetProperty() during VVA +** processes but is a no-op for delivery. +*/ +#ifdef SQLITE_DEBUG +# define ExprSetVVAProperty(E,P) (E)->flags|=(P) +#else +# define ExprSetVVAProperty(E,P) +#endif + +/* +** Macros to determine the number of bytes required by a normal Expr +** struct, an Expr struct with the EP_Reduced flag set in Expr.flags +** and an Expr struct with the EP_TokenOnly flag set. +*/ +#define EXPR_FULLSIZE sizeof(Expr) /* Full size */ +#define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */ +#define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */ + +/* +** Flags passed to the sqlite3ExprDup() function. See the header comment +** above sqlite3ExprDup() for details. +*/ +#define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */ + +/* +** A list of expressions. Each expression may optionally have a +** name. An expr/name combination can be used in several ways, such +** as the list of "expr AS ID" fields following a "SELECT" or in the +** list of "ID = expr" items in an UPDATE. A list of expressions can +** also be used as the argument to a function, in which case the a.zName +** field is not used. +** +** By default the Expr.zSpan field holds a human-readable description of +** the expression that is used in the generation of error messages and +** column labels. In this case, Expr.zSpan is typically the text of a +** column expression as it exists in a SELECT statement. However, if +** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name +** of the result column in the form: DATABASE.TABLE.COLUMN. This later +** form is used for name resolution with nested FROM clauses. +*/ +struct ExprList { + int nExpr; /* Number of expressions on the list */ + int iECursor; /* VDBE Cursor associated with this ExprList */ + struct ExprList_item { /* For each expression in the list */ + Expr *pExpr; /* The list of expressions */ + char *zName; /* Token associated with this expression */ + char *zSpan; /* Original text of the expression */ + u8 sortOrder; /* 1 for DESC or 0 for ASC */ + unsigned done :1; /* A flag to indicate when processing is finished */ + unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */ + u16 iOrderByCol; /* For ORDER BY, column number in result set */ + u16 iAlias; /* Index into Parse.aAlias[] for zName */ + } *a; /* Alloc a power of two greater or equal to nExpr */ +}; + +/* +** An instance of this structure is used by the parser to record both +** the parse tree for an expression and the span of input text for an +** expression. +*/ +struct ExprSpan { + Expr *pExpr; /* The expression parse tree */ + const char *zStart; /* First character of input text */ + const char *zEnd; /* One character past the end of input text */ +}; + +/* +** An instance of this structure can hold a simple list of identifiers, +** such as the list "a,b,c" in the following statements: +** +** INSERT INTO t(a,b,c) VALUES ...; +** CREATE INDEX idx ON t(a,b,c); +** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...; +** +** The IdList.a.idx field is used when the IdList represents the list of +** column names after a table name in an INSERT statement. In the statement +** +** INSERT INTO t(a,b,c) ... +** +** If "a" is the k-th column of table "t", then IdList.a[0].idx==k. +*/ +struct IdList { + struct IdList_item { + char *zName; /* Name of the identifier */ + int idx; /* Index in some Table.aCol[] of a column named zName */ + } *a; + int nId; /* Number of identifiers on the list */ +}; + +/* +** The bitmask datatype defined below is used for various optimizations. +** +** Changing this from a 64-bit to a 32-bit type limits the number of +** tables in a join to 32 instead of 64. But it also reduces the size +** of the library by 738 bytes on ix86. +*/ +typedef u64 Bitmask; + +/* +** The number of bits in a Bitmask. "BMS" means "BitMask Size". +*/ +#define BMS ((int)(sizeof(Bitmask)*8)) + +/* +** A bit in a Bitmask +*/ +#define MASKBIT(n) (((Bitmask)1)<<(n)) + +/* +** The following structure describes the FROM clause of a SELECT statement. +** Each table or subquery in the FROM clause is a separate element of +** the SrcList.a[] array. +** +** With the addition of multiple database support, the following structure +** can also be used to describe a particular table such as the table that +** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL, +** such a table must be a simple name: ID. But in SQLite, the table can +** now be identified by a database name, a dot, then the table name: ID.ID. +** +** The jointype starts out showing the join type between the current table +** and the next table on the list. The parser builds the list this way. +** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each +** jointype expresses the join between the table and the previous table. +** +** In the colUsed field, the high-order bit (bit 63) is set if the table +** contains more than 63 columns and the 64-th or later column is used. +*/ +struct SrcList { + u8 nSrc; /* Number of tables or subqueries in the FROM clause */ + u8 nAlloc; /* Number of entries allocated in a[] below */ + struct SrcList_item { + Schema *pSchema; /* Schema to which this item is fixed */ + char *zDatabase; /* Name of database holding this table */ + char *zName; /* Name of the table */ + char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */ + Table *pTab; /* An SQL table corresponding to zName */ + Select *pSelect; /* A SELECT statement used in place of a table name */ + int addrFillSub; /* Address of subroutine to manifest a subquery */ + int regReturn; /* Register holding return address of addrFillSub */ + u8 jointype; /* Type of join between this able and the previous */ + unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */ + unsigned isCorrelated :1; /* True if sub-query is correlated */ + unsigned viaCoroutine :1; /* Implemented as a co-routine */ +#ifndef SQLITE_OMIT_EXPLAIN + u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */ +#endif + int iCursor; /* The VDBE cursor number used to access this table */ + Expr *pOn; /* The ON clause of a join */ + IdList *pUsing; /* The USING clause of a join */ + Bitmask colUsed; /* Bit N (1<" clause */ + Index *pIndex; /* Index structure corresponding to zIndex, if any */ + } a[1]; /* One entry for each identifier on the list */ +}; + +/* +** Permitted values of the SrcList.a.jointype field +*/ +#define JT_INNER 0x0001 /* Any kind of inner or cross join */ +#define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */ +#define JT_NATURAL 0x0004 /* True for a "natural" join */ +#define JT_LEFT 0x0008 /* Left outer join */ +#define JT_RIGHT 0x0010 /* Right outer join */ +#define JT_OUTER 0x0020 /* The "OUTER" keyword is present */ +#define JT_ERROR 0x0040 /* unknown or unsupported join type */ + + +/* +** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin() +** and the WhereInfo.wctrlFlags member. +*/ +#define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */ +#define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */ +#define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */ +#define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */ +#define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */ +#define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */ +#define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */ +#define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */ +#define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */ +#define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */ +#define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */ +#define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */ + +/* Allowed return values from sqlite3WhereIsDistinct() +*/ +#define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */ +#define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */ +#define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */ +#define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */ + +/* +** A NameContext defines a context in which to resolve table and column +** names. The context consists of a list of tables (the pSrcList) field and +** a list of named expression (pEList). The named expression list may +** be NULL. The pSrc corresponds to the FROM clause of a SELECT or +** to the table being operated on by INSERT, UPDATE, or DELETE. The +** pEList corresponds to the result set of a SELECT and is NULL for +** other statements. +** +** NameContexts can be nested. When resolving names, the inner-most +** context is searched first. If no match is found, the next outer +** context is checked. If there is still no match, the next context +** is checked. This process continues until either a match is found +** or all contexts are check. When a match is found, the nRef member of +** the context containing the match is incremented. +** +** Each subquery gets a new NameContext. The pNext field points to the +** NameContext in the parent query. Thus the process of scanning the +** NameContext list corresponds to searching through successively outer +** subqueries looking for a match. +*/ +struct NameContext { + Parse *pParse; /* The parser */ + SrcList *pSrcList; /* One or more tables used to resolve names */ + ExprList *pEList; /* Optional list of result-set columns */ + AggInfo *pAggInfo; /* Information about aggregates at this level */ + NameContext *pNext; /* Next outer name context. NULL for outermost */ + int nRef; /* Number of names resolved by this context */ + int nErr; /* Number of errors encountered while resolving names */ + u8 ncFlags; /* Zero or more NC_* flags defined below */ +}; + +/* +** Allowed values for the NameContext, ncFlags field. +*/ +#define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */ +#define NC_HasAgg 0x02 /* One or more aggregate functions seen */ +#define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */ +#define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */ +#define NC_PartIdx 0x10 /* True if resolving a partial index WHERE */ + +/* +** An instance of the following structure contains all information +** needed to generate code for a single SELECT statement. +** +** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0. +** If there is a LIMIT clause, the parser sets nLimit to the value of the +** limit and nOffset to the value of the offset (or 0 if there is not +** offset). But later on, nLimit and nOffset become the memory locations +** in the VDBE that record the limit and offset counters. +** +** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes. +** These addresses must be stored so that we can go back and fill in +** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor +** the number of columns in P2 can be computed at the same time +** as the OP_OpenEphm instruction is coded because not +** enough information about the compound query is known at that point. +** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences +** for the result set. The KeyInfo for addrOpenEphm[2] contains collating +** sequences for the ORDER BY clause. +*/ +struct Select { + ExprList *pEList; /* The fields of the result */ + u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */ + u16 selFlags; /* Various SF_* values */ + int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */ + int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */ + u64 nSelectRow; /* Estimated number of result rows */ + SrcList *pSrc; /* The FROM clause */ + Expr *pWhere; /* The WHERE clause */ + ExprList *pGroupBy; /* The GROUP BY clause */ + Expr *pHaving; /* The HAVING clause */ + ExprList *pOrderBy; /* The ORDER BY clause */ + Select *pPrior; /* Prior select in a compound select statement */ + Select *pNext; /* Next select to the left in a compound */ + Select *pRightmost; /* Right-most select in a compound select statement */ + Expr *pLimit; /* LIMIT expression. NULL means not used. */ + Expr *pOffset; /* OFFSET expression. NULL means not used. */ +}; + +/* +** Allowed values for Select.selFlags. The "SF" prefix stands for +** "Select Flag". +*/ +#define SF_Distinct 0x0001 /* Output should be DISTINCT */ +#define SF_Resolved 0x0002 /* Identifiers have been resolved */ +#define SF_Aggregate 0x0004 /* Contains aggregate functions */ +#define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */ +#define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */ +#define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */ +#define SF_UseSorter 0x0040 /* Sort using a sorter */ +#define SF_Values 0x0080 /* Synthesized from VALUES clause */ +#define SF_Materialize 0x0100 /* Force materialization of views */ +#define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */ +#define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */ + + +/* +** The results of a select can be distributed in several ways. The +** "SRT" prefix means "SELECT Result Type". +*/ +#define SRT_Union 1 /* Store result as keys in an index */ +#define SRT_Except 2 /* Remove result from a UNION index */ +#define SRT_Exists 3 /* Store 1 if the result is not empty */ +#define SRT_Discard 4 /* Do not save the results anywhere */ + +/* The ORDER BY clause is ignored for all of the above */ +#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard) + +#define SRT_Output 5 /* Output each row of result */ +#define SRT_Mem 6 /* Store result in a memory cell */ +#define SRT_Set 7 /* Store results as keys in an index */ +#define SRT_Table 8 /* Store result as data with an automatic rowid */ +#define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */ +#define SRT_Coroutine 10 /* Generate a single row of result */ + +/* +** An instance of this object describes where to put of the results of +** a SELECT statement. +*/ +struct SelectDest { + u8 eDest; /* How to dispose of the results. On of SRT_* above. */ + char affSdst; /* Affinity used when eDest==SRT_Set */ + int iSDParm; /* A parameter used by the eDest disposal method */ + int iSdst; /* Base register where results are written */ + int nSdst; /* Number of registers allocated */ +}; + +/* +** During code generation of statements that do inserts into AUTOINCREMENT +** tables, the following information is attached to the Table.u.autoInc.p +** pointer of each autoincrement table to record some side information that +** the code generator needs. We have to keep per-table autoincrement +** information in case inserts are down within triggers. Triggers do not +** normally coordinate their activities, but we do need to coordinate the +** loading and saving of autoincrement information. +*/ +struct AutoincInfo { + AutoincInfo *pNext; /* Next info block in a list of them all */ + Table *pTab; /* Table this info block refers to */ + int iDb; /* Index in sqlite3.aDb[] of database holding pTab */ + int regCtr; /* Memory register holding the rowid counter */ +}; + +/* +** Size of the column cache +*/ +#ifndef SQLITE_N_COLCACHE +# define SQLITE_N_COLCACHE 10 +#endif + +/* +** At least one instance of the following structure is created for each +** trigger that may be fired while parsing an INSERT, UPDATE or DELETE +** statement. All such objects are stored in the linked list headed at +** Parse.pTriggerPrg and deleted once statement compilation has been +** completed. +** +** A Vdbe sub-program that implements the body and WHEN clause of trigger +** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of +** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable. +** The Parse.pTriggerPrg list never contains two entries with the same +** values for both pTrigger and orconf. +** +** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns +** accessed (or set to 0 for triggers fired as a result of INSERT +** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to +** a mask of new.* columns used by the program. +*/ +struct TriggerPrg { + Trigger *pTrigger; /* Trigger this program was coded from */ + TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */ + SubProgram *pProgram; /* Program implementing pTrigger/orconf */ + int orconf; /* Default ON CONFLICT policy */ + u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */ +}; + +/* +** The yDbMask datatype for the bitmask of all attached databases. +*/ +#if SQLITE_MAX_ATTACHED>30 + typedef sqlite3_uint64 yDbMask; +#else + typedef unsigned int yDbMask; +#endif + +/* +** An SQL parser context. A copy of this structure is passed through +** the parser and down into all the parser action routine in order to +** carry around information that is global to the entire parse. +** +** The structure is divided into two parts. When the parser and code +** generate call themselves recursively, the first part of the structure +** is constant but the second part is reset at the beginning and end of +** each recursion. +** +** The nTableLock and aTableLock variables are only used if the shared-cache +** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are +** used to store the set of table-locks required by the statement being +** compiled. Function sqlite3TableLock() is used to add entries to the +** list. +*/ +struct Parse { + sqlite3 *db; /* The main database structure */ + char *zErrMsg; /* An error message */ + Vdbe *pVdbe; /* An engine for executing database bytecode */ + int rc; /* Return code from execution */ + u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */ + u8 checkSchema; /* Causes schema cookie check after an error */ + u8 nested; /* Number of nested calls to the parser/code generator */ + u8 nTempReg; /* Number of temporary registers in aTempReg[] */ + u8 nTempInUse; /* Number of aTempReg[] currently checked out */ + u8 nColCache; /* Number of entries in aColCache[] */ + u8 iColCache; /* Next entry in aColCache[] to replace */ + u8 isMultiWrite; /* True if statement may modify/insert multiple rows */ + u8 mayAbort; /* True if statement may throw an ABORT exception */ + u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */ + int aTempReg[8]; /* Holding area for temporary registers */ + int nRangeReg; /* Size of the temporary register block */ + int iRangeReg; /* First register in temporary register block */ + int nErr; /* Number of errors seen */ + int nTab; /* Number of previously allocated VDBE cursors */ + int nMem; /* Number of memory cells used so far */ + int nSet; /* Number of sets used so far */ + int nOnce; /* Number of OP_Once instructions so far */ + int ckBase; /* Base register of data during check constraints */ + int iPartIdxTab; /* Table corresponding to a partial index */ + int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */ + int iCacheCnt; /* Counter used to generate aColCache[].lru values */ + struct yColCache { + int iTable; /* Table cursor number */ + int iColumn; /* Table column number */ + u8 tempReg; /* iReg is a temp register that needs to be freed */ + int iLevel; /* Nesting level */ + int iReg; /* Reg with value of this column. 0 means none. */ + int lru; /* Least recently used entry has the smallest value */ + } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */ + yDbMask writeMask; /* Start a write transaction on these databases */ + yDbMask cookieMask; /* Bitmask of schema verified databases */ + int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */ + int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */ + int regRowid; /* Register holding rowid of CREATE TABLE entry */ + int regRoot; /* Register holding root page number for new objects */ + int nMaxArg; /* Max args passed to user function by sub-program */ + Token constraintName;/* Name of the constraint currently being parsed */ +#ifndef SQLITE_OMIT_SHARED_CACHE + int nTableLock; /* Number of locks in aTableLock */ + TableLock *aTableLock; /* Required table locks for shared-cache mode */ +#endif + AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */ + + /* Information used while coding trigger programs. */ + Parse *pToplevel; /* Parse structure for main program (or NULL) */ + Table *pTriggerTab; /* Table triggers are being coded for */ + u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */ + u32 oldmask; /* Mask of old.* columns referenced */ + u32 newmask; /* Mask of new.* columns referenced */ + u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */ + u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */ + u8 disableTriggers; /* True to disable triggers */ + + /* Above is constant between recursions. Below is reset before and after + ** each recursion */ + + int nVar; /* Number of '?' variables seen in the SQL so far */ + int nzVar; /* Number of available slots in azVar[] */ + u8 explain; /* True if the EXPLAIN flag is found on the query */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + u8 declareVtab; /* True if inside sqlite3_declare_vtab() */ + int nVtabLock; /* Number of virtual tables to lock */ +#endif + int nAlias; /* Number of aliased result set columns */ + int nHeight; /* Expression tree height of current sub-select */ +#ifndef SQLITE_OMIT_EXPLAIN + int iSelectId; /* ID of current select for EXPLAIN output */ + int iNextSelectId; /* Next available select ID for EXPLAIN output */ +#endif + char **azVar; /* Pointers to names of parameters */ + Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */ + int *aAlias; /* Register used to hold aliased result */ + const char *zTail; /* All SQL text past the last semicolon parsed */ + Table *pNewTable; /* A table being constructed by CREATE TABLE */ + Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */ + const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */ + Token sNameToken; /* Token with unqualified schema object name */ + Token sLastToken; /* The last token parsed */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + Token sArg; /* Complete text of a module argument */ + Table **apVtabLock; /* Pointer to virtual tables needing locking */ +#endif + Table *pZombieTab; /* List of Table objects to delete after code gen */ + TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */ +}; + +/* +** Return true if currently inside an sqlite3_declare_vtab() call. +*/ +#ifdef SQLITE_OMIT_VIRTUALTABLE + #define IN_DECLARE_VTAB 0 +#else + #define IN_DECLARE_VTAB (pParse->declareVtab) +#endif + +/* +** An instance of the following structure can be declared on a stack and used +** to save the Parse.zAuthContext value so that it can be restored later. +*/ +struct AuthContext { + const char *zAuthContext; /* Put saved Parse.zAuthContext here */ + Parse *pParse; /* The Parse structure */ +}; + +/* +** Bitfield flags for P5 value in various opcodes. +*/ +#define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */ +#define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */ +#define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */ +#define OPFLAG_APPEND 0x08 /* This is likely to be an append */ +#define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */ +#define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */ +#define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */ +#define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */ +#define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */ +#define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */ +#define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */ + +/* + * Each trigger present in the database schema is stored as an instance of + * struct Trigger. + * + * Pointers to instances of struct Trigger are stored in two ways. + * 1. In the "trigHash" hash table (part of the sqlite3* that represents the + * database). This allows Trigger structures to be retrieved by name. + * 2. All triggers associated with a single table form a linked list, using the + * pNext member of struct Trigger. A pointer to the first element of the + * linked list is stored as the "pTrigger" member of the associated + * struct Table. + * + * The "step_list" member points to the first element of a linked list + * containing the SQL statements specified as the trigger program. + */ +struct Trigger { + char *zName; /* The name of the trigger */ + char *table; /* The table or view to which the trigger applies */ + u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */ + u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ + Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */ + IdList *pColumns; /* If this is an UPDATE OF trigger, + the is stored here */ + Schema *pSchema; /* Schema containing the trigger */ + Schema *pTabSchema; /* Schema containing the table */ + TriggerStep *step_list; /* Link list of trigger program steps */ + Trigger *pNext; /* Next trigger associated with the table */ +}; + +/* +** A trigger is either a BEFORE or an AFTER trigger. The following constants +** determine which. +** +** If there are multiple triggers, you might of some BEFORE and some AFTER. +** In that cases, the constants below can be ORed together. +*/ +#define TRIGGER_BEFORE 1 +#define TRIGGER_AFTER 2 + +/* + * An instance of struct TriggerStep is used to store a single SQL statement + * that is a part of a trigger-program. + * + * Instances of struct TriggerStep are stored in a singly linked list (linked + * using the "pNext" member) referenced by the "step_list" member of the + * associated struct Trigger instance. The first element of the linked list is + * the first step of the trigger-program. + * + * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or + * "SELECT" statement. The meanings of the other members is determined by the + * value of "op" as follows: + * + * (op == TK_INSERT) + * orconf -> stores the ON CONFLICT algorithm + * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then + * this stores a pointer to the SELECT statement. Otherwise NULL. + * target -> A token holding the quoted name of the table to insert into. + * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then + * this stores values to be inserted. Otherwise NULL. + * pIdList -> If this is an INSERT INTO ... () VALUES ... + * statement, then this stores the column-names to be + * inserted into. + * + * (op == TK_DELETE) + * target -> A token holding the quoted name of the table to delete from. + * pWhere -> The WHERE clause of the DELETE statement if one is specified. + * Otherwise NULL. + * + * (op == TK_UPDATE) + * target -> A token holding the quoted name of the table to update rows of. + * pWhere -> The WHERE clause of the UPDATE statement if one is specified. + * Otherwise NULL. + * pExprList -> A list of the columns to update and the expressions to update + * them to. See sqlite3Update() documentation of "pChanges" + * argument. + * + */ +struct TriggerStep { + u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */ + u8 orconf; /* OE_Rollback etc. */ + Trigger *pTrig; /* The trigger that this step is a part of */ + Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */ + Token target; /* Target table for DELETE, UPDATE, INSERT */ + Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */ + ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */ + IdList *pIdList; /* Column names for INSERT */ + TriggerStep *pNext; /* Next in the link-list */ + TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */ +}; + +/* +** The following structure contains information used by the sqliteFix... +** routines as they walk the parse tree to make database references +** explicit. +*/ +typedef struct DbFixer DbFixer; +struct DbFixer { + Parse *pParse; /* The parsing context. Error messages written here */ + Schema *pSchema; /* Fix items to this schema */ + int bVarOnly; /* Check for variable references only */ + const char *zDb; /* Make sure all objects are contained in this database */ + const char *zType; /* Type of the container - used for error messages */ + const Token *pName; /* Name of the container - used for error messages */ +}; + +/* +** An objected used to accumulate the text of a string where we +** do not necessarily know how big the string will be in the end. +*/ +struct StrAccum { + sqlite3 *db; /* Optional database for lookaside. Can be NULL */ + char *zBase; /* A base allocation. Not from malloc. */ + char *zText; /* The string collected so far */ + int nChar; /* Length of the string so far */ + int nAlloc; /* Amount of space allocated in zText */ + int mxAlloc; /* Maximum allowed string length */ + u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */ + u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */ +}; +#define STRACCUM_NOMEM 1 +#define STRACCUM_TOOBIG 2 + +/* +** A pointer to this structure is used to communicate information +** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback. +*/ +typedef struct { + sqlite3 *db; /* The database being initialized */ + char **pzErrMsg; /* Error message stored here */ + int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */ + int rc; /* Result code stored here */ +} InitData; + +/* +** Structure containing global configuration data for the SQLite library. +** +** This structure also contains some state information. +*/ +struct Sqlite3Config { + int bMemstat; /* True to enable memory status */ + int bCoreMutex; /* True to enable core mutexing */ + int bFullMutex; /* True to enable full mutexing */ + int bOpenUri; /* True to interpret filenames as URIs */ + int bUseCis; /* Use covering indices for full-scans */ + int mxStrlen; /* Maximum string length */ + int szLookaside; /* Default lookaside buffer size */ + int nLookaside; /* Default lookaside buffer count */ + sqlite3_mem_methods m; /* Low-level memory allocation interface */ + sqlite3_mutex_methods mutex; /* Low-level mutex interface */ + sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */ + void *pHeap; /* Heap storage space */ + int nHeap; /* Size of pHeap[] */ + int mnReq, mxReq; /* Min and max heap requests sizes */ + sqlite3_int64 szMmap; /* mmap() space per open file */ + sqlite3_int64 mxMmap; /* Maximum value for szMmap */ + void *pScratch; /* Scratch memory */ + int szScratch; /* Size of each scratch buffer */ + int nScratch; /* Number of scratch buffers */ + void *pPage; /* Page cache memory */ + int szPage; /* Size of each page in pPage[] */ + int nPage; /* Number of pages in pPage[] */ + int mxParserStack; /* maximum depth of the parser stack */ + int sharedCacheEnabled; /* true if shared-cache mode enabled */ + /* The above might be initialized to non-zero. The following need to always + ** initially be zero, however. */ + int isInit; /* True after initialization has finished */ + int inProgress; /* True while initialization in progress */ + int isMutexInit; /* True after mutexes are initialized */ + int isMallocInit; /* True after malloc is initialized */ + int isPCacheInit; /* True after malloc is initialized */ + sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */ + int nRefInitMutex; /* Number of users of pInitMutex */ + void (*xLog)(void*,int,const char*); /* Function for logging */ + void *pLogArg; /* First argument to xLog() */ + int bLocaltimeFault; /* True to fail localtime() calls */ +#ifdef SQLITE_ENABLE_SQLLOG + void(*xSqllog)(void*,sqlite3*,const char*, int); + void *pSqllogArg; +#endif +}; + +/* +** Context pointer passed down through the tree-walk. +*/ +struct Walker { + int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */ + int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */ + Parse *pParse; /* Parser context. */ + int walkerDepth; /* Number of subqueries */ + u8 bSelectDepthFirst; /* Do subqueries first */ + union { /* Extra data for callback */ + NameContext *pNC; /* Naming context */ + int i; /* Integer value */ + SrcList *pSrcList; /* FROM clause */ + struct SrcCount *pSrcCount; /* Counting column references */ + } u; +}; + +/* Forward declarations */ +SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*); +SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*); +SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*); +SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*); +SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*); + +/* +** Return code from the parse-tree walking primitives and their +** callbacks. +*/ +#define WRC_Continue 0 /* Continue down into children */ +#define WRC_Prune 1 /* Omit children but continue walking siblings */ +#define WRC_Abort 2 /* Abandon the tree walk */ + +/* +** Assuming zIn points to the first byte of a UTF-8 character, +** advance zIn to point to the first byte of the next UTF-8 character. +*/ +#define SQLITE_SKIP_UTF8(zIn) { \ + if( (*(zIn++))>=0xc0 ){ \ + while( (*zIn & 0xc0)==0x80 ){ zIn++; } \ + } \ +} + +/* +** The SQLITE_*_BKPT macros are substitutes for the error codes with +** the same name but without the _BKPT suffix. These macros invoke +** routines that report the line-number on which the error originated +** using sqlite3_log(). The routines also provide a convenient place +** to set a debugger breakpoint. +*/ +SQLITE_PRIVATE int sqlite3CorruptError(int); +SQLITE_PRIVATE int sqlite3MisuseError(int); +SQLITE_PRIVATE int sqlite3CantopenError(int); +#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__) +#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__) +#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__) + + +/* +** FTS4 is really an extension for FTS3. It is enabled using the +** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all +** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3. +*/ +#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) +# define SQLITE_ENABLE_FTS3 +#endif + +/* +** The ctype.h header is needed for non-ASCII systems. It is also +** needed by FTS3 when FTS3 is included in the amalgamation. +*/ +#if !defined(SQLITE_ASCII) || \ + (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION)) +# include +#endif + +/* +** The following macros mimic the standard library functions toupper(), +** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The +** sqlite versions only work for ASCII characters, regardless of locale. +*/ +#ifdef SQLITE_ASCII +# define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) +# define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01) +# define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06) +# define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02) +# define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04) +# define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08) +# define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)]) +#else +# define sqlite3Toupper(x) toupper((unsigned char)(x)) +# define sqlite3Isspace(x) isspace((unsigned char)(x)) +# define sqlite3Isalnum(x) isalnum((unsigned char)(x)) +# define sqlite3Isalpha(x) isalpha((unsigned char)(x)) +# define sqlite3Isdigit(x) isdigit((unsigned char)(x)) +# define sqlite3Isxdigit(x) isxdigit((unsigned char)(x)) +# define sqlite3Tolower(x) tolower((unsigned char)(x)) +#endif + +/* +** Internal function prototypes +*/ +#define sqlite3StrICmp sqlite3_stricmp +SQLITE_PRIVATE int sqlite3Strlen30(const char*); +#define sqlite3StrNICmp sqlite3_strnicmp + +SQLITE_PRIVATE int sqlite3MallocInit(void); +SQLITE_PRIVATE void sqlite3MallocEnd(void); +SQLITE_PRIVATE void *sqlite3Malloc(int); +SQLITE_PRIVATE void *sqlite3MallocZero(int); +SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int); +SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int); +SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*); +SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int); +SQLITE_PRIVATE void *sqlite3Realloc(void*, int); +SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int); +SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int); +SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*); +SQLITE_PRIVATE int sqlite3MallocSize(void*); +SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*); +SQLITE_PRIVATE void *sqlite3ScratchMalloc(int); +SQLITE_PRIVATE void sqlite3ScratchFree(void*); +SQLITE_PRIVATE void *sqlite3PageMalloc(int); +SQLITE_PRIVATE void sqlite3PageFree(void*); +SQLITE_PRIVATE void sqlite3MemSetDefault(void); +SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void)); +SQLITE_PRIVATE int sqlite3HeapNearlyFull(void); + +/* +** On systems with ample stack space and that support alloca(), make +** use of alloca() to obtain space for large automatic objects. By default, +** obtain space from malloc(). +** +** The alloca() routine never returns NULL. This will cause code paths +** that deal with sqlite3StackAlloc() failures to be unreachable. +*/ +#ifdef SQLITE_USE_ALLOCA +# define sqlite3StackAllocRaw(D,N) alloca(N) +# define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N) +# define sqlite3StackFree(D,P) +#else +# define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N) +# define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N) +# define sqlite3StackFree(D,P) sqlite3DbFree(D,P) +#endif + +#ifdef SQLITE_ENABLE_MEMSYS3 +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void); +#endif +#ifdef SQLITE_ENABLE_MEMSYS5 +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void); +#endif + + +#ifndef SQLITE_MUTEX_OMIT +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void); +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void); +SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int); +SQLITE_PRIVATE int sqlite3MutexInit(void); +SQLITE_PRIVATE int sqlite3MutexEnd(void); +#endif + +SQLITE_PRIVATE int sqlite3StatusValue(int); +SQLITE_PRIVATE void sqlite3StatusAdd(int, int); +SQLITE_PRIVATE void sqlite3StatusSet(int, int); + +#ifndef SQLITE_OMIT_FLOATING_POINT +SQLITE_PRIVATE int sqlite3IsNaN(double); +#else +# define sqlite3IsNaN(X) 0 +#endif + +SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list); +#ifndef SQLITE_OMIT_TRACE +SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...); +#endif +SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...); +SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list); +SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...); +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) +SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...); +#endif +#if defined(SQLITE_TEST) +SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*); +#endif + +/* Output formatting for SQLITE_TESTCTRL_EXPLAIN */ +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) +SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*); +SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...); +SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*); +SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*); +SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*); +SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*); +SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*); +SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*); +SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*); +SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*); +#else +# define sqlite3ExplainBegin(X) +# define sqlite3ExplainSelect(A,B) +# define sqlite3ExplainExpr(A,B) +# define sqlite3ExplainExprList(A,B) +# define sqlite3ExplainFinish(X) +# define sqlite3VdbeExplanation(X) 0 +#endif + + +SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...); +SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...); +SQLITE_PRIVATE int sqlite3Dequote(char*); +SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int); +SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **); +SQLITE_PRIVATE void sqlite3FinishCoding(Parse*); +SQLITE_PRIVATE int sqlite3GetTempReg(Parse*); +SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int); +SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int); +SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int); +SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*); +SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int); +SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*); +SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*); +SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*); +SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*); +SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*); +SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*); +SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*); +SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*); +SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int); +SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*); +SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*); +SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**); +SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**); +SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int); +SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*); +SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int); +SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*); +SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int); +SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*); +SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*); +SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int); +SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int); +SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*); +SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int); +SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int); +SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*); +SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*); +SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*); +SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*); +SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*); +SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*, + sqlite3_vfs**,char**,char **); +SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*); +SQLITE_PRIVATE int sqlite3CodeOnce(Parse *); + +SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32); +SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32); +SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32); +SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*); +SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*); +SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*); +SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*); + +SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int); +SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*); +SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64); +SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64); +SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*); + +SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int); + +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) +SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*); +#else +# define sqlite3ViewGetColumnNames(A,B) 0 +#endif + +SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int); +SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int); +SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*); +#ifndef SQLITE_OMIT_AUTOINCREMENT +SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse); +SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse); +#else +# define sqlite3AutoincrementBegin(X) +# define sqlite3AutoincrementEnd(X) +#endif +SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*); +SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int); +SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*); +SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*); +SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*); +SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int); +SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*); +SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, + Token*, Select*, Expr*, IdList*); +SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *); +SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *); +SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*); +SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*); +SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*); +SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*); +SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, + Expr*, int, int); +SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int); +SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*); +SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*, + Expr*,ExprList*,u16,Expr*,Expr*); +SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*); +SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*); +SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int); +SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int); +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) +SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*); +#endif +SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*); +SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int); +SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int); +SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*); +SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*); +SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*); +SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*); +SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*); +SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*); +SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*); +SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8); +SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int); +SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int); +SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int); +SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*); +SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int); +SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int); +SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*); +SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int); +SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int); +SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*); +SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int); +SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int); +SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*); +SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int); +SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int); +SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int); +SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*); +SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*); +SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *); +SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*); +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*); +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*); +SQLITE_PRIVATE void sqlite3Vacuum(Parse*); +SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*); +SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*); +SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int); +SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int); +SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int); +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*); +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*); +SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*); +SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*); +SQLITE_PRIVATE void sqlite3PrngSaveState(void); +SQLITE_PRIVATE void sqlite3PrngRestoreState(void); +SQLITE_PRIVATE void sqlite3PrngResetState(void); +SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int); +SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int); +SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb); +SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int); +SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*); +SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*); +SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*); +SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *); +SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*); +SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*); +SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*); +SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*); +SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*); +SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*); +SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int); +SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char); +SQLITE_PRIVATE int sqlite3IsRowid(const char*); +SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int); +SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*); +SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*); +SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int, + int*,int,int,int,int,int*); +SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int); +SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int); +SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int); +SQLITE_PRIVATE void sqlite3MultiWrite(Parse*); +SQLITE_PRIVATE void sqlite3MayAbort(Parse*); +SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int); +SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int); +SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int); +SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int); +SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*); +SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int); +SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*); +SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8); +SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*); +SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void); +SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void); +SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*); +SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*); +SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int); + +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) +SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int); +#endif + +#ifndef SQLITE_OMIT_TRIGGER +SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*, + Expr*,int, int); +SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*); +SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int); +SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*); +SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask); +SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *); +SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *, + int, int, int); +SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int); + void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*); +SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*); +SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*); +SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*, + ExprList*,Select*,u8); +SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8); +SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*); +SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*); +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*); +SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int); +# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p)) +#else +# define sqlite3TriggersExist(B,C,D,E,F) 0 +# define sqlite3DeleteTrigger(A,B) +# define sqlite3DropTriggerPtr(A,B) +# define sqlite3UnlinkAndDeleteTrigger(A,B,C) +# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) +# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F) +# define sqlite3TriggerList(X, Y) 0 +# define sqlite3ParseToplevel(p) p +# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0 +#endif + +SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*); +SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int); +SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int); +#ifndef SQLITE_OMIT_AUTHORIZATION +SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*); +SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*); +SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*); +SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*); +SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int); +#else +# define sqlite3AuthRead(a,b,c,d) +# define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK +# define sqlite3AuthContextPush(a,b,c) +# define sqlite3AuthContextPop(a) ((void)(a)) +#endif +SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*); +SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*); +SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*); +SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*); +SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*); +SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*); +SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*); +SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*); +SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8); +SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*); +SQLITE_PRIVATE int sqlite3Atoi(const char*); +SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar); +SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte); +SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**); +SQLITE_PRIVATE LogEst sqlite3LogEst(u64); +SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst); +#ifndef SQLITE_OMIT_VIRTUALTABLE +SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double); +#endif +SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst); + +/* +** Routines to read and write variable-length integers. These used to +** be defined locally, but now we use the varint routines in the util.c +** file. Code should use the MACRO forms below, as the Varint32 versions +** are coded to assume the single byte case is already handled (which +** the MACRO form does). +*/ +SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64); +SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32); +SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *); +SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *); +SQLITE_PRIVATE int sqlite3VarintLen(u64 v); + +/* +** The header of a record consists of a sequence variable-length integers. +** These integers are almost always small and are encoded as a single byte. +** The following macros take advantage this fact to provide a fast encode +** and decode of the integers in a record header. It is faster for the common +** case where the integer is a single byte. It is a little slower when the +** integer is two or more bytes. But overall it is faster. +** +** The following expressions are equivalent: +** +** x = sqlite3GetVarint32( A, &B ); +** x = sqlite3PutVarint32( A, B ); +** +** x = getVarint32( A, B ); +** x = putVarint32( A, B ); +** +*/ +#define getVarint32(A,B) \ + (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B))) +#define putVarint32(A,B) \ + (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\ + sqlite3PutVarint32((A),(B))) +#define getVarint sqlite3GetVarint +#define putVarint sqlite3PutVarint + + +SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *); +SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *); +SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2); +SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity); +SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr); +SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8); +SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...); +SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n); +SQLITE_PRIVATE u8 sqlite3HexToInt(int h); +SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **); + +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \ + defined(SQLITE_DEBUG_OS_TRACE) +SQLITE_PRIVATE const char *sqlite3ErrName(int); +#endif + +SQLITE_PRIVATE const char *sqlite3ErrStr(int); +SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse); +SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int); +SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName); +SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr); +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*); +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*); +SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*); +SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *); +SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *); +SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int); +SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64); +SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64); +SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64); +SQLITE_PRIVATE int sqlite3AbsInt32(int); +#ifdef SQLITE_ENABLE_8_3_NAMES +SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*); +#else +# define sqlite3FileSuffix3(X,Y) +#endif +SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int); + +SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8); +SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8); +SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, + void(*)(void*)); +SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*); +SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *); +SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8); +SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **); +SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8); +#ifndef SQLITE_AMALGAMATION +SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[]; +SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[]; +SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[]; +SQLITE_PRIVATE const Token sqlite3IntTokens[]; +SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config; +SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions; +#ifndef SQLITE_OMIT_WSD +SQLITE_PRIVATE int sqlite3PendingByte; +#endif +#endif +SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int); +SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*); +SQLITE_PRIVATE void sqlite3AlterFunctions(void); +SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*); +SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *); +SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...); +SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*); +SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int); +SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*); +SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*); +SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*); +SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*); +SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*); +SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*); +SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int); +SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *); +SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *); +SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*); +SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*); +SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*); +SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*); +SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*); +SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *); +SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB); +SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*); +SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*); +SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int); +SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*); +SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int); +SQLITE_PRIVATE void sqlite3SchemaClear(void *); +SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *); +SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *); +SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int); +SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *); +SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, + void (*)(sqlite3_context*,int,sqlite3_value **), + void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*), + FuncDestructor *pDestructor +); +SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int); +SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *); + +SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int); +SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int); +SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int); +SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*); +SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*); +SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int); +SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int); + +SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *); +SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *); + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void); +SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*); +SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*); +#endif + +/* +** The interface to the LEMON-generated parser +*/ +SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t)); +SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*)); +SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*); +#ifdef YYTRACKMAXSTACKDEPTH +SQLITE_PRIVATE int sqlite3ParserStackPeak(void*); +#endif + +SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*); +#else +# define sqlite3CloseExtensions(X) +#endif + +#ifndef SQLITE_OMIT_SHARED_CACHE +SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *); +#else + #define sqlite3TableLock(v,w,x,y,z) +#endif + +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*); +#endif + +#ifdef SQLITE_OMIT_VIRTUALTABLE +# define sqlite3VtabClear(Y) +# define sqlite3VtabSync(X,Y) SQLITE_OK +# define sqlite3VtabRollback(X) +# define sqlite3VtabCommit(X) +# define sqlite3VtabInSync(db) 0 +# define sqlite3VtabLock(X) +# define sqlite3VtabUnlock(X) +# define sqlite3VtabUnlockList(X) +# define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK +# define sqlite3GetVTable(X,Y) ((VTable*)0) +#else +SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*); +SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p); +SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*); +SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db); +SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db); +SQLITE_PRIVATE void sqlite3VtabLock(VTable *); +SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *); +SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*); +SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int); +SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*); +SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*); +# define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0) +#endif +SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*); +SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int); +SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*); +SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*); +SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*); +SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **); +SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*); +SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *); +SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *); +SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*); +SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**); +SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*); +SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int); +SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *); +SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*); +SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*); +SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *); +SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*); +SQLITE_PRIVATE const char *sqlite3JournalModename(int); +#ifndef SQLITE_OMIT_WAL +SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*); +SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int); +#endif + +/* Declarations for functions in fkey.c. All of these are replaced by +** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign +** key functionality is available. If OMIT_TRIGGER is defined but +** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In +** this case foreign keys are parsed, but no other functionality is +** provided (enforcement of FK constraints requires the triggers sub-system). +*/ +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) +SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int); +SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*); +SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int); +SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int); +SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*); +SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *); +#else + #define sqlite3FkActions(a,b,c,d,e,f) + #define sqlite3FkCheck(a,b,c,d,e,f) + #define sqlite3FkDropTable(a,b,c) + #define sqlite3FkOldmask(a,b) 0 + #define sqlite3FkRequired(a,b,c,d) 0 +#endif +#ifndef SQLITE_OMIT_FOREIGN_KEY +SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*); +SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**); +#else + #define sqlite3FkDelete(a,b) + #define sqlite3FkLocateIndex(a,b,c,d,e) +#endif + + +/* +** Available fault injectors. Should be numbered beginning with 0. +*/ +#define SQLITE_FAULTINJECTOR_MALLOC 0 +#define SQLITE_FAULTINJECTOR_COUNT 1 + +/* +** The interface to the code in fault.c used for identifying "benign" +** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST +** is not defined. +*/ +#ifndef SQLITE_OMIT_BUILTIN_TEST +SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void); +SQLITE_PRIVATE void sqlite3EndBenignMalloc(void); +#else + #define sqlite3BeginBenignMalloc() + #define sqlite3EndBenignMalloc() +#endif + +#define IN_INDEX_ROWID 1 +#define IN_INDEX_EPH 2 +#define IN_INDEX_INDEX_ASC 3 +#define IN_INDEX_INDEX_DESC 4 +SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*); + +#ifdef SQLITE_ENABLE_ATOMIC_WRITE +SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int); +SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *); +SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *); +SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p); +#else + #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile) + #define sqlite3JournalExists(p) 1 +#endif + +SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *); +SQLITE_PRIVATE int sqlite3MemJournalSize(void); +SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *); + +#if SQLITE_MAX_EXPR_DEPTH>0 +SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p); +SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *); +SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int); +#else + #define sqlite3ExprSetHeight(x,y) + #define sqlite3SelectExprHeight(x) 0 + #define sqlite3ExprCheckHeight(x,y) +#endif + +SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*); +SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32); + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY +SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *); +SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db); +SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db); +#else + #define sqlite3ConnectionBlocked(x,y) + #define sqlite3ConnectionUnlocked(x) + #define sqlite3ConnectionClosed(x) +#endif + +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *); +#endif + +/* +** If the SQLITE_ENABLE IOTRACE exists then the global variable +** sqlite3IoTrace is a pointer to a printf-like routine used to +** print I/O tracing messages. +*/ +#ifdef SQLITE_ENABLE_IOTRACE +# define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; } +SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*); +SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...); +#else +# define IOTRACE(A) +# define sqlite3VdbeIOTraceSql(X) +#endif + +/* +** These routines are available for the mem2.c debugging memory allocator +** only. They are used to verify that different "types" of memory +** allocations are properly tracked by the system. +** +** sqlite3MemdebugSetType() sets the "type" of an allocation to one of +** the MEMTYPE_* macros defined below. The type must be a bitmask with +** a single bit set. +** +** sqlite3MemdebugHasType() returns true if any of the bits in its second +** argument match the type set by the previous sqlite3MemdebugSetType(). +** sqlite3MemdebugHasType() is intended for use inside assert() statements. +** +** sqlite3MemdebugNoType() returns true if none of the bits in its second +** argument match the type set by the previous sqlite3MemdebugSetType(). +** +** Perhaps the most important point is the difference between MEMTYPE_HEAP +** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means +** it might have been allocated by lookaside, except the allocation was +** too large or lookaside was already full. It is important to verify +** that allocations that might have been satisfied by lookaside are not +** passed back to non-lookaside free() routines. Asserts such as the +** example above are placed on the non-lookaside free() routines to verify +** this constraint. +** +** All of this is no-op for a production build. It only comes into +** play when the SQLITE_MEMDEBUG compile-time option is used. +*/ +#ifdef SQLITE_MEMDEBUG +SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8); +SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8); +SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8); +#else +# define sqlite3MemdebugSetType(X,Y) /* no-op */ +# define sqlite3MemdebugHasType(X,Y) 1 +# define sqlite3MemdebugNoType(X,Y) 1 +#endif +#define MEMTYPE_HEAP 0x01 /* General heap allocations */ +#define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */ +#define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */ +#define MEMTYPE_PCACHE 0x08 /* Page cache allocations */ +#define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */ + +#endif /* _SQLITEINT_H_ */ + +/************** End of sqliteInt.h *******************************************/ +/************** Begin file global.c ******************************************/ +/* +** 2008 June 13 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains definitions of global variables and contants. +*/ + +/* An array to map all upper-case characters into their corresponding +** lower-case character. +** +** SQLite only considers US-ASCII (or EBCDIC) characters. We do not +** handle case conversions for the UTF character set since the tables +** involved are nearly as big or bigger than SQLite itself. +*/ +SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = { +#ifdef SQLITE_ASCII + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, + 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, + 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, + 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, + 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, + 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, + 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, + 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, + 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, + 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, + 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, + 252,253,254,255 +#endif +#ifdef SQLITE_EBCDIC + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */ + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */ + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */ + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */ + 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */ + 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */ + 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */ + 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */ + 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */ + 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */ + 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */ + 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */ + 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */ + 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */ + 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */ + 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */ +#endif +}; + +/* +** The following 256 byte lookup table is used to support SQLites built-in +** equivalents to the following standard library functions: +** +** isspace() 0x01 +** isalpha() 0x02 +** isdigit() 0x04 +** isalnum() 0x06 +** isxdigit() 0x08 +** toupper() 0x20 +** SQLite identifier character 0x40 +** +** Bit 0x20 is set if the mapped character requires translation to upper +** case. i.e. if the character is a lower-case ASCII character. +** If x is a lower-case ASCII character, then its upper-case equivalent +** is (x - 0x20). Therefore toupper() can be implemented as: +** +** (x & ~(map[x]&0x20)) +** +** Standard function tolower() is implemented using the sqlite3UpperToLower[] +** array. tolower() is used more often than toupper() by SQLite. +** +** Bit 0x40 is set if the character non-alphanumeric and can be used in an +** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any +** non-ASCII UTF character. Hence the test for whether or not a character is +** part of an identifier is 0x46. +** +** SQLite's versions are identical to the standard versions assuming a +** locale of "C". They are implemented as macros in sqliteInt.h. +*/ +#ifdef SQLITE_ASCII +SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */ + 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */ + 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */ + 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */ + 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */ + + 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */ + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */ + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */ + 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */ + 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */ + 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */ + 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */ + 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */ + + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */ + + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */ +}; +#endif + +#ifndef SQLITE_USE_URI +# define SQLITE_USE_URI 0 +#endif + +#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN +# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1 +#endif + +/* +** The following singleton contains the global configuration for +** the SQLite library. +*/ +SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = { + SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */ + 1, /* bCoreMutex */ + SQLITE_THREADSAFE==1, /* bFullMutex */ + SQLITE_USE_URI, /* bOpenUri */ + SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */ + 0x7ffffffe, /* mxStrlen */ + 128, /* szLookaside */ + 500, /* nLookaside */ + {0,0,0,0,0,0,0,0}, /* m */ + {0,0,0,0,0,0,0,0,0}, /* mutex */ + {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */ + (void*)0, /* pHeap */ + 0, /* nHeap */ + 0, 0, /* mnHeap, mxHeap */ + SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */ + SQLITE_MAX_MMAP_SIZE, /* mxMmap */ + (void*)0, /* pScratch */ + 0, /* szScratch */ + 0, /* nScratch */ + (void*)0, /* pPage */ + 0, /* szPage */ + 0, /* nPage */ + 0, /* mxParserStack */ + 0, /* sharedCacheEnabled */ + /* All the rest should always be initialized to zero */ + 0, /* isInit */ + 0, /* inProgress */ + 0, /* isMutexInit */ + 0, /* isMallocInit */ + 0, /* isPCacheInit */ + 0, /* pInitMutex */ + 0, /* nRefInitMutex */ + 0, /* xLog */ + 0, /* pLogArg */ + 0, /* bLocaltimeFault */ +#ifdef SQLITE_ENABLE_SQLLOG + 0, /* xSqllog */ + 0 /* pSqllogArg */ +#endif +}; + + +/* +** Hash table for global functions - functions common to all +** database connections. After initialization, this table is +** read-only. +*/ +SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions; + +/* +** Constant tokens for values 0 and 1. +*/ +SQLITE_PRIVATE const Token sqlite3IntTokens[] = { + { "0", 1 }, + { "1", 1 } +}; + + +/* +** The value of the "pending" byte must be 0x40000000 (1 byte past the +** 1-gibabyte boundary) in a compatible database. SQLite never uses +** the database page that contains the pending byte. It never attempts +** to read or write that page. The pending byte page is set assign +** for use by the VFS layers as space for managing file locks. +** +** During testing, it is often desirable to move the pending byte to +** a different position in the file. This allows code that has to +** deal with the pending byte to run on files that are much smaller +** than 1 GiB. The sqlite3_test_control() interface can be used to +** move the pending byte. +** +** IMPORTANT: Changing the pending byte to any value other than +** 0x40000000 results in an incompatible database file format! +** Changing the pending byte during operating results in undefined +** and dileterious behavior. +*/ +#ifndef SQLITE_OMIT_WSD +SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000; +#endif + +/* +** Properties of opcodes. The OPFLG_INITIALIZER macro is +** created by mkopcodeh.awk during compilation. Data is obtained +** from the comments following the "case OP_xxxx:" statements in +** the vdbe.c file. +*/ +SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER; + +/************** End of global.c **********************************************/ +/************** Begin file ctime.c *******************************************/ +/* +** 2010 February 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements routines used to report what compile-time options +** SQLite was built with. +*/ + +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS + + +/* +** An array of names of all compile-time options. This array should +** be sorted A-Z. +** +** This array looks large, but in a typical installation actually uses +** only a handful of compile-time options, so most times this array is usually +** rather short and uses little memory space. +*/ +static const char * const azCompileOpt[] = { + +/* These macros are provided to "stringify" the value of the define +** for those options in which the value is meaningful. */ +#define CTIMEOPT_VAL_(opt) #opt +#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) + +#ifdef SQLITE_32BIT_ROWID + "32BIT_ROWID", +#endif +#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC + "4_BYTE_ALIGNED_MALLOC", +#endif +#ifdef SQLITE_CASE_SENSITIVE_LIKE + "CASE_SENSITIVE_LIKE", +#endif +#ifdef SQLITE_CHECK_PAGES + "CHECK_PAGES", +#endif +#ifdef SQLITE_COVERAGE_TEST + "COVERAGE_TEST", +#endif +#ifdef SQLITE_DEBUG + "DEBUG", +#endif +#ifdef SQLITE_DEFAULT_LOCKING_MODE + "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), +#endif +#if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc) + "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE), +#endif +#ifdef SQLITE_DISABLE_DIRSYNC + "DISABLE_DIRSYNC", +#endif +#ifdef SQLITE_DISABLE_LFS + "DISABLE_LFS", +#endif +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + "ENABLE_ATOMIC_WRITE", +#endif +#ifdef SQLITE_ENABLE_CEROD + "ENABLE_CEROD", +#endif +#ifdef SQLITE_ENABLE_COLUMN_METADATA + "ENABLE_COLUMN_METADATA", +#endif +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT + "ENABLE_EXPENSIVE_ASSERT", +#endif +#ifdef SQLITE_ENABLE_FTS1 + "ENABLE_FTS1", +#endif +#ifdef SQLITE_ENABLE_FTS2 + "ENABLE_FTS2", +#endif +#ifdef SQLITE_ENABLE_FTS3 + "ENABLE_FTS3", +#endif +#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS + "ENABLE_FTS3_PARENTHESIS", +#endif +#ifdef SQLITE_ENABLE_FTS4 + "ENABLE_FTS4", +#endif +#ifdef SQLITE_ENABLE_ICU + "ENABLE_ICU", +#endif +#ifdef SQLITE_ENABLE_IOTRACE + "ENABLE_IOTRACE", +#endif +#ifdef SQLITE_ENABLE_LOAD_EXTENSION + "ENABLE_LOAD_EXTENSION", +#endif +#ifdef SQLITE_ENABLE_LOCKING_STYLE + "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), +#endif +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT + "ENABLE_MEMORY_MANAGEMENT", +#endif +#ifdef SQLITE_ENABLE_MEMSYS3 + "ENABLE_MEMSYS3", +#endif +#ifdef SQLITE_ENABLE_MEMSYS5 + "ENABLE_MEMSYS5", +#endif +#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK + "ENABLE_OVERSIZE_CELL_CHECK", +#endif +#ifdef SQLITE_ENABLE_RTREE + "ENABLE_RTREE", +#endif +#if defined(SQLITE_ENABLE_STAT4) + "ENABLE_STAT4", +#elif defined(SQLITE_ENABLE_STAT3) + "ENABLE_STAT3", +#endif +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + "ENABLE_UNLOCK_NOTIFY", +#endif +#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT + "ENABLE_UPDATE_DELETE_LIMIT", +#endif +#ifdef SQLITE_HAS_CODEC + "HAS_CODEC", +#endif +#ifdef SQLITE_HAVE_ISNAN + "HAVE_ISNAN", +#endif +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + "HOMEGROWN_RECURSIVE_MUTEX", +#endif +#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS + "IGNORE_AFP_LOCK_ERRORS", +#endif +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + "IGNORE_FLOCK_LOCK_ERRORS", +#endif +#ifdef SQLITE_INT64_TYPE + "INT64_TYPE", +#endif +#ifdef SQLITE_LOCK_TRACE + "LOCK_TRACE", +#endif +#if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc) + "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE), +#endif +#ifdef SQLITE_MAX_SCHEMA_RETRY + "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY), +#endif +#ifdef SQLITE_MEMDEBUG + "MEMDEBUG", +#endif +#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT + "MIXED_ENDIAN_64BIT_FLOAT", +#endif +#ifdef SQLITE_NO_SYNC + "NO_SYNC", +#endif +#ifdef SQLITE_OMIT_ALTERTABLE + "OMIT_ALTERTABLE", +#endif +#ifdef SQLITE_OMIT_ANALYZE + "OMIT_ANALYZE", +#endif +#ifdef SQLITE_OMIT_ATTACH + "OMIT_ATTACH", +#endif +#ifdef SQLITE_OMIT_AUTHORIZATION + "OMIT_AUTHORIZATION", +#endif +#ifdef SQLITE_OMIT_AUTOINCREMENT + "OMIT_AUTOINCREMENT", +#endif +#ifdef SQLITE_OMIT_AUTOINIT + "OMIT_AUTOINIT", +#endif +#ifdef SQLITE_OMIT_AUTOMATIC_INDEX + "OMIT_AUTOMATIC_INDEX", +#endif +#ifdef SQLITE_OMIT_AUTORESET + "OMIT_AUTORESET", +#endif +#ifdef SQLITE_OMIT_AUTOVACUUM + "OMIT_AUTOVACUUM", +#endif +#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION + "OMIT_BETWEEN_OPTIMIZATION", +#endif +#ifdef SQLITE_OMIT_BLOB_LITERAL + "OMIT_BLOB_LITERAL", +#endif +#ifdef SQLITE_OMIT_BTREECOUNT + "OMIT_BTREECOUNT", +#endif +#ifdef SQLITE_OMIT_BUILTIN_TEST + "OMIT_BUILTIN_TEST", +#endif +#ifdef SQLITE_OMIT_CAST + "OMIT_CAST", +#endif +#ifdef SQLITE_OMIT_CHECK + "OMIT_CHECK", +#endif +#ifdef SQLITE_OMIT_COMPLETE + "OMIT_COMPLETE", +#endif +#ifdef SQLITE_OMIT_COMPOUND_SELECT + "OMIT_COMPOUND_SELECT", +#endif +#ifdef SQLITE_OMIT_DATETIME_FUNCS + "OMIT_DATETIME_FUNCS", +#endif +#ifdef SQLITE_OMIT_DECLTYPE + "OMIT_DECLTYPE", +#endif +#ifdef SQLITE_OMIT_DEPRECATED + "OMIT_DEPRECATED", +#endif +#ifdef SQLITE_OMIT_DISKIO + "OMIT_DISKIO", +#endif +#ifdef SQLITE_OMIT_EXPLAIN + "OMIT_EXPLAIN", +#endif +#ifdef SQLITE_OMIT_FLAG_PRAGMAS + "OMIT_FLAG_PRAGMAS", +#endif +#ifdef SQLITE_OMIT_FLOATING_POINT + "OMIT_FLOATING_POINT", +#endif +#ifdef SQLITE_OMIT_FOREIGN_KEY + "OMIT_FOREIGN_KEY", +#endif +#ifdef SQLITE_OMIT_GET_TABLE + "OMIT_GET_TABLE", +#endif +#ifdef SQLITE_OMIT_INCRBLOB + "OMIT_INCRBLOB", +#endif +#ifdef SQLITE_OMIT_INTEGRITY_CHECK + "OMIT_INTEGRITY_CHECK", +#endif +#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION + "OMIT_LIKE_OPTIMIZATION", +#endif +#ifdef SQLITE_OMIT_LOAD_EXTENSION + "OMIT_LOAD_EXTENSION", +#endif +#ifdef SQLITE_OMIT_LOCALTIME + "OMIT_LOCALTIME", +#endif +#ifdef SQLITE_OMIT_LOOKASIDE + "OMIT_LOOKASIDE", +#endif +#ifdef SQLITE_OMIT_MEMORYDB + "OMIT_MEMORYDB", +#endif +#ifdef SQLITE_OMIT_OR_OPTIMIZATION + "OMIT_OR_OPTIMIZATION", +#endif +#ifdef SQLITE_OMIT_PAGER_PRAGMAS + "OMIT_PAGER_PRAGMAS", +#endif +#ifdef SQLITE_OMIT_PRAGMA + "OMIT_PRAGMA", +#endif +#ifdef SQLITE_OMIT_PROGRESS_CALLBACK + "OMIT_PROGRESS_CALLBACK", +#endif +#ifdef SQLITE_OMIT_QUICKBALANCE + "OMIT_QUICKBALANCE", +#endif +#ifdef SQLITE_OMIT_REINDEX + "OMIT_REINDEX", +#endif +#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS + "OMIT_SCHEMA_PRAGMAS", +#endif +#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS + "OMIT_SCHEMA_VERSION_PRAGMAS", +#endif +#ifdef SQLITE_OMIT_SHARED_CACHE + "OMIT_SHARED_CACHE", +#endif +#ifdef SQLITE_OMIT_SUBQUERY + "OMIT_SUBQUERY", +#endif +#ifdef SQLITE_OMIT_TCL_VARIABLE + "OMIT_TCL_VARIABLE", +#endif +#ifdef SQLITE_OMIT_TEMPDB + "OMIT_TEMPDB", +#endif +#ifdef SQLITE_OMIT_TRACE + "OMIT_TRACE", +#endif +#ifdef SQLITE_OMIT_TRIGGER + "OMIT_TRIGGER", +#endif +#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION + "OMIT_TRUNCATE_OPTIMIZATION", +#endif +#ifdef SQLITE_OMIT_UTF16 + "OMIT_UTF16", +#endif +#ifdef SQLITE_OMIT_VACUUM + "OMIT_VACUUM", +#endif +#ifdef SQLITE_OMIT_VIEW + "OMIT_VIEW", +#endif +#ifdef SQLITE_OMIT_VIRTUALTABLE + "OMIT_VIRTUALTABLE", +#endif +#ifdef SQLITE_OMIT_WAL + "OMIT_WAL", +#endif +#ifdef SQLITE_OMIT_WSD + "OMIT_WSD", +#endif +#ifdef SQLITE_OMIT_XFER_OPT + "OMIT_XFER_OPT", +#endif +#ifdef SQLITE_PERFORMANCE_TRACE + "PERFORMANCE_TRACE", +#endif +#ifdef SQLITE_PROXY_DEBUG + "PROXY_DEBUG", +#endif +#ifdef SQLITE_RTREE_INT_ONLY + "RTREE_INT_ONLY", +#endif +#ifdef SQLITE_SECURE_DELETE + "SECURE_DELETE", +#endif +#ifdef SQLITE_SMALL_STACK + "SMALL_STACK", +#endif +#ifdef SQLITE_SOUNDEX + "SOUNDEX", +#endif +#ifdef SQLITE_TCL + "TCL", +#endif +#if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc) + "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE), +#endif +#ifdef SQLITE_TEST + "TEST", +#endif +#if defined(SQLITE_THREADSAFE) + "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE), +#endif +#ifdef SQLITE_USE_ALLOCA + "USE_ALLOCA", +#endif +#ifdef SQLITE_ZERO_MALLOC + "ZERO_MALLOC" +#endif +}; + +/* +** Given the name of a compile-time option, return true if that option +** was used and false if not. +** +** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix +** is not required for a match. +*/ +SQLITE_API int sqlite3_compileoption_used(const char *zOptName){ + int i, n; + if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7; + n = sqlite3Strlen30(zOptName); + + /* Since ArraySize(azCompileOpt) is normally in single digits, a + ** linear search is adequate. No need for a binary search. */ + for(i=0; i=0 && NaDb[] (or -1) */ + int pseudoTableReg; /* Register holding pseudotable content. */ + int nField; /* Number of fields in the header */ + Bool zeroed; /* True if zeroed out and ready for reuse */ + Bool rowidIsValid; /* True if lastRowid is valid */ + Bool atFirst; /* True if pointing to first entry */ + Bool useRandomRowid; /* Generate new record numbers semi-randomly */ + Bool nullRow; /* True if pointing to a row with no data */ + Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ + Bool isTable; /* True if a table requiring integer keys */ + Bool isIndex; /* True if an index containing keys only - no data */ + Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */ + Bool isSorter; /* True if a new-style sorter */ + Bool multiPseudo; /* Multi-register pseudo-cursor */ + sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */ + const sqlite3_module *pModule; /* Module for cursor pVtabCursor */ + i64 seqCount; /* Sequence counter */ + i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ + i64 lastRowid; /* Last rowid from a Next or NextIdx operation */ + VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */ + + /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or + ** OP_IsUnique opcode on this cursor. */ + int seekResult; + + /* Cached information about the header for the data record that the + ** cursor is currently pointing to. Only valid if cacheStatus matches + ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of + ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that + ** the cache is out of date. + ** + ** aRow might point to (ephemeral) data for the current row, or it might + ** be NULL. + */ + u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ + int payloadSize; /* Total number of bytes in the record */ + u32 *aType; /* Type values for all entries in the record */ + u32 *aOffset; /* Cached offsets to the start of each columns data */ + u8 *aRow; /* Data for the current row, if all on one page */ +}; +typedef struct VdbeCursor VdbeCursor; + +/* +** When a sub-program is executed (OP_Program), a structure of this type +** is allocated to store the current value of the program counter, as +** well as the current memory cell array and various other frame specific +** values stored in the Vdbe struct. When the sub-program is finished, +** these values are copied back to the Vdbe from the VdbeFrame structure, +** restoring the state of the VM to as it was before the sub-program +** began executing. +** +** The memory for a VdbeFrame object is allocated and managed by a memory +** cell in the parent (calling) frame. When the memory cell is deleted or +** overwritten, the VdbeFrame object is not freed immediately. Instead, it +** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame +** list is deleted when the VM is reset in VdbeHalt(). The reason for doing +** this instead of deleting the VdbeFrame immediately is to avoid recursive +** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the +** child frame are released. +** +** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is +** set to NULL if the currently executing frame is the main program. +*/ +typedef struct VdbeFrame VdbeFrame; +struct VdbeFrame { + Vdbe *v; /* VM this frame belongs to */ + VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */ + Op *aOp; /* Program instructions for parent frame */ + Mem *aMem; /* Array of memory cells for parent frame */ + u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */ + VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */ + void *token; /* Copy of SubProgram.token */ + i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ + int nCursor; /* Number of entries in apCsr */ + int pc; /* Program Counter in parent (calling) frame */ + int nOp; /* Size of aOp array */ + int nMem; /* Number of entries in aMem */ + int nOnceFlag; /* Number of entries in aOnceFlag */ + int nChildMem; /* Number of memory cells for child frame */ + int nChildCsr; /* Number of cursors for child frame */ + int nChange; /* Statement changes (Vdbe.nChanges) */ +}; + +#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))]) + +/* +** A value for VdbeCursor.cacheValid that means the cache is always invalid. +*/ +#define CACHE_STALE 0 + +/* +** Internally, the vdbe manipulates nearly all SQL values as Mem +** structures. Each Mem struct may cache multiple representations (string, +** integer etc.) of the same value. +*/ +struct Mem { + sqlite3 *db; /* The associated database connection */ + char *z; /* String or BLOB value */ + double r; /* Real value */ + union { + i64 i; /* Integer value used when MEM_Int is set in flags */ + int nZero; /* Used when bit MEM_Zero is set in flags */ + FuncDef *pDef; /* Used only when flags==MEM_Agg */ + RowSet *pRowSet; /* Used only when flags==MEM_RowSet */ + VdbeFrame *pFrame; /* Used when flags==MEM_Frame */ + } u; + int n; /* Number of characters in string value, excluding '\0' */ + u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ + u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */ + u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ +#ifdef SQLITE_DEBUG + Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */ + void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */ +#endif + void (*xDel)(void *); /* If not null, call this function to delete Mem.z */ + char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */ +}; + +/* One or more of the following flags are set to indicate the validOK +** representations of the value stored in the Mem struct. +** +** If the MEM_Null flag is set, then the value is an SQL NULL value. +** No other flags may be set in this case. +** +** If the MEM_Str flag is set then Mem.z points at a string representation. +** Usually this is encoded in the same unicode encoding as the main +** database (see below for exceptions). If the MEM_Term flag is also +** set, then the string is nul terminated. The MEM_Int and MEM_Real +** flags may coexist with the MEM_Str flag. +*/ +#define MEM_Null 0x0001 /* Value is NULL */ +#define MEM_Str 0x0002 /* Value is a string */ +#define MEM_Int 0x0004 /* Value is an integer */ +#define MEM_Real 0x0008 /* Value is a real number */ +#define MEM_Blob 0x0010 /* Value is a BLOB */ +#define MEM_RowSet 0x0020 /* Value is a RowSet object */ +#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */ +#define MEM_Invalid 0x0080 /* Value is undefined */ +#define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */ +#define MEM_TypeMask 0x01ff /* Mask of type bits */ + + +/* Whenever Mem contains a valid string or blob representation, one of +** the following flags must be set to determine the memory management +** policy for Mem.z. The MEM_Term flag tells us whether or not the +** string is \000 or \u0000 terminated +*/ +#define MEM_Term 0x0200 /* String rep is nul terminated */ +#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */ +#define MEM_Static 0x0800 /* Mem.z points to a static string */ +#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */ +#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */ +#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */ +#ifdef SQLITE_OMIT_INCRBLOB + #undef MEM_Zero + #define MEM_Zero 0x0000 +#endif + +/* +** Clear any existing type flags from a Mem and replace them with f +*/ +#define MemSetTypeFlag(p, f) \ + ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f) + +/* +** Return true if a memory cell is not marked as invalid. This macro +** is for use inside assert() statements only. +*/ +#ifdef SQLITE_DEBUG +#define memIsValid(M) ((M)->flags & MEM_Invalid)==0 +#endif + +/* +** Each auxilliary data pointer stored by a user defined function +** implementation calling sqlite3_set_auxdata() is stored in an instance +** of this structure. All such structures associated with a single VM +** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed +** when the VM is halted (if not before). +*/ +struct AuxData { + int iOp; /* Instruction number of OP_Function opcode */ + int iArg; /* Index of function argument. */ + void *pAux; /* Aux data pointer */ + void (*xDelete)(void *); /* Destructor for the aux data */ + AuxData *pNext; /* Next element in list */ +}; + +/* +** The "context" argument for a installable function. A pointer to an +** instance of this structure is the first argument to the routines used +** implement the SQL functions. +** +** There is a typedef for this structure in sqlite.h. So all routines, +** even the public interface to SQLite, can use a pointer to this structure. +** But this file is the only place where the internal details of this +** structure are known. +** +** This structure is defined inside of vdbeInt.h because it uses substructures +** (Mem) which are only defined there. +*/ +struct sqlite3_context { + FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */ + Mem s; /* The return value is stored here */ + Mem *pMem; /* Memory cell used to store aggregate context */ + CollSeq *pColl; /* Collating sequence */ + Vdbe *pVdbe; /* The VM that owns this context */ + int iOp; /* Instruction number of OP_Function */ + int isError; /* Error code returned by the function. */ + u8 skipFlag; /* Skip skip accumulator loading if true */ + u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */ +}; + +/* +** An Explain object accumulates indented output which is helpful +** in describing recursive data structures. +*/ +struct Explain { + Vdbe *pVdbe; /* Attach the explanation to this Vdbe */ + StrAccum str; /* The string being accumulated */ + int nIndent; /* Number of elements in aIndent */ + u16 aIndent[100]; /* Levels of indentation */ + char zBase[100]; /* Initial space */ +}; + +/* A bitfield type for use inside of structures. Always follow with :N where +** N is the number of bits. +*/ +typedef unsigned bft; /* Bit Field Type */ + +/* +** An instance of the virtual machine. This structure contains the complete +** state of the virtual machine. +** +** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare() +** is really a pointer to an instance of this structure. +** +** The Vdbe.inVtabMethod variable is set to non-zero for the duration of +** any virtual table method invocations made by the vdbe program. It is +** set to 2 for xDestroy method calls and 1 for all other methods. This +** variable is used for two purposes: to allow xDestroy methods to execute +** "DROP TABLE" statements and to prevent some nasty side effects of +** malloc failure when SQLite is invoked recursively by a virtual table +** method function. +*/ +struct Vdbe { + sqlite3 *db; /* The database connection that owns this statement */ + Op *aOp; /* Space to hold the virtual machine's program */ + Mem *aMem; /* The memory locations */ + Mem **apArg; /* Arguments to currently executing user function */ + Mem *aColName; /* Column names to return */ + Mem *pResultSet; /* Pointer to an array of results */ + int nMem; /* Number of memory locations currently allocated */ + int nOp; /* Number of instructions in the program */ + int nOpAlloc; /* Number of slots allocated for aOp[] */ + int nLabel; /* Number of labels used */ + int *aLabel; /* Space to hold the labels */ + u16 nResColumn; /* Number of columns in one row of the result set */ + int nCursor; /* Number of slots in apCsr[] */ + u32 magic; /* Magic number for sanity checking */ + char *zErrMsg; /* Error message written here */ + Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */ + VdbeCursor **apCsr; /* One element of this array for each open cursor */ + Mem *aVar; /* Values for the OP_Variable opcode. */ + char **azVar; /* Name of variables */ + ynVar nVar; /* Number of entries in aVar[] */ + ynVar nzVar; /* Number of entries in azVar[] */ + u32 cacheCtr; /* VdbeCursor row cache generation counter */ + int pc; /* The program counter */ + int rc; /* Value to return */ + u8 errorAction; /* Recovery action to do in case of an error */ + u8 minWriteFileFormat; /* Minimum file format for writable database files */ + bft explain:2; /* True if EXPLAIN present on SQL command */ + bft inVtabMethod:2; /* See comments above */ + bft changeCntOn:1; /* True to update the change-counter */ + bft expired:1; /* True if the VM needs to be recompiled */ + bft runOnlyOnce:1; /* Automatically expire on reset */ + bft usesStmtJournal:1; /* True if uses a statement journal */ + bft readOnly:1; /* True for statements that do not write */ + bft bIsReader:1; /* True for statements that read */ + bft isPrepareV2:1; /* True if prepared with prepare_v2() */ + bft doingRerun:1; /* True if rerunning after an auto-reprepare */ + int nChange; /* Number of db changes made since last reset */ + yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */ + yDbMask lockMask; /* Subset of btreeMask that requires a lock */ + int iStatement; /* Statement number (or 0 if has not opened stmt) */ + u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */ +#ifndef SQLITE_OMIT_TRACE + i64 startTime; /* Time when query started - used for profiling */ +#endif + i64 iCurrentTime; /* Value of julianday('now') for this statement */ + i64 nFkConstraint; /* Number of imm. FK constraints this VM */ + i64 nStmtDefCons; /* Number of def. constraints when stmt started */ + i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */ + char *zSql; /* Text of the SQL statement that generated this */ + void *pFree; /* Free this when deleting the vdbe */ +#ifdef SQLITE_DEBUG + FILE *trace; /* Write an execution trace here, if not NULL */ +#endif +#ifdef SQLITE_ENABLE_TREE_EXPLAIN + Explain *pExplain; /* The explainer */ + char *zExplain; /* Explanation of data structures */ +#endif + VdbeFrame *pFrame; /* Parent frame */ + VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */ + int nFrame; /* Number of frames in pFrame list */ + u32 expmask; /* Binding to these vars invalidates VM */ + SubProgram *pProgram; /* Linked list of all sub-programs used by VM */ + int nOnceFlag; /* Size of array aOnceFlag[] */ + u8 *aOnceFlag; /* Flags for OP_Once */ + AuxData *pAuxData; /* Linked list of auxdata allocations */ +}; + +/* +** The following are allowed values for Vdbe.magic +*/ +#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */ +#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */ +#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */ +#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */ + +/* +** Function prototypes +*/ +SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); +void sqliteVdbePopStack(Vdbe*,int); +SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*); +#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) +SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*); +#endif +SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32); +SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int); +SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int); +SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); +SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int); + +int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); +SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*); +SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *); +SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); +SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*); +SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*); +SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*); +SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int); +SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*); +SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); +SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); +SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64); +#ifdef SQLITE_OMIT_FLOATING_POINT +# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 +#else +SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double); +#endif +SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*); +SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int); +SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int); +SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*); +SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*); +SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*); +SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p); +SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p); +#define VdbeMemRelease(X) \ + if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \ + sqlite3VdbeMemReleaseExternal(X); +SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*); +SQLITE_PRIVATE const char *sqlite3OpcodeName(int); +SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve); +SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int); +SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); +SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *); +SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem); +SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p); + +SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *); +SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *); +SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *); +SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *); +SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *); +SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *); +SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *); + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 +SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*); +#else +# define sqlite3VdbeEnter(X) +# define sqlite3VdbeLeave(X) +#endif + +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*); +#endif + +#ifndef SQLITE_OMIT_FOREIGN_KEY +SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int); +#else +# define sqlite3VdbeCheckFk(p,i) 0 +#endif + +SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf); +#endif +SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem); + +#ifndef SQLITE_OMIT_INCRBLOB +SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *); + #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0) +#else + #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK + #define ExpandBlob(P) SQLITE_OK +#endif + +#endif /* !defined(_VDBEINT_H_) */ + +/************** End of vdbeInt.h *********************************************/ +/************** Continuing where we left off in status.c *********************/ + +/* +** Variables in which to record status information. +*/ +typedef struct sqlite3StatType sqlite3StatType; +static SQLITE_WSD struct sqlite3StatType { + int nowValue[10]; /* Current value */ + int mxValue[10]; /* Maximum value */ +} sqlite3Stat = { {0,}, {0,} }; + + +/* The "wsdStat" macro will resolve to the status information +** state vector. If writable static data is unsupported on the target, +** we have to locate the state vector at run-time. In the more common +** case where writable static data is supported, wsdStat can refer directly +** to the "sqlite3Stat" state vector declared above. +*/ +#ifdef SQLITE_OMIT_WSD +# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat) +# define wsdStat x[0] +#else +# define wsdStatInit +# define wsdStat sqlite3Stat +#endif + +/* +** Return the current value of a status parameter. +*/ +SQLITE_PRIVATE int sqlite3StatusValue(int op){ + wsdStatInit; + assert( op>=0 && op=0 && opwsdStat.mxValue[op] ){ + wsdStat.mxValue[op] = wsdStat.nowValue[op]; + } +} + +/* +** Set the value of a status to X. +*/ +SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){ + wsdStatInit; + assert( op>=0 && opwsdStat.mxValue[op] ){ + wsdStat.mxValue[op] = wsdStat.nowValue[op]; + } +} + +/* +** Query status information. +** +** This implementation assumes that reading or writing an aligned +** 32-bit integer is an atomic operation. If that assumption is not true, +** then this routine is not threadsafe. +*/ +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){ + wsdStatInit; + if( op<0 || op>=ArraySize(wsdStat.nowValue) ){ + return SQLITE_MISUSE_BKPT; + } + *pCurrent = wsdStat.nowValue[op]; + *pHighwater = wsdStat.mxValue[op]; + if( resetFlag ){ + wsdStat.mxValue[op] = wsdStat.nowValue[op]; + } + return SQLITE_OK; +} + +/* +** Query status information for a single database connection +*/ +SQLITE_API int sqlite3_db_status( + sqlite3 *db, /* The database connection whose status is desired */ + int op, /* Status verb */ + int *pCurrent, /* Write current value here */ + int *pHighwater, /* Write high-water mark here */ + int resetFlag /* Reset high-water mark if true */ +){ + int rc = SQLITE_OK; /* Return code */ + sqlite3_mutex_enter(db->mutex); + switch( op ){ + case SQLITE_DBSTATUS_LOOKASIDE_USED: { + *pCurrent = db->lookaside.nOut; + *pHighwater = db->lookaside.mxOut; + if( resetFlag ){ + db->lookaside.mxOut = db->lookaside.nOut; + } + break; + } + + case SQLITE_DBSTATUS_LOOKASIDE_HIT: + case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE: + case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: { + testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT ); + testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE ); + testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL ); + assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 ); + assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 ); + *pCurrent = 0; + *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT]; + if( resetFlag ){ + db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0; + } + break; + } + + /* + ** Return an approximation for the amount of memory currently used + ** by all pagers associated with the given database connection. The + ** highwater mark is meaningless and is returned as zero. + */ + case SQLITE_DBSTATUS_CACHE_USED: { + int totalUsed = 0; + int i; + sqlite3BtreeEnterAll(db); + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + Pager *pPager = sqlite3BtreePager(pBt); + totalUsed += sqlite3PagerMemUsed(pPager); + } + } + sqlite3BtreeLeaveAll(db); + *pCurrent = totalUsed; + *pHighwater = 0; + break; + } + + /* + ** *pCurrent gets an accurate estimate of the amount of memory used + ** to store the schema for all databases (main, temp, and any ATTACHed + ** databases. *pHighwater is set to zero. + */ + case SQLITE_DBSTATUS_SCHEMA_USED: { + int i; /* Used to iterate through schemas */ + int nByte = 0; /* Used to accumulate return value */ + + sqlite3BtreeEnterAll(db); + db->pnBytesFreed = &nByte; + for(i=0; inDb; i++){ + Schema *pSchema = db->aDb[i].pSchema; + if( ALWAYS(pSchema!=0) ){ + HashElem *p; + + nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * ( + pSchema->tblHash.count + + pSchema->trigHash.count + + pSchema->idxHash.count + + pSchema->fkeyHash.count + ); + nByte += sqlite3MallocSize(pSchema->tblHash.ht); + nByte += sqlite3MallocSize(pSchema->trigHash.ht); + nByte += sqlite3MallocSize(pSchema->idxHash.ht); + nByte += sqlite3MallocSize(pSchema->fkeyHash.ht); + + for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){ + sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p)); + } + for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ + sqlite3DeleteTable(db, (Table *)sqliteHashData(p)); + } + } + } + db->pnBytesFreed = 0; + sqlite3BtreeLeaveAll(db); + + *pHighwater = 0; + *pCurrent = nByte; + break; + } + + /* + ** *pCurrent gets an accurate estimate of the amount of memory used + ** to store all prepared statements. + ** *pHighwater is set to zero. + */ + case SQLITE_DBSTATUS_STMT_USED: { + struct Vdbe *pVdbe; /* Used to iterate through VMs */ + int nByte = 0; /* Used to accumulate return value */ + + db->pnBytesFreed = &nByte; + for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){ + sqlite3VdbeClearObject(db, pVdbe); + sqlite3DbFree(db, pVdbe); + } + db->pnBytesFreed = 0; + + *pHighwater = 0; + *pCurrent = nByte; + + break; + } + + /* + ** Set *pCurrent to the total cache hits or misses encountered by all + ** pagers the database handle is connected to. *pHighwater is always set + ** to zero. + */ + case SQLITE_DBSTATUS_CACHE_HIT: + case SQLITE_DBSTATUS_CACHE_MISS: + case SQLITE_DBSTATUS_CACHE_WRITE:{ + int i; + int nRet = 0; + assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 ); + assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 ); + + for(i=0; inDb; i++){ + if( db->aDb[i].pBt ){ + Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt); + sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet); + } + } + *pHighwater = 0; + *pCurrent = nRet; + break; + } + + /* Set *pCurrent to non-zero if there are unresolved deferred foreign + ** key constraints. Set *pCurrent to zero if all foreign key constraints + ** have been satisfied. The *pHighwater is always set to zero. + */ + case SQLITE_DBSTATUS_DEFERRED_FKS: { + *pHighwater = 0; + *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0; + break; + } + + default: { + rc = SQLITE_ERROR; + } + } + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/************** End of status.c **********************************************/ +/************** Begin file date.c ********************************************/ +/* +** 2003 October 31 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement date and time +** functions for SQLite. +** +** There is only one exported symbol in this file - the function +** sqlite3RegisterDateTimeFunctions() found at the bottom of the file. +** All other code has file scope. +** +** SQLite processes all times and dates as Julian Day numbers. The +** dates and times are stored as the number of days since noon +** in Greenwich on November 24, 4714 B.C. according to the Gregorian +** calendar system. +** +** 1970-01-01 00:00:00 is JD 2440587.5 +** 2000-01-01 00:00:00 is JD 2451544.5 +** +** This implemention requires years to be expressed as a 4-digit number +** which means that only dates between 0000-01-01 and 9999-12-31 can +** be represented, even though julian day numbers allow a much wider +** range of dates. +** +** The Gregorian calendar system is used for all dates and times, +** even those that predate the Gregorian calendar. Historians usually +** use the Julian calendar for dates prior to 1582-10-15 and for some +** dates afterwards, depending on locale. Beware of this difference. +** +** The conversion algorithms are implemented based on descriptions +** in the following text: +** +** Jean Meeus +** Astronomical Algorithms, 2nd Edition, 1998 +** ISBM 0-943396-61-1 +** Willmann-Bell, Inc +** Richmond, Virginia (USA) +*/ +/* #include */ +/* #include */ +#include + +#ifndef SQLITE_OMIT_DATETIME_FUNCS + + +/* +** A structure for holding a single date and time. +*/ +typedef struct DateTime DateTime; +struct DateTime { + sqlite3_int64 iJD; /* The julian day number times 86400000 */ + int Y, M, D; /* Year, month, and day */ + int h, m; /* Hour and minutes */ + int tz; /* Timezone offset in minutes */ + double s; /* Seconds */ + char validYMD; /* True (1) if Y,M,D are valid */ + char validHMS; /* True (1) if h,m,s are valid */ + char validJD; /* True (1) if iJD is valid */ + char validTZ; /* True (1) if tz is valid */ +}; + + +/* +** Convert zDate into one or more integers. Additional arguments +** come in groups of 5 as follows: +** +** N number of digits in the integer +** min minimum allowed value of the integer +** max maximum allowed value of the integer +** nextC first character after the integer +** pVal where to write the integers value. +** +** Conversions continue until one with nextC==0 is encountered. +** The function returns the number of successful conversions. +*/ +static int getDigits(const char *zDate, ...){ + va_list ap; + int val; + int N; + int min; + int max; + int nextC; + int *pVal; + int cnt = 0; + va_start(ap, zDate); + do{ + N = va_arg(ap, int); + min = va_arg(ap, int); + max = va_arg(ap, int); + nextC = va_arg(ap, int); + pVal = va_arg(ap, int*); + val = 0; + while( N-- ){ + if( !sqlite3Isdigit(*zDate) ){ + goto end_getDigits; + } + val = val*10 + *zDate - '0'; + zDate++; + } + if( valmax || (nextC!=0 && nextC!=*zDate) ){ + goto end_getDigits; + } + *pVal = val; + zDate++; + cnt++; + }while( nextC ); +end_getDigits: + va_end(ap); + return cnt; +} + +/* +** Parse a timezone extension on the end of a date-time. +** The extension is of the form: +** +** (+/-)HH:MM +** +** Or the "zulu" notation: +** +** Z +** +** If the parse is successful, write the number of minutes +** of change in p->tz and return 0. If a parser error occurs, +** return non-zero. +** +** A missing specifier is not considered an error. +*/ +static int parseTimezone(const char *zDate, DateTime *p){ + int sgn = 0; + int nHr, nMn; + int c; + while( sqlite3Isspace(*zDate) ){ zDate++; } + p->tz = 0; + c = *zDate; + if( c=='-' ){ + sgn = -1; + }else if( c=='+' ){ + sgn = +1; + }else if( c=='Z' || c=='z' ){ + zDate++; + goto zulu_time; + }else{ + return c!=0; + } + zDate++; + if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){ + return 1; + } + zDate += 5; + p->tz = sgn*(nMn + nHr*60); +zulu_time: + while( sqlite3Isspace(*zDate) ){ zDate++; } + return *zDate!=0; +} + +/* +** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF. +** The HH, MM, and SS must each be exactly 2 digits. The +** fractional seconds FFFF can be one or more digits. +** +** Return 1 if there is a parsing error and 0 on success. +*/ +static int parseHhMmSs(const char *zDate, DateTime *p){ + int h, m, s; + double ms = 0.0; + if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){ + return 1; + } + zDate += 5; + if( *zDate==':' ){ + zDate++; + if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){ + return 1; + } + zDate += 2; + if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){ + double rScale = 1.0; + zDate++; + while( sqlite3Isdigit(*zDate) ){ + ms = ms*10.0 + *zDate - '0'; + rScale *= 10.0; + zDate++; + } + ms /= rScale; + } + }else{ + s = 0; + } + p->validJD = 0; + p->validHMS = 1; + p->h = h; + p->m = m; + p->s = s + ms; + if( parseTimezone(zDate, p) ) return 1; + p->validTZ = (p->tz!=0)?1:0; + return 0; +} + +/* +** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume +** that the YYYY-MM-DD is according to the Gregorian calendar. +** +** Reference: Meeus page 61 +*/ +static void computeJD(DateTime *p){ + int Y, M, D, A, B, X1, X2; + + if( p->validJD ) return; + if( p->validYMD ){ + Y = p->Y; + M = p->M; + D = p->D; + }else{ + Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */ + M = 1; + D = 1; + } + if( M<=2 ){ + Y--; + M += 12; + } + A = Y/100; + B = 2 - A + (A/4); + X1 = 36525*(Y+4716)/100; + X2 = 306001*(M+1)/10000; + p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000); + p->validJD = 1; + if( p->validHMS ){ + p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000); + if( p->validTZ ){ + p->iJD -= p->tz*60000; + p->validYMD = 0; + p->validHMS = 0; + p->validTZ = 0; + } + } +} + +/* +** Parse dates of the form +** +** YYYY-MM-DD HH:MM:SS.FFF +** YYYY-MM-DD HH:MM:SS +** YYYY-MM-DD HH:MM +** YYYY-MM-DD +** +** Write the result into the DateTime structure and return 0 +** on success and 1 if the input string is not a well-formed +** date. +*/ +static int parseYyyyMmDd(const char *zDate, DateTime *p){ + int Y, M, D, neg; + + if( zDate[0]=='-' ){ + zDate++; + neg = 1; + }else{ + neg = 0; + } + if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){ + return 1; + } + zDate += 10; + while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; } + if( parseHhMmSs(zDate, p)==0 ){ + /* We got the time */ + }else if( *zDate==0 ){ + p->validHMS = 0; + }else{ + return 1; + } + p->validJD = 0; + p->validYMD = 1; + p->Y = neg ? -Y : Y; + p->M = M; + p->D = D; + if( p->validTZ ){ + computeJD(p); + } + return 0; +} + +/* +** Set the time to the current time reported by the VFS. +** +** Return the number of errors. +*/ +static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){ + p->iJD = sqlite3StmtCurrentTime(context); + if( p->iJD>0 ){ + p->validJD = 1; + return 0; + }else{ + return 1; + } +} + +/* +** Attempt to parse the given string into a Julian Day Number. Return +** the number of errors. +** +** The following are acceptable forms for the input string: +** +** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM +** DDDD.DD +** now +** +** In the first form, the +/-HH:MM is always optional. The fractional +** seconds extension (the ".FFF") is optional. The seconds portion +** (":SS.FFF") is option. The year and date can be omitted as long +** as there is a time string. The time string can be omitted as long +** as there is a year and date. +*/ +static int parseDateOrTime( + sqlite3_context *context, + const char *zDate, + DateTime *p +){ + double r; + if( parseYyyyMmDd(zDate,p)==0 ){ + return 0; + }else if( parseHhMmSs(zDate, p)==0 ){ + return 0; + }else if( sqlite3StrICmp(zDate,"now")==0){ + return setDateTimeToCurrent(context, p); + }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){ + p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5); + p->validJD = 1; + return 0; + } + return 1; +} + +/* +** Compute the Year, Month, and Day from the julian day number. +*/ +static void computeYMD(DateTime *p){ + int Z, A, B, C, D, E, X1; + if( p->validYMD ) return; + if( !p->validJD ){ + p->Y = 2000; + p->M = 1; + p->D = 1; + }else{ + Z = (int)((p->iJD + 43200000)/86400000); + A = (int)((Z - 1867216.25)/36524.25); + A = Z + 1 + A - (A/4); + B = A + 1524; + C = (int)((B - 122.1)/365.25); + D = (36525*C)/100; + E = (int)((B-D)/30.6001); + X1 = (int)(30.6001*E); + p->D = B - D - X1; + p->M = E<14 ? E-1 : E-13; + p->Y = p->M>2 ? C - 4716 : C - 4715; + } + p->validYMD = 1; +} + +/* +** Compute the Hour, Minute, and Seconds from the julian day number. +*/ +static void computeHMS(DateTime *p){ + int s; + if( p->validHMS ) return; + computeJD(p); + s = (int)((p->iJD + 43200000) % 86400000); + p->s = s/1000.0; + s = (int)p->s; + p->s -= s; + p->h = s/3600; + s -= p->h*3600; + p->m = s/60; + p->s += s - p->m*60; + p->validHMS = 1; +} + +/* +** Compute both YMD and HMS +*/ +static void computeYMD_HMS(DateTime *p){ + computeYMD(p); + computeHMS(p); +} + +/* +** Clear the YMD and HMS and the TZ +*/ +static void clearYMD_HMS_TZ(DateTime *p){ + p->validYMD = 0; + p->validHMS = 0; + p->validTZ = 0; +} + +/* +** On recent Windows platforms, the localtime_s() function is available +** as part of the "Secure CRT". It is essentially equivalent to +** localtime_r() available under most POSIX platforms, except that the +** order of the parameters is reversed. +** +** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx. +** +** If the user has not indicated to use localtime_r() or localtime_s() +** already, check for an MSVC build environment that provides +** localtime_s(). +*/ +#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \ + defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE) +#define HAVE_LOCALTIME_S 1 +#endif + +#ifndef SQLITE_OMIT_LOCALTIME +/* +** The following routine implements the rough equivalent of localtime_r() +** using whatever operating-system specific localtime facility that +** is available. This routine returns 0 on success and +** non-zero on any kind of error. +** +** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this +** routine will always fail. +** +** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C +** library function localtime_r() is used to assist in the calculation of +** local time. +*/ +static int osLocaltime(time_t *t, struct tm *pTm){ + int rc; +#if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \ + && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S) + struct tm *pX; +#if SQLITE_THREADSAFE>0 + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter(mutex); + pX = localtime(t); +#ifndef SQLITE_OMIT_BUILTIN_TEST + if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0; +#endif + if( pX ) *pTm = *pX; + sqlite3_mutex_leave(mutex); + rc = pX==0; +#else +#ifndef SQLITE_OMIT_BUILTIN_TEST + if( sqlite3GlobalConfig.bLocaltimeFault ) return 1; +#endif +#if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R + rc = localtime_r(t, pTm)==0; +#else + rc = localtime_s(pTm, t); +#endif /* HAVE_LOCALTIME_R */ +#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */ + return rc; +} +#endif /* SQLITE_OMIT_LOCALTIME */ + + +#ifndef SQLITE_OMIT_LOCALTIME +/* +** Compute the difference (in milliseconds) between localtime and UTC +** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs, +** return this value and set *pRc to SQLITE_OK. +** +** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value +** is undefined in this case. +*/ +static sqlite3_int64 localtimeOffset( + DateTime *p, /* Date at which to calculate offset */ + sqlite3_context *pCtx, /* Write error here if one occurs */ + int *pRc /* OUT: Error code. SQLITE_OK or ERROR */ +){ + DateTime x, y; + time_t t; + struct tm sLocal; + + /* Initialize the contents of sLocal to avoid a compiler warning. */ + memset(&sLocal, 0, sizeof(sLocal)); + + x = *p; + computeYMD_HMS(&x); + if( x.Y<1971 || x.Y>=2038 ){ + /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only + ** works for years between 1970 and 2037. For dates outside this range, + ** SQLite attempts to map the year into an equivalent year within this + ** range, do the calculation, then map the year back. + */ + x.Y = 2000; + x.M = 1; + x.D = 1; + x.h = 0; + x.m = 0; + x.s = 0.0; + } else { + int s = (int)(x.s + 0.5); + x.s = s; + } + x.tz = 0; + x.validJD = 0; + computeJD(&x); + t = (time_t)(x.iJD/1000 - 21086676*(i64)10000); + if( osLocaltime(&t, &sLocal) ){ + sqlite3_result_error(pCtx, "local time unavailable", -1); + *pRc = SQLITE_ERROR; + return 0; + } + y.Y = sLocal.tm_year + 1900; + y.M = sLocal.tm_mon + 1; + y.D = sLocal.tm_mday; + y.h = sLocal.tm_hour; + y.m = sLocal.tm_min; + y.s = sLocal.tm_sec; + y.validYMD = 1; + y.validHMS = 1; + y.validJD = 0; + y.validTZ = 0; + computeJD(&y); + *pRc = SQLITE_OK; + return y.iJD - x.iJD; +} +#endif /* SQLITE_OMIT_LOCALTIME */ + +/* +** Process a modifier to a date-time stamp. The modifiers are +** as follows: +** +** NNN days +** NNN hours +** NNN minutes +** NNN.NNNN seconds +** NNN months +** NNN years +** start of month +** start of year +** start of week +** start of day +** weekday N +** unixepoch +** localtime +** utc +** +** Return 0 on success and 1 if there is any kind of error. If the error +** is in a system call (i.e. localtime()), then an error message is written +** to context pCtx. If the error is an unrecognized modifier, no error is +** written to pCtx. +*/ +static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ + int rc = 1; + int n; + double r; + char *z, zBuf[30]; + z = zBuf; + for(n=0; niJD += localtimeOffset(p, pCtx, &rc); + clearYMD_HMS_TZ(p); + } + break; + } +#endif + case 'u': { + /* + ** unixepoch + ** + ** Treat the current value of p->iJD as the number of + ** seconds since 1970. Convert to a real julian day number. + */ + if( strcmp(z, "unixepoch")==0 && p->validJD ){ + p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000; + clearYMD_HMS_TZ(p); + rc = 0; + } +#ifndef SQLITE_OMIT_LOCALTIME + else if( strcmp(z, "utc")==0 ){ + sqlite3_int64 c1; + computeJD(p); + c1 = localtimeOffset(p, pCtx, &rc); + if( rc==SQLITE_OK ){ + p->iJD -= c1; + clearYMD_HMS_TZ(p); + p->iJD += c1 - localtimeOffset(p, pCtx, &rc); + } + } +#endif + break; + } + case 'w': { + /* + ** weekday N + ** + ** Move the date to the same time on the next occurrence of + ** weekday N where 0==Sunday, 1==Monday, and so forth. If the + ** date is already on the appropriate weekday, this is a no-op. + */ + if( strncmp(z, "weekday ", 8)==0 + && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8) + && (n=(int)r)==r && n>=0 && r<7 ){ + sqlite3_int64 Z; + computeYMD_HMS(p); + p->validTZ = 0; + p->validJD = 0; + computeJD(p); + Z = ((p->iJD + 129600000)/86400000) % 7; + if( Z>n ) Z -= 7; + p->iJD += (n - Z)*86400000; + clearYMD_HMS_TZ(p); + rc = 0; + } + break; + } + case 's': { + /* + ** start of TTTTT + ** + ** Move the date backwards to the beginning of the current day, + ** or month or year. + */ + if( strncmp(z, "start of ", 9)!=0 ) break; + z += 9; + computeYMD(p); + p->validHMS = 1; + p->h = p->m = 0; + p->s = 0.0; + p->validTZ = 0; + p->validJD = 0; + if( strcmp(z,"month")==0 ){ + p->D = 1; + rc = 0; + }else if( strcmp(z,"year")==0 ){ + computeYMD(p); + p->M = 1; + p->D = 1; + rc = 0; + }else if( strcmp(z,"day")==0 ){ + rc = 0; + } + break; + } + case '+': + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { + double rRounder; + for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){} + if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){ + rc = 1; + break; + } + if( z[n]==':' ){ + /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the + ** specified number of hours, minutes, seconds, and fractional seconds + ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be + ** omitted. + */ + const char *z2 = z; + DateTime tx; + sqlite3_int64 day; + if( !sqlite3Isdigit(*z2) ) z2++; + memset(&tx, 0, sizeof(tx)); + if( parseHhMmSs(z2, &tx) ) break; + computeJD(&tx); + tx.iJD -= 43200000; + day = tx.iJD/86400000; + tx.iJD -= day*86400000; + if( z[0]=='-' ) tx.iJD = -tx.iJD; + computeJD(p); + clearYMD_HMS_TZ(p); + p->iJD += tx.iJD; + rc = 0; + break; + } + z += n; + while( sqlite3Isspace(*z) ) z++; + n = sqlite3Strlen30(z); + if( n>10 || n<3 ) break; + if( z[n-1]=='s' ){ z[n-1] = 0; n--; } + computeJD(p); + rc = 0; + rRounder = r<0 ? -0.5 : +0.5; + if( n==3 && strcmp(z,"day")==0 ){ + p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder); + }else if( n==4 && strcmp(z,"hour")==0 ){ + p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder); + }else if( n==6 && strcmp(z,"minute")==0 ){ + p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder); + }else if( n==6 && strcmp(z,"second")==0 ){ + p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder); + }else if( n==5 && strcmp(z,"month")==0 ){ + int x, y; + computeYMD_HMS(p); + p->M += (int)r; + x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; + p->Y += x; + p->M -= x*12; + p->validJD = 0; + computeJD(p); + y = (int)r; + if( y!=r ){ + p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder); + } + }else if( n==4 && strcmp(z,"year")==0 ){ + int y = (int)r; + computeYMD_HMS(p); + p->Y += y; + p->validJD = 0; + computeJD(p); + if( y!=r ){ + p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder); + } + }else{ + rc = 1; + } + clearYMD_HMS_TZ(p); + break; + } + default: { + break; + } + } + return rc; +} + +/* +** Process time function arguments. argv[0] is a date-time stamp. +** argv[1] and following are modifiers. Parse them all and write +** the resulting time into the DateTime structure p. Return 0 +** on success and 1 if there are any errors. +** +** If there are zero parameters (if even argv[0] is undefined) +** then assume a default value of "now" for argv[0]. +*/ +static int isDate( + sqlite3_context *context, + int argc, + sqlite3_value **argv, + DateTime *p +){ + int i; + const unsigned char *z; + int eType; + memset(p, 0, sizeof(*p)); + if( argc==0 ){ + return setDateTimeToCurrent(context, p); + } + if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT + || eType==SQLITE_INTEGER ){ + p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5); + p->validJD = 1; + }else{ + z = sqlite3_value_text(argv[0]); + if( !z || parseDateOrTime(context, (char*)z, p) ){ + return 1; + } + } + for(i=1; iaLimit[SQLITE_LIMIT_LENGTH]+1 ); + testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ); + if( n(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){ + sqlite3_result_error_toobig(context); + return; + }else{ + z = sqlite3DbMallocRaw(db, (int)n); + if( z==0 ){ + sqlite3_result_error_nomem(context); + return; + } + } + computeJD(&x); + computeYMD_HMS(&x); + for(i=j=0; zFmt[i]; i++){ + if( zFmt[i]!='%' ){ + z[j++] = zFmt[i]; + }else{ + i++; + switch( zFmt[i] ){ + case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break; + case 'f': { + double s = x.s; + if( s>59.999 ) s = 59.999; + sqlite3_snprintf(7, &z[j],"%06.3f", s); + j += sqlite3Strlen30(&z[j]); + break; + } + case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break; + case 'W': /* Fall thru */ + case 'j': { + int nDay; /* Number of days since 1st day of year */ + DateTime y = x; + y.validJD = 0; + y.M = 1; + y.D = 1; + computeJD(&y); + nDay = (int)((x.iJD-y.iJD+43200000)/86400000); + if( zFmt[i]=='W' ){ + int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */ + wd = (int)(((x.iJD+43200000)/86400000)%7); + sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7); + j += 2; + }else{ + sqlite3_snprintf(4, &z[j],"%03d",nDay+1); + j += 3; + } + break; + } + case 'J': { + sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0); + j+=sqlite3Strlen30(&z[j]); + break; + } + case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break; + case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break; + case 's': { + sqlite3_snprintf(30,&z[j],"%lld", + (i64)(x.iJD/1000 - 21086676*(i64)10000)); + j += sqlite3Strlen30(&z[j]); + break; + } + case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break; + case 'w': { + z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0'; + break; + } + case 'Y': { + sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]); + break; + } + default: z[j++] = '%'; break; + } + } + } + z[j] = 0; + sqlite3_result_text(context, z, -1, + z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC); +} + +/* +** current_time() +** +** This function returns the same value as time('now'). +*/ +static void ctimeFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + timeFunc(context, 0, 0); +} + +/* +** current_date() +** +** This function returns the same value as date('now'). +*/ +static void cdateFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + dateFunc(context, 0, 0); +} + +/* +** current_timestamp() +** +** This function returns the same value as datetime('now'). +*/ +static void ctimestampFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + datetimeFunc(context, 0, 0); +} +#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */ + +#ifdef SQLITE_OMIT_DATETIME_FUNCS +/* +** If the library is compiled to omit the full-scale date and time +** handling (to get a smaller binary), the following minimal version +** of the functions current_time(), current_date() and current_timestamp() +** are included instead. This is to support column declarations that +** include "DEFAULT CURRENT_TIME" etc. +** +** This function uses the C-library functions time(), gmtime() +** and strftime(). The format string to pass to strftime() is supplied +** as the user-data for the function. +*/ +static void currentTimeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + time_t t; + char *zFormat = (char *)sqlite3_user_data(context); + sqlite3 *db; + sqlite3_int64 iT; + struct tm *pTm; + struct tm sNow; + char zBuf[20]; + + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + + iT = sqlite3StmtCurrentTime(context); + if( iT<=0 ) return; + t = iT/1000 - 10000*(sqlite3_int64)21086676; +#ifdef HAVE_GMTIME_R + pTm = gmtime_r(&t, &sNow); +#else + sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); + pTm = gmtime(&t); + if( pTm ) memcpy(&sNow, pTm, sizeof(sNow)); + sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +#endif + if( pTm ){ + strftime(zBuf, 20, zFormat, &sNow); + sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + } +} +#endif + +/* +** This function registered all of the above C functions as SQL +** functions. This should be the only routine in this file with +** external linkage. +*/ +SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){ + static SQLITE_WSD FuncDef aDateTimeFuncs[] = { +#ifndef SQLITE_OMIT_DATETIME_FUNCS + FUNCTION(julianday, -1, 0, 0, juliandayFunc ), + FUNCTION(date, -1, 0, 0, dateFunc ), + FUNCTION(time, -1, 0, 0, timeFunc ), + FUNCTION(datetime, -1, 0, 0, datetimeFunc ), + FUNCTION(strftime, -1, 0, 0, strftimeFunc ), + FUNCTION(current_time, 0, 0, 0, ctimeFunc ), + FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc), + FUNCTION(current_date, 0, 0, 0, cdateFunc ), +#else + STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc), + STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc), + STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), +#endif + }; + int i; + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs); + + for(i=0; ipMethods ){ + rc = pId->pMethods->xClose(pId); + pId->pMethods = 0; + } + return rc; +} +SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xRead(id, pBuf, amt, offset); +} +SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xWrite(id, pBuf, amt, offset); +} +SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){ + return id->pMethods->xTruncate(id, size); +} +SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xSync(id, flags); +} +SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xFileSize(id, pSize); +} +SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xLock(id, lockType); +} +SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){ + return id->pMethods->xUnlock(id, lockType); +} +SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xCheckReservedLock(id, pResOut); +} + +/* +** Use sqlite3OsFileControl() when we are doing something that might fail +** and we need to know about the failures. Use sqlite3OsFileControlHint() +** when simply tossing information over the wall to the VFS and we do not +** really care if the VFS receives and understands the information since it +** is only a hint and can be safely ignored. The sqlite3OsFileControlHint() +** routine has no return value since the return value would be meaningless. +*/ +SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xFileControl(id, op, pArg); +} +SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){ + (void)id->pMethods->xFileControl(id, op, pArg); +} + +SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){ + int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; + return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); +} +SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ + return id->pMethods->xDeviceCharacteristics(id); +} +SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){ + return id->pMethods->xShmLock(id, offset, n, flags); +} +SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){ + id->pMethods->xShmBarrier(id); +} +SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){ + return id->pMethods->xShmUnmap(id, deleteFlag); +} +SQLITE_PRIVATE int sqlite3OsShmMap( + sqlite3_file *id, /* Database file handle */ + int iPage, + int pgsz, + int bExtend, /* True to extend file if necessary */ + void volatile **pp /* OUT: Pointer to mapping */ +){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp); +} + +#if SQLITE_MAX_MMAP_SIZE>0 +/* The real implementation of xFetch and xUnfetch */ +SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xFetch(id, iOff, iAmt, pp); +} +SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ + return id->pMethods->xUnfetch(id, iOff, p); +} +#else +/* No-op stubs to use when memory-mapped I/O is disabled */ +SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ + *pp = 0; + return SQLITE_OK; +} +SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ + return SQLITE_OK; +} +#endif + +/* +** The next group of routines are convenience wrappers around the +** VFS methods. +*/ +SQLITE_PRIVATE int sqlite3OsOpen( + sqlite3_vfs *pVfs, + const char *zPath, + sqlite3_file *pFile, + int flags, + int *pFlagsOut +){ + int rc; + DO_OS_MALLOC_TEST(0); + /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed + ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, + ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before + ** reaching the VFS. */ + rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut); + assert( rc==SQLITE_OK || pFile->pMethods==0 ); + return rc; +} +SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + DO_OS_MALLOC_TEST(0); + assert( dirSync==0 || dirSync==1 ); + return pVfs->xDelete(pVfs, zPath, dirSync); +} +SQLITE_PRIVATE int sqlite3OsAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + DO_OS_MALLOC_TEST(0); + return pVfs->xAccess(pVfs, zPath, flags, pResOut); +} +SQLITE_PRIVATE int sqlite3OsFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nPathOut, + char *zPathOut +){ + DO_OS_MALLOC_TEST(0); + zPathOut[0] = 0; + return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); +} +#ifndef SQLITE_OMIT_LOAD_EXTENSION +SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return pVfs->xDlOpen(pVfs, zPath); +} +SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + pVfs->xDlError(pVfs, nByte, zBufOut); +} +SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){ + return pVfs->xDlSym(pVfs, pHdle, zSym); +} +SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){ + pVfs->xDlClose(pVfs, pHandle); +} +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return pVfs->xRandomness(pVfs, nByte, zBufOut); +} +SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){ + return pVfs->xSleep(pVfs, nMicro); +} +SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ + int rc; + /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() + ** method to get the current date and time if that method is available + ** (if iVersion is 2 or greater and the function pointer is not NULL) and + ** will fall back to xCurrentTime() if xCurrentTimeInt64() is + ** unavailable. + */ + if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ + rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut); + }else{ + double r; + rc = pVfs->xCurrentTime(pVfs, &r); + *pTimeOut = (sqlite3_int64)(r*86400000.0); + } + return rc; +} + +SQLITE_PRIVATE int sqlite3OsOpenMalloc( + sqlite3_vfs *pVfs, + const char *zFile, + sqlite3_file **ppFile, + int flags, + int *pOutFlags +){ + int rc = SQLITE_NOMEM; + sqlite3_file *pFile; + pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile); + if( pFile ){ + rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags); + if( rc!=SQLITE_OK ){ + sqlite3_free(pFile); + }else{ + *ppFile = pFile; + } + } + return rc; +} +SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){ + int rc = SQLITE_OK; + assert( pFile ); + rc = sqlite3OsClose(pFile); + sqlite3_free(pFile); + return rc; +} + +/* +** This function is a wrapper around the OS specific implementation of +** sqlite3_os_init(). The purpose of the wrapper is to provide the +** ability to simulate a malloc failure, so that the handling of an +** error in sqlite3_os_init() by the upper layers can be tested. +*/ +SQLITE_PRIVATE int sqlite3OsInit(void){ + void *p = sqlite3_malloc(10); + if( p==0 ) return SQLITE_NOMEM; + sqlite3_free(p); + return sqlite3_os_init(); +} + +/* +** The list of all registered VFS implementations. +*/ +static sqlite3_vfs * SQLITE_WSD vfsList = 0; +#define vfsList GLOBAL(sqlite3_vfs *, vfsList) + +/* +** Locate a VFS by name. If no name is given, simply return the +** first VFS on the list. +*/ +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){ + sqlite3_vfs *pVfs = 0; +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex; +#endif +#ifndef SQLITE_OMIT_AUTOINIT + int rc = sqlite3_initialize(); + if( rc ) return 0; +#endif +#if SQLITE_THREADSAFE + mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter(mutex); + for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){ + if( zVfs==0 ) break; + if( strcmp(zVfs, pVfs->zName)==0 ) break; + } + sqlite3_mutex_leave(mutex); + return pVfs; +} + +/* +** Unlink a VFS from the linked list +*/ +static void vfsUnlink(sqlite3_vfs *pVfs){ + assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ); + if( pVfs==0 ){ + /* No-op */ + }else if( vfsList==pVfs ){ + vfsList = pVfs->pNext; + }else if( vfsList ){ + sqlite3_vfs *p = vfsList; + while( p->pNext && p->pNext!=pVfs ){ + p = p->pNext; + } + if( p->pNext==pVfs ){ + p->pNext = pVfs->pNext; + } + } +} + +/* +** Register a VFS with the system. It is harmless to register the same +** VFS multiple times. The new VFS becomes the default if makeDflt is +** true. +*/ +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){ + MUTEX_LOGIC(sqlite3_mutex *mutex;) +#ifndef SQLITE_OMIT_AUTOINIT + int rc = sqlite3_initialize(); + if( rc ) return rc; +#endif + MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + sqlite3_mutex_enter(mutex); + vfsUnlink(pVfs); + if( makeDflt || vfsList==0 ){ + pVfs->pNext = vfsList; + vfsList = pVfs; + }else{ + pVfs->pNext = vfsList->pNext; + vfsList->pNext = pVfs; + } + assert(vfsList); + sqlite3_mutex_leave(mutex); + return SQLITE_OK; +} + +/* +** Unregister a VFS so that it is no longer accessible. +*/ +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter(mutex); + vfsUnlink(pVfs); + sqlite3_mutex_leave(mutex); + return SQLITE_OK; +} + +/************** End of os.c **************************************************/ +/************** Begin file fault.c *******************************************/ +/* +** 2008 Jan 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code to support the concept of "benign" +** malloc failures (when the xMalloc() or xRealloc() method of the +** sqlite3_mem_methods structure fails to allocate a block of memory +** and returns 0). +** +** Most malloc failures are non-benign. After they occur, SQLite +** abandons the current operation and returns an error code (usually +** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily +** fatal. For example, if a malloc fails while resizing a hash table, this +** is completely recoverable simply by not carrying out the resize. The +** hash table will continue to function normally. So a malloc failure +** during a hash table resize is a benign fault. +*/ + + +#ifndef SQLITE_OMIT_BUILTIN_TEST + +/* +** Global variables. +*/ +typedef struct BenignMallocHooks BenignMallocHooks; +static SQLITE_WSD struct BenignMallocHooks { + void (*xBenignBegin)(void); + void (*xBenignEnd)(void); +} sqlite3Hooks = { 0, 0 }; + +/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks +** structure. If writable static data is unsupported on the target, +** we have to locate the state vector at run-time. In the more common +** case where writable static data is supported, wsdHooks can refer directly +** to the "sqlite3Hooks" state vector declared above. +*/ +#ifdef SQLITE_OMIT_WSD +# define wsdHooksInit \ + BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks) +# define wsdHooks x[0] +#else +# define wsdHooksInit +# define wsdHooks sqlite3Hooks +#endif + + +/* +** Register hooks to call when sqlite3BeginBenignMalloc() and +** sqlite3EndBenignMalloc() are called, respectively. +*/ +SQLITE_PRIVATE void sqlite3BenignMallocHooks( + void (*xBenignBegin)(void), + void (*xBenignEnd)(void) +){ + wsdHooksInit; + wsdHooks.xBenignBegin = xBenignBegin; + wsdHooks.xBenignEnd = xBenignEnd; +} + +/* +** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that +** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc() +** indicates that subsequent malloc failures are non-benign. +*/ +SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){ + wsdHooksInit; + if( wsdHooks.xBenignBegin ){ + wsdHooks.xBenignBegin(); + } +} +SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){ + wsdHooksInit; + if( wsdHooks.xBenignEnd ){ + wsdHooks.xBenignEnd(); + } +} + +#endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */ + +/************** End of fault.c ***********************************************/ +/************** Begin file mem0.c ********************************************/ +/* +** 2008 October 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains a no-op memory allocation drivers for use when +** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented +** here always fail. SQLite will not operate with these drivers. These +** are merely placeholders. Real drivers must be substituted using +** sqlite3_config() before SQLite will operate. +*/ + +/* +** This version of the memory allocator is the default. It is +** used when no other memory allocator is specified using compile-time +** macros. +*/ +#ifdef SQLITE_ZERO_MALLOC + +/* +** No-op versions of all memory allocation routines +*/ +static void *sqlite3MemMalloc(int nByte){ return 0; } +static void sqlite3MemFree(void *pPrior){ return; } +static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; } +static int sqlite3MemSize(void *pPrior){ return 0; } +static int sqlite3MemRoundup(int n){ return n; } +static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; } +static void sqlite3MemShutdown(void *NotUsed){ return; } + +/* +** This routine is the only routine in this file with external linkage. +** +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +SQLITE_PRIVATE void sqlite3MemSetDefault(void){ + static const sqlite3_mem_methods defaultMethods = { + sqlite3MemMalloc, + sqlite3MemFree, + sqlite3MemRealloc, + sqlite3MemSize, + sqlite3MemRoundup, + sqlite3MemInit, + sqlite3MemShutdown, + 0 + }; + sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); +} + +#endif /* SQLITE_ZERO_MALLOC */ + +/************** End of mem0.c ************************************************/ +/************** Begin file mem1.c ********************************************/ +/* +** 2007 August 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains low-level memory allocation drivers for when +** SQLite will use the standard C-library malloc/realloc/free interface +** to obtain the memory it needs. +** +** This file contains implementations of the low-level memory allocation +** routines specified in the sqlite3_mem_methods object. The content of +** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The +** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the +** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The +** default configuration is to use memory allocation routines in this +** file. +** +** C-preprocessor macro summary: +** +** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if +** the malloc_usable_size() interface exists +** on the target platform. Or, this symbol +** can be set manually, if desired. +** If an equivalent interface exists by +** a different name, using a separate -D +** option to rename it. +** +** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone +** memory allocator. Set this symbol to enable +** building on older macs. +** +** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of +** _msize() on windows systems. This might +** be necessary when compiling for Delphi, +** for example. +*/ + +/* +** This version of the memory allocator is the default. It is +** used when no other memory allocator is specified using compile-time +** macros. +*/ +#ifdef SQLITE_SYSTEM_MALLOC + +/* +** The MSVCRT has malloc_usable_size() but it is called _msize(). +** The use of _msize() is automatic, but can be disabled by compiling +** with -DSQLITE_WITHOUT_MSIZE +*/ +#if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE) +# define SQLITE_MALLOCSIZE _msize +#endif + +#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) + +/* +** Use the zone allocator available on apple products unless the +** SQLITE_WITHOUT_ZONEMALLOC symbol is defined. +*/ +#include +#include +#include +static malloc_zone_t* _sqliteZone_; +#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x)) +#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x)); +#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y)) +#define SQLITE_MALLOCSIZE(x) \ + (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x)) + +#elif defined(SQLITE_OS_RTTHREAD) +#include +/* +** Use standard C library malloc and free on non-Apple systems. +** Also used by rt-thread systems if SQLITE_WITHOUT_ZONEMALLOC is defined. +*/ +#define SQLITE_MALLOC(x) rt_malloc((rt_size_t)x) +#define SQLITE_FREE(x) rt_free(x) +#define SQLITE_REALLOC(x,y) rt_realloc((x),(rt_size_t)(y)) + +#if (!defined(SQLITE_WITHOUT_MSIZE)) \ + && (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)) +# error "not have malloc_usable_size()" +#endif +#ifdef HAVE_MALLOC_USABLE_SIZE +# undef SQLITE_MALLOCSIZE +#endif + +#else /* if not __APPLE__ */ + +/* +** Use standard C library malloc and free on non-Apple systems. +** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined. +*/ +#define SQLITE_MALLOC(x) malloc(x) +#define SQLITE_FREE(x) free(x) +#define SQLITE_REALLOC(x,y) realloc((x),(y)) + +#if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \ + || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)) +# include /* Needed for malloc_usable_size on linux */ +#endif +#ifdef HAVE_MALLOC_USABLE_SIZE +# ifndef SQLITE_MALLOCSIZE +# define SQLITE_MALLOCSIZE(x) malloc_usable_size(x) +# endif +#else +# undef SQLITE_MALLOCSIZE +#endif + +#endif /* __APPLE__ or not __APPLE__ */ + +/* +** Like malloc(), but remember the size of the allocation +** so that we can find it later using sqlite3MemSize(). +** +** For this low-level routine, we are guaranteed that nByte>0 because +** cases of nByte<=0 will be intercepted and dealt with by higher level +** routines. +*/ +static void *sqlite3MemMalloc(int nByte){ +#ifdef SQLITE_MALLOCSIZE + void *p = SQLITE_MALLOC( nByte ); + if( p==0 ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); + } + return p; +#else + sqlite3_int64 *p; + assert( nByte>0 ); + nByte = ROUND8(nByte); + p = SQLITE_MALLOC( nByte+8 ); + if( p ){ + p[0] = nByte; + p++; + }else{ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); + } + return (void *)p; +#endif +} + +/* +** Like free() but works for allocations obtained from sqlite3MemMalloc() +** or sqlite3MemRealloc(). +** +** For this low-level routine, we already know that pPrior!=0 since +** cases where pPrior==0 will have been intecepted and dealt with +** by higher-level routines. +*/ +static void sqlite3MemFree(void *pPrior){ +#ifdef SQLITE_MALLOCSIZE + SQLITE_FREE(pPrior); +#else + sqlite3_int64 *p = (sqlite3_int64*)pPrior; + assert( pPrior!=0 ); + p--; + SQLITE_FREE(p); +#endif +} + +/* +** Report the allocated size of a prior return from xMalloc() +** or xRealloc(). +*/ +static int sqlite3MemSize(void *pPrior){ +#ifdef SQLITE_MALLOCSIZE + return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0; +#else + sqlite3_int64 *p; + if( pPrior==0 ) return 0; + p = (sqlite3_int64*)pPrior; + p--; + return (int)p[0]; +#endif +} + +/* +** Like realloc(). Resize an allocation previously obtained from +** sqlite3MemMalloc(). +** +** For this low-level interface, we know that pPrior!=0. Cases where +** pPrior==0 while have been intercepted by higher-level routine and +** redirected to xMalloc. Similarly, we know that nByte>0 becauses +** cases where nByte<=0 will have been intercepted by higher-level +** routines and redirected to xFree. +*/ +static void *sqlite3MemRealloc(void *pPrior, int nByte){ +#ifdef SQLITE_MALLOCSIZE + void *p = SQLITE_REALLOC(pPrior, nByte); + if( p==0 ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, + "failed memory resize %u to %u bytes", + SQLITE_MALLOCSIZE(pPrior), nByte); + } + return p; +#else + sqlite3_int64 *p = (sqlite3_int64*)pPrior; + assert( pPrior!=0 && nByte>0 ); + assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */ + p--; + p = SQLITE_REALLOC(p, nByte+8 ); + if( p ){ + p[0] = nByte; + p++; + }else{ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, + "failed memory resize %u to %u bytes", + sqlite3MemSize(pPrior), nByte); + } + return (void*)p; +#endif +} + +/* +** Round up a request size to the next valid allocation size. +*/ +static int sqlite3MemRoundup(int n){ + return ROUND8(n); +} + +/* +** Initialize this module. +*/ +static int sqlite3MemInit(void *NotUsed){ +#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) + int cpuCount; + size_t len; + if( _sqliteZone_ ){ + return SQLITE_OK; + } + len = sizeof(cpuCount); + /* One usually wants to use hw.acctivecpu for MT decisions, but not here */ + sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0); + if( cpuCount>1 ){ + /* defer MT decisions to system malloc */ + _sqliteZone_ = malloc_default_zone(); + }else{ + /* only 1 core, use our own zone to contention over global locks, + ** e.g. we have our own dedicated locks */ + bool success; + malloc_zone_t* newzone = malloc_create_zone(4096, 0); + malloc_set_zone_name(newzone, "Sqlite_Heap"); + do{ + success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, + (void * volatile *)&_sqliteZone_); + }while(!_sqliteZone_); + if( !success ){ + /* somebody registered a zone first */ + malloc_destroy_zone(newzone); + } + } +#endif + UNUSED_PARAMETER(NotUsed); + return SQLITE_OK; +} + +/* +** Deinitialize this module. +*/ +static void sqlite3MemShutdown(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + return; +} + +/* +** This routine is the only routine in this file with external linkage. +** +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +SQLITE_PRIVATE void sqlite3MemSetDefault(void){ + static const sqlite3_mem_methods defaultMethods = { + sqlite3MemMalloc, + sqlite3MemFree, + sqlite3MemRealloc, + sqlite3MemSize, + sqlite3MemRoundup, + sqlite3MemInit, + sqlite3MemShutdown, + 0 + }; + sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); +} + +#endif /* SQLITE_SYSTEM_MALLOC */ + +/************** End of mem1.c ************************************************/ +/************** Begin file mem2.c ********************************************/ +/* +** 2007 August 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains low-level memory allocation drivers for when +** SQLite will use the standard C-library malloc/realloc/free interface +** to obtain the memory it needs while adding lots of additional debugging +** information to each allocation in order to help detect and fix memory +** leaks and memory usage errors. +** +** This file contains implementations of the low-level memory allocation +** routines specified in the sqlite3_mem_methods object. +*/ + +/* +** This version of the memory allocator is used only if the +** SQLITE_MEMDEBUG macro is defined +*/ +#ifdef SQLITE_MEMDEBUG + +/* +** The backtrace functionality is only available with GLIBC +*/ +#ifdef __GLIBC__ + extern int backtrace(void**,int); + extern void backtrace_symbols_fd(void*const*,int,int); +#else +# define backtrace(A,B) 1 +# define backtrace_symbols_fd(A,B,C) +#endif +/* #include */ + +/* +** Each memory allocation looks like this: +** +** ------------------------------------------------------------------------ +** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard | +** ------------------------------------------------------------------------ +** +** The application code sees only a pointer to the allocation. We have +** to back up from the allocation pointer to find the MemBlockHdr. The +** MemBlockHdr tells us the size of the allocation and the number of +** backtrace pointers. There is also a guard word at the end of the +** MemBlockHdr. +*/ +struct MemBlockHdr { + i64 iSize; /* Size of this allocation */ + struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */ + char nBacktrace; /* Number of backtraces on this alloc */ + char nBacktraceSlots; /* Available backtrace slots */ + u8 nTitle; /* Bytes of title; includes '\0' */ + u8 eType; /* Allocation type code */ + int iForeGuard; /* Guard word for sanity */ +}; + +/* +** Guard words +*/ +#define FOREGUARD 0x80F5E153 +#define REARGUARD 0xE4676B53 + +/* +** Number of malloc size increments to track. +*/ +#define NCSIZE 1000 + +/* +** All of the static variables used by this module are collected +** into a single structure named "mem". This is to keep the +** static variables organized and to reduce namespace pollution +** when this module is combined with other in the amalgamation. +*/ +static struct { + + /* + ** Mutex to control access to the memory allocation subsystem. + */ + sqlite3_mutex *mutex; + + /* + ** Head and tail of a linked list of all outstanding allocations + */ + struct MemBlockHdr *pFirst; + struct MemBlockHdr *pLast; + + /* + ** The number of levels of backtrace to save in new allocations. + */ + int nBacktrace; + void (*xBacktrace)(int, int, void **); + + /* + ** Title text to insert in front of each block + */ + int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */ + char zTitle[100]; /* The title text */ + + /* + ** sqlite3MallocDisallow() increments the following counter. + ** sqlite3MallocAllow() decrements it. + */ + int disallow; /* Do not allow memory allocation */ + + /* + ** Gather statistics on the sizes of memory allocations. + ** nAlloc[i] is the number of allocation attempts of i*8 + ** bytes. i==NCSIZE is the number of allocation attempts for + ** sizes more than NCSIZE*8 bytes. + */ + int nAlloc[NCSIZE]; /* Total number of allocations */ + int nCurrent[NCSIZE]; /* Current number of allocations */ + int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */ + +} mem; + + +/* +** Adjust memory usage statistics +*/ +static void adjustStats(int iSize, int increment){ + int i = ROUND8(iSize)/8; + if( i>NCSIZE-1 ){ + i = NCSIZE - 1; + } + if( increment>0 ){ + mem.nAlloc[i]++; + mem.nCurrent[i]++; + if( mem.nCurrent[i]>mem.mxCurrent[i] ){ + mem.mxCurrent[i] = mem.nCurrent[i]; + } + }else{ + mem.nCurrent[i]--; + assert( mem.nCurrent[i]>=0 ); + } +} + +/* +** Given an allocation, find the MemBlockHdr for that allocation. +** +** This routine checks the guards at either end of the allocation and +** if they are incorrect it asserts. +*/ +static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){ + struct MemBlockHdr *p; + int *pInt; + u8 *pU8; + int nReserve; + + p = (struct MemBlockHdr*)pAllocation; + p--; + assert( p->iForeGuard==(int)FOREGUARD ); + nReserve = ROUND8(p->iSize); + pInt = (int*)pAllocation; + pU8 = (u8*)pAllocation; + assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD ); + /* This checks any of the "extra" bytes allocated due + ** to rounding up to an 8 byte boundary to ensure + ** they haven't been overwritten. + */ + while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 ); + return p; +} + +/* +** Return the number of bytes currently allocated at address p. +*/ +static int sqlite3MemSize(void *p){ + struct MemBlockHdr *pHdr; + if( !p ){ + return 0; + } + pHdr = sqlite3MemsysGetHeader(p); + return (int)pHdr->iSize; +} + +/* +** Initialize the memory allocation subsystem. +*/ +static int sqlite3MemInit(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + assert( (sizeof(struct MemBlockHdr)&7) == 0 ); + if( !sqlite3GlobalConfig.bMemstat ){ + /* If memory status is enabled, then the malloc.c wrapper will already + ** hold the STATIC_MEM mutex when the routines here are invoked. */ + mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + } + return SQLITE_OK; +} + +/* +** Deinitialize the memory allocation subsystem. +*/ +static void sqlite3MemShutdown(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + mem.mutex = 0; +} + +/* +** Round up a request size to the next valid allocation size. +*/ +static int sqlite3MemRoundup(int n){ + return ROUND8(n); +} + +/* +** Fill a buffer with pseudo-random bytes. This is used to preset +** the content of a new memory allocation to unpredictable values and +** to clear the content of a freed allocation to unpredictable values. +*/ +static void randomFill(char *pBuf, int nByte){ + unsigned int x, y, r; + x = SQLITE_PTR_TO_INT(pBuf); + y = nByte | 1; + while( nByte >= 4 ){ + x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); + y = y*1103515245 + 12345; + r = x ^ y; + *(int*)pBuf = r; + pBuf += 4; + nByte -= 4; + } + while( nByte-- > 0 ){ + x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); + y = y*1103515245 + 12345; + r = x ^ y; + *(pBuf++) = r & 0xff; + } +} + +/* +** Allocate nByte bytes of memory. +*/ +static void *sqlite3MemMalloc(int nByte){ + struct MemBlockHdr *pHdr; + void **pBt; + char *z; + int *pInt; + void *p = 0; + int totalSize; + int nReserve; + sqlite3_mutex_enter(mem.mutex); + assert( mem.disallow==0 ); + nReserve = ROUND8(nByte); + totalSize = nReserve + sizeof(*pHdr) + sizeof(int) + + mem.nBacktrace*sizeof(void*) + mem.nTitle; + p = malloc(totalSize); + if( p ){ + z = p; + pBt = (void**)&z[mem.nTitle]; + pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace]; + pHdr->pNext = 0; + pHdr->pPrev = mem.pLast; + if( mem.pLast ){ + mem.pLast->pNext = pHdr; + }else{ + mem.pFirst = pHdr; + } + mem.pLast = pHdr; + pHdr->iForeGuard = FOREGUARD; + pHdr->eType = MEMTYPE_HEAP; + pHdr->nBacktraceSlots = mem.nBacktrace; + pHdr->nTitle = mem.nTitle; + if( mem.nBacktrace ){ + void *aAddr[40]; + pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; + memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); + assert(pBt[0]); + if( mem.xBacktrace ){ + mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); + } + }else{ + pHdr->nBacktrace = 0; + } + if( mem.nTitle ){ + memcpy(z, mem.zTitle, mem.nTitle); + } + pHdr->iSize = nByte; + adjustStats(nByte, +1); + pInt = (int*)&pHdr[1]; + pInt[nReserve/sizeof(int)] = REARGUARD; + randomFill((char*)pInt, nByte); + memset(((char*)pInt)+nByte, 0x65, nReserve-nByte); + p = (void*)pInt; + } + sqlite3_mutex_leave(mem.mutex); + return p; +} + +/* +** Free memory. +*/ +static void sqlite3MemFree(void *pPrior){ + struct MemBlockHdr *pHdr; + void **pBt; + char *z; + assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 + || mem.mutex!=0 ); + pHdr = sqlite3MemsysGetHeader(pPrior); + pBt = (void**)pHdr; + pBt -= pHdr->nBacktraceSlots; + sqlite3_mutex_enter(mem.mutex); + if( pHdr->pPrev ){ + assert( pHdr->pPrev->pNext==pHdr ); + pHdr->pPrev->pNext = pHdr->pNext; + }else{ + assert( mem.pFirst==pHdr ); + mem.pFirst = pHdr->pNext; + } + if( pHdr->pNext ){ + assert( pHdr->pNext->pPrev==pHdr ); + pHdr->pNext->pPrev = pHdr->pPrev; + }else{ + assert( mem.pLast==pHdr ); + mem.pLast = pHdr->pPrev; + } + z = (char*)pBt; + z -= pHdr->nTitle; + adjustStats((int)pHdr->iSize, -1); + randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + + (int)pHdr->iSize + sizeof(int) + pHdr->nTitle); + free(z); + sqlite3_mutex_leave(mem.mutex); +} + +/* +** Change the size of an existing memory allocation. +** +** For this debugging implementation, we *always* make a copy of the +** allocation into a new place in memory. In this way, if the +** higher level code is using pointer to the old allocation, it is +** much more likely to break and we are much more liking to find +** the error. +*/ +static void *sqlite3MemRealloc(void *pPrior, int nByte){ + struct MemBlockHdr *pOldHdr; + void *pNew; + assert( mem.disallow==0 ); + assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */ + pOldHdr = sqlite3MemsysGetHeader(pPrior); + pNew = sqlite3MemMalloc(nByte); + if( pNew ){ + memcpy(pNew, pPrior, (int)(nByteiSize ? nByte : pOldHdr->iSize)); + if( nByte>pOldHdr->iSize ){ + randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize); + } + sqlite3MemFree(pPrior); + } + return pNew; +} + +/* +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +SQLITE_PRIVATE void sqlite3MemSetDefault(void){ + static const sqlite3_mem_methods defaultMethods = { + sqlite3MemMalloc, + sqlite3MemFree, + sqlite3MemRealloc, + sqlite3MemSize, + sqlite3MemRoundup, + sqlite3MemInit, + sqlite3MemShutdown, + 0 + }; + sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); +} + +/* +** Set the "type" of an allocation. +*/ +SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){ + if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ + struct MemBlockHdr *pHdr; + pHdr = sqlite3MemsysGetHeader(p); + assert( pHdr->iForeGuard==FOREGUARD ); + pHdr->eType = eType; + } +} + +/* +** Return TRUE if the mask of type in eType matches the type of the +** allocation p. Also return true if p==NULL. +** +** This routine is designed for use within an assert() statement, to +** verify the type of an allocation. For example: +** +** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) ); +*/ +SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){ + int rc = 1; + if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ + struct MemBlockHdr *pHdr; + pHdr = sqlite3MemsysGetHeader(p); + assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ + if( (pHdr->eType&eType)==0 ){ + rc = 0; + } + } + return rc; +} + +/* +** Return TRUE if the mask of type in eType matches no bits of the type of the +** allocation p. Also return true if p==NULL. +** +** This routine is designed for use within an assert() statement, to +** verify the type of an allocation. For example: +** +** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) ); +*/ +SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){ + int rc = 1; + if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ + struct MemBlockHdr *pHdr; + pHdr = sqlite3MemsysGetHeader(p); + assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ + if( (pHdr->eType&eType)!=0 ){ + rc = 0; + } + } + return rc; +} + +/* +** Set the number of backtrace levels kept for each allocation. +** A value of zero turns off backtracing. The number is always rounded +** up to a multiple of 2. +*/ +SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){ + if( depth<0 ){ depth = 0; } + if( depth>20 ){ depth = 20; } + depth = (depth+1)&0xfe; + mem.nBacktrace = depth; +} + +SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ + mem.xBacktrace = xBacktrace; +} + +/* +** Set the title string for subsequent allocations. +*/ +SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){ + unsigned int n = sqlite3Strlen30(zTitle) + 1; + sqlite3_mutex_enter(mem.mutex); + if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; + memcpy(mem.zTitle, zTitle, n); + mem.zTitle[n] = 0; + mem.nTitle = ROUND8(n); + sqlite3_mutex_leave(mem.mutex); +} + +SQLITE_PRIVATE void sqlite3MemdebugSync(){ + struct MemBlockHdr *pHdr; + for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ + void **pBt = (void**)pHdr; + pBt -= pHdr->nBacktraceSlots; + mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]); + } +} + +/* +** Open the file indicated and write a log of all unfreed memory +** allocations into that log. +*/ +SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){ + FILE *out; + struct MemBlockHdr *pHdr; + void **pBt; + int i; + out = fopen(zFilename, "w"); + if( out==0 ){ + fprintf(stderr, "** Unable to output memory debug output log: %s **\n", + zFilename); + return; + } + for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ + char *z = (char*)pHdr; + z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle; + fprintf(out, "**** %lld bytes at %p from %s ****\n", + pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???"); + if( pHdr->nBacktrace ){ + fflush(out); + pBt = (void**)pHdr; + pBt -= pHdr->nBacktraceSlots; + backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out)); + fprintf(out, "\n"); + } + } + fprintf(out, "COUNTS:\n"); + for(i=0; i=1 ); + size = mem3.aPool[i-1].u.hdr.size4x/4; + assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); + assert( size>=2 ); + if( size <= MX_SMALL ){ + memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]); + }else{ + hash = size % N_HASH; + memsys3UnlinkFromList(i, &mem3.aiHash[hash]); + } +} + +/* +** Link the chunk at mem3.aPool[i] so that is on the list rooted +** at *pRoot. +*/ +static void memsys3LinkIntoList(u32 i, u32 *pRoot){ + assert( sqlite3_mutex_held(mem3.mutex) ); + mem3.aPool[i].u.list.next = *pRoot; + mem3.aPool[i].u.list.prev = 0; + if( *pRoot ){ + mem3.aPool[*pRoot].u.list.prev = i; + } + *pRoot = i; +} + +/* +** Link the chunk at index i into either the appropriate +** small chunk list, or into the large chunk hash table. +*/ +static void memsys3Link(u32 i){ + u32 size, hash; + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( i>=1 ); + assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); + size = mem3.aPool[i-1].u.hdr.size4x/4; + assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); + assert( size>=2 ); + if( size <= MX_SMALL ){ + memsys3LinkIntoList(i, &mem3.aiSmall[size-2]); + }else{ + hash = size % N_HASH; + memsys3LinkIntoList(i, &mem3.aiHash[hash]); + } +} + +/* +** If the STATIC_MEM mutex is not already held, obtain it now. The mutex +** will already be held (obtained by code in malloc.c) if +** sqlite3GlobalConfig.bMemStat is true. +*/ +static void memsys3Enter(void){ + if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){ + mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + } + sqlite3_mutex_enter(mem3.mutex); +} +static void memsys3Leave(void){ + sqlite3_mutex_leave(mem3.mutex); +} + +/* +** Called when we are unable to satisfy an allocation of nBytes. +*/ +static void memsys3OutOfMemory(int nByte){ + if( !mem3.alarmBusy ){ + mem3.alarmBusy = 1; + assert( sqlite3_mutex_held(mem3.mutex) ); + sqlite3_mutex_leave(mem3.mutex); + sqlite3_release_memory(nByte); + sqlite3_mutex_enter(mem3.mutex); + mem3.alarmBusy = 0; + } +} + + +/* +** Chunk i is a free chunk that has been unlinked. Adjust its +** size parameters for check-out and return a pointer to the +** user portion of the chunk. +*/ +static void *memsys3Checkout(u32 i, u32 nBlock){ + u32 x; + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( i>=1 ); + assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ); + assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock ); + x = mem3.aPool[i-1].u.hdr.size4x; + mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2); + mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock; + mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2; + return &mem3.aPool[i]; +} + +/* +** Carve a piece off of the end of the mem3.iMaster free chunk. +** Return a pointer to the new allocation. Or, if the master chunk +** is not large enough, return 0. +*/ +static void *memsys3FromMaster(u32 nBlock){ + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( mem3.szMaster>=nBlock ); + if( nBlock>=mem3.szMaster-1 ){ + /* Use the entire master */ + void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster); + mem3.iMaster = 0; + mem3.szMaster = 0; + mem3.mnMaster = 0; + return p; + }else{ + /* Split the master block. Return the tail. */ + u32 newi, x; + newi = mem3.iMaster + mem3.szMaster - nBlock; + assert( newi > mem3.iMaster+1 ); + mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock; + mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2; + mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1; + mem3.szMaster -= nBlock; + mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster; + x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; + mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; + if( mem3.szMaster < mem3.mnMaster ){ + mem3.mnMaster = mem3.szMaster; + } + return (void*)&mem3.aPool[newi]; + } +} + +/* +** *pRoot is the head of a list of free chunks of the same size +** or same size hash. In other words, *pRoot is an entry in either +** mem3.aiSmall[] or mem3.aiHash[]. +** +** This routine examines all entries on the given list and tries +** to coalesce each entries with adjacent free chunks. +** +** If it sees a chunk that is larger than mem3.iMaster, it replaces +** the current mem3.iMaster with the new larger chunk. In order for +** this mem3.iMaster replacement to work, the master chunk must be +** linked into the hash tables. That is not the normal state of +** affairs, of course. The calling routine must link the master +** chunk before invoking this routine, then must unlink the (possibly +** changed) master chunk once this routine has finished. +*/ +static void memsys3Merge(u32 *pRoot){ + u32 iNext, prev, size, i, x; + + assert( sqlite3_mutex_held(mem3.mutex) ); + for(i=*pRoot; i>0; i=iNext){ + iNext = mem3.aPool[i].u.list.next; + size = mem3.aPool[i-1].u.hdr.size4x; + assert( (size&1)==0 ); + if( (size&2)==0 ){ + memsys3UnlinkFromList(i, pRoot); + assert( i > mem3.aPool[i-1].u.hdr.prevSize ); + prev = i - mem3.aPool[i-1].u.hdr.prevSize; + if( prev==iNext ){ + iNext = mem3.aPool[prev].u.list.next; + } + memsys3Unlink(prev); + size = i + size/4 - prev; + x = mem3.aPool[prev-1].u.hdr.size4x & 2; + mem3.aPool[prev-1].u.hdr.size4x = size*4 | x; + mem3.aPool[prev+size-1].u.hdr.prevSize = size; + memsys3Link(prev); + i = prev; + }else{ + size /= 4; + } + if( size>mem3.szMaster ){ + mem3.iMaster = i; + mem3.szMaster = size; + } + } +} + +/* +** Return a block of memory of at least nBytes in size. +** Return NULL if unable. +** +** This function assumes that the necessary mutexes, if any, are +** already held by the caller. Hence "Unsafe". +*/ +static void *memsys3MallocUnsafe(int nByte){ + u32 i; + u32 nBlock; + u32 toFree; + + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( sizeof(Mem3Block)==8 ); + if( nByte<=12 ){ + nBlock = 2; + }else{ + nBlock = (nByte + 11)/8; + } + assert( nBlock>=2 ); + + /* STEP 1: + ** Look for an entry of the correct size in either the small + ** chunk table or in the large chunk hash table. This is + ** successful most of the time (about 9 times out of 10). + */ + if( nBlock <= MX_SMALL ){ + i = mem3.aiSmall[nBlock-2]; + if( i>0 ){ + memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]); + return memsys3Checkout(i, nBlock); + } + }else{ + int hash = nBlock % N_HASH; + for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){ + if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){ + memsys3UnlinkFromList(i, &mem3.aiHash[hash]); + return memsys3Checkout(i, nBlock); + } + } + } + + /* STEP 2: + ** Try to satisfy the allocation by carving a piece off of the end + ** of the master chunk. This step usually works if step 1 fails. + */ + if( mem3.szMaster>=nBlock ){ + return memsys3FromMaster(nBlock); + } + + + /* STEP 3: + ** Loop through the entire memory pool. Coalesce adjacent free + ** chunks. Recompute the master chunk as the largest free chunk. + ** Then try again to satisfy the allocation by carving a piece off + ** of the end of the master chunk. This step happens very + ** rarely (we hope!) + */ + for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){ + memsys3OutOfMemory(toFree); + if( mem3.iMaster ){ + memsys3Link(mem3.iMaster); + mem3.iMaster = 0; + mem3.szMaster = 0; + } + for(i=0; i=nBlock ){ + return memsys3FromMaster(nBlock); + } + } + } + + /* If none of the above worked, then we fail. */ + return 0; +} + +/* +** Free an outstanding memory allocation. +** +** This function assumes that the necessary mutexes, if any, are +** already held by the caller. Hence "Unsafe". +*/ +static void memsys3FreeUnsafe(void *pOld){ + Mem3Block *p = (Mem3Block*)pOld; + int i; + u32 size, x; + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] ); + i = p - mem3.aPool; + assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 ); + size = mem3.aPool[i-1].u.hdr.size4x/4; + assert( i+size<=mem3.nPool+1 ); + mem3.aPool[i-1].u.hdr.size4x &= ~1; + mem3.aPool[i+size-1].u.hdr.prevSize = size; + mem3.aPool[i+size-1].u.hdr.size4x &= ~2; + memsys3Link(i); + + /* Try to expand the master using the newly freed chunk */ + if( mem3.iMaster ){ + while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){ + size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize; + mem3.iMaster -= size; + mem3.szMaster += size; + memsys3Unlink(mem3.iMaster); + x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; + mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; + mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; + } + x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; + while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){ + memsys3Unlink(mem3.iMaster+mem3.szMaster); + mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4; + mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; + mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; + } + } +} + +/* +** Return the size of an outstanding allocation, in bytes. The +** size returned omits the 8-byte header overhead. This only +** works for chunks that are currently checked out. +*/ +static int memsys3Size(void *p){ + Mem3Block *pBlock; + if( p==0 ) return 0; + pBlock = (Mem3Block*)p; + assert( (pBlock[-1].u.hdr.size4x&1)!=0 ); + return (pBlock[-1].u.hdr.size4x&~3)*2 - 4; +} + +/* +** Round up a request size to the next valid allocation size. +*/ +static int memsys3Roundup(int n){ + if( n<=12 ){ + return 12; + }else{ + return ((n+11)&~7) - 4; + } +} + +/* +** Allocate nBytes of memory. +*/ +static void *memsys3Malloc(int nBytes){ + sqlite3_int64 *p; + assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */ + memsys3Enter(); + p = memsys3MallocUnsafe(nBytes); + memsys3Leave(); + return (void*)p; +} + +/* +** Free memory. +*/ +static void memsys3Free(void *pPrior){ + assert( pPrior ); + memsys3Enter(); + memsys3FreeUnsafe(pPrior); + memsys3Leave(); +} + +/* +** Change the size of an existing memory allocation +*/ +static void *memsys3Realloc(void *pPrior, int nBytes){ + int nOld; + void *p; + if( pPrior==0 ){ + return sqlite3_malloc(nBytes); + } + if( nBytes<=0 ){ + sqlite3_free(pPrior); + return 0; + } + nOld = memsys3Size(pPrior); + if( nBytes<=nOld && nBytes>=nOld-128 ){ + return pPrior; + } + memsys3Enter(); + p = memsys3MallocUnsafe(nBytes); + if( p ){ + if( nOld>1)!=(size&1) ){ + fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]); + assert( 0 ); + break; + } + if( size&1 ){ + fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8); + }else{ + fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8, + i==mem3.iMaster ? " **master**" : ""); + } + } + for(i=0; i0; j=mem3.aPool[j].u.list.next){ + fprintf(out, " %p(%d)", &mem3.aPool[j], + (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); + } + fprintf(out, "\n"); + } + for(i=0; i0; j=mem3.aPool[j].u.list.next){ + fprintf(out, " %p(%d)", &mem3.aPool[j], + (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); + } + fprintf(out, "\n"); + } + fprintf(out, "master=%d\n", mem3.iMaster); + fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8); + fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8); + sqlite3_mutex_leave(mem3.mutex); + if( out==stdout ){ + fflush(stdout); + }else{ + fclose(out); + } +#else + UNUSED_PARAMETER(zFilename); +#endif +} + +/* +** This routine is the only routine in this file with external +** linkage. +** +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. The +** arguments specify the block of memory to manage. +** +** This routine is only called by sqlite3_config(), and therefore +** is not required to be threadsafe (it is not). +*/ +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){ + static const sqlite3_mem_methods mempoolMethods = { + memsys3Malloc, + memsys3Free, + memsys3Realloc, + memsys3Size, + memsys3Roundup, + memsys3Init, + memsys3Shutdown, + 0 + }; + return &mempoolMethods; +} + +#endif /* SQLITE_ENABLE_MEMSYS3 */ + +/************** End of mem3.c ************************************************/ +/************** Begin file mem5.c ********************************************/ +/* +** 2007 October 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement a memory +** allocation subsystem for use by SQLite. +** +** This version of the memory allocation subsystem omits all +** use of malloc(). The application gives SQLite a block of memory +** before calling sqlite3_initialize() from which allocations +** are made and returned by the xMalloc() and xRealloc() +** implementations. Once sqlite3_initialize() has been called, +** the amount of memory available to SQLite is fixed and cannot +** be changed. +** +** This version of the memory allocation subsystem is included +** in the build only if SQLITE_ENABLE_MEMSYS5 is defined. +** +** This memory allocator uses the following algorithm: +** +** 1. All memory allocations sizes are rounded up to a power of 2. +** +** 2. If two adjacent free blocks are the halves of a larger block, +** then the two blocks are coalesed into the single larger block. +** +** 3. New memory is allocated from the first available free block. +** +** This algorithm is described in: J. M. Robson. "Bounds for Some Functions +** Concerning Dynamic Storage Allocation". Journal of the Association for +** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499. +** +** Let n be the size of the largest allocation divided by the minimum +** allocation size (after rounding all sizes up to a power of 2.) Let M +** be the maximum amount of memory ever outstanding at one time. Let +** N be the total amount of memory available for allocation. Robson +** proved that this memory allocator will never breakdown due to +** fragmentation as long as the following constraint holds: +** +** N >= M*(1 + log2(n)/2) - n + 1 +** +** The sqlite3_status() logic tracks the maximum values of n and M so +** that an application can, at any time, verify this constraint. +*/ + +/* +** This version of the memory allocator is used only when +** SQLITE_ENABLE_MEMSYS5 is defined. +*/ +#ifdef SQLITE_ENABLE_MEMSYS5 + +/* +** A minimum allocation is an instance of the following structure. +** Larger allocations are an array of these structures where the +** size of the array is a power of 2. +** +** The size of this object must be a power of two. That fact is +** verified in memsys5Init(). +*/ +typedef struct Mem5Link Mem5Link; +struct Mem5Link { + int next; /* Index of next free chunk */ + int prev; /* Index of previous free chunk */ +}; + +/* +** Maximum size of any allocation is ((1<=0 && i=0 && iLogsize<=LOGMAX ); + assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); + + next = MEM5LINK(i)->next; + prev = MEM5LINK(i)->prev; + if( prev<0 ){ + mem5.aiFreelist[iLogsize] = next; + }else{ + MEM5LINK(prev)->next = next; + } + if( next>=0 ){ + MEM5LINK(next)->prev = prev; + } +} + +/* +** Link the chunk at mem5.aPool[i] so that is on the iLogsize +** free list. +*/ +static void memsys5Link(int i, int iLogsize){ + int x; + assert( sqlite3_mutex_held(mem5.mutex) ); + assert( i>=0 && i=0 && iLogsize<=LOGMAX ); + assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); + + x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize]; + MEM5LINK(i)->prev = -1; + if( x>=0 ){ + assert( xprev = i; + } + mem5.aiFreelist[iLogsize] = i; +} + +/* +** If the STATIC_MEM mutex is not already held, obtain it now. The mutex +** will already be held (obtained by code in malloc.c) if +** sqlite3GlobalConfig.bMemStat is true. +*/ +static void memsys5Enter(void){ + sqlite3_mutex_enter(mem5.mutex); +} +static void memsys5Leave(void){ + sqlite3_mutex_leave(mem5.mutex); +} + +/* +** Return the size of an outstanding allocation, in bytes. The +** size returned omits the 8-byte header overhead. This only +** works for chunks that are currently checked out. +*/ +static int memsys5Size(void *p){ + int iSize = 0; + if( p ){ + int i = ((u8 *)p-mem5.zPool)/mem5.szAtom; + assert( i>=0 && i=0 && iLogsize<=LOGMAX ); + i = iFirst = mem5.aiFreelist[iLogsize]; + assert( iFirst>=0 ); + while( i>0 ){ + if( inext; + } + memsys5Unlink(iFirst, iLogsize); + return iFirst; +} + +/* +** Return a block of memory of at least nBytes in size. +** Return NULL if unable. Return NULL if nBytes==0. +** +** The caller guarantees that nByte is positive. +** +** The caller has obtained a mutex prior to invoking this +** routine so there is never any chance that two or more +** threads can be in this routine at the same time. +*/ +static void *memsys5MallocUnsafe(int nByte){ + int i; /* Index of a mem5.aPool[] slot */ + int iBin; /* Index into mem5.aiFreelist[] */ + int iFullSz; /* Size of allocation rounded up to power of 2 */ + int iLogsize; /* Log2 of iFullSz/POW2_MIN */ + + /* nByte must be a positive */ + assert( nByte>0 ); + + /* Keep track of the maximum allocation request. Even unfulfilled + ** requests are counted */ + if( (u32)nByte>mem5.maxRequest ){ + mem5.maxRequest = nByte; + } + + /* Abort if the requested allocation size is larger than the largest + ** power of two that we can represent using 32-bit signed integers. + */ + if( nByte > 0x40000000 ){ + return 0; + } + + /* Round nByte up to the next valid power of two */ + for(iFullSz=mem5.szAtom, iLogsize=0; iFullSzLOGMAX ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte); + return 0; + } + i = memsys5UnlinkFirst(iBin); + while( iBin>iLogsize ){ + int newSize; + + iBin--; + newSize = 1 << iBin; + mem5.aCtrl[i+newSize] = CTRL_FREE | iBin; + memsys5Link(i+newSize, iBin); + } + mem5.aCtrl[i] = iLogsize; + + /* Update allocator performance statistics. */ + mem5.nAlloc++; + mem5.totalAlloc += iFullSz; + mem5.totalExcess += iFullSz - nByte; + mem5.currentCount++; + mem5.currentOut += iFullSz; + if( mem5.maxCount=0 && iBlock0 ); + assert( mem5.currentOut>=(size*mem5.szAtom) ); + mem5.currentCount--; + mem5.currentOut -= size*mem5.szAtom; + assert( mem5.currentOut>0 || mem5.currentCount==0 ); + assert( mem5.currentCount>0 || mem5.currentOut==0 ); + + mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize; + while( ALWAYS(iLogsize>iLogsize) & 1 ){ + iBuddy = iBlock - size; + }else{ + iBuddy = iBlock + size; + } + assert( iBuddy>=0 ); + if( (iBuddy+(1<mem5.nBlock ) break; + if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break; + memsys5Unlink(iBuddy, iLogsize); + iLogsize++; + if( iBuddy0 ){ + memsys5Enter(); + p = memsys5MallocUnsafe(nBytes); + memsys5Leave(); + } + return (void*)p; +} + +/* +** Free memory. +** +** The outer layer memory allocator prevents this routine from +** being called with pPrior==0. +*/ +static void memsys5Free(void *pPrior){ + assert( pPrior!=0 ); + memsys5Enter(); + memsys5FreeUnsafe(pPrior); + memsys5Leave(); +} + +/* +** Change the size of an existing memory allocation. +** +** The outer layer memory allocator prevents this routine from +** being called with pPrior==0. +** +** nBytes is always a value obtained from a prior call to +** memsys5Round(). Hence nBytes is always a non-negative power +** of two. If nBytes==0 that means that an oversize allocation +** (an allocation larger than 0x40000000) was requested and this +** routine should return 0 without freeing pPrior. +*/ +static void *memsys5Realloc(void *pPrior, int nBytes){ + int nOld; + void *p; + assert( pPrior!=0 ); + assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */ + assert( nBytes>=0 ); + if( nBytes==0 ){ + return 0; + } + nOld = memsys5Size(pPrior); + if( nBytes<=nOld ){ + return pPrior; + } + memsys5Enter(); + p = memsys5MallocUnsafe(nBytes); + if( p ){ + memcpy(p, pPrior, nOld); + memsys5FreeUnsafe(pPrior); + } + memsys5Leave(); + return p; +} + +/* +** Round up a request size to the next valid allocation size. If +** the allocation is too large to be handled by this allocation system, +** return 0. +** +** All allocations must be a power of two and must be expressed by a +** 32-bit signed integer. Hence the largest allocation is 0x40000000 +** or 1073741824 bytes. +*/ +static int memsys5Roundup(int n){ + int iFullSz; + if( n > 0x40000000 ) return 0; + for(iFullSz=mem5.szAtom; iFullSz 0 +** memsys5Log(2) -> 1 +** memsys5Log(4) -> 2 +** memsys5Log(5) -> 3 +** memsys5Log(8) -> 3 +** memsys5Log(9) -> 4 +*/ +static int memsys5Log(int iValue){ + int iLog; + for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<mem5.szAtom ){ + mem5.szAtom = mem5.szAtom << 1; + } + + mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8))); + mem5.zPool = zByte; + mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom]; + + for(ii=0; ii<=LOGMAX; ii++){ + mem5.aiFreelist[ii] = -1; + } + + iOffset = 0; + for(ii=LOGMAX; ii>=0; ii--){ + int nAlloc = (1<mem5.nBlock); + } + + /* If a mutex is required for normal operation, allocate one */ + if( sqlite3GlobalConfig.bMemstat==0 ){ + mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + } + + return SQLITE_OK; +} + +/* +** Deinitialize this module. +*/ +static void memsys5Shutdown(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + mem5.mutex = 0; + return; +} + +#ifdef SQLITE_TEST +/* +** Open the file indicated and write a log of all unfreed memory +** allocations into that log. +*/ +SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){ + FILE *out; + int i, j, n; + int nMinLog; + + if( zFilename==0 || zFilename[0]==0 ){ + out = stdout; + }else{ + out = fopen(zFilename, "w"); + if( out==0 ){ + fprintf(stderr, "** Unable to output memory debug output log: %s **\n", + zFilename); + return; + } + } + memsys5Enter(); + nMinLog = memsys5Log(mem5.szAtom); + for(i=0; i<=LOGMAX && i+nMinLog<32; i++){ + for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){} + fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n); + } + fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc); + fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc); + fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess); + fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut); + fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount); + fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut); + fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount); + fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest); + memsys5Leave(); + if( out==stdout ){ + fflush(stdout); + }else{ + fclose(out); + } +} +#endif + +/* +** This routine is the only routine in this file with external +** linkage. It returns a pointer to a static sqlite3_mem_methods +** struct populated with the memsys5 methods. +*/ +SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){ + static const sqlite3_mem_methods memsys5Methods = { + memsys5Malloc, + memsys5Free, + memsys5Realloc, + memsys5Size, + memsys5Roundup, + memsys5Init, + memsys5Shutdown, + 0 + }; + return &memsys5Methods; +} + +#endif /* SQLITE_ENABLE_MEMSYS5 */ + +/************** End of mem5.c ************************************************/ +/************** Begin file mutex.c *******************************************/ +/* +** 2007 August 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement mutexes. +** +** This file contains code that is common across all mutex implementations. +*/ + +#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT) +/* +** For debugging purposes, record when the mutex subsystem is initialized +** and uninitialized so that we can assert() if there is an attempt to +** allocate a mutex while the system is uninitialized. +*/ +static SQLITE_WSD int mutexIsInit = 0; +#endif /* SQLITE_DEBUG */ + + +#ifndef SQLITE_MUTEX_OMIT +/* +** Initialize the mutex system. +*/ +SQLITE_PRIVATE int sqlite3MutexInit(void){ + int rc = SQLITE_OK; + if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){ + /* If the xMutexAlloc method has not been set, then the user did not + ** install a mutex implementation via sqlite3_config() prior to + ** sqlite3_initialize() being called. This block copies pointers to + ** the default implementation into the sqlite3GlobalConfig structure. + */ + sqlite3_mutex_methods const *pFrom; + sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex; + + if( sqlite3GlobalConfig.bCoreMutex ){ + pFrom = sqlite3DefaultMutex(); + }else{ + pFrom = sqlite3NoopMutex(); + } + memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc)); + memcpy(&pTo->xMutexFree, &pFrom->xMutexFree, + sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree)); + pTo->xMutexAlloc = pFrom->xMutexAlloc; + } + rc = sqlite3GlobalConfig.mutex.xMutexInit(); + +#ifdef SQLITE_DEBUG + GLOBAL(int, mutexIsInit) = 1; +#endif + + return rc; +} + +/* +** Shutdown the mutex system. This call frees resources allocated by +** sqlite3MutexInit(). +*/ +SQLITE_PRIVATE int sqlite3MutexEnd(void){ + int rc = SQLITE_OK; + if( sqlite3GlobalConfig.mutex.xMutexEnd ){ + rc = sqlite3GlobalConfig.mutex.xMutexEnd(); + } + +#ifdef SQLITE_DEBUG + GLOBAL(int, mutexIsInit) = 0; +#endif + + return rc; +} + +/* +** Retrieve a pointer to a static mutex or allocate a new dynamic one. +*/ +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){ +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + return sqlite3GlobalConfig.mutex.xMutexAlloc(id); +} + +SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){ + if( !sqlite3GlobalConfig.bCoreMutex ){ + return 0; + } + assert( GLOBAL(int, mutexIsInit) ); + return sqlite3GlobalConfig.mutex.xMutexAlloc(id); +} + +/* +** Free a dynamic mutex. +*/ +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){ + if( p ){ + sqlite3GlobalConfig.mutex.xMutexFree(p); + } +} + +/* +** Obtain the mutex p. If some other thread already has the mutex, block +** until it can be obtained. +*/ +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){ + if( p ){ + sqlite3GlobalConfig.mutex.xMutexEnter(p); + } +} + +/* +** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another +** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY. +*/ +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){ + int rc = SQLITE_OK; + if( p ){ + return sqlite3GlobalConfig.mutex.xMutexTry(p); + } + return rc; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was previously +** entered by the same thread. The behavior is undefined if the mutex +** is not currently entered. If a NULL pointer is passed as an argument +** this function is a no-op. +*/ +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){ + if( p ){ + sqlite3GlobalConfig.mutex.xMutexLeave(p); + } +} + +#ifndef NDEBUG +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use inside assert() statements. +*/ +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){ + return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p); +} +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){ + return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p); +} +#endif + +#endif /* !defined(SQLITE_MUTEX_OMIT) */ + +/************** End of mutex.c ***********************************************/ +/************** Begin file mutex_noop.c **************************************/ +/* +** 2008 October 07 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement mutexes. +** +** This implementation in this file does not provide any mutual +** exclusion and is thus suitable for use only in applications +** that use SQLite in a single thread. The routines defined +** here are place-holders. Applications can substitute working +** mutex routines at start-time using the +** +** sqlite3_config(SQLITE_CONFIG_MUTEX,...) +** +** interface. +** +** If compiled with SQLITE_DEBUG, then additional logic is inserted +** that does error checking on mutexes to make sure they are being +** called correctly. +*/ + +#ifndef SQLITE_MUTEX_OMIT + +#ifndef SQLITE_DEBUG +/* +** Stub routines for all mutex methods. +** +** This routines provide no mutual exclusion or error checking. +*/ +static int noopMutexInit(void){ return SQLITE_OK; } +static int noopMutexEnd(void){ return SQLITE_OK; } +static sqlite3_mutex *noopMutexAlloc(int id){ + UNUSED_PARAMETER(id); + return (sqlite3_mutex*)8; +} +static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } +static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } +static int noopMutexTry(sqlite3_mutex *p){ + UNUSED_PARAMETER(p); + return SQLITE_OK; +} +static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } + +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ + static const sqlite3_mutex_methods sMutex = { + noopMutexInit, + noopMutexEnd, + noopMutexAlloc, + noopMutexFree, + noopMutexEnter, + noopMutexTry, + noopMutexLeave, + + 0, + 0, + }; + + return &sMutex; +} +#endif /* !SQLITE_DEBUG */ + +#ifdef SQLITE_DEBUG +/* +** In this implementation, error checking is provided for testing +** and debugging purposes. The mutexes still do not provide any +** mutual exclusion. +*/ + +/* +** The mutex object +*/ +typedef struct sqlite3_debug_mutex { + int id; /* The mutex type */ + int cnt; /* Number of entries without a matching leave */ +} sqlite3_debug_mutex; + +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use inside assert() statements. +*/ +static int debugMutexHeld(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + return p==0 || p->cnt>0; +} +static int debugMutexNotheld(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + return p==0 || p->cnt==0; +} + +/* +** Initialize and deinitialize the mutex subsystem. +*/ +static int debugMutexInit(void){ return SQLITE_OK; } +static int debugMutexEnd(void){ return SQLITE_OK; } + +/* +** The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. If it returns NULL +** that means that a mutex could not be allocated. +*/ +static sqlite3_mutex *debugMutexAlloc(int id){ + static sqlite3_debug_mutex aStatic[6]; + sqlite3_debug_mutex *pNew = 0; + switch( id ){ + case SQLITE_MUTEX_FAST: + case SQLITE_MUTEX_RECURSIVE: { + pNew = sqlite3Malloc(sizeof(*pNew)); + if( pNew ){ + pNew->id = id; + pNew->cnt = 0; + } + break; + } + default: { + assert( id-2 >= 0 ); + assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) ); + pNew = &aStatic[id-2]; + pNew->id = id; + break; + } + } + return (sqlite3_mutex*)pNew; +} + +/* +** This routine deallocates a previously allocated mutex. +*/ +static void debugMutexFree(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + assert( p->cnt==0 ); + assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ); + sqlite3_free(p); +} + +/* +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can +** be entered multiple times by the same thread. In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. If the same thread tries to enter any other kind of mutex +** more than once, the behavior is undefined. +*/ +static void debugMutexEnter(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); + p->cnt++; +} +static int debugMutexTry(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); + p->cnt++; + return SQLITE_OK; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. The behavior +** is undefined if the mutex is not currently entered or +** is not currently allocated. SQLite will never do either. +*/ +static void debugMutexLeave(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + assert( debugMutexHeld(pX) ); + p->cnt--; + assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); +} + +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ + static const sqlite3_mutex_methods sMutex = { + debugMutexInit, + debugMutexEnd, + debugMutexAlloc, + debugMutexFree, + debugMutexEnter, + debugMutexTry, + debugMutexLeave, + + debugMutexHeld, + debugMutexNotheld + }; + + return &sMutex; +} +#endif /* SQLITE_DEBUG */ + +/* +** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation +** is used regardless of the run-time threadsafety setting. +*/ +#ifdef SQLITE_MUTEX_NOOP +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ + return sqlite3NoopMutex(); +} +#endif /* defined(SQLITE_MUTEX_NOOP) */ +#endif /* !defined(SQLITE_MUTEX_OMIT) */ + +/************** End of mutex_noop.c ******************************************/ +/************** Begin file mutex_rtthread.c **********************************/ +/* +** 2007 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement mutexes for rtthread +*/ + +/* +** The code in this file is only used if we are compiling threadsafe +** under rt-thread with rt_mutex. +** +** Note that this implementation requires a version of rt-thread that +** supports recursive mutexes. +*/ +#ifdef SQLITE_MUTEX_RTTHREAD + +/* #include */ + +/* +** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields +** are necessary under two condidtions: (1) Debug builds and (2) using +** home-grown mutexes. Encapsulate these conditions into a single #define. +*/ +#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX) +# define SQLITE_MUTEX_NREF 1 +#else +# define SQLITE_MUTEX_NREF 0 +#endif + +/* +** Each recursive mutex is an instance of the following structure. +*/ +struct sqlite3_mutex { + struct rt_mutex mutex; /* Mutex controlling the lock */ +#if SQLITE_MUTEX_NREF + int id; /* Mutex type */ + volatile int nRef; /* Number of entrances */ + volatile rt_thread_t owner; /* Thread that is within this mutex */ + int trace; /* True to trace changes */ +#endif +}; +#define RTT_MUTEX_INITIALIZER { 0 } +#if SQLITE_MUTEX_NREF +#define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER, 0, 0, (rt_thread_t)0, 0 } +#else +#define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER } +#endif + +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use only inside assert() statements. On some platforms, +** there might be race conditions that can cause these routines to +** deliver incorrect results. In particular, if rtthread_equal() is +** not an atomic operation, then these routines might delivery +** incorrect results. On most platforms, rtthread_equal() is a +** comparison of two integers and is therefore atomic. But we are +** told that HPUX is not such a platform. If so, then these routines +** will not always work correctly on HPUX. +** +** On those platforms where rtthread_equal() is not atomic, SQLite +** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to +** make sure no assert() statements are evaluated and hence these +** routines are never called. +*/ +#if !defined(NDEBUG) || defined(SQLITE_DEBUG) +static int rtthreadMutexHeld(sqlite3_mutex *p){ + return (p->nRef != 0 && p->owner == rt_thread_self()); +} +static int rtthreadMutexNotheld(sqlite3_mutex *p){ + return (p->nRef == 0 || p->owner != rt_thread_self()); +} +#endif + +/* +** Initialize and deinitialize the mutex subsystem. +*/ +static int rtthreadMutexInit(void){ return SQLITE_OK; } +static int rtthreadMutexEnd(void){ return SQLITE_OK; } + +/* +** The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. If it returns NULL +** that means that a mutex could not be allocated. SQLite +** will unwind its stack and return an error. The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_PMEM +**
+** +** The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. But SQLite will only request a recursive mutex in +** cases where it really needs one. If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +*/ +static sqlite3_mutex* rtthreadMutexAlloc(int iType){ + static sqlite3_mutex staticMutexes[] = { + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER + }; + sqlite3_mutex *p; + switch( iType ){ + case SQLITE_MUTEX_RECURSIVE: { + p = sqlite3MallocZero( sizeof(*p) ); + if( p ){ + /* Use a recursive mutex if it is available */ + rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO); +#if SQLITE_MUTEX_NREF + p->id = iType; +#endif + } + break; + } + case SQLITE_MUTEX_FAST: { + p = sqlite3MallocZero( sizeof(*p) ); + if( p ){ +#if SQLITE_MUTEX_NREF + p->id = iType; +#endif + rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO); + } + break; + } + default: { + assert( iType-2 >= 0 ); + assert( iType-2 < ArraySize(staticMutexes) ); + p = &staticMutexes[iType-2]; +#if SQLITE_MUTEX_NREF + p->id = iType; +#endif + rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO); + break; + } + } + return p; +} + + +/* +** This routine deallocates a previously +** allocated mutex. SQLite is careful to deallocate every +** mutex that it allocates. +*/ +static void rtthreadMutexFree(sqlite3_mutex *p){ + assert( p->nRef==0 ); + assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ); + rt_mutex_detach(&p->mutex); + sqlite3_free(p); +} + +/* +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can +** be entered multiple times by the same thread. In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. If the same thread tries to enter any other kind of mutex +** more than once, the behavior is undefined. +*/ +static void rtthreadMutexEnter(sqlite3_mutex *p){ + assert( p->id==SQLITE_MUTEX_RECURSIVE || rtthreadMutexNotheld(p) ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, then we have to grow + ** our own. This implementation assumes that rtthread_equal() + ** is atomic - that it cannot be deceived into thinking self + ** and p->owner are equal if p->owner changes between two values + ** that are not equal to self while the comparison is taking place. + ** This implementation also assumes a coherent cache - that + ** separate processes cannot read different values from the same + ** address at the same time. If either of these two conditions + ** are not met, then the mutexes will fail and problems will result. + */ + { + rt_thread_t self = rt_thread_self(); + if( p->nRef>0 && (p->owner == self) ){ + p->nRef++; + }else{ + rt_mutex_take(&p->mutex, RT_WAITING_FOREVER); + assert( p->nRef==0 ); + p->owner = self; + p->nRef = 1; + } + } +#else + /* Use the built-in recursive mutexes if they are available. + */ + rt_mutex_take(&p->mutex, RT_WAITING_FOREVER); +#if SQLITE_MUTEX_NREF + assert( p->nRef>0 || p->owner==0 ); + p->owner = rt_thread_self(); + p->nRef++; +#endif +#endif + +#ifdef SQLITE_DEBUG + if( p->trace ){ + rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif +} +static int rtthreadMutexTry(sqlite3_mutex *p){ + int rc; + assert( p->id==SQLITE_MUTEX_RECURSIVE || rtthreadMutexNotheld(p) ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, then we have to grow + ** our own. This implementation assumes that rtthread_equal() + ** is atomic - that it cannot be deceived into thinking self + ** and p->owner are equal if p->owner changes between two values + ** that are not equal to self while the comparison is taking place. + ** This implementation also assumes a coherent cache - that + ** separate processes cannot read different values from the same + ** address at the same time. If either of these two conditions + ** are not met, then the mutexes will fail and problems will result. + */ + { + rt_thread_t self = rt_thread_self(); + if( p->nRef>0 && (p->owner == self) ){ + p->nRef++; + rc = SQLITE_OK; + }else if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){ + assert( p->nRef==0 ); + p->owner = self; + p->nRef = 1; + rc = SQLITE_OK; + }else{ + rc = SQLITE_BUSY; + } + } +#else + /* Use the built-in recursive mutexes if they are available. + */ + if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){ +#if SQLITE_MUTEX_NREF + p->owner = rt_thread_self(); + p->nRef++; +#endif + rc = SQLITE_OK; + }else{ + rc = SQLITE_BUSY; + } +#endif + +#ifdef SQLITE_DEBUG + if( rc==SQLITE_OK && p->trace ){ + rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif + return rc; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. The behavior +** is undefined if the mutex is not currently entered or +** is not currently allocated. SQLite will never do either. +*/ +static void rtthreadMutexLeave(sqlite3_mutex *p){ + assert( rtthreadMutexHeld(p) ); +#if SQLITE_MUTEX_NREF + p->nRef--; + if( p->nRef==0 ) p->owner = 0; +#endif + assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + if( p->nRef==0 ){ + rt_mutex_release(&p->mutex); + } +#else + rt_mutex_release(&p->mutex); +#endif + +#ifdef SQLITE_DEBUG + if( p->trace ){ + rt_kprintf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif +} + +SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ + static const sqlite3_mutex_methods sMutex = { + rtthreadMutexInit, + rtthreadMutexEnd, + rtthreadMutexAlloc, + rtthreadMutexFree, + rtthreadMutexEnter, + rtthreadMutexTry, + rtthreadMutexLeave, +#ifdef SQLITE_DEBUG + rtthreadMutexHeld, + rtthreadMutexNotheld +#else + 0, + 0 +#endif + }; + + return &sMutex; +} + +#endif /* SQLITE_MUTEX_RTTHREAD */ + + +/************** End of mutex_rtthread.c **************************************/ +/************** Begin file malloc.c ******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** Memory allocation functions used throughout sqlite. +*/ +/* #include */ + +/* +** Attempt to release up to n bytes of non-essential memory currently +** held by SQLite. An example of non-essential memory is memory used to +** cache database pages that are not currently in use. +*/ +SQLITE_API int sqlite3_release_memory(int n){ +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT + return sqlite3PcacheReleaseMemory(n); +#else + /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine + ** is a no-op returning zero if SQLite is not compiled with + ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */ + UNUSED_PARAMETER(n); + return 0; +#endif +} + +/* +** An instance of the following object records the location of +** each unused scratch buffer. +*/ +typedef struct ScratchFreeslot { + struct ScratchFreeslot *pNext; /* Next unused scratch buffer */ +} ScratchFreeslot; + +/* +** State information local to the memory allocation subsystem. +*/ +static SQLITE_WSD struct Mem0Global { + sqlite3_mutex *mutex; /* Mutex to serialize access */ + + /* + ** The alarm callback and its arguments. The mem0.mutex lock will + ** be held while the callback is running. Recursive calls into + ** the memory subsystem are allowed, but no new callbacks will be + ** issued. + */ + sqlite3_int64 alarmThreshold; + void (*alarmCallback)(void*, sqlite3_int64,int); + void *alarmArg; + + /* + ** Pointers to the end of sqlite3GlobalConfig.pScratch memory + ** (so that a range test can be used to determine if an allocation + ** being freed came from pScratch) and a pointer to the list of + ** unused scratch allocations. + */ + void *pScratchEnd; + ScratchFreeslot *pScratchFree; + u32 nScratchFree; + + /* + ** True if heap is nearly "full" where "full" is defined by the + ** sqlite3_soft_heap_limit() setting. + */ + int nearlyFull; +} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 }; + +#define mem0 GLOBAL(struct Mem0Global, mem0) + +/* +** This routine runs when the memory allocator sees that the +** total memory allocation is about to exceed the soft heap +** limit. +*/ +static void softHeapLimitEnforcer( + void *NotUsed, + sqlite3_int64 NotUsed2, + int allocSize +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + sqlite3_release_memory(allocSize); +} + +/* +** Change the alarm callback +*/ +static int sqlite3MemoryAlarm( + void(*xCallback)(void *pArg, sqlite3_int64 used,int N), + void *pArg, + sqlite3_int64 iThreshold +){ + int nUsed; + sqlite3_mutex_enter(mem0.mutex); + mem0.alarmCallback = xCallback; + mem0.alarmArg = pArg; + mem0.alarmThreshold = iThreshold; + nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed); + sqlite3_mutex_leave(mem0.mutex); + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** Deprecated external interface. Internal/core SQLite code +** should call sqlite3MemoryAlarm. +*/ +SQLITE_API int sqlite3_memory_alarm( + void(*xCallback)(void *pArg, sqlite3_int64 used,int N), + void *pArg, + sqlite3_int64 iThreshold +){ + return sqlite3MemoryAlarm(xCallback, pArg, iThreshold); +} +#endif + +/* +** Set the soft heap-size limit for the library. Passing a zero or +** negative value indicates no limit. +*/ +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){ + sqlite3_int64 priorLimit; + sqlite3_int64 excess; +#ifndef SQLITE_OMIT_AUTOINIT + int rc = sqlite3_initialize(); + if( rc ) return -1; +#endif + sqlite3_mutex_enter(mem0.mutex); + priorLimit = mem0.alarmThreshold; + sqlite3_mutex_leave(mem0.mutex); + if( n<0 ) return priorLimit; + if( n>0 ){ + sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n); + }else{ + sqlite3MemoryAlarm(0, 0, 0); + } + excess = sqlite3_memory_used() - n; + if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff)); + return priorLimit; +} +SQLITE_API void sqlite3_soft_heap_limit(int n){ + if( n<0 ) n = 0; + sqlite3_soft_heap_limit64(n); +} + +/* +** Initialize the memory allocation subsystem. +*/ +SQLITE_PRIVATE int sqlite3MallocInit(void){ + if( sqlite3GlobalConfig.m.xMalloc==0 ){ + sqlite3MemSetDefault(); + } + memset(&mem0, 0, sizeof(mem0)); + if( sqlite3GlobalConfig.bCoreMutex ){ + mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + } + if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100 + && sqlite3GlobalConfig.nScratch>0 ){ + int i, n, sz; + ScratchFreeslot *pSlot; + sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch); + sqlite3GlobalConfig.szScratch = sz; + pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch; + n = sqlite3GlobalConfig.nScratch; + mem0.pScratchFree = pSlot; + mem0.nScratchFree = n; + for(i=0; ipNext = (ScratchFreeslot*)(sz+(char*)pSlot); + pSlot = pSlot->pNext; + } + pSlot->pNext = 0; + mem0.pScratchEnd = (void*)&pSlot[1]; + }else{ + mem0.pScratchEnd = 0; + sqlite3GlobalConfig.pScratch = 0; + sqlite3GlobalConfig.szScratch = 0; + sqlite3GlobalConfig.nScratch = 0; + } + if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512 + || sqlite3GlobalConfig.nPage<1 ){ + sqlite3GlobalConfig.pPage = 0; + sqlite3GlobalConfig.szPage = 0; + sqlite3GlobalConfig.nPage = 0; + } + return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData); +} + +/* +** Return true if the heap is currently under memory pressure - in other +** words if the amount of heap used is close to the limit set by +** sqlite3_soft_heap_limit(). +*/ +SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){ + return mem0.nearlyFull; +} + +/* +** Deinitialize the memory allocation subsystem. +*/ +SQLITE_PRIVATE void sqlite3MallocEnd(void){ + if( sqlite3GlobalConfig.m.xShutdown ){ + sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData); + } + memset(&mem0, 0, sizeof(mem0)); +} + +/* +** Return the amount of memory currently checked out. +*/ +SQLITE_API sqlite3_int64 sqlite3_memory_used(void){ + int n, mx; + sqlite3_int64 res; + sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0); + res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */ + return res; +} + +/* +** Return the maximum amount of memory that has ever been +** checked out since either the beginning of this process +** or since the most recent reset. +*/ +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){ + int n, mx; + sqlite3_int64 res; + sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag); + res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */ + return res; +} + +/* +** Trigger the alarm +*/ +static void sqlite3MallocAlarm(int nByte){ + void (*xCallback)(void*,sqlite3_int64,int); + sqlite3_int64 nowUsed; + void *pArg; + if( mem0.alarmCallback==0 ) return; + xCallback = mem0.alarmCallback; + nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + pArg = mem0.alarmArg; + mem0.alarmCallback = 0; + sqlite3_mutex_leave(mem0.mutex); + xCallback(pArg, nowUsed, nByte); + sqlite3_mutex_enter(mem0.mutex); + mem0.alarmCallback = xCallback; + mem0.alarmArg = pArg; +} + +/* +** Do a memory allocation with statistics and alarms. Assume the +** lock is already held. +*/ +static int mallocWithAlarm(int n, void **pp){ + int nFull; + void *p; + assert( sqlite3_mutex_held(mem0.mutex) ); + nFull = sqlite3GlobalConfig.m.xRoundup(n); + sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n); + if( mem0.alarmCallback!=0 ){ + int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + if( nUsed >= mem0.alarmThreshold - nFull ){ + mem0.nearlyFull = 1; + sqlite3MallocAlarm(nFull); + }else{ + mem0.nearlyFull = 0; + } + } + p = sqlite3GlobalConfig.m.xMalloc(nFull); +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT + if( p==0 && mem0.alarmCallback ){ + sqlite3MallocAlarm(nFull); + p = sqlite3GlobalConfig.m.xMalloc(nFull); + } +#endif + if( p ){ + nFull = sqlite3MallocSize(p); + sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull); + sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1); + } + *pp = p; + return nFull; +} + +/* +** Allocate memory. This routine is like sqlite3_malloc() except that it +** assumes the memory subsystem has already been initialized. +*/ +SQLITE_PRIVATE void *sqlite3Malloc(int n){ + void *p; + if( n<=0 /* IMP: R-65312-04917 */ + || n>=0x7fffff00 + ){ + /* A memory allocation of a number of bytes which is near the maximum + ** signed integer value might cause an integer overflow inside of the + ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving + ** 255 bytes of overhead. SQLite itself will never use anything near + ** this amount. The only way to reach the limit is with sqlite3_malloc() */ + p = 0; + }else if( sqlite3GlobalConfig.bMemstat ){ + sqlite3_mutex_enter(mem0.mutex); + mallocWithAlarm(n, &p); + sqlite3_mutex_leave(mem0.mutex); + }else{ + p = sqlite3GlobalConfig.m.xMalloc(n); + } + assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */ + return p; +} + +/* +** This version of the memory allocation is for use by the application. +** First make sure the memory subsystem is initialized, then do the +** allocation. +*/ +SQLITE_API void *sqlite3_malloc(int n){ +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + return sqlite3Malloc(n); +} + +/* +** Each thread may only have a single outstanding allocation from +** xScratchMalloc(). We verify this constraint in the single-threaded +** case by setting scratchAllocOut to 1 when an allocation +** is outstanding clearing it when the allocation is freed. +*/ +#if SQLITE_THREADSAFE==0 && !defined(NDEBUG) +static int scratchAllocOut = 0; +#endif + + +/* +** Allocate memory that is to be used and released right away. +** This routine is similar to alloca() in that it is not intended +** for situations where the memory might be held long-term. This +** routine is intended to get memory to old large transient data +** structures that would not normally fit on the stack of an +** embedded processor. +*/ +SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){ + void *p; + assert( n>0 ); + + sqlite3_mutex_enter(mem0.mutex); + if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){ + p = mem0.pScratchFree; + mem0.pScratchFree = mem0.pScratchFree->pNext; + mem0.nScratchFree--; + sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1); + sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n); + sqlite3_mutex_leave(mem0.mutex); + }else{ + if( sqlite3GlobalConfig.bMemstat ){ + sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n); + n = mallocWithAlarm(n, &p); + if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n); + sqlite3_mutex_leave(mem0.mutex); + }else{ + sqlite3_mutex_leave(mem0.mutex); + p = sqlite3GlobalConfig.m.xMalloc(n); + } + sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH); + } + assert( sqlite3_mutex_notheld(mem0.mutex) ); + + +#if SQLITE_THREADSAFE==0 && !defined(NDEBUG) + /* Verify that no more than two scratch allocations per thread + ** are outstanding at one time. (This is only checked in the + ** single-threaded case since checking in the multi-threaded case + ** would be much more complicated.) */ + assert( scratchAllocOut<=1 ); + if( p ) scratchAllocOut++; +#endif + + return p; +} +SQLITE_PRIVATE void sqlite3ScratchFree(void *p){ + if( p ){ + +#if SQLITE_THREADSAFE==0 && !defined(NDEBUG) + /* Verify that no more than two scratch allocation per thread + ** is outstanding at one time. (This is only checked in the + ** single-threaded case since checking in the multi-threaded case + ** would be much more complicated.) */ + assert( scratchAllocOut>=1 && scratchAllocOut<=2 ); + scratchAllocOut--; +#endif + + if( p>=sqlite3GlobalConfig.pScratch && ppNext = mem0.pScratchFree; + mem0.pScratchFree = pSlot; + mem0.nScratchFree++; + assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch ); + sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1); + sqlite3_mutex_leave(mem0.mutex); + }else{ + /* Release memory back to the heap */ + assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) ); + assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) ); + sqlite3MemdebugSetType(p, MEMTYPE_HEAP); + if( sqlite3GlobalConfig.bMemstat ){ + int iSize = sqlite3MallocSize(p); + sqlite3_mutex_enter(mem0.mutex); + sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize); + sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize); + sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1); + sqlite3GlobalConfig.m.xFree(p); + sqlite3_mutex_leave(mem0.mutex); + }else{ + sqlite3GlobalConfig.m.xFree(p); + } + } + } +} + +/* +** TRUE if p is a lookaside memory allocation from db +*/ +#ifndef SQLITE_OMIT_LOOKASIDE +static int isLookaside(sqlite3 *db, void *p){ + return p && p>=db->lookaside.pStart && plookaside.pEnd; +} +#else +#define isLookaside(A,B) 0 +#endif + +/* +** Return the size of a memory allocation previously obtained from +** sqlite3Malloc() or sqlite3_malloc(). +*/ +SQLITE_PRIVATE int sqlite3MallocSize(void *p){ + assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); + assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) ); + return sqlite3GlobalConfig.m.xSize(p); +} +SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){ + assert( db==0 || sqlite3_mutex_held(db->mutex) ); + if( db && isLookaside(db, p) ){ + return db->lookaside.sz; + }else{ + assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) ); + assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) ); + assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); + return sqlite3GlobalConfig.m.xSize(p); + } +} + +/* +** Free memory previously obtained from sqlite3Malloc(). +*/ +SQLITE_API void sqlite3_free(void *p){ + if( p==0 ) return; /* IMP: R-49053-54554 */ + assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) ); + assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); + if( sqlite3GlobalConfig.bMemstat ){ + sqlite3_mutex_enter(mem0.mutex); + sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p)); + sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1); + sqlite3GlobalConfig.m.xFree(p); + sqlite3_mutex_leave(mem0.mutex); + }else{ + sqlite3GlobalConfig.m.xFree(p); + } +} + +/* +** Free memory that might be associated with a particular database +** connection. +*/ +SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){ + assert( db==0 || sqlite3_mutex_held(db->mutex) ); + if( p==0 ) return; + if( db ){ + if( db->pnBytesFreed ){ + *db->pnBytesFreed += sqlite3DbMallocSize(db, p); + return; + } + if( isLookaside(db, p) ){ + LookasideSlot *pBuf = (LookasideSlot*)p; +#if SQLITE_DEBUG + /* Trash all content in the buffer being freed */ + memset(p, 0xaa, db->lookaside.sz); +#endif + pBuf->pNext = db->lookaside.pFree; + db->lookaside.pFree = pBuf; + db->lookaside.nOut--; + return; + } + } + assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) ); + assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) ); + assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); + sqlite3MemdebugSetType(p, MEMTYPE_HEAP); + sqlite3_free(p); +} + +/* +** Change the size of an existing memory allocation +*/ +SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){ + int nOld, nNew, nDiff; + void *pNew; + if( pOld==0 ){ + return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */ + } + if( nBytes<=0 ){ + sqlite3_free(pOld); /* IMP: R-31593-10574 */ + return 0; + } + if( nBytes>=0x7fffff00 ){ + /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ + return 0; + } + nOld = sqlite3MallocSize(pOld); + /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second + ** argument to xRealloc is always a value returned by a prior call to + ** xRoundup. */ + nNew = sqlite3GlobalConfig.m.xRoundup(nBytes); + if( nOld==nNew ){ + pNew = pOld; + }else if( sqlite3GlobalConfig.bMemstat ){ + sqlite3_mutex_enter(mem0.mutex); + sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes); + nDiff = nNew - nOld; + if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= + mem0.alarmThreshold-nDiff ){ + sqlite3MallocAlarm(nDiff); + } + assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) ); + assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) ); + pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + if( pNew==0 && mem0.alarmCallback ){ + sqlite3MallocAlarm(nBytes); + pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + } + if( pNew ){ + nNew = sqlite3MallocSize(pNew); + sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld); + } + sqlite3_mutex_leave(mem0.mutex); + }else{ + pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + } + assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */ + return pNew; +} + +/* +** The public interface to sqlite3Realloc. Make sure that the memory +** subsystem is initialized prior to invoking sqliteRealloc. +*/ +SQLITE_API void *sqlite3_realloc(void *pOld, int n){ +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + return sqlite3Realloc(pOld, n); +} + + +/* +** Allocate and zero memory. +*/ +SQLITE_PRIVATE void *sqlite3MallocZero(int n){ + void *p = sqlite3Malloc(n); + if( p ){ + memset(p, 0, n); + } + return p; +} + +/* +** Allocate and zero memory. If the allocation fails, make +** the mallocFailed flag in the connection pointer. +*/ +SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){ + void *p = sqlite3DbMallocRaw(db, n); + if( p ){ + memset(p, 0, n); + } + return p; +} + +/* +** Allocate and zero memory. If the allocation fails, make +** the mallocFailed flag in the connection pointer. +** +** If db!=0 and db->mallocFailed is true (indicating a prior malloc +** failure on the same database connection) then always return 0. +** Hence for a particular database connection, once malloc starts +** failing, it fails consistently until mallocFailed is reset. +** This is an important assumption. There are many places in the +** code that do things like this: +** +** int *a = (int*)sqlite3DbMallocRaw(db, 100); +** int *b = (int*)sqlite3DbMallocRaw(db, 200); +** if( b ) a[10] = 9; +** +** In other words, if a subsequent malloc (ex: "b") worked, it is assumed +** that all prior mallocs (ex: "a") worked too. +*/ +SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){ + void *p; + assert( db==0 || sqlite3_mutex_held(db->mutex) ); + assert( db==0 || db->pnBytesFreed==0 ); +#ifndef SQLITE_OMIT_LOOKASIDE + if( db ){ + LookasideSlot *pBuf; + if( db->mallocFailed ){ + return 0; + } + if( db->lookaside.bEnabled ){ + if( n>db->lookaside.sz ){ + db->lookaside.anStat[1]++; + }else if( (pBuf = db->lookaside.pFree)==0 ){ + db->lookaside.anStat[2]++; + }else{ + db->lookaside.pFree = pBuf->pNext; + db->lookaside.nOut++; + db->lookaside.anStat[0]++; + if( db->lookaside.nOut>db->lookaside.mxOut ){ + db->lookaside.mxOut = db->lookaside.nOut; + } + return (void*)pBuf; + } + } + } +#else + if( db && db->mallocFailed ){ + return 0; + } +#endif + p = sqlite3Malloc(n); + if( !p && db ){ + db->mallocFailed = 1; + } + sqlite3MemdebugSetType(p, MEMTYPE_DB | + ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); + return p; +} + +/* +** Resize the block of memory pointed to by p to n bytes. If the +** resize fails, set the mallocFailed flag in the connection object. +*/ +SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){ + void *pNew = 0; + assert( db!=0 ); + assert( sqlite3_mutex_held(db->mutex) ); + if( db->mallocFailed==0 ){ + if( p==0 ){ + return sqlite3DbMallocRaw(db, n); + } + if( isLookaside(db, p) ){ + if( n<=db->lookaside.sz ){ + return p; + } + pNew = sqlite3DbMallocRaw(db, n); + if( pNew ){ + memcpy(pNew, p, db->lookaside.sz); + sqlite3DbFree(db, p); + } + }else{ + assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) ); + assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) ); + sqlite3MemdebugSetType(p, MEMTYPE_HEAP); + pNew = sqlite3_realloc(p, n); + if( !pNew ){ + sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP); + db->mallocFailed = 1; + } + sqlite3MemdebugSetType(pNew, MEMTYPE_DB | + (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); + } + } + return pNew; +} + +/* +** Attempt to reallocate p. If the reallocation fails, then free p +** and set the mallocFailed flag in the database connection. +*/ +SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){ + void *pNew; + pNew = sqlite3DbRealloc(db, p, n); + if( !pNew ){ + sqlite3DbFree(db, p); + } + return pNew; +} + +/* +** Make a copy of a string in memory obtained from sqliteMalloc(). These +** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This +** is because when memory debugging is turned on, these two functions are +** called via macros that record the current file and line number in the +** ThreadData structure. +*/ +SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){ + char *zNew; + size_t n; + if( z==0 ){ + return 0; + } + n = sqlite3Strlen30(z) + 1; + assert( (n&0x7fffffff)==n ); + zNew = sqlite3DbMallocRaw(db, (int)n); + if( zNew ){ + memcpy(zNew, z, n); + } + return zNew; +} +SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){ + char *zNew; + if( z==0 ){ + return 0; + } + assert( (n&0x7fffffff)==n ); + zNew = sqlite3DbMallocRaw(db, n+1); + if( zNew ){ + memcpy(zNew, z, n); + zNew[n] = 0; + } + return zNew; +} + +/* +** Create a string from the zFromat argument and the va_list that follows. +** Store the string in memory obtained from sqliteMalloc() and make *pz +** point to that string. +*/ +SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){ + va_list ap; + char *z; + + va_start(ap, zFormat); + z = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + sqlite3DbFree(db, *pz); + *pz = z; +} + + +/* +** This function must be called before exiting any API function (i.e. +** returning control to the user) that has called sqlite3_malloc or +** sqlite3_realloc. +** +** The returned value is normally a copy of the second argument to this +** function. However, if a malloc() failure has occurred since the previous +** invocation SQLITE_NOMEM is returned instead. +** +** If the first argument, db, is not NULL and a malloc() error has occurred, +** then the connection error-code (the value returned by sqlite3_errcode()) +** is set to SQLITE_NOMEM. +*/ +SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){ + /* If the db handle is not NULL, then we must hold the connection handle + ** mutex here. Otherwise the read (and possible write) of db->mallocFailed + ** is unsafe, as is the call to sqlite3Error(). + */ + assert( !db || sqlite3_mutex_held(db->mutex) ); + if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){ + sqlite3Error(db, SQLITE_NOMEM, 0); + db->mallocFailed = 0; + rc = SQLITE_NOMEM; + } + return rc & (db ? db->errMask : 0xff); +} + +/************** End of malloc.c **********************************************/ +/************** Begin file printf.c ******************************************/ +/* +** The "printf" code that follows dates from the 1980's. It is in +** the public domain. The original comments are included here for +** completeness. They are very out-of-date but might be useful as +** an historical reference. Most of the "enhancements" have been backed +** out so that the functionality is now the same as standard printf(). +** +************************************************************************** +** +** This file contains code for a set of "printf"-like routines. These +** routines format strings much like the printf() from the standard C +** library, though the implementation here has enhancements to support +** SQLlite. +*/ + +/* +** Conversion types fall into various categories as defined by the +** following enumeration. +*/ +#define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */ +#define etFLOAT 2 /* Floating point. %f */ +#define etEXP 3 /* Exponentional notation. %e and %E */ +#define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */ +#define etSIZE 5 /* Return number of characters processed so far. %n */ +#define etSTRING 6 /* Strings. %s */ +#define etDYNSTRING 7 /* Dynamically allocated strings. %z */ +#define etPERCENT 8 /* Percent symbol. %% */ +#define etCHARX 9 /* Characters. %c */ +/* The rest are extensions, not normally found in printf() */ +#define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */ +#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '', + NULL pointers replaced by SQL NULL. %Q */ +#define etTOKEN 12 /* a pointer to a Token structure */ +#define etSRCLIST 13 /* a pointer to a SrcList */ +#define etPOINTER 14 /* The %p conversion */ +#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */ +#define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ + +#define etINVALID 0 /* Any unrecognized conversion type */ + + +/* +** An "etByte" is an 8-bit unsigned value. +*/ +typedef unsigned char etByte; + +/* +** Each builtin conversion character (ex: the 'd' in "%d") is described +** by an instance of the following structure +*/ +typedef struct et_info { /* Information about each format field */ + char fmttype; /* The format field code letter */ + etByte base; /* The base for radix conversion */ + etByte flags; /* One or more of FLAG_ constants below */ + etByte type; /* Conversion paradigm */ + etByte charset; /* Offset into aDigits[] of the digits string */ + etByte prefix; /* Offset into aPrefix[] of the prefix string */ +} et_info; + +/* +** Allowed values for et_info.flags +*/ +#define FLAG_SIGNED 1 /* True if the value to convert is signed */ +#define FLAG_INTERN 2 /* True if for internal use only */ +#define FLAG_STRING 4 /* Allow infinity precision */ + + +/* +** The following table is searched linearly, so it is good to put the +** most frequently used conversion types first. +*/ +static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; +static const char aPrefix[] = "-x0\000X0"; +static const et_info fmtinfo[] = { + { 'd', 10, 1, etRADIX, 0, 0 }, + { 's', 0, 4, etSTRING, 0, 0 }, + { 'g', 0, 1, etGENERIC, 30, 0 }, + { 'z', 0, 4, etDYNSTRING, 0, 0 }, + { 'q', 0, 4, etSQLESCAPE, 0, 0 }, + { 'Q', 0, 4, etSQLESCAPE2, 0, 0 }, + { 'w', 0, 4, etSQLESCAPE3, 0, 0 }, + { 'c', 0, 0, etCHARX, 0, 0 }, + { 'o', 8, 0, etRADIX, 0, 2 }, + { 'u', 10, 0, etRADIX, 0, 0 }, + { 'x', 16, 0, etRADIX, 16, 1 }, + { 'X', 16, 0, etRADIX, 0, 4 }, +#ifndef SQLITE_OMIT_FLOATING_POINT + { 'f', 0, 1, etFLOAT, 0, 0 }, + { 'e', 0, 1, etEXP, 30, 0 }, + { 'E', 0, 1, etEXP, 14, 0 }, + { 'G', 0, 1, etGENERIC, 14, 0 }, +#endif + { 'i', 10, 1, etRADIX, 0, 0 }, + { 'n', 0, 0, etSIZE, 0, 0 }, + { '%', 0, 0, etPERCENT, 0, 0 }, + { 'p', 16, 0, etPOINTER, 0, 1 }, + +/* All the rest have the FLAG_INTERN bit set and are thus for internal +** use only */ + { 'T', 0, 2, etTOKEN, 0, 0 }, + { 'S', 0, 2, etSRCLIST, 0, 0 }, + { 'r', 10, 3, etORDINAL, 0, 0 }, +}; + +/* +** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point +** conversions will work. +*/ +#ifndef SQLITE_OMIT_FLOATING_POINT +/* +** "*val" is a double such that 0.1 <= *val < 10.0 +** Return the ascii code for the leading digit of *val, then +** multiply "*val" by 10.0 to renormalize. +** +** Example: +** input: *val = 3.14159 +** output: *val = 1.4159 function return = '3' +** +** The counter *cnt is incremented each time. After counter exceeds +** 16 (the number of significant digits in a 64-bit float) '0' is +** always returned. +*/ +static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){ + int digit; + LONGDOUBLE_TYPE d; + if( (*cnt)<=0 ) return '0'; + (*cnt)--; + digit = (int)*val; + d = digit; + digit += '0'; + *val = (*val - d)*10.0; + return (char)digit; +} +#endif /* SQLITE_OMIT_FLOATING_POINT */ + +/* +** Append N space characters to the given string buffer. +*/ +SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){ + static const char zSpaces[] = " "; + while( N>=(int)sizeof(zSpaces)-1 ){ + sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1); + N -= sizeof(zSpaces)-1; + } + if( N>0 ){ + sqlite3StrAccumAppend(pAccum, zSpaces, N); + } +} + +/* +** On machines with a small stack size, you can redefine the +** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired. +*/ +#ifndef SQLITE_PRINT_BUF_SIZE +# define SQLITE_PRINT_BUF_SIZE 70 +#endif +#define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */ + +/* +** Render a string given by "fmt" into the StrAccum object. +*/ +SQLITE_PRIVATE void sqlite3VXPrintf( + StrAccum *pAccum, /* Accumulate results here */ + int useExtended, /* Allow extended %-conversions */ + const char *fmt, /* Format string */ + va_list ap /* arguments */ +){ + int c; /* Next character in the format string */ + char *bufpt; /* Pointer to the conversion buffer */ + int precision; /* Precision of the current field */ + int length; /* Length of the field */ + int idx; /* A general purpose loop counter */ + int width; /* Width of the current field */ + etByte flag_leftjustify; /* True if "-" flag is present */ + etByte flag_plussign; /* True if "+" flag is present */ + etByte flag_blanksign; /* True if " " flag is present */ + etByte flag_alternateform; /* True if "#" flag is present */ + etByte flag_altform2; /* True if "!" flag is present */ + etByte flag_zeropad; /* True if field width constant starts with zero */ + etByte flag_long; /* True if "l" flag is present */ + etByte flag_longlong; /* True if the "ll" flag is present */ + etByte done; /* Loop termination flag */ + etByte xtype = 0; /* Conversion paradigm */ + char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ + sqlite_uint64 longvalue; /* Value for integer types */ + LONGDOUBLE_TYPE realvalue; /* Value for real types */ + const et_info *infop; /* Pointer to the appropriate info structure */ + char *zOut; /* Rendering buffer */ + int nOut; /* Size of the rendering buffer */ + char *zExtra; /* Malloced memory used by some conversion */ +#ifndef SQLITE_OMIT_FLOATING_POINT + int exp, e2; /* exponent of real numbers */ + int nsd; /* Number of significant digits returned */ + double rounder; /* Used for rounding floating point values */ + etByte flag_dp; /* True if decimal point should be shown */ + etByte flag_rtz; /* True if trailing zeros should be removed */ +#endif + char buf[etBUFSIZE]; /* Conversion buffer */ + + bufpt = 0; + for(; (c=(*fmt))!=0; ++fmt){ + if( c!='%' ){ + int amt; + bufpt = (char *)fmt; + amt = 1; + while( (c=(*++fmt))!='%' && c!=0 ) amt++; + sqlite3StrAccumAppend(pAccum, bufpt, amt); + if( c==0 ) break; + } + if( (c=(*++fmt))==0 ){ + sqlite3StrAccumAppend(pAccum, "%", 1); + break; + } + /* Find out what flags are present */ + flag_leftjustify = flag_plussign = flag_blanksign = + flag_alternateform = flag_altform2 = flag_zeropad = 0; + done = 0; + do{ + switch( c ){ + case '-': flag_leftjustify = 1; break; + case '+': flag_plussign = 1; break; + case ' ': flag_blanksign = 1; break; + case '#': flag_alternateform = 1; break; + case '!': flag_altform2 = 1; break; + case '0': flag_zeropad = 1; break; + default: done = 1; break; + } + }while( !done && (c=(*++fmt))!=0 ); + /* Get the field width */ + width = 0; + if( c=='*' ){ + width = va_arg(ap,int); + if( width<0 ){ + flag_leftjustify = 1; + width = -width; + } + c = *++fmt; + }else{ + while( c>='0' && c<='9' ){ + width = width*10 + c - '0'; + c = *++fmt; + } + } + /* Get the precision */ + if( c=='.' ){ + precision = 0; + c = *++fmt; + if( c=='*' ){ + precision = va_arg(ap,int); + if( precision<0 ) precision = -precision; + c = *++fmt; + }else{ + while( c>='0' && c<='9' ){ + precision = precision*10 + c - '0'; + c = *++fmt; + } + } + }else{ + precision = -1; + } + /* Get the conversion type modifier */ + if( c=='l' ){ + flag_long = 1; + c = *++fmt; + if( c=='l' ){ + flag_longlong = 1; + c = *++fmt; + }else{ + flag_longlong = 0; + } + }else{ + flag_long = flag_longlong = 0; + } + /* Fetch the info entry for the field */ + infop = &fmtinfo[0]; + xtype = etINVALID; + for(idx=0; idxflags & FLAG_INTERN)==0 ){ + xtype = infop->type; + }else{ + return; + } + break; + } + } + zExtra = 0; + + /* + ** At this point, variables are initialized as follows: + ** + ** flag_alternateform TRUE if a '#' is present. + ** flag_altform2 TRUE if a '!' is present. + ** flag_plussign TRUE if a '+' is present. + ** flag_leftjustify TRUE if a '-' is present or if the + ** field width was negative. + ** flag_zeropad TRUE if the width began with 0. + ** flag_long TRUE if the letter 'l' (ell) prefixed + ** the conversion character. + ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed + ** the conversion character. + ** flag_blanksign TRUE if a ' ' is present. + ** width The specified field width. This is + ** always non-negative. Zero is the default. + ** precision The specified precision. The default + ** is -1. + ** xtype The class of the conversion. + ** infop Pointer to the appropriate info struct. + */ + switch( xtype ){ + case etPOINTER: + flag_longlong = sizeof(char*)==sizeof(i64); + flag_long = sizeof(char*)==sizeof(long int); + /* Fall through into the next case */ + case etORDINAL: + case etRADIX: + if( infop->flags & FLAG_SIGNED ){ + i64 v; + if( flag_longlong ){ + v = va_arg(ap,i64); + }else if( flag_long ){ + v = va_arg(ap,long int); + }else{ + v = va_arg(ap,int); + } + if( v<0 ){ + if( v==SMALLEST_INT64 ){ + longvalue = ((u64)1)<<63; + }else{ + longvalue = -v; + } + prefix = '-'; + }else{ + longvalue = v; + if( flag_plussign ) prefix = '+'; + else if( flag_blanksign ) prefix = ' '; + else prefix = 0; + } + }else{ + if( flag_longlong ){ + longvalue = va_arg(ap,u64); + }else if( flag_long ){ + longvalue = va_arg(ap,unsigned long int); + }else{ + longvalue = va_arg(ap,unsigned int); + } + prefix = 0; + } + if( longvalue==0 ) flag_alternateform = 0; + if( flag_zeropad && precisionaccError = STRACCUM_NOMEM; + return; + } + } + bufpt = &zOut[nOut-1]; + if( xtype==etORDINAL ){ + static const char zOrd[] = "thstndrd"; + int x = (int)(longvalue % 10); + if( x>=4 || (longvalue/10)%10==1 ){ + x = 0; + } + *(--bufpt) = zOrd[x*2+1]; + *(--bufpt) = zOrd[x*2]; + } + { + register const char *cset; /* Use registers for speed */ + register int base; + cset = &aDigits[infop->charset]; + base = infop->base; + do{ /* Convert to ascii */ + *(--bufpt) = cset[longvalue%base]; + longvalue = longvalue/base; + }while( longvalue>0 ); + } + length = (int)(&zOut[nOut-1]-bufpt); + for(idx=precision-length; idx>0; idx--){ + *(--bufpt) = '0'; /* Zero pad */ + } + if( prefix ) *(--bufpt) = prefix; /* Add sign */ + if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ + const char *pre; + char x; + pre = &aPrefix[infop->prefix]; + for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; + } + length = (int)(&zOut[nOut-1]-bufpt); + break; + case etFLOAT: + case etEXP: + case etGENERIC: + realvalue = va_arg(ap,double); +#ifdef SQLITE_OMIT_FLOATING_POINT + length = 0; +#else + if( precision<0 ) precision = 6; /* Set default precision */ + if( realvalue<0.0 ){ + realvalue = -realvalue; + prefix = '-'; + }else{ + if( flag_plussign ) prefix = '+'; + else if( flag_blanksign ) prefix = ' '; + else prefix = 0; + } + if( xtype==etGENERIC && precision>0 ) precision--; + for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){} + if( xtype==etFLOAT ) realvalue += rounder; + /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ + exp = 0; + if( sqlite3IsNaN((double)realvalue) ){ + bufpt = "NaN"; + length = 3; + break; + } + if( realvalue>0.0 ){ + LONGDOUBLE_TYPE scale = 1.0; + while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;} + while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; } + while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; } + while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; } + realvalue /= scale; + while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; } + while( realvalue<1.0 ){ realvalue *= 10.0; exp--; } + if( exp>350 ){ + if( prefix=='-' ){ + bufpt = "-Inf"; + }else if( prefix=='+' ){ + bufpt = "+Inf"; + }else{ + bufpt = "Inf"; + } + length = sqlite3Strlen30(bufpt); + break; + } + } + bufpt = buf; + /* + ** If the field type is etGENERIC, then convert to either etEXP + ** or etFLOAT, as appropriate. + */ + if( xtype!=etFLOAT ){ + realvalue += rounder; + if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; } + } + if( xtype==etGENERIC ){ + flag_rtz = !flag_alternateform; + if( exp<-4 || exp>precision ){ + xtype = etEXP; + }else{ + precision = precision - exp; + xtype = etFLOAT; + } + }else{ + flag_rtz = flag_altform2; + } + if( xtype==etEXP ){ + e2 = 0; + }else{ + e2 = exp; + } + if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){ + bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 ); + if( bufpt==0 ){ + pAccum->accError = STRACCUM_NOMEM; + return; + } + } + zOut = bufpt; + nsd = 16 + flag_altform2*10; + flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2; + /* The sign in front of the number */ + if( prefix ){ + *(bufpt++) = prefix; + } + /* Digits prior to the decimal point */ + if( e2<0 ){ + *(bufpt++) = '0'; + }else{ + for(; e2>=0; e2--){ + *(bufpt++) = et_getdigit(&realvalue,&nsd); + } + } + /* The decimal point */ + if( flag_dp ){ + *(bufpt++) = '.'; + } + /* "0" digits after the decimal point but before the first + ** significant digit of the number */ + for(e2++; e2<0; precision--, e2++){ + assert( precision>0 ); + *(bufpt++) = '0'; + } + /* Significant digits after the decimal point */ + while( (precision--)>0 ){ + *(bufpt++) = et_getdigit(&realvalue,&nsd); + } + /* Remove trailing zeros and the "." if no digits follow the "." */ + if( flag_rtz && flag_dp ){ + while( bufpt[-1]=='0' ) *(--bufpt) = 0; + assert( bufpt>zOut ); + if( bufpt[-1]=='.' ){ + if( flag_altform2 ){ + *(bufpt++) = '0'; + }else{ + *(--bufpt) = 0; + } + } + } + /* Add the "eNNN" suffix */ + if( xtype==etEXP ){ + *(bufpt++) = aDigits[infop->charset]; + if( exp<0 ){ + *(bufpt++) = '-'; exp = -exp; + }else{ + *(bufpt++) = '+'; + } + if( exp>=100 ){ + *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */ + exp %= 100; + } + *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */ + *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */ + } + *bufpt = 0; + + /* The converted number is in buf[] and zero terminated. Output it. + ** Note that the number is in the usual order, not reversed as with + ** integer conversions. */ + length = (int)(bufpt-zOut); + bufpt = zOut; + + /* Special case: Add leading zeros if the flag_zeropad flag is + ** set and we are not left justified */ + if( flag_zeropad && !flag_leftjustify && length < width){ + int i; + int nPad = width - length; + for(i=width; i>=nPad; i--){ + bufpt[i] = bufpt[i-nPad]; + } + i = prefix!=0; + while( nPad-- ) bufpt[i++] = '0'; + length = width; + } +#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */ + break; + case etSIZE: + *(va_arg(ap,int*)) = pAccum->nChar; + length = width = 0; + break; + case etPERCENT: + buf[0] = '%'; + bufpt = buf; + length = 1; + break; + case etCHARX: + c = va_arg(ap,int); + buf[0] = (char)c; + if( precision>=0 ){ + for(idx=1; idx=0 ){ + for(length=0; lengthetBUFSIZE ){ + bufpt = zExtra = sqlite3Malloc( n ); + if( bufpt==0 ){ + pAccum->accError = STRACCUM_NOMEM; + return; + } + }else{ + bufpt = buf; + } + j = 0; + if( needQuote ) bufpt[j++] = q; + k = i; + for(i=0; i=0 && precisionz, pToken->n); + } + length = width = 0; + break; + } + case etSRCLIST: { + SrcList *pSrc = va_arg(ap, SrcList*); + int k = va_arg(ap, int); + struct SrcList_item *pItem = &pSrc->a[k]; + assert( k>=0 && knSrc ); + if( pItem->zDatabase ){ + sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1); + sqlite3StrAccumAppend(pAccum, ".", 1); + } + sqlite3StrAccumAppend(pAccum, pItem->zName, -1); + length = width = 0; + break; + } + default: { + assert( xtype==etINVALID ); + return; + } + }/* End switch over the format type */ + /* + ** The text of the conversion is pointed to by "bufpt" and is + ** "length" characters long. The field width is "width". Do + ** the output. + */ + if( !flag_leftjustify ){ + register int nspace; + nspace = width-length; + if( nspace>0 ){ + sqlite3AppendSpace(pAccum, nspace); + } + } + if( length>0 ){ + sqlite3StrAccumAppend(pAccum, bufpt, length); + } + if( flag_leftjustify ){ + register int nspace; + nspace = width-length; + if( nspace>0 ){ + sqlite3AppendSpace(pAccum, nspace); + } + } + sqlite3_free(zExtra); + }/* End for loop over the format string */ +} /* End of function */ + +/* +** Append N bytes of text from z to the StrAccum object. +*/ +SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ + assert( z!=0 || N==0 ); + if( p->accError ){ + testcase(p->accError==STRACCUM_TOOBIG); + testcase(p->accError==STRACCUM_NOMEM); + return; + } + assert( p->zText!=0 || p->nChar==0 ); + if( N<=0 ){ + if( N==0 || z[0]==0 ) return; + N = sqlite3Strlen30(z); + } + if( p->nChar+N >= p->nAlloc ){ + char *zNew; + if( !p->useMalloc ){ + p->accError = STRACCUM_TOOBIG; + N = p->nAlloc - p->nChar - 1; + if( N<=0 ){ + return; + } + }else{ + char *zOld = (p->zText==p->zBase ? 0 : p->zText); + i64 szNew = p->nChar; + szNew += N + 1; + if( szNew > p->mxAlloc ){ + sqlite3StrAccumReset(p); + p->accError = STRACCUM_TOOBIG; + return; + }else{ + p->nAlloc = (int)szNew; + } + if( p->useMalloc==1 ){ + zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); + }else{ + zNew = sqlite3_realloc(zOld, p->nAlloc); + } + if( zNew ){ + if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); + p->zText = zNew; + }else{ + p->accError = STRACCUM_NOMEM; + sqlite3StrAccumReset(p); + return; + } + } + } + assert( p->zText ); + memcpy(&p->zText[p->nChar], z, N); + p->nChar += N; +} + +/* +** Finish off a string by making sure it is zero-terminated. +** Return a pointer to the resulting string. Return a NULL +** pointer if any kind of error was encountered. +*/ +SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){ + if( p->zText ){ + p->zText[p->nChar] = 0; + if( p->useMalloc && p->zText==p->zBase ){ + if( p->useMalloc==1 ){ + p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 ); + }else{ + p->zText = sqlite3_malloc(p->nChar+1); + } + if( p->zText ){ + memcpy(p->zText, p->zBase, p->nChar+1); + }else{ + p->accError = STRACCUM_NOMEM; + } + } + } + return p->zText; +} + +/* +** Reset an StrAccum string. Reclaim all malloced memory. +*/ +SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){ + if( p->zText!=p->zBase ){ + if( p->useMalloc==1 ){ + sqlite3DbFree(p->db, p->zText); + }else{ + sqlite3_free(p->zText); + } + } + p->zText = 0; +} + +/* +** Initialize a string accumulator +*/ +SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){ + p->zText = p->zBase = zBase; + p->db = 0; + p->nChar = 0; + p->nAlloc = n; + p->mxAlloc = mx; + p->useMalloc = 1; + p->accError = 0; +} + +/* +** Print into memory obtained from sqliteMalloc(). Use the internal +** %-conversion extensions. +*/ +SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){ + char *z; + char zBase[SQLITE_PRINT_BUF_SIZE]; + StrAccum acc; + assert( db!=0 ); + sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), + db->aLimit[SQLITE_LIMIT_LENGTH]); + acc.db = db; + sqlite3VXPrintf(&acc, 1, zFormat, ap); + z = sqlite3StrAccumFinish(&acc); + if( acc.accError==STRACCUM_NOMEM ){ + db->mallocFailed = 1; + } + return z; +} + +/* +** Print into memory obtained from sqliteMalloc(). Use the internal +** %-conversion extensions. +*/ +SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){ + va_list ap; + char *z; + va_start(ap, zFormat); + z = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + return z; +} + +/* +** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting +** the string and before returnning. This routine is intended to be used +** to modify an existing string. For example: +** +** x = sqlite3MPrintf(db, x, "prefix %s suffix", x); +** +*/ +SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){ + va_list ap; + char *z; + va_start(ap, zFormat); + z = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + sqlite3DbFree(db, zStr); + return z; +} + +/* +** Print into memory obtained from sqlite3_malloc(). Omit the internal +** %-conversion extensions. +*/ +SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){ + char *z; + char zBase[SQLITE_PRINT_BUF_SIZE]; + StrAccum acc; +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH); + acc.useMalloc = 2; + sqlite3VXPrintf(&acc, 0, zFormat, ap); + z = sqlite3StrAccumFinish(&acc); + return z; +} + +/* +** Print into memory obtained from sqlite3_malloc()(). Omit the internal +** %-conversion extensions. +*/ +SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){ + va_list ap; + char *z; +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + va_start(ap, zFormat); + z = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + return z; +} + +/* +** sqlite3_snprintf() works like snprintf() except that it ignores the +** current locale settings. This is important for SQLite because we +** are not able to use a "," as the decimal point in place of "." as +** specified by some locales. +** +** Oops: The first two arguments of sqlite3_snprintf() are backwards +** from the snprintf() standard. Unfortunately, it is too late to change +** this without breaking compatibility, so we just have to live with the +** mistake. +** +** sqlite3_vsnprintf() is the varargs version. +*/ +SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){ + StrAccum acc; + if( n<=0 ) return zBuf; + sqlite3StrAccumInit(&acc, zBuf, n, 0); + acc.useMalloc = 0; + sqlite3VXPrintf(&acc, 0, zFormat, ap); + return sqlite3StrAccumFinish(&acc); +} +SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ + char *z; + va_list ap; + va_start(ap,zFormat); + z = sqlite3_vsnprintf(n, zBuf, zFormat, ap); + va_end(ap); + return z; +} + +/* +** This is the routine that actually formats the sqlite3_log() message. +** We house it in a separate routine from sqlite3_log() to avoid using +** stack space on small-stack systems when logging is disabled. +** +** sqlite3_log() must render into a static buffer. It cannot dynamically +** allocate memory because it might be called while the memory allocator +** mutex is held. +*/ +static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ + StrAccum acc; /* String accumulator */ + char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ + + sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0); + acc.useMalloc = 0; + sqlite3VXPrintf(&acc, 0, zFormat, ap); + sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode, + sqlite3StrAccumFinish(&acc)); +} + +/* +** Format and write a message to the log if logging is enabled. +*/ +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){ + va_list ap; /* Vararg list */ + if( sqlite3GlobalConfig.xLog ){ + va_start(ap, zFormat); + renderLogMsg(iErrCode, zFormat, ap); + va_end(ap); + } +} + +#if defined(SQLITE_DEBUG) +/* +** A version of printf() that understands %lld. Used for debugging. +** The printf() built into some versions of windows does not understand %lld +** and segfaults if you give it a long long int. +*/ +SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){ + va_list ap; + StrAccum acc; + char zBuf[500]; + sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0); + acc.useMalloc = 0; + va_start(ap,zFormat); + sqlite3VXPrintf(&acc, 0, zFormat, ap); + va_end(ap); + sqlite3StrAccumFinish(&acc); + fprintf(stdout,"%s", zBuf); + fflush(stdout); +} +#endif + +#ifndef SQLITE_OMIT_TRACE +/* +** variable-argument wrapper around sqlite3VXPrintf(). +*/ +SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){ + va_list ap; + va_start(ap,zFormat); + sqlite3VXPrintf(p, 1, zFormat, ap); + va_end(ap); +} +#endif + +/************** End of printf.c **********************************************/ +/************** Begin file random.c ******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code to implement a pseudo-random number +** generator (PRNG) for SQLite. +** +** Random numbers are used by some of the database backends in order +** to generate random integer keys for tables or random filenames. +*/ + + +/* All threads share a single random number generator. +** This structure is the current state of the generator. +*/ +static SQLITE_WSD struct sqlite3PrngType { + unsigned char isInit; /* True if initialized */ + unsigned char i, j; /* State variables */ + unsigned char s[256]; /* State variables */ +} sqlite3Prng; + +/* +** Return N random bytes. +*/ +SQLITE_API void sqlite3_randomness(int N, void *pBuf){ + unsigned char t; + unsigned char *zBuf = pBuf; + + /* The "wsdPrng" macro will resolve to the pseudo-random number generator + ** state vector. If writable static data is unsupported on the target, + ** we have to locate the state vector at run-time. In the more common + ** case where writable static data is supported, wsdPrng can refer directly + ** to the "sqlite3Prng" state vector declared above. + */ +#ifdef SQLITE_OMIT_WSD + struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); +# define wsdPrng p[0] +#else +# define wsdPrng sqlite3Prng +#endif + +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); + sqlite3_mutex_enter(mutex); +#endif + + /* Initialize the state of the random number generator once, + ** the first time this routine is called. The seed value does + ** not need to contain a lot of randomness since we are not + ** trying to do secure encryption or anything like that... + ** + ** Nothing in this file or anywhere else in SQLite does any kind of + ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random + ** number generator) not as an encryption device. + */ + if( !wsdPrng.isInit ){ + int i; + char k[256]; + wsdPrng.j = 0; + wsdPrng.i = 0; + sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k); + for(i=0; i<256; i++){ + wsdPrng.s[i] = (u8)i; + } + for(i=0; i<256; i++){ + wsdPrng.j += wsdPrng.s[i] + k[i]; + t = wsdPrng.s[wsdPrng.j]; + wsdPrng.s[wsdPrng.j] = wsdPrng.s[i]; + wsdPrng.s[i] = t; + } + wsdPrng.isInit = 1; + } + + while( N-- ){ + wsdPrng.i++; + t = wsdPrng.s[wsdPrng.i]; + wsdPrng.j += t; + wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j]; + wsdPrng.s[wsdPrng.j] = t; + t += wsdPrng.s[wsdPrng.i]; + *(zBuf++) = wsdPrng.s[t]; + } + sqlite3_mutex_leave(mutex); +} + +#ifndef SQLITE_OMIT_BUILTIN_TEST +/* +** For testing purposes, we sometimes want to preserve the state of +** PRNG and restore the PRNG to its saved state at a later time, or +** to reset the PRNG to its initial state. These routines accomplish +** those tasks. +** +** The sqlite3_test_control() interface calls these routines to +** control the PRNG. +*/ +static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng; +SQLITE_PRIVATE void sqlite3PrngSaveState(void){ + memcpy( + &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), + &GLOBAL(struct sqlite3PrngType, sqlite3Prng), + sizeof(sqlite3Prng) + ); +} +SQLITE_PRIVATE void sqlite3PrngRestoreState(void){ + memcpy( + &GLOBAL(struct sqlite3PrngType, sqlite3Prng), + &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), + sizeof(sqlite3Prng) + ); +} +SQLITE_PRIVATE void sqlite3PrngResetState(void){ + GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0; +} +#endif /* SQLITE_OMIT_BUILTIN_TEST */ + +/************** End of random.c **********************************************/ +/************** Begin file utf.c *********************************************/ +/* +** 2004 April 13 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains routines used to translate between UTF-8, +** UTF-16, UTF-16BE, and UTF-16LE. +** +** Notes on UTF-8: +** +** Byte-0 Byte-1 Byte-2 Byte-3 Value +** 0xxxxxxx 00000000 00000000 0xxxxxxx +** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx +** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx +** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx +** +** +** Notes on UTF-16: (with wwww+1==uuuuu) +** +** Word-0 Word-1 Value +** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx +** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx +** +** +** BOM or Byte Order Mark: +** 0xff 0xfe little-endian utf-16 follows +** 0xfe 0xff big-endian utf-16 follows +** +*/ +/* #include */ + +#ifndef SQLITE_AMALGAMATION +/* +** The following constant value is used by the SQLITE_BIGENDIAN and +** SQLITE_LITTLEENDIAN macros. +*/ +SQLITE_PRIVATE const int sqlite3one = 1; +#endif /* SQLITE_AMALGAMATION */ + +/* +** This lookup table is used to help decode the first byte of +** a multi-byte UTF8 character. +*/ +static const unsigned char sqlite3Utf8Trans1[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, +}; + + +#define WRITE_UTF8(zOut, c) { \ + if( c<0x00080 ){ \ + *zOut++ = (u8)(c&0xFF); \ + } \ + else if( c<0x00800 ){ \ + *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ + else if( c<0x10000 ){ \ + *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + }else{ \ + *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ + *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ +} + +#define WRITE_UTF16LE(zOut, c) { \ + if( c<=0xFFFF ){ \ + *zOut++ = (u8)(c&0x00FF); \ + *zOut++ = (u8)((c>>8)&0x00FF); \ + }else{ \ + *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ + *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ + *zOut++ = (u8)(c&0x00FF); \ + *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ + } \ +} + +#define WRITE_UTF16BE(zOut, c) { \ + if( c<=0xFFFF ){ \ + *zOut++ = (u8)((c>>8)&0x00FF); \ + *zOut++ = (u8)(c&0x00FF); \ + }else{ \ + *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ + *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ + *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ + *zOut++ = (u8)(c&0x00FF); \ + } \ +} + +#define READ_UTF16LE(zIn, TERM, c){ \ + c = (*zIn++); \ + c += ((*zIn++)<<8); \ + if( c>=0xD800 && c<0xE000 && TERM ){ \ + int c2 = (*zIn++); \ + c2 += ((*zIn++)<<8); \ + c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ + } \ +} + +#define READ_UTF16BE(zIn, TERM, c){ \ + c = ((*zIn++)<<8); \ + c += (*zIn++); \ + if( c>=0xD800 && c<0xE000 && TERM ){ \ + int c2 = ((*zIn++)<<8); \ + c2 += (*zIn++); \ + c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ + } \ +} + +/* +** Translate a single UTF-8 character. Return the unicode value. +** +** During translation, assume that the byte that zTerm points +** is a 0x00. +** +** Write a pointer to the next unread byte back into *pzNext. +** +** Notes On Invalid UTF-8: +** +** * This routine never allows a 7-bit character (0x00 through 0x7f) to +** be encoded as a multi-byte character. Any multi-byte character that +** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. +** +** * This routine never allows a UTF16 surrogate value to be encoded. +** If a multi-byte character attempts to encode a value between +** 0xd800 and 0xe000 then it is rendered as 0xfffd. +** +** * Bytes in the range of 0x80 through 0xbf which occur as the first +** byte of a character are interpreted as single-byte characters +** and rendered as themselves even though they are technically +** invalid characters. +** +** * This routine accepts an infinite number of different UTF8 encodings +** for unicode values 0x80 and greater. It do not change over-length +** encodings to 0xfffd as some systems recommend. +*/ +#define READ_UTF8(zIn, zTerm, c) \ + c = *(zIn++); \ + if( c>=0xc0 ){ \ + c = sqlite3Utf8Trans1[c-0xc0]; \ + while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ + c = (c<<6) + (0x3f & *(zIn++)); \ + } \ + if( c<0x80 \ + || (c&0xFFFFF800)==0xD800 \ + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ + } +SQLITE_PRIVATE u32 sqlite3Utf8Read( + const unsigned char **pz /* Pointer to string from which to read char */ +){ + unsigned int c; + + /* Same as READ_UTF8() above but without the zTerm parameter. + ** For this routine, we assume the UTF8 string is always zero-terminated. + */ + c = *((*pz)++); + if( c>=0xc0 ){ + c = sqlite3Utf8Trans1[c-0xc0]; + while( (*(*pz) & 0xc0)==0x80 ){ + c = (c<<6) + (0x3f & *((*pz)++)); + } + if( c<0x80 + || (c&0xFFFFF800)==0xD800 + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } + } + return c; +} + + + + +/* +** If the TRANSLATE_TRACE macro is defined, the value of each Mem is +** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). +*/ +/* #define TRANSLATE_TRACE 1 */ + +#ifndef SQLITE_OMIT_UTF16 +/* +** This routine transforms the internal text encoding used by pMem to +** desiredEnc. It is an error if the string is already of the desired +** encoding, or if *pMem does not contain a string value. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){ + int len; /* Maximum length of output string in bytes */ + unsigned char *zOut; /* Output buffer */ + unsigned char *zIn; /* Input iterator */ + unsigned char *zTerm; /* End of input */ + unsigned char *z; /* Output iterator */ + unsigned int c; + + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( pMem->flags&MEM_Str ); + assert( pMem->enc!=desiredEnc ); + assert( pMem->enc!=0 ); + assert( pMem->n>=0 ); + +#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) + { + char zBuf[100]; + sqlite3VdbeMemPrettyPrint(pMem, zBuf); + fprintf(stderr, "INPUT: %s\n", zBuf); + } +#endif + + /* If the translation is between UTF-16 little and big endian, then + ** all that is required is to swap the byte order. This case is handled + ** differently from the others. + */ + if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ + u8 temp; + int rc; + rc = sqlite3VdbeMemMakeWriteable(pMem); + if( rc!=SQLITE_OK ){ + assert( rc==SQLITE_NOMEM ); + return SQLITE_NOMEM; + } + zIn = (u8*)pMem->z; + zTerm = &zIn[pMem->n&~1]; + while( zInenc = desiredEnc; + goto translate_out; + } + + /* Set len to the maximum number of bytes required in the output buffer. */ + if( desiredEnc==SQLITE_UTF8 ){ + /* When converting from UTF-16, the maximum growth results from + ** translating a 2-byte character to a 4-byte UTF-8 character. + ** A single byte is required for the output string + ** nul-terminator. + */ + pMem->n &= ~1; + len = pMem->n * 2 + 1; + }else{ + /* When converting from UTF-8 to UTF-16 the maximum growth is caused + ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 + ** character. Two bytes are required in the output buffer for the + ** nul-terminator. + */ + len = pMem->n * 2 + 2; + } + + /* Set zIn to point at the start of the input buffer and zTerm to point 1 + ** byte past the end. + ** + ** Variable zOut is set to point at the output buffer, space obtained + ** from sqlite3_malloc(). + */ + zIn = (u8*)pMem->z; + zTerm = &zIn[pMem->n]; + zOut = sqlite3DbMallocRaw(pMem->db, len); + if( !zOut ){ + return SQLITE_NOMEM; + } + z = zOut; + + if( pMem->enc==SQLITE_UTF8 ){ + if( desiredEnc==SQLITE_UTF16LE ){ + /* UTF-8 -> UTF-16 Little-endian */ + while( zIn UTF-16 Big-endian */ + while( zInn = (int)(z - zOut); + *z++ = 0; + }else{ + assert( desiredEnc==SQLITE_UTF8 ); + if( pMem->enc==SQLITE_UTF16LE ){ + /* UTF-16 Little-endian -> UTF-8 */ + while( zIn UTF-8 */ + while( zInn = (int)(z - zOut); + } + *z = 0; + assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); + + sqlite3VdbeMemRelease(pMem); + pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem); + pMem->enc = desiredEnc; + pMem->flags |= (MEM_Term|MEM_Dyn); + pMem->z = (char*)zOut; + pMem->zMalloc = pMem->z; + +translate_out: +#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) + { + char zBuf[100]; + sqlite3VdbeMemPrettyPrint(pMem, zBuf); + fprintf(stderr, "OUTPUT: %s\n", zBuf); + } +#endif + return SQLITE_OK; +} + +/* +** This routine checks for a byte-order mark at the beginning of the +** UTF-16 string stored in *pMem. If one is present, it is removed and +** the encoding of the Mem adjusted. This routine does not do any +** byte-swapping, it just sets Mem.enc appropriately. +** +** The allocation (static, dynamic etc.) and encoding of the Mem may be +** changed by this function. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){ + int rc = SQLITE_OK; + u8 bom = 0; + + assert( pMem->n>=0 ); + if( pMem->n>1 ){ + u8 b1 = *(u8 *)pMem->z; + u8 b2 = *(((u8 *)pMem->z) + 1); + if( b1==0xFE && b2==0xFF ){ + bom = SQLITE_UTF16BE; + } + if( b1==0xFF && b2==0xFE ){ + bom = SQLITE_UTF16LE; + } + } + + if( bom ){ + rc = sqlite3VdbeMemMakeWriteable(pMem); + if( rc==SQLITE_OK ){ + pMem->n -= 2; + memmove(pMem->z, &pMem->z[2], pMem->n); + pMem->z[pMem->n] = '\0'; + pMem->z[pMem->n+1] = '\0'; + pMem->flags |= MEM_Term; + pMem->enc = bom; + } + } + return rc; +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, +** return the number of unicode characters in pZ up to (but not including) +** the first 0x00 byte. If nByte is not less than zero, return the +** number of unicode characters in the first nByte of pZ (or up to +** the first 0x00, whichever comes first). +*/ +SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){ + int r = 0; + const u8 *z = (const u8*)zIn; + const u8 *zTerm; + if( nByte>=0 ){ + zTerm = &z[nByte]; + }else{ + zTerm = (const u8*)(-1); + } + assert( z<=zTerm ); + while( *z!=0 && zmallocFailed ){ + sqlite3VdbeMemRelease(&m); + m.z = 0; + } + assert( (m.flags & MEM_Term)!=0 || db->mallocFailed ); + assert( (m.flags & MEM_Str)!=0 || db->mallocFailed ); + assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed ); + assert( m.z || db->mallocFailed ); + return m.z; +} + +/* +** zIn is a UTF-16 encoded unicode string at least nChar characters long. +** Return the number of bytes in the first nChar unicode characters +** in pZ. nChar must be non-negative. +*/ +SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){ + int c; + unsigned char const *z = zIn; + int n = 0; + + if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){ + while( n0 && n<=4 ); + z[0] = 0; + z = zBuf; + c = sqlite3Utf8Read((const u8**)&z); + t = i; + if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; + if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; + assert( c==t ); + assert( (z-zBuf)==n ); + } + for(i=0; i<0x00110000; i++){ + if( i>=0xD800 && i<0xE000 ) continue; + z = zBuf; + WRITE_UTF16LE(z, i); + n = (int)(z-zBuf); + assert( n>0 && n<=4 ); + z[0] = 0; + z = zBuf; + READ_UTF16LE(z, 1, c); + assert( c==i ); + assert( (z-zBuf)==n ); + } + for(i=0; i<0x00110000; i++){ + if( i>=0xD800 && i<0xE000 ) continue; + z = zBuf; + WRITE_UTF16BE(z, i); + n = (int)(z-zBuf); + assert( n>0 && n<=4 ); + z[0] = 0; + z = zBuf; + READ_UTF16BE(z, 1, c); + assert( c==i ); + assert( (z-zBuf)==n ); + } +} +#endif /* SQLITE_TEST */ +#endif /* SQLITE_OMIT_UTF16 */ + +/************** End of utf.c *************************************************/ +/************** Begin file util.c ********************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Utility functions used throughout sqlite. +** +** This file contains functions for allocating memory, comparing +** strings, and stuff like that. +** +*/ +/* #include */ +#ifdef SQLITE_HAVE_ISNAN +# include +#endif + +/* +** Routine needed to support the testcase() macro. +*/ +#ifdef SQLITE_COVERAGE_TEST +SQLITE_PRIVATE void sqlite3Coverage(int x){ + static unsigned dummy = 0; + dummy += (unsigned)x; +} +#endif + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* +** Return true if the floating point value is Not a Number (NaN). +** +** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN. +** Otherwise, we have our own implementation that works on most systems. +*/ +SQLITE_PRIVATE int sqlite3IsNaN(double x){ + int rc; /* The value return */ +#if !defined(SQLITE_HAVE_ISNAN) + /* + ** Systems that support the isnan() library function should probably + ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have + ** found that many systems do not have a working isnan() function so + ** this implementation is provided as an alternative. + ** + ** This NaN test sometimes fails if compiled on GCC with -ffast-math. + ** On the other hand, the use of -ffast-math comes with the following + ** warning: + ** + ** This option [-ffast-math] should never be turned on by any + ** -O option since it can result in incorrect output for programs + ** which depend on an exact implementation of IEEE or ISO + ** rules/specifications for math functions. + ** + ** Under MSVC, this NaN test may fail if compiled with a floating- + ** point precision mode other than /fp:precise. From the MSDN + ** documentation: + ** + ** The compiler [with /fp:precise] will properly handle comparisons + ** involving NaN. For example, x != x evaluates to true if x is NaN + ** ... + */ +#ifdef __FAST_MATH__ +# error SQLite will not work correctly with the -ffast-math option of GCC. +#endif + volatile double y = x; + volatile double z = y; + rc = (y!=z); +#else /* if defined(SQLITE_HAVE_ISNAN) */ + rc = isnan(x); +#endif /* SQLITE_HAVE_ISNAN */ + testcase( rc ); + return rc; +} +#endif /* SQLITE_OMIT_FLOATING_POINT */ + +/* +** Compute a string length that is limited to what can be stored in +** lower 30 bits of a 32-bit signed integer. +** +** The value returned will never be negative. Nor will it ever be greater +** than the actual length of the string. For very long strings (greater +** than 1GiB) the value returned might be less than the true string length. +*/ +SQLITE_PRIVATE int sqlite3Strlen30(const char *z){ + const char *z2 = z; + if( z==0 ) return 0; + while( *z2 ){ z2++; } + return 0x3fffffff & (int)(z2 - z); +} + +/* +** Set the most recent error code and error string for the sqlite +** handle "db". The error code is set to "err_code". +** +** If it is not NULL, string zFormat specifies the format of the +** error string in the style of the printf functions: The following +** format characters are allowed: +** +** %s Insert a string +** %z A string that should be freed after use +** %d Insert an integer +** %T Insert a token +** %S Insert the first element of a SrcList +** +** zFormat and any string tokens that follow it are assumed to be +** encoded in UTF-8. +** +** To clear the most recent error for sqlite handle "db", sqlite3Error +** should be called with err_code set to SQLITE_OK and zFormat set +** to NULL. +*/ +SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){ + if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){ + db->errCode = err_code; + if( zFormat ){ + char *z; + va_list ap; + va_start(ap, zFormat); + z = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC); + }else{ + sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC); + } + } +} + +/* +** Add an error message to pParse->zErrMsg and increment pParse->nErr. +** The following formatting characters are allowed: +** +** %s Insert a string +** %z A string that should be freed after use +** %d Insert an integer +** %T Insert a token +** %S Insert the first element of a SrcList +** +** This function should be used to report any error that occurs whilst +** compiling an SQL statement (i.e. within sqlite3_prepare()). The +** last thing the sqlite3_prepare() function does is copy the error +** stored by this function into the database handle using sqlite3Error(). +** Function sqlite3Error() should be used during statement execution +** (sqlite3_step() etc.). +*/ +SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ + char *zMsg; + va_list ap; + sqlite3 *db = pParse->db; + va_start(ap, zFormat); + zMsg = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + if( db->suppressErr ){ + sqlite3DbFree(db, zMsg); + }else{ + pParse->nErr++; + sqlite3DbFree(db, pParse->zErrMsg); + pParse->zErrMsg = zMsg; + pParse->rc = SQLITE_ERROR; + } +} + +/* +** Convert an SQL-style quoted string into a normal string by removing +** the quote characters. The conversion is done in-place. If the +** input does not begin with a quote character, then this routine +** is a no-op. +** +** The input string must be zero-terminated. A new zero-terminator +** is added to the dequoted string. +** +** The return value is -1 if no dequoting occurs or the length of the +** dequoted string, exclusive of the zero terminator, if dequoting does +** occur. +** +** 2002-Feb-14: This routine is extended to remove MS-Access style +** brackets from around identifers. For example: "[a-b-c]" becomes +** "a-b-c". +*/ +SQLITE_PRIVATE int sqlite3Dequote(char *z){ + char quote; + int i, j; + if( z==0 ) return -1; + quote = z[0]; + switch( quote ){ + case '\'': break; + case '"': break; + case '`': break; /* For MySQL compatibility */ + case '[': quote = ']'; break; /* For MS SqlServer compatibility */ + default: return -1; + } + for(i=1, j=0;; i++){ + assert( z[i] ); + if( z[i]==quote ){ + if( z[i+1]==quote ){ + z[j++] = quote; + i++; + }else{ + break; + } + }else{ + z[j++] = z[i]; + } + } + z[j] = 0; + return j; +} + +/* Convenient short-hand */ +#define UpperToLower sqlite3UpperToLower + +/* +** Some systems have stricmp(). Others have strcasecmp(). Because +** there is no consistency, we will define our own. +** +** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and +** sqlite3_strnicmp() APIs allow applications and extensions to compare +** the contents of two buffers containing UTF-8 strings in a +** case-independent fashion, using the same definition of "case +** independence" that SQLite uses internally when comparing identifiers. +*/ +SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){ + register unsigned char *a, *b; + a = (unsigned char *)zLeft; + b = (unsigned char *)zRight; + while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; } + return UpperToLower[*a] - UpperToLower[*b]; +} +SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ + register unsigned char *a, *b; + a = (unsigned char *)zLeft; + b = (unsigned char *)zRight; + while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; } + return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b]; +} + +/* +** The string z[] is an text representation of a real number. +** Convert this string to a double and write it into *pResult. +** +** The string z[] is length bytes in length (bytes, not characters) and +** uses the encoding enc. The string is not necessarily zero-terminated. +** +** Return TRUE if the result is a valid real number (or integer) and FALSE +** if the string is empty or contains extraneous text. Valid numbers +** are in one of these formats: +** +** [+-]digits[E[+-]digits] +** [+-]digits.[digits][E[+-]digits] +** [+-].digits[E[+-]digits] +** +** Leading and trailing whitespace is ignored for the purpose of determining +** validity. +** +** If some prefix of the input string is a valid number, this routine +** returns FALSE but it still converts the prefix and writes the result +** into *pResult. +*/ +SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ +#ifndef SQLITE_OMIT_FLOATING_POINT + int incr; + const char *zEnd = z + length; + /* sign * significand * (10 ^ (esign * exponent)) */ + int sign = 1; /* sign of significand */ + i64 s = 0; /* significand */ + int d = 0; /* adjust exponent for shifting decimal point */ + int esign = 1; /* sign of exponent */ + int e = 0; /* exponent */ + int eValid = 1; /* True exponent is either not used or is well-formed */ + double result; + int nDigits = 0; + int nonNum = 0; + + assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); + *pResult = 0.0; /* Default return value, in case of an error */ + + if( enc==SQLITE_UTF8 ){ + incr = 1; + }else{ + int i; + incr = 2; + assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); + for(i=3-enc; i=zEnd ) return 0; + + /* get sign of significand */ + if( *z=='-' ){ + sign = -1; + z+=incr; + }else if( *z=='+' ){ + z+=incr; + } + + /* skip leading zeroes */ + while( z=zEnd ) goto do_atof_calc; + + /* if decimal point is present */ + if( *z=='.' ){ + z+=incr; + /* copy digits from after decimal to significand + ** (decrease exponent by d to shift decimal right) */ + while( z=zEnd ) goto do_atof_calc; + + /* if exponent is present */ + if( *z=='e' || *z=='E' ){ + z+=incr; + eValid = 0; + if( z>=zEnd ) goto do_atof_calc; + /* get sign of exponent */ + if( *z=='-' ){ + esign = -1; + z+=incr; + }else if( *z=='+' ){ + z+=incr; + } + /* copy digits to exponent */ + while( z0 ){ + while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10; + }else{ + while( !(s%10) && e>0 ) e--,s/=10; + } + + /* adjust the sign of significand */ + s = sign<0 ? -s : s; + + /* if exponent, scale significand as appropriate + ** and store in result. */ + if( e ){ + LONGDOUBLE_TYPE scale = 1.0; + /* attempt to handle extremely small/large numbers better */ + if( e>307 && e<342 ){ + while( e%308 ) { scale *= 1.0e+1; e -= 1; } + if( esign<0 ){ + result = s / scale; + result /= 1.0e+308; + }else{ + result = s * scale; + result *= 1.0e+308; + } + }else if( e>=342 ){ + if( esign<0 ){ + result = 0.0*s; + }else{ + result = 1e308*1e308*s; /* Infinity */ + } + }else{ + /* 1.0e+22 is the largest power of 10 than can be + ** represented exactly. */ + while( e%22 ) { scale *= 1.0e+1; e -= 1; } + while( e>0 ) { scale *= 1.0e+22; e -= 22; } + if( esign<0 ){ + result = s / scale; + }else{ + result = s * scale; + } + } + } else { + result = (double)s; + } + } + + /* store the result */ + *pResult = result; + + /* return true if number and no extra non-whitespace chracters after */ + return z>=zEnd && nDigits>0 && eValid && nonNum==0; +#else + return !sqlite3Atoi64(z, pResult, length, enc); +#endif /* SQLITE_OMIT_FLOATING_POINT */ +} + +/* +** Compare the 19-character string zNum against the text representation +** value 2^63: 9223372036854775808. Return negative, zero, or positive +** if zNum is less than, equal to, or greater than the string. +** Note that zNum must contain exactly 19 characters. +** +** Unlike memcmp() this routine is guaranteed to return the difference +** in the values of the last digit if the only difference is in the +** last digit. So, for example, +** +** compare2pow63("9223372036854775800", 1) +** +** will return -8. +*/ +static int compare2pow63(const char *zNum, int incr){ + int c = 0; + int i; + /* 012345678901234567 */ + const char *pow63 = "922337203685477580"; + for(i=0; c==0 && i<18; i++){ + c = (zNum[i*incr]-pow63[i])*10; + } + if( c==0 ){ + c = zNum[18*incr] - '8'; + testcase( c==(-1) ); + testcase( c==0 ); + testcase( c==(+1) ); + } + return c; +} + + +/* +** Convert zNum to a 64-bit signed integer. +** +** If the zNum value is representable as a 64-bit twos-complement +** integer, then write that value into *pNum and return 0. +** +** If zNum is exactly 9223372036854665808, return 2. This special +** case is broken out because while 9223372036854665808 cannot be a +** signed 64-bit integer, its negative -9223372036854665808 can be. +** +** If zNum is too big for a 64-bit integer and is not +** 9223372036854665808 or if zNum contains any non-numeric text, +** then return 1. +** +** length is the number of bytes in the string (bytes, not characters). +** The string is not necessarily zero-terminated. The encoding is +** given by enc. +*/ +SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){ + int incr; + u64 u = 0; + int neg = 0; /* assume positive */ + int i; + int c = 0; + int nonNum = 0; + const char *zStart; + const char *zEnd = zNum + length; + assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); + if( enc==SQLITE_UTF8 ){ + incr = 1; + }else{ + incr = 2; + assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); + for(i=3-enc; i='0' && c<='9'; i+=incr){ + u = u*10 + c - '0'; + } + if( u>LARGEST_INT64 ){ + *pNum = SMALLEST_INT64; + }else if( neg ){ + *pNum = -(i64)u; + }else{ + *pNum = (i64)u; + } + testcase( i==18 ); + testcase( i==19 ); + testcase( i==20 ); + if( (c!=0 && &zNum[i]19*incr || nonNum ){ + /* zNum is empty or contains non-numeric text or is longer + ** than 19 digits (thus guaranteeing that it is too large) */ + return 1; + }else if( i<19*incr ){ + /* Less than 19 digits, so we know that it fits in 64 bits */ + assert( u<=LARGEST_INT64 ); + return 0; + }else{ + /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ + c = compare2pow63(zNum, incr); + if( c<0 ){ + /* zNum is less than 9223372036854775808 so it fits */ + assert( u<=LARGEST_INT64 ); + return 0; + }else if( c>0 ){ + /* zNum is greater than 9223372036854775808 so it overflows */ + return 1; + }else{ + /* zNum is exactly 9223372036854775808. Fits if negative. The + ** special case 2 overflow if positive */ + assert( u-1==LARGEST_INT64 ); + assert( (*pNum)==SMALLEST_INT64 ); + return neg ? 0 : 2; + } + } +} + +/* +** If zNum represents an integer that will fit in 32-bits, then set +** *pValue to that integer and return true. Otherwise return false. +** +** Any non-numeric characters that following zNum are ignored. +** This is different from sqlite3Atoi64() which requires the +** input number to be zero-terminated. +*/ +SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){ + sqlite_int64 v = 0; + int i, c; + int neg = 0; + if( zNum[0]=='-' ){ + neg = 1; + zNum++; + }else if( zNum[0]=='+' ){ + zNum++; + } + while( zNum[0]=='0' ) zNum++; + for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){ + v = v*10 + c; + } + + /* The longest decimal representation of a 32 bit integer is 10 digits: + ** + ** 1234567890 + ** 2^31 -> 2147483648 + */ + testcase( i==10 ); + if( i>10 ){ + return 0; + } + testcase( v-neg==2147483647 ); + if( v-neg>2147483647 ){ + return 0; + } + if( neg ){ + v = -v; + } + *pValue = (int)v; + return 1; +} + +/* +** Return a 32-bit integer value extracted from a string. If the +** string is not an integer, just return 0. +*/ +SQLITE_PRIVATE int sqlite3Atoi(const char *z){ + int x = 0; + if( z ) sqlite3GetInt32(z, &x); + return x; +} + +/* +** The variable-length integer encoding is as follows: +** +** KEY: +** A = 0xxxxxxx 7 bits of data and one flag bit +** B = 1xxxxxxx 7 bits of data and one flag bit +** C = xxxxxxxx 8 bits of data +** +** 7 bits - A +** 14 bits - BA +** 21 bits - BBA +** 28 bits - BBBA +** 35 bits - BBBBA +** 42 bits - BBBBBA +** 49 bits - BBBBBBA +** 56 bits - BBBBBBBA +** 64 bits - BBBBBBBBC +*/ + +/* +** Write a 64-bit variable-length integer to memory starting at p[0]. +** The length of data write will be between 1 and 9 bytes. The number +** of bytes written is returned. +** +** A variable-length integer consists of the lower 7 bits of each byte +** for all bytes that have the 8th bit set and one byte with the 8th +** bit clear. Except, if we get to the 9th byte, it stores the full +** 8 bits and is the last byte. +*/ +SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){ + int i, j, n; + u8 buf[10]; + if( v & (((u64)0xff000000)<<32) ){ + p[8] = (u8)v; + v >>= 8; + for(i=7; i>=0; i--){ + p[i] = (u8)((v & 0x7f) | 0x80); + v >>= 7; + } + return 9; + } + n = 0; + do{ + buf[n++] = (u8)((v & 0x7f) | 0x80); + v >>= 7; + }while( v!=0 ); + buf[0] &= 0x7f; + assert( n<=9 ); + for(i=0, j=n-1; j>=0; j--, i++){ + p[i] = buf[j]; + } + return n; +} + +/* +** This routine is a faster version of sqlite3PutVarint() that only +** works for 32-bit positive integers and which is optimized for +** the common case of small integers. A MACRO version, putVarint32, +** is provided which inlines the single-byte case. All code should use +** the MACRO version as this function assumes the single-byte case has +** already been handled. +*/ +SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){ +#ifndef putVarint32 + if( (v & ~0x7f)==0 ){ + p[0] = v; + return 1; + } +#endif + if( (v & ~0x3fff)==0 ){ + p[0] = (u8)((v>>7) | 0x80); + p[1] = (u8)(v & 0x7f); + return 2; + } + return sqlite3PutVarint(p, v); +} + +/* +** Bitmasks used by sqlite3GetVarint(). These precomputed constants +** are defined here rather than simply putting the constant expressions +** inline in order to work around bugs in the RVT compiler. +** +** SLOT_2_0 A mask for (0x7f<<14) | 0x7f +** +** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0 +*/ +#define SLOT_2_0 0x001fc07f +#define SLOT_4_2_0 0xf01fc07f + + +/* +** Read a 64-bit variable-length integer from memory starting at p[0]. +** Return the number of bytes read. The value is stored in *v. +*/ +SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ + u32 a,b,s; + + a = *p; + /* a: p0 (unmasked) */ + if (!(a&0x80)) + { + *v = a; + return 1; + } + + p++; + b = *p; + /* b: p1 (unmasked) */ + if (!(b&0x80)) + { + a &= 0x7f; + a = a<<7; + a |= b; + *v = a; + return 2; + } + + /* Verify that constants are precomputed correctly */ + assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) ); + assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) ); + + p++; + a = a<<14; + a |= *p; + /* a: p0<<14 | p2 (unmasked) */ + if (!(a&0x80)) + { + a &= SLOT_2_0; + b &= 0x7f; + b = b<<7; + a |= b; + *v = a; + return 3; + } + + /* CSE1 from below */ + a &= SLOT_2_0; + p++; + b = b<<14; + b |= *p; + /* b: p1<<14 | p3 (unmasked) */ + if (!(b&0x80)) + { + b &= SLOT_2_0; + /* moved CSE1 up */ + /* a &= (0x7f<<14)|(0x7f); */ + a = a<<7; + a |= b; + *v = a; + return 4; + } + + /* a: p0<<14 | p2 (masked) */ + /* b: p1<<14 | p3 (unmasked) */ + /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ + /* moved CSE1 up */ + /* a &= (0x7f<<14)|(0x7f); */ + b &= SLOT_2_0; + s = a; + /* s: p0<<14 | p2 (masked) */ + + p++; + a = a<<14; + a |= *p; + /* a: p0<<28 | p2<<14 | p4 (unmasked) */ + if (!(a&0x80)) + { + /* we can skip these cause they were (effectively) done above in calc'ing s */ + /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ + /* b &= (0x7f<<14)|(0x7f); */ + b = b<<7; + a |= b; + s = s>>18; + *v = ((u64)s)<<32 | a; + return 5; + } + + /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ + s = s<<7; + s |= b; + /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ + + p++; + b = b<<14; + b |= *p; + /* b: p1<<28 | p3<<14 | p5 (unmasked) */ + if (!(b&0x80)) + { + /* we can skip this cause it was (effectively) done above in calc'ing s */ + /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ + a &= SLOT_2_0; + a = a<<7; + a |= b; + s = s>>18; + *v = ((u64)s)<<32 | a; + return 6; + } + + p++; + a = a<<14; + a |= *p; + /* a: p2<<28 | p4<<14 | p6 (unmasked) */ + if (!(a&0x80)) + { + a &= SLOT_4_2_0; + b &= SLOT_2_0; + b = b<<7; + a |= b; + s = s>>11; + *v = ((u64)s)<<32 | a; + return 7; + } + + /* CSE2 from below */ + a &= SLOT_2_0; + p++; + b = b<<14; + b |= *p; + /* b: p3<<28 | p5<<14 | p7 (unmasked) */ + if (!(b&0x80)) + { + b &= SLOT_4_2_0; + /* moved CSE2 up */ + /* a &= (0x7f<<14)|(0x7f); */ + a = a<<7; + a |= b; + s = s>>4; + *v = ((u64)s)<<32 | a; + return 8; + } + + p++; + a = a<<15; + a |= *p; + /* a: p4<<29 | p6<<15 | p8 (unmasked) */ + + /* moved CSE2 up */ + /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ + b &= SLOT_2_0; + b = b<<8; + a |= b; + + s = s<<4; + b = p[-4]; + b &= 0x7f; + b = b>>3; + s |= b; + + *v = ((u64)s)<<32 | a; + + return 9; +} + +/* +** Read a 32-bit variable-length integer from memory starting at p[0]. +** Return the number of bytes read. The value is stored in *v. +** +** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned +** integer, then set *v to 0xffffffff. +** +** A MACRO version, getVarint32, is provided which inlines the +** single-byte case. All code should use the MACRO version as +** this function assumes the single-byte case has already been handled. +*/ +SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ + u32 a,b; + + /* The 1-byte case. Overwhelmingly the most common. Handled inline + ** by the getVarin32() macro */ + a = *p; + /* a: p0 (unmasked) */ +#ifndef getVarint32 + if (!(a&0x80)) + { + /* Values between 0 and 127 */ + *v = a; + return 1; + } +#endif + + /* The 2-byte case */ + p++; + b = *p; + /* b: p1 (unmasked) */ + if (!(b&0x80)) + { + /* Values between 128 and 16383 */ + a &= 0x7f; + a = a<<7; + *v = a | b; + return 2; + } + + /* The 3-byte case */ + p++; + a = a<<14; + a |= *p; + /* a: p0<<14 | p2 (unmasked) */ + if (!(a&0x80)) + { + /* Values between 16384 and 2097151 */ + a &= (0x7f<<14)|(0x7f); + b &= 0x7f; + b = b<<7; + *v = a | b; + return 3; + } + + /* A 32-bit varint is used to store size information in btrees. + ** Objects are rarely larger than 2MiB limit of a 3-byte varint. + ** A 3-byte varint is sufficient, for example, to record the size + ** of a 1048569-byte BLOB or string. + ** + ** We only unroll the first 1-, 2-, and 3- byte cases. The very + ** rare larger cases can be handled by the slower 64-bit varint + ** routine. + */ +#if 1 + { + u64 v64; + u8 n; + + p -= 2; + n = sqlite3GetVarint(p, &v64); + assert( n>3 && n<=9 ); + if( (v64 & SQLITE_MAX_U32)!=v64 ){ + *v = 0xffffffff; + }else{ + *v = (u32)v64; + } + return n; + } + +#else + /* For following code (kept for historical record only) shows an + ** unrolling for the 3- and 4-byte varint cases. This code is + ** slightly faster, but it is also larger and much harder to test. + */ + p++; + b = b<<14; + b |= *p; + /* b: p1<<14 | p3 (unmasked) */ + if (!(b&0x80)) + { + /* Values between 2097152 and 268435455 */ + b &= (0x7f<<14)|(0x7f); + a &= (0x7f<<14)|(0x7f); + a = a<<7; + *v = a | b; + return 4; + } + + p++; + a = a<<14; + a |= *p; + /* a: p0<<28 | p2<<14 | p4 (unmasked) */ + if (!(a&0x80)) + { + /* Values between 268435456 and 34359738367 */ + a &= SLOT_4_2_0; + b &= SLOT_4_2_0; + b = b<<7; + *v = a | b; + return 5; + } + + /* We can only reach this point when reading a corrupt database + ** file. In that case we are not in any hurry. Use the (relatively + ** slow) general-purpose sqlite3GetVarint() routine to extract the + ** value. */ + { + u64 v64; + u8 n; + + p -= 4; + n = sqlite3GetVarint(p, &v64); + assert( n>5 && n<=9 ); + *v = (u32)v64; + return n; + } +#endif +} + +/* +** Return the number of bytes that will be needed to store the given +** 64-bit integer. +*/ +SQLITE_PRIVATE int sqlite3VarintLen(u64 v){ + int i = 0; + do{ + i++; + v >>= 7; + }while( v!=0 && ALWAYS(i<9) ); + return i; +} + + +/* +** Read or write a four-byte big-endian integer value. +*/ +SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ + return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]; +} +SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ + p[0] = (u8)(v>>24); + p[1] = (u8)(v>>16); + p[2] = (u8)(v>>8); + p[3] = (u8)v; +} + + + +/* +** Translate a single byte of Hex into an integer. +** This routine only works if h really is a valid hexadecimal +** character: 0..9a..fA..F +*/ +SQLITE_PRIVATE u8 sqlite3HexToInt(int h){ + assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); +#ifdef SQLITE_ASCII + h += 9*(1&(h>>6)); +#endif +#ifdef SQLITE_EBCDIC + h += 9*(1&~(h>>4)); +#endif + return (u8)(h & 0xf); +} + +#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) +/* +** Convert a BLOB literal of the form "x'hhhhhh'" into its binary +** value. Return a pointer to its binary value. Space to hold the +** binary value has been obtained from malloc and must be freed by +** the calling routine. +*/ +SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){ + char *zBlob; + int i; + + zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1); + n--; + if( zBlob ){ + for(i=0; imagic; + if( magic!=SQLITE_MAGIC_OPEN ){ + if( sqlite3SafetyCheckSickOrOk(db) ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + logBadConnection("unopened"); + } + return 0; + }else{ + return 1; + } +} +SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ + u32 magic; + magic = db->magic; + if( magic!=SQLITE_MAGIC_SICK && + magic!=SQLITE_MAGIC_OPEN && + magic!=SQLITE_MAGIC_BUSY ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + logBadConnection("invalid"); + return 0; + }else{ + return 1; + } +} + +/* +** Attempt to add, substract, or multiply the 64-bit signed value iB against +** the other 64-bit signed integer at *pA and store the result in *pA. +** Return 0 on success. Or if the operation would have resulted in an +** overflow, leave *pA unchanged and return 1. +*/ +SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){ + i64 iA = *pA; + testcase( iA==0 ); testcase( iA==1 ); + testcase( iB==-1 ); testcase( iB==0 ); + if( iB>=0 ){ + testcase( iA>0 && LARGEST_INT64 - iA == iB ); + testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 ); + if( iA>0 && LARGEST_INT64 - iA < iB ) return 1; + *pA += iB; + }else{ + testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 ); + testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 ); + if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1; + *pA += iB; + } + return 0; +} +SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){ + testcase( iB==SMALLEST_INT64+1 ); + if( iB==SMALLEST_INT64 ){ + testcase( (*pA)==(-1) ); testcase( (*pA)==0 ); + if( (*pA)>=0 ) return 1; + *pA -= iB; + return 0; + }else{ + return sqlite3AddInt64(pA, -iB); + } +} +#define TWOPOWER32 (((i64)1)<<32) +#define TWOPOWER31 (((i64)1)<<31) +SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){ + i64 iA = *pA; + i64 iA1, iA0, iB1, iB0, r; + + iA1 = iA/TWOPOWER32; + iA0 = iA % TWOPOWER32; + iB1 = iB/TWOPOWER32; + iB0 = iB % TWOPOWER32; + if( iA1*iB1 != 0 ) return 1; + assert( iA1*iB0==0 || iA0*iB1==0 ); + r = iA1*iB0 + iA0*iB1; + testcase( r==(-TWOPOWER31)-1 ); + testcase( r==(-TWOPOWER31) ); + testcase( r==TWOPOWER31 ); + testcase( r==TWOPOWER31-1 ); + if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1; + r *= TWOPOWER32; + if( sqlite3AddInt64(&r, iA0*iB0) ) return 1; + *pA = r; + return 0; +} + +/* +** Compute the absolute value of a 32-bit signed integer, of possible. Or +** if the integer has a value of -2147483648, return +2147483647 +*/ +SQLITE_PRIVATE int sqlite3AbsInt32(int x){ + if( x>=0 ) return x; + if( x==(int)0x80000000 ) return 0x7fffffff; + return -x; +} + +#ifdef SQLITE_ENABLE_8_3_NAMES +/* +** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database +** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and +** if filename in z[] has a suffix (a.k.a. "extension") that is longer than +** three characters, then shorten the suffix on z[] to be the last three +** characters of the original suffix. +** +** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always +** do the suffix shortening regardless of URI parameter. +** +** Examples: +** +** test.db-journal => test.nal +** test.db-wal => test.wal +** test.db-shm => test.shm +** test.db-mj7f3319fa => test.9fa +*/ +SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){ +#if SQLITE_ENABLE_8_3_NAMES<2 + if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) ) +#endif + { + int i, sz; + sz = sqlite3Strlen30(z); + for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} + if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4); + } +} +#endif + +/* +** Find (an approximate) sum of two LogEst values. This computation is +** not a simple "+" operator because LogEst is stored as a logarithmic +** value. +** +*/ +SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){ + static const unsigned char x[] = { + 10, 10, /* 0,1 */ + 9, 9, /* 2,3 */ + 8, 8, /* 4,5 */ + 7, 7, 7, /* 6,7,8 */ + 6, 6, 6, /* 9,10,11 */ + 5, 5, 5, /* 12-14 */ + 4, 4, 4, 4, /* 15-18 */ + 3, 3, 3, 3, 3, 3, /* 19-24 */ + 2, 2, 2, 2, 2, 2, 2, /* 25-31 */ + }; + if( a>=b ){ + if( a>b+49 ) return a; + if( a>b+31 ) return a+1; + return a+x[a-b]; + }else{ + if( b>a+49 ) return b; + if( b>a+31 ) return b+1; + return b+x[b-a]; + } +} + +/* +** Convert an integer into a LogEst. In other words, compute a +** good approximatation for 10*log2(x). +*/ +SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){ + static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 }; + LogEst y = 40; + if( x<8 ){ + if( x<2 ) return 0; + while( x<8 ){ y -= 10; x <<= 1; } + }else{ + while( x>255 ){ y += 40; x >>= 4; } + while( x>15 ){ y += 10; x >>= 1; } + } + return a[x&7] + y - 10; +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Convert a double into a LogEst +** In other words, compute an approximation for 10*log2(x). +*/ +SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){ + u64 a; + LogEst e; + assert( sizeof(x)==8 && sizeof(a)==8 ); + if( x<=1 ) return 0; + if( x<=2000000000 ) return sqlite3LogEst((u64)x); + memcpy(&a, &x, 8); + e = (a>>52) - 1022; + return e*10; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** Convert a LogEst into an integer. +*/ +SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){ + u64 n; + if( x<10 ) return 1; + n = x%10; + x /= 10; + if( n>=5 ) n -= 2; + else if( n>=1 ) n -= 1; + if( x>=3 ) return (n+8)<<(x-3); + return (n+8)>>(3-x); +} + +/************** End of util.c ************************************************/ +/************** Begin file hash.c ********************************************/ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the implementation of generic hash-tables +** used in SQLite. +*/ +/* #include */ + +/* Turn bulk memory into a hash table object by initializing the +** fields of the Hash structure. +** +** "pNew" is a pointer to the hash table that is to be initialized. +*/ +SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){ + assert( pNew!=0 ); + pNew->first = 0; + pNew->count = 0; + pNew->htsize = 0; + pNew->ht = 0; +} + +/* Remove all entries from a hash table. Reclaim all memory. +** Call this routine to delete a hash table or to reset a hash table +** to the empty state. +*/ +SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){ + HashElem *elem; /* For looping over all elements of the table */ + + assert( pH!=0 ); + elem = pH->first; + pH->first = 0; + sqlite3_free(pH->ht); + pH->ht = 0; + pH->htsize = 0; + while( elem ){ + HashElem *next_elem = elem->next; + sqlite3_free(elem); + elem = next_elem; + } + pH->count = 0; +} + +/* +** The hashing function. +*/ +static unsigned int strHash(const char *z, int nKey){ + int h = 0; + assert( nKey>=0 ); + while( nKey > 0 ){ + h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++]; + nKey--; + } + return h; +} + + +/* Link pNew element into the hash table pH. If pEntry!=0 then also +** insert pNew into the pEntry hash bucket. +*/ +static void insertElement( + Hash *pH, /* The complete hash table */ + struct _ht *pEntry, /* The entry into which pNew is inserted */ + HashElem *pNew /* The element to be inserted */ +){ + HashElem *pHead; /* First element already in pEntry */ + if( pEntry ){ + pHead = pEntry->count ? pEntry->chain : 0; + pEntry->count++; + pEntry->chain = pNew; + }else{ + pHead = 0; + } + if( pHead ){ + pNew->next = pHead; + pNew->prev = pHead->prev; + if( pHead->prev ){ pHead->prev->next = pNew; } + else { pH->first = pNew; } + pHead->prev = pNew; + }else{ + pNew->next = pH->first; + if( pH->first ){ pH->first->prev = pNew; } + pNew->prev = 0; + pH->first = pNew; + } +} + + +/* Resize the hash table so that it cantains "new_size" buckets. +** +** The hash table might fail to resize if sqlite3_malloc() fails or +** if the new size is the same as the prior size. +** Return TRUE if the resize occurs and false if not. +*/ +static int rehash(Hash *pH, unsigned int new_size){ + struct _ht *new_ht; /* The new hash table */ + HashElem *elem, *next_elem; /* For looping over existing elements */ + +#if SQLITE_MALLOC_SOFT_LIMIT>0 + if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){ + new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht); + } + if( new_size==pH->htsize ) return 0; +#endif + + /* The inability to allocates space for a larger hash table is + ** a performance hit but it is not a fatal error. So mark the + ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of + ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero() + ** only zeroes the requested number of bytes whereas this module will + ** use the actual amount of space allocated for the hash table (which + ** may be larger than the requested amount). + */ + sqlite3BeginBenignMalloc(); + new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) ); + sqlite3EndBenignMalloc(); + + if( new_ht==0 ) return 0; + sqlite3_free(pH->ht); + pH->ht = new_ht; + pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); + memset(new_ht, 0, new_size*sizeof(struct _ht)); + for(elem=pH->first, pH->first=0; elem; elem = next_elem){ + unsigned int h = strHash(elem->pKey, elem->nKey) % new_size; + next_elem = elem->next; + insertElement(pH, &new_ht[h], elem); + } + return 1; +} + +/* This function (for internal use only) locates an element in an +** hash table that matches the given key. The hash for this key has +** already been computed and is passed as the 4th parameter. +*/ +static HashElem *findElementGivenHash( + const Hash *pH, /* The pH to be searched */ + const char *pKey, /* The key we are searching for */ + int nKey, /* Bytes in key (not counting zero terminator) */ + unsigned int h /* The hash for this key. */ +){ + HashElem *elem; /* Used to loop thru the element list */ + int count; /* Number of elements left to test */ + + if( pH->ht ){ + struct _ht *pEntry = &pH->ht[h]; + elem = pEntry->chain; + count = pEntry->count; + }else{ + elem = pH->first; + count = pH->count; + } + while( count-- && ALWAYS(elem) ){ + if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ + return elem; + } + elem = elem->next; + } + return 0; +} + +/* Remove a single entry from the hash table given a pointer to that +** element and a hash on the element's key. +*/ +static void removeElementGivenHash( + Hash *pH, /* The pH containing "elem" */ + HashElem* elem, /* The element to be removed from the pH */ + unsigned int h /* Hash value for the element */ +){ + struct _ht *pEntry; + if( elem->prev ){ + elem->prev->next = elem->next; + }else{ + pH->first = elem->next; + } + if( elem->next ){ + elem->next->prev = elem->prev; + } + if( pH->ht ){ + pEntry = &pH->ht[h]; + if( pEntry->chain==elem ){ + pEntry->chain = elem->next; + } + pEntry->count--; + assert( pEntry->count>=0 ); + } + sqlite3_free( elem ); + pH->count--; + if( pH->count==0 ){ + assert( pH->first==0 ); + assert( pH->count==0 ); + sqlite3HashClear(pH); + } +} + +/* Attempt to locate an element of the hash table pH with a key +** that matches pKey,nKey. Return the data for this element if it is +** found, or NULL if there is no match. +*/ +SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){ + HashElem *elem; /* The element that matches key */ + unsigned int h; /* A hash on key */ + + assert( pH!=0 ); + assert( pKey!=0 ); + assert( nKey>=0 ); + if( pH->ht ){ + h = strHash(pKey, nKey) % pH->htsize; + }else{ + h = 0; + } + elem = findElementGivenHash(pH, pKey, nKey, h); + return elem ? elem->data : 0; +} + +/* Insert an element into the hash table pH. The key is pKey,nKey +** and the data is "data". +** +** If no element exists with a matching key, then a new +** element is created and NULL is returned. +** +** If another element already exists with the same key, then the +** new data replaces the old data and the old data is returned. +** The key is not copied in this instance. If a malloc fails, then +** the new data is returned and the hash table is unchanged. +** +** If the "data" parameter to this function is NULL, then the +** element corresponding to "key" is removed from the hash table. +*/ +SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){ + unsigned int h; /* the hash of the key modulo hash table size */ + HashElem *elem; /* Used to loop thru the element list */ + HashElem *new_elem; /* New element added to the pH */ + + assert( pH!=0 ); + assert( pKey!=0 ); + assert( nKey>=0 ); + if( pH->htsize ){ + h = strHash(pKey, nKey) % pH->htsize; + }else{ + h = 0; + } + elem = findElementGivenHash(pH,pKey,nKey,h); + if( elem ){ + void *old_data = elem->data; + if( data==0 ){ + removeElementGivenHash(pH,elem,h); + }else{ + elem->data = data; + elem->pKey = pKey; + assert(nKey==elem->nKey); + } + return old_data; + } + if( data==0 ) return 0; + new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) ); + if( new_elem==0 ) return data; + new_elem->pKey = pKey; + new_elem->nKey = nKey; + new_elem->data = data; + pH->count++; + if( pH->count>=10 && pH->count > 2*pH->htsize ){ + if( rehash(pH, pH->count*2) ){ + assert( pH->htsize>0 ); + h = strHash(pKey, nKey) % pH->htsize; + } + } + if( pH->ht ){ + insertElement(pH, &pH->ht[h], new_elem); + }else{ + insertElement(pH, 0, new_elem); + } + return 0; +} + +/************** End of hash.c ************************************************/ +/************** Begin file opcodes.c *****************************************/ +/* Automatically generated. Do not edit */ +/* See the mkopcodec.awk script for details. */ +#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) +SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ + static const char *const azName[] = { "?", + /* 1 */ "Function", + /* 2 */ "Savepoint", + /* 3 */ "AutoCommit", + /* 4 */ "Transaction", + /* 5 */ "SorterNext", + /* 6 */ "Prev", + /* 7 */ "Next", + /* 8 */ "AggStep", + /* 9 */ "Checkpoint", + /* 10 */ "JournalMode", + /* 11 */ "Vacuum", + /* 12 */ "VFilter", + /* 13 */ "VUpdate", + /* 14 */ "Goto", + /* 15 */ "Gosub", + /* 16 */ "Return", + /* 17 */ "Yield", + /* 18 */ "HaltIfNull", + /* 19 */ "Not", + /* 20 */ "Halt", + /* 21 */ "Integer", + /* 22 */ "Int64", + /* 23 */ "String", + /* 24 */ "Null", + /* 25 */ "Blob", + /* 26 */ "Variable", + /* 27 */ "Move", + /* 28 */ "Copy", + /* 29 */ "SCopy", + /* 30 */ "ResultRow", + /* 31 */ "CollSeq", + /* 32 */ "AddImm", + /* 33 */ "MustBeInt", + /* 34 */ "RealAffinity", + /* 35 */ "Permutation", + /* 36 */ "Compare", + /* 37 */ "Jump", + /* 38 */ "Once", + /* 39 */ "If", + /* 40 */ "IfNot", + /* 41 */ "Column", + /* 42 */ "Affinity", + /* 43 */ "MakeRecord", + /* 44 */ "Count", + /* 45 */ "ReadCookie", + /* 46 */ "SetCookie", + /* 47 */ "VerifyCookie", + /* 48 */ "OpenRead", + /* 49 */ "OpenWrite", + /* 50 */ "OpenAutoindex", + /* 51 */ "OpenEphemeral", + /* 52 */ "SorterOpen", + /* 53 */ "OpenPseudo", + /* 54 */ "Close", + /* 55 */ "SeekLt", + /* 56 */ "SeekLe", + /* 57 */ "SeekGe", + /* 58 */ "SeekGt", + /* 59 */ "Seek", + /* 60 */ "NotFound", + /* 61 */ "Found", + /* 62 */ "IsUnique", + /* 63 */ "NotExists", + /* 64 */ "Sequence", + /* 65 */ "NewRowid", + /* 66 */ "Insert", + /* 67 */ "InsertInt", + /* 68 */ "Or", + /* 69 */ "And", + /* 70 */ "Delete", + /* 71 */ "ResetCount", + /* 72 */ "SorterCompare", + /* 73 */ "IsNull", + /* 74 */ "NotNull", + /* 75 */ "Ne", + /* 76 */ "Eq", + /* 77 */ "Gt", + /* 78 */ "Le", + /* 79 */ "Lt", + /* 80 */ "Ge", + /* 81 */ "SorterData", + /* 82 */ "BitAnd", + /* 83 */ "BitOr", + /* 84 */ "ShiftLeft", + /* 85 */ "ShiftRight", + /* 86 */ "Add", + /* 87 */ "Subtract", + /* 88 */ "Multiply", + /* 89 */ "Divide", + /* 90 */ "Remainder", + /* 91 */ "Concat", + /* 92 */ "RowKey", + /* 93 */ "BitNot", + /* 94 */ "String8", + /* 95 */ "RowData", + /* 96 */ "Rowid", + /* 97 */ "NullRow", + /* 98 */ "Last", + /* 99 */ "SorterSort", + /* 100 */ "Sort", + /* 101 */ "Rewind", + /* 102 */ "SorterInsert", + /* 103 */ "IdxInsert", + /* 104 */ "IdxDelete", + /* 105 */ "IdxRowid", + /* 106 */ "IdxLT", + /* 107 */ "IdxGE", + /* 108 */ "Destroy", + /* 109 */ "Clear", + /* 110 */ "CreateIndex", + /* 111 */ "CreateTable", + /* 112 */ "ParseSchema", + /* 113 */ "LoadAnalysis", + /* 114 */ "DropTable", + /* 115 */ "DropIndex", + /* 116 */ "DropTrigger", + /* 117 */ "IntegrityCk", + /* 118 */ "RowSetAdd", + /* 119 */ "RowSetRead", + /* 120 */ "RowSetTest", + /* 121 */ "Program", + /* 122 */ "Param", + /* 123 */ "FkCounter", + /* 124 */ "FkIfZero", + /* 125 */ "MemMax", + /* 126 */ "IfPos", + /* 127 */ "IfNeg", + /* 128 */ "IfZero", + /* 129 */ "AggFinal", + /* 130 */ "Real", + /* 131 */ "IncrVacuum", + /* 132 */ "Expire", + /* 133 */ "TableLock", + /* 134 */ "VBegin", + /* 135 */ "VCreate", + /* 136 */ "VDestroy", + /* 137 */ "VOpen", + /* 138 */ "VColumn", + /* 139 */ "VNext", + /* 140 */ "VRename", + /* 141 */ "ToText", + /* 142 */ "ToBlob", + /* 143 */ "ToNumeric", + /* 144 */ "ToInt", + /* 145 */ "ToReal", + /* 146 */ "Pagecount", + /* 147 */ "MaxPgcnt", + /* 148 */ "Trace", + /* 149 */ "Noop", + /* 150 */ "Explain", + }; + return azName[i]; +} +#endif + +/************** End of opcodes.c *********************************************/ +/************** Begin file os_rtthread.c *************************************/ +/* +** 2004 May 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code that is specific to Windows. +*/ +#if SQLITE_OS_RTTHREAD /* This file is used for rt-thread only */ + +/* #include */ + +/* +** Include code that is common to all os_*.c files +*/ +/************** Include os_common.h in the middle of os_rtthread.c ***********/ +/************** Begin file os_common.h ***************************************/ +/* +** 2004 May 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains macros and a little bit of code that is common to +** all of the platform-specific files (os_*.c) and is #included into those +** files. +** +** This file should be #included by the os_*.c files only. It is not a +** general purpose header file. +*/ +#ifndef _OS_COMMON_H_ +#define _OS_COMMON_H_ + +/* +** At least two bugs have slipped in because we changed the MEMORY_DEBUG +** macro to SQLITE_DEBUG and some older makefiles have not yet made the +** switch. The following code should catch this problem at compile-time. +*/ +#ifdef MEMORY_DEBUG +# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." +#endif + +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) +# ifndef SQLITE_DEBUG_OS_TRACE +# define SQLITE_DEBUG_OS_TRACE 0 +# endif + int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; +# define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X +#else +# define OSTRACE(X) +#endif + +/* +** Macros for performance tracing. Normally turned off. Only works +** on i486 hardware. +*/ +#ifdef SQLITE_PERFORMANCE_TRACE + +/* +** hwtime.h contains inline assembler code for implementing +** high-performance timing routines. +*/ +/************** Include hwtime.h in the middle of os_common.h ****************/ +/************** Begin file hwtime.h ******************************************/ +/* +** 2008 May 27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains inline asm code for retrieving "high-performance" +** counters for x86 class CPUs. +*/ +#ifndef _HWTIME_H_ +#define _HWTIME_H_ + +/* +** The following routine only works on pentium-class (or newer) processors. +** It uses the RDTSC opcode to read the cycle count value out of the +** processor and returns that value. This can be used for high-res +** profiling. +*/ +#if (defined(__GNUC__) || defined(_MSC_VER)) && \ + (defined(i386) || defined(__i386__) || defined(_M_IX86)) + + #if defined(__GNUC__) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + unsigned int lo, hi; + __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); + return (sqlite_uint64)hi << 32 | lo; + } + + #elif defined(_MSC_VER) + + __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ + __asm { + rdtsc + ret ; return value at EDX:EAX + } + } + + #endif + +#elif (defined(__GNUC__) && defined(__x86_64__)) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + unsigned long val; + __asm__ __volatile__ ("rdtsc" : "=A" (val)); + return val; + } + +#elif (defined(__GNUC__) && defined(__ppc__)) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + unsigned long long retval; + unsigned long junk; + __asm__ __volatile__ ("\n\ + 1: mftbu %1\n\ + mftb %L0\n\ + mftbu %0\n\ + cmpw %0,%1\n\ + bne 1b" + : "=r" (retval), "=r" (junk)); + return retval; + } + +#else + + #error Need implementation of sqlite3Hwtime() for your platform. + + /* + ** To compile without implementing sqlite3Hwtime() for your platform, + ** you can remove the above #error and use the following + ** stub function. You will lose timing support for many + ** of the debugging and testing utilities, but it should at + ** least compile and run. + */ +SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } + +#endif + +#endif /* !defined(_HWTIME_H_) */ + +/************** End of hwtime.h **********************************************/ +/************** Continuing where we left off in os_common.h ******************/ + +static sqlite_uint64 g_start; +static sqlite_uint64 g_elapsed; +#define TIMER_START g_start=sqlite3Hwtime() +#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start +#define TIMER_ELAPSED g_elapsed +#else +#define TIMER_START +#define TIMER_END +#define TIMER_ELAPSED ((sqlite_uint64)0) +#endif + +/* +** If we compile with the SQLITE_TEST macro set, then the following block +** of code will give us the ability to simulate a disk I/O error. This +** is used for testing the I/O recovery logic. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ +SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ +SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ +SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ +SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */ +SQLITE_API int sqlite3_diskfull_pending = 0; +SQLITE_API int sqlite3_diskfull = 0; +#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) +#define SimulateIOError(CODE) \ + if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ + || sqlite3_io_error_pending-- == 1 ) \ + { local_ioerr(); CODE; } +static void local_ioerr(){ + IOTRACE(("IOERR\n")); + sqlite3_io_error_hit++; + if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; +} +#define SimulateDiskfullError(CODE) \ + if( sqlite3_diskfull_pending ){ \ + if( sqlite3_diskfull_pending == 1 ){ \ + local_ioerr(); \ + sqlite3_diskfull = 1; \ + sqlite3_io_error_hit = 1; \ + CODE; \ + }else{ \ + sqlite3_diskfull_pending--; \ + } \ + } +#else +#define SimulateIOErrorBenign(X) +#define SimulateIOError(A) +#define SimulateDiskfullError(A) +#endif + +/* +** When testing, keep a count of the number of open files. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_open_file_count = 0; +#define OpenCounter(X) sqlite3_open_file_count+=(X) +#else +#define OpenCounter(X) +#endif + +#endif /* !defined(_OS_COMMON_H_) */ + +/************** End of os_common.h *******************************************/ +/************** Continuing where we left off in os_rtthread.c ****************/ + +/* +** Compiling and using WAL mode requires several APIs that are not +** available in rt-thread. +*/ +#if !defined(SQLITE_OMIT_WAL) +# error "WAL mode requires not support from the rt-thread, compile\ + with SQLITE_OMIT_WAL." +#endif + +/* +** Are most of the rtthread ANSI APIs available (i.e. with certain exceptions +** based on the sub-platform)? +*/ +#if !defined(SQLITE_RTTHREAD_NO_ANSI) +# warning "please ensure rtthread ANSI APIs is available, otherwise compile with\ + SQLITE_RTTHREAD_NO_ANSI" +# define SQLITE_RTTHREAD_HAS_ANSI +#endif + +/* +** Are most of the rtthread Unicode APIs available (i.e. with certain exceptions +** based on the sub-platform)? +*/ +#if !defined(SQLITE_RTTHREAD_NO_WIDE) +# error "rtthread not support Unicode APIs" +# define SQLITE_RTTHREAD_HAS_WIDE +#endif + +/* +** Make sure at least one set of rtthread APIs is available. +*/ +#if !defined(SQLITE_RTTHREAD_HAS_ANSI) && !defined(SQLITE_RTTHREAD_HAS_WIDE) +# error "At least one of SQLITE_RTTHREAD_HAS_ANSI and SQLITE_RTTHREAD_HAS_WIDE\ + must be defined." +#endif + +/* +** Maximum pathname length (in chars) for rtthread. This should normally be +** MAX_PATH. +*/ +#ifndef SQLITE_RTTHREAD_MAX_PATH_CHARS +# warning "default Maximum pathname length be 255, otherwise compile with\ + SQLITE_RTTHREAD_MAX_PATH_CHARS=?" +# define SQLITE_RTTHREAD_MAX_PATH_CHARS (255) +#endif + +/* +** Maximum supported path-length. +*/ +#define MAX_PATHNAME 512 + +/* +** Returns non-zero if the character should be treated as a directory +** separator. +*/ +#ifndef rtthreadIsDirSep +# define rtthreadIsDirSep(a) ((a) == '/') +#endif + +/* +** This macro is used when a local variable is set to a value that is +** [sometimes] not used by the code (e.g. via conditional compilation). +*/ +#ifndef UNUSED_VARIABLE_VALUE +# define UNUSED_VARIABLE_VALUE(x) (void)(x) +#endif + +/* +** Returns the string that should be used as the directory separator. +*/ +#ifndef rtthreadGetDirDep +# define rtthreadGetDirDep() "/" +#endif + +/* +** The winFile structure is a subclass of sqlite3_file* specific to the win32 +** portability layer. +*/ +typedef struct rtthreadFile rtthreadFile; +struct rtthreadFile { + sqlite3_io_methods const *pMethod; /* Always the first entry */ + sqlite3_vfs *pVfs; /* The VFS that created this rtthreadFile */ + int h; /* The file descriptor */ + unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */ + unsigned char eFileLock; /* The type of lock held on this fd */ + int lastErrno; /* The unix errno from last I/O error */ + void *lockingContext; /* Locking style specific state */ + const char *zPath; /* Name of the file */ + int szChunk; /* Configured by FCNTL_CHUNK_SIZE */ +#if SQLITE_ENABLE_LOCKING_STYLE + int openFlags; /* The flags specified at open() */ +#endif +#if SQLITE_ENABLE_LOCKING_STYLE + unsigned fsFlags; /* cached details from statfs() */ +#endif +#ifdef SQLITE_DEBUG + /* The next group of variables are used to track whether or not the + ** transaction counter in bytes 24-27 of database files are updated + ** whenever any part of the database changes. An assertion fault will + ** occur if a file is updated without also updating the transaction + ** counter. This test is made to avoid new problems similar to the + ** one described by ticket #3584. + */ + unsigned char transCntrChng; /* True if the transaction counter changed */ + unsigned char dbUpdate; /* True if any part of database file changed */ + unsigned char inNormalWrite; /* True if in a normal write operation */ + +#endif + +#ifdef SQLITE_TEST + /* In test mode, increase the size of this structure a bit so that + ** it is larger than the struct CrashFile defined in test6.c. + */ + char aPadding[32]; +#endif +}; + +/* +** Allowed values for the rtthreadFile.ctrlFlags bitmask: +*/ +#define UNIXFILE_EXCL 0x01 /* Connections from one process only */ +#define UNIXFILE_RDONLY 0x02 /* Connection is read only */ +#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ +#ifndef SQLITE_DISABLE_DIRSYNC +# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */ +#else +# define UNIXFILE_DIRSYNC 0x00 +#endif +#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ +#define UNIXFILE_DELETE 0x20 /* Delete on close */ +#define UNIXFILE_URI 0x40 /* Filename might have query parameters */ +#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */ +#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */ + +/* +** The following variable is (normally) set once and never changes +** thereafter. It records whether the operating system is Win9x +** or WinNT. +** +** 0: Operating system unknown. +** 1: Operating system is rtthread. +** +** In order to facilitate testing on a rtthread system, the test fixture +** can manually set this value to 1 to emulate Win98 behavior. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_os_type = 0; +#elif !SQLITE_OS_RTTHREAD && \ + defined(SQLITE_RTTHREAD_HAS_ANSI) && defined(SQLITE_RTTHREAD_HAS_WIDE) +static int sqlite3_os_type = 0; +#endif + +#ifndef SYSCALL +# define SYSCALL sqlite3_syscall_ptr +#endif + +#include + +static int _Access(const char *pathname, int mode) +{ + int fd; + + fd = open(pathname, O_RDONLY, mode); + + if (fd >= 0) + { + close(fd); + return 0; + } + + return -1; +} + +/* +** Invoke open(). Do so multiple times, until it either succeeds or +** fails for some reason other than EINTR. +** +** If the file creation mode "m" is 0 then set it to the default for +** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally +** 0644) as modified by the system umask. If m is not 0, then +** make the file creation mode be exactly m ignoring the umask. +** +** The m parameter will be non-zero only when creating -wal, -journal, +** and -shm files. We want those files to have *exactly* the same +** permissions as their original database, unadulterated by the umask. +** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a +** transaction crashes and leaves behind hot journals, then any +** process that is able to write to the database will also be able to +** recover the hot journals. +*/ +static int robust_open(const char *z, int f, mode_t m); + +/* +** Open a file descriptor to the directory containing file zFilename. +** If successful, *pFd is set to the opened file descriptor and +** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM +** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined +** value. +** +** The directory file descriptor is used for only one thing - to +** fsync() a directory to make sure file creation and deletion events +** are flushed to disk. Such fsyncs are not needed on newer +** journaling filesystems, but are required on older filesystems. +** +** This routine can be overridden using the xSetSysCall interface. +** The ability to override this routine was added in support of the +** chromium sandbox. Opening a directory is a security risk (we are +** told) so making it overrideable allows the chromium sandbox to +** replace this routine with a harmless no-op. To make this routine +** a no-op, replace it with a stub that returns SQLITE_OK but leaves +** *pFd set to a negative number. +** +** If SQLITE_OK is returned, the caller is responsible for closing +** the file descriptor *pFd using close(). +*/ +static int openDirectory(const char *zFilename, int *pFd); + +/* +** Many system calls are accessed through pointer-to-functions so that +** they may be overridden at runtime to facilitate fault injection during +** testing and sandboxing. The following array holds the names and pointers +** to all overrideable system calls. +*/ +static struct rtthread_syscall { + const char *zName; /* Name of the system call */ + sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ + sqlite3_syscall_ptr pDefault; /* Default value */ +} aSyscall[] = { + {"sleep", (sqlite3_syscall_ptr)rt_thread_delay, 0}, +#define osSleep ((rt_err_t(*)(rt_tick_t))aSyscall[0].pCurrent) + + { "open", (sqlite3_syscall_ptr)open, 0 }, +#define osOpen ((int(*)(const char*,int,int))aSyscall[1].pCurrent) + + { "close", (sqlite3_syscall_ptr)close, 0 }, +#define osClose ((int(*)(int))aSyscall[2].pCurrent) + + { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 }, +#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent) + + { "stat", (sqlite3_syscall_ptr)stat, 0 }, +#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) + + { "fstat", (sqlite3_syscall_ptr)fstat, 0 }, +#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent) + + { "read", (sqlite3_syscall_ptr)read, 0 }, +#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[6].pCurrent) + + { "write", (sqlite3_syscall_ptr)write, 0 }, +#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[7].pCurrent) + + { "unlink", (sqlite3_syscall_ptr)unlink, 0 }, +#define osUnlink ((int(*)(const char*))aSyscall[8].pCurrent) + + { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 }, +#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[9].pCurrent) + + { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 }, +#define osMkdir ((int(*)(const char*,mode_t))aSyscall[10].pCurrent) + + { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 }, +#define osRmdir ((int(*)(const char*))aSyscall[11].pCurrent) + + {"access", (sqlite3_syscall_ptr)_Access, 0 }, +#define osAccess ((int(*)(const char*, int))aSyscall[12].pCurrent) +}; /* End of the overrideable system calls */ + +/* +** +** This function - unixLogError_x(), is only ever called via the macro +** unixLogError(). +** +** It is invoked after an error occurs in an OS function and errno has been +** set. It logs a message using sqlite3_log() containing the current value of +** errno and, if possible, the human-readable equivalent from strerror() or +** strerror_r(). +** +** The first argument passed to the macro should be the error code that +** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). +** The two subsequent arguments should be the name of the OS function that +** failed (e.g. "unlink", "open") and the associated file-system path, +** if any. +*/ +#define rtthreadLogError(a,b,c) rtthreadLogErrorAtLine(a,b,c,__LINE__) +static int rtthreadLogErrorAtLine( + int errcode, /* SQLite error code */ + const char *zFunc, /* Name of OS function that failed */ + const char *zPath, /* File path associated with error */ + int iLine /* Source line number where error occurred */ +){ + char *zErr; /* Message from strerror() or equivalent */ + int iErrno = errno; /* Saved syscall error number */ + + /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use + ** the strerror() function to obtain the human-readable error message + ** equivalent to errno. Otherwise, use strerror_r(). + */ +#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R) + char aErr[80]; + memset(aErr, 0, sizeof(aErr)); + zErr = aErr; + + /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined, + ** assume that the system provides the GNU version of strerror_r() that + ** returns a pointer to a buffer containing the error message. That pointer + ** may point to aErr[], or it may point to some static storage somewhere. + ** Otherwise, assume that the system provides the POSIX version of + ** strerror_r(), which always writes an error message into aErr[]. + ** + ** If the code incorrectly assumes that it is the POSIX version that is + ** available, the error message will often be an empty string. Not a + ** huge problem. Incorrectly concluding that the GNU version is available + ** could lead to a segfault though. + */ +#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU) + zErr = +# endif + strerror_r(iErrno, aErr, sizeof(aErr)-1); + +#elif SQLITE_THREADSAFE + /* This is a threadsafe build, but strerror_r() is not available. */ + zErr = ""; +#else + /* Non-threadsafe build, use strerror(). */ + zErr = strerror(iErrno); +#endif + + if( zPath==0 ) zPath = ""; + sqlite3_log(errcode, + "os_rtthread.c:%d: (%d) %s(%s) - %s", + iLine, iErrno, zFunc, zPath, zErr + ); + + return errcode; +} + + +/* +** Do not accept any file descriptor less than this value, in order to avoid +** opening database file using file descriptors that are commonly used for +** standard input, output, and error. +*/ +#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR +# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3 +#endif + +/* +** Invoke open(). Do so multiple times, until it either succeeds or +** fails for some reason other than EINTR. +** +** If the file creation mode "m" is 0 then set it to the default for +** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally +** 0644) as modified by the system umask. If m is not 0, then +** make the file creation mode be exactly m ignoring the umask. +** +** The m parameter will be non-zero only when creating -wal, -journal, +** and -shm files. We want those files to have *exactly* the same +** permissions as their original database, unadulterated by the umask. +** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a +** transaction crashes and leaves behind hot journals, then any +** process that is able to write to the database will also be able to +** recover the hot journals. +*/ +static int robust_open(const char *z, int f, mode_t m){ + int fd; + mode_t m2 = m ; + while(1){ +#if defined(O_CLOEXEC) + fd = osOpen(z,f|O_CLOEXEC,m2); +#else + fd = osOpen(z,f,m2); +#endif + if( fd<0 ){ + if( errno==EINTR ) continue; + break; + } + if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break; + osClose(fd); + sqlite3_log(SQLITE_WARNING, + "attempt to open \"%s\" as file descriptor %d", z, fd); + fd = -1; + if( osOpen("/000111sql.test111000", f, m)<0 ) break; + } + + return fd; +} + +/* +** Open a file descriptor to the directory containing file zFilename. +** If successful, *pFd is set to the opened file descriptor and +** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM +** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined +** value. +** +** The directory file descriptor is used for only one thing - to +** fsync() a directory to make sure file creation and deletion events +** are flushed to disk. Such fsyncs are not needed on newer +** journaling filesystems, but are required on older filesystems. +** +** This routine can be overridden using the xSetSysCall interface. +** The ability to override this routine was added in support of the +** chromium sandbox. Opening a directory is a security risk (we are +** told) so making it overrideable allows the chromium sandbox to +** replace this routine with a harmless no-op. To make this routine +** a no-op, replace it with a stub that returns SQLITE_OK but leaves +** *pFd set to a negative number. +** +** If SQLITE_OK is returned, the caller is responsible for closing +** the file descriptor *pFd using close(). +*/ +static int openDirectory(const char *zFilename, int *pFd){ + int ii; + int fd = -1; + char zDirname[MAX_PATHNAME+1]; + + sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); + for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--); + if( ii>0 ){ + zDirname[ii] = '\0'; + fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0); + if( fd>=0 ){ + OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); + } + } + *pFd = fd; + return (fd>=0?SQLITE_OK:rtthreadLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname)); +} + + + +/* +** This is the xSetSystemCall() method of sqlite3_vfs for all of the +** "win32" VFSes. Return SQLITE_OK opon successfully updating the +** system call pointer, or SQLITE_NOTFOUND if there is no configurable +** system call named zName. +*/ +static int rtthreadSetSystemCall( + sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ + const char *zName, /* Name of system call to override */ + sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ +){ + unsigned int i; + int rc = SQLITE_NOTFOUND; + + UNUSED_PARAMETER(pNotUsed); + if( zName==0 ){ + /* If no zName is given, restore all system calls to their default + ** settings and return NULL + */ + rc = SQLITE_OK; + for(i=0; izPath : 0, lineno); + } +} + +/* +** Check a rtthreadFile that is a database. Verify the following: +** +** (1) There is exactly one hard link on the file +** (2) The file is not a symbolic link +** (3) The file has not been renamed or unlinked +** +** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right. +*/ +static void verifyDbFile(rtthreadFile *pFile){ + struct stat buf; + int rc; + if( pFile->ctrlFlags & UNIXFILE_WARNED ){ + /* One or more of the following warnings have already been issued. Do not + ** repeat them so as not to clutter the error log */ + return; + } + rc = osFstat(pFile->h, &buf); + if( rc!=0 ){ + sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath); + pFile->ctrlFlags |= UNIXFILE_WARNED; + return; + } + if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){ + sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath); + pFile->ctrlFlags |= UNIXFILE_WARNED; + return; + } +} + +/* +** This function performs the parts of the "close file" operation +** common to all locking schemes. It closes the directory and file +** handles, if they are valid, and sets all fields of the rtthreadFile +** structure to 0. +** +** It is *not* necessary to hold the mutex when this routine is called, +** even on VxWorks. A mutex will be acquired on VxWorks by the +** vxworksReleaseFileId() routine. +*/ +static int closeRtthreadFile(sqlite3_file *id){ + rtthreadFile *pFile = (rtthreadFile*)id; + if( pFile->h>=0 ){ + robust_close(pFile, pFile->h, __LINE__); + pFile->h = -1; + } + OSTRACE(("CLOSE %-3d\n", pFile->h)); + OpenCounter(-1); + memset(pFile, 0, sizeof(rtthreadFile)); + return SQLITE_OK; +} + +/************** End of the posix advisory lock implementation ***************** +******************************************************************************/ + +/****************************************************************************** +****************************** No-op Locking ********************************** +** +** Of the various locking implementations available, this is by far the +** simplest: locking is ignored. No attempt is made to lock the database +** file for reading or writing. +** +** This locking mode is appropriate for use on read-only databases +** (ex: databases that are burned into CD-ROM, for example.) It can +** also be used if the application employs some external mechanism to +** prevent simultaneous access of the same database by two or more +** database connections. But there is a serious risk of database +** corruption if this locking mode is used in situations where multiple +** database connections are accessing the same database file at the same +** time and one or more of those connections are writing. +*/ + +static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){ + UNUSED_PARAMETER(NotUsed); + *pResOut = 0; + return SQLITE_OK; +} +static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return SQLITE_OK; +} +static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return SQLITE_OK; +} + +/* +** Close the file. +*/ +static int nolockClose(sqlite3_file *id) { + return closeRtthreadFile(id); +} + +/******************* End of the no-op lock implementation ********************* +******************************************************************************/ + +/****************************************************************************** +************************* Begin dot-file Locking ****************************** +** +** The dotfile locking implementation uses the existence of separate lock +** files (really a directory) to control access to the database. This works +** on just about every filesystem imaginable. But there are serious downsides: +** +** (1) There is zero concurrency. A single reader blocks all other +** connections from reading or writing the database. +** +** (2) An application crash or power loss can leave stale lock files +** sitting around that need to be cleared manually. +** +** Nevertheless, a dotlock is an appropriate locking mode for use if no +** other locking strategy is available. +** +** Dotfile locking works by creating a subdirectory in the same directory as +** the database and with the same name but with a ".lock" extension added. +** The existence of a lock directory implies an EXCLUSIVE lock. All other +** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE. +*/ + +/* +** The file suffix added to the data base filename in order to create the +** lock directory. +*/ +#define DOTLOCK_SUFFIX ".lock" + +/* +** Only set the lastErrno if the error code is a real error and not +** a normal expected return code of SQLITE_BUSY or SQLITE_OK +*/ +#define IS_LOCK_ERROR(x) (((x) != SQLITE_OK) && ((x) != SQLITE_BUSY)) + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +** +** In dotfile locking, either a lock exists or it does not. So in this +** variation of CheckReservedLock(), *pResOut is set to true if any lock +** is held on the file and false if the file is unlocked. +*/ +static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { + int rc = SQLITE_OK; + int reserved = 0; + rtthreadFile *pFile = (rtthreadFile*)id; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + + assert( pFile ); + + /* Check if a thread in this process holds such a lock */ + if( pFile->eFileLock>SHARED_LOCK ){ + /* Either this connection or some other connection in the same process + ** holds a lock on the file. No need to check further. */ + reserved = 1; + }else{ + /* The lock is held if and only if the lockfile exists */ + const char *zLockFile = (const char*)pFile->lockingContext; + reserved = 0; + } + OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved)); + *pResOut = reserved; + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +** +** With dotfile locking, we really only support state (4): EXCLUSIVE. +** But we track the other locking levels internally. +*/ +static int dotlockLock(sqlite3_file *id, int eFileLock) { + rtthreadFile *pFile = (rtthreadFile*)id; + char *zLockFile = (char *)pFile->lockingContext; + int rc = SQLITE_OK; + + + /* If we have any lock, then the lock file already exists. All we have + ** to do is adjust our internal record of the lock level. + */ + if( pFile->eFileLock > NO_LOCK ){ + pFile->eFileLock = eFileLock; + return SQLITE_OK; + } + + /* grab an exclusive lock */ + rc = osMkdir(zLockFile, 0777); + if( rc<0 ){ + /* failed to open/create the lock directory */ + int tErrno = errno; + if( EEXIST == tErrno ){ + rc = SQLITE_BUSY; + } else { + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + } + return rc; + } + + /* got it, set the type and return ok */ + pFile->eFileLock = eFileLock; + return rc; +} + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +** +** When the locking level reaches NO_LOCK, delete the lock file. +*/ +static int dotlockUnlock(sqlite3_file *id, int eFileLock) { + rtthreadFile *pFile = (rtthreadFile*)id; + char *zLockFile = (char *)pFile->lockingContext; + int rc; + + assert( pFile ); + OSTRACE(("UNLOCK %d %d was %d tnm=%s (dotlock)\n", pFile->h, eFileLock, + pFile->eFileLock, rt_thread_self()->name )); + assert( eFileLock<=SHARED_LOCK ); + + /* no-op if possible */ + if( pFile->eFileLock==eFileLock ){ + return SQLITE_OK; + } + + /* To downgrade to shared, simply update our internal notion of the + ** lock state. No need to mess with the file on disk. + */ + if( eFileLock==SHARED_LOCK ){ + pFile->eFileLock = SHARED_LOCK; + return SQLITE_OK; + } + + /* To fully unlock the database, delete the lock file */ + assert( eFileLock==NO_LOCK ); + rc = osRmdir(zLockFile); + if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile); + if( rc<0 ){ + int tErrno = errno; + rc = 0; + if( ENOENT != tErrno ){ + rc = SQLITE_IOERR_UNLOCK; + } + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + return rc; + } + pFile->eFileLock = NO_LOCK; + return SQLITE_OK; +} + +/* +** Close a file. Make sure the lock has been released before closing. +*/ +static int dotlockClose(sqlite3_file *id) { + int rc = SQLITE_OK; + if( id ){ + rtthreadFile *pFile = (rtthreadFile*)id; + dotlockUnlock(id, NO_LOCK); + sqlite3_free(pFile->lockingContext); + rc = closeRtthreadFile(id); + } + return rc; +} +/****************** End of the dot-file lock implementation ******************* +******************************************************************************/ + +/****************************************************************************** +************************** Begin flock Locking ******************************** +** +** Use the flock() system call to do file locking. +** +** flock() locking is like dot-file locking in that the various +** fine-grain locking levels supported by SQLite are collapsed into +** a single exclusive lock. In other words, SHARED, RESERVED, and +** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite +** still works when you do this, but concurrency is reduced since +** only a single process can be reading the database at a time. +** +** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if +** compiling for VXWORKS. +*/ +#if SQLITE_ENABLE_LOCKING_STYLE +#warning "rtthread file lock not available" +/* +** Retry flock() calls that fail with EINTR +*/ +static int robust_flock(int fd, int op){ + int rc = 0; + + return rc; +} + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +*/ +static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ + int rc = SQLITE_OK; + int reserved = 0; + rtthreadFile *pFile = (rtthreadFile*)id; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + + assert( pFile ); + + /* Check if a thread in this process holds such a lock */ + if( pFile->eFileLock>SHARED_LOCK ){ + reserved = 1; + } + + /* Otherwise see if some other process holds it. */ + if( !reserved ){ + /* attempt to get the lock */ + int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB); + if( !lrc ){ + /* got the lock, unlock it */ + lrc = robust_flock(pFile->h, LOCK_UN); + if ( lrc ) { + int tErrno = errno; + /* unlock failed with an error */ + lrc = SQLITE_IOERR_UNLOCK; + if( IS_LOCK_ERROR(lrc) ){ + pFile->lastErrno = tErrno; + rc = lrc; + } + } + } else { + int tErrno = errno; + reserved = 1; + /* someone else might have it reserved */ + lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( IS_LOCK_ERROR(lrc) ){ + pFile->lastErrno = tErrno; + rc = lrc; + } + } + } + OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved)); + +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ + rc = SQLITE_OK; + reserved=1; + } +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ + *pResOut = reserved; + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** flock() only really support EXCLUSIVE locks. We track intermediate +** lock states in the sqlite3_file structure, but all locks SHARED or +** above are really EXCLUSIVE locks and exclude all other processes from +** access the file. +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +*/ +static int flockLock(sqlite3_file *id, int eFileLock) { + int rc = SQLITE_OK; + rtthreadFile *pFile = (rtthreadFile*)id; + + assert( pFile ); + + /* if we already have a lock, it is exclusive. + ** Just adjust level and punt on outta here. */ + if (pFile->eFileLock > NO_LOCK) { + pFile->eFileLock = eFileLock; + return SQLITE_OK; + } + + /* grab an exclusive lock */ + + if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) { + int tErrno = errno; + /* didn't get, must be busy */ + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + } else { + /* got it, set the type and return ok */ + pFile->eFileLock = eFileLock; + } + OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), + rc==SQLITE_OK ? "ok" : "failed")); +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ + rc = SQLITE_BUSY; + } +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ + return rc; +} + + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +*/ +static int flockUnlock(sqlite3_file *id, int eFileLock) { + rtthreadFile *pFile = (rtthreadFile*)id; + + assert( pFile ); + OSTRACE(("UNLOCK %d %d was %d tnm=%s (flock)\n", pFile->h, eFileLock, + pFile->eFileLock, rt_thread_self()->name)); + assert( eFileLock<=SHARED_LOCK ); + + /* no-op if possible */ + if( pFile->eFileLock==eFileLock ){ + return SQLITE_OK; + } + + /* shared can just be set because we always have an exclusive */ + if (eFileLock==SHARED_LOCK) { + pFile->eFileLock = eFileLock; + return SQLITE_OK; + } + + /* no, really, unlock. */ + if( robust_flock(pFile->h, LOCK_UN) ){ +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + return SQLITE_OK; +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ + return SQLITE_IOERR_UNLOCK; + }else{ + pFile->eFileLock = NO_LOCK; + return SQLITE_OK; + } +} + +/* +** Close a file. +*/ +static int flockClose(sqlite3_file *id) { + int rc = SQLITE_OK; + if( id ){ + flockUnlock(id, NO_LOCK); + rc = closeRtthreadFile(id); + } + return rc; +} + +#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */ + +/******************* End of the flock lock implementation ********************* +******************************************************************************/ + +/****************************************************************************** +**************** Non-locking sqlite3_file methods ***************************** +** +** The next division contains implementations for all methods of the +** sqlite3_file object other than the locking methods. The locking +** methods were defined in divisions above (one locking method per +** division). Those methods that are common to all locking modes +** are gather together into this division. +*/ + +/* +** Seek to the offset passed as the second argument, then read cnt +** bytes into pBuf. Return the number of bytes actually read. +** +** NB: If you define USE_PREAD or USE_PREAD64, then it might also +** be necessary to define _XOPEN_SOURCE to be 500. This varies from +** one system to another. Since SQLite does not define USE_PREAD +** any any form by default, we will not attempt to define _XOPEN_SOURCE. +** See tickets #2741 and #2681. +** +** To avoid stomping the errno value on a failed read the lastErrno value +** is set before returning. +*/ +static int seekAndRead(rtthreadFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ + int got; + int prior = 0; +#if (!defined(USE_PREAD) && !defined(USE_PREAD64)) + i64 newOffset; +#endif + TIMER_START; + assert( cnt==(cnt&0x1ffff) ); + assert( id->h>2 ); + cnt &= 0x1ffff; + do{ +#if defined(USE_PREAD) + #error "rtthread pread not support" + got = osPread(id->h, pBuf, cnt, offset); + SimulateIOError( got = -1 ); +#elif defined(USE_PREAD64) + #error "rtthread pread64 not support" + got = osPread64(id->h, pBuf, cnt, offset); + SimulateIOError( got = -1 ); +#else + newOffset = lseek(id->h, offset, SEEK_SET); + SimulateIOError( newOffset-- ); + if( newOffset!=offset ){ + if( newOffset == -1 ){ + ((rtthreadFile*)id)->lastErrno = errno; + }else{ + ((rtthreadFile*)id)->lastErrno = 0; + } + return -1; + } + got = osRead(id->h, pBuf, cnt); +#endif + if( got==cnt ) break; + if( got<0 ){ + if( errno==EINTR ){ got = 1; continue; } + prior = 0; + ((rtthreadFile*)id)->lastErrno = errno; + break; + }else if( got>0 ){ + cnt -= got; + offset += got; + prior += got; + pBuf = (void*)(got + (char*)pBuf); + } + }while( got>0 ); + TIMER_END; + OSTRACE(("READ %-3d %5d %7lld %llu\n", + id->h, got+prior, offset-prior, TIMER_ELAPSED)); + return got+prior; +} + +/* +** Read data from a file into a buffer. Return SQLITE_OK if all +** bytes were read successfully and SQLITE_IOERR if anything goes +** wrong. +*/ +static int rtthreadRead( + sqlite3_file *id, + void *pBuf, + int amt, + sqlite3_int64 offset +){ + rtthreadFile *pFile = (rtthreadFile *)id; + int got; + assert( id ); + assert( offset>=0 ); + assert( amt>0 ); + + got = seekAndRead(pFile, offset, pBuf, amt); + if( got==amt ){ + return SQLITE_OK; + }else if( got<0 ){ + /* lastErrno set by seekAndRead */ + return SQLITE_IOERR_READ; + }else{ + pFile->lastErrno = 0; /* not a system error */ + /* Unread parts of the buffer must be zero-filled */ + memset(&((char*)pBuf)[got], 0, amt-got); + return SQLITE_IOERR_SHORT_READ; + } +} + +/* +** Attempt to seek the file-descriptor passed as the first argument to +** absolute offset iOff, then attempt to write nBuf bytes of data from +** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, +** return the actual number of bytes written (which may be less than +** nBuf). +*/ +static int seekAndWriteFd( + int fd, /* File descriptor to write to */ + i64 iOff, /* File offset to begin writing at */ + const void *pBuf, /* Copy data from this buffer to the file */ + int nBuf, /* Size of buffer pBuf in bytes */ + int *piErrno /* OUT: Error number if error occurs */ +){ + int rc = 0; /* Value returned by system call */ + + assert( nBuf==(nBuf&0x1ffff) ); + assert( fd>2 ); + nBuf &= 0x1ffff; + TIMER_START; + +#if defined(USE_PREAD) + do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR ); +#elif defined(USE_PREAD64) + do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR); +#else + do{ + i64 iSeek = lseek(fd, iOff, SEEK_SET); + SimulateIOError( iSeek-- ); + + if( iSeek!=iOff ){ + if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0); + return -1; + } + rc = osWrite(fd, pBuf, nBuf); + }while( rc<0 && errno==EINTR ); +#endif + + TIMER_END; + OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED)); + + if( rc<0 && piErrno ) *piErrno = errno; + return rc; +} + + +/* +** Seek to the offset in id->offset then read cnt bytes into pBuf. +** Return the number of bytes actually read. Update the offset. +** +** To avoid stomping the errno value on a failed write the lastErrno value +** is set before returning. +*/ +static int seekAndWrite(rtthreadFile *id, i64 offset, const void *pBuf, int cnt){ + return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno); +} + + +/* +** Write data from a buffer into a file. Return SQLITE_OK on success +** or some other error code on failure. +*/ +static int rtthreadWrite( + sqlite3_file *id, + const void *pBuf, + int amt, + sqlite3_int64 offset +){ + rtthreadFile *pFile = (rtthreadFile*)id; + int wrote = 0; + assert( id ); + assert( amt>0 ); + +#ifdef SQLITE_DEBUG + /* If we are doing a normal write to a database file (as opposed to + ** doing a hot-journal rollback or a write to some file other than a + ** normal database file) then record the fact that the database + ** has changed. If the transaction counter is modified, record that + ** fact too. + */ + if( pFile->inNormalWrite ){ + pFile->dbUpdate = 1; /* The database has been modified */ + if( offset<=24 && offset+amt>=27 ){ + int rc; + char oldCntr[4]; + SimulateIOErrorBenign(1); + rc = seekAndRead(pFile, 24, oldCntr, 4); + SimulateIOErrorBenign(0); + if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){ + pFile->transCntrChng = 1; /* The transaction counter has changed */ + } + } + } +#endif + + while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){ + amt -= wrote; + offset += wrote; + pBuf = &((char*)pBuf)[wrote]; + } + SimulateIOError(( wrote=(-1), amt=1 )); + SimulateDiskfullError(( wrote=0, amt=1 )); + + if( amt>0 ){ + if( wrote<0 && pFile->lastErrno!=ENOSPC ){ + /* lastErrno set by seekAndWrite */ + return SQLITE_IOERR_WRITE; + }else{ + pFile->lastErrno = 0; /* not a system error */ + return SQLITE_FULL; + } + } + + return SQLITE_OK; +} + +#ifdef SQLITE_TEST +/* +** Count the number of fullsyncs and normal syncs. This is used to test +** that syncs and fullsyncs are occurring at the right times. +*/ +SQLITE_API int sqlite3_sync_count = 0; +SQLITE_API int sqlite3_fullsync_count = 0; +#endif + +/* +** We do not trust systems to provide a working fdatasync(). Some do. +** Others do no. To be safe, we will stick with the (slightly slower) +** fsync(). If you know that your system does support fdatasync() correctly, +** then simply compile with -Dfdatasync=fdatasync +*/ +#if !defined(fdatasync) +#include "dfs.h" +#include "dfs_file.h" +int fdatasync(fd) +{ + struct dfs_fd *dfs_fd; + dfs_fd = fd_get(fd); + return dfs_file_flush(dfs_fd); +} +#endif + +/* +** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not +** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently +** only available on Mac OS X. But that could change. +*/ +#ifdef F_FULLFSYNC +# define HAVE_FULLFSYNC 0 +#endif + + +/* +** The fsync() system call does not work as advertised on many +** unix systems. The following procedure is an attempt to make +** it work better. +** +** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful +** for testing when we want to run through the test suite quickly. +** You are strongly advised *not* to deploy with SQLITE_NO_SYNC +** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash +** or power failure will likely corrupt the database file. +** +** SQLite sets the dataOnly flag if the size of the file is unchanged. +** The idea behind dataOnly is that it should only write the file content +** to disk, not the inode. We only set dataOnly if the file size is +** unchanged since the file size is part of the inode. However, +** Ted Ts'o tells us that fdatasync() will also write the inode if the +** file size has changed. The only real difference between fdatasync() +** and fsync(), Ted tells us, is that fdatasync() will not flush the +** inode if the mtime or owner or other inode attributes have changed. +** We only care about the file size, not the other file attributes, so +** as far as SQLite is concerned, an fdatasync() is always adequate. +** So, we always use fdatasync() if it is available, regardless of +** the value of the dataOnly flag. +*/ +static int full_fsync(int fd, int fullSync, int dataOnly){ + int rc; + + /* The following "ifdef/elif/else/" block has the same structure as + ** the one below. It is replicated here solely to avoid cluttering + ** up the real code with the UNUSED_PARAMETER() macros. + */ +#ifdef SQLITE_NO_SYNC + UNUSED_PARAMETER(fd); + UNUSED_PARAMETER(fullSync); + UNUSED_PARAMETER(dataOnly); +#elif HAVE_FULLFSYNC + UNUSED_PARAMETER(dataOnly); +#else + UNUSED_PARAMETER(fullSync); + UNUSED_PARAMETER(dataOnly); +#endif + + /* Record the number of times that we do a normal fsync() and + ** FULLSYNC. This is used during testing to verify that this procedure + ** gets called with the correct arguments. + */ +#ifdef SQLITE_TEST + if( fullSync ) sqlite3_fullsync_count++; + sqlite3_sync_count++; +#endif + + /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a + ** no-op + */ +#ifdef SQLITE_NO_SYNC + rc = SQLITE_OK; +#elif HAVE_FULLFSYNC + #error "rtthread not support FULLFSYNC" +#else + rc = fdatasync(fd); +#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */ + + return rc; +} + +/* +** Make sure all writes to a particular file are committed to disk. +** +** If dataOnly==0 then both the file itself and its metadata (file +** size, access time, etc) are synced. If dataOnly!=0 then only the +** file data is synced. +** +** Under Rtthread, also make sure that the directory entry for the file +** has been created by fsync-ing the directory that contains the file. +** If we do not do this and we encounter a power failure, the directory +** entry for the journal might not exist after we reboot. The next +** SQLite to access the file will not know that the journal exists (because +** the directory entry for the journal was never created) and the transaction +** will not roll back - possibly leading to database corruption. +*/ +static int rtthreadSync(sqlite3_file *id, int flags){ + int rc; + rtthreadFile *pFile = (rtthreadFile*)id; + + int isDataOnly = (flags&SQLITE_SYNC_DATAONLY); + int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL; + + /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ + assert((flags&0x0F)==SQLITE_SYNC_NORMAL + || (flags&0x0F)==SQLITE_SYNC_FULL + ); + + /* Rtthread cannot, but some systems may return SQLITE_FULL from here. This + ** line is to test that doing so does not cause any problems. + */ + SimulateDiskfullError( return SQLITE_FULL ); + + assert( pFile ); + OSTRACE(("SYNC %-3d\n", pFile->h)); + rc = full_fsync(pFile->h, isFullsync, isDataOnly); + SimulateIOError( rc=1 ); + if( rc ){ + pFile->lastErrno = errno; + return rtthreadLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath); + } + + /* Also fsync the directory containing the file if the DIRSYNC flag + ** is set. This is a one-time occurrence. Many systems (examples: AIX) + ** are unable to fsync a directory, so ignore errors on the fsync. + */ + if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){ + int dirfd; + OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath, + HAVE_FULLFSYNC, isFullsync)); + rc = osOpenDirectory(pFile->zPath, &dirfd); + if( rc==SQLITE_OK && dirfd>=0 ){ + full_fsync(dirfd, 0, 0); + robust_close(pFile, dirfd, __LINE__); + }else if( rc==SQLITE_CANTOPEN ){ + rc = SQLITE_OK; + } + pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC; + } + return rc; +} + +/* +** Truncate an open file to a specified size +*/ +static int rtthreadTruncate(sqlite3_file *id, i64 nByte){ + rtthreadFile *pFile = (rtthreadFile *)id; + int rc; + assert( pFile ); + SimulateIOError( return SQLITE_IOERR_TRUNCATE ); + + /* If the user has configured a chunk-size for this file, truncate the + ** file so that it consists of an integer number of chunks (i.e. the + ** actual file size after the operation may be larger than the requested + ** size). + */ + if( pFile->szChunk>0 ){ + nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; + } + + rc = robust_ftruncate(pFile->h, (off_t)nByte); + if( rc ){ + pFile->lastErrno = errno; + return rtthreadLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); + }else{ +#ifdef SQLITE_DEBUG + /* If we are doing a normal write to a database file (as opposed to + ** doing a hot-journal rollback or a write to some file other than a + ** normal database file) and we truncate the file to zero length, + ** that effectively updates the change counter. This might happen + ** when restoring a database using the backup API from a zero-length + ** source. + */ + if( pFile->inNormalWrite && nByte==0 ){ + pFile->transCntrChng = 1; + } +#endif + + return SQLITE_OK; + } +} + +/* +** Determine the current size of a file in bytes +*/ +static int rtthreadFileSize(sqlite3_file *id, i64 *pSize){ + int rc; + struct stat buf; + assert( id ); + rc = osFstat(((rtthreadFile*)id)->h, &buf); + SimulateIOError( rc=1 ); + if( rc!=0 ){ + ((rtthreadFile*)id)->lastErrno = errno; + return SQLITE_IOERR_FSTAT; + } + *pSize = buf.st_size; + + /* When opening a zero-size database, the findInodeInfo() procedure + ** writes a single byte into that file in order to work around a bug + ** in the OS-X msdos filesystem. In order to avoid problems with upper + ** layers, we need to report this file size as zero even though it is + ** really 1. Ticket #3260. + */ + if( *pSize==1 ) *pSize = 0; + + + return SQLITE_OK; +} + +/* +** This function is called to handle the SQLITE_FCNTL_SIZE_HINT +** file-control operation. Enlarge the database to nBytes in size +** (rounded up to the next chunk-size). If the database is already +** nBytes or larger, this routine is a no-op. +*/ +static int fcntlSizeHint(rtthreadFile *pFile, i64 nByte){ + if( pFile->szChunk>0 ){ + i64 nSize; /* Required file size */ + struct stat buf; /* Used to hold return values of fstat() */ + + if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT; + + nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk; + if( nSize>(i64)buf.st_size ){ + /* If the OS does not have posix_fallocate(), fake it. First use + ** ftruncate() to set the file size, then write a single byte to + ** the last byte in each block within the extended region. This + ** is the same technique used by glibc to implement posix_fallocate() + ** on systems that do not have a real fallocate() system call. + */ + int nBlk = buf.st_blksize; /* File-system block size */ + i64 iWrite; /* Next offset to write to */ + + if( robust_ftruncate(pFile->h, nSize) ){ + pFile->lastErrno = errno; + return rtthreadLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); + } + iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1; + while( iWritectrlFlags is set. +** +** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. +*/ +static void rtthreadModeBit(rtthreadFile *pFile, unsigned char mask, int *pArg){ + if( *pArg<0 ){ + *pArg = (pFile->ctrlFlags & mask)!=0; + }else if( (*pArg)==0 ){ + pFile->ctrlFlags &= ~mask; + }else{ + pFile->ctrlFlags |= mask; + } +} + +/* Forward declaration */ +static int rtthreadGetTempname(int nBuf, char *zBuf); + +/* +** Information and control of an open file handle. +*/ +static int rtthreadFileControl(sqlite3_file *id, int op, void *pArg){ + rtthreadFile *pFile = (rtthreadFile*)id; + switch( op ){ + case SQLITE_FCNTL_LOCKSTATE: { + *(int*)pArg = pFile->eFileLock; + return SQLITE_OK; + } + case SQLITE_LAST_ERRNO: { + *(int*)pArg = pFile->lastErrno; + return SQLITE_OK; + } + case SQLITE_FCNTL_CHUNK_SIZE: { + pFile->szChunk = *(int *)pArg; + return SQLITE_OK; + } + case SQLITE_FCNTL_SIZE_HINT: { + int rc; + SimulateIOErrorBenign(1); + rc = fcntlSizeHint(pFile, *(i64 *)pArg); + SimulateIOErrorBenign(0); + return rc; + } + case SQLITE_FCNTL_PERSIST_WAL: { + rtthreadModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg); + return SQLITE_OK; + } + case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { + rtthreadModeBit(pFile, UNIXFILE_PSOW, (int*)pArg); + return SQLITE_OK; + } + case SQLITE_FCNTL_VFSNAME: { + *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); + return SQLITE_OK; + } + case SQLITE_FCNTL_TEMPFILENAME: { + char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname ); + if( zTFile ){ + rtthreadGetTempname(pFile->pVfs->mxPathname, zTFile); + *(char**)pArg = zTFile; + } + return SQLITE_OK; + } +#ifdef SQLITE_DEBUG + /* The pager calls this method to signal that it has done + ** a rollback and that the database is therefore unchanged and + ** it hence it is OK for the transaction change counter to be + ** unchanged. + */ + case SQLITE_FCNTL_DB_UNCHANGED: { + ((rtthreadFile*)id)->dbUpdate = 0; + return SQLITE_OK; + } +#endif + } + return SQLITE_NOTFOUND; +} + +/* +** Return the sector size in bytes of the underlying block device for +** the specified file. This is almost always 512 bytes, but may be +** larger for some devices. +** +** SQLite code assumes this function cannot fail. It also assumes that +** if two files are created in the same file-system directory (i.e. +** a database and its journal file) that the sector size will be the +** same for both. +*/ +static int rtthreadSectorSize(sqlite3_file *NotUsed){ + UNUSED_PARAMETER(NotUsed); + return SQLITE_DEFAULT_SECTOR_SIZE; +} + + +/* +** Return the device characteristics for the file. +** +** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default. +** However, that choice is contraversial since technically the underlying +** file system does not always provide powersafe overwrites. (In other +** words, after a power-loss event, parts of the file that were never +** written might end up being altered.) However, non-PSOW behavior is very, +** very rare. And asserting PSOW makes a large reduction in the amount +** of required I/O for journaling, since a lot of padding is eliminated. +** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control +** available to turn it off and URI query parameter available to turn it off. +*/ +static int rtthreadDeviceCharacteristics(sqlite3_file *id){ + rtthreadFile *p = (rtthreadFile*)id; + int rc = 0; + + if( p->ctrlFlags & UNIXFILE_PSOW ){ + rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; + } + return rc; +} + +#ifndef SQLITE_OMIT_WAL +# error "WAL mode requires not support from the rt-thread, compile\ + with SQLITE_OMIT_WAL." +#else +# define rtthreadShmMap 0 +# define rtthreadShmLock 0 +# define rtthreadShmBarrier 0 +# define rtthreadShmUnmap 0 +#endif /* #ifndef SQLITE_OMIT_WAL */ + +#if SQLITE_MAX_MMAP_SIZE>0 +#error "rtthread not spportt mmap" +#endif /* SQLITE_MAX_MMAP_SIZE>0 */ + +/* +** If possible, return a pointer to a mapping of file fd starting at offset +** iOff. The mapping must be valid for at least nAmt bytes. +** +** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. +** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. +** Finally, if an error does occur, return an SQLite error code. The final +** value of *pp is undefined in this case. +** +** If this function does return a pointer, the caller must eventually +** release the reference by calling unixUnfetch(). +*/ +static int rtthreadFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ + + *pp = 0; + + return SQLITE_OK; +} + +/* +** If the third argument is non-NULL, then this function releases a +** reference obtained by an earlier call to unixFetch(). The second +** argument passed to this function must be the same as the corresponding +** argument that was passed to the unixFetch() invocation. +** +** Or, if the third argument is NULL, then this function is being called +** to inform the VFS layer that, according to POSIX, any existing mapping +** may now be invalid and should be unmapped. +*/ +static int rtthreadUnfetch(sqlite3_file *fd, i64 iOff, void *p){ + rtthreadFile *pFd = (rtthreadFile *)fd; /* The underlying database file */ + UNUSED_PARAMETER(iOff); + + return SQLITE_OK; +} + +/* +** Here ends the implementation of all sqlite3_file methods. +** +********************** End sqlite3_file Methods ******************************* +******************************************************************************/ + +/* +** This division contains definitions of sqlite3_io_methods objects that +** implement various file locking strategies. It also contains definitions +** of "finder" functions. A finder-function is used to locate the appropriate +** sqlite3_io_methods object for a particular database file. The pAppData +** field of the sqlite3_vfs VFS objects are initialized to be pointers to +** the correct finder-function for that VFS. +** +** Most finder functions return a pointer to a fixed sqlite3_io_methods +** object. The only interesting finder-function is autolockIoFinder, which +** looks at the filesystem type and tries to guess the best locking +** strategy from that. +** +** For finder-funtion F, two objects are created: +** +** (1) The real finder-function named "FImpt()". +** +** (2) A constant pointer to this function named just "F". +** +** +** A pointer to the F pointer is used as the pAppData value for VFS +** objects. We have to do this instead of letting pAppData point +** directly at the finder-function since C90 rules prevent a void* +** from be cast into a function pointer. +** +** +** Each instance of this macro generates two objects: +** +** * A constant sqlite3_io_methods object call METHOD that has locking +** methods CLOSE, LOCK, UNLOCK, CKRESLOCK. +** +** * An I/O method finder function called FINDER that returns a pointer +** to the METHOD object in the previous bullet. +*/ +#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \ +static const sqlite3_io_methods METHOD = { \ + VERSION, /* iVersion */ \ + CLOSE, /* xClose */ \ + rtthreadRead, /* xRead */ \ + rtthreadWrite, /* xWrite */ \ + rtthreadTruncate, /* xTruncate */ \ + rtthreadSync, /* xSync */ \ + rtthreadFileSize, /* xFileSize */ \ + LOCK, /* xLock */ \ + UNLOCK, /* xUnlock */ \ + CKLOCK, /* xCheckReservedLock */ \ + rtthreadFileControl, /* xFileControl */ \ + rtthreadSectorSize, /* xSectorSize */ \ + rtthreadDeviceCharacteristics, /* xDeviceCapabilities */ \ + rtthreadShmMap, /* xShmMap */ \ + rtthreadShmLock, /* xShmLock */ \ + rtthreadShmBarrier, /* xShmBarrier */ \ + rtthreadShmUnmap, /* xShmUnmap */ \ + rtthreadFetch, /* xFetch */ \ + rtthreadUnfetch, /* xUnfetch */ \ +}; \ +static const sqlite3_io_methods *FINDER##Impl(const char *z, rtthreadFile *p){ \ + UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \ + return &METHOD; \ +} \ +static const sqlite3_io_methods *(*const FINDER)(const char*,rtthreadFile *p) \ + = FINDER##Impl; + +/* +** Here are all of the sqlite3_io_methods objects for each of the +** locking strategies. Functions that return pointers to these methods +** are also created. +*/ +IOMETHODS( + nolockIoFinder, /* Finder function name */ + nolockIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + nolockClose, /* xClose method */ + nolockLock, /* xLock method */ + nolockUnlock, /* xUnlock method */ + nolockCheckReservedLock /* xCheckReservedLock method */ +) +IOMETHODS( + dotlockIoFinder, /* Finder function name */ + dotlockIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + dotlockClose, /* xClose method */ + dotlockLock, /* xLock method */ + dotlockUnlock, /* xUnlock method */ + dotlockCheckReservedLock /* xCheckReservedLock method */ +) + +#if SQLITE_ENABLE_LOCKING_STYLE +IOMETHODS( + flockIoFinder, /* Finder function name */ + flockIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + flockClose, /* xClose method */ + flockLock, /* xLock method */ + flockUnlock, /* xUnlock method */ + flockCheckReservedLock /* xCheckReservedLock method */ +) +#endif + +/* +** An abstract type for a pointer to a IO method finder function: +*/ +typedef const sqlite3_io_methods *(*finder_type)(const char*,rtthreadFile*); + + +/**************************************************************************** +**************************** sqlite3_vfs methods **************************** +** +** This division contains the implementation of methods on the +** sqlite3_vfs object. +*/ + +/* +** Initialize the contents of the rtthreadFile structure pointed to by pId. +*/ +static int fillInRtthreadFile( + sqlite3_vfs *pVfs, /* Pointer to vfs object */ + int h, /* Open file descriptor of file being opened */ + sqlite3_file *pId, /* Write to the rtthreadFile structure here */ + const char *zFilename, /* Name of the file being opened */ + int ctrlFlags /* Zero or more UNIXFILE_* values */ +){ + const sqlite3_io_methods *pLockingStyle; + rtthreadFile *pNew = (rtthreadFile *)pId; + int rc = SQLITE_OK; + + assert( pNew->pInode==NULL ); + + /* Usually the path zFilename should not be a relative pathname. The + ** exception is when opening the proxy "conch" file in builds that + ** include the special Apple locking styles. + */ + assert( zFilename==0 || zFilename[0]=='/' ); + + /* No locking occurs in temporary files */ + assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 ); + + OSTRACE(("OPEN %-3d %s\n", h, zFilename)); + pNew->h = h; + pNew->pVfs = pVfs; + pNew->zPath = zFilename; + pNew->ctrlFlags = (u8)ctrlFlags; + if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0), + "psow", SQLITE_POWERSAFE_OVERWRITE) ){ + pNew->ctrlFlags |= UNIXFILE_PSOW; + } + if( strcmp(pVfs->zName,"unix-excl")==0 ){ + pNew->ctrlFlags |= UNIXFILE_EXCL; + } + + if( ctrlFlags & UNIXFILE_NOLOCK ){ + pLockingStyle = &nolockIoMethods; + }else{ + pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); +#if SQLITE_ENABLE_LOCKING_STYLE + /* Cache zFilename in the locking context (AFP and dotlock override) for + ** proxyLock activation is possible (remote proxy is based on db name) + ** zFilename remains valid until file is closed, to support */ + pNew->lockingContext = (void*)zFilename; +#endif + } + + if( pLockingStyle == &dotlockIoMethods ){ + /* Dotfile locking uses the file path so it needs to be included in + ** the dotlockLockingContext + */ + char *zLockFile; + int nFilename; + assert( zFilename!=0 ); + nFilename = (int)strlen(zFilename) + 6; + zLockFile = (char *)sqlite3_malloc(nFilename); + if( zLockFile==0 ){ + rc = SQLITE_NOMEM; + }else{ + sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); + } + pNew->lockingContext = zLockFile; + } + + pNew->lastErrno = 0; + if( rc!=SQLITE_OK ){ + if( h>=0 ) robust_close(pNew, h, __LINE__); + }else{ + pNew->pMethod = pLockingStyle; + OpenCounter(+1); + verifyDbFile(pNew); + } + return rc; +} + +/* +** Return the name of a directory in which to put temporary files. +** If no suitable temporary file directory can be found, return NULL. +*/ +static const char* rtthreadTempFileDir(void){ + static const char *azDirs[] = { + 0, + "/sql", + "/sql/tmp" + "/tmp", + 0 /* List terminator */ + }; + unsigned int i; + struct stat buf; + const char *zDir = 0; + + azDirs[0] = sqlite3_temp_directory; + + for(i=0; imxPathname bytes. +*/ +static int rtthreadGetTempname(int nBuf, char *zBuf){ + static const unsigned char zChars[] = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"; + unsigned int i, j; + const char *zDir; + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. + */ + SimulateIOError( return SQLITE_IOERR ); + + zDir = rtthreadTempFileDir(); + if( zDir==0 ) zDir = "."; + + /* Check that the output buffer is large enough for the temporary file + ** name. If it is not, return SQLITE_ERROR. + */ + if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){ + return SQLITE_ERROR; + } + + do{ + sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir); + j = (int)strlen(zBuf); + sqlite3_randomness(15, &zBuf[j]); + for(i=0; i<15; i++, j++){ + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; + } + zBuf[j] = 0; + zBuf[j+1] = 0; + }while( osAccess(zBuf,0)==0 ); + return SQLITE_OK; +} + +/* +** Open the file zPath. +** +** Previously, the SQLite OS layer used three functions in place of this +** one: +** +** sqlite3OsOpenReadWrite(); +** sqlite3OsOpenReadOnly(); +** sqlite3OsOpenExclusive(); +** +** These calls correspond to the following combinations of flags: +** +** ReadWrite() -> (READWRITE | CREATE) +** ReadOnly() -> (READONLY) +** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE) +** +** The old OpenExclusive() accepted a boolean argument - "delFlag". If +** true, the file was configured to be automatically deleted when the +** file handle closed. To achieve the same effect using this new +** interface, add the DELETEONCLOSE flag to those specified above for +** OpenExclusive(). +*/ +static int rtthreadOpen( + sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ + const char *zPath, /* Pathname of file to be opened */ + sqlite3_file *pFile, /* The file descriptor to be filled in */ + int flags, /* Input flags to control the opening */ + int *pOutFlags /* Output flags returned to SQLite core */ +){ + rtthreadFile *p = (rtthreadFile *)pFile; + int fd = -1; /* File descriptor returned by open() */ + int openFlags = 0; /* Flags to pass to open() */ + int eType = flags&0xFFFFFF00; /* Type of file to open */ + int noLock; /* True to omit locking primitives */ + int rc = SQLITE_OK; /* Function Return Code */ + int ctrlFlags = 0; /* UNIXFILE_* flags */ + + int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); + int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); + int isCreate = (flags & SQLITE_OPEN_CREATE); + int isReadonly = (flags & SQLITE_OPEN_READONLY); + int isReadWrite = (flags & SQLITE_OPEN_READWRITE); +#if SQLITE_ENABLE_LOCKING_STYLE + int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY); +#endif + + /* If creating a master or main-file journal, this function will open + ** a file-descriptor on the directory too. The first time unixSync() + ** is called the directory file descriptor will be fsync()ed and close()d. + */ + int syncDir = (isCreate && ( + eType==SQLITE_OPEN_MASTER_JOURNAL + || eType==SQLITE_OPEN_MAIN_JOURNAL + || eType==SQLITE_OPEN_WAL + )); + + /* If argument zPath is a NULL pointer, this function is required to open + ** a temporary file. Use this buffer to store the file name in. + */ + char zTmpname[MAX_PATHNAME+2]; + const char *zName = zPath; + + /* Check the following statements are true: + ** + ** (a) Exactly one of the READWRITE and READONLY flags must be set, and + ** (b) if CREATE is set, then READWRITE must also be set, and + ** (c) if EXCLUSIVE is set, then CREATE must also be set. + ** (d) if DELETEONCLOSE is set, then CREATE must also be set. + */ + assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); + assert(isCreate==0 || isReadWrite); + assert(isExclusive==0 || isCreate); + assert(isDelete==0 || isCreate); + + /* The main DB, main journal, WAL file and master journal are never + ** automatically deleted. Nor are they ever temporary files. */ + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); + + /* Assert that the upper layer has set one of the "file-type" flags. */ + assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB + || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL + || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL + || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL + ); + + memset(p, 0, sizeof(rtthreadFile)); + if( !zName ){ + /* If zName is NULL, the upper layer is requesting a temp file. */ + assert(isDelete && !syncDir); + rc = rtthreadGetTempname(MAX_PATHNAME+2, zTmpname); + if( rc!=SQLITE_OK ){ + return rc; + } + zName = zTmpname; + + /* Generated temporary filenames are always double-zero terminated + ** for use by sqlite3_uri_parameter(). */ + assert( zName[strlen(zName)+1]==0 ); + } + + /* Determine the value of the flags parameter passed to POSIX function + ** open(). These must be calculated even if open() is not called, as + ** they may be stored as part of the file handle and used by the + ** 'conch file' locking functions later on. */ + if( isReadonly ) openFlags |= O_RDONLY; + if( isReadWrite ) openFlags |= O_RDWR; + if( isCreate ) openFlags |= O_CREAT; + if( isExclusive ) openFlags |= (O_EXCL|0/*O_NOFOLLOW8*/); + openFlags |= (0/*O_LARGEFILE*/|O_BINARY); + + if( fd<0 ){ + mode_t openMode = 0; /* Permissions to create file with */ + + fd = robust_open(zName, openFlags, openMode); + OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); + if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){ + /* Failed to open the file for read/write access. Try read-only. */ + flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); + openFlags &= ~(O_RDWR|O_CREAT); + flags |= SQLITE_OPEN_READONLY; + openFlags |= O_RDONLY; + isReadonly = 1; + fd = robust_open(zName, openFlags, openMode); + } + if( fd<0 ){ + rc = rtthreadLogError(SQLITE_CANTOPEN_BKPT, "open", zName); + goto open_finished; + } + } + assert( fd>=0 ); + if( pOutFlags ){ + *pOutFlags = flags; + } + + if( isDelete ){ + osUnlink(zName); + } +#if SQLITE_ENABLE_LOCKING_STYLE + else{ + p->openFlags = openFlags; + } +#endif + + noLock = eType!=SQLITE_OPEN_MAIN_DB; + + /* Set up appropriate ctrlFlags */ + if( isDelete ) ctrlFlags |= UNIXFILE_DELETE; + if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY; + if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK; + if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC; + if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI; + + rc = fillInRtthreadFile(pVfs, fd, pFile, zPath, ctrlFlags); + +open_finished: + + return rc; +} + + +/* +** Delete the file at zPath. If the dirSync argument is true, fsync() +** the directory after deleting the file. +*/ +static int rtthreadDelete( + sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ + const char *zPath, /* Name of file to be deleted */ + int dirSync /* If true, fsync() directory after deleting file */ +){ + int rc = SQLITE_OK; + UNUSED_PARAMETER(NotUsed); + SimulateIOError(return SQLITE_IOERR_DELETE); + if( osUnlink(zPath)==(-1) ){ + if( errno==ENOENT ){ + rc = SQLITE_IOERR_DELETE_NOENT; + }else{ + rc = rtthreadLogError(SQLITE_IOERR_DELETE, "unlink", zPath); + } + return rc; + } +#ifndef SQLITE_DISABLE_DIRSYNC + if( (dirSync & 1)!=0 ){ + int fd; + rc = osOpenDirectory(zPath, &fd); + if( rc==SQLITE_OK ){ + robust_close(0, fd, __LINE__); + }else if( rc==SQLITE_CANTOPEN ){ + rc = SQLITE_OK; + } + } +#endif + return rc; +} + +/* +** Test the existence of or access permissions of file zPath. The +** test performed depends on the value of flags: +** +** SQLITE_ACCESS_EXISTS: Return 1 if the file exists +** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable. +** SQLITE_ACCESS_READONLY: Return 1 if the file is readable. +** +** Otherwise return 0. +*/ +static int rtthreadAccess( + sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ + const char *zPath, /* Path of the file to examine */ + int flags, /* What do we want to learn about the zPath file? */ + int *pResOut /* Write result boolean here */ +){ + int amode = 0; + UNUSED_PARAMETER(NotUsed); + SimulateIOError( return SQLITE_IOERR_ACCESS; ); + switch( flags ){ + case SQLITE_ACCESS_EXISTS: + amode = F_OK; + break; + case SQLITE_ACCESS_READWRITE: + amode = W_OK|R_OK; + break; + case SQLITE_ACCESS_READ: + amode = R_OK; + break; + + default: + assert(!"Invalid flags argument"); + } + *pResOut = (osAccess(zPath, amode)==0); + if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){ + struct stat buf; + if( 0==osStat(zPath, &buf) && buf.st_size==0 ){ + *pResOut = 0; + } + } + return SQLITE_OK; +} + + +/* +** Turn a relative pathname into a full pathname. The relative path +** is stored as a nul-terminated string in the buffer pointed to by +** zPath. +** +** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes +** (in this case, MAX_PATHNAME bytes). The full-path is written to +** this buffer before returning. +*/ +static int rtthreadFullPathname( + sqlite3_vfs *pVfs, /* Pointer to vfs object */ + const char *zPath, /* Possibly relative input path */ + int nOut, /* Size of output buffer in bytes */ + char *zOut /* Output buffer */ +){ + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. This function could fail if, for example, the + ** current working directory has been unlinked. + */ + SimulateIOError( return SQLITE_ERROR ); + + assert( pVfs->mxPathname==MAX_PATHNAME ); + UNUSED_PARAMETER(pVfs); + + zOut[nOut-1] = '\0'; + if( zPath[0]=='/' ){ + sqlite3_snprintf(nOut, zOut, "%s", zPath); + }else{ + int nCwd; + if( osGetcwd(zOut, nOut-1)==0 ){ + return rtthreadLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath); + } + nCwd = (int)strlen(zOut); + sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath); + } + return SQLITE_OK; +} + + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +# error "rtthread not support load extension, compile with SQLITE_OMIT_WAL." +#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ + #define rtthreadDlOpen 0 + #define rtthreadDlError 0 + #define rtthreadDlSym 0 + #define rtthreadDlClose 0 +#endif + +/* +** Write nBuf bytes of random data to the supplied buffer zBuf. +*/ +static int rtthreadRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ + UNUSED_PARAMETER(NotUsed); + assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int))); + + /* We have to initialize zBuf to prevent valgrind from reporting + ** errors. The reports issued by valgrind are incorrect - we would + ** prefer that the randomness be increased by making use of the + ** uninitialized space in zBuf - but valgrind errors tend to worry + ** some users. Rather than argue, it seems easier just to initialize + ** the whole array and silence valgrind, even if that means less randomness + ** in the random seed. + ** + ** When testing, initializing zBuf[] to zero is all we do. That means + ** that we always use the same random number sequence. This makes the + ** tests repeatable. + */ + memset(zBuf, 0, nBuf); + { + int i; + char tick8, tick16; + tick8 = (char)rt_tick_get(); + tick16 = (char)(rt_tick_get() >> 8); + + for (i=0; iBITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is +** a hash table that will hold up to BITVEC_MXHASH distinct values. +** +** Otherwise, the value i is redirected into one of BITVEC_NPTR +** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap +** handles up to iDivisor separate values of i. apSub[0] holds +** values between 1 and iDivisor. apSub[1] holds values between +** iDivisor+1 and 2*iDivisor. apSub[N] holds values between +** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized +** to hold deal with values between 1 and iDivisor. +*/ +struct Bitvec { + u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */ + u32 nSet; /* Number of bits that are set - only valid for aHash + ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512, + ** this would be 125. */ + u32 iDivisor; /* Number of bits handled by each apSub[] entry. */ + /* Should >=0 for apSub element. */ + /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */ + /* For a BITVEC_SZ of 512, this would be 34,359,739. */ + union { + BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */ + u32 aHash[BITVEC_NINT]; /* Hash table representation */ + Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */ + } u; +}; + +/* +** Create a new bitmap object able to handle bits between 0 and iSize, +** inclusive. Return a pointer to the new object. Return NULL if +** malloc fails. +*/ +SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){ + Bitvec *p; + assert( sizeof(*p)==BITVEC_SZ ); + p = sqlite3MallocZero( sizeof(*p) ); + if( p ){ + p->iSize = iSize; + } + return p; +} + +/* +** Check to see if the i-th bit is set. Return true or false. +** If p is NULL (if the bitmap has not been created) or if +** i is out of range, then return false. +*/ +SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){ + if( p==0 ) return 0; + if( i>p->iSize || i==0 ) return 0; + i--; + while( p->iDivisor ){ + u32 bin = i/p->iDivisor; + i = i%p->iDivisor; + p = p->u.apSub[bin]; + if (!p) { + return 0; + } + } + if( p->iSize<=BITVEC_NBIT ){ + return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0; + } else{ + u32 h = BITVEC_HASH(i++); + while( p->u.aHash[h] ){ + if( p->u.aHash[h]==i ) return 1; + h = (h+1) % BITVEC_NINT; + } + return 0; + } +} + +/* +** Set the i-th bit. Return 0 on success and an error code if +** anything goes wrong. +** +** This routine might cause sub-bitmaps to be allocated. Failing +** to get the memory needed to hold the sub-bitmap is the only +** that can go wrong with an insert, assuming p and i are valid. +** +** The calling function must ensure that p is a valid Bitvec object +** and that the value for "i" is within range of the Bitvec object. +** Otherwise the behavior is undefined. +*/ +SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){ + u32 h; + if( p==0 ) return SQLITE_OK; + assert( i>0 ); + assert( i<=p->iSize ); + i--; + while((p->iSize > BITVEC_NBIT) && p->iDivisor) { + u32 bin = i/p->iDivisor; + i = i%p->iDivisor; + if( p->u.apSub[bin]==0 ){ + p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor ); + if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM; + } + p = p->u.apSub[bin]; + } + if( p->iSize<=BITVEC_NBIT ){ + p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1)); + return SQLITE_OK; + } + h = BITVEC_HASH(i++); + /* if there wasn't a hash collision, and this doesn't */ + /* completely fill the hash, then just add it without */ + /* worring about sub-dividing and re-hashing. */ + if( !p->u.aHash[h] ){ + if (p->nSet<(BITVEC_NINT-1)) { + goto bitvec_set_end; + } else { + goto bitvec_set_rehash; + } + } + /* there was a collision, check to see if it's already */ + /* in hash, if not, try to find a spot for it */ + do { + if( p->u.aHash[h]==i ) return SQLITE_OK; + h++; + if( h>=BITVEC_NINT ) h = 0; + } while( p->u.aHash[h] ); + /* we didn't find it in the hash. h points to the first */ + /* available free spot. check to see if this is going to */ + /* make our hash too "full". */ +bitvec_set_rehash: + if( p->nSet>=BITVEC_MXHASH ){ + unsigned int j; + int rc; + u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash)); + if( aiValues==0 ){ + return SQLITE_NOMEM; + }else{ + memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); + memset(p->u.apSub, 0, sizeof(p->u.apSub)); + p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR; + rc = sqlite3BitvecSet(p, i); + for(j=0; jnSet++; + p->u.aHash[h] = i; + return SQLITE_OK; +} + +/* +** Clear the i-th bit. +** +** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage +** that BitvecClear can use to rebuilt its hash table. +*/ +SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ + if( p==0 ) return; + assert( i>0 ); + i--; + while( p->iDivisor ){ + u32 bin = i/p->iDivisor; + i = i%p->iDivisor; + p = p->u.apSub[bin]; + if (!p) { + return; + } + } + if( p->iSize<=BITVEC_NBIT ){ + p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1))); + }else{ + unsigned int j; + u32 *aiValues = pBuf; + memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); + memset(p->u.aHash, 0, sizeof(p->u.aHash)); + p->nSet = 0; + for(j=0; jnSet++; + while( p->u.aHash[h] ){ + h++; + if( h>=BITVEC_NINT ) h = 0; + } + p->u.aHash[h] = aiValues[j]; + } + } + } +} + +/* +** Destroy a bitmap object. Reclaim all memory used. +*/ +SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){ + if( p==0 ) return; + if( p->iDivisor ){ + unsigned int i; + for(i=0; iu.apSub[i]); + } + } + sqlite3_free(p); +} + +/* +** Return the value of the iSize parameter specified when Bitvec *p +** was created. +*/ +SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){ + return p->iSize; +} + +#ifndef SQLITE_OMIT_BUILTIN_TEST +/* +** Let V[] be an array of unsigned characters sufficient to hold +** up to N bits. Let I be an integer between 0 and N. 0<=I>3] |= (1<<(I&7)) +#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7)) +#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0 + +/* +** This routine runs an extensive test of the Bitvec code. +** +** The input is an array of integers that acts as a program +** to test the Bitvec. The integers are opcodes followed +** by 0, 1, or 3 operands, depending on the opcode. Another +** opcode follows immediately after the last operand. +** +** There are 6 opcodes numbered from 0 through 5. 0 is the +** "halt" opcode and causes the test to end. +** +** 0 Halt and return the number of errors +** 1 N S X Set N bits beginning with S and incrementing by X +** 2 N S X Clear N bits beginning with S and incrementing by X +** 3 N Set N randomly chosen bits +** 4 N Clear N randomly chosen bits +** 5 N S X Set N bits from S increment X in array only, not in bitvec +** +** The opcodes 1 through 4 perform set and clear operations are performed +** on both a Bitvec object and on a linear array of bits obtained from malloc. +** Opcode 5 works on the linear array only, not on the Bitvec. +** Opcode 5 is used to deliberately induce a fault in order to +** confirm that error detection works. +** +** At the conclusion of the test the linear array is compared +** against the Bitvec object. If there are any differences, +** an error is returned. If they are the same, zero is returned. +** +** If a memory allocation error occurs, return -1. +*/ +SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ + Bitvec *pBitvec = 0; + unsigned char *pV = 0; + int rc = -1; + int i, nx, pc, op; + void *pTmpSpace; + + /* Allocate the Bitvec to be tested and a linear array of + ** bits to act as the reference */ + pBitvec = sqlite3BitvecCreate( sz ); + pV = sqlite3MallocZero( (sz+7)/8 + 1 ); + pTmpSpace = sqlite3_malloc(BITVEC_SZ); + if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end; + + /* NULL pBitvec tests */ + sqlite3BitvecSet(0, 1); + sqlite3BitvecClear(0, 1, pTmpSpace); + + /* Run the program */ + pc = 0; + while( (op = aOp[pc])!=0 ){ + switch( op ){ + case 1: + case 2: + case 5: { + nx = 4; + i = aOp[pc+2] - 1; + aOp[pc+2] += aOp[pc+3]; + break; + } + case 3: + case 4: + default: { + nx = 2; + sqlite3_randomness(sizeof(i), &i); + break; + } + } + if( (--aOp[pc+1]) > 0 ) nx = 0; + pc += nx; + i = (i & 0x7fffffff)%sz; + if( (op & 1)!=0 ){ + SETBIT(pV, (i+1)); + if( op!=5 ){ + if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end; + } + }else{ + CLEARBIT(pV, (i+1)); + sqlite3BitvecClear(pBitvec, i+1, pTmpSpace); + } + } + + /* Test to make sure the linear array exactly matches the + ** Bitvec object. Start with the assumption that they do + ** match (rc==0). Change rc to non-zero if a discrepancy + ** is found. + */ + rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1) + + sqlite3BitvecTest(pBitvec, 0) + + (sqlite3BitvecSize(pBitvec) - sz); + for(i=1; i<=sz; i++){ + if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){ + rc = i; + break; + } + } + + /* Free allocated structure */ +bitvec_end: + sqlite3_free(pTmpSpace); + sqlite3_free(pV); + sqlite3BitvecDestroy(pBitvec); + return rc; +} +#endif /* SQLITE_OMIT_BUILTIN_TEST */ + +/************** End of bitvec.c **********************************************/ +/************** Begin file pcache.c ******************************************/ +/* +** 2008 August 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements that page cache. +*/ + +/* +** A complete page cache is an instance of this structure. +*/ +struct PCache { + PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */ + PgHdr *pSynced; /* Last synced page in dirty page list */ + int nRef; /* Number of referenced pages */ + int szCache; /* Configured cache size */ + int szPage; /* Size of every page in this cache */ + int szExtra; /* Size of extra space for each page */ + int bPurgeable; /* True if pages are on backing store */ + int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */ + void *pStress; /* Argument to xStress */ + sqlite3_pcache *pCache; /* Pluggable cache module */ + PgHdr *pPage1; /* Reference to page 1 */ +}; + +/* +** Some of the assert() macros in this code are too expensive to run +** even during normal debugging. Use them only rarely on long-running +** tests. Enable the expensive asserts using the +** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option. +*/ +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT +# define expensive_assert(X) assert(X) +#else +# define expensive_assert(X) +#endif + +/********************************** Linked List Management ********************/ + +#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT) +/* +** Check that the pCache->pSynced variable is set correctly. If it +** is not, either fail an assert or return zero. Otherwise, return +** non-zero. This is only used in debugging builds, as follows: +** +** expensive_assert( pcacheCheckSynced(pCache) ); +*/ +static int pcacheCheckSynced(PCache *pCache){ + PgHdr *p; + for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){ + assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) ); + } + return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0); +} +#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */ + +/* +** Remove page pPage from the list of dirty pages. +*/ +static void pcacheRemoveFromDirtyList(PgHdr *pPage){ + PCache *p = pPage->pCache; + + assert( pPage->pDirtyNext || pPage==p->pDirtyTail ); + assert( pPage->pDirtyPrev || pPage==p->pDirty ); + + /* Update the PCache1.pSynced variable if necessary. */ + if( p->pSynced==pPage ){ + PgHdr *pSynced = pPage->pDirtyPrev; + while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){ + pSynced = pSynced->pDirtyPrev; + } + p->pSynced = pSynced; + } + + if( pPage->pDirtyNext ){ + pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev; + }else{ + assert( pPage==p->pDirtyTail ); + p->pDirtyTail = pPage->pDirtyPrev; + } + if( pPage->pDirtyPrev ){ + pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext; + }else{ + assert( pPage==p->pDirty ); + p->pDirty = pPage->pDirtyNext; + } + pPage->pDirtyNext = 0; + pPage->pDirtyPrev = 0; + + expensive_assert( pcacheCheckSynced(p) ); +} + +/* +** Add page pPage to the head of the dirty list (PCache1.pDirty is set to +** pPage). +*/ +static void pcacheAddToDirtyList(PgHdr *pPage){ + PCache *p = pPage->pCache; + + assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage ); + + pPage->pDirtyNext = p->pDirty; + if( pPage->pDirtyNext ){ + assert( pPage->pDirtyNext->pDirtyPrev==0 ); + pPage->pDirtyNext->pDirtyPrev = pPage; + } + p->pDirty = pPage; + if( !p->pDirtyTail ){ + p->pDirtyTail = pPage; + } + if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){ + p->pSynced = pPage; + } + expensive_assert( pcacheCheckSynced(p) ); +} + +/* +** Wrapper around the pluggable caches xUnpin method. If the cache is +** being used for an in-memory database, this function is a no-op. +*/ +static void pcacheUnpin(PgHdr *p){ + PCache *pCache = p->pCache; + if( pCache->bPurgeable ){ + if( p->pgno==1 ){ + pCache->pPage1 = 0; + } + sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0); + } +} + +/*************************************************** General Interfaces ****** +** +** Initialize and shutdown the page cache subsystem. Neither of these +** functions are threadsafe. +*/ +SQLITE_PRIVATE int sqlite3PcacheInitialize(void){ + if( sqlite3GlobalConfig.pcache2.xInit==0 ){ + /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the + ** built-in default page cache is used instead of the application defined + ** page cache. */ + sqlite3PCacheSetDefault(); + } + return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg); +} +SQLITE_PRIVATE void sqlite3PcacheShutdown(void){ + if( sqlite3GlobalConfig.pcache2.xShutdown ){ + /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */ + sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg); + } +} + +/* +** Return the size in bytes of a PCache object. +*/ +SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); } + +/* +** Create a new PCache object. Storage space to hold the object +** has already been allocated and is passed in as the p pointer. +** The caller discovers how much space needs to be allocated by +** calling sqlite3PcacheSize(). +*/ +SQLITE_PRIVATE void sqlite3PcacheOpen( + int szPage, /* Size of every page */ + int szExtra, /* Extra space associated with each page */ + int bPurgeable, /* True if pages are on backing store */ + int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */ + void *pStress, /* Argument to xStress */ + PCache *p /* Preallocated space for the PCache */ +){ + memset(p, 0, sizeof(PCache)); + p->szPage = szPage; + p->szExtra = szExtra; + p->bPurgeable = bPurgeable; + p->xStress = xStress; + p->pStress = pStress; + p->szCache = 100; +} + +/* +** Change the page size for PCache object. The caller must ensure that there +** are no outstanding page references when this function is called. +*/ +SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ + assert( pCache->nRef==0 && pCache->pDirty==0 ); + if( pCache->pCache ){ + sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); + pCache->pCache = 0; + pCache->pPage1 = 0; + } + pCache->szPage = szPage; +} + +/* +** Compute the number of pages of cache requested. +*/ +static int numberOfCachePages(PCache *p){ + if( p->szCache>=0 ){ + return p->szCache; + }else{ + return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra)); + } +} + +/* +** Try to obtain a page from the cache. +*/ +SQLITE_PRIVATE int sqlite3PcacheFetch( + PCache *pCache, /* Obtain the page from this cache */ + Pgno pgno, /* Page number to obtain */ + int createFlag, /* If true, create page if it does not exist already */ + PgHdr **ppPage /* Write the page here */ +){ + sqlite3_pcache_page *pPage = 0; + PgHdr *pPgHdr = 0; + int eCreate; + + assert( pCache!=0 ); + assert( createFlag==1 || createFlag==0 ); + assert( pgno>0 ); + + /* If the pluggable cache (sqlite3_pcache*) has not been allocated, + ** allocate it now. + */ + if( !pCache->pCache && createFlag ){ + sqlite3_pcache *p; + p = sqlite3GlobalConfig.pcache2.xCreate( + pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable + ); + if( !p ){ + return SQLITE_NOMEM; + } + sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache)); + pCache->pCache = p; + } + + eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty)); + if( pCache->pCache ){ + pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate); + } + + if( !pPage && eCreate==1 ){ + PgHdr *pPg; + + /* Find a dirty page to write-out and recycle. First try to find a + ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC + ** cleared), but if that is not possible settle for any other + ** unreferenced dirty page. + */ + expensive_assert( pcacheCheckSynced(pCache) ); + for(pPg=pCache->pSynced; + pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); + pPg=pPg->pDirtyPrev + ); + pCache->pSynced = pPg; + if( !pPg ){ + for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev); + } + if( pPg ){ + int rc; +#ifdef SQLITE_LOG_CACHE_SPILL + sqlite3_log(SQLITE_FULL, + "spill page %d making room for %d - cache used: %d/%d", + pPg->pgno, pgno, + sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache), + numberOfCachePages(pCache)); +#endif + rc = pCache->xStress(pCache->pStress, pPg); + if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){ + return rc; + } + } + + pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2); + } + + if( pPage ){ + pPgHdr = (PgHdr *)pPage->pExtra; + + if( !pPgHdr->pPage ){ + memset(pPgHdr, 0, sizeof(PgHdr)); + pPgHdr->pPage = pPage; + pPgHdr->pData = pPage->pBuf; + pPgHdr->pExtra = (void *)&pPgHdr[1]; + memset(pPgHdr->pExtra, 0, pCache->szExtra); + pPgHdr->pCache = pCache; + pPgHdr->pgno = pgno; + } + assert( pPgHdr->pCache==pCache ); + assert( pPgHdr->pgno==pgno ); + assert( pPgHdr->pData==pPage->pBuf ); + assert( pPgHdr->pExtra==(void *)&pPgHdr[1] ); + + if( 0==pPgHdr->nRef ){ + pCache->nRef++; + } + pPgHdr->nRef++; + if( pgno==1 ){ + pCache->pPage1 = pPgHdr; + } + } + *ppPage = pPgHdr; + return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK; +} + +/* +** Decrement the reference count on a page. If the page is clean and the +** reference count drops to 0, then it is made elible for recycling. +*/ +SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){ + assert( p->nRef>0 ); + p->nRef--; + if( p->nRef==0 ){ + PCache *pCache = p->pCache; + pCache->nRef--; + if( (p->flags&PGHDR_DIRTY)==0 ){ + pcacheUnpin(p); + }else{ + /* Move the page to the head of the dirty list. */ + pcacheRemoveFromDirtyList(p); + pcacheAddToDirtyList(p); + } + } +} + +/* +** Increase the reference count of a supplied page by 1. +*/ +SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){ + assert(p->nRef>0); + p->nRef++; +} + +/* +** Drop a page from the cache. There must be exactly one reference to the +** page. This function deletes that reference, so after it returns the +** page pointed to by p is invalid. +*/ +SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){ + PCache *pCache; + assert( p->nRef==1 ); + if( p->flags&PGHDR_DIRTY ){ + pcacheRemoveFromDirtyList(p); + } + pCache = p->pCache; + pCache->nRef--; + if( p->pgno==1 ){ + pCache->pPage1 = 0; + } + sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1); +} + +/* +** Make sure the page is marked as dirty. If it isn't dirty already, +** make it so. +*/ +SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){ + p->flags &= ~PGHDR_DONT_WRITE; + assert( p->nRef>0 ); + if( 0==(p->flags & PGHDR_DIRTY) ){ + p->flags |= PGHDR_DIRTY; + pcacheAddToDirtyList( p); + } +} + +/* +** Make sure the page is marked as clean. If it isn't clean already, +** make it so. +*/ +SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){ + if( (p->flags & PGHDR_DIRTY) ){ + pcacheRemoveFromDirtyList(p); + p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC); + if( p->nRef==0 ){ + pcacheUnpin(p); + } + } +} + +/* +** Make every page in the cache clean. +*/ +SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){ + PgHdr *p; + while( (p = pCache->pDirty)!=0 ){ + sqlite3PcacheMakeClean(p); + } +} + +/* +** Clear the PGHDR_NEED_SYNC flag from all dirty pages. +*/ +SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){ + PgHdr *p; + for(p=pCache->pDirty; p; p=p->pDirtyNext){ + p->flags &= ~PGHDR_NEED_SYNC; + } + pCache->pSynced = pCache->pDirtyTail; +} + +/* +** Change the page number of page p to newPgno. +*/ +SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){ + PCache *pCache = p->pCache; + assert( p->nRef>0 ); + assert( newPgno>0 ); + sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno); + p->pgno = newPgno; + if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){ + pcacheRemoveFromDirtyList(p); + pcacheAddToDirtyList(p); + } +} + +/* +** Drop every cache entry whose page number is greater than "pgno". The +** caller must ensure that there are no outstanding references to any pages +** other than page 1 with a page number greater than pgno. +** +** If there is a reference to page 1 and the pgno parameter passed to this +** function is 0, then the data area associated with page 1 is zeroed, but +** the page object is not dropped. +*/ +SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){ + if( pCache->pCache ){ + PgHdr *p; + PgHdr *pNext; + for(p=pCache->pDirty; p; p=pNext){ + pNext = p->pDirtyNext; + /* This routine never gets call with a positive pgno except right + ** after sqlite3PcacheCleanAll(). So if there are dirty pages, + ** it must be that pgno==0. + */ + assert( p->pgno>0 ); + if( ALWAYS(p->pgno>pgno) ){ + assert( p->flags&PGHDR_DIRTY ); + sqlite3PcacheMakeClean(p); + } + } + if( pgno==0 && pCache->pPage1 ){ + memset(pCache->pPage1->pData, 0, pCache->szPage); + pgno = 1; + } + sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1); + } +} + +/* +** Close a cache. +*/ +SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){ + if( pCache->pCache ){ + sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); + } +} + +/* +** Discard the contents of the cache. +*/ +SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){ + sqlite3PcacheTruncate(pCache, 0); +} + +/* +** Merge two lists of pages connected by pDirty and in pgno order. +** Do not both fixing the pDirtyPrev pointers. +*/ +static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){ + PgHdr result, *pTail; + pTail = &result; + while( pA && pB ){ + if( pA->pgnopgno ){ + pTail->pDirty = pA; + pTail = pA; + pA = pA->pDirty; + }else{ + pTail->pDirty = pB; + pTail = pB; + pB = pB->pDirty; + } + } + if( pA ){ + pTail->pDirty = pA; + }else if( pB ){ + pTail->pDirty = pB; + }else{ + pTail->pDirty = 0; + } + return result.pDirty; +} + +/* +** Sort the list of pages in accending order by pgno. Pages are +** connected by pDirty pointers. The pDirtyPrev pointers are +** corrupted by this sort. +** +** Since there cannot be more than 2^31 distinct pages in a database, +** there cannot be more than 31 buckets required by the merge sorter. +** One extra bucket is added to catch overflow in case something +** ever changes to make the previous sentence incorrect. +*/ +#define N_SORT_BUCKET 32 +static PgHdr *pcacheSortDirtyList(PgHdr *pIn){ + PgHdr *a[N_SORT_BUCKET], *p; + int i; + memset(a, 0, sizeof(a)); + while( pIn ){ + p = pIn; + pIn = p->pDirty; + p->pDirty = 0; + for(i=0; ALWAYS(ipDirty; p; p=p->pDirtyNext){ + p->pDirty = p->pDirtyNext; + } + return pcacheSortDirtyList(pCache->pDirty); +} + +/* +** Return the total number of referenced pages held by the cache. +*/ +SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){ + return pCache->nRef; +} + +/* +** Return the number of references to the page supplied as an argument. +*/ +SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){ + return p->nRef; +} + +/* +** Return the total number of pages in the cache. +*/ +SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){ + int nPage = 0; + if( pCache->pCache ){ + nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache); + } + return nPage; +} + +#ifdef SQLITE_TEST +/* +** Get the suggested cache-size value. +*/ +SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){ + return numberOfCachePages(pCache); +} +#endif + +/* +** Set the suggested cache-size value. +*/ +SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){ + pCache->szCache = mxPage; + if( pCache->pCache ){ + sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache, + numberOfCachePages(pCache)); + } +} + +/* +** Free up as much memory as possible from the page cache. +*/ +SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){ + if( pCache->pCache ){ + sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache); + } +} + +#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) +/* +** For all dirty pages currently in the cache, invoke the specified +** callback. This is only used if the SQLITE_CHECK_PAGES macro is +** defined. +*/ +SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){ + PgHdr *pDirty; + for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){ + xIter(pDirty); + } +} +#endif + +/************** End of pcache.c **********************************************/ +/************** Begin file pcache1.c *****************************************/ +/* +** 2008 November 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements the default page cache implementation (the +** sqlite3_pcache interface). It also contains part of the implementation +** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features. +** If the default page cache implementation is overriden, then neither of +** these two features are available. +*/ + + +typedef struct PCache1 PCache1; +typedef struct PgHdr1 PgHdr1; +typedef struct PgFreeslot PgFreeslot; +typedef struct PGroup PGroup; + +/* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set +** of one or more PCaches that are able to recycle each others unpinned +** pages when they are under memory pressure. A PGroup is an instance of +** the following object. +** +** This page cache implementation works in one of two modes: +** +** (1) Every PCache is the sole member of its own PGroup. There is +** one PGroup per PCache. +** +** (2) There is a single global PGroup that all PCaches are a member +** of. +** +** Mode 1 uses more memory (since PCache instances are not able to rob +** unused pages from other PCaches) but it also operates without a mutex, +** and is therefore often faster. Mode 2 requires a mutex in order to be +** threadsafe, but recycles pages more efficiently. +** +** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single +** PGroup which is the pcache1.grp global variable and its mutex is +** SQLITE_MUTEX_STATIC_LRU. +*/ +struct PGroup { + sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */ + unsigned int nMaxPage; /* Sum of nMax for purgeable caches */ + unsigned int nMinPage; /* Sum of nMin for purgeable caches */ + unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */ + unsigned int nCurrentPage; /* Number of purgeable pages allocated */ + PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */ +}; + +/* Each page cache is an instance of the following object. Every +** open database file (including each in-memory database and each +** temporary or transient database) has a single page cache which +** is an instance of this object. +** +** Pointers to structures of this type are cast and returned as +** opaque sqlite3_pcache* handles. +*/ +struct PCache1 { + /* Cache configuration parameters. Page size (szPage) and the purgeable + ** flag (bPurgeable) are set when the cache is created. nMax may be + ** modified at any time by a call to the pcache1Cachesize() method. + ** The PGroup mutex must be held when accessing nMax. + */ + PGroup *pGroup; /* PGroup this cache belongs to */ + int szPage; /* Size of allocated pages in bytes */ + int szExtra; /* Size of extra space in bytes */ + int bPurgeable; /* True if cache is purgeable */ + unsigned int nMin; /* Minimum number of pages reserved */ + unsigned int nMax; /* Configured "cache_size" value */ + unsigned int n90pct; /* nMax*9/10 */ + unsigned int iMaxKey; /* Largest key seen since xTruncate() */ + + /* Hash table of all pages. The following variables may only be accessed + ** when the accessor is holding the PGroup mutex. + */ + unsigned int nRecyclable; /* Number of pages in the LRU list */ + unsigned int nPage; /* Total number of pages in apHash */ + unsigned int nHash; /* Number of slots in apHash[] */ + PgHdr1 **apHash; /* Hash table for fast lookup by key */ +}; + +/* +** Each cache entry is represented by an instance of the following +** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of +** PgHdr1.pCache->szPage bytes is allocated directly before this structure +** in memory. +*/ +struct PgHdr1 { + sqlite3_pcache_page page; + unsigned int iKey; /* Key value (page number) */ + PgHdr1 *pNext; /* Next in hash table chain */ + PCache1 *pCache; /* Cache that currently owns this page */ + PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */ + PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */ +}; + +/* +** Free slots in the allocator used to divide up the buffer provided using +** the SQLITE_CONFIG_PAGECACHE mechanism. +*/ +struct PgFreeslot { + PgFreeslot *pNext; /* Next free slot */ +}; + +/* +** Global data used by this cache. +*/ +static SQLITE_WSD struct PCacheGlobal { + PGroup grp; /* The global PGroup for mode (2) */ + + /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The + ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all + ** fixed at sqlite3_initialize() time and do not require mutex protection. + ** The nFreeSlot and pFree values do require mutex protection. + */ + int isInit; /* True if initialized */ + int szSlot; /* Size of each free slot */ + int nSlot; /* The number of pcache slots */ + int nReserve; /* Try to keep nFreeSlot above this */ + void *pStart, *pEnd; /* Bounds of pagecache malloc range */ + /* Above requires no mutex. Use mutex below for variable that follow. */ + sqlite3_mutex *mutex; /* Mutex for accessing the following: */ + PgFreeslot *pFree; /* Free page blocks */ + int nFreeSlot; /* Number of unused pcache slots */ + /* The following value requires a mutex to change. We skip the mutex on + ** reading because (1) most platforms read a 32-bit integer atomically and + ** (2) even if an incorrect value is read, no great harm is done since this + ** is really just an optimization. */ + int bUnderPressure; /* True if low on PAGECACHE memory */ +} pcache1_g; + +/* +** All code in this file should access the global structure above via the +** alias "pcache1". This ensures that the WSD emulation is used when +** compiling for systems that do not support real WSD. +*/ +#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g)) + +/* +** Macros to enter and leave the PCache LRU mutex. +*/ +#define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex) +#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex) + +/******************************************************************************/ +/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/ + +/* +** This function is called during initialization if a static buffer is +** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE +** verb to sqlite3_config(). Parameter pBuf points to an allocation large +** enough to contain 'n' buffers of 'sz' bytes each. +** +** This routine is called from sqlite3_initialize() and so it is guaranteed +** to be serialized already. There is no need for further mutexing. +*/ +SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){ + if( pcache1.isInit ){ + PgFreeslot *p; + sz = ROUNDDOWN8(sz); + pcache1.szSlot = sz; + pcache1.nSlot = pcache1.nFreeSlot = n; + pcache1.nReserve = n>90 ? 10 : (n/10 + 1); + pcache1.pStart = pBuf; + pcache1.pFree = 0; + pcache1.bUnderPressure = 0; + while( n-- ){ + p = (PgFreeslot*)pBuf; + p->pNext = pcache1.pFree; + pcache1.pFree = p; + pBuf = (void*)&((char*)pBuf)[sz]; + } + pcache1.pEnd = pBuf; + } +} + +/* +** Malloc function used within this file to allocate space from the buffer +** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no +** such buffer exists or there is no space left in it, this function falls +** back to sqlite3Malloc(). +** +** Multiple threads can run this routine at the same time. Global variables +** in pcache1 need to be protected via mutex. +*/ +static void *pcache1Alloc(int nByte){ + void *p = 0; + assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); + sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte); + if( nByte<=pcache1.szSlot ){ + sqlite3_mutex_enter(pcache1.mutex); + p = (PgHdr1 *)pcache1.pFree; + if( p ){ + pcache1.pFree = pcache1.pFree->pNext; + pcache1.nFreeSlot--; + pcache1.bUnderPressure = pcache1.nFreeSlot=0 ); + sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1); + } + sqlite3_mutex_leave(pcache1.mutex); + } + if( p==0 ){ + /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get + ** it from sqlite3Malloc instead. + */ + p = sqlite3Malloc(nByte); +#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS + if( p ){ + int sz = sqlite3MallocSize(p); + sqlite3_mutex_enter(pcache1.mutex); + sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz); + sqlite3_mutex_leave(pcache1.mutex); + } +#endif + sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); + } + return p; +} + +/* +** Free an allocated buffer obtained from pcache1Alloc(). +*/ +static int pcache1Free(void *p){ + int nFreed = 0; + if( p==0 ) return 0; + if( p>=pcache1.pStart && ppNext = pcache1.pFree; + pcache1.pFree = pSlot; + pcache1.nFreeSlot++; + pcache1.bUnderPressure = pcache1.nFreeSlot=pcache1.pStart && ppGroup->mutex) ); + pcache1LeaveMutex(pCache->pGroup); +#ifdef SQLITE_PCACHE_SEPARATE_HEADER + pPg = pcache1Alloc(pCache->szPage); + p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra); + if( !pPg || !p ){ + pcache1Free(pPg); + sqlite3_free(p); + pPg = 0; + } +#else + pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra); + p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage]; +#endif + pcache1EnterMutex(pCache->pGroup); + + if( pPg ){ + p->page.pBuf = pPg; + p->page.pExtra = &p[1]; + if( pCache->bPurgeable ){ + pCache->pGroup->nCurrentPage++; + } + return p; + } + return 0; +} + +/* +** Free a page object allocated by pcache1AllocPage(). +** +** The pointer is allowed to be NULL, which is prudent. But it turns out +** that the current implementation happens to never call this routine +** with a NULL pointer, so we mark the NULL test with ALWAYS(). +*/ +static void pcache1FreePage(PgHdr1 *p){ + if( ALWAYS(p) ){ + PCache1 *pCache = p->pCache; + assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) ); + pcache1Free(p->page.pBuf); +#ifdef SQLITE_PCACHE_SEPARATE_HEADER + sqlite3_free(p); +#endif + if( pCache->bPurgeable ){ + pCache->pGroup->nCurrentPage--; + } + } +} + +/* +** Malloc function used by SQLite to obtain space from the buffer configured +** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer +** exists, this function falls back to sqlite3Malloc(). +*/ +SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){ + return pcache1Alloc(sz); +} + +/* +** Free an allocated buffer obtained from sqlite3PageMalloc(). +*/ +SQLITE_PRIVATE void sqlite3PageFree(void *p){ + pcache1Free(p); +} + + +/* +** Return true if it desirable to avoid allocating a new page cache +** entry. +** +** If memory was allocated specifically to the page cache using +** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then +** it is desirable to avoid allocating a new page cache entry because +** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient +** for all page cache needs and we should not need to spill the +** allocation onto the heap. +** +** Or, the heap is used for all page cache memory but the heap is +** under memory pressure, then again it is desirable to avoid +** allocating a new page cache entry in order to avoid stressing +** the heap even further. +*/ +static int pcache1UnderMemoryPressure(PCache1 *pCache){ + if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){ + return pcache1.bUnderPressure; + }else{ + return sqlite3HeapNearlyFull(); + } +} + +/******************************************************************************/ +/******** General Implementation Functions ************************************/ + +/* +** This function is used to resize the hash table used by the cache passed +** as the first argument. +** +** The PCache mutex must be held when this function is called. +*/ +static int pcache1ResizeHash(PCache1 *p){ + PgHdr1 **apNew; + unsigned int nNew; + unsigned int i; + + assert( sqlite3_mutex_held(p->pGroup->mutex) ); + + nNew = p->nHash*2; + if( nNew<256 ){ + nNew = 256; + } + + pcache1LeaveMutex(p->pGroup); + if( p->nHash ){ sqlite3BeginBenignMalloc(); } + apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew); + if( p->nHash ){ sqlite3EndBenignMalloc(); } + pcache1EnterMutex(p->pGroup); + if( apNew ){ + for(i=0; inHash; i++){ + PgHdr1 *pPage; + PgHdr1 *pNext = p->apHash[i]; + while( (pPage = pNext)!=0 ){ + unsigned int h = pPage->iKey % nNew; + pNext = pPage->pNext; + pPage->pNext = apNew[h]; + apNew[h] = pPage; + } + } + sqlite3_free(p->apHash); + p->apHash = apNew; + p->nHash = nNew; + } + + return (p->apHash ? SQLITE_OK : SQLITE_NOMEM); +} + +/* +** This function is used internally to remove the page pPage from the +** PGroup LRU list, if is part of it. If pPage is not part of the PGroup +** LRU list, then this function is a no-op. +** +** The PGroup mutex must be held when this function is called. +** +** If pPage is NULL then this routine is a no-op. +*/ +static void pcache1PinPage(PgHdr1 *pPage){ + PCache1 *pCache; + PGroup *pGroup; + + if( pPage==0 ) return; + pCache = pPage->pCache; + pGroup = pCache->pGroup; + assert( sqlite3_mutex_held(pGroup->mutex) ); + if( pPage->pLruNext || pPage==pGroup->pLruTail ){ + if( pPage->pLruPrev ){ + pPage->pLruPrev->pLruNext = pPage->pLruNext; + } + if( pPage->pLruNext ){ + pPage->pLruNext->pLruPrev = pPage->pLruPrev; + } + if( pGroup->pLruHead==pPage ){ + pGroup->pLruHead = pPage->pLruNext; + } + if( pGroup->pLruTail==pPage ){ + pGroup->pLruTail = pPage->pLruPrev; + } + pPage->pLruNext = 0; + pPage->pLruPrev = 0; + pPage->pCache->nRecyclable--; + } +} + + +/* +** Remove the page supplied as an argument from the hash table +** (PCache1.apHash structure) that it is currently stored in. +** +** The PGroup mutex must be held when this function is called. +*/ +static void pcache1RemoveFromHash(PgHdr1 *pPage){ + unsigned int h; + PCache1 *pCache = pPage->pCache; + PgHdr1 **pp; + + assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); + h = pPage->iKey % pCache->nHash; + for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext); + *pp = (*pp)->pNext; + + pCache->nPage--; +} + +/* +** If there are currently more than nMaxPage pages allocated, try +** to recycle pages to reduce the number allocated to nMaxPage. +*/ +static void pcache1EnforceMaxPage(PGroup *pGroup){ + assert( sqlite3_mutex_held(pGroup->mutex) ); + while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){ + PgHdr1 *p = pGroup->pLruTail; + assert( p->pCache->pGroup==pGroup ); + pcache1PinPage(p); + pcache1RemoveFromHash(p); + pcache1FreePage(p); + } +} + +/* +** Discard all pages from cache pCache with a page number (key value) +** greater than or equal to iLimit. Any pinned pages that meet this +** criteria are unpinned before they are discarded. +** +** The PCache mutex must be held when this function is called. +*/ +static void pcache1TruncateUnsafe( + PCache1 *pCache, /* The cache to truncate */ + unsigned int iLimit /* Drop pages with this pgno or larger */ +){ + TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */ + unsigned int h; + assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); + for(h=0; hnHash; h++){ + PgHdr1 **pp = &pCache->apHash[h]; + PgHdr1 *pPage; + while( (pPage = *pp)!=0 ){ + if( pPage->iKey>=iLimit ){ + pCache->nPage--; + *pp = pPage->pNext; + pcache1PinPage(pPage); + pcache1FreePage(pPage); + }else{ + pp = &pPage->pNext; + TESTONLY( nPage++; ) + } + } + } + assert( pCache->nPage==nPage ); +} + +/******************************************************************************/ +/******** sqlite3_pcache Methods **********************************************/ + +/* +** Implementation of the sqlite3_pcache.xInit method. +*/ +static int pcache1Init(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + assert( pcache1.isInit==0 ); + memset(&pcache1, 0, sizeof(pcache1)); + if( sqlite3GlobalConfig.bCoreMutex ){ + pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU); + pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM); + } + pcache1.grp.mxPinned = 10; + pcache1.isInit = 1; + return SQLITE_OK; +} + +/* +** Implementation of the sqlite3_pcache.xShutdown method. +** Note that the static mutex allocated in xInit does +** not need to be freed. +*/ +static void pcache1Shutdown(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + assert( pcache1.isInit!=0 ); + memset(&pcache1, 0, sizeof(pcache1)); +} + +/* +** Implementation of the sqlite3_pcache.xCreate method. +** +** Allocate a new cache. +*/ +static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ + PCache1 *pCache; /* The newly created page cache */ + PGroup *pGroup; /* The group the new page cache will belong to */ + int sz; /* Bytes of memory required to allocate the new cache */ + + /* + ** The separateCache variable is true if each PCache has its own private + ** PGroup. In other words, separateCache is true for mode (1) where no + ** mutexing is required. + ** + ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT + ** + ** * Always use a unified cache in single-threaded applications + ** + ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off) + ** use separate caches (mode-1) + */ +#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0 + const int separateCache = 0; +#else + int separateCache = sqlite3GlobalConfig.bCoreMutex>0; +#endif + + assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 ); + assert( szExtra < 300 ); + + sz = sizeof(PCache1) + sizeof(PGroup)*separateCache; + pCache = (PCache1 *)sqlite3MallocZero(sz); + if( pCache ){ + if( separateCache ){ + pGroup = (PGroup*)&pCache[1]; + pGroup->mxPinned = 10; + }else{ + pGroup = &pcache1.grp; + } + pCache->pGroup = pGroup; + pCache->szPage = szPage; + pCache->szExtra = szExtra; + pCache->bPurgeable = (bPurgeable ? 1 : 0); + if( bPurgeable ){ + pCache->nMin = 10; + pcache1EnterMutex(pGroup); + pGroup->nMinPage += pCache->nMin; + pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; + pcache1LeaveMutex(pGroup); + } + } + return (sqlite3_pcache *)pCache; +} + +/* +** Implementation of the sqlite3_pcache.xCachesize method. +** +** Configure the cache_size limit for a cache. +*/ +static void pcache1Cachesize(sqlite3_pcache *p, int nMax){ + PCache1 *pCache = (PCache1 *)p; + if( pCache->bPurgeable ){ + PGroup *pGroup = pCache->pGroup; + pcache1EnterMutex(pGroup); + pGroup->nMaxPage += (nMax - pCache->nMax); + pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; + pCache->nMax = nMax; + pCache->n90pct = pCache->nMax*9/10; + pcache1EnforceMaxPage(pGroup); + pcache1LeaveMutex(pGroup); + } +} + +/* +** Implementation of the sqlite3_pcache.xShrink method. +** +** Free up as much memory as possible. +*/ +static void pcache1Shrink(sqlite3_pcache *p){ + PCache1 *pCache = (PCache1*)p; + if( pCache->bPurgeable ){ + PGroup *pGroup = pCache->pGroup; + int savedMaxPage; + pcache1EnterMutex(pGroup); + savedMaxPage = pGroup->nMaxPage; + pGroup->nMaxPage = 0; + pcache1EnforceMaxPage(pGroup); + pGroup->nMaxPage = savedMaxPage; + pcache1LeaveMutex(pGroup); + } +} + +/* +** Implementation of the sqlite3_pcache.xPagecount method. +*/ +static int pcache1Pagecount(sqlite3_pcache *p){ + int n; + PCache1 *pCache = (PCache1*)p; + pcache1EnterMutex(pCache->pGroup); + n = pCache->nPage; + pcache1LeaveMutex(pCache->pGroup); + return n; +} + +/* +** Implementation of the sqlite3_pcache.xFetch method. +** +** Fetch a page by key value. +** +** Whether or not a new page may be allocated by this function depends on +** the value of the createFlag argument. 0 means do not allocate a new +** page. 1 means allocate a new page if space is easily available. 2 +** means to try really hard to allocate a new page. +** +** For a non-purgeable cache (a cache used as the storage for an in-memory +** database) there is really no difference between createFlag 1 and 2. So +** the calling function (pcache.c) will never have a createFlag of 1 on +** a non-purgeable cache. +** +** There are three different approaches to obtaining space for a page, +** depending on the value of parameter createFlag (which may be 0, 1 or 2). +** +** 1. Regardless of the value of createFlag, the cache is searched for a +** copy of the requested page. If one is found, it is returned. +** +** 2. If createFlag==0 and the page is not already in the cache, NULL is +** returned. +** +** 3. If createFlag is 1, and the page is not already in the cache, then +** return NULL (do not allocate a new page) if any of the following +** conditions are true: +** +** (a) the number of pages pinned by the cache is greater than +** PCache1.nMax, or +** +** (b) the number of pages pinned by the cache is greater than +** the sum of nMax for all purgeable caches, less the sum of +** nMin for all other purgeable caches, or +** +** 4. If none of the first three conditions apply and the cache is marked +** as purgeable, and if one of the following is true: +** +** (a) The number of pages allocated for the cache is already +** PCache1.nMax, or +** +** (b) The number of pages allocated for all purgeable caches is +** already equal to or greater than the sum of nMax for all +** purgeable caches, +** +** (c) The system is under memory pressure and wants to avoid +** unnecessary pages cache entry allocations +** +** then attempt to recycle a page from the LRU list. If it is the right +** size, return the recycled buffer. Otherwise, free the buffer and +** proceed to step 5. +** +** 5. Otherwise, allocate and return a new page buffer. +*/ +static sqlite3_pcache_page *pcache1Fetch( + sqlite3_pcache *p, + unsigned int iKey, + int createFlag +){ + unsigned int nPinned; + PCache1 *pCache = (PCache1 *)p; + PGroup *pGroup; + PgHdr1 *pPage = 0; + + assert( pCache->bPurgeable || createFlag!=1 ); + assert( pCache->bPurgeable || pCache->nMin==0 ); + assert( pCache->bPurgeable==0 || pCache->nMin==10 ); + assert( pCache->nMin==0 || pCache->bPurgeable ); + pcache1EnterMutex(pGroup = pCache->pGroup); + + /* Step 1: Search the hash table for an existing entry. */ + if( pCache->nHash>0 ){ + unsigned int h = iKey % pCache->nHash; + for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext); + } + + /* Step 2: Abort if no existing page is found and createFlag is 0 */ + if( pPage || createFlag==0 ){ + pcache1PinPage(pPage); + goto fetch_out; + } + + /* The pGroup local variable will normally be initialized by the + ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined, + ** then pcache1EnterMutex() is a no-op, so we have to initialize the + ** local variable here. Delaying the initialization of pGroup is an + ** optimization: The common case is to exit the module before reaching + ** this point. + */ +#ifdef SQLITE_MUTEX_OMIT + pGroup = pCache->pGroup; +#endif + + /* Step 3: Abort if createFlag is 1 but the cache is nearly full */ + assert( pCache->nPage >= pCache->nRecyclable ); + nPinned = pCache->nPage - pCache->nRecyclable; + assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage ); + assert( pCache->n90pct == pCache->nMax*9/10 ); + if( createFlag==1 && ( + nPinned>=pGroup->mxPinned + || nPinned>=pCache->n90pct + || pcache1UnderMemoryPressure(pCache) + )){ + goto fetch_out; + } + + if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){ + goto fetch_out; + } + assert( pCache->nHash>0 && pCache->apHash ); + + /* Step 4. Try to recycle a page. */ + if( pCache->bPurgeable && pGroup->pLruTail && ( + (pCache->nPage+1>=pCache->nMax) + || pGroup->nCurrentPage>=pGroup->nMaxPage + || pcache1UnderMemoryPressure(pCache) + )){ + PCache1 *pOther; + pPage = pGroup->pLruTail; + pcache1RemoveFromHash(pPage); + pcache1PinPage(pPage); + pOther = pPage->pCache; + + /* We want to verify that szPage and szExtra are the same for pOther + ** and pCache. Assert that we can verify this by comparing sums. */ + assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 ); + assert( pCache->szExtra<512 ); + assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 ); + assert( pOther->szExtra<512 ); + + if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){ + pcache1FreePage(pPage); + pPage = 0; + }else{ + pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable); + } + } + + /* Step 5. If a usable page buffer has still not been found, + ** attempt to allocate a new one. + */ + if( !pPage ){ + if( createFlag==1 ) sqlite3BeginBenignMalloc(); + pPage = pcache1AllocPage(pCache); + if( createFlag==1 ) sqlite3EndBenignMalloc(); + } + + if( pPage ){ + unsigned int h = iKey % pCache->nHash; + pCache->nPage++; + pPage->iKey = iKey; + pPage->pNext = pCache->apHash[h]; + pPage->pCache = pCache; + pPage->pLruPrev = 0; + pPage->pLruNext = 0; + *(void **)pPage->page.pExtra = 0; + pCache->apHash[h] = pPage; + } + +fetch_out: + if( pPage && iKey>pCache->iMaxKey ){ + pCache->iMaxKey = iKey; + } + pcache1LeaveMutex(pGroup); + return &pPage->page; +} + + +/* +** Implementation of the sqlite3_pcache.xUnpin method. +** +** Mark a page as unpinned (eligible for asynchronous recycling). +*/ +static void pcache1Unpin( + sqlite3_pcache *p, + sqlite3_pcache_page *pPg, + int reuseUnlikely +){ + PCache1 *pCache = (PCache1 *)p; + PgHdr1 *pPage = (PgHdr1 *)pPg; + PGroup *pGroup = pCache->pGroup; + + assert( pPage->pCache==pCache ); + pcache1EnterMutex(pGroup); + + /* It is an error to call this function if the page is already + ** part of the PGroup LRU list. + */ + assert( pPage->pLruPrev==0 && pPage->pLruNext==0 ); + assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage ); + + if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){ + pcache1RemoveFromHash(pPage); + pcache1FreePage(pPage); + }else{ + /* Add the page to the PGroup LRU list. */ + if( pGroup->pLruHead ){ + pGroup->pLruHead->pLruPrev = pPage; + pPage->pLruNext = pGroup->pLruHead; + pGroup->pLruHead = pPage; + }else{ + pGroup->pLruTail = pPage; + pGroup->pLruHead = pPage; + } + pCache->nRecyclable++; + } + + pcache1LeaveMutex(pCache->pGroup); +} + +/* +** Implementation of the sqlite3_pcache.xRekey method. +*/ +static void pcache1Rekey( + sqlite3_pcache *p, + sqlite3_pcache_page *pPg, + unsigned int iOld, + unsigned int iNew +){ + PCache1 *pCache = (PCache1 *)p; + PgHdr1 *pPage = (PgHdr1 *)pPg; + PgHdr1 **pp; + unsigned int h; + assert( pPage->iKey==iOld ); + assert( pPage->pCache==pCache ); + + pcache1EnterMutex(pCache->pGroup); + + h = iOld%pCache->nHash; + pp = &pCache->apHash[h]; + while( (*pp)!=pPage ){ + pp = &(*pp)->pNext; + } + *pp = pPage->pNext; + + h = iNew%pCache->nHash; + pPage->iKey = iNew; + pPage->pNext = pCache->apHash[h]; + pCache->apHash[h] = pPage; + if( iNew>pCache->iMaxKey ){ + pCache->iMaxKey = iNew; + } + + pcache1LeaveMutex(pCache->pGroup); +} + +/* +** Implementation of the sqlite3_pcache.xTruncate method. +** +** Discard all unpinned pages in the cache with a page number equal to +** or greater than parameter iLimit. Any pinned pages with a page number +** equal to or greater than iLimit are implicitly unpinned. +*/ +static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){ + PCache1 *pCache = (PCache1 *)p; + pcache1EnterMutex(pCache->pGroup); + if( iLimit<=pCache->iMaxKey ){ + pcache1TruncateUnsafe(pCache, iLimit); + pCache->iMaxKey = iLimit-1; + } + pcache1LeaveMutex(pCache->pGroup); +} + +/* +** Implementation of the sqlite3_pcache.xDestroy method. +** +** Destroy a cache allocated using pcache1Create(). +*/ +static void pcache1Destroy(sqlite3_pcache *p){ + PCache1 *pCache = (PCache1 *)p; + PGroup *pGroup = pCache->pGroup; + assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) ); + pcache1EnterMutex(pGroup); + pcache1TruncateUnsafe(pCache, 0); + assert( pGroup->nMaxPage >= pCache->nMax ); + pGroup->nMaxPage -= pCache->nMax; + assert( pGroup->nMinPage >= pCache->nMin ); + pGroup->nMinPage -= pCache->nMin; + pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; + pcache1EnforceMaxPage(pGroup); + pcache1LeaveMutex(pGroup); + sqlite3_free(pCache->apHash); + sqlite3_free(pCache); +} + +/* +** This function is called during initialization (sqlite3_initialize()) to +** install the default pluggable cache module, assuming the user has not +** already provided an alternative. +*/ +SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){ + static const sqlite3_pcache_methods2 defaultMethods = { + 1, /* iVersion */ + 0, /* pArg */ + pcache1Init, /* xInit */ + pcache1Shutdown, /* xShutdown */ + pcache1Create, /* xCreate */ + pcache1Cachesize, /* xCachesize */ + pcache1Pagecount, /* xPagecount */ + pcache1Fetch, /* xFetch */ + pcache1Unpin, /* xUnpin */ + pcache1Rekey, /* xRekey */ + pcache1Truncate, /* xTruncate */ + pcache1Destroy, /* xDestroy */ + pcache1Shrink /* xShrink */ + }; + sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods); +} + +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT +/* +** This function is called to free superfluous dynamically allocated memory +** held by the pager system. Memory in use by any SQLite pager allocated +** by the current thread may be sqlite3_free()ed. +** +** nReq is the number of bytes of memory required. Once this much has +** been released, the function returns. The return value is the total number +** of bytes of memory released. +*/ +SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){ + int nFree = 0; + assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); + assert( sqlite3_mutex_notheld(pcache1.mutex) ); + if( pcache1.pStart==0 ){ + PgHdr1 *p; + pcache1EnterMutex(&pcache1.grp); + while( (nReq<0 || nFreepage.pBuf); +#ifdef SQLITE_PCACHE_SEPARATE_HEADER + nFree += sqlite3MemSize(p); +#endif + pcache1PinPage(p); + pcache1RemoveFromHash(p); + pcache1FreePage(p); + } + pcache1LeaveMutex(&pcache1.grp); + } + return nFree; +} +#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */ + +#ifdef SQLITE_TEST +/* +** This function is used by test procedures to inspect the internal state +** of the global cache. +*/ +SQLITE_PRIVATE void sqlite3PcacheStats( + int *pnCurrent, /* OUT: Total number of pages cached */ + int *pnMax, /* OUT: Global maximum cache size */ + int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */ + int *pnRecyclable /* OUT: Total number of pages available for recycling */ +){ + PgHdr1 *p; + int nRecyclable = 0; + for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){ + nRecyclable++; + } + *pnCurrent = pcache1.grp.nCurrentPage; + *pnMax = (int)pcache1.grp.nMaxPage; + *pnMin = (int)pcache1.grp.nMinPage; + *pnRecyclable = nRecyclable; +} +#endif + +/************** End of pcache1.c *********************************************/ +/************** Begin file rowset.c ******************************************/ +/* +** 2008 December 3 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This module implements an object we call a "RowSet". +** +** The RowSet object is a collection of rowids. Rowids +** are inserted into the RowSet in an arbitrary order. Inserts +** can be intermixed with tests to see if a given rowid has been +** previously inserted into the RowSet. +** +** After all inserts are finished, it is possible to extract the +** elements of the RowSet in sorted order. Once this extraction +** process has started, no new elements may be inserted. +** +** Hence, the primitive operations for a RowSet are: +** +** CREATE +** INSERT +** TEST +** SMALLEST +** DESTROY +** +** The CREATE and DESTROY primitives are the constructor and destructor, +** obviously. The INSERT primitive adds a new element to the RowSet. +** TEST checks to see if an element is already in the RowSet. SMALLEST +** extracts the least value from the RowSet. +** +** The INSERT primitive might allocate additional memory. Memory is +** allocated in chunks so most INSERTs do no allocation. There is an +** upper bound on the size of allocated memory. No memory is freed +** until DESTROY. +** +** The TEST primitive includes a "batch" number. The TEST primitive +** will only see elements that were inserted before the last change +** in the batch number. In other words, if an INSERT occurs between +** two TESTs where the TESTs have the same batch nubmer, then the +** value added by the INSERT will not be visible to the second TEST. +** The initial batch number is zero, so if the very first TEST contains +** a non-zero batch number, it will see all prior INSERTs. +** +** No INSERTs may occurs after a SMALLEST. An assertion will fail if +** that is attempted. +** +** The cost of an INSERT is roughly constant. (Sometime new memory +** has to be allocated on an INSERT.) The cost of a TEST with a new +** batch number is O(NlogN) where N is the number of elements in the RowSet. +** The cost of a TEST using the same batch number is O(logN). The cost +** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST +** primitives are constant time. The cost of DESTROY is O(N). +** +** There is an added cost of O(N) when switching between TEST and +** SMALLEST primitives. +*/ + + +/* +** Target size for allocation chunks. +*/ +#define ROWSET_ALLOCATION_SIZE 1024 + +/* +** The number of rowset entries per allocation chunk. +*/ +#define ROWSET_ENTRY_PER_CHUNK \ + ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry)) + +/* +** Each entry in a RowSet is an instance of the following object. +** +** This same object is reused to store a linked list of trees of RowSetEntry +** objects. In that alternative use, pRight points to the next entry +** in the list, pLeft points to the tree, and v is unused. The +** RowSet.pForest value points to the head of this forest list. +*/ +struct RowSetEntry { + i64 v; /* ROWID value for this entry */ + struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */ + struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */ +}; + +/* +** RowSetEntry objects are allocated in large chunks (instances of the +** following structure) to reduce memory allocation overhead. The +** chunks are kept on a linked list so that they can be deallocated +** when the RowSet is destroyed. +*/ +struct RowSetChunk { + struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */ + struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */ +}; + +/* +** A RowSet in an instance of the following structure. +** +** A typedef of this structure if found in sqliteInt.h. +*/ +struct RowSet { + struct RowSetChunk *pChunk; /* List of all chunk allocations */ + sqlite3 *db; /* The database connection */ + struct RowSetEntry *pEntry; /* List of entries using pRight */ + struct RowSetEntry *pLast; /* Last entry on the pEntry list */ + struct RowSetEntry *pFresh; /* Source of new entry objects */ + struct RowSetEntry *pForest; /* List of binary trees of entries */ + u16 nFresh; /* Number of objects on pFresh */ + u8 rsFlags; /* Various flags */ + u8 iBatch; /* Current insert batch */ +}; + +/* +** Allowed values for RowSet.rsFlags +*/ +#define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */ +#define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */ + +/* +** Turn bulk memory into a RowSet object. N bytes of memory +** are available at pSpace. The db pointer is used as a memory context +** for any subsequent allocations that need to occur. +** Return a pointer to the new RowSet object. +** +** It must be the case that N is sufficient to make a Rowset. If not +** an assertion fault occurs. +** +** If N is larger than the minimum, use the surplus as an initial +** allocation of entries available to be filled. +*/ +SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){ + RowSet *p; + assert( N >= ROUND8(sizeof(*p)) ); + p = pSpace; + p->pChunk = 0; + p->db = db; + p->pEntry = 0; + p->pLast = 0; + p->pForest = 0; + p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); + p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); + p->rsFlags = ROWSET_SORTED; + p->iBatch = 0; + return p; +} + +/* +** Deallocate all chunks from a RowSet. This frees all memory that +** the RowSet has allocated over its lifetime. This routine is +** the destructor for the RowSet. +*/ +SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){ + struct RowSetChunk *pChunk, *pNextChunk; + for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){ + pNextChunk = pChunk->pNextChunk; + sqlite3DbFree(p->db, pChunk); + } + p->pChunk = 0; + p->nFresh = 0; + p->pEntry = 0; + p->pLast = 0; + p->pForest = 0; + p->rsFlags = ROWSET_SORTED; +} + +/* +** Allocate a new RowSetEntry object that is associated with the +** given RowSet. Return a pointer to the new and completely uninitialized +** objected. +** +** In an OOM situation, the RowSet.db->mallocFailed flag is set and this +** routine returns NULL. +*/ +static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){ + assert( p!=0 ); + if( p->nFresh==0 ){ + struct RowSetChunk *pNew; + pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew)); + if( pNew==0 ){ + return 0; + } + pNew->pNextChunk = p->pChunk; + p->pChunk = pNew; + p->pFresh = pNew->aEntry; + p->nFresh = ROWSET_ENTRY_PER_CHUNK; + } + p->nFresh--; + return p->pFresh++; +} + +/* +** Insert a new value into a RowSet. +** +** The mallocFailed flag of the database connection is set if a +** memory allocation fails. +*/ +SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){ + struct RowSetEntry *pEntry; /* The new entry */ + struct RowSetEntry *pLast; /* The last prior entry */ + + /* This routine is never called after sqlite3RowSetNext() */ + assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); + + pEntry = rowSetEntryAlloc(p); + if( pEntry==0 ) return; + pEntry->v = rowid; + pEntry->pRight = 0; + pLast = p->pLast; + if( pLast ){ + if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){ + p->rsFlags &= ~ROWSET_SORTED; + } + pLast->pRight = pEntry; + }else{ + p->pEntry = pEntry; + } + p->pLast = pEntry; +} + +/* +** Merge two lists of RowSetEntry objects. Remove duplicates. +** +** The input lists are connected via pRight pointers and are +** assumed to each already be in sorted order. +*/ +static struct RowSetEntry *rowSetEntryMerge( + struct RowSetEntry *pA, /* First sorted list to be merged */ + struct RowSetEntry *pB /* Second sorted list to be merged */ +){ + struct RowSetEntry head; + struct RowSetEntry *pTail; + + pTail = &head; + while( pA && pB ){ + assert( pA->pRight==0 || pA->v<=pA->pRight->v ); + assert( pB->pRight==0 || pB->v<=pB->pRight->v ); + if( pA->vv ){ + pTail->pRight = pA; + pA = pA->pRight; + pTail = pTail->pRight; + }else if( pB->vv ){ + pTail->pRight = pB; + pB = pB->pRight; + pTail = pTail->pRight; + }else{ + pA = pA->pRight; + } + } + if( pA ){ + assert( pA->pRight==0 || pA->v<=pA->pRight->v ); + pTail->pRight = pA; + }else{ + assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v ); + pTail->pRight = pB; + } + return head.pRight; +} + +/* +** Sort all elements on the list of RowSetEntry objects into order of +** increasing v. +*/ +static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){ + unsigned int i; + struct RowSetEntry *pNext, *aBucket[40]; + + memset(aBucket, 0, sizeof(aBucket)); + while( pIn ){ + pNext = pIn->pRight; + pIn->pRight = 0; + for(i=0; aBucket[i]; i++){ + pIn = rowSetEntryMerge(aBucket[i], pIn); + aBucket[i] = 0; + } + aBucket[i] = pIn; + pIn = pNext; + } + pIn = 0; + for(i=0; ipLeft ){ + struct RowSetEntry *p; + rowSetTreeToList(pIn->pLeft, ppFirst, &p); + p->pRight = pIn; + }else{ + *ppFirst = pIn; + } + if( pIn->pRight ){ + rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast); + }else{ + *ppLast = pIn; + } + assert( (*ppLast)->pRight==0 ); +} + + +/* +** Convert a sorted list of elements (connected by pRight) into a binary +** tree with depth of iDepth. A depth of 1 means the tree contains a single +** node taken from the head of *ppList. A depth of 2 means a tree with +** three nodes. And so forth. +** +** Use as many entries from the input list as required and update the +** *ppList to point to the unused elements of the list. If the input +** list contains too few elements, then construct an incomplete tree +** and leave *ppList set to NULL. +** +** Return a pointer to the root of the constructed binary tree. +*/ +static struct RowSetEntry *rowSetNDeepTree( + struct RowSetEntry **ppList, + int iDepth +){ + struct RowSetEntry *p; /* Root of the new tree */ + struct RowSetEntry *pLeft; /* Left subtree */ + if( *ppList==0 ){ + return 0; + } + if( iDepth==1 ){ + p = *ppList; + *ppList = p->pRight; + p->pLeft = p->pRight = 0; + return p; + } + pLeft = rowSetNDeepTree(ppList, iDepth-1); + p = *ppList; + if( p==0 ){ + return pLeft; + } + p->pLeft = pLeft; + *ppList = p->pRight; + p->pRight = rowSetNDeepTree(ppList, iDepth-1); + return p; +} + +/* +** Convert a sorted list of elements into a binary tree. Make the tree +** as deep as it needs to be in order to contain the entire list. +*/ +static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){ + int iDepth; /* Depth of the tree so far */ + struct RowSetEntry *p; /* Current tree root */ + struct RowSetEntry *pLeft; /* Left subtree */ + + assert( pList!=0 ); + p = pList; + pList = p->pRight; + p->pLeft = p->pRight = 0; + for(iDepth=1; pList; iDepth++){ + pLeft = p; + p = pList; + pList = p->pRight; + p->pLeft = pLeft; + p->pRight = rowSetNDeepTree(&pList, iDepth); + } + return p; +} + +/* +** Take all the entries on p->pEntry and on the trees in p->pForest and +** sort them all together into one big ordered list on p->pEntry. +** +** This routine should only be called once in the life of a RowSet. +*/ +static void rowSetToList(RowSet *p){ + + /* This routine is called only once */ + assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); + + if( (p->rsFlags & ROWSET_SORTED)==0 ){ + p->pEntry = rowSetEntrySort(p->pEntry); + } + + /* While this module could theoretically support it, sqlite3RowSetNext() + ** is never called after sqlite3RowSetText() for the same RowSet. So + ** there is never a forest to deal with. Should this change, simply + ** remove the assert() and the #if 0. */ + assert( p->pForest==0 ); +#if 0 + while( p->pForest ){ + struct RowSetEntry *pTree = p->pForest->pLeft; + if( pTree ){ + struct RowSetEntry *pHead, *pTail; + rowSetTreeToList(pTree, &pHead, &pTail); + p->pEntry = rowSetEntryMerge(p->pEntry, pHead); + } + p->pForest = p->pForest->pRight; + } +#endif + p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */ +} + +/* +** Extract the smallest element from the RowSet. +** Write the element into *pRowid. Return 1 on success. Return +** 0 if the RowSet is already empty. +** +** After this routine has been called, the sqlite3RowSetInsert() +** routine may not be called again. +*/ +SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ + assert( p!=0 ); + + /* Merge the forest into a single sorted list on first call */ + if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p); + + /* Return the next entry on the list */ + if( p->pEntry ){ + *pRowid = p->pEntry->v; + p->pEntry = p->pEntry->pRight; + if( p->pEntry==0 ){ + sqlite3RowSetClear(p); + } + return 1; + }else{ + return 0; + } +} + +/* +** Check to see if element iRowid was inserted into the rowset as +** part of any insert batch prior to iBatch. Return 1 or 0. +** +** If this is the first test of a new batch and if there exist entires +** on pRowSet->pEntry, then sort those entires into the forest at +** pRowSet->pForest so that they can be tested. +*/ +SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){ + struct RowSetEntry *p, *pTree; + + /* This routine is never called after sqlite3RowSetNext() */ + assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 ); + + /* Sort entries into the forest on the first test of a new batch + */ + if( iBatch!=pRowSet->iBatch ){ + p = pRowSet->pEntry; + if( p ){ + struct RowSetEntry **ppPrevTree = &pRowSet->pForest; + if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ + p = rowSetEntrySort(p); + } + for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ + ppPrevTree = &pTree->pRight; + if( pTree->pLeft==0 ){ + pTree->pLeft = rowSetListToTree(p); + break; + }else{ + struct RowSetEntry *pAux, *pTail; + rowSetTreeToList(pTree->pLeft, &pAux, &pTail); + pTree->pLeft = 0; + p = rowSetEntryMerge(pAux, p); + } + } + if( pTree==0 ){ + *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet); + if( pTree ){ + pTree->v = 0; + pTree->pRight = 0; + pTree->pLeft = rowSetListToTree(p); + } + } + pRowSet->pEntry = 0; + pRowSet->pLast = 0; + pRowSet->rsFlags |= ROWSET_SORTED; + } + pRowSet->iBatch = iBatch; + } + + /* Test to see if the iRowid value appears anywhere in the forest. + ** Return 1 if it does and 0 if not. + */ + for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ + p = pTree->pLeft; + while( p ){ + if( p->vpRight; + }else if( p->v>iRowid ){ + p = p->pLeft; + }else{ + return 1; + } + } + } + return 0; +} + +/************** End of rowset.c **********************************************/ +/************** Begin file pager.c *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the implementation of the page cache subsystem or "pager". +** +** The pager is used to access a database disk file. It implements +** atomic commit and rollback through the use of a journal file that +** is separate from the database file. The pager also implements file +** locking to prevent two processes from writing the same database +** file simultaneously, or one process from reading the database while +** another is writing. +*/ +#ifndef SQLITE_OMIT_DISKIO +/************** Include wal.h in the middle of pager.c ***********************/ +/************** Begin file wal.h *********************************************/ +/* +** 2010 February 1 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface to the write-ahead logging +** system. Refer to the comments below and the header comment attached to +** the implementation of each function in log.c for further details. +*/ + +#ifndef _WAL_H_ +#define _WAL_H_ + + +/* Additional values that can be added to the sync_flags argument of +** sqlite3WalFrames(): +*/ +#define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */ +#define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */ + +#ifdef SQLITE_OMIT_WAL +# define sqlite3WalOpen(x,y,z) 0 +# define sqlite3WalLimit(x,y) +# define sqlite3WalClose(w,x,y,z) 0 +# define sqlite3WalBeginReadTransaction(y,z) 0 +# define sqlite3WalEndReadTransaction(z) +# define sqlite3WalDbsize(y) 0 +# define sqlite3WalBeginWriteTransaction(y) 0 +# define sqlite3WalEndWriteTransaction(x) 0 +# define sqlite3WalUndo(x,y,z) 0 +# define sqlite3WalSavepoint(y,z) +# define sqlite3WalSavepointUndo(y,z) 0 +# define sqlite3WalFrames(u,v,w,x,y,z) 0 +# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0 +# define sqlite3WalCallback(z) 0 +# define sqlite3WalExclusiveMode(y,z) 0 +# define sqlite3WalHeapMemory(z) 0 +# define sqlite3WalFramesize(z) 0 +# define sqlite3WalFindFrame(x,y,z) 0 +#else + +#define WAL_SAVEPOINT_NDATA 4 + +/* Connection to a write-ahead log (WAL) file. +** There is one object of this type for each pager. +*/ +typedef struct Wal Wal; + +/* Open and close a connection to a write-ahead log. */ +SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**); +SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *); + +/* Set the limiting size of a WAL file. */ +SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64); + +/* Used by readers to open (lock) and close (unlock) a snapshot. A +** snapshot is like a read-transaction. It is the state of the database +** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and +** preserves the current state even if the other threads or processes +** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the +** transaction and releases the lock. +*/ +SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *); +SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal); + +/* Read a page from the write-ahead log, if it is present. */ +SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *); +SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *); + +/* If the WAL is not empty, return the size of the database. */ +SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal); + +/* Obtain or release the WRITER lock. */ +SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal); +SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal); + +/* Undo any frames written (but not committed) to the log */ +SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx); + +/* Return an integer that records the current (uncommitted) write +** position in the WAL */ +SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData); + +/* Move the write position of the WAL back to iFrame. Called in +** response to a ROLLBACK TO command. */ +SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData); + +/* Write a frame or frames to the log. */ +SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int); + +/* Copy pages from the log to the database file */ +SQLITE_PRIVATE int sqlite3WalCheckpoint( + Wal *pWal, /* Write-ahead log connection */ + int eMode, /* One of PASSIVE, FULL and RESTART */ + int (*xBusy)(void*), /* Function to call when busy */ + void *pBusyArg, /* Context argument for xBusyHandler */ + int sync_flags, /* Flags to sync db file with (or 0) */ + int nBuf, /* Size of buffer nBuf */ + u8 *zBuf, /* Temporary buffer to use */ + int *pnLog, /* OUT: Number of frames in WAL */ + int *pnCkpt /* OUT: Number of backfilled frames in WAL */ +); + +/* Return the value to pass to a sqlite3_wal_hook callback, the +** number of frames in the WAL at the point of the last commit since +** sqlite3WalCallback() was called. If no commits have occurred since +** the last call, then return 0. +*/ +SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal); + +/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released) +** by the pager layer on the database file. +*/ +SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op); + +/* Return true if the argument is non-NULL and the WAL module is using +** heap-memory for the wal-index. Otherwise, if the argument is NULL or the +** WAL module is using shared-memory, return false. +*/ +SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal); + +#ifdef SQLITE_ENABLE_ZIPVFS +/* If the WAL file is not empty, return the number of bytes of content +** stored in each frame (i.e. the db page-size when the WAL was created). +*/ +SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal); +#endif + +#endif /* ifndef SQLITE_OMIT_WAL */ +#endif /* _WAL_H_ */ + +/************** End of wal.h *************************************************/ +/************** Continuing where we left off in pager.c **********************/ + + +/******************* NOTES ON THE DESIGN OF THE PAGER ************************ +** +** This comment block describes invariants that hold when using a rollback +** journal. These invariants do not apply for journal_mode=WAL, +** journal_mode=MEMORY, or journal_mode=OFF. +** +** Within this comment block, a page is deemed to have been synced +** automatically as soon as it is written when PRAGMA synchronous=OFF. +** Otherwise, the page is not synced until the xSync method of the VFS +** is called successfully on the file containing the page. +** +** Definition: A page of the database file is said to be "overwriteable" if +** one or more of the following are true about the page: +** +** (a) The original content of the page as it was at the beginning of +** the transaction has been written into the rollback journal and +** synced. +** +** (b) The page was a freelist leaf page at the start of the transaction. +** +** (c) The page number is greater than the largest page that existed in +** the database file at the start of the transaction. +** +** (1) A page of the database file is never overwritten unless one of the +** following are true: +** +** (a) The page and all other pages on the same sector are overwriteable. +** +** (b) The atomic page write optimization is enabled, and the entire +** transaction other than the update of the transaction sequence +** number consists of a single page change. +** +** (2) The content of a page written into the rollback journal exactly matches +** both the content in the database when the rollback journal was written +** and the content in the database at the beginning of the current +** transaction. +** +** (3) Writes to the database file are an integer multiple of the page size +** in length and are aligned on a page boundary. +** +** (4) Reads from the database file are either aligned on a page boundary and +** an integer multiple of the page size in length or are taken from the +** first 100 bytes of the database file. +** +** (5) All writes to the database file are synced prior to the rollback journal +** being deleted, truncated, or zeroed. +** +** (6) If a master journal file is used, then all writes to the database file +** are synced prior to the master journal being deleted. +** +** Definition: Two databases (or the same database at two points it time) +** are said to be "logically equivalent" if they give the same answer to +** all queries. Note in particular the content of freelist leaf +** pages can be changed arbitarily without effecting the logical equivalence +** of the database. +** +** (7) At any time, if any subset, including the empty set and the total set, +** of the unsynced changes to a rollback journal are removed and the +** journal is rolled back, the resulting database file will be logical +** equivalent to the database file at the beginning of the transaction. +** +** (8) When a transaction is rolled back, the xTruncate method of the VFS +** is called to restore the database file to the same size it was at +** the beginning of the transaction. (In some VFSes, the xTruncate +** method is a no-op, but that does not change the fact the SQLite will +** invoke it.) +** +** (9) Whenever the database file is modified, at least one bit in the range +** of bytes from 24 through 39 inclusive will be changed prior to releasing +** the EXCLUSIVE lock, thus signaling other connections on the same +** database to flush their caches. +** +** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less +** than one billion transactions. +** +** (11) A database file is well-formed at the beginning and at the conclusion +** of every transaction. +** +** (12) An EXCLUSIVE lock is held on the database file when writing to +** the database file. +** +** (13) A SHARED lock is held on the database file while reading any +** content out of the database file. +** +******************************************************************************/ + +/* +** Macros for troubleshooting. Normally turned off +*/ +#if 0 +int sqlite3PagerTrace=1; /* True to enable tracing */ +#define sqlite3DebugPrintf printf +#define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; } +#else +#define PAGERTRACE(X) +#endif + +/* +** The following two macros are used within the PAGERTRACE() macros above +** to print out file-descriptors. +** +** PAGERID() takes a pointer to a Pager struct as its argument. The +** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file +** struct as its argument. +*/ +#define PAGERID(p) ((int)(p->fd)) +#define FILEHANDLEID(fd) ((int)fd) + +/* +** The Pager.eState variable stores the current 'state' of a pager. A +** pager may be in any one of the seven states shown in the following +** state diagram. +** +** OPEN <------+------+ +** | | | +** V | | +** +---------> READER-------+ | +** | | | +** | V | +** |<-------WRITER_LOCKED------> ERROR +** | | ^ +** | V | +** |<------WRITER_CACHEMOD-------->| +** | | | +** | V | +** |<-------WRITER_DBMOD---------->| +** | | | +** | V | +** +<------WRITER_FINISHED-------->+ +** +** +** List of state transitions and the C [function] that performs each: +** +** OPEN -> READER [sqlite3PagerSharedLock] +** READER -> OPEN [pager_unlock] +** +** READER -> WRITER_LOCKED [sqlite3PagerBegin] +** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal] +** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal] +** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne] +** WRITER_*** -> READER [pager_end_transaction] +** +** WRITER_*** -> ERROR [pager_error] +** ERROR -> OPEN [pager_unlock] +** +** +** OPEN: +** +** The pager starts up in this state. Nothing is guaranteed in this +** state - the file may or may not be locked and the database size is +** unknown. The database may not be read or written. +** +** * No read or write transaction is active. +** * Any lock, or no lock at all, may be held on the database file. +** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted. +** +** READER: +** +** In this state all the requirements for reading the database in +** rollback (non-WAL) mode are met. Unless the pager is (or recently +** was) in exclusive-locking mode, a user-level read transaction is +** open. The database size is known in this state. +** +** A connection running with locking_mode=normal enters this state when +** it opens a read-transaction on the database and returns to state +** OPEN after the read-transaction is completed. However a connection +** running in locking_mode=exclusive (including temp databases) remains in +** this state even after the read-transaction is closed. The only way +** a locking_mode=exclusive connection can transition from READER to OPEN +** is via the ERROR state (see below). +** +** * A read transaction may be active (but a write-transaction cannot). +** * A SHARED or greater lock is held on the database file. +** * The dbSize variable may be trusted (even if a user-level read +** transaction is not active). The dbOrigSize and dbFileSize variables +** may not be trusted at this point. +** * If the database is a WAL database, then the WAL connection is open. +** * Even if a read-transaction is not open, it is guaranteed that +** there is no hot-journal in the file-system. +** +** WRITER_LOCKED: +** +** The pager moves to this state from READER when a write-transaction +** is first opened on the database. In WRITER_LOCKED state, all locks +** required to start a write-transaction are held, but no actual +** modifications to the cache or database have taken place. +** +** In rollback mode, a RESERVED or (if the transaction was opened with +** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when +** moving to this state, but the journal file is not written to or opened +** to in this state. If the transaction is committed or rolled back while +** in WRITER_LOCKED state, all that is required is to unlock the database +** file. +** +** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file. +** If the connection is running with locking_mode=exclusive, an attempt +** is made to obtain an EXCLUSIVE lock on the database file. +** +** * A write transaction is active. +** * If the connection is open in rollback-mode, a RESERVED or greater +** lock is held on the database file. +** * If the connection is open in WAL-mode, a WAL write transaction +** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully +** called). +** * The dbSize, dbOrigSize and dbFileSize variables are all valid. +** * The contents of the pager cache have not been modified. +** * The journal file may or may not be open. +** * Nothing (not even the first header) has been written to the journal. +** +** WRITER_CACHEMOD: +** +** A pager moves from WRITER_LOCKED state to this state when a page is +** first modified by the upper layer. In rollback mode the journal file +** is opened (if it is not already open) and a header written to the +** start of it. The database file on disk has not been modified. +** +** * A write transaction is active. +** * A RESERVED or greater lock is held on the database file. +** * The journal file is open and the first header has been written +** to it, but the header has not been synced to disk. +** * The contents of the page cache have been modified. +** +** WRITER_DBMOD: +** +** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state +** when it modifies the contents of the database file. WAL connections +** never enter this state (since they do not modify the database file, +** just the log file). +** +** * A write transaction is active. +** * An EXCLUSIVE or greater lock is held on the database file. +** * The journal file is open and the first header has been written +** and synced to disk. +** * The contents of the page cache have been modified (and possibly +** written to disk). +** +** WRITER_FINISHED: +** +** It is not possible for a WAL connection to enter this state. +** +** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD +** state after the entire transaction has been successfully written into the +** database file. In this state the transaction may be committed simply +** by finalizing the journal file. Once in WRITER_FINISHED state, it is +** not possible to modify the database further. At this point, the upper +** layer must either commit or rollback the transaction. +** +** * A write transaction is active. +** * An EXCLUSIVE or greater lock is held on the database file. +** * All writing and syncing of journal and database data has finished. +** If no error occurred, all that remains is to finalize the journal to +** commit the transaction. If an error did occur, the caller will need +** to rollback the transaction. +** +** ERROR: +** +** The ERROR state is entered when an IO or disk-full error (including +** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it +** difficult to be sure that the in-memory pager state (cache contents, +** db size etc.) are consistent with the contents of the file-system. +** +** Temporary pager files may enter the ERROR state, but in-memory pagers +** cannot. +** +** For example, if an IO error occurs while performing a rollback, +** the contents of the page-cache may be left in an inconsistent state. +** At this point it would be dangerous to change back to READER state +** (as usually happens after a rollback). Any subsequent readers might +** report database corruption (due to the inconsistent cache), and if +** they upgrade to writers, they may inadvertently corrupt the database +** file. To avoid this hazard, the pager switches into the ERROR state +** instead of READER following such an error. +** +** Once it has entered the ERROR state, any attempt to use the pager +** to read or write data returns an error. Eventually, once all +** outstanding transactions have been abandoned, the pager is able to +** transition back to OPEN state, discarding the contents of the +** page-cache and any other in-memory state at the same time. Everything +** is reloaded from disk (and, if necessary, hot-journal rollback peformed) +** when a read-transaction is next opened on the pager (transitioning +** the pager into READER state). At that point the system has recovered +** from the error. +** +** Specifically, the pager jumps into the ERROR state if: +** +** 1. An error occurs while attempting a rollback. This happens in +** function sqlite3PagerRollback(). +** +** 2. An error occurs while attempting to finalize a journal file +** following a commit in function sqlite3PagerCommitPhaseTwo(). +** +** 3. An error occurs while attempting to write to the journal or +** database file in function pagerStress() in order to free up +** memory. +** +** In other cases, the error is returned to the b-tree layer. The b-tree +** layer then attempts a rollback operation. If the error condition +** persists, the pager enters the ERROR state via condition (1) above. +** +** Condition (3) is necessary because it can be triggered by a read-only +** statement executed within a transaction. In this case, if the error +** code were simply returned to the user, the b-tree layer would not +** automatically attempt a rollback, as it assumes that an error in a +** read-only statement cannot leave the pager in an internally inconsistent +** state. +** +** * The Pager.errCode variable is set to something other than SQLITE_OK. +** * There are one or more outstanding references to pages (after the +** last reference is dropped the pager should move back to OPEN state). +** * The pager is not an in-memory pager. +** +** +** Notes: +** +** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the +** connection is open in WAL mode. A WAL connection is always in one +** of the first four states. +** +** * Normally, a connection open in exclusive mode is never in PAGER_OPEN +** state. There are two exceptions: immediately after exclusive-mode has +** been turned on (and before any read or write transactions are +** executed), and when the pager is leaving the "error state". +** +** * See also: assert_pager_state(). +*/ +#define PAGER_OPEN 0 +#define PAGER_READER 1 +#define PAGER_WRITER_LOCKED 2 +#define PAGER_WRITER_CACHEMOD 3 +#define PAGER_WRITER_DBMOD 4 +#define PAGER_WRITER_FINISHED 5 +#define PAGER_ERROR 6 + +/* +** The Pager.eLock variable is almost always set to one of the +** following locking-states, according to the lock currently held on +** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. +** This variable is kept up to date as locks are taken and released by +** the pagerLockDb() and pagerUnlockDb() wrappers. +** +** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY +** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not +** the operation was successful. In these circumstances pagerLockDb() and +** pagerUnlockDb() take a conservative approach - eLock is always updated +** when unlocking the file, and only updated when locking the file if the +** VFS call is successful. This way, the Pager.eLock variable may be set +** to a less exclusive (lower) value than the lock that is actually held +** at the system level, but it is never set to a more exclusive value. +** +** This is usually safe. If an xUnlock fails or appears to fail, there may +** be a few redundant xLock() calls or a lock may be held for longer than +** required, but nothing really goes wrong. +** +** The exception is when the database file is unlocked as the pager moves +** from ERROR to OPEN state. At this point there may be a hot-journal file +** in the file-system that needs to be rolled back (as part of a OPEN->SHARED +** transition, by the same pager or any other). If the call to xUnlock() +** fails at this point and the pager is left holding an EXCLUSIVE lock, this +** can confuse the call to xCheckReservedLock() call made later as part +** of hot-journal detection. +** +** xCheckReservedLock() is defined as returning true "if there is a RESERVED +** lock held by this process or any others". So xCheckReservedLock may +** return true because the caller itself is holding an EXCLUSIVE lock (but +** doesn't know it because of a previous error in xUnlock). If this happens +** a hot-journal may be mistaken for a journal being created by an active +** transaction in another process, causing SQLite to read from the database +** without rolling it back. +** +** To work around this, if a call to xUnlock() fails when unlocking the +** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It +** is only changed back to a real locking state after a successful call +** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition +** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK +** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE +** lock on the database file before attempting to roll it back. See function +** PagerSharedLock() for more detail. +** +** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in +** PAGER_OPEN state. +*/ +#define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1) + +/* +** A macro used for invoking the codec if there is one +*/ +#ifdef SQLITE_HAS_CODEC +# define CODEC1(P,D,N,X,E) \ + if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; } +# define CODEC2(P,D,N,X,E,O) \ + if( P->xCodec==0 ){ O=(char*)D; }else \ + if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; } +#else +# define CODEC1(P,D,N,X,E) /* NO-OP */ +# define CODEC2(P,D,N,X,E,O) O=(char*)D +#endif + +/* +** The maximum allowed sector size. 64KiB. If the xSectorsize() method +** returns a value larger than this, then MAX_SECTOR_SIZE is used instead. +** This could conceivably cause corruption following a power failure on +** such a system. This is currently an undocumented limit. +*/ +#define MAX_SECTOR_SIZE 0x10000 + +/* +** An instance of the following structure is allocated for each active +** savepoint and statement transaction in the system. All such structures +** are stored in the Pager.aSavepoint[] array, which is allocated and +** resized using sqlite3Realloc(). +** +** When a savepoint is created, the PagerSavepoint.iHdrOffset field is +** set to 0. If a journal-header is written into the main journal while +** the savepoint is active, then iHdrOffset is set to the byte offset +** immediately following the last journal record written into the main +** journal before the journal-header. This is required during savepoint +** rollback (see pagerPlaybackSavepoint()). +*/ +typedef struct PagerSavepoint PagerSavepoint; +struct PagerSavepoint { + i64 iOffset; /* Starting offset in main journal */ + i64 iHdrOffset; /* See above */ + Bitvec *pInSavepoint; /* Set of pages in this savepoint */ + Pgno nOrig; /* Original number of pages in file */ + Pgno iSubRec; /* Index of first record in sub-journal */ +#ifndef SQLITE_OMIT_WAL + u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */ +#endif +}; + +/* +** Bits of the Pager.doNotSpill flag. See further description below. +*/ +#define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */ +#define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */ +#define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */ + +/* +** A open page cache is an instance of struct Pager. A description of +** some of the more important member variables follows: +** +** eState +** +** The current 'state' of the pager object. See the comment and state +** diagram above for a description of the pager state. +** +** eLock +** +** For a real on-disk database, the current lock held on the database file - +** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. +** +** For a temporary or in-memory database (neither of which require any +** locks), this variable is always set to EXCLUSIVE_LOCK. Since such +** databases always have Pager.exclusiveMode==1, this tricks the pager +** logic into thinking that it already has all the locks it will ever +** need (and no reason to release them). +** +** In some (obscure) circumstances, this variable may also be set to +** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for +** details. +** +** changeCountDone +** +** This boolean variable is used to make sure that the change-counter +** (the 4-byte header field at byte offset 24 of the database file) is +** not updated more often than necessary. +** +** It is set to true when the change-counter field is updated, which +** can only happen if an exclusive lock is held on the database file. +** It is cleared (set to false) whenever an exclusive lock is +** relinquished on the database file. Each time a transaction is committed, +** The changeCountDone flag is inspected. If it is true, the work of +** updating the change-counter is omitted for the current transaction. +** +** This mechanism means that when running in exclusive mode, a connection +** need only update the change-counter once, for the first transaction +** committed. +** +** setMaster +** +** When PagerCommitPhaseOne() is called to commit a transaction, it may +** (or may not) specify a master-journal name to be written into the +** journal file before it is synced to disk. +** +** Whether or not a journal file contains a master-journal pointer affects +** the way in which the journal file is finalized after the transaction is +** committed or rolled back when running in "journal_mode=PERSIST" mode. +** If a journal file does not contain a master-journal pointer, it is +** finalized by overwriting the first journal header with zeroes. If +** it does contain a master-journal pointer the journal file is finalized +** by truncating it to zero bytes, just as if the connection were +** running in "journal_mode=truncate" mode. +** +** Journal files that contain master journal pointers cannot be finalized +** simply by overwriting the first journal-header with zeroes, as the +** master journal pointer could interfere with hot-journal rollback of any +** subsequently interrupted transaction that reuses the journal file. +** +** The flag is cleared as soon as the journal file is finalized (either +** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the +** journal file from being successfully finalized, the setMaster flag +** is cleared anyway (and the pager will move to ERROR state). +** +** doNotSpill +** +** This variables control the behavior of cache-spills (calls made by +** the pcache module to the pagerStress() routine to write cached data +** to the file-system in order to free up memory). +** +** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set, +** writing to the database from pagerStress() is disabled altogether. +** The SPILLFLAG_ROLLBACK case is done in a very obscure case that +** comes up during savepoint rollback that requires the pcache module +** to allocate a new page to prevent the journal file from being written +** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF +** case is a user preference. +** +** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress() +** is permitted, but syncing the journal file is not. This flag is set +** by sqlite3PagerWrite() when the file-system sector-size is larger than +** the database page-size in order to prevent a journal sync from happening +** in between the journalling of two pages on the same sector. +** +** subjInMemory +** +** This is a boolean variable. If true, then any required sub-journal +** is opened as an in-memory journal file. If false, then in-memory +** sub-journals are only used for in-memory pager files. +** +** This variable is updated by the upper layer each time a new +** write-transaction is opened. +** +** dbSize, dbOrigSize, dbFileSize +** +** Variable dbSize is set to the number of pages in the database file. +** It is valid in PAGER_READER and higher states (all states except for +** OPEN and ERROR). +** +** dbSize is set based on the size of the database file, which may be +** larger than the size of the database (the value stored at offset +** 28 of the database header by the btree). If the size of the file +** is not an integer multiple of the page-size, the value stored in +** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2). +** Except, any file that is greater than 0 bytes in size is considered +** to have at least one page. (i.e. a 1KB file with 2K page-size leads +** to dbSize==1). +** +** During a write-transaction, if pages with page-numbers greater than +** dbSize are modified in the cache, dbSize is updated accordingly. +** Similarly, if the database is truncated using PagerTruncateImage(), +** dbSize is updated. +** +** Variables dbOrigSize and dbFileSize are valid in states +** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize +** variable at the start of the transaction. It is used during rollback, +** and to determine whether or not pages need to be journalled before +** being modified. +** +** Throughout a write-transaction, dbFileSize contains the size of +** the file on disk in pages. It is set to a copy of dbSize when the +** write-transaction is first opened, and updated when VFS calls are made +** to write or truncate the database file on disk. +** +** The only reason the dbFileSize variable is required is to suppress +** unnecessary calls to xTruncate() after committing a transaction. If, +** when a transaction is committed, the dbFileSize variable indicates +** that the database file is larger than the database image (Pager.dbSize), +** pager_truncate() is called. The pager_truncate() call uses xFilesize() +** to measure the database file on disk, and then truncates it if required. +** dbFileSize is not used when rolling back a transaction. In this case +** pager_truncate() is called unconditionally (which means there may be +** a call to xFilesize() that is not strictly required). In either case, +** pager_truncate() may cause the file to become smaller or larger. +** +** dbHintSize +** +** The dbHintSize variable is used to limit the number of calls made to +** the VFS xFileControl(FCNTL_SIZE_HINT) method. +** +** dbHintSize is set to a copy of the dbSize variable when a +** write-transaction is opened (at the same time as dbFileSize and +** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called, +** dbHintSize is increased to the number of pages that correspond to the +** size-hint passed to the method call. See pager_write_pagelist() for +** details. +** +** errCode +** +** The Pager.errCode variable is only ever used in PAGER_ERROR state. It +** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode +** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX +** sub-codes. +*/ +struct Pager { + sqlite3_vfs *pVfs; /* OS functions to use for IO */ + u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */ + u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */ + u8 useJournal; /* Use a rollback journal on this file */ + u8 noSync; /* Do not sync the journal if true */ + u8 fullSync; /* Do extra syncs of the journal for robustness */ + u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */ + u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */ + u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */ + u8 tempFile; /* zFilename is a temporary file */ + u8 readOnly; /* True for a read-only database */ + u8 memDb; /* True to inhibit all file I/O */ + + /************************************************************************** + ** The following block contains those class members that change during + ** routine opertion. Class members not in this block are either fixed + ** when the pager is first created or else only change when there is a + ** significant mode change (such as changing the page_size, locking_mode, + ** or the journal_mode). From another view, these class members describe + ** the "state" of the pager, while other class members describe the + ** "configuration" of the pager. + */ + u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */ + u8 eLock; /* Current lock held on database file */ + u8 changeCountDone; /* Set after incrementing the change-counter */ + u8 setMaster; /* True if a m-j name has been written to jrnl */ + u8 doNotSpill; /* Do not spill the cache when non-zero */ + u8 subjInMemory; /* True to use in-memory sub-journals */ + Pgno dbSize; /* Number of pages in the database */ + Pgno dbOrigSize; /* dbSize before the current transaction */ + Pgno dbFileSize; /* Number of pages in the database file */ + Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */ + int errCode; /* One of several kinds of errors */ + int nRec; /* Pages journalled since last j-header written */ + u32 cksumInit; /* Quasi-random value added to every checksum */ + u32 nSubRec; /* Number of records written to sub-journal */ + Bitvec *pInJournal; /* One bit for each page in the database file */ + sqlite3_file *fd; /* File descriptor for database */ + sqlite3_file *jfd; /* File descriptor for main journal */ + sqlite3_file *sjfd; /* File descriptor for sub-journal */ + i64 journalOff; /* Current write offset in the journal file */ + i64 journalHdr; /* Byte offset to previous journal header */ + sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */ + PagerSavepoint *aSavepoint; /* Array of active savepoints */ + int nSavepoint; /* Number of elements in aSavepoint[] */ + char dbFileVers[16]; /* Changes whenever database file changes */ + + u8 bUseFetch; /* True to use xFetch() */ + int nMmapOut; /* Number of mmap pages currently outstanding */ + sqlite3_int64 szMmap; /* Desired maximum mmap size */ + PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */ + /* + ** End of the routinely-changing class members + ***************************************************************************/ + + u16 nExtra; /* Add this many bytes to each in-memory page */ + i16 nReserve; /* Number of unused bytes at end of each page */ + u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */ + u32 sectorSize; /* Assumed sector size during rollback */ + int pageSize; /* Number of bytes in a page */ + Pgno mxPgno; /* Maximum allowed size of the database */ + i64 journalSizeLimit; /* Size limit for persistent journal files */ + char *zFilename; /* Name of the database file */ + char *zJournal; /* Name of the journal file */ + int (*xBusyHandler)(void*); /* Function to call when busy */ + void *pBusyHandlerArg; /* Context argument for xBusyHandler */ + int aStat[3]; /* Total cache hits, misses and writes */ +#ifdef SQLITE_TEST + int nRead; /* Database pages read */ +#endif + void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */ +#ifdef SQLITE_HAS_CODEC + void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ + void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ + void (*xCodecFree)(void*); /* Destructor for the codec */ + void *pCodec; /* First argument to xCodec... methods */ +#endif + char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */ + PCache *pPCache; /* Pointer to page cache object */ +#ifndef SQLITE_OMIT_WAL + Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */ + char *zWal; /* File name for write-ahead log */ +#endif +}; + +/* +** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains +** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS +** or CACHE_WRITE to sqlite3_db_status(). +*/ +#define PAGER_STAT_HIT 0 +#define PAGER_STAT_MISS 1 +#define PAGER_STAT_WRITE 2 + +/* +** The following global variables hold counters used for +** testing purposes only. These variables do not exist in +** a non-testing build. These variables are not thread-safe. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ +SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ +SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */ +# define PAGER_INCR(v) v++ +#else +# define PAGER_INCR(v) +#endif + + + +/* +** Journal files begin with the following magic string. The data +** was obtained from /dev/random. It is used only as a sanity check. +** +** Since version 2.8.0, the journal format contains additional sanity +** checking information. If the power fails while the journal is being +** written, semi-random garbage data might appear in the journal +** file after power is restored. If an attempt is then made +** to roll the journal back, the database could be corrupted. The additional +** sanity checking data is an attempt to discover the garbage in the +** journal and ignore it. +** +** The sanity checking information for the new journal format consists +** of a 32-bit checksum on each page of data. The checksum covers both +** the page number and the pPager->pageSize bytes of data for the page. +** This cksum is initialized to a 32-bit random value that appears in the +** journal file right after the header. The random initializer is important, +** because garbage data that appears at the end of a journal is likely +** data that was once in other files that have now been deleted. If the +** garbage data came from an obsolete journal file, the checksums might +** be correct. But by initializing the checksum to random value which +** is different for every journal, we minimize that risk. +*/ +static const unsigned char aJournalMagic[] = { + 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7, +}; + +/* +** The size of the of each page record in the journal is given by +** the following macro. +*/ +#define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8) + +/* +** The journal header size for this pager. This is usually the same +** size as a single disk sector. See also setSectorSize(). +*/ +#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize) + +/* +** The macro MEMDB is true if we are dealing with an in-memory database. +** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set, +** the value of MEMDB will be a constant and the compiler will optimize +** out code that would never execute. +*/ +#ifdef SQLITE_OMIT_MEMORYDB +# define MEMDB 0 +#else +# define MEMDB pPager->memDb +#endif + +/* +** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch +** interfaces to access the database using memory-mapped I/O. +*/ +#if SQLITE_MAX_MMAP_SIZE>0 +# define USEFETCH(x) ((x)->bUseFetch) +#else +# define USEFETCH(x) 0 +#endif + +/* +** The maximum legal page number is (2^31 - 1). +*/ +#define PAGER_MAX_PGNO 2147483647 + +/* +** The argument to this macro is a file descriptor (type sqlite3_file*). +** Return 0 if it is not open, or non-zero (but not 1) if it is. +** +** This is so that expressions can be written as: +** +** if( isOpen(pPager->jfd) ){ ... +** +** instead of +** +** if( pPager->jfd->pMethods ){ ... +*/ +#define isOpen(pFd) ((pFd)->pMethods) + +/* +** Return true if this pager uses a write-ahead log instead of the usual +** rollback journal. Otherwise false. +*/ +#ifndef SQLITE_OMIT_WAL +static int pagerUseWal(Pager *pPager){ + return (pPager->pWal!=0); +} +#else +# define pagerUseWal(x) 0 +# define pagerRollbackWal(x) 0 +# define pagerWalFrames(v,w,x,y) 0 +# define pagerOpenWalIfPresent(z) SQLITE_OK +# define pagerBeginReadTransaction(z) SQLITE_OK +#endif + +#ifndef NDEBUG +/* +** Usage: +** +** assert( assert_pager_state(pPager) ); +** +** This function runs many asserts to try to find inconsistencies in +** the internal state of the Pager object. +*/ +static int assert_pager_state(Pager *p){ + Pager *pPager = p; + + /* State must be valid. */ + assert( p->eState==PAGER_OPEN + || p->eState==PAGER_READER + || p->eState==PAGER_WRITER_LOCKED + || p->eState==PAGER_WRITER_CACHEMOD + || p->eState==PAGER_WRITER_DBMOD + || p->eState==PAGER_WRITER_FINISHED + || p->eState==PAGER_ERROR + ); + + /* Regardless of the current state, a temp-file connection always behaves + ** as if it has an exclusive lock on the database file. It never updates + ** the change-counter field, so the changeCountDone flag is always set. + */ + assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK ); + assert( p->tempFile==0 || pPager->changeCountDone ); + + /* If the useJournal flag is clear, the journal-mode must be "OFF". + ** And if the journal-mode is "OFF", the journal file must not be open. + */ + assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal ); + assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) ); + + /* Check that MEMDB implies noSync. And an in-memory journal. Since + ** this means an in-memory pager performs no IO at all, it cannot encounter + ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing + ** a journal file. (although the in-memory journal implementation may + ** return SQLITE_IOERR_NOMEM while the journal file is being written). It + ** is therefore not possible for an in-memory pager to enter the ERROR + ** state. + */ + if( MEMDB ){ + assert( p->noSync ); + assert( p->journalMode==PAGER_JOURNALMODE_OFF + || p->journalMode==PAGER_JOURNALMODE_MEMORY + ); + assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN ); + assert( pagerUseWal(p)==0 ); + } + + /* If changeCountDone is set, a RESERVED lock or greater must be held + ** on the file. + */ + assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK ); + assert( p->eLock!=PENDING_LOCK ); + + switch( p->eState ){ + case PAGER_OPEN: + assert( !MEMDB ); + assert( pPager->errCode==SQLITE_OK ); + assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile ); + break; + + case PAGER_READER: + assert( pPager->errCode==SQLITE_OK ); + assert( p->eLock!=UNKNOWN_LOCK ); + assert( p->eLock>=SHARED_LOCK ); + break; + + case PAGER_WRITER_LOCKED: + assert( p->eLock!=UNKNOWN_LOCK ); + assert( pPager->errCode==SQLITE_OK ); + if( !pagerUseWal(pPager) ){ + assert( p->eLock>=RESERVED_LOCK ); + } + assert( pPager->dbSize==pPager->dbOrigSize ); + assert( pPager->dbOrigSize==pPager->dbFileSize ); + assert( pPager->dbOrigSize==pPager->dbHintSize ); + assert( pPager->setMaster==0 ); + break; + + case PAGER_WRITER_CACHEMOD: + assert( p->eLock!=UNKNOWN_LOCK ); + assert( pPager->errCode==SQLITE_OK ); + if( !pagerUseWal(pPager) ){ + /* It is possible that if journal_mode=wal here that neither the + ** journal file nor the WAL file are open. This happens during + ** a rollback transaction that switches from journal_mode=off + ** to journal_mode=wal. + */ + assert( p->eLock>=RESERVED_LOCK ); + assert( isOpen(p->jfd) + || p->journalMode==PAGER_JOURNALMODE_OFF + || p->journalMode==PAGER_JOURNALMODE_WAL + ); + } + assert( pPager->dbOrigSize==pPager->dbFileSize ); + assert( pPager->dbOrigSize==pPager->dbHintSize ); + break; + + case PAGER_WRITER_DBMOD: + assert( p->eLock==EXCLUSIVE_LOCK ); + assert( pPager->errCode==SQLITE_OK ); + assert( !pagerUseWal(pPager) ); + assert( p->eLock>=EXCLUSIVE_LOCK ); + assert( isOpen(p->jfd) + || p->journalMode==PAGER_JOURNALMODE_OFF + || p->journalMode==PAGER_JOURNALMODE_WAL + ); + assert( pPager->dbOrigSize<=pPager->dbHintSize ); + break; + + case PAGER_WRITER_FINISHED: + assert( p->eLock==EXCLUSIVE_LOCK ); + assert( pPager->errCode==SQLITE_OK ); + assert( !pagerUseWal(pPager) ); + assert( isOpen(p->jfd) + || p->journalMode==PAGER_JOURNALMODE_OFF + || p->journalMode==PAGER_JOURNALMODE_WAL + ); + break; + + case PAGER_ERROR: + /* There must be at least one outstanding reference to the pager if + ** in ERROR state. Otherwise the pager should have already dropped + ** back to OPEN state. + */ + assert( pPager->errCode!=SQLITE_OK ); + assert( sqlite3PcacheRefCount(pPager->pPCache)>0 ); + break; + } + + return 1; +} +#endif /* ifndef NDEBUG */ + +#ifdef SQLITE_DEBUG +/* +** Return a pointer to a human readable string in a static buffer +** containing the state of the Pager object passed as an argument. This +** is intended to be used within debuggers. For example, as an alternative +** to "print *pPager" in gdb: +** +** (gdb) printf "%s", print_pager_state(pPager) +*/ +static char *print_pager_state(Pager *p){ + static char zRet[1024]; + + sqlite3_snprintf(1024, zRet, + "Filename: %s\n" + "State: %s errCode=%d\n" + "Lock: %s\n" + "Locking mode: locking_mode=%s\n" + "Journal mode: journal_mode=%s\n" + "Backing store: tempFile=%d memDb=%d useJournal=%d\n" + "Journal: journalOff=%lld journalHdr=%lld\n" + "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n" + , p->zFilename + , p->eState==PAGER_OPEN ? "OPEN" : + p->eState==PAGER_READER ? "READER" : + p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" : + p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" : + p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" : + p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" : + p->eState==PAGER_ERROR ? "ERROR" : "?error?" + , (int)p->errCode + , p->eLock==NO_LOCK ? "NO_LOCK" : + p->eLock==RESERVED_LOCK ? "RESERVED" : + p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" : + p->eLock==SHARED_LOCK ? "SHARED" : + p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?" + , p->exclusiveMode ? "exclusive" : "normal" + , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" : + p->journalMode==PAGER_JOURNALMODE_OFF ? "off" : + p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" : + p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" : + p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" : + p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?" + , (int)p->tempFile, (int)p->memDb, (int)p->useJournal + , p->journalOff, p->journalHdr + , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize + ); + + return zRet; +} +#endif + +/* +** Return true if it is necessary to write page *pPg into the sub-journal. +** A page needs to be written into the sub-journal if there exists one +** or more open savepoints for which: +** +** * The page-number is less than or equal to PagerSavepoint.nOrig, and +** * The bit corresponding to the page-number is not set in +** PagerSavepoint.pInSavepoint. +*/ +static int subjRequiresPage(PgHdr *pPg){ + Pager *pPager = pPg->pPager; + PagerSavepoint *p; + Pgno pgno; + int i; + if( pPager->nSavepoint ){ + pgno = pPg->pgno; + for(i=0; inSavepoint; i++){ + p = &pPager->aSavepoint[i]; + if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){ + return 1; + } + } + } + return 0; +} + +/* +** Return true if the page is already in the journal file. +*/ +static int pageInJournal(PgHdr *pPg){ + return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno); +} + +/* +** Read a 32-bit integer from the given file descriptor. Store the integer +** that is read in *pRes. Return SQLITE_OK if everything worked, or an +** error code is something goes wrong. +** +** All values are stored on disk as big-endian. +*/ +static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){ + unsigned char ac[4]; + int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset); + if( rc==SQLITE_OK ){ + *pRes = sqlite3Get4byte(ac); + } + return rc; +} + +/* +** Write a 32-bit integer into a string buffer in big-endian byte order. +*/ +#define put32bits(A,B) sqlite3Put4byte((u8*)A,B) + + +/* +** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK +** on success or an error code is something goes wrong. +*/ +static int write32bits(sqlite3_file *fd, i64 offset, u32 val){ + char ac[4]; + put32bits(ac, val); + return sqlite3OsWrite(fd, ac, 4, offset); +} + +/* +** Unlock the database file to level eLock, which must be either NO_LOCK +** or SHARED_LOCK. Regardless of whether or not the call to xUnlock() +** succeeds, set the Pager.eLock variable to match the (attempted) new lock. +** +** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is +** called, do not modify it. See the comment above the #define of +** UNKNOWN_LOCK for an explanation of this. +*/ +static int pagerUnlockDb(Pager *pPager, int eLock){ + int rc = SQLITE_OK; + + assert( !pPager->exclusiveMode || pPager->eLock==eLock ); + assert( eLock==NO_LOCK || eLock==SHARED_LOCK ); + assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 ); + if( isOpen(pPager->fd) ){ + assert( pPager->eLock>=eLock ); + rc = sqlite3OsUnlock(pPager->fd, eLock); + if( pPager->eLock!=UNKNOWN_LOCK ){ + pPager->eLock = (u8)eLock; + } + IOTRACE(("UNLOCK %p %d\n", pPager, eLock)) + } + return rc; +} + +/* +** Lock the database file to level eLock, which must be either SHARED_LOCK, +** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the +** Pager.eLock variable to the new locking state. +** +** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is +** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. +** See the comment above the #define of UNKNOWN_LOCK for an explanation +** of this. +*/ +static int pagerLockDb(Pager *pPager, int eLock){ + int rc = SQLITE_OK; + + assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK ); + if( pPager->eLockeLock==UNKNOWN_LOCK ){ + rc = sqlite3OsLock(pPager->fd, eLock); + if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){ + pPager->eLock = (u8)eLock; + IOTRACE(("LOCK %p %d\n", pPager, eLock)) + } + } + return rc; +} + +/* +** This function determines whether or not the atomic-write optimization +** can be used with this pager. The optimization can be used if: +** +** (a) the value returned by OsDeviceCharacteristics() indicates that +** a database page may be written atomically, and +** (b) the value returned by OsSectorSize() is less than or equal +** to the page size. +** +** The optimization is also always enabled for temporary files. It is +** an error to call this function if pPager is opened on an in-memory +** database. +** +** If the optimization cannot be used, 0 is returned. If it can be used, +** then the value returned is the size of the journal file when it +** contains rollback data for exactly one page. +*/ +#ifdef SQLITE_ENABLE_ATOMIC_WRITE +static int jrnlBufferSize(Pager *pPager){ + assert( !MEMDB ); + if( !pPager->tempFile ){ + int dc; /* Device characteristics */ + int nSector; /* Sector size */ + int szPage; /* Page size */ + + assert( isOpen(pPager->fd) ); + dc = sqlite3OsDeviceCharacteristics(pPager->fd); + nSector = pPager->sectorSize; + szPage = pPager->pageSize; + + assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); + assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); + if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){ + return 0; + } + } + + return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager); +} +#endif + +/* +** If SQLITE_CHECK_PAGES is defined then we do some sanity checking +** on the cache using a hash function. This is used for testing +** and debugging only. +*/ +#ifdef SQLITE_CHECK_PAGES +/* +** Return a 32-bit hash of the page data for pPage. +*/ +static u32 pager_datahash(int nByte, unsigned char *pData){ + u32 hash = 0; + int i; + for(i=0; ipPager->pageSize, (unsigned char *)pPage->pData); +} +static void pager_set_pagehash(PgHdr *pPage){ + pPage->pageHash = pager_pagehash(pPage); +} + +/* +** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES +** is defined, and NDEBUG is not defined, an assert() statement checks +** that the page is either dirty or still matches the calculated page-hash. +*/ +#define CHECK_PAGE(x) checkPage(x) +static void checkPage(PgHdr *pPg){ + Pager *pPager = pPg->pPager; + assert( pPager->eState!=PAGER_ERROR ); + assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) ); +} + +#else +#define pager_datahash(X,Y) 0 +#define pager_pagehash(X) 0 +#define pager_set_pagehash(X) +#define CHECK_PAGE(x) +#endif /* SQLITE_CHECK_PAGES */ + +/* +** When this is called the journal file for pager pPager must be open. +** This function attempts to read a master journal file name from the +** end of the file and, if successful, copies it into memory supplied +** by the caller. See comments above writeMasterJournal() for the format +** used to store a master journal file name at the end of a journal file. +** +** zMaster must point to a buffer of at least nMaster bytes allocated by +** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is +** enough space to write the master journal name). If the master journal +** name in the journal is longer than nMaster bytes (including a +** nul-terminator), then this is handled as if no master journal name +** were present in the journal. +** +** If a master journal file name is present at the end of the journal +** file, then it is copied into the buffer pointed to by zMaster. A +** nul-terminator byte is appended to the buffer following the master +** journal file name. +** +** If it is determined that no master journal file name is present +** zMaster[0] is set to 0 and SQLITE_OK returned. +** +** If an error occurs while reading from the journal file, an SQLite +** error code is returned. +*/ +static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){ + int rc; /* Return code */ + u32 len; /* Length in bytes of master journal name */ + i64 szJ; /* Total size in bytes of journal file pJrnl */ + u32 cksum; /* MJ checksum value read from journal */ + u32 u; /* Unsigned loop counter */ + unsigned char aMagic[8]; /* A buffer to hold the magic header */ + zMaster[0] = '\0'; + + if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ)) + || szJ<16 + || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len)) + || len>=nMaster + || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum)) + || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8)) + || memcmp(aMagic, aJournalMagic, 8) + || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len)) + ){ + return rc; + } + + /* See if the checksum matches the master journal name */ + for(u=0; ujournalOff, assuming a sector +** size of pPager->sectorSize bytes. +** +** i.e for a sector size of 512: +** +** Pager.journalOff Return value +** --------------------------------------- +** 0 0 +** 512 512 +** 100 512 +** 2000 2048 +** +*/ +static i64 journalHdrOffset(Pager *pPager){ + i64 offset = 0; + i64 c = pPager->journalOff; + if( c ){ + offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager); + } + assert( offset%JOURNAL_HDR_SZ(pPager)==0 ); + assert( offset>=c ); + assert( (offset-c)jfd) ); + if( pPager->journalOff ){ + const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */ + + IOTRACE(("JZEROHDR %p\n", pPager)) + if( doTruncate || iLimit==0 ){ + rc = sqlite3OsTruncate(pPager->jfd, 0); + }else{ + static const char zeroHdr[28] = {0}; + rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0); + } + if( rc==SQLITE_OK && !pPager->noSync ){ + rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags); + } + + /* At this point the transaction is committed but the write lock + ** is still held on the file. If there is a size limit configured for + ** the persistent journal and the journal file currently consumes more + ** space than that limit allows for, truncate it now. There is no need + ** to sync the file following this operation. + */ + if( rc==SQLITE_OK && iLimit>0 ){ + i64 sz; + rc = sqlite3OsFileSize(pPager->jfd, &sz); + if( rc==SQLITE_OK && sz>iLimit ){ + rc = sqlite3OsTruncate(pPager->jfd, iLimit); + } + } + } + return rc; +} + +/* +** The journal file must be open when this routine is called. A journal +** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the +** current location. +** +** The format for the journal header is as follows: +** - 8 bytes: Magic identifying journal format. +** - 4 bytes: Number of records in journal, or -1 no-sync mode is on. +** - 4 bytes: Random number used for page hash. +** - 4 bytes: Initial database page count. +** - 4 bytes: Sector size used by the process that wrote this journal. +** - 4 bytes: Database page size. +** +** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space. +*/ +static int writeJournalHdr(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */ + u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */ + u32 nWrite; /* Bytes of header sector written */ + int ii; /* Loop counter */ + + assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ + + if( nHeader>JOURNAL_HDR_SZ(pPager) ){ + nHeader = JOURNAL_HDR_SZ(pPager); + } + + /* If there are active savepoints and any of them were created + ** since the most recent journal header was written, update the + ** PagerSavepoint.iHdrOffset fields now. + */ + for(ii=0; iinSavepoint; ii++){ + if( pPager->aSavepoint[ii].iHdrOffset==0 ){ + pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff; + } + } + + pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager); + + /* + ** Write the nRec Field - the number of page records that follow this + ** journal header. Normally, zero is written to this value at this time. + ** After the records are added to the journal (and the journal synced, + ** if in full-sync mode), the zero is overwritten with the true number + ** of records (see syncJournal()). + ** + ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When + ** reading the journal this value tells SQLite to assume that the + ** rest of the journal file contains valid page records. This assumption + ** is dangerous, as if a failure occurred whilst writing to the journal + ** file it may contain some garbage data. There are two scenarios + ** where this risk can be ignored: + ** + ** * When the pager is in no-sync mode. Corruption can follow a + ** power failure in this case anyway. + ** + ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees + ** that garbage data is never appended to the journal file. + */ + assert( isOpen(pPager->fd) || pPager->noSync ); + if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY) + || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) + ){ + memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); + put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff); + }else{ + memset(zHeader, 0, sizeof(aJournalMagic)+4); + } + + /* The random check-hash initializer */ + sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit); + put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit); + /* The initial database size */ + put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize); + /* The assumed sector size for this process */ + put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize); + + /* The page size */ + put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize); + + /* Initializing the tail of the buffer is not necessary. Everything + ** works find if the following memset() is omitted. But initializing + ** the memory prevents valgrind from complaining, so we are willing to + ** take the performance hit. + */ + memset(&zHeader[sizeof(aJournalMagic)+20], 0, + nHeader-(sizeof(aJournalMagic)+20)); + + /* In theory, it is only necessary to write the 28 bytes that the + ** journal header consumes to the journal file here. Then increment the + ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next + ** record is written to the following sector (leaving a gap in the file + ** that will be implicitly filled in by the OS). + ** + ** However it has been discovered that on some systems this pattern can + ** be significantly slower than contiguously writing data to the file, + ** even if that means explicitly writing data to the block of + ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what + ** is done. + ** + ** The loop is required here in case the sector-size is larger than the + ** database page size. Since the zHeader buffer is only Pager.pageSize + ** bytes in size, more than one call to sqlite3OsWrite() may be required + ** to populate the entire journal header sector. + */ + for(nWrite=0; rc==SQLITE_OK&&nWritejournalHdr, nHeader)) + rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff); + assert( pPager->journalHdr <= pPager->journalOff ); + pPager->journalOff += nHeader; + } + + return rc; +} + +/* +** The journal file must be open when this is called. A journal header file +** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal +** file. The current location in the journal file is given by +** pPager->journalOff. See comments above function writeJournalHdr() for +** a description of the journal header format. +** +** If the header is read successfully, *pNRec is set to the number of +** page records following this header and *pDbSize is set to the size of the +** database before the transaction began, in pages. Also, pPager->cksumInit +** is set to the value read from the journal header. SQLITE_OK is returned +** in this case. +** +** If the journal header file appears to be corrupted, SQLITE_DONE is +** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes +** cannot be read from the journal file an error code is returned. +*/ +static int readJournalHdr( + Pager *pPager, /* Pager object */ + int isHot, + i64 journalSize, /* Size of the open journal file in bytes */ + u32 *pNRec, /* OUT: Value read from the nRec field */ + u32 *pDbSize /* OUT: Value of original database size field */ +){ + int rc; /* Return code */ + unsigned char aMagic[8]; /* A buffer to hold the magic header */ + i64 iHdrOff; /* Offset of journal header being read */ + + assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ + + /* Advance Pager.journalOff to the start of the next sector. If the + ** journal file is too small for there to be a header stored at this + ** point, return SQLITE_DONE. + */ + pPager->journalOff = journalHdrOffset(pPager); + if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){ + return SQLITE_DONE; + } + iHdrOff = pPager->journalOff; + + /* Read in the first 8 bytes of the journal header. If they do not match + ** the magic string found at the start of each journal header, return + ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise, + ** proceed. + */ + if( isHot || iHdrOff!=pPager->journalHdr ){ + rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff); + if( rc ){ + return rc; + } + if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){ + return SQLITE_DONE; + } + } + + /* Read the first three 32-bit fields of the journal header: The nRec + ** field, the checksum-initializer and the database size at the start + ** of the transaction. Return an error code if anything goes wrong. + */ + if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec)) + || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit)) + || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize)) + ){ + return rc; + } + + if( pPager->journalOff==0 ){ + u32 iPageSize; /* Page-size field of journal header */ + u32 iSectorSize; /* Sector-size field of journal header */ + + /* Read the page-size and sector-size journal header fields. */ + if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize)) + || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize)) + ){ + return rc; + } + + /* Versions of SQLite prior to 3.5.8 set the page-size field of the + ** journal header to zero. In this case, assume that the Pager.pageSize + ** variable is already set to the correct page size. + */ + if( iPageSize==0 ){ + iPageSize = pPager->pageSize; + } + + /* Check that the values read from the page-size and sector-size fields + ** are within range. To be 'in range', both values need to be a power + ** of two greater than or equal to 512 or 32, and not greater than their + ** respective compile time maximum limits. + */ + if( iPageSize<512 || iSectorSize<32 + || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE + || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0 + ){ + /* If the either the page-size or sector-size in the journal-header is + ** invalid, then the process that wrote the journal-header must have + ** crashed before the header was synced. In this case stop reading + ** the journal file here. + */ + return SQLITE_DONE; + } + + /* Update the page-size to match the value read from the journal. + ** Use a testcase() macro to make sure that malloc failure within + ** PagerSetPagesize() is tested. + */ + rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1); + testcase( rc!=SQLITE_OK ); + + /* Update the assumed sector-size to match the value used by + ** the process that created this journal. If this journal was + ** created by a process other than this one, then this routine + ** is being called from within pager_playback(). The local value + ** of Pager.sectorSize is restored at the end of that routine. + */ + pPager->sectorSize = iSectorSize; + } + + pPager->journalOff += JOURNAL_HDR_SZ(pPager); + return rc; +} + + +/* +** Write the supplied master journal name into the journal file for pager +** pPager at the current location. The master journal name must be the last +** thing written to a journal file. If the pager is in full-sync mode, the +** journal file descriptor is advanced to the next sector boundary before +** anything is written. The format is: +** +** + 4 bytes: PAGER_MJ_PGNO. +** + N bytes: Master journal filename in utf-8. +** + 4 bytes: N (length of master journal name in bytes, no nul-terminator). +** + 4 bytes: Master journal name checksum. +** + 8 bytes: aJournalMagic[]. +** +** The master journal page checksum is the sum of the bytes in the master +** journal name, where each byte is interpreted as a signed 8-bit integer. +** +** If zMaster is a NULL pointer (occurs for a single database transaction), +** this call is a no-op. +*/ +static int writeMasterJournal(Pager *pPager, const char *zMaster){ + int rc; /* Return code */ + int nMaster; /* Length of string zMaster */ + i64 iHdrOff; /* Offset of header in journal file */ + i64 jrnlSize; /* Size of journal file on disk */ + u32 cksum = 0; /* Checksum of string zMaster */ + + assert( pPager->setMaster==0 ); + assert( !pagerUseWal(pPager) ); + + if( !zMaster + || pPager->journalMode==PAGER_JOURNALMODE_MEMORY + || pPager->journalMode==PAGER_JOURNALMODE_OFF + ){ + return SQLITE_OK; + } + pPager->setMaster = 1; + assert( isOpen(pPager->jfd) ); + assert( pPager->journalHdr <= pPager->journalOff ); + + /* Calculate the length in bytes and the checksum of zMaster */ + for(nMaster=0; zMaster[nMaster]; nMaster++){ + cksum += zMaster[nMaster]; + } + + /* If in full-sync mode, advance to the next disk sector before writing + ** the master journal name. This is in case the previous page written to + ** the journal has already been synced. + */ + if( pPager->fullSync ){ + pPager->journalOff = journalHdrOffset(pPager); + } + iHdrOff = pPager->journalOff; + + /* Write the master journal data to the end of the journal file. If + ** an error occurs, return the error code to the caller. + */ + if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager)))) + || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4))) + || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster))) + || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum))) + || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8))) + ){ + return rc; + } + pPager->journalOff += (nMaster+20); + + /* If the pager is in peristent-journal mode, then the physical + ** journal-file may extend past the end of the master-journal name + ** and 8 bytes of magic data just written to the file. This is + ** dangerous because the code to rollback a hot-journal file + ** will not be able to find the master-journal name to determine + ** whether or not the journal is hot. + ** + ** Easiest thing to do in this scenario is to truncate the journal + ** file to the required size. + */ + if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize)) + && jrnlSize>pPager->journalOff + ){ + rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff); + } + return rc; +} + +/* +** Find a page in the hash table given its page number. Return +** a pointer to the page or NULL if the requested page is not +** already in memory. +*/ +static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){ + PgHdr *p; /* Return value */ + + /* It is not possible for a call to PcacheFetch() with createFlag==0 to + ** fail, since no attempt to allocate dynamic memory will be made. + */ + (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p); + return p; +} + +/* +** Discard the entire contents of the in-memory page-cache. +*/ +static void pager_reset(Pager *pPager){ + sqlite3BackupRestart(pPager->pBackup); + sqlite3PcacheClear(pPager->pPCache); +} + +/* +** Free all structures in the Pager.aSavepoint[] array and set both +** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal +** if it is open and the pager is not in exclusive mode. +*/ +static void releaseAllSavepoints(Pager *pPager){ + int ii; /* Iterator for looping through Pager.aSavepoint */ + for(ii=0; iinSavepoint; ii++){ + sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); + } + if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){ + sqlite3OsClose(pPager->sjfd); + } + sqlite3_free(pPager->aSavepoint); + pPager->aSavepoint = 0; + pPager->nSavepoint = 0; + pPager->nSubRec = 0; +} + +/* +** Set the bit number pgno in the PagerSavepoint.pInSavepoint +** bitvecs of all open savepoints. Return SQLITE_OK if successful +** or SQLITE_NOMEM if a malloc failure occurs. +*/ +static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){ + int ii; /* Loop counter */ + int rc = SQLITE_OK; /* Result code */ + + for(ii=0; iinSavepoint; ii++){ + PagerSavepoint *p = &pPager->aSavepoint[ii]; + if( pgno<=p->nOrig ){ + rc |= sqlite3BitvecSet(p->pInSavepoint, pgno); + testcase( rc==SQLITE_NOMEM ); + assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); + } + } + return rc; +} + +/* +** This function is a no-op if the pager is in exclusive mode and not +** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN +** state. +** +** If the pager is not in exclusive-access mode, the database file is +** completely unlocked. If the file is unlocked and the file-system does +** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is +** closed (if it is open). +** +** If the pager is in ERROR state when this function is called, the +** contents of the pager cache are discarded before switching back to +** the OPEN state. Regardless of whether the pager is in exclusive-mode +** or not, any journal file left in the file-system will be treated +** as a hot-journal and rolled back the next time a read-transaction +** is opened (by this or by any other connection). +*/ +static void pager_unlock(Pager *pPager){ + + assert( pPager->eState==PAGER_READER + || pPager->eState==PAGER_OPEN + || pPager->eState==PAGER_ERROR + ); + + sqlite3BitvecDestroy(pPager->pInJournal); + pPager->pInJournal = 0; + releaseAllSavepoints(pPager); + + if( pagerUseWal(pPager) ){ + assert( !isOpen(pPager->jfd) ); + sqlite3WalEndReadTransaction(pPager->pWal); + pPager->eState = PAGER_OPEN; + }else if( !pPager->exclusiveMode ){ + int rc; /* Error code returned by pagerUnlockDb() */ + int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0; + + /* If the operating system support deletion of open files, then + ** close the journal file when dropping the database lock. Otherwise + ** another connection with journal_mode=delete might delete the file + ** out from under us. + */ + assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 ); + assert( (PAGER_JOURNALMODE_OFF & 5)!=1 ); + assert( (PAGER_JOURNALMODE_WAL & 5)!=1 ); + assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 ); + assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); + assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); + if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN) + || 1!=(pPager->journalMode & 5) + ){ + sqlite3OsClose(pPager->jfd); + } + + /* If the pager is in the ERROR state and the call to unlock the database + ** file fails, set the current lock to UNKNOWN_LOCK. See the comment + ** above the #define for UNKNOWN_LOCK for an explanation of why this + ** is necessary. + */ + rc = pagerUnlockDb(pPager, NO_LOCK); + if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){ + pPager->eLock = UNKNOWN_LOCK; + } + + /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here + ** without clearing the error code. This is intentional - the error + ** code is cleared and the cache reset in the block below. + */ + assert( pPager->errCode || pPager->eState!=PAGER_ERROR ); + pPager->changeCountDone = 0; + pPager->eState = PAGER_OPEN; + } + + /* If Pager.errCode is set, the contents of the pager cache cannot be + ** trusted. Now that there are no outstanding references to the pager, + ** it can safely move back to PAGER_OPEN state. This happens in both + ** normal and exclusive-locking mode. + */ + if( pPager->errCode ){ + assert( !MEMDB ); + pager_reset(pPager); + pPager->changeCountDone = pPager->tempFile; + pPager->eState = PAGER_OPEN; + pPager->errCode = SQLITE_OK; + if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); + } + + pPager->journalOff = 0; + pPager->journalHdr = 0; + pPager->setMaster = 0; +} + +/* +** This function is called whenever an IOERR or FULL error that requires +** the pager to transition into the ERROR state may ahve occurred. +** The first argument is a pointer to the pager structure, the second +** the error-code about to be returned by a pager API function. The +** value returned is a copy of the second argument to this function. +** +** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the +** IOERR sub-codes, the pager enters the ERROR state and the error code +** is stored in Pager.errCode. While the pager remains in the ERROR state, +** all major API calls on the Pager will immediately return Pager.errCode. +** +** The ERROR state indicates that the contents of the pager-cache +** cannot be trusted. This state can be cleared by completely discarding +** the contents of the pager-cache. If a transaction was active when +** the persistent error occurred, then the rollback journal may need +** to be replayed to restore the contents of the database file (as if +** it were a hot-journal). +*/ +static int pager_error(Pager *pPager, int rc){ + int rc2 = rc & 0xff; + assert( rc==SQLITE_OK || !MEMDB ); + assert( + pPager->errCode==SQLITE_FULL || + pPager->errCode==SQLITE_OK || + (pPager->errCode & 0xff)==SQLITE_IOERR + ); + if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){ + pPager->errCode = rc; + pPager->eState = PAGER_ERROR; + } + return rc; +} + +static int pager_truncate(Pager *pPager, Pgno nPage); + +/* +** This routine ends a transaction. A transaction is usually ended by +** either a COMMIT or a ROLLBACK operation. This routine may be called +** after rollback of a hot-journal, or if an error occurs while opening +** the journal file or writing the very first journal-header of a +** database transaction. +** +** This routine is never called in PAGER_ERROR state. If it is called +** in PAGER_NONE or PAGER_SHARED state and the lock held is less +** exclusive than a RESERVED lock, it is a no-op. +** +** Otherwise, any active savepoints are released. +** +** If the journal file is open, then it is "finalized". Once a journal +** file has been finalized it is not possible to use it to roll back a +** transaction. Nor will it be considered to be a hot-journal by this +** or any other database connection. Exactly how a journal is finalized +** depends on whether or not the pager is running in exclusive mode and +** the current journal-mode (Pager.journalMode value), as follows: +** +** journalMode==MEMORY +** Journal file descriptor is simply closed. This destroys an +** in-memory journal. +** +** journalMode==TRUNCATE +** Journal file is truncated to zero bytes in size. +** +** journalMode==PERSIST +** The first 28 bytes of the journal file are zeroed. This invalidates +** the first journal header in the file, and hence the entire journal +** file. An invalid journal file cannot be rolled back. +** +** journalMode==DELETE +** The journal file is closed and deleted using sqlite3OsDelete(). +** +** If the pager is running in exclusive mode, this method of finalizing +** the journal file is never used. Instead, if the journalMode is +** DELETE and the pager is in exclusive mode, the method described under +** journalMode==PERSIST is used instead. +** +** After the journal is finalized, the pager moves to PAGER_READER state. +** If running in non-exclusive rollback mode, the lock on the file is +** downgraded to a SHARED_LOCK. +** +** SQLITE_OK is returned if no error occurs. If an error occurs during +** any of the IO operations to finalize the journal file or unlock the +** database then the IO error code is returned to the user. If the +** operation to finalize the journal file fails, then the code still +** tries to unlock the database file if not in exclusive mode. If the +** unlock operation fails as well, then the first error code related +** to the first error encountered (the journal finalization one) is +** returned. +*/ +static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){ + int rc = SQLITE_OK; /* Error code from journal finalization operation */ + int rc2 = SQLITE_OK; /* Error code from db file unlock operation */ + + /* Do nothing if the pager does not have an open write transaction + ** or at least a RESERVED lock. This function may be called when there + ** is no write-transaction active but a RESERVED or greater lock is + ** held under two circumstances: + ** + ** 1. After a successful hot-journal rollback, it is called with + ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK. + ** + ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE + ** lock switches back to locking_mode=normal and then executes a + ** read-transaction, this function is called with eState==PAGER_READER + ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed. + */ + assert( assert_pager_state(pPager) ); + assert( pPager->eState!=PAGER_ERROR ); + if( pPager->eStateeLockjfd) || pPager->pInJournal==0 ); + if( isOpen(pPager->jfd) ){ + assert( !pagerUseWal(pPager) ); + + /* Finalize the journal file. */ + if( sqlite3IsMemJournal(pPager->jfd) ){ + assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); + sqlite3OsClose(pPager->jfd); + }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){ + if( pPager->journalOff==0 ){ + rc = SQLITE_OK; + }else{ + rc = sqlite3OsTruncate(pPager->jfd, 0); + } + pPager->journalOff = 0; + }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST + || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL) + ){ + rc = zeroJournalHdr(pPager, hasMaster); + pPager->journalOff = 0; + }else{ + /* This branch may be executed with Pager.journalMode==MEMORY if + ** a hot-journal was just rolled back. In this case the journal + ** file should be closed and deleted. If this connection writes to + ** the database file, it will do so using an in-memory journal. + */ + int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd)); + assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE + || pPager->journalMode==PAGER_JOURNALMODE_MEMORY + || pPager->journalMode==PAGER_JOURNALMODE_WAL + ); + sqlite3OsClose(pPager->jfd); + if( bDelete ){ + rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); + } + } + } + +#ifdef SQLITE_CHECK_PAGES + sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash); + if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){ + PgHdr *p = pager_lookup(pPager, 1); + if( p ){ + p->pageHash = 0; + sqlite3PagerUnref(p); + } + } +#endif + + sqlite3BitvecDestroy(pPager->pInJournal); + pPager->pInJournal = 0; + pPager->nRec = 0; + sqlite3PcacheCleanAll(pPager->pPCache); + sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize); + + if( pagerUseWal(pPager) ){ + /* Drop the WAL write-lock, if any. Also, if the connection was in + ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE + ** lock held on the database file. + */ + rc2 = sqlite3WalEndWriteTransaction(pPager->pWal); + assert( rc2==SQLITE_OK ); + }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){ + /* This branch is taken when committing a transaction in rollback-journal + ** mode if the database file on disk is larger than the database image. + ** At this point the journal has been finalized and the transaction + ** successfully committed, but the EXCLUSIVE lock is still held on the + ** file. So it is safe to truncate the database file to its minimum + ** required size. */ + assert( pPager->eLock==EXCLUSIVE_LOCK ); + rc = pager_truncate(pPager, pPager->dbSize); + } + + if( !pPager->exclusiveMode + && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0)) + ){ + rc2 = pagerUnlockDb(pPager, SHARED_LOCK); + pPager->changeCountDone = 0; + } + pPager->eState = PAGER_READER; + pPager->setMaster = 0; + + return (rc==SQLITE_OK?rc2:rc); +} + +/* +** Execute a rollback if a transaction is active and unlock the +** database file. +** +** If the pager has already entered the ERROR state, do not attempt +** the rollback at this time. Instead, pager_unlock() is called. The +** call to pager_unlock() will discard all in-memory pages, unlock +** the database file and move the pager back to OPEN state. If this +** means that there is a hot-journal left in the file-system, the next +** connection to obtain a shared lock on the pager (which may be this one) +** will roll it back. +** +** If the pager has not already entered the ERROR state, but an IO or +** malloc error occurs during a rollback, then this will itself cause +** the pager to enter the ERROR state. Which will be cleared by the +** call to pager_unlock(), as described above. +*/ +static void pagerUnlockAndRollback(Pager *pPager){ + if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){ + assert( assert_pager_state(pPager) ); + if( pPager->eState>=PAGER_WRITER_LOCKED ){ + sqlite3BeginBenignMalloc(); + sqlite3PagerRollback(pPager); + sqlite3EndBenignMalloc(); + }else if( !pPager->exclusiveMode ){ + assert( pPager->eState==PAGER_READER ); + pager_end_transaction(pPager, 0, 0); + } + } + pager_unlock(pPager); +} + +/* +** Parameter aData must point to a buffer of pPager->pageSize bytes +** of data. Compute and return a checksum based ont the contents of the +** page of data and the current value of pPager->cksumInit. +** +** This is not a real checksum. It is really just the sum of the +** random initial value (pPager->cksumInit) and every 200th byte +** of the page data, starting with byte offset (pPager->pageSize%200). +** Each byte is interpreted as an 8-bit unsigned integer. +** +** Changing the formula used to compute this checksum results in an +** incompatible journal file format. +** +** If journal corruption occurs due to a power failure, the most likely +** scenario is that one end or the other of the record will be changed. +** It is much less likely that the two ends of the journal record will be +** correct and the middle be corrupt. Thus, this "checksum" scheme, +** though fast and simple, catches the mostly likely kind of corruption. +*/ +static u32 pager_cksum(Pager *pPager, const u8 *aData){ + u32 cksum = pPager->cksumInit; /* Checksum value to return */ + int i = pPager->pageSize-200; /* Loop counter */ + while( i>0 ){ + cksum += aData[i]; + i -= 200; + } + return cksum; +} + +/* +** Report the current page size and number of reserved bytes back +** to the codec. +*/ +#ifdef SQLITE_HAS_CODEC +static void pagerReportSize(Pager *pPager){ + if( pPager->xCodecSizeChng ){ + pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize, + (int)pPager->nReserve); + } +} +#else +# define pagerReportSize(X) /* No-op if we do not support a codec */ +#endif + +/* +** Read a single page from either the journal file (if isMainJrnl==1) or +** from the sub-journal (if isMainJrnl==0) and playback that page. +** The page begins at offset *pOffset into the file. The *pOffset +** value is increased to the start of the next page in the journal. +** +** The main rollback journal uses checksums - the statement journal does +** not. +** +** If the page number of the page record read from the (sub-)journal file +** is greater than the current value of Pager.dbSize, then playback is +** skipped and SQLITE_OK is returned. +** +** If pDone is not NULL, then it is a record of pages that have already +** been played back. If the page at *pOffset has already been played back +** (if the corresponding pDone bit is set) then skip the playback. +** Make sure the pDone bit corresponding to the *pOffset page is set +** prior to returning. +** +** If the page record is successfully read from the (sub-)journal file +** and played back, then SQLITE_OK is returned. If an IO error occurs +** while reading the record from the (sub-)journal file or while writing +** to the database file, then the IO error code is returned. If data +** is successfully read from the (sub-)journal file but appears to be +** corrupted, SQLITE_DONE is returned. Data is considered corrupted in +** two circumstances: +** +** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or +** * If the record is being rolled back from the main journal file +** and the checksum field does not match the record content. +** +** Neither of these two scenarios are possible during a savepoint rollback. +** +** If this is a savepoint rollback, then memory may have to be dynamically +** allocated by this function. If this is the case and an allocation fails, +** SQLITE_NOMEM is returned. +*/ +static int pager_playback_one_page( + Pager *pPager, /* The pager being played back */ + i64 *pOffset, /* Offset of record to playback */ + Bitvec *pDone, /* Bitvec of pages already played back */ + int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */ + int isSavepnt /* True for a savepoint rollback */ +){ + int rc; + PgHdr *pPg; /* An existing page in the cache */ + Pgno pgno; /* The page number of a page in journal */ + u32 cksum; /* Checksum used for sanity checking */ + char *aData; /* Temporary storage for the page */ + sqlite3_file *jfd; /* The file descriptor for the journal file */ + int isSynced; /* True if journal page is synced */ + + assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */ + assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */ + assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */ + assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */ + + aData = pPager->pTmpSpace; + assert( aData ); /* Temp storage must have already been allocated */ + assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) ); + + /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction + ** or savepoint rollback done at the request of the caller) or this is + ** a hot-journal rollback. If it is a hot-journal rollback, the pager + ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback + ** only reads from the main journal, not the sub-journal. + */ + assert( pPager->eState>=PAGER_WRITER_CACHEMOD + || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK) + ); + assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl ); + + /* Read the page number and page data from the journal or sub-journal + ** file. Return an error code to the caller if an IO error occurs. + */ + jfd = isMainJrnl ? pPager->jfd : pPager->sjfd; + rc = read32bits(jfd, *pOffset, &pgno); + if( rc!=SQLITE_OK ) return rc; + rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4); + if( rc!=SQLITE_OK ) return rc; + *pOffset += pPager->pageSize + 4 + isMainJrnl*4; + + /* Sanity checking on the page. This is more important that I originally + ** thought. If a power failure occurs while the journal is being written, + ** it could cause invalid data to be written into the journal. We need to + ** detect this invalid data (with high probability) and ignore it. + */ + if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){ + assert( !isSavepnt ); + return SQLITE_DONE; + } + if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){ + return SQLITE_OK; + } + if( isMainJrnl ){ + rc = read32bits(jfd, (*pOffset)-4, &cksum); + if( rc ) return rc; + if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){ + return SQLITE_DONE; + } + } + + /* If this page has already been played by before during the current + ** rollback, then don't bother to play it back again. + */ + if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){ + return rc; + } + + /* When playing back page 1, restore the nReserve setting + */ + if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){ + pPager->nReserve = ((u8*)aData)[20]; + pagerReportSize(pPager); + } + + /* If the pager is in CACHEMOD state, then there must be a copy of this + ** page in the pager cache. In this case just update the pager cache, + ** not the database file. The page is left marked dirty in this case. + ** + ** An exception to the above rule: If the database is in no-sync mode + ** and a page is moved during an incremental vacuum then the page may + ** not be in the pager cache. Later: if a malloc() or IO error occurs + ** during a Movepage() call, then the page may not be in the cache + ** either. So the condition described in the above paragraph is not + ** assert()able. + ** + ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the + ** pager cache if it exists and the main file. The page is then marked + ** not dirty. Since this code is only executed in PAGER_OPEN state for + ** a hot-journal rollback, it is guaranteed that the page-cache is empty + ** if the pager is in OPEN state. + ** + ** Ticket #1171: The statement journal might contain page content that is + ** different from the page content at the start of the transaction. + ** This occurs when a page is changed prior to the start of a statement + ** then changed again within the statement. When rolling back such a + ** statement we must not write to the original database unless we know + ** for certain that original page contents are synced into the main rollback + ** journal. Otherwise, a power loss might leave modified data in the + ** database file without an entry in the rollback journal that can + ** restore the database to its original form. Two conditions must be + ** met before writing to the database files. (1) the database must be + ** locked. (2) we know that the original page content is fully synced + ** in the main journal either because the page is not in cache or else + ** the page is marked as needSync==0. + ** + ** 2008-04-14: When attempting to vacuum a corrupt database file, it + ** is possible to fail a statement on a database that does not yet exist. + ** Do not attempt to write if database file has never been opened. + */ + if( pagerUseWal(pPager) ){ + pPg = 0; + }else{ + pPg = pager_lookup(pPager, pgno); + } + assert( pPg || !MEMDB ); + assert( pPager->eState!=PAGER_OPEN || pPg==0 ); + PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n", + PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData), + (isMainJrnl?"main-journal":"sub-journal") + )); + if( isMainJrnl ){ + isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr); + }else{ + isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC)); + } + if( isOpen(pPager->fd) + && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) + && isSynced + ){ + i64 ofst = (pgno-1)*(i64)pPager->pageSize; + testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 ); + assert( !pagerUseWal(pPager) ); + rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); + if( pgno>pPager->dbFileSize ){ + pPager->dbFileSize = pgno; + } + if( pPager->pBackup ){ + CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM); + sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); + CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData); + } + }else if( !isMainJrnl && pPg==0 ){ + /* If this is a rollback of a savepoint and data was not written to + ** the database and the page is not in-memory, there is a potential + ** problem. When the page is next fetched by the b-tree layer, it + ** will be read from the database file, which may or may not be + ** current. + ** + ** There are a couple of different ways this can happen. All are quite + ** obscure. When running in synchronous mode, this can only happen + ** if the page is on the free-list at the start of the transaction, then + ** populated, then moved using sqlite3PagerMovepage(). + ** + ** The solution is to add an in-memory page to the cache containing + ** the data just read from the sub-journal. Mark the page as dirty + ** and if the pager requires a journal-sync, then mark the page as + ** requiring a journal-sync before it is written. + */ + assert( isSavepnt ); + assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 ); + pPager->doNotSpill |= SPILLFLAG_ROLLBACK; + rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1); + assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 ); + pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK; + if( rc!=SQLITE_OK ) return rc; + pPg->flags &= ~PGHDR_NEED_READ; + sqlite3PcacheMakeDirty(pPg); + } + if( pPg ){ + /* No page should ever be explicitly rolled back that is in use, except + ** for page 1 which is held in use in order to keep the lock on the + ** database active. However such a page may be rolled back as a result + ** of an internal error resulting in an automatic call to + ** sqlite3PagerRollback(). + */ + void *pData; + pData = pPg->pData; + memcpy(pData, (u8*)aData, pPager->pageSize); + pPager->xReiniter(pPg); + if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){ + /* If the contents of this page were just restored from the main + ** journal file, then its content must be as they were when the + ** transaction was first opened. In this case we can mark the page + ** as clean, since there will be no need to write it out to the + ** database. + ** + ** There is one exception to this rule. If the page is being rolled + ** back as part of a savepoint (or statement) rollback from an + ** unsynced portion of the main journal file, then it is not safe + ** to mark the page as clean. This is because marking the page as + ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is + ** already in the journal file (recorded in Pager.pInJournal) and + ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to + ** again within this transaction, it will be marked as dirty but + ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially + ** be written out into the database file before its journal file + ** segment is synced. If a crash occurs during or following this, + ** database corruption may ensue. + */ + assert( !pagerUseWal(pPager) ); + sqlite3PcacheMakeClean(pPg); + } + pager_set_pagehash(pPg); + + /* If this was page 1, then restore the value of Pager.dbFileVers. + ** Do this before any decoding. */ + if( pgno==1 ){ + memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers)); + } + + /* Decode the page just read from disk */ + CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM); + sqlite3PcacheRelease(pPg); + } + return rc; +} + +/* +** Parameter zMaster is the name of a master journal file. A single journal +** file that referred to the master journal file has just been rolled back. +** This routine checks if it is possible to delete the master journal file, +** and does so if it is. +** +** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not +** available for use within this function. +** +** When a master journal file is created, it is populated with the names +** of all of its child journals, one after another, formatted as utf-8 +** encoded text. The end of each child journal file is marked with a +** nul-terminator byte (0x00). i.e. the entire contents of a master journal +** file for a transaction involving two databases might be: +** +** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00" +** +** A master journal file may only be deleted once all of its child +** journals have been rolled back. +** +** This function reads the contents of the master-journal file into +** memory and loops through each of the child journal names. For +** each child journal, it checks if: +** +** * if the child journal exists, and if so +** * if the child journal contains a reference to master journal +** file zMaster +** +** If a child journal can be found that matches both of the criteria +** above, this function returns without doing anything. Otherwise, if +** no such child journal can be found, file zMaster is deleted from +** the file-system using sqlite3OsDelete(). +** +** If an IO error within this function, an error code is returned. This +** function allocates memory by calling sqlite3Malloc(). If an allocation +** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors +** occur, SQLITE_OK is returned. +** +** TODO: This function allocates a single block of memory to load +** the entire contents of the master journal file. This could be +** a couple of kilobytes or so - potentially larger than the page +** size. +*/ +static int pager_delmaster(Pager *pPager, const char *zMaster){ + sqlite3_vfs *pVfs = pPager->pVfs; + int rc; /* Return code */ + sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */ + sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */ + char *zMasterJournal = 0; /* Contents of master journal file */ + i64 nMasterJournal; /* Size of master journal file */ + char *zJournal; /* Pointer to one journal within MJ file */ + char *zMasterPtr; /* Space to hold MJ filename from a journal file */ + int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */ + + /* Allocate space for both the pJournal and pMaster file descriptors. + ** If successful, open the master journal file for reading. + */ + pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2); + pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile); + if( !pMaster ){ + rc = SQLITE_NOMEM; + }else{ + const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL); + rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0); + } + if( rc!=SQLITE_OK ) goto delmaster_out; + + /* Load the entire master journal file into space obtained from + ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain + ** sufficient space (in zMasterPtr) to hold the names of master + ** journal files extracted from regular rollback-journals. + */ + rc = sqlite3OsFileSize(pMaster, &nMasterJournal); + if( rc!=SQLITE_OK ) goto delmaster_out; + nMasterPtr = pVfs->mxPathname+1; + zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1); + if( !zMasterJournal ){ + rc = SQLITE_NOMEM; + goto delmaster_out; + } + zMasterPtr = &zMasterJournal[nMasterJournal+1]; + rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0); + if( rc!=SQLITE_OK ) goto delmaster_out; + zMasterJournal[nMasterJournal] = 0; + + zJournal = zMasterJournal; + while( (zJournal-zMasterJournal)pageSize bytes). +** If the file on disk is currently larger than nPage pages, then use the VFS +** xTruncate() method to truncate it. +** +** Or, it might might be the case that the file on disk is smaller than +** nPage pages. Some operating system implementations can get confused if +** you try to truncate a file to some size that is larger than it +** currently is, so detect this case and write a single zero byte to +** the end of the new file instead. +** +** If successful, return SQLITE_OK. If an IO error occurs while modifying +** the database file, return the error code to the caller. +*/ +static int pager_truncate(Pager *pPager, Pgno nPage){ + int rc = SQLITE_OK; + assert( pPager->eState!=PAGER_ERROR ); + assert( pPager->eState!=PAGER_READER ); + + if( isOpen(pPager->fd) + && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) + ){ + i64 currentSize, newSize; + int szPage = pPager->pageSize; + assert( pPager->eLock==EXCLUSIVE_LOCK ); + /* TODO: Is it safe to use Pager.dbFileSize here? */ + rc = sqlite3OsFileSize(pPager->fd, ¤tSize); + newSize = szPage*(i64)nPage; + if( rc==SQLITE_OK && currentSize!=newSize ){ + if( currentSize>newSize ){ + rc = sqlite3OsTruncate(pPager->fd, newSize); + }else if( (currentSize+szPage)<=newSize ){ + char *pTmp = pPager->pTmpSpace; + memset(pTmp, 0, szPage); + testcase( (newSize-szPage) == currentSize ); + testcase( (newSize-szPage) > currentSize ); + rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage); + } + if( rc==SQLITE_OK ){ + pPager->dbFileSize = nPage; + } + } + } + return rc; +} + +/* +** Return a sanitized version of the sector-size of OS file pFile. The +** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE. +*/ +SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){ + int iRet = sqlite3OsSectorSize(pFile); + if( iRet<32 ){ + iRet = 512; + }else if( iRet>MAX_SECTOR_SIZE ){ + assert( MAX_SECTOR_SIZE>=512 ); + iRet = MAX_SECTOR_SIZE; + } + return iRet; +} + +/* +** Set the value of the Pager.sectorSize variable for the given +** pager based on the value returned by the xSectorSize method +** of the open database file. The sector size will be used used +** to determine the size and alignment of journal header and +** master journal pointers within created journal files. +** +** For temporary files the effective sector size is always 512 bytes. +** +** Otherwise, for non-temporary files, the effective sector size is +** the value returned by the xSectorSize() method rounded up to 32 if +** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it +** is greater than MAX_SECTOR_SIZE. +** +** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set +** the effective sector size to its minimum value (512). The purpose of +** pPager->sectorSize is to define the "blast radius" of bytes that +** might change if a crash occurs while writing to a single byte in +** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero +** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector +** size. For backwards compatibility of the rollback journal file format, +** we cannot reduce the effective sector size below 512. +*/ +static void setSectorSize(Pager *pPager){ + assert( isOpen(pPager->fd) || pPager->tempFile ); + + if( pPager->tempFile + || (sqlite3OsDeviceCharacteristics(pPager->fd) & + SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0 + ){ + /* Sector size doesn't matter for temporary files. Also, the file + ** may not have been opened yet, in which case the OsSectorSize() + ** call will segfault. */ + pPager->sectorSize = 512; + }else{ + pPager->sectorSize = sqlite3SectorSize(pPager->fd); + } +} + +/* +** Playback the journal and thus restore the database file to +** the state it was in before we started making changes. +** +** The journal file format is as follows: +** +** (1) 8 byte prefix. A copy of aJournalMagic[]. +** (2) 4 byte big-endian integer which is the number of valid page records +** in the journal. If this value is 0xffffffff, then compute the +** number of page records from the journal size. +** (3) 4 byte big-endian integer which is the initial value for the +** sanity checksum. +** (4) 4 byte integer which is the number of pages to truncate the +** database to during a rollback. +** (5) 4 byte big-endian integer which is the sector size. The header +** is this many bytes in size. +** (6) 4 byte big-endian integer which is the page size. +** (7) zero padding out to the next sector size. +** (8) Zero or more pages instances, each as follows: +** + 4 byte page number. +** + pPager->pageSize bytes of data. +** + 4 byte checksum +** +** When we speak of the journal header, we mean the first 7 items above. +** Each entry in the journal is an instance of the 8th item. +** +** Call the value from the second bullet "nRec". nRec is the number of +** valid page entries in the journal. In most cases, you can compute the +** value of nRec from the size of the journal file. But if a power +** failure occurred while the journal was being written, it could be the +** case that the size of the journal file had already been increased but +** the extra entries had not yet made it safely to disk. In such a case, +** the value of nRec computed from the file size would be too large. For +** that reason, we always use the nRec value in the header. +** +** If the nRec value is 0xffffffff it means that nRec should be computed +** from the file size. This value is used when the user selects the +** no-sync option for the journal. A power failure could lead to corruption +** in this case. But for things like temporary table (which will be +** deleted when the power is restored) we don't care. +** +** If the file opened as the journal file is not a well-formed +** journal file then all pages up to the first corrupted page are rolled +** back (or no pages if the journal header is corrupted). The journal file +** is then deleted and SQLITE_OK returned, just as if no corruption had +** been encountered. +** +** If an I/O or malloc() error occurs, the journal-file is not deleted +** and an error code is returned. +** +** The isHot parameter indicates that we are trying to rollback a journal +** that might be a hot journal. Or, it could be that the journal is +** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE. +** If the journal really is hot, reset the pager cache prior rolling +** back any content. If the journal is merely persistent, no reset is +** needed. +*/ +static int pager_playback(Pager *pPager, int isHot){ + sqlite3_vfs *pVfs = pPager->pVfs; + i64 szJ; /* Size of the journal file in bytes */ + u32 nRec; /* Number of Records in the journal */ + u32 u; /* Unsigned loop counter */ + Pgno mxPg = 0; /* Size of the original file in pages */ + int rc; /* Result code of a subroutine */ + int res = 1; /* Value returned by sqlite3OsAccess() */ + char *zMaster = 0; /* Name of master journal file if any */ + int needPagerReset; /* True to reset page prior to first page rollback */ + int nPlayback = 0; /* Total number of pages restored from journal */ + + /* Figure out how many records are in the journal. Abort early if + ** the journal is empty. + */ + assert( isOpen(pPager->jfd) ); + rc = sqlite3OsFileSize(pPager->jfd, &szJ); + if( rc!=SQLITE_OK ){ + goto end_playback; + } + + /* Read the master journal name from the journal, if it is present. + ** If a master journal file name is specified, but the file is not + ** present on disk, then the journal is not hot and does not need to be + ** played back. + ** + ** TODO: Technically the following is an error because it assumes that + ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that + ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c, + ** mxPathname is 512, which is the same as the minimum allowable value + ** for pageSize. + */ + zMaster = pPager->pTmpSpace; + rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); + if( rc==SQLITE_OK && zMaster[0] ){ + rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); + } + zMaster = 0; + if( rc!=SQLITE_OK || !res ){ + goto end_playback; + } + pPager->journalOff = 0; + needPagerReset = isHot; + + /* This loop terminates either when a readJournalHdr() or + ** pager_playback_one_page() call returns SQLITE_DONE or an IO error + ** occurs. + */ + while( 1 ){ + /* Read the next journal header from the journal file. If there are + ** not enough bytes left in the journal file for a complete header, or + ** it is corrupted, then a process must have failed while writing it. + ** This indicates nothing more needs to be rolled back. + */ + rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + } + goto end_playback; + } + + /* If nRec is 0xffffffff, then this journal was created by a process + ** working in no-sync mode. This means that the rest of the journal + ** file consists of pages, there are no more journal headers. Compute + ** the value of nRec based on this assumption. + */ + if( nRec==0xffffffff ){ + assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ); + nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager)); + } + + /* If nRec is 0 and this rollback is of a transaction created by this + ** process and if this is the final header in the journal, then it means + ** that this part of the journal was being filled but has not yet been + ** synced to disk. Compute the number of pages based on the remaining + ** size of the file. + ** + ** The third term of the test was added to fix ticket #2565. + ** When rolling back a hot journal, nRec==0 always means that the next + ** chunk of the journal contains zero pages to be rolled back. But + ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in + ** the journal, it means that the journal might contain additional + ** pages that need to be rolled back and that the number of pages + ** should be computed based on the journal file size. + */ + if( nRec==0 && !isHot && + pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){ + nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager)); + } + + /* If this is the first header read from the journal, truncate the + ** database file back to its original size. + */ + if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){ + rc = pager_truncate(pPager, mxPg); + if( rc!=SQLITE_OK ){ + goto end_playback; + } + pPager->dbSize = mxPg; + } + + /* Copy original pages out of the journal and back into the + ** database file and/or page cache. + */ + for(u=0; ujournalOff,0,1,0); + if( rc==SQLITE_OK ){ + nPlayback++; + }else{ + if( rc==SQLITE_DONE ){ + pPager->journalOff = szJ; + break; + }else if( rc==SQLITE_IOERR_SHORT_READ ){ + /* If the journal has been truncated, simply stop reading and + ** processing the journal. This might happen if the journal was + ** not completely written and synced prior to a crash. In that + ** case, the database should have never been written in the + ** first place so it is OK to simply abandon the rollback. */ + rc = SQLITE_OK; + goto end_playback; + }else{ + /* If we are unable to rollback, quit and return the error + ** code. This will cause the pager to enter the error state + ** so that no further harm will be done. Perhaps the next + ** process to come along will be able to rollback the database. + */ + goto end_playback; + } + } + } + } + /*NOTREACHED*/ + assert( 0 ); + +end_playback: + /* Following a rollback, the database file should be back in its original + ** state prior to the start of the transaction, so invoke the + ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the + ** assertion that the transaction counter was modified. + */ +#ifdef SQLITE_DEBUG + if( pPager->fd->pMethods ){ + sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0); + } +#endif + + /* If this playback is happening automatically as a result of an IO or + ** malloc error that occurred after the change-counter was updated but + ** before the transaction was committed, then the change-counter + ** modification may just have been reverted. If this happens in exclusive + ** mode, then subsequent transactions performed by the connection will not + ** update the change-counter at all. This may lead to cache inconsistency + ** problems for other processes at some point in the future. So, just + ** in case this has happened, clear the changeCountDone flag now. + */ + pPager->changeCountDone = pPager->tempFile; + + if( rc==SQLITE_OK ){ + zMaster = pPager->pTmpSpace; + rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); + testcase( rc!=SQLITE_OK ); + } + if( rc==SQLITE_OK + && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) + ){ + rc = sqlite3PagerSync(pPager); + } + if( rc==SQLITE_OK ){ + rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0); + testcase( rc!=SQLITE_OK ); + } + if( rc==SQLITE_OK && zMaster[0] && res ){ + /* If there was a master journal and this routine will return success, + ** see if it is possible to delete the master journal. + */ + rc = pager_delmaster(pPager, zMaster); + testcase( rc!=SQLITE_OK ); + } + if( isHot && nPlayback ){ + sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s", + nPlayback, pPager->zJournal); + } + + /* The Pager.sectorSize variable may have been updated while rolling + ** back a journal created by a process with a different sector size + ** value. Reset it to the correct value for this process. + */ + setSectorSize(pPager); + return rc; +} + + +/* +** Read the content for page pPg out of the database file and into +** pPg->pData. A shared lock or greater must be held on the database +** file before this function is called. +** +** If page 1 is read, then the value of Pager.dbFileVers[] is set to +** the value read from the database file. +** +** If an IO error occurs, then the IO error is returned to the caller. +** Otherwise, SQLITE_OK is returned. +*/ +static int readDbPage(PgHdr *pPg, u32 iFrame){ + Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */ + Pgno pgno = pPg->pgno; /* Page number to read */ + int rc = SQLITE_OK; /* Return code */ + int pgsz = pPager->pageSize; /* Number of bytes to read */ + + assert( pPager->eState>=PAGER_READER && !MEMDB ); + assert( isOpen(pPager->fd) ); + +#ifndef SQLITE_OMIT_WAL + if( iFrame ){ + /* Try to pull the page from the write-ahead log. */ + rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData); + }else +#endif + { + i64 iOffset = (pgno-1)*(i64)pPager->pageSize; + rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset); + if( rc==SQLITE_IOERR_SHORT_READ ){ + rc = SQLITE_OK; + } + } + + if( pgno==1 ){ + if( rc ){ + /* If the read is unsuccessful, set the dbFileVers[] to something + ** that will never be a valid file version. dbFileVers[] is a copy + ** of bytes 24..39 of the database. Bytes 28..31 should always be + ** zero or the size of the database in page. Bytes 32..35 and 35..39 + ** should be page numbers which are never 0xffffffff. So filling + ** pPager->dbFileVers[] with all 0xff bytes should suffice. + ** + ** For an encrypted database, the situation is more complex: bytes + ** 24..39 of the database are white noise. But the probability of + ** white noising equaling 16 bytes of 0xff is vanishingly small so + ** we should still be ok. + */ + memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers)); + }else{ + u8 *dbFileVers = &((u8*)pPg->pData)[24]; + memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); + } + } + CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM); + + PAGER_INCR(sqlite3_pager_readdb_count); + PAGER_INCR(pPager->nRead); + IOTRACE(("PGIN %p %d\n", pPager, pgno)); + PAGERTRACE(("FETCH %d page %d hash(%08x)\n", + PAGERID(pPager), pgno, pager_pagehash(pPg))); + + return rc; +} + +/* +** Update the value of the change-counter at offsets 24 and 92 in +** the header and the sqlite version number at offset 96. +** +** This is an unconditional update. See also the pager_incr_changecounter() +** routine which only updates the change-counter if the update is actually +** needed, as determined by the pPager->changeCountDone state variable. +*/ +static void pager_write_changecounter(PgHdr *pPg){ + u32 change_counter; + + /* Increment the value just read and write it back to byte 24. */ + change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1; + put32bits(((char*)pPg->pData)+24, change_counter); + + /* Also store the SQLite version number in bytes 96..99 and in + ** bytes 92..95 store the change counter for which the version number + ** is valid. */ + put32bits(((char*)pPg->pData)+92, change_counter); + put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER); +} + +#ifndef SQLITE_OMIT_WAL +/* +** This function is invoked once for each page that has already been +** written into the log file when a WAL transaction is rolled back. +** Parameter iPg is the page number of said page. The pCtx argument +** is actually a pointer to the Pager structure. +** +** If page iPg is present in the cache, and has no outstanding references, +** it is discarded. Otherwise, if there are one or more outstanding +** references, the page content is reloaded from the database. If the +** attempt to reload content from the database is required and fails, +** return an SQLite error code. Otherwise, SQLITE_OK. +*/ +static int pagerUndoCallback(void *pCtx, Pgno iPg){ + int rc = SQLITE_OK; + Pager *pPager = (Pager *)pCtx; + PgHdr *pPg; + + assert( pagerUseWal(pPager) ); + pPg = sqlite3PagerLookup(pPager, iPg); + if( pPg ){ + if( sqlite3PcachePageRefcount(pPg)==1 ){ + sqlite3PcacheDrop(pPg); + }else{ + u32 iFrame = 0; + rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame); + if( rc==SQLITE_OK ){ + rc = readDbPage(pPg, iFrame); + } + if( rc==SQLITE_OK ){ + pPager->xReiniter(pPg); + } + sqlite3PagerUnref(pPg); + } + } + + /* Normally, if a transaction is rolled back, any backup processes are + ** updated as data is copied out of the rollback journal and into the + ** database. This is not generally possible with a WAL database, as + ** rollback involves simply truncating the log file. Therefore, if one + ** or more frames have already been written to the log (and therefore + ** also copied into the backup databases) as part of this transaction, + ** the backups must be restarted. + */ + sqlite3BackupRestart(pPager->pBackup); + + return rc; +} + +/* +** This function is called to rollback a transaction on a WAL database. +*/ +static int pagerRollbackWal(Pager *pPager){ + int rc; /* Return Code */ + PgHdr *pList; /* List of dirty pages to revert */ + + /* For all pages in the cache that are currently dirty or have already + ** been written (but not committed) to the log file, do one of the + ** following: + ** + ** + Discard the cached page (if refcount==0), or + ** + Reload page content from the database (if refcount>0). + */ + pPager->dbSize = pPager->dbOrigSize; + rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager); + pList = sqlite3PcacheDirtyList(pPager->pPCache); + while( pList && rc==SQLITE_OK ){ + PgHdr *pNext = pList->pDirty; + rc = pagerUndoCallback((void *)pPager, pList->pgno); + pList = pNext; + } + + return rc; +} + +/* +** This function is a wrapper around sqlite3WalFrames(). As well as logging +** the contents of the list of pages headed by pList (connected by pDirty), +** this function notifies any active backup processes that the pages have +** changed. +** +** The list of pages passed into this routine is always sorted by page number. +** Hence, if page 1 appears anywhere on the list, it will be the first page. +*/ +static int pagerWalFrames( + Pager *pPager, /* Pager object */ + PgHdr *pList, /* List of frames to log */ + Pgno nTruncate, /* Database size after this commit */ + int isCommit /* True if this is a commit */ +){ + int rc; /* Return code */ + int nList; /* Number of pages in pList */ +#if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES) + PgHdr *p; /* For looping over pages */ +#endif + + assert( pPager->pWal ); + assert( pList ); +#ifdef SQLITE_DEBUG + /* Verify that the page list is in accending order */ + for(p=pList; p && p->pDirty; p=p->pDirty){ + assert( p->pgno < p->pDirty->pgno ); + } +#endif + + assert( pList->pDirty==0 || isCommit ); + if( isCommit ){ + /* If a WAL transaction is being committed, there is no point in writing + ** any pages with page numbers greater than nTruncate into the WAL file. + ** They will never be read by any client. So remove them from the pDirty + ** list here. */ + PgHdr *p; + PgHdr **ppNext = &pList; + nList = 0; + for(p=pList; (*ppNext = p)!=0; p=p->pDirty){ + if( p->pgno<=nTruncate ){ + ppNext = &p->pDirty; + nList++; + } + } + assert( pList ); + }else{ + nList = 1; + } + pPager->aStat[PAGER_STAT_WRITE] += nList; + + if( pList->pgno==1 ) pager_write_changecounter(pList); + rc = sqlite3WalFrames(pPager->pWal, + pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags + ); + if( rc==SQLITE_OK && pPager->pBackup ){ + PgHdr *p; + for(p=pList; p; p=p->pDirty){ + sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData); + } + } + +#ifdef SQLITE_CHECK_PAGES + pList = sqlite3PcacheDirtyList(pPager->pPCache); + for(p=pList; p; p=p->pDirty){ + pager_set_pagehash(p); + } +#endif + + return rc; +} + +/* +** Begin a read transaction on the WAL. +** +** This routine used to be called "pagerOpenSnapshot()" because it essentially +** makes a snapshot of the database at the current point in time and preserves +** that snapshot for use by the reader in spite of concurrently changes by +** other writers or checkpointers. +*/ +static int pagerBeginReadTransaction(Pager *pPager){ + int rc; /* Return code */ + int changed = 0; /* True if cache must be reset */ + + assert( pagerUseWal(pPager) ); + assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); + + /* sqlite3WalEndReadTransaction() was not called for the previous + ** transaction in locking_mode=EXCLUSIVE. So call it now. If we + ** are in locking_mode=NORMAL and EndRead() was previously called, + ** the duplicate call is harmless. + */ + sqlite3WalEndReadTransaction(pPager->pWal); + + rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed); + if( rc!=SQLITE_OK || changed ){ + pager_reset(pPager); + if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); + } + + return rc; +} +#endif + +/* +** This function is called as part of the transition from PAGER_OPEN +** to PAGER_READER state to determine the size of the database file +** in pages (assuming the page size currently stored in Pager.pageSize). +** +** If no error occurs, SQLITE_OK is returned and the size of the database +** in pages is stored in *pnPage. Otherwise, an error code (perhaps +** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified. +*/ +static int pagerPagecount(Pager *pPager, Pgno *pnPage){ + Pgno nPage; /* Value to return via *pnPage */ + + /* Query the WAL sub-system for the database size. The WalDbsize() + ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or + ** if the database size is not available. The database size is not + ** available from the WAL sub-system if the log file is empty or + ** contains no valid committed transactions. + */ + assert( pPager->eState==PAGER_OPEN ); + assert( pPager->eLock>=SHARED_LOCK ); + nPage = sqlite3WalDbsize(pPager->pWal); + + /* If the database size was not available from the WAL sub-system, + ** determine it based on the size of the database file. If the size + ** of the database file is not an integer multiple of the page-size, + ** round down to the nearest page. Except, any file larger than 0 + ** bytes in size is considered to contain at least one page. + */ + if( nPage==0 ){ + i64 n = 0; /* Size of db file in bytes */ + assert( isOpen(pPager->fd) || pPager->tempFile ); + if( isOpen(pPager->fd) ){ + int rc = sqlite3OsFileSize(pPager->fd, &n); + if( rc!=SQLITE_OK ){ + return rc; + } + } + nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize); + } + + /* If the current number of pages in the file is greater than the + ** configured maximum pager number, increase the allowed limit so + ** that the file can be read. + */ + if( nPage>pPager->mxPgno ){ + pPager->mxPgno = (Pgno)nPage; + } + + *pnPage = nPage; + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_WAL +/* +** Check if the *-wal file that corresponds to the database opened by pPager +** exists if the database is not empy, or verify that the *-wal file does +** not exist (by deleting it) if the database file is empty. +** +** If the database is not empty and the *-wal file exists, open the pager +** in WAL mode. If the database is empty or if no *-wal file exists and +** if no error occurs, make sure Pager.journalMode is not set to +** PAGER_JOURNALMODE_WAL. +** +** Return SQLITE_OK or an error code. +** +** The caller must hold a SHARED lock on the database file to call this +** function. Because an EXCLUSIVE lock on the db file is required to delete +** a WAL on a none-empty database, this ensures there is no race condition +** between the xAccess() below and an xDelete() being executed by some +** other connection. +*/ +static int pagerOpenWalIfPresent(Pager *pPager){ + int rc = SQLITE_OK; + assert( pPager->eState==PAGER_OPEN ); + assert( pPager->eLock>=SHARED_LOCK ); + + if( !pPager->tempFile ){ + int isWal; /* True if WAL file exists */ + Pgno nPage; /* Size of the database file */ + + rc = pagerPagecount(pPager, &nPage); + if( rc ) return rc; + if( nPage==0 ){ + rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0); + if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK; + isWal = 0; + }else{ + rc = sqlite3OsAccess( + pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal + ); + } + if( rc==SQLITE_OK ){ + if( isWal ){ + testcase( sqlite3PcachePagecount(pPager->pPCache)==0 ); + rc = sqlite3PagerOpenWal(pPager, 0); + }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){ + pPager->journalMode = PAGER_JOURNALMODE_DELETE; + } + } + } + return rc; +} +#endif + +/* +** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback +** the entire master journal file. The case pSavepoint==NULL occurs when +** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction +** savepoint. +** +** When pSavepoint is not NULL (meaning a non-transaction savepoint is +** being rolled back), then the rollback consists of up to three stages, +** performed in the order specified: +** +** * Pages are played back from the main journal starting at byte +** offset PagerSavepoint.iOffset and continuing to +** PagerSavepoint.iHdrOffset, or to the end of the main journal +** file if PagerSavepoint.iHdrOffset is zero. +** +** * If PagerSavepoint.iHdrOffset is not zero, then pages are played +** back starting from the journal header immediately following +** PagerSavepoint.iHdrOffset to the end of the main journal file. +** +** * Pages are then played back from the sub-journal file, starting +** with the PagerSavepoint.iSubRec and continuing to the end of +** the journal file. +** +** Throughout the rollback process, each time a page is rolled back, the +** corresponding bit is set in a bitvec structure (variable pDone in the +** implementation below). This is used to ensure that a page is only +** rolled back the first time it is encountered in either journal. +** +** If pSavepoint is NULL, then pages are only played back from the main +** journal file. There is no need for a bitvec in this case. +** +** In either case, before playback commences the Pager.dbSize variable +** is reset to the value that it held at the start of the savepoint +** (or transaction). No page with a page-number greater than this value +** is played back. If one is encountered it is simply skipped. +*/ +static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ + i64 szJ; /* Effective size of the main journal */ + i64 iHdrOff; /* End of first segment of main-journal records */ + int rc = SQLITE_OK; /* Return code */ + Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */ + + assert( pPager->eState!=PAGER_ERROR ); + assert( pPager->eState>=PAGER_WRITER_LOCKED ); + + /* Allocate a bitvec to use to store the set of pages rolled back */ + if( pSavepoint ){ + pDone = sqlite3BitvecCreate(pSavepoint->nOrig); + if( !pDone ){ + return SQLITE_NOMEM; + } + } + + /* Set the database size back to the value it was before the savepoint + ** being reverted was opened. + */ + pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize; + pPager->changeCountDone = pPager->tempFile; + + if( !pSavepoint && pagerUseWal(pPager) ){ + return pagerRollbackWal(pPager); + } + + /* Use pPager->journalOff as the effective size of the main rollback + ** journal. The actual file might be larger than this in + ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything + ** past pPager->journalOff is off-limits to us. + */ + szJ = pPager->journalOff; + assert( pagerUseWal(pPager)==0 || szJ==0 ); + + /* Begin by rolling back records from the main journal starting at + ** PagerSavepoint.iOffset and continuing to the next journal header. + ** There might be records in the main journal that have a page number + ** greater than the current database size (pPager->dbSize) but those + ** will be skipped automatically. Pages are added to pDone as they + ** are played back. + */ + if( pSavepoint && !pagerUseWal(pPager) ){ + iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ; + pPager->journalOff = pSavepoint->iOffset; + while( rc==SQLITE_OK && pPager->journalOffjournalOff, pDone, 1, 1); + } + assert( rc!=SQLITE_DONE ); + }else{ + pPager->journalOff = 0; + } + + /* Continue rolling back records out of the main journal starting at + ** the first journal header seen and continuing until the effective end + ** of the main journal file. Continue to skip out-of-range pages and + ** continue adding pages rolled back to pDone. + */ + while( rc==SQLITE_OK && pPager->journalOffjournalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff" + ** test is related to ticket #2565. See the discussion in the + ** pager_playback() function for additional information. + */ + if( nJRec==0 + && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff + ){ + nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager)); + } + for(ii=0; rc==SQLITE_OK && iijournalOffjournalOff, pDone, 1, 1); + } + assert( rc!=SQLITE_DONE ); + } + assert( rc!=SQLITE_OK || pPager->journalOff>=szJ ); + + /* Finally, rollback pages from the sub-journal. Page that were + ** previously rolled back out of the main journal (and are hence in pDone) + ** will be skipped. Out-of-range pages are also skipped. + */ + if( pSavepoint ){ + u32 ii; /* Loop counter */ + i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize); + + if( pagerUseWal(pPager) ){ + rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData); + } + for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && iinSubRec; ii++){ + assert( offset==(i64)ii*(4+pPager->pageSize) ); + rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1); + } + assert( rc!=SQLITE_DONE ); + } + + sqlite3BitvecDestroy(pDone); + if( rc==SQLITE_OK ){ + pPager->journalOff = szJ; + } + + return rc; +} + +/* +** Change the maximum number of in-memory pages that are allowed. +*/ +SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){ + sqlite3PcacheSetCachesize(pPager->pPCache, mxPage); +} + +/* +** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap. +*/ +static void pagerFixMaplimit(Pager *pPager){ +#if SQLITE_MAX_MMAP_SIZE>0 + sqlite3_file *fd = pPager->fd; + if( isOpen(fd) && fd->pMethods->iVersion>=3 ){ + sqlite3_int64 sz; + sz = pPager->szMmap; + pPager->bUseFetch = (sz>0); + sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz); + } +#endif +} + +/* +** Change the maximum size of any memory mapping made of the database file. +*/ +SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){ + pPager->szMmap = szMmap; + pagerFixMaplimit(pPager); +} + +/* +** Free as much memory as possible from the pager. +*/ +SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){ + sqlite3PcacheShrink(pPager->pPCache); +} + +/* +** Adjust settings of the pager to those specified in the pgFlags parameter. +** +** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness +** of the database to damage due to OS crashes or power failures by +** changing the number of syncs()s when writing the journals. +** There are three levels: +** +** OFF sqlite3OsSync() is never called. This is the default +** for temporary and transient files. +** +** NORMAL The journal is synced once before writes begin on the +** database. This is normally adequate protection, but +** it is theoretically possible, though very unlikely, +** that an inopertune power failure could leave the journal +** in a state which would cause damage to the database +** when it is rolled back. +** +** FULL The journal is synced twice before writes begin on the +** database (with some additional information - the nRec field +** of the journal header - being written in between the two +** syncs). If we assume that writing a +** single disk sector is atomic, then this mode provides +** assurance that the journal will not be corrupted to the +** point of causing damage to the database during rollback. +** +** The above is for a rollback-journal mode. For WAL mode, OFF continues +** to mean that no syncs ever occur. NORMAL means that the WAL is synced +** prior to the start of checkpoint and that the database file is synced +** at the conclusion of the checkpoint if the entire content of the WAL +** was written back into the database. But no sync operations occur for +** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL +** file is synced following each commit operation, in addition to the +** syncs associated with NORMAL. +** +** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The +** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync +** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an +** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL +** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the +** synchronous=FULL versus synchronous=NORMAL setting determines when +** the xSync primitive is called and is relevant to all platforms. +** +** Numeric values associated with these states are OFF==1, NORMAL=2, +** and FULL=3. +*/ +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +SQLITE_PRIVATE void sqlite3PagerSetFlags( + Pager *pPager, /* The pager to set safety level for */ + unsigned pgFlags /* Various flags */ +){ + unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK; + assert( level>=1 && level<=3 ); + pPager->noSync = (level==1 || pPager->tempFile) ?1:0; + pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0; + if( pPager->noSync ){ + pPager->syncFlags = 0; + pPager->ckptSyncFlags = 0; + }else if( pgFlags & PAGER_FULLFSYNC ){ + pPager->syncFlags = SQLITE_SYNC_FULL; + pPager->ckptSyncFlags = SQLITE_SYNC_FULL; + }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){ + pPager->syncFlags = SQLITE_SYNC_NORMAL; + pPager->ckptSyncFlags = SQLITE_SYNC_FULL; + }else{ + pPager->syncFlags = SQLITE_SYNC_NORMAL; + pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; + } + pPager->walSyncFlags = pPager->syncFlags; + if( pPager->fullSync ){ + pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS; + } + if( pgFlags & PAGER_CACHESPILL ){ + pPager->doNotSpill &= ~SPILLFLAG_OFF; + }else{ + pPager->doNotSpill |= SPILLFLAG_OFF; + } +} +#endif + +/* +** The following global variable is incremented whenever the library +** attempts to open a temporary file. This information is used for +** testing and analysis only. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_opentemp_count = 0; +#endif + +/* +** Open a temporary file. +** +** Write the file descriptor into *pFile. Return SQLITE_OK on success +** or some other error code if we fail. The OS will automatically +** delete the temporary file when it is closed. +** +** The flags passed to the VFS layer xOpen() call are those specified +** by parameter vfsFlags ORed with the following: +** +** SQLITE_OPEN_READWRITE +** SQLITE_OPEN_CREATE +** SQLITE_OPEN_EXCLUSIVE +** SQLITE_OPEN_DELETEONCLOSE +*/ +static int pagerOpentemp( + Pager *pPager, /* The pager object */ + sqlite3_file *pFile, /* Write the file descriptor here */ + int vfsFlags /* Flags passed through to the VFS */ +){ + int rc; /* Return code */ + +#ifdef SQLITE_TEST + sqlite3_opentemp_count++; /* Used for testing and analysis only */ +#endif + + vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; + rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0); + assert( rc!=SQLITE_OK || isOpen(pFile) ); + return rc; +} + +/* +** Set the busy handler function. +** +** The pager invokes the busy-handler if sqlite3OsLock() returns +** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock, +** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE +** lock. It does *not* invoke the busy handler when upgrading from +** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE +** (which occurs during hot-journal rollback). Summary: +** +** Transition | Invokes xBusyHandler +** -------------------------------------------------------- +** NO_LOCK -> SHARED_LOCK | Yes +** SHARED_LOCK -> RESERVED_LOCK | No +** SHARED_LOCK -> EXCLUSIVE_LOCK | No +** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes +** +** If the busy-handler callback returns non-zero, the lock is +** retried. If it returns zero, then the SQLITE_BUSY error is +** returned to the caller of the pager API function. +*/ +SQLITE_PRIVATE void sqlite3PagerSetBusyhandler( + Pager *pPager, /* Pager object */ + int (*xBusyHandler)(void *), /* Pointer to busy-handler function */ + void *pBusyHandlerArg /* Argument to pass to xBusyHandler */ +){ + pPager->xBusyHandler = xBusyHandler; + pPager->pBusyHandlerArg = pBusyHandlerArg; + + if( isOpen(pPager->fd) ){ + void **ap = (void **)&pPager->xBusyHandler; + assert( ((int(*)(void *))(ap[0]))==xBusyHandler ); + assert( ap[1]==pBusyHandlerArg ); + sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap); + } +} + +/* +** Change the page size used by the Pager object. The new page size +** is passed in *pPageSize. +** +** If the pager is in the error state when this function is called, it +** is a no-op. The value returned is the error state error code (i.e. +** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL). +** +** Otherwise, if all of the following are true: +** +** * the new page size (value of *pPageSize) is valid (a power +** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and +** +** * there are no outstanding page references, and +** +** * the database is either not an in-memory database or it is +** an in-memory database that currently consists of zero pages. +** +** then the pager object page size is set to *pPageSize. +** +** If the page size is changed, then this function uses sqlite3PagerMalloc() +** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt +** fails, SQLITE_NOMEM is returned and the page size remains unchanged. +** In all other cases, SQLITE_OK is returned. +** +** If the page size is not changed, either because one of the enumerated +** conditions above is not true, the pager was in error state when this +** function was called, or because the memory allocation attempt failed, +** then *pPageSize is set to the old, retained page size before returning. +*/ +SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){ + int rc = SQLITE_OK; + + /* It is not possible to do a full assert_pager_state() here, as this + ** function may be called from within PagerOpen(), before the state + ** of the Pager object is internally consistent. + ** + ** At one point this function returned an error if the pager was in + ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that + ** there is at least one outstanding page reference, this function + ** is a no-op for that case anyhow. + */ + + u32 pageSize = *pPageSize; + assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) ); + if( (pPager->memDb==0 || pPager->dbSize==0) + && sqlite3PcacheRefCount(pPager->pPCache)==0 + && pageSize && pageSize!=(u32)pPager->pageSize + ){ + char *pNew = NULL; /* New temp space */ + i64 nByte = 0; + + if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){ + rc = sqlite3OsFileSize(pPager->fd, &nByte); + } + if( rc==SQLITE_OK ){ + pNew = (char *)sqlite3PageMalloc(pageSize); + if( !pNew ) rc = SQLITE_NOMEM; + } + + if( rc==SQLITE_OK ){ + pager_reset(pPager); + pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize); + pPager->pageSize = pageSize; + sqlite3PageFree(pPager->pTmpSpace); + pPager->pTmpSpace = pNew; + sqlite3PcacheSetPageSize(pPager->pPCache, pageSize); + } + } + + *pPageSize = pPager->pageSize; + if( rc==SQLITE_OK ){ + if( nReserve<0 ) nReserve = pPager->nReserve; + assert( nReserve>=0 && nReserve<1000 ); + pPager->nReserve = (i16)nReserve; + pagerReportSize(pPager); + pagerFixMaplimit(pPager); + } + return rc; +} + +/* +** Return a pointer to the "temporary page" buffer held internally +** by the pager. This is a buffer that is big enough to hold the +** entire content of a database page. This buffer is used internally +** during rollback and will be overwritten whenever a rollback +** occurs. But other modules are free to use it too, as long as +** no rollbacks are happening. +*/ +SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){ + return pPager->pTmpSpace; +} + +/* +** Attempt to set the maximum database page count if mxPage is positive. +** Make no changes if mxPage is zero or negative. And never reduce the +** maximum page count below the current size of the database. +** +** Regardless of mxPage, return the current maximum page count. +*/ +SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){ + if( mxPage>0 ){ + pPager->mxPgno = mxPage; + } + assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */ + assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */ + return pPager->mxPgno; +} + +/* +** The following set of routines are used to disable the simulated +** I/O error mechanism. These routines are used to avoid simulated +** errors in places where we do not care about errors. +** +** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops +** and generate no code. +*/ +#ifdef SQLITE_TEST +SQLITE_API extern int sqlite3_io_error_pending; +SQLITE_API extern int sqlite3_io_error_hit; +static int saved_cnt; +void disable_simulated_io_errors(void){ + saved_cnt = sqlite3_io_error_pending; + sqlite3_io_error_pending = -1; +} +void enable_simulated_io_errors(void){ + sqlite3_io_error_pending = saved_cnt; +} +#else +# define disable_simulated_io_errors() +# define enable_simulated_io_errors() +#endif + +/* +** Read the first N bytes from the beginning of the file into memory +** that pDest points to. +** +** If the pager was opened on a transient file (zFilename==""), or +** opened on a file less than N bytes in size, the output buffer is +** zeroed and SQLITE_OK returned. The rationale for this is that this +** function is used to read database headers, and a new transient or +** zero sized database has a header than consists entirely of zeroes. +** +** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered, +** the error code is returned to the caller and the contents of the +** output buffer undefined. +*/ +SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){ + int rc = SQLITE_OK; + memset(pDest, 0, N); + assert( isOpen(pPager->fd) || pPager->tempFile ); + + /* This routine is only called by btree immediately after creating + ** the Pager object. There has not been an opportunity to transition + ** to WAL mode yet. + */ + assert( !pagerUseWal(pPager) ); + + if( isOpen(pPager->fd) ){ + IOTRACE(("DBHDR %p 0 %d\n", pPager, N)) + rc = sqlite3OsRead(pPager->fd, pDest, N, 0); + if( rc==SQLITE_IOERR_SHORT_READ ){ + rc = SQLITE_OK; + } + } + return rc; +} + +/* +** This function may only be called when a read-transaction is open on +** the pager. It returns the total number of pages in the database. +** +** However, if the file is between 1 and bytes in size, then +** this is considered a 1 page file. +*/ +SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){ + assert( pPager->eState>=PAGER_READER ); + assert( pPager->eState!=PAGER_WRITER_FINISHED ); + *pnPage = (int)pPager->dbSize; +} + + +/* +** Try to obtain a lock of type locktype on the database file. If +** a similar or greater lock is already held, this function is a no-op +** (returning SQLITE_OK immediately). +** +** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke +** the busy callback if the lock is currently not available. Repeat +** until the busy callback returns false or until the attempt to +** obtain the lock succeeds. +** +** Return SQLITE_OK on success and an error code if we cannot obtain +** the lock. If the lock is obtained successfully, set the Pager.state +** variable to locktype before returning. +*/ +static int pager_wait_on_lock(Pager *pPager, int locktype){ + int rc; /* Return code */ + + /* Check that this is either a no-op (because the requested lock is + ** already held, or one of the transistions that the busy-handler + ** may be invoked during, according to the comment above + ** sqlite3PagerSetBusyhandler(). + */ + assert( (pPager->eLock>=locktype) + || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK) + || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK) + ); + + do { + rc = pagerLockDb(pPager, locktype); + }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) ); + return rc; +} + +/* +** Function assertTruncateConstraint(pPager) checks that one of the +** following is true for all dirty pages currently in the page-cache: +** +** a) The page number is less than or equal to the size of the +** current database image, in pages, OR +** +** b) if the page content were written at this time, it would not +** be necessary to write the current content out to the sub-journal +** (as determined by function subjRequiresPage()). +** +** If the condition asserted by this function were not true, and the +** dirty page were to be discarded from the cache via the pagerStress() +** routine, pagerStress() would not write the current page content to +** the database file. If a savepoint transaction were rolled back after +** this happened, the correct behavior would be to restore the current +** content of the page. However, since this content is not present in either +** the database file or the portion of the rollback journal and +** sub-journal rolled back the content could not be restored and the +** database image would become corrupt. It is therefore fortunate that +** this circumstance cannot arise. +*/ +#if defined(SQLITE_DEBUG) +static void assertTruncateConstraintCb(PgHdr *pPg){ + assert( pPg->flags&PGHDR_DIRTY ); + assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize ); +} +static void assertTruncateConstraint(Pager *pPager){ + sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb); +} +#else +# define assertTruncateConstraint(pPager) +#endif + +/* +** Truncate the in-memory database file image to nPage pages. This +** function does not actually modify the database file on disk. It +** just sets the internal state of the pager object so that the +** truncation will be done when the current transaction is committed. +** +** This function is only called right before committing a transaction. +** Once this function has been called, the transaction must either be +** rolled back or committed. It is not safe to call this function and +** then continue writing to the database. +*/ +SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){ + assert( pPager->dbSize>=nPage ); + assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); + pPager->dbSize = nPage; + + /* At one point the code here called assertTruncateConstraint() to + ** ensure that all pages being truncated away by this operation are, + ** if one or more savepoints are open, present in the savepoint + ** journal so that they can be restored if the savepoint is rolled + ** back. This is no longer necessary as this function is now only + ** called right before committing a transaction. So although the + ** Pager object may still have open savepoints (Pager.nSavepoint!=0), + ** they cannot be rolled back. So the assertTruncateConstraint() call + ** is no longer correct. */ +} + + +/* +** This function is called before attempting a hot-journal rollback. It +** syncs the journal file to disk, then sets pPager->journalHdr to the +** size of the journal file so that the pager_playback() routine knows +** that the entire journal file has been synced. +** +** Syncing a hot-journal to disk before attempting to roll it back ensures +** that if a power-failure occurs during the rollback, the process that +** attempts rollback following system recovery sees the same journal +** content as this process. +** +** If everything goes as planned, SQLITE_OK is returned. Otherwise, +** an SQLite error code. +*/ +static int pagerSyncHotJournal(Pager *pPager){ + int rc = SQLITE_OK; + if( !pPager->noSync ){ + rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL); + } + if( rc==SQLITE_OK ){ + rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr); + } + return rc; +} + +/* +** Obtain a reference to a memory mapped page object for page number pgno. +** The new object will use the pointer pData, obtained from xFetch(). +** If successful, set *ppPage to point to the new page reference +** and return SQLITE_OK. Otherwise, return an SQLite error code and set +** *ppPage to zero. +** +** Page references obtained by calling this function should be released +** by calling pagerReleaseMapPage(). +*/ +static int pagerAcquireMapPage( + Pager *pPager, /* Pager object */ + Pgno pgno, /* Page number */ + void *pData, /* xFetch()'d data for this page */ + PgHdr **ppPage /* OUT: Acquired page object */ +){ + PgHdr *p; /* Memory mapped page to return */ + + if( pPager->pMmapFreelist ){ + *ppPage = p = pPager->pMmapFreelist; + pPager->pMmapFreelist = p->pDirty; + p->pDirty = 0; + memset(p->pExtra, 0, pPager->nExtra); + }else{ + *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra); + if( p==0 ){ + sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData); + return SQLITE_NOMEM; + } + p->pExtra = (void *)&p[1]; + p->flags = PGHDR_MMAP; + p->nRef = 1; + p->pPager = pPager; + } + + assert( p->pExtra==(void *)&p[1] ); + assert( p->pPage==0 ); + assert( p->flags==PGHDR_MMAP ); + assert( p->pPager==pPager ); + assert( p->nRef==1 ); + + p->pgno = pgno; + p->pData = pData; + pPager->nMmapOut++; + + return SQLITE_OK; +} + +/* +** Release a reference to page pPg. pPg must have been returned by an +** earlier call to pagerAcquireMapPage(). +*/ +static void pagerReleaseMapPage(PgHdr *pPg){ + Pager *pPager = pPg->pPager; + pPager->nMmapOut--; + pPg->pDirty = pPager->pMmapFreelist; + pPager->pMmapFreelist = pPg; + + assert( pPager->fd->pMethods->iVersion>=3 ); + sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData); +} + +/* +** Free all PgHdr objects stored in the Pager.pMmapFreelist list. +*/ +static void pagerFreeMapHdrs(Pager *pPager){ + PgHdr *p; + PgHdr *pNext; + for(p=pPager->pMmapFreelist; p; p=pNext){ + pNext = p->pDirty; + sqlite3_free(p); + } +} + + +/* +** Shutdown the page cache. Free all memory and close all files. +** +** If a transaction was in progress when this routine is called, that +** transaction is rolled back. All outstanding pages are invalidated +** and their memory is freed. Any attempt to use a page associated +** with this page cache after this function returns will likely +** result in a coredump. +** +** This function always succeeds. If a transaction is active an attempt +** is made to roll it back. If an error occurs during the rollback +** a hot journal may be left in the filesystem but no error is returned +** to the caller. +*/ +SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){ + u8 *pTmp = (u8 *)pPager->pTmpSpace; + + assert( assert_pager_state(pPager) ); + disable_simulated_io_errors(); + sqlite3BeginBenignMalloc(); + pagerFreeMapHdrs(pPager); + /* pPager->errCode = 0; */ + pPager->exclusiveMode = 0; +#ifndef SQLITE_OMIT_WAL + sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp); + pPager->pWal = 0; +#endif + pager_reset(pPager); + if( MEMDB ){ + pager_unlock(pPager); + }else{ + /* If it is open, sync the journal file before calling UnlockAndRollback. + ** If this is not done, then an unsynced portion of the open journal + ** file may be played back into the database. If a power failure occurs + ** while this is happening, the database could become corrupt. + ** + ** If an error occurs while trying to sync the journal, shift the pager + ** into the ERROR state. This causes UnlockAndRollback to unlock the + ** database and close the journal file without attempting to roll it + ** back or finalize it. The next database user will have to do hot-journal + ** rollback before accessing the database file. + */ + if( isOpen(pPager->jfd) ){ + pager_error(pPager, pagerSyncHotJournal(pPager)); + } + pagerUnlockAndRollback(pPager); + } + sqlite3EndBenignMalloc(); + enable_simulated_io_errors(); + PAGERTRACE(("CLOSE %d\n", PAGERID(pPager))); + IOTRACE(("CLOSE %p\n", pPager)) + sqlite3OsClose(pPager->jfd); + sqlite3OsClose(pPager->fd); + sqlite3PageFree(pTmp); + sqlite3PcacheClose(pPager->pPCache); + +#ifdef SQLITE_HAS_CODEC + if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); +#endif + + assert( !pPager->aSavepoint && !pPager->pInJournal ); + assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ); + + sqlite3_free(pPager); + return SQLITE_OK; +} + +#if !defined(NDEBUG) || defined(SQLITE_TEST) +/* +** Return the page number for page pPg. +*/ +SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){ + return pPg->pgno; +} +#endif + +/* +** Increment the reference count for page pPg. +*/ +SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){ + sqlite3PcacheRef(pPg); +} + +/* +** Sync the journal. In other words, make sure all the pages that have +** been written to the journal have actually reached the surface of the +** disk and can be restored in the event of a hot-journal rollback. +** +** If the Pager.noSync flag is set, then this function is a no-op. +** Otherwise, the actions required depend on the journal-mode and the +** device characteristics of the file-system, as follows: +** +** * If the journal file is an in-memory journal file, no action need +** be taken. +** +** * Otherwise, if the device does not support the SAFE_APPEND property, +** then the nRec field of the most recently written journal header +** is updated to contain the number of journal records that have +** been written following it. If the pager is operating in full-sync +** mode, then the journal file is synced before this field is updated. +** +** * If the device does not support the SEQUENTIAL property, then +** journal file is synced. +** +** Or, in pseudo-code: +** +** if( NOT ){ +** if( NOT SAFE_APPEND ){ +** if( ) xSync(); +** +** } +** if( NOT SEQUENTIAL ) xSync(); +** } +** +** If successful, this routine clears the PGHDR_NEED_SYNC flag of every +** page currently held in memory before returning SQLITE_OK. If an IO +** error is encountered, then the IO error code is returned to the caller. +*/ +static int syncJournal(Pager *pPager, int newHdr){ + int rc; /* Return code */ + + assert( pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + ); + assert( assert_pager_state(pPager) ); + assert( !pagerUseWal(pPager) ); + + rc = sqlite3PagerExclusiveLock(pPager); + if( rc!=SQLITE_OK ) return rc; + + if( !pPager->noSync ){ + assert( !pPager->tempFile ); + if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){ + const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); + assert( isOpen(pPager->jfd) ); + + if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ + /* This block deals with an obscure problem. If the last connection + ** that wrote to this database was operating in persistent-journal + ** mode, then the journal file may at this point actually be larger + ** than Pager.journalOff bytes. If the next thing in the journal + ** file happens to be a journal-header (written as part of the + ** previous connection's transaction), and a crash or power-failure + ** occurs after nRec is updated but before this connection writes + ** anything else to the journal file (or commits/rolls back its + ** transaction), then SQLite may become confused when doing the + ** hot-journal rollback following recovery. It may roll back all + ** of this connections data, then proceed to rolling back the old, + ** out-of-date data that follows it. Database corruption. + ** + ** To work around this, if the journal file does appear to contain + ** a valid header following Pager.journalOff, then write a 0x00 + ** byte to the start of it to prevent it from being recognized. + ** + ** Variable iNextHdrOffset is set to the offset at which this + ** problematic header will occur, if it exists. aMagic is used + ** as a temporary buffer to inspect the first couple of bytes of + ** the potential journal header. + */ + i64 iNextHdrOffset; + u8 aMagic[8]; + u8 zHeader[sizeof(aJournalMagic)+4]; + + memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); + put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec); + + iNextHdrOffset = journalHdrOffset(pPager); + rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset); + if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){ + static const u8 zerobyte = 0; + rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset); + } + if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ + return rc; + } + + /* Write the nRec value into the journal file header. If in + ** full-synchronous mode, sync the journal first. This ensures that + ** all data has really hit the disk before nRec is updated to mark + ** it as a candidate for rollback. + ** + ** This is not required if the persistent media supports the + ** SAFE_APPEND property. Because in this case it is not possible + ** for garbage data to be appended to the file, the nRec field + ** is populated with 0xFFFFFFFF when the journal header is written + ** and never needs to be updated. + */ + if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ + PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); + IOTRACE(("JSYNC %p\n", pPager)) + rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); + if( rc!=SQLITE_OK ) return rc; + } + IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr)); + rc = sqlite3OsWrite( + pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr + ); + if( rc!=SQLITE_OK ) return rc; + } + if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ + PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); + IOTRACE(("JSYNC %p\n", pPager)) + rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| + (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0) + ); + if( rc!=SQLITE_OK ) return rc; + } + + pPager->journalHdr = pPager->journalOff; + if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ + pPager->nRec = 0; + rc = writeJournalHdr(pPager); + if( rc!=SQLITE_OK ) return rc; + } + }else{ + pPager->journalHdr = pPager->journalOff; + } + } + + /* Unless the pager is in noSync mode, the journal file was just + ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on + ** all pages. + */ + sqlite3PcacheClearSyncFlags(pPager->pPCache); + pPager->eState = PAGER_WRITER_DBMOD; + assert( assert_pager_state(pPager) ); + return SQLITE_OK; +} + +/* +** The argument is the first in a linked list of dirty pages connected +** by the PgHdr.pDirty pointer. This function writes each one of the +** in-memory pages in the list to the database file. The argument may +** be NULL, representing an empty list. In this case this function is +** a no-op. +** +** The pager must hold at least a RESERVED lock when this function +** is called. Before writing anything to the database file, this lock +** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained, +** SQLITE_BUSY is returned and no data is written to the database file. +** +** If the pager is a temp-file pager and the actual file-system file +** is not yet open, it is created and opened before any data is +** written out. +** +** Once the lock has been upgraded and, if necessary, the file opened, +** the pages are written out to the database file in list order. Writing +** a page is skipped if it meets either of the following criteria: +** +** * The page number is greater than Pager.dbSize, or +** * The PGHDR_DONT_WRITE flag is set on the page. +** +** If writing out a page causes the database file to grow, Pager.dbFileSize +** is updated accordingly. If page 1 is written out, then the value cached +** in Pager.dbFileVers[] is updated to match the new value stored in +** the database file. +** +** If everything is successful, SQLITE_OK is returned. If an IO error +** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot +** be obtained, SQLITE_BUSY is returned. +*/ +static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ + int rc = SQLITE_OK; /* Return code */ + + /* This function is only called for rollback pagers in WRITER_DBMOD state. */ + assert( !pagerUseWal(pPager) ); + assert( pPager->eState==PAGER_WRITER_DBMOD ); + assert( pPager->eLock==EXCLUSIVE_LOCK ); + + /* If the file is a temp-file has not yet been opened, open it now. It + ** is not possible for rc to be other than SQLITE_OK if this branch + ** is taken, as pager_wait_on_lock() is a no-op for temp-files. + */ + if( !isOpen(pPager->fd) ){ + assert( pPager->tempFile && rc==SQLITE_OK ); + rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags); + } + + /* Before the first write, give the VFS a hint of what the final + ** file size will be. + */ + assert( rc!=SQLITE_OK || isOpen(pPager->fd) ); + if( rc==SQLITE_OK + && pPager->dbHintSizedbSize + && (pList->pDirty || pList->pgno>pPager->dbHintSize) + ){ + sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize; + sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile); + pPager->dbHintSize = pPager->dbSize; + } + + while( rc==SQLITE_OK && pList ){ + Pgno pgno = pList->pgno; + + /* If there are dirty pages in the page cache with page numbers greater + ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to + ** make the file smaller (presumably by auto-vacuum code). Do not write + ** any such pages to the file. + ** + ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag + ** set (set by sqlite3PagerDontWrite()). + */ + if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){ + i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */ + char *pData; /* Data to write */ + + assert( (pList->flags&PGHDR_NEED_SYNC)==0 ); + if( pList->pgno==1 ) pager_write_changecounter(pList); + + /* Encode the database */ + CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData); + + /* Write out the page data. */ + rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset); + + /* If page 1 was just written, update Pager.dbFileVers to match + ** the value now stored in the database file. If writing this + ** page caused the database file to grow, update dbFileSize. + */ + if( pgno==1 ){ + memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers)); + } + if( pgno>pPager->dbFileSize ){ + pPager->dbFileSize = pgno; + } + pPager->aStat[PAGER_STAT_WRITE]++; + + /* Update any backup objects copying the contents of this pager. */ + sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData); + + PAGERTRACE(("STORE %d page %d hash(%08x)\n", + PAGERID(pPager), pgno, pager_pagehash(pList))); + IOTRACE(("PGOUT %p %d\n", pPager, pgno)); + PAGER_INCR(sqlite3_pager_writedb_count); + }else{ + PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno)); + } + pager_set_pagehash(pList); + pList = pList->pDirty; + } + + return rc; +} + +/* +** Ensure that the sub-journal file is open. If it is already open, this +** function is a no-op. +** +** SQLITE_OK is returned if everything goes according to plan. An +** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() +** fails. +*/ +static int openSubJournal(Pager *pPager){ + int rc = SQLITE_OK; + if( !isOpen(pPager->sjfd) ){ + if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){ + sqlite3MemJournalOpen(pPager->sjfd); + }else{ + rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL); + } + } + return rc; +} + +/* +** Append a record of the current state of page pPg to the sub-journal. +** It is the callers responsibility to use subjRequiresPage() to check +** that it is really required before calling this function. +** +** If successful, set the bit corresponding to pPg->pgno in the bitvecs +** for all open savepoints before returning. +** +** This function returns SQLITE_OK if everything is successful, an IO +** error code if the attempt to write to the sub-journal fails, or +** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint +** bitvec. +*/ +static int subjournalPage(PgHdr *pPg){ + int rc = SQLITE_OK; + Pager *pPager = pPg->pPager; + if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ + + /* Open the sub-journal, if it has not already been opened */ + assert( pPager->useJournal ); + assert( isOpen(pPager->jfd) || pagerUseWal(pPager) ); + assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 ); + assert( pagerUseWal(pPager) + || pageInJournal(pPg) + || pPg->pgno>pPager->dbOrigSize + ); + rc = openSubJournal(pPager); + + /* If the sub-journal was opened successfully (or was already open), + ** write the journal record into the file. */ + if( rc==SQLITE_OK ){ + void *pData = pPg->pData; + i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize); + char *pData2; + + CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2); + PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno)); + rc = write32bits(pPager->sjfd, offset, pPg->pgno); + if( rc==SQLITE_OK ){ + rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4); + } + } + } + if( rc==SQLITE_OK ){ + pPager->nSubRec++; + assert( pPager->nSavepoint>0 ); + rc = addToSavepointBitvecs(pPager, pPg->pgno); + } + return rc; +} + +/* +** This function is called by the pcache layer when it has reached some +** soft memory limit. The first argument is a pointer to a Pager object +** (cast as a void*). The pager is always 'purgeable' (not an in-memory +** database). The second argument is a reference to a page that is +** currently dirty but has no outstanding references. The page +** is always associated with the Pager object passed as the first +** argument. +** +** The job of this function is to make pPg clean by writing its contents +** out to the database file, if possible. This may involve syncing the +** journal file. +** +** If successful, sqlite3PcacheMakeClean() is called on the page and +** SQLITE_OK returned. If an IO error occurs while trying to make the +** page clean, the IO error code is returned. If the page cannot be +** made clean for some other reason, but no error occurs, then SQLITE_OK +** is returned by sqlite3PcacheMakeClean() is not called. +*/ +static int pagerStress(void *p, PgHdr *pPg){ + Pager *pPager = (Pager *)p; + int rc = SQLITE_OK; + + assert( pPg->pPager==pPager ); + assert( pPg->flags&PGHDR_DIRTY ); + + /* The doNotSpill NOSYNC bit is set during times when doing a sync of + ** journal (and adding a new header) is not allowed. This occurs + ** during calls to sqlite3PagerWrite() while trying to journal multiple + ** pages belonging to the same sector. + ** + ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling + ** regardless of whether or not a sync is required. This is set during + ** a rollback or by user request, respectively. + ** + ** Spilling is also prohibited when in an error state since that could + ** lead to database corruption. In the current implementaton it + ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1 + ** while in the error state, hence it is impossible for this routine to + ** be called in the error state. Nevertheless, we include a NEVER() + ** test for the error state as a safeguard against future changes. + */ + if( NEVER(pPager->errCode) ) return SQLITE_OK; + testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK ); + testcase( pPager->doNotSpill & SPILLFLAG_OFF ); + testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC ); + if( pPager->doNotSpill + && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0 + || (pPg->flags & PGHDR_NEED_SYNC)!=0) + ){ + return SQLITE_OK; + } + + pPg->pDirty = 0; + if( pagerUseWal(pPager) ){ + /* Write a single frame for this page to the log. */ + if( subjRequiresPage(pPg) ){ + rc = subjournalPage(pPg); + } + if( rc==SQLITE_OK ){ + rc = pagerWalFrames(pPager, pPg, 0, 0); + } + }else{ + + /* Sync the journal file if required. */ + if( pPg->flags&PGHDR_NEED_SYNC + || pPager->eState==PAGER_WRITER_CACHEMOD + ){ + rc = syncJournal(pPager, 1); + } + + /* If the page number of this page is larger than the current size of + ** the database image, it may need to be written to the sub-journal. + ** This is because the call to pager_write_pagelist() below will not + ** actually write data to the file in this case. + ** + ** Consider the following sequence of events: + ** + ** BEGIN; + ** + ** + ** SAVEPOINT sp; + ** + ** pagerStress(page X) + ** ROLLBACK TO sp; + ** + ** If (X>Y), then when pagerStress is called page X will not be written + ** out to the database file, but will be dropped from the cache. Then, + ** following the "ROLLBACK TO sp" statement, reading page X will read + ** data from the database file. This will be the copy of page X as it + ** was when the transaction started, not as it was when "SAVEPOINT sp" + ** was executed. + ** + ** The solution is to write the current data for page X into the + ** sub-journal file now (if it is not already there), so that it will + ** be restored to its current value when the "ROLLBACK TO sp" is + ** executed. + */ + if( NEVER( + rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg) + ) ){ + rc = subjournalPage(pPg); + } + + /* Write the contents of the page out to the database file. */ + if( rc==SQLITE_OK ){ + assert( (pPg->flags&PGHDR_NEED_SYNC)==0 ); + rc = pager_write_pagelist(pPager, pPg); + } + } + + /* Mark the page as clean. */ + if( rc==SQLITE_OK ){ + PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno)); + sqlite3PcacheMakeClean(pPg); + } + + return pager_error(pPager, rc); +} + + +/* +** Allocate and initialize a new Pager object and put a pointer to it +** in *ppPager. The pager should eventually be freed by passing it +** to sqlite3PagerClose(). +** +** The zFilename argument is the path to the database file to open. +** If zFilename is NULL then a randomly-named temporary file is created +** and used as the file to be cached. Temporary files are be deleted +** automatically when they are closed. If zFilename is ":memory:" then +** all information is held in cache. It is never written to disk. +** This can be used to implement an in-memory database. +** +** The nExtra parameter specifies the number of bytes of space allocated +** along with each page reference. This space is available to the user +** via the sqlite3PagerGetExtra() API. +** +** The flags argument is used to specify properties that affect the +** operation of the pager. It should be passed some bitwise combination +** of the PAGER_* flags. +** +** The vfsFlags parameter is a bitmask to pass to the flags parameter +** of the xOpen() method of the supplied VFS when opening files. +** +** If the pager object is allocated and the specified file opened +** successfully, SQLITE_OK is returned and *ppPager set to point to +** the new pager object. If an error occurs, *ppPager is set to NULL +** and error code returned. This function may return SQLITE_NOMEM +** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or +** various SQLITE_IO_XXX errors. +*/ +SQLITE_PRIVATE int sqlite3PagerOpen( + sqlite3_vfs *pVfs, /* The virtual file system to use */ + Pager **ppPager, /* OUT: Return the Pager structure here */ + const char *zFilename, /* Name of the database file to open */ + int nExtra, /* Extra bytes append to each in-memory page */ + int flags, /* flags controlling this file */ + int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */ + void (*xReinit)(DbPage*) /* Function to reinitialize pages */ +){ + u8 *pPtr; + Pager *pPager = 0; /* Pager object to allocate and return */ + int rc = SQLITE_OK; /* Return code */ + int tempFile = 0; /* True for temp files (incl. in-memory files) */ + int memDb = 0; /* True if this is an in-memory file */ + int readOnly = 0; /* True if this is a read-only file */ + int journalFileSize; /* Bytes to allocate for each journal fd */ + char *zPathname = 0; /* Full path to database file */ + int nPathname = 0; /* Number of bytes in zPathname */ + int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */ + int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */ + u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */ + const char *zUri = 0; /* URI args to copy */ + int nUri = 0; /* Number of bytes of URI args at *zUri */ + + /* Figure out how much space is required for each journal file-handle + ** (there are two of them, the main journal and the sub-journal). This + ** is the maximum space required for an in-memory journal file handle + ** and a regular journal file-handle. Note that a "regular journal-handle" + ** may be a wrapper capable of caching the first portion of the journal + ** file in memory to implement the atomic-write optimization (see + ** source file journal.c). + */ + if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){ + journalFileSize = ROUND8(sqlite3JournalSize(pVfs)); + }else{ + journalFileSize = ROUND8(sqlite3MemJournalSize()); + } + + /* Set the output variable to NULL in case an error occurs. */ + *ppPager = 0; + +#ifndef SQLITE_OMIT_MEMORYDB + if( flags & PAGER_MEMORY ){ + memDb = 1; + if( zFilename && zFilename[0] ){ + zPathname = sqlite3DbStrDup(0, zFilename); + if( zPathname==0 ) return SQLITE_NOMEM; + nPathname = sqlite3Strlen30(zPathname); + zFilename = 0; + } + } +#endif + + /* Compute and store the full pathname in an allocated buffer pointed + ** to by zPathname, length nPathname. Or, if this is a temporary file, + ** leave both nPathname and zPathname set to 0. + */ + if( zFilename && zFilename[0] ){ + const char *z; + nPathname = pVfs->mxPathname+1; + zPathname = sqlite3DbMallocRaw(0, nPathname*2); + if( zPathname==0 ){ + return SQLITE_NOMEM; + } + zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ + rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname); + nPathname = sqlite3Strlen30(zPathname); + z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1]; + while( *z ){ + z += sqlite3Strlen30(z)+1; + z += sqlite3Strlen30(z)+1; + } + nUri = (int)(&z[1] - zUri); + assert( nUri>=0 ); + if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){ + /* This branch is taken when the journal path required by + ** the database being opened will be more than pVfs->mxPathname + ** bytes in length. This means the database cannot be opened, + ** as it will not be possible to open the journal file or even + ** check for a hot-journal before reading. + */ + rc = SQLITE_CANTOPEN_BKPT; + } + if( rc!=SQLITE_OK ){ + sqlite3DbFree(0, zPathname); + return rc; + } + } + + /* Allocate memory for the Pager structure, PCache object, the + ** three file descriptors, the database file name and the journal + ** file name. The layout in memory is as follows: + ** + ** Pager object (sizeof(Pager) bytes) + ** PCache object (sqlite3PcacheSize() bytes) + ** Database file handle (pVfs->szOsFile bytes) + ** Sub-journal file handle (journalFileSize bytes) + ** Main journal file handle (journalFileSize bytes) + ** Database file name (nPathname+1 bytes) + ** Journal file name (nPathname+8+1 bytes) + */ + pPtr = (u8 *)sqlite3MallocZero( + ROUND8(sizeof(*pPager)) + /* Pager structure */ + ROUND8(pcacheSize) + /* PCache object */ + ROUND8(pVfs->szOsFile) + /* The main db file */ + journalFileSize * 2 + /* The two journal files */ + nPathname + 1 + nUri + /* zFilename */ + nPathname + 8 + 2 /* zJournal */ +#ifndef SQLITE_OMIT_WAL + + nPathname + 4 + 2 /* zWal */ +#endif + ); + assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) ); + if( !pPtr ){ + sqlite3DbFree(0, zPathname); + return SQLITE_NOMEM; + } + pPager = (Pager*)(pPtr); + pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager))); + pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize)); + pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile)); + pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize); + pPager->zFilename = (char*)(pPtr += journalFileSize); + assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) ); + + /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */ + if( zPathname ){ + assert( nPathname>0 ); + pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri); + memcpy(pPager->zFilename, zPathname, nPathname); + if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri); + memcpy(pPager->zJournal, zPathname, nPathname); + memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2); + sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal); +#ifndef SQLITE_OMIT_WAL + pPager->zWal = &pPager->zJournal[nPathname+8+1]; + memcpy(pPager->zWal, zPathname, nPathname); + memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1); + sqlite3FileSuffix3(pPager->zFilename, pPager->zWal); +#endif + sqlite3DbFree(0, zPathname); + } + pPager->pVfs = pVfs; + pPager->vfsFlags = vfsFlags; + + /* Open the pager file. + */ + if( zFilename && zFilename[0] ){ + int fout = 0; /* VFS flags returned by xOpen() */ + rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout); + assert( !memDb ); + readOnly = (fout&SQLITE_OPEN_READONLY); + + /* If the file was successfully opened for read/write access, + ** choose a default page size in case we have to create the + ** database file. The default page size is the maximum of: + ** + ** + SQLITE_DEFAULT_PAGE_SIZE, + ** + The value returned by sqlite3OsSectorSize() + ** + The largest page size that can be written atomically. + */ + if( rc==SQLITE_OK && !readOnly ){ + setSectorSize(pPager); + assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE); + if( szPageDfltsectorSize ){ + if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){ + szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE; + }else{ + szPageDflt = (u32)pPager->sectorSize; + } + } +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + { + int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); + int ii; + assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); + assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); + assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536); + for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){ + if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){ + szPageDflt = ii; + } + } + } +#endif + } + }else{ + /* If a temporary file is requested, it is not opened immediately. + ** In this case we accept the default page size and delay actually + ** opening the file until the first call to OsWrite(). + ** + ** This branch is also run for an in-memory database. An in-memory + ** database is the same as a temp-file that is never written out to + ** disk and uses an in-memory rollback journal. + */ + tempFile = 1; + pPager->eState = PAGER_READER; + pPager->eLock = EXCLUSIVE_LOCK; + readOnly = (vfsFlags&SQLITE_OPEN_READONLY); + } + + /* The following call to PagerSetPagesize() serves to set the value of + ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer. + */ + if( rc==SQLITE_OK ){ + assert( pPager->memDb==0 ); + rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1); + testcase( rc!=SQLITE_OK ); + } + + /* If an error occurred in either of the blocks above, free the + ** Pager structure and close the file. + */ + if( rc!=SQLITE_OK ){ + assert( !pPager->pTmpSpace ); + sqlite3OsClose(pPager->fd); + sqlite3_free(pPager); + return rc; + } + + /* Initialize the PCache object. */ + assert( nExtra<1000 ); + nExtra = ROUND8(nExtra); + sqlite3PcacheOpen(szPageDflt, nExtra, !memDb, + !memDb?pagerStress:0, (void *)pPager, pPager->pPCache); + + PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename)); + IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename)) + + pPager->useJournal = (u8)useJournal; + /* pPager->stmtOpen = 0; */ + /* pPager->stmtInUse = 0; */ + /* pPager->nRef = 0; */ + /* pPager->stmtSize = 0; */ + /* pPager->stmtJSize = 0; */ + /* pPager->nPage = 0; */ + pPager->mxPgno = SQLITE_MAX_PAGE_COUNT; + /* pPager->state = PAGER_UNLOCK; */ +#if 0 + assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) ); +#endif + /* pPager->errMask = 0; */ + pPager->tempFile = (u8)tempFile; + assert( tempFile==PAGER_LOCKINGMODE_NORMAL + || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE ); + assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 ); + pPager->exclusiveMode = (u8)tempFile; + pPager->changeCountDone = pPager->tempFile; + pPager->memDb = (u8)memDb; + pPager->readOnly = (u8)readOnly; + assert( useJournal || pPager->tempFile ); + pPager->noSync = pPager->tempFile; + if( pPager->noSync ){ + assert( pPager->fullSync==0 ); + assert( pPager->syncFlags==0 ); + assert( pPager->walSyncFlags==0 ); + assert( pPager->ckptSyncFlags==0 ); + }else{ + pPager->fullSync = 1; + pPager->syncFlags = SQLITE_SYNC_NORMAL; + pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS; + pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; + } + /* pPager->pFirst = 0; */ + /* pPager->pFirstSynced = 0; */ + /* pPager->pLast = 0; */ + pPager->nExtra = (u16)nExtra; + pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT; + assert( isOpen(pPager->fd) || tempFile ); + setSectorSize(pPager); + if( !useJournal ){ + pPager->journalMode = PAGER_JOURNALMODE_OFF; + }else if( memDb ){ + pPager->journalMode = PAGER_JOURNALMODE_MEMORY; + } + /* pPager->xBusyHandler = 0; */ + /* pPager->pBusyHandlerArg = 0; */ + pPager->xReiniter = xReinit; + /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */ + /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */ + + *ppPager = pPager; + return SQLITE_OK; +} + + + +/* +** This function is called after transitioning from PAGER_UNLOCK to +** PAGER_SHARED state. It tests if there is a hot journal present in +** the file-system for the given pager. A hot journal is one that +** needs to be played back. According to this function, a hot-journal +** file exists if the following criteria are met: +** +** * The journal file exists in the file system, and +** * No process holds a RESERVED or greater lock on the database file, and +** * The database file itself is greater than 0 bytes in size, and +** * The first byte of the journal file exists and is not 0x00. +** +** If the current size of the database file is 0 but a journal file +** exists, that is probably an old journal left over from a prior +** database with the same name. In this case the journal file is +** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK +** is returned. +** +** This routine does not check if there is a master journal filename +** at the end of the file. If there is, and that master journal file +** does not exist, then the journal file is not really hot. In this +** case this routine will return a false-positive. The pager_playback() +** routine will discover that the journal file is not really hot and +** will not roll it back. +** +** If a hot-journal file is found to exist, *pExists is set to 1 and +** SQLITE_OK returned. If no hot-journal file is present, *pExists is +** set to 0 and SQLITE_OK returned. If an IO error occurs while trying +** to determine whether or not a hot-journal file exists, the IO error +** code is returned and the value of *pExists is undefined. +*/ +static int hasHotJournal(Pager *pPager, int *pExists){ + sqlite3_vfs * const pVfs = pPager->pVfs; + int rc = SQLITE_OK; /* Return code */ + int exists = 1; /* True if a journal file is present */ + int jrnlOpen = !!isOpen(pPager->jfd); + + assert( pPager->useJournal ); + assert( isOpen(pPager->fd) ); + assert( pPager->eState==PAGER_OPEN ); + + assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) & + SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN + )); + + *pExists = 0; + if( !jrnlOpen ){ + rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists); + } + if( rc==SQLITE_OK && exists ){ + int locked = 0; /* True if some process holds a RESERVED lock */ + + /* Race condition here: Another process might have been holding the + ** the RESERVED lock and have a journal open at the sqlite3OsAccess() + ** call above, but then delete the journal and drop the lock before + ** we get to the following sqlite3OsCheckReservedLock() call. If that + ** is the case, this routine might think there is a hot journal when + ** in fact there is none. This results in a false-positive which will + ** be dealt with by the playback routine. Ticket #3883. + */ + rc = sqlite3OsCheckReservedLock(pPager->fd, &locked); + if( rc==SQLITE_OK && !locked ){ + Pgno nPage; /* Number of pages in database file */ + + /* Check the size of the database file. If it consists of 0 pages, + ** then delete the journal file. See the header comment above for + ** the reasoning here. Delete the obsolete journal file under + ** a RESERVED lock to avoid race conditions and to avoid violating + ** [H33020]. + */ + rc = pagerPagecount(pPager, &nPage); + if( rc==SQLITE_OK ){ + if( nPage==0 ){ + sqlite3BeginBenignMalloc(); + if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){ + sqlite3OsDelete(pVfs, pPager->zJournal, 0); + if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK); + } + sqlite3EndBenignMalloc(); + }else{ + /* The journal file exists and no other connection has a reserved + ** or greater lock on the database file. Now check that there is + ** at least one non-zero bytes at the start of the journal file. + ** If there is, then we consider this journal to be hot. If not, + ** it can be ignored. + */ + if( !jrnlOpen ){ + int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL; + rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f); + } + if( rc==SQLITE_OK ){ + u8 first = 0; + rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0); + if( rc==SQLITE_IOERR_SHORT_READ ){ + rc = SQLITE_OK; + } + if( !jrnlOpen ){ + sqlite3OsClose(pPager->jfd); + } + *pExists = (first!=0); + }else if( rc==SQLITE_CANTOPEN ){ + /* If we cannot open the rollback journal file in order to see if + ** its has a zero header, that might be due to an I/O error, or + ** it might be due to the race condition described above and in + ** ticket #3883. Either way, assume that the journal is hot. + ** This might be a false positive. But if it is, then the + ** automatic journal playback and recovery mechanism will deal + ** with it under an EXCLUSIVE lock where we do not need to + ** worry so much with race conditions. + */ + *pExists = 1; + rc = SQLITE_OK; + } + } + } + } + } + + return rc; +} + +/* +** This function is called to obtain a shared lock on the database file. +** It is illegal to call sqlite3PagerAcquire() until after this function +** has been successfully called. If a shared-lock is already held when +** this function is called, it is a no-op. +** +** The following operations are also performed by this function. +** +** 1) If the pager is currently in PAGER_OPEN state (no lock held +** on the database file), then an attempt is made to obtain a +** SHARED lock on the database file. Immediately after obtaining +** the SHARED lock, the file-system is checked for a hot-journal, +** which is played back if present. Following any hot-journal +** rollback, the contents of the cache are validated by checking +** the 'change-counter' field of the database file header and +** discarded if they are found to be invalid. +** +** 2) If the pager is running in exclusive-mode, and there are currently +** no outstanding references to any pages, and is in the error state, +** then an attempt is made to clear the error state by discarding +** the contents of the page cache and rolling back any open journal +** file. +** +** If everything is successful, SQLITE_OK is returned. If an IO error +** occurs while locking the database, checking for a hot-journal file or +** rolling back a journal file, the IO error code is returned. +*/ +SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + + /* This routine is only called from b-tree and only when there are no + ** outstanding pages. This implies that the pager state should either + ** be OPEN or READER. READER is only possible if the pager is or was in + ** exclusive access mode. + */ + assert( sqlite3PcacheRefCount(pPager->pPCache)==0 ); + assert( assert_pager_state(pPager) ); + assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); + if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; } + + if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){ + int bHotJournal = 1; /* True if there exists a hot journal-file */ + + assert( !MEMDB ); + + rc = pager_wait_on_lock(pPager, SHARED_LOCK); + if( rc!=SQLITE_OK ){ + assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK ); + goto failed; + } + + /* If a journal file exists, and there is no RESERVED lock on the + ** database file, then it either needs to be played back or deleted. + */ + if( pPager->eLock<=SHARED_LOCK ){ + rc = hasHotJournal(pPager, &bHotJournal); + } + if( rc!=SQLITE_OK ){ + goto failed; + } + if( bHotJournal ){ + if( pPager->readOnly ){ + rc = SQLITE_READONLY_ROLLBACK; + goto failed; + } + + /* Get an EXCLUSIVE lock on the database file. At this point it is + ** important that a RESERVED lock is not obtained on the way to the + ** EXCLUSIVE lock. If it were, another process might open the + ** database file, detect the RESERVED lock, and conclude that the + ** database is safe to read while this process is still rolling the + ** hot-journal back. + ** + ** Because the intermediate RESERVED lock is not requested, any + ** other process attempting to access the database file will get to + ** this point in the code and fail to obtain its own EXCLUSIVE lock + ** on the database file. + ** + ** Unless the pager is in locking_mode=exclusive mode, the lock is + ** downgraded to SHARED_LOCK before this function returns. + */ + rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); + if( rc!=SQLITE_OK ){ + goto failed; + } + + /* If it is not already open and the file exists on disk, open the + ** journal for read/write access. Write access is required because + ** in exclusive-access mode the file descriptor will be kept open + ** and possibly used for a transaction later on. Also, write-access + ** is usually required to finalize the journal in journal_mode=persist + ** mode (and also for journal_mode=truncate on some systems). + ** + ** If the journal does not exist, it usually means that some + ** other connection managed to get in and roll it back before + ** this connection obtained the exclusive lock above. Or, it + ** may mean that the pager was in the error-state when this + ** function was called and the journal file does not exist. + */ + if( !isOpen(pPager->jfd) ){ + sqlite3_vfs * const pVfs = pPager->pVfs; + int bExists; /* True if journal file exists */ + rc = sqlite3OsAccess( + pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists); + if( rc==SQLITE_OK && bExists ){ + int fout = 0; + int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL; + assert( !pPager->tempFile ); + rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); + assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); + if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){ + rc = SQLITE_CANTOPEN_BKPT; + sqlite3OsClose(pPager->jfd); + } + } + } + + /* Playback and delete the journal. Drop the database write + ** lock and reacquire the read lock. Purge the cache before + ** playing back the hot-journal so that we don't end up with + ** an inconsistent cache. Sync the hot journal before playing + ** it back since the process that crashed and left the hot journal + ** probably did not sync it and we are required to always sync + ** the journal before playing it back. + */ + if( isOpen(pPager->jfd) ){ + assert( rc==SQLITE_OK ); + rc = pagerSyncHotJournal(pPager); + if( rc==SQLITE_OK ){ + rc = pager_playback(pPager, 1); + pPager->eState = PAGER_OPEN; + } + }else if( !pPager->exclusiveMode ){ + pagerUnlockDb(pPager, SHARED_LOCK); + } + + if( rc!=SQLITE_OK ){ + /* This branch is taken if an error occurs while trying to open + ** or roll back a hot-journal while holding an EXCLUSIVE lock. The + ** pager_unlock() routine will be called before returning to unlock + ** the file. If the unlock attempt fails, then Pager.eLock must be + ** set to UNKNOWN_LOCK (see the comment above the #define for + ** UNKNOWN_LOCK above for an explanation). + ** + ** In order to get pager_unlock() to do this, set Pager.eState to + ** PAGER_ERROR now. This is not actually counted as a transition + ** to ERROR state in the state diagram at the top of this file, + ** since we know that the same call to pager_unlock() will very + ** shortly transition the pager object to the OPEN state. Calling + ** assert_pager_state() would fail now, as it should not be possible + ** to be in ERROR state when there are zero outstanding page + ** references. + */ + pager_error(pPager, rc); + goto failed; + } + + assert( pPager->eState==PAGER_OPEN ); + assert( (pPager->eLock==SHARED_LOCK) + || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK) + ); + } + + if( !pPager->tempFile && ( + pPager->pBackup + || sqlite3PcachePagecount(pPager->pPCache)>0 + || USEFETCH(pPager) + )){ + /* The shared-lock has just been acquired on the database file + ** and there are already pages in the cache (from a previous + ** read or write transaction). Check to see if the database + ** has been modified. If the database has changed, flush the + ** cache. + ** + ** Database changes is detected by looking at 15 bytes beginning + ** at offset 24 into the file. The first 4 of these 16 bytes are + ** a 32-bit counter that is incremented with each change. The + ** other bytes change randomly with each file change when + ** a codec is in use. + ** + ** There is a vanishingly small chance that a change will not be + ** detected. The chance of an undetected change is so small that + ** it can be neglected. + */ + Pgno nPage = 0; + char dbFileVers[sizeof(pPager->dbFileVers)]; + + rc = pagerPagecount(pPager, &nPage); + if( rc ) goto failed; + + if( nPage>0 ){ + IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers))); + rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24); + if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ + goto failed; + } + }else{ + memset(dbFileVers, 0, sizeof(dbFileVers)); + } + + if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){ + pager_reset(pPager); + + /* Unmap the database file. It is possible that external processes + ** may have truncated the database file and then extended it back + ** to its original size while this process was not holding a lock. + ** In this case there may exist a Pager.pMap mapping that appears + ** to be the right size but is not actually valid. Avoid this + ** possibility by unmapping the db here. */ + if( USEFETCH(pPager) ){ + sqlite3OsUnfetch(pPager->fd, 0, 0); + } + } + } + + /* If there is a WAL file in the file-system, open this database in WAL + ** mode. Otherwise, the following function call is a no-op. + */ + rc = pagerOpenWalIfPresent(pPager); +#ifndef SQLITE_OMIT_WAL + assert( pPager->pWal==0 || rc==SQLITE_OK ); +#endif + } + + if( pagerUseWal(pPager) ){ + assert( rc==SQLITE_OK ); + rc = pagerBeginReadTransaction(pPager); + } + + if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){ + rc = pagerPagecount(pPager, &pPager->dbSize); + } + + failed: + if( rc!=SQLITE_OK ){ + assert( !MEMDB ); + pager_unlock(pPager); + assert( pPager->eState==PAGER_OPEN ); + }else{ + pPager->eState = PAGER_READER; + } + return rc; +} + +/* +** If the reference count has reached zero, rollback any active +** transaction and unlock the pager. +** +** Except, in locking_mode=EXCLUSIVE when there is nothing to in +** the rollback journal, the unlock is not performed and there is +** nothing to rollback, so this routine is a no-op. +*/ +static void pagerUnlockIfUnused(Pager *pPager){ + if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){ + pagerUnlockAndRollback(pPager); + } +} + +/* +** Acquire a reference to page number pgno in pager pPager (a page +** reference has type DbPage*). If the requested reference is +** successfully obtained, it is copied to *ppPage and SQLITE_OK returned. +** +** If the requested page is already in the cache, it is returned. +** Otherwise, a new page object is allocated and populated with data +** read from the database file. In some cases, the pcache module may +** choose not to allocate a new page object and may reuse an existing +** object with no outstanding references. +** +** The extra data appended to a page is always initialized to zeros the +** first time a page is loaded into memory. If the page requested is +** already in the cache when this function is called, then the extra +** data is left as it was when the page object was last used. +** +** If the database image is smaller than the requested page or if a +** non-zero value is passed as the noContent parameter and the +** requested page is not already stored in the cache, then no +** actual disk read occurs. In this case the memory image of the +** page is initialized to all zeros. +** +** If noContent is true, it means that we do not care about the contents +** of the page. This occurs in two scenarios: +** +** a) When reading a free-list leaf page from the database, and +** +** b) When a savepoint is being rolled back and we need to load +** a new page into the cache to be filled with the data read +** from the savepoint journal. +** +** If noContent is true, then the data returned is zeroed instead of +** being read from the database. Additionally, the bits corresponding +** to pgno in Pager.pInJournal (bitvec of pages already written to the +** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open +** savepoints are set. This means if the page is made writable at any +** point in the future, using a call to sqlite3PagerWrite(), its contents +** will not be journaled. This saves IO. +** +** The acquisition might fail for several reasons. In all cases, +** an appropriate error code is returned and *ppPage is set to NULL. +** +** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt +** to find a page in the in-memory cache first. If the page is not already +** in memory, this routine goes to disk to read it in whereas Lookup() +** just returns 0. This routine acquires a read-lock the first time it +** has to go to disk, and could also playback an old journal if necessary. +** Since Lookup() never goes to disk, it never has to deal with locks +** or journal files. +*/ +SQLITE_PRIVATE int sqlite3PagerAcquire( + Pager *pPager, /* The pager open on the database file */ + Pgno pgno, /* Page number to fetch */ + DbPage **ppPage, /* Write a pointer to the page here */ + int flags /* PAGER_GET_XXX flags */ +){ + int rc = SQLITE_OK; + PgHdr *pPg = 0; + u32 iFrame = 0; /* Frame to read from WAL file */ + const int noContent = (flags & PAGER_GET_NOCONTENT); + + /* It is acceptable to use a read-only (mmap) page for any page except + ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY + ** flag was specified by the caller. And so long as the db is not a + ** temporary or in-memory database. */ + const int bMmapOk = (pgno!=1 && USEFETCH(pPager) + && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY)) +#ifdef SQLITE_HAS_CODEC + && pPager->xCodec==0 +#endif + ); + + assert( pPager->eState>=PAGER_READER ); + assert( assert_pager_state(pPager) ); + assert( noContent==0 || bMmapOk==0 ); + + if( pgno==0 ){ + return SQLITE_CORRUPT_BKPT; + } + + /* If the pager is in the error state, return an error immediately. + ** Otherwise, request the page from the PCache layer. */ + if( pPager->errCode!=SQLITE_OK ){ + rc = pPager->errCode; + }else{ + + if( bMmapOk && pagerUseWal(pPager) ){ + rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); + if( rc!=SQLITE_OK ) goto pager_acquire_err; + } + + if( iFrame==0 && bMmapOk ){ + void *pData = 0; + + rc = sqlite3OsFetch(pPager->fd, + (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData + ); + + if( rc==SQLITE_OK && pData ){ + if( pPager->eState>PAGER_READER ){ + (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg); + } + if( pPg==0 ){ + rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg); + }else{ + sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData); + } + if( pPg ){ + assert( rc==SQLITE_OK ); + *ppPage = pPg; + return SQLITE_OK; + } + } + if( rc!=SQLITE_OK ){ + goto pager_acquire_err; + } + } + + rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage); + } + + if( rc!=SQLITE_OK ){ + /* Either the call to sqlite3PcacheFetch() returned an error or the + ** pager was already in the error-state when this function was called. + ** Set pPg to 0 and jump to the exception handler. */ + pPg = 0; + goto pager_acquire_err; + } + assert( (*ppPage)->pgno==pgno ); + assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 ); + + if( (*ppPage)->pPager && !noContent ){ + /* In this case the pcache already contains an initialized copy of + ** the page. Return without further ado. */ + assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) ); + pPager->aStat[PAGER_STAT_HIT]++; + return SQLITE_OK; + + }else{ + /* The pager cache has created a new page. Its content needs to + ** be initialized. */ + + pPg = *ppPage; + pPg->pPager = pPager; + + /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page + ** number greater than this, or the unused locking-page, is requested. */ + if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){ + rc = SQLITE_CORRUPT_BKPT; + goto pager_acquire_err; + } + + if( MEMDB || pPager->dbSizefd) ){ + if( pgno>pPager->mxPgno ){ + rc = SQLITE_FULL; + goto pager_acquire_err; + } + if( noContent ){ + /* Failure to set the bits in the InJournal bit-vectors is benign. + ** It merely means that we might do some extra work to journal a + ** page that does not need to be journaled. Nevertheless, be sure + ** to test the case where a malloc error occurs while trying to set + ** a bit in a bit vector. + */ + sqlite3BeginBenignMalloc(); + if( pgno<=pPager->dbOrigSize ){ + TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno); + testcase( rc==SQLITE_NOMEM ); + } + TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno); + testcase( rc==SQLITE_NOMEM ); + sqlite3EndBenignMalloc(); + } + memset(pPg->pData, 0, pPager->pageSize); + IOTRACE(("ZERO %p %d\n", pPager, pgno)); + }else{ + if( pagerUseWal(pPager) && bMmapOk==0 ){ + rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); + if( rc!=SQLITE_OK ) goto pager_acquire_err; + } + assert( pPg->pPager==pPager ); + pPager->aStat[PAGER_STAT_MISS]++; + rc = readDbPage(pPg, iFrame); + if( rc!=SQLITE_OK ){ + goto pager_acquire_err; + } + } + pager_set_pagehash(pPg); + } + + return SQLITE_OK; + +pager_acquire_err: + assert( rc!=SQLITE_OK ); + if( pPg ){ + sqlite3PcacheDrop(pPg); + } + pagerUnlockIfUnused(pPager); + + *ppPage = 0; + return rc; +} + +/* +** Acquire a page if it is already in the in-memory cache. Do +** not read the page from disk. Return a pointer to the page, +** or 0 if the page is not in cache. +** +** See also sqlite3PagerGet(). The difference between this routine +** and sqlite3PagerGet() is that _get() will go to the disk and read +** in the page if the page is not already in cache. This routine +** returns NULL if the page is not in cache or if a disk I/O error +** has ever happened. +*/ +SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){ + PgHdr *pPg = 0; + assert( pPager!=0 ); + assert( pgno!=0 ); + assert( pPager->pPCache!=0 ); + assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR ); + sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg); + return pPg; +} + +/* +** Release a page reference. +** +** If the number of references to the page drop to zero, then the +** page is added to the LRU list. When all references to all pages +** are released, a rollback occurs and the lock on the database is +** removed. +*/ +SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){ + if( pPg ){ + Pager *pPager = pPg->pPager; + if( pPg->flags & PGHDR_MMAP ){ + pagerReleaseMapPage(pPg); + }else{ + sqlite3PcacheRelease(pPg); + } + pagerUnlockIfUnused(pPager); + } +} + +/* +** This function is called at the start of every write transaction. +** There must already be a RESERVED or EXCLUSIVE lock on the database +** file when this routine is called. +** +** Open the journal file for pager pPager and write a journal header +** to the start of it. If there are active savepoints, open the sub-journal +** as well. This function is only used when the journal file is being +** opened to write a rollback log for a transaction. It is not used +** when opening a hot journal file to roll it back. +** +** If the journal file is already open (as it may be in exclusive mode), +** then this function just writes a journal header to the start of the +** already open file. +** +** Whether or not the journal file is opened by this function, the +** Pager.pInJournal bitvec structure is allocated. +** +** Return SQLITE_OK if everything is successful. Otherwise, return +** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or +** an IO error code if opening or writing the journal file fails. +*/ +static int pager_open_journal(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */ + + assert( pPager->eState==PAGER_WRITER_LOCKED ); + assert( assert_pager_state(pPager) ); + assert( pPager->pInJournal==0 ); + + /* If already in the error state, this function is a no-op. But on + ** the other hand, this routine is never called if we are already in + ** an error state. */ + if( NEVER(pPager->errCode) ) return pPager->errCode; + + if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ + pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize); + if( pPager->pInJournal==0 ){ + return SQLITE_NOMEM; + } + + /* Open the journal file if it is not already open. */ + if( !isOpen(pPager->jfd) ){ + if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){ + sqlite3MemJournalOpen(pPager->jfd); + }else{ + const int flags = /* VFS flags to open journal file */ + SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE| + (pPager->tempFile ? + (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL): + (SQLITE_OPEN_MAIN_JOURNAL) + ); + #ifdef SQLITE_ENABLE_ATOMIC_WRITE + rc = sqlite3JournalOpen( + pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager) + ); + #else + rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0); + #endif + } + assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); + } + + + /* Write the first journal header to the journal file and open + ** the sub-journal if necessary. + */ + if( rc==SQLITE_OK ){ + /* TODO: Check if all of these are really required. */ + pPager->nRec = 0; + pPager->journalOff = 0; + pPager->setMaster = 0; + pPager->journalHdr = 0; + rc = writeJournalHdr(pPager); + } + } + + if( rc!=SQLITE_OK ){ + sqlite3BitvecDestroy(pPager->pInJournal); + pPager->pInJournal = 0; + }else{ + assert( pPager->eState==PAGER_WRITER_LOCKED ); + pPager->eState = PAGER_WRITER_CACHEMOD; + } + + return rc; +} + +/* +** Begin a write-transaction on the specified pager object. If a +** write-transaction has already been opened, this function is a no-op. +** +** If the exFlag argument is false, then acquire at least a RESERVED +** lock on the database file. If exFlag is true, then acquire at least +** an EXCLUSIVE lock. If such a lock is already held, no locking +** functions need be called. +** +** If the subjInMemory argument is non-zero, then any sub-journal opened +** within this transaction will be opened as an in-memory file. This +** has no effect if the sub-journal is already opened (as it may be when +** running in exclusive mode) or if the transaction does not require a +** sub-journal. If the subjInMemory argument is zero, then any required +** sub-journal is implemented in-memory if pPager is an in-memory database, +** or using a temporary file otherwise. +*/ +SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){ + int rc = SQLITE_OK; + + if( pPager->errCode ) return pPager->errCode; + assert( pPager->eState>=PAGER_READER && pPager->eStatesubjInMemory = (u8)subjInMemory; + + if( ALWAYS(pPager->eState==PAGER_READER) ){ + assert( pPager->pInJournal==0 ); + + if( pagerUseWal(pPager) ){ + /* If the pager is configured to use locking_mode=exclusive, and an + ** exclusive lock on the database is not already held, obtain it now. + */ + if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){ + rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); + if( rc!=SQLITE_OK ){ + return rc; + } + sqlite3WalExclusiveMode(pPager->pWal, 1); + } + + /* Grab the write lock on the log file. If successful, upgrade to + ** PAGER_RESERVED state. Otherwise, return an error code to the caller. + ** The busy-handler is not invoked if another connection already + ** holds the write-lock. If possible, the upper layer will call it. + */ + rc = sqlite3WalBeginWriteTransaction(pPager->pWal); + }else{ + /* Obtain a RESERVED lock on the database file. If the exFlag parameter + ** is true, then immediately upgrade this to an EXCLUSIVE lock. The + ** busy-handler callback can be used when upgrading to the EXCLUSIVE + ** lock, but not when obtaining the RESERVED lock. + */ + rc = pagerLockDb(pPager, RESERVED_LOCK); + if( rc==SQLITE_OK && exFlag ){ + rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); + } + } + + if( rc==SQLITE_OK ){ + /* Change to WRITER_LOCKED state. + ** + ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD + ** when it has an open transaction, but never to DBMOD or FINISHED. + ** This is because in those states the code to roll back savepoint + ** transactions may copy data from the sub-journal into the database + ** file as well as into the page cache. Which would be incorrect in + ** WAL mode. + */ + pPager->eState = PAGER_WRITER_LOCKED; + pPager->dbHintSize = pPager->dbSize; + pPager->dbFileSize = pPager->dbSize; + pPager->dbOrigSize = pPager->dbSize; + pPager->journalOff = 0; + } + + assert( rc==SQLITE_OK || pPager->eState==PAGER_READER ); + assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED ); + assert( assert_pager_state(pPager) ); + } + + PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager))); + return rc; +} + +/* +** Mark a single data page as writeable. The page is written into the +** main journal or sub-journal as required. If the page is written into +** one of the journals, the corresponding bit is set in the +** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs +** of any open savepoints as appropriate. +*/ +static int pager_write(PgHdr *pPg){ + void *pData = pPg->pData; + Pager *pPager = pPg->pPager; + int rc = SQLITE_OK; + + /* This routine is not called unless a write-transaction has already + ** been started. The journal file may or may not be open at this point. + ** It is never called in the ERROR state. + */ + assert( pPager->eState==PAGER_WRITER_LOCKED + || pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + ); + assert( assert_pager_state(pPager) ); + + /* If an error has been previously detected, report the same error + ** again. This should not happen, but the check provides robustness. */ + if( NEVER(pPager->errCode) ) return pPager->errCode; + + /* Higher-level routines never call this function if database is not + ** writable. But check anyway, just for robustness. */ + if( NEVER(pPager->readOnly) ) return SQLITE_PERM; + + CHECK_PAGE(pPg); + + /* The journal file needs to be opened. Higher level routines have already + ** obtained the necessary locks to begin the write-transaction, but the + ** rollback journal might not yet be open. Open it now if this is the case. + ** + ** This is done before calling sqlite3PcacheMakeDirty() on the page. + ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then + ** an error might occur and the pager would end up in WRITER_LOCKED state + ** with pages marked as dirty in the cache. + */ + if( pPager->eState==PAGER_WRITER_LOCKED ){ + rc = pager_open_journal(pPager); + if( rc!=SQLITE_OK ) return rc; + } + assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); + assert( assert_pager_state(pPager) ); + + /* Mark the page as dirty. If the page has already been written + ** to the journal then we can return right away. + */ + sqlite3PcacheMakeDirty(pPg); + if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){ + assert( !pagerUseWal(pPager) ); + }else{ + + /* The transaction journal now exists and we have a RESERVED or an + ** EXCLUSIVE lock on the main database file. Write the current page to + ** the transaction journal if it is not there already. + */ + if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){ + assert( pagerUseWal(pPager)==0 ); + if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){ + u32 cksum; + char *pData2; + i64 iOff = pPager->journalOff; + + /* We should never write to the journal file the page that + ** contains the database locks. The following assert verifies + ** that we do not. */ + assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) ); + + assert( pPager->journalHdr<=pPager->journalOff ); + CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2); + cksum = pager_cksum(pPager, (u8*)pData2); + + /* Even if an IO or diskfull error occurs while journalling the + ** page in the block above, set the need-sync flag for the page. + ** Otherwise, when the transaction is rolled back, the logic in + ** playback_one_page() will think that the page needs to be restored + ** in the database file. And if an IO error occurs while doing so, + ** then corruption may follow. + */ + pPg->flags |= PGHDR_NEED_SYNC; + + rc = write32bits(pPager->jfd, iOff, pPg->pgno); + if( rc!=SQLITE_OK ) return rc; + rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4); + if( rc!=SQLITE_OK ) return rc; + rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum); + if( rc!=SQLITE_OK ) return rc; + + IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, + pPager->journalOff, pPager->pageSize)); + PAGER_INCR(sqlite3_pager_writej_count); + PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n", + PAGERID(pPager), pPg->pgno, + ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg))); + + pPager->journalOff += 8 + pPager->pageSize; + pPager->nRec++; + assert( pPager->pInJournal!=0 ); + rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno); + testcase( rc==SQLITE_NOMEM ); + assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); + rc |= addToSavepointBitvecs(pPager, pPg->pgno); + if( rc!=SQLITE_OK ){ + assert( rc==SQLITE_NOMEM ); + return rc; + } + }else{ + if( pPager->eState!=PAGER_WRITER_DBMOD ){ + pPg->flags |= PGHDR_NEED_SYNC; + } + PAGERTRACE(("APPEND %d page %d needSync=%d\n", + PAGERID(pPager), pPg->pgno, + ((pPg->flags&PGHDR_NEED_SYNC)?1:0))); + } + } + + /* If the statement journal is open and the page is not in it, + ** then write the current page to the statement journal. Note that + ** the statement journal format differs from the standard journal format + ** in that it omits the checksums and the header. + */ + if( subjRequiresPage(pPg) ){ + rc = subjournalPage(pPg); + } + } + + /* Update the database size and return. + */ + if( pPager->dbSizepgno ){ + pPager->dbSize = pPg->pgno; + } + return rc; +} + +/* +** Mark a data page as writeable. This routine must be called before +** making changes to a page. The caller must check the return value +** of this function and be careful not to change any page data unless +** this routine returns SQLITE_OK. +** +** The difference between this function and pager_write() is that this +** function also deals with the special case where 2 or more pages +** fit on a single disk sector. In this case all co-resident pages +** must have been written to the journal file before returning. +** +** If an error occurs, SQLITE_NOMEM or an IO error code is returned +** as appropriate. Otherwise, SQLITE_OK. +*/ +SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){ + int rc = SQLITE_OK; + + PgHdr *pPg = pDbPage; + Pager *pPager = pPg->pPager; + Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize); + + assert( (pPg->flags & PGHDR_MMAP)==0 ); + assert( pPager->eState>=PAGER_WRITER_LOCKED ); + assert( pPager->eState!=PAGER_ERROR ); + assert( assert_pager_state(pPager) ); + + if( nPagePerSector>1 ){ + Pgno nPageCount; /* Total number of pages in database file */ + Pgno pg1; /* First page of the sector pPg is located on. */ + int nPage = 0; /* Number of pages starting at pg1 to journal */ + int ii; /* Loop counter */ + int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */ + + /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow + ** a journal header to be written between the pages journaled by + ** this function. + */ + assert( !MEMDB ); + assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 ); + pPager->doNotSpill |= SPILLFLAG_NOSYNC; + + /* This trick assumes that both the page-size and sector-size are + ** an integer power of 2. It sets variable pg1 to the identifier + ** of the first page of the sector pPg is located on. + */ + pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1; + + nPageCount = pPager->dbSize; + if( pPg->pgno>nPageCount ){ + nPage = (pPg->pgno - pg1)+1; + }else if( (pg1+nPagePerSector-1)>nPageCount ){ + nPage = nPageCount+1-pg1; + }else{ + nPage = nPagePerSector; + } + assert(nPage>0); + assert(pg1<=pPg->pgno); + assert((pg1+nPage)>pPg->pgno); + + for(ii=0; iipgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){ + if( pg!=PAGER_MJ_PGNO(pPager) ){ + rc = sqlite3PagerGet(pPager, pg, &pPage); + if( rc==SQLITE_OK ){ + rc = pager_write(pPage); + if( pPage->flags&PGHDR_NEED_SYNC ){ + needSync = 1; + } + sqlite3PagerUnref(pPage); + } + } + }else if( (pPage = pager_lookup(pPager, pg))!=0 ){ + if( pPage->flags&PGHDR_NEED_SYNC ){ + needSync = 1; + } + sqlite3PagerUnref(pPage); + } + } + + /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages + ** starting at pg1, then it needs to be set for all of them. Because + ** writing to any of these nPage pages may damage the others, the + ** journal file must contain sync()ed copies of all of them + ** before any of them can be written out to the database file. + */ + if( rc==SQLITE_OK && needSync ){ + assert( !MEMDB ); + for(ii=0; iiflags |= PGHDR_NEED_SYNC; + sqlite3PagerUnref(pPage); + } + } + } + + assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 ); + pPager->doNotSpill &= ~SPILLFLAG_NOSYNC; + }else{ + rc = pager_write(pDbPage); + } + return rc; +} + +/* +** Return TRUE if the page given in the argument was previously passed +** to sqlite3PagerWrite(). In other words, return TRUE if it is ok +** to change the content of the page. +*/ +#ifndef NDEBUG +SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){ + return pPg->flags&PGHDR_DIRTY; +} +#endif + +/* +** A call to this routine tells the pager that it is not necessary to +** write the information on page pPg back to the disk, even though +** that page might be marked as dirty. This happens, for example, when +** the page has been added as a leaf of the freelist and so its +** content no longer matters. +** +** The overlying software layer calls this routine when all of the data +** on the given page is unused. The pager marks the page as clean so +** that it does not get written to disk. +** +** Tests show that this optimization can quadruple the speed of large +** DELETE operations. +*/ +SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){ + Pager *pPager = pPg->pPager; + if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){ + PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager))); + IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno)) + pPg->flags |= PGHDR_DONT_WRITE; + pager_set_pagehash(pPg); + } +} + +/* +** This routine is called to increment the value of the database file +** change-counter, stored as a 4-byte big-endian integer starting at +** byte offset 24 of the pager file. The secondary change counter at +** 92 is also updated, as is the SQLite version number at offset 96. +** +** But this only happens if the pPager->changeCountDone flag is false. +** To avoid excess churning of page 1, the update only happens once. +** See also the pager_write_changecounter() routine that does an +** unconditional update of the change counters. +** +** If the isDirectMode flag is zero, then this is done by calling +** sqlite3PagerWrite() on page 1, then modifying the contents of the +** page data. In this case the file will be updated when the current +** transaction is committed. +** +** The isDirectMode flag may only be non-zero if the library was compiled +** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case, +** if isDirect is non-zero, then the database file is updated directly +** by writing an updated version of page 1 using a call to the +** sqlite3OsWrite() function. +*/ +static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ + int rc = SQLITE_OK; + + assert( pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + ); + assert( assert_pager_state(pPager) ); + + /* Declare and initialize constant integer 'isDirect'. If the + ** atomic-write optimization is enabled in this build, then isDirect + ** is initialized to the value passed as the isDirectMode parameter + ** to this function. Otherwise, it is always set to zero. + ** + ** The idea is that if the atomic-write optimization is not + ** enabled at compile time, the compiler can omit the tests of + ** 'isDirect' below, as well as the block enclosed in the + ** "if( isDirect )" condition. + */ +#ifndef SQLITE_ENABLE_ATOMIC_WRITE +# define DIRECT_MODE 0 + assert( isDirectMode==0 ); + UNUSED_PARAMETER(isDirectMode); +#else +# define DIRECT_MODE isDirectMode +#endif + + if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){ + PgHdr *pPgHdr; /* Reference to page 1 */ + + assert( !pPager->tempFile && isOpen(pPager->fd) ); + + /* Open page 1 of the file for writing. */ + rc = sqlite3PagerGet(pPager, 1, &pPgHdr); + assert( pPgHdr==0 || rc==SQLITE_OK ); + + /* If page one was fetched successfully, and this function is not + ** operating in direct-mode, make page 1 writable. When not in + ** direct mode, page 1 is always held in cache and hence the PagerGet() + ** above is always successful - hence the ALWAYS on rc==SQLITE_OK. + */ + if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){ + rc = sqlite3PagerWrite(pPgHdr); + } + + if( rc==SQLITE_OK ){ + /* Actually do the update of the change counter */ + pager_write_changecounter(pPgHdr); + + /* If running in direct mode, write the contents of page 1 to the file. */ + if( DIRECT_MODE ){ + const void *zBuf; + assert( pPager->dbFileSize>0 ); + CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf); + if( rc==SQLITE_OK ){ + rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0); + pPager->aStat[PAGER_STAT_WRITE]++; + } + if( rc==SQLITE_OK ){ + /* Update the pager's copy of the change-counter. Otherwise, the + ** next time a read transaction is opened the cache will be + ** flushed (as the change-counter values will not match). */ + const void *pCopy = (const void *)&((const char *)zBuf)[24]; + memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers)); + pPager->changeCountDone = 1; + } + }else{ + pPager->changeCountDone = 1; + } + } + + /* Release the page reference. */ + sqlite3PagerUnref(pPgHdr); + } + return rc; +} + +/* +** Sync the database file to disk. This is a no-op for in-memory databases +** or pages with the Pager.noSync flag set. +** +** If successful, or if called on a pager for which it is a no-op, this +** function returns SQLITE_OK. Otherwise, an IO error code is returned. +*/ +SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){ + int rc = SQLITE_OK; + if( !pPager->noSync ){ + assert( !MEMDB ); + rc = sqlite3OsSync(pPager->fd, pPager->syncFlags); + }else if( isOpen(pPager->fd) ){ + assert( !MEMDB ); + rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0); + if( rc==SQLITE_NOTFOUND ){ + rc = SQLITE_OK; + } + } + return rc; +} + +/* +** This function may only be called while a write-transaction is active in +** rollback. If the connection is in WAL mode, this call is a no-op. +** Otherwise, if the connection does not already have an EXCLUSIVE lock on +** the database file, an attempt is made to obtain one. +** +** If the EXCLUSIVE lock is already held or the attempt to obtain it is +** successful, or the connection is in WAL mode, SQLITE_OK is returned. +** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is +** returned. +*/ +SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){ + int rc = SQLITE_OK; + assert( pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + || pPager->eState==PAGER_WRITER_LOCKED + ); + assert( assert_pager_state(pPager) ); + if( 0==pagerUseWal(pPager) ){ + rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); + } + return rc; +} + +/* +** Sync the database file for the pager pPager. zMaster points to the name +** of a master journal file that should be written into the individual +** journal file. zMaster may be NULL, which is interpreted as no master +** journal (a single database transaction). +** +** This routine ensures that: +** +** * The database file change-counter is updated, +** * the journal is synced (unless the atomic-write optimization is used), +** * all dirty pages are written to the database file, +** * the database file is truncated (if required), and +** * the database file synced. +** +** The only thing that remains to commit the transaction is to finalize +** (delete, truncate or zero the first part of) the journal file (or +** delete the master journal file if specified). +** +** Note that if zMaster==NULL, this does not overwrite a previous value +** passed to an sqlite3PagerCommitPhaseOne() call. +** +** If the final parameter - noSync - is true, then the database file itself +** is not synced. The caller must call sqlite3PagerSync() directly to +** sync the database file before calling CommitPhaseTwo() to delete the +** journal file in this case. +*/ +SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( + Pager *pPager, /* Pager object */ + const char *zMaster, /* If not NULL, the master journal name */ + int noSync /* True to omit the xSync on the db file */ +){ + int rc = SQLITE_OK; /* Return code */ + + assert( pPager->eState==PAGER_WRITER_LOCKED + || pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + || pPager->eState==PAGER_ERROR + ); + assert( assert_pager_state(pPager) ); + + /* If a prior error occurred, report that error again. */ + if( NEVER(pPager->errCode) ) return pPager->errCode; + + PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", + pPager->zFilename, zMaster, pPager->dbSize)); + + /* If no database changes have been made, return early. */ + if( pPager->eStatepBackup); + }else{ + if( pagerUseWal(pPager) ){ + PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); + PgHdr *pPageOne = 0; + if( pList==0 ){ + /* Must have at least one page for the WAL commit flag. + ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */ + rc = sqlite3PagerGet(pPager, 1, &pPageOne); + pList = pPageOne; + pList->pDirty = 0; + } + assert( rc==SQLITE_OK ); + if( ALWAYS(pList) ){ + rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1); + } + sqlite3PagerUnref(pPageOne); + if( rc==SQLITE_OK ){ + sqlite3PcacheCleanAll(pPager->pPCache); + } + }else{ + /* The following block updates the change-counter. Exactly how it + ** does this depends on whether or not the atomic-update optimization + ** was enabled at compile time, and if this transaction meets the + ** runtime criteria to use the operation: + ** + ** * The file-system supports the atomic-write property for + ** blocks of size page-size, and + ** * This commit is not part of a multi-file transaction, and + ** * Exactly one page has been modified and store in the journal file. + ** + ** If the optimization was not enabled at compile time, then the + ** pager_incr_changecounter() function is called to update the change + ** counter in 'indirect-mode'. If the optimization is compiled in but + ** is not applicable to this transaction, call sqlite3JournalCreate() + ** to make sure the journal file has actually been created, then call + ** pager_incr_changecounter() to update the change-counter in indirect + ** mode. + ** + ** Otherwise, if the optimization is both enabled and applicable, + ** then call pager_incr_changecounter() to update the change-counter + ** in 'direct' mode. In this case the journal file will never be + ** created for this transaction. + */ + #ifdef SQLITE_ENABLE_ATOMIC_WRITE + PgHdr *pPg; + assert( isOpen(pPager->jfd) + || pPager->journalMode==PAGER_JOURNALMODE_OFF + || pPager->journalMode==PAGER_JOURNALMODE_WAL + ); + if( !zMaster && isOpen(pPager->jfd) + && pPager->journalOff==jrnlBufferSize(pPager) + && pPager->dbSize>=pPager->dbOrigSize + && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty) + ){ + /* Update the db file change counter via the direct-write method. The + ** following call will modify the in-memory representation of page 1 + ** to include the updated change counter and then write page 1 + ** directly to the database file. Because of the atomic-write + ** property of the host file-system, this is safe. + */ + rc = pager_incr_changecounter(pPager, 1); + }else{ + rc = sqlite3JournalCreate(pPager->jfd); + if( rc==SQLITE_OK ){ + rc = pager_incr_changecounter(pPager, 0); + } + } + #else + rc = pager_incr_changecounter(pPager, 0); + #endif + if( rc!=SQLITE_OK ) goto commit_phase_one_exit; + + /* Write the master journal name into the journal file. If a master + ** journal file name has already been written to the journal file, + ** or if zMaster is NULL (no master journal), then this call is a no-op. + */ + rc = writeMasterJournal(pPager, zMaster); + if( rc!=SQLITE_OK ) goto commit_phase_one_exit; + + /* Sync the journal file and write all dirty pages to the database. + ** If the atomic-update optimization is being used, this sync will not + ** create the journal file or perform any real IO. + ** + ** Because the change-counter page was just modified, unless the + ** atomic-update optimization is used it is almost certain that the + ** journal requires a sync here. However, in locking_mode=exclusive + ** on a system under memory pressure it is just possible that this is + ** not the case. In this case it is likely enough that the redundant + ** xSync() call will be changed to a no-op by the OS anyhow. + */ + rc = syncJournal(pPager, 0); + if( rc!=SQLITE_OK ) goto commit_phase_one_exit; + + rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache)); + if( rc!=SQLITE_OK ){ + assert( rc!=SQLITE_IOERR_BLOCKED ); + goto commit_phase_one_exit; + } + sqlite3PcacheCleanAll(pPager->pPCache); + + /* If the file on disk is smaller than the database image, use + ** pager_truncate to grow the file here. This can happen if the database + ** image was extended as part of the current transaction and then the + ** last page in the db image moved to the free-list. In this case the + ** last page is never written out to disk, leaving the database file + ** undersized. Fix this now if it is the case. */ + if( pPager->dbSize>pPager->dbFileSize ){ + Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager)); + assert( pPager->eState==PAGER_WRITER_DBMOD ); + rc = pager_truncate(pPager, nNew); + if( rc!=SQLITE_OK ) goto commit_phase_one_exit; + } + + /* Finally, sync the database file. */ + if( !noSync ){ + rc = sqlite3PagerSync(pPager); + } + IOTRACE(("DBSYNC %p\n", pPager)) + } + } + +commit_phase_one_exit: + if( rc==SQLITE_OK && !pagerUseWal(pPager) ){ + pPager->eState = PAGER_WRITER_FINISHED; + } + return rc; +} + + +/* +** When this function is called, the database file has been completely +** updated to reflect the changes made by the current transaction and +** synced to disk. The journal file still exists in the file-system +** though, and if a failure occurs at this point it will eventually +** be used as a hot-journal and the current transaction rolled back. +** +** This function finalizes the journal file, either by deleting, +** truncating or partially zeroing it, so that it cannot be used +** for hot-journal rollback. Once this is done the transaction is +** irrevocably committed. +** +** If an error occurs, an IO error code is returned and the pager +** moves into the error state. Otherwise, SQLITE_OK is returned. +*/ +SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + + /* This routine should not be called if a prior error has occurred. + ** But if (due to a coding error elsewhere in the system) it does get + ** called, just return the same error code without doing anything. */ + if( NEVER(pPager->errCode) ) return pPager->errCode; + + assert( pPager->eState==PAGER_WRITER_LOCKED + || pPager->eState==PAGER_WRITER_FINISHED + || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD) + ); + assert( assert_pager_state(pPager) ); + + /* An optimization. If the database was not actually modified during + ** this transaction, the pager is running in exclusive-mode and is + ** using persistent journals, then this function is a no-op. + ** + ** The start of the journal file currently contains a single journal + ** header with the nRec field set to 0. If such a journal is used as + ** a hot-journal during hot-journal rollback, 0 changes will be made + ** to the database file. So there is no need to zero the journal + ** header. Since the pager is in exclusive mode, there is no need + ** to drop any locks either. + */ + if( pPager->eState==PAGER_WRITER_LOCKED + && pPager->exclusiveMode + && pPager->journalMode==PAGER_JOURNALMODE_PERSIST + ){ + assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff ); + pPager->eState = PAGER_READER; + return SQLITE_OK; + } + + PAGERTRACE(("COMMIT %d\n", PAGERID(pPager))); + rc = pager_end_transaction(pPager, pPager->setMaster, 1); + return pager_error(pPager, rc); +} + +/* +** If a write transaction is open, then all changes made within the +** transaction are reverted and the current write-transaction is closed. +** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR +** state if an error occurs. +** +** If the pager is already in PAGER_ERROR state when this function is called, +** it returns Pager.errCode immediately. No work is performed in this case. +** +** Otherwise, in rollback mode, this function performs two functions: +** +** 1) It rolls back the journal file, restoring all database file and +** in-memory cache pages to the state they were in when the transaction +** was opened, and +** +** 2) It finalizes the journal file, so that it is not used for hot +** rollback at any point in the future. +** +** Finalization of the journal file (task 2) is only performed if the +** rollback is successful. +** +** In WAL mode, all cache-entries containing data modified within the +** current transaction are either expelled from the cache or reverted to +** their pre-transaction state by re-reading data from the database or +** WAL files. The WAL transaction is then closed. +*/ +SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager))); + + /* PagerRollback() is a no-op if called in READER or OPEN state. If + ** the pager is already in the ERROR state, the rollback is not + ** attempted here. Instead, the error code is returned to the caller. + */ + assert( assert_pager_state(pPager) ); + if( pPager->eState==PAGER_ERROR ) return pPager->errCode; + if( pPager->eState<=PAGER_READER ) return SQLITE_OK; + + if( pagerUseWal(pPager) ){ + int rc2; + rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1); + rc2 = pager_end_transaction(pPager, pPager->setMaster, 0); + if( rc==SQLITE_OK ) rc = rc2; + }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){ + int eState = pPager->eState; + rc = pager_end_transaction(pPager, 0, 0); + if( !MEMDB && eState>PAGER_WRITER_LOCKED ){ + /* This can happen using journal_mode=off. Move the pager to the error + ** state to indicate that the contents of the cache may not be trusted. + ** Any active readers will get SQLITE_ABORT. + */ + pPager->errCode = SQLITE_ABORT; + pPager->eState = PAGER_ERROR; + return rc; + } + }else{ + rc = pager_playback(pPager, 0); + } + + assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK ); + assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT + || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR ); + + /* If an error occurs during a ROLLBACK, we can no longer trust the pager + ** cache. So call pager_error() on the way out to make any error persistent. + */ + return pager_error(pPager, rc); +} + +/* +** Return TRUE if the database file is opened read-only. Return FALSE +** if the database is (in theory) writable. +*/ +SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){ + return pPager->readOnly; +} + +/* +** Return the number of references to the pager. +*/ +SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){ + return sqlite3PcacheRefCount(pPager->pPCache); +} + +/* +** Return the approximate number of bytes of memory currently +** used by the pager and its associated cache. +*/ +SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){ + int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr) + + 5*sizeof(void*); + return perPageSize*sqlite3PcachePagecount(pPager->pPCache) + + sqlite3MallocSize(pPager) + + pPager->pageSize; +} + +/* +** Return the number of references to the specified page. +*/ +SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){ + return sqlite3PcachePageRefcount(pPage); +} + +#ifdef SQLITE_TEST +/* +** This routine is used for testing and analysis only. +*/ +SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){ + static int a[11]; + a[0] = sqlite3PcacheRefCount(pPager->pPCache); + a[1] = sqlite3PcachePagecount(pPager->pPCache); + a[2] = sqlite3PcacheGetCachesize(pPager->pPCache); + a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize; + a[4] = pPager->eState; + a[5] = pPager->errCode; + a[6] = pPager->aStat[PAGER_STAT_HIT]; + a[7] = pPager->aStat[PAGER_STAT_MISS]; + a[8] = 0; /* Used to be pPager->nOvfl */ + a[9] = pPager->nRead; + a[10] = pPager->aStat[PAGER_STAT_WRITE]; + return a; +} +#endif + +/* +** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or +** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the +** current cache hit or miss count, according to the value of eStat. If the +** reset parameter is non-zero, the cache hit or miss count is zeroed before +** returning. +*/ +SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){ + + assert( eStat==SQLITE_DBSTATUS_CACHE_HIT + || eStat==SQLITE_DBSTATUS_CACHE_MISS + || eStat==SQLITE_DBSTATUS_CACHE_WRITE + ); + + assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS ); + assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE ); + assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 ); + + *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT]; + if( reset ){ + pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0; + } +} + +/* +** Return true if this is an in-memory pager. +*/ +SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){ + return MEMDB; +} + +/* +** Check that there are at least nSavepoint savepoints open. If there are +** currently less than nSavepoints open, then open one or more savepoints +** to make up the difference. If the number of savepoints is already +** equal to nSavepoint, then this function is a no-op. +** +** If a memory allocation fails, SQLITE_NOMEM is returned. If an error +** occurs while opening the sub-journal file, then an IO error code is +** returned. Otherwise, SQLITE_OK. +*/ +SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ + int rc = SQLITE_OK; /* Return code */ + int nCurrent = pPager->nSavepoint; /* Current number of savepoints */ + + assert( pPager->eState>=PAGER_WRITER_LOCKED ); + assert( assert_pager_state(pPager) ); + + if( nSavepoint>nCurrent && pPager->useJournal ){ + int ii; /* Iterator variable */ + PagerSavepoint *aNew; /* New Pager.aSavepoint array */ + + /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM + ** if the allocation fails. Otherwise, zero the new portion in case a + ** malloc failure occurs while populating it in the for(...) loop below. + */ + aNew = (PagerSavepoint *)sqlite3Realloc( + pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint + ); + if( !aNew ){ + return SQLITE_NOMEM; + } + memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint)); + pPager->aSavepoint = aNew; + + /* Populate the PagerSavepoint structures just allocated. */ + for(ii=nCurrent; iidbSize; + if( isOpen(pPager->jfd) && pPager->journalOff>0 ){ + aNew[ii].iOffset = pPager->journalOff; + }else{ + aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager); + } + aNew[ii].iSubRec = pPager->nSubRec; + aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize); + if( !aNew[ii].pInSavepoint ){ + return SQLITE_NOMEM; + } + if( pagerUseWal(pPager) ){ + sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData); + } + pPager->nSavepoint = ii+1; + } + assert( pPager->nSavepoint==nSavepoint ); + assertTruncateConstraint(pPager); + } + + return rc; +} + +/* +** This function is called to rollback or release (commit) a savepoint. +** The savepoint to release or rollback need not be the most recently +** created savepoint. +** +** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE. +** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with +** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes +** that have occurred since the specified savepoint was created. +** +** The savepoint to rollback or release is identified by parameter +** iSavepoint. A value of 0 means to operate on the outermost savepoint +** (the first created). A value of (Pager.nSavepoint-1) means operate +** on the most recently created savepoint. If iSavepoint is greater than +** (Pager.nSavepoint-1), then this function is a no-op. +** +** If a negative value is passed to this function, then the current +** transaction is rolled back. This is different to calling +** sqlite3PagerRollback() because this function does not terminate +** the transaction or unlock the database, it just restores the +** contents of the database to its original state. +** +** In any case, all savepoints with an index greater than iSavepoint +** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE), +** then savepoint iSavepoint is also destroyed. +** +** This function may return SQLITE_NOMEM if a memory allocation fails, +** or an IO error code if an IO error occurs while rolling back a +** savepoint. If no errors occur, SQLITE_OK is returned. +*/ +SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ + int rc = pPager->errCode; /* Return code */ + + assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); + assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK ); + + if( rc==SQLITE_OK && iSavepointnSavepoint ){ + int ii; /* Iterator variable */ + int nNew; /* Number of remaining savepoints after this op. */ + + /* Figure out how many savepoints will still be active after this + ** operation. Store this value in nNew. Then free resources associated + ** with any savepoints that are destroyed by this operation. + */ + nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1); + for(ii=nNew; iinSavepoint; ii++){ + sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); + } + pPager->nSavepoint = nNew; + + /* If this is a release of the outermost savepoint, truncate + ** the sub-journal to zero bytes in size. */ + if( op==SAVEPOINT_RELEASE ){ + if( nNew==0 && isOpen(pPager->sjfd) ){ + /* Only truncate if it is an in-memory sub-journal. */ + if( sqlite3IsMemJournal(pPager->sjfd) ){ + rc = sqlite3OsTruncate(pPager->sjfd, 0); + assert( rc==SQLITE_OK ); + } + pPager->nSubRec = 0; + } + } + /* Else this is a rollback operation, playback the specified savepoint. + ** If this is a temp-file, it is possible that the journal file has + ** not yet been opened. In this case there have been no changes to + ** the database file, so the playback operation can be skipped. + */ + else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){ + PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1]; + rc = pagerPlaybackSavepoint(pPager, pSavepoint); + assert(rc!=SQLITE_DONE); + } + } + + return rc; +} + +/* +** Return the full pathname of the database file. +** +** Except, if the pager is in-memory only, then return an empty string if +** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when +** used to report the filename to the user, for compatibility with legacy +** behavior. But when the Btree needs to know the filename for matching to +** shared cache, it uses nullIfMemDb==0 so that in-memory databases can +** participate in shared-cache. +*/ +SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){ + return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename; +} + +/* +** Return the VFS structure for the pager. +*/ +SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){ + return pPager->pVfs; +} + +/* +** Return the file handle for the database file associated +** with the pager. This might return NULL if the file has +** not yet been opened. +*/ +SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){ + return pPager->fd; +} + +/* +** Return the full pathname of the journal file. +*/ +SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){ + return pPager->zJournal; +} + +/* +** Return true if fsync() calls are disabled for this pager. Return FALSE +** if fsync()s are executed normally. +*/ +SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){ + return pPager->noSync; +} + +#ifdef SQLITE_HAS_CODEC +/* +** Set or retrieve the codec for this pager +*/ +SQLITE_PRIVATE void sqlite3PagerSetCodec( + Pager *pPager, + void *(*xCodec)(void*,void*,Pgno,int), + void (*xCodecSizeChng)(void*,int,int), + void (*xCodecFree)(void*), + void *pCodec +){ + if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); + pPager->xCodec = pPager->memDb ? 0 : xCodec; + pPager->xCodecSizeChng = xCodecSizeChng; + pPager->xCodecFree = xCodecFree; + pPager->pCodec = pCodec; + pagerReportSize(pPager); +} +SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){ + return pPager->pCodec; +} + +/* +** This function is called by the wal module when writing page content +** into the log file. +** +** This function returns a pointer to a buffer containing the encrypted +** page content. If a malloc fails, this function may return NULL. +*/ +SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){ + void *aData = 0; + CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData); + return aData; +} + +/* +** Return the current pager state +*/ +SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){ + return pPager->eState; +} +#endif /* SQLITE_HAS_CODEC */ + +#ifndef SQLITE_OMIT_AUTOVACUUM +/* +** Move the page pPg to location pgno in the file. +** +** There must be no references to the page previously located at +** pgno (which we call pPgOld) though that page is allowed to be +** in cache. If the page previously located at pgno is not already +** in the rollback journal, it is not put there by by this routine. +** +** References to the page pPg remain valid. Updating any +** meta-data associated with pPg (i.e. data stored in the nExtra bytes +** allocated along with the page) is the responsibility of the caller. +** +** A transaction must be active when this routine is called. It used to be +** required that a statement transaction was not active, but this restriction +** has been removed (CREATE INDEX needs to move a page when a statement +** transaction is active). +** +** If the fourth argument, isCommit, is non-zero, then this page is being +** moved as part of a database reorganization just before the transaction +** is being committed. In this case, it is guaranteed that the database page +** pPg refers to will not be written to again within this transaction. +** +** This function may return SQLITE_NOMEM or an IO error code if an error +** occurs. Otherwise, it returns SQLITE_OK. +*/ +SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){ + PgHdr *pPgOld; /* The page being overwritten. */ + Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */ + int rc; /* Return code */ + Pgno origPgno; /* The original page number */ + + assert( pPg->nRef>0 ); + assert( pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + ); + assert( assert_pager_state(pPager) ); + + /* In order to be able to rollback, an in-memory database must journal + ** the page we are moving from. + */ + if( MEMDB ){ + rc = sqlite3PagerWrite(pPg); + if( rc ) return rc; + } + + /* If the page being moved is dirty and has not been saved by the latest + ** savepoint, then save the current contents of the page into the + ** sub-journal now. This is required to handle the following scenario: + ** + ** BEGIN; + ** + ** SAVEPOINT one; + ** + ** ROLLBACK TO one; + ** + ** If page X were not written to the sub-journal here, it would not + ** be possible to restore its contents when the "ROLLBACK TO one" + ** statement were is processed. + ** + ** subjournalPage() may need to allocate space to store pPg->pgno into + ** one or more savepoint bitvecs. This is the reason this function + ** may return SQLITE_NOMEM. + */ + if( pPg->flags&PGHDR_DIRTY + && subjRequiresPage(pPg) + && SQLITE_OK!=(rc = subjournalPage(pPg)) + ){ + return rc; + } + + PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", + PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno)); + IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno)) + + /* If the journal needs to be sync()ed before page pPg->pgno can + ** be written to, store pPg->pgno in local variable needSyncPgno. + ** + ** If the isCommit flag is set, there is no need to remember that + ** the journal needs to be sync()ed before database page pPg->pgno + ** can be written to. The caller has already promised not to write to it. + */ + if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){ + needSyncPgno = pPg->pgno; + assert( pPager->journalMode==PAGER_JOURNALMODE_OFF || + pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize ); + assert( pPg->flags&PGHDR_DIRTY ); + } + + /* If the cache contains a page with page-number pgno, remove it + ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for + ** page pgno before the 'move' operation, it needs to be retained + ** for the page moved there. + */ + pPg->flags &= ~PGHDR_NEED_SYNC; + pPgOld = pager_lookup(pPager, pgno); + assert( !pPgOld || pPgOld->nRef==1 ); + if( pPgOld ){ + pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC); + if( MEMDB ){ + /* Do not discard pages from an in-memory database since we might + ** need to rollback later. Just move the page out of the way. */ + sqlite3PcacheMove(pPgOld, pPager->dbSize+1); + }else{ + sqlite3PcacheDrop(pPgOld); + } + } + + origPgno = pPg->pgno; + sqlite3PcacheMove(pPg, pgno); + sqlite3PcacheMakeDirty(pPg); + + /* For an in-memory database, make sure the original page continues + ** to exist, in case the transaction needs to roll back. Use pPgOld + ** as the original page since it has already been allocated. + */ + if( MEMDB ){ + assert( pPgOld ); + sqlite3PcacheMove(pPgOld, origPgno); + sqlite3PagerUnref(pPgOld); + } + + if( needSyncPgno ){ + /* If needSyncPgno is non-zero, then the journal file needs to be + ** sync()ed before any data is written to database file page needSyncPgno. + ** Currently, no such page exists in the page-cache and the + ** "is journaled" bitvec flag has been set. This needs to be remedied by + ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC + ** flag. + ** + ** If the attempt to load the page into the page-cache fails, (due + ** to a malloc() or IO failure), clear the bit in the pInJournal[] + ** array. Otherwise, if the page is loaded and written again in + ** this transaction, it may be written to the database file before + ** it is synced into the journal file. This way, it may end up in + ** the journal file twice, but that is not a problem. + */ + PgHdr *pPgHdr; + rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr); + if( rc!=SQLITE_OK ){ + if( needSyncPgno<=pPager->dbOrigSize ){ + assert( pPager->pTmpSpace!=0 ); + sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace); + } + return rc; + } + pPgHdr->flags |= PGHDR_NEED_SYNC; + sqlite3PcacheMakeDirty(pPgHdr); + sqlite3PagerUnref(pPgHdr); + } + + return SQLITE_OK; +} +#endif + +/* +** Return a pointer to the data for the specified page. +*/ +SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){ + assert( pPg->nRef>0 || pPg->pPager->memDb ); + return pPg->pData; +} + +/* +** Return a pointer to the Pager.nExtra bytes of "extra" space +** allocated along with the specified page. +*/ +SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){ + return pPg->pExtra; +} + +/* +** Get/set the locking-mode for this pager. Parameter eMode must be one +** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or +** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then +** the locking-mode is set to the value specified. +** +** The returned value is either PAGER_LOCKINGMODE_NORMAL or +** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated) +** locking-mode. +*/ +SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){ + assert( eMode==PAGER_LOCKINGMODE_QUERY + || eMode==PAGER_LOCKINGMODE_NORMAL + || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); + assert( PAGER_LOCKINGMODE_QUERY<0 ); + assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 ); + assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) ); + if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){ + pPager->exclusiveMode = (u8)eMode; + } + return (int)pPager->exclusiveMode; +} + +/* +** Set the journal-mode for this pager. Parameter eMode must be one of: +** +** PAGER_JOURNALMODE_DELETE +** PAGER_JOURNALMODE_TRUNCATE +** PAGER_JOURNALMODE_PERSIST +** PAGER_JOURNALMODE_OFF +** PAGER_JOURNALMODE_MEMORY +** PAGER_JOURNALMODE_WAL +** +** The journalmode is set to the value specified if the change is allowed. +** The change may be disallowed for the following reasons: +** +** * An in-memory database can only have its journal_mode set to _OFF +** or _MEMORY. +** +** * Temporary databases cannot have _WAL journalmode. +** +** The returned indicate the current (possibly updated) journal-mode. +*/ +SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ + u8 eOld = pPager->journalMode; /* Prior journalmode */ + +#ifdef SQLITE_DEBUG + /* The print_pager_state() routine is intended to be used by the debugger + ** only. We invoke it once here to suppress a compiler warning. */ + print_pager_state(pPager); +#endif + + + /* The eMode parameter is always valid */ + assert( eMode==PAGER_JOURNALMODE_DELETE + || eMode==PAGER_JOURNALMODE_TRUNCATE + || eMode==PAGER_JOURNALMODE_PERSIST + || eMode==PAGER_JOURNALMODE_OFF + || eMode==PAGER_JOURNALMODE_WAL + || eMode==PAGER_JOURNALMODE_MEMORY ); + + /* This routine is only called from the OP_JournalMode opcode, and + ** the logic there will never allow a temporary file to be changed + ** to WAL mode. + */ + assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL ); + + /* Do allow the journalmode of an in-memory database to be set to + ** anything other than MEMORY or OFF + */ + if( MEMDB ){ + assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF ); + if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){ + eMode = eOld; + } + } + + if( eMode!=eOld ){ + + /* Change the journal mode. */ + assert( pPager->eState!=PAGER_ERROR ); + pPager->journalMode = (u8)eMode; + + /* When transistioning from TRUNCATE or PERSIST to any other journal + ** mode except WAL, unless the pager is in locking_mode=exclusive mode, + ** delete the journal file. + */ + assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); + assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); + assert( (PAGER_JOURNALMODE_DELETE & 5)==0 ); + assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 ); + assert( (PAGER_JOURNALMODE_OFF & 5)==0 ); + assert( (PAGER_JOURNALMODE_WAL & 5)==5 ); + + assert( isOpen(pPager->fd) || pPager->exclusiveMode ); + if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){ + + /* In this case we would like to delete the journal file. If it is + ** not possible, then that is not a problem. Deleting the journal file + ** here is an optimization only. + ** + ** Before deleting the journal file, obtain a RESERVED lock on the + ** database file. This ensures that the journal file is not deleted + ** while it is in use by some other client. + */ + sqlite3OsClose(pPager->jfd); + if( pPager->eLock>=RESERVED_LOCK ){ + sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); + }else{ + int rc = SQLITE_OK; + int state = pPager->eState; + assert( state==PAGER_OPEN || state==PAGER_READER ); + if( state==PAGER_OPEN ){ + rc = sqlite3PagerSharedLock(pPager); + } + if( pPager->eState==PAGER_READER ){ + assert( rc==SQLITE_OK ); + rc = pagerLockDb(pPager, RESERVED_LOCK); + } + if( rc==SQLITE_OK ){ + sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); + } + if( rc==SQLITE_OK && state==PAGER_READER ){ + pagerUnlockDb(pPager, SHARED_LOCK); + }else if( state==PAGER_OPEN ){ + pager_unlock(pPager); + } + assert( state==pPager->eState ); + } + } + } + + /* Return the new journal mode */ + return (int)pPager->journalMode; +} + +/* +** Return the current journal mode. +*/ +SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){ + return (int)pPager->journalMode; +} + +/* +** Return TRUE if the pager is in a state where it is OK to change the +** journalmode. Journalmode changes can only happen when the database +** is unmodified. +*/ +SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){ + assert( assert_pager_state(pPager) ); + if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0; + if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0; + return 1; +} + +/* +** Get/set the size-limit used for persistent journal files. +** +** Setting the size limit to -1 means no limit is enforced. +** An attempt to set a limit smaller than -1 is a no-op. +*/ +SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){ + if( iLimit>=-1 ){ + pPager->journalSizeLimit = iLimit; + sqlite3WalLimit(pPager->pWal, iLimit); + } + return pPager->journalSizeLimit; +} + +/* +** Return a pointer to the pPager->pBackup variable. The backup module +** in backup.c maintains the content of this variable. This module +** uses it opaquely as an argument to sqlite3BackupRestart() and +** sqlite3BackupUpdate() only. +*/ +SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){ + return &pPager->pBackup; +} + +#ifndef SQLITE_OMIT_VACUUM +/* +** Unless this is an in-memory or temporary database, clear the pager cache. +*/ +SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){ + if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager); +} +#endif + +#ifndef SQLITE_OMIT_WAL +/* +** This function is called when the user invokes "PRAGMA wal_checkpoint", +** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint() +** or wal_blocking_checkpoint() API functions. +** +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +*/ +SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){ + int rc = SQLITE_OK; + if( pPager->pWal ){ + rc = sqlite3WalCheckpoint(pPager->pWal, eMode, + pPager->xBusyHandler, pPager->pBusyHandlerArg, + pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace, + pnLog, pnCkpt + ); + } + return rc; +} + +SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){ + return sqlite3WalCallback(pPager->pWal); +} + +/* +** Return true if the underlying VFS for the given pager supports the +** primitives necessary for write-ahead logging. +*/ +SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){ + const sqlite3_io_methods *pMethods = pPager->fd->pMethods; + return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap); +} + +/* +** Attempt to take an exclusive lock on the database file. If a PENDING lock +** is obtained instead, immediately release it. +*/ +static int pagerExclusiveLock(Pager *pPager){ + int rc; /* Return code */ + + assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); + rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); + if( rc!=SQLITE_OK ){ + /* If the attempt to grab the exclusive lock failed, release the + ** pending lock that may have been obtained instead. */ + pagerUnlockDb(pPager, SHARED_LOCK); + } + + return rc; +} + +/* +** Call sqlite3WalOpen() to open the WAL handle. If the pager is in +** exclusive-locking mode when this function is called, take an EXCLUSIVE +** lock on the database file and use heap-memory to store the wal-index +** in. Otherwise, use the normal shared-memory. +*/ +static int pagerOpenWal(Pager *pPager){ + int rc = SQLITE_OK; + + assert( pPager->pWal==0 && pPager->tempFile==0 ); + assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); + + /* If the pager is already in exclusive-mode, the WAL module will use + ** heap-memory for the wal-index instead of the VFS shared-memory + ** implementation. Take the exclusive lock now, before opening the WAL + ** file, to make sure this is safe. + */ + if( pPager->exclusiveMode ){ + rc = pagerExclusiveLock(pPager); + } + + /* Open the connection to the log file. If this operation fails, + ** (e.g. due to malloc() failure), return an error code. + */ + if( rc==SQLITE_OK ){ + rc = sqlite3WalOpen(pPager->pVfs, + pPager->fd, pPager->zWal, pPager->exclusiveMode, + pPager->journalSizeLimit, &pPager->pWal + ); + } + pagerFixMaplimit(pPager); + + return rc; +} + + +/* +** The caller must be holding a SHARED lock on the database file to call +** this function. +** +** If the pager passed as the first argument is open on a real database +** file (not a temp file or an in-memory database), and the WAL file +** is not already open, make an attempt to open it now. If successful, +** return SQLITE_OK. If an error occurs or the VFS used by the pager does +** not support the xShmXXX() methods, return an error code. *pbOpen is +** not modified in either case. +** +** If the pager is open on a temp-file (or in-memory database), or if +** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK +** without doing anything. +*/ +SQLITE_PRIVATE int sqlite3PagerOpenWal( + Pager *pPager, /* Pager object */ + int *pbOpen /* OUT: Set to true if call is a no-op */ +){ + int rc = SQLITE_OK; /* Return code */ + + assert( assert_pager_state(pPager) ); + assert( pPager->eState==PAGER_OPEN || pbOpen ); + assert( pPager->eState==PAGER_READER || !pbOpen ); + assert( pbOpen==0 || *pbOpen==0 ); + assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) ); + + if( !pPager->tempFile && !pPager->pWal ){ + if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN; + + /* Close any rollback journal previously open */ + sqlite3OsClose(pPager->jfd); + + rc = pagerOpenWal(pPager); + if( rc==SQLITE_OK ){ + pPager->journalMode = PAGER_JOURNALMODE_WAL; + pPager->eState = PAGER_OPEN; + } + }else{ + *pbOpen = 1; + } + + return rc; +} + +/* +** This function is called to close the connection to the log file prior +** to switching from WAL to rollback mode. +** +** Before closing the log file, this function attempts to take an +** EXCLUSIVE lock on the database file. If this cannot be obtained, an +** error (SQLITE_BUSY) is returned and the log connection is not closed. +** If successful, the EXCLUSIVE lock is not released before returning. +*/ +SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){ + int rc = SQLITE_OK; + + assert( pPager->journalMode==PAGER_JOURNALMODE_WAL ); + + /* If the log file is not already open, but does exist in the file-system, + ** it may need to be checkpointed before the connection can switch to + ** rollback mode. Open it now so this can happen. + */ + if( !pPager->pWal ){ + int logexists = 0; + rc = pagerLockDb(pPager, SHARED_LOCK); + if( rc==SQLITE_OK ){ + rc = sqlite3OsAccess( + pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists + ); + } + if( rc==SQLITE_OK && logexists ){ + rc = pagerOpenWal(pPager); + } + } + + /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on + ** the database file, the log and log-summary files will be deleted. + */ + if( rc==SQLITE_OK && pPager->pWal ){ + rc = pagerExclusiveLock(pPager); + if( rc==SQLITE_OK ){ + rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, + pPager->pageSize, (u8*)pPager->pTmpSpace); + pPager->pWal = 0; + pagerFixMaplimit(pPager); + } + } + return rc; +} + +#endif /* !SQLITE_OMIT_WAL */ + +#ifdef SQLITE_ENABLE_ZIPVFS +/* +** A read-lock must be held on the pager when this function is called. If +** the pager is in WAL mode and the WAL file currently contains one or more +** frames, return the size in bytes of the page images stored within the +** WAL frames. Otherwise, if this is not a WAL database or the WAL file +** is empty, return 0. +*/ +SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){ + assert( pPager->eState==PAGER_READER ); + return sqlite3WalFramesize(pPager->pWal); +} +#endif + +#endif /* SQLITE_OMIT_DISKIO */ + +/************** End of pager.c ***********************************************/ +/************** Begin file wal.c *********************************************/ +/* +** 2010 February 1 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the implementation of a write-ahead log (WAL) used in +** "journal_mode=WAL" mode. +** +** WRITE-AHEAD LOG (WAL) FILE FORMAT +** +** A WAL file consists of a header followed by zero or more "frames". +** Each frame records the revised content of a single page from the +** database file. All changes to the database are recorded by writing +** frames into the WAL. Transactions commit when a frame is written that +** contains a commit marker. A single WAL can and usually does record +** multiple transactions. Periodically, the content of the WAL is +** transferred back into the database file in an operation called a +** "checkpoint". +** +** A single WAL file can be used multiple times. In other words, the +** WAL can fill up with frames and then be checkpointed and then new +** frames can overwrite the old ones. A WAL always grows from beginning +** toward the end. Checksums and counters attached to each frame are +** used to determine which frames within the WAL are valid and which +** are leftovers from prior checkpoints. +** +** The WAL header is 32 bytes in size and consists of the following eight +** big-endian 32-bit unsigned integer values: +** +** 0: Magic number. 0x377f0682 or 0x377f0683 +** 4: File format version. Currently 3007000 +** 8: Database page size. Example: 1024 +** 12: Checkpoint sequence number +** 16: Salt-1, random integer incremented with each checkpoint +** 20: Salt-2, a different random integer changing with each ckpt +** 24: Checksum-1 (first part of checksum for first 24 bytes of header). +** 28: Checksum-2 (second part of checksum for first 24 bytes of header). +** +** Immediately following the wal-header are zero or more frames. Each +** frame consists of a 24-byte frame-header followed by a bytes +** of page data. The frame-header is six big-endian 32-bit unsigned +** integer values, as follows: +** +** 0: Page number. +** 4: For commit records, the size of the database image in pages +** after the commit. For all other records, zero. +** 8: Salt-1 (copied from the header) +** 12: Salt-2 (copied from the header) +** 16: Checksum-1. +** 20: Checksum-2. +** +** A frame is considered valid if and only if the following conditions are +** true: +** +** (1) The salt-1 and salt-2 values in the frame-header match +** salt values in the wal-header +** +** (2) The checksum values in the final 8 bytes of the frame-header +** exactly match the checksum computed consecutively on the +** WAL header and the first 8 bytes and the content of all frames +** up to and including the current frame. +** +** The checksum is computed using 32-bit big-endian integers if the +** magic number in the first 4 bytes of the WAL is 0x377f0683 and it +** is computed using little-endian if the magic number is 0x377f0682. +** The checksum values are always stored in the frame header in a +** big-endian format regardless of which byte order is used to compute +** the checksum. The checksum is computed by interpreting the input as +** an even number of unsigned 32-bit integers: x[0] through x[N]. The +** algorithm used for the checksum is as follows: +** +** for i from 0 to n-1 step 2: +** s0 += x[i] + s1; +** s1 += x[i+1] + s0; +** endfor +** +** Note that s0 and s1 are both weighted checksums using fibonacci weights +** in reverse order (the largest fibonacci weight occurs on the first element +** of the sequence being summed.) The s1 value spans all 32-bit +** terms of the sequence whereas s0 omits the final term. +** +** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the +** WAL is transferred into the database, then the database is VFS.xSync-ed. +** The VFS.xSync operations serve as write barriers - all writes launched +** before the xSync must complete before any write that launches after the +** xSync begins. +** +** After each checkpoint, the salt-1 value is incremented and the salt-2 +** value is randomized. This prevents old and new frames in the WAL from +** being considered valid at the same time and being checkpointing together +** following a crash. +** +** READER ALGORITHM +** +** To read a page from the database (call it page number P), a reader +** first checks the WAL to see if it contains page P. If so, then the +** last valid instance of page P that is a followed by a commit frame +** or is a commit frame itself becomes the value read. If the WAL +** contains no copies of page P that are valid and which are a commit +** frame or are followed by a commit frame, then page P is read from +** the database file. +** +** To start a read transaction, the reader records the index of the last +** valid frame in the WAL. The reader uses this recorded "mxFrame" value +** for all subsequent read operations. New transactions can be appended +** to the WAL, but as long as the reader uses its original mxFrame value +** and ignores the newly appended content, it will see a consistent snapshot +** of the database from a single point in time. This technique allows +** multiple concurrent readers to view different versions of the database +** content simultaneously. +** +** The reader algorithm in the previous paragraphs works correctly, but +** because frames for page P can appear anywhere within the WAL, the +** reader has to scan the entire WAL looking for page P frames. If the +** WAL is large (multiple megabytes is typical) that scan can be slow, +** and read performance suffers. To overcome this problem, a separate +** data structure called the wal-index is maintained to expedite the +** search for frames of a particular page. +** +** WAL-INDEX FORMAT +** +** Conceptually, the wal-index is shared memory, though VFS implementations +** might choose to implement the wal-index using a mmapped file. Because +** the wal-index is shared memory, SQLite does not support journal_mode=WAL +** on a network filesystem. All users of the database must be able to +** share memory. +** +** The wal-index is transient. After a crash, the wal-index can (and should +** be) reconstructed from the original WAL file. In fact, the VFS is required +** to either truncate or zero the header of the wal-index when the last +** connection to it closes. Because the wal-index is transient, it can +** use an architecture-specific format; it does not have to be cross-platform. +** Hence, unlike the database and WAL file formats which store all values +** as big endian, the wal-index can store multi-byte values in the native +** byte order of the host computer. +** +** The purpose of the wal-index is to answer this question quickly: Given +** a page number P and a maximum frame index M, return the index of the +** last frame in the wal before frame M for page P in the WAL, or return +** NULL if there are no frames for page P in the WAL prior to M. +** +** The wal-index consists of a header region, followed by an one or +** more index blocks. +** +** The wal-index header contains the total number of frames within the WAL +** in the mxFrame field. +** +** Each index block except for the first contains information on +** HASHTABLE_NPAGE frames. The first index block contains information on +** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and +** HASHTABLE_NPAGE are selected so that together the wal-index header and +** first index block are the same size as all other index blocks in the +** wal-index. +** +** Each index block contains two sections, a page-mapping that contains the +** database page number associated with each wal frame, and a hash-table +** that allows readers to query an index block for a specific page number. +** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE +** for the first index block) 32-bit page numbers. The first entry in the +** first index-block contains the database page number corresponding to the +** first frame in the WAL file. The first entry in the second index block +** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in +** the log, and so on. +** +** The last index block in a wal-index usually contains less than the full +** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers, +** depending on the contents of the WAL file. This does not change the +** allocated size of the page-mapping array - the page-mapping array merely +** contains unused entries. +** +** Even without using the hash table, the last frame for page P +** can be found by scanning the page-mapping sections of each index block +** starting with the last index block and moving toward the first, and +** within each index block, starting at the end and moving toward the +** beginning. The first entry that equals P corresponds to the frame +** holding the content for that page. +** +** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers. +** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the +** hash table for each page number in the mapping section, so the hash +** table is never more than half full. The expected number of collisions +** prior to finding a match is 1. Each entry of the hash table is an +** 1-based index of an entry in the mapping section of the same +** index block. Let K be the 1-based index of the largest entry in +** the mapping section. (For index blocks other than the last, K will +** always be exactly HASHTABLE_NPAGE (4096) and for the last index block +** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table +** contain a value of 0. +** +** To look for page P in the hash table, first compute a hash iKey on +** P as follows: +** +** iKey = (P * 383) % HASHTABLE_NSLOT +** +** Then start scanning entries of the hash table, starting with iKey +** (wrapping around to the beginning when the end of the hash table is +** reached) until an unused hash slot is found. Let the first unused slot +** be at index iUnused. (iUnused might be less than iKey if there was +** wrap-around.) Because the hash table is never more than half full, +** the search is guaranteed to eventually hit an unused entry. Let +** iMax be the value between iKey and iUnused, closest to iUnused, +** where aHash[iMax]==P. If there is no iMax entry (if there exists +** no hash slot such that aHash[i]==p) then page P is not in the +** current index block. Otherwise the iMax-th mapping entry of the +** current index block corresponds to the last entry that references +** page P. +** +** A hash search begins with the last index block and moves toward the +** first index block, looking for entries corresponding to page P. On +** average, only two or three slots in each index block need to be +** examined in order to either find the last entry for page P, or to +** establish that no such entry exists in the block. Each index block +** holds over 4000 entries. So two or three index blocks are sufficient +** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10 +** comparisons (on average) suffice to either locate a frame in the +** WAL or to establish that the frame does not exist in the WAL. This +** is much faster than scanning the entire 10MB WAL. +** +** Note that entries are added in order of increasing K. Hence, one +** reader might be using some value K0 and a second reader that started +** at a later time (after additional transactions were added to the WAL +** and to the wal-index) might be using a different value K1, where K1>K0. +** Both readers can use the same hash table and mapping section to get +** the correct result. There may be entries in the hash table with +** K>K0 but to the first reader, those entries will appear to be unused +** slots in the hash table and so the first reader will get an answer as +** if no values greater than K0 had ever been inserted into the hash table +** in the first place - which is what reader one wants. Meanwhile, the +** second reader using K1 will see additional values that were inserted +** later, which is exactly what reader two wants. +** +** When a rollback occurs, the value of K is decreased. Hash table entries +** that correspond to frames greater than the new K value are removed +** from the hash table at this point. +*/ +#ifndef SQLITE_OMIT_WAL + + +/* +** Trace output macros +*/ +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) +SQLITE_PRIVATE int sqlite3WalTrace = 0; +# define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X +#else +# define WALTRACE(X) +#endif + +/* +** The maximum (and only) versions of the wal and wal-index formats +** that may be interpreted by this version of SQLite. +** +** If a client begins recovering a WAL file and finds that (a) the checksum +** values in the wal-header are correct and (b) the version field is not +** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN. +** +** Similarly, if a client successfully reads a wal-index header (i.e. the +** checksum test is successful) and finds that the version field is not +** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite +** returns SQLITE_CANTOPEN. +*/ +#define WAL_MAX_VERSION 3007000 +#define WALINDEX_MAX_VERSION 3007000 + +/* +** Indices of various locking bytes. WAL_NREADER is the number +** of available reader locks and should be at least 3. +*/ +#define WAL_WRITE_LOCK 0 +#define WAL_ALL_BUT_WRITE 1 +#define WAL_CKPT_LOCK 1 +#define WAL_RECOVER_LOCK 2 +#define WAL_READ_LOCK(I) (3+(I)) +#define WAL_NREADER (SQLITE_SHM_NLOCK-3) + + +/* Object declarations */ +typedef struct WalIndexHdr WalIndexHdr; +typedef struct WalIterator WalIterator; +typedef struct WalCkptInfo WalCkptInfo; + + +/* +** The following object holds a copy of the wal-index header content. +** +** The actual header in the wal-index consists of two copies of this +** object. +** +** The szPage value can be any power of 2 between 512 and 32768, inclusive. +** Or it can be 1 to represent a 65536-byte page. The latter case was +** added in 3.7.1 when support for 64K pages was added. +*/ +struct WalIndexHdr { + u32 iVersion; /* Wal-index version */ + u32 unused; /* Unused (padding) field */ + u32 iChange; /* Counter incremented each transaction */ + u8 isInit; /* 1 when initialized */ + u8 bigEndCksum; /* True if checksums in WAL are big-endian */ + u16 szPage; /* Database page size in bytes. 1==64K */ + u32 mxFrame; /* Index of last valid frame in the WAL */ + u32 nPage; /* Size of database in pages */ + u32 aFrameCksum[2]; /* Checksum of last frame in log */ + u32 aSalt[2]; /* Two salt values copied from WAL header */ + u32 aCksum[2]; /* Checksum over all prior fields */ +}; + +/* +** A copy of the following object occurs in the wal-index immediately +** following the second copy of the WalIndexHdr. This object stores +** information used by checkpoint. +** +** nBackfill is the number of frames in the WAL that have been written +** back into the database. (We call the act of moving content from WAL to +** database "backfilling".) The nBackfill number is never greater than +** WalIndexHdr.mxFrame. nBackfill can only be increased by threads +** holding the WAL_CKPT_LOCK lock (which includes a recovery thread). +** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from +** mxFrame back to zero when the WAL is reset. +** +** There is one entry in aReadMark[] for each reader lock. If a reader +** holds read-lock K, then the value in aReadMark[K] is no greater than +** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff) +** for any aReadMark[] means that entry is unused. aReadMark[0] is +** a special case; its value is never used and it exists as a place-holder +** to avoid having to offset aReadMark[] indexs by one. Readers holding +** WAL_READ_LOCK(0) always ignore the entire WAL and read all content +** directly from the database. +** +** The value of aReadMark[K] may only be changed by a thread that +** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of +** aReadMark[K] cannot changed while there is a reader is using that mark +** since the reader will be holding a shared lock on WAL_READ_LOCK(K). +** +** The checkpointer may only transfer frames from WAL to database where +** the frame numbers are less than or equal to every aReadMark[] that is +** in use (that is, every aReadMark[j] for which there is a corresponding +** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the +** largest value and will increase an unused aReadMark[] to mxFrame if there +** is not already an aReadMark[] equal to mxFrame. The exception to the +** previous sentence is when nBackfill equals mxFrame (meaning that everything +** in the WAL has been backfilled into the database) then new readers +** will choose aReadMark[0] which has value 0 and hence such reader will +** get all their all content directly from the database file and ignore +** the WAL. +** +** Writers normally append new frames to the end of the WAL. However, +** if nBackfill equals mxFrame (meaning that all WAL content has been +** written back into the database) and if no readers are using the WAL +** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then +** the writer will first "reset" the WAL back to the beginning and start +** writing new content beginning at frame 1. +** +** We assume that 32-bit loads are atomic and so no locks are needed in +** order to read from any aReadMark[] entries. +*/ +struct WalCkptInfo { + u32 nBackfill; /* Number of WAL frames backfilled into DB */ + u32 aReadMark[WAL_NREADER]; /* Reader marks */ +}; +#define READMARK_NOT_USED 0xffffffff + + +/* A block of WALINDEX_LOCK_RESERVED bytes beginning at +** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems +** only support mandatory file-locks, we do not read or write data +** from the region of the file on which locks are applied. +*/ +#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo)) +#define WALINDEX_LOCK_RESERVED 16 +#define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED) + +/* Size of header before each frame in wal */ +#define WAL_FRAME_HDRSIZE 24 + +/* Size of write ahead log header, including checksum. */ +/* #define WAL_HDRSIZE 24 */ +#define WAL_HDRSIZE 32 + +/* WAL magic value. Either this value, or the same value with the least +** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit +** big-endian format in the first 4 bytes of a WAL file. +** +** If the LSB is set, then the checksums for each frame within the WAL +** file are calculated by treating all data as an array of 32-bit +** big-endian words. Otherwise, they are calculated by interpreting +** all data as 32-bit little-endian words. +*/ +#define WAL_MAGIC 0x377f0682 + +/* +** Return the offset of frame iFrame in the write-ahead log file, +** assuming a database page size of szPage bytes. The offset returned +** is to the start of the write-ahead log frame-header. +*/ +#define walFrameOffset(iFrame, szPage) ( \ + WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \ +) + +/* +** An open write-ahead log file is represented by an instance of the +** following object. +*/ +struct Wal { + sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */ + sqlite3_file *pDbFd; /* File handle for the database file */ + sqlite3_file *pWalFd; /* File handle for WAL file */ + u32 iCallback; /* Value to pass to log callback (or 0) */ + i64 mxWalSize; /* Truncate WAL to this size upon reset */ + int nWiData; /* Size of array apWiData */ + int szFirstBlock; /* Size of first block written to WAL file */ + volatile u32 **apWiData; /* Pointer to wal-index content in memory */ + u32 szPage; /* Database page size */ + i16 readLock; /* Which read lock is being held. -1 for none */ + u8 syncFlags; /* Flags to use to sync header writes */ + u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */ + u8 writeLock; /* True if in a write transaction */ + u8 ckptLock; /* True if holding a checkpoint lock */ + u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */ + u8 truncateOnCommit; /* True to truncate WAL file on commit */ + u8 syncHeader; /* Fsync the WAL header if true */ + u8 padToSectorBoundary; /* Pad transactions out to the next sector */ + WalIndexHdr hdr; /* Wal-index header for current transaction */ + const char *zWalName; /* Name of WAL file */ + u32 nCkpt; /* Checkpoint sequence counter in the wal-header */ +#ifdef SQLITE_DEBUG + u8 lockError; /* True if a locking error has occurred */ +#endif +}; + +/* +** Candidate values for Wal.exclusiveMode. +*/ +#define WAL_NORMAL_MODE 0 +#define WAL_EXCLUSIVE_MODE 1 +#define WAL_HEAPMEMORY_MODE 2 + +/* +** Possible values for WAL.readOnly +*/ +#define WAL_RDWR 0 /* Normal read/write connection */ +#define WAL_RDONLY 1 /* The WAL file is readonly */ +#define WAL_SHM_RDONLY 2 /* The SHM file is readonly */ + +/* +** Each page of the wal-index mapping contains a hash-table made up of +** an array of HASHTABLE_NSLOT elements of the following type. +*/ +typedef u16 ht_slot; + +/* +** This structure is used to implement an iterator that loops through +** all frames in the WAL in database page order. Where two or more frames +** correspond to the same database page, the iterator visits only the +** frame most recently written to the WAL (in other words, the frame with +** the largest index). +** +** The internals of this structure are only accessed by: +** +** walIteratorInit() - Create a new iterator, +** walIteratorNext() - Step an iterator, +** walIteratorFree() - Free an iterator. +** +** This functionality is used by the checkpoint code (see walCheckpoint()). +*/ +struct WalIterator { + int iPrior; /* Last result returned from the iterator */ + int nSegment; /* Number of entries in aSegment[] */ + struct WalSegment { + int iNext; /* Next slot in aIndex[] not yet returned */ + ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */ + u32 *aPgno; /* Array of page numbers. */ + int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */ + int iZero; /* Frame number associated with aPgno[0] */ + } aSegment[1]; /* One for every 32KB page in the wal-index */ +}; + +/* +** Define the parameters of the hash tables in the wal-index file. There +** is a hash-table following every HASHTABLE_NPAGE page numbers in the +** wal-index. +** +** Changing any of these constants will alter the wal-index format and +** create incompatibilities. +*/ +#define HASHTABLE_NPAGE 4096 /* Must be power of 2 */ +#define HASHTABLE_HASH_1 383 /* Should be prime */ +#define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */ + +/* +** The block of page numbers associated with the first hash-table in a +** wal-index is smaller than usual. This is so that there is a complete +** hash-table on each aligned 32KB page of the wal-index. +*/ +#define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32))) + +/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */ +#define WALINDEX_PGSZ ( \ + sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \ +) + +/* +** Obtain a pointer to the iPage'th page of the wal-index. The wal-index +** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are +** numbered from zero. +** +** If this call is successful, *ppPage is set to point to the wal-index +** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs, +** then an SQLite error code is returned and *ppPage is set to 0. +*/ +static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){ + int rc = SQLITE_OK; + + /* Enlarge the pWal->apWiData[] array if required */ + if( pWal->nWiData<=iPage ){ + int nByte = sizeof(u32*)*(iPage+1); + volatile u32 **apNew; + apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte); + if( !apNew ){ + *ppPage = 0; + return SQLITE_NOMEM; + } + memset((void*)&apNew[pWal->nWiData], 0, + sizeof(u32*)*(iPage+1-pWal->nWiData)); + pWal->apWiData = apNew; + pWal->nWiData = iPage+1; + } + + /* Request a pointer to the required page from the VFS */ + if( pWal->apWiData[iPage]==0 ){ + if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ + pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ); + if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM; + }else{ + rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, + pWal->writeLock, (void volatile **)&pWal->apWiData[iPage] + ); + if( rc==SQLITE_READONLY ){ + pWal->readOnly |= WAL_SHM_RDONLY; + rc = SQLITE_OK; + } + } + } + + *ppPage = pWal->apWiData[iPage]; + assert( iPage==0 || *ppPage || rc!=SQLITE_OK ); + return rc; +} + +/* +** Return a pointer to the WalCkptInfo structure in the wal-index. +*/ +static volatile WalCkptInfo *walCkptInfo(Wal *pWal){ + assert( pWal->nWiData>0 && pWal->apWiData[0] ); + return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]); +} + +/* +** Return a pointer to the WalIndexHdr structure in the wal-index. +*/ +static volatile WalIndexHdr *walIndexHdr(Wal *pWal){ + assert( pWal->nWiData>0 && pWal->apWiData[0] ); + return (volatile WalIndexHdr*)pWal->apWiData[0]; +} + +/* +** The argument to this macro must be of type u32. On a little-endian +** architecture, it returns the u32 value that results from interpreting +** the 4 bytes as a big-endian value. On a big-endian architecture, it +** returns the value that would be produced by intepreting the 4 bytes +** of the input value as a little-endian integer. +*/ +#define BYTESWAP32(x) ( \ + (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \ + + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \ +) + +/* +** Generate or extend an 8 byte checksum based on the data in +** array aByte[] and the initial values of aIn[0] and aIn[1] (or +** initial values of 0 and 0 if aIn==NULL). +** +** The checksum is written back into aOut[] before returning. +** +** nByte must be a positive multiple of 8. +*/ +static void walChecksumBytes( + int nativeCksum, /* True for native byte-order, false for non-native */ + u8 *a, /* Content to be checksummed */ + int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */ + const u32 *aIn, /* Initial checksum value input */ + u32 *aOut /* OUT: Final checksum value output */ +){ + u32 s1, s2; + u32 *aData = (u32 *)a; + u32 *aEnd = (u32 *)&a[nByte]; + + if( aIn ){ + s1 = aIn[0]; + s2 = aIn[1]; + }else{ + s1 = s2 = 0; + } + + assert( nByte>=8 ); + assert( (nByte&0x00000007)==0 ); + + if( nativeCksum ){ + do { + s1 += *aData++ + s2; + s2 += *aData++ + s1; + }while( aDataexclusiveMode!=WAL_HEAPMEMORY_MODE ){ + sqlite3OsShmBarrier(pWal->pDbFd); + } +} + +/* +** Write the header information in pWal->hdr into the wal-index. +** +** The checksum on pWal->hdr is updated before it is written. +*/ +static void walIndexWriteHdr(Wal *pWal){ + volatile WalIndexHdr *aHdr = walIndexHdr(pWal); + const int nCksum = offsetof(WalIndexHdr, aCksum); + + assert( pWal->writeLock ); + pWal->hdr.isInit = 1; + pWal->hdr.iVersion = WALINDEX_MAX_VERSION; + walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum); + memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr)); + walShmBarrier(pWal); + memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr)); +} + +/* +** This function encodes a single frame header and writes it to a buffer +** supplied by the caller. A frame-header is made up of a series of +** 4-byte big-endian integers, as follows: +** +** 0: Page number. +** 4: For commit records, the size of the database image in pages +** after the commit. For all other records, zero. +** 8: Salt-1 (copied from the wal-header) +** 12: Salt-2 (copied from the wal-header) +** 16: Checksum-1. +** 20: Checksum-2. +*/ +static void walEncodeFrame( + Wal *pWal, /* The write-ahead log */ + u32 iPage, /* Database page number for frame */ + u32 nTruncate, /* New db size (or 0 for non-commit frames) */ + u8 *aData, /* Pointer to page data */ + u8 *aFrame /* OUT: Write encoded frame here */ +){ + int nativeCksum; /* True for native byte-order checksums */ + u32 *aCksum = pWal->hdr.aFrameCksum; + assert( WAL_FRAME_HDRSIZE==24 ); + sqlite3Put4byte(&aFrame[0], iPage); + sqlite3Put4byte(&aFrame[4], nTruncate); + memcpy(&aFrame[8], pWal->hdr.aSalt, 8); + + nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); + walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); + walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); + + sqlite3Put4byte(&aFrame[16], aCksum[0]); + sqlite3Put4byte(&aFrame[20], aCksum[1]); +} + +/* +** Check to see if the frame with header in aFrame[] and content +** in aData[] is valid. If it is a valid frame, fill *piPage and +** *pnTruncate and return true. Return if the frame is not valid. +*/ +static int walDecodeFrame( + Wal *pWal, /* The write-ahead log */ + u32 *piPage, /* OUT: Database page number for frame */ + u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */ + u8 *aData, /* Pointer to page data (for checksum) */ + u8 *aFrame /* Frame data */ +){ + int nativeCksum; /* True for native byte-order checksums */ + u32 *aCksum = pWal->hdr.aFrameCksum; + u32 pgno; /* Page number of the frame */ + assert( WAL_FRAME_HDRSIZE==24 ); + + /* A frame is only valid if the salt values in the frame-header + ** match the salt values in the wal-header. + */ + if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){ + return 0; + } + + /* A frame is only valid if the page number is creater than zero. + */ + pgno = sqlite3Get4byte(&aFrame[0]); + if( pgno==0 ){ + return 0; + } + + /* A frame is only valid if a checksum of the WAL header, + ** all prior frams, the first 16 bytes of this frame-header, + ** and the frame-data matches the checksum in the last 8 + ** bytes of this frame-header. + */ + nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); + walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); + walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); + if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) + || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) + ){ + /* Checksum failed. */ + return 0; + } + + /* If we reach this point, the frame is valid. Return the page number + ** and the new database size. + */ + *piPage = pgno; + *pnTruncate = sqlite3Get4byte(&aFrame[4]); + return 1; +} + + +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) +/* +** Names of locks. This routine is used to provide debugging output and is not +** a part of an ordinary build. +*/ +static const char *walLockName(int lockIdx){ + if( lockIdx==WAL_WRITE_LOCK ){ + return "WRITE-LOCK"; + }else if( lockIdx==WAL_CKPT_LOCK ){ + return "CKPT-LOCK"; + }else if( lockIdx==WAL_RECOVER_LOCK ){ + return "RECOVER-LOCK"; + }else{ + static char zName[15]; + sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]", + lockIdx-WAL_READ_LOCK(0)); + return zName; + } +} +#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ + + +/* +** Set or release locks on the WAL. Locks are either shared or exclusive. +** A lock cannot be moved directly between shared and exclusive - it must go +** through the unlocked state first. +** +** In locking_mode=EXCLUSIVE, all of these routines become no-ops. +*/ +static int walLockShared(Wal *pWal, int lockIdx){ + int rc; + if( pWal->exclusiveMode ) return SQLITE_OK; + rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, + SQLITE_SHM_LOCK | SQLITE_SHM_SHARED); + WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal, + walLockName(lockIdx), rc ? "failed" : "ok")); + VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); ) + return rc; +} +static void walUnlockShared(Wal *pWal, int lockIdx){ + if( pWal->exclusiveMode ) return; + (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, + SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED); + WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx))); +} +static int walLockExclusive(Wal *pWal, int lockIdx, int n){ + int rc; + if( pWal->exclusiveMode ) return SQLITE_OK; + rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, + SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE); + WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal, + walLockName(lockIdx), n, rc ? "failed" : "ok")); + VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); ) + return rc; +} +static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){ + if( pWal->exclusiveMode ) return; + (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, + SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE); + WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal, + walLockName(lockIdx), n)); +} + +/* +** Compute a hash on a page number. The resulting hash value must land +** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances +** the hash to the next value in the event of a collision. +*/ +static int walHash(u32 iPage){ + assert( iPage>0 ); + assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 ); + return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1); +} +static int walNextHash(int iPriorHash){ + return (iPriorHash+1)&(HASHTABLE_NSLOT-1); +} + +/* +** Return pointers to the hash table and page number array stored on +** page iHash of the wal-index. The wal-index is broken into 32KB pages +** numbered starting from 0. +** +** Set output variable *paHash to point to the start of the hash table +** in the wal-index file. Set *piZero to one less than the frame +** number of the first frame indexed by this hash table. If a +** slot in the hash table is set to N, it refers to frame number +** (*piZero+N) in the log. +** +** Finally, set *paPgno so that *paPgno[1] is the page number of the +** first frame indexed by the hash table, frame (*piZero+1). +*/ +static int walHashGet( + Wal *pWal, /* WAL handle */ + int iHash, /* Find the iHash'th table */ + volatile ht_slot **paHash, /* OUT: Pointer to hash index */ + volatile u32 **paPgno, /* OUT: Pointer to page number array */ + u32 *piZero /* OUT: Frame associated with *paPgno[0] */ +){ + int rc; /* Return code */ + volatile u32 *aPgno; + + rc = walIndexPage(pWal, iHash, &aPgno); + assert( rc==SQLITE_OK || iHash>0 ); + + if( rc==SQLITE_OK ){ + u32 iZero; + volatile ht_slot *aHash; + + aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE]; + if( iHash==0 ){ + aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)]; + iZero = 0; + }else{ + iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE; + } + + *paPgno = &aPgno[-1]; + *paHash = aHash; + *piZero = iZero; + } + return rc; +} + +/* +** Return the number of the wal-index page that contains the hash-table +** and page-number array that contain entries corresponding to WAL frame +** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages +** are numbered starting from 0. +*/ +static int walFramePage(u32 iFrame){ + int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE; + assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE) + && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE) + && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)) + && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE) + && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE)) + ); + return iHash; +} + +/* +** Return the page number associated with frame iFrame in this WAL. +*/ +static u32 walFramePgno(Wal *pWal, u32 iFrame){ + int iHash = walFramePage(iFrame); + if( iHash==0 ){ + return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1]; + } + return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE]; +} + +/* +** Remove entries from the hash table that point to WAL slots greater +** than pWal->hdr.mxFrame. +** +** This function is called whenever pWal->hdr.mxFrame is decreased due +** to a rollback or savepoint. +** +** At most only the hash table containing pWal->hdr.mxFrame needs to be +** updated. Any later hash tables will be automatically cleared when +** pWal->hdr.mxFrame advances to the point where those hash tables are +** actually needed. +*/ +static void walCleanupHash(Wal *pWal){ + volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */ + volatile u32 *aPgno = 0; /* Page number array for hash table */ + u32 iZero = 0; /* frame == (aHash[x]+iZero) */ + int iLimit = 0; /* Zero values greater than this */ + int nByte; /* Number of bytes to zero in aPgno[] */ + int i; /* Used to iterate through aHash[] */ + + assert( pWal->writeLock ); + testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 ); + testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE ); + testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 ); + + if( pWal->hdr.mxFrame==0 ) return; + + /* Obtain pointers to the hash-table and page-number array containing + ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed + ** that the page said hash-table and array reside on is already mapped. + */ + assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) ); + assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] ); + walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero); + + /* Zero all hash-table entries that correspond to frame numbers greater + ** than pWal->hdr.mxFrame. + */ + iLimit = pWal->hdr.mxFrame - iZero; + assert( iLimit>0 ); + for(i=0; iiLimit ){ + aHash[i] = 0; + } + } + + /* Zero the entries in the aPgno array that correspond to frames with + ** frame numbers greater than pWal->hdr.mxFrame. + */ + nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]); + memset((void *)&aPgno[iLimit+1], 0, nByte); + +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT + /* Verify that the every entry in the mapping region is still reachable + ** via the hash table even after the cleanup. + */ + if( iLimit ){ + int i; /* Loop counter */ + int iKey; /* Hash key */ + for(i=1; i<=iLimit; i++){ + for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){ + if( aHash[iKey]==i ) break; + } + assert( aHash[iKey]==i ); + } + } +#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ +} + + +/* +** Set an entry in the wal-index that will map database page number +** pPage into WAL frame iFrame. +*/ +static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ + int rc; /* Return code */ + u32 iZero = 0; /* One less than frame number of aPgno[1] */ + volatile u32 *aPgno = 0; /* Page number array */ + volatile ht_slot *aHash = 0; /* Hash table */ + + rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero); + + /* Assuming the wal-index file was successfully mapped, populate the + ** page number array and hash table entry. + */ + if( rc==SQLITE_OK ){ + int iKey; /* Hash table key */ + int idx; /* Value to write to hash-table slot */ + int nCollide; /* Number of hash collisions */ + + idx = iFrame - iZero; + assert( idx <= HASHTABLE_NSLOT/2 + 1 ); + + /* If this is the first entry to be added to this hash-table, zero the + ** entire hash table and aPgno[] array before proceding. + */ + if( idx==1 ){ + int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]); + memset((void*)&aPgno[1], 0, nByte); + } + + /* If the entry in aPgno[] is already set, then the previous writer + ** must have exited unexpectedly in the middle of a transaction (after + ** writing one or more dirty pages to the WAL to free up memory). + ** Remove the remnants of that writers uncommitted transaction from + ** the hash-table before writing any new entries. + */ + if( aPgno[idx] ){ + walCleanupHash(pWal); + assert( !aPgno[idx] ); + } + + /* Write the aPgno[] array entry and the hash-table slot. */ + nCollide = idx; + for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){ + if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT; + } + aPgno[idx] = iPage; + aHash[iKey] = (ht_slot)idx; + +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT + /* Verify that the number of entries in the hash table exactly equals + ** the number of entries in the mapping region. + */ + { + int i; /* Loop counter */ + int nEntry = 0; /* Number of entries in the hash table */ + for(i=0; ickptLock==1 || pWal->ckptLock==0 ); + assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 ); + assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE ); + assert( pWal->writeLock ); + iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock; + nLock = SQLITE_SHM_NLOCK - iLock; + rc = walLockExclusive(pWal, iLock, nLock); + if( rc ){ + return rc; + } + WALTRACE(("WAL%p: recovery begin...\n", pWal)); + + memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); + + rc = sqlite3OsFileSize(pWal->pWalFd, &nSize); + if( rc!=SQLITE_OK ){ + goto recovery_error; + } + + if( nSize>WAL_HDRSIZE ){ + u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */ + u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */ + int szFrame; /* Number of bytes in buffer aFrame[] */ + u8 *aData; /* Pointer to data part of aFrame buffer */ + int iFrame; /* Index of last frame read */ + i64 iOffset; /* Next offset to read from log file */ + int szPage; /* Page size according to the log */ + u32 magic; /* Magic value read from WAL header */ + u32 version; /* Magic value read from WAL header */ + int isValid; /* True if this frame is valid */ + + /* Read in the WAL header. */ + rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0); + if( rc!=SQLITE_OK ){ + goto recovery_error; + } + + /* If the database page size is not a power of two, or is greater than + ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid + ** data. Similarly, if the 'magic' value is invalid, ignore the whole + ** WAL file. + */ + magic = sqlite3Get4byte(&aBuf[0]); + szPage = sqlite3Get4byte(&aBuf[8]); + if( (magic&0xFFFFFFFE)!=WAL_MAGIC + || szPage&(szPage-1) + || szPage>SQLITE_MAX_PAGE_SIZE + || szPage<512 + ){ + goto finished; + } + pWal->hdr.bigEndCksum = (u8)(magic&0x00000001); + pWal->szPage = szPage; + pWal->nCkpt = sqlite3Get4byte(&aBuf[12]); + memcpy(&pWal->hdr.aSalt, &aBuf[16], 8); + + /* Verify that the WAL header checksum is correct */ + walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, + aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum + ); + if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24]) + || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28]) + ){ + goto finished; + } + + /* Verify that the version number on the WAL format is one that + ** are able to understand */ + version = sqlite3Get4byte(&aBuf[4]); + if( version!=WAL_MAX_VERSION ){ + rc = SQLITE_CANTOPEN_BKPT; + goto finished; + } + + /* Malloc a buffer to read frames into. */ + szFrame = szPage + WAL_FRAME_HDRSIZE; + aFrame = (u8 *)sqlite3_malloc(szFrame); + if( !aFrame ){ + rc = SQLITE_NOMEM; + goto recovery_error; + } + aData = &aFrame[WAL_FRAME_HDRSIZE]; + + /* Read all frames from the log file. */ + iFrame = 0; + for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){ + u32 pgno; /* Database page number for frame */ + u32 nTruncate; /* dbsize field from frame header */ + + /* Read and decode the next log frame. */ + iFrame++; + rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); + if( rc!=SQLITE_OK ) break; + isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame); + if( !isValid ) break; + rc = walIndexAppend(pWal, iFrame, pgno); + if( rc!=SQLITE_OK ) break; + + /* If nTruncate is non-zero, this is a commit record. */ + if( nTruncate ){ + pWal->hdr.mxFrame = iFrame; + pWal->hdr.nPage = nTruncate; + pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); + testcase( szPage<=32768 ); + testcase( szPage>=65536 ); + aFrameCksum[0] = pWal->hdr.aFrameCksum[0]; + aFrameCksum[1] = pWal->hdr.aFrameCksum[1]; + } + } + + sqlite3_free(aFrame); + } + +finished: + if( rc==SQLITE_OK ){ + volatile WalCkptInfo *pInfo; + int i; + pWal->hdr.aFrameCksum[0] = aFrameCksum[0]; + pWal->hdr.aFrameCksum[1] = aFrameCksum[1]; + walIndexWriteHdr(pWal); + + /* Reset the checkpoint-header. This is safe because this thread is + ** currently holding locks that exclude all other readers, writers and + ** checkpointers. + */ + pInfo = walCkptInfo(pWal); + pInfo->nBackfill = 0; + pInfo->aReadMark[0] = 0; + for(i=1; iaReadMark[i] = READMARK_NOT_USED; + if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame; + + /* If more than one frame was recovered from the log file, report an + ** event via sqlite3_log(). This is to help with identifying performance + ** problems caused by applications routinely shutting down without + ** checkpointing the log file. + */ + if( pWal->hdr.nPage ){ + sqlite3_log(SQLITE_NOTICE_RECOVER_WAL, + "recovered %d frames from WAL file %s", + pWal->hdr.mxFrame, pWal->zWalName + ); + } + } + +recovery_error: + WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok")); + walUnlockExclusive(pWal, iLock, nLock); + return rc; +} + +/* +** Close an open wal-index. +*/ +static void walIndexClose(Wal *pWal, int isDelete){ + if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ + int i; + for(i=0; inWiData; i++){ + sqlite3_free((void *)pWal->apWiData[i]); + pWal->apWiData[i] = 0; + } + }else{ + sqlite3OsShmUnmap(pWal->pDbFd, isDelete); + } +} + +/* +** Open a connection to the WAL file zWalName. The database file must +** already be opened on connection pDbFd. The buffer that zWalName points +** to must remain valid for the lifetime of the returned Wal* handle. +** +** A SHARED lock should be held on the database file when this function +** is called. The purpose of this SHARED lock is to prevent any other +** client from unlinking the WAL or wal-index file. If another process +** were to do this just after this client opened one of these files, the +** system would be badly broken. +** +** If the log file is successfully opened, SQLITE_OK is returned and +** *ppWal is set to point to a new WAL handle. If an error occurs, +** an SQLite error code is returned and *ppWal is left unmodified. +*/ +SQLITE_PRIVATE int sqlite3WalOpen( + sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */ + sqlite3_file *pDbFd, /* The open database file */ + const char *zWalName, /* Name of the WAL file */ + int bNoShm, /* True to run in heap-memory mode */ + i64 mxWalSize, /* Truncate WAL to this size on reset */ + Wal **ppWal /* OUT: Allocated Wal handle */ +){ + int rc; /* Return Code */ + Wal *pRet; /* Object to allocate and return */ + int flags; /* Flags passed to OsOpen() */ + + assert( zWalName && zWalName[0] ); + assert( pDbFd ); + + /* In the amalgamation, the os_unix.c and os_win.c source files come before + ** this source file. Verify that the #defines of the locking byte offsets + ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value. + */ +#ifdef WIN_SHM_BASE + assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET ); +#endif +#ifdef UNIX_SHM_BASE + assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET ); +#endif + + + /* Allocate an instance of struct Wal to return. */ + *ppWal = 0; + pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile); + if( !pRet ){ + return SQLITE_NOMEM; + } + + pRet->pVfs = pVfs; + pRet->pWalFd = (sqlite3_file *)&pRet[1]; + pRet->pDbFd = pDbFd; + pRet->readLock = -1; + pRet->mxWalSize = mxWalSize; + pRet->zWalName = zWalName; + pRet->syncHeader = 1; + pRet->padToSectorBoundary = 1; + pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE); + + /* Open file handle on the write-ahead log file. */ + flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL); + rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags); + if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){ + pRet->readOnly = WAL_RDONLY; + } + + if( rc!=SQLITE_OK ){ + walIndexClose(pRet, 0); + sqlite3OsClose(pRet->pWalFd); + sqlite3_free(pRet); + }else{ + int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd); + if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; } + if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){ + pRet->padToSectorBoundary = 0; + } + *ppWal = pRet; + WALTRACE(("WAL%d: opened\n", pRet)); + } + return rc; +} + +/* +** Change the size to which the WAL file is trucated on each reset. +*/ +SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){ + if( pWal ) pWal->mxWalSize = iLimit; +} + +/* +** Find the smallest page number out of all pages held in the WAL that +** has not been returned by any prior invocation of this method on the +** same WalIterator object. Write into *piFrame the frame index where +** that page was last written into the WAL. Write into *piPage the page +** number. +** +** Return 0 on success. If there are no pages in the WAL with a page +** number larger than *piPage, then return 1. +*/ +static int walIteratorNext( + WalIterator *p, /* Iterator */ + u32 *piPage, /* OUT: The page number of the next page */ + u32 *piFrame /* OUT: Wal frame index of next page */ +){ + u32 iMin; /* Result pgno must be greater than iMin */ + u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */ + int i; /* For looping through segments */ + + iMin = p->iPrior; + assert( iMin<0xffffffff ); + for(i=p->nSegment-1; i>=0; i--){ + struct WalSegment *pSegment = &p->aSegment[i]; + while( pSegment->iNextnEntry ){ + u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]]; + if( iPg>iMin ){ + if( iPgiZero + pSegment->aIndex[pSegment->iNext]; + } + break; + } + pSegment->iNext++; + } + } + + *piPage = p->iPrior = iRet; + return (iRet==0xFFFFFFFF); +} + +/* +** This function merges two sorted lists into a single sorted list. +** +** aLeft[] and aRight[] are arrays of indices. The sort key is +** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following +** is guaranteed for all J0 && nRight>0 ); + while( iRight=nRight || aContent[aLeft[iLeft]]=nLeft || aContent[aLeft[iLeft]]>dbpage ); + assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage ); + } + + *paRight = aLeft; + *pnRight = iOut; + memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut); +} + +/* +** Sort the elements in list aList using aContent[] as the sort key. +** Remove elements with duplicate keys, preferring to keep the +** larger aList[] values. +** +** The aList[] entries are indices into aContent[]. The values in +** aList[] are to be sorted so that for all J0 ); + assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) ); + + for(iList=0; iListaList && p->nList<=(1<aList==&aList[iList&~((2<aList, p->nList, &aMerge, &nMerge, aBuffer); + } + aSub[iSub].aList = aMerge; + aSub[iSub].nList = nMerge; + } + + for(iSub++; iSubnList<=(1<aList==&aList[nList&~((2<aList, p->nList, &aMerge, &nMerge, aBuffer); + } + } + assert( aMerge==aList ); + *pnList = nMerge; + +#ifdef SQLITE_DEBUG + { + int i; + for(i=1; i<*pnList; i++){ + assert( aContent[aList[i]] > aContent[aList[i-1]] ); + } + } +#endif +} + +/* +** Free an iterator allocated by walIteratorInit(). +*/ +static void walIteratorFree(WalIterator *p){ + sqlite3ScratchFree(p); +} + +/* +** Construct a WalInterator object that can be used to loop over all +** pages in the WAL in ascending order. The caller must hold the checkpoint +** lock. +** +** On success, make *pp point to the newly allocated WalInterator object +** return SQLITE_OK. Otherwise, return an error code. If this routine +** returns an error, the value of *pp is undefined. +** +** The calling routine should invoke walIteratorFree() to destroy the +** WalIterator object when it has finished with it. +*/ +static int walIteratorInit(Wal *pWal, WalIterator **pp){ + WalIterator *p; /* Return value */ + int nSegment; /* Number of segments to merge */ + u32 iLast; /* Last frame in log */ + int nByte; /* Number of bytes to allocate */ + int i; /* Iterator variable */ + ht_slot *aTmp; /* Temp space used by merge-sort */ + int rc = SQLITE_OK; /* Return Code */ + + /* This routine only runs while holding the checkpoint lock. And + ** it only runs if there is actually content in the log (mxFrame>0). + */ + assert( pWal->ckptLock && pWal->hdr.mxFrame>0 ); + iLast = pWal->hdr.mxFrame; + + /* Allocate space for the WalIterator object. */ + nSegment = walFramePage(iLast) + 1; + nByte = sizeof(WalIterator) + + (nSegment-1)*sizeof(struct WalSegment) + + iLast*sizeof(ht_slot); + p = (WalIterator *)sqlite3ScratchMalloc(nByte); + if( !p ){ + return SQLITE_NOMEM; + } + memset(p, 0, nByte); + p->nSegment = nSegment; + + /* Allocate temporary space used by the merge-sort routine. This block + ** of memory will be freed before this function returns. + */ + aTmp = (ht_slot *)sqlite3ScratchMalloc( + sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast) + ); + if( !aTmp ){ + rc = SQLITE_NOMEM; + } + + for(i=0; rc==SQLITE_OK && iaSegment[p->nSegment])[iZero]; + iZero++; + + for(j=0; jaSegment[i].iZero = iZero; + p->aSegment[i].nEntry = nEntry; + p->aSegment[i].aIndex = aIndex; + p->aSegment[i].aPgno = (u32 *)aPgno; + } + } + sqlite3ScratchFree(aTmp); + + if( rc!=SQLITE_OK ){ + walIteratorFree(p); + } + *pp = p; + return rc; +} + +/* +** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and +** n. If the attempt fails and parameter xBusy is not NULL, then it is a +** busy-handler function. Invoke it and retry the lock until either the +** lock is successfully obtained or the busy-handler returns 0. +*/ +static int walBusyLock( + Wal *pWal, /* WAL connection */ + int (*xBusy)(void*), /* Function to call when busy */ + void *pBusyArg, /* Context argument for xBusyHandler */ + int lockIdx, /* Offset of first byte to lock */ + int n /* Number of bytes to lock */ +){ + int rc; + do { + rc = walLockExclusive(pWal, lockIdx, n); + }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) ); + return rc; +} + +/* +** The cache of the wal-index header must be valid to call this function. +** Return the page-size in bytes used by the database. +*/ +static int walPagesize(Wal *pWal){ + return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); +} + +/* +** Copy as much content as we can from the WAL back into the database file +** in response to an sqlite3_wal_checkpoint() request or the equivalent. +** +** The amount of information copies from WAL to database might be limited +** by active readers. This routine will never overwrite a database page +** that a concurrent reader might be using. +** +** All I/O barrier operations (a.k.a fsyncs) occur in this routine when +** SQLite is in WAL-mode in synchronous=NORMAL. That means that if +** checkpoints are always run by a background thread or background +** process, foreground threads will never block on a lengthy fsync call. +** +** Fsync is called on the WAL before writing content out of the WAL and +** into the database. This ensures that if the new content is persistent +** in the WAL and can be recovered following a power-loss or hard reset. +** +** Fsync is also called on the database file if (and only if) the entire +** WAL content is copied into the database file. This second fsync makes +** it safe to delete the WAL since the new content will persist in the +** database file. +** +** This routine uses and updates the nBackfill field of the wal-index header. +** This is the only routine tha will increase the value of nBackfill. +** (A WAL reset or recovery will revert nBackfill to zero, but not increase +** its value.) +** +** The caller must be holding sufficient locks to ensure that no other +** checkpoint is running (in any other thread or process) at the same +** time. +*/ +static int walCheckpoint( + Wal *pWal, /* Wal connection */ + int eMode, /* One of PASSIVE, FULL or RESTART */ + int (*xBusyCall)(void*), /* Function to call when busy */ + void *pBusyArg, /* Context argument for xBusyHandler */ + int sync_flags, /* Flags for OsSync() (or 0) */ + u8 *zBuf /* Temporary buffer to use */ +){ + int rc; /* Return code */ + int szPage; /* Database page-size */ + WalIterator *pIter = 0; /* Wal iterator context */ + u32 iDbpage = 0; /* Next database page to write */ + u32 iFrame = 0; /* Wal frame containing data for iDbpage */ + u32 mxSafeFrame; /* Max frame that can be backfilled */ + u32 mxPage; /* Max database page to write */ + int i; /* Loop counter */ + volatile WalCkptInfo *pInfo; /* The checkpoint status information */ + int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */ + + szPage = walPagesize(pWal); + testcase( szPage<=32768 ); + testcase( szPage>=65536 ); + pInfo = walCkptInfo(pWal); + if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK; + + /* Allocate the iterator */ + rc = walIteratorInit(pWal, &pIter); + if( rc!=SQLITE_OK ){ + return rc; + } + assert( pIter ); + + if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall; + + /* Compute in mxSafeFrame the index of the last frame of the WAL that is + ** safe to write into the database. Frames beyond mxSafeFrame might + ** overwrite database pages that are in use by active readers and thus + ** cannot be backfilled from the WAL. + */ + mxSafeFrame = pWal->hdr.mxFrame; + mxPage = pWal->hdr.nPage; + for(i=1; iaReadMark[i]; + if( mxSafeFrame>y ){ + assert( y<=pWal->hdr.mxFrame ); + rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1); + if( rc==SQLITE_OK ){ + pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED); + walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); + }else if( rc==SQLITE_BUSY ){ + mxSafeFrame = y; + xBusy = 0; + }else{ + goto walcheckpoint_out; + } + } + } + + if( pInfo->nBackfillnBackfill; + + /* Sync the WAL to disk */ + if( sync_flags ){ + rc = sqlite3OsSync(pWal->pWalFd, sync_flags); + } + + /* If the database may grow as a result of this checkpoint, hint + ** about the eventual size of the db file to the VFS layer. + */ + if( rc==SQLITE_OK ){ + i64 nReq = ((i64)mxPage * szPage); + rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); + if( rc==SQLITE_OK && nSizepDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq); + } + } + + + /* Iterate through the contents of the WAL, copying data to the db file. */ + while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){ + i64 iOffset; + assert( walFramePgno(pWal, iFrame)==iDbpage ); + if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue; + iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE; + /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */ + rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); + if( rc!=SQLITE_OK ) break; + iOffset = (iDbpage-1)*(i64)szPage; + testcase( IS_BIG_INT(iOffset) ); + rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); + if( rc!=SQLITE_OK ) break; + } + + /* If work was actually accomplished... */ + if( rc==SQLITE_OK ){ + if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){ + i64 szDb = pWal->hdr.nPage*(i64)szPage; + testcase( IS_BIG_INT(szDb) ); + rc = sqlite3OsTruncate(pWal->pDbFd, szDb); + if( rc==SQLITE_OK && sync_flags ){ + rc = sqlite3OsSync(pWal->pDbFd, sync_flags); + } + } + if( rc==SQLITE_OK ){ + pInfo->nBackfill = mxSafeFrame; + } + } + + /* Release the reader lock held while backfilling */ + walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1); + } + + if( rc==SQLITE_BUSY ){ + /* Reset the return code so as not to report a checkpoint failure + ** just because there are active readers. */ + rc = SQLITE_OK; + } + + /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal + ** file has been copied into the database file, then block until all + ** readers have finished using the wal file. This ensures that the next + ** process to write to the database restarts the wal file. + */ + if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){ + assert( pWal->writeLock ); + if( pInfo->nBackfillhdr.mxFrame ){ + rc = SQLITE_BUSY; + }else if( eMode==SQLITE_CHECKPOINT_RESTART ){ + assert( mxSafeFrame==pWal->hdr.mxFrame ); + rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1); + if( rc==SQLITE_OK ){ + walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); + } + } + } + + walcheckpoint_out: + walIteratorFree(pIter); + return rc; +} + +/* +** If the WAL file is currently larger than nMax bytes in size, truncate +** it to exactly nMax bytes. If an error occurs while doing so, ignore it. +*/ +static void walLimitSize(Wal *pWal, i64 nMax){ + i64 sz; + int rx; + sqlite3BeginBenignMalloc(); + rx = sqlite3OsFileSize(pWal->pWalFd, &sz); + if( rx==SQLITE_OK && (sz > nMax ) ){ + rx = sqlite3OsTruncate(pWal->pWalFd, nMax); + } + sqlite3EndBenignMalloc(); + if( rx ){ + sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName); + } +} + +/* +** Close a connection to a log file. +*/ +SQLITE_PRIVATE int sqlite3WalClose( + Wal *pWal, /* Wal to close */ + int sync_flags, /* Flags to pass to OsSync() (or 0) */ + int nBuf, + u8 *zBuf /* Buffer of at least nBuf bytes */ +){ + int rc = SQLITE_OK; + if( pWal ){ + int isDelete = 0; /* True to unlink wal and wal-index files */ + + /* If an EXCLUSIVE lock can be obtained on the database file (using the + ** ordinary, rollback-mode locking methods, this guarantees that the + ** connection associated with this log file is the only connection to + ** the database. In this case checkpoint the database and unlink both + ** the wal and wal-index files. + ** + ** The EXCLUSIVE lock is not released before returning. + */ + rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE); + if( rc==SQLITE_OK ){ + if( pWal->exclusiveMode==WAL_NORMAL_MODE ){ + pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; + } + rc = sqlite3WalCheckpoint( + pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0 + ); + if( rc==SQLITE_OK ){ + int bPersist = -1; + sqlite3OsFileControlHint( + pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist + ); + if( bPersist!=1 ){ + /* Try to delete the WAL file if the checkpoint completed and + ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal + ** mode (!bPersist) */ + isDelete = 1; + }else if( pWal->mxWalSize>=0 ){ + /* Try to truncate the WAL file to zero bytes if the checkpoint + ** completed and fsynced (rc==SQLITE_OK) and we are in persistent + ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a + ** non-negative value (pWal->mxWalSize>=0). Note that we truncate + ** to zero bytes as truncating to the journal_size_limit might + ** leave a corrupt WAL file on disk. */ + walLimitSize(pWal, 0); + } + } + } + + walIndexClose(pWal, isDelete); + sqlite3OsClose(pWal->pWalFd); + if( isDelete ){ + sqlite3BeginBenignMalloc(); + sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0); + sqlite3EndBenignMalloc(); + } + WALTRACE(("WAL%p: closed\n", pWal)); + sqlite3_free((void *)pWal->apWiData); + sqlite3_free(pWal); + } + return rc; +} + +/* +** Try to read the wal-index header. Return 0 on success and 1 if +** there is a problem. +** +** The wal-index is in shared memory. Another thread or process might +** be writing the header at the same time this procedure is trying to +** read it, which might result in inconsistency. A dirty read is detected +** by verifying that both copies of the header are the same and also by +** a checksum on the header. +** +** If and only if the read is consistent and the header is different from +** pWal->hdr, then pWal->hdr is updated to the content of the new header +** and *pChanged is set to 1. +** +** If the checksum cannot be verified return non-zero. If the header +** is read successfully and the checksum verified, return zero. +*/ +static int walIndexTryHdr(Wal *pWal, int *pChanged){ + u32 aCksum[2]; /* Checksum on the header content */ + WalIndexHdr h1, h2; /* Two copies of the header content */ + WalIndexHdr volatile *aHdr; /* Header in shared memory */ + + /* The first page of the wal-index must be mapped at this point. */ + assert( pWal->nWiData>0 && pWal->apWiData[0] ); + + /* Read the header. This might happen concurrently with a write to the + ** same area of shared memory on a different CPU in a SMP, + ** meaning it is possible that an inconsistent snapshot is read + ** from the file. If this happens, return non-zero. + ** + ** There are two copies of the header at the beginning of the wal-index. + ** When reading, read [0] first then [1]. Writes are in the reverse order. + ** Memory barriers are used to prevent the compiler or the hardware from + ** reordering the reads and writes. + */ + aHdr = walIndexHdr(pWal); + memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); + walShmBarrier(pWal); + memcpy(&h2, (void *)&aHdr[1], sizeof(h2)); + + if( memcmp(&h1, &h2, sizeof(h1))!=0 ){ + return 1; /* Dirty read */ + } + if( h1.isInit==0 ){ + return 1; /* Malformed header - probably all zeros */ + } + walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum); + if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){ + return 1; /* Checksum does not match */ + } + + if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){ + *pChanged = 1; + memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr)); + pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); + testcase( pWal->szPage<=32768 ); + testcase( pWal->szPage>=65536 ); + } + + /* The header was successfully read. Return zero. */ + return 0; +} + +/* +** Read the wal-index header from the wal-index and into pWal->hdr. +** If the wal-header appears to be corrupt, try to reconstruct the +** wal-index from the WAL before returning. +** +** Set *pChanged to 1 if the wal-index header value in pWal->hdr is +** changed by this opertion. If pWal->hdr is unchanged, set *pChanged +** to 0. +** +** If the wal-index header is successfully read, return SQLITE_OK. +** Otherwise an SQLite error code. +*/ +static int walIndexReadHdr(Wal *pWal, int *pChanged){ + int rc; /* Return code */ + int badHdr; /* True if a header read failed */ + volatile u32 *page0; /* Chunk of wal-index containing header */ + + /* Ensure that page 0 of the wal-index (the page that contains the + ** wal-index header) is mapped. Return early if an error occurs here. + */ + assert( pChanged ); + rc = walIndexPage(pWal, 0, &page0); + if( rc!=SQLITE_OK ){ + return rc; + }; + assert( page0 || pWal->writeLock==0 ); + + /* If the first page of the wal-index has been mapped, try to read the + ** wal-index header immediately, without holding any lock. This usually + ** works, but may fail if the wal-index header is corrupt or currently + ** being modified by another thread or process. + */ + badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1); + + /* If the first attempt failed, it might have been due to a race + ** with a writer. So get a WRITE lock and try again. + */ + assert( badHdr==0 || pWal->writeLock==0 ); + if( badHdr ){ + if( pWal->readOnly & WAL_SHM_RDONLY ){ + if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){ + walUnlockShared(pWal, WAL_WRITE_LOCK); + rc = SQLITE_READONLY_RECOVERY; + } + }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){ + pWal->writeLock = 1; + if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){ + badHdr = walIndexTryHdr(pWal, pChanged); + if( badHdr ){ + /* If the wal-index header is still malformed even while holding + ** a WRITE lock, it can only mean that the header is corrupted and + ** needs to be reconstructed. So run recovery to do exactly that. + */ + rc = walIndexRecover(pWal); + *pChanged = 1; + } + } + pWal->writeLock = 0; + walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); + } + } + + /* If the header is read successfully, check the version number to make + ** sure the wal-index was not constructed with some future format that + ** this version of SQLite cannot understand. + */ + if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){ + rc = SQLITE_CANTOPEN_BKPT; + } + + return rc; +} + +/* +** This is the value that walTryBeginRead returns when it needs to +** be retried. +*/ +#define WAL_RETRY (-1) + +/* +** Attempt to start a read transaction. This might fail due to a race or +** other transient condition. When that happens, it returns WAL_RETRY to +** indicate to the caller that it is safe to retry immediately. +** +** On success return SQLITE_OK. On a permanent failure (such an +** I/O error or an SQLITE_BUSY because another process is running +** recovery) return a positive error code. +** +** The useWal parameter is true to force the use of the WAL and disable +** the case where the WAL is bypassed because it has been completely +** checkpointed. If useWal==0 then this routine calls walIndexReadHdr() +** to make a copy of the wal-index header into pWal->hdr. If the +** wal-index header has changed, *pChanged is set to 1 (as an indication +** to the caller that the local paget cache is obsolete and needs to be +** flushed.) When useWal==1, the wal-index header is assumed to already +** be loaded and the pChanged parameter is unused. +** +** The caller must set the cnt parameter to the number of prior calls to +** this routine during the current read attempt that returned WAL_RETRY. +** This routine will start taking more aggressive measures to clear the +** race conditions after multiple WAL_RETRY returns, and after an excessive +** number of errors will ultimately return SQLITE_PROTOCOL. The +** SQLITE_PROTOCOL return indicates that some other process has gone rogue +** and is not honoring the locking protocol. There is a vanishingly small +** chance that SQLITE_PROTOCOL could be returned because of a run of really +** bad luck when there is lots of contention for the wal-index, but that +** possibility is so small that it can be safely neglected, we believe. +** +** On success, this routine obtains a read lock on +** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is +** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1) +** that means the Wal does not hold any read lock. The reader must not +** access any database page that is modified by a WAL frame up to and +** including frame number aReadMark[pWal->readLock]. The reader will +** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0 +** Or if pWal->readLock==0, then the reader will ignore the WAL +** completely and get all content directly from the database file. +** If the useWal parameter is 1 then the WAL will never be ignored and +** this routine will always set pWal->readLock>0 on success. +** When the read transaction is completed, the caller must release the +** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1. +** +** This routine uses the nBackfill and aReadMark[] fields of the header +** to select a particular WAL_READ_LOCK() that strives to let the +** checkpoint process do as much work as possible. This routine might +** update values of the aReadMark[] array in the header, but if it does +** so it takes care to hold an exclusive lock on the corresponding +** WAL_READ_LOCK() while changing values. +*/ +static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ + volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */ + u32 mxReadMark; /* Largest aReadMark[] value */ + int mxI; /* Index of largest aReadMark[] value */ + int i; /* Loop counter */ + int rc = SQLITE_OK; /* Return code */ + + assert( pWal->readLock<0 ); /* Not currently locked */ + + /* Take steps to avoid spinning forever if there is a protocol error. + ** + ** Circumstances that cause a RETRY should only last for the briefest + ** instances of time. No I/O or other system calls are done while the + ** locks are held, so the locks should not be held for very long. But + ** if we are unlucky, another process that is holding a lock might get + ** paged out or take a page-fault that is time-consuming to resolve, + ** during the few nanoseconds that it is holding the lock. In that case, + ** it might take longer than normal for the lock to free. + ** + ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few + ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this + ** is more of a scheduler yield than an actual delay. But on the 10th + ** an subsequent retries, the delays start becoming longer and longer, + ** so that on the 100th (and last) RETRY we delay for 21 milliseconds. + ** The total delay time before giving up is less than 1 second. + */ + if( cnt>5 ){ + int nDelay = 1; /* Pause time in microseconds */ + if( cnt>100 ){ + VVA_ONLY( pWal->lockError = 1; ) + return SQLITE_PROTOCOL; + } + if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */ + sqlite3OsSleep(pWal->pVfs, nDelay); + } + + if( !useWal ){ + rc = walIndexReadHdr(pWal, pChanged); + if( rc==SQLITE_BUSY ){ + /* If there is not a recovery running in another thread or process + ** then convert BUSY errors to WAL_RETRY. If recovery is known to + ** be running, convert BUSY to BUSY_RECOVERY. There is a race here + ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY + ** would be technically correct. But the race is benign since with + ** WAL_RETRY this routine will be called again and will probably be + ** right on the second iteration. + */ + if( pWal->apWiData[0]==0 ){ + /* This branch is taken when the xShmMap() method returns SQLITE_BUSY. + ** We assume this is a transient condition, so return WAL_RETRY. The + ** xShmMap() implementation used by the default unix and win32 VFS + ** modules may return SQLITE_BUSY due to a race condition in the + ** code that determines whether or not the shared-memory region + ** must be zeroed before the requested page is returned. + */ + rc = WAL_RETRY; + }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){ + walUnlockShared(pWal, WAL_RECOVER_LOCK); + rc = WAL_RETRY; + }else if( rc==SQLITE_BUSY ){ + rc = SQLITE_BUSY_RECOVERY; + } + } + if( rc!=SQLITE_OK ){ + return rc; + } + } + + pInfo = walCkptInfo(pWal); + if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){ + /* The WAL has been completely backfilled (or it is empty). + ** and can be safely ignored. + */ + rc = walLockShared(pWal, WAL_READ_LOCK(0)); + walShmBarrier(pWal); + if( rc==SQLITE_OK ){ + if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){ + /* It is not safe to allow the reader to continue here if frames + ** may have been appended to the log before READ_LOCK(0) was obtained. + ** When holding READ_LOCK(0), the reader ignores the entire log file, + ** which implies that the database file contains a trustworthy + ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from + ** happening, this is usually correct. + ** + ** However, if frames have been appended to the log (or if the log + ** is wrapped and written for that matter) before the READ_LOCK(0) + ** is obtained, that is not necessarily true. A checkpointer may + ** have started to backfill the appended frames but crashed before + ** it finished. Leaving a corrupt image in the database file. + */ + walUnlockShared(pWal, WAL_READ_LOCK(0)); + return WAL_RETRY; + } + pWal->readLock = 0; + return SQLITE_OK; + }else if( rc!=SQLITE_BUSY ){ + return rc; + } + } + + /* If we get this far, it means that the reader will want to use + ** the WAL to get at content from recent commits. The job now is + ** to select one of the aReadMark[] entries that is closest to + ** but not exceeding pWal->hdr.mxFrame and lock that entry. + */ + mxReadMark = 0; + mxI = 0; + for(i=1; iaReadMark[i]; + if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){ + assert( thisMark!=READMARK_NOT_USED ); + mxReadMark = thisMark; + mxI = i; + } + } + /* There was once an "if" here. The extra "{" is to preserve indentation. */ + { + if( (pWal->readOnly & WAL_SHM_RDONLY)==0 + && (mxReadMarkhdr.mxFrame || mxI==0) + ){ + for(i=1; iaReadMark[i] = pWal->hdr.mxFrame; + mxI = i; + walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); + break; + }else if( rc!=SQLITE_BUSY ){ + return rc; + } + } + } + if( mxI==0 ){ + assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 ); + return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK; + } + + rc = walLockShared(pWal, WAL_READ_LOCK(mxI)); + if( rc ){ + return rc==SQLITE_BUSY ? WAL_RETRY : rc; + } + /* Now that the read-lock has been obtained, check that neither the + ** value in the aReadMark[] array or the contents of the wal-index + ** header have changed. + ** + ** It is necessary to check that the wal-index header did not change + ** between the time it was read and when the shared-lock was obtained + ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility + ** that the log file may have been wrapped by a writer, or that frames + ** that occur later in the log than pWal->hdr.mxFrame may have been + ** copied into the database by a checkpointer. If either of these things + ** happened, then reading the database with the current value of + ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry + ** instead. + ** + ** This does not guarantee that the copy of the wal-index header is up to + ** date before proceeding. That would not be possible without somehow + ** blocking writers. It only guarantees that a dangerous checkpoint or + ** log-wrap (either of which would require an exclusive lock on + ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid. + */ + walShmBarrier(pWal); + if( pInfo->aReadMark[mxI]!=mxReadMark + || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) + ){ + walUnlockShared(pWal, WAL_READ_LOCK(mxI)); + return WAL_RETRY; + }else{ + assert( mxReadMark<=pWal->hdr.mxFrame ); + pWal->readLock = (i16)mxI; + } + } + return rc; +} + +/* +** Begin a read transaction on the database. +** +** This routine used to be called sqlite3OpenSnapshot() and with good reason: +** it takes a snapshot of the state of the WAL and wal-index for the current +** instant in time. The current thread will continue to use this snapshot. +** Other threads might append new content to the WAL and wal-index but +** that extra content is ignored by the current thread. +** +** If the database contents have changes since the previous read +** transaction, then *pChanged is set to 1 before returning. The +** Pager layer will use this to know that is cache is stale and +** needs to be flushed. +*/ +SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ + int rc; /* Return code */ + int cnt = 0; /* Number of TryBeginRead attempts */ + + do{ + rc = walTryBeginRead(pWal, pChanged, 0, ++cnt); + }while( rc==WAL_RETRY ); + testcase( (rc&0xff)==SQLITE_BUSY ); + testcase( (rc&0xff)==SQLITE_IOERR ); + testcase( rc==SQLITE_PROTOCOL ); + testcase( rc==SQLITE_OK ); + return rc; +} + +/* +** Finish with a read transaction. All this does is release the +** read-lock. +*/ +SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){ + sqlite3WalEndWriteTransaction(pWal); + if( pWal->readLock>=0 ){ + walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); + pWal->readLock = -1; + } +} + +/* +** Search the wal file for page pgno. If found, set *piRead to the frame that +** contains the page. Otherwise, if pgno is not in the wal file, set *piRead +** to zero. +** +** Return SQLITE_OK if successful, or an error code if an error occurs. If an +** error does occur, the final value of *piRead is undefined. +*/ +SQLITE_PRIVATE int sqlite3WalFindFrame( + Wal *pWal, /* WAL handle */ + Pgno pgno, /* Database page number to read data for */ + u32 *piRead /* OUT: Frame number (or zero) */ +){ + u32 iRead = 0; /* If !=0, WAL frame to return data from */ + u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */ + int iHash; /* Used to loop through N hash tables */ + + /* This routine is only be called from within a read transaction. */ + assert( pWal->readLock>=0 || pWal->lockError ); + + /* If the "last page" field of the wal-index header snapshot is 0, then + ** no data will be read from the wal under any circumstances. Return early + ** in this case as an optimization. Likewise, if pWal->readLock==0, + ** then the WAL is ignored by the reader so return early, as if the + ** WAL were empty. + */ + if( iLast==0 || pWal->readLock==0 ){ + *piRead = 0; + return SQLITE_OK; + } + + /* Search the hash table or tables for an entry matching page number + ** pgno. Each iteration of the following for() loop searches one + ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames). + ** + ** This code might run concurrently to the code in walIndexAppend() + ** that adds entries to the wal-index (and possibly to this hash + ** table). This means the value just read from the hash + ** slot (aHash[iKey]) may have been added before or after the + ** current read transaction was opened. Values added after the + ** read transaction was opened may have been written incorrectly - + ** i.e. these slots may contain garbage data. However, we assume + ** that any slots written before the current read transaction was + ** opened remain unmodified. + ** + ** For the reasons above, the if(...) condition featured in the inner + ** loop of the following block is more stringent that would be required + ** if we had exclusive access to the hash-table: + ** + ** (aPgno[iFrame]==pgno): + ** This condition filters out normal hash-table collisions. + ** + ** (iFrame<=iLast): + ** This condition filters out entries that were added to the hash + ** table after the current read-transaction had started. + */ + for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){ + volatile ht_slot *aHash; /* Pointer to hash table */ + volatile u32 *aPgno; /* Pointer to array of page numbers */ + u32 iZero; /* Frame number corresponding to aPgno[0] */ + int iKey; /* Hash slot index */ + int nCollide; /* Number of hash collisions remaining */ + int rc; /* Error code */ + + rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero); + if( rc!=SQLITE_OK ){ + return rc; + } + nCollide = HASHTABLE_NSLOT; + for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){ + u32 iFrame = aHash[iKey] + iZero; + if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){ + /* assert( iFrame>iRead ); -- not true if there is corruption */ + iRead = iFrame; + } + if( (nCollide--)==0 ){ + return SQLITE_CORRUPT_BKPT; + } + } + } + +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT + /* If expensive assert() statements are available, do a linear search + ** of the wal-index file content. Make sure the results agree with the + ** result obtained using the hash indexes above. */ + { + u32 iRead2 = 0; + u32 iTest; + for(iTest=iLast; iTest>0; iTest--){ + if( walFramePgno(pWal, iTest)==pgno ){ + iRead2 = iTest; + break; + } + } + assert( iRead==iRead2 ); + } +#endif + + *piRead = iRead; + return SQLITE_OK; +} + +/* +** Read the contents of frame iRead from the wal file into buffer pOut +** (which is nOut bytes in size). Return SQLITE_OK if successful, or an +** error code otherwise. +*/ +SQLITE_PRIVATE int sqlite3WalReadFrame( + Wal *pWal, /* WAL handle */ + u32 iRead, /* Frame to read */ + int nOut, /* Size of buffer pOut in bytes */ + u8 *pOut /* Buffer to write page data to */ +){ + int sz; + i64 iOffset; + sz = pWal->hdr.szPage; + sz = (sz&0xfe00) + ((sz&0x0001)<<16); + testcase( sz<=32768 ); + testcase( sz>=65536 ); + iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE; + /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */ + return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset); +} + +/* +** Return the size of the database in pages (or zero, if unknown). +*/ +SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){ + if( pWal && ALWAYS(pWal->readLock>=0) ){ + return pWal->hdr.nPage; + } + return 0; +} + + +/* +** This function starts a write transaction on the WAL. +** +** A read transaction must have already been started by a prior call +** to sqlite3WalBeginReadTransaction(). +** +** If another thread or process has written into the database since +** the read transaction was started, then it is not possible for this +** thread to write as doing so would cause a fork. So this routine +** returns SQLITE_BUSY in that case and no write transaction is started. +** +** There can only be a single writer active at a time. +*/ +SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){ + int rc; + + /* Cannot start a write transaction without first holding a read + ** transaction. */ + assert( pWal->readLock>=0 ); + + if( pWal->readOnly ){ + return SQLITE_READONLY; + } + + /* Only one writer allowed at a time. Get the write lock. Return + ** SQLITE_BUSY if unable. + */ + rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1); + if( rc ){ + return rc; + } + pWal->writeLock = 1; + + /* If another connection has written to the database file since the + ** time the read transaction on this connection was started, then + ** the write is disallowed. + */ + if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){ + walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); + pWal->writeLock = 0; + rc = SQLITE_BUSY_SNAPSHOT; + } + + return rc; +} + +/* +** End a write transaction. The commit has already been done. This +** routine merely releases the lock. +*/ +SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){ + if( pWal->writeLock ){ + walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); + pWal->writeLock = 0; + pWal->truncateOnCommit = 0; + } + return SQLITE_OK; +} + +/* +** If any data has been written (but not committed) to the log file, this +** function moves the write-pointer back to the start of the transaction. +** +** Additionally, the callback function is invoked for each frame written +** to the WAL since the start of the transaction. If the callback returns +** other than SQLITE_OK, it is not invoked again and the error code is +** returned to the caller. +** +** Otherwise, if the callback function does not return an error, this +** function returns SQLITE_OK. +*/ +SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){ + int rc = SQLITE_OK; + if( ALWAYS(pWal->writeLock) ){ + Pgno iMax = pWal->hdr.mxFrame; + Pgno iFrame; + + /* Restore the clients cache of the wal-index header to the state it + ** was in before the client began writing to the database. + */ + memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr)); + + for(iFrame=pWal->hdr.mxFrame+1; + ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; + iFrame++ + ){ + /* This call cannot fail. Unless the page for which the page number + ** is passed as the second argument is (a) in the cache and + ** (b) has an outstanding reference, then xUndo is either a no-op + ** (if (a) is false) or simply expels the page from the cache (if (b) + ** is false). + ** + ** If the upper layer is doing a rollback, it is guaranteed that there + ** are no outstanding references to any page other than page 1. And + ** page 1 is never written to the log until the transaction is + ** committed. As a result, the call to xUndo may not fail. + */ + assert( walFramePgno(pWal, iFrame)!=1 ); + rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame)); + } + if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal); + } + assert( rc==SQLITE_OK ); + return rc; +} + +/* +** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 +** values. This function populates the array with values required to +** "rollback" the write position of the WAL handle back to the current +** point in the event of a savepoint rollback (via WalSavepointUndo()). +*/ +SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){ + assert( pWal->writeLock ); + aWalData[0] = pWal->hdr.mxFrame; + aWalData[1] = pWal->hdr.aFrameCksum[0]; + aWalData[2] = pWal->hdr.aFrameCksum[1]; + aWalData[3] = pWal->nCkpt; +} + +/* +** Move the write position of the WAL back to the point identified by +** the values in the aWalData[] array. aWalData must point to an array +** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated +** by a call to WalSavepoint(). +*/ +SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ + int rc = SQLITE_OK; + + assert( pWal->writeLock ); + assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame ); + + if( aWalData[3]!=pWal->nCkpt ){ + /* This savepoint was opened immediately after the write-transaction + ** was started. Right after that, the writer decided to wrap around + ** to the start of the log. Update the savepoint values to match. + */ + aWalData[0] = 0; + aWalData[3] = pWal->nCkpt; + } + + if( aWalData[0]hdr.mxFrame ){ + pWal->hdr.mxFrame = aWalData[0]; + pWal->hdr.aFrameCksum[0] = aWalData[1]; + pWal->hdr.aFrameCksum[1] = aWalData[2]; + walCleanupHash(pWal); + } + + return rc; +} + + +/* +** This function is called just before writing a set of frames to the log +** file (see sqlite3WalFrames()). It checks to see if, instead of appending +** to the current log file, it is possible to overwrite the start of the +** existing log file with the new frames (i.e. "reset" the log). If so, +** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left +** unchanged. +** +** SQLITE_OK is returned if no error is encountered (regardless of whether +** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned +** if an error occurs. +*/ +static int walRestartLog(Wal *pWal){ + int rc = SQLITE_OK; + int cnt; + + if( pWal->readLock==0 ){ + volatile WalCkptInfo *pInfo = walCkptInfo(pWal); + assert( pInfo->nBackfill==pWal->hdr.mxFrame ); + if( pInfo->nBackfill>0 ){ + u32 salt1; + sqlite3_randomness(4, &salt1); + rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); + if( rc==SQLITE_OK ){ + /* If all readers are using WAL_READ_LOCK(0) (in other words if no + ** readers are currently using the WAL), then the transactions + ** frames will overwrite the start of the existing log. Update the + ** wal-index header to reflect this. + ** + ** In theory it would be Ok to update the cache of the header only + ** at this point. But updating the actual wal-index header is also + ** safe and means there is no special case for sqlite3WalUndo() + ** to handle if this transaction is rolled back. + */ + int i; /* Loop counter */ + u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */ + + pWal->nCkpt++; + pWal->hdr.mxFrame = 0; + sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0])); + aSalt[1] = salt1; + walIndexWriteHdr(pWal); + pInfo->nBackfill = 0; + pInfo->aReadMark[1] = 0; + for(i=2; iaReadMark[i] = READMARK_NOT_USED; + assert( pInfo->aReadMark[0]==0 ); + walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); + }else if( rc!=SQLITE_BUSY ){ + return rc; + } + } + walUnlockShared(pWal, WAL_READ_LOCK(0)); + pWal->readLock = -1; + cnt = 0; + do{ + int notUsed; + rc = walTryBeginRead(pWal, ¬Used, 1, ++cnt); + }while( rc==WAL_RETRY ); + assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */ + testcase( (rc&0xff)==SQLITE_IOERR ); + testcase( rc==SQLITE_PROTOCOL ); + testcase( rc==SQLITE_OK ); + } + return rc; +} + +/* +** Information about the current state of the WAL file and where +** the next fsync should occur - passed from sqlite3WalFrames() into +** walWriteToLog(). +*/ +typedef struct WalWriter { + Wal *pWal; /* The complete WAL information */ + sqlite3_file *pFd; /* The WAL file to which we write */ + sqlite3_int64 iSyncPoint; /* Fsync at this offset */ + int syncFlags; /* Flags for the fsync */ + int szPage; /* Size of one page */ +} WalWriter; + +/* +** Write iAmt bytes of content into the WAL file beginning at iOffset. +** Do a sync when crossing the p->iSyncPoint boundary. +** +** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt, +** first write the part before iSyncPoint, then sync, then write the +** rest. +*/ +static int walWriteToLog( + WalWriter *p, /* WAL to write to */ + void *pContent, /* Content to be written */ + int iAmt, /* Number of bytes to write */ + sqlite3_int64 iOffset /* Start writing at this offset */ +){ + int rc; + if( iOffsetiSyncPoint && iOffset+iAmt>=p->iSyncPoint ){ + int iFirstAmt = (int)(p->iSyncPoint - iOffset); + rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset); + if( rc ) return rc; + iOffset += iFirstAmt; + iAmt -= iFirstAmt; + pContent = (void*)(iFirstAmt + (char*)pContent); + assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) ); + rc = sqlite3OsSync(p->pFd, p->syncFlags); + if( iAmt==0 || rc ) return rc; + } + rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset); + return rc; +} + +/* +** Write out a single frame of the WAL +*/ +static int walWriteOneFrame( + WalWriter *p, /* Where to write the frame */ + PgHdr *pPage, /* The page of the frame to be written */ + int nTruncate, /* The commit flag. Usually 0. >0 for commit */ + sqlite3_int64 iOffset /* Byte offset at which to write */ +){ + int rc; /* Result code from subfunctions */ + void *pData; /* Data actually written */ + u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */ +#if defined(SQLITE_HAS_CODEC) + if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM; +#else + pData = pPage->pData; +#endif + walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame); + rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset); + if( rc ) return rc; + /* Write the page data */ + rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame)); + return rc; +} + +/* +** Write a set of frames to the log. The caller must hold the write-lock +** on the log file (obtained using sqlite3WalBeginWriteTransaction()). +*/ +SQLITE_PRIVATE int sqlite3WalFrames( + Wal *pWal, /* Wal handle to write to */ + int szPage, /* Database page-size in bytes */ + PgHdr *pList, /* List of dirty pages to write */ + Pgno nTruncate, /* Database size after this commit */ + int isCommit, /* True if this is a commit */ + int sync_flags /* Flags to pass to OsSync() (or 0) */ +){ + int rc; /* Used to catch return codes */ + u32 iFrame; /* Next frame address */ + PgHdr *p; /* Iterator to run through pList with. */ + PgHdr *pLast = 0; /* Last frame in list */ + int nExtra = 0; /* Number of extra copies of last page */ + int szFrame; /* The size of a single frame */ + i64 iOffset; /* Next byte to write in WAL file */ + WalWriter w; /* The writer */ + + assert( pList ); + assert( pWal->writeLock ); + + /* If this frame set completes a transaction, then nTruncate>0. If + ** nTruncate==0 then this frame set does not complete the transaction. */ + assert( (isCommit!=0)==(nTruncate!=0) ); + +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) + { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){} + WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n", + pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill")); + } +#endif + + /* See if it is possible to write these frames into the start of the + ** log file, instead of appending to it at pWal->hdr.mxFrame. + */ + if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){ + return rc; + } + + /* If this is the first frame written into the log, write the WAL + ** header to the start of the WAL file. See comments at the top of + ** this source file for a description of the WAL header format. + */ + iFrame = pWal->hdr.mxFrame; + if( iFrame==0 ){ + u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */ + u32 aCksum[2]; /* Checksum for wal-header */ + + sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN)); + sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION); + sqlite3Put4byte(&aWalHdr[8], szPage); + sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt); + if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt); + memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8); + walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum); + sqlite3Put4byte(&aWalHdr[24], aCksum[0]); + sqlite3Put4byte(&aWalHdr[28], aCksum[1]); + + pWal->szPage = szPage; + pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN; + pWal->hdr.aFrameCksum[0] = aCksum[0]; + pWal->hdr.aFrameCksum[1] = aCksum[1]; + pWal->truncateOnCommit = 1; + + rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0); + WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok")); + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless + ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise + ** an out-of-order write following a WAL restart could result in + ** database corruption. See the ticket: + ** + ** http://localhost:591/sqlite/info/ff5be73dee + */ + if( pWal->syncHeader && sync_flags ){ + rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK); + if( rc ) return rc; + } + } + assert( (int)pWal->szPage==szPage ); + + /* Setup information needed to write frames into the WAL */ + w.pWal = pWal; + w.pFd = pWal->pWalFd; + w.iSyncPoint = 0; + w.syncFlags = sync_flags; + w.szPage = szPage; + iOffset = walFrameOffset(iFrame+1, szPage); + szFrame = szPage + WAL_FRAME_HDRSIZE; + + /* Write all frames into the log file exactly once */ + for(p=pList; p; p=p->pDirty){ + int nDbSize; /* 0 normally. Positive == commit flag */ + iFrame++; + assert( iOffset==walFrameOffset(iFrame, szPage) ); + nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0; + rc = walWriteOneFrame(&w, p, nDbSize, iOffset); + if( rc ) return rc; + pLast = p; + iOffset += szFrame; + } + + /* If this is the end of a transaction, then we might need to pad + ** the transaction and/or sync the WAL file. + ** + ** Padding and syncing only occur if this set of frames complete a + ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL + ** or synchonous==OFF, then no padding or syncing are needed. + ** + ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not + ** needed and only the sync is done. If padding is needed, then the + ** final frame is repeated (with its commit mark) until the next sector + ** boundary is crossed. Only the part of the WAL prior to the last + ** sector boundary is synced; the part of the last frame that extends + ** past the sector boundary is written after the sync. + */ + if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){ + if( pWal->padToSectorBoundary ){ + int sectorSize = sqlite3SectorSize(pWal->pWalFd); + w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize; + while( iOffsettruncateOnCommit && pWal->mxWalSize>=0 ){ + i64 sz = pWal->mxWalSize; + if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){ + sz = walFrameOffset(iFrame+nExtra+1, szPage); + } + walLimitSize(pWal, sz); + pWal->truncateOnCommit = 0; + } + + /* Append data to the wal-index. It is not necessary to lock the + ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index + ** guarantees that there are no other writers, and no data that may + ** be in use by existing readers is being overwritten. + */ + iFrame = pWal->hdr.mxFrame; + for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){ + iFrame++; + rc = walIndexAppend(pWal, iFrame, p->pgno); + } + while( rc==SQLITE_OK && nExtra>0 ){ + iFrame++; + nExtra--; + rc = walIndexAppend(pWal, iFrame, pLast->pgno); + } + + if( rc==SQLITE_OK ){ + /* Update the private copy of the header. */ + pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); + testcase( szPage<=32768 ); + testcase( szPage>=65536 ); + pWal->hdr.mxFrame = iFrame; + if( isCommit ){ + pWal->hdr.iChange++; + pWal->hdr.nPage = nTruncate; + } + /* If this is a commit, update the wal-index header too. */ + if( isCommit ){ + walIndexWriteHdr(pWal); + pWal->iCallback = iFrame; + } + } + + WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok")); + return rc; +} + +/* +** This routine is called to implement sqlite3_wal_checkpoint() and +** related interfaces. +** +** Obtain a CHECKPOINT lock and then backfill as much information as +** we can from WAL into the database. +** +** If parameter xBusy is not NULL, it is a pointer to a busy-handler +** callback. In this case this function runs a blocking checkpoint. +*/ +SQLITE_PRIVATE int sqlite3WalCheckpoint( + Wal *pWal, /* Wal connection */ + int eMode, /* PASSIVE, FULL or RESTART */ + int (*xBusy)(void*), /* Function to call when busy */ + void *pBusyArg, /* Context argument for xBusyHandler */ + int sync_flags, /* Flags to sync db file with (or 0) */ + int nBuf, /* Size of temporary buffer */ + u8 *zBuf, /* Temporary buffer to use */ + int *pnLog, /* OUT: Number of frames in WAL */ + int *pnCkpt /* OUT: Number of backfilled frames in WAL */ +){ + int rc; /* Return code */ + int isChanged = 0; /* True if a new wal-index header is loaded */ + int eMode2 = eMode; /* Mode to pass to walCheckpoint() */ + + assert( pWal->ckptLock==0 ); + assert( pWal->writeLock==0 ); + + if( pWal->readOnly ) return SQLITE_READONLY; + WALTRACE(("WAL%p: checkpoint begins\n", pWal)); + rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); + if( rc ){ + /* Usually this is SQLITE_BUSY meaning that another thread or process + ** is already running a checkpoint, or maybe a recovery. But it might + ** also be SQLITE_IOERR. */ + return rc; + } + pWal->ckptLock = 1; + + /* If this is a blocking-checkpoint, then obtain the write-lock as well + ** to prevent any writers from running while the checkpoint is underway. + ** This has to be done before the call to walIndexReadHdr() below. + ** + ** If the writer lock cannot be obtained, then a passive checkpoint is + ** run instead. Since the checkpointer is not holding the writer lock, + ** there is no point in blocking waiting for any readers. Assuming no + ** other error occurs, this function will return SQLITE_BUSY to the caller. + */ + if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){ + rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1); + if( rc==SQLITE_OK ){ + pWal->writeLock = 1; + }else if( rc==SQLITE_BUSY ){ + eMode2 = SQLITE_CHECKPOINT_PASSIVE; + rc = SQLITE_OK; + } + } + + /* Read the wal-index header. */ + if( rc==SQLITE_OK ){ + rc = walIndexReadHdr(pWal, &isChanged); + if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){ + sqlite3OsUnfetch(pWal->pDbFd, 0, 0); + } + } + + /* Copy data from the log to the database file. */ + if( rc==SQLITE_OK ){ + if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf); + } + + /* If no error occurred, set the output variables. */ + if( rc==SQLITE_OK || rc==SQLITE_BUSY ){ + if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame; + if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill); + } + } + + if( isChanged ){ + /* If a new wal-index header was loaded before the checkpoint was + ** performed, then the pager-cache associated with pWal is now + ** out of date. So zero the cached wal-index header to ensure that + ** next time the pager opens a snapshot on this database it knows that + ** the cache needs to be reset. + */ + memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); + } + + /* Release the locks. */ + sqlite3WalEndWriteTransaction(pWal); + walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); + pWal->ckptLock = 0; + WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok")); + return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc); +} + +/* Return the value to pass to a sqlite3_wal_hook callback, the +** number of frames in the WAL at the point of the last commit since +** sqlite3WalCallback() was called. If no commits have occurred since +** the last call, then return 0. +*/ +SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){ + u32 ret = 0; + if( pWal ){ + ret = pWal->iCallback; + pWal->iCallback = 0; + } + return (int)ret; +} + +/* +** This function is called to change the WAL subsystem into or out +** of locking_mode=EXCLUSIVE. +** +** If op is zero, then attempt to change from locking_mode=EXCLUSIVE +** into locking_mode=NORMAL. This means that we must acquire a lock +** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL +** or if the acquisition of the lock fails, then return 0. If the +** transition out of exclusive-mode is successful, return 1. This +** operation must occur while the pager is still holding the exclusive +** lock on the main database file. +** +** If op is one, then change from locking_mode=NORMAL into +** locking_mode=EXCLUSIVE. This means that the pWal->readLock must +** be released. Return 1 if the transition is made and 0 if the +** WAL is already in exclusive-locking mode - meaning that this +** routine is a no-op. The pager must already hold the exclusive lock +** on the main database file before invoking this operation. +** +** If op is negative, then do a dry-run of the op==1 case but do +** not actually change anything. The pager uses this to see if it +** should acquire the database exclusive lock prior to invoking +** the op==1 case. +*/ +SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){ + int rc; + assert( pWal->writeLock==0 ); + assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 ); + + /* pWal->readLock is usually set, but might be -1 if there was a + ** prior error while attempting to acquire are read-lock. This cannot + ** happen if the connection is actually in exclusive mode (as no xShmLock + ** locks are taken in this case). Nor should the pager attempt to + ** upgrade to exclusive-mode following such an error. + */ + assert( pWal->readLock>=0 || pWal->lockError ); + assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) ); + + if( op==0 ){ + if( pWal->exclusiveMode ){ + pWal->exclusiveMode = 0; + if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){ + pWal->exclusiveMode = 1; + } + rc = pWal->exclusiveMode==0; + }else{ + /* Already in locking_mode=NORMAL */ + rc = 0; + } + }else if( op>0 ){ + assert( pWal->exclusiveMode==0 ); + assert( pWal->readLock>=0 ); + walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); + pWal->exclusiveMode = 1; + rc = 1; + }else{ + rc = pWal->exclusiveMode==0; + } + return rc; +} + +/* +** Return true if the argument is non-NULL and the WAL module is using +** heap-memory for the wal-index. Otherwise, if the argument is NULL or the +** WAL module is using shared-memory, return false. +*/ +SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){ + return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ); +} + +#ifdef SQLITE_ENABLE_ZIPVFS +/* +** If the argument is not NULL, it points to a Wal object that holds a +** read-lock. This function returns the database page-size if it is known, +** or zero if it is not (or if pWal is NULL). +*/ +SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){ + assert( pWal==0 || pWal->readLock>=0 ); + return (pWal ? pWal->szPage : 0); +} +#endif + +#endif /* #ifndef SQLITE_OMIT_WAL */ + +/************** End of wal.c *************************************************/ +/************** Begin file btmutex.c *****************************************/ +/* +** 2007 August 27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used to implement mutexes on Btree objects. +** This code really belongs in btree.c. But btree.c is getting too +** big and we want to break it down some. This packaged seemed like +** a good breakout. +*/ +/************** Include btreeInt.h in the middle of btmutex.c ****************/ +/************** Begin file btreeInt.h ****************************************/ +/* +** 2004 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements a external (disk-based) database using BTrees. +** For a detailed discussion of BTrees, refer to +** +** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: +** "Sorting And Searching", pages 473-480. Addison-Wesley +** Publishing Company, Reading, Massachusetts. +** +** The basic idea is that each page of the file contains N database +** entries and N+1 pointers to subpages. +** +** ---------------------------------------------------------------- +** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) | +** ---------------------------------------------------------------- +** +** All of the keys on the page that Ptr(0) points to have values less +** than Key(0). All of the keys on page Ptr(1) and its subpages have +** values greater than Key(0) and less than Key(1). All of the keys +** on Ptr(N) and its subpages have values greater than Key(N-1). And +** so forth. +** +** Finding a particular key requires reading O(log(M)) pages from the +** disk where M is the number of entries in the tree. +** +** In this implementation, a single file can hold one or more separate +** BTrees. Each BTree is identified by the index of its root page. The +** key and data for any entry are combined to form the "payload". A +** fixed amount of payload can be carried directly on the database +** page. If the payload is larger than the preset amount then surplus +** bytes are stored on overflow pages. The payload for an entry +** and the preceding pointer are combined to form a "Cell". Each +** page has a small header which contains the Ptr(N) pointer and other +** information such as the size of key and data. +** +** FORMAT DETAILS +** +** The file is divided into pages. The first page is called page 1, +** the second is page 2, and so forth. A page number of zero indicates +** "no such page". The page size can be any power of 2 between 512 and 65536. +** Each page can be either a btree page, a freelist page, an overflow +** page, or a pointer-map page. +** +** The first page is always a btree page. The first 100 bytes of the first +** page contain a special header (the "file header") that describes the file. +** The format of the file header is as follows: +** +** OFFSET SIZE DESCRIPTION +** 0 16 Header string: "SQLite format 3\000" +** 16 2 Page size in bytes. (1 means 65536) +** 18 1 File format write version +** 19 1 File format read version +** 20 1 Bytes of unused space at the end of each page +** 21 1 Max embedded payload fraction (must be 64) +** 22 1 Min embedded payload fraction (must be 32) +** 23 1 Min leaf payload fraction (must be 32) +** 24 4 File change counter +** 28 4 Reserved for future use +** 32 4 First freelist page +** 36 4 Number of freelist pages in the file +** 40 60 15 4-byte meta values passed to higher layers +** +** 40 4 Schema cookie +** 44 4 File format of schema layer +** 48 4 Size of page cache +** 52 4 Largest root-page (auto/incr_vacuum) +** 56 4 1=UTF-8 2=UTF16le 3=UTF16be +** 60 4 User version +** 64 4 Incremental vacuum mode +** 68 4 Application-ID +** 72 20 unused +** 92 4 The version-valid-for number +** 96 4 SQLITE_VERSION_NUMBER +** +** All of the integer values are big-endian (most significant byte first). +** +** The file change counter is incremented when the database is changed +** This counter allows other processes to know when the file has changed +** and thus when they need to flush their cache. +** +** The max embedded payload fraction is the amount of the total usable +** space in a page that can be consumed by a single cell for standard +** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default +** is to limit the maximum cell size so that at least 4 cells will fit +** on one page. Thus the default max embedded payload fraction is 64. +** +** If the payload for a cell is larger than the max payload, then extra +** payload is spilled to overflow pages. Once an overflow page is allocated, +** as many bytes as possible are moved into the overflow pages without letting +** the cell size drop below the min embedded payload fraction. +** +** The min leaf payload fraction is like the min embedded payload fraction +** except that it applies to leaf nodes in a LEAFDATA tree. The maximum +** payload fraction for a LEAFDATA tree is always 100% (or 255) and it +** not specified in the header. +** +** Each btree pages is divided into three sections: The header, the +** cell pointer array, and the cell content area. Page 1 also has a 100-byte +** file header that occurs before the page header. +** +** |----------------| +** | file header | 100 bytes. Page 1 only. +** |----------------| +** | page header | 8 bytes for leaves. 12 bytes for interior nodes +** |----------------| +** | cell pointer | | 2 bytes per cell. Sorted order. +** | array | | Grows downward +** | | v +** |----------------| +** | unallocated | +** | space | +** |----------------| ^ Grows upwards +** | cell content | | Arbitrary order interspersed with freeblocks. +** | area | | and free space fragments. +** |----------------| +** +** The page headers looks like this: +** +** OFFSET SIZE DESCRIPTION +** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf +** 1 2 byte offset to the first freeblock +** 3 2 number of cells on this page +** 5 2 first byte of the cell content area +** 7 1 number of fragmented free bytes +** 8 4 Right child (the Ptr(N) value). Omitted on leaves. +** +** The flags define the format of this btree page. The leaf flag means that +** this page has no children. The zerodata flag means that this page carries +** only keys and no data. The intkey flag means that the key is a integer +** which is stored in the key size entry of the cell header rather than in +** the payload area. +** +** The cell pointer array begins on the first byte after the page header. +** The cell pointer array contains zero or more 2-byte numbers which are +** offsets from the beginning of the page to the cell content in the cell +** content area. The cell pointers occur in sorted order. The system strives +** to keep free space after the last cell pointer so that new cells can +** be easily added without having to defragment the page. +** +** Cell content is stored at the very end of the page and grows toward the +** beginning of the page. +** +** Unused space within the cell content area is collected into a linked list of +** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset +** to the first freeblock is given in the header. Freeblocks occur in +** increasing order. Because a freeblock must be at least 4 bytes in size, +** any group of 3 or fewer unused bytes in the cell content area cannot +** exist on the freeblock chain. A group of 3 or fewer free bytes is called +** a fragment. The total number of bytes in all fragments is recorded. +** in the page header at offset 7. +** +** SIZE DESCRIPTION +** 2 Byte offset of the next freeblock +** 2 Bytes in this freeblock +** +** Cells are of variable length. Cells are stored in the cell content area at +** the end of the page. Pointers to the cells are in the cell pointer array +** that immediately follows the page header. Cells is not necessarily +** contiguous or in order, but cell pointers are contiguous and in order. +** +** Cell content makes use of variable length integers. A variable +** length integer is 1 to 9 bytes where the lower 7 bits of each +** byte are used. The integer consists of all bytes that have bit 8 set and +** the first byte with bit 8 clear. The most significant byte of the integer +** appears first. A variable-length integer may not be more than 9 bytes long. +** As a special case, all 8 bytes of the 9th byte are used as data. This +** allows a 64-bit integer to be encoded in 9 bytes. +** +** 0x00 becomes 0x00000000 +** 0x7f becomes 0x0000007f +** 0x81 0x00 becomes 0x00000080 +** 0x82 0x00 becomes 0x00000100 +** 0x80 0x7f becomes 0x0000007f +** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678 +** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081 +** +** Variable length integers are used for rowids and to hold the number of +** bytes of key and data in a btree cell. +** +** The content of a cell looks like this: +** +** SIZE DESCRIPTION +** 4 Page number of the left child. Omitted if leaf flag is set. +** var Number of bytes of data. Omitted if the zerodata flag is set. +** var Number of bytes of key. Or the key itself if intkey flag is set. +** * Payload +** 4 First page of the overflow chain. Omitted if no overflow +** +** Overflow pages form a linked list. Each page except the last is completely +** filled with data (pagesize - 4 bytes). The last page can have as little +** as 1 byte of data. +** +** SIZE DESCRIPTION +** 4 Page number of next overflow page +** * Data +** +** Freelist pages come in two subtypes: trunk pages and leaf pages. The +** file header points to the first in a linked list of trunk page. Each trunk +** page points to multiple leaf pages. The content of a leaf page is +** unspecified. A trunk page looks like this: +** +** SIZE DESCRIPTION +** 4 Page number of next trunk page +** 4 Number of leaf pointers on this page +** * zero or more pages numbers of leaves +*/ + + +/* The following value is the maximum cell size assuming a maximum page +** size give above. +*/ +#define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8)) + +/* The maximum number of cells on a single page of the database. This +** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself +** plus 2 bytes for the index to the cell in the page header). Such +** small cells will be rare, but they are possible. +*/ +#define MX_CELL(pBt) ((pBt->pageSize-8)/6) + +/* Forward declarations */ +typedef struct MemPage MemPage; +typedef struct BtLock BtLock; + +/* +** This is a magic string that appears at the beginning of every +** SQLite database in order to identify the file as a real database. +** +** You can change this value at compile-time by specifying a +** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The +** header must be exactly 16 bytes including the zero-terminator so +** the string itself should be 15 characters long. If you change +** the header, then your custom library will not be able to read +** databases generated by the standard tools and the standard tools +** will not be able to read databases created by your custom library. +*/ +#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */ +# define SQLITE_FILE_HEADER "SQLite format 3" +#endif + +/* +** Page type flags. An ORed combination of these flags appear as the +** first byte of on-disk image of every BTree page. +*/ +#define PTF_INTKEY 0x01 +#define PTF_ZERODATA 0x02 +#define PTF_LEAFDATA 0x04 +#define PTF_LEAF 0x08 + +/* +** As each page of the file is loaded into memory, an instance of the following +** structure is appended and initialized to zero. This structure stores +** information about the page that is decoded from the raw file page. +** +** The pParent field points back to the parent page. This allows us to +** walk up the BTree from any leaf to the root. Care must be taken to +** unref() the parent page pointer when this page is no longer referenced. +** The pageDestructor() routine handles that chore. +** +** Access to all fields of this structure is controlled by the mutex +** stored in MemPage.pBt->mutex. +*/ +struct MemPage { + u8 isInit; /* True if previously initialized. MUST BE FIRST! */ + u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ + u8 intKey; /* True if intkey flag is set */ + u8 leaf; /* True if leaf flag is set */ + u8 hasData; /* True if this page stores data */ + u8 hdrOffset; /* 100 for page 1. 0 otherwise */ + u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ + u8 max1bytePayload; /* min(maxLocal,127) */ + u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ + u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ + u16 cellOffset; /* Index in aData of first cell pointer */ + u16 nFree; /* Number of free bytes on the page */ + u16 nCell; /* Number of cells on this page, local and ovfl */ + u16 maskPage; /* Mask for page offset */ + u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th + ** non-overflow cell */ + u8 *apOvfl[5]; /* Pointers to the body of overflow cells */ + BtShared *pBt; /* Pointer to BtShared that this page is part of */ + u8 *aData; /* Pointer to disk image of the page data */ + u8 *aDataEnd; /* One byte past the end of usable data */ + u8 *aCellIdx; /* The cell index area */ + DbPage *pDbPage; /* Pager page handle */ + Pgno pgno; /* Page number for this page */ +}; + +/* +** The in-memory image of a disk page has the auxiliary information appended +** to the end. EXTRA_SIZE is the number of bytes of space needed to hold +** that extra information. +*/ +#define EXTRA_SIZE sizeof(MemPage) + +/* +** A linked list of the following structures is stored at BtShared.pLock. +** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor +** is opened on the table with root page BtShared.iTable. Locks are removed +** from this list when a transaction is committed or rolled back, or when +** a btree handle is closed. +*/ +struct BtLock { + Btree *pBtree; /* Btree handle holding this lock */ + Pgno iTable; /* Root page of table */ + u8 eLock; /* READ_LOCK or WRITE_LOCK */ + BtLock *pNext; /* Next in BtShared.pLock list */ +}; + +/* Candidate values for BtLock.eLock */ +#define READ_LOCK 1 +#define WRITE_LOCK 2 + +/* A Btree handle +** +** A database connection contains a pointer to an instance of +** this object for every database file that it has open. This structure +** is opaque to the database connection. The database connection cannot +** see the internals of this structure and only deals with pointers to +** this structure. +** +** For some database files, the same underlying database cache might be +** shared between multiple connections. In that case, each connection +** has it own instance of this object. But each instance of this object +** points to the same BtShared object. The database cache and the +** schema associated with the database file are all contained within +** the BtShared object. +** +** All fields in this structure are accessed under sqlite3.mutex. +** The pBt pointer itself may not be changed while there exists cursors +** in the referenced BtShared that point back to this Btree since those +** cursors have to go through this Btree to find their BtShared and +** they often do so without holding sqlite3.mutex. +*/ +struct Btree { + sqlite3 *db; /* The database connection holding this btree */ + BtShared *pBt; /* Sharable content of this btree */ + u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ + u8 sharable; /* True if we can share pBt with another db */ + u8 locked; /* True if db currently has pBt locked */ + int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ + int nBackup; /* Number of backup operations reading this btree */ + Btree *pNext; /* List of other sharable Btrees from the same db */ + Btree *pPrev; /* Back pointer of the same list */ +#ifndef SQLITE_OMIT_SHARED_CACHE + BtLock lock; /* Object used to lock page 1 */ +#endif +}; + +/* +** Btree.inTrans may take one of the following values. +** +** If the shared-data extension is enabled, there may be multiple users +** of the Btree structure. At most one of these may open a write transaction, +** but any number may have active read transactions. +*/ +#define TRANS_NONE 0 +#define TRANS_READ 1 +#define TRANS_WRITE 2 + +/* +** An instance of this object represents a single database file. +** +** A single database file can be in use at the same time by two +** or more database connections. When two or more connections are +** sharing the same database file, each connection has it own +** private Btree object for the file and each of those Btrees points +** to this one BtShared object. BtShared.nRef is the number of +** connections currently sharing this database file. +** +** Fields in this structure are accessed under the BtShared.mutex +** mutex, except for nRef and pNext which are accessed under the +** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field +** may not be modified once it is initially set as long as nRef>0. +** The pSchema field may be set once under BtShared.mutex and +** thereafter is unchanged as long as nRef>0. +** +** isPending: +** +** If a BtShared client fails to obtain a write-lock on a database +** table (because there exists one or more read-locks on the table), +** the shared-cache enters 'pending-lock' state and isPending is +** set to true. +** +** The shared-cache leaves the 'pending lock' state when either of +** the following occur: +** +** 1) The current writer (BtShared.pWriter) concludes its transaction, OR +** 2) The number of locks held by other connections drops to zero. +** +** while in the 'pending-lock' state, no connection may start a new +** transaction. +** +** This feature is included to help prevent writer-starvation. +*/ +struct BtShared { + Pager *pPager; /* The page cache */ + sqlite3 *db; /* Database connection currently using this Btree */ + BtCursor *pCursor; /* A list of all open cursors */ + MemPage *pPage1; /* First page of the database */ + u8 openFlags; /* Flags to sqlite3BtreeOpen() */ +#ifndef SQLITE_OMIT_AUTOVACUUM + u8 autoVacuum; /* True if auto-vacuum is enabled */ + u8 incrVacuum; /* True if incr-vacuum is enabled */ + u8 bDoTruncate; /* True to truncate db on commit */ +#endif + u8 inTransaction; /* Transaction state */ + u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */ + u16 btsFlags; /* Boolean parameters. See BTS_* macros below */ + u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ + u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */ + u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */ + u16 minLeaf; /* Minimum local payload in a LEAFDATA table */ + u32 pageSize; /* Total number of bytes on a page */ + u32 usableSize; /* Number of usable bytes on each page */ + int nTransaction; /* Number of open transactions (read + write) */ + u32 nPage; /* Number of pages in the database */ + void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ + void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */ + sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */ + Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */ +#ifndef SQLITE_OMIT_SHARED_CACHE + int nRef; /* Number of references to this structure */ + BtShared *pNext; /* Next on a list of sharable BtShared structs */ + BtLock *pLock; /* List of locks held on this shared-btree struct */ + Btree *pWriter; /* Btree with currently open write transaction */ +#endif + u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */ +}; + +/* +** Allowed values for BtShared.btsFlags +*/ +#define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */ +#define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */ +#define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */ +#define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */ +#define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */ +#define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */ +#define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */ + +/* +** An instance of the following structure is used to hold information +** about a cell. The parseCellPtr() function fills in this structure +** based on information extract from the raw disk page. +*/ +typedef struct CellInfo CellInfo; +struct CellInfo { + i64 nKey; /* The key for INTKEY tables, or number of bytes in key */ + u8 *pCell; /* Pointer to the start of cell content */ + u32 nData; /* Number of bytes of data */ + u32 nPayload; /* Total amount of payload */ + u16 nHeader; /* Size of the cell content header in bytes */ + u16 nLocal; /* Amount of payload held locally */ + u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */ + u16 nSize; /* Size of the cell content on the main b-tree page */ +}; + +/* +** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than +** this will be declared corrupt. This value is calculated based on a +** maximum database size of 2^31 pages a minimum fanout of 2 for a +** root-node and 3 for all other internal nodes. +** +** If a tree that appears to be taller than this is encountered, it is +** assumed that the database is corrupt. +*/ +#define BTCURSOR_MAX_DEPTH 20 + +/* +** A cursor is a pointer to a particular entry within a particular +** b-tree within a database file. +** +** The entry is identified by its MemPage and the index in +** MemPage.aCell[] of the entry. +** +** A single database file can be shared by two more database connections, +** but cursors cannot be shared. Each cursor is associated with a +** particular database connection identified BtCursor.pBtree.db. +** +** Fields in this structure are accessed under the BtShared.mutex +** found at self->pBt->mutex. +*/ +struct BtCursor { + Btree *pBtree; /* The Btree to which this cursor belongs */ + BtShared *pBt; /* The BtShared this cursor points to */ + BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */ + struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */ +#ifndef SQLITE_OMIT_INCRBLOB + Pgno *aOverflow; /* Cache of overflow page locations */ +#endif + Pgno pgnoRoot; /* The root page of this tree */ + sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */ + CellInfo info; /* A parse of the cell we are pointing at */ + i64 nKey; /* Size of pKey, or last integer key */ + void *pKey; /* Saved key that was cursor's last known position */ + int skipNext; /* Prev() is noop if negative. Next() is noop if positive */ + u8 wrFlag; /* True if writable */ + u8 atLast; /* Cursor pointing to the last entry */ + u8 validNKey; /* True if info.nKey is valid */ + u8 eState; /* One of the CURSOR_XXX constants (see below) */ +#ifndef SQLITE_OMIT_INCRBLOB + u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */ +#endif + u8 hints; /* As configured by CursorSetHints() */ + i16 iPage; /* Index of current page in apPage */ + u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */ + MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */ +}; + +/* +** Potential values for BtCursor.eState. +** +** CURSOR_INVALID: +** Cursor does not point to a valid entry. This can happen (for example) +** because the table is empty or because BtreeCursorFirst() has not been +** called. +** +** CURSOR_VALID: +** Cursor points to a valid entry. getPayload() etc. may be called. +** +** CURSOR_SKIPNEXT: +** Cursor is valid except that the Cursor.skipNext field is non-zero +** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious() +** operation should be a no-op. +** +** CURSOR_REQUIRESEEK: +** The table that this cursor was opened on still exists, but has been +** modified since the cursor was last used. The cursor position is saved +** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in +** this state, restoreCursorPosition() can be called to attempt to +** seek the cursor to the saved position. +** +** CURSOR_FAULT: +** A unrecoverable error (an I/O error or a malloc failure) has occurred +** on a different connection that shares the BtShared cache with this +** cursor. The error has left the cache in an inconsistent state. +** Do nothing else with this cursor. Any attempt to use the cursor +** should return the error code stored in BtCursor.skip +*/ +#define CURSOR_INVALID 0 +#define CURSOR_VALID 1 +#define CURSOR_SKIPNEXT 2 +#define CURSOR_REQUIRESEEK 3 +#define CURSOR_FAULT 4 + +/* +** The database page the PENDING_BYTE occupies. This page is never used. +*/ +# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt) + +/* +** These macros define the location of the pointer-map entry for a +** database page. The first argument to each is the number of usable +** bytes on each page of the database (often 1024). The second is the +** page number to look up in the pointer map. +** +** PTRMAP_PAGENO returns the database page number of the pointer-map +** page that stores the required pointer. PTRMAP_PTROFFSET returns +** the offset of the requested map entry. +** +** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page, +** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be +** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements +** this test. +*/ +#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno) +#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1)) +#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno)) + +/* +** The pointer map is a lookup table that identifies the parent page for +** each child page in the database file. The parent page is the page that +** contains a pointer to the child. Every page in the database contains +** 0 or 1 parent pages. (In this context 'database page' refers +** to any page that is not part of the pointer map itself.) Each pointer map +** entry consists of a single byte 'type' and a 4 byte parent page number. +** The PTRMAP_XXX identifiers below are the valid types. +** +** The purpose of the pointer map is to facility moving pages from one +** position in the file to another as part of autovacuum. When a page +** is moved, the pointer in its parent must be updated to point to the +** new location. The pointer map is used to locate the parent page quickly. +** +** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not +** used in this case. +** +** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number +** is not used in this case. +** +** PTRMAP_OVERFLOW1: The database page is the first page in a list of +** overflow pages. The page number identifies the page that +** contains the cell with a pointer to this overflow page. +** +** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of +** overflow pages. The page-number identifies the previous +** page in the overflow page list. +** +** PTRMAP_BTREE: The database page is a non-root btree page. The page number +** identifies the parent page in the btree. +*/ +#define PTRMAP_ROOTPAGE 1 +#define PTRMAP_FREEPAGE 2 +#define PTRMAP_OVERFLOW1 3 +#define PTRMAP_OVERFLOW2 4 +#define PTRMAP_BTREE 5 + +/* A bunch of assert() statements to check the transaction state variables +** of handle p (type Btree*) are internally consistent. +*/ +#define btreeIntegrity(p) \ + assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \ + assert( p->pBt->inTransaction>=p->inTrans ); + + +/* +** The ISAUTOVACUUM macro is used within balance_nonroot() to determine +** if the database supports auto-vacuum or not. Because it is used +** within an expression that is an argument to another macro +** (sqliteMallocRaw), it is not possible to use conditional compilation. +** So, this macro is defined instead. +*/ +#ifndef SQLITE_OMIT_AUTOVACUUM +#define ISAUTOVACUUM (pBt->autoVacuum) +#else +#define ISAUTOVACUUM 0 +#endif + + +/* +** This structure is passed around through all the sanity checking routines +** in order to keep track of some global state information. +** +** The aRef[] array is allocated so that there is 1 bit for each page in +** the database. As the integrity-check proceeds, for each page used in +** the database the corresponding bit is set. This allows integrity-check to +** detect pages that are used twice and orphaned pages (both of which +** indicate corruption). +*/ +typedef struct IntegrityCk IntegrityCk; +struct IntegrityCk { + BtShared *pBt; /* The tree being checked out */ + Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */ + u8 *aPgRef; /* 1 bit per page in the db (see above) */ + Pgno nPage; /* Number of pages in the database */ + int mxErr; /* Stop accumulating errors when this reaches zero */ + int nErr; /* Number of messages written to zErrMsg so far */ + int mallocFailed; /* A memory allocation error has occurred */ + StrAccum errMsg; /* Accumulate the error message text here */ +}; + +/* +** Routines to read or write a two- and four-byte big-endian integer values. +*/ +#define get2byte(x) ((x)[0]<<8 | (x)[1]) +#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) +#define get4byte sqlite3Get4byte +#define put4byte sqlite3Put4byte + +/************** End of btreeInt.h ********************************************/ +/************** Continuing where we left off in btmutex.c ********************/ +#ifndef SQLITE_OMIT_SHARED_CACHE +#if SQLITE_THREADSAFE + +/* +** Obtain the BtShared mutex associated with B-Tree handle p. Also, +** set BtShared.db to the database handle associated with p and the +** p->locked boolean to true. +*/ +static void lockBtreeMutex(Btree *p){ + assert( p->locked==0 ); + assert( sqlite3_mutex_notheld(p->pBt->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); + + sqlite3_mutex_enter(p->pBt->mutex); + p->pBt->db = p->db; + p->locked = 1; +} + +/* +** Release the BtShared mutex associated with B-Tree handle p and +** clear the p->locked boolean. +*/ +static void unlockBtreeMutex(Btree *p){ + BtShared *pBt = p->pBt; + assert( p->locked==1 ); + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); + assert( p->db==pBt->db ); + + sqlite3_mutex_leave(pBt->mutex); + p->locked = 0; +} + +/* +** Enter a mutex on the given BTree object. +** +** If the object is not sharable, then no mutex is ever required +** and this routine is a no-op. The underlying mutex is non-recursive. +** But we keep a reference count in Btree.wantToLock so the behavior +** of this interface is recursive. +** +** To avoid deadlocks, multiple Btrees are locked in the same order +** by all database connections. The p->pNext is a list of other +** Btrees belonging to the same database connection as the p Btree +** which need to be locked after p. If we cannot get a lock on +** p, then first unlock all of the others on p->pNext, then wait +** for the lock to become available on p, then relock all of the +** subsequent Btrees that desire a lock. +*/ +SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ + Btree *pLater; + + /* Some basic sanity checking on the Btree. The list of Btrees + ** connected by pNext and pPrev should be in sorted order by + ** Btree.pBt value. All elements of the list should belong to + ** the same connection. Only shared Btrees are on the list. */ + assert( p->pNext==0 || p->pNext->pBt>p->pBt ); + assert( p->pPrev==0 || p->pPrev->pBtpBt ); + assert( p->pNext==0 || p->pNext->db==p->db ); + assert( p->pPrev==0 || p->pPrev->db==p->db ); + assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); + + /* Check for locking consistency */ + assert( !p->locked || p->wantToLock>0 ); + assert( p->sharable || p->wantToLock==0 ); + + /* We should already hold a lock on the database connection */ + assert( sqlite3_mutex_held(p->db->mutex) ); + + /* Unless the database is sharable and unlocked, then BtShared.db + ** should already be set correctly. */ + assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db ); + + if( !p->sharable ) return; + p->wantToLock++; + if( p->locked ) return; + + /* In most cases, we should be able to acquire the lock we + ** want without having to go throught the ascending lock + ** procedure that follows. Just be sure not to block. + */ + if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ + p->pBt->db = p->db; + p->locked = 1; + return; + } + + /* To avoid deadlock, first release all locks with a larger + ** BtShared address. Then acquire our lock. Then reacquire + ** the other BtShared locks that we used to hold in ascending + ** order. + */ + for(pLater=p->pNext; pLater; pLater=pLater->pNext){ + assert( pLater->sharable ); + assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt ); + assert( !pLater->locked || pLater->wantToLock>0 ); + if( pLater->locked ){ + unlockBtreeMutex(pLater); + } + } + lockBtreeMutex(p); + for(pLater=p->pNext; pLater; pLater=pLater->pNext){ + if( pLater->wantToLock ){ + lockBtreeMutex(pLater); + } + } +} + +/* +** Exit the recursive mutex on a Btree. +*/ +SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){ + if( p->sharable ){ + assert( p->wantToLock>0 ); + p->wantToLock--; + if( p->wantToLock==0 ){ + unlockBtreeMutex(p); + } + } +} + +#ifndef NDEBUG +/* +** Return true if the BtShared mutex is held on the btree, or if the +** B-Tree is not marked as sharable. +** +** This routine is used only from within assert() statements. +*/ +SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){ + assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); + assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); + assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); + assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); + + return (p->sharable==0 || p->locked); +} +#endif + + +#ifndef SQLITE_OMIT_INCRBLOB +/* +** Enter and leave a mutex on a Btree given a cursor owned by that +** Btree. These entry points are used by incremental I/O and can be +** omitted if that module is not used. +*/ +SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){ + sqlite3BtreeEnter(pCur->pBtree); +} +SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){ + sqlite3BtreeLeave(pCur->pBtree); +} +#endif /* SQLITE_OMIT_INCRBLOB */ + + +/* +** Enter the mutex on every Btree associated with a database +** connection. This is needed (for example) prior to parsing +** a statement since we will be comparing table and column names +** against all schemas and we do not want those schemas being +** reset out from under us. +** +** There is a corresponding leave-all procedures. +** +** Enter the mutexes in accending order by BtShared pointer address +** to avoid the possibility of deadlock when two threads with +** two or more btrees in common both try to lock all their btrees +** at the same instant. +*/ +SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ + int i; + Btree *p; + assert( sqlite3_mutex_held(db->mutex) ); + for(i=0; inDb; i++){ + p = db->aDb[i].pBt; + if( p ) sqlite3BtreeEnter(p); + } +} +SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){ + int i; + Btree *p; + assert( sqlite3_mutex_held(db->mutex) ); + for(i=0; inDb; i++){ + p = db->aDb[i].pBt; + if( p ) sqlite3BtreeLeave(p); + } +} + +/* +** Return true if a particular Btree requires a lock. Return FALSE if +** no lock is ever required since it is not sharable. +*/ +SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){ + return p->sharable; +} + +#ifndef NDEBUG +/* +** Return true if the current thread holds the database connection +** mutex and all required BtShared mutexes. +** +** This routine is used inside assert() statements only. +*/ +SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ + int i; + if( !sqlite3_mutex_held(db->mutex) ){ + return 0; + } + for(i=0; inDb; i++){ + Btree *p; + p = db->aDb[i].pBt; + if( p && p->sharable && + (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ + return 0; + } + } + return 1; +} +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* +** Return true if the correct mutexes are held for accessing the +** db->aDb[iDb].pSchema structure. The mutexes required for schema +** access are: +** +** (1) The mutex on db +** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. +** +** If pSchema is not NULL, then iDb is computed from pSchema and +** db using sqlite3SchemaToIndex(). +*/ +SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){ + Btree *p; + assert( db!=0 ); + if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); + assert( iDb>=0 && iDbnDb ); + if( !sqlite3_mutex_held(db->mutex) ) return 0; + if( iDb==1 ) return 1; + p = db->aDb[iDb].pBt; + assert( p!=0 ); + return p->sharable==0 || p->locked==1; +} +#endif /* NDEBUG */ + +#else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */ +/* +** The following are special cases for mutex enter routines for use +** in single threaded applications that use shared cache. Except for +** these two routines, all mutex operations are no-ops in that case and +** are null #defines in btree.h. +** +** If shared cache is disabled, then all btree mutex routines, including +** the ones below, are no-ops and are null #defines in btree.h. +*/ + +SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ + p->pBt->db = p->db; +} +SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ + int i; + for(i=0; inDb; i++){ + Btree *p = db->aDb[i].pBt; + if( p ){ + p->pBt->db = p->db; + } + } +} +#endif /* if SQLITE_THREADSAFE */ +#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */ + +/************** End of btmutex.c *********************************************/ +/************** Begin file btree.c *******************************************/ +/* +** 2004 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements a external (disk-based) database using BTrees. +** See the header comment on "btreeInt.h" for additional information. +** Including a description of file format and an overview of operation. +*/ + +/* +** The header string that appears at the beginning of every +** SQLite database. +*/ +static const char zMagicHeader[] = SQLITE_FILE_HEADER; + +/* +** Set this global variable to 1 to enable tracing using the TRACE +** macro. +*/ +#if 0 +int sqlite3BtreeTrace=1; /* True to enable tracing */ +# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} +#else +# define TRACE(X) +#endif + +/* +** Extract a 2-byte big-endian integer from an array of unsigned bytes. +** But if the value is zero, make it 65536. +** +** This routine is used to extract the "offset to cell content area" value +** from the header of a btree page. If the page size is 65536 and the page +** is empty, the offset should be 65536, but the 2-byte value stores zero. +** This routine makes the necessary adjustment to 65536. +*/ +#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) + +/* +** Values passed as the 5th argument to allocateBtreePage() +*/ +#define BTALLOC_ANY 0 /* Allocate any page */ +#define BTALLOC_EXACT 1 /* Allocate exact page if possible */ +#define BTALLOC_LE 2 /* Allocate any page <= the parameter */ + +/* +** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not +** defined, or 0 if it is. For example: +** +** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum); +*/ +#ifndef SQLITE_OMIT_AUTOVACUUM +#define IfNotOmitAV(expr) (expr) +#else +#define IfNotOmitAV(expr) 0 +#endif + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** A list of BtShared objects that are eligible for participation +** in shared cache. This variable has file scope during normal builds, +** but the test harness needs to access it so we make it global for +** test builds. +** +** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. +*/ +#ifdef SQLITE_TEST +SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; +#else +static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; +#endif +#endif /* SQLITE_OMIT_SHARED_CACHE */ + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** Enable or disable the shared pager and schema features. +** +** This routine has no effect on existing database connections. +** The shared cache setting effects only future calls to +** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). +*/ +SQLITE_API int sqlite3_enable_shared_cache(int enable){ + sqlite3GlobalConfig.sharedCacheEnabled = enable; + return SQLITE_OK; +} +#endif + + + +#ifdef SQLITE_OMIT_SHARED_CACHE + /* + ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), + ** and clearAllSharedCacheTableLocks() + ** manipulate entries in the BtShared.pLock linked list used to store + ** shared-cache table level locks. If the library is compiled with the + ** shared-cache feature disabled, then there is only ever one user + ** of each BtShared structure and so this locking is not necessary. + ** So define the lock related functions as no-ops. + */ + #define querySharedCacheTableLock(a,b,c) SQLITE_OK + #define setSharedCacheTableLock(a,b,c) SQLITE_OK + #define clearAllSharedCacheTableLocks(a) + #define downgradeAllSharedCacheTableLocks(a) + #define hasSharedCacheTableLock(a,b,c,d) 1 + #define hasReadConflicts(a, b) 0 +#endif + +#ifndef SQLITE_OMIT_SHARED_CACHE + +#ifdef SQLITE_DEBUG +/* +**** This function is only used as part of an assert() statement. *** +** +** Check to see if pBtree holds the required locks to read or write to the +** table with root page iRoot. Return 1 if it does and 0 if not. +** +** For example, when writing to a table with root-page iRoot via +** Btree connection pBtree: +** +** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); +** +** When writing to an index that resides in a sharable database, the +** caller should have first obtained a lock specifying the root page of +** the corresponding table. This makes things a bit more complicated, +** as this module treats each table as a separate structure. To determine +** the table corresponding to the index being written, this +** function has to search through the database schema. +** +** Instead of a lock on the table/index rooted at page iRoot, the caller may +** hold a write-lock on the schema table (root page 1). This is also +** acceptable. +*/ +static int hasSharedCacheTableLock( + Btree *pBtree, /* Handle that must hold lock */ + Pgno iRoot, /* Root page of b-tree */ + int isIndex, /* True if iRoot is the root of an index b-tree */ + int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ +){ + Schema *pSchema = (Schema *)pBtree->pBt->pSchema; + Pgno iTab = 0; + BtLock *pLock; + + /* If this database is not shareable, or if the client is reading + ** and has the read-uncommitted flag set, then no lock is required. + ** Return true immediately. + */ + if( (pBtree->sharable==0) + || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted)) + ){ + return 1; + } + + /* If the client is reading or writing an index and the schema is + ** not loaded, then it is too difficult to actually check to see if + ** the correct locks are held. So do not bother - just return true. + ** This case does not come up very often anyhow. + */ + if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){ + return 1; + } + + /* Figure out the root-page that the lock should be held on. For table + ** b-trees, this is just the root page of the b-tree being read or + ** written. For index b-trees, it is the root page of the associated + ** table. */ + if( isIndex ){ + HashElem *p; + for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ + Index *pIdx = (Index *)sqliteHashData(p); + if( pIdx->tnum==(int)iRoot ){ + iTab = pIdx->pTable->tnum; + } + } + }else{ + iTab = iRoot; + } + + /* Search for the required lock. Either a write-lock on root-page iTab, a + ** write-lock on the schema table, or (if the client is reading) a + ** read-lock on iTab will suffice. Return 1 if any of these are found. */ + for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){ + if( pLock->pBtree==pBtree + && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1)) + && pLock->eLock>=eLockType + ){ + return 1; + } + } + + /* Failed to find the required lock. */ + return 0; +} +#endif /* SQLITE_DEBUG */ + +#ifdef SQLITE_DEBUG +/* +**** This function may be used as part of assert() statements only. **** +** +** Return true if it would be illegal for pBtree to write into the +** table or index rooted at iRoot because other shared connections are +** simultaneously reading that same table or index. +** +** It is illegal for pBtree to write if some other Btree object that +** shares the same BtShared object is currently reading or writing +** the iRoot table. Except, if the other Btree object has the +** read-uncommitted flag set, then it is OK for the other object to +** have a read cursor. +** +** For example, before writing to any part of the table or index +** rooted at page iRoot, one should call: +** +** assert( !hasReadConflicts(pBtree, iRoot) ); +*/ +static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ + BtCursor *p; + for(p=pBtree->pBt->pCursor; p; p=p->pNext){ + if( p->pgnoRoot==iRoot + && p->pBtree!=pBtree + && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted) + ){ + return 1; + } + } + return 0; +} +#endif /* #ifdef SQLITE_DEBUG */ + +/* +** Query to see if Btree handle p may obtain a lock of type eLock +** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return +** SQLITE_OK if the lock may be obtained (by calling +** setSharedCacheTableLock()), or SQLITE_LOCKED if not. +*/ +static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ + BtShared *pBt = p->pBt; + BtLock *pIter; + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); + assert( p->db!=0 ); + assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 ); + + /* If requesting a write-lock, then the Btree must have an open write + ** transaction on this file. And, obviously, for this to be so there + ** must be an open write transaction on the file itself. + */ + assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) ); + assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); + + /* This routine is a no-op if the shared-cache is not enabled */ + if( !p->sharable ){ + return SQLITE_OK; + } + + /* If some other connection is holding an exclusive lock, the + ** requested lock may not be obtained. + */ + if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ + sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); + return SQLITE_LOCKED_SHAREDCACHE; + } + + for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ + /* The condition (pIter->eLock!=eLock) in the following if(...) + ** statement is a simplification of: + ** + ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) + ** + ** since we know that if eLock==WRITE_LOCK, then no other connection + ** may hold a WRITE_LOCK on any table in this file (since there can + ** only be a single writer). + */ + assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); + assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); + if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ + sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); + if( eLock==WRITE_LOCK ){ + assert( p==pBt->pWriter ); + pBt->btsFlags |= BTS_PENDING; + } + return SQLITE_LOCKED_SHAREDCACHE; + } + } + return SQLITE_OK; +} +#endif /* !SQLITE_OMIT_SHARED_CACHE */ + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** Add a lock on the table with root-page iTable to the shared-btree used +** by Btree handle p. Parameter eLock must be either READ_LOCK or +** WRITE_LOCK. +** +** This function assumes the following: +** +** (a) The specified Btree object p is connected to a sharable +** database (one with the BtShared.sharable flag set), and +** +** (b) No other Btree objects hold a lock that conflicts +** with the requested lock (i.e. querySharedCacheTableLock() has +** already been called and returned SQLITE_OK). +** +** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM +** is returned if a malloc attempt fails. +*/ +static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ + BtShared *pBt = p->pBt; + BtLock *pLock = 0; + BtLock *pIter; + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); + assert( p->db!=0 ); + + /* A connection with the read-uncommitted flag set will never try to + ** obtain a read-lock using this function. The only read-lock obtained + ** by a connection in read-uncommitted mode is on the sqlite_master + ** table, and that lock is obtained in BtreeBeginTrans(). */ + assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK ); + + /* This function should only be called on a sharable b-tree after it + ** has been determined that no other b-tree holds a conflicting lock. */ + assert( p->sharable ); + assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); + + /* First search the list for an existing lock on this table. */ + for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ + if( pIter->iTable==iTable && pIter->pBtree==p ){ + pLock = pIter; + break; + } + } + + /* If the above search did not find a BtLock struct associating Btree p + ** with table iTable, allocate one and link it into the list. + */ + if( !pLock ){ + pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); + if( !pLock ){ + return SQLITE_NOMEM; + } + pLock->iTable = iTable; + pLock->pBtree = p; + pLock->pNext = pBt->pLock; + pBt->pLock = pLock; + } + + /* Set the BtLock.eLock variable to the maximum of the current lock + ** and the requested lock. This means if a write-lock was already held + ** and a read-lock requested, we don't incorrectly downgrade the lock. + */ + assert( WRITE_LOCK>READ_LOCK ); + if( eLock>pLock->eLock ){ + pLock->eLock = eLock; + } + + return SQLITE_OK; +} +#endif /* !SQLITE_OMIT_SHARED_CACHE */ + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** Release all the table locks (locks obtained via calls to +** the setSharedCacheTableLock() procedure) held by Btree object p. +** +** This function assumes that Btree p has an open read or write +** transaction. If it does not, then the BTS_PENDING flag +** may be incorrectly cleared. +*/ +static void clearAllSharedCacheTableLocks(Btree *p){ + BtShared *pBt = p->pBt; + BtLock **ppIter = &pBt->pLock; + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( p->sharable || 0==*ppIter ); + assert( p->inTrans>0 ); + + while( *ppIter ){ + BtLock *pLock = *ppIter; + assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree ); + assert( pLock->pBtree->inTrans>=pLock->eLock ); + if( pLock->pBtree==p ){ + *ppIter = pLock->pNext; + assert( pLock->iTable!=1 || pLock==&p->lock ); + if( pLock->iTable!=1 ){ + sqlite3_free(pLock); + } + }else{ + ppIter = &pLock->pNext; + } + } + + assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter ); + if( pBt->pWriter==p ){ + pBt->pWriter = 0; + pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); + }else if( pBt->nTransaction==2 ){ + /* This function is called when Btree p is concluding its + ** transaction. If there currently exists a writer, and p is not + ** that writer, then the number of locks held by connections other + ** than the writer must be about to drop to zero. In this case + ** set the BTS_PENDING flag to 0. + ** + ** If there is not currently a writer, then BTS_PENDING must + ** be zero already. So this next line is harmless in that case. + */ + pBt->btsFlags &= ~BTS_PENDING; + } +} + +/* +** This function changes all write-locks held by Btree p into read-locks. +*/ +static void downgradeAllSharedCacheTableLocks(Btree *p){ + BtShared *pBt = p->pBt; + if( pBt->pWriter==p ){ + BtLock *pLock; + pBt->pWriter = 0; + pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); + for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ + assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); + pLock->eLock = READ_LOCK; + } + } +} + +#endif /* SQLITE_OMIT_SHARED_CACHE */ + +static void releasePage(MemPage *pPage); /* Forward reference */ + +/* +***** This routine is used inside of assert() only **** +** +** Verify that the cursor holds the mutex on its BtShared +*/ +#ifdef SQLITE_DEBUG +static int cursorHoldsMutex(BtCursor *p){ + return sqlite3_mutex_held(p->pBt->mutex); +} +#endif + + +#ifndef SQLITE_OMIT_INCRBLOB +/* +** Invalidate the overflow page-list cache for cursor pCur, if any. +*/ +static void invalidateOverflowCache(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + sqlite3_free(pCur->aOverflow); + pCur->aOverflow = 0; +} + +/* +** Invalidate the overflow page-list cache for all cursors opened +** on the shared btree structure pBt. +*/ +static void invalidateAllOverflowCache(BtShared *pBt){ + BtCursor *p; + assert( sqlite3_mutex_held(pBt->mutex) ); + for(p=pBt->pCursor; p; p=p->pNext){ + invalidateOverflowCache(p); + } +} + +/* +** This function is called before modifying the contents of a table +** to invalidate any incrblob cursors that are open on the +** row or one of the rows being modified. +** +** If argument isClearTable is true, then the entire contents of the +** table is about to be deleted. In this case invalidate all incrblob +** cursors open on any row within the table with root-page pgnoRoot. +** +** Otherwise, if argument isClearTable is false, then the row with +** rowid iRow is being replaced or deleted. In this case invalidate +** only those incrblob cursors open on that specific row. +*/ +static void invalidateIncrblobCursors( + Btree *pBtree, /* The database file to check */ + i64 iRow, /* The rowid that might be changing */ + int isClearTable /* True if all rows are being deleted */ +){ + BtCursor *p; + BtShared *pBt = pBtree->pBt; + assert( sqlite3BtreeHoldsMutex(pBtree) ); + for(p=pBt->pCursor; p; p=p->pNext){ + if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){ + p->eState = CURSOR_INVALID; + } + } +} + +#else + /* Stub functions when INCRBLOB is omitted */ + #define invalidateOverflowCache(x) + #define invalidateAllOverflowCache(x) + #define invalidateIncrblobCursors(x,y,z) +#endif /* SQLITE_OMIT_INCRBLOB */ + +/* +** Set bit pgno of the BtShared.pHasContent bitvec. This is called +** when a page that previously contained data becomes a free-list leaf +** page. +** +** The BtShared.pHasContent bitvec exists to work around an obscure +** bug caused by the interaction of two useful IO optimizations surrounding +** free-list leaf pages: +** +** 1) When all data is deleted from a page and the page becomes +** a free-list leaf page, the page is not written to the database +** (as free-list leaf pages contain no meaningful data). Sometimes +** such a page is not even journalled (as it will not be modified, +** why bother journalling it?). +** +** 2) When a free-list leaf page is reused, its content is not read +** from the database or written to the journal file (why should it +** be, if it is not at all meaningful?). +** +** By themselves, these optimizations work fine and provide a handy +** performance boost to bulk delete or insert operations. However, if +** a page is moved to the free-list and then reused within the same +** transaction, a problem comes up. If the page is not journalled when +** it is moved to the free-list and it is also not journalled when it +** is extracted from the free-list and reused, then the original data +** may be lost. In the event of a rollback, it may not be possible +** to restore the database to its original configuration. +** +** The solution is the BtShared.pHasContent bitvec. Whenever a page is +** moved to become a free-list leaf page, the corresponding bit is +** set in the bitvec. Whenever a leaf page is extracted from the free-list, +** optimization 2 above is omitted if the corresponding bit is already +** set in BtShared.pHasContent. The contents of the bitvec are cleared +** at the end of every transaction. +*/ +static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ + int rc = SQLITE_OK; + if( !pBt->pHasContent ){ + assert( pgno<=pBt->nPage ); + pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); + if( !pBt->pHasContent ){ + rc = SQLITE_NOMEM; + } + } + if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ + rc = sqlite3BitvecSet(pBt->pHasContent, pgno); + } + return rc; +} + +/* +** Query the BtShared.pHasContent vector. +** +** This function is called when a free-list leaf page is removed from the +** free-list for reuse. It returns false if it is safe to retrieve the +** page from the pager layer with the 'no-content' flag set. True otherwise. +*/ +static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ + Bitvec *p = pBt->pHasContent; + return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno))); +} + +/* +** Clear (destroy) the BtShared.pHasContent bitvec. This should be +** invoked at the conclusion of each write-transaction. +*/ +static void btreeClearHasContent(BtShared *pBt){ + sqlite3BitvecDestroy(pBt->pHasContent); + pBt->pHasContent = 0; +} + +/* +** Release all of the apPage[] pages for a cursor. +*/ +static void btreeReleaseAllCursorPages(BtCursor *pCur){ + int i; + for(i=0; i<=pCur->iPage; i++){ + releasePage(pCur->apPage[i]); + pCur->apPage[i] = 0; + } + pCur->iPage = -1; +} + + +/* +** Save the current cursor position in the variables BtCursor.nKey +** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. +** +** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) +** prior to calling this routine. +*/ +static int saveCursorPosition(BtCursor *pCur){ + int rc; + + assert( CURSOR_VALID==pCur->eState ); + assert( 0==pCur->pKey ); + assert( cursorHoldsMutex(pCur) ); + + rc = sqlite3BtreeKeySize(pCur, &pCur->nKey); + assert( rc==SQLITE_OK ); /* KeySize() cannot fail */ + + /* If this is an intKey table, then the above call to BtreeKeySize() + ** stores the integer key in pCur->nKey. In this case this value is + ** all that is required. Otherwise, if pCur is not open on an intKey + ** table, then malloc space for and store the pCur->nKey bytes of key + ** data. + */ + if( 0==pCur->apPage[0]->intKey ){ + void *pKey = sqlite3Malloc( (int)pCur->nKey ); + if( pKey ){ + rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey); + if( rc==SQLITE_OK ){ + pCur->pKey = pKey; + }else{ + sqlite3_free(pKey); + } + }else{ + rc = SQLITE_NOMEM; + } + } + assert( !pCur->apPage[0]->intKey || !pCur->pKey ); + + if( rc==SQLITE_OK ){ + btreeReleaseAllCursorPages(pCur); + pCur->eState = CURSOR_REQUIRESEEK; + } + + invalidateOverflowCache(pCur); + return rc; +} + +/* +** Save the positions of all cursors (except pExcept) that are open on +** the table with root-page iRoot. Usually, this is called just before cursor +** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()). +*/ +static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ + BtCursor *p; + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( pExcept==0 || pExcept->pBt==pBt ); + for(p=pBt->pCursor; p; p=p->pNext){ + if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ + if( p->eState==CURSOR_VALID ){ + int rc = saveCursorPosition(p); + if( SQLITE_OK!=rc ){ + return rc; + } + }else{ + testcase( p->iPage>0 ); + btreeReleaseAllCursorPages(p); + } + } + } + return SQLITE_OK; +} + +/* +** Clear the current cursor position. +*/ +SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + sqlite3_free(pCur->pKey); + pCur->pKey = 0; + pCur->eState = CURSOR_INVALID; +} + +/* +** In this version of BtreeMoveto, pKey is a packed index record +** such as is generated by the OP_MakeRecord opcode. Unpack the +** record and then call BtreeMovetoUnpacked() to do the work. +*/ +static int btreeMoveto( + BtCursor *pCur, /* Cursor open on the btree to be searched */ + const void *pKey, /* Packed key if the btree is an index */ + i64 nKey, /* Integer key for tables. Size of pKey for indices */ + int bias, /* Bias search to the high end */ + int *pRes /* Write search results here */ +){ + int rc; /* Status code */ + UnpackedRecord *pIdxKey; /* Unpacked index key */ + char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */ + char *pFree = 0; + + if( pKey ){ + assert( nKey==(i64)(int)nKey ); + pIdxKey = sqlite3VdbeAllocUnpackedRecord( + pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree + ); + if( pIdxKey==0 ) return SQLITE_NOMEM; + sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey); + }else{ + pIdxKey = 0; + } + rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); + if( pFree ){ + sqlite3DbFree(pCur->pKeyInfo->db, pFree); + } + return rc; +} + +/* +** Restore the cursor to the position it was in (or as close to as possible) +** when saveCursorPosition() was called. Note that this call deletes the +** saved position info stored by saveCursorPosition(), so there can be +** at most one effective restoreCursorPosition() call after each +** saveCursorPosition(). +*/ +static int btreeRestoreCursorPosition(BtCursor *pCur){ + int rc; + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState>=CURSOR_REQUIRESEEK ); + if( pCur->eState==CURSOR_FAULT ){ + return pCur->skipNext; + } + pCur->eState = CURSOR_INVALID; + rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext); + if( rc==SQLITE_OK ){ + sqlite3_free(pCur->pKey); + pCur->pKey = 0; + assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); + if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ + pCur->eState = CURSOR_SKIPNEXT; + } + } + return rc; +} + +#define restoreCursorPosition(p) \ + (p->eState>=CURSOR_REQUIRESEEK ? \ + btreeRestoreCursorPosition(p) : \ + SQLITE_OK) + +/* +** Determine whether or not a cursor has moved from the position it +** was last placed at. Cursors can move when the row they are pointing +** at is deleted out from under them. +** +** This routine returns an error code if something goes wrong. The +** integer *pHasMoved is set to one if the cursor has moved and 0 if not. +*/ +SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){ + int rc; + + rc = restoreCursorPosition(pCur); + if( rc ){ + *pHasMoved = 1; + return rc; + } + if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){ + *pHasMoved = 1; + }else{ + *pHasMoved = 0; + } + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_AUTOVACUUM +/* +** Given a page number of a regular database page, return the page +** number for the pointer-map page that contains the entry for the +** input page number. +** +** Return 0 (not a valid page) for pgno==1 since there is +** no pointer map associated with page 1. The integrity_check logic +** requires that ptrmapPageno(*,1)!=1. +*/ +static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ + int nPagesPerMapPage; + Pgno iPtrMap, ret; + assert( sqlite3_mutex_held(pBt->mutex) ); + if( pgno<2 ) return 0; + nPagesPerMapPage = (pBt->usableSize/5)+1; + iPtrMap = (pgno-2)/nPagesPerMapPage; + ret = (iPtrMap*nPagesPerMapPage) + 2; + if( ret==PENDING_BYTE_PAGE(pBt) ){ + ret++; + } + return ret; +} + +/* +** Write an entry into the pointer map. +** +** This routine updates the pointer map entry for page number 'key' +** so that it maps to type 'eType' and parent page number 'pgno'. +** +** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is +** a no-op. If an error occurs, the appropriate error code is written +** into *pRC. +*/ +static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ + DbPage *pDbPage; /* The pointer map page */ + u8 *pPtrmap; /* The pointer map data */ + Pgno iPtrmap; /* The pointer map page number */ + int offset; /* Offset in pointer map page */ + int rc; /* Return code from subfunctions */ + + if( *pRC ) return; + + assert( sqlite3_mutex_held(pBt->mutex) ); + /* The master-journal page number must never be used as a pointer map page */ + assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); + + assert( pBt->autoVacuum ); + if( key==0 ){ + *pRC = SQLITE_CORRUPT_BKPT; + return; + } + iPtrmap = PTRMAP_PAGENO(pBt, key); + rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); + if( rc!=SQLITE_OK ){ + *pRC = rc; + return; + } + offset = PTRMAP_PTROFFSET(iPtrmap, key); + if( offset<0 ){ + *pRC = SQLITE_CORRUPT_BKPT; + goto ptrmap_exit; + } + assert( offset <= (int)pBt->usableSize-5 ); + pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); + + if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ + TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); + *pRC= rc = sqlite3PagerWrite(pDbPage); + if( rc==SQLITE_OK ){ + pPtrmap[offset] = eType; + put4byte(&pPtrmap[offset+1], parent); + } + } + +ptrmap_exit: + sqlite3PagerUnref(pDbPage); +} + +/* +** Read an entry from the pointer map. +** +** This routine retrieves the pointer map entry for page 'key', writing +** the type and parent page number to *pEType and *pPgno respectively. +** An error code is returned if something goes wrong, otherwise SQLITE_OK. +*/ +static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ + DbPage *pDbPage; /* The pointer map page */ + int iPtrmap; /* Pointer map page index */ + u8 *pPtrmap; /* Pointer map page data */ + int offset; /* Offset of entry in pointer map */ + int rc; + + assert( sqlite3_mutex_held(pBt->mutex) ); + + iPtrmap = PTRMAP_PAGENO(pBt, key); + rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); + if( rc!=0 ){ + return rc; + } + pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); + + offset = PTRMAP_PTROFFSET(iPtrmap, key); + if( offset<0 ){ + sqlite3PagerUnref(pDbPage); + return SQLITE_CORRUPT_BKPT; + } + assert( offset <= (int)pBt->usableSize-5 ); + assert( pEType!=0 ); + *pEType = pPtrmap[offset]; + if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); + + sqlite3PagerUnref(pDbPage); + if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT; + return SQLITE_OK; +} + +#else /* if defined SQLITE_OMIT_AUTOVACUUM */ + #define ptrmapPut(w,x,y,z,rc) + #define ptrmapGet(w,x,y,z) SQLITE_OK + #define ptrmapPutOvflPtr(x, y, rc) +#endif + +/* +** Given a btree page and a cell index (0 means the first cell on +** the page, 1 means the second cell, and so forth) return a pointer +** to the cell content. +** +** This routine works only for pages that do not contain overflow cells. +*/ +#define findCell(P,I) \ + ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)]))) +#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I))))) + + +/* +** This a more complex version of findCell() that works for +** pages that do contain overflow cells. +*/ +static u8 *findOverflowCell(MemPage *pPage, int iCell){ + int i; + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + for(i=pPage->nOverflow-1; i>=0; i--){ + int k; + k = pPage->aiOvfl[i]; + if( k<=iCell ){ + if( k==iCell ){ + return pPage->apOvfl[i]; + } + iCell--; + } + } + return findCell(pPage, iCell); +} + +/* +** Parse a cell content block and fill in the CellInfo structure. There +** are two versions of this function. btreeParseCell() takes a +** cell index as the second argument and btreeParseCellPtr() +** takes a pointer to the body of the cell as its second argument. +** +** Within this file, the parseCell() macro can be called instead of +** btreeParseCellPtr(). Using some compilers, this will be faster. +*/ +static void btreeParseCellPtr( + MemPage *pPage, /* Page containing the cell */ + u8 *pCell, /* Pointer to the cell text. */ + CellInfo *pInfo /* Fill in this structure */ +){ + u16 n; /* Number bytes in cell content header */ + u32 nPayload; /* Number of bytes of cell payload */ + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + + pInfo->pCell = pCell; + assert( pPage->leaf==0 || pPage->leaf==1 ); + n = pPage->childPtrSize; + assert( n==4-4*pPage->leaf ); + if( pPage->intKey ){ + if( pPage->hasData ){ + assert( n==0 ); + n = getVarint32(pCell, nPayload); + }else{ + nPayload = 0; + } + n += getVarint(&pCell[n], (u64*)&pInfo->nKey); + pInfo->nData = nPayload; + }else{ + pInfo->nData = 0; + n += getVarint32(&pCell[n], nPayload); + pInfo->nKey = nPayload; + } + pInfo->nPayload = nPayload; + pInfo->nHeader = n; + testcase( nPayload==pPage->maxLocal ); + testcase( nPayload==pPage->maxLocal+1 ); + if( likely(nPayload<=pPage->maxLocal) ){ + /* This is the (easy) common case where the entire payload fits + ** on the local page. No overflow is required. + */ + if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4; + pInfo->nLocal = (u16)nPayload; + pInfo->iOverflow = 0; + }else{ + /* If the payload will not fit completely on the local page, we have + ** to decide how much to store locally and how much to spill onto + ** overflow pages. The strategy is to minimize the amount of unused + ** space on overflow pages while keeping the amount of local storage + ** in between minLocal and maxLocal. + ** + ** Warning: changing the way overflow payload is distributed in any + ** way will result in an incompatible file format. + */ + int minLocal; /* Minimum amount of payload held locally */ + int maxLocal; /* Maximum amount of payload held locally */ + int surplus; /* Overflow payload available for local storage */ + + minLocal = pPage->minLocal; + maxLocal = pPage->maxLocal; + surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4); + testcase( surplus==maxLocal ); + testcase( surplus==maxLocal+1 ); + if( surplus <= maxLocal ){ + pInfo->nLocal = (u16)surplus; + }else{ + pInfo->nLocal = (u16)minLocal; + } + pInfo->iOverflow = (u16)(pInfo->nLocal + n); + pInfo->nSize = pInfo->iOverflow + 4; + } +} +#define parseCell(pPage, iCell, pInfo) \ + btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo)) +static void btreeParseCell( + MemPage *pPage, /* Page containing the cell */ + int iCell, /* The cell index. First cell is 0 */ + CellInfo *pInfo /* Fill in this structure */ +){ + parseCell(pPage, iCell, pInfo); +} + +/* +** Compute the total number of bytes that a Cell needs in the cell +** data area of the btree-page. The return number includes the cell +** data header and the local payload, but not any overflow page or +** the space used by the cell pointer. +*/ +static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ + u8 *pIter = &pCell[pPage->childPtrSize]; + u32 nSize; + +#ifdef SQLITE_DEBUG + /* The value returned by this function should always be the same as + ** the (CellInfo.nSize) value found by doing a full parse of the + ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of + ** this function verifies that this invariant is not violated. */ + CellInfo debuginfo; + btreeParseCellPtr(pPage, pCell, &debuginfo); +#endif + + if( pPage->intKey ){ + u8 *pEnd; + if( pPage->hasData ){ + pIter += getVarint32(pIter, nSize); + }else{ + nSize = 0; + } + + /* pIter now points at the 64-bit integer key value, a variable length + ** integer. The following block moves pIter to point at the first byte + ** past the end of the key value. */ + pEnd = &pIter[9]; + while( (*pIter++)&0x80 && pItermaxLocal ); + testcase( nSize==pPage->maxLocal+1 ); + if( nSize>pPage->maxLocal ){ + int minLocal = pPage->minLocal; + nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); + testcase( nSize==pPage->maxLocal ); + testcase( nSize==pPage->maxLocal+1 ); + if( nSize>pPage->maxLocal ){ + nSize = minLocal; + } + nSize += 4; + } + nSize += (u32)(pIter - pCell); + + /* The minimum size of any cell is 4 bytes. */ + if( nSize<4 ){ + nSize = 4; + } + + assert( nSize==debuginfo.nSize ); + return (u16)nSize; +} + +#ifdef SQLITE_DEBUG +/* This variation on cellSizePtr() is used inside of assert() statements +** only. */ +static u16 cellSize(MemPage *pPage, int iCell){ + return cellSizePtr(pPage, findCell(pPage, iCell)); +} +#endif + +#ifndef SQLITE_OMIT_AUTOVACUUM +/* +** If the cell pCell, part of page pPage contains a pointer +** to an overflow page, insert an entry into the pointer-map +** for the overflow page. +*/ +static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ + CellInfo info; + if( *pRC ) return; + assert( pCell!=0 ); + btreeParseCellPtr(pPage, pCell, &info); + assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload ); + if( info.iOverflow ){ + Pgno ovfl = get4byte(&pCell[info.iOverflow]); + ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); + } +} +#endif + + +/* +** Defragment the page given. All Cells are moved to the +** end of the page and all free space is collected into one +** big FreeBlk that occurs in between the header and cell +** pointer array and the cell content area. +*/ +static int defragmentPage(MemPage *pPage){ + int i; /* Loop counter */ + int pc; /* Address of a i-th cell */ + int hdr; /* Offset to the page header */ + int size; /* Size of a cell */ + int usableSize; /* Number of usable bytes on a page */ + int cellOffset; /* Offset to the cell pointer array */ + int cbrk; /* Offset to the cell content area */ + int nCell; /* Number of cells on the page */ + unsigned char *data; /* The page data */ + unsigned char *temp; /* Temp area for cell content */ + int iCellFirst; /* First allowable cell index */ + int iCellLast; /* Last possible cell index */ + + + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( pPage->pBt!=0 ); + assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); + assert( pPage->nOverflow==0 ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + temp = sqlite3PagerTempSpace(pPage->pBt->pPager); + data = pPage->aData; + hdr = pPage->hdrOffset; + cellOffset = pPage->cellOffset; + nCell = pPage->nCell; + assert( nCell==get2byte(&data[hdr+3]) ); + usableSize = pPage->pBt->usableSize; + cbrk = get2byte(&data[hdr+5]); + memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk); + cbrk = usableSize; + iCellFirst = cellOffset + 2*nCell; + iCellLast = usableSize - 4; + for(i=0; iiCellLast ){ + return SQLITE_CORRUPT_BKPT; + } +#endif + assert( pc>=iCellFirst && pc<=iCellLast ); + size = cellSizePtr(pPage, &temp[pc]); + cbrk -= size; +#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) + if( cbrkusableSize ){ + return SQLITE_CORRUPT_BKPT; + } +#endif + assert( cbrk+size<=usableSize && cbrk>=iCellFirst ); + testcase( cbrk+size==usableSize ); + testcase( pc+size==usableSize ); + memcpy(&data[cbrk], &temp[pc], size); + put2byte(pAddr, cbrk); + } + assert( cbrk>=iCellFirst ); + put2byte(&data[hdr+5], cbrk); + data[hdr+1] = 0; + data[hdr+2] = 0; + data[hdr+7] = 0; + memset(&data[iCellFirst], 0, cbrk-iCellFirst); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + if( cbrk-iCellFirst!=pPage->nFree ){ + return SQLITE_CORRUPT_BKPT; + } + return SQLITE_OK; +} + +/* +** Allocate nByte bytes of space from within the B-Tree page passed +** as the first argument. Write into *pIdx the index into pPage->aData[] +** of the first byte of allocated space. Return either SQLITE_OK or +** an error code (usually SQLITE_CORRUPT). +** +** The caller guarantees that there is sufficient space to make the +** allocation. This routine might need to defragment in order to bring +** all the space together, however. This routine will avoid using +** the first two bytes past the cell pointer area since presumably this +** allocation is being made in order to insert a new cell, so we will +** also end up needing a new cell pointer. +*/ +static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ + const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ + u8 * const data = pPage->aData; /* Local cache of pPage->aData */ + int nFrag; /* Number of fragmented bytes on pPage */ + int top; /* First byte of cell content area */ + int gap; /* First byte of gap between cell pointers and cell content */ + int rc; /* Integer return code */ + int usableSize; /* Usable size of the page */ + + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( pPage->pBt ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( nByte>=0 ); /* Minimum cell size is 4 */ + assert( pPage->nFree>=nByte ); + assert( pPage->nOverflow==0 ); + usableSize = pPage->pBt->usableSize; + assert( nByte < usableSize-8 ); + + nFrag = data[hdr+7]; + assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); + gap = pPage->cellOffset + 2*pPage->nCell; + top = get2byteNotZero(&data[hdr+5]); + if( gap>top ) return SQLITE_CORRUPT_BKPT; + testcase( gap+2==top ); + testcase( gap+1==top ); + testcase( gap==top ); + + if( nFrag>=60 ){ + /* Always defragment highly fragmented pages */ + rc = defragmentPage(pPage); + if( rc ) return rc; + top = get2byteNotZero(&data[hdr+5]); + }else if( gap+2<=top ){ + /* Search the freelist looking for a free slot big enough to satisfy + ** the request. The allocation is made from the first free slot in + ** the list that is large enough to accommodate it. + */ + int pc, addr; + for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){ + int size; /* Size of the free slot */ + if( pc>usableSize-4 || pc=nByte ){ + int x = size - nByte; + testcase( x==4 ); + testcase( x==3 ); + if( x<4 ){ + /* Remove the slot from the free-list. Update the number of + ** fragmented bytes within the page. */ + memcpy(&data[addr], &data[pc], 2); + data[hdr+7] = (u8)(nFrag + x); + }else if( size+pc > usableSize ){ + return SQLITE_CORRUPT_BKPT; + }else{ + /* The slot remains on the free-list. Reduce its size to account + ** for the portion used by the new allocation. */ + put2byte(&data[pc+2], x); + } + *pIdx = pc + x; + return SQLITE_OK; + } + } + } + + /* Check to make sure there is enough space in the gap to satisfy + ** the allocation. If not, defragment. + */ + testcase( gap+2+nByte==top ); + if( gap+2+nByte>top ){ + rc = defragmentPage(pPage); + if( rc ) return rc; + top = get2byteNotZero(&data[hdr+5]); + assert( gap+nByte<=top ); + } + + + /* Allocate memory from the gap in between the cell pointer array + ** and the cell content area. The btreeInitPage() call has already + ** validated the freelist. Given that the freelist is valid, there + ** is no way that the allocation can extend off the end of the page. + ** The assert() below verifies the previous sentence. + */ + top -= nByte; + put2byte(&data[hdr+5], top); + assert( top+nByte <= (int)pPage->pBt->usableSize ); + *pIdx = top; + return SQLITE_OK; +} + +/* +** Return a section of the pPage->aData to the freelist. +** The first byte of the new free block is pPage->aDisk[start] +** and the size of the block is "size" bytes. +** +** Most of the effort here is involved in coalesing adjacent +** free blocks into a single big free block. +*/ +static int freeSpace(MemPage *pPage, int start, int size){ + int addr, pbegin, hdr; + int iLast; /* Largest possible freeblock offset */ + unsigned char *data = pPage->aData; + + assert( pPage->pBt!=0 ); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( start>=pPage->hdrOffset+6+pPage->childPtrSize ); + assert( (start + size) <= (int)pPage->pBt->usableSize ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( size>=0 ); /* Minimum cell size is 4 */ + + if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){ + /* Overwrite deleted information with zeros when the secure_delete + ** option is enabled */ + memset(&data[start], 0, size); + } + + /* Add the space back into the linked list of freeblocks. Note that + ** even though the freeblock list was checked by btreeInitPage(), + ** btreeInitPage() did not detect overlapping cells or + ** freeblocks that overlapped cells. Nor does it detect when the + ** cell content area exceeds the value in the page header. If these + ** situations arise, then subsequent insert operations might corrupt + ** the freelist. So we do need to check for corruption while scanning + ** the freelist. + */ + hdr = pPage->hdrOffset; + addr = hdr + 1; + iLast = pPage->pBt->usableSize - 4; + assert( start<=iLast ); + while( (pbegin = get2byte(&data[addr]))0 ){ + if( pbeginiLast ){ + return SQLITE_CORRUPT_BKPT; + } + assert( pbegin>addr || pbegin==0 ); + put2byte(&data[addr], start); + put2byte(&data[start], pbegin); + put2byte(&data[start+2], size); + pPage->nFree = pPage->nFree + (u16)size; + + /* Coalesce adjacent free blocks */ + addr = hdr + 1; + while( (pbegin = get2byte(&data[addr]))>0 ){ + int pnext, psize, x; + assert( pbegin>addr ); + assert( pbegin <= (int)pPage->pBt->usableSize-4 ); + pnext = get2byte(&data[pbegin]); + psize = get2byte(&data[pbegin+2]); + if( pbegin + psize + 3 >= pnext && pnext>0 ){ + int frag = pnext - (pbegin+psize); + if( (frag<0) || (frag>(int)data[hdr+7]) ){ + return SQLITE_CORRUPT_BKPT; + } + data[hdr+7] -= (u8)frag; + x = get2byte(&data[pnext]); + put2byte(&data[pbegin], x); + x = pnext + get2byte(&data[pnext+2]) - pbegin; + put2byte(&data[pbegin+2], x); + }else{ + addr = pbegin; + } + } + + /* If the cell content area begins with a freeblock, remove it. */ + if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){ + int top; + pbegin = get2byte(&data[hdr+1]); + memcpy(&data[hdr+1], &data[pbegin], 2); + top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]); + put2byte(&data[hdr+5], top); + } + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + return SQLITE_OK; +} + +/* +** Decode the flags byte (the first byte of the header) for a page +** and initialize fields of the MemPage structure accordingly. +** +** Only the following combinations are supported. Anything different +** indicates a corrupt database files: +** +** PTF_ZERODATA +** PTF_ZERODATA | PTF_LEAF +** PTF_LEAFDATA | PTF_INTKEY +** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF +*/ +static int decodeFlags(MemPage *pPage, int flagByte){ + BtShared *pBt; /* A copy of pPage->pBt */ + + assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); + flagByte &= ~PTF_LEAF; + pPage->childPtrSize = 4-4*pPage->leaf; + pBt = pPage->pBt; + if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ + pPage->intKey = 1; + pPage->hasData = pPage->leaf; + pPage->maxLocal = pBt->maxLeaf; + pPage->minLocal = pBt->minLeaf; + }else if( flagByte==PTF_ZERODATA ){ + pPage->intKey = 0; + pPage->hasData = 0; + pPage->maxLocal = pBt->maxLocal; + pPage->minLocal = pBt->minLocal; + }else{ + return SQLITE_CORRUPT_BKPT; + } + pPage->max1bytePayload = pBt->max1bytePayload; + return SQLITE_OK; +} + +/* +** Initialize the auxiliary information for a disk block. +** +** Return SQLITE_OK on success. If we see that the page does +** not contain a well-formed database page, then return +** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not +** guarantee that the page is well-formed. It only shows that +** we failed to detect any corruption. +*/ +static int btreeInitPage(MemPage *pPage){ + + assert( pPage->pBt!=0 ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); + assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); + assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); + + if( !pPage->isInit ){ + u16 pc; /* Address of a freeblock within pPage->aData[] */ + u8 hdr; /* Offset to beginning of page header */ + u8 *data; /* Equal to pPage->aData */ + BtShared *pBt; /* The main btree structure */ + int usableSize; /* Amount of usable space on each page */ + u16 cellOffset; /* Offset from start of page to first cell pointer */ + int nFree; /* Number of unused bytes on the page */ + int top; /* First byte of the cell content area */ + int iCellFirst; /* First allowable cell or freeblock offset */ + int iCellLast; /* Last possible cell or freeblock offset */ + + pBt = pPage->pBt; + + hdr = pPage->hdrOffset; + data = pPage->aData; + if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT; + assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); + pPage->maskPage = (u16)(pBt->pageSize - 1); + pPage->nOverflow = 0; + usableSize = pBt->usableSize; + pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf; + pPage->aDataEnd = &data[usableSize]; + pPage->aCellIdx = &data[cellOffset]; + top = get2byteNotZero(&data[hdr+5]); + pPage->nCell = get2byte(&data[hdr+3]); + if( pPage->nCell>MX_CELL(pBt) ){ + /* To many cells for a single page. The page must be corrupt */ + return SQLITE_CORRUPT_BKPT; + } + testcase( pPage->nCell==MX_CELL(pBt) ); + + /* A malformed database page might cause us to read past the end + ** of page when parsing a cell. + ** + ** The following block of code checks early to see if a cell extends + ** past the end of a page boundary and causes SQLITE_CORRUPT to be + ** returned if it does. + */ + iCellFirst = cellOffset + 2*pPage->nCell; + iCellLast = usableSize - 4; +#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) + { + int i; /* Index into the cell pointer array */ + int sz; /* Size of a cell */ + + if( !pPage->leaf ) iCellLast--; + for(i=0; inCell; i++){ + pc = get2byte(&data[cellOffset+i*2]); + testcase( pc==iCellFirst ); + testcase( pc==iCellLast ); + if( pciCellLast ){ + return SQLITE_CORRUPT_BKPT; + } + sz = cellSizePtr(pPage, &data[pc]); + testcase( pc+sz==usableSize ); + if( pc+sz>usableSize ){ + return SQLITE_CORRUPT_BKPT; + } + } + if( !pPage->leaf ) iCellLast++; + } +#endif + + /* Compute the total free space on the page */ + pc = get2byte(&data[hdr+1]); + nFree = data[hdr+7] + top; + while( pc>0 ){ + u16 next, size; + if( pciCellLast ){ + /* Start of free block is off the page */ + return SQLITE_CORRUPT_BKPT; + } + next = get2byte(&data[pc]); + size = get2byte(&data[pc+2]); + if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){ + /* Free blocks must be in ascending order. And the last byte of + ** the free-block must lie on the database page. */ + return SQLITE_CORRUPT_BKPT; + } + nFree = nFree + size; + pc = next; + } + + /* At this point, nFree contains the sum of the offset to the start + ** of the cell-content area plus the number of free bytes within + ** the cell-content area. If this is greater than the usable-size + ** of the page, then the page must be corrupted. This check also + ** serves to verify that the offset to the start of the cell-content + ** area, according to the page header, lies within the page. + */ + if( nFree>usableSize ){ + return SQLITE_CORRUPT_BKPT; + } + pPage->nFree = (u16)(nFree - iCellFirst); + pPage->isInit = 1; + } + return SQLITE_OK; +} + +/* +** Set up a raw page so that it looks like a database page holding +** no entries. +*/ +static void zeroPage(MemPage *pPage, int flags){ + unsigned char *data = pPage->aData; + BtShared *pBt = pPage->pBt; + u8 hdr = pPage->hdrOffset; + u16 first; + + assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); + assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); + assert( sqlite3PagerGetData(pPage->pDbPage) == data ); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( sqlite3_mutex_held(pBt->mutex) ); + if( pBt->btsFlags & BTS_SECURE_DELETE ){ + memset(&data[hdr], 0, pBt->usableSize - hdr); + } + data[hdr] = (char)flags; + first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0); + memset(&data[hdr+1], 0, 4); + data[hdr+7] = 0; + put2byte(&data[hdr+5], pBt->usableSize); + pPage->nFree = (u16)(pBt->usableSize - first); + decodeFlags(pPage, flags); + pPage->hdrOffset = hdr; + pPage->cellOffset = first; + pPage->aDataEnd = &data[pBt->usableSize]; + pPage->aCellIdx = &data[first]; + pPage->nOverflow = 0; + assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); + pPage->maskPage = (u16)(pBt->pageSize - 1); + pPage->nCell = 0; + pPage->isInit = 1; +} + + +/* +** Convert a DbPage obtained from the pager into a MemPage used by +** the btree layer. +*/ +static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ + MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); + pPage->aData = sqlite3PagerGetData(pDbPage); + pPage->pDbPage = pDbPage; + pPage->pBt = pBt; + pPage->pgno = pgno; + pPage->hdrOffset = pPage->pgno==1 ? 100 : 0; + return pPage; +} + +/* +** Get a page from the pager. Initialize the MemPage.pBt and +** MemPage.aData elements if needed. +** +** If the noContent flag is set, it means that we do not care about +** the content of the page at this time. So do not go to the disk +** to fetch the content. Just fill in the content with zeros for now. +** If in the future we call sqlite3PagerWrite() on this page, that +** means we have started to be concerned about content and the disk +** read should occur at that point. +*/ +static int btreeGetPage( + BtShared *pBt, /* The btree */ + Pgno pgno, /* Number of the page to fetch */ + MemPage **ppPage, /* Return the page in this parameter */ + int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ +){ + int rc; + DbPage *pDbPage; + + assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); + assert( sqlite3_mutex_held(pBt->mutex) ); + rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); + if( rc ) return rc; + *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); + return SQLITE_OK; +} + +/* +** Retrieve a page from the pager cache. If the requested page is not +** already in the pager cache return NULL. Initialize the MemPage.pBt and +** MemPage.aData elements if needed. +*/ +static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ + DbPage *pDbPage; + assert( sqlite3_mutex_held(pBt->mutex) ); + pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); + if( pDbPage ){ + return btreePageFromDbPage(pDbPage, pgno, pBt); + } + return 0; +} + +/* +** Return the size of the database file in pages. If there is any kind of +** error, return ((unsigned int)-1). +*/ +static Pgno btreePagecount(BtShared *pBt){ + return pBt->nPage; +} +SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){ + assert( sqlite3BtreeHoldsMutex(p) ); + assert( ((p->pBt->nPage)&0x8000000)==0 ); + return (int)btreePagecount(p->pBt); +} + +/* +** Get a page from the pager and initialize it. This routine is just a +** convenience wrapper around separate calls to btreeGetPage() and +** btreeInitPage(). +** +** If an error occurs, then the value *ppPage is set to is undefined. It +** may remain unchanged, or it may be set to an invalid value. +*/ +static int getAndInitPage( + BtShared *pBt, /* The database file */ + Pgno pgno, /* Number of the page to get */ + MemPage **ppPage, /* Write the page pointer here */ + int bReadonly /* PAGER_GET_READONLY or 0 */ +){ + int rc; + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 ); + + if( pgno>btreePagecount(pBt) ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = btreeGetPage(pBt, pgno, ppPage, bReadonly); + if( rc==SQLITE_OK ){ + rc = btreeInitPage(*ppPage); + if( rc!=SQLITE_OK ){ + releasePage(*ppPage); + } + } + } + + testcase( pgno==0 ); + assert( pgno!=0 || rc==SQLITE_CORRUPT ); + return rc; +} + +/* +** Release a MemPage. This should be called once for each prior +** call to btreeGetPage. +*/ +static void releasePage(MemPage *pPage){ + if( pPage ){ + assert( pPage->aData ); + assert( pPage->pBt ); + assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); + assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + sqlite3PagerUnref(pPage->pDbPage); + } +} + +/* +** During a rollback, when the pager reloads information into the cache +** so that the cache is restored to its original state at the start of +** the transaction, for each page restored this routine is called. +** +** This routine needs to reset the extra data section at the end of the +** page to agree with the restored data. +*/ +static void pageReinit(DbPage *pData){ + MemPage *pPage; + pPage = (MemPage *)sqlite3PagerGetExtra(pData); + assert( sqlite3PagerPageRefcount(pData)>0 ); + if( pPage->isInit ){ + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + pPage->isInit = 0; + if( sqlite3PagerPageRefcount(pData)>1 ){ + /* pPage might not be a btree page; it might be an overflow page + ** or ptrmap page or a free page. In those cases, the following + ** call to btreeInitPage() will likely return SQLITE_CORRUPT. + ** But no harm is done by this. And it is very important that + ** btreeInitPage() be called on every btree page so we make + ** the call for every page that comes in for re-initing. */ + btreeInitPage(pPage); + } + } +} + +/* +** Invoke the busy handler for a btree. +*/ +static int btreeInvokeBusyHandler(void *pArg){ + BtShared *pBt = (BtShared*)pArg; + assert( pBt->db ); + assert( sqlite3_mutex_held(pBt->db->mutex) ); + return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); +} + +/* +** Open a database file. +** +** zFilename is the name of the database file. If zFilename is NULL +** then an ephemeral database is created. The ephemeral database might +** be exclusively in memory, or it might use a disk-based memory cache. +** Either way, the ephemeral database will be automatically deleted +** when sqlite3BtreeClose() is called. +** +** If zFilename is ":memory:" then an in-memory database is created +** that is automatically destroyed when it is closed. +** +** The "flags" parameter is a bitmask that might contain bits like +** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. +** +** If the database is already opened in the same database connection +** and we are in shared cache mode, then the open will fail with an +** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared +** objects in the same database connection since doing so will lead +** to problems with locking. +*/ +SQLITE_PRIVATE int sqlite3BtreeOpen( + sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ + const char *zFilename, /* Name of the file containing the BTree database */ + sqlite3 *db, /* Associated database handle */ + Btree **ppBtree, /* Pointer to new Btree object written here */ + int flags, /* Options */ + int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ +){ + BtShared *pBt = 0; /* Shared part of btree structure */ + Btree *p; /* Handle to return */ + sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ + int rc = SQLITE_OK; /* Result code from this function */ + u8 nReserve; /* Byte of unused space on each page */ + unsigned char zDbHeader[100]; /* Database header content */ + + /* True if opening an ephemeral, temporary database */ + const int isTempDb = zFilename==0 || zFilename[0]==0; + + /* Set the variable isMemdb to true for an in-memory database, or + ** false for a file-based database. + */ +#ifdef SQLITE_OMIT_MEMORYDB + const int isMemdb = 0; +#else + const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) + || (isTempDb && sqlite3TempInMemory(db)) + || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; +#endif + + assert( db!=0 ); + assert( pVfs!=0 ); + assert( sqlite3_mutex_held(db->mutex) ); + assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ + + /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ + assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); + + /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ + assert( (flags & BTREE_SINGLE)==0 || isTempDb ); + + if( isMemdb ){ + flags |= BTREE_MEMORY; + } + if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ + vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; + } + p = sqlite3MallocZero(sizeof(Btree)); + if( !p ){ + return SQLITE_NOMEM; + } + p->inTrans = TRANS_NONE; + p->db = db; +#ifndef SQLITE_OMIT_SHARED_CACHE + p->lock.pBtree = p; + p->lock.iTable = 1; +#endif + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) + /* + ** If this Btree is a candidate for shared cache, try to find an + ** existing BtShared object that we can share with + */ + if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ + if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ + int nFullPathname = pVfs->mxPathname+1; + char *zFullPathname = sqlite3Malloc(nFullPathname); + MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) + p->sharable = 1; + if( !zFullPathname ){ + sqlite3_free(p); + return SQLITE_NOMEM; + } + if( isMemdb ){ + memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1); + }else{ + rc = sqlite3OsFullPathname(pVfs, zFilename, + nFullPathname, zFullPathname); + if( rc ){ + sqlite3_free(zFullPathname); + sqlite3_free(p); + return rc; + } + } +#if SQLITE_THREADSAFE + mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); + sqlite3_mutex_enter(mutexOpen); + mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); + sqlite3_mutex_enter(mutexShared); +#endif + for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ + assert( pBt->nRef>0 ); + if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) + && sqlite3PagerVfs(pBt->pPager)==pVfs ){ + int iDb; + for(iDb=db->nDb-1; iDb>=0; iDb--){ + Btree *pExisting = db->aDb[iDb].pBt; + if( pExisting && pExisting->pBt==pBt ){ + sqlite3_mutex_leave(mutexShared); + sqlite3_mutex_leave(mutexOpen); + sqlite3_free(zFullPathname); + sqlite3_free(p); + return SQLITE_CONSTRAINT; + } + } + p->pBt = pBt; + pBt->nRef++; + break; + } + } + sqlite3_mutex_leave(mutexShared); + sqlite3_free(zFullPathname); + } +#ifdef SQLITE_DEBUG + else{ + /* In debug mode, we mark all persistent databases as sharable + ** even when they are not. This exercises the locking code and + ** gives more opportunity for asserts(sqlite3_mutex_held()) + ** statements to find locking problems. + */ + p->sharable = 1; + } +#endif + } +#endif + if( pBt==0 ){ + /* + ** The following asserts make sure that structures used by the btree are + ** the right size. This is to guard against size changes that result + ** when compiling on a different architecture. + */ + assert( sizeof(i64)==8 || sizeof(i64)==4 ); + assert( sizeof(u64)==8 || sizeof(u64)==4 ); + assert( sizeof(u32)==4 ); + assert( sizeof(u16)==2 ); + assert( sizeof(Pgno)==4 ); + + pBt = sqlite3MallocZero( sizeof(*pBt) ); + if( pBt==0 ){ + rc = SQLITE_NOMEM; + goto btree_open_out; + } + rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, + EXTRA_SIZE, flags, vfsFlags, pageReinit); + if( rc==SQLITE_OK ){ + sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); + rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); + } + if( rc!=SQLITE_OK ){ + goto btree_open_out; + } + pBt->openFlags = (u8)flags; + pBt->db = db; + sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); + p->pBt = pBt; + + pBt->pCursor = 0; + pBt->pPage1 = 0; + if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; +#ifdef SQLITE_SECURE_DELETE + pBt->btsFlags |= BTS_SECURE_DELETE; +#endif + pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); + if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE + || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ + pBt->pageSize = 0; +#ifndef SQLITE_OMIT_AUTOVACUUM + /* If the magic name ":memory:" will create an in-memory database, then + ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if + ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if + ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a + ** regular file-name. In this case the auto-vacuum applies as per normal. + */ + if( zFilename && !isMemdb ){ + pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); + pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); + } +#endif + nReserve = 0; + }else{ + nReserve = zDbHeader[20]; + pBt->btsFlags |= BTS_PAGESIZE_FIXED; +#ifndef SQLITE_OMIT_AUTOVACUUM + pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); + pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); +#endif + } + rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); + if( rc ) goto btree_open_out; + pBt->usableSize = pBt->pageSize - nReserve; + assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) + /* Add the new BtShared object to the linked list sharable BtShareds. + */ + if( p->sharable ){ + MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) + pBt->nRef = 1; + MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);) + if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ + pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); + if( pBt->mutex==0 ){ + rc = SQLITE_NOMEM; + db->mallocFailed = 0; + goto btree_open_out; + } + } + sqlite3_mutex_enter(mutexShared); + pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); + GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; + sqlite3_mutex_leave(mutexShared); + } +#endif + } + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) + /* If the new Btree uses a sharable pBtShared, then link the new + ** Btree into the list of all sharable Btrees for the same connection. + ** The list is kept in ascending order by pBt address. + */ + if( p->sharable ){ + int i; + Btree *pSib; + for(i=0; inDb; i++){ + if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ + while( pSib->pPrev ){ pSib = pSib->pPrev; } + if( p->pBtpBt ){ + p->pNext = pSib; + p->pPrev = 0; + pSib->pPrev = p; + }else{ + while( pSib->pNext && pSib->pNext->pBtpBt ){ + pSib = pSib->pNext; + } + p->pNext = pSib->pNext; + p->pPrev = pSib; + if( p->pNext ){ + p->pNext->pPrev = p; + } + pSib->pNext = p; + } + break; + } + } + } +#endif + *ppBtree = p; + +btree_open_out: + if( rc!=SQLITE_OK ){ + if( pBt && pBt->pPager ){ + sqlite3PagerClose(pBt->pPager); + } + sqlite3_free(pBt); + sqlite3_free(p); + *ppBtree = 0; + }else{ + /* If the B-Tree was successfully opened, set the pager-cache size to the + ** default value. Except, when opening on an existing shared pager-cache, + ** do not change the pager-cache size. + */ + if( sqlite3BtreeSchema(p, 0, 0)==0 ){ + sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE); + } + } + if( mutexOpen ){ + assert( sqlite3_mutex_held(mutexOpen) ); + sqlite3_mutex_leave(mutexOpen); + } + return rc; +} + +/* +** Decrement the BtShared.nRef counter. When it reaches zero, +** remove the BtShared structure from the sharing list. Return +** true if the BtShared.nRef counter reaches zero and return +** false if it is still positive. +*/ +static int removeFromSharingList(BtShared *pBt){ +#ifndef SQLITE_OMIT_SHARED_CACHE + MUTEX_LOGIC( sqlite3_mutex *pMaster; ) + BtShared *pList; + int removed = 0; + + assert( sqlite3_mutex_notheld(pBt->mutex) ); + MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + sqlite3_mutex_enter(pMaster); + pBt->nRef--; + if( pBt->nRef<=0 ){ + if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ + GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; + }else{ + pList = GLOBAL(BtShared*,sqlite3SharedCacheList); + while( ALWAYS(pList) && pList->pNext!=pBt ){ + pList=pList->pNext; + } + if( ALWAYS(pList) ){ + pList->pNext = pBt->pNext; + } + } + if( SQLITE_THREADSAFE ){ + sqlite3_mutex_free(pBt->mutex); + } + removed = 1; + } + sqlite3_mutex_leave(pMaster); + return removed; +#else + return 1; +#endif +} + +/* +** Make sure pBt->pTmpSpace points to an allocation of +** MX_CELL_SIZE(pBt) bytes. +*/ +static void allocateTempSpace(BtShared *pBt){ + if( !pBt->pTmpSpace ){ + pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); + + /* One of the uses of pBt->pTmpSpace is to format cells before + ** inserting them into a leaf page (function fillInCell()). If + ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes + ** by the various routines that manipulate binary cells. Which + ** can mean that fillInCell() only initializes the first 2 or 3 + ** bytes of pTmpSpace, but that the first 4 bytes are copied from + ** it into a database page. This is not actually a problem, but it + ** does cause a valgrind error when the 1 or 2 bytes of unitialized + ** data is passed to system call write(). So to avoid this error, + ** zero the first 4 bytes of temp space here. */ + if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4); + } +} + +/* +** Free the pBt->pTmpSpace allocation +*/ +static void freeTempSpace(BtShared *pBt){ + sqlite3PageFree( pBt->pTmpSpace); + pBt->pTmpSpace = 0; +} + +/* +** Close an open database and invalidate all cursors. +*/ +SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){ + BtShared *pBt = p->pBt; + BtCursor *pCur; + + /* Close all cursors opened via this handle. */ + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + pCur = pBt->pCursor; + while( pCur ){ + BtCursor *pTmp = pCur; + pCur = pCur->pNext; + if( pTmp->pBtree==p ){ + sqlite3BtreeCloseCursor(pTmp); + } + } + + /* Rollback any active transaction and free the handle structure. + ** The call to sqlite3BtreeRollback() drops any table-locks held by + ** this handle. + */ + sqlite3BtreeRollback(p, SQLITE_OK); + sqlite3BtreeLeave(p); + + /* If there are still other outstanding references to the shared-btree + ** structure, return now. The remainder of this procedure cleans + ** up the shared-btree. + */ + assert( p->wantToLock==0 && p->locked==0 ); + if( !p->sharable || removeFromSharingList(pBt) ){ + /* The pBt is no longer on the sharing list, so we can access + ** it without having to hold the mutex. + ** + ** Clean out and delete the BtShared object. + */ + assert( !pBt->pCursor ); + sqlite3PagerClose(pBt->pPager); + if( pBt->xFreeSchema && pBt->pSchema ){ + pBt->xFreeSchema(pBt->pSchema); + } + sqlite3DbFree(0, pBt->pSchema); + freeTempSpace(pBt); + sqlite3_free(pBt); + } + +#ifndef SQLITE_OMIT_SHARED_CACHE + assert( p->wantToLock==0 ); + assert( p->locked==0 ); + if( p->pPrev ) p->pPrev->pNext = p->pNext; + if( p->pNext ) p->pNext->pPrev = p->pPrev; +#endif + + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Change the limit on the number of pages allowed in the cache. +** +** The maximum number of cache pages is set to the absolute +** value of mxPage. If mxPage is negative, the pager will +** operate asynchronously - it will not stop to do fsync()s +** to insure data is written to the disk surface before +** continuing. Transactions still work if synchronous is off, +** and the database cannot be corrupted if this program +** crashes. But if the operating system crashes or there is +** an abrupt power failure when synchronous is off, the database +** could be left in an inconsistent and unrecoverable state. +** Synchronous is on by default so database corruption is not +** normally a worry. +*/ +SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ + BtShared *pBt = p->pBt; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + sqlite3PagerSetCachesize(pBt->pPager, mxPage); + sqlite3BtreeLeave(p); + return SQLITE_OK; +} + +/* +** Change the limit on the amount of the database file that may be +** memory mapped. +*/ +SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ + BtShared *pBt = p->pBt; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); + sqlite3BtreeLeave(p); + return SQLITE_OK; +} + +/* +** Change the way data is synced to disk in order to increase or decrease +** how well the database resists damage due to OS crashes and power +** failures. Level 1 is the same as asynchronous (no syncs() occur and +** there is a high probability of damage) Level 2 is the default. There +** is a very low but non-zero probability of damage. Level 3 reduces the +** probability of damage to near zero but with a write performance reduction. +*/ +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags( + Btree *p, /* The btree to set the safety level on */ + unsigned pgFlags /* Various PAGER_* flags */ +){ + BtShared *pBt = p->pBt; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + sqlite3PagerSetFlags(pBt->pPager, pgFlags); + sqlite3BtreeLeave(p); + return SQLITE_OK; +} +#endif + +/* +** Return TRUE if the given btree is set to safety level 1. In other +** words, return TRUE if no sync() occurs on the disk files. +*/ +SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){ + BtShared *pBt = p->pBt; + int rc; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + assert( pBt && pBt->pPager ); + rc = sqlite3PagerNosync(pBt->pPager); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Change the default pages size and the number of reserved bytes per page. +** Or, if the page size has already been fixed, return SQLITE_READONLY +** without changing anything. +** +** The page size must be a power of 2 between 512 and 65536. If the page +** size supplied does not meet this constraint then the page size is not +** changed. +** +** Page sizes are constrained to be a power of two so that the region +** of the database file used for locking (beginning at PENDING_BYTE, +** the first byte past the 1GB boundary, 0x40000000) needs to occur +** at the beginning of a page. +** +** If parameter nReserve is less than zero, then the number of reserved +** bytes per page is left unchanged. +** +** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size +** and autovacuum mode can no longer be changed. +*/ +SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ + int rc = SQLITE_OK; + BtShared *pBt = p->pBt; + assert( nReserve>=-1 && nReserve<=255 ); + sqlite3BtreeEnter(p); + if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ + sqlite3BtreeLeave(p); + return SQLITE_READONLY; + } + if( nReserve<0 ){ + nReserve = pBt->pageSize - pBt->usableSize; + } + assert( nReserve>=0 && nReserve<=255 ); + if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && + ((pageSize-1)&pageSize)==0 ){ + assert( (pageSize & 7)==0 ); + assert( !pBt->pPage1 && !pBt->pCursor ); + pBt->pageSize = (u32)pageSize; + freeTempSpace(pBt); + } + rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); + pBt->usableSize = pBt->pageSize - (u16)nReserve; + if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Return the currently defined page size +*/ +SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){ + return p->pBt->pageSize; +} + +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG) +/* +** This function is similar to sqlite3BtreeGetReserve(), except that it +** may only be called if it is guaranteed that the b-tree mutex is already +** held. +** +** This is useful in one special case in the backup API code where it is +** known that the shared b-tree mutex is held, but the mutex on the +** database handle that owns *p is not. In this case if sqlite3BtreeEnter() +** were to be called, it might collide with some other operation on the +** database handle that owns *p, causing undefined behavior. +*/ +SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){ + assert( sqlite3_mutex_held(p->pBt->mutex) ); + return p->pBt->pageSize - p->pBt->usableSize; +} +#endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */ + +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) +/* +** Return the number of bytes of space at the end of every page that +** are intentually left unused. This is the "reserved" space that is +** sometimes used by extensions. +*/ +SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){ + int n; + sqlite3BtreeEnter(p); + n = p->pBt->pageSize - p->pBt->usableSize; + sqlite3BtreeLeave(p); + return n; +} + +/* +** Set the maximum page count for a database if mxPage is positive. +** No changes are made if mxPage is 0 or negative. +** Regardless of the value of mxPage, return the maximum page count. +*/ +SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ + int n; + sqlite3BtreeEnter(p); + n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); + sqlite3BtreeLeave(p); + return n; +} + +/* +** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1, +** then make no changes. Always return the value of the BTS_SECURE_DELETE +** setting after the change. +*/ +SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ + int b; + if( p==0 ) return 0; + sqlite3BtreeEnter(p); + if( newFlag>=0 ){ + p->pBt->btsFlags &= ~BTS_SECURE_DELETE; + if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE; + } + b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0; + sqlite3BtreeLeave(p); + return b; +} +#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */ + +/* +** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' +** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it +** is disabled. The default value for the auto-vacuum property is +** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. +*/ +SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ +#ifdef SQLITE_OMIT_AUTOVACUUM + return SQLITE_READONLY; +#else + BtShared *pBt = p->pBt; + int rc = SQLITE_OK; + u8 av = (u8)autoVacuum; + + sqlite3BtreeEnter(p); + if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ + rc = SQLITE_READONLY; + }else{ + pBt->autoVacuum = av ?1:0; + pBt->incrVacuum = av==2 ?1:0; + } + sqlite3BtreeLeave(p); + return rc; +#endif +} + +/* +** Return the value of the 'auto-vacuum' property. If auto-vacuum is +** enabled 1 is returned. Otherwise 0. +*/ +SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){ +#ifdef SQLITE_OMIT_AUTOVACUUM + return BTREE_AUTOVACUUM_NONE; +#else + int rc; + sqlite3BtreeEnter(p); + rc = ( + (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: + (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: + BTREE_AUTOVACUUM_INCR + ); + sqlite3BtreeLeave(p); + return rc; +#endif +} + + +/* +** Get a reference to pPage1 of the database file. This will +** also acquire a readlock on that file. +** +** SQLITE_OK is returned on success. If the file is not a +** well-formed database file, then SQLITE_CORRUPT is returned. +** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM +** is returned if we run out of memory. +*/ +static int lockBtree(BtShared *pBt){ + int rc; /* Result code from subfunctions */ + MemPage *pPage1; /* Page 1 of the database file */ + int nPage; /* Number of pages in the database */ + int nPageFile = 0; /* Number of pages in the database file */ + int nPageHeader; /* Number of pages in the database according to hdr */ + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( pBt->pPage1==0 ); + rc = sqlite3PagerSharedLock(pBt->pPager); + if( rc!=SQLITE_OK ) return rc; + rc = btreeGetPage(pBt, 1, &pPage1, 0); + if( rc!=SQLITE_OK ) return rc; + + /* Do some checking to help insure the file we opened really is + ** a valid database file. + */ + nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData); + sqlite3PagerPagecount(pBt->pPager, &nPageFile); + if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ + nPage = nPageFile; + } + if( nPage>0 ){ + u32 pageSize; + u32 usableSize; + u8 *page1 = pPage1->aData; + rc = SQLITE_NOTADB; + if( memcmp(page1, zMagicHeader, 16)!=0 ){ + goto page1_init_failed; + } + +#ifdef SQLITE_OMIT_WAL + if( page1[18]>1 ){ + pBt->btsFlags |= BTS_READ_ONLY; + } + if( page1[19]>1 ){ + goto page1_init_failed; + } +#else + if( page1[18]>2 ){ + pBt->btsFlags |= BTS_READ_ONLY; + } + if( page1[19]>2 ){ + goto page1_init_failed; + } + + /* If the write version is set to 2, this database should be accessed + ** in WAL mode. If the log is not already open, open it now. Then + ** return SQLITE_OK and return without populating BtShared.pPage1. + ** The caller detects this and calls this function again. This is + ** required as the version of page 1 currently in the page1 buffer + ** may not be the latest version - there may be a newer one in the log + ** file. + */ + if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ + int isOpen = 0; + rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); + if( rc!=SQLITE_OK ){ + goto page1_init_failed; + }else if( isOpen==0 ){ + releasePage(pPage1); + return SQLITE_OK; + } + rc = SQLITE_NOTADB; + } +#endif + + /* The maximum embedded fraction must be exactly 25%. And the minimum + ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data. + ** The original design allowed these amounts to vary, but as of + ** version 3.6.0, we require them to be fixed. + */ + if( memcmp(&page1[21], "\100\040\040",3)!=0 ){ + goto page1_init_failed; + } + pageSize = (page1[16]<<8) | (page1[17]<<16); + if( ((pageSize-1)&pageSize)!=0 + || pageSize>SQLITE_MAX_PAGE_SIZE + || pageSize<=256 + ){ + goto page1_init_failed; + } + assert( (pageSize & 7)==0 ); + usableSize = pageSize - page1[20]; + if( (u32)pageSize!=pBt->pageSize ){ + /* After reading the first page of the database assuming a page size + ** of BtShared.pageSize, we have discovered that the page-size is + ** actually pageSize. Unlock the database, leave pBt->pPage1 at + ** zero and return SQLITE_OK. The caller will call this function + ** again with the correct page-size. + */ + releasePage(pPage1); + pBt->usableSize = usableSize; + pBt->pageSize = pageSize; + freeTempSpace(pBt); + rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, + pageSize-usableSize); + return rc; + } + if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){ + rc = SQLITE_CORRUPT_BKPT; + goto page1_init_failed; + } + if( usableSize<480 ){ + goto page1_init_failed; + } + pBt->pageSize = pageSize; + pBt->usableSize = usableSize; +#ifndef SQLITE_OMIT_AUTOVACUUM + pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0); + pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0); +#endif + } + + /* maxLocal is the maximum amount of payload to store locally for + ** a cell. Make sure it is small enough so that at least minFanout + ** cells can will fit on one page. We assume a 10-byte page header. + ** Besides the payload, the cell must store: + ** 2-byte pointer to the cell + ** 4-byte child pointer + ** 9-byte nKey value + ** 4-byte nData value + ** 4-byte overflow page pointer + ** So a cell consists of a 2-byte pointer, a header which is as much as + ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow + ** page pointer. + */ + pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); + pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); + pBt->maxLeaf = (u16)(pBt->usableSize - 35); + pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); + if( pBt->maxLocal>127 ){ + pBt->max1bytePayload = 127; + }else{ + pBt->max1bytePayload = (u8)pBt->maxLocal; + } + assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); + pBt->pPage1 = pPage1; + pBt->nPage = nPage; + return SQLITE_OK; + +page1_init_failed: + releasePage(pPage1); + pBt->pPage1 = 0; + return rc; +} + +#ifndef NDEBUG +/* +** Return the number of cursors open on pBt. This is for use +** in assert() expressions, so it is only compiled if NDEBUG is not +** defined. +** +** Only write cursors are counted if wrOnly is true. If wrOnly is +** false then all cursors are counted. +** +** For the purposes of this routine, a cursor is any cursor that +** is capable of reading or writing to the databse. Cursors that +** have been tripped into the CURSOR_FAULT state are not counted. +*/ +static int countValidCursors(BtShared *pBt, int wrOnly){ + BtCursor *pCur; + int r = 0; + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ + if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++; + } + return r; +} +#endif + +/* +** If there are no outstanding cursors and we are not in the middle +** of a transaction but there is a read lock on the database, then +** this routine unrefs the first page of the database file which +** has the effect of releasing the read lock. +** +** If there is a transaction in progress, this routine is a no-op. +*/ +static void unlockBtreeIfUnused(BtShared *pBt){ + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); + if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ + assert( pBt->pPage1->aData ); + assert( sqlite3PagerRefcount(pBt->pPager)==1 ); + assert( pBt->pPage1->aData ); + releasePage(pBt->pPage1); + pBt->pPage1 = 0; + } +} + +/* +** If pBt points to an empty file then convert that empty file +** into a new empty database by initializing the first page of +** the database. +*/ +static int newDatabase(BtShared *pBt){ + MemPage *pP1; + unsigned char *data; + int rc; + + assert( sqlite3_mutex_held(pBt->mutex) ); + if( pBt->nPage>0 ){ + return SQLITE_OK; + } + pP1 = pBt->pPage1; + assert( pP1!=0 ); + data = pP1->aData; + rc = sqlite3PagerWrite(pP1->pDbPage); + if( rc ) return rc; + memcpy(data, zMagicHeader, sizeof(zMagicHeader)); + assert( sizeof(zMagicHeader)==16 ); + data[16] = (u8)((pBt->pageSize>>8)&0xff); + data[17] = (u8)((pBt->pageSize>>16)&0xff); + data[18] = 1; + data[19] = 1; + assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); + data[20] = (u8)(pBt->pageSize - pBt->usableSize); + data[21] = 64; + data[22] = 32; + data[23] = 32; + memset(&data[24], 0, 100-24); + zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); + pBt->btsFlags |= BTS_PAGESIZE_FIXED; +#ifndef SQLITE_OMIT_AUTOVACUUM + assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); + assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); + put4byte(&data[36 + 4*4], pBt->autoVacuum); + put4byte(&data[36 + 7*4], pBt->incrVacuum); +#endif + pBt->nPage = 1; + data[31] = 1; + return SQLITE_OK; +} + +/* +** Initialize the first page of the database file (creating a database +** consisting of a single page and no schema objects). Return SQLITE_OK +** if successful, or an SQLite error code otherwise. +*/ +SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){ + int rc; + sqlite3BtreeEnter(p); + p->pBt->nPage = 0; + rc = newDatabase(p->pBt); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Attempt to start a new transaction. A write-transaction +** is started if the second argument is nonzero, otherwise a read- +** transaction. If the second argument is 2 or more and exclusive +** transaction is started, meaning that no other process is allowed +** to access the database. A preexisting transaction may not be +** upgraded to exclusive by calling this routine a second time - the +** exclusivity flag only works for a new transaction. +** +** A write-transaction must be started before attempting any +** changes to the database. None of the following routines +** will work unless a transaction is started first: +** +** sqlite3BtreeCreateTable() +** sqlite3BtreeCreateIndex() +** sqlite3BtreeClearTable() +** sqlite3BtreeDropTable() +** sqlite3BtreeInsert() +** sqlite3BtreeDelete() +** sqlite3BtreeUpdateMeta() +** +** If an initial attempt to acquire the lock fails because of lock contention +** and the database was previously unlocked, then invoke the busy handler +** if there is one. But if there was previously a read-lock, do not +** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is +** returned when there is already a read-lock in order to avoid a deadlock. +** +** Suppose there are two processes A and B. A has a read lock and B has +** a reserved lock. B tries to promote to exclusive but is blocked because +** of A's read lock. A tries to promote to reserved but is blocked by B. +** One or the other of the two processes must give way or there can be +** no progress. By returning SQLITE_BUSY and not invoking the busy callback +** when A already has a read lock, we encourage A to give up and let B +** proceed. +*/ +SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ + sqlite3 *pBlock = 0; + BtShared *pBt = p->pBt; + int rc = SQLITE_OK; + + sqlite3BtreeEnter(p); + btreeIntegrity(p); + + /* If the btree is already in a write-transaction, or it + ** is already in a read-transaction and a read-transaction + ** is requested, this is a no-op. + */ + if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ + goto trans_begun; + } + assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); + + /* Write transactions are not possible on a read-only database */ + if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ + rc = SQLITE_READONLY; + goto trans_begun; + } + +#ifndef SQLITE_OMIT_SHARED_CACHE + /* If another database handle has already opened a write transaction + ** on this shared-btree structure and a second write transaction is + ** requested, return SQLITE_LOCKED. + */ + if( (wrflag && pBt->inTransaction==TRANS_WRITE) + || (pBt->btsFlags & BTS_PENDING)!=0 + ){ + pBlock = pBt->pWriter->db; + }else if( wrflag>1 ){ + BtLock *pIter; + for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ + if( pIter->pBtree!=p ){ + pBlock = pIter->pBtree->db; + break; + } + } + } + if( pBlock ){ + sqlite3ConnectionBlocked(p->db, pBlock); + rc = SQLITE_LOCKED_SHAREDCACHE; + goto trans_begun; + } +#endif + + /* Any read-only or read-write transaction implies a read-lock on + ** page 1. So if some other shared-cache client already has a write-lock + ** on page 1, the transaction cannot be opened. */ + rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); + if( SQLITE_OK!=rc ) goto trans_begun; + + pBt->btsFlags &= ~BTS_INITIALLY_EMPTY; + if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY; + do { + /* Call lockBtree() until either pBt->pPage1 is populated or + ** lockBtree() returns something other than SQLITE_OK. lockBtree() + ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after + ** reading page 1 it discovers that the page-size of the database + ** file is not pBt->pageSize. In this case lockBtree() will update + ** pBt->pageSize to the page-size of the file on disk. + */ + while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); + + if( rc==SQLITE_OK && wrflag ){ + if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ + rc = SQLITE_READONLY; + }else{ + rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db)); + if( rc==SQLITE_OK ){ + rc = newDatabase(pBt); + } + } + } + + if( rc!=SQLITE_OK ){ + unlockBtreeIfUnused(pBt); + } + }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && + btreeInvokeBusyHandler(pBt) ); + + if( rc==SQLITE_OK ){ + if( p->inTrans==TRANS_NONE ){ + pBt->nTransaction++; +#ifndef SQLITE_OMIT_SHARED_CACHE + if( p->sharable ){ + assert( p->lock.pBtree==p && p->lock.iTable==1 ); + p->lock.eLock = READ_LOCK; + p->lock.pNext = pBt->pLock; + pBt->pLock = &p->lock; + } +#endif + } + p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); + if( p->inTrans>pBt->inTransaction ){ + pBt->inTransaction = p->inTrans; + } + if( wrflag ){ + MemPage *pPage1 = pBt->pPage1; +#ifndef SQLITE_OMIT_SHARED_CACHE + assert( !pBt->pWriter ); + pBt->pWriter = p; + pBt->btsFlags &= ~BTS_EXCLUSIVE; + if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE; +#endif + + /* If the db-size header field is incorrect (as it may be if an old + ** client has been writing the database file), update it now. Doing + ** this sooner rather than later means the database size can safely + ** re-read the database size from page 1 if a savepoint or transaction + ** rollback occurs within the transaction. + */ + if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ + rc = sqlite3PagerWrite(pPage1->pDbPage); + if( rc==SQLITE_OK ){ + put4byte(&pPage1->aData[28], pBt->nPage); + } + } + } + } + + +trans_begun: + if( rc==SQLITE_OK && wrflag ){ + /* This call makes sure that the pager has the correct number of + ** open savepoints. If the second parameter is greater than 0 and + ** the sub-journal is not already open, then it will be opened here. + */ + rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint); + } + + btreeIntegrity(p); + sqlite3BtreeLeave(p); + return rc; +} + +#ifndef SQLITE_OMIT_AUTOVACUUM + +/* +** Set the pointer-map entries for all children of page pPage. Also, if +** pPage contains cells that point to overflow pages, set the pointer +** map entries for the overflow pages as well. +*/ +static int setChildPtrmaps(MemPage *pPage){ + int i; /* Counter variable */ + int nCell; /* Number of cells in page pPage */ + int rc; /* Return code */ + BtShared *pBt = pPage->pBt; + u8 isInitOrig = pPage->isInit; + Pgno pgno = pPage->pgno; + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + rc = btreeInitPage(pPage); + if( rc!=SQLITE_OK ){ + goto set_child_ptrmaps_out; + } + nCell = pPage->nCell; + + for(i=0; ileaf ){ + Pgno childPgno = get4byte(pCell); + ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); + } + } + + if( !pPage->leaf ){ + Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); + ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); + } + +set_child_ptrmaps_out: + pPage->isInit = isInitOrig; + return rc; +} + +/* +** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so +** that it points to iTo. Parameter eType describes the type of pointer to +** be modified, as follows: +** +** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child +** page of pPage. +** +** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow +** page pointed to by one of the cells on pPage. +** +** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next +** overflow page in the list. +*/ +static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + if( eType==PTRMAP_OVERFLOW2 ){ + /* The pointer is always the first 4 bytes of the page in this case. */ + if( get4byte(pPage->aData)!=iFrom ){ + return SQLITE_CORRUPT_BKPT; + } + put4byte(pPage->aData, iTo); + }else{ + u8 isInitOrig = pPage->isInit; + int i; + int nCell; + + btreeInitPage(pPage); + nCell = pPage->nCell; + + for(i=0; iaData+pPage->maskPage + && iFrom==get4byte(&pCell[info.iOverflow]) + ){ + put4byte(&pCell[info.iOverflow], iTo); + break; + } + }else{ + if( get4byte(pCell)==iFrom ){ + put4byte(pCell, iTo); + break; + } + } + } + + if( i==nCell ){ + if( eType!=PTRMAP_BTREE || + get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ + return SQLITE_CORRUPT_BKPT; + } + put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); + } + + pPage->isInit = isInitOrig; + } + return SQLITE_OK; +} + + +/* +** Move the open database page pDbPage to location iFreePage in the +** database. The pDbPage reference remains valid. +** +** The isCommit flag indicates that there is no need to remember that +** the journal needs to be sync()ed before database page pDbPage->pgno +** can be written to. The caller has already promised not to write to that +** page. +*/ +static int relocatePage( + BtShared *pBt, /* Btree */ + MemPage *pDbPage, /* Open page to move */ + u8 eType, /* Pointer map 'type' entry for pDbPage */ + Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ + Pgno iFreePage, /* The location to move pDbPage to */ + int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ +){ + MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ + Pgno iDbPage = pDbPage->pgno; + Pager *pPager = pBt->pPager; + int rc; + + assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || + eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( pDbPage->pBt==pBt ); + + /* Move page iDbPage from its current location to page number iFreePage */ + TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", + iDbPage, iFreePage, iPtrPage, eType)); + rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); + if( rc!=SQLITE_OK ){ + return rc; + } + pDbPage->pgno = iFreePage; + + /* If pDbPage was a btree-page, then it may have child pages and/or cells + ** that point to overflow pages. The pointer map entries for all these + ** pages need to be changed. + ** + ** If pDbPage is an overflow page, then the first 4 bytes may store a + ** pointer to a subsequent overflow page. If this is the case, then + ** the pointer map needs to be updated for the subsequent overflow page. + */ + if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){ + rc = setChildPtrmaps(pDbPage); + if( rc!=SQLITE_OK ){ + return rc; + } + }else{ + Pgno nextOvfl = get4byte(pDbPage->aData); + if( nextOvfl!=0 ){ + ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc); + if( rc!=SQLITE_OK ){ + return rc; + } + } + } + + /* Fix the database pointer on page iPtrPage that pointed at iDbPage so + ** that it points at iFreePage. Also fix the pointer map entry for + ** iPtrPage. + */ + if( eType!=PTRMAP_ROOTPAGE ){ + rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + rc = sqlite3PagerWrite(pPtrPage->pDbPage); + if( rc!=SQLITE_OK ){ + releasePage(pPtrPage); + return rc; + } + rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); + releasePage(pPtrPage); + if( rc==SQLITE_OK ){ + ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); + } + } + return rc; +} + +/* Forward declaration required by incrVacuumStep(). */ +static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); + +/* +** Perform a single step of an incremental-vacuum. If successful, return +** SQLITE_OK. If there is no work to do (and therefore no point in +** calling this function again), return SQLITE_DONE. Or, if an error +** occurs, return some other error code. +** +** More specificly, this function attempts to re-organize the database so +** that the last page of the file currently in use is no longer in use. +** +** Parameter nFin is the number of pages that this database would contain +** were this function called until it returns SQLITE_DONE. +** +** If the bCommit parameter is non-zero, this function assumes that the +** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE +** or an error. bCommit is passed true for an auto-vacuum-on-commmit +** operation, or false for an incremental vacuum. +*/ +static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ + Pgno nFreeList; /* Number of pages still on the free-list */ + int rc; + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( iLastPg>nFin ); + + if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ + u8 eType; + Pgno iPtrPage; + + nFreeList = get4byte(&pBt->pPage1->aData[36]); + if( nFreeList==0 ){ + return SQLITE_DONE; + } + + rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); + if( rc!=SQLITE_OK ){ + return rc; + } + if( eType==PTRMAP_ROOTPAGE ){ + return SQLITE_CORRUPT_BKPT; + } + + if( eType==PTRMAP_FREEPAGE ){ + if( bCommit==0 ){ + /* Remove the page from the files free-list. This is not required + ** if bCommit is non-zero. In that case, the free-list will be + ** truncated to zero after this function returns, so it doesn't + ** matter if it still contains some garbage entries. + */ + Pgno iFreePg; + MemPage *pFreePg; + rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT); + if( rc!=SQLITE_OK ){ + return rc; + } + assert( iFreePg==iLastPg ); + releasePage(pFreePg); + } + } else { + Pgno iFreePg; /* Index of free page to move pLastPg to */ + MemPage *pLastPg; + u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */ + Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ + + rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + /* If bCommit is zero, this loop runs exactly once and page pLastPg + ** is swapped with the first free page pulled off the free list. + ** + ** On the other hand, if bCommit is greater than zero, then keep + ** looping until a free-page located within the first nFin pages + ** of the file is found. + */ + if( bCommit==0 ){ + eMode = BTALLOC_LE; + iNear = nFin; + } + do { + MemPage *pFreePg; + rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); + if( rc!=SQLITE_OK ){ + releasePage(pLastPg); + return rc; + } + releasePage(pFreePg); + }while( bCommit && iFreePg>nFin ); + assert( iFreePgbDoTruncate = 1; + pBt->nPage = iLastPg; + } + return SQLITE_OK; +} + +/* +** The database opened by the first argument is an auto-vacuum database +** nOrig pages in size containing nFree free pages. Return the expected +** size of the database in pages following an auto-vacuum operation. +*/ +static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ + int nEntry; /* Number of entries on one ptrmap page */ + Pgno nPtrmap; /* Number of PtrMap pages to be freed */ + Pgno nFin; /* Return value */ + + nEntry = pBt->usableSize/5; + nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; + nFin = nOrig - nFree - nPtrmap; + if( nOrig>PENDING_BYTE_PAGE(pBt) && nFinpBt; + + sqlite3BtreeEnter(p); + assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); + if( !pBt->autoVacuum ){ + rc = SQLITE_DONE; + }else{ + Pgno nOrig = btreePagecount(pBt); + Pgno nFree = get4byte(&pBt->pPage1->aData[36]); + Pgno nFin = finalDbSize(pBt, nOrig, nFree); + + if( nOrig0 ){ + rc = saveAllCursors(pBt, 0, 0); + if( rc==SQLITE_OK ){ + invalidateAllOverflowCache(pBt); + rc = incrVacuumStep(pBt, nFin, nOrig, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + put4byte(&pBt->pPage1->aData[28], pBt->nPage); + } + }else{ + rc = SQLITE_DONE; + } + } + sqlite3BtreeLeave(p); + return rc; +} + +/* +** This routine is called prior to sqlite3PagerCommit when a transaction +** is committed for an auto-vacuum database. +** +** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages +** the database file should be truncated to during the commit process. +** i.e. the database has been reorganized so that only the first *pnTrunc +** pages are in use. +*/ +static int autoVacuumCommit(BtShared *pBt){ + int rc = SQLITE_OK; + Pager *pPager = pBt->pPager; + VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) ); + + assert( sqlite3_mutex_held(pBt->mutex) ); + invalidateAllOverflowCache(pBt); + assert(pBt->autoVacuum); + if( !pBt->incrVacuum ){ + Pgno nFin; /* Number of pages in database after autovacuuming */ + Pgno nFree; /* Number of pages on the freelist initially */ + Pgno iFree; /* The next page to be freed */ + Pgno nOrig; /* Database size before freeing */ + + nOrig = btreePagecount(pBt); + if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ + /* It is not possible to create a database for which the final page + ** is either a pointer-map page or the pending-byte page. If one + ** is encountered, this indicates corruption. + */ + return SQLITE_CORRUPT_BKPT; + } + + nFree = get4byte(&pBt->pPage1->aData[36]); + nFin = finalDbSize(pBt, nOrig, nFree); + if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; + if( nFinnFin && rc==SQLITE_OK; iFree--){ + rc = incrVacuumStep(pBt, nFin, iFree, 1); + } + if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + put4byte(&pBt->pPage1->aData[32], 0); + put4byte(&pBt->pPage1->aData[36], 0); + put4byte(&pBt->pPage1->aData[28], nFin); + pBt->bDoTruncate = 1; + pBt->nPage = nFin; + } + if( rc!=SQLITE_OK ){ + sqlite3PagerRollback(pPager); + } + } + + assert( nRef>=sqlite3PagerRefcount(pPager) ); + return rc; +} + +#else /* ifndef SQLITE_OMIT_AUTOVACUUM */ +# define setChildPtrmaps(x) SQLITE_OK +#endif + +/* +** This routine does the first phase of a two-phase commit. This routine +** causes a rollback journal to be created (if it does not already exist) +** and populated with enough information so that if a power loss occurs +** the database can be restored to its original state by playing back +** the journal. Then the contents of the journal are flushed out to +** the disk. After the journal is safely on oxide, the changes to the +** database are written into the database file and flushed to oxide. +** At the end of this call, the rollback journal still exists on the +** disk and we are still holding all locks, so the transaction has not +** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the +** commit process. +** +** This call is a no-op if no write-transaction is currently active on pBt. +** +** Otherwise, sync the database file for the btree pBt. zMaster points to +** the name of a master journal file that should be written into the +** individual journal file, or is NULL, indicating no master journal file +** (single database transaction). +** +** When this is called, the master journal should already have been +** created, populated with this journal pointer and synced to disk. +** +** Once this is routine has returned, the only thing required to commit +** the write-transaction for this database file is to delete the journal. +*/ +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ + int rc = SQLITE_OK; + if( p->inTrans==TRANS_WRITE ){ + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum ){ + rc = autoVacuumCommit(pBt); + if( rc!=SQLITE_OK ){ + sqlite3BtreeLeave(p); + return rc; + } + } + if( pBt->bDoTruncate ){ + sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); + } +#endif + rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); + sqlite3BtreeLeave(p); + } + return rc; +} + +/* +** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() +** at the conclusion of a transaction. +*/ +static void btreeEndTransaction(Btree *p){ + BtShared *pBt = p->pBt; + sqlite3 *db = p->db; + assert( sqlite3BtreeHoldsMutex(p) ); + +#ifndef SQLITE_OMIT_AUTOVACUUM + pBt->bDoTruncate = 0; +#endif + if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){ + /* If there are other active statements that belong to this database + ** handle, downgrade to a read-only transaction. The other statements + ** may still be reading from the database. */ + downgradeAllSharedCacheTableLocks(p); + p->inTrans = TRANS_READ; + }else{ + /* If the handle had any kind of transaction open, decrement the + ** transaction count of the shared btree. If the transaction count + ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() + ** call below will unlock the pager. */ + if( p->inTrans!=TRANS_NONE ){ + clearAllSharedCacheTableLocks(p); + pBt->nTransaction--; + if( 0==pBt->nTransaction ){ + pBt->inTransaction = TRANS_NONE; + } + } + + /* Set the current transaction state to TRANS_NONE and unlock the + ** pager if this call closed the only read or write transaction. */ + p->inTrans = TRANS_NONE; + unlockBtreeIfUnused(pBt); + } + + btreeIntegrity(p); +} + +/* +** Commit the transaction currently in progress. +** +** This routine implements the second phase of a 2-phase commit. The +** sqlite3BtreeCommitPhaseOne() routine does the first phase and should +** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() +** routine did all the work of writing information out to disk and flushing the +** contents so that they are written onto the disk platter. All this +** routine has to do is delete or truncate or zero the header in the +** the rollback journal (which causes the transaction to commit) and +** drop locks. +** +** Normally, if an error occurs while the pager layer is attempting to +** finalize the underlying journal file, this function returns an error and +** the upper layer will attempt a rollback. However, if the second argument +** is non-zero then this b-tree transaction is part of a multi-file +** transaction. In this case, the transaction has already been committed +** (by deleting a master journal file) and the caller will ignore this +** functions return code. So, even if an error occurs in the pager layer, +** reset the b-tree objects internal state to indicate that the write +** transaction has been closed. This is quite safe, as the pager will have +** transitioned to the error state. +** +** This will release the write lock on the database file. If there +** are no active cursors, it also releases the read lock. +*/ +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ + + if( p->inTrans==TRANS_NONE ) return SQLITE_OK; + sqlite3BtreeEnter(p); + btreeIntegrity(p); + + /* If the handle has a write-transaction open, commit the shared-btrees + ** transaction and set the shared state to TRANS_READ. + */ + if( p->inTrans==TRANS_WRITE ){ + int rc; + BtShared *pBt = p->pBt; + assert( pBt->inTransaction==TRANS_WRITE ); + assert( pBt->nTransaction>0 ); + rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); + if( rc!=SQLITE_OK && bCleanup==0 ){ + sqlite3BtreeLeave(p); + return rc; + } + pBt->inTransaction = TRANS_READ; + btreeClearHasContent(pBt); + } + + btreeEndTransaction(p); + sqlite3BtreeLeave(p); + return SQLITE_OK; +} + +/* +** Do both phases of a commit. +*/ +SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){ + int rc; + sqlite3BtreeEnter(p); + rc = sqlite3BtreeCommitPhaseOne(p, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeCommitPhaseTwo(p, 0); + } + sqlite3BtreeLeave(p); + return rc; +} + +/* +** This routine sets the state to CURSOR_FAULT and the error +** code to errCode for every cursor on BtShared that pBtree +** references. +** +** Every cursor is tripped, including cursors that belong +** to other database connections that happen to be sharing +** the cache with pBtree. +** +** This routine gets called when a rollback occurs. +** All cursors using the same cache must be tripped +** to prevent them from trying to use the btree after +** the rollback. The rollback may have deleted tables +** or moved root pages, so it is not sufficient to +** save the state of the cursor. The cursor must be +** invalidated. +*/ +SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){ + BtCursor *p; + if( pBtree==0 ) return; + sqlite3BtreeEnter(pBtree); + for(p=pBtree->pBt->pCursor; p; p=p->pNext){ + int i; + sqlite3BtreeClearCursor(p); + p->eState = CURSOR_FAULT; + p->skipNext = errCode; + for(i=0; i<=p->iPage; i++){ + releasePage(p->apPage[i]); + p->apPage[i] = 0; + } + } + sqlite3BtreeLeave(pBtree); +} + +/* +** Rollback the transaction in progress. All cursors will be +** invalided by this operation. Any attempt to use a cursor +** that was open at the beginning of this operation will result +** in an error. +** +** This will release the write lock on the database file. If there +** are no active cursors, it also releases the read lock. +*/ +SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){ + int rc; + BtShared *pBt = p->pBt; + MemPage *pPage1; + + sqlite3BtreeEnter(p); + if( tripCode==SQLITE_OK ){ + rc = tripCode = saveAllCursors(pBt, 0, 0); + }else{ + rc = SQLITE_OK; + } + if( tripCode ){ + sqlite3BtreeTripAllCursors(p, tripCode); + } + btreeIntegrity(p); + + if( p->inTrans==TRANS_WRITE ){ + int rc2; + + assert( TRANS_WRITE==pBt->inTransaction ); + rc2 = sqlite3PagerRollback(pBt->pPager); + if( rc2!=SQLITE_OK ){ + rc = rc2; + } + + /* The rollback may have destroyed the pPage1->aData value. So + ** call btreeGetPage() on page 1 again to make + ** sure pPage1->aData is set correctly. */ + if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ + int nPage = get4byte(28+(u8*)pPage1->aData); + testcase( nPage==0 ); + if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); + testcase( pBt->nPage!=nPage ); + pBt->nPage = nPage; + releasePage(pPage1); + } + assert( countValidCursors(pBt, 1)==0 ); + pBt->inTransaction = TRANS_READ; + btreeClearHasContent(pBt); + } + + btreeEndTransaction(p); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Start a statement subtransaction. The subtransaction can can be rolled +** back independently of the main transaction. You must start a transaction +** before starting a subtransaction. The subtransaction is ended automatically +** if the main transaction commits or rolls back. +** +** Statement subtransactions are used around individual SQL statements +** that are contained within a BEGIN...COMMIT block. If a constraint +** error occurs within the statement, the effect of that one statement +** can be rolled back without having to rollback the entire transaction. +** +** A statement sub-transaction is implemented as an anonymous savepoint. The +** value passed as the second parameter is the total number of savepoints, +** including the new anonymous savepoint, open on the B-Tree. i.e. if there +** are no active savepoints and no other statement-transactions open, +** iStatement is 1. This anonymous savepoint can be released or rolled back +** using the sqlite3BtreeSavepoint() function. +*/ +SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ + int rc; + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); + assert( p->inTrans==TRANS_WRITE ); + assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); + assert( iStatement>0 ); + assert( iStatement>p->db->nSavepoint ); + assert( pBt->inTransaction==TRANS_WRITE ); + /* At the pager level, a statement transaction is a savepoint with + ** an index greater than all savepoints created explicitly using + ** SQL statements. It is illegal to open, release or rollback any + ** such savepoints while the statement transaction savepoint is active. + */ + rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** The second argument to this function, op, is always SAVEPOINT_ROLLBACK +** or SAVEPOINT_RELEASE. This function either releases or rolls back the +** savepoint identified by parameter iSavepoint, depending on the value +** of op. +** +** Normally, iSavepoint is greater than or equal to zero. However, if op is +** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the +** contents of the entire transaction are rolled back. This is different +** from a normal transaction rollback, as no locks are released and the +** transaction remains open. +*/ +SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ + int rc = SQLITE_OK; + if( p && p->inTrans==TRANS_WRITE ){ + BtShared *pBt = p->pBt; + assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); + assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); + sqlite3BtreeEnter(p); + rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); + if( rc==SQLITE_OK ){ + if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ + pBt->nPage = 0; + } + rc = newDatabase(pBt); + pBt->nPage = get4byte(28 + pBt->pPage1->aData); + + /* The database size was written into the offset 28 of the header + ** when the transaction started, so we know that the value at offset + ** 28 is nonzero. */ + assert( pBt->nPage>0 ); + } + sqlite3BtreeLeave(p); + } + return rc; +} + +/* +** Create a new cursor for the BTree whose root is on the page +** iTable. If a read-only cursor is requested, it is assumed that +** the caller already has at least a read-only transaction open +** on the database already. If a write-cursor is requested, then +** the caller is assumed to have an open write transaction. +** +** If wrFlag==0, then the cursor can only be used for reading. +** If wrFlag==1, then the cursor can be used for reading or for +** writing if other conditions for writing are also met. These +** are the conditions that must be met in order for writing to +** be allowed: +** +** 1: The cursor must have been opened with wrFlag==1 +** +** 2: Other database connections that share the same pager cache +** but which are not in the READ_UNCOMMITTED state may not have +** cursors open with wrFlag==0 on the same table. Otherwise +** the changes made by this write cursor would be visible to +** the read cursors in the other database connection. +** +** 3: The database must be writable (not on read-only media) +** +** 4: There must be an active transaction. +** +** No checking is done to make sure that page iTable really is the +** root page of a b-tree. If it is not, then the cursor acquired +** will not work correctly. +** +** It is assumed that the sqlite3BtreeCursorZero() has been called +** on pCur to initialize the memory space prior to invoking this routine. +*/ +static int btreeCursor( + Btree *p, /* The btree */ + int iTable, /* Root page of table to open */ + int wrFlag, /* 1 to write. 0 read-only */ + struct KeyInfo *pKeyInfo, /* First arg to comparison function */ + BtCursor *pCur /* Space for new cursor */ +){ + BtShared *pBt = p->pBt; /* Shared b-tree handle */ + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( wrFlag==0 || wrFlag==1 ); + + /* The following assert statements verify that if this is a sharable + ** b-tree database, the connection is holding the required table locks, + ** and that no other connection has any open cursor that conflicts with + ** this lock. */ + assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) ); + assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); + + /* Assert that the caller has opened the required transaction. */ + assert( p->inTrans>TRANS_NONE ); + assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); + assert( pBt->pPage1 && pBt->pPage1->aData ); + + if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){ + return SQLITE_READONLY; + } + if( iTable==1 && btreePagecount(pBt)==0 ){ + assert( wrFlag==0 ); + iTable = 0; + } + + /* Now that no other errors can occur, finish filling in the BtCursor + ** variables and link the cursor into the BtShared list. */ + pCur->pgnoRoot = (Pgno)iTable; + pCur->iPage = -1; + pCur->pKeyInfo = pKeyInfo; + pCur->pBtree = p; + pCur->pBt = pBt; + pCur->wrFlag = (u8)wrFlag; + pCur->pNext = pBt->pCursor; + if( pCur->pNext ){ + pCur->pNext->pPrev = pCur; + } + pBt->pCursor = pCur; + pCur->eState = CURSOR_INVALID; + pCur->cachedRowid = 0; + return SQLITE_OK; +} +SQLITE_PRIVATE int sqlite3BtreeCursor( + Btree *p, /* The btree */ + int iTable, /* Root page of table to open */ + int wrFlag, /* 1 to write. 0 read-only */ + struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ + BtCursor *pCur /* Write new cursor here */ +){ + int rc; + sqlite3BtreeEnter(p); + rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Return the size of a BtCursor object in bytes. +** +** This interfaces is needed so that users of cursors can preallocate +** sufficient storage to hold a cursor. The BtCursor object is opaque +** to users so they cannot do the sizeof() themselves - they must call +** this routine. +*/ +SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){ + return ROUND8(sizeof(BtCursor)); +} + +/* +** Initialize memory that will be converted into a BtCursor object. +** +** The simple approach here would be to memset() the entire object +** to zero. But it turns out that the apPage[] and aiIdx[] arrays +** do not need to be zeroed and they are large, so we can save a lot +** of run-time by skipping the initialization of those elements. +*/ +SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){ + memset(p, 0, offsetof(BtCursor, iPage)); +} + +/* +** Set the cached rowid value of every cursor in the same database file +** as pCur and having the same root page number as pCur. The value is +** set to iRowid. +** +** Only positive rowid values are considered valid for this cache. +** The cache is initialized to zero, indicating an invalid cache. +** A btree will work fine with zero or negative rowids. We just cannot +** cache zero or negative rowids, which means tables that use zero or +** negative rowids might run a little slower. But in practice, zero +** or negative rowids are very uncommon so this should not be a problem. +*/ +SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){ + BtCursor *p; + for(p=pCur->pBt->pCursor; p; p=p->pNext){ + if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid; + } + assert( pCur->cachedRowid==iRowid ); +} + +/* +** Return the cached rowid for the given cursor. A negative or zero +** return value indicates that the rowid cache is invalid and should be +** ignored. If the rowid cache has never before been set, then a +** zero is returned. +*/ +SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){ + return pCur->cachedRowid; +} + +/* +** Close a cursor. The read lock on the database file is released +** when the last cursor is closed. +*/ +SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){ + Btree *pBtree = pCur->pBtree; + if( pBtree ){ + int i; + BtShared *pBt = pCur->pBt; + sqlite3BtreeEnter(pBtree); + sqlite3BtreeClearCursor(pCur); + if( pCur->pPrev ){ + pCur->pPrev->pNext = pCur->pNext; + }else{ + pBt->pCursor = pCur->pNext; + } + if( pCur->pNext ){ + pCur->pNext->pPrev = pCur->pPrev; + } + for(i=0; i<=pCur->iPage; i++){ + releasePage(pCur->apPage[i]); + } + unlockBtreeIfUnused(pBt); + invalidateOverflowCache(pCur); + /* sqlite3_free(pCur); */ + sqlite3BtreeLeave(pBtree); + } + return SQLITE_OK; +} + +/* +** Make sure the BtCursor* given in the argument has a valid +** BtCursor.info structure. If it is not already valid, call +** btreeParseCell() to fill it in. +** +** BtCursor.info is a cache of the information in the current cell. +** Using this cache reduces the number of calls to btreeParseCell(). +** +** 2007-06-25: There is a bug in some versions of MSVC that cause the +** compiler to crash when getCellInfo() is implemented as a macro. +** But there is a measureable speed advantage to using the macro on gcc +** (when less compiler optimizations like -Os or -O0 are used and the +** compiler is not doing agressive inlining.) So we use a real function +** for MSVC and a macro for everything else. Ticket #2457. +*/ +#ifndef NDEBUG + static void assertCellInfo(BtCursor *pCur){ + CellInfo info; + int iPage = pCur->iPage; + memset(&info, 0, sizeof(info)); + btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info); + assert( memcmp(&info, &pCur->info, sizeof(info))==0 ); + } +#else + #define assertCellInfo(x) +#endif +#ifdef _MSC_VER + /* Use a real function in MSVC to work around bugs in that compiler. */ + static void getCellInfo(BtCursor *pCur){ + if( pCur->info.nSize==0 ){ + int iPage = pCur->iPage; + btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); + pCur->validNKey = 1; + }else{ + assertCellInfo(pCur); + } + } +#else /* if not _MSC_VER */ + /* Use a macro in all other compilers so that the function is inlined */ +#define getCellInfo(pCur) \ + if( pCur->info.nSize==0 ){ \ + int iPage = pCur->iPage; \ + btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \ + pCur->validNKey = 1; \ + }else{ \ + assertCellInfo(pCur); \ + } +#endif /* _MSC_VER */ + +#ifndef NDEBUG /* The next routine used only within assert() statements */ +/* +** Return true if the given BtCursor is valid. A valid cursor is one +** that is currently pointing to a row in a (non-empty) table. +** This is a verification routine is used only within assert() statements. +*/ +SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){ + return pCur && pCur->eState==CURSOR_VALID; +} +#endif /* NDEBUG */ + +/* +** Set *pSize to the size of the buffer needed to hold the value of +** the key for the current entry. If the cursor is not pointing +** to a valid entry, *pSize is set to 0. +** +** For a table with the INTKEY flag set, this routine returns the key +** itself, not the number of bytes in the key. +** +** The caller must position the cursor prior to invoking this routine. +** +** This routine cannot fail. It always returns SQLITE_OK. +*/ +SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID ); + if( pCur->eState!=CURSOR_VALID ){ + *pSize = 0; + }else{ + getCellInfo(pCur); + *pSize = pCur->info.nKey; + } + return SQLITE_OK; +} + +/* +** Set *pSize to the number of bytes of data in the entry the +** cursor currently points to. +** +** The caller must guarantee that the cursor is pointing to a non-NULL +** valid entry. In other words, the calling procedure must guarantee +** that the cursor has Cursor.eState==CURSOR_VALID. +** +** Failure is not possible. This function always returns SQLITE_OK. +** It might just as well be a procedure (returning void) but we continue +** to return an integer result code for historical reasons. +*/ +SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + getCellInfo(pCur); + *pSize = pCur->info.nData; + return SQLITE_OK; +} + +/* +** Given the page number of an overflow page in the database (parameter +** ovfl), this function finds the page number of the next page in the +** linked list of overflow pages. If possible, it uses the auto-vacuum +** pointer-map data instead of reading the content of page ovfl to do so. +** +** If an error occurs an SQLite error code is returned. Otherwise: +** +** The page number of the next overflow page in the linked list is +** written to *pPgnoNext. If page ovfl is the last page in its linked +** list, *pPgnoNext is set to zero. +** +** If ppPage is not NULL, and a reference to the MemPage object corresponding +** to page number pOvfl was obtained, then *ppPage is set to point to that +** reference. It is the responsibility of the caller to call releasePage() +** on *ppPage to free the reference. In no reference was obtained (because +** the pointer-map was used to obtain the value for *pPgnoNext), then +** *ppPage is set to zero. +*/ +static int getOverflowPage( + BtShared *pBt, /* The database file */ + Pgno ovfl, /* Current overflow page number */ + MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */ + Pgno *pPgnoNext /* OUT: Next overflow page number */ +){ + Pgno next = 0; + MemPage *pPage = 0; + int rc = SQLITE_OK; + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert(pPgnoNext); + +#ifndef SQLITE_OMIT_AUTOVACUUM + /* Try to find the next page in the overflow list using the + ** autovacuum pointer-map pages. Guess that the next page in + ** the overflow list is page number (ovfl+1). If that guess turns + ** out to be wrong, fall back to loading the data of page + ** number ovfl to determine the next page number. + */ + if( pBt->autoVacuum ){ + Pgno pgno; + Pgno iGuess = ovfl+1; + u8 eType; + + while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){ + iGuess++; + } + + if( iGuess<=btreePagecount(pBt) ){ + rc = ptrmapGet(pBt, iGuess, &eType, &pgno); + if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ + next = iGuess; + rc = SQLITE_DONE; + } + } + } +#endif + + assert( next==0 || rc==SQLITE_DONE ); + if( rc==SQLITE_OK ){ + rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0); + assert( rc==SQLITE_OK || pPage==0 ); + if( rc==SQLITE_OK ){ + next = get4byte(pPage->aData); + } + } + + *pPgnoNext = next; + if( ppPage ){ + *ppPage = pPage; + }else{ + releasePage(pPage); + } + return (rc==SQLITE_DONE ? SQLITE_OK : rc); +} + +/* +** Copy data from a buffer to a page, or from a page to a buffer. +** +** pPayload is a pointer to data stored on database page pDbPage. +** If argument eOp is false, then nByte bytes of data are copied +** from pPayload to the buffer pointed at by pBuf. If eOp is true, +** then sqlite3PagerWrite() is called on pDbPage and nByte bytes +** of data are copied from the buffer pBuf to pPayload. +** +** SQLITE_OK is returned on success, otherwise an error code. +*/ +static int copyPayload( + void *pPayload, /* Pointer to page data */ + void *pBuf, /* Pointer to buffer */ + int nByte, /* Number of bytes to copy */ + int eOp, /* 0 -> copy from page, 1 -> copy to page */ + DbPage *pDbPage /* Page containing pPayload */ +){ + if( eOp ){ + /* Copy data from buffer to page (a write operation) */ + int rc = sqlite3PagerWrite(pDbPage); + if( rc!=SQLITE_OK ){ + return rc; + } + memcpy(pPayload, pBuf, nByte); + }else{ + /* Copy data from page to buffer (a read operation) */ + memcpy(pBuf, pPayload, nByte); + } + return SQLITE_OK; +} + +/* +** This function is used to read or overwrite payload information +** for the entry that the pCur cursor is pointing to. If the eOp +** parameter is 0, this is a read operation (data copied into +** buffer pBuf). If it is non-zero, a write (data copied from +** buffer pBuf). +** +** A total of "amt" bytes are read or written beginning at "offset". +** Data is read to or from the buffer pBuf. +** +** The content being read or written might appear on the main page +** or be scattered out on multiple overflow pages. +** +** If the BtCursor.isIncrblobHandle flag is set, and the current +** cursor entry uses one or more overflow pages, this function +** allocates space for and lazily popluates the overflow page-list +** cache array (BtCursor.aOverflow). Subsequent calls use this +** cache to make seeking to the supplied offset more efficient. +** +** Once an overflow page-list cache has been allocated, it may be +** invalidated if some other cursor writes to the same table, or if +** the cursor is moved to a different row. Additionally, in auto-vacuum +** mode, the following events may invalidate an overflow page-list cache. +** +** * An incremental vacuum, +** * A commit in auto_vacuum="full" mode, +** * Creating a table (may require moving an overflow page). +*/ +static int accessPayload( + BtCursor *pCur, /* Cursor pointing to entry to read from */ + u32 offset, /* Begin reading this far into payload */ + u32 amt, /* Read this many bytes */ + unsigned char *pBuf, /* Write the bytes into this buffer */ + int eOp /* zero to read. non-zero to write. */ +){ + unsigned char *aPayload; + int rc = SQLITE_OK; + u32 nKey; + int iIdx = 0; + MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */ + BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ + + assert( pPage ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->aiIdx[pCur->iPage]nCell ); + assert( cursorHoldsMutex(pCur) ); + + getCellInfo(pCur); + aPayload = pCur->info.pCell + pCur->info.nHeader; + nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey); + + if( NEVER(offset+amt > nKey+pCur->info.nData) + || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] + ){ + /* Trying to read or write past the end of the data is an error */ + return SQLITE_CORRUPT_BKPT; + } + + /* Check if data must be read/written to/from the btree page itself. */ + if( offsetinfo.nLocal ){ + int a = amt; + if( a+offset>pCur->info.nLocal ){ + a = pCur->info.nLocal - offset; + } + rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); + offset = 0; + pBuf += a; + amt -= a; + }else{ + offset -= pCur->info.nLocal; + } + + if( rc==SQLITE_OK && amt>0 ){ + const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ + Pgno nextPage; + + nextPage = get4byte(&aPayload[pCur->info.nLocal]); + +#ifndef SQLITE_OMIT_INCRBLOB + /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[] + ** has not been allocated, allocate it now. The array is sized at + ** one entry for each overflow page in the overflow chain. The + ** page number of the first overflow page is stored in aOverflow[0], + ** etc. A value of 0 in the aOverflow[] array means "not yet known" + ** (the cache is lazily populated). + */ + if( pCur->isIncrblobHandle && !pCur->aOverflow ){ + int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; + pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl); + /* nOvfl is always positive. If it were zero, fetchPayload would have + ** been used instead of this routine. */ + if( ALWAYS(nOvfl) && !pCur->aOverflow ){ + rc = SQLITE_NOMEM; + } + } + + /* If the overflow page-list cache has been allocated and the + ** entry for the first required overflow page is valid, skip + ** directly to it. + */ + if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){ + iIdx = (offset/ovflSize); + nextPage = pCur->aOverflow[iIdx]; + offset = (offset%ovflSize); + } +#endif + + for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){ + +#ifndef SQLITE_OMIT_INCRBLOB + /* If required, populate the overflow page-list cache. */ + if( pCur->aOverflow ){ + assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage); + pCur->aOverflow[iIdx] = nextPage; + } +#endif + + if( offset>=ovflSize ){ + /* The only reason to read this page is to obtain the page + ** number for the next page in the overflow chain. The page + ** data is not required. So first try to lookup the overflow + ** page-list cache, if any, then fall back to the getOverflowPage() + ** function. + */ +#ifndef SQLITE_OMIT_INCRBLOB + if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){ + nextPage = pCur->aOverflow[iIdx+1]; + } else +#endif + rc = getOverflowPage(pBt, nextPage, 0, &nextPage); + offset -= ovflSize; + }else{ + /* Need to read this page properly. It contains some of the + ** range of data that is being read (eOp==0) or written (eOp!=0). + */ +#ifdef SQLITE_DIRECT_OVERFLOW_READ + sqlite3_file *fd; +#endif + int a = amt; + if( a + offset > ovflSize ){ + a = ovflSize - offset; + } + +#ifdef SQLITE_DIRECT_OVERFLOW_READ + /* If all the following are true: + ** + ** 1) this is a read operation, and + ** 2) data is required from the start of this overflow page, and + ** 3) the database is file-backed, and + ** 4) there is no open write-transaction, and + ** 5) the database is not a WAL database, + ** + ** then data can be read directly from the database file into the + ** output buffer, bypassing the page-cache altogether. This speeds + ** up loading large records that span many overflow pages. + */ + if( eOp==0 /* (1) */ + && offset==0 /* (2) */ + && pBt->inTransaction==TRANS_READ /* (4) */ + && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */ + && pBt->pPage1->aData[19]==0x01 /* (5) */ + ){ + u8 aSave[4]; + u8 *aWrite = &pBuf[-4]; + memcpy(aSave, aWrite, 4); + rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); + nextPage = get4byte(aWrite); + memcpy(aWrite, aSave, 4); + }else +#endif + + { + DbPage *pDbPage; + rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage, + (eOp==0 ? PAGER_GET_READONLY : 0) + ); + if( rc==SQLITE_OK ){ + aPayload = sqlite3PagerGetData(pDbPage); + nextPage = get4byte(aPayload); + rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); + sqlite3PagerUnref(pDbPage); + offset = 0; + } + } + amt -= a; + pBuf += a; + } + } + } + + if( rc==SQLITE_OK && amt>0 ){ + return SQLITE_CORRUPT_BKPT; + } + return rc; +} + +/* +** Read part of the key associated with cursor pCur. Exactly +** "amt" bytes will be transfered into pBuf[]. The transfer +** begins at "offset". +** +** The caller must ensure that pCur is pointing to a valid row +** in the table. +** +** Return SQLITE_OK on success or an error code if anything goes +** wrong. An error is returned if "offset+amt" is larger than +** the available payload. +*/ +SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); + assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); + return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); +} + +/* +** Read part of the data associated with cursor pCur. Exactly +** "amt" bytes will be transfered into pBuf[]. The transfer +** begins at "offset". +** +** Return SQLITE_OK on success or an error code if anything goes +** wrong. An error is returned if "offset+amt" is larger than +** the available payload. +*/ +SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ + int rc; + +#ifndef SQLITE_OMIT_INCRBLOB + if ( pCur->eState==CURSOR_INVALID ){ + return SQLITE_ABORT; + } +#endif + + assert( cursorHoldsMutex(pCur) ); + rc = restoreCursorPosition(pCur); + if( rc==SQLITE_OK ){ + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); + assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); + rc = accessPayload(pCur, offset, amt, pBuf, 0); + } + return rc; +} + +/* +** Return a pointer to payload information from the entry that the +** pCur cursor is pointing to. The pointer is to the beginning of +** the key if skipKey==0 and it points to the beginning of data if +** skipKey==1. The number of bytes of available key/data is written +** into *pAmt. If *pAmt==0, then the value returned will not be +** a valid pointer. +** +** This routine is an optimization. It is common for the entire key +** and data to fit on the local page and for there to be no overflow +** pages. When that is so, this routine can be used to access the +** key and data without making a copy. If the key and/or data spills +** onto overflow pages, then accessPayload() must be used to reassemble +** the key/data and copy it into a preallocated buffer. +** +** The pointer returned by this routine looks directly into the cached +** page of the database. The data might change or move the next time +** any btree routine is called. +*/ +static const unsigned char *fetchPayload( + BtCursor *pCur, /* Cursor pointing to entry to read from */ + int *pAmt, /* Write the number of available bytes here */ + int skipKey /* read beginning at data if this is true */ +){ + unsigned char *aPayload; + MemPage *pPage; + u32 nKey; + u32 nLocal; + + assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]); + assert( pCur->eState==CURSOR_VALID ); + assert( cursorHoldsMutex(pCur) ); + pPage = pCur->apPage[pCur->iPage]; + assert( pCur->aiIdx[pCur->iPage]nCell ); + if( NEVER(pCur->info.nSize==0) ){ + btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage], + &pCur->info); + } + aPayload = pCur->info.pCell; + aPayload += pCur->info.nHeader; + if( pPage->intKey ){ + nKey = 0; + }else{ + nKey = (int)pCur->info.nKey; + } + if( skipKey ){ + aPayload += nKey; + nLocal = pCur->info.nLocal - nKey; + }else{ + nLocal = pCur->info.nLocal; + assert( nLocal<=nKey ); + } + *pAmt = nLocal; + return aPayload; +} + + +/* +** For the entry that cursor pCur is point to, return as +** many bytes of the key or data as are available on the local +** b-tree page. Write the number of available bytes into *pAmt. +** +** The pointer returned is ephemeral. The key/data may move +** or be destroyed on the next call to any Btree routine, +** including calls from other threads against the same cache. +** Hence, a mutex on the BtShared should be held prior to calling +** this routine. +** +** These routines is used to get quick access to key and data +** in the common case where no overflow pages are used. +*/ +SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){ + const void *p = 0; + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( cursorHoldsMutex(pCur) ); + if( ALWAYS(pCur->eState==CURSOR_VALID) ){ + p = (const void*)fetchPayload(pCur, pAmt, 0); + } + return p; +} +SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){ + const void *p = 0; + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( cursorHoldsMutex(pCur) ); + if( ALWAYS(pCur->eState==CURSOR_VALID) ){ + p = (const void*)fetchPayload(pCur, pAmt, 1); + } + return p; +} + + +/* +** Move the cursor down to a new child page. The newPgno argument is the +** page number of the child page to move to. +** +** This function returns SQLITE_CORRUPT if the page-header flags field of +** the new child page does not match the flags field of the parent (i.e. +** if an intkey page appears to be the parent of a non-intkey page, or +** vice-versa). +*/ +static int moveToChild(BtCursor *pCur, u32 newPgno){ + int rc; + int i = pCur->iPage; + MemPage *pNewPage; + BtShared *pBt = pCur->pBt; + + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->iPageiPage>=0 ); + if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ + return SQLITE_CORRUPT_BKPT; + } + rc = getAndInitPage(pBt, newPgno, &pNewPage, + pCur->wrFlag==0 ? PAGER_GET_READONLY : 0); + if( rc ) return rc; + pCur->apPage[i+1] = pNewPage; + pCur->aiIdx[i+1] = 0; + pCur->iPage++; + + pCur->info.nSize = 0; + pCur->validNKey = 0; + if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){ + return SQLITE_CORRUPT_BKPT; + } + return SQLITE_OK; +} + +#if 0 +/* +** Page pParent is an internal (non-leaf) tree page. This function +** asserts that page number iChild is the left-child if the iIdx'th +** cell in page pParent. Or, if iIdx is equal to the total number of +** cells in pParent, that page number iChild is the right-child of +** the page. +*/ +static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ + assert( iIdx<=pParent->nCell ); + if( iIdx==pParent->nCell ){ + assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild ); + }else{ + assert( get4byte(findCell(pParent, iIdx))==iChild ); + } +} +#else +# define assertParentIndex(x,y,z) +#endif + +/* +** Move the cursor up to the parent page. +** +** pCur->idx is set to the cell index that contains the pointer +** to the page we are coming from. If we are coming from the +** right-most child page then pCur->idx is set to one more than +** the largest cell index. +*/ +static void moveToParent(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->iPage>0 ); + assert( pCur->apPage[pCur->iPage] ); + + /* UPDATE: It is actually possible for the condition tested by the assert + ** below to be untrue if the database file is corrupt. This can occur if + ** one cursor has modified page pParent while a reference to it is held + ** by a second cursor. Which can only happen if a single page is linked + ** into more than one b-tree structure in a corrupt database. */ +#if 0 + assertParentIndex( + pCur->apPage[pCur->iPage-1], + pCur->aiIdx[pCur->iPage-1], + pCur->apPage[pCur->iPage]->pgno + ); +#endif + testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); + + releasePage(pCur->apPage[pCur->iPage]); + pCur->iPage--; + pCur->info.nSize = 0; + pCur->validNKey = 0; +} + +/* +** Move the cursor to point to the root page of its b-tree structure. +** +** If the table has a virtual root page, then the cursor is moved to point +** to the virtual root page instead of the actual root page. A table has a +** virtual root page when the actual root page contains no cells and a +** single child page. This can only happen with the table rooted at page 1. +** +** If the b-tree structure is empty, the cursor state is set to +** CURSOR_INVALID. Otherwise, the cursor is set to point to the first +** cell located on the root (or virtual root) page and the cursor state +** is set to CURSOR_VALID. +** +** If this function returns successfully, it may be assumed that the +** page-header flags indicate that the [virtual] root-page is the expected +** kind of b-tree page (i.e. if when opening the cursor the caller did not +** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, +** indicating a table b-tree, or if the caller did specify a KeyInfo +** structure the flags byte is set to 0x02 or 0x0A, indicating an index +** b-tree). +*/ +static int moveToRoot(BtCursor *pCur){ + MemPage *pRoot; + int rc = SQLITE_OK; + Btree *p = pCur->pBtree; + BtShared *pBt = p->pBt; + + assert( cursorHoldsMutex(pCur) ); + assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); + assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); + assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); + if( pCur->eState>=CURSOR_REQUIRESEEK ){ + if( pCur->eState==CURSOR_FAULT ){ + assert( pCur->skipNext!=SQLITE_OK ); + return pCur->skipNext; + } + sqlite3BtreeClearCursor(pCur); + } + + if( pCur->iPage>=0 ){ + int i; + for(i=1; i<=pCur->iPage; i++){ + releasePage(pCur->apPage[i]); + } + pCur->iPage = 0; + }else if( pCur->pgnoRoot==0 ){ + pCur->eState = CURSOR_INVALID; + return SQLITE_OK; + }else{ + rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0], + pCur->wrFlag==0 ? PAGER_GET_READONLY : 0); + if( rc!=SQLITE_OK ){ + pCur->eState = CURSOR_INVALID; + return rc; + } + pCur->iPage = 0; + + /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor + ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is + ** NULL, the caller expects a table b-tree. If this is not the case, + ** return an SQLITE_CORRUPT error. */ + assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 ); + if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){ + return SQLITE_CORRUPT_BKPT; + } + } + + /* Assert that the root page is of the correct type. This must be the + ** case as the call to this function that loaded the root-page (either + ** this call or a previous invocation) would have detected corruption + ** if the assumption were not true, and it is not possible for the flags + ** byte to have been modified while this cursor is holding a reference + ** to the page. */ + pRoot = pCur->apPage[0]; + assert( pRoot->pgno==pCur->pgnoRoot ); + assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey ); + + pCur->aiIdx[0] = 0; + pCur->info.nSize = 0; + pCur->atLast = 0; + pCur->validNKey = 0; + + if( pRoot->nCell==0 && !pRoot->leaf ){ + Pgno subpage; + if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; + subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); + pCur->eState = CURSOR_VALID; + rc = moveToChild(pCur, subpage); + }else{ + pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID); + } + return rc; +} + +/* +** Move the cursor down to the left-most leaf entry beneath the +** entry to which it is currently pointing. +** +** The left-most leaf is the one with the smallest key - the first +** in ascending order. +*/ +static int moveToLeftmost(BtCursor *pCur){ + Pgno pgno; + int rc = SQLITE_OK; + MemPage *pPage; + + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){ + assert( pCur->aiIdx[pCur->iPage]nCell ); + pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage])); + rc = moveToChild(pCur, pgno); + } + return rc; +} + +/* +** Move the cursor down to the right-most leaf entry beneath the +** page to which it is currently pointing. Notice the difference +** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() +** finds the left-most entry beneath the *entry* whereas moveToRightmost() +** finds the right-most entry beneath the *page*. +** +** The right-most entry is the one with the largest key - the last +** key in ascending order. +*/ +static int moveToRightmost(BtCursor *pCur){ + Pgno pgno; + int rc = SQLITE_OK; + MemPage *pPage = 0; + + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){ + pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); + pCur->aiIdx[pCur->iPage] = pPage->nCell; + rc = moveToChild(pCur, pgno); + } + if( rc==SQLITE_OK ){ + pCur->aiIdx[pCur->iPage] = pPage->nCell-1; + pCur->info.nSize = 0; + pCur->validNKey = 0; + } + return rc; +} + +/* Move the cursor to the first entry in the table. Return SQLITE_OK +** on success. Set *pRes to 0 if the cursor actually points to something +** or set *pRes to 1 if the table is empty. +*/ +SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ + int rc; + + assert( cursorHoldsMutex(pCur) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + rc = moveToRoot(pCur); + if( rc==SQLITE_OK ){ + if( pCur->eState==CURSOR_INVALID ){ + assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); + *pRes = 1; + }else{ + assert( pCur->apPage[pCur->iPage]->nCell>0 ); + *pRes = 0; + rc = moveToLeftmost(pCur); + } + } + return rc; +} + +/* Move the cursor to the last entry in the table. Return SQLITE_OK +** on success. Set *pRes to 0 if the cursor actually points to something +** or set *pRes to 1 if the table is empty. +*/ +SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ + int rc; + + assert( cursorHoldsMutex(pCur) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + + /* If the cursor already points to the last entry, this is a no-op. */ + if( CURSOR_VALID==pCur->eState && pCur->atLast ){ +#ifdef SQLITE_DEBUG + /* This block serves to assert() that the cursor really does point + ** to the last entry in the b-tree. */ + int ii; + for(ii=0; iiiPage; ii++){ + assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); + } + assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 ); + assert( pCur->apPage[pCur->iPage]->leaf ); +#endif + return SQLITE_OK; + } + + rc = moveToRoot(pCur); + if( rc==SQLITE_OK ){ + if( CURSOR_INVALID==pCur->eState ){ + assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); + *pRes = 1; + }else{ + assert( pCur->eState==CURSOR_VALID ); + *pRes = 0; + rc = moveToRightmost(pCur); + pCur->atLast = rc==SQLITE_OK ?1:0; + } + } + return rc; +} + +/* Move the cursor so that it points to an entry near the key +** specified by pIdxKey or intKey. Return a success code. +** +** For INTKEY tables, the intKey parameter is used. pIdxKey +** must be NULL. For index tables, pIdxKey is used and intKey +** is ignored. +** +** If an exact match is not found, then the cursor is always +** left pointing at a leaf page which would hold the entry if it +** were present. The cursor might point to an entry that comes +** before or after the key. +** +** An integer is written into *pRes which is the result of +** comparing the key with the entry to which the cursor is +** pointing. The meaning of the integer written into +** *pRes is as follows: +** +** *pRes<0 The cursor is left pointing at an entry that +** is smaller than intKey/pIdxKey or if the table is empty +** and the cursor is therefore left point to nothing. +** +** *pRes==0 The cursor is left pointing at an entry that +** exactly matches intKey/pIdxKey. +** +** *pRes>0 The cursor is left pointing at an entry that +** is larger than intKey/pIdxKey. +** +*/ +SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( + BtCursor *pCur, /* The cursor to be moved */ + UnpackedRecord *pIdxKey, /* Unpacked index key */ + i64 intKey, /* The table key */ + int biasRight, /* If true, bias the search to the high end */ + int *pRes /* Write search results here */ +){ + int rc; + + assert( cursorHoldsMutex(pCur) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( pRes ); + assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); + + /* If the cursor is already positioned at the point we are trying + ** to move to, then just return without doing any work */ + if( pCur->eState==CURSOR_VALID && pCur->validNKey + && pCur->apPage[0]->intKey + ){ + if( pCur->info.nKey==intKey ){ + *pRes = 0; + return SQLITE_OK; + } + if( pCur->atLast && pCur->info.nKeypgnoRoot==0 || pCur->apPage[pCur->iPage] ); + assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit ); + assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 ); + if( pCur->eState==CURSOR_INVALID ){ + *pRes = -1; + assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); + return SQLITE_OK; + } + assert( pCur->apPage[0]->intKey || pIdxKey ); + for(;;){ + int lwr, upr, idx; + Pgno chldPg; + MemPage *pPage = pCur->apPage[pCur->iPage]; + int c; + + /* pPage->nCell must be greater than zero. If this is the root-page + ** the cursor would have been INVALID above and this for(;;) loop + ** not run. If this is not the root-page, then the moveToChild() routine + ** would have already detected db corruption. Similarly, pPage must + ** be the right kind (index or table) of b-tree page. Otherwise + ** a moveToChild() or moveToRoot() call would have detected corruption. */ + assert( pPage->nCell>0 ); + assert( pPage->intKey==(pIdxKey==0) ); + lwr = 0; + upr = pPage->nCell-1; + if( biasRight ){ + pCur->aiIdx[pCur->iPage] = (u16)(idx = upr); + }else{ + pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2); + } + for(;;){ + u8 *pCell; /* Pointer to current cell in pPage */ + + assert( idx==pCur->aiIdx[pCur->iPage] ); + pCur->info.nSize = 0; + pCell = findCell(pPage, idx) + pPage->childPtrSize; + if( pPage->intKey ){ + i64 nCellKey; + if( pPage->hasData ){ + u32 dummy; + pCell += getVarint32(pCell, dummy); + } + getVarint(pCell, (u64*)&nCellKey); + if( nCellKey==intKey ){ + c = 0; + }else if( nCellKeyintKey ); + c = +1; + } + pCur->validNKey = 1; + pCur->info.nKey = nCellKey; + }else{ + /* The maximum supported page-size is 65536 bytes. This means that + ** the maximum number of record bytes stored on an index B-Tree + ** page is less than 16384 bytes and may be stored as a 2-byte + ** varint. This information is used to attempt to avoid parsing + ** the entire cell by checking for the cases where the record is + ** stored entirely within the b-tree page by inspecting the first + ** 2 bytes of the cell. + */ + int nCell = pCell[0]; + if( nCell<=pPage->max1bytePayload + /* && (pCell+nCell)aDataEnd */ + ){ + /* This branch runs if the record-size field of the cell is a + ** single byte varint and the record fits entirely on the main + ** b-tree page. */ + testcase( pCell+nCell+1==pPage->aDataEnd ); + c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey); + }else if( !(pCell[1] & 0x80) + && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal + /* && (pCell+nCell+2)<=pPage->aDataEnd */ + ){ + /* The record-size field is a 2 byte varint and the record + ** fits entirely on the main b-tree page. */ + testcase( pCell+nCell+2==pPage->aDataEnd ); + c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey); + }else{ + /* The record flows over onto one or more overflow pages. In + ** this case the whole cell needs to be parsed, a buffer allocated + ** and accessPayload() used to retrieve the record into the + ** buffer before VdbeRecordCompare() can be called. */ + void *pCellKey; + u8 * const pCellBody = pCell - pPage->childPtrSize; + btreeParseCellPtr(pPage, pCellBody, &pCur->info); + nCell = (int)pCur->info.nKey; + pCellKey = sqlite3Malloc( nCell ); + if( pCellKey==0 ){ + rc = SQLITE_NOMEM; + goto moveto_finish; + } + rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); + if( rc ){ + sqlite3_free(pCellKey); + goto moveto_finish; + } + c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); + sqlite3_free(pCellKey); + } + } + if( c==0 ){ + if( pPage->intKey && !pPage->leaf ){ + lwr = idx; + break; + }else{ + *pRes = 0; + rc = SQLITE_OK; + goto moveto_finish; + } + } + if( c<0 ){ + lwr = idx+1; + }else{ + upr = idx-1; + } + if( lwr>upr ){ + break; + } + pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2); + } + assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); + assert( pPage->isInit ); + if( pPage->leaf ){ + chldPg = 0; + }else if( lwr>=pPage->nCell ){ + chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); + }else{ + chldPg = get4byte(findCell(pPage, lwr)); + } + if( chldPg==0 ){ + assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); + *pRes = c; + rc = SQLITE_OK; + goto moveto_finish; + } + pCur->aiIdx[pCur->iPage] = (u16)lwr; + pCur->info.nSize = 0; + pCur->validNKey = 0; + rc = moveToChild(pCur, chldPg); + if( rc ) goto moveto_finish; + } +moveto_finish: + return rc; +} + + +/* +** Return TRUE if the cursor is not pointing at an entry of the table. +** +** TRUE will be returned after a call to sqlite3BtreeNext() moves +** past the last entry in the table or sqlite3BtreePrev() moves past +** the first entry. TRUE is also returned if the table is empty. +*/ +SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){ + /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries + ** have been deleted? This API will need to change to return an error code + ** as well as the boolean result value. + */ + return (CURSOR_VALID!=pCur->eState); +} + +/* +** Advance the cursor to the next entry in the database. If +** successful then set *pRes=0. If the cursor +** was already pointing to the last entry in the database before +** this routine was called, then set *pRes=1. +*/ +SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ + int rc; + int idx; + MemPage *pPage; + + assert( cursorHoldsMutex(pCur) ); + assert( pRes!=0 ); + assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); + if( pCur->eState!=CURSOR_VALID ){ + rc = restoreCursorPosition(pCur); + if( rc!=SQLITE_OK ){ + *pRes = 0; + return rc; + } + if( CURSOR_INVALID==pCur->eState ){ + *pRes = 1; + return SQLITE_OK; + } + if( pCur->skipNext ){ + assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); + pCur->eState = CURSOR_VALID; + if( pCur->skipNext>0 ){ + pCur->skipNext = 0; + *pRes = 0; + return SQLITE_OK; + } + pCur->skipNext = 0; + } + } + + pPage = pCur->apPage[pCur->iPage]; + idx = ++pCur->aiIdx[pCur->iPage]; + assert( pPage->isInit ); + + /* If the database file is corrupt, it is possible for the value of idx + ** to be invalid here. This can only occur if a second cursor modifies + ** the page while cursor pCur is holding a reference to it. Which can + ** only happen if the database is corrupt in such a way as to link the + ** page into more than one b-tree structure. */ + testcase( idx>pPage->nCell ); + + pCur->info.nSize = 0; + pCur->validNKey = 0; + if( idx>=pPage->nCell ){ + if( !pPage->leaf ){ + rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); + if( rc ){ + *pRes = 0; + return rc; + } + rc = moveToLeftmost(pCur); + *pRes = 0; + return rc; + } + do{ + if( pCur->iPage==0 ){ + *pRes = 1; + pCur->eState = CURSOR_INVALID; + return SQLITE_OK; + } + moveToParent(pCur); + pPage = pCur->apPage[pCur->iPage]; + }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell ); + *pRes = 0; + if( pPage->intKey ){ + rc = sqlite3BtreeNext(pCur, pRes); + }else{ + rc = SQLITE_OK; + } + return rc; + } + *pRes = 0; + if( pPage->leaf ){ + return SQLITE_OK; + } + rc = moveToLeftmost(pCur); + return rc; +} + + +/* +** Step the cursor to the back to the previous entry in the database. If +** successful then set *pRes=0. If the cursor +** was already pointing to the first entry in the database before +** this routine was called, then set *pRes=1. +*/ +SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){ + int rc; + MemPage *pPage; + + assert( cursorHoldsMutex(pCur) ); + assert( pRes!=0 ); + assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); + pCur->atLast = 0; + if( pCur->eState!=CURSOR_VALID ){ + if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){ + rc = btreeRestoreCursorPosition(pCur); + if( rc!=SQLITE_OK ){ + *pRes = 0; + return rc; + } + } + if( CURSOR_INVALID==pCur->eState ){ + *pRes = 1; + return SQLITE_OK; + } + if( pCur->skipNext ){ + assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); + pCur->eState = CURSOR_VALID; + if( pCur->skipNext<0 ){ + pCur->skipNext = 0; + *pRes = 0; + return SQLITE_OK; + } + pCur->skipNext = 0; + } + } + + pPage = pCur->apPage[pCur->iPage]; + assert( pPage->isInit ); + if( !pPage->leaf ){ + int idx = pCur->aiIdx[pCur->iPage]; + rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); + if( rc ){ + *pRes = 0; + return rc; + } + rc = moveToRightmost(pCur); + }else{ + while( pCur->aiIdx[pCur->iPage]==0 ){ + if( pCur->iPage==0 ){ + pCur->eState = CURSOR_INVALID; + *pRes = 1; + return SQLITE_OK; + } + moveToParent(pCur); + } + pCur->info.nSize = 0; + pCur->validNKey = 0; + + pCur->aiIdx[pCur->iPage]--; + pPage = pCur->apPage[pCur->iPage]; + if( pPage->intKey && !pPage->leaf ){ + rc = sqlite3BtreePrevious(pCur, pRes); + }else{ + rc = SQLITE_OK; + } + } + *pRes = 0; + return rc; +} + +/* +** Allocate a new page from the database file. +** +** The new page is marked as dirty. (In other words, sqlite3PagerWrite() +** has already been called on the new page.) The new page has also +** been referenced and the calling routine is responsible for calling +** sqlite3PagerUnref() on the new page when it is done. +** +** SQLITE_OK is returned on success. Any other return value indicates +** an error. *ppPage and *pPgno are undefined in the event of an error. +** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned. +** +** If the "nearby" parameter is not 0, then an effort is made to +** locate a page close to the page number "nearby". This can be used in an +** attempt to keep related pages close to each other in the database file, +** which in turn can make database access faster. +** +** If the eMode parameter is BTALLOC_EXACT and the nearby page exists +** anywhere on the free-list, then it is guaranteed to be returned. If +** eMode is BTALLOC_LT then the page returned will be less than or equal +** to nearby if any such page exists. If eMode is BTALLOC_ANY then there +** are no restrictions on which page is returned. +*/ +static int allocateBtreePage( + BtShared *pBt, /* The btree */ + MemPage **ppPage, /* Store pointer to the allocated page here */ + Pgno *pPgno, /* Store the page number here */ + Pgno nearby, /* Search for a page near this one */ + u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ +){ + MemPage *pPage1; + int rc; + u32 n; /* Number of pages on the freelist */ + u32 k; /* Number of leaves on the trunk of the freelist */ + MemPage *pTrunk = 0; + MemPage *pPrevTrunk = 0; + Pgno mxPage; /* Total size of the database file */ + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); + pPage1 = pBt->pPage1; + mxPage = btreePagecount(pBt); + n = get4byte(&pPage1->aData[36]); + testcase( n==mxPage-1 ); + if( n>=mxPage ){ + return SQLITE_CORRUPT_BKPT; + } + if( n>0 ){ + /* There are pages on the freelist. Reuse one of those pages. */ + Pgno iTrunk; + u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ + + /* If eMode==BTALLOC_EXACT and a query of the pointer-map + ** shows that the page 'nearby' is somewhere on the free-list, then + ** the entire-list will be searched for that page. + */ +#ifndef SQLITE_OMIT_AUTOVACUUM + if( eMode==BTALLOC_EXACT ){ + if( nearby<=mxPage ){ + u8 eType; + assert( nearby>0 ); + assert( pBt->autoVacuum ); + rc = ptrmapGet(pBt, nearby, &eType, 0); + if( rc ) return rc; + if( eType==PTRMAP_FREEPAGE ){ + searchList = 1; + } + } + }else if( eMode==BTALLOC_LE ){ + searchList = 1; + } +#endif + + /* Decrement the free-list count by 1. Set iTrunk to the index of the + ** first free-list trunk page. iPrevTrunk is initially 1. + */ + rc = sqlite3PagerWrite(pPage1->pDbPage); + if( rc ) return rc; + put4byte(&pPage1->aData[36], n-1); + + /* The code within this loop is run only once if the 'searchList' variable + ** is not true. Otherwise, it runs once for each trunk-page on the + ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) + ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) + */ + do { + pPrevTrunk = pTrunk; + if( pPrevTrunk ){ + iTrunk = get4byte(&pPrevTrunk->aData[0]); + }else{ + iTrunk = get4byte(&pPage1->aData[32]); + } + testcase( iTrunk==mxPage ); + if( iTrunk>mxPage ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); + } + if( rc ){ + pTrunk = 0; + goto end_allocate_page; + } + assert( pTrunk!=0 ); + assert( pTrunk->aData!=0 ); + + k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */ + if( k==0 && !searchList ){ + /* The trunk has no leaves and the list is not being searched. + ** So extract the trunk page itself and use it as the newly + ** allocated page */ + assert( pPrevTrunk==0 ); + rc = sqlite3PagerWrite(pTrunk->pDbPage); + if( rc ){ + goto end_allocate_page; + } + *pPgno = iTrunk; + memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); + *ppPage = pTrunk; + pTrunk = 0; + TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); + }else if( k>(u32)(pBt->usableSize/4 - 2) ){ + /* Value of k is out of range. Database corruption */ + rc = SQLITE_CORRUPT_BKPT; + goto end_allocate_page; +#ifndef SQLITE_OMIT_AUTOVACUUM + }else if( searchList + && (nearby==iTrunk || (iTrunkpDbPage); + if( rc ){ + goto end_allocate_page; + } + if( k==0 ){ + if( !pPrevTrunk ){ + memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); + }else{ + rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); + if( rc!=SQLITE_OK ){ + goto end_allocate_page; + } + memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); + } + }else{ + /* The trunk page is required by the caller but it contains + ** pointers to free-list leaves. The first leaf becomes a trunk + ** page in this case. + */ + MemPage *pNewTrunk; + Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); + if( iNewTrunk>mxPage ){ + rc = SQLITE_CORRUPT_BKPT; + goto end_allocate_page; + } + testcase( iNewTrunk==mxPage ); + rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0); + if( rc!=SQLITE_OK ){ + goto end_allocate_page; + } + rc = sqlite3PagerWrite(pNewTrunk->pDbPage); + if( rc!=SQLITE_OK ){ + releasePage(pNewTrunk); + goto end_allocate_page; + } + memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); + put4byte(&pNewTrunk->aData[4], k-1); + memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); + releasePage(pNewTrunk); + if( !pPrevTrunk ){ + assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); + put4byte(&pPage1->aData[32], iNewTrunk); + }else{ + rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); + if( rc ){ + goto end_allocate_page; + } + put4byte(&pPrevTrunk->aData[0], iNewTrunk); + } + } + pTrunk = 0; + TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); +#endif + }else if( k>0 ){ + /* Extract a leaf from the trunk */ + u32 closest; + Pgno iPage; + unsigned char *aData = pTrunk->aData; + if( nearby>0 ){ + u32 i; + closest = 0; + if( eMode==BTALLOC_LE ){ + for(i=0; imxPage ){ + rc = SQLITE_CORRUPT_BKPT; + goto end_allocate_page; + } + testcase( iPage==mxPage ); + if( !searchList + || (iPage==nearby || (iPagepgno, n-1)); + rc = sqlite3PagerWrite(pTrunk->pDbPage); + if( rc ) goto end_allocate_page; + if( closestpDbPage); + if( rc!=SQLITE_OK ){ + releasePage(*ppPage); + } + } + searchList = 0; + } + } + releasePage(pPrevTrunk); + pPrevTrunk = 0; + }while( searchList ); + }else{ + /* There are no pages on the freelist, so append a new page to the + ** database image. + ** + ** Normally, new pages allocated by this block can be requested from the + ** pager layer with the 'no-content' flag set. This prevents the pager + ** from trying to read the pages content from disk. However, if the + ** current transaction has already run one or more incremental-vacuum + ** steps, then the page we are about to allocate may contain content + ** that is required in the event of a rollback. In this case, do + ** not set the no-content flag. This causes the pager to load and journal + ** the current page content before overwriting it. + ** + ** Note that the pager will not actually attempt to load or journal + ** content for any page that really does lie past the end of the database + ** file on disk. So the effects of disabling the no-content optimization + ** here are confined to those pages that lie between the end of the + ** database image and the end of the database file. + */ + int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0; + + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + if( rc ) return rc; + pBt->nPage++; + if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; + +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ + /* If *pPgno refers to a pointer-map page, allocate two new pages + ** at the end of the file instead of one. The first allocated page + ** becomes a new pointer-map page, the second is used by the caller. + */ + MemPage *pPg = 0; + TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); + assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); + rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent); + if( rc==SQLITE_OK ){ + rc = sqlite3PagerWrite(pPg->pDbPage); + releasePage(pPg); + } + if( rc ) return rc; + pBt->nPage++; + if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } + } +#endif + put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); + *pPgno = pBt->nPage; + + assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); + rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent); + if( rc ) return rc; + rc = sqlite3PagerWrite((*ppPage)->pDbPage); + if( rc!=SQLITE_OK ){ + releasePage(*ppPage); + } + TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); + } + + assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); + +end_allocate_page: + releasePage(pTrunk); + releasePage(pPrevTrunk); + if( rc==SQLITE_OK ){ + if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ + releasePage(*ppPage); + return SQLITE_CORRUPT_BKPT; + } + (*ppPage)->isInit = 0; + }else{ + *ppPage = 0; + } + assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) ); + return rc; +} + +/* +** This function is used to add page iPage to the database file free-list. +** It is assumed that the page is not already a part of the free-list. +** +** The value passed as the second argument to this function is optional. +** If the caller happens to have a pointer to the MemPage object +** corresponding to page iPage handy, it may pass it as the second value. +** Otherwise, it may pass NULL. +** +** If a pointer to a MemPage object is passed as the second argument, +** its reference count is not altered by this function. +*/ +static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ + MemPage *pTrunk = 0; /* Free-list trunk page */ + Pgno iTrunk = 0; /* Page number of free-list trunk page */ + MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ + MemPage *pPage; /* Page being freed. May be NULL. */ + int rc; /* Return Code */ + int nFree; /* Initial number of pages on free-list */ + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( iPage>1 ); + assert( !pMemPage || pMemPage->pgno==iPage ); + + if( pMemPage ){ + pPage = pMemPage; + sqlite3PagerRef(pPage->pDbPage); + }else{ + pPage = btreePageLookup(pBt, iPage); + } + + /* Increment the free page count on pPage1 */ + rc = sqlite3PagerWrite(pPage1->pDbPage); + if( rc ) goto freepage_out; + nFree = get4byte(&pPage1->aData[36]); + put4byte(&pPage1->aData[36], nFree+1); + + if( pBt->btsFlags & BTS_SECURE_DELETE ){ + /* If the secure_delete option is enabled, then + ** always fully overwrite deleted information with zeros. + */ + if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) + || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) + ){ + goto freepage_out; + } + memset(pPage->aData, 0, pPage->pBt->pageSize); + } + + /* If the database supports auto-vacuum, write an entry in the pointer-map + ** to indicate that the page is free. + */ + if( ISAUTOVACUUM ){ + ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); + if( rc ) goto freepage_out; + } + + /* Now manipulate the actual database free-list structure. There are two + ** possibilities. If the free-list is currently empty, or if the first + ** trunk page in the free-list is full, then this page will become a + ** new free-list trunk page. Otherwise, it will become a leaf of the + ** first trunk page in the current free-list. This block tests if it + ** is possible to add the page as a new free-list leaf. + */ + if( nFree!=0 ){ + u32 nLeaf; /* Initial number of leaf cells on trunk page */ + + iTrunk = get4byte(&pPage1->aData[32]); + rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); + if( rc!=SQLITE_OK ){ + goto freepage_out; + } + + nLeaf = get4byte(&pTrunk->aData[4]); + assert( pBt->usableSize>32 ); + if( nLeaf > (u32)pBt->usableSize/4 - 2 ){ + rc = SQLITE_CORRUPT_BKPT; + goto freepage_out; + } + if( nLeaf < (u32)pBt->usableSize/4 - 8 ){ + /* In this case there is room on the trunk page to insert the page + ** being freed as a new leaf. + ** + ** Note that the trunk page is not really full until it contains + ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have + ** coded. But due to a coding error in versions of SQLite prior to + ** 3.6.0, databases with freelist trunk pages holding more than + ** usableSize/4 - 8 entries will be reported as corrupt. In order + ** to maintain backwards compatibility with older versions of SQLite, + ** we will continue to restrict the number of entries to usableSize/4 - 8 + ** for now. At some point in the future (once everyone has upgraded + ** to 3.6.0 or later) we should consider fixing the conditional above + ** to read "usableSize/4-2" instead of "usableSize/4-8". + */ + rc = sqlite3PagerWrite(pTrunk->pDbPage); + if( rc==SQLITE_OK ){ + put4byte(&pTrunk->aData[4], nLeaf+1); + put4byte(&pTrunk->aData[8+nLeaf*4], iPage); + if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ + sqlite3PagerDontWrite(pPage->pDbPage); + } + rc = btreeSetHasContent(pBt, iPage); + } + TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); + goto freepage_out; + } + } + + /* If control flows to this point, then it was not possible to add the + ** the page being freed as a leaf page of the first trunk in the free-list. + ** Possibly because the free-list is empty, or possibly because the + ** first trunk in the free-list is full. Either way, the page being freed + ** will become the new first trunk page in the free-list. + */ + if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ + goto freepage_out; + } + rc = sqlite3PagerWrite(pPage->pDbPage); + if( rc!=SQLITE_OK ){ + goto freepage_out; + } + put4byte(pPage->aData, iTrunk); + put4byte(&pPage->aData[4], 0); + put4byte(&pPage1->aData[32], iPage); + TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk)); + +freepage_out: + if( pPage ){ + pPage->isInit = 0; + } + releasePage(pPage); + releasePage(pTrunk); + return rc; +} +static void freePage(MemPage *pPage, int *pRC){ + if( (*pRC)==SQLITE_OK ){ + *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); + } +} + +/* +** Free any overflow pages associated with the given Cell. +*/ +static int clearCell(MemPage *pPage, unsigned char *pCell){ + BtShared *pBt = pPage->pBt; + CellInfo info; + Pgno ovflPgno; + int rc; + int nOvfl; + u32 ovflPageSize; + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + btreeParseCellPtr(pPage, pCell, &info); + if( info.iOverflow==0 ){ + return SQLITE_OK; /* No overflow pages. Return without doing anything */ + } + if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){ + return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */ + } + ovflPgno = get4byte(&pCell[info.iOverflow]); + assert( pBt->usableSize > 4 ); + ovflPageSize = pBt->usableSize - 4; + nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize; + assert( ovflPgno==0 || nOvfl>0 ); + while( nOvfl-- ){ + Pgno iNext = 0; + MemPage *pOvfl = 0; + if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){ + /* 0 is not a legal page number and page 1 cannot be an + ** overflow page. Therefore if ovflPgno<2 or past the end of the + ** file the database must be corrupt. */ + return SQLITE_CORRUPT_BKPT; + } + if( nOvfl ){ + rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); + if( rc ) return rc; + } + + if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) + && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 + ){ + /* There is no reason any cursor should have an outstanding reference + ** to an overflow page belonging to a cell that is being deleted/updated. + ** So if there exists more than one reference to this page, then it + ** must not really be an overflow page and the database must be corrupt. + ** It is helpful to detect this before calling freePage2(), as + ** freePage2() may zero the page contents if secure-delete mode is + ** enabled. If this 'overflow' page happens to be a page that the + ** caller is iterating through or using in some other way, this + ** can be problematic. + */ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = freePage2(pBt, pOvfl, ovflPgno); + } + + if( pOvfl ){ + sqlite3PagerUnref(pOvfl->pDbPage); + } + if( rc ) return rc; + ovflPgno = iNext; + } + return SQLITE_OK; +} + +/* +** Create the byte sequence used to represent a cell on page pPage +** and write that byte sequence into pCell[]. Overflow pages are +** allocated and filled in as necessary. The calling procedure +** is responsible for making sure sufficient space has been allocated +** for pCell[]. +** +** Note that pCell does not necessary need to point to the pPage->aData +** area. pCell might point to some temporary storage. The cell will +** be constructed in this temporary area then copied into pPage->aData +** later. +*/ +static int fillInCell( + MemPage *pPage, /* The page that contains the cell */ + unsigned char *pCell, /* Complete text of the cell */ + const void *pKey, i64 nKey, /* The key */ + const void *pData,int nData, /* The data */ + int nZero, /* Extra zero bytes to append to pData */ + int *pnSize /* Write cell size here */ +){ + int nPayload; + const u8 *pSrc; + int nSrc, n, rc; + int spaceLeft; + MemPage *pOvfl = 0; + MemPage *pToRelease = 0; + unsigned char *pPrior; + unsigned char *pPayload; + BtShared *pBt = pPage->pBt; + Pgno pgnoOvfl = 0; + int nHeader; + CellInfo info; + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + + /* pPage is not necessarily writeable since pCell might be auxiliary + ** buffer space that is separate from the pPage buffer area */ + assert( pCellaData || pCell>=&pPage->aData[pBt->pageSize] + || sqlite3PagerIswriteable(pPage->pDbPage) ); + + /* Fill in the header. */ + nHeader = 0; + if( !pPage->leaf ){ + nHeader += 4; + } + if( pPage->hasData ){ + nHeader += putVarint(&pCell[nHeader], nData+nZero); + }else{ + nData = nZero = 0; + } + nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey); + btreeParseCellPtr(pPage, pCell, &info); + assert( info.nHeader==nHeader ); + assert( info.nKey==nKey ); + assert( info.nData==(u32)(nData+nZero) ); + + /* Fill in the payload */ + nPayload = nData + nZero; + if( pPage->intKey ){ + pSrc = pData; + nSrc = nData; + nData = 0; + }else{ + if( NEVER(nKey>0x7fffffff || pKey==0) ){ + return SQLITE_CORRUPT_BKPT; + } + nPayload += (int)nKey; + pSrc = pKey; + nSrc = (int)nKey; + } + *pnSize = info.nSize; + spaceLeft = info.nLocal; + pPayload = &pCell[nHeader]; + pPrior = &pCell[info.iOverflow]; + + while( nPayload>0 ){ + if( spaceLeft==0 ){ +#ifndef SQLITE_OMIT_AUTOVACUUM + Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ + if( pBt->autoVacuum ){ + do{ + pgnoOvfl++; + } while( + PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) + ); + } +#endif + rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); +#ifndef SQLITE_OMIT_AUTOVACUUM + /* If the database supports auto-vacuum, and the second or subsequent + ** overflow page is being allocated, add an entry to the pointer-map + ** for that page now. + ** + ** If this is the first overflow page, then write a partial entry + ** to the pointer-map. If we write nothing to this pointer-map slot, + ** then the optimistic overflow chain processing in clearCell() + ** may misinterpret the uninitialized values and delete the + ** wrong pages from the database. + */ + if( pBt->autoVacuum && rc==SQLITE_OK ){ + u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); + ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); + if( rc ){ + releasePage(pOvfl); + } + } +#endif + if( rc ){ + releasePage(pToRelease); + return rc; + } + + /* If pToRelease is not zero than pPrior points into the data area + ** of pToRelease. Make sure pToRelease is still writeable. */ + assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); + + /* If pPrior is part of the data area of pPage, then make sure pPage + ** is still writeable */ + assert( pPrioraData || pPrior>=&pPage->aData[pBt->pageSize] + || sqlite3PagerIswriteable(pPage->pDbPage) ); + + put4byte(pPrior, pgnoOvfl); + releasePage(pToRelease); + pToRelease = pOvfl; + pPrior = pOvfl->aData; + put4byte(pPrior, 0); + pPayload = &pOvfl->aData[4]; + spaceLeft = pBt->usableSize - 4; + } + n = nPayload; + if( n>spaceLeft ) n = spaceLeft; + + /* If pToRelease is not zero than pPayload points into the data area + ** of pToRelease. Make sure pToRelease is still writeable. */ + assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); + + /* If pPayload is part of the data area of pPage, then make sure pPage + ** is still writeable */ + assert( pPayloadaData || pPayload>=&pPage->aData[pBt->pageSize] + || sqlite3PagerIswriteable(pPage->pDbPage) ); + + if( nSrc>0 ){ + if( n>nSrc ) n = nSrc; + assert( pSrc ); + memcpy(pPayload, pSrc, n); + }else{ + memset(pPayload, 0, n); + } + nPayload -= n; + pPayload += n; + pSrc += n; + nSrc -= n; + spaceLeft -= n; + if( nSrc==0 ){ + nSrc = nData; + pSrc = pData; + } + } + releasePage(pToRelease); + return SQLITE_OK; +} + +/* +** Remove the i-th cell from pPage. This routine effects pPage only. +** The cell content is not freed or deallocated. It is assumed that +** the cell content has been copied someplace else. This routine just +** removes the reference to the cell from pPage. +** +** "sz" must be the number of bytes in the cell. +*/ +static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ + u32 pc; /* Offset to cell content of cell being deleted */ + u8 *data; /* pPage->aData */ + u8 *ptr; /* Used to move bytes around within data[] */ + u8 *endPtr; /* End of loop */ + int rc; /* The return code */ + int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ + + if( *pRC ) return; + + assert( idx>=0 && idxnCell ); + assert( sz==cellSize(pPage, idx) ); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + data = pPage->aData; + ptr = &pPage->aCellIdx[2*idx]; + pc = get2byte(ptr); + hdr = pPage->hdrOffset; + testcase( pc==get2byte(&data[hdr+5]) ); + testcase( pc+sz==pPage->pBt->usableSize ); + if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){ + *pRC = SQLITE_CORRUPT_BKPT; + return; + } + rc = freeSpace(pPage, pc, sz); + if( rc ){ + *pRC = rc; + return; + } + endPtr = &pPage->aCellIdx[2*pPage->nCell - 2]; + assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */ + while( ptrnCell--; + put2byte(&data[hdr+3], pPage->nCell); + pPage->nFree += 2; +} + +/* +** Insert a new cell on pPage at cell index "i". pCell points to the +** content of the cell. +** +** If the cell content will fit on the page, then put it there. If it +** will not fit, then make a copy of the cell content into pTemp if +** pTemp is not null. Regardless of pTemp, allocate a new entry +** in pPage->apOvfl[] and make it point to the cell content (either +** in pTemp or the original pCell) and also record its index. +** Allocating a new entry in pPage->aCell[] implies that +** pPage->nOverflow is incremented. +** +** If nSkip is non-zero, then do not copy the first nSkip bytes of the +** cell. The caller will overwrite them after this function returns. If +** nSkip is non-zero, then pCell may not point to an invalid memory location +** (but pCell+nSkip is always valid). +*/ +static void insertCell( + MemPage *pPage, /* Page into which we are copying */ + int i, /* New cell becomes the i-th cell of the page */ + u8 *pCell, /* Content of the new cell */ + int sz, /* Bytes of content in pCell */ + u8 *pTemp, /* Temp storage space for pCell, if needed */ + Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ + int *pRC /* Read and write return code from here */ +){ + int idx = 0; /* Where to write new cell content in data[] */ + int j; /* Loop counter */ + int end; /* First byte past the last cell pointer in data[] */ + int ins; /* Index in data[] where new cell pointer is inserted */ + int cellOffset; /* Address of first cell pointer in data[] */ + u8 *data; /* The content of the whole page */ + u8 *ptr; /* Used for moving information around in data[] */ + u8 *endPtr; /* End of the loop */ + + int nSkip = (iChild ? 4 : 0); + + if( *pRC ) return; + + assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); + assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 ); + assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); + assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + /* The cell should normally be sized correctly. However, when moving a + ** malformed cell from a leaf page to an interior page, if the cell size + ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size + ** might be less than 8 (leaf-size + pointer) on the interior node. Hence + ** the term after the || in the following assert(). */ + assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) ); + if( pPage->nOverflow || sz+2>pPage->nFree ){ + if( pTemp ){ + memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip); + pCell = pTemp; + } + if( iChild ){ + put4byte(pCell, iChild); + } + j = pPage->nOverflow++; + assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) ); + pPage->apOvfl[j] = pCell; + pPage->aiOvfl[j] = (u16)i; + }else{ + int rc = sqlite3PagerWrite(pPage->pDbPage); + if( rc!=SQLITE_OK ){ + *pRC = rc; + return; + } + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + data = pPage->aData; + cellOffset = pPage->cellOffset; + end = cellOffset + 2*pPage->nCell; + ins = cellOffset + 2*i; + rc = allocateSpace(pPage, sz, &idx); + if( rc ){ *pRC = rc; return; } + /* The allocateSpace() routine guarantees the following two properties + ** if it returns success */ + assert( idx >= end+2 ); + assert( idx+sz <= (int)pPage->pBt->usableSize ); + pPage->nCell++; + pPage->nFree -= (u16)(2 + sz); + memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip); + if( iChild ){ + put4byte(&data[idx], iChild); + } + ptr = &data[end]; + endPtr = &data[ins]; + assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */ + while( ptr>endPtr ){ + *(u16*)ptr = *(u16*)&ptr[-2]; + ptr -= 2; + } + put2byte(&data[ins], idx); + put2byte(&data[pPage->hdrOffset+3], pPage->nCell); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pPage->pBt->autoVacuum ){ + /* The cell may contain a pointer to an overflow page. If so, write + ** the entry for the overflow page into the pointer map. + */ + ptrmapPutOvflPtr(pPage, pCell, pRC); + } +#endif + } +} + +/* +** Add a list of cells to a page. The page should be initially empty. +** The cells are guaranteed to fit on the page. +*/ +static void assemblePage( + MemPage *pPage, /* The page to be assemblied */ + int nCell, /* The number of cells to add to this page */ + u8 **apCell, /* Pointers to cell bodies */ + u16 *aSize /* Sizes of the cells */ +){ + int i; /* Loop counter */ + u8 *pCellptr; /* Address of next cell pointer */ + int cellbody; /* Address of next cell body */ + u8 * const data = pPage->aData; /* Pointer to data for pPage */ + const int hdr = pPage->hdrOffset; /* Offset of header on pPage */ + const int nUsable = pPage->pBt->usableSize; /* Usable size of page */ + + assert( pPage->nOverflow==0 ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt) + && (int)MX_CELL(pPage->pBt)<=10921); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + + /* Check that the page has just been zeroed by zeroPage() */ + assert( pPage->nCell==0 ); + assert( get2byteNotZero(&data[hdr+5])==nUsable ); + + pCellptr = &pPage->aCellIdx[nCell*2]; + cellbody = nUsable; + for(i=nCell-1; i>=0; i--){ + u16 sz = aSize[i]; + pCellptr -= 2; + cellbody -= sz; + put2byte(pCellptr, cellbody); + memcpy(&data[cellbody], apCell[i], sz); + } + put2byte(&data[hdr+3], nCell); + put2byte(&data[hdr+5], cellbody); + pPage->nFree -= (nCell*2 + nUsable - cellbody); + pPage->nCell = (u16)nCell; +} + +/* +** The following parameters determine how many adjacent pages get involved +** in a balancing operation. NN is the number of neighbors on either side +** of the page that participate in the balancing operation. NB is the +** total number of pages that participate, including the target page and +** NN neighbors on either side. +** +** The minimum value of NN is 1 (of course). Increasing NN above 1 +** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance +** in exchange for a larger degradation in INSERT and UPDATE performance. +** The value of NN appears to give the best results overall. +*/ +#define NN 1 /* Number of neighbors on either side of pPage */ +#define NB (NN*2+1) /* Total pages involved in the balance */ + + +#ifndef SQLITE_OMIT_QUICKBALANCE +/* +** This version of balance() handles the common special case where +** a new entry is being inserted on the extreme right-end of the +** tree, in other words, when the new entry will become the largest +** entry in the tree. +** +** Instead of trying to balance the 3 right-most leaf pages, just add +** a new page to the right-hand side and put the one new entry in +** that page. This leaves the right side of the tree somewhat +** unbalanced. But odds are that we will be inserting new entries +** at the end soon afterwards so the nearly empty page will quickly +** fill up. On average. +** +** pPage is the leaf page which is the right-most page in the tree. +** pParent is its parent. pPage must have a single overflow entry +** which is also the right-most entry on the page. +** +** The pSpace buffer is used to store a temporary copy of the divider +** cell that will be inserted into pParent. Such a cell consists of a 4 +** byte page number followed by a variable length integer. In other +** words, at most 13 bytes. Hence the pSpace buffer must be at +** least 13 bytes in size. +*/ +static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ + BtShared *const pBt = pPage->pBt; /* B-Tree Database */ + MemPage *pNew; /* Newly allocated page */ + int rc; /* Return Code */ + Pgno pgnoNew; /* Page number of pNew */ + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + assert( pPage->nOverflow==1 ); + + /* This error condition is now caught prior to reaching this function */ + if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; + + /* Allocate a new page. This page will become the right-sibling of + ** pPage. Make the parent page writable, so that the new divider cell + ** may be inserted. If both these operations are successful, proceed. + */ + rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); + + if( rc==SQLITE_OK ){ + + u8 *pOut = &pSpace[4]; + u8 *pCell = pPage->apOvfl[0]; + u16 szCell = cellSizePtr(pPage, pCell); + u8 *pStop; + + assert( sqlite3PagerIswriteable(pNew->pDbPage) ); + assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); + zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); + assemblePage(pNew, 1, &pCell, &szCell); + + /* If this is an auto-vacuum database, update the pointer map + ** with entries for the new page, and any pointer from the + ** cell on the page to an overflow page. If either of these + ** operations fails, the return code is set, but the contents + ** of the parent page are still manipulated by thh code below. + ** That is Ok, at this point the parent page is guaranteed to + ** be marked as dirty. Returning an error code will cause a + ** rollback, undoing any changes made to the parent page. + */ + if( ISAUTOVACUUM ){ + ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc); + if( szCell>pNew->minLocal ){ + ptrmapPutOvflPtr(pNew, pCell, &rc); + } + } + + /* Create a divider cell to insert into pParent. The divider cell + ** consists of a 4-byte page number (the page number of pPage) and + ** a variable length key value (which must be the same value as the + ** largest key on pPage). + ** + ** To find the largest key value on pPage, first find the right-most + ** cell on pPage. The first two fields of this cell are the + ** record-length (a variable length integer at most 32-bits in size) + ** and the key value (a variable length integer, may have any value). + ** The first of the while(...) loops below skips over the record-length + ** field. The second while(...) loop copies the key value from the + ** cell on pPage into the pSpace buffer. + */ + pCell = findCell(pPage, pPage->nCell-1); + pStop = &pCell[9]; + while( (*(pCell++)&0x80) && pCellnCell, pSpace, (int)(pOut-pSpace), + 0, pPage->pgno, &rc); + + /* Set the right-child pointer of pParent to point to the new page. */ + put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); + + /* Release the reference to the new page. */ + releasePage(pNew); + } + + return rc; +} +#endif /* SQLITE_OMIT_QUICKBALANCE */ + +#if 0 +/* +** This function does not contribute anything to the operation of SQLite. +** it is sometimes activated temporarily while debugging code responsible +** for setting pointer-map entries. +*/ +static int ptrmapCheckPages(MemPage **apPage, int nPage){ + int i, j; + for(i=0; ipBt; + assert( pPage->isInit ); + + for(j=0; jnCell; j++){ + CellInfo info; + u8 *z; + + z = findCell(pPage, j); + btreeParseCellPtr(pPage, z, &info); + if( info.iOverflow ){ + Pgno ovfl = get4byte(&z[info.iOverflow]); + ptrmapGet(pBt, ovfl, &e, &n); + assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 ); + } + if( !pPage->leaf ){ + Pgno child = get4byte(z); + ptrmapGet(pBt, child, &e, &n); + assert( n==pPage->pgno && e==PTRMAP_BTREE ); + } + } + if( !pPage->leaf ){ + Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]); + ptrmapGet(pBt, child, &e, &n); + assert( n==pPage->pgno && e==PTRMAP_BTREE ); + } + } + return 1; +} +#endif + +/* +** This function is used to copy the contents of the b-tree node stored +** on page pFrom to page pTo. If page pFrom was not a leaf page, then +** the pointer-map entries for each child page are updated so that the +** parent page stored in the pointer map is page pTo. If pFrom contained +** any cells with overflow page pointers, then the corresponding pointer +** map entries are also updated so that the parent page is page pTo. +** +** If pFrom is currently carrying any overflow cells (entries in the +** MemPage.apOvfl[] array), they are not copied to pTo. +** +** Before returning, page pTo is reinitialized using btreeInitPage(). +** +** The performance of this function is not critical. It is only used by +** the balance_shallower() and balance_deeper() procedures, neither of +** which are called often under normal circumstances. +*/ +static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ + if( (*pRC)==SQLITE_OK ){ + BtShared * const pBt = pFrom->pBt; + u8 * const aFrom = pFrom->aData; + u8 * const aTo = pTo->aData; + int const iFromHdr = pFrom->hdrOffset; + int const iToHdr = ((pTo->pgno==1) ? 100 : 0); + int rc; + int iData; + + + assert( pFrom->isInit ); + assert( pFrom->nFree>=iToHdr ); + assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize ); + + /* Copy the b-tree node content from page pFrom to page pTo. */ + iData = get2byte(&aFrom[iFromHdr+5]); + memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); + memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); + + /* Reinitialize page pTo so that the contents of the MemPage structure + ** match the new data. The initialization of pTo can actually fail under + ** fairly obscure circumstances, even though it is a copy of initialized + ** page pFrom. + */ + pTo->isInit = 0; + rc = btreeInitPage(pTo); + if( rc!=SQLITE_OK ){ + *pRC = rc; + return; + } + + /* If this is an auto-vacuum database, update the pointer-map entries + ** for any b-tree or overflow pages that pTo now contains the pointers to. + */ + if( ISAUTOVACUUM ){ + *pRC = setChildPtrmaps(pTo); + } + } +} + +/* +** This routine redistributes cells on the iParentIdx'th child of pParent +** (hereafter "the page") and up to 2 siblings so that all pages have about the +** same amount of free space. Usually a single sibling on either side of the +** page are used in the balancing, though both siblings might come from one +** side if the page is the first or last child of its parent. If the page +** has fewer than 2 siblings (something which can only happen if the page +** is a root page or a child of a root page) then all available siblings +** participate in the balancing. +** +** The number of siblings of the page might be increased or decreased by +** one or two in an effort to keep pages nearly full but not over full. +** +** Note that when this routine is called, some of the cells on the page +** might not actually be stored in MemPage.aData[]. This can happen +** if the page is overfull. This routine ensures that all cells allocated +** to the page and its siblings fit into MemPage.aData[] before returning. +** +** In the course of balancing the page and its siblings, cells may be +** inserted into or removed from the parent page (pParent). Doing so +** may cause the parent page to become overfull or underfull. If this +** happens, it is the responsibility of the caller to invoke the correct +** balancing routine to fix this problem (see the balance() routine). +** +** If this routine fails for any reason, it might leave the database +** in a corrupted state. So if this routine fails, the database should +** be rolled back. +** +** The third argument to this function, aOvflSpace, is a pointer to a +** buffer big enough to hold one page. If while inserting cells into the parent +** page (pParent) the parent page becomes overfull, this buffer is +** used to store the parent's overflow cells. Because this function inserts +** a maximum of four divider cells into the parent page, and the maximum +** size of a cell stored within an internal node is always less than 1/4 +** of the page-size, the aOvflSpace[] buffer is guaranteed to be large +** enough for all overflow cells. +** +** If aOvflSpace is set to a null pointer, this function returns +** SQLITE_NOMEM. +*/ +#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM) +#pragma optimize("", off) +#endif +static int balance_nonroot( + MemPage *pParent, /* Parent page of siblings being balanced */ + int iParentIdx, /* Index of "the page" in pParent */ + u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ + int isRoot, /* True if pParent is a root-page */ + int bBulk /* True if this call is part of a bulk load */ +){ + BtShared *pBt; /* The whole database */ + int nCell = 0; /* Number of cells in apCell[] */ + int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ + int nNew = 0; /* Number of pages in apNew[] */ + int nOld; /* Number of pages in apOld[] */ + int i, j, k; /* Loop counters */ + int nxDiv; /* Next divider slot in pParent->aCell[] */ + int rc = SQLITE_OK; /* The return code */ + u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ + int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ + int usableSpace; /* Bytes in pPage beyond the header */ + int pageFlags; /* Value of pPage->aData[0] */ + int subtotal; /* Subtotal of bytes in cells on one page */ + int iSpace1 = 0; /* First unused byte of aSpace1[] */ + int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ + int szScratch; /* Size of scratch memory requested */ + MemPage *apOld[NB]; /* pPage and up to two siblings */ + MemPage *apCopy[NB]; /* Private copies of apOld[] pages */ + MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ + u8 *pRight; /* Location in parent of right-sibling pointer */ + u8 *apDiv[NB-1]; /* Divider cells in pParent */ + int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */ + int szNew[NB+2]; /* Combined size of cells place on i-th page */ + u8 **apCell = 0; /* All cells begin balanced */ + u16 *szCell; /* Local size of all cells in apCell[] */ + u8 *aSpace1; /* Space for copies of dividers cells */ + Pgno pgno; /* Temp var to store a page number in */ + + pBt = pParent->pBt; + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + +#if 0 + TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); +#endif + + /* At this point pParent may have at most one overflow cell. And if + ** this overflow cell is present, it must be the cell with + ** index iParentIdx. This scenario comes about when this function + ** is called (indirectly) from sqlite3BtreeDelete(). + */ + assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); + assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); + + if( !aOvflSpace ){ + return SQLITE_NOMEM; + } + + /* Find the sibling pages to balance. Also locate the cells in pParent + ** that divide the siblings. An attempt is made to find NN siblings on + ** either side of pPage. More siblings are taken from one side, however, + ** if there are fewer than NN siblings on the other side. If pParent + ** has NB or fewer children then all children of pParent are taken. + ** + ** This loop also drops the divider cells from the parent page. This + ** way, the remainder of the function does not have to deal with any + ** overflow cells in the parent page, since if any existed they will + ** have already been removed. + */ + i = pParent->nOverflow + pParent->nCell; + if( i<2 ){ + nxDiv = 0; + }else{ + assert( bBulk==0 || bBulk==1 ); + if( iParentIdx==0 ){ + nxDiv = 0; + }else if( iParentIdx==i ){ + nxDiv = i-2+bBulk; + }else{ + assert( bBulk==0 ); + nxDiv = iParentIdx-1; + } + i = 2-bBulk; + } + nOld = i+1; + if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ + pRight = &pParent->aData[pParent->hdrOffset+8]; + }else{ + pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); + } + pgno = get4byte(pRight); + while( 1 ){ + rc = getAndInitPage(pBt, pgno, &apOld[i], 0); + if( rc ){ + memset(apOld, 0, (i+1)*sizeof(MemPage*)); + goto balance_cleanup; + } + nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; + if( (i--)==0 ) break; + + if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){ + apDiv[i] = pParent->apOvfl[0]; + pgno = get4byte(apDiv[i]); + szNew[i] = cellSizePtr(pParent, apDiv[i]); + pParent->nOverflow = 0; + }else{ + apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); + pgno = get4byte(apDiv[i]); + szNew[i] = cellSizePtr(pParent, apDiv[i]); + + /* Drop the cell from the parent page. apDiv[i] still points to + ** the cell within the parent, even though it has been dropped. + ** This is safe because dropping a cell only overwrites the first + ** four bytes of it, and this function does not need the first + ** four bytes of the divider cell. So the pointer is safe to use + ** later on. + ** + ** But not if we are in secure-delete mode. In secure-delete mode, + ** the dropCell() routine will overwrite the entire cell with zeroes. + ** In this case, temporarily copy the cell into the aOvflSpace[] + ** buffer. It will be copied out again as soon as the aSpace[] buffer + ** is allocated. */ + if( pBt->btsFlags & BTS_SECURE_DELETE ){ + int iOff; + + iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); + if( (iOff+szNew[i])>(int)pBt->usableSize ){ + rc = SQLITE_CORRUPT_BKPT; + memset(apOld, 0, (i+1)*sizeof(MemPage*)); + goto balance_cleanup; + }else{ + memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); + apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; + } + } + dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); + } + } + + /* Make nMaxCells a multiple of 4 in order to preserve 8-byte + ** alignment */ + nMaxCells = (nMaxCells + 3)&~3; + + /* + ** Allocate space for memory structures + */ + k = pBt->pageSize + ROUND8(sizeof(MemPage)); + szScratch = + nMaxCells*sizeof(u8*) /* apCell */ + + nMaxCells*sizeof(u16) /* szCell */ + + pBt->pageSize /* aSpace1 */ + + k*nOld; /* Page copies (apCopy) */ + apCell = sqlite3ScratchMalloc( szScratch ); + if( apCell==0 ){ + rc = SQLITE_NOMEM; + goto balance_cleanup; + } + szCell = (u16*)&apCell[nMaxCells]; + aSpace1 = (u8*)&szCell[nMaxCells]; + assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); + + /* + ** Load pointers to all cells on sibling pages and the divider cells + ** into the local apCell[] array. Make copies of the divider cells + ** into space obtained from aSpace1[] and remove the divider cells + ** from pParent. + ** + ** If the siblings are on leaf pages, then the child pointers of the + ** divider cells are stripped from the cells before they are copied + ** into aSpace1[]. In this way, all cells in apCell[] are without + ** child pointers. If siblings are not leaves, then all cell in + ** apCell[] include child pointers. Either way, all cells in apCell[] + ** are alike. + ** + ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. + ** leafData: 1 if pPage holds key+data and pParent holds only keys. + */ + leafCorrection = apOld[0]->leaf*4; + leafData = apOld[0]->hasData; + for(i=0; ipageSize + k*i]; + memcpy(pOld, apOld[i], sizeof(MemPage)); + pOld->aData = (void*)&pOld[1]; + memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize); + + limit = pOld->nCell+pOld->nOverflow; + if( pOld->nOverflow>0 ){ + for(j=0; jaData; + u16 maskPage = pOld->maskPage; + u16 cellOffset = pOld->cellOffset; + for(j=0; jmaxLocal+23 ); + assert( iSpace1 <= (int)pBt->pageSize ); + memcpy(pTemp, apDiv[i], sz); + apCell[nCell] = pTemp+leafCorrection; + assert( leafCorrection==0 || leafCorrection==4 ); + szCell[nCell] = szCell[nCell] - leafCorrection; + if( !pOld->leaf ){ + assert( leafCorrection==0 ); + assert( pOld->hdrOffset==0 ); + /* The right pointer of the child page pOld becomes the left + ** pointer of the divider cell */ + memcpy(apCell[nCell], &pOld->aData[8], 4); + }else{ + assert( leafCorrection==4 ); + if( szCell[nCell]<4 ){ + /* Do not allow any cells smaller than 4 bytes. */ + szCell[nCell] = 4; + } + } + nCell++; + } + } + + /* + ** Figure out the number of pages needed to hold all nCell cells. + ** Store this number in "k". Also compute szNew[] which is the total + ** size of all cells on the i-th page and cntNew[] which is the index + ** in apCell[] of the cell that divides page i from page i+1. + ** cntNew[k] should equal nCell. + ** + ** Values computed by this block: + ** + ** k: The total number of sibling pages + ** szNew[i]: Spaced used on the i-th sibling page. + ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to + ** the right of the i-th sibling page. + ** usableSpace: Number of bytes of space available on each sibling. + ** + */ + usableSpace = pBt->usableSize - 12 + leafCorrection; + for(subtotal=k=i=0; i usableSpace ){ + szNew[k] = subtotal - szCell[i]; + cntNew[k] = i; + if( leafData ){ i--; } + subtotal = 0; + k++; + if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } + } + } + szNew[k] = subtotal; + cntNew[k] = nCell; + k++; + + /* + ** The packing computed by the previous block is biased toward the siblings + ** on the left side. The left siblings are always nearly full, while the + ** right-most sibling might be nearly empty. This block of code attempts + ** to adjust the packing of siblings to get a better balance. + ** + ** This adjustment is more than an optimization. The packing above might + ** be so out of balance as to be illegal. For example, the right-most + ** sibling might be completely empty. This adjustment is not optional. + */ + for(i=k-1; i>0; i--){ + int szRight = szNew[i]; /* Size of sibling on the right */ + int szLeft = szNew[i-1]; /* Size of sibling on the left */ + int r; /* Index of right-most cell in left sibling */ + int d; /* Index of first cell to the left of right sibling */ + + r = cntNew[i-1] - 1; + d = r + 1 - leafData; + assert( d0) or pPage is + ** a virtual root page. A virtual root page is when the real root + ** page is page 1 and we are the only child of that page. + ** + ** UPDATE: The assert() below is not necessarily true if the database + ** file is corrupt. The corruption will be detected and reported later + ** in this procedure so there is no need to act upon it now. + */ +#if 0 + assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) ); +#endif + + TRACE(("BALANCE: old: %d %d %d ", + apOld[0]->pgno, + nOld>=2 ? apOld[1]->pgno : 0, + nOld>=3 ? apOld[2]->pgno : 0 + )); + + /* + ** Allocate k new pages. Reuse old pages where possible. + */ + if( apOld[0]->pgno<=1 ){ + rc = SQLITE_CORRUPT_BKPT; + goto balance_cleanup; + } + pageFlags = apOld[0]->aData[0]; + for(i=0; ipDbPage); + nNew++; + if( rc ) goto balance_cleanup; + }else{ + assert( i>0 ); + rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); + if( rc ) goto balance_cleanup; + apNew[i] = pNew; + nNew++; + + /* Set the pointer-map entry for the new sibling page. */ + if( ISAUTOVACUUM ){ + ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); + if( rc!=SQLITE_OK ){ + goto balance_cleanup; + } + } + } + } + + /* Free any old pages that were not reused as new pages. + */ + while( ipgno; + int minI = i; + for(j=i+1; jpgno<(unsigned)minV ){ + minI = j; + minV = apNew[j]->pgno; + } + } + if( minI>i ){ + MemPage *pT; + pT = apNew[i]; + apNew[i] = apNew[minI]; + apNew[minI] = pT; + } + } + TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n", + apNew[0]->pgno, szNew[0], + nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0, + nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0, + nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0, + nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0)); + + assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + put4byte(pRight, apNew[nNew-1]->pgno); + + /* + ** Evenly distribute the data in apCell[] across the new pages. + ** Insert divider cells into pParent as necessary. + */ + j = 0; + for(i=0; inCell>0 || (nNew==1 && cntNew[0]==0) ); + assert( pNew->nOverflow==0 ); + + j = cntNew[i]; + + /* If the sibling page assembled above was not the right-most sibling, + ** insert a divider cell into the parent page. + */ + assert( ileaf ){ + memcpy(&pNew->aData[8], pCell, 4); + }else if( leafData ){ + /* If the tree is a leaf-data tree, and the siblings are leaves, + ** then there is no divider cell in apCell[]. Instead, the divider + ** cell consists of the integer key for the right-most cell of + ** the sibling-page assembled above only. + */ + CellInfo info; + j--; + btreeParseCellPtr(pNew, apCell[j], &info); + pCell = pTemp; + sz = 4 + putVarint(&pCell[4], info.nKey); + pTemp = 0; + }else{ + pCell -= 4; + /* Obscure case for non-leaf-data trees: If the cell at pCell was + ** previously stored on a leaf node, and its reported size was 4 + ** bytes, then it may actually be smaller than this + ** (see btreeParseCellPtr(), 4 bytes is the minimum size of + ** any cell). But it is important to pass the correct size to + ** insertCell(), so reparse the cell now. + ** + ** Note that this can never happen in an SQLite data file, as all + ** cells are at least 4 bytes. It only happens in b-trees used + ** to evaluate "IN (SELECT ...)" and similar clauses. + */ + if( szCell[j]==4 ){ + assert(leafCorrection==4); + sz = cellSizePtr(pParent, pCell); + } + } + iOvflSpace += sz; + assert( sz<=pBt->maxLocal+23 ); + assert( iOvflSpace <= (int)pBt->pageSize ); + insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc); + if( rc!=SQLITE_OK ) goto balance_cleanup; + assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + + j++; + nxDiv++; + } + } + assert( j==nCell ); + assert( nOld>0 ); + assert( nNew>0 ); + if( (pageFlags & PTF_LEAF)==0 ){ + u8 *zChild = &apCopy[nOld-1]->aData[8]; + memcpy(&apNew[nNew-1]->aData[8], zChild, 4); + } + + if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){ + /* The root page of the b-tree now contains no cells. The only sibling + ** page is the right-child of the parent. Copy the contents of the + ** child page into the parent, decreasing the overall height of the + ** b-tree structure by one. This is described as the "balance-shallower" + ** sub-algorithm in some documentation. + ** + ** If this is an auto-vacuum database, the call to copyNodeContent() + ** sets all pointer-map entries corresponding to database image pages + ** for which the pointer is stored within the content being copied. + ** + ** The second assert below verifies that the child page is defragmented + ** (it must be, as it was just reconstructed using assemblePage()). This + ** is important if the parent page happens to be page 1 of the database + ** image. */ + assert( nNew==1 ); + assert( apNew[0]->nFree == + (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) + ); + copyNodeContent(apNew[0], pParent, &rc); + freePage(apNew[0], &rc); + }else if( ISAUTOVACUUM ){ + /* Fix the pointer-map entries for all the cells that were shifted around. + ** There are several different types of pointer-map entries that need to + ** be dealt with by this routine. Some of these have been set already, but + ** many have not. The following is a summary: + ** + ** 1) The entries associated with new sibling pages that were not + ** siblings when this function was called. These have already + ** been set. We don't need to worry about old siblings that were + ** moved to the free-list - the freePage() code has taken care + ** of those. + ** + ** 2) The pointer-map entries associated with the first overflow + ** page in any overflow chains used by new divider cells. These + ** have also already been taken care of by the insertCell() code. + ** + ** 3) If the sibling pages are not leaves, then the child pages of + ** cells stored on the sibling pages may need to be updated. + ** + ** 4) If the sibling pages are not internal intkey nodes, then any + ** overflow pages used by these cells may need to be updated + ** (internal intkey nodes never contain pointers to overflow pages). + ** + ** 5) If the sibling pages are not leaves, then the pointer-map + ** entries for the right-child pages of each sibling may need + ** to be updated. + ** + ** Cases 1 and 2 are dealt with above by other code. The next + ** block deals with cases 3 and 4 and the one after that, case 5. Since + ** setting a pointer map entry is a relatively expensive operation, this + ** code only sets pointer map entries for child or overflow pages that have + ** actually moved between pages. */ + MemPage *pNew = apNew[0]; + MemPage *pOld = apCopy[0]; + int nOverflow = pOld->nOverflow; + int iNextOld = pOld->nCell + nOverflow; + int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1); + j = 0; /* Current 'old' sibling page */ + k = 0; /* Current 'new' sibling page */ + for(i=0; inCell + pOld->nOverflow; + if( pOld->nOverflow ){ + nOverflow = pOld->nOverflow; + iOverflow = i + !leafData + pOld->aiOvfl[0]; + } + isDivider = !leafData; + } + + assert(nOverflow>0 || iOverflowaiOvfl[0]==pOld->aiOvfl[1]-1); + assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1); + if( i==iOverflow ){ + isDivider = 1; + if( (--nOverflow)>0 ){ + iOverflow++; + } + } + + if( i==cntNew[k] ){ + /* Cell i is the cell immediately following the last cell on new + ** sibling page k. If the siblings are not leaf pages of an + ** intkey b-tree, then cell i is a divider cell. */ + pNew = apNew[++k]; + if( !leafData ) continue; + } + assert( jpgno!=pNew->pgno ){ + if( !leafCorrection ){ + ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc); + } + if( szCell[i]>pNew->minLocal ){ + ptrmapPutOvflPtr(pNew, apCell[i], &rc); + } + } + } + + if( !leafCorrection ){ + for(i=0; iaData[8]); + ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc); + } + } + +#if 0 + /* The ptrmapCheckPages() contains assert() statements that verify that + ** all pointer map pages are set correctly. This is helpful while + ** debugging. This is usually disabled because a corrupt database may + ** cause an assert() statement to fail. */ + ptrmapCheckPages(apNew, nNew); + ptrmapCheckPages(&pParent, 1); +#endif + } + + assert( pParent->isInit ); + TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n", + nOld, nNew, nCell)); + + /* + ** Cleanup before returning. + */ +balance_cleanup: + sqlite3ScratchFree(apCell); + for(i=0; i= 1700 && defined(_M_ARM) +#pragma optimize("", on) +#endif + + +/* +** This function is called when the root page of a b-tree structure is +** overfull (has one or more overflow pages). +** +** A new child page is allocated and the contents of the current root +** page, including overflow cells, are copied into the child. The root +** page is then overwritten to make it an empty page with the right-child +** pointer pointing to the new page. +** +** Before returning, all pointer-map entries corresponding to pages +** that the new child-page now contains pointers to are updated. The +** entry corresponding to the new right-child pointer of the root +** page is also updated. +** +** If successful, *ppChild is set to contain a reference to the child +** page and SQLITE_OK is returned. In this case the caller is required +** to call releasePage() on *ppChild exactly once. If an error occurs, +** an error code is returned and *ppChild is set to 0. +*/ +static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ + int rc; /* Return value from subprocedures */ + MemPage *pChild = 0; /* Pointer to a new child page */ + Pgno pgnoChild = 0; /* Page number of the new child page */ + BtShared *pBt = pRoot->pBt; /* The BTree */ + + assert( pRoot->nOverflow>0 ); + assert( sqlite3_mutex_held(pBt->mutex) ); + + /* Make pRoot, the root page of the b-tree, writable. Allocate a new + ** page that will become the new right-child of pPage. Copy the contents + ** of the node stored on pRoot into the new child page. + */ + rc = sqlite3PagerWrite(pRoot->pDbPage); + if( rc==SQLITE_OK ){ + rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); + copyNodeContent(pRoot, pChild, &rc); + if( ISAUTOVACUUM ){ + ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc); + } + } + if( rc ){ + *ppChild = 0; + releasePage(pChild); + return rc; + } + assert( sqlite3PagerIswriteable(pChild->pDbPage) ); + assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); + assert( pChild->nCell==pRoot->nCell ); + + TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); + + /* Copy the overflow cells from pRoot to pChild */ + memcpy(pChild->aiOvfl, pRoot->aiOvfl, + pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); + memcpy(pChild->apOvfl, pRoot->apOvfl, + pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); + pChild->nOverflow = pRoot->nOverflow; + + /* Zero the contents of pRoot. Then install pChild as the right-child. */ + zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); + put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); + + *ppChild = pChild; + return SQLITE_OK; +} + +/* +** The page that pCur currently points to has just been modified in +** some way. This function figures out if this modification means the +** tree needs to be balanced, and if so calls the appropriate balancing +** routine. Balancing routines are: +** +** balance_quick() +** balance_deeper() +** balance_nonroot() +*/ +static int balance(BtCursor *pCur){ + int rc = SQLITE_OK; + const int nMin = pCur->pBt->usableSize * 2 / 3; + u8 aBalanceQuickSpace[13]; + u8 *pFree = 0; + + TESTONLY( int balance_quick_called = 0 ); + TESTONLY( int balance_deeper_called = 0 ); + + do { + int iPage = pCur->iPage; + MemPage *pPage = pCur->apPage[iPage]; + + if( iPage==0 ){ + if( pPage->nOverflow ){ + /* The root page of the b-tree is overfull. In this case call the + ** balance_deeper() function to create a new child for the root-page + ** and copy the current contents of the root-page to it. The + ** next iteration of the do-loop will balance the child page. + */ + assert( (balance_deeper_called++)==0 ); + rc = balance_deeper(pPage, &pCur->apPage[1]); + if( rc==SQLITE_OK ){ + pCur->iPage = 1; + pCur->aiIdx[0] = 0; + pCur->aiIdx[1] = 0; + assert( pCur->apPage[1]->nOverflow ); + } + }else{ + break; + } + }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ + break; + }else{ + MemPage * const pParent = pCur->apPage[iPage-1]; + int const iIdx = pCur->aiIdx[iPage-1]; + + rc = sqlite3PagerWrite(pParent->pDbPage); + if( rc==SQLITE_OK ){ +#ifndef SQLITE_OMIT_QUICKBALANCE + if( pPage->hasData + && pPage->nOverflow==1 + && pPage->aiOvfl[0]==pPage->nCell + && pParent->pgno!=1 + && pParent->nCell==iIdx + ){ + /* Call balance_quick() to create a new sibling of pPage on which + ** to store the overflow cell. balance_quick() inserts a new cell + ** into pParent, which may cause pParent overflow. If this + ** happens, the next interation of the do-loop will balance pParent + ** use either balance_nonroot() or balance_deeper(). Until this + ** happens, the overflow cell is stored in the aBalanceQuickSpace[] + ** buffer. + ** + ** The purpose of the following assert() is to check that only a + ** single call to balance_quick() is made for each call to this + ** function. If this were not verified, a subtle bug involving reuse + ** of the aBalanceQuickSpace[] might sneak in. + */ + assert( (balance_quick_called++)==0 ); + rc = balance_quick(pParent, pPage, aBalanceQuickSpace); + }else +#endif + { + /* In this case, call balance_nonroot() to redistribute cells + ** between pPage and up to 2 of its sibling pages. This involves + ** modifying the contents of pParent, which may cause pParent to + ** become overfull or underfull. The next iteration of the do-loop + ** will balance the parent page to correct this. + ** + ** If the parent page becomes overfull, the overflow cell or cells + ** are stored in the pSpace buffer allocated immediately below. + ** A subsequent iteration of the do-loop will deal with this by + ** calling balance_nonroot() (balance_deeper() may be called first, + ** but it doesn't deal with overflow cells - just moves them to a + ** different page). Once this subsequent call to balance_nonroot() + ** has completed, it is safe to release the pSpace buffer used by + ** the previous call, as the overflow cell data will have been + ** copied either into the body of a database page or into the new + ** pSpace buffer passed to the latter call to balance_nonroot(). + */ + u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); + rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints); + if( pFree ){ + /* If pFree is not NULL, it points to the pSpace buffer used + ** by a previous call to balance_nonroot(). Its contents are + ** now stored either on real database pages or within the + ** new pSpace buffer, so it may be safely freed here. */ + sqlite3PageFree(pFree); + } + + /* The pSpace buffer will be freed after the next call to + ** balance_nonroot(), or just before this function returns, whichever + ** comes first. */ + pFree = pSpace; + } + } + + pPage->nOverflow = 0; + + /* The next iteration of the do-loop balances the parent page. */ + releasePage(pPage); + pCur->iPage--; + } + }while( rc==SQLITE_OK ); + + if( pFree ){ + sqlite3PageFree(pFree); + } + return rc; +} + + +/* +** Insert a new record into the BTree. The key is given by (pKey,nKey) +** and the data is given by (pData,nData). The cursor is used only to +** define what table the record should be inserted into. The cursor +** is left pointing at a random location. +** +** For an INTKEY table, only the nKey value of the key is used. pKey is +** ignored. For a ZERODATA table, the pData and nData are both ignored. +** +** If the seekResult parameter is non-zero, then a successful call to +** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already +** been performed. seekResult is the search result returned (a negative +** number if pCur points at an entry that is smaller than (pKey, nKey), or +** a positive value if pCur points at an etry that is larger than +** (pKey, nKey)). +** +** If the seekResult parameter is non-zero, then the caller guarantees that +** cursor pCur is pointing at the existing copy of a row that is to be +** overwritten. If the seekResult parameter is 0, then cursor pCur may +** point to any entry or to no entry at all and so this function has to seek +** the cursor before the new key can be inserted. +*/ +SQLITE_PRIVATE int sqlite3BtreeInsert( + BtCursor *pCur, /* Insert data into the table of this cursor */ + const void *pKey, i64 nKey, /* The key of the new record */ + const void *pData, int nData, /* The data of the new record */ + int nZero, /* Number of extra 0 bytes to append to data */ + int appendBias, /* True if this is likely an append */ + int seekResult /* Result of prior MovetoUnpacked() call */ +){ + int rc; + int loc = seekResult; /* -1: before desired location +1: after */ + int szNew = 0; + int idx; + MemPage *pPage; + Btree *p = pCur->pBtree; + BtShared *pBt = p->pBt; + unsigned char *oldCell; + unsigned char *newCell = 0; + + if( pCur->eState==CURSOR_FAULT ){ + assert( pCur->skipNext!=SQLITE_OK ); + return pCur->skipNext; + } + + assert( cursorHoldsMutex(pCur) ); + assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE + && (pBt->btsFlags & BTS_READ_ONLY)==0 ); + assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); + + /* Assert that the caller has been consistent. If this cursor was opened + ** expecting an index b-tree, then the caller should be inserting blob + ** keys with no associated data. If the cursor was opened expecting an + ** intkey table, the caller should be inserting integer keys with a + ** blob of associated data. */ + assert( (pKey==0)==(pCur->pKeyInfo==0) ); + + /* Save the positions of any other cursors open on this table. + ** + ** In some cases, the call to btreeMoveto() below is a no-op. For + ** example, when inserting data into a table with auto-generated integer + ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the + ** integer key to use. It then calls this function to actually insert the + ** data into the intkey B-Tree. In this case btreeMoveto() recognizes + ** that the cursor is already where it needs to be and returns without + ** doing any work. To avoid thwarting these optimizations, it is important + ** not to clear the cursor here. + */ + rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); + if( rc ) return rc; + + /* If this is an insert into a table b-tree, invalidate any incrblob + ** cursors open on the row being replaced (assuming this is a replace + ** operation - if it is not, the following is a no-op). */ + if( pCur->pKeyInfo==0 ){ + invalidateIncrblobCursors(p, nKey, 0); + } + + if( !loc ){ + rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc); + if( rc ) return rc; + } + assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) ); + + pPage = pCur->apPage[pCur->iPage]; + assert( pPage->intKey || nKey>=0 ); + assert( pPage->leaf || !pPage->intKey ); + + TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", + pCur->pgnoRoot, nKey, nData, pPage->pgno, + loc==0 ? "overwrite" : "new entry")); + assert( pPage->isInit ); + allocateTempSpace(pBt); + newCell = pBt->pTmpSpace; + if( newCell==0 ) return SQLITE_NOMEM; + rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew); + if( rc ) goto end_insert; + assert( szNew==cellSizePtr(pPage, newCell) ); + assert( szNew <= MX_CELL_SIZE(pBt) ); + idx = pCur->aiIdx[pCur->iPage]; + if( loc==0 ){ + u16 szOld; + assert( idxnCell ); + rc = sqlite3PagerWrite(pPage->pDbPage); + if( rc ){ + goto end_insert; + } + oldCell = findCell(pPage, idx); + if( !pPage->leaf ){ + memcpy(newCell, oldCell, 4); + } + szOld = cellSizePtr(pPage, oldCell); + rc = clearCell(pPage, oldCell); + dropCell(pPage, idx, szOld, &rc); + if( rc ) goto end_insert; + }else if( loc<0 && pPage->nCell>0 ){ + assert( pPage->leaf ); + idx = ++pCur->aiIdx[pCur->iPage]; + }else{ + assert( pPage->leaf ); + } + insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); + assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); + + /* If no error has occurred and pPage has an overflow cell, call balance() + ** to redistribute the cells within the tree. Since balance() may move + ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey + ** variables. + ** + ** Previous versions of SQLite called moveToRoot() to move the cursor + ** back to the root page as balance() used to invalidate the contents + ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, + ** set the cursor state to "invalid". This makes common insert operations + ** slightly faster. + ** + ** There is a subtle but important optimization here too. When inserting + ** multiple records into an intkey b-tree using a single cursor (as can + ** happen while processing an "INSERT INTO ... SELECT" statement), it + ** is advantageous to leave the cursor pointing to the last entry in + ** the b-tree if possible. If the cursor is left pointing to the last + ** entry in the table, and the next row inserted has an integer key + ** larger than the largest existing key, it is possible to insert the + ** row without seeking the cursor. This can be a big performance boost. + */ + pCur->info.nSize = 0; + pCur->validNKey = 0; + if( rc==SQLITE_OK && pPage->nOverflow ){ + rc = balance(pCur); + + /* Must make sure nOverflow is reset to zero even if the balance() + ** fails. Internal data structure corruption will result otherwise. + ** Also, set the cursor state to invalid. This stops saveCursorPosition() + ** from trying to save the current position of the cursor. */ + pCur->apPage[pCur->iPage]->nOverflow = 0; + pCur->eState = CURSOR_INVALID; + } + assert( pCur->apPage[pCur->iPage]->nOverflow==0 ); + +end_insert: + return rc; +} + +/* +** Delete the entry that the cursor is pointing to. The cursor +** is left pointing at a arbitrary location. +*/ +SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){ + Btree *p = pCur->pBtree; + BtShared *pBt = p->pBt; + int rc; /* Return code */ + MemPage *pPage; /* Page to delete cell from */ + unsigned char *pCell; /* Pointer to cell to delete */ + int iCellIdx; /* Index of cell to delete */ + int iCellDepth; /* Depth of node containing pCell */ + + assert( cursorHoldsMutex(pCur) ); + assert( pBt->inTransaction==TRANS_WRITE ); + assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); + assert( pCur->wrFlag ); + assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); + assert( !hasReadConflicts(p, pCur->pgnoRoot) ); + + if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) + || NEVER(pCur->eState!=CURSOR_VALID) + ){ + return SQLITE_ERROR; /* Something has gone awry. */ + } + + iCellDepth = pCur->iPage; + iCellIdx = pCur->aiIdx[iCellDepth]; + pPage = pCur->apPage[iCellDepth]; + pCell = findCell(pPage, iCellIdx); + + /* If the page containing the entry to delete is not a leaf page, move + ** the cursor to the largest entry in the tree that is smaller than + ** the entry being deleted. This cell will replace the cell being deleted + ** from the internal node. The 'previous' entry is used for this instead + ** of the 'next' entry, as the previous entry is always a part of the + ** sub-tree headed by the child page of the cell being deleted. This makes + ** balancing the tree following the delete operation easier. */ + if( !pPage->leaf ){ + int notUsed; + rc = sqlite3BtreePrevious(pCur, ¬Used); + if( rc ) return rc; + } + + /* Save the positions of any other cursors open on this table before + ** making any modifications. Make the page containing the entry to be + ** deleted writable. Then free any overflow pages associated with the + ** entry and finally remove the cell itself from within the page. + */ + rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); + if( rc ) return rc; + + /* If this is a delete operation to remove a row from a table b-tree, + ** invalidate any incrblob cursors open on the row being deleted. */ + if( pCur->pKeyInfo==0 ){ + invalidateIncrblobCursors(p, pCur->info.nKey, 0); + } + + rc = sqlite3PagerWrite(pPage->pDbPage); + if( rc ) return rc; + rc = clearCell(pPage, pCell); + dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc); + if( rc ) return rc; + + /* If the cell deleted was not located on a leaf page, then the cursor + ** is currently pointing to the largest entry in the sub-tree headed + ** by the child-page of the cell that was just deleted from an internal + ** node. The cell from the leaf node needs to be moved to the internal + ** node to replace the deleted cell. */ + if( !pPage->leaf ){ + MemPage *pLeaf = pCur->apPage[pCur->iPage]; + int nCell; + Pgno n = pCur->apPage[iCellDepth+1]->pgno; + unsigned char *pTmp; + + pCell = findCell(pLeaf, pLeaf->nCell-1); + nCell = cellSizePtr(pLeaf, pCell); + assert( MX_CELL_SIZE(pBt) >= nCell ); + + allocateTempSpace(pBt); + pTmp = pBt->pTmpSpace; + + rc = sqlite3PagerWrite(pLeaf->pDbPage); + insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); + dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); + if( rc ) return rc; + } + + /* Balance the tree. If the entry deleted was located on a leaf page, + ** then the cursor still points to that page. In this case the first + ** call to balance() repairs the tree, and the if(...) condition is + ** never true. + ** + ** Otherwise, if the entry deleted was on an internal node page, then + ** pCur is pointing to the leaf page from which a cell was removed to + ** replace the cell deleted from the internal node. This is slightly + ** tricky as the leaf node may be underfull, and the internal node may + ** be either under or overfull. In this case run the balancing algorithm + ** on the leaf node first. If the balance proceeds far enough up the + ** tree that we can be sure that any problem in the internal node has + ** been corrected, so be it. Otherwise, after balancing the leaf node, + ** walk the cursor up the tree to the internal node and balance it as + ** well. */ + rc = balance(pCur); + if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){ + while( pCur->iPage>iCellDepth ){ + releasePage(pCur->apPage[pCur->iPage--]); + } + rc = balance(pCur); + } + + if( rc==SQLITE_OK ){ + moveToRoot(pCur); + } + return rc; +} + +/* +** Create a new BTree table. Write into *piTable the page +** number for the root page of the new table. +** +** The type of type is determined by the flags parameter. Only the +** following values of flags are currently in use. Other values for +** flags might not work: +** +** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys +** BTREE_ZERODATA Used for SQL indices +*/ +static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ + BtShared *pBt = p->pBt; + MemPage *pRoot; + Pgno pgnoRoot; + int rc; + int ptfFlags; /* Page-type flage for the root page of new table */ + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( pBt->inTransaction==TRANS_WRITE ); + assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); + +#ifdef SQLITE_OMIT_AUTOVACUUM + rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); + if( rc ){ + return rc; + } +#else + if( pBt->autoVacuum ){ + Pgno pgnoMove; /* Move a page here to make room for the root-page */ + MemPage *pPageMove; /* The page to move to. */ + + /* Creating a new table may probably require moving an existing database + ** to make room for the new tables root page. In case this page turns + ** out to be an overflow page, delete all overflow page-map caches + ** held by open cursors. + */ + invalidateAllOverflowCache(pBt); + + /* Read the value of meta[3] from the database to determine where the + ** root page of the new table should go. meta[3] is the largest root-page + ** created so far, so the new root-page is (meta[3]+1). + */ + sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); + pgnoRoot++; + + /* The new root-page may not be allocated on a pointer-map page, or the + ** PENDING_BYTE page. + */ + while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || + pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ + pgnoRoot++; + } + assert( pgnoRoot>=3 ); + + /* Allocate a page. The page that currently resides at pgnoRoot will + ** be moved to the allocated page (unless the allocated page happens + ** to reside at pgnoRoot). + */ + rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT); + if( rc!=SQLITE_OK ){ + return rc; + } + + if( pgnoMove!=pgnoRoot ){ + /* pgnoRoot is the page that will be used for the root-page of + ** the new table (assuming an error did not occur). But we were + ** allocated pgnoMove. If required (i.e. if it was not allocated + ** by extending the file), the current page at position pgnoMove + ** is already journaled. + */ + u8 eType = 0; + Pgno iPtrPage = 0; + + /* Save the positions of any open cursors. This is required in + ** case they are holding a reference to an xFetch reference + ** corresponding to page pgnoRoot. */ + rc = saveAllCursors(pBt, 0, 0); + releasePage(pPageMove); + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Move the page currently at pgnoRoot to pgnoMove. */ + rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); + if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ + rc = SQLITE_CORRUPT_BKPT; + } + if( rc!=SQLITE_OK ){ + releasePage(pRoot); + return rc; + } + assert( eType!=PTRMAP_ROOTPAGE ); + assert( eType!=PTRMAP_FREEPAGE ); + rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); + releasePage(pRoot); + + /* Obtain the page at pgnoRoot */ + if( rc!=SQLITE_OK ){ + return rc; + } + rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + rc = sqlite3PagerWrite(pRoot->pDbPage); + if( rc!=SQLITE_OK ){ + releasePage(pRoot); + return rc; + } + }else{ + pRoot = pPageMove; + } + + /* Update the pointer-map and meta-data with the new root-page number. */ + ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc); + if( rc ){ + releasePage(pRoot); + return rc; + } + + /* When the new root page was allocated, page 1 was made writable in + ** order either to increase the database filesize, or to decrement the + ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. + */ + assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); + rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); + if( NEVER(rc) ){ + releasePage(pRoot); + return rc; + } + + }else{ + rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); + if( rc ) return rc; + } +#endif + assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); + if( createTabFlags & BTREE_INTKEY ){ + ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; + }else{ + ptfFlags = PTF_ZERODATA | PTF_LEAF; + } + zeroPage(pRoot, ptfFlags); + sqlite3PagerUnref(pRoot->pDbPage); + assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 ); + *piTable = (int)pgnoRoot; + return SQLITE_OK; +} +SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ + int rc; + sqlite3BtreeEnter(p); + rc = btreeCreateTable(p, piTable, flags); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Erase the given database page and all its children. Return +** the page to the freelist. +*/ +static int clearDatabasePage( + BtShared *pBt, /* The BTree that contains the table */ + Pgno pgno, /* Page number to clear */ + int freePageFlag, /* Deallocate page if true */ + int *pnChange /* Add number of Cells freed to this counter */ +){ + MemPage *pPage; + int rc; + unsigned char *pCell; + int i; + + assert( sqlite3_mutex_held(pBt->mutex) ); + if( pgno>btreePagecount(pBt) ){ + return SQLITE_CORRUPT_BKPT; + } + + rc = getAndInitPage(pBt, pgno, &pPage, 0); + if( rc ) return rc; + for(i=0; inCell; i++){ + pCell = findCell(pPage, i); + if( !pPage->leaf ){ + rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); + if( rc ) goto cleardatabasepage_out; + } + rc = clearCell(pPage, pCell); + if( rc ) goto cleardatabasepage_out; + } + if( !pPage->leaf ){ + rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange); + if( rc ) goto cleardatabasepage_out; + }else if( pnChange ){ + assert( pPage->intKey ); + *pnChange += pPage->nCell; + } + if( freePageFlag ){ + freePage(pPage, &rc); + }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ + zeroPage(pPage, pPage->aData[0] | PTF_LEAF); + } + +cleardatabasepage_out: + releasePage(pPage); + return rc; +} + +/* +** Delete all information from a single table in the database. iTable is +** the page number of the root of the table. After this routine returns, +** the root page is empty, but still exists. +** +** This routine will fail with SQLITE_LOCKED if there are any open +** read cursors on the table. Open write cursors are moved to the +** root of the table. +** +** If pnChange is not NULL, then table iTable must be an intkey table. The +** integer value pointed to by pnChange is incremented by the number of +** entries in the table. +*/ +SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ + int rc; + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); + assert( p->inTrans==TRANS_WRITE ); + + rc = saveAllCursors(pBt, (Pgno)iTable, 0); + + if( SQLITE_OK==rc ){ + /* Invalidate all incrblob cursors open on table iTable (assuming iTable + ** is the root of a table b-tree - if it is not, the following call is + ** a no-op). */ + invalidateIncrblobCursors(p, 0, 1); + rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); + } + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Erase all information in a table and add the root of the table to +** the freelist. Except, the root of the principle table (the one on +** page 1) is never added to the freelist. +** +** This routine will fail with SQLITE_LOCKED if there are any open +** cursors on the table. +** +** If AUTOVACUUM is enabled and the page at iTable is not the last +** root page in the database file, then the last root page +** in the database file is moved into the slot formerly occupied by +** iTable and that last slot formerly occupied by the last root page +** is added to the freelist instead of iTable. In this say, all +** root pages are kept at the beginning of the database file, which +** is necessary for AUTOVACUUM to work right. *piMoved is set to the +** page number that used to be the last root page in the file before +** the move. If no page gets moved, *piMoved is set to 0. +** The last root page is recorded in meta[3] and the value of +** meta[3] is updated by this procedure. +*/ +static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ + int rc; + MemPage *pPage = 0; + BtShared *pBt = p->pBt; + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( p->inTrans==TRANS_WRITE ); + + /* It is illegal to drop a table if any cursors are open on the + ** database. This is because in auto-vacuum mode the backend may + ** need to move another root-page to fill a gap left by the deleted + ** root page. If an open cursor was using this page a problem would + ** occur. + ** + ** This error is caught long before control reaches this point. + */ + if( NEVER(pBt->pCursor) ){ + sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db); + return SQLITE_LOCKED_SHAREDCACHE; + } + + rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); + if( rc ) return rc; + rc = sqlite3BtreeClearTable(p, iTable, 0); + if( rc ){ + releasePage(pPage); + return rc; + } + + *piMoved = 0; + + if( iTable>1 ){ +#ifdef SQLITE_OMIT_AUTOVACUUM + freePage(pPage, &rc); + releasePage(pPage); +#else + if( pBt->autoVacuum ){ + Pgno maxRootPgno; + sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); + + if( iTable==maxRootPgno ){ + /* If the table being dropped is the table with the largest root-page + ** number in the database, put the root page on the free list. + */ + freePage(pPage, &rc); + releasePage(pPage); + if( rc!=SQLITE_OK ){ + return rc; + } + }else{ + /* The table being dropped does not have the largest root-page + ** number in the database. So move the page that does into the + ** gap left by the deleted root-page. + */ + MemPage *pMove; + releasePage(pPage); + rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); + releasePage(pMove); + if( rc!=SQLITE_OK ){ + return rc; + } + pMove = 0; + rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); + freePage(pMove, &rc); + releasePage(pMove); + if( rc!=SQLITE_OK ){ + return rc; + } + *piMoved = maxRootPgno; + } + + /* Set the new 'max-root-page' value in the database header. This + ** is the old value less one, less one more if that happens to + ** be a root-page number, less one again if that is the + ** PENDING_BYTE_PAGE. + */ + maxRootPgno--; + while( maxRootPgno==PENDING_BYTE_PAGE(pBt) + || PTRMAP_ISPAGE(pBt, maxRootPgno) ){ + maxRootPgno--; + } + assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); + + rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); + }else{ + freePage(pPage, &rc); + releasePage(pPage); + } +#endif + }else{ + /* If sqlite3BtreeDropTable was called on page 1. + ** This really never should happen except in a corrupt + ** database. + */ + zeroPage(pPage, PTF_INTKEY|PTF_LEAF ); + releasePage(pPage); + } + return rc; +} +SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ + int rc; + sqlite3BtreeEnter(p); + rc = btreeDropTable(p, iTable, piMoved); + sqlite3BtreeLeave(p); + return rc; +} + + +/* +** This function may only be called if the b-tree connection already +** has a read or write transaction open on the database. +** +** Read the meta-information out of a database file. Meta[0] +** is the number of free pages currently in the database. Meta[1] +** through meta[15] are available for use by higher layers. Meta[0] +** is read-only, the others are read/write. +** +** The schema layer numbers meta values differently. At the schema +** layer (and the SetCookie and ReadCookie opcodes) the number of +** free pages is not visible. So Cookie[0] is the same as Meta[1]. +*/ +SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ + BtShared *pBt = p->pBt; + + sqlite3BtreeEnter(p); + assert( p->inTrans>TRANS_NONE ); + assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) ); + assert( pBt->pPage1 ); + assert( idx>=0 && idx<=15 ); + + *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); + + /* If auto-vacuum is disabled in this build and this is an auto-vacuum + ** database, mark the database as read-only. */ +#ifdef SQLITE_OMIT_AUTOVACUUM + if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){ + pBt->btsFlags |= BTS_READ_ONLY; + } +#endif + + sqlite3BtreeLeave(p); +} + +/* +** Write meta-information back into the database. Meta[0] is +** read-only and may not be written. +*/ +SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ + BtShared *pBt = p->pBt; + unsigned char *pP1; + int rc; + assert( idx>=1 && idx<=15 ); + sqlite3BtreeEnter(p); + assert( p->inTrans==TRANS_WRITE ); + assert( pBt->pPage1!=0 ); + pP1 = pBt->pPage1->aData; + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + if( rc==SQLITE_OK ){ + put4byte(&pP1[36 + idx*4], iMeta); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( idx==BTREE_INCR_VACUUM ){ + assert( pBt->autoVacuum || iMeta==0 ); + assert( iMeta==0 || iMeta==1 ); + pBt->incrVacuum = (u8)iMeta; + } +#endif + } + sqlite3BtreeLeave(p); + return rc; +} + +#ifndef SQLITE_OMIT_BTREECOUNT +/* +** The first argument, pCur, is a cursor opened on some b-tree. Count the +** number of entries in the b-tree and write the result to *pnEntry. +** +** SQLITE_OK is returned if the operation is successfully executed. +** Otherwise, if an error is encountered (i.e. an IO error or database +** corruption) an SQLite error code is returned. +*/ +SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ + i64 nEntry = 0; /* Value to return in *pnEntry */ + int rc; /* Return code */ + + if( pCur->pgnoRoot==0 ){ + *pnEntry = 0; + return SQLITE_OK; + } + rc = moveToRoot(pCur); + + /* Unless an error occurs, the following loop runs one iteration for each + ** page in the B-Tree structure (not including overflow pages). + */ + while( rc==SQLITE_OK ){ + int iIdx; /* Index of child node in parent */ + MemPage *pPage; /* Current page of the b-tree */ + + /* If this is a leaf page or the tree is not an int-key tree, then + ** this page contains countable entries. Increment the entry counter + ** accordingly. + */ + pPage = pCur->apPage[pCur->iPage]; + if( pPage->leaf || !pPage->intKey ){ + nEntry += pPage->nCell; + } + + /* pPage is a leaf node. This loop navigates the cursor so that it + ** points to the first interior cell that it points to the parent of + ** the next page in the tree that has not yet been visited. The + ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell + ** of the page, or to the number of cells in the page if the next page + ** to visit is the right-child of its parent. + ** + ** If all pages in the tree have been visited, return SQLITE_OK to the + ** caller. + */ + if( pPage->leaf ){ + do { + if( pCur->iPage==0 ){ + /* All pages of the b-tree have been visited. Return successfully. */ + *pnEntry = nEntry; + return SQLITE_OK; + } + moveToParent(pCur); + }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell ); + + pCur->aiIdx[pCur->iPage]++; + pPage = pCur->apPage[pCur->iPage]; + } + + /* Descend to the child node of the cell that the cursor currently + ** points at. This is the right-child if (iIdx==pPage->nCell). + */ + iIdx = pCur->aiIdx[pCur->iPage]; + if( iIdx==pPage->nCell ){ + rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); + }else{ + rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx))); + } + } + + /* An error has occurred. Return an error code. */ + return rc; +} +#endif + +/* +** Return the pager associated with a BTree. This routine is used for +** testing and debugging only. +*/ +SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){ + return p->pBt->pPager; +} + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK +/* +** Append a message to the error message string. +*/ +static void checkAppendMsg( + IntegrityCk *pCheck, + char *zMsg1, + const char *zFormat, + ... +){ + va_list ap; + if( !pCheck->mxErr ) return; + pCheck->mxErr--; + pCheck->nErr++; + va_start(ap, zFormat); + if( pCheck->errMsg.nChar ){ + sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1); + } + if( zMsg1 ){ + sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1); + } + sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap); + va_end(ap); + if( pCheck->errMsg.accError==STRACCUM_NOMEM ){ + pCheck->mallocFailed = 1; + } +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK + +/* +** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that +** corresponds to page iPg is already set. +*/ +static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ + assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); + return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); +} + +/* +** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. +*/ +static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ + assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); + pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); +} + + +/* +** Add 1 to the reference count for page iPage. If this is the second +** reference to the page, add an error message to pCheck->zErrMsg. +** Return 1 if there are 2 ore more references to the page and 0 if +** if this is the first reference to the page. +** +** Also check that the page number is in bounds. +*/ +static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){ + if( iPage==0 ) return 1; + if( iPage>pCheck->nPage ){ + checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage); + return 1; + } + if( getPageReferenced(pCheck, iPage) ){ + checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage); + return 1; + } + setPageReferenced(pCheck, iPage); + return 0; +} + +#ifndef SQLITE_OMIT_AUTOVACUUM +/* +** Check that the entry in the pointer-map for page iChild maps to +** page iParent, pointer type ptrType. If not, append an error message +** to pCheck. +*/ +static void checkPtrmap( + IntegrityCk *pCheck, /* Integrity check context */ + Pgno iChild, /* Child page number */ + u8 eType, /* Expected pointer map type */ + Pgno iParent, /* Expected pointer map parent page number */ + char *zContext /* Context description (used for error msg) */ +){ + int rc; + u8 ePtrmapType; + Pgno iPtrmapParent; + + rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1; + checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild); + return; + } + + if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ + checkAppendMsg(pCheck, zContext, + "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", + iChild, eType, iParent, ePtrmapType, iPtrmapParent); + } +} +#endif + +/* +** Check the integrity of the freelist or of an overflow page list. +** Verify that the number of pages on the list is N. +*/ +static void checkList( + IntegrityCk *pCheck, /* Integrity checking context */ + int isFreeList, /* True for a freelist. False for overflow page list */ + int iPage, /* Page number for first page in the list */ + int N, /* Expected number of pages in the list */ + char *zContext /* Context for error messages */ +){ + int i; + int expected = N; + int iFirst = iPage; + while( N-- > 0 && pCheck->mxErr ){ + DbPage *pOvflPage; + unsigned char *pOvflData; + if( iPage<1 ){ + checkAppendMsg(pCheck, zContext, + "%d of %d pages missing from overflow list starting at %d", + N+1, expected, iFirst); + break; + } + if( checkRef(pCheck, iPage, zContext) ) break; + if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){ + checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage); + break; + } + pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); + if( isFreeList ){ + int n = get4byte(&pOvflData[4]); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pCheck->pBt->autoVacuum ){ + checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext); + } +#endif + if( n>(int)pCheck->pBt->usableSize/4-2 ){ + checkAppendMsg(pCheck, zContext, + "freelist leaf count too big on page %d", iPage); + N--; + }else{ + for(i=0; ipBt->autoVacuum ){ + checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext); + } +#endif + checkRef(pCheck, iFreePage, zContext); + } + N -= n; + } + } +#ifndef SQLITE_OMIT_AUTOVACUUM + else{ + /* If this database supports auto-vacuum and iPage is not the last + ** page in this overflow list, check that the pointer-map entry for + ** the following page matches iPage. + */ + if( pCheck->pBt->autoVacuum && N>0 ){ + i = get4byte(pOvflData); + checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext); + } + } +#endif + iPage = get4byte(pOvflData); + sqlite3PagerUnref(pOvflPage); + } +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK +/* +** Do various sanity checks on a single page of a tree. Return +** the tree depth. Root pages return 0. Parents of root pages +** return 1, and so forth. +** +** These checks are done: +** +** 1. Make sure that cells and freeblocks do not overlap +** but combine to completely cover the page. +** NO 2. Make sure cell keys are in order. +** NO 3. Make sure no key is less than or equal to zLowerBound. +** NO 4. Make sure no key is greater than or equal to zUpperBound. +** 5. Check the integrity of overflow pages. +** 6. Recursively call checkTreePage on all children. +** 7. Verify that the depth of all children is the same. +** 8. Make sure this page is at least 33% full or else it is +** the root of the tree. +*/ +static int checkTreePage( + IntegrityCk *pCheck, /* Context for the sanity check */ + int iPage, /* Page number of the page to check */ + char *zParentContext, /* Parent context */ + i64 *pnParentMinKey, + i64 *pnParentMaxKey +){ + MemPage *pPage; + int i, rc, depth, d2, pgno, cnt; + int hdr, cellStart; + int nCell; + u8 *data; + BtShared *pBt; + int usableSize; + char zContext[100]; + char *hit = 0; + i64 nMinKey = 0; + i64 nMaxKey = 0; + + sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage); + + /* Check that the page exists + */ + pBt = pCheck->pBt; + usableSize = pBt->usableSize; + if( iPage==0 ) return 0; + if( checkRef(pCheck, iPage, zParentContext) ) return 0; + if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){ + checkAppendMsg(pCheck, zContext, + "unable to get the page. error code=%d", rc); + return 0; + } + + /* Clear MemPage.isInit to make sure the corruption detection code in + ** btreeInitPage() is executed. */ + pPage->isInit = 0; + if( (rc = btreeInitPage(pPage))!=0 ){ + assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ + checkAppendMsg(pCheck, zContext, + "btreeInitPage() returns error code %d", rc); + releasePage(pPage); + return 0; + } + + /* Check out all the cells. + */ + depth = 0; + for(i=0; inCell && pCheck->mxErr; i++){ + u8 *pCell; + u32 sz; + CellInfo info; + + /* Check payload overflow pages + */ + sqlite3_snprintf(sizeof(zContext), zContext, + "On tree page %d cell %d: ", iPage, i); + pCell = findCell(pPage,i); + btreeParseCellPtr(pPage, pCell, &info); + sz = info.nData; + if( !pPage->intKey ) sz += (int)info.nKey; + /* For intKey pages, check that the keys are in order. + */ + else if( i==0 ) nMinKey = nMaxKey = info.nKey; + else{ + if( info.nKey <= nMaxKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey); + } + nMaxKey = info.nKey; + } + assert( sz==info.nPayload ); + if( (sz>info.nLocal) + && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize]) + ){ + int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4); + Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum ){ + checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext); + } +#endif + checkList(pCheck, 0, pgnoOvfl, nPage, zContext); + } + + /* Check sanity of left child page. + */ + if( !pPage->leaf ){ + pgno = get4byte(pCell); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum ){ + checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); + } +#endif + d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey); + if( i>0 && d2!=depth ){ + checkAppendMsg(pCheck, zContext, "Child page depth differs"); + } + depth = d2; + } + } + + if( !pPage->leaf ){ + pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); + sqlite3_snprintf(sizeof(zContext), zContext, + "On page %d at right child: ", iPage); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum ){ + checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); + } +#endif + checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey); + } + + /* For intKey leaf pages, check that the min/max keys are in order + ** with any left/parent/right pages. + */ + if( pPage->leaf && pPage->intKey ){ + /* if we are a left child page */ + if( pnParentMinKey ){ + /* if we are the left most child page */ + if( !pnParentMaxKey ){ + if( nMaxKey > *pnParentMinKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (max larger than parent min of %lld)", + nMaxKey, *pnParentMinKey); + } + }else{ + if( nMinKey <= *pnParentMinKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (min less than parent min of %lld)", + nMinKey, *pnParentMinKey); + } + if( nMaxKey > *pnParentMaxKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (max larger than parent max of %lld)", + nMaxKey, *pnParentMaxKey); + } + *pnParentMinKey = nMaxKey; + } + /* else if we're a right child page */ + } else if( pnParentMaxKey ){ + if( nMinKey <= *pnParentMaxKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (min less than parent max of %lld)", + nMinKey, *pnParentMaxKey); + } + } + } + + /* Check for complete coverage of the page + */ + data = pPage->aData; + hdr = pPage->hdrOffset; + hit = sqlite3PageMalloc( pBt->pageSize ); + if( hit==0 ){ + pCheck->mallocFailed = 1; + }else{ + int contentOffset = get2byteNotZero(&data[hdr+5]); + assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ + memset(hit+contentOffset, 0, usableSize-contentOffset); + memset(hit, 1, contentOffset); + nCell = get2byte(&data[hdr+3]); + cellStart = hdr + 12 - 4*pPage->leaf; + for(i=0; i=usableSize ){ + checkAppendMsg(pCheck, 0, + "Corruption detected in cell %d on page %d",i,iPage); + }else{ + for(j=pc+size-1; j>=pc; j--) hit[j]++; + } + } + i = get2byte(&data[hdr+1]); + while( i>0 ){ + int size, j; + assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */ + size = get2byte(&data[i+2]); + assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */ + for(j=i+size-1; j>=i; j--) hit[j]++; + j = get2byte(&data[i]); + assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */ + assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */ + i = j; + } + for(i=cnt=0; i1 ){ + checkAppendMsg(pCheck, 0, + "Multiple uses for byte %d of page %d", i, iPage); + break; + } + } + if( cnt!=data[hdr+7] ){ + checkAppendMsg(pCheck, 0, + "Fragmentation of %d bytes reported as %d on page %d", + cnt, data[hdr+7], iPage); + } + } + sqlite3PageFree(hit); + releasePage(pPage); + return depth+1; +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK +/* +** This routine does a complete check of the given BTree file. aRoot[] is +** an array of pages numbers were each page number is the root page of +** a table. nRoot is the number of entries in aRoot. +** +** A read-only or read-write transaction must be opened before calling +** this function. +** +** Write the number of error seen in *pnErr. Except for some memory +** allocation errors, an error message held in memory obtained from +** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is +** returned. If a memory allocation error occurs, NULL is returned. +*/ +SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( + Btree *p, /* The btree to be checked */ + int *aRoot, /* An array of root pages numbers for individual trees */ + int nRoot, /* Number of entries in aRoot[] */ + int mxErr, /* Stop reporting errors after this many */ + int *pnErr /* Write number of errors seen to this variable */ +){ + Pgno i; + int nRef; + IntegrityCk sCheck; + BtShared *pBt = p->pBt; + char zErr[100]; + + sqlite3BtreeEnter(p); + assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); + nRef = sqlite3PagerRefcount(pBt->pPager); + sCheck.pBt = pBt; + sCheck.pPager = pBt->pPager; + sCheck.nPage = btreePagecount(sCheck.pBt); + sCheck.mxErr = mxErr; + sCheck.nErr = 0; + sCheck.mallocFailed = 0; + *pnErr = 0; + if( sCheck.nPage==0 ){ + sqlite3BtreeLeave(p); + return 0; + } + + sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); + if( !sCheck.aPgRef ){ + *pnErr = 1; + sqlite3BtreeLeave(p); + return 0; + } + i = PENDING_BYTE_PAGE(pBt); + if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); + sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); + sCheck.errMsg.useMalloc = 2; + + /* Check the integrity of the freelist + */ + checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), + get4byte(&pBt->pPage1->aData[36]), "Main freelist: "); + + /* Check all the tables. + */ + for(i=0; (int)iautoVacuum && aRoot[i]>1 ){ + checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0); + } +#endif + checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL); + } + + /* Make sure every page in the file is referenced + */ + for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ +#ifdef SQLITE_OMIT_AUTOVACUUM + if( getPageReferenced(&sCheck, i)==0 ){ + checkAppendMsg(&sCheck, 0, "Page %d is never used", i); + } +#else + /* If the database supports auto-vacuum, make sure no tables contain + ** references to pointer-map pages. + */ + if( getPageReferenced(&sCheck, i)==0 && + (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ + checkAppendMsg(&sCheck, 0, "Page %d is never used", i); + } + if( getPageReferenced(&sCheck, i)!=0 && + (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ + checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i); + } +#endif + } + + /* Make sure this analysis did not leave any unref() pages. + ** This is an internal consistency check; an integrity check + ** of the integrity check. + */ + if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){ + checkAppendMsg(&sCheck, 0, + "Outstanding page count goes from %d to %d during this analysis", + nRef, sqlite3PagerRefcount(pBt->pPager) + ); + } + + /* Clean up and report errors. + */ + sqlite3BtreeLeave(p); + sqlite3_free(sCheck.aPgRef); + if( sCheck.mallocFailed ){ + sqlite3StrAccumReset(&sCheck.errMsg); + *pnErr = sCheck.nErr+1; + return 0; + } + *pnErr = sCheck.nErr; + if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg); + return sqlite3StrAccumFinish(&sCheck.errMsg); +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +/* +** Return the full pathname of the underlying database file. Return +** an empty string if the database is in-memory or a TEMP database. +** +** The pager filename is invariant as long as the pager is +** open so it is safe to access without the BtShared mutex. +*/ +SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){ + assert( p->pBt->pPager!=0 ); + return sqlite3PagerFilename(p->pBt->pPager, 1); +} + +/* +** Return the pathname of the journal file for this database. The return +** value of this routine is the same regardless of whether the journal file +** has been created or not. +** +** The pager journal filename is invariant as long as the pager is +** open so it is safe to access without the BtShared mutex. +*/ +SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){ + assert( p->pBt->pPager!=0 ); + return sqlite3PagerJournalname(p->pBt->pPager); +} + +/* +** Return non-zero if a transaction is active. +*/ +SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){ + assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); + return (p && (p->inTrans==TRANS_WRITE)); +} + +#ifndef SQLITE_OMIT_WAL +/* +** Run a checkpoint on the Btree passed as the first argument. +** +** Return SQLITE_LOCKED if this or any other connection has an open +** transaction on the shared-cache the argument Btree is connected to. +** +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +*/ +SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ + int rc = SQLITE_OK; + if( p ){ + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); + if( pBt->inTransaction!=TRANS_NONE ){ + rc = SQLITE_LOCKED; + }else{ + rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt); + } + sqlite3BtreeLeave(p); + } + return rc; +} +#endif + +/* +** Return non-zero if a read (or write) transaction is active. +*/ +SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){ + assert( p ); + assert( sqlite3_mutex_held(p->db->mutex) ); + return p->inTrans!=TRANS_NONE; +} + +SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){ + assert( p ); + assert( sqlite3_mutex_held(p->db->mutex) ); + return p->nBackup!=0; +} + +/* +** This function returns a pointer to a blob of memory associated with +** a single shared-btree. The memory is used by client code for its own +** purposes (for example, to store a high-level schema associated with +** the shared-btree). The btree layer manages reference counting issues. +** +** The first time this is called on a shared-btree, nBytes bytes of memory +** are allocated, zeroed, and returned to the caller. For each subsequent +** call the nBytes parameter is ignored and a pointer to the same blob +** of memory returned. +** +** If the nBytes parameter is 0 and the blob of memory has not yet been +** allocated, a null pointer is returned. If the blob has already been +** allocated, it is returned as normal. +** +** Just before the shared-btree is closed, the function passed as the +** xFree argument when the memory allocation was made is invoked on the +** blob of allocated memory. The xFree function should not call sqlite3_free() +** on the memory, the btree layer does that. +*/ +SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); + if( !pBt->pSchema && nBytes ){ + pBt->pSchema = sqlite3DbMallocZero(0, nBytes); + pBt->xFreeSchema = xFree; + } + sqlite3BtreeLeave(p); + return pBt->pSchema; +} + +/* +** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared +** btree as the argument handle holds an exclusive lock on the +** sqlite_master table. Otherwise SQLITE_OK. +*/ +SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){ + int rc; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); + assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE ); + sqlite3BtreeLeave(p); + return rc; +} + + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** Obtain a lock on the table whose root page is iTab. The +** lock is a write lock if isWritelock is true or a read lock +** if it is false. +*/ +SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ + int rc = SQLITE_OK; + assert( p->inTrans!=TRANS_NONE ); + if( p->sharable ){ + u8 lockType = READ_LOCK + isWriteLock; + assert( READ_LOCK+1==WRITE_LOCK ); + assert( isWriteLock==0 || isWriteLock==1 ); + + sqlite3BtreeEnter(p); + rc = querySharedCacheTableLock(p, iTab, lockType); + if( rc==SQLITE_OK ){ + rc = setSharedCacheTableLock(p, iTab, lockType); + } + sqlite3BtreeLeave(p); + } + return rc; +} +#endif + +#ifndef SQLITE_OMIT_INCRBLOB +/* +** Argument pCsr must be a cursor opened for writing on an +** INTKEY table currently pointing at a valid table entry. +** This function modifies the data stored as part of that entry. +** +** Only the data content may only be modified, it is not possible to +** change the length of the data stored. If this function is called with +** parameters that attempt to write past the end of the existing data, +** no modifications are made and SQLITE_CORRUPT is returned. +*/ +SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ + int rc; + assert( cursorHoldsMutex(pCsr) ); + assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); + assert( pCsr->isIncrblobHandle ); + + rc = restoreCursorPosition(pCsr); + if( rc!=SQLITE_OK ){ + return rc; + } + assert( pCsr->eState!=CURSOR_REQUIRESEEK ); + if( pCsr->eState!=CURSOR_VALID ){ + return SQLITE_ABORT; + } + + /* Save the positions of all other cursors open on this table. This is + ** required in case any of them are holding references to an xFetch + ** version of the b-tree page modified by the accessPayload call below. + ** + ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition() + ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence + ** saveAllCursors can only return SQLITE_OK. + */ + VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); + assert( rc==SQLITE_OK ); + + /* Check some assumptions: + ** (a) the cursor is open for writing, + ** (b) there is a read/write transaction open, + ** (c) the connection holds a write-lock on the table (if required), + ** (d) there are no conflicting read-locks, and + ** (e) the cursor points at a valid row of an intKey table. + */ + if( !pCsr->wrFlag ){ + return SQLITE_READONLY; + } + assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0 + && pCsr->pBt->inTransaction==TRANS_WRITE ); + assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); + assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); + assert( pCsr->apPage[pCsr->iPage]->intKey ); + + return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); +} + +/* +** Set a flag on this cursor to cache the locations of pages from the +** overflow list for the current row. This is used by cursors opened +** for incremental blob IO only. +** +** This function sets a flag only. The actual page location cache +** (stored in BtCursor.aOverflow[]) is allocated and used by function +** accessPayload() (the worker function for sqlite3BtreeData() and +** sqlite3BtreePutData()). +*/ +SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + invalidateOverflowCache(pCur); + pCur->isIncrblobHandle = 1; +} +#endif + +/* +** Set both the "read version" (single byte at byte offset 18) and +** "write version" (single byte at byte offset 19) fields in the database +** header to iVersion. +*/ +SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ + BtShared *pBt = pBtree->pBt; + int rc; /* Return code */ + + assert( iVersion==1 || iVersion==2 ); + + /* If setting the version fields to 1, do not automatically open the + ** WAL connection, even if the version fields are currently set to 2. + */ + pBt->btsFlags &= ~BTS_NO_WAL; + if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; + + rc = sqlite3BtreeBeginTrans(pBtree, 0); + if( rc==SQLITE_OK ){ + u8 *aData = pBt->pPage1->aData; + if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ + rc = sqlite3BtreeBeginTrans(pBtree, 2); + if( rc==SQLITE_OK ){ + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + if( rc==SQLITE_OK ){ + aData[18] = (u8)iVersion; + aData[19] = (u8)iVersion; + } + } + } + } + + pBt->btsFlags &= ~BTS_NO_WAL; + return rc; +} + +/* +** set the mask of hint flags for cursor pCsr. Currently the only valid +** values are 0 and BTREE_BULKLOAD. +*/ +SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){ + assert( mask==BTREE_BULKLOAD || mask==0 ); + pCsr->hints = mask; +} + +/************** End of btree.c ***********************************************/ +/************** Begin file backup.c ******************************************/ +/* +** 2009 January 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the implementation of the sqlite3_backup_XXX() +** API functions and the related features. +*/ + +/* +** Structure allocated for each backup operation. +*/ +struct sqlite3_backup { + sqlite3* pDestDb; /* Destination database handle */ + Btree *pDest; /* Destination b-tree file */ + u32 iDestSchema; /* Original schema cookie in destination */ + int bDestLocked; /* True once a write-transaction is open on pDest */ + + Pgno iNext; /* Page number of the next source page to copy */ + sqlite3* pSrcDb; /* Source database handle */ + Btree *pSrc; /* Source b-tree file */ + + int rc; /* Backup process error code */ + + /* These two variables are set by every call to backup_step(). They are + ** read by calls to backup_remaining() and backup_pagecount(). + */ + Pgno nRemaining; /* Number of pages left to copy */ + Pgno nPagecount; /* Total number of pages to copy */ + + int isAttached; /* True once backup has been registered with pager */ + sqlite3_backup *pNext; /* Next backup associated with source pager */ +}; + +/* +** THREAD SAFETY NOTES: +** +** Once it has been created using backup_init(), a single sqlite3_backup +** structure may be accessed via two groups of thread-safe entry points: +** +** * Via the sqlite3_backup_XXX() API function backup_step() and +** backup_finish(). Both these functions obtain the source database +** handle mutex and the mutex associated with the source BtShared +** structure, in that order. +** +** * Via the BackupUpdate() and BackupRestart() functions, which are +** invoked by the pager layer to report various state changes in +** the page cache associated with the source database. The mutex +** associated with the source database BtShared structure will always +** be held when either of these functions are invoked. +** +** The other sqlite3_backup_XXX() API functions, backup_remaining() and +** backup_pagecount() are not thread-safe functions. If they are called +** while some other thread is calling backup_step() or backup_finish(), +** the values returned may be invalid. There is no way for a call to +** BackupUpdate() or BackupRestart() to interfere with backup_remaining() +** or backup_pagecount(). +** +** Depending on the SQLite configuration, the database handles and/or +** the Btree objects may have their own mutexes that require locking. +** Non-sharable Btrees (in-memory databases for example), do not have +** associated mutexes. +*/ + +/* +** Return a pointer corresponding to database zDb (i.e. "main", "temp") +** in connection handle pDb. If such a database cannot be found, return +** a NULL pointer and write an error message to pErrorDb. +** +** If the "temp" database is requested, it may need to be opened by this +** function. If an error occurs while doing so, return 0 and write an +** error message to pErrorDb. +*/ +static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ + int i = sqlite3FindDbName(pDb, zDb); + + if( i==1 ){ + Parse *pParse; + int rc = 0; + pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse)); + if( pParse==0 ){ + sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory"); + rc = SQLITE_NOMEM; + }else{ + pParse->db = pDb; + if( sqlite3OpenTempDatabase(pParse) ){ + sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg); + rc = SQLITE_ERROR; + } + sqlite3DbFree(pErrorDb, pParse->zErrMsg); + sqlite3StackFree(pErrorDb, pParse); + } + if( rc ){ + return 0; + } + } + + if( i<0 ){ + sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb); + return 0; + } + + return pDb->aDb[i].pBt; +} + +/* +** Attempt to set the page size of the destination to match the page size +** of the source. +*/ +static int setDestPgsz(sqlite3_backup *p){ + int rc; + rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0); + return rc; +} + +/* +** Create an sqlite3_backup process to copy the contents of zSrcDb from +** connection handle pSrcDb to zDestDb in pDestDb. If successful, return +** a pointer to the new sqlite3_backup object. +** +** If an error occurs, NULL is returned and an error code and error message +** stored in database handle pDestDb. +*/ +SQLITE_API sqlite3_backup *sqlite3_backup_init( + sqlite3* pDestDb, /* Database to write to */ + const char *zDestDb, /* Name of database within pDestDb */ + sqlite3* pSrcDb, /* Database connection to read from */ + const char *zSrcDb /* Name of database within pSrcDb */ +){ + sqlite3_backup *p; /* Value to return */ + + /* Lock the source database handle. The destination database + ** handle is not locked in this routine, but it is locked in + ** sqlite3_backup_step(). The user is required to ensure that no + ** other thread accesses the destination handle for the duration + ** of the backup operation. Any attempt to use the destination + ** database connection while a backup is in progress may cause + ** a malfunction or a deadlock. + */ + sqlite3_mutex_enter(pSrcDb->mutex); + sqlite3_mutex_enter(pDestDb->mutex); + + if( pSrcDb==pDestDb ){ + sqlite3Error( + pDestDb, SQLITE_ERROR, "source and destination must be distinct" + ); + p = 0; + }else { + /* Allocate space for a new sqlite3_backup object... + ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a + ** call to sqlite3_backup_init() and is destroyed by a call to + ** sqlite3_backup_finish(). */ + p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup)); + if( !p ){ + sqlite3Error(pDestDb, SQLITE_NOMEM, 0); + } + } + + /* If the allocation succeeded, populate the new object. */ + if( p ){ + p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb); + p->pDest = findBtree(pDestDb, pDestDb, zDestDb); + p->pDestDb = pDestDb; + p->pSrcDb = pSrcDb; + p->iNext = 1; + p->isAttached = 0; + + if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){ + /* One (or both) of the named databases did not exist or an OOM + ** error was hit. The error has already been written into the + ** pDestDb handle. All that is left to do here is free the + ** sqlite3_backup structure. + */ + sqlite3_free(p); + p = 0; + } + } + if( p ){ + p->pSrc->nBackup++; + } + + sqlite3_mutex_leave(pDestDb->mutex); + sqlite3_mutex_leave(pSrcDb->mutex); + return p; +} + +/* +** Argument rc is an SQLite error code. Return true if this error is +** considered fatal if encountered during a backup operation. All errors +** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED. +*/ +static int isFatalError(int rc){ + return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED)); +} + +/* +** Parameter zSrcData points to a buffer containing the data for +** page iSrcPg from the source database. Copy this data into the +** destination database. +*/ +static int backupOnePage( + sqlite3_backup *p, /* Backup handle */ + Pgno iSrcPg, /* Source database page to backup */ + const u8 *zSrcData, /* Source database page data */ + int bUpdate /* True for an update, false otherwise */ +){ + Pager * const pDestPager = sqlite3BtreePager(p->pDest); + const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc); + int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest); + const int nCopy = MIN(nSrcPgsz, nDestPgsz); + const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz; +#ifdef SQLITE_HAS_CODEC + /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is + ** guaranteed that the shared-mutex is held by this thread, handle + ** p->pSrc may not actually be the owner. */ + int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc); + int nDestReserve = sqlite3BtreeGetReserve(p->pDest); +#endif + int rc = SQLITE_OK; + i64 iOff; + + assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 ); + assert( p->bDestLocked ); + assert( !isFatalError(p->rc) ); + assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ); + assert( zSrcData ); + + /* Catch the case where the destination is an in-memory database and the + ** page sizes of the source and destination differ. + */ + if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){ + rc = SQLITE_READONLY; + } + +#ifdef SQLITE_HAS_CODEC + /* Backup is not possible if the page size of the destination is changing + ** and a codec is in use. + */ + if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){ + rc = SQLITE_READONLY; + } + + /* Backup is not possible if the number of bytes of reserve space differ + ** between source and destination. If there is a difference, try to + ** fix the destination to agree with the source. If that is not possible, + ** then the backup cannot proceed. + */ + if( nSrcReserve!=nDestReserve ){ + u32 newPgsz = nSrcPgsz; + rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve); + if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY; + } +#endif + + /* This loop runs once for each destination page spanned by the source + ** page. For each iteration, variable iOff is set to the byte offset + ** of the destination page. + */ + for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOffpDest->pBt) ) continue; + if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg)) + && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg)) + ){ + const u8 *zIn = &zSrcData[iOff%nSrcPgsz]; + u8 *zDestData = sqlite3PagerGetData(pDestPg); + u8 *zOut = &zDestData[iOff%nDestPgsz]; + + /* Copy the data from the source page into the destination page. + ** Then clear the Btree layer MemPage.isInit flag. Both this module + ** and the pager code use this trick (clearing the first byte + ** of the page 'extra' space to invalidate the Btree layers + ** cached parse of the page). MemPage.isInit is marked + ** "MUST BE FIRST" for this purpose. + */ + memcpy(zOut, zIn, nCopy); + ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0; + if( iOff==0 && bUpdate==0 ){ + sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc)); + } + } + sqlite3PagerUnref(pDestPg); + } + + return rc; +} + +/* +** If pFile is currently larger than iSize bytes, then truncate it to +** exactly iSize bytes. If pFile is not larger than iSize bytes, then +** this function is a no-op. +** +** Return SQLITE_OK if everything is successful, or an SQLite error +** code if an error occurs. +*/ +static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){ + i64 iCurrent; + int rc = sqlite3OsFileSize(pFile, &iCurrent); + if( rc==SQLITE_OK && iCurrent>iSize ){ + rc = sqlite3OsTruncate(pFile, iSize); + } + return rc; +} + +/* +** Register this backup object with the associated source pager for +** callbacks when pages are changed or the cache invalidated. +*/ +static void attachBackupObject(sqlite3_backup *p){ + sqlite3_backup **pp; + assert( sqlite3BtreeHoldsMutex(p->pSrc) ); + pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); + p->pNext = *pp; + *pp = p; + p->isAttached = 1; +} + +/* +** Copy nPage pages from the source b-tree to the destination. +*/ +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ + int rc; + int destMode; /* Destination journal mode */ + int pgszSrc = 0; /* Source page size */ + int pgszDest = 0; /* Destination page size */ + + sqlite3_mutex_enter(p->pSrcDb->mutex); + sqlite3BtreeEnter(p->pSrc); + if( p->pDestDb ){ + sqlite3_mutex_enter(p->pDestDb->mutex); + } + + rc = p->rc; + if( !isFatalError(rc) ){ + Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */ + Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */ + int ii; /* Iterator variable */ + int nSrcPage = -1; /* Size of source db in pages */ + int bCloseTrans = 0; /* True if src db requires unlocking */ + + /* If the source pager is currently in a write-transaction, return + ** SQLITE_BUSY immediately. + */ + if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){ + rc = SQLITE_BUSY; + }else{ + rc = SQLITE_OK; + } + + /* Lock the destination database, if it is not locked already. */ + if( SQLITE_OK==rc && p->bDestLocked==0 + && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) + ){ + p->bDestLocked = 1; + sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema); + } + + /* If there is no open read-transaction on the source database, open + ** one now. If a transaction is opened here, then it will be closed + ** before this function exits. + */ + if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){ + rc = sqlite3BtreeBeginTrans(p->pSrc, 0); + bCloseTrans = 1; + } + + /* Do not allow backup if the destination database is in WAL mode + ** and the page sizes are different between source and destination */ + pgszSrc = sqlite3BtreeGetPageSize(p->pSrc); + pgszDest = sqlite3BtreeGetPageSize(p->pDest); + destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest)); + if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){ + rc = SQLITE_READONLY; + } + + /* Now that there is a read-lock on the source database, query the + ** source pager for the number of pages in the database. + */ + nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc); + assert( nSrcPage>=0 ); + for(ii=0; (nPage<0 || iiiNext<=(Pgno)nSrcPage && !rc; ii++){ + const Pgno iSrcPg = p->iNext; /* Source page number */ + if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){ + DbPage *pSrcPg; /* Source page object */ + rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg, + PAGER_GET_READONLY); + if( rc==SQLITE_OK ){ + rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0); + sqlite3PagerUnref(pSrcPg); + } + } + p->iNext++; + } + if( rc==SQLITE_OK ){ + p->nPagecount = nSrcPage; + p->nRemaining = nSrcPage+1-p->iNext; + if( p->iNext>(Pgno)nSrcPage ){ + rc = SQLITE_DONE; + }else if( !p->isAttached ){ + attachBackupObject(p); + } + } + + /* Update the schema version field in the destination database. This + ** is to make sure that the schema-version really does change in + ** the case where the source and destination databases have the + ** same schema version. + */ + if( rc==SQLITE_DONE ){ + if( nSrcPage==0 ){ + rc = sqlite3BtreeNewDb(p->pDest); + nSrcPage = 1; + } + if( rc==SQLITE_OK || rc==SQLITE_DONE ){ + rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1); + } + if( rc==SQLITE_OK ){ + if( p->pDestDb ){ + sqlite3ResetAllSchemasOfConnection(p->pDestDb); + } + if( destMode==PAGER_JOURNALMODE_WAL ){ + rc = sqlite3BtreeSetVersion(p->pDest, 2); + } + } + if( rc==SQLITE_OK ){ + int nDestTruncate; + /* Set nDestTruncate to the final number of pages in the destination + ** database. The complication here is that the destination page + ** size may be different to the source page size. + ** + ** If the source page size is smaller than the destination page size, + ** round up. In this case the call to sqlite3OsTruncate() below will + ** fix the size of the file. However it is important to call + ** sqlite3PagerTruncateImage() here so that any pages in the + ** destination file that lie beyond the nDestTruncate page mark are + ** journalled by PagerCommitPhaseOne() before they are destroyed + ** by the file truncation. + */ + assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) ); + assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) ); + if( pgszSrcpDest->pBt) ){ + nDestTruncate--; + } + }else{ + nDestTruncate = nSrcPage * (pgszSrc/pgszDest); + } + assert( nDestTruncate>0 ); + + if( pgszSrc= iSize || ( + nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1) + && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest + )); + + /* This block ensures that all data required to recreate the original + ** database has been stored in the journal for pDestPager and the + ** journal synced to disk. So at this point we may safely modify + ** the database file in any way, knowing that if a power failure + ** occurs, the original database will be reconstructed from the + ** journal file. */ + sqlite3PagerPagecount(pDestPager, &nDstPage); + for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){ + if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){ + DbPage *pPg; + rc = sqlite3PagerGet(pDestPager, iPg, &pPg); + if( rc==SQLITE_OK ){ + rc = sqlite3PagerWrite(pPg); + sqlite3PagerUnref(pPg); + } + } + } + if( rc==SQLITE_OK ){ + rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1); + } + + /* Write the extra pages and truncate the database file as required */ + iEnd = MIN(PENDING_BYTE + pgszDest, iSize); + for( + iOff=PENDING_BYTE+pgszSrc; + rc==SQLITE_OK && iOffpDest, 0)) + ){ + rc = SQLITE_DONE; + } + } + } + + /* If bCloseTrans is true, then this function opened a read transaction + ** on the source database. Close the read transaction here. There is + ** no need to check the return values of the btree methods here, as + ** "committing" a read-only transaction cannot fail. + */ + if( bCloseTrans ){ + TESTONLY( int rc2 ); + TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0); + TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0); + assert( rc2==SQLITE_OK ); + } + + if( rc==SQLITE_IOERR_NOMEM ){ + rc = SQLITE_NOMEM; + } + p->rc = rc; + } + if( p->pDestDb ){ + sqlite3_mutex_leave(p->pDestDb->mutex); + } + sqlite3BtreeLeave(p->pSrc); + sqlite3_mutex_leave(p->pSrcDb->mutex); + return rc; +} + +/* +** Release all resources associated with an sqlite3_backup* handle. +*/ +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){ + sqlite3_backup **pp; /* Ptr to head of pagers backup list */ + sqlite3 *pSrcDb; /* Source database connection */ + int rc; /* Value to return */ + + /* Enter the mutexes */ + if( p==0 ) return SQLITE_OK; + pSrcDb = p->pSrcDb; + sqlite3_mutex_enter(pSrcDb->mutex); + sqlite3BtreeEnter(p->pSrc); + if( p->pDestDb ){ + sqlite3_mutex_enter(p->pDestDb->mutex); + } + + /* Detach this backup from the source pager. */ + if( p->pDestDb ){ + p->pSrc->nBackup--; + } + if( p->isAttached ){ + pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); + while( *pp!=p ){ + pp = &(*pp)->pNext; + } + *pp = p->pNext; + } + + /* If a transaction is still open on the Btree, roll it back. */ + sqlite3BtreeRollback(p->pDest, SQLITE_OK); + + /* Set the error code of the destination database handle. */ + rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc; + sqlite3Error(p->pDestDb, rc, 0); + + /* Exit the mutexes and free the backup context structure. */ + if( p->pDestDb ){ + sqlite3LeaveMutexAndCloseZombie(p->pDestDb); + } + sqlite3BtreeLeave(p->pSrc); + if( p->pDestDb ){ + /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a + ** call to sqlite3_backup_init() and is destroyed by a call to + ** sqlite3_backup_finish(). */ + sqlite3_free(p); + } + sqlite3LeaveMutexAndCloseZombie(pSrcDb); + return rc; +} + +/* +** Return the number of pages still to be backed up as of the most recent +** call to sqlite3_backup_step(). +*/ +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){ + return p->nRemaining; +} + +/* +** Return the total number of pages in the source database as of the most +** recent call to sqlite3_backup_step(). +*/ +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){ + return p->nPagecount; +} + +/* +** This function is called after the contents of page iPage of the +** source database have been modified. If page iPage has already been +** copied into the destination database, then the data written to the +** destination is now invalidated. The destination copy of iPage needs +** to be updated with the new data before the backup operation is +** complete. +** +** It is assumed that the mutex associated with the BtShared object +** corresponding to the source database is held when this function is +** called. +*/ +SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){ + sqlite3_backup *p; /* Iterator variable */ + for(p=pBackup; p; p=p->pNext){ + assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); + if( !isFatalError(p->rc) && iPageiNext ){ + /* The backup process p has already copied page iPage. But now it + ** has been modified by a transaction on the source pager. Copy + ** the new data into the backup. + */ + int rc; + assert( p->pDestDb ); + sqlite3_mutex_enter(p->pDestDb->mutex); + rc = backupOnePage(p, iPage, aData, 1); + sqlite3_mutex_leave(p->pDestDb->mutex); + assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED ); + if( rc!=SQLITE_OK ){ + p->rc = rc; + } + } + } +} + +/* +** Restart the backup process. This is called when the pager layer +** detects that the database has been modified by an external database +** connection. In this case there is no way of knowing which of the +** pages that have been copied into the destination database are still +** valid and which are not, so the entire process needs to be restarted. +** +** It is assumed that the mutex associated with the BtShared object +** corresponding to the source database is held when this function is +** called. +*/ +SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){ + sqlite3_backup *p; /* Iterator variable */ + for(p=pBackup; p; p=p->pNext){ + assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); + p->iNext = 1; + } +} + +#ifndef SQLITE_OMIT_VACUUM +/* +** Copy the complete content of pBtFrom into pBtTo. A transaction +** must be active for both files. +** +** The size of file pTo may be reduced by this operation. If anything +** goes wrong, the transaction on pTo is rolled back. If successful, the +** transaction is committed before returning. +*/ +SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){ + int rc; + sqlite3_file *pFd; /* File descriptor for database pTo */ + sqlite3_backup b; + sqlite3BtreeEnter(pTo); + sqlite3BtreeEnter(pFrom); + + assert( sqlite3BtreeIsInTrans(pTo) ); + pFd = sqlite3PagerFile(sqlite3BtreePager(pTo)); + if( pFd->pMethods ){ + i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom); + rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte); + if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; + if( rc ) goto copy_finished; + } + + /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set + ** to 0. This is used by the implementations of sqlite3_backup_step() + ** and sqlite3_backup_finish() to detect that they are being called + ** from this function, not directly by the user. + */ + memset(&b, 0, sizeof(b)); + b.pSrcDb = pFrom->db; + b.pSrc = pFrom; + b.pDest = pTo; + b.iNext = 1; + + /* 0x7FFFFFFF is the hard limit for the number of pages in a database + ** file. By passing this as the number of pages to copy to + ** sqlite3_backup_step(), we can guarantee that the copy finishes + ** within a single call (unless an error occurs). The assert() statement + ** checks this assumption - (p->rc) should be set to either SQLITE_DONE + ** or an error code. + */ + sqlite3_backup_step(&b, 0x7FFFFFFF); + assert( b.rc!=SQLITE_OK ); + rc = sqlite3_backup_finish(&b); + if( rc==SQLITE_OK ){ + pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; + }else{ + sqlite3PagerClearCache(sqlite3BtreePager(b.pDest)); + } + + assert( sqlite3BtreeIsInTrans(pTo)==0 ); +copy_finished: + sqlite3BtreeLeave(pFrom); + sqlite3BtreeLeave(pTo); + return rc; +} +#endif /* SQLITE_OMIT_VACUUM */ + +/************** End of backup.c **********************************************/ +/************** Begin file vdbemem.c *****************************************/ +/* +** 2004 May 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code use to manipulate "Mem" structure. A "Mem" +** stores a single value in the VDBE. Mem is an opaque structure visible +** only within the VDBE. Interface routines refer to a Mem using the +** name sqlite_value +*/ + +/* +** If pMem is an object with a valid string representation, this routine +** ensures the internal encoding for the string representation is +** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE. +** +** If pMem is not a string object, or the encoding of the string +** representation is already stored using the requested encoding, then this +** routine is a no-op. +** +** SQLITE_OK is returned if the conversion is successful (or not required). +** SQLITE_NOMEM may be returned if a malloc() fails during conversion +** between formats. +*/ +SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){ +#ifndef SQLITE_OMIT_UTF16 + int rc; +#endif + assert( (pMem->flags&MEM_RowSet)==0 ); + assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE + || desiredEnc==SQLITE_UTF16BE ); + if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){ + return SQLITE_OK; + } + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); +#ifdef SQLITE_OMIT_UTF16 + return SQLITE_ERROR; +#else + + /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned, + ** then the encoding of the value may not have changed. + */ + rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc); + assert(rc==SQLITE_OK || rc==SQLITE_NOMEM); + assert(rc==SQLITE_OK || pMem->enc!=desiredEnc); + assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc); + return rc; +#endif +} + +/* +** Make sure pMem->z points to a writable allocation of at least +** n bytes. +** +** If the third argument passed to this function is true, then memory +** cell pMem must contain a string or blob. In this case the content is +** preserved. Otherwise, if the third parameter to this function is false, +** any current string or blob value may be discarded. +** +** This function sets the MEM_Dyn flag and clears any xDel callback. +** It also clears MEM_Ephem and MEM_Static. If the preserve flag is +** not set, Mem.n is zeroed. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){ + assert( 1 >= + ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) + + (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + + ((pMem->flags&MEM_Ephem) ? 1 : 0) + + ((pMem->flags&MEM_Static) ? 1 : 0) + ); + assert( (pMem->flags&MEM_RowSet)==0 ); + + /* If the preserve flag is set to true, then the memory cell must already + ** contain a valid string or blob value. */ + assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) ); + + if( n<32 ) n = 32; + if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)z==pMem->zMalloc ){ + pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n); + preserve = 0; + }else{ + sqlite3DbFree(pMem->db, pMem->zMalloc); + pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n); + } + } + + if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){ + memcpy(pMem->zMalloc, pMem->z, pMem->n); + } + if( pMem->flags&MEM_Dyn && pMem->xDel ){ + assert( pMem->xDel!=SQLITE_DYNAMIC ); + pMem->xDel((void *)(pMem->z)); + } + + pMem->z = pMem->zMalloc; + if( pMem->z==0 ){ + pMem->flags = MEM_Null; + }else{ + pMem->flags &= ~(MEM_Ephem|MEM_Static); + } + pMem->xDel = 0; + return (pMem->z ? SQLITE_OK : SQLITE_NOMEM); +} + +/* +** Make the given Mem object MEM_Dyn. In other words, make it so +** that any TEXT or BLOB content is stored in memory obtained from +** malloc(). In this way, we know that the memory is safe to be +** overwritten or altered. +** +** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){ + int f; + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( (pMem->flags&MEM_RowSet)==0 ); + ExpandBlob(pMem); + f = pMem->flags; + if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){ + if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){ + return SQLITE_NOMEM; + } + pMem->z[pMem->n] = 0; + pMem->z[pMem->n+1] = 0; + pMem->flags |= MEM_Term; +#ifdef SQLITE_DEBUG + pMem->pScopyFrom = 0; +#endif + } + + return SQLITE_OK; +} + +/* +** If the given Mem* has a zero-filled tail, turn it into an ordinary +** blob stored in dynamically allocated space. +*/ +#ifndef SQLITE_OMIT_INCRBLOB +SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){ + if( pMem->flags & MEM_Zero ){ + int nByte; + assert( pMem->flags&MEM_Blob ); + assert( (pMem->flags&MEM_RowSet)==0 ); + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + + /* Set nByte to the number of bytes required to store the expanded blob. */ + nByte = pMem->n + pMem->u.nZero; + if( nByte<=0 ){ + nByte = 1; + } + if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){ + return SQLITE_NOMEM; + } + + memset(&pMem->z[pMem->n], 0, pMem->u.nZero); + pMem->n += pMem->u.nZero; + pMem->flags &= ~(MEM_Zero|MEM_Term); + } + return SQLITE_OK; +} +#endif + + +/* +** Make sure the given Mem is \u0000 terminated. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){ + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){ + return SQLITE_OK; /* Nothing to do */ + } + if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){ + return SQLITE_NOMEM; + } + pMem->z[pMem->n] = 0; + pMem->z[pMem->n+1] = 0; + pMem->flags |= MEM_Term; + return SQLITE_OK; +} + +/* +** Add MEM_Str to the set of representations for the given Mem. Numbers +** are converted using sqlite3_snprintf(). Converting a BLOB to a string +** is a no-op. +** +** Existing representations MEM_Int and MEM_Real are *not* invalidated. +** +** A MEM_Null value will never be passed to this function. This function is +** used for converting values to text for returning to the user (i.e. via +** sqlite3_value_text()), or for ensuring that values to be used as btree +** keys are strings. In the former case a NULL pointer is returned the +** user and the later is an internal programming error. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){ + int rc = SQLITE_OK; + int fg = pMem->flags; + const int nByte = 32; + + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( !(fg&MEM_Zero) ); + assert( !(fg&(MEM_Str|MEM_Blob)) ); + assert( fg&(MEM_Int|MEM_Real) ); + assert( (pMem->flags&MEM_RowSet)==0 ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + + + if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){ + return SQLITE_NOMEM; + } + + /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8 + ** string representation of the value. Then, if the required encoding + ** is UTF-16le or UTF-16be do a translation. + ** + ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16. + */ + if( fg & MEM_Int ){ + sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i); + }else{ + assert( fg & MEM_Real ); + sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r); + } + pMem->n = sqlite3Strlen30(pMem->z); + pMem->enc = SQLITE_UTF8; + pMem->flags |= MEM_Str|MEM_Term; + sqlite3VdbeChangeEncoding(pMem, enc); + return rc; +} + +/* +** Memory cell pMem contains the context of an aggregate function. +** This routine calls the finalize method for that function. The +** result of the aggregate is stored back into pMem. +** +** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK +** otherwise. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){ + int rc = SQLITE_OK; + if( ALWAYS(pFunc && pFunc->xFinalize) ){ + sqlite3_context ctx; + assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef ); + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + memset(&ctx, 0, sizeof(ctx)); + ctx.s.flags = MEM_Null; + ctx.s.db = pMem->db; + ctx.pMem = pMem; + ctx.pFunc = pFunc; + pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */ + assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel ); + sqlite3DbFree(pMem->db, pMem->zMalloc); + memcpy(pMem, &ctx.s, sizeof(ctx.s)); + rc = ctx.isError; + } + return rc; +} + +/* +** If the memory cell contains a string value that must be freed by +** invoking an external callback, free it now. Calling this function +** does not free any Mem.zMalloc buffer. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){ + assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) ); + if( p->flags&MEM_Agg ){ + sqlite3VdbeMemFinalize(p, p->u.pDef); + assert( (p->flags & MEM_Agg)==0 ); + sqlite3VdbeMemRelease(p); + }else if( p->flags&MEM_Dyn && p->xDel ){ + assert( (p->flags&MEM_RowSet)==0 ); + assert( p->xDel!=SQLITE_DYNAMIC ); + p->xDel((void *)p->z); + p->xDel = 0; + }else if( p->flags&MEM_RowSet ){ + sqlite3RowSetClear(p->u.pRowSet); + }else if( p->flags&MEM_Frame ){ + sqlite3VdbeMemSetNull(p); + } +} + +/* +** Release any memory held by the Mem. This may leave the Mem in an +** inconsistent state, for example with (Mem.z==0) and +** (Mem.type==SQLITE_TEXT). +*/ +SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){ + VdbeMemRelease(p); + sqlite3DbFree(p->db, p->zMalloc); + p->z = 0; + p->zMalloc = 0; + p->xDel = 0; +} + +/* +** Convert a 64-bit IEEE double into a 64-bit signed integer. +** If the double is too large, return 0x8000000000000000. +** +** Most systems appear to do this simply by assigning +** variables and without the extra range tests. But +** there are reports that windows throws an expection +** if the floating point value is out of range. (See ticket #2880.) +** Because we do not completely understand the problem, we will +** take the conservative approach and always do range tests +** before attempting the conversion. +*/ +static i64 doubleToInt64(double r){ +#ifdef SQLITE_OMIT_FLOATING_POINT + /* When floating-point is omitted, double and int64 are the same thing */ + return r; +#else + /* + ** Many compilers we encounter do not define constants for the + ** minimum and maximum 64-bit integers, or they define them + ** inconsistently. And many do not understand the "LL" notation. + ** So we define our own static constants here using nothing + ** larger than a 32-bit integer constant. + */ + static const i64 maxInt = LARGEST_INT64; + static const i64 minInt = SMALLEST_INT64; + + if( r<(double)minInt ){ + return minInt; + }else if( r>(double)maxInt ){ + /* minInt is correct here - not maxInt. It turns out that assigning + ** a very large positive number to an integer results in a very large + ** negative integer. This makes no sense, but it is what x86 hardware + ** does so for compatibility we will do the same in software. */ + return minInt; + }else{ + return (i64)r; + } +#endif +} + +/* +** Return some kind of integer value which is the best we can do +** at representing the value that *pMem describes as an integer. +** If pMem is an integer, then the value is exact. If pMem is +** a floating-point then the value returned is the integer part. +** If pMem is a string or blob, then we make an attempt to convert +** it into a integer and return that. If pMem represents an +** an SQL-NULL value, return 0. +** +** If pMem represents a string value, its encoding might be changed. +*/ +SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){ + int flags; + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + flags = pMem->flags; + if( flags & MEM_Int ){ + return pMem->u.i; + }else if( flags & MEM_Real ){ + return doubleToInt64(pMem->r); + }else if( flags & (MEM_Str|MEM_Blob) ){ + i64 value = 0; + assert( pMem->z || pMem->n==0 ); + testcase( pMem->z==0 ); + sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc); + return value; + }else{ + return 0; + } +} + +/* +** Return the best representation of pMem that we can get into a +** double. If pMem is already a double or an integer, return its +** value. If it is a string or blob, try to convert it to a double. +** If it is a NULL, return 0.0. +*/ +SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){ + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + if( pMem->flags & MEM_Real ){ + return pMem->r; + }else if( pMem->flags & MEM_Int ){ + return (double)pMem->u.i; + }else if( pMem->flags & (MEM_Str|MEM_Blob) ){ + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + double val = (double)0; + sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc); + return val; + }else{ + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + return (double)0; + } +} + +/* +** The MEM structure is already a MEM_Real. Try to also make it a +** MEM_Int if we can. +*/ +SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){ + assert( pMem->flags & MEM_Real ); + assert( (pMem->flags & MEM_RowSet)==0 ); + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + + pMem->u.i = doubleToInt64(pMem->r); + + /* Only mark the value as an integer if + ** + ** (1) the round-trip conversion real->int->real is a no-op, and + ** (2) The integer is neither the largest nor the smallest + ** possible integer (ticket #3922) + ** + ** The second and third terms in the following conditional enforces + ** the second condition under the assumption that addition overflow causes + ** values to wrap around. On x86 hardware, the third term is always + ** true and could be omitted. But we leave it in because other + ** architectures might behave differently. + */ + if( pMem->r==(double)pMem->u.i + && pMem->u.i>SMALLEST_INT64 +#if defined(__i486__) || defined(__x86_64__) + && ALWAYS(pMem->u.iu.iflags |= MEM_Int; + } +} + +/* +** Convert pMem to type integer. Invalidate any prior representations. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){ + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( (pMem->flags & MEM_RowSet)==0 ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + + pMem->u.i = sqlite3VdbeIntValue(pMem); + MemSetTypeFlag(pMem, MEM_Int); + return SQLITE_OK; +} + +/* +** Convert pMem so that it is of type MEM_Real. +** Invalidate any prior representations. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){ + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + + pMem->r = sqlite3VdbeRealValue(pMem); + MemSetTypeFlag(pMem, MEM_Real); + return SQLITE_OK; +} + +/* +** Convert pMem so that it has types MEM_Real or MEM_Int or both. +** Invalidate any prior representations. +** +** Every effort is made to force the conversion, even if the input +** is a string that does not look completely like a number. Convert +** as much of the string as we can and ignore the rest. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){ + if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){ + assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){ + MemSetTypeFlag(pMem, MEM_Int); + }else{ + pMem->r = sqlite3VdbeRealValue(pMem); + MemSetTypeFlag(pMem, MEM_Real); + sqlite3VdbeIntegerAffinity(pMem); + } + } + assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 ); + pMem->flags &= ~(MEM_Str|MEM_Blob); + return SQLITE_OK; +} + +/* +** Delete any previous value and set the value stored in *pMem to NULL. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){ + if( pMem->flags & MEM_Frame ){ + VdbeFrame *pFrame = pMem->u.pFrame; + pFrame->pParent = pFrame->v->pDelFrame; + pFrame->v->pDelFrame = pFrame; + } + if( pMem->flags & MEM_RowSet ){ + sqlite3RowSetClear(pMem->u.pRowSet); + } + MemSetTypeFlag(pMem, MEM_Null); + pMem->type = SQLITE_NULL; +} + +/* +** Delete any previous value and set the value to be a BLOB of length +** n containing all zeros. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){ + sqlite3VdbeMemRelease(pMem); + pMem->flags = MEM_Blob|MEM_Zero; + pMem->type = SQLITE_BLOB; + pMem->n = 0; + if( n<0 ) n = 0; + pMem->u.nZero = n; + pMem->enc = SQLITE_UTF8; + +#ifdef SQLITE_OMIT_INCRBLOB + sqlite3VdbeMemGrow(pMem, n, 0); + if( pMem->z ){ + pMem->n = n; + memset(pMem->z, 0, n); + } +#endif +} + +/* +** Delete any previous value and set the value stored in *pMem to val, +** manifest type INTEGER. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ + sqlite3VdbeMemRelease(pMem); + pMem->u.i = val; + pMem->flags = MEM_Int; + pMem->type = SQLITE_INTEGER; +} + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* +** Delete any previous value and set the value stored in *pMem to val, +** manifest type REAL. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){ + if( sqlite3IsNaN(val) ){ + sqlite3VdbeMemSetNull(pMem); + }else{ + sqlite3VdbeMemRelease(pMem); + pMem->r = val; + pMem->flags = MEM_Real; + pMem->type = SQLITE_FLOAT; + } +} +#endif + +/* +** Delete any previous value and set the value of pMem to be an +** empty boolean index. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){ + sqlite3 *db = pMem->db; + assert( db!=0 ); + assert( (pMem->flags & MEM_RowSet)==0 ); + sqlite3VdbeMemRelease(pMem); + pMem->zMalloc = sqlite3DbMallocRaw(db, 64); + if( db->mallocFailed ){ + pMem->flags = MEM_Null; + }else{ + assert( pMem->zMalloc ); + pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, + sqlite3DbMallocSize(db, pMem->zMalloc)); + assert( pMem->u.pRowSet!=0 ); + pMem->flags = MEM_RowSet; + } +} + +/* +** Return true if the Mem object contains a TEXT or BLOB that is +** too large - whose size exceeds SQLITE_MAX_LENGTH. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){ + assert( p->db!=0 ); + if( p->flags & (MEM_Str|MEM_Blob) ){ + int n = p->n; + if( p->flags & MEM_Zero ){ + n += p->u.nZero; + } + return n>p->db->aLimit[SQLITE_LIMIT_LENGTH]; + } + return 0; +} + +#ifdef SQLITE_DEBUG +/* +** This routine prepares a memory cell for modication by breaking +** its link to a shallow copy and by marking any current shallow +** copies of this cell as invalid. +** +** This is used for testing and debugging only - to make sure shallow +** copies are not misused. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ + int i; + Mem *pX; + for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){ + if( pX->pScopyFrom==pMem ){ + pX->flags |= MEM_Invalid; + pX->pScopyFrom = 0; + } + } + pMem->pScopyFrom = 0; +} +#endif /* SQLITE_DEBUG */ + +/* +** Size of struct Mem not including the Mem.zMalloc member. +*/ +#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc)) + +/* +** Make an shallow copy of pFrom into pTo. Prior contents of +** pTo are freed. The pFrom->z field is not duplicated. If +** pFrom->z is used, then pTo->z points to the same thing as pFrom->z +** and flags gets srcType (either MEM_Ephem or MEM_Static). +*/ +SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){ + assert( (pFrom->flags & MEM_RowSet)==0 ); + VdbeMemRelease(pTo); + memcpy(pTo, pFrom, MEMCELLSIZE); + pTo->xDel = 0; + if( (pFrom->flags&MEM_Static)==0 ){ + pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem); + assert( srcType==MEM_Ephem || srcType==MEM_Static ); + pTo->flags |= srcType; + } +} + +/* +** Make a full copy of pFrom into pTo. Prior contents of pTo are +** freed before the copy is made. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ + int rc = SQLITE_OK; + + assert( (pFrom->flags & MEM_RowSet)==0 ); + VdbeMemRelease(pTo); + memcpy(pTo, pFrom, MEMCELLSIZE); + pTo->flags &= ~MEM_Dyn; + + if( pTo->flags&(MEM_Str|MEM_Blob) ){ + if( 0==(pFrom->flags&MEM_Static) ){ + pTo->flags |= MEM_Ephem; + rc = sqlite3VdbeMemMakeWriteable(pTo); + } + } + + return rc; +} + +/* +** Transfer the contents of pFrom to pTo. Any existing value in pTo is +** freed. If pFrom contains ephemeral data, a copy is made. +** +** pFrom contains an SQL NULL when this routine returns. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ + assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) ); + assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) ); + assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db ); + + sqlite3VdbeMemRelease(pTo); + memcpy(pTo, pFrom, sizeof(Mem)); + pFrom->flags = MEM_Null; + pFrom->xDel = 0; + pFrom->zMalloc = 0; +} + +/* +** Change the value of a Mem to be a string or a BLOB. +** +** The memory management strategy depends on the value of the xDel +** parameter. If the value passed is SQLITE_TRANSIENT, then the +** string is copied into a (possibly existing) buffer managed by the +** Mem structure. Otherwise, any existing buffer is freed and the +** pointer copied. +** +** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH +** size limit) then no memory allocation occurs. If the string can be +** stored without allocating memory, then it is. If a memory allocation +** is required to store the string, then value of pMem is unchanged. In +** either case, SQLITE_TOOBIG is returned. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemSetStr( + Mem *pMem, /* Memory cell to set to string value */ + const char *z, /* String pointer */ + int n, /* Bytes in string, or negative */ + u8 enc, /* Encoding of z. 0 for BLOBs */ + void (*xDel)(void*) /* Destructor function */ +){ + int nByte = n; /* New value for pMem->n */ + int iLimit; /* Maximum allowed string or blob size */ + u16 flags = 0; /* New value for pMem->flags */ + + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( (pMem->flags & MEM_RowSet)==0 ); + + /* If z is a NULL pointer, set pMem to contain an SQL NULL. */ + if( !z ){ + sqlite3VdbeMemSetNull(pMem); + return SQLITE_OK; + } + + if( pMem->db ){ + iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH]; + }else{ + iLimit = SQLITE_MAX_LENGTH; + } + flags = (enc==0?MEM_Blob:MEM_Str); + if( nByte<0 ){ + assert( enc!=0 ); + if( enc==SQLITE_UTF8 ){ + for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){} + }else{ + for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){} + } + flags |= MEM_Term; + } + + /* The following block sets the new values of Mem.z and Mem.xDel. It + ** also sets a flag in local variable "flags" to indicate the memory + ** management (one of MEM_Dyn or MEM_Static). + */ + if( xDel==SQLITE_TRANSIENT ){ + int nAlloc = nByte; + if( flags&MEM_Term ){ + nAlloc += (enc==SQLITE_UTF8?1:2); + } + if( nByte>iLimit ){ + return SQLITE_TOOBIG; + } + if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){ + return SQLITE_NOMEM; + } + memcpy(pMem->z, z, nAlloc); + }else if( xDel==SQLITE_DYNAMIC ){ + sqlite3VdbeMemRelease(pMem); + pMem->zMalloc = pMem->z = (char *)z; + pMem->xDel = 0; + }else{ + sqlite3VdbeMemRelease(pMem); + pMem->z = (char *)z; + pMem->xDel = xDel; + flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn); + } + + pMem->n = nByte; + pMem->flags = flags; + pMem->enc = (enc==0 ? SQLITE_UTF8 : enc); + pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT); + +#ifndef SQLITE_OMIT_UTF16 + if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){ + return SQLITE_NOMEM; + } +#endif + + if( nByte>iLimit ){ + return SQLITE_TOOBIG; + } + + return SQLITE_OK; +} + +/* +** Compare the values contained by the two memory cells, returning +** negative, zero or positive if pMem1 is less than, equal to, or greater +** than pMem2. Sorting order is NULL's first, followed by numbers (integers +** and reals) sorted numerically, followed by text ordered by the collating +** sequence pColl and finally blob's ordered by memcmp(). +** +** Two NULL values are considered equal by this function. +*/ +SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){ + int rc; + int f1, f2; + int combined_flags; + + f1 = pMem1->flags; + f2 = pMem2->flags; + combined_flags = f1|f2; + assert( (combined_flags & MEM_RowSet)==0 ); + + /* If one value is NULL, it is less than the other. If both values + ** are NULL, return 0. + */ + if( combined_flags&MEM_Null ){ + return (f2&MEM_Null) - (f1&MEM_Null); + } + + /* If one value is a number and the other is not, the number is less. + ** If both are numbers, compare as reals if one is a real, or as integers + ** if both values are integers. + */ + if( combined_flags&(MEM_Int|MEM_Real) ){ + double r1, r2; + if( (f1 & f2 & MEM_Int)!=0 ){ + if( pMem1->u.i < pMem2->u.i ) return -1; + if( pMem1->u.i > pMem2->u.i ) return 1; + return 0; + } + if( (f1&MEM_Real)!=0 ){ + r1 = pMem1->r; + }else if( (f1&MEM_Int)!=0 ){ + r1 = (double)pMem1->u.i; + }else{ + return 1; + } + if( (f2&MEM_Real)!=0 ){ + r2 = pMem2->r; + }else if( (f2&MEM_Int)!=0 ){ + r2 = (double)pMem2->u.i; + }else{ + return -1; + } + if( r1r2 ) return 1; + return 0; + } + + /* If one value is a string and the other is a blob, the string is less. + ** If both are strings, compare using the collating functions. + */ + if( combined_flags&MEM_Str ){ + if( (f1 & MEM_Str)==0 ){ + return 1; + } + if( (f2 & MEM_Str)==0 ){ + return -1; + } + + assert( pMem1->enc==pMem2->enc ); + assert( pMem1->enc==SQLITE_UTF8 || + pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE ); + + /* The collation sequence must be defined at this point, even if + ** the user deletes the collation sequence after the vdbe program is + ** compiled (this was not always the case). + */ + assert( !pColl || pColl->xCmp ); + + if( pColl ){ + if( pMem1->enc==pColl->enc ){ + /* The strings are already in the correct encoding. Call the + ** comparison function directly */ + return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z); + }else{ + const void *v1, *v2; + int n1, n2; + Mem c1; + Mem c2; + memset(&c1, 0, sizeof(c1)); + memset(&c2, 0, sizeof(c2)); + sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem); + sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem); + v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc); + n1 = v1==0 ? 0 : c1.n; + v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc); + n2 = v2==0 ? 0 : c2.n; + rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2); + sqlite3VdbeMemRelease(&c1); + sqlite3VdbeMemRelease(&c2); + return rc; + } + } + /* If a NULL pointer was passed as the collate function, fall through + ** to the blob case and use memcmp(). */ + } + + /* Both values must be blobs. Compare using memcmp(). */ + rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n); + if( rc==0 ){ + rc = pMem1->n - pMem2->n; + } + return rc; +} + +/* +** Move data out of a btree key or data field and into a Mem structure. +** The data or key is taken from the entry that pCur is currently pointing +** to. offset and amt determine what portion of the data or key to retrieve. +** key is true to get the key or false to get data. The result is written +** into the pMem element. +** +** The pMem structure is assumed to be uninitialized. Any prior content +** is overwritten without being freed. +** +** If this routine fails for any reason (malloc returns NULL or unable +** to read from the disk) then the pMem is left in an inconsistent state. +*/ +SQLITE_PRIVATE int sqlite3VdbeMemFromBtree( + BtCursor *pCur, /* Cursor pointing at record to retrieve. */ + int offset, /* Offset from the start of data to return bytes from. */ + int amt, /* Number of bytes to return. */ + int key, /* If true, retrieve from the btree key, not data. */ + Mem *pMem /* OUT: Return data in this Mem structure. */ +){ + char *zData; /* Data from the btree layer */ + int available = 0; /* Number of bytes available on the local btree page */ + int rc = SQLITE_OK; /* Return code */ + + assert( sqlite3BtreeCursorIsValid(pCur) ); + + /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() + ** that both the BtShared and database handle mutexes are held. */ + assert( (pMem->flags & MEM_RowSet)==0 ); + if( key ){ + zData = (char *)sqlite3BtreeKeyFetch(pCur, &available); + }else{ + zData = (char *)sqlite3BtreeDataFetch(pCur, &available); + } + assert( zData!=0 ); + + if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){ + sqlite3VdbeMemRelease(pMem); + pMem->z = &zData[offset]; + pMem->flags = MEM_Blob|MEM_Ephem; + }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){ + pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term; + pMem->enc = 0; + pMem->type = SQLITE_BLOB; + if( key ){ + rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z); + }else{ + rc = sqlite3BtreeData(pCur, offset, amt, pMem->z); + } + pMem->z[amt] = 0; + pMem->z[amt+1] = 0; + if( rc!=SQLITE_OK ){ + sqlite3VdbeMemRelease(pMem); + } + } + pMem->n = amt; + + return rc; +} + +/* This function is only available internally, it is not part of the +** external API. It works in a similar way to sqlite3_value_text(), +** except the data returned is in the encoding specified by the second +** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or +** SQLITE_UTF8. +** +** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED. +** If that is the case, then the result must be aligned on an even byte +** boundary. +*/ +SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){ + if( !pVal ) return 0; + + assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); + assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); + assert( (pVal->flags & MEM_RowSet)==0 ); + + if( pVal->flags&MEM_Null ){ + return 0; + } + assert( (MEM_Blob>>3) == MEM_Str ); + pVal->flags |= (pVal->flags & MEM_Blob)>>3; + ExpandBlob(pVal); + if( pVal->flags&MEM_Str ){ + sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED); + if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){ + assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 ); + if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){ + return 0; + } + } + sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */ + }else{ + assert( (pVal->flags&MEM_Blob)==0 ); + sqlite3VdbeMemStringify(pVal, enc); + assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) ); + } + assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0 + || pVal->db->mallocFailed ); + if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){ + return pVal->z; + }else{ + return 0; + } +} + +/* +** Create a new sqlite3_value object. +*/ +SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){ + Mem *p = sqlite3DbMallocZero(db, sizeof(*p)); + if( p ){ + p->flags = MEM_Null; + p->type = SQLITE_NULL; + p->db = db; + } + return p; +} + +/* +** Context object passed by sqlite3Stat4ProbeSetValue() through to +** valueNew(). See comments above valueNew() for details. +*/ +struct ValueNewStat4Ctx { + Parse *pParse; + Index *pIdx; + UnpackedRecord **ppRec; + int iVal; +}; + +/* +** Allocate and return a pointer to a new sqlite3_value object. If +** the second argument to this function is NULL, the object is allocated +** by calling sqlite3ValueNew(). +** +** Otherwise, if the second argument is non-zero, then this function is +** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not +** already been allocated, allocate the UnpackedRecord structure that +** that function will return to its caller here. Then return a pointer +** an sqlite3_value within the UnpackedRecord.a[] array. +*/ +static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( p ){ + UnpackedRecord *pRec = p->ppRec[0]; + + if( pRec==0 ){ + Index *pIdx = p->pIdx; /* Index being probed */ + int nByte; /* Bytes of space to allocate */ + int i; /* Counter variable */ + int nCol = pIdx->nColumn+1; /* Number of index columns including rowid */ + + nByte = sizeof(Mem) * nCol + sizeof(UnpackedRecord); + pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte); + if( pRec ){ + pRec->pKeyInfo = sqlite3IndexKeyinfo(p->pParse, pIdx); + if( pRec->pKeyInfo ){ + assert( pRec->pKeyInfo->nField+1==nCol ); + pRec->pKeyInfo->enc = ENC(db); + pRec->flags = UNPACKED_PREFIX_MATCH; + pRec->aMem = (Mem *)&pRec[1]; + for(i=0; iaMem[i].flags = MEM_Null; + pRec->aMem[i].type = SQLITE_NULL; + pRec->aMem[i].db = db; + } + }else{ + sqlite3DbFree(db, pRec); + pRec = 0; + } + } + if( pRec==0 ) return 0; + p->ppRec[0] = pRec; + } + + pRec->nField = p->iVal+1; + return &pRec->aMem[p->iVal]; + } +#else + UNUSED_PARAMETER(p); +#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */ + return sqlite3ValueNew(db); +} + +/* +** Extract a value from the supplied expression in the manner described +** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object +** using valueNew(). +** +** If pCtx is NULL and an error occurs after the sqlite3_value object +** has been allocated, it is freed before returning. Or, if pCtx is not +** NULL, it is assumed that the caller will free any allocated object +** in all cases. +*/ +static int valueFromExpr( + sqlite3 *db, /* The database connection */ + Expr *pExpr, /* The expression to evaluate */ + u8 enc, /* Encoding to use */ + u8 affinity, /* Affinity to use */ + sqlite3_value **ppVal, /* Write the new value here */ + struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */ +){ + int op; + char *zVal = 0; + sqlite3_value *pVal = 0; + int negInt = 1; + const char *zNeg = ""; + int rc = SQLITE_OK; + + if( !pExpr ){ + *ppVal = 0; + return SQLITE_OK; + } + op = pExpr->op; + + /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT4. + ** The ifdef here is to enable us to achieve 100% branch test coverage even + ** when SQLITE_ENABLE_STAT4 is omitted. + */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( op==TK_REGISTER ) op = pExpr->op2; +#else + if( NEVER(op==TK_REGISTER) ) op = pExpr->op2; +#endif + + /* Handle negative integers in a single step. This is needed in the + ** case when the value is -9223372036854775808. + */ + if( op==TK_UMINUS + && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){ + pExpr = pExpr->pLeft; + op = pExpr->op; + negInt = -1; + zNeg = "-"; + } + + if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){ + pVal = valueNew(db, pCtx); + if( pVal==0 ) goto no_mem; + if( ExprHasProperty(pExpr, EP_IntValue) ){ + sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt); + }else{ + zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken); + if( zVal==0 ) goto no_mem; + sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC); + if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT; + } + if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){ + sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8); + }else{ + sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8); + } + if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str; + if( enc!=SQLITE_UTF8 ){ + rc = sqlite3VdbeChangeEncoding(pVal, enc); + } + }else if( op==TK_UMINUS ) { + /* This branch happens for multiple negative signs. Ex: -(-5) */ + if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) + && pVal!=0 + ){ + sqlite3VdbeMemNumerify(pVal); + if( pVal->u.i==SMALLEST_INT64 ){ + pVal->flags &= MEM_Int; + pVal->flags |= MEM_Real; + pVal->r = (double)LARGEST_INT64; + }else{ + pVal->u.i = -pVal->u.i; + } + pVal->r = -pVal->r; + sqlite3ValueApplyAffinity(pVal, affinity, enc); + } + }else if( op==TK_NULL ){ + pVal = valueNew(db, pCtx); + if( pVal==0 ) goto no_mem; + } +#ifndef SQLITE_OMIT_BLOB_LITERAL + else if( op==TK_BLOB ){ + int nVal; + assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); + assert( pExpr->u.zToken[1]=='\'' ); + pVal = valueNew(db, pCtx); + if( !pVal ) goto no_mem; + zVal = &pExpr->u.zToken[2]; + nVal = sqlite3Strlen30(zVal)-1; + assert( zVal[nVal]=='\'' ); + sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2, + 0, SQLITE_DYNAMIC); + } +#endif + + if( pVal ){ + sqlite3VdbeMemStoreType(pVal); + } + *ppVal = pVal; + return rc; + +no_mem: + db->mallocFailed = 1; + sqlite3DbFree(db, zVal); + assert( *ppVal==0 ); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( pCtx==0 ) sqlite3ValueFree(pVal); +#else + assert( pCtx==0 ); sqlite3ValueFree(pVal); +#endif + return SQLITE_NOMEM; +} + +/* +** Create a new sqlite3_value object, containing the value of pExpr. +** +** This only works for very simple expressions that consist of one constant +** token (i.e. "5", "5.1", "'a string'"). If the expression can +** be converted directly into a value, then the value is allocated and +** a pointer written to *ppVal. The caller is responsible for deallocating +** the value by passing it to sqlite3ValueFree() later on. If the expression +** cannot be converted to a value, then *ppVal is set to NULL. +*/ +SQLITE_PRIVATE int sqlite3ValueFromExpr( + sqlite3 *db, /* The database connection */ + Expr *pExpr, /* The expression to evaluate */ + u8 enc, /* Encoding to use */ + u8 affinity, /* Affinity to use */ + sqlite3_value **ppVal /* Write the new value here */ +){ + return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0); +} + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** The implementation of the sqlite_record() function. This function accepts +** a single argument of any type. The return value is a formatted database +** record (a blob) containing the argument value. +** +** This is used to convert the value stored in the 'sample' column of the +** sqlite_stat3 table to the record format SQLite uses internally. +*/ +static void recordFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const int file_format = 1; + int iSerial; /* Serial type */ + int nSerial; /* Bytes of space for iSerial as varint */ + int nVal; /* Bytes of space required for argv[0] */ + int nRet; + sqlite3 *db; + u8 *aRet; + + UNUSED_PARAMETER( argc ); + iSerial = sqlite3VdbeSerialType(argv[0], file_format); + nSerial = sqlite3VarintLen(iSerial); + nVal = sqlite3VdbeSerialTypeLen(iSerial); + db = sqlite3_context_db_handle(context); + + nRet = 1 + nSerial + nVal; + aRet = sqlite3DbMallocRaw(db, nRet); + if( aRet==0 ){ + sqlite3_result_error_nomem(context); + }else{ + aRet[0] = nSerial+1; + sqlite3PutVarint(&aRet[1], iSerial); + sqlite3VdbeSerialPut(&aRet[1+nSerial], nVal, argv[0], file_format); + sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT); + sqlite3DbFree(db, aRet); + } +} + +/* +** Register built-in functions used to help read ANALYZE data. +*/ +SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){ + static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = { + FUNCTION(sqlite_record, 1, 0, 0, recordFunc), + }; + int i; + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs); + for(i=0; idb; + + + struct ValueNewStat4Ctx alloc; + alloc.pParse = pParse; + alloc.pIdx = pIdx; + alloc.ppRec = ppRec; + alloc.iVal = iVal; + + /* Skip over any TK_COLLATE nodes */ + pExpr = sqlite3ExprSkipCollate(pExpr); + + if( !pExpr ){ + pVal = valueNew(db, &alloc); + if( pVal ){ + sqlite3VdbeMemSetNull((Mem*)pVal); + *pbOk = 1; + } + }else if( pExpr->op==TK_VARIABLE + || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE) + ){ + Vdbe *v; + int iBindVar = pExpr->iColumn; + sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar); + if( (v = pParse->pReprepare)!=0 ){ + pVal = valueNew(db, &alloc); + if( pVal ){ + rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]); + if( rc==SQLITE_OK ){ + sqlite3ValueApplyAffinity(pVal, affinity, ENC(db)); + } + pVal->db = pParse->db; + *pbOk = 1; + sqlite3VdbeMemStoreType((Mem*)pVal); + } + }else{ + *pbOk = 0; + } + }else{ + rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc); + *pbOk = (pVal!=0); + } + + assert( pVal==0 || pVal->db==db ); + return rc; +} + +/* +** Unless it is NULL, the argument must be an UnpackedRecord object returned +** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes +** the object. +*/ +SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){ + if( pRec ){ + int i; + int nCol = pRec->pKeyInfo->nField+1; + Mem *aMem = pRec->aMem; + sqlite3 *db = aMem[0].db; + for(i=0; ipKeyInfo); + sqlite3DbFree(db, pRec); + } +} +#endif /* ifdef SQLITE_ENABLE_STAT4 */ + +/* +** Change the string value of an sqlite3_value object +*/ +SQLITE_PRIVATE void sqlite3ValueSetStr( + sqlite3_value *v, /* Value to be set */ + int n, /* Length of string z */ + const void *z, /* Text of the new string */ + u8 enc, /* Encoding to use */ + void (*xDel)(void*) /* Destructor for the string */ +){ + if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel); +} + +/* +** Free an sqlite3_value object +*/ +SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){ + if( !v ) return; + sqlite3VdbeMemRelease((Mem *)v); + sqlite3DbFree(((Mem*)v)->db, v); +} + +/* +** Return the number of bytes in the sqlite3_value object assuming +** that it uses the encoding "enc" +*/ +SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){ + Mem *p = (Mem*)pVal; + if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){ + if( p->flags & MEM_Zero ){ + return p->n + p->u.nZero; + }else{ + return p->n; + } + } + return 0; +} + +/************** End of vdbemem.c *********************************************/ +/************** Begin file vdbeaux.c *****************************************/ +/* +** 2003 September 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used for creating, destroying, and populating +** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior +** to version 2.8.7, all this code was combined into the vdbe.c source file. +** But that file was getting too big so this subroutines were split out. +*/ + +/* +** Create a new virtual database engine. +*/ +SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){ + Vdbe *p; + p = sqlite3DbMallocZero(db, sizeof(Vdbe) ); + if( p==0 ) return 0; + p->db = db; + if( db->pVdbe ){ + db->pVdbe->pPrev = p; + } + p->pNext = db->pVdbe; + p->pPrev = 0; + db->pVdbe = p; + p->magic = VDBE_MAGIC_INIT; + return p; +} + +/* +** Remember the SQL string for a prepared statement. +*/ +SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){ + assert( isPrepareV2==1 || isPrepareV2==0 ); + if( p==0 ) return; +#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG) + if( !isPrepareV2 ) return; +#endif + assert( p->zSql==0 ); + p->zSql = sqlite3DbStrNDup(p->db, z, n); + p->isPrepareV2 = (u8)isPrepareV2; +} + +/* +** Return the SQL associated with a prepared statement +*/ +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){ + Vdbe *p = (Vdbe *)pStmt; + return (p && p->isPrepareV2) ? p->zSql : 0; +} + +/* +** Swap all content between two VDBE structures. +*/ +SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ + Vdbe tmp, *pTmp; + char *zTmp; + tmp = *pA; + *pA = *pB; + *pB = tmp; + pTmp = pA->pNext; + pA->pNext = pB->pNext; + pB->pNext = pTmp; + pTmp = pA->pPrev; + pA->pPrev = pB->pPrev; + pB->pPrev = pTmp; + zTmp = pA->zSql; + pA->zSql = pB->zSql; + pB->zSql = zTmp; + pB->isPrepareV2 = pA->isPrepareV2; +} + +#ifdef SQLITE_DEBUG +/* +** Turn tracing on or off +*/ +SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){ + p->trace = trace; +} +#endif + +/* +** Resize the Vdbe.aOp array so that it is at least one op larger than +** it was. +** +** If an out-of-memory error occurs while resizing the array, return +** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain +** unchanged (this is so that any opcodes already allocated can be +** correctly deallocated along with the rest of the Vdbe). +*/ +static int growOpArray(Vdbe *p){ + VdbeOp *pNew; + int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op))); + pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op)); + if( pNew ){ + p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op); + p->aOp = pNew; + } + return (pNew ? SQLITE_OK : SQLITE_NOMEM); +} + +/* +** Add a new instruction to the list of instructions current in the +** VDBE. Return the address of the new instruction. +** +** Parameters: +** +** p Pointer to the VDBE +** +** op The opcode for this instruction +** +** p1, p2, p3 Operands +** +** Use the sqlite3VdbeResolveLabel() function to fix an address and +** the sqlite3VdbeChangeP4() function to change the value of the P4 +** operand. +*/ +SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ + int i; + VdbeOp *pOp; + + i = p->nOp; + assert( p->magic==VDBE_MAGIC_INIT ); + assert( op>0 && op<0xff ); + if( p->nOpAlloc<=i ){ + if( growOpArray(p) ){ + return 1; + } + } + p->nOp++; + pOp = &p->aOp[i]; + pOp->opcode = (u8)op; + pOp->p5 = 0; + pOp->p1 = p1; + pOp->p2 = p2; + pOp->p3 = p3; + pOp->p4.p = 0; + pOp->p4type = P4_NOTUSED; +#ifdef SQLITE_DEBUG + pOp->zComment = 0; + if( p->db->flags & SQLITE_VdbeAddopTrace ){ + sqlite3VdbePrintOp(0, i, &p->aOp[i]); + } +#endif +#ifdef VDBE_PROFILE + pOp->cycles = 0; + pOp->cnt = 0; +#endif + return i; +} +SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){ + return sqlite3VdbeAddOp3(p, op, 0, 0, 0); +} +SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){ + return sqlite3VdbeAddOp3(p, op, p1, 0, 0); +} +SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){ + return sqlite3VdbeAddOp3(p, op, p1, p2, 0); +} + + +/* +** Add an opcode that includes the p4 value as a pointer. +*/ +SQLITE_PRIVATE int sqlite3VdbeAddOp4( + Vdbe *p, /* Add the opcode to this VM */ + int op, /* The new opcode */ + int p1, /* The P1 operand */ + int p2, /* The P2 operand */ + int p3, /* The P3 operand */ + const char *zP4, /* The P4 operand */ + int p4type /* P4 operand type */ +){ + int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); + sqlite3VdbeChangeP4(p, addr, zP4, p4type); + return addr; +} + +/* +** Add an OP_ParseSchema opcode. This routine is broken out from +** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees +** as having been used. +** +** The zWhere string must have been obtained from sqlite3_malloc(). +** This routine will take ownership of the allocated memory. +*/ +SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){ + int j; + int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0); + sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC); + for(j=0; jdb->nDb; j++) sqlite3VdbeUsesBtree(p, j); +} + +/* +** Add an opcode that includes the p4 value as an integer. +*/ +SQLITE_PRIVATE int sqlite3VdbeAddOp4Int( + Vdbe *p, /* Add the opcode to this VM */ + int op, /* The new opcode */ + int p1, /* The P1 operand */ + int p2, /* The P2 operand */ + int p3, /* The P3 operand */ + int p4 /* The P4 operand as an integer */ +){ + int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); + sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32); + return addr; +} + +/* +** Create a new symbolic label for an instruction that has yet to be +** coded. The symbolic label is really just a negative number. The +** label can be used as the P2 value of an operation. Later, when +** the label is resolved to a specific address, the VDBE will scan +** through its operation list and change all values of P2 which match +** the label into the resolved address. +** +** The VDBE knows that a P2 value is a label because labels are +** always negative and P2 values are suppose to be non-negative. +** Hence, a negative P2 value is a label that has yet to be resolved. +** +** Zero is returned if a malloc() fails. +*/ +SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){ + int i = p->nLabel++; + assert( p->magic==VDBE_MAGIC_INIT ); + if( (i & (i-1))==0 ){ + p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, + (i*2+1)*sizeof(p->aLabel[0])); + } + if( p->aLabel ){ + p->aLabel[i] = -1; + } + return -1-i; +} + +/* +** Resolve label "x" to be the address of the next instruction to +** be inserted. The parameter "x" must have been obtained from +** a prior call to sqlite3VdbeMakeLabel(). +*/ +SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){ + int j = -1-x; + assert( p->magic==VDBE_MAGIC_INIT ); + assert( jnLabel ); + if( j>=0 && p->aLabel ){ + p->aLabel[j] = p->nOp; + } +} + +/* +** Mark the VDBE as one that can only be run one time. +*/ +SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){ + p->runOnlyOnce = 1; +} + +#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */ + +/* +** The following type and function are used to iterate through all opcodes +** in a Vdbe main program and each of the sub-programs (triggers) it may +** invoke directly or indirectly. It should be used as follows: +** +** Op *pOp; +** VdbeOpIter sIter; +** +** memset(&sIter, 0, sizeof(sIter)); +** sIter.v = v; // v is of type Vdbe* +** while( (pOp = opIterNext(&sIter)) ){ +** // Do something with pOp +** } +** sqlite3DbFree(v->db, sIter.apSub); +** +*/ +typedef struct VdbeOpIter VdbeOpIter; +struct VdbeOpIter { + Vdbe *v; /* Vdbe to iterate through the opcodes of */ + SubProgram **apSub; /* Array of subprograms */ + int nSub; /* Number of entries in apSub */ + int iAddr; /* Address of next instruction to return */ + int iSub; /* 0 = main program, 1 = first sub-program etc. */ +}; +static Op *opIterNext(VdbeOpIter *p){ + Vdbe *v = p->v; + Op *pRet = 0; + Op *aOp; + int nOp; + + if( p->iSub<=p->nSub ){ + + if( p->iSub==0 ){ + aOp = v->aOp; + nOp = v->nOp; + }else{ + aOp = p->apSub[p->iSub-1]->aOp; + nOp = p->apSub[p->iSub-1]->nOp; + } + assert( p->iAddriAddr]; + p->iAddr++; + if( p->iAddr==nOp ){ + p->iSub++; + p->iAddr = 0; + } + + if( pRet->p4type==P4_SUBPROGRAM ){ + int nByte = (p->nSub+1)*sizeof(SubProgram*); + int j; + for(j=0; jnSub; j++){ + if( p->apSub[j]==pRet->p4.pProgram ) break; + } + if( j==p->nSub ){ + p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte); + if( !p->apSub ){ + pRet = 0; + }else{ + p->apSub[p->nSub++] = pRet->p4.pProgram; + } + } + } + } + + return pRet; +} + +/* +** Check if the program stored in the VM associated with pParse may +** throw an ABORT exception (causing the statement, but not entire transaction +** to be rolled back). This condition is true if the main program or any +** sub-programs contains any of the following: +** +** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort. +** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort. +** * OP_Destroy +** * OP_VUpdate +** * OP_VRename +** * OP_FkCounter with P2==0 (immediate foreign key constraint) +** +** Then check that the value of Parse.mayAbort is true if an +** ABORT may be thrown, or false otherwise. Return true if it does +** match, or false otherwise. This function is intended to be used as +** part of an assert statement in the compiler. Similar to: +** +** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) ); +*/ +SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ + int hasAbort = 0; + Op *pOp; + VdbeOpIter sIter; + memset(&sIter, 0, sizeof(sIter)); + sIter.v = v; + + while( (pOp = opIterNext(&sIter))!=0 ){ + int opcode = pOp->opcode; + if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename +#ifndef SQLITE_OMIT_FOREIGN_KEY + || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) +#endif + || ((opcode==OP_Halt || opcode==OP_HaltIfNull) + && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort)) + ){ + hasAbort = 1; + break; + } + } + sqlite3DbFree(v->db, sIter.apSub); + + /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred. + ** If malloc failed, then the while() loop above may not have iterated + ** through all opcodes and hasAbort may be set incorrectly. Return + ** true for this case to prevent the assert() in the callers frame + ** from failing. */ + return ( v->db->mallocFailed || hasAbort==mayAbort ); +} +#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */ + +/* +** Loop through the program looking for P2 values that are negative +** on jump instructions. Each such value is a label. Resolve the +** label by setting the P2 value to its correct non-zero value. +** +** This routine is called once after all opcodes have been inserted. +** +** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument +** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by +** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array. +** +** The Op.opflags field is set on all opcodes. +*/ +static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ + int i; + int nMaxArgs = *pMaxFuncArgs; + Op *pOp; + int *aLabel = p->aLabel; + p->readOnly = 1; + p->bIsReader = 0; + for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){ + u8 opcode = pOp->opcode; + + /* NOTE: Be sure to update mkopcodeh.awk when adding or removing + ** cases from this switch! */ + switch( opcode ){ + case OP_Function: + case OP_AggStep: { + if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5; + break; + } + case OP_Transaction: { + if( pOp->p2!=0 ) p->readOnly = 0; + /* fall thru */ + } + case OP_AutoCommit: + case OP_Savepoint: { + p->bIsReader = 1; + break; + } +#ifndef SQLITE_OMIT_WAL + case OP_Checkpoint: +#endif + case OP_Vacuum: + case OP_JournalMode: { + p->readOnly = 0; + p->bIsReader = 1; + break; + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + case OP_VUpdate: { + if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2; + break; + } + case OP_VFilter: { + int n; + assert( p->nOp - i >= 3 ); + assert( pOp[-1].opcode==OP_Integer ); + n = pOp[-1].p1; + if( n>nMaxArgs ) nMaxArgs = n; + break; + } +#endif + case OP_Next: + case OP_SorterNext: { + pOp->p4.xAdvance = sqlite3BtreeNext; + pOp->p4type = P4_ADVANCE; + break; + } + case OP_Prev: { + pOp->p4.xAdvance = sqlite3BtreePrevious; + pOp->p4type = P4_ADVANCE; + break; + } + } + + pOp->opflags = sqlite3OpcodeProperty[opcode]; + if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){ + assert( -1-pOp->p2nLabel ); + pOp->p2 = aLabel[-1-pOp->p2]; + } + } + sqlite3DbFree(p->db, p->aLabel); + p->aLabel = 0; + *pMaxFuncArgs = nMaxArgs; + assert( p->bIsReader!=0 || p->btreeMask==0 ); +} + +/* +** Return the address of the next instruction to be inserted. +*/ +SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){ + assert( p->magic==VDBE_MAGIC_INIT ); + return p->nOp; +} + +/* +** This function returns a pointer to the array of opcodes associated with +** the Vdbe passed as the first argument. It is the callers responsibility +** to arrange for the returned array to be eventually freed using the +** vdbeFreeOpArray() function. +** +** Before returning, *pnOp is set to the number of entries in the returned +** array. Also, *pnMaxArg is set to the larger of its current value and +** the number of entries in the Vdbe.apArg[] array required to execute the +** returned program. +*/ +SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){ + VdbeOp *aOp = p->aOp; + assert( aOp && !p->db->mallocFailed ); + + /* Check that sqlite3VdbeUsesBtree() was not called on this VM */ + assert( p->btreeMask==0 ); + + resolveP2Values(p, pnMaxArg); + *pnOp = p->nOp; + p->aOp = 0; + return aOp; +} + +/* +** Add a whole list of operations to the operation stack. Return the +** address of the first operation added. +*/ +SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){ + int addr; + assert( p->magic==VDBE_MAGIC_INIT ); + if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){ + return 0; + } + addr = p->nOp; + if( ALWAYS(nOp>0) ){ + int i; + VdbeOpList const *pIn = aOp; + for(i=0; ip2; + VdbeOp *pOut = &p->aOp[i+addr]; + pOut->opcode = pIn->opcode; + pOut->p1 = pIn->p1; + if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){ + pOut->p2 = addr + ADDR(p2); + }else{ + pOut->p2 = p2; + } + pOut->p3 = pIn->p3; + pOut->p4type = P4_NOTUSED; + pOut->p4.p = 0; + pOut->p5 = 0; +#ifdef SQLITE_DEBUG + pOut->zComment = 0; + if( p->db->flags & SQLITE_VdbeAddopTrace ){ + sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]); + } +#endif + } + p->nOp += nOp; + } + return addr; +} + +/* +** Change the value of the P1 operand for a specific instruction. +** This routine is useful when a large program is loaded from a +** static array using sqlite3VdbeAddOpList but we want to make a +** few minor changes to the program. +*/ +SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){ + assert( p!=0 ); + if( ((u32)p->nOp)>addr ){ + p->aOp[addr].p1 = val; + } +} + +/* +** Change the value of the P2 operand for a specific instruction. +** This routine is useful for setting a jump destination. +*/ +SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){ + assert( p!=0 ); + if( ((u32)p->nOp)>addr ){ + p->aOp[addr].p2 = val; + } +} + +/* +** Change the value of the P3 operand for a specific instruction. +*/ +SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){ + assert( p!=0 ); + if( ((u32)p->nOp)>addr ){ + p->aOp[addr].p3 = val; + } +} + +/* +** Change the value of the P5 operand for the most recently +** added operation. +*/ +SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){ + assert( p!=0 ); + if( p->aOp ){ + assert( p->nOp>0 ); + p->aOp[p->nOp-1].p5 = val; + } +} + +/* +** Change the P2 operand of instruction addr so that it points to +** the address of the next instruction to be coded. +*/ +SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){ + if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp); +} + + +/* +** If the input FuncDef structure is ephemeral, then free it. If +** the FuncDef is not ephermal, then do nothing. +*/ +static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){ + if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){ + sqlite3DbFree(db, pDef); + } +} + +static void vdbeFreeOpArray(sqlite3 *, Op *, int); + +/* +** Delete a P4 value if necessary. +*/ +static void freeP4(sqlite3 *db, int p4type, void *p4){ + if( p4 ){ + assert( db ); + switch( p4type ){ + case P4_REAL: + case P4_INT64: + case P4_DYNAMIC: + case P4_KEYINFO: + case P4_INTARRAY: + case P4_KEYINFO_HANDOFF: { + sqlite3DbFree(db, p4); + break; + } + case P4_MPRINTF: { + if( db->pnBytesFreed==0 ) sqlite3_free(p4); + break; + } + case P4_FUNCDEF: { + freeEphemeralFunction(db, (FuncDef*)p4); + break; + } + case P4_MEM: { + if( db->pnBytesFreed==0 ){ + sqlite3ValueFree((sqlite3_value*)p4); + }else{ + Mem *p = (Mem*)p4; + sqlite3DbFree(db, p->zMalloc); + sqlite3DbFree(db, p); + } + break; + } + case P4_VTAB : { + if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4); + break; + } + } + } +} + +/* +** Free the space allocated for aOp and any p4 values allocated for the +** opcodes contained within. If aOp is not NULL it is assumed to contain +** nOp entries. +*/ +static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){ + if( aOp ){ + Op *pOp; + for(pOp=aOp; pOp<&aOp[nOp]; pOp++){ + freeP4(db, pOp->p4type, pOp->p4.p); +#ifdef SQLITE_DEBUG + sqlite3DbFree(db, pOp->zComment); +#endif + } + } + sqlite3DbFree(db, aOp); +} + +/* +** Link the SubProgram object passed as the second argument into the linked +** list at Vdbe.pSubProgram. This list is used to delete all sub-program +** objects when the VM is no longer required. +*/ +SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){ + p->pNext = pVdbe->pProgram; + pVdbe->pProgram = p; +} + +/* +** Change the opcode at addr into OP_Noop +*/ +SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){ + if( p->aOp ){ + VdbeOp *pOp = &p->aOp[addr]; + sqlite3 *db = p->db; + freeP4(db, pOp->p4type, pOp->p4.p); + memset(pOp, 0, sizeof(pOp[0])); + pOp->opcode = OP_Noop; + } +} + +/* +** Change the value of the P4 operand for a specific instruction. +** This routine is useful when a large program is loaded from a +** static array using sqlite3VdbeAddOpList but we want to make a +** few minor changes to the program. +** +** If n>=0 then the P4 operand is dynamic, meaning that a copy of +** the string is made into memory obtained from sqlite3_malloc(). +** A value of n==0 means copy bytes of zP4 up to and including the +** first null byte. If n>0 then copy n+1 bytes of zP4. +** +** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure. +** A copy is made of the KeyInfo structure into memory obtained from +** sqlite3_malloc, to be freed when the Vdbe is finalized. +** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure +** stored in memory that the caller has obtained from sqlite3_malloc. The +** caller should not free the allocation, it will be freed when the Vdbe is +** finalized. +** +** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points +** to a string or structure that is guaranteed to exist for the lifetime of +** the Vdbe. In these cases we can just copy the pointer. +** +** If addr<0 then change P4 on the most recently inserted instruction. +*/ +SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ + Op *pOp; + sqlite3 *db; + assert( p!=0 ); + db = p->db; + assert( p->magic==VDBE_MAGIC_INIT ); + if( p->aOp==0 || db->mallocFailed ){ + if ( n!=P4_KEYINFO && n!=P4_VTAB ) { + freeP4(db, n, (void*)*(char**)&zP4); + } + return; + } + assert( p->nOp>0 ); + assert( addrnOp ); + if( addr<0 ){ + addr = p->nOp - 1; + } + pOp = &p->aOp[addr]; + assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 ); + freeP4(db, pOp->p4type, pOp->p4.p); + pOp->p4.p = 0; + if( n==P4_INT32 ){ + /* Note: this cast is safe, because the origin data point was an int + ** that was cast to a (const char *). */ + pOp->p4.i = SQLITE_PTR_TO_INT(zP4); + pOp->p4type = P4_INT32; + }else if( zP4==0 ){ + pOp->p4.p = 0; + pOp->p4type = P4_NOTUSED; + }else if( n==P4_KEYINFO ){ + KeyInfo *pOrig, *pNew; + + pOrig = (KeyInfo*)zP4; + pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField); + if( pNew ){ + memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0])); + memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField); + pOp->p4type = P4_KEYINFO; + }else{ + p->db->mallocFailed = 1; + pOp->p4type = P4_NOTUSED; + } + }else if( n==P4_KEYINFO_HANDOFF ){ + pOp->p4.p = (void*)zP4; + pOp->p4type = P4_KEYINFO; + }else if( n==P4_VTAB ){ + pOp->p4.p = (void*)zP4; + pOp->p4type = P4_VTAB; + sqlite3VtabLock((VTable *)zP4); + assert( ((VTable *)zP4)->db==p->db ); + }else if( n<0 ){ + pOp->p4.p = (void*)zP4; + pOp->p4type = (signed char)n; + }else{ + if( n==0 ) n = sqlite3Strlen30(zP4); + pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n); + pOp->p4type = P4_DYNAMIC; + } +} + +#ifndef NDEBUG +/* +** Change the comment on the most recently coded instruction. Or +** insert a No-op and add the comment to that new instruction. This +** makes the code easier to read during debugging. None of this happens +** in a production build. +*/ +static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){ + assert( p->nOp>0 || p->aOp==0 ); + assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed ); + if( p->nOp ){ + assert( p->aOp ); + sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment); + p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap); + } +} +SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){ + va_list ap; + if( p ){ + va_start(ap, zFormat); + vdbeVComment(p, zFormat, ap); + va_end(ap); + } +} +SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){ + va_list ap; + if( p ){ + sqlite3VdbeAddOp0(p, OP_Noop); + va_start(ap, zFormat); + vdbeVComment(p, zFormat, ap); + va_end(ap); + } +} +#endif /* NDEBUG */ + +/* +** Return the opcode for a given address. If the address is -1, then +** return the most recently inserted opcode. +** +** If a memory allocation error has occurred prior to the calling of this +** routine, then a pointer to a dummy VdbeOp will be returned. That opcode +** is readable but not writable, though it is cast to a writable value. +** The return of a dummy opcode allows the call to continue functioning +** after a OOM fault without having to check to see if the return from +** this routine is a valid pointer. But because the dummy.opcode is 0, +** dummy will never be written to. This is verified by code inspection and +** by running with Valgrind. +** +** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called +** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE, +** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as +** a new VDBE is created. So we are free to set addr to p->nOp-1 without +** having to double-check to make sure that the result is non-negative. But +** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to +** check the value of p->nOp-1 before continuing. +*/ +SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){ + /* C89 specifies that the constant "dummy" will be initialized to all + ** zeros, which is correct. MSVC generates a warning, nevertheless. */ + static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */ + assert( p->magic==VDBE_MAGIC_INIT ); + if( addr<0 ){ +#ifdef SQLITE_OMIT_TRACE + if( p->nOp==0 ) return (VdbeOp*)&dummy; +#endif + addr = p->nOp - 1; + } + assert( (addr>=0 && addrnOp) || p->db->mallocFailed ); + if( p->db->mallocFailed ){ + return (VdbeOp*)&dummy; + }else{ + return &p->aOp[addr]; + } +} + +#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \ + || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) +/* +** Compute a string that describes the P4 parameter for an opcode. +** Use zTemp for any required temporary buffer space. +*/ +static char *displayP4(Op *pOp, char *zTemp, int nTemp){ + char *zP4 = zTemp; + assert( nTemp>=20 ); + switch( pOp->p4type ){ + case P4_KEYINFO_STATIC: + case P4_KEYINFO: { + int i, j; + KeyInfo *pKeyInfo = pOp->p4.pKeyInfo; + assert( pKeyInfo->aSortOrder!=0 ); + sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField); + i = sqlite3Strlen30(zTemp); + for(j=0; jnField; j++){ + CollSeq *pColl = pKeyInfo->aColl[j]; + const char *zColl = pColl ? pColl->zName : "nil"; + int n = sqlite3Strlen30(zColl); + if( i+n>nTemp-6 ){ + memcpy(&zTemp[i],",...",4); + break; + } + zTemp[i++] = ','; + if( pKeyInfo->aSortOrder[j] ){ + zTemp[i++] = '-'; + } + memcpy(&zTemp[i], zColl, n+1); + i += n; + } + zTemp[i++] = ')'; + zTemp[i] = 0; + assert( ip4.pColl; + sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName); + break; + } + case P4_FUNCDEF: { + FuncDef *pDef = pOp->p4.pFunc; + sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg); + break; + } + case P4_INT64: { + sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64); + break; + } + case P4_INT32: { + sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i); + break; + } + case P4_REAL: { + sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal); + break; + } + case P4_MEM: { + Mem *pMem = pOp->p4.pMem; + if( pMem->flags & MEM_Str ){ + zP4 = pMem->z; + }else if( pMem->flags & MEM_Int ){ + sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i); + }else if( pMem->flags & MEM_Real ){ + sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r); + }else if( pMem->flags & MEM_Null ){ + sqlite3_snprintf(nTemp, zTemp, "NULL"); + }else{ + assert( pMem->flags & MEM_Blob ); + zP4 = "(blob)"; + } + break; + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + case P4_VTAB: { + sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab; + sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule); + break; + } +#endif + case P4_INTARRAY: { + sqlite3_snprintf(nTemp, zTemp, "intarray"); + break; + } + case P4_SUBPROGRAM: { + sqlite3_snprintf(nTemp, zTemp, "program"); + break; + } + case P4_ADVANCE: { + zTemp[0] = 0; + break; + } + default: { + zP4 = pOp->p4.z; + if( zP4==0 ){ + zP4 = zTemp; + zTemp[0] = 0; + } + } + } + assert( zP4!=0 ); + return zP4; +} +#endif + +/* +** Declare to the Vdbe that the BTree object at db->aDb[i] is used. +** +** The prepared statements need to know in advance the complete set of +** attached databases that will be use. A mask of these databases +** is maintained in p->btreeMask. The p->lockMask value is the subset of +** p->btreeMask of databases that will require a lock. +*/ +SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){ + assert( i>=0 && idb->nDb && i<(int)sizeof(yDbMask)*8 ); + assert( i<(int)sizeof(p->btreeMask)*8 ); + p->btreeMask |= ((yDbMask)1)<db->aDb[i].pBt) ){ + p->lockMask |= ((yDbMask)1)<0 +/* +** If SQLite is compiled to support shared-cache mode and to be threadsafe, +** this routine obtains the mutex associated with each BtShared structure +** that may be accessed by the VM passed as an argument. In doing so it also +** sets the BtShared.db member of each of the BtShared structures, ensuring +** that the correct busy-handler callback is invoked if required. +** +** If SQLite is not threadsafe but does support shared-cache mode, then +** sqlite3BtreeEnter() is invoked to set the BtShared.db variables +** of all of BtShared structures accessible via the database handle +** associated with the VM. +** +** If SQLite is not threadsafe and does not support shared-cache mode, this +** function is a no-op. +** +** The p->btreeMask field is a bitmask of all btrees that the prepared +** statement p will ever use. Let N be the number of bits in p->btreeMask +** corresponding to btrees that use shared cache. Then the runtime of +** this routine is N*N. But as N is rarely more than 1, this should not +** be a problem. +*/ +SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){ + int i; + yDbMask mask; + sqlite3 *db; + Db *aDb; + int nDb; + if( p->lockMask==0 ) return; /* The common case */ + db = p->db; + aDb = db->aDb; + nDb = db->nDb; + for(i=0, mask=1; ilockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){ + sqlite3BtreeEnter(aDb[i].pBt); + } + } +} +#endif + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 +/* +** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter(). +*/ +SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){ + int i; + yDbMask mask; + sqlite3 *db; + Db *aDb; + int nDb; + if( p->lockMask==0 ) return; /* The common case */ + db = p->db; + aDb = db->aDb; + nDb = db->nDb; + for(i=0, mask=1; ilockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){ + sqlite3BtreeLeave(aDb[i].pBt); + } + } +} +#endif + +#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) +/* +** Print a single opcode. This routine is used for debugging only. +*/ +SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){ + char *zP4; + char zPtr[50]; + static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n"; + if( pOut==0 ) pOut = stdout; + zP4 = displayP4(pOp, zPtr, sizeof(zPtr)); + fprintf(pOut, zFormat1, pc, + sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5, +#ifdef SQLITE_DEBUG + pOp->zComment ? pOp->zComment : "" +#else + "" +#endif + ); + fflush(pOut); +} +#endif + +/* +** Release an array of N Mem elements +*/ +static void releaseMemArray(Mem *p, int N){ + if( p && N ){ + Mem *pEnd; + sqlite3 *db = p->db; + u8 malloc_failed = db->mallocFailed; + if( db->pnBytesFreed ){ + for(pEnd=&p[N]; pzMalloc); + } + return; + } + for(pEnd=&p[N]; pflags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){ + sqlite3VdbeMemRelease(p); + }else if( p->zMalloc ){ + sqlite3DbFree(db, p->zMalloc); + p->zMalloc = 0; + } + + p->flags = MEM_Invalid; + } + db->mallocFailed = malloc_failed; + } +} + +/* +** Delete a VdbeFrame object and its contents. VdbeFrame objects are +** allocated by the OP_Program opcode in sqlite3VdbeExec(). +*/ +SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){ + int i; + Mem *aMem = VdbeFrameMem(p); + VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem]; + for(i=0; inChildCsr; i++){ + sqlite3VdbeFreeCursor(p->v, apCsr[i]); + } + releaseMemArray(aMem, p->nChildMem); + sqlite3DbFree(p->v->db, p); +} + +#ifndef SQLITE_OMIT_EXPLAIN +/* +** Give a listing of the program in the virtual machine. +** +** The interface is the same as sqlite3VdbeExec(). But instead of +** running the code, it invokes the callback once for each instruction. +** This feature is used to implement "EXPLAIN". +** +** When p->explain==1, each instruction is listed. When +** p->explain==2, only OP_Explain instructions are listed and these +** are shown in a different format. p->explain==2 is used to implement +** EXPLAIN QUERY PLAN. +** +** When p->explain==1, first the main program is listed, then each of +** the trigger subprograms are listed one by one. +*/ +SQLITE_PRIVATE int sqlite3VdbeList( + Vdbe *p /* The VDBE */ +){ + int nRow; /* Stop when row count reaches this */ + int nSub = 0; /* Number of sub-vdbes seen so far */ + SubProgram **apSub = 0; /* Array of sub-vdbes */ + Mem *pSub = 0; /* Memory cell hold array of subprogs */ + sqlite3 *db = p->db; /* The database connection */ + int i; /* Loop counter */ + int rc = SQLITE_OK; /* Return code */ + Mem *pMem = &p->aMem[1]; /* First Mem of result set */ + + assert( p->explain ); + assert( p->magic==VDBE_MAGIC_RUN ); + assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM ); + + /* Even though this opcode does not use dynamic strings for + ** the result, result columns may become dynamic if the user calls + ** sqlite3_column_text16(), causing a translation to UTF-16 encoding. + */ + releaseMemArray(pMem, 8); + p->pResultSet = 0; + + if( p->rc==SQLITE_NOMEM ){ + /* This happens if a malloc() inside a call to sqlite3_column_text() or + ** sqlite3_column_text16() failed. */ + db->mallocFailed = 1; + return SQLITE_ERROR; + } + + /* When the number of output rows reaches nRow, that means the + ** listing has finished and sqlite3_step() should return SQLITE_DONE. + ** nRow is the sum of the number of rows in the main program, plus + ** the sum of the number of rows in all trigger subprograms encountered + ** so far. The nRow value will increase as new trigger subprograms are + ** encountered, but p->pc will eventually catch up to nRow. + */ + nRow = p->nOp; + if( p->explain==1 ){ + /* The first 8 memory cells are used for the result set. So we will + ** commandeer the 9th cell to use as storage for an array of pointers + ** to trigger subprograms. The VDBE is guaranteed to have at least 9 + ** cells. */ + assert( p->nMem>9 ); + pSub = &p->aMem[9]; + if( pSub->flags&MEM_Blob ){ + /* On the first call to sqlite3_step(), pSub will hold a NULL. It is + ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */ + nSub = pSub->n/sizeof(Vdbe*); + apSub = (SubProgram **)pSub->z; + } + for(i=0; inOp; + } + } + + do{ + i = p->pc++; + }while( iexplain==2 && p->aOp[i].opcode!=OP_Explain ); + if( i>=nRow ){ + p->rc = SQLITE_OK; + rc = SQLITE_DONE; + }else if( db->u1.isInterrupted ){ + p->rc = SQLITE_INTERRUPT; + rc = SQLITE_ERROR; + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc)); + }else{ + char *z; + Op *pOp; + if( inOp ){ + /* The output line number is small enough that we are still in the + ** main program. */ + pOp = &p->aOp[i]; + }else{ + /* We are currently listing subprograms. Figure out which one and + ** pick up the appropriate opcode. */ + int j; + i -= p->nOp; + for(j=0; i>=apSub[j]->nOp; j++){ + i -= apSub[j]->nOp; + } + pOp = &apSub[j]->aOp[i]; + } + if( p->explain==1 ){ + pMem->flags = MEM_Int; + pMem->type = SQLITE_INTEGER; + pMem->u.i = i; /* Program counter */ + pMem++; + + pMem->flags = MEM_Static|MEM_Str|MEM_Term; + pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ + assert( pMem->z!=0 ); + pMem->n = sqlite3Strlen30(pMem->z); + pMem->type = SQLITE_TEXT; + pMem->enc = SQLITE_UTF8; + pMem++; + + /* When an OP_Program opcode is encounter (the only opcode that has + ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms + ** kept in p->aMem[9].z to hold the new program - assuming this subprogram + ** has not already been seen. + */ + if( pOp->p4type==P4_SUBPROGRAM ){ + int nByte = (nSub+1)*sizeof(SubProgram*); + int j; + for(j=0; jp4.pProgram ) break; + } + if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){ + apSub = (SubProgram **)pSub->z; + apSub[nSub++] = pOp->p4.pProgram; + pSub->flags |= MEM_Blob; + pSub->n = nSub*sizeof(SubProgram*); + } + } + } + + pMem->flags = MEM_Int; + pMem->u.i = pOp->p1; /* P1 */ + pMem->type = SQLITE_INTEGER; + pMem++; + + pMem->flags = MEM_Int; + pMem->u.i = pOp->p2; /* P2 */ + pMem->type = SQLITE_INTEGER; + pMem++; + + pMem->flags = MEM_Int; + pMem->u.i = pOp->p3; /* P3 */ + pMem->type = SQLITE_INTEGER; + pMem++; + + if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */ + assert( p->db->mallocFailed ); + return SQLITE_ERROR; + } + pMem->flags = MEM_Dyn|MEM_Str|MEM_Term; + z = displayP4(pOp, pMem->z, 32); + if( z!=pMem->z ){ + sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0); + }else{ + assert( pMem->z!=0 ); + pMem->n = sqlite3Strlen30(pMem->z); + pMem->enc = SQLITE_UTF8; + } + pMem->type = SQLITE_TEXT; + pMem++; + + if( p->explain==1 ){ + if( sqlite3VdbeMemGrow(pMem, 4, 0) ){ + assert( p->db->mallocFailed ); + return SQLITE_ERROR; + } + pMem->flags = MEM_Dyn|MEM_Str|MEM_Term; + pMem->n = 2; + sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */ + pMem->type = SQLITE_TEXT; + pMem->enc = SQLITE_UTF8; + pMem++; + +#ifdef SQLITE_DEBUG + if( pOp->zComment ){ + pMem->flags = MEM_Str|MEM_Term; + pMem->z = pOp->zComment; + pMem->n = sqlite3Strlen30(pMem->z); + pMem->enc = SQLITE_UTF8; + pMem->type = SQLITE_TEXT; + }else +#endif + { + pMem->flags = MEM_Null; /* Comment */ + pMem->type = SQLITE_NULL; + } + } + + p->nResColumn = 8 - 4*(p->explain-1); + p->pResultSet = &p->aMem[1]; + p->rc = SQLITE_OK; + rc = SQLITE_ROW; + } + return rc; +} +#endif /* SQLITE_OMIT_EXPLAIN */ + +#ifdef SQLITE_DEBUG +/* +** Print the SQL that was used to generate a VDBE program. +*/ +SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){ + int nOp = p->nOp; + VdbeOp *pOp; + if( nOp<1 ) return; + pOp = &p->aOp[0]; + if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){ + const char *z = pOp->p4.z; + while( sqlite3Isspace(*z) ) z++; + printf("SQL: [%s]\n", z); + } +} +#endif + +#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) +/* +** Print an IOTRACE message showing SQL content. +*/ +SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){ + int nOp = p->nOp; + VdbeOp *pOp; + if( sqlite3IoTrace==0 ) return; + if( nOp<1 ) return; + pOp = &p->aOp[0]; + if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){ + int i, j; + char z[1000]; + sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z); + for(i=0; sqlite3Isspace(z[i]); i++){} + for(j=0; z[i]; i++){ + if( sqlite3Isspace(z[i]) ){ + if( z[i-1]!=' ' ){ + z[j++] = ' '; + } + }else{ + z[j++] = z[i]; + } + } + z[j] = 0; + sqlite3IoTrace("SQL %s\n", z); + } +} +#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */ + +/* +** Allocate space from a fixed size buffer and return a pointer to +** that space. If insufficient space is available, return NULL. +** +** The pBuf parameter is the initial value of a pointer which will +** receive the new memory. pBuf is normally NULL. If pBuf is not +** NULL, it means that memory space has already been allocated and that +** this routine should not allocate any new memory. When pBuf is not +** NULL simply return pBuf. Only allocate new memory space when pBuf +** is NULL. +** +** nByte is the number of bytes of space needed. +** +** *ppFrom points to available space and pEnd points to the end of the +** available space. When space is allocated, *ppFrom is advanced past +** the end of the allocated space. +** +** *pnByte is a counter of the number of bytes of space that have failed +** to allocate. If there is insufficient space in *ppFrom to satisfy the +** request, then increment *pnByte by the amount of the request. +*/ +static void *allocSpace( + void *pBuf, /* Where return pointer will be stored */ + int nByte, /* Number of bytes to allocate */ + u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */ + u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */ + int *pnByte /* If allocation cannot be made, increment *pnByte */ +){ + assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) ); + if( pBuf ) return pBuf; + nByte = ROUND8(nByte); + if( &(*ppFrom)[nByte] <= pEnd ){ + pBuf = (void*)*ppFrom; + *ppFrom += nByte; + }else{ + *pnByte += nByte; + } + return pBuf; +} + +/* +** Rewind the VDBE back to the beginning in preparation for +** running it. +*/ +SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){ +#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) + int i; +#endif + assert( p!=0 ); + assert( p->magic==VDBE_MAGIC_INIT ); + + /* There should be at least one opcode. + */ + assert( p->nOp>0 ); + + /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */ + p->magic = VDBE_MAGIC_RUN; + +#ifdef SQLITE_DEBUG + for(i=1; inMem; i++){ + assert( p->aMem[i].db==p->db ); + } +#endif + p->pc = -1; + p->rc = SQLITE_OK; + p->errorAction = OE_Abort; + p->magic = VDBE_MAGIC_RUN; + p->nChange = 0; + p->cacheCtr = 1; + p->minWriteFileFormat = 255; + p->iStatement = 0; + p->nFkConstraint = 0; +#ifdef VDBE_PROFILE + for(i=0; inOp; i++){ + p->aOp[i].cnt = 0; + p->aOp[i].cycles = 0; + } +#endif +} + +/* +** Prepare a virtual machine for execution for the first time after +** creating the virtual machine. This involves things such +** as allocating stack space and initializing the program counter. +** After the VDBE has be prepped, it can be executed by one or more +** calls to sqlite3VdbeExec(). +** +** This function may be called exact once on a each virtual machine. +** After this routine is called the VM has been "packaged" and is ready +** to run. After this routine is called, futher calls to +** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects +** the Vdbe from the Parse object that helped generate it so that the +** the Vdbe becomes an independent entity and the Parse object can be +** destroyed. +** +** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back +** to its initial state after it has been run. +*/ +SQLITE_PRIVATE void sqlite3VdbeMakeReady( + Vdbe *p, /* The VDBE */ + Parse *pParse /* Parsing context */ +){ + sqlite3 *db; /* The database connection */ + int nVar; /* Number of parameters */ + int nMem; /* Number of VM memory registers */ + int nCursor; /* Number of cursors required */ + int nArg; /* Number of arguments in subprograms */ + int nOnce; /* Number of OP_Once instructions */ + int n; /* Loop counter */ + u8 *zCsr; /* Memory available for allocation */ + u8 *zEnd; /* First byte past allocated memory */ + int nByte; /* How much extra memory is needed */ + + assert( p!=0 ); + assert( p->nOp>0 ); + assert( pParse!=0 ); + assert( p->magic==VDBE_MAGIC_INIT ); + db = p->db; + assert( db->mallocFailed==0 ); + nVar = pParse->nVar; + nMem = pParse->nMem; + nCursor = pParse->nTab; + nArg = pParse->nMaxArg; + nOnce = pParse->nOnce; + if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */ + + /* For each cursor required, also allocate a memory cell. Memory + ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by + ** the vdbe program. Instead they are used to allocate space for + ** VdbeCursor/BtCursor structures. The blob of memory associated with + ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1) + ** stores the blob of memory associated with cursor 1, etc. + ** + ** See also: allocateCursor(). + */ + nMem += nCursor; + + /* Allocate space for memory registers, SQL variables, VDBE cursors and + ** an array to marshal SQL function arguments in. + */ + zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */ + zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */ + + resolveP2Values(p, &nArg); + p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort); + if( pParse->explain && nMem<10 ){ + nMem = 10; + } + memset(zCsr, 0, zEnd-zCsr); + zCsr += (zCsr - (u8*)0)&7; + assert( EIGHT_BYTE_ALIGNMENT(zCsr) ); + p->expired = 0; + + /* Memory for registers, parameters, cursor, etc, is allocated in two + ** passes. On the first pass, we try to reuse unused space at the + ** end of the opcode array. If we are unable to satisfy all memory + ** requirements by reusing the opcode array tail, then the second + ** pass will fill in the rest using a fresh allocation. + ** + ** This two-pass approach that reuses as much memory as possible from + ** the leftover space at the end of the opcode array can significantly + ** reduce the amount of memory held by a prepared statement. + */ + do { + nByte = 0; + p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte); + p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte); + p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte); + p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte); + p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*), + &zCsr, zEnd, &nByte); + p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte); + if( nByte ){ + p->pFree = sqlite3DbMallocZero(db, nByte); + } + zCsr = p->pFree; + zEnd = &zCsr[nByte]; + }while( nByte && !db->mallocFailed ); + + p->nCursor = nCursor; + p->nOnceFlag = nOnce; + if( p->aVar ){ + p->nVar = (ynVar)nVar; + for(n=0; naVar[n].flags = MEM_Null; + p->aVar[n].db = db; + } + } + if( p->azVar ){ + p->nzVar = pParse->nzVar; + memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0])); + memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0])); + } + if( p->aMem ){ + p->aMem--; /* aMem[] goes from 1..nMem */ + p->nMem = nMem; /* not from 0..nMem-1 */ + for(n=1; n<=nMem; n++){ + p->aMem[n].flags = MEM_Invalid; + p->aMem[n].db = db; + } + } + p->explain = pParse->explain; + sqlite3VdbeRewind(p); +} + +/* +** Close a VDBE cursor and release all the resources that cursor +** happens to hold. +*/ +SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){ + if( pCx==0 ){ + return; + } + sqlite3VdbeSorterClose(p->db, pCx); + if( pCx->pBt ){ + sqlite3BtreeClose(pCx->pBt); + /* The pCx->pCursor will be close automatically, if it exists, by + ** the call above. */ + }else if( pCx->pCursor ){ + sqlite3BtreeCloseCursor(pCx->pCursor); + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pCx->pVtabCursor ){ + sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor; + const sqlite3_module *pModule = pCx->pModule; + p->inVtabMethod = 1; + pModule->xClose(pVtabCursor); + p->inVtabMethod = 0; + } +#endif +} + +/* +** Copy the values stored in the VdbeFrame structure to its Vdbe. This +** is used, for example, when a trigger sub-program is halted to restore +** control to the main program. +*/ +SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){ + Vdbe *v = pFrame->v; + v->aOnceFlag = pFrame->aOnceFlag; + v->nOnceFlag = pFrame->nOnceFlag; + v->aOp = pFrame->aOp; + v->nOp = pFrame->nOp; + v->aMem = pFrame->aMem; + v->nMem = pFrame->nMem; + v->apCsr = pFrame->apCsr; + v->nCursor = pFrame->nCursor; + v->db->lastRowid = pFrame->lastRowid; + v->nChange = pFrame->nChange; + return pFrame->pc; +} + +/* +** Close all cursors. +** +** Also release any dynamic memory held by the VM in the Vdbe.aMem memory +** cell array. This is necessary as the memory cell array may contain +** pointers to VdbeFrame objects, which may in turn contain pointers to +** open cursors. +*/ +static void closeAllCursors(Vdbe *p){ + if( p->pFrame ){ + VdbeFrame *pFrame; + for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); + sqlite3VdbeFrameRestore(pFrame); + } + p->pFrame = 0; + p->nFrame = 0; + + if( p->apCsr ){ + int i; + for(i=0; inCursor; i++){ + VdbeCursor *pC = p->apCsr[i]; + if( pC ){ + sqlite3VdbeFreeCursor(p, pC); + p->apCsr[i] = 0; + } + } + } + if( p->aMem ){ + releaseMemArray(&p->aMem[1], p->nMem); + } + while( p->pDelFrame ){ + VdbeFrame *pDel = p->pDelFrame; + p->pDelFrame = pDel->pParent; + sqlite3VdbeFrameDelete(pDel); + } + + /* Delete any auxdata allocations made by the VM */ + sqlite3VdbeDeleteAuxData(p, -1, 0); + assert( p->pAuxData==0 ); +} + +/* +** Clean up the VM after execution. +** +** This routine will automatically close any cursors, lists, and/or +** sorters that were left open. It also deletes the values of +** variables in the aVar[] array. +*/ +static void Cleanup(Vdbe *p){ + sqlite3 *db = p->db; + +#ifdef SQLITE_DEBUG + /* Execute assert() statements to ensure that the Vdbe.apCsr[] and + ** Vdbe.aMem[] arrays have already been cleaned up. */ + int i; + if( p->apCsr ) for(i=0; inCursor; i++) assert( p->apCsr[i]==0 ); + if( p->aMem ){ + for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid ); + } +#endif + + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = 0; + p->pResultSet = 0; +} + +/* +** Set the number of result columns that will be returned by this SQL +** statement. This is now set at compile time, rather than during +** execution of the vdbe program so that sqlite3_column_count() can +** be called on an SQL statement before sqlite3_step(). +*/ +SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){ + Mem *pColName; + int n; + sqlite3 *db = p->db; + + releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); + sqlite3DbFree(db, p->aColName); + n = nResColumn*COLNAME_N; + p->nResColumn = (u16)nResColumn; + p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n ); + if( p->aColName==0 ) return; + while( n-- > 0 ){ + pColName->flags = MEM_Null; + pColName->db = p->db; + pColName++; + } +} + +/* +** Set the name of the idx'th column to be returned by the SQL statement. +** zName must be a pointer to a nul terminated string. +** +** This call must be made after a call to sqlite3VdbeSetNumCols(). +** +** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC +** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed +** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed. +*/ +SQLITE_PRIVATE int sqlite3VdbeSetColName( + Vdbe *p, /* Vdbe being configured */ + int idx, /* Index of column zName applies to */ + int var, /* One of the COLNAME_* constants */ + const char *zName, /* Pointer to buffer containing name */ + void (*xDel)(void*) /* Memory management strategy for zName */ +){ + int rc; + Mem *pColName; + assert( idxnResColumn ); + assert( vardb->mallocFailed ){ + assert( !zName || xDel!=SQLITE_DYNAMIC ); + return SQLITE_NOMEM; + } + assert( p->aColName!=0 ); + pColName = &(p->aColName[idx+var*p->nResColumn]); + rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel); + assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 ); + return rc; +} + +/* +** A read or write transaction may or may not be active on database handle +** db. If a transaction is active, commit it. If there is a +** write-transaction spanning more than one database file, this routine +** takes care of the master journal trickery. +*/ +static int vdbeCommit(sqlite3 *db, Vdbe *p){ + int i; + int nTrans = 0; /* Number of databases with an active write-transaction */ + int rc = SQLITE_OK; + int needXcommit = 0; + +#ifdef SQLITE_OMIT_VIRTUALTABLE + /* With this option, sqlite3VtabSync() is defined to be simply + ** SQLITE_OK so p is not used. + */ + UNUSED_PARAMETER(p); +#endif + + /* Before doing anything else, call the xSync() callback for any + ** virtual module tables written in this transaction. This has to + ** be done before determining whether a master journal file is + ** required, as an xSync() callback may add an attached database + ** to the transaction. + */ + rc = sqlite3VtabSync(db, p); + + /* This loop determines (a) if the commit hook should be invoked and + ** (b) how many database files have open write transactions, not + ** including the temp database. (b) is important because if more than + ** one database file has an open write transaction, a master journal + ** file is required for an atomic commit. + */ + for(i=0; rc==SQLITE_OK && inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( sqlite3BtreeIsInTrans(pBt) ){ + needXcommit = 1; + if( i!=1 ) nTrans++; + sqlite3BtreeEnter(pBt); + rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt)); + sqlite3BtreeLeave(pBt); + } + } + if( rc!=SQLITE_OK ){ + return rc; + } + + /* If there are any write-transactions at all, invoke the commit hook */ + if( needXcommit && db->xCommitCallback ){ + rc = db->xCommitCallback(db->pCommitArg); + if( rc ){ + return SQLITE_CONSTRAINT_COMMITHOOK; + } + } + + /* The simple case - no more than one database file (not counting the + ** TEMP database) has a transaction active. There is no need for the + ** master-journal. + ** + ** If the return value of sqlite3BtreeGetFilename() is a zero length + ** string, it means the main database is :memory: or a temp file. In + ** that case we do not support atomic multi-file commits, so use the + ** simple case then too. + */ + if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt)) + || nTrans<=1 + ){ + for(i=0; rc==SQLITE_OK && inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + rc = sqlite3BtreeCommitPhaseOne(pBt, 0); + } + } + + /* Do the commit only if all databases successfully complete phase 1. + ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an + ** IO error while deleting or truncating a journal file. It is unlikely, + ** but could happen. In this case abandon processing and return the error. + */ + for(i=0; rc==SQLITE_OK && inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + rc = sqlite3BtreeCommitPhaseTwo(pBt, 0); + } + } + if( rc==SQLITE_OK ){ + sqlite3VtabCommit(db); + } + } + + /* The complex case - There is a multi-file write-transaction active. + ** This requires a master journal file to ensure the transaction is + ** committed atomicly. + */ +#ifndef SQLITE_OMIT_DISKIO + else{ + sqlite3_vfs *pVfs = db->pVfs; + int needSync = 0; + char *zMaster = 0; /* File-name for the master journal */ + char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt); + sqlite3_file *pMaster = 0; + i64 offset = 0; + int res; + int retryCount = 0; + int nMainFile; + + /* Select a master journal file name */ + nMainFile = sqlite3Strlen30(zMainFile); + zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile); + if( zMaster==0 ) return SQLITE_NOMEM; + do { + u32 iRandom; + if( retryCount ){ + if( retryCount>100 ){ + sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster); + sqlite3OsDelete(pVfs, zMaster, 0); + break; + }else if( retryCount==1 ){ + sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster); + } + } + retryCount++; + sqlite3_randomness(sizeof(iRandom), &iRandom); + sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X", + (iRandom>>8)&0xffffff, iRandom&0xff); + /* The antipenultimate character of the master journal name must + ** be "9" to avoid name collisions when using 8+3 filenames. */ + assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' ); + sqlite3FileSuffix3(zMainFile, zMaster); + rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); + }while( rc==SQLITE_OK && res ); + if( rc==SQLITE_OK ){ + /* Open the master journal. */ + rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, + SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE| + SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0 + ); + } + if( rc!=SQLITE_OK ){ + sqlite3DbFree(db, zMaster); + return rc; + } + + /* Write the name of each database file in the transaction into the new + ** master journal file. If an error occurs at this point close + ** and delete the master journal file. All the individual journal files + ** still have 'null' as the master journal pointer, so they will roll + ** back independently if a failure occurs. + */ + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( sqlite3BtreeIsInTrans(pBt) ){ + char const *zFile = sqlite3BtreeGetJournalname(pBt); + if( zFile==0 ){ + continue; /* Ignore TEMP and :memory: databases */ + } + assert( zFile[0]!=0 ); + if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){ + needSync = 1; + } + rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset); + offset += sqlite3Strlen30(zFile)+1; + if( rc!=SQLITE_OK ){ + sqlite3OsCloseFree(pMaster); + sqlite3OsDelete(pVfs, zMaster, 0); + sqlite3DbFree(db, zMaster); + return rc; + } + } + } + + /* Sync the master journal file. If the IOCAP_SEQUENTIAL device + ** flag is set this is not required. + */ + if( needSync + && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL) + && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL)) + ){ + sqlite3OsCloseFree(pMaster); + sqlite3OsDelete(pVfs, zMaster, 0); + sqlite3DbFree(db, zMaster); + return rc; + } + + /* Sync all the db files involved in the transaction. The same call + ** sets the master journal pointer in each individual journal. If + ** an error occurs here, do not delete the master journal file. + ** + ** If the error occurs during the first call to + ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the + ** master journal file will be orphaned. But we cannot delete it, + ** in case the master journal file name was written into the journal + ** file before the failure occurred. + */ + for(i=0; rc==SQLITE_OK && inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster); + } + } + sqlite3OsCloseFree(pMaster); + assert( rc!=SQLITE_BUSY ); + if( rc!=SQLITE_OK ){ + sqlite3DbFree(db, zMaster); + return rc; + } + + /* Delete the master journal file. This commits the transaction. After + ** doing this the directory is synced again before any individual + ** transaction files are deleted. + */ + rc = sqlite3OsDelete(pVfs, zMaster, 1); + sqlite3DbFree(db, zMaster); + zMaster = 0; + if( rc ){ + return rc; + } + + /* All files and directories have already been synced, so the following + ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and + ** deleting or truncating journals. If something goes wrong while + ** this is happening we don't really care. The integrity of the + ** transaction is already guaranteed, but some stray 'cold' journals + ** may be lying around. Returning an error code won't help matters. + */ + disable_simulated_io_errors(); + sqlite3BeginBenignMalloc(); + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + sqlite3BtreeCommitPhaseTwo(pBt, 1); + } + } + sqlite3EndBenignMalloc(); + enable_simulated_io_errors(); + + sqlite3VtabCommit(db); + } +#endif + + return rc; +} + +/* +** This routine checks that the sqlite3.nVdbeActive count variable +** matches the number of vdbe's in the list sqlite3.pVdbe that are +** currently active. An assertion fails if the two counts do not match. +** This is an internal self-check only - it is not an essential processing +** step. +** +** This is a no-op if NDEBUG is defined. +*/ +#ifndef NDEBUG +static void checkActiveVdbeCnt(sqlite3 *db){ + Vdbe *p; + int cnt = 0; + int nWrite = 0; + int nRead = 0; + p = db->pVdbe; + while( p ){ + if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){ + cnt++; + if( p->readOnly==0 ) nWrite++; + if( p->bIsReader ) nRead++; + } + p = p->pNext; + } + assert( cnt==db->nVdbeActive ); + assert( nWrite==db->nVdbeWrite ); + assert( nRead==db->nVdbeRead ); +} +#else +#define checkActiveVdbeCnt(x) +#endif + +/* +** If the Vdbe passed as the first argument opened a statement-transaction, +** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or +** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement +** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the +** statement transaction is committed. +** +** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. +** Otherwise SQLITE_OK. +*/ +SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){ + sqlite3 *const db = p->db; + int rc = SQLITE_OK; + + /* If p->iStatement is greater than zero, then this Vdbe opened a + ** statement transaction that should be closed here. The only exception + ** is that an IO error may have occurred, causing an emergency rollback. + ** In this case (db->nStatement==0), and there is nothing to do. + */ + if( db->nStatement && p->iStatement ){ + int i; + const int iSavepoint = p->iStatement-1; + + assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE); + assert( db->nStatement>0 ); + assert( p->iStatement==(db->nStatement+db->nSavepoint) ); + + for(i=0; inDb; i++){ + int rc2 = SQLITE_OK; + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + if( eOp==SAVEPOINT_ROLLBACK ){ + rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint); + } + if( rc2==SQLITE_OK ){ + rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint); + } + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + db->nStatement--; + p->iStatement = 0; + + if( rc==SQLITE_OK ){ + if( eOp==SAVEPOINT_ROLLBACK ){ + rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint); + } + if( rc==SQLITE_OK ){ + rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint); + } + } + + /* If the statement transaction is being rolled back, also restore the + ** database handles deferred constraint counter to the value it had when + ** the statement transaction was opened. */ + if( eOp==SAVEPOINT_ROLLBACK ){ + db->nDeferredCons = p->nStmtDefCons; + db->nDeferredImmCons = p->nStmtDefImmCons; + } + } + return rc; +} + +/* +** This function is called when a transaction opened by the database +** handle associated with the VM passed as an argument is about to be +** committed. If there are outstanding deferred foreign key constraint +** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK. +** +** If there are outstanding FK violations and this function returns +** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY +** and write an error message to it. Then return SQLITE_ERROR. +*/ +#ifndef SQLITE_OMIT_FOREIGN_KEY +SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){ + sqlite3 *db = p->db; + if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) + || (!deferred && p->nFkConstraint>0) + ){ + p->rc = SQLITE_CONSTRAINT_FOREIGNKEY; + p->errorAction = OE_Abort; + sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed"); + return SQLITE_ERROR; + } + return SQLITE_OK; +} +#endif + +/* +** This routine is called the when a VDBE tries to halt. If the VDBE +** has made changes and is in autocommit mode, then commit those +** changes. If a rollback is needed, then do the rollback. +** +** This routine is the only way to move the state of a VM from +** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to +** call this on a VM that is in the SQLITE_MAGIC_HALT state. +** +** Return an error code. If the commit could not complete because of +** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it +** means the close did not happen and needs to be repeated. +*/ +SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ + int rc; /* Used to store transient return codes */ + sqlite3 *db = p->db; + + /* This function contains the logic that determines if a statement or + ** transaction will be committed or rolled back as a result of the + ** execution of this virtual machine. + ** + ** If any of the following errors occur: + ** + ** SQLITE_NOMEM + ** SQLITE_IOERR + ** SQLITE_FULL + ** SQLITE_INTERRUPT + ** + ** Then the internal cache might have been left in an inconsistent + ** state. We need to rollback the statement transaction, if there is + ** one, or the complete transaction if there is no statement transaction. + */ + + if( p->db->mallocFailed ){ + p->rc = SQLITE_NOMEM; + } + if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag); + closeAllCursors(p); + if( p->magic!=VDBE_MAGIC_RUN ){ + return SQLITE_OK; + } + checkActiveVdbeCnt(db); + + /* No commit or rollback needed if the program never started or if the + ** SQL statement does not read or write a database file. */ + if( p->pc>=0 && p->bIsReader ){ + int mrc; /* Primary error code from p->rc */ + int eStatementOp = 0; + int isSpecialError; /* Set to true if a 'special' error */ + + /* Lock all btrees used by the statement */ + sqlite3VdbeEnter(p); + + /* Check for one of the special errors */ + mrc = p->rc & 0xff; + assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */ + isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR + || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL; + if( isSpecialError ){ + /* If the query was read-only and the error code is SQLITE_INTERRUPT, + ** no rollback is necessary. Otherwise, at least a savepoint + ** transaction must be rolled back to restore the database to a + ** consistent state. + ** + ** Even if the statement is read-only, it is important to perform + ** a statement or transaction rollback operation. If the error + ** occurred while writing to the journal, sub-journal or database + ** file as part of an effort to free up cache space (see function + ** pagerStress() in pager.c), the rollback is required to restore + ** the pager to a consistent state. + */ + if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){ + if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){ + eStatementOp = SAVEPOINT_ROLLBACK; + }else{ + /* We are forced to roll back the active transaction. Before doing + ** so, abort any other statements this handle currently has active. + */ + sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + sqlite3CloseSavepoints(db); + db->autoCommit = 1; + } + } + } + + /* Check for immediate foreign key violations. */ + if( p->rc==SQLITE_OK ){ + sqlite3VdbeCheckFk(p, 0); + } + + /* If the auto-commit flag is set and this is the only active writer + ** VM, then we do either a commit or rollback of the current transaction. + ** + ** Note: This block also runs if one of the special errors handled + ** above has occurred. + */ + if( !sqlite3VtabInSync(db) + && db->autoCommit + && db->nVdbeWrite==(p->readOnly==0) + ){ + if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ + rc = sqlite3VdbeCheckFk(p, 1); + if( rc!=SQLITE_OK ){ + if( NEVER(p->readOnly) ){ + sqlite3VdbeLeave(p); + return SQLITE_ERROR; + } + rc = SQLITE_CONSTRAINT_FOREIGNKEY; + }else{ + /* The auto-commit flag is true, the vdbe program was successful + ** or hit an 'OR FAIL' constraint and there are no deferred foreign + ** key constraints to hold up the transaction. This means a commit + ** is required. */ + rc = vdbeCommit(db, p); + } + if( rc==SQLITE_BUSY && p->readOnly ){ + sqlite3VdbeLeave(p); + return SQLITE_BUSY; + }else if( rc!=SQLITE_OK ){ + p->rc = rc; + sqlite3RollbackAll(db, SQLITE_OK); + }else{ + db->nDeferredCons = 0; + db->nDeferredImmCons = 0; + db->flags &= ~SQLITE_DeferFKs; + sqlite3CommitInternalChanges(db); + } + }else{ + sqlite3RollbackAll(db, SQLITE_OK); + } + db->nStatement = 0; + }else if( eStatementOp==0 ){ + if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){ + eStatementOp = SAVEPOINT_RELEASE; + }else if( p->errorAction==OE_Abort ){ + eStatementOp = SAVEPOINT_ROLLBACK; + }else{ + sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + sqlite3CloseSavepoints(db); + db->autoCommit = 1; + } + } + + /* If eStatementOp is non-zero, then a statement transaction needs to + ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to + ** do so. If this operation returns an error, and the current statement + ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the + ** current statement error code. + */ + if( eStatementOp ){ + rc = sqlite3VdbeCloseStatement(p, eStatementOp); + if( rc ){ + if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){ + p->rc = rc; + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = 0; + } + sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + sqlite3CloseSavepoints(db); + db->autoCommit = 1; + } + } + + /* If this was an INSERT, UPDATE or DELETE and no statement transaction + ** has been rolled back, update the database connection change-counter. + */ + if( p->changeCntOn ){ + if( eStatementOp!=SAVEPOINT_ROLLBACK ){ + sqlite3VdbeSetChanges(db, p->nChange); + }else{ + sqlite3VdbeSetChanges(db, 0); + } + p->nChange = 0; + } + + /* Release the locks */ + sqlite3VdbeLeave(p); + } + + /* We have successfully halted and closed the VM. Record this fact. */ + if( p->pc>=0 ){ + db->nVdbeActive--; + if( !p->readOnly ) db->nVdbeWrite--; + if( p->bIsReader ) db->nVdbeRead--; + assert( db->nVdbeActive>=db->nVdbeRead ); + assert( db->nVdbeRead>=db->nVdbeWrite ); + assert( db->nVdbeWrite>=0 ); + } + p->magic = VDBE_MAGIC_HALT; + checkActiveVdbeCnt(db); + if( p->db->mallocFailed ){ + p->rc = SQLITE_NOMEM; + } + + /* If the auto-commit flag is set to true, then any locks that were held + ** by connection db have now been released. Call sqlite3ConnectionUnlocked() + ** to invoke any required unlock-notify callbacks. + */ + if( db->autoCommit ){ + sqlite3ConnectionUnlocked(db); + } + + assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 ); + return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK); +} + + +/* +** Each VDBE holds the result of the most recent sqlite3_step() call +** in p->rc. This routine sets that result back to SQLITE_OK. +*/ +SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){ + p->rc = SQLITE_OK; +} + +/* +** Copy the error code and error message belonging to the VDBE passed +** as the first argument to its database handle (so that they will be +** returned by calls to sqlite3_errcode() and sqlite3_errmsg()). +** +** This function does not clear the VDBE error code or message, just +** copies them to the database handle. +*/ +SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){ + sqlite3 *db = p->db; + int rc = p->rc; + if( p->zErrMsg ){ + u8 mallocFailed = db->mallocFailed; + sqlite3BeginBenignMalloc(); + sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); + sqlite3EndBenignMalloc(); + db->mallocFailed = mallocFailed; + db->errCode = rc; + }else{ + sqlite3Error(db, rc, 0); + } + return rc; +} + +#ifdef SQLITE_ENABLE_SQLLOG +/* +** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, +** invoke it. +*/ +static void vdbeInvokeSqllog(Vdbe *v){ + if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){ + char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql); + assert( v->db->init.busy==0 ); + if( zExpanded ){ + sqlite3GlobalConfig.xSqllog( + sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1 + ); + sqlite3DbFree(v->db, zExpanded); + } + } +} +#else +# define vdbeInvokeSqllog(x) +#endif + +/* +** Clean up a VDBE after execution but do not delete the VDBE just yet. +** Write any error messages into *pzErrMsg. Return the result code. +** +** After this routine is run, the VDBE should be ready to be executed +** again. +** +** To look at it another way, this routine resets the state of the +** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to +** VDBE_MAGIC_INIT. +*/ +SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){ + sqlite3 *db; + db = p->db; + + /* If the VM did not run to completion or if it encountered an + ** error, then it might not have been halted properly. So halt + ** it now. + */ + sqlite3VdbeHalt(p); + + /* If the VDBE has be run even partially, then transfer the error code + ** and error message from the VDBE into the main database structure. But + ** if the VDBE has just been set to run but has not actually executed any + ** instructions yet, leave the main database error information unchanged. + */ + if( p->pc>=0 ){ + vdbeInvokeSqllog(p); + sqlite3VdbeTransferError(p); + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = 0; + if( p->runOnlyOnce ) p->expired = 1; + }else if( p->rc && p->expired ){ + /* The expired flag was set on the VDBE before the first call + ** to sqlite3_step(). For consistency (since sqlite3_step() was + ** called), set the database error in this case as well. + */ + sqlite3Error(db, p->rc, 0); + sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = 0; + } + + /* Reclaim all memory used by the VDBE + */ + Cleanup(p); + + /* Save profiling information from this VDBE run. + */ +#ifdef VDBE_PROFILE + { + FILE *out = fopen("vdbe_profile.out", "a"); + if( out ){ + int i; + fprintf(out, "---- "); + for(i=0; inOp; i++){ + fprintf(out, "%02x", p->aOp[i].opcode); + } + fprintf(out, "\n"); + for(i=0; inOp; i++){ + fprintf(out, "%6d %10lld %8lld ", + p->aOp[i].cnt, + p->aOp[i].cycles, + p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0 + ); + sqlite3VdbePrintOp(out, i, &p->aOp[i]); + } + fclose(out); + } + } +#endif + p->iCurrentTime = 0; + p->magic = VDBE_MAGIC_INIT; + return p->rc & db->errMask; +} + +/* +** Clean up and delete a VDBE after execution. Return an integer which is +** the result code. Write any error message text into *pzErrMsg. +*/ +SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){ + int rc = SQLITE_OK; + if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){ + rc = sqlite3VdbeReset(p); + assert( (rc & p->db->errMask)==rc ); + } + sqlite3VdbeDelete(p); + return rc; +} + +/* +** If parameter iOp is less than zero, then invoke the destructor for +** all auxiliary data pointers currently cached by the VM passed as +** the first argument. +** +** Or, if iOp is greater than or equal to zero, then the destructor is +** only invoked for those auxiliary data pointers created by the user +** function invoked by the OP_Function opcode at instruction iOp of +** VM pVdbe, and only then if: +** +** * the associated function parameter is the 32nd or later (counting +** from left to right), or +** +** * the corresponding bit in argument mask is clear (where the first +** function parameter corrsponds to bit 0 etc.). +*/ +SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){ + AuxData **pp = &pVdbe->pAuxData; + while( *pp ){ + AuxData *pAux = *pp; + if( (iOp<0) + || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & ((u32)1<iArg)))) + ){ + if( pAux->xDelete ){ + pAux->xDelete(pAux->pAux); + } + *pp = pAux->pNext; + sqlite3DbFree(pVdbe->db, pAux); + }else{ + pp= &pAux->pNext; + } + } +} + +/* +** Free all memory associated with the Vdbe passed as the second argument, +** except for object itself, which is preserved. +** +** The difference between this function and sqlite3VdbeDelete() is that +** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with +** the database connection and frees the object itself. +*/ +SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){ + SubProgram *pSub, *pNext; + int i; + assert( p->db==0 || p->db==db ); + releaseMemArray(p->aVar, p->nVar); + releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); + for(pSub=p->pProgram; pSub; pSub=pNext){ + pNext = pSub->pNext; + vdbeFreeOpArray(db, pSub->aOp, pSub->nOp); + sqlite3DbFree(db, pSub); + } + for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]); + vdbeFreeOpArray(db, p->aOp, p->nOp); + sqlite3DbFree(db, p->aLabel); + sqlite3DbFree(db, p->aColName); + sqlite3DbFree(db, p->zSql); + sqlite3DbFree(db, p->pFree); +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) + sqlite3DbFree(db, p->zExplain); + sqlite3DbFree(db, p->pExplain); +#endif +} + +/* +** Delete an entire VDBE. +*/ +SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){ + sqlite3 *db; + + if( NEVER(p==0) ) return; + db = p->db; + assert( sqlite3_mutex_held(db->mutex) ); + sqlite3VdbeClearObject(db, p); + if( p->pPrev ){ + p->pPrev->pNext = p->pNext; + }else{ + assert( db->pVdbe==p ); + db->pVdbe = p->pNext; + } + if( p->pNext ){ + p->pNext->pPrev = p->pPrev; + } + p->magic = VDBE_MAGIC_DEAD; + p->db = 0; + sqlite3DbFree(db, p); +} + +/* +** Make sure the cursor p is ready to read or write the row to which it +** was last positioned. Return an error code if an OOM fault or I/O error +** prevents us from positioning the cursor to its correct position. +** +** If a MoveTo operation is pending on the given cursor, then do that +** MoveTo now. If no move is pending, check to see if the row has been +** deleted out from under the cursor and if it has, mark the row as +** a NULL row. +** +** If the cursor is already pointing to the correct row and that row has +** not been deleted out from under the cursor, then this routine is a no-op. +*/ +SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){ + if( p->deferredMoveto ){ + int res, rc; +#ifdef SQLITE_TEST + extern int sqlite3_search_count; +#endif + assert( p->isTable ); + rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res); + if( rc ) return rc; + p->lastRowid = p->movetoTarget; + if( res!=0 ) return SQLITE_CORRUPT_BKPT; + p->rowidIsValid = 1; +#ifdef SQLITE_TEST + sqlite3_search_count++; +#endif + p->deferredMoveto = 0; + p->cacheStatus = CACHE_STALE; + }else if( ALWAYS(p->pCursor) ){ + int hasMoved; + int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved); + if( rc ) return rc; + if( hasMoved ){ + p->cacheStatus = CACHE_STALE; + p->nullRow = 1; + } + } + return SQLITE_OK; +} + +/* +** The following functions: +** +** sqlite3VdbeSerialType() +** sqlite3VdbeSerialTypeLen() +** sqlite3VdbeSerialLen() +** sqlite3VdbeSerialPut() +** sqlite3VdbeSerialGet() +** +** encapsulate the code that serializes values for storage in SQLite +** data and index records. Each serialized value consists of a +** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned +** integer, stored as a varint. +** +** In an SQLite index record, the serial type is stored directly before +** the blob of data that it corresponds to. In a table record, all serial +** types are stored at the start of the record, and the blobs of data at +** the end. Hence these functions allow the caller to handle the +** serial-type and data blob separately. +** +** The following table describes the various storage classes for data: +** +** serial type bytes of data type +** -------------- --------------- --------------- +** 0 0 NULL +** 1 1 signed integer +** 2 2 signed integer +** 3 3 signed integer +** 4 4 signed integer +** 5 6 signed integer +** 6 8 signed integer +** 7 8 IEEE float +** 8 0 Integer constant 0 +** 9 0 Integer constant 1 +** 10,11 reserved for expansion +** N>=12 and even (N-12)/2 BLOB +** N>=13 and odd (N-13)/2 text +** +** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions +** of SQLite will not understand those serial types. +*/ + +/* +** Return the serial-type for the value stored in pMem. +*/ +SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){ + int flags = pMem->flags; + int n; + + if( flags&MEM_Null ){ + return 0; + } + if( flags&MEM_Int ){ + /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */ +# define MAX_6BYTE ((((i64)0x00008000)<<32)-1) + i64 i = pMem->u.i; + u64 u; + if( i<0 ){ + if( i<(-MAX_6BYTE) ) return 6; + /* Previous test prevents: u = -(-9223372036854775808) */ + u = -i; + }else{ + u = i; + } + if( u<=127 ){ + return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1; + } + if( u<=32767 ) return 2; + if( u<=8388607 ) return 3; + if( u<=2147483647 ) return 4; + if( u<=MAX_6BYTE ) return 5; + return 6; + } + if( flags&MEM_Real ){ + return 7; + } + assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) ); + n = pMem->n; + if( flags & MEM_Zero ){ + n += pMem->u.nZero; + } + assert( n>=0 ); + return ((n*2) + 12 + ((flags&MEM_Str)!=0)); +} + +/* +** Return the length of the data corresponding to the supplied serial-type. +*/ +SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){ + if( serial_type>=12 ){ + return (serial_type-12)/2; + }else{ + static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 }; + return aSize[serial_type]; + } +} + +/* +** If we are on an architecture with mixed-endian floating +** points (ex: ARM7) then swap the lower 4 bytes with the +** upper 4 bytes. Return the result. +** +** For most architectures, this is a no-op. +** +** (later): It is reported to me that the mixed-endian problem +** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems +** that early versions of GCC stored the two words of a 64-bit +** float in the wrong order. And that error has been propagated +** ever since. The blame is not necessarily with GCC, though. +** GCC might have just copying the problem from a prior compiler. +** I am also told that newer versions of GCC that follow a different +** ABI get the byte order right. +** +** Developers using SQLite on an ARM7 should compile and run their +** application using -DSQLITE_DEBUG=1 at least once. With DEBUG +** enabled, some asserts below will ensure that the byte order of +** floating point values is correct. +** +** (2007-08-30) Frank van Vugt has studied this problem closely +** and has send his findings to the SQLite developers. Frank +** writes that some Linux kernels offer floating point hardware +** emulation that uses only 32-bit mantissas instead of a full +** 48-bits as required by the IEEE standard. (This is the +** CONFIG_FPE_FASTFPE option.) On such systems, floating point +** byte swapping becomes very complicated. To avoid problems, +** the necessary byte swapping is carried out using a 64-bit integer +** rather than a 64-bit float. Frank assures us that the code here +** works for him. We, the developers, have no way to independently +** verify this, but Frank seems to know what he is talking about +** so we trust him. +*/ +#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT +static u64 floatSwap(u64 in){ + union { + u64 r; + u32 i[2]; + } u; + u32 t; + + u.r = in; + t = u.i[0]; + u.i[0] = u.i[1]; + u.i[1] = t; + return u.r; +} +# define swapMixedEndianFloat(X) X = floatSwap(X) +#else +# define swapMixedEndianFloat(X) +#endif + +/* +** Write the serialized data blob for the value stored in pMem into +** buf. It is assumed that the caller has allocated sufficient space. +** Return the number of bytes written. +** +** nBuf is the amount of space left in buf[]. nBuf must always be +** large enough to hold the entire field. Except, if the field is +** a blob with a zero-filled tail, then buf[] might be just the right +** size to hold everything except for the zero-filled tail. If buf[] +** is only big enough to hold the non-zero prefix, then only write that +** prefix into buf[]. But if buf[] is large enough to hold both the +** prefix and the tail then write the prefix and set the tail to all +** zeros. +** +** Return the number of bytes actually written into buf[]. The number +** of bytes in the zero-filled tail is included in the return value only +** if those bytes were zeroed in buf[]. +*/ +SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){ + u32 serial_type = sqlite3VdbeSerialType(pMem, file_format); + u32 len; + + /* Integer and Real */ + if( serial_type<=7 && serial_type>0 ){ + u64 v; + u32 i; + if( serial_type==7 ){ + assert( sizeof(v)==sizeof(pMem->r) ); + memcpy(&v, &pMem->r, sizeof(v)); + swapMixedEndianFloat(v); + }else{ + v = pMem->u.i; + } + len = i = sqlite3VdbeSerialTypeLen(serial_type); + assert( len<=(u32)nBuf ); + while( i-- ){ + buf[i] = (u8)(v&0xFF); + v >>= 8; + } + return len; + } + + /* String or blob */ + if( serial_type>=12 ){ + assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0) + == (int)sqlite3VdbeSerialTypeLen(serial_type) ); + assert( pMem->n<=nBuf ); + len = pMem->n; + memcpy(buf, pMem->z, len); + if( pMem->flags & MEM_Zero ){ + len += pMem->u.nZero; + assert( nBuf>=0 ); + if( len > (u32)nBuf ){ + len = (u32)nBuf; + } + memset(&buf[pMem->n], 0, len-pMem->n); + } + return len; + } + + /* NULL or constants 0 or 1 */ + return 0; +} + +/* +** Deserialize the data blob pointed to by buf as serial type serial_type +** and store the result in pMem. Return the number of bytes read. +*/ +SQLITE_PRIVATE u32 sqlite3VdbeSerialGet( + const unsigned char *buf, /* Buffer to deserialize from */ + u32 serial_type, /* Serial type to deserialize */ + Mem *pMem /* Memory cell to write value into */ +){ + switch( serial_type ){ + case 10: /* Reserved for future use */ + case 11: /* Reserved for future use */ + case 0: { /* NULL */ + pMem->flags = MEM_Null; + break; + } + case 1: { /* 1-byte signed integer */ + pMem->u.i = (signed char)buf[0]; + pMem->flags = MEM_Int; + return 1; + } + case 2: { /* 2-byte signed integer */ + pMem->u.i = (((signed char)buf[0])<<8) | buf[1]; + pMem->flags = MEM_Int; + return 2; + } + case 3: { /* 3-byte signed integer */ + pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2]; + pMem->flags = MEM_Int; + return 3; + } + case 4: { /* 4-byte signed integer */ + pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3]; + pMem->flags = MEM_Int; + return 4; + } + case 5: { /* 6-byte signed integer */ + u64 x = (((signed char)buf[0])<<8) | buf[1]; + u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5]; + x = (x<<32) | y; + pMem->u.i = *(i64*)&x; + pMem->flags = MEM_Int; + return 6; + } + case 6: /* 8-byte signed integer */ + case 7: { /* IEEE floating point */ + u64 x; + u32 y; +#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT) + /* Verify that integers and floating point values use the same + ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is + ** defined that 64-bit floating point values really are mixed + ** endian. + */ + static const u64 t1 = ((u64)0x3ff00000)<<32; + static const double r1 = 1.0; + u64 t2 = t1; + swapMixedEndianFloat(t2); + assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 ); +#endif + + x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3]; + y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7]; + x = (x<<32) | y; + if( serial_type==6 ){ + pMem->u.i = *(i64*)&x; + pMem->flags = MEM_Int; + }else{ + assert( sizeof(x)==8 && sizeof(pMem->r)==8 ); + swapMixedEndianFloat(x); + memcpy(&pMem->r, &x, sizeof(x)); + pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real; + } + return 8; + } + case 8: /* Integer 0 */ + case 9: { /* Integer 1 */ + pMem->u.i = serial_type-8; + pMem->flags = MEM_Int; + return 0; + } + default: { + u32 len = (serial_type-12)/2; + pMem->z = (char *)buf; + pMem->n = len; + pMem->xDel = 0; + if( serial_type&0x01 ){ + pMem->flags = MEM_Str | MEM_Ephem; + }else{ + pMem->flags = MEM_Blob | MEM_Ephem; + } + return len; + } + } + return 0; +} + +/* +** This routine is used to allocate sufficient space for an UnpackedRecord +** structure large enough to be used with sqlite3VdbeRecordUnpack() if +** the first argument is a pointer to KeyInfo structure pKeyInfo. +** +** The space is either allocated using sqlite3DbMallocRaw() or from within +** the unaligned buffer passed via the second and third arguments (presumably +** stack space). If the former, then *ppFree is set to a pointer that should +** be eventually freed by the caller using sqlite3DbFree(). Or, if the +** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL +** before returning. +** +** If an OOM error occurs, NULL is returned. +*/ +SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord( + KeyInfo *pKeyInfo, /* Description of the record */ + char *pSpace, /* Unaligned space available */ + int szSpace, /* Size of pSpace[] in bytes */ + char **ppFree /* OUT: Caller should free this pointer */ +){ + UnpackedRecord *p; /* Unpacked record to return */ + int nOff; /* Increment pSpace by nOff to align it */ + int nByte; /* Number of bytes required for *p */ + + /* We want to shift the pointer pSpace up such that it is 8-byte aligned. + ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift + ** it by. If pSpace is already 8-byte aligned, nOff should be zero. + */ + nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7; + nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1); + if( nByte>szSpace+nOff ){ + p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte); + *ppFree = (char *)p; + if( !p ) return 0; + }else{ + p = (UnpackedRecord*)&pSpace[nOff]; + *ppFree = 0; + } + + p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))]; + assert( pKeyInfo->aSortOrder!=0 ); + p->pKeyInfo = pKeyInfo; + p->nField = pKeyInfo->nField + 1; + return p; +} + +/* +** Given the nKey-byte encoding of a record in pKey[], populate the +** UnpackedRecord structure indicated by the fourth argument with the +** contents of the decoded record. +*/ +SQLITE_PRIVATE void sqlite3VdbeRecordUnpack( + KeyInfo *pKeyInfo, /* Information about the record format */ + int nKey, /* Size of the binary record */ + const void *pKey, /* The binary record */ + UnpackedRecord *p /* Populate this structure before returning. */ +){ + const unsigned char *aKey = (const unsigned char *)pKey; + int d; + u32 idx; /* Offset in aKey[] to read from */ + u16 u; /* Unsigned loop counter */ + u32 szHdr; + Mem *pMem = p->aMem; + + p->flags = 0; + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + idx = getVarint32(aKey, szHdr); + d = szHdr; + u = 0; + while( idxnField && d<=nKey ){ + u32 serial_type; + + idx += getVarint32(&aKey[idx], serial_type); + pMem->enc = pKeyInfo->enc; + pMem->db = pKeyInfo->db; + /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */ + pMem->zMalloc = 0; + d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem); + pMem++; + u++; + } + assert( u<=pKeyInfo->nField + 1 ); + p->nField = u; +} + +/* +** This function compares the two table rows or index records +** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero +** or positive integer if key1 is less than, equal to or +** greater than key2. The {nKey1, pKey1} key must be a blob +** created by th OP_MakeRecord opcode of the VDBE. The pPKey2 +** key must be a parsed key such as obtained from +** sqlite3VdbeParseRecord. +** +** Key1 and Key2 do not have to contain the same number of fields. +** The key with fewer fields is usually compares less than the +** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set +** and the common prefixes are equal, then key1 is less than key2. +** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are +** equal, then the keys are considered to be equal and +** the parts beyond the common prefix are ignored. +*/ +SQLITE_PRIVATE int sqlite3VdbeRecordCompare( + int nKey1, const void *pKey1, /* Left key */ + UnpackedRecord *pPKey2 /* Right key */ +){ + u32 d1; /* Offset into aKey[] of next data element */ + u32 idx1; /* Offset into aKey[] of next header element */ + u32 szHdr1; /* Number of bytes in header */ + int i = 0; + int rc = 0; + const unsigned char *aKey1 = (const unsigned char *)pKey1; + KeyInfo *pKeyInfo; + Mem mem1; + + pKeyInfo = pPKey2->pKeyInfo; + mem1.enc = pKeyInfo->enc; + mem1.db = pKeyInfo->db; + /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */ + VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */ + + /* Compilers may complain that mem1.u.i is potentially uninitialized. + ** We could initialize it, as shown here, to silence those complaints. + ** But in fact, mem1.u.i will never actually be used uninitialized, and doing + ** the unnecessary initialization has a measurable negative performance + ** impact, since this routine is a very high runner. And so, we choose + ** to ignore the compiler warnings and leave this variable uninitialized. + */ + /* mem1.u.i = 0; // not needed, here to silence compiler warning */ + + idx1 = getVarint32(aKey1, szHdr1); + d1 = szHdr1; + assert( pKeyInfo->nField+1>=pPKey2->nField ); + assert( pKeyInfo->aSortOrder!=0 ); + while( idx1nField ){ + u32 serial_type1; + + /* Read the serial types for the next element in each key. */ + idx1 += getVarint32( aKey1+idx1, serial_type1 ); + + /* Verify that there is enough key space remaining to avoid + ** a buffer overread. The "d1+serial_type1+2" subexpression will + ** always be greater than or equal to the amount of required key space. + ** Use that approximation to avoid the more expensive call to + ** sqlite3VdbeSerialTypeLen() in the common case. + */ + if( d1+serial_type1+2>(u32)nKey1 + && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 + ){ + break; + } + + /* Extract the values to be compared. + */ + d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1); + + /* Do the comparison + */ + rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]); + if( rc!=0 ){ + assert( mem1.zMalloc==0 ); /* See comment below */ + + /* Invert the result if we are using DESC sort order. */ + if( pKeyInfo->aSortOrder[i] ){ + rc = -rc; + } + + /* If the PREFIX_SEARCH flag is set and all fields except the final + ** rowid field were equal, then clear the PREFIX_SEARCH flag and set + ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1). + ** This is used by the OP_IsUnique opcode. + */ + if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){ + assert( idx1==szHdr1 && rc ); + assert( mem1.flags & MEM_Int ); + pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH; + pPKey2->rowid = mem1.u.i; + } + + return rc; + } + i++; + } + + /* No memory allocation is ever used on mem1. Prove this using + ** the following assert(). If the assert() fails, it indicates a + ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). + */ + assert( mem1.zMalloc==0 ); + + /* rc==0 here means that one of the keys ran out of fields and + ** all the fields up to that point were equal. If the UNPACKED_INCRKEY + ** flag is set, then break the tie by treating key2 as larger. + ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes + ** are considered to be equal. Otherwise, the longer key is the + ** larger. As it happens, the pPKey2 will always be the longer + ** if there is a difference. + */ + assert( rc==0 ); + if( pPKey2->flags & UNPACKED_INCRKEY ){ + rc = -1; + }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){ + /* Leave rc==0 */ + }else if( idx1m.n) ){ + goto idx_rowid_corruption; + } + + /* The last field of the index should be an integer - the ROWID. + ** Verify that the last entry really is an integer. */ + (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid); + testcase( typeRowid==1 ); + testcase( typeRowid==2 ); + testcase( typeRowid==3 ); + testcase( typeRowid==4 ); + testcase( typeRowid==5 ); + testcase( typeRowid==6 ); + testcase( typeRowid==8 ); + testcase( typeRowid==9 ); + if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){ + goto idx_rowid_corruption; + } + lenRowid = sqlite3VdbeSerialTypeLen(typeRowid); + testcase( (u32)m.n==szHdr+lenRowid ); + if( unlikely((u32)m.npCursor; + Mem m; + + assert( sqlite3BtreeCursorIsValid(pCur) ); + VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey); + assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */ + /* nCellKey will always be between 0 and 0xffffffff because of the say + ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */ + if( nCellKey<=0 || nCellKey>0x7fffffff ){ + *res = 0; + return SQLITE_CORRUPT_BKPT; + } + memset(&m, 0, sizeof(m)); + rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m); + if( rc ){ + return rc; + } + assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH ); + *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked); + sqlite3VdbeMemRelease(&m); + return SQLITE_OK; +} + +/* +** This routine sets the value to be returned by subsequent calls to +** sqlite3_changes() on the database handle 'db'. +*/ +SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){ + assert( sqlite3_mutex_held(db->mutex) ); + db->nChange = nChange; + db->nTotalChange += nChange; +} + +/* +** Set a flag in the vdbe to update the change counter when it is finalised +** or reset. +*/ +SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){ + v->changeCntOn = 1; +} + +/* +** Mark every prepared statement associated with a database connection +** as expired. +** +** An expired statement means that recompilation of the statement is +** recommend. Statements expire when things happen that make their +** programs obsolete. Removing user-defined functions or collating +** sequences, or changing an authorization function are the types of +** things that make prepared statements obsolete. +*/ +SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){ + Vdbe *p; + for(p = db->pVdbe; p; p=p->pNext){ + p->expired = 1; + } +} + +/* +** Return the database associated with the Vdbe. +*/ +SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){ + return v->db; +} + +/* +** Return a pointer to an sqlite3_value structure containing the value bound +** parameter iVar of VM v. Except, if the value is an SQL NULL, return +** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_* +** constants) to the value before returning it. +** +** The returned value must be freed by the caller using sqlite3ValueFree(). +*/ +SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){ + assert( iVar>0 ); + if( v ){ + Mem *pMem = &v->aVar[iVar-1]; + if( 0==(pMem->flags & MEM_Null) ){ + sqlite3_value *pRet = sqlite3ValueNew(v->db); + if( pRet ){ + sqlite3VdbeMemCopy((Mem *)pRet, pMem); + sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8); + sqlite3VdbeMemStoreType((Mem *)pRet); + } + return pRet; + } + } + return 0; +} + +/* +** Configure SQL variable iVar so that binding a new value to it signals +** to sqlite3_reoptimize() that re-preparing the statement may result +** in a better query plan. +*/ +SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){ + assert( iVar>0 ); + if( iVar>32 ){ + v->expmask = 0xffffffff; + }else{ + v->expmask |= ((u32)1 << (iVar-1)); + } +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored +** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored +** in memory obtained from sqlite3DbMalloc). +*/ +SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){ + sqlite3 *db = p->db; + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg); + sqlite3_free(pVtab->zErrMsg); + pVtab->zErrMsg = 0; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/************** End of vdbeaux.c *********************************************/ +/************** Begin file vdbeapi.c *****************************************/ +/* +** 2004 May 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code use to implement APIs that are part of the +** VDBE. +*/ + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** Return TRUE (non-zero) of the statement supplied as an argument needs +** to be recompiled. A statement needs to be recompiled whenever the +** execution environment changes in a way that would alter the program +** that sqlite3_prepare() generates. For example, if new functions or +** collating sequences are registered or if an authorizer function is +** added or changed. +*/ +SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){ + Vdbe *p = (Vdbe*)pStmt; + return p==0 || p->expired; +} +#endif + +/* +** Check on a Vdbe to make sure it has not been finalized. Log +** an error and return true if it has been finalized (or is otherwise +** invalid). Return false if it is ok. +*/ +static int vdbeSafety(Vdbe *p){ + if( p->db==0 ){ + sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement"); + return 1; + }else{ + return 0; + } +} +static int vdbeSafetyNotNull(Vdbe *p){ + if( p==0 ){ + sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement"); + return 1; + }else{ + return vdbeSafety(p); + } +} + +/* +** The following routine destroys a virtual machine that is created by +** the sqlite3_compile() routine. The integer returned is an SQLITE_ +** success/failure code that describes the result of executing the virtual +** machine. +** +** This routine sets the error code and string returned by +** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). +*/ +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){ + int rc; + if( pStmt==0 ){ + /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL + ** pointer is a harmless no-op. */ + rc = SQLITE_OK; + }else{ + Vdbe *v = (Vdbe*)pStmt; + sqlite3 *db = v->db; + if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT; + sqlite3_mutex_enter(db->mutex); + rc = sqlite3VdbeFinalize(v); + rc = sqlite3ApiExit(db, rc); + sqlite3LeaveMutexAndCloseZombie(db); + } + return rc; +} + +/* +** Terminate the current execution of an SQL statement and reset it +** back to its starting state so that it can be reused. A success code from +** the prior execution is returned. +** +** This routine sets the error code and string returned by +** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). +*/ +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){ + int rc; + if( pStmt==0 ){ + rc = SQLITE_OK; + }else{ + Vdbe *v = (Vdbe*)pStmt; + sqlite3_mutex_enter(v->db->mutex); + rc = sqlite3VdbeReset(v); + sqlite3VdbeRewind(v); + assert( (rc & (v->db->errMask))==rc ); + rc = sqlite3ApiExit(v->db, rc); + sqlite3_mutex_leave(v->db->mutex); + } + return rc; +} + +/* +** Set all the parameters in the compiled SQL statement to NULL. +*/ +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){ + int i; + int rc = SQLITE_OK; + Vdbe *p = (Vdbe*)pStmt; +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex; +#endif + sqlite3_mutex_enter(mutex); + for(i=0; inVar; i++){ + sqlite3VdbeMemRelease(&p->aVar[i]); + p->aVar[i].flags = MEM_Null; + } + if( p->isPrepareV2 && p->expmask ){ + p->expired = 1; + } + sqlite3_mutex_leave(mutex); + return rc; +} + + +/**************************** sqlite3_value_ ******************************* +** The following routines extract information from a Mem or sqlite3_value +** structure. +*/ +SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){ + Mem *p = (Mem*)pVal; + if( p->flags & (MEM_Blob|MEM_Str) ){ + sqlite3VdbeMemExpandBlob(p); + p->flags &= ~MEM_Str; + p->flags |= MEM_Blob; + return p->n ? p->z : 0; + }else{ + return sqlite3_value_text(pVal); + } +} +SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){ + return sqlite3ValueBytes(pVal, SQLITE_UTF8); +} +SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){ + return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE); +} +SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){ + return sqlite3VdbeRealValue((Mem*)pVal); +} +SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){ + return (int)sqlite3VdbeIntValue((Mem*)pVal); +} +SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){ + return sqlite3VdbeIntValue((Mem*)pVal); +} +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){ + return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8); +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){ + return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); +} +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){ + return sqlite3ValueText(pVal, SQLITE_UTF16BE); +} +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){ + return sqlite3ValueText(pVal, SQLITE_UTF16LE); +} +#endif /* SQLITE_OMIT_UTF16 */ +SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){ + return pVal->type; +} + +/**************************** sqlite3_result_ ******************************* +** The following routines are used by user-defined functions to specify +** the function result. +** +** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the +** result as a string or blob but if the string or blob is too large, it +** then sets the error code to SQLITE_TOOBIG +*/ +static void setResultStrOrError( + sqlite3_context *pCtx, /* Function context */ + const char *z, /* String pointer */ + int n, /* Bytes in string, or negative */ + u8 enc, /* Encoding of z. 0 for BLOBs */ + void (*xDel)(void*) /* Destructor function */ +){ + if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){ + sqlite3_result_error_toobig(pCtx); + } +} +SQLITE_API void sqlite3_result_blob( + sqlite3_context *pCtx, + const void *z, + int n, + void (*xDel)(void *) +){ + assert( n>=0 ); + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, 0, xDel); +} +SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetDouble(&pCtx->s, rVal); +} +SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + pCtx->isError = SQLITE_ERROR; + pCtx->fErrorOrAux = 1; + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT); +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + pCtx->isError = SQLITE_ERROR; + pCtx->fErrorOrAux = 1; + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT); +} +#endif +SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal); +} +SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetInt64(&pCtx->s, iVal); +} +SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetNull(&pCtx->s); +} +SQLITE_API void sqlite3_result_text( + sqlite3_context *pCtx, + const char *z, + int n, + void (*xDel)(void *) +){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel); +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API void sqlite3_result_text16( + sqlite3_context *pCtx, + const void *z, + int n, + void (*xDel)(void *) +){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel); +} +SQLITE_API void sqlite3_result_text16be( + sqlite3_context *pCtx, + const void *z, + int n, + void (*xDel)(void *) +){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel); +} +SQLITE_API void sqlite3_result_text16le( + sqlite3_context *pCtx, + const void *z, + int n, + void (*xDel)(void *) +){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel); +} +#endif /* SQLITE_OMIT_UTF16 */ +SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemCopy(&pCtx->s, pValue); +} +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetZeroBlob(&pCtx->s, n); +} +SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){ + pCtx->isError = errCode; + pCtx->fErrorOrAux = 1; + if( pCtx->s.flags & MEM_Null ){ + sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, + SQLITE_UTF8, SQLITE_STATIC); + } +} + +/* Force an SQLITE_TOOBIG error. */ +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + pCtx->isError = SQLITE_TOOBIG; + pCtx->fErrorOrAux = 1; + sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, + SQLITE_UTF8, SQLITE_STATIC); +} + +/* An SQLITE_NOMEM error. */ +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetNull(&pCtx->s); + pCtx->isError = SQLITE_NOMEM; + pCtx->fErrorOrAux = 1; + pCtx->s.db->mallocFailed = 1; +} + +/* +** This function is called after a transaction has been committed. It +** invokes callbacks registered with sqlite3_wal_hook() as required. +*/ +static int doWalCallbacks(sqlite3 *db){ + int rc = SQLITE_OK; +#ifndef SQLITE_OMIT_WAL + int i; + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt)); + if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){ + rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry); + } + } + } +#endif + return rc; +} + +/* +** Execute the statement pStmt, either until a row of data is ready, the +** statement is completely executed or an error occurs. +** +** This routine implements the bulk of the logic behind the sqlite_step() +** API. The only thing omitted is the automatic recompile if a +** schema change has occurred. That detail is handled by the +** outer sqlite3_step() wrapper procedure. +*/ +static int sqlite3Step(Vdbe *p){ + sqlite3 *db; + int rc; + + assert(p); + if( p->magic!=VDBE_MAGIC_RUN ){ + /* We used to require that sqlite3_reset() be called before retrying + ** sqlite3_step() after any error or after SQLITE_DONE. But beginning + ** with version 3.7.0, we changed this so that sqlite3_reset() would + ** be called automatically instead of throwing the SQLITE_MISUSE error. + ** This "automatic-reset" change is not technically an incompatibility, + ** since any application that receives an SQLITE_MISUSE is broken by + ** definition. + ** + ** Nevertheless, some published applications that were originally written + ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE + ** returns, and those were broken by the automatic-reset change. As a + ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the + ** legacy behavior of returning SQLITE_MISUSE for cases where the + ** previous sqlite3_step() returned something other than a SQLITE_LOCKED + ** or SQLITE_BUSY error. + */ +#ifdef SQLITE_OMIT_AUTORESET + if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){ + sqlite3_reset((sqlite3_stmt*)p); + }else{ + return SQLITE_MISUSE_BKPT; + } +#else + sqlite3_reset((sqlite3_stmt*)p); +#endif + } + + /* Check that malloc() has not failed. If it has, return early. */ + db = p->db; + if( db->mallocFailed ){ + p->rc = SQLITE_NOMEM; + return SQLITE_NOMEM; + } + + if( p->pc<=0 && p->expired ){ + p->rc = SQLITE_SCHEMA; + rc = SQLITE_ERROR; + goto end_of_step; + } + if( p->pc<0 ){ + /* If there are no other statements currently running, then + ** reset the interrupt flag. This prevents a call to sqlite3_interrupt + ** from interrupting a statement that has not yet started. + */ + if( db->nVdbeActive==0 ){ + db->u1.isInterrupted = 0; + } + + assert( db->nVdbeWrite>0 || db->autoCommit==0 + || (db->nDeferredCons==0 && db->nDeferredImmCons==0) + ); + +#ifndef SQLITE_OMIT_TRACE + if( db->xProfile && !db->init.busy ){ + sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime); + } +#endif + + db->nVdbeActive++; + if( p->readOnly==0 ) db->nVdbeWrite++; + if( p->bIsReader ) db->nVdbeRead++; + p->pc = 0; + } +#ifndef SQLITE_OMIT_EXPLAIN + if( p->explain ){ + rc = sqlite3VdbeList(p); + }else +#endif /* SQLITE_OMIT_EXPLAIN */ + { + db->nVdbeExec++; + rc = sqlite3VdbeExec(p); + db->nVdbeExec--; + } + +#ifndef SQLITE_OMIT_TRACE + /* Invoke the profile callback if there is one + */ + if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){ + sqlite3_int64 iNow; + sqlite3OsCurrentTimeInt64(db->pVfs, &iNow); + db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000); + } +#endif + + if( rc==SQLITE_DONE ){ + assert( p->rc==SQLITE_OK ); + p->rc = doWalCallbacks(db); + if( p->rc!=SQLITE_OK ){ + rc = SQLITE_ERROR; + } + } + + db->errCode = rc; + if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){ + p->rc = SQLITE_NOMEM; + } +end_of_step: + /* At this point local variable rc holds the value that should be + ** returned if this statement was compiled using the legacy + ** sqlite3_prepare() interface. According to the docs, this can only + ** be one of the values in the first assert() below. Variable p->rc + ** contains the value that would be returned if sqlite3_finalize() + ** were called on statement p. + */ + assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR + || rc==SQLITE_BUSY || rc==SQLITE_MISUSE + ); + assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE ); + if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ + /* If this statement was prepared using sqlite3_prepare_v2(), and an + ** error has occurred, then return the error code in p->rc to the + ** caller. Set the error code in the database handle to the same value. + */ + rc = sqlite3VdbeTransferError(p); + } + return (rc&db->errMask); +} + +/* +** This is the top-level implementation of sqlite3_step(). Call +** sqlite3Step() to do most of the work. If a schema error occurs, +** call sqlite3Reprepare() and try again. +*/ +SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){ + int rc = SQLITE_OK; /* Result from sqlite3Step() */ + int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */ + Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */ + int cnt = 0; /* Counter to prevent infinite loop of reprepares */ + sqlite3 *db; /* The database connection */ + + if( vdbeSafetyNotNull(v) ){ + return SQLITE_MISUSE_BKPT; + } + db = v->db; + sqlite3_mutex_enter(db->mutex); + v->doingRerun = 0; + while( (rc = sqlite3Step(v))==SQLITE_SCHEMA + && cnt++ < SQLITE_MAX_SCHEMA_RETRY + && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){ + sqlite3_reset(pStmt); + v->doingRerun = 1; + assert( v->expired==0 ); + } + if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){ + /* This case occurs after failing to recompile an sql statement. + ** The error message from the SQL compiler has already been loaded + ** into the database handle. This block copies the error message + ** from the database handle into the statement and sets the statement + ** program counter to 0 to ensure that when the statement is + ** finalized or reset the parser error message is available via + ** sqlite3_errmsg() and sqlite3_errcode(). + */ + const char *zErr = (const char *)sqlite3_value_text(db->pErr); + sqlite3DbFree(db, v->zErrMsg); + if( !db->mallocFailed ){ + v->zErrMsg = sqlite3DbStrDup(db, zErr); + v->rc = rc2; + } else { + v->zErrMsg = 0; + v->rc = rc = SQLITE_NOMEM; + } + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + + +/* +** Extract the user data from a sqlite3_context structure and return a +** pointer to it. +*/ +SQLITE_API void *sqlite3_user_data(sqlite3_context *p){ + assert( p && p->pFunc ); + return p->pFunc->pUserData; +} + +/* +** Extract the user data from a sqlite3_context structure and return a +** pointer to it. +** +** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface +** returns a copy of the pointer to the database connection (the 1st +** parameter) of the sqlite3_create_function() and +** sqlite3_create_function16() routines that originally registered the +** application defined function. +*/ +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){ + assert( p && p->pFunc ); + return p->s.db; +} + +/* +** Return the current time for a statement +*/ +SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){ + Vdbe *v = p->pVdbe; + int rc; + if( v->iCurrentTime==0 ){ + rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime); + if( rc ) v->iCurrentTime = 0; + } + return v->iCurrentTime; +} + +/* +** The following is the implementation of an SQL function that always +** fails with an error message stating that the function is used in the +** wrong context. The sqlite3_overload_function() API might construct +** SQL function that use this routine so that the functions will exist +** for name resolution but are actually overloaded by the xFindFunction +** method of virtual tables. +*/ +SQLITE_PRIVATE void sqlite3InvalidFunction( + sqlite3_context *context, /* The function calling context */ + int NotUsed, /* Number of arguments to the function */ + sqlite3_value **NotUsed2 /* Value of each argument */ +){ + const char *zName = context->pFunc->zName; + char *zErr; + UNUSED_PARAMETER2(NotUsed, NotUsed2); + zErr = sqlite3_mprintf( + "unable to use function %s in the requested context", zName); + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); +} + +/* +** Allocate or return the aggregate context for a user function. A new +** context is allocated on the first call. Subsequent calls return the +** same context that was returned on prior calls. +*/ +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){ + Mem *pMem; + assert( p && p->pFunc && p->pFunc->xStep ); + assert( sqlite3_mutex_held(p->s.db->mutex) ); + pMem = p->pMem; + testcase( nByte<0 ); + if( (pMem->flags & MEM_Agg)==0 ){ + if( nByte<=0 ){ + sqlite3VdbeMemReleaseExternal(pMem); + pMem->flags = MEM_Null; + pMem->z = 0; + }else{ + sqlite3VdbeMemGrow(pMem, nByte, 0); + pMem->flags = MEM_Agg; + pMem->u.pDef = p->pFunc; + if( pMem->z ){ + memset(pMem->z, 0, nByte); + } + } + } + return (void*)pMem->z; +} + +/* +** Return the auxilary data pointer, if any, for the iArg'th argument to +** the user-function defined by pCtx. +*/ +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){ + AuxData *pAuxData; + + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ + if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; + } + + return (pAuxData ? pAuxData->pAux : 0); +} + +/* +** Set the auxilary data pointer and delete function, for the iArg'th +** argument to the user-function defined by pCtx. Any previous value is +** deleted by calling the delete function specified when it was set. +*/ +SQLITE_API void sqlite3_set_auxdata( + sqlite3_context *pCtx, + int iArg, + void *pAux, + void (*xDelete)(void*) +){ + AuxData *pAuxData; + Vdbe *pVdbe = pCtx->pVdbe; + + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + if( iArg<0 ) goto failed; + + for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ + if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; + } + if( pAuxData==0 ){ + pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData)); + if( !pAuxData ) goto failed; + pAuxData->iOp = pCtx->iOp; + pAuxData->iArg = iArg; + pAuxData->pNext = pVdbe->pAuxData; + pVdbe->pAuxData = pAuxData; + if( pCtx->fErrorOrAux==0 ){ + pCtx->isError = 0; + pCtx->fErrorOrAux = 1; + } + }else if( pAuxData->xDelete ){ + pAuxData->xDelete(pAuxData->pAux); + } + + pAuxData->pAux = pAux; + pAuxData->xDelete = xDelete; + return; + +failed: + if( xDelete ){ + xDelete(pAux); + } +} + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** Return the number of times the Step function of a aggregate has been +** called. +** +** This function is deprecated. Do not use it for new code. It is +** provide only to avoid breaking legacy code. New aggregate function +** implementations should keep their own counts within their aggregate +** context. +*/ +SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){ + assert( p && p->pMem && p->pFunc && p->pFunc->xStep ); + return p->pMem->n; +} +#endif + +/* +** Return the number of columns in the result set for the statement pStmt. +*/ +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){ + Vdbe *pVm = (Vdbe *)pStmt; + return pVm ? pVm->nResColumn : 0; +} + +/* +** Return the number of values available from the current row of the +** currently executing statement pStmt. +*/ +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){ + Vdbe *pVm = (Vdbe *)pStmt; + if( pVm==0 || pVm->pResultSet==0 ) return 0; + return pVm->nResColumn; +} + + +/* +** Check to see if column iCol of the given statement is valid. If +** it is, return a pointer to the Mem for the value of that column. +** If iCol is not valid, return a pointer to a Mem which has a value +** of NULL. +*/ +static Mem *columnMem(sqlite3_stmt *pStmt, int i){ + Vdbe *pVm; + Mem *pOut; + + pVm = (Vdbe *)pStmt; + if( pVm && pVm->pResultSet!=0 && inResColumn && i>=0 ){ + sqlite3_mutex_enter(pVm->db->mutex); + pOut = &pVm->pResultSet[i]; + }else{ + /* If the value passed as the second argument is out of range, return + ** a pointer to the following static Mem object which contains the + ** value SQL NULL. Even though the Mem structure contains an element + ** of type i64, on certain architectures (x86) with certain compiler + ** switches (-Os), gcc may align this Mem object on a 4-byte boundary + ** instead of an 8-byte one. This all works fine, except that when + ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s + ** that a Mem structure is located on an 8-byte boundary. To prevent + ** these assert()s from failing, when building with SQLITE_DEBUG defined + ** using gcc, we force nullMem to be 8-byte aligned using the magical + ** __attribute__((aligned(8))) macro. */ + static const Mem nullMem +#if defined(SQLITE_DEBUG) && defined(__GNUC__) + __attribute__((aligned(8))) +#endif + = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0, +#ifdef SQLITE_DEBUG + 0, 0, /* pScopyFrom, pFiller */ +#endif + 0, 0 }; + + if( pVm && ALWAYS(pVm->db) ){ + sqlite3_mutex_enter(pVm->db->mutex); + sqlite3Error(pVm->db, SQLITE_RANGE, 0); + } + pOut = (Mem*)&nullMem; + } + return pOut; +} + +/* +** This function is called after invoking an sqlite3_value_XXX function on a +** column value (i.e. a value returned by evaluating an SQL expression in the +** select list of a SELECT statement) that may cause a malloc() failure. If +** malloc() has failed, the threads mallocFailed flag is cleared and the result +** code of statement pStmt set to SQLITE_NOMEM. +** +** Specifically, this is called from within: +** +** sqlite3_column_int() +** sqlite3_column_int64() +** sqlite3_column_text() +** sqlite3_column_text16() +** sqlite3_column_real() +** sqlite3_column_bytes() +** sqlite3_column_bytes16() +** sqiite3_column_blob() +*/ +static void columnMallocFailure(sqlite3_stmt *pStmt) +{ + /* If malloc() failed during an encoding conversion within an + ** sqlite3_column_XXX API, then set the return code of the statement to + ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR + ** and _finalize() will return NOMEM. + */ + Vdbe *p = (Vdbe *)pStmt; + if( p ){ + p->rc = sqlite3ApiExit(p->db, p->rc); + sqlite3_mutex_leave(p->db->mutex); + } +} + +/**************************** sqlite3_column_ ******************************* +** The following routines are used to access elements of the current row +** in the result set. +*/ +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){ + const void *val; + val = sqlite3_value_blob( columnMem(pStmt,i) ); + /* Even though there is no encoding conversion, value_blob() might + ** need to call malloc() to expand the result of a zeroblob() + ** expression. + */ + columnMallocFailure(pStmt); + return val; +} +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){ + int val = sqlite3_value_bytes( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){ + int val = sqlite3_value_bytes16( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){ + double val = sqlite3_value_double( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){ + int val = sqlite3_value_int( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){ + sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){ + const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){ + Mem *pOut = columnMem(pStmt, i); + if( pOut->flags&MEM_Static ){ + pOut->flags &= ~MEM_Static; + pOut->flags |= MEM_Ephem; + } + columnMallocFailure(pStmt); + return (sqlite3_value *)pOut; +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){ + const void *val = sqlite3_value_text16( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +#endif /* SQLITE_OMIT_UTF16 */ +SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){ + int iType = sqlite3_value_type( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return iType; +} + +/* +** Convert the N-th element of pStmt->pColName[] into a string using +** xFunc() then return that string. If N is out of range, return 0. +** +** There are up to 5 names for each column. useType determines which +** name is returned. Here are the names: +** +** 0 The column name as it should be displayed for output +** 1 The datatype name for the column +** 2 The name of the database that the column derives from +** 3 The name of the table that the column derives from +** 4 The name of the table column that the result column derives from +** +** If the result is not a simple column reference (if it is an expression +** or a constant) then useTypes 2, 3, and 4 return NULL. +*/ +static const void *columnName( + sqlite3_stmt *pStmt, + int N, + const void *(*xFunc)(Mem*), + int useType +){ + const void *ret = 0; + Vdbe *p = (Vdbe *)pStmt; + int n; + sqlite3 *db = p->db; + + assert( db!=0 ); + n = sqlite3_column_count(pStmt); + if( N=0 ){ + N += useType*n; + sqlite3_mutex_enter(db->mutex); + assert( db->mallocFailed==0 ); + ret = xFunc(&p->aColName[N]); + /* A malloc may have failed inside of the xFunc() call. If this + ** is the case, clear the mallocFailed flag and return NULL. + */ + if( db->mallocFailed ){ + db->mallocFailed = 0; + ret = 0; + } + sqlite3_mutex_leave(db->mutex); + } + return ret; +} + +/* +** Return the name of the Nth column of the result set returned by SQL +** statement pStmt. +*/ +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME); +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME); +} +#endif + +/* +** Constraint: If you have ENABLE_COLUMN_METADATA then you must +** not define OMIT_DECLTYPE. +*/ +#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA) +# error "Must not define both SQLITE_OMIT_DECLTYPE \ + and SQLITE_ENABLE_COLUMN_METADATA" +#endif + +#ifndef SQLITE_OMIT_DECLTYPE +/* +** Return the column declaration type (if applicable) of the 'i'th column +** of the result set of SQL statement pStmt. +*/ +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE); +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE); +} +#endif /* SQLITE_OMIT_UTF16 */ +#endif /* SQLITE_OMIT_DECLTYPE */ + +#ifdef SQLITE_ENABLE_COLUMN_METADATA +/* +** Return the name of the database from which a result column derives. +** NULL is returned if the result column is an expression or constant or +** anything else which is not an unabiguous reference to a database column. +*/ +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE); +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE); +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Return the name of the table from which a result column derives. +** NULL is returned if the result column is an expression or constant or +** anything else which is not an unabiguous reference to a database column. +*/ +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE); +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE); +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Return the name of the table column from which a result column derives. +** NULL is returned if the result column is an expression or constant or +** anything else which is not an unabiguous reference to a database column. +*/ +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN); +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN); +} +#endif /* SQLITE_OMIT_UTF16 */ +#endif /* SQLITE_ENABLE_COLUMN_METADATA */ + + +/******************************* sqlite3_bind_ *************************** +** +** Routines used to attach values to wildcards in a compiled SQL statement. +*/ +/* +** Unbind the value bound to variable i in virtual machine p. This is the +** the same as binding a NULL value to the column. If the "i" parameter is +** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK. +** +** A successful evaluation of this routine acquires the mutex on p. +** the mutex is released if any kind of error occurs. +** +** The error code stored in database p->db is overwritten with the return +** value in any case. +*/ +static int vdbeUnbind(Vdbe *p, int i){ + Mem *pVar; + if( vdbeSafetyNotNull(p) ){ + return SQLITE_MISUSE_BKPT; + } + sqlite3_mutex_enter(p->db->mutex); + if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){ + sqlite3Error(p->db, SQLITE_MISUSE, 0); + sqlite3_mutex_leave(p->db->mutex); + sqlite3_log(SQLITE_MISUSE, + "bind on a busy prepared statement: [%s]", p->zSql); + return SQLITE_MISUSE_BKPT; + } + if( i<1 || i>p->nVar ){ + sqlite3Error(p->db, SQLITE_RANGE, 0); + sqlite3_mutex_leave(p->db->mutex); + return SQLITE_RANGE; + } + i--; + pVar = &p->aVar[i]; + sqlite3VdbeMemRelease(pVar); + pVar->flags = MEM_Null; + sqlite3Error(p->db, SQLITE_OK, 0); + + /* If the bit corresponding to this variable in Vdbe.expmask is set, then + ** binding a new value to this variable invalidates the current query plan. + ** + ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host + ** parameter in the WHERE clause might influence the choice of query plan + ** for a statement, then the statement will be automatically recompiled, + ** as if there had been a schema change, on the first sqlite3_step() call + ** following any change to the bindings of that parameter. + */ + if( p->isPrepareV2 && + ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff) + ){ + p->expired = 1; + } + return SQLITE_OK; +} + +/* +** Bind a text or BLOB value. +*/ +static int bindText( + sqlite3_stmt *pStmt, /* The statement to bind against */ + int i, /* Index of the parameter to bind */ + const void *zData, /* Pointer to the data to be bound */ + int nData, /* Number of bytes of data to be bound */ + void (*xDel)(void*), /* Destructor for the data */ + u8 encoding /* Encoding for the data */ +){ + Vdbe *p = (Vdbe *)pStmt; + Mem *pVar; + int rc; + + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + if( zData!=0 ){ + pVar = &p->aVar[i-1]; + rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel); + if( rc==SQLITE_OK && encoding!=0 ){ + rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db)); + } + sqlite3Error(p->db, rc, 0); + rc = sqlite3ApiExit(p->db, rc); + } + sqlite3_mutex_leave(p->db->mutex); + }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){ + xDel((void*)zData); + } + return rc; +} + + +/* +** Bind a blob value to an SQL statement variable. +*/ +SQLITE_API int sqlite3_bind_blob( + sqlite3_stmt *pStmt, + int i, + const void *zData, + int nData, + void (*xDel)(void*) +){ + return bindText(pStmt, i, zData, nData, xDel, 0); +} +SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){ + int rc; + Vdbe *p = (Vdbe *)pStmt; + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue); + sqlite3_mutex_leave(p->db->mutex); + } + return rc; +} +SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){ + return sqlite3_bind_int64(p, i, (i64)iValue); +} +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){ + int rc; + Vdbe *p = (Vdbe *)pStmt; + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue); + sqlite3_mutex_leave(p->db->mutex); + } + return rc; +} +SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){ + int rc; + Vdbe *p = (Vdbe*)pStmt; + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + sqlite3_mutex_leave(p->db->mutex); + } + return rc; +} +SQLITE_API int sqlite3_bind_text( + sqlite3_stmt *pStmt, + int i, + const char *zData, + int nData, + void (*xDel)(void*) +){ + return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8); +} +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API int sqlite3_bind_text16( + sqlite3_stmt *pStmt, + int i, + const void *zData, + int nData, + void (*xDel)(void*) +){ + return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE); +} +#endif /* SQLITE_OMIT_UTF16 */ +SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){ + int rc; + switch( pValue->type ){ + case SQLITE_INTEGER: { + rc = sqlite3_bind_int64(pStmt, i, pValue->u.i); + break; + } + case SQLITE_FLOAT: { + rc = sqlite3_bind_double(pStmt, i, pValue->r); + break; + } + case SQLITE_BLOB: { + if( pValue->flags & MEM_Zero ){ + rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero); + }else{ + rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT); + } + break; + } + case SQLITE_TEXT: { + rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT, + pValue->enc); + break; + } + default: { + rc = sqlite3_bind_null(pStmt, i); + break; + } + } + return rc; +} +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){ + int rc; + Vdbe *p = (Vdbe *)pStmt; + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n); + sqlite3_mutex_leave(p->db->mutex); + } + return rc; +} + +/* +** Return the number of wildcards that can be potentially bound to. +** This routine is added to support DBD::SQLite. +*/ +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){ + Vdbe *p = (Vdbe*)pStmt; + return p ? p->nVar : 0; +} + +/* +** Return the name of a wildcard parameter. Return NULL if the index +** is out of range or if the wildcard is unnamed. +** +** The result is always UTF-8. +*/ +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){ + Vdbe *p = (Vdbe*)pStmt; + if( p==0 || i<1 || i>p->nzVar ){ + return 0; + } + return p->azVar[i-1]; +} + +/* +** Given a wildcard parameter name, return the index of the variable +** with that name. If there is no variable with the given name, +** return 0. +*/ +SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){ + int i; + if( p==0 ){ + return 0; + } + if( zName ){ + for(i=0; inzVar; i++){ + const char *z = p->azVar[i]; + if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){ + return i+1; + } + } + } + return 0; +} +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){ + return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName)); +} + +/* +** Transfer all bindings from the first statement over to the second. +*/ +SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ + Vdbe *pFrom = (Vdbe*)pFromStmt; + Vdbe *pTo = (Vdbe*)pToStmt; + int i; + assert( pTo->db==pFrom->db ); + assert( pTo->nVar==pFrom->nVar ); + sqlite3_mutex_enter(pTo->db->mutex); + for(i=0; inVar; i++){ + sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]); + } + sqlite3_mutex_leave(pTo->db->mutex); + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** Deprecated external interface. Internal/core SQLite code +** should call sqlite3TransferBindings. +** +** Is is misuse to call this routine with statements from different +** database connections. But as this is a deprecated interface, we +** will not bother to check for that condition. +** +** If the two statements contain a different number of bindings, then +** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise +** SQLITE_OK is returned. +*/ +SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ + Vdbe *pFrom = (Vdbe*)pFromStmt; + Vdbe *pTo = (Vdbe*)pToStmt; + if( pFrom->nVar!=pTo->nVar ){ + return SQLITE_ERROR; + } + if( pTo->isPrepareV2 && pTo->expmask ){ + pTo->expired = 1; + } + if( pFrom->isPrepareV2 && pFrom->expmask ){ + pFrom->expired = 1; + } + return sqlite3TransferBindings(pFromStmt, pToStmt); +} +#endif + +/* +** Return the sqlite3* database handle to which the prepared statement given +** in the argument belongs. This is the same database handle that was +** the first argument to the sqlite3_prepare() that was used to create +** the statement in the first place. +*/ +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){ + return pStmt ? ((Vdbe*)pStmt)->db : 0; +} + +/* +** Return true if the prepared statement is guaranteed to not modify the +** database. +*/ +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){ + return pStmt ? ((Vdbe*)pStmt)->readOnly : 1; +} + +/* +** Return true if the prepared statement is in need of being reset. +*/ +SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){ + Vdbe *v = (Vdbe*)pStmt; + return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN; +} + +/* +** Return a pointer to the next prepared statement after pStmt associated +** with database connection pDb. If pStmt is NULL, return the first +** prepared statement for the database connection. Return NULL if there +** are no more. +*/ +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){ + sqlite3_stmt *pNext; + sqlite3_mutex_enter(pDb->mutex); + if( pStmt==0 ){ + pNext = (sqlite3_stmt*)pDb->pVdbe; + }else{ + pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext; + } + sqlite3_mutex_leave(pDb->mutex); + return pNext; +} + +/* +** Return the value of a status counter for a prepared statement +*/ +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){ + Vdbe *pVdbe = (Vdbe*)pStmt; + u32 v = pVdbe->aCounter[op]; + if( resetFlag ) pVdbe->aCounter[op] = 0; + return (int)v; +} + +/************** End of vdbeapi.c *********************************************/ +/************** Begin file vdbetrace.c ***************************************/ +/* +** 2009 November 25 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used to insert the values of host parameters +** (aka "wildcards") into the SQL text output by sqlite3_trace(). +** +** The Vdbe parse-tree explainer is also found here. +*/ + +#ifndef SQLITE_OMIT_TRACE + +/* +** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of +** bytes in this text up to but excluding the first character in +** a host parameter. If the text contains no host parameters, return +** the total number of bytes in the text. +*/ +static int findNextHostParameter(const char *zSql, int *pnToken){ + int tokenType; + int nTotal = 0; + int n; + + *pnToken = 0; + while( zSql[0] ){ + n = sqlite3GetToken((u8*)zSql, &tokenType); + assert( n>0 && tokenType!=TK_ILLEGAL ); + if( tokenType==TK_VARIABLE ){ + *pnToken = n; + break; + } + nTotal += n; + zSql += n; + } + return nTotal; +} + +/* +** This function returns a pointer to a nul-terminated string in memory +** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the +** string contains a copy of zRawSql but with host parameters expanded to +** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, +** then the returned string holds a copy of zRawSql with "-- " prepended +** to each line of text. +** +** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then +** then long strings and blobs are truncated to that many bytes. This +** can be used to prevent unreasonably large trace strings when dealing +** with large (multi-megabyte) strings and blobs. +** +** The calling function is responsible for making sure the memory returned +** is eventually freed. +** +** ALGORITHM: Scan the input string looking for host parameters in any of +** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within +** string literals, quoted identifier names, and comments. For text forms, +** the host parameter index is found by scanning the perpared +** statement for the corresponding OP_Variable opcode. Once the host +** parameter index is known, locate the value in p->aVar[]. Then render +** the value as a literal in place of the host parameter name. +*/ +SQLITE_PRIVATE char *sqlite3VdbeExpandSql( + Vdbe *p, /* The prepared statement being evaluated */ + const char *zRawSql /* Raw text of the SQL statement */ +){ + sqlite3 *db; /* The database connection */ + int idx = 0; /* Index of a host parameter */ + int nextIndex = 1; /* Index of next ? host parameter */ + int n; /* Length of a token prefix */ + int nToken; /* Length of the parameter token */ + int i; /* Loop counter */ + Mem *pVar; /* Value of a host parameter */ + StrAccum out; /* Accumulate the output here */ + char zBase[100]; /* Initial working space */ + + db = p->db; + sqlite3StrAccumInit(&out, zBase, sizeof(zBase), + db->aLimit[SQLITE_LIMIT_LENGTH]); + out.db = db; + if( db->nVdbeExec>1 ){ + while( *zRawSql ){ + const char *zStart = zRawSql; + while( *(zRawSql++)!='\n' && *zRawSql ); + sqlite3StrAccumAppend(&out, "-- ", 3); + sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart)); + } + }else{ + while( zRawSql[0] ){ + n = findNextHostParameter(zRawSql, &nToken); + assert( n>0 ); + sqlite3StrAccumAppend(&out, zRawSql, n); + zRawSql += n; + assert( zRawSql[0] || nToken==0 ); + if( nToken==0 ) break; + if( zRawSql[0]=='?' ){ + if( nToken>1 ){ + assert( sqlite3Isdigit(zRawSql[1]) ); + sqlite3GetInt32(&zRawSql[1], &idx); + }else{ + idx = nextIndex; + } + }else{ + assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' ); + testcase( zRawSql[0]==':' ); + testcase( zRawSql[0]=='$' ); + testcase( zRawSql[0]=='@' ); + idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken); + assert( idx>0 ); + } + zRawSql += nToken; + nextIndex = idx + 1; + assert( idx>0 && idx<=p->nVar ); + pVar = &p->aVar[idx-1]; + if( pVar->flags & MEM_Null ){ + sqlite3StrAccumAppend(&out, "NULL", 4); + }else if( pVar->flags & MEM_Int ){ + sqlite3XPrintf(&out, "%lld", pVar->u.i); + }else if( pVar->flags & MEM_Real ){ + sqlite3XPrintf(&out, "%!.15g", pVar->r); + }else if( pVar->flags & MEM_Str ){ + int nOut; /* Number of bytes of the string text to include in output */ +#ifndef SQLITE_OMIT_UTF16 + u8 enc = ENC(db); + Mem utf8; + if( enc!=SQLITE_UTF8 ){ + memset(&utf8, 0, sizeof(utf8)); + utf8.db = db; + sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC); + sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8); + pVar = &utf8; + } +#endif + nOut = pVar->n; +#ifdef SQLITE_TRACE_SIZE_LIMIT + if( nOut>SQLITE_TRACE_SIZE_LIMIT ){ + nOut = SQLITE_TRACE_SIZE_LIMIT; + while( nOutn && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; } + } +#endif + sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z); +#ifdef SQLITE_TRACE_SIZE_LIMIT + if( nOutn ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); +#endif +#ifndef SQLITE_OMIT_UTF16 + if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8); +#endif + }else if( pVar->flags & MEM_Zero ){ + sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero); + }else{ + int nOut; /* Number of bytes of the blob to include in output */ + assert( pVar->flags & MEM_Blob ); + sqlite3StrAccumAppend(&out, "x'", 2); + nOut = pVar->n; +#ifdef SQLITE_TRACE_SIZE_LIMIT + if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT; +#endif + for(i=0; iz[i]&0xff); + } + sqlite3StrAccumAppend(&out, "'", 1); +#ifdef SQLITE_TRACE_SIZE_LIMIT + if( nOutn ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); +#endif + } + } + } + return sqlite3StrAccumFinish(&out); +} + +#endif /* #ifndef SQLITE_OMIT_TRACE */ + +/***************************************************************************** +** The following code implements the data-structure explaining logic +** for the Vdbe. +*/ + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) + +/* +** Allocate a new Explain object +*/ +SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){ + if( pVdbe ){ + Explain *p; + sqlite3BeginBenignMalloc(); + p = (Explain *)sqlite3MallocZero( sizeof(Explain) ); + if( p ){ + p->pVdbe = pVdbe; + sqlite3_free(pVdbe->pExplain); + pVdbe->pExplain = p; + sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase), + SQLITE_MAX_LENGTH); + p->str.useMalloc = 2; + }else{ + sqlite3EndBenignMalloc(); + } + } +} + +/* +** Return true if the Explain ends with a new-line. +*/ +static int endsWithNL(Explain *p){ + return p && p->str.zText && p->str.nChar + && p->str.zText[p->str.nChar-1]=='\n'; +} + +/* +** Append text to the indentation +*/ +SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){ + Explain *p; + if( pVdbe && (p = pVdbe->pExplain)!=0 ){ + va_list ap; + if( p->nIndent && endsWithNL(p) ){ + int n = p->nIndent; + if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent); + sqlite3AppendSpace(&p->str, p->aIndent[n-1]); + } + va_start(ap, zFormat); + sqlite3VXPrintf(&p->str, 1, zFormat, ap); + va_end(ap); + } +} + +/* +** Append a '\n' if there is not already one. +*/ +SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){ + Explain *p; + if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){ + sqlite3StrAccumAppend(&p->str, "\n", 1); + } +} + +/* +** Push a new indentation level. Subsequent lines will be indented +** so that they begin at the current cursor position. +*/ +SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){ + Explain *p; + if( pVdbe && (p = pVdbe->pExplain)!=0 ){ + if( p->str.zText && p->nIndentaIndent) ){ + const char *z = p->str.zText; + int i = p->str.nChar-1; + int x; + while( i>=0 && z[i]!='\n' ){ i--; } + x = (p->str.nChar - 1) - i; + if( p->nIndent && xaIndent[p->nIndent-1] ){ + x = p->aIndent[p->nIndent-1]; + } + p->aIndent[p->nIndent] = x; + } + p->nIndent++; + } +} + +/* +** Pop the indentation stack by one level. +*/ +SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){ + if( p && p->pExplain ) p->pExplain->nIndent--; +} + +/* +** Free the indentation structure +*/ +SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){ + if( pVdbe && pVdbe->pExplain ){ + sqlite3_free(pVdbe->zExplain); + sqlite3ExplainNL(pVdbe); + pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str); + sqlite3_free(pVdbe->pExplain); + pVdbe->pExplain = 0; + sqlite3EndBenignMalloc(); + } +} + +/* +** Return the explanation of a virtual machine. +*/ +SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){ + return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0; +} +#endif /* defined(SQLITE_DEBUG) */ + +/************** End of vdbetrace.c *******************************************/ +/************** Begin file vdbe.c ********************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** The code in this file implements execution method of the +** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c") +** handles housekeeping details such as creating and deleting +** VDBE instances. This file is solely interested in executing +** the VDBE program. +** +** In the external interface, an "sqlite3_stmt*" is an opaque pointer +** to a VDBE. +** +** The SQL parser generates a program which is then executed by +** the VDBE to do the work of the SQL statement. VDBE programs are +** similar in form to assembly language. The program consists of +** a linear sequence of operations. Each operation has an opcode +** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4 +** is a null-terminated string. Operand P5 is an unsigned character. +** Few opcodes use all 5 operands. +** +** Computation results are stored on a set of registers numbered beginning +** with 1 and going up to Vdbe.nMem. Each register can store +** either an integer, a null-terminated string, a floating point +** number, or the SQL "NULL" value. An implicit conversion from one +** type to the other occurs as necessary. +** +** Most of the code in this file is taken up by the sqlite3VdbeExec() +** function which does the work of interpreting a VDBE program. +** But other routines are also provided to help in building up +** a program instruction by instruction. +** +** Various scripts scan this source file in order to generate HTML +** documentation, headers files, or other derived files. The formatting +** of the code in this file is, therefore, important. See other comments +** in this file for details. If in doubt, do not deviate from existing +** commenting and indentation practices when changing or adding code. +*/ + +/* +** Invoke this macro on memory cells just prior to changing the +** value of the cell. This macro verifies that shallow copies are +** not misused. +*/ +#ifdef SQLITE_DEBUG +# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M) +#else +# define memAboutToChange(P,M) +#endif + +/* +** The following global variable is incremented every time a cursor +** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test +** procedures use this information to make sure that indices are +** working correctly. This variable has no function other than to +** help verify the correct operation of the library. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_search_count = 0; +#endif + +/* +** When this global variable is positive, it gets decremented once before +** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted +** field of the sqlite3 structure is set in order to simulate an interrupt. +** +** This facility is used for testing purposes only. It does not function +** in an ordinary build. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_interrupt_count = 0; +#endif + +/* +** The next global variable is incremented each type the OP_Sort opcode +** is executed. The test procedures use this information to make sure that +** sorting is occurring or not occurring at appropriate times. This variable +** has no function other than to help verify the correct operation of the +** library. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_sort_count = 0; +#endif + +/* +** The next global variable records the size of the largest MEM_Blob +** or MEM_Str that has been used by a VDBE opcode. The test procedures +** use this information to make sure that the zero-blob functionality +** is working correctly. This variable has no function other than to +** help verify the correct operation of the library. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_max_blobsize = 0; +static void updateMaxBlobsize(Mem *p){ + if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){ + sqlite3_max_blobsize = p->n; + } +} +#endif + +/* +** The next global variable is incremented each type the OP_Found opcode +** is executed. This is used to test whether or not the foreign key +** operation implemented using OP_FkIsZero is working. This variable +** has no function other than to help verify the correct operation of the +** library. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_found_count = 0; +#endif + +/* +** Test a register to see if it exceeds the current maximum blob size. +** If it does, record the new maximum blob size. +*/ +#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST) +# define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P) +#else +# define UPDATE_MAX_BLOBSIZE(P) +#endif + +/* +** Convert the given register into a string if it isn't one +** already. Return non-zero if a malloc() fails. +*/ +#define Stringify(P, enc) \ + if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \ + { goto no_mem; } + +/* +** An ephemeral string value (signified by the MEM_Ephem flag) contains +** a pointer to a dynamically allocated string where some other entity +** is responsible for deallocating that string. Because the register +** does not control the string, it might be deleted without the register +** knowing it. +** +** This routine converts an ephemeral string into a dynamically allocated +** string that the register itself controls. In other words, it +** converts an MEM_Ephem string into an MEM_Dyn string. +*/ +#define Deephemeralize(P) \ + if( ((P)->flags&MEM_Ephem)!=0 \ + && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} + +/* Return true if the cursor was opened using the OP_OpenSorter opcode. */ +# define isSorter(x) ((x)->pSorter!=0) + +/* +** Argument pMem points at a register that will be passed to a +** user-defined function or returned to the user as the result of a query. +** This routine sets the pMem->type variable used by the sqlite3_value_*() +** routines. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){ + int flags = pMem->flags; + if( flags & MEM_Null ){ + pMem->type = SQLITE_NULL; + } + else if( flags & MEM_Int ){ + pMem->type = SQLITE_INTEGER; + } + else if( flags & MEM_Real ){ + pMem->type = SQLITE_FLOAT; + } + else if( flags & MEM_Str ){ + pMem->type = SQLITE_TEXT; + }else{ + pMem->type = SQLITE_BLOB; + } +} + +/* +** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL +** if we run out of memory. +*/ +static VdbeCursor *allocateCursor( + Vdbe *p, /* The virtual machine */ + int iCur, /* Index of the new VdbeCursor */ + int nField, /* Number of fields in the table or index */ + int iDb, /* Database the cursor belongs to, or -1 */ + int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */ +){ + /* Find the memory cell that will be used to store the blob of memory + ** required for this VdbeCursor structure. It is convenient to use a + ** vdbe memory cell to manage the memory allocation required for a + ** VdbeCursor structure for the following reasons: + ** + ** * Sometimes cursor numbers are used for a couple of different + ** purposes in a vdbe program. The different uses might require + ** different sized allocations. Memory cells provide growable + ** allocations. + ** + ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can + ** be freed lazily via the sqlite3_release_memory() API. This + ** minimizes the number of malloc calls made by the system. + ** + ** Memory cells for cursors are allocated at the top of the address + ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for + ** cursor 1 is managed by memory cell (p->nMem-1), etc. + */ + Mem *pMem = &p->aMem[p->nMem-iCur]; + + int nByte; + VdbeCursor *pCx = 0; + nByte = + ROUND8(sizeof(VdbeCursor)) + + (isBtreeCursor?sqlite3BtreeCursorSize():0) + + 2*nField*sizeof(u32); + + assert( iCurnCursor ); + if( p->apCsr[iCur] ){ + sqlite3VdbeFreeCursor(p, p->apCsr[iCur]); + p->apCsr[iCur] = 0; + } + if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){ + p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z; + memset(pCx, 0, sizeof(VdbeCursor)); + pCx->iDb = iDb; + pCx->nField = nField; + if( nField ){ + pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))]; + } + if( isBtreeCursor ){ + pCx->pCursor = (BtCursor*) + &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)]; + sqlite3BtreeCursorZero(pCx->pCursor); + } + } + return pCx; +} + +/* +** Try to convert a value into a numeric representation if we can +** do so without loss of information. In other words, if the string +** looks like a number, convert it into a number. If it does not +** look like a number, leave it alone. +*/ +static void applyNumericAffinity(Mem *pRec){ + if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){ + double rValue; + i64 iValue; + u8 enc = pRec->enc; + if( (pRec->flags&MEM_Str)==0 ) return; + if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return; + if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){ + pRec->u.i = iValue; + pRec->flags |= MEM_Int; + }else{ + pRec->r = rValue; + pRec->flags |= MEM_Real; + } + } +} + +/* +** Processing is determine by the affinity parameter: +** +** SQLITE_AFF_INTEGER: +** SQLITE_AFF_REAL: +** SQLITE_AFF_NUMERIC: +** Try to convert pRec to an integer representation or a +** floating-point representation if an integer representation +** is not possible. Note that the integer representation is +** always preferred, even if the affinity is REAL, because +** an integer representation is more space efficient on disk. +** +** SQLITE_AFF_TEXT: +** Convert pRec to a text representation. +** +** SQLITE_AFF_NONE: +** No-op. pRec is unchanged. +*/ +static void applyAffinity( + Mem *pRec, /* The value to apply affinity to */ + char affinity, /* The affinity to be applied */ + u8 enc /* Use this text encoding */ +){ + if( affinity==SQLITE_AFF_TEXT ){ + /* Only attempt the conversion to TEXT if there is an integer or real + ** representation (blob and NULL do not get converted) but no string + ** representation. + */ + if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){ + sqlite3VdbeMemStringify(pRec, enc); + } + pRec->flags &= ~(MEM_Real|MEM_Int); + }else if( affinity!=SQLITE_AFF_NONE ){ + assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL + || affinity==SQLITE_AFF_NUMERIC ); + applyNumericAffinity(pRec); + if( pRec->flags & MEM_Real ){ + sqlite3VdbeIntegerAffinity(pRec); + } + } +} + +/* +** Try to convert the type of a function argument or a result column +** into a numeric representation. Use either INTEGER or REAL whichever +** is appropriate. But only do the conversion if it is possible without +** loss of information and return the revised type of the argument. +*/ +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){ + Mem *pMem = (Mem*)pVal; + if( pMem->type==SQLITE_TEXT ){ + applyNumericAffinity(pMem); + sqlite3VdbeMemStoreType(pMem); + } + return pMem->type; +} + +/* +** Exported version of applyAffinity(). This one works on sqlite3_value*, +** not the internal Mem* type. +*/ +SQLITE_PRIVATE void sqlite3ValueApplyAffinity( + sqlite3_value *pVal, + u8 affinity, + u8 enc +){ + applyAffinity((Mem *)pVal, affinity, enc); +} + +#ifdef SQLITE_DEBUG +/* +** Write a nice string representation of the contents of cell pMem +** into buffer zBuf, length nBuf. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){ + char *zCsr = zBuf; + int f = pMem->flags; + + static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"}; + + if( f&MEM_Blob ){ + int i; + char c; + if( f & MEM_Dyn ){ + c = 'z'; + assert( (f & (MEM_Static|MEM_Ephem))==0 ); + }else if( f & MEM_Static ){ + c = 't'; + assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); + }else if( f & MEM_Ephem ){ + c = 'e'; + assert( (f & (MEM_Static|MEM_Dyn))==0 ); + }else{ + c = 's'; + } + + sqlite3_snprintf(100, zCsr, "%c", c); + zCsr += sqlite3Strlen30(zCsr); + sqlite3_snprintf(100, zCsr, "%d[", pMem->n); + zCsr += sqlite3Strlen30(zCsr); + for(i=0; i<16 && in; i++){ + sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF)); + zCsr += sqlite3Strlen30(zCsr); + } + for(i=0; i<16 && in; i++){ + char z = pMem->z[i]; + if( z<32 || z>126 ) *zCsr++ = '.'; + else *zCsr++ = z; + } + + sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]); + zCsr += sqlite3Strlen30(zCsr); + if( f & MEM_Zero ){ + sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero); + zCsr += sqlite3Strlen30(zCsr); + } + *zCsr = '\0'; + }else if( f & MEM_Str ){ + int j, k; + zBuf[0] = ' '; + if( f & MEM_Dyn ){ + zBuf[1] = 'z'; + assert( (f & (MEM_Static|MEM_Ephem))==0 ); + }else if( f & MEM_Static ){ + zBuf[1] = 't'; + assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); + }else if( f & MEM_Ephem ){ + zBuf[1] = 'e'; + assert( (f & (MEM_Static|MEM_Dyn))==0 ); + }else{ + zBuf[1] = 's'; + } + k = 2; + sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n); + k += sqlite3Strlen30(&zBuf[k]); + zBuf[k++] = '['; + for(j=0; j<15 && jn; j++){ + u8 c = pMem->z[j]; + if( c>=0x20 && c<0x7f ){ + zBuf[k++] = c; + }else{ + zBuf[k++] = '.'; + } + } + zBuf[k++] = ']'; + sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]); + k += sqlite3Strlen30(&zBuf[k]); + zBuf[k++] = 0; + } +} +#endif + +#ifdef SQLITE_DEBUG +/* +** Print the value of a register for tracing purposes: +*/ +static void memTracePrint(FILE *out, Mem *p){ + if( p->flags & MEM_Invalid ){ + fprintf(out, " undefined"); + }else if( p->flags & MEM_Null ){ + fprintf(out, " NULL"); + }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ + fprintf(out, " si:%lld", p->u.i); + }else if( p->flags & MEM_Int ){ + fprintf(out, " i:%lld", p->u.i); +#ifndef SQLITE_OMIT_FLOATING_POINT + }else if( p->flags & MEM_Real ){ + fprintf(out, " r:%g", p->r); +#endif + }else if( p->flags & MEM_RowSet ){ + fprintf(out, " (rowset)"); + }else{ + char zBuf[200]; + sqlite3VdbeMemPrettyPrint(p, zBuf); + fprintf(out, " "); + fprintf(out, "%s", zBuf); + } +} +static void registerTrace(FILE *out, int iReg, Mem *p){ + fprintf(out, "REG[%d] = ", iReg); + memTracePrint(out, p); + fprintf(out, "\n"); +} +#endif + +#ifdef SQLITE_DEBUG +# define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M) +#else +# define REGISTER_TRACE(R,M) +#endif + + +#ifdef VDBE_PROFILE + +/* +** hwtime.h contains inline assembler code for implementing +** high-performance timing routines. +*/ +/************** Include hwtime.h in the middle of vdbe.c *********************/ +/************** Begin file hwtime.h ******************************************/ +/* +** 2008 May 27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains inline asm code for retrieving "high-performance" +** counters for x86 class CPUs. +*/ +#ifndef _HWTIME_H_ +#define _HWTIME_H_ + +/* +** The following routine only works on pentium-class (or newer) processors. +** It uses the RDTSC opcode to read the cycle count value out of the +** processor and returns that value. This can be used for high-res +** profiling. +*/ +#if (defined(__GNUC__) || defined(_MSC_VER)) && \ + (defined(i386) || defined(__i386__) || defined(_M_IX86)) + + #if defined(__GNUC__) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + unsigned int lo, hi; + __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); + return (sqlite_uint64)hi << 32 | lo; + } + + #elif defined(_MSC_VER) + + __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ + __asm { + rdtsc + ret ; return value at EDX:EAX + } + } + + #endif + +#elif (defined(__GNUC__) && defined(__x86_64__)) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + unsigned long val; + __asm__ __volatile__ ("rdtsc" : "=A" (val)); + return val; + } + +#elif (defined(__GNUC__) && defined(__ppc__)) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + unsigned long long retval; + unsigned long junk; + __asm__ __volatile__ ("\n\ + 1: mftbu %1\n\ + mftb %L0\n\ + mftbu %0\n\ + cmpw %0,%1\n\ + bne 1b" + : "=r" (retval), "=r" (junk)); + return retval; + } + +#else + + #error Need implementation of sqlite3Hwtime() for your platform. + + /* + ** To compile without implementing sqlite3Hwtime() for your platform, + ** you can remove the above #error and use the following + ** stub function. You will lose timing support for many + ** of the debugging and testing utilities, but it should at + ** least compile and run. + */ +SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } + +#endif + +#endif /* !defined(_HWTIME_H_) */ + +/************** End of hwtime.h **********************************************/ +/************** Continuing where we left off in vdbe.c ***********************/ + +#endif + +/* +** The CHECK_FOR_INTERRUPT macro defined here looks to see if the +** sqlite3_interrupt() routine has been called. If it has been, then +** processing of the VDBE program is interrupted. +** +** This macro added to every instruction that does a jump in order to +** implement a loop. This test used to be on every single instruction, +** but that meant we more testing than we needed. By only testing the +** flag on jump instructions, we get a (small) speed improvement. +*/ +#define CHECK_FOR_INTERRUPT \ + if( db->u1.isInterrupted ) goto abort_due_to_interrupt; + + +#ifndef NDEBUG +/* +** This function is only called from within an assert() expression. It +** checks that the sqlite3.nTransaction variable is correctly set to +** the number of non-transaction savepoints currently in the +** linked list starting at sqlite3.pSavepoint. +** +** Usage: +** +** assert( checkSavepointCount(db) ); +*/ +static int checkSavepointCount(sqlite3 *db){ + int n = 0; + Savepoint *p; + for(p=db->pSavepoint; p; p=p->pNext) n++; + assert( n==(db->nSavepoint + db->isTransactionSavepoint) ); + return 1; +} +#endif + + +/* +** Execute as much of a VDBE program as we can then return. +** +** sqlite3VdbeMakeReady() must be called before this routine in order to +** close the program with a final OP_Halt and to set up the callbacks +** and the error message pointer. +** +** Whenever a row or result data is available, this routine will either +** invoke the result callback (if there is one) or return with +** SQLITE_ROW. +** +** If an attempt is made to open a locked database, then this routine +** will either invoke the busy callback (if there is one) or it will +** return SQLITE_BUSY. +** +** If an error occurs, an error message is written to memory obtained +** from sqlite3_malloc() and p->zErrMsg is made to point to that memory. +** The error code is stored in p->rc and this routine returns SQLITE_ERROR. +** +** If the callback ever returns non-zero, then the program exits +** immediately. There will be no error message but the p->rc field is +** set to SQLITE_ABORT and this routine will return SQLITE_ERROR. +** +** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this +** routine to return SQLITE_ERROR. +** +** Other fatal errors return SQLITE_ERROR. +** +** After this routine has finished, sqlite3VdbeFinalize() should be +** used to clean up the mess that was left behind. +*/ +SQLITE_PRIVATE int sqlite3VdbeExec( + Vdbe *p /* The VDBE */ +){ + int pc=0; /* The program counter */ + Op *aOp = p->aOp; /* Copy of p->aOp */ + Op *pOp; /* Current operation */ + int rc = SQLITE_OK; /* Value to return */ + sqlite3 *db = p->db; /* The database */ + u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */ + u8 encoding = ENC(db); /* The database encoding */ + int iCompare = 0; /* Result of last OP_Compare operation */ + unsigned nVmStep = 0; /* Number of virtual machine steps */ +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */ +#endif + Mem *aMem = p->aMem; /* Copy of p->aMem */ + Mem *pIn1 = 0; /* 1st input operand */ + Mem *pIn2 = 0; /* 2nd input operand */ + Mem *pIn3 = 0; /* 3rd input operand */ + Mem *pOut = 0; /* Output operand */ + int *aPermute = 0; /* Permutation of columns for OP_Compare */ + i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */ +#ifdef VDBE_PROFILE + u64 start; /* CPU clock count at start of opcode */ + int origPc; /* Program counter at start of opcode */ +#endif + /******************************************************************** + ** Automatically generated code + ** + ** The following union is automatically generated by the + ** vdbe-compress.tcl script. The purpose of this union is to + ** reduce the amount of stack space required by this function. + ** See comments in the vdbe-compress.tcl script for details. + */ + union vdbeExecUnion { + struct OP_Yield_stack_vars { + int pcDest; + } aa; + struct OP_Null_stack_vars { + int cnt; + u16 nullFlag; + } ab; + struct OP_Variable_stack_vars { + Mem *pVar; /* Value being transferred */ + } ac; + struct OP_Move_stack_vars { + char *zMalloc; /* Holding variable for allocated memory */ + int n; /* Number of registers left to copy */ + int p1; /* Register to copy from */ + int p2; /* Register to copy to */ + } ad; + struct OP_Copy_stack_vars { + int n; + } ae; + struct OP_ResultRow_stack_vars { + Mem *pMem; + int i; + } af; + struct OP_Concat_stack_vars { + i64 nByte; + } ag; + struct OP_Remainder_stack_vars { + char bIntint; /* Started out as two integer operands */ + int flags; /* Combined MEM_* flags from both inputs */ + i64 iA; /* Integer value of left operand */ + i64 iB; /* Integer value of right operand */ + double rA; /* Real value of left operand */ + double rB; /* Real value of right operand */ + } ah; + struct OP_Function_stack_vars { + int i; + Mem *pArg; + sqlite3_context ctx; + sqlite3_value **apVal; + int n; + } ai; + struct OP_ShiftRight_stack_vars { + i64 iA; + u64 uA; + i64 iB; + u8 op; + } aj; + struct OP_Ge_stack_vars { + int res; /* Result of the comparison of pIn1 against pIn3 */ + char affinity; /* Affinity to use for comparison */ + u16 flags1; /* Copy of initial value of pIn1->flags */ + u16 flags3; /* Copy of initial value of pIn3->flags */ + } ak; + struct OP_Compare_stack_vars { + int n; + int i; + int p1; + int p2; + const KeyInfo *pKeyInfo; + int idx; + CollSeq *pColl; /* Collating sequence to use on this term */ + int bRev; /* True for DESCENDING sort order */ + } al; + struct OP_Or_stack_vars { + int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ + int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ + } am; + struct OP_IfNot_stack_vars { + int c; + } an; + struct OP_Column_stack_vars { + u32 payloadSize; /* Number of bytes in the record */ + i64 payloadSize64; /* Number of bytes in the record */ + int p1; /* P1 value of the opcode */ + int p2; /* column number to retrieve */ + VdbeCursor *pC; /* The VDBE cursor */ + char *zRec; /* Pointer to complete record-data */ + BtCursor *pCrsr; /* The BTree cursor */ + u32 *aType; /* aType[i] holds the numeric type of the i-th column */ + u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */ + int nField; /* number of fields in the record */ + int len; /* The length of the serialized data for the column */ + int i; /* Loop counter */ + char *zData; /* Part of the record being decoded */ + Mem *pDest; /* Where to write the extracted value */ + Mem sMem; /* For storing the record being decoded */ + u8 *zIdx; /* Index into header */ + u8 *zEndHdr; /* Pointer to first byte after the header */ + u32 offset; /* Offset into the data */ + u32 szField; /* Number of bytes in the content of a field */ + int szHdr; /* Size of the header size field at start of record */ + int avail; /* Number of bytes of available data */ + u32 t; /* A type code from the record header */ + Mem *pReg; /* PseudoTable input register */ + } ao; + struct OP_Affinity_stack_vars { + const char *zAffinity; /* The affinity to be applied */ + char cAff; /* A single character of affinity */ + } ap; + struct OP_MakeRecord_stack_vars { + u8 *zNewRecord; /* A buffer to hold the data for the new record */ + Mem *pRec; /* The new record */ + u64 nData; /* Number of bytes of data space */ + int nHdr; /* Number of bytes of header space */ + i64 nByte; /* Data space required for this record */ + int nZero; /* Number of zero bytes at the end of the record */ + int nVarint; /* Number of bytes in a varint */ + u32 serial_type; /* Type field */ + Mem *pData0; /* First field to be combined into the record */ + Mem *pLast; /* Last field of the record */ + int nField; /* Number of fields in the record */ + char *zAffinity; /* The affinity string for the record */ + int file_format; /* File format to use for encoding */ + int i; /* Space used in zNewRecord[] */ + int len; /* Length of a field */ + } aq; + struct OP_Count_stack_vars { + i64 nEntry; + BtCursor *pCrsr; + } ar; + struct OP_Savepoint_stack_vars { + int p1; /* Value of P1 operand */ + char *zName; /* Name of savepoint */ + int nName; + Savepoint *pNew; + Savepoint *pSavepoint; + Savepoint *pTmp; + int iSavepoint; + int ii; + } as; + struct OP_AutoCommit_stack_vars { + int desiredAutoCommit; + int iRollback; + int turnOnAC; + } at; + struct OP_Transaction_stack_vars { + Btree *pBt; + } au; + struct OP_ReadCookie_stack_vars { + int iMeta; + int iDb; + int iCookie; + } av; + struct OP_SetCookie_stack_vars { + Db *pDb; + } aw; + struct OP_VerifyCookie_stack_vars { + int iMeta; + int iGen; + Btree *pBt; + } ax; + struct OP_OpenWrite_stack_vars { + int nField; + KeyInfo *pKeyInfo; + int p2; + int iDb; + int wrFlag; + Btree *pX; + VdbeCursor *pCur; + Db *pDb; + } ay; + struct OP_OpenEphemeral_stack_vars { + VdbeCursor *pCx; + } az; + struct OP_SorterOpen_stack_vars { + VdbeCursor *pCx; + } ba; + struct OP_OpenPseudo_stack_vars { + VdbeCursor *pCx; + } bb; + struct OP_SeekGt_stack_vars { + int res; + int oc; + VdbeCursor *pC; + UnpackedRecord r; + int nField; + i64 iKey; /* The rowid we are to seek to */ + } bc; + struct OP_Seek_stack_vars { + VdbeCursor *pC; + } bd; + struct OP_Found_stack_vars { + int alreadyExists; + VdbeCursor *pC; + int res; + char *pFree; + UnpackedRecord *pIdxKey; + UnpackedRecord r; + char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7]; + } be; + struct OP_IsUnique_stack_vars { + u16 ii; + VdbeCursor *pCx; + BtCursor *pCrsr; + u16 nField; + Mem *aMx; + UnpackedRecord r; /* B-Tree index search key */ + i64 R; /* Rowid stored in register P3 */ + } bf; + struct OP_NotExists_stack_vars { + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + u64 iKey; + } bg; + struct OP_NewRowid_stack_vars { + i64 v; /* The new rowid */ + VdbeCursor *pC; /* Cursor of table to get the new rowid */ + int res; /* Result of an sqlite3BtreeLast() */ + int cnt; /* Counter to limit the number of searches */ + Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ + VdbeFrame *pFrame; /* Root frame of VDBE */ + } bh; + struct OP_InsertInt_stack_vars { + Mem *pData; /* MEM cell holding data for the record to be inserted */ + Mem *pKey; /* MEM cell holding key for the record */ + i64 iKey; /* The integer ROWID or key for the record to be inserted */ + VdbeCursor *pC; /* Cursor to table into which insert is written */ + int nZero; /* Number of zero-bytes to append */ + int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ + const char *zDb; /* database name - used by the update hook */ + const char *zTbl; /* Table name - used by the opdate hook */ + int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */ + } bi; + struct OP_Delete_stack_vars { + i64 iKey; + VdbeCursor *pC; + } bj; + struct OP_SorterCompare_stack_vars { + VdbeCursor *pC; + int res; + } bk; + struct OP_SorterData_stack_vars { + VdbeCursor *pC; + } bl; + struct OP_RowData_stack_vars { + VdbeCursor *pC; + BtCursor *pCrsr; + u32 n; + i64 n64; + } bm; + struct OP_Rowid_stack_vars { + VdbeCursor *pC; + i64 v; + sqlite3_vtab *pVtab; + const sqlite3_module *pModule; + } bn; + struct OP_NullRow_stack_vars { + VdbeCursor *pC; + } bo; + struct OP_Last_stack_vars { + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + } bp; + struct OP_Rewind_stack_vars { + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + } bq; + struct OP_Next_stack_vars { + VdbeCursor *pC; + int res; + } br; + struct OP_IdxInsert_stack_vars { + VdbeCursor *pC; + BtCursor *pCrsr; + int nKey; + const char *zKey; + } bs; + struct OP_IdxDelete_stack_vars { + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + UnpackedRecord r; + } bt; + struct OP_IdxRowid_stack_vars { + BtCursor *pCrsr; + VdbeCursor *pC; + i64 rowid; + } bu; + struct OP_IdxGE_stack_vars { + VdbeCursor *pC; + int res; + UnpackedRecord r; + } bv; + struct OP_Destroy_stack_vars { + int iMoved; + int iCnt; + Vdbe *pVdbe; + int iDb; + } bw; + struct OP_Clear_stack_vars { + int nChange; + } bx; + struct OP_CreateTable_stack_vars { + int pgno; + int flags; + Db *pDb; + } by; + struct OP_ParseSchema_stack_vars { + int iDb; + const char *zMaster; + char *zSql; + InitData initData; + } bz; + struct OP_IntegrityCk_stack_vars { + int nRoot; /* Number of tables to check. (Number of root pages.) */ + int *aRoot; /* Array of rootpage numbers for tables to be checked */ + int j; /* Loop counter */ + int nErr; /* Number of errors reported */ + char *z; /* Text of the error report */ + Mem *pnErr; /* Register keeping track of errors remaining */ + } ca; + struct OP_RowSetRead_stack_vars { + i64 val; + } cb; + struct OP_RowSetTest_stack_vars { + int iSet; + int exists; + } cc; + struct OP_Program_stack_vars { + int nMem; /* Number of memory registers for sub-program */ + int nByte; /* Bytes of runtime space required for sub-program */ + Mem *pRt; /* Register to allocate runtime space */ + Mem *pMem; /* Used to iterate through memory cells */ + Mem *pEnd; /* Last memory cell in new array */ + VdbeFrame *pFrame; /* New vdbe frame to execute in */ + SubProgram *pProgram; /* Sub-program to execute */ + void *t; /* Token identifying trigger */ + } cd; + struct OP_Param_stack_vars { + VdbeFrame *pFrame; + Mem *pIn; + } ce; + struct OP_MemMax_stack_vars { + Mem *pIn1; + VdbeFrame *pFrame; + } cf; + struct OP_AggStep_stack_vars { + int n; + int i; + Mem *pMem; + Mem *pRec; + sqlite3_context ctx; + sqlite3_value **apVal; + } cg; + struct OP_AggFinal_stack_vars { + Mem *pMem; + } ch; + struct OP_Checkpoint_stack_vars { + int i; /* Loop counter */ + int aRes[3]; /* Results */ + Mem *pMem; /* Write results here */ + } ci; + struct OP_JournalMode_stack_vars { + Btree *pBt; /* Btree to change journal mode of */ + Pager *pPager; /* Pager associated with pBt */ + int eNew; /* New journal mode */ + int eOld; /* The old journal mode */ +#ifndef SQLITE_OMIT_WAL + const char *zFilename; /* Name of database file for pPager */ +#endif + } cj; + struct OP_IncrVacuum_stack_vars { + Btree *pBt; + } ck; + struct OP_VBegin_stack_vars { + VTable *pVTab; + } cl; + struct OP_VOpen_stack_vars { + VdbeCursor *pCur; + sqlite3_vtab_cursor *pVtabCursor; + sqlite3_vtab *pVtab; + sqlite3_module *pModule; + } cm; + struct OP_VFilter_stack_vars { + int nArg; + int iQuery; + const sqlite3_module *pModule; + Mem *pQuery; + Mem *pArgc; + sqlite3_vtab_cursor *pVtabCursor; + sqlite3_vtab *pVtab; + VdbeCursor *pCur; + int res; + int i; + Mem **apArg; + } cn; + struct OP_VColumn_stack_vars { + sqlite3_vtab *pVtab; + const sqlite3_module *pModule; + Mem *pDest; + sqlite3_context sContext; + } co; + struct OP_VNext_stack_vars { + sqlite3_vtab *pVtab; + const sqlite3_module *pModule; + int res; + VdbeCursor *pCur; + } cp; + struct OP_VRename_stack_vars { + sqlite3_vtab *pVtab; + Mem *pName; + } cq; + struct OP_VUpdate_stack_vars { + sqlite3_vtab *pVtab; + sqlite3_module *pModule; + int nArg; + int i; + sqlite_int64 rowid; + Mem **apArg; + Mem *pX; + } cr; + struct OP_Trace_stack_vars { + char *zTrace; + char *z; + } cs; + } u; + /* End automatically generated code + ********************************************************************/ + + assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ + sqlite3VdbeEnter(p); + if( p->rc==SQLITE_NOMEM ){ + /* This happens if a malloc() inside a call to sqlite3_column_text() or + ** sqlite3_column_text16() failed. */ + goto no_mem; + } + assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY ); + assert( p->bIsReader || p->readOnly!=0 ); + p->rc = SQLITE_OK; + p->iCurrentTime = 0; + assert( p->explain==0 ); + p->pResultSet = 0; + db->busyHandler.nBusy = 0; + CHECK_FOR_INTERRUPT; + sqlite3VdbeIOTraceSql(p); +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + if( db->xProgress ){ + assert( 0 < db->nProgressOps ); + nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP]; + if( nProgressLimit==0 ){ + nProgressLimit = db->nProgressOps; + }else{ + nProgressLimit %= (unsigned)db->nProgressOps; + } + } +#endif +#ifdef SQLITE_DEBUG + sqlite3BeginBenignMalloc(); + if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){ + int i; + printf("VDBE Program Listing:\n"); + sqlite3VdbePrintSql(p); + for(i=0; inOp; i++){ + sqlite3VdbePrintOp(stdout, i, &aOp[i]); + } + } + sqlite3EndBenignMalloc(); +#endif + for(pc=p->pc; rc==SQLITE_OK; pc++){ + assert( pc>=0 && pcnOp ); + if( db->mallocFailed ) goto no_mem; +#ifdef VDBE_PROFILE + origPc = pc; + start = sqlite3Hwtime(); +#endif + nVmStep++; + pOp = &aOp[pc]; + + /* Only allow tracing if SQLITE_DEBUG is defined. + */ +#ifdef SQLITE_DEBUG + if( p->trace ){ + if( pc==0 ){ + printf("VDBE Execution Trace:\n"); + sqlite3VdbePrintSql(p); + } + sqlite3VdbePrintOp(p->trace, pc, pOp); + } +#endif + + + /* Check to see if we need to simulate an interrupt. This only happens + ** if we have a special test build. + */ +#ifdef SQLITE_TEST + if( sqlite3_interrupt_count>0 ){ + sqlite3_interrupt_count--; + if( sqlite3_interrupt_count==0 ){ + sqlite3_interrupt(db); + } + } +#endif + + /* On any opcode with the "out2-prerelease" tag, free any + ** external allocations out of mem[p2] and set mem[p2] to be + ** an undefined integer. Opcodes will either fill in the integer + ** value or convert mem[p2] to a different type. + */ + assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] ); + if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){ + assert( pOp->p2>0 ); + assert( pOp->p2<=(p->nMem-p->nCursor) ); + pOut = &aMem[pOp->p2]; + memAboutToChange(p, pOut); + VdbeMemRelease(pOut); + pOut->flags = MEM_Int; + } + + /* Sanity checking on other operands */ +#ifdef SQLITE_DEBUG + if( (pOp->opflags & OPFLG_IN1)!=0 ){ + assert( pOp->p1>0 ); + assert( pOp->p1<=(p->nMem-p->nCursor) ); + assert( memIsValid(&aMem[pOp->p1]) ); + REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]); + } + if( (pOp->opflags & OPFLG_IN2)!=0 ){ + assert( pOp->p2>0 ); + assert( pOp->p2<=(p->nMem-p->nCursor) ); + assert( memIsValid(&aMem[pOp->p2]) ); + REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]); + } + if( (pOp->opflags & OPFLG_IN3)!=0 ){ + assert( pOp->p3>0 ); + assert( pOp->p3<=(p->nMem-p->nCursor) ); + assert( memIsValid(&aMem[pOp->p3]) ); + REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]); + } + if( (pOp->opflags & OPFLG_OUT2)!=0 ){ + assert( pOp->p2>0 ); + assert( pOp->p2<=(p->nMem-p->nCursor) ); + memAboutToChange(p, &aMem[pOp->p2]); + } + if( (pOp->opflags & OPFLG_OUT3)!=0 ){ + assert( pOp->p3>0 ); + assert( pOp->p3<=(p->nMem-p->nCursor) ); + memAboutToChange(p, &aMem[pOp->p3]); + } +#endif + + switch( pOp->opcode ){ + +/***************************************************************************** +** What follows is a massive switch statement where each case implements a +** separate instruction in the virtual machine. If we follow the usual +** indentation conventions, each case should be indented by 6 spaces. But +** that is a lot of wasted space on the left margin. So the code within +** the switch statement will break with convention and be flush-left. Another +** big comment (similar to this one) will mark the point in the code where +** we transition back to normal indentation. +** +** The formatting of each case is important. The makefile for SQLite +** generates two C files "opcodes.h" and "opcodes.c" by scanning this +** file looking for lines that begin with "case OP_". The opcodes.h files +** will be filled with #defines that give unique integer values to each +** opcode and the opcodes.c file is filled with an array of strings where +** each string is the symbolic name for the corresponding opcode. If the +** case statement is followed by a comment of the form "/# same as ... #/" +** that comment is used to determine the particular value of the opcode. +** +** Other keywords in the comment that follows each case are used to +** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[]. +** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See +** the mkopcodeh.awk script for additional information. +** +** Documentation about VDBE opcodes is generated by scanning this file +** for lines of that contain "Opcode:". That line and all subsequent +** comment lines are used in the generation of the opcode.html documentation +** file. +** +** SUMMARY: +** +** Formatting is important to scripts that scan this file. +** Do not deviate from the formatting style currently in use. +** +*****************************************************************************/ + +/* Opcode: Goto * P2 * * * +** +** An unconditional jump to address P2. +** The next instruction executed will be +** the one at index P2 from the beginning of +** the program. +*/ +case OP_Goto: { /* jump */ + pc = pOp->p2 - 1; + + /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev, + ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon + ** completion. Check to see if sqlite3_interrupt() has been called + ** or if the progress callback needs to be invoked. + ** + ** This code uses unstructured "goto" statements and does not look clean. + ** But that is not due to sloppy coding habits. The code is written this + ** way for performance, to avoid having to run the interrupt and progress + ** checks on every opcode. This helps sqlite3_step() to run about 1.5% + ** faster according to "valgrind --tool=cachegrind" */ +check_for_interrupt: + CHECK_FOR_INTERRUPT; +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + /* Call the progress callback if it is configured and the required number + ** of VDBE ops have been executed (either since this invocation of + ** sqlite3VdbeExec() or since last time the progress callback was called). + ** If the progress callback returns non-zero, exit the virtual machine with + ** a return code SQLITE_ABORT. + */ + if( db->xProgress!=0 && nVmStep>=nProgressLimit ){ + int prc; + prc = db->xProgress(db->pProgressArg); + if( prc!=0 ){ + rc = SQLITE_INTERRUPT; + goto vdbe_error_halt; + } + if( db->xProgress!=0 ){ + nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps); + } + } +#endif + + break; +} + +/* Opcode: Gosub P1 P2 * * * +** +** Write the current address onto register P1 +** and then jump to address P2. +*/ +case OP_Gosub: { /* jump */ + assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) ); + pIn1 = &aMem[pOp->p1]; + assert( (pIn1->flags & MEM_Dyn)==0 ); + memAboutToChange(p, pIn1); + pIn1->flags = MEM_Int; + pIn1->u.i = pc; + REGISTER_TRACE(pOp->p1, pIn1); + pc = pOp->p2 - 1; + break; +} + +/* Opcode: Return P1 * * * * +** +** Jump to the next instruction after the address in register P1. +*/ +case OP_Return: { /* in1 */ + pIn1 = &aMem[pOp->p1]; + assert( pIn1->flags & MEM_Int ); + pc = (int)pIn1->u.i; + break; +} + +/* Opcode: Yield P1 * * * * +** +** Swap the program counter with the value in register P1. +*/ +case OP_Yield: { /* in1 */ +#if 0 /* local variables moved into u.aa */ + int pcDest; +#endif /* local variables moved into u.aa */ + pIn1 = &aMem[pOp->p1]; + assert( (pIn1->flags & MEM_Dyn)==0 ); + pIn1->flags = MEM_Int; + u.aa.pcDest = (int)pIn1->u.i; + pIn1->u.i = pc; + REGISTER_TRACE(pOp->p1, pIn1); + pc = u.aa.pcDest; + break; +} + +/* Opcode: HaltIfNull P1 P2 P3 P4 * +** +** Check the value in register P3. If it is NULL then Halt using +** parameter P1, P2, and P4 as if this were a Halt instruction. If the +** value in register P3 is not NULL, then this routine is a no-op. +*/ +case OP_HaltIfNull: { /* in3 */ + pIn3 = &aMem[pOp->p3]; + if( (pIn3->flags & MEM_Null)==0 ) break; + /* Fall through into OP_Halt */ +} + +/* Opcode: Halt P1 P2 * P4 * +** +** Exit immediately. All open cursors, etc are closed +** automatically. +** +** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(), +** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0). +** For errors, it can be some other value. If P1!=0 then P2 will determine +** whether or not to rollback the current transaction. Do not rollback +** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort, +** then back out all changes that have occurred during this execution of the +** VDBE, but do not rollback the transaction. +** +** If P4 is not null then it is an error message string. +** +** There is an implied "Halt 0 0 0" instruction inserted at the very end of +** every program. So a jump past the last instruction of the program +** is the same as executing Halt. +*/ +case OP_Halt: { + if( pOp->p1==SQLITE_OK && p->pFrame ){ + /* Halt the sub-program. Return control to the parent frame. */ + VdbeFrame *pFrame = p->pFrame; + p->pFrame = pFrame->pParent; + p->nFrame--; + sqlite3VdbeSetChanges(db, p->nChange); + pc = sqlite3VdbeFrameRestore(pFrame); + lastRowid = db->lastRowid; + if( pOp->p2==OE_Ignore ){ + /* Instruction pc is the OP_Program that invoked the sub-program + ** currently being halted. If the p2 instruction of this OP_Halt + ** instruction is set to OE_Ignore, then the sub-program is throwing + ** an IGNORE exception. In this case jump to the address specified + ** as the p2 of the calling OP_Program. */ + pc = p->aOp[pc].p2-1; + } + aOp = p->aOp; + aMem = p->aMem; + break; + } + + p->rc = pOp->p1; + p->errorAction = (u8)pOp->p2; + p->pc = pc; + if( pOp->p4.z ){ + assert( p->rc!=SQLITE_OK ); + sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z); + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z); + }else if( p->rc ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql); + } + rc = sqlite3VdbeHalt(p); + assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); + if( rc==SQLITE_BUSY ){ + p->rc = rc = SQLITE_BUSY; + }else{ + assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ); + assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 ); + rc = p->rc ? SQLITE_ERROR : SQLITE_DONE; + } + goto vdbe_return; +} + +/* Opcode: Integer P1 P2 * * * +** +** The 32-bit integer value P1 is written into register P2. +*/ +case OP_Integer: { /* out2-prerelease */ + pOut->u.i = pOp->p1; + break; +} + +/* Opcode: Int64 * P2 * P4 * +** +** P4 is a pointer to a 64-bit integer value. +** Write that value into register P2. +*/ +case OP_Int64: { /* out2-prerelease */ + assert( pOp->p4.pI64!=0 ); + pOut->u.i = *pOp->p4.pI64; + break; +} + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* Opcode: Real * P2 * P4 * +** +** P4 is a pointer to a 64-bit floating point value. +** Write that value into register P2. +*/ +case OP_Real: { /* same as TK_FLOAT, out2-prerelease */ + pOut->flags = MEM_Real; + assert( !sqlite3IsNaN(*pOp->p4.pReal) ); + pOut->r = *pOp->p4.pReal; + break; +} +#endif + +/* Opcode: String8 * P2 * P4 * +** +** P4 points to a nul terminated UTF-8 string. This opcode is transformed +** into an OP_String before it is executed for the first time. +*/ +case OP_String8: { /* same as TK_STRING, out2-prerelease */ + assert( pOp->p4.z!=0 ); + pOp->opcode = OP_String; + pOp->p1 = sqlite3Strlen30(pOp->p4.z); + +#ifndef SQLITE_OMIT_UTF16 + if( encoding!=SQLITE_UTF8 ){ + rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); + if( rc==SQLITE_TOOBIG ) goto too_big; + if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; + assert( pOut->zMalloc==pOut->z ); + assert( pOut->flags & MEM_Dyn ); + pOut->zMalloc = 0; + pOut->flags |= MEM_Static; + pOut->flags &= ~MEM_Dyn; + if( pOp->p4type==P4_DYNAMIC ){ + sqlite3DbFree(db, pOp->p4.z); + } + pOp->p4type = P4_DYNAMIC; + pOp->p4.z = pOut->z; + pOp->p1 = pOut->n; + } +#endif + if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + /* Fall through to the next case, OP_String */ +} + +/* Opcode: String P1 P2 * P4 * +** +** The string value P4 of length P1 (bytes) is stored in register P2. +*/ +case OP_String: { /* out2-prerelease */ + assert( pOp->p4.z!=0 ); + pOut->flags = MEM_Str|MEM_Static|MEM_Term; + pOut->z = pOp->p4.z; + pOut->n = pOp->p1; + pOut->enc = encoding; + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Null P1 P2 P3 * * +** +** Write a NULL into registers P2. If P3 greater than P2, then also write +** NULL into register P3 and every register in between P2 and P3. If P3 +** is less than P2 (typically P3 is zero) then only register P2 is +** set to NULL. +** +** If the P1 value is non-zero, then also set the MEM_Cleared flag so that +** NULL values will not compare equal even if SQLITE_NULLEQ is set on +** OP_Ne or OP_Eq. +*/ +case OP_Null: { /* out2-prerelease */ +#if 0 /* local variables moved into u.ab */ + int cnt; + u16 nullFlag; +#endif /* local variables moved into u.ab */ + u.ab.cnt = pOp->p3-pOp->p2; + assert( pOp->p3<=(p->nMem-p->nCursor) ); + pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null; + while( u.ab.cnt>0 ){ + pOut++; + memAboutToChange(p, pOut); + VdbeMemRelease(pOut); + pOut->flags = u.ab.nullFlag; + u.ab.cnt--; + } + break; +} + + +/* Opcode: Blob P1 P2 * P4 +** +** P4 points to a blob of data P1 bytes long. Store this +** blob in register P2. +*/ +case OP_Blob: { /* out2-prerelease */ + assert( pOp->p1 <= SQLITE_MAX_LENGTH ); + sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); + pOut->enc = encoding; + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Variable P1 P2 * P4 * +** +** Transfer the values of bound parameter P1 into register P2 +** +** If the parameter is named, then its name appears in P4 and P3==1. +** The P4 value is used by sqlite3_bind_parameter_name(). +*/ +case OP_Variable: { /* out2-prerelease */ +#if 0 /* local variables moved into u.ac */ + Mem *pVar; /* Value being transferred */ +#endif /* local variables moved into u.ac */ + + assert( pOp->p1>0 && pOp->p1<=p->nVar ); + assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] ); + u.ac.pVar = &p->aVar[pOp->p1 - 1]; + if( sqlite3VdbeMemTooBig(u.ac.pVar) ){ + goto too_big; + } + sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Move P1 P2 P3 * * +** +** Move the values in register P1..P1+P3 over into +** registers P2..P2+P3. Registers P1..P1+P3 are +** left holding a NULL. It is an error for register ranges +** P1..P1+P3 and P2..P2+P3 to overlap. +*/ +case OP_Move: { +#if 0 /* local variables moved into u.ad */ + char *zMalloc; /* Holding variable for allocated memory */ + int n; /* Number of registers left to copy */ + int p1; /* Register to copy from */ + int p2; /* Register to copy to */ +#endif /* local variables moved into u.ad */ + + u.ad.n = pOp->p3 + 1; + u.ad.p1 = pOp->p1; + u.ad.p2 = pOp->p2; + assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 ); + assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 ); + + pIn1 = &aMem[u.ad.p1]; + pOut = &aMem[u.ad.p2]; + while( u.ad.n-- ){ + assert( pOut<=&aMem[(p->nMem-p->nCursor)] ); + assert( pIn1<=&aMem[(p->nMem-p->nCursor)] ); + assert( memIsValid(pIn1) ); + memAboutToChange(p, pOut); + u.ad.zMalloc = pOut->zMalloc; + pOut->zMalloc = 0; + sqlite3VdbeMemMove(pOut, pIn1); +#ifdef SQLITE_DEBUG + if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){ + pOut->pScopyFrom += u.ad.p1 - pOp->p2; + } +#endif + pIn1->zMalloc = u.ad.zMalloc; + REGISTER_TRACE(u.ad.p2++, pOut); + pIn1++; + pOut++; + } + break; +} + +/* Opcode: Copy P1 P2 P3 * * +** +** Make a copy of registers P1..P1+P3 into registers P2..P2+P3. +** +** This instruction makes a deep copy of the value. A duplicate +** is made of any string or blob constant. See also OP_SCopy. +*/ +case OP_Copy: { +#if 0 /* local variables moved into u.ae */ + int n; +#endif /* local variables moved into u.ae */ + + u.ae.n = pOp->p3; + pIn1 = &aMem[pOp->p1]; + pOut = &aMem[pOp->p2]; + assert( pOut!=pIn1 ); + while( 1 ){ + sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); + Deephemeralize(pOut); +#ifdef SQLITE_DEBUG + pOut->pScopyFrom = 0; +#endif + REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut); + if( (u.ae.n--)==0 ) break; + pOut++; + pIn1++; + } + break; +} + +/* Opcode: SCopy P1 P2 * * * +** +** Make a shallow copy of register P1 into register P2. +** +** This instruction makes a shallow copy of the value. If the value +** is a string or blob, then the copy is only a pointer to the +** original and hence if the original changes so will the copy. +** Worse, if the original is deallocated, the copy becomes invalid. +** Thus the program must guarantee that the original will not change +** during the lifetime of the copy. Use OP_Copy to make a complete +** copy. +*/ +case OP_SCopy: { /* in1, out2 */ + pIn1 = &aMem[pOp->p1]; + pOut = &aMem[pOp->p2]; + assert( pOut!=pIn1 ); + sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); +#ifdef SQLITE_DEBUG + if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1; +#endif + REGISTER_TRACE(pOp->p2, pOut); + break; +} + +/* Opcode: ResultRow P1 P2 * * * +** +** The registers P1 through P1+P2-1 contain a single row of +** results. This opcode causes the sqlite3_step() call to terminate +** with an SQLITE_ROW return code and it sets up the sqlite3_stmt +** structure to provide access to the top P1 values as the result +** row. +*/ +case OP_ResultRow: { +#if 0 /* local variables moved into u.af */ + Mem *pMem; + int i; +#endif /* local variables moved into u.af */ + assert( p->nResColumn==pOp->p2 ); + assert( pOp->p1>0 ); + assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 ); + + /* If this statement has violated immediate foreign key constraints, do + ** not return the number of rows modified. And do not RELEASE the statement + ** transaction. It needs to be rolled back. */ + if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){ + assert( db->flags&SQLITE_CountRows ); + assert( p->usesStmtJournal ); + break; + } + + /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then + ** DML statements invoke this opcode to return the number of rows + ** modified to the user. This is the only way that a VM that + ** opens a statement transaction may invoke this opcode. + ** + ** In case this is such a statement, close any statement transaction + ** opened by this VM before returning control to the user. This is to + ** ensure that statement-transactions are always nested, not overlapping. + ** If the open statement-transaction is not closed here, then the user + ** may step another VM that opens its own statement transaction. This + ** may lead to overlapping statement transactions. + ** + ** The statement transaction is never a top-level transaction. Hence + ** the RELEASE call below can never fail. + */ + assert( p->iStatement==0 || db->flags&SQLITE_CountRows ); + rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE); + if( NEVER(rc!=SQLITE_OK) ){ + break; + } + + /* Invalidate all ephemeral cursor row caches */ + p->cacheCtr = (p->cacheCtr + 2)|1; + + /* Make sure the results of the current row are \000 terminated + ** and have an assigned type. The results are de-ephemeralized as + ** a side effect. + */ + u.af.pMem = p->pResultSet = &aMem[pOp->p1]; + for(u.af.i=0; u.af.ip2; u.af.i++){ + assert( memIsValid(&u.af.pMem[u.af.i]) ); + Deephemeralize(&u.af.pMem[u.af.i]); + assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0 + || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 ); + sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]); + sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]); + REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]); + } + if( db->mallocFailed ) goto no_mem; + + /* Return SQLITE_ROW + */ + p->pc = pc + 1; + rc = SQLITE_ROW; + goto vdbe_return; +} + +/* Opcode: Concat P1 P2 P3 * * +** +** Add the text in register P1 onto the end of the text in +** register P2 and store the result in register P3. +** If either the P1 or P2 text are NULL then store NULL in P3. +** +** P3 = P2 || P1 +** +** It is illegal for P1 and P3 to be the same register. Sometimes, +** if P3 is the same register as P2, the implementation is able +** to avoid a memcpy(). +*/ +case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ +#if 0 /* local variables moved into u.ag */ + i64 nByte; +#endif /* local variables moved into u.ag */ + + pIn1 = &aMem[pOp->p1]; + pIn2 = &aMem[pOp->p2]; + pOut = &aMem[pOp->p3]; + assert( pIn1!=pOut ); + if( (pIn1->flags | pIn2->flags) & MEM_Null ){ + sqlite3VdbeMemSetNull(pOut); + break; + } + if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem; + Stringify(pIn1, encoding); + Stringify(pIn2, encoding); + u.ag.nByte = pIn1->n + pIn2->n; + if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + MemSetTypeFlag(pOut, MEM_Str); + if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){ + goto no_mem; + } + if( pOut!=pIn2 ){ + memcpy(pOut->z, pIn2->z, pIn2->n); + } + memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); + pOut->z[u.ag.nByte] = 0; + pOut->z[u.ag.nByte+1] = 0; + pOut->flags |= MEM_Term; + pOut->n = (int)u.ag.nByte; + pOut->enc = encoding; + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Add P1 P2 P3 * * +** +** Add the value in register P1 to the value in register P2 +** and store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Multiply P1 P2 P3 * * +** +** +** Multiply the value in register P1 by the value in register P2 +** and store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Subtract P1 P2 P3 * * +** +** Subtract the value in register P1 from the value in register P2 +** and store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Divide P1 P2 P3 * * +** +** Divide the value in register P1 by the value in register P2 +** and store the result in register P3 (P3=P2/P1). If the value in +** register P1 is zero, then the result is NULL. If either input is +** NULL, the result is NULL. +*/ +/* Opcode: Remainder P1 P2 P3 * * +** +** Compute the remainder after integer division of the value in +** register P1 by the value in register P2 and store the result in P3. +** If the value in register P2 is zero the result is NULL. +** If either operand is NULL, the result is NULL. +*/ +case OP_Add: /* same as TK_PLUS, in1, in2, out3 */ +case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */ +case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */ +case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */ +case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ +#if 0 /* local variables moved into u.ah */ + char bIntint; /* Started out as two integer operands */ + int flags; /* Combined MEM_* flags from both inputs */ + i64 iA; /* Integer value of left operand */ + i64 iB; /* Integer value of right operand */ + double rA; /* Real value of left operand */ + double rB; /* Real value of right operand */ +#endif /* local variables moved into u.ah */ + + pIn1 = &aMem[pOp->p1]; + applyNumericAffinity(pIn1); + pIn2 = &aMem[pOp->p2]; + applyNumericAffinity(pIn2); + pOut = &aMem[pOp->p3]; + u.ah.flags = pIn1->flags | pIn2->flags; + if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null; + if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){ + u.ah.iA = pIn1->u.i; + u.ah.iB = pIn2->u.i; + u.ah.bIntint = 1; + switch( pOp->opcode ){ + case OP_Add: if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break; + case OP_Subtract: if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break; + case OP_Multiply: if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break; + case OP_Divide: { + if( u.ah.iA==0 ) goto arithmetic_result_is_null; + if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math; + u.ah.iB /= u.ah.iA; + break; + } + default: { + if( u.ah.iA==0 ) goto arithmetic_result_is_null; + if( u.ah.iA==-1 ) u.ah.iA = 1; + u.ah.iB %= u.ah.iA; + break; + } + } + pOut->u.i = u.ah.iB; + MemSetTypeFlag(pOut, MEM_Int); + }else{ + u.ah.bIntint = 0; +fp_math: + u.ah.rA = sqlite3VdbeRealValue(pIn1); + u.ah.rB = sqlite3VdbeRealValue(pIn2); + switch( pOp->opcode ){ + case OP_Add: u.ah.rB += u.ah.rA; break; + case OP_Subtract: u.ah.rB -= u.ah.rA; break; + case OP_Multiply: u.ah.rB *= u.ah.rA; break; + case OP_Divide: { + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null; + u.ah.rB /= u.ah.rA; + break; + } + default: { + u.ah.iA = (i64)u.ah.rA; + u.ah.iB = (i64)u.ah.rB; + if( u.ah.iA==0 ) goto arithmetic_result_is_null; + if( u.ah.iA==-1 ) u.ah.iA = 1; + u.ah.rB = (double)(u.ah.iB % u.ah.iA); + break; + } + } +#ifdef SQLITE_OMIT_FLOATING_POINT + pOut->u.i = u.ah.rB; + MemSetTypeFlag(pOut, MEM_Int); +#else + if( sqlite3IsNaN(u.ah.rB) ){ + goto arithmetic_result_is_null; + } + pOut->r = u.ah.rB; + MemSetTypeFlag(pOut, MEM_Real); + if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){ + sqlite3VdbeIntegerAffinity(pOut); + } +#endif + } + break; + +arithmetic_result_is_null: + sqlite3VdbeMemSetNull(pOut); + break; +} + +/* Opcode: CollSeq P1 * * P4 +** +** P4 is a pointer to a CollSeq struct. If the next call to a user function +** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will +** be returned. This is used by the built-in min(), max() and nullif() +** functions. +** +** If P1 is not zero, then it is a register that a subsequent min() or +** max() aggregate will set to 1 if the current row is not the minimum or +** maximum. The P1 register is initialized to 0 by this instruction. +** +** The interface used by the implementation of the aforementioned functions +** to retrieve the collation sequence set by this opcode is not available +** publicly, only to user functions defined in func.c. +*/ +case OP_CollSeq: { + assert( pOp->p4type==P4_COLLSEQ ); + if( pOp->p1 ){ + sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0); + } + break; +} + +/* Opcode: Function P1 P2 P3 P4 P5 +** +** Invoke a user function (P4 is a pointer to a Function structure that +** defines the function) with P5 arguments taken from register P2 and +** successors. The result of the function is stored in register P3. +** Register P3 must not be one of the function inputs. +** +** P1 is a 32-bit bitmask indicating whether or not each argument to the +** function was determined to be constant at compile time. If the first +** argument was constant then bit 0 of P1 is set. This is used to determine +** whether meta data associated with a user function argument using the +** sqlite3_set_auxdata() API may be safely retained until the next +** invocation of this opcode. +** +** See also: AggStep and AggFinal +*/ +case OP_Function: { +#if 0 /* local variables moved into u.ai */ + int i; + Mem *pArg; + sqlite3_context ctx; + sqlite3_value **apVal; + int n; +#endif /* local variables moved into u.ai */ + + u.ai.n = pOp->p5; + u.ai.apVal = p->apArg; + assert( u.ai.apVal || u.ai.n==0 ); + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + pOut = &aMem[pOp->p3]; + memAboutToChange(p, pOut); + + assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=(p->nMem-p->nCursor)+1) ); + assert( pOp->p3p2 || pOp->p3>=pOp->p2+u.ai.n ); + u.ai.pArg = &aMem[pOp->p2]; + for(u.ai.i=0; u.ai.ip2+u.ai.i, u.ai.pArg); + } + + assert( pOp->p4type==P4_FUNCDEF ); + u.ai.ctx.pFunc = pOp->p4.pFunc; + u.ai.ctx.s.flags = MEM_Null; + u.ai.ctx.s.db = db; + u.ai.ctx.s.xDel = 0; + u.ai.ctx.s.zMalloc = 0; + u.ai.ctx.iOp = pc; + u.ai.ctx.pVdbe = p; + + /* The output cell may already have a buffer allocated. Move + ** the pointer to u.ai.ctx.s so in case the user-function can use + ** the already allocated buffer instead of allocating a new one. + */ + sqlite3VdbeMemMove(&u.ai.ctx.s, pOut); + MemSetTypeFlag(&u.ai.ctx.s, MEM_Null); + + u.ai.ctx.fErrorOrAux = 0; + if( u.ai.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ + assert( pOp>aOp ); + assert( pOp[-1].p4type==P4_COLLSEQ ); + assert( pOp[-1].opcode==OP_CollSeq ); + u.ai.ctx.pColl = pOp[-1].p4.pColl; + } + db->lastRowid = lastRowid; + (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */ + lastRowid = db->lastRowid; + + if( db->mallocFailed ){ + /* Even though a malloc() has failed, the implementation of the + ** user function may have called an sqlite3_result_XXX() function + ** to return a value. The following call releases any resources + ** associated with such a value. + */ + sqlite3VdbeMemRelease(&u.ai.ctx.s); + goto no_mem; + } + + /* If the function returned an error, throw an exception */ + if( u.ai.ctx.fErrorOrAux ){ + if( u.ai.ctx.isError ){ + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s)); + rc = u.ai.ctx.isError; + } + sqlite3VdbeDeleteAuxData(p, pc, pOp->p1); + } + + /* Copy the result of the function into register P3 */ + sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding); + sqlite3VdbeMemMove(pOut, &u.ai.ctx.s); + if( sqlite3VdbeMemTooBig(pOut) ){ + goto too_big; + } + +#if 0 + /* The app-defined function has done something that as caused this + ** statement to expire. (Perhaps the function called sqlite3_exec() + ** with a CREATE TABLE statement.) + */ + if( p->expired ) rc = SQLITE_ABORT; +#endif + + REGISTER_TRACE(pOp->p3, pOut); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: BitAnd P1 P2 P3 * * +** +** Take the bit-wise AND of the values in register P1 and P2 and +** store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: BitOr P1 P2 P3 * * +** +** Take the bit-wise OR of the values in register P1 and P2 and +** store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: ShiftLeft P1 P2 P3 * * +** +** Shift the integer value in register P2 to the left by the +** number of bits specified by the integer in register P1. +** Store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: ShiftRight P1 P2 P3 * * +** +** Shift the integer value in register P2 to the right by the +** number of bits specified by the integer in register P1. +** Store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */ +case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */ +case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */ +case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ +#if 0 /* local variables moved into u.aj */ + i64 iA; + u64 uA; + i64 iB; + u8 op; +#endif /* local variables moved into u.aj */ + + pIn1 = &aMem[pOp->p1]; + pIn2 = &aMem[pOp->p2]; + pOut = &aMem[pOp->p3]; + if( (pIn1->flags | pIn2->flags) & MEM_Null ){ + sqlite3VdbeMemSetNull(pOut); + break; + } + u.aj.iA = sqlite3VdbeIntValue(pIn2); + u.aj.iB = sqlite3VdbeIntValue(pIn1); + u.aj.op = pOp->opcode; + if( u.aj.op==OP_BitAnd ){ + u.aj.iA &= u.aj.iB; + }else if( u.aj.op==OP_BitOr ){ + u.aj.iA |= u.aj.iB; + }else if( u.aj.iB!=0 ){ + assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft ); + + /* If shifting by a negative amount, shift in the other direction */ + if( u.aj.iB<0 ){ + assert( OP_ShiftRight==OP_ShiftLeft+1 ); + u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op; + u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64; + } + + if( u.aj.iB>=64 ){ + u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1; + }else{ + memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA)); + if( u.aj.op==OP_ShiftLeft ){ + u.aj.uA <<= u.aj.iB; + }else{ + u.aj.uA >>= u.aj.iB; + /* Sign-extend on a right shift of a negative number */ + if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB); + } + memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA)); + } + } + pOut->u.i = u.aj.iA; + MemSetTypeFlag(pOut, MEM_Int); + break; +} + +/* Opcode: AddImm P1 P2 * * * +** +** Add the constant P2 to the value in register P1. +** The result is always an integer. +** +** To force any register to be an integer, just add 0. +*/ +case OP_AddImm: { /* in1 */ + pIn1 = &aMem[pOp->p1]; + memAboutToChange(p, pIn1); + sqlite3VdbeMemIntegerify(pIn1); + pIn1->u.i += pOp->p2; + break; +} + +/* Opcode: MustBeInt P1 P2 * * * +** +** Force the value in register P1 to be an integer. If the value +** in P1 is not an integer and cannot be converted into an integer +** without data loss, then jump immediately to P2, or if P2==0 +** raise an SQLITE_MISMATCH exception. +*/ +case OP_MustBeInt: { /* jump, in1 */ + pIn1 = &aMem[pOp->p1]; + applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); + if( (pIn1->flags & MEM_Int)==0 ){ + if( pOp->p2==0 ){ + rc = SQLITE_MISMATCH; + goto abort_due_to_error; + }else{ + pc = pOp->p2 - 1; + } + }else{ + MemSetTypeFlag(pIn1, MEM_Int); + } + break; +} + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* Opcode: RealAffinity P1 * * * * +** +** If register P1 holds an integer convert it to a real value. +** +** This opcode is used when extracting information from a column that +** has REAL affinity. Such column values may still be stored as +** integers, for space efficiency, but after extraction we want them +** to have only a real value. +*/ +case OP_RealAffinity: { /* in1 */ + pIn1 = &aMem[pOp->p1]; + if( pIn1->flags & MEM_Int ){ + sqlite3VdbeMemRealify(pIn1); + } + break; +} +#endif + +#ifndef SQLITE_OMIT_CAST +/* Opcode: ToText P1 * * * * +** +** Force the value in register P1 to be text. +** If the value is numeric, convert it to a string using the +** equivalent of printf(). Blob values are unchanged and +** are afterwards simply interpreted as text. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToText: { /* same as TK_TO_TEXT, in1 */ + pIn1 = &aMem[pOp->p1]; + memAboutToChange(p, pIn1); + if( pIn1->flags & MEM_Null ) break; + assert( MEM_Str==(MEM_Blob>>3) ); + pIn1->flags |= (pIn1->flags&MEM_Blob)>>3; + applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding); + rc = ExpandBlob(pIn1); + assert( pIn1->flags & MEM_Str || db->mallocFailed ); + pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero); + UPDATE_MAX_BLOBSIZE(pIn1); + break; +} + +/* Opcode: ToBlob P1 * * * * +** +** Force the value in register P1 to be a BLOB. +** If the value is numeric, convert it to a string first. +** Strings are simply reinterpreted as blobs with no change +** to the underlying data. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */ + pIn1 = &aMem[pOp->p1]; + if( pIn1->flags & MEM_Null ) break; + if( (pIn1->flags & MEM_Blob)==0 ){ + applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding); + assert( pIn1->flags & MEM_Str || db->mallocFailed ); + MemSetTypeFlag(pIn1, MEM_Blob); + }else{ + pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob); + } + UPDATE_MAX_BLOBSIZE(pIn1); + break; +} + +/* Opcode: ToNumeric P1 * * * * +** +** Force the value in register P1 to be numeric (either an +** integer or a floating-point number.) +** If the value is text or blob, try to convert it to an using the +** equivalent of atoi() or atof() and store 0 if no such conversion +** is possible. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */ + pIn1 = &aMem[pOp->p1]; + sqlite3VdbeMemNumerify(pIn1); + break; +} +#endif /* SQLITE_OMIT_CAST */ + +/* Opcode: ToInt P1 * * * * +** +** Force the value in register P1 to be an integer. If +** The value is currently a real number, drop its fractional part. +** If the value is text or blob, try to convert it to an integer using the +** equivalent of atoi() and store 0 if no such conversion is possible. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToInt: { /* same as TK_TO_INT, in1 */ + pIn1 = &aMem[pOp->p1]; + if( (pIn1->flags & MEM_Null)==0 ){ + sqlite3VdbeMemIntegerify(pIn1); + } + break; +} + +#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) +/* Opcode: ToReal P1 * * * * +** +** Force the value in register P1 to be a floating point number. +** If The value is currently an integer, convert it. +** If the value is text or blob, try to convert it to an integer using the +** equivalent of atoi() and store 0.0 if no such conversion is possible. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToReal: { /* same as TK_TO_REAL, in1 */ + pIn1 = &aMem[pOp->p1]; + memAboutToChange(p, pIn1); + if( (pIn1->flags & MEM_Null)==0 ){ + sqlite3VdbeMemRealify(pIn1); + } + break; +} +#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */ + +/* Opcode: Lt P1 P2 P3 P4 P5 +** +** Compare the values in register P1 and P3. If reg(P3)flags */ + u16 flags3; /* Copy of initial value of pIn3->flags */ +#endif /* local variables moved into u.ak */ + + pIn1 = &aMem[pOp->p1]; + pIn3 = &aMem[pOp->p3]; + u.ak.flags1 = pIn1->flags; + u.ak.flags3 = pIn3->flags; + if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){ + /* One or both operands are NULL */ + if( pOp->p5 & SQLITE_NULLEQ ){ + /* If SQLITE_NULLEQ is set (which will only happen if the operator is + ** OP_Eq or OP_Ne) then take the jump or not depending on whether + ** or not both operands are null. + */ + assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne ); + assert( (u.ak.flags1 & MEM_Cleared)==0 ); + if( (u.ak.flags1&MEM_Null)!=0 + && (u.ak.flags3&MEM_Null)!=0 + && (u.ak.flags3&MEM_Cleared)==0 + ){ + u.ak.res = 0; /* Results are equal */ + }else{ + u.ak.res = 1; /* Results are not equal */ + } + }else{ + /* SQLITE_NULLEQ is clear and at least one operand is NULL, + ** then the result is always NULL. + ** The jump is taken if the SQLITE_JUMPIFNULL bit is set. + */ + if( pOp->p5 & SQLITE_JUMPIFNULL ){ + pc = pOp->p2-1; + }else if( pOp->p5 & SQLITE_STOREP2 ){ + pOut = &aMem[pOp->p2]; + MemSetTypeFlag(pOut, MEM_Null); + REGISTER_TRACE(pOp->p2, pOut); + } + break; + } + }else{ + /* Neither operand is NULL. Do a comparison. */ + u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK; + if( u.ak.affinity ){ + applyAffinity(pIn1, u.ak.affinity, encoding); + applyAffinity(pIn3, u.ak.affinity, encoding); + if( db->mallocFailed ) goto no_mem; + } + + assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 ); + ExpandBlob(pIn1); + ExpandBlob(pIn3); + u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); + } + switch( pOp->opcode ){ + case OP_Eq: u.ak.res = u.ak.res==0; break; + case OP_Ne: u.ak.res = u.ak.res!=0; break; + case OP_Lt: u.ak.res = u.ak.res<0; break; + case OP_Le: u.ak.res = u.ak.res<=0; break; + case OP_Gt: u.ak.res = u.ak.res>0; break; + default: u.ak.res = u.ak.res>=0; break; + } + + if( pOp->p5 & SQLITE_STOREP2 ){ + pOut = &aMem[pOp->p2]; + memAboutToChange(p, pOut); + MemSetTypeFlag(pOut, MEM_Int); + pOut->u.i = u.ak.res; + REGISTER_TRACE(pOp->p2, pOut); + }else if( u.ak.res ){ + pc = pOp->p2-1; + } + + /* Undo any changes made by applyAffinity() to the input registers. */ + pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask); + pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask); + break; +} + +/* Opcode: Permutation * * * P4 * +** +** Set the permutation used by the OP_Compare operator to be the array +** of integers in P4. +** +** The permutation is only valid until the next OP_Compare that has +** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should +** occur immediately prior to the OP_Compare. +*/ +case OP_Permutation: { + assert( pOp->p4type==P4_INTARRAY ); + assert( pOp->p4.ai ); + aPermute = pOp->p4.ai; + break; +} + +/* Opcode: Compare P1 P2 P3 P4 P5 +** +** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this +** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of +** the comparison for use by the next OP_Jump instruct. +** +** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is +** determined by the most recent OP_Permutation operator. If the +** OPFLAG_PERMUTE bit is clear, then register are compared in sequential +** order. +** +** P4 is a KeyInfo structure that defines collating sequences and sort +** orders for the comparison. The permutation applies to registers +** only. The KeyInfo elements are used sequentially. +** +** The comparison is a sort comparison, so NULLs compare equal, +** NULLs are less than numbers, numbers are less than strings, +** and strings are less than blobs. +*/ +case OP_Compare: { +#if 0 /* local variables moved into u.al */ + int n; + int i; + int p1; + int p2; + const KeyInfo *pKeyInfo; + int idx; + CollSeq *pColl; /* Collating sequence to use on this term */ + int bRev; /* True for DESCENDING sort order */ +#endif /* local variables moved into u.al */ + + if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0; + u.al.n = pOp->p3; + u.al.pKeyInfo = pOp->p4.pKeyInfo; + assert( u.al.n>0 ); + assert( u.al.pKeyInfo!=0 ); + u.al.p1 = pOp->p1; + u.al.p2 = pOp->p2; +#if SQLITE_DEBUG + if( aPermute ){ + int k, mx = 0; + for(k=0; kmx ) mx = aPermute[k]; + assert( u.al.p1>0 && u.al.p1+mx<=(p->nMem-p->nCursor)+1 ); + assert( u.al.p2>0 && u.al.p2+mx<=(p->nMem-p->nCursor)+1 ); + }else{ + assert( u.al.p1>0 && u.al.p1+u.al.n<=(p->nMem-p->nCursor)+1 ); + assert( u.al.p2>0 && u.al.p2+u.al.n<=(p->nMem-p->nCursor)+1 ); + } +#endif /* SQLITE_DEBUG */ + for(u.al.i=0; u.al.inField ); + u.al.pColl = u.al.pKeyInfo->aColl[u.al.i]; + u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i]; + iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl); + if( iCompare ){ + if( u.al.bRev ) iCompare = -iCompare; + break; + } + } + aPermute = 0; + break; +} + +/* Opcode: Jump P1 P2 P3 * * +** +** Jump to the instruction at address P1, P2, or P3 depending on whether +** in the most recent OP_Compare instruction the P1 vector was less than +** equal to, or greater than the P2 vector, respectively. +*/ +case OP_Jump: { /* jump */ + if( iCompare<0 ){ + pc = pOp->p1 - 1; + }else if( iCompare==0 ){ + pc = pOp->p2 - 1; + }else{ + pc = pOp->p3 - 1; + } + break; +} + +/* Opcode: And P1 P2 P3 * * +** +** Take the logical AND of the values in registers P1 and P2 and +** write the result into register P3. +** +** If either P1 or P2 is 0 (false) then the result is 0 even if +** the other input is NULL. A NULL and true or two NULLs give +** a NULL output. +*/ +/* Opcode: Or P1 P2 P3 * * +** +** Take the logical OR of the values in register P1 and P2 and +** store the answer in register P3. +** +** If either P1 or P2 is nonzero (true) then the result is 1 (true) +** even if the other input is NULL. A NULL and false or two NULLs +** give a NULL output. +*/ +case OP_And: /* same as TK_AND, in1, in2, out3 */ +case OP_Or: { /* same as TK_OR, in1, in2, out3 */ +#if 0 /* local variables moved into u.am */ + int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ + int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ +#endif /* local variables moved into u.am */ + + pIn1 = &aMem[pOp->p1]; + if( pIn1->flags & MEM_Null ){ + u.am.v1 = 2; + }else{ + u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0; + } + pIn2 = &aMem[pOp->p2]; + if( pIn2->flags & MEM_Null ){ + u.am.v2 = 2; + }else{ + u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0; + } + if( pOp->opcode==OP_And ){ + static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 }; + u.am.v1 = and_logic[u.am.v1*3+u.am.v2]; + }else{ + static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 }; + u.am.v1 = or_logic[u.am.v1*3+u.am.v2]; + } + pOut = &aMem[pOp->p3]; + if( u.am.v1==2 ){ + MemSetTypeFlag(pOut, MEM_Null); + }else{ + pOut->u.i = u.am.v1; + MemSetTypeFlag(pOut, MEM_Int); + } + break; +} + +/* Opcode: Not P1 P2 * * * +** +** Interpret the value in register P1 as a boolean value. Store the +** boolean complement in register P2. If the value in register P1 is +** NULL, then a NULL is stored in P2. +*/ +case OP_Not: { /* same as TK_NOT, in1, out2 */ + pIn1 = &aMem[pOp->p1]; + pOut = &aMem[pOp->p2]; + if( pIn1->flags & MEM_Null ){ + sqlite3VdbeMemSetNull(pOut); + }else{ + sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1)); + } + break; +} + +/* Opcode: BitNot P1 P2 * * * +** +** Interpret the content of register P1 as an integer. Store the +** ones-complement of the P1 value into register P2. If P1 holds +** a NULL then store a NULL in P2. +*/ +case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ + pIn1 = &aMem[pOp->p1]; + pOut = &aMem[pOp->p2]; + if( pIn1->flags & MEM_Null ){ + sqlite3VdbeMemSetNull(pOut); + }else{ + sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1)); + } + break; +} + +/* Opcode: Once P1 P2 * * * +** +** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise, +** set the flag and fall through to the next instruction. +*/ +case OP_Once: { /* jump */ + assert( pOp->p1nOnceFlag ); + if( p->aOnceFlag[pOp->p1] ){ + pc = pOp->p2-1; + }else{ + p->aOnceFlag[pOp->p1] = 1; + } + break; +} + +/* Opcode: If P1 P2 P3 * * +** +** Jump to P2 if the value in register P1 is true. The value +** is considered true if it is numeric and non-zero. If the value +** in P1 is NULL then take the jump if P3 is non-zero. +*/ +/* Opcode: IfNot P1 P2 P3 * * +** +** Jump to P2 if the value in register P1 is False. The value +** is considered false if it has a numeric value of zero. If the value +** in P1 is NULL then take the jump if P3 is zero. +*/ +case OP_If: /* jump, in1 */ +case OP_IfNot: { /* jump, in1 */ +#if 0 /* local variables moved into u.an */ + int c; +#endif /* local variables moved into u.an */ + pIn1 = &aMem[pOp->p1]; + if( pIn1->flags & MEM_Null ){ + u.an.c = pOp->p3; + }else{ +#ifdef SQLITE_OMIT_FLOATING_POINT + u.an.c = sqlite3VdbeIntValue(pIn1)!=0; +#else + u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0; +#endif + if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c; + } + if( u.an.c ){ + pc = pOp->p2-1; + } + break; +} + +/* Opcode: IsNull P1 P2 * * * +** +** Jump to P2 if the value in register P1 is NULL. +*/ +case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */ + pIn1 = &aMem[pOp->p1]; + if( (pIn1->flags & MEM_Null)!=0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: NotNull P1 P2 * * * +** +** Jump to P2 if the value in register P1 is not NULL. +*/ +case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ + pIn1 = &aMem[pOp->p1]; + if( (pIn1->flags & MEM_Null)==0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: Column P1 P2 P3 P4 P5 +** +** Interpret the data that cursor P1 points to as a structure built using +** the MakeRecord instruction. (See the MakeRecord opcode for additional +** information about the format of the data.) Extract the P2-th column +** from this record. If there are less that (P2+1) +** values in the record, extract a NULL. +** +** The value extracted is stored in register P3. +** +** If the column contains fewer than P2 fields, then extract a NULL. Or, +** if the P4 argument is a P4_MEM use the value of the P4 argument as +** the result. +** +** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor, +** then the cache of the cursor is reset prior to extracting the column. +** The first OP_Column against a pseudo-table after the value of the content +** register has changed should have this bit set. +** +** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when +** the result is guaranteed to only be used as the argument of a length() +** or typeof() function, respectively. The loading of large blobs can be +** skipped for length() and all content loading can be skipped for typeof(). +*/ +case OP_Column: { +#if 0 /* local variables moved into u.ao */ + u32 payloadSize; /* Number of bytes in the record */ + i64 payloadSize64; /* Number of bytes in the record */ + int p1; /* P1 value of the opcode */ + int p2; /* column number to retrieve */ + VdbeCursor *pC; /* The VDBE cursor */ + char *zRec; /* Pointer to complete record-data */ + BtCursor *pCrsr; /* The BTree cursor */ + u32 *aType; /* aType[i] holds the numeric type of the i-th column */ + u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */ + int nField; /* number of fields in the record */ + int len; /* The length of the serialized data for the column */ + int i; /* Loop counter */ + char *zData; /* Part of the record being decoded */ + Mem *pDest; /* Where to write the extracted value */ + Mem sMem; /* For storing the record being decoded */ + u8 *zIdx; /* Index into header */ + u8 *zEndHdr; /* Pointer to first byte after the header */ + u32 offset; /* Offset into the data */ + u32 szField; /* Number of bytes in the content of a field */ + int szHdr; /* Size of the header size field at start of record */ + int avail; /* Number of bytes of available data */ + u32 t; /* A type code from the record header */ + Mem *pReg; /* PseudoTable input register */ +#endif /* local variables moved into u.ao */ + + + u.ao.p1 = pOp->p1; + u.ao.p2 = pOp->p2; + u.ao.pC = 0; + memset(&u.ao.sMem, 0, sizeof(u.ao.sMem)); + assert( u.ao.p1nCursor ); + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + u.ao.pDest = &aMem[pOp->p3]; + memAboutToChange(p, u.ao.pDest); + u.ao.zRec = 0; + + /* This block sets the variable u.ao.payloadSize to be the total number of + ** bytes in the record. + ** + ** u.ao.zRec is set to be the complete text of the record if it is available. + ** The complete record text is always available for pseudo-tables + ** If the record is stored in a cursor, the complete record text + ** might be available in the u.ao.pC->aRow cache. Or it might not be. + ** If the data is unavailable, u.ao.zRec is set to NULL. + ** + ** We also compute the number of columns in the record. For cursors, + ** the number of columns is stored in the VdbeCursor.nField element. + */ + u.ao.pC = p->apCsr[u.ao.p1]; + assert( u.ao.pC!=0 ); +#ifndef SQLITE_OMIT_VIRTUALTABLE + assert( u.ao.pC->pVtabCursor==0 ); +#endif + u.ao.pCrsr = u.ao.pC->pCursor; + if( u.ao.pCrsr!=0 ){ + /* The record is stored in a B-Tree */ + rc = sqlite3VdbeCursorMoveto(u.ao.pC); + if( rc ) goto abort_due_to_error; + if( u.ao.pC->nullRow ){ + u.ao.payloadSize = 0; + }else if( u.ao.pC->cacheStatus==p->cacheCtr ){ + u.ao.payloadSize = u.ao.pC->payloadSize; + u.ao.zRec = (char*)u.ao.pC->aRow; + }else if( u.ao.pC->isIndex ){ + assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) ); + VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64); + assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */ + /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the + ** payload size, so it is impossible for u.ao.payloadSize64 to be + ** larger than 32 bits. */ + assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 ); + u.ao.payloadSize = (u32)u.ao.payloadSize64; + }else{ + assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) ); + VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize); + assert( rc==SQLITE_OK ); /* DataSize() cannot fail */ + } + }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){ + u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg]; + if( u.ao.pC->multiPseudo ){ + sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem); + Deephemeralize(u.ao.pDest); + goto op_column_out; + } + assert( u.ao.pReg->flags & MEM_Blob ); + assert( memIsValid(u.ao.pReg) ); + u.ao.payloadSize = u.ao.pReg->n; + u.ao.zRec = u.ao.pReg->z; + u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr; + assert( u.ao.payloadSize==0 || u.ao.zRec!=0 ); + }else{ + /* Consider the row to be NULL */ + u.ao.payloadSize = 0; + } + + /* If u.ao.payloadSize is 0, then just store a NULL. This can happen because of + ** nullRow or because of a corrupt database. */ + if( u.ao.payloadSize==0 ){ + MemSetTypeFlag(u.ao.pDest, MEM_Null); + goto op_column_out; + } + assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 ); + if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + + u.ao.nField = u.ao.pC->nField; + assert( u.ao.p2aType; + if( u.ao.pC->cacheStatus==p->cacheCtr ){ + u.ao.aOffset = u.ao.pC->aOffset; + }else{ + assert(u.ao.aType); + u.ao.avail = 0; + u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField]; + u.ao.pC->payloadSize = u.ao.payloadSize; + u.ao.pC->cacheStatus = p->cacheCtr; + + /* Figure out how many bytes are in the header */ + if( u.ao.zRec ){ + u.ao.zData = u.ao.zRec; + }else{ + if( u.ao.pC->isIndex ){ + u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail); + }else{ + u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail); + } + /* If KeyFetch()/DataFetch() managed to get the entire payload, + ** save the payload in the u.ao.pC->aRow cache. That will save us from + ** having to make additional calls to fetch the content portion of + ** the record. + */ + assert( u.ao.avail>=0 ); + if( u.ao.payloadSize <= (u32)u.ao.avail ){ + u.ao.zRec = u.ao.zData; + u.ao.pC->aRow = (u8*)u.ao.zData; + }else{ + u.ao.pC->aRow = 0; + } + } + /* The following assert is true in all cases except when + ** the database file has been corrupted externally. + ** assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */ + u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset); + + /* Make sure a corrupt database has not given us an oversize header. + ** Do this now to avoid an oversize memory allocation. + ** + ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte + ** types use so much data space that there can only be 4096 and 32 of + ** them, respectively. So the maximum header length results from a + ** 3-byte type for each of the maximum of 32768 columns plus three + ** extra bytes for the header length itself. 32768*3 + 3 = 98307. + */ + if( u.ao.offset > 98307 ){ + rc = SQLITE_CORRUPT_BKPT; + goto op_column_out; + } + + /* Compute in u.ao.len the number of bytes of data we need to read in order + ** to get u.ao.nField type values. u.ao.offset is an upper bound on this. But + ** u.ao.nField might be significantly less than the true number of columns + ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset. + ** We want to minimize u.ao.len in order to limit the size of the memory + ** allocation, especially if a corrupt database file has caused u.ao.offset + ** to be oversized. Offset is limited to 98307 above. But 98307 might + ** still exceed Robson memory allocation limits on some configurations. + ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3 + ** will likely be much smaller since u.ao.nField will likely be less than + ** 20 or so. This insures that Robson memory allocation limits are + ** not exceeded even for corrupt database files. + */ + u.ao.len = u.ao.nField*5 + 3; + if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset; + + /* The KeyFetch() or DataFetch() above are fast and will get the entire + ** record header in most cases. But they will fail to get the complete + ** record header if the record header does not fit on a single page + ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to + ** acquire the complete header text. + */ + if( !u.ao.zRec && u.ao.availisIndex, &u.ao.sMem); + if( rc!=SQLITE_OK ){ + goto op_column_out; + } + u.ao.zData = u.ao.sMem.z; + } + u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len]; + u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr]; + + /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[] + ** arrays. u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th + ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning + ** of the record to the start of the data for the u.ao.i-th column + */ + for(u.ao.i=0; u.ao.i u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize) + || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){ + rc = SQLITE_CORRUPT_BKPT; + goto op_column_out; + } + } + + /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then + ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero, + ** then there are not enough fields in the record to satisfy the + ** request. In this case, set the value NULL or to P4 if P4 is + ** a pointer to a Mem object. + */ + if( u.ao.aOffset[u.ao.p2] ){ + assert( rc==SQLITE_OK ); + if( u.ao.zRec ){ + /* This is the common case where the whole row fits on a single page */ + VdbeMemRelease(u.ao.pDest); + sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest); + }else{ + /* This branch happens only when the row overflows onto multiple pages */ + u.ao.t = u.ao.aType[u.ao.p2]; + if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0 + && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0) + ){ + /* Content is irrelevant for the typeof() function and for + ** the length(X) function if X is a blob. So we might as well use + ** bogus content rather than reading content from disk. NULL works + ** for text and blob and whatever is in the u.ao.payloadSize64 variable + ** will work for everything else. */ + u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0; + }else{ + u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t); + sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest); + rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len, u.ao.pC->isIndex, + &u.ao.sMem); + if( rc!=SQLITE_OK ){ + goto op_column_out; + } + u.ao.zData = u.ao.sMem.z; + } + sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest); + } + u.ao.pDest->enc = encoding; + }else{ + if( pOp->p4type==P4_MEM ){ + sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static); + }else{ + MemSetTypeFlag(u.ao.pDest, MEM_Null); + } + } + + /* If we dynamically allocated space to hold the data (in the + ** sqlite3VdbeMemFromBtree() call above) then transfer control of that + ** dynamically allocated space over to the u.ao.pDest structure. + ** This prevents a memory copy. + */ + if( u.ao.sMem.zMalloc ){ + assert( u.ao.sMem.z==u.ao.sMem.zMalloc ); + assert( !(u.ao.pDest->flags & MEM_Dyn) ); + assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z ); + u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static); + u.ao.pDest->flags |= MEM_Term; + u.ao.pDest->z = u.ao.sMem.z; + u.ao.pDest->zMalloc = u.ao.sMem.zMalloc; + } + + rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest); + +op_column_out: + UPDATE_MAX_BLOBSIZE(u.ao.pDest); + REGISTER_TRACE(pOp->p3, u.ao.pDest); + break; +} + +/* Opcode: Affinity P1 P2 * P4 * +** +** Apply affinities to a range of P2 registers starting with P1. +** +** P4 is a string that is P2 characters long. The nth character of the +** string indicates the column affinity that should be used for the nth +** memory cell in the range. +*/ +case OP_Affinity: { +#if 0 /* local variables moved into u.ap */ + const char *zAffinity; /* The affinity to be applied */ + char cAff; /* A single character of affinity */ +#endif /* local variables moved into u.ap */ + + u.ap.zAffinity = pOp->p4.z; + assert( u.ap.zAffinity!=0 ); + assert( u.ap.zAffinity[pOp->p2]==0 ); + pIn1 = &aMem[pOp->p1]; + while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){ + assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] ); + assert( memIsValid(pIn1) ); + ExpandBlob(pIn1); + applyAffinity(pIn1, u.ap.cAff, encoding); + pIn1++; + } + break; +} + +/* Opcode: MakeRecord P1 P2 P3 P4 * +** +** Convert P2 registers beginning with P1 into the [record format] +** use as a data record in a database table or as a key +** in an index. The OP_Column opcode can decode the record later. +** +** P4 may be a string that is P2 characters long. The nth character of the +** string indicates the column affinity that should be used for the nth +** field of the index key. +** +** The mapping from character to affinity is given by the SQLITE_AFF_ +** macros defined in sqliteInt.h. +** +** If P4 is NULL then all index fields have the affinity NONE. +*/ +case OP_MakeRecord: { +#if 0 /* local variables moved into u.aq */ + u8 *zNewRecord; /* A buffer to hold the data for the new record */ + Mem *pRec; /* The new record */ + u64 nData; /* Number of bytes of data space */ + int nHdr; /* Number of bytes of header space */ + i64 nByte; /* Data space required for this record */ + int nZero; /* Number of zero bytes at the end of the record */ + int nVarint; /* Number of bytes in a varint */ + u32 serial_type; /* Type field */ + Mem *pData0; /* First field to be combined into the record */ + Mem *pLast; /* Last field of the record */ + int nField; /* Number of fields in the record */ + char *zAffinity; /* The affinity string for the record */ + int file_format; /* File format to use for encoding */ + int i; /* Space used in zNewRecord[] */ + int len; /* Length of a field */ +#endif /* local variables moved into u.aq */ + + /* Assuming the record contains N fields, the record format looks + ** like this: + ** + ** ------------------------------------------------------------------------ + ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | + ** ------------------------------------------------------------------------ + ** + ** Data(0) is taken from register P1. Data(1) comes from register P1+1 + ** and so froth. + ** + ** Each type field is a varint representing the serial type of the + ** corresponding data element (see sqlite3VdbeSerialType()). The + ** hdr-size field is also a varint which is the offset from the beginning + ** of the record to data0. + */ + u.aq.nData = 0; /* Number of bytes of data space */ + u.aq.nHdr = 0; /* Number of bytes of header space */ + u.aq.nZero = 0; /* Number of zero bytes at the end of the record */ + u.aq.nField = pOp->p1; + u.aq.zAffinity = pOp->p4.z; + assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=(p->nMem-p->nCursor)+1 ); + u.aq.pData0 = &aMem[u.aq.nField]; + u.aq.nField = pOp->p2; + u.aq.pLast = &u.aq.pData0[u.aq.nField-1]; + u.aq.file_format = p->minWriteFileFormat; + + /* Identify the output register */ + assert( pOp->p3p1 || pOp->p3>=pOp->p1+pOp->p2 ); + pOut = &aMem[pOp->p3]; + memAboutToChange(p, pOut); + + /* Loop through the elements that will make up the record to figure + ** out how much space is required for the new record. + */ + for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ + assert( memIsValid(u.aq.pRec) ); + if( u.aq.zAffinity ){ + applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding); + } + if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){ + sqlite3VdbeMemExpandBlob(u.aq.pRec); + } + u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format); + u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type); + u.aq.nData += u.aq.len; + u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type); + if( u.aq.pRec->flags & MEM_Zero ){ + /* Only pure zero-filled BLOBs can be input to this Opcode. + ** We do not allow blobs with a prefix and a zero-filled tail. */ + u.aq.nZero += u.aq.pRec->u.nZero; + }else if( u.aq.len ){ + u.aq.nZero = 0; + } + } + + /* Add the initial header varint and total the size */ + u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr); + if( u.aq.nVarintdb->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + + /* Make sure the output register has a buffer large enough to store + ** the new record. The output register (pOp->p3) is not allowed to + ** be one of the input registers (because the following call to + ** sqlite3VdbeMemGrow() could clobber the value before it is used). + */ + if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){ + goto no_mem; + } + u.aq.zNewRecord = (u8 *)pOut->z; + + /* Write the record */ + u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr); + for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ + u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format); + u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type); /* serial type */ + } + for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ /* serial data */ + u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format); + } + assert( u.aq.i==u.aq.nByte ); + + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + pOut->n = (int)u.aq.nByte; + pOut->flags = MEM_Blob | MEM_Dyn; + pOut->xDel = 0; + if( u.aq.nZero ){ + pOut->u.nZero = u.aq.nZero; + pOut->flags |= MEM_Zero; + } + pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */ + REGISTER_TRACE(pOp->p3, pOut); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Count P1 P2 * * * +** +** Store the number of entries (an integer value) in the table or index +** opened by cursor P1 in register P2 +*/ +#ifndef SQLITE_OMIT_BTREECOUNT +case OP_Count: { /* out2-prerelease */ +#if 0 /* local variables moved into u.ar */ + i64 nEntry; + BtCursor *pCrsr; +#endif /* local variables moved into u.ar */ + + u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor; + if( ALWAYS(u.ar.pCrsr) ){ + rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry); + }else{ + u.ar.nEntry = 0; + } + pOut->u.i = u.ar.nEntry; + break; +} +#endif + +/* Opcode: Savepoint P1 * * P4 * +** +** Open, release or rollback the savepoint named by parameter P4, depending +** on the value of P1. To open a new savepoint, P1==0. To release (commit) an +** existing savepoint, P1==1, or to rollback an existing savepoint P1==2. +*/ +case OP_Savepoint: { +#if 0 /* local variables moved into u.as */ + int p1; /* Value of P1 operand */ + char *zName; /* Name of savepoint */ + int nName; + Savepoint *pNew; + Savepoint *pSavepoint; + Savepoint *pTmp; + int iSavepoint; + int ii; +#endif /* local variables moved into u.as */ + + u.as.p1 = pOp->p1; + u.as.zName = pOp->p4.z; + + /* Assert that the u.as.p1 parameter is valid. Also that if there is no open + ** transaction, then there cannot be any savepoints. + */ + assert( db->pSavepoint==0 || db->autoCommit==0 ); + assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK ); + assert( db->pSavepoint || db->isTransactionSavepoint==0 ); + assert( checkSavepointCount(db) ); + assert( p->bIsReader ); + + if( u.as.p1==SAVEPOINT_BEGIN ){ + if( db->nVdbeWrite>0 ){ + /* A new savepoint cannot be created if there are active write + ** statements (i.e. open read/write incremental blob handles). + */ + sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - " + "SQL statements in progress"); + rc = SQLITE_BUSY; + }else{ + u.as.nName = sqlite3Strlen30(u.as.zName); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + /* This call is Ok even if this savepoint is actually a transaction + ** savepoint (and therefore should not prompt xSavepoint()) callbacks. + ** If this is a transaction savepoint being opened, it is guaranteed + ** that the db->aVTrans[] array is empty. */ + assert( db->autoCommit==0 || db->nVTrans==0 ); + rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, + db->nStatement+db->nSavepoint); + if( rc!=SQLITE_OK ) goto abort_due_to_error; +#endif + + /* Create a new savepoint structure. */ + u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1); + if( u.as.pNew ){ + u.as.pNew->zName = (char *)&u.as.pNew[1]; + memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1); + + /* If there is no open transaction, then mark this as a special + ** "transaction savepoint". */ + if( db->autoCommit ){ + db->autoCommit = 0; + db->isTransactionSavepoint = 1; + }else{ + db->nSavepoint++; + } + + /* Link the new savepoint into the database handle's list. */ + u.as.pNew->pNext = db->pSavepoint; + db->pSavepoint = u.as.pNew; + u.as.pNew->nDeferredCons = db->nDeferredCons; + u.as.pNew->nDeferredImmCons = db->nDeferredImmCons; + } + } + }else{ + u.as.iSavepoint = 0; + + /* Find the named savepoint. If there is no such savepoint, then an + ** an error is returned to the user. */ + for( + u.as.pSavepoint = db->pSavepoint; + u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName); + u.as.pSavepoint = u.as.pSavepoint->pNext + ){ + u.as.iSavepoint++; + } + if( !u.as.pSavepoint ){ + sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName); + rc = SQLITE_ERROR; + }else if( db->nVdbeWrite>0 && u.as.p1==SAVEPOINT_RELEASE ){ + /* It is not possible to release (commit) a savepoint if there are + ** active write statements. + */ + sqlite3SetString(&p->zErrMsg, db, + "cannot release savepoint - SQL statements in progress" + ); + rc = SQLITE_BUSY; + }else{ + + /* Determine whether or not this is a transaction savepoint. If so, + ** and this is a RELEASE command, then the current transaction + ** is committed. + */ + int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint; + if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){ + if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ + goto vdbe_return; + } + db->autoCommit = 1; + if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ + p->pc = pc; + db->autoCommit = 0; + p->rc = rc = SQLITE_BUSY; + goto vdbe_return; + } + db->isTransactionSavepoint = 0; + rc = p->rc; + }else{ + u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1; + if( u.as.p1==SAVEPOINT_ROLLBACK ){ + for(u.as.ii=0; u.as.iinDb; u.as.ii++){ + sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT); + } + } + for(u.as.ii=0; u.as.iinDb; u.as.ii++){ + rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + } + if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){ + sqlite3ExpirePreparedStatements(db); + sqlite3ResetAllSchemasOfConnection(db); + db->flags = (db->flags | SQLITE_InternChanges); + } + } + + /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all + ** savepoints nested inside of the savepoint being operated on. */ + while( db->pSavepoint!=u.as.pSavepoint ){ + u.as.pTmp = db->pSavepoint; + db->pSavepoint = u.as.pTmp->pNext; + sqlite3DbFree(db, u.as.pTmp); + db->nSavepoint--; + } + + /* If it is a RELEASE, then destroy the savepoint being operated on + ** too. If it is a ROLLBACK TO, then set the number of deferred + ** constraint violations present in the database to the value stored + ** when the savepoint was created. */ + if( u.as.p1==SAVEPOINT_RELEASE ){ + assert( u.as.pSavepoint==db->pSavepoint ); + db->pSavepoint = u.as.pSavepoint->pNext; + sqlite3DbFree(db, u.as.pSavepoint); + if( !isTransaction ){ + db->nSavepoint--; + } + }else{ + db->nDeferredCons = u.as.pSavepoint->nDeferredCons; + db->nDeferredImmCons = u.as.pSavepoint->nDeferredImmCons; + } + + if( !isTransaction ){ + rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + } + } + } + + break; +} + +/* Opcode: AutoCommit P1 P2 * * * +** +** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll +** back any currently active btree transactions. If there are any active +** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if +** there are active writing VMs or active VMs that use shared cache. +** +** This instruction causes the VM to halt. +*/ +case OP_AutoCommit: { +#if 0 /* local variables moved into u.at */ + int desiredAutoCommit; + int iRollback; + int turnOnAC; +#endif /* local variables moved into u.at */ + + u.at.desiredAutoCommit = pOp->p1; + u.at.iRollback = pOp->p2; + u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit; + assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 ); + assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 ); + assert( db->nVdbeActive>0 ); /* At least this one VM is active */ + assert( p->bIsReader ); + +#if 0 + if( u.at.turnOnAC && u.at.iRollback && db->nVdbeActive>1 ){ + /* If this instruction implements a ROLLBACK and other VMs are + ** still running, and a transaction is active, return an error indicating + ** that the other VMs must complete first. + */ + sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - " + "SQL statements in progress"); + rc = SQLITE_BUSY; + }else +#endif + if( u.at.turnOnAC && !u.at.iRollback && db->nVdbeWrite>0 ){ + /* If this instruction implements a COMMIT and other VMs are writing + ** return an error indicating that the other VMs must complete first. + */ + sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - " + "SQL statements in progress"); + rc = SQLITE_BUSY; + }else if( u.at.desiredAutoCommit!=db->autoCommit ){ + if( u.at.iRollback ){ + assert( u.at.desiredAutoCommit==1 ); + sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + db->autoCommit = 1; + }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ + goto vdbe_return; + }else{ + db->autoCommit = (u8)u.at.desiredAutoCommit; + if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ + p->pc = pc; + db->autoCommit = (u8)(1-u.at.desiredAutoCommit); + p->rc = rc = SQLITE_BUSY; + goto vdbe_return; + } + } + assert( db->nStatement==0 ); + sqlite3CloseSavepoints(db); + if( p->rc==SQLITE_OK ){ + rc = SQLITE_DONE; + }else{ + rc = SQLITE_ERROR; + } + goto vdbe_return; + }else{ + sqlite3SetString(&p->zErrMsg, db, + (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":( + (u.at.iRollback)?"cannot rollback - no transaction is active": + "cannot commit - no transaction is active")); + + rc = SQLITE_ERROR; + } + break; +} + +/* Opcode: Transaction P1 P2 * * * +** +** Begin a transaction. The transaction ends when a Commit or Rollback +** opcode is encountered. Depending on the ON CONFLICT setting, the +** transaction might also be rolled back if an error is encountered. +** +** P1 is the index of the database file on which the transaction is +** started. Index 0 is the main database file and index 1 is the +** file used for temporary tables. Indices of 2 or more are used for +** attached databases. +** +** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is +** obtained on the database file when a write-transaction is started. No +** other process can start another write transaction while this transaction is +** underway. Starting a write transaction also creates a rollback journal. A +** write transaction must be started before any changes can be made to the +** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is +** also obtained on the file. +** +** If a write-transaction is started and the Vdbe.usesStmtJournal flag is +** true (this flag is set if the Vdbe may modify more than one row and may +** throw an ABORT exception), a statement transaction may also be opened. +** More specifically, a statement transaction is opened iff the database +** connection is currently not in autocommit mode, or if there are other +** active statements. A statement transaction allows the changes made by this +** VDBE to be rolled back after an error without having to roll back the +** entire transaction. If no error is encountered, the statement transaction +** will automatically commit when the VDBE halts. +** +** If P2 is zero, then a read-lock is obtained on the database file. +*/ +case OP_Transaction: { +#if 0 /* local variables moved into u.au */ + Btree *pBt; +#endif /* local variables moved into u.au */ + + assert( p->bIsReader ); + assert( p->readOnly==0 || pOp->p2==0 ); + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){ + rc = SQLITE_READONLY; + goto abort_due_to_error; + } + u.au.pBt = db->aDb[pOp->p1].pBt; + + if( u.au.pBt ){ + rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2); + if( rc==SQLITE_BUSY ){ + p->pc = pc; + p->rc = rc = SQLITE_BUSY; + goto vdbe_return; + } + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + + if( pOp->p2 && p->usesStmtJournal + && (db->autoCommit==0 || db->nVdbeRead>1) + ){ + assert( sqlite3BtreeIsInTrans(u.au.pBt) ); + if( p->iStatement==0 ){ + assert( db->nStatement>=0 && db->nSavepoint>=0 ); + db->nStatement++; + p->iStatement = db->nSavepoint + db->nStatement; + } + + rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1); + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement); + } + + /* Store the current value of the database handles deferred constraint + ** counter. If the statement transaction needs to be rolled back, + ** the value of this counter needs to be restored too. */ + p->nStmtDefCons = db->nDeferredCons; + p->nStmtDefImmCons = db->nDeferredImmCons; + } + } + break; +} + +/* Opcode: ReadCookie P1 P2 P3 * * +** +** Read cookie number P3 from database P1 and write it into register P2. +** P3==1 is the schema version. P3==2 is the database format. +** P3==3 is the recommended pager cache size, and so forth. P1==0 is +** the main database file and P1==1 is the database file used to store +** temporary tables. +** +** There must be a read-lock on the database (either a transaction +** must be started or there must be an open cursor) before +** executing this instruction. +*/ +case OP_ReadCookie: { /* out2-prerelease */ +#if 0 /* local variables moved into u.av */ + int iMeta; + int iDb; + int iCookie; +#endif /* local variables moved into u.av */ + + assert( p->bIsReader ); + u.av.iDb = pOp->p1; + u.av.iCookie = pOp->p3; + assert( pOp->p3=0 && u.av.iDbnDb ); + assert( db->aDb[u.av.iDb].pBt!=0 ); + assert( (p->btreeMask & (((yDbMask)1)<aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta); + pOut->u.i = u.av.iMeta; + break; +} + +/* Opcode: SetCookie P1 P2 P3 * * +** +** Write the content of register P3 (interpreted as an integer) +** into cookie number P2 of database P1. P2==1 is the schema version. +** P2==2 is the database format. P2==3 is the recommended pager cache +** size, and so forth. P1==0 is the main database file and P1==1 is the +** database file used to store temporary tables. +** +** A transaction must be started before executing this opcode. +*/ +case OP_SetCookie: { /* in3 */ +#if 0 /* local variables moved into u.aw */ + Db *pDb; +#endif /* local variables moved into u.aw */ + assert( pOp->p2p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + assert( p->readOnly==0 ); + u.aw.pDb = &db->aDb[pOp->p1]; + assert( u.aw.pDb->pBt!=0 ); + assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); + pIn3 = &aMem[pOp->p3]; + sqlite3VdbeMemIntegerify(pIn3); + /* See note about index shifting on OP_ReadCookie */ + rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i); + if( pOp->p2==BTREE_SCHEMA_VERSION ){ + /* When the schema cookie changes, record the new cookie internally */ + u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i; + db->flags |= SQLITE_InternChanges; + }else if( pOp->p2==BTREE_FILE_FORMAT ){ + /* Record changes in the file format */ + u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i; + } + if( pOp->p1==1 ){ + /* Invalidate all prepared statements whenever the TEMP database + ** schema is changed. Ticket #1644 */ + sqlite3ExpirePreparedStatements(db); + p->expired = 0; + } + break; +} + +/* Opcode: VerifyCookie P1 P2 P3 * * +** +** Check the value of global database parameter number 0 (the +** schema version) and make sure it is equal to P2 and that the +** generation counter on the local schema parse equals P3. +** +** P1 is the database number which is 0 for the main database file +** and 1 for the file holding temporary tables and some higher number +** for auxiliary databases. +** +** The cookie changes its value whenever the database schema changes. +** This operation is used to detect when that the cookie has changed +** and that the current process needs to reread the schema. +** +** Either a transaction needs to have been started or an OP_Open needs +** to be executed (to establish a read lock) before this opcode is +** invoked. +*/ +case OP_VerifyCookie: { +#if 0 /* local variables moved into u.ax */ + int iMeta; + int iGen; + Btree *pBt; +#endif /* local variables moved into u.ax */ + + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); + assert( p->bIsReader ); + u.ax.pBt = db->aDb[pOp->p1].pBt; + if( u.ax.pBt ){ + sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta); + u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration; + }else{ + u.ax.iGen = u.ax.iMeta = 0; + } + if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){ + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed"); + /* If the schema-cookie from the database file matches the cookie + ** stored with the in-memory representation of the schema, do + ** not reload the schema from the database file. + ** + ** If virtual-tables are in use, this is not just an optimization. + ** Often, v-tables store their data in other SQLite tables, which + ** are queried from within xNext() and other v-table methods using + ** prepared queries. If such a query is out-of-date, we do not want to + ** discard the database schema, as the user code implementing the + ** v-table would have to be ready for the sqlite3_vtab structure itself + ** to be invalidated whenever sqlite3_step() is called from within + ** a v-table method. + */ + if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){ + sqlite3ResetOneSchema(db, pOp->p1); + } + + p->expired = 1; + rc = SQLITE_SCHEMA; + } + break; +} + +/* Opcode: OpenRead P1 P2 P3 P4 P5 +** +** Open a read-only cursor for the database table whose root page is +** P2 in a database file. The database file is determined by P3. +** P3==0 means the main database, P3==1 means the database used for +** temporary tables, and P3>1 means used the corresponding attached +** database. Give the new cursor an identifier of P1. The P1 +** values need not be contiguous but all P1 values should be small integers. +** It is an error for P1 to be negative. +** +** If P5!=0 then use the content of register P2 as the root page, not +** the value of P2 itself. +** +** There will be a read lock on the database whenever there is an +** open cursor. If the database was unlocked prior to this instruction +** then a read lock is acquired as part of this instruction. A read +** lock allows other processes to read the database but prohibits +** any other process from modifying the database. The read lock is +** released when all cursors are closed. If this instruction attempts +** to get a read lock but fails, the script terminates with an +** SQLITE_BUSY error code. +** +** The P4 value may be either an integer (P4_INT32) or a pointer to +** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo +** structure, then said structure defines the content and collating +** sequence of the index being opened. Otherwise, if P4 is an integer +** value, it is set to the number of columns in the table. +** +** See also OpenWrite. +*/ +/* Opcode: OpenWrite P1 P2 P3 P4 P5 +** +** Open a read/write cursor named P1 on the table or index whose root +** page is P2. Or if P5!=0 use the content of register P2 to find the +** root page. +** +** The P4 value may be either an integer (P4_INT32) or a pointer to +** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo +** structure, then said structure defines the content and collating +** sequence of the index being opened. Otherwise, if P4 is an integer +** value, it is set to the number of columns in the table, or to the +** largest index of any column of the table that is actually used. +** +** This instruction works just like OpenRead except that it opens the cursor +** in read/write mode. For a given table, there can be one or more read-only +** cursors or a single read/write cursor but not both. +** +** See also OpenRead. +*/ +case OP_OpenRead: +case OP_OpenWrite: { +#if 0 /* local variables moved into u.ay */ + int nField; + KeyInfo *pKeyInfo; + int p2; + int iDb; + int wrFlag; + Btree *pX; + VdbeCursor *pCur; + Db *pDb; +#endif /* local variables moved into u.ay */ + + assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 ); + assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 ); + assert( p->bIsReader ); + assert( pOp->opcode==OP_OpenRead || p->readOnly==0 ); + + if( p->expired ){ + rc = SQLITE_ABORT; + break; + } + + u.ay.nField = 0; + u.ay.pKeyInfo = 0; + u.ay.p2 = pOp->p2; + u.ay.iDb = pOp->p3; + assert( u.ay.iDb>=0 && u.ay.iDbnDb ); + assert( (p->btreeMask & (((yDbMask)1)<aDb[u.ay.iDb]; + u.ay.pX = u.ay.pDb->pBt; + assert( u.ay.pX!=0 ); + if( pOp->opcode==OP_OpenWrite ){ + u.ay.wrFlag = 1; + assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) ); + if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){ + p->minWriteFileFormat = u.ay.pDb->pSchema->file_format; + } + }else{ + u.ay.wrFlag = 0; + } + if( pOp->p5 & OPFLAG_P2ISREG ){ + assert( u.ay.p2>0 ); + assert( u.ay.p2<=(p->nMem-p->nCursor) ); + pIn2 = &aMem[u.ay.p2]; + assert( memIsValid(pIn2) ); + assert( (pIn2->flags & MEM_Int)!=0 ); + sqlite3VdbeMemIntegerify(pIn2); + u.ay.p2 = (int)pIn2->u.i; + /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and + ** that opcode will always set the u.ay.p2 value to 2 or more or else fail. + ** If there were a failure, the prepared statement would have halted + ** before reaching this instruction. */ + if( NEVER(u.ay.p2<2) ) { + rc = SQLITE_CORRUPT_BKPT; + goto abort_due_to_error; + } + } + if( pOp->p4type==P4_KEYINFO ){ + u.ay.pKeyInfo = pOp->p4.pKeyInfo; + u.ay.pKeyInfo->enc = ENC(p->db); + u.ay.nField = u.ay.pKeyInfo->nField+1; + }else if( pOp->p4type==P4_INT32 ){ + u.ay.nField = pOp->p4.i; + } + assert( pOp->p1>=0 ); + u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1); + if( u.ay.pCur==0 ) goto no_mem; + u.ay.pCur->nullRow = 1; + u.ay.pCur->isOrdered = 1; + rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor); + u.ay.pCur->pKeyInfo = u.ay.pKeyInfo; + assert( OPFLAG_BULKCSR==BTREE_BULKLOAD ); + sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR)); + + /* Since it performs no memory allocation or IO, the only value that + ** sqlite3BtreeCursor() may return is SQLITE_OK. */ + assert( rc==SQLITE_OK ); + + /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of + ** SQLite used to check if the root-page flags were sane at this point + ** and report database corruption if they were not, but this check has + ** since moved into the btree layer. */ + u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO; + u.ay.pCur->isIndex = !u.ay.pCur->isTable; + break; +} + +/* Opcode: OpenEphemeral P1 P2 * P4 P5 +** +** Open a new cursor P1 to a transient table. +** The cursor is always opened read/write even if +** the main database is read-only. The ephemeral +** table is deleted automatically when the cursor is closed. +** +** P2 is the number of columns in the ephemeral table. +** The cursor points to a BTree table if P4==0 and to a BTree index +** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure +** that defines the format of keys in the index. +** +** This opcode was once called OpenTemp. But that created +** confusion because the term "temp table", might refer either +** to a TEMP table at the SQL level, or to a table opened by +** this opcode. Then this opcode was call OpenVirtual. But +** that created confusion with the whole virtual-table idea. +** +** The P5 parameter can be a mask of the BTREE_* flags defined +** in btree.h. These flags control aspects of the operation of +** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are +** added automatically. +*/ +/* Opcode: OpenAutoindex P1 P2 * P4 * +** +** This opcode works the same as OP_OpenEphemeral. It has a +** different name to distinguish its use. Tables created using +** by this opcode will be used for automatically created transient +** indices in joins. +*/ +case OP_OpenAutoindex: +case OP_OpenEphemeral: { +#if 0 /* local variables moved into u.az */ + VdbeCursor *pCx; +#endif /* local variables moved into u.az */ + static const int vfsFlags = + SQLITE_OPEN_READWRITE | + SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | + SQLITE_OPEN_DELETEONCLOSE | + SQLITE_OPEN_TRANSIENT_DB; + + assert( pOp->p1>=0 ); + u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1); + if( u.az.pCx==0 ) goto no_mem; + u.az.pCx->nullRow = 1; + rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt, + BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags); + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1); + } + if( rc==SQLITE_OK ){ + /* If a transient index is required, create it by calling + ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before + ** opening it. If a transient table is required, just use the + ** automatically created table with root-page 1 (an BLOB_INTKEY table). + */ + if( pOp->p4.pKeyInfo ){ + int pgno; + assert( pOp->p4type==P4_KEYINFO ); + rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5); + if( rc==SQLITE_OK ){ + assert( pgno==MASTER_ROOT+1 ); + rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1, + (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor); + u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo; + u.az.pCx->pKeyInfo->enc = ENC(p->db); + } + u.az.pCx->isTable = 0; + }else{ + rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor); + u.az.pCx->isTable = 1; + } + } + u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); + u.az.pCx->isIndex = !u.az.pCx->isTable; + break; +} + +/* Opcode: SorterOpen P1 P2 * P4 * +** +** This opcode works like OP_OpenEphemeral except that it opens +** a transient index that is specifically designed to sort large +** tables using an external merge-sort algorithm. +*/ +case OP_SorterOpen: { +#if 0 /* local variables moved into u.ba */ + VdbeCursor *pCx; +#endif /* local variables moved into u.ba */ + + u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1); + if( u.ba.pCx==0 ) goto no_mem; + u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo; + u.ba.pCx->pKeyInfo->enc = ENC(p->db); + u.ba.pCx->isSorter = 1; + rc = sqlite3VdbeSorterInit(db, u.ba.pCx); + break; +} + +/* Opcode: OpenPseudo P1 P2 P3 * P5 +** +** Open a new cursor that points to a fake table that contains a single +** row of data. The content of that one row in the content of memory +** register P2 when P5==0. In other words, cursor P1 becomes an alias for the +** MEM_Blob content contained in register P2. When P5==1, then the +** row is represented by P3 consecutive registers beginning with P2. +** +** A pseudo-table created by this opcode is used to hold a single +** row output from the sorter so that the row can be decomposed into +** individual columns using the OP_Column opcode. The OP_Column opcode +** is the only cursor opcode that works with a pseudo-table. +** +** P3 is the number of fields in the records that will be stored by +** the pseudo-table. +*/ +case OP_OpenPseudo: { +#if 0 /* local variables moved into u.bb */ + VdbeCursor *pCx; +#endif /* local variables moved into u.bb */ + + assert( pOp->p1>=0 ); + u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0); + if( u.bb.pCx==0 ) goto no_mem; + u.bb.pCx->nullRow = 1; + u.bb.pCx->pseudoTableReg = pOp->p2; + u.bb.pCx->isTable = 1; + u.bb.pCx->isIndex = 0; + u.bb.pCx->multiPseudo = pOp->p5; + break; +} + +/* Opcode: Close P1 * * * * +** +** Close a cursor previously opened as P1. If P1 is not +** currently open, this instruction is a no-op. +*/ +case OP_Close: { + assert( pOp->p1>=0 && pOp->p1nCursor ); + sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); + p->apCsr[pOp->p1] = 0; + break; +} + +/* Opcode: SeekGe P1 P2 P3 P4 * +** +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), +** use the value in register P3 as the key. If cursor P1 refers +** to an SQL index, then P3 is the first in an array of P4 registers +** that are used as an unpacked index key. +** +** Reposition cursor P1 so that it points to the smallest entry that +** is greater than or equal to the key value. If there are no records +** greater than or equal to the key and P2 is not zero, then jump to P2. +** +** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe +*/ +/* Opcode: SeekGt P1 P2 P3 P4 * +** +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), +** use the value in register P3 as a key. If cursor P1 refers +** to an SQL index, then P3 is the first in an array of P4 registers +** that are used as an unpacked index key. +** +** Reposition cursor P1 so that it points to the smallest entry that +** is greater than the key value. If there are no records greater than +** the key and P2 is not zero, then jump to P2. +** +** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe +*/ +/* Opcode: SeekLt P1 P2 P3 P4 * +** +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), +** use the value in register P3 as a key. If cursor P1 refers +** to an SQL index, then P3 is the first in an array of P4 registers +** that are used as an unpacked index key. +** +** Reposition cursor P1 so that it points to the largest entry that +** is less than the key value. If there are no records less than +** the key and P2 is not zero, then jump to P2. +** +** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe +*/ +/* Opcode: SeekLe P1 P2 P3 P4 * +** +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), +** use the value in register P3 as a key. If cursor P1 refers +** to an SQL index, then P3 is the first in an array of P4 registers +** that are used as an unpacked index key. +** +** Reposition cursor P1 so that it points to the largest entry that +** is less than or equal to the key value. If there are no records +** less than or equal to the key and P2 is not zero, then jump to P2. +** +** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt +*/ +case OP_SeekLt: /* jump, in3 */ +case OP_SeekLe: /* jump, in3 */ +case OP_SeekGe: /* jump, in3 */ +case OP_SeekGt: { /* jump, in3 */ +#if 0 /* local variables moved into u.bc */ + int res; + int oc; + VdbeCursor *pC; + UnpackedRecord r; + int nField; + i64 iKey; /* The rowid we are to seek to */ +#endif /* local variables moved into u.bc */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( pOp->p2!=0 ); + u.bc.pC = p->apCsr[pOp->p1]; + assert( u.bc.pC!=0 ); + assert( u.bc.pC->pseudoTableReg==0 ); + assert( OP_SeekLe == OP_SeekLt+1 ); + assert( OP_SeekGe == OP_SeekLt+2 ); + assert( OP_SeekGt == OP_SeekLt+3 ); + assert( u.bc.pC->isOrdered ); + if( ALWAYS(u.bc.pC->pCursor!=0) ){ + u.bc.oc = pOp->opcode; + u.bc.pC->nullRow = 0; + if( u.bc.pC->isTable ){ + /* The input value in P3 might be of any type: integer, real, string, + ** blob, or NULL. But it needs to be an integer before we can do + ** the seek, so covert it. */ + pIn3 = &aMem[pOp->p3]; + applyNumericAffinity(pIn3); + u.bc.iKey = sqlite3VdbeIntValue(pIn3); + u.bc.pC->rowidIsValid = 0; + + /* If the P3 value could not be converted into an integer without + ** loss of information, then special processing is required... */ + if( (pIn3->flags & MEM_Int)==0 ){ + if( (pIn3->flags & MEM_Real)==0 ){ + /* If the P3 value cannot be converted into any kind of a number, + ** then the seek is not possible, so jump to P2 */ + pc = pOp->p2 - 1; + break; + } + /* If we reach this point, then the P3 value must be a floating + ** point number. */ + assert( (pIn3->flags & MEM_Real)!=0 ); + + if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){ + /* The P3 value is too large in magnitude to be expressed as an + ** integer. */ + u.bc.res = 1; + if( pIn3->r<0 ){ + if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt ); + rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + } + }else{ + if( u.bc.oc<=OP_SeekLe ){ assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe ); + rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + } + } + if( u.bc.res ){ + pc = pOp->p2 - 1; + } + break; + }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){ + /* Use the ceiling() function to convert real->int */ + if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++; + }else{ + /* Use the floor() function to convert real->int */ + assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt ); + if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--; + } + } + rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + if( u.bc.res==0 ){ + u.bc.pC->rowidIsValid = 1; + u.bc.pC->lastRowid = u.bc.iKey; + } + }else{ + u.bc.nField = pOp->p4.i; + assert( pOp->p4type==P4_INT32 ); + assert( u.bc.nField>0 ); + u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo; + u.bc.r.nField = (u16)u.bc.nField; + + /* The next line of code computes as follows, only faster: + ** if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){ + ** u.bc.r.flags = UNPACKED_INCRKEY; + ** }else{ + ** u.bc.r.flags = 0; + ** } + */ + u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt))); + assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY ); + assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY ); + assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 ); + assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 ); + + u.bc.r.aMem = &aMem[pOp->p3]; +#ifdef SQLITE_DEBUG + { int i; for(i=0; ipCursor, &u.bc.r, 0, 0, &u.bc.res); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + u.bc.pC->rowidIsValid = 0; + } + u.bc.pC->deferredMoveto = 0; + u.bc.pC->cacheStatus = CACHE_STALE; +#ifdef SQLITE_TEST + sqlite3_search_count++; +#endif + if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt ); + if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){ + rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + u.bc.pC->rowidIsValid = 0; + }else{ + u.bc.res = 0; + } + }else{ + assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe ); + if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){ + rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + u.bc.pC->rowidIsValid = 0; + }else{ + /* u.bc.res might be negative because the table is empty. Check to + ** see if this is the case. + */ + u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor); + } + } + assert( pOp->p2>0 ); + if( u.bc.res ){ + pc = pOp->p2 - 1; + } + }else{ + /* This happens when attempting to open the sqlite3_master table + ** for read access returns SQLITE_EMPTY. In this case always + ** take the jump (since there are no records in the table). + */ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: Seek P1 P2 * * * +** +** P1 is an open table cursor and P2 is a rowid integer. Arrange +** for P1 to move so that it points to the rowid given by P2. +** +** This is actually a deferred seek. Nothing actually happens until +** the cursor is used to read a record. That way, if no reads +** occur, no unnecessary I/O happens. +*/ +case OP_Seek: { /* in2 */ +#if 0 /* local variables moved into u.bd */ + VdbeCursor *pC; +#endif /* local variables moved into u.bd */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bd.pC = p->apCsr[pOp->p1]; + assert( u.bd.pC!=0 ); + if( ALWAYS(u.bd.pC->pCursor!=0) ){ + assert( u.bd.pC->isTable ); + u.bd.pC->nullRow = 0; + pIn2 = &aMem[pOp->p2]; + u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2); + u.bd.pC->rowidIsValid = 0; + u.bd.pC->deferredMoveto = 1; + } + break; +} + + +/* Opcode: Found P1 P2 P3 P4 * +** +** If P4==0 then register P3 holds a blob constructed by MakeRecord. If +** P4>0 then register P3 is the first of P4 registers that form an unpacked +** record. +** +** Cursor P1 is on an index btree. If the record identified by P3 and P4 +** is a prefix of any entry in P1 then a jump is made to P2 and +** P1 is left pointing at the matching entry. +*/ +/* Opcode: NotFound P1 P2 P3 P4 * +** +** If P4==0 then register P3 holds a blob constructed by MakeRecord. If +** P4>0 then register P3 is the first of P4 registers that form an unpacked +** record. +** +** Cursor P1 is on an index btree. If the record identified by P3 and P4 +** is not the prefix of any entry in P1 then a jump is made to P2. If P1 +** does contain an entry whose prefix matches the P3/P4 record then control +** falls through to the next instruction and P1 is left pointing at the +** matching entry. +** +** See also: Found, NotExists, IsUnique +*/ +case OP_NotFound: /* jump, in3 */ +case OP_Found: { /* jump, in3 */ +#if 0 /* local variables moved into u.be */ + int alreadyExists; + VdbeCursor *pC; + int res; + char *pFree; + UnpackedRecord *pIdxKey; + UnpackedRecord r; + char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7]; +#endif /* local variables moved into u.be */ + +#ifdef SQLITE_TEST + sqlite3_found_count++; +#endif + + u.be.alreadyExists = 0; + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( pOp->p4type==P4_INT32 ); + u.be.pC = p->apCsr[pOp->p1]; + assert( u.be.pC!=0 ); + pIn3 = &aMem[pOp->p3]; + if( ALWAYS(u.be.pC->pCursor!=0) ){ + + assert( u.be.pC->isTable==0 ); + if( pOp->p4.i>0 ){ + u.be.r.pKeyInfo = u.be.pC->pKeyInfo; + u.be.r.nField = (u16)pOp->p4.i; + u.be.r.aMem = pIn3; +#ifdef SQLITE_DEBUG + { int i; for(i=0; ipKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree + ); + if( u.be.pIdxKey==0 ) goto no_mem; + assert( pIn3->flags & MEM_Blob ); + assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */ + sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey); + u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH; + } + rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res); + if( pOp->p4.i==0 ){ + sqlite3DbFree(db, u.be.pFree); + } + if( rc!=SQLITE_OK ){ + break; + } + u.be.alreadyExists = (u.be.res==0); + u.be.pC->deferredMoveto = 0; + u.be.pC->cacheStatus = CACHE_STALE; + } + if( pOp->opcode==OP_Found ){ + if( u.be.alreadyExists ) pc = pOp->p2 - 1; + }else{ + if( !u.be.alreadyExists ) pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: IsUnique P1 P2 P3 P4 * +** +** Cursor P1 is open on an index b-tree - that is to say, a btree which +** no data and where the key are records generated by OP_MakeRecord with +** the list field being the integer ROWID of the entry that the index +** entry refers to. +** +** The P3 register contains an integer record number. Call this record +** number R. Register P4 is the first in a set of N contiguous registers +** that make up an unpacked index key that can be used with cursor P1. +** The value of N can be inferred from the cursor. N includes the rowid +** value appended to the end of the index record. This rowid value may +** or may not be the same as R. +** +** If any of the N registers beginning with register P4 contains a NULL +** value, jump immediately to P2. +** +** Otherwise, this instruction checks if cursor P1 contains an entry +** where the first (N-1) fields match but the rowid value at the end +** of the index entry is not R. If there is no such entry, control jumps +** to instruction P2. Otherwise, the rowid of the conflicting index +** entry is copied to register P3 and control falls through to the next +** instruction. +** +** See also: NotFound, NotExists, Found +*/ +case OP_IsUnique: { /* jump, in3 */ +#if 0 /* local variables moved into u.bf */ + u16 ii; + VdbeCursor *pCx; + BtCursor *pCrsr; + u16 nField; + Mem *aMx; + UnpackedRecord r; /* B-Tree index search key */ + i64 R; /* Rowid stored in register P3 */ +#endif /* local variables moved into u.bf */ + + pIn3 = &aMem[pOp->p3]; + u.bf.aMx = &aMem[pOp->p4.i]; + /* Assert that the values of parameters P1 and P4 are in range. */ + assert( pOp->p4type==P4_INT32 ); + assert( pOp->p4.i>0 && pOp->p4.i<=(p->nMem-p->nCursor) ); + assert( pOp->p1>=0 && pOp->p1nCursor ); + + /* Find the index cursor. */ + u.bf.pCx = p->apCsr[pOp->p1]; + assert( u.bf.pCx->deferredMoveto==0 ); + u.bf.pCx->seekResult = 0; + u.bf.pCx->cacheStatus = CACHE_STALE; + u.bf.pCrsr = u.bf.pCx->pCursor; + + /* If any of the values are NULL, take the jump. */ + u.bf.nField = u.bf.pCx->pKeyInfo->nField; + for(u.bf.ii=0; u.bf.iip2 - 1; + u.bf.pCrsr = 0; + break; + } + } + assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 ); + + if( u.bf.pCrsr!=0 ){ + /* Populate the index search key. */ + u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo; + u.bf.r.nField = u.bf.nField + 1; + u.bf.r.flags = UNPACKED_PREFIX_SEARCH; + u.bf.r.aMem = u.bf.aMx; +#ifdef SQLITE_DEBUG + { int i; for(i=0; iu.i; + + /* Search the B-Tree index. If no conflicting record is found, jump + ** to P2. Otherwise, copy the rowid of the conflicting record to + ** register P3 and fall through to the next instruction. */ + rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult); + if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){ + pc = pOp->p2 - 1; + }else{ + pIn3->u.i = u.bf.r.rowid; + } + } + break; +} + +/* Opcode: NotExists P1 P2 P3 * * +** +** Use the content of register P3 as an integer key. If a record +** with that key does not exist in table of P1, then jump to P2. +** If the record does exist, then fall through. The cursor is left +** pointing to the record if it exists. +** +** The difference between this operation and NotFound is that this +** operation assumes the key is an integer and that P1 is a table whereas +** NotFound assumes key is a blob constructed from MakeRecord and +** P1 is an index. +** +** See also: Found, NotFound, IsUnique +*/ +case OP_NotExists: { /* jump, in3 */ +#if 0 /* local variables moved into u.bg */ + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + u64 iKey; +#endif /* local variables moved into u.bg */ + + pIn3 = &aMem[pOp->p3]; + assert( pIn3->flags & MEM_Int ); + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bg.pC = p->apCsr[pOp->p1]; + assert( u.bg.pC!=0 ); + assert( u.bg.pC->isTable ); + assert( u.bg.pC->pseudoTableReg==0 ); + u.bg.pCrsr = u.bg.pC->pCursor; + if( ALWAYS(u.bg.pCrsr!=0) ){ + u.bg.res = 0; + u.bg.iKey = pIn3->u.i; + rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res); + u.bg.pC->lastRowid = pIn3->u.i; + u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0; + u.bg.pC->nullRow = 0; + u.bg.pC->cacheStatus = CACHE_STALE; + u.bg.pC->deferredMoveto = 0; + if( u.bg.res!=0 ){ + pc = pOp->p2 - 1; + assert( u.bg.pC->rowidIsValid==0 ); + } + u.bg.pC->seekResult = u.bg.res; + }else{ + /* This happens when an attempt to open a read cursor on the + ** sqlite_master table returns SQLITE_EMPTY. + */ + pc = pOp->p2 - 1; + assert( u.bg.pC->rowidIsValid==0 ); + u.bg.pC->seekResult = 0; + } + break; +} + +/* Opcode: Sequence P1 P2 * * * +** +** Find the next available sequence number for cursor P1. +** Write the sequence number into register P2. +** The sequence number on the cursor is incremented after this +** instruction. +*/ +case OP_Sequence: { /* out2-prerelease */ + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( p->apCsr[pOp->p1]!=0 ); + pOut->u.i = p->apCsr[pOp->p1]->seqCount++; + break; +} + + +/* Opcode: NewRowid P1 P2 P3 * * +** +** Get a new integer record number (a.k.a "rowid") used as the key to a table. +** The record number is not previously used as a key in the database +** table that cursor P1 points to. The new record number is written +** written to register P2. +** +** If P3>0 then P3 is a register in the root frame of this VDBE that holds +** the largest previously generated record number. No new record numbers are +** allowed to be less than this value. When this value reaches its maximum, +** an SQLITE_FULL error is generated. The P3 register is updated with the ' +** generated record number. This P3 mechanism is used to help implement the +** AUTOINCREMENT feature. +*/ +case OP_NewRowid: { /* out2-prerelease */ +#if 0 /* local variables moved into u.bh */ + i64 v; /* The new rowid */ + VdbeCursor *pC; /* Cursor of table to get the new rowid */ + int res; /* Result of an sqlite3BtreeLast() */ + int cnt; /* Counter to limit the number of searches */ + Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ + VdbeFrame *pFrame; /* Root frame of VDBE */ +#endif /* local variables moved into u.bh */ + + u.bh.v = 0; + u.bh.res = 0; + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bh.pC = p->apCsr[pOp->p1]; + assert( u.bh.pC!=0 ); + if( NEVER(u.bh.pC->pCursor==0) ){ + /* The zero initialization above is all that is needed */ + }else{ + /* The next rowid or record number (different terms for the same + ** thing) is obtained in a two-step algorithm. + ** + ** First we attempt to find the largest existing rowid and add one + ** to that. But if the largest existing rowid is already the maximum + ** positive integer, we have to fall through to the second + ** probabilistic algorithm + ** + ** The second algorithm is to select a rowid at random and see if + ** it already exists in the table. If it does not exist, we have + ** succeeded. If the random rowid does exist, we select a new one + ** and try again, up to 100 times. + */ + assert( u.bh.pC->isTable ); + +#ifdef SQLITE_32BIT_ROWID +# define MAX_ROWID 0x7fffffff +#else + /* Some compilers complain about constants of the form 0x7fffffffffffffff. + ** Others complain about 0x7ffffffffffffffffLL. The following macro seems + ** to provide the constant while making all compilers happy. + */ +# define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff ) +#endif + + if( !u.bh.pC->useRandomRowid ){ + u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor); + if( u.bh.v==0 ){ + rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + if( u.bh.res ){ + u.bh.v = 1; /* IMP: R-61914-48074 */ + }else{ + assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) ); + rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v); + assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */ + if( u.bh.v>=MAX_ROWID ){ + u.bh.pC->useRandomRowid = 1; + }else{ + u.bh.v++; /* IMP: R-29538-34987 */ + } + } + } + +#ifndef SQLITE_OMIT_AUTOINCREMENT + if( pOp->p3 ){ + /* Assert that P3 is a valid memory cell. */ + assert( pOp->p3>0 ); + if( p->pFrame ){ + for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent); + /* Assert that P3 is a valid memory cell. */ + assert( pOp->p3<=u.bh.pFrame->nMem ); + u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3]; + }else{ + /* Assert that P3 is a valid memory cell. */ + assert( pOp->p3<=(p->nMem-p->nCursor) ); + u.bh.pMem = &aMem[pOp->p3]; + memAboutToChange(p, u.bh.pMem); + } + assert( memIsValid(u.bh.pMem) ); + + REGISTER_TRACE(pOp->p3, u.bh.pMem); + sqlite3VdbeMemIntegerify(u.bh.pMem); + assert( (u.bh.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ + if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){ + rc = SQLITE_FULL; /* IMP: R-12275-61338 */ + goto abort_due_to_error; + } + if( u.bh.vu.i+1 ){ + u.bh.v = u.bh.pMem->u.i + 1; + } + u.bh.pMem->u.i = u.bh.v; + } +#endif + + sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.vuseRandomRowid ){ + /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the + ** largest possible integer (9223372036854775807) then the database + ** engine starts picking positive candidate ROWIDs at random until + ** it finds one that is not previously used. */ + assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is + ** an AUTOINCREMENT table. */ + /* on the first attempt, simply do one more than previous */ + u.bh.v = lastRowid; + u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */ + u.bh.v++; /* ensure non-zero */ + u.bh.cnt = 0; + while( ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v, + 0, &u.bh.res))==SQLITE_OK) + && (u.bh.res==0) + && (++u.bh.cnt<100)){ + /* collision - try another random rowid */ + sqlite3_randomness(sizeof(u.bh.v), &u.bh.v); + if( u.bh.cnt<5 ){ + /* try "small" random rowids for the initial attempts */ + u.bh.v &= 0xffffff; + }else{ + u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */ + } + u.bh.v++; /* ensure non-zero */ + } + if( rc==SQLITE_OK && u.bh.res==0 ){ + rc = SQLITE_FULL; /* IMP: R-38219-53002 */ + goto abort_due_to_error; + } + assert( u.bh.v>0 ); /* EV: R-40812-03570 */ + } + u.bh.pC->rowidIsValid = 0; + u.bh.pC->deferredMoveto = 0; + u.bh.pC->cacheStatus = CACHE_STALE; + } + pOut->u.i = u.bh.v; + break; +} + +/* Opcode: Insert P1 P2 P3 P4 P5 +** +** Write an entry into the table of cursor P1. A new entry is +** created if it doesn't already exist or the data for an existing +** entry is overwritten. The data is the value MEM_Blob stored in register +** number P2. The key is stored in register P3. The key must +** be a MEM_Int. +** +** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is +** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, +** then rowid is stored for subsequent return by the +** sqlite3_last_insert_rowid() function (otherwise it is unmodified). +** +** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of +** the last seek operation (OP_NotExists) was a success, then this +** operation will not attempt to find the appropriate row before doing +** the insert but will instead overwrite the row that the cursor is +** currently pointing to. Presumably, the prior OP_NotExists opcode +** has already positioned the cursor correctly. This is an optimization +** that boosts performance by avoiding redundant seeks. +** +** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an +** UPDATE operation. Otherwise (if the flag is clear) then this opcode +** is part of an INSERT operation. The difference is only important to +** the update hook. +** +** Parameter P4 may point to a string containing the table-name, or +** may be NULL. If it is not NULL, then the update-hook +** (sqlite3.xUpdateCallback) is invoked following a successful insert. +** +** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically +** allocated, then ownership of P2 is transferred to the pseudo-cursor +** and register P2 becomes ephemeral. If the cursor is changed, the +** value of register P2 will then change. Make sure this does not +** cause any problems.) +** +** This instruction only works on tables. The equivalent instruction +** for indices is OP_IdxInsert. +*/ +/* Opcode: InsertInt P1 P2 P3 P4 P5 +** +** This works exactly like OP_Insert except that the key is the +** integer value P3, not the value of the integer stored in register P3. +*/ +case OP_Insert: +case OP_InsertInt: { +#if 0 /* local variables moved into u.bi */ + Mem *pData; /* MEM cell holding data for the record to be inserted */ + Mem *pKey; /* MEM cell holding key for the record */ + i64 iKey; /* The integer ROWID or key for the record to be inserted */ + VdbeCursor *pC; /* Cursor to table into which insert is written */ + int nZero; /* Number of zero-bytes to append */ + int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ + const char *zDb; /* database name - used by the update hook */ + const char *zTbl; /* Table name - used by the opdate hook */ + int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */ +#endif /* local variables moved into u.bi */ + + u.bi.pData = &aMem[pOp->p2]; + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( memIsValid(u.bi.pData) ); + u.bi.pC = p->apCsr[pOp->p1]; + assert( u.bi.pC!=0 ); + assert( u.bi.pC->pCursor!=0 ); + assert( u.bi.pC->pseudoTableReg==0 ); + assert( u.bi.pC->isTable ); + REGISTER_TRACE(pOp->p2, u.bi.pData); + + if( pOp->opcode==OP_Insert ){ + u.bi.pKey = &aMem[pOp->p3]; + assert( u.bi.pKey->flags & MEM_Int ); + assert( memIsValid(u.bi.pKey) ); + REGISTER_TRACE(pOp->p3, u.bi.pKey); + u.bi.iKey = u.bi.pKey->u.i; + }else{ + assert( pOp->opcode==OP_InsertInt ); + u.bi.iKey = pOp->p3; + } + + if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; + if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey; + if( u.bi.pData->flags & MEM_Null ){ + u.bi.pData->z = 0; + u.bi.pData->n = 0; + }else{ + assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) ); + } + u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0); + if( u.bi.pData->flags & MEM_Zero ){ + u.bi.nZero = u.bi.pData->u.nZero; + }else{ + u.bi.nZero = 0; + } + sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0); + rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey, + u.bi.pData->z, u.bi.pData->n, u.bi.nZero, + pOp->p5 & OPFLAG_APPEND, u.bi.seekResult + ); + u.bi.pC->rowidIsValid = 0; + u.bi.pC->deferredMoveto = 0; + u.bi.pC->cacheStatus = CACHE_STALE; + + /* Invoke the update-hook if required. */ + if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){ + u.bi.zDb = db->aDb[u.bi.pC->iDb].zName; + u.bi.zTbl = pOp->p4.z; + u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT); + assert( u.bi.pC->isTable ); + db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey); + assert( u.bi.pC->iDb>=0 ); + } + break; +} + +/* Opcode: Delete P1 P2 * P4 * +** +** Delete the record at which the P1 cursor is currently pointing. +** +** The cursor will be left pointing at either the next or the previous +** record in the table. If it is left pointing at the next record, then +** the next Next instruction will be a no-op. Hence it is OK to delete +** a record from within an Next loop. +** +** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is +** incremented (otherwise not). +** +** P1 must not be pseudo-table. It has to be a real table with +** multiple rows. +** +** If P4 is not NULL, then it is the name of the table that P1 is +** pointing to. The update hook will be invoked, if it exists. +** If P4 is not NULL then the P1 cursor must have been positioned +** using OP_NotFound prior to invoking this opcode. +*/ +case OP_Delete: { +#if 0 /* local variables moved into u.bj */ + i64 iKey; + VdbeCursor *pC; +#endif /* local variables moved into u.bj */ + + u.bj.iKey = 0; + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bj.pC = p->apCsr[pOp->p1]; + assert( u.bj.pC!=0 ); + assert( u.bj.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */ + + /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the + ** row being deleted. + */ + if( db->xUpdateCallback && pOp->p4.z ){ + assert( u.bj.pC->isTable ); + assert( u.bj.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */ + u.bj.iKey = u.bj.pC->lastRowid; + } + + /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or + ** OP_Column on the same table without any intervening operations that + ** might move or invalidate the cursor. Hence cursor u.bj.pC is always pointing + ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation + ** below is always a no-op and cannot fail. We will run it anyhow, though, + ** to guard against future changes to the code generator. + **/ + assert( u.bj.pC->deferredMoveto==0 ); + rc = sqlite3VdbeCursorMoveto(u.bj.pC); + if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; + + sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0); + rc = sqlite3BtreeDelete(u.bj.pC->pCursor); + u.bj.pC->cacheStatus = CACHE_STALE; + + /* Invoke the update-hook if required. */ + if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){ + const char *zDb = db->aDb[u.bj.pC->iDb].zName; + const char *zTbl = pOp->p4.z; + db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey); + assert( u.bj.pC->iDb>=0 ); + } + if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++; + break; +} +/* Opcode: ResetCount * * * * * +** +** The value of the change counter is copied to the database handle +** change counter (returned by subsequent calls to sqlite3_changes()). +** Then the VMs internal change counter resets to 0. +** This is used by trigger programs. +*/ +case OP_ResetCount: { + sqlite3VdbeSetChanges(db, p->nChange); + p->nChange = 0; + break; +} + +/* Opcode: SorterCompare P1 P2 P3 +** +** P1 is a sorter cursor. This instruction compares the record blob in +** register P3 with the entry that the sorter cursor currently points to. +** If, excluding the rowid fields at the end, the two records are a match, +** fall through to the next instruction. Otherwise, jump to instruction P2. +*/ +case OP_SorterCompare: { +#if 0 /* local variables moved into u.bk */ + VdbeCursor *pC; + int res; +#endif /* local variables moved into u.bk */ + + u.bk.pC = p->apCsr[pOp->p1]; + assert( isSorter(u.bk.pC) ); + pIn3 = &aMem[pOp->p3]; + rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res); + if( u.bk.res ){ + pc = pOp->p2-1; + } + break; +}; + +/* Opcode: SorterData P1 P2 * * * +** +** Write into register P2 the current sorter data for sorter cursor P1. +*/ +case OP_SorterData: { +#if 0 /* local variables moved into u.bl */ + VdbeCursor *pC; +#endif /* local variables moved into u.bl */ + + pOut = &aMem[pOp->p2]; + u.bl.pC = p->apCsr[pOp->p1]; + assert( u.bl.pC->isSorter ); + rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut); + break; +} + +/* Opcode: RowData P1 P2 * * * +** +** Write into register P2 the complete row data for cursor P1. +** There is no interpretation of the data. +** It is just copied onto the P2 register exactly as +** it is found in the database file. +** +** If the P1 cursor must be pointing to a valid row (not a NULL row) +** of a real table, not a pseudo-table. +*/ +/* Opcode: RowKey P1 P2 * * * +** +** Write into register P2 the complete row key for cursor P1. +** There is no interpretation of the data. +** The key is copied onto the P3 register exactly as +** it is found in the database file. +** +** If the P1 cursor must be pointing to a valid row (not a NULL row) +** of a real table, not a pseudo-table. +*/ +case OP_RowKey: +case OP_RowData: { +#if 0 /* local variables moved into u.bm */ + VdbeCursor *pC; + BtCursor *pCrsr; + u32 n; + i64 n64; +#endif /* local variables moved into u.bm */ + + pOut = &aMem[pOp->p2]; + memAboutToChange(p, pOut); + + /* Note that RowKey and RowData are really exactly the same instruction */ + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bm.pC = p->apCsr[pOp->p1]; + assert( u.bm.pC->isSorter==0 ); + assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData ); + assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData ); + assert( u.bm.pC!=0 ); + assert( u.bm.pC->nullRow==0 ); + assert( u.bm.pC->pseudoTableReg==0 ); + assert( u.bm.pC->pCursor!=0 ); + u.bm.pCrsr = u.bm.pC->pCursor; + assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) ); + + /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or + ** OP_Rewind/Op_Next with no intervening instructions that might invalidate + ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always + ** a no-op and can never fail. But we leave it in place as a safety. + */ + assert( u.bm.pC->deferredMoveto==0 ); + rc = sqlite3VdbeCursorMoveto(u.bm.pC); + if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; + + if( u.bm.pC->isIndex ){ + assert( !u.bm.pC->isTable ); + VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64); + assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */ + if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + u.bm.n = (u32)u.bm.n64; + }else{ + VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n); + assert( rc==SQLITE_OK ); /* DataSize() cannot fail */ + if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + } + if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){ + goto no_mem; + } + pOut->n = u.bm.n; + MemSetTypeFlag(pOut, MEM_Blob); + if( u.bm.pC->isIndex ){ + rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z); + }else{ + rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z); + } + pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */ + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Rowid P1 P2 * * * +** +** Store in register P2 an integer which is the key of the table entry that +** P1 is currently point to. +** +** P1 can be either an ordinary table or a virtual table. There used to +** be a separate OP_VRowid opcode for use with virtual tables, but this +** one opcode now works for both table types. +*/ +case OP_Rowid: { /* out2-prerelease */ +#if 0 /* local variables moved into u.bn */ + VdbeCursor *pC; + i64 v; + sqlite3_vtab *pVtab; + const sqlite3_module *pModule; +#endif /* local variables moved into u.bn */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bn.pC = p->apCsr[pOp->p1]; + assert( u.bn.pC!=0 ); + assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow ); + if( u.bn.pC->nullRow ){ + pOut->flags = MEM_Null; + break; + }else if( u.bn.pC->deferredMoveto ){ + u.bn.v = u.bn.pC->movetoTarget; +#ifndef SQLITE_OMIT_VIRTUALTABLE + }else if( u.bn.pC->pVtabCursor ){ + u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab; + u.bn.pModule = u.bn.pVtab->pModule; + assert( u.bn.pModule->xRowid ); + rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v); + sqlite3VtabImportErrmsg(p, u.bn.pVtab); +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + }else{ + assert( u.bn.pC->pCursor!=0 ); + rc = sqlite3VdbeCursorMoveto(u.bn.pC); + if( rc ) goto abort_due_to_error; + if( u.bn.pC->rowidIsValid ){ + u.bn.v = u.bn.pC->lastRowid; + }else{ + rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v); + assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */ + } + } + pOut->u.i = u.bn.v; + break; +} + +/* Opcode: NullRow P1 * * * * +** +** Move the cursor P1 to a null row. Any OP_Column operations +** that occur while the cursor is on the null row will always +** write a NULL. +*/ +case OP_NullRow: { +#if 0 /* local variables moved into u.bo */ + VdbeCursor *pC; +#endif /* local variables moved into u.bo */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bo.pC = p->apCsr[pOp->p1]; + assert( u.bo.pC!=0 ); + u.bo.pC->nullRow = 1; + u.bo.pC->rowidIsValid = 0; + assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor ); + if( u.bo.pC->pCursor ){ + sqlite3BtreeClearCursor(u.bo.pC->pCursor); + } + break; +} + +/* Opcode: Last P1 P2 * * * +** +** The next use of the Rowid or Column or Next instruction for P1 +** will refer to the last entry in the database table or index. +** If the table or index is empty and P2>0, then jump immediately to P2. +** If P2 is 0 or if the table or index is not empty, fall through +** to the following instruction. +*/ +case OP_Last: { /* jump */ +#if 0 /* local variables moved into u.bp */ + VdbeCursor *pC; + BtCursor *pCrsr; + int res; +#endif /* local variables moved into u.bp */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bp.pC = p->apCsr[pOp->p1]; + assert( u.bp.pC!=0 ); + u.bp.pCrsr = u.bp.pC->pCursor; + u.bp.res = 0; + if( ALWAYS(u.bp.pCrsr!=0) ){ + rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res); + } + u.bp.pC->nullRow = (u8)u.bp.res; + u.bp.pC->deferredMoveto = 0; + u.bp.pC->rowidIsValid = 0; + u.bp.pC->cacheStatus = CACHE_STALE; + if( pOp->p2>0 && u.bp.res ){ + pc = pOp->p2 - 1; + } + break; +} + + +/* Opcode: Sort P1 P2 * * * +** +** This opcode does exactly the same thing as OP_Rewind except that +** it increments an undocumented global variable used for testing. +** +** Sorting is accomplished by writing records into a sorting index, +** then rewinding that index and playing it back from beginning to +** end. We use the OP_Sort opcode instead of OP_Rewind to do the +** rewinding so that the global variable will be incremented and +** regression tests can determine whether or not the optimizer is +** correctly optimizing out sorts. +*/ +case OP_SorterSort: /* jump */ +case OP_Sort: { /* jump */ +#ifdef SQLITE_TEST + sqlite3_sort_count++; + sqlite3_search_count--; +#endif + p->aCounter[SQLITE_STMTSTATUS_SORT]++; + /* Fall through into OP_Rewind */ +} +/* Opcode: Rewind P1 P2 * * * +** +** The next use of the Rowid or Column or Next instruction for P1 +** will refer to the first entry in the database table or index. +** If the table or index is empty and P2>0, then jump immediately to P2. +** If P2 is 0 or if the table or index is not empty, fall through +** to the following instruction. +*/ +case OP_Rewind: { /* jump */ +#if 0 /* local variables moved into u.bq */ + VdbeCursor *pC; + BtCursor *pCrsr; + int res; +#endif /* local variables moved into u.bq */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bq.pC = p->apCsr[pOp->p1]; + assert( u.bq.pC!=0 ); + assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) ); + u.bq.res = 1; + if( isSorter(u.bq.pC) ){ + rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res); + }else{ + u.bq.pCrsr = u.bq.pC->pCursor; + assert( u.bq.pCrsr ); + rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res); + u.bq.pC->atFirst = u.bq.res==0 ?1:0; + u.bq.pC->deferredMoveto = 0; + u.bq.pC->cacheStatus = CACHE_STALE; + u.bq.pC->rowidIsValid = 0; + } + u.bq.pC->nullRow = (u8)u.bq.res; + assert( pOp->p2>0 && pOp->p2nOp ); + if( u.bq.res ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: Next P1 P2 * P4 P5 +** +** Advance cursor P1 so that it points to the next key/data pair in its +** table or index. If there are no more key/value pairs then fall through +** to the following instruction. But if the cursor advance was successful, +** jump immediately to P2. +** +** The P1 cursor must be for a real table, not a pseudo-table. +** +** P4 is always of type P4_ADVANCE. The function pointer points to +** sqlite3BtreeNext(). +** +** If P5 is positive and the jump is taken, then event counter +** number P5-1 in the prepared statement is incremented. +** +** See also: Prev +*/ +/* Opcode: Prev P1 P2 * * P5 +** +** Back up cursor P1 so that it points to the previous key/data pair in its +** table or index. If there is no previous key/value pairs then fall through +** to the following instruction. But if the cursor backup was successful, +** jump immediately to P2. +** +** The P1 cursor must be for a real table, not a pseudo-table. +** +** P4 is always of type P4_ADVANCE. The function pointer points to +** sqlite3BtreePrevious(). +** +** If P5 is positive and the jump is taken, then event counter +** number P5-1 in the prepared statement is incremented. +*/ +case OP_SorterNext: /* jump */ +case OP_Prev: /* jump */ +case OP_Next: { /* jump */ +#if 0 /* local variables moved into u.br */ + VdbeCursor *pC; + int res; +#endif /* local variables moved into u.br */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( pOp->p5aCounter) ); + u.br.pC = p->apCsr[pOp->p1]; + if( u.br.pC==0 ){ + break; /* See ticket #2273 */ + } + assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) ); + if( isSorter(u.br.pC) ){ + assert( pOp->opcode==OP_SorterNext ); + rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res); + }else{ + /* u.br.res = 1; // Always initialized by the xAdvance() call */ + assert( u.br.pC->deferredMoveto==0 ); + assert( u.br.pC->pCursor ); + assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext ); + assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious ); + rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res); + } + u.br.pC->nullRow = (u8)u.br.res; + u.br.pC->cacheStatus = CACHE_STALE; + if( u.br.res==0 ){ + pc = pOp->p2 - 1; + p->aCounter[pOp->p5]++; +#ifdef SQLITE_TEST + sqlite3_search_count++; +#endif + } + u.br.pC->rowidIsValid = 0; + goto check_for_interrupt; +} + +/* Opcode: IdxInsert P1 P2 P3 * P5 +** +** Register P2 holds an SQL index key made using the +** MakeRecord instructions. This opcode writes that key +** into the index P1. Data for the entry is nil. +** +** P3 is a flag that provides a hint to the b-tree layer that this +** insert is likely to be an append. +** +** This instruction only works for indices. The equivalent instruction +** for tables is OP_Insert. +*/ +case OP_SorterInsert: /* in2 */ +case OP_IdxInsert: { /* in2 */ +#if 0 /* local variables moved into u.bs */ + VdbeCursor *pC; + BtCursor *pCrsr; + int nKey; + const char *zKey; +#endif /* local variables moved into u.bs */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bs.pC = p->apCsr[pOp->p1]; + assert( u.bs.pC!=0 ); + assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) ); + pIn2 = &aMem[pOp->p2]; + assert( pIn2->flags & MEM_Blob ); + u.bs.pCrsr = u.bs.pC->pCursor; + if( ALWAYS(u.bs.pCrsr!=0) ){ + assert( u.bs.pC->isTable==0 ); + rc = ExpandBlob(pIn2); + if( rc==SQLITE_OK ){ + if( isSorter(u.bs.pC) ){ + rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2); + }else{ + u.bs.nKey = pIn2->n; + u.bs.zKey = pIn2->z; + rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3, + ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0) + ); + assert( u.bs.pC->deferredMoveto==0 ); + u.bs.pC->cacheStatus = CACHE_STALE; + } + } + } + break; +} + +/* Opcode: IdxDelete P1 P2 P3 * * +** +** The content of P3 registers starting at register P2 form +** an unpacked index key. This opcode removes that entry from the +** index opened by cursor P1. +*/ +case OP_IdxDelete: { +#if 0 /* local variables moved into u.bt */ + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + UnpackedRecord r; +#endif /* local variables moved into u.bt */ + + assert( pOp->p3>0 ); + assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 ); + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bt.pC = p->apCsr[pOp->p1]; + assert( u.bt.pC!=0 ); + u.bt.pCrsr = u.bt.pC->pCursor; + if( ALWAYS(u.bt.pCrsr!=0) ){ + u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo; + u.bt.r.nField = (u16)pOp->p3; + u.bt.r.flags = 0; + u.bt.r.aMem = &aMem[pOp->p2]; +#ifdef SQLITE_DEBUG + { int i; for(i=0; ideferredMoveto==0 ); + u.bt.pC->cacheStatus = CACHE_STALE; + } + break; +} + +/* Opcode: IdxRowid P1 P2 * * * +** +** Write into register P2 an integer which is the last entry in the record at +** the end of the index key pointed to by cursor P1. This integer should be +** the rowid of the table entry to which this index entry points. +** +** See also: Rowid, MakeRecord. +*/ +case OP_IdxRowid: { /* out2-prerelease */ +#if 0 /* local variables moved into u.bu */ + BtCursor *pCrsr; + VdbeCursor *pC; + i64 rowid; +#endif /* local variables moved into u.bu */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bu.pC = p->apCsr[pOp->p1]; + assert( u.bu.pC!=0 ); + u.bu.pCrsr = u.bu.pC->pCursor; + pOut->flags = MEM_Null; + if( ALWAYS(u.bu.pCrsr!=0) ){ + rc = sqlite3VdbeCursorMoveto(u.bu.pC); + if( NEVER(rc) ) goto abort_due_to_error; + assert( u.bu.pC->deferredMoveto==0 ); + assert( u.bu.pC->isTable==0 ); + if( !u.bu.pC->nullRow ){ + rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + pOut->u.i = u.bu.rowid; + pOut->flags = MEM_Int; + } + } + break; +} + +/* Opcode: IdxGE P1 P2 P3 P4 P5 +** +** The P4 register values beginning with P3 form an unpacked index +** key that omits the ROWID. Compare this key value against the index +** that P1 is currently pointing to, ignoring the ROWID on the P1 index. +** +** If the P1 index entry is greater than or equal to the key value +** then jump to P2. Otherwise fall through to the next instruction. +** +** If P5 is non-zero then the key value is increased by an epsilon +** prior to the comparison. This make the opcode work like IdxGT except +** that if the key from register P3 is a prefix of the key in the cursor, +** the result is false whereas it would be true with IdxGT. +*/ +/* Opcode: IdxLT P1 P2 P3 P4 P5 +** +** The P4 register values beginning with P3 form an unpacked index +** key that omits the ROWID. Compare this key value against the index +** that P1 is currently pointing to, ignoring the ROWID on the P1 index. +** +** If the P1 index entry is less than the key value then jump to P2. +** Otherwise fall through to the next instruction. +** +** If P5 is non-zero then the key value is increased by an epsilon prior +** to the comparison. This makes the opcode work like IdxLE. +*/ +case OP_IdxLT: /* jump */ +case OP_IdxGE: { /* jump */ +#if 0 /* local variables moved into u.bv */ + VdbeCursor *pC; + int res; + UnpackedRecord r; +#endif /* local variables moved into u.bv */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + u.bv.pC = p->apCsr[pOp->p1]; + assert( u.bv.pC!=0 ); + assert( u.bv.pC->isOrdered ); + if( ALWAYS(u.bv.pC->pCursor!=0) ){ + assert( u.bv.pC->deferredMoveto==0 ); + assert( pOp->p5==0 || pOp->p5==1 ); + assert( pOp->p4type==P4_INT32 ); + u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo; + u.bv.r.nField = (u16)pOp->p4.i; + if( pOp->p5 ){ + u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH; + }else{ + u.bv.r.flags = UNPACKED_PREFIX_MATCH; + } + u.bv.r.aMem = &aMem[pOp->p3]; +#ifdef SQLITE_DEBUG + { int i; for(i=0; iopcode==OP_IdxLT ){ + u.bv.res = -u.bv.res; + }else{ + assert( pOp->opcode==OP_IdxGE ); + u.bv.res++; + } + if( u.bv.res>0 ){ + pc = pOp->p2 - 1 ; + } + } + break; +} + +/* Opcode: Destroy P1 P2 P3 * * +** +** Delete an entire database table or index whose root page in the database +** file is given by P1. +** +** The table being destroyed is in the main database file if P3==0. If +** P3==1 then the table to be clear is in the auxiliary database file +** that is used to store tables create using CREATE TEMPORARY TABLE. +** +** If AUTOVACUUM is enabled then it is possible that another root page +** might be moved into the newly deleted root page in order to keep all +** root pages contiguous at the beginning of the database. The former +** value of the root page that moved - its value before the move occurred - +** is stored in register P2. If no page +** movement was required (because the table being dropped was already +** the last one in the database) then a zero is stored in register P2. +** If AUTOVACUUM is disabled then a zero is stored in register P2. +** +** See also: Clear +*/ +case OP_Destroy: { /* out2-prerelease */ +#if 0 /* local variables moved into u.bw */ + int iMoved; + int iCnt; + Vdbe *pVdbe; + int iDb; +#endif /* local variables moved into u.bw */ + + assert( p->readOnly==0 ); +#ifndef SQLITE_OMIT_VIRTUALTABLE + u.bw.iCnt = 0; + for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){ + if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->bIsReader + && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0 + ){ + u.bw.iCnt++; + } + } +#else + u.bw.iCnt = db->nVdbeRead; +#endif + pOut->flags = MEM_Null; + if( u.bw.iCnt>1 ){ + rc = SQLITE_LOCKED; + p->errorAction = OE_Abort; + }else{ + u.bw.iDb = pOp->p3; + assert( u.bw.iCnt==1 ); + assert( (p->btreeMask & (((yDbMask)1)<aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved); + pOut->flags = MEM_Int; + pOut->u.i = u.bw.iMoved; +#ifndef SQLITE_OMIT_AUTOVACUUM + if( rc==SQLITE_OK && u.bw.iMoved!=0 ){ + sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1); + /* All OP_Destroy operations occur on the same btree */ + assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 ); + resetSchemaOnFault = u.bw.iDb+1; + } +#endif + } + break; +} + +/* Opcode: Clear P1 P2 P3 +** +** Delete all contents of the database table or index whose root page +** in the database file is given by P1. But, unlike Destroy, do not +** remove the table or index from the database file. +** +** The table being clear is in the main database file if P2==0. If +** P2==1 then the table to be clear is in the auxiliary database file +** that is used to store tables create using CREATE TEMPORARY TABLE. +** +** If the P3 value is non-zero, then the table referred to must be an +** intkey table (an SQL table, not an index). In this case the row change +** count is incremented by the number of rows in the table being cleared. +** If P3 is greater than zero, then the value stored in register P3 is +** also incremented by the number of rows in the table being cleared. +** +** See also: Destroy +*/ +case OP_Clear: { +#if 0 /* local variables moved into u.bx */ + int nChange; +#endif /* local variables moved into u.bx */ + + u.bx.nChange = 0; + assert( p->readOnly==0 ); + assert( pOp->p1!=1 ); + assert( (p->btreeMask & (((yDbMask)1)<p2))!=0 ); + rc = sqlite3BtreeClearTable( + db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0) + ); + if( pOp->p3 ){ + p->nChange += u.bx.nChange; + if( pOp->p3>0 ){ + assert( memIsValid(&aMem[pOp->p3]) ); + memAboutToChange(p, &aMem[pOp->p3]); + aMem[pOp->p3].u.i += u.bx.nChange; + } + } + break; +} + +/* Opcode: CreateTable P1 P2 * * * +** +** Allocate a new table in the main database file if P1==0 or in the +** auxiliary database file if P1==1 or in an attached database if +** P1>1. Write the root page number of the new table into +** register P2 +** +** The difference between a table and an index is this: A table must +** have a 4-byte integer key and can have arbitrary data. An index +** has an arbitrary key but no data. +** +** See also: CreateIndex +*/ +/* Opcode: CreateIndex P1 P2 * * * +** +** Allocate a new index in the main database file if P1==0 or in the +** auxiliary database file if P1==1 or in an attached database if +** P1>1. Write the root page number of the new table into +** register P2. +** +** See documentation on OP_CreateTable for additional information. +*/ +case OP_CreateIndex: /* out2-prerelease */ +case OP_CreateTable: { /* out2-prerelease */ +#if 0 /* local variables moved into u.by */ + int pgno; + int flags; + Db *pDb; +#endif /* local variables moved into u.by */ + + u.by.pgno = 0; + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + assert( p->readOnly==0 ); + u.by.pDb = &db->aDb[pOp->p1]; + assert( u.by.pDb->pBt!=0 ); + if( pOp->opcode==OP_CreateTable ){ + /* u.by.flags = BTREE_INTKEY; */ + u.by.flags = BTREE_INTKEY; + }else{ + u.by.flags = BTREE_BLOBKEY; + } + rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags); + pOut->u.i = u.by.pgno; + break; +} + +/* Opcode: ParseSchema P1 * * P4 * +** +** Read and parse all entries from the SQLITE_MASTER table of database P1 +** that match the WHERE clause P4. +** +** This opcode invokes the parser to create a new virtual machine, +** then runs the new virtual machine. It is thus a re-entrant opcode. +*/ +case OP_ParseSchema: { +#if 0 /* local variables moved into u.bz */ + int iDb; + const char *zMaster; + char *zSql; + InitData initData; +#endif /* local variables moved into u.bz */ + + /* Any prepared statement that invokes this opcode will hold mutexes + ** on every btree. This is a prerequisite for invoking + ** sqlite3InitCallback(). + */ +#ifdef SQLITE_DEBUG + for(u.bz.iDb=0; u.bz.iDbnDb; u.bz.iDb++){ + assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) ); + } +#endif + + u.bz.iDb = pOp->p1; + assert( u.bz.iDb>=0 && u.bz.iDbnDb ); + assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) ); + /* Used to be a conditional */ { + u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb); + u.bz.initData.db = db; + u.bz.initData.iDb = pOp->p1; + u.bz.initData.pzErrMsg = &p->zErrMsg; + u.bz.zSql = sqlite3MPrintf(db, + "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid", + db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z); + if( u.bz.zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + assert( db->init.busy==0 ); + db->init.busy = 1; + u.bz.initData.rc = SQLITE_OK; + assert( !db->mallocFailed ); + rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0); + if( rc==SQLITE_OK ) rc = u.bz.initData.rc; + sqlite3DbFree(db, u.bz.zSql); + db->init.busy = 0; + } + } + if( rc ) sqlite3ResetAllSchemasOfConnection(db); + if( rc==SQLITE_NOMEM ){ + goto no_mem; + } + break; +} + +#if !defined(SQLITE_OMIT_ANALYZE) +/* Opcode: LoadAnalysis P1 * * * * +** +** Read the sqlite_stat1 table for database P1 and load the content +** of that table into the internal index hash table. This will cause +** the analysis to be used when preparing all subsequent queries. +*/ +case OP_LoadAnalysis: { + assert( pOp->p1>=0 && pOp->p1nDb ); + rc = sqlite3AnalysisLoad(db, pOp->p1); + break; +} +#endif /* !defined(SQLITE_OMIT_ANALYZE) */ + +/* Opcode: DropTable P1 * * P4 * +** +** Remove the internal (in-memory) data structures that describe +** the table named P4 in database P1. This is called after a table +** is dropped in order to keep the internal representation of the +** schema consistent with what is on disk. +*/ +case OP_DropTable: { + sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); + break; +} + +/* Opcode: DropIndex P1 * * P4 * +** +** Remove the internal (in-memory) data structures that describe +** the index named P4 in database P1. This is called after an index +** is dropped in order to keep the internal representation of the +** schema consistent with what is on disk. +*/ +case OP_DropIndex: { + sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); + break; +} + +/* Opcode: DropTrigger P1 * * P4 * +** +** Remove the internal (in-memory) data structures that describe +** the trigger named P4 in database P1. This is called after a trigger +** is dropped in order to keep the internal representation of the +** schema consistent with what is on disk. +*/ +case OP_DropTrigger: { + sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); + break; +} + + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK +/* Opcode: IntegrityCk P1 P2 P3 * P5 +** +** Do an analysis of the currently open database. Store in +** register P1 the text of an error message describing any problems. +** If no problems are found, store a NULL in register P1. +** +** The register P3 contains the maximum number of allowed errors. +** At most reg(P3) errors will be reported. +** In other words, the analysis stops as soon as reg(P1) errors are +** seen. Reg(P1) is updated with the number of errors remaining. +** +** The root page numbers of all tables in the database are integer +** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables +** total. +** +** If P5 is not zero, the check is done on the auxiliary database +** file, not the main database file. +** +** This opcode is used to implement the integrity_check pragma. +*/ +case OP_IntegrityCk: { +#if 0 /* local variables moved into u.ca */ + int nRoot; /* Number of tables to check. (Number of root pages.) */ + int *aRoot; /* Array of rootpage numbers for tables to be checked */ + int j; /* Loop counter */ + int nErr; /* Number of errors reported */ + char *z; /* Text of the error report */ + Mem *pnErr; /* Register keeping track of errors remaining */ +#endif /* local variables moved into u.ca */ + + assert( p->bIsReader ); + u.ca.nRoot = pOp->p2; + assert( u.ca.nRoot>0 ); + u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) ); + if( u.ca.aRoot==0 ) goto no_mem; + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + u.ca.pnErr = &aMem[pOp->p3]; + assert( (u.ca.pnErr->flags & MEM_Int)!=0 ); + assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 ); + pIn1 = &aMem[pOp->p1]; + for(u.ca.j=0; u.ca.jp5nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p5))!=0 ); + u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot, + (int)u.ca.pnErr->u.i, &u.ca.nErr); + sqlite3DbFree(db, u.ca.aRoot); + u.ca.pnErr->u.i -= u.ca.nErr; + sqlite3VdbeMemSetNull(pIn1); + if( u.ca.nErr==0 ){ + assert( u.ca.z==0 ); + }else if( u.ca.z==0 ){ + goto no_mem; + }else{ + sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free); + } + UPDATE_MAX_BLOBSIZE(pIn1); + sqlite3VdbeChangeEncoding(pIn1, encoding); + break; +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +/* Opcode: RowSetAdd P1 P2 * * * +** +** Insert the integer value held by register P2 into a boolean index +** held in register P1. +** +** An assertion fails if P2 is not an integer. +*/ +case OP_RowSetAdd: { /* in1, in2 */ + pIn1 = &aMem[pOp->p1]; + pIn2 = &aMem[pOp->p2]; + assert( (pIn2->flags & MEM_Int)!=0 ); + if( (pIn1->flags & MEM_RowSet)==0 ){ + sqlite3VdbeMemSetRowSet(pIn1); + if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; + } + sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i); + break; +} + +/* Opcode: RowSetRead P1 P2 P3 * * +** +** Extract the smallest value from boolean index P1 and put that value into +** register P3. Or, if boolean index P1 is initially empty, leave P3 +** unchanged and jump to instruction P2. +*/ +case OP_RowSetRead: { /* jump, in1, out3 */ +#if 0 /* local variables moved into u.cb */ + i64 val; +#endif /* local variables moved into u.cb */ + + pIn1 = &aMem[pOp->p1]; + if( (pIn1->flags & MEM_RowSet)==0 + || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0 + ){ + /* The boolean index is empty */ + sqlite3VdbeMemSetNull(pIn1); + pc = pOp->p2 - 1; + }else{ + /* A value was pulled from the index */ + sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val); + } + goto check_for_interrupt; +} + +/* Opcode: RowSetTest P1 P2 P3 P4 +** +** Register P3 is assumed to hold a 64-bit integer value. If register P1 +** contains a RowSet object and that RowSet object contains +** the value held in P3, jump to register P2. Otherwise, insert the +** integer in P3 into the RowSet and continue on to the +** next opcode. +** +** The RowSet object is optimized for the case where successive sets +** of integers, where each set contains no duplicates. Each set +** of values is identified by a unique P4 value. The first set +** must have P4==0, the final set P4=-1. P4 must be either -1 or +** non-negative. For non-negative values of P4 only the lower 4 +** bits are significant. +** +** This allows optimizations: (a) when P4==0 there is no need to test +** the rowset object for P3, as it is guaranteed not to contain it, +** (b) when P4==-1 there is no need to insert the value, as it will +** never be tested for, and (c) when a value that is part of set X is +** inserted, there is no need to search to see if the same value was +** previously inserted as part of set X (only if it was previously +** inserted as part of some other set). +*/ +case OP_RowSetTest: { /* jump, in1, in3 */ +#if 0 /* local variables moved into u.cc */ + int iSet; + int exists; +#endif /* local variables moved into u.cc */ + + pIn1 = &aMem[pOp->p1]; + pIn3 = &aMem[pOp->p3]; + u.cc.iSet = pOp->p4.i; + assert( pIn3->flags&MEM_Int ); + + /* If there is anything other than a rowset object in memory cell P1, + ** delete it now and initialize P1 with an empty rowset + */ + if( (pIn1->flags & MEM_RowSet)==0 ){ + sqlite3VdbeMemSetRowSet(pIn1); + if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; + } + + assert( pOp->p4type==P4_INT32 ); + assert( u.cc.iSet==-1 || u.cc.iSet>=0 ); + if( u.cc.iSet ){ + u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet, + (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff), + pIn3->u.i); + if( u.cc.exists ){ + pc = pOp->p2 - 1; + break; + } + } + if( u.cc.iSet>=0 ){ + sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i); + } + break; +} + + +#ifndef SQLITE_OMIT_TRIGGER + +/* Opcode: Program P1 P2 P3 P4 * +** +** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). +** +** P1 contains the address of the memory cell that contains the first memory +** cell in an array of values used as arguments to the sub-program. P2 +** contains the address to jump to if the sub-program throws an IGNORE +** exception using the RAISE() function. Register P3 contains the address +** of a memory cell in this (the parent) VM that is used to allocate the +** memory required by the sub-vdbe at runtime. +** +** P4 is a pointer to the VM containing the trigger program. +*/ +case OP_Program: { /* jump */ +#if 0 /* local variables moved into u.cd */ + int nMem; /* Number of memory registers for sub-program */ + int nByte; /* Bytes of runtime space required for sub-program */ + Mem *pRt; /* Register to allocate runtime space */ + Mem *pMem; /* Used to iterate through memory cells */ + Mem *pEnd; /* Last memory cell in new array */ + VdbeFrame *pFrame; /* New vdbe frame to execute in */ + SubProgram *pProgram; /* Sub-program to execute */ + void *t; /* Token identifying trigger */ +#endif /* local variables moved into u.cd */ + + u.cd.pProgram = pOp->p4.pProgram; + u.cd.pRt = &aMem[pOp->p3]; + assert( u.cd.pProgram->nOp>0 ); + + /* If the p5 flag is clear, then recursive invocation of triggers is + ** disabled for backwards compatibility (p5 is set if this sub-program + ** is really a trigger, not a foreign key action, and the flag set + ** and cleared by the "PRAGMA recursive_triggers" command is clear). + ** + ** It is recursive invocation of triggers, at the SQL level, that is + ** disabled. In some cases a single trigger may generate more than one + ** SubProgram (if the trigger may be executed with more than one different + ** ON CONFLICT algorithm). SubProgram structures associated with a + ** single trigger all have the same value for the SubProgram.token + ** variable. */ + if( pOp->p5 ){ + u.cd.t = u.cd.pProgram->token; + for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent); + if( u.cd.pFrame ) break; + } + + if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ + rc = SQLITE_ERROR; + sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion"); + break; + } + + /* Register u.cd.pRt is used to store the memory required to save the state + ** of the current program, and the memory required at runtime to execute + ** the trigger program. If this trigger has been fired before, then u.cd.pRt + ** is already allocated. Otherwise, it must be initialized. */ + if( (u.cd.pRt->flags&MEM_Frame)==0 ){ + /* SubProgram.nMem is set to the number of memory cells used by the + ** program stored in SubProgram.aOp. As well as these, one memory + ** cell is required for each cursor used by the program. Set local + ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value. + */ + u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr; + u.cd.nByte = ROUND8(sizeof(VdbeFrame)) + + u.cd.nMem * sizeof(Mem) + + u.cd.pProgram->nCsr * sizeof(VdbeCursor *) + + u.cd.pProgram->nOnce * sizeof(u8); + u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte); + if( !u.cd.pFrame ){ + goto no_mem; + } + sqlite3VdbeMemRelease(u.cd.pRt); + u.cd.pRt->flags = MEM_Frame; + u.cd.pRt->u.pFrame = u.cd.pFrame; + + u.cd.pFrame->v = p; + u.cd.pFrame->nChildMem = u.cd.nMem; + u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr; + u.cd.pFrame->pc = pc; + u.cd.pFrame->aMem = p->aMem; + u.cd.pFrame->nMem = p->nMem; + u.cd.pFrame->apCsr = p->apCsr; + u.cd.pFrame->nCursor = p->nCursor; + u.cd.pFrame->aOp = p->aOp; + u.cd.pFrame->nOp = p->nOp; + u.cd.pFrame->token = u.cd.pProgram->token; + u.cd.pFrame->aOnceFlag = p->aOnceFlag; + u.cd.pFrame->nOnceFlag = p->nOnceFlag; + + u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem]; + for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){ + u.cd.pMem->flags = MEM_Invalid; + u.cd.pMem->db = db; + } + }else{ + u.cd.pFrame = u.cd.pRt->u.pFrame; + assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem ); + assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr ); + assert( pc==u.cd.pFrame->pc ); + } + + p->nFrame++; + u.cd.pFrame->pParent = p->pFrame; + u.cd.pFrame->lastRowid = lastRowid; + u.cd.pFrame->nChange = p->nChange; + p->nChange = 0; + p->pFrame = u.cd.pFrame; + p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1]; + p->nMem = u.cd.pFrame->nChildMem; + p->nCursor = (u16)u.cd.pFrame->nChildCsr; + p->apCsr = (VdbeCursor **)&aMem[p->nMem+1]; + p->aOp = aOp = u.cd.pProgram->aOp; + p->nOp = u.cd.pProgram->nOp; + p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor]; + p->nOnceFlag = u.cd.pProgram->nOnce; + pc = -1; + memset(p->aOnceFlag, 0, p->nOnceFlag); + + break; +} + +/* Opcode: Param P1 P2 * * * +** +** This opcode is only ever present in sub-programs called via the +** OP_Program instruction. Copy a value currently stored in a memory +** cell of the calling (parent) frame to cell P2 in the current frames +** address space. This is used by trigger programs to access the new.* +** and old.* values. +** +** The address of the cell in the parent frame is determined by adding +** the value of the P1 argument to the value of the P1 argument to the +** calling OP_Program instruction. +*/ +case OP_Param: { /* out2-prerelease */ +#if 0 /* local variables moved into u.ce */ + VdbeFrame *pFrame; + Mem *pIn; +#endif /* local variables moved into u.ce */ + u.ce.pFrame = p->pFrame; + u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1]; + sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem); + break; +} + +#endif /* #ifndef SQLITE_OMIT_TRIGGER */ + +#ifndef SQLITE_OMIT_FOREIGN_KEY +/* Opcode: FkCounter P1 P2 * * * +** +** Increment a "constraint counter" by P2 (P2 may be negative or positive). +** If P1 is non-zero, the database constraint counter is incremented +** (deferred foreign key constraints). Otherwise, if P1 is zero, the +** statement counter is incremented (immediate foreign key constraints). +*/ +case OP_FkCounter: { + if( db->flags & SQLITE_DeferFKs ){ + db->nDeferredImmCons += pOp->p2; + }else if( pOp->p1 ){ + db->nDeferredCons += pOp->p2; + }else{ + p->nFkConstraint += pOp->p2; + } + break; +} + +/* Opcode: FkIfZero P1 P2 * * * +** +** This opcode tests if a foreign key constraint-counter is currently zero. +** If so, jump to instruction P2. Otherwise, fall through to the next +** instruction. +** +** If P1 is non-zero, then the jump is taken if the database constraint-counter +** is zero (the one that counts deferred constraint violations). If P1 is +** zero, the jump is taken if the statement constraint-counter is zero +** (immediate foreign key constraint violations). +*/ +case OP_FkIfZero: { /* jump */ + if( pOp->p1 ){ + if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1; + }else{ + if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1; + } + break; +} +#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ + +#ifndef SQLITE_OMIT_AUTOINCREMENT +/* Opcode: MemMax P1 P2 * * * +** +** P1 is a register in the root frame of this VM (the root frame is +** different from the current frame if this instruction is being executed +** within a sub-program). Set the value of register P1 to the maximum of +** its current value and the value in register P2. +** +** This instruction throws an error if the memory cell is not initially +** an integer. +*/ +case OP_MemMax: { /* in2 */ +#if 0 /* local variables moved into u.cf */ + Mem *pIn1; + VdbeFrame *pFrame; +#endif /* local variables moved into u.cf */ + if( p->pFrame ){ + for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent); + u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1]; + }else{ + u.cf.pIn1 = &aMem[pOp->p1]; + } + assert( memIsValid(u.cf.pIn1) ); + sqlite3VdbeMemIntegerify(u.cf.pIn1); + pIn2 = &aMem[pOp->p2]; + sqlite3VdbeMemIntegerify(pIn2); + if( u.cf.pIn1->u.iu.i){ + u.cf.pIn1->u.i = pIn2->u.i; + } + break; +} +#endif /* SQLITE_OMIT_AUTOINCREMENT */ + +/* Opcode: IfPos P1 P2 * * * +** +** If the value of register P1 is 1 or greater, jump to P2. +** +** It is illegal to use this instruction on a register that does +** not contain an integer. An assertion fault will result if you try. +*/ +case OP_IfPos: { /* jump, in1 */ + pIn1 = &aMem[pOp->p1]; + assert( pIn1->flags&MEM_Int ); + if( pIn1->u.i>0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: IfNeg P1 P2 * * * +** +** If the value of register P1 is less than zero, jump to P2. +** +** It is illegal to use this instruction on a register that does +** not contain an integer. An assertion fault will result if you try. +*/ +case OP_IfNeg: { /* jump, in1 */ + pIn1 = &aMem[pOp->p1]; + assert( pIn1->flags&MEM_Int ); + if( pIn1->u.i<0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: IfZero P1 P2 P3 * * +** +** The register P1 must contain an integer. Add literal P3 to the +** value in register P1. If the result is exactly 0, jump to P2. +** +** It is illegal to use this instruction on a register that does +** not contain an integer. An assertion fault will result if you try. +*/ +case OP_IfZero: { /* jump, in1 */ + pIn1 = &aMem[pOp->p1]; + assert( pIn1->flags&MEM_Int ); + pIn1->u.i += pOp->p3; + if( pIn1->u.i==0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: AggStep * P2 P3 P4 P5 +** +** Execute the step function for an aggregate. The +** function has P5 arguments. P4 is a pointer to the FuncDef +** structure that specifies the function. Use register +** P3 as the accumulator. +** +** The P5 arguments are taken from register P2 and its +** successors. +*/ +case OP_AggStep: { +#if 0 /* local variables moved into u.cg */ + int n; + int i; + Mem *pMem; + Mem *pRec; + sqlite3_context ctx; + sqlite3_value **apVal; +#endif /* local variables moved into u.cg */ + + u.cg.n = pOp->p5; + assert( u.cg.n>=0 ); + u.cg.pRec = &aMem[pOp->p2]; + u.cg.apVal = p->apArg; + assert( u.cg.apVal || u.cg.n==0 ); + for(u.cg.i=0; u.cg.ip4.pFunc; + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3]; + u.cg.pMem->n++; + u.cg.ctx.s.flags = MEM_Null; + u.cg.ctx.s.z = 0; + u.cg.ctx.s.zMalloc = 0; + u.cg.ctx.s.xDel = 0; + u.cg.ctx.s.db = db; + u.cg.ctx.isError = 0; + u.cg.ctx.pColl = 0; + u.cg.ctx.skipFlag = 0; + if( u.cg.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ + assert( pOp>p->aOp ); + assert( pOp[-1].p4type==P4_COLLSEQ ); + assert( pOp[-1].opcode==OP_CollSeq ); + u.cg.ctx.pColl = pOp[-1].p4.pColl; + } + (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */ + if( u.cg.ctx.isError ){ + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s)); + rc = u.cg.ctx.isError; + } + if( u.cg.ctx.skipFlag ){ + assert( pOp[-1].opcode==OP_CollSeq ); + u.cg.i = pOp[-1].p1; + if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1); + } + + sqlite3VdbeMemRelease(&u.cg.ctx.s); + + break; +} + +/* Opcode: AggFinal P1 P2 * P4 * +** +** Execute the finalizer function for an aggregate. P1 is +** the memory location that is the accumulator for the aggregate. +** +** P2 is the number of arguments that the step function takes and +** P4 is a pointer to the FuncDef for this function. The P2 +** argument is not used by this opcode. It is only there to disambiguate +** functions that can take varying numbers of arguments. The +** P4 argument is only needed for the degenerate case where +** the step function was not previously called. +*/ +case OP_AggFinal: { +#if 0 /* local variables moved into u.ch */ + Mem *pMem; +#endif /* local variables moved into u.ch */ + assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) ); + u.ch.pMem = &aMem[pOp->p1]; + assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); + rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc); + if( rc ){ + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem)); + } + sqlite3VdbeChangeEncoding(u.ch.pMem, encoding); + UPDATE_MAX_BLOBSIZE(u.ch.pMem); + if( sqlite3VdbeMemTooBig(u.ch.pMem) ){ + goto too_big; + } + break; +} + +#ifndef SQLITE_OMIT_WAL +/* Opcode: Checkpoint P1 P2 P3 * * +** +** Checkpoint database P1. This is a no-op if P1 is not currently in +** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL +** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns +** SQLITE_BUSY or not, respectively. Write the number of pages in the +** WAL after the checkpoint into mem[P3+1] and the number of pages +** in the WAL that have been checkpointed after the checkpoint +** completes into mem[P3+2]. However on an error, mem[P3+1] and +** mem[P3+2] are initialized to -1. +*/ +case OP_Checkpoint: { +#if 0 /* local variables moved into u.ci */ + int i; /* Loop counter */ + int aRes[3]; /* Results */ + Mem *pMem; /* Write results here */ +#endif /* local variables moved into u.ci */ + + assert( p->readOnly==0 ); + u.ci.aRes[0] = 0; + u.ci.aRes[1] = u.ci.aRes[2] = -1; + assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE + || pOp->p2==SQLITE_CHECKPOINT_FULL + || pOp->p2==SQLITE_CHECKPOINT_RESTART + ); + rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]); + if( rc==SQLITE_BUSY ){ + rc = SQLITE_OK; + u.ci.aRes[0] = 1; + } + for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){ + sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]); + } + break; +}; +#endif + +#ifndef SQLITE_OMIT_PRAGMA +/* Opcode: JournalMode P1 P2 P3 * P5 +** +** Change the journal mode of database P1 to P3. P3 must be one of the +** PAGER_JOURNALMODE_XXX values. If changing between the various rollback +** modes (delete, truncate, persist, off and memory), this is a simple +** operation. No IO is required. +** +** If changing into or out of WAL mode the procedure is more complicated. +** +** Write a string containing the final journal-mode to register P2. +*/ +case OP_JournalMode: { /* out2-prerelease */ +#if 0 /* local variables moved into u.cj */ + Btree *pBt; /* Btree to change journal mode of */ + Pager *pPager; /* Pager associated with pBt */ + int eNew; /* New journal mode */ + int eOld; /* The old journal mode */ +#ifndef SQLITE_OMIT_WAL + const char *zFilename; /* Name of database file for pPager */ +#endif +#endif /* local variables moved into u.cj */ + + u.cj.eNew = pOp->p3; + assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE + || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE + || u.cj.eNew==PAGER_JOURNALMODE_PERSIST + || u.cj.eNew==PAGER_JOURNALMODE_OFF + || u.cj.eNew==PAGER_JOURNALMODE_MEMORY + || u.cj.eNew==PAGER_JOURNALMODE_WAL + || u.cj.eNew==PAGER_JOURNALMODE_QUERY + ); + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( p->readOnly==0 ); + + u.cj.pBt = db->aDb[pOp->p1].pBt; + u.cj.pPager = sqlite3BtreePager(u.cj.pBt); + u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager); + if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld; + if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld; + +#ifndef SQLITE_OMIT_WAL + u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1); + + /* Do not allow a transition to journal_mode=WAL for a database + ** in temporary storage or if the VFS does not support shared memory + */ + if( u.cj.eNew==PAGER_JOURNALMODE_WAL + && (sqlite3Strlen30(u.cj.zFilename)==0 /* Temp file */ + || !sqlite3PagerWalSupported(u.cj.pPager)) /* No shared-memory support */ + ){ + u.cj.eNew = u.cj.eOld; + } + + if( (u.cj.eNew!=u.cj.eOld) + && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL) + ){ + if( !db->autoCommit || db->nVdbeRead>1 ){ + rc = SQLITE_ERROR; + sqlite3SetString(&p->zErrMsg, db, + "cannot change %s wal mode from within a transaction", + (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of") + ); + break; + }else{ + + if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){ + /* If leaving WAL mode, close the log file. If successful, the call + ** to PagerCloseWal() checkpoints and deletes the write-ahead-log + ** file. An EXCLUSIVE lock may still be held on the database file + ** after a successful return. + */ + rc = sqlite3PagerCloseWal(u.cj.pPager); + if( rc==SQLITE_OK ){ + sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew); + } + }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){ + /* Cannot transition directly from MEMORY to WAL. Use mode OFF + ** as an intermediate */ + sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF); + } + + /* Open a transaction on the database file. Regardless of the journal + ** mode, this transaction always uses a rollback journal. + */ + assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 ); + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1)); + } + } + } +#endif /* ifndef SQLITE_OMIT_WAL */ + + if( rc ){ + u.cj.eNew = u.cj.eOld; + } + u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew); + + pOut = &aMem[pOp->p2]; + pOut->flags = MEM_Str|MEM_Static|MEM_Term; + pOut->z = (char *)sqlite3JournalModename(u.cj.eNew); + pOut->n = sqlite3Strlen30(pOut->z); + pOut->enc = SQLITE_UTF8; + sqlite3VdbeChangeEncoding(pOut, encoding); + break; +}; +#endif /* SQLITE_OMIT_PRAGMA */ + +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) +/* Opcode: Vacuum * * * * * +** +** Vacuum the entire database. This opcode will cause other virtual +** machines to be created and run. It may not be called from within +** a transaction. +*/ +case OP_Vacuum: { + assert( p->readOnly==0 ); + rc = sqlite3RunVacuum(&p->zErrMsg, db); + break; +} +#endif + +#if !defined(SQLITE_OMIT_AUTOVACUUM) +/* Opcode: IncrVacuum P1 P2 * * * +** +** Perform a single step of the incremental vacuum procedure on +** the P1 database. If the vacuum has finished, jump to instruction +** P2. Otherwise, fall through to the next instruction. +*/ +case OP_IncrVacuum: { /* jump */ +#if 0 /* local variables moved into u.ck */ + Btree *pBt; +#endif /* local variables moved into u.ck */ + + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + assert( p->readOnly==0 ); + u.ck.pBt = db->aDb[pOp->p1].pBt; + rc = sqlite3BtreeIncrVacuum(u.ck.pBt); + if( rc==SQLITE_DONE ){ + pc = pOp->p2 - 1; + rc = SQLITE_OK; + } + break; +} +#endif + +/* Opcode: Expire P1 * * * * +** +** Cause precompiled statements to become expired. An expired statement +** fails with an error code of SQLITE_SCHEMA if it is ever executed +** (via sqlite3_step()). +** +** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, +** then only the currently executing statement is affected. +*/ +case OP_Expire: { + if( !pOp->p1 ){ + sqlite3ExpirePreparedStatements(db); + }else{ + p->expired = 1; + } + break; +} + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* Opcode: TableLock P1 P2 P3 P4 * +** +** Obtain a lock on a particular table. This instruction is only used when +** the shared-cache feature is enabled. +** +** P1 is the index of the database in sqlite3.aDb[] of the database +** on which the lock is acquired. A readlock is obtained if P3==0 or +** a write lock if P3==1. +** +** P2 contains the root-page of the table to lock. +** +** P4 contains a pointer to the name of the table being locked. This is only +** used to generate an error message if the lock cannot be obtained. +*/ +case OP_TableLock: { + u8 isWriteLock = (u8)pOp->p3; + if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){ + int p1 = pOp->p1; + assert( p1>=0 && p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<aDb[p1].pBt, pOp->p2, isWriteLock); + if( (rc&0xFF)==SQLITE_LOCKED ){ + const char *z = pOp->p4.z; + sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z); + } + } + break; +} +#endif /* SQLITE_OMIT_SHARED_CACHE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VBegin * * * P4 * +** +** P4 may be a pointer to an sqlite3_vtab structure. If so, call the +** xBegin method for that table. +** +** Also, whether or not P4 is set, check that this is not being called from +** within a callback to a virtual table xSync() method. If it is, the error +** code will be set to SQLITE_LOCKED. +*/ +case OP_VBegin: { +#if 0 /* local variables moved into u.cl */ + VTable *pVTab; +#endif /* local variables moved into u.cl */ + u.cl.pVTab = pOp->p4.pVtab; + rc = sqlite3VtabBegin(db, u.cl.pVTab); + if( u.cl.pVTab ) sqlite3VtabImportErrmsg(p, u.cl.pVTab->pVtab); + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VCreate P1 * * P4 * +** +** P4 is the name of a virtual table in database P1. Call the xCreate method +** for that table. +*/ +case OP_VCreate: { + rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg); + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VDestroy P1 * * P4 * +** +** P4 is the name of a virtual table in database P1. Call the xDestroy method +** of that table. +*/ +case OP_VDestroy: { + p->inVtabMethod = 2; + rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); + p->inVtabMethod = 0; + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VOpen P1 * * P4 * +** +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. +** P1 is a cursor number. This opcode opens a cursor to the virtual +** table and stores that cursor in P1. +*/ +case OP_VOpen: { +#if 0 /* local variables moved into u.cm */ + VdbeCursor *pCur; + sqlite3_vtab_cursor *pVtabCursor; + sqlite3_vtab *pVtab; + sqlite3_module *pModule; +#endif /* local variables moved into u.cm */ + + assert( p->bIsReader ); + u.cm.pCur = 0; + u.cm.pVtabCursor = 0; + u.cm.pVtab = pOp->p4.pVtab->pVtab; + u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule; + assert(u.cm.pVtab && u.cm.pModule); + rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor); + sqlite3VtabImportErrmsg(p, u.cm.pVtab); + if( SQLITE_OK==rc ){ + /* Initialize sqlite3_vtab_cursor base class */ + u.cm.pVtabCursor->pVtab = u.cm.pVtab; + + /* Initialize vdbe cursor object */ + u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0); + if( u.cm.pCur ){ + u.cm.pCur->pVtabCursor = u.cm.pVtabCursor; + u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule; + }else{ + db->mallocFailed = 1; + u.cm.pModule->xClose(u.cm.pVtabCursor); + } + } + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VFilter P1 P2 P3 P4 * +** +** P1 is a cursor opened using VOpen. P2 is an address to jump to if +** the filtered result set is empty. +** +** P4 is either NULL or a string that was generated by the xBestIndex +** method of the module. The interpretation of the P4 string is left +** to the module implementation. +** +** This opcode invokes the xFilter method on the virtual table specified +** by P1. The integer query plan parameter to xFilter is stored in register +** P3. Register P3+1 stores the argc parameter to be passed to the +** xFilter method. Registers P3+2..P3+1+argc are the argc +** additional parameters which are passed to +** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter. +** +** A jump is made to P2 if the result set after filtering would be empty. +*/ +case OP_VFilter: { /* jump */ +#if 0 /* local variables moved into u.cn */ + int nArg; + int iQuery; + const sqlite3_module *pModule; + Mem *pQuery; + Mem *pArgc; + sqlite3_vtab_cursor *pVtabCursor; + sqlite3_vtab *pVtab; + VdbeCursor *pCur; + int res; + int i; + Mem **apArg; +#endif /* local variables moved into u.cn */ + + u.cn.pQuery = &aMem[pOp->p3]; + u.cn.pArgc = &u.cn.pQuery[1]; + u.cn.pCur = p->apCsr[pOp->p1]; + assert( memIsValid(u.cn.pQuery) ); + REGISTER_TRACE(pOp->p3, u.cn.pQuery); + assert( u.cn.pCur->pVtabCursor ); + u.cn.pVtabCursor = u.cn.pCur->pVtabCursor; + u.cn.pVtab = u.cn.pVtabCursor->pVtab; + u.cn.pModule = u.cn.pVtab->pModule; + + /* Grab the index number and argc parameters */ + assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int ); + u.cn.nArg = (int)u.cn.pArgc->u.i; + u.cn.iQuery = (int)u.cn.pQuery->u.i; + + /* Invoke the xFilter method */ + { + u.cn.res = 0; + u.cn.apArg = p->apArg; + for(u.cn.i = 0; u.cn.iinVtabMethod = 1; + rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg); + p->inVtabMethod = 0; + sqlite3VtabImportErrmsg(p, u.cn.pVtab); + if( rc==SQLITE_OK ){ + u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor); + } + + if( u.cn.res ){ + pc = pOp->p2 - 1; + } + } + u.cn.pCur->nullRow = 0; + + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VColumn P1 P2 P3 * * +** +** Store the value of the P2-th column of +** the row of the virtual-table that the +** P1 cursor is pointing to into register P3. +*/ +case OP_VColumn: { +#if 0 /* local variables moved into u.co */ + sqlite3_vtab *pVtab; + const sqlite3_module *pModule; + Mem *pDest; + sqlite3_context sContext; +#endif /* local variables moved into u.co */ + + VdbeCursor *pCur = p->apCsr[pOp->p1]; + assert( pCur->pVtabCursor ); + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + u.co.pDest = &aMem[pOp->p3]; + memAboutToChange(p, u.co.pDest); + if( pCur->nullRow ){ + sqlite3VdbeMemSetNull(u.co.pDest); + break; + } + u.co.pVtab = pCur->pVtabCursor->pVtab; + u.co.pModule = u.co.pVtab->pModule; + assert( u.co.pModule->xColumn ); + memset(&u.co.sContext, 0, sizeof(u.co.sContext)); + + /* The output cell may already have a buffer allocated. Move + ** the current contents to u.co.sContext.s so in case the user-function + ** can use the already allocated buffer instead of allocating a + ** new one. + */ + sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest); + MemSetTypeFlag(&u.co.sContext.s, MEM_Null); + + rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2); + sqlite3VtabImportErrmsg(p, u.co.pVtab); + if( u.co.sContext.isError ){ + rc = u.co.sContext.isError; + } + + /* Copy the result of the function to the P3 register. We + ** do this regardless of whether or not an error occurred to ensure any + ** dynamic allocation in u.co.sContext.s (a Mem struct) is released. + */ + sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding); + sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s); + REGISTER_TRACE(pOp->p3, u.co.pDest); + UPDATE_MAX_BLOBSIZE(u.co.pDest); + + if( sqlite3VdbeMemTooBig(u.co.pDest) ){ + goto too_big; + } + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VNext P1 P2 * * * +** +** Advance virtual table P1 to the next row in its result set and +** jump to instruction P2. Or, if the virtual table has reached +** the end of its result set, then fall through to the next instruction. +*/ +case OP_VNext: { /* jump */ +#if 0 /* local variables moved into u.cp */ + sqlite3_vtab *pVtab; + const sqlite3_module *pModule; + int res; + VdbeCursor *pCur; +#endif /* local variables moved into u.cp */ + + u.cp.res = 0; + u.cp.pCur = p->apCsr[pOp->p1]; + assert( u.cp.pCur->pVtabCursor ); + if( u.cp.pCur->nullRow ){ + break; + } + u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab; + u.cp.pModule = u.cp.pVtab->pModule; + assert( u.cp.pModule->xNext ); + + /* Invoke the xNext() method of the module. There is no way for the + ** underlying implementation to return an error if one occurs during + ** xNext(). Instead, if an error occurs, true is returned (indicating that + ** data is available) and the error code returned when xColumn or + ** some other method is next invoked on the save virtual table cursor. + */ + p->inVtabMethod = 1; + rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor); + p->inVtabMethod = 0; + sqlite3VtabImportErrmsg(p, u.cp.pVtab); + if( rc==SQLITE_OK ){ + u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor); + } + + if( !u.cp.res ){ + /* If there is data, jump to P2 */ + pc = pOp->p2 - 1; + } + goto check_for_interrupt; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VRename P1 * * P4 * +** +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. +** This opcode invokes the corresponding xRename method. The value +** in register P1 is passed as the zName argument to the xRename method. +*/ +case OP_VRename: { +#if 0 /* local variables moved into u.cq */ + sqlite3_vtab *pVtab; + Mem *pName; +#endif /* local variables moved into u.cq */ + + u.cq.pVtab = pOp->p4.pVtab->pVtab; + u.cq.pName = &aMem[pOp->p1]; + assert( u.cq.pVtab->pModule->xRename ); + assert( memIsValid(u.cq.pName) ); + assert( p->readOnly==0 ); + REGISTER_TRACE(pOp->p1, u.cq.pName); + assert( u.cq.pName->flags & MEM_Str ); + testcase( u.cq.pName->enc==SQLITE_UTF8 ); + testcase( u.cq.pName->enc==SQLITE_UTF16BE ); + testcase( u.cq.pName->enc==SQLITE_UTF16LE ); + rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8); + if( rc==SQLITE_OK ){ + rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z); + sqlite3VtabImportErrmsg(p, u.cq.pVtab); + p->expired = 0; + } + break; +} +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VUpdate P1 P2 P3 P4 * +** +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. +** This opcode invokes the corresponding xUpdate method. P2 values +** are contiguous memory cells starting at P3 to pass to the xUpdate +** invocation. The value in register (P3+P2-1) corresponds to the +** p2th element of the argv array passed to xUpdate. +** +** The xUpdate method will do a DELETE or an INSERT or both. +** The argv[0] element (which corresponds to memory cell P3) +** is the rowid of a row to delete. If argv[0] is NULL then no +** deletion occurs. The argv[1] element is the rowid of the new +** row. This can be NULL to have the virtual table select the new +** rowid for itself. The subsequent elements in the array are +** the values of columns in the new row. +** +** If P2==1 then no insert is performed. argv[0] is the rowid of +** a row to delete. +** +** P1 is a boolean flag. If it is set to true and the xUpdate call +** is successful, then the value returned by sqlite3_last_insert_rowid() +** is set to the value of the rowid for the row just inserted. +*/ +case OP_VUpdate: { +#if 0 /* local variables moved into u.cr */ + sqlite3_vtab *pVtab; + sqlite3_module *pModule; + int nArg; + int i; + sqlite_int64 rowid; + Mem **apArg; + Mem *pX; +#endif /* local variables moved into u.cr */ + + assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback + || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace + ); + assert( p->readOnly==0 ); + u.cr.pVtab = pOp->p4.pVtab->pVtab; + u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule; + u.cr.nArg = pOp->p2; + assert( pOp->p4type==P4_VTAB ); + if( ALWAYS(u.cr.pModule->xUpdate) ){ + u8 vtabOnConflict = db->vtabOnConflict; + u.cr.apArg = p->apArg; + u.cr.pX = &aMem[pOp->p3]; + for(u.cr.i=0; u.cr.ivtabOnConflict = pOp->p5; + rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid); + db->vtabOnConflict = vtabOnConflict; + sqlite3VtabImportErrmsg(p, u.cr.pVtab); + if( rc==SQLITE_OK && pOp->p1 ){ + assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) ); + db->lastRowid = lastRowid = u.cr.rowid; + } + if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){ + if( pOp->p5==OE_Ignore ){ + rc = SQLITE_OK; + }else{ + p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5); + } + }else{ + p->nChange++; + } + } + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* Opcode: Pagecount P1 P2 * * * +** +** Write the current number of pages in database P1 to memory cell P2. +*/ +case OP_Pagecount: { /* out2-prerelease */ + pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt); + break; +} +#endif + + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* Opcode: MaxPgcnt P1 P2 P3 * * +** +** Try to set the maximum page count for database P1 to the value in P3. +** Do not let the maximum page count fall below the current page count and +** do not change the maximum page count value if P3==0. +** +** Store the maximum page count after the change in register P2. +*/ +case OP_MaxPgcnt: { /* out2-prerelease */ + unsigned int newMax; + Btree *pBt; + + pBt = db->aDb[pOp->p1].pBt; + newMax = 0; + if( pOp->p3 ){ + newMax = sqlite3BtreeLastPage(pBt); + if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3; + } + pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax); + break; +} +#endif + + +#ifndef SQLITE_OMIT_TRACE +/* Opcode: Trace * * * P4 * +** +** If tracing is enabled (by the sqlite3_trace()) interface, then +** the UTF-8 string contained in P4 is emitted on the trace callback. +*/ +case OP_Trace: { +#if 0 /* local variables moved into u.cs */ + char *zTrace; + char *z; +#endif /* local variables moved into u.cs */ + + if( db->xTrace + && !p->doingRerun + && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 + ){ + u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace); + db->xTrace(db->pTraceArg, u.cs.z); + sqlite3DbFree(db, u.cs.z); + } +#ifdef SQLITE_DEBUG + if( (db->flags & SQLITE_SqlTrace)!=0 + && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 + ){ + sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace); + } +#endif /* SQLITE_DEBUG */ + break; +} +#endif + + +/* Opcode: Noop * * * * * +** +** Do nothing. This instruction is often useful as a jump +** destination. +*/ +/* +** The magic Explain opcode are only inserted when explain==2 (which +** is to say when the EXPLAIN QUERY PLAN syntax is used.) +** This opcode records information from the optimizer. It is the +** the same as a no-op. This opcodesnever appears in a real VM program. +*/ +default: { /* This is really OP_Noop and OP_Explain */ + assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain ); + break; +} + +/***************************************************************************** +** The cases of the switch statement above this line should all be indented +** by 6 spaces. But the left-most 6 spaces have been removed to improve the +** readability. From this point on down, the normal indentation rules are +** restored. +*****************************************************************************/ + } + +#ifdef VDBE_PROFILE + { + u64 elapsed = sqlite3Hwtime() - start; + pOp->cycles += elapsed; + pOp->cnt++; +#if 0 + fprintf(stdout, "%10llu ", elapsed); + sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]); +#endif + } +#endif + + /* The following code adds nothing to the actual functionality + ** of the program. It is only here for testing and debugging. + ** On the other hand, it does burn CPU cycles every time through + ** the evaluator loop. So we can leave it out when NDEBUG is defined. + */ +#ifndef NDEBUG + assert( pc>=-1 && pcnOp ); + +#ifdef SQLITE_DEBUG + if( p->trace ){ + if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc); + if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){ + registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]); + } + if( pOp->opflags & OPFLG_OUT3 ){ + registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]); + } + } +#endif /* SQLITE_DEBUG */ +#endif /* NDEBUG */ + } /* The end of the for(;;) loop the loops through opcodes */ + + /* If we reach this point, it means that execution is finished with + ** an error of some kind. + */ +vdbe_error_halt: + assert( rc ); + p->rc = rc; + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(rc, "statement aborts at %d: [%s] %s", + pc, p->zSql, p->zErrMsg); + sqlite3VdbeHalt(p); + if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1; + rc = SQLITE_ERROR; + if( resetSchemaOnFault>0 ){ + sqlite3ResetOneSchema(db, resetSchemaOnFault-1); + } + + /* This is the only way out of this procedure. We have to + ** release the mutexes on btrees that were acquired at the + ** top. */ +vdbe_return: + db->lastRowid = lastRowid; + testcase( nVmStep>0 ); + p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep; + sqlite3VdbeLeave(p); + return rc; + + /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH + ** is encountered. + */ +too_big: + sqlite3SetString(&p->zErrMsg, db, "string or blob too big"); + rc = SQLITE_TOOBIG; + goto vdbe_error_halt; + + /* Jump to here if a malloc() fails. + */ +no_mem: + db->mallocFailed = 1; + sqlite3SetString(&p->zErrMsg, db, "out of memory"); + rc = SQLITE_NOMEM; + goto vdbe_error_halt; + + /* Jump to here for any other kind of fatal error. The "rc" variable + ** should hold the error number. + */ +abort_due_to_error: + assert( p->zErrMsg==0 ); + if( db->mallocFailed ) rc = SQLITE_NOMEM; + if( rc!=SQLITE_IOERR_NOMEM ){ + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc)); + } + goto vdbe_error_halt; + + /* Jump to here if the sqlite3_interrupt() API sets the interrupt + ** flag. + */ +abort_due_to_interrupt: + assert( db->u1.isInterrupted ); + rc = SQLITE_INTERRUPT; + p->rc = rc; + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc)); + goto vdbe_error_halt; +} + +/************** End of vdbe.c ************************************************/ +/************** Begin file vdbeblob.c ****************************************/ +/* +** 2007 May 1 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used to implement incremental BLOB I/O. +*/ + + +#ifndef SQLITE_OMIT_INCRBLOB + +/* +** Valid sqlite3_blob* handles point to Incrblob structures. +*/ +typedef struct Incrblob Incrblob; +struct Incrblob { + int flags; /* Copy of "flags" passed to sqlite3_blob_open() */ + int nByte; /* Size of open blob, in bytes */ + int iOffset; /* Byte offset of blob in cursor data */ + int iCol; /* Table column this handle is open on */ + BtCursor *pCsr; /* Cursor pointing at blob row */ + sqlite3_stmt *pStmt; /* Statement holding cursor open */ + sqlite3 *db; /* The associated database */ +}; + + +/* +** This function is used by both blob_open() and blob_reopen(). It seeks +** the b-tree cursor associated with blob handle p to point to row iRow. +** If successful, SQLITE_OK is returned and subsequent calls to +** sqlite3_blob_read() or sqlite3_blob_write() access the specified row. +** +** If an error occurs, or if the specified row does not exist or does not +** contain a value of type TEXT or BLOB in the column nominated when the +** blob handle was opened, then an error code is returned and *pzErr may +** be set to point to a buffer containing an error message. It is the +** responsibility of the caller to free the error message buffer using +** sqlite3DbFree(). +** +** If an error does occur, then the b-tree cursor is closed. All subsequent +** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will +** immediately return SQLITE_ABORT. +*/ +static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){ + int rc; /* Error code */ + char *zErr = 0; /* Error message */ + Vdbe *v = (Vdbe *)p->pStmt; + + /* Set the value of the SQL statements only variable to integer iRow. + ** This is done directly instead of using sqlite3_bind_int64() to avoid + ** triggering asserts related to mutexes. + */ + assert( v->aVar[0].flags&MEM_Int ); + v->aVar[0].u.i = iRow; + + rc = sqlite3_step(p->pStmt); + if( rc==SQLITE_ROW ){ + u32 type = v->apCsr[0]->aType[p->iCol]; + if( type<12 ){ + zErr = sqlite3MPrintf(p->db, "cannot open value of type %s", + type==0?"null": type==7?"real": "integer" + ); + rc = SQLITE_ERROR; + sqlite3_finalize(p->pStmt); + p->pStmt = 0; + }else{ + p->iOffset = v->apCsr[0]->aOffset[p->iCol]; + p->nByte = sqlite3VdbeSerialTypeLen(type); + p->pCsr = v->apCsr[0]->pCursor; + sqlite3BtreeEnterCursor(p->pCsr); + sqlite3BtreeCacheOverflow(p->pCsr); + sqlite3BtreeLeaveCursor(p->pCsr); + } + } + + if( rc==SQLITE_ROW ){ + rc = SQLITE_OK; + }else if( p->pStmt ){ + rc = sqlite3_finalize(p->pStmt); + p->pStmt = 0; + if( rc==SQLITE_OK ){ + zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow); + rc = SQLITE_ERROR; + }else{ + zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db)); + } + } + + assert( rc!=SQLITE_OK || zErr==0 ); + assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE ); + + *pzErr = zErr; + return rc; +} + +/* +** Open a blob handle. +*/ +SQLITE_API int sqlite3_blob_open( + sqlite3* db, /* The database connection */ + const char *zDb, /* The attached database containing the blob */ + const char *zTable, /* The table containing the blob */ + const char *zColumn, /* The column containing the blob */ + sqlite_int64 iRow, /* The row containing the glob */ + int flags, /* True -> read/write access, false -> read-only */ + sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */ +){ + int nAttempt = 0; + int iCol; /* Index of zColumn in row-record */ + + /* This VDBE program seeks a btree cursor to the identified + ** db/table/row entry. The reason for using a vdbe program instead + ** of writing code to use the b-tree layer directly is that the + ** vdbe program will take advantage of the various transaction, + ** locking and error handling infrastructure built into the vdbe. + ** + ** After seeking the cursor, the vdbe executes an OP_ResultRow. + ** Code external to the Vdbe then "borrows" the b-tree cursor and + ** uses it to implement the blob_read(), blob_write() and + ** blob_bytes() functions. + ** + ** The sqlite3_blob_close() function finalizes the vdbe program, + ** which closes the b-tree cursor and (possibly) commits the + ** transaction. + */ + static const VdbeOpList openBlob[] = { + {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */ + {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */ + {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */ + + /* One of the following two instructions is replaced by an OP_Noop. */ + {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */ + {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */ + + {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */ + {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */ + {OP_Column, 0, 0, 1}, /* 7 */ + {OP_ResultRow, 1, 0, 0}, /* 8 */ + {OP_Goto, 0, 5, 0}, /* 9 */ + {OP_Close, 0, 0, 0}, /* 10 */ + {OP_Halt, 0, 0, 0}, /* 11 */ + }; + + int rc = SQLITE_OK; + char *zErr = 0; + Table *pTab; + Parse *pParse = 0; + Incrblob *pBlob = 0; + + flags = !!flags; /* flags = (flags ? 1 : 0); */ + *ppBlob = 0; + + sqlite3_mutex_enter(db->mutex); + + pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob)); + if( !pBlob ) goto blob_open_out; + pParse = sqlite3StackAllocRaw(db, sizeof(*pParse)); + if( !pParse ) goto blob_open_out; + + do { + memset(pParse, 0, sizeof(Parse)); + pParse->db = db; + sqlite3DbFree(db, zErr); + zErr = 0; + + sqlite3BtreeEnterAll(db); + pTab = sqlite3LocateTable(pParse, 0, zTable, zDb); + if( pTab && IsVirtual(pTab) ){ + pTab = 0; + sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable); + } +#ifndef SQLITE_OMIT_VIEW + if( pTab && pTab->pSelect ){ + pTab = 0; + sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable); + } +#endif + if( !pTab ){ + if( pParse->zErrMsg ){ + sqlite3DbFree(db, zErr); + zErr = pParse->zErrMsg; + pParse->zErrMsg = 0; + } + rc = SQLITE_ERROR; + sqlite3BtreeLeaveAll(db); + goto blob_open_out; + } + + /* Now search pTab for the exact column. */ + for(iCol=0; iColnCol; iCol++) { + if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){ + break; + } + } + if( iCol==pTab->nCol ){ + sqlite3DbFree(db, zErr); + zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn); + rc = SQLITE_ERROR; + sqlite3BtreeLeaveAll(db); + goto blob_open_out; + } + + /* If the value is being opened for writing, check that the + ** column is not indexed, and that it is not part of a foreign key. + ** It is against the rules to open a column to which either of these + ** descriptions applies for writing. */ + if( flags ){ + const char *zFault = 0; + Index *pIdx; +#ifndef SQLITE_OMIT_FOREIGN_KEY + if( db->flags&SQLITE_ForeignKeys ){ + /* Check that the column is not part of an FK child key definition. It + ** is not necessary to check if it is part of a parent key, as parent + ** key columns must be indexed. The check below will pick up this + ** case. */ + FKey *pFKey; + for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ + int j; + for(j=0; jnCol; j++){ + if( pFKey->aCol[j].iFrom==iCol ){ + zFault = "foreign key"; + } + } + } + } +#endif + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + int j; + for(j=0; jnColumn; j++){ + if( pIdx->aiColumn[j]==iCol ){ + zFault = "indexed"; + } + } + } + if( zFault ){ + sqlite3DbFree(db, zErr); + zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault); + rc = SQLITE_ERROR; + sqlite3BtreeLeaveAll(db); + goto blob_open_out; + } + } + + pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db); + assert( pBlob->pStmt || db->mallocFailed ); + if( pBlob->pStmt ){ + Vdbe *v = (Vdbe *)pBlob->pStmt; + int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + + sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob); + + + /* Configure the OP_Transaction */ + sqlite3VdbeChangeP1(v, 0, iDb); + sqlite3VdbeChangeP2(v, 0, flags); + + /* Configure the OP_VerifyCookie */ + sqlite3VdbeChangeP1(v, 1, iDb); + sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie); + sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration); + + /* Make sure a mutex is held on the table to be accessed */ + sqlite3VdbeUsesBtree(v, iDb); + + /* Configure the OP_TableLock instruction */ +#ifdef SQLITE_OMIT_SHARED_CACHE + sqlite3VdbeChangeToNoop(v, 2); +#else + sqlite3VdbeChangeP1(v, 2, iDb); + sqlite3VdbeChangeP2(v, 2, pTab->tnum); + sqlite3VdbeChangeP3(v, 2, flags); + sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT); +#endif + + /* Remove either the OP_OpenWrite or OpenRead. Set the P2 + ** parameter of the other to pTab->tnum. */ + sqlite3VdbeChangeToNoop(v, 4 - flags); + sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum); + sqlite3VdbeChangeP3(v, 3 + flags, iDb); + + /* Configure the number of columns. Configure the cursor to + ** think that the table has one more column than it really + ** does. An OP_Column to retrieve this imaginary column will + ** always return an SQL NULL. This is useful because it means + ** we can invoke OP_Column to fill in the vdbe cursors type + ** and offset cache without causing any IO. + */ + sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32); + sqlite3VdbeChangeP2(v, 7, pTab->nCol); + if( !db->mallocFailed ){ + pParse->nVar = 1; + pParse->nMem = 1; + pParse->nTab = 1; + sqlite3VdbeMakeReady(v, pParse); + } + } + + pBlob->flags = flags; + pBlob->iCol = iCol; + pBlob->db = db; + sqlite3BtreeLeaveAll(db); + if( db->mallocFailed ){ + goto blob_open_out; + } + sqlite3_bind_int64(pBlob->pStmt, 1, iRow); + rc = blobSeekToRow(pBlob, iRow, &zErr); + } while( (++nAttempt)mallocFailed==0 ){ + *ppBlob = (sqlite3_blob *)pBlob; + }else{ + if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt); + sqlite3DbFree(db, pBlob); + } + sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr); + sqlite3DbFree(db, zErr); + sqlite3StackFree(db, pParse); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Close a blob handle that was previously created using +** sqlite3_blob_open(). +*/ +SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){ + Incrblob *p = (Incrblob *)pBlob; + int rc; + sqlite3 *db; + + if( p ){ + db = p->db; + sqlite3_mutex_enter(db->mutex); + rc = sqlite3_finalize(p->pStmt); + sqlite3DbFree(db, p); + sqlite3_mutex_leave(db->mutex); + }else{ + rc = SQLITE_OK; + } + return rc; +} + +/* +** Perform a read or write operation on a blob +*/ +static int blobReadWrite( + sqlite3_blob *pBlob, + void *z, + int n, + int iOffset, + int (*xCall)(BtCursor*, u32, u32, void*) +){ + int rc; + Incrblob *p = (Incrblob *)pBlob; + Vdbe *v; + sqlite3 *db; + + if( p==0 ) return SQLITE_MISUSE_BKPT; + db = p->db; + sqlite3_mutex_enter(db->mutex); + v = (Vdbe*)p->pStmt; + + if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){ + /* Request is out of range. Return a transient error. */ + rc = SQLITE_ERROR; + sqlite3Error(db, SQLITE_ERROR, 0); + }else if( v==0 ){ + /* If there is no statement handle, then the blob-handle has + ** already been invalidated. Return SQLITE_ABORT in this case. + */ + rc = SQLITE_ABORT; + }else{ + /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is + ** returned, clean-up the statement handle. + */ + assert( db == v->db ); + sqlite3BtreeEnterCursor(p->pCsr); + rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); + sqlite3BtreeLeaveCursor(p->pCsr); + if( rc==SQLITE_ABORT ){ + sqlite3VdbeFinalize(v); + p->pStmt = 0; + }else{ + db->errCode = rc; + v->rc = rc; + } + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Read data from a blob handle. +*/ +SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){ + return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData); +} + +/* +** Write data to a blob handle. +*/ +SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){ + return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData); +} + +/* +** Query a blob handle for the size of the data. +** +** The Incrblob.nByte field is fixed for the lifetime of the Incrblob +** so no mutex is required for access. +*/ +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){ + Incrblob *p = (Incrblob *)pBlob; + return (p && p->pStmt) ? p->nByte : 0; +} + +/* +** Move an existing blob handle to point to a different row of the same +** database table. +** +** If an error occurs, or if the specified row does not exist or does not +** contain a blob or text value, then an error code is returned and the +** database handle error code and message set. If this happens, then all +** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) +** immediately return SQLITE_ABORT. +*/ +SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){ + int rc; + Incrblob *p = (Incrblob *)pBlob; + sqlite3 *db; + + if( p==0 ) return SQLITE_MISUSE_BKPT; + db = p->db; + sqlite3_mutex_enter(db->mutex); + + if( p->pStmt==0 ){ + /* If there is no statement handle, then the blob-handle has + ** already been invalidated. Return SQLITE_ABORT in this case. + */ + rc = SQLITE_ABORT; + }else{ + char *zErr; + rc = blobSeekToRow(p, iRow, &zErr); + if( rc!=SQLITE_OK ){ + sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr); + sqlite3DbFree(db, zErr); + } + assert( rc!=SQLITE_SCHEMA ); + } + + rc = sqlite3ApiExit(db, rc); + assert( rc==SQLITE_OK || p->pStmt==0 ); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#endif /* #ifndef SQLITE_OMIT_INCRBLOB */ + +/************** End of vdbeblob.c ********************************************/ +/************** Begin file vdbesort.c ****************************************/ +/* +** 2011 July 9 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code for the VdbeSorter object, used in concert with +** a VdbeCursor to sort large numbers of keys (as may be required, for +** example, by CREATE INDEX statements on tables too large to fit in main +** memory). +*/ + + + +typedef struct VdbeSorterIter VdbeSorterIter; +typedef struct SorterRecord SorterRecord; +typedef struct FileWriter FileWriter; + +/* +** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES: +** +** As keys are added to the sorter, they are written to disk in a series +** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly +** the same as the cache-size allowed for temporary databases. In order +** to allow the caller to extract keys from the sorter in sorted order, +** all PMAs currently stored on disk must be merged together. This comment +** describes the data structure used to do so. The structure supports +** merging any number of arrays in a single pass with no redundant comparison +** operations. +** +** The aIter[] array contains an iterator for each of the PMAs being merged. +** An aIter[] iterator either points to a valid key or else is at EOF. For +** the purposes of the paragraphs below, we assume that the array is actually +** N elements in size, where N is the smallest power of 2 greater to or equal +** to the number of iterators being merged. The extra aIter[] elements are +** treated as if they are empty (always at EOF). +** +** The aTree[] array is also N elements in size. The value of N is stored in +** the VdbeSorter.nTree variable. +** +** The final (N/2) elements of aTree[] contain the results of comparing +** pairs of iterator keys together. Element i contains the result of +** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the +** aTree element is set to the index of it. +** +** For the purposes of this comparison, EOF is considered greater than any +** other key value. If the keys are equal (only possible with two EOF +** values), it doesn't matter which index is stored. +** +** The (N/4) elements of aTree[] that precede the final (N/2) described +** above contains the index of the smallest of each block of 4 iterators. +** And so on. So that aTree[1] contains the index of the iterator that +** currently points to the smallest key value. aTree[0] is unused. +** +** Example: +** +** aIter[0] -> Banana +** aIter[1] -> Feijoa +** aIter[2] -> Elderberry +** aIter[3] -> Currant +** aIter[4] -> Grapefruit +** aIter[5] -> Apple +** aIter[6] -> Durian +** aIter[7] -> EOF +** +** aTree[] = { X, 5 0, 5 0, 3, 5, 6 } +** +** The current element is "Apple" (the value of the key indicated by +** iterator 5). When the Next() operation is invoked, iterator 5 will +** be advanced to the next key in its segment. Say the next key is +** "Eggplant": +** +** aIter[5] -> Eggplant +** +** The contents of aTree[] are updated first by comparing the new iterator +** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator +** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree. +** The value of iterator 6 - "Durian" - is now smaller than that of iterator +** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (BananaaAlloc); + sqlite3DbFree(db, pIter->aBuffer); + memset(pIter, 0, sizeof(VdbeSorterIter)); +} + +/* +** Read nByte bytes of data from the stream of data iterated by object p. +** If successful, set *ppOut to point to a buffer containing the data +** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite +** error code. +** +** The buffer indicated by *ppOut may only be considered valid until the +** next call to this function. +*/ +static int vdbeSorterIterRead( + sqlite3 *db, /* Database handle (for malloc) */ + VdbeSorterIter *p, /* Iterator */ + int nByte, /* Bytes of data to read */ + u8 **ppOut /* OUT: Pointer to buffer containing data */ +){ + int iBuf; /* Offset within buffer to read from */ + int nAvail; /* Bytes of data available in buffer */ + assert( p->aBuffer ); + + /* If there is no more data to be read from the buffer, read the next + ** p->nBuffer bytes of data from the file into it. Or, if there are less + ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */ + iBuf = p->iReadOff % p->nBuffer; + if( iBuf==0 ){ + int nRead; /* Bytes to read from disk */ + int rc; /* sqlite3OsRead() return code */ + + /* Determine how many bytes of data to read. */ + if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){ + nRead = p->nBuffer; + }else{ + nRead = (int)(p->iEof - p->iReadOff); + } + assert( nRead>0 ); + + /* Read data from the file. Return early if an error occurs. */ + rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff); + assert( rc!=SQLITE_IOERR_SHORT_READ ); + if( rc!=SQLITE_OK ) return rc; + } + nAvail = p->nBuffer - iBuf; + + if( nByte<=nAvail ){ + /* The requested data is available in the in-memory buffer. In this + ** case there is no need to make a copy of the data, just return a + ** pointer into the buffer to the caller. */ + *ppOut = &p->aBuffer[iBuf]; + p->iReadOff += nByte; + }else{ + /* The requested data is not all available in the in-memory buffer. + ** In this case, allocate space at p->aAlloc[] to copy the requested + ** range into. Then return a copy of pointer p->aAlloc to the caller. */ + int nRem; /* Bytes remaining to copy */ + + /* Extend the p->aAlloc[] allocation if required. */ + if( p->nAllocnAlloc*2; + while( nByte>nNew ) nNew = nNew*2; + p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew); + if( !p->aAlloc ) return SQLITE_NOMEM; + p->nAlloc = nNew; + } + + /* Copy as much data as is available in the buffer into the start of + ** p->aAlloc[]. */ + memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail); + p->iReadOff += nAvail; + nRem = nByte - nAvail; + + /* The following loop copies up to p->nBuffer bytes per iteration into + ** the p->aAlloc[] buffer. */ + while( nRem>0 ){ + int rc; /* vdbeSorterIterRead() return code */ + int nCopy; /* Number of bytes to copy */ + u8 *aNext; /* Pointer to buffer to copy data from */ + + nCopy = nRem; + if( nRem>p->nBuffer ) nCopy = p->nBuffer; + rc = vdbeSorterIterRead(db, p, nCopy, &aNext); + if( rc!=SQLITE_OK ) return rc; + assert( aNext!=p->aAlloc ); + memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy); + nRem -= nCopy; + } + + *ppOut = p->aAlloc; + } + + return SQLITE_OK; +} + +/* +** Read a varint from the stream of data accessed by p. Set *pnOut to +** the value read. +*/ +static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){ + int iBuf; + + iBuf = p->iReadOff % p->nBuffer; + if( iBuf && (p->nBuffer-iBuf)>=9 ){ + p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut); + }else{ + u8 aVarint[16], *a; + int i = 0, rc; + do{ + rc = vdbeSorterIterRead(db, p, 1, &a); + if( rc ) return rc; + aVarint[(i++)&0xf] = a[0]; + }while( (a[0]&0x80)!=0 ); + sqlite3GetVarint(aVarint, pnOut); + } + + return SQLITE_OK; +} + + +/* +** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if +** no error occurs, or an SQLite error code if one does. +*/ +static int vdbeSorterIterNext( + sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */ + VdbeSorterIter *pIter /* Iterator to advance */ +){ + int rc; /* Return Code */ + u64 nRec = 0; /* Size of record in bytes */ + + if( pIter->iReadOff>=pIter->iEof ){ + /* This is an EOF condition */ + vdbeSorterIterZero(db, pIter); + return SQLITE_OK; + } + + rc = vdbeSorterIterVarint(db, pIter, &nRec); + if( rc==SQLITE_OK ){ + pIter->nKey = (int)nRec; + rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey); + } + + return rc; +} + +/* +** Initialize iterator pIter to scan through the PMA stored in file pFile +** starting at offset iStart and ending at offset iEof-1. This function +** leaves the iterator pointing to the first key in the PMA (or EOF if the +** PMA is empty). +*/ +static int vdbeSorterIterInit( + sqlite3 *db, /* Database handle */ + const VdbeSorter *pSorter, /* Sorter object */ + i64 iStart, /* Start offset in pFile */ + VdbeSorterIter *pIter, /* Iterator to populate */ + i64 *pnByte /* IN/OUT: Increment this value by PMA size */ +){ + int rc = SQLITE_OK; + int nBuf; + + nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt); + + assert( pSorter->iWriteOff>iStart ); + assert( pIter->aAlloc==0 ); + assert( pIter->aBuffer==0 ); + pIter->pFile = pSorter->pTemp1; + pIter->iReadOff = iStart; + pIter->nAlloc = 128; + pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc); + pIter->nBuffer = nBuf; + pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf); + + if( !pIter->aBuffer ){ + rc = SQLITE_NOMEM; + }else{ + int iBuf; + + iBuf = iStart % nBuf; + if( iBuf ){ + int nRead = nBuf - iBuf; + if( (iStart + nRead) > pSorter->iWriteOff ){ + nRead = (int)(pSorter->iWriteOff - iStart); + } + rc = sqlite3OsRead( + pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart + ); + assert( rc!=SQLITE_IOERR_SHORT_READ ); + } + + if( rc==SQLITE_OK ){ + u64 nByte; /* Size of PMA in bytes */ + pIter->iEof = pSorter->iWriteOff; + rc = vdbeSorterIterVarint(db, pIter, &nByte); + pIter->iEof = pIter->iReadOff + nByte; + *pnByte += nByte; + } + } + + if( rc==SQLITE_OK ){ + rc = vdbeSorterIterNext(db, pIter); + } + return rc; +} + + +/* +** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, +** size nKey2 bytes). Argument pKeyInfo supplies the collation functions +** used by the comparison. If an error occurs, return an SQLite error code. +** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive +** value, depending on whether key1 is smaller, equal to or larger than key2. +** +** If the bOmitRowid argument is non-zero, assume both keys end in a rowid +** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid +** is true and key1 contains even a single NULL value, it is considered to +** be less than key2. Even if key2 also contains NULL values. +** +** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace +** has been allocated and contains an unpacked record that is used as key2. +*/ +static void vdbeSorterCompare( + const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */ + int bOmitRowid, /* Ignore rowid field at end of keys */ + const void *pKey1, int nKey1, /* Left side of comparison */ + const void *pKey2, int nKey2, /* Right side of comparison */ + int *pRes /* OUT: Result of comparison */ +){ + KeyInfo *pKeyInfo = pCsr->pKeyInfo; + VdbeSorter *pSorter = pCsr->pSorter; + UnpackedRecord *r2 = pSorter->pUnpacked; + int i; + + if( pKey2 ){ + sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2); + } + + if( bOmitRowid ){ + r2->nField = pKeyInfo->nField; + assert( r2->nField>0 ); + for(i=0; inField; i++){ + if( r2->aMem[i].flags & MEM_Null ){ + *pRes = -1; + return; + } + } + r2->flags |= UNPACKED_PREFIX_MATCH; + } + + *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2); +} + +/* +** This function is called to compare two iterator keys when merging +** multiple b-tree segments. Parameter iOut is the index of the aTree[] +** value to recalculate. +*/ +static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){ + VdbeSorter *pSorter = pCsr->pSorter; + int i1; + int i2; + int iRes; + VdbeSorterIter *p1; + VdbeSorterIter *p2; + + assert( iOutnTree && iOut>0 ); + + if( iOut>=(pSorter->nTree/2) ){ + i1 = (iOut - pSorter->nTree/2) * 2; + i2 = i1 + 1; + }else{ + i1 = pSorter->aTree[iOut*2]; + i2 = pSorter->aTree[iOut*2+1]; + } + + p1 = &pSorter->aIter[i1]; + p2 = &pSorter->aIter[i2]; + + if( p1->pFile==0 ){ + iRes = i2; + }else if( p2->pFile==0 ){ + iRes = i1; + }else{ + int res; + assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */ + vdbeSorterCompare( + pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res + ); + if( res<=0 ){ + iRes = i1; + }else{ + iRes = i2; + } + } + + pSorter->aTree[iOut] = iRes; + return SQLITE_OK; +} + +/* +** Initialize the temporary index cursor just opened as a sorter cursor. +*/ +SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){ + int pgsz; /* Page size of main database */ + int mxCache; /* Cache size */ + VdbeSorter *pSorter; /* The new sorter */ + char *d; /* Dummy */ + + assert( pCsr->pKeyInfo && pCsr->pBt==0 ); + pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter)); + if( pSorter==0 ){ + return SQLITE_NOMEM; + } + + pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d); + if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM; + assert( pSorter->pUnpacked==(UnpackedRecord *)d ); + + if( !sqlite3TempInMemory(db) ){ + pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt); + pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz; + mxCache = db->aDb[0].pSchema->cache_size; + if( mxCachemxPmaSize = mxCache * pgsz; + } + + return SQLITE_OK; +} + +/* +** Free the list of sorted records starting at pRecord. +*/ +static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){ + SorterRecord *p; + SorterRecord *pNext; + for(p=pRecord; p; p=pNext){ + pNext = p->pNext; + sqlite3DbFree(db, p); + } +} + +/* +** Free any cursor components allocated by sqlite3VdbeSorterXXX routines. +*/ +SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){ + VdbeSorter *pSorter = pCsr->pSorter; + if( pSorter ){ + if( pSorter->aIter ){ + int i; + for(i=0; inTree; i++){ + vdbeSorterIterZero(db, &pSorter->aIter[i]); + } + sqlite3DbFree(db, pSorter->aIter); + } + if( pSorter->pTemp1 ){ + sqlite3OsCloseFree(pSorter->pTemp1); + } + vdbeSorterRecordFree(db, pSorter->pRecord); + sqlite3DbFree(db, pSorter->pUnpacked); + sqlite3DbFree(db, pSorter); + pCsr->pSorter = 0; + } +} + +/* +** Allocate space for a file-handle and open a temporary file. If successful, +** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK. +** Otherwise, set *ppFile to 0 and return an SQLite error code. +*/ +static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){ + int dummy; + return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile, + SQLITE_OPEN_TEMP_JOURNAL | + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy + ); +} + +/* +** Merge the two sorted lists p1 and p2 into a single list. +** Set *ppOut to the head of the new list. +*/ +static void vdbeSorterMerge( + const VdbeCursor *pCsr, /* For pKeyInfo */ + SorterRecord *p1, /* First list to merge */ + SorterRecord *p2, /* Second list to merge */ + SorterRecord **ppOut /* OUT: Head of merged list */ +){ + SorterRecord *pFinal = 0; + SorterRecord **pp = &pFinal; + void *pVal2 = p2 ? p2->pVal : 0; + + while( p1 && p2 ){ + int res; + vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res); + if( res<=0 ){ + *pp = p1; + pp = &p1->pNext; + p1 = p1->pNext; + pVal2 = 0; + }else{ + *pp = p2; + pp = &p2->pNext; + p2 = p2->pNext; + if( p2==0 ) break; + pVal2 = p2->pVal; + } + } + *pp = p1 ? p1 : p2; + *ppOut = pFinal; +} + +/* +** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK +** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error +** occurs. +*/ +static int vdbeSorterSort(const VdbeCursor *pCsr){ + int i; + SorterRecord **aSlot; + SorterRecord *p; + VdbeSorter *pSorter = pCsr->pSorter; + + aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *)); + if( !aSlot ){ + return SQLITE_NOMEM; + } + + p = pSorter->pRecord; + while( p ){ + SorterRecord *pNext = p->pNext; + p->pNext = 0; + for(i=0; aSlot[i]; i++){ + vdbeSorterMerge(pCsr, p, aSlot[i], &p); + aSlot[i] = 0; + } + aSlot[i] = p; + p = pNext; + } + + p = 0; + for(i=0; i<64; i++){ + vdbeSorterMerge(pCsr, p, aSlot[i], &p); + } + pSorter->pRecord = p; + + sqlite3_free(aSlot); + return SQLITE_OK; +} + +/* +** Initialize a file-writer object. +*/ +static void fileWriterInit( + sqlite3 *db, /* Database (for malloc) */ + sqlite3_file *pFile, /* File to write to */ + FileWriter *p, /* Object to populate */ + i64 iStart /* Offset of pFile to begin writing at */ +){ + int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt); + + memset(p, 0, sizeof(FileWriter)); + p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf); + if( !p->aBuffer ){ + p->eFWErr = SQLITE_NOMEM; + }else{ + p->iBufEnd = p->iBufStart = (iStart % nBuf); + p->iWriteOff = iStart - p->iBufStart; + p->nBuffer = nBuf; + p->pFile = pFile; + } +} + +/* +** Write nData bytes of data to the file-write object. Return SQLITE_OK +** if successful, or an SQLite error code if an error occurs. +*/ +static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){ + int nRem = nData; + while( nRem>0 && p->eFWErr==0 ){ + int nCopy = nRem; + if( nCopy>(p->nBuffer - p->iBufEnd) ){ + nCopy = p->nBuffer - p->iBufEnd; + } + + memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy); + p->iBufEnd += nCopy; + if( p->iBufEnd==p->nBuffer ){ + p->eFWErr = sqlite3OsWrite(p->pFile, + &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, + p->iWriteOff + p->iBufStart + ); + p->iBufStart = p->iBufEnd = 0; + p->iWriteOff += p->nBuffer; + } + assert( p->iBufEndnBuffer ); + + nRem -= nCopy; + } +} + +/* +** Flush any buffered data to disk and clean up the file-writer object. +** The results of using the file-writer after this call are undefined. +** Return SQLITE_OK if flushing the buffered data succeeds or is not +** required. Otherwise, return an SQLite error code. +** +** Before returning, set *piEof to the offset immediately following the +** last byte written to the file. +*/ +static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){ + int rc; + if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){ + p->eFWErr = sqlite3OsWrite(p->pFile, + &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, + p->iWriteOff + p->iBufStart + ); + } + *piEof = (p->iWriteOff + p->iBufEnd); + sqlite3DbFree(db, p->aBuffer); + rc = p->eFWErr; + memset(p, 0, sizeof(FileWriter)); + return rc; +} + +/* +** Write value iVal encoded as a varint to the file-write object. Return +** SQLITE_OK if successful, or an SQLite error code if an error occurs. +*/ +static void fileWriterWriteVarint(FileWriter *p, u64 iVal){ + int nByte; + u8 aByte[10]; + nByte = sqlite3PutVarint(aByte, iVal); + fileWriterWrite(p, aByte, nByte); +} + +/* +** Write the current contents of the in-memory linked-list to a PMA. Return +** SQLITE_OK if successful, or an SQLite error code otherwise. +** +** The format of a PMA is: +** +** * A varint. This varint contains the total number of bytes of content +** in the PMA (not including the varint itself). +** +** * One or more records packed end-to-end in order of ascending keys. +** Each record consists of a varint followed by a blob of data (the +** key). The varint is the number of bytes in the blob of data. +*/ +static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){ + int rc = SQLITE_OK; /* Return code */ + VdbeSorter *pSorter = pCsr->pSorter; + FileWriter writer; + + memset(&writer, 0, sizeof(FileWriter)); + + if( pSorter->nInMemory==0 ){ + assert( pSorter->pRecord==0 ); + return rc; + } + + rc = vdbeSorterSort(pCsr); + + /* If the first temporary PMA file has not been opened, open it now. */ + if( rc==SQLITE_OK && pSorter->pTemp1==0 ){ + rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1); + assert( rc!=SQLITE_OK || pSorter->pTemp1 ); + assert( pSorter->iWriteOff==0 ); + assert( pSorter->nPMA==0 ); + } + + if( rc==SQLITE_OK ){ + SorterRecord *p; + SorterRecord *pNext = 0; + + fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff); + pSorter->nPMA++; + fileWriterWriteVarint(&writer, pSorter->nInMemory); + for(p=pSorter->pRecord; p; p=pNext){ + pNext = p->pNext; + fileWriterWriteVarint(&writer, p->nVal); + fileWriterWrite(&writer, p->pVal, p->nVal); + sqlite3DbFree(db, p); + } + pSorter->pRecord = p; + rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff); + } + + return rc; +} + +/* +** Add a record to the sorter. +*/ +SQLITE_PRIVATE int sqlite3VdbeSorterWrite( + sqlite3 *db, /* Database handle */ + const VdbeCursor *pCsr, /* Sorter cursor */ + Mem *pVal /* Memory cell containing record */ +){ + VdbeSorter *pSorter = pCsr->pSorter; + int rc = SQLITE_OK; /* Return Code */ + SorterRecord *pNew; /* New list element */ + + assert( pSorter ); + pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n; + + pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord)); + if( pNew==0 ){ + rc = SQLITE_NOMEM; + }else{ + pNew->pVal = (void *)&pNew[1]; + memcpy(pNew->pVal, pVal->z, pVal->n); + pNew->nVal = pVal->n; + pNew->pNext = pSorter->pRecord; + pSorter->pRecord = pNew; + } + + /* See if the contents of the sorter should now be written out. They + ** are written out when either of the following are true: + ** + ** * The total memory allocated for the in-memory list is greater + ** than (page-size * cache-size), or + ** + ** * The total memory allocated for the in-memory list is greater + ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true. + */ + if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && ( + (pSorter->nInMemory>pSorter->mxPmaSize) + || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull()) + )){ +#ifdef SQLITE_DEBUG + i64 nExpect = pSorter->iWriteOff + + sqlite3VarintLen(pSorter->nInMemory) + + pSorter->nInMemory; +#endif + rc = vdbeSorterListToPMA(db, pCsr); + pSorter->nInMemory = 0; + assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) ); + } + + return rc; +} + +/* +** Helper function for sqlite3VdbeSorterRewind(). +*/ +static int vdbeSorterInitMerge( + sqlite3 *db, /* Database handle */ + const VdbeCursor *pCsr, /* Cursor handle for this sorter */ + i64 *pnByte /* Sum of bytes in all opened PMAs */ +){ + VdbeSorter *pSorter = pCsr->pSorter; + int rc = SQLITE_OK; /* Return code */ + int i; /* Used to iterator through aIter[] */ + i64 nByte = 0; /* Total bytes in all opened PMAs */ + + /* Initialize the iterators. */ + for(i=0; iaIter[i]; + rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte); + pSorter->iReadOff = pIter->iEof; + assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff ); + if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break; + } + + /* Initialize the aTree[] array. */ + for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){ + rc = vdbeSorterDoCompare(pCsr, i); + } + + *pnByte = nByte; + return rc; +} + +/* +** Once the sorter has been populated, this function is called to prepare +** for iterating through its contents in sorted order. +*/ +SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){ + VdbeSorter *pSorter = pCsr->pSorter; + int rc; /* Return code */ + sqlite3_file *pTemp2 = 0; /* Second temp file to use */ + i64 iWrite2 = 0; /* Write offset for pTemp2 */ + int nIter; /* Number of iterators used */ + int nByte; /* Bytes of space required for aIter/aTree */ + int N = 2; /* Power of 2 >= nIter */ + + assert( pSorter ); + + /* If no data has been written to disk, then do not do so now. Instead, + ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly + ** from the in-memory list. */ + if( pSorter->nPMA==0 ){ + *pbEof = !pSorter->pRecord; + assert( pSorter->aTree==0 ); + return vdbeSorterSort(pCsr); + } + + /* Write the current in-memory list to a PMA. */ + rc = vdbeSorterListToPMA(db, pCsr); + if( rc!=SQLITE_OK ) return rc; + + /* Allocate space for aIter[] and aTree[]. */ + nIter = pSorter->nPMA; + if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT; + assert( nIter>0 ); + while( NaIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte); + if( !pSorter->aIter ) return SQLITE_NOMEM; + pSorter->aTree = (int *)&pSorter->aIter[N]; + pSorter->nTree = N; + + do { + int iNew; /* Index of new, merged, PMA */ + + for(iNew=0; + rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNTnPMA; + iNew++ + ){ + int rc2; /* Return code from fileWriterFinish() */ + FileWriter writer; /* Object used to write to disk */ + i64 nWrite; /* Number of bytes in new PMA */ + + memset(&writer, 0, sizeof(FileWriter)); + + /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1, + ** initialize an iterator for each of them and break out of the loop. + ** These iterators will be incrementally merged as the VDBE layer calls + ** sqlite3VdbeSorterNext(). + ** + ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs, + ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs + ** are merged into a single PMA that is written to file pTemp2. + */ + rc = vdbeSorterInitMerge(db, pCsr, &nWrite); + assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile ); + if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){ + break; + } + + /* Open the second temp file, if it is not already open. */ + if( pTemp2==0 ){ + assert( iWrite2==0 ); + rc = vdbeSorterOpenTempFile(db, &pTemp2); + } + + if( rc==SQLITE_OK ){ + int bEof = 0; + fileWriterInit(db, pTemp2, &writer, iWrite2); + fileWriterWriteVarint(&writer, nWrite); + while( rc==SQLITE_OK && bEof==0 ){ + VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ]; + assert( pIter->pFile ); + + fileWriterWriteVarint(&writer, pIter->nKey); + fileWriterWrite(&writer, pIter->aKey, pIter->nKey); + rc = sqlite3VdbeSorterNext(db, pCsr, &bEof); + } + rc2 = fileWriterFinish(db, &writer, &iWrite2); + if( rc==SQLITE_OK ) rc = rc2; + } + } + + if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){ + break; + }else{ + sqlite3_file *pTmp = pSorter->pTemp1; + pSorter->nPMA = iNew; + pSorter->pTemp1 = pTemp2; + pTemp2 = pTmp; + pSorter->iWriteOff = iWrite2; + pSorter->iReadOff = 0; + iWrite2 = 0; + } + }while( rc==SQLITE_OK ); + + if( pTemp2 ){ + sqlite3OsCloseFree(pTemp2); + } + *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0); + return rc; +} + +/* +** Advance to the next element in the sorter. +*/ +SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){ + VdbeSorter *pSorter = pCsr->pSorter; + int rc; /* Return code */ + + if( pSorter->aTree ){ + int iPrev = pSorter->aTree[1];/* Index of iterator to advance */ + int i; /* Index of aTree[] to recalculate */ + + rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]); + for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){ + rc = vdbeSorterDoCompare(pCsr, i); + } + + *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0); + }else{ + SorterRecord *pFree = pSorter->pRecord; + pSorter->pRecord = pFree->pNext; + pFree->pNext = 0; + vdbeSorterRecordFree(db, pFree); + *pbEof = !pSorter->pRecord; + rc = SQLITE_OK; + } + return rc; +} + +/* +** Return a pointer to a buffer owned by the sorter that contains the +** current key. +*/ +static void *vdbeSorterRowkey( + const VdbeSorter *pSorter, /* Sorter object */ + int *pnKey /* OUT: Size of current key in bytes */ +){ + void *pKey; + if( pSorter->aTree ){ + VdbeSorterIter *pIter; + pIter = &pSorter->aIter[ pSorter->aTree[1] ]; + *pnKey = pIter->nKey; + pKey = pIter->aKey; + }else{ + *pnKey = pSorter->pRecord->nVal; + pKey = pSorter->pRecord->pVal; + } + return pKey; +} + +/* +** Copy the current sorter key into the memory cell pOut. +*/ +SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ + VdbeSorter *pSorter = pCsr->pSorter; + void *pKey; int nKey; /* Sorter key to copy into pOut */ + + pKey = vdbeSorterRowkey(pSorter, &nKey); + if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){ + return SQLITE_NOMEM; + } + pOut->n = nKey; + MemSetTypeFlag(pOut, MEM_Blob); + memcpy(pOut->z, pKey, nKey); + + return SQLITE_OK; +} + +/* +** Compare the key in memory cell pVal with the key that the sorter cursor +** passed as the first argument currently points to. For the purposes of +** the comparison, ignore the rowid field at the end of each record. +** +** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM). +** Otherwise, set *pRes to a negative, zero or positive value if the +** key in pVal is smaller than, equal to or larger than the current sorter +** key. +*/ +SQLITE_PRIVATE int sqlite3VdbeSorterCompare( + const VdbeCursor *pCsr, /* Sorter cursor */ + Mem *pVal, /* Value to compare to current sorter key */ + int *pRes /* OUT: Result of comparison */ +){ + VdbeSorter *pSorter = pCsr->pSorter; + void *pKey; int nKey; /* Sorter key to compare pVal with */ + + pKey = vdbeSorterRowkey(pSorter, &nKey); + vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes); + return SQLITE_OK; +} + +/************** End of vdbesort.c ********************************************/ +/************** Begin file journal.c *****************************************/ +/* +** 2007 August 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements a special kind of sqlite3_file object used +** by SQLite to create journal files if the atomic-write optimization +** is enabled. +** +** The distinctive characteristic of this sqlite3_file is that the +** actual on disk file is created lazily. When the file is created, +** the caller specifies a buffer size for an in-memory buffer to +** be used to service read() and write() requests. The actual file +** on disk is not created or populated until either: +** +** 1) The in-memory representation grows too large for the allocated +** buffer, or +** 2) The sqlite3JournalCreate() function is called. +*/ +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + + +/* +** A JournalFile object is a subclass of sqlite3_file used by +** as an open file handle for journal files. +*/ +struct JournalFile { + sqlite3_io_methods *pMethod; /* I/O methods on journal files */ + int nBuf; /* Size of zBuf[] in bytes */ + char *zBuf; /* Space to buffer journal writes */ + int iSize; /* Amount of zBuf[] currently used */ + int flags; /* xOpen flags */ + sqlite3_vfs *pVfs; /* The "real" underlying VFS */ + sqlite3_file *pReal; /* The "real" underlying file descriptor */ + const char *zJournal; /* Name of the journal file */ +}; +typedef struct JournalFile JournalFile; + +/* +** If it does not already exists, create and populate the on-disk file +** for JournalFile p. +*/ +static int createFile(JournalFile *p){ + int rc = SQLITE_OK; + if( !p->pReal ){ + sqlite3_file *pReal = (sqlite3_file *)&p[1]; + rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0); + if( rc==SQLITE_OK ){ + p->pReal = pReal; + if( p->iSize>0 ){ + assert(p->iSize<=p->nBuf); + rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0); + } + if( rc!=SQLITE_OK ){ + /* If an error occurred while writing to the file, close it before + ** returning. This way, SQLite uses the in-memory journal data to + ** roll back changes made to the internal page-cache before this + ** function was called. */ + sqlite3OsClose(pReal); + p->pReal = 0; + } + } + } + return rc; +} + +/* +** Close the file. +*/ +static int jrnlClose(sqlite3_file *pJfd){ + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + sqlite3OsClose(p->pReal); + } + sqlite3_free(p->zBuf); + return SQLITE_OK; +} + +/* +** Read data from the file. +*/ +static int jrnlRead( + sqlite3_file *pJfd, /* The journal file from which to read */ + void *zBuf, /* Put the results here */ + int iAmt, /* Number of bytes to read */ + sqlite_int64 iOfst /* Begin reading at this offset */ +){ + int rc = SQLITE_OK; + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst); + }else if( (iAmt+iOfst)>p->iSize ){ + rc = SQLITE_IOERR_SHORT_READ; + }else{ + memcpy(zBuf, &p->zBuf[iOfst], iAmt); + } + return rc; +} + +/* +** Write data to the file. +*/ +static int jrnlWrite( + sqlite3_file *pJfd, /* The journal file into which to write */ + const void *zBuf, /* Take data to be written from here */ + int iAmt, /* Number of bytes to write */ + sqlite_int64 iOfst /* Begin writing at this offset into the file */ +){ + int rc = SQLITE_OK; + JournalFile *p = (JournalFile *)pJfd; + if( !p->pReal && (iOfst+iAmt)>p->nBuf ){ + rc = createFile(p); + } + if( rc==SQLITE_OK ){ + if( p->pReal ){ + rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst); + }else{ + memcpy(&p->zBuf[iOfst], zBuf, iAmt); + if( p->iSize<(iOfst+iAmt) ){ + p->iSize = (iOfst+iAmt); + } + } + } + return rc; +} + +/* +** Truncate the file. +*/ +static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){ + int rc = SQLITE_OK; + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + rc = sqlite3OsTruncate(p->pReal, size); + }else if( sizeiSize ){ + p->iSize = size; + } + return rc; +} + +/* +** Sync the file. +*/ +static int jrnlSync(sqlite3_file *pJfd, int flags){ + int rc; + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + rc = sqlite3OsSync(p->pReal, flags); + }else{ + rc = SQLITE_OK; + } + return rc; +} + +/* +** Query the size of the file in bytes. +*/ +static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){ + int rc = SQLITE_OK; + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + rc = sqlite3OsFileSize(p->pReal, pSize); + }else{ + *pSize = (sqlite_int64) p->iSize; + } + return rc; +} + +/* +** Table of methods for JournalFile sqlite3_file object. +*/ +static struct sqlite3_io_methods JournalFileMethods = { + 1, /* iVersion */ + jrnlClose, /* xClose */ + jrnlRead, /* xRead */ + jrnlWrite, /* xWrite */ + jrnlTruncate, /* xTruncate */ + jrnlSync, /* xSync */ + jrnlFileSize, /* xFileSize */ + 0, /* xLock */ + 0, /* xUnlock */ + 0, /* xCheckReservedLock */ + 0, /* xFileControl */ + 0, /* xSectorSize */ + 0, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0 /* xShmUnmap */ +}; + +/* +** Open a journal file. +*/ +SQLITE_PRIVATE int sqlite3JournalOpen( + sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */ + const char *zName, /* Name of the journal file */ + sqlite3_file *pJfd, /* Preallocated, blank file handle */ + int flags, /* Opening flags */ + int nBuf /* Bytes buffered before opening the file */ +){ + JournalFile *p = (JournalFile *)pJfd; + memset(p, 0, sqlite3JournalSize(pVfs)); + if( nBuf>0 ){ + p->zBuf = sqlite3MallocZero(nBuf); + if( !p->zBuf ){ + return SQLITE_NOMEM; + } + }else{ + return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0); + } + p->pMethod = &JournalFileMethods; + p->nBuf = nBuf; + p->flags = flags; + p->zJournal = zName; + p->pVfs = pVfs; + return SQLITE_OK; +} + +/* +** If the argument p points to a JournalFile structure, and the underlying +** file has not yet been created, create it now. +*/ +SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){ + if( p->pMethods!=&JournalFileMethods ){ + return SQLITE_OK; + } + return createFile((JournalFile *)p); +} + +/* +** The file-handle passed as the only argument is guaranteed to be an open +** file. It may or may not be of class JournalFile. If the file is a +** JournalFile, and the underlying file on disk has not yet been opened, +** return 0. Otherwise, return 1. +*/ +SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){ + return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0); +} + +/* +** Return the number of bytes required to store a JournalFile that uses vfs +** pVfs to create the underlying on-disk files. +*/ +SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){ + return (pVfs->szOsFile+sizeof(JournalFile)); +} +#endif + +/************** End of journal.c *********************************************/ +/************** Begin file memjournal.c **************************************/ +/* +** 2008 October 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code use to implement an in-memory rollback journal. +** The in-memory rollback journal is used to journal transactions for +** ":memory:" databases and when the journal_mode=MEMORY pragma is used. +*/ + +/* Forward references to internal structures */ +typedef struct MemJournal MemJournal; +typedef struct FilePoint FilePoint; +typedef struct FileChunk FileChunk; + +/* Space to hold the rollback journal is allocated in increments of +** this many bytes. +** +** The size chosen is a little less than a power of two. That way, +** the FileChunk object will have a size that almost exactly fills +** a power-of-two allocation. This mimimizes wasted space in power-of-two +** memory allocators. +*/ +#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*))) + +/* +** The rollback journal is composed of a linked list of these structures. +*/ +struct FileChunk { + FileChunk *pNext; /* Next chunk in the journal */ + u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */ +}; + +/* +** An instance of this object serves as a cursor into the rollback journal. +** The cursor can be either for reading or writing. +*/ +struct FilePoint { + sqlite3_int64 iOffset; /* Offset from the beginning of the file */ + FileChunk *pChunk; /* Specific chunk into which cursor points */ +}; + +/* +** This subclass is a subclass of sqlite3_file. Each open memory-journal +** is an instance of this class. +*/ +struct MemJournal { + sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */ + FileChunk *pFirst; /* Head of in-memory chunk-list */ + FilePoint endpoint; /* Pointer to the end of the file */ + FilePoint readpoint; /* Pointer to the end of the last xRead() */ +}; + +/* +** Read data from the in-memory journal file. This is the implementation +** of the sqlite3_vfs.xRead method. +*/ +static int memjrnlRead( + sqlite3_file *pJfd, /* The journal file from which to read */ + void *zBuf, /* Put the results here */ + int iAmt, /* Number of bytes to read */ + sqlite_int64 iOfst /* Begin reading at this offset */ +){ + MemJournal *p = (MemJournal *)pJfd; + u8 *zOut = zBuf; + int nRead = iAmt; + int iChunkOffset; + FileChunk *pChunk; + + /* SQLite never tries to read past the end of a rollback journal file */ + assert( iOfst+iAmt<=p->endpoint.iOffset ); + + if( p->readpoint.iOffset!=iOfst || iOfst==0 ){ + sqlite3_int64 iOff = 0; + for(pChunk=p->pFirst; + ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst; + pChunk=pChunk->pNext + ){ + iOff += JOURNAL_CHUNKSIZE; + } + }else{ + pChunk = p->readpoint.pChunk; + } + + iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE); + do { + int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset; + int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset)); + memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy); + zOut += nCopy; + nRead -= iSpace; + iChunkOffset = 0; + } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 ); + p->readpoint.iOffset = iOfst+iAmt; + p->readpoint.pChunk = pChunk; + + return SQLITE_OK; +} + +/* +** Write data to the file. +*/ +static int memjrnlWrite( + sqlite3_file *pJfd, /* The journal file into which to write */ + const void *zBuf, /* Take data to be written from here */ + int iAmt, /* Number of bytes to write */ + sqlite_int64 iOfst /* Begin writing at this offset into the file */ +){ + MemJournal *p = (MemJournal *)pJfd; + int nWrite = iAmt; + u8 *zWrite = (u8 *)zBuf; + + /* An in-memory journal file should only ever be appended to. Random + ** access writes are not required by sqlite. + */ + assert( iOfst==p->endpoint.iOffset ); + UNUSED_PARAMETER(iOfst); + + while( nWrite>0 ){ + FileChunk *pChunk = p->endpoint.pChunk; + int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE); + int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset); + + if( iChunkOffset==0 ){ + /* New chunk is required to extend the file. */ + FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk)); + if( !pNew ){ + return SQLITE_IOERR_NOMEM; + } + pNew->pNext = 0; + if( pChunk ){ + assert( p->pFirst ); + pChunk->pNext = pNew; + }else{ + assert( !p->pFirst ); + p->pFirst = pNew; + } + p->endpoint.pChunk = pNew; + } + + memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace); + zWrite += iSpace; + nWrite -= iSpace; + p->endpoint.iOffset += iSpace; + } + + return SQLITE_OK; +} + +/* +** Truncate the file. +*/ +static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){ + MemJournal *p = (MemJournal *)pJfd; + FileChunk *pChunk; + assert(size==0); + UNUSED_PARAMETER(size); + pChunk = p->pFirst; + while( pChunk ){ + FileChunk *pTmp = pChunk; + pChunk = pChunk->pNext; + sqlite3_free(pTmp); + } + sqlite3MemJournalOpen(pJfd); + return SQLITE_OK; +} + +/* +** Close the file. +*/ +static int memjrnlClose(sqlite3_file *pJfd){ + memjrnlTruncate(pJfd, 0); + return SQLITE_OK; +} + + +/* +** Sync the file. +** +** Syncing an in-memory journal is a no-op. And, in fact, this routine +** is never called in a working implementation. This implementation +** exists purely as a contingency, in case some malfunction in some other +** part of SQLite causes Sync to be called by mistake. +*/ +static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return SQLITE_OK; +} + +/* +** Query the size of the file in bytes. +*/ +static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){ + MemJournal *p = (MemJournal *)pJfd; + *pSize = (sqlite_int64) p->endpoint.iOffset; + return SQLITE_OK; +} + +/* +** Table of methods for MemJournal sqlite3_file object. +*/ +static const struct sqlite3_io_methods MemJournalMethods = { + 1, /* iVersion */ + memjrnlClose, /* xClose */ + memjrnlRead, /* xRead */ + memjrnlWrite, /* xWrite */ + memjrnlTruncate, /* xTruncate */ + memjrnlSync, /* xSync */ + memjrnlFileSize, /* xFileSize */ + 0, /* xLock */ + 0, /* xUnlock */ + 0, /* xCheckReservedLock */ + 0, /* xFileControl */ + 0, /* xSectorSize */ + 0, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0, /* xShmUnmap */ + 0, /* xFetch */ + 0 /* xUnfetch */ +}; + +/* +** Open a journal file. +*/ +SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){ + MemJournal *p = (MemJournal *)pJfd; + assert( EIGHT_BYTE_ALIGNMENT(p) ); + memset(p, 0, sqlite3MemJournalSize()); + p->pMethod = (sqlite3_io_methods*)&MemJournalMethods; +} + +/* +** Return true if the file-handle passed as an argument is +** an in-memory journal +*/ +SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){ + return pJfd->pMethods==&MemJournalMethods; +} + +/* +** Return the number of bytes required to store a MemJournal file descriptor. +*/ +SQLITE_PRIVATE int sqlite3MemJournalSize(void){ + return sizeof(MemJournal); +} + +/************** End of memjournal.c ******************************************/ +/************** Begin file walker.c ******************************************/ +/* +** 2008 August 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains routines used for walking the parser tree for +** an SQL statement. +*/ +/* #include */ +/* #include */ + + +/* +** Walk an expression tree. Invoke the callback once for each node +** of the expression, while decending. (In other words, the callback +** is invoked before visiting children.) +** +** The return value from the callback should be one of the WRC_* +** constants to specify how to proceed with the walk. +** +** WRC_Continue Continue descending down the tree. +** +** WRC_Prune Do not descend into child nodes. But allow +** the walk to continue with sibling nodes. +** +** WRC_Abort Do no more callbacks. Unwind the stack and +** return the top-level walk call. +** +** The return value from this routine is WRC_Abort to abandon the tree walk +** and WRC_Continue to continue. +*/ +SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){ + int rc; + if( pExpr==0 ) return WRC_Continue; + testcase( ExprHasProperty(pExpr, EP_TokenOnly) ); + testcase( ExprHasProperty(pExpr, EP_Reduced) ); + rc = pWalker->xExprCallback(pWalker, pExpr); + if( rc==WRC_Continue + && !ExprHasProperty(pExpr,EP_TokenOnly) ){ + if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort; + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort; + }else{ + if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort; + } + } + return rc & WRC_Abort; +} + +/* +** Call sqlite3WalkExpr() for every expression in list p or until +** an abort request is seen. +*/ +SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){ + int i; + struct ExprList_item *pItem; + if( p ){ + for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){ + if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort; + } + } + return WRC_Continue; +} + +/* +** Walk all expressions associated with SELECT statement p. Do +** not invoke the SELECT callback on p, but do (of course) invoke +** any expr callbacks and SELECT callbacks that come from subqueries. +** Return WRC_Abort or WRC_Continue. +*/ +SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){ + if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort; + if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort; + if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort; + return WRC_Continue; +} + +/* +** Walk the parse trees associated with all subqueries in the +** FROM clause of SELECT statement p. Do not invoke the select +** callback on p, but do invoke it on each FROM clause subquery +** and on any subqueries further down in the tree. Return +** WRC_Abort or WRC_Continue; +*/ +SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){ + SrcList *pSrc; + int i; + struct SrcList_item *pItem; + + pSrc = p->pSrc; + if( ALWAYS(pSrc) ){ + for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ + if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){ + return WRC_Abort; + } + } + } + return WRC_Continue; +} + +/* +** Call sqlite3WalkExpr() for every expression in Select statement p. +** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and +** on the compound select chain, p->pPrior. Invoke the xSelectCallback() +** either before or after the walk of expressions and FROM clause, depending +** on whether pWalker->bSelectDepthFirst is false or true, respectively. +** +** Return WRC_Continue under normal conditions. Return WRC_Abort if +** there is an abort request. +** +** If the Walker does not have an xSelectCallback() then this routine +** is a no-op returning WRC_Continue. +*/ +SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){ + int rc; + if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue; + rc = WRC_Continue; + pWalker->walkerDepth++; + while( p ){ + if( !pWalker->bSelectDepthFirst ){ + rc = pWalker->xSelectCallback(pWalker, p); + if( rc ) break; + } + if( sqlite3WalkSelectExpr(pWalker, p) + || sqlite3WalkSelectFrom(pWalker, p) + ){ + pWalker->walkerDepth--; + return WRC_Abort; + } + if( pWalker->bSelectDepthFirst ){ + rc = pWalker->xSelectCallback(pWalker, p); + /* Depth-first search is currently only used for + ** selectAddSubqueryTypeInfo() and that routine always returns + ** WRC_Continue (0). So the following branch is never taken. */ + if( NEVER(rc) ) break; + } + p = p->pPrior; + } + pWalker->walkerDepth--; + return rc & WRC_Abort; +} + +/************** End of walker.c **********************************************/ +/************** Begin file resolve.c *****************************************/ +/* +** 2008 August 18 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains routines used for walking the parser tree and +** resolve all identifiers by associating them with a particular +** table and column. +*/ +/* #include */ +/* #include */ + +/* +** Walk the expression tree pExpr and increase the aggregate function +** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node. +** This needs to occur when copying a TK_AGG_FUNCTION node from an +** outer query into an inner subquery. +** +** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..) +** is a helper function - a callback for the tree walker. +*/ +static int incrAggDepth(Walker *pWalker, Expr *pExpr){ + if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i; + return WRC_Continue; +} +static void incrAggFunctionDepth(Expr *pExpr, int N){ + if( N>0 ){ + Walker w; + memset(&w, 0, sizeof(w)); + w.xExprCallback = incrAggDepth; + w.u.i = N; + sqlite3WalkExpr(&w, pExpr); + } +} + +/* +** Turn the pExpr expression into an alias for the iCol-th column of the +** result set in pEList. +** +** If the result set column is a simple column reference, then this routine +** makes an exact copy. But for any other kind of expression, this +** routine make a copy of the result set column as the argument to the +** TK_AS operator. The TK_AS operator causes the expression to be +** evaluated just once and then reused for each alias. +** +** The reason for suppressing the TK_AS term when the expression is a simple +** column reference is so that the column reference will be recognized as +** usable by indices within the WHERE clause processing logic. +** +** The TK_AS operator is inhibited if zType[0]=='G'. This means +** that in a GROUP BY clause, the expression is evaluated twice. Hence: +** +** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x +** +** Is equivalent to: +** +** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5 +** +** The result of random()%5 in the GROUP BY clause is probably different +** from the result in the result-set. On the other hand Standard SQL does +** not allow the GROUP BY clause to contain references to result-set columns. +** So this should never come up in well-formed queries. +** +** If the reference is followed by a COLLATE operator, then make sure +** the COLLATE operator is preserved. For example: +** +** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase; +** +** Should be transformed into: +** +** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase; +** +** The nSubquery parameter specifies how many levels of subquery the +** alias is removed from the original expression. The usually value is +** zero but it might be more if the alias is contained within a subquery +** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION +** structures must be increased by the nSubquery amount. +*/ +static void resolveAlias( + Parse *pParse, /* Parsing context */ + ExprList *pEList, /* A result set */ + int iCol, /* A column in the result set. 0..pEList->nExpr-1 */ + Expr *pExpr, /* Transform this into an alias to the result set */ + const char *zType, /* "GROUP" or "ORDER" or "" */ + int nSubquery /* Number of subqueries that the label is moving */ +){ + Expr *pOrig; /* The iCol-th column of the result set */ + Expr *pDup; /* Copy of pOrig */ + sqlite3 *db; /* The database connection */ + + assert( iCol>=0 && iColnExpr ); + pOrig = pEList->a[iCol].pExpr; + assert( pOrig!=0 ); + assert( pOrig->flags & EP_Resolved ); + db = pParse->db; + pDup = sqlite3ExprDup(db, pOrig, 0); + if( pDup==0 ) return; + if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){ + incrAggFunctionDepth(pDup, nSubquery); + pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0); + if( pDup==0 ) return; + ExprSetProperty(pDup, EP_Skip); + if( pEList->a[iCol].iAlias==0 ){ + pEList->a[iCol].iAlias = (u16)(++pParse->nAlias); + } + pDup->iTable = pEList->a[iCol].iAlias; + } + if( pExpr->op==TK_COLLATE ){ + pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); + } + + /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This + ** prevents ExprDelete() from deleting the Expr structure itself, + ** allowing it to be repopulated by the memcpy() on the following line. + ** The pExpr->u.zToken might point into memory that will be freed by the + ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to + ** make a copy of the token before doing the sqlite3DbFree(). + */ + ExprSetProperty(pExpr, EP_Static); + sqlite3ExprDelete(db, pExpr); + memcpy(pExpr, pDup, sizeof(*pExpr)); + if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ + assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); + pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken); + pExpr->flags |= EP_MemToken; + } + sqlite3DbFree(db, pDup); +} + + +/* +** Return TRUE if the name zCol occurs anywhere in the USING clause. +** +** Return FALSE if the USING clause is NULL or if it does not contain +** zCol. +*/ +static int nameInUsingClause(IdList *pUsing, const char *zCol){ + if( pUsing ){ + int k; + for(k=0; knId; k++){ + if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1; + } + } + return 0; +} + +/* +** Subqueries stores the original database, table and column names for their +** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN". +** Check to see if the zSpan given to this routine matches the zDb, zTab, +** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will +** match anything. +*/ +SQLITE_PRIVATE int sqlite3MatchSpanName( + const char *zSpan, + const char *zCol, + const char *zTab, + const char *zDb +){ + int n; + for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} + if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ + return 0; + } + zSpan += n+1; + for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} + if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ + return 0; + } + zSpan += n+1; + if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){ + return 0; + } + return 1; +} + +/* +** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up +** that name in the set of source tables in pSrcList and make the pExpr +** expression node refer back to that source column. The following changes +** are made to pExpr: +** +** pExpr->iDb Set the index in db->aDb[] of the database X +** (even if X is implied). +** pExpr->iTable Set to the cursor number for the table obtained +** from pSrcList. +** pExpr->pTab Points to the Table structure of X.Y (even if +** X and/or Y are implied.) +** pExpr->iColumn Set to the column number within the table. +** pExpr->op Set to TK_COLUMN. +** pExpr->pLeft Any expression this points to is deleted +** pExpr->pRight Any expression this points to is deleted. +** +** The zDb variable is the name of the database (the "X"). This value may be +** NULL meaning that name is of the form Y.Z or Z. Any available database +** can be used. The zTable variable is the name of the table (the "Y"). This +** value can be NULL if zDb is also NULL. If zTable is NULL it +** means that the form of the name is Z and that columns from any table +** can be used. +** +** If the name cannot be resolved unambiguously, leave an error message +** in pParse and return WRC_Abort. Return WRC_Prune on success. +*/ +static int lookupName( + Parse *pParse, /* The parsing context */ + const char *zDb, /* Name of the database containing table, or NULL */ + const char *zTab, /* Name of table containing column, or NULL */ + const char *zCol, /* Name of the column. */ + NameContext *pNC, /* The name context used to resolve the name */ + Expr *pExpr /* Make this EXPR node point to the selected column */ +){ + int i, j; /* Loop counters */ + int cnt = 0; /* Number of matching column names */ + int cntTab = 0; /* Number of matching table names */ + int nSubquery = 0; /* How many levels of subquery */ + sqlite3 *db = pParse->db; /* The database connection */ + struct SrcList_item *pItem; /* Use for looping over pSrcList items */ + struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ + NameContext *pTopNC = pNC; /* First namecontext in the list */ + Schema *pSchema = 0; /* Schema of the expression */ + int isTrigger = 0; + + assert( pNC ); /* the name context cannot be NULL. */ + assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ + assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); + + /* Initialize the node to no-match */ + pExpr->iTable = -1; + pExpr->pTab = 0; + ExprSetVVAProperty(pExpr, EP_NoReduce); + + /* Translate the schema name in zDb into a pointer to the corresponding + ** schema. If not found, pSchema will remain NULL and nothing will match + ** resulting in an appropriate error message toward the end of this routine + */ + if( zDb ){ + testcase( pNC->ncFlags & NC_PartIdx ); + testcase( pNC->ncFlags & NC_IsCheck ); + if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ + /* Silently ignore database qualifiers inside CHECK constraints and partial + ** indices. Do not raise errors because that might break legacy and + ** because it does not hurt anything to just ignore the database name. */ + zDb = 0; + }else{ + for(i=0; inDb; i++){ + assert( db->aDb[i].zName ); + if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){ + pSchema = db->aDb[i].pSchema; + break; + } + } + } + } + + /* Start at the inner-most context and move outward until a match is found */ + while( pNC && cnt==0 ){ + ExprList *pEList; + SrcList *pSrcList = pNC->pSrcList; + + if( pSrcList ){ + for(i=0, pItem=pSrcList->a; inSrc; i++, pItem++){ + Table *pTab; + Column *pCol; + + pTab = pItem->pTab; + assert( pTab!=0 && pTab->zName!=0 ); + assert( pTab->nCol>0 ); + if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ + int hit = 0; + pEList = pItem->pSelect->pEList; + for(j=0; jnExpr; j++){ + if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ + cnt++; + cntTab = 2; + pMatch = pItem; + pExpr->iColumn = j; + hit = 1; + } + } + if( hit || zTab==0 ) continue; + } + if( zDb && pTab->pSchema!=pSchema ){ + continue; + } + if( zTab ){ + const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; + assert( zTabName!=0 ); + if( sqlite3StrICmp(zTabName, zTab)!=0 ){ + continue; + } + } + if( 0==(cntTab++) ){ + pMatch = pItem; + } + for(j=0, pCol=pTab->aCol; jnCol; j++, pCol++){ + if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ + /* If there has been exactly one prior match and this match + ** is for the right-hand table of a NATURAL JOIN or is in a + ** USING clause, then skip this match. + */ + if( cnt==1 ){ + if( pItem->jointype & JT_NATURAL ) continue; + if( nameInUsingClause(pItem->pUsing, zCol) ) continue; + } + cnt++; + pMatch = pItem; + /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ + pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; + break; + } + } + } + if( pMatch ){ + pExpr->iTable = pMatch->iCursor; + pExpr->pTab = pMatch->pTab; + pSchema = pExpr->pTab->pSchema; + } + } /* if( pSrcList ) */ + +#ifndef SQLITE_OMIT_TRIGGER + /* If we have not already resolved the name, then maybe + ** it is a new.* or old.* trigger argument reference + */ + if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){ + int op = pParse->eTriggerOp; + Table *pTab = 0; + assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); + if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ + pExpr->iTable = 1; + pTab = pParse->pTriggerTab; + }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ + pExpr->iTable = 0; + pTab = pParse->pTriggerTab; + } + + if( pTab ){ + int iCol; + pSchema = pTab->pSchema; + cntTab++; + for(iCol=0; iColnCol; iCol++){ + Column *pCol = &pTab->aCol[iCol]; + if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ + if( iCol==pTab->iPKey ){ + iCol = -1; + } + break; + } + } + if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){ + iCol = -1; /* IMP: R-44911-55124 */ + } + if( iColnCol ){ + cnt++; + if( iCol<0 ){ + pExpr->affinity = SQLITE_AFF_INTEGER; + }else if( pExpr->iTable==0 ){ + testcase( iCol==31 ); + testcase( iCol==32 ); + pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<iColumn = (i16)iCol; + pExpr->pTab = pTab; + isTrigger = 1; + } + } + } +#endif /* !defined(SQLITE_OMIT_TRIGGER) */ + + /* + ** Perhaps the name is a reference to the ROWID + */ + if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){ + cnt = 1; + pExpr->iColumn = -1; /* IMP: R-44911-55124 */ + pExpr->affinity = SQLITE_AFF_INTEGER; + } + + /* + ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z + ** might refer to an result-set alias. This happens, for example, when + ** we are resolving names in the WHERE clause of the following command: + ** + ** SELECT a+b AS x FROM table WHERE x<10; + ** + ** In cases like this, replace pExpr with a copy of the expression that + ** forms the result set entry ("a+b" in the example) and return immediately. + ** Note that the expression in the result set should have already been + ** resolved by the time the WHERE clause is resolved. + ** + ** The ability to use an output result-set column in the WHERE, GROUP BY, + ** or HAVING clauses, or as part of a larger expression in the ORDRE BY + ** clause is not standard SQL. This is a (goofy) SQLite extension, that + ** is supported for backwards compatibility only. TO DO: Issue a warning + ** on sqlite3_log() whenever the capability is used. + */ + if( (pEList = pNC->pEList)!=0 + && zTab==0 + && cnt==0 + ){ + for(j=0; jnExpr; j++){ + char *zAs = pEList->a[j].zName; + if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ + Expr *pOrig; + assert( pExpr->pLeft==0 && pExpr->pRight==0 ); + assert( pExpr->x.pList==0 ); + assert( pExpr->x.pSelect==0 ); + pOrig = pEList->a[j].pExpr; + if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ + sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); + return WRC_Abort; + } + resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); + cnt = 1; + pMatch = 0; + assert( zTab==0 && zDb==0 ); + goto lookupname_end; + } + } + } + + /* Advance to the next name context. The loop will exit when either + ** we have a match (cnt>0) or when we run out of name contexts. + */ + if( cnt==0 ){ + pNC = pNC->pNext; + nSubquery++; + } + } + + /* + ** If X and Y are NULL (in other words if only the column name Z is + ** supplied) and the value of Z is enclosed in double-quotes, then + ** Z is a string literal if it doesn't match any column names. In that + ** case, we need to return right away and not make any changes to + ** pExpr. + ** + ** Because no reference was made to outer contexts, the pNC->nRef + ** fields are not changed in any context. + */ + if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){ + pExpr->op = TK_STRING; + pExpr->pTab = 0; + return WRC_Prune; + } + + /* + ** cnt==0 means there was not match. cnt>1 means there were two or + ** more matches. Either way, we have an error. + */ + if( cnt!=1 ){ + const char *zErr; + zErr = cnt==0 ? "no such column" : "ambiguous column name"; + if( zDb ){ + sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); + }else if( zTab ){ + sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); + }else{ + sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); + } + pParse->checkSchema = 1; + pTopNC->nErr++; + } + + /* If a column from a table in pSrcList is referenced, then record + ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes + ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the + ** column number is greater than the number of bits in the bitmask + ** then set the high-order bit of the bitmask. + */ + if( pExpr->iColumn>=0 && pMatch!=0 ){ + int n = pExpr->iColumn; + testcase( n==BMS-1 ); + if( n>=BMS ){ + n = BMS-1; + } + assert( pMatch->iCursor==pExpr->iTable ); + pMatch->colUsed |= ((Bitmask)1)<pLeft); + pExpr->pLeft = 0; + sqlite3ExprDelete(db, pExpr->pRight); + pExpr->pRight = 0; + pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN); +lookupname_end: + if( cnt==1 ){ + assert( pNC!=0 ); + if( pExpr->op!=TK_AS ){ + sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); + } + /* Increment the nRef value on all name contexts from TopNC up to + ** the point where the name matched. */ + for(;;){ + assert( pTopNC!=0 ); + pTopNC->nRef++; + if( pTopNC==pNC ) break; + pTopNC = pTopNC->pNext; + } + return WRC_Prune; + } else { + return WRC_Abort; + } +} + +/* +** Allocate and return a pointer to an expression to load the column iCol +** from datasource iSrc in SrcList pSrc. +*/ +SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ + Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0); + if( p ){ + struct SrcList_item *pItem = &pSrc->a[iSrc]; + p->pTab = pItem->pTab; + p->iTable = pItem->iCursor; + if( p->pTab->iPKey==iCol ){ + p->iColumn = -1; + }else{ + p->iColumn = (ynVar)iCol; + testcase( iCol==BMS ); + testcase( iCol==BMS-1 ); + pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); + } + ExprSetProperty(p, EP_Resolved); + } + return p; +} + +/* +** Report an error that an expression is not valid for a partial index WHERE +** clause. +*/ +static void notValidPartIdxWhere( + Parse *pParse, /* Leave error message here */ + NameContext *pNC, /* The name context */ + const char *zMsg /* Type of error */ +){ + if( (pNC->ncFlags & NC_PartIdx)!=0 ){ + sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses", + zMsg); + } +} + +#ifndef SQLITE_OMIT_CHECK +/* +** Report an error that an expression is not valid for a CHECK constraint. +*/ +static void notValidCheckConstraint( + Parse *pParse, /* Leave error message here */ + NameContext *pNC, /* The name context */ + const char *zMsg /* Type of error */ +){ + if( (pNC->ncFlags & NC_IsCheck)!=0 ){ + sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg); + } +} +#else +# define notValidCheckConstraint(P,N,M) +#endif + +/* +** Expression p should encode a floating point value between 1.0 and 0.0. +** Return 1024 times this value. Or return -1 if p is not a floating point +** value between 1.0 and 0.0. +*/ +static int exprProbability(Expr *p){ + double r = -1.0; + if( p->op!=TK_FLOAT ) return -1; + sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); + assert( r>=0.0 ); + if( r>1.0 ) return -1; + return (int)(r*1000.0); +} + +/* +** This routine is callback for sqlite3WalkExpr(). +** +** Resolve symbolic names into TK_COLUMN operators for the current +** node in the expression tree. Return 0 to continue the search down +** the tree or 2 to abort the tree walk. +** +** This routine also does error checking and name resolution for +** function names. The operator for aggregate functions is changed +** to TK_AGG_FUNCTION. +*/ +static int resolveExprStep(Walker *pWalker, Expr *pExpr){ + NameContext *pNC; + Parse *pParse; + + pNC = pWalker->u.pNC; + assert( pNC!=0 ); + pParse = pNC->pParse; + assert( pParse==pWalker->pParse ); + + if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune; + ExprSetProperty(pExpr, EP_Resolved); +#ifndef NDEBUG + if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ + SrcList *pSrcList = pNC->pSrcList; + int i; + for(i=0; ipSrcList->nSrc; i++){ + assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursornTab); + } + } +#endif + switch( pExpr->op ){ + +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) + /* The special operator TK_ROW means use the rowid for the first + ** column in the FROM clause. This is used by the LIMIT and ORDER BY + ** clause processing on UPDATE and DELETE statements. + */ + case TK_ROW: { + SrcList *pSrcList = pNC->pSrcList; + struct SrcList_item *pItem; + assert( pSrcList && pSrcList->nSrc==1 ); + pItem = pSrcList->a; + pExpr->op = TK_COLUMN; + pExpr->pTab = pItem->pTab; + pExpr->iTable = pItem->iCursor; + pExpr->iColumn = -1; + pExpr->affinity = SQLITE_AFF_INTEGER; + break; + } +#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ + + /* A lone identifier is the name of a column. + */ + case TK_ID: { + return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr); + } + + /* A table name and column name: ID.ID + ** Or a database, table and column: ID.ID.ID + */ + case TK_DOT: { + const char *zColumn; + const char *zTable; + const char *zDb; + Expr *pRight; + + /* if( pSrcList==0 ) break; */ + pRight = pExpr->pRight; + if( pRight->op==TK_ID ){ + zDb = 0; + zTable = pExpr->pLeft->u.zToken; + zColumn = pRight->u.zToken; + }else{ + assert( pRight->op==TK_DOT ); + zDb = pExpr->pLeft->u.zToken; + zTable = pRight->pLeft->u.zToken; + zColumn = pRight->pRight->u.zToken; + } + return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); + } + + /* Resolve function names + */ + case TK_CONST_FUNC: + case TK_FUNCTION: { + ExprList *pList = pExpr->x.pList; /* The argument list */ + int n = pList ? pList->nExpr : 0; /* Number of arguments */ + int no_such_func = 0; /* True if no such function exists */ + int wrong_num_args = 0; /* True if wrong number of arguments */ + int is_agg = 0; /* True if is an aggregate function */ + int auth; /* Authorization to use the function */ + int nId; /* Number of characters in function name */ + const char *zId; /* The function name. */ + FuncDef *pDef; /* Information about the function */ + u8 enc = ENC(pParse->db); /* The database encoding */ + + testcase( pExpr->op==TK_CONST_FUNC ); + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + notValidPartIdxWhere(pParse, pNC, "functions"); + zId = pExpr->u.zToken; + nId = sqlite3Strlen30(zId); + pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0); + if( pDef==0 ){ + pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0); + if( pDef==0 ){ + no_such_func = 1; + }else{ + wrong_num_args = 1; + } + }else{ + is_agg = pDef->xFunc==0; + if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ + ExprSetProperty(pExpr, EP_Unlikely|EP_Skip); + if( n==2 ){ + pExpr->iTable = exprProbability(pList->a[1].pExpr); + if( pExpr->iTable<0 ){ + sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a " + "constant between 0.0 and 1.0"); + pNC->nErr++; + } + }else{ + /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to + ** likelihood(X, 0.0625). + ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for + ** likelihood(X,0.0625). */ + pExpr->iTable = 62; /* TUNING: Default 2nd arg to unlikely() is 0.0625 */ + } + } + } +#ifndef SQLITE_OMIT_AUTHORIZATION + if( pDef ){ + auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0); + if( auth!=SQLITE_OK ){ + if( auth==SQLITE_DENY ){ + sqlite3ErrorMsg(pParse, "not authorized to use function: %s", + pDef->zName); + pNC->nErr++; + } + pExpr->op = TK_NULL; + return WRC_Prune; + } + } +#endif + if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){ + sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId); + pNC->nErr++; + is_agg = 0; + }else if( no_such_func && pParse->db->init.busy==0 ){ + sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); + pNC->nErr++; + }else if( wrong_num_args ){ + sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", + nId, zId); + pNC->nErr++; + } + if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg; + sqlite3WalkExprList(pWalker, pList); + if( is_agg ){ + NameContext *pNC2 = pNC; + pExpr->op = TK_AGG_FUNCTION; + pExpr->op2 = 0; + while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ + pExpr->op2++; + pNC2 = pNC2->pNext; + } + if( pNC2 ) pNC2->ncFlags |= NC_HasAgg; + pNC->ncFlags |= NC_AllowAgg; + } + /* FIX ME: Compute pExpr->affinity based on the expected return + ** type of the function + */ + return WRC_Prune; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_SELECT: + case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); +#endif + case TK_IN: { + testcase( pExpr->op==TK_IN ); + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + int nRef = pNC->nRef; + notValidCheckConstraint(pParse, pNC, "subqueries"); + notValidPartIdxWhere(pParse, pNC, "subqueries"); + sqlite3WalkSelect(pWalker, pExpr->x.pSelect); + assert( pNC->nRef>=nRef ); + if( nRef!=pNC->nRef ){ + ExprSetProperty(pExpr, EP_VarSelect); + } + } + break; + } + case TK_VARIABLE: { + notValidCheckConstraint(pParse, pNC, "parameters"); + notValidPartIdxWhere(pParse, pNC, "parameters"); + break; + } + } + return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue; +} + +/* +** pEList is a list of expressions which are really the result set of the +** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. +** This routine checks to see if pE is a simple identifier which corresponds +** to the AS-name of one of the terms of the expression list. If it is, +** this routine return an integer between 1 and N where N is the number of +** elements in pEList, corresponding to the matching entry. If there is +** no match, or if pE is not a simple identifier, then this routine +** return 0. +** +** pEList has been resolved. pE has not. +*/ +static int resolveAsName( + Parse *pParse, /* Parsing context for error messages */ + ExprList *pEList, /* List of expressions to scan */ + Expr *pE /* Expression we are trying to match */ +){ + int i; /* Loop counter */ + + UNUSED_PARAMETER(pParse); + + if( pE->op==TK_ID ){ + char *zCol = pE->u.zToken; + for(i=0; inExpr; i++){ + char *zAs = pEList->a[i].zName; + if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ + return i+1; + } + } + } + return 0; +} + +/* +** pE is a pointer to an expression which is a single term in the +** ORDER BY of a compound SELECT. The expression has not been +** name resolved. +** +** At the point this routine is called, we already know that the +** ORDER BY term is not an integer index into the result set. That +** case is handled by the calling routine. +** +** Attempt to match pE against result set columns in the left-most +** SELECT statement. Return the index i of the matching column, +** as an indication to the caller that it should sort by the i-th column. +** The left-most column is 1. In other words, the value returned is the +** same integer value that would be used in the SQL statement to indicate +** the column. +** +** If there is no match, return 0. Return -1 if an error occurs. +*/ +static int resolveOrderByTermToExprList( + Parse *pParse, /* Parsing context for error messages */ + Select *pSelect, /* The SELECT statement with the ORDER BY clause */ + Expr *pE /* The specific ORDER BY term */ +){ + int i; /* Loop counter */ + ExprList *pEList; /* The columns of the result set */ + NameContext nc; /* Name context for resolving pE */ + sqlite3 *db; /* Database connection */ + int rc; /* Return code from subprocedures */ + u8 savedSuppErr; /* Saved value of db->suppressErr */ + + assert( sqlite3ExprIsInteger(pE, &i)==0 ); + pEList = pSelect->pEList; + + /* Resolve all names in the ORDER BY term expression + */ + memset(&nc, 0, sizeof(nc)); + nc.pParse = pParse; + nc.pSrcList = pSelect->pSrc; + nc.pEList = pEList; + nc.ncFlags = NC_AllowAgg; + nc.nErr = 0; + db = pParse->db; + savedSuppErr = db->suppressErr; + db->suppressErr = 1; + rc = sqlite3ResolveExprNames(&nc, pE); + db->suppressErr = savedSuppErr; + if( rc ) return 0; + + /* Try to match the ORDER BY expression against an expression + ** in the result set. Return an 1-based index of the matching + ** result-set entry. + */ + for(i=0; inExpr; i++){ + if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){ + return i+1; + } + } + + /* If no match, return 0. */ + return 0; +} + +/* +** Generate an ORDER BY or GROUP BY term out-of-range error. +*/ +static void resolveOutOfRangeError( + Parse *pParse, /* The error context into which to write the error */ + const char *zType, /* "ORDER" or "GROUP" */ + int i, /* The index (1-based) of the term out of range */ + int mx /* Largest permissible value of i */ +){ + sqlite3ErrorMsg(pParse, + "%r %s BY term out of range - should be " + "between 1 and %d", i, zType, mx); +} + +/* +** Analyze the ORDER BY clause in a compound SELECT statement. Modify +** each term of the ORDER BY clause is a constant integer between 1 +** and N where N is the number of columns in the compound SELECT. +** +** ORDER BY terms that are already an integer between 1 and N are +** unmodified. ORDER BY terms that are integers outside the range of +** 1 through N generate an error. ORDER BY terms that are expressions +** are matched against result set expressions of compound SELECT +** beginning with the left-most SELECT and working toward the right. +** At the first match, the ORDER BY expression is transformed into +** the integer column number. +** +** Return the number of errors seen. +*/ +static int resolveCompoundOrderBy( + Parse *pParse, /* Parsing context. Leave error messages here */ + Select *pSelect /* The SELECT statement containing the ORDER BY */ +){ + int i; + ExprList *pOrderBy; + ExprList *pEList; + sqlite3 *db; + int moreToDo = 1; + + pOrderBy = pSelect->pOrderBy; + if( pOrderBy==0 ) return 0; + db = pParse->db; +#if SQLITE_MAX_COLUMN + if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); + return 1; + } +#endif + for(i=0; inExpr; i++){ + pOrderBy->a[i].done = 0; + } + pSelect->pNext = 0; + while( pSelect->pPrior ){ + pSelect->pPrior->pNext = pSelect; + pSelect = pSelect->pPrior; + } + while( pSelect && moreToDo ){ + struct ExprList_item *pItem; + moreToDo = 0; + pEList = pSelect->pEList; + assert( pEList!=0 ); + for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ + int iCol = -1; + Expr *pE, *pDup; + if( pItem->done ) continue; + pE = sqlite3ExprSkipCollate(pItem->pExpr); + if( sqlite3ExprIsInteger(pE, &iCol) ){ + if( iCol<=0 || iCol>pEList->nExpr ){ + resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr); + return 1; + } + }else{ + iCol = resolveAsName(pParse, pEList, pE); + if( iCol==0 ){ + pDup = sqlite3ExprDup(db, pE, 0); + if( !db->mallocFailed ){ + assert(pDup); + iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); + } + sqlite3ExprDelete(db, pDup); + } + } + if( iCol>0 ){ + /* Convert the ORDER BY term into an integer column number iCol, + ** taking care to preserve the COLLATE clause if it exists */ + Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); + if( pNew==0 ) return 1; + pNew->flags |= EP_IntValue; + pNew->u.iValue = iCol; + if( pItem->pExpr==pE ){ + pItem->pExpr = pNew; + }else{ + assert( pItem->pExpr->op==TK_COLLATE ); + assert( pItem->pExpr->pLeft==pE ); + pItem->pExpr->pLeft = pNew; + } + sqlite3ExprDelete(db, pE); + pItem->iOrderByCol = (u16)iCol; + pItem->done = 1; + }else{ + moreToDo = 1; + } + } + pSelect = pSelect->pNext; + } + for(i=0; inExpr; i++){ + if( pOrderBy->a[i].done==0 ){ + sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " + "column in the result set", i+1); + return 1; + } + } + return 0; +} + +/* +** Check every term in the ORDER BY or GROUP BY clause pOrderBy of +** the SELECT statement pSelect. If any term is reference to a +** result set expression (as determined by the ExprList.a.iOrderByCol field) +** then convert that term into a copy of the corresponding result set +** column. +** +** If any errors are detected, add an error message to pParse and +** return non-zero. Return zero if no errors are seen. +*/ +SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy( + Parse *pParse, /* Parsing context. Leave error messages here */ + Select *pSelect, /* The SELECT statement containing the clause */ + ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ + const char *zType /* "ORDER" or "GROUP" */ +){ + int i; + sqlite3 *db = pParse->db; + ExprList *pEList; + struct ExprList_item *pItem; + + if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; +#if SQLITE_MAX_COLUMN + if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); + return 1; + } +#endif + pEList = pSelect->pEList; + assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ + for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ + if( pItem->iOrderByCol ){ + if( pItem->iOrderByCol>pEList->nExpr ){ + resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr); + return 1; + } + resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0); + } + } + return 0; +} + +/* +** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. +** The Name context of the SELECT statement is pNC. zType is either +** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. +** +** This routine resolves each term of the clause into an expression. +** If the order-by term is an integer I between 1 and N (where N is the +** number of columns in the result set of the SELECT) then the expression +** in the resolution is a copy of the I-th result-set expression. If +** the order-by term is an identifier that corresponds to the AS-name of +** a result-set expression, then the term resolves to a copy of the +** result-set expression. Otherwise, the expression is resolved in +** the usual way - using sqlite3ResolveExprNames(). +** +** This routine returns the number of errors. If errors occur, then +** an appropriate error message might be left in pParse. (OOM errors +** excepted.) +*/ +static int resolveOrderGroupBy( + NameContext *pNC, /* The name context of the SELECT statement */ + Select *pSelect, /* The SELECT statement holding pOrderBy */ + ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ + const char *zType /* Either "ORDER" or "GROUP", as appropriate */ +){ + int i, j; /* Loop counters */ + int iCol; /* Column number */ + struct ExprList_item *pItem; /* A term of the ORDER BY clause */ + Parse *pParse; /* Parsing context */ + int nResult; /* Number of terms in the result set */ + + if( pOrderBy==0 ) return 0; + nResult = pSelect->pEList->nExpr; + pParse = pNC->pParse; + for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ + Expr *pE = pItem->pExpr; + Expr *pE2 = sqlite3ExprSkipCollate(pE); + if( zType[0]!='G' ){ + iCol = resolveAsName(pParse, pSelect->pEList, pE2); + if( iCol>0 ){ + /* If an AS-name match is found, mark this ORDER BY column as being + ** a copy of the iCol-th result-set column. The subsequent call to + ** sqlite3ResolveOrderGroupBy() will convert the expression to a + ** copy of the iCol-th result-set expression. */ + pItem->iOrderByCol = (u16)iCol; + continue; + } + } + if( sqlite3ExprIsInteger(pE2, &iCol) ){ + /* The ORDER BY term is an integer constant. Again, set the column + ** number so that sqlite3ResolveOrderGroupBy() will convert the + ** order-by term to a copy of the result-set expression */ + if( iCol<1 || iCol>0xffff ){ + resolveOutOfRangeError(pParse, zType, i+1, nResult); + return 1; + } + pItem->iOrderByCol = (u16)iCol; + continue; + } + + /* Otherwise, treat the ORDER BY term as an ordinary expression */ + pItem->iOrderByCol = 0; + if( sqlite3ResolveExprNames(pNC, pE) ){ + return 1; + } + for(j=0; jpEList->nExpr; j++){ + if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ + pItem->iOrderByCol = j+1; + } + } + } + return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); +} + +/* +** Resolve names in the SELECT statement p and all of its descendents. +*/ +static int resolveSelectStep(Walker *pWalker, Select *p){ + NameContext *pOuterNC; /* Context that contains this SELECT */ + NameContext sNC; /* Name context of this SELECT */ + int isCompound; /* True if p is a compound select */ + int nCompound; /* Number of compound terms processed so far */ + Parse *pParse; /* Parsing context */ + ExprList *pEList; /* Result set expression list */ + int i; /* Loop counter */ + ExprList *pGroupBy; /* The GROUP BY clause */ + Select *pLeftmost; /* Left-most of SELECT of a compound */ + sqlite3 *db; /* Database connection */ + + + assert( p!=0 ); + if( p->selFlags & SF_Resolved ){ + return WRC_Prune; + } + pOuterNC = pWalker->u.pNC; + pParse = pWalker->pParse; + db = pParse->db; + + /* Normally sqlite3SelectExpand() will be called first and will have + ** already expanded this SELECT. However, if this is a subquery within + ** an expression, sqlite3ResolveExprNames() will be called without a + ** prior call to sqlite3SelectExpand(). When that happens, let + ** sqlite3SelectPrep() do all of the processing for this SELECT. + ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and + ** this routine in the correct order. + */ + if( (p->selFlags & SF_Expanded)==0 ){ + sqlite3SelectPrep(pParse, p, pOuterNC); + return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune; + } + + isCompound = p->pPrior!=0; + nCompound = 0; + pLeftmost = p; + while( p ){ + assert( (p->selFlags & SF_Expanded)!=0 ); + assert( (p->selFlags & SF_Resolved)==0 ); + p->selFlags |= SF_Resolved; + + /* Resolve the expressions in the LIMIT and OFFSET clauses. These + ** are not allowed to refer to any names, so pass an empty NameContext. + */ + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + if( sqlite3ResolveExprNames(&sNC, p->pLimit) || + sqlite3ResolveExprNames(&sNC, p->pOffset) ){ + return WRC_Abort; + } + + /* Recursively resolve names in all subqueries + */ + for(i=0; ipSrc->nSrc; i++){ + struct SrcList_item *pItem = &p->pSrc->a[i]; + if( pItem->pSelect ){ + NameContext *pNC; /* Used to iterate name contexts */ + int nRef = 0; /* Refcount for pOuterNC and outer contexts */ + const char *zSavedContext = pParse->zAuthContext; + + /* Count the total number of references to pOuterNC and all of its + ** parent contexts. After resolving references to expressions in + ** pItem->pSelect, check if this value has changed. If so, then + ** SELECT statement pItem->pSelect must be correlated. Set the + ** pItem->isCorrelated flag if this is the case. */ + for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef; + + if( pItem->zName ) pParse->zAuthContext = pItem->zName; + sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); + pParse->zAuthContext = zSavedContext; + if( pParse->nErr || db->mallocFailed ) return WRC_Abort; + + for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef; + assert( pItem->isCorrelated==0 && nRef<=0 ); + pItem->isCorrelated = (nRef!=0); + } + } + + /* Set up the local name-context to pass to sqlite3ResolveExprNames() to + ** resolve the result-set expression list. + */ + sNC.ncFlags = NC_AllowAgg; + sNC.pSrcList = p->pSrc; + sNC.pNext = pOuterNC; + + /* Resolve names in the result set. */ + pEList = p->pEList; + assert( pEList!=0 ); + for(i=0; inExpr; i++){ + Expr *pX = pEList->a[i].pExpr; + if( sqlite3ResolveExprNames(&sNC, pX) ){ + return WRC_Abort; + } + } + + /* If there are no aggregate functions in the result-set, and no GROUP BY + ** expression, do not allow aggregates in any of the other expressions. + */ + assert( (p->selFlags & SF_Aggregate)==0 ); + pGroupBy = p->pGroupBy; + if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){ + p->selFlags |= SF_Aggregate; + }else{ + sNC.ncFlags &= ~NC_AllowAgg; + } + + /* If a HAVING clause is present, then there must be a GROUP BY clause. + */ + if( p->pHaving && !pGroupBy ){ + sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); + return WRC_Abort; + } + + /* Add the output column list to the name-context before parsing the + ** other expressions in the SELECT statement. This is so that + ** expressions in the WHERE clause (etc.) can refer to expressions by + ** aliases in the result set. + ** + ** Minor point: If this is the case, then the expression will be + ** re-evaluated for each reference to it. + */ + sNC.pEList = p->pEList; + if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; + if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; + + /* The ORDER BY and GROUP BY clauses may not refer to terms in + ** outer queries + */ + sNC.pNext = 0; + sNC.ncFlags |= NC_AllowAgg; + + /* Process the ORDER BY clause for singleton SELECT statements. + ** The ORDER BY clause for compounds SELECT statements is handled + ** below, after all of the result-sets for all of the elements of + ** the compound have been resolved. + */ + if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){ + return WRC_Abort; + } + if( db->mallocFailed ){ + return WRC_Abort; + } + + /* Resolve the GROUP BY clause. At the same time, make sure + ** the GROUP BY clause does not contain aggregate functions. + */ + if( pGroupBy ){ + struct ExprList_item *pItem; + + if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){ + return WRC_Abort; + } + for(i=0, pItem=pGroupBy->a; inExpr; i++, pItem++){ + if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ + sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " + "the GROUP BY clause"); + return WRC_Abort; + } + } + } + + /* Advance to the next term of the compound + */ + p = p->pPrior; + nCompound++; + } + + /* Resolve the ORDER BY on a compound SELECT after all terms of + ** the compound have been resolved. + */ + if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){ + return WRC_Abort; + } + + return WRC_Prune; +} + +/* +** This routine walks an expression tree and resolves references to +** table columns and result-set columns. At the same time, do error +** checking on function usage and set a flag if any aggregate functions +** are seen. +** +** To resolve table columns references we look for nodes (or subtrees) of the +** form X.Y.Z or Y.Z or just Z where +** +** X: The name of a database. Ex: "main" or "temp" or +** the symbolic name assigned to an ATTACH-ed database. +** +** Y: The name of a table in a FROM clause. Or in a trigger +** one of the special names "old" or "new". +** +** Z: The name of a column in table Y. +** +** The node at the root of the subtree is modified as follows: +** +** Expr.op Changed to TK_COLUMN +** Expr.pTab Points to the Table object for X.Y +** Expr.iColumn The column index in X.Y. -1 for the rowid. +** Expr.iTable The VDBE cursor number for X.Y +** +** +** To resolve result-set references, look for expression nodes of the +** form Z (with no X and Y prefix) where the Z matches the right-hand +** size of an AS clause in the result-set of a SELECT. The Z expression +** is replaced by a copy of the left-hand side of the result-set expression. +** Table-name and function resolution occurs on the substituted expression +** tree. For example, in: +** +** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; +** +** The "x" term of the order by is replaced by "a+b" to render: +** +** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; +** +** Function calls are checked to make sure that the function is +** defined and that the correct number of arguments are specified. +** If the function is an aggregate function, then the NC_HasAgg flag is +** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. +** If an expression contains aggregate functions then the EP_Agg +** property on the expression is set. +** +** An error message is left in pParse if anything is amiss. The number +** if errors is returned. +*/ +SQLITE_PRIVATE int sqlite3ResolveExprNames( + NameContext *pNC, /* Namespace to resolve expressions in. */ + Expr *pExpr /* The expression to be analyzed. */ +){ + u8 savedHasAgg; + Walker w; + + if( pExpr==0 ) return 0; +#if SQLITE_MAX_EXPR_DEPTH>0 + { + Parse *pParse = pNC->pParse; + if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){ + return 1; + } + pParse->nHeight += pExpr->nHeight; + } +#endif + savedHasAgg = pNC->ncFlags & NC_HasAgg; + pNC->ncFlags &= ~NC_HasAgg; + memset(&w, 0, sizeof(w)); + w.xExprCallback = resolveExprStep; + w.xSelectCallback = resolveSelectStep; + w.pParse = pNC->pParse; + w.u.pNC = pNC; + sqlite3WalkExpr(&w, pExpr); +#if SQLITE_MAX_EXPR_DEPTH>0 + pNC->pParse->nHeight -= pExpr->nHeight; +#endif + if( pNC->nErr>0 || w.pParse->nErr>0 ){ + ExprSetProperty(pExpr, EP_Error); + } + if( pNC->ncFlags & NC_HasAgg ){ + ExprSetProperty(pExpr, EP_Agg); + }else if( savedHasAgg ){ + pNC->ncFlags |= NC_HasAgg; + } + return ExprHasProperty(pExpr, EP_Error); +} + + +/* +** Resolve all names in all expressions of a SELECT and in all +** decendents of the SELECT, including compounds off of p->pPrior, +** subqueries in expressions, and subqueries used as FROM clause +** terms. +** +** See sqlite3ResolveExprNames() for a description of the kinds of +** transformations that occur. +** +** All SELECT statements should have been expanded using +** sqlite3SelectExpand() prior to invoking this routine. +*/ +SQLITE_PRIVATE void sqlite3ResolveSelectNames( + Parse *pParse, /* The parser context */ + Select *p, /* The SELECT statement being coded. */ + NameContext *pOuterNC /* Name context for parent SELECT statement */ +){ + Walker w; + + assert( p!=0 ); + memset(&w, 0, sizeof(w)); + w.xExprCallback = resolveExprStep; + w.xSelectCallback = resolveSelectStep; + w.pParse = pParse; + w.u.pNC = pOuterNC; + sqlite3WalkSelect(&w, p); +} + +/* +** Resolve names in expressions that can only reference a single table: +** +** * CHECK constraints +** * WHERE clauses on partial indices +** +** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression +** is set to -1 and the Expr.iColumn value is set to the column number. +** +** Any errors cause an error message to be set in pParse. +*/ +SQLITE_PRIVATE void sqlite3ResolveSelfReference( + Parse *pParse, /* Parsing context */ + Table *pTab, /* The table being referenced */ + int type, /* NC_IsCheck or NC_PartIdx */ + Expr *pExpr, /* Expression to resolve. May be NULL. */ + ExprList *pList /* Expression list to resolve. May be NUL. */ +){ + SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ + NameContext sNC; /* Name context for pParse->pNewTable */ + int i; /* Loop counter */ + + assert( type==NC_IsCheck || type==NC_PartIdx ); + memset(&sNC, 0, sizeof(sNC)); + memset(&sSrc, 0, sizeof(sSrc)); + sSrc.nSrc = 1; + sSrc.a[0].zName = pTab->zName; + sSrc.a[0].pTab = pTab; + sSrc.a[0].iCursor = -1; + sNC.pParse = pParse; + sNC.pSrcList = &sSrc; + sNC.ncFlags = type; + if( sqlite3ResolveExprNames(&sNC, pExpr) ) return; + if( pList ){ + for(i=0; inExpr; i++){ + if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){ + return; + } + } + } +} + +/************** End of resolve.c *********************************************/ +/************** Begin file expr.c ********************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains routines used for analyzing expressions and +** for generating VDBE code that evaluates expressions in SQLite. +*/ + +/* +** Return the 'affinity' of the expression pExpr if any. +** +** If pExpr is a column, a reference to a column via an 'AS' alias, +** or a sub-select with a column as the return value, then the +** affinity of that column is returned. Otherwise, 0x00 is returned, +** indicating no affinity for the expression. +** +** i.e. the WHERE clause expresssions in the following statements all +** have an affinity: +** +** CREATE TABLE t1(a); +** SELECT * FROM t1 WHERE a; +** SELECT a AS b FROM t1 WHERE b; +** SELECT * FROM t1 WHERE (select a from t1); +*/ +SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){ + int op; + pExpr = sqlite3ExprSkipCollate(pExpr); + op = pExpr->op; + if( op==TK_SELECT ){ + assert( pExpr->flags&EP_xIsSelect ); + return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); + } +#ifndef SQLITE_OMIT_CAST + if( op==TK_CAST ){ + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + return sqlite3AffinityType(pExpr->u.zToken, 0); + } +#endif + if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) + && pExpr->pTab!=0 + ){ + /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally + ** a TK_COLUMN but was previously evaluated and cached in a register */ + int j = pExpr->iColumn; + if( j<0 ) return SQLITE_AFF_INTEGER; + assert( pExpr->pTab && jpTab->nCol ); + return pExpr->pTab->aCol[j].affinity; + } + return pExpr->affinity; +} + +/* +** Set the collating sequence for expression pExpr to be the collating +** sequence named by pToken. Return a pointer to a new Expr node that +** implements the COLLATE operator. +** +** If a memory allocation error occurs, that fact is recorded in pParse->db +** and the pExpr parameter is returned unchanged. +*/ +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){ + if( pCollName->n>0 ){ + Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1); + if( pNew ){ + pNew->pLeft = pExpr; + pNew->flags |= EP_Collate|EP_Skip; + pExpr = pNew; + } + } + return pExpr; +} +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){ + Token s; + assert( zC!=0 ); + s.z = zC; + s.n = sqlite3Strlen30(s.z); + return sqlite3ExprAddCollateToken(pParse, pExpr, &s); +} + +/* +** Skip over any TK_COLLATE or TK_AS operators and any unlikely() +** or likelihood() function at the root of an expression. +*/ +SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){ + while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ + if( ExprHasProperty(pExpr, EP_Unlikely) ){ + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + assert( pExpr->x.pList->nExpr>0 ); + assert( pExpr->op==TK_FUNCTION ); + pExpr = pExpr->x.pList->a[0].pExpr; + }else{ + assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS ); + pExpr = pExpr->pLeft; + } + } + return pExpr; +} + +/* +** Return the collation sequence for the expression pExpr. If +** there is no defined collating sequence, return NULL. +** +** The collating sequence might be determined by a COLLATE operator +** or by the presence of a column with a defined collating sequence. +** COLLATE operators take first precedence. Left operands take +** precedence over right operands. +*/ +SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ + sqlite3 *db = pParse->db; + CollSeq *pColl = 0; + Expr *p = pExpr; + while( p ){ + int op = p->op; + if( op==TK_CAST || op==TK_UPLUS ){ + p = p->pLeft; + continue; + } + if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){ + pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); + break; + } + if( p->pTab!=0 + && (op==TK_AGG_COLUMN || op==TK_COLUMN + || op==TK_REGISTER || op==TK_TRIGGER) + ){ + /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally + ** a TK_COLUMN but was previously evaluated and cached in a register */ + int j = p->iColumn; + if( j>=0 ){ + const char *zColl = p->pTab->aCol[j].zColl; + pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); + } + break; + } + if( p->flags & EP_Collate ){ + if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){ + p = p->pLeft; + }else{ + p = p->pRight; + } + }else{ + break; + } + } + if( sqlite3CheckCollSeq(pParse, pColl) ){ + pColl = 0; + } + return pColl; +} + +/* +** pExpr is an operand of a comparison operator. aff2 is the +** type affinity of the other operand. This routine returns the +** type affinity that should be used for the comparison operator. +*/ +SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){ + char aff1 = sqlite3ExprAffinity(pExpr); + if( aff1 && aff2 ){ + /* Both sides of the comparison are columns. If one has numeric + ** affinity, use that. Otherwise use no affinity. + */ + if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ + return SQLITE_AFF_NUMERIC; + }else{ + return SQLITE_AFF_NONE; + } + }else if( !aff1 && !aff2 ){ + /* Neither side of the comparison is a column. Compare the + ** results directly. + */ + return SQLITE_AFF_NONE; + }else{ + /* One side is a column, the other is not. Use the columns affinity. */ + assert( aff1==0 || aff2==0 ); + return (aff1 + aff2); + } +} + +/* +** pExpr is a comparison operator. Return the type affinity that should +** be applied to both operands prior to doing the comparison. +*/ +static char comparisonAffinity(Expr *pExpr){ + char aff; + assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || + pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || + pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); + assert( pExpr->pLeft ); + aff = sqlite3ExprAffinity(pExpr->pLeft); + if( pExpr->pRight ){ + aff = sqlite3CompareAffinity(pExpr->pRight, aff); + }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); + }else if( !aff ){ + aff = SQLITE_AFF_NONE; + } + return aff; +} + +/* +** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. +** idx_affinity is the affinity of an indexed column. Return true +** if the index with affinity idx_affinity may be used to implement +** the comparison in pExpr. +*/ +SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ + char aff = comparisonAffinity(pExpr); + switch( aff ){ + case SQLITE_AFF_NONE: + return 1; + case SQLITE_AFF_TEXT: + return idx_affinity==SQLITE_AFF_TEXT; + default: + return sqlite3IsNumericAffinity(idx_affinity); + } +} + +/* +** Return the P5 value that should be used for a binary comparison +** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. +*/ +static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ + u8 aff = (char)sqlite3ExprAffinity(pExpr2); + aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; + return aff; +} + +/* +** Return a pointer to the collation sequence that should be used by +** a binary comparison operator comparing pLeft and pRight. +** +** If the left hand expression has a collating sequence type, then it is +** used. Otherwise the collation sequence for the right hand expression +** is used, or the default (BINARY) if neither expression has a collating +** type. +** +** Argument pRight (but not pLeft) may be a null pointer. In this case, +** it is not considered. +*/ +SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq( + Parse *pParse, + Expr *pLeft, + Expr *pRight +){ + CollSeq *pColl; + assert( pLeft ); + if( pLeft->flags & EP_Collate ){ + pColl = sqlite3ExprCollSeq(pParse, pLeft); + }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ + pColl = sqlite3ExprCollSeq(pParse, pRight); + }else{ + pColl = sqlite3ExprCollSeq(pParse, pLeft); + if( !pColl ){ + pColl = sqlite3ExprCollSeq(pParse, pRight); + } + } + return pColl; +} + +/* +** Generate code for a comparison operator. +*/ +static int codeCompare( + Parse *pParse, /* The parsing (and code generating) context */ + Expr *pLeft, /* The left operand */ + Expr *pRight, /* The right operand */ + int opcode, /* The comparison opcode */ + int in1, int in2, /* Register holding operands */ + int dest, /* Jump here if true. */ + int jumpIfNull /* If true, jump if either operand is NULL */ +){ + int p5; + int addr; + CollSeq *p4; + + p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); + p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); + addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, + (void*)p4, P4_COLLSEQ); + sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); + return addr; +} + +#if SQLITE_MAX_EXPR_DEPTH>0 +/* +** Check that argument nHeight is less than or equal to the maximum +** expression depth allowed. If it is not, leave an error message in +** pParse. +*/ +SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ + int rc = SQLITE_OK; + int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; + if( nHeight>mxHeight ){ + sqlite3ErrorMsg(pParse, + "Expression tree is too large (maximum depth %d)", mxHeight + ); + rc = SQLITE_ERROR; + } + return rc; +} + +/* The following three functions, heightOfExpr(), heightOfExprList() +** and heightOfSelect(), are used to determine the maximum height +** of any expression tree referenced by the structure passed as the +** first argument. +** +** If this maximum height is greater than the current value pointed +** to by pnHeight, the second parameter, then set *pnHeight to that +** value. +*/ +static void heightOfExpr(Expr *p, int *pnHeight){ + if( p ){ + if( p->nHeight>*pnHeight ){ + *pnHeight = p->nHeight; + } + } +} +static void heightOfExprList(ExprList *p, int *pnHeight){ + if( p ){ + int i; + for(i=0; inExpr; i++){ + heightOfExpr(p->a[i].pExpr, pnHeight); + } + } +} +static void heightOfSelect(Select *p, int *pnHeight){ + if( p ){ + heightOfExpr(p->pWhere, pnHeight); + heightOfExpr(p->pHaving, pnHeight); + heightOfExpr(p->pLimit, pnHeight); + heightOfExpr(p->pOffset, pnHeight); + heightOfExprList(p->pEList, pnHeight); + heightOfExprList(p->pGroupBy, pnHeight); + heightOfExprList(p->pOrderBy, pnHeight); + heightOfSelect(p->pPrior, pnHeight); + } +} + +/* +** Set the Expr.nHeight variable in the structure passed as an +** argument. An expression with no children, Expr.pList or +** Expr.pSelect member has a height of 1. Any other expression +** has a height equal to the maximum height of any other +** referenced Expr plus one. +*/ +static void exprSetHeight(Expr *p){ + int nHeight = 0; + heightOfExpr(p->pLeft, &nHeight); + heightOfExpr(p->pRight, &nHeight); + if( ExprHasProperty(p, EP_xIsSelect) ){ + heightOfSelect(p->x.pSelect, &nHeight); + }else{ + heightOfExprList(p->x.pList, &nHeight); + } + p->nHeight = nHeight + 1; +} + +/* +** Set the Expr.nHeight variable using the exprSetHeight() function. If +** the height is greater than the maximum allowed expression depth, +** leave an error in pParse. +*/ +SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){ + exprSetHeight(p); + sqlite3ExprCheckHeight(pParse, p->nHeight); +} + +/* +** Return the maximum height of any expression tree referenced +** by the select statement passed as an argument. +*/ +SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){ + int nHeight = 0; + heightOfSelect(p, &nHeight); + return nHeight; +} +#else + #define exprSetHeight(y) +#endif /* SQLITE_MAX_EXPR_DEPTH>0 */ + +/* +** This routine is the core allocator for Expr nodes. +** +** Construct a new expression node and return a pointer to it. Memory +** for this node and for the pToken argument is a single allocation +** obtained from sqlite3DbMalloc(). The calling function +** is responsible for making sure the node eventually gets freed. +** +** If dequote is true, then the token (if it exists) is dequoted. +** If dequote is false, no dequoting is performance. The deQuote +** parameter is ignored if pToken is NULL or if the token does not +** appear to be quoted. If the quotes were of the form "..." (double-quotes) +** then the EP_DblQuoted flag is set on the expression node. +** +** Special case: If op==TK_INTEGER and pToken points to a string that +** can be translated into a 32-bit integer, then the token is not +** stored in u.zToken. Instead, the integer values is written +** into u.iValue and the EP_IntValue flag is set. No extra storage +** is allocated to hold the integer text and the dequote flag is ignored. +*/ +SQLITE_PRIVATE Expr *sqlite3ExprAlloc( + sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ + int op, /* Expression opcode */ + const Token *pToken, /* Token argument. Might be NULL */ + int dequote /* True to dequote */ +){ + Expr *pNew; + int nExtra = 0; + int iValue = 0; + + if( pToken ){ + if( op!=TK_INTEGER || pToken->z==0 + || sqlite3GetInt32(pToken->z, &iValue)==0 ){ + nExtra = pToken->n+1; + assert( iValue>=0 ); + } + } + pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra); + if( pNew ){ + pNew->op = (u8)op; + pNew->iAgg = -1; + if( pToken ){ + if( nExtra==0 ){ + pNew->flags |= EP_IntValue; + pNew->u.iValue = iValue; + }else{ + int c; + pNew->u.zToken = (char*)&pNew[1]; + assert( pToken->z!=0 || pToken->n==0 ); + if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); + pNew->u.zToken[pToken->n] = 0; + if( dequote && nExtra>=3 + && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){ + sqlite3Dequote(pNew->u.zToken); + if( c=='"' ) pNew->flags |= EP_DblQuoted; + } + } + } +#if SQLITE_MAX_EXPR_DEPTH>0 + pNew->nHeight = 1; +#endif + } + return pNew; +} + +/* +** Allocate a new expression node from a zero-terminated token that has +** already been dequoted. +*/ +SQLITE_PRIVATE Expr *sqlite3Expr( + sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ + int op, /* Expression opcode */ + const char *zToken /* Token argument. Might be NULL */ +){ + Token x; + x.z = zToken; + x.n = zToken ? sqlite3Strlen30(zToken) : 0; + return sqlite3ExprAlloc(db, op, &x, 0); +} + +/* +** Attach subtrees pLeft and pRight to the Expr node pRoot. +** +** If pRoot==NULL that means that a memory allocation error has occurred. +** In that case, delete the subtrees pLeft and pRight. +*/ +SQLITE_PRIVATE void sqlite3ExprAttachSubtrees( + sqlite3 *db, + Expr *pRoot, + Expr *pLeft, + Expr *pRight +){ + if( pRoot==0 ){ + assert( db->mallocFailed ); + sqlite3ExprDelete(db, pLeft); + sqlite3ExprDelete(db, pRight); + }else{ + if( pRight ){ + pRoot->pRight = pRight; + pRoot->flags |= EP_Collate & pRight->flags; + } + if( pLeft ){ + pRoot->pLeft = pLeft; + pRoot->flags |= EP_Collate & pLeft->flags; + } + exprSetHeight(pRoot); + } +} + +/* +** Allocate a Expr node which joins as many as two subtrees. +** +** One or both of the subtrees can be NULL. Return a pointer to the new +** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, +** free the subtrees and return NULL. +*/ +SQLITE_PRIVATE Expr *sqlite3PExpr( + Parse *pParse, /* Parsing context */ + int op, /* Expression opcode */ + Expr *pLeft, /* Left operand */ + Expr *pRight, /* Right operand */ + const Token *pToken /* Argument token */ +){ + Expr *p; + if( op==TK_AND && pLeft && pRight ){ + /* Take advantage of short-circuit false optimization for AND */ + p = sqlite3ExprAnd(pParse->db, pLeft, pRight); + }else{ + p = sqlite3ExprAlloc(pParse->db, op, pToken, 1); + sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); + } + if( p ) { + sqlite3ExprCheckHeight(pParse, p->nHeight); + } + return p; +} + +/* +** Return 1 if an expression must be FALSE in all cases and 0 if the +** expression might be true. This is an optimization. If is OK to +** return 0 here even if the expression really is always false (a +** false negative). But it is a bug to return 1 if the expression +** might be true in some rare circumstances (a false positive.) +** +** Note that if the expression is part of conditional for a +** LEFT JOIN, then we cannot determine at compile-time whether or not +** is it true or false, so always return 0. +*/ +static int exprAlwaysFalse(Expr *p){ + int v = 0; + if( ExprHasProperty(p, EP_FromJoin) ) return 0; + if( !sqlite3ExprIsInteger(p, &v) ) return 0; + return v==0; +} + +/* +** Join two expressions using an AND operator. If either expression is +** NULL, then just return the other expression. +** +** If one side or the other of the AND is known to be false, then instead +** of returning an AND expression, just return a constant expression with +** a value of false. +*/ +SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){ + if( pLeft==0 ){ + return pRight; + }else if( pRight==0 ){ + return pLeft; + }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){ + sqlite3ExprDelete(db, pLeft); + sqlite3ExprDelete(db, pRight); + return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0); + }else{ + Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0); + sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight); + return pNew; + } +} + +/* +** Construct a new expression node for a function with multiple +** arguments. +*/ +SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){ + Expr *pNew; + sqlite3 *db = pParse->db; + assert( pToken ); + pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); + if( pNew==0 ){ + sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ + return 0; + } + pNew->x.pList = pList; + assert( !ExprHasProperty(pNew, EP_xIsSelect) ); + sqlite3ExprSetHeight(pParse, pNew); + return pNew; +} + +/* +** Assign a variable number to an expression that encodes a wildcard +** in the original SQL statement. +** +** Wildcards consisting of a single "?" are assigned the next sequential +** variable number. +** +** Wildcards of the form "?nnn" are assigned the number "nnn". We make +** sure "nnn" is not too be to avoid a denial of service attack when +** the SQL statement comes from an external source. +** +** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number +** as the previous instance of the same wildcard. Or if this is the first +** instance of the wildcard, the next sequenial variable number is +** assigned. +*/ +SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){ + sqlite3 *db = pParse->db; + const char *z; + + if( pExpr==0 ) return; + assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); + z = pExpr->u.zToken; + assert( z!=0 ); + assert( z[0]!=0 ); + if( z[1]==0 ){ + /* Wildcard of the form "?". Assign the next variable number */ + assert( z[0]=='?' ); + pExpr->iColumn = (ynVar)(++pParse->nVar); + }else{ + ynVar x = 0; + u32 n = sqlite3Strlen30(z); + if( z[0]=='?' ){ + /* Wildcard of the form "?nnn". Convert "nnn" to an integer and + ** use it as the variable number */ + i64 i; + int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); + pExpr->iColumn = x = (ynVar)i; + testcase( i==0 ); + testcase( i==1 ); + testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); + testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); + if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ + sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", + db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); + x = 0; + } + if( i>pParse->nVar ){ + pParse->nVar = (int)i; + } + }else{ + /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable + ** number as the prior appearance of the same name, or if the name + ** has never appeared before, reuse the same variable number + */ + ynVar i; + for(i=0; inzVar; i++){ + if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){ + pExpr->iColumn = x = (ynVar)i+1; + break; + } + } + if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar); + } + if( x>0 ){ + if( x>pParse->nzVar ){ + char **a; + a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0])); + if( a==0 ) return; /* Error reported through db->mallocFailed */ + pParse->azVar = a; + memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0])); + pParse->nzVar = x; + } + if( z[0]!='?' || pParse->azVar[x-1]==0 ){ + sqlite3DbFree(db, pParse->azVar[x-1]); + pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n); + } + } + } + if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ + sqlite3ErrorMsg(pParse, "too many SQL variables"); + } +} + +/* +** Recursively delete an expression tree. +*/ +SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){ + if( p==0 ) return; + /* Sanity check: Assert that the IntValue is non-negative if it exists */ + assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 ); + if( !ExprHasProperty(p, EP_TokenOnly) ){ + /* The Expr.x union is never used at the same time as Expr.pRight */ + assert( p->x.pList==0 || p->pRight==0 ); + sqlite3ExprDelete(db, p->pLeft); + sqlite3ExprDelete(db, p->pRight); + if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken); + if( ExprHasProperty(p, EP_xIsSelect) ){ + sqlite3SelectDelete(db, p->x.pSelect); + }else{ + sqlite3ExprListDelete(db, p->x.pList); + } + } + if( !ExprHasProperty(p, EP_Static) ){ + sqlite3DbFree(db, p); + } +} + +/* +** Return the number of bytes allocated for the expression structure +** passed as the first argument. This is always one of EXPR_FULLSIZE, +** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. +*/ +static int exprStructSize(Expr *p){ + if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; + if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; + return EXPR_FULLSIZE; +} + +/* +** The dupedExpr*Size() routines each return the number of bytes required +** to store a copy of an expression or expression tree. They differ in +** how much of the tree is measured. +** +** dupedExprStructSize() Size of only the Expr structure +** dupedExprNodeSize() Size of Expr + space for token +** dupedExprSize() Expr + token + subtree components +** +*************************************************************************** +** +** The dupedExprStructSize() function returns two values OR-ed together: +** (1) the space required for a copy of the Expr structure only and +** (2) the EP_xxx flags that indicate what the structure size should be. +** The return values is always one of: +** +** EXPR_FULLSIZE +** EXPR_REDUCEDSIZE | EP_Reduced +** EXPR_TOKENONLYSIZE | EP_TokenOnly +** +** The size of the structure can be found by masking the return value +** of this routine with 0xfff. The flags can be found by masking the +** return value with EP_Reduced|EP_TokenOnly. +** +** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size +** (unreduced) Expr objects as they or originally constructed by the parser. +** During expression analysis, extra information is computed and moved into +** later parts of teh Expr object and that extra information might get chopped +** off if the expression is reduced. Note also that it does not work to +** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal +** to reduce a pristine expression tree from the parser. The implementation +** of dupedExprStructSize() contain multiple assert() statements that attempt +** to enforce this constraint. +*/ +static int dupedExprStructSize(Expr *p, int flags){ + int nSize; + assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ + assert( EXPR_FULLSIZE<=0xfff ); + assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); + if( 0==(flags&EXPRDUP_REDUCE) ){ + nSize = EXPR_FULLSIZE; + }else{ + assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); + assert( !ExprHasProperty(p, EP_FromJoin) ); + assert( !ExprHasProperty(p, EP_MemToken) ); + assert( !ExprHasProperty(p, EP_NoReduce) ); + if( p->pLeft || p->x.pList ){ + nSize = EXPR_REDUCEDSIZE | EP_Reduced; + }else{ + assert( p->pRight==0 ); + nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; + } + } + return nSize; +} + +/* +** This function returns the space in bytes required to store the copy +** of the Expr structure and a copy of the Expr.u.zToken string (if that +** string is defined.) +*/ +static int dupedExprNodeSize(Expr *p, int flags){ + int nByte = dupedExprStructSize(p, flags) & 0xfff; + if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ + nByte += sqlite3Strlen30(p->u.zToken)+1; + } + return ROUND8(nByte); +} + +/* +** Return the number of bytes required to create a duplicate of the +** expression passed as the first argument. The second argument is a +** mask containing EXPRDUP_XXX flags. +** +** The value returned includes space to create a copy of the Expr struct +** itself and the buffer referred to by Expr.u.zToken, if any. +** +** If the EXPRDUP_REDUCE flag is set, then the return value includes +** space to duplicate all Expr nodes in the tree formed by Expr.pLeft +** and Expr.pRight variables (but not for any structures pointed to or +** descended from the Expr.x.pList or Expr.x.pSelect variables). +*/ +static int dupedExprSize(Expr *p, int flags){ + int nByte = 0; + if( p ){ + nByte = dupedExprNodeSize(p, flags); + if( flags&EXPRDUP_REDUCE ){ + nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags); + } + } + return nByte; +} + +/* +** This function is similar to sqlite3ExprDup(), except that if pzBuffer +** is not NULL then *pzBuffer is assumed to point to a buffer large enough +** to store the copy of expression p, the copies of p->u.zToken +** (if applicable), and the copies of the p->pLeft and p->pRight expressions, +** if any. Before returning, *pzBuffer is set to the first byte passed the +** portion of the buffer copied into by this function. +*/ +static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){ + Expr *pNew = 0; /* Value to return */ + if( p ){ + const int isReduced = (flags&EXPRDUP_REDUCE); + u8 *zAlloc; + u32 staticFlag = 0; + + assert( pzBuffer==0 || isReduced ); + + /* Figure out where to write the new Expr structure. */ + if( pzBuffer ){ + zAlloc = *pzBuffer; + staticFlag = EP_Static; + }else{ + zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags)); + } + pNew = (Expr *)zAlloc; + + if( pNew ){ + /* Set nNewSize to the size allocated for the structure pointed to + ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or + ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed + ** by the copy of the p->u.zToken string (if any). + */ + const unsigned nStructSize = dupedExprStructSize(p, flags); + const int nNewSize = nStructSize & 0xfff; + int nToken; + if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ + nToken = sqlite3Strlen30(p->u.zToken) + 1; + }else{ + nToken = 0; + } + if( isReduced ){ + assert( ExprHasProperty(p, EP_Reduced)==0 ); + memcpy(zAlloc, p, nNewSize); + }else{ + int nSize = exprStructSize(p); + memcpy(zAlloc, p, nSize); + memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize); + } + + /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */ + pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken); + pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); + pNew->flags |= staticFlag; + + /* Copy the p->u.zToken string, if any. */ + if( nToken ){ + char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize]; + memcpy(zToken, p->u.zToken, nToken); + } + + if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){ + /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ + if( ExprHasProperty(p, EP_xIsSelect) ){ + pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced); + }else{ + pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced); + } + } + + /* Fill in pNew->pLeft and pNew->pRight. */ + if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){ + zAlloc += dupedExprNodeSize(p, flags); + if( ExprHasProperty(pNew, EP_Reduced) ){ + pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc); + pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc); + } + if( pzBuffer ){ + *pzBuffer = zAlloc; + } + }else{ + if( !ExprHasProperty(p, EP_TokenOnly) ){ + pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); + pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); + } + } + + } + } + return pNew; +} + +/* +** The following group of routines make deep copies of expressions, +** expression lists, ID lists, and select statements. The copies can +** be deleted (by being passed to their respective ...Delete() routines) +** without effecting the originals. +** +** The expression list, ID, and source lists return by sqlite3ExprListDup(), +** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded +** by subsequent calls to sqlite*ListAppend() routines. +** +** Any tables that the SrcList might point to are not duplicated. +** +** The flags parameter contains a combination of the EXPRDUP_XXX flags. +** If the EXPRDUP_REDUCE flag is set, then the structure returned is a +** truncated version of the usual Expr structure that will be stored as +** part of the in-memory representation of the database schema. +*/ +SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){ + return exprDup(db, p, flags, 0); +} +SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){ + ExprList *pNew; + struct ExprList_item *pItem, *pOldItem; + int i; + if( p==0 ) return 0; + pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) ); + if( pNew==0 ) return 0; + pNew->iECursor = 0; + pNew->nExpr = i = p->nExpr; + if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; inExpr; i+=i){} + pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) ); + if( pItem==0 ){ + sqlite3DbFree(db, pNew); + return 0; + } + pOldItem = p->a; + for(i=0; inExpr; i++, pItem++, pOldItem++){ + Expr *pOldExpr = pOldItem->pExpr; + pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); + pItem->zName = sqlite3DbStrDup(db, pOldItem->zName); + pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan); + pItem->sortOrder = pOldItem->sortOrder; + pItem->done = 0; + pItem->bSpanIsTab = pOldItem->bSpanIsTab; + pItem->iOrderByCol = pOldItem->iOrderByCol; + pItem->iAlias = pOldItem->iAlias; + } + return pNew; +} + +/* +** If cursors, triggers, views and subqueries are all omitted from +** the build, then none of the following routines, except for +** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes +** called with a NULL argument. +*/ +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ + || !defined(SQLITE_OMIT_SUBQUERY) +SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ + SrcList *pNew; + int i; + int nByte; + if( p==0 ) return 0; + nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); + pNew = sqlite3DbMallocRaw(db, nByte ); + if( pNew==0 ) return 0; + pNew->nSrc = pNew->nAlloc = p->nSrc; + for(i=0; inSrc; i++){ + struct SrcList_item *pNewItem = &pNew->a[i]; + struct SrcList_item *pOldItem = &p->a[i]; + Table *pTab; + pNewItem->pSchema = pOldItem->pSchema; + pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); + pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); + pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); + pNewItem->jointype = pOldItem->jointype; + pNewItem->iCursor = pOldItem->iCursor; + pNewItem->addrFillSub = pOldItem->addrFillSub; + pNewItem->regReturn = pOldItem->regReturn; + pNewItem->isCorrelated = pOldItem->isCorrelated; + pNewItem->viaCoroutine = pOldItem->viaCoroutine; + pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex); + pNewItem->notIndexed = pOldItem->notIndexed; + pNewItem->pIndex = pOldItem->pIndex; + pTab = pNewItem->pTab = pOldItem->pTab; + if( pTab ){ + pTab->nRef++; + } + pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); + pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags); + pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); + pNewItem->colUsed = pOldItem->colUsed; + } + return pNew; +} +SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ + IdList *pNew; + int i; + if( p==0 ) return 0; + pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) ); + if( pNew==0 ) return 0; + pNew->nId = p->nId; + pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) ); + if( pNew->a==0 ){ + sqlite3DbFree(db, pNew); + return 0; + } + /* Note that because the size of the allocation for p->a[] is not + ** necessarily a power of two, sqlite3IdListAppend() may not be called + ** on the duplicate created by this function. */ + for(i=0; inId; i++){ + struct IdList_item *pNewItem = &pNew->a[i]; + struct IdList_item *pOldItem = &p->a[i]; + pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); + pNewItem->idx = pOldItem->idx; + } + return pNew; +} +SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ + Select *pNew, *pPrior; + if( p==0 ) return 0; + pNew = sqlite3DbMallocRaw(db, sizeof(*p) ); + if( pNew==0 ) return 0; + pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); + pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); + pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); + pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); + pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); + pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); + pNew->op = p->op; + pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags); + if( pPrior ) pPrior->pNext = pNew; + pNew->pNext = 0; + pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); + pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags); + pNew->iLimit = 0; + pNew->iOffset = 0; + pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; + pNew->pRightmost = 0; + pNew->addrOpenEphm[0] = -1; + pNew->addrOpenEphm[1] = -1; + pNew->addrOpenEphm[2] = -1; + return pNew; +} +#else +SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ + assert( p==0 ); + return 0; +} +#endif + + +/* +** Add a new element to the end of an expression list. If pList is +** initially NULL, then create a new expression list. +** +** If a memory allocation error occurs, the entire list is freed and +** NULL is returned. If non-NULL is returned, then it is guaranteed +** that the new entry was successfully appended. +*/ +SQLITE_PRIVATE ExprList *sqlite3ExprListAppend( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* List to which to append. Might be NULL */ + Expr *pExpr /* Expression to be appended. Might be NULL */ +){ + sqlite3 *db = pParse->db; + if( pList==0 ){ + pList = sqlite3DbMallocZero(db, sizeof(ExprList) ); + if( pList==0 ){ + goto no_mem; + } + pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0])); + if( pList->a==0 ) goto no_mem; + }else if( (pList->nExpr & (pList->nExpr-1))==0 ){ + struct ExprList_item *a; + assert( pList->nExpr>0 ); + a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0])); + if( a==0 ){ + goto no_mem; + } + pList->a = a; + } + assert( pList->a!=0 ); + if( 1 ){ + struct ExprList_item *pItem = &pList->a[pList->nExpr++]; + memset(pItem, 0, sizeof(*pItem)); + pItem->pExpr = pExpr; + } + return pList; + +no_mem: + /* Avoid leaking memory if malloc has failed. */ + sqlite3ExprDelete(db, pExpr); + sqlite3ExprListDelete(db, pList); + return 0; +} + +/* +** Set the ExprList.a[].zName element of the most recently added item +** on the expression list. +** +** pList might be NULL following an OOM error. But pName should never be +** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag +** is set. +*/ +SQLITE_PRIVATE void sqlite3ExprListSetName( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* List to which to add the span. */ + Token *pName, /* Name to be added */ + int dequote /* True to cause the name to be dequoted */ +){ + assert( pList!=0 || pParse->db->mallocFailed!=0 ); + if( pList ){ + struct ExprList_item *pItem; + assert( pList->nExpr>0 ); + pItem = &pList->a[pList->nExpr-1]; + assert( pItem->zName==0 ); + pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); + if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName); + } +} + +/* +** Set the ExprList.a[].zSpan element of the most recently added item +** on the expression list. +** +** pList might be NULL following an OOM error. But pSpan should never be +** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag +** is set. +*/ +SQLITE_PRIVATE void sqlite3ExprListSetSpan( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* List to which to add the span. */ + ExprSpan *pSpan /* The span to be added */ +){ + sqlite3 *db = pParse->db; + assert( pList!=0 || db->mallocFailed!=0 ); + if( pList ){ + struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; + assert( pList->nExpr>0 ); + assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr ); + sqlite3DbFree(db, pItem->zSpan); + pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart, + (int)(pSpan->zEnd - pSpan->zStart)); + } +} + +/* +** If the expression list pEList contains more than iLimit elements, +** leave an error message in pParse. +*/ +SQLITE_PRIVATE void sqlite3ExprListCheckLength( + Parse *pParse, + ExprList *pEList, + const char *zObject +){ + int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; + testcase( pEList && pEList->nExpr==mx ); + testcase( pEList && pEList->nExpr==mx+1 ); + if( pEList && pEList->nExpr>mx ){ + sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); + } +} + +/* +** Delete an entire expression list. +*/ +SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ + int i; + struct ExprList_item *pItem; + if( pList==0 ) return; + assert( pList->a!=0 || pList->nExpr==0 ); + for(pItem=pList->a, i=0; inExpr; i++, pItem++){ + sqlite3ExprDelete(db, pItem->pExpr); + sqlite3DbFree(db, pItem->zName); + sqlite3DbFree(db, pItem->zSpan); + } + sqlite3DbFree(db, pList->a); + sqlite3DbFree(db, pList); +} + +/* +** These routines are Walker callbacks. Walker.u.pi is a pointer +** to an integer. These routines are checking an expression to see +** if it is a constant. Set *Walker.u.pi to 0 if the expression is +** not constant. +** +** These callback routines are used to implement the following: +** +** sqlite3ExprIsConstant() +** sqlite3ExprIsConstantNotJoin() +** sqlite3ExprIsConstantOrFunction() +** +*/ +static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ + + /* If pWalker->u.i is 3 then any term of the expression that comes from + ** the ON or USING clauses of a join disqualifies the expression + ** from being considered constant. */ + if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){ + pWalker->u.i = 0; + return WRC_Abort; + } + + switch( pExpr->op ){ + /* Consider functions to be constant if all their arguments are constant + ** and pWalker->u.i==2 */ + case TK_FUNCTION: + if( pWalker->u.i==2 ) return 0; + /* Fall through */ + case TK_ID: + case TK_COLUMN: + case TK_AGG_FUNCTION: + case TK_AGG_COLUMN: + testcase( pExpr->op==TK_ID ); + testcase( pExpr->op==TK_COLUMN ); + testcase( pExpr->op==TK_AGG_FUNCTION ); + testcase( pExpr->op==TK_AGG_COLUMN ); + pWalker->u.i = 0; + return WRC_Abort; + default: + testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */ + testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */ + return WRC_Continue; + } +} +static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){ + UNUSED_PARAMETER(NotUsed); + pWalker->u.i = 0; + return WRC_Abort; +} +static int exprIsConst(Expr *p, int initFlag){ + Walker w; + memset(&w, 0, sizeof(w)); + w.u.i = initFlag; + w.xExprCallback = exprNodeIsConstant; + w.xSelectCallback = selectNodeIsConstant; + sqlite3WalkExpr(&w, p); + return w.u.i; +} + +/* +** Walk an expression tree. Return 1 if the expression is constant +** and 0 if it involves variables or function calls. +** +** For the purposes of this function, a double-quoted string (ex: "abc") +** is considered a variable but a single-quoted string (ex: 'abc') is +** a constant. +*/ +SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){ + return exprIsConst(p, 1); +} + +/* +** Walk an expression tree. Return 1 if the expression is constant +** that does no originate from the ON or USING clauses of a join. +** Return 0 if it involves variables or function calls or terms from +** an ON or USING clause. +*/ +SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){ + return exprIsConst(p, 3); +} + +/* +** Walk an expression tree. Return 1 if the expression is constant +** or a function call with constant arguments. Return and 0 if there +** are any variables. +** +** For the purposes of this function, a double-quoted string (ex: "abc") +** is considered a variable but a single-quoted string (ex: 'abc') is +** a constant. +*/ +SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){ + return exprIsConst(p, 2); +} + +/* +** If the expression p codes a constant integer that is small enough +** to fit in a 32-bit integer, return 1 and put the value of the integer +** in *pValue. If the expression is not an integer or if it is too big +** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. +*/ +SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){ + int rc = 0; + + /* If an expression is an integer literal that fits in a signed 32-bit + ** integer, then the EP_IntValue flag will have already been set */ + assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 + || sqlite3GetInt32(p->u.zToken, &rc)==0 ); + + if( p->flags & EP_IntValue ){ + *pValue = p->u.iValue; + return 1; + } + switch( p->op ){ + case TK_UPLUS: { + rc = sqlite3ExprIsInteger(p->pLeft, pValue); + break; + } + case TK_UMINUS: { + int v; + if( sqlite3ExprIsInteger(p->pLeft, &v) ){ + assert( v!=(-2147483647-1) ); + *pValue = -v; + rc = 1; + } + break; + } + default: break; + } + return rc; +} + +/* +** Return FALSE if there is no chance that the expression can be NULL. +** +** If the expression might be NULL or if the expression is too complex +** to tell return TRUE. +** +** This routine is used as an optimization, to skip OP_IsNull opcodes +** when we know that a value cannot be NULL. Hence, a false positive +** (returning TRUE when in fact the expression can never be NULL) might +** be a small performance hit but is otherwise harmless. On the other +** hand, a false negative (returning FALSE when the result could be NULL) +** will likely result in an incorrect answer. So when in doubt, return +** TRUE. +*/ +SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){ + u8 op; + while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } + op = p->op; + if( op==TK_REGISTER ) op = p->op2; + switch( op ){ + case TK_INTEGER: + case TK_STRING: + case TK_FLOAT: + case TK_BLOB: + return 0; + default: + return 1; + } +} + +/* +** Generate an OP_IsNull instruction that tests register iReg and jumps +** to location iDest if the value in iReg is NULL. The value in iReg +** was computed by pExpr. If we can look at pExpr at compile-time and +** determine that it can never generate a NULL, then the OP_IsNull operation +** can be omitted. +*/ +SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump( + Vdbe *v, /* The VDBE under construction */ + const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */ + int iReg, /* Test the value in this register for NULL */ + int iDest /* Jump here if the value is null */ +){ + if( sqlite3ExprCanBeNull(pExpr) ){ + sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest); + } +} + +/* +** Return TRUE if the given expression is a constant which would be +** unchanged by OP_Affinity with the affinity given in the second +** argument. +** +** This routine is used to determine if the OP_Affinity operation +** can be omitted. When in doubt return FALSE. A false negative +** is harmless. A false positive, however, can result in the wrong +** answer. +*/ +SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ + u8 op; + if( aff==SQLITE_AFF_NONE ) return 1; + while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } + op = p->op; + if( op==TK_REGISTER ) op = p->op2; + switch( op ){ + case TK_INTEGER: { + return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC; + } + case TK_FLOAT: { + return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC; + } + case TK_STRING: { + return aff==SQLITE_AFF_TEXT; + } + case TK_BLOB: { + return 1; + } + case TK_COLUMN: { + assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ + return p->iColumn<0 + && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC); + } + default: { + return 0; + } + } +} + +/* +** Return TRUE if the given string is a row-id column name. +*/ +SQLITE_PRIVATE int sqlite3IsRowid(const char *z){ + if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; + if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; + if( sqlite3StrICmp(z, "OID")==0 ) return 1; + return 0; +} + +/* +** Return true if we are able to the IN operator optimization on a +** query of the form +** +** x IN (SELECT ...) +** +** Where the SELECT... clause is as specified by the parameter to this +** routine. +** +** The Select object passed in has already been preprocessed and no +** errors have been found. +*/ +#ifndef SQLITE_OMIT_SUBQUERY +static int isCandidateForInOpt(Select *p){ + SrcList *pSrc; + ExprList *pEList; + Table *pTab; + if( p==0 ) return 0; /* right-hand side of IN is SELECT */ + if( p->pPrior ) return 0; /* Not a compound SELECT */ + if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ + testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); + testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); + return 0; /* No DISTINCT keyword and no aggregate functions */ + } + assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ + if( p->pLimit ) return 0; /* Has no LIMIT clause */ + assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */ + if( p->pWhere ) return 0; /* Has no WHERE clause */ + pSrc = p->pSrc; + assert( pSrc!=0 ); + if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ + if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */ + pTab = pSrc->a[0].pTab; + if( NEVER(pTab==0) ) return 0; + assert( pTab->pSelect==0 ); /* FROM clause is not a view */ + if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ + pEList = p->pEList; + if( pEList->nExpr!=1 ) return 0; /* One column in the result set */ + if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */ + return 1; +} +#endif /* SQLITE_OMIT_SUBQUERY */ + +/* +** Code an OP_Once instruction and allocate space for its flag. Return the +** address of the new instruction. +*/ +SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){ + Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ + return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++); +} + +/* +** This function is used by the implementation of the IN (...) operator. +** The pX parameter is the expression on the RHS of the IN operator, which +** might be either a list of expressions or a subquery. +** +** The job of this routine is to find or create a b-tree object that can +** be used either to test for membership in the RHS set or to iterate through +** all members of the RHS set, skipping duplicates. +** +** A cursor is opened on the b-tree object that the RHS of the IN operator +** and pX->iTable is set to the index of that cursor. +** +** The returned value of this function indicates the b-tree type, as follows: +** +** IN_INDEX_ROWID - The cursor was opened on a database table. +** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index. +** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index. +** IN_INDEX_EPH - The cursor was opened on a specially created and +** populated epheremal table. +** +** An existing b-tree might be used if the RHS expression pX is a simple +** subquery such as: +** +** SELECT FROM +** +** If the RHS of the IN operator is a list or a more complex subquery, then +** an ephemeral table might need to be generated from the RHS and then +** pX->iTable made to point to the ephermeral table instead of an +** existing table. +** +** If the prNotFound parameter is 0, then the b-tree will be used to iterate +** through the set members, skipping any duplicates. In this case an +** epheremal table must be used unless the selected is guaranteed +** to be unique - either because it is an INTEGER PRIMARY KEY or it +** has a UNIQUE constraint or UNIQUE index. +** +** If the prNotFound parameter is not 0, then the b-tree will be used +** for fast set membership tests. In this case an epheremal table must +** be used unless is an INTEGER PRIMARY KEY or an index can +** be found with as its left-most column. +** +** When the b-tree is being used for membership tests, the calling function +** needs to know whether or not the structure contains an SQL NULL +** value in order to correctly evaluate expressions like "X IN (Y, Z)". +** If there is any chance that the (...) might contain a NULL value at +** runtime, then a register is allocated and the register number written +** to *prNotFound. If there is no chance that the (...) contains a +** NULL value, then *prNotFound is left unchanged. +** +** If a register is allocated and its location stored in *prNotFound, then +** its initial value is NULL. If the (...) does not remain constant +** for the duration of the query (i.e. the SELECT within the (...) +** is a correlated subquery) then the value of the allocated register is +** reset to NULL each time the subquery is rerun. This allows the +** caller to use vdbe code equivalent to the following: +** +** if( register==NULL ){ +** has_null = +** register = 1 +** } +** +** in order to avoid running the +** test more often than is necessary. +*/ +#ifndef SQLITE_OMIT_SUBQUERY +SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ + Select *p; /* SELECT to the right of IN operator */ + int eType = 0; /* Type of RHS table. IN_INDEX_* */ + int iTab = pParse->nTab++; /* Cursor of the RHS table */ + int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */ + Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ + + assert( pX->op==TK_IN ); + + /* Check to see if an existing table or index can be used to + ** satisfy the query. This is preferable to generating a new + ** ephemeral table. + */ + p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0); + if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){ + sqlite3 *db = pParse->db; /* Database connection */ + Table *pTab; /* Table
. */ + Expr *pExpr; /* Expression */ + int iCol; /* Index of column */ + int iDb; /* Database idx for pTab */ + + assert( p ); /* Because of isCandidateForInOpt(p) */ + assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ + assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */ + assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ + pTab = p->pSrc->a[0].pTab; + pExpr = p->pEList->a[0].pExpr; + iCol = pExpr->iColumn; + + /* Code an OP_VerifyCookie and OP_TableLock for
. */ + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + + /* This function is only called from two places. In both cases the vdbe + ** has already been allocated. So assume sqlite3GetVdbe() is always + ** successful here. + */ + assert(v); + if( iCol<0 ){ + int iAddr; + + iAddr = sqlite3CodeOnce(pParse); + + sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); + eType = IN_INDEX_ROWID; + + sqlite3VdbeJumpHere(v, iAddr); + }else{ + Index *pIdx; /* Iterator variable */ + + /* The collation sequence used by the comparison. If an index is to + ** be used in place of a temp-table, it must be ordered according + ** to this collation sequence. */ + CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr); + + /* Check that the affinity that will be used to perform the + ** comparison is the same as the affinity of the column. If + ** it is not, it is not possible to use any index. + */ + int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity); + + for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){ + if( (pIdx->aiColumn[0]==iCol) + && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq + && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None)) + ){ + int iAddr; + char *pKey; + + pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx); + iAddr = sqlite3CodeOnce(pParse); + + sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb, + pKey,P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIdx->zName)); + assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); + eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; + + sqlite3VdbeJumpHere(v, iAddr); + if( prNotFound && !pTab->aCol[iCol].notNull ){ + *prNotFound = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound); + } + } + } + } + } + + if( eType==0 ){ + /* Could not found an existing table or index to use as the RHS b-tree. + ** We will have to generate an ephemeral table to do the job. + */ + u32 savedNQueryLoop = pParse->nQueryLoop; + int rMayHaveNull = 0; + eType = IN_INDEX_EPH; + if( prNotFound ){ + *prNotFound = rMayHaveNull = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound); + }else{ + testcase( pParse->nQueryLoop>0 ); + pParse->nQueryLoop = 0; + if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){ + eType = IN_INDEX_ROWID; + } + } + sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID); + pParse->nQueryLoop = savedNQueryLoop; + }else{ + pX->iTable = iTab; + } + return eType; +} +#endif + +/* +** Generate code for scalar subqueries used as a subquery expression, EXISTS, +** or IN operators. Examples: +** +** (SELECT a FROM b) -- subquery +** EXISTS (SELECT a FROM b) -- EXISTS subquery +** x IN (4,5,11) -- IN operator with list on right-hand side +** x IN (SELECT a FROM b) -- IN operator with subquery on the right +** +** The pExpr parameter describes the expression that contains the IN +** operator or subquery. +** +** If parameter isRowid is non-zero, then expression pExpr is guaranteed +** to be of the form " IN (?, ?, ?)", where is a reference +** to some integer key column of a table B-Tree. In this case, use an +** intkey B-Tree to store the set of IN(...) values instead of the usual +** (slower) variable length keys B-Tree. +** +** If rMayHaveNull is non-zero, that means that the operation is an IN +** (not a SELECT or EXISTS) and that the RHS might contains NULLs. +** Furthermore, the IN is in a WHERE clause and that we really want +** to iterate over the RHS of the IN operator in order to quickly locate +** all corresponding LHS elements. All this routine does is initialize +** the register given by rMayHaveNull to NULL. Calling routines will take +** care of changing this register value to non-NULL if the RHS is NULL-free. +** +** If rMayHaveNull is zero, that means that the subquery is being used +** for membership testing only. There is no need to initialize any +** registers to indicate the presence or absence of NULLs on the RHS. +** +** For a SELECT or EXISTS operator, return the register that holds the +** result. For IN operators or if an error occurs, the return value is 0. +*/ +#ifndef SQLITE_OMIT_SUBQUERY +SQLITE_PRIVATE int sqlite3CodeSubselect( + Parse *pParse, /* Parsing context */ + Expr *pExpr, /* The IN, SELECT, or EXISTS operator */ + int rMayHaveNull, /* Register that records whether NULLs exist in RHS */ + int isRowid /* If true, LHS of IN operator is a rowid */ +){ + int testAddr = -1; /* One-time test address */ + int rReg = 0; /* Register storing resulting */ + Vdbe *v = sqlite3GetVdbe(pParse); + if( NEVER(v==0) ) return 0; + sqlite3ExprCachePush(pParse); + + /* This code must be run in its entirety every time it is encountered + ** if any of the following is true: + ** + ** * The right-hand side is a correlated subquery + ** * The right-hand side is an expression list containing variables + ** * We are inside a trigger + ** + ** If all of the above are false, then we can run this code just once + ** save the results, and reuse the same result on subsequent invocations. + */ + if( !ExprHasProperty(pExpr, EP_VarSelect) ){ + testAddr = sqlite3CodeOnce(pParse); + } + +#ifndef SQLITE_OMIT_EXPLAIN + if( pParse->explain==2 ){ + char *zMsg = sqlite3MPrintf( + pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ", + pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId + ); + sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); + } +#endif + + switch( pExpr->op ){ + case TK_IN: { + char affinity; /* Affinity of the LHS of the IN */ + int addr; /* Address of OP_OpenEphemeral instruction */ + Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */ + KeyInfo *pKeyInfo = 0; /* Key information */ + + if( rMayHaveNull ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull); + } + + affinity = sqlite3ExprAffinity(pLeft); + + /* Whether this is an 'x IN(SELECT...)' or an 'x IN()' + ** expression it is handled the same way. An ephemeral table is + ** filled with single-field index keys representing the results + ** from the SELECT or the . + ** + ** If the 'x' expression is a column value, or the SELECT... + ** statement returns a column value, then the affinity of that + ** column is used to build the index keys. If both 'x' and the + ** SELECT... statement are columns, then numeric affinity is used + ** if either column has NUMERIC or INTEGER affinity. If neither + ** 'x' nor the SELECT... statement are columns, then numeric affinity + ** is used. + */ + pExpr->iTable = pParse->nTab++; + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid); + if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED); + pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1); + + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + /* Case 1: expr IN (SELECT ...) + ** + ** Generate code to write the results of the select into the temporary + ** table allocated and opened above. + */ + SelectDest dest; + ExprList *pEList; + + assert( !isRowid ); + sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable); + dest.affSdst = (u8)affinity; + assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable ); + pExpr->x.pSelect->iLimit = 0; + testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ + if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){ + sqlite3DbFree(pParse->db, pKeyInfo); + return 0; + } + pEList = pExpr->x.pSelect->pEList; + assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ + assert( pEList!=0 ); + assert( pEList->nExpr>0 ); + pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, + pEList->a[0].pExpr); + }else if( ALWAYS(pExpr->x.pList!=0) ){ + /* Case 2: expr IN (exprlist) + ** + ** For each expression, build an index key from the evaluation and + ** store it in the temporary table. If is a column, then use + ** that columns affinity when building index keys. If is not + ** a column, use numeric affinity. + */ + int i; + ExprList *pList = pExpr->x.pList; + struct ExprList_item *pItem; + int r1, r2, r3; + + if( !affinity ){ + affinity = SQLITE_AFF_NONE; + } + if( pKeyInfo ){ + pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); + } + + /* Loop through each expression in . */ + r1 = sqlite3GetTempReg(pParse); + r2 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_Null, 0, r2); + for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ + Expr *pE2 = pItem->pExpr; + int iValToIns; + + /* If the expression is not constant then we will need to + ** disable the test that was generated above that makes sure + ** this code only executes once. Because for a non-constant + ** expression we need to rerun this code each time. + */ + if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){ + sqlite3VdbeChangeToNoop(v, testAddr); + testAddr = -1; + } + + /* Evaluate the expression and insert it into the temp table */ + if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){ + sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns); + }else{ + r3 = sqlite3ExprCodeTarget(pParse, pE2, r1); + if( isRowid ){ + sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, + sqlite3VdbeCurrentAddr(v)+2); + sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3); + }else{ + sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1); + sqlite3ExprCacheAffinityChange(pParse, r3, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2); + } + } + } + sqlite3ReleaseTempReg(pParse, r1); + sqlite3ReleaseTempReg(pParse, r2); + } + if( pKeyInfo ){ + sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF); + } + break; + } + + case TK_EXISTS: + case TK_SELECT: + default: { + /* If this has to be a scalar SELECT. Generate code to put the + ** value of this select in a memory cell and record the number + ** of the memory cell in iColumn. If this is an EXISTS, write + ** an integer 0 (not exists) or 1 (exists) into a memory cell + ** and record that memory cell in iColumn. + */ + Select *pSel; /* SELECT statement to encode */ + SelectDest dest; /* How to deal with SELECt result */ + + testcase( pExpr->op==TK_EXISTS ); + testcase( pExpr->op==TK_SELECT ); + assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); + + assert( ExprHasProperty(pExpr, EP_xIsSelect) ); + pSel = pExpr->x.pSelect; + sqlite3SelectDestInit(&dest, 0, ++pParse->nMem); + if( pExpr->op==TK_SELECT ){ + dest.eDest = SRT_Mem; + sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm); + VdbeComment((v, "Init subquery result")); + }else{ + dest.eDest = SRT_Exists; + sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); + VdbeComment((v, "Init EXISTS result")); + } + sqlite3ExprDelete(pParse->db, pSel->pLimit); + pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, + &sqlite3IntTokens[1]); + pSel->iLimit = 0; + if( sqlite3Select(pParse, pSel, &dest) ){ + return 0; + } + rReg = dest.iSDParm; + ExprSetVVAProperty(pExpr, EP_NoReduce); + break; + } + } + + if( testAddr>=0 ){ + sqlite3VdbeJumpHere(v, testAddr); + } + sqlite3ExprCachePop(pParse, 1); + + return rReg; +} +#endif /* SQLITE_OMIT_SUBQUERY */ + +#ifndef SQLITE_OMIT_SUBQUERY +/* +** Generate code for an IN expression. +** +** x IN (SELECT ...) +** x IN (value, value, ...) +** +** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS) +** is an array of zero or more values. The expression is true if the LHS is +** contained within the RHS. The value of the expression is unknown (NULL) +** if the LHS is NULL or if the LHS is not contained within the RHS and the +** RHS contains one or more NULL values. +** +** This routine generates code will jump to destIfFalse if the LHS is not +** contained within the RHS. If due to NULLs we cannot determine if the LHS +** is contained in the RHS then jump to destIfNull. If the LHS is contained +** within the RHS then fall through. +*/ +static void sqlite3ExprCodeIN( + Parse *pParse, /* Parsing and code generating context */ + Expr *pExpr, /* The IN expression */ + int destIfFalse, /* Jump here if LHS is not contained in the RHS */ + int destIfNull /* Jump here if the results are unknown due to NULLs */ +){ + int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ + char affinity; /* Comparison affinity to use */ + int eType; /* Type of the RHS */ + int r1; /* Temporary use register */ + Vdbe *v; /* Statement under construction */ + + /* Compute the RHS. After this step, the table with cursor + ** pExpr->iTable will contains the values that make up the RHS. + */ + v = pParse->pVdbe; + assert( v!=0 ); /* OOM detected prior to this routine */ + VdbeNoopComment((v, "begin IN expr")); + eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull); + + /* Figure out the affinity to use to create a key from the results + ** of the expression. affinityStr stores a static string suitable for + ** P4 of OP_MakeRecord. + */ + affinity = comparisonAffinity(pExpr); + + /* Code the LHS, the from " IN (...)". + */ + sqlite3ExprCachePush(pParse); + r1 = sqlite3GetTempReg(pParse); + sqlite3ExprCode(pParse, pExpr->pLeft, r1); + + /* If the LHS is NULL, then the result is either false or NULL depending + ** on whether the RHS is empty or not, respectively. + */ + if( destIfNull==destIfFalse ){ + /* Shortcut for the common case where the false and NULL outcomes are + ** the same. */ + sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); + }else{ + int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); + sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse); + sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); + sqlite3VdbeJumpHere(v, addr1); + } + + if( eType==IN_INDEX_ROWID ){ + /* In this case, the RHS is the ROWID of table b-tree + */ + sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); + sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1); + }else{ + /* In this case, the RHS is an index b-tree. + */ + sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1); + + /* If the set membership test fails, then the result of the + ** "x IN (...)" expression must be either 0 or NULL. If the set + ** contains no NULL values, then the result is 0. If the set + ** contains one or more NULL values, then the result of the + ** expression is also NULL. + */ + if( rRhsHasNull==0 || destIfFalse==destIfNull ){ + /* This branch runs if it is known at compile time that the RHS + ** cannot contain NULL values. This happens as the result + ** of a "NOT NULL" constraint in the database schema. + ** + ** Also run this branch if NULL is equivalent to FALSE + ** for this particular IN operator. + */ + sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1); + + }else{ + /* In this branch, the RHS of the IN might contain a NULL and + ** the presence of a NULL on the RHS makes a difference in the + ** outcome. + */ + int j1, j2, j3; + + /* First check to see if the LHS is contained in the RHS. If so, + ** then the presence of NULLs in the RHS does not matter, so jump + ** over all of the code that follows. + */ + j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1); + + /* Here we begin generating code that runs if the LHS is not + ** contained within the RHS. Generate additional code that + ** tests the RHS for NULLs. If the RHS contains a NULL then + ** jump to destIfNull. If there are no NULLs in the RHS then + ** jump to destIfFalse. + */ + j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull); + j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1); + sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull); + sqlite3VdbeJumpHere(v, j3); + sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1); + sqlite3VdbeJumpHere(v, j2); + + /* Jump to the appropriate target depending on whether or not + ** the RHS contains a NULL + */ + sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull); + sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); + + /* The OP_Found at the top of this branch jumps here when true, + ** causing the overall IN expression evaluation to fall through. + */ + sqlite3VdbeJumpHere(v, j1); + } + } + sqlite3ReleaseTempReg(pParse, r1); + sqlite3ExprCachePop(pParse, 1); + VdbeComment((v, "end IN expr")); +} +#endif /* SQLITE_OMIT_SUBQUERY */ + +/* +** Duplicate an 8-byte value +*/ +static char *dup8bytes(Vdbe *v, const char *in){ + char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8); + if( out ){ + memcpy(out, in, 8); + } + return out; +} + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* +** Generate an instruction that will put the floating point +** value described by z[0..n-1] into register iMem. +** +** The z[] string will probably not be zero-terminated. But the +** z[n] character is guaranteed to be something that does not look +** like the continuation of the number. +*/ +static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ + if( ALWAYS(z!=0) ){ + double value; + char *zV; + sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); + assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ + if( negateFlag ) value = -value; + zV = dup8bytes(v, (char*)&value); + sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL); + } +} +#endif + + +/* +** Generate an instruction that will put the integer describe by +** text z[0..n-1] into register iMem. +** +** Expr.u.zToken is always UTF8 and zero-terminated. +*/ +static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ + Vdbe *v = pParse->pVdbe; + if( pExpr->flags & EP_IntValue ){ + int i = pExpr->u.iValue; + assert( i>=0 ); + if( negFlag ) i = -i; + sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); + }else{ + int c; + i64 value; + const char *z = pExpr->u.zToken; + assert( z!=0 ); + c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); + if( c==0 || (c==2 && negFlag) ){ + char *zV; + if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; } + zV = dup8bytes(v, (char*)&value); + sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64); + }else{ +#ifdef SQLITE_OMIT_FLOATING_POINT + sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); +#else + codeReal(v, z, negFlag, iMem); +#endif + } + } +} + +/* +** Clear a cache entry. +*/ +static void cacheEntryClear(Parse *pParse, struct yColCache *p){ + if( p->tempReg ){ + if( pParse->nTempRegaTempReg) ){ + pParse->aTempReg[pParse->nTempReg++] = p->iReg; + } + p->tempReg = 0; + } +} + + +/* +** Record in the column cache that a particular column from a +** particular table is stored in a particular register. +*/ +SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){ + int i; + int minLru; + int idxLru; + struct yColCache *p; + + assert( iReg>0 ); /* Register numbers are always positive */ + assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */ + + /* The SQLITE_ColumnCache flag disables the column cache. This is used + ** for testing only - to verify that SQLite always gets the same answer + ** with and without the column cache. + */ + if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return; + + /* First replace any existing entry. + ** + ** Actually, the way the column cache is currently used, we are guaranteed + ** that the object will never already be in cache. Verify this guarantee. + */ +#ifndef NDEBUG + for(i=0, p=pParse->aColCache; iiReg==0 || p->iTable!=iTab || p->iColumn!=iCol ); + } +#endif + + /* Find an empty slot and replace it */ + for(i=0, p=pParse->aColCache; iiReg==0 ){ + p->iLevel = pParse->iCacheLevel; + p->iTable = iTab; + p->iColumn = iCol; + p->iReg = iReg; + p->tempReg = 0; + p->lru = pParse->iCacheCnt++; + return; + } + } + + /* Replace the last recently used */ + minLru = 0x7fffffff; + idxLru = -1; + for(i=0, p=pParse->aColCache; ilrulru; + } + } + if( ALWAYS(idxLru>=0) ){ + p = &pParse->aColCache[idxLru]; + p->iLevel = pParse->iCacheLevel; + p->iTable = iTab; + p->iColumn = iCol; + p->iReg = iReg; + p->tempReg = 0; + p->lru = pParse->iCacheCnt++; + return; + } +} + +/* +** Indicate that registers between iReg..iReg+nReg-1 are being overwritten. +** Purge the range of registers from the column cache. +*/ +SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){ + int i; + int iLast = iReg + nReg - 1; + struct yColCache *p; + for(i=0, p=pParse->aColCache; iiReg; + if( r>=iReg && r<=iLast ){ + cacheEntryClear(pParse, p); + p->iReg = 0; + } + } +} + +/* +** Remember the current column cache context. Any new entries added +** added to the column cache after this call are removed when the +** corresponding pop occurs. +*/ +SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){ + pParse->iCacheLevel++; +} + +/* +** Remove from the column cache any entries that were added since the +** the previous N Push operations. In other words, restore the cache +** to the state it was in N Pushes ago. +*/ +SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){ + int i; + struct yColCache *p; + assert( N>0 ); + assert( pParse->iCacheLevel>=N ); + pParse->iCacheLevel -= N; + for(i=0, p=pParse->aColCache; iiReg && p->iLevel>pParse->iCacheLevel ){ + cacheEntryClear(pParse, p); + p->iReg = 0; + } + } +} + +/* +** When a cached column is reused, make sure that its register is +** no longer available as a temp register. ticket #3879: that same +** register might be in the cache in multiple places, so be sure to +** get them all. +*/ +static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){ + int i; + struct yColCache *p; + for(i=0, p=pParse->aColCache; iiReg==iReg ){ + p->tempReg = 0; + } + } +} + +/* +** Generate code to extract the value of the iCol-th column of a table. +*/ +SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable( + Vdbe *v, /* The VDBE under construction */ + Table *pTab, /* The table containing the value */ + int iTabCur, /* The cursor for this table */ + int iCol, /* Index of the column to extract */ + int regOut /* Extract the valud into this register */ +){ + if( iCol<0 || iCol==pTab->iPKey ){ + sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); + }else{ + int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; + sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut); + } + if( iCol>=0 ){ + sqlite3ColumnDefault(v, pTab, iCol, regOut); + } +} + +/* +** Generate code that will extract the iColumn-th column from +** table pTab and store the column value in a register. An effort +** is made to store the column value in register iReg, but this is +** not guaranteed. The location of the column value is returned. +** +** There must be an open cursor to pTab in iTable when this routine +** is called. If iColumn<0 then code is generated that extracts the rowid. +*/ +SQLITE_PRIVATE int sqlite3ExprCodeGetColumn( + Parse *pParse, /* Parsing and code generating context */ + Table *pTab, /* Description of the table we are reading from */ + int iColumn, /* Index of the table column */ + int iTable, /* The cursor pointing to the table */ + int iReg, /* Store results here */ + u8 p5 /* P5 value for OP_Column */ +){ + Vdbe *v = pParse->pVdbe; + int i; + struct yColCache *p; + + for(i=0, p=pParse->aColCache; iiReg>0 && p->iTable==iTable && p->iColumn==iColumn ){ + p->lru = pParse->iCacheCnt++; + sqlite3ExprCachePinRegister(pParse, p->iReg); + return p->iReg; + } + } + assert( v!=0 ); + sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg); + if( p5 ){ + sqlite3VdbeChangeP5(v, p5); + }else{ + sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg); + } + return iReg; +} + +/* +** Clear all column cache entries. +*/ +SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){ + int i; + struct yColCache *p; + + for(i=0, p=pParse->aColCache; iiReg ){ + cacheEntryClear(pParse, p); + p->iReg = 0; + } + } +} + +/* +** Record the fact that an affinity change has occurred on iCount +** registers starting with iStart. +*/ +SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){ + sqlite3ExprCacheRemove(pParse, iStart, iCount); +} + +/* +** Generate code to move content from registers iFrom...iFrom+nReg-1 +** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. +*/ +SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ + int i; + struct yColCache *p; + assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo ); + sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1); + for(i=0, p=pParse->aColCache; iiReg; + if( x>=iFrom && xiReg += iTo-iFrom; + } + } +} + +#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) +/* +** Return true if any register in the range iFrom..iTo (inclusive) +** is used as part of the column cache. +** +** This routine is used within assert() and testcase() macros only +** and does not appear in a normal build. +*/ +static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){ + int i; + struct yColCache *p; + for(i=0, p=pParse->aColCache; iiReg; + if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/ + } + return 0; +} +#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */ + +/* +** Convert an expression node to a TK_REGISTER +*/ +static void exprToRegister(Expr *p, int iReg){ + p->op2 = p->op; + p->op = TK_REGISTER; + p->iTable = iReg; + ExprClearProperty(p, EP_Skip); +} + +/* +** Generate code into the current Vdbe to evaluate the given +** expression. Attempt to store the results in register "target". +** Return the register where results are stored. +** +** With this routine, there is no guarantee that results will +** be stored in target. The result might be stored in some other +** register if it is convenient to do so. The calling function +** must check the return code and move the results to the desired +** register. +*/ +SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ + Vdbe *v = pParse->pVdbe; /* The VM under construction */ + int op; /* The opcode being coded */ + int inReg = target; /* Results stored in register inReg */ + int regFree1 = 0; /* If non-zero free this temporary register */ + int regFree2 = 0; /* If non-zero free this temporary register */ + int r1, r2, r3, r4; /* Various register numbers */ + sqlite3 *db = pParse->db; /* The database connection */ + + assert( target>0 && target<=pParse->nMem ); + if( v==0 ){ + assert( pParse->db->mallocFailed ); + return 0; + } + + if( pExpr==0 ){ + op = TK_NULL; + }else{ + op = pExpr->op; + } + switch( op ){ + case TK_AGG_COLUMN: { + AggInfo *pAggInfo = pExpr->pAggInfo; + struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; + if( !pAggInfo->directMode ){ + assert( pCol->iMem>0 ); + inReg = pCol->iMem; + break; + }else if( pAggInfo->useSortingIdx ){ + sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, + pCol->iSorterColumn, target); + break; + } + /* Otherwise, fall thru into the TK_COLUMN case */ + } + case TK_COLUMN: { + int iTab = pExpr->iTable; + if( iTab<0 ){ + if( pParse->ckBase>0 ){ + /* Generating CHECK constraints or inserting into partial index */ + inReg = pExpr->iColumn + pParse->ckBase; + break; + }else{ + /* Deleting from a partial index */ + iTab = pParse->iPartIdxTab; + } + } + inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab, + pExpr->iColumn, iTab, target, + pExpr->op2); + break; + } + case TK_INTEGER: { + codeInteger(pParse, pExpr, 0, target); + break; + } +#ifndef SQLITE_OMIT_FLOATING_POINT + case TK_FLOAT: { + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + codeReal(v, pExpr->u.zToken, 0, target); + break; + } +#endif + case TK_STRING: { + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0); + break; + } + case TK_NULL: { + sqlite3VdbeAddOp2(v, OP_Null, 0, target); + break; + } +#ifndef SQLITE_OMIT_BLOB_LITERAL + case TK_BLOB: { + int n; + const char *z; + char *zBlob; + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); + assert( pExpr->u.zToken[1]=='\'' ); + z = &pExpr->u.zToken[2]; + n = sqlite3Strlen30(z) - 1; + assert( z[n]=='\'' ); + zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); + sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); + break; + } +#endif + case TK_VARIABLE: { + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + assert( pExpr->u.zToken!=0 ); + assert( pExpr->u.zToken[0]!=0 ); + sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); + if( pExpr->u.zToken[1]!=0 ){ + assert( pExpr->u.zToken[0]=='?' + || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 ); + sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC); + } + break; + } + case TK_REGISTER: { + inReg = pExpr->iTable; + break; + } + case TK_AS: { + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + break; + } +#ifndef SQLITE_OMIT_CAST + case TK_CAST: { + /* Expressions of the form: CAST(pLeft AS token) */ + int aff, to_op; + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + aff = sqlite3AffinityType(pExpr->u.zToken, 0); + to_op = aff - SQLITE_AFF_TEXT + OP_ToText; + assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT ); + assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE ); + assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC ); + assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER ); + assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL ); + testcase( to_op==OP_ToText ); + testcase( to_op==OP_ToBlob ); + testcase( to_op==OP_ToNumeric ); + testcase( to_op==OP_ToInt ); + testcase( to_op==OP_ToReal ); + if( inReg!=target ){ + sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); + inReg = target; + } + sqlite3VdbeAddOp1(v, to_op, inReg); + testcase( usedAsColumnCache(pParse, inReg, inReg) ); + sqlite3ExprCacheAffinityChange(pParse, inReg, 1); + break; + } +#endif /* SQLITE_OMIT_CAST */ + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_NE: + case TK_EQ: { + assert( TK_LT==OP_Lt ); + assert( TK_LE==OP_Le ); + assert( TK_GT==OP_Gt ); + assert( TK_GE==OP_Ge ); + assert( TK_EQ==OP_Eq ); + assert( TK_NE==OP_Ne ); + testcase( op==TK_LT ); + testcase( op==TK_LE ); + testcase( op==TK_GT ); + testcase( op==TK_GE ); + testcase( op==TK_EQ ); + testcase( op==TK_NE ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, inReg, SQLITE_STOREP2); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_IS: + case TK_ISNOT: { + testcase( op==TK_IS ); + testcase( op==TK_ISNOT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + op = (op==TK_IS) ? TK_EQ : TK_NE; + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_AND: + case TK_OR: + case TK_PLUS: + case TK_STAR: + case TK_MINUS: + case TK_REM: + case TK_BITAND: + case TK_BITOR: + case TK_SLASH: + case TK_LSHIFT: + case TK_RSHIFT: + case TK_CONCAT: { + assert( TK_AND==OP_And ); + assert( TK_OR==OP_Or ); + assert( TK_PLUS==OP_Add ); + assert( TK_MINUS==OP_Subtract ); + assert( TK_REM==OP_Remainder ); + assert( TK_BITAND==OP_BitAnd ); + assert( TK_BITOR==OP_BitOr ); + assert( TK_SLASH==OP_Divide ); + assert( TK_LSHIFT==OP_ShiftLeft ); + assert( TK_RSHIFT==OP_ShiftRight ); + assert( TK_CONCAT==OP_Concat ); + testcase( op==TK_AND ); + testcase( op==TK_OR ); + testcase( op==TK_PLUS ); + testcase( op==TK_MINUS ); + testcase( op==TK_REM ); + testcase( op==TK_BITAND ); + testcase( op==TK_BITOR ); + testcase( op==TK_SLASH ); + testcase( op==TK_LSHIFT ); + testcase( op==TK_RSHIFT ); + testcase( op==TK_CONCAT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + sqlite3VdbeAddOp3(v, op, r2, r1, target); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_UMINUS: { + Expr *pLeft = pExpr->pLeft; + assert( pLeft ); + if( pLeft->op==TK_INTEGER ){ + codeInteger(pParse, pLeft, 1, target); +#ifndef SQLITE_OMIT_FLOATING_POINT + }else if( pLeft->op==TK_FLOAT ){ + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + codeReal(v, pLeft->u.zToken, 1, target); +#endif + }else{ + regFree1 = r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_Integer, 0, r1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); + sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); + testcase( regFree2==0 ); + } + inReg = target; + break; + } + case TK_BITNOT: + case TK_NOT: { + assert( TK_BITNOT==OP_BitNot ); + assert( TK_NOT==OP_Not ); + testcase( op==TK_BITNOT ); + testcase( op==TK_NOT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + testcase( regFree1==0 ); + inReg = target; + sqlite3VdbeAddOp2(v, op, r1, inReg); + break; + } + case TK_ISNULL: + case TK_NOTNULL: { + int addr; + assert( TK_ISNULL==OP_IsNull ); + assert( TK_NOTNULL==OP_NotNull ); + testcase( op==TK_ISNULL ); + testcase( op==TK_NOTNULL ); + sqlite3VdbeAddOp2(v, OP_Integer, 1, target); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + testcase( regFree1==0 ); + addr = sqlite3VdbeAddOp1(v, op, r1); + sqlite3VdbeAddOp2(v, OP_AddImm, target, -1); + sqlite3VdbeJumpHere(v, addr); + break; + } + case TK_AGG_FUNCTION: { + AggInfo *pInfo = pExpr->pAggInfo; + if( pInfo==0 ){ + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); + }else{ + inReg = pInfo->aFunc[pExpr->iAgg].iMem; + } + break; + } + case TK_CONST_FUNC: + case TK_FUNCTION: { + ExprList *pFarg; /* List of function arguments */ + int nFarg; /* Number of function arguments */ + FuncDef *pDef; /* The function definition object */ + int nId; /* Length of the function name in bytes */ + const char *zId; /* The function name */ + int constMask = 0; /* Mask of function arguments that are constant */ + int i; /* Loop counter */ + u8 enc = ENC(db); /* The text encoding used by this database */ + CollSeq *pColl = 0; /* A collating sequence */ + + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + testcase( op==TK_CONST_FUNC ); + testcase( op==TK_FUNCTION ); + if( ExprHasProperty(pExpr, EP_TokenOnly) ){ + pFarg = 0; + }else{ + pFarg = pExpr->x.pList; + } + nFarg = pFarg ? pFarg->nExpr : 0; + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + zId = pExpr->u.zToken; + nId = sqlite3Strlen30(zId); + pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0); + if( pDef==0 ){ + sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId); + break; + } + + /* Attempt a direct implementation of the built-in COALESCE() and + ** IFNULL() functions. This avoids unnecessary evalation of + ** arguments past the first non-NULL argument. + */ + if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){ + int endCoalesce = sqlite3VdbeMakeLabel(v); + assert( nFarg>=2 ); + sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); + for(i=1; ia[i].pExpr, target); + sqlite3ExprCachePop(pParse, 1); + } + sqlite3VdbeResolveLabel(v, endCoalesce); + break; + } + + /* The UNLIKELY() function is a no-op. The result is the value + ** of the first argument. + */ + if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ + assert( nFarg>=1 ); + sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); + break; + } + + if( pFarg ){ + r1 = sqlite3GetTempRange(pParse, nFarg); + + /* For length() and typeof() functions with a column argument, + ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG + ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data + ** loading. + */ + if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){ + u8 exprOp; + assert( nFarg==1 ); + assert( pFarg->a[0].pExpr!=0 ); + exprOp = pFarg->a[0].pExpr->op; + if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){ + assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG ); + assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG ); + testcase( (pDef->funcFlags&~SQLITE_FUNC_ENCMASK) + ==SQLITE_FUNC_LENGTH ); + pFarg->a[0].pExpr->op2 = pDef->funcFlags&~SQLITE_FUNC_ENCMASK; + } + } + + sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */ + sqlite3ExprCodeExprList(pParse, pFarg, r1, 1); + sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */ + }else{ + r1 = 0; + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + /* Possibly overload the function if the first argument is + ** a virtual table column. + ** + ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the + ** second argument, not the first, as the argument to test to + ** see if it is a column in a virtual table. This is done because + ** the left operand of infix functions (the operand we want to + ** control overloading) ends up as the second argument to the + ** function. The expression "A glob B" is equivalent to + ** "glob(B,A). We want to use the A in "A glob B" to test + ** for function overloading. But we use the B term in "glob(B,A)". + */ + if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){ + pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); + }else if( nFarg>0 ){ + pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); + } +#endif + for(i=0; ia[i].pExpr) ){ + constMask |= (1<funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ + pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); + } + } + if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ + if( !pColl ) pColl = db->pDfltColl; + sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); + } + sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target, + (char*)pDef, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, (u8)nFarg); + if( nFarg ){ + sqlite3ReleaseTempRange(pParse, r1, nFarg); + } + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_EXISTS: + case TK_SELECT: { + testcase( op==TK_EXISTS ); + testcase( op==TK_SELECT ); + inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0); + break; + } + case TK_IN: { + int destIfFalse = sqlite3VdbeMakeLabel(v); + int destIfNull = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp2(v, OP_Null, 0, target); + sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); + sqlite3VdbeAddOp2(v, OP_Integer, 1, target); + sqlite3VdbeResolveLabel(v, destIfFalse); + sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); + sqlite3VdbeResolveLabel(v, destIfNull); + break; + } +#endif /* SQLITE_OMIT_SUBQUERY */ + + + /* + ** x BETWEEN y AND z + ** + ** This is equivalent to + ** + ** x>=y AND x<=z + ** + ** X is stored in pExpr->pLeft. + ** Y is stored in pExpr->pList->a[0].pExpr. + ** Z is stored in pExpr->pList->a[1].pExpr. + */ + case TK_BETWEEN: { + Expr *pLeft = pExpr->pLeft; + struct ExprList_item *pLItem = pExpr->x.pList->a; + Expr *pRight = pLItem->pExpr; + + r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + r3 = sqlite3GetTempReg(pParse); + r4 = sqlite3GetTempReg(pParse); + codeCompare(pParse, pLeft, pRight, OP_Ge, + r1, r2, r3, SQLITE_STOREP2); + pLItem++; + pRight = pLItem->pExpr; + sqlite3ReleaseTempReg(pParse, regFree2); + r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2); + testcase( regFree2==0 ); + codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2); + sqlite3VdbeAddOp3(v, OP_And, r3, r4, target); + sqlite3ReleaseTempReg(pParse, r3); + sqlite3ReleaseTempReg(pParse, r4); + break; + } + case TK_COLLATE: + case TK_UPLUS: { + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + break; + } + + case TK_TRIGGER: { + /* If the opcode is TK_TRIGGER, then the expression is a reference + ** to a column in the new.* or old.* pseudo-tables available to + ** trigger programs. In this case Expr.iTable is set to 1 for the + ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn + ** is set to the column of the pseudo-table to read, or to -1 to + ** read the rowid field. + ** + ** The expression is implemented using an OP_Param opcode. The p1 + ** parameter is set to 0 for an old.rowid reference, or to (i+1) + ** to reference another column of the old.* pseudo-table, where + ** i is the index of the column. For a new.rowid reference, p1 is + ** set to (n+1), where n is the number of columns in each pseudo-table. + ** For a reference to any other column in the new.* pseudo-table, p1 + ** is set to (n+2+i), where n and i are as defined previously. For + ** example, if the table on which triggers are being fired is + ** declared as: + ** + ** CREATE TABLE t1(a, b); + ** + ** Then p1 is interpreted as follows: + ** + ** p1==0 -> old.rowid p1==3 -> new.rowid + ** p1==1 -> old.a p1==4 -> new.a + ** p1==2 -> old.b p1==5 -> new.b + */ + Table *pTab = pExpr->pTab; + int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn; + + assert( pExpr->iTable==0 || pExpr->iTable==1 ); + assert( pExpr->iColumn>=-1 && pExpr->iColumnnCol ); + assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey ); + assert( p1>=0 && p1<(pTab->nCol*2+2) ); + + sqlite3VdbeAddOp2(v, OP_Param, p1, target); + VdbeComment((v, "%s.%s -> $%d", + (pExpr->iTable ? "new" : "old"), + (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName), + target + )); + +#ifndef SQLITE_OMIT_FLOATING_POINT + /* If the column has REAL affinity, it may currently be stored as an + ** integer. Use OP_RealAffinity to make sure it is really real. */ + if( pExpr->iColumn>=0 + && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL + ){ + sqlite3VdbeAddOp1(v, OP_RealAffinity, target); + } +#endif + break; + } + + + /* + ** Form A: + ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END + ** + ** Form B: + ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END + ** + ** Form A is can be transformed into the equivalent form B as follows: + ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... + ** WHEN x=eN THEN rN ELSE y END + ** + ** X (if it exists) is in pExpr->pLeft. + ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is + ** odd. The Y is also optional. If the number of elements in x.pList + ** is even, then Y is omitted and the "otherwise" result is NULL. + ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. + ** + ** The result of the expression is the Ri for the first matching Ei, + ** or if there is no matching Ei, the ELSE term Y, or if there is + ** no ELSE term, NULL. + */ + default: assert( op==TK_CASE ); { + int endLabel; /* GOTO label for end of CASE stmt */ + int nextCase; /* GOTO label for next WHEN clause */ + int nExpr; /* 2x number of WHEN terms */ + int i; /* Loop counter */ + ExprList *pEList; /* List of WHEN terms */ + struct ExprList_item *aListelem; /* Array of WHEN terms */ + Expr opCompare; /* The X==Ei expression */ + Expr cacheX; /* Cached expression X */ + Expr *pX; /* The X expression */ + Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ + VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; ) + + assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList ); + assert(pExpr->x.pList->nExpr > 0); + pEList = pExpr->x.pList; + aListelem = pEList->a; + nExpr = pEList->nExpr; + endLabel = sqlite3VdbeMakeLabel(v); + if( (pX = pExpr->pLeft)!=0 ){ + cacheX = *pX; + testcase( pX->op==TK_COLUMN ); + testcase( pX->op==TK_REGISTER ); + exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, ®Free1)); + testcase( regFree1==0 ); + opCompare.op = TK_EQ; + opCompare.pLeft = &cacheX; + pTest = &opCompare; + /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: + ** The value in regFree1 might get SCopy-ed into the file result. + ** So make sure that the regFree1 register is not reused for other + ** purposes and possibly overwritten. */ + regFree1 = 0; + } + for(i=0; iop==TK_COLUMN ); + sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); + testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); + testcase( aListelem[i+1].pExpr->op==TK_REGISTER ); + sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); + sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel); + sqlite3ExprCachePop(pParse, 1); + sqlite3VdbeResolveLabel(v, nextCase); + } + if( (nExpr&1)!=0 ){ + sqlite3ExprCachePush(pParse); + sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); + sqlite3ExprCachePop(pParse, 1); + }else{ + sqlite3VdbeAddOp2(v, OP_Null, 0, target); + } + assert( db->mallocFailed || pParse->nErr>0 + || pParse->iCacheLevel==iCacheLevel ); + sqlite3VdbeResolveLabel(v, endLabel); + break; + } +#ifndef SQLITE_OMIT_TRIGGER + case TK_RAISE: { + assert( pExpr->affinity==OE_Rollback + || pExpr->affinity==OE_Abort + || pExpr->affinity==OE_Fail + || pExpr->affinity==OE_Ignore + ); + if( !pParse->pTriggerTab ){ + sqlite3ErrorMsg(pParse, + "RAISE() may only be used within a trigger-program"); + return 0; + } + if( pExpr->affinity==OE_Abort ){ + sqlite3MayAbort(pParse); + } + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + if( pExpr->affinity==OE_Ignore ){ + sqlite3VdbeAddOp4( + v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); + }else{ + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER, + pExpr->affinity, pExpr->u.zToken, 0); + } + + break; + } +#endif + } + sqlite3ReleaseTempReg(pParse, regFree1); + sqlite3ReleaseTempReg(pParse, regFree2); + return inReg; +} + +/* +** Generate code to evaluate an expression and store the results +** into a register. Return the register number where the results +** are stored. +** +** If the register is a temporary register that can be deallocated, +** then write its number into *pReg. If the result register is not +** a temporary, then set *pReg to zero. +*/ +SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ + int r1 = sqlite3GetTempReg(pParse); + int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); + if( r2==r1 ){ + *pReg = r1; + }else{ + sqlite3ReleaseTempReg(pParse, r1); + *pReg = 0; + } + return r2; +} + +/* +** Generate code that will evaluate expression pExpr and store the +** results in register target. The results are guaranteed to appear +** in register target. +*/ +SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ + int inReg; + + assert( target>0 && target<=pParse->nMem ); + if( pExpr && pExpr->op==TK_REGISTER ){ + sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target); + }else{ + inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); + assert( pParse->pVdbe || pParse->db->mallocFailed ); + if( inReg!=target && pParse->pVdbe ){ + sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target); + } + } + return target; +} + +/* +** Generate code that evalutes the given expression and puts the result +** in register target. +** +** Also make a copy of the expression results into another "cache" register +** and modify the expression so that the next time it is evaluated, +** the result is a copy of the cache register. +** +** This routine is used for expressions that are used multiple +** times. They are evaluated once and the results of the expression +** are reused. +*/ +SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ + Vdbe *v = pParse->pVdbe; + int inReg; + inReg = sqlite3ExprCode(pParse, pExpr, target); + assert( target>0 ); + /* This routine is called for terms to INSERT or UPDATE. And the only + ** other place where expressions can be converted into TK_REGISTER is + ** in WHERE clause processing. So as currently implemented, there is + ** no way for a TK_REGISTER to exist here. But it seems prudent to + ** keep the ALWAYS() in case the conditions above change with future + ** modifications or enhancements. */ + if( ALWAYS(pExpr->op!=TK_REGISTER) ){ + int iMem; + iMem = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem); + exprToRegister(pExpr, iMem); + } + return inReg; +} + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) +/* +** Generate a human-readable explanation of an expression tree. +*/ +SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){ + int op; /* The opcode being coded */ + const char *zBinOp = 0; /* Binary operator */ + const char *zUniOp = 0; /* Unary operator */ + if( pExpr==0 ){ + op = TK_NULL; + }else{ + op = pExpr->op; + } + switch( op ){ + case TK_AGG_COLUMN: { + sqlite3ExplainPrintf(pOut, "AGG{%d:%d}", + pExpr->iTable, pExpr->iColumn); + break; + } + case TK_COLUMN: { + if( pExpr->iTable<0 ){ + /* This only happens when coding check constraints */ + sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn); + }else{ + sqlite3ExplainPrintf(pOut, "{%d:%d}", + pExpr->iTable, pExpr->iColumn); + } + break; + } + case TK_INTEGER: { + if( pExpr->flags & EP_IntValue ){ + sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue); + }else{ + sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken); + } + break; + } +#ifndef SQLITE_OMIT_FLOATING_POINT + case TK_FLOAT: { + sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken); + break; + } +#endif + case TK_STRING: { + sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken); + break; + } + case TK_NULL: { + sqlite3ExplainPrintf(pOut,"NULL"); + break; + } +#ifndef SQLITE_OMIT_BLOB_LITERAL + case TK_BLOB: { + sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken); + break; + } +#endif + case TK_VARIABLE: { + sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)", + pExpr->u.zToken, pExpr->iColumn); + break; + } + case TK_REGISTER: { + sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable); + break; + } + case TK_AS: { + sqlite3ExplainExpr(pOut, pExpr->pLeft); + break; + } +#ifndef SQLITE_OMIT_CAST + case TK_CAST: { + /* Expressions of the form: CAST(pLeft AS token) */ + const char *zAff = "unk"; + switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){ + case SQLITE_AFF_TEXT: zAff = "TEXT"; break; + case SQLITE_AFF_NONE: zAff = "NONE"; break; + case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break; + case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break; + case SQLITE_AFF_REAL: zAff = "REAL"; break; + } + sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut, ")"); + break; + } +#endif /* SQLITE_OMIT_CAST */ + case TK_LT: zBinOp = "LT"; break; + case TK_LE: zBinOp = "LE"; break; + case TK_GT: zBinOp = "GT"; break; + case TK_GE: zBinOp = "GE"; break; + case TK_NE: zBinOp = "NE"; break; + case TK_EQ: zBinOp = "EQ"; break; + case TK_IS: zBinOp = "IS"; break; + case TK_ISNOT: zBinOp = "ISNOT"; break; + case TK_AND: zBinOp = "AND"; break; + case TK_OR: zBinOp = "OR"; break; + case TK_PLUS: zBinOp = "ADD"; break; + case TK_STAR: zBinOp = "MUL"; break; + case TK_MINUS: zBinOp = "SUB"; break; + case TK_REM: zBinOp = "REM"; break; + case TK_BITAND: zBinOp = "BITAND"; break; + case TK_BITOR: zBinOp = "BITOR"; break; + case TK_SLASH: zBinOp = "DIV"; break; + case TK_LSHIFT: zBinOp = "LSHIFT"; break; + case TK_RSHIFT: zBinOp = "RSHIFT"; break; + case TK_CONCAT: zBinOp = "CONCAT"; break; + + case TK_UMINUS: zUniOp = "UMINUS"; break; + case TK_UPLUS: zUniOp = "UPLUS"; break; + case TK_BITNOT: zUniOp = "BITNOT"; break; + case TK_NOT: zUniOp = "NOT"; break; + case TK_ISNULL: zUniOp = "ISNULL"; break; + case TK_NOTNULL: zUniOp = "NOTNULL"; break; + + case TK_COLLATE: { + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken); + break; + } + + case TK_AGG_FUNCTION: + case TK_CONST_FUNC: + case TK_FUNCTION: { + ExprList *pFarg; /* List of function arguments */ + if( ExprHasProperty(pExpr, EP_TokenOnly) ){ + pFarg = 0; + }else{ + pFarg = pExpr->x.pList; + } + if( op==TK_AGG_FUNCTION ){ + sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(", + pExpr->op2, pExpr->u.zToken); + }else{ + sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken); + } + if( pFarg ){ + sqlite3ExplainExprList(pOut, pFarg); + } + sqlite3ExplainPrintf(pOut, ")"); + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_EXISTS: { + sqlite3ExplainPrintf(pOut, "EXISTS("); + sqlite3ExplainSelect(pOut, pExpr->x.pSelect); + sqlite3ExplainPrintf(pOut,")"); + break; + } + case TK_SELECT: { + sqlite3ExplainPrintf(pOut, "("); + sqlite3ExplainSelect(pOut, pExpr->x.pSelect); + sqlite3ExplainPrintf(pOut, ")"); + break; + } + case TK_IN: { + sqlite3ExplainPrintf(pOut, "IN("); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut, ","); + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + sqlite3ExplainSelect(pOut, pExpr->x.pSelect); + }else{ + sqlite3ExplainExprList(pOut, pExpr->x.pList); + } + sqlite3ExplainPrintf(pOut, ")"); + break; + } +#endif /* SQLITE_OMIT_SUBQUERY */ + + /* + ** x BETWEEN y AND z + ** + ** This is equivalent to + ** + ** x>=y AND x<=z + ** + ** X is stored in pExpr->pLeft. + ** Y is stored in pExpr->pList->a[0].pExpr. + ** Z is stored in pExpr->pList->a[1].pExpr. + */ + case TK_BETWEEN: { + Expr *pX = pExpr->pLeft; + Expr *pY = pExpr->x.pList->a[0].pExpr; + Expr *pZ = pExpr->x.pList->a[1].pExpr; + sqlite3ExplainPrintf(pOut, "BETWEEN("); + sqlite3ExplainExpr(pOut, pX); + sqlite3ExplainPrintf(pOut, ","); + sqlite3ExplainExpr(pOut, pY); + sqlite3ExplainPrintf(pOut, ","); + sqlite3ExplainExpr(pOut, pZ); + sqlite3ExplainPrintf(pOut, ")"); + break; + } + case TK_TRIGGER: { + /* If the opcode is TK_TRIGGER, then the expression is a reference + ** to a column in the new.* or old.* pseudo-tables available to + ** trigger programs. In this case Expr.iTable is set to 1 for the + ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn + ** is set to the column of the pseudo-table to read, or to -1 to + ** read the rowid field. + */ + sqlite3ExplainPrintf(pOut, "%s(%d)", + pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn); + break; + } + case TK_CASE: { + sqlite3ExplainPrintf(pOut, "CASE("); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut, ","); + sqlite3ExplainExprList(pOut, pExpr->x.pList); + break; + } +#ifndef SQLITE_OMIT_TRIGGER + case TK_RAISE: { + const char *zType = "unk"; + switch( pExpr->affinity ){ + case OE_Rollback: zType = "rollback"; break; + case OE_Abort: zType = "abort"; break; + case OE_Fail: zType = "fail"; break; + case OE_Ignore: zType = "ignore"; break; + } + sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken); + break; + } +#endif + } + if( zBinOp ){ + sqlite3ExplainPrintf(pOut,"%s(", zBinOp); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut,","); + sqlite3ExplainExpr(pOut, pExpr->pRight); + sqlite3ExplainPrintf(pOut,")"); + }else if( zUniOp ){ + sqlite3ExplainPrintf(pOut,"%s(", zUniOp); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut,")"); + } +} +#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */ + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) +/* +** Generate a human-readable explanation of an expression list. +*/ +SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){ + int i; + if( pList==0 || pList->nExpr==0 ){ + sqlite3ExplainPrintf(pOut, "(empty-list)"); + return; + }else if( pList->nExpr==1 ){ + sqlite3ExplainExpr(pOut, pList->a[0].pExpr); + }else{ + sqlite3ExplainPush(pOut); + for(i=0; inExpr; i++){ + sqlite3ExplainPrintf(pOut, "item[%d] = ", i); + sqlite3ExplainPush(pOut); + sqlite3ExplainExpr(pOut, pList->a[i].pExpr); + sqlite3ExplainPop(pOut); + if( pList->a[i].zName ){ + sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName); + } + if( pList->a[i].bSpanIsTab ){ + sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan); + } + if( inExpr-1 ){ + sqlite3ExplainNL(pOut); + } + } + sqlite3ExplainPop(pOut); + } +} +#endif /* SQLITE_DEBUG */ + +/* +** Return TRUE if pExpr is an constant expression that is appropriate +** for factoring out of a loop. Appropriate expressions are: +** +** * Any expression that evaluates to two or more opcodes. +** +** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, +** or OP_Variable that does not need to be placed in a +** specific register. +** +** There is no point in factoring out single-instruction constant +** expressions that need to be placed in a particular register. +** We could factor them out, but then we would end up adding an +** OP_SCopy instruction to move the value into the correct register +** later. We might as well just use the original instruction and +** avoid the OP_SCopy. +*/ +static int isAppropriateForFactoring(Expr *p){ + if( !sqlite3ExprIsConstantNotJoin(p) ){ + return 0; /* Only constant expressions are appropriate for factoring */ + } + if( (p->flags & EP_FixedDest)==0 ){ + return 1; /* Any constant without a fixed destination is appropriate */ + } + while( p->op==TK_UPLUS ) p = p->pLeft; + switch( p->op ){ +#ifndef SQLITE_OMIT_BLOB_LITERAL + case TK_BLOB: +#endif + case TK_VARIABLE: + case TK_INTEGER: + case TK_FLOAT: + case TK_NULL: + case TK_STRING: { + testcase( p->op==TK_BLOB ); + testcase( p->op==TK_VARIABLE ); + testcase( p->op==TK_INTEGER ); + testcase( p->op==TK_FLOAT ); + testcase( p->op==TK_NULL ); + testcase( p->op==TK_STRING ); + /* Single-instruction constants with a fixed destination are + ** better done in-line. If we factor them, they will just end + ** up generating an OP_SCopy to move the value to the destination + ** register. */ + return 0; + } + case TK_UMINUS: { + if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){ + return 0; + } + break; + } + default: { + break; + } + } + return 1; +} + +/* +** If pExpr is a constant expression that is appropriate for +** factoring out of a loop, then evaluate the expression +** into a register and convert the expression into a TK_REGISTER +** expression. +*/ +static int evalConstExpr(Walker *pWalker, Expr *pExpr){ + Parse *pParse = pWalker->pParse; + switch( pExpr->op ){ + case TK_IN: + case TK_REGISTER: { + return WRC_Prune; + } + case TK_COLLATE: { + return WRC_Continue; + } + case TK_FUNCTION: + case TK_AGG_FUNCTION: + case TK_CONST_FUNC: { + /* The arguments to a function have a fixed destination. + ** Mark them this way to avoid generated unneeded OP_SCopy + ** instructions. + */ + ExprList *pList = pExpr->x.pList; + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + if( pList ){ + int i = pList->nExpr; + struct ExprList_item *pItem = pList->a; + for(; i>0; i--, pItem++){ + if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest; + } + } + break; + } + } + if( isAppropriateForFactoring(pExpr) ){ + int r1 = ++pParse->nMem; + int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); + /* If r2!=r1, it means that register r1 is never used. That is harmless + ** but suboptimal, so we want to know about the situation to fix it. + ** Hence the following assert: */ + assert( r2==r1 ); + exprToRegister(pExpr, r2); + return WRC_Prune; + } + return WRC_Continue; +} + +/* +** Preevaluate constant subexpressions within pExpr and store the +** results in registers. Modify pExpr so that the constant subexpresions +** are TK_REGISTER opcodes that refer to the precomputed values. +** +** This routine is a no-op if the jump to the cookie-check code has +** already occur. Since the cookie-check jump is generated prior to +** any other serious processing, this check ensures that there is no +** way to accidently bypass the constant initializations. +** +** This routine is also a no-op if the SQLITE_FactorOutConst optimization +** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS) +** interface. This allows test logic to verify that the same answer is +** obtained for queries regardless of whether or not constants are +** precomputed into registers or if they are inserted in-line. +*/ +SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){ + Walker w; + if( pParse->cookieGoto ) return; + if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return; + memset(&w, 0, sizeof(w)); + w.xExprCallback = evalConstExpr; + w.pParse = pParse; + sqlite3WalkExpr(&w, pExpr); +} + + +/* +** Generate code that pushes the value of every element of the given +** expression list into a sequence of registers beginning at target. +** +** Return the number of elements evaluated. +*/ +SQLITE_PRIVATE int sqlite3ExprCodeExprList( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* The expression list to be coded */ + int target, /* Where to write results */ + int doHardCopy /* Make a hard copy of every element */ +){ + struct ExprList_item *pItem; + int i, n; + assert( pList!=0 ); + assert( target>0 ); + assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */ + n = pList->nExpr; + for(pItem=pList->a, i=0; ipExpr; + int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); + if( inReg!=target+i ){ + sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy, + inReg, target+i); + } + } + return n; +} + +/* +** Generate code for a BETWEEN operator. +** +** x BETWEEN y AND z +** +** The above is equivalent to +** +** x>=y AND x<=z +** +** Code it as such, taking care to do the common subexpression +** elementation of x. +*/ +static void exprCodeBetween( + Parse *pParse, /* Parsing and code generating context */ + Expr *pExpr, /* The BETWEEN expression */ + int dest, /* Jump here if the jump is taken */ + int jumpIfTrue, /* Take the jump if the BETWEEN is true */ + int jumpIfNull /* Take the jump if the BETWEEN is NULL */ +){ + Expr exprAnd; /* The AND operator in x>=y AND x<=z */ + Expr compLeft; /* The x>=y term */ + Expr compRight; /* The x<=z term */ + Expr exprX; /* The x subexpression */ + int regFree1 = 0; /* Temporary use register */ + + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + exprX = *pExpr->pLeft; + exprAnd.op = TK_AND; + exprAnd.pLeft = &compLeft; + exprAnd.pRight = &compRight; + compLeft.op = TK_GE; + compLeft.pLeft = &exprX; + compLeft.pRight = pExpr->x.pList->a[0].pExpr; + compRight.op = TK_LE; + compRight.pLeft = &exprX; + compRight.pRight = pExpr->x.pList->a[1].pExpr; + exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, ®Free1)); + if( jumpIfTrue ){ + sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull); + }else{ + sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull); + } + sqlite3ReleaseTempReg(pParse, regFree1); + + /* Ensure adequate test coverage */ + testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 ); + testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 ); + testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 ); + testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 ); + testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 ); + testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 ); + testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 ); + testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 ); +} + +/* +** Generate code for a boolean expression such that a jump is made +** to the label "dest" if the expression is true but execution +** continues straight thru if the expression is false. +** +** If the expression evaluates to NULL (neither true nor false), then +** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. +** +** This code depends on the fact that certain token values (ex: TK_EQ) +** are the same as opcode values (ex: OP_Eq) that implement the corresponding +** operation. Special comments in vdbe.c and the mkopcodeh.awk script in +** the make process cause these values to align. Assert()s in the code +** below verify that the numbers are aligned correctly. +*/ +SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ + Vdbe *v = pParse->pVdbe; + int op = 0; + int regFree1 = 0; + int regFree2 = 0; + int r1, r2; + + assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); + if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ + if( NEVER(pExpr==0) ) return; /* No way this can happen */ + op = pExpr->op; + switch( op ){ + case TK_AND: { + int d2 = sqlite3VdbeMakeLabel(v); + testcase( jumpIfNull==0 ); + sqlite3ExprCachePush(pParse); + sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL); + sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); + sqlite3VdbeResolveLabel(v, d2); + sqlite3ExprCachePop(pParse, 1); + break; + } + case TK_OR: { + testcase( jumpIfNull==0 ); + sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); + sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); + break; + } + case TK_NOT: { + testcase( jumpIfNull==0 ); + sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); + break; + } + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_NE: + case TK_EQ: { + assert( TK_LT==OP_Lt ); + assert( TK_LE==OP_Le ); + assert( TK_GT==OP_Gt ); + assert( TK_GE==OP_Ge ); + assert( TK_EQ==OP_Eq ); + assert( TK_NE==OP_Ne ); + testcase( op==TK_LT ); + testcase( op==TK_LE ); + testcase( op==TK_GT ); + testcase( op==TK_GE ); + testcase( op==TK_EQ ); + testcase( op==TK_NE ); + testcase( jumpIfNull==0 ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, jumpIfNull); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_IS: + case TK_ISNOT: { + testcase( op==TK_IS ); + testcase( op==TK_ISNOT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + op = (op==TK_IS) ? TK_EQ : TK_NE; + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, SQLITE_NULLEQ); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_ISNULL: + case TK_NOTNULL: { + assert( TK_ISNULL==OP_IsNull ); + assert( TK_NOTNULL==OP_NotNull ); + testcase( op==TK_ISNULL ); + testcase( op==TK_NOTNULL ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + sqlite3VdbeAddOp2(v, op, r1, dest); + testcase( regFree1==0 ); + break; + } + case TK_BETWEEN: { + testcase( jumpIfNull==0 ); + exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull); + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_IN: { + int destIfFalse = sqlite3VdbeMakeLabel(v); + int destIfNull = jumpIfNull ? dest : destIfFalse; + sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); + sqlite3VdbeAddOp2(v, OP_Goto, 0, dest); + sqlite3VdbeResolveLabel(v, destIfFalse); + break; + } +#endif + default: { + r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); + sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); + testcase( regFree1==0 ); + testcase( jumpIfNull==0 ); + break; + } + } + sqlite3ReleaseTempReg(pParse, regFree1); + sqlite3ReleaseTempReg(pParse, regFree2); +} + +/* +** Generate code for a boolean expression such that a jump is made +** to the label "dest" if the expression is false but execution +** continues straight thru if the expression is true. +** +** If the expression evaluates to NULL (neither true nor false) then +** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull +** is 0. +*/ +SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ + Vdbe *v = pParse->pVdbe; + int op = 0; + int regFree1 = 0; + int regFree2 = 0; + int r1, r2; + + assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); + if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ + if( pExpr==0 ) return; + + /* The value of pExpr->op and op are related as follows: + ** + ** pExpr->op op + ** --------- ---------- + ** TK_ISNULL OP_NotNull + ** TK_NOTNULL OP_IsNull + ** TK_NE OP_Eq + ** TK_EQ OP_Ne + ** TK_GT OP_Le + ** TK_LE OP_Gt + ** TK_GE OP_Lt + ** TK_LT OP_Ge + ** + ** For other values of pExpr->op, op is undefined and unused. + ** The value of TK_ and OP_ constants are arranged such that we + ** can compute the mapping above using the following expression. + ** Assert()s verify that the computation is correct. + */ + op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); + + /* Verify correct alignment of TK_ and OP_ constants + */ + assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); + assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); + assert( pExpr->op!=TK_NE || op==OP_Eq ); + assert( pExpr->op!=TK_EQ || op==OP_Ne ); + assert( pExpr->op!=TK_LT || op==OP_Ge ); + assert( pExpr->op!=TK_LE || op==OP_Gt ); + assert( pExpr->op!=TK_GT || op==OP_Le ); + assert( pExpr->op!=TK_GE || op==OP_Lt ); + + switch( pExpr->op ){ + case TK_AND: { + testcase( jumpIfNull==0 ); + sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); + sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); + break; + } + case TK_OR: { + int d2 = sqlite3VdbeMakeLabel(v); + testcase( jumpIfNull==0 ); + sqlite3ExprCachePush(pParse); + sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL); + sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); + sqlite3VdbeResolveLabel(v, d2); + sqlite3ExprCachePop(pParse, 1); + break; + } + case TK_NOT: { + testcase( jumpIfNull==0 ); + sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); + break; + } + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_NE: + case TK_EQ: { + testcase( op==TK_LT ); + testcase( op==TK_LE ); + testcase( op==TK_GT ); + testcase( op==TK_GE ); + testcase( op==TK_EQ ); + testcase( op==TK_NE ); + testcase( jumpIfNull==0 ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, jumpIfNull); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_IS: + case TK_ISNOT: { + testcase( pExpr->op==TK_IS ); + testcase( pExpr->op==TK_ISNOT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, SQLITE_NULLEQ); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_ISNULL: + case TK_NOTNULL: { + testcase( op==TK_ISNULL ); + testcase( op==TK_NOTNULL ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + sqlite3VdbeAddOp2(v, op, r1, dest); + testcase( regFree1==0 ); + break; + } + case TK_BETWEEN: { + testcase( jumpIfNull==0 ); + exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull); + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_IN: { + if( jumpIfNull ){ + sqlite3ExprCodeIN(pParse, pExpr, dest, dest); + }else{ + int destIfNull = sqlite3VdbeMakeLabel(v); + sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); + sqlite3VdbeResolveLabel(v, destIfNull); + } + break; + } +#endif + default: { + r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); + sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); + testcase( regFree1==0 ); + testcase( jumpIfNull==0 ); + break; + } + } + sqlite3ReleaseTempReg(pParse, regFree1); + sqlite3ReleaseTempReg(pParse, regFree2); +} + +/* +** Do a deep comparison of two expression trees. Return 0 if the two +** expressions are completely identical. Return 1 if they differ only +** by a COLLATE operator at the top level. Return 2 if there are differences +** other than the top-level COLLATE operator. +** +** If any subelement of pB has Expr.iTable==(-1) then it is allowed +** to compare equal to an equivalent element in pA with Expr.iTable==iTab. +** +** The pA side might be using TK_REGISTER. If that is the case and pB is +** not using TK_REGISTER but is otherwise equivalent, then still return 0. +** +** Sometimes this routine will return 2 even if the two expressions +** really are equivalent. If we cannot prove that the expressions are +** identical, we return 2 just to be safe. So if this routine +** returns 2, then you do not really know for certain if the two +** expressions are the same. But if you get a 0 or 1 return, then you +** can be sure the expressions are the same. In the places where +** this routine is used, it does not hurt to get an extra 2 - that +** just might result in some slightly slower code. But returning +** an incorrect 0 or 1 could lead to a malfunction. +*/ +SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){ + if( pA==0||pB==0 ){ + return pB==pA ? 0 : 2; + } + assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) ); + assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) ); + if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){ + return 2; + } + if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2; + if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){ + if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){ + return 1; + } + if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){ + return 1; + } + return 2; + } + if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2; + if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2; + if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; + if( pA->iColumn!=pB->iColumn ) return 2; + if( pA->iTable!=pB->iTable + && pA->op!=TK_REGISTER + && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2; + if( ExprHasProperty(pA, EP_IntValue) ){ + if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){ + return 2; + } + }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){ + if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2; + if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ + return pA->op==TK_COLLATE ? 1 : 2; + } + } + return 0; +} + +/* +** Compare two ExprList objects. Return 0 if they are identical and +** non-zero if they differ in any way. +** +** If any subelement of pB has Expr.iTable==(-1) then it is allowed +** to compare equal to an equivalent element in pA with Expr.iTable==iTab. +** +** This routine might return non-zero for equivalent ExprLists. The +** only consequence will be disabled optimizations. But this routine +** must never return 0 if the two ExprList objects are different, or +** a malfunction will result. +** +** Two NULL pointers are considered to be the same. But a NULL pointer +** always differs from a non-NULL pointer. +*/ +SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ + int i; + if( pA==0 && pB==0 ) return 0; + if( pA==0 || pB==0 ) return 1; + if( pA->nExpr!=pB->nExpr ) return 1; + for(i=0; inExpr; i++){ + Expr *pExprA = pA->a[i].pExpr; + Expr *pExprB = pB->a[i].pExpr; + if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1; + if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1; + } + return 0; +} + +/* +** Return true if we can prove the pE2 will always be true if pE1 is +** true. Return false if we cannot complete the proof or if pE2 might +** be false. Examples: +** +** pE1: x==5 pE2: x==5 Result: true +** pE1: x>0 pE2: x==5 Result: false +** pE1: x=21 pE2: x=21 OR y=43 Result: true +** pE1: x!=123 pE2: x IS NOT NULL Result: true +** pE1: x!=?1 pE2: x IS NOT NULL Result: true +** pE1: x IS NULL pE2: x IS NOT NULL Result: false +** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false +** +** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has +** Expr.iTable<0 then assume a table number given by iTab. +** +** When in doubt, return false. Returning true might give a performance +** improvement. Returning false might cause a performance reduction, but +** it will always give the correct answer and is hence always safe. +*/ +SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){ + if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){ + return 1; + } + if( pE2->op==TK_OR + && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab) + || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) ) + ){ + return 1; + } + if( pE2->op==TK_NOTNULL + && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0 + && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS) + ){ + return 1; + } + return 0; +} + +/* +** An instance of the following structure is used by the tree walker +** to count references to table columns in the arguments of an +** aggregate function, in order to implement the +** sqlite3FunctionThisSrc() routine. +*/ +struct SrcCount { + SrcList *pSrc; /* One particular FROM clause in a nested query */ + int nThis; /* Number of references to columns in pSrcList */ + int nOther; /* Number of references to columns in other FROM clauses */ +}; + +/* +** Count the number of references to columns. +*/ +static int exprSrcCount(Walker *pWalker, Expr *pExpr){ + /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc() + ** is always called before sqlite3ExprAnalyzeAggregates() and so the + ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If + ** sqlite3FunctionUsesThisSrc() is used differently in the future, the + ** NEVER() will need to be removed. */ + if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){ + int i; + struct SrcCount *p = pWalker->u.pSrcCount; + SrcList *pSrc = p->pSrc; + for(i=0; inSrc; i++){ + if( pExpr->iTable==pSrc->a[i].iCursor ) break; + } + if( inSrc ){ + p->nThis++; + }else{ + p->nOther++; + } + } + return WRC_Continue; +} + +/* +** Determine if any of the arguments to the pExpr Function reference +** pSrcList. Return true if they do. Also return true if the function +** has no arguments or has only constant arguments. Return false if pExpr +** references columns but not columns of tables found in pSrcList. +*/ +SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ + Walker w; + struct SrcCount cnt; + assert( pExpr->op==TK_AGG_FUNCTION ); + memset(&w, 0, sizeof(w)); + w.xExprCallback = exprSrcCount; + w.u.pSrcCount = &cnt; + cnt.pSrc = pSrcList; + cnt.nThis = 0; + cnt.nOther = 0; + sqlite3WalkExprList(&w, pExpr->x.pList); + return cnt.nThis>0 || cnt.nOther==0; +} + +/* +** Add a new element to the pAggInfo->aCol[] array. Return the index of +** the new element. Return a negative number if malloc fails. +*/ +static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ + int i; + pInfo->aCol = sqlite3ArrayAllocate( + db, + pInfo->aCol, + sizeof(pInfo->aCol[0]), + &pInfo->nColumn, + &i + ); + return i; +} + +/* +** Add a new element to the pAggInfo->aFunc[] array. Return the index of +** the new element. Return a negative number if malloc fails. +*/ +static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ + int i; + pInfo->aFunc = sqlite3ArrayAllocate( + db, + pInfo->aFunc, + sizeof(pInfo->aFunc[0]), + &pInfo->nFunc, + &i + ); + return i; +} + +/* +** This is the xExprCallback for a tree walker. It is used to +** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates +** for additional information. +*/ +static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ + int i; + NameContext *pNC = pWalker->u.pNC; + Parse *pParse = pNC->pParse; + SrcList *pSrcList = pNC->pSrcList; + AggInfo *pAggInfo = pNC->pAggInfo; + + switch( pExpr->op ){ + case TK_AGG_COLUMN: + case TK_COLUMN: { + testcase( pExpr->op==TK_AGG_COLUMN ); + testcase( pExpr->op==TK_COLUMN ); + /* Check to see if the column is in one of the tables in the FROM + ** clause of the aggregate query */ + if( ALWAYS(pSrcList!=0) ){ + struct SrcList_item *pItem = pSrcList->a; + for(i=0; inSrc; i++, pItem++){ + struct AggInfo_col *pCol; + assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); + if( pExpr->iTable==pItem->iCursor ){ + /* If we reach this point, it means that pExpr refers to a table + ** that is in the FROM clause of the aggregate query. + ** + ** Make an entry for the column in pAggInfo->aCol[] if there + ** is not an entry there already. + */ + int k; + pCol = pAggInfo->aCol; + for(k=0; knColumn; k++, pCol++){ + if( pCol->iTable==pExpr->iTable && + pCol->iColumn==pExpr->iColumn ){ + break; + } + } + if( (k>=pAggInfo->nColumn) + && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 + ){ + pCol = &pAggInfo->aCol[k]; + pCol->pTab = pExpr->pTab; + pCol->iTable = pExpr->iTable; + pCol->iColumn = pExpr->iColumn; + pCol->iMem = ++pParse->nMem; + pCol->iSorterColumn = -1; + pCol->pExpr = pExpr; + if( pAggInfo->pGroupBy ){ + int j, n; + ExprList *pGB = pAggInfo->pGroupBy; + struct ExprList_item *pTerm = pGB->a; + n = pGB->nExpr; + for(j=0; jpExpr; + if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable && + pE->iColumn==pExpr->iColumn ){ + pCol->iSorterColumn = j; + break; + } + } + } + if( pCol->iSorterColumn<0 ){ + pCol->iSorterColumn = pAggInfo->nSortingColumn++; + } + } + /* There is now an entry for pExpr in pAggInfo->aCol[] (either + ** because it was there before or because we just created it). + ** Convert the pExpr to be a TK_AGG_COLUMN referring to that + ** pAggInfo->aCol[] entry. + */ + ExprSetVVAProperty(pExpr, EP_NoReduce); + pExpr->pAggInfo = pAggInfo; + pExpr->op = TK_AGG_COLUMN; + pExpr->iAgg = (i16)k; + break; + } /* endif pExpr->iTable==pItem->iCursor */ + } /* end loop over pSrcList */ + } + return WRC_Prune; + } + case TK_AGG_FUNCTION: { + if( (pNC->ncFlags & NC_InAggFunc)==0 + && pWalker->walkerDepth==pExpr->op2 + ){ + /* Check to see if pExpr is a duplicate of another aggregate + ** function that is already in the pAggInfo structure + */ + struct AggInfo_func *pItem = pAggInfo->aFunc; + for(i=0; inFunc; i++, pItem++){ + if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){ + break; + } + } + if( i>=pAggInfo->nFunc ){ + /* pExpr is original. Make a new entry in pAggInfo->aFunc[] + */ + u8 enc = ENC(pParse->db); + i = addAggInfoFunc(pParse->db, pAggInfo); + if( i>=0 ){ + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + pItem = &pAggInfo->aFunc[i]; + pItem->pExpr = pExpr; + pItem->iMem = ++pParse->nMem; + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + pItem->pFunc = sqlite3FindFunction(pParse->db, + pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken), + pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0); + if( pExpr->flags & EP_Distinct ){ + pItem->iDistinct = pParse->nTab++; + }else{ + pItem->iDistinct = -1; + } + } + } + /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry + */ + assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); + ExprSetVVAProperty(pExpr, EP_NoReduce); + pExpr->iAgg = (i16)i; + pExpr->pAggInfo = pAggInfo; + return WRC_Prune; + }else{ + return WRC_Continue; + } + } + } + return WRC_Continue; +} +static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){ + UNUSED_PARAMETER(pWalker); + UNUSED_PARAMETER(pSelect); + return WRC_Continue; +} + +/* +** Analyze the pExpr expression looking for aggregate functions and +** for variables that need to be added to AggInfo object that pNC->pAggInfo +** points to. Additional entries are made on the AggInfo object as +** necessary. +** +** This routine should only be called after the expression has been +** analyzed by sqlite3ResolveExprNames(). +*/ +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ + Walker w; + memset(&w, 0, sizeof(w)); + w.xExprCallback = analyzeAggregate; + w.xSelectCallback = analyzeAggregatesInSelect; + w.u.pNC = pNC; + assert( pNC->pSrcList!=0 ); + sqlite3WalkExpr(&w, pExpr); +} + +/* +** Call sqlite3ExprAnalyzeAggregates() for every expression in an +** expression list. Return the number of errors. +** +** If an error is found, the analysis is cut short. +*/ +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ + struct ExprList_item *pItem; + int i; + if( pList ){ + for(pItem=pList->a, i=0; inExpr; i++, pItem++){ + sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); + } + } +} + +/* +** Allocate a single new register for use to hold some intermediate result. +*/ +SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){ + if( pParse->nTempReg==0 ){ + return ++pParse->nMem; + } + return pParse->aTempReg[--pParse->nTempReg]; +} + +/* +** Deallocate a register, making available for reuse for some other +** purpose. +** +** If a register is currently being used by the column cache, then +** the dallocation is deferred until the column cache line that uses +** the register becomes stale. +*/ +SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ + if( iReg && pParse->nTempRegaTempReg) ){ + int i; + struct yColCache *p; + for(i=0, p=pParse->aColCache; iiReg==iReg ){ + p->tempReg = 1; + return; + } + } + pParse->aTempReg[pParse->nTempReg++] = iReg; + } +} + +/* +** Allocate or deallocate a block of nReg consecutive registers +*/ +SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){ + int i, n; + i = pParse->iRangeReg; + n = pParse->nRangeReg; + if( nReg<=n ){ + assert( !usedAsColumnCache(pParse, i, i+n-1) ); + pParse->iRangeReg += nReg; + pParse->nRangeReg -= nReg; + }else{ + i = pParse->nMem+1; + pParse->nMem += nReg; + } + return i; +} +SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ + sqlite3ExprCacheRemove(pParse, iReg, nReg); + if( nReg>pParse->nRangeReg ){ + pParse->nRangeReg = nReg; + pParse->iRangeReg = iReg; + } +} + +/* +** Mark all temporary registers as being unavailable for reuse. +*/ +SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){ + pParse->nTempReg = 0; + pParse->nRangeReg = 0; +} + +/************** End of expr.c ************************************************/ +/************** Begin file alter.c *******************************************/ +/* +** 2005 February 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that used to generate VDBE code +** that implements the ALTER TABLE command. +*/ + +/* +** The code in this file only exists if we are not omitting the +** ALTER TABLE logic from the build. +*/ +#ifndef SQLITE_OMIT_ALTERTABLE + + +/* +** This function is used by SQL generated to implement the +** ALTER TABLE command. The first argument is the text of a CREATE TABLE or +** CREATE INDEX command. The second is a table name. The table name in +** the CREATE TABLE or CREATE INDEX statement is replaced with the third +** argument and the result returned. Examples: +** +** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def') +** -> 'CREATE TABLE def(a, b, c)' +** +** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def') +** -> 'CREATE INDEX i ON def(a, b, c)' +*/ +static void renameTableFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + unsigned char const *zSql = sqlite3_value_text(argv[0]); + unsigned char const *zTableName = sqlite3_value_text(argv[1]); + + int token; + Token tname; + unsigned char const *zCsr = zSql; + int len = 0; + char *zRet; + + sqlite3 *db = sqlite3_context_db_handle(context); + + UNUSED_PARAMETER(NotUsed); + + /* The principle used to locate the table name in the CREATE TABLE + ** statement is that the table name is the first non-space token that + ** is immediately followed by a TK_LP or TK_USING token. + */ + if( zSql ){ + do { + if( !*zCsr ){ + /* Ran out of input before finding an opening bracket. Return NULL. */ + return; + } + + /* Store the token that zCsr points to in tname. */ + tname.z = (char*)zCsr; + tname.n = len; + + /* Advance zCsr to the next token. Store that token type in 'token', + ** and its length in 'len' (to be used next iteration of this loop). + */ + do { + zCsr += len; + len = sqlite3GetToken(zCsr, &token); + } while( token==TK_SPACE ); + assert( len>0 ); + } while( token!=TK_LP && token!=TK_USING ); + + zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, + zTableName, tname.z+tname.n); + sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); + } +} + +/* +** This C function implements an SQL user function that is used by SQL code +** generated by the ALTER TABLE ... RENAME command to modify the definition +** of any foreign key constraints that use the table being renamed as the +** parent table. It is passed three arguments: +** +** 1) The complete text of the CREATE TABLE statement being modified, +** 2) The old name of the table being renamed, and +** 3) The new name of the table being renamed. +** +** It returns the new CREATE TABLE statement. For example: +** +** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3') +** -> 'CREATE TABLE t1(a REFERENCES t3)' +*/ +#ifndef SQLITE_OMIT_FOREIGN_KEY +static void renameParentFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + char *zOutput = 0; + char *zResult; + unsigned char const *zInput = sqlite3_value_text(argv[0]); + unsigned char const *zOld = sqlite3_value_text(argv[1]); + unsigned char const *zNew = sqlite3_value_text(argv[2]); + + unsigned const char *z; /* Pointer to token */ + int n; /* Length of token z */ + int token; /* Type of token */ + + UNUSED_PARAMETER(NotUsed); + for(z=zInput; *z; z=z+n){ + n = sqlite3GetToken(z, &token); + if( token==TK_REFERENCES ){ + char *zParent; + do { + z += n; + n = sqlite3GetToken(z, &token); + }while( token==TK_SPACE ); + + zParent = sqlite3DbStrNDup(db, (const char *)z, n); + if( zParent==0 ) break; + sqlite3Dequote(zParent); + if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){ + char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", + (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew + ); + sqlite3DbFree(db, zOutput); + zOutput = zOut; + zInput = &z[n]; + } + sqlite3DbFree(db, zParent); + } + } + + zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), + sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC); + sqlite3DbFree(db, zOutput); +} +#endif + +#ifndef SQLITE_OMIT_TRIGGER +/* This function is used by SQL generated to implement the +** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER +** statement. The second is a table name. The table name in the CREATE +** TRIGGER statement is replaced with the third argument and the result +** returned. This is analagous to renameTableFunc() above, except for CREATE +** TRIGGER, not CREATE INDEX and CREATE TABLE. +*/ +static void renameTriggerFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + unsigned char const *zSql = sqlite3_value_text(argv[0]); + unsigned char const *zTableName = sqlite3_value_text(argv[1]); + + int token; + Token tname; + int dist = 3; + unsigned char const *zCsr = zSql; + int len = 0; + char *zRet; + sqlite3 *db = sqlite3_context_db_handle(context); + + UNUSED_PARAMETER(NotUsed); + + /* The principle used to locate the table name in the CREATE TRIGGER + ** statement is that the table name is the first token that is immediatedly + ** preceded by either TK_ON or TK_DOT and immediatedly followed by one + ** of TK_WHEN, TK_BEGIN or TK_FOR. + */ + if( zSql ){ + do { + + if( !*zCsr ){ + /* Ran out of input before finding the table name. Return NULL. */ + return; + } + + /* Store the token that zCsr points to in tname. */ + tname.z = (char*)zCsr; + tname.n = len; + + /* Advance zCsr to the next token. Store that token type in 'token', + ** and its length in 'len' (to be used next iteration of this loop). + */ + do { + zCsr += len; + len = sqlite3GetToken(zCsr, &token); + }while( token==TK_SPACE ); + assert( len>0 ); + + /* Variable 'dist' stores the number of tokens read since the most + ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN + ** token is read and 'dist' equals 2, the condition stated above + ** to be met. + ** + ** Note that ON cannot be a database, table or column name, so + ** there is no need to worry about syntax like + ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. + */ + dist++; + if( token==TK_DOT || token==TK_ON ){ + dist = 0; + } + } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) ); + + /* Variable tname now contains the token that is the old table-name + ** in the CREATE TRIGGER statement. + */ + zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, + zTableName, tname.z+tname.n); + sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); + } +} +#endif /* !SQLITE_OMIT_TRIGGER */ + +/* +** Register built-in functions used to help implement ALTER TABLE +*/ +SQLITE_PRIVATE void sqlite3AlterFunctions(void){ + static SQLITE_WSD FuncDef aAlterTableFuncs[] = { + FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc), +#ifndef SQLITE_OMIT_TRIGGER + FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc), +#endif +#ifndef SQLITE_OMIT_FOREIGN_KEY + FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc), +#endif + }; + int i; + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs); + + for(i=0; i OR name= OR ... +** +** If argument zWhere is NULL, then a pointer string containing the text +** "name=" is returned, where is the quoted version +** of the string passed as argument zConstant. The returned buffer is +** allocated using sqlite3DbMalloc(). It is the responsibility of the +** caller to ensure that it is eventually freed. +** +** If argument zWhere is not NULL, then the string returned is +** " OR name=", where is the contents of zWhere. +** In this case zWhere is passed to sqlite3DbFree() before returning. +** +*/ +static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){ + char *zNew; + if( !zWhere ){ + zNew = sqlite3MPrintf(db, "name=%Q", zConstant); + }else{ + zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant); + sqlite3DbFree(db, zWhere); + } + return zNew; +} + +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) +/* +** Generate the text of a WHERE expression which can be used to select all +** tables that have foreign key constraints that refer to table pTab (i.e. +** constraints for which pTab is the parent table) from the sqlite_master +** table. +*/ +static char *whereForeignKeys(Parse *pParse, Table *pTab){ + FKey *p; + char *zWhere = 0; + for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ + zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName); + } + return zWhere; +} +#endif + +/* +** Generate the text of a WHERE expression which can be used to select all +** temporary triggers on table pTab from the sqlite_temp_master table. If +** table pTab has no temporary triggers, or is itself stored in the +** temporary database, NULL is returned. +*/ +static char *whereTempTriggers(Parse *pParse, Table *pTab){ + Trigger *pTrig; + char *zWhere = 0; + const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */ + + /* If the table is not located in the temp-db (in which case NULL is + ** returned, loop through the tables list of triggers. For each trigger + ** that is not part of the temp-db schema, add a clause to the WHERE + ** expression being built up in zWhere. + */ + if( pTab->pSchema!=pTempSchema ){ + sqlite3 *db = pParse->db; + for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ + if( pTrig->pSchema==pTempSchema ){ + zWhere = whereOrName(db, zWhere, pTrig->zName); + } + } + } + if( zWhere ){ + char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere); + sqlite3DbFree(pParse->db, zWhere); + zWhere = zNew; + } + return zWhere; +} + +/* +** Generate code to drop and reload the internal representation of table +** pTab from the database, including triggers and temporary triggers. +** Argument zName is the name of the table in the database schema at +** the time the generated code is executed. This can be different from +** pTab->zName if this function is being called to code part of an +** "ALTER TABLE RENAME TO" statement. +*/ +static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){ + Vdbe *v; + char *zWhere; + int iDb; /* Index of database containing pTab */ +#ifndef SQLITE_OMIT_TRIGGER + Trigger *pTrig; +#endif + + v = sqlite3GetVdbe(pParse); + if( NEVER(v==0) ) return; + assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + assert( iDb>=0 ); + +#ifndef SQLITE_OMIT_TRIGGER + /* Drop any table triggers from the internal schema. */ + for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ + int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); + assert( iTrigDb==iDb || iTrigDb==1 ); + sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0); + } +#endif + + /* Drop the table and index from the internal schema. */ + sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); + + /* Reload the table, index and permanent trigger schemas. */ + zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName); + if( !zWhere ) return; + sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); + +#ifndef SQLITE_OMIT_TRIGGER + /* Now, if the table is not stored in the temp database, reload any temp + ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. + */ + if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ + sqlite3VdbeAddParseSchemaOp(v, 1, zWhere); + } +#endif +} + +/* +** Parameter zName is the name of a table that is about to be altered +** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). +** If the table is a system table, this function leaves an error message +** in pParse->zErr (system tables may not be altered) and returns non-zero. +** +** Or, if zName is not a system table, zero is returned. +*/ +static int isSystemTable(Parse *pParse, const char *zName){ + if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ + sqlite3ErrorMsg(pParse, "table %s may not be altered", zName); + return 1; + } + return 0; +} + +/* +** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" +** command. +*/ +SQLITE_PRIVATE void sqlite3AlterRenameTable( + Parse *pParse, /* Parser context. */ + SrcList *pSrc, /* The table to rename. */ + Token *pName /* The new table name. */ +){ + int iDb; /* Database that contains the table */ + char *zDb; /* Name of database iDb */ + Table *pTab; /* Table being renamed */ + char *zName = 0; /* NULL-terminated version of pName */ + sqlite3 *db = pParse->db; /* Database connection */ + int nTabName; /* Number of UTF-8 characters in zTabName */ + const char *zTabName; /* Original name of the table */ + Vdbe *v; +#ifndef SQLITE_OMIT_TRIGGER + char *zWhere = 0; /* Where clause to locate temp triggers */ +#endif + VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */ + int savedDbFlags; /* Saved value of db->flags */ + + savedDbFlags = db->flags; + if( NEVER(db->mallocFailed) ) goto exit_rename_table; + assert( pSrc->nSrc==1 ); + assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); + + pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); + if( !pTab ) goto exit_rename_table; + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + zDb = db->aDb[iDb].zName; + db->flags |= SQLITE_PreferBuiltin; + + /* Get a NULL terminated version of the new table name. */ + zName = sqlite3NameFromToken(db, pName); + if( !zName ) goto exit_rename_table; + + /* Check that a table or index named 'zName' does not already exist + ** in database iDb. If so, this is an error. + */ + if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){ + sqlite3ErrorMsg(pParse, + "there is already another table or index with this name: %s", zName); + goto exit_rename_table; + } + + /* Make sure it is not a system table being altered, or a reserved name + ** that the table is being renamed to. + */ + if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ + goto exit_rename_table; + } + if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto + exit_rename_table; + } + +#ifndef SQLITE_OMIT_VIEW + if( pTab->pSelect ){ + sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); + goto exit_rename_table; + } +#endif + +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Invoke the authorization callback. */ + if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ + goto exit_rename_table; + } +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto exit_rename_table; + } + if( IsVirtual(pTab) ){ + pVTab = sqlite3GetVTable(db, pTab); + if( pVTab->pVtab->pModule->xRename==0 ){ + pVTab = 0; + } + } +#endif + + /* Begin a transaction and code the VerifyCookie for database iDb. + ** Then modify the schema cookie (since the ALTER TABLE modifies the + ** schema). Open a statement transaction if the table is a virtual + ** table. + */ + v = sqlite3GetVdbe(pParse); + if( v==0 ){ + goto exit_rename_table; + } + sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb); + sqlite3ChangeCookie(pParse, iDb); + + /* If this is a virtual table, invoke the xRename() function if + ** one is defined. The xRename() callback will modify the names + ** of any resources used by the v-table implementation (including other + ** SQLite tables) that are identified by the name of the virtual table. + */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pVTab ){ + int i = ++pParse->nMem; + sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0); + sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB); + sqlite3MayAbort(pParse); + } +#endif + + /* figure out how many UTF-8 characters are in zName */ + zTabName = pTab->zName; + nTabName = sqlite3Utf8CharLen(zTabName, -1); + +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + if( db->flags&SQLITE_ForeignKeys ){ + /* If foreign-key support is enabled, rewrite the CREATE TABLE + ** statements corresponding to all child tables of foreign key constraints + ** for which the renamed table is the parent table. */ + if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){ + sqlite3NestedParse(pParse, + "UPDATE \"%w\".%s SET " + "sql = sqlite_rename_parent(sql, %Q, %Q) " + "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere); + sqlite3DbFree(db, zWhere); + } + } +#endif + + /* Modify the sqlite_master table to use the new table name. */ + sqlite3NestedParse(pParse, + "UPDATE %Q.%s SET " +#ifdef SQLITE_OMIT_TRIGGER + "sql = sqlite_rename_table(sql, %Q), " +#else + "sql = CASE " + "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" + "ELSE sqlite_rename_table(sql, %Q) END, " +#endif + "tbl_name = %Q, " + "name = CASE " + "WHEN type='table' THEN %Q " + "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " + "'sqlite_autoindex_' || %Q || substr(name,%d+18) " + "ELSE name END " + "WHERE tbl_name=%Q COLLATE nocase AND " + "(type='table' OR type='index' OR type='trigger');", + zDb, SCHEMA_TABLE(iDb), zName, zName, zName, +#ifndef SQLITE_OMIT_TRIGGER + zName, +#endif + zName, nTabName, zTabName + ); + +#ifndef SQLITE_OMIT_AUTOINCREMENT + /* If the sqlite_sequence table exists in this database, then update + ** it with the new table name. + */ + if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ + sqlite3NestedParse(pParse, + "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", + zDb, zName, pTab->zName); + } +#endif + +#ifndef SQLITE_OMIT_TRIGGER + /* If there are TEMP triggers on this table, modify the sqlite_temp_master + ** table. Don't do this if the table being ALTERed is itself located in + ** the temp database. + */ + if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ + sqlite3NestedParse(pParse, + "UPDATE sqlite_temp_master SET " + "sql = sqlite_rename_trigger(sql, %Q), " + "tbl_name = %Q " + "WHERE %s;", zName, zName, zWhere); + sqlite3DbFree(db, zWhere); + } +#endif + +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + if( db->flags&SQLITE_ForeignKeys ){ + FKey *p; + for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ + Table *pFrom = p->pFrom; + if( pFrom!=pTab ){ + reloadTableSchema(pParse, p->pFrom, pFrom->zName); + } + } + } +#endif + + /* Drop and reload the internal table schema. */ + reloadTableSchema(pParse, pTab, zName); + +exit_rename_table: + sqlite3SrcListDelete(db, pSrc); + sqlite3DbFree(db, zName); + db->flags = savedDbFlags; +} + + +/* +** Generate code to make sure the file format number is at least minFormat. +** The generated code will increase the file format number if necessary. +*/ +SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){ + Vdbe *v; + v = sqlite3GetVdbe(pParse); + /* The VDBE should have been allocated before this routine is called. + ** If that allocation failed, we would have quit before reaching this + ** point */ + if( ALWAYS(v) ){ + int r1 = sqlite3GetTempReg(pParse); + int r2 = sqlite3GetTempReg(pParse); + int j1; + sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); + sqlite3VdbeUsesBtree(v, iDb); + sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2); + j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2); + sqlite3VdbeJumpHere(v, j1); + sqlite3ReleaseTempReg(pParse, r1); + sqlite3ReleaseTempReg(pParse, r2); + } +} + +/* +** This function is called after an "ALTER TABLE ... ADD" statement +** has been parsed. Argument pColDef contains the text of the new +** column definition. +** +** The Table structure pParse->pNewTable was extended to include +** the new column during parsing. +*/ +SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ + Table *pNew; /* Copy of pParse->pNewTable */ + Table *pTab; /* Table being altered */ + int iDb; /* Database number */ + const char *zDb; /* Database name */ + const char *zTab; /* Table name */ + char *zCol; /* Null-terminated column definition */ + Column *pCol; /* The new column */ + Expr *pDflt; /* Default value for the new column */ + sqlite3 *db; /* The database connection; */ + + db = pParse->db; + if( pParse->nErr || db->mallocFailed ) return; + pNew = pParse->pNewTable; + assert( pNew ); + + assert( sqlite3BtreeHoldsAllMutexes(db) ); + iDb = sqlite3SchemaToIndex(db, pNew->pSchema); + zDb = db->aDb[iDb].zName; + zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ + pCol = &pNew->aCol[pNew->nCol-1]; + pDflt = pCol->pDflt; + pTab = sqlite3FindTable(db, zTab, zDb); + assert( pTab ); + +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Invoke the authorization callback. */ + if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ + return; + } +#endif + + /* If the default value for the new column was specified with a + ** literal NULL, then set pDflt to 0. This simplifies checking + ** for an SQL NULL default below. + */ + if( pDflt && pDflt->op==TK_NULL ){ + pDflt = 0; + } + + /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. + ** If there is a NOT NULL constraint, then the default value for the + ** column must not be NULL. + */ + if( pCol->colFlags & COLFLAG_PRIMKEY ){ + sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); + return; + } + if( pNew->pIndex ){ + sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column"); + return; + } + if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){ + sqlite3ErrorMsg(pParse, + "Cannot add a REFERENCES column with non-NULL default value"); + return; + } + if( pCol->notNull && !pDflt ){ + sqlite3ErrorMsg(pParse, + "Cannot add a NOT NULL column with default value NULL"); + return; + } + + /* Ensure the default expression is something that sqlite3ValueFromExpr() + ** can handle (i.e. not CURRENT_TIME etc.) + */ + if( pDflt ){ + sqlite3_value *pVal = 0; + if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){ + db->mallocFailed = 1; + return; + } + if( !pVal ){ + sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default"); + return; + } + sqlite3ValueFree(pVal); + } + + /* Modify the CREATE TABLE statement. */ + zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n); + if( zCol ){ + char *zEnd = &zCol[pColDef->n-1]; + int savedDbFlags = db->flags; + while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ + *zEnd-- = '\0'; + } + db->flags |= SQLITE_PreferBuiltin; + sqlite3NestedParse(pParse, + "UPDATE \"%w\".%s SET " + "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " + "WHERE type = 'table' AND name = %Q", + zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1, + zTab + ); + sqlite3DbFree(db, zCol); + db->flags = savedDbFlags; + } + + /* If the default value of the new column is NULL, then set the file + ** format to 2. If the default value of the new column is not NULL, + ** the file format becomes 3. + */ + sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2); + + /* Reload the schema of the modified table. */ + reloadTableSchema(pParse, pTab, pTab->zName); +} + +/* +** This function is called by the parser after the table-name in +** an "ALTER TABLE ADD" statement is parsed. Argument +** pSrc is the full-name of the table being altered. +** +** This routine makes a (partial) copy of the Table structure +** for the table being altered and sets Parse.pNewTable to point +** to it. Routines called by the parser as the column definition +** is parsed (i.e. sqlite3AddColumn()) add the new Column data to +** the copy. The copy of the Table structure is deleted by tokenize.c +** after parsing is finished. +** +** Routine sqlite3AlterFinishAddColumn() will be called to complete +** coding the "ALTER TABLE ... ADD" statement. +*/ +SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ + Table *pNew; + Table *pTab; + Vdbe *v; + int iDb; + int i; + int nAlloc; + sqlite3 *db = pParse->db; + + /* Look up the table being altered. */ + assert( pParse->pNewTable==0 ); + assert( sqlite3BtreeHoldsAllMutexes(db) ); + if( db->mallocFailed ) goto exit_begin_add_column; + pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); + if( !pTab ) goto exit_begin_add_column; + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); + goto exit_begin_add_column; + } +#endif + + /* Make sure this is not an attempt to ALTER a view. */ + if( pTab->pSelect ){ + sqlite3ErrorMsg(pParse, "Cannot add a column to a view"); + goto exit_begin_add_column; + } + if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ + goto exit_begin_add_column; + } + + assert( pTab->addColOffset>0 ); + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + + /* Put a copy of the Table struct in Parse.pNewTable for the + ** sqlite3AddColumn() function and friends to modify. But modify + ** the name by adding an "sqlite_altertab_" prefix. By adding this + ** prefix, we insure that the name will not collide with an existing + ** table because user table are not allowed to have the "sqlite_" + ** prefix on their name. + */ + pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table)); + if( !pNew ) goto exit_begin_add_column; + pParse->pNewTable = pNew; + pNew->nRef = 1; + pNew->nCol = pTab->nCol; + assert( pNew->nCol>0 ); + nAlloc = (((pNew->nCol-1)/8)*8)+8; + assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); + pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc); + pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); + if( !pNew->aCol || !pNew->zName ){ + db->mallocFailed = 1; + goto exit_begin_add_column; + } + memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); + for(i=0; inCol; i++){ + Column *pCol = &pNew->aCol[i]; + pCol->zName = sqlite3DbStrDup(db, pCol->zName); + pCol->zColl = 0; + pCol->zType = 0; + pCol->pDflt = 0; + pCol->zDflt = 0; + } + pNew->pSchema = db->aDb[iDb].pSchema; + pNew->addColOffset = pTab->addColOffset; + pNew->nRef = 1; + + /* Begin a transaction and increment the schema cookie. */ + sqlite3BeginWriteOperation(pParse, 0, iDb); + v = sqlite3GetVdbe(pParse); + if( !v ) goto exit_begin_add_column; + sqlite3ChangeCookie(pParse, iDb); + +exit_begin_add_column: + sqlite3SrcListDelete(db, pSrc); + return; +} +#endif /* SQLITE_ALTER_TABLE */ + +/************** End of alter.c ***********************************************/ +/************** Begin file analyze.c *****************************************/ +/* +** 2005-07-08 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code associated with the ANALYZE command. +** +** The ANALYZE command gather statistics about the content of tables +** and indices. These statistics are made available to the query planner +** to help it make better decisions about how to perform queries. +** +** The following system tables are or have been supported: +** +** CREATE TABLE sqlite_stat1(tbl, idx, stat); +** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample); +** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample); +** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample); +** +** Additional tables might be added in future releases of SQLite. +** The sqlite_stat2 table is not created or used unless the SQLite version +** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled +** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated. +** The sqlite_stat2 table is superseded by sqlite_stat3, which is only +** created and used by SQLite versions 3.7.9 and later and with +** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3 +** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced +** version of sqlite_stat3 and is only available when compiled with +** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is +** not possible to enable both STAT3 and STAT4 at the same time. If they +** are both enabled, then STAT4 takes precedence. +** +** For most applications, sqlite_stat1 provides all the statisics required +** for the query planner to make good choices. +** +** Format of sqlite_stat1: +** +** There is normally one row per index, with the index identified by the +** name in the idx column. The tbl column is the name of the table to +** which the index belongs. In each such row, the stat column will be +** a string consisting of a list of integers. The first integer in this +** list is the number of rows in the index. (This is the same as the +** number of rows in the table, except for partial indices.) The second +** integer is the average number of rows in the index that have the same +** value in the first column of the index. The third integer is the average +** number of rows in the index that have the same value for the first two +** columns. The N-th integer (for N>1) is the average number of rows in +** the index which have the same value for the first N-1 columns. For +** a K-column index, there will be K+1 integers in the stat column. If +** the index is unique, then the last integer will be 1. +** +** The list of integers in the stat column can optionally be followed +** by the keyword "unordered". The "unordered" keyword, if it is present, +** must be separated from the last integer by a single space. If the +** "unordered" keyword is present, then the query planner assumes that +** the index is unordered and will not use the index for a range query. +** +** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat +** column contains a single integer which is the (estimated) number of +** rows in the table identified by sqlite_stat1.tbl. +** +** Format of sqlite_stat2: +** +** The sqlite_stat2 is only created and is only used if SQLite is compiled +** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between +** 3.6.18 and 3.7.8. The "stat2" table contains additional information +** about the distribution of keys within an index. The index is identified by +** the "idx" column and the "tbl" column is the name of the table to which +** the index belongs. There are usually 10 rows in the sqlite_stat2 +** table for each index. +** +** The sqlite_stat2 entries for an index that have sampleno between 0 and 9 +** inclusive are samples of the left-most key value in the index taken at +** evenly spaced points along the index. Let the number of samples be S +** (10 in the standard build) and let C be the number of rows in the index. +** Then the sampled rows are given by: +** +** rownumber = (i*C*2 + C)/(S*2) +** +** For i between 0 and S-1. Conceptually, the index space is divided into +** S uniform buckets and the samples are the middle row from each bucket. +** +** The format for sqlite_stat2 is recorded here for legacy reference. This +** version of SQLite does not support sqlite_stat2. It neither reads nor +** writes the sqlite_stat2 table. This version of SQLite only supports +** sqlite_stat3. +** +** Format for sqlite_stat3: +** +** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the +** sqlite_stat4 format will be described first. Further information +** about sqlite_stat3 follows the sqlite_stat4 description. +** +** Format for sqlite_stat4: +** +** As with sqlite_stat2, the sqlite_stat4 table contains histogram data +** to aid the query planner in choosing good indices based on the values +** that indexed columns are compared against in the WHERE clauses of +** queries. +** +** The sqlite_stat4 table contains multiple entries for each index. +** The idx column names the index and the tbl column is the table of the +** index. If the idx and tbl columns are the same, then the sample is +** of the INTEGER PRIMARY KEY. The sample column is a blob which is the +** binary encoding of a key from the index. The nEq column is a +** list of integers. The first integer is the approximate number +** of entries in the index whose left-most column exactly matches +** the left-most column of the sample. The second integer in nEq +** is the approximate number of entries in the index where the +** first two columns match the first two columns of the sample. +** And so forth. nLt is another list of integers that show the approximate +** number of entries that are strictly less than the sample. The first +** integer in nLt contains the number of entries in the index where the +** left-most column is less than the left-most column of the sample. +** The K-th integer in the nLt entry is the number of index entries +** where the first K columns are less than the first K columns of the +** sample. The nDLt column is like nLt except that it contains the +** number of distinct entries in the index that are less than the +** sample. +** +** There can be an arbitrary number of sqlite_stat4 entries per index. +** The ANALYZE command will typically generate sqlite_stat4 tables +** that contain between 10 and 40 samples which are distributed across +** the key space, though not uniformly, and which include samples with +** large nEq values. +** +** Format for sqlite_stat3 redux: +** +** The sqlite_stat3 table is like sqlite_stat4 except that it only +** looks at the left-most column of the index. The sqlite_stat3.sample +** column contains the actual value of the left-most column instead +** of a blob encoding of the complete index key as is found in +** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3 +** all contain just a single integer which is the same as the first +** integer in the equivalent columns in sqlite_stat4. +*/ +#ifndef SQLITE_OMIT_ANALYZE + +#if defined(SQLITE_ENABLE_STAT4) +# define IsStat4 1 +# define IsStat3 0 +#elif defined(SQLITE_ENABLE_STAT3) +# define IsStat4 0 +# define IsStat3 1 +#else +# define IsStat4 0 +# define IsStat3 0 +# undef SQLITE_STAT4_SAMPLES +# define SQLITE_STAT4_SAMPLES 1 +#endif +#define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */ + +/* +** This routine generates code that opens the sqlite_statN tables. +** The sqlite_stat1 table is always relevant. sqlite_stat2 is now +** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when +** appropriate compile-time options are provided. +** +** If the sqlite_statN tables do not previously exist, it is created. +** +** Argument zWhere may be a pointer to a buffer containing a table name, +** or it may be a NULL pointer. If it is not NULL, then all entries in +** the sqlite_statN tables associated with the named table are deleted. +** If zWhere==0, then code is generated to delete all stat table entries. +*/ +static void openStatTable( + Parse *pParse, /* Parsing context */ + int iDb, /* The database we are looking in */ + int iStatCur, /* Open the sqlite_stat1 table on this cursor */ + const char *zWhere, /* Delete entries for this table or index */ + const char *zWhereType /* Either "tbl" or "idx" */ +){ + static const struct { + const char *zName; + const char *zCols; + } aTable[] = { + { "sqlite_stat1", "tbl,idx,stat" }, +#if defined(SQLITE_ENABLE_STAT4) + { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" }, + { "sqlite_stat3", 0 }, +#elif defined(SQLITE_ENABLE_STAT3) + { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" }, + { "sqlite_stat4", 0 }, +#else + { "sqlite_stat3", 0 }, + { "sqlite_stat4", 0 }, +#endif + }; + int i; + sqlite3 *db = pParse->db; + Db *pDb; + Vdbe *v = sqlite3GetVdbe(pParse); + int aRoot[ArraySize(aTable)]; + u8 aCreateTbl[ArraySize(aTable)]; + + if( v==0 ) return; + assert( sqlite3BtreeHoldsAllMutexes(db) ); + assert( sqlite3VdbeDb(v)==db ); + pDb = &db->aDb[iDb]; + + /* Create new statistic tables if they do not exist, or clear them + ** if they do already exist. + */ + for(i=0; izName))==0 ){ + if( aTable[i].zCols ){ + /* The sqlite_statN table does not exist. Create it. Note that a + ** side-effect of the CREATE TABLE statement is to leave the rootpage + ** of the new table in register pParse->regRoot. This is important + ** because the OpenWrite opcode below will be needing it. */ + sqlite3NestedParse(pParse, + "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols + ); + aRoot[i] = pParse->regRoot; + aCreateTbl[i] = OPFLAG_P2ISREG; + } + }else{ + /* The table already exists. If zWhere is not NULL, delete all entries + ** associated with the table zWhere. If zWhere is NULL, delete the + ** entire contents of the table. */ + aRoot[i] = pStat->tnum; + aCreateTbl[i] = 0; + sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab); + if( zWhere ){ + sqlite3NestedParse(pParse, + "DELETE FROM %Q.%s WHERE %s=%Q", + pDb->zName, zTab, zWhereType, zWhere + ); + }else{ + /* The sqlite_stat[134] table already exists. Delete all rows. */ + sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb); + } + } + } + + /* Open the sqlite_stat[134] tables for writing. */ + for(i=0; aTable[i].zCols; i++){ + assert( i1 ); /* >1 because it includes the rowid column */ + nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol; + + /* Allocate the space required for the Stat4Accum object */ + n = sizeof(*p) + + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */ + + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */ + + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */ + + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample) +#endif + ; + p = sqlite3MallocZero(n); + if( p==0 ){ + sqlite3_result_error_nomem(context); + return; + } + + p->nRow = 0; + p->nCol = nCol; + p->current.anDLt = (tRowcnt*)&p[1]; + p->current.anEq = &p->current.anDLt[nColUp]; + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + { + u8 *pSpace; /* Allocated space not yet assigned */ + int i; /* Used to iterate through p->aSample[] */ + + p->iGet = -1; + p->mxSample = mxSample; + p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1); + p->current.anLt = &p->current.anEq[nColUp]; + p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565; + + /* Set up the Stat4Accum.a[] and aBest[] arrays */ + p->a = (struct Stat4Sample*)&p->current.anLt[nColUp]; + p->aBest = &p->a[mxSample]; + pSpace = (u8*)(&p->a[mxSample+nCol]); + for(i=0; i<(mxSample+nCol); i++){ + p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); + p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); + p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); + } + assert( (pSpace - (u8*)p)==n ); + + for(i=0; iaBest[i].iCol = i; + } + } +#endif + + /* Return a pointer to the allocated object to the caller */ + sqlite3_result_blob(context, p, sizeof(p), sqlite3_free); +} +static const FuncDef statInitFuncdef = { + 1+IsStat34, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + statInit, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "stat_init", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ +}; + +#ifdef SQLITE_ENABLE_STAT4 +/* +** pNew and pOld are both candidate non-periodic samples selected for +** the same column (pNew->iCol==pOld->iCol). Ignoring this column and +** considering only any trailing columns and the sample hash value, this +** function returns true if sample pNew is to be preferred over pOld. +** In other words, if we assume that the cardinalities of the selected +** column for pNew and pOld are equal, is pNew to be preferred over pOld. +** +** This function assumes that for each argument sample, the contents of +** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. +*/ +static int sampleIsBetterPost( + Stat4Accum *pAccum, + Stat4Sample *pNew, + Stat4Sample *pOld +){ + int nCol = pAccum->nCol; + int i; + assert( pNew->iCol==pOld->iCol ); + for(i=pNew->iCol+1; ianEq[i]>pOld->anEq[i] ) return 1; + if( pNew->anEq[i]anEq[i] ) return 0; + } + if( pNew->iHash>pOld->iHash ) return 1; + return 0; +} +#endif + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Return true if pNew is to be preferred over pOld. +** +** This function assumes that for each argument sample, the contents of +** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. +*/ +static int sampleIsBetter( + Stat4Accum *pAccum, + Stat4Sample *pNew, + Stat4Sample *pOld +){ + tRowcnt nEqNew = pNew->anEq[pNew->iCol]; + tRowcnt nEqOld = pOld->anEq[pOld->iCol]; + + assert( pOld->isPSample==0 && pNew->isPSample==0 ); + assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) ); + + if( (nEqNew>nEqOld) ) return 1; +#ifdef SQLITE_ENABLE_STAT4 + if( nEqNew==nEqOld ){ + if( pNew->iColiCol ) return 1; + return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld)); + } + return 0; +#else + return (nEqNew==nEqOld && pNew->iHash>pOld->iHash); +#endif +} + +/* +** Copy the contents of object (*pFrom) into (*pTo). +*/ +static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){ + pTo->iRowid = pFrom->iRowid; + pTo->isPSample = pFrom->isPSample; + pTo->iCol = pFrom->iCol; + pTo->iHash = pFrom->iHash; + memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol); + memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol); + memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol); +} + +/* +** Copy the contents of sample *pNew into the p->a[] array. If necessary, +** remove the least desirable sample from p->a[] to make room. +*/ +static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ + Stat4Sample *pSample; + int i; + + assert( IsStat4 || nEqZero==0 ); + +#ifdef SQLITE_ENABLE_STAT4 + if( pNew->isPSample==0 ){ + Stat4Sample *pUpgrade = 0; + assert( pNew->anEq[pNew->iCol]>0 ); + + /* This sample is being added because the prefix that ends in column + ** iCol occurs many times in the table. However, if we have already + ** added a sample that shares this prefix, there is no need to add + ** this one. Instead, upgrade the priority of the highest priority + ** existing sample that shares this prefix. */ + for(i=p->nSample-1; i>=0; i--){ + Stat4Sample *pOld = &p->a[i]; + if( pOld->anEq[pNew->iCol]==0 ){ + if( pOld->isPSample ) return; + assert( pOld->iCol>pNew->iCol ); + assert( sampleIsBetter(p, pNew, pOld) ); + if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){ + pUpgrade = pOld; + } + } + } + if( pUpgrade ){ + pUpgrade->iCol = pNew->iCol; + pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol]; + goto find_new_min; + } + } +#endif + + /* If necessary, remove sample iMin to make room for the new sample. */ + if( p->nSample>=p->mxSample ){ + Stat4Sample *pMin = &p->a[p->iMin]; + tRowcnt *anEq = pMin->anEq; + tRowcnt *anLt = pMin->anLt; + tRowcnt *anDLt = pMin->anDLt; + memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1)); + pSample = &p->a[p->nSample-1]; + pSample->anEq = anEq; + pSample->anDLt = anDLt; + pSample->anLt = anLt; + p->nSample = p->mxSample-1; + } + + /* The "rows less-than" for the rowid column must be greater than that + ** for the last sample in the p->a[] array. Otherwise, the samples would + ** be out of order. */ +#ifdef SQLITE_ENABLE_STAT4 + assert( p->nSample==0 + || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] ); +#endif + + /* Insert the new sample */ + pSample = &p->a[p->nSample]; + sampleCopy(p, pSample, pNew); + p->nSample++; + + /* Zero the first nEqZero entries in the anEq[] array. */ + memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero); + +#ifdef SQLITE_ENABLE_STAT4 + find_new_min: +#endif + if( p->nSample>=p->mxSample ){ + int iMin = -1; + for(i=0; imxSample; i++){ + if( p->a[i].isPSample ) continue; + if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){ + iMin = i; + } + } + assert( iMin>=0 ); + p->iMin = iMin; + } +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +/* +** Field iChng of the index being scanned has changed. So at this point +** p->current contains a sample that reflects the previous row of the +** index. The value of anEq[iChng] and subsequent anEq[] elements are +** correct at this point. +*/ +static void samplePushPrevious(Stat4Accum *p, int iChng){ +#ifdef SQLITE_ENABLE_STAT4 + int i; + + /* Check if any samples from the aBest[] array should be pushed + ** into IndexSample.a[] at this point. */ + for(i=(p->nCol-2); i>=iChng; i--){ + Stat4Sample *pBest = &p->aBest[i]; + pBest->anEq[i] = p->current.anEq[i]; + if( p->nSamplemxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){ + sampleInsert(p, pBest, i); + } + } + + /* Update the anEq[] fields of any samples already collected. */ + for(i=p->nSample-1; i>=0; i--){ + int j; + for(j=iChng; jnCol; j++){ + if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j]; + } + } +#endif + +#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4) + if( iChng==0 ){ + tRowcnt nLt = p->current.anLt[0]; + tRowcnt nEq = p->current.anEq[0]; + + /* Check if this is to be a periodic sample. If so, add it. */ + if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){ + p->current.isPSample = 1; + sampleInsert(p, &p->current, 0); + p->current.isPSample = 0; + }else + + /* Or if it is a non-periodic sample. Add it in this case too. */ + if( p->nSamplemxSample + || sampleIsBetter(p, &p->current, &p->a[p->iMin]) + ){ + sampleInsert(p, &p->current, 0); + } + } +#endif + +#ifndef SQLITE_ENABLE_STAT3_OR_STAT4 + UNUSED_PARAMETER( p ); + UNUSED_PARAMETER( iChng ); +#endif +} + +/* +** Implementation of the stat_push SQL function: stat_push(P,R,C) +** Arguments: +** +** P Pointer to the Stat4Accum object created by stat_init() +** C Index of left-most column to differ from previous row +** R Rowid for the current row +** +** The SQL function always returns NULL. +** +** The R parameter is only used for STAT3 and STAT4. +*/ +static void statPush( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int i; + + /* The three function arguments */ + Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); + int iChng = sqlite3_value_int(argv[1]); + + UNUSED_PARAMETER( argc ); + UNUSED_PARAMETER( context ); + assert( p->nCol>1 ); /* Includes rowid field */ + assert( iChngnCol ); + + if( p->nRow==0 ){ + /* This is the first call to this function. Do initialization. */ + for(i=0; inCol; i++) p->current.anEq[i] = 1; + }else{ + /* Second and subsequent calls get processed here */ + samplePushPrevious(p, iChng); + + /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply + ** to the current row of the index. */ + for(i=0; icurrent.anEq[i]++; + } + for(i=iChng; inCol; i++){ + p->current.anDLt[i]++; +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + p->current.anLt[i] += p->current.anEq[i]; +#endif + p->current.anEq[i] = 1; + } + } + p->nRow++; +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + p->current.iRowid = sqlite3_value_int64(argv[2]); + p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345; +#endif + +#ifdef SQLITE_ENABLE_STAT4 + { + tRowcnt nLt = p->current.anLt[p->nCol-1]; + + /* Check if this is to be a periodic sample. If so, add it. */ + if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){ + p->current.isPSample = 1; + p->current.iCol = 0; + sampleInsert(p, &p->current, p->nCol-1); + p->current.isPSample = 0; + } + + /* Update the aBest[] array. */ + for(i=0; i<(p->nCol-1); i++){ + p->current.iCol = i; + if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){ + sampleCopy(p, &p->aBest[i], &p->current); + } + } + } +#endif +} +static const FuncDef statPushFuncdef = { + 2+IsStat34, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + statPush, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "stat_push", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ +}; + +#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */ +#define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */ +#define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */ +#define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */ +#define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */ + +/* +** Implementation of the stat_get(P,J) SQL function. This routine is +** used to query the results. Content is returned for parameter J +** which is one of the STAT_GET_xxxx values defined above. +** +** If neither STAT3 nor STAT4 are enabled, then J is always +** STAT_GET_STAT1 and is hence omitted and this routine becomes +** a one-parameter function, stat_get(P), that always returns the +** stat1 table entry information. +*/ +static void statGet( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + /* STAT3 and STAT4 have a parameter on this routine. */ + int eCall = sqlite3_value_int(argv[1]); + assert( argc==2 ); + assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ + || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT + || eCall==STAT_GET_NDLT + ); + if( eCall==STAT_GET_STAT1 ) +#else + assert( argc==1 ); +#endif + { + /* Return the value to store in the "stat" column of the sqlite_stat1 + ** table for this index. + ** + ** The value is a string composed of a list of integers describing + ** the index. The first integer in the list is the total number of + ** entries in the index. There is one additional integer in the list + ** for each indexed column. This additional integer is an estimate of + ** the number of rows matched by a stabbing query on the index using + ** a key with the corresponding number of fields. In other words, + ** if the index is on columns (a,b) and the sqlite_stat1 value is + ** "100 10 2", then SQLite estimates that: + ** + ** * the index contains 100 rows, + ** * "WHERE a=?" matches 10 rows, and + ** * "WHERE a=? AND b=?" matches 2 rows. + ** + ** If D is the count of distinct values and K is the total number of + ** rows, then each estimate is computed as: + ** + ** I = (K+D-1)/D + */ + char *z; + int i; + + char *zRet = sqlite3MallocZero(p->nCol * 25); + if( zRet==0 ){ + sqlite3_result_error_nomem(context); + return; + } + + sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow); + z = zRet + sqlite3Strlen30(zRet); + for(i=0; i<(p->nCol-1); i++){ + u64 nDistinct = p->current.anDLt[i] + 1; + u64 iVal = (p->nRow + nDistinct - 1) / nDistinct; + sqlite3_snprintf(24, z, " %llu", iVal); + z += sqlite3Strlen30(z); + assert( p->current.anEq[i] ); + } + assert( z[0]=='\0' && z>zRet ); + + sqlite3_result_text(context, zRet, -1, sqlite3_free); + } +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + else if( eCall==STAT_GET_ROWID ){ + if( p->iGet<0 ){ + samplePushPrevious(p, 0); + p->iGet = 0; + } + if( p->iGetnSample ){ + sqlite3_result_int64(context, p->a[p->iGet].iRowid); + } + }else{ + tRowcnt *aCnt = 0; + + assert( p->iGetnSample ); + switch( eCall ){ + case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break; + case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break; + default: { + aCnt = p->a[p->iGet].anDLt; + p->iGet++; + break; + } + } + + if( IsStat3 ){ + sqlite3_result_int64(context, (i64)aCnt[0]); + }else{ + char *zRet = sqlite3MallocZero(p->nCol * 25); + if( zRet==0 ){ + sqlite3_result_error_nomem(context); + }else{ + int i; + char *z = zRet; + for(i=0; inCol; i++){ + sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]); + z += sqlite3Strlen30(z); + } + assert( z[0]=='\0' && z>zRet ); + z[-1] = '\0'; + sqlite3_result_text(context, zRet, -1, sqlite3_free); + } + } + } +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#ifndef SQLITE_DEBUG + UNUSED_PARAMETER( argc ); +#endif +} +static const FuncDef statGetFuncdef = { + 1+IsStat34, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + statGet, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "stat_get", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ +}; + +static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){ + assert( regOut!=regStat4 && regOut!=regStat4+1 ); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1); +#elif SQLITE_DEBUG + assert( iParam==STAT_GET_STAT1 ); +#else + UNUSED_PARAMETER( iParam ); +#endif + sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut); + sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, 1 + IsStat34); +} + +/* +** Generate code to do an analysis of all indices associated with +** a single table. +*/ +static void analyzeOneTable( + Parse *pParse, /* Parser context */ + Table *pTab, /* Table whose indices are to be analyzed */ + Index *pOnlyIdx, /* If not NULL, only analyze this one index */ + int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ + int iMem, /* Available memory locations begin here */ + int iTab /* Next available cursor */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + Index *pIdx; /* An index to being analyzed */ + int iIdxCur; /* Cursor open on index being analyzed */ + int iTabCur; /* Table cursor */ + Vdbe *v; /* The virtual machine being built up */ + int i; /* Loop counter */ + int jZeroRows = -1; /* Jump from here if number of rows is zero */ + int iDb; /* Index of database containing pTab */ + u8 needTableCnt = 1; /* True to count the table */ + int regNewRowid = iMem++; /* Rowid for the inserted record */ + int regStat4 = iMem++; /* Register to hold Stat4Accum object */ + int regChng = iMem++; /* Index of changed index field */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + int regRowid = iMem++; /* Rowid argument passed to stat_push() */ +#endif + int regTemp = iMem++; /* Temporary use register */ + int regTabname = iMem++; /* Register containing table name */ + int regIdxname = iMem++; /* Register containing index name */ + int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */ + int regPrev = iMem; /* MUST BE LAST (see below) */ + + pParse->nMem = MAX(pParse->nMem, iMem); + v = sqlite3GetVdbe(pParse); + if( v==0 || NEVER(pTab==0) ){ + return; + } + if( pTab->tnum==0 ){ + /* Do not gather statistics on views or virtual tables */ + return; + } + if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){ + /* Do not gather statistics on system tables */ + return; + } + assert( sqlite3BtreeHoldsAllMutexes(db) ); + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( iDb>=0 ); + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); +#ifndef SQLITE_OMIT_AUTHORIZATION + if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0, + db->aDb[iDb].zName ) ){ + return; + } +#endif + + /* Establish a read-lock on the table at the shared-cache level. + ** Open a read-only cursor on the table. Also allocate a cursor number + ** to use for scanning indexes (iIdxCur). No index cursor is opened at + ** this time though. */ + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + iTabCur = iTab++; + iIdxCur = iTab++; + pParse->nTab = MAX(pParse->nTab, iTab); + sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); + sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0); + + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + int nCol; /* Number of columns indexed by pIdx */ + KeyInfo *pKey; /* KeyInfo structure for pIdx */ + int *aGotoChng; /* Array of jump instruction addresses */ + int addrRewind; /* Address of "OP_Rewind iIdxCur" */ + int addrGotoChng0; /* Address of "Goto addr_chng_0" */ + int addrNextRow; /* Address of "next_row:" */ + + if( pOnlyIdx && pOnlyIdx!=pIdx ) continue; + if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0; + VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName)); + nCol = pIdx->nColumn; + aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1)); + if( aGotoChng==0 ) continue; + pKey = sqlite3IndexKeyinfo(pParse, pIdx); + + /* Populate the register containing the index name. */ + sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0); + + /* + ** Pseudo-code for loop that calls stat_push(): + ** + ** Rewind csr + ** if eof(csr) goto end_of_scan; + ** regChng = 0 + ** goto chng_addr_0; + ** + ** next_row: + ** regChng = 0 + ** if( idx(0) != regPrev(0) ) goto chng_addr_0 + ** regChng = 1 + ** if( idx(1) != regPrev(1) ) goto chng_addr_1 + ** ... + ** regChng = N + ** goto chng_addr_N + ** + ** chng_addr_0: + ** regPrev(0) = idx(0) + ** chng_addr_1: + ** regPrev(1) = idx(1) + ** ... + ** + ** chng_addr_N: + ** regRowid = idx(rowid) + ** stat_push(P, regChng, regRowid) + ** Next csr + ** if !eof(csr) goto next_row; + ** + ** end_of_scan: + */ + + /* Make sure there are enough memory cells allocated to accommodate + ** the regPrev array and a trailing rowid (the rowid slot is required + ** when building a record to insert into the sample column of + ** the sqlite_stat4 table. */ + pParse->nMem = MAX(pParse->nMem, regPrev+nCol); + + /* Open a read-only cursor on the index being analyzed. */ + assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) ); + sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb); + sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIdx->zName)); + + /* Invoke the stat_init() function. The arguments are: + ** + ** (1) the number of columns in the index including the rowid, + ** (2) the number of rows in the index, + ** + ** The second argument is only used for STAT3 and STAT4 + */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2); +#endif + sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1); + sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4); + sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, 1+IsStat34); + + /* Implementation of the following: + ** + ** Rewind csr + ** if eof(csr) goto end_of_scan; + ** regChng = 0 + ** goto next_push_0; + ** + */ + addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur); + sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng); + addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto); + + /* + ** next_row: + ** regChng = 0 + ** if( idx(0) != regPrev(0) ) goto chng_addr_0 + ** regChng = 1 + ** if( idx(1) != regPrev(1) ) goto chng_addr_1 + ** ... + ** regChng = N + ** goto chng_addr_N + */ + addrNextRow = sqlite3VdbeCurrentAddr(v); + for(i=0; iazColl[i]); + sqlite3VdbeAddOp2(v, OP_Integer, i, regChng); + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp); + aGotoChng[i] = + sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ); + sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); + } + sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng); + aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto); + + /* + ** chng_addr_0: + ** regPrev(0) = idx(0) + ** chng_addr_1: + ** regPrev(1) = idx(1) + ** ... + */ + sqlite3VdbeJumpHere(v, addrGotoChng0); + for(i=0; inMem = MAX(pParse->nMem, regCol+nCol+1); + + addrNext = sqlite3VdbeCurrentAddr(v); + callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid); + addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid); + callStatGet(v, regStat4, STAT_GET_NEQ, regEq); + callStatGet(v, regStat4, STAT_GET_NLT, regLt); + callStatGet(v, regStat4, STAT_GET_NDLT, regDLt); + sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid); +#ifdef SQLITE_ENABLE_STAT3 + sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, + pIdx->aiColumn[0], regSample); +#else + for(i=0; iaiColumn[i]; + sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i); + } + sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample); +#endif + sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0); + sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid); + sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext); + sqlite3VdbeJumpHere(v, addrIsNull); + } +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + + /* End of analysis */ + sqlite3VdbeJumpHere(v, addrRewind); + sqlite3DbFree(db, aGotoChng); + } + + + /* Create a single sqlite_stat1 entry containing NULL as the index + ** name and the row count as the content. + */ + if( pOnlyIdx==0 && needTableCnt ){ + VdbeComment((v, "%s", pTab->zName)); + sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1); + jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); + sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname); + sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0); + sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); + sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3VdbeJumpHere(v, jZeroRows); + } +} + + +/* +** Generate code that will cause the most recent index analysis to +** be loaded into internal hash tables where is can be used. +*/ +static void loadAnalysis(Parse *pParse, int iDb){ + Vdbe *v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb); + } +} + +/* +** Generate code that will do an analysis of an entire database +*/ +static void analyzeDatabase(Parse *pParse, int iDb){ + sqlite3 *db = pParse->db; + Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */ + HashElem *k; + int iStatCur; + int iMem; + int iTab; + + sqlite3BeginWriteOperation(pParse, 0, iDb); + iStatCur = pParse->nTab; + pParse->nTab += 3; + openStatTable(pParse, iDb, iStatCur, 0, 0); + iMem = pParse->nMem+1; + iTab = pParse->nTab; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ + Table *pTab = (Table*)sqliteHashData(k); + analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab); + } + loadAnalysis(pParse, iDb); +} + +/* +** Generate code that will do an analysis of a single table in +** a database. If pOnlyIdx is not NULL then it is a single index +** in pTab that should be analyzed. +*/ +static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){ + int iDb; + int iStatCur; + + assert( pTab!=0 ); + assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + sqlite3BeginWriteOperation(pParse, 0, iDb); + iStatCur = pParse->nTab; + pParse->nTab += 3; + if( pOnlyIdx ){ + openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx"); + }else{ + openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl"); + } + analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab); + loadAnalysis(pParse, iDb); +} + +/* +** Generate code for the ANALYZE command. The parser calls this routine +** when it recognizes an ANALYZE command. +** +** ANALYZE -- 1 +** ANALYZE -- 2 +** ANALYZE ?.? -- 3 +** +** Form 1 causes all indices in all attached databases to be analyzed. +** Form 2 analyzes all indices the single database named. +** Form 3 analyzes all indices associated with the named table. +*/ +SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ + sqlite3 *db = pParse->db; + int iDb; + int i; + char *z, *zDb; + Table *pTab; + Index *pIdx; + Token *pTableName; + + /* Read the database schema. If an error occurs, leave an error message + ** and code in pParse and return NULL. */ + assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + return; + } + + assert( pName2!=0 || pName1==0 ); + if( pName1==0 ){ + /* Form 1: Analyze everything */ + for(i=0; inDb; i++){ + if( i==1 ) continue; /* Do not analyze the TEMP database */ + analyzeDatabase(pParse, i); + } + }else if( pName2->n==0 ){ + /* Form 2: Analyze the database or table named */ + iDb = sqlite3FindDb(db, pName1); + if( iDb>=0 ){ + analyzeDatabase(pParse, iDb); + }else{ + z = sqlite3NameFromToken(db, pName1); + if( z ){ + if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){ + analyzeTable(pParse, pIdx->pTable, pIdx); + }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){ + analyzeTable(pParse, pTab, 0); + } + sqlite3DbFree(db, z); + } + } + }else{ + /* Form 3: Analyze the fully qualified table name */ + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName); + if( iDb>=0 ){ + zDb = db->aDb[iDb].zName; + z = sqlite3NameFromToken(db, pTableName); + if( z ){ + if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){ + analyzeTable(pParse, pIdx->pTable, pIdx); + }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){ + analyzeTable(pParse, pTab, 0); + } + sqlite3DbFree(db, z); + } + } + } +} + +/* +** Used to pass information from the analyzer reader through to the +** callback routine. +*/ +typedef struct analysisInfo analysisInfo; +struct analysisInfo { + sqlite3 *db; + const char *zDatabase; +}; + +/* +** The first argument points to a nul-terminated string containing a +** list of space separated integers. Read the first nOut of these into +** the array aOut[]. +*/ +static void decodeIntArray( + char *zIntArray, /* String containing int array to decode */ + int nOut, /* Number of slots in aOut[] */ + tRowcnt *aOut, /* Store integers here */ + Index *pIndex /* Handle extra flags for this index, if not NULL */ +){ + char *z = zIntArray; + int c; + int i; + tRowcnt v; + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( z==0 ) z = ""; +#else + if( NEVER(z==0) ) z = ""; +#endif + for(i=0; *z && i='0' && c<='9' ){ + v = v*10 + c - '0'; + z++; + } + aOut[i] = v; + if( *z==' ' ) z++; + } +#ifndef SQLITE_ENABLE_STAT3_OR_STAT4 + assert( pIndex!=0 ); +#else + if( pIndex ) +#endif + { + if( strcmp(z, "unordered")==0 ){ + pIndex->bUnordered = 1; + }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){ + int v32 = 0; + sqlite3GetInt32(z+3, &v32); + pIndex->szIdxRow = sqlite3LogEst(v32); + } + } +} + +/* +** This callback is invoked once for each index when reading the +** sqlite_stat1 table. +** +** argv[0] = name of the table +** argv[1] = name of the index (might be NULL) +** argv[2] = results of analysis - on integer for each column +** +** Entries for which argv[1]==NULL simply record the number of rows in +** the table. +*/ +static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){ + analysisInfo *pInfo = (analysisInfo*)pData; + Index *pIndex; + Table *pTable; + const char *z; + + assert( argc==3 ); + UNUSED_PARAMETER2(NotUsed, argc); + + if( argv==0 || argv[0]==0 || argv[2]==0 ){ + return 0; + } + pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase); + if( pTable==0 ){ + return 0; + } + if( argv[1] ){ + pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase); + }else{ + pIndex = 0; + } + z = argv[2]; + + if( pIndex ){ + decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, pIndex); + if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0]; + }else{ + Index fakeIdx; + fakeIdx.szIdxRow = pTable->szTabRow; + decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx); + pTable->szTabRow = fakeIdx.szIdxRow; + } + + return 0; +} + +/* +** If the Index.aSample variable is not NULL, delete the aSample[] array +** and its contents. +*/ +SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( pIdx->aSample ){ + int j; + for(j=0; jnSample; j++){ + IndexSample *p = &pIdx->aSample[j]; + sqlite3DbFree(db, p->p); + } + sqlite3DbFree(db, pIdx->aSample); + } + if( db && db->pnBytesFreed==0 ){ + pIdx->nSample = 0; + pIdx->aSample = 0; + } +#else + UNUSED_PARAMETER(db); + UNUSED_PARAMETER(pIdx); +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +} + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Populate the pIdx->aAvgEq[] array based on the samples currently +** stored in pIdx->aSample[]. +*/ +static void initAvgEq(Index *pIdx){ + if( pIdx ){ + IndexSample *aSample = pIdx->aSample; + IndexSample *pFinal = &aSample[pIdx->nSample-1]; + int iCol; + for(iCol=0; iColnColumn; iCol++){ + int i; /* Used to iterate through samples */ + tRowcnt sumEq = 0; /* Sum of the nEq values */ + tRowcnt nSum = 0; /* Number of terms contributing to sumEq */ + tRowcnt avgEq = 0; + tRowcnt nDLt = pFinal->anDLt[iCol]; + + /* Set nSum to the number of distinct (iCol+1) field prefixes that + ** occur in the stat4 table for this index before pFinal. Set + ** sumEq to the sum of the nEq values for column iCol for the same + ** set (adding the value only once where there exist dupicate + ** prefixes). */ + for(i=0; i<(pIdx->nSample-1); i++){ + if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){ + sumEq += aSample[i].anEq[iCol]; + nSum++; + } + } + if( nDLt>nSum ){ + avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum); + } + if( avgEq==0 ) avgEq = 1; + pIdx->aAvgEq[iCol] = avgEq; + if( pIdx->nSampleCol==1 ) break; + } + } +} + +/* +** Load the content from either the sqlite_stat4 or sqlite_stat3 table +** into the relevant Index.aSample[] arrays. +** +** Arguments zSql1 and zSql2 must point to SQL statements that return +** data equivalent to the following (statements are different for stat3, +** see the caller of this function for details): +** +** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx +** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4 +** +** where %Q is replaced with the database name before the SQL is executed. +*/ +static int loadStatTbl( + sqlite3 *db, /* Database handle */ + int bStat3, /* Assume single column records only */ + const char *zSql1, /* SQL statement 1 (see above) */ + const char *zSql2, /* SQL statement 2 (see above) */ + const char *zDb /* Database name (e.g. "main") */ +){ + int rc; /* Result codes from subroutines */ + sqlite3_stmt *pStmt = 0; /* An SQL statement being run */ + char *zSql; /* Text of the SQL statement */ + Index *pPrevIdx = 0; /* Previous index in the loop */ + IndexSample *pSample; /* A slot in pIdx->aSample[] */ + + assert( db->lookaside.bEnabled==0 ); + zSql = sqlite3MPrintf(db, zSql1, zDb); + if( !zSql ){ + return SQLITE_NOMEM; + } + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + sqlite3DbFree(db, zSql); + if( rc ) return rc; + + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + int nIdxCol = 1; /* Number of columns in stat4 records */ + int nAvgCol = 1; /* Number of entries in Index.aAvgEq */ + + char *zIndex; /* Index name */ + Index *pIdx; /* Pointer to the index object */ + int nSample; /* Number of samples */ + int nByte; /* Bytes of space required */ + int i; /* Bytes of space required */ + tRowcnt *pSpace; + + zIndex = (char *)sqlite3_column_text(pStmt, 0); + if( zIndex==0 ) continue; + nSample = sqlite3_column_int(pStmt, 1); + pIdx = sqlite3FindIndex(db, zIndex, zDb); + assert( pIdx==0 || bStat3 || pIdx->nSample==0 ); + /* Index.nSample is non-zero at this point if data has already been + ** loaded from the stat4 table. In this case ignore stat3 data. */ + if( pIdx==0 || pIdx->nSample ) continue; + if( bStat3==0 ){ + nIdxCol = pIdx->nColumn+1; + nAvgCol = pIdx->nColumn; + } + pIdx->nSampleCol = nIdxCol; + nByte = sizeof(IndexSample) * nSample; + nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample; + nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */ + + pIdx->aSample = sqlite3DbMallocZero(db, nByte); + if( pIdx->aSample==0 ){ + sqlite3_finalize(pStmt); + return SQLITE_NOMEM; + } + pSpace = (tRowcnt*)&pIdx->aSample[nSample]; + pIdx->aAvgEq = pSpace; pSpace += nAvgCol; + for(i=0; iaSample[i].anEq = pSpace; pSpace += nIdxCol; + pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol; + pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol; + } + assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) ); + } + rc = sqlite3_finalize(pStmt); + if( rc ) return rc; + + zSql = sqlite3MPrintf(db, zSql2, zDb); + if( !zSql ){ + return SQLITE_NOMEM; + } + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + sqlite3DbFree(db, zSql); + if( rc ) return rc; + + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + char *zIndex; /* Index name */ + Index *pIdx; /* Pointer to the index object */ + int nCol = 1; /* Number of columns in index */ + + zIndex = (char *)sqlite3_column_text(pStmt, 0); + if( zIndex==0 ) continue; + pIdx = sqlite3FindIndex(db, zIndex, zDb); + if( pIdx==0 ) continue; + /* This next condition is true if data has already been loaded from + ** the sqlite_stat4 table. In this case ignore stat3 data. */ + nCol = pIdx->nSampleCol; + if( bStat3 && nCol>1 ) continue; + if( pIdx!=pPrevIdx ){ + initAvgEq(pPrevIdx); + pPrevIdx = pIdx; + } + pSample = &pIdx->aSample[pIdx->nSample]; + decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0); + decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0); + decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0); + + /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer. + ** This is in case the sample record is corrupted. In that case, the + ** sqlite3VdbeRecordCompare() may read up to two varints past the + ** end of the allocated buffer before it realizes it is dealing with + ** a corrupt record. Adding the two 0x00 bytes prevents this from causing + ** a buffer overread. */ + pSample->n = sqlite3_column_bytes(pStmt, 4); + pSample->p = sqlite3DbMallocZero(db, pSample->n + 2); + if( pSample->p==0 ){ + sqlite3_finalize(pStmt); + return SQLITE_NOMEM; + } + memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n); + pIdx->nSample++; + } + rc = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ) initAvgEq(pPrevIdx); + return rc; +} + +/* +** Load content from the sqlite_stat4 and sqlite_stat3 tables into +** the Index.aSample[] arrays of all indices. +*/ +static int loadStat4(sqlite3 *db, const char *zDb){ + int rc = SQLITE_OK; /* Result codes from subroutines */ + + assert( db->lookaside.bEnabled==0 ); + if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){ + rc = loadStatTbl(db, 0, + "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", + "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4", + zDb + ); + } + + if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){ + rc = loadStatTbl(db, 1, + "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", + "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3", + zDb + ); + } + + return rc; +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +/* +** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The +** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] +** arrays. The contents of sqlite_stat3/4 are used to populate the +** Index.aSample[] arrays. +** +** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR +** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined +** during compilation and the sqlite_stat3/4 table is present, no data is +** read from it. +** +** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the +** sqlite_stat4 table is not present in the database, SQLITE_ERROR is +** returned. However, in this case, data is read from the sqlite_stat1 +** table (if it is present) before returning. +** +** If an OOM error occurs, this function always sets db->mallocFailed. +** This means if the caller does not care about other errors, the return +** code may be ignored. +*/ +SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){ + analysisInfo sInfo; + HashElem *i; + char *zSql; + int rc; + + assert( iDb>=0 && iDbnDb ); + assert( db->aDb[iDb].pBt!=0 ); + + /* Clear any prior statistics */ + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ + Index *pIdx = sqliteHashData(i); + sqlite3DefaultRowEst(pIdx); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sqlite3DeleteIndexSamples(db, pIdx); + pIdx->aSample = 0; +#endif + } + + /* Check to make sure the sqlite_stat1 table exists */ + sInfo.db = db; + sInfo.zDatabase = db->aDb[iDb].zName; + if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){ + return SQLITE_ERROR; + } + + /* Load new statistics out of the sqlite_stat1 table */ + zSql = sqlite3MPrintf(db, + "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase); + if( zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0); + sqlite3DbFree(db, zSql); + } + + + /* Load the statistics from the sqlite_stat4 table. */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( rc==SQLITE_OK ){ + int lookasideEnabled = db->lookaside.bEnabled; + db->lookaside.bEnabled = 0; + rc = loadStat4(db, sInfo.zDatabase); + db->lookaside.bEnabled = lookasideEnabled; + } +#endif + + if( rc==SQLITE_NOMEM ){ + db->mallocFailed = 1; + } + return rc; +} + + +#endif /* SQLITE_OMIT_ANALYZE */ + +/************** End of analyze.c *********************************************/ +/************** Begin file attach.c ******************************************/ +/* +** 2003 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the ATTACH and DETACH commands. +*/ + +#ifndef SQLITE_OMIT_ATTACH +/* +** Resolve an expression that was part of an ATTACH or DETACH statement. This +** is slightly different from resolving a normal SQL expression, because simple +** identifiers are treated as strings, not possible column names or aliases. +** +** i.e. if the parser sees: +** +** ATTACH DATABASE abc AS def +** +** it treats the two expressions as literal strings 'abc' and 'def' instead of +** looking for columns of the same name. +** +** This only applies to the root node of pExpr, so the statement: +** +** ATTACH DATABASE abc||def AS 'db2' +** +** will fail because neither abc or def can be resolved. +*/ +static int resolveAttachExpr(NameContext *pName, Expr *pExpr) +{ + int rc = SQLITE_OK; + if( pExpr ){ + if( pExpr->op!=TK_ID ){ + rc = sqlite3ResolveExprNames(pName, pExpr); + if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){ + sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken); + return SQLITE_ERROR; + } + }else{ + pExpr->op = TK_STRING; + } + } + return rc; +} + +/* +** An SQL user-function registered to do the work of an ATTACH statement. The +** three arguments to the function come directly from an attach statement: +** +** ATTACH DATABASE x AS y KEY z +** +** SELECT sqlite_attach(x, y, z) +** +** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the +** third argument. +*/ +static void attachFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + int i; + int rc = 0; + sqlite3 *db = sqlite3_context_db_handle(context); + const char *zName; + const char *zFile; + char *zPath = 0; + char *zErr = 0; + unsigned int flags; + Db *aNew; + char *zErrDyn = 0; + sqlite3_vfs *pVfs; + + UNUSED_PARAMETER(NotUsed); + + zFile = (const char *)sqlite3_value_text(argv[0]); + zName = (const char *)sqlite3_value_text(argv[1]); + if( zFile==0 ) zFile = ""; + if( zName==0 ) zName = ""; + + /* Check for the following errors: + ** + ** * Too many attached databases, + ** * Transaction currently open + ** * Specified database name already being used. + */ + if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){ + zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", + db->aLimit[SQLITE_LIMIT_ATTACHED] + ); + goto attach_error; + } + if( !db->autoCommit ){ + zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction"); + goto attach_error; + } + for(i=0; inDb; i++){ + char *z = db->aDb[i].zName; + assert( z && zName ); + if( sqlite3StrICmp(z, zName)==0 ){ + zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName); + goto attach_error; + } + } + + /* Allocate the new entry in the db->aDb[] array and initialize the schema + ** hash tables. + */ + if( db->aDb==db->aDbStatic ){ + aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 ); + if( aNew==0 ) return; + memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); + }else{ + aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); + if( aNew==0 ) return; + } + db->aDb = aNew; + aNew = &db->aDb[db->nDb]; + memset(aNew, 0, sizeof(*aNew)); + + /* Open the database file. If the btree is successfully opened, use + ** it to obtain the database schema. At this point the schema may + ** or may not be initialized. + */ + flags = db->openFlags; + rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM ) db->mallocFailed = 1; + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); + return; + } + assert( pVfs ); + flags |= SQLITE_OPEN_MAIN_DB; + rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags); + sqlite3_free( zPath ); + db->nDb++; + if( rc==SQLITE_CONSTRAINT ){ + rc = SQLITE_ERROR; + zErrDyn = sqlite3MPrintf(db, "database is already attached"); + }else if( rc==SQLITE_OK ){ + Pager *pPager; + aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt); + if( !aNew->pSchema ){ + rc = SQLITE_NOMEM; + }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){ + zErrDyn = sqlite3MPrintf(db, + "attached databases must use the same text encoding as main database"); + rc = SQLITE_ERROR; + } + pPager = sqlite3BtreePager(aNew->pBt); + sqlite3PagerLockingMode(pPager, db->dfltLockMode); + sqlite3BtreeSecureDelete(aNew->pBt, + sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) ); +#ifndef SQLITE_OMIT_PAGER_PRAGMAS + sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK)); +#endif + } + aNew->safety_level = 3; + aNew->zName = sqlite3DbStrDup(db, zName); + if( rc==SQLITE_OK && aNew->zName==0 ){ + rc = SQLITE_NOMEM; + } + + +#ifdef SQLITE_HAS_CODEC + if( rc==SQLITE_OK ){ + extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); + extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); + int nKey; + char *zKey; + int t = sqlite3_value_type(argv[2]); + switch( t ){ + case SQLITE_INTEGER: + case SQLITE_FLOAT: + zErrDyn = sqlite3DbStrDup(db, "Invalid key value"); + rc = SQLITE_ERROR; + break; + + case SQLITE_TEXT: + case SQLITE_BLOB: + nKey = sqlite3_value_bytes(argv[2]); + zKey = (char *)sqlite3_value_blob(argv[2]); + rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); + break; + + case SQLITE_NULL: + /* No key specified. Use the key from the main database */ + sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); + if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){ + rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); + } + break; + } + } +#endif + + /* If the file was opened successfully, read the schema for the new database. + ** If this fails, or if opening the file failed, then close the file and + ** remove the entry from the db->aDb[] array. i.e. put everything back the way + ** we found it. + */ + if( rc==SQLITE_OK ){ + sqlite3BtreeEnterAll(db); + rc = sqlite3Init(db, &zErrDyn); + sqlite3BtreeLeaveAll(db); + } + if( rc ){ + int iDb = db->nDb - 1; + assert( iDb>=2 ); + if( db->aDb[iDb].pBt ){ + sqlite3BtreeClose(db->aDb[iDb].pBt); + db->aDb[iDb].pBt = 0; + db->aDb[iDb].pSchema = 0; + } + sqlite3ResetAllSchemasOfConnection(db); + db->nDb = iDb; + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ + db->mallocFailed = 1; + sqlite3DbFree(db, zErrDyn); + zErrDyn = sqlite3MPrintf(db, "out of memory"); + }else if( zErrDyn==0 ){ + zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile); + } + goto attach_error; + } + + return; + +attach_error: + /* Return an error if we get here */ + if( zErrDyn ){ + sqlite3_result_error(context, zErrDyn, -1); + sqlite3DbFree(db, zErrDyn); + } + if( rc ) sqlite3_result_error_code(context, rc); +} + +/* +** An SQL user-function registered to do the work of an DETACH statement. The +** three arguments to the function come directly from a detach statement: +** +** DETACH DATABASE x +** +** SELECT sqlite_detach(x) +*/ +static void detachFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + const char *zName = (const char *)sqlite3_value_text(argv[0]); + sqlite3 *db = sqlite3_context_db_handle(context); + int i; + Db *pDb = 0; + char zErr[128]; + + UNUSED_PARAMETER(NotUsed); + + if( zName==0 ) zName = ""; + for(i=0; inDb; i++){ + pDb = &db->aDb[i]; + if( pDb->pBt==0 ) continue; + if( sqlite3StrICmp(pDb->zName, zName)==0 ) break; + } + + if( i>=db->nDb ){ + sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName); + goto detach_error; + } + if( i<2 ){ + sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName); + goto detach_error; + } + if( !db->autoCommit ){ + sqlite3_snprintf(sizeof(zErr), zErr, + "cannot DETACH database within transaction"); + goto detach_error; + } + if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){ + sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName); + goto detach_error; + } + + sqlite3BtreeClose(pDb->pBt); + pDb->pBt = 0; + pDb->pSchema = 0; + sqlite3ResetAllSchemasOfConnection(db); + return; + +detach_error: + sqlite3_result_error(context, zErr, -1); +} + +/* +** This procedure generates VDBE code for a single invocation of either the +** sqlite_detach() or sqlite_attach() SQL user functions. +*/ +static void codeAttach( + Parse *pParse, /* The parser context */ + int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */ + FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */ + Expr *pAuthArg, /* Expression to pass to authorization callback */ + Expr *pFilename, /* Name of database file */ + Expr *pDbname, /* Name of the database to use internally */ + Expr *pKey /* Database key for encryption extension */ +){ + int rc; + NameContext sName; + Vdbe *v; + sqlite3* db = pParse->db; + int regArgs; + + memset(&sName, 0, sizeof(NameContext)); + sName.pParse = pParse; + + if( + SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) || + SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) || + SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey)) + ){ + pParse->nErr++; + goto attach_end; + } + +#ifndef SQLITE_OMIT_AUTHORIZATION + if( pAuthArg ){ + char *zAuthArg; + if( pAuthArg->op==TK_STRING ){ + zAuthArg = pAuthArg->u.zToken; + }else{ + zAuthArg = 0; + } + rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); + if(rc!=SQLITE_OK ){ + goto attach_end; + } + } +#endif /* SQLITE_OMIT_AUTHORIZATION */ + + + v = sqlite3GetVdbe(pParse); + regArgs = sqlite3GetTempRange(pParse, 4); + sqlite3ExprCode(pParse, pFilename, regArgs); + sqlite3ExprCode(pParse, pDbname, regArgs+1); + sqlite3ExprCode(pParse, pKey, regArgs+2); + + assert( v || db->mallocFailed ); + if( v ){ + sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3); + assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg ); + sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg)); + sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF); + + /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this + ** statement only). For DETACH, set it to false (expire all existing + ** statements). + */ + sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH)); + } + +attach_end: + sqlite3ExprDelete(db, pFilename); + sqlite3ExprDelete(db, pDbname); + sqlite3ExprDelete(db, pKey); +} + +/* +** Called by the parser to compile a DETACH statement. +** +** DETACH pDbname +*/ +SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){ + static const FuncDef detach_func = { + 1, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + detachFunc, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "sqlite_detach", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ + }; + codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname); +} + +/* +** Called by the parser to compile an ATTACH statement. +** +** ATTACH p AS pDbname KEY pKey +*/ +SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){ + static const FuncDef attach_func = { + 3, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + attachFunc, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "sqlite_attach", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ + }; + codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey); +} +#endif /* SQLITE_OMIT_ATTACH */ + +/* +** Initialize a DbFixer structure. This routine must be called prior +** to passing the structure to one of the sqliteFixAAAA() routines below. +*/ +SQLITE_PRIVATE void sqlite3FixInit( + DbFixer *pFix, /* The fixer to be initialized */ + Parse *pParse, /* Error messages will be written here */ + int iDb, /* This is the database that must be used */ + const char *zType, /* "view", "trigger", or "index" */ + const Token *pName /* Name of the view, trigger, or index */ +){ + sqlite3 *db; + + db = pParse->db; + assert( db->nDb>iDb ); + pFix->pParse = pParse; + pFix->zDb = db->aDb[iDb].zName; + pFix->pSchema = db->aDb[iDb].pSchema; + pFix->zType = zType; + pFix->pName = pName; + pFix->bVarOnly = (iDb==1); +} + +/* +** The following set of routines walk through the parse tree and assign +** a specific database to all table references where the database name +** was left unspecified in the original SQL statement. The pFix structure +** must have been initialized by a prior call to sqlite3FixInit(). +** +** These routines are used to make sure that an index, trigger, or +** view in one database does not refer to objects in a different database. +** (Exception: indices, triggers, and views in the TEMP database are +** allowed to refer to anything.) If a reference is explicitly made +** to an object in a different database, an error message is added to +** pParse->zErrMsg and these routines return non-zero. If everything +** checks out, these routines return 0. +*/ +SQLITE_PRIVATE int sqlite3FixSrcList( + DbFixer *pFix, /* Context of the fixation */ + SrcList *pList /* The Source list to check and modify */ +){ + int i; + const char *zDb; + struct SrcList_item *pItem; + + if( NEVER(pList==0) ) return 0; + zDb = pFix->zDb; + for(i=0, pItem=pList->a; inSrc; i++, pItem++){ + if( pFix->bVarOnly==0 ){ + if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){ + sqlite3ErrorMsg(pFix->pParse, + "%s %T cannot reference objects in database %s", + pFix->zType, pFix->pName, pItem->zDatabase); + return 1; + } + sqlite3DbFree(pFix->pParse->db, pItem->zDatabase); + pItem->zDatabase = 0; + pItem->pSchema = pFix->pSchema; + } +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) + if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1; + if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1; +#endif + } + return 0; +} +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) +SQLITE_PRIVATE int sqlite3FixSelect( + DbFixer *pFix, /* Context of the fixation */ + Select *pSelect /* The SELECT statement to be fixed to one database */ +){ + while( pSelect ){ + if( sqlite3FixExprList(pFix, pSelect->pEList) ){ + return 1; + } + if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pSelect->pWhere) ){ + return 1; + } + if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pSelect->pHaving) ){ + return 1; + } + if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pSelect->pLimit) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pSelect->pOffset) ){ + return 1; + } + pSelect = pSelect->pPrior; + } + return 0; +} +SQLITE_PRIVATE int sqlite3FixExpr( + DbFixer *pFix, /* Context of the fixation */ + Expr *pExpr /* The expression to be fixed to one database */ +){ + while( pExpr ){ + if( pExpr->op==TK_VARIABLE ){ + if( pFix->pParse->db->init.busy ){ + pExpr->op = TK_NULL; + }else{ + sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType); + return 1; + } + } + if( ExprHasProperty(pExpr, EP_TokenOnly) ) break; + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1; + }else{ + if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1; + } + if( sqlite3FixExpr(pFix, pExpr->pRight) ){ + return 1; + } + pExpr = pExpr->pLeft; + } + return 0; +} +SQLITE_PRIVATE int sqlite3FixExprList( + DbFixer *pFix, /* Context of the fixation */ + ExprList *pList /* The expression to be fixed to one database */ +){ + int i; + struct ExprList_item *pItem; + if( pList==0 ) return 0; + for(i=0, pItem=pList->a; inExpr; i++, pItem++){ + if( sqlite3FixExpr(pFix, pItem->pExpr) ){ + return 1; + } + } + return 0; +} +#endif + +#ifndef SQLITE_OMIT_TRIGGER +SQLITE_PRIVATE int sqlite3FixTriggerStep( + DbFixer *pFix, /* Context of the fixation */ + TriggerStep *pStep /* The trigger step be fixed to one database */ +){ + while( pStep ){ + if( sqlite3FixSelect(pFix, pStep->pSelect) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pStep->pWhere) ){ + return 1; + } + if( sqlite3FixExprList(pFix, pStep->pExprList) ){ + return 1; + } + pStep = pStep->pNext; + } + return 0; +} +#endif + +/************** End of attach.c **********************************************/ +/************** Begin file auth.c ********************************************/ +/* +** 2003 January 11 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the sqlite3_set_authorizer() +** API. This facility is an optional feature of the library. Embedded +** systems that do not need this facility may omit it by recompiling +** the library with -DSQLITE_OMIT_AUTHORIZATION=1 +*/ + +/* +** All of the code in this file may be omitted by defining a single +** macro. +*/ +#ifndef SQLITE_OMIT_AUTHORIZATION + +/* +** Set or clear the access authorization function. +** +** The access authorization function is be called during the compilation +** phase to verify that the user has read and/or write access permission on +** various fields of the database. The first argument to the auth function +** is a copy of the 3rd argument to this routine. The second argument +** to the auth function is one of these constants: +** +** SQLITE_CREATE_INDEX +** SQLITE_CREATE_TABLE +** SQLITE_CREATE_TEMP_INDEX +** SQLITE_CREATE_TEMP_TABLE +** SQLITE_CREATE_TEMP_TRIGGER +** SQLITE_CREATE_TEMP_VIEW +** SQLITE_CREATE_TRIGGER +** SQLITE_CREATE_VIEW +** SQLITE_DELETE +** SQLITE_DROP_INDEX +** SQLITE_DROP_TABLE +** SQLITE_DROP_TEMP_INDEX +** SQLITE_DROP_TEMP_TABLE +** SQLITE_DROP_TEMP_TRIGGER +** SQLITE_DROP_TEMP_VIEW +** SQLITE_DROP_TRIGGER +** SQLITE_DROP_VIEW +** SQLITE_INSERT +** SQLITE_PRAGMA +** SQLITE_READ +** SQLITE_SELECT +** SQLITE_TRANSACTION +** SQLITE_UPDATE +** +** The third and fourth arguments to the auth function are the name of +** the table and the column that are being accessed. The auth function +** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If +** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY +** means that the SQL statement will never-run - the sqlite3_exec() call +** will return with an error. SQLITE_IGNORE means that the SQL statement +** should run but attempts to read the specified column will return NULL +** and attempts to write the column will be ignored. +** +** Setting the auth function to NULL disables this hook. The default +** setting of the auth function is NULL. +*/ +SQLITE_API int sqlite3_set_authorizer( + sqlite3 *db, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pArg +){ + sqlite3_mutex_enter(db->mutex); + db->xAuth = xAuth; + db->pAuthArg = pArg; + sqlite3ExpirePreparedStatements(db); + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +/* +** Write an error message into pParse->zErrMsg that explains that the +** user-supplied authorization function returned an illegal value. +*/ +static void sqliteAuthBadReturnCode(Parse *pParse){ + sqlite3ErrorMsg(pParse, "authorizer malfunction"); + pParse->rc = SQLITE_ERROR; +} + +/* +** Invoke the authorization callback for permission to read column zCol from +** table zTab in database zDb. This function assumes that an authorization +** callback has been registered (i.e. that sqlite3.xAuth is not NULL). +** +** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed +** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE +** is treated as SQLITE_DENY. In this case an error is left in pParse. +*/ +SQLITE_PRIVATE int sqlite3AuthReadCol( + Parse *pParse, /* The parser context */ + const char *zTab, /* Table name */ + const char *zCol, /* Column name */ + int iDb /* Index of containing database. */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + char *zDb = db->aDb[iDb].zName; /* Name of attached database */ + int rc; /* Auth callback return code */ + + rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext); + if( rc==SQLITE_DENY ){ + if( db->nDb>2 || iDb!=0 ){ + sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol); + }else{ + sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol); + } + pParse->rc = SQLITE_AUTH; + }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){ + sqliteAuthBadReturnCode(pParse); + } + return rc; +} + +/* +** The pExpr should be a TK_COLUMN expression. The table referred to +** is in pTabList or else it is the NEW or OLD table of a trigger. +** Check to see if it is OK to read this particular column. +** +** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN +** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, +** then generate an error. +*/ +SQLITE_PRIVATE void sqlite3AuthRead( + Parse *pParse, /* The parser context */ + Expr *pExpr, /* The expression to check authorization on */ + Schema *pSchema, /* The schema of the expression */ + SrcList *pTabList /* All table that pExpr might refer to */ +){ + sqlite3 *db = pParse->db; + Table *pTab = 0; /* The table being read */ + const char *zCol; /* Name of the column of the table */ + int iSrc; /* Index in pTabList->a[] of table being read */ + int iDb; /* The index of the database the expression refers to */ + int iCol; /* Index of column in table */ + + if( db->xAuth==0 ) return; + iDb = sqlite3SchemaToIndex(pParse->db, pSchema); + if( iDb<0 ){ + /* An attempt to read a column out of a subquery or other + ** temporary table. */ + return; + } + + assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); + if( pExpr->op==TK_TRIGGER ){ + pTab = pParse->pTriggerTab; + }else{ + assert( pTabList ); + for(iSrc=0; ALWAYS(iSrcnSrc); iSrc++){ + if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ + pTab = pTabList->a[iSrc].pTab; + break; + } + } + } + iCol = pExpr->iColumn; + if( NEVER(pTab==0) ) return; + + if( iCol>=0 ){ + assert( iColnCol ); + zCol = pTab->aCol[iCol].zName; + }else if( pTab->iPKey>=0 ){ + assert( pTab->iPKeynCol ); + zCol = pTab->aCol[pTab->iPKey].zName; + }else{ + zCol = "ROWID"; + } + assert( iDb>=0 && iDbnDb ); + if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ + pExpr->op = TK_NULL; + } +} + +/* +** Do an authorization check using the code and arguments given. Return +** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY +** is returned, then the error count and error message in pParse are +** modified appropriately. +*/ +SQLITE_PRIVATE int sqlite3AuthCheck( + Parse *pParse, + int code, + const char *zArg1, + const char *zArg2, + const char *zArg3 +){ + sqlite3 *db = pParse->db; + int rc; + + /* Don't do any authorization checks if the database is initialising + ** or if the parser is being invoked from within sqlite3_declare_vtab. + */ + if( db->init.busy || IN_DECLARE_VTAB ){ + return SQLITE_OK; + } + + if( db->xAuth==0 ){ + return SQLITE_OK; + } + rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext); + if( rc==SQLITE_DENY ){ + sqlite3ErrorMsg(pParse, "not authorized"); + pParse->rc = SQLITE_AUTH; + }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ + rc = SQLITE_DENY; + sqliteAuthBadReturnCode(pParse); + } + return rc; +} + +/* +** Push an authorization context. After this routine is called, the +** zArg3 argument to authorization callbacks will be zContext until +** popped. Or if pParse==0, this routine is a no-op. +*/ +SQLITE_PRIVATE void sqlite3AuthContextPush( + Parse *pParse, + AuthContext *pContext, + const char *zContext +){ + assert( pParse ); + pContext->pParse = pParse; + pContext->zAuthContext = pParse->zAuthContext; + pParse->zAuthContext = zContext; +} + +/* +** Pop an authorization context that was previously pushed +** by sqlite3AuthContextPush +*/ +SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){ + if( pContext->pParse ){ + pContext->pParse->zAuthContext = pContext->zAuthContext; + pContext->pParse = 0; + } +} + +#endif /* SQLITE_OMIT_AUTHORIZATION */ + +/************** End of auth.c ************************************************/ +/************** Begin file build.c *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that are called by the SQLite parser +** when syntax rules are reduced. The routines in this file handle the +** following kinds of SQL syntax: +** +** CREATE TABLE +** DROP TABLE +** CREATE INDEX +** DROP INDEX +** creating ID lists +** BEGIN TRANSACTION +** COMMIT +** ROLLBACK +*/ + +/* +** This routine is called when a new SQL statement is beginning to +** be parsed. Initialize the pParse structure as needed. +*/ +SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){ + pParse->explain = (u8)explainFlag; + pParse->nVar = 0; +} + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** The TableLock structure is only used by the sqlite3TableLock() and +** codeTableLocks() functions. +*/ +struct TableLock { + int iDb; /* The database containing the table to be locked */ + int iTab; /* The root page of the table to be locked */ + u8 isWriteLock; /* True for write lock. False for a read lock */ + const char *zName; /* Name of the table */ +}; + +/* +** Record the fact that we want to lock a table at run-time. +** +** The table to be locked has root page iTab and is found in database iDb. +** A read or a write lock can be taken depending on isWritelock. +** +** This routine just records the fact that the lock is desired. The +** code to make the lock occur is generated by a later call to +** codeTableLocks() which occurs during sqlite3FinishCoding(). +*/ +SQLITE_PRIVATE void sqlite3TableLock( + Parse *pParse, /* Parsing context */ + int iDb, /* Index of the database containing the table to lock */ + int iTab, /* Root page number of the table to be locked */ + u8 isWriteLock, /* True for a write lock */ + const char *zName /* Name of the table to be locked */ +){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + int i; + int nBytes; + TableLock *p; + assert( iDb>=0 ); + + for(i=0; inTableLock; i++){ + p = &pToplevel->aTableLock[i]; + if( p->iDb==iDb && p->iTab==iTab ){ + p->isWriteLock = (p->isWriteLock || isWriteLock); + return; + } + } + + nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); + pToplevel->aTableLock = + sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); + if( pToplevel->aTableLock ){ + p = &pToplevel->aTableLock[pToplevel->nTableLock++]; + p->iDb = iDb; + p->iTab = iTab; + p->isWriteLock = isWriteLock; + p->zName = zName; + }else{ + pToplevel->nTableLock = 0; + pToplevel->db->mallocFailed = 1; + } +} + +/* +** Code an OP_TableLock instruction for each table locked by the +** statement (configured by calls to sqlite3TableLock()). +*/ +static void codeTableLocks(Parse *pParse){ + int i; + Vdbe *pVdbe; + + pVdbe = sqlite3GetVdbe(pParse); + assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ + + for(i=0; inTableLock; i++){ + TableLock *p = &pParse->aTableLock[i]; + int p1 = p->iDb; + sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, + p->zName, P4_STATIC); + } +} +#else + #define codeTableLocks(x) +#endif + +/* +** This routine is called after a single SQL statement has been +** parsed and a VDBE program to execute that statement has been +** prepared. This routine puts the finishing touches on the +** VDBE program and resets the pParse structure for the next +** parse. +** +** Note that if an error occurred, it might be the case that +** no VDBE code was generated. +*/ +SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ + sqlite3 *db; + Vdbe *v; + + assert( pParse->pToplevel==0 ); + db = pParse->db; + if( db->mallocFailed ) return; + if( pParse->nested ) return; + if( pParse->nErr ) return; + + /* Begin by generating some termination code at the end of the + ** vdbe program + */ + v = sqlite3GetVdbe(pParse); + assert( !pParse->isMultiWrite + || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); + if( v ){ + sqlite3VdbeAddOp0(v, OP_Halt); + + /* The cookie mask contains one bit for each database file open. + ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are + ** set for each database that is used. Generate code to start a + ** transaction on each used database and to verify the schema cookie + ** on each used database. + */ + if( pParse->cookieGoto>0 ){ + yDbMask mask; + int iDb; + sqlite3VdbeJumpHere(v, pParse->cookieGoto-1); + for(iDb=0, mask=1; iDbnDb; mask<<=1, iDb++){ + if( (mask & pParse->cookieMask)==0 ) continue; + sqlite3VdbeUsesBtree(v, iDb); + sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0); + if( db->init.busy==0 ){ + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + sqlite3VdbeAddOp3(v, OP_VerifyCookie, + iDb, pParse->cookieValue[iDb], + db->aDb[iDb].pSchema->iGeneration); + } + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + { + int i; + for(i=0; inVtabLock; i++){ + char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); + sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); + } + pParse->nVtabLock = 0; + } +#endif + + /* Once all the cookies have been verified and transactions opened, + ** obtain the required table-locks. This is a no-op unless the + ** shared-cache feature is enabled. + */ + codeTableLocks(pParse); + + /* Initialize any AUTOINCREMENT data structures required. + */ + sqlite3AutoincrementBegin(pParse); + + /* Finally, jump back to the beginning of the executable code. */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto); + } + } + + + /* Get the VDBE program ready for execution + */ + if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){ +#ifdef SQLITE_DEBUG + FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0; + sqlite3VdbeTrace(v, trace); +#endif + assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ + /* A minimum of one cursor is required if autoincrement is used + * See ticket [a696379c1f08866] */ + if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; + sqlite3VdbeMakeReady(v, pParse); + pParse->rc = SQLITE_DONE; + pParse->colNamesSet = 0; + }else{ + pParse->rc = SQLITE_ERROR; + } + pParse->nTab = 0; + pParse->nMem = 0; + pParse->nSet = 0; + pParse->nVar = 0; + pParse->cookieMask = 0; + pParse->cookieGoto = 0; +} + +/* +** Run the parser and code generator recursively in order to generate +** code for the SQL statement given onto the end of the pParse context +** currently under construction. When the parser is run recursively +** this way, the final OP_Halt is not appended and other initialization +** and finalization steps are omitted because those are handling by the +** outermost parser. +** +** Not everything is nestable. This facility is designed to permit +** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use +** care if you decide to try to use this routine for some other purposes. +*/ +SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ + va_list ap; + char *zSql; + char *zErrMsg = 0; + sqlite3 *db = pParse->db; +# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) + char saveBuf[SAVE_SZ]; + + if( pParse->nErr ) return; + assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ + va_start(ap, zFormat); + zSql = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + if( zSql==0 ){ + return; /* A malloc must have failed */ + } + pParse->nested++; + memcpy(saveBuf, &pParse->nVar, SAVE_SZ); + memset(&pParse->nVar, 0, SAVE_SZ); + sqlite3RunParser(pParse, zSql, &zErrMsg); + sqlite3DbFree(db, zErrMsg); + sqlite3DbFree(db, zSql); + memcpy(&pParse->nVar, saveBuf, SAVE_SZ); + pParse->nested--; +} + +/* +** Locate the in-memory structure that describes a particular database +** table given the name of that table and (optionally) the name of the +** database containing the table. Return NULL if not found. +** +** If zDatabase is 0, all databases are searched for the table and the +** first matching table is returned. (No checking for duplicate table +** names is done.) The search order is TEMP first, then MAIN, then any +** auxiliary databases added using the ATTACH command. +** +** See also sqlite3LocateTable(). +*/ +SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ + Table *p = 0; + int i; + int nName; + assert( zName!=0 ); + nName = sqlite3Strlen30(zName); + /* All mutexes are required for schema access. Make sure we hold them. */ + assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); + for(i=OMIT_TEMPDB; inDb; i++){ + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ + if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; + assert( sqlite3SchemaMutexHeld(db, j, 0) ); + p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName); + if( p ) break; + } + return p; +} + +/* +** Locate the in-memory structure that describes a particular database +** table given the name of that table and (optionally) the name of the +** database containing the table. Return NULL if not found. Also leave an +** error message in pParse->zErrMsg. +** +** The difference between this routine and sqlite3FindTable() is that this +** routine leaves an error message in pParse->zErrMsg where +** sqlite3FindTable() does not. +*/ +SQLITE_PRIVATE Table *sqlite3LocateTable( + Parse *pParse, /* context in which to report errors */ + int isView, /* True if looking for a VIEW rather than a TABLE */ + const char *zName, /* Name of the table we are looking for */ + const char *zDbase /* Name of the database. Might be NULL */ +){ + Table *p; + + /* Read the database schema. If an error occurs, leave an error message + ** and code in pParse and return NULL. */ + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + return 0; + } + + p = sqlite3FindTable(pParse->db, zName, zDbase); + if( p==0 ){ + const char *zMsg = isView ? "no such view" : "no such table"; + if( zDbase ){ + sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); + }else{ + sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); + } + pParse->checkSchema = 1; + } + return p; +} + +/* +** Locate the table identified by *p. +** +** This is a wrapper around sqlite3LocateTable(). The difference between +** sqlite3LocateTable() and this function is that this function restricts +** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be +** non-NULL if it is part of a view or trigger program definition. See +** sqlite3FixSrcList() for details. +*/ +SQLITE_PRIVATE Table *sqlite3LocateTableItem( + Parse *pParse, + int isView, + struct SrcList_item *p +){ + const char *zDb; + assert( p->pSchema==0 || p->zDatabase==0 ); + if( p->pSchema ){ + int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); + zDb = pParse->db->aDb[iDb].zName; + }else{ + zDb = p->zDatabase; + } + return sqlite3LocateTable(pParse, isView, p->zName, zDb); +} + +/* +** Locate the in-memory structure that describes +** a particular index given the name of that index +** and the name of the database that contains the index. +** Return NULL if not found. +** +** If zDatabase is 0, all databases are searched for the +** table and the first matching index is returned. (No checking +** for duplicate index names is done.) The search order is +** TEMP first, then MAIN, then any auxiliary databases added +** using the ATTACH command. +*/ +SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ + Index *p = 0; + int i; + int nName = sqlite3Strlen30(zName); + /* All mutexes are required for schema access. Make sure we hold them. */ + assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); + for(i=OMIT_TEMPDB; inDb; i++){ + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ + Schema *pSchema = db->aDb[j].pSchema; + assert( pSchema ); + if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; + assert( sqlite3SchemaMutexHeld(db, j, 0) ); + p = sqlite3HashFind(&pSchema->idxHash, zName, nName); + if( p ) break; + } + return p; +} + +/* +** Reclaim the memory used by an index +*/ +static void freeIndex(sqlite3 *db, Index *p){ +#ifndef SQLITE_OMIT_ANALYZE + sqlite3DeleteIndexSamples(db, p); +#endif + sqlite3ExprDelete(db, p->pPartIdxWhere); + sqlite3DbFree(db, p->zColAff); + sqlite3DbFree(db, p); +} + +/* +** For the index called zIdxName which is found in the database iDb, +** unlike that index from its Table then remove the index from +** the index hash table and free all memory structures associated +** with the index. +*/ +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ + Index *pIndex; + int len; + Hash *pHash; + + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pHash = &db->aDb[iDb].pSchema->idxHash; + len = sqlite3Strlen30(zIdxName); + pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0); + if( ALWAYS(pIndex) ){ + if( pIndex->pTable->pIndex==pIndex ){ + pIndex->pTable->pIndex = pIndex->pNext; + }else{ + Index *p; + /* Justification of ALWAYS(); The index must be on the list of + ** indices. */ + p = pIndex->pTable->pIndex; + while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } + if( ALWAYS(p && p->pNext==pIndex) ){ + p->pNext = pIndex->pNext; + } + } + freeIndex(db, pIndex); + } + db->flags |= SQLITE_InternChanges; +} + +/* +** Look through the list of open database files in db->aDb[] and if +** any have been closed, remove them from the list. Reallocate the +** db->aDb[] structure to a smaller size, if possible. +** +** Entry 0 (the "main" database) and entry 1 (the "temp" database) +** are never candidates for being collapsed. +*/ +SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){ + int i, j; + for(i=j=2; inDb; i++){ + struct Db *pDb = &db->aDb[i]; + if( pDb->pBt==0 ){ + sqlite3DbFree(db, pDb->zName); + pDb->zName = 0; + continue; + } + if( jaDb[j] = db->aDb[i]; + } + j++; + } + memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); + db->nDb = j; + if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ + memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); + sqlite3DbFree(db, db->aDb); + db->aDb = db->aDbStatic; + } +} + +/* +** Reset the schema for the database at index iDb. Also reset the +** TEMP schema. +*/ +SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ + Db *pDb; + assert( iDbnDb ); + + /* Case 1: Reset the single schema identified by iDb */ + pDb = &db->aDb[iDb]; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( pDb->pSchema!=0 ); + sqlite3SchemaClear(pDb->pSchema); + + /* If any database other than TEMP is reset, then also reset TEMP + ** since TEMP might be holding triggers that reference tables in the + ** other database. + */ + if( iDb!=1 ){ + pDb = &db->aDb[1]; + assert( pDb->pSchema!=0 ); + sqlite3SchemaClear(pDb->pSchema); + } + return; +} + +/* +** Erase all schema information from all attached databases (including +** "main" and "temp") for a single database connection. +*/ +SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ + int i; + sqlite3BtreeEnterAll(db); + for(i=0; inDb; i++){ + Db *pDb = &db->aDb[i]; + if( pDb->pSchema ){ + sqlite3SchemaClear(pDb->pSchema); + } + } + db->flags &= ~SQLITE_InternChanges; + sqlite3VtabUnlockList(db); + sqlite3BtreeLeaveAll(db); + sqlite3CollapseDatabaseArray(db); +} + +/* +** This routine is called when a commit occurs. +*/ +SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){ + db->flags &= ~SQLITE_InternChanges; +} + +/* +** Delete memory allocated for the column names of a table or view (the +** Table.aCol[] array). +*/ +static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){ + int i; + Column *pCol; + assert( pTable!=0 ); + if( (pCol = pTable->aCol)!=0 ){ + for(i=0; inCol; i++, pCol++){ + sqlite3DbFree(db, pCol->zName); + sqlite3ExprDelete(db, pCol->pDflt); + sqlite3DbFree(db, pCol->zDflt); + sqlite3DbFree(db, pCol->zType); + sqlite3DbFree(db, pCol->zColl); + } + sqlite3DbFree(db, pTable->aCol); + } +} + +/* +** Remove the memory data structures associated with the given +** Table. No changes are made to disk by this routine. +** +** This routine just deletes the data structure. It does not unlink +** the table data structure from the hash table. But it does destroy +** memory structures of the indices and foreign keys associated with +** the table. +** +** The db parameter is optional. It is needed if the Table object +** contains lookaside memory. (Table objects in the schema do not use +** lookaside memory, but some ephemeral Table objects do.) Or the +** db parameter can be used with db->pnBytesFreed to measure the memory +** used by the Table object. +*/ +SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ + Index *pIndex, *pNext; + TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */ + + assert( !pTable || pTable->nRef>0 ); + + /* Do not delete the table until the reference count reaches zero. */ + if( !pTable ) return; + if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return; + + /* Record the number of outstanding lookaside allocations in schema Tables + ** prior to doing any free() operations. Since schema Tables do not use + ** lookaside, this number should not change. */ + TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ? + db->lookaside.nOut : 0 ); + + /* Delete all indices associated with this table. */ + for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ + pNext = pIndex->pNext; + assert( pIndex->pSchema==pTable->pSchema ); + if( !db || db->pnBytesFreed==0 ){ + char *zName = pIndex->zName; + TESTONLY ( Index *pOld = ) sqlite3HashInsert( + &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0 + ); + assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); + assert( pOld==pIndex || pOld==0 ); + } + freeIndex(db, pIndex); + } + + /* Delete any foreign keys attached to this table. */ + sqlite3FkDelete(db, pTable); + + /* Delete the Table structure itself. + */ + sqliteDeleteColumnNames(db, pTable); + sqlite3DbFree(db, pTable->zName); + sqlite3DbFree(db, pTable->zColAff); + sqlite3SelectDelete(db, pTable->pSelect); +#ifndef SQLITE_OMIT_CHECK + sqlite3ExprListDelete(db, pTable->pCheck); +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3VtabClear(db, pTable); +#endif + sqlite3DbFree(db, pTable); + + /* Verify that no lookaside memory was used by schema tables */ + assert( nLookaside==0 || nLookaside==db->lookaside.nOut ); +} + +/* +** Unlink the given table from the hash tables and the delete the +** table structure with all its indices and foreign keys. +*/ +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ + Table *p; + Db *pDb; + + assert( db!=0 ); + assert( iDb>=0 && iDbnDb ); + assert( zTabName ); + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ + pDb = &db->aDb[iDb]; + p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, + sqlite3Strlen30(zTabName),0); + sqlite3DeleteTable(db, p); + db->flags |= SQLITE_InternChanges; +} + +/* +** Given a token, return a string that consists of the text of that +** token. Space to hold the returned string +** is obtained from sqliteMalloc() and must be freed by the calling +** function. +** +** Any quotation marks (ex: "name", 'name', [name], or `name`) that +** surround the body of the token are removed. +** +** Tokens are often just pointers into the original SQL text and so +** are not \000 terminated and are not persistent. The returned string +** is \000 terminated and is persistent. +*/ +SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ + char *zName; + if( pName ){ + zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); + sqlite3Dequote(zName); + }else{ + zName = 0; + } + return zName; +} + +/* +** Open the sqlite_master table stored in database number iDb for +** writing. The table is opened using cursor 0. +*/ +SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){ + Vdbe *v = sqlite3GetVdbe(p); + sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); + sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb); + sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */ + if( p->nTab==0 ){ + p->nTab = 1; + } +} + +/* +** Parameter zName points to a nul-terminated buffer containing the name +** of a database ("main", "temp" or the name of an attached db). This +** function returns the index of the named database in db->aDb[], or +** -1 if the named db cannot be found. +*/ +SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){ + int i = -1; /* Database number */ + if( zName ){ + Db *pDb; + int n = sqlite3Strlen30(zName); + for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ + if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && + 0==sqlite3StrICmp(pDb->zName, zName) ){ + break; + } + } + } + return i; +} + +/* +** The token *pName contains the name of a database (either "main" or +** "temp" or the name of an attached db). This routine returns the +** index of the named database in db->aDb[], or -1 if the named db +** does not exist. +*/ +SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){ + int i; /* Database number */ + char *zName; /* Name we are searching for */ + zName = sqlite3NameFromToken(db, pName); + i = sqlite3FindDbName(db, zName); + sqlite3DbFree(db, zName); + return i; +} + +/* The table or view or trigger name is passed to this routine via tokens +** pName1 and pName2. If the table name was fully qualified, for example: +** +** CREATE TABLE xxx.yyy (...); +** +** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if +** the table name is not fully qualified, i.e.: +** +** CREATE TABLE yyy(...); +** +** Then pName1 is set to "yyy" and pName2 is "". +** +** This routine sets the *ppUnqual pointer to point at the token (pName1 or +** pName2) that stores the unqualified table name. The index of the +** database "xxx" is returned. +*/ +SQLITE_PRIVATE int sqlite3TwoPartName( + Parse *pParse, /* Parsing and code generating context */ + Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ + Token *pName2, /* The "yyy" in the name "xxx.yyy" */ + Token **pUnqual /* Write the unqualified object name here */ +){ + int iDb; /* Database holding the object */ + sqlite3 *db = pParse->db; + + if( ALWAYS(pName2!=0) && pName2->n>0 ){ + if( db->init.busy ) { + sqlite3ErrorMsg(pParse, "corrupt database"); + pParse->nErr++; + return -1; + } + *pUnqual = pName2; + iDb = sqlite3FindDb(db, pName1); + if( iDb<0 ){ + sqlite3ErrorMsg(pParse, "unknown database %T", pName1); + pParse->nErr++; + return -1; + } + }else{ + assert( db->init.iDb==0 || db->init.busy ); + iDb = db->init.iDb; + *pUnqual = pName1; + } + return iDb; +} + +/* +** This routine is used to check if the UTF-8 string zName is a legal +** unqualified name for a new schema object (table, index, view or +** trigger). All names are legal except those that begin with the string +** "sqlite_" (in upper, lower or mixed case). This portion of the namespace +** is reserved for internal use. +*/ +SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){ + if( !pParse->db->init.busy && pParse->nested==0 + && (pParse->db->flags & SQLITE_WriteSchema)==0 + && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ + sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); + return SQLITE_ERROR; + } + return SQLITE_OK; +} + +/* +** Begin constructing a new table representation in memory. This is +** the first of several action routines that get called in response +** to a CREATE TABLE statement. In particular, this routine is called +** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp +** flag is true if the table should be stored in the auxiliary database +** file instead of in the main database file. This is normally the case +** when the "TEMP" or "TEMPORARY" keyword occurs in between +** CREATE and TABLE. +** +** The new table record is initialized and put in pParse->pNewTable. +** As more of the CREATE TABLE statement is parsed, additional action +** routines will be called to add more information to this record. +** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine +** is called to complete the construction of the new table record. +*/ +SQLITE_PRIVATE void sqlite3StartTable( + Parse *pParse, /* Parser context */ + Token *pName1, /* First part of the name of the table or view */ + Token *pName2, /* Second part of the name of the table or view */ + int isTemp, /* True if this is a TEMP table */ + int isView, /* True if this is a VIEW */ + int isVirtual, /* True if this is a VIRTUAL table */ + int noErr /* Do nothing if table already exists */ +){ + Table *pTable; + char *zName = 0; /* The name of the new table */ + sqlite3 *db = pParse->db; + Vdbe *v; + int iDb; /* Database number to create the table in */ + Token *pName; /* Unqualified name of the table to create */ + + /* The table or view name to create is passed to this routine via tokens + ** pName1 and pName2. If the table name was fully qualified, for example: + ** + ** CREATE TABLE xxx.yyy (...); + ** + ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if + ** the table name is not fully qualified, i.e.: + ** + ** CREATE TABLE yyy(...); + ** + ** Then pName1 is set to "yyy" and pName2 is "". + ** + ** The call below sets the pName pointer to point at the token (pName1 or + ** pName2) that stores the unqualified table name. The variable iDb is + ** set to the index of the database that the table or view is to be + ** created in. + */ + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); + if( iDb<0 ) return; + if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ + /* If creating a temp table, the name may not be qualified. Unless + ** the database name is "temp" anyway. */ + sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); + return; + } + if( !OMIT_TEMPDB && isTemp ) iDb = 1; + + pParse->sNameToken = *pName; + zName = sqlite3NameFromToken(db, pName); + if( zName==0 ) return; + if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ + goto begin_table_error; + } + if( db->init.iDb==1 ) isTemp = 1; +#ifndef SQLITE_OMIT_AUTHORIZATION + assert( (isTemp & 1)==isTemp ); + { + int code; + char *zDb = db->aDb[iDb].zName; + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ + goto begin_table_error; + } + if( isView ){ + if( !OMIT_TEMPDB && isTemp ){ + code = SQLITE_CREATE_TEMP_VIEW; + }else{ + code = SQLITE_CREATE_VIEW; + } + }else{ + if( !OMIT_TEMPDB && isTemp ){ + code = SQLITE_CREATE_TEMP_TABLE; + }else{ + code = SQLITE_CREATE_TABLE; + } + } + if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ + goto begin_table_error; + } + } +#endif + + /* Make sure the new table name does not collide with an existing + ** index or table name in the same database. Issue an error message if + ** it does. The exception is if the statement being parsed was passed + ** to an sqlite3_declare_vtab() call. In that case only the column names + ** and types will be used, so there is no need to test for namespace + ** collisions. + */ + if( !IN_DECLARE_VTAB ){ + char *zDb = db->aDb[iDb].zName; + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + goto begin_table_error; + } + pTable = sqlite3FindTable(db, zName, zDb); + if( pTable ){ + if( !noErr ){ + sqlite3ErrorMsg(pParse, "table %T already exists", pName); + }else{ + assert( !db->init.busy ); + sqlite3CodeVerifySchema(pParse, iDb); + } + goto begin_table_error; + } + if( sqlite3FindIndex(db, zName, zDb)!=0 ){ + sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); + goto begin_table_error; + } + } + + pTable = sqlite3DbMallocZero(db, sizeof(Table)); + if( pTable==0 ){ + db->mallocFailed = 1; + pParse->rc = SQLITE_NOMEM; + pParse->nErr++; + goto begin_table_error; + } + pTable->zName = zName; + pTable->iPKey = -1; + pTable->pSchema = db->aDb[iDb].pSchema; + pTable->nRef = 1; + pTable->nRowEst = 1048576; + assert( pParse->pNewTable==0 ); + pParse->pNewTable = pTable; + + /* If this is the magic sqlite_sequence table used by autoincrement, + ** then record a pointer to this table in the main database structure + ** so that INSERT can find the table easily. + */ +#ifndef SQLITE_OMIT_AUTOINCREMENT + if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pTable->pSchema->pSeqTab = pTable; + } +#endif + + /* Begin generating the code that will insert the table record into + ** the SQLITE_MASTER table. Note in particular that we must go ahead + ** and allocate the record number for the table entry now. Before any + ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause + ** indices to be created and the table record must come before the + ** indices. Hence, the record number for the table must be allocated + ** now. + */ + if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ + int j1; + int fileFormat; + int reg1, reg2, reg3; + sqlite3BeginWriteOperation(pParse, 0, iDb); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( isVirtual ){ + sqlite3VdbeAddOp0(v, OP_VBegin); + } +#endif + + /* If the file format and encoding in the database have not been set, + ** set them now. + */ + reg1 = pParse->regRowid = ++pParse->nMem; + reg2 = pParse->regRoot = ++pParse->nMem; + reg3 = ++pParse->nMem; + sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); + sqlite3VdbeUsesBtree(v, iDb); + j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); + fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? + 1 : SQLITE_MAX_FILE_FORMAT; + sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3); + sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3); + sqlite3VdbeJumpHere(v, j1); + + /* This just creates a place-holder record in the sqlite_master table. + ** The record created does not contain anything yet. It will be replaced + ** by the real entry in code generated at sqlite3EndTable(). + ** + ** The rowid for the new entry is left in register pParse->regRowid. + ** The root page number of the new table is left in reg pParse->regRoot. + ** The rowid and root page number values are needed by the code that + ** sqlite3EndTable will generate. + */ +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) + if( isView || isVirtual ){ + sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); + }else +#endif + { + sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); + } + sqlite3OpenMasterTable(pParse, iDb); + sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); + sqlite3VdbeAddOp2(v, OP_Null, 0, reg3); + sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3VdbeAddOp0(v, OP_Close); + } + + /* Normal (non-error) return. */ + return; + + /* If an error occurs, we jump here */ +begin_table_error: + sqlite3DbFree(db, zName); + return; +} + +/* +** This macro is used to compare two strings in a case-insensitive manner. +** It is slightly faster than calling sqlite3StrICmp() directly, but +** produces larger code. +** +** WARNING: This macro is not compatible with the strcmp() family. It +** returns true if the two strings are equal, otherwise false. +*/ +#define STRICMP(x, y) (\ +sqlite3UpperToLower[*(unsigned char *)(x)]== \ +sqlite3UpperToLower[*(unsigned char *)(y)] \ +&& sqlite3StrICmp((x)+1,(y)+1)==0 ) + +/* +** Add a new column to the table currently being constructed. +** +** The parser calls this routine once for each column declaration +** in a CREATE TABLE statement. sqlite3StartTable() gets called +** first to get things going. Then this routine is called for each +** column. +*/ +SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){ + Table *p; + int i; + char *z; + Column *pCol; + sqlite3 *db = pParse->db; + if( (p = pParse->pNewTable)==0 ) return; +#if SQLITE_MAX_COLUMN + if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); + return; + } +#endif + z = sqlite3NameFromToken(db, pName); + if( z==0 ) return; + for(i=0; inCol; i++){ + if( STRICMP(z, p->aCol[i].zName) ){ + sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); + sqlite3DbFree(db, z); + return; + } + } + if( (p->nCol & 0x7)==0 ){ + Column *aNew; + aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); + if( aNew==0 ){ + sqlite3DbFree(db, z); + return; + } + p->aCol = aNew; + } + pCol = &p->aCol[p->nCol]; + memset(pCol, 0, sizeof(p->aCol[0])); + pCol->zName = z; + + /* If there is no type specified, columns have the default affinity + ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will + ** be called next to set pCol->affinity correctly. + */ + pCol->affinity = SQLITE_AFF_NONE; + pCol->szEst = 1; + p->nCol++; +} + +/* +** This routine is called by the parser while in the middle of +** parsing a CREATE TABLE statement. A "NOT NULL" constraint has +** been seen on a column. This routine sets the notNull flag on +** the column currently under construction. +*/ +SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){ + Table *p; + p = pParse->pNewTable; + if( p==0 || NEVER(p->nCol<1) ) return; + p->aCol[p->nCol-1].notNull = (u8)onError; +} + +/* +** Scan the column type name zType (length nType) and return the +** associated affinity type. +** +** This routine does a case-independent search of zType for the +** substrings in the following table. If one of the substrings is +** found, the corresponding affinity is returned. If zType contains +** more than one of the substrings, entries toward the top of +** the table take priority. For example, if zType is 'BLOBINT', +** SQLITE_AFF_INTEGER is returned. +** +** Substring | Affinity +** -------------------------------- +** 'INT' | SQLITE_AFF_INTEGER +** 'CHAR' | SQLITE_AFF_TEXT +** 'CLOB' | SQLITE_AFF_TEXT +** 'TEXT' | SQLITE_AFF_TEXT +** 'BLOB' | SQLITE_AFF_NONE +** 'REAL' | SQLITE_AFF_REAL +** 'FLOA' | SQLITE_AFF_REAL +** 'DOUB' | SQLITE_AFF_REAL +** +** If none of the substrings in the above table are found, +** SQLITE_AFF_NUMERIC is returned. +*/ +SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){ + u32 h = 0; + char aff = SQLITE_AFF_NUMERIC; + const char *zChar = 0; + + if( zIn==0 ) return aff; + while( zIn[0] ){ + h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; + zIn++; + if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ + aff = SQLITE_AFF_TEXT; + zChar = zIn; + }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ + aff = SQLITE_AFF_TEXT; + }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ + aff = SQLITE_AFF_TEXT; + }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ + && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ + aff = SQLITE_AFF_NONE; + if( zIn[0]=='(' ) zChar = zIn; +#ifndef SQLITE_OMIT_FLOATING_POINT + }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ + && aff==SQLITE_AFF_NUMERIC ){ + aff = SQLITE_AFF_REAL; + }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ + && aff==SQLITE_AFF_NUMERIC ){ + aff = SQLITE_AFF_REAL; + }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ + && aff==SQLITE_AFF_NUMERIC ){ + aff = SQLITE_AFF_REAL; +#endif + }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ + aff = SQLITE_AFF_INTEGER; + break; + } + } + + /* If pszEst is not NULL, store an estimate of the field size. The + ** estimate is scaled so that the size of an integer is 1. */ + if( pszEst ){ + *pszEst = 1; /* default size is approx 4 bytes */ + if( aff<=SQLITE_AFF_NONE ){ + if( zChar ){ + while( zChar[0] ){ + if( sqlite3Isdigit(zChar[0]) ){ + int v = 0; + sqlite3GetInt32(zChar, &v); + v = v/4 + 1; + if( v>255 ) v = 255; + *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ + break; + } + zChar++; + } + }else{ + *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ + } + } + } + return aff; +} + +/* +** This routine is called by the parser while in the middle of +** parsing a CREATE TABLE statement. The pFirst token is the first +** token in the sequence of tokens that describe the type of the +** column currently under construction. pLast is the last token +** in the sequence. Use this information to construct a string +** that contains the typename of the column and store that string +** in zType. +*/ +SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){ + Table *p; + Column *pCol; + + p = pParse->pNewTable; + if( p==0 || NEVER(p->nCol<1) ) return; + pCol = &p->aCol[p->nCol-1]; + assert( pCol->zType==0 ); + pCol->zType = sqlite3NameFromToken(pParse->db, pType); + pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst); +} + +/* +** The expression is the default value for the most recently added column +** of the table currently under construction. +** +** Default value expressions must be constant. Raise an exception if this +** is not the case. +** +** This routine is called by the parser while in the middle of +** parsing a CREATE TABLE statement. +*/ +SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ + Table *p; + Column *pCol; + sqlite3 *db = pParse->db; + p = pParse->pNewTable; + if( p!=0 ){ + pCol = &(p->aCol[p->nCol-1]); + if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){ + sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", + pCol->zName); + }else{ + /* A copy of pExpr is used instead of the original, as pExpr contains + ** tokens that point to volatile memory. The 'span' of the expression + ** is required by pragma table_info. + */ + sqlite3ExprDelete(db, pCol->pDflt); + pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE); + sqlite3DbFree(db, pCol->zDflt); + pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart, + (int)(pSpan->zEnd - pSpan->zStart)); + } + } + sqlite3ExprDelete(db, pSpan->pExpr); +} + +/* +** Designate the PRIMARY KEY for the table. pList is a list of names +** of columns that form the primary key. If pList is NULL, then the +** most recently added column of the table is the primary key. +** +** A table can have at most one primary key. If the table already has +** a primary key (and this is the second primary key) then create an +** error. +** +** If the PRIMARY KEY is on a single column whose datatype is INTEGER, +** then we will try to use that column as the rowid. Set the Table.iPKey +** field of the table under construction to be the index of the +** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is +** no INTEGER PRIMARY KEY. +** +** If the key is not an INTEGER PRIMARY KEY, then create a unique +** index for the key. No index is created for INTEGER PRIMARY KEYs. +*/ +SQLITE_PRIVATE void sqlite3AddPrimaryKey( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* List of field names to be indexed */ + int onError, /* What to do with a uniqueness conflict */ + int autoInc, /* True if the AUTOINCREMENT keyword is present */ + int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ +){ + Table *pTab = pParse->pNewTable; + char *zType = 0; + int iCol = -1, i; + if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; + if( pTab->tabFlags & TF_HasPrimaryKey ){ + sqlite3ErrorMsg(pParse, + "table \"%s\" has more than one primary key", pTab->zName); + goto primary_key_exit; + } + pTab->tabFlags |= TF_HasPrimaryKey; + if( pList==0 ){ + iCol = pTab->nCol - 1; + pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; + }else{ + for(i=0; inExpr; i++){ + for(iCol=0; iColnCol; iCol++){ + if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ + break; + } + } + if( iColnCol ){ + pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; + } + } + if( pList->nExpr>1 ) iCol = -1; + } + if( iCol>=0 && iColnCol ){ + zType = pTab->aCol[iCol].zType; + } + if( zType && sqlite3StrICmp(zType, "INTEGER")==0 + && sortOrder==SQLITE_SO_ASC ){ + pTab->iPKey = iCol; + pTab->keyConf = (u8)onError; + assert( autoInc==0 || autoInc==1 ); + pTab->tabFlags |= autoInc*TF_Autoincrement; + }else if( autoInc ){ +#ifndef SQLITE_OMIT_AUTOINCREMENT + sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " + "INTEGER PRIMARY KEY"); +#endif + }else{ + Index *p; + p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, + 0, sortOrder, 0); + if( p ){ + p->autoIndex = 2; + } + pList = 0; + } + +primary_key_exit: + sqlite3ExprListDelete(pParse->db, pList); + return; +} + +/* +** Add a new CHECK constraint to the table currently under construction. +*/ +SQLITE_PRIVATE void sqlite3AddCheckConstraint( + Parse *pParse, /* Parsing context */ + Expr *pCheckExpr /* The check expression */ +){ +#ifndef SQLITE_OMIT_CHECK + Table *pTab = pParse->pNewTable; + if( pTab && !IN_DECLARE_VTAB ){ + pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); + if( pParse->constraintName.n ){ + sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); + } + }else +#endif + { + sqlite3ExprDelete(pParse->db, pCheckExpr); + } +} + +/* +** Set the collation function of the most recently parsed table column +** to the CollSeq given. +*/ +SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){ + Table *p; + int i; + char *zColl; /* Dequoted name of collation sequence */ + sqlite3 *db; + + if( (p = pParse->pNewTable)==0 ) return; + i = p->nCol-1; + db = pParse->db; + zColl = sqlite3NameFromToken(db, pToken); + if( !zColl ) return; + + if( sqlite3LocateCollSeq(pParse, zColl) ){ + Index *pIdx; + sqlite3DbFree(db, p->aCol[i].zColl); + p->aCol[i].zColl = zColl; + + /* If the column is declared as " PRIMARY KEY COLLATE ", + ** then an index may have been created on this column before the + ** collation type was added. Correct this if it is the case. + */ + for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ + assert( pIdx->nColumn==1 ); + if( pIdx->aiColumn[0]==i ){ + pIdx->azColl[0] = p->aCol[i].zColl; + } + } + }else{ + sqlite3DbFree(db, zColl); + } +} + +/* +** This function returns the collation sequence for database native text +** encoding identified by the string zName, length nName. +** +** If the requested collation sequence is not available, or not available +** in the database native encoding, the collation factory is invoked to +** request it. If the collation factory does not supply such a sequence, +** and the sequence is available in another text encoding, then that is +** returned instead. +** +** If no versions of the requested collations sequence are available, or +** another error occurs, NULL is returned and an error message written into +** pParse. +** +** This routine is a wrapper around sqlite3FindCollSeq(). This routine +** invokes the collation factory if the named collation cannot be found +** and generates an error message. +** +** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() +*/ +SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ + sqlite3 *db = pParse->db; + u8 enc = ENC(db); + u8 initbusy = db->init.busy; + CollSeq *pColl; + + pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); + if( !initbusy && (!pColl || !pColl->xCmp) ){ + pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); + } + + return pColl; +} + + +/* +** Generate code that will increment the schema cookie. +** +** The schema cookie is used to determine when the schema for the +** database changes. After each schema change, the cookie value +** changes. When a process first reads the schema it records the +** cookie. Thereafter, whenever it goes to access the database, +** it checks the cookie to make sure the schema has not changed +** since it was last read. +** +** This plan is not completely bullet-proof. It is possible for +** the schema to change multiple times and for the cookie to be +** set back to prior value. But schema changes are infrequent +** and the probability of hitting the same cookie value is only +** 1 chance in 2^32. So we're safe enough. +*/ +SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){ + int r1 = sqlite3GetTempReg(pParse); + sqlite3 *db = pParse->db; + Vdbe *v = pParse->pVdbe; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1); + sqlite3ReleaseTempReg(pParse, r1); +} + +/* +** Measure the number of characters needed to output the given +** identifier. The number returned includes any quotes used +** but does not include the null terminator. +** +** The estimate is conservative. It might be larger that what is +** really needed. +*/ +static int identLength(const char *z){ + int n; + for(n=0; *z; n++, z++){ + if( *z=='"' ){ n++; } + } + return n + 2; +} + +/* +** The first parameter is a pointer to an output buffer. The second +** parameter is a pointer to an integer that contains the offset at +** which to write into the output buffer. This function copies the +** nul-terminated string pointed to by the third parameter, zSignedIdent, +** to the specified offset in the buffer and updates *pIdx to refer +** to the first byte after the last byte written before returning. +** +** If the string zSignedIdent consists entirely of alpha-numeric +** characters, does not begin with a digit and is not an SQL keyword, +** then it is copied to the output buffer exactly as it is. Otherwise, +** it is quoted using double-quotes. +*/ +static void identPut(char *z, int *pIdx, char *zSignedIdent){ + unsigned char *zIdent = (unsigned char*)zSignedIdent; + int i, j, needQuote; + i = *pIdx; + + for(j=0; zIdent[j]; j++){ + if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; + } + needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID; + if( !needQuote ){ + needQuote = zIdent[j]; + } + + if( needQuote ) z[i++] = '"'; + for(j=0; zIdent[j]; j++){ + z[i++] = zIdent[j]; + if( zIdent[j]=='"' ) z[i++] = '"'; + } + if( needQuote ) z[i++] = '"'; + z[i] = 0; + *pIdx = i; +} + +/* +** Generate a CREATE TABLE statement appropriate for the given +** table. Memory to hold the text of the statement is obtained +** from sqliteMalloc() and must be freed by the calling function. +*/ +static char *createTableStmt(sqlite3 *db, Table *p){ + int i, k, n; + char *zStmt; + char *zSep, *zSep2, *zEnd; + Column *pCol; + n = 0; + for(pCol = p->aCol, i=0; inCol; i++, pCol++){ + n += identLength(pCol->zName) + 5; + } + n += identLength(p->zName); + if( n<50 ){ + zSep = ""; + zSep2 = ","; + zEnd = ")"; + }else{ + zSep = "\n "; + zSep2 = ",\n "; + zEnd = "\n)"; + } + n += 35 + 6*p->nCol; + zStmt = sqlite3DbMallocRaw(0, n); + if( zStmt==0 ){ + db->mallocFailed = 1; + return 0; + } + sqlite3_snprintf(n, zStmt, "CREATE TABLE "); + k = sqlite3Strlen30(zStmt); + identPut(zStmt, &k, p->zName); + zStmt[k++] = '('; + for(pCol=p->aCol, i=0; inCol; i++, pCol++){ + static const char * const azType[] = { + /* SQLITE_AFF_TEXT */ " TEXT", + /* SQLITE_AFF_NONE */ "", + /* SQLITE_AFF_NUMERIC */ " NUM", + /* SQLITE_AFF_INTEGER */ " INT", + /* SQLITE_AFF_REAL */ " REAL" + }; + int len; + const char *zType; + + sqlite3_snprintf(n-k, &zStmt[k], zSep); + k += sqlite3Strlen30(&zStmt[k]); + zSep = zSep2; + identPut(zStmt, &k, pCol->zName); + assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 ); + assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) ); + testcase( pCol->affinity==SQLITE_AFF_TEXT ); + testcase( pCol->affinity==SQLITE_AFF_NONE ); + testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); + testcase( pCol->affinity==SQLITE_AFF_INTEGER ); + testcase( pCol->affinity==SQLITE_AFF_REAL ); + + zType = azType[pCol->affinity - SQLITE_AFF_TEXT]; + len = sqlite3Strlen30(zType); + assert( pCol->affinity==SQLITE_AFF_NONE + || pCol->affinity==sqlite3AffinityType(zType, 0) ); + memcpy(&zStmt[k], zType, len); + k += len; + assert( k<=n ); + } + sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); + return zStmt; +} + +/* +** Estimate the total row width for a table. +*/ +static void estimateTableWidth(Table *pTab){ + unsigned wTable = 0; + const Column *pTabCol; + int i; + for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ + wTable += pTabCol->szEst; + } + if( pTab->iPKey<0 ) wTable++; + pTab->szTabRow = sqlite3LogEst(wTable*4); +} + +/* +** Estimate the average size of a row for an index. +*/ +static void estimateIndexWidth(Index *pIdx){ + unsigned wIndex = 1; + int i; + const Column *aCol = pIdx->pTable->aCol; + for(i=0; inColumn; i++){ + assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]pTable->nCol ); + wIndex += aCol[pIdx->aiColumn[i]].szEst; + } + pIdx->szIdxRow = sqlite3LogEst(wIndex*4); +} + +/* +** This routine is called to report the final ")" that terminates +** a CREATE TABLE statement. +** +** The table structure that other action routines have been building +** is added to the internal hash tables, assuming no errors have +** occurred. +** +** An entry for the table is made in the master table on disk, unless +** this is a temporary table or db->init.busy==1. When db->init.busy==1 +** it means we are reading the sqlite_master table because we just +** connected to the database or because the sqlite_master table has +** recently changed, so the entry for this table already exists in +** the sqlite_master table. We do not want to create it again. +** +** If the pSelect argument is not NULL, it means that this routine +** was called to create a table generated from a +** "CREATE TABLE ... AS SELECT ..." statement. The column names of +** the new table will match the result set of the SELECT. +*/ +SQLITE_PRIVATE void sqlite3EndTable( + Parse *pParse, /* Parse context */ + Token *pCons, /* The ',' token after the last column defn. */ + Token *pEnd, /* The final ')' token in the CREATE TABLE */ + Select *pSelect /* Select from a "CREATE ... AS SELECT" */ +){ + Table *p; /* The new table */ + sqlite3 *db = pParse->db; /* The database connection */ + int iDb; /* Database in which the table lives */ + Index *pIdx; /* An implied index of the table */ + + if( (pEnd==0 && pSelect==0) || db->mallocFailed ){ + return; + } + p = pParse->pNewTable; + if( p==0 ) return; + + assert( !db->init.busy || !pSelect ); + + iDb = sqlite3SchemaToIndex(db, p->pSchema); + +#ifndef SQLITE_OMIT_CHECK + /* Resolve names in all CHECK constraint expressions. + */ + if( p->pCheck ){ + sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); + } +#endif /* !defined(SQLITE_OMIT_CHECK) */ + + /* Estimate the average row size for the table and for all implied indices */ + estimateTableWidth(p); + for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ + estimateIndexWidth(pIdx); + } + + /* If the db->init.busy is 1 it means we are reading the SQL off the + ** "sqlite_master" or "sqlite_temp_master" table on the disk. + ** So do not write to the disk again. Extract the root page number + ** for the table from the db->init.newTnum field. (The page number + ** should have been put there by the sqliteOpenCb routine.) + */ + if( db->init.busy ){ + p->tnum = db->init.newTnum; + } + + /* If not initializing, then create a record for the new table + ** in the SQLITE_MASTER table of the database. + ** + ** If this is a TEMPORARY table, write the entry into the auxiliary + ** file instead of into the main database file. + */ + if( !db->init.busy ){ + int n; + Vdbe *v; + char *zType; /* "view" or "table" */ + char *zType2; /* "VIEW" or "TABLE" */ + char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ + + v = sqlite3GetVdbe(pParse); + if( NEVER(v==0) ) return; + + sqlite3VdbeAddOp1(v, OP_Close, 0); + + /* + ** Initialize zType for the new view or table. + */ + if( p->pSelect==0 ){ + /* A regular table */ + zType = "table"; + zType2 = "TABLE"; +#ifndef SQLITE_OMIT_VIEW + }else{ + /* A view */ + zType = "view"; + zType2 = "VIEW"; +#endif + } + + /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT + ** statement to populate the new table. The root-page number for the + ** new table is in register pParse->regRoot. + ** + ** Once the SELECT has been coded by sqlite3Select(), it is in a + ** suitable state to query for the column names and types to be used + ** by the new table. + ** + ** A shared-cache write-lock is not required to write to the new table, + ** as a schema-lock must have already been obtained to create it. Since + ** a schema-lock excludes all other database users, the write-lock would + ** be redundant. + */ + if( pSelect ){ + SelectDest dest; + Table *pSelTab; + + assert(pParse->nTab==1); + sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); + sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); + pParse->nTab = 2; + sqlite3SelectDestInit(&dest, SRT_Table, 1); + sqlite3Select(pParse, pSelect, &dest); + sqlite3VdbeAddOp1(v, OP_Close, 1); + if( pParse->nErr==0 ){ + pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); + if( pSelTab==0 ) return; + assert( p->aCol==0 ); + p->nCol = pSelTab->nCol; + p->aCol = pSelTab->aCol; + pSelTab->nCol = 0; + pSelTab->aCol = 0; + sqlite3DeleteTable(db, pSelTab); + } + } + + /* Compute the complete text of the CREATE statement */ + if( pSelect ){ + zStmt = createTableStmt(db, p); + }else{ + n = (int)(pEnd->z - pParse->sNameToken.z) + 1; + zStmt = sqlite3MPrintf(db, + "CREATE %s %.*s", zType2, n, pParse->sNameToken.z + ); + } + + /* A slot for the record has already been allocated in the + ** SQLITE_MASTER table. We just need to update that slot with all + ** the information we've collected. + */ + sqlite3NestedParse(pParse, + "UPDATE %Q.%s " + "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " + "WHERE rowid=#%d", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), + zType, + p->zName, + p->zName, + pParse->regRoot, + zStmt, + pParse->regRowid + ); + sqlite3DbFree(db, zStmt); + sqlite3ChangeCookie(pParse, iDb); + +#ifndef SQLITE_OMIT_AUTOINCREMENT + /* Check to see if we need to create an sqlite_sequence table for + ** keeping track of autoincrement keys. + */ + if( p->tabFlags & TF_Autoincrement ){ + Db *pDb = &db->aDb[iDb]; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( pDb->pSchema->pSeqTab==0 ){ + sqlite3NestedParse(pParse, + "CREATE TABLE %Q.sqlite_sequence(name,seq)", + pDb->zName + ); + } + } +#endif + + /* Reparse everything to update our internal data structures */ + sqlite3VdbeAddParseSchemaOp(v, iDb, + sqlite3MPrintf(db, "tbl_name='%q'", p->zName)); + } + + + /* Add the table to the in-memory representation of the database. + */ + if( db->init.busy ){ + Table *pOld; + Schema *pSchema = p->pSchema; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, + sqlite3Strlen30(p->zName),p); + if( pOld ){ + assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ + db->mallocFailed = 1; + return; + } + pParse->pNewTable = 0; + db->flags |= SQLITE_InternChanges; + +#ifndef SQLITE_OMIT_ALTERTABLE + if( !p->pSelect ){ + const char *zName = (const char *)pParse->sNameToken.z; + int nName; + assert( !pSelect && pCons && pEnd ); + if( pCons->z==0 ){ + pCons = pEnd; + } + nName = (int)((const char *)pCons->z - zName); + p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); + } +#endif + } +} + +#ifndef SQLITE_OMIT_VIEW +/* +** The parser calls this routine in order to create a new VIEW +*/ +SQLITE_PRIVATE void sqlite3CreateView( + Parse *pParse, /* The parsing context */ + Token *pBegin, /* The CREATE token that begins the statement */ + Token *pName1, /* The token that holds the name of the view */ + Token *pName2, /* The token that holds the name of the view */ + Select *pSelect, /* A SELECT statement that will become the new view */ + int isTemp, /* TRUE for a TEMPORARY view */ + int noErr /* Suppress error messages if VIEW already exists */ +){ + Table *p; + int n; + const char *z; + Token sEnd; + DbFixer sFix; + Token *pName = 0; + int iDb; + sqlite3 *db = pParse->db; + + if( pParse->nVar>0 ){ + sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); + sqlite3SelectDelete(db, pSelect); + return; + } + sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); + p = pParse->pNewTable; + if( p==0 || pParse->nErr ){ + sqlite3SelectDelete(db, pSelect); + return; + } + sqlite3TwoPartName(pParse, pName1, pName2, &pName); + iDb = sqlite3SchemaToIndex(db, p->pSchema); + sqlite3FixInit(&sFix, pParse, iDb, "view", pName); + if( sqlite3FixSelect(&sFix, pSelect) ){ + sqlite3SelectDelete(db, pSelect); + return; + } + + /* Make a copy of the entire SELECT statement that defines the view. + ** This will force all the Expr.token.z values to be dynamically + ** allocated rather than point to the input string - which means that + ** they will persist after the current sqlite3_exec() call returns. + */ + p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + sqlite3SelectDelete(db, pSelect); + if( db->mallocFailed ){ + return; + } + if( !db->init.busy ){ + sqlite3ViewGetColumnNames(pParse, p); + } + + /* Locate the end of the CREATE VIEW statement. Make sEnd point to + ** the end. + */ + sEnd = pParse->sLastToken; + if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){ + sEnd.z += sEnd.n; + } + sEnd.n = 0; + n = (int)(sEnd.z - pBegin->z); + z = pBegin->z; + while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; } + sEnd.z = &z[n-1]; + sEnd.n = 1; + + /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ + sqlite3EndTable(pParse, 0, &sEnd, 0); + return; +} +#endif /* SQLITE_OMIT_VIEW */ + +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) +/* +** The Table structure pTable is really a VIEW. Fill in the names of +** the columns of the view in the pTable structure. Return the number +** of errors. If an error is seen leave an error message in pParse->zErrMsg. +*/ +SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ + Table *pSelTab; /* A fake table from which we get the result set */ + Select *pSel; /* Copy of the SELECT that implements the view */ + int nErr = 0; /* Number of errors encountered */ + int n; /* Temporarily holds the number of cursors assigned */ + sqlite3 *db = pParse->db; /* Database connection for malloc errors */ + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); + + assert( pTable ); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( sqlite3VtabCallConnect(pParse, pTable) ){ + return SQLITE_ERROR; + } + if( IsVirtual(pTable) ) return 0; +#endif + +#ifndef SQLITE_OMIT_VIEW + /* A positive nCol means the columns names for this view are + ** already known. + */ + if( pTable->nCol>0 ) return 0; + + /* A negative nCol is a special marker meaning that we are currently + ** trying to compute the column names. If we enter this routine with + ** a negative nCol, it means two or more views form a loop, like this: + ** + ** CREATE VIEW one AS SELECT * FROM two; + ** CREATE VIEW two AS SELECT * FROM one; + ** + ** Actually, the error above is now caught prior to reaching this point. + ** But the following test is still important as it does come up + ** in the following: + ** + ** CREATE TABLE main.ex1(a); + ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; + ** SELECT * FROM temp.ex1; + */ + if( pTable->nCol<0 ){ + sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); + return 1; + } + assert( pTable->nCol>=0 ); + + /* If we get this far, it means we need to compute the table names. + ** Note that the call to sqlite3ResultSetOfSelect() will expand any + ** "*" elements in the results set of the view and will assign cursors + ** to the elements of the FROM clause. But we do not want these changes + ** to be permanent. So the computation is done on a copy of the SELECT + ** statement that defines the view. + */ + assert( pTable->pSelect ); + pSel = sqlite3SelectDup(db, pTable->pSelect, 0); + if( pSel ){ + u8 enableLookaside = db->lookaside.bEnabled; + n = pParse->nTab; + sqlite3SrcListAssignCursors(pParse, pSel->pSrc); + pTable->nCol = -1; + db->lookaside.bEnabled = 0; +#ifndef SQLITE_OMIT_AUTHORIZATION + xAuth = db->xAuth; + db->xAuth = 0; + pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); + db->xAuth = xAuth; +#else + pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); +#endif + db->lookaside.bEnabled = enableLookaside; + pParse->nTab = n; + if( pSelTab ){ + assert( pTable->aCol==0 ); + pTable->nCol = pSelTab->nCol; + pTable->aCol = pSelTab->aCol; + pSelTab->nCol = 0; + pSelTab->aCol = 0; + sqlite3DeleteTable(db, pSelTab); + assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); + pTable->pSchema->flags |= DB_UnresetViews; + }else{ + pTable->nCol = 0; + nErr++; + } + sqlite3SelectDelete(db, pSel); + } else { + nErr++; + } +#endif /* SQLITE_OMIT_VIEW */ + return nErr; +} +#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ + +#ifndef SQLITE_OMIT_VIEW +/* +** Clear the column names from every VIEW in database idx. +*/ +static void sqliteViewResetAll(sqlite3 *db, int idx){ + HashElem *i; + assert( sqlite3SchemaMutexHeld(db, idx, 0) ); + if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; + for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ + Table *pTab = sqliteHashData(i); + if( pTab->pSelect ){ + sqliteDeleteColumnNames(db, pTab); + pTab->aCol = 0; + pTab->nCol = 0; + } + } + DbClearProperty(db, idx, DB_UnresetViews); +} +#else +# define sqliteViewResetAll(A,B) +#endif /* SQLITE_OMIT_VIEW */ + +/* +** This function is called by the VDBE to adjust the internal schema +** used by SQLite when the btree layer moves a table root page. The +** root-page of a table or index in database iDb has changed from iFrom +** to iTo. +** +** Ticket #1728: The symbol table might still contain information +** on tables and/or indices that are the process of being deleted. +** If you are unlucky, one of those deleted indices or tables might +** have the same rootpage number as the real table or index that is +** being moved. So we cannot stop searching after the first match +** because the first match might be for one of the deleted indices +** or tables and not the table/index that is actually being moved. +** We must continue looping until all tables and indices with +** rootpage==iFrom have been converted to have a rootpage of iTo +** in order to be certain that we got the right one. +*/ +#ifndef SQLITE_OMIT_AUTOVACUUM +SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){ + HashElem *pElem; + Hash *pHash; + Db *pDb; + + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pDb = &db->aDb[iDb]; + pHash = &pDb->pSchema->tblHash; + for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ + Table *pTab = sqliteHashData(pElem); + if( pTab->tnum==iFrom ){ + pTab->tnum = iTo; + } + } + pHash = &pDb->pSchema->idxHash; + for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ + Index *pIdx = sqliteHashData(pElem); + if( pIdx->tnum==iFrom ){ + pIdx->tnum = iTo; + } + } +} +#endif + +/* +** Write code to erase the table with root-page iTable from database iDb. +** Also write code to modify the sqlite_master table and internal schema +** if a root-page of another table is moved by the btree-layer whilst +** erasing iTable (this can happen with an auto-vacuum database). +*/ +static void destroyRootPage(Parse *pParse, int iTable, int iDb){ + Vdbe *v = sqlite3GetVdbe(pParse); + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); + sqlite3MayAbort(pParse); +#ifndef SQLITE_OMIT_AUTOVACUUM + /* OP_Destroy stores an in integer r1. If this integer + ** is non-zero, then it is the root page number of a table moved to + ** location iTable. The following code modifies the sqlite_master table to + ** reflect this. + ** + ** The "#NNN" in the SQL is a special constant that means whatever value + ** is in register NNN. See grammar rules associated with the TK_REGISTER + ** token for additional information. + */ + sqlite3NestedParse(pParse, + "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", + pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); +#endif + sqlite3ReleaseTempReg(pParse, r1); +} + +/* +** Write VDBE code to erase table pTab and all associated indices on disk. +** Code to update the sqlite_master tables and internal schema definitions +** in case a root-page belonging to another table is moved by the btree layer +** is also added (this can happen with an auto-vacuum database). +*/ +static void destroyTable(Parse *pParse, Table *pTab){ +#ifdef SQLITE_OMIT_AUTOVACUUM + Index *pIdx; + int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + destroyRootPage(pParse, pTab->tnum, iDb); + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + destroyRootPage(pParse, pIdx->tnum, iDb); + } +#else + /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM + ** is not defined), then it is important to call OP_Destroy on the + ** table and index root-pages in order, starting with the numerically + ** largest root-page number. This guarantees that none of the root-pages + ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the + ** following were coded: + ** + ** OP_Destroy 4 0 + ** ... + ** OP_Destroy 5 0 + ** + ** and root page 5 happened to be the largest root-page number in the + ** database, then root page 5 would be moved to page 4 by the + ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit + ** a free-list page. + */ + int iTab = pTab->tnum; + int iDestroyed = 0; + + while( 1 ){ + Index *pIdx; + int iLargest = 0; + + if( iDestroyed==0 || iTabpIndex; pIdx; pIdx=pIdx->pNext){ + int iIdx = pIdx->tnum; + assert( pIdx->pSchema==pTab->pSchema ); + if( (iDestroyed==0 || (iIdxiLargest ){ + iLargest = iIdx; + } + } + if( iLargest==0 ){ + return; + }else{ + int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + assert( iDb>=0 && iDbdb->nDb ); + destroyRootPage(pParse, iLargest, iDb); + iDestroyed = iLargest; + } + } +#endif +} + +/* +** Remove entries from the sqlite_statN tables (for N in (1,2,3)) +** after a DROP INDEX or DROP TABLE command. +*/ +static void sqlite3ClearStatTables( + Parse *pParse, /* The parsing context */ + int iDb, /* The database number */ + const char *zType, /* "idx" or "tbl" */ + const char *zName /* Name of index or table */ +){ + int i; + const char *zDbName = pParse->db->aDb[iDb].zName; + for(i=1; i<=4; i++){ + char zTab[24]; + sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); + if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ + sqlite3NestedParse(pParse, + "DELETE FROM %Q.%s WHERE %s=%Q", + zDbName, zTab, zType, zName + ); + } + } +} + +/* +** Generate code to drop a table. +*/ +SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ + Vdbe *v; + sqlite3 *db = pParse->db; + Trigger *pTrigger; + Db *pDb = &db->aDb[iDb]; + + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); + sqlite3BeginWriteOperation(pParse, 1, iDb); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + sqlite3VdbeAddOp0(v, OP_VBegin); + } +#endif + + /* Drop all triggers associated with the table being dropped. Code + ** is generated to remove entries from sqlite_master and/or + ** sqlite_temp_master if required. + */ + pTrigger = sqlite3TriggerList(pParse, pTab); + while( pTrigger ){ + assert( pTrigger->pSchema==pTab->pSchema || + pTrigger->pSchema==db->aDb[1].pSchema ); + sqlite3DropTriggerPtr(pParse, pTrigger); + pTrigger = pTrigger->pNext; + } + +#ifndef SQLITE_OMIT_AUTOINCREMENT + /* Remove any entries of the sqlite_sequence table associated with + ** the table being dropped. This is done before the table is dropped + ** at the btree level, in case the sqlite_sequence table needs to + ** move as a result of the drop (can happen in auto-vacuum mode). + */ + if( pTab->tabFlags & TF_Autoincrement ){ + sqlite3NestedParse(pParse, + "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", + pDb->zName, pTab->zName + ); + } +#endif + + /* Drop all SQLITE_MASTER table and index entries that refer to the + ** table. The program name loops through the master table and deletes + ** every row that refers to a table of the same name as the one being + ** dropped. Triggers are handled separately because a trigger can be + ** created in the temp database that refers to a table in another + ** database. + */ + sqlite3NestedParse(pParse, + "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", + pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); + if( !isView && !IsVirtual(pTab) ){ + destroyTable(pParse, pTab); + } + + /* Remove the table entry from SQLite's internal schema and modify + ** the schema cookie. + */ + if( IsVirtual(pTab) ){ + sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); + } + sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); + sqlite3ChangeCookie(pParse, iDb); + sqliteViewResetAll(db, iDb); +} + +/* +** This routine is called to do the work of a DROP TABLE statement. +** pName is the name of the table to be dropped. +*/ +SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ + Table *pTab; + Vdbe *v; + sqlite3 *db = pParse->db; + int iDb; + + if( db->mallocFailed ){ + goto exit_drop_table; + } + assert( pParse->nErr==0 ); + assert( pName->nSrc==1 ); + if( noErr ) db->suppressErr++; + pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); + if( noErr ) db->suppressErr--; + + if( pTab==0 ){ + if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); + goto exit_drop_table; + } + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( iDb>=0 && iDbnDb ); + + /* If pTab is a virtual table, call ViewGetColumnNames() to ensure + ** it is initialized. + */ + if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto exit_drop_table; + } +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int code; + const char *zTab = SCHEMA_TABLE(iDb); + const char *zDb = db->aDb[iDb].zName; + const char *zArg2 = 0; + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ + goto exit_drop_table; + } + if( isView ){ + if( !OMIT_TEMPDB && iDb==1 ){ + code = SQLITE_DROP_TEMP_VIEW; + }else{ + code = SQLITE_DROP_VIEW; + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + }else if( IsVirtual(pTab) ){ + code = SQLITE_DROP_VTABLE; + zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; +#endif + }else{ + if( !OMIT_TEMPDB && iDb==1 ){ + code = SQLITE_DROP_TEMP_TABLE; + }else{ + code = SQLITE_DROP_TABLE; + } + } + if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ + goto exit_drop_table; + } + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ + goto exit_drop_table; + } + } +#endif + if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 + && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ + sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); + goto exit_drop_table; + } + +#ifndef SQLITE_OMIT_VIEW + /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used + ** on a table. + */ + if( isView && pTab->pSelect==0 ){ + sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); + goto exit_drop_table; + } + if( !isView && pTab->pSelect ){ + sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); + goto exit_drop_table; + } +#endif + + /* Generate code to remove the table from the master table + ** on disk. + */ + v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3BeginWriteOperation(pParse, 1, iDb); + sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); + sqlite3FkDropTable(pParse, pName, pTab); + sqlite3CodeDropTable(pParse, pTab, iDb, isView); + } + +exit_drop_table: + sqlite3SrcListDelete(db, pName); +} + +/* +** This routine is called to create a new foreign key on the table +** currently under construction. pFromCol determines which columns +** in the current table point to the foreign key. If pFromCol==0 then +** connect the key to the last column inserted. pTo is the name of +** the table referred to. pToCol is a list of tables in the other +** pTo table that the foreign key points to. flags contains all +** information about the conflict resolution algorithms specified +** in the ON DELETE, ON UPDATE and ON INSERT clauses. +** +** An FKey structure is created and added to the table currently +** under construction in the pParse->pNewTable field. +** +** The foreign key is set for IMMEDIATE processing. A subsequent call +** to sqlite3DeferForeignKey() might change this to DEFERRED. +*/ +SQLITE_PRIVATE void sqlite3CreateForeignKey( + Parse *pParse, /* Parsing context */ + ExprList *pFromCol, /* Columns in this table that point to other table */ + Token *pTo, /* Name of the other table */ + ExprList *pToCol, /* Columns in the other table */ + int flags /* Conflict resolution algorithms. */ +){ + sqlite3 *db = pParse->db; +#ifndef SQLITE_OMIT_FOREIGN_KEY + FKey *pFKey = 0; + FKey *pNextTo; + Table *p = pParse->pNewTable; + int nByte; + int i; + int nCol; + char *z; + + assert( pTo!=0 ); + if( p==0 || IN_DECLARE_VTAB ) goto fk_end; + if( pFromCol==0 ){ + int iCol = p->nCol-1; + if( NEVER(iCol<0) ) goto fk_end; + if( pToCol && pToCol->nExpr!=1 ){ + sqlite3ErrorMsg(pParse, "foreign key on %s" + " should reference only one column of table %T", + p->aCol[iCol].zName, pTo); + goto fk_end; + } + nCol = 1; + }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ + sqlite3ErrorMsg(pParse, + "number of columns in foreign key does not match the number of " + "columns in the referenced table"); + goto fk_end; + }else{ + nCol = pFromCol->nExpr; + } + nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; + if( pToCol ){ + for(i=0; inExpr; i++){ + nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; + } + } + pFKey = sqlite3DbMallocZero(db, nByte ); + if( pFKey==0 ){ + goto fk_end; + } + pFKey->pFrom = p; + pFKey->pNextFrom = p->pFKey; + z = (char*)&pFKey->aCol[nCol]; + pFKey->zTo = z; + memcpy(z, pTo->z, pTo->n); + z[pTo->n] = 0; + sqlite3Dequote(z); + z += pTo->n+1; + pFKey->nCol = nCol; + if( pFromCol==0 ){ + pFKey->aCol[0].iFrom = p->nCol-1; + }else{ + for(i=0; inCol; j++){ + if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ + pFKey->aCol[i].iFrom = j; + break; + } + } + if( j>=p->nCol ){ + sqlite3ErrorMsg(pParse, + "unknown column \"%s\" in foreign key definition", + pFromCol->a[i].zName); + goto fk_end; + } + } + } + if( pToCol ){ + for(i=0; ia[i].zName); + pFKey->aCol[i].zCol = z; + memcpy(z, pToCol->a[i].zName, n); + z[n] = 0; + z += n+1; + } + } + pFKey->isDeferred = 0; + pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ + pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ + + assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); + pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, + pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey + ); + if( pNextTo==pFKey ){ + db->mallocFailed = 1; + goto fk_end; + } + if( pNextTo ){ + assert( pNextTo->pPrevTo==0 ); + pFKey->pNextTo = pNextTo; + pNextTo->pPrevTo = pFKey; + } + + /* Link the foreign key to the table as the last step. + */ + p->pFKey = pFKey; + pFKey = 0; + +fk_end: + sqlite3DbFree(db, pFKey); +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ + sqlite3ExprListDelete(db, pFromCol); + sqlite3ExprListDelete(db, pToCol); +} + +/* +** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED +** clause is seen as part of a foreign key definition. The isDeferred +** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. +** The behavior of the most recently created foreign key is adjusted +** accordingly. +*/ +SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ +#ifndef SQLITE_OMIT_FOREIGN_KEY + Table *pTab; + FKey *pFKey; + if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; + assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ + pFKey->isDeferred = (u8)isDeferred; +#endif +} + +/* +** Generate code that will erase and refill index *pIdx. This is +** used to initialize a newly created index or to recompute the +** content of an index in response to a REINDEX command. +** +** if memRootPage is not negative, it means that the index is newly +** created. The register specified by memRootPage contains the +** root page number of the index. If memRootPage is negative, then +** the index already exists and must be cleared before being refilled and +** the root page number of the index is taken from pIndex->tnum. +*/ +static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ + Table *pTab = pIndex->pTable; /* The table that is indexed */ + int iTab = pParse->nTab++; /* Btree cursor used for pTab */ + int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ + int iSorter; /* Cursor opened by OpenSorter (if in use) */ + int addr1; /* Address of top of loop */ + int addr2; /* Address to jump to for next iteration */ + int tnum; /* Root page of index */ + int iPartIdxLabel; /* Jump to this label to skip a row */ + Vdbe *v; /* Generate code into this virtual machine */ + KeyInfo *pKey; /* KeyInfo for index */ + int regRecord; /* Register holding assemblied index record */ + sqlite3 *db = pParse->db; /* The database connection */ + int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); + +#ifndef SQLITE_OMIT_AUTHORIZATION + if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, + db->aDb[iDb].zName ) ){ + return; + } +#endif + + /* Require a write-lock on the table to perform this operation */ + sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); + + v = sqlite3GetVdbe(pParse); + if( v==0 ) return; + if( memRootPage>=0 ){ + tnum = memRootPage; + }else{ + tnum = pIndex->tnum; + sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); + } + pKey = sqlite3IndexKeyinfo(pParse, pIndex); + sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, + (char *)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); + + /* Open the sorter cursor if we are to use one. */ + iSorter = pParse->nTab++; + sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO); + + /* Open the table. Loop through all rows of the table, inserting index + ** records into the sorter. */ + sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); + addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); + regRecord = sqlite3GetTempReg(pParse); + + sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel); + sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); + sqlite3VdbeResolveLabel(v, iPartIdxLabel); + sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); + sqlite3VdbeJumpHere(v, addr1); + addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); + if( pIndex->onError!=OE_None ){ + int j2 = sqlite3VdbeCurrentAddr(v) + 3; + sqlite3VdbeAddOp2(v, OP_Goto, 0, j2); + addr2 = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE, + OE_Abort, "indexed columns are not unique", P4_STATIC + ); + }else{ + addr2 = sqlite3VdbeCurrentAddr(v); + } + sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord); + sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1); + sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + sqlite3ReleaseTempReg(pParse, regRecord); + sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); + sqlite3VdbeJumpHere(v, addr1); + + sqlite3VdbeAddOp1(v, OP_Close, iTab); + sqlite3VdbeAddOp1(v, OP_Close, iIdx); + sqlite3VdbeAddOp1(v, OP_Close, iSorter); +} + +/* +** Create a new index for an SQL table. pName1.pName2 is the name of the index +** and pTblList is the name of the table that is to be indexed. Both will +** be NULL for a primary key or an index that is created to satisfy a +** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable +** as the table to be indexed. pParse->pNewTable is a table that is +** currently being constructed by a CREATE TABLE statement. +** +** pList is a list of columns to be indexed. pList will be NULL if this +** is a primary key or unique-constraint on the most recent column added +** to the table currently under construction. +** +** If the index is created successfully, return a pointer to the new Index +** structure. This is used by sqlite3AddPrimaryKey() to mark the index +** as the tables primary key (Index.autoIndex==2). +*/ +SQLITE_PRIVATE Index *sqlite3CreateIndex( + Parse *pParse, /* All information about this parse */ + Token *pName1, /* First part of index name. May be NULL */ + Token *pName2, /* Second part of index name. May be NULL */ + SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ + ExprList *pList, /* A list of columns to be indexed */ + int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ + Token *pStart, /* The CREATE token that begins this statement */ + Expr *pPIWhere, /* WHERE clause for partial indices */ + int sortOrder, /* Sort order of primary key when pList==NULL */ + int ifNotExist /* Omit error if index already exists */ +){ + Index *pRet = 0; /* Pointer to return */ + Table *pTab = 0; /* Table to be indexed */ + Index *pIndex = 0; /* The index to be created */ + char *zName = 0; /* Name of the index */ + int nName; /* Number of characters in zName */ + int i, j; + Token nullId; /* Fake token for an empty ID list */ + DbFixer sFix; /* For assigning database names to pTable */ + int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ + sqlite3 *db = pParse->db; + Db *pDb; /* The specific table containing the indexed database */ + int iDb; /* Index of the database that is being written */ + Token *pName = 0; /* Unqualified name of the index to create */ + struct ExprList_item *pListItem; /* For looping over pList */ + const Column *pTabCol; /* A column in the table */ + int nCol; /* Number of columns */ + int nExtra = 0; /* Space allocated for zExtra[] */ + char *zExtra; /* Extra space after the Index object */ + + assert( pParse->nErr==0 ); /* Never called with prior errors */ + if( db->mallocFailed || IN_DECLARE_VTAB ){ + goto exit_create_index; + } + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + goto exit_create_index; + } + + /* + ** Find the table that is to be indexed. Return early if not found. + */ + if( pTblName!=0 ){ + + /* Use the two-part index name to determine the database + ** to search for the table. 'Fix' the table name to this db + ** before looking up the table. + */ + assert( pName1 && pName2 ); + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); + if( iDb<0 ) goto exit_create_index; + assert( pName && pName->z ); + +#ifndef SQLITE_OMIT_TEMPDB + /* If the index name was unqualified, check if the table + ** is a temp table. If so, set the database to 1. Do not do this + ** if initialising a database schema. + */ + if( !db->init.busy ){ + pTab = sqlite3SrcListLookup(pParse, pTblName); + if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ + iDb = 1; + } + } +#endif + + sqlite3FixInit(&sFix, pParse, iDb, "index", pName); + if( sqlite3FixSrcList(&sFix, pTblName) ){ + /* Because the parser constructs pTblName from a single identifier, + ** sqlite3FixSrcList can never fail. */ + assert(0); + } + pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); + assert( db->mallocFailed==0 || pTab==0 ); + if( pTab==0 ) goto exit_create_index; + if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ + sqlite3ErrorMsg(pParse, + "cannot create a TEMP index on non-TEMP table \"%s\"", + pTab->zName); + goto exit_create_index; + } + }else{ + assert( pName==0 ); + assert( pStart==0 ); + pTab = pParse->pNewTable; + if( !pTab ) goto exit_create_index; + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + } + pDb = &db->aDb[iDb]; + + assert( pTab!=0 ); + assert( pParse->nErr==0 ); + if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 + && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ + sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); + goto exit_create_index; + } +#ifndef SQLITE_OMIT_VIEW + if( pTab->pSelect ){ + sqlite3ErrorMsg(pParse, "views may not be indexed"); + goto exit_create_index; + } +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); + goto exit_create_index; + } +#endif + + /* + ** Find the name of the index. Make sure there is not already another + ** index or table with the same name. + ** + ** Exception: If we are reading the names of permanent indices from the + ** sqlite_master table (because some other process changed the schema) and + ** one of the index names collides with the name of a temporary table or + ** index, then we will continue to process this index. + ** + ** If pName==0 it means that we are + ** dealing with a primary key or UNIQUE constraint. We have to invent our + ** own name. + */ + if( pName ){ + zName = sqlite3NameFromToken(db, pName); + if( zName==0 ) goto exit_create_index; + assert( pName->z!=0 ); + if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ + goto exit_create_index; + } + if( !db->init.busy ){ + if( sqlite3FindTable(db, zName, 0)!=0 ){ + sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); + goto exit_create_index; + } + } + if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ + if( !ifNotExist ){ + sqlite3ErrorMsg(pParse, "index %s already exists", zName); + }else{ + assert( !db->init.busy ); + sqlite3CodeVerifySchema(pParse, iDb); + } + goto exit_create_index; + } + }else{ + int n; + Index *pLoop; + for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} + zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); + if( zName==0 ){ + goto exit_create_index; + } + } + + /* Check for authorization to create an index. + */ +#ifndef SQLITE_OMIT_AUTHORIZATION + { + const char *zDb = pDb->zName; + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ + goto exit_create_index; + } + i = SQLITE_CREATE_INDEX; + if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; + if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ + goto exit_create_index; + } + } +#endif + + /* If pList==0, it means this routine was called to make a primary + ** key out of the last column added to the table under construction. + ** So create a fake list to simulate this. + */ + if( pList==0 ){ + nullId.z = pTab->aCol[pTab->nCol-1].zName; + nullId.n = sqlite3Strlen30((char*)nullId.z); + pList = sqlite3ExprListAppend(pParse, 0, 0); + if( pList==0 ) goto exit_create_index; + sqlite3ExprListSetName(pParse, pList, &nullId, 0); + pList->a[0].sortOrder = (u8)sortOrder; + } + + /* Figure out how many bytes of space are required to store explicitly + ** specified collation sequence names. + */ + for(i=0; inExpr; i++){ + Expr *pExpr = pList->a[i].pExpr; + if( pExpr ){ + assert( pExpr->op==TK_COLLATE ); + nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); + } + } + + /* + ** Allocate the index structure. + */ + nName = sqlite3Strlen30(zName); + nCol = pList->nExpr; + pIndex = sqlite3DbMallocZero(db, + ROUND8(sizeof(Index)) + /* Index structure */ + ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */ + sizeof(char *)*nCol + /* Index.azColl */ + sizeof(int)*nCol + /* Index.aiColumn */ + sizeof(u8)*nCol + /* Index.aSortOrder */ + nName + 1 + /* Index.zName */ + nExtra /* Collation sequence names */ + ); + if( db->mallocFailed ){ + goto exit_create_index; + } + zExtra = (char*)pIndex; + pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))]; + pIndex->azColl = (char**) + ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1)); + assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) ); + assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); + pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]); + pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]); + pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]); + zExtra = (char *)(&pIndex->zName[nName+1]); + memcpy(pIndex->zName, zName, nName+1); + pIndex->pTable = pTab; + pIndex->nColumn = pList->nExpr; + pIndex->onError = (u8)onError; + pIndex->uniqNotNull = onError==OE_Abort; + pIndex->autoIndex = (u8)(pName==0); + pIndex->pSchema = db->aDb[iDb].pSchema; + if( pPIWhere ){ + sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); + pIndex->pPartIdxWhere = pPIWhere; + pPIWhere = 0; + } + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + + /* Check to see if we should honor DESC requests on index columns + */ + if( pDb->pSchema->file_format>=4 ){ + sortOrderMask = -1; /* Honor DESC */ + }else{ + sortOrderMask = 0; /* Ignore DESC */ + } + + /* Scan the names of the columns of the table to be indexed and + ** load the column indices into the Index structure. Report an error + ** if any column is not found. + ** + ** TODO: Add a test to make sure that the same column is not named + ** more than once within the same index. Only the first instance of + ** the column will ever be used by the optimizer. Note that using the + ** same column more than once cannot be an error because that would + ** break backwards compatibility - it needs to be a warning. + */ + for(i=0, pListItem=pList->a; inExpr; i++, pListItem++){ + const char *zColName = pListItem->zName; + int requestedSortOrder; + char *zColl; /* Collation sequence name */ + + for(j=0, pTabCol=pTab->aCol; jnCol; j++, pTabCol++){ + if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break; + } + if( j>=pTab->nCol ){ + sqlite3ErrorMsg(pParse, "table %s has no column named %s", + pTab->zName, zColName); + pParse->checkSchema = 1; + goto exit_create_index; + } + pIndex->aiColumn[i] = j; + if( pListItem->pExpr ){ + int nColl; + assert( pListItem->pExpr->op==TK_COLLATE ); + zColl = pListItem->pExpr->u.zToken; + nColl = sqlite3Strlen30(zColl) + 1; + assert( nExtra>=nColl ); + memcpy(zExtra, zColl, nColl); + zColl = zExtra; + zExtra += nColl; + nExtra -= nColl; + }else{ + zColl = pTab->aCol[j].zColl; + if( !zColl ) zColl = "BINARY"; + } + if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ + goto exit_create_index; + } + pIndex->azColl[i] = zColl; + requestedSortOrder = pListItem->sortOrder & sortOrderMask; + pIndex->aSortOrder[i] = (u8)requestedSortOrder; + if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0; + } + sqlite3DefaultRowEst(pIndex); + if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); + + if( pTab==pParse->pNewTable ){ + /* This routine has been called to create an automatic index as a + ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or + ** a PRIMARY KEY or UNIQUE clause following the column definitions. + ** i.e. one of: + ** + ** CREATE TABLE t(x PRIMARY KEY, y); + ** CREATE TABLE t(x, y, UNIQUE(x, y)); + ** + ** Either way, check to see if the table already has such an index. If + ** so, don't bother creating this one. This only applies to + ** automatically created indices. Users can do as they wish with + ** explicit indices. + ** + ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent + ** (and thus suppressing the second one) even if they have different + ** sort orders. + ** + ** If there are different collating sequences or if the columns of + ** the constraint occur in different orders, then the constraints are + ** considered distinct and both result in separate indices. + */ + Index *pIdx; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + int k; + assert( pIdx->onError!=OE_None ); + assert( pIdx->autoIndex ); + assert( pIndex->onError!=OE_None ); + + if( pIdx->nColumn!=pIndex->nColumn ) continue; + for(k=0; knColumn; k++){ + const char *z1; + const char *z2; + if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; + z1 = pIdx->azColl[k]; + z2 = pIndex->azColl[k]; + if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; + } + if( k==pIdx->nColumn ){ + if( pIdx->onError!=pIndex->onError ){ + /* This constraint creates the same index as a previous + ** constraint specified somewhere in the CREATE TABLE statement. + ** However the ON CONFLICT clauses are different. If both this + ** constraint and the previous equivalent constraint have explicit + ** ON CONFLICT clauses this is an error. Otherwise, use the + ** explicitly specified behavior for the index. + */ + if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ + sqlite3ErrorMsg(pParse, + "conflicting ON CONFLICT clauses specified", 0); + } + if( pIdx->onError==OE_Default ){ + pIdx->onError = pIndex->onError; + } + } + goto exit_create_index; + } + } + } + + /* Link the new Index structure to its table and to the other + ** in-memory database structures. + */ + if( db->init.busy ){ + Index *p; + assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); + p = sqlite3HashInsert(&pIndex->pSchema->idxHash, + pIndex->zName, sqlite3Strlen30(pIndex->zName), + pIndex); + if( p ){ + assert( p==pIndex ); /* Malloc must have failed */ + db->mallocFailed = 1; + goto exit_create_index; + } + db->flags |= SQLITE_InternChanges; + if( pTblName!=0 ){ + pIndex->tnum = db->init.newTnum; + } + } + + /* If the db->init.busy is 0 then create the index on disk. This + ** involves writing the index into the master table and filling in the + ** index with the current table contents. + ** + ** The db->init.busy is 0 when the user first enters a CREATE INDEX + ** command. db->init.busy is 1 when a database is opened and + ** CREATE INDEX statements are read out of the master table. In + ** the latter case the index already exists on disk, which is why + ** we don't want to recreate it. + ** + ** If pTblName==0 it means this index is generated as a primary key + ** or UNIQUE constraint of a CREATE TABLE statement. Since the table + ** has just been created, it contains no data and the index initialization + ** step can be skipped. + */ + else if( pParse->nErr==0 ){ + Vdbe *v; + char *zStmt; + int iMem = ++pParse->nMem; + + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto exit_create_index; + + + /* Create the rootpage for the index + */ + sqlite3BeginWriteOperation(pParse, 1, iDb); + sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); + + /* Gather the complete text of the CREATE INDEX statement into + ** the zStmt variable + */ + if( pStart ){ + int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; + if( pName->z[n-1]==';' ) n--; + /* A named index with an explicit CREATE INDEX statement */ + zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", + onError==OE_None ? "" : " UNIQUE", n, pName->z); + }else{ + /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ + /* zStmt = sqlite3MPrintf(""); */ + zStmt = 0; + } + + /* Add an entry in sqlite_master for this index + */ + sqlite3NestedParse(pParse, + "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), + pIndex->zName, + pTab->zName, + iMem, + zStmt + ); + sqlite3DbFree(db, zStmt); + + /* Fill the index with data and reparse the schema. Code an OP_Expire + ** to invalidate all pre-compiled statements. + */ + if( pTblName ){ + sqlite3RefillIndex(pParse, pIndex, iMem); + sqlite3ChangeCookie(pParse, iDb); + sqlite3VdbeAddParseSchemaOp(v, iDb, + sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); + sqlite3VdbeAddOp1(v, OP_Expire, 0); + } + } + + /* When adding an index to the list of indices for a table, make + ** sure all indices labeled OE_Replace come after all those labeled + ** OE_Ignore. This is necessary for the correct constraint check + ** processing (in sqlite3GenerateConstraintChecks()) as part of + ** UPDATE and INSERT statements. + */ + if( db->init.busy || pTblName==0 ){ + if( onError!=OE_Replace || pTab->pIndex==0 + || pTab->pIndex->onError==OE_Replace){ + pIndex->pNext = pTab->pIndex; + pTab->pIndex = pIndex; + }else{ + Index *pOther = pTab->pIndex; + while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ + pOther = pOther->pNext; + } + pIndex->pNext = pOther->pNext; + pOther->pNext = pIndex; + } + pRet = pIndex; + pIndex = 0; + } + + /* Clean up before exiting */ +exit_create_index: + if( pIndex ) freeIndex(db, pIndex); + sqlite3ExprDelete(db, pPIWhere); + sqlite3ExprListDelete(db, pList); + sqlite3SrcListDelete(db, pTblName); + sqlite3DbFree(db, zName); + return pRet; +} + +/* +** Fill the Index.aiRowEst[] array with default information - information +** to be used when we have not run the ANALYZE command. +** +** aiRowEst[0] is suppose to contain the number of elements in the index. +** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the +** number of rows in the table that match any particular value of the +** first column of the index. aiRowEst[2] is an estimate of the number +** of rows that match any particular combiniation of the first 2 columns +** of the index. And so forth. It must always be the case that +* +** aiRowEst[N]<=aiRowEst[N-1] +** aiRowEst[N]>=1 +** +** Apart from that, we have little to go on besides intuition as to +** how aiRowEst[] should be initialized. The numbers generated here +** are based on typical values found in actual indices. +*/ +SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){ + tRowcnt *a = pIdx->aiRowEst; + int i; + tRowcnt n; + assert( a!=0 ); + a[0] = pIdx->pTable->nRowEst; + if( a[0]<10 ) a[0] = 10; + n = 10; + for(i=1; i<=pIdx->nColumn; i++){ + a[i] = n; + if( n>5 ) n--; + } + if( pIdx->onError!=OE_None ){ + a[pIdx->nColumn] = 1; + } +} + +/* +** This routine will drop an existing named index. This routine +** implements the DROP INDEX statement. +*/ +SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ + Index *pIndex; + Vdbe *v; + sqlite3 *db = pParse->db; + int iDb; + + assert( pParse->nErr==0 ); /* Never called with prior errors */ + if( db->mallocFailed ){ + goto exit_drop_index; + } + assert( pName->nSrc==1 ); + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + goto exit_drop_index; + } + pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); + if( pIndex==0 ){ + if( !ifExists ){ + sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); + }else{ + sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); + } + pParse->checkSchema = 1; + goto exit_drop_index; + } + if( pIndex->autoIndex ){ + sqlite3ErrorMsg(pParse, "index associated with UNIQUE " + "or PRIMARY KEY constraint cannot be dropped", 0); + goto exit_drop_index; + } + iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int code = SQLITE_DROP_INDEX; + Table *pTab = pIndex->pTable; + const char *zDb = db->aDb[iDb].zName; + const char *zTab = SCHEMA_TABLE(iDb); + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ + goto exit_drop_index; + } + if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; + if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ + goto exit_drop_index; + } + } +#endif + + /* Generate code to remove the index and from the master table */ + v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3BeginWriteOperation(pParse, 1, iDb); + sqlite3NestedParse(pParse, + "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName + ); + sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); + sqlite3ChangeCookie(pParse, iDb); + destroyRootPage(pParse, pIndex->tnum, iDb); + sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); + } + +exit_drop_index: + sqlite3SrcListDelete(db, pName); +} + +/* +** pArray is a pointer to an array of objects. Each object in the +** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() +** to extend the array so that there is space for a new object at the end. +** +** When this function is called, *pnEntry contains the current size of +** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes +** in total). +** +** If the realloc() is successful (i.e. if no OOM condition occurs), the +** space allocated for the new object is zeroed, *pnEntry updated to +** reflect the new size of the array and a pointer to the new allocation +** returned. *pIdx is set to the index of the new array entry in this case. +** +** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains +** unchanged and a copy of pArray returned. +*/ +SQLITE_PRIVATE void *sqlite3ArrayAllocate( + sqlite3 *db, /* Connection to notify of malloc failures */ + void *pArray, /* Array of objects. Might be reallocated */ + int szEntry, /* Size of each object in the array */ + int *pnEntry, /* Number of objects currently in use */ + int *pIdx /* Write the index of a new slot here */ +){ + char *z; + int n = *pnEntry; + if( (n & (n-1))==0 ){ + int sz = (n==0) ? 1 : 2*n; + void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); + if( pNew==0 ){ + *pIdx = -1; + return pArray; + } + pArray = pNew; + } + z = (char*)pArray; + memset(&z[n * szEntry], 0, szEntry); + *pIdx = n; + ++*pnEntry; + return pArray; +} + +/* +** Append a new element to the given IdList. Create a new IdList if +** need be. +** +** A new IdList is returned, or NULL if malloc() fails. +*/ +SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ + int i; + if( pList==0 ){ + pList = sqlite3DbMallocZero(db, sizeof(IdList) ); + if( pList==0 ) return 0; + } + pList->a = sqlite3ArrayAllocate( + db, + pList->a, + sizeof(pList->a[0]), + &pList->nId, + &i + ); + if( i<0 ){ + sqlite3IdListDelete(db, pList); + return 0; + } + pList->a[i].zName = sqlite3NameFromToken(db, pToken); + return pList; +} + +/* +** Delete an IdList. +*/ +SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ + int i; + if( pList==0 ) return; + for(i=0; inId; i++){ + sqlite3DbFree(db, pList->a[i].zName); + } + sqlite3DbFree(db, pList->a); + sqlite3DbFree(db, pList); +} + +/* +** Return the index in pList of the identifier named zId. Return -1 +** if not found. +*/ +SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){ + int i; + if( pList==0 ) return -1; + for(i=0; inId; i++){ + if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; + } + return -1; +} + +/* +** Expand the space allocated for the given SrcList object by +** creating nExtra new slots beginning at iStart. iStart is zero based. +** New slots are zeroed. +** +** For example, suppose a SrcList initially contains two entries: A,B. +** To append 3 new entries onto the end, do this: +** +** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); +** +** After the call above it would contain: A, B, nil, nil, nil. +** If the iStart argument had been 1 instead of 2, then the result +** would have been: A, nil, nil, nil, B. To prepend the new slots, +** the iStart value would be 0. The result then would +** be: nil, nil, nil, A, B. +** +** If a memory allocation fails the SrcList is unchanged. The +** db->mallocFailed flag will be set to true. +*/ +SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( + sqlite3 *db, /* Database connection to notify of OOM errors */ + SrcList *pSrc, /* The SrcList to be enlarged */ + int nExtra, /* Number of new slots to add to pSrc->a[] */ + int iStart /* Index in pSrc->a[] of first new slot */ +){ + int i; + + /* Sanity checking on calling parameters */ + assert( iStart>=0 ); + assert( nExtra>=1 ); + assert( pSrc!=0 ); + assert( iStart<=pSrc->nSrc ); + + /* Allocate additional space if needed */ + if( pSrc->nSrc+nExtra>pSrc->nAlloc ){ + SrcList *pNew; + int nAlloc = pSrc->nSrc+nExtra; + int nGot; + pNew = sqlite3DbRealloc(db, pSrc, + sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); + if( pNew==0 ){ + assert( db->mallocFailed ); + return pSrc; + } + pSrc = pNew; + nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; + pSrc->nAlloc = (u8)nGot; + } + + /* Move existing slots that come after the newly inserted slots + ** out of the way */ + for(i=pSrc->nSrc-1; i>=iStart; i--){ + pSrc->a[i+nExtra] = pSrc->a[i]; + } + pSrc->nSrc += (i8)nExtra; + + /* Zero the newly allocated slots */ + memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); + for(i=iStart; ia[i].iCursor = -1; + } + + /* Return a pointer to the enlarged SrcList */ + return pSrc; +} + + +/* +** Append a new table name to the given SrcList. Create a new SrcList if +** need be. A new entry is created in the SrcList even if pTable is NULL. +** +** A SrcList is returned, or NULL if there is an OOM error. The returned +** SrcList might be the same as the SrcList that was input or it might be +** a new one. If an OOM error does occurs, then the prior value of pList +** that is input to this routine is automatically freed. +** +** If pDatabase is not null, it means that the table has an optional +** database name prefix. Like this: "database.table". The pDatabase +** points to the table name and the pTable points to the database name. +** The SrcList.a[].zName field is filled with the table name which might +** come from pTable (if pDatabase is NULL) or from pDatabase. +** SrcList.a[].zDatabase is filled with the database name from pTable, +** or with NULL if no database is specified. +** +** In other words, if call like this: +** +** sqlite3SrcListAppend(D,A,B,0); +** +** Then B is a table name and the database name is unspecified. If called +** like this: +** +** sqlite3SrcListAppend(D,A,B,C); +** +** Then C is the table name and B is the database name. If C is defined +** then so is B. In other words, we never have a case where: +** +** sqlite3SrcListAppend(D,A,0,C); +** +** Both pTable and pDatabase are assumed to be quoted. They are dequoted +** before being added to the SrcList. +*/ +SQLITE_PRIVATE SrcList *sqlite3SrcListAppend( + sqlite3 *db, /* Connection to notify of malloc failures */ + SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ + Token *pTable, /* Table to append */ + Token *pDatabase /* Database of the table */ +){ + struct SrcList_item *pItem; + assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ + if( pList==0 ){ + pList = sqlite3DbMallocZero(db, sizeof(SrcList) ); + if( pList==0 ) return 0; + pList->nAlloc = 1; + } + pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); + if( db->mallocFailed ){ + sqlite3SrcListDelete(db, pList); + return 0; + } + pItem = &pList->a[pList->nSrc-1]; + if( pDatabase && pDatabase->z==0 ){ + pDatabase = 0; + } + if( pDatabase ){ + Token *pTemp = pDatabase; + pDatabase = pTable; + pTable = pTemp; + } + pItem->zName = sqlite3NameFromToken(db, pTable); + pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); + return pList; +} + +/* +** Assign VdbeCursor index numbers to all tables in a SrcList +*/ +SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ + int i; + struct SrcList_item *pItem; + assert(pList || pParse->db->mallocFailed ); + if( pList ){ + for(i=0, pItem=pList->a; inSrc; i++, pItem++){ + if( pItem->iCursor>=0 ) break; + pItem->iCursor = pParse->nTab++; + if( pItem->pSelect ){ + sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); + } + } + } +} + +/* +** Delete an entire SrcList including all its substructure. +*/ +SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ + int i; + struct SrcList_item *pItem; + if( pList==0 ) return; + for(pItem=pList->a, i=0; inSrc; i++, pItem++){ + sqlite3DbFree(db, pItem->zDatabase); + sqlite3DbFree(db, pItem->zName); + sqlite3DbFree(db, pItem->zAlias); + sqlite3DbFree(db, pItem->zIndex); + sqlite3DeleteTable(db, pItem->pTab); + sqlite3SelectDelete(db, pItem->pSelect); + sqlite3ExprDelete(db, pItem->pOn); + sqlite3IdListDelete(db, pItem->pUsing); + } + sqlite3DbFree(db, pList); +} + +/* +** This routine is called by the parser to add a new term to the +** end of a growing FROM clause. The "p" parameter is the part of +** the FROM clause that has already been constructed. "p" is NULL +** if this is the first term of the FROM clause. pTable and pDatabase +** are the name of the table and database named in the FROM clause term. +** pDatabase is NULL if the database name qualifier is missing - the +** usual case. If the term has a alias, then pAlias points to the +** alias token. If the term is a subquery, then pSubquery is the +** SELECT statement that the subquery encodes. The pTable and +** pDatabase parameters are NULL for subqueries. The pOn and pUsing +** parameters are the content of the ON and USING clauses. +** +** Return a new SrcList which encodes is the FROM with the new +** term added. +*/ +SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm( + Parse *pParse, /* Parsing context */ + SrcList *p, /* The left part of the FROM clause already seen */ + Token *pTable, /* Name of the table to add to the FROM clause */ + Token *pDatabase, /* Name of the database containing pTable */ + Token *pAlias, /* The right-hand side of the AS subexpression */ + Select *pSubquery, /* A subquery used in place of a table name */ + Expr *pOn, /* The ON clause of a join */ + IdList *pUsing /* The USING clause of a join */ +){ + struct SrcList_item *pItem; + sqlite3 *db = pParse->db; + if( !p && (pOn || pUsing) ){ + sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", + (pOn ? "ON" : "USING") + ); + goto append_from_error; + } + p = sqlite3SrcListAppend(db, p, pTable, pDatabase); + if( p==0 || NEVER(p->nSrc==0) ){ + goto append_from_error; + } + pItem = &p->a[p->nSrc-1]; + assert( pAlias!=0 ); + if( pAlias->n ){ + pItem->zAlias = sqlite3NameFromToken(db, pAlias); + } + pItem->pSelect = pSubquery; + pItem->pOn = pOn; + pItem->pUsing = pUsing; + return p; + + append_from_error: + assert( p==0 ); + sqlite3ExprDelete(db, pOn); + sqlite3IdListDelete(db, pUsing); + sqlite3SelectDelete(db, pSubquery); + return 0; +} + +/* +** Add an INDEXED BY or NOT INDEXED clause to the most recently added +** element of the source-list passed as the second argument. +*/ +SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ + assert( pIndexedBy!=0 ); + if( p && ALWAYS(p->nSrc>0) ){ + struct SrcList_item *pItem = &p->a[p->nSrc-1]; + assert( pItem->notIndexed==0 && pItem->zIndex==0 ); + if( pIndexedBy->n==1 && !pIndexedBy->z ){ + /* A "NOT INDEXED" clause was supplied. See parse.y + ** construct "indexed_opt" for details. */ + pItem->notIndexed = 1; + }else{ + pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy); + } + } +} + +/* +** When building up a FROM clause in the parser, the join operator +** is initially attached to the left operand. But the code generator +** expects the join operator to be on the right operand. This routine +** Shifts all join operators from left to right for an entire FROM +** clause. +** +** Example: Suppose the join is like this: +** +** A natural cross join B +** +** The operator is "natural cross join". The A and B operands are stored +** in p->a[0] and p->a[1], respectively. The parser initially stores the +** operator with A. This routine shifts that operator over to B. +*/ +SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){ + if( p ){ + int i; + assert( p->a || p->nSrc==0 ); + for(i=p->nSrc-1; i>0; i--){ + p->a[i].jointype = p->a[i-1].jointype; + } + p->a[0].jointype = 0; + } +} + +/* +** Begin a transaction +*/ +SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){ + sqlite3 *db; + Vdbe *v; + int i; + + assert( pParse!=0 ); + db = pParse->db; + assert( db!=0 ); +/* if( db->aDb[0].pBt==0 ) return; */ + if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ + return; + } + v = sqlite3GetVdbe(pParse); + if( !v ) return; + if( type!=TK_DEFERRED ){ + for(i=0; inDb; i++){ + sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); + sqlite3VdbeUsesBtree(v, i); + } + } + sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); +} + +/* +** Commit a transaction +*/ +SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){ + Vdbe *v; + + assert( pParse!=0 ); + assert( pParse->db!=0 ); + if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ + return; + } + v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); + } +} + +/* +** Rollback a transaction +*/ +SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){ + Vdbe *v; + + assert( pParse!=0 ); + assert( pParse->db!=0 ); + if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ + return; + } + v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); + } +} + +/* +** This function is called by the parser when it parses a command to create, +** release or rollback an SQL savepoint. +*/ +SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ + char *zName = sqlite3NameFromToken(pParse->db, pName); + if( zName ){ + Vdbe *v = sqlite3GetVdbe(pParse); +#ifndef SQLITE_OMIT_AUTHORIZATION + static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; + assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); +#endif + if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ + sqlite3DbFree(pParse->db, zName); + return; + } + sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); + } +} + +/* +** Make sure the TEMP database is open and available for use. Return +** the number of errors. Leave any error messages in the pParse structure. +*/ +SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){ + sqlite3 *db = pParse->db; + if( db->aDb[1].pBt==0 && !pParse->explain ){ + int rc; + Btree *pBt; + static const int flags = + SQLITE_OPEN_READWRITE | + SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | + SQLITE_OPEN_DELETEONCLOSE | + SQLITE_OPEN_TEMP_DB; + + rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); + if( rc!=SQLITE_OK ){ + sqlite3ErrorMsg(pParse, "unable to open a temporary database " + "file for storing temporary tables"); + pParse->rc = rc; + return 1; + } + db->aDb[1].pBt = pBt; + assert( db->aDb[1].pSchema ); + if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ + db->mallocFailed = 1; + return 1; + } + } + return 0; +} + +/* +** Generate VDBE code that will verify the schema cookie and start +** a read-transaction for all named database files. +** +** It is important that all schema cookies be verified and all +** read transactions be started before anything else happens in +** the VDBE program. But this routine can be called after much other +** code has been generated. So here is what we do: +** +** The first time this routine is called, we code an OP_Goto that +** will jump to a subroutine at the end of the program. Then we +** record every database that needs its schema verified in the +** pParse->cookieMask field. Later, after all other code has been +** generated, the subroutine that does the cookie verifications and +** starts the transactions will be coded and the OP_Goto P2 value +** will be made to point to that subroutine. The generation of the +** cookie verification subroutine code happens in sqlite3FinishCoding(). +** +** If iDb<0 then code the OP_Goto only - don't set flag to verify the +** schema on any databases. This can be used to position the OP_Goto +** early in the code, before we know if any database tables will be used. +*/ +SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + +#ifndef SQLITE_OMIT_TRIGGER + if( pToplevel!=pParse ){ + /* This branch is taken if a trigger is currently being coded. In this + ** case, set cookieGoto to a non-zero value to show that this function + ** has been called. This is used by the sqlite3ExprCodeConstants() + ** function. */ + pParse->cookieGoto = -1; + } +#endif + if( pToplevel->cookieGoto==0 ){ + Vdbe *v = sqlite3GetVdbe(pToplevel); + if( v==0 ) return; /* This only happens if there was a prior error */ + pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1; + } + if( iDb>=0 ){ + sqlite3 *db = pToplevel->db; + yDbMask mask; + + assert( iDbnDb ); + assert( db->aDb[iDb].pBt!=0 || iDb==1 ); + assert( iDbcookieMask & mask)==0 ){ + pToplevel->cookieMask |= mask; + pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie; + if( !OMIT_TEMPDB && iDb==1 ){ + sqlite3OpenTempDatabase(pToplevel); + } + } + } +} + +/* +** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each +** attached database. Otherwise, invoke it for the database named zDb only. +*/ +SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ + sqlite3 *db = pParse->db; + int i; + for(i=0; inDb; i++){ + Db *pDb = &db->aDb[i]; + if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){ + sqlite3CodeVerifySchema(pParse, i); + } + } +} + +/* +** Generate VDBE code that prepares for doing an operation that +** might change the database. +** +** This routine starts a new transaction if we are not already within +** a transaction. If we are already within a transaction, then a checkpoint +** is set if the setStatement parameter is true. A checkpoint should +** be set for operations that might fail (due to a constraint) part of +** the way through and which will need to undo some writes without having to +** rollback the whole transaction. For operations where all constraints +** can be checked before any changes are made to the database, it is never +** necessary to undo a write and the checkpoint should not be set. +*/ +SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + sqlite3CodeVerifySchema(pParse, iDb); + pToplevel->writeMask |= ((yDbMask)1)<isMultiWrite |= setStatement; +} + +/* +** Indicate that the statement currently under construction might write +** more than one entry (example: deleting one row then inserting another, +** inserting multiple rows in a table, or inserting a row and index entries.) +** If an abort occurs after some of these writes have completed, then it will +** be necessary to undo the completed writes. +*/ +SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + pToplevel->isMultiWrite = 1; +} + +/* +** The code generator calls this routine if is discovers that it is +** possible to abort a statement prior to completion. In order to +** perform this abort without corrupting the database, we need to make +** sure that the statement is protected by a statement transaction. +** +** Technically, we only need to set the mayAbort flag if the +** isMultiWrite flag was previously set. There is a time dependency +** such that the abort must occur after the multiwrite. This makes +** some statements involving the REPLACE conflict resolution algorithm +** go a little faster. But taking advantage of this time dependency +** makes it more difficult to prove that the code is correct (in +** particular, it prevents us from writing an effective +** implementation of sqlite3AssertMayAbort()) and so we have chosen +** to take the safe route and skip the optimization. +*/ +SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + pToplevel->mayAbort = 1; +} + +/* +** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT +** error. The onError parameter determines which (if any) of the statement +** and/or current transaction is rolled back. +*/ +SQLITE_PRIVATE void sqlite3HaltConstraint( + Parse *pParse, /* Parsing context */ + int errCode, /* extended error code */ + int onError, /* Constraint type */ + char *p4, /* Error message */ + int p4type /* P4_STATIC or P4_TRANSIENT */ +){ + Vdbe *v = sqlite3GetVdbe(pParse); + assert( (errCode&0xff)==SQLITE_CONSTRAINT ); + if( onError==OE_Abort ){ + sqlite3MayAbort(pParse); + } + sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); +} + +/* +** Check to see if pIndex uses the collating sequence pColl. Return +** true if it does and false if it does not. +*/ +#ifndef SQLITE_OMIT_REINDEX +static int collationMatch(const char *zColl, Index *pIndex){ + int i; + assert( zColl!=0 ); + for(i=0; inColumn; i++){ + const char *z = pIndex->azColl[i]; + assert( z!=0 ); + if( 0==sqlite3StrICmp(z, zColl) ){ + return 1; + } + } + return 0; +} +#endif + +/* +** Recompute all indices of pTab that use the collating sequence pColl. +** If pColl==0 then recompute all indices of pTab. +*/ +#ifndef SQLITE_OMIT_REINDEX +static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ + Index *pIndex; /* An index associated with pTab */ + + for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ + if( zColl==0 || collationMatch(zColl, pIndex) ){ + int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3RefillIndex(pParse, pIndex, -1); + } + } +} +#endif + +/* +** Recompute all indices of all tables in all databases where the +** indices use the collating sequence pColl. If pColl==0 then recompute +** all indices everywhere. +*/ +#ifndef SQLITE_OMIT_REINDEX +static void reindexDatabases(Parse *pParse, char const *zColl){ + Db *pDb; /* A single database */ + int iDb; /* The database index number */ + sqlite3 *db = pParse->db; /* The database connection */ + HashElem *k; /* For looping over tables in pDb */ + Table *pTab; /* A table in the database */ + + assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ + for(iDb=0, pDb=db->aDb; iDbnDb; iDb++, pDb++){ + assert( pDb!=0 ); + for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ + pTab = (Table*)sqliteHashData(k); + reindexTable(pParse, pTab, zColl); + } + } +} +#endif + +/* +** Generate code for the REINDEX command. +** +** REINDEX -- 1 +** REINDEX -- 2 +** REINDEX ?.? -- 3 +** REINDEX ?.? -- 4 +** +** Form 1 causes all indices in all attached databases to be rebuilt. +** Form 2 rebuilds all indices in all databases that use the named +** collating function. Forms 3 and 4 rebuild the named index or all +** indices associated with the named table. +*/ +#ifndef SQLITE_OMIT_REINDEX +SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ + CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ + char *z; /* Name of a table or index */ + const char *zDb; /* Name of the database */ + Table *pTab; /* A table in the database */ + Index *pIndex; /* An index associated with pTab */ + int iDb; /* The database index number */ + sqlite3 *db = pParse->db; /* The database connection */ + Token *pObjName; /* Name of the table or index to be reindexed */ + + /* Read the database schema. If an error occurs, leave an error message + ** and code in pParse and return NULL. */ + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + return; + } + + if( pName1==0 ){ + reindexDatabases(pParse, 0); + return; + }else if( NEVER(pName2==0) || pName2->z==0 ){ + char *zColl; + assert( pName1->z ); + zColl = sqlite3NameFromToken(pParse->db, pName1); + if( !zColl ) return; + pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); + if( pColl ){ + reindexDatabases(pParse, zColl); + sqlite3DbFree(db, zColl); + return; + } + sqlite3DbFree(db, zColl); + } + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); + if( iDb<0 ) return; + z = sqlite3NameFromToken(db, pObjName); + if( z==0 ) return; + zDb = db->aDb[iDb].zName; + pTab = sqlite3FindTable(db, z, zDb); + if( pTab ){ + reindexTable(pParse, pTab, 0); + sqlite3DbFree(db, z); + return; + } + pIndex = sqlite3FindIndex(db, z, zDb); + sqlite3DbFree(db, z); + if( pIndex ){ + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3RefillIndex(pParse, pIndex, -1); + return; + } + sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); +} +#endif + +/* +** Return a dynamicly allocated KeyInfo structure that can be used +** with OP_OpenRead or OP_OpenWrite to access database index pIdx. +** +** If successful, a pointer to the new structure is returned. In this case +** the caller is responsible for calling sqlite3DbFree(db, ) on the returned +** pointer. If an error occurs (out of memory or missing collation +** sequence), NULL is returned and the state of pParse updated to reflect +** the error. +*/ +SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ + int i; + int nCol = pIdx->nColumn; + KeyInfo *pKey; + + pKey = sqlite3KeyInfoAlloc(pParse->db, nCol); + if( pKey ){ + for(i=0; iazColl[i]; + assert( zColl ); + pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl); + pKey->aSortOrder[i] = pIdx->aSortOrder[i]; + } + } + + if( pParse->nErr ){ + sqlite3DbFree(pParse->db, pKey); + pKey = 0; + } + return pKey; +} + +/************** End of build.c ***********************************************/ +/************** Begin file callback.c ****************************************/ +/* +** 2005 May 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains functions used to access the internal hash tables +** of user defined functions and collation sequences. +*/ + + +/* +** Invoke the 'collation needed' callback to request a collation sequence +** in the encoding enc of name zName, length nName. +*/ +static void callCollNeeded(sqlite3 *db, int enc, const char *zName){ + assert( !db->xCollNeeded || !db->xCollNeeded16 ); + if( db->xCollNeeded ){ + char *zExternal = sqlite3DbStrDup(db, zName); + if( !zExternal ) return; + db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal); + sqlite3DbFree(db, zExternal); + } +#ifndef SQLITE_OMIT_UTF16 + if( db->xCollNeeded16 ){ + char const *zExternal; + sqlite3_value *pTmp = sqlite3ValueNew(db); + sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC); + zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE); + if( zExternal ){ + db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal); + } + sqlite3ValueFree(pTmp); + } +#endif +} + +/* +** This routine is called if the collation factory fails to deliver a +** collation function in the best encoding but there may be other versions +** of this collation function (for other text encodings) available. Use one +** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if +** possible. +*/ +static int synthCollSeq(sqlite3 *db, CollSeq *pColl){ + CollSeq *pColl2; + char *z = pColl->zName; + int i; + static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 }; + for(i=0; i<3; i++){ + pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0); + if( pColl2->xCmp!=0 ){ + memcpy(pColl, pColl2, sizeof(CollSeq)); + pColl->xDel = 0; /* Do not copy the destructor */ + return SQLITE_OK; + } + } + return SQLITE_ERROR; +} + +/* +** This function is responsible for invoking the collation factory callback +** or substituting a collation sequence of a different encoding when the +** requested collation sequence is not available in the desired encoding. +** +** If it is not NULL, then pColl must point to the database native encoding +** collation sequence with name zName, length nName. +** +** The return value is either the collation sequence to be used in database +** db for collation type name zName, length nName, or NULL, if no collation +** sequence can be found. If no collation is found, leave an error message. +** +** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq() +*/ +SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq( + Parse *pParse, /* Parsing context */ + u8 enc, /* The desired encoding for the collating sequence */ + CollSeq *pColl, /* Collating sequence with native encoding, or NULL */ + const char *zName /* Collating sequence name */ +){ + CollSeq *p; + sqlite3 *db = pParse->db; + + p = pColl; + if( !p ){ + p = sqlite3FindCollSeq(db, enc, zName, 0); + } + if( !p || !p->xCmp ){ + /* No collation sequence of this type for this encoding is registered. + ** Call the collation factory to see if it can supply us with one. + */ + callCollNeeded(db, enc, zName); + p = sqlite3FindCollSeq(db, enc, zName, 0); + } + if( p && !p->xCmp && synthCollSeq(db, p) ){ + p = 0; + } + assert( !p || p->xCmp ); + if( p==0 ){ + sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName); + } + return p; +} + +/* +** This routine is called on a collation sequence before it is used to +** check that it is defined. An undefined collation sequence exists when +** a database is loaded that contains references to collation sequences +** that have not been defined by sqlite3_create_collation() etc. +** +** If required, this routine calls the 'collation needed' callback to +** request a definition of the collating sequence. If this doesn't work, +** an equivalent collating sequence that uses a text encoding different +** from the main database is substituted, if one is available. +*/ +SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){ + if( pColl ){ + const char *zName = pColl->zName; + sqlite3 *db = pParse->db; + CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName); + if( !p ){ + return SQLITE_ERROR; + } + assert( p==pColl ); + } + return SQLITE_OK; +} + + + +/* +** Locate and return an entry from the db.aCollSeq hash table. If the entry +** specified by zName and nName is not found and parameter 'create' is +** true, then create a new entry. Otherwise return NULL. +** +** Each pointer stored in the sqlite3.aCollSeq hash table contains an +** array of three CollSeq structures. The first is the collation sequence +** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be. +** +** Stored immediately after the three collation sequences is a copy of +** the collation sequence name. A pointer to this string is stored in +** each collation sequence structure. +*/ +static CollSeq *findCollSeqEntry( + sqlite3 *db, /* Database connection */ + const char *zName, /* Name of the collating sequence */ + int create /* Create a new entry if true */ +){ + CollSeq *pColl; + int nName = sqlite3Strlen30(zName); + pColl = sqlite3HashFind(&db->aCollSeq, zName, nName); + + if( 0==pColl && create ){ + pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 ); + if( pColl ){ + CollSeq *pDel = 0; + pColl[0].zName = (char*)&pColl[3]; + pColl[0].enc = SQLITE_UTF8; + pColl[1].zName = (char*)&pColl[3]; + pColl[1].enc = SQLITE_UTF16LE; + pColl[2].zName = (char*)&pColl[3]; + pColl[2].enc = SQLITE_UTF16BE; + memcpy(pColl[0].zName, zName, nName); + pColl[0].zName[nName] = 0; + pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl); + + /* If a malloc() failure occurred in sqlite3HashInsert(), it will + ** return the pColl pointer to be deleted (because it wasn't added + ** to the hash table). + */ + assert( pDel==0 || pDel==pColl ); + if( pDel!=0 ){ + db->mallocFailed = 1; + sqlite3DbFree(db, pDel); + pColl = 0; + } + } + } + return pColl; +} + +/* +** Parameter zName points to a UTF-8 encoded string nName bytes long. +** Return the CollSeq* pointer for the collation sequence named zName +** for the encoding 'enc' from the database 'db'. +** +** If the entry specified is not found and 'create' is true, then create a +** new entry. Otherwise return NULL. +** +** A separate function sqlite3LocateCollSeq() is a wrapper around +** this routine. sqlite3LocateCollSeq() invokes the collation factory +** if necessary and generates an error message if the collating sequence +** cannot be found. +** +** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq() +*/ +SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq( + sqlite3 *db, + u8 enc, + const char *zName, + int create +){ + CollSeq *pColl; + if( zName ){ + pColl = findCollSeqEntry(db, zName, create); + }else{ + pColl = db->pDfltColl; + } + assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); + assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE ); + if( pColl ) pColl += enc-1; + return pColl; +} + +/* During the search for the best function definition, this procedure +** is called to test how well the function passed as the first argument +** matches the request for a function with nArg arguments in a system +** that uses encoding enc. The value returned indicates how well the +** request is matched. A higher value indicates a better match. +** +** If nArg is -1 that means to only return a match (non-zero) if p->nArg +** is also -1. In other words, we are searching for a function that +** takes a variable number of arguments. +** +** If nArg is -2 that means that we are searching for any function +** regardless of the number of arguments it uses, so return a positive +** match score for any +** +** The returned value is always between 0 and 6, as follows: +** +** 0: Not a match. +** 1: UTF8/16 conversion required and function takes any number of arguments. +** 2: UTF16 byte order change required and function takes any number of args. +** 3: encoding matches and function takes any number of arguments +** 4: UTF8/16 conversion required - argument count matches exactly +** 5: UTF16 byte order conversion required - argument count matches exactly +** 6: Perfect match: encoding and argument count match exactly. +** +** If nArg==(-2) then any function with a non-null xStep or xFunc is +** a perfect match and any function with both xStep and xFunc NULL is +** a non-match. +*/ +#define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */ +static int matchQuality( + FuncDef *p, /* The function we are evaluating for match quality */ + int nArg, /* Desired number of arguments. (-1)==any */ + u8 enc /* Desired text encoding */ +){ + int match; + + /* nArg of -2 is a special case */ + if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH; + + /* Wrong number of arguments means "no match" */ + if( p->nArg!=nArg && p->nArg>=0 ) return 0; + + /* Give a better score to a function with a specific number of arguments + ** than to function that accepts any number of arguments. */ + if( p->nArg==nArg ){ + match = 4; + }else{ + match = 1; + } + + /* Bonus points if the text encoding matches */ + if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){ + match += 2; /* Exact encoding match */ + }else if( (enc & p->funcFlags & 2)!=0 ){ + match += 1; /* Both are UTF16, but with different byte orders */ + } + + return match; +} + +/* +** Search a FuncDefHash for a function with the given name. Return +** a pointer to the matching FuncDef if found, or 0 if there is no match. +*/ +static FuncDef *functionSearch( + FuncDefHash *pHash, /* Hash table to search */ + int h, /* Hash of the name */ + const char *zFunc, /* Name of function */ + int nFunc /* Number of bytes in zFunc */ +){ + FuncDef *p; + for(p=pHash->a[h]; p; p=p->pHash){ + if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){ + return p; + } + } + return 0; +} + +/* +** Insert a new FuncDef into a FuncDefHash hash table. +*/ +SQLITE_PRIVATE void sqlite3FuncDefInsert( + FuncDefHash *pHash, /* The hash table into which to insert */ + FuncDef *pDef /* The function definition to insert */ +){ + FuncDef *pOther; + int nName = sqlite3Strlen30(pDef->zName); + u8 c1 = (u8)pDef->zName[0]; + int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a); + pOther = functionSearch(pHash, h, pDef->zName, nName); + if( pOther ){ + assert( pOther!=pDef && pOther->pNext!=pDef ); + pDef->pNext = pOther->pNext; + pOther->pNext = pDef; + }else{ + pDef->pNext = 0; + pDef->pHash = pHash->a[h]; + pHash->a[h] = pDef; + } +} + + + +/* +** Locate a user function given a name, a number of arguments and a flag +** indicating whether the function prefers UTF-16 over UTF-8. Return a +** pointer to the FuncDef structure that defines that function, or return +** NULL if the function does not exist. +** +** If the createFlag argument is true, then a new (blank) FuncDef +** structure is created and liked into the "db" structure if a +** no matching function previously existed. +** +** If nArg is -2, then the first valid function found is returned. A +** function is valid if either xFunc or xStep is non-zero. The nArg==(-2) +** case is used to see if zName is a valid function name for some number +** of arguments. If nArg is -2, then createFlag must be 0. +** +** If createFlag is false, then a function with the required name and +** number of arguments may be returned even if the eTextRep flag does not +** match that requested. +*/ +SQLITE_PRIVATE FuncDef *sqlite3FindFunction( + sqlite3 *db, /* An open database */ + const char *zName, /* Name of the function. Not null-terminated */ + int nName, /* Number of characters in the name */ + int nArg, /* Number of arguments. -1 means any number */ + u8 enc, /* Preferred text encoding */ + u8 createFlag /* Create new entry if true and does not otherwise exist */ +){ + FuncDef *p; /* Iterator variable */ + FuncDef *pBest = 0; /* Best match found so far */ + int bestScore = 0; /* Score of best match */ + int h; /* Hash value */ + + assert( nArg>=(-2) ); + assert( nArg>=(-1) || createFlag==0 ); + assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); + h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a); + + /* First search for a match amongst the application-defined functions. + */ + p = functionSearch(&db->aFunc, h, zName, nName); + while( p ){ + int score = matchQuality(p, nArg, enc); + if( score>bestScore ){ + pBest = p; + bestScore = score; + } + p = p->pNext; + } + + /* If no match is found, search the built-in functions. + ** + ** If the SQLITE_PreferBuiltin flag is set, then search the built-in + ** functions even if a prior app-defined function was found. And give + ** priority to built-in functions. + ** + ** Except, if createFlag is true, that means that we are trying to + ** install a new function. Whatever FuncDef structure is returned it will + ** have fields overwritten with new information appropriate for the + ** new function. But the FuncDefs for built-in functions are read-only. + ** So we must not search for built-ins when creating a new function. + */ + if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){ + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + bestScore = 0; + p = functionSearch(pHash, h, zName, nName); + while( p ){ + int score = matchQuality(p, nArg, enc); + if( score>bestScore ){ + pBest = p; + bestScore = score; + } + p = p->pNext; + } + } + + /* If the createFlag parameter is true and the search did not reveal an + ** exact match for the name, number of arguments and encoding, then add a + ** new entry to the hash table and return it. + */ + if( createFlag && bestScorezName = (char *)&pBest[1]; + pBest->nArg = (u16)nArg; + pBest->funcFlags = enc; + memcpy(pBest->zName, zName, nName); + pBest->zName[nName] = 0; + sqlite3FuncDefInsert(&db->aFunc, pBest); + } + + if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){ + return pBest; + } + return 0; +} + +/* +** Free all resources held by the schema structure. The void* argument points +** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the +** pointer itself, it just cleans up subsidiary resources (i.e. the contents +** of the schema hash tables). +** +** The Schema.cache_size variable is not cleared. +*/ +SQLITE_PRIVATE void sqlite3SchemaClear(void *p){ + Hash temp1; + Hash temp2; + HashElem *pElem; + Schema *pSchema = (Schema *)p; + + temp1 = pSchema->tblHash; + temp2 = pSchema->trigHash; + sqlite3HashInit(&pSchema->trigHash); + sqlite3HashClear(&pSchema->idxHash); + for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){ + sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem)); + } + sqlite3HashClear(&temp2); + sqlite3HashInit(&pSchema->tblHash); + for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){ + Table *pTab = sqliteHashData(pElem); + sqlite3DeleteTable(0, pTab); + } + sqlite3HashClear(&temp1); + sqlite3HashClear(&pSchema->fkeyHash); + pSchema->pSeqTab = 0; + if( pSchema->flags & DB_SchemaLoaded ){ + pSchema->iGeneration++; + pSchema->flags &= ~DB_SchemaLoaded; + } +} + +/* +** Find and return the schema associated with a BTree. Create +** a new one if necessary. +*/ +SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){ + Schema * p; + if( pBt ){ + p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear); + }else{ + p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema)); + } + if( !p ){ + db->mallocFailed = 1; + }else if ( 0==p->file_format ){ + sqlite3HashInit(&p->tblHash); + sqlite3HashInit(&p->idxHash); + sqlite3HashInit(&p->trigHash); + sqlite3HashInit(&p->fkeyHash); + p->enc = SQLITE_UTF8; + } + return p; +} + +/************** End of callback.c ********************************************/ +/************** Begin file delete.c ******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that are called by the parser +** in order to generate code for DELETE FROM statements. +*/ + +/* +** While a SrcList can in general represent multiple tables and subqueries +** (as in the FROM clause of a SELECT statement) in this case it contains +** the name of a single table, as one might find in an INSERT, DELETE, +** or UPDATE statement. Look up that table in the symbol table and +** return a pointer. Set an error message and return NULL if the table +** name is not found or if any other error occurs. +** +** The following fields are initialized appropriate in pSrc: +** +** pSrc->a[0].pTab Pointer to the Table object +** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one +** +*/ +SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ + struct SrcList_item *pItem = pSrc->a; + Table *pTab; + assert( pItem && pSrc->nSrc==1 ); + pTab = sqlite3LocateTableItem(pParse, 0, pItem); + sqlite3DeleteTable(pParse->db, pItem->pTab); + pItem->pTab = pTab; + if( pTab ){ + pTab->nRef++; + } + if( sqlite3IndexedByLookup(pParse, pItem) ){ + pTab = 0; + } + return pTab; +} + +/* +** Check to make sure the given table is writable. If it is not +** writable, generate an error message and return 1. If it is +** writable return 0; +*/ +SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ + /* A table is not writable under the following circumstances: + ** + ** 1) It is a virtual table and no implementation of the xUpdate method + ** has been provided, or + ** 2) It is a system table (i.e. sqlite_master), this call is not + ** part of a nested parse and writable_schema pragma has not + ** been specified. + ** + ** In either case leave an error message in pParse and return non-zero. + */ + if( ( IsVirtual(pTab) + && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ) + || ( (pTab->tabFlags & TF_Readonly)!=0 + && (pParse->db->flags & SQLITE_WriteSchema)==0 + && pParse->nested==0 ) + ){ + sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); + return 1; + } + +#ifndef SQLITE_OMIT_VIEW + if( !viewOk && pTab->pSelect ){ + sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName); + return 1; + } +#endif + return 0; +} + + +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) +/* +** Evaluate a view and store its result in an ephemeral table. The +** pWhere argument is an optional WHERE clause that restricts the +** set of rows in the view that are to be added to the ephemeral table. +*/ +SQLITE_PRIVATE void sqlite3MaterializeView( + Parse *pParse, /* Parsing context */ + Table *pView, /* View definition */ + Expr *pWhere, /* Optional WHERE clause to be added */ + int iCur /* Cursor number for ephemerial table */ +){ + SelectDest dest; + Select *pSel; + SrcList *pFrom; + sqlite3 *db = pParse->db; + int iDb = sqlite3SchemaToIndex(db, pView->pSchema); + + pWhere = sqlite3ExprDup(db, pWhere, 0); + pFrom = sqlite3SrcListAppend(db, 0, 0, 0); + + if( pFrom ){ + assert( pFrom->nSrc==1 ); + pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName); + pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName); + assert( pFrom->a[0].pOn==0 ); + assert( pFrom->a[0].pUsing==0 ); + } + + pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0); + if( pSel ) pSel->selFlags |= SF_Materialize; + + sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); + sqlite3Select(pParse, pSel, &dest); + sqlite3SelectDelete(db, pSel); +} +#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */ + +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) +/* +** Generate an expression tree to implement the WHERE, ORDER BY, +** and LIMIT/OFFSET portion of DELETE and UPDATE statements. +** +** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1; +** \__________________________/ +** pLimitWhere (pInClause) +*/ +SQLITE_PRIVATE Expr *sqlite3LimitWhere( + Parse *pParse, /* The parser context */ + SrcList *pSrc, /* the FROM clause -- which tables to scan */ + Expr *pWhere, /* The WHERE clause. May be null */ + ExprList *pOrderBy, /* The ORDER BY clause. May be null */ + Expr *pLimit, /* The LIMIT clause. May be null */ + Expr *pOffset, /* The OFFSET clause. May be null */ + char *zStmtType /* Either DELETE or UPDATE. For error messages. */ +){ + Expr *pWhereRowid = NULL; /* WHERE rowid .. */ + Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */ + Expr *pSelectRowid = NULL; /* SELECT rowid ... */ + ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */ + SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */ + Select *pSelect = NULL; /* Complete SELECT tree */ + + /* Check that there isn't an ORDER BY without a LIMIT clause. + */ + if( pOrderBy && (pLimit == 0) ) { + sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); + goto limit_where_cleanup_2; + } + + /* We only need to generate a select expression if there + ** is a limit/offset term to enforce. + */ + if( pLimit == 0 ) { + /* if pLimit is null, pOffset will always be null as well. */ + assert( pOffset == 0 ); + return pWhere; + } + + /* Generate a select expression tree to enforce the limit/offset + ** term for the DELETE or UPDATE statement. For example: + ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 + ** becomes: + ** DELETE FROM table_a WHERE rowid IN ( + ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 + ** ); + */ + + pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0); + if( pSelectRowid == 0 ) goto limit_where_cleanup_2; + pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid); + if( pEList == 0 ) goto limit_where_cleanup_2; + + /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree + ** and the SELECT subtree. */ + pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0); + if( pSelectSrc == 0 ) { + sqlite3ExprListDelete(pParse->db, pEList); + goto limit_where_cleanup_2; + } + + /* generate the SELECT expression tree. */ + pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0, + pOrderBy,0,pLimit,pOffset); + if( pSelect == 0 ) return 0; + + /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ + pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0); + if( pWhereRowid == 0 ) goto limit_where_cleanup_1; + pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0); + if( pInClause == 0 ) goto limit_where_cleanup_1; + + pInClause->x.pSelect = pSelect; + pInClause->flags |= EP_xIsSelect; + sqlite3ExprSetHeight(pParse, pInClause); + return pInClause; + + /* something went wrong. clean up anything allocated. */ +limit_where_cleanup_1: + sqlite3SelectDelete(pParse->db, pSelect); + return 0; + +limit_where_cleanup_2: + sqlite3ExprDelete(pParse->db, pWhere); + sqlite3ExprListDelete(pParse->db, pOrderBy); + sqlite3ExprDelete(pParse->db, pLimit); + sqlite3ExprDelete(pParse->db, pOffset); + return 0; +} +#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ + +/* +** Generate code for a DELETE FROM statement. +** +** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; +** \________/ \________________/ +** pTabList pWhere +*/ +SQLITE_PRIVATE void sqlite3DeleteFrom( + Parse *pParse, /* The parser context */ + SrcList *pTabList, /* The table from which we should delete things */ + Expr *pWhere /* The WHERE clause. May be null */ +){ + Vdbe *v; /* The virtual database engine */ + Table *pTab; /* The table from which records will be deleted */ + const char *zDb; /* Name of database holding pTab */ + int end, addr = 0; /* A couple addresses of generated code */ + int i; /* Loop counter */ + WhereInfo *pWInfo; /* Information about the WHERE clause */ + Index *pIdx; /* For looping over indices of the table */ + int iCur; /* VDBE Cursor number for pTab */ + sqlite3 *db; /* Main database structure */ + AuthContext sContext; /* Authorization context */ + NameContext sNC; /* Name context to resolve expressions in */ + int iDb; /* Database number */ + int memCnt = -1; /* Memory cell used for change counting */ + int rcauth; /* Value returned by authorization callback */ + +#ifndef SQLITE_OMIT_TRIGGER + int isView; /* True if attempting to delete from a view */ + Trigger *pTrigger; /* List of table triggers, if required */ +#endif + + memset(&sContext, 0, sizeof(sContext)); + db = pParse->db; + if( pParse->nErr || db->mallocFailed ){ + goto delete_from_cleanup; + } + assert( pTabList->nSrc==1 ); + + /* Locate the table which we want to delete. This table has to be + ** put in an SrcList structure because some of the subroutines we + ** will be calling are designed to work with multiple tables and expect + ** an SrcList* parameter instead of just a Table* parameter. + */ + pTab = sqlite3SrcListLookup(pParse, pTabList); + if( pTab==0 ) goto delete_from_cleanup; + + /* Figure out if we have any triggers and if the table being + ** deleted from is a view + */ +#ifndef SQLITE_OMIT_TRIGGER + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); + isView = pTab->pSelect!=0; +#else +# define pTrigger 0 +# define isView 0 +#endif +#ifdef SQLITE_OMIT_VIEW +# undef isView +# define isView 0 +#endif + + /* If pTab is really a view, make sure it has been initialized. + */ + if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto delete_from_cleanup; + } + + if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){ + goto delete_from_cleanup; + } + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( iDbnDb ); + zDb = db->aDb[iDb].zName; + rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb); + assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE ); + if( rcauth==SQLITE_DENY ){ + goto delete_from_cleanup; + } + assert(!isView || pTrigger); + + /* Assign cursor number to the table and all its indices. + */ + assert( pTabList->nSrc==1 ); + iCur = pTabList->a[0].iCursor = pParse->nTab++; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + pParse->nTab++; + } + + /* Start the view context + */ + if( isView ){ + sqlite3AuthContextPush(pParse, &sContext, pTab->zName); + } + + /* Begin generating code. + */ + v = sqlite3GetVdbe(pParse); + if( v==0 ){ + goto delete_from_cleanup; + } + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); + sqlite3BeginWriteOperation(pParse, 1, iDb); + + /* If we are trying to delete from a view, realize that view into + ** a ephemeral table. + */ +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) + if( isView ){ + sqlite3MaterializeView(pParse, pTab, pWhere, iCur); + } +#endif + + /* Resolve the column names in the WHERE clause. + */ + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + if( sqlite3ResolveExprNames(&sNC, pWhere) ){ + goto delete_from_cleanup; + } + + /* Initialize the counter of the number of rows deleted, if + ** we are counting rows. + */ + if( db->flags & SQLITE_CountRows ){ + memCnt = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); + } + +#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION + /* Special case: A DELETE without a WHERE clause deletes everything. + ** It is easier just to erase the whole table. Prior to version 3.6.5, + ** this optimization caused the row change count (the value returned by + ** API function sqlite3_count_changes) to be set incorrectly. */ + if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) + && 0==sqlite3FkRequired(pParse, pTab, 0, 0) + ){ + assert( !isView ); + sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); + sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt, + pTab->zName, P4_STATIC); + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + assert( pIdx->pSchema==pTab->pSchema ); + sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); + } + }else +#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ + /* The usual case: There is a WHERE clause so we have to scan through + ** the table and pick which records to delete. + */ + { + int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */ + int iRowid = ++pParse->nMem; /* Used for storing rowid values. */ + int regRowid; /* Actual register containing rowids */ + + /* Collect rowids of every row to be deleted. + */ + sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); + pWInfo = sqlite3WhereBegin( + pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0 + ); + if( pWInfo==0 ) goto delete_from_cleanup; + regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0); + sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid); + if( db->flags & SQLITE_CountRows ){ + sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); + } + sqlite3WhereEnd(pWInfo); + + /* Delete every item whose key was written to the list during the + ** database scan. We have to delete items after the scan is complete + ** because deleting an item can change the scan order. */ + end = sqlite3VdbeMakeLabel(v); + + /* Unless this is a view, open cursors for the table we are + ** deleting from and all its indices. If this is a view, then the + ** only effect this statement has is to fire the INSTEAD OF + ** triggers. */ + if( !isView ){ + sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite); + } + + addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid); + + /* Delete the row */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); + sqlite3VtabMakeWritable(pParse, pTab); + sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB); + sqlite3VdbeChangeP5(v, OE_Abort); + sqlite3MayAbort(pParse); + }else +#endif + { + int count = (pParse->nested==0); /* True to count changes */ + sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default); + } + + /* End of the delete loop */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); + sqlite3VdbeResolveLabel(v, end); + + /* Close the cursors open on the table and its indexes. */ + if( !isView && !IsVirtual(pTab) ){ + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ + sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum); + } + sqlite3VdbeAddOp1(v, OP_Close, iCur); + } + } + + /* Update the sqlite_sequence table by storing the content of the + ** maximum rowid counter values recorded while inserting into + ** autoincrement tables. + */ + if( pParse->nested==0 && pParse->pTriggerTab==0 ){ + sqlite3AutoincrementEnd(pParse); + } + + /* Return the number of rows that were deleted. If this routine is + ** generating code because of a call to sqlite3NestedParse(), do not + ** invoke the callback function. + */ + if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ + sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); + } + +delete_from_cleanup: + sqlite3AuthContextPop(&sContext); + sqlite3SrcListDelete(db, pTabList); + sqlite3ExprDelete(db, pWhere); + return; +} +/* Make sure "isView" and other macros defined above are undefined. Otherwise +** thely may interfere with compilation of other functions in this file +** (or in another file, if this file becomes part of the amalgamation). */ +#ifdef isView + #undef isView +#endif +#ifdef pTrigger + #undef pTrigger +#endif + +/* +** This routine generates VDBE code that causes a single row of a +** single table to be deleted. +** +** The VDBE must be in a particular state when this routine is called. +** These are the requirements: +** +** 1. A read/write cursor pointing to pTab, the table containing the row +** to be deleted, must be opened as cursor number $iCur. +** +** 2. Read/write cursors for all indices of pTab must be open as +** cursor number base+i for the i-th index. +** +** 3. The record number of the row to be deleted must be stored in +** memory cell iRowid. +** +** This routine generates code to remove both the table record and all +** index entries that point to that record. +*/ +SQLITE_PRIVATE void sqlite3GenerateRowDelete( + Parse *pParse, /* Parsing context */ + Table *pTab, /* Table containing the row to be deleted */ + int iCur, /* Cursor number for the table */ + int iRowid, /* Memory cell that contains the rowid to delete */ + int count, /* If non-zero, increment the row change counter */ + Trigger *pTrigger, /* List of triggers to (potentially) fire */ + int onconf /* Default ON CONFLICT policy for triggers */ +){ + Vdbe *v = pParse->pVdbe; /* Vdbe */ + int iOld = 0; /* First register in OLD.* array */ + int iLabel; /* Label resolved to end of generated code */ + + /* Vdbe is guaranteed to have been allocated by this stage. */ + assert( v ); + + /* Seek cursor iCur to the row to delete. If this row no longer exists + ** (this can happen if a trigger program has already deleted it), do + ** not attempt to delete it or fire any DELETE triggers. */ + iLabel = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid); + + /* If there are any triggers to fire, allocate a range of registers to + ** use for the old.* references in the triggers. */ + if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){ + u32 mask; /* Mask of OLD.* columns in use */ + int iCol; /* Iterator used while populating OLD.* */ + + /* TODO: Could use temporary registers here. Also could attempt to + ** avoid copying the contents of the rowid register. */ + mask = sqlite3TriggerColmask( + pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf + ); + mask |= sqlite3FkOldmask(pParse, pTab); + iOld = pParse->nMem+1; + pParse->nMem += (1 + pTab->nCol); + + /* Populate the OLD.* pseudo-table register array. These values will be + ** used by any BEFORE and AFTER triggers that exist. */ + sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld); + for(iCol=0; iColnCol; iCol++){ + if( mask==0xffffffff || mask&(1<pSelect==0 ){ + sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0); + sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0)); + if( count ){ + sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); + } + } + + /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to + ** handle rows (possibly in other tables) that refer via a foreign key + ** to the row just deleted. */ + sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0); + + /* Invoke AFTER DELETE trigger programs. */ + sqlite3CodeRowTrigger(pParse, pTrigger, + TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel + ); + + /* Jump here if the row had already been deleted before any BEFORE + ** trigger programs were invoked. Or if a trigger program throws a + ** RAISE(IGNORE) exception. */ + sqlite3VdbeResolveLabel(v, iLabel); +} + +/* +** This routine generates VDBE code that causes the deletion of all +** index entries associated with a single row of a single table. +** +** The VDBE must be in a particular state when this routine is called. +** These are the requirements: +** +** 1. A read/write cursor pointing to pTab, the table containing the row +** to be deleted, must be opened as cursor number "iCur". +** +** 2. Read/write cursors for all indices of pTab must be open as +** cursor number iCur+i for the i-th index. +** +** 3. The "iCur" cursor must be pointing to the row that is to be +** deleted. +*/ +SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( + Parse *pParse, /* Parsing and code generating context */ + Table *pTab, /* Table containing the row to be deleted */ + int iCur, /* Cursor number for the table */ + int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ +){ + int i; + Index *pIdx; + int r1; + int iPartIdxLabel; + Vdbe *v = pParse->pVdbe; + + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ + if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue; + r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel); + sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1); + sqlite3VdbeResolveLabel(v, iPartIdxLabel); + } +} + +/* +** Generate code that will assemble an index key and put it in register +** regOut. The key with be for index pIdx which is an index on pTab. +** iCur is the index of a cursor open on the pTab table and pointing to +** the entry that needs indexing. +** +** Return a register number which is the first in a block of +** registers that holds the elements of the index key. The +** block of registers has already been deallocated by the time +** this routine returns. +** +** If *piPartIdxLabel is not NULL, fill it in with a label and jump +** to that label if pIdx is a partial index that should be skipped. +** A partial index should be skipped if its WHERE clause evaluates +** to false or null. If pIdx is not a partial index, *piPartIdxLabel +** will be set to zero which is an empty label that is ignored by +** sqlite3VdbeResolveLabel(). +*/ +SQLITE_PRIVATE int sqlite3GenerateIndexKey( + Parse *pParse, /* Parsing context */ + Index *pIdx, /* The index for which to generate a key */ + int iCur, /* Cursor number for the pIdx->pTable table */ + int regOut, /* Write the new index key to this register */ + int doMakeRec, /* Run the OP_MakeRecord instruction if true */ + int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */ +){ + Vdbe *v = pParse->pVdbe; + int j; + Table *pTab = pIdx->pTable; + int regBase; + int nCol; + + if( piPartIdxLabel ){ + if( pIdx->pPartIdxWhere ){ + *piPartIdxLabel = sqlite3VdbeMakeLabel(v); + pParse->iPartIdxTab = iCur; + sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, + SQLITE_JUMPIFNULL); + }else{ + *piPartIdxLabel = 0; + } + } + nCol = pIdx->nColumn; + regBase = sqlite3GetTempRange(pParse, nCol+1); + sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol); + for(j=0; jaiColumn[j]; + if( idx==pTab->iPKey ){ + sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j); + }else{ + sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j); + sqlite3ColumnDefault(v, pTab, idx, -1); + } + } + if( doMakeRec ){ + const char *zAff; + if( pTab->pSelect + || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt) + ){ + zAff = 0; + }else{ + zAff = sqlite3IndexAffinityStr(v, pIdx); + } + sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut); + sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT); + } + sqlite3ReleaseTempRange(pParse, regBase, nCol+1); + return regBase; +} + +/************** End of delete.c **********************************************/ +/************** Begin file func.c ********************************************/ +/* +** 2002 February 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement various SQL +** functions of SQLite. +** +** There is only one exported symbol in this file - the function +** sqliteRegisterBuildinFunctions() found at the bottom of the file. +** All other code has file scope. +*/ +/* #include */ +/* #include */ + +/* +** Return the collating function associated with a function. +*/ +static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ + return context->pColl; +} + +/* +** Indicate that the accumulator load should be skipped on this +** iteration of the aggregate loop. +*/ +static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ + context->skipFlag = 1; +} + +/* +** Implementation of the non-aggregate min() and max() functions +*/ +static void minmaxFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int i; + int mask; /* 0 for min() or 0xffffffff for max() */ + int iBest; + CollSeq *pColl; + + assert( argc>1 ); + mask = sqlite3_user_data(context)==0 ? 0 : -1; + pColl = sqlite3GetFuncCollSeq(context); + assert( pColl ); + assert( mask==-1 || mask==0 ); + iBest = 0; + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; + for(i=1; i=0 ){ + testcase( mask==0 ); + iBest = i; + } + } + sqlite3_result_value(context, argv[iBest]); +} + +/* +** Return the type of the argument. +*/ +static void typeofFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + const char *z = 0; + UNUSED_PARAMETER(NotUsed); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_INTEGER: z = "integer"; break; + case SQLITE_TEXT: z = "text"; break; + case SQLITE_FLOAT: z = "real"; break; + case SQLITE_BLOB: z = "blob"; break; + default: z = "null"; break; + } + sqlite3_result_text(context, z, -1, SQLITE_STATIC); +} + + +/* +** Implementation of the length() function +*/ +static void lengthFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int len; + + assert( argc==1 ); + UNUSED_PARAMETER(argc); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_BLOB: + case SQLITE_INTEGER: + case SQLITE_FLOAT: { + sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); + break; + } + case SQLITE_TEXT: { + const unsigned char *z = sqlite3_value_text(argv[0]); + if( z==0 ) return; + len = 0; + while( *z ){ + len++; + SQLITE_SKIP_UTF8(z); + } + sqlite3_result_int(context, len); + break; + } + default: { + sqlite3_result_null(context); + break; + } + } +} + +/* +** Implementation of the abs() function. +** +** IMP: R-23979-26855 The abs(X) function returns the absolute value of +** the numeric argument X. +*/ +static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + assert( argc==1 ); + UNUSED_PARAMETER(argc); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_INTEGER: { + i64 iVal = sqlite3_value_int64(argv[0]); + if( iVal<0 ){ + if( (iVal<<1)==0 ){ + /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then + ** abs(X) throws an integer overflow error since there is no + ** equivalent positive 64-bit two complement value. */ + sqlite3_result_error(context, "integer overflow", -1); + return; + } + iVal = -iVal; + } + sqlite3_result_int64(context, iVal); + break; + } + case SQLITE_NULL: { + /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ + sqlite3_result_null(context); + break; + } + default: { + /* Because sqlite3_value_double() returns 0.0 if the argument is not + ** something that can be converted into a number, we have: + ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that + ** cannot be converted to a numeric value. + */ + double rVal = sqlite3_value_double(argv[0]); + if( rVal<0 ) rVal = -rVal; + sqlite3_result_double(context, rVal); + break; + } + } +} + +/* +** Implementation of the instr() function. +** +** instr(haystack,needle) finds the first occurrence of needle +** in haystack and returns the number of previous characters plus 1, +** or 0 if needle does not occur within haystack. +** +** If both haystack and needle are BLOBs, then the result is one more than +** the number of bytes in haystack prior to the first occurrence of needle, +** or 0 if needle never occurs in haystack. +*/ +static void instrFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zHaystack; + const unsigned char *zNeedle; + int nHaystack; + int nNeedle; + int typeHaystack, typeNeedle; + int N = 1; + int isText; + + UNUSED_PARAMETER(argc); + typeHaystack = sqlite3_value_type(argv[0]); + typeNeedle = sqlite3_value_type(argv[1]); + if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; + nHaystack = sqlite3_value_bytes(argv[0]); + nNeedle = sqlite3_value_bytes(argv[1]); + if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ + zHaystack = sqlite3_value_blob(argv[0]); + zNeedle = sqlite3_value_blob(argv[1]); + isText = 0; + }else{ + zHaystack = sqlite3_value_text(argv[0]); + zNeedle = sqlite3_value_text(argv[1]); + isText = 1; + } + while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){ + N++; + do{ + nHaystack--; + zHaystack++; + }while( isText && (zHaystack[0]&0xc0)==0x80 ); + } + if( nNeedle>nHaystack ) N = 0; + sqlite3_result_int(context, N); +} + +/* +** Implementation of the substr() function. +** +** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. +** p1 is 1-indexed. So substr(x,1,1) returns the first character +** of x. If x is text, then we actually count UTF-8 characters. +** If x is a blob, then we count bytes. +** +** If p1 is negative, then we begin abs(p1) from the end of x[]. +** +** If p2 is negative, return the p2 characters preceding p1. +*/ +static void substrFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *z; + const unsigned char *z2; + int len; + int p0type; + i64 p1, p2; + int negP2 = 0; + + assert( argc==3 || argc==2 ); + if( sqlite3_value_type(argv[1])==SQLITE_NULL + || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) + ){ + return; + } + p0type = sqlite3_value_type(argv[0]); + p1 = sqlite3_value_int(argv[1]); + if( p0type==SQLITE_BLOB ){ + len = sqlite3_value_bytes(argv[0]); + z = sqlite3_value_blob(argv[0]); + if( z==0 ) return; + assert( len==sqlite3_value_bytes(argv[0]) ); + }else{ + z = sqlite3_value_text(argv[0]); + if( z==0 ) return; + len = 0; + if( p1<0 ){ + for(z2=z; *z2; len++){ + SQLITE_SKIP_UTF8(z2); + } + } + } + if( argc==3 ){ + p2 = sqlite3_value_int(argv[2]); + if( p2<0 ){ + p2 = -p2; + negP2 = 1; + } + }else{ + p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; + } + if( p1<0 ){ + p1 += len; + if( p1<0 ){ + p2 += p1; + if( p2<0 ) p2 = 0; + p1 = 0; + } + }else if( p1>0 ){ + p1--; + }else if( p2>0 ){ + p2--; + } + if( negP2 ){ + p1 -= p2; + if( p1<0 ){ + p2 += p1; + p1 = 0; + } + } + assert( p1>=0 && p2>=0 ); + if( p0type!=SQLITE_BLOB ){ + while( *z && p1 ){ + SQLITE_SKIP_UTF8(z); + p1--; + } + for(z2=z; *z2 && p2; p2--){ + SQLITE_SKIP_UTF8(z2); + } + sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT); + }else{ + if( p1+p2>len ){ + p2 = len-p1; + if( p2<0 ) p2 = 0; + } + sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT); + } +} + +/* +** Implementation of the round() function +*/ +#ifndef SQLITE_OMIT_FLOATING_POINT +static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + int n = 0; + double r; + char *zBuf; + assert( argc==1 || argc==2 ); + if( argc==2 ){ + if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; + n = sqlite3_value_int(argv[1]); + if( n>30 ) n = 30; + if( n<0 ) n = 0; + } + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; + r = sqlite3_value_double(argv[0]); + /* If Y==0 and X will fit in a 64-bit int, + ** handle the rounding directly, + ** otherwise use printf. + */ + if( n==0 && r>=0 && r0 ); + testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); + testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); + if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + sqlite3_result_error_toobig(context); + z = 0; + }else{ + z = sqlite3Malloc((int)nByte); + if( !z ){ + sqlite3_result_error_nomem(context); + } + } + return z; +} + +/* +** Implementation of the upper() and lower() SQL functions. +*/ +static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + char *z1; + const char *z2; + int i, n; + UNUSED_PARAMETER(argc); + z2 = (char*)sqlite3_value_text(argv[0]); + n = sqlite3_value_bytes(argv[0]); + /* Verify that the call to _bytes() does not invalidate the _text() pointer */ + assert( z2==(char*)sqlite3_value_text(argv[0]) ); + if( z2 ){ + z1 = contextMalloc(context, ((i64)n)+1); + if( z1 ){ + for(i=0; imatchOne; + u8 matchAll = pInfo->matchAll; + u8 matchSet = pInfo->matchSet; + u8 noCase = pInfo->noCase; + int prevEscape = 0; /* True if the previous character was 'escape' */ + + while( (c = sqlite3Utf8Read(&zPattern))!=0 ){ + if( c==matchAll && !prevEscape ){ + while( (c=sqlite3Utf8Read(&zPattern)) == matchAll + || c == matchOne ){ + if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ + return 0; + } + } + if( c==0 ){ + return 1; + }else if( c==esc ){ + c = sqlite3Utf8Read(&zPattern); + if( c==0 ){ + return 0; + } + }else if( c==matchSet ){ + assert( esc==0 ); /* This is GLOB, not LIKE */ + assert( matchSet<0x80 ); /* '[' is a single-byte character */ + while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){ + SQLITE_SKIP_UTF8(zString); + } + return *zString!=0; + } + while( (c2 = sqlite3Utf8Read(&zString))!=0 ){ + if( noCase ){ + GlobUpperToLower(c2); + GlobUpperToLower(c); + while( c2 != 0 && c2 != c ){ + c2 = sqlite3Utf8Read(&zString); + GlobUpperToLower(c2); + } + }else{ + while( c2 != 0 && c2 != c ){ + c2 = sqlite3Utf8Read(&zString); + } + } + if( c2==0 ) return 0; + if( patternCompare(zPattern,zString,pInfo,esc) ) return 1; + } + return 0; + }else if( c==matchOne && !prevEscape ){ + if( sqlite3Utf8Read(&zString)==0 ){ + return 0; + } + }else if( c==matchSet ){ + u32 prior_c = 0; + assert( esc==0 ); /* This only occurs for GLOB, not LIKE */ + seen = 0; + invert = 0; + c = sqlite3Utf8Read(&zString); + if( c==0 ) return 0; + c2 = sqlite3Utf8Read(&zPattern); + if( c2=='^' ){ + invert = 1; + c2 = sqlite3Utf8Read(&zPattern); + } + if( c2==']' ){ + if( c==']' ) seen = 1; + c2 = sqlite3Utf8Read(&zPattern); + } + while( c2 && c2!=']' ){ + if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ + c2 = sqlite3Utf8Read(&zPattern); + if( c>=prior_c && c<=c2 ) seen = 1; + prior_c = 0; + }else{ + if( c==c2 ){ + seen = 1; + } + prior_c = c2; + } + c2 = sqlite3Utf8Read(&zPattern); + } + if( c2==0 || (seen ^ invert)==0 ){ + return 0; + } + }else if( esc==c && !prevEscape ){ + prevEscape = 1; + }else{ + c2 = sqlite3Utf8Read(&zString); + if( noCase ){ + GlobUpperToLower(c); + GlobUpperToLower(c2); + } + if( c!=c2 ){ + return 0; + } + prevEscape = 0; + } + } + return *zString==0; +} + +/* +** The sqlite3_strglob() interface. +*/ +SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){ + return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0; +} + +/* +** Count the number of times that the LIKE operator (or GLOB which is +** just a variation of LIKE) gets called. This is used for testing +** only. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_like_count = 0; +#endif + + +/* +** Implementation of the like() SQL function. This function implements +** the build-in LIKE operator. The first argument to the function is the +** pattern and the second argument is the string. So, the SQL statements: +** +** A LIKE B +** +** is implemented as like(B,A). +** +** This same function (with a different compareInfo structure) computes +** the GLOB operator. +*/ +static void likeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zA, *zB; + u32 escape = 0; + int nPat; + sqlite3 *db = sqlite3_context_db_handle(context); + + zB = sqlite3_value_text(argv[0]); + zA = sqlite3_value_text(argv[1]); + + /* Limit the length of the LIKE or GLOB pattern to avoid problems + ** of deep recursion and N*N behavior in patternCompare(). + */ + nPat = sqlite3_value_bytes(argv[0]); + testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); + testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); + if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ + sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); + return; + } + assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */ + + if( argc==3 ){ + /* The escape character string must consist of a single UTF-8 character. + ** Otherwise, return an error. + */ + const unsigned char *zEsc = sqlite3_value_text(argv[2]); + if( zEsc==0 ) return; + if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ + sqlite3_result_error(context, + "ESCAPE expression must be a single character", -1); + return; + } + escape = sqlite3Utf8Read(&zEsc); + } + if( zA && zB ){ + struct compareInfo *pInfo = sqlite3_user_data(context); +#ifdef SQLITE_TEST + sqlite3_like_count++; +#endif + + sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape)); + } +} + +/* +** Implementation of the NULLIF(x,y) function. The result is the first +** argument if the arguments are different. The result is NULL if the +** arguments are equal to each other. +*/ +static void nullifFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + CollSeq *pColl = sqlite3GetFuncCollSeq(context); + UNUSED_PARAMETER(NotUsed); + if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ + sqlite3_result_value(context, argv[0]); + } +} + +/* +** Implementation of the sqlite_version() function. The result is the version +** of the SQLite library that is running. +*/ +static void versionFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + /* IMP: R-48699-48617 This function is an SQL wrapper around the + ** sqlite3_libversion() C-interface. */ + sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); +} + +/* +** Implementation of the sqlite_source_id() function. The result is a string +** that identifies the particular version of the source code used to build +** SQLite. +*/ +static void sourceidFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + /* IMP: R-24470-31136 This function is an SQL wrapper around the + ** sqlite3_sourceid() C interface. */ + sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); +} + +/* +** Implementation of the sqlite_log() function. This is a wrapper around +** sqlite3_log(). The return value is NULL. The function exists purely for +** its side-effects. +*/ +static void errlogFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(context); + sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); +} + +/* +** Implementation of the sqlite_compileoption_used() function. +** The result is an integer that identifies if the compiler option +** was used to build SQLite. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +static void compileoptionusedFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const char *zOptName; + assert( argc==1 ); + UNUSED_PARAMETER(argc); + /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL + ** function is a wrapper around the sqlite3_compileoption_used() C/C++ + ** function. + */ + if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ + sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); + } +} +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + +/* +** Implementation of the sqlite_compileoption_get() function. +** The result is a string that identifies the compiler options +** used to build SQLite. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +static void compileoptiongetFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int n; + assert( argc==1 ); + UNUSED_PARAMETER(argc); + /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function + ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. + */ + n = sqlite3_value_int(argv[0]); + sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC); +} +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + +/* Array for converting from half-bytes (nybbles) into ASCII hex +** digits. */ +static const char hexdigits[] = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' +}; + +/* +** Implementation of the QUOTE() function. This function takes a single +** argument. If the argument is numeric, the return value is the same as +** the argument. If the argument is NULL, the return value is the string +** "NULL". Otherwise, the argument is enclosed in single quotes with +** single-quote escapes. +*/ +static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + assert( argc==1 ); + UNUSED_PARAMETER(argc); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_FLOAT: { + double r1, r2; + char zBuf[50]; + r1 = sqlite3_value_double(argv[0]); + sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1); + sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8); + if( r1!=r2 ){ + sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1); + } + sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + break; + } + case SQLITE_INTEGER: { + sqlite3_result_value(context, argv[0]); + break; + } + case SQLITE_BLOB: { + char *zText = 0; + char const *zBlob = sqlite3_value_blob(argv[0]); + int nBlob = sqlite3_value_bytes(argv[0]); + assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ + zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); + if( zText ){ + int i; + for(i=0; i>4)&0x0F]; + zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F]; + } + zText[(nBlob*2)+2] = '\''; + zText[(nBlob*2)+3] = '\0'; + zText[0] = 'X'; + zText[1] = '\''; + sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); + sqlite3_free(zText); + } + break; + } + case SQLITE_TEXT: { + int i,j; + u64 n; + const unsigned char *zArg = sqlite3_value_text(argv[0]); + char *z; + + if( zArg==0 ) return; + for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; } + z = contextMalloc(context, ((i64)i)+((i64)n)+3); + if( z ){ + z[0] = '\''; + for(i=0, j=1; zArg[i]; i++){ + z[j++] = zArg[i]; + if( zArg[i]=='\'' ){ + z[j++] = '\''; + } + } + z[j++] = '\''; + z[j] = 0; + sqlite3_result_text(context, z, j, sqlite3_free); + } + break; + } + default: { + assert( sqlite3_value_type(argv[0])==SQLITE_NULL ); + sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC); + break; + } + } +} + +/* +** The unicode() function. Return the integer unicode code-point value +** for the first character of the input string. +*/ +static void unicodeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *z = sqlite3_value_text(argv[0]); + (void)argc; + if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); +} + +/* +** The char() function takes zero or more arguments, each of which is +** an integer. It constructs a string where each character of the string +** is the unicode character for the corresponding integer argument. +*/ +static void charFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + unsigned char *z, *zOut; + int i; + zOut = z = sqlite3_malloc( argc*4 ); + if( z==0 ){ + sqlite3_result_error_nomem(context); + return; + } + for(i=0; i0x10ffff ) x = 0xfffd; + c = (unsigned)(x & 0x1fffff); + if( c<0x00080 ){ + *zOut++ = (u8)(c&0xFF); + }else if( c<0x00800 ){ + *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); + *zOut++ = 0x80 + (u8)(c & 0x3F); + }else if( c<0x10000 ){ + *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); + *zOut++ = 0x80 + (u8)(c & 0x3F); + }else{ + *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); + *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); + *zOut++ = 0x80 + (u8)(c & 0x3F); + } \ + } + sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free); +} + +/* +** The hex() function. Interpret the argument as a blob. Return +** a hexadecimal rendering as text. +*/ +static void hexFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int i, n; + const unsigned char *pBlob; + char *zHex, *z; + assert( argc==1 ); + UNUSED_PARAMETER(argc); + pBlob = sqlite3_value_blob(argv[0]); + n = sqlite3_value_bytes(argv[0]); + assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ + z = zHex = contextMalloc(context, ((i64)n)*2 + 1); + if( zHex ){ + for(i=0; i>4)&0xf]; + *(z++) = hexdigits[c&0xf]; + } + *z = 0; + sqlite3_result_text(context, zHex, n*2, sqlite3_free); + } +} + +/* +** The zeroblob(N) function returns a zero-filled blob of size N bytes. +*/ +static void zeroblobFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + i64 n; + sqlite3 *db = sqlite3_context_db_handle(context); + assert( argc==1 ); + UNUSED_PARAMETER(argc); + n = sqlite3_value_int64(argv[0]); + testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] ); + testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); + if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + sqlite3_result_error_toobig(context); + }else{ + sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */ + } +} + +/* +** The replace() function. Three arguments are all strings: call +** them A, B, and C. The result is also a string which is derived +** from A by replacing every occurrence of B with C. The match +** must be exact. Collating sequences are not used. +*/ +static void replaceFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zStr; /* The input string A */ + const unsigned char *zPattern; /* The pattern string B */ + const unsigned char *zRep; /* The replacement string C */ + unsigned char *zOut; /* The output */ + int nStr; /* Size of zStr */ + int nPattern; /* Size of zPattern */ + int nRep; /* Size of zRep */ + i64 nOut; /* Maximum size of zOut */ + int loopLimit; /* Last zStr[] that might match zPattern[] */ + int i, j; /* Loop counters */ + + assert( argc==3 ); + UNUSED_PARAMETER(argc); + zStr = sqlite3_value_text(argv[0]); + if( zStr==0 ) return; + nStr = sqlite3_value_bytes(argv[0]); + assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */ + zPattern = sqlite3_value_text(argv[1]); + if( zPattern==0 ){ + assert( sqlite3_value_type(argv[1])==SQLITE_NULL + || sqlite3_context_db_handle(context)->mallocFailed ); + return; + } + if( zPattern[0]==0 ){ + assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); + sqlite3_result_value(context, argv[0]); + return; + } + nPattern = sqlite3_value_bytes(argv[1]); + assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ + zRep = sqlite3_value_text(argv[2]); + if( zRep==0 ) return; + nRep = sqlite3_value_bytes(argv[2]); + assert( zRep==sqlite3_value_text(argv[2]) ); + nOut = nStr + 1; + assert( nOutaLimit[SQLITE_LIMIT_LENGTH] ); + testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); + if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + sqlite3_result_error_toobig(context); + sqlite3_free(zOut); + return; + } + zOld = zOut; + zOut = sqlite3_realloc(zOut, (int)nOut); + if( zOut==0 ){ + sqlite3_result_error_nomem(context); + sqlite3_free(zOld); + return; + } + memcpy(&zOut[j], zRep, nRep); + j += nRep; + i += nPattern-1; + } + } + assert( j+nStr-i+1==nOut ); + memcpy(&zOut[j], &zStr[i], nStr-i); + j += nStr - i; + assert( j<=nOut ); + zOut[j] = 0; + sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); +} + +/* +** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. +** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. +*/ +static void trimFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zIn; /* Input string */ + const unsigned char *zCharSet; /* Set of characters to trim */ + int nIn; /* Number of bytes in input */ + int flags; /* 1: trimleft 2: trimright 3: trim */ + int i; /* Loop counter */ + unsigned char *aLen = 0; /* Length of each character in zCharSet */ + unsigned char **azChar = 0; /* Individual characters in zCharSet */ + int nChar; /* Number of characters in zCharSet */ + + if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ + return; + } + zIn = sqlite3_value_text(argv[0]); + if( zIn==0 ) return; + nIn = sqlite3_value_bytes(argv[0]); + assert( zIn==sqlite3_value_text(argv[0]) ); + if( argc==1 ){ + static const unsigned char lenOne[] = { 1 }; + static unsigned char * const azOne[] = { (u8*)" " }; + nChar = 1; + aLen = (u8*)lenOne; + azChar = (unsigned char **)azOne; + zCharSet = 0; + }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ + return; + }else{ + const unsigned char *z; + for(z=zCharSet, nChar=0; *z; nChar++){ + SQLITE_SKIP_UTF8(z); + } + if( nChar>0 ){ + azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); + if( azChar==0 ){ + return; + } + aLen = (unsigned char*)&azChar[nChar]; + for(z=zCharSet, nChar=0; *z; nChar++){ + azChar[nChar] = (unsigned char *)z; + SQLITE_SKIP_UTF8(z); + aLen[nChar] = (u8)(z - azChar[nChar]); + } + } + } + if( nChar>0 ){ + flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); + if( flags & 1 ){ + while( nIn>0 ){ + int len = 0; + for(i=0; i=nChar ) break; + zIn += len; + nIn -= len; + } + } + if( flags & 2 ){ + while( nIn>0 ){ + int len = 0; + for(i=0; i=nChar ) break; + nIn -= len; + } + } + if( zCharSet ){ + sqlite3_free(azChar); + } + } + sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); +} + + +/* IMP: R-25361-16150 This function is omitted from SQLite by default. It +** is only available if the SQLITE_SOUNDEX compile-time option is used +** when SQLite is built. +*/ +#ifdef SQLITE_SOUNDEX +/* +** Compute the soundex encoding of a word. +** +** IMP: R-59782-00072 The soundex(X) function returns a string that is the +** soundex encoding of the string X. +*/ +static void soundexFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + char zResult[8]; + const u8 *zIn; + int i, j; + static const unsigned char iCode[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, + }; + assert( argc==1 ); + zIn = (u8*)sqlite3_value_text(argv[0]); + if( zIn==0 ) zIn = (u8*)""; + for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} + if( zIn[i] ){ + u8 prevcode = iCode[zIn[i]&0x7f]; + zResult[0] = sqlite3Toupper(zIn[i]); + for(j=1; j<4 && zIn[i]; i++){ + int code = iCode[zIn[i]&0x7f]; + if( code>0 ){ + if( code!=prevcode ){ + prevcode = code; + zResult[j++] = code + '0'; + } + }else{ + prevcode = 0; + } + } + while( j<4 ){ + zResult[j++] = '0'; + } + zResult[j] = 0; + sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); + }else{ + /* IMP: R-64894-50321 The string "?000" is returned if the argument + ** is NULL or contains no ASCII alphabetic characters. */ + sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); + } +} +#endif /* SQLITE_SOUNDEX */ + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +/* +** A function that loads a shared-library extension then returns NULL. +*/ +static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ + const char *zFile = (const char *)sqlite3_value_text(argv[0]); + const char *zProc; + sqlite3 *db = sqlite3_context_db_handle(context); + char *zErrMsg = 0; + + if( argc==2 ){ + zProc = (const char *)sqlite3_value_text(argv[1]); + }else{ + zProc = 0; + } + if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ + sqlite3_result_error(context, zErrMsg, -1); + sqlite3_free(zErrMsg); + } +} +#endif + + +/* +** An instance of the following structure holds the context of a +** sum() or avg() aggregate computation. +*/ +typedef struct SumCtx SumCtx; +struct SumCtx { + double rSum; /* Floating point sum */ + i64 iSum; /* Integer sum */ + i64 cnt; /* Number of elements summed */ + u8 overflow; /* True if integer overflow seen */ + u8 approx; /* True if non-integer value was input to the sum */ +}; + +/* +** Routines used to compute the sum, average, and total. +** +** The SUM() function follows the (broken) SQL standard which means +** that it returns NULL if it sums over no inputs. TOTAL returns +** 0.0 in that case. In addition, TOTAL always returns a float where +** SUM might return an integer if it never encounters a floating point +** value. TOTAL never fails, but SUM might through an exception if +** it overflows an integer. +*/ +static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ + SumCtx *p; + int type; + assert( argc==1 ); + UNUSED_PARAMETER(argc); + p = sqlite3_aggregate_context(context, sizeof(*p)); + type = sqlite3_value_numeric_type(argv[0]); + if( p && type!=SQLITE_NULL ){ + p->cnt++; + if( type==SQLITE_INTEGER ){ + i64 v = sqlite3_value_int64(argv[0]); + p->rSum += v; + if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){ + p->overflow = 1; + } + }else{ + p->rSum += sqlite3_value_double(argv[0]); + p->approx = 1; + } + } +} +static void sumFinalize(sqlite3_context *context){ + SumCtx *p; + p = sqlite3_aggregate_context(context, 0); + if( p && p->cnt>0 ){ + if( p->overflow ){ + sqlite3_result_error(context,"integer overflow",-1); + }else if( p->approx ){ + sqlite3_result_double(context, p->rSum); + }else{ + sqlite3_result_int64(context, p->iSum); + } + } +} +static void avgFinalize(sqlite3_context *context){ + SumCtx *p; + p = sqlite3_aggregate_context(context, 0); + if( p && p->cnt>0 ){ + sqlite3_result_double(context, p->rSum/(double)p->cnt); + } +} +static void totalFinalize(sqlite3_context *context){ + SumCtx *p; + p = sqlite3_aggregate_context(context, 0); + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + sqlite3_result_double(context, p ? p->rSum : (double)0); +} + +/* +** The following structure keeps track of state information for the +** count() aggregate function. +*/ +typedef struct CountCtx CountCtx; +struct CountCtx { + i64 n; +}; + +/* +** Routines to implement the count() aggregate function. +*/ +static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ + CountCtx *p; + p = sqlite3_aggregate_context(context, sizeof(*p)); + if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ + p->n++; + } + +#ifndef SQLITE_OMIT_DEPRECATED + /* The sqlite3_aggregate_count() function is deprecated. But just to make + ** sure it still operates correctly, verify that its count agrees with our + ** internal count when using count(*) and when the total count can be + ** expressed as a 32-bit integer. */ + assert( argc==1 || p==0 || p->n>0x7fffffff + || p->n==sqlite3_aggregate_count(context) ); +#endif +} +static void countFinalize(sqlite3_context *context){ + CountCtx *p; + p = sqlite3_aggregate_context(context, 0); + sqlite3_result_int64(context, p ? p->n : 0); +} + +/* +** Routines to implement min() and max() aggregate functions. +*/ +static void minmaxStep( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + Mem *pArg = (Mem *)argv[0]; + Mem *pBest; + UNUSED_PARAMETER(NotUsed); + + pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); + if( !pBest ) return; + + if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ + if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); + }else if( pBest->flags ){ + int max; + int cmp; + CollSeq *pColl = sqlite3GetFuncCollSeq(context); + /* This step function is used for both the min() and max() aggregates, + ** the only difference between the two being that the sense of the + ** comparison is inverted. For the max() aggregate, the + ** sqlite3_user_data() function returns (void *)-1. For min() it + ** returns (void *)db, where db is the sqlite3* database pointer. + ** Therefore the next statement sets variable 'max' to 1 for the max() + ** aggregate, or 0 for min(). + */ + max = sqlite3_user_data(context)!=0; + cmp = sqlite3MemCompare(pBest, pArg, pColl); + if( (max && cmp<0) || (!max && cmp>0) ){ + sqlite3VdbeMemCopy(pBest, pArg); + }else{ + sqlite3SkipAccumulatorLoad(context); + } + }else{ + sqlite3VdbeMemCopy(pBest, pArg); + } +} +static void minMaxFinalize(sqlite3_context *context){ + sqlite3_value *pRes; + pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); + if( pRes ){ + if( pRes->flags ){ + sqlite3_result_value(context, pRes); + } + sqlite3VdbeMemRelease(pRes); + } +} + +/* +** group_concat(EXPR, ?SEPARATOR?) +*/ +static void groupConcatStep( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const char *zVal; + StrAccum *pAccum; + const char *zSep; + int nVal, nSep; + assert( argc==1 || argc==2 ); + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; + pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); + + if( pAccum ){ + sqlite3 *db = sqlite3_context_db_handle(context); + int firstTerm = pAccum->useMalloc==0; + pAccum->useMalloc = 2; + pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; + if( !firstTerm ){ + if( argc==2 ){ + zSep = (char*)sqlite3_value_text(argv[1]); + nSep = sqlite3_value_bytes(argv[1]); + }else{ + zSep = ","; + nSep = 1; + } + sqlite3StrAccumAppend(pAccum, zSep, nSep); + } + zVal = (char*)sqlite3_value_text(argv[0]); + nVal = sqlite3_value_bytes(argv[0]); + sqlite3StrAccumAppend(pAccum, zVal, nVal); + } +} +static void groupConcatFinalize(sqlite3_context *context){ + StrAccum *pAccum; + pAccum = sqlite3_aggregate_context(context, 0); + if( pAccum ){ + if( pAccum->accError==STRACCUM_TOOBIG ){ + sqlite3_result_error_toobig(context); + }else if( pAccum->accError==STRACCUM_NOMEM ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, + sqlite3_free); + } + } +} + +/* +** This routine does per-connection function registration. Most +** of the built-in functions above are part of the global function set. +** This routine only deals with those that are not global. +*/ +SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){ + int rc = sqlite3_overload_function(db, "MATCH", 2); + assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); + if( rc==SQLITE_NOMEM ){ + db->mallocFailed = 1; + } +} + +/* +** Set the LIKEOPT flag on the 2-argument function with the given name. +*/ +static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){ + FuncDef *pDef; + pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName), + 2, SQLITE_UTF8, 0); + if( ALWAYS(pDef) ){ + pDef->funcFlags |= flagVal; + } +} + +/* +** Register the built-in LIKE and GLOB functions. The caseSensitive +** parameter determines whether or not the LIKE operator is case +** sensitive. GLOB is always case sensitive. +*/ +SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ + struct compareInfo *pInfo; + if( caseSensitive ){ + pInfo = (struct compareInfo*)&likeInfoAlt; + }else{ + pInfo = (struct compareInfo*)&likeInfoNorm; + } + sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); + sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); + sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, + (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0); + setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE); + setLikeOptFlag(db, "like", + caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE); +} + +/* +** pExpr points to an expression which implements a function. If +** it is appropriate to apply the LIKE optimization to that function +** then set aWc[0] through aWc[2] to the wildcard characters and +** return TRUE. If the function is not a LIKE-style function then +** return FALSE. +*/ +SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ + FuncDef *pDef; + if( pExpr->op!=TK_FUNCTION + || !pExpr->x.pList + || pExpr->x.pList->nExpr!=2 + ){ + return 0; + } + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + pDef = sqlite3FindFunction(db, pExpr->u.zToken, + sqlite3Strlen30(pExpr->u.zToken), + 2, SQLITE_UTF8, 0); + if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ + return 0; + } + + /* The memcpy() statement assumes that the wildcard characters are + ** the first three statements in the compareInfo structure. The + ** asserts() that follow verify that assumption + */ + memcpy(aWc, pDef->pUserData, 3); + assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); + assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); + assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); + *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0; + return 1; +} + +/* +** All all of the FuncDef structures in the aBuiltinFunc[] array above +** to the global function hash table. This occurs at start-time (as +** a consequence of calling sqlite3_initialize()). +** +** After this routine runs +*/ +SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){ + /* + ** The following array holds FuncDef structures for all of the functions + ** defined in this file. + ** + ** The array cannot be constant since changes are made to the + ** FuncDef.pHash elements at start-time. The elements of this array + ** are read-only after initialization is complete. + */ + static SQLITE_WSD FuncDef aBuiltinFunc[] = { + FUNCTION(ltrim, 1, 1, 0, trimFunc ), + FUNCTION(ltrim, 2, 1, 0, trimFunc ), + FUNCTION(rtrim, 1, 2, 0, trimFunc ), + FUNCTION(rtrim, 2, 2, 0, trimFunc ), + FUNCTION(trim, 1, 3, 0, trimFunc ), + FUNCTION(trim, 2, 3, 0, trimFunc ), + FUNCTION(min, -1, 0, 1, minmaxFunc ), + FUNCTION(min, 0, 0, 1, 0 ), + AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ), + FUNCTION(max, -1, 1, 1, minmaxFunc ), + FUNCTION(max, 0, 1, 1, 0 ), + AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ), + FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), + FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH), + FUNCTION(instr, 2, 0, 0, instrFunc ), + FUNCTION(substr, 2, 0, 0, substrFunc ), + FUNCTION(substr, 3, 0, 0, substrFunc ), + FUNCTION(unicode, 1, 0, 0, unicodeFunc ), + FUNCTION(char, -1, 0, 0, charFunc ), + FUNCTION(abs, 1, 0, 0, absFunc ), +#ifndef SQLITE_OMIT_FLOATING_POINT + FUNCTION(round, 1, 0, 0, roundFunc ), + FUNCTION(round, 2, 0, 0, roundFunc ), +#endif + FUNCTION(upper, 1, 0, 0, upperFunc ), + FUNCTION(lower, 1, 0, 0, lowerFunc ), + FUNCTION(coalesce, 1, 0, 0, 0 ), + FUNCTION(coalesce, 0, 0, 0, 0 ), + FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), + FUNCTION(hex, 1, 0, 0, hexFunc ), + FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), + FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), + FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), + FUNCTION(random, 0, 0, 0, randomFunc ), + FUNCTION(randomblob, 1, 0, 0, randomBlob ), + FUNCTION(nullif, 2, 0, 1, nullifFunc ), + FUNCTION(sqlite_version, 0, 0, 0, versionFunc ), + FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ), + FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS + FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), + FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + FUNCTION(quote, 1, 0, 0, quoteFunc ), + FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid), + FUNCTION(changes, 0, 0, 0, changes ), + FUNCTION(total_changes, 0, 0, 0, total_changes ), + FUNCTION(replace, 3, 0, 0, replaceFunc ), + FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ), + #ifdef SQLITE_SOUNDEX + FUNCTION(soundex, 1, 0, 0, soundexFunc ), + #endif + #ifndef SQLITE_OMIT_LOAD_EXTENSION + FUNCTION(load_extension, 1, 0, 0, loadExt ), + FUNCTION(load_extension, 2, 0, 0, loadExt ), + #endif + AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ), + AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ), + AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ), + /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */ + {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0}, + AGGREGATE(count, 1, 0, 0, countStep, countFinalize ), + AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize), + AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize), + + LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), + #ifdef SQLITE_CASE_SENSITIVE_LIKE + LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), + LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), + #else + LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE), + LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE), + #endif + }; + + int i; + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc); + + for(i=0; idb->mallocFailed flag is set. +*/ +SQLITE_PRIVATE int sqlite3FkLocateIndex( + Parse *pParse, /* Parse context to store any error in */ + Table *pParent, /* Parent table of FK constraint pFKey */ + FKey *pFKey, /* Foreign key to find index for */ + Index **ppIdx, /* OUT: Unique index on parent table */ + int **paiCol /* OUT: Map of index columns in pFKey */ +){ + Index *pIdx = 0; /* Value to return via *ppIdx */ + int *aiCol = 0; /* Value to return via *paiCol */ + int nCol = pFKey->nCol; /* Number of columns in parent key */ + char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */ + + /* The caller is responsible for zeroing output parameters. */ + assert( ppIdx && *ppIdx==0 ); + assert( !paiCol || *paiCol==0 ); + assert( pParse ); + + /* If this is a non-composite (single column) foreign key, check if it + ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx + ** and *paiCol set to zero and return early. + ** + ** Otherwise, for a composite foreign key (more than one column), allocate + ** space for the aiCol array (returned via output parameter *paiCol). + ** Non-composite foreign keys do not require the aiCol array. + */ + if( nCol==1 ){ + /* The FK maps to the IPK if any of the following are true: + ** + ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly + ** mapped to the primary key of table pParent, or + ** 2) The FK is explicitly mapped to a column declared as INTEGER + ** PRIMARY KEY. + */ + if( pParent->iPKey>=0 ){ + if( !zKey ) return 0; + if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0; + } + }else if( paiCol ){ + assert( nCol>1 ); + aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int)); + if( !aiCol ) return 1; + *paiCol = aiCol; + } + + for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ + /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number + ** of columns. If each indexed column corresponds to a foreign key + ** column of pFKey, then this index is a winner. */ + + if( zKey==0 ){ + /* If zKey is NULL, then this foreign key is implicitly mapped to + ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be + ** identified by the test (Index.autoIndex==2). */ + if( pIdx->autoIndex==2 ){ + if( aiCol ){ + int i; + for(i=0; iaCol[i].iFrom; + } + break; + } + }else{ + /* If zKey is non-NULL, then this foreign key was declared to + ** map to an explicit list of columns in table pParent. Check if this + ** index matches those columns. Also, check that the index uses + ** the default collation sequences for each column. */ + int i, j; + for(i=0; iaiColumn[i]; /* Index of column in parent tbl */ + char *zDfltColl; /* Def. collation for column */ + char *zIdxCol; /* Name of indexed column */ + + /* If the index uses a collation sequence that is different from + ** the default collation sequence for the column, this index is + ** unusable. Bail out early in this case. */ + zDfltColl = pParent->aCol[iCol].zColl; + if( !zDfltColl ){ + zDfltColl = "BINARY"; + } + if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break; + + zIdxCol = pParent->aCol[iCol].zName; + for(j=0; jaCol[j].zCol, zIdxCol)==0 ){ + if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom; + break; + } + } + if( j==nCol ) break; + } + if( i==nCol ) break; /* pIdx is usable */ + } + } + } + + if( !pIdx ){ + if( !pParse->disableTriggers ){ + sqlite3ErrorMsg(pParse, + "foreign key mismatch - \"%w\" referencing \"%w\"", + pFKey->pFrom->zName, pFKey->zTo); + } + sqlite3DbFree(pParse->db, aiCol); + return 1; + } + + *ppIdx = pIdx; + return 0; +} + +/* +** This function is called when a row is inserted into or deleted from the +** child table of foreign key constraint pFKey. If an SQL UPDATE is executed +** on the child table of pFKey, this function is invoked twice for each row +** affected - once to "delete" the old row, and then again to "insert" the +** new row. +** +** Each time it is called, this function generates VDBE code to locate the +** row in the parent table that corresponds to the row being inserted into +** or deleted from the child table. If the parent row can be found, no +** special action is taken. Otherwise, if the parent row can *not* be +** found in the parent table: +** +** Operation | FK type | Action taken +** -------------------------------------------------------------------------- +** INSERT immediate Increment the "immediate constraint counter". +** +** DELETE immediate Decrement the "immediate constraint counter". +** +** INSERT deferred Increment the "deferred constraint counter". +** +** DELETE deferred Decrement the "deferred constraint counter". +** +** These operations are identified in the comment at the top of this file +** (fkey.c) as "I.1" and "D.1". +*/ +static void fkLookupParent( + Parse *pParse, /* Parse context */ + int iDb, /* Index of database housing pTab */ + Table *pTab, /* Parent table of FK pFKey */ + Index *pIdx, /* Unique index on parent key columns in pTab */ + FKey *pFKey, /* Foreign key constraint */ + int *aiCol, /* Map from parent key columns to child table columns */ + int regData, /* Address of array containing child table row */ + int nIncr, /* Increment constraint counter by this */ + int isIgnore /* If true, pretend pTab contains all NULL values */ +){ + int i; /* Iterator variable */ + Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */ + int iCur = pParse->nTab - 1; /* Cursor number to use */ + int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */ + + /* If nIncr is less than zero, then check at runtime if there are any + ** outstanding constraints to resolve. If there are not, there is no need + ** to check if deleting this row resolves any outstanding violations. + ** + ** Check if any of the key columns in the child table row are NULL. If + ** any are, then the constraint is considered satisfied. No need to + ** search for a matching row in the parent table. */ + if( nIncr<0 ){ + sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk); + } + for(i=0; inCol; i++){ + int iReg = aiCol[i] + regData + 1; + sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); + } + + if( isIgnore==0 ){ + if( pIdx==0 ){ + /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY + ** column of the parent table (table pTab). */ + int iMustBeInt; /* Address of MustBeInt instruction */ + int regTemp = sqlite3GetTempReg(pParse); + + /* Invoke MustBeInt to coerce the child key value to an integer (i.e. + ** apply the affinity of the parent key). If this fails, then there + ** is no matching parent key. Before using MustBeInt, make a copy of + ** the value. Otherwise, the value inserted into the child key column + ** will have INTEGER affinity applied to it, which may not be correct. */ + sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp); + iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0); + + /* If the parent table is the same as the child table, and we are about + ** to increment the constraint-counter (i.e. this is an INSERT operation), + ** then check if the row being inserted matches itself. If so, do not + ** increment the constraint-counter. */ + if( pTab==pFKey->pFrom && nIncr==1 ){ + sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); + } + + sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); + sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk); + sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); + sqlite3VdbeJumpHere(v, iMustBeInt); + sqlite3ReleaseTempReg(pParse, regTemp); + }else{ + int nCol = pFKey->nCol; + int regTemp = sqlite3GetTempRange(pParse, nCol); + int regRec = sqlite3GetTempReg(pParse); + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + + sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); + sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); + for(i=0; ipFrom && nIncr==1 ){ + int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1; + for(i=0; iaiColumn[i]+1+regData; + assert( aiCol[i]!=pTab->iPKey ); + if( pIdx->aiColumn[i]==pTab->iPKey ){ + /* The parent key is a composite key that includes the IPK column */ + iParent = regData; + } + sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); + sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); + } + sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk); + } + + sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec); + sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT); + sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); + + sqlite3ReleaseTempReg(pParse, regRec); + sqlite3ReleaseTempRange(pParse, regTemp, nCol); + } + } + + if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs) + && !pParse->pToplevel + && !pParse->isMultiWrite + ){ + /* Special case: If this is an INSERT statement that will insert exactly + ** one row into the table, raise a constraint immediately instead of + ** incrementing a counter. This is necessary as the VM code is being + ** generated for will not open a statement transaction. */ + assert( nIncr==1 ); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, + OE_Abort, "foreign key constraint failed", P4_STATIC + ); + }else{ + if( nIncr>0 && pFKey->isDeferred==0 ){ + sqlite3ParseToplevel(pParse)->mayAbort = 1; + } + sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); + } + + sqlite3VdbeResolveLabel(v, iOk); + sqlite3VdbeAddOp1(v, OP_Close, iCur); +} + +/* +** This function is called to generate code executed when a row is deleted +** from the parent table of foreign key constraint pFKey and, if pFKey is +** deferred, when a row is inserted into the same table. When generating +** code for an SQL UPDATE operation, this function may be called twice - +** once to "delete" the old row and once to "insert" the new row. +** +** The code generated by this function scans through the rows in the child +** table that correspond to the parent table row being deleted or inserted. +** For each child row found, one of the following actions is taken: +** +** Operation | FK type | Action taken +** -------------------------------------------------------------------------- +** DELETE immediate Increment the "immediate constraint counter". +** Or, if the ON (UPDATE|DELETE) action is RESTRICT, +** throw a "foreign key constraint failed" exception. +** +** INSERT immediate Decrement the "immediate constraint counter". +** +** DELETE deferred Increment the "deferred constraint counter". +** Or, if the ON (UPDATE|DELETE) action is RESTRICT, +** throw a "foreign key constraint failed" exception. +** +** INSERT deferred Decrement the "deferred constraint counter". +** +** These operations are identified in the comment at the top of this file +** (fkey.c) as "I.2" and "D.2". +*/ +static void fkScanChildren( + Parse *pParse, /* Parse context */ + SrcList *pSrc, /* SrcList containing the table to scan */ + Table *pTab, + Index *pIdx, /* Foreign key index */ + FKey *pFKey, /* Foreign key relationship */ + int *aiCol, /* Map from pIdx cols to child table cols */ + int regData, /* Referenced table data starts here */ + int nIncr /* Amount to increment deferred counter by */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + int i; /* Iterator variable */ + Expr *pWhere = 0; /* WHERE clause to scan with */ + NameContext sNameContext; /* Context used to resolve WHERE clause */ + WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */ + int iFkIfZero = 0; /* Address of OP_FkIfZero */ + Vdbe *v = sqlite3GetVdbe(pParse); + + assert( !pIdx || pIdx->pTable==pTab ); + + if( nIncr<0 ){ + iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0); + } + + /* Create an Expr object representing an SQL expression like: + ** + ** = AND = ... + ** + ** The collation sequence used for the comparison should be that of + ** the parent key columns. The affinity of the parent key column should + ** be applied to each child key value before the comparison takes place. + */ + for(i=0; inCol; i++){ + Expr *pLeft; /* Value from parent table row */ + Expr *pRight; /* Column ref to child table */ + Expr *pEq; /* Expression (pLeft = pRight) */ + int iCol; /* Index of column in child table */ + const char *zCol; /* Name of column in child table */ + + pLeft = sqlite3Expr(db, TK_REGISTER, 0); + if( pLeft ){ + /* Set the collation sequence and affinity of the LHS of each TK_EQ + ** expression to the parent key column defaults. */ + if( pIdx ){ + Column *pCol; + const char *zColl; + iCol = pIdx->aiColumn[i]; + pCol = &pTab->aCol[iCol]; + if( pTab->iPKey==iCol ) iCol = -1; + pLeft->iTable = regData+iCol+1; + pLeft->affinity = pCol->affinity; + zColl = pCol->zColl; + if( zColl==0 ) zColl = db->pDfltColl->zName; + pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl); + }else{ + pLeft->iTable = regData; + pLeft->affinity = SQLITE_AFF_INTEGER; + } + } + iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; + assert( iCol>=0 ); + zCol = pFKey->pFrom->aCol[iCol].zName; + pRight = sqlite3Expr(db, TK_ID, zCol); + pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); + pWhere = sqlite3ExprAnd(db, pWhere, pEq); + } + + /* If the child table is the same as the parent table, and this scan + ** is taking place as part of a DELETE operation (operation D.2), omit the + ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE + ** clause, where $rowid is the rowid of the row being deleted. */ + if( pTab==pFKey->pFrom && nIncr>0 ){ + Expr *pEq; /* Expression (pLeft = pRight) */ + Expr *pLeft; /* Value from parent table row */ + Expr *pRight; /* Column ref to child table */ + pLeft = sqlite3Expr(db, TK_REGISTER, 0); + pRight = sqlite3Expr(db, TK_COLUMN, 0); + if( pLeft && pRight ){ + pLeft->iTable = regData; + pLeft->affinity = SQLITE_AFF_INTEGER; + pRight->iTable = pSrc->a[0].iCursor; + pRight->iColumn = -1; + } + pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0); + pWhere = sqlite3ExprAnd(db, pWhere, pEq); + } + + /* Resolve the references in the WHERE clause. */ + memset(&sNameContext, 0, sizeof(NameContext)); + sNameContext.pSrcList = pSrc; + sNameContext.pParse = pParse; + sqlite3ResolveExprNames(&sNameContext, pWhere); + + /* Create VDBE to loop through the entries in pSrc that match the WHERE + ** clause. If the constraint is not deferred, throw an exception for + ** each row found. Otherwise, for deferred constraints, increment the + ** deferred constraint counter by nIncr for each row selected. */ + pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0); + if( nIncr>0 && pFKey->isDeferred==0 ){ + sqlite3ParseToplevel(pParse)->mayAbort = 1; + } + sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); + if( pWInfo ){ + sqlite3WhereEnd(pWInfo); + } + + /* Clean up the WHERE clause constructed above. */ + sqlite3ExprDelete(db, pWhere); + if( iFkIfZero ){ + sqlite3VdbeJumpHere(v, iFkIfZero); + } +} + +/* +** This function returns a pointer to the head of a linked list of FK +** constraints for which table pTab is the parent table. For example, +** given the following schema: +** +** CREATE TABLE t1(a PRIMARY KEY); +** CREATE TABLE t2(b REFERENCES t1(a); +** +** Calling this function with table "t1" as an argument returns a pointer +** to the FKey structure representing the foreign key constraint on table +** "t2". Calling this function with "t2" as the argument would return a +** NULL pointer (as there are no FK constraints for which t2 is the parent +** table). +*/ +SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){ + int nName = sqlite3Strlen30(pTab->zName); + return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName); +} + +/* +** The second argument is a Trigger structure allocated by the +** fkActionTrigger() routine. This function deletes the Trigger structure +** and all of its sub-components. +** +** The Trigger structure or any of its sub-components may be allocated from +** the lookaside buffer belonging to database handle dbMem. +*/ +static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ + if( p ){ + TriggerStep *pStep = p->step_list; + sqlite3ExprDelete(dbMem, pStep->pWhere); + sqlite3ExprListDelete(dbMem, pStep->pExprList); + sqlite3SelectDelete(dbMem, pStep->pSelect); + sqlite3ExprDelete(dbMem, p->pWhen); + sqlite3DbFree(dbMem, p); + } +} + +/* +** This function is called to generate code that runs when table pTab is +** being dropped from the database. The SrcList passed as the second argument +** to this function contains a single entry guaranteed to resolve to +** table pTab. +** +** Normally, no code is required. However, if either +** +** (a) The table is the parent table of a FK constraint, or +** (b) The table is the child table of a deferred FK constraint and it is +** determined at runtime that there are outstanding deferred FK +** constraint violations in the database, +** +** then the equivalent of "DELETE FROM " is executed before dropping +** the table from the database. Triggers are disabled while running this +** DELETE, but foreign key actions are not. +*/ +SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){ + sqlite3 *db = pParse->db; + if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){ + int iSkip = 0; + Vdbe *v = sqlite3GetVdbe(pParse); + + assert( v ); /* VDBE has already been allocated */ + if( sqlite3FkReferences(pTab)==0 ){ + /* Search for a deferred foreign key constraint for which this table + ** is the child table. If one cannot be found, return without + ** generating any VDBE code. If one can be found, then jump over + ** the entire DELETE if there are no outstanding deferred constraints + ** when this statement is run. */ + FKey *p; + for(p=pTab->pFKey; p; p=p->pNextFrom){ + if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break; + } + if( !p ) return; + iSkip = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); + } + + pParse->disableTriggers = 1; + sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0); + pParse->disableTriggers = 0; + + /* If the DELETE has generated immediate foreign key constraint + ** violations, halt the VDBE and return an error at this point, before + ** any modifications to the schema are made. This is because statement + ** transactions are not able to rollback schema changes. + ** + ** If the SQLITE_DeferFKs flag is set, then this is not required, as + ** the statement transaction will not be rolled back even if FK + ** constraints are violated. + */ + if( (db->flags & SQLITE_DeferFKs)==0 ){ + sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, + OE_Abort, "foreign key constraint failed", P4_STATIC + ); + } + + if( iSkip ){ + sqlite3VdbeResolveLabel(v, iSkip); + } + } +} + + +/* +** The second argument points to an FKey object representing a foreign key +** for which pTab is the child table. An UPDATE statement against pTab +** is currently being processed. For each column of the table that is +** actually updated, the corresponding element in the aChange[] array +** is zero or greater (if a column is unmodified the corresponding element +** is set to -1). If the rowid column is modified by the UPDATE statement +** the bChngRowid argument is non-zero. +** +** This function returns true if any of the columns that are part of the +** child key for FK constraint *p are modified. +*/ +static int fkChildIsModified( + Table *pTab, /* Table being updated */ + FKey *p, /* Foreign key for which pTab is the child */ + int *aChange, /* Array indicating modified columns */ + int bChngRowid /* True if rowid is modified by this update */ +){ + int i; + for(i=0; inCol; i++){ + int iChildKey = p->aCol[i].iFrom; + if( aChange[iChildKey]>=0 ) return 1; + if( iChildKey==pTab->iPKey && bChngRowid ) return 1; + } + return 0; +} + +/* +** The second argument points to an FKey object representing a foreign key +** for which pTab is the parent table. An UPDATE statement against pTab +** is currently being processed. For each column of the table that is +** actually updated, the corresponding element in the aChange[] array +** is zero or greater (if a column is unmodified the corresponding element +** is set to -1). If the rowid column is modified by the UPDATE statement +** the bChngRowid argument is non-zero. +** +** This function returns true if any of the columns that are part of the +** parent key for FK constraint *p are modified. +*/ +static int fkParentIsModified( + Table *pTab, + FKey *p, + int *aChange, + int bChngRowid +){ + int i; + for(i=0; inCol; i++){ + char *zKey = p->aCol[i].zCol; + int iKey; + for(iKey=0; iKeynCol; iKey++){ + if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){ + Column *pCol = &pTab->aCol[iKey]; + if( zKey ){ + if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1; + }else if( pCol->colFlags & COLFLAG_PRIMKEY ){ + return 1; + } + } + } + } + return 0; +} + +/* +** This function is called when inserting, deleting or updating a row of +** table pTab to generate VDBE code to perform foreign key constraint +** processing for the operation. +** +** For a DELETE operation, parameter regOld is passed the index of the +** first register in an array of (pTab->nCol+1) registers containing the +** rowid of the row being deleted, followed by each of the column values +** of the row being deleted, from left to right. Parameter regNew is passed +** zero in this case. +** +** For an INSERT operation, regOld is passed zero and regNew is passed the +** first register of an array of (pTab->nCol+1) registers containing the new +** row data. +** +** For an UPDATE operation, this function is called twice. Once before +** the original record is deleted from the table using the calling convention +** described for DELETE. Then again after the original record is deleted +** but before the new record is inserted using the INSERT convention. +*/ +SQLITE_PRIVATE void sqlite3FkCheck( + Parse *pParse, /* Parse context */ + Table *pTab, /* Row is being deleted from this table */ + int regOld, /* Previous row data is stored here */ + int regNew, /* New row data is stored here */ + int *aChange, /* Array indicating UPDATEd columns (or 0) */ + int bChngRowid /* True if rowid is UPDATEd */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + FKey *pFKey; /* Used to iterate through FKs */ + int iDb; /* Index of database containing pTab */ + const char *zDb; /* Name of database containing pTab */ + int isIgnoreErrors = pParse->disableTriggers; + + /* Exactly one of regOld and regNew should be non-zero. */ + assert( (regOld==0)!=(regNew==0) ); + + /* If foreign-keys are disabled, this function is a no-op. */ + if( (db->flags&SQLITE_ForeignKeys)==0 ) return; + + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + zDb = db->aDb[iDb].zName; + + /* Loop through all the foreign key constraints for which pTab is the + ** child table (the table that the foreign key definition is part of). */ + for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ + Table *pTo; /* Parent table of foreign key pFKey */ + Index *pIdx = 0; /* Index on key columns in pTo */ + int *aiFree = 0; + int *aiCol; + int iCol; + int i; + int isIgnore = 0; + + if( aChange + && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0 + && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 + ){ + continue; + } + + /* Find the parent table of this foreign key. Also find a unique index + ** on the parent key columns in the parent table. If either of these + ** schema items cannot be located, set an error in pParse and return + ** early. */ + if( pParse->disableTriggers ){ + pTo = sqlite3FindTable(db, pFKey->zTo, zDb); + }else{ + pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); + } + if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){ + assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) ); + if( !isIgnoreErrors || db->mallocFailed ) return; + if( pTo==0 ){ + /* If isIgnoreErrors is true, then a table is being dropped. In this + ** case SQLite runs a "DELETE FROM xxx" on the table being dropped + ** before actually dropping it in order to check FK constraints. + ** If the parent table of an FK constraint on the current table is + ** missing, behave as if it is empty. i.e. decrement the relevant + ** FK counter for each row of the current table with non-NULL keys. + */ + Vdbe *v = sqlite3GetVdbe(pParse); + int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1; + for(i=0; inCol; i++){ + int iReg = pFKey->aCol[i].iFrom + regOld + 1; + sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); + } + sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1); + } + continue; + } + assert( pFKey->nCol==1 || (aiFree && pIdx) ); + + if( aiFree ){ + aiCol = aiFree; + }else{ + iCol = pFKey->aCol[0].iFrom; + aiCol = &iCol; + } + for(i=0; inCol; i++){ + if( aiCol[i]==pTab->iPKey ){ + aiCol[i] = -1; + } +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Request permission to read the parent key columns. If the + ** authorization callback returns SQLITE_IGNORE, behave as if any + ** values read from the parent table are NULL. */ + if( db->xAuth ){ + int rcauth; + char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName; + rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb); + isIgnore = (rcauth==SQLITE_IGNORE); + } +#endif + } + + /* Take a shared-cache advisory read-lock on the parent table. Allocate + ** a cursor to use to search the unique index on the parent key columns + ** in the parent table. */ + sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName); + pParse->nTab++; + + if( regOld!=0 ){ + /* A row is being removed from the child table. Search for the parent. + ** If the parent does not exist, removing the child row resolves an + ** outstanding foreign key constraint violation. */ + fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore); + } + if( regNew!=0 ){ + /* A row is being added to the child table. If a parent row cannot + ** be found, adding the child row has violated the FK constraint. */ + fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore); + } + + sqlite3DbFree(db, aiFree); + } + + /* Loop through all the foreign key constraints that refer to this table */ + for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ + Index *pIdx = 0; /* Foreign key index for pFKey */ + SrcList *pSrc; + int *aiCol = 0; + + if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){ + continue; + } + + if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) + && !pParse->pToplevel && !pParse->isMultiWrite + ){ + assert( regOld==0 && regNew!=0 ); + /* Inserting a single row into a parent table cannot cause an immediate + ** foreign key violation. So do nothing in this case. */ + continue; + } + + if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){ + if( !isIgnoreErrors || db->mallocFailed ) return; + continue; + } + assert( aiCol || pFKey->nCol==1 ); + + /* Create a SrcList structure containing a single table (the table + ** the foreign key that refers to this table is attached to). This + ** is required for the sqlite3WhereXXX() interface. */ + pSrc = sqlite3SrcListAppend(db, 0, 0, 0); + if( pSrc ){ + struct SrcList_item *pItem = pSrc->a; + pItem->pTab = pFKey->pFrom; + pItem->zName = pFKey->pFrom->zName; + pItem->pTab->nRef++; + pItem->iCursor = pParse->nTab++; + + if( regNew!=0 ){ + fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1); + } + if( regOld!=0 ){ + /* If there is a RESTRICT action configured for the current operation + ** on the parent table of this FK, then throw an exception + ** immediately if the FK constraint is violated, even if this is a + ** deferred trigger. That's what RESTRICT means. To defer checking + ** the constraint, the FK should specify NO ACTION (represented + ** using OE_None). NO ACTION is the default. */ + fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1); + } + pItem->zName = 0; + sqlite3SrcListDelete(db, pSrc); + } + sqlite3DbFree(db, aiCol); + } +} + +#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x))) + +/* +** This function is called before generating code to update or delete a +** row contained in table pTab. +*/ +SQLITE_PRIVATE u32 sqlite3FkOldmask( + Parse *pParse, /* Parse context */ + Table *pTab /* Table being modified */ +){ + u32 mask = 0; + if( pParse->db->flags&SQLITE_ForeignKeys ){ + FKey *p; + int i; + for(p=pTab->pFKey; p; p=p->pNextFrom){ + for(i=0; inCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom); + } + for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ + Index *pIdx = 0; + sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0); + if( pIdx ){ + for(i=0; inColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]); + } + } + } + return mask; +} + + +/* +** This function is called before generating code to update or delete a +** row contained in table pTab. If the operation is a DELETE, then +** parameter aChange is passed a NULL value. For an UPDATE, aChange points +** to an array of size N, where N is the number of columns in table pTab. +** If the i'th column is not modified by the UPDATE, then the corresponding +** entry in the aChange[] array is set to -1. If the column is modified, +** the value is 0 or greater. Parameter chngRowid is set to true if the +** UPDATE statement modifies the rowid fields of the table. +** +** If any foreign key processing will be required, this function returns +** true. If there is no foreign key related processing, this function +** returns false. +*/ +SQLITE_PRIVATE int sqlite3FkRequired( + Parse *pParse, /* Parse context */ + Table *pTab, /* Table being modified */ + int *aChange, /* Non-NULL for UPDATE operations */ + int chngRowid /* True for UPDATE that affects rowid */ +){ + if( pParse->db->flags&SQLITE_ForeignKeys ){ + if( !aChange ){ + /* A DELETE operation. Foreign key processing is required if the + ** table in question is either the child or parent table for any + ** foreign key constraint. */ + return (sqlite3FkReferences(pTab) || pTab->pFKey); + }else{ + /* This is an UPDATE. Foreign key processing is only required if the + ** operation modifies one or more child or parent key columns. */ + FKey *p; + + /* Check if any child key columns are being modified. */ + for(p=pTab->pFKey; p; p=p->pNextFrom){ + if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1; + } + + /* Check if any parent key columns are being modified. */ + for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ + if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1; + } + } + } + return 0; +} + +/* +** This function is called when an UPDATE or DELETE operation is being +** compiled on table pTab, which is the parent table of foreign-key pFKey. +** If the current operation is an UPDATE, then the pChanges parameter is +** passed a pointer to the list of columns being modified. If it is a +** DELETE, pChanges is passed a NULL pointer. +** +** It returns a pointer to a Trigger structure containing a trigger +** equivalent to the ON UPDATE or ON DELETE action specified by pFKey. +** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is +** returned (these actions require no special handling by the triggers +** sub-system, code for them is created by fkScanChildren()). +** +** For example, if pFKey is the foreign key and pTab is table "p" in +** the following schema: +** +** CREATE TABLE p(pk PRIMARY KEY); +** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE); +** +** then the returned trigger structure is equivalent to: +** +** CREATE TRIGGER ... DELETE ON p BEGIN +** DELETE FROM c WHERE ck = old.pk; +** END; +** +** The returned pointer is cached as part of the foreign key object. It +** is eventually freed along with the rest of the foreign key object by +** sqlite3FkDelete(). +*/ +static Trigger *fkActionTrigger( + Parse *pParse, /* Parse context */ + Table *pTab, /* Table being updated or deleted from */ + FKey *pFKey, /* Foreign key to get action for */ + ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + int action; /* One of OE_None, OE_Cascade etc. */ + Trigger *pTrigger; /* Trigger definition to return */ + int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */ + + action = pFKey->aAction[iAction]; + pTrigger = pFKey->apTrigger[iAction]; + + if( action!=OE_None && !pTrigger ){ + u8 enableLookaside; /* Copy of db->lookaside.bEnabled */ + char const *zFrom; /* Name of child table */ + int nFrom; /* Length in bytes of zFrom */ + Index *pIdx = 0; /* Parent key index for this FK */ + int *aiCol = 0; /* child table cols -> parent key cols */ + TriggerStep *pStep = 0; /* First (only) step of trigger program */ + Expr *pWhere = 0; /* WHERE clause of trigger step */ + ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */ + Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */ + int i; /* Iterator variable */ + Expr *pWhen = 0; /* WHEN clause for the trigger */ + + if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; + assert( aiCol || pFKey->nCol==1 ); + + for(i=0; inCol; i++){ + Token tOld = { "old", 3 }; /* Literal "old" token */ + Token tNew = { "new", 3 }; /* Literal "new" token */ + Token tFromCol; /* Name of column in child table */ + Token tToCol; /* Name of column in parent table */ + int iFromCol; /* Idx of column in child table */ + Expr *pEq; /* tFromCol = OLD.tToCol */ + + iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; + assert( iFromCol>=0 ); + tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid"; + tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName; + + tToCol.n = sqlite3Strlen30(tToCol.z); + tFromCol.n = sqlite3Strlen30(tFromCol.z); + + /* Create the expression "OLD.zToCol = zFromCol". It is important + ** that the "OLD.zToCol" term is on the LHS of the = operator, so + ** that the affinity and collation sequence associated with the + ** parent table are used for the comparison. */ + pEq = sqlite3PExpr(pParse, TK_EQ, + sqlite3PExpr(pParse, TK_DOT, + sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol) + , 0), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol) + , 0); + pWhere = sqlite3ExprAnd(db, pWhere, pEq); + + /* For ON UPDATE, construct the next term of the WHEN clause. + ** The final WHEN clause will be like this: + ** + ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) + */ + if( pChanges ){ + pEq = sqlite3PExpr(pParse, TK_IS, + sqlite3PExpr(pParse, TK_DOT, + sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol), + 0), + sqlite3PExpr(pParse, TK_DOT, + sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol), + 0), + 0); + pWhen = sqlite3ExprAnd(db, pWhen, pEq); + } + + if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){ + Expr *pNew; + if( action==OE_Cascade ){ + pNew = sqlite3PExpr(pParse, TK_DOT, + sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol) + , 0); + }else if( action==OE_SetDflt ){ + Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt; + if( pDflt ){ + pNew = sqlite3ExprDup(db, pDflt, 0); + }else{ + pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0); + } + }else{ + pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0); + } + pList = sqlite3ExprListAppend(pParse, pList, pNew); + sqlite3ExprListSetName(pParse, pList, &tFromCol, 0); + } + } + sqlite3DbFree(db, aiCol); + + zFrom = pFKey->pFrom->zName; + nFrom = sqlite3Strlen30(zFrom); + + if( action==OE_Restrict ){ + Token tFrom; + Expr *pRaise; + + tFrom.z = zFrom; + tFrom.n = nFrom; + pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed"); + if( pRaise ){ + pRaise->affinity = OE_Abort; + } + pSelect = sqlite3SelectNew(pParse, + sqlite3ExprListAppend(pParse, 0, pRaise), + sqlite3SrcListAppend(db, 0, &tFrom, 0), + pWhere, + 0, 0, 0, 0, 0, 0 + ); + pWhere = 0; + } + + /* Disable lookaside memory allocation */ + enableLookaside = db->lookaside.bEnabled; + db->lookaside.bEnabled = 0; + + pTrigger = (Trigger *)sqlite3DbMallocZero(db, + sizeof(Trigger) + /* struct Trigger */ + sizeof(TriggerStep) + /* Single step in trigger program */ + nFrom + 1 /* Space for pStep->target.z */ + ); + if( pTrigger ){ + pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1]; + pStep->target.z = (char *)&pStep[1]; + pStep->target.n = nFrom; + memcpy((char *)pStep->target.z, zFrom, nFrom); + + pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); + pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + if( pWhen ){ + pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0); + pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); + } + } + + /* Re-enable the lookaside buffer, if it was disabled earlier. */ + db->lookaside.bEnabled = enableLookaside; + + sqlite3ExprDelete(db, pWhere); + sqlite3ExprDelete(db, pWhen); + sqlite3ExprListDelete(db, pList); + sqlite3SelectDelete(db, pSelect); + if( db->mallocFailed==1 ){ + fkTriggerDelete(db, pTrigger); + return 0; + } + assert( pStep!=0 ); + + switch( action ){ + case OE_Restrict: + pStep->op = TK_SELECT; + break; + case OE_Cascade: + if( !pChanges ){ + pStep->op = TK_DELETE; + break; + } + default: + pStep->op = TK_UPDATE; + } + pStep->pTrig = pTrigger; + pTrigger->pSchema = pTab->pSchema; + pTrigger->pTabSchema = pTab->pSchema; + pFKey->apTrigger[iAction] = pTrigger; + pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE); + } + + return pTrigger; +} + +/* +** This function is called when deleting or updating a row to implement +** any required CASCADE, SET NULL or SET DEFAULT actions. +*/ +SQLITE_PRIVATE void sqlite3FkActions( + Parse *pParse, /* Parse context */ + Table *pTab, /* Table being updated or deleted from */ + ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */ + int regOld, /* Address of array containing old row */ + int *aChange, /* Array indicating UPDATEd columns (or 0) */ + int bChngRowid /* True if rowid is UPDATEd */ +){ + /* If foreign-key support is enabled, iterate through all FKs that + ** refer to table pTab. If there is an action associated with the FK + ** for this operation (either update or delete), invoke the associated + ** trigger sub-program. */ + if( pParse->db->flags&SQLITE_ForeignKeys ){ + FKey *pFKey; /* Iterator variable */ + for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ + if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){ + Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges); + if( pAct ){ + sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0); + } + } + } + } +} + +#endif /* ifndef SQLITE_OMIT_TRIGGER */ + +/* +** Free all memory associated with foreign key definitions attached to +** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash +** hash table. +*/ +SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){ + FKey *pFKey; /* Iterator variable */ + FKey *pNext; /* Copy of pFKey->pNextFrom */ + + assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) ); + for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){ + + /* Remove the FK from the fkeyHash hash table. */ + if( !db || db->pnBytesFreed==0 ){ + if( pFKey->pPrevTo ){ + pFKey->pPrevTo->pNextTo = pFKey->pNextTo; + }else{ + void *p = (void *)pFKey->pNextTo; + const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo); + sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p); + } + if( pFKey->pNextTo ){ + pFKey->pNextTo->pPrevTo = pFKey->pPrevTo; + } + } + + /* EV: R-30323-21917 Each foreign key constraint in SQLite is + ** classified as either immediate or deferred. + */ + assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 ); + + /* Delete any triggers created to implement actions for this FK. */ +#ifndef SQLITE_OMIT_TRIGGER + fkTriggerDelete(db, pFKey->apTrigger[0]); + fkTriggerDelete(db, pFKey->apTrigger[1]); +#endif + + pNext = pFKey->pNextFrom; + sqlite3DbFree(db, pFKey); + } +} +#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */ + +/************** End of fkey.c ************************************************/ +/************** Begin file insert.c ******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that are called by the parser +** to handle INSERT statements in SQLite. +*/ + +/* +** Generate code that will open a table for reading. +*/ +SQLITE_PRIVATE void sqlite3OpenTable( + Parse *p, /* Generate code into this VDBE */ + int iCur, /* The cursor number of the table */ + int iDb, /* The database index in sqlite3.aDb[] */ + Table *pTab, /* The table to be opened */ + int opcode /* OP_OpenRead or OP_OpenWrite */ +){ + Vdbe *v; + assert( !IsVirtual(pTab) ); + v = sqlite3GetVdbe(p); + assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); + sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName); + sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb); + sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32); + VdbeComment((v, "%s", pTab->zName)); +} + +/* +** Return a pointer to the column affinity string associated with index +** pIdx. A column affinity string has one character for each column in +** the table, according to the affinity of the column: +** +** Character Column affinity +** ------------------------------ +** 'a' TEXT +** 'b' NONE +** 'c' NUMERIC +** 'd' INTEGER +** 'e' REAL +** +** An extra 'd' is appended to the end of the string to cover the +** rowid that appears as the last column in every index. +** +** Memory for the buffer containing the column index affinity string +** is managed along with the rest of the Index structure. It will be +** released when sqlite3DeleteIndex() is called. +*/ +SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ + if( !pIdx->zColAff ){ + /* The first time a column affinity string for a particular index is + ** required, it is allocated and populated here. It is then stored as + ** a member of the Index structure for subsequent use. + ** + ** The column affinity string will eventually be deleted by + ** sqliteDeleteIndex() when the Index structure itself is cleaned + ** up. + */ + int n; + Table *pTab = pIdx->pTable; + sqlite3 *db = sqlite3VdbeDb(v); + pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2); + if( !pIdx->zColAff ){ + db->mallocFailed = 1; + return 0; + } + for(n=0; nnColumn; n++){ + pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; + } + pIdx->zColAff[n++] = SQLITE_AFF_INTEGER; + pIdx->zColAff[n] = 0; + } + + return pIdx->zColAff; +} + +/* +** Set P4 of the most recently inserted opcode to a column affinity +** string for table pTab. A column affinity string has one character +** for each column indexed by the index, according to the affinity of the +** column: +** +** Character Column affinity +** ------------------------------ +** 'a' TEXT +** 'b' NONE +** 'c' NUMERIC +** 'd' INTEGER +** 'e' REAL +*/ +SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ + /* The first time a column affinity string for a particular table + ** is required, it is allocated and populated here. It is then + ** stored as a member of the Table structure for subsequent use. + ** + ** The column affinity string will eventually be deleted by + ** sqlite3DeleteTable() when the Table structure itself is cleaned up. + */ + if( !pTab->zColAff ){ + char *zColAff; + int i; + sqlite3 *db = sqlite3VdbeDb(v); + + zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); + if( !zColAff ){ + db->mallocFailed = 1; + return; + } + + for(i=0; inCol; i++){ + zColAff[i] = pTab->aCol[i].affinity; + } + zColAff[pTab->nCol] = '\0'; + + pTab->zColAff = zColAff; + } + + sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT); +} + +/* +** Return non-zero if the table pTab in database iDb or any of its indices +** have been opened at any point in the VDBE program beginning at location +** iStartAddr throught the end of the program. This is used to see if +** a statement of the form "INSERT INTO SELECT ..." can +** run without using temporary table for the results of the SELECT. +*/ +static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){ + Vdbe *v = sqlite3GetVdbe(p); + int i; + int iEnd = sqlite3VdbeCurrentAddr(v); +#ifndef SQLITE_OMIT_VIRTUALTABLE + VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; +#endif + + for(i=iStartAddr; iopcode==OP_OpenRead && pOp->p3==iDb ){ + Index *pIndex; + int tnum = pOp->p2; + if( tnum==pTab->tnum ){ + return 1; + } + for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ + if( tnum==pIndex->tnum ){ + return 1; + } + } + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ + assert( pOp->p4.pVtab!=0 ); + assert( pOp->p4type==P4_VTAB ); + return 1; + } +#endif + } + return 0; +} + +#ifndef SQLITE_OMIT_AUTOINCREMENT +/* +** Locate or create an AutoincInfo structure associated with table pTab +** which is in database iDb. Return the register number for the register +** that holds the maximum rowid. +** +** There is at most one AutoincInfo structure per table even if the +** same table is autoincremented multiple times due to inserts within +** triggers. A new AutoincInfo structure is created if this is the +** first use of table pTab. On 2nd and subsequent uses, the original +** AutoincInfo structure is used. +** +** Three memory locations are allocated: +** +** (1) Register to hold the name of the pTab table. +** (2) Register to hold the maximum ROWID of pTab. +** (3) Register to hold the rowid in sqlite_sequence of pTab +** +** The 2nd register is the one that is returned. That is all the +** insert routine needs to know about. +*/ +static int autoIncBegin( + Parse *pParse, /* Parsing context */ + int iDb, /* Index of the database holding pTab */ + Table *pTab /* The table we are writing to */ +){ + int memId = 0; /* Register holding maximum rowid */ + if( pTab->tabFlags & TF_Autoincrement ){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + AutoincInfo *pInfo; + + pInfo = pToplevel->pAinc; + while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } + if( pInfo==0 ){ + pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo)); + if( pInfo==0 ) return 0; + pInfo->pNext = pToplevel->pAinc; + pToplevel->pAinc = pInfo; + pInfo->pTab = pTab; + pInfo->iDb = iDb; + pToplevel->nMem++; /* Register to hold name of table */ + pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ + pToplevel->nMem++; /* Rowid in sqlite_sequence */ + } + memId = pInfo->regCtr; + } + return memId; +} + +/* +** This routine generates code that will initialize all of the +** register used by the autoincrement tracker. +*/ +SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){ + AutoincInfo *p; /* Information about an AUTOINCREMENT */ + sqlite3 *db = pParse->db; /* The database connection */ + Db *pDb; /* Database only autoinc table */ + int memId; /* Register holding max rowid */ + int addr; /* A VDBE address */ + Vdbe *v = pParse->pVdbe; /* VDBE under construction */ + + /* This routine is never called during trigger-generation. It is + ** only called from the top-level */ + assert( pParse->pTriggerTab==0 ); + assert( pParse==sqlite3ParseToplevel(pParse) ); + + assert( v ); /* We failed long ago if this is not so */ + for(p = pParse->pAinc; p; p = p->pNext){ + pDb = &db->aDb[p->iDb]; + memId = p->regCtr; + assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); + sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); + sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1); + addr = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0); + sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); + sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId); + sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); + sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); + sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); + sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9); + sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); + sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); + sqlite3VdbeAddOp0(v, OP_Close); + } +} + +/* +** Update the maximum rowid for an autoincrement calculation. +** +** This routine should be called when the top of the stack holds a +** new rowid that is about to be inserted. If that new rowid is +** larger than the maximum rowid in the memId memory cell, then the +** memory cell is updated. The stack is unchanged. +*/ +static void autoIncStep(Parse *pParse, int memId, int regRowid){ + if( memId>0 ){ + sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); + } +} + +/* +** This routine generates the code needed to write autoincrement +** maximum rowid values back into the sqlite_sequence register. +** Every statement that might do an INSERT into an autoincrement +** table (either directly or through triggers) needs to call this +** routine just before the "exit" code. +*/ +SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){ + AutoincInfo *p; + Vdbe *v = pParse->pVdbe; + sqlite3 *db = pParse->db; + + assert( v ); + for(p = pParse->pAinc; p; p = p->pNext){ + Db *pDb = &db->aDb[p->iDb]; + int j1, j2, j3, j4, j5; + int iRec; + int memId = p->regCtr; + + iRec = sqlite3GetTempReg(pParse); + assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); + sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); + j2 = sqlite3VdbeAddOp0(v, OP_Rewind); + j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec); + j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec); + sqlite3VdbeAddOp2(v, OP_Next, 0, j3); + sqlite3VdbeJumpHere(v, j2); + sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1); + j5 = sqlite3VdbeAddOp0(v, OP_Goto); + sqlite3VdbeJumpHere(v, j4); + sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeJumpHere(v, j5); + sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); + sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3VdbeAddOp0(v, OP_Close); + sqlite3ReleaseTempReg(pParse, iRec); + } +} +#else +/* +** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines +** above are all no-ops +*/ +# define autoIncBegin(A,B,C) (0) +# define autoIncStep(A,B,C) +#endif /* SQLITE_OMIT_AUTOINCREMENT */ + + +/* +** Generate code for a co-routine that will evaluate a subquery one +** row at a time. +** +** The pSelect parameter is the subquery that the co-routine will evaluation. +** Information about the location of co-routine and the registers it will use +** is returned by filling in the pDest object. +** +** Registers are allocated as follows: +** +** pDest->iSDParm The register holding the next entry-point of the +** co-routine. Run the co-routine to its next breakpoint +** by calling "OP_Yield $X" where $X is pDest->iSDParm. +** +** pDest->iSDParm+1 The register holding the "completed" flag for the +** co-routine. This register is 0 if the previous Yield +** generated a new result row, or 1 if the subquery +** has completed. If the Yield is called again +** after this register becomes 1, then the VDBE will +** halt with an SQLITE_INTERNAL error. +** +** pDest->iSdst First result register. +** +** pDest->nSdst Number of result registers. +** +** This routine handles all of the register allocation and fills in the +** pDest structure appropriately. +** +** Here is a schematic of the generated code assuming that X is the +** co-routine entry-point register reg[pDest->iSDParm], that EOF is the +** completed flag reg[pDest->iSDParm+1], and R and S are the range of +** registers that hold the result set, reg[pDest->iSdst] through +** reg[pDest->iSdst+pDest->nSdst-1]: +** +** X <- A +** EOF <- 0 +** goto B +** A: setup for the SELECT +** loop rows in the SELECT +** load results into registers R..S +** yield X +** end loop +** cleanup after the SELECT +** EOF <- 1 +** yield X +** halt-error +** B: +** +** To use this subroutine, the caller generates code as follows: +** +** [ Co-routine generated by this subroutine, shown above ] +** S: yield X +** if EOF goto E +** if skip this row, goto C +** if terminate loop, goto E +** deal with this row +** C: goto S +** E: +*/ +SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){ + int regYield; /* Register holding co-routine entry-point */ + int regEof; /* Register holding co-routine completion flag */ + int addrTop; /* Top of the co-routine */ + int j1; /* Jump instruction */ + int rc; /* Result code */ + Vdbe *v; /* VDBE under construction */ + + regYield = ++pParse->nMem; + regEof = ++pParse->nMem; + v = sqlite3GetVdbe(pParse); + addrTop = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */ + VdbeComment((v, "Co-routine entry point")); + sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */ + VdbeComment((v, "Co-routine completion flag")); + sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield); + j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); + rc = sqlite3Select(pParse, pSelect, pDest); + assert( pParse->nErr==0 || rc ); + if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM; + if( rc ) return rc; + sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */ + sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */ + sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort); + VdbeComment((v, "End of coroutine")); + sqlite3VdbeJumpHere(v, j1); /* label B: */ + return rc; +} + + + +/* Forward declaration */ +static int xferOptimization( + Parse *pParse, /* Parser context */ + Table *pDest, /* The table we are inserting into */ + Select *pSelect, /* A SELECT statement to use as the data source */ + int onError, /* How to handle constraint errors */ + int iDbDest /* The database of pDest */ +); + +/* +** This routine is call to handle SQL of the following forms: +** +** insert into TABLE (IDLIST) values(EXPRLIST) +** insert into TABLE (IDLIST) select +** +** The IDLIST following the table name is always optional. If omitted, +** then a list of all columns for the table is substituted. The IDLIST +** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. +** +** The pList parameter holds EXPRLIST in the first form of the INSERT +** statement above, and pSelect is NULL. For the second form, pList is +** NULL and pSelect is a pointer to the select statement used to generate +** data for the insert. +** +** The code generated follows one of four templates. For a simple +** select with data coming from a VALUES clause, the code executes +** once straight down through. Pseudo-code follows (we call this +** the "1st template"): +** +** open write cursor to
and its indices +** puts VALUES clause expressions onto the stack +** write the resulting record into
+** cleanup +** +** The three remaining templates assume the statement is of the form +** +** INSERT INTO
SELECT ... +** +** If the SELECT clause is of the restricted form "SELECT * FROM " - +** in other words if the SELECT pulls all columns from a single table +** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and +** if and are distinct tables but have identical +** schemas, including all the same indices, then a special optimization +** is invoked that copies raw records from over to . +** See the xferOptimization() function for the implementation of this +** template. This is the 2nd template. +** +** open a write cursor to
+** open read cursor on +** transfer all records in over to
+** close cursors +** foreach index on
+** open a write cursor on the
index +** open a read cursor on the corresponding index +** transfer all records from the read to the write cursors +** close cursors +** end foreach +** +** The 3rd template is for when the second template does not apply +** and the SELECT clause does not read from
at any time. +** The generated code follows this template: +** +** EOF <- 0 +** X <- A +** goto B +** A: setup for the SELECT +** loop over the rows in the SELECT +** load values into registers R..R+n +** yield X +** end loop +** cleanup after the SELECT +** EOF <- 1 +** yield X +** goto A +** B: open write cursor to
and its indices +** C: yield X +** if EOF goto D +** insert the select result into
from R..R+n +** goto C +** D: cleanup +** +** The 4th template is used if the insert statement takes its +** values from a SELECT but the data is being inserted into a table +** that is also read as part of the SELECT. In the third form, +** we have to use a intermediate table to store the results of +** the select. The template is like this: +** +** EOF <- 0 +** X <- A +** goto B +** A: setup for the SELECT +** loop over the tables in the SELECT +** load value into register R..R+n +** yield X +** end loop +** cleanup after the SELECT +** EOF <- 1 +** yield X +** halt-error +** B: open temp table +** L: yield X +** if EOF goto M +** insert row from R..R+n into temp table +** goto L +** M: open write cursor to
and its indices +** rewind temp table +** C: loop over rows of intermediate table +** transfer values form intermediate table into
+** end loop +** D: cleanup +*/ +SQLITE_PRIVATE void sqlite3Insert( + Parse *pParse, /* Parser context */ + SrcList *pTabList, /* Name of table into which we are inserting */ + ExprList *pList, /* List of values to be inserted */ + Select *pSelect, /* A SELECT statement to use as the data source */ + IdList *pColumn, /* Column names corresponding to IDLIST. */ + int onError /* How to handle constraint errors */ +){ + sqlite3 *db; /* The main database structure */ + Table *pTab; /* The table to insert into. aka TABLE */ + char *zTab; /* Name of the table into which we are inserting */ + const char *zDb; /* Name of the database holding this table */ + int i, j, idx; /* Loop counters */ + Vdbe *v; /* Generate code into this virtual machine */ + Index *pIdx; /* For looping over indices of the table */ + int nColumn; /* Number of columns in the data */ + int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ + int baseCur = 0; /* VDBE Cursor number for pTab */ + int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ + int endOfLoop; /* Label for the end of the insertion loop */ + int useTempTable = 0; /* Store SELECT results in intermediate table */ + int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ + int addrInsTop = 0; /* Jump to label "D" */ + int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ + int addrSelect = 0; /* Address of coroutine that implements the SELECT */ + SelectDest dest; /* Destination for SELECT on rhs of INSERT */ + int iDb; /* Index of database holding TABLE */ + Db *pDb; /* The database containing table being inserted into */ + int appendFlag = 0; /* True if the insert is likely to be an append */ + + /* Register allocations */ + int regFromSelect = 0;/* Base register for data coming from SELECT */ + int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ + int regRowCount = 0; /* Memory cell used for the row counter */ + int regIns; /* Block of regs holding rowid+data being inserted */ + int regRowid; /* registers holding insert rowid */ + int regData; /* register holding first column to insert */ + int regEof = 0; /* Register recording end of SELECT data */ + int *aRegIdx = 0; /* One register allocated to each index */ + +#ifndef SQLITE_OMIT_TRIGGER + int isView; /* True if attempting to insert into a view */ + Trigger *pTrigger; /* List of triggers on pTab, if required */ + int tmask; /* Mask of trigger times */ +#endif + + db = pParse->db; + memset(&dest, 0, sizeof(dest)); + if( pParse->nErr || db->mallocFailed ){ + goto insert_cleanup; + } + + /* Locate the table into which we will be inserting new information. + */ + assert( pTabList->nSrc==1 ); + zTab = pTabList->a[0].zName; + if( NEVER(zTab==0) ) goto insert_cleanup; + pTab = sqlite3SrcListLookup(pParse, pTabList); + if( pTab==0 ){ + goto insert_cleanup; + } + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( iDbnDb ); + pDb = &db->aDb[iDb]; + zDb = pDb->zName; + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ + goto insert_cleanup; + } + + /* Figure out if we have any triggers and if the table being + ** inserted into is a view + */ +#ifndef SQLITE_OMIT_TRIGGER + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); + isView = pTab->pSelect!=0; +#else +# define pTrigger 0 +# define tmask 0 +# define isView 0 +#endif +#ifdef SQLITE_OMIT_VIEW +# undef isView +# define isView 0 +#endif + assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); + + /* If pTab is really a view, make sure it has been initialized. + ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual + ** module table). + */ + if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto insert_cleanup; + } + + /* Ensure that: + * (a) the table is not read-only, + * (b) that if it is a view then ON INSERT triggers exist + */ + if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ + goto insert_cleanup; + } + + /* Allocate a VDBE + */ + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto insert_cleanup; + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); + sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); + +#ifndef SQLITE_OMIT_XFER_OPT + /* If the statement is of the form + ** + ** INSERT INTO SELECT * FROM ; + ** + ** Then special optimizations can be applied that make the transfer + ** very fast and which reduce fragmentation of indices. + ** + ** This is the 2nd template. + */ + if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ + assert( !pTrigger ); + assert( pList==0 ); + goto insert_end; + } +#endif /* SQLITE_OMIT_XFER_OPT */ + + /* If this is an AUTOINCREMENT table, look up the sequence number in the + ** sqlite_sequence table and store it in memory cell regAutoinc. + */ + regAutoinc = autoIncBegin(pParse, iDb, pTab); + + /* Figure out how many columns of data are supplied. If the data + ** is coming from a SELECT statement, then generate a co-routine that + ** produces a single row of the SELECT on each invocation. The + ** co-routine is the common header to the 3rd and 4th templates. + */ + if( pSelect ){ + /* Data is coming from a SELECT. Generate a co-routine to run that + ** SELECT. */ + int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest); + if( rc ) goto insert_cleanup; + + regEof = dest.iSDParm + 1; + regFromSelect = dest.iSdst; + assert( pSelect->pEList ); + nColumn = pSelect->pEList->nExpr; + assert( dest.nSdst==nColumn ); + + /* Set useTempTable to TRUE if the result of the SELECT statement + ** should be written into a temporary table (template 4). Set to + ** FALSE if each* row of the SELECT can be written directly into + ** the destination table (template 3). + ** + ** A temp table must be used if the table being updated is also one + ** of the tables being read by the SELECT statement. Also use a + ** temp table in the case of row triggers. + */ + if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){ + useTempTable = 1; + } + + if( useTempTable ){ + /* Invoke the coroutine to extract information from the SELECT + ** and add it to a transient table srcTab. The code generated + ** here is from the 4th template: + ** + ** B: open temp table + ** L: yield X + ** if EOF goto M + ** insert row from R..R+n into temp table + ** goto L + ** M: ... + */ + int regRec; /* Register to hold packed record */ + int regTempRowid; /* Register to hold temp table ROWID */ + int addrTop; /* Label "L" */ + int addrIf; /* Address of jump to M */ + + srcTab = pParse->nTab++; + regRec = sqlite3GetTempReg(pParse); + regTempRowid = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); + addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); + addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); + sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); + sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); + sqlite3VdbeJumpHere(v, addrIf); + sqlite3ReleaseTempReg(pParse, regRec); + sqlite3ReleaseTempReg(pParse, regTempRowid); + } + }else{ + /* This is the case if the data for the INSERT is coming from a VALUES + ** clause + */ + NameContext sNC; + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + srcTab = -1; + assert( useTempTable==0 ); + nColumn = pList ? pList->nExpr : 0; + for(i=0; ia[i].pExpr) ){ + goto insert_cleanup; + } + } + } + + /* Make sure the number of columns in the source data matches the number + ** of columns to be inserted into the table. + */ + if( IsVirtual(pTab) ){ + for(i=0; inCol; i++){ + nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); + } + } + if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ + sqlite3ErrorMsg(pParse, + "table %S has %d columns but %d values were supplied", + pTabList, 0, pTab->nCol-nHidden, nColumn); + goto insert_cleanup; + } + if( pColumn!=0 && nColumn!=pColumn->nId ){ + sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); + goto insert_cleanup; + } + + /* If the INSERT statement included an IDLIST term, then make sure + ** all elements of the IDLIST really are columns of the table and + ** remember the column indices. + ** + ** If the table has an INTEGER PRIMARY KEY column and that column + ** is named in the IDLIST, then record in the keyColumn variable + ** the index into IDLIST of the primary key column. keyColumn is + ** the index of the primary key as it appears in IDLIST, not as + ** is appears in the original table. (The index of the primary + ** key in the original table is pTab->iPKey.) + */ + if( pColumn ){ + for(i=0; inId; i++){ + pColumn->a[i].idx = -1; + } + for(i=0; inId; i++){ + for(j=0; jnCol; j++){ + if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ + pColumn->a[i].idx = j; + if( j==pTab->iPKey ){ + keyColumn = i; + } + break; + } + } + if( j>=pTab->nCol ){ + if( sqlite3IsRowid(pColumn->a[i].zName) ){ + keyColumn = i; + }else{ + sqlite3ErrorMsg(pParse, "table %S has no column named %s", + pTabList, 0, pColumn->a[i].zName); + pParse->checkSchema = 1; + goto insert_cleanup; + } + } + } + } + + /* If there is no IDLIST term but the table has an integer primary + ** key, the set the keyColumn variable to the primary key column index + ** in the original table definition. + */ + if( pColumn==0 && nColumn>0 ){ + keyColumn = pTab->iPKey; + } + + /* Initialize the count of rows to be inserted + */ + if( db->flags & SQLITE_CountRows ){ + regRowCount = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); + } + + /* If this is not a view, open the table and and all indices */ + if( !isView ){ + int nIdx; + + baseCur = pParse->nTab; + nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); + aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); + if( aRegIdx==0 ){ + goto insert_cleanup; + } + for(i=0; inMem; + } + } + + /* This is the top of the main insertion loop */ + if( useTempTable ){ + /* This block codes the top of loop only. The complete loop is the + ** following pseudocode (template 4): + ** + ** rewind temp table + ** C: loop over rows of intermediate table + ** transfer values form intermediate table into
+ ** end loop + ** D: ... + */ + addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); + addrCont = sqlite3VdbeCurrentAddr(v); + }else if( pSelect ){ + /* This block codes the top of loop only. The complete loop is the + ** following pseudocode (template 3): + ** + ** C: yield X + ** if EOF goto D + ** insert the select result into
from R..R+n + ** goto C + ** D: ... + */ + addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); + addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof); + } + + /* Allocate registers for holding the rowid of the new row, + ** the content of the new row, and the assemblied row record. + */ + regRowid = regIns = pParse->nMem+1; + pParse->nMem += pTab->nCol + 1; + if( IsVirtual(pTab) ){ + regRowid++; + pParse->nMem++; + } + regData = regRowid+1; + + /* Run the BEFORE and INSTEAD OF triggers, if there are any + */ + endOfLoop = sqlite3VdbeMakeLabel(v); + if( tmask & TRIGGER_BEFORE ){ + int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); + + /* build the NEW.* reference row. Note that if there is an INTEGER + ** PRIMARY KEY into which a NULL is being inserted, that NULL will be + ** translated into a unique ID for the row. But on a BEFORE trigger, + ** we do not know what the unique ID will be (because the insert has + ** not happened yet) so we substitute a rowid of -1 + */ + if( keyColumn<0 ){ + sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); + }else{ + int j1; + if( useTempTable ){ + sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols); + }else{ + assert( pSelect==0 ); /* Otherwise useTempTable is true */ + sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols); + } + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); + sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); + } + + /* Cannot have triggers on a virtual table. If it were possible, + ** this block would have to account for hidden column. + */ + assert( !IsVirtual(pTab) ); + + /* Create the new column data + */ + for(i=0; inCol; i++){ + if( pColumn==0 ){ + j = i; + }else{ + for(j=0; jnId; j++){ + if( pColumn->a[j].idx==i ) break; + } + } + if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){ + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); + }else if( useTempTable ){ + sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); + }else{ + assert( pSelect==0 ); /* Otherwise useTempTable is true */ + sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); + } + } + + /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, + ** do not attempt any conversions before assembling the record. + ** If this is a real table, attempt conversions as required by the + ** table column affinities. + */ + if( !isView ){ + sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol); + sqlite3TableAffinityStr(v, pTab); + } + + /* Fire BEFORE or INSTEAD OF triggers */ + sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, + pTab, regCols-pTab->nCol-1, onError, endOfLoop); + + sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); + } + + /* Push the record number for the new entry onto the stack. The + ** record number is a randomly generate integer created by NewRowid + ** except when the table has an INTEGER PRIMARY KEY column, in which + ** case the record number is the same as that column. + */ + if( !isView ){ + if( IsVirtual(pTab) ){ + /* The row that the VUpdate opcode will delete: none */ + sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); + } + if( keyColumn>=0 ){ + if( useTempTable ){ + sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); + }else if( pSelect ){ + sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); + }else{ + VdbeOp *pOp; + sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); + pOp = sqlite3VdbeGetOp(v, -1); + if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ + appendFlag = 1; + pOp->opcode = OP_NewRowid; + pOp->p1 = baseCur; + pOp->p2 = regRowid; + pOp->p3 = regAutoinc; + } + } + /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid + ** to generate a unique primary key value. + */ + if( !appendFlag ){ + int j1; + if( !IsVirtual(pTab) ){ + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); + sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); + sqlite3VdbeJumpHere(v, j1); + }else{ + j1 = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); + } + sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); + } + }else if( IsVirtual(pTab) ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); + }else{ + sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); + appendFlag = 1; + } + autoIncStep(pParse, regAutoinc, regRowid); + + /* Push onto the stack, data for all columns of the new entry, beginning + ** with the first column. + */ + nHidden = 0; + for(i=0; inCol; i++){ + int iRegStore = regRowid+1+i; + if( i==pTab->iPKey ){ + /* The value of the INTEGER PRIMARY KEY column is always a NULL. + ** Whenever this column is read, the record number will be substituted + ** in its place. So will fill this column with a NULL to avoid + ** taking up data space with information that will never be used. */ + sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); + continue; + } + if( pColumn==0 ){ + if( IsHiddenColumn(&pTab->aCol[i]) ){ + assert( IsVirtual(pTab) ); + j = -1; + nHidden++; + }else{ + j = i - nHidden; + } + }else{ + for(j=0; jnId; j++){ + if( pColumn->a[j].idx==i ) break; + } + } + if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); + }else if( useTempTable ){ + sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); + }else if( pSelect ){ + sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); + }else{ + sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); + } + } + + /* Generate code to check constraints and generate index keys and + ** do the insertion. + */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); + sqlite3VtabMakeWritable(pParse, pTab); + sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); + sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); + sqlite3MayAbort(pParse); + }else +#endif + { + int isReplace; /* Set to true if constraints may cause a replace */ + sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx, + keyColumn>=0, 0, onError, endOfLoop, &isReplace + ); + sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); + sqlite3CompleteInsertion( + pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0 + ); + } + } + + /* Update the count of rows that are inserted + */ + if( (db->flags & SQLITE_CountRows)!=0 ){ + sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); + } + + if( pTrigger ){ + /* Code AFTER triggers */ + sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, + pTab, regData-2-pTab->nCol, onError, endOfLoop); + } + + /* The bottom of the main insertion loop, if the data source + ** is a SELECT statement. + */ + sqlite3VdbeResolveLabel(v, endOfLoop); + if( useTempTable ){ + sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); + sqlite3VdbeJumpHere(v, addrInsTop); + sqlite3VdbeAddOp1(v, OP_Close, srcTab); + }else if( pSelect ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont); + sqlite3VdbeJumpHere(v, addrInsTop); + } + + if( !IsVirtual(pTab) && !isView ){ + /* Close all tables opened */ + sqlite3VdbeAddOp1(v, OP_Close, baseCur); + for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ + sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur); + } + } + +insert_end: + /* Update the sqlite_sequence table by storing the content of the + ** maximum rowid counter values recorded while inserting into + ** autoincrement tables. + */ + if( pParse->nested==0 && pParse->pTriggerTab==0 ){ + sqlite3AutoincrementEnd(pParse); + } + + /* + ** Return the number of rows inserted. If this routine is + ** generating code because of a call to sqlite3NestedParse(), do not + ** invoke the callback function. + */ + if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ + sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); + } + +insert_cleanup: + sqlite3SrcListDelete(db, pTabList); + sqlite3ExprListDelete(db, pList); + sqlite3SelectDelete(db, pSelect); + sqlite3IdListDelete(db, pColumn); + sqlite3DbFree(db, aRegIdx); +} + +/* Make sure "isView" and other macros defined above are undefined. Otherwise +** thely may interfere with compilation of other functions in this file +** (or in another file, if this file becomes part of the amalgamation). */ +#ifdef isView + #undef isView +#endif +#ifdef pTrigger + #undef pTrigger +#endif +#ifdef tmask + #undef tmask +#endif + + +/* +** Generate code to do constraint checks prior to an INSERT or an UPDATE. +** +** The input is a range of consecutive registers as follows: +** +** 1. The rowid of the row after the update. +** +** 2. The data in the first column of the entry after the update. +** +** i. Data from middle columns... +** +** N. The data in the last column of the entry after the update. +** +** The regRowid parameter is the index of the register containing (1). +** +** If isUpdate is true and rowidChng is non-zero, then rowidChng contains +** the address of a register containing the rowid before the update takes +** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate +** is false, indicating an INSERT statement, then a non-zero rowidChng +** indicates that the rowid was explicitly specified as part of the +** INSERT statement. If rowidChng is false, it means that the rowid is +** computed automatically in an insert or that the rowid value is not +** modified by an update. +** +** The code generated by this routine store new index entries into +** registers identified by aRegIdx[]. No index entry is created for +** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is +** the same as the order of indices on the linked list of indices +** attached to the table. +** +** This routine also generates code to check constraints. NOT NULL, +** CHECK, and UNIQUE constraints are all checked. If a constraint fails, +** then the appropriate action is performed. There are five possible +** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. +** +** Constraint type Action What Happens +** --------------- ---------- ---------------------------------------- +** any ROLLBACK The current transaction is rolled back and +** sqlite3_exec() returns immediately with a +** return code of SQLITE_CONSTRAINT. +** +** any ABORT Back out changes from the current command +** only (do not do a complete rollback) then +** cause sqlite3_exec() to return immediately +** with SQLITE_CONSTRAINT. +** +** any FAIL Sqlite3_exec() returns immediately with a +** return code of SQLITE_CONSTRAINT. The +** transaction is not rolled back and any +** prior changes are retained. +** +** any IGNORE The record number and data is popped from +** the stack and there is an immediate jump +** to label ignoreDest. +** +** NOT NULL REPLACE The NULL value is replace by the default +** value for that column. If the default value +** is NULL, the action is the same as ABORT. +** +** UNIQUE REPLACE The other row that conflicts with the row +** being inserted is removed. +** +** CHECK REPLACE Illegal. The results in an exception. +** +** Which action to take is determined by the overrideError parameter. +** Or if overrideError==OE_Default, then the pParse->onError parameter +** is used. Or if pParse->onError==OE_Default then the onError value +** for the constraint is used. +** +** The calling routine must open a read/write cursor for pTab with +** cursor number "baseCur". All indices of pTab must also have open +** read/write cursors with cursor number baseCur+i for the i-th cursor. +** Except, if there is no possibility of a REPLACE action then +** cursors do not need to be open for indices where aRegIdx[i]==0. +*/ +SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( + Parse *pParse, /* The parser context */ + Table *pTab, /* the table into which we are inserting */ + int baseCur, /* Index of a read/write cursor pointing at pTab */ + int regRowid, /* Index of the range of input registers */ + int *aRegIdx, /* Register used by each index. 0 for unused indices */ + int rowidChng, /* True if the rowid might collide with existing entry */ + int isUpdate, /* True for UPDATE, False for INSERT */ + int overrideError, /* Override onError to this if not OE_Default */ + int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ + int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */ +){ + int i; /* loop counter */ + Vdbe *v; /* VDBE under constrution */ + int nCol; /* Number of columns */ + int onError; /* Conflict resolution strategy */ + int j1; /* Addresss of jump instruction */ + int j2 = 0, j3; /* Addresses of jump instructions */ + int regData; /* Register containing first data column */ + int iCur; /* Table cursor number */ + Index *pIdx; /* Pointer to one of the indices */ + sqlite3 *db; /* Database connection */ + int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ + int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid; + + db = pParse->db; + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); + assert( pTab->pSelect==0 ); /* This table is not a VIEW */ + nCol = pTab->nCol; + regData = regRowid + 1; + + /* Test all NOT NULL constraints. + */ + for(i=0; iiPKey ){ + continue; + } + onError = pTab->aCol[i].notNull; + if( onError==OE_None ) continue; + if( overrideError!=OE_Default ){ + onError = overrideError; + }else if( onError==OE_Default ){ + onError = OE_Abort; + } + if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ + onError = OE_Abort; + } + assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail + || onError==OE_Ignore || onError==OE_Replace ); + switch( onError ){ + case OE_Abort: + sqlite3MayAbort(pParse); + case OE_Rollback: + case OE_Fail: { + char *zMsg; + sqlite3VdbeAddOp3(v, OP_HaltIfNull, + SQLITE_CONSTRAINT_NOTNULL, onError, regData+i); + zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL", + pTab->zName, pTab->aCol[i].zName); + sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); + break; + } + case OE_Ignore: { + sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest); + break; + } + default: { + assert( onError==OE_Replace ); + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); + sqlite3VdbeJumpHere(v, j1); + break; + } + } + } + + /* Test all CHECK constraints + */ +#ifndef SQLITE_OMIT_CHECK + if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ + ExprList *pCheck = pTab->pCheck; + pParse->ckBase = regData; + onError = overrideError!=OE_Default ? overrideError : OE_Abort; + for(i=0; inExpr; i++){ + int allOk = sqlite3VdbeMakeLabel(v); + sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL); + if( onError==OE_Ignore ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + }else{ + char *zConsName = pCheck->a[i].zName; + if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ + if( zConsName ){ + zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName); + }else{ + zConsName = 0; + } + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, + onError, zConsName, P4_DYNAMIC); + } + sqlite3VdbeResolveLabel(v, allOk); + } + } +#endif /* !defined(SQLITE_OMIT_CHECK) */ + + /* If we have an INTEGER PRIMARY KEY, make sure the primary key + ** of the new record does not previously exist. Except, if this + ** is an UPDATE and the primary key is not changing, that is OK. + */ + if( rowidChng ){ + onError = pTab->keyConf; + if( overrideError!=OE_Default ){ + onError = overrideError; + }else if( onError==OE_Default ){ + onError = OE_Abort; + } + + if( isUpdate ){ + j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng); + } + j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); + switch( onError ){ + default: { + onError = OE_Abort; + /* Fall thru into the next case */ + } + case OE_Rollback: + case OE_Abort: + case OE_Fail: { + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY, + onError, "PRIMARY KEY must be unique", P4_STATIC); + break; + } + case OE_Replace: { + /* If there are DELETE triggers on this table and the + ** recursive-triggers flag is set, call GenerateRowDelete() to + ** remove the conflicting row from the table. This will fire + ** the triggers and remove both the table and index b-tree entries. + ** + ** Otherwise, if there are no triggers or the recursive-triggers + ** flag is not set, but the table has one or more indexes, call + ** GenerateRowIndexDelete(). This removes the index b-tree entries + ** only. The table b-tree entry will be replaced by the new entry + ** when it is inserted. + ** + ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, + ** also invoke MultiWrite() to indicate that this VDBE may require + ** statement rollback (if the statement is aborted after the delete + ** takes place). Earlier versions called sqlite3MultiWrite() regardless, + ** but being more selective here allows statements like: + ** + ** REPLACE INTO t(rowid) VALUES($newrowid) + ** + ** to run without a statement journal if there are no indexes on the + ** table. + */ + Trigger *pTrigger = 0; + if( db->flags&SQLITE_RecTriggers ){ + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); + } + if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ + sqlite3MultiWrite(pParse); + sqlite3GenerateRowDelete( + pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace + ); + }else if( pTab->pIndex ){ + sqlite3MultiWrite(pParse); + sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); + } + seenReplace = 1; + break; + } + case OE_Ignore: { + assert( seenReplace==0 ); + sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + break; + } + } + sqlite3VdbeJumpHere(v, j3); + if( isUpdate ){ + sqlite3VdbeJumpHere(v, j2); + } + } + + /* Test all UNIQUE constraints by creating entries for each UNIQUE + ** index and making sure that duplicate entries do not already exist. + ** Add the new records to the indices as we go. + */ + for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ + int regIdx; + int regR; + int addrSkipRow = 0; + + if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ + + if( pIdx->pPartIdxWhere ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]); + addrSkipRow = sqlite3VdbeMakeLabel(v); + pParse->ckBase = regData; + sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow, + SQLITE_JUMPIFNULL); + pParse->ckBase = 0; + } + + /* Create a key for accessing the index entry */ + regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); + for(i=0; inColumn; i++){ + int idx = pIdx->aiColumn[i]; + if( idx==pTab->iPKey ){ + sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); + }else{ + sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); + } + } + sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); + sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT); + sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1); + + /* Find out what action to take in case there is an indexing conflict */ + onError = pIdx->onError; + if( onError==OE_None ){ + sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); + sqlite3VdbeResolveLabel(v, addrSkipRow); + continue; /* pIdx is not a UNIQUE index */ + } + if( overrideError!=OE_Default ){ + onError = overrideError; + }else if( onError==OE_Default ){ + onError = OE_Abort; + } + if( seenReplace ){ + if( onError==OE_Ignore ) onError = OE_Replace; + else if( onError==OE_Fail ) onError = OE_Abort; + } + + /* Check to see if the new index entry will be unique */ + regR = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR); + j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, + regR, SQLITE_INT_TO_PTR(regIdx), + P4_INT32); + sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); + + /* Generate code that executes if the new index entry is not unique */ + assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail + || onError==OE_Ignore || onError==OE_Replace ); + switch( onError ){ + case OE_Rollback: + case OE_Abort: + case OE_Fail: { + int j; + StrAccum errMsg; + const char *zSep; + char *zErr; + + sqlite3StrAccumInit(&errMsg, 0, 0, 200); + errMsg.db = db; + zSep = pIdx->nColumn>1 ? "columns " : "column "; + for(j=0; jnColumn; j++){ + char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; + sqlite3StrAccumAppend(&errMsg, zSep, -1); + zSep = ", "; + sqlite3StrAccumAppend(&errMsg, zCol, -1); + } + sqlite3StrAccumAppend(&errMsg, + pIdx->nColumn>1 ? " are not unique" : " is not unique", -1); + zErr = sqlite3StrAccumFinish(&errMsg); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE, + onError, zErr, 0); + sqlite3DbFree(errMsg.db, zErr); + break; + } + case OE_Ignore: { + assert( seenReplace==0 ); + sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + break; + } + default: { + Trigger *pTrigger = 0; + assert( onError==OE_Replace ); + sqlite3MultiWrite(pParse); + if( db->flags&SQLITE_RecTriggers ){ + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); + } + sqlite3GenerateRowDelete( + pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace + ); + seenReplace = 1; + break; + } + } + sqlite3VdbeJumpHere(v, j3); + sqlite3VdbeResolveLabel(v, addrSkipRow); + sqlite3ReleaseTempReg(pParse, regR); + } + + if( pbMayReplace ){ + *pbMayReplace = seenReplace; + } +} + +/* +** This routine generates code to finish the INSERT or UPDATE operation +** that was started by a prior call to sqlite3GenerateConstraintChecks. +** A consecutive range of registers starting at regRowid contains the +** rowid and the content to be inserted. +** +** The arguments to this routine should be the same as the first six +** arguments to sqlite3GenerateConstraintChecks. +*/ +SQLITE_PRIVATE void sqlite3CompleteInsertion( + Parse *pParse, /* The parser context */ + Table *pTab, /* the table into which we are inserting */ + int baseCur, /* Index of a read/write cursor pointing at pTab */ + int regRowid, /* Range of content */ + int *aRegIdx, /* Register used by each index. 0 for unused indices */ + int isUpdate, /* True for UPDATE, False for INSERT */ + int appendBias, /* True if this is likely to be an append */ + int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ +){ + int i; + Vdbe *v; + Index *pIdx; + u8 pik_flags; + int regData; + int regRec; + + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); + assert( pTab->pSelect==0 ); /* This table is not a VIEW */ + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + if( aRegIdx[i]==0 ) continue; + if( pIdx->pPartIdxWhere ){ + sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); + } + sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); + if( useSeekResult ){ + sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + } + } + regData = regRowid + 1; + regRec = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); + sqlite3TableAffinityStr(v, pTab); + sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); + if( pParse->nested ){ + pik_flags = 0; + }else{ + pik_flags = OPFLAG_NCHANGE; + pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); + } + if( appendBias ){ + pik_flags |= OPFLAG_APPEND; + } + if( useSeekResult ){ + pik_flags |= OPFLAG_USESEEKRESULT; + } + sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); + if( !pParse->nested ){ + sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); + } + sqlite3VdbeChangeP5(v, pik_flags); +} + +/* +** Generate code that will open cursors for a table and for all +** indices of that table. The "baseCur" parameter is the cursor number used +** for the table. Indices are opened on subsequent cursors. +** +** Return the number of indices on the table. +*/ +SQLITE_PRIVATE int sqlite3OpenTableAndIndices( + Parse *pParse, /* Parsing context */ + Table *pTab, /* Table to be opened */ + int baseCur, /* Cursor number assigned to the table */ + int op /* OP_OpenRead or OP_OpenWrite */ +){ + int i; + int iDb; + Index *pIdx; + Vdbe *v; + + if( IsVirtual(pTab) ) return 0; + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); + sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); + for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + assert( pIdx->pSchema==pTab->pSchema ); + sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, + (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIdx->zName)); + } + if( pParse->nTabnTab = baseCur+i; + } + return i-1; +} + + +#ifdef SQLITE_TEST +/* +** The following global variable is incremented whenever the +** transfer optimization is used. This is used for testing +** purposes only - to make sure the transfer optimization really +** is happening when it is suppose to. +*/ +SQLITE_API int sqlite3_xferopt_count; +#endif /* SQLITE_TEST */ + + +#ifndef SQLITE_OMIT_XFER_OPT +/* +** Check to collation names to see if they are compatible. +*/ +static int xferCompatibleCollation(const char *z1, const char *z2){ + if( z1==0 ){ + return z2==0; + } + if( z2==0 ){ + return 0; + } + return sqlite3StrICmp(z1, z2)==0; +} + + +/* +** Check to see if index pSrc is compatible as a source of data +** for index pDest in an insert transfer optimization. The rules +** for a compatible index: +** +** * The index is over the same set of columns +** * The same DESC and ASC markings occurs on all columns +** * The same onError processing (OE_Abort, OE_Ignore, etc) +** * The same collating sequence on each column +** * The index has the exact same WHERE clause +*/ +static int xferCompatibleIndex(Index *pDest, Index *pSrc){ + int i; + assert( pDest && pSrc ); + assert( pDest->pTable!=pSrc->pTable ); + if( pDest->nColumn!=pSrc->nColumn ){ + return 0; /* Different number of columns */ + } + if( pDest->onError!=pSrc->onError ){ + return 0; /* Different conflict resolution strategies */ + } + for(i=0; inColumn; i++){ + if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ + return 0; /* Different columns indexed */ + } + if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ + return 0; /* Different sort orders */ + } + if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){ + return 0; /* Different collating sequences */ + } + } + if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ + return 0; /* Different WHERE clauses */ + } + + /* If no test above fails then the indices must be compatible */ + return 1; +} + +/* +** Attempt the transfer optimization on INSERTs of the form +** +** INSERT INTO tab1 SELECT * FROM tab2; +** +** The xfer optimization transfers raw records from tab2 over to tab1. +** Columns are not decoded and reassemblied, which greatly improves +** performance. Raw index records are transferred in the same way. +** +** The xfer optimization is only attempted if tab1 and tab2 are compatible. +** There are lots of rules for determining compatibility - see comments +** embedded in the code for details. +** +** This routine returns TRUE if the optimization is guaranteed to be used. +** Sometimes the xfer optimization will only work if the destination table +** is empty - a factor that can only be determined at run-time. In that +** case, this routine generates code for the xfer optimization but also +** does a test to see if the destination table is empty and jumps over the +** xfer optimization code if the test fails. In that case, this routine +** returns FALSE so that the caller will know to go ahead and generate +** an unoptimized transfer. This routine also returns FALSE if there +** is no chance that the xfer optimization can be applied. +** +** This optimization is particularly useful at making VACUUM run faster. +*/ +static int xferOptimization( + Parse *pParse, /* Parser context */ + Table *pDest, /* The table we are inserting into */ + Select *pSelect, /* A SELECT statement to use as the data source */ + int onError, /* How to handle constraint errors */ + int iDbDest /* The database of pDest */ +){ + ExprList *pEList; /* The result set of the SELECT */ + Table *pSrc; /* The table in the FROM clause of SELECT */ + Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ + struct SrcList_item *pItem; /* An element of pSelect->pSrc */ + int i; /* Loop counter */ + int iDbSrc; /* The database of pSrc */ + int iSrc, iDest; /* Cursors from source and destination */ + int addr1, addr2; /* Loop addresses */ + int emptyDestTest; /* Address of test for empty pDest */ + int emptySrcTest; /* Address of test for empty pSrc */ + Vdbe *v; /* The VDBE we are building */ + KeyInfo *pKey; /* Key information for an index */ + int regAutoinc; /* Memory register used by AUTOINC */ + int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ + int regData, regRowid; /* Registers holding data and rowid */ + + if( pSelect==0 ){ + return 0; /* Must be of the form INSERT INTO ... SELECT ... */ + } + if( sqlite3TriggerList(pParse, pDest) ){ + return 0; /* tab1 must not have triggers */ + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pDest->tabFlags & TF_Virtual ){ + return 0; /* tab1 must not be a virtual table */ + } +#endif + if( onError==OE_Default ){ + if( pDest->iPKey>=0 ) onError = pDest->keyConf; + if( onError==OE_Default ) onError = OE_Abort; + } + assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ + if( pSelect->pSrc->nSrc!=1 ){ + return 0; /* FROM clause must have exactly one term */ + } + if( pSelect->pSrc->a[0].pSelect ){ + return 0; /* FROM clause cannot contain a subquery */ + } + if( pSelect->pWhere ){ + return 0; /* SELECT may not have a WHERE clause */ + } + if( pSelect->pOrderBy ){ + return 0; /* SELECT may not have an ORDER BY clause */ + } + /* Do not need to test for a HAVING clause. If HAVING is present but + ** there is no ORDER BY, we will get an error. */ + if( pSelect->pGroupBy ){ + return 0; /* SELECT may not have a GROUP BY clause */ + } + if( pSelect->pLimit ){ + return 0; /* SELECT may not have a LIMIT clause */ + } + assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ + if( pSelect->pPrior ){ + return 0; /* SELECT may not be a compound query */ + } + if( pSelect->selFlags & SF_Distinct ){ + return 0; /* SELECT may not be DISTINCT */ + } + pEList = pSelect->pEList; + assert( pEList!=0 ); + if( pEList->nExpr!=1 ){ + return 0; /* The result set must have exactly one column */ + } + assert( pEList->a[0].pExpr ); + if( pEList->a[0].pExpr->op!=TK_ALL ){ + return 0; /* The result set must be the special operator "*" */ + } + + /* At this point we have established that the statement is of the + ** correct syntactic form to participate in this optimization. Now + ** we have to check the semantics. + */ + pItem = pSelect->pSrc->a; + pSrc = sqlite3LocateTableItem(pParse, 0, pItem); + if( pSrc==0 ){ + return 0; /* FROM clause does not contain a real table */ + } + if( pSrc==pDest ){ + return 0; /* tab1 and tab2 may not be the same table */ + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pSrc->tabFlags & TF_Virtual ){ + return 0; /* tab2 must not be a virtual table */ + } +#endif + if( pSrc->pSelect ){ + return 0; /* tab2 may not be a view */ + } + if( pDest->nCol!=pSrc->nCol ){ + return 0; /* Number of columns must be the same in tab1 and tab2 */ + } + if( pDest->iPKey!=pSrc->iPKey ){ + return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ + } + for(i=0; inCol; i++){ + if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){ + return 0; /* Affinity must be the same on all columns */ + } + if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){ + return 0; /* Collating sequence must be the same on all columns */ + } + if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){ + return 0; /* tab2 must be NOT NULL if tab1 is */ + } + } + for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ + if( pDestIdx->onError!=OE_None ){ + destHasUniqueIdx = 1; + } + for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ + if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; + } + if( pSrcIdx==0 ){ + return 0; /* pDestIdx has no corresponding index in pSrc */ + } + } +#ifndef SQLITE_OMIT_CHECK + if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ + return 0; /* Tables have different CHECK constraints. Ticket #2252 */ + } +#endif +#ifndef SQLITE_OMIT_FOREIGN_KEY + /* Disallow the transfer optimization if the destination table constains + ** any foreign key constraints. This is more restrictive than necessary. + ** But the main beneficiary of the transfer optimization is the VACUUM + ** command, and the VACUUM command disables foreign key constraints. So + ** the extra complication to make this rule less restrictive is probably + ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] + */ + if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ + return 0; + } +#endif + if( (pParse->db->flags & SQLITE_CountRows)!=0 ){ + return 0; /* xfer opt does not play well with PRAGMA count_changes */ + } + + /* If we get this far, it means that the xfer optimization is at + ** least a possibility, though it might only work if the destination + ** table (tab1) is initially empty. + */ +#ifdef SQLITE_TEST + sqlite3_xferopt_count++; +#endif + iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); + v = sqlite3GetVdbe(pParse); + sqlite3CodeVerifySchema(pParse, iDbSrc); + iSrc = pParse->nTab++; + iDest = pParse->nTab++; + regAutoinc = autoIncBegin(pParse, iDbDest, pDest); + sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); + if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ + || destHasUniqueIdx /* (2) */ + || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ + ){ + /* In some circumstances, we are able to run the xfer optimization + ** only if the destination table is initially empty. This code makes + ** that determination. Conditions under which the destination must + ** be empty: + ** + ** (1) There is no INTEGER PRIMARY KEY but there are indices. + ** (If the destination is not initially empty, the rowid fields + ** of index entries might need to change.) + ** + ** (2) The destination has a unique index. (The xfer optimization + ** is unable to test uniqueness.) + ** + ** (3) onError is something other than OE_Abort and OE_Rollback. + */ + addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); + emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); + sqlite3VdbeJumpHere(v, addr1); + }else{ + emptyDestTest = 0; + } + sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); + emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); + regData = sqlite3GetTempReg(pParse); + regRowid = sqlite3GetTempReg(pParse); + if( pDest->iPKey>=0 ){ + addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); + addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY, + onError, "PRIMARY KEY must be unique", P4_STATIC); + sqlite3VdbeJumpHere(v, addr2); + autoIncStep(pParse, regAutoinc, regRowid); + }else if( pDest->pIndex==0 ){ + addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); + }else{ + addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); + assert( (pDest->tabFlags & TF_Autoincrement)==0 ); + } + sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); + sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); + sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); + sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); + sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); + for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ + for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ + if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; + } + assert( pSrcIdx ); + sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); + sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, + (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pSrcIdx->zName)); + pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); + sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, + (char*)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); + VdbeComment((v, "%s", pDestIdx->zName)); + addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); + sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); + sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); + sqlite3VdbeJumpHere(v, addr1); + } + sqlite3VdbeJumpHere(v, emptySrcTest); + sqlite3ReleaseTempReg(pParse, regRowid); + sqlite3ReleaseTempReg(pParse, regData); + sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + if( emptyDestTest ){ + sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); + sqlite3VdbeJumpHere(v, emptyDestTest); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + return 0; + }else{ + return 1; + } +} +#endif /* SQLITE_OMIT_XFER_OPT */ + +/************** End of insert.c **********************************************/ +/************** Begin file legacy.c ******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Main file for the SQLite library. The routines in this file +** implement the programmer interface to the library. Routines in +** other files are for internal use by SQLite and should not be +** accessed by users of the library. +*/ + + +/* +** Execute SQL code. Return one of the SQLITE_ success/failure +** codes. Also write an error message into memory obtained from +** malloc() and make *pzErrMsg point to that message. +** +** If the SQL is a query, then for each row in the query result +** the xCallback() function is called. pArg becomes the first +** argument to xCallback(). If xCallback=NULL then no callback +** is invoked, even for queries. +*/ +SQLITE_API int sqlite3_exec( + sqlite3 *db, /* The database on which the SQL executes */ + const char *zSql, /* The SQL to be executed */ + sqlite3_callback xCallback, /* Invoke this callback routine */ + void *pArg, /* First argument to xCallback() */ + char **pzErrMsg /* Write error messages here */ +){ + int rc = SQLITE_OK; /* Return code */ + const char *zLeftover; /* Tail of unprocessed SQL */ + sqlite3_stmt *pStmt = 0; /* The current SQL statement */ + char **azCols = 0; /* Names of result columns */ + int callbackIsInit; /* True if callback data is initialized */ + + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( zSql==0 ) zSql = ""; + + sqlite3_mutex_enter(db->mutex); + sqlite3Error(db, SQLITE_OK, 0); + while( rc==SQLITE_OK && zSql[0] ){ + int nCol; + char **azVals = 0; + + pStmt = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); + assert( rc==SQLITE_OK || pStmt==0 ); + if( rc!=SQLITE_OK ){ + continue; + } + if( !pStmt ){ + /* this happens for a comment or white-space */ + zSql = zLeftover; + continue; + } + + callbackIsInit = 0; + nCol = sqlite3_column_count(pStmt); + + while( 1 ){ + int i; + rc = sqlite3_step(pStmt); + + /* Invoke the callback function if required */ + if( xCallback && (SQLITE_ROW==rc || + (SQLITE_DONE==rc && !callbackIsInit + && db->flags&SQLITE_NullCallback)) ){ + if( !callbackIsInit ){ + azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); + if( azCols==0 ){ + goto exec_out; + } + for(i=0; imallocFailed = 1; + goto exec_out; + } + } + } + if( xCallback(pArg, nCol, azVals, azCols) ){ + rc = SQLITE_ABORT; + sqlite3VdbeFinalize((Vdbe *)pStmt); + pStmt = 0; + sqlite3Error(db, SQLITE_ABORT, 0); + goto exec_out; + } + } + + if( rc!=SQLITE_ROW ){ + rc = sqlite3VdbeFinalize((Vdbe *)pStmt); + pStmt = 0; + zSql = zLeftover; + while( sqlite3Isspace(zSql[0]) ) zSql++; + break; + } + } + + sqlite3DbFree(db, azCols); + azCols = 0; + } + +exec_out: + if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt); + sqlite3DbFree(db, azCols); + + rc = sqlite3ApiExit(db, rc); + if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){ + int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db)); + *pzErrMsg = sqlite3Malloc(nErrMsg); + if( *pzErrMsg ){ + memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg); + }else{ + rc = SQLITE_NOMEM; + sqlite3Error(db, SQLITE_NOMEM, 0); + } + }else if( pzErrMsg ){ + *pzErrMsg = 0; + } + + assert( (rc&db->errMask)==rc ); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/************** End of legacy.c **********************************************/ +/************** Begin file loadext.c *****************************************/ +/* +** 2006 June 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to dynamically load extensions into +** the SQLite library. +*/ + +#ifndef SQLITE_CORE + #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ +#endif +/************** Include sqlite3ext.h in the middle of loadext.c **************/ +/************** Begin file sqlite3ext.h **************************************/ +/* +** 2006 June 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the SQLite interface for use by +** shared libraries that want to be imported as extensions into +** an SQLite instance. Shared libraries that intend to be loaded +** as extensions by SQLite should #include this file instead of +** sqlite3.h. +*/ +#ifndef _SQLITE3EXT_H_ +#define _SQLITE3EXT_H_ + +typedef struct sqlite3_api_routines sqlite3_api_routines; + +/* +** The following structure holds pointers to all of the SQLite API +** routines. +** +** WARNING: In order to maintain backwards compatibility, add new +** interfaces to the end of this structure only. If you insert new +** interfaces in the middle of this structure, then older different +** versions of SQLite will not be able to load each others' shared +** libraries! +*/ +struct sqlite3_api_routines { + void * (*aggregate_context)(sqlite3_context*,int nBytes); + int (*aggregate_count)(sqlite3_context*); + int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); + int (*bind_double)(sqlite3_stmt*,int,double); + int (*bind_int)(sqlite3_stmt*,int,int); + int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); + int (*bind_null)(sqlite3_stmt*,int); + int (*bind_parameter_count)(sqlite3_stmt*); + int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); + const char * (*bind_parameter_name)(sqlite3_stmt*,int); + int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); + int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); + int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); + int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); + int (*busy_timeout)(sqlite3*,int ms); + int (*changes)(sqlite3*); + int (*close)(sqlite3*); + int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, + int eTextRep,const char*)); + int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, + int eTextRep,const void*)); + const void * (*column_blob)(sqlite3_stmt*,int iCol); + int (*column_bytes)(sqlite3_stmt*,int iCol); + int (*column_bytes16)(sqlite3_stmt*,int iCol); + int (*column_count)(sqlite3_stmt*pStmt); + const char * (*column_database_name)(sqlite3_stmt*,int); + const void * (*column_database_name16)(sqlite3_stmt*,int); + const char * (*column_decltype)(sqlite3_stmt*,int i); + const void * (*column_decltype16)(sqlite3_stmt*,int); + double (*column_double)(sqlite3_stmt*,int iCol); + int (*column_int)(sqlite3_stmt*,int iCol); + sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); + const char * (*column_name)(sqlite3_stmt*,int); + const void * (*column_name16)(sqlite3_stmt*,int); + const char * (*column_origin_name)(sqlite3_stmt*,int); + const void * (*column_origin_name16)(sqlite3_stmt*,int); + const char * (*column_table_name)(sqlite3_stmt*,int); + const void * (*column_table_name16)(sqlite3_stmt*,int); + const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); + const void * (*column_text16)(sqlite3_stmt*,int iCol); + int (*column_type)(sqlite3_stmt*,int iCol); + sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); + void * (*commit_hook)(sqlite3*,int(*)(void*),void*); + int (*complete)(const char*sql); + int (*complete16)(const void*sql); + int (*create_collation)(sqlite3*,const char*,int,void*, + int(*)(void*,int,const void*,int,const void*)); + int (*create_collation16)(sqlite3*,const void*,int,void*, + int(*)(void*,int,const void*,int,const void*)); + int (*create_function)(sqlite3*,const char*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*)); + int (*create_function16)(sqlite3*,const void*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*)); + int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); + int (*data_count)(sqlite3_stmt*pStmt); + sqlite3 * (*db_handle)(sqlite3_stmt*); + int (*declare_vtab)(sqlite3*,const char*); + int (*enable_shared_cache)(int); + int (*errcode)(sqlite3*db); + const char * (*errmsg)(sqlite3*); + const void * (*errmsg16)(sqlite3*); + int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); + int (*expired)(sqlite3_stmt*); + int (*finalize)(sqlite3_stmt*pStmt); + void (*free)(void*); + void (*free_table)(char**result); + int (*get_autocommit)(sqlite3*); + void * (*get_auxdata)(sqlite3_context*,int); + int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); + int (*global_recover)(void); + void (*interruptx)(sqlite3*); + sqlite_int64 (*last_insert_rowid)(sqlite3*); + const char * (*libversion)(void); + int (*libversion_number)(void); + void *(*malloc)(int); + char * (*mprintf)(const char*,...); + int (*open)(const char*,sqlite3**); + int (*open16)(const void*,sqlite3**); + int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); + void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); + void *(*realloc)(void*,int); + int (*reset)(sqlite3_stmt*pStmt); + void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_double)(sqlite3_context*,double); + void (*result_error)(sqlite3_context*,const char*,int); + void (*result_error16)(sqlite3_context*,const void*,int); + void (*result_int)(sqlite3_context*,int); + void (*result_int64)(sqlite3_context*,sqlite_int64); + void (*result_null)(sqlite3_context*); + void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); + void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_value)(sqlite3_context*,sqlite3_value*); + void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); + int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, + const char*,const char*),void*); + void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); + char * (*snprintf)(int,char*,const char*,...); + int (*step)(sqlite3_stmt*); + int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, + char const**,char const**,int*,int*,int*); + void (*thread_cleanup)(void); + int (*total_changes)(sqlite3*); + void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); + int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); + void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, + sqlite_int64),void*); + void * (*user_data)(sqlite3_context*); + const void * (*value_blob)(sqlite3_value*); + int (*value_bytes)(sqlite3_value*); + int (*value_bytes16)(sqlite3_value*); + double (*value_double)(sqlite3_value*); + int (*value_int)(sqlite3_value*); + sqlite_int64 (*value_int64)(sqlite3_value*); + int (*value_numeric_type)(sqlite3_value*); + const unsigned char * (*value_text)(sqlite3_value*); + const void * (*value_text16)(sqlite3_value*); + const void * (*value_text16be)(sqlite3_value*); + const void * (*value_text16le)(sqlite3_value*); + int (*value_type)(sqlite3_value*); + char *(*vmprintf)(const char*,va_list); + /* Added ??? */ + int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); + /* Added by 3.3.13 */ + int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + int (*clear_bindings)(sqlite3_stmt*); + /* Added by 3.4.1 */ + int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, + void (*xDestroy)(void *)); + /* Added by 3.5.0 */ + int (*bind_zeroblob)(sqlite3_stmt*,int,int); + int (*blob_bytes)(sqlite3_blob*); + int (*blob_close)(sqlite3_blob*); + int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, + int,sqlite3_blob**); + int (*blob_read)(sqlite3_blob*,void*,int,int); + int (*blob_write)(sqlite3_blob*,const void*,int,int); + int (*create_collation_v2)(sqlite3*,const char*,int,void*, + int(*)(void*,int,const void*,int,const void*), + void(*)(void*)); + int (*file_control)(sqlite3*,const char*,int,void*); + sqlite3_int64 (*memory_highwater)(int); + sqlite3_int64 (*memory_used)(void); + sqlite3_mutex *(*mutex_alloc)(int); + void (*mutex_enter)(sqlite3_mutex*); + void (*mutex_free)(sqlite3_mutex*); + void (*mutex_leave)(sqlite3_mutex*); + int (*mutex_try)(sqlite3_mutex*); + int (*open_v2)(const char*,sqlite3**,int,const char*); + int (*release_memory)(int); + void (*result_error_nomem)(sqlite3_context*); + void (*result_error_toobig)(sqlite3_context*); + int (*sleep)(int); + void (*soft_heap_limit)(int); + sqlite3_vfs *(*vfs_find)(const char*); + int (*vfs_register)(sqlite3_vfs*,int); + int (*vfs_unregister)(sqlite3_vfs*); + int (*xthreadsafe)(void); + void (*result_zeroblob)(sqlite3_context*,int); + void (*result_error_code)(sqlite3_context*,int); + int (*test_control)(int, ...); + void (*randomness)(int,void*); + sqlite3 *(*context_db_handle)(sqlite3_context*); + int (*extended_result_codes)(sqlite3*,int); + int (*limit)(sqlite3*,int,int); + sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); + const char *(*sql)(sqlite3_stmt*); + int (*status)(int,int*,int*,int); + int (*backup_finish)(sqlite3_backup*); + sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); + int (*backup_pagecount)(sqlite3_backup*); + int (*backup_remaining)(sqlite3_backup*); + int (*backup_step)(sqlite3_backup*,int); + const char *(*compileoption_get)(int); + int (*compileoption_used)(const char*); + int (*create_function_v2)(sqlite3*,const char*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*)); + int (*db_config)(sqlite3*,int,...); + sqlite3_mutex *(*db_mutex)(sqlite3*); + int (*db_status)(sqlite3*,int,int*,int*,int); + int (*extended_errcode)(sqlite3*); + void (*log)(int,const char*,...); + sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); + const char *(*sourceid)(void); + int (*stmt_status)(sqlite3_stmt*,int,int); + int (*strnicmp)(const char*,const char*,int); + int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); + int (*wal_autocheckpoint)(sqlite3*,int); + int (*wal_checkpoint)(sqlite3*,const char*); + void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); + int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); + int (*vtab_config)(sqlite3*,int op,...); + int (*vtab_on_conflict)(sqlite3*); + /* Version 3.7.16 and later */ + int (*close_v2)(sqlite3*); + const char *(*db_filename)(sqlite3*,const char*); + int (*db_readonly)(sqlite3*,const char*); + int (*db_release_memory)(sqlite3*); + const char *(*errstr)(int); + int (*stmt_busy)(sqlite3_stmt*); + int (*stmt_readonly)(sqlite3_stmt*); + int (*stricmp)(const char*,const char*); + int (*uri_boolean)(const char*,const char*,int); + sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); + const char *(*uri_parameter)(const char*,const char*); + char *(*vsnprintf)(int,char*,const char*,va_list); + int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); +}; + +/* +** The following macros redefine the API routines so that they are +** redirected throught the global sqlite3_api structure. +** +** This header file is also used by the loadext.c source file +** (part of the main SQLite library - not an extension) so that +** it can get access to the sqlite3_api_routines structure +** definition. But the main library does not want to redefine +** the API. So the redefinition macros are only valid if the +** SQLITE_CORE macros is undefined. +*/ +#ifndef SQLITE_CORE +#define sqlite3_aggregate_context sqlite3_api->aggregate_context +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_aggregate_count sqlite3_api->aggregate_count +#endif +#define sqlite3_bind_blob sqlite3_api->bind_blob +#define sqlite3_bind_double sqlite3_api->bind_double +#define sqlite3_bind_int sqlite3_api->bind_int +#define sqlite3_bind_int64 sqlite3_api->bind_int64 +#define sqlite3_bind_null sqlite3_api->bind_null +#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count +#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index +#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name +#define sqlite3_bind_text sqlite3_api->bind_text +#define sqlite3_bind_text16 sqlite3_api->bind_text16 +#define sqlite3_bind_value sqlite3_api->bind_value +#define sqlite3_busy_handler sqlite3_api->busy_handler +#define sqlite3_busy_timeout sqlite3_api->busy_timeout +#define sqlite3_changes sqlite3_api->changes +#define sqlite3_close sqlite3_api->close +#define sqlite3_collation_needed sqlite3_api->collation_needed +#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 +#define sqlite3_column_blob sqlite3_api->column_blob +#define sqlite3_column_bytes sqlite3_api->column_bytes +#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 +#define sqlite3_column_count sqlite3_api->column_count +#define sqlite3_column_database_name sqlite3_api->column_database_name +#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 +#define sqlite3_column_decltype sqlite3_api->column_decltype +#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 +#define sqlite3_column_double sqlite3_api->column_double +#define sqlite3_column_int sqlite3_api->column_int +#define sqlite3_column_int64 sqlite3_api->column_int64 +#define sqlite3_column_name sqlite3_api->column_name +#define sqlite3_column_name16 sqlite3_api->column_name16 +#define sqlite3_column_origin_name sqlite3_api->column_origin_name +#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 +#define sqlite3_column_table_name sqlite3_api->column_table_name +#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 +#define sqlite3_column_text sqlite3_api->column_text +#define sqlite3_column_text16 sqlite3_api->column_text16 +#define sqlite3_column_type sqlite3_api->column_type +#define sqlite3_column_value sqlite3_api->column_value +#define sqlite3_commit_hook sqlite3_api->commit_hook +#define sqlite3_complete sqlite3_api->complete +#define sqlite3_complete16 sqlite3_api->complete16 +#define sqlite3_create_collation sqlite3_api->create_collation +#define sqlite3_create_collation16 sqlite3_api->create_collation16 +#define sqlite3_create_function sqlite3_api->create_function +#define sqlite3_create_function16 sqlite3_api->create_function16 +#define sqlite3_create_module sqlite3_api->create_module +#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 +#define sqlite3_data_count sqlite3_api->data_count +#define sqlite3_db_handle sqlite3_api->db_handle +#define sqlite3_declare_vtab sqlite3_api->declare_vtab +#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache +#define sqlite3_errcode sqlite3_api->errcode +#define sqlite3_errmsg sqlite3_api->errmsg +#define sqlite3_errmsg16 sqlite3_api->errmsg16 +#define sqlite3_exec sqlite3_api->exec +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_expired sqlite3_api->expired +#endif +#define sqlite3_finalize sqlite3_api->finalize +#define sqlite3_free sqlite3_api->free +#define sqlite3_free_table sqlite3_api->free_table +#define sqlite3_get_autocommit sqlite3_api->get_autocommit +#define sqlite3_get_auxdata sqlite3_api->get_auxdata +#define sqlite3_get_table sqlite3_api->get_table +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_global_recover sqlite3_api->global_recover +#endif +#define sqlite3_interrupt sqlite3_api->interruptx +#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid +#define sqlite3_libversion sqlite3_api->libversion +#define sqlite3_libversion_number sqlite3_api->libversion_number +#define sqlite3_malloc sqlite3_api->malloc +#define sqlite3_mprintf sqlite3_api->mprintf +#define sqlite3_open sqlite3_api->open +#define sqlite3_open16 sqlite3_api->open16 +#define sqlite3_prepare sqlite3_api->prepare +#define sqlite3_prepare16 sqlite3_api->prepare16 +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_profile sqlite3_api->profile +#define sqlite3_progress_handler sqlite3_api->progress_handler +#define sqlite3_realloc sqlite3_api->realloc +#define sqlite3_reset sqlite3_api->reset +#define sqlite3_result_blob sqlite3_api->result_blob +#define sqlite3_result_double sqlite3_api->result_double +#define sqlite3_result_error sqlite3_api->result_error +#define sqlite3_result_error16 sqlite3_api->result_error16 +#define sqlite3_result_int sqlite3_api->result_int +#define sqlite3_result_int64 sqlite3_api->result_int64 +#define sqlite3_result_null sqlite3_api->result_null +#define sqlite3_result_text sqlite3_api->result_text +#define sqlite3_result_text16 sqlite3_api->result_text16 +#define sqlite3_result_text16be sqlite3_api->result_text16be +#define sqlite3_result_text16le sqlite3_api->result_text16le +#define sqlite3_result_value sqlite3_api->result_value +#define sqlite3_rollback_hook sqlite3_api->rollback_hook +#define sqlite3_set_authorizer sqlite3_api->set_authorizer +#define sqlite3_set_auxdata sqlite3_api->set_auxdata +#define sqlite3_snprintf sqlite3_api->snprintf +#define sqlite3_step sqlite3_api->step +#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata +#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup +#define sqlite3_total_changes sqlite3_api->total_changes +#define sqlite3_trace sqlite3_api->trace +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings +#endif +#define sqlite3_update_hook sqlite3_api->update_hook +#define sqlite3_user_data sqlite3_api->user_data +#define sqlite3_value_blob sqlite3_api->value_blob +#define sqlite3_value_bytes sqlite3_api->value_bytes +#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 +#define sqlite3_value_double sqlite3_api->value_double +#define sqlite3_value_int sqlite3_api->value_int +#define sqlite3_value_int64 sqlite3_api->value_int64 +#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type +#define sqlite3_value_text sqlite3_api->value_text +#define sqlite3_value_text16 sqlite3_api->value_text16 +#define sqlite3_value_text16be sqlite3_api->value_text16be +#define sqlite3_value_text16le sqlite3_api->value_text16le +#define sqlite3_value_type sqlite3_api->value_type +#define sqlite3_vmprintf sqlite3_api->vmprintf +#define sqlite3_overload_function sqlite3_api->overload_function +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_clear_bindings sqlite3_api->clear_bindings +#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob +#define sqlite3_blob_bytes sqlite3_api->blob_bytes +#define sqlite3_blob_close sqlite3_api->blob_close +#define sqlite3_blob_open sqlite3_api->blob_open +#define sqlite3_blob_read sqlite3_api->blob_read +#define sqlite3_blob_write sqlite3_api->blob_write +#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 +#define sqlite3_file_control sqlite3_api->file_control +#define sqlite3_memory_highwater sqlite3_api->memory_highwater +#define sqlite3_memory_used sqlite3_api->memory_used +#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc +#define sqlite3_mutex_enter sqlite3_api->mutex_enter +#define sqlite3_mutex_free sqlite3_api->mutex_free +#define sqlite3_mutex_leave sqlite3_api->mutex_leave +#define sqlite3_mutex_try sqlite3_api->mutex_try +#define sqlite3_open_v2 sqlite3_api->open_v2 +#define sqlite3_release_memory sqlite3_api->release_memory +#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem +#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig +#define sqlite3_sleep sqlite3_api->sleep +#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit +#define sqlite3_vfs_find sqlite3_api->vfs_find +#define sqlite3_vfs_register sqlite3_api->vfs_register +#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister +#define sqlite3_threadsafe sqlite3_api->xthreadsafe +#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob +#define sqlite3_result_error_code sqlite3_api->result_error_code +#define sqlite3_test_control sqlite3_api->test_control +#define sqlite3_randomness sqlite3_api->randomness +#define sqlite3_context_db_handle sqlite3_api->context_db_handle +#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes +#define sqlite3_limit sqlite3_api->limit +#define sqlite3_next_stmt sqlite3_api->next_stmt +#define sqlite3_sql sqlite3_api->sql +#define sqlite3_status sqlite3_api->status +#define sqlite3_backup_finish sqlite3_api->backup_finish +#define sqlite3_backup_init sqlite3_api->backup_init +#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount +#define sqlite3_backup_remaining sqlite3_api->backup_remaining +#define sqlite3_backup_step sqlite3_api->backup_step +#define sqlite3_compileoption_get sqlite3_api->compileoption_get +#define sqlite3_compileoption_used sqlite3_api->compileoption_used +#define sqlite3_create_function_v2 sqlite3_api->create_function_v2 +#define sqlite3_db_config sqlite3_api->db_config +#define sqlite3_db_mutex sqlite3_api->db_mutex +#define sqlite3_db_status sqlite3_api->db_status +#define sqlite3_extended_errcode sqlite3_api->extended_errcode +#define sqlite3_log sqlite3_api->log +#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 +#define sqlite3_sourceid sqlite3_api->sourceid +#define sqlite3_stmt_status sqlite3_api->stmt_status +#define sqlite3_strnicmp sqlite3_api->strnicmp +#define sqlite3_unlock_notify sqlite3_api->unlock_notify +#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint +#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint +#define sqlite3_wal_hook sqlite3_api->wal_hook +#define sqlite3_blob_reopen sqlite3_api->blob_reopen +#define sqlite3_vtab_config sqlite3_api->vtab_config +#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict +/* Version 3.7.16 and later */ +#define sqlite3_close_v2 sqlite3_api->close_v2 +#define sqlite3_db_filename sqlite3_api->db_filename +#define sqlite3_db_readonly sqlite3_api->db_readonly +#define sqlite3_db_release_memory sqlite3_api->db_release_memory +#define sqlite3_errstr sqlite3_api->errstr +#define sqlite3_stmt_busy sqlite3_api->stmt_busy +#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly +#define sqlite3_stricmp sqlite3_api->stricmp +#define sqlite3_uri_boolean sqlite3_api->uri_boolean +#define sqlite3_uri_int64 sqlite3_api->uri_int64 +#define sqlite3_uri_parameter sqlite3_api->uri_parameter +#define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf +#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 +#endif /* SQLITE_CORE */ + +#ifndef SQLITE_CORE + /* This case when the file really is being compiled as a loadable + ** extension */ +# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; +# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; +# define SQLITE_EXTENSION_INIT3 \ + extern const sqlite3_api_routines *sqlite3_api; +#else + /* This case when the file is being statically linked into the + ** application */ +# define SQLITE_EXTENSION_INIT1 /*no-op*/ +# define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */ +# define SQLITE_EXTENSION_INIT3 /*no-op*/ +#endif + +#endif /* _SQLITE3EXT_H_ */ + +/************** End of sqlite3ext.h ******************************************/ +/************** Continuing where we left off in loadext.c ********************/ +/* #include */ + +#ifndef SQLITE_OMIT_LOAD_EXTENSION + +/* +** Some API routines are omitted when various features are +** excluded from a build of SQLite. Substitute a NULL pointer +** for any missing APIs. +*/ +#ifndef SQLITE_ENABLE_COLUMN_METADATA +# define sqlite3_column_database_name 0 +# define sqlite3_column_database_name16 0 +# define sqlite3_column_table_name 0 +# define sqlite3_column_table_name16 0 +# define sqlite3_column_origin_name 0 +# define sqlite3_column_origin_name16 0 +# define sqlite3_table_column_metadata 0 +#endif + +#ifdef SQLITE_OMIT_AUTHORIZATION +# define sqlite3_set_authorizer 0 +#endif + +#ifdef SQLITE_OMIT_UTF16 +# define sqlite3_bind_text16 0 +# define sqlite3_collation_needed16 0 +# define sqlite3_column_decltype16 0 +# define sqlite3_column_name16 0 +# define sqlite3_column_text16 0 +# define sqlite3_complete16 0 +# define sqlite3_create_collation16 0 +# define sqlite3_create_function16 0 +# define sqlite3_errmsg16 0 +# define sqlite3_open16 0 +# define sqlite3_prepare16 0 +# define sqlite3_prepare16_v2 0 +# define sqlite3_result_error16 0 +# define sqlite3_result_text16 0 +# define sqlite3_result_text16be 0 +# define sqlite3_result_text16le 0 +# define sqlite3_value_text16 0 +# define sqlite3_value_text16be 0 +# define sqlite3_value_text16le 0 +# define sqlite3_column_database_name16 0 +# define sqlite3_column_table_name16 0 +# define sqlite3_column_origin_name16 0 +#endif + +#ifdef SQLITE_OMIT_COMPLETE +# define sqlite3_complete 0 +# define sqlite3_complete16 0 +#endif + +#ifdef SQLITE_OMIT_DECLTYPE +# define sqlite3_column_decltype16 0 +# define sqlite3_column_decltype 0 +#endif + +#ifdef SQLITE_OMIT_PROGRESS_CALLBACK +# define sqlite3_progress_handler 0 +#endif + +#ifdef SQLITE_OMIT_VIRTUALTABLE +# define sqlite3_create_module 0 +# define sqlite3_create_module_v2 0 +# define sqlite3_declare_vtab 0 +# define sqlite3_vtab_config 0 +# define sqlite3_vtab_on_conflict 0 +#endif + +#ifdef SQLITE_OMIT_SHARED_CACHE +# define sqlite3_enable_shared_cache 0 +#endif + +#ifdef SQLITE_OMIT_TRACE +# define sqlite3_profile 0 +# define sqlite3_trace 0 +#endif + +#ifdef SQLITE_OMIT_GET_TABLE +# define sqlite3_free_table 0 +# define sqlite3_get_table 0 +#endif + +#ifdef SQLITE_OMIT_INCRBLOB +#define sqlite3_bind_zeroblob 0 +#define sqlite3_blob_bytes 0 +#define sqlite3_blob_close 0 +#define sqlite3_blob_open 0 +#define sqlite3_blob_read 0 +#define sqlite3_blob_write 0 +#define sqlite3_blob_reopen 0 +#endif + +/* +** The following structure contains pointers to all SQLite API routines. +** A pointer to this structure is passed into extensions when they are +** loaded so that the extension can make calls back into the SQLite +** library. +** +** When adding new APIs, add them to the bottom of this structure +** in order to preserve backwards compatibility. +** +** Extensions that use newer APIs should first call the +** sqlite3_libversion_number() to make sure that the API they +** intend to use is supported by the library. Extensions should +** also check to make sure that the pointer to the function is +** not NULL before calling it. +*/ +static const sqlite3_api_routines sqlite3Apis = { + sqlite3_aggregate_context, +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_aggregate_count, +#else + 0, +#endif + sqlite3_bind_blob, + sqlite3_bind_double, + sqlite3_bind_int, + sqlite3_bind_int64, + sqlite3_bind_null, + sqlite3_bind_parameter_count, + sqlite3_bind_parameter_index, + sqlite3_bind_parameter_name, + sqlite3_bind_text, + sqlite3_bind_text16, + sqlite3_bind_value, + sqlite3_busy_handler, + sqlite3_busy_timeout, + sqlite3_changes, + sqlite3_close, + sqlite3_collation_needed, + sqlite3_collation_needed16, + sqlite3_column_blob, + sqlite3_column_bytes, + sqlite3_column_bytes16, + sqlite3_column_count, + sqlite3_column_database_name, + sqlite3_column_database_name16, + sqlite3_column_decltype, + sqlite3_column_decltype16, + sqlite3_column_double, + sqlite3_column_int, + sqlite3_column_int64, + sqlite3_column_name, + sqlite3_column_name16, + sqlite3_column_origin_name, + sqlite3_column_origin_name16, + sqlite3_column_table_name, + sqlite3_column_table_name16, + sqlite3_column_text, + sqlite3_column_text16, + sqlite3_column_type, + sqlite3_column_value, + sqlite3_commit_hook, + sqlite3_complete, + sqlite3_complete16, + sqlite3_create_collation, + sqlite3_create_collation16, + sqlite3_create_function, + sqlite3_create_function16, + sqlite3_create_module, + sqlite3_data_count, + sqlite3_db_handle, + sqlite3_declare_vtab, + sqlite3_enable_shared_cache, + sqlite3_errcode, + sqlite3_errmsg, + sqlite3_errmsg16, + sqlite3_exec, +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_expired, +#else + 0, +#endif + sqlite3_finalize, + sqlite3_free, + sqlite3_free_table, + sqlite3_get_autocommit, + sqlite3_get_auxdata, + sqlite3_get_table, + 0, /* Was sqlite3_global_recover(), but that function is deprecated */ + sqlite3_interrupt, + sqlite3_last_insert_rowid, + sqlite3_libversion, + sqlite3_libversion_number, + sqlite3_malloc, + sqlite3_mprintf, + sqlite3_open, + sqlite3_open16, + sqlite3_prepare, + sqlite3_prepare16, + sqlite3_profile, + sqlite3_progress_handler, + sqlite3_realloc, + sqlite3_reset, + sqlite3_result_blob, + sqlite3_result_double, + sqlite3_result_error, + sqlite3_result_error16, + sqlite3_result_int, + sqlite3_result_int64, + sqlite3_result_null, + sqlite3_result_text, + sqlite3_result_text16, + sqlite3_result_text16be, + sqlite3_result_text16le, + sqlite3_result_value, + sqlite3_rollback_hook, + sqlite3_set_authorizer, + sqlite3_set_auxdata, + sqlite3_snprintf, + sqlite3_step, + sqlite3_table_column_metadata, +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_thread_cleanup, +#else + 0, +#endif + sqlite3_total_changes, + sqlite3_trace, +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_transfer_bindings, +#else + 0, +#endif + sqlite3_update_hook, + sqlite3_user_data, + sqlite3_value_blob, + sqlite3_value_bytes, + sqlite3_value_bytes16, + sqlite3_value_double, + sqlite3_value_int, + sqlite3_value_int64, + sqlite3_value_numeric_type, + sqlite3_value_text, + sqlite3_value_text16, + sqlite3_value_text16be, + sqlite3_value_text16le, + sqlite3_value_type, + sqlite3_vmprintf, + /* + ** The original API set ends here. All extensions can call any + ** of the APIs above provided that the pointer is not NULL. But + ** before calling APIs that follow, extension should check the + ** sqlite3_libversion_number() to make sure they are dealing with + ** a library that is new enough to support that API. + ************************************************************************* + */ + sqlite3_overload_function, + + /* + ** Added after 3.3.13 + */ + sqlite3_prepare_v2, + sqlite3_prepare16_v2, + sqlite3_clear_bindings, + + /* + ** Added for 3.4.1 + */ + sqlite3_create_module_v2, + + /* + ** Added for 3.5.0 + */ + sqlite3_bind_zeroblob, + sqlite3_blob_bytes, + sqlite3_blob_close, + sqlite3_blob_open, + sqlite3_blob_read, + sqlite3_blob_write, + sqlite3_create_collation_v2, + sqlite3_file_control, + sqlite3_memory_highwater, + sqlite3_memory_used, +#ifdef SQLITE_MUTEX_OMIT + 0, + 0, + 0, + 0, + 0, +#else + sqlite3_mutex_alloc, + sqlite3_mutex_enter, + sqlite3_mutex_free, + sqlite3_mutex_leave, + sqlite3_mutex_try, +#endif + sqlite3_open_v2, + sqlite3_release_memory, + sqlite3_result_error_nomem, + sqlite3_result_error_toobig, + sqlite3_sleep, + sqlite3_soft_heap_limit, + sqlite3_vfs_find, + sqlite3_vfs_register, + sqlite3_vfs_unregister, + + /* + ** Added for 3.5.8 + */ + sqlite3_threadsafe, + sqlite3_result_zeroblob, + sqlite3_result_error_code, + sqlite3_test_control, + sqlite3_randomness, + sqlite3_context_db_handle, + + /* + ** Added for 3.6.0 + */ + sqlite3_extended_result_codes, + sqlite3_limit, + sqlite3_next_stmt, + sqlite3_sql, + sqlite3_status, + + /* + ** Added for 3.7.4 + */ + sqlite3_backup_finish, + sqlite3_backup_init, + sqlite3_backup_pagecount, + sqlite3_backup_remaining, + sqlite3_backup_step, +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS + sqlite3_compileoption_get, + sqlite3_compileoption_used, +#else + 0, + 0, +#endif + sqlite3_create_function_v2, + sqlite3_db_config, + sqlite3_db_mutex, + sqlite3_db_status, + sqlite3_extended_errcode, + sqlite3_log, + sqlite3_soft_heap_limit64, + sqlite3_sourceid, + sqlite3_stmt_status, + sqlite3_strnicmp, +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + sqlite3_unlock_notify, +#else + 0, +#endif +#ifndef SQLITE_OMIT_WAL + sqlite3_wal_autocheckpoint, + sqlite3_wal_checkpoint, + sqlite3_wal_hook, +#else + 0, + 0, + 0, +#endif + sqlite3_blob_reopen, + sqlite3_vtab_config, + sqlite3_vtab_on_conflict, + sqlite3_close_v2, + sqlite3_db_filename, + sqlite3_db_readonly, + sqlite3_db_release_memory, + sqlite3_errstr, + sqlite3_stmt_busy, + sqlite3_stmt_readonly, + sqlite3_stricmp, + sqlite3_uri_boolean, + sqlite3_uri_int64, + sqlite3_uri_parameter, + sqlite3_vsnprintf, + sqlite3_wal_checkpoint_v2 +}; + +/* +** Attempt to load an SQLite extension library contained in the file +** zFile. The entry point is zProc. zProc may be 0 in which case a +** default entry point name (sqlite3_extension_init) is used. Use +** of the default name is recommended. +** +** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. +** +** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with +** error message text. The calling function should free this memory +** by calling sqlite3DbFree(db, ). +*/ +static int sqlite3LoadExtension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +){ + sqlite3_vfs *pVfs = db->pVfs; + void *handle; + int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*); + char *zErrmsg = 0; + const char *zEntry; + char *zAltEntry = 0; + void **aHandle; + int nMsg = 300 + sqlite3Strlen30(zFile); + int ii; + + /* Shared library endings to try if zFile cannot be loaded as written */ + static const char *azEndings[] = { +#if SQLITE_OS_WIN + "dll" +#elif defined(__APPLE__) + "dylib" +#else + "so" +#endif + }; + + + if( pzErrMsg ) *pzErrMsg = 0; + + /* Ticket #1863. To avoid a creating security problems for older + ** applications that relink against newer versions of SQLite, the + ** ability to run load_extension is turned off by default. One + ** must call sqlite3_enable_load_extension() to turn on extension + ** loading. Otherwise you get the following error. + */ + if( (db->flags & SQLITE_LoadExtension)==0 ){ + if( pzErrMsg ){ + *pzErrMsg = sqlite3_mprintf("not authorized"); + } + return SQLITE_ERROR; + } + + zEntry = zProc ? zProc : "sqlite3_extension_init"; + + handle = sqlite3OsDlOpen(pVfs, zFile); +#if SQLITE_OS_UNIX || SQLITE_OS_WIN + for(ii=0; ii sqlite3_example_init + ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init + */ + if( xInit==0 && zProc==0 ){ + int iFile, iEntry, c; + int ncFile = sqlite3Strlen30(zFile); + zAltEntry = sqlite3_malloc(ncFile+30); + if( zAltEntry==0 ){ + sqlite3OsDlClose(pVfs, handle); + return SQLITE_NOMEM; + } + memcpy(zAltEntry, "sqlite3_", 8); + for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){} + iFile++; + if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; + for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){ + if( sqlite3Isalpha(c) ){ + zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c]; + } + } + memcpy(zAltEntry+iEntry, "_init", 6); + zEntry = zAltEntry; + xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*)) + sqlite3OsDlSym(pVfs, handle, zEntry); + } + if( xInit==0 ){ + if( pzErrMsg ){ + nMsg += sqlite3Strlen30(zEntry); + *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); + if( zErrmsg ){ + sqlite3_snprintf(nMsg, zErrmsg, + "no entry point [%s] in shared library [%s]", zEntry, zFile); + sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); + } + } + sqlite3OsDlClose(pVfs, handle); + sqlite3_free(zAltEntry); + return SQLITE_ERROR; + } + sqlite3_free(zAltEntry); + if( xInit(db, &zErrmsg, &sqlite3Apis) ){ + if( pzErrMsg ){ + *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); + } + sqlite3_free(zErrmsg); + sqlite3OsDlClose(pVfs, handle); + return SQLITE_ERROR; + } + + /* Append the new shared library handle to the db->aExtension array. */ + aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1)); + if( aHandle==0 ){ + return SQLITE_NOMEM; + } + if( db->nExtension>0 ){ + memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension); + } + sqlite3DbFree(db, db->aExtension); + db->aExtension = aHandle; + + db->aExtension[db->nExtension++] = handle; + return SQLITE_OK; +} +SQLITE_API int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +){ + int rc; + sqlite3_mutex_enter(db->mutex); + rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Call this routine when the database connection is closing in order +** to clean up loaded extensions +*/ +SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){ + int i; + assert( sqlite3_mutex_held(db->mutex) ); + for(i=0; inExtension; i++){ + sqlite3OsDlClose(db->pVfs, db->aExtension[i]); + } + sqlite3DbFree(db, db->aExtension); +} + +/* +** Enable or disable extension loading. Extension loading is disabled by +** default so as not to open security holes in older applications. +*/ +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){ + sqlite3_mutex_enter(db->mutex); + if( onoff ){ + db->flags |= SQLITE_LoadExtension; + }else{ + db->flags &= ~SQLITE_LoadExtension; + } + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + +/* +** The auto-extension code added regardless of whether or not extension +** loading is supported. We need a dummy sqlite3Apis pointer for that +** code if regular extension loading is not available. This is that +** dummy pointer. +*/ +#ifdef SQLITE_OMIT_LOAD_EXTENSION +static const sqlite3_api_routines sqlite3Apis = { 0 }; +#endif + + +/* +** The following object holds the list of automatically loaded +** extensions. +** +** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER +** mutex must be held while accessing this list. +*/ +typedef struct sqlite3AutoExtList sqlite3AutoExtList; +static SQLITE_WSD struct sqlite3AutoExtList { + int nExt; /* Number of entries in aExt[] */ + void (**aExt)(void); /* Pointers to the extension init functions */ +} sqlite3Autoext = { 0, 0 }; + +/* The "wsdAutoext" macro will resolve to the autoextension +** state vector. If writable static data is unsupported on the target, +** we have to locate the state vector at run-time. In the more common +** case where writable static data is supported, wsdStat can refer directly +** to the "sqlite3Autoext" state vector declared above. +*/ +#ifdef SQLITE_OMIT_WSD +# define wsdAutoextInit \ + sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) +# define wsdAutoext x[0] +#else +# define wsdAutoextInit +# define wsdAutoext sqlite3Autoext +#endif + + +/* +** Register a statically linked extension that is automatically +** loaded by every new database connection. +*/ +SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){ + int rc = SQLITE_OK; +#ifndef SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if( rc ){ + return rc; + }else +#endif + { + int i; +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + wsdAutoextInit; + sqlite3_mutex_enter(mutex); + for(i=0; i=0; i--){ + if( wsdAutoext.aExt[i]==xInit ){ + wsdAutoext.nExt--; + wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt]; + n++; + break; + } + } + sqlite3_mutex_leave(mutex); + return n; +} + +/* +** Reset the automatic extension loading mechanism. +*/ +SQLITE_API void sqlite3_reset_auto_extension(void){ +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize()==SQLITE_OK ) +#endif + { +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + wsdAutoextInit; + sqlite3_mutex_enter(mutex); + sqlite3_free(wsdAutoext.aExt); + wsdAutoext.aExt = 0; + wsdAutoext.nExt = 0; + sqlite3_mutex_leave(mutex); + } +} + +/* +** Load all automatic extensions. +** +** If anything goes wrong, set an error in the database connection. +*/ +SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){ + int i; + int go = 1; + int rc; + int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*); + + wsdAutoextInit; + if( wsdAutoext.nExt==0 ){ + /* Common case: early out without every having to acquire a mutex */ + return; + } + for(i=0; go; i++){ + char *zErrmsg; +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter(mutex); + if( i>=wsdAutoext.nExt ){ + xInit = 0; + go = 0; + }else{ + xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*)) + wsdAutoext.aExt[i]; + } + sqlite3_mutex_leave(mutex); + zErrmsg = 0; + if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){ + sqlite3Error(db, rc, + "automatic extension loading failed: %s", zErrmsg); + go = 0; + } + sqlite3_free(zErrmsg); + } +} + +/************** End of loadext.c *********************************************/ +/************** Begin file pragma.c ******************************************/ +/* +** 2003 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the PRAGMA command. +*/ + +#if !defined(SQLITE_ENABLE_LOCKING_STYLE) +# if defined(__APPLE__) +# define SQLITE_ENABLE_LOCKING_STYLE 1 +# else +# define SQLITE_ENABLE_LOCKING_STYLE 0 +# endif +#endif + +/*************************************************************************** +** The next block of code, including the PragTyp_XXXX macro definitions and +** the aPragmaName[] object is composed of generated code. DO NOT EDIT. +** +** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun +** that script. Then copy/paste the output in place of the following: +*/ +#define PragTyp_HEADER_VALUE 0 +#define PragTyp_AUTO_VACUUM 1 +#define PragTyp_FLAG 2 +#define PragTyp_BUSY_TIMEOUT 3 +#define PragTyp_CACHE_SIZE 4 +#define PragTyp_CASE_SENSITIVE_LIKE 5 +#define PragTyp_COLLATION_LIST 6 +#define PragTyp_COMPILE_OPTIONS 7 +#define PragTyp_DATA_STORE_DIRECTORY 8 +#define PragTyp_DATABASE_LIST 9 +#define PragTyp_DEFAULT_CACHE_SIZE 10 +#define PragTyp_ENCODING 11 +#define PragTyp_FOREIGN_KEY_CHECK 12 +#define PragTyp_FOREIGN_KEY_LIST 13 +#define PragTyp_INCREMENTAL_VACUUM 14 +#define PragTyp_INDEX_INFO 15 +#define PragTyp_INDEX_LIST 16 +#define PragTyp_INTEGRITY_CHECK 17 +#define PragTyp_JOURNAL_MODE 18 +#define PragTyp_JOURNAL_SIZE_LIMIT 19 +#define PragTyp_LOCK_PROXY_FILE 20 +#define PragTyp_LOCKING_MODE 21 +#define PragTyp_PAGE_COUNT 22 +#define PragTyp_MMAP_SIZE 23 +#define PragTyp_PAGE_SIZE 24 +#define PragTyp_SECURE_DELETE 25 +#define PragTyp_SHRINK_MEMORY 26 +#define PragTyp_SOFT_HEAP_LIMIT 27 +#define PragTyp_STATS 28 +#define PragTyp_SYNCHRONOUS 29 +#define PragTyp_TABLE_INFO 30 +#define PragTyp_TEMP_STORE 31 +#define PragTyp_TEMP_STORE_DIRECTORY 32 +#define PragTyp_WAL_AUTOCHECKPOINT 33 +#define PragTyp_WAL_CHECKPOINT 34 +#define PragTyp_ACTIVATE_EXTENSIONS 35 +#define PragTyp_HEXKEY 36 +#define PragTyp_KEY 37 +#define PragTyp_REKEY 38 +#define PragTyp_LOCK_STATUS 39 +#define PragTyp_PARSER_TRACE 40 +#define PragFlag_NeedSchema 0x01 +static const struct sPragmaNames { + const char *const zName; /* Name of pragma */ + u8 ePragTyp; /* PragTyp_XXX value */ + u8 mPragFlag; /* Zero or more PragFlag_XXX values */ + u32 iArg; /* Extra argument */ +} aPragmaNames[] = { +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) + { /* zName: */ "activate_extensions", + /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + { /* zName: */ "application_id", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_AUTOVACUUM) + { /* zName: */ "auto_vacuum", + /* ePragTyp: */ PragTyp_AUTO_VACUUM, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX) + { /* zName: */ "automatic_index", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_AutoIndex }, +#endif + { /* zName: */ "busy_timeout", + /* ePragTyp: */ PragTyp_BUSY_TIMEOUT, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "cache_size", + /* ePragTyp: */ PragTyp_CACHE_SIZE, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif + { /* zName: */ "cache_spill", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_CacheSpill }, + { /* zName: */ "case_sensitive_like", + /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "checkpoint_fullfsync", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_CkptFullFSync }, +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "collation_list", + /* ePragTyp: */ PragTyp_COLLATION_LIST, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS) + { /* zName: */ "compile_options", + /* ePragTyp: */ PragTyp_COMPILE_OPTIONS, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "count_changes", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_CountRows }, +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN + { /* zName: */ "data_store_directory", + /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "database_list", + /* ePragTyp: */ PragTyp_DATABASE_LIST, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) + { /* zName: */ "default_cache_size", + /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + { /* zName: */ "defer_foreign_keys", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_DeferFKs }, +#endif + { /* zName: */ "empty_result_callbacks", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_NullCallback }, +#if !defined(SQLITE_OMIT_UTF16) + { /* zName: */ "encoding", + /* ePragTyp: */ PragTyp_ENCODING, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + { /* zName: */ "foreign_key_check", + /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_FOREIGN_KEY) + { /* zName: */ "foreign_key_list", + /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + { /* zName: */ "foreign_keys", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_ForeignKeys }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + { /* zName: */ "freelist_count", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "full_column_names", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_FullColNames }, + { /* zName: */ "fullfsync", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_FullFSync }, +#if defined(SQLITE_HAS_CODEC) + { /* zName: */ "hexkey", + /* ePragTyp: */ PragTyp_HEXKEY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "hexrekey", + /* ePragTyp: */ PragTyp_HEXKEY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_CHECK) + { /* zName: */ "ignore_check_constraints", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_IgnoreChecks }, +#endif +#if !defined(SQLITE_OMIT_AUTOVACUUM) + { /* zName: */ "incremental_vacuum", + /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "index_info", + /* ePragTyp: */ PragTyp_INDEX_INFO, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, + { /* zName: */ "index_list", + /* ePragTyp: */ PragTyp_INDEX_LIST, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_INTEGRITY_CHECK) + { /* zName: */ "integrity_check", + /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "journal_mode", + /* ePragTyp: */ PragTyp_JOURNAL_MODE, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, + { /* zName: */ "journal_size_limit", + /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if defined(SQLITE_HAS_CODEC) + { /* zName: */ "key", + /* ePragTyp: */ PragTyp_KEY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "legacy_file_format", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_LegacyFileFmt }, +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE + { /* zName: */ "lock_proxy_file", + /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) + { /* zName: */ "lock_status", + /* ePragTyp: */ PragTyp_LOCK_STATUS, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "locking_mode", + /* ePragTyp: */ PragTyp_LOCKING_MODE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "max_page_count", + /* ePragTyp: */ PragTyp_PAGE_COUNT, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, + { /* zName: */ "mmap_size", + /* ePragTyp: */ PragTyp_MMAP_SIZE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "page_count", + /* ePragTyp: */ PragTyp_PAGE_COUNT, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, + { /* zName: */ "page_size", + /* ePragTyp: */ PragTyp_PAGE_SIZE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if defined(SQLITE_DEBUG) + { /* zName: */ "parser_trace", + /* ePragTyp: */ PragTyp_PARSER_TRACE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "query_only", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_QueryOnly }, +#if !defined(SQLITE_OMIT_INTEGRITY_CHECK) + { /* zName: */ "quick_check", + /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif + { /* zName: */ "read_uncommitted", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_ReadUncommitted }, + { /* zName: */ "recursive_triggers", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_RecTriggers }, +#if defined(SQLITE_HAS_CODEC) + { /* zName: */ "rekey", + /* ePragTyp: */ PragTyp_REKEY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "reverse_unordered_selects", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_ReverseOrder }, +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + { /* zName: */ "schema_version", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "secure_delete", + /* ePragTyp: */ PragTyp_SECURE_DELETE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "short_column_names", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_ShortColNames }, + { /* zName: */ "shrink_memory", + /* ePragTyp: */ PragTyp_SHRINK_MEMORY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "soft_heap_limit", + /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#if defined(SQLITE_DEBUG) + { /* zName: */ "sql_trace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_SqlTrace }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "stats", + /* ePragTyp: */ PragTyp_STATS, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "synchronous", + /* ePragTyp: */ PragTyp_SYNCHRONOUS, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "table_info", + /* ePragTyp: */ PragTyp_TABLE_INFO, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "temp_store", + /* ePragTyp: */ PragTyp_TEMP_STORE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "temp_store_directory", + /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + { /* zName: */ "user_version", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if defined(SQLITE_DEBUG) + { /* zName: */ "vdbe_addoptrace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_VdbeAddopTrace }, + { /* zName: */ "vdbe_debug", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace }, + { /* zName: */ "vdbe_listing", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_VdbeListing }, + { /* zName: */ "vdbe_trace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_VdbeTrace }, +#endif +#if !defined(SQLITE_OMIT_WAL) + { /* zName: */ "wal_autocheckpoint", + /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "wal_checkpoint", + /* ePragTyp: */ PragTyp_WAL_CHECKPOINT, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif + { /* zName: */ "writable_schema", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode }, +}; +/* Number of pragmas: 56 on by default, 68 total. */ +/* End of the automatically generated pragma table. +***************************************************************************/ + +/* +** Interpret the given string as a safety level. Return 0 for OFF, +** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or +** unrecognized string argument. The FULL option is disallowed +** if the omitFull parameter it 1. +** +** Note that the values returned are one less that the values that +** should be passed into sqlite3BtreeSetSafetyLevel(). The is done +** to support legacy SQL code. The safety level used to be boolean +** and older scripts may have used numbers 0 for OFF and 1 for ON. +*/ +static u8 getSafetyLevel(const char *z, int omitFull, int dflt){ + /* 123456789 123456789 */ + static const char zText[] = "onoffalseyestruefull"; + static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16}; + static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4}; + static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2}; + int i, n; + if( sqlite3Isdigit(*z) ){ + return (u8)sqlite3Atoi(z); + } + n = sqlite3Strlen30(z); + for(i=0; i=0&&i<=2)?i:0); +} +#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */ + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* +** Interpret the given string as a temp db location. Return 1 for file +** backed temporary databases, 2 for the Red-Black tree in memory database +** and 0 to use the compile-time default. +*/ +static int getTempStore(const char *z){ + if( z[0]>='0' && z[0]<='2' ){ + return z[0] - '0'; + }else if( sqlite3StrICmp(z, "file")==0 ){ + return 1; + }else if( sqlite3StrICmp(z, "memory")==0 ){ + return 2; + }else{ + return 0; + } +} +#endif /* SQLITE_PAGER_PRAGMAS */ + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* +** Invalidate temp storage, either when the temp storage is changed +** from default, or when 'file' and the temp_store_directory has changed +*/ +static int invalidateTempStorage(Parse *pParse){ + sqlite3 *db = pParse->db; + if( db->aDb[1].pBt!=0 ){ + if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){ + sqlite3ErrorMsg(pParse, "temporary storage cannot be changed " + "from within a transaction"); + return SQLITE_ERROR; + } + sqlite3BtreeClose(db->aDb[1].pBt); + db->aDb[1].pBt = 0; + sqlite3ResetAllSchemasOfConnection(db); + } + return SQLITE_OK; +} +#endif /* SQLITE_PAGER_PRAGMAS */ + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* +** If the TEMP database is open, close it and mark the database schema +** as needing reloading. This must be done when using the SQLITE_TEMP_STORE +** or DEFAULT_TEMP_STORE pragmas. +*/ +static int changeTempStorage(Parse *pParse, const char *zStorageType){ + int ts = getTempStore(zStorageType); + sqlite3 *db = pParse->db; + if( db->temp_store==ts ) return SQLITE_OK; + if( invalidateTempStorage( pParse ) != SQLITE_OK ){ + return SQLITE_ERROR; + } + db->temp_store = (u8)ts; + return SQLITE_OK; +} +#endif /* SQLITE_PAGER_PRAGMAS */ + +/* +** Generate code to return a single integer value. +*/ +static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){ + Vdbe *v = sqlite3GetVdbe(pParse); + int mem = ++pParse->nMem; + i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value)); + if( pI64 ){ + memcpy(pI64, &value, sizeof(value)); + } + sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC); + sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1); +} + + +/* +** Set the safety_level and pager flags for pager iDb. Or if iDb<0 +** set these values for all pagers. +*/ +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +static void setAllPagerFlags(sqlite3 *db){ + if( db->autoCommit ){ + Db *pDb = db->aDb; + int n = db->nDb; + assert( SQLITE_FullFSync==PAGER_FULLFSYNC ); + assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC ); + assert( SQLITE_CacheSpill==PAGER_CACHESPILL ); + assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL) + == PAGER_FLAGS_MASK ); + assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level ); + while( (n--) > 0 ){ + if( pDb->pBt ){ + sqlite3BtreeSetPagerFlags(pDb->pBt, + pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) ); + } + pDb++; + } + } +} +#else +# define setAllPagerFlags(X) /* no-op */ +#endif + + +/* +** Return a human-readable name for a constraint resolution action. +*/ +#ifndef SQLITE_OMIT_FOREIGN_KEY +static const char *actionName(u8 action){ + const char *zName; + switch( action ){ + case OE_SetNull: zName = "SET NULL"; break; + case OE_SetDflt: zName = "SET DEFAULT"; break; + case OE_Cascade: zName = "CASCADE"; break; + case OE_Restrict: zName = "RESTRICT"; break; + default: zName = "NO ACTION"; + assert( action==OE_None ); break; + } + return zName; +} +#endif + + +/* +** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants +** defined in pager.h. This function returns the associated lowercase +** journal-mode name. +*/ +SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){ + static char * const azModeName[] = { + "delete", "persist", "off", "truncate", "memory" +#ifndef SQLITE_OMIT_WAL + , "wal" +#endif + }; + assert( PAGER_JOURNALMODE_DELETE==0 ); + assert( PAGER_JOURNALMODE_PERSIST==1 ); + assert( PAGER_JOURNALMODE_OFF==2 ); + assert( PAGER_JOURNALMODE_TRUNCATE==3 ); + assert( PAGER_JOURNALMODE_MEMORY==4 ); + assert( PAGER_JOURNALMODE_WAL==5 ); + assert( eMode>=0 && eMode<=ArraySize(azModeName) ); + + if( eMode==ArraySize(azModeName) ) return 0; + return azModeName[eMode]; +} + +/* +** Process a pragma statement. +** +** Pragmas are of this form: +** +** PRAGMA [database.]id [= value] +** +** The identifier might also be a string. The value is a string, and +** identifier, or a number. If minusFlag is true, then the value is +** a number that was preceded by a minus sign. +** +** If the left side is "database.id" then pId1 is the database name +** and pId2 is the id. If the left side is just "id" then pId1 is the +** id and pId2 is any empty string. +*/ +SQLITE_PRIVATE void sqlite3Pragma( + Parse *pParse, + Token *pId1, /* First part of [database.]id field */ + Token *pId2, /* Second part of [database.]id field, or NULL */ + Token *pValue, /* Token for , or NULL */ + int minusFlag /* True if a '-' sign preceded */ +){ + char *zLeft = 0; /* Nul-terminated UTF-8 string */ + char *zRight = 0; /* Nul-terminated UTF-8 string , or NULL */ + const char *zDb = 0; /* The database name */ + Token *pId; /* Pointer to token */ + char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */ + int iDb; /* Database index for */ + int lwr, upr, mid; /* Binary search bounds */ + int rc; /* return value form SQLITE_FCNTL_PRAGMA */ + sqlite3 *db = pParse->db; /* The database connection */ + Db *pDb; /* The specific database being pragmaed */ + Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */ + + if( v==0 ) return; + sqlite3VdbeRunOnlyOnce(v); + pParse->nMem = 2; + + /* Interpret the [database.] part of the pragma statement. iDb is the + ** index of the database this pragma is being applied to in db.aDb[]. */ + iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); + if( iDb<0 ) return; + pDb = &db->aDb[iDb]; + + /* If the temp database has been explicitly named as part of the + ** pragma, make sure it is open. + */ + if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ + return; + } + + zLeft = sqlite3NameFromToken(db, pId); + if( !zLeft ) return; + if( minusFlag ){ + zRight = sqlite3MPrintf(db, "-%T", pValue); + }else{ + zRight = sqlite3NameFromToken(db, pValue); + } + + assert( pId2 ); + zDb = pId2->n>0 ? pDb->zName : 0; + if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ + goto pragma_out; + } + + /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS + ** connection. If it returns SQLITE_OK, then assume that the VFS + ** handled the pragma and generate a no-op prepared statement. + */ + aFcntl[0] = 0; + aFcntl[1] = zLeft; + aFcntl[2] = zRight; + aFcntl[3] = 0; + db->busyHandler.nBusy = 0; + rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); + if( rc==SQLITE_OK ){ + if( aFcntl[0] ){ + int mem = ++pParse->nMem; + sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC); + sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1); + sqlite3_free(aFcntl[0]); + } + goto pragma_out; + } + if( rc!=SQLITE_NOTFOUND ){ + if( aFcntl[0] ){ + sqlite3ErrorMsg(pParse, "%s", aFcntl[0]); + sqlite3_free(aFcntl[0]); + } + pParse->nErr++; + pParse->rc = rc; + goto pragma_out; + } + + /* Locate the pragma in the lookup table */ + lwr = 0; + upr = ArraySize(aPragmaNames)-1; + while( lwr<=upr ){ + mid = (lwr+upr)/2; + rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName); + if( rc==0 ) break; + if( rc<0 ){ + upr = mid - 1; + }else{ + lwr = mid + 1; + } + } + if( lwr>upr ) goto pragma_out; + + /* Make sure the database schema is loaded if the pragma requires that */ + if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){ + if( sqlite3ReadSchema(pParse) ) goto pragma_out; + } + + /* Jump to the appropriate pragma handler */ + switch( aPragmaNames[mid].ePragTyp ){ + +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) + /* + ** PRAGMA [database.]default_cache_size + ** PRAGMA [database.]default_cache_size=N + ** + ** The first form reports the current persistent setting for the + ** page cache size. The value returned is the maximum number of + ** pages in the page cache. The second form sets both the current + ** page cache size value and the persistent page cache size value + ** stored in the database file. + ** + ** Older versions of SQLite would set the default cache size to a + ** negative number to indicate synchronous=OFF. These days, synchronous + ** is always on by default regardless of the sign of the default cache + ** size. But continue to take the absolute value of the default cache + ** size of historical compatibility. + */ + case PragTyp_DEFAULT_CACHE_SIZE: { + static const VdbeOpList getCacheSize[] = { + { OP_Transaction, 0, 0, 0}, /* 0 */ + { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */ + { OP_IfPos, 1, 8, 0}, + { OP_Integer, 0, 2, 0}, + { OP_Subtract, 1, 2, 1}, + { OP_IfPos, 1, 8, 0}, + { OP_Integer, 0, 1, 0}, /* 6 */ + { OP_Noop, 0, 0, 0}, + { OP_ResultRow, 1, 1, 0}, + }; + int addr; + sqlite3VdbeUsesBtree(v, iDb); + if( !zRight ){ + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC); + pParse->nMem += 2; + addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize); + sqlite3VdbeChangeP1(v, addr, iDb); + sqlite3VdbeChangeP1(v, addr+1, iDb); + sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE); + }else{ + int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3VdbeAddOp2(v, OP_Integer, size, 1); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1); + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pDb->pSchema->cache_size = size; + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); + } + break; + } +#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */ + +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + /* + ** PRAGMA [database.]page_size + ** PRAGMA [database.]page_size=N + ** + ** The first form reports the current setting for the + ** database page size in bytes. The second form sets the + ** database page size value. The value can only be set if + ** the database has not yet been created. + */ + case PragTyp_PAGE_SIZE: { + Btree *pBt = pDb->pBt; + assert( pBt!=0 ); + if( !zRight ){ + int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; + returnSingleInt(pParse, "page_size", size); + }else{ + /* Malloc may fail when setting the page-size, as there is an internal + ** buffer that the pager module resizes using sqlite3_realloc(). + */ + db->nextPagesize = sqlite3Atoi(zRight); + if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ + db->mallocFailed = 1; + } + } + break; + } + + /* + ** PRAGMA [database.]secure_delete + ** PRAGMA [database.]secure_delete=ON/OFF + ** + ** The first form reports the current setting for the + ** secure_delete flag. The second form changes the secure_delete + ** flag setting and reports thenew value. + */ + case PragTyp_SECURE_DELETE: { + Btree *pBt = pDb->pBt; + int b = -1; + assert( pBt!=0 ); + if( zRight ){ + b = sqlite3GetBoolean(zRight, 0); + } + if( pId2->n==0 && b>=0 ){ + int ii; + for(ii=0; iinDb; ii++){ + sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); + } + } + b = sqlite3BtreeSecureDelete(pBt, b); + returnSingleInt(pParse, "secure_delete", b); + break; + } + + /* + ** PRAGMA [database.]max_page_count + ** PRAGMA [database.]max_page_count=N + ** + ** The first form reports the current setting for the + ** maximum number of pages in the database file. The + ** second form attempts to change this setting. Both + ** forms return the current setting. + ** + ** The absolute value of N is used. This is undocumented and might + ** change. The only purpose is to provide an easy way to test + ** the sqlite3AbsInt32() function. + ** + ** PRAGMA [database.]page_count + ** + ** Return the number of pages in the specified database. + */ + case PragTyp_PAGE_COUNT: { + int iReg; + sqlite3CodeVerifySchema(pParse, iDb); + iReg = ++pParse->nMem; + if( sqlite3Tolower(zLeft[0])=='p' ){ + sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); + }else{ + sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, + sqlite3AbsInt32(sqlite3Atoi(zRight))); + } + sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT); + break; + } + + /* + ** PRAGMA [database.]locking_mode + ** PRAGMA [database.]locking_mode = (normal|exclusive) + */ + case PragTyp_LOCKING_MODE: { + const char *zRet = "normal"; + int eMode = getLockingMode(zRight); + + if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){ + /* Simple "PRAGMA locking_mode;" statement. This is a query for + ** the current default locking mode (which may be different to + ** the locking-mode of the main database). + */ + eMode = db->dfltLockMode; + }else{ + Pager *pPager; + if( pId2->n==0 ){ + /* This indicates that no database name was specified as part + ** of the PRAGMA command. In this case the locking-mode must be + ** set on all attached databases, as well as the main db file. + ** + ** Also, the sqlite3.dfltLockMode variable is set so that + ** any subsequently attached databases also use the specified + ** locking mode. + */ + int ii; + assert(pDb==&db->aDb[0]); + for(ii=2; iinDb; ii++){ + pPager = sqlite3BtreePager(db->aDb[ii].pBt); + sqlite3PagerLockingMode(pPager, eMode); + } + db->dfltLockMode = (u8)eMode; + } + pPager = sqlite3BtreePager(pDb->pBt); + eMode = sqlite3PagerLockingMode(pPager, eMode); + } + + assert( eMode==PAGER_LOCKINGMODE_NORMAL + || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); + if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ + zRet = "exclusive"; + } + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + break; + } + + /* + ** PRAGMA [database.]journal_mode + ** PRAGMA [database.]journal_mode = + ** (delete|persist|off|truncate|memory|wal|off) + */ + case PragTyp_JOURNAL_MODE: { + int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */ + int ii; /* Loop counter */ + + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC); + + if( zRight==0 ){ + /* If there is no "=MODE" part of the pragma, do a query for the + ** current mode */ + eMode = PAGER_JOURNALMODE_QUERY; + }else{ + const char *zMode; + int n = sqlite3Strlen30(zRight); + for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ + if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; + } + if( !zMode ){ + /* If the "=MODE" part does not match any known journal mode, + ** then do a query */ + eMode = PAGER_JOURNALMODE_QUERY; + } + } + if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ + /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */ + iDb = 0; + pId2->n = 1; + } + for(ii=db->nDb-1; ii>=0; ii--){ + if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ + sqlite3VdbeUsesBtree(v, ii); + sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); + } + } + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + break; + } + + /* + ** PRAGMA [database.]journal_size_limit + ** PRAGMA [database.]journal_size_limit=N + ** + ** Get or set the size limit on rollback journal files. + */ + case PragTyp_JOURNAL_SIZE_LIMIT: { + Pager *pPager = sqlite3BtreePager(pDb->pBt); + i64 iLimit = -2; + if( zRight ){ + sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8); + if( iLimit<-1 ) iLimit = -1; + } + iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); + returnSingleInt(pParse, "journal_size_limit", iLimit); + break; + } + +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */ + + /* + ** PRAGMA [database.]auto_vacuum + ** PRAGMA [database.]auto_vacuum=N + ** + ** Get or set the value of the database 'auto-vacuum' parameter. + ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL + */ +#ifndef SQLITE_OMIT_AUTOVACUUM + case PragTyp_AUTO_VACUUM: { + Btree *pBt = pDb->pBt; + assert( pBt!=0 ); + if( !zRight ){ + returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt)); + }else{ + int eAuto = getAutoVacuum(zRight); + assert( eAuto>=0 && eAuto<=2 ); + db->nextAutovac = (u8)eAuto; + /* Call SetAutoVacuum() to set initialize the internal auto and + ** incr-vacuum flags. This is required in case this connection + ** creates the database file. It is important that it is created + ** as an auto-vacuum capable db. + */ + rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); + if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ + /* When setting the auto_vacuum mode to either "full" or + ** "incremental", write the value of meta[6] in the database + ** file. Before writing to meta[6], check that meta[3] indicates + ** that this really is an auto-vacuum capable database. + */ + static const VdbeOpList setMeta6[] = { + { OP_Transaction, 0, 1, 0}, /* 0 */ + { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE}, + { OP_If, 1, 0, 0}, /* 2 */ + { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */ + { OP_Integer, 0, 1, 0}, /* 4 */ + { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */ + }; + int iAddr; + iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6); + sqlite3VdbeChangeP1(v, iAddr, iDb); + sqlite3VdbeChangeP1(v, iAddr+1, iDb); + sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4); + sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1); + sqlite3VdbeChangeP1(v, iAddr+5, iDb); + sqlite3VdbeUsesBtree(v, iDb); + } + } + break; + } +#endif + + /* + ** PRAGMA [database.]incremental_vacuum(N) + ** + ** Do N steps of incremental vacuuming on a database. + */ +#ifndef SQLITE_OMIT_AUTOVACUUM + case PragTyp_INCREMENTAL_VACUUM: { + int iLimit, addr; + if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ + iLimit = 0x7fffffff; + } + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); + addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); + sqlite3VdbeAddOp1(v, OP_ResultRow, 1); + sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); + sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); + sqlite3VdbeJumpHere(v, addr); + break; + } +#endif + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS + /* + ** PRAGMA [database.]cache_size + ** PRAGMA [database.]cache_size=N + ** + ** The first form reports the current local setting for the + ** page cache size. The second form sets the local + ** page cache size value. If N is positive then that is the + ** number of pages in the cache. If N is negative, then the + ** number of pages is adjusted so that the cache uses -N kibibytes + ** of memory. + */ + case PragTyp_CACHE_SIZE: { + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( !zRight ){ + returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size); + }else{ + int size = sqlite3Atoi(zRight); + pDb->pSchema->cache_size = size; + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); + } + break; + } + + /* + ** PRAGMA [database.]mmap_size(N) + ** + ** Used to set mapping size limit. The mapping size limit is + ** used to limit the aggregate size of all memory mapped regions of the + ** database file. If this parameter is set to zero, then memory mapping + ** is not used at all. If N is negative, then the default memory map + ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. + ** The parameter N is measured in bytes. + ** + ** This value is advisory. The underlying VFS is free to memory map + ** as little or as much as it wants. Except, if N is set to 0 then the + ** upper layers will never invoke the xFetch interfaces to the VFS. + */ + case PragTyp_MMAP_SIZE: { + sqlite3_int64 sz; +#if SQLITE_MAX_MMAP_SIZE>0 + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( zRight ){ + int ii; + sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8); + if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; + if( pId2->n==0 ) db->szMmap = sz; + for(ii=db->nDb-1; ii>=0; ii--){ + if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ + sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); + } + } + } + sz = -1; + rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); +#else + sz = 0; + rc = SQLITE_OK; +#endif + if( rc==SQLITE_OK ){ + returnSingleInt(pParse, "mmap_size", sz); + }else if( rc!=SQLITE_NOTFOUND ){ + pParse->nErr++; + pParse->rc = rc; + } + break; + } + + /* + ** PRAGMA temp_store + ** PRAGMA temp_store = "default"|"memory"|"file" + ** + ** Return or set the local value of the temp_store flag. Changing + ** the local value does not make changes to the disk file and the default + ** value will be restored the next time the database is opened. + ** + ** Note that it is possible for the library compile-time options to + ** override this setting + */ + case PragTyp_TEMP_STORE: { + if( !zRight ){ + returnSingleInt(pParse, "temp_store", db->temp_store); + }else{ + changeTempStorage(pParse, zRight); + } + break; + } + + /* + ** PRAGMA temp_store_directory + ** PRAGMA temp_store_directory = ""|"directory_name" + ** + ** Return or set the local value of the temp_store_directory flag. Changing + ** the value sets a specific directory to be used for temporary files. + ** Setting to a null string reverts to the default temporary directory search. + ** If temporary directory is changed, then invalidateTempStorage. + ** + */ + case PragTyp_TEMP_STORE_DIRECTORY: { + if( !zRight ){ + if( sqlite3_temp_directory ){ + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, + "temp_store_directory", SQLITE_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } + }else{ +#ifndef SQLITE_OMIT_WSD + if( zRight[0] ){ + int res; + rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); + if( rc!=SQLITE_OK || res==0 ){ + sqlite3ErrorMsg(pParse, "not a writable directory"); + goto pragma_out; + } + } + if( SQLITE_TEMP_STORE==0 + || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) + || (SQLITE_TEMP_STORE==2 && db->temp_store==1) + ){ + invalidateTempStorage(pParse); + } + sqlite3_free(sqlite3_temp_directory); + if( zRight[0] ){ + sqlite3_temp_directory = sqlite3_mprintf("%s", zRight); + }else{ + sqlite3_temp_directory = 0; + } +#endif /* SQLITE_OMIT_WSD */ + } + break; + } + +#if SQLITE_OS_WIN + /* + ** PRAGMA data_store_directory + ** PRAGMA data_store_directory = ""|"directory_name" + ** + ** Return or set the local value of the data_store_directory flag. Changing + ** the value sets a specific directory to be used for database files that + ** were specified with a relative pathname. Setting to a null string reverts + ** to the default database directory, which for database files specified with + ** a relative path will probably be based on the current directory for the + ** process. Database file specified with an absolute path are not impacted + ** by this setting, regardless of its value. + ** + */ + case PragTyp_DATA_STORE_DIRECTORY: { + if( !zRight ){ + if( sqlite3_data_directory ){ + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, + "data_store_directory", SQLITE_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } + }else{ +#ifndef SQLITE_OMIT_WSD + if( zRight[0] ){ + int res; + rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); + if( rc!=SQLITE_OK || res==0 ){ + sqlite3ErrorMsg(pParse, "not a writable directory"); + goto pragma_out; + } + } + sqlite3_free(sqlite3_data_directory); + if( zRight[0] ){ + sqlite3_data_directory = sqlite3_mprintf("%s", zRight); + }else{ + sqlite3_data_directory = 0; + } +#endif /* SQLITE_OMIT_WSD */ + } + break; + } +#endif + +#if SQLITE_ENABLE_LOCKING_STYLE + /* + ** PRAGMA [database.]lock_proxy_file + ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path" + ** + ** Return or set the value of the lock_proxy_file flag. Changing + ** the value sets a specific file to be used for database access locks. + ** + */ + case PragTyp_LOCK_PROXY_FILE: { + if( !zRight ){ + Pager *pPager = sqlite3BtreePager(pDb->pBt); + char *proxy_file_path = NULL; + sqlite3_file *pFile = sqlite3PagerFile(pPager); + sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, + &proxy_file_path); + + if( proxy_file_path ){ + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, + "lock_proxy_file", SQLITE_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } + }else{ + Pager *pPager = sqlite3BtreePager(pDb->pBt); + sqlite3_file *pFile = sqlite3PagerFile(pPager); + int res; + if( zRight[0] ){ + res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, + zRight); + } else { + res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, + NULL); + } + if( res!=SQLITE_OK ){ + sqlite3ErrorMsg(pParse, "failed to set lock proxy file"); + goto pragma_out; + } + } + break; + } +#endif /* SQLITE_ENABLE_LOCKING_STYLE */ + + /* + ** PRAGMA [database.]synchronous + ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL + ** + ** Return or set the local value of the synchronous flag. Changing + ** the local value does not make changes to the disk file and the + ** default value will be restored the next time the database is + ** opened. + */ + case PragTyp_SYNCHRONOUS: { + if( !zRight ){ + returnSingleInt(pParse, "synchronous", pDb->safety_level-1); + }else{ + if( !db->autoCommit ){ + sqlite3ErrorMsg(pParse, + "Safety level may not be changed inside a transaction"); + }else{ + pDb->safety_level = getSafetyLevel(zRight,0,1)+1; + setAllPagerFlags(db); + } + } + break; + } +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */ + +#ifndef SQLITE_OMIT_FLAG_PRAGMAS + case PragTyp_FLAG: { + if( zRight==0 ){ + returnSingleInt(pParse, aPragmaNames[mid].zName, + (db->flags & aPragmaNames[mid].iArg)!=0 ); + }else{ + int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */ + if( db->autoCommit==0 ){ + /* Foreign key support may not be enabled or disabled while not + ** in auto-commit mode. */ + mask &= ~(SQLITE_ForeignKeys); + } + + if( sqlite3GetBoolean(zRight, 0) ){ + db->flags |= mask; + }else{ + db->flags &= ~mask; + if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; + } + + /* Many of the flag-pragmas modify the code generated by the SQL + ** compiler (eg. count_changes). So add an opcode to expire all + ** compiled SQL statements after modifying a pragma value. + */ + sqlite3VdbeAddOp2(v, OP_Expire, 0, 0); + setAllPagerFlags(db); + } + break; + } +#endif /* SQLITE_OMIT_FLAG_PRAGMAS */ + +#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS + /* + ** PRAGMA table_info(
) + ** + ** Return a single row for each column of the named table. The columns of + ** the returned data set are: + ** + ** cid: Column id (numbered from left to right, starting at 0) + ** name: Column name + ** type: Column declaration type. + ** notnull: True if 'NOT NULL' is part of column declaration + ** dflt_value: The default value for the column, if any. + */ + case PragTyp_TABLE_INFO: if( zRight ){ + Table *pTab; + pTab = sqlite3FindTable(db, zRight, zDb); + if( pTab ){ + int i, k; + int nHidden = 0; + Column *pCol; + Index *pPk; + for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){} + sqlite3VdbeSetNumCols(v, 6); + pParse->nMem = 6; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC); + sqlite3ViewGetColumnNames(pParse, pTab); + for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ + if( IsHiddenColumn(pCol) ){ + nHidden++; + continue; + } + sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + pCol->zType ? pCol->zType : "", 0); + sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4); + if( pCol->zDflt ){ + sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0); + }else{ + sqlite3VdbeAddOp2(v, OP_Null, 0, 5); + } + if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ + k = 0; + }else if( pPk==0 ){ + k = 1; + }else{ + for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){} + } + sqlite3VdbeAddOp2(v, OP_Integer, k, 6); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6); + } + } + } + break; + + case PragTyp_STATS: { + Index *pIdx; + HashElem *i; + v = sqlite3GetVdbe(pParse); + sqlite3VdbeSetNumCols(v, 4); + pParse->nMem = 4; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC); + for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ + Table *pTab = sqliteHashData(i); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0); + sqlite3VdbeAddOp2(v, OP_Null, 0, 2); + sqlite3VdbeAddOp2(v, OP_Integer, + (int)sqlite3LogEstToInt(pTab->szTabRow), 3); + sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0); + sqlite3VdbeAddOp2(v, OP_Integer, + (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3); + sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); + } + } + } + break; + + case PragTyp_INDEX_INFO: if( zRight ){ + Index *pIdx; + Table *pTab; + pIdx = sqlite3FindIndex(db, zRight, zDb); + if( pIdx ){ + int i; + pTab = pIdx->pTable; + sqlite3VdbeSetNumCols(v, 3); + pParse->nMem = 3; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC); + for(i=0; inColumn; i++){ + int cnum = pIdx->aiColumn[i]; + sqlite3VdbeAddOp2(v, OP_Integer, i, 1); + sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2); + assert( pTab->nCol>cnum ); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + } + } + } + break; + + case PragTyp_INDEX_LIST: if( zRight ){ + Index *pIdx; + Table *pTab; + int i; + pTab = sqlite3FindTable(db, zRight, zDb); + if( pTab ){ + v = sqlite3GetVdbe(pParse); + sqlite3VdbeSetNumCols(v, 3); + pParse->nMem = 3; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC); + for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ + sqlite3VdbeAddOp2(v, OP_Integer, i, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0); + sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + } + } + } + break; + + case PragTyp_DATABASE_LIST: { + int i; + sqlite3VdbeSetNumCols(v, 3); + pParse->nMem = 3; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC); + for(i=0; inDb; i++){ + if( db->aDb[i].pBt==0 ) continue; + assert( db->aDb[i].zName!=0 ); + sqlite3VdbeAddOp2(v, OP_Integer, i, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + sqlite3BtreeGetFilename(db->aDb[i].pBt), 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + } + } + break; + + case PragTyp_COLLATION_LIST: { + int i = 0; + HashElem *p; + sqlite3VdbeSetNumCols(v, 2); + pParse->nMem = 2; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC); + for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ + CollSeq *pColl = (CollSeq *)sqliteHashData(p); + sqlite3VdbeAddOp2(v, OP_Integer, i++, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); + } + } + break; +#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */ + +#ifndef SQLITE_OMIT_FOREIGN_KEY + case PragTyp_FOREIGN_KEY_LIST: if( zRight ){ + FKey *pFK; + Table *pTab; + pTab = sqlite3FindTable(db, zRight, zDb); + if( pTab ){ + v = sqlite3GetVdbe(pParse); + pFK = pTab->pFKey; + if( pFK ){ + int i = 0; + sqlite3VdbeSetNumCols(v, 8); + pParse->nMem = 8; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC); + while(pFK){ + int j; + for(j=0; jnCol; j++){ + char *zCol = pFK->aCol[j].zCol; + char *zOnDelete = (char *)actionName(pFK->aAction[0]); + char *zOnUpdate = (char *)actionName(pFK->aAction[1]); + sqlite3VdbeAddOp2(v, OP_Integer, i, 1); + sqlite3VdbeAddOp2(v, OP_Integer, j, 2); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, + pTab->aCol[pFK->aCol[j].iFrom].zName, 0); + sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8); + } + ++i; + pFK = pFK->pNextFrom; + } + } + } + } + break; +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ + +#ifndef SQLITE_OMIT_FOREIGN_KEY +#ifndef SQLITE_OMIT_TRIGGER + case PragTyp_FOREIGN_KEY_CHECK: { + FKey *pFK; /* A foreign key constraint */ + Table *pTab; /* Child table contain "REFERENCES" keyword */ + Table *pParent; /* Parent table that child points to */ + Index *pIdx; /* Index in the parent table */ + int i; /* Loop counter: Foreign key number for pTab */ + int j; /* Loop counter: Field of the foreign key */ + HashElem *k; /* Loop counter: Next table in schema */ + int x; /* result variable */ + int regResult; /* 3 registers to hold a result row */ + int regKey; /* Register to hold key for checking the FK */ + int regRow; /* Registers to hold a row from pTab */ + int addrTop; /* Top of a loop checking foreign keys */ + int addrOk; /* Jump here if the key is OK */ + int *aiCols; /* child to parent column mapping */ + + regResult = pParse->nMem+1; + pParse->nMem += 4; + regKey = ++pParse->nMem; + regRow = ++pParse->nMem; + v = sqlite3GetVdbe(pParse); + sqlite3VdbeSetNumCols(v, 4); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC); + sqlite3CodeVerifySchema(pParse, iDb); + k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); + while( k ){ + if( zRight ){ + pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); + k = 0; + }else{ + pTab = (Table*)sqliteHashData(k); + k = sqliteHashNext(k); + } + if( pTab==0 || pTab->pFKey==0 ) continue; + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; + sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead); + sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName, + P4_TRANSIENT); + for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ + pParent = sqlite3FindTable(db, pFK->zTo, zDb); + if( pParent==0 ) continue; + pIdx = 0; + sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName); + x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); + if( x==0 ){ + if( pIdx==0 ){ + sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead); + }else{ + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb); + sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); + } + }else{ + k = 0; + break; + } + } + assert( pParse->nErr>0 || pFK==0 ); + if( pFK ) break; + if( pParse->nTabnTab = i; + addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); + for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ + pParent = sqlite3FindTable(db, pFK->zTo, zDb); + pIdx = 0; + aiCols = 0; + if( pParent ){ + x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); + assert( x==0 ); + } + addrOk = sqlite3VdbeMakeLabel(v); + if( pParent && pIdx==0 ){ + int iKey = pFK->aCol[0].iFrom; + assert( iKey>=0 && iKeynCol ); + if( iKey!=pTab->iPKey ){ + sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow); + sqlite3ColumnDefault(v, pTab, iKey, regRow); + sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); + sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow, + sqlite3VdbeCurrentAddr(v)+3); + }else{ + sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow); + } + sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk); + sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); + }else{ + for(j=0; jnCol; j++){ + sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, + aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j); + sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); + } + if( pParent ){ + sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey); + sqlite3VdbeChangeP4(v, -1, + sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT); + sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); + } + } + sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); + sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0, + pFK->zTo, P4_TRANSIENT); + sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3); + sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); + sqlite3VdbeResolveLabel(v, addrOk); + sqlite3DbFree(db, aiCols); + } + sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); + sqlite3VdbeJumpHere(v, addrTop); + } + } + break; +#endif /* !defined(SQLITE_OMIT_TRIGGER) */ +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ + +#ifndef NDEBUG + case PragTyp_PARSER_TRACE: { + if( zRight ){ + if( sqlite3GetBoolean(zRight, 0) ){ + sqlite3ParserTrace(stderr, "parser: "); + }else{ + sqlite3ParserTrace(0, 0); + } + } + } + break; +#endif + + /* Reinstall the LIKE and GLOB functions. The variant of LIKE + ** used will be case sensitive or not depending on the RHS. + */ + case PragTyp_CASE_SENSITIVE_LIKE: { + if( zRight ){ + sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); + } + } + break; + +#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX +# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 +#endif + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK + /* Pragma "quick_check" is reduced version of + ** integrity_check designed to detect most database corruption + ** without most of the overhead of a full integrity-check. + */ + case PragTyp_INTEGRITY_CHECK: { + int i, j, addr, mxErr; + + /* Code that appears at the end of the integrity check. If no error + ** messages have been generated, output OK. Otherwise output the + ** error message + */ + static const VdbeOpList endCode[] = { + { OP_AddImm, 1, 0, 0}, /* 0 */ + { OP_IfNeg, 1, 0, 0}, /* 1 */ + { OP_String8, 0, 3, 0}, /* 2 */ + { OP_ResultRow, 3, 1, 0}, + }; + + int isQuick = (sqlite3Tolower(zLeft[0])=='q'); + + /* If the PRAGMA command was of the form "PRAGMA .integrity_check", + ** then iDb is set to the index of the database identified by . + ** In this case, the integrity of database iDb only is verified by + ** the VDBE created below. + ** + ** Otherwise, if the command was simply "PRAGMA integrity_check" (or + ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb + ** to -1 here, to indicate that the VDBE should verify the integrity + ** of all attached databases. */ + assert( iDb>=0 ); + assert( iDb==0 || pId2->z ); + if( pId2->z==0 ) iDb = -1; + + /* Initialize the VDBE program */ + pParse->nMem = 6; + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC); + + /* Set the maximum error count */ + mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; + if( zRight ){ + sqlite3GetInt32(zRight, &mxErr); + if( mxErr<=0 ){ + mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; + } + } + sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */ + + /* Do an integrity check on each database file */ + for(i=0; inDb; i++){ + HashElem *x; + Hash *pTbls; + int cnt = 0; + + if( OMIT_TEMPDB && i==1 ) continue; + if( iDb>=0 && i!=iDb ) continue; + + sqlite3CodeVerifySchema(pParse, i); + addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */ + sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); + sqlite3VdbeJumpHere(v, addr); + + /* Do an integrity check of the B-Tree + ** + ** Begin by filling registers 2, 3, ... with the root pages numbers + ** for all tables and indices in the database. + */ + assert( sqlite3SchemaMutexHeld(db, i, 0) ); + pTbls = &db->aDb[i].pSchema->tblHash; + for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ + Table *pTab = sqliteHashData(x); + Index *pIdx; + sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt); + cnt++; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt); + cnt++; + } + } + + /* Make sure sufficient number of registers have been allocated */ + pParse->nMem = MAX( pParse->nMem, cnt+7 ); + + /* Do the b-tree integrity checks */ + sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1); + sqlite3VdbeChangeP5(v, (u8)i); + addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName), + P4_DYNAMIC); + sqlite3VdbeAddOp2(v, OP_Move, 2, 4); + sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2); + sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1); + sqlite3VdbeJumpHere(v, addr); + + /* Make sure all the indices are constructed correctly. + */ + for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){ + Table *pTab = sqliteHashData(x); + Index *pIdx; + int loopTop; + + if( pTab->pIndex==0 ) continue; + addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */ + sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); + sqlite3VdbeJumpHere(v, addr); + sqlite3ExprCacheClear(pParse); + sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead); + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */ + } + pParse->nMem = MAX(pParse->nMem, 7+j); + loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1; + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + int jmp2, jmp3; + int r1; + static const VdbeOpList idxErr[] = { + { OP_AddImm, 1, -1, 0}, + { OP_String8, 0, 3, 0}, /* 1 */ + { OP_Rowid, 1, 4, 0}, + { OP_String8, 0, 5, 0}, /* 3 */ + { OP_String8, 0, 6, 0}, /* 4 */ + { OP_Concat, 4, 3, 3}, + { OP_Concat, 5, 3, 3}, + { OP_Concat, 6, 3, 3}, + { OP_ResultRow, 3, 1, 0}, + { OP_IfPos, 1, 0, 0}, /* 9 */ + { OP_Halt, 0, 0, 0}, + }; + r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3); + sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1); /* increment entry count */ + jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1); + addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr); + sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC); + sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC); + sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT); + sqlite3VdbeJumpHere(v, addr+9); + sqlite3VdbeJumpHere(v, jmp2); + sqlite3VdbeResolveLabel(v, jmp3); + } + sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop); + sqlite3VdbeJumpHere(v, loopTop-1); +#ifndef SQLITE_OMIT_BTREECOUNT + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, + "wrong # of entries in index ", P4_STATIC); + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + addr = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); + sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); + sqlite3VdbeAddOp2(v, OP_Count, j+2, 3); + sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3); + sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT); + sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7); + sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1); + } +#endif /* SQLITE_OMIT_BTREECOUNT */ + } + } + addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode); + sqlite3VdbeChangeP2(v, addr, -mxErr); + sqlite3VdbeJumpHere(v, addr+1); + sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC); + } + break; +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +#ifndef SQLITE_OMIT_UTF16 + /* + ** PRAGMA encoding + ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" + ** + ** In its first form, this pragma returns the encoding of the main + ** database. If the database is not initialized, it is initialized now. + ** + ** The second form of this pragma is a no-op if the main database file + ** has not already been initialized. In this case it sets the default + ** encoding that will be used for the main database file if a new file + ** is created. If an existing main database file is opened, then the + ** default text encoding for the existing database is used. + ** + ** In all cases new databases created using the ATTACH command are + ** created to use the same default text encoding as the main database. If + ** the main database has not been initialized and/or created when ATTACH + ** is executed, this is done before the ATTACH operation. + ** + ** In the second form this pragma sets the text encoding to be used in + ** new database files created using this database handle. It is only + ** useful if invoked immediately after the main database i + */ + case PragTyp_ENCODING: { + static const struct EncName { + char *zName; + u8 enc; + } encnames[] = { + { "UTF8", SQLITE_UTF8 }, + { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */ + { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */ + { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */ + { "UTF16le", SQLITE_UTF16LE }, + { "UTF16be", SQLITE_UTF16BE }, + { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */ + { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */ + { 0, 0 } + }; + const struct EncName *pEnc; + if( !zRight ){ /* "PRAGMA encoding" */ + if( sqlite3ReadSchema(pParse) ) goto pragma_out; + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC); + sqlite3VdbeAddOp2(v, OP_String8, 0, 1); + assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); + assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); + assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); + sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + }else{ /* "PRAGMA encoding = XXX" */ + /* Only change the value of sqlite.enc if the database handle is not + ** initialized. If the main database exists, the new sqlite.enc value + ** will be overwritten when the schema is next loaded. If it does not + ** already exists, it will be created to use the new encoding value. + */ + if( + !(DbHasProperty(db, 0, DB_SchemaLoaded)) || + DbHasProperty(db, 0, DB_Empty) + ){ + for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ + if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ + ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; + break; + } + } + if( !pEnc->zName ){ + sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight); + } + } + } + } + break; +#endif /* SQLITE_OMIT_UTF16 */ + +#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS + /* + ** PRAGMA [database.]schema_version + ** PRAGMA [database.]schema_version = + ** + ** PRAGMA [database.]user_version + ** PRAGMA [database.]user_version = + ** + ** PRAGMA [database.]freelist_count = + ** + ** PRAGMA [database.]application_id + ** PRAGMA [database.]application_id = + ** + ** The pragma's schema_version and user_version are used to set or get + ** the value of the schema-version and user-version, respectively. Both + ** the schema-version and the user-version are 32-bit signed integers + ** stored in the database header. + ** + ** The schema-cookie is usually only manipulated internally by SQLite. It + ** is incremented by SQLite whenever the database schema is modified (by + ** creating or dropping a table or index). The schema version is used by + ** SQLite each time a query is executed to ensure that the internal cache + ** of the schema used when compiling the SQL query matches the schema of + ** the database against which the compiled query is actually executed. + ** Subverting this mechanism by using "PRAGMA schema_version" to modify + ** the schema-version is potentially dangerous and may lead to program + ** crashes or database corruption. Use with caution! + ** + ** The user-version is not used internally by SQLite. It may be used by + ** applications for any purpose. + */ + case PragTyp_HEADER_VALUE: { + int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */ + sqlite3VdbeUsesBtree(v, iDb); + switch( zLeft[0] ){ + case 'a': case 'A': + iCookie = BTREE_APPLICATION_ID; + break; + case 'f': case 'F': + iCookie = BTREE_FREE_PAGE_COUNT; + break; + case 's': case 'S': + iCookie = BTREE_SCHEMA_VERSION; + break; + default: + iCookie = BTREE_USER_VERSION; + break; + } + + if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){ + /* Write the specified cookie value */ + static const VdbeOpList setCookie[] = { + { OP_Transaction, 0, 1, 0}, /* 0 */ + { OP_Integer, 0, 1, 0}, /* 1 */ + { OP_SetCookie, 0, 0, 1}, /* 2 */ + }; + int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie); + sqlite3VdbeChangeP1(v, addr, iDb); + sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight)); + sqlite3VdbeChangeP1(v, addr+2, iDb); + sqlite3VdbeChangeP2(v, addr+2, iCookie); + }else{ + /* Read the specified cookie value */ + static const VdbeOpList readCookie[] = { + { OP_Transaction, 0, 0, 0}, /* 0 */ + { OP_ReadCookie, 0, 1, 0}, /* 1 */ + { OP_ResultRow, 1, 1, 0} + }; + int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie); + sqlite3VdbeChangeP1(v, addr, iDb); + sqlite3VdbeChangeP1(v, addr+1, iDb); + sqlite3VdbeChangeP3(v, addr+1, iCookie); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT); + } + } + break; +#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ + +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS + /* + ** PRAGMA compile_options + ** + ** Return the names of all compile-time options used in this build, + ** one option per row. + */ + case PragTyp_COMPILE_OPTIONS: { + int i = 0; + const char *zOpt; + sqlite3VdbeSetNumCols(v, 1); + pParse->nMem = 1; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC); + while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } + } + break; +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + +#ifndef SQLITE_OMIT_WAL + /* + ** PRAGMA [database.]wal_checkpoint = passive|full|restart + ** + ** Checkpoint the database. + */ + case PragTyp_WAL_CHECKPOINT: { + int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); + int eMode = SQLITE_CHECKPOINT_PASSIVE; + if( zRight ){ + if( sqlite3StrICmp(zRight, "full")==0 ){ + eMode = SQLITE_CHECKPOINT_FULL; + }else if( sqlite3StrICmp(zRight, "restart")==0 ){ + eMode = SQLITE_CHECKPOINT_RESTART; + } + } + sqlite3VdbeSetNumCols(v, 3); + pParse->nMem = 3; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC); + + sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + } + break; + + /* + ** PRAGMA wal_autocheckpoint + ** PRAGMA wal_autocheckpoint = N + ** + ** Configure a database connection to automatically checkpoint a database + ** after accumulating N frames in the log. Or query for the current value + ** of N. + */ + case PragTyp_WAL_AUTOCHECKPOINT: { + if( zRight ){ + sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); + } + returnSingleInt(pParse, "wal_autocheckpoint", + db->xWalCallback==sqlite3WalDefaultHook ? + SQLITE_PTR_TO_INT(db->pWalArg) : 0); + } + break; +#endif + + /* + ** PRAGMA shrink_memory + ** + ** This pragma attempts to free as much memory as possible from the + ** current database connection. + */ + case PragTyp_SHRINK_MEMORY: { + sqlite3_db_release_memory(db); + break; + } + + /* + ** PRAGMA busy_timeout + ** PRAGMA busy_timeout = N + ** + ** Call sqlite3_busy_timeout(db, N). Return the current timeout value + ** if one is set. If no busy handler or a different busy handler is set + ** then 0 is returned. Setting the busy_timeout to 0 or negative + ** disables the timeout. + */ + /*case PragTyp_BUSY_TIMEOUT*/ default: { + assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT ); + if( zRight ){ + sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); + } + returnSingleInt(pParse, "timeout", db->busyTimeout); + break; + } + + /* + ** PRAGMA soft_heap_limit + ** PRAGMA soft_heap_limit = N + ** + ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted, + ** use -1. + */ + case PragTyp_SOFT_HEAP_LIMIT: { + sqlite3_int64 N; + if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){ + sqlite3_soft_heap_limit64(N); + } + returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1)); + break; + } + +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) + /* + ** Report the current state of file logs for all databases + */ + case PragTyp_LOCK_STATUS: { + static const char *const azLockName[] = { + "unlocked", "shared", "reserved", "pending", "exclusive" + }; + int i; + sqlite3VdbeSetNumCols(v, 2); + pParse->nMem = 2; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC); + for(i=0; inDb; i++){ + Btree *pBt; + const char *zState = "unknown"; + int j; + if( db->aDb[i].zName==0 ) continue; + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC); + pBt = db->aDb[i].pBt; + if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ + zState = "closed"; + }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, + SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ + zState = azLockName[j]; + } + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); + } + break; + } +#endif + +#ifdef SQLITE_HAS_CODEC + case PragTyp_KEY: { + if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); + break; + } + case PragTyp_REKEY: { + if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); + break; + } + case PragTyp_HEXKEY: { + if( zRight ){ + u8 iByte; + int i; + char zKey[40]; + for(i=0, iByte=0; idb; + if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){ + if( zObj==0 ) zObj = "?"; + sqlite3SetString(pData->pzErrMsg, db, + "malformed database schema (%s)", zObj); + if( zExtra ){ + *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, + "%s - %s", *pData->pzErrMsg, zExtra); + } + } + pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT; +} + +/* +** This is the callback routine for the code that initializes the +** database. See sqlite3Init() below for additional information. +** This routine is also called from the OP_ParseSchema opcode of the VDBE. +** +** Each callback contains the following information: +** +** argv[0] = name of thing being created +** argv[1] = root page number for table or index. 0 for trigger or view. +** argv[2] = SQL text for the CREATE statement. +** +*/ +SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){ + InitData *pData = (InitData*)pInit; + sqlite3 *db = pData->db; + int iDb = pData->iDb; + + assert( argc==3 ); + UNUSED_PARAMETER2(NotUsed, argc); + assert( sqlite3_mutex_held(db->mutex) ); + DbClearProperty(db, iDb, DB_Empty); + if( db->mallocFailed ){ + corruptSchema(pData, argv[0], 0); + return 1; + } + + assert( iDb>=0 && iDbnDb ); + if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ + if( argv[1]==0 ){ + corruptSchema(pData, argv[0], 0); + }else if( argv[2] && argv[2][0] ){ + /* Call the parser to process a CREATE TABLE, INDEX or VIEW. + ** But because db->init.busy is set to 1, no VDBE code is generated + ** or executed. All the parser does is build the internal data + ** structures that describe the table, index, or view. + */ + int rc; + sqlite3_stmt *pStmt; + TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ + + assert( db->init.busy ); + db->init.iDb = iDb; + db->init.newTnum = sqlite3Atoi(argv[1]); + db->init.orphanTrigger = 0; + TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0); + rc = db->errCode; + assert( (rc&0xFF)==(rcp&0xFF) ); + db->init.iDb = 0; + if( SQLITE_OK!=rc ){ + if( db->init.orphanTrigger ){ + assert( iDb==1 ); + }else{ + pData->rc = rc; + if( rc==SQLITE_NOMEM ){ + db->mallocFailed = 1; + }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){ + corruptSchema(pData, argv[0], sqlite3_errmsg(db)); + } + } + } + sqlite3_finalize(pStmt); + }else if( argv[0]==0 ){ + corruptSchema(pData, 0, 0); + }else{ + /* If the SQL column is blank it means this is an index that + ** was created to be the PRIMARY KEY or to fulfill a UNIQUE + ** constraint for a CREATE TABLE. The index should have already + ** been created when we processed the CREATE TABLE. All we have + ** to do here is record the root page number for that index. + */ + Index *pIndex; + pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName); + if( pIndex==0 ){ + /* This can occur if there exists an index on a TEMP table which + ** has the same name as another index on a permanent index. Since + ** the permanent table is hidden by the TEMP table, we can also + ** safely ignore the index on the permanent table. + */ + /* Do Nothing */; + }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){ + corruptSchema(pData, argv[0], "invalid rootpage"); + } + } + return 0; +} + +/* +** Attempt to read the database schema and initialize internal +** data structures for a single database file. The index of the +** database file is given by iDb. iDb==0 is used for the main +** database. iDb==1 should never be used. iDb>=2 is used for +** auxiliary databases. Return one of the SQLITE_ error codes to +** indicate success or failure. +*/ +static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ + int rc; + int i; +#ifndef SQLITE_OMIT_DEPRECATED + int size; +#endif + Table *pTab; + Db *pDb; + char const *azArg[4]; + int meta[5]; + InitData initData; + char const *zMasterSchema; + char const *zMasterName; + int openedTransaction = 0; + + /* + ** The master database table has a structure like this + */ + static const char master_schema[] = + "CREATE TABLE sqlite_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" + ; +#ifndef SQLITE_OMIT_TEMPDB + static const char temp_master_schema[] = + "CREATE TEMP TABLE sqlite_temp_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" + ; +#else + #define temp_master_schema 0 +#endif + + assert( iDb>=0 && iDbnDb ); + assert( db->aDb[iDb].pSchema ); + assert( sqlite3_mutex_held(db->mutex) ); + assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); + + /* zMasterSchema and zInitScript are set to point at the master schema + ** and initialisation script appropriate for the database being + ** initialized. zMasterName is the name of the master table. + */ + if( !OMIT_TEMPDB && iDb==1 ){ + zMasterSchema = temp_master_schema; + }else{ + zMasterSchema = master_schema; + } + zMasterName = SCHEMA_TABLE(iDb); + + /* Construct the schema tables. */ + azArg[0] = zMasterName; + azArg[1] = "1"; + azArg[2] = zMasterSchema; + azArg[3] = 0; + initData.db = db; + initData.iDb = iDb; + initData.rc = SQLITE_OK; + initData.pzErrMsg = pzErrMsg; + sqlite3InitCallback(&initData, 3, (char **)azArg, 0); + if( initData.rc ){ + rc = initData.rc; + goto error_out; + } + pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName); + if( ALWAYS(pTab) ){ + pTab->tabFlags |= TF_Readonly; + } + + /* Create a cursor to hold the database open + */ + pDb = &db->aDb[iDb]; + if( pDb->pBt==0 ){ + if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){ + DbSetProperty(db, 1, DB_SchemaLoaded); + } + return SQLITE_OK; + } + + /* If there is not already a read-only (or read-write) transaction opened + ** on the b-tree database, open one now. If a transaction is opened, it + ** will be closed before this function returns. */ + sqlite3BtreeEnter(pDb->pBt); + if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){ + rc = sqlite3BtreeBeginTrans(pDb->pBt, 0); + if( rc!=SQLITE_OK ){ + sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc)); + goto initone_error_out; + } + openedTransaction = 1; + } + + /* Get the database meta information. + ** + ** Meta values are as follows: + ** meta[0] Schema cookie. Changes with each schema change. + ** meta[1] File format of schema layer. + ** meta[2] Size of the page cache. + ** meta[3] Largest rootpage (auto/incr_vacuum mode) + ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE + ** meta[5] User version + ** meta[6] Incremental vacuum mode + ** meta[7] unused + ** meta[8] unused + ** meta[9] unused + ** + ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to + ** the possible values of meta[4]. + */ + for(i=0; ipBt, i+1, (u32 *)&meta[i]); + } + pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1]; + + /* If opening a non-empty database, check the text encoding. For the + ** main database, set sqlite3.enc to the encoding of the main database. + ** For an attached db, it is an error if the encoding is not the same + ** as sqlite3.enc. + */ + if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */ + if( iDb==0 ){ +#ifndef SQLITE_OMIT_UTF16 + u8 encoding; + /* If opening the main database, set ENC(db). */ + encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3; + if( encoding==0 ) encoding = SQLITE_UTF8; + ENC(db) = encoding; +#else + ENC(db) = SQLITE_UTF8; +#endif + }else{ + /* If opening an attached database, the encoding much match ENC(db) */ + if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){ + sqlite3SetString(pzErrMsg, db, "attached databases must use the same" + " text encoding as main database"); + rc = SQLITE_ERROR; + goto initone_error_out; + } + } + }else{ + DbSetProperty(db, iDb, DB_Empty); + } + pDb->pSchema->enc = ENC(db); + + if( pDb->pSchema->cache_size==0 ){ +#ifndef SQLITE_OMIT_DEPRECATED + size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]); + if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; } + pDb->pSchema->cache_size = size; +#else + pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE; +#endif + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); + } + + /* + ** file_format==1 Version 3.0.0. + ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN + ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults + ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants + */ + pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1]; + if( pDb->pSchema->file_format==0 ){ + pDb->pSchema->file_format = 1; + } + if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){ + sqlite3SetString(pzErrMsg, db, "unsupported file format"); + rc = SQLITE_ERROR; + goto initone_error_out; + } + + /* Ticket #2804: When we open a database in the newer file format, + ** clear the legacy_file_format pragma flag so that a VACUUM will + ** not downgrade the database and thus invalidate any descending + ** indices that the user might have created. + */ + if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){ + db->flags &= ~SQLITE_LegacyFileFmt; + } + + /* Read the schema information out of the schema tables + */ + assert( db->init.busy ); + { + char *zSql; + zSql = sqlite3MPrintf(db, + "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid", + db->aDb[iDb].zName, zMasterName); +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); + xAuth = db->xAuth; + db->xAuth = 0; +#endif + rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); +#ifndef SQLITE_OMIT_AUTHORIZATION + db->xAuth = xAuth; + } +#endif + if( rc==SQLITE_OK ) rc = initData.rc; + sqlite3DbFree(db, zSql); +#ifndef SQLITE_OMIT_ANALYZE + if( rc==SQLITE_OK ){ + sqlite3AnalysisLoad(db, iDb); + } +#endif + } + if( db->mallocFailed ){ + rc = SQLITE_NOMEM; + sqlite3ResetAllSchemasOfConnection(db); + } + if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){ + /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider + ** the schema loaded, even if errors occurred. In this situation the + ** current sqlite3_prepare() operation will fail, but the following one + ** will attempt to compile the supplied statement against whatever subset + ** of the schema was loaded before the error occurred. The primary + ** purpose of this is to allow access to the sqlite_master table + ** even when its contents have been corrupted. + */ + DbSetProperty(db, iDb, DB_SchemaLoaded); + rc = SQLITE_OK; + } + + /* Jump here for an error that occurs after successfully allocating + ** curMain and calling sqlite3BtreeEnter(). For an error that occurs + ** before that point, jump to error_out. + */ +initone_error_out: + if( openedTransaction ){ + sqlite3BtreeCommit(pDb->pBt); + } + sqlite3BtreeLeave(pDb->pBt); + +error_out: + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ + db->mallocFailed = 1; + } + return rc; +} + +/* +** Initialize all database files - the main database file, the file +** used to store temporary tables, and any additional database files +** created using ATTACH statements. Return a success code. If an +** error occurs, write an error message into *pzErrMsg. +** +** After a database is initialized, the DB_SchemaLoaded bit is set +** bit is set in the flags field of the Db structure. If the database +** file was of zero-length, then the DB_Empty flag is also set. +*/ +SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){ + int i, rc; + int commit_internal = !(db->flags&SQLITE_InternChanges); + + assert( sqlite3_mutex_held(db->mutex) ); + rc = SQLITE_OK; + db->init.busy = 1; + for(i=0; rc==SQLITE_OK && inDb; i++){ + if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue; + rc = sqlite3InitOne(db, i, pzErrMsg); + if( rc ){ + sqlite3ResetOneSchema(db, i); + } + } + + /* Once all the other databases have been initialized, load the schema + ** for the TEMP database. This is loaded last, as the TEMP database + ** schema may contain references to objects in other databases. + */ +#ifndef SQLITE_OMIT_TEMPDB + if( rc==SQLITE_OK && ALWAYS(db->nDb>1) + && !DbHasProperty(db, 1, DB_SchemaLoaded) ){ + rc = sqlite3InitOne(db, 1, pzErrMsg); + if( rc ){ + sqlite3ResetOneSchema(db, 1); + } + } +#endif + + db->init.busy = 0; + if( rc==SQLITE_OK && commit_internal ){ + sqlite3CommitInternalChanges(db); + } + + return rc; +} + +/* +** This routine is a no-op if the database schema is already initialized. +** Otherwise, the schema is loaded. An error code is returned. +*/ +SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){ + int rc = SQLITE_OK; + sqlite3 *db = pParse->db; + assert( sqlite3_mutex_held(db->mutex) ); + if( !db->init.busy ){ + rc = sqlite3Init(db, &pParse->zErrMsg); + } + if( rc!=SQLITE_OK ){ + pParse->rc = rc; + pParse->nErr++; + } + return rc; +} + + +/* +** Check schema cookies in all databases. If any cookie is out +** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies +** make no changes to pParse->rc. +*/ +static void schemaIsValid(Parse *pParse){ + sqlite3 *db = pParse->db; + int iDb; + int rc; + int cookie; + + assert( pParse->checkSchema ); + assert( sqlite3_mutex_held(db->mutex) ); + for(iDb=0; iDbnDb; iDb++){ + int openedTransaction = 0; /* True if a transaction is opened */ + Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */ + if( pBt==0 ) continue; + + /* If there is not already a read-only (or read-write) transaction opened + ** on the b-tree database, open one now. If a transaction is opened, it + ** will be closed immediately after reading the meta-value. */ + if( !sqlite3BtreeIsInReadTrans(pBt) ){ + rc = sqlite3BtreeBeginTrans(pBt, 0); + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ + db->mallocFailed = 1; + } + if( rc!=SQLITE_OK ) return; + openedTransaction = 1; + } + + /* Read the schema cookie from the database. If it does not match the + ** value stored as part of the in-memory schema representation, + ** set Parse.rc to SQLITE_SCHEMA. */ + sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie); + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){ + sqlite3ResetOneSchema(db, iDb); + pParse->rc = SQLITE_SCHEMA; + } + + /* Close the transaction, if one was opened. */ + if( openedTransaction ){ + sqlite3BtreeCommit(pBt); + } + } +} + +/* +** Convert a schema pointer into the iDb index that indicates +** which database file in db->aDb[] the schema refers to. +** +** If the same database is attached more than once, the first +** attached database is returned. +*/ +SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ + int i = -1000000; + + /* If pSchema is NULL, then return -1000000. This happens when code in + ** expr.c is trying to resolve a reference to a transient table (i.e. one + ** created by a sub-select). In this case the return value of this + ** function should never be used. + ** + ** We return -1000000 instead of the more usual -1 simply because using + ** -1000000 as the incorrect index into db->aDb[] is much + ** more likely to cause a segfault than -1 (of course there are assert() + ** statements too, but it never hurts to play the odds). + */ + assert( sqlite3_mutex_held(db->mutex) ); + if( pSchema ){ + for(i=0; ALWAYS(inDb); i++){ + if( db->aDb[i].pSchema==pSchema ){ + break; + } + } + assert( i>=0 && inDb ); + } + return i; +} + +/* +** Compile the UTF-8 encoded SQL statement zSql into a statement handle. +*/ +static int sqlite3Prepare( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ + Vdbe *pReprepare, /* VM being reprepared */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +){ + Parse *pParse; /* Parsing context */ + char *zErrMsg = 0; /* Error message */ + int rc = SQLITE_OK; /* Result code */ + int i; /* Loop counter */ + + /* Allocate the parsing context */ + pParse = sqlite3StackAllocZero(db, sizeof(*pParse)); + if( pParse==0 ){ + rc = SQLITE_NOMEM; + goto end_prepare; + } + pParse->pReprepare = pReprepare; + assert( ppStmt && *ppStmt==0 ); + assert( !db->mallocFailed ); + assert( sqlite3_mutex_held(db->mutex) ); + + /* Check to verify that it is possible to get a read lock on all + ** database schemas. The inability to get a read lock indicates that + ** some other database connection is holding a write-lock, which in + ** turn means that the other connection has made uncommitted changes + ** to the schema. + ** + ** Were we to proceed and prepare the statement against the uncommitted + ** schema changes and if those schema changes are subsequently rolled + ** back and different changes are made in their place, then when this + ** prepared statement goes to run the schema cookie would fail to detect + ** the schema change. Disaster would follow. + ** + ** This thread is currently holding mutexes on all Btrees (because + ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it + ** is not possible for another thread to start a new schema change + ** while this routine is running. Hence, we do not need to hold + ** locks on the schema, we just need to make sure nobody else is + ** holding them. + ** + ** Note that setting READ_UNCOMMITTED overrides most lock detection, + ** but it does *not* override schema lock detection, so this all still + ** works even if READ_UNCOMMITTED is set. + */ + for(i=0; inDb; i++) { + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + assert( sqlite3BtreeHoldsMutex(pBt) ); + rc = sqlite3BtreeSchemaLocked(pBt); + if( rc ){ + const char *zDb = db->aDb[i].zName; + sqlite3Error(db, rc, "database schema is locked: %s", zDb); + testcase( db->flags & SQLITE_ReadUncommitted ); + goto end_prepare; + } + } + } + + sqlite3VtabUnlockList(db); + + pParse->db = db; + pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */ + if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){ + char *zSqlCopy; + int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; + testcase( nBytes==mxLen ); + testcase( nBytes==mxLen+1 ); + if( nBytes>mxLen ){ + sqlite3Error(db, SQLITE_TOOBIG, "statement too long"); + rc = sqlite3ApiExit(db, SQLITE_TOOBIG); + goto end_prepare; + } + zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes); + if( zSqlCopy ){ + sqlite3RunParser(pParse, zSqlCopy, &zErrMsg); + sqlite3DbFree(db, zSqlCopy); + pParse->zTail = &zSql[pParse->zTail-zSqlCopy]; + }else{ + pParse->zTail = &zSql[nBytes]; + } + }else{ + sqlite3RunParser(pParse, zSql, &zErrMsg); + } + assert( 0==pParse->nQueryLoop ); + + if( db->mallocFailed ){ + pParse->rc = SQLITE_NOMEM; + } + if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK; + if( pParse->checkSchema ){ + schemaIsValid(pParse); + } + if( db->mallocFailed ){ + pParse->rc = SQLITE_NOMEM; + } + if( pzTail ){ + *pzTail = pParse->zTail; + } + rc = pParse->rc; + +#ifndef SQLITE_OMIT_EXPLAIN + if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){ + static const char * const azColName[] = { + "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", + "selectid", "order", "from", "detail" + }; + int iFirst, mx; + if( pParse->explain==2 ){ + sqlite3VdbeSetNumCols(pParse->pVdbe, 4); + iFirst = 8; + mx = 12; + }else{ + sqlite3VdbeSetNumCols(pParse->pVdbe, 8); + iFirst = 0; + mx = 8; + } + for(i=iFirst; ipVdbe, i-iFirst, COLNAME_NAME, + azColName[i], SQLITE_STATIC); + } + } +#endif + + if( db->init.busy==0 ){ + Vdbe *pVdbe = pParse->pVdbe; + sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag); + } + if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){ + sqlite3VdbeFinalize(pParse->pVdbe); + assert(!(*ppStmt)); + }else{ + *ppStmt = (sqlite3_stmt*)pParse->pVdbe; + } + + if( zErrMsg ){ + sqlite3Error(db, rc, "%s", zErrMsg); + sqlite3DbFree(db, zErrMsg); + }else{ + sqlite3Error(db, rc, 0); + } + + /* Delete any TriggerPrg structures allocated while parsing this statement. */ + while( pParse->pTriggerPrg ){ + TriggerPrg *pT = pParse->pTriggerPrg; + pParse->pTriggerPrg = pT->pNext; + sqlite3DbFree(db, pT); + } + +end_prepare: + + sqlite3StackFree(db, pParse); + rc = sqlite3ApiExit(db, rc); + assert( (rc&db->errMask)==rc ); + return rc; +} +static int sqlite3LockAndPrepare( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ + Vdbe *pOld, /* VM being reprepared */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +){ + int rc; + assert( ppStmt!=0 ); + *ppStmt = 0; + if( !sqlite3SafetyCheckOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + sqlite3_mutex_enter(db->mutex); + sqlite3BtreeEnterAll(db); + rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); + if( rc==SQLITE_SCHEMA ){ + sqlite3_finalize(*ppStmt); + rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); + } + sqlite3BtreeLeaveAll(db); + sqlite3_mutex_leave(db->mutex); + assert( rc==SQLITE_OK || *ppStmt==0 ); + return rc; +} + +/* +** Rerun the compilation of a statement after a schema change. +** +** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, +** if the statement cannot be recompiled because another connection has +** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error +** occurs, return SQLITE_SCHEMA. +*/ +SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){ + int rc; + sqlite3_stmt *pNew; + const char *zSql; + sqlite3 *db; + + assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) ); + zSql = sqlite3_sql((sqlite3_stmt *)p); + assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */ + db = sqlite3VdbeDb(p); + assert( sqlite3_mutex_held(db->mutex) ); + rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0); + if( rc ){ + if( rc==SQLITE_NOMEM ){ + db->mallocFailed = 1; + } + assert( pNew==0 ); + return rc; + }else{ + assert( pNew!=0 ); + } + sqlite3VdbeSwap((Vdbe*)pNew, p); + sqlite3TransferBindings(pNew, (sqlite3_stmt*)p); + sqlite3VdbeResetStepResult((Vdbe*)pNew); + sqlite3VdbeFinalize((Vdbe*)pNew); + return SQLITE_OK; +} + + +/* +** Two versions of the official API. Legacy and new use. In the legacy +** version, the original SQL text is not saved in the prepared statement +** and so if a schema change occurs, SQLITE_SCHEMA is returned by +** sqlite3_step(). In the new version, the original SQL text is retained +** and the statement is automatically recompiled if an schema change +** occurs. +*/ +SQLITE_API int sqlite3_prepare( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +){ + int rc; + rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + return rc; +} +SQLITE_API int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +){ + int rc; + rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + return rc; +} + + +#ifndef SQLITE_OMIT_UTF16 +/* +** Compile the UTF-16 encoded SQL statement zSql into a statement handle. +*/ +static int sqlite3Prepare16( + sqlite3 *db, /* Database handle. */ + const void *zSql, /* UTF-16 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const void **pzTail /* OUT: End of parsed string */ +){ + /* This function currently works by first transforming the UTF-16 + ** encoded string to UTF-8, then invoking sqlite3_prepare(). The + ** tricky bit is figuring out the pointer to return in *pzTail. + */ + char *zSql8; + const char *zTail8 = 0; + int rc = SQLITE_OK; + + assert( ppStmt ); + *ppStmt = 0; + if( !sqlite3SafetyCheckOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + if( nBytes>=0 ){ + int sz; + const char *z = (const char*)zSql; + for(sz=0; szmutex); + zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); + if( zSql8 ){ + rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8); + } + + if( zTail8 && pzTail ){ + /* If sqlite3_prepare returns a tail pointer, we calculate the + ** equivalent pointer into the UTF-16 string by counting the unicode + ** characters between zSql8 and zTail8, and then returning a pointer + ** the same number of characters into the UTF-16 string. + */ + int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); + *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); + } + sqlite3DbFree(db, zSql8); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Two versions of the official API. Legacy and new use. In the legacy +** version, the original SQL text is not saved in the prepared statement +** and so if a schema change occurs, SQLITE_SCHEMA is returned by +** sqlite3_step(). In the new version, the original SQL text is retained +** and the statement is automatically recompiled if an schema change +** occurs. +*/ +SQLITE_API int sqlite3_prepare16( + sqlite3 *db, /* Database handle. */ + const void *zSql, /* UTF-16 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const void **pzTail /* OUT: End of parsed string */ +){ + int rc; + rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + return rc; +} +SQLITE_API int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle. */ + const void *zSql, /* UTF-16 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const void **pzTail /* OUT: End of parsed string */ +){ + int rc; + rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + return rc; +} + +#endif /* SQLITE_OMIT_UTF16 */ + +/************** End of prepare.c *********************************************/ +/************** Begin file select.c ******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that are called by the parser +** to handle SELECT statements in SQLite. +*/ + + +/* +** Delete all the content of a Select structure but do not deallocate +** the select structure itself. +*/ +static void clearSelect(sqlite3 *db, Select *p){ + sqlite3ExprListDelete(db, p->pEList); + sqlite3SrcListDelete(db, p->pSrc); + sqlite3ExprDelete(db, p->pWhere); + sqlite3ExprListDelete(db, p->pGroupBy); + sqlite3ExprDelete(db, p->pHaving); + sqlite3ExprListDelete(db, p->pOrderBy); + sqlite3SelectDelete(db, p->pPrior); + sqlite3ExprDelete(db, p->pLimit); + sqlite3ExprDelete(db, p->pOffset); +} + +/* +** Initialize a SelectDest structure. +*/ +SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ + pDest->eDest = (u8)eDest; + pDest->iSDParm = iParm; + pDest->affSdst = 0; + pDest->iSdst = 0; + pDest->nSdst = 0; +} + + +/* +** Allocate a new Select structure and return a pointer to that +** structure. +*/ +SQLITE_PRIVATE Select *sqlite3SelectNew( + Parse *pParse, /* Parsing context */ + ExprList *pEList, /* which columns to include in the result */ + SrcList *pSrc, /* the FROM clause -- which tables to scan */ + Expr *pWhere, /* the WHERE clause */ + ExprList *pGroupBy, /* the GROUP BY clause */ + Expr *pHaving, /* the HAVING clause */ + ExprList *pOrderBy, /* the ORDER BY clause */ + u16 selFlags, /* Flag parameters, such as SF_Distinct */ + Expr *pLimit, /* LIMIT value. NULL means not used */ + Expr *pOffset /* OFFSET value. NULL means no offset */ +){ + Select *pNew; + Select standin; + sqlite3 *db = pParse->db; + pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); + assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */ + if( pNew==0 ){ + assert( db->mallocFailed ); + pNew = &standin; + memset(pNew, 0, sizeof(*pNew)); + } + if( pEList==0 ){ + pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0)); + } + pNew->pEList = pEList; + if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc)); + pNew->pSrc = pSrc; + pNew->pWhere = pWhere; + pNew->pGroupBy = pGroupBy; + pNew->pHaving = pHaving; + pNew->pOrderBy = pOrderBy; + pNew->selFlags = selFlags; + pNew->op = TK_SELECT; + pNew->pLimit = pLimit; + pNew->pOffset = pOffset; + assert( pOffset==0 || pLimit!=0 ); + pNew->addrOpenEphm[0] = -1; + pNew->addrOpenEphm[1] = -1; + pNew->addrOpenEphm[2] = -1; + if( db->mallocFailed ) { + clearSelect(db, pNew); + if( pNew!=&standin ) sqlite3DbFree(db, pNew); + pNew = 0; + }else{ + assert( pNew->pSrc!=0 || pParse->nErr>0 ); + } + assert( pNew!=&standin ); + return pNew; +} + +/* +** Delete the given Select structure and all of its substructures. +*/ +SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){ + if( p ){ + clearSelect(db, p); + sqlite3DbFree(db, p); + } +} + +/* +** Given 1 to 3 identifiers preceding the JOIN keyword, determine the +** type of join. Return an integer constant that expresses that type +** in terms of the following bit values: +** +** JT_INNER +** JT_CROSS +** JT_OUTER +** JT_NATURAL +** JT_LEFT +** JT_RIGHT +** +** A full outer join is the combination of JT_LEFT and JT_RIGHT. +** +** If an illegal or unsupported join type is seen, then still return +** a join type, but put an error in the pParse structure. +*/ +SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ + int jointype = 0; + Token *apAll[3]; + Token *p; + /* 0123456789 123456789 123456789 123 */ + static const char zKeyText[] = "naturaleftouterightfullinnercross"; + static const struct { + u8 i; /* Beginning of keyword text in zKeyText[] */ + u8 nChar; /* Length of the keyword in characters */ + u8 code; /* Join type mask */ + } aKeyword[] = { + /* natural */ { 0, 7, JT_NATURAL }, + /* left */ { 6, 4, JT_LEFT|JT_OUTER }, + /* outer */ { 10, 5, JT_OUTER }, + /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, + /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, + /* inner */ { 23, 5, JT_INNER }, + /* cross */ { 28, 5, JT_INNER|JT_CROSS }, + }; + int i, j; + apAll[0] = pA; + apAll[1] = pB; + apAll[2] = pC; + for(i=0; i<3 && apAll[i]; i++){ + p = apAll[i]; + for(j=0; jn==aKeyword[j].nChar + && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ + jointype |= aKeyword[j].code; + break; + } + } + testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); + if( j>=ArraySize(aKeyword) ){ + jointype |= JT_ERROR; + break; + } + } + if( + (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || + (jointype & JT_ERROR)!=0 + ){ + const char *zSp = " "; + assert( pB!=0 ); + if( pC==0 ){ zSp++; } + sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " + "%T %T%s%T", pA, pB, zSp, pC); + jointype = JT_INNER; + }else if( (jointype & JT_OUTER)!=0 + && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ + sqlite3ErrorMsg(pParse, + "RIGHT and FULL OUTER JOINs are not currently supported"); + jointype = JT_INNER; + } + return jointype; +} + +/* +** Return the index of a column in a table. Return -1 if the column +** is not contained in the table. +*/ +static int columnIndex(Table *pTab, const char *zCol){ + int i; + for(i=0; inCol; i++){ + if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; + } + return -1; +} + +/* +** Search the first N tables in pSrc, from left to right, looking for a +** table that has a column named zCol. +** +** When found, set *piTab and *piCol to the table index and column index +** of the matching column and return TRUE. +** +** If not found, return FALSE. +*/ +static int tableAndColumnIndex( + SrcList *pSrc, /* Array of tables to search */ + int N, /* Number of tables in pSrc->a[] to search */ + const char *zCol, /* Name of the column we are looking for */ + int *piTab, /* Write index of pSrc->a[] here */ + int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ +){ + int i; /* For looping over tables in pSrc */ + int iCol; /* Index of column matching zCol */ + + assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ + for(i=0; ia[i].pTab, zCol); + if( iCol>=0 ){ + if( piTab ){ + *piTab = i; + *piCol = iCol; + } + return 1; + } + } + return 0; +} + +/* +** This function is used to add terms implied by JOIN syntax to the +** WHERE clause expression of a SELECT statement. The new term, which +** is ANDed with the existing WHERE clause, is of the form: +** +** (tab1.col1 = tab2.col2) +** +** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the +** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is +** column iColRight of tab2. +*/ +static void addWhereTerm( + Parse *pParse, /* Parsing context */ + SrcList *pSrc, /* List of tables in FROM clause */ + int iLeft, /* Index of first table to join in pSrc */ + int iColLeft, /* Index of column in first table */ + int iRight, /* Index of second table in pSrc */ + int iColRight, /* Index of column in second table */ + int isOuterJoin, /* True if this is an OUTER join */ + Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ +){ + sqlite3 *db = pParse->db; + Expr *pE1; + Expr *pE2; + Expr *pEq; + + assert( iLeftnSrc>iRight ); + assert( pSrc->a[iLeft].pTab ); + assert( pSrc->a[iRight].pTab ); + + pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); + pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); + + pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0); + if( pEq && isOuterJoin ){ + ExprSetProperty(pEq, EP_FromJoin); + assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); + ExprSetVVAProperty(pEq, EP_NoReduce); + pEq->iRightJoinTable = (i16)pE2->iTable; + } + *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); +} + +/* +** Set the EP_FromJoin property on all terms of the given expression. +** And set the Expr.iRightJoinTable to iTable for every term in the +** expression. +** +** The EP_FromJoin property is used on terms of an expression to tell +** the LEFT OUTER JOIN processing logic that this term is part of the +** join restriction specified in the ON or USING clause and not a part +** of the more general WHERE clause. These terms are moved over to the +** WHERE clause during join processing but we need to remember that they +** originated in the ON or USING clause. +** +** The Expr.iRightJoinTable tells the WHERE clause processing that the +** expression depends on table iRightJoinTable even if that table is not +** explicitly mentioned in the expression. That information is needed +** for cases like this: +** +** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 +** +** The where clause needs to defer the handling of the t1.x=5 +** term until after the t2 loop of the join. In that way, a +** NULL t2 row will be inserted whenever t1.x!=5. If we do not +** defer the handling of t1.x=5, it will be processed immediately +** after the t1 loop and rows with t1.x!=5 will never appear in +** the output, which is incorrect. +*/ +static void setJoinExpr(Expr *p, int iTable){ + while( p ){ + ExprSetProperty(p, EP_FromJoin); + assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); + ExprSetVVAProperty(p, EP_NoReduce); + p->iRightJoinTable = (i16)iTable; + setJoinExpr(p->pLeft, iTable); + p = p->pRight; + } +} + +/* +** This routine processes the join information for a SELECT statement. +** ON and USING clauses are converted into extra terms of the WHERE clause. +** NATURAL joins also create extra WHERE clause terms. +** +** The terms of a FROM clause are contained in the Select.pSrc structure. +** The left most table is the first entry in Select.pSrc. The right-most +** table is the last entry. The join operator is held in the entry to +** the left. Thus entry 0 contains the join operator for the join between +** entries 0 and 1. Any ON or USING clauses associated with the join are +** also attached to the left entry. +** +** This routine returns the number of errors encountered. +*/ +static int sqliteProcessJoin(Parse *pParse, Select *p){ + SrcList *pSrc; /* All tables in the FROM clause */ + int i, j; /* Loop counters */ + struct SrcList_item *pLeft; /* Left table being joined */ + struct SrcList_item *pRight; /* Right table being joined */ + + pSrc = p->pSrc; + pLeft = &pSrc->a[0]; + pRight = &pLeft[1]; + for(i=0; inSrc-1; i++, pRight++, pLeft++){ + Table *pLeftTab = pLeft->pTab; + Table *pRightTab = pRight->pTab; + int isOuter; + + if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; + isOuter = (pRight->jointype & JT_OUTER)!=0; + + /* When the NATURAL keyword is present, add WHERE clause terms for + ** every column that the two tables have in common. + */ + if( pRight->jointype & JT_NATURAL ){ + if( pRight->pOn || pRight->pUsing ){ + sqlite3ErrorMsg(pParse, "a NATURAL join may not have " + "an ON or USING clause", 0); + return 1; + } + for(j=0; jnCol; j++){ + char *zName; /* Name of column in the right table */ + int iLeft; /* Matching left table */ + int iLeftCol; /* Matching column in the left table */ + + zName = pRightTab->aCol[j].zName; + if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ + addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, + isOuter, &p->pWhere); + } + } + } + + /* Disallow both ON and USING clauses in the same join + */ + if( pRight->pOn && pRight->pUsing ){ + sqlite3ErrorMsg(pParse, "cannot have both ON and USING " + "clauses in the same join"); + return 1; + } + + /* Add the ON clause to the end of the WHERE clause, connected by + ** an AND operator. + */ + if( pRight->pOn ){ + if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); + p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); + pRight->pOn = 0; + } + + /* Create extra terms on the WHERE clause for each column named + ** in the USING clause. Example: If the two tables to be joined are + ** A and B and the USING clause names X, Y, and Z, then add this + ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z + ** Report an error if any column mentioned in the USING clause is + ** not contained in both tables to be joined. + */ + if( pRight->pUsing ){ + IdList *pList = pRight->pUsing; + for(j=0; jnId; j++){ + char *zName; /* Name of the term in the USING clause */ + int iLeft; /* Table on the left with matching column name */ + int iLeftCol; /* Column number of matching column on the left */ + int iRightCol; /* Column number of matching column on the right */ + + zName = pList->a[j].zName; + iRightCol = columnIndex(pRightTab, zName); + if( iRightCol<0 + || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) + ){ + sqlite3ErrorMsg(pParse, "cannot join using column %s - column " + "not present in both tables", zName); + return 1; + } + addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, + isOuter, &p->pWhere); + } + } + } + return 0; +} + +/* +** Insert code into "v" that will push the record on the top of the +** stack into the sorter. +*/ +static void pushOntoSorter( + Parse *pParse, /* Parser context */ + ExprList *pOrderBy, /* The ORDER BY clause */ + Select *pSelect, /* The whole SELECT statement */ + int regData /* Register holding data to be sorted */ +){ + Vdbe *v = pParse->pVdbe; + int nExpr = pOrderBy->nExpr; + int regBase = sqlite3GetTempRange(pParse, nExpr+2); + int regRecord = sqlite3GetTempReg(pParse); + int op; + sqlite3ExprCacheClear(pParse); + sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0); + sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr); + sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord); + if( pSelect->selFlags & SF_UseSorter ){ + op = OP_SorterInsert; + }else{ + op = OP_IdxInsert; + } + sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord); + sqlite3ReleaseTempReg(pParse, regRecord); + sqlite3ReleaseTempRange(pParse, regBase, nExpr+2); + if( pSelect->iLimit ){ + int addr1, addr2; + int iLimit; + if( pSelect->iOffset ){ + iLimit = pSelect->iOffset+1; + }else{ + iLimit = pSelect->iLimit; + } + addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); + sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1); + addr2 = sqlite3VdbeAddOp0(v, OP_Goto); + sqlite3VdbeJumpHere(v, addr1); + sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor); + sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor); + sqlite3VdbeJumpHere(v, addr2); + } +} + +/* +** Add code to implement the OFFSET +*/ +static void codeOffset( + Vdbe *v, /* Generate code into this VM */ + Select *p, /* The SELECT statement being coded */ + int iContinue /* Jump here to skip the current record */ +){ + if( p->iOffset && iContinue!=0 ){ + int addr; + sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1); + addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset); + sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue); + VdbeComment((v, "skip OFFSET records")); + sqlite3VdbeJumpHere(v, addr); + } +} + +/* +** Add code that will check to make sure the N registers starting at iMem +** form a distinct entry. iTab is a sorting index that holds previously +** seen combinations of the N values. A new entry is made in iTab +** if the current N values are new. +** +** A jump to addrRepeat is made and the N+1 values are popped from the +** stack if the top N elements are not distinct. +*/ +static void codeDistinct( + Parse *pParse, /* Parsing and code generating context */ + int iTab, /* A sorting index used to test for distinctness */ + int addrRepeat, /* Jump to here if not distinct */ + int N, /* Number of elements */ + int iMem /* First element */ +){ + Vdbe *v; + int r1; + + v = pParse->pVdbe; + r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); + sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); + sqlite3ReleaseTempReg(pParse, r1); +} + +#ifndef SQLITE_OMIT_SUBQUERY +/* +** Generate an error message when a SELECT is used within a subexpression +** (example: "a IN (SELECT * FROM table)") but it has more than 1 result +** column. We do this in a subroutine because the error used to occur +** in multiple places. (The error only occurs in one place now, but we +** retain the subroutine to minimize code disruption.) +*/ +static int checkForMultiColumnSelectError( + Parse *pParse, /* Parse context. */ + SelectDest *pDest, /* Destination of SELECT results */ + int nExpr /* Number of result columns returned by SELECT */ +){ + int eDest = pDest->eDest; + if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ + sqlite3ErrorMsg(pParse, "only a single result allowed for " + "a SELECT that is part of an expression"); + return 1; + }else{ + return 0; + } +} +#endif + +/* +** An instance of the following object is used to record information about +** how to process the DISTINCT keyword, to simplify passing that information +** into the selectInnerLoop() routine. +*/ +typedef struct DistinctCtx DistinctCtx; +struct DistinctCtx { + u8 isTnct; /* True if the DISTINCT keyword is present */ + u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ + int tabTnct; /* Ephemeral table used for DISTINCT processing */ + int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ +}; + +/* +** This routine generates the code for the inside of the inner loop +** of a SELECT. +** +** If srcTab and nColumn are both zero, then the pEList expressions +** are evaluated in order to get the data for this row. If nColumn>0 +** then data is pulled from srcTab and pEList is used only to get the +** datatypes for each column. +*/ +static void selectInnerLoop( + Parse *pParse, /* The parser context */ + Select *p, /* The complete select statement being coded */ + ExprList *pEList, /* List of values being extracted */ + int srcTab, /* Pull data from this table */ + int nColumn, /* Number of columns in the source table */ + ExprList *pOrderBy, /* If not NULL, sort results using this key */ + DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ + SelectDest *pDest, /* How to dispose of the results */ + int iContinue, /* Jump here to continue with next row */ + int iBreak /* Jump here to break out of the inner loop */ +){ + Vdbe *v = pParse->pVdbe; + int i; + int hasDistinct; /* True if the DISTINCT keyword is present */ + int regResult; /* Start of memory holding result set */ + int eDest = pDest->eDest; /* How to dispose of results */ + int iParm = pDest->iSDParm; /* First argument to disposal method */ + int nResultCol; /* Number of result columns */ + + assert( v ); + if( NEVER(v==0) ) return; + assert( pEList!=0 ); + hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; + if( pOrderBy==0 && !hasDistinct ){ + codeOffset(v, p, iContinue); + } + + /* Pull the requested columns. + */ + if( nColumn>0 ){ + nResultCol = nColumn; + }else{ + nResultCol = pEList->nExpr; + } + if( pDest->iSdst==0 ){ + pDest->iSdst = pParse->nMem+1; + pDest->nSdst = nResultCol; + pParse->nMem += nResultCol; + }else{ + assert( pDest->nSdst==nResultCol ); + } + regResult = pDest->iSdst; + if( nColumn>0 ){ + for(i=0; inExpr==nColumn ); + switch( pDistinct->eTnctType ){ + case WHERE_DISTINCT_ORDERED: { + VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ + int iJump; /* Jump destination */ + int regPrev; /* Previous row content */ + + /* Allocate space for the previous row */ + regPrev = pParse->nMem+1; + pParse->nMem += nColumn; + + /* Change the OP_OpenEphemeral coded earlier to an OP_Null + ** sets the MEM_Cleared bit on the first register of the + ** previous value. This will cause the OP_Ne below to always + ** fail on the first iteration of the loop even if the first + ** row is all NULLs. + */ + sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); + pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); + pOp->opcode = OP_Null; + pOp->p1 = 1; + pOp->p2 = regPrev; + + iJump = sqlite3VdbeCurrentAddr(v) + nColumn; + for(i=0; ia[i].pExpr); + if( iaddrTnct); + break; + } + + default: { + assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); + codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult); + break; + } + } + if( pOrderBy==0 ){ + codeOffset(v, p, iContinue); + } + } + + switch( eDest ){ + /* In this mode, write each query result to the key of the temporary + ** table iParm. + */ +#ifndef SQLITE_OMIT_COMPOUND_SELECT + case SRT_Union: { + int r1; + r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); + sqlite3ReleaseTempReg(pParse, r1); + break; + } + + /* Construct a record from the query result, but instead of + ** saving that record, use it as a key to delete elements from + ** the temporary table iParm. + */ + case SRT_Except: { + sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn); + break; + } +#endif + + /* Store the result as data using a unique key. + */ + case SRT_Table: + case SRT_EphemTab: { + int r1 = sqlite3GetTempReg(pParse); + testcase( eDest==SRT_Table ); + testcase( eDest==SRT_EphemTab ); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); + if( pOrderBy ){ + pushOntoSorter(pParse, pOrderBy, p, r1); + }else{ + int r2 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); + sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3ReleaseTempReg(pParse, r2); + } + sqlite3ReleaseTempReg(pParse, r1); + break; + } + +#ifndef SQLITE_OMIT_SUBQUERY + /* If we are creating a set for an "expr IN (SELECT ...)" construct, + ** then there should be a single item on the stack. Write this + ** item into the set table with bogus data. + */ + case SRT_Set: { + assert( nColumn==1 ); + pDest->affSdst = + sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst); + if( pOrderBy ){ + /* At first glance you would think we could optimize out the + ** ORDER BY in this case since the order of entries in the set + ** does not matter. But there might be a LIMIT clause, in which + ** case the order does matter */ + pushOntoSorter(pParse, pOrderBy, p, regResult); + }else{ + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1); + sqlite3ExprCacheAffinityChange(pParse, regResult, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); + sqlite3ReleaseTempReg(pParse, r1); + } + break; + } + + /* If any row exist in the result set, record that fact and abort. + */ + case SRT_Exists: { + sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); + /* The LIMIT clause will terminate the loop for us */ + break; + } + + /* If this is a scalar select that is part of an expression, then + ** store the results in the appropriate memory cell and break out + ** of the scan loop. + */ + case SRT_Mem: { + assert( nColumn==1 ); + if( pOrderBy ){ + pushOntoSorter(pParse, pOrderBy, p, regResult); + }else{ + sqlite3ExprCodeMove(pParse, regResult, iParm, 1); + /* The LIMIT clause will jump out of the loop for us */ + } + break; + } +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */ + + /* Send the data to the callback function or to a subroutine. In the + ** case of a subroutine, the subroutine itself is responsible for + ** popping the data from the stack. + */ + case SRT_Coroutine: + case SRT_Output: { + testcase( eDest==SRT_Coroutine ); + testcase( eDest==SRT_Output ); + if( pOrderBy ){ + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); + pushOntoSorter(pParse, pOrderBy, p, r1); + sqlite3ReleaseTempReg(pParse, r1); + }else if( eDest==SRT_Coroutine ){ + sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); + }else{ + sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); + sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn); + } + break; + } + +#if !defined(SQLITE_OMIT_TRIGGER) + /* Discard the results. This is used for SELECT statements inside + ** the body of a TRIGGER. The purpose of such selects is to call + ** user-defined functions that have side effects. We do not care + ** about the actual results of the select. + */ + default: { + assert( eDest==SRT_Discard ); + break; + } +#endif + } + + /* Jump to the end of the loop if the LIMIT is reached. Except, if + ** there is a sorter, in which case the sorter has already limited + ** the output for us. + */ + if( pOrderBy==0 && p->iLimit ){ + sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); + } +} + +/* +** Allocate a KeyInfo object sufficient for an index of N columns. +** +** Actually, always allocate one extra column for the rowid at the end +** of the index. So the KeyInfo returned will have space sufficient for +** N+1 columns. +*/ +SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){ + KeyInfo *p = sqlite3DbMallocZero(db, + sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1)); + if( p ){ + p->aSortOrder = (u8*)&p->aColl[N+1]; + p->nField = (u16)N; + p->enc = ENC(db); + p->db = db; + } + return p; +} + +/* +** Given an expression list, generate a KeyInfo structure that records +** the collating sequence for each expression in that expression list. +** +** If the ExprList is an ORDER BY or GROUP BY clause then the resulting +** KeyInfo structure is appropriate for initializing a virtual index to +** implement that clause. If the ExprList is the result set of a SELECT +** then the KeyInfo structure is appropriate for initializing a virtual +** index to implement a DISTINCT test. +** +** Space to hold the KeyInfo structure is obtain from malloc. The calling +** function is responsible for seeing that this structure is eventually +** freed. Add the KeyInfo structure to the P4 field of an opcode using +** P4_KEYINFO_HANDOFF is the usual way of dealing with this. +*/ +static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ + int nExpr; + KeyInfo *pInfo; + struct ExprList_item *pItem; + sqlite3 *db = pParse->db; + int i; + + nExpr = pList->nExpr; + pInfo = sqlite3KeyInfoAlloc(db, nExpr); + if( pInfo ){ + for(i=0, pItem=pList->a; ipExpr); + if( !pColl ) pColl = db->pDfltColl; + pInfo->aColl[i] = pColl; + pInfo->aSortOrder[i] = pItem->sortOrder; + } + } + return pInfo; +} + +#ifndef SQLITE_OMIT_COMPOUND_SELECT +/* +** Name of the connection operator, used for error messages. +*/ +static const char *selectOpName(int id){ + char *z; + switch( id ){ + case TK_ALL: z = "UNION ALL"; break; + case TK_INTERSECT: z = "INTERSECT"; break; + case TK_EXCEPT: z = "EXCEPT"; break; + default: z = "UNION"; break; + } + return z; +} +#endif /* SQLITE_OMIT_COMPOUND_SELECT */ + +#ifndef SQLITE_OMIT_EXPLAIN +/* +** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function +** is a no-op. Otherwise, it adds a single row of output to the EQP result, +** where the caption is of the form: +** +** "USE TEMP B-TREE FOR xxx" +** +** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which +** is determined by the zUsage argument. +*/ +static void explainTempTable(Parse *pParse, const char *zUsage){ + if( pParse->explain==2 ){ + Vdbe *v = pParse->pVdbe; + char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); + sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); + } +} + +/* +** Assign expression b to lvalue a. A second, no-op, version of this macro +** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code +** in sqlite3Select() to assign values to structure member variables that +** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the +** code with #ifndef directives. +*/ +# define explainSetInteger(a, b) a = b + +#else +/* No-op versions of the explainXXX() functions and macros. */ +# define explainTempTable(y,z) +# define explainSetInteger(y,z) +#endif + +#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) +/* +** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function +** is a no-op. Otherwise, it adds a single row of output to the EQP result, +** where the caption is of one of the two forms: +** +** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" +** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" +** +** where iSub1 and iSub2 are the integers passed as the corresponding +** function parameters, and op is the text representation of the parameter +** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, +** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is +** false, or the second form if it is true. +*/ +static void explainComposite( + Parse *pParse, /* Parse context */ + int op, /* One of TK_UNION, TK_EXCEPT etc. */ + int iSub1, /* Subquery id 1 */ + int iSub2, /* Subquery id 2 */ + int bUseTmp /* True if a temp table was used */ +){ + assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); + if( pParse->explain==2 ){ + Vdbe *v = pParse->pVdbe; + char *zMsg = sqlite3MPrintf( + pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, + bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) + ); + sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); + } +} +#else +/* No-op versions of the explainXXX() functions and macros. */ +# define explainComposite(v,w,x,y,z) +#endif + +/* +** If the inner loop was generated using a non-null pOrderBy argument, +** then the results were placed in a sorter. After the loop is terminated +** we need to run the sorter and output the results. The following +** routine generates the code needed to do that. +*/ +static void generateSortTail( + Parse *pParse, /* Parsing context */ + Select *p, /* The SELECT statement */ + Vdbe *v, /* Generate code into this VDBE */ + int nColumn, /* Number of columns of data */ + SelectDest *pDest /* Write the sorted results here */ +){ + int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */ + int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ + int addr; + int iTab; + int pseudoTab = 0; + ExprList *pOrderBy = p->pOrderBy; + + int eDest = pDest->eDest; + int iParm = pDest->iSDParm; + + int regRow; + int regRowid; + + iTab = pOrderBy->iECursor; + regRow = sqlite3GetTempReg(pParse); + if( eDest==SRT_Output || eDest==SRT_Coroutine ){ + pseudoTab = pParse->nTab++; + sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn); + regRowid = 0; + }else{ + regRowid = sqlite3GetTempReg(pParse); + } + if( p->selFlags & SF_UseSorter ){ + int regSortOut = ++pParse->nMem; + int ptab2 = pParse->nTab++; + sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2); + addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); + codeOffset(v, p, addrContinue); + sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut); + sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow); + sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); + }else{ + addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); + codeOffset(v, p, addrContinue); + sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow); + } + switch( eDest ){ + case SRT_Table: + case SRT_EphemTab: { + testcase( eDest==SRT_Table ); + testcase( eDest==SRT_EphemTab ); + sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); + sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case SRT_Set: { + assert( nColumn==1 ); + sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, + &pDest->affSdst, 1); + sqlite3ExprCacheAffinityChange(pParse, regRow, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); + break; + } + case SRT_Mem: { + assert( nColumn==1 ); + sqlite3ExprCodeMove(pParse, regRow, iParm, 1); + /* The LIMIT clause will terminate the loop for us */ + break; + } +#endif + default: { + int i; + assert( eDest==SRT_Output || eDest==SRT_Coroutine ); + testcase( eDest==SRT_Output ); + testcase( eDest==SRT_Coroutine ); + for(i=0; iiSdst+i ); + sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i); + if( i==0 ){ + sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); + } + } + if( eDest==SRT_Output ){ + sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); + sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); + }else{ + sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); + } + break; + } + } + sqlite3ReleaseTempReg(pParse, regRow); + sqlite3ReleaseTempReg(pParse, regRowid); + + /* The bottom of the loop + */ + sqlite3VdbeResolveLabel(v, addrContinue); + if( p->selFlags & SF_UseSorter ){ + sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); + }else{ + sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); + } + sqlite3VdbeResolveLabel(v, addrBreak); + if( eDest==SRT_Output || eDest==SRT_Coroutine ){ + sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); + } +} + +/* +** Return a pointer to a string containing the 'declaration type' of the +** expression pExpr. The string may be treated as static by the caller. +** +** Also try to estimate the size of the returned value and return that +** result in *pEstWidth. +** +** The declaration type is the exact datatype definition extracted from the +** original CREATE TABLE statement if the expression is a column. The +** declaration type for a ROWID field is INTEGER. Exactly when an expression +** is considered a column can be complex in the presence of subqueries. The +** result-set expression in all of the following SELECT statements is +** considered a column by this function. +** +** SELECT col FROM tbl; +** SELECT (SELECT col FROM tbl; +** SELECT (SELECT col FROM tbl); +** SELECT abc FROM (SELECT col AS abc FROM tbl); +** +** The declaration type for any expression other than a column is NULL. +** +** This routine has either 3 or 6 parameters depending on whether or not +** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. +*/ +#ifdef SQLITE_ENABLE_COLUMN_METADATA +# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F) +static const char *columnTypeImpl( + NameContext *pNC, + Expr *pExpr, + const char **pzOrigDb, + const char **pzOrigTab, + const char **pzOrigCol, + u8 *pEstWidth +){ + char const *zOrigDb = 0; + char const *zOrigTab = 0; + char const *zOrigCol = 0; +#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ +# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F) +static const char *columnTypeImpl( + NameContext *pNC, + Expr *pExpr, + u8 *pEstWidth +){ +#endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */ + char const *zType = 0; + int j; + u8 estWidth = 1; + + if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0; + switch( pExpr->op ){ + case TK_AGG_COLUMN: + case TK_COLUMN: { + /* The expression is a column. Locate the table the column is being + ** extracted from in NameContext.pSrcList. This table may be real + ** database table or a subquery. + */ + Table *pTab = 0; /* Table structure column is extracted from */ + Select *pS = 0; /* Select the column is extracted from */ + int iCol = pExpr->iColumn; /* Index of column in pTab */ + testcase( pExpr->op==TK_AGG_COLUMN ); + testcase( pExpr->op==TK_COLUMN ); + while( pNC && !pTab ){ + SrcList *pTabList = pNC->pSrcList; + for(j=0;jnSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); + if( jnSrc ){ + pTab = pTabList->a[j].pTab; + pS = pTabList->a[j].pSelect; + }else{ + pNC = pNC->pNext; + } + } + + if( pTab==0 ){ + /* At one time, code such as "SELECT new.x" within a trigger would + ** cause this condition to run. Since then, we have restructured how + ** trigger code is generated and so this condition is no longer + ** possible. However, it can still be true for statements like + ** the following: + ** + ** CREATE TABLE t1(col INTEGER); + ** SELECT (SELECT t1.col) FROM FROM t1; + ** + ** when columnType() is called on the expression "t1.col" in the + ** sub-select. In this case, set the column type to NULL, even + ** though it should really be "INTEGER". + ** + ** This is not a problem, as the column type of "t1.col" is never + ** used. When columnType() is called on the expression + ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT + ** branch below. */ + break; + } + + assert( pTab && pExpr->pTab==pTab ); + if( pS ){ + /* The "table" is actually a sub-select or a view in the FROM clause + ** of the SELECT statement. Return the declaration type and origin + ** data for the result-set column of the sub-select. + */ + if( iCol>=0 && ALWAYS(iColpEList->nExpr) ){ + /* If iCol is less than zero, then the expression requests the + ** rowid of the sub-select or view. This expression is legal (see + ** test case misc2.2.2) - it always evaluates to NULL. + */ + NameContext sNC; + Expr *p = pS->pEList->a[iCol].pExpr; + sNC.pSrcList = pS->pSrc; + sNC.pNext = pNC; + sNC.pParse = pNC->pParse; + zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); + } + }else if( ALWAYS(pTab->pSchema) ){ + /* A real table */ + assert( !pS ); + if( iCol<0 ) iCol = pTab->iPKey; + assert( iCol==-1 || (iCol>=0 && iColnCol) ); +#ifdef SQLITE_ENABLE_COLUMN_METADATA + if( iCol<0 ){ + zType = "INTEGER"; + zOrigCol = "rowid"; + }else{ + zType = pTab->aCol[iCol].zType; + zOrigCol = pTab->aCol[iCol].zName; + estWidth = pTab->aCol[iCol].szEst; + } + zOrigTab = pTab->zName; + if( pNC->pParse ){ + int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); + zOrigDb = pNC->pParse->db->aDb[iDb].zName; + } +#else + if( iCol<0 ){ + zType = "INTEGER"; + }else{ + zType = pTab->aCol[iCol].zType; + estWidth = pTab->aCol[iCol].szEst; + } +#endif + } + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_SELECT: { + /* The expression is a sub-select. Return the declaration type and + ** origin info for the single column in the result set of the SELECT + ** statement. + */ + NameContext sNC; + Select *pS = pExpr->x.pSelect; + Expr *p = pS->pEList->a[0].pExpr; + assert( ExprHasProperty(pExpr, EP_xIsSelect) ); + sNC.pSrcList = pS->pSrc; + sNC.pNext = pNC; + sNC.pParse = pNC->pParse; + zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); + break; + } +#endif + } + +#ifdef SQLITE_ENABLE_COLUMN_METADATA + if( pzOrigDb ){ + assert( pzOrigTab && pzOrigCol ); + *pzOrigDb = zOrigDb; + *pzOrigTab = zOrigTab; + *pzOrigCol = zOrigCol; + } +#endif + if( pEstWidth ) *pEstWidth = estWidth; + return zType; +} + +/* +** Generate code that will tell the VDBE the declaration types of columns +** in the result set. +*/ +static void generateColumnTypes( + Parse *pParse, /* Parser context */ + SrcList *pTabList, /* List of tables */ + ExprList *pEList /* Expressions defining the result set */ +){ +#ifndef SQLITE_OMIT_DECLTYPE + Vdbe *v = pParse->pVdbe; + int i; + NameContext sNC; + sNC.pSrcList = pTabList; + sNC.pParse = pParse; + for(i=0; inExpr; i++){ + Expr *p = pEList->a[i].pExpr; + const char *zType; +#ifdef SQLITE_ENABLE_COLUMN_METADATA + const char *zOrigDb = 0; + const char *zOrigTab = 0; + const char *zOrigCol = 0; + zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0); + + /* The vdbe must make its own copy of the column-type and other + ** column specific strings, in case the schema is reset before this + ** virtual machine is deleted. + */ + sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); +#else + zType = columnType(&sNC, p, 0, 0, 0, 0); +#endif + sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); + } +#endif /* !defined(SQLITE_OMIT_DECLTYPE) */ +} + +/* +** Generate code that will tell the VDBE the names of columns +** in the result set. This information is used to provide the +** azCol[] values in the callback. +*/ +static void generateColumnNames( + Parse *pParse, /* Parser context */ + SrcList *pTabList, /* List of tables */ + ExprList *pEList /* Expressions defining the result set */ +){ + Vdbe *v = pParse->pVdbe; + int i, j; + sqlite3 *db = pParse->db; + int fullNames, shortNames; + +#ifndef SQLITE_OMIT_EXPLAIN + /* If this is an EXPLAIN, skip this step */ + if( pParse->explain ){ + return; + } +#endif + + if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return; + pParse->colNamesSet = 1; + fullNames = (db->flags & SQLITE_FullColNames)!=0; + shortNames = (db->flags & SQLITE_ShortColNames)!=0; + sqlite3VdbeSetNumCols(v, pEList->nExpr); + for(i=0; inExpr; i++){ + Expr *p; + p = pEList->a[i].pExpr; + if( NEVER(p==0) ) continue; + if( pEList->a[i].zName ){ + char *zName = pEList->a[i].zName; + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); + }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){ + Table *pTab; + char *zCol; + int iCol = p->iColumn; + for(j=0; ALWAYS(jnSrc); j++){ + if( pTabList->a[j].iCursor==p->iTable ) break; + } + assert( jnSrc ); + pTab = pTabList->a[j].pTab; + if( iCol<0 ) iCol = pTab->iPKey; + assert( iCol==-1 || (iCol>=0 && iColnCol) ); + if( iCol<0 ){ + zCol = "rowid"; + }else{ + zCol = pTab->aCol[iCol].zName; + } + if( !shortNames && !fullNames ){ + sqlite3VdbeSetColName(v, i, COLNAME_NAME, + sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); + }else if( fullNames ){ + char *zName = 0; + zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); + }else{ + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); + } + }else{ + sqlite3VdbeSetColName(v, i, COLNAME_NAME, + sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); + } + } + generateColumnTypes(pParse, pTabList, pEList); +} + +/* +** Given a an expression list (which is really the list of expressions +** that form the result set of a SELECT statement) compute appropriate +** column names for a table that would hold the expression list. +** +** All column names will be unique. +** +** Only the column names are computed. Column.zType, Column.zColl, +** and other fields of Column are zeroed. +** +** Return SQLITE_OK on success. If a memory allocation error occurs, +** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. +*/ +static int selectColumnsFromExprList( + Parse *pParse, /* Parsing context */ + ExprList *pEList, /* Expr list from which to derive column names */ + i16 *pnCol, /* Write the number of columns here */ + Column **paCol /* Write the new column list here */ +){ + sqlite3 *db = pParse->db; /* Database connection */ + int i, j; /* Loop counters */ + int cnt; /* Index added to make the name unique */ + Column *aCol, *pCol; /* For looping over result columns */ + int nCol; /* Number of columns in the result set */ + Expr *p; /* Expression for a single result column */ + char *zName; /* Column name */ + int nName; /* Size of name in zName[] */ + + if( pEList ){ + nCol = pEList->nExpr; + aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); + testcase( aCol==0 ); + }else{ + nCol = 0; + aCol = 0; + } + *pnCol = nCol; + *paCol = aCol; + + for(i=0, pCol=aCol; ia[i].pExpr); + if( (zName = pEList->a[i].zName)!=0 ){ + /* If the column contains an "AS " phrase, use as the name */ + zName = sqlite3DbStrDup(db, zName); + }else{ + Expr *pColExpr = p; /* The expression that is the result column name */ + Table *pTab; /* Table associated with this expression */ + while( pColExpr->op==TK_DOT ){ + pColExpr = pColExpr->pRight; + assert( pColExpr!=0 ); + } + if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ + /* For columns use the column name name */ + int iCol = pColExpr->iColumn; + pTab = pColExpr->pTab; + if( iCol<0 ) iCol = pTab->iPKey; + zName = sqlite3MPrintf(db, "%s", + iCol>=0 ? pTab->aCol[iCol].zName : "rowid"); + }else if( pColExpr->op==TK_ID ){ + assert( !ExprHasProperty(pColExpr, EP_IntValue) ); + zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken); + }else{ + /* Use the original text of the column expression as its name */ + zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan); + } + } + if( db->mallocFailed ){ + sqlite3DbFree(db, zName); + break; + } + + /* Make sure the column name is unique. If the name is not unique, + ** append a integer to the name so that it becomes unique. + */ + nName = sqlite3Strlen30(zName); + for(j=cnt=0; j1 && sqlite3Isdigit(zName[k]); k--){} + if( zName[k]==':' ) nName = k; + zName[nName] = 0; + zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt); + sqlite3DbFree(db, zName); + zName = zNewName; + j = -1; + if( zName==0 ) break; + } + } + pCol->zName = zName; + } + if( db->mallocFailed ){ + for(j=0; jdb; + NameContext sNC; + Column *pCol; + CollSeq *pColl; + int i; + Expr *p; + struct ExprList_item *a; + u64 szAll = 0; + + assert( pSelect!=0 ); + assert( (pSelect->selFlags & SF_Resolved)!=0 ); + assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); + if( db->mallocFailed ) return; + memset(&sNC, 0, sizeof(sNC)); + sNC.pSrcList = pSelect->pSrc; + a = pSelect->pEList->a; + for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ + p = a[i].pExpr; + pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst)); + szAll += pCol->szEst; + pCol->affinity = sqlite3ExprAffinity(p); + if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE; + pColl = sqlite3ExprCollSeq(pParse, p); + if( pColl ){ + pCol->zColl = sqlite3DbStrDup(db, pColl->zName); + } + } + pTab->szTabRow = sqlite3LogEst(szAll*4); +} + +/* +** Given a SELECT statement, generate a Table structure that describes +** the result set of that SELECT. +*/ +SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ + Table *pTab; + sqlite3 *db = pParse->db; + int savedFlags; + + savedFlags = db->flags; + db->flags &= ~SQLITE_FullColNames; + db->flags |= SQLITE_ShortColNames; + sqlite3SelectPrep(pParse, pSelect, 0); + if( pParse->nErr ) return 0; + while( pSelect->pPrior ) pSelect = pSelect->pPrior; + db->flags = savedFlags; + pTab = sqlite3DbMallocZero(db, sizeof(Table) ); + if( pTab==0 ){ + return 0; + } + /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside + ** is disabled */ + assert( db->lookaside.bEnabled==0 ); + pTab->nRef = 1; + pTab->zName = 0; + pTab->nRowEst = 1048576; + selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); + selectAddColumnTypeAndCollation(pParse, pTab, pSelect); + pTab->iPKey = -1; + if( db->mallocFailed ){ + sqlite3DeleteTable(db, pTab); + return 0; + } + return pTab; +} + +/* +** Get a VDBE for the given parser context. Create a new one if necessary. +** If an error occurs, return NULL and leave a message in pParse. +*/ +SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){ + Vdbe *v = pParse->pVdbe; + if( v==0 ){ + v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); +#ifndef SQLITE_OMIT_TRACE + if( v ){ + sqlite3VdbeAddOp0(v, OP_Trace); + } +#endif + } + return v; +} + + +/* +** Compute the iLimit and iOffset fields of the SELECT based on the +** pLimit and pOffset expressions. pLimit and pOffset hold the expressions +** that appear in the original SQL statement after the LIMIT and OFFSET +** keywords. Or NULL if those keywords are omitted. iLimit and iOffset +** are the integer memory register numbers for counters used to compute +** the limit and offset. If there is no limit and/or offset, then +** iLimit and iOffset are negative. +** +** This routine changes the values of iLimit and iOffset only if +** a limit or offset is defined by pLimit and pOffset. iLimit and +** iOffset should have been preset to appropriate default values +** (usually but not always -1) prior to calling this routine. +** Only if pLimit!=0 or pOffset!=0 do the limit registers get +** redefined. The UNION ALL operator uses this property to force +** the reuse of the same limit and offset registers across multiple +** SELECT statements. +*/ +static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ + Vdbe *v = 0; + int iLimit = 0; + int iOffset; + int addr1, n; + if( p->iLimit ) return; + + /* + ** "LIMIT -1" always shows all rows. There is some + ** controversy about what the correct behavior should be. + ** The current implementation interprets "LIMIT 0" to mean + ** no rows. + */ + sqlite3ExprCacheClear(pParse); + assert( p->pOffset==0 || p->pLimit!=0 ); + if( p->pLimit ){ + p->iLimit = iLimit = ++pParse->nMem; + v = sqlite3GetVdbe(pParse); + if( NEVER(v==0) ) return; /* VDBE should have already been allocated */ + if( sqlite3ExprIsInteger(p->pLimit, &n) ){ + sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); + VdbeComment((v, "LIMIT counter")); + if( n==0 ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); + }else if( n>=0 && p->nSelectRow>(u64)n ){ + p->nSelectRow = n; + } + }else{ + sqlite3ExprCode(pParse, p->pLimit, iLimit); + sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); + VdbeComment((v, "LIMIT counter")); + sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); + } + if( p->pOffset ){ + p->iOffset = iOffset = ++pParse->nMem; + pParse->nMem++; /* Allocate an extra register for limit+offset */ + sqlite3ExprCode(pParse, p->pOffset, iOffset); + sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); + VdbeComment((v, "OFFSET counter")); + addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); + sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); + sqlite3VdbeJumpHere(v, addr1); + sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); + VdbeComment((v, "LIMIT+OFFSET")); + addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); + sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); + sqlite3VdbeJumpHere(v, addr1); + } + } +} + +#ifndef SQLITE_OMIT_COMPOUND_SELECT +/* +** Return the appropriate collating sequence for the iCol-th column of +** the result set for the compound-select statement "p". Return NULL if +** the column has no default collating sequence. +** +** The collating sequence for the compound select is taken from the +** left-most term of the select that has a collating sequence. +*/ +static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ + CollSeq *pRet; + if( p->pPrior ){ + pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); + }else{ + pRet = 0; + } + assert( iCol>=0 ); + if( pRet==0 && iColpEList->nExpr ){ + pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); + } + return pRet; +} +#endif /* SQLITE_OMIT_COMPOUND_SELECT */ + +/* Forward reference */ +static int multiSelectOrderBy( + Parse *pParse, /* Parsing context */ + Select *p, /* The right-most of SELECTs to be coded */ + SelectDest *pDest /* What to do with query results */ +); + + +#ifndef SQLITE_OMIT_COMPOUND_SELECT +/* +** This routine is called to process a compound query form from +** two or more separate queries using UNION, UNION ALL, EXCEPT, or +** INTERSECT +** +** "p" points to the right-most of the two queries. the query on the +** left is p->pPrior. The left query could also be a compound query +** in which case this routine will be called recursively. +** +** The results of the total query are to be written into a destination +** of type eDest with parameter iParm. +** +** Example 1: Consider a three-way compound SQL statement. +** +** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 +** +** This statement is parsed up as follows: +** +** SELECT c FROM t3 +** | +** `-----> SELECT b FROM t2 +** | +** `------> SELECT a FROM t1 +** +** The arrows in the diagram above represent the Select.pPrior pointer. +** So if this routine is called with p equal to the t3 query, then +** pPrior will be the t2 query. p->op will be TK_UNION in this case. +** +** Notice that because of the way SQLite parses compound SELECTs, the +** individual selects always group from left to right. +*/ +static int multiSelect( + Parse *pParse, /* Parsing context */ + Select *p, /* The right-most of SELECTs to be coded */ + SelectDest *pDest /* What to do with query results */ +){ + int rc = SQLITE_OK; /* Success code from a subroutine */ + Select *pPrior; /* Another SELECT immediately to our left */ + Vdbe *v; /* Generate code to this VDBE */ + SelectDest dest; /* Alternative data destination */ + Select *pDelete = 0; /* Chain of simple selects to delete */ + sqlite3 *db; /* Database connection */ +#ifndef SQLITE_OMIT_EXPLAIN + int iSub1; /* EQP id of left-hand query */ + int iSub2; /* EQP id of right-hand query */ +#endif + + /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only + ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. + */ + assert( p && p->pPrior ); /* Calling function guarantees this much */ + db = pParse->db; + pPrior = p->pPrior; + assert( pPrior->pRightmost!=pPrior ); + assert( pPrior->pRightmost==p->pRightmost ); + dest = *pDest; + if( pPrior->pOrderBy ){ + sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", + selectOpName(p->op)); + rc = 1; + goto multi_select_end; + } + if( pPrior->pLimit ){ + sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", + selectOpName(p->op)); + rc = 1; + goto multi_select_end; + } + + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); /* The VDBE already created by calling function */ + + /* Create the destination temporary table if necessary + */ + if( dest.eDest==SRT_EphemTab ){ + assert( p->pEList ); + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); + sqlite3VdbeChangeP5(v, BTREE_UNORDERED); + dest.eDest = SRT_Table; + } + + /* Make sure all SELECTs in the statement have the same number of elements + ** in their result sets. + */ + assert( p->pEList && pPrior->pEList ); + if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ + if( p->selFlags & SF_Values ){ + sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); + }else{ + sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" + " do not have the same number of result columns", selectOpName(p->op)); + } + rc = 1; + goto multi_select_end; + } + + /* Compound SELECTs that have an ORDER BY clause are handled separately. + */ + if( p->pOrderBy ){ + return multiSelectOrderBy(pParse, p, pDest); + } + + /* Generate code for the left and right SELECT statements. + */ + switch( p->op ){ + case TK_ALL: { + int addr = 0; + int nLimit; + assert( !pPrior->pLimit ); + pPrior->iLimit = p->iLimit; + pPrior->iOffset = p->iOffset; + pPrior->pLimit = p->pLimit; + pPrior->pOffset = p->pOffset; + explainSetInteger(iSub1, pParse->iNextSelectId); + rc = sqlite3Select(pParse, pPrior, &dest); + p->pLimit = 0; + p->pOffset = 0; + if( rc ){ + goto multi_select_end; + } + p->pPrior = 0; + p->iLimit = pPrior->iLimit; + p->iOffset = pPrior->iOffset; + if( p->iLimit ){ + addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); + VdbeComment((v, "Jump ahead if LIMIT reached")); + } + explainSetInteger(iSub2, pParse->iNextSelectId); + rc = sqlite3Select(pParse, p, &dest); + testcase( rc!=SQLITE_OK ); + pDelete = p->pPrior; + p->pPrior = pPrior; + p->nSelectRow += pPrior->nSelectRow; + if( pPrior->pLimit + && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) + && nLimit>0 && p->nSelectRow > (u64)nLimit + ){ + p->nSelectRow = nLimit; + } + if( addr ){ + sqlite3VdbeJumpHere(v, addr); + } + break; + } + case TK_EXCEPT: + case TK_UNION: { + int unionTab; /* Cursor number of the temporary table holding result */ + u8 op = 0; /* One of the SRT_ operations to apply to self */ + int priorOp; /* The SRT_ operation to apply to prior selects */ + Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ + int addr; + SelectDest uniondest; + + testcase( p->op==TK_EXCEPT ); + testcase( p->op==TK_UNION ); + priorOp = SRT_Union; + if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){ + /* We can reuse a temporary table generated by a SELECT to our + ** right. + */ + assert( p->pRightmost!=p ); /* Can only happen for leftward elements + ** of a 3-way or more compound */ + assert( p->pLimit==0 ); /* Not allowed on leftward elements */ + assert( p->pOffset==0 ); /* Not allowed on leftward elements */ + unionTab = dest.iSDParm; + }else{ + /* We will need to create our own temporary table to hold the + ** intermediate results. + */ + unionTab = pParse->nTab++; + assert( p->pOrderBy==0 ); + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); + assert( p->addrOpenEphm[0] == -1 ); + p->addrOpenEphm[0] = addr; + p->pRightmost->selFlags |= SF_UsesEphemeral; + assert( p->pEList ); + } + + /* Code the SELECT statements to our left + */ + assert( !pPrior->pOrderBy ); + sqlite3SelectDestInit(&uniondest, priorOp, unionTab); + explainSetInteger(iSub1, pParse->iNextSelectId); + rc = sqlite3Select(pParse, pPrior, &uniondest); + if( rc ){ + goto multi_select_end; + } + + /* Code the current SELECT statement + */ + if( p->op==TK_EXCEPT ){ + op = SRT_Except; + }else{ + assert( p->op==TK_UNION ); + op = SRT_Union; + } + p->pPrior = 0; + pLimit = p->pLimit; + p->pLimit = 0; + pOffset = p->pOffset; + p->pOffset = 0; + uniondest.eDest = op; + explainSetInteger(iSub2, pParse->iNextSelectId); + rc = sqlite3Select(pParse, p, &uniondest); + testcase( rc!=SQLITE_OK ); + /* Query flattening in sqlite3Select() might refill p->pOrderBy. + ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ + sqlite3ExprListDelete(db, p->pOrderBy); + pDelete = p->pPrior; + p->pPrior = pPrior; + p->pOrderBy = 0; + if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow; + sqlite3ExprDelete(db, p->pLimit); + p->pLimit = pLimit; + p->pOffset = pOffset; + p->iLimit = 0; + p->iOffset = 0; + + /* Convert the data in the temporary table into whatever form + ** it is that we currently need. + */ + assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); + if( dest.eDest!=priorOp ){ + int iCont, iBreak, iStart; + assert( p->pEList ); + if( dest.eDest==SRT_Output ){ + Select *pFirst = p; + while( pFirst->pPrior ) pFirst = pFirst->pPrior; + generateColumnNames(pParse, 0, pFirst->pEList); + } + iBreak = sqlite3VdbeMakeLabel(v); + iCont = sqlite3VdbeMakeLabel(v); + computeLimitRegisters(pParse, p, iBreak); + sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); + iStart = sqlite3VdbeCurrentAddr(v); + selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, + 0, 0, &dest, iCont, iBreak); + sqlite3VdbeResolveLabel(v, iCont); + sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); + sqlite3VdbeResolveLabel(v, iBreak); + sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); + } + break; + } + default: assert( p->op==TK_INTERSECT ); { + int tab1, tab2; + int iCont, iBreak, iStart; + Expr *pLimit, *pOffset; + int addr; + SelectDest intersectdest; + int r1; + + /* INTERSECT is different from the others since it requires + ** two temporary tables. Hence it has its own case. Begin + ** by allocating the tables we will need. + */ + tab1 = pParse->nTab++; + tab2 = pParse->nTab++; + assert( p->pOrderBy==0 ); + + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); + assert( p->addrOpenEphm[0] == -1 ); + p->addrOpenEphm[0] = addr; + p->pRightmost->selFlags |= SF_UsesEphemeral; + assert( p->pEList ); + + /* Code the SELECTs to our left into temporary table "tab1". + */ + sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); + explainSetInteger(iSub1, pParse->iNextSelectId); + rc = sqlite3Select(pParse, pPrior, &intersectdest); + if( rc ){ + goto multi_select_end; + } + + /* Code the current SELECT into temporary table "tab2" + */ + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); + assert( p->addrOpenEphm[1] == -1 ); + p->addrOpenEphm[1] = addr; + p->pPrior = 0; + pLimit = p->pLimit; + p->pLimit = 0; + pOffset = p->pOffset; + p->pOffset = 0; + intersectdest.iSDParm = tab2; + explainSetInteger(iSub2, pParse->iNextSelectId); + rc = sqlite3Select(pParse, p, &intersectdest); + testcase( rc!=SQLITE_OK ); + pDelete = p->pPrior; + p->pPrior = pPrior; + if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; + sqlite3ExprDelete(db, p->pLimit); + p->pLimit = pLimit; + p->pOffset = pOffset; + + /* Generate code to take the intersection of the two temporary + ** tables. + */ + assert( p->pEList ); + if( dest.eDest==SRT_Output ){ + Select *pFirst = p; + while( pFirst->pPrior ) pFirst = pFirst->pPrior; + generateColumnNames(pParse, 0, pFirst->pEList); + } + iBreak = sqlite3VdbeMakeLabel(v); + iCont = sqlite3VdbeMakeLabel(v); + computeLimitRegisters(pParse, p, iBreak); + sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); + r1 = sqlite3GetTempReg(pParse); + iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); + sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); + sqlite3ReleaseTempReg(pParse, r1); + selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, + 0, 0, &dest, iCont, iBreak); + sqlite3VdbeResolveLabel(v, iCont); + sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); + sqlite3VdbeResolveLabel(v, iBreak); + sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); + sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); + break; + } + } + + explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); + + /* Compute collating sequences used by + ** temporary tables needed to implement the compound select. + ** Attach the KeyInfo structure to all temporary tables. + ** + ** This section is run by the right-most SELECT statement only. + ** SELECT statements to the left always skip this part. The right-most + ** SELECT might also skip this part if it has no ORDER BY clause and + ** no temp tables are required. + */ + if( p->selFlags & SF_UsesEphemeral ){ + int i; /* Loop counter */ + KeyInfo *pKeyInfo; /* Collating sequence for the result set */ + Select *pLoop; /* For looping through SELECT statements */ + CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ + int nCol; /* Number of columns in result set */ + + assert( p->pRightmost==p ); + nCol = p->pEList->nExpr; + pKeyInfo = sqlite3KeyInfoAlloc(db, nCol); + if( !pKeyInfo ){ + rc = SQLITE_NOMEM; + goto multi_select_end; + } + for(i=0, apColl=pKeyInfo->aColl; ipDfltColl; + } + } + + for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ + for(i=0; i<2; i++){ + int addr = pLoop->addrOpenEphm[i]; + if( addr<0 ){ + /* If [0] is unused then [1] is also unused. So we can + ** always safely abort as soon as the first unused slot is found */ + assert( pLoop->addrOpenEphm[1]<0 ); + break; + } + sqlite3VdbeChangeP2(v, addr, nCol); + sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); + pLoop->addrOpenEphm[i] = -1; + } + } + sqlite3DbFree(db, pKeyInfo); + } + +multi_select_end: + pDest->iSdst = dest.iSdst; + pDest->nSdst = dest.nSdst; + sqlite3SelectDelete(db, pDelete); + return rc; +} +#endif /* SQLITE_OMIT_COMPOUND_SELECT */ + +/* +** Code an output subroutine for a coroutine implementation of a +** SELECT statment. +** +** The data to be output is contained in pIn->iSdst. There are +** pIn->nSdst columns to be output. pDest is where the output should +** be sent. +** +** regReturn is the number of the register holding the subroutine +** return address. +** +** If regPrev>0 then it is the first register in a vector that +** records the previous output. mem[regPrev] is a flag that is false +** if there has been no previous output. If regPrev>0 then code is +** generated to suppress duplicates. pKeyInfo is used for comparing +** keys. +** +** If the LIMIT found in p->iLimit is reached, jump immediately to +** iBreak. +*/ +static int generateOutputSubroutine( + Parse *pParse, /* Parsing context */ + Select *p, /* The SELECT statement */ + SelectDest *pIn, /* Coroutine supplying data */ + SelectDest *pDest, /* Where to send the data */ + int regReturn, /* The return address register */ + int regPrev, /* Previous result register. No uniqueness if 0 */ + KeyInfo *pKeyInfo, /* For comparing with previous entry */ + int p4type, /* The p4 type for pKeyInfo */ + int iBreak /* Jump here if we hit the LIMIT */ +){ + Vdbe *v = pParse->pVdbe; + int iContinue; + int addr; + + addr = sqlite3VdbeCurrentAddr(v); + iContinue = sqlite3VdbeMakeLabel(v); + + /* Suppress duplicates for UNION, EXCEPT, and INTERSECT + */ + if( regPrev ){ + int j1, j2; + j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); + j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, + (char*)pKeyInfo, p4type); + sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); + sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); + } + if( pParse->db->mallocFailed ) return 0; + + /* Suppress the first OFFSET entries if there is an OFFSET clause + */ + codeOffset(v, p, iContinue); + + switch( pDest->eDest ){ + /* Store the result as data using a unique key. + */ + case SRT_Table: + case SRT_EphemTab: { + int r1 = sqlite3GetTempReg(pParse); + int r2 = sqlite3GetTempReg(pParse); + testcase( pDest->eDest==SRT_Table ); + testcase( pDest->eDest==SRT_EphemTab ); + sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); + sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); + sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3ReleaseTempReg(pParse, r2); + sqlite3ReleaseTempReg(pParse, r1); + break; + } + +#ifndef SQLITE_OMIT_SUBQUERY + /* If we are creating a set for an "expr IN (SELECT ...)" construct, + ** then there should be a single item on the stack. Write this + ** item into the set table with bogus data. + */ + case SRT_Set: { + int r1; + assert( pIn->nSdst==1 ); + pDest->affSdst = + sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst); + r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1); + sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1); + sqlite3ReleaseTempReg(pParse, r1); + break; + } + +#if 0 /* Never occurs on an ORDER BY query */ + /* If any row exist in the result set, record that fact and abort. + */ + case SRT_Exists: { + sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm); + /* The LIMIT clause will terminate the loop for us */ + break; + } +#endif + + /* If this is a scalar select that is part of an expression, then + ** store the results in the appropriate memory cell and break out + ** of the scan loop. + */ + case SRT_Mem: { + assert( pIn->nSdst==1 ); + sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); + /* The LIMIT clause will jump out of the loop for us */ + break; + } +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */ + + /* The results are stored in a sequence of registers + ** starting at pDest->iSdst. Then the co-routine yields. + */ + case SRT_Coroutine: { + if( pDest->iSdst==0 ){ + pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); + pDest->nSdst = pIn->nSdst; + } + sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst); + sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); + break; + } + + /* If none of the above, then the result destination must be + ** SRT_Output. This routine is never called with any other + ** destination other than the ones handled above or SRT_Output. + ** + ** For SRT_Output, results are stored in a sequence of registers. + ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to + ** return the next row of result. + */ + default: { + assert( pDest->eDest==SRT_Output ); + sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); + sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); + break; + } + } + + /* Jump to the end of the loop if the LIMIT is reached. + */ + if( p->iLimit ){ + sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); + } + + /* Generate the subroutine return + */ + sqlite3VdbeResolveLabel(v, iContinue); + sqlite3VdbeAddOp1(v, OP_Return, regReturn); + + return addr; +} + +/* +** Alternative compound select code generator for cases when there +** is an ORDER BY clause. +** +** We assume a query of the following form: +** +** ORDER BY +** +** is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea +** is to code both and with the ORDER BY clause as +** co-routines. Then run the co-routines in parallel and merge the results +** into the output. In addition to the two coroutines (called selectA and +** selectB) there are 7 subroutines: +** +** outA: Move the output of the selectA coroutine into the output +** of the compound query. +** +** outB: Move the output of the selectB coroutine into the output +** of the compound query. (Only generated for UNION and +** UNION ALL. EXCEPT and INSERTSECT never output a row that +** appears only in B.) +** +** AltB: Called when there is data from both coroutines and AB. +** +** EofA: Called when data is exhausted from selectA. +** +** EofB: Called when data is exhausted from selectB. +** +** The implementation of the latter five subroutines depend on which +** is used: +** +** +** UNION ALL UNION EXCEPT INTERSECT +** ------------- ----------------- -------------- ----------------- +** AltB: outA, nextA outA, nextA outA, nextA nextA +** +** AeqB: outA, nextA nextA nextA outA, nextA +** +** AgtB: outB, nextB outB, nextB nextB nextB +** +** EofA: outB, nextB outB, nextB halt halt +** +** EofB: outA, nextA outA, nextA outA, nextA halt +** +** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA +** causes an immediate jump to EofA and an EOF on B following nextB causes +** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or +** following nextX causes a jump to the end of the select processing. +** +** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled +** within the output subroutine. The regPrev register set holds the previously +** output value. A comparison is made against this value and the output +** is skipped if the next results would be the same as the previous. +** +** The implementation plan is to implement the two coroutines and seven +** subroutines first, then put the control logic at the bottom. Like this: +** +** goto Init +** coA: coroutine for left query (A) +** coB: coroutine for right query (B) +** outA: output one row of A +** outB: output one row of B (UNION and UNION ALL only) +** EofA: ... +** EofB: ... +** AltB: ... +** AeqB: ... +** AgtB: ... +** Init: initialize coroutine registers +** yield coA +** if eof(A) goto EofA +** yield coB +** if eof(B) goto EofB +** Cmpr: Compare A, B +** Jump AltB, AeqB, AgtB +** End: ... +** +** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not +** actually called using Gosub and they do not Return. EofA and EofB loop +** until all data is exhausted then jump to the "end" labe. AltB, AeqB, +** and AgtB jump to either L2 or to one of EofA or EofB. +*/ +#ifndef SQLITE_OMIT_COMPOUND_SELECT +static int multiSelectOrderBy( + Parse *pParse, /* Parsing context */ + Select *p, /* The right-most of SELECTs to be coded */ + SelectDest *pDest /* What to do with query results */ +){ + int i, j; /* Loop counters */ + Select *pPrior; /* Another SELECT immediately to our left */ + Vdbe *v; /* Generate code to this VDBE */ + SelectDest destA; /* Destination for coroutine A */ + SelectDest destB; /* Destination for coroutine B */ + int regAddrA; /* Address register for select-A coroutine */ + int regEofA; /* Flag to indicate when select-A is complete */ + int regAddrB; /* Address register for select-B coroutine */ + int regEofB; /* Flag to indicate when select-B is complete */ + int addrSelectA; /* Address of the select-A coroutine */ + int addrSelectB; /* Address of the select-B coroutine */ + int regOutA; /* Address register for the output-A subroutine */ + int regOutB; /* Address register for the output-B subroutine */ + int addrOutA; /* Address of the output-A subroutine */ + int addrOutB = 0; /* Address of the output-B subroutine */ + int addrEofA; /* Address of the select-A-exhausted subroutine */ + int addrEofB; /* Address of the select-B-exhausted subroutine */ + int addrAltB; /* Address of the AB subroutine */ + int regLimitA; /* Limit register for select-A */ + int regLimitB; /* Limit register for select-A */ + int regPrev; /* A range of registers to hold previous output */ + int savedLimit; /* Saved value of p->iLimit */ + int savedOffset; /* Saved value of p->iOffset */ + int labelCmpr; /* Label for the start of the merge algorithm */ + int labelEnd; /* Label for the end of the overall SELECT stmt */ + int j1; /* Jump instructions that get retargetted */ + int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ + KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ + KeyInfo *pKeyMerge; /* Comparison information for merging rows */ + sqlite3 *db; /* Database connection */ + ExprList *pOrderBy; /* The ORDER BY clause */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + int *aPermute; /* Mapping from ORDER BY terms to result set columns */ +#ifndef SQLITE_OMIT_EXPLAIN + int iSub1; /* EQP id of left-hand query */ + int iSub2; /* EQP id of right-hand query */ +#endif + + assert( p->pOrderBy!=0 ); + assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ + db = pParse->db; + v = pParse->pVdbe; + assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ + labelEnd = sqlite3VdbeMakeLabel(v); + labelCmpr = sqlite3VdbeMakeLabel(v); + + + /* Patch up the ORDER BY clause + */ + op = p->op; + pPrior = p->pPrior; + assert( pPrior->pOrderBy==0 ); + pOrderBy = p->pOrderBy; + assert( pOrderBy ); + nOrderBy = pOrderBy->nExpr; + + /* For operators other than UNION ALL we have to make sure that + ** the ORDER BY clause covers every term of the result set. Add + ** terms to the ORDER BY clause as necessary. + */ + if( op!=TK_ALL ){ + for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ + struct ExprList_item *pItem; + for(j=0, pItem=pOrderBy->a; jiOrderByCol>0 ); + if( pItem->iOrderByCol==i ) break; + } + if( j==nOrderBy ){ + Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); + if( pNew==0 ) return SQLITE_NOMEM; + pNew->flags |= EP_IntValue; + pNew->u.iValue = i; + pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); + if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i; + } + } + } + + /* Compute the comparison permutation and keyinfo that is used with + ** the permutation used to determine if the next + ** row of results comes from selectA or selectB. Also add explicit + ** collations to the ORDER BY clause terms so that when the subqueries + ** to the right and the left are evaluated, they use the correct + ** collation. + */ + aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); + if( aPermute ){ + struct ExprList_item *pItem; + for(i=0, pItem=pOrderBy->a; iiOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr ); + aPermute[i] = pItem->iOrderByCol - 1; + } + pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy); + if( pKeyMerge ){ + for(i=0; ia[i].pExpr; + if( pTerm->flags & EP_Collate ){ + pColl = sqlite3ExprCollSeq(pParse, pTerm); + }else{ + pColl = multiSelectCollSeq(pParse, p, aPermute[i]); + if( pColl==0 ) pColl = db->pDfltColl; + pOrderBy->a[i].pExpr = + sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); + } + pKeyMerge->aColl[i] = pColl; + pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder; + } + } + }else{ + pKeyMerge = 0; + } + + /* Reattach the ORDER BY clause to the query. + */ + p->pOrderBy = pOrderBy; + pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); + + /* Allocate a range of temporary registers and the KeyInfo needed + ** for the logic that removes duplicate result rows when the + ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). + */ + if( op==TK_ALL ){ + regPrev = 0; + }else{ + int nExpr = p->pEList->nExpr; + assert( nOrderBy>=nExpr || db->mallocFailed ); + regPrev = pParse->nMem+1; + pParse->nMem += nExpr+1; + sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); + pKeyDup = sqlite3KeyInfoAlloc(db, nExpr); + if( pKeyDup ){ + for(i=0; iaColl[i] = multiSelectCollSeq(pParse, p, i); + pKeyDup->aSortOrder[i] = 0; + } + } + } + + /* Separate the left and the right query from one another + */ + p->pPrior = 0; + sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); + if( pPrior->pPrior==0 ){ + sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); + } + + /* Compute the limit registers */ + computeLimitRegisters(pParse, p, labelEnd); + if( p->iLimit && op==TK_ALL ){ + regLimitA = ++pParse->nMem; + regLimitB = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, + regLimitA); + sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); + }else{ + regLimitA = regLimitB = 0; + } + sqlite3ExprDelete(db, p->pLimit); + p->pLimit = 0; + sqlite3ExprDelete(db, p->pOffset); + p->pOffset = 0; + + regAddrA = ++pParse->nMem; + regEofA = ++pParse->nMem; + regAddrB = ++pParse->nMem; + regEofB = ++pParse->nMem; + regOutA = ++pParse->nMem; + regOutB = ++pParse->nMem; + sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); + sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); + + /* Jump past the various subroutines and coroutines to the main + ** merge loop + */ + j1 = sqlite3VdbeAddOp0(v, OP_Goto); + addrSelectA = sqlite3VdbeCurrentAddr(v); + + + /* Generate a coroutine to evaluate the SELECT statement to the + ** left of the compound operator - the "A" select. + */ + VdbeNoopComment((v, "Begin coroutine for left SELECT")); + pPrior->iLimit = regLimitA; + explainSetInteger(iSub1, pParse->iNextSelectId); + sqlite3Select(pParse, pPrior, &destA); + sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA); + sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); + VdbeNoopComment((v, "End coroutine for left SELECT")); + + /* Generate a coroutine to evaluate the SELECT statement on + ** the right - the "B" select + */ + addrSelectB = sqlite3VdbeCurrentAddr(v); + VdbeNoopComment((v, "Begin coroutine for right SELECT")); + savedLimit = p->iLimit; + savedOffset = p->iOffset; + p->iLimit = regLimitB; + p->iOffset = 0; + explainSetInteger(iSub2, pParse->iNextSelectId); + sqlite3Select(pParse, p, &destB); + p->iLimit = savedLimit; + p->iOffset = savedOffset; + sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB); + sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); + VdbeNoopComment((v, "End coroutine for right SELECT")); + + /* Generate a subroutine that outputs the current row of the A + ** select as the next output row of the compound select. + */ + VdbeNoopComment((v, "Output routine for A")); + addrOutA = generateOutputSubroutine(pParse, + p, &destA, pDest, regOutA, + regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd); + + /* Generate a subroutine that outputs the current row of the B + ** select as the next output row of the compound select. + */ + if( op==TK_ALL || op==TK_UNION ){ + VdbeNoopComment((v, "Output routine for B")); + addrOutB = generateOutputSubroutine(pParse, + p, &destB, pDest, regOutB, + regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd); + } + + /* Generate a subroutine to run when the results from select A + ** are exhausted and only data in select B remains. + */ + VdbeNoopComment((v, "eof-A subroutine")); + if( op==TK_EXCEPT || op==TK_INTERSECT ){ + addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd); + }else{ + addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd); + sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); + sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA); + p->nSelectRow += pPrior->nSelectRow; + } + + /* Generate a subroutine to run when the results from select B + ** are exhausted and only data in select A remains. + */ + if( op==TK_INTERSECT ){ + addrEofB = addrEofA; + if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; + }else{ + VdbeNoopComment((v, "eof-B subroutine")); + addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd); + sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); + sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB); + } + + /* Generate code to handle the case of AB + */ + VdbeNoopComment((v, "A-gt-B subroutine")); + addrAgtB = sqlite3VdbeCurrentAddr(v); + if( op==TK_ALL || op==TK_UNION ){ + sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); + } + sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); + sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); + sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); + + /* This code runs once to initialize everything. + */ + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA); + sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB); + sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA); + sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB); + sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); + sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); + + /* Implement the main merge loop + */ + sqlite3VdbeResolveLabel(v, labelCmpr); + sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); + sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, + (char*)pKeyMerge, P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); + sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); + + /* Jump to the this point in order to terminate the query. + */ + sqlite3VdbeResolveLabel(v, labelEnd); + + /* Set the number of output columns + */ + if( pDest->eDest==SRT_Output ){ + Select *pFirst = pPrior; + while( pFirst->pPrior ) pFirst = pFirst->pPrior; + generateColumnNames(pParse, 0, pFirst->pEList); + } + + /* Reassembly the compound query so that it will be freed correctly + ** by the calling function */ + if( p->pPrior ){ + sqlite3SelectDelete(db, p->pPrior); + } + p->pPrior = pPrior; + + /*** TBD: Insert subroutine calls to close cursors on incomplete + **** subqueries ****/ + explainComposite(pParse, p->op, iSub1, iSub2, 0); + return SQLITE_OK; +} +#endif + +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) +/* Forward Declarations */ +static void substExprList(sqlite3*, ExprList*, int, ExprList*); +static void substSelect(sqlite3*, Select *, int, ExprList *); + +/* +** Scan through the expression pExpr. Replace every reference to +** a column in table number iTable with a copy of the iColumn-th +** entry in pEList. (But leave references to the ROWID column +** unchanged.) +** +** This routine is part of the flattening procedure. A subquery +** whose result set is defined by pEList appears as entry in the +** FROM clause of a SELECT such that the VDBE cursor assigned to that +** FORM clause entry is iTable. This routine make the necessary +** changes to pExpr so that it refers directly to the source table +** of the subquery rather the result set of the subquery. +*/ +static Expr *substExpr( + sqlite3 *db, /* Report malloc errors to this connection */ + Expr *pExpr, /* Expr in which substitution occurs */ + int iTable, /* Table to be substituted */ + ExprList *pEList /* Substitute expressions */ +){ + if( pExpr==0 ) return 0; + if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ + if( pExpr->iColumn<0 ){ + pExpr->op = TK_NULL; + }else{ + Expr *pNew; + assert( pEList!=0 && pExpr->iColumnnExpr ); + assert( pExpr->pLeft==0 && pExpr->pRight==0 ); + pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); + sqlite3ExprDelete(db, pExpr); + pExpr = pNew; + } + }else{ + pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); + pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + substSelect(db, pExpr->x.pSelect, iTable, pEList); + }else{ + substExprList(db, pExpr->x.pList, iTable, pEList); + } + } + return pExpr; +} +static void substExprList( + sqlite3 *db, /* Report malloc errors here */ + ExprList *pList, /* List to scan and in which to make substitutes */ + int iTable, /* Table to be substituted */ + ExprList *pEList /* Substitute values */ +){ + int i; + if( pList==0 ) return; + for(i=0; inExpr; i++){ + pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); + } +} +static void substSelect( + sqlite3 *db, /* Report malloc errors here */ + Select *p, /* SELECT statement in which to make substitutions */ + int iTable, /* Table to be replaced */ + ExprList *pEList /* Substitute values */ +){ + SrcList *pSrc; + struct SrcList_item *pItem; + int i; + if( !p ) return; + substExprList(db, p->pEList, iTable, pEList); + substExprList(db, p->pGroupBy, iTable, pEList); + substExprList(db, p->pOrderBy, iTable, pEList); + p->pHaving = substExpr(db, p->pHaving, iTable, pEList); + p->pWhere = substExpr(db, p->pWhere, iTable, pEList); + substSelect(db, p->pPrior, iTable, pEList); + pSrc = p->pSrc; + assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ + if( ALWAYS(pSrc) ){ + for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ + substSelect(db, pItem->pSelect, iTable, pEList); + } + } +} +#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ + +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) +/* +** This routine attempts to flatten subqueries as a performance optimization. +** This routine returns 1 if it makes changes and 0 if no flattening occurs. +** +** To understand the concept of flattening, consider the following +** query: +** +** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 +** +** The default way of implementing this query is to execute the +** subquery first and store the results in a temporary table, then +** run the outer query on that temporary table. This requires two +** passes over the data. Furthermore, because the temporary table +** has no indices, the WHERE clause on the outer query cannot be +** optimized. +** +** This routine attempts to rewrite queries such as the above into +** a single flat select, like this: +** +** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 +** +** The code generated for this simpification gives the same result +** but only has to scan the data once. And because indices might +** exist on the table t1, a complete scan of the data might be +** avoided. +** +** Flattening is only attempted if all of the following are true: +** +** (1) The subquery and the outer query do not both use aggregates. +** +** (2) The subquery is not an aggregate or the outer query is not a join. +** +** (3) The subquery is not the right operand of a left outer join +** (Originally ticket #306. Strengthened by ticket #3300) +** +** (4) The subquery is not DISTINCT. +** +** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT +** sub-queries that were excluded from this optimization. Restriction +** (4) has since been expanded to exclude all DISTINCT subqueries. +** +** (6) The subquery does not use aggregates or the outer query is not +** DISTINCT. +** +** (7) The subquery has a FROM clause. TODO: For subqueries without +** A FROM clause, consider adding a FROM close with the special +** table sqlite_once that consists of a single row containing a +** single NULL. +** +** (8) The subquery does not use LIMIT or the outer query is not a join. +** +** (9) The subquery does not use LIMIT or the outer query does not use +** aggregates. +** +** (10) The subquery does not use aggregates or the outer query does not +** use LIMIT. +** +** (11) The subquery and the outer query do not both have ORDER BY clauses. +** +** (**) Not implemented. Subsumed into restriction (3). Was previously +** a separate restriction deriving from ticket #350. +** +** (13) The subquery and outer query do not both use LIMIT. +** +** (14) The subquery does not use OFFSET. +** +** (15) The outer query is not part of a compound select or the +** subquery does not have a LIMIT clause. +** (See ticket #2339 and ticket [02a8e81d44]). +** +** (16) The outer query is not an aggregate or the subquery does +** not contain ORDER BY. (Ticket #2942) This used to not matter +** until we introduced the group_concat() function. +** +** (17) The sub-query is not a compound select, or it is a UNION ALL +** compound clause made up entirely of non-aggregate queries, and +** the parent query: +** +** * is not itself part of a compound select, +** * is not an aggregate or DISTINCT query, and +** * is not a join +** +** The parent and sub-query may contain WHERE clauses. Subject to +** rules (11), (13) and (14), they may also contain ORDER BY, +** LIMIT and OFFSET clauses. The subquery cannot use any compound +** operator other than UNION ALL because all the other compound +** operators have an implied DISTINCT which is disallowed by +** restriction (4). +** +** Also, each component of the sub-query must return the same number +** of result columns. This is actually a requirement for any compound +** SELECT statement, but all the code here does is make sure that no +** such (illegal) sub-query is flattened. The caller will detect the +** syntax error and return a detailed message. +** +** (18) If the sub-query is a compound select, then all terms of the +** ORDER by clause of the parent must be simple references to +** columns of the sub-query. +** +** (19) The subquery does not use LIMIT or the outer query does not +** have a WHERE clause. +** +** (20) If the sub-query is a compound select, then it must not use +** an ORDER BY clause. Ticket #3773. We could relax this constraint +** somewhat by saying that the terms of the ORDER BY clause must +** appear as unmodified result columns in the outer query. But we +** have other optimizations in mind to deal with that case. +** +** (21) The subquery does not use LIMIT or the outer query is not +** DISTINCT. (See ticket [752e1646fc]). +** +** In this routine, the "p" parameter is a pointer to the outer query. +** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query +** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. +** +** If flattening is not attempted, this routine is a no-op and returns 0. +** If flattening is attempted this routine returns 1. +** +** All of the expression analysis must occur on both the outer query and +** the subquery before this routine runs. +*/ +static int flattenSubquery( + Parse *pParse, /* Parsing context */ + Select *p, /* The parent or outer SELECT statement */ + int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ + int isAgg, /* True if outer SELECT uses aggregate functions */ + int subqueryIsAgg /* True if the subquery uses aggregate functions */ +){ + const char *zSavedAuthContext = pParse->zAuthContext; + Select *pParent; + Select *pSub; /* The inner query or "subquery" */ + Select *pSub1; /* Pointer to the rightmost select in sub-query */ + SrcList *pSrc; /* The FROM clause of the outer query */ + SrcList *pSubSrc; /* The FROM clause of the subquery */ + ExprList *pList; /* The result set of the outer query */ + int iParent; /* VDBE cursor number of the pSub result set temp table */ + int i; /* Loop counter */ + Expr *pWhere; /* The WHERE clause */ + struct SrcList_item *pSubitem; /* The subquery */ + sqlite3 *db = pParse->db; + + /* Check to see if flattening is permitted. Return 0 if not. + */ + assert( p!=0 ); + assert( p->pPrior==0 ); /* Unable to flatten compound queries */ + if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; + pSrc = p->pSrc; + assert( pSrc && iFrom>=0 && iFromnSrc ); + pSubitem = &pSrc->a[iFrom]; + iParent = pSubitem->iCursor; + pSub = pSubitem->pSelect; + assert( pSub!=0 ); + if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ + if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ + pSubSrc = pSub->pSrc; + assert( pSubSrc ); + /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, + ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET + ** because they could be computed at compile-time. But when LIMIT and OFFSET + ** became arbitrary expressions, we were forced to add restrictions (13) + ** and (14). */ + if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ + if( pSub->pOffset ) return 0; /* Restriction (14) */ + if( p->pRightmost && pSub->pLimit ){ + return 0; /* Restriction (15) */ + } + if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ + if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ + if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ + return 0; /* Restrictions (8)(9) */ + } + if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ + return 0; /* Restriction (6) */ + } + if( p->pOrderBy && pSub->pOrderBy ){ + return 0; /* Restriction (11) */ + } + if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ + if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ + if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ + return 0; /* Restriction (21) */ + } + + /* OBSOLETE COMMENT 1: + ** Restriction 3: If the subquery is a join, make sure the subquery is + ** not used as the right operand of an outer join. Examples of why this + ** is not allowed: + ** + ** t1 LEFT OUTER JOIN (t2 JOIN t3) + ** + ** If we flatten the above, we would get + ** + ** (t1 LEFT OUTER JOIN t2) JOIN t3 + ** + ** which is not at all the same thing. + ** + ** OBSOLETE COMMENT 2: + ** Restriction 12: If the subquery is the right operand of a left outer + ** join, make sure the subquery has no WHERE clause. + ** An examples of why this is not allowed: + ** + ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) + ** + ** If we flatten the above, we would get + ** + ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 + ** + ** But the t2.x>0 test will always fail on a NULL row of t2, which + ** effectively converts the OUTER JOIN into an INNER JOIN. + ** + ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: + ** Ticket #3300 shows that flattening the right term of a LEFT JOIN + ** is fraught with danger. Best to avoid the whole thing. If the + ** subquery is the right term of a LEFT JOIN, then do not flatten. + */ + if( (pSubitem->jointype & JT_OUTER)!=0 ){ + return 0; + } + + /* Restriction 17: If the sub-query is a compound SELECT, then it must + ** use only the UNION ALL operator. And none of the simple select queries + ** that make up the compound SELECT are allowed to be aggregate or distinct + ** queries. + */ + if( pSub->pPrior ){ + if( pSub->pOrderBy ){ + return 0; /* Restriction 20 */ + } + if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ + return 0; + } + for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ + testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); + testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); + assert( pSub->pSrc!=0 ); + if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 + || (pSub1->pPrior && pSub1->op!=TK_ALL) + || pSub1->pSrc->nSrc<1 + || pSub->pEList->nExpr!=pSub1->pEList->nExpr + ){ + return 0; + } + testcase( pSub1->pSrc->nSrc>1 ); + } + + /* Restriction 18. */ + if( p->pOrderBy ){ + int ii; + for(ii=0; iipOrderBy->nExpr; ii++){ + if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0; + } + } + } + + /***** If we reach this point, flattening is permitted. *****/ + + /* Authorize the subquery */ + pParse->zAuthContext = pSubitem->zName; + TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); + testcase( i==SQLITE_DENY ); + pParse->zAuthContext = zSavedAuthContext; + + /* If the sub-query is a compound SELECT statement, then (by restrictions + ** 17 and 18 above) it must be a UNION ALL and the parent query must + ** be of the form: + ** + ** SELECT FROM () + ** + ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block + ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or + ** OFFSET clauses and joins them to the left-hand-side of the original + ** using UNION ALL operators. In this case N is the number of simple + ** select statements in the compound sub-query. + ** + ** Example: + ** + ** SELECT a+1 FROM ( + ** SELECT x FROM tab + ** UNION ALL + ** SELECT y FROM tab + ** UNION ALL + ** SELECT abs(z*2) FROM tab2 + ** ) WHERE a!=5 ORDER BY 1 + ** + ** Transformed into: + ** + ** SELECT x+1 FROM tab WHERE x+1!=5 + ** UNION ALL + ** SELECT y+1 FROM tab WHERE y+1!=5 + ** UNION ALL + ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 + ** ORDER BY 1 + ** + ** We call this the "compound-subquery flattening". + */ + for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ + Select *pNew; + ExprList *pOrderBy = p->pOrderBy; + Expr *pLimit = p->pLimit; + Expr *pOffset = p->pOffset; + Select *pPrior = p->pPrior; + p->pOrderBy = 0; + p->pSrc = 0; + p->pPrior = 0; + p->pLimit = 0; + p->pOffset = 0; + pNew = sqlite3SelectDup(db, p, 0); + p->pOffset = pOffset; + p->pLimit = pLimit; + p->pOrderBy = pOrderBy; + p->pSrc = pSrc; + p->op = TK_ALL; + p->pRightmost = 0; + if( pNew==0 ){ + pNew = pPrior; + }else{ + pNew->pPrior = pPrior; + pNew->pRightmost = 0; + } + p->pPrior = pNew; + if( db->mallocFailed ) return 1; + } + + /* Begin flattening the iFrom-th entry of the FROM clause + ** in the outer query. + */ + pSub = pSub1 = pSubitem->pSelect; + + /* Delete the transient table structure associated with the + ** subquery + */ + sqlite3DbFree(db, pSubitem->zDatabase); + sqlite3DbFree(db, pSubitem->zName); + sqlite3DbFree(db, pSubitem->zAlias); + pSubitem->zDatabase = 0; + pSubitem->zName = 0; + pSubitem->zAlias = 0; + pSubitem->pSelect = 0; + + /* Defer deleting the Table object associated with the + ** subquery until code generation is + ** complete, since there may still exist Expr.pTab entries that + ** refer to the subquery even after flattening. Ticket #3346. + ** + ** pSubitem->pTab is always non-NULL by test restrictions and tests above. + */ + if( ALWAYS(pSubitem->pTab!=0) ){ + Table *pTabToDel = pSubitem->pTab; + if( pTabToDel->nRef==1 ){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + pTabToDel->pNextZombie = pToplevel->pZombieTab; + pToplevel->pZombieTab = pTabToDel; + }else{ + pTabToDel->nRef--; + } + pSubitem->pTab = 0; + } + + /* The following loop runs once for each term in a compound-subquery + ** flattening (as described above). If we are doing a different kind + ** of flattening - a flattening other than a compound-subquery flattening - + ** then this loop only runs once. + ** + ** This loop moves all of the FROM elements of the subquery into the + ** the FROM clause of the outer query. Before doing this, remember + ** the cursor number for the original outer query FROM element in + ** iParent. The iParent cursor will never be used. Subsequent code + ** will scan expressions looking for iParent references and replace + ** those references with expressions that resolve to the subquery FROM + ** elements we are now copying in. + */ + for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ + int nSubSrc; + u8 jointype = 0; + pSubSrc = pSub->pSrc; /* FROM clause of subquery */ + nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ + pSrc = pParent->pSrc; /* FROM clause of the outer query */ + + if( pSrc ){ + assert( pParent==p ); /* First time through the loop */ + jointype = pSubitem->jointype; + }else{ + assert( pParent!=p ); /* 2nd and subsequent times through the loop */ + pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); + if( pSrc==0 ){ + assert( db->mallocFailed ); + break; + } + } + + /* The subquery uses a single slot of the FROM clause of the outer + ** query. If the subquery has more than one element in its FROM clause, + ** then expand the outer query to make space for it to hold all elements + ** of the subquery. + ** + ** Example: + ** + ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; + ** + ** The outer query has 3 slots in its FROM clause. One slot of the + ** outer query (the middle slot) is used by the subquery. The next + ** block of code will expand the out query to 4 slots. The middle + ** slot is expanded to two slots in order to make space for the + ** two elements in the FROM clause of the subquery. + */ + if( nSubSrc>1 ){ + pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); + if( db->mallocFailed ){ + break; + } + } + + /* Transfer the FROM clause terms from the subquery into the + ** outer query. + */ + for(i=0; ia[i+iFrom].pUsing); + pSrc->a[i+iFrom] = pSubSrc->a[i]; + memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); + } + pSrc->a[iFrom].jointype = jointype; + + /* Now begin substituting subquery result set expressions for + ** references to the iParent in the outer query. + ** + ** Example: + ** + ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; + ** \ \_____________ subquery __________/ / + ** \_____________________ outer query ______________________________/ + ** + ** We look at every expression in the outer query and every place we see + ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". + */ + pList = pParent->pEList; + for(i=0; inExpr; i++){ + if( pList->a[i].zName==0 ){ + char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); + sqlite3Dequote(zName); + pList->a[i].zName = zName; + } + } + substExprList(db, pParent->pEList, iParent, pSub->pEList); + if( isAgg ){ + substExprList(db, pParent->pGroupBy, iParent, pSub->pEList); + pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); + } + if( pSub->pOrderBy ){ + assert( pParent->pOrderBy==0 ); + pParent->pOrderBy = pSub->pOrderBy; + pSub->pOrderBy = 0; + }else if( pParent->pOrderBy ){ + substExprList(db, pParent->pOrderBy, iParent, pSub->pEList); + } + if( pSub->pWhere ){ + pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); + }else{ + pWhere = 0; + } + if( subqueryIsAgg ){ + assert( pParent->pHaving==0 ); + pParent->pHaving = pParent->pWhere; + pParent->pWhere = pWhere; + pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); + pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, + sqlite3ExprDup(db, pSub->pHaving, 0)); + assert( pParent->pGroupBy==0 ); + pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); + }else{ + pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList); + pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); + } + + /* The flattened query is distinct if either the inner or the + ** outer query is distinct. + */ + pParent->selFlags |= pSub->selFlags & SF_Distinct; + + /* + ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; + ** + ** One is tempted to try to add a and b to combine the limits. But this + ** does not work if either limit is negative. + */ + if( pSub->pLimit ){ + pParent->pLimit = pSub->pLimit; + pSub->pLimit = 0; + } + } + + /* Finially, delete what is left of the subquery and return + ** success. + */ + sqlite3SelectDelete(db, pSub1); + + return 1; +} +#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ + +/* +** Based on the contents of the AggInfo structure indicated by the first +** argument, this function checks if the following are true: +** +** * the query contains just a single aggregate function, +** * the aggregate function is either min() or max(), and +** * the argument to the aggregate function is a column value. +** +** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX +** is returned as appropriate. Also, *ppMinMax is set to point to the +** list of arguments passed to the aggregate before returning. +** +** Or, if the conditions above are not met, *ppMinMax is set to 0 and +** WHERE_ORDERBY_NORMAL is returned. +*/ +static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){ + int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ + + *ppMinMax = 0; + if( pAggInfo->nFunc==1 ){ + Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */ + ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */ + + assert( pExpr->op==TK_AGG_FUNCTION ); + if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){ + const char *zFunc = pExpr->u.zToken; + if( sqlite3StrICmp(zFunc, "min")==0 ){ + eRet = WHERE_ORDERBY_MIN; + *ppMinMax = pEList; + }else if( sqlite3StrICmp(zFunc, "max")==0 ){ + eRet = WHERE_ORDERBY_MAX; + *ppMinMax = pEList; + } + } + } + + assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 ); + return eRet; +} + +/* +** The select statement passed as the first argument is an aggregate query. +** The second argment is the associated aggregate-info object. This +** function tests if the SELECT is of the form: +** +** SELECT count(*) FROM +** +** where table is a database table, not a sub-select or view. If the query +** does match this pattern, then a pointer to the Table object representing +** is returned. Otherwise, 0 is returned. +*/ +static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ + Table *pTab; + Expr *pExpr; + + assert( !p->pGroupBy ); + + if( p->pWhere || p->pEList->nExpr!=1 + || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect + ){ + return 0; + } + pTab = p->pSrc->a[0].pTab; + pExpr = p->pEList->a[0].pExpr; + assert( pTab && !pTab->pSelect && pExpr ); + + if( IsVirtual(pTab) ) return 0; + if( pExpr->op!=TK_AGG_FUNCTION ) return 0; + if( NEVER(pAggInfo->nFunc==0) ) return 0; + if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; + if( pExpr->flags&EP_Distinct ) return 0; + + return pTab; +} + +/* +** If the source-list item passed as an argument was augmented with an +** INDEXED BY clause, then try to locate the specified index. If there +** was such a clause and the named index cannot be found, return +** SQLITE_ERROR and leave an error in pParse. Otherwise, populate +** pFrom->pIndex and return SQLITE_OK. +*/ +SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ + if( pFrom->pTab && pFrom->zIndex ){ + Table *pTab = pFrom->pTab; + char *zIndex = pFrom->zIndex; + Index *pIdx; + for(pIdx=pTab->pIndex; + pIdx && sqlite3StrICmp(pIdx->zName, zIndex); + pIdx=pIdx->pNext + ); + if( !pIdx ){ + sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0); + pParse->checkSchema = 1; + return SQLITE_ERROR; + } + pFrom->pIndex = pIdx; + } + return SQLITE_OK; +} +/* +** Detect compound SELECT statements that use an ORDER BY clause with +** an alternative collating sequence. +** +** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... +** +** These are rewritten as a subquery: +** +** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) +** ORDER BY ... COLLATE ... +** +** This transformation is necessary because the multiSelectOrderBy() routine +** above that generates the code for a compound SELECT with an ORDER BY clause +** uses a merge algorithm that requires the same collating sequence on the +** result columns as on the ORDER BY clause. See ticket +** http://www.sqlite.org/src/info/6709574d2a +** +** This transformation is only needed for EXCEPT, INTERSECT, and UNION. +** The UNION ALL operator works fine with multiSelectOrderBy() even when +** there are COLLATE terms in the ORDER BY. +*/ +static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ + int i; + Select *pNew; + Select *pX; + sqlite3 *db; + struct ExprList_item *a; + SrcList *pNewSrc; + Parse *pParse; + Token dummy; + + if( p->pPrior==0 ) return WRC_Continue; + if( p->pOrderBy==0 ) return WRC_Continue; + for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} + if( pX==0 ) return WRC_Continue; + a = p->pOrderBy->a; + for(i=p->pOrderBy->nExpr-1; i>=0; i--){ + if( a[i].pExpr->flags & EP_Collate ) break; + } + if( i<0 ) return WRC_Continue; + + /* If we reach this point, that means the transformation is required. */ + + pParse = pWalker->pParse; + db = pParse->db; + pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); + if( pNew==0 ) return WRC_Abort; + memset(&dummy, 0, sizeof(dummy)); + pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); + if( pNewSrc==0 ) return WRC_Abort; + *pNew = *p; + p->pSrc = pNewSrc; + p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0)); + p->op = TK_SELECT; + p->pWhere = 0; + pNew->pGroupBy = 0; + pNew->pHaving = 0; + pNew->pOrderBy = 0; + p->pPrior = 0; + pNew->pLimit = 0; + pNew->pOffset = 0; + return WRC_Continue; +} + +/* +** This routine is a Walker callback for "expanding" a SELECT statement. +** "Expanding" means to do the following: +** +** (1) Make sure VDBE cursor numbers have been assigned to every +** element of the FROM clause. +** +** (2) Fill in the pTabList->a[].pTab fields in the SrcList that +** defines FROM clause. When views appear in the FROM clause, +** fill pTabList->a[].pSelect with a copy of the SELECT statement +** that implements the view. A copy is made of the view's SELECT +** statement so that we can freely modify or delete that statement +** without worrying about messing up the presistent representation +** of the view. +** +** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword +** on joins and the ON and USING clause of joins. +** +** (4) Scan the list of columns in the result set (pEList) looking +** for instances of the "*" operator or the TABLE.* operator. +** If found, expand each "*" to be every column in every table +** and TABLE.* to be every column in TABLE. +** +*/ +static int selectExpander(Walker *pWalker, Select *p){ + Parse *pParse = pWalker->pParse; + int i, j, k; + SrcList *pTabList; + ExprList *pEList; + struct SrcList_item *pFrom; + sqlite3 *db = pParse->db; + Expr *pE, *pRight, *pExpr; + u16 selFlags = p->selFlags; + + p->selFlags |= SF_Expanded; + if( db->mallocFailed ){ + return WRC_Abort; + } + if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ + return WRC_Prune; + } + pTabList = p->pSrc; + pEList = p->pEList; + + /* Make sure cursor numbers have been assigned to all entries in + ** the FROM clause of the SELECT statement. + */ + sqlite3SrcListAssignCursors(pParse, pTabList); + + /* Look up every table named in the FROM clause of the select. If + ** an entry of the FROM clause is a subquery instead of a table or view, + ** then create a transient table structure to describe the subquery. + */ + for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ + Table *pTab; + if( pFrom->pTab!=0 ){ + /* This statement has already been prepared. There is no need + ** to go further. */ + assert( i==0 ); + return WRC_Prune; + } + if( pFrom->zName==0 ){ +#ifndef SQLITE_OMIT_SUBQUERY + Select *pSel = pFrom->pSelect; + /* A sub-query in the FROM clause of a SELECT */ + assert( pSel!=0 ); + assert( pFrom->pTab==0 ); + sqlite3WalkSelect(pWalker, pSel); + pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); + if( pTab==0 ) return WRC_Abort; + pTab->nRef = 1; + pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab); + while( pSel->pPrior ){ pSel = pSel->pPrior; } + selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol); + pTab->iPKey = -1; + pTab->nRowEst = 1048576; + pTab->tabFlags |= TF_Ephemeral; +#endif + }else{ + /* An ordinary table or view name in the FROM clause */ + assert( pFrom->pTab==0 ); + pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); + if( pTab==0 ) return WRC_Abort; + if( pTab->nRef==0xffff ){ + sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", + pTab->zName); + pFrom->pTab = 0; + return WRC_Abort; + } + pTab->nRef++; +#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) + if( pTab->pSelect || IsVirtual(pTab) ){ + /* We reach here if the named table is a really a view */ + if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; + assert( pFrom->pSelect==0 ); + pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); + sqlite3WalkSelect(pWalker, pFrom->pSelect); + } +#endif + } + + /* Locate the index named by the INDEXED BY clause, if any. */ + if( sqlite3IndexedByLookup(pParse, pFrom) ){ + return WRC_Abort; + } + } + + /* Process NATURAL keywords, and ON and USING clauses of joins. + */ + if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ + return WRC_Abort; + } + + /* For every "*" that occurs in the column list, insert the names of + ** all columns in all tables. And for every TABLE.* insert the names + ** of all columns in TABLE. The parser inserted a special expression + ** with the TK_ALL operator for each "*" that it found in the column list. + ** The following code just has to locate the TK_ALL expressions and expand + ** each one to the list of all columns in all tables. + ** + ** The first loop just checks to see if there are any "*" operators + ** that need expanding. + */ + for(k=0; knExpr; k++){ + pE = pEList->a[k].pExpr; + if( pE->op==TK_ALL ) break; + assert( pE->op!=TK_DOT || pE->pRight!=0 ); + assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); + if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break; + } + if( knExpr ){ + /* + ** If we get here it means the result set contains one or more "*" + ** operators that need to be expanded. Loop through each expression + ** in the result set and expand them one by one. + */ + struct ExprList_item *a = pEList->a; + ExprList *pNew = 0; + int flags = pParse->db->flags; + int longNames = (flags & SQLITE_FullColNames)!=0 + && (flags & SQLITE_ShortColNames)==0; + + /* When processing FROM-clause subqueries, it is always the case + ** that full_column_names=OFF and short_column_names=ON. The + ** sqlite3ResultSetOfSelect() routine makes it so. */ + assert( (p->selFlags & SF_NestedFrom)==0 + || ((flags & SQLITE_FullColNames)==0 && + (flags & SQLITE_ShortColNames)!=0) ); + + for(k=0; knExpr; k++){ + pE = a[k].pExpr; + pRight = pE->pRight; + assert( pE->op!=TK_DOT || pRight!=0 ); + if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){ + /* This particular expression does not need to be expanded. + */ + pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); + if( pNew ){ + pNew->a[pNew->nExpr-1].zName = a[k].zName; + pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; + a[k].zName = 0; + a[k].zSpan = 0; + } + a[k].pExpr = 0; + }else{ + /* This expression is a "*" or a "TABLE.*" and needs to be + ** expanded. */ + int tableSeen = 0; /* Set to 1 when TABLE matches */ + char *zTName = 0; /* text of name of TABLE */ + if( pE->op==TK_DOT ){ + assert( pE->pLeft!=0 ); + assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); + zTName = pE->pLeft->u.zToken; + } + for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ + Table *pTab = pFrom->pTab; + Select *pSub = pFrom->pSelect; + char *zTabName = pFrom->zAlias; + const char *zSchemaName = 0; + int iDb; + if( zTabName==0 ){ + zTabName = pTab->zName; + } + if( db->mallocFailed ) break; + if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ + pSub = 0; + if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ + continue; + } + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*"; + } + for(j=0; jnCol; j++){ + char *zName = pTab->aCol[j].zName; + char *zColname; /* The computed column name */ + char *zToFree; /* Malloced string that needs to be freed */ + Token sColname; /* Computed column name as a token */ + + assert( zName ); + if( zTName && pSub + && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 + ){ + continue; + } + + /* If a column is marked as 'hidden' (currently only possible + ** for virtual tables), do not include it in the expanded + ** result-set list. + */ + if( IsHiddenColumn(&pTab->aCol[j]) ){ + assert(IsVirtual(pTab)); + continue; + } + tableSeen = 1; + + if( i>0 && zTName==0 ){ + if( (pFrom->jointype & JT_NATURAL)!=0 + && tableAndColumnIndex(pTabList, i, zName, 0, 0) + ){ + /* In a NATURAL join, omit the join columns from the + ** table to the right of the join */ + continue; + } + if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ + /* In a join with a USING clause, omit columns in the + ** using clause from the table on the right. */ + continue; + } + } + pRight = sqlite3Expr(db, TK_ID, zName); + zColname = zName; + zToFree = 0; + if( longNames || pTabList->nSrc>1 ){ + Expr *pLeft; + pLeft = sqlite3Expr(db, TK_ID, zTabName); + pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); + if( zSchemaName ){ + pLeft = sqlite3Expr(db, TK_ID, zSchemaName); + pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0); + } + if( longNames ){ + zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); + zToFree = zColname; + } + }else{ + pExpr = pRight; + } + pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); + sColname.z = zColname; + sColname.n = sqlite3Strlen30(zColname); + sqlite3ExprListSetName(pParse, pNew, &sColname, 0); + if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ + struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; + if( pSub ){ + pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); + testcase( pX->zSpan==0 ); + }else{ + pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", + zSchemaName, zTabName, zColname); + testcase( pX->zSpan==0 ); + } + pX->bSpanIsTab = 1; + } + sqlite3DbFree(db, zToFree); + } + } + if( !tableSeen ){ + if( zTName ){ + sqlite3ErrorMsg(pParse, "no such table: %s", zTName); + }else{ + sqlite3ErrorMsg(pParse, "no tables specified"); + } + } + } + } + sqlite3ExprListDelete(db, pEList); + p->pEList = pNew; + } +#if SQLITE_MAX_COLUMN + if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + sqlite3ErrorMsg(pParse, "too many columns in result set"); + } +#endif + return WRC_Continue; +} + +/* +** No-op routine for the parse-tree walker. +** +** When this routine is the Walker.xExprCallback then expression trees +** are walked without any actions being taken at each node. Presumably, +** when this routine is used for Walker.xExprCallback then +** Walker.xSelectCallback is set to do something useful for every +** subquery in the parser tree. +*/ +static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return WRC_Continue; +} + +/* +** This routine "expands" a SELECT statement and all of its subqueries. +** For additional information on what it means to "expand" a SELECT +** statement, see the comment on the selectExpand worker callback above. +** +** Expanding a SELECT statement is the first step in processing a +** SELECT statement. The SELECT statement must be expanded before +** name resolution is performed. +** +** If anything goes wrong, an error message is written into pParse. +** The calling function can detect the problem by looking at pParse->nErr +** and/or pParse->db->mallocFailed. +*/ +static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ + Walker w; + memset(&w, 0, sizeof(w)); + w.xExprCallback = exprWalkNoop; + w.pParse = pParse; + if( pParse->hasCompound ){ + w.xSelectCallback = convertCompoundSelectToSubquery; + sqlite3WalkSelect(&w, pSelect); + } + w.xSelectCallback = selectExpander; + sqlite3WalkSelect(&w, pSelect); +} + + +#ifndef SQLITE_OMIT_SUBQUERY +/* +** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() +** interface. +** +** For each FROM-clause subquery, add Column.zType and Column.zColl +** information to the Table structure that represents the result set +** of that subquery. +** +** The Table structure that represents the result set was constructed +** by selectExpander() but the type and collation information was omitted +** at that point because identifiers had not yet been resolved. This +** routine is called after identifier resolution. +*/ +static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ + Parse *pParse; + int i; + SrcList *pTabList; + struct SrcList_item *pFrom; + + assert( p->selFlags & SF_Resolved ); + if( (p->selFlags & SF_HasTypeInfo)==0 ){ + p->selFlags |= SF_HasTypeInfo; + pParse = pWalker->pParse; + pTabList = p->pSrc; + for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ + Table *pTab = pFrom->pTab; + if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){ + /* A sub-query in the FROM clause of a SELECT */ + Select *pSel = pFrom->pSelect; + assert( pSel ); + while( pSel->pPrior ) pSel = pSel->pPrior; + selectAddColumnTypeAndCollation(pParse, pTab, pSel); + } + } + } + return WRC_Continue; +} +#endif + + +/* +** This routine adds datatype and collating sequence information to +** the Table structures of all FROM-clause subqueries in a +** SELECT statement. +** +** Use this routine after name resolution. +*/ +static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ +#ifndef SQLITE_OMIT_SUBQUERY + Walker w; + memset(&w, 0, sizeof(w)); + w.xSelectCallback = selectAddSubqueryTypeInfo; + w.xExprCallback = exprWalkNoop; + w.pParse = pParse; + w.bSelectDepthFirst = 1; + sqlite3WalkSelect(&w, pSelect); +#endif +} + + +/* +** This routine sets up a SELECT statement for processing. The +** following is accomplished: +** +** * VDBE Cursor numbers are assigned to all FROM-clause terms. +** * Ephemeral Table objects are created for all FROM-clause subqueries. +** * ON and USING clauses are shifted into WHERE statements +** * Wildcards "*" and "TABLE.*" in result sets are expanded. +** * Identifiers in expression are matched to tables. +** +** This routine acts recursively on all subqueries within the SELECT. +*/ +SQLITE_PRIVATE void sqlite3SelectPrep( + Parse *pParse, /* The parser context */ + Select *p, /* The SELECT statement being coded. */ + NameContext *pOuterNC /* Name context for container */ +){ + sqlite3 *db; + if( NEVER(p==0) ) return; + db = pParse->db; + if( db->mallocFailed ) return; + if( p->selFlags & SF_HasTypeInfo ) return; + sqlite3SelectExpand(pParse, p); + if( pParse->nErr || db->mallocFailed ) return; + sqlite3ResolveSelectNames(pParse, p, pOuterNC); + if( pParse->nErr || db->mallocFailed ) return; + sqlite3SelectAddTypeInfo(pParse, p); +} + +/* +** Reset the aggregate accumulator. +** +** The aggregate accumulator is a set of memory cells that hold +** intermediate results while calculating an aggregate. This +** routine generates code that stores NULLs in all of those memory +** cells. +*/ +static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ + Vdbe *v = pParse->pVdbe; + int i; + struct AggInfo_func *pFunc; + if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ + return; + } + for(i=0; inColumn; i++){ + sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); + } + for(pFunc=pAggInfo->aFunc, i=0; inFunc; i++, pFunc++){ + sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); + if( pFunc->iDistinct>=0 ){ + Expr *pE = pFunc->pExpr; + assert( !ExprHasProperty(pE, EP_xIsSelect) ); + if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ + sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " + "argument"); + pFunc->iDistinct = -1; + }else{ + KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList); + sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, + (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + } + } + } +} + +/* +** Invoke the OP_AggFinalize opcode for every aggregate function +** in the AggInfo structure. +*/ +static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ + Vdbe *v = pParse->pVdbe; + int i; + struct AggInfo_func *pF; + for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ + ExprList *pList = pF->pExpr->x.pList; + assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); + sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, + (void*)pF->pFunc, P4_FUNCDEF); + } +} + +/* +** Update the accumulator memory cells for an aggregate based on +** the current cursor position. +*/ +static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ + Vdbe *v = pParse->pVdbe; + int i; + int regHit = 0; + int addrHitTest = 0; + struct AggInfo_func *pF; + struct AggInfo_col *pC; + + pAggInfo->directMode = 1; + sqlite3ExprCacheClear(pParse); + for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ + int nArg; + int addrNext = 0; + int regAgg; + ExprList *pList = pF->pExpr->x.pList; + assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); + if( pList ){ + nArg = pList->nExpr; + regAgg = sqlite3GetTempRange(pParse, nArg); + sqlite3ExprCodeExprList(pParse, pList, regAgg, 1); + }else{ + nArg = 0; + regAgg = 0; + } + if( pF->iDistinct>=0 ){ + addrNext = sqlite3VdbeMakeLabel(v); + assert( nArg==1 ); + codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); + } + if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ + CollSeq *pColl = 0; + struct ExprList_item *pItem; + int j; + assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ + for(j=0, pItem=pList->a; !pColl && jpExpr); + } + if( !pColl ){ + pColl = pParse->db->pDfltColl; + } + if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; + sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); + } + sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, + (void*)pF->pFunc, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, (u8)nArg); + sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); + sqlite3ReleaseTempRange(pParse, regAgg, nArg); + if( addrNext ){ + sqlite3VdbeResolveLabel(v, addrNext); + sqlite3ExprCacheClear(pParse); + } + } + + /* Before populating the accumulator registers, clear the column cache. + ** Otherwise, if any of the required column values are already present + ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value + ** to pC->iMem. But by the time the value is used, the original register + ** may have been used, invalidating the underlying buffer holding the + ** text or blob value. See ticket [883034dcb5]. + ** + ** Another solution would be to change the OP_SCopy used to copy cached + ** values to an OP_Copy. + */ + if( regHit ){ + addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); + } + sqlite3ExprCacheClear(pParse); + for(i=0, pC=pAggInfo->aCol; inAccumulator; i++, pC++){ + sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); + } + pAggInfo->directMode = 0; + sqlite3ExprCacheClear(pParse); + if( addrHitTest ){ + sqlite3VdbeJumpHere(v, addrHitTest); + } +} + +/* +** Add a single OP_Explain instruction to the VDBE to explain a simple +** count(*) query ("SELECT count(*) FROM pTab"). +*/ +#ifndef SQLITE_OMIT_EXPLAIN +static void explainSimpleCount( + Parse *pParse, /* Parse context */ + Table *pTab, /* Table being queried */ + Index *pIdx /* Index used to optimize scan, or NULL */ +){ + if( pParse->explain==2 ){ + char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", + pTab->zName, + pIdx ? " USING COVERING INDEX " : "", + pIdx ? pIdx->zName : "" + ); + sqlite3VdbeAddOp4( + pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC + ); + } +} +#else +# define explainSimpleCount(a,b,c) +#endif + +/* +** Generate code for the SELECT statement given in the p argument. +** +** The results are distributed in various ways depending on the +** contents of the SelectDest structure pointed to by argument pDest +** as follows: +** +** pDest->eDest Result +** ------------ ------------------------------------------- +** SRT_Output Generate a row of output (using the OP_ResultRow +** opcode) for each row in the result set. +** +** SRT_Mem Only valid if the result is a single column. +** Store the first column of the first result row +** in register pDest->iSDParm then abandon the rest +** of the query. This destination implies "LIMIT 1". +** +** SRT_Set The result must be a single column. Store each +** row of result as the key in table pDest->iSDParm. +** Apply the affinity pDest->affSdst before storing +** results. Used to implement "IN (SELECT ...)". +** +** SRT_Union Store results as a key in a temporary table +** identified by pDest->iSDParm. +** +** SRT_Except Remove results from the temporary table pDest->iSDParm. +** +** SRT_Table Store results in temporary table pDest->iSDParm. +** This is like SRT_EphemTab except that the table +** is assumed to already be open. +** +** SRT_EphemTab Create an temporary table pDest->iSDParm and store +** the result there. The cursor is left open after +** returning. This is like SRT_Table except that +** this destination uses OP_OpenEphemeral to create +** the table first. +** +** SRT_Coroutine Generate a co-routine that returns a new row of +** results each time it is invoked. The entry point +** of the co-routine is stored in register pDest->iSDParm. +** +** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result +** set is not empty. +** +** SRT_Discard Throw the results away. This is used by SELECT +** statements within triggers whose only purpose is +** the side-effects of functions. +** +** This routine returns the number of errors. If any errors are +** encountered, then an appropriate error message is left in +** pParse->zErrMsg. +** +** This routine does NOT free the Select structure passed in. The +** calling function needs to do that. +*/ +SQLITE_PRIVATE int sqlite3Select( + Parse *pParse, /* The parser context */ + Select *p, /* The SELECT statement being coded. */ + SelectDest *pDest /* What to do with the query results */ +){ + int i, j; /* Loop counters */ + WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ + Vdbe *v; /* The virtual machine under construction */ + int isAgg; /* True for select lists like "count(*)" */ + ExprList *pEList; /* List of columns to extract. */ + SrcList *pTabList; /* List of tables to select from */ + Expr *pWhere; /* The WHERE clause. May be NULL */ + ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ + ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ + Expr *pHaving; /* The HAVING clause. May be NULL */ + int rc = 1; /* Value to return from this function */ + int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ + DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ + AggInfo sAggInfo; /* Information used by aggregate queries */ + int iEnd; /* Address of the end of the query */ + sqlite3 *db; /* The database connection */ + +#ifndef SQLITE_OMIT_EXPLAIN + int iRestoreSelectId = pParse->iSelectId; + pParse->iSelectId = pParse->iNextSelectId++; +#endif + + db = pParse->db; + if( p==0 || db->mallocFailed || pParse->nErr ){ + return 1; + } + if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; + memset(&sAggInfo, 0, sizeof(sAggInfo)); + + if( IgnorableOrderby(pDest) ){ + assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || + pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); + /* If ORDER BY makes no difference in the output then neither does + ** DISTINCT so it can be removed too. */ + sqlite3ExprListDelete(db, p->pOrderBy); + p->pOrderBy = 0; + p->selFlags &= ~SF_Distinct; + } + sqlite3SelectPrep(pParse, p, 0); + pOrderBy = p->pOrderBy; + pTabList = p->pSrc; + pEList = p->pEList; + if( pParse->nErr || db->mallocFailed ){ + goto select_end; + } + isAgg = (p->selFlags & SF_Aggregate)!=0; + assert( pEList!=0 ); + + /* Begin generating code. + */ + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto select_end; + + /* If writing to memory or generating a set + ** only a single column may be output. + */ +#ifndef SQLITE_OMIT_SUBQUERY + if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ + goto select_end; + } +#endif + + /* Generate code for all sub-queries in the FROM clause + */ +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) + for(i=0; !p->pPrior && inSrc; i++){ + struct SrcList_item *pItem = &pTabList->a[i]; + SelectDest dest; + Select *pSub = pItem->pSelect; + int isAggSub; + + if( pSub==0 ) continue; + + /* Sometimes the code for a subquery will be generated more than + ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, + ** for example. In that case, do not regenerate the code to manifest + ** a view or the co-routine to implement a view. The first instance + ** is sufficient, though the subroutine to manifest the view does need + ** to be invoked again. */ + if( pItem->addrFillSub ){ + if( pItem->viaCoroutine==0 ){ + sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); + } + continue; + } + + /* Increment Parse.nHeight by the height of the largest expression + ** tree referred to by this, the parent select. The child select + ** may contain expression trees of at most + ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit + ** more conservative than necessary, but much easier than enforcing + ** an exact limit. + */ + pParse->nHeight += sqlite3SelectExprHeight(p); + + isAggSub = (pSub->selFlags & SF_Aggregate)!=0; + if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ + /* This subquery can be absorbed into its parent. */ + if( isAggSub ){ + isAgg = 1; + p->selFlags |= SF_Aggregate; + } + i = -1; + }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0 + && OptimizationEnabled(db, SQLITE_SubqCoroutine) + ){ + /* Implement a co-routine that will return a single row of the result + ** set on each invocation. + */ + int addrTop; + int addrEof; + pItem->regReturn = ++pParse->nMem; + addrEof = ++pParse->nMem; + /* Before coding the OP_Goto to jump to the start of the main routine, + ** ensure that the jump to the verify-schema routine has already + ** been coded. Otherwise, the verify-schema would likely be coded as + ** part of the co-routine. If the main routine then accessed the + ** database before invoking the co-routine for the first time (for + ** example to initialize a LIMIT register from a sub-select), it would + ** be doing so without having verified the schema version and obtained + ** the required db locks. See ticket d6b36be38. */ + sqlite3CodeVerifySchema(pParse, -1); + sqlite3VdbeAddOp0(v, OP_Goto); + addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor); + sqlite3VdbeChangeP5(v, 1); + VdbeComment((v, "coroutine for %s", pItem->pTab->zName)); + pItem->addrFillSub = addrTop; + sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof); + sqlite3VdbeChangeP5(v, 1); + sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); + explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); + sqlite3Select(pParse, pSub, &dest); + pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow; + pItem->viaCoroutine = 1; + sqlite3VdbeChangeP2(v, addrTop, dest.iSdst); + sqlite3VdbeChangeP3(v, addrTop, dest.nSdst); + sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof); + sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn); + VdbeComment((v, "end %s", pItem->pTab->zName)); + sqlite3VdbeJumpHere(v, addrTop-1); + sqlite3ClearTempRegCache(pParse); + }else{ + /* Generate a subroutine that will fill an ephemeral table with + ** the content of this subquery. pItem->addrFillSub will point + ** to the address of the generated subroutine. pItem->regReturn + ** is a register allocated to hold the subroutine return address + */ + int topAddr; + int onceAddr = 0; + int retAddr; + assert( pItem->addrFillSub==0 ); + pItem->regReturn = ++pParse->nMem; + topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); + pItem->addrFillSub = topAddr+1; + VdbeNoopComment((v, "materialize %s", pItem->pTab->zName)); + if( pItem->isCorrelated==0 ){ + /* If the subquery is not correlated and if we are not inside of + ** a trigger, then we only need to compute the value of the subquery + ** once. */ + onceAddr = sqlite3CodeOnce(pParse); + } + sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); + explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); + sqlite3Select(pParse, pSub, &dest); + pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow; + if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); + retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); + VdbeComment((v, "end %s", pItem->pTab->zName)); + sqlite3VdbeChangeP1(v, topAddr, retAddr); + sqlite3ClearTempRegCache(pParse); + } + if( /*pParse->nErr ||*/ db->mallocFailed ){ + goto select_end; + } + pParse->nHeight -= sqlite3SelectExprHeight(p); + pTabList = p->pSrc; + if( !IgnorableOrderby(pDest) ){ + pOrderBy = p->pOrderBy; + } + } + pEList = p->pEList; +#endif + pWhere = p->pWhere; + pGroupBy = p->pGroupBy; + pHaving = p->pHaving; + sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; + +#ifndef SQLITE_OMIT_COMPOUND_SELECT + /* If there is are a sequence of queries, do the earlier ones first. + */ + if( p->pPrior ){ + if( p->pRightmost==0 ){ + Select *pLoop, *pRight = 0; + int cnt = 0; + int mxSelect; + for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ + pLoop->pRightmost = p; + pLoop->pNext = pRight; + pRight = pLoop; + } + mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; + if( mxSelect && cnt>mxSelect ){ + sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); + goto select_end; + } + } + rc = multiSelect(pParse, p, pDest); + explainSetInteger(pParse->iSelectId, iRestoreSelectId); + return rc; + } +#endif + + /* If there is both a GROUP BY and an ORDER BY clause and they are + ** identical, then disable the ORDER BY clause since the GROUP BY + ** will cause elements to come out in the correct order. This is + ** an optimization - the correct answer should result regardless. + ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER + ** to disable this optimization for testing purposes. + */ + if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0 + && OptimizationEnabled(db, SQLITE_GroupByOrder) ){ + pOrderBy = 0; + } + + /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and + ** if the select-list is the same as the ORDER BY list, then this query + ** can be rewritten as a GROUP BY. In other words, this: + ** + ** SELECT DISTINCT xyz FROM ... ORDER BY xyz + ** + ** is transformed to: + ** + ** SELECT xyz FROM ... GROUP BY xyz + ** + ** The second form is preferred as a single index (or temp-table) may be + ** used for both the ORDER BY and DISTINCT processing. As originally + ** written the query must use a temp-table for at least one of the ORDER + ** BY and DISTINCT, and an index or separate temp-table for the other. + */ + if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct + && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0 + ){ + p->selFlags &= ~SF_Distinct; + p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0); + pGroupBy = p->pGroupBy; + pOrderBy = 0; + /* Notice that even thought SF_Distinct has been cleared from p->selFlags, + ** the sDistinct.isTnct is still set. Hence, isTnct represents the + ** original setting of the SF_Distinct flag, not the current setting */ + assert( sDistinct.isTnct ); + } + + /* If there is an ORDER BY clause, then this sorting + ** index might end up being unused if the data can be + ** extracted in pre-sorted order. If that is the case, then the + ** OP_OpenEphemeral instruction will be changed to an OP_Noop once + ** we figure out that the sorting index is not needed. The addrSortIndex + ** variable is used to facilitate that change. + */ + if( pOrderBy ){ + KeyInfo *pKeyInfo; + pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); + pOrderBy->iECursor = pParse->nTab++; + p->addrOpenEphm[2] = addrSortIndex = + sqlite3VdbeAddOp4(v, OP_OpenEphemeral, + pOrderBy->iECursor, pOrderBy->nExpr+2, 0, + (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + }else{ + addrSortIndex = -1; + } + + /* If the output is destined for a temporary table, open that table. + */ + if( pDest->eDest==SRT_EphemTab ){ + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); + } + + /* Set the limiter. + */ + iEnd = sqlite3VdbeMakeLabel(v); + p->nSelectRow = LARGEST_INT64; + computeLimitRegisters(pParse, p, iEnd); + if( p->iLimit==0 && addrSortIndex>=0 ){ + sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen; + p->selFlags |= SF_UseSorter; + } + + /* Open a virtual index to use for the distinct set. + */ + if( p->selFlags & SF_Distinct ){ + sDistinct.tabTnct = pParse->nTab++; + sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, + sDistinct.tabTnct, 0, 0, + (char*)keyInfoFromExprList(pParse, p->pEList), + P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP5(v, BTREE_UNORDERED); + sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; + }else{ + sDistinct.eTnctType = WHERE_DISTINCT_NOOP; + } + + if( !isAgg && pGroupBy==0 ){ + /* No aggregate functions and no GROUP BY clause */ + u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); + + /* Begin the database scan. */ + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList, + wctrlFlags, 0); + if( pWInfo==0 ) goto select_end; + if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ + p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); + } + if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ + sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); + } + if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0; + + /* If sorting index that was created by a prior OP_OpenEphemeral + ** instruction ended up not being needed, then change the OP_OpenEphemeral + ** into an OP_Noop. + */ + if( addrSortIndex>=0 && pOrderBy==0 ){ + sqlite3VdbeChangeToNoop(v, addrSortIndex); + p->addrOpenEphm[2] = -1; + } + + /* Use the standard inner loop. */ + selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest, + sqlite3WhereContinueLabel(pWInfo), + sqlite3WhereBreakLabel(pWInfo)); + + /* End the database scan loop. + */ + sqlite3WhereEnd(pWInfo); + }else{ + /* This case when there exist aggregate functions or a GROUP BY clause + ** or both */ + NameContext sNC; /* Name context for processing aggregate information */ + int iAMem; /* First Mem address for storing current GROUP BY */ + int iBMem; /* First Mem address for previous GROUP BY */ + int iUseFlag; /* Mem address holding flag indicating that at least + ** one row of the input to the aggregator has been + ** processed */ + int iAbortFlag; /* Mem address which causes query abort if positive */ + int groupBySort; /* Rows come from source in GROUP BY order */ + int addrEnd; /* End of processing for this SELECT */ + int sortPTab = 0; /* Pseudotable used to decode sorting results */ + int sortOut = 0; /* Output register from the sorter */ + + /* Remove any and all aliases between the result set and the + ** GROUP BY clause. + */ + if( pGroupBy ){ + int k; /* Loop counter */ + struct ExprList_item *pItem; /* For looping over expression in a list */ + + for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ + pItem->iAlias = 0; + } + for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ + pItem->iAlias = 0; + } + if( p->nSelectRow>100 ) p->nSelectRow = 100; + }else{ + p->nSelectRow = 1; + } + + + /* Create a label to jump to when we want to abort the query */ + addrEnd = sqlite3VdbeMakeLabel(v); + + /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in + ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the + ** SELECT statement. + */ + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + sNC.pAggInfo = &sAggInfo; + sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; + sAggInfo.pGroupBy = pGroupBy; + sqlite3ExprAnalyzeAggList(&sNC, pEList); + sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); + if( pHaving ){ + sqlite3ExprAnalyzeAggregates(&sNC, pHaving); + } + sAggInfo.nAccumulator = sAggInfo.nColumn; + for(i=0; ix.pList); + sNC.ncFlags &= ~NC_InAggFunc; + } + if( db->mallocFailed ) goto select_end; + + /* Processing for aggregates with GROUP BY is very different and + ** much more complex than aggregates without a GROUP BY. + */ + if( pGroupBy ){ + KeyInfo *pKeyInfo; /* Keying information for the group by clause */ + int j1; /* A-vs-B comparision jump */ + int addrOutputRow; /* Start of subroutine that outputs a result row */ + int regOutputRow; /* Return address register for output subroutine */ + int addrSetAbort; /* Set the abort flag and return */ + int addrTopOfLoop; /* Top of the input loop */ + int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ + int addrReset; /* Subroutine for resetting the accumulator */ + int regReset; /* Return address register for reset subroutine */ + + /* If there is a GROUP BY clause we might need a sorting index to + ** implement it. Allocate that sorting index now. If it turns out + ** that we do not need it after all, the OP_SorterOpen instruction + ** will be converted into a Noop. + */ + sAggInfo.sortingIdx = pParse->nTab++; + pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); + addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, + sAggInfo.sortingIdx, sAggInfo.nSortingColumn, + 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + + /* Initialize memory locations used by GROUP BY aggregate processing + */ + iUseFlag = ++pParse->nMem; + iAbortFlag = ++pParse->nMem; + regOutputRow = ++pParse->nMem; + addrOutputRow = sqlite3VdbeMakeLabel(v); + regReset = ++pParse->nMem; + addrReset = sqlite3VdbeMakeLabel(v); + iAMem = pParse->nMem + 1; + pParse->nMem += pGroupBy->nExpr; + iBMem = pParse->nMem + 1; + pParse->nMem += pGroupBy->nExpr; + sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); + VdbeComment((v, "clear abort flag")); + sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); + VdbeComment((v, "indicate accumulator empty")); + sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); + + /* Begin a loop that will extract all source rows in GROUP BY order. + ** This might involve two separate loops with an OP_Sort in between, or + ** it might be a single loop that uses an index to extract information + ** in the right order to begin with. + */ + sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, + WHERE_GROUPBY, 0); + if( pWInfo==0 ) goto select_end; + if( sqlite3WhereIsOrdered(pWInfo) ){ + /* The optimizer is able to deliver rows in group by order so + ** we do not have to sort. The OP_OpenEphemeral table will be + ** cancelled later because we still need to use the pKeyInfo + */ + groupBySort = 0; + }else{ + /* Rows are coming out in undetermined order. We have to push + ** each row into a sorting index, terminate the first loop, + ** then loop over the sorting index in order to get the output + ** in sorted order + */ + int regBase; + int regRecord; + int nCol; + int nGroupBy; + + explainTempTable(pParse, + (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? + "DISTINCT" : "GROUP BY"); + + groupBySort = 1; + nGroupBy = pGroupBy->nExpr; + nCol = nGroupBy + 1; + j = nGroupBy+1; + for(i=0; i=j ){ + nCol++; + j++; + } + } + regBase = sqlite3GetTempRange(pParse, nCol); + sqlite3ExprCacheClear(pParse); + sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0); + sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); + j = nGroupBy+1; + for(i=0; iiSorterColumn>=j ){ + int r1 = j + regBase; + int r2; + + r2 = sqlite3ExprCodeGetColumn(pParse, + pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0); + if( r1!=r2 ){ + sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1); + } + j++; + } + } + regRecord = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); + sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); + sqlite3ReleaseTempReg(pParse, regRecord); + sqlite3ReleaseTempRange(pParse, regBase, nCol); + sqlite3WhereEnd(pWInfo); + sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; + sortOut = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); + sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); + VdbeComment((v, "GROUP BY sort")); + sAggInfo.useSortingIdx = 1; + sqlite3ExprCacheClear(pParse); + } + + /* Evaluate the current GROUP BY terms and store in b0, b1, b2... + ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) + ** Then compare the current GROUP BY terms against the GROUP BY terms + ** from the previous row currently stored in a0, a1, a2... + */ + addrTopOfLoop = sqlite3VdbeCurrentAddr(v); + sqlite3ExprCacheClear(pParse); + if( groupBySort ){ + sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut); + } + for(j=0; jnExpr; j++){ + if( groupBySort ){ + sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); + if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); + }else{ + sAggInfo.directMode = 1; + sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); + } + } + sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, + (char*)pKeyInfo, P4_KEYINFO); + j1 = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); + + /* Generate code that runs whenever the GROUP BY changes. + ** Changes in the GROUP BY are detected by the previous code + ** block. If there were no changes, this block is skipped. + ** + ** This code copies current group by terms in b0,b1,b2,... + ** over to a0,a1,a2. It then calls the output subroutine + ** and resets the aggregate accumulator registers in preparation + ** for the next GROUP BY batch. + */ + sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); + sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); + VdbeComment((v, "output one row")); + sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); + VdbeComment((v, "check abort flag")); + sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); + VdbeComment((v, "reset accumulator")); + + /* Update the aggregate accumulators based on the content of + ** the current row + */ + sqlite3VdbeJumpHere(v, j1); + updateAccumulator(pParse, &sAggInfo); + sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); + VdbeComment((v, "indicate data in accumulator")); + + /* End of the loop + */ + if( groupBySort ){ + sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); + }else{ + sqlite3WhereEnd(pWInfo); + sqlite3VdbeChangeToNoop(v, addrSortingIdx); + } + + /* Output the final row of result + */ + sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); + VdbeComment((v, "output final row")); + + /* Jump over the subroutines + */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd); + + /* Generate a subroutine that outputs a single row of the result + ** set. This subroutine first looks at the iUseFlag. If iUseFlag + ** is less than or equal to zero, the subroutine is a no-op. If + ** the processing calls for the query to abort, this subroutine + ** increments the iAbortFlag memory location before returning in + ** order to signal the caller to abort. + */ + addrSetAbort = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); + VdbeComment((v, "set abort flag")); + sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + sqlite3VdbeResolveLabel(v, addrOutputRow); + addrOutputRow = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); + VdbeComment((v, "Groupby result generator entry point")); + sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + finalizeAggFunctions(pParse, &sAggInfo); + sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); + selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, + &sDistinct, pDest, + addrOutputRow+1, addrSetAbort); + sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + VdbeComment((v, "end groupby result generator")); + + /* Generate a subroutine that will reset the group-by accumulator + */ + sqlite3VdbeResolveLabel(v, addrReset); + resetAccumulator(pParse, &sAggInfo); + sqlite3VdbeAddOp1(v, OP_Return, regReset); + + } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ + else { + ExprList *pDel = 0; +#ifndef SQLITE_OMIT_BTREECOUNT + Table *pTab; + if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ + /* If isSimpleCount() returns a pointer to a Table structure, then + ** the SQL statement is of the form: + ** + ** SELECT count(*) FROM + ** + ** where the Table structure returned represents table . + ** + ** This statement is so common that it is optimized specially. The + ** OP_Count instruction is executed either on the intkey table that + ** contains the data for table or on one of its indexes. It + ** is better to execute the op on an index, as indexes are almost + ** always spread across less pages than their corresponding tables. + */ + const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ + Index *pIdx; /* Iterator variable */ + KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ + Index *pBest = 0; /* Best index found so far */ + int iRoot = pTab->tnum; /* Root page of scanned b-tree */ + + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + + /* Search for the index that has the lowest scan cost. + ** + ** (2011-04-15) Do not do a full scan of an unordered index. + ** + ** (2013-10-03) Do not count the entires in a partial index. + ** + ** In practice the KeyInfo structure will not be used. It is only + ** passed to keep OP_OpenRead happy. + */ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->bUnordered==0 + && pIdx->szIdxRowszTabRow + && pIdx->pPartIdxWhere==0 + && (!pBest || pIdx->szIdxRowszIdxRow) + ){ + pBest = pIdx; + } + } + if( pBest ){ + iRoot = pBest->tnum; + pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest); + } + + /* Open a read-only cursor, execute the OP_Count, close the cursor. */ + sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb); + if( pKeyInfo ){ + sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF); + } + sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); + sqlite3VdbeAddOp1(v, OP_Close, iCsr); + explainSimpleCount(pParse, pTab, pBest); + }else +#endif /* SQLITE_OMIT_BTREECOUNT */ + { + /* Check if the query is of one of the following forms: + ** + ** SELECT min(x) FROM ... + ** SELECT max(x) FROM ... + ** + ** If it is, then ask the code in where.c to attempt to sort results + ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. + ** If where.c is able to produce results sorted in this order, then + ** add vdbe code to break out of the processing loop after the + ** first iteration (since the first iteration of the loop is + ** guaranteed to operate on the row with the minimum or maximum + ** value of x, the only row required). + ** + ** A special flag must be passed to sqlite3WhereBegin() to slightly + ** modify behavior as follows: + ** + ** + If the query is a "SELECT min(x)", then the loop coded by + ** where.c should not iterate over any values with a NULL value + ** for x. + ** + ** + The optimizer code in where.c (the thing that decides which + ** index or indices to use) should place a different priority on + ** satisfying the 'ORDER BY' clause than it does in other cases. + ** Refer to code and comments in where.c for details. + */ + ExprList *pMinMax = 0; + u8 flag = WHERE_ORDERBY_NORMAL; + + assert( p->pGroupBy==0 ); + assert( flag==0 ); + if( p->pHaving==0 ){ + flag = minMaxQuery(&sAggInfo, &pMinMax); + } + assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) ); + + if( flag ){ + pMinMax = sqlite3ExprListDup(db, pMinMax, 0); + pDel = pMinMax; + if( pMinMax && !db->mallocFailed ){ + pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; + pMinMax->a[0].pExpr->op = TK_COLUMN; + } + } + + /* This case runs if the aggregate has no GROUP BY clause. The + ** processing is much simpler since there is only a single row + ** of output. + */ + resetAccumulator(pParse, &sAggInfo); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0); + if( pWInfo==0 ){ + sqlite3ExprListDelete(db, pDel); + goto select_end; + } + updateAccumulator(pParse, &sAggInfo); + assert( pMinMax==0 || pMinMax->nExpr==1 ); + if( sqlite3WhereIsOrdered(pWInfo) ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo)); + VdbeComment((v, "%s() by index", + (flag==WHERE_ORDERBY_MIN?"min":"max"))); + } + sqlite3WhereEnd(pWInfo); + finalizeAggFunctions(pParse, &sAggInfo); + } + + pOrderBy = 0; + sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); + selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0, + pDest, addrEnd, addrEnd); + sqlite3ExprListDelete(db, pDel); + } + sqlite3VdbeResolveLabel(v, addrEnd); + + } /* endif aggregate query */ + + if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ + explainTempTable(pParse, "DISTINCT"); + } + + /* If there is an ORDER BY clause, then we need to sort the results + ** and send them to the callback one by one. + */ + if( pOrderBy ){ + explainTempTable(pParse, "ORDER BY"); + generateSortTail(pParse, p, v, pEList->nExpr, pDest); + } + + /* Jump here to skip this query + */ + sqlite3VdbeResolveLabel(v, iEnd); + + /* The SELECT was successfully coded. Set the return code to 0 + ** to indicate no errors. + */ + rc = 0; + + /* Control jumps to here if an error is encountered above, or upon + ** successful coding of the SELECT. + */ +select_end: + explainSetInteger(pParse->iSelectId, iRestoreSelectId); + + /* Identify column names if results of the SELECT are to be output. + */ + if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ + generateColumnNames(pParse, pTabList, pEList); + } + + sqlite3DbFree(db, sAggInfo.aCol); + sqlite3DbFree(db, sAggInfo.aFunc); + return rc; +} + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) +/* +** Generate a human-readable description of a the Select object. +*/ +static void explainOneSelect(Vdbe *pVdbe, Select *p){ + sqlite3ExplainPrintf(pVdbe, "SELECT "); + if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ + if( p->selFlags & SF_Distinct ){ + sqlite3ExplainPrintf(pVdbe, "DISTINCT "); + } + if( p->selFlags & SF_Aggregate ){ + sqlite3ExplainPrintf(pVdbe, "agg_flag "); + } + sqlite3ExplainNL(pVdbe); + sqlite3ExplainPrintf(pVdbe, " "); + } + sqlite3ExplainExprList(pVdbe, p->pEList); + sqlite3ExplainNL(pVdbe); + if( p->pSrc && p->pSrc->nSrc ){ + int i; + sqlite3ExplainPrintf(pVdbe, "FROM "); + sqlite3ExplainPush(pVdbe); + for(i=0; ipSrc->nSrc; i++){ + struct SrcList_item *pItem = &p->pSrc->a[i]; + sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor); + if( pItem->pSelect ){ + sqlite3ExplainSelect(pVdbe, pItem->pSelect); + if( pItem->pTab ){ + sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName); + } + }else if( pItem->zName ){ + sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName); + } + if( pItem->zAlias ){ + sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias); + } + if( pItem->jointype & JT_LEFT ){ + sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN"); + } + sqlite3ExplainNL(pVdbe); + } + sqlite3ExplainPop(pVdbe); + } + if( p->pWhere ){ + sqlite3ExplainPrintf(pVdbe, "WHERE "); + sqlite3ExplainExpr(pVdbe, p->pWhere); + sqlite3ExplainNL(pVdbe); + } + if( p->pGroupBy ){ + sqlite3ExplainPrintf(pVdbe, "GROUPBY "); + sqlite3ExplainExprList(pVdbe, p->pGroupBy); + sqlite3ExplainNL(pVdbe); + } + if( p->pHaving ){ + sqlite3ExplainPrintf(pVdbe, "HAVING "); + sqlite3ExplainExpr(pVdbe, p->pHaving); + sqlite3ExplainNL(pVdbe); + } + if( p->pOrderBy ){ + sqlite3ExplainPrintf(pVdbe, "ORDERBY "); + sqlite3ExplainExprList(pVdbe, p->pOrderBy); + sqlite3ExplainNL(pVdbe); + } + if( p->pLimit ){ + sqlite3ExplainPrintf(pVdbe, "LIMIT "); + sqlite3ExplainExpr(pVdbe, p->pLimit); + sqlite3ExplainNL(pVdbe); + } + if( p->pOffset ){ + sqlite3ExplainPrintf(pVdbe, "OFFSET "); + sqlite3ExplainExpr(pVdbe, p->pOffset); + sqlite3ExplainNL(pVdbe); + } +} +SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){ + if( p==0 ){ + sqlite3ExplainPrintf(pVdbe, "(null-select)"); + return; + } + while( p->pPrior ){ + p->pPrior->pNext = p; + p = p->pPrior; + } + sqlite3ExplainPush(pVdbe); + while( p ){ + explainOneSelect(pVdbe, p); + p = p->pNext; + if( p==0 ) break; + sqlite3ExplainNL(pVdbe); + sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op)); + } + sqlite3ExplainPrintf(pVdbe, "END"); + sqlite3ExplainPop(pVdbe); +} + +/* End of the structure debug printing code +*****************************************************************************/ +#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */ + +/************** End of select.c **********************************************/ +/************** Begin file table.c *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the sqlite3_get_table() and sqlite3_free_table() +** interface routines. These are just wrappers around the main +** interface routine of sqlite3_exec(). +** +** These routines are in a separate files so that they will not be linked +** if they are not used. +*/ +/* #include */ +/* #include */ + +#ifndef SQLITE_OMIT_GET_TABLE + +/* +** This structure is used to pass data from sqlite3_get_table() through +** to the callback function is uses to build the result. +*/ +typedef struct TabResult { + char **azResult; /* Accumulated output */ + char *zErrMsg; /* Error message text, if an error occurs */ + int nAlloc; /* Slots allocated for azResult[] */ + int nRow; /* Number of rows in the result */ + int nColumn; /* Number of columns in the result */ + int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */ + int rc; /* Return code from sqlite3_exec() */ +} TabResult; + +/* +** This routine is called once for each row in the result table. Its job +** is to fill in the TabResult structure appropriately, allocating new +** memory as necessary. +*/ +static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ + TabResult *p = (TabResult*)pArg; /* Result accumulator */ + int need; /* Slots needed in p->azResult[] */ + int i; /* Loop counter */ + char *z; /* A single column of result */ + + /* Make sure there is enough space in p->azResult to hold everything + ** we need to remember from this invocation of the callback. + */ + if( p->nRow==0 && argv!=0 ){ + need = nCol*2; + }else{ + need = nCol; + } + if( p->nData + need > p->nAlloc ){ + char **azNew; + p->nAlloc = p->nAlloc*2 + need; + azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc ); + if( azNew==0 ) goto malloc_failed; + p->azResult = azNew; + } + + /* If this is the first row, then generate an extra row containing + ** the names of all columns. + */ + if( p->nRow==0 ){ + p->nColumn = nCol; + for(i=0; iazResult[p->nData++] = z; + } + }else if( p->nColumn!=nCol ){ + sqlite3_free(p->zErrMsg); + p->zErrMsg = sqlite3_mprintf( + "sqlite3_get_table() called with two or more incompatible queries" + ); + p->rc = SQLITE_ERROR; + return 1; + } + + /* Copy over the row data + */ + if( argv!=0 ){ + for(i=0; iazResult[p->nData++] = z; + } + p->nRow++; + } + return 0; + +malloc_failed: + p->rc = SQLITE_NOMEM; + return 1; +} + +/* +** Query the database. But instead of invoking a callback for each row, +** malloc() for space to hold the result and return the entire results +** at the conclusion of the call. +** +** The result that is written to ***pazResult is held in memory obtained +** from malloc(). But the caller cannot free this memory directly. +** Instead, the entire table should be passed to sqlite3_free_table() when +** the calling procedure is finished using it. +*/ +SQLITE_API int sqlite3_get_table( + sqlite3 *db, /* The database on which the SQL executes */ + const char *zSql, /* The SQL to be executed */ + char ***pazResult, /* Write the result table here */ + int *pnRow, /* Write the number of rows in the result here */ + int *pnColumn, /* Write the number of columns of result here */ + char **pzErrMsg /* Write error messages here */ +){ + int rc; + TabResult res; + + *pazResult = 0; + if( pnColumn ) *pnColumn = 0; + if( pnRow ) *pnRow = 0; + if( pzErrMsg ) *pzErrMsg = 0; + res.zErrMsg = 0; + res.nRow = 0; + res.nColumn = 0; + res.nData = 1; + res.nAlloc = 20; + res.rc = SQLITE_OK; + res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc ); + if( res.azResult==0 ){ + db->errCode = SQLITE_NOMEM; + return SQLITE_NOMEM; + } + res.azResult[0] = 0; + rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg); + assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); + res.azResult[0] = SQLITE_INT_TO_PTR(res.nData); + if( (rc&0xff)==SQLITE_ABORT ){ + sqlite3_free_table(&res.azResult[1]); + if( res.zErrMsg ){ + if( pzErrMsg ){ + sqlite3_free(*pzErrMsg); + *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); + } + sqlite3_free(res.zErrMsg); + } + db->errCode = res.rc; /* Assume 32-bit assignment is atomic */ + return res.rc; + } + sqlite3_free(res.zErrMsg); + if( rc!=SQLITE_OK ){ + sqlite3_free_table(&res.azResult[1]); + return rc; + } + if( res.nAlloc>res.nData ){ + char **azNew; + azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData ); + if( azNew==0 ){ + sqlite3_free_table(&res.azResult[1]); + db->errCode = SQLITE_NOMEM; + return SQLITE_NOMEM; + } + res.azResult = azNew; + } + *pazResult = &res.azResult[1]; + if( pnColumn ) *pnColumn = res.nColumn; + if( pnRow ) *pnRow = res.nRow; + return rc; +} + +/* +** This routine frees the space the sqlite3_get_table() malloced. +*/ +SQLITE_API void sqlite3_free_table( + char **azResult /* Result returned from from sqlite3_get_table() */ +){ + if( azResult ){ + int i, n; + azResult--; + assert( azResult!=0 ); + n = SQLITE_PTR_TO_INT(azResult[0]); + for(i=1; ipNext; + + sqlite3ExprDelete(db, pTmp->pWhere); + sqlite3ExprListDelete(db, pTmp->pExprList); + sqlite3SelectDelete(db, pTmp->pSelect); + sqlite3IdListDelete(db, pTmp->pIdList); + + sqlite3DbFree(db, pTmp); + } +} + +/* +** Given table pTab, return a list of all the triggers attached to +** the table. The list is connected by Trigger.pNext pointers. +** +** All of the triggers on pTab that are in the same database as pTab +** are already attached to pTab->pTrigger. But there might be additional +** triggers on pTab in the TEMP schema. This routine prepends all +** TEMP triggers on pTab to the beginning of the pTab->pTrigger list +** and returns the combined list. +** +** To state it another way: This routine returns a list of all triggers +** that fire off of pTab. The list will include any TEMP triggers on +** pTab as well as the triggers lised in pTab->pTrigger. +*/ +SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ + Schema * const pTmpSchema = pParse->db->aDb[1].pSchema; + Trigger *pList = 0; /* List of triggers to return */ + + if( pParse->disableTriggers ){ + return 0; + } + + if( pTmpSchema!=pTab->pSchema ){ + HashElem *p; + assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) ); + for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){ + Trigger *pTrig = (Trigger *)sqliteHashData(p); + if( pTrig->pTabSchema==pTab->pSchema + && 0==sqlite3StrICmp(pTrig->table, pTab->zName) + ){ + pTrig->pNext = (pList ? pList : pTab->pTrigger); + pList = pTrig; + } + } + } + + return (pList ? pList : pTab->pTrigger); +} + +/* +** This is called by the parser when it sees a CREATE TRIGGER statement +** up to the point of the BEGIN before the trigger actions. A Trigger +** structure is generated based on the information available and stored +** in pParse->pNewTrigger. After the trigger actions have been parsed, the +** sqlite3FinishTrigger() function is called to complete the trigger +** construction process. +*/ +SQLITE_PRIVATE void sqlite3BeginTrigger( + Parse *pParse, /* The parse context of the CREATE TRIGGER statement */ + Token *pName1, /* The name of the trigger */ + Token *pName2, /* The name of the trigger */ + int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */ + int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */ + IdList *pColumns, /* column list if this is an UPDATE OF trigger */ + SrcList *pTableName,/* The name of the table/view the trigger applies to */ + Expr *pWhen, /* WHEN clause */ + int isTemp, /* True if the TEMPORARY keyword is present */ + int noErr /* Suppress errors if the trigger already exists */ +){ + Trigger *pTrigger = 0; /* The new trigger */ + Table *pTab; /* Table that the trigger fires off of */ + char *zName = 0; /* Name of the trigger */ + sqlite3 *db = pParse->db; /* The database connection */ + int iDb; /* The database to store the trigger in */ + Token *pName; /* The unqualified db name */ + DbFixer sFix; /* State vector for the DB fixer */ + int iTabDb; /* Index of the database holding pTab */ + + assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */ + assert( pName2!=0 ); + assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE ); + assert( op>0 && op<0xff ); + if( isTemp ){ + /* If TEMP was specified, then the trigger name may not be qualified. */ + if( pName2->n>0 ){ + sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name"); + goto trigger_cleanup; + } + iDb = 1; + pName = pName1; + }else{ + /* Figure out the db that the trigger will be created in */ + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); + if( iDb<0 ){ + goto trigger_cleanup; + } + } + if( !pTableName || db->mallocFailed ){ + goto trigger_cleanup; + } + + /* A long-standing parser bug is that this syntax was allowed: + ** + ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab .... + ** ^^^^^^^^ + ** + ** To maintain backwards compatibility, ignore the database + ** name on pTableName if we are reparsing our of SQLITE_MASTER. + */ + if( db->init.busy && iDb!=1 ){ + sqlite3DbFree(db, pTableName->a[0].zDatabase); + pTableName->a[0].zDatabase = 0; + } + + /* If the trigger name was unqualified, and the table is a temp table, + ** then set iDb to 1 to create the trigger in the temporary database. + ** If sqlite3SrcListLookup() returns 0, indicating the table does not + ** exist, the error is caught by the block below. + */ + pTab = sqlite3SrcListLookup(pParse, pTableName); + if( db->init.busy==0 && pName2->n==0 && pTab + && pTab->pSchema==db->aDb[1].pSchema ){ + iDb = 1; + } + + /* Ensure the table name matches database name and that the table exists */ + if( db->mallocFailed ) goto trigger_cleanup; + assert( pTableName->nSrc==1 ); + sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName); + if( sqlite3FixSrcList(&sFix, pTableName) ){ + goto trigger_cleanup; + } + pTab = sqlite3SrcListLookup(pParse, pTableName); + if( !pTab ){ + /* The table does not exist. */ + if( db->init.iDb==1 ){ + /* Ticket #3810. + ** Normally, whenever a table is dropped, all associated triggers are + ** dropped too. But if a TEMP trigger is created on a non-TEMP table + ** and the table is dropped by a different database connection, the + ** trigger is not visible to the database connection that does the + ** drop so the trigger cannot be dropped. This results in an + ** "orphaned trigger" - a trigger whose associated table is missing. + */ + db->init.orphanTrigger = 1; + } + goto trigger_cleanup; + } + if( IsVirtual(pTab) ){ + sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables"); + goto trigger_cleanup; + } + + /* Check that the trigger name is not reserved and that no trigger of the + ** specified name exists */ + zName = sqlite3NameFromToken(db, pName); + if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ + goto trigger_cleanup; + } + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), + zName, sqlite3Strlen30(zName)) ){ + if( !noErr ){ + sqlite3ErrorMsg(pParse, "trigger %T already exists", pName); + }else{ + assert( !db->init.busy ); + sqlite3CodeVerifySchema(pParse, iDb); + } + goto trigger_cleanup; + } + + /* Do not create a trigger on a system table */ + if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ + sqlite3ErrorMsg(pParse, "cannot create trigger on system table"); + pParse->nErr++; + goto trigger_cleanup; + } + + /* INSTEAD of triggers are only for views and views only support INSTEAD + ** of triggers. + */ + if( pTab->pSelect && tr_tm!=TK_INSTEAD ){ + sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", + (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0); + goto trigger_cleanup; + } + if( !pTab->pSelect && tr_tm==TK_INSTEAD ){ + sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF" + " trigger on table: %S", pTableName, 0); + goto trigger_cleanup; + } + iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); + +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int code = SQLITE_CREATE_TRIGGER; + const char *zDb = db->aDb[iTabDb].zName; + const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb; + if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER; + if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){ + goto trigger_cleanup; + } + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){ + goto trigger_cleanup; + } + } +#endif + + /* INSTEAD OF triggers can only appear on views and BEFORE triggers + ** cannot appear on views. So we might as well translate every + ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code + ** elsewhere. + */ + if (tr_tm == TK_INSTEAD){ + tr_tm = TK_BEFORE; + } + + /* Build the Trigger object */ + pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger)); + if( pTrigger==0 ) goto trigger_cleanup; + pTrigger->zName = zName; + zName = 0; + pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName); + pTrigger->pSchema = db->aDb[iDb].pSchema; + pTrigger->pTabSchema = pTab->pSchema; + pTrigger->op = (u8)op; + pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER; + pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); + pTrigger->pColumns = sqlite3IdListDup(db, pColumns); + assert( pParse->pNewTrigger==0 ); + pParse->pNewTrigger = pTrigger; + +trigger_cleanup: + sqlite3DbFree(db, zName); + sqlite3SrcListDelete(db, pTableName); + sqlite3IdListDelete(db, pColumns); + sqlite3ExprDelete(db, pWhen); + if( !pParse->pNewTrigger ){ + sqlite3DeleteTrigger(db, pTrigger); + }else{ + assert( pParse->pNewTrigger==pTrigger ); + } +} + +/* +** This routine is called after all of the trigger actions have been parsed +** in order to complete the process of building the trigger. +*/ +SQLITE_PRIVATE void sqlite3FinishTrigger( + Parse *pParse, /* Parser context */ + TriggerStep *pStepList, /* The triggered program */ + Token *pAll /* Token that describes the complete CREATE TRIGGER */ +){ + Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */ + char *zName; /* Name of trigger */ + sqlite3 *db = pParse->db; /* The database */ + DbFixer sFix; /* Fixer object */ + int iDb; /* Database containing the trigger */ + Token nameToken; /* Trigger name for error reporting */ + + pParse->pNewTrigger = 0; + if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup; + zName = pTrig->zName; + iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); + pTrig->step_list = pStepList; + while( pStepList ){ + pStepList->pTrig = pTrig; + pStepList = pStepList->pNext; + } + nameToken.z = pTrig->zName; + nameToken.n = sqlite3Strlen30(nameToken.z); + sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken); + if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) + || sqlite3FixExpr(&sFix, pTrig->pWhen) + ){ + goto triggerfinish_cleanup; + } + + /* if we are not initializing, + ** build the sqlite_master entry + */ + if( !db->init.busy ){ + Vdbe *v; + char *z; + + /* Make an entry in the sqlite_master table */ + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto triggerfinish_cleanup; + sqlite3BeginWriteOperation(pParse, 0, iDb); + z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n); + sqlite3NestedParse(pParse, + "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName, + pTrig->table, z); + sqlite3DbFree(db, z); + sqlite3ChangeCookie(pParse, iDb); + sqlite3VdbeAddParseSchemaOp(v, iDb, + sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName)); + } + + if( db->init.busy ){ + Trigger *pLink = pTrig; + Hash *pHash = &db->aDb[iDb].pSchema->trigHash; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig); + if( pTrig ){ + db->mallocFailed = 1; + }else if( pLink->pSchema==pLink->pTabSchema ){ + Table *pTab; + int n = sqlite3Strlen30(pLink->table); + pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n); + assert( pTab!=0 ); + pLink->pNext = pTab->pTrigger; + pTab->pTrigger = pLink; + } + } + +triggerfinish_cleanup: + sqlite3DeleteTrigger(db, pTrig); + assert( !pParse->pNewTrigger ); + sqlite3DeleteTriggerStep(db, pStepList); +} + +/* +** Turn a SELECT statement (that the pSelect parameter points to) into +** a trigger step. Return a pointer to a TriggerStep structure. +** +** The parser calls this routine when it finds a SELECT statement in +** body of a TRIGGER. +*/ +SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){ + TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); + if( pTriggerStep==0 ) { + sqlite3SelectDelete(db, pSelect); + return 0; + } + pTriggerStep->op = TK_SELECT; + pTriggerStep->pSelect = pSelect; + pTriggerStep->orconf = OE_Default; + return pTriggerStep; +} + +/* +** Allocate space to hold a new trigger step. The allocated space +** holds both the TriggerStep object and the TriggerStep.target.z string. +** +** If an OOM error occurs, NULL is returned and db->mallocFailed is set. +*/ +static TriggerStep *triggerStepAllocate( + sqlite3 *db, /* Database connection */ + u8 op, /* Trigger opcode */ + Token *pName /* The target name */ +){ + TriggerStep *pTriggerStep; + + pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n); + if( pTriggerStep ){ + char *z = (char*)&pTriggerStep[1]; + memcpy(z, pName->z, pName->n); + pTriggerStep->target.z = z; + pTriggerStep->target.n = pName->n; + pTriggerStep->op = op; + } + return pTriggerStep; +} + +/* +** Build a trigger step out of an INSERT statement. Return a pointer +** to the new trigger step. +** +** The parser calls this routine when it sees an INSERT inside the +** body of a trigger. +*/ +SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep( + sqlite3 *db, /* The database connection */ + Token *pTableName, /* Name of the table into which we insert */ + IdList *pColumn, /* List of columns in pTableName to insert into */ + ExprList *pEList, /* The VALUE clause: a list of values to be inserted */ + Select *pSelect, /* A SELECT statement that supplies values */ + u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */ +){ + TriggerStep *pTriggerStep; + + assert(pEList == 0 || pSelect == 0); + assert(pEList != 0 || pSelect != 0 || db->mallocFailed); + + pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName); + if( pTriggerStep ){ + pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + pTriggerStep->pIdList = pColumn; + pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); + pTriggerStep->orconf = orconf; + }else{ + sqlite3IdListDelete(db, pColumn); + } + sqlite3ExprListDelete(db, pEList); + sqlite3SelectDelete(db, pSelect); + + return pTriggerStep; +} + +/* +** Construct a trigger step that implements an UPDATE statement and return +** a pointer to that trigger step. The parser calls this routine when it +** sees an UPDATE statement inside the body of a CREATE TRIGGER. +*/ +SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep( + sqlite3 *db, /* The database connection */ + Token *pTableName, /* Name of the table to be updated */ + ExprList *pEList, /* The SET clause: list of column and new values */ + Expr *pWhere, /* The WHERE clause */ + u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */ +){ + TriggerStep *pTriggerStep; + + pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName); + if( pTriggerStep ){ + pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); + pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + pTriggerStep->orconf = orconf; + } + sqlite3ExprListDelete(db, pEList); + sqlite3ExprDelete(db, pWhere); + return pTriggerStep; +} + +/* +** Construct a trigger step that implements a DELETE statement and return +** a pointer to that trigger step. The parser calls this routine when it +** sees a DELETE statement inside the body of a CREATE TRIGGER. +*/ +SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep( + sqlite3 *db, /* Database connection */ + Token *pTableName, /* The table from which rows are deleted */ + Expr *pWhere /* The WHERE clause */ +){ + TriggerStep *pTriggerStep; + + pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName); + if( pTriggerStep ){ + pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + pTriggerStep->orconf = OE_Default; + } + sqlite3ExprDelete(db, pWhere); + return pTriggerStep; +} + +/* +** Recursively delete a Trigger structure +*/ +SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){ + if( pTrigger==0 ) return; + sqlite3DeleteTriggerStep(db, pTrigger->step_list); + sqlite3DbFree(db, pTrigger->zName); + sqlite3DbFree(db, pTrigger->table); + sqlite3ExprDelete(db, pTrigger->pWhen); + sqlite3IdListDelete(db, pTrigger->pColumns); + sqlite3DbFree(db, pTrigger); +} + +/* +** This function is called to drop a trigger from the database schema. +** +** This may be called directly from the parser and therefore identifies +** the trigger by name. The sqlite3DropTriggerPtr() routine does the +** same job as this routine except it takes a pointer to the trigger +** instead of the trigger name. +**/ +SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){ + Trigger *pTrigger = 0; + int i; + const char *zDb; + const char *zName; + int nName; + sqlite3 *db = pParse->db; + + if( db->mallocFailed ) goto drop_trigger_cleanup; + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + goto drop_trigger_cleanup; + } + + assert( pName->nSrc==1 ); + zDb = pName->a[0].zDatabase; + zName = pName->a[0].zName; + nName = sqlite3Strlen30(zName); + assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); + for(i=OMIT_TEMPDB; inDb; i++){ + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ + if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue; + assert( sqlite3SchemaMutexHeld(db, j, 0) ); + pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName); + if( pTrigger ) break; + } + if( !pTrigger ){ + if( !noErr ){ + sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0); + }else{ + sqlite3CodeVerifyNamedSchema(pParse, zDb); + } + pParse->checkSchema = 1; + goto drop_trigger_cleanup; + } + sqlite3DropTriggerPtr(pParse, pTrigger); + +drop_trigger_cleanup: + sqlite3SrcListDelete(db, pName); +} + +/* +** Return a pointer to the Table structure for the table that a trigger +** is set on. +*/ +static Table *tableOfTrigger(Trigger *pTrigger){ + int n = sqlite3Strlen30(pTrigger->table); + return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n); +} + + +/* +** Drop a trigger given a pointer to that trigger. +*/ +SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ + Table *pTable; + Vdbe *v; + sqlite3 *db = pParse->db; + int iDb; + + iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema); + assert( iDb>=0 && iDbnDb ); + pTable = tableOfTrigger(pTrigger); + assert( pTable ); + assert( pTable->pSchema==pTrigger->pSchema || iDb==1 ); +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int code = SQLITE_DROP_TRIGGER; + const char *zDb = db->aDb[iDb].zName; + const char *zTab = SCHEMA_TABLE(iDb); + if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER; + if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) || + sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ + return; + } + } +#endif + + /* Generate code to destroy the database record of the trigger. + */ + assert( pTable!=0 ); + if( (v = sqlite3GetVdbe(pParse))!=0 ){ + int base; + static const VdbeOpList dropTrigger[] = { + { OP_Rewind, 0, ADDR(9), 0}, + { OP_String8, 0, 1, 0}, /* 1 */ + { OP_Column, 0, 1, 2}, + { OP_Ne, 2, ADDR(8), 1}, + { OP_String8, 0, 1, 0}, /* 4: "trigger" */ + { OP_Column, 0, 0, 2}, + { OP_Ne, 2, ADDR(8), 1}, + { OP_Delete, 0, 0, 0}, + { OP_Next, 0, ADDR(1), 0}, /* 8 */ + }; + + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3OpenMasterTable(pParse, iDb); + base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger); + sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT); + sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC); + sqlite3ChangeCookie(pParse, iDb); + sqlite3VdbeAddOp2(v, OP_Close, 0, 0); + sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0); + if( pParse->nMem<3 ){ + pParse->nMem = 3; + } + } +} + +/* +** Remove a trigger from the hash tables of the sqlite* pointer. +*/ +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){ + Trigger *pTrigger; + Hash *pHash; + + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pHash = &(db->aDb[iDb].pSchema->trigHash); + pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0); + if( ALWAYS(pTrigger) ){ + if( pTrigger->pSchema==pTrigger->pTabSchema ){ + Table *pTab = tableOfTrigger(pTrigger); + Trigger **pp; + for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext)); + *pp = (*pp)->pNext; + } + sqlite3DeleteTrigger(db, pTrigger); + db->flags |= SQLITE_InternChanges; + } +} + +/* +** pEList is the SET clause of an UPDATE statement. Each entry +** in pEList is of the format =. If any of the entries +** in pEList have an which matches an identifier in pIdList, +** then return TRUE. If pIdList==NULL, then it is considered a +** wildcard that matches anything. Likewise if pEList==NULL then +** it matches anything so always return true. Return false only +** if there is no match. +*/ +static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){ + int e; + if( pIdList==0 || NEVER(pEList==0) ) return 1; + for(e=0; enExpr; e++){ + if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1; + } + return 0; +} + +/* +** Return a list of all triggers on table pTab if there exists at least +** one trigger that must be fired when an operation of type 'op' is +** performed on the table, and, if that operation is an UPDATE, if at +** least one of the columns in pChanges is being modified. +*/ +SQLITE_PRIVATE Trigger *sqlite3TriggersExist( + Parse *pParse, /* Parse context */ + Table *pTab, /* The table the contains the triggers */ + int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */ + ExprList *pChanges, /* Columns that change in an UPDATE statement */ + int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ +){ + int mask = 0; + Trigger *pList = 0; + Trigger *p; + + if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){ + pList = sqlite3TriggerList(pParse, pTab); + } + assert( pList==0 || IsVirtual(pTab)==0 ); + for(p=pList; p; p=p->pNext){ + if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){ + mask |= p->tr_tm; + } + } + if( pMask ){ + *pMask = mask; + } + return (mask ? pList : 0); +} + +/* +** Convert the pStep->target token into a SrcList and return a pointer +** to that SrcList. +** +** This routine adds a specific database name, if needed, to the target when +** forming the SrcList. This prevents a trigger in one database from +** referring to a target in another database. An exception is when the +** trigger is in TEMP in which case it can refer to any other database it +** wants. +*/ +static SrcList *targetSrcList( + Parse *pParse, /* The parsing context */ + TriggerStep *pStep /* The trigger containing the target token */ +){ + int iDb; /* Index of the database to use */ + SrcList *pSrc; /* SrcList to be returned */ + + pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0); + if( pSrc ){ + assert( pSrc->nSrc>0 ); + assert( pSrc->a!=0 ); + iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema); + if( iDb==0 || iDb>=2 ){ + sqlite3 *db = pParse->db; + assert( iDbdb->nDb ); + pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName); + } + } + return pSrc; +} + +/* +** Generate VDBE code for the statements inside the body of a single +** trigger. +*/ +static int codeTriggerProgram( + Parse *pParse, /* The parser context */ + TriggerStep *pStepList, /* List of statements inside the trigger body */ + int orconf /* Conflict algorithm. (OE_Abort, etc) */ +){ + TriggerStep *pStep; + Vdbe *v = pParse->pVdbe; + sqlite3 *db = pParse->db; + + assert( pParse->pTriggerTab && pParse->pToplevel ); + assert( pStepList ); + assert( v!=0 ); + for(pStep=pStepList; pStep; pStep=pStep->pNext){ + /* Figure out the ON CONFLICT policy that will be used for this step + ** of the trigger program. If the statement that caused this trigger + ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use + ** the ON CONFLICT policy that was specified as part of the trigger + ** step statement. Example: + ** + ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN; + ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b); + ** END; + ** + ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy + ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy + */ + pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf; + + /* Clear the cookieGoto flag. When coding triggers, the cookieGoto + ** variable is used as a flag to indicate to sqlite3ExprCodeConstants() + ** that it is not safe to refactor constants (this happens after the + ** start of the first loop in the SQL statement is coded - at that + ** point code may be conditionally executed, so it is no longer safe to + ** initialize constant register values). */ + assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 ); + pParse->cookieGoto = 0; + + switch( pStep->op ){ + case TK_UPDATE: { + sqlite3Update(pParse, + targetSrcList(pParse, pStep), + sqlite3ExprListDup(db, pStep->pExprList, 0), + sqlite3ExprDup(db, pStep->pWhere, 0), + pParse->eOrconf + ); + break; + } + case TK_INSERT: { + sqlite3Insert(pParse, + targetSrcList(pParse, pStep), + sqlite3ExprListDup(db, pStep->pExprList, 0), + sqlite3SelectDup(db, pStep->pSelect, 0), + sqlite3IdListDup(db, pStep->pIdList), + pParse->eOrconf + ); + break; + } + case TK_DELETE: { + sqlite3DeleteFrom(pParse, + targetSrcList(pParse, pStep), + sqlite3ExprDup(db, pStep->pWhere, 0) + ); + break; + } + default: assert( pStep->op==TK_SELECT ); { + SelectDest sDest; + Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0); + sqlite3SelectDestInit(&sDest, SRT_Discard, 0); + sqlite3Select(pParse, pSelect, &sDest); + sqlite3SelectDelete(db, pSelect); + break; + } + } + if( pStep->op!=TK_SELECT ){ + sqlite3VdbeAddOp0(v, OP_ResetCount); + } + } + + return 0; +} + +#ifdef SQLITE_DEBUG +/* +** This function is used to add VdbeComment() annotations to a VDBE +** program. It is not used in production code, only for debugging. +*/ +static const char *onErrorText(int onError){ + switch( onError ){ + case OE_Abort: return "abort"; + case OE_Rollback: return "rollback"; + case OE_Fail: return "fail"; + case OE_Replace: return "replace"; + case OE_Ignore: return "ignore"; + case OE_Default: return "default"; + } + return "n/a"; +} +#endif + +/* +** Parse context structure pFrom has just been used to create a sub-vdbe +** (trigger program). If an error has occurred, transfer error information +** from pFrom to pTo. +*/ +static void transferParseError(Parse *pTo, Parse *pFrom){ + assert( pFrom->zErrMsg==0 || pFrom->nErr ); + assert( pTo->zErrMsg==0 || pTo->nErr ); + if( pTo->nErr==0 ){ + pTo->zErrMsg = pFrom->zErrMsg; + pTo->nErr = pFrom->nErr; + }else{ + sqlite3DbFree(pFrom->db, pFrom->zErrMsg); + } +} + +/* +** Create and populate a new TriggerPrg object with a sub-program +** implementing trigger pTrigger with ON CONFLICT policy orconf. +*/ +static TriggerPrg *codeRowTrigger( + Parse *pParse, /* Current parse context */ + Trigger *pTrigger, /* Trigger to code */ + Table *pTab, /* The table pTrigger is attached to */ + int orconf /* ON CONFLICT policy to code trigger program with */ +){ + Parse *pTop = sqlite3ParseToplevel(pParse); + sqlite3 *db = pParse->db; /* Database handle */ + TriggerPrg *pPrg; /* Value to return */ + Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */ + Vdbe *v; /* Temporary VM */ + NameContext sNC; /* Name context for sub-vdbe */ + SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */ + Parse *pSubParse; /* Parse context for sub-vdbe */ + int iEndTrigger = 0; /* Label to jump to if WHEN is false */ + + assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); + assert( pTop->pVdbe ); + + /* Allocate the TriggerPrg and SubProgram objects. To ensure that they + ** are freed if an error occurs, link them into the Parse.pTriggerPrg + ** list of the top-level Parse object sooner rather than later. */ + pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg)); + if( !pPrg ) return 0; + pPrg->pNext = pTop->pTriggerPrg; + pTop->pTriggerPrg = pPrg; + pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram)); + if( !pProgram ) return 0; + sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram); + pPrg->pTrigger = pTrigger; + pPrg->orconf = orconf; + pPrg->aColmask[0] = 0xffffffff; + pPrg->aColmask[1] = 0xffffffff; + + /* Allocate and populate a new Parse context to use for coding the + ** trigger sub-program. */ + pSubParse = sqlite3StackAllocZero(db, sizeof(Parse)); + if( !pSubParse ) return 0; + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pSubParse; + pSubParse->db = db; + pSubParse->pTriggerTab = pTab; + pSubParse->pToplevel = pTop; + pSubParse->zAuthContext = pTrigger->zName; + pSubParse->eTriggerOp = pTrigger->op; + pSubParse->nQueryLoop = pParse->nQueryLoop; + + v = sqlite3GetVdbe(pSubParse); + if( v ){ + VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", + pTrigger->zName, onErrorText(orconf), + (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"), + (pTrigger->op==TK_UPDATE ? "UPDATE" : ""), + (pTrigger->op==TK_INSERT ? "INSERT" : ""), + (pTrigger->op==TK_DELETE ? "DELETE" : ""), + pTab->zName + )); +#ifndef SQLITE_OMIT_TRACE + sqlite3VdbeChangeP4(v, -1, + sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC + ); +#endif + + /* If one was specified, code the WHEN clause. If it evaluates to false + ** (or NULL) the sub-vdbe is immediately halted by jumping to the + ** OP_Halt inserted at the end of the program. */ + if( pTrigger->pWhen ){ + pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0); + if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) + && db->mallocFailed==0 + ){ + iEndTrigger = sqlite3VdbeMakeLabel(v); + sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL); + } + sqlite3ExprDelete(db, pWhen); + } + + /* Code the trigger program into the sub-vdbe. */ + codeTriggerProgram(pSubParse, pTrigger->step_list, orconf); + + /* Insert an OP_Halt at the end of the sub-program. */ + if( iEndTrigger ){ + sqlite3VdbeResolveLabel(v, iEndTrigger); + } + sqlite3VdbeAddOp0(v, OP_Halt); + VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf))); + + transferParseError(pParse, pSubParse); + if( db->mallocFailed==0 ){ + pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg); + } + pProgram->nMem = pSubParse->nMem; + pProgram->nCsr = pSubParse->nTab; + pProgram->nOnce = pSubParse->nOnce; + pProgram->token = (void *)pTrigger; + pPrg->aColmask[0] = pSubParse->oldmask; + pPrg->aColmask[1] = pSubParse->newmask; + sqlite3VdbeDelete(v); + } + + assert( !pSubParse->pAinc && !pSubParse->pZombieTab ); + assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg ); + sqlite3StackFree(db, pSubParse); + + return pPrg; +} + +/* +** Return a pointer to a TriggerPrg object containing the sub-program for +** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such +** TriggerPrg object exists, a new object is allocated and populated before +** being returned. +*/ +static TriggerPrg *getRowTrigger( + Parse *pParse, /* Current parse context */ + Trigger *pTrigger, /* Trigger to code */ + Table *pTab, /* The table trigger pTrigger is attached to */ + int orconf /* ON CONFLICT algorithm. */ +){ + Parse *pRoot = sqlite3ParseToplevel(pParse); + TriggerPrg *pPrg; + + assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); + + /* It may be that this trigger has already been coded (or is in the + ** process of being coded). If this is the case, then an entry with + ** a matching TriggerPrg.pTrigger field will be present somewhere + ** in the Parse.pTriggerPrg list. Search for such an entry. */ + for(pPrg=pRoot->pTriggerPrg; + pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); + pPrg=pPrg->pNext + ); + + /* If an existing TriggerPrg could not be located, create a new one. */ + if( !pPrg ){ + pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf); + } + + return pPrg; +} + +/* +** Generate code for the trigger program associated with trigger p on +** table pTab. The reg, orconf and ignoreJump parameters passed to this +** function are the same as those described in the header function for +** sqlite3CodeRowTrigger() +*/ +SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( + Parse *pParse, /* Parse context */ + Trigger *p, /* Trigger to code */ + Table *pTab, /* The table to code triggers from */ + int reg, /* Reg array containing OLD.* and NEW.* values */ + int orconf, /* ON CONFLICT policy */ + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ +){ + Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */ + TriggerPrg *pPrg; + pPrg = getRowTrigger(pParse, p, pTab, orconf); + assert( pPrg || pParse->nErr || pParse->db->mallocFailed ); + + /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program + ** is a pointer to the sub-vdbe containing the trigger program. */ + if( pPrg ){ + int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers)); + + sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem); + sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM); + VdbeComment( + (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf))); + + /* Set the P5 operand of the OP_Program instruction to non-zero if + ** recursive invocation of this trigger program is disallowed. Recursive + ** invocation is disallowed if (a) the sub-program is really a trigger, + ** not a foreign key action, and (b) the flag to enable recursive triggers + ** is clear. */ + sqlite3VdbeChangeP5(v, (u8)bRecursive); + } +} + +/* +** This is called to code the required FOR EACH ROW triggers for an operation +** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE) +** is given by the op parameter. The tr_tm parameter determines whether the +** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then +** parameter pChanges is passed the list of columns being modified. +** +** If there are no triggers that fire at the specified time for the specified +** operation on pTab, this function is a no-op. +** +** The reg argument is the address of the first in an array of registers +** that contain the values substituted for the new.* and old.* references +** in the trigger program. If N is the number of columns in table pTab +** (a copy of pTab->nCol), then registers are populated as follows: +** +** Register Contains +** ------------------------------------------------------ +** reg+0 OLD.rowid +** reg+1 OLD.* value of left-most column of pTab +** ... ... +** reg+N OLD.* value of right-most column of pTab +** reg+N+1 NEW.rowid +** reg+N+2 OLD.* value of left-most column of pTab +** ... ... +** reg+N+N+1 NEW.* value of right-most column of pTab +** +** For ON DELETE triggers, the registers containing the NEW.* values will +** never be accessed by the trigger program, so they are not allocated or +** populated by the caller (there is no data to populate them with anyway). +** Similarly, for ON INSERT triggers the values stored in the OLD.* registers +** are never accessed, and so are not allocated by the caller. So, for an +** ON INSERT trigger, the value passed to this function as parameter reg +** is not a readable register, although registers (reg+N) through +** (reg+N+N+1) are. +** +** Parameter orconf is the default conflict resolution algorithm for the +** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump +** is the instruction that control should jump to if a trigger program +** raises an IGNORE exception. +*/ +SQLITE_PRIVATE void sqlite3CodeRowTrigger( + Parse *pParse, /* Parse context */ + Trigger *pTrigger, /* List of triggers on table pTab */ + int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */ + ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ + int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ + Table *pTab, /* The table to code triggers from */ + int reg, /* The first in an array of registers (see above) */ + int orconf, /* ON CONFLICT policy */ + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ +){ + Trigger *p; /* Used to iterate through pTrigger list */ + + assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE ); + assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER ); + assert( (op==TK_UPDATE)==(pChanges!=0) ); + + for(p=pTrigger; p; p=p->pNext){ + + /* Sanity checking: The schema for the trigger and for the table are + ** always defined. The trigger must be in the same schema as the table + ** or else it must be a TEMP trigger. */ + assert( p->pSchema!=0 ); + assert( p->pTabSchema!=0 ); + assert( p->pSchema==p->pTabSchema + || p->pSchema==pParse->db->aDb[1].pSchema ); + + /* Determine whether we should code this trigger */ + if( p->op==op + && p->tr_tm==tr_tm + && checkColumnOverlap(p->pColumns, pChanges) + ){ + sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump); + } + } +} + +/* +** Triggers may access values stored in the old.* or new.* pseudo-table. +** This function returns a 32-bit bitmask indicating which columns of the +** old.* or new.* tables actually are used by triggers. This information +** may be used by the caller, for example, to avoid having to load the entire +** old.* record into memory when executing an UPDATE or DELETE command. +** +** Bit 0 of the returned mask is set if the left-most column of the +** table may be accessed using an [old|new].reference. Bit 1 is set if +** the second leftmost column value is required, and so on. If there +** are more than 32 columns in the table, and at least one of the columns +** with an index greater than 32 may be accessed, 0xffffffff is returned. +** +** It is not possible to determine if the old.rowid or new.rowid column is +** accessed by triggers. The caller must always assume that it is. +** +** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned +** applies to the old.* table. If 1, the new.* table. +** +** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE +** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only +** included in the returned mask if the TRIGGER_BEFORE bit is set in the +** tr_tm parameter. Similarly, values accessed by AFTER triggers are only +** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm. +*/ +SQLITE_PRIVATE u32 sqlite3TriggerColmask( + Parse *pParse, /* Parse context */ + Trigger *pTrigger, /* List of triggers on table pTab */ + ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ + int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */ + int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ + Table *pTab, /* The table to code triggers from */ + int orconf /* Default ON CONFLICT policy for trigger steps */ +){ + const int op = pChanges ? TK_UPDATE : TK_DELETE; + u32 mask = 0; + Trigger *p; + + assert( isNew==1 || isNew==0 ); + for(p=pTrigger; p; p=p->pNext){ + if( p->op==op && (tr_tm&p->tr_tm) + && checkColumnOverlap(p->pColumns,pChanges) + ){ + TriggerPrg *pPrg; + pPrg = getRowTrigger(pParse, p, pTab, orconf); + if( pPrg ){ + mask |= pPrg->aColmask[isNew]; + } + } + } + + return mask; +} + +#endif /* !defined(SQLITE_OMIT_TRIGGER) */ + +/************** End of trigger.c *********************************************/ +/************** Begin file update.c ******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that are called by the parser +** to handle UPDATE statements. +*/ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Forward declaration */ +static void updateVirtualTable( + Parse *pParse, /* The parsing context */ + SrcList *pSrc, /* The virtual table to be modified */ + Table *pTab, /* The virtual table */ + ExprList *pChanges, /* The columns to change in the UPDATE statement */ + Expr *pRowidExpr, /* Expression used to recompute the rowid */ + int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ + Expr *pWhere, /* WHERE clause of the UPDATE statement */ + int onError /* ON CONFLICT strategy */ +); +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** The most recently coded instruction was an OP_Column to retrieve the +** i-th column of table pTab. This routine sets the P4 parameter of the +** OP_Column to the default value, if any. +** +** The default value of a column is specified by a DEFAULT clause in the +** column definition. This was either supplied by the user when the table +** was created, or added later to the table definition by an ALTER TABLE +** command. If the latter, then the row-records in the table btree on disk +** may not contain a value for the column and the default value, taken +** from the P4 parameter of the OP_Column instruction, is returned instead. +** If the former, then all row-records are guaranteed to include a value +** for the column and the P4 value is not required. +** +** Column definitions created by an ALTER TABLE command may only have +** literal default values specified: a number, null or a string. (If a more +** complicated default expression value was provided, it is evaluated +** when the ALTER TABLE is executed and one of the literal values written +** into the sqlite_master table.) +** +** Therefore, the P4 parameter is only required if the default value for +** the column is a literal number, string or null. The sqlite3ValueFromExpr() +** function is capable of transforming these types of expressions into +** sqlite3_value objects. +** +** If parameter iReg is not negative, code an OP_RealAffinity instruction +** on register iReg. This is used when an equivalent integer value is +** stored in place of an 8-byte floating point value in order to save +** space. +*/ +SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ + assert( pTab!=0 ); + if( !pTab->pSelect ){ + sqlite3_value *pValue = 0; + u8 enc = ENC(sqlite3VdbeDb(v)); + Column *pCol = &pTab->aCol[i]; + VdbeComment((v, "%s.%s", pTab->zName, pCol->zName)); + assert( inCol ); + sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, + pCol->affinity, &pValue); + if( pValue ){ + sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM); + } +#ifndef SQLITE_OMIT_FLOATING_POINT + if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){ + sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); + } +#endif + } +} + +/* +** Process an UPDATE statement. +** +** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL; +** \_______/ \________/ \______/ \________________/ +* onError pTabList pChanges pWhere +*/ +SQLITE_PRIVATE void sqlite3Update( + Parse *pParse, /* The parser context */ + SrcList *pTabList, /* The table in which we should change things */ + ExprList *pChanges, /* Things to be changed */ + Expr *pWhere, /* The WHERE clause. May be null */ + int onError /* How to handle constraint errors */ +){ + int i, j; /* Loop counters */ + Table *pTab; /* The table to be updated */ + int addr = 0; /* VDBE instruction address of the start of the loop */ + WhereInfo *pWInfo; /* Information about the WHERE clause */ + Vdbe *v; /* The virtual database engine */ + Index *pIdx; /* For looping over indices */ + int nIdx; /* Number of indices that need updating */ + int iCur; /* VDBE Cursor number of pTab */ + sqlite3 *db; /* The database structure */ + int *aRegIdx = 0; /* One register assigned to each index to be updated */ + int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the + ** an expression for the i-th column of the table. + ** aXRef[i]==-1 if the i-th column is not changed. */ + int chngRowid; /* True if the record number is being changed */ + Expr *pRowidExpr = 0; /* Expression defining the new record number */ + int openAll = 0; /* True if all indices need to be opened */ + AuthContext sContext; /* The authorization context */ + NameContext sNC; /* The name-context to resolve expressions in */ + int iDb; /* Database containing the table being updated */ + int okOnePass; /* True for one-pass algorithm without the FIFO */ + int hasFK; /* True if foreign key processing is required */ + +#ifndef SQLITE_OMIT_TRIGGER + int isView; /* True when updating a view (INSTEAD OF trigger) */ + Trigger *pTrigger; /* List of triggers on pTab, if required */ + int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ +#endif + int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */ + + /* Register Allocations */ + int regRowCount = 0; /* A count of rows changed */ + int regOldRowid; /* The old rowid */ + int regNewRowid; /* The new rowid */ + int regNew; /* Content of the NEW.* table in triggers */ + int regOld = 0; /* Content of OLD.* table in triggers */ + int regRowSet = 0; /* Rowset of rows to be updated */ + + memset(&sContext, 0, sizeof(sContext)); + db = pParse->db; + if( pParse->nErr || db->mallocFailed ){ + goto update_cleanup; + } + assert( pTabList->nSrc==1 ); + + /* Locate the table which we want to update. + */ + pTab = sqlite3SrcListLookup(pParse, pTabList); + if( pTab==0 ) goto update_cleanup; + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + + /* Figure out if we have any triggers and if the table being + ** updated is a view. + */ +#ifndef SQLITE_OMIT_TRIGGER + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask); + isView = pTab->pSelect!=0; + assert( pTrigger || tmask==0 ); +#else +# define pTrigger 0 +# define isView 0 +# define tmask 0 +#endif +#ifdef SQLITE_OMIT_VIEW +# undef isView +# define isView 0 +#endif + + if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto update_cleanup; + } + if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ + goto update_cleanup; + } + aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol ); + if( aXRef==0 ) goto update_cleanup; + for(i=0; inCol; i++) aXRef[i] = -1; + + /* Allocate a cursors for the main database table and for all indices. + ** The index cursors might not be used, but if they are used they + ** need to occur right after the database cursor. So go ahead and + ** allocate enough space, just in case. + */ + pTabList->a[0].iCursor = iCur = pParse->nTab++; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + pParse->nTab++; + } + + /* Initialize the name-context */ + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + + /* Resolve the column names in all the expressions of the + ** of the UPDATE statement. Also find the column index + ** for each column to be updated in the pChanges array. For each + ** column to be updated, make sure we have authorization to change + ** that column. + */ + chngRowid = 0; + for(i=0; inExpr; i++){ + if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ + goto update_cleanup; + } + for(j=0; jnCol; j++){ + if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){ + if( j==pTab->iPKey ){ + chngRowid = 1; + pRowidExpr = pChanges->a[i].pExpr; + } + aXRef[j] = i; + break; + } + } + if( j>=pTab->nCol ){ + if( sqlite3IsRowid(pChanges->a[i].zName) ){ + j = -1; + chngRowid = 1; + pRowidExpr = pChanges->a[i].pExpr; + }else{ + sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName); + pParse->checkSchema = 1; + goto update_cleanup; + } + } +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int rc; + rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName, + j<0 ? "ROWID" : pTab->aCol[j].zName, + db->aDb[iDb].zName); + if( rc==SQLITE_DENY ){ + goto update_cleanup; + }else if( rc==SQLITE_IGNORE ){ + aXRef[j] = -1; + } + } +#endif + } + + hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid); + + /* Allocate memory for the array aRegIdx[]. There is one entry in the + ** array for each index associated with table being updated. Fill in + ** the value with a register number for indices that are to be used + ** and with zero for unused indices. + */ + for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} + if( nIdx>0 ){ + aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx ); + if( aRegIdx==0 ) goto update_cleanup; + } + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + int reg; + if( hasFK || chngRowid || pIdx->pPartIdxWhere ){ + reg = ++pParse->nMem; + }else{ + reg = 0; + for(i=0; inColumn; i++){ + if( aXRef[pIdx->aiColumn[i]]>=0 ){ + reg = ++pParse->nMem; + break; + } + } + } + aRegIdx[j] = reg; + } + + /* Begin generating code. */ + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto update_cleanup; + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); + sqlite3BeginWriteOperation(pParse, 1, iDb); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + /* Virtual tables must be handled separately */ + if( IsVirtual(pTab) ){ + updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef, + pWhere, onError); + pWhere = 0; + pTabList = 0; + goto update_cleanup; + } +#endif + + /* Allocate required registers. */ + regRowSet = ++pParse->nMem; + regOldRowid = regNewRowid = ++pParse->nMem; + if( pTrigger || hasFK ){ + regOld = pParse->nMem + 1; + pParse->nMem += pTab->nCol; + } + if( chngRowid || pTrigger || hasFK ){ + regNewRowid = ++pParse->nMem; + } + regNew = pParse->nMem + 1; + pParse->nMem += pTab->nCol; + + /* Start the view context. */ + if( isView ){ + sqlite3AuthContextPush(pParse, &sContext, pTab->zName); + } + + /* If we are trying to update a view, realize that view into + ** a ephemeral table. + */ +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) + if( isView ){ + sqlite3MaterializeView(pParse, pTab, pWhere, iCur); + } +#endif + + /* Resolve the column names in all the expressions in the + ** WHERE clause. + */ + if( sqlite3ResolveExprNames(&sNC, pWhere) ){ + goto update_cleanup; + } + + /* Begin the database scan + */ + sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); + pWInfo = sqlite3WhereBegin( + pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0 + ); + if( pWInfo==0 ) goto update_cleanup; + okOnePass = sqlite3WhereOkOnePass(pWInfo); + + /* Remember the rowid of every item to be updated. + */ + sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid); + if( !okOnePass ){ + sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); + } + + /* End the database scan loop. + */ + sqlite3WhereEnd(pWInfo); + + /* Initialize the count of updated rows + */ + if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){ + regRowCount = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); + } + + if( !isView ){ + /* + ** Open every index that needs updating. Note that if any + ** index could potentially invoke a REPLACE conflict resolution + ** action, then we need to open all indices because we might need + ** to be deleting some records. + */ + if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); + if( onError==OE_Replace ){ + openAll = 1; + }else{ + openAll = 0; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->onError==OE_Replace ){ + openAll = 1; + break; + } + } + } + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + assert( aRegIdx ); + if( openAll || aRegIdx[i]>0 ){ + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb, + (char*)pKey, P4_KEYINFO_HANDOFF); + assert( pParse->nTab>iCur+i+1 ); + } + } + } + + /* Top of the update loop */ + if( okOnePass ){ + int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid); + addr = sqlite3VdbeAddOp0(v, OP_Goto); + sqlite3VdbeJumpHere(v, a1); + }else{ + addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid); + } + + /* Make cursor iCur point to the record that is being updated. If + ** this record does not exist for some reason (deleted by a trigger, + ** for example, then jump to the next iteration of the RowSet loop. */ + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); + + /* If the record number will change, set register regNewRowid to + ** contain the new value. If the record number is not being modified, + ** then regNewRowid is the same register as regOldRowid, which is + ** already populated. */ + assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid ); + if( chngRowid ){ + sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); + sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); + } + + /* If there are triggers on this table, populate an array of registers + ** with the required old.* column data. */ + if( hasFK || pTrigger ){ + u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0); + oldmask |= sqlite3TriggerColmask(pParse, + pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError + ); + for(i=0; inCol; i++){ + if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<nCol-1); + for(i=0; inCol; i++){ + if( i==pTab->iPKey ){ + /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/ + }else{ + j = aXRef[i]; + if( j>=0 ){ + sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i); + }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<nCol); + sqlite3TableAffinityStr(v, pTab); + sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, + TRIGGER_BEFORE, pTab, regOldRowid, onError, addr); + + /* The row-trigger may have deleted the row being updated. In this + ** case, jump to the next row. No updates or AFTER triggers are + ** required. This behavior - what happens when the row being updated + ** is deleted or renamed by a BEFORE trigger - is left undefined in the + ** documentation. + */ + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); + + /* If it did not delete it, the row-trigger may still have modified + ** some of the columns of the row being updated. Load the values for + ** all columns not modified by the update statement into their + ** registers in case this has happened. + */ + for(i=0; inCol; i++){ + if( aXRef[i]<0 && i!=pTab->iPKey ){ + sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i); + sqlite3ColumnDefault(v, pTab, i, regNew+i); + } + } + } + + if( !isView ){ + int j1; /* Address of jump instruction */ + + /* Do constraint checks. */ + sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid, + aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0); + + /* Do FK constraint checks. */ + if( hasFK ){ + sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid); + } + + /* Delete the index entries associated with the current record. */ + j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid); + sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx); + + /* If changing the record number, delete the old record. */ + if( hasFK || chngRowid ){ + sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0); + } + sqlite3VdbeJumpHere(v, j1); + + if( hasFK ){ + sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid); + } + + /* Insert the new index entries and the new record. */ + sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0); + + /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to + ** handle rows (possibly in other tables) that refer via a foreign key + ** to the row just updated. */ + if( hasFK ){ + sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid); + } + } + + /* Increment the row counter + */ + if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){ + sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); + } + + sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, + TRIGGER_AFTER, pTab, regOldRowid, onError, addr); + + /* Repeat the above with the next record to be updated, until + ** all record selected by the WHERE clause have been updated. + */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); + sqlite3VdbeJumpHere(v, addr); + + /* Close all tables */ + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + assert( aRegIdx ); + if( openAll || aRegIdx[i]>0 ){ + sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0); + } + } + sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); + + /* Update the sqlite_sequence table by storing the content of the + ** maximum rowid counter values recorded while inserting into + ** autoincrement tables. + */ + if( pParse->nested==0 && pParse->pTriggerTab==0 ){ + sqlite3AutoincrementEnd(pParse); + } + + /* + ** Return the number of rows that were changed. If this routine is + ** generating code because of a call to sqlite3NestedParse(), do not + ** invoke the callback function. + */ + if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){ + sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC); + } + +update_cleanup: + sqlite3AuthContextPop(&sContext); + sqlite3DbFree(db, aRegIdx); + sqlite3DbFree(db, aXRef); + sqlite3SrcListDelete(db, pTabList); + sqlite3ExprListDelete(db, pChanges); + sqlite3ExprDelete(db, pWhere); + return; +} +/* Make sure "isView" and other macros defined above are undefined. Otherwise +** thely may interfere with compilation of other functions in this file +** (or in another file, if this file becomes part of the amalgamation). */ +#ifdef isView + #undef isView +#endif +#ifdef pTrigger + #undef pTrigger +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Generate code for an UPDATE of a virtual table. +** +** The strategy is that we create an ephemerial table that contains +** for each row to be changed: +** +** (A) The original rowid of that row. +** (B) The revised rowid for the row. (note1) +** (C) The content of every column in the row. +** +** Then we loop over this ephemeral table and for each row in +** the ephermeral table call VUpdate. +** +** When finished, drop the ephemeral table. +** +** (note1) Actually, if we know in advance that (A) is always the same +** as (B) we only store (A), then duplicate (A) when pulling +** it out of the ephemeral table before calling VUpdate. +*/ +static void updateVirtualTable( + Parse *pParse, /* The parsing context */ + SrcList *pSrc, /* The virtual table to be modified */ + Table *pTab, /* The virtual table */ + ExprList *pChanges, /* The columns to change in the UPDATE statement */ + Expr *pRowid, /* Expression used to recompute the rowid */ + int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ + Expr *pWhere, /* WHERE clause of the UPDATE statement */ + int onError /* ON CONFLICT strategy */ +){ + Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */ + ExprList *pEList = 0; /* The result set of the SELECT statement */ + Select *pSelect = 0; /* The SELECT statement */ + Expr *pExpr; /* Temporary expression */ + int ephemTab; /* Table holding the result of the SELECT */ + int i; /* Loop counter */ + int addr; /* Address of top of loop */ + int iReg; /* First register in set passed to OP_VUpdate */ + sqlite3 *db = pParse->db; /* Database connection */ + const char *pVTab = (const char*)sqlite3GetVTable(db, pTab); + SelectDest dest; + + /* Construct the SELECT statement that will find the new values for + ** all updated rows. + */ + pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_")); + if( pRowid ){ + pEList = sqlite3ExprListAppend(pParse, pEList, + sqlite3ExprDup(db, pRowid, 0)); + } + assert( pTab->iPKey<0 ); + for(i=0; inCol; i++){ + if( aXRef[i]>=0 ){ + pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0); + }else{ + pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName); + } + pEList = sqlite3ExprListAppend(pParse, pEList, pExpr); + } + pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0); + + /* Create the ephemeral table into which the update results will + ** be stored. + */ + assert( v ); + ephemTab = pParse->nTab++; + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0)); + sqlite3VdbeChangeP5(v, BTREE_UNORDERED); + + /* fill the ephemeral table + */ + sqlite3SelectDestInit(&dest, SRT_Table, ephemTab); + sqlite3Select(pParse, pSelect, &dest); + + /* Generate code to scan the ephemeral table and call VUpdate. */ + iReg = ++pParse->nMem; + pParse->nMem += pTab->nCol+1; + addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg); + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1); + for(i=0; inCol; i++){ + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i); + } + sqlite3VtabMakeWritable(pParse, pTab); + sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB); + sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); + sqlite3MayAbort(pParse); + sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); + sqlite3VdbeJumpHere(v, addr); + sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0); + + /* Cleanup */ + sqlite3SelectDelete(db, pSelect); +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/************** End of update.c **********************************************/ +/************** Begin file vacuum.c ******************************************/ +/* +** 2003 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the VACUUM command. +** +** Most of the code in this file may be omitted by defining the +** SQLITE_OMIT_VACUUM macro. +*/ + +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) +/* +** Finalize a prepared statement. If there was an error, store the +** text of the error message in *pzErrMsg. Return the result code. +*/ +static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){ + int rc; + rc = sqlite3VdbeFinalize((Vdbe*)pStmt); + if( rc ){ + sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); + } + return rc; +} + +/* +** Execute zSql on database db. Return an error code. +*/ +static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ + sqlite3_stmt *pStmt; + VVA_ONLY( int rc; ) + if( !zSql ){ + return SQLITE_NOMEM; + } + if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ + sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); + return sqlite3_errcode(db); + } + VVA_ONLY( rc = ) sqlite3_step(pStmt); + assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) ); + return vacuumFinalize(db, pStmt, pzErrMsg); +} + +/* +** Execute zSql on database db. The statement returns exactly +** one column. Execute this as SQL on the same database. +*/ +static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ + sqlite3_stmt *pStmt; + int rc; + + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0)); + if( rc!=SQLITE_OK ){ + vacuumFinalize(db, pStmt, pzErrMsg); + return rc; + } + } + + return vacuumFinalize(db, pStmt, pzErrMsg); +} + +/* +** The VACUUM command is used to clean up the database, +** collapse free space, etc. It is modelled after the VACUUM command +** in PostgreSQL. The VACUUM command works as follows: +** +** (1) Create a new transient database file +** (2) Copy all content from the database being vacuumed into +** the new transient database file +** (3) Copy content from the transient database back into the +** original database. +** +** The transient database requires temporary disk space approximately +** equal to the size of the original database. The copy operation of +** step (3) requires additional temporary disk space approximately equal +** to the size of the original database for the rollback journal. +** Hence, temporary disk space that is approximately 2x the size of the +** orginal database is required. Every page of the database is written +** approximately 3 times: Once for step (2) and twice for step (3). +** Two writes per page are required in step (3) because the original +** database content must be written into the rollback journal prior to +** overwriting the database with the vacuumed content. +** +** Only 1x temporary space and only 1x writes would be required if +** the copy of step (3) were replace by deleting the original database +** and renaming the transient database as the original. But that will +** not work if other processes are attached to the original database. +** And a power loss in between deleting the original and renaming the +** transient would cause the database file to appear to be deleted +** following reboot. +*/ +SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){ + Vdbe *v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0); + sqlite3VdbeUsesBtree(v, 0); + } + return; +} + +/* +** This routine implements the OP_Vacuum opcode of the VDBE. +*/ +SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){ + int rc = SQLITE_OK; /* Return code from service routines */ + Btree *pMain; /* The database being vacuumed */ + Btree *pTemp; /* The temporary database we vacuum into */ + char *zSql = 0; /* SQL statements */ + int saved_flags; /* Saved value of the db->flags */ + int saved_nChange; /* Saved value of db->nChange */ + int saved_nTotalChange; /* Saved value of db->nTotalChange */ + void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */ + Db *pDb = 0; /* Database to detach at end of vacuum */ + int isMemDb; /* True if vacuuming a :memory: database */ + int nRes; /* Bytes of reserved space at the end of each page */ + int nDb; /* Number of attached databases */ + + if( !db->autoCommit ){ + sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); + return SQLITE_ERROR; + } + if( db->nVdbeActive>1 ){ + sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress"); + return SQLITE_ERROR; + } + + /* Save the current value of the database flags so that it can be + ** restored before returning. Then set the writable-schema flag, and + ** disable CHECK and foreign key constraints. */ + saved_flags = db->flags; + saved_nChange = db->nChange; + saved_nTotalChange = db->nTotalChange; + saved_xTrace = db->xTrace; + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin; + db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder); + db->xTrace = 0; + + pMain = db->aDb[0].pBt; + isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain)); + + /* Attach the temporary database as 'vacuum_db'. The synchronous pragma + ** can be set to 'off' for this file, as it is not recovered if a crash + ** occurs anyway. The integrity of the database is maintained by a + ** (possibly synchronous) transaction opened on the main database before + ** sqlite3BtreeCopyFile() is called. + ** + ** An optimisation would be to use a non-journaled pager. + ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but + ** that actually made the VACUUM run slower. Very little journalling + ** actually occurs when doing a vacuum since the vacuum_db is initially + ** empty. Only the journal header is written. Apparently it takes more + ** time to parse and run the PRAGMA to turn journalling off than it does + ** to write the journal header file. + */ + nDb = db->nDb; + if( sqlite3TempInMemory(db) ){ + zSql = "ATTACH ':memory:' AS vacuum_db;"; + }else{ + zSql = "ATTACH '' AS vacuum_db;"; + } + rc = execSql(db, pzErrMsg, zSql); + if( db->nDb>nDb ){ + pDb = &db->aDb[db->nDb-1]; + assert( strcmp(pDb->zName,"vacuum_db")==0 ); + } + if( rc!=SQLITE_OK ) goto end_of_vacuum; + pTemp = db->aDb[db->nDb-1].pBt; + + /* The call to execSql() to attach the temp database has left the file + ** locked (as there was more than one active statement when the transaction + ** to read the schema was concluded. Unlock it here so that this doesn't + ** cause problems for the call to BtreeSetPageSize() below. */ + sqlite3BtreeCommit(pTemp); + + nRes = sqlite3BtreeGetReserve(pMain); + + /* A VACUUM cannot change the pagesize of an encrypted database. */ +#ifdef SQLITE_HAS_CODEC + if( db->nextPagesize ){ + extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); + int nKey; + char *zKey; + sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); + if( nKey ) db->nextPagesize = 0; + } +#endif + + rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Begin a transaction and take an exclusive lock on the main database + ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below, + ** to ensure that we do not try to change the page-size on a WAL database. + */ + rc = execSql(db, pzErrMsg, "BEGIN;"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = sqlite3BtreeBeginTrans(pMain, 2); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Do not attempt to change the page size for a WAL database */ + if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain)) + ==PAGER_JOURNALMODE_WAL ){ + db->nextPagesize = 0; + } + + if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0) + || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0)) + || NEVER(db->mallocFailed) + ){ + rc = SQLITE_NOMEM; + goto end_of_vacuum; + } + +#ifndef SQLITE_OMIT_AUTOVACUUM + sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : + sqlite3BtreeGetAutoVacuum(pMain)); +#endif + + /* Query the schema of the main database. Create a mirror schema + ** in the temporary database. + */ + rc = execExecSql(db, pzErrMsg, + "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) " + " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" + " AND rootpage>0" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, pzErrMsg, + "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)" + " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' "); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, pzErrMsg, + "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) " + " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Loop through the tables in the main database. For each, do + ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy + ** the contents to the temporary database. + */ + rc = execExecSql(db, pzErrMsg, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM main.' || quote(name) || ';'" + "FROM main.sqlite_master " + "WHERE type = 'table' AND name!='sqlite_sequence' " + " AND rootpage>0" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Copy over the sequence table + */ + rc = execExecSql(db, pzErrMsg, + "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' " + "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' " + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, pzErrMsg, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM main.' || quote(name) || ';' " + "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + + /* Copy the triggers, views, and virtual tables from the main database + ** over to the temporary database. None of these objects has any + ** associated storage, so all we have to do is copy their entries + ** from the SQLITE_MASTER table. + */ + rc = execSql(db, pzErrMsg, + "INSERT INTO vacuum_db.sqlite_master " + " SELECT type, name, tbl_name, rootpage, sql" + " FROM main.sqlite_master" + " WHERE type='view' OR type='trigger'" + " OR (type='table' AND rootpage=0)" + ); + if( rc ) goto end_of_vacuum; + + /* At this point, there is a write transaction open on both the + ** vacuum database and the main database. Assuming no error occurs, + ** both transactions are closed by this block - the main database + ** transaction by sqlite3BtreeCopyFile() and the other by an explicit + ** call to sqlite3BtreeCommit(). + */ + { + u32 meta; + int i; + + /* This array determines which meta meta values are preserved in the + ** vacuum. Even entries are the meta value number and odd entries + ** are an increment to apply to the meta value after the vacuum. + ** The increment is used to increase the schema cookie so that other + ** connections to the same database will know to reread the schema. + */ + static const unsigned char aCopy[] = { + BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */ + BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */ + BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */ + BTREE_USER_VERSION, 0, /* Preserve the user version */ + BTREE_APPLICATION_ID, 0, /* Preserve the application id */ + }; + + assert( 1==sqlite3BtreeIsInTrans(pTemp) ); + assert( 1==sqlite3BtreeIsInTrans(pMain) ); + + /* Copy Btree meta values */ + for(i=0; iflags */ + db->flags = saved_flags; + db->nChange = saved_nChange; + db->nTotalChange = saved_nTotalChange; + db->xTrace = saved_xTrace; + sqlite3BtreeSetPageSize(pMain, -1, -1, 1); + + /* Currently there is an SQL level transaction open on the vacuum + ** database. No locks are held on any other files (since the main file + ** was committed at the btree level). So it safe to end the transaction + ** by manually setting the autoCommit flag to true and detaching the + ** vacuum database. The vacuum_db journal file is deleted when the pager + ** is closed by the DETACH. + */ + db->autoCommit = 1; + + if( pDb ){ + sqlite3BtreeClose(pDb->pBt); + pDb->pBt = 0; + pDb->pSchema = 0; + } + + /* This both clears the schemas and reduces the size of the db->aDb[] + ** array. */ + sqlite3ResetAllSchemasOfConnection(db); + + return rc; +} + +#endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */ + +/************** End of vacuum.c **********************************************/ +/************** Begin file vtab.c ********************************************/ +/* +** 2006 June 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to help implement virtual tables. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Before a virtual table xCreate() or xConnect() method is invoked, the +** sqlite3.pVtabCtx member variable is set to point to an instance of +** this struct allocated on the stack. It is used by the implementation of +** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which +** are invoked only from within xCreate and xConnect methods. +*/ +struct VtabCtx { + VTable *pVTable; /* The virtual table being constructed */ + Table *pTab; /* The Table object to which the virtual table belongs */ +}; + +/* +** The actual function that does the work of creating a new module. +** This function implements the sqlite3_create_module() and +** sqlite3_create_module_v2() interfaces. +*/ +static int createModule( + sqlite3 *db, /* Database in which module is registered */ + const char *zName, /* Name assigned to this module */ + const sqlite3_module *pModule, /* The definition of the module */ + void *pAux, /* Context pointer for xCreate/xConnect */ + void (*xDestroy)(void *) /* Module destructor function */ +){ + int rc = SQLITE_OK; + int nName; + + sqlite3_mutex_enter(db->mutex); + nName = sqlite3Strlen30(zName); + if( sqlite3HashFind(&db->aModule, zName, nName) ){ + rc = SQLITE_MISUSE_BKPT; + }else{ + Module *pMod; + pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1); + if( pMod ){ + Module *pDel; + char *zCopy = (char *)(&pMod[1]); + memcpy(zCopy, zName, nName+1); + pMod->zName = zCopy; + pMod->pModule = pModule; + pMod->pAux = pAux; + pMod->xDestroy = xDestroy; + pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod); + assert( pDel==0 || pDel==pMod ); + if( pDel ){ + db->mallocFailed = 1; + sqlite3DbFree(db, pDel); + } + } + } + rc = sqlite3ApiExit(db, rc); + if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux); + + sqlite3_mutex_leave(db->mutex); + return rc; +} + + +/* +** External API function used to create a new virtual-table module. +*/ +SQLITE_API int sqlite3_create_module( + sqlite3 *db, /* Database in which module is registered */ + const char *zName, /* Name assigned to this module */ + const sqlite3_module *pModule, /* The definition of the module */ + void *pAux /* Context pointer for xCreate/xConnect */ +){ + return createModule(db, zName, pModule, pAux, 0); +} + +/* +** External API function used to create a new virtual-table module. +*/ +SQLITE_API int sqlite3_create_module_v2( + sqlite3 *db, /* Database in which module is registered */ + const char *zName, /* Name assigned to this module */ + const sqlite3_module *pModule, /* The definition of the module */ + void *pAux, /* Context pointer for xCreate/xConnect */ + void (*xDestroy)(void *) /* Module destructor function */ +){ + return createModule(db, zName, pModule, pAux, xDestroy); +} + +/* +** Lock the virtual table so that it cannot be disconnected. +** Locks nest. Every lock should have a corresponding unlock. +** If an unlock is omitted, resources leaks will occur. +** +** If a disconnect is attempted while a virtual table is locked, +** the disconnect is deferred until all locks have been removed. +*/ +SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){ + pVTab->nRef++; +} + + +/* +** pTab is a pointer to a Table structure representing a virtual-table. +** Return a pointer to the VTable object used by connection db to access +** this virtual-table, if one has been created, or NULL otherwise. +*/ +SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){ + VTable *pVtab; + assert( IsVirtual(pTab) ); + for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext); + return pVtab; +} + +/* +** Decrement the ref-count on a virtual table object. When the ref-count +** reaches zero, call the xDisconnect() method to delete the object. +*/ +SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){ + sqlite3 *db = pVTab->db; + + assert( db ); + assert( pVTab->nRef>0 ); + assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE ); + + pVTab->nRef--; + if( pVTab->nRef==0 ){ + sqlite3_vtab *p = pVTab->pVtab; + if( p ){ + p->pModule->xDisconnect(p); + } + sqlite3DbFree(db, pVTab); + } +} + +/* +** Table p is a virtual table. This function moves all elements in the +** p->pVTable list to the sqlite3.pDisconnect lists of their associated +** database connections to be disconnected at the next opportunity. +** Except, if argument db is not NULL, then the entry associated with +** connection db is left in the p->pVTable list. +*/ +static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){ + VTable *pRet = 0; + VTable *pVTable = p->pVTable; + p->pVTable = 0; + + /* Assert that the mutex (if any) associated with the BtShared database + ** that contains table p is held by the caller. See header comments + ** above function sqlite3VtabUnlockList() for an explanation of why + ** this makes it safe to access the sqlite3.pDisconnect list of any + ** database connection that may have an entry in the p->pVTable list. + */ + assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); + + while( pVTable ){ + sqlite3 *db2 = pVTable->db; + VTable *pNext = pVTable->pNext; + assert( db2 ); + if( db2==db ){ + pRet = pVTable; + p->pVTable = pRet; + pRet->pNext = 0; + }else{ + pVTable->pNext = db2->pDisconnect; + db2->pDisconnect = pVTable; + } + pVTable = pNext; + } + + assert( !db || pRet ); + return pRet; +} + +/* +** Table *p is a virtual table. This function removes the VTable object +** for table *p associated with database connection db from the linked +** list in p->pVTab. It also decrements the VTable ref count. This is +** used when closing database connection db to free all of its VTable +** objects without disturbing the rest of the Schema object (which may +** be being used by other shared-cache connections). +*/ +SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){ + VTable **ppVTab; + + assert( IsVirtual(p) ); + assert( sqlite3BtreeHoldsAllMutexes(db) ); + assert( sqlite3_mutex_held(db->mutex) ); + + for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){ + if( (*ppVTab)->db==db ){ + VTable *pVTab = *ppVTab; + *ppVTab = pVTab->pNext; + sqlite3VtabUnlock(pVTab); + break; + } + } +} + + +/* +** Disconnect all the virtual table objects in the sqlite3.pDisconnect list. +** +** This function may only be called when the mutexes associated with all +** shared b-tree databases opened using connection db are held by the +** caller. This is done to protect the sqlite3.pDisconnect list. The +** sqlite3.pDisconnect list is accessed only as follows: +** +** 1) By this function. In this case, all BtShared mutexes and the mutex +** associated with the database handle itself must be held. +** +** 2) By function vtabDisconnectAll(), when it adds a VTable entry to +** the sqlite3.pDisconnect list. In this case either the BtShared mutex +** associated with the database the virtual table is stored in is held +** or, if the virtual table is stored in a non-sharable database, then +** the database handle mutex is held. +** +** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously +** by multiple threads. It is thread-safe. +*/ +SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){ + VTable *p = db->pDisconnect; + db->pDisconnect = 0; + + assert( sqlite3BtreeHoldsAllMutexes(db) ); + assert( sqlite3_mutex_held(db->mutex) ); + + if( p ){ + sqlite3ExpirePreparedStatements(db); + do { + VTable *pNext = p->pNext; + sqlite3VtabUnlock(p); + p = pNext; + }while( p ); + } +} + +/* +** Clear any and all virtual-table information from the Table record. +** This routine is called, for example, just before deleting the Table +** record. +** +** Since it is a virtual-table, the Table structure contains a pointer +** to the head of a linked list of VTable structures. Each VTable +** structure is associated with a single sqlite3* user of the schema. +** The reference count of the VTable structure associated with database +** connection db is decremented immediately (which may lead to the +** structure being xDisconnected and free). Any other VTable structures +** in the list are moved to the sqlite3.pDisconnect list of the associated +** database connection. +*/ +SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){ + if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p); + if( p->azModuleArg ){ + int i; + for(i=0; inModuleArg; i++){ + if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]); + } + sqlite3DbFree(db, p->azModuleArg); + } +} + +/* +** Add a new module argument to pTable->azModuleArg[]. +** The string is not copied - the pointer is stored. The +** string will be freed automatically when the table is +** deleted. +*/ +static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){ + int i = pTable->nModuleArg++; + int nBytes = sizeof(char *)*(1+pTable->nModuleArg); + char **azModuleArg; + azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes); + if( azModuleArg==0 ){ + int j; + for(j=0; jazModuleArg[j]); + } + sqlite3DbFree(db, zArg); + sqlite3DbFree(db, pTable->azModuleArg); + pTable->nModuleArg = 0; + }else{ + azModuleArg[i] = zArg; + azModuleArg[i+1] = 0; + } + pTable->azModuleArg = azModuleArg; +} + +/* +** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE +** statement. The module name has been parsed, but the optional list +** of parameters that follow the module name are still pending. +*/ +SQLITE_PRIVATE void sqlite3VtabBeginParse( + Parse *pParse, /* Parsing context */ + Token *pName1, /* Name of new table, or database name */ + Token *pName2, /* Name of new table or NULL */ + Token *pModuleName, /* Name of the module for the virtual table */ + int ifNotExists /* No error if the table already exists */ +){ + int iDb; /* The database the table is being created in */ + Table *pTable; /* The new virtual table */ + sqlite3 *db; /* Database connection */ + + sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists); + pTable = pParse->pNewTable; + if( pTable==0 ) return; + assert( 0==pTable->pIndex ); + + db = pParse->db; + iDb = sqlite3SchemaToIndex(db, pTable->pSchema); + assert( iDb>=0 ); + + pTable->tabFlags |= TF_Virtual; + pTable->nModuleArg = 0; + addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName)); + addModuleArgument(db, pTable, 0); + addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName)); + pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z); + +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Creating a virtual table invokes the authorization callback twice. + ** The first invocation, to obtain permission to INSERT a row into the + ** sqlite_master table, has already been made by sqlite3StartTable(). + ** The second call, to obtain permission to create the table, is made now. + */ + if( pTable->azModuleArg ){ + sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, + pTable->azModuleArg[0], pParse->db->aDb[iDb].zName); + } +#endif +} + +/* +** This routine takes the module argument that has been accumulating +** in pParse->zArg[] and appends it to the list of arguments on the +** virtual table currently under construction in pParse->pTable. +*/ +static void addArgumentToVtab(Parse *pParse){ + if( pParse->sArg.z && pParse->pNewTable ){ + const char *z = (const char*)pParse->sArg.z; + int n = pParse->sArg.n; + sqlite3 *db = pParse->db; + addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); + } +} + +/* +** The parser calls this routine after the CREATE VIRTUAL TABLE statement +** has been completely parsed. +*/ +SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ + Table *pTab = pParse->pNewTable; /* The table being constructed */ + sqlite3 *db = pParse->db; /* The database connection */ + + if( pTab==0 ) return; + addArgumentToVtab(pParse); + pParse->sArg.z = 0; + if( pTab->nModuleArg<1 ) return; + + /* If the CREATE VIRTUAL TABLE statement is being entered for the + ** first time (in other words if the virtual table is actually being + ** created now instead of just being read out of sqlite_master) then + ** do additional initialization work and store the statement text + ** in the sqlite_master table. + */ + if( !db->init.busy ){ + char *zStmt; + char *zWhere; + int iDb; + Vdbe *v; + + /* Compute the complete text of the CREATE VIRTUAL TABLE statement */ + if( pEnd ){ + pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n; + } + zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken); + + /* A slot for the record has already been allocated in the + ** SQLITE_MASTER table. We just need to update that slot with all + ** the information we've collected. + ** + ** The VM register number pParse->regRowid holds the rowid of an + ** entry in the sqlite_master table tht was created for this vtab + ** by sqlite3StartTable(). + */ + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + sqlite3NestedParse(pParse, + "UPDATE %Q.%s " + "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " + "WHERE rowid=#%d", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), + pTab->zName, + pTab->zName, + zStmt, + pParse->regRowid + ); + sqlite3DbFree(db, zStmt); + v = sqlite3GetVdbe(pParse); + sqlite3ChangeCookie(pParse, iDb); + + sqlite3VdbeAddOp2(v, OP_Expire, 0, 0); + zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName); + sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); + sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, + pTab->zName, sqlite3Strlen30(pTab->zName) + 1); + } + + /* If we are rereading the sqlite_master table create the in-memory + ** record of the table. The xConnect() method is not called until + ** the first time the virtual table is used in an SQL statement. This + ** allows a schema that contains virtual tables to be loaded before + ** the required virtual table implementations are registered. */ + else { + Table *pOld; + Schema *pSchema = pTab->pSchema; + const char *zName = pTab->zName; + int nName = sqlite3Strlen30(zName); + assert( sqlite3SchemaMutexHeld(db, 0, pSchema) ); + pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab); + if( pOld ){ + db->mallocFailed = 1; + assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */ + return; + } + pParse->pNewTable = 0; + } +} + +/* +** The parser calls this routine when it sees the first token +** of an argument to the module name in a CREATE VIRTUAL TABLE statement. +*/ +SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){ + addArgumentToVtab(pParse); + pParse->sArg.z = 0; + pParse->sArg.n = 0; +} + +/* +** The parser calls this routine for each token after the first token +** in an argument to the module name in a CREATE VIRTUAL TABLE statement. +*/ +SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){ + Token *pArg = &pParse->sArg; + if( pArg->z==0 ){ + pArg->z = p->z; + pArg->n = p->n; + }else{ + assert(pArg->z < p->z); + pArg->n = (int)(&p->z[p->n] - pArg->z); + } +} + +/* +** Invoke a virtual table constructor (either xCreate or xConnect). The +** pointer to the function to invoke is passed as the fourth parameter +** to this procedure. +*/ +static int vtabCallConstructor( + sqlite3 *db, + Table *pTab, + Module *pMod, + int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**), + char **pzErr +){ + VtabCtx sCtx, *pPriorCtx; + VTable *pVTable; + int rc; + const char *const*azArg = (const char *const*)pTab->azModuleArg; + int nArg = pTab->nModuleArg; + char *zErr = 0; + char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName); + int iDb; + + if( !zModuleName ){ + return SQLITE_NOMEM; + } + + pVTable = sqlite3DbMallocZero(db, sizeof(VTable)); + if( !pVTable ){ + sqlite3DbFree(db, zModuleName); + return SQLITE_NOMEM; + } + pVTable->db = db; + pVTable->pMod = pMod; + + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + pTab->azModuleArg[1] = db->aDb[iDb].zName; + + /* Invoke the virtual table constructor */ + assert( &db->pVtabCtx ); + assert( xConstruct ); + sCtx.pTab = pTab; + sCtx.pVTable = pVTable; + pPriorCtx = db->pVtabCtx; + db->pVtabCtx = &sCtx; + rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr); + db->pVtabCtx = pPriorCtx; + if( rc==SQLITE_NOMEM ) db->mallocFailed = 1; + + if( SQLITE_OK!=rc ){ + if( zErr==0 ){ + *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName); + }else { + *pzErr = sqlite3MPrintf(db, "%s", zErr); + sqlite3_free(zErr); + } + sqlite3DbFree(db, pVTable); + }else if( ALWAYS(pVTable->pVtab) ){ + /* Justification of ALWAYS(): A correct vtab constructor must allocate + ** the sqlite3_vtab object if successful. */ + pVTable->pVtab->pModule = pMod->pModule; + pVTable->nRef = 1; + if( sCtx.pTab ){ + const char *zFormat = "vtable constructor did not declare schema: %s"; + *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName); + sqlite3VtabUnlock(pVTable); + rc = SQLITE_ERROR; + }else{ + int iCol; + /* If everything went according to plan, link the new VTable structure + ** into the linked list headed by pTab->pVTable. Then loop through the + ** columns of the table to see if any of them contain the token "hidden". + ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from + ** the type string. */ + pVTable->pNext = pTab->pVTable; + pTab->pVTable = pVTable; + + for(iCol=0; iColnCol; iCol++){ + char *zType = pTab->aCol[iCol].zType; + int nType; + int i = 0; + if( !zType ) continue; + nType = sqlite3Strlen30(zType); + if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){ + for(i=0; i0 ){ + assert(zType[i-1]==' '); + zType[i-1] = '\0'; + } + pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN; + } + } + } + } + + sqlite3DbFree(db, zModuleName); + return rc; +} + +/* +** This function is invoked by the parser to call the xConnect() method +** of the virtual table pTab. If an error occurs, an error code is returned +** and an error left in pParse. +** +** This call is a no-op if table pTab is not a virtual table. +*/ +SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){ + sqlite3 *db = pParse->db; + const char *zMod; + Module *pMod; + int rc; + + assert( pTab ); + if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){ + return SQLITE_OK; + } + + /* Locate the required virtual table module */ + zMod = pTab->azModuleArg[0]; + pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod)); + + if( !pMod ){ + const char *zModule = pTab->azModuleArg[0]; + sqlite3ErrorMsg(pParse, "no such module: %s", zModule); + rc = SQLITE_ERROR; + }else{ + char *zErr = 0; + rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr); + if( rc!=SQLITE_OK ){ + sqlite3ErrorMsg(pParse, "%s", zErr); + } + sqlite3DbFree(db, zErr); + } + + return rc; +} +/* +** Grow the db->aVTrans[] array so that there is room for at least one +** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise. +*/ +static int growVTrans(sqlite3 *db){ + const int ARRAY_INCR = 5; + + /* Grow the sqlite3.aVTrans array if required */ + if( (db->nVTrans%ARRAY_INCR)==0 ){ + VTable **aVTrans; + int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR); + aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes); + if( !aVTrans ){ + return SQLITE_NOMEM; + } + memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR); + db->aVTrans = aVTrans; + } + + return SQLITE_OK; +} + +/* +** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should +** have already been reserved using growVTrans(). +*/ +static void addToVTrans(sqlite3 *db, VTable *pVTab){ + /* Add pVtab to the end of sqlite3.aVTrans */ + db->aVTrans[db->nVTrans++] = pVTab; + sqlite3VtabLock(pVTab); +} + +/* +** This function is invoked by the vdbe to call the xCreate method +** of the virtual table named zTab in database iDb. +** +** If an error occurs, *pzErr is set to point an an English language +** description of the error and an SQLITE_XXX error code is returned. +** In this case the caller must call sqlite3DbFree(db, ) on *pzErr. +*/ +SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){ + int rc = SQLITE_OK; + Table *pTab; + Module *pMod; + const char *zMod; + + pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName); + assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable ); + + /* Locate the required virtual table module */ + zMod = pTab->azModuleArg[0]; + pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod)); + + /* If the module has been registered and includes a Create method, + ** invoke it now. If the module has not been registered, return an + ** error. Otherwise, do nothing. + */ + if( !pMod ){ + *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod); + rc = SQLITE_ERROR; + }else{ + rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr); + } + + /* Justification of ALWAYS(): The xConstructor method is required to + ** create a valid sqlite3_vtab if it returns SQLITE_OK. */ + if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){ + rc = growVTrans(db); + if( rc==SQLITE_OK ){ + addToVTrans(db, sqlite3GetVTable(db, pTab)); + } + } + + return rc; +} + +/* +** This function is used to set the schema of a virtual table. It is only +** valid to call this function from within the xCreate() or xConnect() of a +** virtual table module. +*/ +SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){ + Parse *pParse; + + int rc = SQLITE_OK; + Table *pTab; + char *zErr = 0; + + sqlite3_mutex_enter(db->mutex); + if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){ + sqlite3Error(db, SQLITE_MISUSE, 0); + sqlite3_mutex_leave(db->mutex); + return SQLITE_MISUSE_BKPT; + } + assert( (pTab->tabFlags & TF_Virtual)!=0 ); + + pParse = sqlite3StackAllocZero(db, sizeof(*pParse)); + if( pParse==0 ){ + rc = SQLITE_NOMEM; + }else{ + pParse->declareVtab = 1; + pParse->db = db; + pParse->nQueryLoop = 1; + + if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) + && pParse->pNewTable + && !db->mallocFailed + && !pParse->pNewTable->pSelect + && (pParse->pNewTable->tabFlags & TF_Virtual)==0 + ){ + if( !pTab->aCol ){ + pTab->aCol = pParse->pNewTable->aCol; + pTab->nCol = pParse->pNewTable->nCol; + pParse->pNewTable->nCol = 0; + pParse->pNewTable->aCol = 0; + } + db->pVtabCtx->pTab = 0; + }else{ + sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr); + sqlite3DbFree(db, zErr); + rc = SQLITE_ERROR; + } + pParse->declareVtab = 0; + + if( pParse->pVdbe ){ + sqlite3VdbeFinalize(pParse->pVdbe); + } + sqlite3DeleteTable(db, pParse->pNewTable); + sqlite3StackFree(db, pParse); + } + + assert( (rc&0xff)==rc ); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** This function is invoked by the vdbe to call the xDestroy method +** of the virtual table named zTab in database iDb. This occurs +** when a DROP TABLE is mentioned. +** +** This call is a no-op if zTab is not a virtual table. +*/ +SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){ + int rc = SQLITE_OK; + Table *pTab; + + pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName); + if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){ + VTable *p = vtabDisconnectAll(db, pTab); + + assert( rc==SQLITE_OK ); + rc = p->pMod->pModule->xDestroy(p->pVtab); + + /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */ + if( rc==SQLITE_OK ){ + assert( pTab->pVTable==p && p->pNext==0 ); + p->pVtab = 0; + pTab->pVTable = 0; + sqlite3VtabUnlock(p); + } + } + + return rc; +} + +/* +** This function invokes either the xRollback or xCommit method +** of each of the virtual tables in the sqlite3.aVTrans array. The method +** called is identified by the second argument, "offset", which is +** the offset of the method to call in the sqlite3_module structure. +** +** The array is cleared after invoking the callbacks. +*/ +static void callFinaliser(sqlite3 *db, int offset){ + int i; + if( db->aVTrans ){ + for(i=0; inVTrans; i++){ + VTable *pVTab = db->aVTrans[i]; + sqlite3_vtab *p = pVTab->pVtab; + if( p ){ + int (*x)(sqlite3_vtab *); + x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset); + if( x ) x(p); + } + pVTab->iSavepoint = 0; + sqlite3VtabUnlock(pVTab); + } + sqlite3DbFree(db, db->aVTrans); + db->nVTrans = 0; + db->aVTrans = 0; + } +} + +/* +** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans +** array. Return the error code for the first error that occurs, or +** SQLITE_OK if all xSync operations are successful. +** +** If an error message is available, leave it in p->zErrMsg. +*/ +SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){ + int i; + int rc = SQLITE_OK; + VTable **aVTrans = db->aVTrans; + + db->aVTrans = 0; + for(i=0; rc==SQLITE_OK && inVTrans; i++){ + int (*x)(sqlite3_vtab *); + sqlite3_vtab *pVtab = aVTrans[i]->pVtab; + if( pVtab && (x = pVtab->pModule->xSync)!=0 ){ + rc = x(pVtab); + sqlite3VtabImportErrmsg(p, pVtab); + } + } + db->aVTrans = aVTrans; + return rc; +} + +/* +** Invoke the xRollback method of all virtual tables in the +** sqlite3.aVTrans array. Then clear the array itself. +*/ +SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){ + callFinaliser(db, offsetof(sqlite3_module,xRollback)); + return SQLITE_OK; +} + +/* +** Invoke the xCommit method of all virtual tables in the +** sqlite3.aVTrans array. Then clear the array itself. +*/ +SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){ + callFinaliser(db, offsetof(sqlite3_module,xCommit)); + return SQLITE_OK; +} + +/* +** If the virtual table pVtab supports the transaction interface +** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is +** not currently open, invoke the xBegin method now. +** +** If the xBegin call is successful, place the sqlite3_vtab pointer +** in the sqlite3.aVTrans array. +*/ +SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){ + int rc = SQLITE_OK; + const sqlite3_module *pModule; + + /* Special case: If db->aVTrans is NULL and db->nVTrans is greater + ** than zero, then this function is being called from within a + ** virtual module xSync() callback. It is illegal to write to + ** virtual module tables in this case, so return SQLITE_LOCKED. + */ + if( sqlite3VtabInSync(db) ){ + return SQLITE_LOCKED; + } + if( !pVTab ){ + return SQLITE_OK; + } + pModule = pVTab->pVtab->pModule; + + if( pModule->xBegin ){ + int i; + + /* If pVtab is already in the aVTrans array, return early */ + for(i=0; inVTrans; i++){ + if( db->aVTrans[i]==pVTab ){ + return SQLITE_OK; + } + } + + /* Invoke the xBegin method. If successful, add the vtab to the + ** sqlite3.aVTrans[] array. */ + rc = growVTrans(db); + if( rc==SQLITE_OK ){ + rc = pModule->xBegin(pVTab->pVtab); + if( rc==SQLITE_OK ){ + addToVTrans(db, pVTab); + } + } + } + return rc; +} + +/* +** Invoke either the xSavepoint, xRollbackTo or xRelease method of all +** virtual tables that currently have an open transaction. Pass iSavepoint +** as the second argument to the virtual table method invoked. +** +** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is +** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is +** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with +** an open transaction is invoked. +** +** If any virtual table method returns an error code other than SQLITE_OK, +** processing is abandoned and the error returned to the caller of this +** function immediately. If all calls to virtual table methods are successful, +** SQLITE_OK is returned. +*/ +SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){ + int rc = SQLITE_OK; + + assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN ); + assert( iSavepoint>=0 ); + if( db->aVTrans ){ + int i; + for(i=0; rc==SQLITE_OK && inVTrans; i++){ + VTable *pVTab = db->aVTrans[i]; + const sqlite3_module *pMod = pVTab->pMod->pModule; + if( pVTab->pVtab && pMod->iVersion>=2 ){ + int (*xMethod)(sqlite3_vtab *, int); + switch( op ){ + case SAVEPOINT_BEGIN: + xMethod = pMod->xSavepoint; + pVTab->iSavepoint = iSavepoint+1; + break; + case SAVEPOINT_ROLLBACK: + xMethod = pMod->xRollbackTo; + break; + default: + xMethod = pMod->xRelease; + break; + } + if( xMethod && pVTab->iSavepoint>iSavepoint ){ + rc = xMethod(pVTab->pVtab, iSavepoint); + } + } + } + } + return rc; +} + +/* +** The first parameter (pDef) is a function implementation. The +** second parameter (pExpr) is the first argument to this function. +** If pExpr is a column in a virtual table, then let the virtual +** table implementation have an opportunity to overload the function. +** +** This routine is used to allow virtual table implementations to +** overload MATCH, LIKE, GLOB, and REGEXP operators. +** +** Return either the pDef argument (indicating no change) or a +** new FuncDef structure that is marked as ephemeral using the +** SQLITE_FUNC_EPHEM flag. +*/ +SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction( + sqlite3 *db, /* Database connection for reporting malloc problems */ + FuncDef *pDef, /* Function to possibly overload */ + int nArg, /* Number of arguments to the function */ + Expr *pExpr /* First argument to the function */ +){ + Table *pTab; + sqlite3_vtab *pVtab; + sqlite3_module *pMod; + void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0; + void *pArg = 0; + FuncDef *pNew; + int rc = 0; + char *zLowerName; + unsigned char *z; + + + /* Check to see the left operand is a column in a virtual table */ + if( NEVER(pExpr==0) ) return pDef; + if( pExpr->op!=TK_COLUMN ) return pDef; + pTab = pExpr->pTab; + if( NEVER(pTab==0) ) return pDef; + if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef; + pVtab = sqlite3GetVTable(db, pTab)->pVtab; + assert( pVtab!=0 ); + assert( pVtab->pModule!=0 ); + pMod = (sqlite3_module *)pVtab->pModule; + if( pMod->xFindFunction==0 ) return pDef; + + /* Call the xFindFunction method on the virtual table implementation + ** to see if the implementation wants to overload this function + */ + zLowerName = sqlite3DbStrDup(db, pDef->zName); + if( zLowerName ){ + for(z=(unsigned char*)zLowerName; *z; z++){ + *z = sqlite3UpperToLower[*z]; + } + rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg); + sqlite3DbFree(db, zLowerName); + } + if( rc==0 ){ + return pDef; + } + + /* Create a new ephemeral function definition for the overloaded + ** function */ + pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + + sqlite3Strlen30(pDef->zName) + 1); + if( pNew==0 ){ + return pDef; + } + *pNew = *pDef; + pNew->zName = (char *)&pNew[1]; + memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1); + pNew->xFunc = xFunc; + pNew->pUserData = pArg; + pNew->funcFlags |= SQLITE_FUNC_EPHEM; + return pNew; +} + +/* +** Make sure virtual table pTab is contained in the pParse->apVirtualLock[] +** array so that an OP_VBegin will get generated for it. Add pTab to the +** array if it is missing. If pTab is already in the array, this routine +** is a no-op. +*/ +SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + int i, n; + Table **apVtabLock; + + assert( IsVirtual(pTab) ); + for(i=0; inVtabLock; i++){ + if( pTab==pToplevel->apVtabLock[i] ) return; + } + n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]); + apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n); + if( apVtabLock ){ + pToplevel->apVtabLock = apVtabLock; + pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab; + }else{ + pToplevel->db->mallocFailed = 1; + } +} + +/* +** Return the ON CONFLICT resolution mode in effect for the virtual +** table update operation currently in progress. +** +** The results of this routine are undefined unless it is called from +** within an xUpdate method. +*/ +SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){ + static const unsigned char aMap[] = { + SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE + }; + assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 ); + assert( OE_Ignore==4 && OE_Replace==5 ); + assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 ); + return (int)aMap[db->vtabOnConflict-1]; +} + +/* +** Call from within the xCreate() or xConnect() methods to provide +** the SQLite core with additional information about the behavior +** of the virtual table being implemented. +*/ +SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){ + va_list ap; + int rc = SQLITE_OK; + + sqlite3_mutex_enter(db->mutex); + + va_start(ap, op); + switch( op ){ + case SQLITE_VTAB_CONSTRAINT_SUPPORT: { + VtabCtx *p = db->pVtabCtx; + if( !p ){ + rc = SQLITE_MISUSE_BKPT; + }else{ + assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 ); + p->pVTable->bConstraint = (u8)va_arg(ap, int); + } + break; + } + default: + rc = SQLITE_MISUSE_BKPT; + break; + } + va_end(ap); + + if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/************** End of vtab.c ************************************************/ +/************** Begin file where.c *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This module contains C code that generates VDBE code used to process +** the WHERE clause of SQL statements. This module is responsible for +** generating the code that loops through a table looking for applicable +** rows. Indices are selected and used to speed the search when doing +** so is applicable. Because this module is responsible for selecting +** indices, you might also think of this module as the "query optimizer". +*/ + + +/* +** Trace output macros +*/ +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) +/***/ int sqlite3WhereTrace = 0; +#endif +#if defined(SQLITE_DEBUG) \ + && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE)) +# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X +# define WHERETRACE_ENABLED 1 +#else +# define WHERETRACE(K,X) +#endif + +/* Forward references +*/ +typedef struct WhereClause WhereClause; +typedef struct WhereMaskSet WhereMaskSet; +typedef struct WhereOrInfo WhereOrInfo; +typedef struct WhereAndInfo WhereAndInfo; +typedef struct WhereLevel WhereLevel; +typedef struct WhereLoop WhereLoop; +typedef struct WherePath WherePath; +typedef struct WhereTerm WhereTerm; +typedef struct WhereLoopBuilder WhereLoopBuilder; +typedef struct WhereScan WhereScan; +typedef struct WhereOrCost WhereOrCost; +typedef struct WhereOrSet WhereOrSet; + +/* +** This object contains information needed to implement a single nested +** loop in WHERE clause. +** +** Contrast this object with WhereLoop. This object describes the +** implementation of the loop. WhereLoop describes the algorithm. +** This object contains a pointer to the WhereLoop algorithm as one of +** its elements. +** +** The WhereInfo object contains a single instance of this object for +** each term in the FROM clause (which is to say, for each of the +** nested loops as implemented). The order of WhereLevel objects determines +** the loop nested order, with WhereInfo.a[0] being the outer loop and +** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop. +*/ +struct WhereLevel { + int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */ + int iTabCur; /* The VDBE cursor used to access the table */ + int iIdxCur; /* The VDBE cursor used to access pIdx */ + int addrBrk; /* Jump here to break out of the loop */ + int addrNxt; /* Jump here to start the next IN combination */ + int addrCont; /* Jump here to continue with the next loop cycle */ + int addrFirst; /* First instruction of interior of the loop */ + int addrBody; /* Beginning of the body of this loop */ + u8 iFrom; /* Which entry in the FROM clause */ + u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */ + int p1, p2; /* Operands of the opcode used to ends the loop */ + union { /* Information that depends on pWLoop->wsFlags */ + struct { + int nIn; /* Number of entries in aInLoop[] */ + struct InLoop { + int iCur; /* The VDBE cursor used by this IN operator */ + int addrInTop; /* Top of the IN loop */ + u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */ + } *aInLoop; /* Information about each nested IN operator */ + } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */ + Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */ + } u; + struct WhereLoop *pWLoop; /* The selected WhereLoop object */ + Bitmask notReady; /* FROM entries not usable at this level */ +}; + +/* +** Each instance of this object represents an algorithm for evaluating one +** term of a join. Every term of the FROM clause will have at least +** one corresponding WhereLoop object (unless INDEXED BY constraints +** prevent a query solution - which is an error) and many terms of the +** FROM clause will have multiple WhereLoop objects, each describing a +** potential way of implementing that FROM-clause term, together with +** dependencies and cost estimates for using the chosen algorithm. +** +** Query planning consists of building up a collection of these WhereLoop +** objects, then computing a particular sequence of WhereLoop objects, with +** one WhereLoop object per FROM clause term, that satisfy all dependencies +** and that minimize the overall cost. +*/ +struct WhereLoop { + Bitmask prereq; /* Bitmask of other loops that must run first */ + Bitmask maskSelf; /* Bitmask identifying table iTab */ +#ifdef SQLITE_DEBUG + char cId; /* Symbolic ID of this loop for debugging use */ +#endif + u8 iTab; /* Position in FROM clause of table for this loop */ + u8 iSortIdx; /* Sorting index number. 0==None */ + LogEst rSetup; /* One-time setup cost (ex: create transient index) */ + LogEst rRun; /* Cost of running each loop */ + LogEst nOut; /* Estimated number of output rows */ + union { + struct { /* Information for internal btree tables */ + int nEq; /* Number of equality constraints */ + Index *pIndex; /* Index used, or NULL */ + } btree; + struct { /* Information for virtual tables */ + int idxNum; /* Index number */ + u8 needFree; /* True if sqlite3_free(idxStr) is needed */ + u8 isOrdered; /* True if satisfies ORDER BY */ + u16 omitMask; /* Terms that may be omitted */ + char *idxStr; /* Index identifier string */ + } vtab; + } u; + u32 wsFlags; /* WHERE_* flags describing the plan */ + u16 nLTerm; /* Number of entries in aLTerm[] */ + /**** whereLoopXfer() copies fields above ***********************/ +# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot) + u16 nLSlot; /* Number of slots allocated for aLTerm[] */ + WhereTerm **aLTerm; /* WhereTerms used */ + WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */ + WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */ +}; + +/* This object holds the prerequisites and the cost of running a +** subquery on one operand of an OR operator in the WHERE clause. +** See WhereOrSet for additional information +*/ +struct WhereOrCost { + Bitmask prereq; /* Prerequisites */ + LogEst rRun; /* Cost of running this subquery */ + LogEst nOut; /* Number of outputs for this subquery */ +}; + +/* The WhereOrSet object holds a set of possible WhereOrCosts that +** correspond to the subquery(s) of OR-clause processing. Only the +** best N_OR_COST elements are retained. +*/ +#define N_OR_COST 3 +struct WhereOrSet { + u16 n; /* Number of valid a[] entries */ + WhereOrCost a[N_OR_COST]; /* Set of best costs */ +}; + + +/* Forward declaration of methods */ +static int whereLoopResize(sqlite3*, WhereLoop*, int); + +/* +** Each instance of this object holds a sequence of WhereLoop objects +** that implement some or all of a query plan. +** +** Think of each WhereLoop object as a node in a graph with arcs +** showing dependencies and costs for travelling between nodes. (That is +** not a completely accurate description because WhereLoop costs are a +** vector, not a scalar, and because dependencies are many-to-one, not +** one-to-one as are graph nodes. But it is a useful visualization aid.) +** Then a WherePath object is a path through the graph that visits some +** or all of the WhereLoop objects once. +** +** The "solver" works by creating the N best WherePath objects of length +** 1. Then using those as a basis to compute the N best WherePath objects +** of length 2. And so forth until the length of WherePaths equals the +** number of nodes in the FROM clause. The best (lowest cost) WherePath +** at the end is the choosen query plan. +*/ +struct WherePath { + Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */ + Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */ + LogEst nRow; /* Estimated number of rows generated by this path */ + LogEst rCost; /* Total cost of this path */ + u8 isOrdered; /* True if this path satisfies ORDER BY */ + u8 isOrderedValid; /* True if the isOrdered field is valid */ + WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */ +}; + +/* +** The query generator uses an array of instances of this structure to +** help it analyze the subexpressions of the WHERE clause. Each WHERE +** clause subexpression is separated from the others by AND operators, +** usually, or sometimes subexpressions separated by OR. +** +** All WhereTerms are collected into a single WhereClause structure. +** The following identity holds: +** +** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm +** +** When a term is of the form: +** +** X +** +** where X is a column name and is one of certain operators, +** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the +** cursor number and column number for X. WhereTerm.eOperator records +** the using a bitmask encoding defined by WO_xxx below. The +** use of a bitmask encoding for the operator allows us to search +** quickly for terms that match any of several different operators. +** +** A WhereTerm might also be two or more subterms connected by OR: +** +** (t1.X ) OR (t1.Y ) OR .... +** +** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR +** and the WhereTerm.u.pOrInfo field points to auxiliary information that +** is collected about the OR clause. +** +** If a term in the WHERE clause does not match either of the two previous +** categories, then eOperator==0. The WhereTerm.pExpr field is still set +** to the original subexpression content and wtFlags is set up appropriately +** but no other fields in the WhereTerm object are meaningful. +** +** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers, +** but they do so indirectly. A single WhereMaskSet structure translates +** cursor number into bits and the translated bit is stored in the prereq +** fields. The translation is used in order to maximize the number of +** bits that will fit in a Bitmask. The VDBE cursor numbers might be +** spread out over the non-negative integers. For example, the cursor +** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet +** translates these sparse cursor numbers into consecutive integers +** beginning with 0 in order to make the best possible use of the available +** bits in the Bitmask. So, in the example above, the cursor numbers +** would be mapped into integers 0 through 7. +** +** The number of terms in a join is limited by the number of bits +** in prereqRight and prereqAll. The default is 64 bits, hence SQLite +** is only able to process joins with 64 or fewer tables. +*/ +struct WhereTerm { + Expr *pExpr; /* Pointer to the subexpression that is this term */ + int iParent; /* Disable pWC->a[iParent] when this term disabled */ + int leftCursor; /* Cursor number of X in "X " */ + union { + int leftColumn; /* Column number of X in "X " */ + WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */ + WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */ + } u; + LogEst truthProb; /* Probability of truth for this expression */ + u16 eOperator; /* A WO_xx value describing */ + u8 wtFlags; /* TERM_xxx bit flags. See below */ + u8 nChild; /* Number of children that must disable us */ + WhereClause *pWC; /* The clause this term is part of */ + Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */ + Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */ +}; + +/* +** Allowed values of WhereTerm.wtFlags +*/ +#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */ +#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */ +#define TERM_CODED 0x04 /* This term is already coded */ +#define TERM_COPIED 0x08 /* Has a child */ +#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */ +#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */ +#define TERM_OR_OK 0x40 /* Used during OR-clause processing */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */ +#else +# define TERM_VNULL 0x00 /* Disabled if not using stat3 */ +#endif + +/* +** An instance of the WhereScan object is used as an iterator for locating +** terms in the WHERE clause that are useful to the query planner. +*/ +struct WhereScan { + WhereClause *pOrigWC; /* Original, innermost WhereClause */ + WhereClause *pWC; /* WhereClause currently being scanned */ + char *zCollName; /* Required collating sequence, if not NULL */ + char idxaff; /* Must match this affinity, if zCollName!=NULL */ + unsigned char nEquiv; /* Number of entries in aEquiv[] */ + unsigned char iEquiv; /* Next unused slot in aEquiv[] */ + u32 opMask; /* Acceptable operators */ + int k; /* Resume scanning at this->pWC->a[this->k] */ + int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */ +}; + +/* +** An instance of the following structure holds all information about a +** WHERE clause. Mostly this is a container for one or more WhereTerms. +** +** Explanation of pOuter: For a WHERE clause of the form +** +** a AND ((b AND c) OR (d AND e)) AND f +** +** There are separate WhereClause objects for the whole clause and for +** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the +** subclauses points to the WhereClause object for the whole clause. +*/ +struct WhereClause { + WhereInfo *pWInfo; /* WHERE clause processing context */ + WhereClause *pOuter; /* Outer conjunction */ + u8 op; /* Split operator. TK_AND or TK_OR */ + int nTerm; /* Number of terms */ + int nSlot; /* Number of entries in a[] */ + WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */ +#if defined(SQLITE_SMALL_STACK) + WhereTerm aStatic[1]; /* Initial static space for a[] */ +#else + WhereTerm aStatic[8]; /* Initial static space for a[] */ +#endif +}; + +/* +** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to +** a dynamically allocated instance of the following structure. +*/ +struct WhereOrInfo { + WhereClause wc; /* Decomposition into subterms */ + Bitmask indexable; /* Bitmask of all indexable tables in the clause */ +}; + +/* +** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to +** a dynamically allocated instance of the following structure. +*/ +struct WhereAndInfo { + WhereClause wc; /* The subexpression broken out */ +}; + +/* +** An instance of the following structure keeps track of a mapping +** between VDBE cursor numbers and bits of the bitmasks in WhereTerm. +** +** The VDBE cursor numbers are small integers contained in +** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE +** clause, the cursor numbers might not begin with 0 and they might +** contain gaps in the numbering sequence. But we want to make maximum +** use of the bits in our bitmasks. This structure provides a mapping +** from the sparse cursor numbers into consecutive integers beginning +** with 0. +** +** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask +** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<3, 5->1, 8->2, 29->0, +** 57->5, 73->4. Or one of 719 other combinations might be used. It +** does not really matter. What is important is that sparse cursor +** numbers all get mapped into bit numbers that begin with 0 and contain +** no gaps. +*/ +struct WhereMaskSet { + int n; /* Number of assigned cursor values */ + int ix[BMS]; /* Cursor assigned to each bit */ +}; + +/* +** This object is a convenience wrapper holding all information needed +** to construct WhereLoop objects for a particular query. +*/ +struct WhereLoopBuilder { + WhereInfo *pWInfo; /* Information about this WHERE */ + WhereClause *pWC; /* WHERE clause terms */ + ExprList *pOrderBy; /* ORDER BY clause */ + WhereLoop *pNew; /* Template WhereLoop */ + WhereOrSet *pOrSet; /* Record best loops here, if not NULL */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + UnpackedRecord *pRec; /* Probe for stat4 (if required) */ + int nRecValid; /* Number of valid fields currently in pRec */ +#endif +}; + +/* +** The WHERE clause processing routine has two halves. The +** first part does the start of the WHERE loop and the second +** half does the tail of the WHERE loop. An instance of +** this structure is returned by the first half and passed +** into the second half to give some continuity. +** +** An instance of this object holds the complete state of the query +** planner. +*/ +struct WhereInfo { + Parse *pParse; /* Parsing and code generating context */ + SrcList *pTabList; /* List of tables in the join */ + ExprList *pOrderBy; /* The ORDER BY clause or NULL */ + ExprList *pResultSet; /* Result set. DISTINCT operates on these */ + WhereLoop *pLoops; /* List of all WhereLoop objects */ + Bitmask revMask; /* Mask of ORDER BY terms that need reversing */ + LogEst nRowOut; /* Estimated number of output rows */ + u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */ + u8 bOBSat; /* ORDER BY satisfied by indices */ + u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */ + u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */ + u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */ + u8 nLevel; /* Number of nested loop */ + int iTop; /* The very beginning of the WHERE loop */ + int iContinue; /* Jump here to continue with next record */ + int iBreak; /* Jump here to break out of the loop */ + int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */ + WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */ + WhereClause sWC; /* Decomposition of the WHERE clause */ + WhereLevel a[1]; /* Information about each nest loop in WHERE */ +}; + +/* +** Bitmasks for the operators on WhereTerm objects. These are all +** operators that are of interest to the query planner. An +** OR-ed combination of these values can be used when searching for +** particular WhereTerms within a WhereClause. +*/ +#define WO_IN 0x001 +#define WO_EQ 0x002 +#define WO_LT (WO_EQ<<(TK_LT-TK_EQ)) +#define WO_LE (WO_EQ<<(TK_LE-TK_EQ)) +#define WO_GT (WO_EQ<<(TK_GT-TK_EQ)) +#define WO_GE (WO_EQ<<(TK_GE-TK_EQ)) +#define WO_MATCH 0x040 +#define WO_ISNULL 0x080 +#define WO_OR 0x100 /* Two or more OR-connected terms */ +#define WO_AND 0x200 /* Two or more AND-connected terms */ +#define WO_EQUIV 0x400 /* Of the form A==B, both columns */ +#define WO_NOOP 0x800 /* This term does not restrict search space */ + +#define WO_ALL 0xfff /* Mask of all possible WO_* values */ +#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */ + +/* +** These are definitions of bits in the WhereLoop.wsFlags field. +** The particular combination of bits in each WhereLoop help to +** determine the algorithm that WhereLoop represents. +*/ +#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */ +#define WHERE_COLUMN_RANGE 0x00000002 /* xEXPR */ +#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */ +#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */ +#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */ +#define WHERE_TOP_LIMIT 0x00000010 /* xEXPR or x>=EXPR constraint */ +#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and xnRowOut); +} + +/* +** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this +** WHERE clause returns outputs for DISTINCT processing. +*/ +SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ + return pWInfo->eDistinct; +} + +/* +** Return TRUE if the WHERE clause returns rows in ORDER BY order. +** Return FALSE if the output needs to be sorted. +*/ +SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ + return pWInfo->bOBSat!=0; +} + +/* +** Return the VDBE address or label to jump to in order to continue +** immediately with the next row of a WHERE clause. +*/ +SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ + return pWInfo->iContinue; +} + +/* +** Return the VDBE address or label to jump to in order to break +** out of a WHERE loop. +*/ +SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ + return pWInfo->iBreak; +} + +/* +** Return TRUE if an UPDATE or DELETE statement can operate directly on +** the rowids returned by a WHERE clause. Return FALSE if doing an +** UPDATE or DELETE might change subsequent WHERE clause results. +*/ +SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){ + return pWInfo->okOnePass; +} + +/* +** Move the content of pSrc into pDest +*/ +static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ + pDest->n = pSrc->n; + memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); +} + +/* +** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet. +** +** The new entry might overwrite an existing entry, or it might be +** appended, or it might be discarded. Do whatever is the right thing +** so that pSet keeps the N_OR_COST best entries seen so far. +*/ +static int whereOrInsert( + WhereOrSet *pSet, /* The WhereOrSet to be updated */ + Bitmask prereq, /* Prerequisites of the new entry */ + LogEst rRun, /* Run-cost of the new entry */ + LogEst nOut /* Number of outputs for the new entry */ +){ + u16 i; + WhereOrCost *p; + for(i=pSet->n, p=pSet->a; i>0; i--, p++){ + if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){ + goto whereOrInsert_done; + } + if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){ + return 0; + } + } + if( pSet->na[pSet->n++]; + p->nOut = nOut; + }else{ + p = pSet->a; + for(i=1; in; i++){ + if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i; + } + if( p->rRun<=rRun ) return 0; + } +whereOrInsert_done: + p->prereq = prereq; + p->rRun = rRun; + if( p->nOut>nOut ) p->nOut = nOut; + return 1; +} + +/* +** Initialize a preallocated WhereClause structure. +*/ +static void whereClauseInit( + WhereClause *pWC, /* The WhereClause to be initialized */ + WhereInfo *pWInfo /* The WHERE processing context */ +){ + pWC->pWInfo = pWInfo; + pWC->pOuter = 0; + pWC->nTerm = 0; + pWC->nSlot = ArraySize(pWC->aStatic); + pWC->a = pWC->aStatic; +} + +/* Forward reference */ +static void whereClauseClear(WhereClause*); + +/* +** Deallocate all memory associated with a WhereOrInfo object. +*/ +static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ + whereClauseClear(&p->wc); + sqlite3DbFree(db, p); +} + +/* +** Deallocate all memory associated with a WhereAndInfo object. +*/ +static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ + whereClauseClear(&p->wc); + sqlite3DbFree(db, p); +} + +/* +** Deallocate a WhereClause structure. The WhereClause structure +** itself is not freed. This routine is the inverse of whereClauseInit(). +*/ +static void whereClauseClear(WhereClause *pWC){ + int i; + WhereTerm *a; + sqlite3 *db = pWC->pWInfo->pParse->db; + for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ + if( a->wtFlags & TERM_DYNAMIC ){ + sqlite3ExprDelete(db, a->pExpr); + } + if( a->wtFlags & TERM_ORINFO ){ + whereOrInfoDelete(db, a->u.pOrInfo); + }else if( a->wtFlags & TERM_ANDINFO ){ + whereAndInfoDelete(db, a->u.pAndInfo); + } + } + if( pWC->a!=pWC->aStatic ){ + sqlite3DbFree(db, pWC->a); + } +} + +/* +** Add a single new WhereTerm entry to the WhereClause object pWC. +** The new WhereTerm object is constructed from Expr p and with wtFlags. +** The index in pWC->a[] of the new WhereTerm is returned on success. +** 0 is returned if the new WhereTerm could not be added due to a memory +** allocation error. The memory allocation failure will be recorded in +** the db->mallocFailed flag so that higher-level functions can detect it. +** +** This routine will increase the size of the pWC->a[] array as necessary. +** +** If the wtFlags argument includes TERM_DYNAMIC, then responsibility +** for freeing the expression p is assumed by the WhereClause object pWC. +** This is true even if this routine fails to allocate a new WhereTerm. +** +** WARNING: This routine might reallocate the space used to store +** WhereTerms. All pointers to WhereTerms should be invalidated after +** calling this routine. Such pointers may be reinitialized by referencing +** the pWC->a[] array. +*/ +static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){ + WhereTerm *pTerm; + int idx; + testcase( wtFlags & TERM_VIRTUAL ); + if( pWC->nTerm>=pWC->nSlot ){ + WhereTerm *pOld = pWC->a; + sqlite3 *db = pWC->pWInfo->pParse->db; + pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); + if( pWC->a==0 ){ + if( wtFlags & TERM_DYNAMIC ){ + sqlite3ExprDelete(db, p); + } + pWC->a = pOld; + return 0; + } + memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); + if( pOld!=pWC->aStatic ){ + sqlite3DbFree(db, pOld); + } + pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); + } + pTerm = &pWC->a[idx = pWC->nTerm++]; + if( p && ExprHasProperty(p, EP_Unlikely) ){ + pTerm->truthProb = sqlite3LogEst(p->iTable) - 99; + }else{ + pTerm->truthProb = -1; + } + pTerm->pExpr = sqlite3ExprSkipCollate(p); + pTerm->wtFlags = wtFlags; + pTerm->pWC = pWC; + pTerm->iParent = -1; + return idx; +} + +/* +** This routine identifies subexpressions in the WHERE clause where +** each subexpression is separated by the AND operator or some other +** operator specified in the op parameter. The WhereClause structure +** is filled with pointers to subexpressions. For example: +** +** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) +** \________/ \_______________/ \________________/ +** slot[0] slot[1] slot[2] +** +** The original WHERE clause in pExpr is unaltered. All this routine +** does is make slot[] entries point to substructure within pExpr. +** +** In the previous sentence and in the diagram, "slot[]" refers to +** the WhereClause.a[] array. The slot[] array grows as needed to contain +** all terms of the WHERE clause. +*/ +static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ + pWC->op = op; + if( pExpr==0 ) return; + if( pExpr->op!=op ){ + whereClauseInsert(pWC, pExpr, 0); + }else{ + whereSplit(pWC, pExpr->pLeft, op); + whereSplit(pWC, pExpr->pRight, op); + } +} + +/* +** Initialize a WhereMaskSet object +*/ +#define initMaskSet(P) (P)->n=0 + +/* +** Return the bitmask for the given cursor number. Return 0 if +** iCursor is not in the set. +*/ +static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){ + int i; + assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); + for(i=0; in; i++){ + if( pMaskSet->ix[i]==iCursor ){ + return MASKBIT(i); + } + } + return 0; +} + +/* +** Create a new mask for cursor iCursor. +** +** There is one cursor per table in the FROM clause. The number of +** tables in the FROM clause is limited by a test early in the +** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] +** array will never overflow. +*/ +static void createMask(WhereMaskSet *pMaskSet, int iCursor){ + assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); + pMaskSet->ix[pMaskSet->n++] = iCursor; +} + +/* +** These routines walk (recursively) an expression tree and generate +** a bitmask indicating which tables are used in that expression +** tree. +*/ +static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*); +static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*); +static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){ + Bitmask mask = 0; + if( p==0 ) return 0; + if( p->op==TK_COLUMN ){ + mask = getMask(pMaskSet, p->iTable); + return mask; + } + mask = exprTableUsage(pMaskSet, p->pRight); + mask |= exprTableUsage(pMaskSet, p->pLeft); + if( ExprHasProperty(p, EP_xIsSelect) ){ + mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect); + }else{ + mask |= exprListTableUsage(pMaskSet, p->x.pList); + } + return mask; +} +static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){ + int i; + Bitmask mask = 0; + if( pList ){ + for(i=0; inExpr; i++){ + mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr); + } + } + return mask; +} +static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){ + Bitmask mask = 0; + while( pS ){ + SrcList *pSrc = pS->pSrc; + mask |= exprListTableUsage(pMaskSet, pS->pEList); + mask |= exprListTableUsage(pMaskSet, pS->pGroupBy); + mask |= exprListTableUsage(pMaskSet, pS->pOrderBy); + mask |= exprTableUsage(pMaskSet, pS->pWhere); + mask |= exprTableUsage(pMaskSet, pS->pHaving); + if( ALWAYS(pSrc!=0) ){ + int i; + for(i=0; inSrc; i++){ + mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect); + mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn); + } + } + pS = pS->pPrior; + } + return mask; +} + +/* +** Return TRUE if the given operator is one of the operators that is +** allowed for an indexable WHERE clause term. The allowed operators are +** "=", "<", ">", "<=", ">=", "IN", and "IS NULL" +*/ +static int allowedOp(int op){ + assert( TK_GT>TK_EQ && TK_GTTK_EQ && TK_LTTK_EQ && TK_LE=TK_EQ && op<=TK_GE) || op==TK_ISNULL; +} + +/* +** Swap two objects of type TYPE. +*/ +#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} + +/* +** Commute a comparison operator. Expressions of the form "X op Y" +** are converted into "Y op X". +** +** If left/right precedence rules come into play when determining the +** collating sequence, then COLLATE operators are adjusted to ensure +** that the collating sequence does not change. For example: +** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on +** the left hand side of a comparison overrides any collation sequence +** attached to the right. For the same reason the EP_Collate flag +** is not commuted. +*/ +static void exprCommute(Parse *pParse, Expr *pExpr){ + u16 expRight = (pExpr->pRight->flags & EP_Collate); + u16 expLeft = (pExpr->pLeft->flags & EP_Collate); + assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN ); + if( expRight==expLeft ){ + /* Either X and Y both have COLLATE operator or neither do */ + if( expRight ){ + /* Both X and Y have COLLATE operators. Make sure X is always + ** used by clearing the EP_Collate flag from Y. */ + pExpr->pRight->flags &= ~EP_Collate; + }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){ + /* Neither X nor Y have COLLATE operators, but X has a non-default + ** collating sequence. So add the EP_Collate marker on X to cause + ** it to be searched first. */ + pExpr->pLeft->flags |= EP_Collate; + } + } + SWAP(Expr*,pExpr->pRight,pExpr->pLeft); + if( pExpr->op>=TK_GT ){ + assert( TK_LT==TK_GT+2 ); + assert( TK_GE==TK_LE+2 ); + assert( TK_GT>TK_EQ ); + assert( TK_GTop>=TK_GT && pExpr->op<=TK_GE ); + pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; + } +} + +/* +** Translate from TK_xx operator to WO_xx bitmask. +*/ +static u16 operatorMask(int op){ + u16 c; + assert( allowedOp(op) ); + if( op==TK_IN ){ + c = WO_IN; + }else if( op==TK_ISNULL ){ + c = WO_ISNULL; + }else{ + assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff ); + c = (u16)(WO_EQ<<(op-TK_EQ)); + } + assert( op!=TK_ISNULL || c==WO_ISNULL ); + assert( op!=TK_IN || c==WO_IN ); + assert( op!=TK_EQ || c==WO_EQ ); + assert( op!=TK_LT || c==WO_LT ); + assert( op!=TK_LE || c==WO_LE ); + assert( op!=TK_GT || c==WO_GT ); + assert( op!=TK_GE || c==WO_GE ); + return c; +} + +/* +** Advance to the next WhereTerm that matches according to the criteria +** established when the pScan object was initialized by whereScanInit(). +** Return NULL if there are no more matching WhereTerms. +*/ +static WhereTerm *whereScanNext(WhereScan *pScan){ + int iCur; /* The cursor on the LHS of the term */ + int iColumn; /* The column on the LHS of the term. -1 for IPK */ + Expr *pX; /* An expression being tested */ + WhereClause *pWC; /* Shorthand for pScan->pWC */ + WhereTerm *pTerm; /* The term being tested */ + int k = pScan->k; /* Where to start scanning */ + + while( pScan->iEquiv<=pScan->nEquiv ){ + iCur = pScan->aEquiv[pScan->iEquiv-2]; + iColumn = pScan->aEquiv[pScan->iEquiv-1]; + while( (pWC = pScan->pWC)!=0 ){ + for(pTerm=pWC->a+k; knTerm; k++, pTerm++){ + if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){ + if( (pTerm->eOperator & WO_EQUIV)!=0 + && pScan->nEquivaEquiv) + ){ + int j; + pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight); + assert( pX->op==TK_COLUMN ); + for(j=0; jnEquiv; j+=2){ + if( pScan->aEquiv[j]==pX->iTable + && pScan->aEquiv[j+1]==pX->iColumn ){ + break; + } + } + if( j==pScan->nEquiv ){ + pScan->aEquiv[j] = pX->iTable; + pScan->aEquiv[j+1] = pX->iColumn; + pScan->nEquiv += 2; + } + } + if( (pTerm->eOperator & pScan->opMask)!=0 ){ + /* Verify the affinity and collating sequence match */ + if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ + CollSeq *pColl; + Parse *pParse = pWC->pWInfo->pParse; + pX = pTerm->pExpr; + if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ + continue; + } + assert(pX->pLeft); + pColl = sqlite3BinaryCompareCollSeq(pParse, + pX->pLeft, pX->pRight); + if( pColl==0 ) pColl = pParse->db->pDfltColl; + if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ + continue; + } + } + if( (pTerm->eOperator & WO_EQ)!=0 + && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN + && pX->iTable==pScan->aEquiv[0] + && pX->iColumn==pScan->aEquiv[1] + ){ + continue; + } + pScan->k = k+1; + return pTerm; + } + } + } + pScan->pWC = pScan->pWC->pOuter; + k = 0; + } + pScan->pWC = pScan->pOrigWC; + k = 0; + pScan->iEquiv += 2; + } + return 0; +} + +/* +** Initialize a WHERE clause scanner object. Return a pointer to the +** first match. Return NULL if there are no matches. +** +** The scanner will be searching the WHERE clause pWC. It will look +** for terms of the form "X " where X is column iColumn of table +** iCur. The must be one of the operators described by opMask. +** +** If the search is for X and the WHERE clause contains terms of the +** form X=Y then this routine might also return terms of the form +** "Y ". The number of levels of transitivity is limited, +** but is enough to handle most commonly occurring SQL statements. +** +** If X is not the INTEGER PRIMARY KEY then X must be compatible with +** index pIdx. +*/ +static WhereTerm *whereScanInit( + WhereScan *pScan, /* The WhereScan object being initialized */ + WhereClause *pWC, /* The WHERE clause to be scanned */ + int iCur, /* Cursor to scan for */ + int iColumn, /* Column to scan for */ + u32 opMask, /* Operator(s) to scan for */ + Index *pIdx /* Must be compatible with this index */ +){ + int j; + + /* memset(pScan, 0, sizeof(*pScan)); */ + pScan->pOrigWC = pWC; + pScan->pWC = pWC; + if( pIdx && iColumn>=0 ){ + pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; + for(j=0; pIdx->aiColumn[j]!=iColumn; j++){ + if( NEVER(j>=pIdx->nColumn) ) return 0; + } + pScan->zCollName = pIdx->azColl[j]; + }else{ + pScan->idxaff = 0; + pScan->zCollName = 0; + } + pScan->opMask = opMask; + pScan->k = 0; + pScan->aEquiv[0] = iCur; + pScan->aEquiv[1] = iColumn; + pScan->nEquiv = 2; + pScan->iEquiv = 2; + return whereScanNext(pScan); +} + +/* +** Search for a term in the WHERE clause that is of the form "X " +** where X is a reference to the iColumn of table iCur and is one of +** the WO_xx operator codes specified by the op parameter. +** Return a pointer to the term. Return 0 if not found. +** +** The term returned might by Y= if there is another constraint in +** the WHERE clause that specifies that X=Y. Any such constraints will be +** identified by the WO_EQUIV bit in the pTerm->eOperator field. The +** aEquiv[] array holds X and all its equivalents, with each SQL variable +** taking up two slots in aEquiv[]. The first slot is for the cursor number +** and the second is for the column number. There are 22 slots in aEquiv[] +** so that means we can look for X plus up to 10 other equivalent values. +** Hence a search for X will return if X=A1 and A1=A2 and A2=A3 +** and ... and A9=A10 and A10=. +** +** If there are multiple terms in the WHERE clause of the form "X " +** then try for the one with no dependencies on - in other words where +** is a constant expression of some kind. Only return entries of +** the form "X Y" where Y is a column in another table if no terms of +** the form "X " exist. If no terms with a constant RHS +** exist, try to return a term that does not use WO_EQUIV. +*/ +static WhereTerm *findTerm( + WhereClause *pWC, /* The WHERE clause to be searched */ + int iCur, /* Cursor number of LHS */ + int iColumn, /* Column number of LHS */ + Bitmask notReady, /* RHS must not overlap with this mask */ + u32 op, /* Mask of WO_xx values describing operator */ + Index *pIdx /* Must be compatible with this index, if not NULL */ +){ + WhereTerm *pResult = 0; + WhereTerm *p; + WhereScan scan; + + p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx); + while( p ){ + if( (p->prereqRight & notReady)==0 ){ + if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){ + return p; + } + if( pResult==0 ) pResult = p; + } + p = whereScanNext(&scan); + } + return pResult; +} + +/* Forward reference */ +static void exprAnalyze(SrcList*, WhereClause*, int); + +/* +** Call exprAnalyze on all terms in a WHERE clause. +*/ +static void exprAnalyzeAll( + SrcList *pTabList, /* the FROM clause */ + WhereClause *pWC /* the WHERE clause to be analyzed */ +){ + int i; + for(i=pWC->nTerm-1; i>=0; i--){ + exprAnalyze(pTabList, pWC, i); + } +} + +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION +/* +** Check to see if the given expression is a LIKE or GLOB operator that +** can be optimized using inequality constraints. Return TRUE if it is +** so and false if not. +** +** In order for the operator to be optimizible, the RHS must be a string +** literal that does not begin with a wildcard. +*/ +static int isLikeOrGlob( + Parse *pParse, /* Parsing and code generating context */ + Expr *pExpr, /* Test this expression */ + Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */ + int *pisComplete, /* True if the only wildcard is % in the last character */ + int *pnoCase /* True if uppercase is equivalent to lowercase */ +){ + const char *z = 0; /* String on RHS of LIKE operator */ + Expr *pRight, *pLeft; /* Right and left size of LIKE operator */ + ExprList *pList; /* List of operands to the LIKE operator */ + int c; /* One character in z[] */ + int cnt; /* Number of non-wildcard prefix characters */ + char wc[3]; /* Wildcard characters */ + sqlite3 *db = pParse->db; /* Database connection */ + sqlite3_value *pVal = 0; + int op; /* Opcode of pRight */ + + if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){ + return 0; + } +#ifdef SQLITE_EBCDIC + if( *pnoCase ) return 0; +#endif + pList = pExpr->x.pList; + pLeft = pList->a[1].pExpr; + if( pLeft->op!=TK_COLUMN + || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT + || IsVirtual(pLeft->pTab) + ){ + /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must + ** be the name of an indexed column with TEXT affinity. */ + return 0; + } + assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */ + + pRight = pList->a[0].pExpr; + op = pRight->op; + if( op==TK_REGISTER ){ + op = pRight->op2; + } + if( op==TK_VARIABLE ){ + Vdbe *pReprepare = pParse->pReprepare; + int iCol = pRight->iColumn; + pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE); + if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ + z = (char *)sqlite3_value_text(pVal); + } + sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); + assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); + }else if( op==TK_STRING ){ + z = pRight->u.zToken; + } + if( z ){ + cnt = 0; + while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ + cnt++; + } + if( cnt!=0 && 255!=(u8)z[cnt-1] ){ + Expr *pPrefix; + *pisComplete = c==wc[0] && z[cnt+1]==0; + pPrefix = sqlite3Expr(db, TK_STRING, z); + if( pPrefix ) pPrefix->u.zToken[cnt] = 0; + *ppPrefix = pPrefix; + if( op==TK_VARIABLE ){ + Vdbe *v = pParse->pVdbe; + sqlite3VdbeSetVarmask(v, pRight->iColumn); + if( *pisComplete && pRight->u.zToken[1] ){ + /* If the rhs of the LIKE expression is a variable, and the current + ** value of the variable means there is no need to invoke the LIKE + ** function, then no OP_Variable will be added to the program. + ** This causes problems for the sqlite3_bind_parameter_name() + ** API. To workaround them, add a dummy OP_Variable here. + */ + int r1 = sqlite3GetTempReg(pParse); + sqlite3ExprCodeTarget(pParse, pRight, r1); + sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0); + sqlite3ReleaseTempReg(pParse, r1); + } + } + }else{ + z = 0; + } + } + + sqlite3ValueFree(pVal); + return (z!=0); +} +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ + + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Check to see if the given expression is of the form +** +** column MATCH expr +** +** If it is then return TRUE. If not, return FALSE. +*/ +static int isMatchOfColumn( + Expr *pExpr /* Test this expression */ +){ + ExprList *pList; + + if( pExpr->op!=TK_FUNCTION ){ + return 0; + } + if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){ + return 0; + } + pList = pExpr->x.pList; + if( pList->nExpr!=2 ){ + return 0; + } + if( pList->a[1].pExpr->op != TK_COLUMN ){ + return 0; + } + return 1; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** If the pBase expression originated in the ON or USING clause of +** a join, then transfer the appropriate markings over to derived. +*/ +static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ + if( pDerived ){ + pDerived->flags |= pBase->flags & EP_FromJoin; + pDerived->iRightJoinTable = pBase->iRightJoinTable; + } +} + +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) +/* +** Analyze a term that consists of two or more OR-connected +** subterms. So in: +** +** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13) +** ^^^^^^^^^^^^^^^^^^^^ +** +** This routine analyzes terms such as the middle term in the above example. +** A WhereOrTerm object is computed and attached to the term under +** analysis, regardless of the outcome of the analysis. Hence: +** +** WhereTerm.wtFlags |= TERM_ORINFO +** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object +** +** The term being analyzed must have two or more of OR-connected subterms. +** A single subterm might be a set of AND-connected sub-subterms. +** Examples of terms under analysis: +** +** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5 +** (B) x=expr1 OR expr2=x OR x=expr3 +** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15) +** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*') +** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6) +** +** CASE 1: +** +** If all subterms are of the form T.C=expr for some single column of C and +** a single table T (as shown in example B above) then create a new virtual +** term that is an equivalent IN expression. In other words, if the term +** being analyzed is: +** +** x = expr1 OR expr2 = x OR x = expr3 +** +** then create a new virtual term like this: +** +** x IN (expr1,expr2,expr3) +** +** CASE 2: +** +** If all subterms are indexable by a single table T, then set +** +** WhereTerm.eOperator = WO_OR +** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T +** +** A subterm is "indexable" if it is of the form +** "T.C " where C is any column of table T and +** is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN". +** A subterm is also indexable if it is an AND of two or more +** subsubterms at least one of which is indexable. Indexable AND +** subterms have their eOperator set to WO_AND and they have +** u.pAndInfo set to a dynamically allocated WhereAndTerm object. +** +** From another point of view, "indexable" means that the subterm could +** potentially be used with an index if an appropriate index exists. +** This analysis does not consider whether or not the index exists; that +** is decided elsewhere. This analysis only looks at whether subterms +** appropriate for indexing exist. +** +** All examples A through E above satisfy case 2. But if a term +** also statisfies case 1 (such as B) we know that the optimizer will +** always prefer case 1, so in that case we pretend that case 2 is not +** satisfied. +** +** It might be the case that multiple tables are indexable. For example, +** (E) above is indexable on tables P, Q, and R. +** +** Terms that satisfy case 2 are candidates for lookup by using +** separate indices to find rowids for each subterm and composing +** the union of all rowids using a RowSet object. This is similar +** to "bitmap indices" in other database engines. +** +** OTHERWISE: +** +** If neither case 1 nor case 2 apply, then leave the eOperator set to +** zero. This term is not useful for search. +*/ +static void exprAnalyzeOrTerm( + SrcList *pSrc, /* the FROM clause */ + WhereClause *pWC, /* the complete WHERE clause */ + int idxTerm /* Index of the OR-term to be analyzed */ +){ + WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ + Parse *pParse = pWInfo->pParse; /* Parser context */ + sqlite3 *db = pParse->db; /* Database connection */ + WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ + Expr *pExpr = pTerm->pExpr; /* The expression of the term */ + int i; /* Loop counters */ + WhereClause *pOrWc; /* Breakup of pTerm into subterms */ + WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */ + WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */ + Bitmask chngToIN; /* Tables that might satisfy case 1 */ + Bitmask indexable; /* Tables that are indexable, satisfying case 2 */ + + /* + ** Break the OR clause into its separate subterms. The subterms are + ** stored in a WhereClause structure containing within the WhereOrInfo + ** object that is attached to the original OR clause term. + */ + assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); + assert( pExpr->op==TK_OR ); + pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); + if( pOrInfo==0 ) return; + pTerm->wtFlags |= TERM_ORINFO; + pOrWc = &pOrInfo->wc; + whereClauseInit(pOrWc, pWInfo); + whereSplit(pOrWc, pExpr, TK_OR); + exprAnalyzeAll(pSrc, pOrWc); + if( db->mallocFailed ) return; + assert( pOrWc->nTerm>=2 ); + + /* + ** Compute the set of tables that might satisfy cases 1 or 2. + */ + indexable = ~(Bitmask)0; + chngToIN = ~(Bitmask)0; + for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){ + if( (pOrTerm->eOperator & WO_SINGLE)==0 ){ + WhereAndInfo *pAndInfo; + assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); + chngToIN = 0; + pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo)); + if( pAndInfo ){ + WhereClause *pAndWC; + WhereTerm *pAndTerm; + int j; + Bitmask b = 0; + pOrTerm->u.pAndInfo = pAndInfo; + pOrTerm->wtFlags |= TERM_ANDINFO; + pOrTerm->eOperator = WO_AND; + pAndWC = &pAndInfo->wc; + whereClauseInit(pAndWC, pWC->pWInfo); + whereSplit(pAndWC, pOrTerm->pExpr, TK_AND); + exprAnalyzeAll(pSrc, pAndWC); + pAndWC->pOuter = pWC; + testcase( db->mallocFailed ); + if( !db->mallocFailed ){ + for(j=0, pAndTerm=pAndWC->a; jnTerm; j++, pAndTerm++){ + assert( pAndTerm->pExpr ); + if( allowedOp(pAndTerm->pExpr->op) ){ + b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); + } + } + } + indexable &= b; + } + }else if( pOrTerm->wtFlags & TERM_COPIED ){ + /* Skip this term for now. We revisit it when we process the + ** corresponding TERM_VIRTUAL term */ + }else{ + Bitmask b; + b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); + if( pOrTerm->wtFlags & TERM_VIRTUAL ){ + WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; + b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor); + } + indexable &= b; + if( (pOrTerm->eOperator & WO_EQ)==0 ){ + chngToIN = 0; + }else{ + chngToIN &= b; + } + } + } + + /* + ** Record the set of tables that satisfy case 2. The set might be + ** empty. + */ + pOrInfo->indexable = indexable; + pTerm->eOperator = indexable==0 ? 0 : WO_OR; + + /* + ** chngToIN holds a set of tables that *might* satisfy case 1. But + ** we have to do some additional checking to see if case 1 really + ** is satisfied. + ** + ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means + ** that there is no possibility of transforming the OR clause into an + ** IN operator because one or more terms in the OR clause contain + ** something other than == on a column in the single table. The 1-bit + ** case means that every term of the OR clause is of the form + ** "table.column=expr" for some single table. The one bit that is set + ** will correspond to the common table. We still need to check to make + ** sure the same column is used on all terms. The 2-bit case is when + ** the all terms are of the form "table1.column=table2.column". It + ** might be possible to form an IN operator with either table1.column + ** or table2.column as the LHS if either is common to every term of + ** the OR clause. + ** + ** Note that terms of the form "table.column1=table.column2" (the + ** same table on both sizes of the ==) cannot be optimized. + */ + if( chngToIN ){ + int okToChngToIN = 0; /* True if the conversion to IN is valid */ + int iColumn = -1; /* Column index on lhs of IN operator */ + int iCursor = -1; /* Table cursor common to all terms */ + int j = 0; /* Loop counter */ + + /* Search for a table and column that appears on one side or the + ** other of the == operator in every subterm. That table and column + ** will be recorded in iCursor and iColumn. There might not be any + ** such table and column. Set okToChngToIN if an appropriate table + ** and column is found but leave okToChngToIN false if not found. + */ + for(j=0; j<2 && !okToChngToIN; j++){ + pOrTerm = pOrWc->a; + for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ + assert( pOrTerm->eOperator & WO_EQ ); + pOrTerm->wtFlags &= ~TERM_OR_OK; + if( pOrTerm->leftCursor==iCursor ){ + /* This is the 2-bit case and we are on the second iteration and + ** current term is from the first iteration. So skip this term. */ + assert( j==1 ); + continue; + } + if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){ + /* This term must be of the form t1.a==t2.b where t2 is in the + ** chngToIN set but t1 is not. This term will be either preceeded + ** or follwed by an inverted copy (t2.b==t1.a). Skip this term + ** and use its inversion. */ + testcase( pOrTerm->wtFlags & TERM_COPIED ); + testcase( pOrTerm->wtFlags & TERM_VIRTUAL ); + assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) ); + continue; + } + iColumn = pOrTerm->u.leftColumn; + iCursor = pOrTerm->leftCursor; + break; + } + if( i<0 ){ + /* No candidate table+column was found. This can only occur + ** on the second iteration */ + assert( j==1 ); + assert( IsPowerOfTwo(chngToIN) ); + assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) ); + break; + } + testcase( j==1 ); + + /* We have found a candidate table and column. Check to see if that + ** table and column is common to every term in the OR clause */ + okToChngToIN = 1; + for(; i>=0 && okToChngToIN; i--, pOrTerm++){ + assert( pOrTerm->eOperator & WO_EQ ); + if( pOrTerm->leftCursor!=iCursor ){ + pOrTerm->wtFlags &= ~TERM_OR_OK; + }else if( pOrTerm->u.leftColumn!=iColumn ){ + okToChngToIN = 0; + }else{ + int affLeft, affRight; + /* If the right-hand side is also a column, then the affinities + ** of both right and left sides must be such that no type + ** conversions are required on the right. (Ticket #2249) + */ + affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); + affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); + if( affRight!=0 && affRight!=affLeft ){ + okToChngToIN = 0; + }else{ + pOrTerm->wtFlags |= TERM_OR_OK; + } + } + } + } + + /* At this point, okToChngToIN is true if original pTerm satisfies + ** case 1. In that case, construct a new virtual term that is + ** pTerm converted into an IN operator. + */ + if( okToChngToIN ){ + Expr *pDup; /* A transient duplicate expression */ + ExprList *pList = 0; /* The RHS of the IN operator */ + Expr *pLeft = 0; /* The LHS of the IN operator */ + Expr *pNew; /* The complete IN operator */ + + for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ + if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue; + assert( pOrTerm->eOperator & WO_EQ ); + assert( pOrTerm->leftCursor==iCursor ); + assert( pOrTerm->u.leftColumn==iColumn ); + pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); + pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); + pLeft = pOrTerm->pExpr->pLeft; + } + assert( pLeft!=0 ); + pDup = sqlite3ExprDup(db, pLeft, 0); + pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0); + if( pNew ){ + int idxNew; + transferJoinMarkings(pNew, pExpr); + assert( !ExprHasProperty(pNew, EP_xIsSelect) ); + pNew->x.pList = pList; + idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew==0 ); + exprAnalyze(pSrc, pWC, idxNew); + pTerm = &pWC->a[idxTerm]; + pWC->a[idxNew].iParent = idxTerm; + pTerm->nChild = 1; + }else{ + sqlite3ExprListDelete(db, pList); + } + pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */ + } + } +} +#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ + +/* +** The input to this routine is an WhereTerm structure with only the +** "pExpr" field filled in. The job of this routine is to analyze the +** subexpression and populate all the other fields of the WhereTerm +** structure. +** +** If the expression is of the form " X" it gets commuted +** to the standard form of "X ". +** +** If the expression is of the form "X Y" where both X and Y are +** columns, then the original expression is unchanged and a new virtual +** term of the form "Y X" is added to the WHERE clause and +** analyzed separately. The original term is marked with TERM_COPIED +** and the new term is marked with TERM_DYNAMIC (because it's pExpr +** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it +** is a commuted copy of a prior term.) The original term has nChild=1 +** and the copy has idxParent set to the index of the original term. +*/ +static void exprAnalyze( + SrcList *pSrc, /* the FROM clause */ + WhereClause *pWC, /* the WHERE clause */ + int idxTerm /* Index of the term to be analyzed */ +){ + WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ + WhereTerm *pTerm; /* The term to be analyzed */ + WhereMaskSet *pMaskSet; /* Set of table index masks */ + Expr *pExpr; /* The expression to be analyzed */ + Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */ + Bitmask prereqAll; /* Prerequesites of pExpr */ + Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */ + Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */ + int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */ + int noCase = 0; /* LIKE/GLOB distinguishes case */ + int op; /* Top-level operator. pExpr->op */ + Parse *pParse = pWInfo->pParse; /* Parsing context */ + sqlite3 *db = pParse->db; /* Database connection */ + + if( db->mallocFailed ){ + return; + } + pTerm = &pWC->a[idxTerm]; + pMaskSet = &pWInfo->sMaskSet; + pExpr = pTerm->pExpr; + assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); + prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft); + op = pExpr->op; + if( op==TK_IN ){ + assert( pExpr->pRight==0 ); + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect); + }else{ + pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList); + } + }else if( op==TK_ISNULL ){ + pTerm->prereqRight = 0; + }else{ + pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight); + } + prereqAll = exprTableUsage(pMaskSet, pExpr); + if( ExprHasProperty(pExpr, EP_FromJoin) ){ + Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable); + prereqAll |= x; + extraRight = x-1; /* ON clause terms may not be used with an index + ** on left table of a LEFT JOIN. Ticket #3015 */ + } + pTerm->prereqAll = prereqAll; + pTerm->leftCursor = -1; + pTerm->iParent = -1; + pTerm->eOperator = 0; + if( allowedOp(op) ){ + Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); + Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); + u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; + if( pLeft->op==TK_COLUMN ){ + pTerm->leftCursor = pLeft->iTable; + pTerm->u.leftColumn = pLeft->iColumn; + pTerm->eOperator = operatorMask(op) & opMask; + } + if( pRight && pRight->op==TK_COLUMN ){ + WhereTerm *pNew; + Expr *pDup; + u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */ + if( pTerm->leftCursor>=0 ){ + int idxNew; + pDup = sqlite3ExprDup(db, pExpr, 0); + if( db->mallocFailed ){ + sqlite3ExprDelete(db, pDup); + return; + } + idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); + if( idxNew==0 ) return; + pNew = &pWC->a[idxNew]; + pNew->iParent = idxTerm; + pTerm = &pWC->a[idxTerm]; + pTerm->nChild = 1; + pTerm->wtFlags |= TERM_COPIED; + if( pExpr->op==TK_EQ + && !ExprHasProperty(pExpr, EP_FromJoin) + && OptimizationEnabled(db, SQLITE_Transitive) + ){ + pTerm->eOperator |= WO_EQUIV; + eExtraOp = WO_EQUIV; + } + }else{ + pDup = pExpr; + pNew = pTerm; + } + exprCommute(pParse, pDup); + pLeft = sqlite3ExprSkipCollate(pDup->pLeft); + pNew->leftCursor = pLeft->iTable; + pNew->u.leftColumn = pLeft->iColumn; + testcase( (prereqLeft | extraRight) != prereqLeft ); + pNew->prereqRight = prereqLeft | extraRight; + pNew->prereqAll = prereqAll; + pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask; + } + } + +#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION + /* If a term is the BETWEEN operator, create two new virtual terms + ** that define the range that the BETWEEN implements. For example: + ** + ** a BETWEEN b AND c + ** + ** is converted into: + ** + ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c) + ** + ** The two new terms are added onto the end of the WhereClause object. + ** The new terms are "dynamic" and are children of the original BETWEEN + ** term. That means that if the BETWEEN term is coded, the children are + ** skipped. Or, if the children are satisfied by an index, the original + ** BETWEEN term is skipped. + */ + else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){ + ExprList *pList = pExpr->x.pList; + int i; + static const u8 ops[] = {TK_GE, TK_LE}; + assert( pList!=0 ); + assert( pList->nExpr==2 ); + for(i=0; i<2; i++){ + Expr *pNewExpr; + int idxNew; + pNewExpr = sqlite3PExpr(pParse, ops[i], + sqlite3ExprDup(db, pExpr->pLeft, 0), + sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0); + transferJoinMarkings(pNewExpr, pExpr); + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew==0 ); + exprAnalyze(pSrc, pWC, idxNew); + pTerm = &pWC->a[idxTerm]; + pWC->a[idxNew].iParent = idxTerm; + } + pTerm->nChild = 2; + } +#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ + +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) + /* Analyze a term that is composed of two or more subterms connected by + ** an OR operator. + */ + else if( pExpr->op==TK_OR ){ + assert( pWC->op==TK_AND ); + exprAnalyzeOrTerm(pSrc, pWC, idxTerm); + pTerm = &pWC->a[idxTerm]; + } +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */ + +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION + /* Add constraints to reduce the search space on a LIKE or GLOB + ** operator. + ** + ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints + ** + ** x>='abc' AND x<'abd' AND x LIKE 'abc%' + ** + ** The last character of the prefix "abc" is incremented to form the + ** termination condition "abd". + */ + if( pWC->op==TK_AND + && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase) + ){ + Expr *pLeft; /* LHS of LIKE/GLOB operator */ + Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */ + Expr *pNewExpr1; + Expr *pNewExpr2; + int idxNew1; + int idxNew2; + Token sCollSeqName; /* Name of collating sequence */ + + pLeft = pExpr->x.pList->a[1].pExpr; + pStr2 = sqlite3ExprDup(db, pStr1, 0); + if( !db->mallocFailed ){ + u8 c, *pC; /* Last character before the first wildcard */ + pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; + c = *pC; + if( noCase ){ + /* The point is to increment the last character before the first + ** wildcard. But if we increment '@', that will push it into the + ** alphabetic range where case conversions will mess up the + ** inequality. To avoid this, make sure to also run the full + ** LIKE on all candidate expressions by clearing the isComplete flag + */ + if( c=='A'-1 ) isComplete = 0; + c = sqlite3UpperToLower[c]; + } + *pC = c + 1; + } + sCollSeqName.z = noCase ? "NOCASE" : "BINARY"; + sCollSeqName.n = 6; + pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); + pNewExpr1 = sqlite3PExpr(pParse, TK_GE, + sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName), + pStr1, 0); + transferJoinMarkings(pNewExpr1, pExpr); + idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew1==0 ); + exprAnalyze(pSrc, pWC, idxNew1); + pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); + pNewExpr2 = sqlite3PExpr(pParse, TK_LT, + sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName), + pStr2, 0); + transferJoinMarkings(pNewExpr2, pExpr); + idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew2==0 ); + exprAnalyze(pSrc, pWC, idxNew2); + pTerm = &pWC->a[idxTerm]; + if( isComplete ){ + pWC->a[idxNew1].iParent = idxTerm; + pWC->a[idxNew2].iParent = idxTerm; + pTerm->nChild = 2; + } + } +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE + /* Add a WO_MATCH auxiliary term to the constraint set if the + ** current expression is of the form: column MATCH expr. + ** This information is used by the xBestIndex methods of + ** virtual tables. The native query optimizer does not attempt + ** to do anything with MATCH functions. + */ + if( isMatchOfColumn(pExpr) ){ + int idxNew; + Expr *pRight, *pLeft; + WhereTerm *pNewTerm; + Bitmask prereqColumn, prereqExpr; + + pRight = pExpr->x.pList->a[0].pExpr; + pLeft = pExpr->x.pList->a[1].pExpr; + prereqExpr = exprTableUsage(pMaskSet, pRight); + prereqColumn = exprTableUsage(pMaskSet, pLeft); + if( (prereqExpr & prereqColumn)==0 ){ + Expr *pNewExpr; + pNewExpr = sqlite3PExpr(pParse, TK_MATCH, + 0, sqlite3ExprDup(db, pRight, 0), 0); + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew==0 ); + pNewTerm = &pWC->a[idxNew]; + pNewTerm->prereqRight = prereqExpr; + pNewTerm->leftCursor = pLeft->iTable; + pNewTerm->u.leftColumn = pLeft->iColumn; + pNewTerm->eOperator = WO_MATCH; + pNewTerm->iParent = idxTerm; + pTerm = &pWC->a[idxTerm]; + pTerm->nChild = 1; + pTerm->wtFlags |= TERM_COPIED; + pNewTerm->prereqAll = pTerm->prereqAll; + } + } +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + /* When sqlite_stat3 histogram data is available an operator of the + ** form "x IS NOT NULL" can sometimes be evaluated more efficiently + ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a + ** virtual term of that form. + ** + ** Note that the virtual term must be tagged with TERM_VNULL. This + ** TERM_VNULL tag will suppress the not-null check at the beginning + ** of the loop. Without the TERM_VNULL flag, the not-null check at + ** the start of the loop will prevent any results from being returned. + */ + if( pExpr->op==TK_NOTNULL + && pExpr->pLeft->op==TK_COLUMN + && pExpr->pLeft->iColumn>=0 + && OptimizationEnabled(db, SQLITE_Stat3) + ){ + Expr *pNewExpr; + Expr *pLeft = pExpr->pLeft; + int idxNew; + WhereTerm *pNewTerm; + + pNewExpr = sqlite3PExpr(pParse, TK_GT, + sqlite3ExprDup(db, pLeft, 0), + sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0); + + idxNew = whereClauseInsert(pWC, pNewExpr, + TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL); + if( idxNew ){ + pNewTerm = &pWC->a[idxNew]; + pNewTerm->prereqRight = 0; + pNewTerm->leftCursor = pLeft->iTable; + pNewTerm->u.leftColumn = pLeft->iColumn; + pNewTerm->eOperator = WO_GT; + pNewTerm->iParent = idxTerm; + pTerm = &pWC->a[idxTerm]; + pTerm->nChild = 1; + pTerm->wtFlags |= TERM_COPIED; + pNewTerm->prereqAll = pTerm->prereqAll; + } + } +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + + /* Prevent ON clause terms of a LEFT JOIN from being used to drive + ** an index for tables to the left of the join. + */ + pTerm->prereqRight |= extraRight; +} + +/* +** This function searches pList for a entry that matches the iCol-th column +** of index pIdx. +** +** If such an expression is found, its index in pList->a[] is returned. If +** no expression is found, -1 is returned. +*/ +static int findIndexCol( + Parse *pParse, /* Parse context */ + ExprList *pList, /* Expression list to search */ + int iBase, /* Cursor for table associated with pIdx */ + Index *pIdx, /* Index to match column of */ + int iCol /* Column of index to match */ +){ + int i; + const char *zColl = pIdx->azColl[iCol]; + + for(i=0; inExpr; i++){ + Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr); + if( p->op==TK_COLUMN + && p->iColumn==pIdx->aiColumn[iCol] + && p->iTable==iBase + ){ + CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr); + if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){ + return i; + } + } + } + + return -1; +} + +/* +** Return true if the DISTINCT expression-list passed as the third argument +** is redundant. +** +** A DISTINCT list is redundant if the database contains some subset of +** columns that are unique and non-null. +*/ +static int isDistinctRedundant( + Parse *pParse, /* Parsing context */ + SrcList *pTabList, /* The FROM clause */ + WhereClause *pWC, /* The WHERE clause */ + ExprList *pDistinct /* The result set that needs to be DISTINCT */ +){ + Table *pTab; + Index *pIdx; + int i; + int iBase; + + /* If there is more than one table or sub-select in the FROM clause of + ** this query, then it will not be possible to show that the DISTINCT + ** clause is redundant. */ + if( pTabList->nSrc!=1 ) return 0; + iBase = pTabList->a[0].iCursor; + pTab = pTabList->a[0].pTab; + + /* If any of the expressions is an IPK column on table iBase, then return + ** true. Note: The (p->iTable==iBase) part of this test may be false if the + ** current SELECT is a correlated sub-query. + */ + for(i=0; inExpr; i++){ + Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr); + if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1; + } + + /* Loop through all indices on the table, checking each to see if it makes + ** the DISTINCT qualifier redundant. It does so if: + ** + ** 1. The index is itself UNIQUE, and + ** + ** 2. All of the columns in the index are either part of the pDistinct + ** list, or else the WHERE clause contains a term of the form "col=X", + ** where X is a constant value. The collation sequences of the + ** comparison and select-list expressions must match those of the index. + ** + ** 3. All of those index columns for which the WHERE clause does not + ** contain a "col=X" term are subject to a NOT NULL constraint. + */ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->onError==OE_None ) continue; + for(i=0; inColumn; i++){ + int iCol = pIdx->aiColumn[i]; + if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){ + int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i); + if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){ + break; + } + } + } + if( i==pIdx->nColumn ){ + /* This index implies that the DISTINCT qualifier is redundant. */ + return 1; + } + } + + return 0; +} + + +/* +** Estimate the logarithm of the input value to base 2. +*/ +static LogEst estLog(LogEst N){ + LogEst x = sqlite3LogEst(N); + return x>33 ? x - 33 : 0; +} + +/* +** Two routines for printing the content of an sqlite3_index_info +** structure. Used for testing and debugging only. If neither +** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines +** are no-ops. +*/ +#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) +static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ + int i; + if( !sqlite3WhereTrace ) return; + for(i=0; inConstraint; i++){ + sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", + i, + p->aConstraint[i].iColumn, + p->aConstraint[i].iTermOffset, + p->aConstraint[i].op, + p->aConstraint[i].usable); + } + for(i=0; inOrderBy; i++){ + sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", + i, + p->aOrderBy[i].iColumn, + p->aOrderBy[i].desc); + } +} +static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ + int i; + if( !sqlite3WhereTrace ) return; + for(i=0; inConstraint; i++){ + sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", + i, + p->aConstraintUsage[i].argvIndex, + p->aConstraintUsage[i].omit); + } + sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); + sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); + sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); + sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); +} +#else +#define TRACE_IDX_INPUTS(A) +#define TRACE_IDX_OUTPUTS(A) +#endif + +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX +/* +** Return TRUE if the WHERE clause term pTerm is of a form where it +** could be used with an index to access pSrc, assuming an appropriate +** index existed. +*/ +static int termCanDriveIndex( + WhereTerm *pTerm, /* WHERE clause term to check */ + struct SrcList_item *pSrc, /* Table we are trying to access */ + Bitmask notReady /* Tables in outer loops of the join */ +){ + char aff; + if( pTerm->leftCursor!=pSrc->iCursor ) return 0; + if( (pTerm->eOperator & WO_EQ)==0 ) return 0; + if( (pTerm->prereqRight & notReady)!=0 ) return 0; + if( pTerm->u.leftColumn<0 ) return 0; + aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity; + if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; + return 1; +} +#endif + + +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX +/* +** Generate code to construct the Index object for an automatic index +** and to set up the WhereLevel object pLevel so that the code generator +** makes use of the automatic index. +*/ +static void constructAutomaticIndex( + Parse *pParse, /* The parsing context */ + WhereClause *pWC, /* The WHERE clause */ + struct SrcList_item *pSrc, /* The FROM clause term to get the next index */ + Bitmask notReady, /* Mask of cursors that are not available */ + WhereLevel *pLevel /* Write new index here */ +){ + int nColumn; /* Number of columns in the constructed index */ + WhereTerm *pTerm; /* A single term of the WHERE clause */ + WhereTerm *pWCEnd; /* End of pWC->a[] */ + int nByte; /* Byte of memory needed for pIdx */ + Index *pIdx; /* Object describing the transient index */ + Vdbe *v; /* Prepared statement under construction */ + int addrInit; /* Address of the initialization bypass jump */ + Table *pTable; /* The table being indexed */ + KeyInfo *pKeyinfo; /* Key information for the index */ + int addrTop; /* Top of the index fill loop */ + int regRecord; /* Register holding an index record */ + int n; /* Column counter */ + int i; /* Loop counter */ + int mxBitCol; /* Maximum column in pSrc->colUsed */ + CollSeq *pColl; /* Collating sequence to on a column */ + WhereLoop *pLoop; /* The Loop object */ + Bitmask idxCols; /* Bitmap of columns used for indexing */ + Bitmask extraCols; /* Bitmap of additional columns */ + u8 sentWarning = 0; /* True if a warnning has been issued */ + + /* Generate code to skip over the creation and initialization of the + ** transient index on 2nd and subsequent iterations of the loop. */ + v = pParse->pVdbe; + assert( v!=0 ); + addrInit = sqlite3CodeOnce(pParse); + + /* Count the number of columns that will be added to the index + ** and used to match WHERE clause constraints */ + nColumn = 0; + pTable = pSrc->pTab; + pWCEnd = &pWC->a[pWC->nTerm]; + pLoop = pLevel->pWLoop; + idxCols = 0; + for(pTerm=pWC->a; pTermu.leftColumn; + Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); + testcase( iCol==BMS ); + testcase( iCol==BMS-1 ); + if( !sentWarning ){ + sqlite3_log(SQLITE_WARNING_AUTOINDEX, + "automatic index on %s(%s)", pTable->zName, + pTable->aCol[iCol].zName); + sentWarning = 1; + } + if( (idxCols & cMask)==0 ){ + if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return; + pLoop->aLTerm[nColumn++] = pTerm; + idxCols |= cMask; + } + } + } + assert( nColumn>0 ); + pLoop->u.btree.nEq = pLoop->nLTerm = nColumn; + pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED + | WHERE_AUTO_INDEX; + + /* Count the number of additional columns needed to create a + ** covering index. A "covering index" is an index that contains all + ** columns that are needed by the query. With a covering index, the + ** original table never needs to be accessed. Automatic indices must + ** be a covering index because the index will not be updated if the + ** original table changes and the index and table cannot both be used + ** if they go out of sync. + */ + extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); + mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol; + testcase( pTable->nCol==BMS-1 ); + testcase( pTable->nCol==BMS-2 ); + for(i=0; icolUsed & MASKBIT(BMS-1) ){ + nColumn += pTable->nCol - BMS + 1; + } + pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY; + + /* Construct the Index object to describe this index */ + nByte = sizeof(Index); + nByte += nColumn*sizeof(int); /* Index.aiColumn */ + nByte += nColumn*sizeof(char*); /* Index.azColl */ + nByte += nColumn; /* Index.aSortOrder */ + pIdx = sqlite3DbMallocZero(pParse->db, nByte); + if( pIdx==0 ) return; + pLoop->u.btree.pIndex = pIdx; + pIdx->azColl = (char**)&pIdx[1]; + pIdx->aiColumn = (int*)&pIdx->azColl[nColumn]; + pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn]; + pIdx->zName = "auto-index"; + pIdx->nColumn = nColumn; + pIdx->pTable = pTable; + n = 0; + idxCols = 0; + for(pTerm=pWC->a; pTermu.leftColumn; + Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); + testcase( iCol==BMS-1 ); + testcase( iCol==BMS ); + if( (idxCols & cMask)==0 ){ + Expr *pX = pTerm->pExpr; + idxCols |= cMask; + pIdx->aiColumn[n] = pTerm->u.leftColumn; + pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); + pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY"; + n++; + } + } + } + assert( (u32)n==pLoop->u.btree.nEq ); + + /* Add additional columns needed to make the automatic index into + ** a covering index */ + for(i=0; iaiColumn[n] = i; + pIdx->azColl[n] = "BINARY"; + n++; + } + } + if( pSrc->colUsed & MASKBIT(BMS-1) ){ + for(i=BMS-1; inCol; i++){ + pIdx->aiColumn[n] = i; + pIdx->azColl[n] = "BINARY"; + n++; + } + } + assert( n==nColumn ); + + /* Create the automatic index */ + pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx); + assert( pLevel->iIdxCur>=0 ); + pLevel->iIdxCur = pParse->nTab++; + sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0, + (char*)pKeyinfo, P4_KEYINFO_HANDOFF); + VdbeComment((v, "for %s", pTable->zName)); + + /* Fill the automatic index with content */ + addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); + regRecord = sqlite3GetTempReg(pParse); + sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0); + sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); + sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); + sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); + sqlite3VdbeJumpHere(v, addrTop); + sqlite3ReleaseTempReg(pParse, regRecord); + + /* Jump here when skipping the initialization */ + sqlite3VdbeJumpHere(v, addrInit); +} +#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Allocate and populate an sqlite3_index_info structure. It is the +** responsibility of the caller to eventually release the structure +** by passing the pointer returned by this function to sqlite3_free(). +*/ +static sqlite3_index_info *allocateIndexInfo( + Parse *pParse, + WhereClause *pWC, + struct SrcList_item *pSrc, + ExprList *pOrderBy +){ + int i, j; + int nTerm; + struct sqlite3_index_constraint *pIdxCons; + struct sqlite3_index_orderby *pIdxOrderBy; + struct sqlite3_index_constraint_usage *pUsage; + WhereTerm *pTerm; + int nOrderBy; + sqlite3_index_info *pIdxInfo; + + /* Count the number of possible WHERE clause constraints referring + ** to this virtual table */ + for(i=nTerm=0, pTerm=pWC->a; inTerm; i++, pTerm++){ + if( pTerm->leftCursor != pSrc->iCursor ) continue; + assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); + testcase( pTerm->eOperator & WO_IN ); + testcase( pTerm->eOperator & WO_ISNULL ); + if( pTerm->eOperator & (WO_ISNULL) ) continue; + if( pTerm->wtFlags & TERM_VNULL ) continue; + nTerm++; + } + + /* If the ORDER BY clause contains only columns in the current + ** virtual table then allocate space for the aOrderBy part of + ** the sqlite3_index_info structure. + */ + nOrderBy = 0; + if( pOrderBy ){ + int n = pOrderBy->nExpr; + for(i=0; ia[i].pExpr; + if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; + } + if( i==n){ + nOrderBy = n; + } + } + + /* Allocate the sqlite3_index_info structure + */ + pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) + + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm + + sizeof(*pIdxOrderBy)*nOrderBy ); + if( pIdxInfo==0 ){ + sqlite3ErrorMsg(pParse, "out of memory"); + return 0; + } + + /* Initialize the structure. The sqlite3_index_info structure contains + ** many fields that are declared "const" to prevent xBestIndex from + ** changing them. We have to do some funky casting in order to + ** initialize those fields. + */ + pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1]; + pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; + pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; + *(int*)&pIdxInfo->nConstraint = nTerm; + *(int*)&pIdxInfo->nOrderBy = nOrderBy; + *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; + *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; + *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = + pUsage; + + for(i=j=0, pTerm=pWC->a; inTerm; i++, pTerm++){ + u8 op; + if( pTerm->leftCursor != pSrc->iCursor ) continue; + assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); + testcase( pTerm->eOperator & WO_IN ); + testcase( pTerm->eOperator & WO_ISNULL ); + if( pTerm->eOperator & (WO_ISNULL) ) continue; + if( pTerm->wtFlags & TERM_VNULL ) continue; + pIdxCons[j].iColumn = pTerm->u.leftColumn; + pIdxCons[j].iTermOffset = i; + op = (u8)pTerm->eOperator & WO_ALL; + if( op==WO_IN ) op = WO_EQ; + pIdxCons[j].op = op; + /* The direct assignment in the previous line is possible only because + ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The + ** following asserts verify this fact. */ + assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); + assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); + assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); + assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); + assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); + assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); + assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) ); + j++; + } + for(i=0; ia[i].pExpr; + pIdxOrderBy[i].iColumn = pExpr->iColumn; + pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder; + } + + return pIdxInfo; +} + +/* +** The table object reference passed as the second argument to this function +** must represent a virtual table. This function invokes the xBestIndex() +** method of the virtual table with the sqlite3_index_info object that +** comes in as the 3rd argument to this function. +** +** If an error occurs, pParse is populated with an error message and a +** non-zero value is returned. Otherwise, 0 is returned and the output +** part of the sqlite3_index_info structure is left populated. +** +** Whether or not an error is returned, it is the responsibility of the +** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates +** that this is required. +*/ +static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ + sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; + int i; + int rc; + + TRACE_IDX_INPUTS(p); + rc = pVtab->pModule->xBestIndex(pVtab, p); + TRACE_IDX_OUTPUTS(p); + + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM ){ + pParse->db->mallocFailed = 1; + }else if( !pVtab->zErrMsg ){ + sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); + }else{ + sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); + } + } + sqlite3_free(pVtab->zErrMsg); + pVtab->zErrMsg = 0; + + for(i=0; inConstraint; i++){ + if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ + sqlite3ErrorMsg(pParse, + "table %s: xBestIndex returned an invalid plan", pTab->zName); + } + } + + return pParse->nErr; +} +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ + + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Estimate the location of a particular key among all keys in an +** index. Store the results in aStat as follows: +** +** aStat[0] Est. number of rows less than pVal +** aStat[1] Est. number of rows equal to pVal +** +** Return SQLITE_OK on success. +*/ +static void whereKeyStats( + Parse *pParse, /* Database connection */ + Index *pIdx, /* Index to consider domain of */ + UnpackedRecord *pRec, /* Vector of values to consider */ + int roundUp, /* Round up if true. Round down if false */ + tRowcnt *aStat /* OUT: stats written here */ +){ + IndexSample *aSample = pIdx->aSample; + int iCol; /* Index of required stats in anEq[] etc. */ + int iMin = 0; /* Smallest sample not yet tested */ + int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */ + int iTest; /* Next sample to test */ + int res; /* Result of comparison operation */ + +#ifndef SQLITE_DEBUG + UNUSED_PARAMETER( pParse ); +#endif + assert( pRec!=0 || pParse->db->mallocFailed ); + if( pRec==0 ) return; + iCol = pRec->nField - 1; + assert( pIdx->nSample>0 ); + assert( pRec->nField>0 && iColnSampleCol ); + do{ + iTest = (iMin+i)/2; + res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec); + if( res<0 ){ + iMin = iTest+1; + }else{ + i = iTest; + } + }while( res && iMinnSample ); + assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) + || pParse->db->mallocFailed ); + }else{ + /* Otherwise, pRec must be smaller than sample $i and larger than + ** sample ($i-1). */ + assert( i==pIdx->nSample + || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 + || pParse->db->mallocFailed ); + assert( i==0 + || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 + || pParse->db->mallocFailed ); + } +#endif /* ifdef SQLITE_DEBUG */ + + /* At this point, aSample[i] is the first sample that is greater than + ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less + ** than pVal. If aSample[i]==pVal, then res==0. + */ + if( res==0 ){ + aStat[0] = aSample[i].anLt[iCol]; + aStat[1] = aSample[i].anEq[iCol]; + }else{ + tRowcnt iLower, iUpper, iGap; + if( i==0 ){ + iLower = 0; + iUpper = aSample[0].anLt[iCol]; + }else{ + iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol]; + iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol]; + } + aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1); + if( iLower>=iUpper ){ + iGap = 0; + }else{ + iGap = iUpper - iLower; + } + if( roundUp ){ + iGap = (iGap*2)/3; + }else{ + iGap = iGap/3; + } + aStat[0] = iLower + iGap; + } +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +/* +** This function is used to estimate the number of rows that will be visited +** by scanning an index for a range of values. The range may have an upper +** bound, a lower bound, or both. The WHERE clause terms that set the upper +** and lower bounds are represented by pLower and pUpper respectively. For +** example, assuming that index p is on t1(a): +** +** ... FROM t1 WHERE a > ? AND a < ? ... +** |_____| |_____| +** | | +** pLower pUpper +** +** If either of the upper or lower bound is not present, then NULL is passed in +** place of the corresponding WhereTerm. +** +** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index +** column subject to the range constraint. Or, equivalently, the number of +** equality constraints optimized by the proposed index scan. For example, +** assuming index p is on t1(a, b), and the SQL query is: +** +** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... +** +** then nEq is set to 1 (as the range restricted column, b, is the second +** left-most column of the index). Or, if the query is: +** +** ... FROM t1 WHERE a > ? AND a < ? ... +** +** then nEq is set to 0. +** +** When this function is called, *pnOut is set to the sqlite3LogEst() of the +** number of rows that the index scan is expected to visit without +** considering the range constraints. If nEq is 0, this is the number of +** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) +** to account for the range contraints pLower and pUpper. +** +** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be +** used, each range inequality reduces the search space by a factor of 4. +** Hence a pair of constraints (x>? AND x123" Might be NULL */ + WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ + WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ +){ + int rc = SQLITE_OK; + int nOut = pLoop->nOut; + LogEst nNew; + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + Index *p = pLoop->u.btree.pIndex; + int nEq = pLoop->u.btree.nEq; + + if( p->nSample>0 + && nEq==pBuilder->nRecValid + && nEqnSampleCol + && OptimizationEnabled(pParse->db, SQLITE_Stat3) + ){ + UnpackedRecord *pRec = pBuilder->pRec; + tRowcnt a[2]; + u8 aff; + + /* Variable iLower will be set to the estimate of the number of rows in + ** the index that are less than the lower bound of the range query. The + ** lower bound being the concatenation of $P and $L, where $P is the + ** key-prefix formed by the nEq values matched against the nEq left-most + ** columns of the index, and $L is the value in pLower. + ** + ** Or, if pLower is NULL or $L cannot be extracted from it (because it + ** is not a simple variable or literal value), the lower bound of the + ** range is $P. Due to a quirk in the way whereKeyStats() works, even + ** if $L is available, whereKeyStats() is called for both ($P) and + ** ($P:$L) and the larger of the two returned values used. + ** + ** Similarly, iUpper is to be set to the estimate of the number of rows + ** less than the upper bound of the range query. Where the upper bound + ** is either ($P) or ($P:$U). Again, even if $U is available, both values + ** of iUpper are requested of whereKeyStats() and the smaller used. + */ + tRowcnt iLower; + tRowcnt iUpper; + + if( nEq==p->nColumn ){ + aff = SQLITE_AFF_INTEGER; + }else{ + aff = p->pTable->aCol[p->aiColumn[nEq]].affinity; + } + /* Determine iLower and iUpper using ($P) only. */ + if( nEq==0 ){ + iLower = 0; + iUpper = p->aiRowEst[0]; + }else{ + /* Note: this call could be optimized away - since the same values must + ** have been requested when testing key $P in whereEqualScanEst(). */ + whereKeyStats(pParse, p, pRec, 0, a); + iLower = a[0]; + iUpper = a[0] + a[1]; + } + + /* If possible, improve on the iLower estimate using ($P:$L). */ + if( pLower ){ + int bOk; /* True if value is extracted from pExpr */ + Expr *pExpr = pLower->pExpr->pRight; + assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 ); + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); + if( rc==SQLITE_OK && bOk ){ + tRowcnt iNew; + whereKeyStats(pParse, p, pRec, 0, a); + iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0); + if( iNew>iLower ) iLower = iNew; + nOut--; + } + } + + /* If possible, improve on the iUpper estimate using ($P:$U). */ + if( pUpper ){ + int bOk; /* True if value is extracted from pExpr */ + Expr *pExpr = pUpper->pExpr->pRight; + assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); + if( rc==SQLITE_OK && bOk ){ + tRowcnt iNew; + whereKeyStats(pParse, p, pRec, 1, a); + iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0); + if( iNewpRec = pRec; + if( rc==SQLITE_OK ){ + if( iUpper>iLower ){ + nNew = sqlite3LogEst(iUpper - iLower); + }else{ + nNew = 10; assert( 10==sqlite3LogEst(2) ); + } + if( nNewnOut = (LogEst)nOut; + WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n", + (u32)iLower, (u32)iUpper, nOut)); + return SQLITE_OK; + } + } +#else + UNUSED_PARAMETER(pParse); + UNUSED_PARAMETER(pBuilder); +#endif + assert( pLower || pUpper ); + /* TUNING: Each inequality constraint reduces the search space 4-fold. + ** A BETWEEN operator, therefore, reduces the search space 16-fold */ + nNew = nOut; + if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){ + nNew -= 20; assert( 20==sqlite3LogEst(4) ); + nOut--; + } + if( pUpper ){ + nNew -= 20; assert( 20==sqlite3LogEst(4) ); + nOut--; + } + if( nNew<10 ) nNew = 10; + if( nNewnOut = (LogEst)nOut; + return rc; +} + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Estimate the number of rows that will be returned based on +** an equality constraint x=VALUE and where that VALUE occurs in +** the histogram data. This only works when x is the left-most +** column of an index and sqlite_stat3 histogram data is available +** for that index. When pExpr==NULL that means the constraint is +** "x IS NULL" instead of "x=VALUE". +** +** Write the estimated row count into *pnRow and return SQLITE_OK. +** If unable to make an estimate, leave *pnRow unchanged and return +** non-zero. +** +** This routine can fail if it is unable to load a collating sequence +** required for string comparison, or if unable to allocate memory +** for a UTF conversion required for comparison. The error is stored +** in the pParse structure. +*/ +static int whereEqualScanEst( + Parse *pParse, /* Parsing & code generating context */ + WhereLoopBuilder *pBuilder, + Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */ + tRowcnt *pnRow /* Write the revised row estimate here */ +){ + Index *p = pBuilder->pNew->u.btree.pIndex; + int nEq = pBuilder->pNew->u.btree.nEq; + UnpackedRecord *pRec = pBuilder->pRec; + u8 aff; /* Column affinity */ + int rc; /* Subfunction return code */ + tRowcnt a[2]; /* Statistics */ + int bOk; + + assert( nEq>=1 ); + assert( nEq<=(p->nColumn+1) ); + assert( p->aSample!=0 ); + assert( p->nSample>0 ); + assert( pBuilder->nRecValidnRecValid<(nEq-1) ){ + return SQLITE_NOTFOUND; + } + + /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() + ** below would return the same value. */ + if( nEq>p->nColumn ){ + *pnRow = 1; + return SQLITE_OK; + } + + aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity; + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk); + pBuilder->pRec = pRec; + if( rc!=SQLITE_OK ) return rc; + if( bOk==0 ) return SQLITE_NOTFOUND; + pBuilder->nRecValid = nEq; + + whereKeyStats(pParse, p, pRec, 0, a); + WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1])); + *pnRow = a[1]; + + return rc; +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Estimate the number of rows that will be returned based on +** an IN constraint where the right-hand side of the IN operator +** is a list of values. Example: +** +** WHERE x IN (1,2,3,4) +** +** Write the estimated row count into *pnRow and return SQLITE_OK. +** If unable to make an estimate, leave *pnRow unchanged and return +** non-zero. +** +** This routine can fail if it is unable to load a collating sequence +** required for string comparison, or if unable to allocate memory +** for a UTF conversion required for comparison. The error is stored +** in the pParse structure. +*/ +static int whereInScanEst( + Parse *pParse, /* Parsing & code generating context */ + WhereLoopBuilder *pBuilder, + ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */ + tRowcnt *pnRow /* Write the revised row estimate here */ +){ + Index *p = pBuilder->pNew->u.btree.pIndex; + int nRecValid = pBuilder->nRecValid; + int rc = SQLITE_OK; /* Subfunction return code */ + tRowcnt nEst; /* Number of rows for a single term */ + tRowcnt nRowEst = 0; /* New estimate of the number of rows */ + int i; /* Loop counter */ + + assert( p->aSample!=0 ); + for(i=0; rc==SQLITE_OK && inExpr; i++){ + nEst = p->aiRowEst[0]; + rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst); + nRowEst += nEst; + pBuilder->nRecValid = nRecValid; + } + + if( rc==SQLITE_OK ){ + if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0]; + *pnRow = nRowEst; + WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst)); + } + assert( pBuilder->nRecValid==nRecValid ); + return rc; +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +/* +** Disable a term in the WHERE clause. Except, do not disable the term +** if it controls a LEFT OUTER JOIN and it did not originate in the ON +** or USING clause of that join. +** +** Consider the term t2.z='ok' in the following queries: +** +** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' +** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' +** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' +** +** The t2.z='ok' is disabled in the in (2) because it originates +** in the ON clause. The term is disabled in (3) because it is not part +** of a LEFT OUTER JOIN. In (1), the term is not disabled. +** +** Disabling a term causes that term to not be tested in the inner loop +** of the join. Disabling is an optimization. When terms are satisfied +** by indices, we disable them to prevent redundant tests in the inner +** loop. We would get the correct results if nothing were ever disabled, +** but joins might run a little slower. The trick is to disable as much +** as we can without disabling too much. If we disabled in (1), we'd get +** the wrong answer. See ticket #813. +*/ +static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ + if( pTerm + && (pTerm->wtFlags & TERM_CODED)==0 + && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) + && (pLevel->notReady & pTerm->prereqAll)==0 + ){ + pTerm->wtFlags |= TERM_CODED; + if( pTerm->iParent>=0 ){ + WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent]; + if( (--pOther->nChild)==0 ){ + disableTerm(pLevel, pOther); + } + } + } +} + +/* +** Code an OP_Affinity opcode to apply the column affinity string zAff +** to the n registers starting at base. +** +** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the +** beginning and end of zAff are ignored. If all entries in zAff are +** SQLITE_AFF_NONE, then no code gets generated. +** +** This routine makes its own copy of zAff so that the caller is free +** to modify zAff after this routine returns. +*/ +static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ + Vdbe *v = pParse->pVdbe; + if( zAff==0 ){ + assert( pParse->db->mallocFailed ); + return; + } + assert( v!=0 ); + + /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning + ** and end of the affinity string. + */ + while( n>0 && zAff[0]==SQLITE_AFF_NONE ){ + n--; + base++; + zAff++; + } + while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){ + n--; + } + + /* Code the OP_Affinity opcode if there is anything left to do. */ + if( n>0 ){ + sqlite3VdbeAddOp2(v, OP_Affinity, base, n); + sqlite3VdbeChangeP4(v, -1, zAff, n); + sqlite3ExprCacheAffinityChange(pParse, base, n); + } +} + + +/* +** Generate code for a single equality term of the WHERE clause. An equality +** term can be either X=expr or X IN (...). pTerm is the term to be +** coded. +** +** The current value for the constraint is left in register iReg. +** +** For a constraint of the form X=expr, the expression is evaluated and its +** result is left on the stack. For constraints of the form X IN (...) +** this routine sets up a loop that will iterate over all values of X. +*/ +static int codeEqualityTerm( + Parse *pParse, /* The parsing context */ + WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ + WhereLevel *pLevel, /* The level of the FROM clause we are working on */ + int iEq, /* Index of the equality term within this level */ + int bRev, /* True for reverse-order IN operations */ + int iTarget /* Attempt to leave results in this register */ +){ + Expr *pX = pTerm->pExpr; + Vdbe *v = pParse->pVdbe; + int iReg; /* Register holding results */ + + assert( iTarget>0 ); + if( pX->op==TK_EQ ){ + iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); + }else if( pX->op==TK_ISNULL ){ + iReg = iTarget; + sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); +#ifndef SQLITE_OMIT_SUBQUERY + }else{ + int eType; + int iTab; + struct InLoop *pIn; + WhereLoop *pLoop = pLevel->pWLoop; + + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 + && pLoop->u.btree.pIndex!=0 + && pLoop->u.btree.pIndex->aSortOrder[iEq] + ){ + testcase( iEq==0 ); + testcase( bRev ); + bRev = !bRev; + } + assert( pX->op==TK_IN ); + iReg = iTarget; + eType = sqlite3FindInIndex(pParse, pX, 0); + if( eType==IN_INDEX_INDEX_DESC ){ + testcase( bRev ); + bRev = !bRev; + } + iTab = pX->iTable; + sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); + assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); + pLoop->wsFlags |= WHERE_IN_ABLE; + if( pLevel->u.in.nIn==0 ){ + pLevel->addrNxt = sqlite3VdbeMakeLabel(v); + } + pLevel->u.in.nIn++; + pLevel->u.in.aInLoop = + sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, + sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); + pIn = pLevel->u.in.aInLoop; + if( pIn ){ + pIn += pLevel->u.in.nIn - 1; + pIn->iCur = iTab; + if( eType==IN_INDEX_ROWID ){ + pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg); + }else{ + pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg); + } + pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next; + sqlite3VdbeAddOp1(v, OP_IsNull, iReg); + }else{ + pLevel->u.in.nIn = 0; + } +#endif + } + disableTerm(pLevel, pTerm); + return iReg; +} + +/* +** Generate code that will evaluate all == and IN constraints for an +** index. +** +** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). +** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 +** The index has as many as three equality constraints, but in this +** example, the third "c" value is an inequality. So only two +** constraints are coded. This routine will generate code to evaluate +** a==5 and b IN (1,2,3). The current values for a and b will be stored +** in consecutive registers and the index of the first register is returned. +** +** In the example above nEq==2. But this subroutine works for any value +** of nEq including 0. If nEq==0, this routine is nearly a no-op. +** The only thing it does is allocate the pLevel->iMem memory cell and +** compute the affinity string. +** +** This routine always allocates at least one memory cell and returns +** the index of that memory cell. The code that +** calls this routine will use that memory cell to store the termination +** key value of the loop. If one or more IN operators appear, then +** this routine allocates an additional nEq memory cells for internal +** use. +** +** Before returning, *pzAff is set to point to a buffer containing a +** copy of the column affinity string of the index allocated using +** sqlite3DbMalloc(). Except, entries in the copy of the string associated +** with equality constraints that use NONE affinity are set to +** SQLITE_AFF_NONE. This is to deal with SQL such as the following: +** +** CREATE TABLE t1(a TEXT PRIMARY KEY, b); +** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; +** +** In the example above, the index on t1(a) has TEXT affinity. But since +** the right hand side of the equality constraint (t2.b) has NONE affinity, +** no conversion should be attempted before using a t2.b value as part of +** a key to search the index. Hence the first byte in the returned affinity +** string in this example would be set to SQLITE_AFF_NONE. +*/ +static int codeAllEqualityTerms( + Parse *pParse, /* Parsing context */ + WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ + int bRev, /* Reverse the order of IN operators */ + int nExtraReg, /* Number of extra registers to allocate */ + char **pzAff /* OUT: Set to point to affinity string */ +){ + int nEq; /* The number of == or IN constraints to code */ + Vdbe *v = pParse->pVdbe; /* The vm under construction */ + Index *pIdx; /* The index being used for this loop */ + WhereTerm *pTerm; /* A single constraint term */ + WhereLoop *pLoop; /* The WhereLoop object */ + int j; /* Loop counter */ + int regBase; /* Base register */ + int nReg; /* Number of registers to allocate */ + char *zAff; /* Affinity string to return */ + + /* This module is only called on query plans that use an index. */ + pLoop = pLevel->pWLoop; + assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); + nEq = pLoop->u.btree.nEq; + pIdx = pLoop->u.btree.pIndex; + assert( pIdx!=0 ); + + /* Figure out how many memory cells we will need then allocate them. + */ + regBase = pParse->nMem + 1; + nReg = pLoop->u.btree.nEq + nExtraReg; + pParse->nMem += nReg; + + zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx)); + if( !zAff ){ + pParse->db->mallocFailed = 1; + } + + /* Evaluate the equality constraints + */ + assert( zAff==0 || (int)strlen(zAff)>=nEq ); + for(j=0; jaLTerm[j]; + assert( pTerm!=0 ); + /* The following true for indices with redundant columns. + ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ + testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); + testcase( pTerm->wtFlags & TERM_VIRTUAL ); + r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); + if( r1!=regBase+j ){ + if( nReg==1 ){ + sqlite3ReleaseTempReg(pParse, regBase); + regBase = r1; + }else{ + sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); + } + } + testcase( pTerm->eOperator & WO_ISNULL ); + testcase( pTerm->eOperator & WO_IN ); + if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ + Expr *pRight = pTerm->pExpr->pRight; + sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk); + if( zAff ){ + if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){ + zAff[j] = SQLITE_AFF_NONE; + } + if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ + zAff[j] = SQLITE_AFF_NONE; + } + } + } + } + *pzAff = zAff; + return regBase; +} + +#ifndef SQLITE_OMIT_EXPLAIN +/* +** This routine is a helper for explainIndexRange() below +** +** pStr holds the text of an expression that we are building up one term +** at a time. This routine adds a new term to the end of the expression. +** Terms are separated by AND so add the "AND" text for second and subsequent +** terms only. +*/ +static void explainAppendTerm( + StrAccum *pStr, /* The text expression being built */ + int iTerm, /* Index of this term. First is zero */ + const char *zColumn, /* Name of the column */ + const char *zOp /* Name of the operator */ +){ + if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5); + sqlite3StrAccumAppend(pStr, zColumn, -1); + sqlite3StrAccumAppend(pStr, zOp, 1); + sqlite3StrAccumAppend(pStr, "?", 1); +} + +/* +** Argument pLevel describes a strategy for scanning table pTab. This +** function returns a pointer to a string buffer containing a description +** of the subset of table rows scanned by the strategy in the form of an +** SQL expression. Or, if all rows are scanned, NULL is returned. +** +** For example, if the query: +** +** SELECT * FROM t1 WHERE a=1 AND b>2; +** +** is run and there is an index on (a, b), then this function returns a +** string similar to: +** +** "a=? AND b>?" +** +** The returned pointer points to memory obtained from sqlite3DbMalloc(). +** It is the responsibility of the caller to free the buffer when it is +** no longer required. +*/ +static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){ + Index *pIndex = pLoop->u.btree.pIndex; + int nEq = pLoop->u.btree.nEq; + int i, j; + Column *aCol = pTab->aCol; + int *aiColumn = pIndex->aiColumn; + StrAccum txt; + + if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){ + return 0; + } + sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH); + txt.db = db; + sqlite3StrAccumAppend(&txt, " (", 2); + for(i=0; inColumn ) ? "rowid" : aCol[aiColumn[i]].zName; + explainAppendTerm(&txt, i, z, "="); + } + + j = i; + if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ + char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName; + explainAppendTerm(&txt, i++, z, ">"); + } + if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ + char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName; + explainAppendTerm(&txt, i, z, "<"); + } + sqlite3StrAccumAppend(&txt, ")", 1); + return sqlite3StrAccumFinish(&txt); +} + +/* +** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN +** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single +** record is added to the output to describe the table scan strategy in +** pLevel. +*/ +static void explainOneScan( + Parse *pParse, /* Parse context */ + SrcList *pTabList, /* Table list this loop refers to */ + WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ + int iLevel, /* Value for "level" column of output */ + int iFrom, /* Value for "from" column of output */ + u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ +){ + if( pParse->explain==2 ){ + struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; + Vdbe *v = pParse->pVdbe; /* VM being constructed */ + sqlite3 *db = pParse->db; /* Database handle */ + char *zMsg; /* Text to add to EQP output */ + int iId = pParse->iSelectId; /* Select id (left-most output column) */ + int isSearch; /* True for a SEARCH. False for SCAN. */ + WhereLoop *pLoop; /* The controlling WhereLoop object */ + u32 flags; /* Flags that describe this loop */ + + pLoop = pLevel->pWLoop; + flags = pLoop->wsFlags; + if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return; + + isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 + || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) + || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); + + zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN"); + if( pItem->pSelect ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId); + }else{ + zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName); + } + + if( pItem->zAlias ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias); + } + if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 + && ALWAYS(pLoop->u.btree.pIndex!=0) + ){ + char *zWhere = explainIndexRange(db, pLoop, pItem->pTab); + zMsg = sqlite3MAppendf(db, zMsg, + ((flags & WHERE_AUTO_INDEX) ? + "%s USING AUTOMATIC %sINDEX%.0s%s" : + "%s USING %sINDEX %s%s"), + zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""), + pLoop->u.btree.pIndex->zName, zWhere); + sqlite3DbFree(db, zWhere); + }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg); + + if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg); + }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid?)", zMsg); + }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s (rowidu.vtab.idxNum, pLoop->u.vtab.idxStr); + } +#endif + zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg); + sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC); + } +} +#else +# define explainOneScan(u,v,w,x,y,z) +#endif /* SQLITE_OMIT_EXPLAIN */ + + +/* +** Generate code for the start of the iLevel-th loop in the WHERE clause +** implementation described by pWInfo. +*/ +static Bitmask codeOneLoopStart( + WhereInfo *pWInfo, /* Complete information about the WHERE clause */ + int iLevel, /* Which level of pWInfo->a[] should be coded */ + Bitmask notReady /* Which tables are currently available */ +){ + int j, k; /* Loop counters */ + int iCur; /* The VDBE cursor for the table */ + int addrNxt; /* Where to jump to continue with the next IN case */ + int omitTable; /* True if we use the index only */ + int bRev; /* True if we need to scan in reverse order */ + WhereLevel *pLevel; /* The where level to be coded */ + WhereLoop *pLoop; /* The WhereLoop object being coded */ + WhereClause *pWC; /* Decomposition of the entire WHERE clause */ + WhereTerm *pTerm; /* A WHERE clause term */ + Parse *pParse; /* Parsing context */ + sqlite3 *db; /* Database connection */ + Vdbe *v; /* The prepared stmt under constructions */ + struct SrcList_item *pTabItem; /* FROM clause term being coded */ + int addrBrk; /* Jump here to break out of the loop */ + int addrCont; /* Jump here to continue with next cycle */ + int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ + int iReleaseReg = 0; /* Temp register to free before returning */ + + pParse = pWInfo->pParse; + v = pParse->pVdbe; + pWC = &pWInfo->sWC; + db = pParse->db; + pLevel = &pWInfo->a[iLevel]; + pLoop = pLevel->pWLoop; + pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; + iCur = pTabItem->iCursor; + pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur); + bRev = (pWInfo->revMask>>iLevel)&1; + omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 + && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0; + VdbeNoopComment((v, "Begin Join Loop %d", iLevel)); + + /* Create labels for the "break" and "continue" instructions + ** for the current loop. Jump to addrBrk to break out of a loop. + ** Jump to cont to go immediately to the next iteration of the + ** loop. + ** + ** When there is an IN operator, we also have a "addrNxt" label that + ** means to continue with the next IN value combination. When + ** there are no IN operators in the constraints, the "addrNxt" label + ** is the same as "addrBrk". + */ + addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); + addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); + + /* If this is the right table of a LEFT OUTER JOIN, allocate and + ** initialize a memory cell that records if this table matches any + ** row of the left table of the join. + */ + if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){ + pLevel->iLeftJoin = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); + VdbeComment((v, "init LEFT JOIN no-match flag")); + } + + /* Special case of a FROM clause subquery implemented as a co-routine */ + if( pTabItem->viaCoroutine ){ + int regYield = pTabItem->regReturn; + sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield); + pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield); + VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName)); + sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk); + pLevel->op = OP_Goto; + }else + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ + /* Case 1: The table is a virtual-table. Use the VFilter and VNext + ** to access the data. + */ + int iReg; /* P3 Value for OP_VFilter */ + int addrNotFound; + int nConstraint = pLoop->nLTerm; + + sqlite3ExprCachePush(pParse); + iReg = sqlite3GetTempRange(pParse, nConstraint+2); + addrNotFound = pLevel->addrBrk; + for(j=0; jaLTerm[j]; + if( pTerm==0 ) continue; + if( pTerm->eOperator & WO_IN ){ + codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); + addrNotFound = pLevel->addrNxt; + }else{ + sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget); + } + } + sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); + sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); + sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, + pLoop->u.vtab.idxStr, + pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC); + pLoop->u.vtab.needFree = 0; + for(j=0; ju.vtab.omitMask>>j)&1 ){ + disableTerm(pLevel, pLoop->aLTerm[j]); + } + } + pLevel->op = OP_VNext; + pLevel->p1 = iCur; + pLevel->p2 = sqlite3VdbeCurrentAddr(v); + sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); + sqlite3ExprCachePop(pParse, 1); + }else +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + + if( (pLoop->wsFlags & WHERE_IPK)!=0 + && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 + ){ + /* Case 2: We can directly reference a single row using an + ** equality comparison against the ROWID field. Or + ** we reference multiple rows using a "rowid IN (...)" + ** construct. + */ + assert( pLoop->u.btree.nEq==1 ); + iReleaseReg = sqlite3GetTempReg(pParse); + pTerm = pLoop->aLTerm[0]; + assert( pTerm!=0 ); + assert( pTerm->pExpr!=0 ); + assert( omitTable==0 ); + testcase( pTerm->wtFlags & TERM_VIRTUAL ); + iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); + addrNxt = pLevel->addrNxt; + sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg); + sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); + sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); + VdbeComment((v, "pk")); + pLevel->op = OP_Noop; + }else if( (pLoop->wsFlags & WHERE_IPK)!=0 + && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 + ){ + /* Case 3: We have an inequality comparison against the ROWID field. + */ + int testOp = OP_Noop; + int start; + int memEndValue = 0; + WhereTerm *pStart, *pEnd; + + assert( omitTable==0 ); + j = 0; + pStart = pEnd = 0; + if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; + if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; + assert( pStart!=0 || pEnd!=0 ); + if( bRev ){ + pTerm = pStart; + pStart = pEnd; + pEnd = pTerm; + } + if( pStart ){ + Expr *pX; /* The expression that defines the start bound */ + int r1, rTemp; /* Registers for holding the start boundary */ + + /* The following constant maps TK_xx codes into corresponding + ** seek opcodes. It depends on a particular ordering of TK_xx + */ + const u8 aMoveOp[] = { + /* TK_GT */ OP_SeekGt, + /* TK_LE */ OP_SeekLe, + /* TK_LT */ OP_SeekLt, + /* TK_GE */ OP_SeekGe + }; + assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ + assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ + assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ + + assert( (pStart->wtFlags & TERM_VNULL)==0 ); + testcase( pStart->wtFlags & TERM_VIRTUAL ); + pX = pStart->pExpr; + assert( pX!=0 ); + testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ + r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); + sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1); + VdbeComment((v, "pk")); + sqlite3ExprCacheAffinityChange(pParse, r1, 1); + sqlite3ReleaseTempReg(pParse, rTemp); + disableTerm(pLevel, pStart); + }else{ + sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); + } + if( pEnd ){ + Expr *pX; + pX = pEnd->pExpr; + assert( pX!=0 ); + assert( (pEnd->wtFlags & TERM_VNULL)==0 ); + testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ + testcase( pEnd->wtFlags & TERM_VIRTUAL ); + memEndValue = ++pParse->nMem; + sqlite3ExprCode(pParse, pX->pRight, memEndValue); + if( pX->op==TK_LT || pX->op==TK_GT ){ + testOp = bRev ? OP_Le : OP_Ge; + }else{ + testOp = bRev ? OP_Lt : OP_Gt; + } + disableTerm(pLevel, pEnd); + } + start = sqlite3VdbeCurrentAddr(v); + pLevel->op = bRev ? OP_Prev : OP_Next; + pLevel->p1 = iCur; + pLevel->p2 = start; + assert( pLevel->p5==0 ); + if( testOp!=OP_Noop ){ + iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); + sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); + sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); + sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); + } + }else if( pLoop->wsFlags & WHERE_INDEXED ){ + /* Case 4: A scan using an index. + ** + ** The WHERE clause may contain zero or more equality + ** terms ("==" or "IN" operators) that refer to the N + ** left-most columns of the index. It may also contain + ** inequality constraints (>, <, >= or <=) on the indexed + ** column that immediately follows the N equalities. Only + ** the right-most column can be an inequality - the rest must + ** use the "==" and "IN" operators. For example, if the + ** index is on (x,y,z), then the following clauses are all + ** optimized: + ** + ** x=5 + ** x=5 AND y=10 + ** x=5 AND y<10 + ** x=5 AND y>5 AND y<10 + ** x=5 AND y=5 AND z<=10 + ** + ** The z<10 term of the following cannot be used, only + ** the x=5 term: + ** + ** x=5 AND z<10 + ** + ** N may be zero if there are inequality constraints. + ** If there are no inequality constraints, then N is at + ** least one. + ** + ** This case is also used when there are no WHERE clause + ** constraints but an index is selected anyway, in order + ** to force the output order to conform to an ORDER BY. + */ + static const u8 aStartOp[] = { + 0, + 0, + OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ + OP_Last, /* 3: (!start_constraints && startEq && bRev) */ + OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */ + OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */ + OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */ + OP_SeekLe /* 7: (start_constraints && startEq && bRev) */ + }; + static const u8 aEndOp[] = { + OP_Noop, /* 0: (!end_constraints) */ + OP_IdxGE, /* 1: (end_constraints && !bRev) */ + OP_IdxLT /* 2: (end_constraints && bRev) */ + }; + int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ + int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */ + int regBase; /* Base register holding constraint values */ + int r1; /* Temp register */ + WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ + WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ + int startEq; /* True if range start uses ==, >= or <= */ + int endEq; /* True if range end uses ==, >= or <= */ + int start_constraints; /* Start of range is constrained */ + int nConstraint; /* Number of constraint terms */ + Index *pIdx; /* The index we will be using */ + int iIdxCur; /* The VDBE cursor for the index */ + int nExtraReg = 0; /* Number of extra registers needed */ + int op; /* Instruction opcode */ + char *zStartAff; /* Affinity for start of range constraint */ + char *zEndAff; /* Affinity for end of range constraint */ + + pIdx = pLoop->u.btree.pIndex; + iIdxCur = pLevel->iIdxCur; + + /* If this loop satisfies a sort order (pOrderBy) request that + ** was passed to this function to implement a "SELECT min(x) ..." + ** query, then the caller will only allow the loop to run for + ** a single iteration. This means that the first row returned + ** should not have a NULL value stored in 'x'. If column 'x' is + ** the first one after the nEq equality constraints in the index, + ** this requires some special handling. + */ + if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 + && (pWInfo->bOBSat!=0) + && (pIdx->nColumn>nEq) + ){ + /* assert( pOrderBy->nExpr==1 ); */ + /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */ + isMinQuery = 1; + nExtraReg = 1; + } + + /* Find any inequality constraint terms for the start and end + ** of the range. + */ + j = nEq; + if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ + pRangeStart = pLoop->aLTerm[j++]; + nExtraReg = 1; + } + if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ + pRangeEnd = pLoop->aLTerm[j++]; + nExtraReg = 1; + } + + /* Generate code to evaluate all constraint terms using == or IN + ** and store the values of those terms in an array of registers + ** starting at regBase. + */ + regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); + zEndAff = sqlite3DbStrDup(db, zStartAff); + addrNxt = pLevel->addrNxt; + + /* If we are doing a reverse order scan on an ascending index, or + ** a forward order scan on a descending index, interchange the + ** start and end terms (pRangeStart and pRangeEnd). + */ + if( (nEqnColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) + || (bRev && pIdx->nColumn==nEq) + ){ + SWAP(WhereTerm *, pRangeEnd, pRangeStart); + } + + testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); + testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); + testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); + testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); + startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); + endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); + start_constraints = pRangeStart || nEq>0; + + /* Seek the index cursor to the start of the range. */ + nConstraint = nEq; + if( pRangeStart ){ + Expr *pRight = pRangeStart->pExpr->pRight; + sqlite3ExprCode(pParse, pRight, regBase+nEq); + if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){ + sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt); + } + if( zStartAff ){ + if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){ + /* Since the comparison is to be performed with no conversions + ** applied to the operands, set the affinity to apply to pRight to + ** SQLITE_AFF_NONE. */ + zStartAff[nEq] = SQLITE_AFF_NONE; + } + if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){ + zStartAff[nEq] = SQLITE_AFF_NONE; + } + } + nConstraint++; + testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); + }else if( isMinQuery ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); + nConstraint++; + startEq = 0; + start_constraints = 1; + } + codeApplyAffinity(pParse, regBase, nConstraint, zStartAff); + op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; + assert( op!=0 ); + testcase( op==OP_Rewind ); + testcase( op==OP_Last ); + testcase( op==OP_SeekGt ); + testcase( op==OP_SeekGe ); + testcase( op==OP_SeekLe ); + testcase( op==OP_SeekLt ); + sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); + + /* Load the value for the inequality constraint at the end of the + ** range (if any). + */ + nConstraint = nEq; + if( pRangeEnd ){ + Expr *pRight = pRangeEnd->pExpr->pRight; + sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); + sqlite3ExprCode(pParse, pRight, regBase+nEq); + if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){ + sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt); + } + if( zEndAff ){ + if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){ + /* Since the comparison is to be performed with no conversions + ** applied to the operands, set the affinity to apply to pRight to + ** SQLITE_AFF_NONE. */ + zEndAff[nEq] = SQLITE_AFF_NONE; + } + if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){ + zEndAff[nEq] = SQLITE_AFF_NONE; + } + } + codeApplyAffinity(pParse, regBase, nEq+1, zEndAff); + nConstraint++; + testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); + } + sqlite3DbFree(db, zStartAff); + sqlite3DbFree(db, zEndAff); + + /* Top of the loop body */ + pLevel->p2 = sqlite3VdbeCurrentAddr(v); + + /* Check if the index cursor is past the end of the range. */ + op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)]; + testcase( op==OP_Noop ); + testcase( op==OP_IdxGE ); + testcase( op==OP_IdxLT ); + if( op!=OP_Noop ){ + sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); + sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0); + } + + /* If there are inequality constraints, check that the value + ** of the table column that the inequality contrains is not NULL. + ** If it is, jump to the next iteration of the loop. + */ + r1 = sqlite3GetTempReg(pParse); + testcase( pLoop->wsFlags & WHERE_BTM_LIMIT ); + testcase( pLoop->wsFlags & WHERE_TOP_LIMIT ); + if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){ + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1); + sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont); + } + sqlite3ReleaseTempReg(pParse, r1); + + /* Seek the table cursor, if required */ + disableTerm(pLevel, pRangeStart); + disableTerm(pLevel, pRangeEnd); + if( !omitTable ){ + iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); + sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); + sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */ + } + + /* Record the instruction used to terminate the loop. Disable + ** WHERE clause terms made redundant by the index range scan. + */ + if( pLoop->wsFlags & WHERE_ONEROW ){ + pLevel->op = OP_Noop; + }else if( bRev ){ + pLevel->op = OP_Prev; + }else{ + pLevel->op = OP_Next; + } + pLevel->p1 = iIdxCur; + if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ + pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; + }else{ + assert( pLevel->p5==0 ); + } + }else + +#ifndef SQLITE_OMIT_OR_OPTIMIZATION + if( pLoop->wsFlags & WHERE_MULTI_OR ){ + /* Case 5: Two or more separately indexed terms connected by OR + ** + ** Example: + ** + ** CREATE TABLE t1(a,b,c,d); + ** CREATE INDEX i1 ON t1(a); + ** CREATE INDEX i2 ON t1(b); + ** CREATE INDEX i3 ON t1(c); + ** + ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) + ** + ** In the example, there are three indexed terms connected by OR. + ** The top of the loop looks like this: + ** + ** Null 1 # Zero the rowset in reg 1 + ** + ** Then, for each indexed term, the following. The arguments to + ** RowSetTest are such that the rowid of the current row is inserted + ** into the RowSet. If it is already present, control skips the + ** Gosub opcode and jumps straight to the code generated by WhereEnd(). + ** + ** sqlite3WhereBegin() + ** RowSetTest # Insert rowid into rowset + ** Gosub 2 A + ** sqlite3WhereEnd() + ** + ** Following the above, code to terminate the loop. Label A, the target + ** of the Gosub above, jumps to the instruction right after the Goto. + ** + ** Null 1 # Zero the rowset in reg 1 + ** Goto B # The loop is finished. + ** + ** A: # Return data, whatever. + ** + ** Return 2 # Jump back to the Gosub + ** + ** B: + ** + */ + WhereClause *pOrWc; /* The OR-clause broken out into subterms */ + SrcList *pOrTab; /* Shortened table list or OR-clause generation */ + Index *pCov = 0; /* Potential covering index (or NULL) */ + int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ + + int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ + int regRowset = 0; /* Register for RowSet object */ + int regRowid = 0; /* Register holding rowid */ + int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ + int iRetInit; /* Address of regReturn init */ + int untestedTerms = 0; /* Some terms not completely tested */ + int ii; /* Loop counter */ + Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ + + pTerm = pLoop->aLTerm[0]; + assert( pTerm!=0 ); + assert( pTerm->eOperator & WO_OR ); + assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); + pOrWc = &pTerm->u.pOrInfo->wc; + pLevel->op = OP_Return; + pLevel->p1 = regReturn; + + /* Set up a new SrcList in pOrTab containing the table being scanned + ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. + ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). + */ + if( pWInfo->nLevel>1 ){ + int nNotReady; /* The number of notReady tables */ + struct SrcList_item *origSrc; /* Original list of tables */ + nNotReady = pWInfo->nLevel - iLevel - 1; + pOrTab = sqlite3StackAllocRaw(db, + sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); + if( pOrTab==0 ) return notReady; + pOrTab->nAlloc = (u8)(nNotReady + 1); + pOrTab->nSrc = pOrTab->nAlloc; + memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); + origSrc = pWInfo->pTabList->a; + for(k=1; k<=nNotReady; k++){ + memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); + } + }else{ + pOrTab = pWInfo->pTabList; + } + + /* Initialize the rowset register to contain NULL. An SQL NULL is + ** equivalent to an empty rowset. + ** + ** Also initialize regReturn to contain the address of the instruction + ** immediately following the OP_Return at the bottom of the loop. This + ** is required in a few obscure LEFT JOIN cases where control jumps + ** over the top of the loop into the body of it. In this case the + ** correct response for the end-of-loop code (the OP_Return) is to + ** fall through to the next instruction, just as an OP_Next does if + ** called on an uninitialized cursor. + */ + if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ + regRowset = ++pParse->nMem; + regRowid = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); + } + iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); + + /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y + ** Then for every term xN, evaluate as the subexpression: xN AND z + ** That way, terms in y that are factored into the disjunction will + ** be picked up by the recursive calls to sqlite3WhereBegin() below. + ** + ** Actually, each subexpression is converted to "xN AND w" where w is + ** the "interesting" terms of z - terms that did not originate in the + ** ON or USING clause of a LEFT JOIN, and terms that are usable as + ** indices. + ** + ** This optimization also only applies if the (x1 OR x2 OR ...) term + ** is not contained in the ON clause of a LEFT JOIN. + ** See ticket http://www.sqlite.org/src/info/f2369304e4 + */ + if( pWC->nTerm>1 ){ + int iTerm; + for(iTerm=0; iTermnTerm; iTerm++){ + Expr *pExpr = pWC->a[iTerm].pExpr; + if( &pWC->a[iTerm] == pTerm ) continue; + if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; + if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue; + if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; + pExpr = sqlite3ExprDup(db, pExpr, 0); + pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); + } + if( pAndExpr ){ + pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0); + } + } + + for(ii=0; iinTerm; ii++){ + WhereTerm *pOrTerm = &pOrWc->a[ii]; + if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ + WhereInfo *pSubWInfo; /* Info for single OR-term scan */ + Expr *pOrExpr = pOrTerm->pExpr; + if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ + pAndExpr->pLeft = pOrExpr; + pOrExpr = pAndExpr; + } + /* Loop through table entries that match term pOrTerm. */ + pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, + WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY | + WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur); + assert( pSubWInfo || pParse->nErr || db->mallocFailed ); + if( pSubWInfo ){ + WhereLoop *pSubLoop; + explainOneScan( + pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 + ); + if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ + int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); + int r; + r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, + regRowid, 0); + sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, + sqlite3VdbeCurrentAddr(v)+2, r, iSet); + } + sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); + + /* The pSubWInfo->untestedTerms flag means that this OR term + ** contained one or more AND term from a notReady table. The + ** terms from the notReady table could not be tested and will + ** need to be tested later. + */ + if( pSubWInfo->untestedTerms ) untestedTerms = 1; + + /* If all of the OR-connected terms are optimized using the same + ** index, and the index is opened using the same cursor number + ** by each call to sqlite3WhereBegin() made by this loop, it may + ** be possible to use that index as a covering index. + ** + ** If the call to sqlite3WhereBegin() above resulted in a scan that + ** uses an index, and this is either the first OR-connected term + ** processed or the index is the same as that used by all previous + ** terms, set pCov to the candidate covering index. Otherwise, set + ** pCov to NULL to indicate that no candidate covering index will + ** be available. + */ + pSubLoop = pSubWInfo->a[0].pWLoop; + assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); + if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 + && (ii==0 || pSubLoop->u.btree.pIndex==pCov) + ){ + assert( pSubWInfo->a[0].iIdxCur==iCovCur ); + pCov = pSubLoop->u.btree.pIndex; + }else{ + pCov = 0; + } + + /* Finish the loop through table entries that match term pOrTerm. */ + sqlite3WhereEnd(pSubWInfo); + } + } + } + pLevel->u.pCovidx = pCov; + if( pCov ) pLevel->iIdxCur = iCovCur; + if( pAndExpr ){ + pAndExpr->pLeft = 0; + sqlite3ExprDelete(db, pAndExpr); + } + sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); + sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk); + sqlite3VdbeResolveLabel(v, iLoopBody); + + if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); + if( !untestedTerms ) disableTerm(pLevel, pTerm); + }else +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */ + + { + /* Case 6: There is no usable index. We must do a complete + ** scan of the entire table. + */ + static const u8 aStep[] = { OP_Next, OP_Prev }; + static const u8 aStart[] = { OP_Rewind, OP_Last }; + assert( bRev==0 || bRev==1 ); + pLevel->op = aStep[bRev]; + pLevel->p1 = iCur; + pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); + pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; + } + + /* Insert code to test every subexpression that can be completely + ** computed using the current set of tables. + */ + for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ + Expr *pE; + testcase( pTerm->wtFlags & TERM_VIRTUAL ); + testcase( pTerm->wtFlags & TERM_CODED ); + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; + if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ + testcase( pWInfo->untestedTerms==0 + && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ); + pWInfo->untestedTerms = 1; + continue; + } + pE = pTerm->pExpr; + assert( pE!=0 ); + if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ + continue; + } + sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); + pTerm->wtFlags |= TERM_CODED; + } + + /* Insert code to test for implied constraints based on transitivity + ** of the "==" operator. + ** + ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" + ** and we are coding the t1 loop and the t2 loop has not yet coded, + ** then we cannot use the "t1.a=t2.b" constraint, but we can code + ** the implied "t1.a=123" constraint. + */ + for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ + Expr *pE, *pEAlt; + WhereTerm *pAlt; + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; + if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue; + if( pTerm->leftCursor!=iCur ) continue; + if( pLevel->iLeftJoin ) continue; + pE = pTerm->pExpr; + assert( !ExprHasProperty(pE, EP_FromJoin) ); + assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); + pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0); + if( pAlt==0 ) continue; + if( pAlt->wtFlags & (TERM_CODED) ) continue; + testcase( pAlt->eOperator & WO_EQ ); + testcase( pAlt->eOperator & WO_IN ); + VdbeNoopComment((v, "begin transitive constraint")); + pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt)); + if( pEAlt ){ + *pEAlt = *pAlt->pExpr; + pEAlt->pLeft = pE->pLeft; + sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL); + sqlite3StackFree(db, pEAlt); + } + } + + /* For a LEFT OUTER JOIN, generate code that will record the fact that + ** at least one row of the right table has matched the left table. + */ + if( pLevel->iLeftJoin ){ + pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); + VdbeComment((v, "record LEFT JOIN hit")); + sqlite3ExprCacheClear(pParse); + for(pTerm=pWC->a, j=0; jnTerm; j++, pTerm++){ + testcase( pTerm->wtFlags & TERM_VIRTUAL ); + testcase( pTerm->wtFlags & TERM_CODED ); + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; + if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ + assert( pWInfo->untestedTerms ); + continue; + } + assert( pTerm->pExpr ); + sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); + pTerm->wtFlags |= TERM_CODED; + } + } + sqlite3ReleaseTempReg(pParse, iReleaseReg); + + return pLevel->notReady; +} + +#ifdef WHERETRACE_ENABLED +/* +** Print a WhereLoop object for debugging purposes +*/ +static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){ + int nb = 1+(pTabList->nSrc+7)/8; + struct SrcList_item *pItem = pTabList->a + p->iTab; + Table *pTab = pItem->pTab; + sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, + p->iTab, nb, p->maskSelf, nb, p->prereq); + sqlite3DebugPrintf(" %12s", + pItem->zAlias ? pItem->zAlias : pTab->zName); + if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ + if( p->u.btree.pIndex ){ + const char *zName = p->u.btree.pIndex->zName; + if( zName==0 ) zName = "ipk"; + if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ + int i = sqlite3Strlen30(zName) - 1; + while( zName[i]!='_' ) i--; + zName += i; + } + sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); + }else{ + sqlite3DebugPrintf("%20s",""); + } + }else{ + char *z; + if( p->u.vtab.idxStr ){ + z = sqlite3_mprintf("(%d,\"%s\",%x)", + p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); + }else{ + z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); + } + sqlite3DebugPrintf(" %-19s", z); + sqlite3_free(z); + } + sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm); + sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); +} +#endif + +/* +** Convert bulk memory into a valid WhereLoop that can be passed +** to whereLoopClear harmlessly. +*/ +static void whereLoopInit(WhereLoop *p){ + p->aLTerm = p->aLTermSpace; + p->nLTerm = 0; + p->nLSlot = ArraySize(p->aLTermSpace); + p->wsFlags = 0; +} + +/* +** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. +*/ +static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ + if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ + if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ + sqlite3_free(p->u.vtab.idxStr); + p->u.vtab.needFree = 0; + p->u.vtab.idxStr = 0; + }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ + sqlite3DbFree(db, p->u.btree.pIndex->zColAff); + sqlite3DbFree(db, p->u.btree.pIndex); + p->u.btree.pIndex = 0; + } + } +} + +/* +** Deallocate internal memory used by a WhereLoop object +*/ +static void whereLoopClear(sqlite3 *db, WhereLoop *p){ + if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); + whereLoopClearUnion(db, p); + whereLoopInit(p); +} + +/* +** Increase the memory allocation for pLoop->aLTerm[] to be at least n. +*/ +static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ + WhereTerm **paNew; + if( p->nLSlot>=n ) return SQLITE_OK; + n = (n+7)&~7; + paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n); + if( paNew==0 ) return SQLITE_NOMEM; + memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); + if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); + p->aLTerm = paNew; + p->nLSlot = n; + return SQLITE_OK; +} + +/* +** Transfer content from the second pLoop into the first. +*/ +static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ + whereLoopClearUnion(db, pTo); + if( whereLoopResize(db, pTo, pFrom->nLTerm) ){ + memset(&pTo->u, 0, sizeof(pTo->u)); + return SQLITE_NOMEM; + } + memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); + memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); + if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ + pFrom->u.vtab.needFree = 0; + }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ + pFrom->u.btree.pIndex = 0; + } + return SQLITE_OK; +} + +/* +** Delete a WhereLoop object +*/ +static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ + whereLoopClear(db, p); + sqlite3DbFree(db, p); +} + +/* +** Free a WhereInfo structure +*/ +static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ + if( ALWAYS(pWInfo) ){ + whereClauseClear(&pWInfo->sWC); + while( pWInfo->pLoops ){ + WhereLoop *p = pWInfo->pLoops; + pWInfo->pLoops = p->pNextLoop; + whereLoopDelete(db, p); + } + sqlite3DbFree(db, pWInfo); + } +} + +/* +** Insert or replace a WhereLoop entry using the template supplied. +** +** An existing WhereLoop entry might be overwritten if the new template +** is better and has fewer dependencies. Or the template will be ignored +** and no insert will occur if an existing WhereLoop is faster and has +** fewer dependencies than the template. Otherwise a new WhereLoop is +** added based on the template. +** +** If pBuilder->pOrSet is not NULL then we only care about only the +** prerequisites and rRun and nOut costs of the N best loops. That +** information is gathered in the pBuilder->pOrSet object. This special +** processing mode is used only for OR clause processing. +** +** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we +** still might overwrite similar loops with the new template if the +** template is better. Loops may be overwritten if the following +** conditions are met: +** +** (1) They have the same iTab. +** (2) They have the same iSortIdx. +** (3) The template has same or fewer dependencies than the current loop +** (4) The template has the same or lower cost than the current loop +** (5) The template uses more terms of the same index but has no additional +** dependencies +*/ +static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ + WhereLoop **ppPrev, *p, *pNext = 0; + WhereInfo *pWInfo = pBuilder->pWInfo; + sqlite3 *db = pWInfo->pParse->db; + + /* If pBuilder->pOrSet is defined, then only keep track of the costs + ** and prereqs. + */ + if( pBuilder->pOrSet!=0 ){ +#if WHERETRACE_ENABLED + u16 n = pBuilder->pOrSet->n; + int x = +#endif + whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, + pTemplate->nOut); +#if WHERETRACE_ENABLED + if( sqlite3WhereTrace & 0x8 ){ + sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); + whereLoopPrint(pTemplate, pWInfo->pTabList); + } +#endif + return SQLITE_OK; + } + + /* Search for an existing WhereLoop to overwrite, or which takes + ** priority over pTemplate. + */ + for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){ + if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){ + /* If either the iTab or iSortIdx values for two WhereLoop are different + ** then those WhereLoops need to be considered separately. Neither is + ** a candidate to replace the other. */ + continue; + } + /* In the current implementation, the rSetup value is either zero + ** or the cost of building an automatic index (NlogN) and the NlogN + ** is the same for compatible WhereLoops. */ + assert( p->rSetup==0 || pTemplate->rSetup==0 + || p->rSetup==pTemplate->rSetup ); + + /* whereLoopAddBtree() always generates and inserts the automatic index + ** case first. Hence compatible candidate WhereLoops never have a larger + ** rSetup. Call this SETUP-INVARIANT */ + assert( p->rSetup>=pTemplate->rSetup ); + + if( (p->prereq & pTemplate->prereq)==p->prereq + && p->rSetup<=pTemplate->rSetup + && p->rRun<=pTemplate->rRun + && p->nOut<=pTemplate->nOut + ){ + /* This branch taken when p is equal or better than pTemplate in + ** all of (1) dependencies (2) setup-cost, (3) run-cost, and + ** (4) number of output rows. */ + assert( p->rSetup==pTemplate->rSetup ); + if( p->prereq==pTemplate->prereq + && p->nLTermnLTerm + && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0 + && (p->u.btree.pIndex==pTemplate->u.btree.pIndex + || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm) + ){ + /* Overwrite an existing WhereLoop with an similar one that uses + ** more terms of the index */ + pNext = p->pNextLoop; + break; + }else{ + /* pTemplate is not helpful. + ** Return without changing or adding anything */ + goto whereLoopInsert_noop; + } + } + if( (p->prereq & pTemplate->prereq)==pTemplate->prereq + && p->rRun>=pTemplate->rRun + && p->nOut>=pTemplate->nOut + ){ + /* Overwrite an existing WhereLoop with a better one: one that is + ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost + ** or (4) number of output rows, and is no worse in any of those + ** categories. */ + assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */ + pNext = p->pNextLoop; + break; + } + } + + /* If we reach this point it means that either p[] should be overwritten + ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new + ** WhereLoop and insert it. + */ +#if WHERETRACE_ENABLED + if( sqlite3WhereTrace & 0x8 ){ + if( p!=0 ){ + sqlite3DebugPrintf("ins-del: "); + whereLoopPrint(p, pWInfo->pTabList); + } + sqlite3DebugPrintf("ins-new: "); + whereLoopPrint(pTemplate, pWInfo->pTabList); + } +#endif + if( p==0 ){ + p = sqlite3DbMallocRaw(db, sizeof(WhereLoop)); + if( p==0 ) return SQLITE_NOMEM; + whereLoopInit(p); + } + whereLoopXfer(db, p, pTemplate); + p->pNextLoop = pNext; + *ppPrev = p; + if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ + Index *pIndex = p->u.btree.pIndex; + if( pIndex && pIndex->tnum==0 ){ + p->u.btree.pIndex = 0; + } + } + return SQLITE_OK; + + /* Jump here if the insert is a no-op */ +whereLoopInsert_noop: +#if WHERETRACE_ENABLED + if( sqlite3WhereTrace & 0x8 ){ + sqlite3DebugPrintf("ins-noop: "); + whereLoopPrint(pTemplate, pWInfo->pTabList); + } +#endif + return SQLITE_OK; +} + +/* +** Adjust the WhereLoop.nOut value downward to account for terms of the +** WHERE clause that reference the loop but which are not used by an +** index. +** +** In the current implementation, the first extra WHERE clause term reduces +** the number of output rows by a factor of 10 and each additional term +** reduces the number of output rows by sqrt(2). +*/ +static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){ + WhereTerm *pTerm, *pX; + Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); + int i, j; + + if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){ + return; + } + for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ + if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; + if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; + if( (pTerm->prereqAll & notAllowed)!=0 ) continue; + for(j=pLoop->nLTerm-1; j>=0; j--){ + pX = pLoop->aLTerm[j]; + if( pX==pTerm ) break; + if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; + } + if( j<0 ) pLoop->nOut += pTerm->truthProb; + } +} + +/* +** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex. +** Try to match one more. +** +** If pProbe->tnum==0, that means pIndex is a fake index used for the +** INTEGER PRIMARY KEY. +*/ +static int whereLoopAddBtreeIndex( + WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ + struct SrcList_item *pSrc, /* FROM clause term being analyzed */ + Index *pProbe, /* An index on pSrc */ + LogEst nInMul /* log(Number of iterations due to IN) */ +){ + WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ + Parse *pParse = pWInfo->pParse; /* Parsing context */ + sqlite3 *db = pParse->db; /* Database connection malloc context */ + WhereLoop *pNew; /* Template WhereLoop under construction */ + WhereTerm *pTerm; /* A WhereTerm under consideration */ + int opMask; /* Valid operators for constraints */ + WhereScan scan; /* Iterator for WHERE terms */ + Bitmask saved_prereq; /* Original value of pNew->prereq */ + u16 saved_nLTerm; /* Original value of pNew->nLTerm */ + int saved_nEq; /* Original value of pNew->u.btree.nEq */ + u32 saved_wsFlags; /* Original value of pNew->wsFlags */ + LogEst saved_nOut; /* Original value of pNew->nOut */ + int iCol; /* Index of the column in the table */ + int rc = SQLITE_OK; /* Return code */ + LogEst nRowEst; /* Estimated index selectivity */ + LogEst rLogSize; /* Logarithm of table size */ + WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ + + pNew = pBuilder->pNew; + if( db->mallocFailed ) return SQLITE_NOMEM; + + assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); + assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); + if( pNew->wsFlags & WHERE_BTM_LIMIT ){ + opMask = WO_LT|WO_LE; + }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){ + opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE; + }else{ + opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE; + } + if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); + + assert( pNew->u.btree.nEq<=pProbe->nColumn ); + if( pNew->u.btree.nEq < pProbe->nColumn ){ + iCol = pProbe->aiColumn[pNew->u.btree.nEq]; + nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]); + if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1; + }else{ + iCol = -1; + nRowEst = 0; + } + pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol, + opMask, pProbe); + saved_nEq = pNew->u.btree.nEq; + saved_nLTerm = pNew->nLTerm; + saved_wsFlags = pNew->wsFlags; + saved_prereq = pNew->prereq; + saved_nOut = pNew->nOut; + pNew->rSetup = 0; + rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0])); + for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ + int nIn = 0; +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + int nRecValid = pBuilder->nRecValid; +#endif + if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) + && (iCol<0 || pSrc->pTab->aCol[iCol].notNull) + ){ + continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ + } + if( pTerm->prereqRight & pNew->maskSelf ) continue; + + assert( pNew->nOut==saved_nOut ); + + pNew->wsFlags = saved_wsFlags; + pNew->u.btree.nEq = saved_nEq; + pNew->nLTerm = saved_nLTerm; + if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ + pNew->aLTerm[pNew->nLTerm++] = pTerm; + pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; + pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */ + if( pTerm->eOperator & WO_IN ){ + Expr *pExpr = pTerm->pExpr; + pNew->wsFlags |= WHERE_COLUMN_IN; + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ + nIn = 46; assert( 46==sqlite3LogEst(25) ); + }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ + /* "x IN (value, value, ...)" */ + nIn = sqlite3LogEst(pExpr->x.pList->nExpr); + } + pNew->rRun += nIn; + pNew->u.btree.nEq++; + pNew->nOut = nRowEst + nInMul + nIn; + }else if( pTerm->eOperator & (WO_EQ) ){ + assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0 + || nInMul==0 ); + pNew->wsFlags |= WHERE_COLUMN_EQ; + if( iCol<0 + || (pProbe->onError!=OE_None && nInMul==0 + && pNew->u.btree.nEq==pProbe->nColumn-1) + ){ + assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 ); + pNew->wsFlags |= WHERE_ONEROW; + } + pNew->u.btree.nEq++; + pNew->nOut = nRowEst + nInMul; + }else if( pTerm->eOperator & (WO_ISNULL) ){ + pNew->wsFlags |= WHERE_COLUMN_NULL; + pNew->u.btree.nEq++; + /* TUNING: IS NULL selects 2 rows */ + nIn = 10; assert( 10==sqlite3LogEst(2) ); + pNew->nOut = nRowEst + nInMul + nIn; + }else if( pTerm->eOperator & (WO_GT|WO_GE) ){ + testcase( pTerm->eOperator & WO_GT ); + testcase( pTerm->eOperator & WO_GE ); + pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; + pBtm = pTerm; + pTop = 0; + }else{ + assert( pTerm->eOperator & (WO_LT|WO_LE) ); + testcase( pTerm->eOperator & WO_LT ); + testcase( pTerm->eOperator & WO_LE ); + pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; + pTop = pTerm; + pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? + pNew->aLTerm[pNew->nLTerm-2] : 0; + } + if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ + /* Adjust nOut and rRun for STAT3 range values */ + assert( pNew->nOut==saved_nOut ); + whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); + } +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( nInMul==0 + && pProbe->nSample + && pNew->u.btree.nEq<=pProbe->nSampleCol + && OptimizationEnabled(db, SQLITE_Stat3) + ){ + Expr *pExpr = pTerm->pExpr; + tRowcnt nOut = 0; + if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){ + testcase( pTerm->eOperator & WO_EQ ); + testcase( pTerm->eOperator & WO_ISNULL ); + rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); + }else if( (pTerm->eOperator & WO_IN) + && !ExprHasProperty(pExpr, EP_xIsSelect) ){ + rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); + } + assert( nOut==0 || rc==SQLITE_OK ); + if( nOut ){ + pNew->nOut = sqlite3LogEst(nOut); + if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; + } + } +#endif + if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){ + /* Each row involves a step of the index, then a binary search of + ** the main table */ + pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10); + } + /* Step cost for each output row */ + pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut); + whereLoopOutputAdjust(pBuilder->pWC, pNew); + rc = whereLoopInsert(pBuilder, pNew); + if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 + && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0)) + ){ + whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); + } + pNew->nOut = saved_nOut; +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + pBuilder->nRecValid = nRecValid; +#endif + } + pNew->prereq = saved_prereq; + pNew->u.btree.nEq = saved_nEq; + pNew->wsFlags = saved_wsFlags; + pNew->nOut = saved_nOut; + pNew->nLTerm = saved_nLTerm; + return rc; +} + +/* +** Return True if it is possible that pIndex might be useful in +** implementing the ORDER BY clause in pBuilder. +** +** Return False if pBuilder does not contain an ORDER BY clause or +** if there is no way for pIndex to be useful in implementing that +** ORDER BY clause. +*/ +static int indexMightHelpWithOrderBy( + WhereLoopBuilder *pBuilder, + Index *pIndex, + int iCursor +){ + ExprList *pOB; + int ii, jj; + + if( pIndex->bUnordered ) return 0; + if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; + for(ii=0; iinExpr; ii++){ + Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr); + if( pExpr->op!=TK_COLUMN ) return 0; + if( pExpr->iTable==iCursor ){ + for(jj=0; jjnColumn; jj++){ + if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; + } + } + } + return 0; +} + +/* +** Return a bitmask where 1s indicate that the corresponding column of +** the table is used by an index. Only the first 63 columns are considered. +*/ +static Bitmask columnsInIndex(Index *pIdx){ + Bitmask m = 0; + int j; + for(j=pIdx->nColumn-1; j>=0; j--){ + int x = pIdx->aiColumn[j]; + assert( x>=0 ); + testcase( x==BMS-1 ); + testcase( x==BMS-2 ); + if( xa; inTerm; i++, pTerm++){ + if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1; + } + return 0; +} + +/* +** Add all WhereLoop objects for a single table of the join where the table +** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be +** a b-tree table, not a virtual table. +*/ +static int whereLoopAddBtree( + WhereLoopBuilder *pBuilder, /* WHERE clause information */ + Bitmask mExtra /* Extra prerequesites for using this table */ +){ + WhereInfo *pWInfo; /* WHERE analysis context */ + Index *pProbe; /* An index we are evaluating */ + Index sPk; /* A fake index object for the primary key */ + tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */ + int aiColumnPk = -1; /* The aColumn[] value for the sPk index */ + SrcList *pTabList; /* The FROM clause */ + struct SrcList_item *pSrc; /* The FROM clause btree term to add */ + WhereLoop *pNew; /* Template WhereLoop object */ + int rc = SQLITE_OK; /* Return code */ + int iSortIdx = 1; /* Index number */ + int b; /* A boolean value */ + LogEst rSize; /* number of rows in the table */ + LogEst rLogSize; /* Logarithm of the number of rows in the table */ + WhereClause *pWC; /* The parsed WHERE clause */ + Table *pTab; /* Table being queried */ + + pNew = pBuilder->pNew; + pWInfo = pBuilder->pWInfo; + pTabList = pWInfo->pTabList; + pSrc = pTabList->a + pNew->iTab; + pTab = pSrc->pTab; + pWC = pBuilder->pWC; + assert( !IsVirtual(pSrc->pTab) ); + + if( pSrc->pIndex ){ + /* An INDEXED BY clause specifies a particular index to use */ + pProbe = pSrc->pIndex; + }else{ + /* There is no INDEXED BY clause. Create a fake Index object in local + ** variable sPk to represent the rowid primary key index. Make this + ** fake index the first in a chain of Index objects with all of the real + ** indices to follow */ + Index *pFirst; /* First of real indices on the table */ + memset(&sPk, 0, sizeof(Index)); + sPk.nColumn = 1; + sPk.aiColumn = &aiColumnPk; + sPk.aiRowEst = aiRowEstPk; + sPk.onError = OE_Replace; + sPk.pTable = pTab; + aiRowEstPk[0] = pTab->nRowEst; + aiRowEstPk[1] = 1; + pFirst = pSrc->pTab->pIndex; + if( pSrc->notIndexed==0 ){ + /* The real indices of the table are only considered if the + ** NOT INDEXED qualifier is omitted from the FROM clause */ + sPk.pNext = pFirst; + } + pProbe = &sPk; + } + rSize = sqlite3LogEst(pTab->nRowEst); + rLogSize = estLog(rSize); + +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX + /* Automatic indexes */ + if( !pBuilder->pOrSet + && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 + && pSrc->pIndex==0 + && !pSrc->viaCoroutine + && !pSrc->notIndexed + && !pSrc->isCorrelated + ){ + /* Generate auto-index WhereLoops */ + WhereTerm *pTerm; + WhereTerm *pWCEnd = pWC->a + pWC->nTerm; + for(pTerm=pWC->a; rc==SQLITE_OK && pTermprereqRight & pNew->maskSelf ) continue; + if( termCanDriveIndex(pTerm, pSrc, 0) ){ + pNew->u.btree.nEq = 1; + pNew->u.btree.pIndex = 0; + pNew->nLTerm = 1; + pNew->aLTerm[0] = pTerm; + /* TUNING: One-time cost for computing the automatic index is + ** approximately 7*N*log2(N) where N is the number of rows in + ** the table being indexed. */ + pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) ); + /* TUNING: Each index lookup yields 20 rows in the table. This + ** is more than the usual guess of 10 rows, since we have no way + ** of knowning how selective the index will ultimately be. It would + ** not be unreasonable to make this value much larger. */ + pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); + pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); + pNew->wsFlags = WHERE_AUTO_INDEX; + pNew->prereq = mExtra | pTerm->prereqRight; + rc = whereLoopInsert(pBuilder, pNew); + } + } + } +#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ + + /* Loop over all indices + */ + for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ + if( pProbe->pPartIdxWhere!=0 + && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){ + continue; /* Partial index inappropriate for this query */ + } + pNew->u.btree.nEq = 0; + pNew->nLTerm = 0; + pNew->iSortIdx = 0; + pNew->rSetup = 0; + pNew->prereq = mExtra; + pNew->nOut = rSize; + pNew->u.btree.pIndex = pProbe; + b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); + /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ + assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); + if( pProbe->tnum<=0 ){ + /* Integer primary key index */ + pNew->wsFlags = WHERE_IPK; + + /* Full table scan */ + pNew->iSortIdx = b ? iSortIdx : 0; + /* TUNING: Cost of full table scan is 3*(N + log2(N)). + ** + The extra 3 factor is to encourage the use of indexed lookups + ** over full scans. FIXME */ + pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16; + whereLoopOutputAdjust(pWC, pNew); + rc = whereLoopInsert(pBuilder, pNew); + pNew->nOut = rSize; + if( rc ) break; + }else{ + Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe); + pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; + + /* Full scan via index */ + if( b + || ( m==0 + && pProbe->bUnordered==0 + && pProbe->szIdxRowszTabRow + && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 + && sqlite3GlobalConfig.bUseCis + && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) + ) + ){ + pNew->iSortIdx = b ? iSortIdx : 0; + if( m==0 ){ + /* TUNING: Cost of a covering index scan is K*(N + log2(N)). + ** + The extra factor K of between 1.1 and 3.0 that depends + ** on the relative sizes of the table and the index. K + ** is smaller for smaller indices, thus favoring them. + */ + pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 + + (15*pProbe->szIdxRow)/pTab->szTabRow; + }else{ + assert( b!=0 ); + /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N) + ** which we will simplify to just N*log2(N) */ + pNew->rRun = rSize + rLogSize; + } + whereLoopOutputAdjust(pWC, pNew); + rc = whereLoopInsert(pBuilder, pNew); + pNew->nOut = rSize; + if( rc ) break; + } + } + + rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sqlite3Stat4ProbeFree(pBuilder->pRec); + pBuilder->nRecValid = 0; + pBuilder->pRec = 0; +#endif + + /* If there was an INDEXED BY clause, then only that one index is + ** considered. */ + if( pSrc->pIndex ) break; + } + return rc; +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Add all WhereLoop objects for a table of the join identified by +** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table. +*/ +static int whereLoopAddVirtual( + WhereLoopBuilder *pBuilder /* WHERE clause information */ +){ + WhereInfo *pWInfo; /* WHERE analysis context */ + Parse *pParse; /* The parsing context */ + WhereClause *pWC; /* The WHERE clause */ + struct SrcList_item *pSrc; /* The FROM clause term to search */ + Table *pTab; + sqlite3 *db; + sqlite3_index_info *pIdxInfo; + struct sqlite3_index_constraint *pIdxCons; + struct sqlite3_index_constraint_usage *pUsage; + WhereTerm *pTerm; + int i, j; + int iTerm, mxTerm; + int nConstraint; + int seenIn = 0; /* True if an IN operator is seen */ + int seenVar = 0; /* True if a non-constant constraint is seen */ + int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */ + WhereLoop *pNew; + int rc = SQLITE_OK; + + pWInfo = pBuilder->pWInfo; + pParse = pWInfo->pParse; + db = pParse->db; + pWC = pBuilder->pWC; + pNew = pBuilder->pNew; + pSrc = &pWInfo->pTabList->a[pNew->iTab]; + pTab = pSrc->pTab; + assert( IsVirtual(pTab) ); + pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy); + if( pIdxInfo==0 ) return SQLITE_NOMEM; + pNew->prereq = 0; + pNew->rSetup = 0; + pNew->wsFlags = WHERE_VIRTUALTABLE; + pNew->nLTerm = 0; + pNew->u.vtab.needFree = 0; + pUsage = pIdxInfo->aConstraintUsage; + nConstraint = pIdxInfo->nConstraint; + if( whereLoopResize(db, pNew, nConstraint) ){ + sqlite3DbFree(db, pIdxInfo); + return SQLITE_NOMEM; + } + + for(iPhase=0; iPhase<=3; iPhase++){ + if( !seenIn && (iPhase&1)!=0 ){ + iPhase++; + if( iPhase>3 ) break; + } + if( !seenVar && iPhase>1 ) break; + pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pIdxCons++){ + j = pIdxCons->iTermOffset; + pTerm = &pWC->a[j]; + switch( iPhase ){ + case 0: /* Constants without IN operator */ + pIdxCons->usable = 0; + if( (pTerm->eOperator & WO_IN)!=0 ){ + seenIn = 1; + } + if( pTerm->prereqRight!=0 ){ + seenVar = 1; + }else if( (pTerm->eOperator & WO_IN)==0 ){ + pIdxCons->usable = 1; + } + break; + case 1: /* Constants with IN operators */ + assert( seenIn ); + pIdxCons->usable = (pTerm->prereqRight==0); + break; + case 2: /* Variables without IN */ + assert( seenVar ); + pIdxCons->usable = (pTerm->eOperator & WO_IN)==0; + break; + default: /* Variables with IN */ + assert( seenVar && seenIn ); + pIdxCons->usable = 1; + break; + } + } + memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint); + if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); + pIdxInfo->idxStr = 0; + pIdxInfo->idxNum = 0; + pIdxInfo->needToFreeIdxStr = 0; + pIdxInfo->orderByConsumed = 0; + pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; + rc = vtabBestIndex(pParse, pTab, pIdxInfo); + if( rc ) goto whereLoopAddVtab_exit; + pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; + pNew->prereq = 0; + mxTerm = -1; + assert( pNew->nLSlot>=nConstraint ); + for(i=0; iaLTerm[i] = 0; + pNew->u.vtab.omitMask = 0; + for(i=0; i=0 ){ + j = pIdxCons->iTermOffset; + if( iTerm>=nConstraint + || j<0 + || j>=pWC->nTerm + || pNew->aLTerm[iTerm]!=0 + ){ + rc = SQLITE_ERROR; + sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName); + goto whereLoopAddVtab_exit; + } + testcase( iTerm==nConstraint-1 ); + testcase( j==0 ); + testcase( j==pWC->nTerm-1 ); + pTerm = &pWC->a[j]; + pNew->prereq |= pTerm->prereqRight; + assert( iTermnLSlot ); + pNew->aLTerm[iTerm] = pTerm; + if( iTerm>mxTerm ) mxTerm = iTerm; + testcase( iTerm==15 ); + testcase( iTerm==16 ); + if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<eOperator & WO_IN)!=0 ){ + if( pUsage[i].omit==0 ){ + /* Do not attempt to use an IN constraint if the virtual table + ** says that the equivalent EQ constraint cannot be safely omitted. + ** If we do attempt to use such a constraint, some rows might be + ** repeated in the output. */ + break; + } + /* A virtual table that is constrained by an IN clause may not + ** consume the ORDER BY clause because (1) the order of IN terms + ** is not necessarily related to the order of output terms and + ** (2) Multiple outputs from a single IN value will not merge + ** together. */ + pIdxInfo->orderByConsumed = 0; + } + } + } + if( i>=nConstraint ){ + pNew->nLTerm = mxTerm+1; + assert( pNew->nLTerm<=pNew->nLSlot ); + pNew->u.vtab.idxNum = pIdxInfo->idxNum; + pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; + pIdxInfo->needToFreeIdxStr = 0; + pNew->u.vtab.idxStr = pIdxInfo->idxStr; + pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0) + && pIdxInfo->orderByConsumed); + pNew->rSetup = 0; + pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); + /* TUNING: Every virtual table query returns 25 rows */ + pNew->nOut = 46; assert( 46==sqlite3LogEst(25) ); + whereLoopInsert(pBuilder, pNew); + if( pNew->u.vtab.needFree ){ + sqlite3_free(pNew->u.vtab.idxStr); + pNew->u.vtab.needFree = 0; + } + } + } + +whereLoopAddVtab_exit: + if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); + sqlite3DbFree(db, pIdxInfo); + return rc; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** Add WhereLoop entries to handle OR terms. This works for either +** btrees or virtual tables. +*/ +static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){ + WhereInfo *pWInfo = pBuilder->pWInfo; + WhereClause *pWC; + WhereLoop *pNew; + WhereTerm *pTerm, *pWCEnd; + int rc = SQLITE_OK; + int iCur; + WhereClause tempWC; + WhereLoopBuilder sSubBuild; + WhereOrSet sSum, sCur, sPrev; + struct SrcList_item *pItem; + + pWC = pBuilder->pWC; + if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK; + pWCEnd = pWC->a + pWC->nTerm; + pNew = pBuilder->pNew; + memset(&sSum, 0, sizeof(sSum)); + pItem = pWInfo->pTabList->a + pNew->iTab; + iCur = pItem->iCursor; + + for(pTerm=pWC->a; pTermeOperator & WO_OR)!=0 + && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 + ){ + WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; + WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; + WhereTerm *pOrTerm; + int once = 1; + int i, j; + + sSubBuild = *pBuilder; + sSubBuild.pOrderBy = 0; + sSubBuild.pOrSet = &sCur; + + for(pOrTerm=pOrWC->a; pOrTermeOperator & WO_AND)!=0 ){ + sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc; + }else if( pOrTerm->leftCursor==iCur ){ + tempWC.pWInfo = pWC->pWInfo; + tempWC.pOuter = pWC; + tempWC.op = TK_AND; + tempWC.nTerm = 1; + tempWC.a = pOrTerm; + sSubBuild.pWC = &tempWC; + }else{ + continue; + } + sCur.n = 0; +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pItem->pTab) ){ + rc = whereLoopAddVirtual(&sSubBuild); + for(i=0; inLTerm = 1; + pNew->aLTerm[0] = pTerm; + pNew->wsFlags = WHERE_MULTI_OR; + pNew->rSetup = 0; + pNew->iSortIdx = 0; + memset(&pNew->u, 0, sizeof(pNew->u)); + for(i=0; rc==SQLITE_OK && irRun = sSum.a[i].rRun + 18; + pNew->nOut = sSum.a[i].nOut; + pNew->prereq = sSum.a[i].prereq; + rc = whereLoopInsert(pBuilder, pNew); + } + } + } + return rc; +} + +/* +** Add all WhereLoop objects for all tables +*/ +static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ + WhereInfo *pWInfo = pBuilder->pWInfo; + Bitmask mExtra = 0; + Bitmask mPrior = 0; + int iTab; + SrcList *pTabList = pWInfo->pTabList; + struct SrcList_item *pItem; + sqlite3 *db = pWInfo->pParse->db; + int nTabList = pWInfo->nLevel; + int rc = SQLITE_OK; + u8 priorJoinType = 0; + WhereLoop *pNew; + + /* Loop over the tables in the join, from left to right */ + pNew = pBuilder->pNew; + whereLoopInit(pNew); + for(iTab=0, pItem=pTabList->a; iTabiTab = iTab; + pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor); + if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){ + mExtra = mPrior; + } + priorJoinType = pItem->jointype; + if( IsVirtual(pItem->pTab) ){ + rc = whereLoopAddVirtual(pBuilder); + }else{ + rc = whereLoopAddBtree(pBuilder, mExtra); + } + if( rc==SQLITE_OK ){ + rc = whereLoopAddOr(pBuilder, mExtra); + } + mPrior |= pNew->maskSelf; + if( rc || db->mallocFailed ) break; + } + whereLoopClear(db, pNew); + return rc; +} + +/* +** Examine a WherePath (with the addition of the extra WhereLoop of the 5th +** parameters) to see if it outputs rows in the requested ORDER BY +** (or GROUP BY) without requiring a separate sort operation. Return: +** +** 0: ORDER BY is not satisfied. Sorting required +** 1: ORDER BY is satisfied. Omit sorting +** -1: Unknown at this time +** +** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as +** strict. With GROUP BY and DISTINCT the only requirement is that +** equivalent rows appear immediately adjacent to one another. GROUP BY +** and DISTINT do not require rows to appear in any particular order as long +** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT +** the pOrderBy terms can be matched in any order. With ORDER BY, the +** pOrderBy terms must be matched in strict left-to-right order. +*/ +static int wherePathSatisfiesOrderBy( + WhereInfo *pWInfo, /* The WHERE clause */ + ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */ + WherePath *pPath, /* The WherePath to check */ + u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */ + u16 nLoop, /* Number of entries in pPath->aLoop[] */ + WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */ + Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */ +){ + u8 revSet; /* True if rev is known */ + u8 rev; /* Composite sort order */ + u8 revIdx; /* Index sort order */ + u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */ + u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */ + u8 isMatch; /* iColumn matches a term of the ORDER BY clause */ + u16 nColumn; /* Number of columns in pIndex */ + u16 nOrderBy; /* Number terms in the ORDER BY clause */ + int iLoop; /* Index of WhereLoop in pPath being processed */ + int i, j; /* Loop counters */ + int iCur; /* Cursor number for current WhereLoop */ + int iColumn; /* A column number within table iCur */ + WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */ + WhereTerm *pTerm; /* A single term of the WHERE clause */ + Expr *pOBExpr; /* An expression from the ORDER BY clause */ + CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ + Index *pIndex; /* The index associated with pLoop */ + sqlite3 *db = pWInfo->pParse->db; /* Database connection */ + Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ + Bitmask obDone; /* Mask of all ORDER BY terms */ + Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ + Bitmask ready; /* Mask of inner loops */ + + /* + ** We say the WhereLoop is "one-row" if it generates no more than one + ** row of output. A WhereLoop is one-row if all of the following are true: + ** (a) All index columns match with WHERE_COLUMN_EQ. + ** (b) The index is unique + ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row. + ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags. + ** + ** We say the WhereLoop is "order-distinct" if the set of columns from + ** that WhereLoop that are in the ORDER BY clause are different for every + ** row of the WhereLoop. Every one-row WhereLoop is automatically + ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause + ** is not order-distinct. To be order-distinct is not quite the same as being + ** UNIQUE since a UNIQUE column or index can have multiple rows that + ** are NULL and NULL values are equivalent for the purpose of order-distinct. + ** To be order-distinct, the columns must be UNIQUE and NOT NULL. + ** + ** The rowid for a table is always UNIQUE and NOT NULL so whenever the + ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is + ** automatically order-distinct. + */ + + assert( pOrderBy!=0 ); + + /* Sortability of virtual tables is determined by the xBestIndex method + ** of the virtual table itself */ + if( pLast->wsFlags & WHERE_VIRTUALTABLE ){ + testcase( nLoop>0 ); /* True when outer loops are one-row and match + ** no ORDER BY terms */ + return pLast->u.vtab.isOrdered; + } + if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0; + + nOrderBy = pOrderBy->nExpr; + testcase( nOrderBy==BMS-1 ); + if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */ + isOrderDistinct = 1; + obDone = MASKBIT(nOrderBy)-1; + orderDistinctMask = 0; + ready = 0; + for(iLoop=0; isOrderDistinct && obSat0 ) ready |= pLoop->maskSelf; + pLoop = iLoopaLoop[iLoop] : pLast; + assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); + iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; + + /* Mark off any ORDER BY term X that is a column in the table of + ** the current loop for which there is term in the WHERE + ** clause of the form X IS NULL or X=? that reference only outer + ** loops. + */ + for(i=0; ia[i].pExpr); + if( pOBExpr->op!=TK_COLUMN ) continue; + if( pOBExpr->iTable!=iCur ) continue; + pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, + ~ready, WO_EQ|WO_ISNULL, 0); + if( pTerm==0 ) continue; + if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){ + const char *z1, *z2; + pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); + if( !pColl ) pColl = db->pDfltColl; + z1 = pColl->zName; + pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr); + if( !pColl ) pColl = db->pDfltColl; + z2 = pColl->zName; + if( sqlite3StrICmp(z1, z2)!=0 ) continue; + } + obSat |= MASKBIT(i); + } + + if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ + if( pLoop->wsFlags & WHERE_IPK ){ + pIndex = 0; + nColumn = 0; + }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ + return 0; + }else{ + nColumn = pIndex->nColumn; + isOrderDistinct = pIndex->onError!=OE_None; + } + + /* Loop through all columns of the index and deal with the ones + ** that are not constrained by == or IN. + */ + rev = revSet = 0; + distinctColumns = 0; + for(j=0; j<=nColumn; j++){ + u8 bOnce; /* True to run the ORDER BY search loop */ + + /* Skip over == and IS NULL terms */ + if( ju.btree.nEq + && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0 + ){ + if( i & WO_ISNULL ){ + testcase( isOrderDistinct ); + isOrderDistinct = 0; + } + continue; + } + + /* Get the column number in the table (iColumn) and sort order + ** (revIdx) for the j-th column of the index. + */ + if( jaiColumn[j]; + revIdx = pIndex->aSortOrder[j]; + if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; + }else{ + /* The ROWID column at the end */ + assert( j==nColumn ); + iColumn = -1; + revIdx = 0; + } + + /* An unconstrained column that might be NULL means that this + ** WhereLoop is not well-ordered + */ + if( isOrderDistinct + && iColumn>=0 + && j>=pLoop->u.btree.nEq + && pIndex->pTable->aCol[iColumn].notNull==0 + ){ + isOrderDistinct = 0; + } + + /* Find the ORDER BY term that corresponds to the j-th column + ** of the index and and mark that ORDER BY term off + */ + bOnce = 1; + isMatch = 0; + for(i=0; bOnce && ia[i].pExpr); + testcase( wctrlFlags & WHERE_GROUPBY ); + testcase( wctrlFlags & WHERE_DISTINCTBY ); + if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; + if( pOBExpr->op!=TK_COLUMN ) continue; + if( pOBExpr->iTable!=iCur ) continue; + if( pOBExpr->iColumn!=iColumn ) continue; + if( iColumn>=0 ){ + pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); + if( !pColl ) pColl = db->pDfltColl; + if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; + } + isMatch = 1; + break; + } + if( isMatch ){ + if( iColumn<0 ){ + testcase( distinctColumns==0 ); + distinctColumns = 1; + } + obSat |= MASKBIT(i); + if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){ + /* Make sure the sort order is compatible in an ORDER BY clause. + ** Sort order is irrelevant for a GROUP BY clause. */ + if( revSet ){ + if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0; + }else{ + rev = revIdx ^ pOrderBy->a[i].sortOrder; + if( rev ) *pRevMask |= MASKBIT(iLoop); + revSet = 1; + } + } + }else{ + /* No match found */ + if( j==0 || jmaskSelf; + for(i=0; ia[i].pExpr; + if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){ + obSat |= MASKBIT(i); + } + } + } + } /* End the loop over all WhereLoops from outer-most down to inner-most */ + if( obSat==obDone ) return 1; + if( !isOrderDistinct ) return 0; + return -1; +} + +#ifdef WHERETRACE_ENABLED +/* For debugging use only: */ +static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){ + static char zName[65]; + int i; + for(i=0; iaLoop[i]->cId; } + if( pLast ) zName[i++] = pLast->cId; + zName[i] = 0; + return zName; +} +#endif + + +/* +** Given the list of WhereLoop objects at pWInfo->pLoops, this routine +** attempts to find the lowest cost path that visits each WhereLoop +** once. This path is then loaded into the pWInfo->a[].pWLoop fields. +** +** Assume that the total number of output rows that will need to be sorted +** will be nRowEst (in the 10*log2 representation). Or, ignore sorting +** costs if nRowEst==0. +** +** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation +** error occurs. +*/ +static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ + int mxChoice; /* Maximum number of simultaneous paths tracked */ + int nLoop; /* Number of terms in the join */ + Parse *pParse; /* Parsing context */ + sqlite3 *db; /* The database connection */ + int iLoop; /* Loop counter over the terms of the join */ + int ii, jj; /* Loop counters */ + int mxI = 0; /* Index of next entry to replace */ + LogEst rCost; /* Cost of a path */ + LogEst nOut; /* Number of outputs */ + LogEst mxCost = 0; /* Maximum cost of a set of paths */ + LogEst mxOut = 0; /* Maximum nOut value on the set of paths */ + LogEst rSortCost; /* Cost to do a sort */ + int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ + WherePath *aFrom; /* All nFrom paths at the previous level */ + WherePath *aTo; /* The nTo best paths at the current level */ + WherePath *pFrom; /* An element of aFrom[] that we are working on */ + WherePath *pTo; /* An element of aTo[] that we are working on */ + WhereLoop *pWLoop; /* One of the WhereLoop objects */ + WhereLoop **pX; /* Used to divy up the pSpace memory */ + char *pSpace; /* Temporary memory used by this routine */ + + pParse = pWInfo->pParse; + db = pParse->db; + nLoop = pWInfo->nLevel; + /* TUNING: For simple queries, only the best path is tracked. + ** For 2-way joins, the 5 best paths are followed. + ** For joins of 3 or more tables, track the 10 best paths */ + mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10); + assert( nLoop<=pWInfo->pTabList->nSrc ); + WHERETRACE(0x002, ("---- begin solver\n")); + + /* Allocate and initialize space for aTo and aFrom */ + ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; + pSpace = sqlite3DbMallocRaw(db, ii); + if( pSpace==0 ) return SQLITE_NOMEM; + aTo = (WherePath*)pSpace; + aFrom = aTo+mxChoice; + memset(aFrom, 0, sizeof(aFrom[0])); + pX = (WhereLoop**)(aFrom+mxChoice); + for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){ + pFrom->aLoop = pX; + } + + /* Seed the search with a single WherePath containing zero WhereLoops. + ** + ** TUNING: Do not let the number of iterations go above 25. If the cost + ** of computing an automatic index is not paid back within the first 25 + ** rows, then do not use the automatic index. */ + aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) ); + nFrom = 1; + + /* Precompute the cost of sorting the final result set, if the caller + ** to sqlite3WhereBegin() was concerned about sorting */ + rSortCost = 0; + if( pWInfo->pOrderBy==0 || nRowEst==0 ){ + aFrom[0].isOrderedValid = 1; + }else{ + /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the + ** number of output rows. The 48 is the expected size of a row to sort. + ** FIXME: compute a better estimate of the 48 multiplier based on the + ** result set expressions. */ + rSortCost = nRowEst + estLog(nRowEst); + WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost)); + } + + /* Compute successively longer WherePaths using the previous generation + ** of WherePaths as the basis for the next. Keep track of the mxChoice + ** best paths at each generation */ + for(iLoop=0; iLooppLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ + Bitmask maskNew; + Bitmask revMask = 0; + u8 isOrderedValid = pFrom->isOrderedValid; + u8 isOrdered = pFrom->isOrdered; + if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; + if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; + /* At this point, pWLoop is a candidate to be the next loop. + ** Compute its cost */ + rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); + rCost = sqlite3LogEstAdd(rCost, pFrom->rCost); + nOut = pFrom->nRow + pWLoop->nOut; + maskNew = pFrom->maskLoop | pWLoop->maskSelf; + if( !isOrderedValid ){ + switch( wherePathSatisfiesOrderBy(pWInfo, + pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags, + iLoop, pWLoop, &revMask) ){ + case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */ + isOrdered = 1; + isOrderedValid = 1; + break; + case 0: /* No. pFrom+pWLoop will require a separate sort */ + isOrdered = 0; + isOrderedValid = 1; + rCost = sqlite3LogEstAdd(rCost, rSortCost); + break; + default: /* Cannot tell yet. Try again on the next iteration */ + break; + } + }else{ + revMask = pFrom->revLoop; + } + /* Check to see if pWLoop should be added to the mxChoice best so far */ + for(jj=0, pTo=aTo; jjmaskLoop==maskNew + && pTo->isOrderedValid==isOrderedValid + && ((pTo->rCost<=rCost && pTo->nRow<=nOut) || + (pTo->rCost>=rCost && pTo->nRow>=nOut)) + ){ + testcase( jj==nTo-1 ); + break; + } + } + if( jj>=nTo ){ + if( nTo>=mxChoice && rCost>=mxCost ){ +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace&0x4 ){ + sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?'); + } +#endif + continue; + } + /* Add a new Path to the aTo[] set */ + if( nTorCost<=rCost && pTo->nRow<=nOut ){ +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace&0x4 ){ + sqlite3DebugPrintf( + "Skip %s cost=%-3d,%3d order=%c", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?'); + sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n", + wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, + pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?'); + } +#endif + testcase( pTo->rCost==rCost ); + continue; + } + testcase( pTo->rCost==rCost+1 ); + /* A new and better score for a previously created equivalent path */ +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace&0x4 ){ + sqlite3DebugPrintf( + "Update %s cost=%-3d,%3d order=%c", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?'); + sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n", + wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, + pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?'); + } +#endif + } + /* pWLoop is a winner. Add it to the set of best so far */ + pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf; + pTo->revLoop = revMask; + pTo->nRow = nOut; + pTo->rCost = rCost; + pTo->isOrderedValid = isOrderedValid; + pTo->isOrdered = isOrdered; + memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); + pTo->aLoop[iLoop] = pWLoop; + if( nTo>=mxChoice ){ + mxI = 0; + mxCost = aTo[0].rCost; + mxOut = aTo[0].nRow; + for(jj=1, pTo=&aTo[1]; jjrCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){ + mxCost = pTo->rCost; + mxOut = pTo->nRow; + mxI = jj; + } + } + } + } + } + +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace>=2 ){ + sqlite3DebugPrintf("---- after round %d ----\n", iLoop); + for(ii=0, pTo=aTo; iirCost, pTo->nRow, + pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?'); + if( pTo->isOrderedValid && pTo->isOrdered ){ + sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); + }else{ + sqlite3DebugPrintf("\n"); + } + } + } +#endif + + /* Swap the roles of aFrom and aTo for the next generation */ + pFrom = aTo; + aTo = aFrom; + aFrom = pFrom; + nFrom = nTo; + } + + if( nFrom==0 ){ + sqlite3ErrorMsg(pParse, "no query solution"); + sqlite3DbFree(db, pSpace); + return SQLITE_ERROR; + } + + /* Find the lowest cost path. pFrom will be left pointing to that path */ + pFrom = aFrom; + for(ii=1; iirCost>aFrom[ii].rCost ) pFrom = &aFrom[ii]; + } + assert( pWInfo->nLevel==nLoop ); + /* Load the lowest cost path into pWInfo */ + for(iLoop=0; iLoopa + iLoop; + pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop]; + pLevel->iFrom = pWLoop->iTab; + pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor; + } + if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 + && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0 + && pWInfo->eDistinct==WHERE_DISTINCT_NOOP + && nRowEst + ){ + Bitmask notUsed; + int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom, + WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used); + if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; + } + if( pFrom->isOrdered ){ + if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ + pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; + }else{ + pWInfo->bOBSat = 1; + pWInfo->revMask = pFrom->revLoop; + } + } + pWInfo->nRowOut = pFrom->nRow; + + /* Free temporary memory and return success */ + sqlite3DbFree(db, pSpace); + return SQLITE_OK; +} + +/* +** Most queries use only a single table (they are not joins) and have +** simple == constraints against indexed fields. This routine attempts +** to plan those simple cases using much less ceremony than the +** general-purpose query planner, and thereby yield faster sqlite3_prepare() +** times for the common case. +** +** Return non-zero on success, if this query can be handled by this +** no-frills query planner. Return zero if this query needs the +** general-purpose query planner. +*/ +static int whereShortCut(WhereLoopBuilder *pBuilder){ + WhereInfo *pWInfo; + struct SrcList_item *pItem; + WhereClause *pWC; + WhereTerm *pTerm; + WhereLoop *pLoop; + int iCur; + int j; + Table *pTab; + Index *pIdx; + + pWInfo = pBuilder->pWInfo; + if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0; + assert( pWInfo->pTabList->nSrc>=1 ); + pItem = pWInfo->pTabList->a; + pTab = pItem->pTab; + if( IsVirtual(pTab) ) return 0; + if( pItem->zIndex ) return 0; + iCur = pItem->iCursor; + pWC = &pWInfo->sWC; + pLoop = pBuilder->pNew; + pLoop->wsFlags = 0; + pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0); + if( pTerm ){ + pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; + pLoop->aLTerm[0] = pTerm; + pLoop->nLTerm = 1; + pLoop->u.btree.nEq = 1; + /* TUNING: Cost of a rowid lookup is 10 */ + pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ + }else{ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + assert( pLoop->aLTermSpace==pLoop->aLTerm ); + assert( ArraySize(pLoop->aLTermSpace)==4 ); + if( pIdx->onError==OE_None + || pIdx->pPartIdxWhere!=0 + || pIdx->nColumn>ArraySize(pLoop->aLTermSpace) + ) continue; + for(j=0; jnColumn; j++){ + pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx); + if( pTerm==0 ) break; + pLoop->aLTerm[j] = pTerm; + } + if( j!=pIdx->nColumn ) continue; + pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; + if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ + pLoop->wsFlags |= WHERE_IDX_ONLY; + } + pLoop->nLTerm = j; + pLoop->u.btree.nEq = j; + pLoop->u.btree.pIndex = pIdx; + /* TUNING: Cost of a unique index lookup is 15 */ + pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ + break; + } + } + if( pLoop->wsFlags ){ + pLoop->nOut = (LogEst)1; + pWInfo->a[0].pWLoop = pLoop; + pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur); + pWInfo->a[0].iTabCur = iCur; + pWInfo->nRowOut = 1; + if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1; + if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ + pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; + } +#ifdef SQLITE_DEBUG + pLoop->cId = '0'; +#endif + return 1; + } + return 0; +} + +/* +** Generate the beginning of the loop used for WHERE clause processing. +** The return value is a pointer to an opaque structure that contains +** information needed to terminate the loop. Later, the calling routine +** should invoke sqlite3WhereEnd() with the return value of this function +** in order to complete the WHERE clause processing. +** +** If an error occurs, this routine returns NULL. +** +** The basic idea is to do a nested loop, one loop for each table in +** the FROM clause of a select. (INSERT and UPDATE statements are the +** same as a SELECT with only a single table in the FROM clause.) For +** example, if the SQL is this: +** +** SELECT * FROM t1, t2, t3 WHERE ...; +** +** Then the code generated is conceptually like the following: +** +** foreach row1 in t1 do \ Code generated +** foreach row2 in t2 do |-- by sqlite3WhereBegin() +** foreach row3 in t3 do / +** ... +** end \ Code generated +** end |-- by sqlite3WhereEnd() +** end / +** +** Note that the loops might not be nested in the order in which they +** appear in the FROM clause if a different order is better able to make +** use of indices. Note also that when the IN operator appears in +** the WHERE clause, it might result in additional nested loops for +** scanning through all values on the right-hand side of the IN. +** +** There are Btree cursors associated with each table. t1 uses cursor +** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. +** And so forth. This routine generates code to open those VDBE cursors +** and sqlite3WhereEnd() generates the code to close them. +** +** The code that sqlite3WhereBegin() generates leaves the cursors named +** in pTabList pointing at their appropriate entries. The [...] code +** can use OP_Column and OP_Rowid opcodes on these cursors to extract +** data from the various tables of the loop. +** +** If the WHERE clause is empty, the foreach loops must each scan their +** entire tables. Thus a three-way join is an O(N^3) operation. But if +** the tables have indices and there are terms in the WHERE clause that +** refer to those indices, a complete table scan can be avoided and the +** code will run much faster. Most of the work of this routine is checking +** to see if there are indices that can be used to speed up the loop. +** +** Terms of the WHERE clause are also used to limit which rows actually +** make it to the "..." in the middle of the loop. After each "foreach", +** terms of the WHERE clause that use only terms in that loop and outer +** loops are evaluated and if false a jump is made around all subsequent +** inner loops (or around the "..." if the test occurs within the inner- +** most loop) +** +** OUTER JOINS +** +** An outer join of tables t1 and t2 is conceptally coded as follows: +** +** foreach row1 in t1 do +** flag = 0 +** foreach row2 in t2 do +** start: +** ... +** flag = 1 +** end +** if flag==0 then +** move the row2 cursor to a null row +** goto start +** fi +** end +** +** ORDER BY CLAUSE PROCESSING +** +** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause +** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement +** if there is one. If there is no ORDER BY clause or if this routine +** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. +*/ +SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( + Parse *pParse, /* The parser context */ + SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ + Expr *pWhere, /* The WHERE clause */ + ExprList *pOrderBy, /* An ORDER BY clause, or NULL */ + ExprList *pResultSet, /* Result set of the query */ + u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */ + int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */ +){ + int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ + int nTabList; /* Number of elements in pTabList */ + WhereInfo *pWInfo; /* Will become the return value of this function */ + Vdbe *v = pParse->pVdbe; /* The virtual database engine */ + Bitmask notReady; /* Cursors that are not yet positioned */ + WhereLoopBuilder sWLB; /* The WhereLoop builder */ + WhereMaskSet *pMaskSet; /* The expression mask set */ + WhereLevel *pLevel; /* A single level in pWInfo->a[] */ + WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ + int ii; /* Loop counter */ + sqlite3 *db; /* Database connection */ + int rc; /* Return code */ + + + /* Variable initialization */ + db = pParse->db; + memset(&sWLB, 0, sizeof(sWLB)); + sWLB.pOrderBy = pOrderBy; + + /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via + ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ + if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ + wctrlFlags &= ~WHERE_WANT_DISTINCT; + } + + /* The number of tables in the FROM clause is limited by the number of + ** bits in a Bitmask + */ + testcase( pTabList->nSrc==BMS ); + if( pTabList->nSrc>BMS ){ + sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); + return 0; + } + + /* This function normally generates a nested loop for all tables in + ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should + ** only generate code for the first table in pTabList and assume that + ** any cursors associated with subsequent tables are uninitialized. + */ + nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc; + + /* Allocate and initialize the WhereInfo structure that will become the + ** return value. A single allocation is used to store the WhereInfo + ** struct, the contents of WhereInfo.a[], the WhereClause structure + ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte + ** field (type Bitmask) it must be aligned on an 8-byte boundary on + ** some architectures. Hence the ROUND8() below. + */ + nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); + pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop)); + if( db->mallocFailed ){ + sqlite3DbFree(db, pWInfo); + pWInfo = 0; + goto whereBeginError; + } + pWInfo->nLevel = nTabList; + pWInfo->pParse = pParse; + pWInfo->pTabList = pTabList; + pWInfo->pOrderBy = pOrderBy; + pWInfo->pResultSet = pResultSet; + pWInfo->iBreak = sqlite3VdbeMakeLabel(v); + pWInfo->wctrlFlags = wctrlFlags; + pWInfo->savedNQueryLoop = pParse->nQueryLoop; + pMaskSet = &pWInfo->sMaskSet; + sWLB.pWInfo = pWInfo; + sWLB.pWC = &pWInfo->sWC; + sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); + assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); + whereLoopInit(sWLB.pNew); +#ifdef SQLITE_DEBUG + sWLB.pNew->cId = '*'; +#endif + + /* Split the WHERE clause into separate subexpressions where each + ** subexpression is separated by an AND operator. + */ + initMaskSet(pMaskSet); + whereClauseInit(&pWInfo->sWC, pWInfo); + sqlite3ExprCodeConstants(pParse, pWhere); + whereSplit(&pWInfo->sWC, pWhere, TK_AND); + sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */ + + /* Special case: a WHERE clause that is constant. Evaluate the + ** expression and either jump over all of the code or fall thru. + */ + if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){ + sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL); + pWhere = 0; + } + + /* Special case: No FROM clause + */ + if( nTabList==0 ){ + if( pOrderBy ) pWInfo->bOBSat = 1; + if( wctrlFlags & WHERE_WANT_DISTINCT ){ + pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; + } + } + + /* Assign a bit from the bitmask to every term in the FROM clause. + ** + ** When assigning bitmask values to FROM clause cursors, it must be + ** the case that if X is the bitmask for the N-th FROM clause term then + ** the bitmask for all FROM clause terms to the left of the N-th term + ** is (X-1). An expression from the ON clause of a LEFT JOIN can use + ** its Expr.iRightJoinTable value to find the bitmask of the right table + ** of the join. Subtracting one from the right table bitmask gives a + ** bitmask for all tables to the left of the join. Knowing the bitmask + ** for all tables to the left of a left join is important. Ticket #3015. + ** + ** Note that bitmasks are created for all pTabList->nSrc tables in + ** pTabList, not just the first nTabList tables. nTabList is normally + ** equal to pTabList->nSrc but might be shortened to 1 if the + ** WHERE_ONETABLE_ONLY flag is set. + */ + for(ii=0; iinSrc; ii++){ + createMask(pMaskSet, pTabList->a[ii].iCursor); + } +#ifndef NDEBUG + { + Bitmask toTheLeft = 0; + for(ii=0; iinSrc; ii++){ + Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor); + assert( (m-1)==toTheLeft ); + toTheLeft |= m; + } + } +#endif + + /* Analyze all of the subexpressions. Note that exprAnalyze() might + ** add new virtual terms onto the end of the WHERE clause. We do not + ** want to analyze these virtual terms, so start analyzing at the end + ** and work forward so that the added virtual terms are never processed. + */ + exprAnalyzeAll(pTabList, &pWInfo->sWC); + if( db->mallocFailed ){ + goto whereBeginError; + } + + /* If the ORDER BY (or GROUP BY) clause contains references to general + ** expressions, then we won't be able to satisfy it using indices, so + ** go ahead and disable it now. + */ + if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){ + for(ii=0; iinExpr; ii++){ + Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr); + if( pExpr->op!=TK_COLUMN ){ + pWInfo->pOrderBy = pOrderBy = 0; + break; + }else if( pExpr->iColumn<0 ){ + break; + } + } + } + + if( wctrlFlags & WHERE_WANT_DISTINCT ){ + if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){ + /* The DISTINCT marking is pointless. Ignore it. */ + pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; + }else if( pOrderBy==0 ){ + /* Try to ORDER BY the result set to make distinct processing easier */ + pWInfo->wctrlFlags |= WHERE_DISTINCTBY; + pWInfo->pOrderBy = pResultSet; + } + } + + /* Construct the WhereLoop objects */ + WHERETRACE(0xffff,("*** Optimizer Start ***\n")); + if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ + rc = whereLoopAddAll(&sWLB); + if( rc ) goto whereBeginError; + + /* Display all of the WhereLoop objects if wheretrace is enabled */ +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace ){ + WhereLoop *p; + int i; + static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" + "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; + for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ + p->cId = zLabel[i%sizeof(zLabel)]; + whereLoopPrint(p, pTabList); + } + } +#endif + + wherePathSolver(pWInfo, 0); + if( db->mallocFailed ) goto whereBeginError; + if( pWInfo->pOrderBy ){ + wherePathSolver(pWInfo, pWInfo->nRowOut+1); + if( db->mallocFailed ) goto whereBeginError; + } + } + if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ + pWInfo->revMask = (Bitmask)(-1); + } + if( pParse->nErr || NEVER(db->mallocFailed) ){ + goto whereBeginError; + } +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace ){ + int ii; + sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); + if( pWInfo->bOBSat ){ + sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask); + } + switch( pWInfo->eDistinct ){ + case WHERE_DISTINCT_UNIQUE: { + sqlite3DebugPrintf(" DISTINCT=unique"); + break; + } + case WHERE_DISTINCT_ORDERED: { + sqlite3DebugPrintf(" DISTINCT=ordered"); + break; + } + case WHERE_DISTINCT_UNORDERED: { + sqlite3DebugPrintf(" DISTINCT=unordered"); + break; + } + } + sqlite3DebugPrintf("\n"); + for(ii=0; iinLevel; ii++){ + whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList); + } + } +#endif + /* Attempt to omit tables from the join that do not effect the result */ + if( pWInfo->nLevel>=2 + && pResultSet!=0 + && OptimizationEnabled(db, SQLITE_OmitNoopJoin) + ){ + Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet); + if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy); + while( pWInfo->nLevel>=2 ){ + WhereTerm *pTerm, *pEnd; + pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop; + if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break; + if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 + && (pLoop->wsFlags & WHERE_ONEROW)==0 + ){ + break; + } + if( (tabUsed & pLoop->maskSelf)!=0 ) break; + pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; + for(pTerm=sWLB.pWC->a; pTermprereqAll & pLoop->maskSelf)!=0 + && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) + ){ + break; + } + } + if( pTerm drop loop %c not used\n", pLoop->cId)); + pWInfo->nLevel--; + nTabList--; + } + } + WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); + pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; + + /* If the caller is an UPDATE or DELETE statement that is requesting + ** to use a one-pass algorithm, determine if this is appropriate. + ** The one-pass algorithm only works if the WHERE clause constrains + ** the statement to update a single row. + */ + assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); + if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 + && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){ + pWInfo->okOnePass = 1; + pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY; + } + + /* Open all tables in the pTabList and any indices selected for + ** searching those tables. + */ + notReady = ~(Bitmask)0; + for(ii=0, pLevel=pWInfo->a; iia[pLevel->iFrom]; + pTab = pTabItem->pTab; + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + pLoop = pLevel->pWLoop; + if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ + /* Do nothing */ + }else +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ + const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); + int iCur = pTabItem->iCursor; + sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); + }else if( IsVirtual(pTab) ){ + /* noop */ + }else +#endif + if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 + && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){ + int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead; + sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); + testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 ); + testcase( !pWInfo->okOnePass && pTab->nCol==BMS ); + if( !pWInfo->okOnePass && pTab->nColcolUsed; + int n = 0; + for(; b; b=b>>1, n++){} + sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, + SQLITE_INT_TO_PTR(n), P4_INT32); + assert( n<=pTab->nCol ); + } + }else{ + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + } + if( pLoop->wsFlags & WHERE_INDEXED ){ + Index *pIx = pLoop->u.btree.pIndex; + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx); + /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */ + int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++; + assert( pIx->pSchema==pTab->pSchema ); + assert( iIndexCur>=0 ); + sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb, + (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIx->zName)); + } + sqlite3CodeVerifySchema(pParse, iDb); + notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor); + } + pWInfo->iTop = sqlite3VdbeCurrentAddr(v); + if( db->mallocFailed ) goto whereBeginError; + + /* Generate the code to do the search. Each iteration of the for + ** loop below generates code for a single nested loop of the VM + ** program. + */ + notReady = ~(Bitmask)0; + for(ii=0; iia[ii]; +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX + if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){ + constructAutomaticIndex(pParse, &pWInfo->sWC, + &pTabList->a[pLevel->iFrom], notReady, pLevel); + if( db->mallocFailed ) goto whereBeginError; + } +#endif + explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags); + pLevel->addrBody = sqlite3VdbeCurrentAddr(v); + notReady = codeOneLoopStart(pWInfo, ii, notReady); + pWInfo->iContinue = pLevel->addrCont; + } + + /* Done. */ + return pWInfo; + + /* Jump here if malloc fails */ +whereBeginError: + if( pWInfo ){ + pParse->nQueryLoop = pWInfo->savedNQueryLoop; + whereInfoFree(db, pWInfo); + } + return 0; +} + +/* +** Generate the end of the WHERE loop. See comments on +** sqlite3WhereBegin() for additional information. +*/ +SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ + Parse *pParse = pWInfo->pParse; + Vdbe *v = pParse->pVdbe; + int i; + WhereLevel *pLevel; + WhereLoop *pLoop; + SrcList *pTabList = pWInfo->pTabList; + sqlite3 *db = pParse->db; + + /* Generate loop termination code. + */ + sqlite3ExprCacheClear(pParse); + for(i=pWInfo->nLevel-1; i>=0; i--){ + pLevel = &pWInfo->a[i]; + pLoop = pLevel->pWLoop; + sqlite3VdbeResolveLabel(v, pLevel->addrCont); + if( pLevel->op!=OP_Noop ){ + sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2); + sqlite3VdbeChangeP5(v, pLevel->p5); + } + if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ + struct InLoop *pIn; + int j; + sqlite3VdbeResolveLabel(v, pLevel->addrNxt); + for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ + sqlite3VdbeJumpHere(v, pIn->addrInTop+1); + sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); + sqlite3VdbeJumpHere(v, pIn->addrInTop-1); + } + sqlite3DbFree(db, pLevel->u.in.aInLoop); + } + sqlite3VdbeResolveLabel(v, pLevel->addrBrk); + if( pLevel->iLeftJoin ){ + int addr; + addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); + assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 + || (pLoop->wsFlags & WHERE_INDEXED)!=0 ); + if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){ + sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); + } + if( pLoop->wsFlags & WHERE_INDEXED ){ + sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); + } + if( pLevel->op==OP_Return ){ + sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); + }else{ + sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst); + } + sqlite3VdbeJumpHere(v, addr); + } + } + + /* The "break" point is here, just past the end of the outer loop. + ** Set it. + */ + sqlite3VdbeResolveLabel(v, pWInfo->iBreak); + + /* Close all of the cursors that were opened by sqlite3WhereBegin. + */ + assert( pWInfo->nLevel<=pTabList->nSrc ); + for(i=0, pLevel=pWInfo->a; inLevel; i++, pLevel++){ + Index *pIdx = 0; + struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; + Table *pTab = pTabItem->pTab; + assert( pTab!=0 ); + pLoop = pLevel->pWLoop; + if( (pTab->tabFlags & TF_Ephemeral)==0 + && pTab->pSelect==0 + && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 + ){ + int ws = pLoop->wsFlags; + if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){ + sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); + } + if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){ + sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); + } + } + + /* If this scan uses an index, make VDBE code substitutions to read data + ** from the index instead of from the table where possible. In some cases + ** this optimization prevents the table from ever being read, which can + ** yield a significant performance boost. + ** + ** Calls to the code generator in between sqlite3WhereBegin and + ** sqlite3WhereEnd will have created code that references the table + ** directly. This loop scans all that code looking for opcodes + ** that reference the table and converts them into opcodes that + ** reference the index. + */ + if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ + pIdx = pLoop->u.btree.pIndex; + }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ + pIdx = pLevel->u.pCovidx; + } + if( pIdx && !db->mallocFailed ){ + int k, j, last; + VdbeOp *pOp; + + last = sqlite3VdbeCurrentAddr(v); + k = pLevel->addrBody; + pOp = sqlite3VdbeGetOp(v, k); + for(; kp1!=pLevel->iTabCur ) continue; + if( pOp->opcode==OP_Column ){ + for(j=0; jnColumn; j++){ + if( pOp->p2==pIdx->aiColumn[j] ){ + pOp->p2 = j; + pOp->p1 = pLevel->iIdxCur; + break; + } + } + assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || jnColumn ); + }else if( pOp->opcode==OP_Rowid ){ + pOp->p1 = pLevel->iIdxCur; + pOp->opcode = OP_IdxRowid; + } + } + } + } + + /* Final cleanup + */ + pParse->nQueryLoop = pWInfo->savedNQueryLoop; + whereInfoFree(db, pWInfo); + return; +} + +/************** End of where.c ***********************************************/ +/************** Begin file parse.c *******************************************/ +/* Driver template for the LEMON parser generator. +** The author disclaims copyright to this source code. +** +** This version of "lempar.c" is modified, slightly, for use by SQLite. +** The only modifications are the addition of a couple of NEVER() +** macros to disable tests that are needed in the case of a general +** LALR(1) grammar but which are always false in the +** specific grammar used by SQLite. +*/ +/* First off, code is included that follows the "include" declaration +** in the input grammar file. */ +/* #include */ + + +/* +** Disable all error recovery processing in the parser push-down +** automaton. +*/ +#define YYNOERRORRECOVERY 1 + +/* +** Make yytestcase() the same as testcase() +*/ +#define yytestcase(X) testcase(X) + +/* +** An instance of this structure holds information about the +** LIMIT clause of a SELECT statement. +*/ +struct LimitVal { + Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */ + Expr *pOffset; /* The OFFSET expression. NULL if there is none */ +}; + +/* +** An instance of this structure is used to store the LIKE, +** GLOB, NOT LIKE, and NOT GLOB operators. +*/ +struct LikeOp { + Token eOperator; /* "like" or "glob" or "regexp" */ + int bNot; /* True if the NOT keyword is present */ +}; + +/* +** An instance of the following structure describes the event of a +** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT, +** TK_DELETE, or TK_INSTEAD. If the event is of the form +** +** UPDATE ON (a,b,c) +** +** Then the "b" IdList records the list "a,b,c". +*/ +struct TrigEvent { int a; IdList * b; }; + +/* +** An instance of this structure holds the ATTACH key and the key type. +*/ +struct AttachKey { int type; Token key; }; + +/* +** One or more VALUES claues +*/ +struct ValueList { + ExprList *pList; + Select *pSelect; +}; + + + /* This is a utility routine used to set the ExprSpan.zStart and + ** ExprSpan.zEnd values of pOut so that the span covers the complete + ** range of text beginning with pStart and going to the end of pEnd. + */ + static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){ + pOut->zStart = pStart->z; + pOut->zEnd = &pEnd->z[pEnd->n]; + } + + /* Construct a new Expr object from a single identifier. Use the + ** new Expr to populate pOut. Set the span of pOut to be the identifier + ** that created the expression. + */ + static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){ + pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue); + pOut->zStart = pValue->z; + pOut->zEnd = &pValue->z[pValue->n]; + } + + /* This routine constructs a binary expression node out of two ExprSpan + ** objects and uses the result to populate a new ExprSpan object. + */ + static void spanBinaryExpr( + ExprSpan *pOut, /* Write the result here */ + Parse *pParse, /* The parsing context. Errors accumulate here */ + int op, /* The binary operation */ + ExprSpan *pLeft, /* The left operand */ + ExprSpan *pRight /* The right operand */ + ){ + pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0); + pOut->zStart = pLeft->zStart; + pOut->zEnd = pRight->zEnd; + } + + /* Construct an expression node for a unary postfix operator + */ + static void spanUnaryPostfix( + ExprSpan *pOut, /* Write the new expression node here */ + Parse *pParse, /* Parsing context to record errors */ + int op, /* The operator */ + ExprSpan *pOperand, /* The operand */ + Token *pPostOp /* The operand token for setting the span */ + ){ + pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0); + pOut->zStart = pOperand->zStart; + pOut->zEnd = &pPostOp->z[pPostOp->n]; + } + + /* A routine to convert a binary TK_IS or TK_ISNOT expression into a + ** unary TK_ISNULL or TK_NOTNULL expression. */ + static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){ + sqlite3 *db = pParse->db; + if( db->mallocFailed==0 && pY->op==TK_NULL ){ + pA->op = (u8)op; + sqlite3ExprDelete(db, pA->pRight); + pA->pRight = 0; + } + } + + /* Construct an expression node for a unary prefix operator + */ + static void spanUnaryPrefix( + ExprSpan *pOut, /* Write the new expression node here */ + Parse *pParse, /* Parsing context to record errors */ + int op, /* The operator */ + ExprSpan *pOperand, /* The operand */ + Token *pPreOp /* The operand token for setting the span */ + ){ + pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0); + pOut->zStart = pPreOp->z; + pOut->zEnd = pOperand->zEnd; + } +/* Next is all token values, in a form suitable for use by makeheaders. +** This section will be null unless lemon is run with the -m switch. +*/ +/* +** These constants (all generated automatically by the parser generator) +** specify the various kinds of tokens (terminals) that the parser +** understands. +** +** Each symbol here is a terminal symbol in the grammar. +*/ +/* Make sure the INTERFACE macro is defined. +*/ +#ifndef INTERFACE +# define INTERFACE 1 +#endif +/* The next thing included is series of defines which control +** various aspects of the generated parser. +** YYCODETYPE is the data type used for storing terminal +** and nonterminal numbers. "unsigned char" is +** used if there are fewer than 250 terminals +** and nonterminals. "int" is used otherwise. +** YYNOCODE is a number of type YYCODETYPE which corresponds +** to no legal terminal or nonterminal number. This +** number is used to fill in empty slots of the hash +** table. +** YYFALLBACK If defined, this indicates that one or more tokens +** have fall-back values which should be used if the +** original value of the token will not parse. +** YYACTIONTYPE is the data type used for storing terminal +** and nonterminal numbers. "unsigned char" is +** used if there are fewer than 250 rules and +** states combined. "int" is used otherwise. +** sqlite3ParserTOKENTYPE is the data type used for minor tokens given +** directly to the parser from the tokenizer. +** YYMINORTYPE is the data type used for all minor tokens. +** This is typically a union of many types, one of +** which is sqlite3ParserTOKENTYPE. The entry in the union +** for base tokens is called "yy0". +** YYSTACKDEPTH is the maximum depth of the parser's stack. If +** zero the stack is dynamically sized using realloc() +** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument +** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument +** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser +** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser +** YYNSTATE the combined number of states. +** YYNRULE the number of rules in the grammar +** YYERRORSYMBOL is the code number of the error symbol. If not +** defined, then do no error processing. +*/ +#define YYCODETYPE unsigned char +#define YYNOCODE 251 +#define YYACTIONTYPE unsigned short int +#define YYWILDCARD 67 +#define sqlite3ParserTOKENTYPE Token +typedef union { + int yyinit; + sqlite3ParserTOKENTYPE yy0; + struct LimitVal yy64; + Expr* yy122; + Select* yy159; + IdList* yy180; + struct {int value; int mask;} yy207; + u8 yy258; + u16 yy305; + struct LikeOp yy318; + TriggerStep* yy327; + ExprSpan yy342; + SrcList* yy347; + int yy392; + struct TrigEvent yy410; + ExprList* yy442; + struct ValueList yy487; +} YYMINORTYPE; +#ifndef YYSTACKDEPTH +#define YYSTACKDEPTH 100 +#endif +#define sqlite3ParserARG_SDECL Parse *pParse; +#define sqlite3ParserARG_PDECL ,Parse *pParse +#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse +#define sqlite3ParserARG_STORE yypParser->pParse = pParse +#define YYNSTATE 628 +#define YYNRULE 327 +#define YYFALLBACK 1 +#define YY_NO_ACTION (YYNSTATE+YYNRULE+2) +#define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) +#define YY_ERROR_ACTION (YYNSTATE+YYNRULE) + +/* The yyzerominor constant is used to initialize instances of +** YYMINORTYPE objects to zero. */ +static const YYMINORTYPE yyzerominor = { 0 }; + +/* Define the yytestcase() macro to be a no-op if is not already defined +** otherwise. +** +** Applications can choose to define yytestcase() in the %include section +** to a macro that can assist in verifying code coverage. For production +** code the yytestcase() macro should be turned off. But it is useful +** for testing. +*/ +#ifndef yytestcase +# define yytestcase(X) +#endif + + +/* Next are the tables used to determine what action to take based on the +** current state and lookahead token. These tables are used to implement +** functions that take a state number and lookahead value and return an +** action integer. +** +** Suppose the action integer is N. Then the action is determined as +** follows +** +** 0 <= N < YYNSTATE Shift N. That is, push the lookahead +** token onto the stack and goto state N. +** +** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. +** +** N == YYNSTATE+YYNRULE A syntax error has occurred. +** +** N == YYNSTATE+YYNRULE+1 The parser accepts its input. +** +** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused +** slots in the yy_action[] table. +** +** The action table is constructed as a single large table named yy_action[]. +** Given state S and lookahead X, the action is computed as +** +** yy_action[ yy_shift_ofst[S] + X ] +** +** If the index value yy_shift_ofst[S]+X is out of range or if the value +** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] +** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table +** and that yy_default[S] should be used instead. +** +** The formula above is for computing the action when the lookahead is +** a terminal symbol. If the lookahead is a non-terminal (as occurs after +** a reduce action) then the yy_reduce_ofst[] array is used in place of +** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of +** YY_SHIFT_USE_DFLT. +** +** The following are the tables generated in this section: +** +** yy_action[] A single table containing all actions. +** yy_lookahead[] A table containing the lookahead for each entry in +** yy_action. Used to detect hash collisions. +** yy_shift_ofst[] For each state, the offset into yy_action for +** shifting terminals. +** yy_reduce_ofst[] For each state, the offset into yy_action for +** shifting non-terminals after a reduce. +** yy_default[] Default action for each state. +*/ +#define YY_ACTTAB_COUNT (1564) +static const YYACTIONTYPE yy_action[] = { + /* 0 */ 310, 956, 184, 418, 2, 171, 625, 595, 56, 56, + /* 10 */ 56, 56, 49, 54, 54, 54, 54, 53, 53, 52, + /* 20 */ 52, 52, 51, 233, 621, 620, 299, 621, 620, 234, + /* 30 */ 588, 582, 56, 56, 56, 56, 19, 54, 54, 54, + /* 40 */ 54, 53, 53, 52, 52, 52, 51, 233, 606, 57, + /* 50 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56, + /* 60 */ 56, 56, 542, 54, 54, 54, 54, 53, 53, 52, + /* 70 */ 52, 52, 51, 233, 310, 595, 326, 196, 195, 194, + /* 80 */ 33, 54, 54, 54, 54, 53, 53, 52, 52, 52, + /* 90 */ 51, 233, 618, 617, 165, 618, 617, 381, 378, 377, + /* 100 */ 408, 533, 577, 577, 588, 582, 304, 423, 376, 59, + /* 110 */ 53, 53, 52, 52, 52, 51, 233, 50, 47, 146, + /* 120 */ 575, 546, 65, 57, 58, 48, 580, 579, 581, 581, + /* 130 */ 55, 55, 56, 56, 56, 56, 213, 54, 54, 54, + /* 140 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 223, + /* 150 */ 540, 421, 170, 176, 138, 281, 384, 276, 383, 168, + /* 160 */ 490, 552, 410, 669, 621, 620, 272, 439, 410, 439, + /* 170 */ 551, 605, 67, 483, 508, 619, 600, 413, 588, 582, + /* 180 */ 601, 484, 619, 413, 619, 599, 91, 440, 441, 440, + /* 190 */ 336, 599, 73, 670, 222, 267, 481, 57, 58, 48, + /* 200 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56, + /* 210 */ 671, 54, 54, 54, 54, 53, 53, 52, 52, 52, + /* 220 */ 51, 233, 310, 280, 232, 231, 1, 132, 200, 386, + /* 230 */ 621, 620, 618, 617, 279, 436, 290, 564, 175, 263, + /* 240 */ 410, 265, 438, 498, 437, 166, 442, 569, 337, 569, + /* 250 */ 201, 538, 588, 582, 600, 413, 165, 595, 601, 381, + /* 260 */ 378, 377, 598, 599, 92, 524, 619, 570, 570, 593, + /* 270 */ 376, 57, 58, 48, 580, 579, 581, 581, 55, 55, + /* 280 */ 56, 56, 56, 56, 598, 54, 54, 54, 54, 53, + /* 290 */ 53, 52, 52, 52, 51, 233, 310, 464, 618, 617, + /* 300 */ 591, 591, 591, 174, 273, 397, 410, 273, 410, 549, + /* 310 */ 398, 621, 620, 68, 327, 621, 620, 621, 620, 619, + /* 320 */ 547, 413, 619, 413, 472, 595, 588, 582, 473, 599, + /* 330 */ 92, 599, 92, 52, 52, 52, 51, 233, 514, 513, + /* 340 */ 206, 323, 364, 465, 221, 57, 58, 48, 580, 579, + /* 350 */ 581, 581, 55, 55, 56, 56, 56, 56, 530, 54, + /* 360 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233, + /* 370 */ 310, 397, 410, 397, 598, 373, 387, 531, 348, 618, + /* 380 */ 617, 576, 202, 618, 617, 618, 617, 413, 621, 620, + /* 390 */ 145, 255, 347, 254, 578, 599, 74, 352, 45, 490, + /* 400 */ 588, 582, 235, 189, 465, 545, 167, 297, 187, 470, + /* 410 */ 480, 67, 62, 39, 619, 547, 598, 346, 574, 57, + /* 420 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56, + /* 430 */ 56, 56, 6, 54, 54, 54, 54, 53, 53, 52, + /* 440 */ 52, 52, 51, 233, 310, 563, 559, 408, 529, 577, + /* 450 */ 577, 345, 255, 347, 254, 182, 618, 617, 504, 505, + /* 460 */ 315, 410, 558, 235, 166, 272, 410, 353, 565, 181, + /* 470 */ 408, 547, 577, 577, 588, 582, 413, 538, 557, 562, + /* 480 */ 518, 413, 619, 249, 599, 16, 7, 36, 468, 599, + /* 490 */ 92, 517, 619, 57, 58, 48, 580, 579, 581, 581, + /* 500 */ 55, 55, 56, 56, 56, 56, 542, 54, 54, 54, + /* 510 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 328, + /* 520 */ 573, 572, 526, 559, 561, 395, 872, 246, 410, 248, + /* 530 */ 171, 393, 595, 219, 408, 410, 577, 577, 503, 558, + /* 540 */ 365, 145, 511, 413, 408, 229, 577, 577, 588, 582, + /* 550 */ 413, 599, 92, 382, 270, 557, 166, 401, 599, 69, + /* 560 */ 502, 420, 946, 199, 946, 198, 547, 57, 58, 48, + /* 570 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56, + /* 580 */ 569, 54, 54, 54, 54, 53, 53, 52, 52, 52, + /* 590 */ 51, 233, 310, 318, 420, 945, 509, 945, 309, 598, + /* 600 */ 595, 566, 491, 212, 173, 247, 424, 616, 615, 614, + /* 610 */ 324, 197, 143, 406, 573, 572, 490, 66, 50, 47, + /* 620 */ 146, 595, 588, 582, 232, 231, 560, 428, 67, 556, + /* 630 */ 15, 619, 186, 544, 304, 422, 35, 206, 433, 424, + /* 640 */ 553, 57, 58, 48, 580, 579, 581, 581, 55, 55, + /* 650 */ 56, 56, 56, 56, 205, 54, 54, 54, 54, 53, + /* 660 */ 53, 52, 52, 52, 51, 233, 310, 570, 570, 261, + /* 670 */ 269, 598, 12, 374, 569, 166, 410, 314, 410, 421, + /* 680 */ 410, 474, 474, 366, 619, 50, 47, 146, 598, 595, + /* 690 */ 256, 413, 166, 413, 352, 413, 588, 582, 32, 599, + /* 700 */ 94, 599, 97, 599, 95, 628, 626, 330, 142, 50, + /* 710 */ 47, 146, 334, 350, 359, 57, 58, 48, 580, 579, + /* 720 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54, + /* 730 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233, + /* 740 */ 310, 410, 389, 413, 410, 22, 566, 405, 212, 363, + /* 750 */ 390, 599, 104, 360, 410, 156, 413, 410, 604, 413, + /* 760 */ 538, 332, 570, 570, 599, 103, 494, 599, 105, 413, + /* 770 */ 588, 582, 413, 261, 550, 619, 11, 599, 106, 522, + /* 780 */ 599, 133, 169, 458, 457, 170, 35, 602, 619, 57, + /* 790 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56, + /* 800 */ 56, 56, 410, 54, 54, 54, 54, 53, 53, 52, + /* 810 */ 52, 52, 51, 233, 310, 410, 260, 413, 410, 50, + /* 820 */ 47, 146, 358, 319, 356, 599, 134, 528, 353, 338, + /* 830 */ 413, 410, 357, 413, 358, 410, 358, 619, 599, 98, + /* 840 */ 129, 599, 102, 619, 588, 582, 413, 21, 235, 619, + /* 850 */ 413, 619, 211, 143, 599, 101, 30, 167, 599, 93, + /* 860 */ 351, 536, 203, 57, 58, 48, 580, 579, 581, 581, + /* 870 */ 55, 55, 56, 56, 56, 56, 410, 54, 54, 54, + /* 880 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 410, + /* 890 */ 527, 413, 410, 426, 215, 306, 598, 552, 141, 599, + /* 900 */ 100, 40, 410, 38, 413, 410, 551, 413, 410, 228, + /* 910 */ 220, 315, 599, 77, 501, 599, 96, 413, 588, 582, + /* 920 */ 413, 339, 253, 413, 218, 599, 137, 380, 599, 136, + /* 930 */ 28, 599, 135, 271, 716, 210, 482, 57, 58, 48, + /* 940 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56, + /* 950 */ 410, 54, 54, 54, 54, 53, 53, 52, 52, 52, + /* 960 */ 51, 233, 310, 410, 273, 413, 410, 316, 147, 598, + /* 970 */ 273, 627, 2, 599, 76, 209, 410, 127, 413, 619, + /* 980 */ 126, 413, 410, 622, 235, 619, 599, 90, 375, 599, + /* 990 */ 89, 413, 588, 582, 27, 261, 351, 413, 619, 599, + /* 1000 */ 75, 322, 542, 542, 125, 599, 88, 321, 279, 598, + /* 1010 */ 619, 57, 46, 48, 580, 579, 581, 581, 55, 55, + /* 1020 */ 56, 56, 56, 56, 410, 54, 54, 54, 54, 53, + /* 1030 */ 53, 52, 52, 52, 51, 233, 310, 410, 451, 413, + /* 1040 */ 164, 285, 283, 273, 610, 425, 305, 599, 87, 371, + /* 1050 */ 410, 478, 413, 410, 609, 410, 608, 603, 619, 619, + /* 1060 */ 599, 99, 587, 586, 122, 413, 588, 582, 413, 619, + /* 1070 */ 413, 619, 619, 599, 86, 367, 599, 17, 599, 85, + /* 1080 */ 320, 185, 520, 519, 584, 583, 58, 48, 580, 579, + /* 1090 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54, + /* 1100 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233, + /* 1110 */ 310, 585, 410, 413, 410, 261, 261, 261, 409, 592, + /* 1120 */ 475, 599, 84, 170, 410, 467, 519, 413, 121, 413, + /* 1130 */ 619, 619, 619, 619, 619, 599, 83, 599, 72, 413, + /* 1140 */ 588, 582, 51, 233, 626, 330, 471, 599, 71, 258, + /* 1150 */ 159, 120, 14, 463, 157, 158, 117, 261, 449, 448, + /* 1160 */ 447, 48, 580, 579, 581, 581, 55, 55, 56, 56, + /* 1170 */ 56, 56, 619, 54, 54, 54, 54, 53, 53, 52, + /* 1180 */ 52, 52, 51, 233, 44, 404, 261, 3, 410, 460, + /* 1190 */ 261, 414, 620, 118, 399, 10, 25, 24, 555, 349, + /* 1200 */ 217, 619, 407, 413, 410, 619, 4, 44, 404, 619, + /* 1210 */ 3, 599, 82, 619, 414, 620, 456, 543, 115, 413, + /* 1220 */ 539, 402, 537, 275, 507, 407, 251, 599, 81, 216, + /* 1230 */ 274, 564, 619, 243, 454, 619, 154, 619, 619, 619, + /* 1240 */ 450, 417, 624, 110, 402, 619, 410, 236, 64, 123, + /* 1250 */ 488, 41, 42, 532, 564, 204, 410, 268, 43, 412, + /* 1260 */ 411, 413, 266, 593, 108, 619, 107, 435, 333, 599, + /* 1270 */ 80, 413, 619, 264, 41, 42, 444, 619, 410, 599, + /* 1280 */ 70, 43, 412, 411, 434, 262, 593, 149, 619, 598, + /* 1290 */ 257, 237, 188, 413, 591, 591, 591, 590, 589, 13, + /* 1300 */ 619, 599, 18, 329, 235, 619, 44, 404, 361, 3, + /* 1310 */ 419, 462, 340, 414, 620, 227, 124, 591, 591, 591, + /* 1320 */ 590, 589, 13, 619, 407, 410, 619, 410, 139, 34, + /* 1330 */ 404, 388, 3, 148, 623, 313, 414, 620, 312, 331, + /* 1340 */ 413, 461, 413, 402, 180, 354, 413, 407, 599, 79, + /* 1350 */ 599, 78, 250, 564, 599, 9, 619, 613, 612, 611, + /* 1360 */ 619, 8, 453, 443, 242, 416, 402, 619, 239, 235, + /* 1370 */ 179, 238, 429, 41, 42, 289, 564, 619, 619, 619, + /* 1380 */ 43, 412, 411, 619, 144, 593, 619, 619, 177, 61, + /* 1390 */ 619, 597, 392, 621, 620, 288, 41, 42, 415, 619, + /* 1400 */ 294, 30, 394, 43, 412, 411, 293, 619, 593, 31, + /* 1410 */ 619, 396, 292, 60, 230, 37, 591, 591, 591, 590, + /* 1420 */ 589, 13, 214, 554, 183, 291, 172, 302, 301, 300, + /* 1430 */ 178, 298, 596, 564, 452, 29, 286, 391, 541, 591, + /* 1440 */ 591, 591, 590, 589, 13, 284, 521, 535, 150, 534, + /* 1450 */ 241, 282, 385, 192, 191, 325, 516, 515, 277, 240, + /* 1460 */ 511, 524, 308, 512, 128, 593, 510, 225, 226, 487, + /* 1470 */ 486, 224, 152, 492, 465, 307, 485, 163, 153, 372, + /* 1480 */ 479, 151, 162, 259, 370, 161, 368, 208, 476, 477, + /* 1490 */ 26, 160, 469, 466, 362, 140, 591, 591, 591, 116, + /* 1500 */ 119, 455, 344, 155, 114, 343, 113, 112, 446, 111, + /* 1510 */ 131, 109, 432, 317, 130, 431, 23, 20, 430, 427, + /* 1520 */ 190, 63, 255, 342, 244, 607, 295, 287, 311, 594, + /* 1530 */ 278, 508, 496, 235, 493, 571, 497, 568, 495, 403, + /* 1540 */ 459, 379, 355, 245, 193, 303, 567, 296, 341, 5, + /* 1550 */ 445, 548, 506, 207, 525, 500, 335, 489, 252, 369, + /* 1560 */ 400, 499, 523, 233, +}; +static const YYCODETYPE yy_lookahead[] = { + /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78, + /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, + /* 20 */ 89, 90, 91, 92, 26, 27, 15, 26, 27, 197, + /* 30 */ 49, 50, 77, 78, 79, 80, 204, 82, 83, 84, + /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 23, 68, + /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, + /* 60 */ 79, 80, 166, 82, 83, 84, 85, 86, 87, 88, + /* 70 */ 89, 90, 91, 92, 19, 94, 19, 105, 106, 107, + /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90, + /* 90 */ 91, 92, 94, 95, 96, 94, 95, 99, 100, 101, + /* 100 */ 112, 205, 114, 115, 49, 50, 22, 23, 110, 54, + /* 110 */ 86, 87, 88, 89, 90, 91, 92, 221, 222, 223, + /* 120 */ 23, 120, 25, 68, 69, 70, 71, 72, 73, 74, + /* 130 */ 75, 76, 77, 78, 79, 80, 22, 82, 83, 84, + /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 92, + /* 150 */ 23, 67, 25, 96, 97, 98, 99, 100, 101, 102, + /* 160 */ 150, 32, 150, 118, 26, 27, 109, 150, 150, 150, + /* 170 */ 41, 161, 162, 180, 181, 165, 113, 165, 49, 50, + /* 180 */ 117, 188, 165, 165, 165, 173, 174, 170, 171, 170, + /* 190 */ 171, 173, 174, 118, 184, 16, 186, 68, 69, 70, + /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + /* 210 */ 118, 82, 83, 84, 85, 86, 87, 88, 89, 90, + /* 220 */ 91, 92, 19, 98, 86, 87, 22, 24, 160, 88, + /* 230 */ 26, 27, 94, 95, 109, 97, 224, 66, 118, 60, + /* 240 */ 150, 62, 104, 23, 106, 25, 229, 230, 229, 230, + /* 250 */ 160, 150, 49, 50, 113, 165, 96, 26, 117, 99, + /* 260 */ 100, 101, 194, 173, 174, 94, 165, 129, 130, 98, + /* 270 */ 110, 68, 69, 70, 71, 72, 73, 74, 75, 76, + /* 280 */ 77, 78, 79, 80, 194, 82, 83, 84, 85, 86, + /* 290 */ 87, 88, 89, 90, 91, 92, 19, 11, 94, 95, + /* 300 */ 129, 130, 131, 118, 150, 215, 150, 150, 150, 25, + /* 310 */ 220, 26, 27, 22, 213, 26, 27, 26, 27, 165, + /* 320 */ 25, 165, 165, 165, 30, 94, 49, 50, 34, 173, + /* 330 */ 174, 173, 174, 88, 89, 90, 91, 92, 7, 8, + /* 340 */ 160, 187, 48, 57, 187, 68, 69, 70, 71, 72, + /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 23, 82, + /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, + /* 370 */ 19, 215, 150, 215, 194, 19, 220, 88, 220, 94, + /* 380 */ 95, 23, 160, 94, 95, 94, 95, 165, 26, 27, + /* 390 */ 95, 105, 106, 107, 113, 173, 174, 217, 22, 150, + /* 400 */ 49, 50, 116, 119, 57, 120, 50, 158, 22, 21, + /* 410 */ 161, 162, 232, 136, 165, 120, 194, 237, 23, 68, + /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, + /* 430 */ 79, 80, 22, 82, 83, 84, 85, 86, 87, 88, + /* 440 */ 89, 90, 91, 92, 19, 23, 12, 112, 23, 114, + /* 450 */ 115, 63, 105, 106, 107, 23, 94, 95, 97, 98, + /* 460 */ 104, 150, 28, 116, 25, 109, 150, 150, 23, 23, + /* 470 */ 112, 25, 114, 115, 49, 50, 165, 150, 44, 11, + /* 480 */ 46, 165, 165, 16, 173, 174, 76, 136, 100, 173, + /* 490 */ 174, 57, 165, 68, 69, 70, 71, 72, 73, 74, + /* 500 */ 75, 76, 77, 78, 79, 80, 166, 82, 83, 84, + /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 169, + /* 520 */ 170, 171, 23, 12, 23, 214, 138, 60, 150, 62, + /* 530 */ 24, 215, 26, 216, 112, 150, 114, 115, 36, 28, + /* 540 */ 213, 95, 103, 165, 112, 205, 114, 115, 49, 50, + /* 550 */ 165, 173, 174, 51, 23, 44, 25, 46, 173, 174, + /* 560 */ 58, 22, 23, 22, 25, 160, 120, 68, 69, 70, + /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + /* 580 */ 230, 82, 83, 84, 85, 86, 87, 88, 89, 90, + /* 590 */ 91, 92, 19, 215, 22, 23, 23, 25, 163, 194, + /* 600 */ 94, 166, 167, 168, 25, 138, 67, 7, 8, 9, + /* 610 */ 108, 206, 207, 169, 170, 171, 150, 22, 221, 222, + /* 620 */ 223, 26, 49, 50, 86, 87, 23, 161, 162, 23, + /* 630 */ 22, 165, 24, 120, 22, 23, 25, 160, 241, 67, + /* 640 */ 176, 68, 69, 70, 71, 72, 73, 74, 75, 76, + /* 650 */ 77, 78, 79, 80, 160, 82, 83, 84, 85, 86, + /* 660 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 150, + /* 670 */ 23, 194, 35, 23, 230, 25, 150, 155, 150, 67, + /* 680 */ 150, 105, 106, 107, 165, 221, 222, 223, 194, 94, + /* 690 */ 23, 165, 25, 165, 217, 165, 49, 50, 25, 173, + /* 700 */ 174, 173, 174, 173, 174, 0, 1, 2, 118, 221, + /* 710 */ 222, 223, 193, 219, 237, 68, 69, 70, 71, 72, + /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82, + /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, + /* 740 */ 19, 150, 19, 165, 150, 24, 166, 167, 168, 227, + /* 750 */ 27, 173, 174, 231, 150, 25, 165, 150, 172, 165, + /* 760 */ 150, 242, 129, 130, 173, 174, 180, 173, 174, 165, + /* 770 */ 49, 50, 165, 150, 176, 165, 35, 173, 174, 165, + /* 780 */ 173, 174, 35, 23, 23, 25, 25, 173, 165, 68, + /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, + /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88, + /* 810 */ 89, 90, 91, 92, 19, 150, 193, 165, 150, 221, + /* 820 */ 222, 223, 150, 213, 19, 173, 174, 23, 150, 97, + /* 830 */ 165, 150, 27, 165, 150, 150, 150, 165, 173, 174, + /* 840 */ 22, 173, 174, 165, 49, 50, 165, 52, 116, 165, + /* 850 */ 165, 165, 206, 207, 173, 174, 126, 50, 173, 174, + /* 860 */ 128, 27, 160, 68, 69, 70, 71, 72, 73, 74, + /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84, + /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150, + /* 890 */ 23, 165, 150, 23, 216, 25, 194, 32, 39, 173, + /* 900 */ 174, 135, 150, 137, 165, 150, 41, 165, 150, 52, + /* 910 */ 238, 104, 173, 174, 29, 173, 174, 165, 49, 50, + /* 920 */ 165, 219, 238, 165, 238, 173, 174, 52, 173, 174, + /* 930 */ 22, 173, 174, 23, 23, 160, 25, 68, 69, 70, + /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90, + /* 960 */ 91, 92, 19, 150, 150, 165, 150, 245, 246, 194, + /* 970 */ 150, 144, 145, 173, 174, 160, 150, 22, 165, 165, + /* 980 */ 22, 165, 150, 150, 116, 165, 173, 174, 52, 173, + /* 990 */ 174, 165, 49, 50, 22, 150, 128, 165, 165, 173, + /* 1000 */ 174, 187, 166, 166, 22, 173, 174, 187, 109, 194, + /* 1010 */ 165, 68, 69, 70, 71, 72, 73, 74, 75, 76, + /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86, + /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 150, 193, 165, + /* 1040 */ 102, 205, 205, 150, 150, 247, 248, 173, 174, 19, + /* 1050 */ 150, 20, 165, 150, 150, 150, 150, 150, 165, 165, + /* 1060 */ 173, 174, 49, 50, 104, 165, 49, 50, 165, 165, + /* 1070 */ 165, 165, 165, 173, 174, 43, 173, 174, 173, 174, + /* 1080 */ 187, 24, 190, 191, 71, 72, 69, 70, 71, 72, + /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82, + /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, + /* 1110 */ 19, 98, 150, 165, 150, 150, 150, 150, 150, 150, + /* 1120 */ 59, 173, 174, 25, 150, 190, 191, 165, 53, 165, + /* 1130 */ 165, 165, 165, 165, 165, 173, 174, 173, 174, 165, + /* 1140 */ 49, 50, 91, 92, 1, 2, 53, 173, 174, 138, + /* 1150 */ 104, 22, 5, 1, 35, 118, 127, 150, 193, 193, + /* 1160 */ 193, 70, 71, 72, 73, 74, 75, 76, 77, 78, + /* 1170 */ 79, 80, 165, 82, 83, 84, 85, 86, 87, 88, + /* 1180 */ 89, 90, 91, 92, 19, 20, 150, 22, 150, 27, + /* 1190 */ 150, 26, 27, 108, 150, 22, 76, 76, 150, 25, + /* 1200 */ 193, 165, 37, 165, 150, 165, 22, 19, 20, 165, + /* 1210 */ 22, 173, 174, 165, 26, 27, 23, 150, 119, 165, + /* 1220 */ 150, 56, 150, 150, 150, 37, 16, 173, 174, 193, + /* 1230 */ 150, 66, 165, 193, 1, 165, 121, 165, 165, 165, + /* 1240 */ 20, 146, 147, 119, 56, 165, 150, 152, 16, 154, + /* 1250 */ 150, 86, 87, 88, 66, 160, 150, 150, 93, 94, + /* 1260 */ 95, 165, 150, 98, 108, 165, 127, 23, 65, 173, + /* 1270 */ 174, 165, 165, 150, 86, 87, 128, 165, 150, 173, + /* 1280 */ 174, 93, 94, 95, 23, 150, 98, 15, 165, 194, + /* 1290 */ 150, 140, 22, 165, 129, 130, 131, 132, 133, 134, + /* 1300 */ 165, 173, 174, 3, 116, 165, 19, 20, 150, 22, + /* 1310 */ 4, 150, 217, 26, 27, 179, 179, 129, 130, 131, + /* 1320 */ 132, 133, 134, 165, 37, 150, 165, 150, 164, 19, + /* 1330 */ 20, 150, 22, 246, 149, 249, 26, 27, 249, 244, + /* 1340 */ 165, 150, 165, 56, 6, 150, 165, 37, 173, 174, + /* 1350 */ 173, 174, 150, 66, 173, 174, 165, 149, 149, 13, + /* 1360 */ 165, 25, 150, 150, 150, 149, 56, 165, 150, 116, + /* 1370 */ 151, 150, 150, 86, 87, 150, 66, 165, 165, 165, + /* 1380 */ 93, 94, 95, 165, 150, 98, 165, 165, 151, 22, + /* 1390 */ 165, 194, 150, 26, 27, 150, 86, 87, 159, 165, + /* 1400 */ 199, 126, 123, 93, 94, 95, 200, 165, 98, 124, + /* 1410 */ 165, 122, 201, 125, 225, 135, 129, 130, 131, 132, + /* 1420 */ 133, 134, 5, 157, 157, 202, 118, 10, 11, 12, + /* 1430 */ 13, 14, 203, 66, 17, 104, 210, 121, 211, 129, + /* 1440 */ 130, 131, 132, 133, 134, 210, 175, 211, 31, 211, + /* 1450 */ 33, 210, 104, 86, 87, 47, 175, 183, 175, 42, + /* 1460 */ 103, 94, 178, 177, 22, 98, 175, 92, 228, 175, + /* 1470 */ 175, 228, 55, 183, 57, 178, 175, 156, 61, 18, + /* 1480 */ 157, 64, 156, 235, 157, 156, 45, 157, 236, 157, + /* 1490 */ 135, 156, 199, 189, 157, 68, 129, 130, 131, 22, + /* 1500 */ 189, 199, 157, 156, 192, 18, 192, 192, 199, 192, + /* 1510 */ 218, 189, 40, 157, 218, 157, 240, 240, 157, 38, + /* 1520 */ 196, 243, 105, 106, 107, 153, 198, 209, 111, 166, + /* 1530 */ 176, 181, 166, 116, 166, 230, 176, 230, 176, 226, + /* 1540 */ 199, 177, 239, 209, 185, 148, 166, 195, 209, 196, + /* 1550 */ 199, 208, 182, 233, 173, 182, 139, 186, 239, 234, + /* 1560 */ 191, 182, 173, 92, +}; +#define YY_SHIFT_USE_DFLT (-70) +#define YY_SHIFT_COUNT (417) +#define YY_SHIFT_MIN (-69) +#define YY_SHIFT_MAX (1487) +static const short yy_shift_ofst[] = { + /* 0 */ 1143, 1188, 1417, 1188, 1287, 1287, 138, 138, -2, -19, + /* 10 */ 1287, 1287, 1287, 1287, 347, 362, 129, 129, 795, 1165, + /* 20 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, + /* 30 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, + /* 40 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287, + /* 50 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, + /* 60 */ 1287, 1287, 286, 362, 362, 538, 538, 231, 1253, 55, + /* 70 */ 721, 647, 573, 499, 425, 351, 277, 203, 869, 869, + /* 80 */ 869, 869, 869, 869, 869, 869, 869, 869, 869, 869, + /* 90 */ 869, 869, 869, 943, 869, 1017, 1091, 1091, -69, -45, + /* 100 */ -45, -45, -45, -45, -1, 24, 245, 362, 362, 362, + /* 110 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362, + /* 120 */ 362, 362, 362, 388, 356, 362, 362, 362, 362, 362, + /* 130 */ 732, 868, 231, 1051, 1471, -70, -70, -70, 1367, 57, + /* 140 */ 434, 434, 289, 291, 285, 1, 204, 572, 539, 362, + /* 150 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362, + /* 160 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362, + /* 170 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362, + /* 180 */ 362, 506, 506, 506, 705, 1253, 1253, 1253, -70, -70, + /* 190 */ -70, 171, 171, 160, 502, 502, 502, 446, 432, 511, + /* 200 */ 422, 358, 335, -12, -12, -12, -12, 576, 294, -12, + /* 210 */ -12, 295, 595, 141, 600, 730, 723, 723, 805, 730, + /* 220 */ 805, 439, 911, 231, 865, 231, 865, 807, 865, 723, + /* 230 */ 766, 633, 633, 231, 284, 63, 608, 1481, 1308, 1308, + /* 240 */ 1472, 1472, 1308, 1477, 1427, 1275, 1487, 1487, 1487, 1487, + /* 250 */ 1308, 1461, 1275, 1477, 1427, 1427, 1275, 1308, 1461, 1355, + /* 260 */ 1441, 1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, + /* 270 */ 1348, 1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, + /* 280 */ 1348, 1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, + /* 290 */ 1280, 1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, + /* 300 */ 1338, 1338, 1338, 1338, -70, -70, -70, -70, -70, -70, + /* 310 */ 1013, 467, 612, 84, 179, -28, 870, 410, 761, 760, + /* 320 */ 667, 650, 531, 220, 361, 331, 125, 127, 97, 1306, + /* 330 */ 1300, 1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, + /* 340 */ 1139, 1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, + /* 350 */ 1174, 1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, + /* 360 */ 1147, 1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032, 960, + /* 370 */ 1057, 1031, 1030, 899, 938, 982, 936, 972, 958, 910, + /* 380 */ 955, 875, 885, 908, 857, 859, 867, 804, 590, 834, + /* 390 */ 747, 818, 513, 611, 741, 673, 637, 611, 606, 603, + /* 400 */ 579, 501, 541, 468, 386, 445, 395, 376, 281, 185, + /* 410 */ 120, 92, 75, 45, 114, 25, 11, 5, +}; +#define YY_REDUCE_USE_DFLT (-169) +#define YY_REDUCE_COUNT (309) +#define YY_REDUCE_MIN (-168) +#define YY_REDUCE_MAX (1397) +static const short yy_reduce_ofst[] = { + /* 0 */ -141, 90, 1095, 222, 158, 156, 19, 17, 10, -104, + /* 10 */ 378, 316, 311, 12, 180, 249, 598, 464, 397, 1181, + /* 20 */ 1177, 1175, 1128, 1106, 1096, 1054, 1038, 974, 964, 962, + /* 30 */ 948, 905, 903, 900, 887, 874, 832, 826, 816, 813, + /* 40 */ 800, 758, 755, 752, 742, 739, 726, 685, 681, 668, + /* 50 */ 665, 652, 607, 604, 594, 591, 578, 530, 528, 526, + /* 60 */ 385, 18, 477, 466, 519, 444, 350, 435, 405, 488, + /* 70 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488, + /* 80 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488, + /* 90 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488, + /* 100 */ 488, 488, 488, 488, 488, 488, 488, 1040, 678, 1036, + /* 110 */ 1007, 967, 966, 965, 845, 686, 610, 684, 317, 672, + /* 120 */ 893, 327, 623, 522, -7, 820, 814, 157, 154, 101, + /* 130 */ 702, 494, 580, 488, 488, 488, 488, 488, 614, 586, + /* 140 */ 935, 892, 968, 1245, 1242, 1234, 1225, 798, 798, 1222, + /* 150 */ 1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158, + /* 160 */ 1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072, + /* 170 */ 1070, 1067, 1048, 1044, 969, 968, 907, 906, 904, 894, + /* 180 */ 833, 837, 836, 340, 827, 815, 775, 68, 722, 646, + /* 190 */ -168, 1389, 1381, 1371, 1379, 1373, 1370, 1343, 1352, 1369, + /* 200 */ 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1325, 1320, 1352, + /* 210 */ 1352, 1343, 1380, 1353, 1397, 1351, 1339, 1334, 1319, 1341, + /* 220 */ 1303, 1364, 1359, 1368, 1362, 1366, 1360, 1350, 1354, 1318, + /* 230 */ 1313, 1307, 1305, 1363, 1328, 1324, 1372, 1278, 1361, 1358, + /* 240 */ 1277, 1276, 1356, 1296, 1322, 1309, 1317, 1315, 1314, 1312, + /* 250 */ 1345, 1347, 1302, 1292, 1311, 1304, 1293, 1337, 1335, 1252, + /* 260 */ 1248, 1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, + /* 270 */ 1295, 1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, + /* 280 */ 1281, 1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, + /* 290 */ 1189, 1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, + /* 300 */ 1216, 1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164, +}; +static const YYACTIONTYPE yy_default[] = { + /* 0 */ 633, 867, 955, 955, 867, 867, 955, 955, 955, 757, + /* 10 */ 955, 955, 955, 865, 955, 955, 785, 785, 929, 955, + /* 20 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 30 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 40 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 50 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 60 */ 955, 955, 955, 955, 955, 955, 955, 672, 761, 791, + /* 70 */ 955, 955, 955, 955, 955, 955, 955, 955, 928, 930, + /* 80 */ 799, 798, 908, 772, 796, 789, 793, 868, 861, 862, + /* 90 */ 860, 864, 869, 955, 792, 828, 845, 827, 839, 844, + /* 100 */ 851, 843, 840, 830, 829, 831, 832, 955, 955, 955, + /* 110 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 120 */ 955, 955, 955, 659, 726, 955, 955, 955, 955, 955, + /* 130 */ 955, 955, 955, 833, 834, 848, 847, 846, 955, 664, + /* 140 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 150 */ 935, 933, 955, 880, 955, 955, 955, 955, 955, 955, + /* 160 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 170 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 180 */ 639, 757, 757, 757, 633, 955, 955, 955, 947, 761, + /* 190 */ 751, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 200 */ 955, 955, 955, 801, 740, 918, 920, 955, 901, 738, + /* 210 */ 661, 759, 674, 749, 641, 795, 774, 774, 913, 795, + /* 220 */ 913, 697, 720, 955, 785, 955, 785, 694, 785, 774, + /* 230 */ 863, 955, 955, 955, 758, 749, 955, 940, 765, 765, + /* 240 */ 932, 932, 765, 807, 730, 795, 737, 737, 737, 737, + /* 250 */ 765, 656, 795, 807, 730, 730, 795, 765, 656, 907, + /* 260 */ 905, 765, 765, 656, 765, 656, 765, 656, 873, 728, + /* 270 */ 728, 728, 712, 877, 877, 873, 728, 697, 728, 712, + /* 280 */ 728, 728, 778, 773, 778, 773, 778, 773, 765, 765, + /* 290 */ 955, 790, 779, 788, 786, 795, 955, 715, 649, 649, + /* 300 */ 638, 638, 638, 638, 952, 952, 947, 699, 699, 682, + /* 310 */ 955, 955, 955, 955, 955, 955, 955, 882, 955, 955, + /* 320 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 330 */ 634, 942, 955, 955, 939, 955, 955, 955, 955, 800, + /* 340 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 350 */ 917, 955, 955, 955, 955, 955, 955, 955, 911, 955, + /* 360 */ 955, 955, 955, 955, 955, 904, 903, 955, 955, 955, + /* 370 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 380 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955, + /* 390 */ 955, 955, 955, 787, 955, 780, 955, 866, 955, 955, + /* 400 */ 955, 955, 955, 955, 955, 955, 955, 955, 743, 816, + /* 410 */ 955, 815, 819, 814, 666, 955, 647, 955, 630, 635, + /* 420 */ 951, 954, 953, 950, 949, 948, 943, 941, 938, 937, + /* 430 */ 936, 934, 931, 927, 886, 884, 891, 890, 889, 888, + /* 440 */ 887, 885, 883, 881, 802, 797, 794, 926, 879, 739, + /* 450 */ 736, 735, 655, 944, 910, 919, 806, 805, 808, 916, + /* 460 */ 915, 914, 912, 909, 896, 804, 803, 731, 871, 870, + /* 470 */ 658, 900, 899, 898, 902, 906, 897, 767, 657, 654, + /* 480 */ 663, 718, 719, 727, 725, 724, 723, 722, 721, 717, + /* 490 */ 665, 673, 711, 696, 695, 876, 878, 875, 874, 704, + /* 500 */ 703, 709, 708, 707, 706, 705, 702, 701, 700, 693, + /* 510 */ 692, 698, 691, 714, 713, 710, 690, 734, 733, 732, + /* 520 */ 729, 689, 688, 687, 819, 686, 685, 825, 824, 812, + /* 530 */ 855, 754, 753, 752, 764, 763, 776, 775, 810, 809, + /* 540 */ 777, 762, 756, 755, 771, 770, 769, 768, 760, 750, + /* 550 */ 782, 784, 783, 781, 857, 766, 854, 925, 924, 923, + /* 560 */ 922, 921, 859, 858, 826, 823, 677, 678, 894, 893, + /* 570 */ 895, 892, 680, 679, 676, 675, 856, 745, 744, 852, + /* 580 */ 849, 841, 837, 853, 850, 842, 838, 836, 835, 821, + /* 590 */ 820, 818, 817, 813, 822, 668, 746, 742, 741, 811, + /* 600 */ 748, 747, 684, 683, 681, 662, 660, 653, 651, 650, + /* 610 */ 652, 648, 646, 645, 644, 643, 642, 671, 670, 669, + /* 620 */ 667, 666, 640, 637, 636, 632, 631, 629, +}; + +/* The next table maps tokens into fallback tokens. If a construct +** like the following: +** +** %fallback ID X Y Z. +** +** appears in the grammar, then ID becomes a fallback token for X, Y, +** and Z. Whenever one of the tokens X, Y, or Z is input to the parser +** but it does not parse, the type of the token is changed to ID and +** the parse is retried before an error is thrown. +*/ +#ifdef YYFALLBACK +static const YYCODETYPE yyFallback[] = { + 0, /* $ => nothing */ + 0, /* SEMI => nothing */ + 26, /* EXPLAIN => ID */ + 26, /* QUERY => ID */ + 26, /* PLAN => ID */ + 26, /* BEGIN => ID */ + 0, /* TRANSACTION => nothing */ + 26, /* DEFERRED => ID */ + 26, /* IMMEDIATE => ID */ + 26, /* EXCLUSIVE => ID */ + 0, /* COMMIT => nothing */ + 26, /* END => ID */ + 26, /* ROLLBACK => ID */ + 26, /* SAVEPOINT => ID */ + 26, /* RELEASE => ID */ + 0, /* TO => nothing */ + 0, /* TABLE => nothing */ + 0, /* CREATE => nothing */ + 26, /* IF => ID */ + 0, /* NOT => nothing */ + 0, /* EXISTS => nothing */ + 26, /* TEMP => ID */ + 0, /* LP => nothing */ + 0, /* RP => nothing */ + 0, /* AS => nothing */ + 0, /* COMMA => nothing */ + 0, /* ID => nothing */ + 0, /* INDEXED => nothing */ + 26, /* ABORT => ID */ + 26, /* ACTION => ID */ + 26, /* AFTER => ID */ + 26, /* ANALYZE => ID */ + 26, /* ASC => ID */ + 26, /* ATTACH => ID */ + 26, /* BEFORE => ID */ + 26, /* BY => ID */ + 26, /* CASCADE => ID */ + 26, /* CAST => ID */ + 26, /* COLUMNKW => ID */ + 26, /* CONFLICT => ID */ + 26, /* DATABASE => ID */ + 26, /* DESC => ID */ + 26, /* DETACH => ID */ + 26, /* EACH => ID */ + 26, /* FAIL => ID */ + 26, /* FOR => ID */ + 26, /* IGNORE => ID */ + 26, /* INITIALLY => ID */ + 26, /* INSTEAD => ID */ + 26, /* LIKE_KW => ID */ + 26, /* MATCH => ID */ + 26, /* NO => ID */ + 26, /* KEY => ID */ + 26, /* OF => ID */ + 26, /* OFFSET => ID */ + 26, /* PRAGMA => ID */ + 26, /* RAISE => ID */ + 26, /* REPLACE => ID */ + 26, /* RESTRICT => ID */ + 26, /* ROW => ID */ + 26, /* TRIGGER => ID */ + 26, /* VACUUM => ID */ + 26, /* VIEW => ID */ + 26, /* VIRTUAL => ID */ + 26, /* REINDEX => ID */ + 26, /* RENAME => ID */ + 26, /* CTIME_KW => ID */ +}; +#endif /* YYFALLBACK */ + +/* The following structure represents a single element of the +** parser's stack. Information stored includes: +** +** + The state number for the parser at this level of the stack. +** +** + The value of the token stored at this level of the stack. +** (In other words, the "major" token.) +** +** + The semantic value stored at this level of the stack. This is +** the information used by the action routines in the grammar. +** It is sometimes called the "minor" token. +*/ +struct yyStackEntry { + YYACTIONTYPE stateno; /* The state-number */ + YYCODETYPE major; /* The major token value. This is the code + ** number for the token at this stack level */ + YYMINORTYPE minor; /* The user-supplied minor token value. This + ** is the value of the token */ +}; +typedef struct yyStackEntry yyStackEntry; + +/* The state of the parser is completely contained in an instance of +** the following structure */ +struct yyParser { + int yyidx; /* Index of top element in stack */ +#ifdef YYTRACKMAXSTACKDEPTH + int yyidxMax; /* Maximum value of yyidx */ +#endif + int yyerrcnt; /* Shifts left before out of the error */ + sqlite3ParserARG_SDECL /* A place to hold %extra_argument */ +#if YYSTACKDEPTH<=0 + int yystksz; /* Current side of the stack */ + yyStackEntry *yystack; /* The parser's stack */ +#else + yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ +#endif +}; +typedef struct yyParser yyParser; + +#ifndef NDEBUG +/* #include */ +static FILE *yyTraceFILE = 0; +static char *yyTracePrompt = 0; +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* +** Turn parser tracing on by giving a stream to which to write the trace +** and a prompt to preface each trace message. Tracing is turned off +** by making either argument NULL +** +** Inputs: +**
    +**
  • A FILE* to which trace output should be written. +** If NULL, then tracing is turned off. +**
  • A prefix string written at the beginning of every +** line of trace output. If NULL, then tracing is +** turned off. +**
+** +** Outputs: +** None. +*/ +SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){ + yyTraceFILE = TraceFILE; + yyTracePrompt = zTracePrompt; + if( yyTraceFILE==0 ) yyTracePrompt = 0; + else if( yyTracePrompt==0 ) yyTraceFILE = 0; +} +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* For tracing shifts, the names of all terminals and nonterminals +** are required. The following table supplies these names */ +static const char *const yyTokenName[] = { + "$", "SEMI", "EXPLAIN", "QUERY", + "PLAN", "BEGIN", "TRANSACTION", "DEFERRED", + "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END", + "ROLLBACK", "SAVEPOINT", "RELEASE", "TO", + "TABLE", "CREATE", "IF", "NOT", + "EXISTS", "TEMP", "LP", "RP", + "AS", "COMMA", "ID", "INDEXED", + "ABORT", "ACTION", "AFTER", "ANALYZE", + "ASC", "ATTACH", "BEFORE", "BY", + "CASCADE", "CAST", "COLUMNKW", "CONFLICT", + "DATABASE", "DESC", "DETACH", "EACH", + "FAIL", "FOR", "IGNORE", "INITIALLY", + "INSTEAD", "LIKE_KW", "MATCH", "NO", + "KEY", "OF", "OFFSET", "PRAGMA", + "RAISE", "REPLACE", "RESTRICT", "ROW", + "TRIGGER", "VACUUM", "VIEW", "VIRTUAL", + "REINDEX", "RENAME", "CTIME_KW", "ANY", + "OR", "AND", "IS", "BETWEEN", + "IN", "ISNULL", "NOTNULL", "NE", + "EQ", "GT", "LE", "LT", + "GE", "ESCAPE", "BITAND", "BITOR", + "LSHIFT", "RSHIFT", "PLUS", "MINUS", + "STAR", "SLASH", "REM", "CONCAT", + "COLLATE", "BITNOT", "STRING", "JOIN_KW", + "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY", + "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR", + "ON", "INSERT", "DELETE", "UPDATE", + "SET", "DEFERRABLE", "FOREIGN", "DROP", + "UNION", "ALL", "EXCEPT", "INTERSECT", + "SELECT", "DISTINCT", "DOT", "FROM", + "JOIN", "USING", "ORDER", "GROUP", + "HAVING", "LIMIT", "WHERE", "INTO", + "VALUES", "INTEGER", "FLOAT", "BLOB", + "REGISTER", "VARIABLE", "CASE", "WHEN", + "THEN", "ELSE", "INDEX", "ALTER", + "ADD", "error", "input", "cmdlist", + "ecmd", "explain", "cmdx", "cmd", + "transtype", "trans_opt", "nm", "savepoint_opt", + "create_table", "create_table_args", "createkw", "temp", + "ifnotexists", "dbnm", "columnlist", "conslist_opt", + "select", "column", "columnid", "type", + "carglist", "id", "ids", "typetoken", + "typename", "signed", "plus_num", "minus_num", + "ccons", "term", "expr", "onconf", + "sortorder", "autoinc", "idxlist_opt", "refargs", + "defer_subclause", "refarg", "refact", "init_deferred_pred_opt", + "conslist", "tconscomma", "tcons", "idxlist", + "defer_subclause_opt", "orconf", "resolvetype", "raisetype", + "ifexists", "fullname", "oneselect", "multiselect_op", + "distinct", "selcollist", "from", "where_opt", + "groupby_opt", "having_opt", "orderby_opt", "limit_opt", + "sclp", "as", "seltablist", "stl_prefix", + "joinop", "indexed_opt", "on_opt", "using_opt", + "joinop2", "inscollist", "sortlist", "nexprlist", + "setlist", "insert_cmd", "inscollist_opt", "valuelist", + "exprlist", "likeop", "between_op", "in_op", + "case_operand", "case_exprlist", "case_else", "uniqueflag", + "collate", "nmnum", "number", "trigger_decl", + "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause", + "when_clause", "trigger_cmd", "trnm", "tridxby", + "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt", + "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken", + "lp", "anylist", +}; +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* For tracing reduce actions, the names of all rules are required. +*/ +static const char *const yyRuleName[] = { + /* 0 */ "input ::= cmdlist", + /* 1 */ "cmdlist ::= cmdlist ecmd", + /* 2 */ "cmdlist ::= ecmd", + /* 3 */ "ecmd ::= SEMI", + /* 4 */ "ecmd ::= explain cmdx SEMI", + /* 5 */ "explain ::=", + /* 6 */ "explain ::= EXPLAIN", + /* 7 */ "explain ::= EXPLAIN QUERY PLAN", + /* 8 */ "cmdx ::= cmd", + /* 9 */ "cmd ::= BEGIN transtype trans_opt", + /* 10 */ "trans_opt ::=", + /* 11 */ "trans_opt ::= TRANSACTION", + /* 12 */ "trans_opt ::= TRANSACTION nm", + /* 13 */ "transtype ::=", + /* 14 */ "transtype ::= DEFERRED", + /* 15 */ "transtype ::= IMMEDIATE", + /* 16 */ "transtype ::= EXCLUSIVE", + /* 17 */ "cmd ::= COMMIT trans_opt", + /* 18 */ "cmd ::= END trans_opt", + /* 19 */ "cmd ::= ROLLBACK trans_opt", + /* 20 */ "savepoint_opt ::= SAVEPOINT", + /* 21 */ "savepoint_opt ::=", + /* 22 */ "cmd ::= SAVEPOINT nm", + /* 23 */ "cmd ::= RELEASE savepoint_opt nm", + /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm", + /* 25 */ "cmd ::= create_table create_table_args", + /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm", + /* 27 */ "createkw ::= CREATE", + /* 28 */ "ifnotexists ::=", + /* 29 */ "ifnotexists ::= IF NOT EXISTS", + /* 30 */ "temp ::= TEMP", + /* 31 */ "temp ::=", + /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP", + /* 33 */ "create_table_args ::= AS select", + /* 34 */ "columnlist ::= columnlist COMMA column", + /* 35 */ "columnlist ::= column", + /* 36 */ "column ::= columnid type carglist", + /* 37 */ "columnid ::= nm", + /* 38 */ "id ::= ID", + /* 39 */ "id ::= INDEXED", + /* 40 */ "ids ::= ID|STRING", + /* 41 */ "nm ::= id", + /* 42 */ "nm ::= STRING", + /* 43 */ "nm ::= JOIN_KW", + /* 44 */ "type ::=", + /* 45 */ "type ::= typetoken", + /* 46 */ "typetoken ::= typename", + /* 47 */ "typetoken ::= typename LP signed RP", + /* 48 */ "typetoken ::= typename LP signed COMMA signed RP", + /* 49 */ "typename ::= ids", + /* 50 */ "typename ::= typename ids", + /* 51 */ "signed ::= plus_num", + /* 52 */ "signed ::= minus_num", + /* 53 */ "carglist ::= carglist ccons", + /* 54 */ "carglist ::=", + /* 55 */ "ccons ::= CONSTRAINT nm", + /* 56 */ "ccons ::= DEFAULT term", + /* 57 */ "ccons ::= DEFAULT LP expr RP", + /* 58 */ "ccons ::= DEFAULT PLUS term", + /* 59 */ "ccons ::= DEFAULT MINUS term", + /* 60 */ "ccons ::= DEFAULT id", + /* 61 */ "ccons ::= NULL onconf", + /* 62 */ "ccons ::= NOT NULL onconf", + /* 63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", + /* 64 */ "ccons ::= UNIQUE onconf", + /* 65 */ "ccons ::= CHECK LP expr RP", + /* 66 */ "ccons ::= REFERENCES nm idxlist_opt refargs", + /* 67 */ "ccons ::= defer_subclause", + /* 68 */ "ccons ::= COLLATE ids", + /* 69 */ "autoinc ::=", + /* 70 */ "autoinc ::= AUTOINCR", + /* 71 */ "refargs ::=", + /* 72 */ "refargs ::= refargs refarg", + /* 73 */ "refarg ::= MATCH nm", + /* 74 */ "refarg ::= ON INSERT refact", + /* 75 */ "refarg ::= ON DELETE refact", + /* 76 */ "refarg ::= ON UPDATE refact", + /* 77 */ "refact ::= SET NULL", + /* 78 */ "refact ::= SET DEFAULT", + /* 79 */ "refact ::= CASCADE", + /* 80 */ "refact ::= RESTRICT", + /* 81 */ "refact ::= NO ACTION", + /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", + /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", + /* 84 */ "init_deferred_pred_opt ::=", + /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", + /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", + /* 87 */ "conslist_opt ::=", + /* 88 */ "conslist_opt ::= COMMA conslist", + /* 89 */ "conslist ::= conslist tconscomma tcons", + /* 90 */ "conslist ::= tcons", + /* 91 */ "tconscomma ::= COMMA", + /* 92 */ "tconscomma ::=", + /* 93 */ "tcons ::= CONSTRAINT nm", + /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf", + /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf", + /* 96 */ "tcons ::= CHECK LP expr RP onconf", + /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt", + /* 98 */ "defer_subclause_opt ::=", + /* 99 */ "defer_subclause_opt ::= defer_subclause", + /* 100 */ "onconf ::=", + /* 101 */ "onconf ::= ON CONFLICT resolvetype", + /* 102 */ "orconf ::=", + /* 103 */ "orconf ::= OR resolvetype", + /* 104 */ "resolvetype ::= raisetype", + /* 105 */ "resolvetype ::= IGNORE", + /* 106 */ "resolvetype ::= REPLACE", + /* 107 */ "cmd ::= DROP TABLE ifexists fullname", + /* 108 */ "ifexists ::= IF EXISTS", + /* 109 */ "ifexists ::=", + /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select", + /* 111 */ "cmd ::= DROP VIEW ifexists fullname", + /* 112 */ "cmd ::= select", + /* 113 */ "select ::= oneselect", + /* 114 */ "select ::= select multiselect_op oneselect", + /* 115 */ "multiselect_op ::= UNION", + /* 116 */ "multiselect_op ::= UNION ALL", + /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT", + /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", + /* 119 */ "distinct ::= DISTINCT", + /* 120 */ "distinct ::= ALL", + /* 121 */ "distinct ::=", + /* 122 */ "sclp ::= selcollist COMMA", + /* 123 */ "sclp ::=", + /* 124 */ "selcollist ::= sclp expr as", + /* 125 */ "selcollist ::= sclp STAR", + /* 126 */ "selcollist ::= sclp nm DOT STAR", + /* 127 */ "as ::= AS nm", + /* 128 */ "as ::= ids", + /* 129 */ "as ::=", + /* 130 */ "from ::=", + /* 131 */ "from ::= FROM seltablist", + /* 132 */ "stl_prefix ::= seltablist joinop", + /* 133 */ "stl_prefix ::=", + /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", + /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", + /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", + /* 137 */ "dbnm ::=", + /* 138 */ "dbnm ::= DOT nm", + /* 139 */ "fullname ::= nm dbnm", + /* 140 */ "joinop ::= COMMA|JOIN", + /* 141 */ "joinop ::= JOIN_KW JOIN", + /* 142 */ "joinop ::= JOIN_KW nm JOIN", + /* 143 */ "joinop ::= JOIN_KW nm nm JOIN", + /* 144 */ "on_opt ::= ON expr", + /* 145 */ "on_opt ::=", + /* 146 */ "indexed_opt ::=", + /* 147 */ "indexed_opt ::= INDEXED BY nm", + /* 148 */ "indexed_opt ::= NOT INDEXED", + /* 149 */ "using_opt ::= USING LP inscollist RP", + /* 150 */ "using_opt ::=", + /* 151 */ "orderby_opt ::=", + /* 152 */ "orderby_opt ::= ORDER BY sortlist", + /* 153 */ "sortlist ::= sortlist COMMA expr sortorder", + /* 154 */ "sortlist ::= expr sortorder", + /* 155 */ "sortorder ::= ASC", + /* 156 */ "sortorder ::= DESC", + /* 157 */ "sortorder ::=", + /* 158 */ "groupby_opt ::=", + /* 159 */ "groupby_opt ::= GROUP BY nexprlist", + /* 160 */ "having_opt ::=", + /* 161 */ "having_opt ::= HAVING expr", + /* 162 */ "limit_opt ::=", + /* 163 */ "limit_opt ::= LIMIT expr", + /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr", + /* 165 */ "limit_opt ::= LIMIT expr COMMA expr", + /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt", + /* 167 */ "where_opt ::=", + /* 168 */ "where_opt ::= WHERE expr", + /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt", + /* 170 */ "setlist ::= setlist COMMA nm EQ expr", + /* 171 */ "setlist ::= nm EQ expr", + /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist", + /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select", + /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES", + /* 175 */ "insert_cmd ::= INSERT orconf", + /* 176 */ "insert_cmd ::= REPLACE", + /* 177 */ "valuelist ::= VALUES LP nexprlist RP", + /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP", + /* 179 */ "inscollist_opt ::=", + /* 180 */ "inscollist_opt ::= LP inscollist RP", + /* 181 */ "inscollist ::= inscollist COMMA nm", + /* 182 */ "inscollist ::= nm", + /* 183 */ "expr ::= term", + /* 184 */ "expr ::= LP expr RP", + /* 185 */ "term ::= NULL", + /* 186 */ "expr ::= id", + /* 187 */ "expr ::= JOIN_KW", + /* 188 */ "expr ::= nm DOT nm", + /* 189 */ "expr ::= nm DOT nm DOT nm", + /* 190 */ "term ::= INTEGER|FLOAT|BLOB", + /* 191 */ "term ::= STRING", + /* 192 */ "expr ::= REGISTER", + /* 193 */ "expr ::= VARIABLE", + /* 194 */ "expr ::= expr COLLATE ids", + /* 195 */ "expr ::= CAST LP expr AS typetoken RP", + /* 196 */ "expr ::= ID LP distinct exprlist RP", + /* 197 */ "expr ::= ID LP STAR RP", + /* 198 */ "term ::= CTIME_KW", + /* 199 */ "expr ::= expr AND expr", + /* 200 */ "expr ::= expr OR expr", + /* 201 */ "expr ::= expr LT|GT|GE|LE expr", + /* 202 */ "expr ::= expr EQ|NE expr", + /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", + /* 204 */ "expr ::= expr PLUS|MINUS expr", + /* 205 */ "expr ::= expr STAR|SLASH|REM expr", + /* 206 */ "expr ::= expr CONCAT expr", + /* 207 */ "likeop ::= LIKE_KW", + /* 208 */ "likeop ::= NOT LIKE_KW", + /* 209 */ "likeop ::= MATCH", + /* 210 */ "likeop ::= NOT MATCH", + /* 211 */ "expr ::= expr likeop expr", + /* 212 */ "expr ::= expr likeop expr ESCAPE expr", + /* 213 */ "expr ::= expr ISNULL|NOTNULL", + /* 214 */ "expr ::= expr NOT NULL", + /* 215 */ "expr ::= expr IS expr", + /* 216 */ "expr ::= expr IS NOT expr", + /* 217 */ "expr ::= NOT expr", + /* 218 */ "expr ::= BITNOT expr", + /* 219 */ "expr ::= MINUS expr", + /* 220 */ "expr ::= PLUS expr", + /* 221 */ "between_op ::= BETWEEN", + /* 222 */ "between_op ::= NOT BETWEEN", + /* 223 */ "expr ::= expr between_op expr AND expr", + /* 224 */ "in_op ::= IN", + /* 225 */ "in_op ::= NOT IN", + /* 226 */ "expr ::= expr in_op LP exprlist RP", + /* 227 */ "expr ::= LP select RP", + /* 228 */ "expr ::= expr in_op LP select RP", + /* 229 */ "expr ::= expr in_op nm dbnm", + /* 230 */ "expr ::= EXISTS LP select RP", + /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END", + /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", + /* 233 */ "case_exprlist ::= WHEN expr THEN expr", + /* 234 */ "case_else ::= ELSE expr", + /* 235 */ "case_else ::=", + /* 236 */ "case_operand ::= expr", + /* 237 */ "case_operand ::=", + /* 238 */ "exprlist ::= nexprlist", + /* 239 */ "exprlist ::=", + /* 240 */ "nexprlist ::= nexprlist COMMA expr", + /* 241 */ "nexprlist ::= expr", + /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt", + /* 243 */ "uniqueflag ::= UNIQUE", + /* 244 */ "uniqueflag ::=", + /* 245 */ "idxlist_opt ::=", + /* 246 */ "idxlist_opt ::= LP idxlist RP", + /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder", + /* 248 */ "idxlist ::= nm collate sortorder", + /* 249 */ "collate ::=", + /* 250 */ "collate ::= COLLATE ids", + /* 251 */ "cmd ::= DROP INDEX ifexists fullname", + /* 252 */ "cmd ::= VACUUM", + /* 253 */ "cmd ::= VACUUM nm", + /* 254 */ "cmd ::= PRAGMA nm dbnm", + /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", + /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", + /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", + /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", + /* 259 */ "nmnum ::= plus_num", + /* 260 */ "nmnum ::= nm", + /* 261 */ "nmnum ::= ON", + /* 262 */ "nmnum ::= DELETE", + /* 263 */ "nmnum ::= DEFAULT", + /* 264 */ "plus_num ::= PLUS number", + /* 265 */ "plus_num ::= number", + /* 266 */ "minus_num ::= MINUS number", + /* 267 */ "number ::= INTEGER|FLOAT", + /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", + /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", + /* 270 */ "trigger_time ::= BEFORE", + /* 271 */ "trigger_time ::= AFTER", + /* 272 */ "trigger_time ::= INSTEAD OF", + /* 273 */ "trigger_time ::=", + /* 274 */ "trigger_event ::= DELETE|INSERT", + /* 275 */ "trigger_event ::= UPDATE", + /* 276 */ "trigger_event ::= UPDATE OF inscollist", + /* 277 */ "foreach_clause ::=", + /* 278 */ "foreach_clause ::= FOR EACH ROW", + /* 279 */ "when_clause ::=", + /* 280 */ "when_clause ::= WHEN expr", + /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", + /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI", + /* 283 */ "trnm ::= nm", + /* 284 */ "trnm ::= nm DOT nm", + /* 285 */ "tridxby ::=", + /* 286 */ "tridxby ::= INDEXED BY nm", + /* 287 */ "tridxby ::= NOT INDEXED", + /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt", + /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist", + /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select", + /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt", + /* 292 */ "trigger_cmd ::= select", + /* 293 */ "expr ::= RAISE LP IGNORE RP", + /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP", + /* 295 */ "raisetype ::= ROLLBACK", + /* 296 */ "raisetype ::= ABORT", + /* 297 */ "raisetype ::= FAIL", + /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname", + /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", + /* 300 */ "cmd ::= DETACH database_kw_opt expr", + /* 301 */ "key_opt ::=", + /* 302 */ "key_opt ::= KEY expr", + /* 303 */ "database_kw_opt ::= DATABASE", + /* 304 */ "database_kw_opt ::=", + /* 305 */ "cmd ::= REINDEX", + /* 306 */ "cmd ::= REINDEX nm dbnm", + /* 307 */ "cmd ::= ANALYZE", + /* 308 */ "cmd ::= ANALYZE nm dbnm", + /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", + /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column", + /* 311 */ "add_column_fullname ::= fullname", + /* 312 */ "kwcolumn_opt ::=", + /* 313 */ "kwcolumn_opt ::= COLUMNKW", + /* 314 */ "cmd ::= create_vtab", + /* 315 */ "cmd ::= create_vtab LP vtabarglist RP", + /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", + /* 317 */ "vtabarglist ::= vtabarg", + /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg", + /* 319 */ "vtabarg ::=", + /* 320 */ "vtabarg ::= vtabarg vtabargtoken", + /* 321 */ "vtabargtoken ::= ANY", + /* 322 */ "vtabargtoken ::= lp anylist RP", + /* 323 */ "lp ::= LP", + /* 324 */ "anylist ::=", + /* 325 */ "anylist ::= anylist LP anylist RP", + /* 326 */ "anylist ::= anylist ANY", +}; +#endif /* NDEBUG */ + + +#if YYSTACKDEPTH<=0 +/* +** Try to increase the size of the parser stack. +*/ +static void yyGrowStack(yyParser *p){ + int newSize; + yyStackEntry *pNew; + + newSize = p->yystksz*2 + 100; + pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); + if( pNew ){ + p->yystack = pNew; + p->yystksz = newSize; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sStack grows to %d entries!\n", + yyTracePrompt, p->yystksz); + } +#endif + } +} +#endif + +/* +** This function allocates a new parser. +** The only argument is a pointer to a function which works like +** malloc. +** +** Inputs: +** A pointer to the function used to allocate memory. +** +** Outputs: +** A pointer to a parser. This pointer is used in subsequent calls +** to sqlite3Parser and sqlite3ParserFree. +*/ +SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){ + yyParser *pParser; + pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); + if( pParser ){ + pParser->yyidx = -1; +#ifdef YYTRACKMAXSTACKDEPTH + pParser->yyidxMax = 0; +#endif +#if YYSTACKDEPTH<=0 + pParser->yystack = NULL; + pParser->yystksz = 0; + yyGrowStack(pParser); +#endif + } + return pParser; +} + +/* The following function deletes the value associated with a +** symbol. The symbol can be either a terminal or nonterminal. +** "yymajor" is the symbol code, and "yypminor" is a pointer to +** the value. +*/ +static void yy_destructor( + yyParser *yypParser, /* The parser */ + YYCODETYPE yymajor, /* Type code for object to destroy */ + YYMINORTYPE *yypminor /* The object to be destroyed */ +){ + sqlite3ParserARG_FETCH; + switch( yymajor ){ + /* Here is inserted the actions which take place when a + ** terminal or non-terminal is destroyed. This can happen + ** when the symbol is popped from the stack during a + ** reduce or during error processing or when a parser is + ** being destroyed before it is finished parsing. + ** + ** Note: during a reduce, the only symbols destroyed are those + ** which appear on the RHS of the rule, but which are not used + ** inside the C code. + */ + case 160: /* select */ + case 194: /* oneselect */ +{ +sqlite3SelectDelete(pParse->db, (yypminor->yy159)); +} + break; + case 173: /* term */ + case 174: /* expr */ +{ +sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr); +} + break; + case 178: /* idxlist_opt */ + case 187: /* idxlist */ + case 197: /* selcollist */ + case 200: /* groupby_opt */ + case 202: /* orderby_opt */ + case 204: /* sclp */ + case 214: /* sortlist */ + case 215: /* nexprlist */ + case 216: /* setlist */ + case 220: /* exprlist */ + case 225: /* case_exprlist */ +{ +sqlite3ExprListDelete(pParse->db, (yypminor->yy442)); +} + break; + case 193: /* fullname */ + case 198: /* from */ + case 206: /* seltablist */ + case 207: /* stl_prefix */ +{ +sqlite3SrcListDelete(pParse->db, (yypminor->yy347)); +} + break; + case 199: /* where_opt */ + case 201: /* having_opt */ + case 210: /* on_opt */ + case 224: /* case_operand */ + case 226: /* case_else */ + case 236: /* when_clause */ + case 241: /* key_opt */ +{ +sqlite3ExprDelete(pParse->db, (yypminor->yy122)); +} + break; + case 211: /* using_opt */ + case 213: /* inscollist */ + case 218: /* inscollist_opt */ +{ +sqlite3IdListDelete(pParse->db, (yypminor->yy180)); +} + break; + case 219: /* valuelist */ +{ + + sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList); + sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect); + +} + break; + case 232: /* trigger_cmd_list */ + case 237: /* trigger_cmd */ +{ +sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327)); +} + break; + case 234: /* trigger_event */ +{ +sqlite3IdListDelete(pParse->db, (yypminor->yy410).b); +} + break; + default: break; /* If no destructor action specified: do nothing */ + } +} + +/* +** Pop the parser's stack once. +** +** If there is a destructor routine associated with the token which +** is popped from the stack, then call it. +** +** Return the major token number for the symbol popped. +*/ +static int yy_pop_parser_stack(yyParser *pParser){ + YYCODETYPE yymajor; + yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; + + /* There is no mechanism by which the parser stack can be popped below + ** empty in SQLite. */ + if( NEVER(pParser->yyidx<0) ) return 0; +#ifndef NDEBUG + if( yyTraceFILE && pParser->yyidx>=0 ){ + fprintf(yyTraceFILE,"%sPopping %s\n", + yyTracePrompt, + yyTokenName[yytos->major]); + } +#endif + yymajor = yytos->major; + yy_destructor(pParser, yymajor, &yytos->minor); + pParser->yyidx--; + return yymajor; +} + +/* +** Deallocate and destroy a parser. Destructors are all called for +** all stack elements before shutting the parser down. +** +** Inputs: +**
    +**
  • A pointer to the parser. This should be a pointer +** obtained from sqlite3ParserAlloc. +**
  • A pointer to a function used to reclaim memory obtained +** from malloc. +**
+*/ +SQLITE_PRIVATE void sqlite3ParserFree( + void *p, /* The parser to be deleted */ + void (*freeProc)(void*) /* Function used to reclaim memory */ +){ + yyParser *pParser = (yyParser*)p; + /* In SQLite, we never try to destroy a parser that was not successfully + ** created in the first place. */ + if( NEVER(pParser==0) ) return; + while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); +#if YYSTACKDEPTH<=0 + free(pParser->yystack); +#endif + (*freeProc)((void*)pParser); +} + +/* +** Return the peak depth of the stack for a parser. +*/ +#ifdef YYTRACKMAXSTACKDEPTH +SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){ + yyParser *pParser = (yyParser*)p; + return pParser->yyidxMax; +} +#endif + +/* +** Find the appropriate action for a parser given the terminal +** look-ahead token iLookAhead. +** +** If the look-ahead token is YYNOCODE, then check to see if the action is +** independent of the look-ahead. If it is, return the action, otherwise +** return YY_NO_ACTION. +*/ +static int yy_find_shift_action( + yyParser *pParser, /* The parser */ + YYCODETYPE iLookAhead /* The look-ahead token */ +){ + int i; + int stateno = pParser->yystack[pParser->yyidx].stateno; + + if( stateno>YY_SHIFT_COUNT + || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){ + return yy_default[stateno]; + } + assert( iLookAhead!=YYNOCODE ); + i += iLookAhead; + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ + if( iLookAhead>0 ){ +#ifdef YYFALLBACK + YYCODETYPE iFallback; /* Fallback token */ + if( iLookAhead %s\n", + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); + } +#endif + return yy_find_shift_action(pParser, iFallback); + } +#endif +#ifdef YYWILDCARD + { + int j = i - iLookAhead + YYWILDCARD; + if( +#if YY_SHIFT_MIN+YYWILDCARD<0 + j>=0 && +#endif +#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT + j %s\n", + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); + } +#endif /* NDEBUG */ + return yy_action[j]; + } + } +#endif /* YYWILDCARD */ + } + return yy_default[stateno]; + }else{ + return yy_action[i]; + } +} + +/* +** Find the appropriate action for a parser given the non-terminal +** look-ahead token iLookAhead. +** +** If the look-ahead token is YYNOCODE, then check to see if the action is +** independent of the look-ahead. If it is, return the action, otherwise +** return YY_NO_ACTION. +*/ +static int yy_find_reduce_action( + int stateno, /* Current state number */ + YYCODETYPE iLookAhead /* The look-ahead token */ +){ + int i; +#ifdef YYERRORSYMBOL + if( stateno>YY_REDUCE_COUNT ){ + return yy_default[stateno]; + } +#else + assert( stateno<=YY_REDUCE_COUNT ); +#endif + i = yy_reduce_ofst[stateno]; + assert( i!=YY_REDUCE_USE_DFLT ); + assert( iLookAhead!=YYNOCODE ); + i += iLookAhead; +#ifdef YYERRORSYMBOL + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ + return yy_default[stateno]; + } +#else + assert( i>=0 && iyyidx--; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); + } +#endif + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will execute if the parser + ** stack every overflows */ + + UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */ + sqlite3ErrorMsg(pParse, "parser stack overflow"); + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */ +} + +/* +** Perform a shift action. +*/ +static void yy_shift( + yyParser *yypParser, /* The parser to be shifted */ + int yyNewState, /* The new state to shift in */ + int yyMajor, /* The major token to shift in */ + YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */ +){ + yyStackEntry *yytos; + yypParser->yyidx++; +#ifdef YYTRACKMAXSTACKDEPTH + if( yypParser->yyidx>yypParser->yyidxMax ){ + yypParser->yyidxMax = yypParser->yyidx; + } +#endif +#if YYSTACKDEPTH>0 + if( yypParser->yyidx>=YYSTACKDEPTH ){ + yyStackOverflow(yypParser, yypMinor); + return; + } +#else + if( yypParser->yyidx>=yypParser->yystksz ){ + yyGrowStack(yypParser); + if( yypParser->yyidx>=yypParser->yystksz ){ + yyStackOverflow(yypParser, yypMinor); + return; + } + } +#endif + yytos = &yypParser->yystack[yypParser->yyidx]; + yytos->stateno = (YYACTIONTYPE)yyNewState; + yytos->major = (YYCODETYPE)yyMajor; + yytos->minor = *yypMinor; +#ifndef NDEBUG + if( yyTraceFILE && yypParser->yyidx>0 ){ + int i; + fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); + fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); + for(i=1; i<=yypParser->yyidx; i++) + fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); + fprintf(yyTraceFILE,"\n"); + } +#endif +} + +/* The following table contains information about every rule that +** is used during the reduce. +*/ +static const struct { + YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ + unsigned char nrhs; /* Number of right-hand side symbols in the rule */ +} yyRuleInfo[] = { + { 142, 1 }, + { 143, 2 }, + { 143, 1 }, + { 144, 1 }, + { 144, 3 }, + { 145, 0 }, + { 145, 1 }, + { 145, 3 }, + { 146, 1 }, + { 147, 3 }, + { 149, 0 }, + { 149, 1 }, + { 149, 2 }, + { 148, 0 }, + { 148, 1 }, + { 148, 1 }, + { 148, 1 }, + { 147, 2 }, + { 147, 2 }, + { 147, 2 }, + { 151, 1 }, + { 151, 0 }, + { 147, 2 }, + { 147, 3 }, + { 147, 5 }, + { 147, 2 }, + { 152, 6 }, + { 154, 1 }, + { 156, 0 }, + { 156, 3 }, + { 155, 1 }, + { 155, 0 }, + { 153, 4 }, + { 153, 2 }, + { 158, 3 }, + { 158, 1 }, + { 161, 3 }, + { 162, 1 }, + { 165, 1 }, + { 165, 1 }, + { 166, 1 }, + { 150, 1 }, + { 150, 1 }, + { 150, 1 }, + { 163, 0 }, + { 163, 1 }, + { 167, 1 }, + { 167, 4 }, + { 167, 6 }, + { 168, 1 }, + { 168, 2 }, + { 169, 1 }, + { 169, 1 }, + { 164, 2 }, + { 164, 0 }, + { 172, 2 }, + { 172, 2 }, + { 172, 4 }, + { 172, 3 }, + { 172, 3 }, + { 172, 2 }, + { 172, 2 }, + { 172, 3 }, + { 172, 5 }, + { 172, 2 }, + { 172, 4 }, + { 172, 4 }, + { 172, 1 }, + { 172, 2 }, + { 177, 0 }, + { 177, 1 }, + { 179, 0 }, + { 179, 2 }, + { 181, 2 }, + { 181, 3 }, + { 181, 3 }, + { 181, 3 }, + { 182, 2 }, + { 182, 2 }, + { 182, 1 }, + { 182, 1 }, + { 182, 2 }, + { 180, 3 }, + { 180, 2 }, + { 183, 0 }, + { 183, 2 }, + { 183, 2 }, + { 159, 0 }, + { 159, 2 }, + { 184, 3 }, + { 184, 1 }, + { 185, 1 }, + { 185, 0 }, + { 186, 2 }, + { 186, 7 }, + { 186, 5 }, + { 186, 5 }, + { 186, 10 }, + { 188, 0 }, + { 188, 1 }, + { 175, 0 }, + { 175, 3 }, + { 189, 0 }, + { 189, 2 }, + { 190, 1 }, + { 190, 1 }, + { 190, 1 }, + { 147, 4 }, + { 192, 2 }, + { 192, 0 }, + { 147, 8 }, + { 147, 4 }, + { 147, 1 }, + { 160, 1 }, + { 160, 3 }, + { 195, 1 }, + { 195, 2 }, + { 195, 1 }, + { 194, 9 }, + { 196, 1 }, + { 196, 1 }, + { 196, 0 }, + { 204, 2 }, + { 204, 0 }, + { 197, 3 }, + { 197, 2 }, + { 197, 4 }, + { 205, 2 }, + { 205, 1 }, + { 205, 0 }, + { 198, 0 }, + { 198, 2 }, + { 207, 2 }, + { 207, 0 }, + { 206, 7 }, + { 206, 7 }, + { 206, 7 }, + { 157, 0 }, + { 157, 2 }, + { 193, 2 }, + { 208, 1 }, + { 208, 2 }, + { 208, 3 }, + { 208, 4 }, + { 210, 2 }, + { 210, 0 }, + { 209, 0 }, + { 209, 3 }, + { 209, 2 }, + { 211, 4 }, + { 211, 0 }, + { 202, 0 }, + { 202, 3 }, + { 214, 4 }, + { 214, 2 }, + { 176, 1 }, + { 176, 1 }, + { 176, 0 }, + { 200, 0 }, + { 200, 3 }, + { 201, 0 }, + { 201, 2 }, + { 203, 0 }, + { 203, 2 }, + { 203, 4 }, + { 203, 4 }, + { 147, 5 }, + { 199, 0 }, + { 199, 2 }, + { 147, 7 }, + { 216, 5 }, + { 216, 3 }, + { 147, 5 }, + { 147, 5 }, + { 147, 6 }, + { 217, 2 }, + { 217, 1 }, + { 219, 4 }, + { 219, 5 }, + { 218, 0 }, + { 218, 3 }, + { 213, 3 }, + { 213, 1 }, + { 174, 1 }, + { 174, 3 }, + { 173, 1 }, + { 174, 1 }, + { 174, 1 }, + { 174, 3 }, + { 174, 5 }, + { 173, 1 }, + { 173, 1 }, + { 174, 1 }, + { 174, 1 }, + { 174, 3 }, + { 174, 6 }, + { 174, 5 }, + { 174, 4 }, + { 173, 1 }, + { 174, 3 }, + { 174, 3 }, + { 174, 3 }, + { 174, 3 }, + { 174, 3 }, + { 174, 3 }, + { 174, 3 }, + { 174, 3 }, + { 221, 1 }, + { 221, 2 }, + { 221, 1 }, + { 221, 2 }, + { 174, 3 }, + { 174, 5 }, + { 174, 2 }, + { 174, 3 }, + { 174, 3 }, + { 174, 4 }, + { 174, 2 }, + { 174, 2 }, + { 174, 2 }, + { 174, 2 }, + { 222, 1 }, + { 222, 2 }, + { 174, 5 }, + { 223, 1 }, + { 223, 2 }, + { 174, 5 }, + { 174, 3 }, + { 174, 5 }, + { 174, 4 }, + { 174, 4 }, + { 174, 5 }, + { 225, 5 }, + { 225, 4 }, + { 226, 2 }, + { 226, 0 }, + { 224, 1 }, + { 224, 0 }, + { 220, 1 }, + { 220, 0 }, + { 215, 3 }, + { 215, 1 }, + { 147, 12 }, + { 227, 1 }, + { 227, 0 }, + { 178, 0 }, + { 178, 3 }, + { 187, 5 }, + { 187, 3 }, + { 228, 0 }, + { 228, 2 }, + { 147, 4 }, + { 147, 1 }, + { 147, 2 }, + { 147, 3 }, + { 147, 5 }, + { 147, 6 }, + { 147, 5 }, + { 147, 6 }, + { 229, 1 }, + { 229, 1 }, + { 229, 1 }, + { 229, 1 }, + { 229, 1 }, + { 170, 2 }, + { 170, 1 }, + { 171, 2 }, + { 230, 1 }, + { 147, 5 }, + { 231, 11 }, + { 233, 1 }, + { 233, 1 }, + { 233, 2 }, + { 233, 0 }, + { 234, 1 }, + { 234, 1 }, + { 234, 3 }, + { 235, 0 }, + { 235, 3 }, + { 236, 0 }, + { 236, 2 }, + { 232, 3 }, + { 232, 2 }, + { 238, 1 }, + { 238, 3 }, + { 239, 0 }, + { 239, 3 }, + { 239, 2 }, + { 237, 7 }, + { 237, 5 }, + { 237, 5 }, + { 237, 5 }, + { 237, 1 }, + { 174, 4 }, + { 174, 6 }, + { 191, 1 }, + { 191, 1 }, + { 191, 1 }, + { 147, 4 }, + { 147, 6 }, + { 147, 3 }, + { 241, 0 }, + { 241, 2 }, + { 240, 1 }, + { 240, 0 }, + { 147, 1 }, + { 147, 3 }, + { 147, 1 }, + { 147, 3 }, + { 147, 6 }, + { 147, 6 }, + { 242, 1 }, + { 243, 0 }, + { 243, 1 }, + { 147, 1 }, + { 147, 4 }, + { 244, 8 }, + { 245, 1 }, + { 245, 3 }, + { 246, 0 }, + { 246, 2 }, + { 247, 1 }, + { 247, 3 }, + { 248, 1 }, + { 249, 0 }, + { 249, 4 }, + { 249, 2 }, +}; + +static void yy_accept(yyParser*); /* Forward Declaration */ + +/* +** Perform a reduce action and the shift that must immediately +** follow the reduce. +*/ +static void yy_reduce( + yyParser *yypParser, /* The parser */ + int yyruleno /* Number of the rule by which to reduce */ +){ + int yygoto; /* The next state */ + int yyact; /* The next action */ + YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ + yyStackEntry *yymsp; /* The top of the parser's stack */ + int yysize; /* Amount to pop the stack */ + sqlite3ParserARG_FETCH; + yymsp = &yypParser->yystack[yypParser->yyidx]; +#ifndef NDEBUG + if( yyTraceFILE && yyruleno>=0 + && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ + fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, + yyRuleName[yyruleno]); + } +#endif /* NDEBUG */ + + /* Silence complaints from purify about yygotominor being uninitialized + ** in some cases when it is copied into the stack after the following + ** switch. yygotominor is uninitialized when a rule reduces that does + ** not set the value of its left-hand side nonterminal. Leaving the + ** value of the nonterminal uninitialized is utterly harmless as long + ** as the value is never used. So really the only thing this code + ** accomplishes is to quieten purify. + ** + ** 2007-01-16: The wireshark project (www.wireshark.org) reports that + ** without this code, their parser segfaults. I'm not sure what there + ** parser is doing to make this happen. This is the second bug report + ** from wireshark this week. Clearly they are stressing Lemon in ways + ** that it has not been previously stressed... (SQLite ticket #2172) + */ + /*memset(&yygotominor, 0, sizeof(yygotominor));*/ + yygotominor = yyzerominor; + + + switch( yyruleno ){ + /* Beginning here are the reduction cases. A typical example + ** follows: + ** case 0: + ** #line + ** { ... } // User supplied code + ** #line + ** break; + */ + case 5: /* explain ::= */ +{ sqlite3BeginParse(pParse, 0); } + break; + case 6: /* explain ::= EXPLAIN */ +{ sqlite3BeginParse(pParse, 1); } + break; + case 7: /* explain ::= EXPLAIN QUERY PLAN */ +{ sqlite3BeginParse(pParse, 2); } + break; + case 8: /* cmdx ::= cmd */ +{ sqlite3FinishCoding(pParse); } + break; + case 9: /* cmd ::= BEGIN transtype trans_opt */ +{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);} + break; + case 13: /* transtype ::= */ +{yygotominor.yy392 = TK_DEFERRED;} + break; + case 14: /* transtype ::= DEFERRED */ + case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15); + case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16); + case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115); + case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117); +{yygotominor.yy392 = yymsp[0].major;} + break; + case 17: /* cmd ::= COMMIT trans_opt */ + case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18); +{sqlite3CommitTransaction(pParse);} + break; + case 19: /* cmd ::= ROLLBACK trans_opt */ +{sqlite3RollbackTransaction(pParse);} + break; + case 22: /* cmd ::= SAVEPOINT nm */ +{ + sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0); +} + break; + case 23: /* cmd ::= RELEASE savepoint_opt nm */ +{ + sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0); +} + break; + case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ +{ + sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0); +} + break; + case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ +{ + sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392); +} + break; + case 27: /* createkw ::= CREATE */ +{ + pParse->db->lookaside.bEnabled = 0; + yygotominor.yy0 = yymsp[0].minor.yy0; +} + break; + case 28: /* ifnotexists ::= */ + case 31: /* temp ::= */ yytestcase(yyruleno==31); + case 69: /* autoinc ::= */ yytestcase(yyruleno==69); + case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82); + case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84); + case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86); + case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98); + case 109: /* ifexists ::= */ yytestcase(yyruleno==109); + case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221); + case 224: /* in_op ::= IN */ yytestcase(yyruleno==224); +{yygotominor.yy392 = 0;} + break; + case 29: /* ifnotexists ::= IF NOT EXISTS */ + case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30); + case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70); + case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85); + case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108); + case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222); + case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225); +{yygotominor.yy392 = 1;} + break; + case 32: /* create_table_args ::= LP columnlist conslist_opt RP */ +{ + sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0); +} + break; + case 33: /* create_table_args ::= AS select */ +{ + sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159); + sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159); +} + break; + case 36: /* column ::= columnid type carglist */ +{ + yygotominor.yy0.z = yymsp[-2].minor.yy0.z; + yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n; +} + break; + case 37: /* columnid ::= nm */ +{ + sqlite3AddColumn(pParse,&yymsp[0].minor.yy0); + yygotominor.yy0 = yymsp[0].minor.yy0; + pParse->constraintName.n = 0; +} + break; + case 38: /* id ::= ID */ + case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39); + case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40); + case 41: /* nm ::= id */ yytestcase(yyruleno==41); + case 42: /* nm ::= STRING */ yytestcase(yyruleno==42); + case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43); + case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46); + case 49: /* typename ::= ids */ yytestcase(yyruleno==49); + case 127: /* as ::= AS nm */ yytestcase(yyruleno==127); + case 128: /* as ::= ids */ yytestcase(yyruleno==128); + case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138); + case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147); + case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250); + case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259); + case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260); + case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261); + case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262); + case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263); + case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264); + case 265: /* plus_num ::= number */ yytestcase(yyruleno==265); + case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266); + case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267); + case 283: /* trnm ::= nm */ yytestcase(yyruleno==283); +{yygotominor.yy0 = yymsp[0].minor.yy0;} + break; + case 45: /* type ::= typetoken */ +{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);} + break; + case 47: /* typetoken ::= typename LP signed RP */ +{ + yygotominor.yy0.z = yymsp[-3].minor.yy0.z; + yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z); +} + break; + case 48: /* typetoken ::= typename LP signed COMMA signed RP */ +{ + yygotominor.yy0.z = yymsp[-5].minor.yy0.z; + yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z); +} + break; + case 50: /* typename ::= typename ids */ +{yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);} + break; + case 55: /* ccons ::= CONSTRAINT nm */ + case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93); +{pParse->constraintName = yymsp[0].minor.yy0;} + break; + case 56: /* ccons ::= DEFAULT term */ + case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58); +{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);} + break; + case 57: /* ccons ::= DEFAULT LP expr RP */ +{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);} + break; + case 59: /* ccons ::= DEFAULT MINUS term */ +{ + ExprSpan v; + v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0); + v.zStart = yymsp[-1].minor.yy0.z; + v.zEnd = yymsp[0].minor.yy342.zEnd; + sqlite3AddDefaultValue(pParse,&v); +} + break; + case 60: /* ccons ::= DEFAULT id */ +{ + ExprSpan v; + spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0); + sqlite3AddDefaultValue(pParse,&v); +} + break; + case 62: /* ccons ::= NOT NULL onconf */ +{sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);} + break; + case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ +{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);} + break; + case 64: /* ccons ::= UNIQUE onconf */ +{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);} + break; + case 65: /* ccons ::= CHECK LP expr RP */ +{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);} + break; + case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */ +{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);} + break; + case 67: /* ccons ::= defer_subclause */ +{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);} + break; + case 68: /* ccons ::= COLLATE ids */ +{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);} + break; + case 71: /* refargs ::= */ +{ yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */} + break; + case 72: /* refargs ::= refargs refarg */ +{ yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; } + break; + case 73: /* refarg ::= MATCH nm */ + case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74); +{ yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; } + break; + case 75: /* refarg ::= ON DELETE refact */ +{ yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; } + break; + case 76: /* refarg ::= ON UPDATE refact */ +{ yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; } + break; + case 77: /* refact ::= SET NULL */ +{ yygotominor.yy392 = OE_SetNull; /* EV: R-33326-45252 */} + break; + case 78: /* refact ::= SET DEFAULT */ +{ yygotominor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */} + break; + case 79: /* refact ::= CASCADE */ +{ yygotominor.yy392 = OE_Cascade; /* EV: R-33326-45252 */} + break; + case 80: /* refact ::= RESTRICT */ +{ yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */} + break; + case 81: /* refact ::= NO ACTION */ +{ yygotominor.yy392 = OE_None; /* EV: R-33326-45252 */} + break; + case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ + case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99); + case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101); + case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104); +{yygotominor.yy392 = yymsp[0].minor.yy392;} + break; + case 87: /* conslist_opt ::= */ +{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;} + break; + case 88: /* conslist_opt ::= COMMA conslist */ +{yygotominor.yy0 = yymsp[-1].minor.yy0;} + break; + case 91: /* tconscomma ::= COMMA */ +{pParse->constraintName.n = 0;} + break; + case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */ +{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);} + break; + case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */ +{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);} + break; + case 96: /* tcons ::= CHECK LP expr RP onconf */ +{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);} + break; + case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */ +{ + sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392); + sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392); +} + break; + case 100: /* onconf ::= */ +{yygotominor.yy392 = OE_Default;} + break; + case 102: /* orconf ::= */ +{yygotominor.yy258 = OE_Default;} + break; + case 103: /* orconf ::= OR resolvetype */ +{yygotominor.yy258 = (u8)yymsp[0].minor.yy392;} + break; + case 105: /* resolvetype ::= IGNORE */ +{yygotominor.yy392 = OE_Ignore;} + break; + case 106: /* resolvetype ::= REPLACE */ +{yygotominor.yy392 = OE_Replace;} + break; + case 107: /* cmd ::= DROP TABLE ifexists fullname */ +{ + sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392); +} + break; + case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */ +{ + sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392); +} + break; + case 111: /* cmd ::= DROP VIEW ifexists fullname */ +{ + sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392); +} + break; + case 112: /* cmd ::= select */ +{ + SelectDest dest = {SRT_Output, 0, 0, 0, 0}; + sqlite3Select(pParse, yymsp[0].minor.yy159, &dest); + sqlite3ExplainBegin(pParse->pVdbe); + sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159); + sqlite3ExplainFinish(pParse->pVdbe); + sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159); +} + break; + case 113: /* select ::= oneselect */ +{yygotominor.yy159 = yymsp[0].minor.yy159;} + break; + case 114: /* select ::= select multiselect_op oneselect */ +{ + if( yymsp[0].minor.yy159 ){ + yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392; + yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159; + if( yymsp[-1].minor.yy392!=TK_ALL ) pParse->hasCompound = 1; + }else{ + sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159); + } + yygotominor.yy159 = yymsp[0].minor.yy159; +} + break; + case 116: /* multiselect_op ::= UNION ALL */ +{yygotominor.yy392 = TK_ALL;} + break; + case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ +{ + yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy305,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset); +} + break; + case 119: /* distinct ::= DISTINCT */ +{yygotominor.yy305 = SF_Distinct;} + break; + case 120: /* distinct ::= ALL */ + case 121: /* distinct ::= */ yytestcase(yyruleno==121); +{yygotominor.yy305 = 0;} + break; + case 122: /* sclp ::= selcollist COMMA */ + case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246); +{yygotominor.yy442 = yymsp[-1].minor.yy442;} + break; + case 123: /* sclp ::= */ + case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151); + case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158); + case 239: /* exprlist ::= */ yytestcase(yyruleno==239); + case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245); +{yygotominor.yy442 = 0;} + break; + case 124: /* selcollist ::= sclp expr as */ +{ + yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr); + if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1); + sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342); +} + break; + case 125: /* selcollist ::= sclp STAR */ +{ + Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0); + yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p); +} + break; + case 126: /* selcollist ::= sclp nm DOT STAR */ +{ + Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0); + Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0); + Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); + yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot); +} + break; + case 129: /* as ::= */ +{yygotominor.yy0.n = 0;} + break; + case 130: /* from ::= */ +{yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));} + break; + case 131: /* from ::= FROM seltablist */ +{ + yygotominor.yy347 = yymsp[0].minor.yy347; + sqlite3SrcListShiftJoinType(yygotominor.yy347); +} + break; + case 132: /* stl_prefix ::= seltablist joinop */ +{ + yygotominor.yy347 = yymsp[-1].minor.yy347; + if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392; +} + break; + case 133: /* stl_prefix ::= */ +{yygotominor.yy347 = 0;} + break; + case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ +{ + yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180); + sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0); +} + break; + case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ +{ + yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180); + } + break; + case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ +{ + if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){ + yygotominor.yy347 = yymsp[-4].minor.yy347; + }else if( yymsp[-4].minor.yy347->nSrc==1 ){ + yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180); + if( yygotominor.yy347 ){ + struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1]; + struct SrcList_item *pOld = yymsp[-4].minor.yy347->a; + pNew->zName = pOld->zName; + pNew->zDatabase = pOld->zDatabase; + pNew->pSelect = pOld->pSelect; + pOld->zName = pOld->zDatabase = 0; + pOld->pSelect = 0; + } + sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347); + }else{ + Select *pSubquery; + sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347); + pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0); + yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180); + } + } + break; + case 137: /* dbnm ::= */ + case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146); +{yygotominor.yy0.z=0; yygotominor.yy0.n=0;} + break; + case 139: /* fullname ::= nm dbnm */ +{yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);} + break; + case 140: /* joinop ::= COMMA|JOIN */ +{ yygotominor.yy392 = JT_INNER; } + break; + case 141: /* joinop ::= JOIN_KW JOIN */ +{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); } + break; + case 142: /* joinop ::= JOIN_KW nm JOIN */ +{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); } + break; + case 143: /* joinop ::= JOIN_KW nm nm JOIN */ +{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); } + break; + case 144: /* on_opt ::= ON expr */ + case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161); + case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168); + case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234); + case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236); +{yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;} + break; + case 145: /* on_opt ::= */ + case 160: /* having_opt ::= */ yytestcase(yyruleno==160); + case 167: /* where_opt ::= */ yytestcase(yyruleno==167); + case 235: /* case_else ::= */ yytestcase(yyruleno==235); + case 237: /* case_operand ::= */ yytestcase(yyruleno==237); +{yygotominor.yy122 = 0;} + break; + case 148: /* indexed_opt ::= NOT INDEXED */ +{yygotominor.yy0.z=0; yygotominor.yy0.n=1;} + break; + case 149: /* using_opt ::= USING LP inscollist RP */ + case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180); +{yygotominor.yy180 = yymsp[-1].minor.yy180;} + break; + case 150: /* using_opt ::= */ + case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179); +{yygotominor.yy180 = 0;} + break; + case 152: /* orderby_opt ::= ORDER BY sortlist */ + case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159); + case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238); +{yygotominor.yy442 = yymsp[0].minor.yy442;} + break; + case 153: /* sortlist ::= sortlist COMMA expr sortorder */ +{ + yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr); + if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392; +} + break; + case 154: /* sortlist ::= expr sortorder */ +{ + yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr); + if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392; +} + break; + case 155: /* sortorder ::= ASC */ + case 157: /* sortorder ::= */ yytestcase(yyruleno==157); +{yygotominor.yy392 = SQLITE_SO_ASC;} + break; + case 156: /* sortorder ::= DESC */ +{yygotominor.yy392 = SQLITE_SO_DESC;} + break; + case 162: /* limit_opt ::= */ +{yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;} + break; + case 163: /* limit_opt ::= LIMIT expr */ +{yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;} + break; + case 164: /* limit_opt ::= LIMIT expr OFFSET expr */ +{yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;} + break; + case 165: /* limit_opt ::= LIMIT expr COMMA expr */ +{yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;} + break; + case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */ +{ + sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0); + sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122); +} + break; + case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */ +{ + sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0); + sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list"); + sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258); +} + break; + case 170: /* setlist ::= setlist COMMA nm EQ expr */ +{ + yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr); + sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1); +} + break; + case 171: /* setlist ::= nm EQ expr */ +{ + yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr); + sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1); +} + break; + case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */ +{sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);} + break; + case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */ +{sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);} + break; + case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */ +{sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);} + break; + case 175: /* insert_cmd ::= INSERT orconf */ +{yygotominor.yy258 = yymsp[0].minor.yy258;} + break; + case 176: /* insert_cmd ::= REPLACE */ +{yygotominor.yy258 = OE_Replace;} + break; + case 177: /* valuelist ::= VALUES LP nexprlist RP */ +{ + yygotominor.yy487.pList = yymsp[-1].minor.yy442; + yygotominor.yy487.pSelect = 0; +} + break; + case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */ +{ + Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0); + if( yymsp[-4].minor.yy487.pList ){ + yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0); + yymsp[-4].minor.yy487.pList = 0; + } + yygotominor.yy487.pList = 0; + if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){ + sqlite3SelectDelete(pParse->db, pRight); + sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect); + yygotominor.yy487.pSelect = 0; + }else{ + pRight->op = TK_ALL; + pRight->pPrior = yymsp[-4].minor.yy487.pSelect; + pRight->selFlags |= SF_Values; + pRight->pPrior->selFlags |= SF_Values; + yygotominor.yy487.pSelect = pRight; + } +} + break; + case 181: /* inscollist ::= inscollist COMMA nm */ +{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);} + break; + case 182: /* inscollist ::= nm */ +{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);} + break; + case 183: /* expr ::= term */ +{yygotominor.yy342 = yymsp[0].minor.yy342;} + break; + case 184: /* expr ::= LP expr RP */ +{yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);} + break; + case 185: /* term ::= NULL */ + case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190); + case 191: /* term ::= STRING */ yytestcase(yyruleno==191); +{spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);} + break; + case 186: /* expr ::= id */ + case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187); +{spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);} + break; + case 188: /* expr ::= nm DOT nm */ +{ + Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0); + Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0); + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0); + spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); +} + break; + case 189: /* expr ::= nm DOT nm DOT nm */ +{ + Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0); + Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0); + Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0); + Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0); + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0); + spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); +} + break; + case 192: /* expr ::= REGISTER */ +{ + /* When doing a nested parse, one can include terms in an expression + ** that look like this: #1 #2 ... These terms refer to registers + ** in the virtual machine. #N is the N-th register. */ + if( pParse->nested==0 ){ + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0); + yygotominor.yy342.pExpr = 0; + }else{ + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0); + if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable); + } + spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0); +} + break; + case 193: /* expr ::= VARIABLE */ +{ + spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0); + sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr); + spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0); +} + break; + case 194: /* expr ::= expr COLLATE ids */ +{ + yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0); + yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart; + yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; +} + break; + case 195: /* expr ::= CAST LP expr AS typetoken RP */ +{ + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0); + spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); +} + break; + case 196: /* expr ::= ID LP distinct exprlist RP */ +{ + if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ + sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0); + } + yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0); + spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); + if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){ + yygotominor.yy342.pExpr->flags |= EP_Distinct; + } +} + break; + case 197: /* expr ::= ID LP STAR RP */ +{ + yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0); + spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); +} + break; + case 198: /* term ::= CTIME_KW */ +{ + /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are + ** treated as functions that return constants */ + yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0); + if( yygotominor.yy342.pExpr ){ + yygotominor.yy342.pExpr->op = TK_CONST_FUNC; + } + spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0); +} + break; + case 199: /* expr ::= expr AND expr */ + case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200); + case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201); + case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202); + case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203); + case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204); + case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205); + case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206); +{spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);} + break; + case 207: /* likeop ::= LIKE_KW */ + case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209); +{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;} + break; + case 208: /* likeop ::= NOT LIKE_KW */ + case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210); +{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;} + break; + case 211: /* expr ::= expr likeop expr */ +{ + ExprList *pList; + pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr); + pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr); + yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator); + if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0); + yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart; + yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd; + if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc; +} + break; + case 212: /* expr ::= expr likeop expr ESCAPE expr */ +{ + ExprList *pList; + pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr); + pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr); + pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr); + yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator); + if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0); + yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart; + yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd; + if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc; +} + break; + case 213: /* expr ::= expr ISNULL|NOTNULL */ +{spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);} + break; + case 214: /* expr ::= expr NOT NULL */ +{spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);} + break; + case 215: /* expr ::= expr IS expr */ +{ + spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342); + binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL); +} + break; + case 216: /* expr ::= expr IS NOT expr */ +{ + spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342); + binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL); +} + break; + case 217: /* expr ::= NOT expr */ + case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218); +{spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);} + break; + case 219: /* expr ::= MINUS expr */ +{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);} + break; + case 220: /* expr ::= PLUS expr */ +{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);} + break; + case 223: /* expr ::= expr between_op expr AND expr */ +{ + ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr); + pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr); + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0); + if( yygotominor.yy342.pExpr ){ + yygotominor.yy342.pExpr->x.pList = pList; + }else{ + sqlite3ExprListDelete(pParse->db, pList); + } + if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0); + yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart; + yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd; +} + break; + case 226: /* expr ::= expr in_op LP exprlist RP */ +{ + if( yymsp[-1].minor.yy442==0 ){ + /* Expressions of the form + ** + ** expr1 IN () + ** expr1 NOT IN () + ** + ** simplify to constants 0 (false) and 1 (true), respectively, + ** regardless of the value of expr1. + */ + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]); + sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr); + }else{ + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0); + if( yygotominor.yy342.pExpr ){ + yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442; + sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr); + }else{ + sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442); + } + if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0); + } + yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart; + yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; + } + break; + case 227: /* expr ::= LP select RP */ +{ + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0); + if( yygotominor.yy342.pExpr ){ + yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159; + ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr); + }else{ + sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159); + } + yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z; + yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; + } + break; + case 228: /* expr ::= expr in_op LP select RP */ +{ + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0); + if( yygotominor.yy342.pExpr ){ + yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159; + ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr); + }else{ + sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159); + } + if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0); + yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart; + yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; + } + break; + case 229: /* expr ::= expr in_op nm dbnm */ +{ + SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0); + if( yygotominor.yy342.pExpr ){ + yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0); + ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr); + }else{ + sqlite3SrcListDelete(pParse->db, pSrc); + } + if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0); + yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart; + yygotominor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]; + } + break; + case 230: /* expr ::= EXISTS LP select RP */ +{ + Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0); + if( p ){ + p->x.pSelect = yymsp[-1].minor.yy159; + ExprSetProperty(p, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, p); + }else{ + sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159); + } + yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z; + yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; + } + break; + case 231: /* expr ::= CASE case_operand case_exprlist case_else END */ +{ + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, 0, 0); + if( yygotominor.yy342.pExpr ){ + yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy122 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122) : yymsp[-2].minor.yy442; + sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr); + }else{ + sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442); + sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy122); + } + yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z; + yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; +} + break; + case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ +{ + yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr); + yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr); +} + break; + case 233: /* case_exprlist ::= WHEN expr THEN expr */ +{ + yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr); + yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr); +} + break; + case 240: /* nexprlist ::= nexprlist COMMA expr */ +{yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);} + break; + case 241: /* nexprlist ::= expr */ +{yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);} + break; + case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */ +{ + sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, + sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy442, yymsp[-10].minor.yy392, + &yymsp[-11].minor.yy0, yymsp[0].minor.yy122, SQLITE_SO_ASC, yymsp[-8].minor.yy392); +} + break; + case 243: /* uniqueflag ::= UNIQUE */ + case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296); +{yygotominor.yy392 = OE_Abort;} + break; + case 244: /* uniqueflag ::= */ +{yygotominor.yy392 = OE_None;} + break; + case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */ +{ + Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0); + yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p); + sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1); + sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index"); + if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392; +} + break; + case 248: /* idxlist ::= nm collate sortorder */ +{ + Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0); + yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p); + sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1); + sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index"); + if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392; +} + break; + case 249: /* collate ::= */ +{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;} + break; + case 251: /* cmd ::= DROP INDEX ifexists fullname */ +{sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);} + break; + case 252: /* cmd ::= VACUUM */ + case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253); +{sqlite3Vacuum(pParse);} + break; + case 254: /* cmd ::= PRAGMA nm dbnm */ +{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);} + break; + case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);} + break; + case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ +{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);} + break; + case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);} + break; + case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ +{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);} + break; + case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ +{ + Token all; + all.z = yymsp[-3].minor.yy0.z; + all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n; + sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all); +} + break; + case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ +{ + sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392); + yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); +} + break; + case 270: /* trigger_time ::= BEFORE */ + case 273: /* trigger_time ::= */ yytestcase(yyruleno==273); +{ yygotominor.yy392 = TK_BEFORE; } + break; + case 271: /* trigger_time ::= AFTER */ +{ yygotominor.yy392 = TK_AFTER; } + break; + case 272: /* trigger_time ::= INSTEAD OF */ +{ yygotominor.yy392 = TK_INSTEAD;} + break; + case 274: /* trigger_event ::= DELETE|INSERT */ + case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275); +{yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;} + break; + case 276: /* trigger_event ::= UPDATE OF inscollist */ +{yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;} + break; + case 279: /* when_clause ::= */ + case 301: /* key_opt ::= */ yytestcase(yyruleno==301); +{ yygotominor.yy122 = 0; } + break; + case 280: /* when_clause ::= WHEN expr */ + case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302); +{ yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; } + break; + case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ +{ + assert( yymsp[-2].minor.yy327!=0 ); + yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327; + yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327; + yygotominor.yy327 = yymsp[-2].minor.yy327; +} + break; + case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */ +{ + assert( yymsp[-1].minor.yy327!=0 ); + yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327; + yygotominor.yy327 = yymsp[-1].minor.yy327; +} + break; + case 284: /* trnm ::= nm DOT nm */ +{ + yygotominor.yy0 = yymsp[0].minor.yy0; + sqlite3ErrorMsg(pParse, + "qualified table names are not allowed on INSERT, UPDATE, and DELETE " + "statements within triggers"); +} + break; + case 286: /* tridxby ::= INDEXED BY nm */ +{ + sqlite3ErrorMsg(pParse, + "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " + "within triggers"); +} + break; + case 287: /* tridxby ::= NOT INDEXED */ +{ + sqlite3ErrorMsg(pParse, + "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " + "within triggers"); +} + break; + case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */ +{ yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); } + break; + case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */ +{yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);} + break; + case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */ +{yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);} + break; + case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */ +{yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);} + break; + case 292: /* trigger_cmd ::= select */ +{yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); } + break; + case 293: /* expr ::= RAISE LP IGNORE RP */ +{ + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); + if( yygotominor.yy342.pExpr ){ + yygotominor.yy342.pExpr->affinity = OE_Ignore; + } + yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z; + yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; +} + break; + case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */ +{ + yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); + if( yygotominor.yy342.pExpr ) { + yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392; + } + yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z; + yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; +} + break; + case 295: /* raisetype ::= ROLLBACK */ +{yygotominor.yy392 = OE_Rollback;} + break; + case 297: /* raisetype ::= FAIL */ +{yygotominor.yy392 = OE_Fail;} + break; + case 298: /* cmd ::= DROP TRIGGER ifexists fullname */ +{ + sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392); +} + break; + case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ +{ + sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122); +} + break; + case 300: /* cmd ::= DETACH database_kw_opt expr */ +{ + sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr); +} + break; + case 305: /* cmd ::= REINDEX */ +{sqlite3Reindex(pParse, 0, 0);} + break; + case 306: /* cmd ::= REINDEX nm dbnm */ +{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} + break; + case 307: /* cmd ::= ANALYZE */ +{sqlite3Analyze(pParse, 0, 0);} + break; + case 308: /* cmd ::= ANALYZE nm dbnm */ +{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} + break; + case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ +{ + sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0); +} + break; + case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */ +{ + sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0); +} + break; + case 311: /* add_column_fullname ::= fullname */ +{ + pParse->db->lookaside.bEnabled = 0; + sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347); +} + break; + case 314: /* cmd ::= create_vtab */ +{sqlite3VtabFinishParse(pParse,0);} + break; + case 315: /* cmd ::= create_vtab LP vtabarglist RP */ +{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} + break; + case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ +{ + sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392); +} + break; + case 319: /* vtabarg ::= */ +{sqlite3VtabArgInit(pParse);} + break; + case 321: /* vtabargtoken ::= ANY */ + case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322); + case 323: /* lp ::= LP */ yytestcase(yyruleno==323); +{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} + break; + default: + /* (0) input ::= cmdlist */ yytestcase(yyruleno==0); + /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1); + /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2); + /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3); + /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4); + /* (10) trans_opt ::= */ yytestcase(yyruleno==10); + /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11); + /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12); + /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20); + /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21); + /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25); + /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34); + /* (35) columnlist ::= column */ yytestcase(yyruleno==35); + /* (44) type ::= */ yytestcase(yyruleno==44); + /* (51) signed ::= plus_num */ yytestcase(yyruleno==51); + /* (52) signed ::= minus_num */ yytestcase(yyruleno==52); + /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53); + /* (54) carglist ::= */ yytestcase(yyruleno==54); + /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61); + /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89); + /* (90) conslist ::= tcons */ yytestcase(yyruleno==90); + /* (92) tconscomma ::= */ yytestcase(yyruleno==92); + /* (277) foreach_clause ::= */ yytestcase(yyruleno==277); + /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278); + /* (285) tridxby ::= */ yytestcase(yyruleno==285); + /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303); + /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304); + /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312); + /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313); + /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317); + /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318); + /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320); + /* (324) anylist ::= */ yytestcase(yyruleno==324); + /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325); + /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326); + break; + }; + assert( yyruleno>=0 && yyrulenoyyidx -= yysize; + yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); + if( yyact < YYNSTATE ){ +#ifdef NDEBUG + /* If we are not debugging and the reduce action popped at least + ** one element off the stack, then we can push the new element back + ** onto the stack here, and skip the stack overflow test in yy_shift(). + ** That gives a significant speed improvement. */ + if( yysize ){ + yypParser->yyidx++; + yymsp -= yysize-1; + yymsp->stateno = (YYACTIONTYPE)yyact; + yymsp->major = (YYCODETYPE)yygoto; + yymsp->minor = yygotominor; + }else +#endif + { + yy_shift(yypParser,yyact,yygoto,&yygotominor); + } + }else{ + assert( yyact == YYNSTATE + YYNRULE + 1 ); + yy_accept(yypParser); + } +} + +/* +** The following code executes when the parse fails +*/ +#ifndef YYNOERRORRECOVERY +static void yy_parse_failed( + yyParser *yypParser /* The parser */ +){ + sqlite3ParserARG_FETCH; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); + } +#endif + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will be executed whenever the + ** parser fails */ + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ +} +#endif /* YYNOERRORRECOVERY */ + +/* +** The following code executes when a syntax error first occurs. +*/ +static void yy_syntax_error( + yyParser *yypParser, /* The parser */ + int yymajor, /* The major type of the error token */ + YYMINORTYPE yyminor /* The minor type of the error token */ +){ + sqlite3ParserARG_FETCH; +#define TOKEN (yyminor.yy0) + + UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ + assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */ + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ +} + +/* +** The following is executed when the parser accepts +*/ +static void yy_accept( + yyParser *yypParser /* The parser */ +){ + sqlite3ParserARG_FETCH; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); + } +#endif + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will be executed whenever the + ** parser accepts */ + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ +} + +/* The main parser program. +** The first argument is a pointer to a structure obtained from +** "sqlite3ParserAlloc" which describes the current state of the parser. +** The second argument is the major token number. The third is +** the minor token. The fourth optional argument is whatever the +** user wants (and specified in the grammar) and is available for +** use by the action routines. +** +** Inputs: +**
    +**
  • A pointer to the parser (an opaque structure.) +**
  • The major token number. +**
  • The minor token number. +**
  • An option argument of a grammar-specified type. +**
+** +** Outputs: +** None. +*/ +SQLITE_PRIVATE void sqlite3Parser( + void *yyp, /* The parser */ + int yymajor, /* The major token code number */ + sqlite3ParserTOKENTYPE yyminor /* The value for the token */ + sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ +){ + YYMINORTYPE yyminorunion; + int yyact; /* The parser action. */ +#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) + int yyendofinput; /* True if we are at the end of input */ +#endif +#ifdef YYERRORSYMBOL + int yyerrorhit = 0; /* True if yymajor has invoked an error */ +#endif + yyParser *yypParser; /* The parser */ + + /* (re)initialize the parser, if necessary */ + yypParser = (yyParser*)yyp; + if( yypParser->yyidx<0 ){ +#if YYSTACKDEPTH<=0 + if( yypParser->yystksz <=0 ){ + /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/ + yyminorunion = yyzerominor; + yyStackOverflow(yypParser, &yyminorunion); + return; + } +#endif + yypParser->yyidx = 0; + yypParser->yyerrcnt = -1; + yypParser->yystack[0].stateno = 0; + yypParser->yystack[0].major = 0; + } + yyminorunion.yy0 = yyminor; +#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) + yyendofinput = (yymajor==0); +#endif + sqlite3ParserARG_STORE; + +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); + } +#endif + + do{ + yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); + if( yyactyyerrcnt--; + yymajor = YYNOCODE; + }else if( yyact < YYNSTATE + YYNRULE ){ + yy_reduce(yypParser,yyact-YYNSTATE); + }else{ + assert( yyact == YY_ERROR_ACTION ); +#ifdef YYERRORSYMBOL + int yymx; +#endif +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); + } +#endif +#ifdef YYERRORSYMBOL + /* A syntax error has occurred. + ** The response to an error depends upon whether or not the + ** grammar defines an error token "ERROR". + ** + ** This is what we do if the grammar does define ERROR: + ** + ** * Call the %syntax_error function. + ** + ** * Begin popping the stack until we enter a state where + ** it is legal to shift the error symbol, then shift + ** the error symbol. + ** + ** * Set the error count to three. + ** + ** * Begin accepting and shifting new tokens. No new error + ** processing will occur until three tokens have been + ** shifted successfully. + ** + */ + if( yypParser->yyerrcnt<0 ){ + yy_syntax_error(yypParser,yymajor,yyminorunion); + } + yymx = yypParser->yystack[yypParser->yyidx].major; + if( yymx==YYERRORSYMBOL || yyerrorhit ){ +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sDiscard input token %s\n", + yyTracePrompt,yyTokenName[yymajor]); + } +#endif + yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion); + yymajor = YYNOCODE; + }else{ + while( + yypParser->yyidx >= 0 && + yymx != YYERRORSYMBOL && + (yyact = yy_find_reduce_action( + yypParser->yystack[yypParser->yyidx].stateno, + YYERRORSYMBOL)) >= YYNSTATE + ){ + yy_pop_parser_stack(yypParser); + } + if( yypParser->yyidx < 0 || yymajor==0 ){ + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); + yy_parse_failed(yypParser); + yymajor = YYNOCODE; + }else if( yymx!=YYERRORSYMBOL ){ + YYMINORTYPE u2; + u2.YYERRSYMDT = 0; + yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); + } + } + yypParser->yyerrcnt = 3; + yyerrorhit = 1; +#elif defined(YYNOERRORRECOVERY) + /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to + ** do any kind of error recovery. Instead, simply invoke the syntax + ** error routine and continue going as if nothing had happened. + ** + ** Applications can set this macro (for example inside %include) if + ** they intend to abandon the parse upon the first syntax error seen. + */ + yy_syntax_error(yypParser,yymajor,yyminorunion); + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); + yymajor = YYNOCODE; + +#else /* YYERRORSYMBOL is not defined */ + /* This is what we do if the grammar does not define ERROR: + ** + ** * Report an error message, and throw away the input token. + ** + ** * If the input token is $, then fail the parse. + ** + ** As before, subsequent error messages are suppressed until + ** three input tokens have been successfully shifted. + */ + if( yypParser->yyerrcnt<=0 ){ + yy_syntax_error(yypParser,yymajor,yyminorunion); + } + yypParser->yyerrcnt = 3; + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); + if( yyendofinput ){ + yy_parse_failed(yypParser); + } + yymajor = YYNOCODE; +#endif + } + }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); + return; +} + +/************** End of parse.c ***********************************************/ +/************** Begin file tokenize.c ****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** An tokenizer for SQL +** +** This file contains C code that splits an SQL input string up into +** individual tokens and sends those tokens one-by-one over to the +** parser for analysis. +*/ +/* #include */ + +/* +** The charMap() macro maps alphabetic characters into their +** lower-case ASCII equivalent. On ASCII machines, this is just +** an upper-to-lower case map. On EBCDIC machines we also need +** to adjust the encoding. Only alphabetic characters and underscores +** need to be translated. +*/ +#ifdef SQLITE_ASCII +# define charMap(X) sqlite3UpperToLower[(unsigned char)X] +#endif +#ifdef SQLITE_EBCDIC +# define charMap(X) ebcdicToAscii[(unsigned char)X] +const unsigned char ebcdicToAscii[] = { +/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */ + 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */ + 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */ + 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ + 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */ + 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */ + 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */ +}; +#endif + +/* +** The sqlite3KeywordCode function looks up an identifier to determine if +** it is a keyword. If it is a keyword, the token code of that keyword is +** returned. If the input is not a keyword, TK_ID is returned. +** +** The implementation of this routine was generated by a program, +** mkkeywordhash.h, located in the tool subdirectory of the distribution. +** The output of the mkkeywordhash.c program is written into a file +** named keywordhash.h and then included into this source file by +** the #include below. +*/ +/************** Include keywordhash.h in the middle of tokenize.c ************/ +/************** Begin file keywordhash.h *************************************/ +/***** This file contains automatically generated code ****** +** +** The code in this file has been automatically generated by +** +** sqlite/tool/mkkeywordhash.c +** +** The code in this file implements a function that determines whether +** or not a given identifier is really an SQL keyword. The same thing +** might be implemented more directly using a hand-written hash table. +** But by using this automatically generated code, the size of the code +** is substantially reduced. This is important for embedded applications +** on platforms with limited memory. +*/ +/* Hash score: 175 */ +static int keywordCode(const char *z, int n){ + /* zText[] encodes 811 bytes of keywords in 541 bytes */ + /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ + /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ + /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ + /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */ + /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */ + /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */ + /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */ + /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */ + /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */ + /* INITIALLY */ + static const char zText[540] = { + 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', + 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', + 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', + 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', + 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N', + 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I', + 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E', + 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E', + 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T', + 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q', + 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U', + 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S', + 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C', + 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L', + 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D', + 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E', + 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A', + 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U', + 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W', + 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C', + 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R', + 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M', + 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U', + 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M', + 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T', + 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L', + 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S', + 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L', + 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V', + 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y', + }; + static const unsigned char aHash[127] = { + 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0, + 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0, + 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67, + 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44, + 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25, + 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0, + 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14, + 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109, + 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0, + 29, 0, 82, 59, 60, 0, 20, 57, 0, 52, + }; + static const unsigned char aNext[121] = { + 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, + 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47, + 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1, + 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0, + 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0, + 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0, + 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0, + 35, 64, 0, 0, + }; + static const unsigned char aLen[121] = { + 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, + 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6, + 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, + 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6, + 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4, + 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6, + 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4, + 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4, + 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5, + 6, 4, 9, 3, + }; + static const unsigned short int aOffset[121] = { + 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, + 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, + 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, + 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197, + 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244, + 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320, + 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383, + 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458, + 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516, + 521, 527, 531, 536, + }; + static const unsigned char aCode[121] = { + TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, + TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, + TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, + TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, + TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, + TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW, + TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, + TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, + TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP, + TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING, + TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE, + TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, + TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, + TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, + TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, + TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, + TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, + TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, + TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, + TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, + TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, + TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER, + TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW, + TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY, + TK_ALL, + }; + int h, i; + if( n<2 ) return TK_ID; + h = ((charMap(z[0])*4) ^ + (charMap(z[n-1])*3) ^ + n) % 127; + for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){ + if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){ + testcase( i==0 ); /* REINDEX */ + testcase( i==1 ); /* INDEXED */ + testcase( i==2 ); /* INDEX */ + testcase( i==3 ); /* DESC */ + testcase( i==4 ); /* ESCAPE */ + testcase( i==5 ); /* EACH */ + testcase( i==6 ); /* CHECK */ + testcase( i==7 ); /* KEY */ + testcase( i==8 ); /* BEFORE */ + testcase( i==9 ); /* FOREIGN */ + testcase( i==10 ); /* FOR */ + testcase( i==11 ); /* IGNORE */ + testcase( i==12 ); /* REGEXP */ + testcase( i==13 ); /* EXPLAIN */ + testcase( i==14 ); /* INSTEAD */ + testcase( i==15 ); /* ADD */ + testcase( i==16 ); /* DATABASE */ + testcase( i==17 ); /* AS */ + testcase( i==18 ); /* SELECT */ + testcase( i==19 ); /* TABLE */ + testcase( i==20 ); /* LEFT */ + testcase( i==21 ); /* THEN */ + testcase( i==22 ); /* END */ + testcase( i==23 ); /* DEFERRABLE */ + testcase( i==24 ); /* ELSE */ + testcase( i==25 ); /* EXCEPT */ + testcase( i==26 ); /* TRANSACTION */ + testcase( i==27 ); /* ACTION */ + testcase( i==28 ); /* ON */ + testcase( i==29 ); /* NATURAL */ + testcase( i==30 ); /* ALTER */ + testcase( i==31 ); /* RAISE */ + testcase( i==32 ); /* EXCLUSIVE */ + testcase( i==33 ); /* EXISTS */ + testcase( i==34 ); /* SAVEPOINT */ + testcase( i==35 ); /* INTERSECT */ + testcase( i==36 ); /* TRIGGER */ + testcase( i==37 ); /* REFERENCES */ + testcase( i==38 ); /* CONSTRAINT */ + testcase( i==39 ); /* INTO */ + testcase( i==40 ); /* OFFSET */ + testcase( i==41 ); /* OF */ + testcase( i==42 ); /* SET */ + testcase( i==43 ); /* TEMPORARY */ + testcase( i==44 ); /* TEMP */ + testcase( i==45 ); /* OR */ + testcase( i==46 ); /* UNIQUE */ + testcase( i==47 ); /* QUERY */ + testcase( i==48 ); /* ATTACH */ + testcase( i==49 ); /* HAVING */ + testcase( i==50 ); /* GROUP */ + testcase( i==51 ); /* UPDATE */ + testcase( i==52 ); /* BEGIN */ + testcase( i==53 ); /* INNER */ + testcase( i==54 ); /* RELEASE */ + testcase( i==55 ); /* BETWEEN */ + testcase( i==56 ); /* NOTNULL */ + testcase( i==57 ); /* NOT */ + testcase( i==58 ); /* NO */ + testcase( i==59 ); /* NULL */ + testcase( i==60 ); /* LIKE */ + testcase( i==61 ); /* CASCADE */ + testcase( i==62 ); /* ASC */ + testcase( i==63 ); /* DELETE */ + testcase( i==64 ); /* CASE */ + testcase( i==65 ); /* COLLATE */ + testcase( i==66 ); /* CREATE */ + testcase( i==67 ); /* CURRENT_DATE */ + testcase( i==68 ); /* DETACH */ + testcase( i==69 ); /* IMMEDIATE */ + testcase( i==70 ); /* JOIN */ + testcase( i==71 ); /* INSERT */ + testcase( i==72 ); /* MATCH */ + testcase( i==73 ); /* PLAN */ + testcase( i==74 ); /* ANALYZE */ + testcase( i==75 ); /* PRAGMA */ + testcase( i==76 ); /* ABORT */ + testcase( i==77 ); /* VALUES */ + testcase( i==78 ); /* VIRTUAL */ + testcase( i==79 ); /* LIMIT */ + testcase( i==80 ); /* WHEN */ + testcase( i==81 ); /* WHERE */ + testcase( i==82 ); /* RENAME */ + testcase( i==83 ); /* AFTER */ + testcase( i==84 ); /* REPLACE */ + testcase( i==85 ); /* AND */ + testcase( i==86 ); /* DEFAULT */ + testcase( i==87 ); /* AUTOINCREMENT */ + testcase( i==88 ); /* TO */ + testcase( i==89 ); /* IN */ + testcase( i==90 ); /* CAST */ + testcase( i==91 ); /* COLUMN */ + testcase( i==92 ); /* COMMIT */ + testcase( i==93 ); /* CONFLICT */ + testcase( i==94 ); /* CROSS */ + testcase( i==95 ); /* CURRENT_TIMESTAMP */ + testcase( i==96 ); /* CURRENT_TIME */ + testcase( i==97 ); /* PRIMARY */ + testcase( i==98 ); /* DEFERRED */ + testcase( i==99 ); /* DISTINCT */ + testcase( i==100 ); /* IS */ + testcase( i==101 ); /* DROP */ + testcase( i==102 ); /* FAIL */ + testcase( i==103 ); /* FROM */ + testcase( i==104 ); /* FULL */ + testcase( i==105 ); /* GLOB */ + testcase( i==106 ); /* BY */ + testcase( i==107 ); /* IF */ + testcase( i==108 ); /* ISNULL */ + testcase( i==109 ); /* ORDER */ + testcase( i==110 ); /* RESTRICT */ + testcase( i==111 ); /* OUTER */ + testcase( i==112 ); /* RIGHT */ + testcase( i==113 ); /* ROLLBACK */ + testcase( i==114 ); /* ROW */ + testcase( i==115 ); /* UNION */ + testcase( i==116 ); /* USING */ + testcase( i==117 ); /* VACUUM */ + testcase( i==118 ); /* VIEW */ + testcase( i==119 ); /* INITIALLY */ + testcase( i==120 ); /* ALL */ + return aCode[i]; + } + } + return TK_ID; +} +SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){ + return keywordCode((char*)z, n); +} +#define SQLITE_N_KEYWORD 121 + +/************** End of keywordhash.h *****************************************/ +/************** Continuing where we left off in tokenize.c *******************/ + + +/* +** If X is a character that can be used in an identifier then +** IdChar(X) will be true. Otherwise it is false. +** +** For ASCII, any character with the high-order bit set is +** allowed in an identifier. For 7-bit characters, +** sqlite3IsIdChar[X] must be 1. +** +** For EBCDIC, the rules are more complex but have the same +** end result. +** +** Ticket #1066. the SQL standard does not allow '$' in the +** middle of identfiers. But many SQL implementations do. +** SQLite will allow '$' in identifiers for compatibility. +** But the feature is undocumented. +*/ +#ifdef SQLITE_ASCII +#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) +#endif +#ifdef SQLITE_EBCDIC +SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = { +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */ + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */ + 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */ + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */ +}; +#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) +#endif + + +/* +** Return the length of the token that begins at z[0]. +** Store the token type in *tokenType before returning. +*/ +SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ + int i, c; + switch( *z ){ + case ' ': case '\t': case '\n': case '\f': case '\r': { + testcase( z[0]==' ' ); + testcase( z[0]=='\t' ); + testcase( z[0]=='\n' ); + testcase( z[0]=='\f' ); + testcase( z[0]=='\r' ); + for(i=1; sqlite3Isspace(z[i]); i++){} + *tokenType = TK_SPACE; + return i; + } + case '-': { + if( z[1]=='-' ){ + for(i=2; (c=z[i])!=0 && c!='\n'; i++){} + *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ + return i; + } + *tokenType = TK_MINUS; + return 1; + } + case '(': { + *tokenType = TK_LP; + return 1; + } + case ')': { + *tokenType = TK_RP; + return 1; + } + case ';': { + *tokenType = TK_SEMI; + return 1; + } + case '+': { + *tokenType = TK_PLUS; + return 1; + } + case '*': { + *tokenType = TK_STAR; + return 1; + } + case '/': { + if( z[1]!='*' || z[2]==0 ){ + *tokenType = TK_SLASH; + return 1; + } + for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){} + if( c ) i++; + *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ + return i; + } + case '%': { + *tokenType = TK_REM; + return 1; + } + case '=': { + *tokenType = TK_EQ; + return 1 + (z[1]=='='); + } + case '<': { + if( (c=z[1])=='=' ){ + *tokenType = TK_LE; + return 2; + }else if( c=='>' ){ + *tokenType = TK_NE; + return 2; + }else if( c=='<' ){ + *tokenType = TK_LSHIFT; + return 2; + }else{ + *tokenType = TK_LT; + return 1; + } + } + case '>': { + if( (c=z[1])=='=' ){ + *tokenType = TK_GE; + return 2; + }else if( c=='>' ){ + *tokenType = TK_RSHIFT; + return 2; + }else{ + *tokenType = TK_GT; + return 1; + } + } + case '!': { + if( z[1]!='=' ){ + *tokenType = TK_ILLEGAL; + return 2; + }else{ + *tokenType = TK_NE; + return 2; + } + } + case '|': { + if( z[1]!='|' ){ + *tokenType = TK_BITOR; + return 1; + }else{ + *tokenType = TK_CONCAT; + return 2; + } + } + case ',': { + *tokenType = TK_COMMA; + return 1; + } + case '&': { + *tokenType = TK_BITAND; + return 1; + } + case '~': { + *tokenType = TK_BITNOT; + return 1; + } + case '`': + case '\'': + case '"': { + int delim = z[0]; + testcase( delim=='`' ); + testcase( delim=='\'' ); + testcase( delim=='"' ); + for(i=1; (c=z[i])!=0; i++){ + if( c==delim ){ + if( z[i+1]==delim ){ + i++; + }else{ + break; + } + } + } + if( c=='\'' ){ + *tokenType = TK_STRING; + return i+1; + }else if( c!=0 ){ + *tokenType = TK_ID; + return i+1; + }else{ + *tokenType = TK_ILLEGAL; + return i; + } + } + case '.': { +#ifndef SQLITE_OMIT_FLOATING_POINT + if( !sqlite3Isdigit(z[1]) ) +#endif + { + *tokenType = TK_DOT; + return 1; + } + /* If the next character is a digit, this is a floating point + ** number that begins with ".". Fall thru into the next case */ + } + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' ); + testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' ); + testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' ); + testcase( z[0]=='9' ); + *tokenType = TK_INTEGER; + for(i=0; sqlite3Isdigit(z[i]); i++){} +#ifndef SQLITE_OMIT_FLOATING_POINT + if( z[i]=='.' ){ + i++; + while( sqlite3Isdigit(z[i]) ){ i++; } + *tokenType = TK_FLOAT; + } + if( (z[i]=='e' || z[i]=='E') && + ( sqlite3Isdigit(z[i+1]) + || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2])) + ) + ){ + i += 2; + while( sqlite3Isdigit(z[i]) ){ i++; } + *tokenType = TK_FLOAT; + } +#endif + while( IdChar(z[i]) ){ + *tokenType = TK_ILLEGAL; + i++; + } + return i; + } + case '[': { + for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} + *tokenType = c==']' ? TK_ID : TK_ILLEGAL; + return i; + } + case '?': { + *tokenType = TK_VARIABLE; + for(i=1; sqlite3Isdigit(z[i]); i++){} + return i; + } + case '#': { + for(i=1; sqlite3Isdigit(z[i]); i++){} + if( i>1 ){ + /* Parameters of the form #NNN (where NNN is a number) are used + ** internally by sqlite3NestedParse. */ + *tokenType = TK_REGISTER; + return i; + } + /* Fall through into the next case if the '#' is not followed by + ** a digit. Try to match #AAAA where AAAA is a parameter name. */ + } +#ifndef SQLITE_OMIT_TCL_VARIABLE + case '$': +#endif + case '@': /* For compatibility with MS SQL Server */ + case ':': { + int n = 0; + testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' ); + *tokenType = TK_VARIABLE; + for(i=1; (c=z[i])!=0; i++){ + if( IdChar(c) ){ + n++; +#ifndef SQLITE_OMIT_TCL_VARIABLE + }else if( c=='(' && n>0 ){ + do{ + i++; + }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' ); + if( c==')' ){ + i++; + }else{ + *tokenType = TK_ILLEGAL; + } + break; + }else if( c==':' && z[i+1]==':' ){ + i++; +#endif + }else{ + break; + } + } + if( n==0 ) *tokenType = TK_ILLEGAL; + return i; + } +#ifndef SQLITE_OMIT_BLOB_LITERAL + case 'x': case 'X': { + testcase( z[0]=='x' ); testcase( z[0]=='X' ); + if( z[1]=='\'' ){ + *tokenType = TK_BLOB; + for(i=2; sqlite3Isxdigit(z[i]); i++){} + if( z[i]!='\'' || i%2 ){ + *tokenType = TK_ILLEGAL; + while( z[i] && z[i]!='\'' ){ i++; } + } + if( z[i] ) i++; + return i; + } + /* Otherwise fall through to the next case */ + } +#endif + default: { + if( !IdChar(*z) ){ + break; + } + for(i=1; IdChar(z[i]); i++){} + *tokenType = keywordCode((char*)z, i); + return i; + } + } + *tokenType = TK_ILLEGAL; + return 1; +} + +/* +** Run the parser on the given SQL string. The parser structure is +** passed in. An SQLITE_ status code is returned. If an error occurs +** then an and attempt is made to write an error message into +** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that +** error message. +*/ +SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){ + int nErr = 0; /* Number of errors encountered */ + int i; /* Loop counter */ + void *pEngine; /* The LEMON-generated LALR(1) parser */ + int tokenType; /* type of the next token */ + int lastTokenParsed = -1; /* type of the previous token */ + u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */ + sqlite3 *db = pParse->db; /* The database connection */ + int mxSqlLen; /* Max length of an SQL string */ + + + mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; + if( db->nVdbeActive==0 ){ + db->u1.isInterrupted = 0; + } + pParse->rc = SQLITE_OK; + pParse->zTail = zSql; + i = 0; + assert( pzErrMsg!=0 ); + pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc); + if( pEngine==0 ){ + db->mallocFailed = 1; + return SQLITE_NOMEM; + } + assert( pParse->pNewTable==0 ); + assert( pParse->pNewTrigger==0 ); + assert( pParse->nVar==0 ); + assert( pParse->nzVar==0 ); + assert( pParse->azVar==0 ); + enableLookaside = db->lookaside.bEnabled; + if( db->lookaside.pStart ) db->lookaside.bEnabled = 1; + while( !db->mallocFailed && zSql[i]!=0 ){ + assert( i>=0 ); + pParse->sLastToken.z = &zSql[i]; + pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType); + i += pParse->sLastToken.n; + if( i>mxSqlLen ){ + pParse->rc = SQLITE_TOOBIG; + break; + } + switch( tokenType ){ + case TK_SPACE: { + if( db->u1.isInterrupted ){ + sqlite3ErrorMsg(pParse, "interrupt"); + pParse->rc = SQLITE_INTERRUPT; + goto abort_parse; + } + break; + } + case TK_ILLEGAL: { + sqlite3DbFree(db, *pzErrMsg); + *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"", + &pParse->sLastToken); + nErr++; + goto abort_parse; + } + case TK_SEMI: { + pParse->zTail = &zSql[i]; + /* Fall thru into the default case */ + } + default: { + sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse); + lastTokenParsed = tokenType; + if( pParse->rc!=SQLITE_OK ){ + goto abort_parse; + } + break; + } + } + } +abort_parse: + if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){ + if( lastTokenParsed!=TK_SEMI ){ + sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse); + pParse->zTail = &zSql[i]; + } + sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse); + } +#ifdef YYTRACKMAXSTACKDEPTH + sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK, + sqlite3ParserStackPeak(pEngine) + ); +#endif /* YYDEBUG */ + sqlite3ParserFree(pEngine, sqlite3_free); + db->lookaside.bEnabled = enableLookaside; + if( db->mallocFailed ){ + pParse->rc = SQLITE_NOMEM; + } + if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){ + sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc)); + } + assert( pzErrMsg!=0 ); + if( pParse->zErrMsg ){ + *pzErrMsg = pParse->zErrMsg; + sqlite3_log(pParse->rc, "%s", *pzErrMsg); + pParse->zErrMsg = 0; + nErr++; + } + if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){ + sqlite3VdbeDelete(pParse->pVdbe); + pParse->pVdbe = 0; + } +#ifndef SQLITE_OMIT_SHARED_CACHE + if( pParse->nested==0 ){ + sqlite3DbFree(db, pParse->aTableLock); + pParse->aTableLock = 0; + pParse->nTableLock = 0; + } +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_free(pParse->apVtabLock); +#endif + + if( !IN_DECLARE_VTAB ){ + /* If the pParse->declareVtab flag is set, do not delete any table + ** structure built up in pParse->pNewTable. The calling code (see vtab.c) + ** will take responsibility for freeing the Table structure. + */ + sqlite3DeleteTable(db, pParse->pNewTable); + } + + sqlite3DeleteTrigger(db, pParse->pNewTrigger); + for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]); + sqlite3DbFree(db, pParse->azVar); + sqlite3DbFree(db, pParse->aAlias); + while( pParse->pAinc ){ + AutoincInfo *p = pParse->pAinc; + pParse->pAinc = p->pNext; + sqlite3DbFree(db, p); + } + while( pParse->pZombieTab ){ + Table *p = pParse->pZombieTab; + pParse->pZombieTab = p->pNextZombie; + sqlite3DeleteTable(db, p); + } + if( nErr>0 && pParse->rc==SQLITE_OK ){ + pParse->rc = SQLITE_ERROR; + } + return nErr; +} + +/************** End of tokenize.c ********************************************/ +/************** Begin file complete.c ****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** An tokenizer for SQL +** +** This file contains C code that implements the sqlite3_complete() API. +** This code used to be part of the tokenizer.c source file. But by +** separating it out, the code will be automatically omitted from +** static links that do not use it. +*/ +#ifndef SQLITE_OMIT_COMPLETE + +/* +** This is defined in tokenize.c. We just have to import the definition. +*/ +#ifndef SQLITE_AMALGAMATION +#ifdef SQLITE_ASCII +#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) +#endif +#ifdef SQLITE_EBCDIC +SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[]; +#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) +#endif +#endif /* SQLITE_AMALGAMATION */ + + +/* +** Token types used by the sqlite3_complete() routine. See the header +** comments on that procedure for additional information. +*/ +#define tkSEMI 0 +#define tkWS 1 +#define tkOTHER 2 +#ifndef SQLITE_OMIT_TRIGGER +#define tkEXPLAIN 3 +#define tkCREATE 4 +#define tkTEMP 5 +#define tkTRIGGER 6 +#define tkEND 7 +#endif + +/* +** Return TRUE if the given SQL string ends in a semicolon. +** +** Special handling is require for CREATE TRIGGER statements. +** Whenever the CREATE TRIGGER keywords are seen, the statement +** must end with ";END;". +** +** This implementation uses a state machine with 8 states: +** +** (0) INVALID We have not yet seen a non-whitespace character. +** +** (1) START At the beginning or end of an SQL statement. This routine +** returns 1 if it ends in the START state and 0 if it ends +** in any other state. +** +** (2) NORMAL We are in the middle of statement which ends with a single +** semicolon. +** +** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of +** a statement. +** +** (4) CREATE The keyword CREATE has been seen at the beginning of a +** statement, possibly preceeded by EXPLAIN and/or followed by +** TEMP or TEMPORARY +** +** (5) TRIGGER We are in the middle of a trigger definition that must be +** ended by a semicolon, the keyword END, and another semicolon. +** +** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at +** the end of a trigger definition. +** +** (7) END We've seen the ";END" of the ";END;" that occurs at the end +** of a trigger difinition. +** +** Transitions between states above are determined by tokens extracted +** from the input. The following tokens are significant: +** +** (0) tkSEMI A semicolon. +** (1) tkWS Whitespace. +** (2) tkOTHER Any other SQL token. +** (3) tkEXPLAIN The "explain" keyword. +** (4) tkCREATE The "create" keyword. +** (5) tkTEMP The "temp" or "temporary" keyword. +** (6) tkTRIGGER The "trigger" keyword. +** (7) tkEND The "end" keyword. +** +** Whitespace never causes a state transition and is always ignored. +** This means that a SQL string of all whitespace is invalid. +** +** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed +** to recognize the end of a trigger can be omitted. All we have to do +** is look for a semicolon that is not part of an string or comment. +*/ +SQLITE_API int sqlite3_complete(const char *zSql){ + u8 state = 0; /* Current state, using numbers defined in header comment */ + u8 token; /* Value of the next token */ + +#ifndef SQLITE_OMIT_TRIGGER + /* A complex statement machine used to detect the end of a CREATE TRIGGER + ** statement. This is the normal case. + */ + static const u8 trans[8][8] = { + /* Token: */ + /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ + /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, }, + /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, }, + /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, }, + /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, }, + /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, }, + /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, }, + /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, }, + /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, }, + }; +#else + /* If triggers are not supported by this compile then the statement machine + ** used to detect the end of a statement is much simplier + */ + static const u8 trans[3][3] = { + /* Token: */ + /* State: ** SEMI WS OTHER */ + /* 0 INVALID: */ { 1, 0, 2, }, + /* 1 START: */ { 1, 1, 2, }, + /* 2 NORMAL: */ { 1, 2, 2, }, + }; +#endif /* SQLITE_OMIT_TRIGGER */ + + while( *zSql ){ + switch( *zSql ){ + case ';': { /* A semicolon */ + token = tkSEMI; + break; + } + case ' ': + case '\r': + case '\t': + case '\n': + case '\f': { /* White space is ignored */ + token = tkWS; + break; + } + case '/': { /* C-style comments */ + if( zSql[1]!='*' ){ + token = tkOTHER; + break; + } + zSql += 2; + while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; } + if( zSql[0]==0 ) return 0; + zSql++; + token = tkWS; + break; + } + case '-': { /* SQL-style comments from "--" to end of line */ + if( zSql[1]!='-' ){ + token = tkOTHER; + break; + } + while( *zSql && *zSql!='\n' ){ zSql++; } + if( *zSql==0 ) return state==1; + token = tkWS; + break; + } + case '[': { /* Microsoft-style identifiers in [...] */ + zSql++; + while( *zSql && *zSql!=']' ){ zSql++; } + if( *zSql==0 ) return 0; + token = tkOTHER; + break; + } + case '`': /* Grave-accent quoted symbols used by MySQL */ + case '"': /* single- and double-quoted strings */ + case '\'': { + int c = *zSql; + zSql++; + while( *zSql && *zSql!=c ){ zSql++; } + if( *zSql==0 ) return 0; + token = tkOTHER; + break; + } + default: { +#ifdef SQLITE_EBCDIC + unsigned char c; +#endif + if( IdChar((u8)*zSql) ){ + /* Keywords and unquoted identifiers */ + int nId; + for(nId=1; IdChar(zSql[nId]); nId++){} +#ifdef SQLITE_OMIT_TRIGGER + token = tkOTHER; +#else + switch( *zSql ){ + case 'c': case 'C': { + if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){ + token = tkCREATE; + }else{ + token = tkOTHER; + } + break; + } + case 't': case 'T': { + if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){ + token = tkTRIGGER; + }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){ + token = tkTEMP; + }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){ + token = tkTEMP; + }else{ + token = tkOTHER; + } + break; + } + case 'e': case 'E': { + if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){ + token = tkEND; + }else +#ifndef SQLITE_OMIT_EXPLAIN + if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){ + token = tkEXPLAIN; + }else +#endif + { + token = tkOTHER; + } + break; + } + default: { + token = tkOTHER; + break; + } + } +#endif /* SQLITE_OMIT_TRIGGER */ + zSql += nId-1; + }else{ + /* Operators and special symbols */ + token = tkOTHER; + } + break; + } + } + state = trans[state][token]; + zSql++; + } + return state==1; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** This routine is the same as the sqlite3_complete() routine described +** above, except that the parameter is required to be UTF-16 encoded, not +** UTF-8. +*/ +SQLITE_API int sqlite3_complete16(const void *zSql){ + sqlite3_value *pVal; + char const *zSql8; + int rc = SQLITE_NOMEM; + +#ifndef SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if( rc ) return rc; +#endif + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); + zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); + if( zSql8 ){ + rc = sqlite3_complete(zSql8); + }else{ + rc = SQLITE_NOMEM; + } + sqlite3ValueFree(pVal); + return sqlite3ApiExit(0, rc); +} +#endif /* SQLITE_OMIT_UTF16 */ +#endif /* SQLITE_OMIT_COMPLETE */ + +/************** End of complete.c ********************************************/ +/************** Begin file main.c ********************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Main file for the SQLite library. The routines in this file +** implement the programmer interface to the library. Routines in +** other files are for internal use by SQLite and should not be +** accessed by users of the library. +*/ + +#ifdef SQLITE_ENABLE_FTS3 +/************** Include fts3.h in the middle of main.c ***********************/ +/************** Begin file fts3.h ********************************************/ +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file is used by programs that want to link against the +** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. +*/ + +#if 0 +extern "C" { +#endif /* __cplusplus */ + +SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db); + +#if 0 +} /* extern "C" */ +#endif /* __cplusplus */ + +/************** End of fts3.h ************************************************/ +/************** Continuing where we left off in main.c ***********************/ +#endif +#ifdef SQLITE_ENABLE_RTREE +/************** Include rtree.h in the middle of main.c **********************/ +/************** Begin file rtree.h *******************************************/ +/* +** 2008 May 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file is used by programs that want to link against the +** RTREE library. All it does is declare the sqlite3RtreeInit() interface. +*/ + +#if 0 +extern "C" { +#endif /* __cplusplus */ + +SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); + +#if 0 +} /* extern "C" */ +#endif /* __cplusplus */ + +/************** End of rtree.h ***********************************************/ +/************** Continuing where we left off in main.c ***********************/ +#endif +#ifdef SQLITE_ENABLE_ICU +/************** Include sqliteicu.h in the middle of main.c ******************/ +/************** Begin file sqliteicu.h ***************************************/ +/* +** 2008 May 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file is used by programs that want to link against the +** ICU extension. All it does is declare the sqlite3IcuInit() interface. +*/ + +#if 0 +extern "C" { +#endif /* __cplusplus */ + +SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db); + +#if 0 +} /* extern "C" */ +#endif /* __cplusplus */ + + +/************** End of sqliteicu.h *******************************************/ +/************** Continuing where we left off in main.c ***********************/ +#endif + +#ifndef SQLITE_AMALGAMATION +/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant +** contains the text of SQLITE_VERSION macro. +*/ +SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; +#endif + +/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns +** a pointer to the to the sqlite3_version[] string constant. +*/ +SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; } + +/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a +** pointer to a string constant whose value is the same as the +** SQLITE_SOURCE_ID C preprocessor macro. +*/ +SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } + +/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function +** returns an integer equal to SQLITE_VERSION_NUMBER. +*/ +SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } + +/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns +** zero if and only if SQLite was compiled with mutexing code omitted due to +** the SQLITE_THREADSAFE compile-time option being set to 0. +*/ +SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } + +#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) +/* +** If the following function pointer is not NULL and if +** SQLITE_ENABLE_IOTRACE is enabled, then messages describing +** I/O active are written using this function. These messages +** are intended for debugging activity only. +*/ +SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0; +#endif + +/* +** If the following global variable points to a string which is the +** name of a directory, then that directory will be used to store +** temporary files. +** +** See also the "PRAGMA temp_store_directory" SQL command. +*/ +SQLITE_API char *sqlite3_temp_directory = 0; + +/* +** If the following global variable points to a string which is the +** name of a directory, then that directory will be used to store +** all database files specified with a relative pathname. +** +** See also the "PRAGMA data_store_directory" SQL command. +*/ +SQLITE_API char *sqlite3_data_directory = 0; + +/* +** Initialize SQLite. +** +** This routine must be called to initialize the memory allocation, +** VFS, and mutex subsystems prior to doing any serious work with +** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT +** this routine will be called automatically by key routines such as +** sqlite3_open(). +** +** This routine is a no-op except on its very first call for the process, +** or for the first call after a call to sqlite3_shutdown. +** +** The first thread to call this routine runs the initialization to +** completion. If subsequent threads call this routine before the first +** thread has finished the initialization process, then the subsequent +** threads must block until the first thread finishes with the initialization. +** +** The first thread might call this routine recursively. Recursive +** calls to this routine should not block, of course. Otherwise the +** initialization process would never complete. +** +** Let X be the first thread to enter this routine. Let Y be some other +** thread. Then while the initial invocation of this routine by X is +** incomplete, it is required that: +** +** * Calls to this routine from Y must block until the outer-most +** call by X completes. +** +** * Recursive calls to this routine from thread X return immediately +** without blocking. +*/ +SQLITE_API int sqlite3_initialize(void){ + MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ + int rc; /* Result code */ +#ifdef SQLITE_EXTRA_INIT + int bRunExtraInit = 0; /* Extra initialization needed */ +#endif + +#ifdef SQLITE_OMIT_WSD + rc = sqlite3_wsd_init(4096, 24); + if( rc!=SQLITE_OK ){ + return rc; + } +#endif + + /* If SQLite is already completely initialized, then this call + ** to sqlite3_initialize() should be a no-op. But the initialization + ** must be complete. So isInit must not be set until the very end + ** of this routine. + */ + if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; + +#ifdef SQLITE_ENABLE_SQLLOG + { + extern void sqlite3_init_sqllog(void); + sqlite3_init_sqllog(); + } +#endif + + /* Make sure the mutex subsystem is initialized. If unable to + ** initialize the mutex subsystem, return early with the error. + ** If the system is so sick that we are unable to allocate a mutex, + ** there is not much SQLite is going to be able to do. + ** + ** The mutex subsystem must take care of serializing its own + ** initialization. + */ + rc = sqlite3MutexInit(); + if( rc ) return rc; + + /* Initialize the malloc() system and the recursive pInitMutex mutex. + ** This operation is protected by the STATIC_MASTER mutex. Note that + ** MutexAlloc() is called for a static mutex prior to initializing the + ** malloc subsystem - this implies that the allocation of a static + ** mutex must not require support from the malloc subsystem. + */ + MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + sqlite3_mutex_enter(pMaster); + sqlite3GlobalConfig.isMutexInit = 1; + if( !sqlite3GlobalConfig.isMallocInit ){ + rc = sqlite3MallocInit(); + } + if( rc==SQLITE_OK ){ + sqlite3GlobalConfig.isMallocInit = 1; + if( !sqlite3GlobalConfig.pInitMutex ){ + sqlite3GlobalConfig.pInitMutex = + sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); + if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ + rc = SQLITE_NOMEM; + } + } + } + if( rc==SQLITE_OK ){ + sqlite3GlobalConfig.nRefInitMutex++; + } + sqlite3_mutex_leave(pMaster); + + /* If rc is not SQLITE_OK at this point, then either the malloc + ** subsystem could not be initialized or the system failed to allocate + ** the pInitMutex mutex. Return an error in either case. */ + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Do the rest of the initialization under the recursive mutex so + ** that we will be able to handle recursive calls into + ** sqlite3_initialize(). The recursive calls normally come through + ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other + ** recursive calls might also be possible. + ** + ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls + ** to the xInit method, so the xInit method need not be threadsafe. + ** + ** The following mutex is what serializes access to the appdef pcache xInit + ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the + ** call to sqlite3PcacheInitialize(). + */ + sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); + if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + sqlite3GlobalConfig.inProgress = 1; + memset(pHash, 0, sizeof(sqlite3GlobalFunctions)); + sqlite3RegisterGlobalFunctions(); + if( sqlite3GlobalConfig.isPCacheInit==0 ){ + rc = sqlite3PcacheInitialize(); + } + if( rc==SQLITE_OK ){ + sqlite3GlobalConfig.isPCacheInit = 1; + rc = sqlite3OsInit(); + } + if( rc==SQLITE_OK ){ + sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, + sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); + sqlite3GlobalConfig.isInit = 1; +#ifdef SQLITE_EXTRA_INIT + bRunExtraInit = 1; +#endif + } + sqlite3GlobalConfig.inProgress = 0; + } + sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); + + /* Go back under the static mutex and clean up the recursive + ** mutex to prevent a resource leak. + */ + sqlite3_mutex_enter(pMaster); + sqlite3GlobalConfig.nRefInitMutex--; + if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ + assert( sqlite3GlobalConfig.nRefInitMutex==0 ); + sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); + sqlite3GlobalConfig.pInitMutex = 0; + } + sqlite3_mutex_leave(pMaster); + + /* The following is just a sanity check to make sure SQLite has + ** been compiled correctly. It is important to run this code, but + ** we don't want to run it too often and soak up CPU cycles for no + ** reason. So we run it once during initialization. + */ +#ifndef NDEBUG +#ifndef SQLITE_OMIT_FLOATING_POINT + /* This section of code's only "output" is via assert() statements. */ + if ( rc==SQLITE_OK ){ + u64 x = (((u64)1)<<63)-1; + double y; + assert(sizeof(x)==8); + assert(sizeof(x)==sizeof(y)); + memcpy(&y, &x, 8); + assert( sqlite3IsNaN(y) ); + } +#endif +#endif + + /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT + ** compile-time option. + */ +#ifdef SQLITE_EXTRA_INIT + if( bRunExtraInit ){ + int SQLITE_EXTRA_INIT(const char*); + rc = SQLITE_EXTRA_INIT(0); + } +#endif + + return rc; +} + +/* +** Undo the effects of sqlite3_initialize(). Must not be called while +** there are outstanding database connections or memory allocations or +** while any part of SQLite is otherwise in use in any thread. This +** routine is not threadsafe. But it is safe to invoke this routine +** on when SQLite is already shut down. If SQLite is already shut down +** when this routine is invoked, then this routine is a harmless no-op. +*/ +SQLITE_API int sqlite3_shutdown(void){ + if( sqlite3GlobalConfig.isInit ){ +#ifdef SQLITE_EXTRA_SHUTDOWN + void SQLITE_EXTRA_SHUTDOWN(void); + SQLITE_EXTRA_SHUTDOWN(); +#endif + sqlite3_os_end(); + sqlite3_reset_auto_extension(); + sqlite3GlobalConfig.isInit = 0; + } + if( sqlite3GlobalConfig.isPCacheInit ){ + sqlite3PcacheShutdown(); + sqlite3GlobalConfig.isPCacheInit = 0; + } + if( sqlite3GlobalConfig.isMallocInit ){ + sqlite3MallocEnd(); + sqlite3GlobalConfig.isMallocInit = 0; + +#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES + /* The heap subsystem has now been shutdown and these values are supposed + ** to be NULL or point to memory that was obtained from sqlite3_malloc(), + ** which would rely on that heap subsystem; therefore, make sure these + ** values cannot refer to heap memory that was just invalidated when the + ** heap subsystem was shutdown. This is only done if the current call to + ** this function resulted in the heap subsystem actually being shutdown. + */ + sqlite3_data_directory = 0; + sqlite3_temp_directory = 0; +#endif + } + if( sqlite3GlobalConfig.isMutexInit ){ + sqlite3MutexEnd(); + sqlite3GlobalConfig.isMutexInit = 0; + } + + return SQLITE_OK; +} + +/* +** This API allows applications to modify the global configuration of +** the SQLite library at run-time. +** +** This routine should only be called when there are no outstanding +** database connections or memory allocations. This routine is not +** threadsafe. Failure to heed these warnings can lead to unpredictable +** behavior. +*/ +SQLITE_API int sqlite3_config(int op, ...){ + va_list ap; + int rc = SQLITE_OK; + + /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while + ** the SQLite library is in use. */ + if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; + + va_start(ap, op); + switch( op ){ + + /* Mutex configuration options are only available in a threadsafe + ** compile. + */ +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 + case SQLITE_CONFIG_SINGLETHREAD: { + /* Disable all mutexing */ + sqlite3GlobalConfig.bCoreMutex = 0; + sqlite3GlobalConfig.bFullMutex = 0; + break; + } + case SQLITE_CONFIG_MULTITHREAD: { + /* Disable mutexing of database connections */ + /* Enable mutexing of core data structures */ + sqlite3GlobalConfig.bCoreMutex = 1; + sqlite3GlobalConfig.bFullMutex = 0; + break; + } + case SQLITE_CONFIG_SERIALIZED: { + /* Enable all mutexing */ + sqlite3GlobalConfig.bCoreMutex = 1; + sqlite3GlobalConfig.bFullMutex = 1; + break; + } + case SQLITE_CONFIG_MUTEX: { + /* Specify an alternative mutex implementation */ + sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); + break; + } + case SQLITE_CONFIG_GETMUTEX: { + /* Retrieve the current mutex implementation */ + *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; + break; + } +#endif + + + case SQLITE_CONFIG_MALLOC: { + /* Specify an alternative malloc implementation */ + sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); + break; + } + case SQLITE_CONFIG_GETMALLOC: { + /* Retrieve the current malloc() implementation */ + if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); + *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; + break; + } + case SQLITE_CONFIG_MEMSTATUS: { + /* Enable or disable the malloc status collection */ + sqlite3GlobalConfig.bMemstat = va_arg(ap, int); + break; + } + case SQLITE_CONFIG_SCRATCH: { + /* Designate a buffer for scratch memory space */ + sqlite3GlobalConfig.pScratch = va_arg(ap, void*); + sqlite3GlobalConfig.szScratch = va_arg(ap, int); + sqlite3GlobalConfig.nScratch = va_arg(ap, int); + break; + } + case SQLITE_CONFIG_PAGECACHE: { + /* Designate a buffer for page cache memory space */ + sqlite3GlobalConfig.pPage = va_arg(ap, void*); + sqlite3GlobalConfig.szPage = va_arg(ap, int); + sqlite3GlobalConfig.nPage = va_arg(ap, int); + break; + } + + case SQLITE_CONFIG_PCACHE: { + /* no-op */ + break; + } + case SQLITE_CONFIG_GETPCACHE: { + /* now an error */ + rc = SQLITE_ERROR; + break; + } + + case SQLITE_CONFIG_PCACHE2: { + /* Specify an alternative page cache implementation */ + sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); + break; + } + case SQLITE_CONFIG_GETPCACHE2: { + if( sqlite3GlobalConfig.pcache2.xInit==0 ){ + sqlite3PCacheSetDefault(); + } + *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; + break; + } + +#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) + case SQLITE_CONFIG_HEAP: { + /* Designate a buffer for heap memory space */ + sqlite3GlobalConfig.pHeap = va_arg(ap, void*); + sqlite3GlobalConfig.nHeap = va_arg(ap, int); + sqlite3GlobalConfig.mnReq = va_arg(ap, int); + + if( sqlite3GlobalConfig.mnReq<1 ){ + sqlite3GlobalConfig.mnReq = 1; + }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ + /* cap min request size at 2^12 */ + sqlite3GlobalConfig.mnReq = (1<<12); + } + + if( sqlite3GlobalConfig.pHeap==0 ){ + /* If the heap pointer is NULL, then restore the malloc implementation + ** back to NULL pointers too. This will cause the malloc to go + ** back to its default implementation when sqlite3_initialize() is + ** run. + */ + memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); + }else{ + /* The heap pointer is not NULL, then install one of the + ** mem5.c/mem3.c methods. The enclosing #if guarantees at + ** least one of these methods is currently enabled. + */ +#ifdef SQLITE_ENABLE_MEMSYS3 + sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); +#endif +#ifdef SQLITE_ENABLE_MEMSYS5 + sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); +#endif + } + break; + } +#endif + + case SQLITE_CONFIG_LOOKASIDE: { + sqlite3GlobalConfig.szLookaside = va_arg(ap, int); + sqlite3GlobalConfig.nLookaside = va_arg(ap, int); + break; + } + + /* Record a pointer to the logger function and its first argument. + ** The default is NULL. Logging is disabled if the function pointer is + ** NULL. + */ + case SQLITE_CONFIG_LOG: { + /* MSVC is picky about pulling func ptrs from va lists. + ** http://support.microsoft.com/kb/47961 + ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); + */ + typedef void(*LOGFUNC_t)(void*,int,const char*); + sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); + sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); + break; + } + + case SQLITE_CONFIG_URI: { + sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); + break; + } + + case SQLITE_CONFIG_COVERING_INDEX_SCAN: { + sqlite3GlobalConfig.bUseCis = va_arg(ap, int); + break; + } + +#ifdef SQLITE_ENABLE_SQLLOG + case SQLITE_CONFIG_SQLLOG: { + typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); + sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); + sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); + break; + } +#endif + + case SQLITE_CONFIG_MMAP_SIZE: { + sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); + sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); + if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){ + mxMmap = SQLITE_MAX_MMAP_SIZE; + } + sqlite3GlobalConfig.mxMmap = mxMmap; + if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; + if( szMmap>mxMmap) szMmap = mxMmap; + sqlite3GlobalConfig.szMmap = szMmap; + break; + } + + default: { + rc = SQLITE_ERROR; + break; + } + } + va_end(ap); + return rc; +} + +/* +** Set up the lookaside buffers for a database connection. +** Return SQLITE_OK on success. +** If lookaside is already active, return SQLITE_BUSY. +** +** The sz parameter is the number of bytes in each lookaside slot. +** The cnt parameter is the number of slots. If pStart is NULL the +** space for the lookaside memory is obtained from sqlite3_malloc(). +** If pStart is not NULL then it is sz*cnt bytes of memory to use for +** the lookaside memory. +*/ +static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ + void *pStart; + if( db->lookaside.nOut ){ + return SQLITE_BUSY; + } + /* Free any existing lookaside buffer for this handle before + ** allocating a new one so we don't have to have space for + ** both at the same time. + */ + if( db->lookaside.bMalloced ){ + sqlite3_free(db->lookaside.pStart); + } + /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger + ** than a pointer to be useful. + */ + sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ + if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; + if( cnt<0 ) cnt = 0; + if( sz==0 || cnt==0 ){ + sz = 0; + pStart = 0; + }else if( pBuf==0 ){ + sqlite3BeginBenignMalloc(); + pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ + sqlite3EndBenignMalloc(); + if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; + }else{ + pStart = pBuf; + } + db->lookaside.pStart = pStart; + db->lookaside.pFree = 0; + db->lookaside.sz = (u16)sz; + if( pStart ){ + int i; + LookasideSlot *p; + assert( sz > (int)sizeof(LookasideSlot*) ); + p = (LookasideSlot*)pStart; + for(i=cnt-1; i>=0; i--){ + p->pNext = db->lookaside.pFree; + db->lookaside.pFree = p; + p = (LookasideSlot*)&((u8*)p)[sz]; + } + db->lookaside.pEnd = p; + db->lookaside.bEnabled = 1; + db->lookaside.bMalloced = pBuf==0 ?1:0; + }else{ + db->lookaside.pEnd = 0; + db->lookaside.bEnabled = 0; + db->lookaside.bMalloced = 0; + } + return SQLITE_OK; +} + +/* +** Return the mutex associated with a database connection. +*/ +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ + return db->mutex; +} + +/* +** Free up as much memory as we can from the given database +** connection. +*/ +SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){ + int i; + sqlite3_mutex_enter(db->mutex); + sqlite3BtreeEnterAll(db); + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + Pager *pPager = sqlite3BtreePager(pBt); + sqlite3PagerShrink(pPager); + } + } + sqlite3BtreeLeaveAll(db); + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +/* +** Configuration settings for an individual database connection +*/ +SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ + va_list ap; + int rc; + va_start(ap, op); + switch( op ){ + case SQLITE_DBCONFIG_LOOKASIDE: { + void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */ + int sz = va_arg(ap, int); /* IMP: R-47871-25994 */ + int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */ + rc = setupLookaside(db, pBuf, sz, cnt); + break; + } + default: { + static const struct { + int op; /* The opcode */ + u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ + } aFlagOp[] = { + { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, + { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, + }; + unsigned int i; + rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ + for(i=0; iflags; + if( onoff>0 ){ + db->flags |= aFlagOp[i].mask; + }else if( onoff==0 ){ + db->flags &= ~aFlagOp[i].mask; + } + if( oldFlags!=db->flags ){ + sqlite3ExpirePreparedStatements(db); + } + if( pRes ){ + *pRes = (db->flags & aFlagOp[i].mask)!=0; + } + rc = SQLITE_OK; + break; + } + } + break; + } + } + va_end(ap); + return rc; +} + + +/* +** Return true if the buffer z[0..n-1] contains all spaces. +*/ +static int allSpaces(const char *z, int n){ + while( n>0 && z[n-1]==' ' ){ n--; } + return n==0; +} + +/* +** This is the default collating function named "BINARY" which is always +** available. +** +** If the padFlag argument is not NULL then space padding at the end +** of strings is ignored. This implements the RTRIM collation. +*/ +static int binCollFunc( + void *padFlag, + int nKey1, const void *pKey1, + int nKey2, const void *pKey2 +){ + int rc, n; + n = nKey1lastRowid; +} + +/* +** Return the number of changes in the most recent call to sqlite3_exec(). +*/ +SQLITE_API int sqlite3_changes(sqlite3 *db){ + return db->nChange; +} + +/* +** Return the number of changes since the database handle was opened. +*/ +SQLITE_API int sqlite3_total_changes(sqlite3 *db){ + return db->nTotalChange; +} + +/* +** Close all open savepoints. This function only manipulates fields of the +** database handle object, it does not close any savepoints that may be open +** at the b-tree/pager level. +*/ +SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){ + while( db->pSavepoint ){ + Savepoint *pTmp = db->pSavepoint; + db->pSavepoint = pTmp->pNext; + sqlite3DbFree(db, pTmp); + } + db->nSavepoint = 0; + db->nStatement = 0; + db->isTransactionSavepoint = 0; +} + +/* +** Invoke the destructor function associated with FuncDef p, if any. Except, +** if this is not the last copy of the function, do not invoke it. Multiple +** copies of a single function are created when create_function() is called +** with SQLITE_ANY as the encoding. +*/ +static void functionDestroy(sqlite3 *db, FuncDef *p){ + FuncDestructor *pDestructor = p->pDestructor; + if( pDestructor ){ + pDestructor->nRef--; + if( pDestructor->nRef==0 ){ + pDestructor->xDestroy(pDestructor->pUserData); + sqlite3DbFree(db, pDestructor); + } + } +} + +/* +** Disconnect all sqlite3_vtab objects that belong to database connection +** db. This is called when db is being closed. +*/ +static void disconnectAllVtab(sqlite3 *db){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + int i; + sqlite3BtreeEnterAll(db); + for(i=0; inDb; i++){ + Schema *pSchema = db->aDb[i].pSchema; + if( db->aDb[i].pSchema ){ + HashElem *p; + for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ + Table *pTab = (Table *)sqliteHashData(p); + if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); + } + } + } + sqlite3BtreeLeaveAll(db); +#else + UNUSED_PARAMETER(db); +#endif +} + +/* +** Return TRUE if database connection db has unfinalized prepared +** statements or unfinished sqlite3_backup objects. +*/ +static int connectionIsBusy(sqlite3 *db){ + int j; + assert( sqlite3_mutex_held(db->mutex) ); + if( db->pVdbe ) return 1; + for(j=0; jnDb; j++){ + Btree *pBt = db->aDb[j].pBt; + if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; + } + return 0; +} + +/* +** Close an existing SQLite database +*/ +static int sqlite3Close(sqlite3 *db, int forceZombie){ + if( !db ){ + return SQLITE_OK; + } + if( !sqlite3SafetyCheckSickOrOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + sqlite3_mutex_enter(db->mutex); + + /* Force xDisconnect calls on all virtual tables */ + disconnectAllVtab(db); + + /* If a transaction is open, the disconnectAllVtab() call above + ** will not have called the xDisconnect() method on any virtual + ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() + ** call will do so. We need to do this before the check for active + ** SQL statements below, as the v-table implementation may be storing + ** some prepared statements internally. + */ + sqlite3VtabRollback(db); + + /* Legacy behavior (sqlite3_close() behavior) is to return + ** SQLITE_BUSY if the connection can not be closed immediately. + */ + if( !forceZombie && connectionIsBusy(db) ){ + sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized " + "statements or unfinished backups"); + sqlite3_mutex_leave(db->mutex); + return SQLITE_BUSY; + } + +#ifdef SQLITE_ENABLE_SQLLOG + if( sqlite3GlobalConfig.xSqllog ){ + /* Closing the handle. Fourth parameter is passed the value 2. */ + sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); + } +#endif + + /* Convert the connection into a zombie and then close it. + */ + db->magic = SQLITE_MAGIC_ZOMBIE; + sqlite3LeaveMutexAndCloseZombie(db); + return SQLITE_OK; +} + +/* +** Two variations on the public interface for closing a database +** connection. The sqlite3_close() version returns SQLITE_BUSY and +** leaves the connection option if there are unfinalized prepared +** statements or unfinished sqlite3_backups. The sqlite3_close_v2() +** version forces the connection to become a zombie if there are +** unclosed resources, and arranges for deallocation when the last +** prepare statement or sqlite3_backup closes. +*/ +SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } +SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } + + +/* +** Close the mutex on database connection db. +** +** Furthermore, if database connection db is a zombie (meaning that there +** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and +** every sqlite3_stmt has now been finalized and every sqlite3_backup has +** finished, then free all resources. +*/ +SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ + HashElem *i; /* Hash table iterator */ + int j; + + /* If there are outstanding sqlite3_stmt or sqlite3_backup objects + ** or if the connection has not yet been closed by sqlite3_close_v2(), + ** then just leave the mutex and return. + */ + if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ + sqlite3_mutex_leave(db->mutex); + return; + } + + /* If we reach this point, it means that the database connection has + ** closed all sqlite3_stmt and sqlite3_backup objects and has been + ** passed to sqlite3_close (meaning that it is a zombie). Therefore, + ** go ahead and free all resources. + */ + + /* If a transaction is open, roll it back. This also ensures that if + ** any database schemas have been modified by an uncommitted transaction + ** they are reset. And that the required b-tree mutex is held to make + ** the pager rollback and schema reset an atomic operation. */ + sqlite3RollbackAll(db, SQLITE_OK); + + /* Free any outstanding Savepoint structures. */ + sqlite3CloseSavepoints(db); + + /* Close all database connections */ + for(j=0; jnDb; j++){ + struct Db *pDb = &db->aDb[j]; + if( pDb->pBt ){ + sqlite3BtreeClose(pDb->pBt); + pDb->pBt = 0; + if( j!=1 ){ + pDb->pSchema = 0; + } + } + } + /* Clear the TEMP schema separately and last */ + if( db->aDb[1].pSchema ){ + sqlite3SchemaClear(db->aDb[1].pSchema); + } + sqlite3VtabUnlockList(db); + + /* Free up the array of auxiliary databases */ + sqlite3CollapseDatabaseArray(db); + assert( db->nDb<=2 ); + assert( db->aDb==db->aDbStatic ); + + /* Tell the code in notify.c that the connection no longer holds any + ** locks and does not require any further unlock-notify callbacks. + */ + sqlite3ConnectionClosed(db); + + for(j=0; jaFunc.a); j++){ + FuncDef *pNext, *pHash, *p; + for(p=db->aFunc.a[j]; p; p=pHash){ + pHash = p->pHash; + while( p ){ + functionDestroy(db, p); + pNext = p->pNext; + sqlite3DbFree(db, p); + p = pNext; + } + } + } + for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ + CollSeq *pColl = (CollSeq *)sqliteHashData(i); + /* Invoke any destructors registered for collation sequence user data. */ + for(j=0; j<3; j++){ + if( pColl[j].xDel ){ + pColl[j].xDel(pColl[j].pUser); + } + } + sqlite3DbFree(db, pColl); + } + sqlite3HashClear(&db->aCollSeq); +#ifndef SQLITE_OMIT_VIRTUALTABLE + for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ + Module *pMod = (Module *)sqliteHashData(i); + if( pMod->xDestroy ){ + pMod->xDestroy(pMod->pAux); + } + sqlite3DbFree(db, pMod); + } + sqlite3HashClear(&db->aModule); +#endif + + sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */ + if( db->pErr ){ + sqlite3ValueFree(db->pErr); + } + sqlite3CloseExtensions(db); + + db->magic = SQLITE_MAGIC_ERROR; + + /* The temp-database schema is allocated differently from the other schema + ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). + ** So it needs to be freed here. Todo: Why not roll the temp schema into + ** the same sqliteMalloc() as the one that allocates the database + ** structure? + */ + sqlite3DbFree(db, db->aDb[1].pSchema); + sqlite3_mutex_leave(db->mutex); + db->magic = SQLITE_MAGIC_CLOSED; + sqlite3_mutex_free(db->mutex); + assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ + if( db->lookaside.bMalloced ){ + sqlite3_free(db->lookaside.pStart); + } + sqlite3_free(db); +} + +/* +** Rollback all database files. If tripCode is not SQLITE_OK, then +** any open cursors are invalidated ("tripped" - as in "tripping a circuit +** breaker") and made to return tripCode if there are any further +** attempts to use that cursor. +*/ +SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){ + int i; + int inTrans = 0; + assert( sqlite3_mutex_held(db->mutex) ); + sqlite3BeginBenignMalloc(); + + /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). + ** This is important in case the transaction being rolled back has + ** modified the database schema. If the b-tree mutexes are not taken + ** here, then another shared-cache connection might sneak in between + ** the database rollback and schema reset, which can cause false + ** corruption reports in some cases. */ + sqlite3BtreeEnterAll(db); + + for(i=0; inDb; i++){ + Btree *p = db->aDb[i].pBt; + if( p ){ + if( sqlite3BtreeIsInTrans(p) ){ + inTrans = 1; + } + sqlite3BtreeRollback(p, tripCode); + } + } + sqlite3VtabRollback(db); + sqlite3EndBenignMalloc(); + + if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){ + sqlite3ExpirePreparedStatements(db); + sqlite3ResetAllSchemasOfConnection(db); + } + sqlite3BtreeLeaveAll(db); + + /* Any deferred constraint violations have now been resolved. */ + db->nDeferredCons = 0; + db->nDeferredImmCons = 0; + db->flags &= ~SQLITE_DeferFKs; + + /* If one has been configured, invoke the rollback-hook callback */ + if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ + db->xRollbackCallback(db->pRollbackArg); + } +} + +/* +** Return a static string containing the name corresponding to the error code +** specified in the argument. +*/ +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \ + defined(SQLITE_DEBUG_OS_TRACE) +SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ + const char *zName = 0; + int i, origRc = rc; + for(i=0; i<2 && zName==0; i++, rc &= 0xff){ + switch( rc ){ + case SQLITE_OK: zName = "SQLITE_OK"; break; + case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; + case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; + case SQLITE_PERM: zName = "SQLITE_PERM"; break; + case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; + case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break; + case SQLITE_BUSY: zName = "SQLITE_BUSY"; break; + case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break; + case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break; + case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break; + case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break; + case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; + case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; + case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; + case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break; + case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; + case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; + case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; + case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; + case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break; + case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break; + case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break; + case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break; + case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break; + case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break; + case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break; + case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break; + case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break; + case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break; + case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break; + case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break; + case SQLITE_IOERR_CHECKRESERVEDLOCK: + zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; + case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break; + case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break; + case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break; + case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break; + case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break; + case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break; + case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break; + case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break; + case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break; + case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break; + case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break; + case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break; + case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break; + case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break; + case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break; + case SQLITE_FULL: zName = "SQLITE_FULL"; break; + case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break; + case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break; + case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; + case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; + case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; + case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; + case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; + case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; + case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break; + case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break; + case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break; + case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break; + case SQLITE_CONSTRAINT_FOREIGNKEY: + zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break; + case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break; + case SQLITE_CONSTRAINT_PRIMARYKEY: + zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break; + case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break; + case SQLITE_CONSTRAINT_COMMITHOOK: + zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break; + case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; + case SQLITE_CONSTRAINT_FUNCTION: + zName = "SQLITE_CONSTRAINT_FUNCTION"; break; + case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; + case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; + case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; + case SQLITE_AUTH: zName = "SQLITE_AUTH"; break; + case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break; + case SQLITE_RANGE: zName = "SQLITE_RANGE"; break; + case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break; + case SQLITE_ROW: zName = "SQLITE_ROW"; break; + case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break; + case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break; + case SQLITE_NOTICE_RECOVER_ROLLBACK: + zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break; + case SQLITE_WARNING: zName = "SQLITE_WARNING"; break; + case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break; + case SQLITE_DONE: zName = "SQLITE_DONE"; break; + } + } + if( zName==0 ){ + static char zBuf[50]; + sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); + zName = zBuf; + } + return zName; +} +#endif + +/* +** Return a static string that describes the kind of error specified in the +** argument. +*/ +SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ + static const char* const aMsg[] = { + /* SQLITE_OK */ "not an error", + /* SQLITE_ERROR */ "SQL logic error or missing database", + /* SQLITE_INTERNAL */ 0, + /* SQLITE_PERM */ "access permission denied", + /* SQLITE_ABORT */ "callback requested query abort", + /* SQLITE_BUSY */ "database is locked", + /* SQLITE_LOCKED */ "database table is locked", + /* SQLITE_NOMEM */ "out of memory", + /* SQLITE_READONLY */ "attempt to write a readonly database", + /* SQLITE_INTERRUPT */ "interrupted", + /* SQLITE_IOERR */ "disk I/O error", + /* SQLITE_CORRUPT */ "database disk image is malformed", + /* SQLITE_NOTFOUND */ "unknown operation", + /* SQLITE_FULL */ "database or disk is full", + /* SQLITE_CANTOPEN */ "unable to open database file", + /* SQLITE_PROTOCOL */ "locking protocol", + /* SQLITE_EMPTY */ "table contains no data", + /* SQLITE_SCHEMA */ "database schema has changed", + /* SQLITE_TOOBIG */ "string or blob too big", + /* SQLITE_CONSTRAINT */ "constraint failed", + /* SQLITE_MISMATCH */ "datatype mismatch", + /* SQLITE_MISUSE */ "library routine called out of sequence", + /* SQLITE_NOLFS */ "large file support is disabled", + /* SQLITE_AUTH */ "authorization denied", + /* SQLITE_FORMAT */ "auxiliary database format error", + /* SQLITE_RANGE */ "bind or column index out of range", + /* SQLITE_NOTADB */ "file is encrypted or is not a database", + }; + const char *zErr = "unknown error"; + switch( rc ){ + case SQLITE_ABORT_ROLLBACK: { + zErr = "abort due to ROLLBACK"; + break; + } + default: { + rc &= 0xff; + if( ALWAYS(rc>=0) && rcbusyTimeout; + int delay, prior; + + assert( count>=0 ); + if( count < NDELAY ){ + delay = delays[count]; + prior = totals[count]; + }else{ + delay = delays[NDELAY-1]; + prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); + } + if( prior + delay > timeout ){ + delay = timeout - prior; + if( delay<=0 ) return 0; + } + sqlite3OsSleep(db->pVfs, delay*1000); + return 1; +#else + sqlite3 *db = (sqlite3 *)ptr; + int timeout = ((sqlite3 *)ptr)->busyTimeout; + if( (count+1)*1000 > timeout ){ + return 0; + } + sqlite3OsSleep(db->pVfs, 1000000); + return 1; +#endif +} + +/* +** Invoke the given busy handler. +** +** This routine is called when an operation failed with a lock. +** If this routine returns non-zero, the lock is retried. If it +** returns 0, the operation aborts with an SQLITE_BUSY error. +*/ +SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){ + int rc; + if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; + rc = p->xFunc(p->pArg, p->nBusy); + if( rc==0 ){ + p->nBusy = -1; + }else{ + p->nBusy++; + } + return rc; +} + +/* +** This routine sets the busy callback for an Sqlite database to the +** given callback function with the given argument. +*/ +SQLITE_API int sqlite3_busy_handler( + sqlite3 *db, + int (*xBusy)(void*,int), + void *pArg +){ + sqlite3_mutex_enter(db->mutex); + db->busyHandler.xFunc = xBusy; + db->busyHandler.pArg = pArg; + db->busyHandler.nBusy = 0; + db->busyTimeout = 0; + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK +/* +** This routine sets the progress callback for an Sqlite database to the +** given callback function with the given argument. The progress callback will +** be invoked every nOps opcodes. +*/ +SQLITE_API void sqlite3_progress_handler( + sqlite3 *db, + int nOps, + int (*xProgress)(void*), + void *pArg +){ + sqlite3_mutex_enter(db->mutex); + if( nOps>0 ){ + db->xProgress = xProgress; + db->nProgressOps = (unsigned)nOps; + db->pProgressArg = pArg; + }else{ + db->xProgress = 0; + db->nProgressOps = 0; + db->pProgressArg = 0; + } + sqlite3_mutex_leave(db->mutex); +} +#endif + + +/* +** This routine installs a default busy handler that waits for the +** specified number of milliseconds before returning 0. +*/ +SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ + if( ms>0 ){ + sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); + db->busyTimeout = ms; + }else{ + sqlite3_busy_handler(db, 0, 0); + } + return SQLITE_OK; +} + +/* +** Cause any pending operation to stop at its earliest opportunity. +*/ +SQLITE_API void sqlite3_interrupt(sqlite3 *db){ + db->u1.isInterrupted = 1; +} + + +/* +** This function is exactly the same as sqlite3_create_function(), except +** that it is designed to be called by internal code. The difference is +** that if a malloc() fails in sqlite3_create_function(), an error code +** is returned and the mallocFailed flag cleared. +*/ +SQLITE_PRIVATE int sqlite3CreateFunc( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int enc, + void *pUserData, + void (*xFunc)(sqlite3_context*,int,sqlite3_value **), + void (*xStep)(sqlite3_context*,int,sqlite3_value **), + void (*xFinal)(sqlite3_context*), + FuncDestructor *pDestructor +){ + FuncDef *p; + int nName; + + assert( sqlite3_mutex_held(db->mutex) ); + if( zFunctionName==0 || + (xFunc && (xFinal || xStep)) || + (!xFunc && (xFinal && !xStep)) || + (!xFunc && (!xFinal && xStep)) || + (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || + (255<(nName = sqlite3Strlen30( zFunctionName))) ){ + return SQLITE_MISUSE_BKPT; + } + +#ifndef SQLITE_OMIT_UTF16 + /* If SQLITE_UTF16 is specified as the encoding type, transform this + ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the + ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. + ** + ** If SQLITE_ANY is specified, add three versions of the function + ** to the hash table. + */ + if( enc==SQLITE_UTF16 ){ + enc = SQLITE_UTF16NATIVE; + }else if( enc==SQLITE_ANY ){ + int rc; + rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8, + pUserData, xFunc, xStep, xFinal, pDestructor); + if( rc==SQLITE_OK ){ + rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE, + pUserData, xFunc, xStep, xFinal, pDestructor); + } + if( rc!=SQLITE_OK ){ + return rc; + } + enc = SQLITE_UTF16BE; + } +#else + enc = SQLITE_UTF8; +#endif + + /* Check if an existing function is being overridden or deleted. If so, + ** and there are active VMs, then return SQLITE_BUSY. If a function + ** is being overridden/deleted but there are no active VMs, allow the + ** operation to continue but invalidate all precompiled statements. + */ + p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0); + if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){ + if( db->nVdbeActive ){ + sqlite3Error(db, SQLITE_BUSY, + "unable to delete/modify user-function due to active statements"); + assert( !db->mallocFailed ); + return SQLITE_BUSY; + }else{ + sqlite3ExpirePreparedStatements(db); + } + } + + p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1); + assert(p || db->mallocFailed); + if( !p ){ + return SQLITE_NOMEM; + } + + /* If an older version of the function with a configured destructor is + ** being replaced invoke the destructor function here. */ + functionDestroy(db, p); + + if( pDestructor ){ + pDestructor->nRef++; + } + p->pDestructor = pDestructor; + p->funcFlags &= SQLITE_FUNC_ENCMASK; + p->xFunc = xFunc; + p->xStep = xStep; + p->xFinalize = xFinal; + p->pUserData = pUserData; + p->nArg = (u16)nArg; + return SQLITE_OK; +} + +/* +** Create new user functions. +*/ +SQLITE_API int sqlite3_create_function( + sqlite3 *db, + const char *zFunc, + int nArg, + int enc, + void *p, + void (*xFunc)(sqlite3_context*,int,sqlite3_value **), + void (*xStep)(sqlite3_context*,int,sqlite3_value **), + void (*xFinal)(sqlite3_context*) +){ + return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep, + xFinal, 0); +} + +SQLITE_API int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunc, + int nArg, + int enc, + void *p, + void (*xFunc)(sqlite3_context*,int,sqlite3_value **), + void (*xStep)(sqlite3_context*,int,sqlite3_value **), + void (*xFinal)(sqlite3_context*), + void (*xDestroy)(void *) +){ + int rc = SQLITE_ERROR; + FuncDestructor *pArg = 0; + sqlite3_mutex_enter(db->mutex); + if( xDestroy ){ + pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); + if( !pArg ){ + xDestroy(p); + goto out; + } + pArg->xDestroy = xDestroy; + pArg->pUserData = p; + } + rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg); + if( pArg && pArg->nRef==0 ){ + assert( rc!=SQLITE_OK ); + xDestroy(p); + sqlite3DbFree(db, pArg); + } + + out: + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#ifndef SQLITE_OMIT_UTF16 +SQLITE_API int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *p, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +){ + int rc; + char *zFunc8; + sqlite3_mutex_enter(db->mutex); + assert( !db->mallocFailed ); + zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); + rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0); + sqlite3DbFree(db, zFunc8); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} +#endif + + +/* +** Declare that a function has been overloaded by a virtual table. +** +** If the function already exists as a regular global function, then +** this routine is a no-op. If the function does not exist, then create +** a new one that always throws a run-time error. +** +** When virtual tables intend to provide an overloaded function, they +** should call this routine to make sure the global function exists. +** A global function must exist in order for name resolution to work +** properly. +*/ +SQLITE_API int sqlite3_overload_function( + sqlite3 *db, + const char *zName, + int nArg +){ + int nName = sqlite3Strlen30(zName); + int rc = SQLITE_OK; + sqlite3_mutex_enter(db->mutex); + if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){ + rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, + 0, sqlite3InvalidFunction, 0, 0, 0); + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#ifndef SQLITE_OMIT_TRACE +/* +** Register a trace function. The pArg from the previously registered trace +** is returned. +** +** A NULL trace function means that no tracing is executes. A non-NULL +** trace is a pointer to a function that is invoked at the start of each +** SQL statement. +*/ +SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){ + void *pOld; + sqlite3_mutex_enter(db->mutex); + pOld = db->pTraceArg; + db->xTrace = xTrace; + db->pTraceArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pOld; +} +/* +** Register a profile function. The pArg from the previously registered +** profile function is returned. +** +** A NULL profile function means that no profiling is executes. A non-NULL +** profile is a pointer to a function that is invoked at the conclusion of +** each SQL statement that is run. +*/ +SQLITE_API void *sqlite3_profile( + sqlite3 *db, + void (*xProfile)(void*,const char*,sqlite_uint64), + void *pArg +){ + void *pOld; + sqlite3_mutex_enter(db->mutex); + pOld = db->pProfileArg; + db->xProfile = xProfile; + db->pProfileArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pOld; +} +#endif /* SQLITE_OMIT_TRACE */ + +/* +** Register a function to be invoked when a transaction commits. +** If the invoked function returns non-zero, then the commit becomes a +** rollback. +*/ +SQLITE_API void *sqlite3_commit_hook( + sqlite3 *db, /* Attach the hook to this database */ + int (*xCallback)(void*), /* Function to invoke on each commit */ + void *pArg /* Argument to the function */ +){ + void *pOld; + sqlite3_mutex_enter(db->mutex); + pOld = db->pCommitArg; + db->xCommitCallback = xCallback; + db->pCommitArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pOld; +} + +/* +** Register a callback to be invoked each time a row is updated, +** inserted or deleted using this database connection. +*/ +SQLITE_API void *sqlite3_update_hook( + sqlite3 *db, /* Attach the hook to this database */ + void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), + void *pArg /* Argument to the function */ +){ + void *pRet; + sqlite3_mutex_enter(db->mutex); + pRet = db->pUpdateArg; + db->xUpdateCallback = xCallback; + db->pUpdateArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pRet; +} + +/* +** Register a callback to be invoked each time a transaction is rolled +** back by this database connection. +*/ +SQLITE_API void *sqlite3_rollback_hook( + sqlite3 *db, /* Attach the hook to this database */ + void (*xCallback)(void*), /* Callback function */ + void *pArg /* Argument to the function */ +){ + void *pRet; + sqlite3_mutex_enter(db->mutex); + pRet = db->pRollbackArg; + db->xRollbackCallback = xCallback; + db->pRollbackArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pRet; +} + +#ifndef SQLITE_OMIT_WAL +/* +** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). +** Invoke sqlite3_wal_checkpoint if the number of frames in the log file +** is greater than sqlite3.pWalArg cast to an integer (the value configured by +** wal_autocheckpoint()). +*/ +SQLITE_PRIVATE int sqlite3WalDefaultHook( + void *pClientData, /* Argument */ + sqlite3 *db, /* Connection */ + const char *zDb, /* Database */ + int nFrame /* Size of WAL */ +){ + if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ + sqlite3BeginBenignMalloc(); + sqlite3_wal_checkpoint(db, zDb); + sqlite3EndBenignMalloc(); + } + return SQLITE_OK; +} +#endif /* SQLITE_OMIT_WAL */ + +/* +** Configure an sqlite3_wal_hook() callback to automatically checkpoint +** a database after committing a transaction if there are nFrame or +** more frames in the log file. Passing zero or a negative value as the +** nFrame parameter disables automatic checkpoints entirely. +** +** The callback registered by this function replaces any existing callback +** registered using sqlite3_wal_hook(). Likewise, registering a callback +** using sqlite3_wal_hook() disables the automatic checkpoint mechanism +** configured by this function. +*/ +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ +#ifdef SQLITE_OMIT_WAL + UNUSED_PARAMETER(db); + UNUSED_PARAMETER(nFrame); +#else + if( nFrame>0 ){ + sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); + }else{ + sqlite3_wal_hook(db, 0, 0); + } +#endif + return SQLITE_OK; +} + +/* +** Register a callback to be invoked each time a transaction is written +** into the write-ahead-log by this database connection. +*/ +SQLITE_API void *sqlite3_wal_hook( + sqlite3 *db, /* Attach the hook to this db handle */ + int(*xCallback)(void *, sqlite3*, const char*, int), + void *pArg /* First argument passed to xCallback() */ +){ +#ifndef SQLITE_OMIT_WAL + void *pRet; + sqlite3_mutex_enter(db->mutex); + pRet = db->pWalArg; + db->xWalCallback = xCallback; + db->pWalArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pRet; +#else + return 0; +#endif +} + +/* +** Checkpoint database zDb. +*/ +SQLITE_API int sqlite3_wal_checkpoint_v2( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + int *pnLog, /* OUT: Size of WAL log in frames */ + int *pnCkpt /* OUT: Total number of frames checkpointed */ +){ +#ifdef SQLITE_OMIT_WAL + return SQLITE_OK; +#else + int rc; /* Return code */ + int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ + + /* Initialize the output variables to -1 in case an error occurs. */ + if( pnLog ) *pnLog = -1; + if( pnCkpt ) *pnCkpt = -1; + + assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE ); + assert( SQLITE_CHECKPOINT_FULLSQLITE_CHECKPOINT_RESTART ){ + return SQLITE_MISUSE; + } + + sqlite3_mutex_enter(db->mutex); + if( zDb && zDb[0] ){ + iDb = sqlite3FindDbName(db, zDb); + } + if( iDb<0 ){ + rc = SQLITE_ERROR; + sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb); + }else{ + rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); + sqlite3Error(db, rc, 0); + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +#endif +} + + +/* +** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points +** to contains a zero-length string, all attached databases are +** checkpointed. +*/ +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ + return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0); +} + +#ifndef SQLITE_OMIT_WAL +/* +** Run a checkpoint on database iDb. This is a no-op if database iDb is +** not currently open in WAL mode. +** +** If a transaction is open on the database being checkpointed, this +** function returns SQLITE_LOCKED and a checkpoint is not attempted. If +** an error occurs while running the checkpoint, an SQLite error code is +** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. +** +** The mutex on database handle db should be held by the caller. The mutex +** associated with the specific b-tree being checkpointed is taken by +** this function while the checkpoint is running. +** +** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are +** checkpointed. If an error is encountered it is returned immediately - +** no attempt is made to checkpoint any remaining databases. +** +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +*/ +SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ + int rc = SQLITE_OK; /* Return code */ + int i; /* Used to iterate through attached dbs */ + int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ + + assert( sqlite3_mutex_held(db->mutex) ); + assert( !pnLog || *pnLog==-1 ); + assert( !pnCkpt || *pnCkpt==-1 ); + + for(i=0; inDb && rc==SQLITE_OK; i++){ + if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ + rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); + pnLog = 0; + pnCkpt = 0; + if( rc==SQLITE_BUSY ){ + bBusy = 1; + rc = SQLITE_OK; + } + } + } + + return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; +} +#endif /* SQLITE_OMIT_WAL */ + +/* +** This function returns true if main-memory should be used instead of +** a temporary file for transient pager files and statement journals. +** The value returned depends on the value of db->temp_store (runtime +** parameter) and the compile time value of SQLITE_TEMP_STORE. The +** following table describes the relationship between these two values +** and this functions return value. +** +** SQLITE_TEMP_STORE db->temp_store Location of temporary database +** ----------------- -------------- ------------------------------ +** 0 any file (return 0) +** 1 1 file (return 0) +** 1 2 memory (return 1) +** 1 0 file (return 0) +** 2 1 file (return 0) +** 2 2 memory (return 1) +** 2 0 memory (return 1) +** 3 any memory (return 1) +*/ +SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){ +#if SQLITE_TEMP_STORE==1 + return ( db->temp_store==2 ); +#endif +#if SQLITE_TEMP_STORE==2 + return ( db->temp_store!=1 ); +#endif +#if SQLITE_TEMP_STORE==3 + return 1; +#endif +#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 + return 0; +#endif +} + +/* +** Return UTF-8 encoded English language explanation of the most recent +** error. +*/ +SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ + const char *z; + if( !db ){ + return sqlite3ErrStr(SQLITE_NOMEM); + } + if( !sqlite3SafetyCheckSickOrOk(db) ){ + return sqlite3ErrStr(SQLITE_MISUSE_BKPT); + } + sqlite3_mutex_enter(db->mutex); + if( db->mallocFailed ){ + z = sqlite3ErrStr(SQLITE_NOMEM); + }else{ + z = (char*)sqlite3_value_text(db->pErr); + assert( !db->mallocFailed ); + if( z==0 ){ + z = sqlite3ErrStr(db->errCode); + } + } + sqlite3_mutex_leave(db->mutex); + return z; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Return UTF-16 encoded English language explanation of the most recent +** error. +*/ +SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ + static const u16 outOfMem[] = { + 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 + }; + static const u16 misuse[] = { + 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', + 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', + 'c', 'a', 'l', 'l', 'e', 'd', ' ', + 'o', 'u', 't', ' ', + 'o', 'f', ' ', + 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 + }; + + const void *z; + if( !db ){ + return (void *)outOfMem; + } + if( !sqlite3SafetyCheckSickOrOk(db) ){ + return (void *)misuse; + } + sqlite3_mutex_enter(db->mutex); + if( db->mallocFailed ){ + z = (void *)outOfMem; + }else{ + z = sqlite3_value_text16(db->pErr); + if( z==0 ){ + sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode), + SQLITE_UTF8, SQLITE_STATIC); + z = sqlite3_value_text16(db->pErr); + } + /* A malloc() may have failed within the call to sqlite3_value_text16() + ** above. If this is the case, then the db->mallocFailed flag needs to + ** be cleared before returning. Do this directly, instead of via + ** sqlite3ApiExit(), to avoid setting the database handle error message. + */ + db->mallocFailed = 0; + } + sqlite3_mutex_leave(db->mutex); + return z; +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Return the most recent error code generated by an SQLite routine. If NULL is +** passed to this function, we assume a malloc() failed during sqlite3_open(). +*/ +SQLITE_API int sqlite3_errcode(sqlite3 *db){ + if( db && !sqlite3SafetyCheckSickOrOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + if( !db || db->mallocFailed ){ + return SQLITE_NOMEM; + } + return db->errCode & db->errMask; +} +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){ + if( db && !sqlite3SafetyCheckSickOrOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + if( !db || db->mallocFailed ){ + return SQLITE_NOMEM; + } + return db->errCode; +} + +/* +** Return a string that describes the kind of error specified in the +** argument. For now, this simply calls the internal sqlite3ErrStr() +** function. +*/ +SQLITE_API const char *sqlite3_errstr(int rc){ + return sqlite3ErrStr(rc); +} + +/* +** Create a new collating function for database "db". The name is zName +** and the encoding is enc. +*/ +static int createCollation( + sqlite3* db, + const char *zName, + u8 enc, + void* pCtx, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDel)(void*) +){ + CollSeq *pColl; + int enc2; + int nName = sqlite3Strlen30(zName); + + assert( sqlite3_mutex_held(db->mutex) ); + + /* If SQLITE_UTF16 is specified as the encoding type, transform this + ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the + ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. + */ + enc2 = enc; + testcase( enc2==SQLITE_UTF16 ); + testcase( enc2==SQLITE_UTF16_ALIGNED ); + if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ + enc2 = SQLITE_UTF16NATIVE; + } + if( enc2SQLITE_UTF16BE ){ + return SQLITE_MISUSE_BKPT; + } + + /* Check if this call is removing or replacing an existing collation + ** sequence. If so, and there are active VMs, return busy. If there + ** are no active VMs, invalidate any pre-compiled statements. + */ + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); + if( pColl && pColl->xCmp ){ + if( db->nVdbeActive ){ + sqlite3Error(db, SQLITE_BUSY, + "unable to delete/modify collation sequence due to active statements"); + return SQLITE_BUSY; + } + sqlite3ExpirePreparedStatements(db); + + /* If collation sequence pColl was created directly by a call to + ** sqlite3_create_collation, and not generated by synthCollSeq(), + ** then any copies made by synthCollSeq() need to be invalidated. + ** Also, collation destructor - CollSeq.xDel() - function may need + ** to be called. + */ + if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ + CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName); + int j; + for(j=0; j<3; j++){ + CollSeq *p = &aColl[j]; + if( p->enc==pColl->enc ){ + if( p->xDel ){ + p->xDel(p->pUser); + } + p->xCmp = 0; + } + } + } + } + + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); + if( pColl==0 ) return SQLITE_NOMEM; + pColl->xCmp = xCompare; + pColl->pUser = pCtx; + pColl->xDel = xDel; + pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); + sqlite3Error(db, SQLITE_OK, 0); + return SQLITE_OK; +} + + +/* +** This array defines hard upper bounds on limit values. The +** initializer must be kept in sync with the SQLITE_LIMIT_* +** #defines in sqlite3.h. +*/ +static const int aHardLimit[] = { + SQLITE_MAX_LENGTH, + SQLITE_MAX_SQL_LENGTH, + SQLITE_MAX_COLUMN, + SQLITE_MAX_EXPR_DEPTH, + SQLITE_MAX_COMPOUND_SELECT, + SQLITE_MAX_VDBE_OP, + SQLITE_MAX_FUNCTION_ARG, + SQLITE_MAX_ATTACHED, + SQLITE_MAX_LIKE_PATTERN_LENGTH, + SQLITE_MAX_VARIABLE_NUMBER, + SQLITE_MAX_TRIGGER_DEPTH, +}; + +/* +** Make sure the hard limits are set to reasonable values +*/ +#if SQLITE_MAX_LENGTH<100 +# error SQLITE_MAX_LENGTH must be at least 100 +#endif +#if SQLITE_MAX_SQL_LENGTH<100 +# error SQLITE_MAX_SQL_LENGTH must be at least 100 +#endif +#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH +# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH +#endif +#if SQLITE_MAX_COMPOUND_SELECT<2 +# error SQLITE_MAX_COMPOUND_SELECT must be at least 2 +#endif +#if SQLITE_MAX_VDBE_OP<40 +# error SQLITE_MAX_VDBE_OP must be at least 40 +#endif +#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000 +# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000 +#endif +#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62 +# error SQLITE_MAX_ATTACHED must be between 0 and 62 +#endif +#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 +# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 +#endif +#if SQLITE_MAX_COLUMN>32767 +# error SQLITE_MAX_COLUMN must not exceed 32767 +#endif +#if SQLITE_MAX_TRIGGER_DEPTH<1 +# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 +#endif + + +/* +** Change the value of a limit. Report the old value. +** If an invalid limit index is supplied, report -1. +** Make no changes but still report the old value if the +** new limit is negative. +** +** A new lower limit does not shrink existing constructs. +** It merely prevents new constructs that exceed the limit +** from forming. +*/ +SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ + int oldLimit; + + + /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME + ** there is a hard upper bound set at compile-time by a C preprocessor + ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to + ** "_MAX_".) + */ + assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); + assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); + assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); + assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); + assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); + assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); + assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); + assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); + assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== + SQLITE_MAX_LIKE_PATTERN_LENGTH ); + assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); + assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); + assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) ); + + + if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ + return -1; + } + oldLimit = db->aLimit[limitId]; + if( newLimit>=0 ){ /* IMP: R-52476-28732 */ + if( newLimit>aHardLimit[limitId] ){ + newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ + } + db->aLimit[limitId] = newLimit; + } + return oldLimit; /* IMP: R-53341-35419 */ +} + +/* +** This function is used to parse both URIs and non-URI filenames passed by the +** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database +** URIs specified as part of ATTACH statements. +** +** The first argument to this function is the name of the VFS to use (or +** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" +** query parameter. The second argument contains the URI (or non-URI filename) +** itself. When this function is called the *pFlags variable should contain +** the default flags to open the database handle with. The value stored in +** *pFlags may be updated before returning if the URI filename contains +** "cache=xxx" or "mode=xxx" query parameters. +** +** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to +** the VFS that should be used to open the database file. *pzFile is set to +** point to a buffer containing the name of the file to open. It is the +** responsibility of the caller to eventually call sqlite3_free() to release +** this buffer. +** +** If an error occurs, then an SQLite error code is returned and *pzErrMsg +** may be set to point to a buffer containing an English language error +** message. It is the responsibility of the caller to eventually release +** this buffer by calling sqlite3_free(). +*/ +SQLITE_PRIVATE int sqlite3ParseUri( + const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ + const char *zUri, /* Nul-terminated URI to parse */ + unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ + sqlite3_vfs **ppVfs, /* OUT: VFS to use */ + char **pzFile, /* OUT: Filename component of URI */ + char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ +){ + int rc = SQLITE_OK; + unsigned int flags = *pFlags; + const char *zVfs = zDefaultVfs; + char *zFile; + char c; + int nUri = sqlite3Strlen30(zUri); + + assert( *pzErrMsg==0 ); + + if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) + && nUri>=5 && memcmp(zUri, "file:", 5)==0 + ){ + char *zOpt; + int eState; /* Parser state when parsing URI */ + int iIn; /* Input character index */ + int iOut = 0; /* Output character index */ + int nByte = nUri+2; /* Bytes of space to allocate */ + + /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen + ** method that there may be extra parameters following the file-name. */ + flags |= SQLITE_OPEN_URI; + + for(iIn=0; iIn=0 && octet<256 ); + if( octet==0 ){ + /* This branch is taken when "%00" appears within the URI. In this + ** case we ignore all text in the remainder of the path, name or + ** value currently being parsed. So ignore the current character + ** and skip to the next "?", "=" or "&", as appropriate. */ + while( (c = zUri[iIn])!=0 && c!='#' + && (eState!=0 || c!='?') + && (eState!=1 || (c!='=' && c!='&')) + && (eState!=2 || c!='&') + ){ + iIn++; + } + continue; + } + c = octet; + }else if( eState==1 && (c=='&' || c=='=') ){ + if( zFile[iOut-1]==0 ){ + /* An empty option name. Ignore this option altogether. */ + while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; + continue; + } + if( c=='&' ){ + zFile[iOut++] = '\0'; + }else{ + eState = 2; + } + c = 0; + }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ + c = 0; + eState = 1; + } + zFile[iOut++] = c; + } + if( eState==1 ) zFile[iOut++] = '\0'; + zFile[iOut++] = '\0'; + zFile[iOut++] = '\0'; + + /* Check if there were any options specified that should be interpreted + ** here. Options that are interpreted here include "vfs" and those that + ** correspond to flags that may be passed to the sqlite3_open_v2() + ** method. */ + zOpt = &zFile[sqlite3Strlen30(zFile)+1]; + while( zOpt[0] ){ + int nOpt = sqlite3Strlen30(zOpt); + char *zVal = &zOpt[nOpt+1]; + int nVal = sqlite3Strlen30(zVal); + + if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ + zVfs = zVal; + }else{ + struct OpenMode { + const char *z; + int mode; + } *aMode = 0; + char *zModeType = 0; + int mask = 0; + int limit = 0; + + if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ + static struct OpenMode aCacheMode[] = { + { "shared", SQLITE_OPEN_SHAREDCACHE }, + { "private", SQLITE_OPEN_PRIVATECACHE }, + { 0, 0 } + }; + + mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; + aMode = aCacheMode; + limit = mask; + zModeType = "cache"; + } + if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ + static struct OpenMode aOpenMode[] = { + { "ro", SQLITE_OPEN_READONLY }, + { "rw", SQLITE_OPEN_READWRITE }, + { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, + { "memory", SQLITE_OPEN_MEMORY }, + { 0, 0 } + }; + + mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE + | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; + aMode = aOpenMode; + limit = mask & flags; + zModeType = "access"; + } + + if( aMode ){ + int i; + int mode = 0; + for(i=0; aMode[i].z; i++){ + const char *z = aMode[i].z; + if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ + mode = aMode[i].mode; + break; + } + } + if( mode==0 ){ + *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); + rc = SQLITE_ERROR; + goto parse_uri_out; + } + if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ + *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", + zModeType, zVal); + rc = SQLITE_PERM; + goto parse_uri_out; + } + flags = (flags & ~mask) | mode; + } + } + + zOpt = &zVal[nVal+1]; + } + + }else{ + zFile = sqlite3_malloc(nUri+2); + if( !zFile ) return SQLITE_NOMEM; + memcpy(zFile, zUri, nUri); + zFile[nUri] = '\0'; + zFile[nUri+1] = '\0'; + flags &= ~SQLITE_OPEN_URI; + } + + *ppVfs = sqlite3_vfs_find(zVfs); + if( *ppVfs==0 ){ + *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); + rc = SQLITE_ERROR; + } + parse_uri_out: + if( rc!=SQLITE_OK ){ + sqlite3_free(zFile); + zFile = 0; + } + *pFlags = flags; + *pzFile = zFile; + return rc; +} + + +/* +** This routine does the work of opening a database on behalf of +** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" +** is UTF-8 encoded. +*/ +static int openDatabase( + const char *zFilename, /* Database filename UTF-8 encoded */ + sqlite3 **ppDb, /* OUT: Returned database handle */ + unsigned int flags, /* Operational flags */ + const char *zVfs /* Name of the VFS to use */ +){ + sqlite3 *db; /* Store allocated handle here */ + int rc; /* Return code */ + int isThreadsafe; /* True for threadsafe connections */ + char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ + char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ + + *ppDb = 0; +#ifndef SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if( rc ) return rc; +#endif + + /* Only allow sensible combinations of bits in the flags argument. + ** Throw an error if any non-sense combination is used. If we + ** do not block illegal combinations here, it could trigger + ** assert() statements in deeper layers. Sensible combinations + ** are: + ** + ** 1: SQLITE_OPEN_READONLY + ** 2: SQLITE_OPEN_READWRITE + ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE + */ + assert( SQLITE_OPEN_READONLY == 0x01 ); + assert( SQLITE_OPEN_READWRITE == 0x02 ); + assert( SQLITE_OPEN_CREATE == 0x04 ); + testcase( (1<<(flags&7))==0x02 ); /* READONLY */ + testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ + testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ + if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT; + + if( sqlite3GlobalConfig.bCoreMutex==0 ){ + isThreadsafe = 0; + }else if( flags & SQLITE_OPEN_NOMUTEX ){ + isThreadsafe = 0; + }else if( flags & SQLITE_OPEN_FULLMUTEX ){ + isThreadsafe = 1; + }else{ + isThreadsafe = sqlite3GlobalConfig.bFullMutex; + } + if( flags & SQLITE_OPEN_PRIVATECACHE ){ + flags &= ~SQLITE_OPEN_SHAREDCACHE; + }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ + flags |= SQLITE_OPEN_SHAREDCACHE; + } + + /* Remove harmful bits from the flags parameter + ** + ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were + ** dealt with in the previous code block. Besides these, the only + ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, + ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, + ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask + ** off all other flags. + */ + flags &= ~( SQLITE_OPEN_DELETEONCLOSE | + SQLITE_OPEN_EXCLUSIVE | + SQLITE_OPEN_MAIN_DB | + SQLITE_OPEN_TEMP_DB | + SQLITE_OPEN_TRANSIENT_DB | + SQLITE_OPEN_MAIN_JOURNAL | + SQLITE_OPEN_TEMP_JOURNAL | + SQLITE_OPEN_SUBJOURNAL | + SQLITE_OPEN_MASTER_JOURNAL | + SQLITE_OPEN_NOMUTEX | + SQLITE_OPEN_FULLMUTEX | + SQLITE_OPEN_WAL + ); + + /* Allocate the sqlite data structure */ + db = sqlite3MallocZero( sizeof(sqlite3) ); + if( db==0 ) goto opendb_out; + if( isThreadsafe ){ + db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); + if( db->mutex==0 ){ + sqlite3_free(db); + db = 0; + goto opendb_out; + } + } + sqlite3_mutex_enter(db->mutex); + db->errMask = 0xff; + db->nDb = 2; + db->magic = SQLITE_MAGIC_BUSY; + db->aDb = db->aDbStatic; + + assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); + memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); + db->autoCommit = 1; + db->nextAutovac = -1; + db->szMmap = sqlite3GlobalConfig.szMmap; + db->nextPagesize = 0; + db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill +#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX + | SQLITE_AutoIndex +#endif +#if SQLITE_DEFAULT_FILE_FORMAT<4 + | SQLITE_LegacyFileFmt +#endif +#ifdef SQLITE_ENABLE_LOAD_EXTENSION + | SQLITE_LoadExtension +#endif +#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS + | SQLITE_RecTriggers +#endif +#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS + | SQLITE_ForeignKeys +#endif + ; + sqlite3HashInit(&db->aCollSeq); +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3HashInit(&db->aModule); +#endif + + /* Add the default collation sequence BINARY. BINARY works for both UTF-8 + ** and UTF-16, so add a version for each to avoid any unnecessary + ** conversions. The only error that can occur here is a malloc() failure. + */ + createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0); + createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0); + createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0); + createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); + if( db->mallocFailed ){ + goto opendb_out; + } + db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0); + assert( db->pDfltColl!=0 ); + + /* Also add a UTF-8 case-insensitive collation sequence. */ + createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); + + /* Parse the filename/URI argument. */ + db->openFlags = flags; + rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM ) db->mallocFailed = 1; + sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg); + sqlite3_free(zErrMsg); + goto opendb_out; + } + + /* Open the backend database driver */ + rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, + flags | SQLITE_OPEN_MAIN_DB); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_IOERR_NOMEM ){ + rc = SQLITE_NOMEM; + } + sqlite3Error(db, rc, 0); + goto opendb_out; + } + db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); + db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); + + + /* The default safety_level for the main database is 'full'; for the temp + ** database it is 'NONE'. This matches the pager layer defaults. + */ + db->aDb[0].zName = "main"; + db->aDb[0].safety_level = 3; + db->aDb[1].zName = "temp"; + db->aDb[1].safety_level = 1; + + db->magic = SQLITE_MAGIC_OPEN; + if( db->mallocFailed ){ + goto opendb_out; + } + + /* Register all built-in functions, but do not attempt to read the + ** database schema yet. This is delayed until the first time the database + ** is accessed. + */ + sqlite3Error(db, SQLITE_OK, 0); + sqlite3RegisterBuiltinFunctions(db); + + /* Load automatic extensions - extensions that have been registered + ** using the sqlite3_automatic_extension() API. + */ + rc = sqlite3_errcode(db); + if( rc==SQLITE_OK ){ + sqlite3AutoLoadExtensions(db); + rc = sqlite3_errcode(db); + if( rc!=SQLITE_OK ){ + goto opendb_out; + } + } + +#ifdef SQLITE_ENABLE_FTS1 + if( !db->mallocFailed ){ + extern int sqlite3Fts1Init(sqlite3*); + rc = sqlite3Fts1Init(db); + } +#endif + +#ifdef SQLITE_ENABLE_FTS2 + if( !db->mallocFailed && rc==SQLITE_OK ){ + extern int sqlite3Fts2Init(sqlite3*); + rc = sqlite3Fts2Init(db); + } +#endif + +#ifdef SQLITE_ENABLE_FTS3 + if( !db->mallocFailed && rc==SQLITE_OK ){ + rc = sqlite3Fts3Init(db); + } +#endif + +#ifdef SQLITE_ENABLE_ICU + if( !db->mallocFailed && rc==SQLITE_OK ){ + rc = sqlite3IcuInit(db); + } +#endif + +#ifdef SQLITE_ENABLE_RTREE + if( !db->mallocFailed && rc==SQLITE_OK){ + rc = sqlite3RtreeInit(db); + } +#endif + + sqlite3Error(db, rc, 0); + + /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking + ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking + ** mode. Doing nothing at all also makes NORMAL the default. + */ +#ifdef SQLITE_DEFAULT_LOCKING_MODE + db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; + sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), + SQLITE_DEFAULT_LOCKING_MODE); +#endif + + /* Enable the lookaside-malloc subsystem */ + setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, + sqlite3GlobalConfig.nLookaside); + + sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); + +opendb_out: + sqlite3_free(zOpen); + if( db ){ + assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 ); + sqlite3_mutex_leave(db->mutex); + } + rc = sqlite3_errcode(db); + assert( db!=0 || rc==SQLITE_NOMEM ); + if( rc==SQLITE_NOMEM ){ + sqlite3_close(db); + db = 0; + }else if( rc!=SQLITE_OK ){ + db->magic = SQLITE_MAGIC_SICK; + } + *ppDb = db; +#ifdef SQLITE_ENABLE_SQLLOG + if( sqlite3GlobalConfig.xSqllog ){ + /* Opening a db handle. Fourth parameter is passed 0. */ + void *pArg = sqlite3GlobalConfig.pSqllogArg; + sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); + } +#endif + return sqlite3ApiExit(0, rc); +} + +/* +** Open a new database handle. +*/ +SQLITE_API int sqlite3_open( + const char *zFilename, + sqlite3 **ppDb +){ + return openDatabase(zFilename, ppDb, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); +} +SQLITE_API int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +){ + return openDatabase(filename, ppDb, (unsigned int)flags, zVfs); +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Open a new database handle. +*/ +SQLITE_API int sqlite3_open16( + const void *zFilename, + sqlite3 **ppDb +){ + char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ + sqlite3_value *pVal; + int rc; + + assert( zFilename ); + assert( ppDb ); + *ppDb = 0; +#ifndef SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if( rc ) return rc; +#endif + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); + zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); + if( zFilename8 ){ + rc = openDatabase(zFilename8, ppDb, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); + assert( *ppDb || rc==SQLITE_NOMEM ); + if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ + ENC(*ppDb) = SQLITE_UTF16NATIVE; + } + }else{ + rc = SQLITE_NOMEM; + } + sqlite3ValueFree(pVal); + + return sqlite3ApiExit(0, rc); +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Register a new collation sequence with the database handle db. +*/ +SQLITE_API int sqlite3_create_collation( + sqlite3* db, + const char *zName, + int enc, + void* pCtx, + int(*xCompare)(void*,int,const void*,int,const void*) +){ + int rc; + sqlite3_mutex_enter(db->mutex); + assert( !db->mallocFailed ); + rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Register a new collation sequence with the database handle db. +*/ +SQLITE_API int sqlite3_create_collation_v2( + sqlite3* db, + const char *zName, + int enc, + void* pCtx, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDel)(void*) +){ + int rc; + sqlite3_mutex_enter(db->mutex); + assert( !db->mallocFailed ); + rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Register a new collation sequence with the database handle db. +*/ +SQLITE_API int sqlite3_create_collation16( + sqlite3* db, + const void *zName, + int enc, + void* pCtx, + int(*xCompare)(void*,int,const void*,int,const void*) +){ + int rc = SQLITE_OK; + char *zName8; + sqlite3_mutex_enter(db->mutex); + assert( !db->mallocFailed ); + zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); + if( zName8 ){ + rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); + sqlite3DbFree(db, zName8); + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Register a collation sequence factory callback with the database handle +** db. Replace any previously installed collation sequence factory. +*/ +SQLITE_API int sqlite3_collation_needed( + sqlite3 *db, + void *pCollNeededArg, + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) +){ + sqlite3_mutex_enter(db->mutex); + db->xCollNeeded = xCollNeeded; + db->xCollNeeded16 = 0; + db->pCollNeededArg = pCollNeededArg; + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Register a collation sequence factory callback with the database handle +** db. Replace any previously installed collation sequence factory. +*/ +SQLITE_API int sqlite3_collation_needed16( + sqlite3 *db, + void *pCollNeededArg, + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) +){ + sqlite3_mutex_enter(db->mutex); + db->xCollNeeded = 0; + db->xCollNeeded16 = xCollNeeded16; + db->pCollNeededArg = pCollNeededArg; + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} +#endif /* SQLITE_OMIT_UTF16 */ + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** This function is now an anachronism. It used to be used to recover from a +** malloc() failure, but SQLite now does this automatically. +*/ +SQLITE_API int sqlite3_global_recover(void){ + return SQLITE_OK; +} +#endif + +/* +** Test to see whether or not the database connection is in autocommit +** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on +** by default. Autocommit is disabled by a BEGIN statement and reenabled +** by the next COMMIT or ROLLBACK. +*/ +SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){ + return db->autoCommit; +} + +/* +** The following routines are subtitutes for constants SQLITE_CORRUPT, +** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error +** constants. They server two purposes: +** +** 1. Serve as a convenient place to set a breakpoint in a debugger +** to detect when version error conditions occurs. +** +** 2. Invoke sqlite3_log() to provide the source code location where +** a low-level error is first detected. +*/ +SQLITE_PRIVATE int sqlite3CorruptError(int lineno){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_CORRUPT, + "database corruption at line %d of [%.10s]", + lineno, 20+sqlite3_sourceid()); + return SQLITE_CORRUPT; +} +SQLITE_PRIVATE int sqlite3MisuseError(int lineno){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_MISUSE, + "misuse at line %d of [%.10s]", + lineno, 20+sqlite3_sourceid()); + return SQLITE_MISUSE; +} +SQLITE_PRIVATE int sqlite3CantopenError(int lineno){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_CANTOPEN, + "cannot open file at line %d of [%.10s]", + lineno, 20+sqlite3_sourceid()); + return SQLITE_CANTOPEN; +} + + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** This is a convenience routine that makes sure that all thread-specific +** data for this thread has been deallocated. +** +** SQLite no longer uses thread-specific data so this routine is now a +** no-op. It is retained for historical compatibility. +*/ +SQLITE_API void sqlite3_thread_cleanup(void){ +} +#endif + +/* +** Return meta information about a specific column of a database table. +** See comment in sqlite3.h (sqlite.h.in) for details. +*/ +#ifdef SQLITE_ENABLE_COLUMN_METADATA +SQLITE_API int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +){ + int rc; + char *zErrMsg = 0; + Table *pTab = 0; + Column *pCol = 0; + int iCol; + + char const *zDataType = 0; + char const *zCollSeq = 0; + int notnull = 0; + int primarykey = 0; + int autoinc = 0; + + /* Ensure the database schema has been loaded */ + sqlite3_mutex_enter(db->mutex); + sqlite3BtreeEnterAll(db); + rc = sqlite3Init(db, &zErrMsg); + if( SQLITE_OK!=rc ){ + goto error_out; + } + + /* Locate the table in question */ + pTab = sqlite3FindTable(db, zTableName, zDbName); + if( !pTab || pTab->pSelect ){ + pTab = 0; + goto error_out; + } + + /* Find the column for which info is requested */ + if( sqlite3IsRowid(zColumnName) ){ + iCol = pTab->iPKey; + if( iCol>=0 ){ + pCol = &pTab->aCol[iCol]; + } + }else{ + for(iCol=0; iColnCol; iCol++){ + pCol = &pTab->aCol[iCol]; + if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ + break; + } + } + if( iCol==pTab->nCol ){ + pTab = 0; + goto error_out; + } + } + + /* The following block stores the meta information that will be returned + ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey + ** and autoinc. At this point there are two possibilities: + ** + ** 1. The specified column name was rowid", "oid" or "_rowid_" + ** and there is no explicitly declared IPK column. + ** + ** 2. The table is not a view and the column name identified an + ** explicitly declared column. Copy meta information from *pCol. + */ + if( pCol ){ + zDataType = pCol->zType; + zCollSeq = pCol->zColl; + notnull = pCol->notNull!=0; + primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; + autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; + }else{ + zDataType = "INTEGER"; + primarykey = 1; + } + if( !zCollSeq ){ + zCollSeq = "BINARY"; + } + +error_out: + sqlite3BtreeLeaveAll(db); + + /* Whether the function call succeeded or failed, set the output parameters + ** to whatever their local counterparts contain. If an error did occur, + ** this has the effect of zeroing all output parameters. + */ + if( pzDataType ) *pzDataType = zDataType; + if( pzCollSeq ) *pzCollSeq = zCollSeq; + if( pNotNull ) *pNotNull = notnull; + if( pPrimaryKey ) *pPrimaryKey = primarykey; + if( pAutoinc ) *pAutoinc = autoinc; + + if( SQLITE_OK==rc && !pTab ){ + sqlite3DbFree(db, zErrMsg); + zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, + zColumnName); + rc = SQLITE_ERROR; + } + sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg); + sqlite3DbFree(db, zErrMsg); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} +#endif + +/* +** Sleep for a little while. Return the amount of time slept. +*/ +SQLITE_API int sqlite3_sleep(int ms){ + sqlite3_vfs *pVfs; + int rc; + pVfs = sqlite3_vfs_find(0); + if( pVfs==0 ) return 0; + + /* This function works in milliseconds, but the underlying OsSleep() + ** API uses microseconds. Hence the 1000's. + */ + rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); + return rc; +} + +/* +** Enable or disable the extended result codes. +*/ +SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ + sqlite3_mutex_enter(db->mutex); + db->errMask = onoff ? 0xffffffff : 0xff; + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +/* +** Invoke the xFileControl method on a particular database. +*/ +SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ + int rc = SQLITE_ERROR; + Btree *pBtree; + + sqlite3_mutex_enter(db->mutex); + pBtree = sqlite3DbNameToBtree(db, zDbName); + if( pBtree ){ + Pager *pPager; + sqlite3_file *fd; + sqlite3BtreeEnter(pBtree); + pPager = sqlite3BtreePager(pBtree); + assert( pPager!=0 ); + fd = sqlite3PagerFile(pPager); + assert( fd!=0 ); + if( op==SQLITE_FCNTL_FILE_POINTER ){ + *(sqlite3_file**)pArg = fd; + rc = SQLITE_OK; + }else if( fd->pMethods ){ + rc = sqlite3OsFileControl(fd, op, pArg); + }else{ + rc = SQLITE_NOTFOUND; + } + sqlite3BtreeLeave(pBtree); + } + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Interface to the testing logic. +*/ +SQLITE_API int sqlite3_test_control(int op, ...){ + int rc = 0; +#ifndef SQLITE_OMIT_BUILTIN_TEST + va_list ap; + va_start(ap, op); + switch( op ){ + + /* + ** Save the current state of the PRNG. + */ + case SQLITE_TESTCTRL_PRNG_SAVE: { + sqlite3PrngSaveState(); + break; + } + + /* + ** Restore the state of the PRNG to the last state saved using + ** PRNG_SAVE. If PRNG_SAVE has never before been called, then + ** this verb acts like PRNG_RESET. + */ + case SQLITE_TESTCTRL_PRNG_RESTORE: { + sqlite3PrngRestoreState(); + break; + } + + /* + ** Reset the PRNG back to its uninitialized state. The next call + ** to sqlite3_randomness() will reseed the PRNG using a single call + ** to the xRandomness method of the default VFS. + */ + case SQLITE_TESTCTRL_PRNG_RESET: { + sqlite3PrngResetState(); + break; + } + + /* + ** sqlite3_test_control(BITVEC_TEST, size, program) + ** + ** Run a test against a Bitvec object of size. The program argument + ** is an array of integers that defines the test. Return -1 on a + ** memory allocation error, 0 on success, or non-zero for an error. + ** See the sqlite3BitvecBuiltinTest() for additional information. + */ + case SQLITE_TESTCTRL_BITVEC_TEST: { + int sz = va_arg(ap, int); + int *aProg = va_arg(ap, int*); + rc = sqlite3BitvecBuiltinTest(sz, aProg); + break; + } + + /* + ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) + ** + ** Register hooks to call to indicate which malloc() failures + ** are benign. + */ + case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { + typedef void (*void_function)(void); + void_function xBenignBegin; + void_function xBenignEnd; + xBenignBegin = va_arg(ap, void_function); + xBenignEnd = va_arg(ap, void_function); + sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); + break; + } + + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) + ** + ** Set the PENDING byte to the value in the argument, if X>0. + ** Make no changes if X==0. Return the value of the pending byte + ** as it existing before this routine was called. + ** + ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in + ** an incompatible database file format. Changing the PENDING byte + ** while any database connection is open results in undefined and + ** dileterious behavior. + */ + case SQLITE_TESTCTRL_PENDING_BYTE: { + rc = PENDING_BYTE; +#ifndef SQLITE_OMIT_WSD + { + unsigned int newVal = va_arg(ap, unsigned int); + if( newVal ) sqlite3PendingByte = newVal; + } +#endif + break; + } + + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) + ** + ** This action provides a run-time test to see whether or not + ** assert() was enabled at compile-time. If X is true and assert() + ** is enabled, then the return value is true. If X is true and + ** assert() is disabled, then the return value is zero. If X is + ** false and assert() is enabled, then the assertion fires and the + ** process aborts. If X is false and assert() is disabled, then the + ** return value is zero. + */ + case SQLITE_TESTCTRL_ASSERT: { + volatile int x = 0; + assert( (x = va_arg(ap,int))!=0 ); + rc = x; + break; + } + + + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) + ** + ** This action provides a run-time test to see how the ALWAYS and + ** NEVER macros were defined at compile-time. + ** + ** The return value is ALWAYS(X). + ** + ** The recommended test is X==2. If the return value is 2, that means + ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the + ** default setting. If the return value is 1, then ALWAYS() is either + ** hard-coded to true or else it asserts if its argument is false. + ** The first behavior (hard-coded to true) is the case if + ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second + ** behavior (assert if the argument to ALWAYS() is false) is the case if + ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. + ** + ** The run-time test procedure might look something like this: + ** + ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ + ** // ALWAYS() and NEVER() are no-op pass-through macros + ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ + ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. + ** }else{ + ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. + ** } + */ + case SQLITE_TESTCTRL_ALWAYS: { + int x = va_arg(ap,int); + rc = ALWAYS(x); + break; + } + + /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) + ** + ** Set the nReserve size to N for the main database on the database + ** connection db. + */ + case SQLITE_TESTCTRL_RESERVE: { + sqlite3 *db = va_arg(ap, sqlite3*); + int x = va_arg(ap,int); + sqlite3_mutex_enter(db->mutex); + sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); + sqlite3_mutex_leave(db->mutex); + break; + } + + /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) + ** + ** Enable or disable various optimizations for testing purposes. The + ** argument N is a bitmask of optimizations to be disabled. For normal + ** operation N should be 0. The idea is that a test program (like the + ** SQL Logic Test or SLT test module) can run the same SQL multiple times + ** with various optimizations disabled to verify that the same answer + ** is obtained in every case. + */ + case SQLITE_TESTCTRL_OPTIMIZATIONS: { + sqlite3 *db = va_arg(ap, sqlite3*); + db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); + break; + } + +#ifdef SQLITE_N_KEYWORD + /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) + ** + ** If zWord is a keyword recognized by the parser, then return the + ** number of keywords. Or if zWord is not a keyword, return 0. + ** + ** This test feature is only available in the amalgamation since + ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite + ** is built using separate source files. + */ + case SQLITE_TESTCTRL_ISKEYWORD: { + const char *zWord = va_arg(ap, const char*); + int n = sqlite3Strlen30(zWord); + rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; + break; + } +#endif + + /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); + ** + ** Pass pFree into sqlite3ScratchFree(). + ** If sz>0 then allocate a scratch buffer into pNew. + */ + case SQLITE_TESTCTRL_SCRATCHMALLOC: { + void *pFree, **ppNew; + int sz; + sz = va_arg(ap, int); + ppNew = va_arg(ap, void**); + pFree = va_arg(ap, void*); + if( sz ) *ppNew = sqlite3ScratchMalloc(sz); + sqlite3ScratchFree(pFree); + break; + } + + /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); + ** + ** If parameter onoff is non-zero, configure the wrappers so that all + ** subsequent calls to localtime() and variants fail. If onoff is zero, + ** undo this setting. + */ + case SQLITE_TESTCTRL_LOCALTIME_FAULT: { + sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); + break; + } + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) + /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, + ** sqlite3_stmt*,const char**); + ** + ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds + ** a string that describes the optimized parse tree. This test-control + ** returns a pointer to that string. + */ + case SQLITE_TESTCTRL_EXPLAIN_STMT: { + sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*); + const char **pzRet = va_arg(ap, const char**); + *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt); + break; + } +#endif + + } + va_end(ap); +#endif /* SQLITE_OMIT_BUILTIN_TEST */ + return rc; +} + +/* +** This is a utility routine, useful to VFS implementations, that checks +** to see if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of the query parameter. +** +** The zFilename argument is the filename pointer passed into the xOpen() +** method of a VFS implementation. The zParam argument is the name of the +** query parameter we seek. This routine returns the value of the zParam +** parameter if it exists. If the parameter does not exist, this routine +** returns a NULL pointer. +*/ +SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ + if( zFilename==0 ) return 0; + zFilename += sqlite3Strlen30(zFilename) + 1; + while( zFilename[0] ){ + int x = strcmp(zFilename, zParam); + zFilename += sqlite3Strlen30(zFilename) + 1; + if( x==0 ) return zFilename; + zFilename += sqlite3Strlen30(zFilename) + 1; + } + return 0; +} + +/* +** Return a boolean value for a query parameter. +*/ +SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ + const char *z = sqlite3_uri_parameter(zFilename, zParam); + bDflt = bDflt!=0; + return z ? sqlite3GetBoolean(z, bDflt) : bDflt; +} + +/* +** Return a 64-bit integer value for a query parameter. +*/ +SQLITE_API sqlite3_int64 sqlite3_uri_int64( + const char *zFilename, /* Filename as passed to xOpen */ + const char *zParam, /* URI parameter sought */ + sqlite3_int64 bDflt /* return if parameter is missing */ +){ + const char *z = sqlite3_uri_parameter(zFilename, zParam); + sqlite3_int64 v; + if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){ + bDflt = v; + } + return bDflt; +} + +/* +** Return the Btree pointer identified by zDbName. Return NULL if not found. +*/ +SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ + int i; + for(i=0; inDb; i++){ + if( db->aDb[i].pBt + && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0) + ){ + return db->aDb[i].pBt; + } + } + return 0; +} + +/* +** Return the filename of the database associated with a database +** connection. +*/ +SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ + Btree *pBt = sqlite3DbNameToBtree(db, zDbName); + return pBt ? sqlite3BtreeGetFilename(pBt) : 0; +} + +/* +** Return 1 if database is read-only or 0 if read/write. Return -1 if +** no such database exists. +*/ +SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ + Btree *pBt = sqlite3DbNameToBtree(db, zDbName); + return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1; +} + +/************** End of main.c ************************************************/ +/************** Begin file notify.c ******************************************/ +/* +** 2009 March 3 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the implementation of the sqlite3_unlock_notify() +** API method and its associated functionality. +*/ + +/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */ +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + +/* +** Public interfaces: +** +** sqlite3ConnectionBlocked() +** sqlite3ConnectionUnlocked() +** sqlite3ConnectionClosed() +** sqlite3_unlock_notify() +*/ + +#define assertMutexHeld() \ + assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) + +/* +** Head of a linked list of all sqlite3 objects created by this process +** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection +** is not NULL. This variable may only accessed while the STATIC_MASTER +** mutex is held. +*/ +static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; + +#ifndef NDEBUG +/* +** This function is a complex assert() that verifies the following +** properties of the blocked connections list: +** +** 1) Each entry in the list has a non-NULL value for either +** pUnlockConnection or pBlockingConnection, or both. +** +** 2) All entries in the list that share a common value for +** xUnlockNotify are grouped together. +** +** 3) If the argument db is not NULL, then none of the entries in the +** blocked connections list have pUnlockConnection or pBlockingConnection +** set to db. This is used when closing connection db. +*/ +static void checkListProperties(sqlite3 *db){ + sqlite3 *p; + for(p=sqlite3BlockedList; p; p=p->pNextBlocked){ + int seen = 0; + sqlite3 *p2; + + /* Verify property (1) */ + assert( p->pUnlockConnection || p->pBlockingConnection ); + + /* Verify property (2) */ + for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ + if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; + assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); + assert( db==0 || p->pUnlockConnection!=db ); + assert( db==0 || p->pBlockingConnection!=db ); + } + } +} +#else +# define checkListProperties(x) +#endif + +/* +** Remove connection db from the blocked connections list. If connection +** db is not currently a part of the list, this function is a no-op. +*/ +static void removeFromBlockedList(sqlite3 *db){ + sqlite3 **pp; + assertMutexHeld(); + for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ + if( *pp==db ){ + *pp = (*pp)->pNextBlocked; + break; + } + } +} + +/* +** Add connection db to the blocked connections list. It is assumed +** that it is not already a part of the list. +*/ +static void addToBlockedList(sqlite3 *db){ + sqlite3 **pp; + assertMutexHeld(); + for( + pp=&sqlite3BlockedList; + *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; + pp=&(*pp)->pNextBlocked + ); + db->pNextBlocked = *pp; + *pp = db; +} + +/* +** Obtain the STATIC_MASTER mutex. +*/ +static void enterMutex(void){ + sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); + checkListProperties(0); +} + +/* +** Release the STATIC_MASTER mutex. +*/ +static void leaveMutex(void){ + assertMutexHeld(); + checkListProperties(0); + sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} + +/* +** Register an unlock-notify callback. +** +** This is called after connection "db" has attempted some operation +** but has received an SQLITE_LOCKED error because another connection +** (call it pOther) in the same process was busy using the same shared +** cache. pOther is found by looking at db->pBlockingConnection. +** +** If there is no blocking connection, the callback is invoked immediately, +** before this routine returns. +** +** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate +** a deadlock. +** +** Otherwise, make arrangements to invoke xNotify when pOther drops +** its locks. +** +** Each call to this routine overrides any prior callbacks registered +** on the same "db". If xNotify==0 then any prior callbacks are immediately +** cancelled. +*/ +SQLITE_API int sqlite3_unlock_notify( + sqlite3 *db, + void (*xNotify)(void **, int), + void *pArg +){ + int rc = SQLITE_OK; + + sqlite3_mutex_enter(db->mutex); + enterMutex(); + + if( xNotify==0 ){ + removeFromBlockedList(db); + db->pBlockingConnection = 0; + db->pUnlockConnection = 0; + db->xUnlockNotify = 0; + db->pUnlockArg = 0; + }else if( 0==db->pBlockingConnection ){ + /* The blocking transaction has been concluded. Or there never was a + ** blocking transaction. In either case, invoke the notify callback + ** immediately. + */ + xNotify(&pArg, 1); + }else{ + sqlite3 *p; + + for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} + if( p ){ + rc = SQLITE_LOCKED; /* Deadlock detected. */ + }else{ + db->pUnlockConnection = db->pBlockingConnection; + db->xUnlockNotify = xNotify; + db->pUnlockArg = pArg; + removeFromBlockedList(db); + addToBlockedList(db); + } + } + + leaveMutex(); + assert( !db->mallocFailed ); + sqlite3Error(db, rc, (rc?"database is deadlocked":0)); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** This function is called while stepping or preparing a statement +** associated with connection db. The operation will return SQLITE_LOCKED +** to the user because it requires a lock that will not be available +** until connection pBlocker concludes its current transaction. +*/ +SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ + enterMutex(); + if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ + addToBlockedList(db); + } + db->pBlockingConnection = pBlocker; + leaveMutex(); +} + +/* +** This function is called when +** the transaction opened by database db has just finished. Locks held +** by database connection db have been released. +** +** This function loops through each entry in the blocked connections +** list and does the following: +** +** 1) If the sqlite3.pBlockingConnection member of a list entry is +** set to db, then set pBlockingConnection=0. +** +** 2) If the sqlite3.pUnlockConnection member of a list entry is +** set to db, then invoke the configured unlock-notify callback and +** set pUnlockConnection=0. +** +** 3) If the two steps above mean that pBlockingConnection==0 and +** pUnlockConnection==0, remove the entry from the blocked connections +** list. +*/ +SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ + void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ + int nArg = 0; /* Number of entries in aArg[] */ + sqlite3 **pp; /* Iterator variable */ + void **aArg; /* Arguments to the unlock callback */ + void **aDyn = 0; /* Dynamically allocated space for aArg[] */ + void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ + + aArg = aStatic; + enterMutex(); /* Enter STATIC_MASTER mutex */ + + /* This loop runs once for each entry in the blocked-connections list. */ + for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ + sqlite3 *p = *pp; + + /* Step 1. */ + if( p->pBlockingConnection==db ){ + p->pBlockingConnection = 0; + } + + /* Step 2. */ + if( p->pUnlockConnection==db ){ + assert( p->xUnlockNotify ); + if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ + xUnlockNotify(aArg, nArg); + nArg = 0; + } + + sqlite3BeginBenignMalloc(); + assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); + assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); + if( (!aDyn && nArg==(int)ArraySize(aStatic)) + || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*))) + ){ + /* The aArg[] array needs to grow. */ + void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); + if( pNew ){ + memcpy(pNew, aArg, nArg*sizeof(void *)); + sqlite3_free(aDyn); + aDyn = aArg = pNew; + }else{ + /* This occurs when the array of context pointers that need to + ** be passed to the unlock-notify callback is larger than the + ** aStatic[] array allocated on the stack and the attempt to + ** allocate a larger array from the heap has failed. + ** + ** This is a difficult situation to handle. Returning an error + ** code to the caller is insufficient, as even if an error code + ** is returned the transaction on connection db will still be + ** closed and the unlock-notify callbacks on blocked connections + ** will go unissued. This might cause the application to wait + ** indefinitely for an unlock-notify callback that will never + ** arrive. + ** + ** Instead, invoke the unlock-notify callback with the context + ** array already accumulated. We can then clear the array and + ** begin accumulating any further context pointers without + ** requiring any dynamic allocation. This is sub-optimal because + ** it means that instead of one callback with a large array of + ** context pointers the application will receive two or more + ** callbacks with smaller arrays of context pointers, which will + ** reduce the applications ability to prioritize multiple + ** connections. But it is the best that can be done under the + ** circumstances. + */ + xUnlockNotify(aArg, nArg); + nArg = 0; + } + } + sqlite3EndBenignMalloc(); + + aArg[nArg++] = p->pUnlockArg; + xUnlockNotify = p->xUnlockNotify; + p->pUnlockConnection = 0; + p->xUnlockNotify = 0; + p->pUnlockArg = 0; + } + + /* Step 3. */ + if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){ + /* Remove connection p from the blocked connections list. */ + *pp = p->pNextBlocked; + p->pNextBlocked = 0; + }else{ + pp = &p->pNextBlocked; + } + } + + if( nArg!=0 ){ + xUnlockNotify(aArg, nArg); + } + sqlite3_free(aDyn); + leaveMutex(); /* Leave STATIC_MASTER mutex */ +} + +/* +** This is called when the database connection passed as an argument is +** being closed. The connection is removed from the blocked list. +*/ +SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){ + sqlite3ConnectionUnlocked(db); + enterMutex(); + removeFromBlockedList(db); + checkListProperties(db); + leaveMutex(); +} +#endif + +/************** End of notify.c **********************************************/ +/************** Begin file fts3.c ********************************************/ +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This is an SQLite module implementing full-text search. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ + +/* The full-text index is stored in a series of b+tree (-like) +** structures called segments which map terms to doclists. The +** structures are like b+trees in layout, but are constructed from the +** bottom up in optimal fashion and are not updatable. Since trees +** are built from the bottom up, things will be described from the +** bottom up. +** +** +**** Varints **** +** The basic unit of encoding is a variable-length integer called a +** varint. We encode variable-length integers in little-endian order +** using seven bits * per byte as follows: +** +** KEY: +** A = 0xxxxxxx 7 bits of data and one flag bit +** B = 1xxxxxxx 7 bits of data and one flag bit +** +** 7 bits - A +** 14 bits - BA +** 21 bits - BBA +** and so on. +** +** This is similar in concept to how sqlite encodes "varints" but +** the encoding is not the same. SQLite varints are big-endian +** are are limited to 9 bytes in length whereas FTS3 varints are +** little-endian and can be up to 10 bytes in length (in theory). +** +** Example encodings: +** +** 1: 0x01 +** 127: 0x7f +** 128: 0x81 0x00 +** +** +**** Document lists **** +** A doclist (document list) holds a docid-sorted list of hits for a +** given term. Doclists hold docids and associated token positions. +** A docid is the unique integer identifier for a single document. +** A position is the index of a word within the document. The first +** word of the document has a position of 0. +** +** FTS3 used to optionally store character offsets using a compile-time +** option. But that functionality is no longer supported. +** +** A doclist is stored like this: +** +** array { +** varint docid; (delta from previous doclist) +** array { (position list for column 0) +** varint position; (2 more than the delta from previous position) +** } +** array { +** varint POS_COLUMN; (marks start of position list for new column) +** varint column; (index of new column) +** array { +** varint position; (2 more than the delta from previous position) +** } +** } +** varint POS_END; (marks end of positions for this document. +** } +** +** Here, array { X } means zero or more occurrences of X, adjacent in +** memory. A "position" is an index of a token in the token stream +** generated by the tokenizer. Note that POS_END and POS_COLUMN occur +** in the same logical place as the position element, and act as sentinals +** ending a position list array. POS_END is 0. POS_COLUMN is 1. +** The positions numbers are not stored literally but rather as two more +** than the difference from the prior position, or the just the position plus +** 2 for the first position. Example: +** +** label: A B C D E F G H I J K +** value: 123 5 9 1 1 14 35 0 234 72 0 +** +** The 123 value is the first docid. For column zero in this document +** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1 +** at D signals the start of a new column; the 1 at E indicates that the +** new column is column number 1. There are two positions at 12 and 45 +** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The +** 234 at I is the delta to next docid (357). It has one position 70 +** (72-2) and then terminates with the 0 at K. +** +** A "position-list" is the list of positions for multiple columns for +** a single docid. A "column-list" is the set of positions for a single +** column. Hence, a position-list consists of one or more column-lists, +** a document record consists of a docid followed by a position-list and +** a doclist consists of one or more document records. +** +** A bare doclist omits the position information, becoming an +** array of varint-encoded docids. +** +**** Segment leaf nodes **** +** Segment leaf nodes store terms and doclists, ordered by term. Leaf +** nodes are written using LeafWriter, and read using LeafReader (to +** iterate through a single leaf node's data) and LeavesReader (to +** iterate through a segment's entire leaf layer). Leaf nodes have +** the format: +** +** varint iHeight; (height from leaf level, always 0) +** varint nTerm; (length of first term) +** char pTerm[nTerm]; (content of first term) +** varint nDoclist; (length of term's associated doclist) +** char pDoclist[nDoclist]; (content of doclist) +** array { +** (further terms are delta-encoded) +** varint nPrefix; (length of prefix shared with previous term) +** varint nSuffix; (length of unshared suffix) +** char pTermSuffix[nSuffix];(unshared suffix of next term) +** varint nDoclist; (length of term's associated doclist) +** char pDoclist[nDoclist]; (content of doclist) +** } +** +** Here, array { X } means zero or more occurrences of X, adjacent in +** memory. +** +** Leaf nodes are broken into blocks which are stored contiguously in +** the %_segments table in sorted order. This means that when the end +** of a node is reached, the next term is in the node with the next +** greater node id. +** +** New data is spilled to a new leaf node when the current node +** exceeds LEAF_MAX bytes (default 2048). New data which itself is +** larger than STANDALONE_MIN (default 1024) is placed in a standalone +** node (a leaf node with a single term and doclist). The goal of +** these settings is to pack together groups of small doclists while +** making it efficient to directly access large doclists. The +** assumption is that large doclists represent terms which are more +** likely to be query targets. +** +** TODO(shess) It may be useful for blocking decisions to be more +** dynamic. For instance, it may make more sense to have a 2.5k leaf +** node rather than splitting into 2k and .5k nodes. My intuition is +** that this might extend through 2x or 4x the pagesize. +** +** +**** Segment interior nodes **** +** Segment interior nodes store blockids for subtree nodes and terms +** to describe what data is stored by the each subtree. Interior +** nodes are written using InteriorWriter, and read using +** InteriorReader. InteriorWriters are created as needed when +** SegmentWriter creates new leaf nodes, or when an interior node +** itself grows too big and must be split. The format of interior +** nodes: +** +** varint iHeight; (height from leaf level, always >0) +** varint iBlockid; (block id of node's leftmost subtree) +** optional { +** varint nTerm; (length of first term) +** char pTerm[nTerm]; (content of first term) +** array { +** (further terms are delta-encoded) +** varint nPrefix; (length of shared prefix with previous term) +** varint nSuffix; (length of unshared suffix) +** char pTermSuffix[nSuffix]; (unshared suffix of next term) +** } +** } +** +** Here, optional { X } means an optional element, while array { X } +** means zero or more occurrences of X, adjacent in memory. +** +** An interior node encodes n terms separating n+1 subtrees. The +** subtree blocks are contiguous, so only the first subtree's blockid +** is encoded. The subtree at iBlockid will contain all terms less +** than the first term encoded (or all terms if no term is encoded). +** Otherwise, for terms greater than or equal to pTerm[i] but less +** than pTerm[i+1], the subtree for that term will be rooted at +** iBlockid+i. Interior nodes only store enough term data to +** distinguish adjacent children (if the rightmost term of the left +** child is "something", and the leftmost term of the right child is +** "wicked", only "w" is stored). +** +** New data is spilled to a new interior node at the same height when +** the current node exceeds INTERIOR_MAX bytes (default 2048). +** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing +** interior nodes and making the tree too skinny. The interior nodes +** at a given height are naturally tracked by interior nodes at +** height+1, and so on. +** +** +**** Segment directory **** +** The segment directory in table %_segdir stores meta-information for +** merging and deleting segments, and also the root node of the +** segment's tree. +** +** The root node is the top node of the segment's tree after encoding +** the entire segment, restricted to ROOT_MAX bytes (default 1024). +** This could be either a leaf node or an interior node. If the top +** node requires more than ROOT_MAX bytes, it is flushed to %_segments +** and a new root interior node is generated (which should always fit +** within ROOT_MAX because it only needs space for 2 varints, the +** height and the blockid of the previous root). +** +** The meta-information in the segment directory is: +** level - segment level (see below) +** idx - index within level +** - (level,idx uniquely identify a segment) +** start_block - first leaf node +** leaves_end_block - last leaf node +** end_block - last block (including interior nodes) +** root - contents of root node +** +** If the root node is a leaf node, then start_block, +** leaves_end_block, and end_block are all 0. +** +** +**** Segment merging **** +** To amortize update costs, segments are grouped into levels and +** merged in batches. Each increase in level represents exponentially +** more documents. +** +** New documents (actually, document updates) are tokenized and +** written individually (using LeafWriter) to a level 0 segment, with +** incrementing idx. When idx reaches MERGE_COUNT (default 16), all +** level 0 segments are merged into a single level 1 segment. Level 1 +** is populated like level 0, and eventually MERGE_COUNT level 1 +** segments are merged to a single level 2 segment (representing +** MERGE_COUNT^2 updates), and so on. +** +** A segment merge traverses all segments at a given level in +** parallel, performing a straightforward sorted merge. Since segment +** leaf nodes are written in to the %_segments table in order, this +** merge traverses the underlying sqlite disk structures efficiently. +** After the merge, all segment blocks from the merged level are +** deleted. +** +** MERGE_COUNT controls how often we merge segments. 16 seems to be +** somewhat of a sweet spot for insertion performance. 32 and 64 show +** very similar performance numbers to 16 on insertion, though they're +** a tiny bit slower (perhaps due to more overhead in merge-time +** sorting). 8 is about 20% slower than 16, 4 about 50% slower than +** 16, 2 about 66% slower than 16. +** +** At query time, high MERGE_COUNT increases the number of segments +** which need to be scanned and merged. For instance, with 100k docs +** inserted: +** +** MERGE_COUNT segments +** 16 25 +** 8 12 +** 4 10 +** 2 6 +** +** This appears to have only a moderate impact on queries for very +** frequent terms (which are somewhat dominated by segment merge +** costs), and infrequent and non-existent terms still seem to be fast +** even with many segments. +** +** TODO(shess) That said, it would be nice to have a better query-side +** argument for MERGE_COUNT of 16. Also, it is possible/likely that +** optimizations to things like doclist merging will swing the sweet +** spot around. +** +** +** +**** Handling of deletions and updates **** +** Since we're using a segmented structure, with no docid-oriented +** index into the term index, we clearly cannot simply update the term +** index when a document is deleted or updated. For deletions, we +** write an empty doclist (varint(docid) varint(POS_END)), for updates +** we simply write the new doclist. Segment merges overwrite older +** data for a particular docid with newer data, so deletes or updates +** will eventually overtake the earlier data and knock it out. The +** query logic likewise merges doclists so that newer data knocks out +** older data. +*/ + +/************** Include fts3Int.h in the middle of fts3.c ********************/ +/************** Begin file fts3Int.h *****************************************/ +/* +** 2009 Nov 12 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +*/ +#ifndef _FTSINT_H +#define _FTSINT_H + +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif + +/* +** FTS4 is really an extension for FTS3. It is enabled using the +** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all +** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3. +*/ +#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) +# define SQLITE_ENABLE_FTS3 +#endif + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* If not building as part of the core, include sqlite3ext.h. */ +#ifndef SQLITE_CORE +SQLITE_EXTENSION_INIT3 +#endif + +/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/ +/************** Begin file fts3_tokenizer.h **********************************/ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _FTS3_TOKENIZER_H_ +#define _FTS3_TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ + +/* +** Structures used by the tokenizer interface. When a new tokenizer +** implementation is registered, the caller provides a pointer to +** an sqlite3_tokenizer_module containing pointers to the callback +** functions that make up an implementation. +** +** When an fts3 table is created, it passes any arguments passed to +** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the +** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer +** implementation. The xCreate() function in turn returns an +** sqlite3_tokenizer structure representing the specific tokenizer to +** be used for the fts3 table (customized by the tokenizer clause arguments). +** +** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() +** method is called. It returns an sqlite3_tokenizer_cursor object +** that may be used to tokenize a specific input buffer based on +** the tokenization rules supplied by a specific sqlite3_tokenizer +** object. +*/ +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; + +struct sqlite3_tokenizer_module { + + /* + ** Structure version. Should always be set to 0 or 1. + */ + int iVersion; + + /* + ** Create a new tokenizer. The values in the argv[] array are the + ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL + ** TABLE statement that created the fts3 table. For example, if + ** the following SQL is executed: + ** + ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) + ** + ** then argc is set to 2, and the argv[] array contains pointers + ** to the strings "arg1" and "arg2". + ** + ** This method should return either SQLITE_OK (0), or an SQLite error + ** code. If SQLITE_OK is returned, then *ppTokenizer should be set + ** to point at the newly created tokenizer structure. The generic + ** sqlite3_tokenizer.pModule variable should not be initialized by + ** this callback. The caller will do so. + */ + int (*xCreate)( + int argc, /* Size of argv array */ + const char *const*argv, /* Tokenizer argument strings */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + ); + + /* + ** Destroy an existing tokenizer. The fts3 module calls this method + ** exactly once for each successful call to xCreate(). + */ + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Create a tokenizer cursor to tokenize an input buffer. The caller + ** is responsible for ensuring that the input buffer remains valid + ** until the cursor is closed (using the xClose() method). + */ + int (*xOpen)( + sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ + const char *pInput, int nBytes, /* Input buffer */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ + ); + + /* + ** Destroy an existing tokenizer cursor. The fts3 module calls this + ** method exactly once for each successful call to xOpen(). + */ + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + + /* + ** Retrieve the next token from the tokenizer cursor pCursor. This + ** method should either return SQLITE_OK and set the values of the + ** "OUT" variables identified below, or SQLITE_DONE to indicate that + ** the end of the buffer has been reached, or an SQLite error code. + ** + ** *ppToken should be set to point at a buffer containing the + ** normalized version of the token (i.e. after any case-folding and/or + ** stemming has been performed). *pnBytes should be set to the length + ** of this buffer in bytes. The input text that generated the token is + ** identified by the byte offsets returned in *piStartOffset and + ** *piEndOffset. *piStartOffset should be set to the index of the first + ** byte of the token in the input buffer. *piEndOffset should be set + ** to the index of the first byte just past the end of the token in + ** the input buffer. + ** + ** The buffer *ppToken is set to point at is managed by the tokenizer + ** implementation. It is only required to be valid until the next call + ** to xNext() or xClose(). + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xNext)( + sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ + const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ + int *piStartOffset, /* OUT: Byte offset of token in input buffer */ + int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ + int *piPosition /* OUT: Number of tokens returned before this one */ + ); + + /*********************************************************************** + ** Methods below this point are only available if iVersion>=1. + */ + + /* + ** Configure the language id of a tokenizer cursor. + */ + int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid); +}; + +struct sqlite3_tokenizer { + const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +int fts3_global_term_cnt(int iTerm, int iCol); +int fts3_term_cnt(int iTerm, int iCol); + + +#endif /* _FTS3_TOKENIZER_H_ */ + +/************** End of fts3_tokenizer.h **************************************/ +/************** Continuing where we left off in fts3Int.h ********************/ +/************** Include fts3_hash.h in the middle of fts3Int.h ***************/ +/************** Begin file fts3_hash.h ***************************************/ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implementation +** used in SQLite. We've modified it slightly to serve as a standalone +** hash table implementation for the full-text indexing module. +** +*/ +#ifndef _FTS3_HASH_H_ +#define _FTS3_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct Fts3Hash Fts3Hash; +typedef struct Fts3HashElem Fts3HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, many of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +*/ +struct Fts3Hash { + char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ + char copyKey; /* True if copy of key made on insert */ + int count; /* Number of entries in this table */ + Fts3HashElem *first; /* The first element of the array */ + int htsize; /* Number of buckets in the hash table */ + struct _fts3ht { /* the hash table */ + int count; /* Number of entries with this hash */ + Fts3HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct Fts3HashElem { + Fts3HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + void *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** There are 2 different modes of operation for a hash table: +** +** FTS3_HASH_STRING pKey points to a string that is nKey bytes long +** (including the null-terminator, if any). Case +** is respected in comparisons. +** +** FTS3_HASH_BINARY pKey points to binary data nKey bytes long. +** memcmp() is used to compare keys. +** +** A copy of the key is made if the copyKey parameter to fts3HashInit is 1. +*/ +#define FTS3_HASH_STRING 1 +#define FTS3_HASH_BINARY 2 + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey); +SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData); +SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey); +SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*); +SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int); + +/* +** Shorthand for the functions above +*/ +#define fts3HashInit sqlite3Fts3HashInit +#define fts3HashInsert sqlite3Fts3HashInsert +#define fts3HashFind sqlite3Fts3HashFind +#define fts3HashClear sqlite3Fts3HashClear +#define fts3HashFindElem sqlite3Fts3HashFindElem + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** Fts3Hash h; +** Fts3HashElem *p; +** ... +** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){ +** SomeStructure *pData = fts3HashData(p); +** // do something with pData +** } +*/ +#define fts3HashFirst(H) ((H)->first) +#define fts3HashNext(E) ((E)->next) +#define fts3HashData(E) ((E)->data) +#define fts3HashKey(E) ((E)->pKey) +#define fts3HashKeysize(E) ((E)->nKey) + +/* +** Number of entries in a hash table +*/ +#define fts3HashCount(H) ((H)->count) + +#endif /* _FTS3_HASH_H_ */ + +/************** End of fts3_hash.h *******************************************/ +/************** Continuing where we left off in fts3Int.h ********************/ + +/* +** This constant determines the maximum depth of an FTS expression tree +** that the library will create and use. FTS uses recursion to perform +** various operations on the query tree, so the disadvantage of a large +** limit is that it may allow very large queries to use large amounts +** of stack space (perhaps causing a stack overflow). +*/ +#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH +# define SQLITE_FTS3_MAX_EXPR_DEPTH 12 +#endif + + +/* +** This constant controls how often segments are merged. Once there are +** FTS3_MERGE_COUNT segments of level N, they are merged into a single +** segment of level N+1. +*/ +#define FTS3_MERGE_COUNT 16 + +/* +** This is the maximum amount of data (in bytes) to store in the +** Fts3Table.pendingTerms hash table. Normally, the hash table is +** populated as documents are inserted/updated/deleted in a transaction +** and used to create a new segment when the transaction is committed. +** However if this limit is reached midway through a transaction, a new +** segment is created and the hash table cleared immediately. +*/ +#define FTS3_MAX_PENDING_DATA (1*1024*1024) + +/* +** Macro to return the number of elements in an array. SQLite has a +** similar macro called ArraySize(). Use a different name to avoid +** a collision when building an amalgamation with built-in FTS3. +*/ +#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0]))) + + +#ifndef MIN +# define MIN(x,y) ((x)<(y)?(x):(y)) +#endif +#ifndef MAX +# define MAX(x,y) ((x)>(y)?(x):(y)) +#endif + +/* +** Maximum length of a varint encoded integer. The varint format is different +** from that used by SQLite, so the maximum length is 10, not 9. +*/ +#define FTS3_VARINT_MAX 10 + +/* +** FTS4 virtual tables may maintain multiple indexes - one index of all terms +** in the document set and zero or more prefix indexes. All indexes are stored +** as one or more b+-trees in the %_segments and %_segdir tables. +** +** It is possible to determine which index a b+-tree belongs to based on the +** value stored in the "%_segdir.level" column. Given this value L, the index +** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with +** level values between 0 and 1023 (inclusive) belong to index 0, all levels +** between 1024 and 2047 to index 1, and so on. +** +** It is considered impossible for an index to use more than 1024 levels. In +** theory though this may happen, but only after at least +** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables. +*/ +#define FTS3_SEGDIR_MAXLEVEL 1024 +#define FTS3_SEGDIR_MAXLEVEL_STR "1024" + +/* +** The testcase() macro is only used by the amalgamation. If undefined, +** make it a no-op. +*/ +#ifndef testcase +# define testcase(X) +#endif + +/* +** Terminator values for position-lists and column-lists. +*/ +#define POS_COLUMN (1) /* Column-list terminator */ +#define POS_END (0) /* Position-list terminator */ + +/* +** This section provides definitions to allow the +** FTS3 extension to be compiled outside of the +** amalgamation. +*/ +#ifndef SQLITE_AMALGAMATION +/* +** Macros indicating that conditional expressions are always true or +** false. +*/ +#ifdef SQLITE_COVERAGE_TEST +# define ALWAYS(x) (1) +# define NEVER(X) (0) +#else +# define ALWAYS(x) (x) +# define NEVER(x) (x) +#endif + +/* +** Internal types used by SQLite. +*/ +typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */ +typedef short int i16; /* 2-byte (or larger) signed integer */ +typedef unsigned int u32; /* 4-byte unsigned integer */ +typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */ +typedef sqlite3_int64 i64; /* 8-byte signed integer */ + +/* +** Macro used to suppress compiler warnings for unused parameters. +*/ +#define UNUSED_PARAMETER(x) (void)(x) + +/* +** Activate assert() only if SQLITE_TEST is enabled. +*/ +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif + +/* +** The TESTONLY macro is used to enclose variable declarations or +** other bits of code that are needed to support the arguments +** within testcase() and assert() macros. +*/ +#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) +# define TESTONLY(X) X +#else +# define TESTONLY(X) +#endif + +#endif /* SQLITE_AMALGAMATION */ + +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int sqlite3Fts3Corrupt(void); +# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt() +#else +# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB +#endif + +typedef struct Fts3Table Fts3Table; +typedef struct Fts3Cursor Fts3Cursor; +typedef struct Fts3Expr Fts3Expr; +typedef struct Fts3Phrase Fts3Phrase; +typedef struct Fts3PhraseToken Fts3PhraseToken; + +typedef struct Fts3Doclist Fts3Doclist; +typedef struct Fts3SegFilter Fts3SegFilter; +typedef struct Fts3DeferredToken Fts3DeferredToken; +typedef struct Fts3SegReader Fts3SegReader; +typedef struct Fts3MultiSegReader Fts3MultiSegReader; + +/* +** A connection to a fulltext index is an instance of the following +** structure. The xCreate and xConnect methods create an instance +** of this structure and xDestroy and xDisconnect free that instance. +** All other methods receive a pointer to the structure as one of their +** arguments. +*/ +struct Fts3Table { + sqlite3_vtab base; /* Base class used by SQLite core */ + sqlite3 *db; /* The database connection */ + const char *zDb; /* logical database name */ + const char *zName; /* virtual table name */ + int nColumn; /* number of named columns in virtual table */ + char **azColumn; /* column names. malloced */ + u8 *abNotindexed; /* True for 'notindexed' columns */ + sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ + char *zContentTbl; /* content=xxx option, or NULL */ + char *zLanguageid; /* languageid=xxx option, or NULL */ + u8 bAutoincrmerge; /* True if automerge=1 */ + u32 nLeafAdd; /* Number of leaf blocks added this trans */ + + /* Precompiled statements used by the implementation. Each of these + ** statements is run and reset within a single virtual table API call. + */ + sqlite3_stmt *aStmt[37]; + + char *zReadExprlist; + char *zWriteExprlist; + + int nNodeSize; /* Soft limit for node size */ + u8 bFts4; /* True for FTS4, false for FTS3 */ + u8 bHasStat; /* True if %_stat table exists */ + u8 bHasDocsize; /* True if %_docsize table exists */ + u8 bDescIdx; /* True if doclists are in reverse order */ + u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */ + int nPgsz; /* Page size for host database */ + char *zSegmentsTbl; /* Name of %_segments table */ + sqlite3_blob *pSegments; /* Blob handle open on %_segments table */ + + /* + ** The following array of hash tables is used to buffer pending index + ** updates during transactions. All pending updates buffered at any one + ** time must share a common language-id (see the FTS4 langid= feature). + ** The current language id is stored in variable iPrevLangid. + ** + ** A single FTS4 table may have multiple full-text indexes. For each index + ** there is an entry in the aIndex[] array. Index 0 is an index of all the + ** terms that appear in the document set. Each subsequent index in aIndex[] + ** is an index of prefixes of a specific length. + ** + ** Variable nPendingData contains an estimate the memory consumed by the + ** pending data structures, including hash table overhead, but not including + ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash + ** tables are flushed to disk. Variable iPrevDocid is the docid of the most + ** recently inserted record. + */ + int nIndex; /* Size of aIndex[] */ + struct Fts3Index { + int nPrefix; /* Prefix length (0 for main terms index) */ + Fts3Hash hPending; /* Pending terms table for this index */ + } *aIndex; + int nMaxPendingData; /* Max pending data before flush to disk */ + int nPendingData; /* Current bytes of pending data */ + sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */ + int iPrevLangid; /* Langid of recently inserted document */ + +#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) + /* State variables used for validating that the transaction control + ** methods of the virtual table are called at appropriate times. These + ** values do not contribute to FTS functionality; they are used for + ** verifying the operation of the SQLite core. + */ + int inTransaction; /* True after xBegin but before xCommit/xRollback */ + int mxSavepoint; /* Largest valid xSavepoint integer */ +#endif + +#ifdef SQLITE_TEST + /* True to disable the incremental doclist optimization. This is controled + ** by special insert command 'test-no-incr-doclist'. */ + int bNoIncrDoclist; +#endif +}; + +/* +** When the core wants to read from the virtual table, it creates a +** virtual table cursor (an instance of the following structure) using +** the xOpen method. Cursors are destroyed using the xClose method. +*/ +struct Fts3Cursor { + sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + i16 eSearch; /* Search strategy (see below) */ + u8 isEof; /* True if at End Of Results */ + u8 isRequireSeek; /* True if must seek pStmt to %_content row */ + sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ + Fts3Expr *pExpr; /* Parsed MATCH query string */ + int iLangid; /* Language being queried for */ + int nPhrase; /* Number of matchable phrases in query */ + Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */ + sqlite3_int64 iPrevId; /* Previous id read from aDoclist */ + char *pNextId; /* Pointer into the body of aDoclist */ + char *aDoclist; /* List of docids for full-text queries */ + int nDoclist; /* Size of buffer at aDoclist */ + u8 bDesc; /* True to sort in descending order */ + int eEvalmode; /* An FTS3_EVAL_XX constant */ + int nRowAvg; /* Average size of database rows, in pages */ + sqlite3_int64 nDoc; /* Documents in table */ + i64 iMinDocid; /* Minimum docid to return */ + i64 iMaxDocid; /* Maximum docid to return */ + int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */ + u32 *aMatchinfo; /* Information about most recent match */ + int nMatchinfo; /* Number of elements in aMatchinfo[] */ + char *zMatchinfo; /* Matchinfo specification */ +}; + +#define FTS3_EVAL_FILTER 0 +#define FTS3_EVAL_NEXT 1 +#define FTS3_EVAL_MATCHINFO 2 + +/* +** The Fts3Cursor.eSearch member is always set to one of the following. +** Actualy, Fts3Cursor.eSearch can be greater than or equal to +** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index +** of the column to be searched. For example, in +** +** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d); +** SELECT docid FROM ex1 WHERE b MATCH 'one two three'; +** +** Because the LHS of the MATCH operator is 2nd column "b", +** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a, +** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1" +** indicating that all columns should be searched, +** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4. +*/ +#define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */ +#define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */ +#define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */ + +/* +** The lower 16-bits of the sqlite3_index_info.idxNum value set by +** the xBestIndex() method contains the Fts3Cursor.eSearch value described +** above. The upper 16-bits contain a combination of the following +** bits, used to describe extra constraints on full-text searches. +*/ +#define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */ +#define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */ +#define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */ + +struct Fts3Doclist { + char *aAll; /* Array containing doclist (or NULL) */ + int nAll; /* Size of a[] in bytes */ + char *pNextDocid; /* Pointer to next docid */ + + sqlite3_int64 iDocid; /* Current docid (if pList!=0) */ + int bFreeList; /* True if pList should be sqlite3_free()d */ + char *pList; /* Pointer to position list following iDocid */ + int nList; /* Length of position list */ +}; + +/* +** A "phrase" is a sequence of one or more tokens that must match in +** sequence. A single token is the base case and the most common case. +** For a sequence of tokens contained in double-quotes (i.e. "one two three") +** nToken will be the number of tokens in the string. +*/ +struct Fts3PhraseToken { + char *z; /* Text of the token */ + int n; /* Number of bytes in buffer z */ + int isPrefix; /* True if token ends with a "*" character */ + int bFirst; /* True if token must appear at position 0 */ + + /* Variables above this point are populated when the expression is + ** parsed (by code in fts3_expr.c). Below this point the variables are + ** used when evaluating the expression. */ + Fts3DeferredToken *pDeferred; /* Deferred token object for this token */ + Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */ +}; + +struct Fts3Phrase { + /* Cache of doclist for this phrase. */ + Fts3Doclist doclist; + int bIncr; /* True if doclist is loaded incrementally */ + int iDoclistToken; + + /* Variables below this point are populated by fts3_expr.c when parsing + ** a MATCH expression. Everything above is part of the evaluation phase. + */ + int nToken; /* Number of tokens in the phrase */ + int iColumn; /* Index of column this phrase must match */ + Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */ +}; + +/* +** A tree of these objects forms the RHS of a MATCH operator. +** +** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist +** points to a malloced buffer, size nDoclist bytes, containing the results +** of this phrase query in FTS3 doclist format. As usual, the initial +** "Length" field found in doclists stored on disk is omitted from this +** buffer. +** +** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global +** matchinfo data. If it is not NULL, it points to an array of size nCol*3, +** where nCol is the number of columns in the queried FTS table. The array +** is populated as follows: +** +** aMI[iCol*3 + 0] = Undefined +** aMI[iCol*3 + 1] = Number of occurrences +** aMI[iCol*3 + 2] = Number of rows containing at least one instance +** +** The aMI array is allocated using sqlite3_malloc(). It should be freed +** when the expression node is. +*/ +struct Fts3Expr { + int eType; /* One of the FTSQUERY_XXX values defined below */ + int nNear; /* Valid if eType==FTSQUERY_NEAR */ + Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */ + Fts3Expr *pLeft; /* Left operand */ + Fts3Expr *pRight; /* Right operand */ + Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */ + + /* The following are used by the fts3_eval.c module. */ + sqlite3_int64 iDocid; /* Current docid */ + u8 bEof; /* True this expression is at EOF already */ + u8 bStart; /* True if iDocid is valid */ + u8 bDeferred; /* True if this expression is entirely deferred */ + + u32 *aMI; +}; + +/* +** Candidate values for Fts3Query.eType. Note that the order of the first +** four values is in order of precedence when parsing expressions. For +** example, the following: +** +** "a OR b AND c NOT d NEAR e" +** +** is equivalent to: +** +** "a OR (b AND (c NOT (d NEAR e)))" +*/ +#define FTSQUERY_NEAR 1 +#define FTSQUERY_NOT 2 +#define FTSQUERY_AND 3 +#define FTSQUERY_OR 4 +#define FTSQUERY_PHRASE 5 + + +/* fts3_write.c */ +SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*); +SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *); +SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *); +SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *); +SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64, + sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**); +SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( + Fts3Table*,int,const char*,int,int,Fts3SegReader**); +SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *); +SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **); +SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*); + +SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **); +SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **); + +#ifndef SQLITE_DISABLE_FTS4_DEFERRED +SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *); +SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int); +SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *); +SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *); +SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *); +#else +# define sqlite3Fts3FreeDeferredTokens(x) +# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK +# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK +# define sqlite3Fts3FreeDeferredDoclists(x) +# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK +#endif + +SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *); +SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *); + +/* Special values interpreted by sqlite3SegReaderCursor() */ +#define FTS3_SEGCURSOR_PENDING -1 +#define FTS3_SEGCURSOR_ALL -2 + +SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*); +SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *); +SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *); + +SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, + int, int, int, const char *, int, int, int, Fts3MultiSegReader *); + +/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */ +#define FTS3_SEGMENT_REQUIRE_POS 0x00000001 +#define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002 +#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004 +#define FTS3_SEGMENT_PREFIX 0x00000008 +#define FTS3_SEGMENT_SCAN 0x00000010 +#define FTS3_SEGMENT_FIRST 0x00000020 + +/* Type passed as 4th argument to SegmentReaderIterate() */ +struct Fts3SegFilter { + const char *zTerm; + int nTerm; + int iCol; + int flags; +}; + +struct Fts3MultiSegReader { + /* Used internally by sqlite3Fts3SegReaderXXX() calls */ + Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */ + int nSegment; /* Size of apSegment array */ + int nAdvance; /* How many seg-readers to advance */ + Fts3SegFilter *pFilter; /* Pointer to filter object */ + char *aBuffer; /* Buffer to merge doclists in */ + int nBuffer; /* Allocated size of aBuffer[] in bytes */ + + int iColFilter; /* If >=0, filter for this column */ + int bRestart; + + /* Used by fts3.c only. */ + int nCost; /* Cost of running iterator */ + int bLookup; /* True if a lookup of a single entry. */ + + /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */ + char *zTerm; /* Pointer to term buffer */ + int nTerm; /* Size of zTerm in bytes */ + char *aDoclist; /* Pointer to doclist buffer */ + int nDoclist; /* Size of aDoclist[] in bytes */ +}; + +SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int); + +/* fts3.c */ +SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64); +SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *); +SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *); +SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64); +SQLITE_PRIVATE void sqlite3Fts3Dequote(char *); +SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*); +SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *); +SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *); +SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*); + +/* fts3_tokenizer.c */ +SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *); +SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *); +SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, + sqlite3_tokenizer **, char ** +); +SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char); + +/* fts3_snippet.c */ +SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*); +SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *, + const char *, const char *, int, int +); +SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *); + +/* fts3_expr.c */ +SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int, + char **, int, int, int, const char *, int, Fts3Expr **, char ** +); +SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *); +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db); +SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db); +#endif + +SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int, + sqlite3_tokenizer_cursor ** +); + +/* fts3_aux.c */ +SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db); + +SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *); + +SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( + Fts3Table*, Fts3MultiSegReader*, int, const char*, int); +SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( + Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *); +SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); +SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *); +SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr); + +/* fts3_tokenize_vtab.c */ +SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *); + +/* fts3_unicode2.c (functions generated by parsing unicode text files) */ +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 +SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int); +SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int); +SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int); +#endif + +#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */ +#endif /* _FTSINT_H */ + +/************** End of fts3Int.h *********************************************/ +/************** Continuing where we left off in fts3.c ***********************/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE) +# define SQLITE_CORE 1 +#endif + +/* #include */ +/* #include */ +/* #include */ +/* #include */ +/* #include */ +/* #include */ + +#ifndef SQLITE_CORE + SQLITE_EXTENSION_INIT1 +#endif + +static int fts3EvalNext(Fts3Cursor *pCsr); +static int fts3EvalStart(Fts3Cursor *pCsr); +static int fts3TermSegReaderCursor( + Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **); + +/* +** Write a 64-bit variable-length integer to memory starting at p[0]. +** The length of data written will be between 1 and FTS3_VARINT_MAX bytes. +** The number of bytes written is returned. +*/ +SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){ + unsigned char *q = (unsigned char *) p; + sqlite_uint64 vu = v; + do{ + *q++ = (unsigned char) ((vu & 0x7f) | 0x80); + vu >>= 7; + }while( vu!=0 ); + q[-1] &= 0x7f; /* turn off high bit in final byte */ + assert( q - (unsigned char *)p <= FTS3_VARINT_MAX ); + return (int) (q - (unsigned char *)p); +} + +/* +** Read a 64-bit variable-length integer from memory starting at p[0]. +** Return the number of bytes read, or 0 on error. +** The value is stored in *v. +*/ +SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){ + const unsigned char *q = (const unsigned char *) p; + sqlite_uint64 x = 0, y = 1; + while( (*q&0x80)==0x80 && q-(unsigned char *)p>= 7; + }while( v!=0 ); + return i; +} + +/* +** Convert an SQL-style quoted string into a normal string by removing +** the quote characters. The conversion is done in-place. If the +** input does not begin with a quote character, then this routine +** is a no-op. +** +** Examples: +** +** "abc" becomes abc +** 'xyz' becomes xyz +** [pqr] becomes pqr +** `mno` becomes mno +** +*/ +SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){ + char quote; /* Quote character (if any ) */ + + quote = z[0]; + if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ + int iIn = 1; /* Index of next byte to read from input */ + int iOut = 0; /* Index of next byte to write to output */ + + /* If the first byte was a '[', then the close-quote character is a ']' */ + if( quote=='[' ) quote = ']'; + + while( ALWAYS(z[iIn]) ){ + if( z[iIn]==quote ){ + if( z[iIn+1]!=quote ) break; + z[iOut++] = quote; + iIn += 2; + }else{ + z[iOut++] = z[iIn++]; + } + } + z[iOut] = '\0'; + } +} + +/* +** Read a single varint from the doclist at *pp and advance *pp to point +** to the first byte past the end of the varint. Add the value of the varint +** to *pVal. +*/ +static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){ + sqlite3_int64 iVal; + *pp += sqlite3Fts3GetVarint(*pp, &iVal); + *pVal += iVal; +} + +/* +** When this function is called, *pp points to the first byte following a +** varint that is part of a doclist (or position-list, or any other list +** of varints). This function moves *pp to point to the start of that varint, +** and sets *pVal by the varint value. +** +** Argument pStart points to the first byte of the doclist that the +** varint is part of. +*/ +static void fts3GetReverseVarint( + char **pp, + char *pStart, + sqlite3_int64 *pVal +){ + sqlite3_int64 iVal; + char *p; + + /* Pointer p now points at the first byte past the varint we are + ** interested in. So, unless the doclist is corrupt, the 0x80 bit is + ** clear on character p[-1]. */ + for(p = (*pp)-2; p>=pStart && *p&0x80; p--); + p++; + *pp = p; + + sqlite3Fts3GetVarint(p, &iVal); + *pVal = iVal; +} + +/* +** The xDisconnect() virtual table method. +*/ +static int fts3DisconnectMethod(sqlite3_vtab *pVtab){ + Fts3Table *p = (Fts3Table *)pVtab; + int i; + + assert( p->nPendingData==0 ); + assert( p->pSegments==0 ); + + /* Free any prepared statements held */ + for(i=0; iaStmt); i++){ + sqlite3_finalize(p->aStmt[i]); + } + sqlite3_free(p->zSegmentsTbl); + sqlite3_free(p->zReadExprlist); + sqlite3_free(p->zWriteExprlist); + sqlite3_free(p->zContentTbl); + sqlite3_free(p->zLanguageid); + + /* Invoke the tokenizer destructor to free the tokenizer. */ + p->pTokenizer->pModule->xDestroy(p->pTokenizer); + + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Construct one or more SQL statements from the format string given +** and then evaluate those statements. The success code is written +** into *pRc. +** +** If *pRc is initially non-zero then this routine is a no-op. +*/ +static void fts3DbExec( + int *pRc, /* Success code */ + sqlite3 *db, /* Database in which to run SQL */ + const char *zFormat, /* Format string for SQL */ + ... /* Arguments to the format string */ +){ + va_list ap; + char *zSql; + if( *pRc ) return; + va_start(ap, zFormat); + zSql = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + if( zSql==0 ){ + *pRc = SQLITE_NOMEM; + }else{ + *pRc = sqlite3_exec(db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } +} + +/* +** The xDestroy() virtual table method. +*/ +static int fts3DestroyMethod(sqlite3_vtab *pVtab){ + Fts3Table *p = (Fts3Table *)pVtab; + int rc = SQLITE_OK; /* Return code */ + const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */ + sqlite3 *db = p->db; /* Database handle */ + + /* Drop the shadow tables */ + if( p->zContentTbl==0 ){ + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName); + } + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName); + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName); + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName); + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName); + + /* If everything has worked, invoke fts3DisconnectMethod() to free the + ** memory associated with the Fts3Table structure and return SQLITE_OK. + ** Otherwise, return an SQLite error code. + */ + return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc); +} + + +/* +** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table +** passed as the first argument. This is done as part of the xConnect() +** and xCreate() methods. +** +** If *pRc is non-zero when this function is called, it is a no-op. +** Otherwise, if an error occurs, an SQLite error code is stored in *pRc +** before returning. +*/ +static void fts3DeclareVtab(int *pRc, Fts3Table *p){ + if( *pRc==SQLITE_OK ){ + int i; /* Iterator variable */ + int rc; /* Return code */ + char *zSql; /* SQL statement passed to declare_vtab() */ + char *zCols; /* List of user defined columns */ + const char *zLanguageid; + + zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid"); + sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); + + /* Create a list of user columns for the virtual table */ + zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]); + for(i=1; zCols && inColumn; i++){ + zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]); + } + + /* Create the whole "CREATE TABLE" statement to pass to SQLite */ + zSql = sqlite3_mprintf( + "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", + zCols, p->zName, zLanguageid + ); + if( !zCols || !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_declare_vtab(p->db, zSql); + } + + sqlite3_free(zSql); + sqlite3_free(zCols); + *pRc = rc; + } +} + +/* +** Create the %_stat table if it does not already exist. +*/ +SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){ + fts3DbExec(pRc, p->db, + "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'" + "(id INTEGER PRIMARY KEY, value BLOB);", + p->zDb, p->zName + ); + if( (*pRc)==SQLITE_OK ) p->bHasStat = 1; +} + +/* +** Create the backing store tables (%_content, %_segments and %_segdir) +** required by the FTS3 table passed as the only argument. This is done +** as part of the vtab xCreate() method. +** +** If the p->bHasDocsize boolean is true (indicating that this is an +** FTS4 table, not an FTS3 table) then also create the %_docsize and +** %_stat tables required by FTS4. +*/ +static int fts3CreateTables(Fts3Table *p){ + int rc = SQLITE_OK; /* Return code */ + int i; /* Iterator variable */ + sqlite3 *db = p->db; /* The database connection */ + + if( p->zContentTbl==0 ){ + const char *zLanguageid = p->zLanguageid; + char *zContentCols; /* Columns of %_content table */ + + /* Create a list of user columns for the content table */ + zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY"); + for(i=0; zContentCols && inColumn; i++){ + char *z = p->azColumn[i]; + zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z); + } + if( zLanguageid && zContentCols ){ + zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid); + } + if( zContentCols==0 ) rc = SQLITE_NOMEM; + + /* Create the content table */ + fts3DbExec(&rc, db, + "CREATE TABLE %Q.'%q_content'(%s)", + p->zDb, p->zName, zContentCols + ); + sqlite3_free(zContentCols); + } + + /* Create other tables */ + fts3DbExec(&rc, db, + "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);", + p->zDb, p->zName + ); + fts3DbExec(&rc, db, + "CREATE TABLE %Q.'%q_segdir'(" + "level INTEGER," + "idx INTEGER," + "start_block INTEGER," + "leaves_end_block INTEGER," + "end_block INTEGER," + "root BLOB," + "PRIMARY KEY(level, idx)" + ");", + p->zDb, p->zName + ); + if( p->bHasDocsize ){ + fts3DbExec(&rc, db, + "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);", + p->zDb, p->zName + ); + } + assert( p->bHasStat==p->bFts4 ); + if( p->bHasStat ){ + sqlite3Fts3CreateStatTable(&rc, p); + } + return rc; +} + +/* +** Store the current database page-size in bytes in p->nPgsz. +** +** If *pRc is non-zero when this function is called, it is a no-op. +** Otherwise, if an error occurs, an SQLite error code is stored in *pRc +** before returning. +*/ +static void fts3DatabasePageSize(int *pRc, Fts3Table *p){ + if( *pRc==SQLITE_OK ){ + int rc; /* Return code */ + char *zSql; /* SQL text "PRAGMA %Q.page_size" */ + sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */ + + zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb); + if( !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_step(pStmt); + p->nPgsz = sqlite3_column_int(pStmt, 0); + rc = sqlite3_finalize(pStmt); + }else if( rc==SQLITE_AUTH ){ + p->nPgsz = 1024; + rc = SQLITE_OK; + } + } + assert( p->nPgsz>0 || rc!=SQLITE_OK ); + sqlite3_free(zSql); + *pRc = rc; + } +} + +/* +** "Special" FTS4 arguments are column specifications of the following form: +** +** = +** +** There may not be whitespace surrounding the "=" character. The +** term may be quoted, but the may not. +*/ +static int fts3IsSpecialColumn( + const char *z, + int *pnKey, + char **pzValue +){ + char *zValue; + const char *zCsr = z; + + while( *zCsr!='=' ){ + if( *zCsr=='\0' ) return 0; + zCsr++; + } + + *pnKey = (int)(zCsr-z); + zValue = sqlite3_mprintf("%s", &zCsr[1]); + if( zValue ){ + sqlite3Fts3Dequote(zValue); + } + *pzValue = zValue; + return 1; +} + +/* +** Append the output of a printf() style formatting to an existing string. +*/ +static void fts3Appendf( + int *pRc, /* IN/OUT: Error code */ + char **pz, /* IN/OUT: Pointer to string buffer */ + const char *zFormat, /* Printf format string to append */ + ... /* Arguments for printf format string */ +){ + if( *pRc==SQLITE_OK ){ + va_list ap; + char *z; + va_start(ap, zFormat); + z = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + if( z && *pz ){ + char *z2 = sqlite3_mprintf("%s%s", *pz, z); + sqlite3_free(z); + z = z2; + } + if( z==0 ) *pRc = SQLITE_NOMEM; + sqlite3_free(*pz); + *pz = z; + } +} + +/* +** Return a copy of input string zInput enclosed in double-quotes (") and +** with all double quote characters escaped. For example: +** +** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\"" +** +** The pointer returned points to memory obtained from sqlite3_malloc(). It +** is the callers responsibility to call sqlite3_free() to release this +** memory. +*/ +static char *fts3QuoteId(char const *zInput){ + int nRet; + char *zRet; + nRet = 2 + (int)strlen(zInput)*2 + 1; + zRet = sqlite3_malloc(nRet); + if( zRet ){ + int i; + char *z = zRet; + *(z++) = '"'; + for(i=0; zInput[i]; i++){ + if( zInput[i]=='"' ) *(z++) = '"'; + *(z++) = zInput[i]; + } + *(z++) = '"'; + *(z++) = '\0'; + } + return zRet; +} + +/* +** Return a list of comma separated SQL expressions and a FROM clause that +** could be used in a SELECT statement such as the following: +** +** SELECT FROM %_content AS x ... +** +** to return the docid, followed by each column of text data in order +** from left to write. If parameter zFunc is not NULL, then instead of +** being returned directly each column of text data is passed to an SQL +** function named zFunc first. For example, if zFunc is "unzip" and the +** table has the three user-defined columns "a", "b", and "c", the following +** string is returned: +** +** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x" +** +** The pointer returned points to a buffer allocated by sqlite3_malloc(). It +** is the responsibility of the caller to eventually free it. +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and +** a NULL pointer is returned). Otherwise, if an OOM error is encountered +** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If +** no error occurs, *pRc is left unmodified. +*/ +static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){ + char *zRet = 0; + char *zFree = 0; + char *zFunction; + int i; + + if( p->zContentTbl==0 ){ + if( !zFunc ){ + zFunction = ""; + }else{ + zFree = zFunction = fts3QuoteId(zFunc); + } + fts3Appendf(pRc, &zRet, "docid"); + for(i=0; inColumn; i++){ + fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]); + } + if( p->zLanguageid ){ + fts3Appendf(pRc, &zRet, ", x.%Q", "langid"); + } + sqlite3_free(zFree); + }else{ + fts3Appendf(pRc, &zRet, "rowid"); + for(i=0; inColumn; i++){ + fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]); + } + if( p->zLanguageid ){ + fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid); + } + } + fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", + p->zDb, + (p->zContentTbl ? p->zContentTbl : p->zName), + (p->zContentTbl ? "" : "_content") + ); + return zRet; +} + +/* +** Return a list of N comma separated question marks, where N is the number +** of columns in the %_content table (one for the docid plus one for each +** user-defined text column). +** +** If argument zFunc is not NULL, then all but the first question mark +** is preceded by zFunc and an open bracket, and followed by a closed +** bracket. For example, if zFunc is "zip" and the FTS3 table has three +** user-defined text columns, the following string is returned: +** +** "?, zip(?), zip(?), zip(?)" +** +** The pointer returned points to a buffer allocated by sqlite3_malloc(). It +** is the responsibility of the caller to eventually free it. +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and +** a NULL pointer is returned). Otherwise, if an OOM error is encountered +** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If +** no error occurs, *pRc is left unmodified. +*/ +static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){ + char *zRet = 0; + char *zFree = 0; + char *zFunction; + int i; + + if( !zFunc ){ + zFunction = ""; + }else{ + zFree = zFunction = fts3QuoteId(zFunc); + } + fts3Appendf(pRc, &zRet, "?"); + for(i=0; inColumn; i++){ + fts3Appendf(pRc, &zRet, ",%s(?)", zFunction); + } + if( p->zLanguageid ){ + fts3Appendf(pRc, &zRet, ", ?"); + } + sqlite3_free(zFree); + return zRet; +} + +/* +** This function interprets the string at (*pp) as a non-negative integer +** value. It reads the integer and sets *pnOut to the value read, then +** sets *pp to point to the byte immediately following the last byte of +** the integer value. +** +** Only decimal digits ('0'..'9') may be part of an integer value. +** +** If *pp does not being with a decimal digit SQLITE_ERROR is returned and +** the output value undefined. Otherwise SQLITE_OK is returned. +** +** This function is used when parsing the "prefix=" FTS4 parameter. +*/ +static int fts3GobbleInt(const char **pp, int *pnOut){ + const char *p; /* Iterator pointer */ + int nInt = 0; /* Output value */ + + for(p=*pp; p[0]>='0' && p[0]<='9'; p++){ + nInt = nInt * 10 + (p[0] - '0'); + } + if( p==*pp ) return SQLITE_ERROR; + *pnOut = nInt; + *pp = p; + return SQLITE_OK; +} + +/* +** This function is called to allocate an array of Fts3Index structures +** representing the indexes maintained by the current FTS table. FTS tables +** always maintain the main "terms" index, but may also maintain one or +** more "prefix" indexes, depending on the value of the "prefix=" parameter +** (if any) specified as part of the CREATE VIRTUAL TABLE statement. +** +** Argument zParam is passed the value of the "prefix=" option if one was +** specified, or NULL otherwise. +** +** If no error occurs, SQLITE_OK is returned and *apIndex set to point to +** the allocated array. *pnIndex is set to the number of elements in the +** array. If an error does occur, an SQLite error code is returned. +** +** Regardless of whether or not an error is returned, it is the responsibility +** of the caller to call sqlite3_free() on the output array to free it. +*/ +static int fts3PrefixParameter( + const char *zParam, /* ABC in prefix=ABC parameter to parse */ + int *pnIndex, /* OUT: size of *apIndex[] array */ + struct Fts3Index **apIndex /* OUT: Array of indexes for this table */ +){ + struct Fts3Index *aIndex; /* Allocated array */ + int nIndex = 1; /* Number of entries in array */ + + if( zParam && zParam[0] ){ + const char *p; + nIndex++; + for(p=zParam; *p; p++){ + if( *p==',' ) nIndex++; + } + } + + aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex); + *apIndex = aIndex; + *pnIndex = nIndex; + if( !aIndex ){ + return SQLITE_NOMEM; + } + + memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex); + if( zParam ){ + const char *p = zParam; + int i; + for(i=1; i module name ("fts3" or "fts4") +** argv[1] -> database name +** argv[2] -> table name +** argv[...] -> "column name" and other module argument fields. +*/ +static int fts3InitVtab( + int isCreate, /* True for xCreate, false for xConnect */ + sqlite3 *db, /* The SQLite database connection */ + void *pAux, /* Hash table containing tokenizers */ + int argc, /* Number of elements in argv array */ + const char * const *argv, /* xCreate/xConnect argument array */ + sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ + char **pzErr /* Write any error message here */ +){ + Fts3Hash *pHash = (Fts3Hash *)pAux; + Fts3Table *p = 0; /* Pointer to allocated vtab */ + int rc = SQLITE_OK; /* Return code */ + int i; /* Iterator variable */ + int nByte; /* Size of allocation used for *p */ + int iCol; /* Column index */ + int nString = 0; /* Bytes required to hold all column names */ + int nCol = 0; /* Number of columns in the FTS table */ + char *zCsr; /* Space for holding column names */ + int nDb; /* Bytes required to hold database name */ + int nName; /* Bytes required to hold table name */ + int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */ + const char **aCol; /* Array of column names */ + sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */ + + int nIndex; /* Size of aIndex[] array */ + struct Fts3Index *aIndex = 0; /* Array of indexes for this table */ + + /* The results of parsing supported FTS4 key=value options: */ + int bNoDocsize = 0; /* True to omit %_docsize table */ + int bDescIdx = 0; /* True to store descending indexes */ + char *zPrefix = 0; /* Prefix parameter value (or NULL) */ + char *zCompress = 0; /* compress=? parameter (or NULL) */ + char *zUncompress = 0; /* uncompress=? parameter (or NULL) */ + char *zContent = 0; /* content=? parameter (or NULL) */ + char *zLanguageid = 0; /* languageid=? parameter (or NULL) */ + char **azNotindexed = 0; /* The set of notindexed= columns */ + int nNotindexed = 0; /* Size of azNotindexed[] array */ + + assert( strlen(argv[0])==4 ); + assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4) + || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4) + ); + + nDb = (int)strlen(argv[1]) + 1; + nName = (int)strlen(argv[2]) + 1; + + nByte = sizeof(const char *) * (argc-2); + aCol = (const char **)sqlite3_malloc(nByte); + if( aCol ){ + memset((void*)aCol, 0, nByte); + azNotindexed = (char **)sqlite3_malloc(nByte); + } + if( azNotindexed ){ + memset(azNotindexed, 0, nByte); + } + if( !aCol || !azNotindexed ){ + rc = SQLITE_NOMEM; + goto fts3_init_out; + } + + /* Loop through all of the arguments passed by the user to the FTS3/4 + ** module (i.e. all the column names and special arguments). This loop + ** does the following: + ** + ** + Figures out the number of columns the FTSX table will have, and + ** the number of bytes of space that must be allocated to store copies + ** of the column names. + ** + ** + If there is a tokenizer specification included in the arguments, + ** initializes the tokenizer pTokenizer. + */ + for(i=3; rc==SQLITE_OK && i8 + && 0==sqlite3_strnicmp(z, "tokenize", 8) + && 0==sqlite3Fts3IsIdChar(z[8]) + ){ + rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr); + } + + /* Check if it is an FTS4 special argument. */ + else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){ + struct Fts4Option { + const char *zOpt; + int nOpt; + } aFts4Opt[] = { + { "matchinfo", 9 }, /* 0 -> MATCHINFO */ + { "prefix", 6 }, /* 1 -> PREFIX */ + { "compress", 8 }, /* 2 -> COMPRESS */ + { "uncompress", 10 }, /* 3 -> UNCOMPRESS */ + { "order", 5 }, /* 4 -> ORDER */ + { "content", 7 }, /* 5 -> CONTENT */ + { "languageid", 10 }, /* 6 -> LANGUAGEID */ + { "notindexed", 10 } /* 7 -> NOTINDEXED */ + }; + + int iOpt; + if( !zVal ){ + rc = SQLITE_NOMEM; + }else{ + for(iOpt=0; iOptnOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){ + break; + } + } + if( iOpt==SizeofArray(aFts4Opt) ){ + *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z); + rc = SQLITE_ERROR; + }else{ + switch( iOpt ){ + case 0: /* MATCHINFO */ + if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){ + *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal); + rc = SQLITE_ERROR; + } + bNoDocsize = 1; + break; + + case 1: /* PREFIX */ + sqlite3_free(zPrefix); + zPrefix = zVal; + zVal = 0; + break; + + case 2: /* COMPRESS */ + sqlite3_free(zCompress); + zCompress = zVal; + zVal = 0; + break; + + case 3: /* UNCOMPRESS */ + sqlite3_free(zUncompress); + zUncompress = zVal; + zVal = 0; + break; + + case 4: /* ORDER */ + if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) + && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) + ){ + *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal); + rc = SQLITE_ERROR; + } + bDescIdx = (zVal[0]=='d' || zVal[0]=='D'); + break; + + case 5: /* CONTENT */ + sqlite3_free(zContent); + zContent = zVal; + zVal = 0; + break; + + case 6: /* LANGUAGEID */ + assert( iOpt==6 ); + sqlite3_free(zLanguageid); + zLanguageid = zVal; + zVal = 0; + break; + + case 7: /* NOTINDEXED */ + azNotindexed[nNotindexed++] = zVal; + zVal = 0; + break; + } + } + sqlite3_free(zVal); + } + } + + /* Otherwise, the argument is a column name. */ + else { + nString += (int)(strlen(z) + 1); + aCol[nCol++] = z; + } + } + + /* If a content=xxx option was specified, the following: + ** + ** 1. Ignore any compress= and uncompress= options. + ** + ** 2. If no column names were specified as part of the CREATE VIRTUAL + ** TABLE statement, use all columns from the content table. + */ + if( rc==SQLITE_OK && zContent ){ + sqlite3_free(zCompress); + sqlite3_free(zUncompress); + zCompress = 0; + zUncompress = 0; + if( nCol==0 ){ + sqlite3_free((void*)aCol); + aCol = 0; + rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString); + + /* If a languageid= option was specified, remove the language id + ** column from the aCol[] array. */ + if( rc==SQLITE_OK && zLanguageid ){ + int j; + for(j=0; jdb = db; + p->nColumn = nCol; + p->nPendingData = 0; + p->azColumn = (char **)&p[1]; + p->pTokenizer = pTokenizer; + p->nMaxPendingData = FTS3_MAX_PENDING_DATA; + p->bHasDocsize = (isFts4 && bNoDocsize==0); + p->bHasStat = isFts4; + p->bFts4 = isFts4; + p->bDescIdx = bDescIdx; + p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */ + p->zContentTbl = zContent; + p->zLanguageid = zLanguageid; + zContent = 0; + zLanguageid = 0; + TESTONLY( p->inTransaction = -1 ); + TESTONLY( p->mxSavepoint = -1 ); + + p->aIndex = (struct Fts3Index *)&p->azColumn[nCol]; + memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex); + p->nIndex = nIndex; + for(i=0; iaIndex[i].hPending, FTS3_HASH_STRING, 1); + } + p->abNotindexed = (u8 *)&p->aIndex[nIndex]; + + /* Fill in the zName and zDb fields of the vtab structure. */ + zCsr = (char *)&p->abNotindexed[nCol]; + p->zName = zCsr; + memcpy(zCsr, argv[2], nName); + zCsr += nName; + p->zDb = zCsr; + memcpy(zCsr, argv[1], nDb); + zCsr += nDb; + + /* Fill in the azColumn array */ + for(iCol=0; iColazColumn[iCol] = zCsr; + zCsr += n+1; + assert( zCsr <= &((char *)p)[nByte] ); + } + + /* Fill in the abNotindexed array */ + for(iCol=0; iColazColumn[iCol]); + for(i=0; iazColumn[iCol], zNot, n) ){ + p->abNotindexed[iCol] = 1; + sqlite3_free(zNot); + azNotindexed[i] = 0; + } + } + } + for(i=0; izReadExprlist = fts3ReadExprList(p, zUncompress, &rc); + p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc); + if( rc!=SQLITE_OK ) goto fts3_init_out; + + /* If this is an xCreate call, create the underlying tables in the + ** database. TODO: For xConnect(), it could verify that said tables exist. + */ + if( isCreate ){ + rc = fts3CreateTables(p); + } + + /* Check to see if a legacy fts3 table has been "upgraded" by the + ** addition of a %_stat table so that it can use incremental merge. + */ + if( !isFts4 && !isCreate ){ + int rc2 = SQLITE_OK; + fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2", + p->zDb, p->zName); + if( rc2==SQLITE_OK ) p->bHasStat = 1; + } + + /* Figure out the page-size for the database. This is required in order to + ** estimate the cost of loading large doclists from the database. */ + fts3DatabasePageSize(&rc, p); + p->nNodeSize = p->nPgsz-35; + + /* Declare the table schema to SQLite. */ + fts3DeclareVtab(&rc, p); + +fts3_init_out: + sqlite3_free(zPrefix); + sqlite3_free(aIndex); + sqlite3_free(zCompress); + sqlite3_free(zUncompress); + sqlite3_free(zContent); + sqlite3_free(zLanguageid); + for(i=0; ipModule->xDestroy(pTokenizer); + } + }else{ + assert( p->pSegments==0 ); + *ppVTab = &p->base; + } + return rc; +} + +/* +** The xConnect() and xCreate() methods for the virtual table. All the +** work is done in function fts3InitVtab(). +*/ +static int fts3ConnectMethod( + sqlite3 *db, /* Database connection */ + void *pAux, /* Pointer to tokenizer hash table */ + int argc, /* Number of elements in argv array */ + const char * const *argv, /* xCreate/xConnect argument array */ + sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ + char **pzErr /* OUT: sqlite3_malloc'd error message */ +){ + return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); +} +static int fts3CreateMethod( + sqlite3 *db, /* Database connection */ + void *pAux, /* Pointer to tokenizer hash table */ + int argc, /* Number of elements in argv array */ + const char * const *argv, /* xCreate/xConnect argument array */ + sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ + char **pzErr /* OUT: sqlite3_malloc'd error message */ +){ + return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); +} + +/* +** Implementation of the xBestIndex method for FTS3 tables. There +** are three possible strategies, in order of preference: +** +** 1. Direct lookup by rowid or docid. +** 2. Full-text search using a MATCH operator on a non-docid column. +** 3. Linear scan of %_content table. +*/ +static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ + Fts3Table *p = (Fts3Table *)pVTab; + int i; /* Iterator variable */ + int iCons = -1; /* Index of constraint to use */ + + int iLangidCons = -1; /* Index of langid=x constraint, if present */ + int iDocidGe = -1; /* Index of docid>=x constraint, if present */ + int iDocidLe = -1; /* Index of docid<=x constraint, if present */ + int iIdx; + + /* By default use a full table scan. This is an expensive option, + ** so search through the constraints to see if a more efficient + ** strategy is possible. + */ + pInfo->idxNum = FTS3_FULLSCAN_SEARCH; + pInfo->estimatedCost = 5000000; + for(i=0; inConstraint; i++){ + int bDocid; /* True if this constraint is on docid */ + struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; + if( pCons->usable==0 ) continue; + + bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1); + + /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */ + if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){ + pInfo->idxNum = FTS3_DOCID_SEARCH; + pInfo->estimatedCost = 1.0; + iCons = i; + } + + /* A MATCH constraint. Use a full-text search. + ** + ** If there is more than one MATCH constraint available, use the first + ** one encountered. If there is both a MATCH constraint and a direct + ** rowid/docid lookup, prefer the MATCH strategy. This is done even + ** though the rowid/docid lookup is faster than a MATCH query, selecting + ** it would lead to an "unable to use function MATCH in the requested + ** context" error. + */ + if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH + && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn + ){ + pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn; + pInfo->estimatedCost = 2.0; + iCons = i; + } + + /* Equality constraint on the langid column */ + if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ + && pCons->iColumn==p->nColumn + 2 + ){ + iLangidCons = i; + } + + if( bDocid ){ + switch( pCons->op ){ + case SQLITE_INDEX_CONSTRAINT_GE: + case SQLITE_INDEX_CONSTRAINT_GT: + iDocidGe = i; + break; + + case SQLITE_INDEX_CONSTRAINT_LE: + case SQLITE_INDEX_CONSTRAINT_LT: + iDocidLe = i; + break; + } + } + } + + iIdx = 1; + if( iCons>=0 ){ + pInfo->aConstraintUsage[iCons].argvIndex = iIdx++; + pInfo->aConstraintUsage[iCons].omit = 1; + } + if( iLangidCons>=0 ){ + pInfo->idxNum |= FTS3_HAVE_LANGID; + pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++; + } + if( iDocidGe>=0 ){ + pInfo->idxNum |= FTS3_HAVE_DOCID_GE; + pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++; + } + if( iDocidLe>=0 ){ + pInfo->idxNum |= FTS3_HAVE_DOCID_LE; + pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++; + } + + /* Regardless of the strategy selected, FTS can deliver rows in rowid (or + ** docid) order. Both ascending and descending are possible. + */ + if( pInfo->nOrderBy==1 ){ + struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0]; + if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){ + if( pOrder->desc ){ + pInfo->idxStr = "DESC"; + }else{ + pInfo->idxStr = "ASC"; + } + pInfo->orderByConsumed = 1; + } + } + + assert( p->pSegments==0 ); + return SQLITE_OK; +} + +/* +** Implementation of xOpen method. +*/ +static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ + sqlite3_vtab_cursor *pCsr; /* Allocated cursor */ + + UNUSED_PARAMETER(pVTab); + + /* Allocate a buffer large enough for an Fts3Cursor structure. If the + ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, + ** if the allocation fails, return SQLITE_NOMEM. + */ + *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor)); + if( !pCsr ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(Fts3Cursor)); + return SQLITE_OK; +} + +/* +** Close the cursor. For additional information see the documentation +** on the xClose method of the virtual table interface. +*/ +static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){ + Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; + assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); + sqlite3_finalize(pCsr->pStmt); + sqlite3Fts3ExprFree(pCsr->pExpr); + sqlite3Fts3FreeDeferredTokens(pCsr); + sqlite3_free(pCsr->aDoclist); + sqlite3_free(pCsr->aMatchinfo); + assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then +** compose and prepare an SQL statement of the form: +** +** "SELECT FROM %_content WHERE rowid = ?" +** +** (or the equivalent for a content=xxx table) and set pCsr->pStmt to +** it. If an error occurs, return an SQLite error code. +** +** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK. +*/ +static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){ + int rc = SQLITE_OK; + if( pCsr->pStmt==0 ){ + Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; + char *zSql; + zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist); + if( !zSql ) return SQLITE_NOMEM; + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); + sqlite3_free(zSql); + } + *ppStmt = pCsr->pStmt; + return rc; +} + +/* +** Position the pCsr->pStmt statement so that it is on the row +** of the %_content table that contains the last match. Return +** SQLITE_OK on success. +*/ +static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){ + int rc = SQLITE_OK; + if( pCsr->isRequireSeek ){ + sqlite3_stmt *pStmt = 0; + + rc = fts3CursorSeekStmt(pCsr, &pStmt); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); + pCsr->isRequireSeek = 0; + if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){ + return SQLITE_OK; + }else{ + rc = sqlite3_reset(pCsr->pStmt); + if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){ + /* If no row was found and no error has occurred, then the %_content + ** table is missing a row that is present in the full-text index. + ** The data structures are corrupt. */ + rc = FTS_CORRUPT_VTAB; + pCsr->isEof = 1; + } + } + } + } + + if( rc!=SQLITE_OK && pContext ){ + sqlite3_result_error_code(pContext, rc); + } + return rc; +} + +/* +** This function is used to process a single interior node when searching +** a b-tree for a term or term prefix. The node data is passed to this +** function via the zNode/nNode parameters. The term to search for is +** passed in zTerm/nTerm. +** +** If piFirst is not NULL, then this function sets *piFirst to the blockid +** of the child node that heads the sub-tree that may contain the term. +** +** If piLast is not NULL, then *piLast is set to the right-most child node +** that heads a sub-tree that may contain a term for which zTerm/nTerm is +** a prefix. +** +** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK. +*/ +static int fts3ScanInteriorNode( + const char *zTerm, /* Term to select leaves for */ + int nTerm, /* Size of term zTerm in bytes */ + const char *zNode, /* Buffer containing segment interior node */ + int nNode, /* Size of buffer at zNode */ + sqlite3_int64 *piFirst, /* OUT: Selected child node */ + sqlite3_int64 *piLast /* OUT: Selected child node */ +){ + int rc = SQLITE_OK; /* Return code */ + const char *zCsr = zNode; /* Cursor to iterate through node */ + const char *zEnd = &zCsr[nNode];/* End of interior node buffer */ + char *zBuffer = 0; /* Buffer to load terms into */ + int nAlloc = 0; /* Size of allocated buffer */ + int isFirstTerm = 1; /* True when processing first term on page */ + sqlite3_int64 iChild; /* Block id of child node to descend to */ + + /* Skip over the 'height' varint that occurs at the start of every + ** interior node. Then load the blockid of the left-child of the b-tree + ** node into variable iChild. + ** + ** Even if the data structure on disk is corrupted, this (reading two + ** varints from the buffer) does not risk an overread. If zNode is a + ** root node, then the buffer comes from a SELECT statement. SQLite does + ** not make this guarantee explicitly, but in practice there are always + ** either more than 20 bytes of allocated space following the nNode bytes of + ** contents, or two zero bytes. Or, if the node is read from the %_segments + ** table, then there are always 20 bytes of zeroed padding following the + ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details). + */ + zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); + zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); + if( zCsr>zEnd ){ + return FTS_CORRUPT_VTAB; + } + + while( zCsrzEnd ){ + rc = FTS_CORRUPT_VTAB; + goto finish_scan; + } + if( nPrefix+nSuffix>nAlloc ){ + char *zNew; + nAlloc = (nPrefix+nSuffix) * 2; + zNew = (char *)sqlite3_realloc(zBuffer, nAlloc); + if( !zNew ){ + rc = SQLITE_NOMEM; + goto finish_scan; + } + zBuffer = zNew; + } + assert( zBuffer ); + memcpy(&zBuffer[nPrefix], zCsr, nSuffix); + nBuffer = nPrefix + nSuffix; + zCsr += nSuffix; + + /* Compare the term we are searching for with the term just loaded from + ** the interior node. If the specified term is greater than or equal + ** to the term from the interior node, then all terms on the sub-tree + ** headed by node iChild are smaller than zTerm. No need to search + ** iChild. + ** + ** If the interior node term is larger than the specified term, then + ** the tree headed by iChild may contain the specified term. + */ + cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer)); + if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){ + *piFirst = iChild; + piFirst = 0; + } + + if( piLast && cmp<0 ){ + *piLast = iChild; + piLast = 0; + } + + iChild++; + }; + + if( piFirst ) *piFirst = iChild; + if( piLast ) *piLast = iChild; + + finish_scan: + sqlite3_free(zBuffer); + return rc; +} + + +/* +** The buffer pointed to by argument zNode (size nNode bytes) contains an +** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes) +** contains a term. This function searches the sub-tree headed by the zNode +** node for the range of leaf nodes that may contain the specified term +** or terms for which the specified term is a prefix. +** +** If piLeaf is not NULL, then *piLeaf is set to the blockid of the +** left-most leaf node in the tree that may contain the specified term. +** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the +** right-most leaf node that may contain a term for which the specified +** term is a prefix. +** +** It is possible that the range of returned leaf nodes does not contain +** the specified term or any terms for which it is a prefix. However, if the +** segment does contain any such terms, they are stored within the identified +** range. Because this function only inspects interior segment nodes (and +** never loads leaf nodes into memory), it is not possible to be sure. +** +** If an error occurs, an error code other than SQLITE_OK is returned. +*/ +static int fts3SelectLeaf( + Fts3Table *p, /* Virtual table handle */ + const char *zTerm, /* Term to select leaves for */ + int nTerm, /* Size of term zTerm in bytes */ + const char *zNode, /* Buffer containing segment interior node */ + int nNode, /* Size of buffer at zNode */ + sqlite3_int64 *piLeaf, /* Selected leaf node */ + sqlite3_int64 *piLeaf2 /* Selected leaf node */ +){ + int rc; /* Return code */ + int iHeight; /* Height of this node in tree */ + + assert( piLeaf || piLeaf2 ); + + sqlite3Fts3GetVarint32(zNode, &iHeight); + rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); + assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); + + if( rc==SQLITE_OK && iHeight>1 ){ + char *zBlob = 0; /* Blob read from %_segments table */ + int nBlob; /* Size of zBlob in bytes */ + + if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){ + rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0); + if( rc==SQLITE_OK ){ + rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0); + } + sqlite3_free(zBlob); + piLeaf = 0; + zBlob = 0; + } + + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0); + } + if( rc==SQLITE_OK ){ + rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); + } + sqlite3_free(zBlob); + } + + return rc; +} + +/* +** This function is used to create delta-encoded serialized lists of FTS3 +** varints. Each call to this function appends a single varint to a list. +*/ +static void fts3PutDeltaVarint( + char **pp, /* IN/OUT: Output pointer */ + sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ + sqlite3_int64 iVal /* Write this value to the list */ +){ + assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) ); + *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); + *piPrev = iVal; +} + +/* +** When this function is called, *ppPoslist is assumed to point to the +** start of a position-list. After it returns, *ppPoslist points to the +** first byte after the position-list. +** +** A position list is list of positions (delta encoded) and columns for +** a single document record of a doclist. So, in other words, this +** routine advances *ppPoslist so that it points to the next docid in +** the doclist, or to the first byte past the end of the doclist. +** +** If pp is not NULL, then the contents of the position list are copied +** to *pp. *pp is set to point to the first byte past the last byte copied +** before this function returns. +*/ +static void fts3PoslistCopy(char **pp, char **ppPoslist){ + char *pEnd = *ppPoslist; + char c = 0; + + /* The end of a position list is marked by a zero encoded as an FTS3 + ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by + ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail + ** of some other, multi-byte, value. + ** + ** The following while-loop moves pEnd to point to the first byte that is not + ** immediately preceded by a byte with the 0x80 bit set. Then increments + ** pEnd once more so that it points to the byte immediately following the + ** last byte in the position-list. + */ + while( *pEnd | c ){ + c = *pEnd++ & 0x80; + testcase( c!=0 && (*pEnd)==0 ); + } + pEnd++; /* Advance past the POS_END terminator byte */ + + if( pp ){ + int n = (int)(pEnd - *ppPoslist); + char *p = *pp; + memcpy(p, *ppPoslist, n); + p += n; + *pp = p; + } + *ppPoslist = pEnd; +} + +/* +** When this function is called, *ppPoslist is assumed to point to the +** start of a column-list. After it returns, *ppPoslist points to the +** to the terminator (POS_COLUMN or POS_END) byte of the column-list. +** +** A column-list is list of delta-encoded positions for a single column +** within a single document within a doclist. +** +** The column-list is terminated either by a POS_COLUMN varint (1) or +** a POS_END varint (0). This routine leaves *ppPoslist pointing to +** the POS_COLUMN or POS_END that terminates the column-list. +** +** If pp is not NULL, then the contents of the column-list are copied +** to *pp. *pp is set to point to the first byte past the last byte copied +** before this function returns. The POS_COLUMN or POS_END terminator +** is not copied into *pp. +*/ +static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ + char *pEnd = *ppPoslist; + char c = 0; + + /* A column-list is terminated by either a 0x01 or 0x00 byte that is + ** not part of a multi-byte varint. + */ + while( 0xFE & (*pEnd | c) ){ + c = *pEnd++ & 0x80; + testcase( c!=0 && ((*pEnd)&0xfe)==0 ); + } + if( pp ){ + int n = (int)(pEnd - *ppPoslist); + char *p = *pp; + memcpy(p, *ppPoslist, n); + p += n; + *pp = p; + } + *ppPoslist = pEnd; +} + +/* +** Value used to signify the end of an position-list. This is safe because +** it is not possible to have a document with 2^31 terms. +*/ +#define POSITION_LIST_END 0x7fffffff + +/* +** This function is used to help parse position-lists. When this function is +** called, *pp may point to the start of the next varint in the position-list +** being parsed, or it may point to 1 byte past the end of the position-list +** (in which case **pp will be a terminator bytes POS_END (0) or +** (1)). +** +** If *pp points past the end of the current position-list, set *pi to +** POSITION_LIST_END and return. Otherwise, read the next varint from *pp, +** increment the current value of *pi by the value read, and set *pp to +** point to the next value before returning. +** +** Before calling this routine *pi must be initialized to the value of +** the previous position, or zero if we are reading the first position +** in the position-list. Because positions are delta-encoded, the value +** of the previous position is needed in order to compute the value of +** the next position. +*/ +static void fts3ReadNextPos( + char **pp, /* IN/OUT: Pointer into position-list buffer */ + sqlite3_int64 *pi /* IN/OUT: Value read from position-list */ +){ + if( (**pp)&0xFE ){ + fts3GetDeltaVarint(pp, pi); + *pi -= 2; + }else{ + *pi = POSITION_LIST_END; + } +} + +/* +** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by +** the value of iCol encoded as a varint to *pp. This will start a new +** column list. +** +** Set *pp to point to the byte just after the last byte written before +** returning (do not modify it if iCol==0). Return the total number of bytes +** written (0 if iCol==0). +*/ +static int fts3PutColNumber(char **pp, int iCol){ + int n = 0; /* Number of bytes written */ + if( iCol ){ + char *p = *pp; /* Output pointer */ + n = 1 + sqlite3Fts3PutVarint(&p[1], iCol); + *p = 0x01; + *pp = &p[n]; + } + return n; +} + +/* +** Compute the union of two position lists. The output written +** into *pp contains all positions of both *pp1 and *pp2 in sorted +** order and with any duplicates removed. All pointers are +** updated appropriately. The caller is responsible for insuring +** that there is enough space in *pp to hold the complete output. +*/ +static void fts3PoslistMerge( + char **pp, /* Output buffer */ + char **pp1, /* Left input list */ + char **pp2 /* Right input list */ +){ + char *p = *pp; + char *p1 = *pp1; + char *p2 = *pp2; + + while( *p1 || *p2 ){ + int iCol1; /* The current column index in pp1 */ + int iCol2; /* The current column index in pp2 */ + + if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1); + else if( *p1==POS_END ) iCol1 = POSITION_LIST_END; + else iCol1 = 0; + + if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2); + else if( *p2==POS_END ) iCol2 = POSITION_LIST_END; + else iCol2 = 0; + + if( iCol1==iCol2 ){ + sqlite3_int64 i1 = 0; /* Last position from pp1 */ + sqlite3_int64 i2 = 0; /* Last position from pp2 */ + sqlite3_int64 iPrev = 0; + int n = fts3PutColNumber(&p, iCol1); + p1 += n; + p2 += n; + + /* At this point, both p1 and p2 point to the start of column-lists + ** for the same column (the column with index iCol1 and iCol2). + ** A column-list is a list of non-negative delta-encoded varints, each + ** incremented by 2 before being stored. Each list is terminated by a + ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists + ** and writes the results to buffer p. p is left pointing to the byte + ** after the list written. No terminator (POS_END or POS_COLUMN) is + ** written to the output. + */ + fts3GetDeltaVarint(&p1, &i1); + fts3GetDeltaVarint(&p2, &i2); + do { + fts3PutDeltaVarint(&p, &iPrev, (i1pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e. +** when the *pp1 token appears before the *pp2 token, but not more than nToken +** slots before it. +** +** e.g. nToken==1 searches for adjacent positions. +*/ +static int fts3PoslistPhraseMerge( + char **pp, /* IN/OUT: Preallocated output buffer */ + int nToken, /* Maximum difference in token positions */ + int isSaveLeft, /* Save the left position */ + int isExact, /* If *pp1 is exactly nTokens before *pp2 */ + char **pp1, /* IN/OUT: Left input list */ + char **pp2 /* IN/OUT: Right input list */ +){ + char *p = *pp; + char *p1 = *pp1; + char *p2 = *pp2; + int iCol1 = 0; + int iCol2 = 0; + + /* Never set both isSaveLeft and isExact for the same invocation. */ + assert( isSaveLeft==0 || isExact==0 ); + + assert( p!=0 && *p1!=0 && *p2!=0 ); + if( *p1==POS_COLUMN ){ + p1++; + p1 += sqlite3Fts3GetVarint32(p1, &iCol1); + } + if( *p2==POS_COLUMN ){ + p2++; + p2 += sqlite3Fts3GetVarint32(p2, &iCol2); + } + + while( 1 ){ + if( iCol1==iCol2 ){ + char *pSave = p; + sqlite3_int64 iPrev = 0; + sqlite3_int64 iPos1 = 0; + sqlite3_int64 iPos2 = 0; + + if( iCol1 ){ + *p++ = POS_COLUMN; + p += sqlite3Fts3PutVarint(p, iCol1); + } + + assert( *p1!=POS_END && *p1!=POS_COLUMN ); + assert( *p2!=POS_END && *p2!=POS_COLUMN ); + fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; + fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; + + while( 1 ){ + if( iPos2==iPos1+nToken + || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) + ){ + sqlite3_int64 iSave; + iSave = isSaveLeft ? iPos1 : iPos2; + fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2; + pSave = 0; + assert( p ); + } + if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){ + if( (*p2&0xFE)==0 ) break; + fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; + }else{ + if( (*p1&0xFE)==0 ) break; + fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; + } + } + + if( pSave ){ + assert( pp && p ); + p = pSave; + } + + fts3ColumnlistCopy(0, &p1); + fts3ColumnlistCopy(0, &p2); + assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 ); + if( 0==*p1 || 0==*p2 ) break; + + p1++; + p1 += sqlite3Fts3GetVarint32(p1, &iCol1); + p2++; + p2 += sqlite3Fts3GetVarint32(p2, &iCol2); + } + + /* Advance pointer p1 or p2 (whichever corresponds to the smaller of + ** iCol1 and iCol2) so that it points to either the 0x00 that marks the + ** end of the position list, or the 0x01 that precedes the next + ** column-number in the position list. + */ + else if( iCol1=pEnd ){ + *pp = 0; + }else{ + sqlite3_int64 iVal; + *pp += sqlite3Fts3GetVarint(*pp, &iVal); + if( bDescIdx ){ + *pVal -= iVal; + }else{ + *pVal += iVal; + } + } +} + +/* +** This function is used to write a single varint to a buffer. The varint +** is written to *pp. Before returning, *pp is set to point 1 byte past the +** end of the value written. +** +** If *pbFirst is zero when this function is called, the value written to +** the buffer is that of parameter iVal. +** +** If *pbFirst is non-zero when this function is called, then the value +** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal) +** (if bDescIdx is non-zero). +** +** Before returning, this function always sets *pbFirst to 1 and *piPrev +** to the value of parameter iVal. +*/ +static void fts3PutDeltaVarint3( + char **pp, /* IN/OUT: Output pointer */ + int bDescIdx, /* True for descending docids */ + sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ + int *pbFirst, /* IN/OUT: True after first int written */ + sqlite3_int64 iVal /* Write this value to the list */ +){ + sqlite3_int64 iWrite; + if( bDescIdx==0 || *pbFirst==0 ){ + iWrite = iVal - *piPrev; + }else{ + iWrite = *piPrev - iVal; + } + assert( *pbFirst || *piPrev==0 ); + assert( *pbFirst==0 || iWrite>0 ); + *pp += sqlite3Fts3PutVarint(*pp, iWrite); + *piPrev = iVal; + *pbFirst = 1; +} + + +/* +** This macro is used by various functions that merge doclists. The two +** arguments are 64-bit docid values. If the value of the stack variable +** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). +** Otherwise, (i2-i1). +** +** Using this makes it easier to write code that can merge doclists that are +** sorted in either ascending or descending order. +*/ +#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2)) + +/* +** This function does an "OR" merge of two doclists (output contains all +** positions contained in either argument doclist). If the docids in the +** input doclists are sorted in ascending order, parameter bDescDoclist +** should be false. If they are sorted in ascending order, it should be +** passed a non-zero value. +** +** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer +** containing the output doclist and SQLITE_OK is returned. In this case +** *pnOut is set to the number of bytes in the output doclist. +** +** If an error occurs, an SQLite error code is returned. The output values +** are undefined in this case. +*/ +static int fts3DoclistOrMerge( + int bDescDoclist, /* True if arguments are desc */ + char *a1, int n1, /* First doclist */ + char *a2, int n2, /* Second doclist */ + char **paOut, int *pnOut /* OUT: Malloc'd doclist */ +){ + sqlite3_int64 i1 = 0; + sqlite3_int64 i2 = 0; + sqlite3_int64 iPrev = 0; + char *pEnd1 = &a1[n1]; + char *pEnd2 = &a2[n2]; + char *p1 = a1; + char *p2 = a2; + char *p; + char *aOut; + int bFirstOut = 0; + + *paOut = 0; + *pnOut = 0; + + /* Allocate space for the output. Both the input and output doclists + ** are delta encoded. If they are in ascending order (bDescDoclist==0), + ** then the first docid in each list is simply encoded as a varint. For + ** each subsequent docid, the varint stored is the difference between the + ** current and previous docid (a positive number - since the list is in + ** ascending order). + ** + ** The first docid written to the output is therefore encoded using the + ** same number of bytes as it is in whichever of the input lists it is + ** read from. And each subsequent docid read from the same input list + ** consumes either the same or less bytes as it did in the input (since + ** the difference between it and the previous value in the output must + ** be a positive value less than or equal to the delta value read from + ** the input list). The same argument applies to all but the first docid + ** read from the 'other' list. And to the contents of all position lists + ** that will be copied and merged from the input to the output. + ** + ** However, if the first docid copied to the output is a negative number, + ** then the encoding of the first docid from the 'other' input list may + ** be larger in the output than it was in the input (since the delta value + ** may be a larger positive integer than the actual docid). + ** + ** The space required to store the output is therefore the sum of the + ** sizes of the two inputs, plus enough space for exactly one of the input + ** docids to grow. + ** + ** A symetric argument may be made if the doclists are in descending + ** order. + */ + aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1); + if( !aOut ) return SQLITE_NOMEM; + + p = aOut; + fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); + fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); + while( p1 || p2 ){ + sqlite3_int64 iDiff = DOCID_CMP(i1, i2); + + if( p2 && p1 && iDiff==0 ){ + fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); + fts3PoslistMerge(&p, &p1, &p2); + fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); + fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); + }else if( !p2 || (p1 && iDiff<0) ){ + fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); + fts3PoslistCopy(&p, &p1); + fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); + }else{ + fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2); + fts3PoslistCopy(&p, &p2); + fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); + } + } + + *paOut = aOut; + *pnOut = (int)(p-aOut); + assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 ); + return SQLITE_OK; +} + +/* +** This function does a "phrase" merge of two doclists. In a phrase merge, +** the output contains a copy of each position from the right-hand input +** doclist for which there is a position in the left-hand input doclist +** exactly nDist tokens before it. +** +** If the docids in the input doclists are sorted in ascending order, +** parameter bDescDoclist should be false. If they are sorted in ascending +** order, it should be passed a non-zero value. +** +** The right-hand input doclist is overwritten by this function. +*/ +static void fts3DoclistPhraseMerge( + int bDescDoclist, /* True if arguments are desc */ + int nDist, /* Distance from left to right (1=adjacent) */ + char *aLeft, int nLeft, /* Left doclist */ + char *aRight, int *pnRight /* IN/OUT: Right/output doclist */ +){ + sqlite3_int64 i1 = 0; + sqlite3_int64 i2 = 0; + sqlite3_int64 iPrev = 0; + char *pEnd1 = &aLeft[nLeft]; + char *pEnd2 = &aRight[*pnRight]; + char *p1 = aLeft; + char *p2 = aRight; + char *p; + int bFirstOut = 0; + char *aOut = aRight; + + assert( nDist>0 ); + + p = aOut; + fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); + fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); + + while( p1 && p2 ){ + sqlite3_int64 iDiff = DOCID_CMP(i1, i2); + if( iDiff==0 ){ + char *pSave = p; + sqlite3_int64 iPrevSave = iPrev; + int bFirstOutSave = bFirstOut; + + fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); + if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){ + p = pSave; + iPrev = iPrevSave; + bFirstOut = bFirstOutSave; + } + fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); + fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); + }else if( iDiff<0 ){ + fts3PoslistCopy(0, &p1); + fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); + }else{ + fts3PoslistCopy(0, &p2); + fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); + } + } + + *pnRight = (int)(p - aOut); +} + +/* +** Argument pList points to a position list nList bytes in size. This +** function checks to see if the position list contains any entries for +** a token in position 0 (of any column). If so, it writes argument iDelta +** to the output buffer pOut, followed by a position list consisting only +** of the entries from pList at position 0, and terminated by an 0x00 byte. +** The value returned is the number of bytes written to pOut (if any). +*/ +SQLITE_PRIVATE int sqlite3Fts3FirstFilter( + sqlite3_int64 iDelta, /* Varint that may be written to pOut */ + char *pList, /* Position list (no 0x00 term) */ + int nList, /* Size of pList in bytes */ + char *pOut /* Write output here */ +){ + int nOut = 0; + int bWritten = 0; /* True once iDelta has been written */ + char *p = pList; + char *pEnd = &pList[nList]; + + if( *p!=0x01 ){ + if( *p==0x02 ){ + nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta); + pOut[nOut++] = 0x02; + bWritten = 1; + } + fts3ColumnlistCopy(0, &p); + } + + while( paaOutput); i++){ + if( pTS->aaOutput[i] ){ + if( !aOut ){ + aOut = pTS->aaOutput[i]; + nOut = pTS->anOutput[i]; + pTS->aaOutput[i] = 0; + }else{ + int nNew; + char *aNew; + + int rc = fts3DoclistOrMerge(p->bDescIdx, + pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew + ); + if( rc!=SQLITE_OK ){ + sqlite3_free(aOut); + return rc; + } + + sqlite3_free(pTS->aaOutput[i]); + sqlite3_free(aOut); + pTS->aaOutput[i] = 0; + aOut = aNew; + nOut = nNew; + } + } + } + + pTS->aaOutput[0] = aOut; + pTS->anOutput[0] = nOut; + return SQLITE_OK; +} + +/* +** Merge the doclist aDoclist/nDoclist into the TermSelect object passed +** as the first argument. The merge is an "OR" merge (see function +** fts3DoclistOrMerge() for details). +** +** This function is called with the doclist for each term that matches +** a queried prefix. It merges all these doclists into one, the doclist +** for the specified prefix. Since there can be a very large number of +** doclists to merge, the merging is done pair-wise using the TermSelect +** object. +** +** This function returns SQLITE_OK if the merge is successful, or an +** SQLite error code (SQLITE_NOMEM) if an error occurs. +*/ +static int fts3TermSelectMerge( + Fts3Table *p, /* FTS table handle */ + TermSelect *pTS, /* TermSelect object to merge into */ + char *aDoclist, /* Pointer to doclist */ + int nDoclist /* Size of aDoclist in bytes */ +){ + if( pTS->aaOutput[0]==0 ){ + /* If this is the first term selected, copy the doclist to the output + ** buffer using memcpy(). */ + pTS->aaOutput[0] = sqlite3_malloc(nDoclist); + pTS->anOutput[0] = nDoclist; + if( pTS->aaOutput[0] ){ + memcpy(pTS->aaOutput[0], aDoclist, nDoclist); + }else{ + return SQLITE_NOMEM; + } + }else{ + char *aMerge = aDoclist; + int nMerge = nDoclist; + int iOut; + + for(iOut=0; iOutaaOutput); iOut++){ + if( pTS->aaOutput[iOut]==0 ){ + assert( iOut>0 ); + pTS->aaOutput[iOut] = aMerge; + pTS->anOutput[iOut] = nMerge; + break; + }else{ + char *aNew; + int nNew; + + int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, + pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew + ); + if( rc!=SQLITE_OK ){ + if( aMerge!=aDoclist ) sqlite3_free(aMerge); + return rc; + } + + if( aMerge!=aDoclist ) sqlite3_free(aMerge); + sqlite3_free(pTS->aaOutput[iOut]); + pTS->aaOutput[iOut] = 0; + + aMerge = aNew; + nMerge = nNew; + if( (iOut+1)==SizeofArray(pTS->aaOutput) ){ + pTS->aaOutput[iOut] = aMerge; + pTS->anOutput[iOut] = nMerge; + } + } + } + } + return SQLITE_OK; +} + +/* +** Append SegReader object pNew to the end of the pCsr->apSegment[] array. +*/ +static int fts3SegReaderCursorAppend( + Fts3MultiSegReader *pCsr, + Fts3SegReader *pNew +){ + if( (pCsr->nSegment%16)==0 ){ + Fts3SegReader **apNew; + int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); + apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte); + if( !apNew ){ + sqlite3Fts3SegReaderFree(pNew); + return SQLITE_NOMEM; + } + pCsr->apSegment = apNew; + } + pCsr->apSegment[pCsr->nSegment++] = pNew; + return SQLITE_OK; +} + +/* +** Add seg-reader objects to the Fts3MultiSegReader object passed as the +** 8th argument. +** +** This function returns SQLITE_OK if successful, or an SQLite error code +** otherwise. +*/ +static int fts3SegReaderCursor( + Fts3Table *p, /* FTS3 table handle */ + int iLangid, /* Language id */ + int iIndex, /* Index to search (from 0 to p->nIndex-1) */ + int iLevel, /* Level of segments to scan */ + const char *zTerm, /* Term to query for */ + int nTerm, /* Size of zTerm in bytes */ + int isPrefix, /* True for a prefix search */ + int isScan, /* True to scan from zTerm to EOF */ + Fts3MultiSegReader *pCsr /* Cursor object to populate */ +){ + int rc = SQLITE_OK; /* Error code */ + sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */ + int rc2; /* Result of sqlite3_reset() */ + + /* If iLevel is less than 0 and this is not a scan, include a seg-reader + ** for the pending-terms. If this is a scan, then this call must be being + ** made by an fts4aux module, not an FTS table. In this case calling + ** Fts3SegReaderPending might segfault, as the data structures used by + ** fts4aux are not completely populated. So it's easiest to filter these + ** calls out here. */ + if( iLevel<0 && p->aIndex ){ + Fts3SegReader *pSeg = 0; + rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg); + if( rc==SQLITE_OK && pSeg ){ + rc = fts3SegReaderCursorAppend(pCsr, pSeg); + } + } + + if( iLevel!=FTS3_SEGCURSOR_PENDING ){ + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt); + } + + while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ + Fts3SegReader *pSeg = 0; + + /* Read the values returned by the SELECT into local variables. */ + sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1); + sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2); + sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3); + int nRoot = sqlite3_column_bytes(pStmt, 4); + char const *zRoot = sqlite3_column_blob(pStmt, 4); + + /* If zTerm is not NULL, and this segment is not stored entirely on its + ** root node, the range of leaves scanned can be reduced. Do this. */ + if( iStartBlock && zTerm ){ + sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0); + rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi); + if( rc!=SQLITE_OK ) goto finished; + if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock; + } + + rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, + (isPrefix==0 && isScan==0), + iStartBlock, iLeavesEndBlock, + iEndBlock, zRoot, nRoot, &pSeg + ); + if( rc!=SQLITE_OK ) goto finished; + rc = fts3SegReaderCursorAppend(pCsr, pSeg); + } + } + + finished: + rc2 = sqlite3_reset(pStmt); + if( rc==SQLITE_DONE ) rc = rc2; + + return rc; +} + +/* +** Set up a cursor object for iterating through a full-text index or a +** single level therein. +*/ +SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor( + Fts3Table *p, /* FTS3 table handle */ + int iLangid, /* Language-id to search */ + int iIndex, /* Index to search (from 0 to p->nIndex-1) */ + int iLevel, /* Level of segments to scan */ + const char *zTerm, /* Term to query for */ + int nTerm, /* Size of zTerm in bytes */ + int isPrefix, /* True for a prefix search */ + int isScan, /* True to scan from zTerm to EOF */ + Fts3MultiSegReader *pCsr /* Cursor object to populate */ +){ + assert( iIndex>=0 && iIndexnIndex ); + assert( iLevel==FTS3_SEGCURSOR_ALL + || iLevel==FTS3_SEGCURSOR_PENDING + || iLevel>=0 + ); + assert( iLevelbase.pVtab; + + if( isPrefix ){ + for(i=1; bFound==0 && inIndex; i++){ + if( p->aIndex[i].nPrefix==nTerm ){ + bFound = 1; + rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, + i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr + ); + pSegcsr->bLookup = 1; + } + } + + for(i=1; bFound==0 && inIndex; i++){ + if( p->aIndex[i].nPrefix==nTerm+1 ){ + bFound = 1; + rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, + i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr + ); + if( rc==SQLITE_OK ){ + rc = fts3SegReaderCursorAddZero( + p, pCsr->iLangid, zTerm, nTerm, pSegcsr + ); + } + } + } + } + + if( bFound==0 ){ + rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, + 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr + ); + pSegcsr->bLookup = !isPrefix; + } + } + + *ppSegcsr = pSegcsr; + return rc; +} + +/* +** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor(). +*/ +static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){ + sqlite3Fts3SegReaderFinish(pSegcsr); + sqlite3_free(pSegcsr); +} + +/* +** This function retrieves the doclist for the specified term (or term +** prefix) from the database. +*/ +static int fts3TermSelect( + Fts3Table *p, /* Virtual table handle */ + Fts3PhraseToken *pTok, /* Token to query for */ + int iColumn, /* Column to query (or -ve for all columns) */ + int *pnOut, /* OUT: Size of buffer at *ppOut */ + char **ppOut /* OUT: Malloced result buffer */ +){ + int rc; /* Return code */ + Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */ + TermSelect tsc; /* Object for pair-wise doclist merging */ + Fts3SegFilter filter; /* Segment term filter configuration */ + + pSegcsr = pTok->pSegcsr; + memset(&tsc, 0, sizeof(TermSelect)); + + filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS + | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0) + | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0) + | (iColumnnColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0); + filter.iCol = iColumn; + filter.zTerm = pTok->z; + filter.nTerm = pTok->n; + + rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter); + while( SQLITE_OK==rc + && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) + ){ + rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist); + } + + if( rc==SQLITE_OK ){ + rc = fts3TermSelectFinishMerge(p, &tsc); + } + if( rc==SQLITE_OK ){ + *ppOut = tsc.aaOutput[0]; + *pnOut = tsc.anOutput[0]; + }else{ + int i; + for(i=0; ipSegcsr = 0; + return rc; +} + +/* +** This function counts the total number of docids in the doclist stored +** in buffer aList[], size nList bytes. +** +** If the isPoslist argument is true, then it is assumed that the doclist +** contains a position-list following each docid. Otherwise, it is assumed +** that the doclist is simply a list of docids stored as delta encoded +** varints. +*/ +static int fts3DoclistCountDocids(char *aList, int nList){ + int nDoc = 0; /* Return value */ + if( aList ){ + char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */ + char *p = aList; /* Cursor */ + while( peSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){ + if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){ + pCsr->isEof = 1; + rc = sqlite3_reset(pCsr->pStmt); + }else{ + pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0); + rc = SQLITE_OK; + } + }else{ + rc = fts3EvalNext((Fts3Cursor *)pCursor); + } + assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); + return rc; +} + +/* +** The following are copied from sqliteInt.h. +** +** Constants for the largest and smallest possible 64-bit signed integers. +** These macros are designed to work correctly on both 32-bit and 64-bit +** compilers. +*/ +#ifndef SQLITE_AMALGAMATION +# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) +# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) +#endif + +/* +** If the numeric type of argument pVal is "integer", then return it +** converted to a 64-bit signed integer. Otherwise, return a copy of +** the second parameter, iDefault. +*/ +static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){ + if( pVal ){ + int eType = sqlite3_value_numeric_type(pVal); + if( eType==SQLITE_INTEGER ){ + return sqlite3_value_int64(pVal); + } + } + return iDefault; +} + +/* +** This is the xFilter interface for the virtual table. See +** the virtual table xFilter method documentation for additional +** information. +** +** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against +** the %_content table. +** +** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry +** in the %_content table. +** +** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The +** column on the left-hand side of the MATCH operator is column +** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand +** side of the MATCH operator. +*/ +static int fts3FilterMethod( + sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + int idxNum, /* Strategy index */ + const char *idxStr, /* Unused */ + int nVal, /* Number of elements in apVal */ + sqlite3_value **apVal /* Arguments for the indexing scheme */ +){ + int rc; + char *zSql; /* SQL statement used to access %_content */ + int eSearch; + Fts3Table *p = (Fts3Table *)pCursor->pVtab; + Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; + + sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */ + sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */ + sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */ + sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */ + int iIdx; + + UNUSED_PARAMETER(idxStr); + UNUSED_PARAMETER(nVal); + + eSearch = (idxNum & 0x0000FFFF); + assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) ); + assert( p->pSegments==0 ); + + /* Collect arguments into local variables */ + iIdx = 0; + if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++]; + if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++]; + if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++]; + if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++]; + assert( iIdx==nVal ); + + /* In case the cursor has been used before, clear it now. */ + sqlite3_finalize(pCsr->pStmt); + sqlite3_free(pCsr->aDoclist); + sqlite3Fts3ExprFree(pCsr->pExpr); + memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor)); + + /* Set the lower and upper bounds on docids to return */ + pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64); + pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64); + + if( idxStr ){ + pCsr->bDesc = (idxStr[0]=='D'); + }else{ + pCsr->bDesc = p->bDescIdx; + } + pCsr->eSearch = (i16)eSearch; + + if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){ + int iCol = eSearch-FTS3_FULLTEXT_SEARCH; + const char *zQuery = (const char *)sqlite3_value_text(pCons); + + if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){ + return SQLITE_NOMEM; + } + + pCsr->iLangid = 0; + if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid); + + assert( p->base.zErrMsg==0 ); + rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid, + p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, + &p->base.zErrMsg + ); + if( rc!=SQLITE_OK ){ + return rc; + } + + rc = fts3EvalStart(pCsr); + sqlite3Fts3SegmentsClose(p); + if( rc!=SQLITE_OK ) return rc; + pCsr->pNextId = pCsr->aDoclist; + pCsr->iPrevId = 0; + } + + /* Compile a SELECT statement for this cursor. For a full-table-scan, the + ** statement loops through all rows of the %_content table. For a + ** full-text query or docid lookup, the statement retrieves a single + ** row by docid. + */ + if( eSearch==FTS3_FULLSCAN_SEARCH ){ + zSql = sqlite3_mprintf( + "SELECT %s ORDER BY rowid %s", + p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC") + ); + if( zSql ){ + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); + sqlite3_free(zSql); + }else{ + rc = SQLITE_NOMEM; + } + }else if( eSearch==FTS3_DOCID_SEARCH ){ + rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt); + if( rc==SQLITE_OK ){ + rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons); + } + } + if( rc!=SQLITE_OK ) return rc; + + return fts3NextMethod(pCursor); +} + +/* +** This is the xEof method of the virtual table. SQLite calls this +** routine to find out if it has reached the end of a result set. +*/ +static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){ + return ((Fts3Cursor *)pCursor)->isEof; +} + +/* +** This is the xRowid method. The SQLite core calls this routine to +** retrieve the rowid for the current row of the result set. fts3 +** exposes %_content.docid as the rowid for the virtual table. The +** rowid should be written to *pRowid. +*/ +static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; + *pRowid = pCsr->iPrevId; + return SQLITE_OK; +} + +/* +** This is the xColumn method, called by SQLite to request a value from +** the row that the supplied cursor currently points to. +** +** If: +** +** (iCol < p->nColumn) -> The value of the iCol'th user column. +** (iCol == p->nColumn) -> Magic column with the same name as the table. +** (iCol == p->nColumn+1) -> Docid column +** (iCol == p->nColumn+2) -> Langid column +*/ +static int fts3ColumnMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + int iCol /* Index of column to read value from */ +){ + int rc = SQLITE_OK; /* Return Code */ + Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; + Fts3Table *p = (Fts3Table *)pCursor->pVtab; + + /* The column value supplied by SQLite must be in range. */ + assert( iCol>=0 && iCol<=p->nColumn+2 ); + + if( iCol==p->nColumn+1 ){ + /* This call is a request for the "docid" column. Since "docid" is an + ** alias for "rowid", use the xRowid() method to obtain the value. + */ + sqlite3_result_int64(pCtx, pCsr->iPrevId); + }else if( iCol==p->nColumn ){ + /* The extra column whose name is the same as the table. + ** Return a blob which is a pointer to the cursor. */ + sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT); + }else if( iCol==p->nColumn+2 && pCsr->pExpr ){ + sqlite3_result_int64(pCtx, pCsr->iLangid); + }else{ + /* The requested column is either a user column (one that contains + ** indexed data), or the language-id column. */ + rc = fts3CursorSeek(0, pCsr); + + if( rc==SQLITE_OK ){ + if( iCol==p->nColumn+2 ){ + int iLangid = 0; + if( p->zLanguageid ){ + iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1); + } + sqlite3_result_int(pCtx, iLangid); + }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){ + sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1)); + } + } + } + + assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); + return rc; +} + +/* +** This function is the implementation of the xUpdate callback used by +** FTS3 virtual tables. It is invoked by SQLite each time a row is to be +** inserted, updated or deleted. +*/ +static int fts3UpdateMethod( + sqlite3_vtab *pVtab, /* Virtual table handle */ + int nArg, /* Size of argument array */ + sqlite3_value **apVal, /* Array of arguments */ + sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ +){ + return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid); +} + +/* +** Implementation of xSync() method. Flush the contents of the pending-terms +** hash-table to the database. +*/ +static int fts3SyncMethod(sqlite3_vtab *pVtab){ + + /* Following an incremental-merge operation, assuming that the input + ** segments are not completely consumed (the usual case), they are updated + ** in place to remove the entries that have already been merged. This + ** involves updating the leaf block that contains the smallest unmerged + ** entry and each block (if any) between the leaf and the root node. So + ** if the height of the input segment b-trees is N, and input segments + ** are merged eight at a time, updating the input segments at the end + ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually + ** small - often between 0 and 2. So the overhead of the incremental + ** merge is somewhere between 8 and 24 blocks. To avoid this overhead + ** dwarfing the actual productive work accomplished, the incremental merge + ** is only attempted if it will write at least 64 leaf blocks. Hence + ** nMinMerge. + ** + ** Of course, updating the input segments also involves deleting a bunch + ** of blocks from the segments table. But this is not considered overhead + ** as it would also be required by a crisis-merge that used the same input + ** segments. + */ + const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */ + + Fts3Table *p = (Fts3Table*)pVtab; + int rc = sqlite3Fts3PendingTermsFlush(p); + + if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){ + int mxLevel = 0; /* Maximum relative level value in db */ + int A; /* Incr-merge parameter A */ + + rc = sqlite3Fts3MaxLevel(p, &mxLevel); + assert( rc==SQLITE_OK || mxLevel==0 ); + A = p->nLeafAdd * mxLevel; + A += (A/2); + if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8); + } + sqlite3Fts3SegmentsClose(p); + return rc; +} + +/* +** Implementation of xBegin() method. This is a no-op. +*/ +static int fts3BeginMethod(sqlite3_vtab *pVtab){ + Fts3Table *p = (Fts3Table*)pVtab; + UNUSED_PARAMETER(pVtab); + assert( p->pSegments==0 ); + assert( p->nPendingData==0 ); + assert( p->inTransaction!=1 ); + TESTONLY( p->inTransaction = 1 ); + TESTONLY( p->mxSavepoint = -1; ); + p->nLeafAdd = 0; + return SQLITE_OK; +} + +/* +** Implementation of xCommit() method. This is a no-op. The contents of +** the pending-terms hash-table have already been flushed into the database +** by fts3SyncMethod(). +*/ +static int fts3CommitMethod(sqlite3_vtab *pVtab){ + TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); + UNUSED_PARAMETER(pVtab); + assert( p->nPendingData==0 ); + assert( p->inTransaction!=0 ); + assert( p->pSegments==0 ); + TESTONLY( p->inTransaction = 0 ); + TESTONLY( p->mxSavepoint = -1; ); + return SQLITE_OK; +} + +/* +** Implementation of xRollback(). Discard the contents of the pending-terms +** hash-table. Any changes made to the database are reverted by SQLite. +*/ +static int fts3RollbackMethod(sqlite3_vtab *pVtab){ + Fts3Table *p = (Fts3Table*)pVtab; + sqlite3Fts3PendingTermsClear(p); + assert( p->inTransaction!=0 ); + TESTONLY( p->inTransaction = 0 ); + TESTONLY( p->mxSavepoint = -1; ); + return SQLITE_OK; +} + +/* +** When called, *ppPoslist must point to the byte immediately following the +** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function +** moves *ppPoslist so that it instead points to the first byte of the +** same position list. +*/ +static void fts3ReversePoslist(char *pStart, char **ppPoslist){ + char *p = &(*ppPoslist)[-2]; + char c = 0; + + while( p>pStart && (c=*p--)==0 ); + while( p>pStart && (*p & 0x80) | c ){ + c = *p--; + } + if( p>pStart ){ p = &p[2]; } + while( *p++&0x80 ); + *ppPoslist = p; +} + +/* +** Helper function used by the implementation of the overloaded snippet(), +** offsets() and optimize() SQL functions. +** +** If the value passed as the third argument is a blob of size +** sizeof(Fts3Cursor*), then the blob contents are copied to the +** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error +** message is written to context pContext and SQLITE_ERROR returned. The +** string passed via zFunc is used as part of the error message. +*/ +static int fts3FunctionArg( + sqlite3_context *pContext, /* SQL function call context */ + const char *zFunc, /* Function name */ + sqlite3_value *pVal, /* argv[0] passed to function */ + Fts3Cursor **ppCsr /* OUT: Store cursor handle here */ +){ + Fts3Cursor *pRet; + if( sqlite3_value_type(pVal)!=SQLITE_BLOB + || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *) + ){ + char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc); + sqlite3_result_error(pContext, zErr, -1); + sqlite3_free(zErr); + return SQLITE_ERROR; + } + memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *)); + *ppCsr = pRet; + return SQLITE_OK; +} + +/* +** Implementation of the snippet() function for FTS3 +*/ +static void fts3SnippetFunc( + sqlite3_context *pContext, /* SQLite function call context */ + int nVal, /* Size of apVal[] array */ + sqlite3_value **apVal /* Array of arguments */ +){ + Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ + const char *zStart = ""; + const char *zEnd = ""; + const char *zEllipsis = "..."; + int iCol = -1; + int nToken = 15; /* Default number of tokens in snippet */ + + /* There must be at least one argument passed to this function (otherwise + ** the non-overloaded version would have been called instead of this one). + */ + assert( nVal>=1 ); + + if( nVal>6 ){ + sqlite3_result_error(pContext, + "wrong number of arguments to function snippet()", -1); + return; + } + if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return; + + switch( nVal ){ + case 6: nToken = sqlite3_value_int(apVal[5]); + case 5: iCol = sqlite3_value_int(apVal[4]); + case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); + case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]); + case 2: zStart = (const char*)sqlite3_value_text(apVal[1]); + } + if( !zEllipsis || !zEnd || !zStart ){ + sqlite3_result_error_nomem(pContext); + }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ + sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); + } +} + +/* +** Implementation of the offsets() function for FTS3 +*/ +static void fts3OffsetsFunc( + sqlite3_context *pContext, /* SQLite function call context */ + int nVal, /* Size of argument array */ + sqlite3_value **apVal /* Array of arguments */ +){ + Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ + + UNUSED_PARAMETER(nVal); + + assert( nVal==1 ); + if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return; + assert( pCsr ); + if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ + sqlite3Fts3Offsets(pContext, pCsr); + } +} + +/* +** Implementation of the special optimize() function for FTS3. This +** function merges all segments in the database to a single segment. +** Example usage is: +** +** SELECT optimize(t) FROM t LIMIT 1; +** +** where 't' is the name of an FTS3 table. +*/ +static void fts3OptimizeFunc( + sqlite3_context *pContext, /* SQLite function call context */ + int nVal, /* Size of argument array */ + sqlite3_value **apVal /* Array of arguments */ +){ + int rc; /* Return code */ + Fts3Table *p; /* Virtual table handle */ + Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */ + + UNUSED_PARAMETER(nVal); + + assert( nVal==1 ); + if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return; + p = (Fts3Table *)pCursor->base.pVtab; + assert( p ); + + rc = sqlite3Fts3Optimize(p); + + switch( rc ){ + case SQLITE_OK: + sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); + break; + case SQLITE_DONE: + sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC); + break; + default: + sqlite3_result_error_code(pContext, rc); + break; + } +} + +/* +** Implementation of the matchinfo() function for FTS3 +*/ +static void fts3MatchinfoFunc( + sqlite3_context *pContext, /* SQLite function call context */ + int nVal, /* Size of argument array */ + sqlite3_value **apVal /* Array of arguments */ +){ + Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ + assert( nVal==1 || nVal==2 ); + if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){ + const char *zArg = 0; + if( nVal>1 ){ + zArg = (const char *)sqlite3_value_text(apVal[1]); + } + sqlite3Fts3Matchinfo(pContext, pCsr, zArg); + } +} + +/* +** This routine implements the xFindFunction method for the FTS3 +** virtual table. +*/ +static int fts3FindFunctionMethod( + sqlite3_vtab *pVtab, /* Virtual table handle */ + int nArg, /* Number of SQL function arguments */ + const char *zName, /* Name of SQL function */ + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ + void **ppArg /* Unused */ +){ + struct Overloaded { + const char *zName; + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); + } aOverload[] = { + { "snippet", fts3SnippetFunc }, + { "offsets", fts3OffsetsFunc }, + { "optimize", fts3OptimizeFunc }, + { "matchinfo", fts3MatchinfoFunc }, + }; + int i; /* Iterator variable */ + + UNUSED_PARAMETER(pVtab); + UNUSED_PARAMETER(nArg); + UNUSED_PARAMETER(ppArg); + + for(i=0; idb; /* Database connection */ + int rc; /* Return Code */ + + /* As it happens, the pending terms table is always empty here. This is + ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction + ** always opens a savepoint transaction. And the xSavepoint() method + ** flushes the pending terms table. But leave the (no-op) call to + ** PendingTermsFlush() in in case that changes. + */ + assert( p->nPendingData==0 ); + rc = sqlite3Fts3PendingTermsFlush(p); + + if( p->zContentTbl==0 ){ + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';", + p->zDb, p->zName, zName + ); + } + + if( p->bHasDocsize ){ + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';", + p->zDb, p->zName, zName + ); + } + if( p->bHasStat ){ + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';", + p->zDb, p->zName, zName + ); + } + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';", + p->zDb, p->zName, zName + ); + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';", + p->zDb, p->zName, zName + ); + return rc; +} + +/* +** The xSavepoint() method. +** +** Flush the contents of the pending-terms table to disk. +*/ +static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ + int rc = SQLITE_OK; + UNUSED_PARAMETER(iSavepoint); + assert( ((Fts3Table *)pVtab)->inTransaction ); + assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint ); + TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint ); + if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){ + rc = fts3SyncMethod(pVtab); + } + return rc; +} + +/* +** The xRelease() method. +** +** This is a no-op. +*/ +static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ + TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); + UNUSED_PARAMETER(iSavepoint); + UNUSED_PARAMETER(pVtab); + assert( p->inTransaction ); + assert( p->mxSavepoint >= iSavepoint ); + TESTONLY( p->mxSavepoint = iSavepoint-1 ); + return SQLITE_OK; +} + +/* +** The xRollbackTo() method. +** +** Discard the contents of the pending terms table. +*/ +static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ + Fts3Table *p = (Fts3Table*)pVtab; + UNUSED_PARAMETER(iSavepoint); + assert( p->inTransaction ); + assert( p->mxSavepoint >= iSavepoint ); + TESTONLY( p->mxSavepoint = iSavepoint ); + sqlite3Fts3PendingTermsClear(p); + return SQLITE_OK; +} + +static const sqlite3_module fts3Module = { + /* iVersion */ 2, + /* xCreate */ fts3CreateMethod, + /* xConnect */ fts3ConnectMethod, + /* xBestIndex */ fts3BestIndexMethod, + /* xDisconnect */ fts3DisconnectMethod, + /* xDestroy */ fts3DestroyMethod, + /* xOpen */ fts3OpenMethod, + /* xClose */ fts3CloseMethod, + /* xFilter */ fts3FilterMethod, + /* xNext */ fts3NextMethod, + /* xEof */ fts3EofMethod, + /* xColumn */ fts3ColumnMethod, + /* xRowid */ fts3RowidMethod, + /* xUpdate */ fts3UpdateMethod, + /* xBegin */ fts3BeginMethod, + /* xSync */ fts3SyncMethod, + /* xCommit */ fts3CommitMethod, + /* xRollback */ fts3RollbackMethod, + /* xFindFunction */ fts3FindFunctionMethod, + /* xRename */ fts3RenameMethod, + /* xSavepoint */ fts3SavepointMethod, + /* xRelease */ fts3ReleaseMethod, + /* xRollbackTo */ fts3RollbackToMethod, +}; + +/* +** This function is registered as the module destructor (called when an +** FTS3 enabled database connection is closed). It frees the memory +** allocated for the tokenizer hash table. +*/ +static void hashDestroy(void *p){ + Fts3Hash *pHash = (Fts3Hash *)p; + sqlite3Fts3HashClear(pHash); + sqlite3_free(pHash); +} + +/* +** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are +** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c +** respectively. The following three forward declarations are for functions +** declared in these files used to retrieve the respective implementations. +** +** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed +** to by the argument to point to the "simple" tokenizer implementation. +** And so on. +*/ +SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); +SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 +SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule); +#endif +#ifdef SQLITE_ENABLE_ICU +SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); +#endif + +/* +** Initialize the fts3 extension. If this extension is built as part +** of the sqlite library, then this function is called directly by +** SQLite. If fts3 is built as a dynamically loadable extension, this +** function is called by the sqlite3_extension_init() entry point. +*/ +SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ + int rc = SQLITE_OK; + Fts3Hash *pHash = 0; + const sqlite3_tokenizer_module *pSimple = 0; + const sqlite3_tokenizer_module *pPorter = 0; +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 + const sqlite3_tokenizer_module *pUnicode = 0; +#endif + +#ifdef SQLITE_ENABLE_ICU + const sqlite3_tokenizer_module *pIcu = 0; + sqlite3Fts3IcuTokenizerModule(&pIcu); +#endif + +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 + sqlite3Fts3UnicodeTokenizer(&pUnicode); +#endif + +#ifdef SQLITE_TEST + rc = sqlite3Fts3InitTerm(db); + if( rc!=SQLITE_OK ) return rc; +#endif + + rc = sqlite3Fts3InitAux(db); + if( rc!=SQLITE_OK ) return rc; + + sqlite3Fts3SimpleTokenizerModule(&pSimple); + sqlite3Fts3PorterTokenizerModule(&pPorter); + + /* Allocate and initialize the hash-table used to store tokenizers. */ + pHash = sqlite3_malloc(sizeof(Fts3Hash)); + if( !pHash ){ + rc = SQLITE_NOMEM; + }else{ + sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); + } + + /* Load the built-in tokenizers into the hash table */ + if( rc==SQLITE_OK ){ + if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple) + || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) + +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 + || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) +#endif +#ifdef SQLITE_ENABLE_ICU + || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu)) +#endif + ){ + rc = SQLITE_NOMEM; + } + } + +#ifdef SQLITE_TEST + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3ExprInitTestInterface(db); + } +#endif + + /* Create the virtual table wrapper around the hash-table and overload + ** the two scalar functions. If this is successful, register the + ** module with sqlite. + */ + if( SQLITE_OK==rc + && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer")) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1)) + ){ + rc = sqlite3_create_module_v2( + db, "fts3", &fts3Module, (void *)pHash, hashDestroy + ); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_module_v2( + db, "fts4", &fts3Module, (void *)pHash, 0 + ); + } + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3InitTok(db, (void *)pHash); + } + return rc; + } + + + /* An error has occurred. Delete the hash table and return the error code. */ + assert( rc!=SQLITE_OK ); + if( pHash ){ + sqlite3Fts3HashClear(pHash); + sqlite3_free(pHash); + } + return rc; +} + +/* +** Allocate an Fts3MultiSegReader for each token in the expression headed +** by pExpr. +** +** An Fts3SegReader object is a cursor that can seek or scan a range of +** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple +** Fts3SegReader objects internally to provide an interface to seek or scan +** within the union of all segments of a b-tree. Hence the name. +** +** If the allocated Fts3MultiSegReader just seeks to a single entry in a +** segment b-tree (if the term is not a prefix or it is a prefix for which +** there exists prefix b-tree of the right length) then it may be traversed +** and merged incrementally. Otherwise, it has to be merged into an in-memory +** doclist and then traversed. +*/ +static void fts3EvalAllocateReaders( + Fts3Cursor *pCsr, /* FTS cursor handle */ + Fts3Expr *pExpr, /* Allocate readers for this expression */ + int *pnToken, /* OUT: Total number of tokens in phrase. */ + int *pnOr, /* OUT: Total number of OR nodes in expr. */ + int *pRc /* IN/OUT: Error code */ +){ + if( pExpr && SQLITE_OK==*pRc ){ + if( pExpr->eType==FTSQUERY_PHRASE ){ + int i; + int nToken = pExpr->pPhrase->nToken; + *pnToken += nToken; + for(i=0; ipPhrase->aToken[i]; + int rc = fts3TermSegReaderCursor(pCsr, + pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr + ); + if( rc!=SQLITE_OK ){ + *pRc = rc; + return; + } + } + assert( pExpr->pPhrase->iDoclistToken==0 ); + pExpr->pPhrase->iDoclistToken = -1; + }else{ + *pnOr += (pExpr->eType==FTSQUERY_OR); + fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc); + fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc); + } + } +} + +/* +** Arguments pList/nList contain the doclist for token iToken of phrase p. +** It is merged into the main doclist stored in p->doclist.aAll/nAll. +** +** This function assumes that pList points to a buffer allocated using +** sqlite3_malloc(). This function takes responsibility for eventually +** freeing the buffer. +*/ +static void fts3EvalPhraseMergeToken( + Fts3Table *pTab, /* FTS Table pointer */ + Fts3Phrase *p, /* Phrase to merge pList/nList into */ + int iToken, /* Token pList/nList corresponds to */ + char *pList, /* Pointer to doclist */ + int nList /* Number of bytes in pList */ +){ + assert( iToken!=p->iDoclistToken ); + + if( pList==0 ){ + sqlite3_free(p->doclist.aAll); + p->doclist.aAll = 0; + p->doclist.nAll = 0; + } + + else if( p->iDoclistToken<0 ){ + p->doclist.aAll = pList; + p->doclist.nAll = nList; + } + + else if( p->doclist.aAll==0 ){ + sqlite3_free(pList); + } + + else { + char *pLeft; + char *pRight; + int nLeft; + int nRight; + int nDiff; + + if( p->iDoclistTokendoclist.aAll; + nLeft = p->doclist.nAll; + pRight = pList; + nRight = nList; + nDiff = iToken - p->iDoclistToken; + }else{ + pRight = p->doclist.aAll; + nRight = p->doclist.nAll; + pLeft = pList; + nLeft = nList; + nDiff = p->iDoclistToken - iToken; + } + + fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight); + sqlite3_free(pLeft); + p->doclist.aAll = pRight; + p->doclist.nAll = nRight; + } + + if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken; +} + +/* +** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist +** does not take deferred tokens into account. +** +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. +*/ +static int fts3EvalPhraseLoad( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Phrase *p /* Phrase object */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int iToken; + int rc = SQLITE_OK; + + for(iToken=0; rc==SQLITE_OK && iTokennToken; iToken++){ + Fts3PhraseToken *pToken = &p->aToken[iToken]; + assert( pToken->pDeferred==0 || pToken->pSegcsr==0 ); + + if( pToken->pSegcsr ){ + int nThis = 0; + char *pThis = 0; + rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis); + if( rc==SQLITE_OK ){ + fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis); + } + } + assert( pToken->pSegcsr==0 ); + } + + return rc; +} + +/* +** This function is called on each phrase after the position lists for +** any deferred tokens have been loaded into memory. It updates the phrases +** current position list to include only those positions that are really +** instances of the phrase (after considering deferred tokens). If this +** means that the phrase does not appear in the current row, doclist.pList +** and doclist.nList are both zeroed. +** +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. +*/ +static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ + int iToken; /* Used to iterate through phrase tokens */ + char *aPoslist = 0; /* Position list for deferred tokens */ + int nPoslist = 0; /* Number of bytes in aPoslist */ + int iPrev = -1; /* Token number of previous deferred token */ + + assert( pPhrase->doclist.bFreeList==0 ); + + for(iToken=0; iTokennToken; iToken++){ + Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; + Fts3DeferredToken *pDeferred = pToken->pDeferred; + + if( pDeferred ){ + char *pList; + int nList; + int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList); + if( rc!=SQLITE_OK ) return rc; + + if( pList==0 ){ + sqlite3_free(aPoslist); + pPhrase->doclist.pList = 0; + pPhrase->doclist.nList = 0; + return SQLITE_OK; + + }else if( aPoslist==0 ){ + aPoslist = pList; + nPoslist = nList; + + }else{ + char *aOut = pList; + char *p1 = aPoslist; + char *p2 = aOut; + + assert( iPrev>=0 ); + fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2); + sqlite3_free(aPoslist); + aPoslist = pList; + nPoslist = (int)(aOut - aPoslist); + if( nPoslist==0 ){ + sqlite3_free(aPoslist); + pPhrase->doclist.pList = 0; + pPhrase->doclist.nList = 0; + return SQLITE_OK; + } + } + iPrev = iToken; + } + } + + if( iPrev>=0 ){ + int nMaxUndeferred = pPhrase->iDoclistToken; + if( nMaxUndeferred<0 ){ + pPhrase->doclist.pList = aPoslist; + pPhrase->doclist.nList = nPoslist; + pPhrase->doclist.iDocid = pCsr->iPrevId; + pPhrase->doclist.bFreeList = 1; + }else{ + int nDistance; + char *p1; + char *p2; + char *aOut; + + if( nMaxUndeferred>iPrev ){ + p1 = aPoslist; + p2 = pPhrase->doclist.pList; + nDistance = nMaxUndeferred - iPrev; + }else{ + p1 = pPhrase->doclist.pList; + p2 = aPoslist; + nDistance = iPrev - nMaxUndeferred; + } + + aOut = (char *)sqlite3_malloc(nPoslist+8); + if( !aOut ){ + sqlite3_free(aPoslist); + return SQLITE_NOMEM; + } + + pPhrase->doclist.pList = aOut; + if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){ + pPhrase->doclist.bFreeList = 1; + pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList); + }else{ + sqlite3_free(aOut); + pPhrase->doclist.pList = 0; + pPhrase->doclist.nList = 0; + } + sqlite3_free(aPoslist); + } + } + + return SQLITE_OK; +} + +/* +** Maximum number of tokens a phrase may have to be considered for the +** incremental doclists strategy. +*/ +#define MAX_INCR_PHRASE_TOKENS 4 + +/* +** This function is called for each Fts3Phrase in a full-text query +** expression to initialize the mechanism for returning rows. Once this +** function has been called successfully on an Fts3Phrase, it may be +** used with fts3EvalPhraseNext() to iterate through the matching docids. +** +** If parameter bOptOk is true, then the phrase may (or may not) use the +** incremental loading strategy. Otherwise, the entire doclist is loaded into +** memory within this call. +** +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. +*/ +static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; /* Error code */ + int i; + + /* Determine if doclists may be loaded from disk incrementally. This is + ** possible if the bOptOk argument is true, the FTS doclists will be + ** scanned in forward order, and the phrase consists of + ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first" + ** tokens or prefix tokens that cannot use a prefix-index. */ + int bHaveIncr = 0; + int bIncrOk = (bOptOk + && pCsr->bDesc==pTab->bDescIdx + && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 + && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 +#ifdef SQLITE_TEST + && pTab->bNoIncrDoclist==0 +#endif + ); + for(i=0; bIncrOk==1 && inToken; i++){ + Fts3PhraseToken *pToken = &p->aToken[i]; + if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){ + bIncrOk = 0; + } + if( pToken->pSegcsr ) bHaveIncr = 1; + } + + if( bIncrOk && bHaveIncr ){ + /* Use the incremental approach. */ + int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn); + for(i=0; rc==SQLITE_OK && inToken; i++){ + Fts3PhraseToken *pToken = &p->aToken[i]; + Fts3MultiSegReader *pSegcsr = pToken->pSegcsr; + if( pSegcsr ){ + rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n); + } + } + p->bIncr = 1; + }else{ + /* Load the full doclist for the phrase into memory. */ + rc = fts3EvalPhraseLoad(pCsr, p); + p->bIncr = 0; + } + + assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr ); + return rc; +} + +/* +** This function is used to iterate backwards (from the end to start) +** through doclists. It is used by this module to iterate through phrase +** doclists in reverse and by the fts3_write.c module to iterate through +** pending-terms lists when writing to databases with "order=desc". +** +** The doclist may be sorted in ascending (parameter bDescIdx==0) or +** descending (parameter bDescIdx==1) order of docid. Regardless, this +** function iterates from the end of the doclist to the beginning. +*/ +SQLITE_PRIVATE void sqlite3Fts3DoclistPrev( + int bDescIdx, /* True if the doclist is desc */ + char *aDoclist, /* Pointer to entire doclist */ + int nDoclist, /* Length of aDoclist in bytes */ + char **ppIter, /* IN/OUT: Iterator pointer */ + sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ + int *pnList, /* OUT: List length pointer */ + u8 *pbEof /* OUT: End-of-file flag */ +){ + char *p = *ppIter; + + assert( nDoclist>0 ); + assert( *pbEof==0 ); + assert( p || *piDocid==0 ); + assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) ); + + if( p==0 ){ + sqlite3_int64 iDocid = 0; + char *pNext = 0; + char *pDocid = aDoclist; + char *pEnd = &aDoclist[nDoclist]; + int iMul = 1; + + while( pDocid0 ); + assert( *pbEof==0 ); + assert( p || *piDocid==0 ); + assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) ); + + if( p==0 ){ + p = aDoclist; + p += sqlite3Fts3GetVarint(p, piDocid); + }else{ + fts3PoslistCopy(0, &p); + if( p>=&aDoclist[nDoclist] ){ + *pbEof = 1; + }else{ + sqlite3_int64 iVar; + p += sqlite3Fts3GetVarint(p, &iVar); + *piDocid += ((bDescIdx ? -1 : 1) * iVar); + } + } + + *ppIter = p; +} + +/* +** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof +** to true if EOF is reached. +*/ +static void fts3EvalDlPhraseNext( + Fts3Table *pTab, + Fts3Doclist *pDL, + u8 *pbEof +){ + char *pIter; /* Used to iterate through aAll */ + char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */ + + if( pDL->pNextDocid ){ + pIter = pDL->pNextDocid; + }else{ + pIter = pDL->aAll; + } + + if( pIter>=pEnd ){ + /* We have already reached the end of this doclist. EOF. */ + *pbEof = 1; + }else{ + sqlite3_int64 iDelta; + pIter += sqlite3Fts3GetVarint(pIter, &iDelta); + if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){ + pDL->iDocid += iDelta; + }else{ + pDL->iDocid -= iDelta; + } + pDL->pList = pIter; + fts3PoslistCopy(0, &pIter); + pDL->nList = (int)(pIter - pDL->pList); + + /* pIter now points just past the 0x00 that terminates the position- + ** list for document pDL->iDocid. However, if this position-list was + ** edited in place by fts3EvalNearTrim(), then pIter may not actually + ** point to the start of the next docid value. The following line deals + ** with this case by advancing pIter past the zero-padding added by + ** fts3EvalNearTrim(). */ + while( pIterpNextDocid = pIter; + assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter ); + *pbEof = 0; + } +} + +/* +** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext(). +*/ +typedef struct TokenDoclist TokenDoclist; +struct TokenDoclist { + int bIgnore; + sqlite3_int64 iDocid; + char *pList; + int nList; +}; + +/* +** Token pToken is an incrementally loaded token that is part of a +** multi-token phrase. Advance it to the next matching document in the +** database and populate output variable *p with the details of the new +** entry. Or, if the iterator has reached EOF, set *pbEof to true. +** +** If an error occurs, return an SQLite error code. Otherwise, return +** SQLITE_OK. +*/ +static int incrPhraseTokenNext( + Fts3Table *pTab, /* Virtual table handle */ + Fts3Phrase *pPhrase, /* Phrase to advance token of */ + int iToken, /* Specific token to advance */ + TokenDoclist *p, /* OUT: Docid and doclist for new entry */ + u8 *pbEof /* OUT: True if iterator is at EOF */ +){ + int rc = SQLITE_OK; + + if( pPhrase->iDoclistToken==iToken ){ + assert( p->bIgnore==0 ); + assert( pPhrase->aToken[iToken].pSegcsr==0 ); + fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof); + p->pList = pPhrase->doclist.pList; + p->nList = pPhrase->doclist.nList; + p->iDocid = pPhrase->doclist.iDocid; + }else{ + Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; + assert( pToken->pDeferred==0 ); + assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 ); + if( pToken->pSegcsr ){ + assert( p->bIgnore==0 ); + rc = sqlite3Fts3MsrIncrNext( + pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList + ); + if( p->pList==0 ) *pbEof = 1; + }else{ + p->bIgnore = 1; + } + } + + return rc; +} + + +/* +** The phrase iterator passed as the second argument: +** +** * features at least one token that uses an incremental doclist, and +** +** * does not contain any deferred tokens. +** +** Advance it to the next matching documnent in the database and populate +** the Fts3Doclist.pList and nList fields. +** +** If there is no "next" entry and no error occurs, then *pbEof is set to +** 1 before returning. Otherwise, if no error occurs and the iterator is +** successfully advanced, *pbEof is set to 0. +** +** If an error occurs, return an SQLite error code. Otherwise, return +** SQLITE_OK. +*/ +static int fts3EvalIncrPhraseNext( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Phrase *p, /* Phrase object to advance to next docid */ + u8 *pbEof /* OUT: Set to 1 if EOF */ +){ + int rc = SQLITE_OK; + Fts3Doclist *pDL = &p->doclist; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + u8 bEof = 0; + + /* This is only called if it is guaranteed that the phrase has at least + ** one incremental token. In which case the bIncr flag is set. */ + assert( p->bIncr==1 ); + + if( p->nToken==1 && p->bIncr ){ + rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, + &pDL->iDocid, &pDL->pList, &pDL->nList + ); + if( pDL->pList==0 ) bEof = 1; + }else{ + int bDescDoclist = pCsr->bDesc; + struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS]; + + memset(a, 0, sizeof(a)); + assert( p->nToken<=MAX_INCR_PHRASE_TOKENS ); + assert( p->iDoclistTokennToken && bEof==0; i++){ + rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); + if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){ + iMax = a[i].iDocid; + bMaxSet = 1; + } + } + assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 ); + assert( rc!=SQLITE_OK || bMaxSet ); + + /* Keep advancing iterators until they all point to the same document */ + for(i=0; inToken; i++){ + while( rc==SQLITE_OK && bEof==0 + && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 + ){ + rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); + if( DOCID_CMP(a[i].iDocid, iMax)>0 ){ + iMax = a[i].iDocid; + i = 0; + } + } + } + + /* Check if the current entries really are a phrase match */ + if( bEof==0 ){ + int nList = 0; + int nByte = a[p->nToken-1].nList; + char *aDoclist = sqlite3_malloc(nByte+1); + if( !aDoclist ) return SQLITE_NOMEM; + memcpy(aDoclist, a[p->nToken-1].pList, nByte+1); + + for(i=0; i<(p->nToken-1); i++){ + if( a[i].bIgnore==0 ){ + char *pL = a[i].pList; + char *pR = aDoclist; + char *pOut = aDoclist; + int nDist = p->nToken-1-i; + int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR); + if( res==0 ) break; + nList = (int)(pOut - aDoclist); + } + } + if( i==(p->nToken-1) ){ + pDL->iDocid = iMax; + pDL->pList = aDoclist; + pDL->nList = nList; + pDL->bFreeList = 1; + break; + } + sqlite3_free(aDoclist); + } + } + } + + *pbEof = bEof; + return rc; +} + +/* +** Attempt to move the phrase iterator to point to the next matching docid. +** If an error occurs, return an SQLite error code. Otherwise, return +** SQLITE_OK. +** +** If there is no "next" entry and no error occurs, then *pbEof is set to +** 1 before returning. Otherwise, if no error occurs and the iterator is +** successfully advanced, *pbEof is set to 0. +*/ +static int fts3EvalPhraseNext( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Phrase *p, /* Phrase object to advance to next docid */ + u8 *pbEof /* OUT: Set to 1 if EOF */ +){ + int rc = SQLITE_OK; + Fts3Doclist *pDL = &p->doclist; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + + if( p->bIncr ){ + rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof); + }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){ + sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, + &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof + ); + pDL->pList = pDL->pNextDocid; + }else{ + fts3EvalDlPhraseNext(pTab, pDL, pbEof); + } + + return rc; +} + +/* +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** Otherwise, fts3EvalPhraseStart() is called on all phrases within the +** expression. Also the Fts3Expr.bDeferred variable is set to true for any +** expressions for which all descendent tokens are deferred. +** +** If parameter bOptOk is zero, then it is guaranteed that the +** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for +** each phrase in the expression (subject to deferred token processing). +** Or, if bOptOk is non-zero, then one or more tokens within the expression +** may be loaded incrementally, meaning doclist.aAll/nAll is not available. +** +** If an error occurs within this function, *pRc is set to an SQLite error +** code before returning. +*/ +static void fts3EvalStartReaders( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Expr *pExpr, /* Expression to initialize phrases in */ + int *pRc /* IN/OUT: Error code */ +){ + if( pExpr && SQLITE_OK==*pRc ){ + if( pExpr->eType==FTSQUERY_PHRASE ){ + int i; + int nToken = pExpr->pPhrase->nToken; + for(i=0; ipPhrase->aToken[i].pDeferred==0 ) break; + } + pExpr->bDeferred = (i==nToken); + *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase); + }else{ + fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc); + fts3EvalStartReaders(pCsr, pExpr->pRight, pRc); + pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred); + } + } +} + +/* +** An array of the following structures is assembled as part of the process +** of selecting tokens to defer before the query starts executing (as part +** of the xFilter() method). There is one element in the array for each +** token in the FTS expression. +** +** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong +** to phrases that are connected only by AND and NEAR operators (not OR or +** NOT). When determining tokens to defer, each AND/NEAR cluster is considered +** separately. The root of a tokens AND/NEAR cluster is stored in +** Fts3TokenAndCost.pRoot. +*/ +typedef struct Fts3TokenAndCost Fts3TokenAndCost; +struct Fts3TokenAndCost { + Fts3Phrase *pPhrase; /* The phrase the token belongs to */ + int iToken; /* Position of token in phrase */ + Fts3PhraseToken *pToken; /* The token itself */ + Fts3Expr *pRoot; /* Root of NEAR/AND cluster */ + int nOvfl; /* Number of overflow pages to load doclist */ + int iCol; /* The column the token must match */ +}; + +/* +** This function is used to populate an allocated Fts3TokenAndCost array. +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** Otherwise, if an error occurs during execution, *pRc is set to an +** SQLite error code. +*/ +static void fts3EvalTokenCosts( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */ + Fts3Expr *pExpr, /* Expression to consider */ + Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */ + Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */ + int *pRc /* IN/OUT: Error code */ +){ + if( *pRc==SQLITE_OK ){ + if( pExpr->eType==FTSQUERY_PHRASE ){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + int i; + for(i=0; *pRc==SQLITE_OK && inToken; i++){ + Fts3TokenAndCost *pTC = (*ppTC)++; + pTC->pPhrase = pPhrase; + pTC->iToken = i; + pTC->pRoot = pRoot; + pTC->pToken = &pPhrase->aToken[i]; + pTC->iCol = pPhrase->iColumn; + *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl); + } + }else if( pExpr->eType!=FTSQUERY_NOT ){ + assert( pExpr->eType==FTSQUERY_OR + || pExpr->eType==FTSQUERY_AND + || pExpr->eType==FTSQUERY_NEAR + ); + assert( pExpr->pLeft && pExpr->pRight ); + if( pExpr->eType==FTSQUERY_OR ){ + pRoot = pExpr->pLeft; + **ppOr = pRoot; + (*ppOr)++; + } + fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc); + if( pExpr->eType==FTSQUERY_OR ){ + pRoot = pExpr->pRight; + **ppOr = pRoot; + (*ppOr)++; + } + fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc); + } + } +} + +/* +** Determine the average document (row) size in pages. If successful, +** write this value to *pnPage and return SQLITE_OK. Otherwise, return +** an SQLite error code. +** +** The average document size in pages is calculated by first calculating +** determining the average size in bytes, B. If B is less than the amount +** of data that will fit on a single leaf page of an intkey table in +** this database, then the average docsize is 1. Otherwise, it is 1 plus +** the number of overflow pages consumed by a record B bytes in size. +*/ +static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){ + if( pCsr->nRowAvg==0 ){ + /* The average document size, which is required to calculate the cost + ** of each doclist, has not yet been determined. Read the required + ** data from the %_stat table to calculate it. + ** + ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 + ** varints, where nCol is the number of columns in the FTS3 table. + ** The first varint is the number of documents currently stored in + ** the table. The following nCol varints contain the total amount of + ** data stored in all rows of each column of the table, from left + ** to right. + */ + int rc; + Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; + sqlite3_stmt *pStmt; + sqlite3_int64 nDoc = 0; + sqlite3_int64 nByte = 0; + const char *pEnd; + const char *a; + + rc = sqlite3Fts3SelectDoctotal(p, &pStmt); + if( rc!=SQLITE_OK ) return rc; + a = sqlite3_column_blob(pStmt, 0); + assert( a ); + + pEnd = &a[sqlite3_column_bytes(pStmt, 0)]; + a += sqlite3Fts3GetVarint(a, &nDoc); + while( anDoc = nDoc; + pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz); + assert( pCsr->nRowAvg>0 ); + rc = sqlite3_reset(pStmt); + if( rc!=SQLITE_OK ) return rc; + } + + *pnPage = pCsr->nRowAvg; + return SQLITE_OK; +} + +/* +** This function is called to select the tokens (if any) that will be +** deferred. The array aTC[] has already been populated when this is +** called. +** +** This function is called once for each AND/NEAR cluster in the +** expression. Each invocation determines which tokens to defer within +** the cluster with root node pRoot. See comments above the definition +** of struct Fts3TokenAndCost for more details. +** +** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken() +** called on each token to defer. Otherwise, an SQLite error code is +** returned. +*/ +static int fts3EvalSelectDeferred( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Expr *pRoot, /* Consider tokens with this root node */ + Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */ + int nTC /* Number of entries in aTC[] */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int nDocSize = 0; /* Number of pages per doc loaded */ + int rc = SQLITE_OK; /* Return code */ + int ii; /* Iterator variable for various purposes */ + int nOvfl = 0; /* Total overflow pages used by doclists */ + int nToken = 0; /* Total number of tokens in cluster */ + + int nMinEst = 0; /* The minimum count for any phrase so far. */ + int nLoad4 = 1; /* (Phrases that will be loaded)^4. */ + + /* Tokens are never deferred for FTS tables created using the content=xxx + ** option. The reason being that it is not guaranteed that the content + ** table actually contains the same data as the index. To prevent this from + ** causing any problems, the deferred token optimization is completely + ** disabled for content=xxx tables. */ + if( pTab->zContentTbl ){ + return SQLITE_OK; + } + + /* Count the tokens in this AND/NEAR cluster. If none of the doclists + ** associated with the tokens spill onto overflow pages, or if there is + ** only 1 token, exit early. No tokens to defer in this case. */ + for(ii=0; ii0 ); + + + /* Iterate through all tokens in this AND/NEAR cluster, in ascending order + ** of the number of overflow pages that will be loaded by the pager layer + ** to retrieve the entire doclist for the token from the full-text index. + ** Load the doclists for tokens that are either: + ** + ** a. The cheapest token in the entire query (i.e. the one visited by the + ** first iteration of this loop), or + ** + ** b. Part of a multi-token phrase. + ** + ** After each token doclist is loaded, merge it with the others from the + ** same phrase and count the number of documents that the merged doclist + ** contains. Set variable "nMinEst" to the smallest number of documents in + ** any phrase doclist for which 1 or more token doclists have been loaded. + ** Let nOther be the number of other phrases for which it is certain that + ** one or more tokens will not be deferred. + ** + ** Then, for each token, defer it if loading the doclist would result in + ** loading N or more overflow pages into memory, where N is computed as: + ** + ** (nMinEst + 4^nOther - 1) / (4^nOther) + */ + for(ii=0; iinOvfl) + ){ + pTC = &aTC[iTC]; + } + } + assert( pTC ); + + if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){ + /* The number of overflow pages to load for this (and therefore all + ** subsequent) tokens is greater than the estimated number of pages + ** that will be loaded if all subsequent tokens are deferred. + */ + Fts3PhraseToken *pToken = pTC->pToken; + rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol); + fts3SegReaderCursorFree(pToken->pSegcsr); + pToken->pSegcsr = 0; + }else{ + /* Set nLoad4 to the value of (4^nOther) for the next iteration of the + ** for-loop. Except, limit the value to 2^24 to prevent it from + ** overflowing the 32-bit integer it is stored in. */ + if( ii<12 ) nLoad4 = nLoad4*4; + + if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){ + /* Either this is the cheapest token in the entire query, or it is + ** part of a multi-token phrase. Either way, the entire doclist will + ** (eventually) be loaded into memory. It may as well be now. */ + Fts3PhraseToken *pToken = pTC->pToken; + int nList = 0; + char *pList = 0; + rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList); + assert( rc==SQLITE_OK || pList==0 ); + if( rc==SQLITE_OK ){ + int nCount; + fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList); + nCount = fts3DoclistCountDocids( + pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll + ); + if( ii==0 || nCountpToken = 0; + } + + return rc; +} + +/* +** This function is called from within the xFilter method. It initializes +** the full-text query currently stored in pCsr->pExpr. To iterate through +** the results of a query, the caller does: +** +** fts3EvalStart(pCsr); +** while( 1 ){ +** fts3EvalNext(pCsr); +** if( pCsr->bEof ) break; +** ... return row pCsr->iPrevId to the caller ... +** } +*/ +static int fts3EvalStart(Fts3Cursor *pCsr){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; + int nToken = 0; + int nOr = 0; + + /* Allocate a MultiSegReader for each token in the expression. */ + fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc); + + /* Determine which, if any, tokens in the expression should be deferred. */ +#ifndef SQLITE_DISABLE_FTS4_DEFERRED + if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){ + Fts3TokenAndCost *aTC; + Fts3Expr **apOr; + aTC = (Fts3TokenAndCost *)sqlite3_malloc( + sizeof(Fts3TokenAndCost) * nToken + + sizeof(Fts3Expr *) * nOr * 2 + ); + apOr = (Fts3Expr **)&aTC[nToken]; + + if( !aTC ){ + rc = SQLITE_NOMEM; + }else{ + int ii; + Fts3TokenAndCost *pTC = aTC; + Fts3Expr **ppOr = apOr; + + fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc); + nToken = (int)(pTC-aTC); + nOr = (int)(ppOr-apOr); + + if( rc==SQLITE_OK ){ + rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken); + for(ii=0; rc==SQLITE_OK && iipExpr, &rc); + return rc; +} + +/* +** Invalidate the current position list for phrase pPhrase. +*/ +static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){ + if( pPhrase->doclist.bFreeList ){ + sqlite3_free(pPhrase->doclist.pList); + } + pPhrase->doclist.pList = 0; + pPhrase->doclist.nList = 0; + pPhrase->doclist.bFreeList = 0; +} + +/* +** This function is called to edit the position list associated with +** the phrase object passed as the fifth argument according to a NEAR +** condition. For example: +** +** abc NEAR/5 "def ghi" +** +** Parameter nNear is passed the NEAR distance of the expression (5 in +** the example above). When this function is called, *paPoslist points to +** the position list, and *pnToken is the number of phrase tokens in, the +** phrase on the other side of the NEAR operator to pPhrase. For example, +** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to +** the position list associated with phrase "abc". +** +** All positions in the pPhrase position list that are not sufficiently +** close to a position in the *paPoslist position list are removed. If this +** leaves 0 positions, zero is returned. Otherwise, non-zero. +** +** Before returning, *paPoslist is set to point to the position lsit +** associated with pPhrase. And *pnToken is set to the number of tokens in +** pPhrase. +*/ +static int fts3EvalNearTrim( + int nNear, /* NEAR distance. As in "NEAR/nNear". */ + char *aTmp, /* Temporary space to use */ + char **paPoslist, /* IN/OUT: Position list */ + int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */ + Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */ +){ + int nParam1 = nNear + pPhrase->nToken; + int nParam2 = nNear + *pnToken; + int nNew; + char *p2; + char *pOut; + int res; + + assert( pPhrase->doclist.pList ); + + p2 = pOut = pPhrase->doclist.pList; + res = fts3PoslistNearMerge( + &pOut, aTmp, nParam1, nParam2, paPoslist, &p2 + ); + if( res ){ + nNew = (int)(pOut - pPhrase->doclist.pList) - 1; + assert( pPhrase->doclist.pList[nNew]=='\0' ); + assert( nNew<=pPhrase->doclist.nList && nNew>0 ); + memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew); + pPhrase->doclist.nList = nNew; + *paPoslist = pPhrase->doclist.pList; + *pnToken = pPhrase->nToken; + } + + return res; +} + +/* +** This function is a no-op if *pRc is other than SQLITE_OK when it is called. +** Otherwise, it advances the expression passed as the second argument to +** point to the next matching row in the database. Expressions iterate through +** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero, +** or descending if it is non-zero. +** +** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if +** successful, the following variables in pExpr are set: +** +** Fts3Expr.bEof (non-zero if EOF - there is no next row) +** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row) +** +** If the expression is of type FTSQUERY_PHRASE, and the expression is not +** at EOF, then the following variables are populated with the position list +** for the phrase for the visited row: +** +** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes) +** FTs3Expr.pPhrase->doclist.pList (pointer to position list) +** +** It says above that this function advances the expression to the next +** matching row. This is usually true, but there are the following exceptions: +** +** 1. Deferred tokens are not taken into account. If a phrase consists +** entirely of deferred tokens, it is assumed to match every row in +** the db. In this case the position-list is not populated at all. +** +** Or, if a phrase contains one or more deferred tokens and one or +** more non-deferred tokens, then the expression is advanced to the +** next possible match, considering only non-deferred tokens. In other +** words, if the phrase is "A B C", and "B" is deferred, the expression +** is advanced to the next row that contains an instance of "A * C", +** where "*" may match any single token. The position list in this case +** is populated as for "A * C" before returning. +** +** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is +** advanced to point to the next row that matches "x AND y". +** +** See fts3EvalTestDeferredAndNear() for details on testing if a row is +** really a match, taking into account deferred tokens and NEAR operators. +*/ +static void fts3EvalNextRow( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Expr *pExpr, /* Expr. to advance to next matching row */ + int *pRc /* IN/OUT: Error code */ +){ + if( *pRc==SQLITE_OK ){ + int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */ + assert( pExpr->bEof==0 ); + pExpr->bStart = 1; + + switch( pExpr->eType ){ + case FTSQUERY_NEAR: + case FTSQUERY_AND: { + Fts3Expr *pLeft = pExpr->pLeft; + Fts3Expr *pRight = pExpr->pRight; + assert( !pLeft->bDeferred || !pRight->bDeferred ); + + if( pLeft->bDeferred ){ + /* LHS is entirely deferred. So we assume it matches every row. + ** Advance the RHS iterator to find the next row visited. */ + fts3EvalNextRow(pCsr, pRight, pRc); + pExpr->iDocid = pRight->iDocid; + pExpr->bEof = pRight->bEof; + }else if( pRight->bDeferred ){ + /* RHS is entirely deferred. So we assume it matches every row. + ** Advance the LHS iterator to find the next row visited. */ + fts3EvalNextRow(pCsr, pLeft, pRc); + pExpr->iDocid = pLeft->iDocid; + pExpr->bEof = pLeft->bEof; + }else{ + /* Neither the RHS or LHS are deferred. */ + fts3EvalNextRow(pCsr, pLeft, pRc); + fts3EvalNextRow(pCsr, pRight, pRc); + while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){ + sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid); + if( iDiff==0 ) break; + if( iDiff<0 ){ + fts3EvalNextRow(pCsr, pLeft, pRc); + }else{ + fts3EvalNextRow(pCsr, pRight, pRc); + } + } + pExpr->iDocid = pLeft->iDocid; + pExpr->bEof = (pLeft->bEof || pRight->bEof); + } + break; + } + + case FTSQUERY_OR: { + Fts3Expr *pLeft = pExpr->pLeft; + Fts3Expr *pRight = pExpr->pRight; + sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); + + assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid ); + assert( pRight->bStart || pLeft->iDocid==pRight->iDocid ); + + if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ + fts3EvalNextRow(pCsr, pLeft, pRc); + }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){ + fts3EvalNextRow(pCsr, pRight, pRc); + }else{ + fts3EvalNextRow(pCsr, pLeft, pRc); + fts3EvalNextRow(pCsr, pRight, pRc); + } + + pExpr->bEof = (pLeft->bEof && pRight->bEof); + iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); + if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ + pExpr->iDocid = pLeft->iDocid; + }else{ + pExpr->iDocid = pRight->iDocid; + } + + break; + } + + case FTSQUERY_NOT: { + Fts3Expr *pLeft = pExpr->pLeft; + Fts3Expr *pRight = pExpr->pRight; + + if( pRight->bStart==0 ){ + fts3EvalNextRow(pCsr, pRight, pRc); + assert( *pRc!=SQLITE_OK || pRight->bStart ); + } + + fts3EvalNextRow(pCsr, pLeft, pRc); + if( pLeft->bEof==0 ){ + while( !*pRc + && !pRight->bEof + && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 + ){ + fts3EvalNextRow(pCsr, pRight, pRc); + } + } + pExpr->iDocid = pLeft->iDocid; + pExpr->bEof = pLeft->bEof; + break; + } + + default: { + Fts3Phrase *pPhrase = pExpr->pPhrase; + fts3EvalInvalidatePoslist(pPhrase); + *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof); + pExpr->iDocid = pPhrase->doclist.iDocid; + break; + } + } + } +} + +/* +** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR +** cluster, then this function returns 1 immediately. +** +** Otherwise, it checks if the current row really does match the NEAR +** expression, using the data currently stored in the position lists +** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. +** +** If the current row is a match, the position list associated with each +** phrase in the NEAR expression is edited in place to contain only those +** phrase instances sufficiently close to their peers to satisfy all NEAR +** constraints. In this case it returns 1. If the NEAR expression does not +** match the current row, 0 is returned. The position lists may or may not +** be edited if 0 is returned. +*/ +static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){ + int res = 1; + + /* The following block runs if pExpr is the root of a NEAR query. + ** For example, the query: + ** + ** "w" NEAR "x" NEAR "y" NEAR "z" + ** + ** which is represented in tree form as: + ** + ** | + ** +--NEAR--+ <-- root of NEAR query + ** | | + ** +--NEAR--+ "z" + ** | | + ** +--NEAR--+ "y" + ** | | + ** "w" "x" + ** + ** The right-hand child of a NEAR node is always a phrase. The + ** left-hand child may be either a phrase or a NEAR node. There are + ** no exceptions to this - it's the way the parser in fts3_expr.c works. + */ + if( *pRc==SQLITE_OK + && pExpr->eType==FTSQUERY_NEAR + && pExpr->bEof==0 + && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) + ){ + Fts3Expr *p; + int nTmp = 0; /* Bytes of temp space */ + char *aTmp; /* Temp space for PoslistNearMerge() */ + + /* Allocate temporary working space. */ + for(p=pExpr; p->pLeft; p=p->pLeft){ + nTmp += p->pRight->pPhrase->doclist.nList; + } + nTmp += p->pPhrase->doclist.nList; + if( nTmp==0 ){ + res = 0; + }else{ + aTmp = sqlite3_malloc(nTmp*2); + if( !aTmp ){ + *pRc = SQLITE_NOMEM; + res = 0; + }else{ + char *aPoslist = p->pPhrase->doclist.pList; + int nToken = p->pPhrase->nToken; + + for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){ + Fts3Phrase *pPhrase = p->pRight->pPhrase; + int nNear = p->nNear; + res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); + } + + aPoslist = pExpr->pRight->pPhrase->doclist.pList; + nToken = pExpr->pRight->pPhrase->nToken; + for(p=pExpr->pLeft; p && res; p=p->pLeft){ + int nNear; + Fts3Phrase *pPhrase; + assert( p->pParent && p->pParent->pLeft==p ); + nNear = p->pParent->nNear; + pPhrase = ( + p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase + ); + res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); + } + } + + sqlite3_free(aTmp); + } + } + + return res; +} + +/* +** This function is a helper function for fts3EvalTestDeferredAndNear(). +** Assuming no error occurs or has occurred, It returns non-zero if the +** expression passed as the second argument matches the row that pCsr +** currently points to, or zero if it does not. +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** If an error occurs during execution of this function, *pRc is set to +** the appropriate SQLite error code. In this case the returned value is +** undefined. +*/ +static int fts3EvalTestExpr( + Fts3Cursor *pCsr, /* FTS cursor handle */ + Fts3Expr *pExpr, /* Expr to test. May or may not be root. */ + int *pRc /* IN/OUT: Error code */ +){ + int bHit = 1; /* Return value */ + if( *pRc==SQLITE_OK ){ + switch( pExpr->eType ){ + case FTSQUERY_NEAR: + case FTSQUERY_AND: + bHit = ( + fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) + && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) + && fts3EvalNearTest(pExpr, pRc) + ); + + /* If the NEAR expression does not match any rows, zero the doclist for + ** all phrases involved in the NEAR. This is because the snippet(), + ** offsets() and matchinfo() functions are not supposed to recognize + ** any instances of phrases that are part of unmatched NEAR queries. + ** For example if this expression: + ** + ** ... MATCH 'a OR (b NEAR c)' + ** + ** is matched against a row containing: + ** + ** 'a b d e' + ** + ** then any snippet() should ony highlight the "a" term, not the "b" + ** (as "b" is part of a non-matching NEAR clause). + */ + if( bHit==0 + && pExpr->eType==FTSQUERY_NEAR + && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) + ){ + Fts3Expr *p; + for(p=pExpr; p->pPhrase==0; p=p->pLeft){ + if( p->pRight->iDocid==pCsr->iPrevId ){ + fts3EvalInvalidatePoslist(p->pRight->pPhrase); + } + } + if( p->iDocid==pCsr->iPrevId ){ + fts3EvalInvalidatePoslist(p->pPhrase); + } + } + + break; + + case FTSQUERY_OR: { + int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc); + int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc); + bHit = bHit1 || bHit2; + break; + } + + case FTSQUERY_NOT: + bHit = ( + fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) + && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) + ); + break; + + default: { +#ifndef SQLITE_DISABLE_FTS4_DEFERRED + if( pCsr->pDeferred + && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred) + ){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 ); + if( pExpr->bDeferred ){ + fts3EvalInvalidatePoslist(pPhrase); + } + *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase); + bHit = (pPhrase->doclist.pList!=0); + pExpr->iDocid = pCsr->iPrevId; + }else +#endif + { + bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId); + } + break; + } + } + } + return bHit; +} + +/* +** This function is called as the second part of each xNext operation when +** iterating through the results of a full-text query. At this point the +** cursor points to a row that matches the query expression, with the +** following caveats: +** +** * Up until this point, "NEAR" operators in the expression have been +** treated as "AND". +** +** * Deferred tokens have not yet been considered. +** +** If *pRc is not SQLITE_OK when this function is called, it immediately +** returns 0. Otherwise, it tests whether or not after considering NEAR +** operators and deferred tokens the current row is still a match for the +** expression. It returns 1 if both of the following are true: +** +** 1. *pRc is SQLITE_OK when this function returns, and +** +** 2. After scanning the current FTS table row for the deferred tokens, +** it is determined that the row does *not* match the query. +** +** Or, if no error occurs and it seems the current row does match the FTS +** query, return 0. +*/ +static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){ + int rc = *pRc; + int bMiss = 0; + if( rc==SQLITE_OK ){ + + /* If there are one or more deferred tokens, load the current row into + ** memory and scan it to determine the position list for each deferred + ** token. Then, see if this row is really a match, considering deferred + ** tokens and NEAR operators (neither of which were taken into account + ** earlier, by fts3EvalNextRow()). + */ + if( pCsr->pDeferred ){ + rc = fts3CursorSeek(0, pCsr); + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3CacheDeferredDoclists(pCsr); + } + } + bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc)); + + /* Free the position-lists accumulated for each deferred token above. */ + sqlite3Fts3FreeDeferredDoclists(pCsr); + *pRc = rc; + } + return (rc==SQLITE_OK && bMiss); +} + +/* +** Advance to the next document that matches the FTS expression in +** Fts3Cursor.pExpr. +*/ +static int fts3EvalNext(Fts3Cursor *pCsr){ + int rc = SQLITE_OK; /* Return Code */ + Fts3Expr *pExpr = pCsr->pExpr; + assert( pCsr->isEof==0 ); + if( pExpr==0 ){ + pCsr->isEof = 1; + }else{ + do { + if( pCsr->isRequireSeek==0 ){ + sqlite3_reset(pCsr->pStmt); + } + assert( sqlite3_data_count(pCsr->pStmt)==0 ); + fts3EvalNextRow(pCsr, pExpr, &rc); + pCsr->isEof = pExpr->bEof; + pCsr->isRequireSeek = 1; + pCsr->isMatchinfoNeeded = 1; + pCsr->iPrevId = pExpr->iDocid; + }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) ); + } + + /* Check if the cursor is past the end of the docid range specified + ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */ + if( rc==SQLITE_OK && ( + (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid) + || (pCsr->bDesc!=0 && pCsr->iPrevIdiMinDocid) + )){ + pCsr->isEof = 1; + } + + return rc; +} + +/* +** Restart interation for expression pExpr so that the next call to +** fts3EvalNext() visits the first row. Do not allow incremental +** loading or merging of phrase doclists for this iteration. +** +** If *pRc is other than SQLITE_OK when this function is called, it is +** a no-op. If an error occurs within this function, *pRc is set to an +** SQLite error code before returning. +*/ +static void fts3EvalRestart( + Fts3Cursor *pCsr, + Fts3Expr *pExpr, + int *pRc +){ + if( pExpr && *pRc==SQLITE_OK ){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + + if( pPhrase ){ + fts3EvalInvalidatePoslist(pPhrase); + if( pPhrase->bIncr ){ + int i; + for(i=0; inToken; i++){ + Fts3PhraseToken *pToken = &pPhrase->aToken[i]; + assert( pToken->pDeferred==0 ); + if( pToken->pSegcsr ){ + sqlite3Fts3MsrIncrRestart(pToken->pSegcsr); + } + } + *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase); + } + pPhrase->doclist.pNextDocid = 0; + pPhrase->doclist.iDocid = 0; + } + + pExpr->iDocid = 0; + pExpr->bEof = 0; + pExpr->bStart = 0; + + fts3EvalRestart(pCsr, pExpr->pLeft, pRc); + fts3EvalRestart(pCsr, pExpr->pRight, pRc); + } +} + +/* +** After allocating the Fts3Expr.aMI[] array for each phrase in the +** expression rooted at pExpr, the cursor iterates through all rows matched +** by pExpr, calling this function for each row. This function increments +** the values in Fts3Expr.aMI[] according to the position-list currently +** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase +** expression nodes. +*/ +static void fts3EvalUpdateCounts(Fts3Expr *pExpr){ + if( pExpr ){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + if( pPhrase && pPhrase->doclist.pList ){ + int iCol = 0; + char *p = pPhrase->doclist.pList; + + assert( *p ); + while( 1 ){ + u8 c = 0; + int iCnt = 0; + while( 0xFE & (*p | c) ){ + if( (c&0x80)==0 ) iCnt++; + c = *p++ & 0x80; + } + + /* aMI[iCol*3 + 1] = Number of occurrences + ** aMI[iCol*3 + 2] = Number of rows containing at least one instance + */ + pExpr->aMI[iCol*3 + 1] += iCnt; + pExpr->aMI[iCol*3 + 2] += (iCnt>0); + if( *p==0x00 ) break; + p++; + p += sqlite3Fts3GetVarint32(p, &iCol); + } + } + + fts3EvalUpdateCounts(pExpr->pLeft); + fts3EvalUpdateCounts(pExpr->pRight); + } +} + +/* +** Expression pExpr must be of type FTSQUERY_PHRASE. +** +** If it is not already allocated and populated, this function allocates and +** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part +** of a NEAR expression, then it also allocates and populates the same array +** for all other phrases that are part of the NEAR expression. +** +** SQLITE_OK is returned if the aMI[] array is successfully allocated and +** populated. Otherwise, if an error occurs, an SQLite error code is returned. +*/ +static int fts3EvalGatherStats( + Fts3Cursor *pCsr, /* Cursor object */ + Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */ +){ + int rc = SQLITE_OK; /* Return code */ + + assert( pExpr->eType==FTSQUERY_PHRASE ); + if( pExpr->aMI==0 ){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + Fts3Expr *pRoot; /* Root of NEAR expression */ + Fts3Expr *p; /* Iterator used for several purposes */ + + sqlite3_int64 iPrevId = pCsr->iPrevId; + sqlite3_int64 iDocid; + u8 bEof; + + /* Find the root of the NEAR expression */ + pRoot = pExpr; + while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){ + pRoot = pRoot->pParent; + } + iDocid = pRoot->iDocid; + bEof = pRoot->bEof; + assert( pRoot->bStart ); + + /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */ + for(p=pRoot; p; p=p->pLeft){ + Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight); + assert( pE->aMI==0 ); + pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32)); + if( !pE->aMI ) return SQLITE_NOMEM; + memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32)); + } + + fts3EvalRestart(pCsr, pRoot, &rc); + + while( pCsr->isEof==0 && rc==SQLITE_OK ){ + + do { + /* Ensure the %_content statement is reset. */ + if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt); + assert( sqlite3_data_count(pCsr->pStmt)==0 ); + + /* Advance to the next document */ + fts3EvalNextRow(pCsr, pRoot, &rc); + pCsr->isEof = pRoot->bEof; + pCsr->isRequireSeek = 1; + pCsr->isMatchinfoNeeded = 1; + pCsr->iPrevId = pRoot->iDocid; + }while( pCsr->isEof==0 + && pRoot->eType==FTSQUERY_NEAR + && fts3EvalTestDeferredAndNear(pCsr, &rc) + ); + + if( rc==SQLITE_OK && pCsr->isEof==0 ){ + fts3EvalUpdateCounts(pRoot); + } + } + + pCsr->isEof = 0; + pCsr->iPrevId = iPrevId; + + if( bEof ){ + pRoot->bEof = bEof; + }else{ + /* Caution: pRoot may iterate through docids in ascending or descending + ** order. For this reason, even though it seems more defensive, the + ** do loop can not be written: + ** + ** do {...} while( pRoot->iDocidbEof==0 ); + }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK ); + fts3EvalTestDeferredAndNear(pCsr, &rc); + } + } + return rc; +} + +/* +** This function is used by the matchinfo() module to query a phrase +** expression node for the following information: +** +** 1. The total number of occurrences of the phrase in each column of +** the FTS table (considering all rows), and +** +** 2. For each column, the number of rows in the table for which the +** column contains at least one instance of the phrase. +** +** If no error occurs, SQLITE_OK is returned and the values for each column +** written into the array aiOut as follows: +** +** aiOut[iCol*3 + 1] = Number of occurrences +** aiOut[iCol*3 + 2] = Number of rows containing at least one instance +** +** Caveats: +** +** * If a phrase consists entirely of deferred tokens, then all output +** values are set to the number of documents in the table. In other +** words we assume that very common tokens occur exactly once in each +** column of each row of the table. +** +** * If a phrase contains some deferred tokens (and some non-deferred +** tokens), count the potential occurrence identified by considering +** the non-deferred tokens instead of actual phrase occurrences. +** +** * If the phrase is part of a NEAR expression, then only phrase instances +** that meet the NEAR constraint are included in the counts. +*/ +SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats( + Fts3Cursor *pCsr, /* FTS cursor handle */ + Fts3Expr *pExpr, /* Phrase expression */ + u32 *aiOut /* Array to write results into (see above) */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; + int iCol; + + if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){ + assert( pCsr->nDoc>0 ); + for(iCol=0; iColnColumn; iCol++){ + aiOut[iCol*3 + 1] = (u32)pCsr->nDoc; + aiOut[iCol*3 + 2] = (u32)pCsr->nDoc; + } + }else{ + rc = fts3EvalGatherStats(pCsr, pExpr); + if( rc==SQLITE_OK ){ + assert( pExpr->aMI ); + for(iCol=0; iColnColumn; iCol++){ + aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1]; + aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2]; + } + } + } + + return rc; +} + +/* +** The expression pExpr passed as the second argument to this function +** must be of type FTSQUERY_PHRASE. +** +** The returned value is either NULL or a pointer to a buffer containing +** a position-list indicating the occurrences of the phrase in column iCol +** of the current row. +** +** More specifically, the returned buffer contains 1 varint for each +** occurrence of the phrase in the column, stored using the normal (delta+2) +** compression and is terminated by either an 0x01 or 0x00 byte. For example, +** if the requested column contains "a b X c d X X" and the position-list +** for 'X' is requested, the buffer returned may contain: +** +** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00 +** +** This function works regardless of whether or not the phrase is deferred, +** incremental, or neither. +*/ +SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist( + Fts3Cursor *pCsr, /* FTS3 cursor object */ + Fts3Expr *pExpr, /* Phrase to return doclist for */ + int iCol, /* Column to return position list for */ + char **ppOut /* OUT: Pointer to position list */ +){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + char *pIter; + int iThis; + sqlite3_int64 iDocid; + + /* If this phrase is applies specifically to some column other than + ** column iCol, return a NULL pointer. */ + *ppOut = 0; + assert( iCol>=0 && iColnColumn ); + if( (pPhrase->iColumnnColumn && pPhrase->iColumn!=iCol) ){ + return SQLITE_OK; + } + + iDocid = pExpr->iDocid; + pIter = pPhrase->doclist.pList; + if( iDocid!=pCsr->iPrevId || pExpr->bEof ){ + int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */ + int iMul; /* +1 if csr dir matches index dir, else -1 */ + int bOr = 0; + u8 bEof = 0; + u8 bTreeEof = 0; + Fts3Expr *p; /* Used to iterate from pExpr to root */ + Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */ + + /* Check if this phrase descends from an OR expression node. If not, + ** return NULL. Otherwise, the entry that corresponds to docid + ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the + ** tree that the node is part of has been marked as EOF, but the node + ** itself is not EOF, then it may point to an earlier entry. */ + pNear = pExpr; + for(p=pExpr->pParent; p; p=p->pParent){ + if( p->eType==FTSQUERY_OR ) bOr = 1; + if( p->eType==FTSQUERY_NEAR ) pNear = p; + if( p->bEof ) bTreeEof = 1; + } + if( bOr==0 ) return SQLITE_OK; + + /* This is the descendent of an OR node. In this case we cannot use + ** an incremental phrase. Load the entire doclist for the phrase + ** into memory in this case. */ + if( pPhrase->bIncr ){ + int rc = SQLITE_OK; + int bEofSave = pExpr->bEof; + fts3EvalRestart(pCsr, pExpr, &rc); + while( rc==SQLITE_OK && !pExpr->bEof ){ + fts3EvalNextRow(pCsr, pExpr, &rc); + if( bEofSave==0 && pExpr->iDocid==iDocid ) break; + } + pIter = pPhrase->doclist.pList; + assert( rc!=SQLITE_OK || pPhrase->bIncr==0 ); + if( rc!=SQLITE_OK ) return rc; + } + + iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1); + while( bTreeEof==1 + && pNear->bEof==0 + && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0 + ){ + int rc = SQLITE_OK; + fts3EvalNextRow(pCsr, pExpr, &rc); + if( rc!=SQLITE_OK ) return rc; + iDocid = pExpr->iDocid; + pIter = pPhrase->doclist.pList; + } + + bEof = (pPhrase->doclist.nAll==0); + assert( bDescDoclist==0 || bDescDoclist==1 ); + assert( pCsr->bDesc==0 || pCsr->bDesc==1 ); + + if( bEof==0 ){ + if( pCsr->bDesc==bDescDoclist ){ + int dummy; + if( pNear->bEof ){ + /* This expression is already at EOF. So position it to point to the + ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable + ** iDocid is already set for this entry, so all that is required is + ** to set pIter to point to the first byte of the last position-list + ** in the doclist. + ** + ** It would also be correct to set pIter and iDocid to zero. In + ** this case, the first call to sqltie3Fts4DoclistPrev() below + ** would also move the iterator to point to the last entry in the + ** doclist. However, this is expensive, as to do so it has to + ** iterate through the entire doclist from start to finish (since + ** it does not know the docid for the last entry). */ + pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1]; + fts3ReversePoslist(pPhrase->doclist.aAll, &pIter); + } + while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){ + sqlite3Fts3DoclistPrev( + bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, + &pIter, &iDocid, &dummy, &bEof + ); + } + }else{ + if( pNear->bEof ){ + pIter = 0; + iDocid = 0; + } + while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){ + sqlite3Fts3DoclistNext( + bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, + &pIter, &iDocid, &bEof + ); + } + } + } + + if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0; + } + if( pIter==0 ) return SQLITE_OK; + + if( *pIter==0x01 ){ + pIter++; + pIter += sqlite3Fts3GetVarint32(pIter, &iThis); + }else{ + iThis = 0; + } + while( iThisdoclist, and +** * any Fts3MultiSegReader objects held by phrase tokens. +*/ +SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){ + if( pPhrase ){ + int i; + sqlite3_free(pPhrase->doclist.aAll); + fts3EvalInvalidatePoslist(pPhrase); + memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist)); + for(i=0; inToken; i++){ + fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr); + pPhrase->aToken[i].pSegcsr = 0; + } + } +} + + +/* +** Return SQLITE_CORRUPT_VTAB. +*/ +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int sqlite3Fts3Corrupt(){ + return SQLITE_CORRUPT_VTAB; +} +#endif + +#if !SQLITE_CORE +/* +** Initialize API pointer table, if required. +*/ +#ifdef _WIN32 +__declspec(dllexport) +#endif +SQLITE_API int sqlite3_fts3_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi) + return sqlite3Fts3Init(db); +} +#endif + +#endif + +/************** End of fts3.c ************************************************/ +/************** Begin file fts3_aux.c ****************************************/ +/* +** 2011 Jan 27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* #include */ +/* #include */ + +typedef struct Fts3auxTable Fts3auxTable; +typedef struct Fts3auxCursor Fts3auxCursor; + +struct Fts3auxTable { + sqlite3_vtab base; /* Base class used by SQLite core */ + Fts3Table *pFts3Tab; +}; + +struct Fts3auxCursor { + sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + Fts3MultiSegReader csr; /* Must be right after "base" */ + Fts3SegFilter filter; + char *zStop; + int nStop; /* Byte-length of string zStop */ + int iLangid; /* Language id to query */ + int isEof; /* True if cursor is at EOF */ + sqlite3_int64 iRowid; /* Current rowid */ + + int iCol; /* Current value of 'col' column */ + int nStat; /* Size of aStat[] array */ + struct Fts3auxColstats { + sqlite3_int64 nDoc; /* 'documents' values for current csr row */ + sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */ + } *aStat; +}; + +/* +** Schema of the terms table. +*/ +#define FTS3_AUX_SCHEMA \ + "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)" + +/* +** This function does all the work for both the xConnect and xCreate methods. +** These tables have no persistent representation of their own, so xConnect +** and xCreate are identical operations. +*/ +static int fts3auxConnectMethod( + sqlite3 *db, /* Database connection */ + void *pUnused, /* Unused */ + int argc, /* Number of elements in argv array */ + const char * const *argv, /* xCreate/xConnect argument array */ + sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ + char **pzErr /* OUT: sqlite3_malloc'd error message */ +){ + char const *zDb; /* Name of database (e.g. "main") */ + char const *zFts3; /* Name of fts3 table */ + int nDb; /* Result of strlen(zDb) */ + int nFts3; /* Result of strlen(zFts3) */ + int nByte; /* Bytes of space to allocate here */ + int rc; /* value returned by declare_vtab() */ + Fts3auxTable *p; /* Virtual table object to return */ + + UNUSED_PARAMETER(pUnused); + + /* The user should invoke this in one of two forms: + ** + ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table); + ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table); + */ + if( argc!=4 && argc!=5 ) goto bad_args; + + zDb = argv[1]; + nDb = (int)strlen(zDb); + if( argc==5 ){ + if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){ + zDb = argv[3]; + nDb = (int)strlen(zDb); + zFts3 = argv[4]; + }else{ + goto bad_args; + } + }else{ + zFts3 = argv[3]; + } + nFts3 = (int)strlen(zFts3); + + rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA); + if( rc!=SQLITE_OK ) return rc; + + nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2; + p = (Fts3auxTable *)sqlite3_malloc(nByte); + if( !p ) return SQLITE_NOMEM; + memset(p, 0, nByte); + + p->pFts3Tab = (Fts3Table *)&p[1]; + p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1]; + p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1]; + p->pFts3Tab->db = db; + p->pFts3Tab->nIndex = 1; + + memcpy((char *)p->pFts3Tab->zDb, zDb, nDb); + memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3); + sqlite3Fts3Dequote((char *)p->pFts3Tab->zName); + + *ppVtab = (sqlite3_vtab *)p; + return SQLITE_OK; + + bad_args: + *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor"); + return SQLITE_ERROR; +} + +/* +** This function does the work for both the xDisconnect and xDestroy methods. +** These tables have no persistent representation of their own, so xDisconnect +** and xDestroy are identical operations. +*/ +static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){ + Fts3auxTable *p = (Fts3auxTable *)pVtab; + Fts3Table *pFts3 = p->pFts3Tab; + int i; + + /* Free any prepared statements held */ + for(i=0; iaStmt); i++){ + sqlite3_finalize(pFts3->aStmt[i]); + } + sqlite3_free(pFts3->zSegmentsTbl); + sqlite3_free(p); + return SQLITE_OK; +} + +#define FTS4AUX_EQ_CONSTRAINT 1 +#define FTS4AUX_GE_CONSTRAINT 2 +#define FTS4AUX_LE_CONSTRAINT 4 + +/* +** xBestIndex - Analyze a WHERE and ORDER BY clause. +*/ +static int fts3auxBestIndexMethod( + sqlite3_vtab *pVTab, + sqlite3_index_info *pInfo +){ + int i; + int iEq = -1; + int iGe = -1; + int iLe = -1; + int iLangid = -1; + int iNext = 1; /* Next free argvIndex value */ + + UNUSED_PARAMETER(pVTab); + + /* This vtab delivers always results in "ORDER BY term ASC" order. */ + if( pInfo->nOrderBy==1 + && pInfo->aOrderBy[0].iColumn==0 + && pInfo->aOrderBy[0].desc==0 + ){ + pInfo->orderByConsumed = 1; + } + + /* Search for equality and range constraints on the "term" column. + ** And equality constraints on the hidden "languageid" column. */ + for(i=0; inConstraint; i++){ + if( pInfo->aConstraint[i].usable ){ + int op = pInfo->aConstraint[i].op; + int iCol = pInfo->aConstraint[i].iColumn; + + if( iCol==0 ){ + if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i; + if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i; + if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i; + if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i; + if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i; + } + if( iCol==4 ){ + if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i; + } + } + } + + if( iEq>=0 ){ + pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT; + pInfo->aConstraintUsage[iEq].argvIndex = iNext++; + pInfo->estimatedCost = 5; + }else{ + pInfo->idxNum = 0; + pInfo->estimatedCost = 20000; + if( iGe>=0 ){ + pInfo->idxNum += FTS4AUX_GE_CONSTRAINT; + pInfo->aConstraintUsage[iGe].argvIndex = iNext++; + pInfo->estimatedCost /= 2; + } + if( iLe>=0 ){ + pInfo->idxNum += FTS4AUX_LE_CONSTRAINT; + pInfo->aConstraintUsage[iLe].argvIndex = iNext++; + pInfo->estimatedCost /= 2; + } + } + if( iLangid>=0 ){ + pInfo->aConstraintUsage[iLangid].argvIndex = iNext++; + pInfo->estimatedCost--; + } + + return SQLITE_OK; +} + +/* +** xOpen - Open a cursor. +*/ +static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ + Fts3auxCursor *pCsr; /* Pointer to cursor object to return */ + + UNUSED_PARAMETER(pVTab); + + pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor)); + if( !pCsr ) return SQLITE_NOMEM; + memset(pCsr, 0, sizeof(Fts3auxCursor)); + + *ppCsr = (sqlite3_vtab_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** xClose - Close a cursor. +*/ +static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){ + Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + + sqlite3Fts3SegmentsClose(pFts3); + sqlite3Fts3SegReaderFinish(&pCsr->csr); + sqlite3_free((void *)pCsr->filter.zTerm); + sqlite3_free(pCsr->zStop); + sqlite3_free(pCsr->aStat); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){ + if( nSize>pCsr->nStat ){ + struct Fts3auxColstats *aNew; + aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, + sizeof(struct Fts3auxColstats) * nSize + ); + if( aNew==0 ) return SQLITE_NOMEM; + memset(&aNew[pCsr->nStat], 0, + sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat) + ); + pCsr->aStat = aNew; + pCsr->nStat = nSize; + } + return SQLITE_OK; +} + +/* +** xNext - Advance the cursor to the next row, if any. +*/ +static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; + int rc; + + /* Increment our pretend rowid value. */ + pCsr->iRowid++; + + for(pCsr->iCol++; pCsr->iColnStat; pCsr->iCol++){ + if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK; + } + + rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr); + if( rc==SQLITE_ROW ){ + int i = 0; + int nDoclist = pCsr->csr.nDoclist; + char *aDoclist = pCsr->csr.aDoclist; + int iCol; + + int eState = 0; + + if( pCsr->zStop ){ + int n = (pCsr->nStopcsr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm; + int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n); + if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){ + pCsr->isEof = 1; + return SQLITE_OK; + } + } + + if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM; + memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat); + iCol = 0; + + while( iaStat[0].nDoc++; + eState = 1; + iCol = 0; + break; + + /* State 1. In this state we are expecting either a 1, indicating + ** that the following integer will be a column number, or the + ** start of a position list for column 0. + ** + ** The only difference between state 1 and state 2 is that if the + ** integer encountered in state 1 is not 0 or 1, then we need to + ** increment the column 0 "nDoc" count for this term. + */ + case 1: + assert( iCol==0 ); + if( v>1 ){ + pCsr->aStat[1].nDoc++; + } + eState = 2; + /* fall through */ + + case 2: + if( v==0 ){ /* 0x00. Next integer will be a docid. */ + eState = 0; + }else if( v==1 ){ /* 0x01. Next integer will be a column number. */ + eState = 3; + }else{ /* 2 or greater. A position. */ + pCsr->aStat[iCol+1].nOcc++; + pCsr->aStat[0].nOcc++; + } + break; + + /* State 3. The integer just read is a column number. */ + default: assert( eState==3 ); + iCol = (int)v; + if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM; + pCsr->aStat[iCol+1].nDoc++; + eState = 2; + break; + } + } + + pCsr->iCol = 0; + rc = SQLITE_OK; + }else{ + pCsr->isEof = 1; + } + return rc; +} + +/* +** xFilter - Initialize a cursor to point at the start of its data. +*/ +static int fts3auxFilterMethod( + sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + int idxNum, /* Strategy index */ + const char *idxStr, /* Unused */ + int nVal, /* Number of elements in apVal */ + sqlite3_value **apVal /* Arguments for the indexing scheme */ +){ + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; + int rc; + int isScan = 0; + int iLangVal = 0; /* Language id to query */ + + int iEq = -1; /* Index of term=? value in apVal */ + int iGe = -1; /* Index of term>=? value in apVal */ + int iLe = -1; /* Index of term<=? value in apVal */ + int iLangid = -1; /* Index of languageid=? value in apVal */ + int iNext = 0; + + UNUSED_PARAMETER(nVal); + UNUSED_PARAMETER(idxStr); + + assert( idxStr==0 ); + assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0 + || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT + || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) + ); + + if( idxNum==FTS4AUX_EQ_CONSTRAINT ){ + iEq = iNext++; + }else{ + isScan = 1; + if( idxNum & FTS4AUX_GE_CONSTRAINT ){ + iGe = iNext++; + } + if( idxNum & FTS4AUX_LE_CONSTRAINT ){ + iLe = iNext++; + } + } + if( iNextfilter.zTerm); + sqlite3Fts3SegReaderFinish(&pCsr->csr); + sqlite3_free((void *)pCsr->filter.zTerm); + sqlite3_free(pCsr->aStat); + memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr); + + pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; + if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN; + + if( iEq>=0 || iGe>=0 ){ + const unsigned char *zStr = sqlite3_value_text(apVal[0]); + assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) ); + if( zStr ){ + pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr); + pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]); + if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM; + } + } + + if( iLe>=0 ){ + pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe])); + pCsr->nStop = sqlite3_value_bytes(apVal[iLe]); + if( pCsr->zStop==0 ) return SQLITE_NOMEM; + } + + if( iLangid>=0 ){ + iLangVal = sqlite3_value_int(apVal[iLangid]); + + /* If the user specified a negative value for the languageid, use zero + ** instead. This works, as the "languageid=?" constraint will also + ** be tested by the VDBE layer. The test will always be false (since + ** this module will not return a row with a negative languageid), and + ** so the overall query will return zero rows. */ + if( iLangVal<0 ) iLangVal = 0; + } + pCsr->iLangid = iLangVal; + + rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL, + pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr + ); + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter); + } + + if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor); + return rc; +} + +/* +** xEof - Return true if the cursor is at EOF, or false otherwise. +*/ +static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){ + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + return pCsr->isEof; +} + +/* +** xColumn - Return a column value. +*/ +static int fts3auxColumnMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + int iCol /* Index of column to read value from */ +){ + Fts3auxCursor *p = (Fts3auxCursor *)pCursor; + + assert( p->isEof==0 ); + switch( iCol ){ + case 0: /* term */ + sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT); + break; + + case 1: /* col */ + if( p->iCol ){ + sqlite3_result_int(pCtx, p->iCol-1); + }else{ + sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC); + } + break; + + case 2: /* documents */ + sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc); + break; + + case 3: /* occurrences */ + sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc); + break; + + default: /* languageid */ + assert( iCol==4 ); + sqlite3_result_int(pCtx, p->iLangid); + break; + } + + return SQLITE_OK; +} + +/* +** xRowid - Return the current rowid for the cursor. +*/ +static int fts3auxRowidMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite_int64 *pRowid /* OUT: Rowid value */ +){ + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + *pRowid = pCsr->iRowid; + return SQLITE_OK; +} + +/* +** Register the fts3aux module with database connection db. Return SQLITE_OK +** if successful or an error code if sqlite3_create_module() fails. +*/ +SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){ + static const sqlite3_module fts3aux_module = { + 0, /* iVersion */ + fts3auxConnectMethod, /* xCreate */ + fts3auxConnectMethod, /* xConnect */ + fts3auxBestIndexMethod, /* xBestIndex */ + fts3auxDisconnectMethod, /* xDisconnect */ + fts3auxDisconnectMethod, /* xDestroy */ + fts3auxOpenMethod, /* xOpen */ + fts3auxCloseMethod, /* xClose */ + fts3auxFilterMethod, /* xFilter */ + fts3auxNextMethod, /* xNext */ + fts3auxEofMethod, /* xEof */ + fts3auxColumnMethod, /* xColumn */ + fts3auxRowidMethod, /* xRowid */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindFunction */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0 /* xRollbackTo */ + }; + int rc; /* Return code */ + + rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0); + return rc; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ + +/************** End of fts3_aux.c ********************************************/ +/************** Begin file fts3_expr.c ***************************************/ +/* +** 2008 Nov 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This module contains code that implements a parser for fts3 query strings +** (the right-hand argument to the MATCH operator). Because the supported +** syntax is relatively simple, the whole tokenizer/parser system is +** hand-coded. +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* +** By default, this module parses the legacy syntax that has been +** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS +** is defined, then it uses the new syntax. The differences between +** the new and the old syntaxes are: +** +** a) The new syntax supports parenthesis. The old does not. +** +** b) The new syntax supports the AND and NOT operators. The old does not. +** +** c) The old syntax supports the "-" token qualifier. This is not +** supported by the new syntax (it is replaced by the NOT operator). +** +** d) When using the old syntax, the OR operator has a greater precedence +** than an implicit AND. When using the new, both implicity and explicit +** AND operators have a higher precedence than OR. +** +** If compiled with SQLITE_TEST defined, then this module exports the +** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable +** to zero causes the module to use the old syntax. If it is set to +** non-zero the new syntax is activated. This is so both syntaxes can +** be tested using a single build of testfixture. +** +** The following describes the syntax supported by the fts3 MATCH +** operator in a similar format to that used by the lemon parser +** generator. This module does not use actually lemon, it uses a +** custom parser. +** +** query ::= andexpr (OR andexpr)*. +** +** andexpr ::= notexpr (AND? notexpr)*. +** +** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*. +** notexpr ::= LP query RP. +** +** nearexpr ::= phrase (NEAR distance_opt nearexpr)*. +** +** distance_opt ::= . +** distance_opt ::= / INTEGER. +** +** phrase ::= TOKEN. +** phrase ::= COLUMN:TOKEN. +** phrase ::= "TOKEN TOKEN TOKEN...". +*/ + +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_fts3_enable_parentheses = 0; +#else +# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS +# define sqlite3_fts3_enable_parentheses 1 +# else +# define sqlite3_fts3_enable_parentheses 0 +# endif +#endif + +/* +** Default span for NEAR operators. +*/ +#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10 + +/* #include */ +/* #include */ + +/* +** isNot: +** This variable is used by function getNextNode(). When getNextNode() is +** called, it sets ParseContext.isNot to true if the 'next node' is a +** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the +** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to +** zero. +*/ +typedef struct ParseContext ParseContext; +struct ParseContext { + sqlite3_tokenizer *pTokenizer; /* Tokenizer module */ + int iLangid; /* Language id used with tokenizer */ + const char **azCol; /* Array of column names for fts3 table */ + int bFts4; /* True to allow FTS4-only syntax */ + int nCol; /* Number of entries in azCol[] */ + int iDefaultCol; /* Default column to query */ + int isNot; /* True if getNextNode() sees a unary - */ + sqlite3_context *pCtx; /* Write error message here */ + int nNest; /* Number of nested brackets */ +}; + +/* +** This function is equivalent to the standard isspace() function. +** +** The standard isspace() can be awkward to use safely, because although it +** is defined to accept an argument of type int, its behavior when passed +** an integer that falls outside of the range of the unsigned char type +** is undefined (and sometimes, "undefined" means segfault). This wrapper +** is defined to accept an argument of type char, and always returns 0 for +** any values that fall outside of the range of the unsigned char type (i.e. +** negative values). +*/ +static int fts3isspace(char c){ + return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; +} + +/* +** Allocate nByte bytes of memory using sqlite3_malloc(). If successful, +** zero the memory before returning a pointer to it. If unsuccessful, +** return NULL. +*/ +static void *fts3MallocZero(int nByte){ + void *pRet = sqlite3_malloc(nByte); + if( pRet ) memset(pRet, 0, nByte); + return pRet; +} + +SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer( + sqlite3_tokenizer *pTokenizer, + int iLangid, + const char *z, + int n, + sqlite3_tokenizer_cursor **ppCsr +){ + sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + sqlite3_tokenizer_cursor *pCsr = 0; + int rc; + + rc = pModule->xOpen(pTokenizer, z, n, &pCsr); + assert( rc==SQLITE_OK || pCsr==0 ); + if( rc==SQLITE_OK ){ + pCsr->pTokenizer = pTokenizer; + if( pModule->iVersion>=1 ){ + rc = pModule->xLanguageid(pCsr, iLangid); + if( rc!=SQLITE_OK ){ + pModule->xClose(pCsr); + pCsr = 0; + } + } + } + *ppCsr = pCsr; + return rc; +} + + +/* +** Extract the next token from buffer z (length n) using the tokenizer +** and other information (column names etc.) in pParse. Create an Fts3Expr +** structure of type FTSQUERY_PHRASE containing a phrase consisting of this +** single token and set *ppExpr to point to it. If the end of the buffer is +** reached before a token is found, set *ppExpr to zero. It is the +** responsibility of the caller to eventually deallocate the allocated +** Fts3Expr structure (if any) by passing it to sqlite3_free(). +** +** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation +** fails. +*/ +static int getNextToken( + ParseContext *pParse, /* fts3 query parse context */ + int iCol, /* Value for Fts3Phrase.iColumn */ + const char *z, int n, /* Input string */ + Fts3Expr **ppExpr, /* OUT: expression */ + int *pnConsumed /* OUT: Number of bytes consumed */ +){ + sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; + sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + int rc; + sqlite3_tokenizer_cursor *pCursor; + Fts3Expr *pRet = 0; + int nConsumed = 0; + + rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor); + if( rc==SQLITE_OK ){ + const char *zToken; + int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0; + int nByte; /* total space to allocate */ + + rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition); + if( rc==SQLITE_OK ){ + nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken; + pRet = (Fts3Expr *)fts3MallocZero(nByte); + if( !pRet ){ + rc = SQLITE_NOMEM; + }else{ + pRet->eType = FTSQUERY_PHRASE; + pRet->pPhrase = (Fts3Phrase *)&pRet[1]; + pRet->pPhrase->nToken = 1; + pRet->pPhrase->iColumn = iCol; + pRet->pPhrase->aToken[0].n = nToken; + pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1]; + memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken); + + if( iEndpPhrase->aToken[0].isPrefix = 1; + iEnd++; + } + + while( 1 ){ + if( !sqlite3_fts3_enable_parentheses + && iStart>0 && z[iStart-1]=='-' + ){ + pParse->isNot = 1; + iStart--; + }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){ + pRet->pPhrase->aToken[0].bFirst = 1; + iStart--; + }else{ + break; + } + } + + } + nConsumed = iEnd; + } + + pModule->xClose(pCursor); + } + + *pnConsumed = nConsumed; + *ppExpr = pRet; + return rc; +} + + +/* +** Enlarge a memory allocation. If an out-of-memory allocation occurs, +** then free the old allocation. +*/ +static void *fts3ReallocOrFree(void *pOrig, int nNew){ + void *pRet = sqlite3_realloc(pOrig, nNew); + if( !pRet ){ + sqlite3_free(pOrig); + } + return pRet; +} + +/* +** Buffer zInput, length nInput, contains the contents of a quoted string +** that appeared as part of an fts3 query expression. Neither quote character +** is included in the buffer. This function attempts to tokenize the entire +** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE +** containing the results. +** +** If successful, SQLITE_OK is returned and *ppExpr set to point at the +** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory +** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set +** to 0. +*/ +static int getNextString( + ParseContext *pParse, /* fts3 query parse context */ + const char *zInput, int nInput, /* Input string */ + Fts3Expr **ppExpr /* OUT: expression */ +){ + sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; + sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + int rc; + Fts3Expr *p = 0; + sqlite3_tokenizer_cursor *pCursor = 0; + char *zTemp = 0; + int nTemp = 0; + + const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase); + int nToken = 0; + + /* The final Fts3Expr data structure, including the Fts3Phrase, + ** Fts3PhraseToken structures token buffers are all stored as a single + ** allocation so that the expression can be freed with a single call to + ** sqlite3_free(). Setting this up requires a two pass approach. + ** + ** The first pass, in the block below, uses a tokenizer cursor to iterate + ** through the tokens in the expression. This pass uses fts3ReallocOrFree() + ** to assemble data in two dynamic buffers: + ** + ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase + ** structure, followed by the array of Fts3PhraseToken + ** structures. This pass only populates the Fts3PhraseToken array. + ** + ** Buffer zTemp: Contains copies of all tokens. + ** + ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below, + ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase + ** structures. + */ + rc = sqlite3Fts3OpenTokenizer( + pTokenizer, pParse->iLangid, zInput, nInput, &pCursor); + if( rc==SQLITE_OK ){ + int ii; + for(ii=0; rc==SQLITE_OK; ii++){ + const char *zByte; + int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0; + rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos); + if( rc==SQLITE_OK ){ + Fts3PhraseToken *pToken; + + p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken)); + if( !p ) goto no_mem; + + zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte); + if( !zTemp ) goto no_mem; + + assert( nToken==ii ); + pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii]; + memset(pToken, 0, sizeof(Fts3PhraseToken)); + + memcpy(&zTemp[nTemp], zByte, nByte); + nTemp += nByte; + + pToken->n = nByte; + pToken->isPrefix = (iEndbFirst = (iBegin>0 && zInput[iBegin-1]=='^'); + nToken = ii+1; + } + } + + pModule->xClose(pCursor); + pCursor = 0; + } + + if( rc==SQLITE_DONE ){ + int jj; + char *zBuf = 0; + + p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp); + if( !p ) goto no_mem; + memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p); + p->eType = FTSQUERY_PHRASE; + p->pPhrase = (Fts3Phrase *)&p[1]; + p->pPhrase->iColumn = pParse->iDefaultCol; + p->pPhrase->nToken = nToken; + + zBuf = (char *)&p->pPhrase->aToken[nToken]; + if( zTemp ){ + memcpy(zBuf, zTemp, nTemp); + sqlite3_free(zTemp); + }else{ + assert( nTemp==0 ); + } + + for(jj=0; jjpPhrase->nToken; jj++){ + p->pPhrase->aToken[jj].z = zBuf; + zBuf += p->pPhrase->aToken[jj].n; + } + rc = SQLITE_OK; + } + + *ppExpr = p; + return rc; +no_mem: + + if( pCursor ){ + pModule->xClose(pCursor); + } + sqlite3_free(zTemp); + sqlite3_free(p); + *ppExpr = 0; + return SQLITE_NOMEM; +} + +/* +** Function getNextNode(), which is called by fts3ExprParse(), may itself +** call fts3ExprParse(). So this forward declaration is required. +*/ +static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *); + +/* +** The output variable *ppExpr is populated with an allocated Fts3Expr +** structure, or set to 0 if the end of the input buffer is reached. +** +** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM +** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered. +** If SQLITE_ERROR is returned, pContext is populated with an error message. +*/ +static int getNextNode( + ParseContext *pParse, /* fts3 query parse context */ + const char *z, int n, /* Input string */ + Fts3Expr **ppExpr, /* OUT: expression */ + int *pnConsumed /* OUT: Number of bytes consumed */ +){ + static const struct Fts3Keyword { + char *z; /* Keyword text */ + unsigned char n; /* Length of the keyword */ + unsigned char parenOnly; /* Only valid in paren mode */ + unsigned char eType; /* Keyword code */ + } aKeyword[] = { + { "OR" , 2, 0, FTSQUERY_OR }, + { "AND", 3, 1, FTSQUERY_AND }, + { "NOT", 3, 1, FTSQUERY_NOT }, + { "NEAR", 4, 0, FTSQUERY_NEAR } + }; + int ii; + int iCol; + int iColLen; + int rc; + Fts3Expr *pRet = 0; + + const char *zInput = z; + int nInput = n; + + pParse->isNot = 0; + + /* Skip over any whitespace before checking for a keyword, an open or + ** close bracket, or a quoted string. + */ + while( nInput>0 && fts3isspace(*zInput) ){ + nInput--; + zInput++; + } + if( nInput==0 ){ + return SQLITE_DONE; + } + + /* See if we are dealing with a keyword. */ + for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){ + const struct Fts3Keyword *pKey = &aKeyword[ii]; + + if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){ + continue; + } + + if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){ + int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM; + int nKey = pKey->n; + char cNext; + + /* If this is a "NEAR" keyword, check for an explicit nearness. */ + if( pKey->eType==FTSQUERY_NEAR ){ + assert( nKey==4 ); + if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){ + nNear = 0; + for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){ + nNear = nNear * 10 + (zInput[nKey] - '0'); + } + } + } + + /* At this point this is probably a keyword. But for that to be true, + ** the next byte must contain either whitespace, an open or close + ** parenthesis, a quote character, or EOF. + */ + cNext = zInput[nKey]; + if( fts3isspace(cNext) + || cNext=='"' || cNext=='(' || cNext==')' || cNext==0 + ){ + pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr)); + if( !pRet ){ + return SQLITE_NOMEM; + } + pRet->eType = pKey->eType; + pRet->nNear = nNear; + *ppExpr = pRet; + *pnConsumed = (int)((zInput - z) + nKey); + return SQLITE_OK; + } + + /* Turns out that wasn't a keyword after all. This happens if the + ** user has supplied a token such as "ORacle". Continue. + */ + } + } + + /* Check for an open bracket. */ + if( sqlite3_fts3_enable_parentheses ){ + if( *zInput=='(' ){ + int nConsumed; + pParse->nNest++; + rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed); + if( rc==SQLITE_OK && !*ppExpr ){ + rc = SQLITE_DONE; + } + *pnConsumed = (int)((zInput - z) + 1 + nConsumed); + return rc; + } + + /* Check for a close bracket. */ + if( *zInput==')' ){ + pParse->nNest--; + *pnConsumed = (int)((zInput - z) + 1); + return SQLITE_DONE; + } + } + + /* See if we are dealing with a quoted phrase. If this is the case, then + ** search for the closing quote and pass the whole string to getNextString() + ** for processing. This is easy to do, as fts3 has no syntax for escaping + ** a quote character embedded in a string. + */ + if( *zInput=='"' ){ + for(ii=1; iiiDefaultCol; + iColLen = 0; + for(ii=0; iinCol; ii++){ + const char *zStr = pParse->azCol[ii]; + int nStr = (int)strlen(zStr); + if( nInput>nStr && zInput[nStr]==':' + && sqlite3_strnicmp(zStr, zInput, nStr)==0 + ){ + iCol = ii; + iColLen = (int)((zInput - z) + nStr + 1); + break; + } + } + rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed); + *pnConsumed += iColLen; + return rc; +} + +/* +** The argument is an Fts3Expr structure for a binary operator (any type +** except an FTSQUERY_PHRASE). Return an integer value representing the +** precedence of the operator. Lower values have a higher precedence (i.e. +** group more tightly). For example, in the C language, the == operator +** groups more tightly than ||, and would therefore have a higher precedence. +** +** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS +** is defined), the order of the operators in precedence from highest to +** lowest is: +** +** NEAR +** NOT +** AND (including implicit ANDs) +** OR +** +** Note that when using the old query syntax, the OR operator has a higher +** precedence than the AND operator. +*/ +static int opPrecedence(Fts3Expr *p){ + assert( p->eType!=FTSQUERY_PHRASE ); + if( sqlite3_fts3_enable_parentheses ){ + return p->eType; + }else if( p->eType==FTSQUERY_NEAR ){ + return 1; + }else if( p->eType==FTSQUERY_OR ){ + return 2; + } + assert( p->eType==FTSQUERY_AND ); + return 3; +} + +/* +** Argument ppHead contains a pointer to the current head of a query +** expression tree being parsed. pPrev is the expression node most recently +** inserted into the tree. This function adds pNew, which is always a binary +** operator node, into the expression tree based on the relative precedence +** of pNew and the existing nodes of the tree. This may result in the head +** of the tree changing, in which case *ppHead is set to the new root node. +*/ +static void insertBinaryOperator( + Fts3Expr **ppHead, /* Pointer to the root node of a tree */ + Fts3Expr *pPrev, /* Node most recently inserted into the tree */ + Fts3Expr *pNew /* New binary node to insert into expression tree */ +){ + Fts3Expr *pSplit = pPrev; + while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){ + pSplit = pSplit->pParent; + } + + if( pSplit->pParent ){ + assert( pSplit->pParent->pRight==pSplit ); + pSplit->pParent->pRight = pNew; + pNew->pParent = pSplit->pParent; + }else{ + *ppHead = pNew; + } + pNew->pLeft = pSplit; + pSplit->pParent = pNew; +} + +/* +** Parse the fts3 query expression found in buffer z, length n. This function +** returns either when the end of the buffer is reached or an unmatched +** closing bracket - ')' - is encountered. +** +** If successful, SQLITE_OK is returned, *ppExpr is set to point to the +** parsed form of the expression and *pnConsumed is set to the number of +** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM +** (out of memory error) or SQLITE_ERROR (parse error) is returned. +*/ +static int fts3ExprParse( + ParseContext *pParse, /* fts3 query parse context */ + const char *z, int n, /* Text of MATCH query */ + Fts3Expr **ppExpr, /* OUT: Parsed query structure */ + int *pnConsumed /* OUT: Number of bytes consumed */ +){ + Fts3Expr *pRet = 0; + Fts3Expr *pPrev = 0; + Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */ + int nIn = n; + const char *zIn = z; + int rc = SQLITE_OK; + int isRequirePhrase = 1; + + while( rc==SQLITE_OK ){ + Fts3Expr *p = 0; + int nByte = 0; + rc = getNextNode(pParse, zIn, nIn, &p, &nByte); + if( rc==SQLITE_OK ){ + int isPhrase; + + if( !sqlite3_fts3_enable_parentheses + && p->eType==FTSQUERY_PHRASE && pParse->isNot + ){ + /* Create an implicit NOT operator. */ + Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr)); + if( !pNot ){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_NOMEM; + goto exprparse_out; + } + pNot->eType = FTSQUERY_NOT; + pNot->pRight = p; + p->pParent = pNot; + if( pNotBranch ){ + pNot->pLeft = pNotBranch; + pNotBranch->pParent = pNot; + } + pNotBranch = pNot; + p = pPrev; + }else{ + int eType = p->eType; + isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft); + + /* The isRequirePhrase variable is set to true if a phrase or + ** an expression contained in parenthesis is required. If a + ** binary operator (AND, OR, NOT or NEAR) is encounted when + ** isRequirePhrase is set, this is a syntax error. + */ + if( !isPhrase && isRequirePhrase ){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_ERROR; + goto exprparse_out; + } + + if( isPhrase && !isRequirePhrase ){ + /* Insert an implicit AND operator. */ + Fts3Expr *pAnd; + assert( pRet && pPrev ); + pAnd = fts3MallocZero(sizeof(Fts3Expr)); + if( !pAnd ){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_NOMEM; + goto exprparse_out; + } + pAnd->eType = FTSQUERY_AND; + insertBinaryOperator(&pRet, pPrev, pAnd); + pPrev = pAnd; + } + + /* This test catches attempts to make either operand of a NEAR + ** operator something other than a phrase. For example, either of + ** the following: + ** + ** (bracketed expression) NEAR phrase + ** phrase NEAR (bracketed expression) + ** + ** Return an error in either case. + */ + if( pPrev && ( + (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE) + || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR) + )){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_ERROR; + goto exprparse_out; + } + + if( isPhrase ){ + if( pRet ){ + assert( pPrev && pPrev->pLeft && pPrev->pRight==0 ); + pPrev->pRight = p; + p->pParent = pPrev; + }else{ + pRet = p; + } + }else{ + insertBinaryOperator(&pRet, pPrev, p); + } + isRequirePhrase = !isPhrase; + } + assert( nByte>0 ); + } + assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) ); + nIn -= nByte; + zIn += nByte; + pPrev = p; + } + + if( rc==SQLITE_DONE && pRet && isRequirePhrase ){ + rc = SQLITE_ERROR; + } + + if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + if( !sqlite3_fts3_enable_parentheses && pNotBranch ){ + if( !pRet ){ + rc = SQLITE_ERROR; + }else{ + Fts3Expr *pIter = pNotBranch; + while( pIter->pLeft ){ + pIter = pIter->pLeft; + } + pIter->pLeft = pRet; + pRet->pParent = pIter; + pRet = pNotBranch; + } + } + } + *pnConsumed = n - nIn; + +exprparse_out: + if( rc!=SQLITE_OK ){ + sqlite3Fts3ExprFree(pRet); + sqlite3Fts3ExprFree(pNotBranch); + pRet = 0; + } + *ppExpr = pRet; + return rc; +} + +/* +** Return SQLITE_ERROR if the maximum depth of the expression tree passed +** as the only argument is more than nMaxDepth. +*/ +static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){ + int rc = SQLITE_OK; + if( p ){ + if( nMaxDepth<0 ){ + rc = SQLITE_TOOBIG; + }else{ + rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1); + if( rc==SQLITE_OK ){ + rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1); + } + } + } + return rc; +} + +/* +** This function attempts to transform the expression tree at (*pp) to +** an equivalent but more balanced form. The tree is modified in place. +** If successful, SQLITE_OK is returned and (*pp) set to point to the +** new root expression node. +** +** nMaxDepth is the maximum allowable depth of the balanced sub-tree. +** +** Otherwise, if an error occurs, an SQLite error code is returned and +** expression (*pp) freed. +*/ +static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ + int rc = SQLITE_OK; /* Return code */ + Fts3Expr *pRoot = *pp; /* Initial root node */ + Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */ + int eType = pRoot->eType; /* Type of node in this tree */ + + if( nMaxDepth==0 ){ + rc = SQLITE_ERROR; + } + + if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){ + Fts3Expr **apLeaf; + apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth); + if( 0==apLeaf ){ + rc = SQLITE_NOMEM; + }else{ + memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth); + } + + if( rc==SQLITE_OK ){ + int i; + Fts3Expr *p; + + /* Set $p to point to the left-most leaf in the tree of eType nodes. */ + for(p=pRoot; p->eType==eType; p=p->pLeft){ + assert( p->pParent==0 || p->pParent->pLeft==p ); + assert( p->pLeft && p->pRight ); + } + + /* This loop runs once for each leaf in the tree of eType nodes. */ + while( 1 ){ + int iLvl; + Fts3Expr *pParent = p->pParent; /* Current parent of p */ + + assert( pParent==0 || pParent->pLeft==p ); + p->pParent = 0; + if( pParent ){ + pParent->pLeft = 0; + }else{ + pRoot = 0; + } + rc = fts3ExprBalance(&p, nMaxDepth-1); + if( rc!=SQLITE_OK ) break; + + for(iLvl=0; p && iLvlpLeft = apLeaf[iLvl]; + pFree->pRight = p; + pFree->pLeft->pParent = pFree; + pFree->pRight->pParent = pFree; + + p = pFree; + pFree = pFree->pParent; + p->pParent = 0; + apLeaf[iLvl] = 0; + } + } + if( p ){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_TOOBIG; + break; + } + + /* If that was the last leaf node, break out of the loop */ + if( pParent==0 ) break; + + /* Set $p to point to the next leaf in the tree of eType nodes */ + for(p=pParent->pRight; p->eType==eType; p=p->pLeft); + + /* Remove pParent from the original tree. */ + assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent ); + pParent->pRight->pParent = pParent->pParent; + if( pParent->pParent ){ + pParent->pParent->pLeft = pParent->pRight; + }else{ + assert( pParent==pRoot ); + pRoot = pParent->pRight; + } + + /* Link pParent into the free node list. It will be used as an + ** internal node of the new tree. */ + pParent->pParent = pFree; + pFree = pParent; + } + + if( rc==SQLITE_OK ){ + p = 0; + for(i=0; ipParent = 0; + }else{ + assert( pFree!=0 ); + pFree->pRight = p; + pFree->pLeft = apLeaf[i]; + pFree->pLeft->pParent = pFree; + pFree->pRight->pParent = pFree; + + p = pFree; + pFree = pFree->pParent; + p->pParent = 0; + } + } + } + pRoot = p; + }else{ + /* An error occurred. Delete the contents of the apLeaf[] array + ** and pFree list. Everything else is cleaned up by the call to + ** sqlite3Fts3ExprFree(pRoot) below. */ + Fts3Expr *pDel; + for(i=0; ipParent; + sqlite3_free(pDel); + } + } + + assert( pFree==0 ); + sqlite3_free( apLeaf ); + } + } + + if( rc!=SQLITE_OK ){ + sqlite3Fts3ExprFree(pRoot); + pRoot = 0; + } + *pp = pRoot; + return rc; +} + +/* +** This function is similar to sqlite3Fts3ExprParse(), with the following +** differences: +** +** 1. It does not do expression rebalancing. +** 2. It does not check that the expression does not exceed the +** maximum allowable depth. +** 3. Even if it fails, *ppExpr may still be set to point to an +** expression tree. It should be deleted using sqlite3Fts3ExprFree() +** in this case. +*/ +static int fts3ExprParseUnbalanced( + sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ + int iLangid, /* Language id for tokenizer */ + char **azCol, /* Array of column names for fts3 table */ + int bFts4, /* True to allow FTS4-only syntax */ + int nCol, /* Number of entries in azCol[] */ + int iDefaultCol, /* Default column to query */ + const char *z, int n, /* Text of MATCH query */ + Fts3Expr **ppExpr /* OUT: Parsed query structure */ +){ + int nParsed; + int rc; + ParseContext sParse; + + memset(&sParse, 0, sizeof(ParseContext)); + sParse.pTokenizer = pTokenizer; + sParse.iLangid = iLangid; + sParse.azCol = (const char **)azCol; + sParse.nCol = nCol; + sParse.iDefaultCol = iDefaultCol; + sParse.bFts4 = bFts4; + if( z==0 ){ + *ppExpr = 0; + return SQLITE_OK; + } + if( n<0 ){ + n = (int)strlen(z); + } + rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed); + assert( rc==SQLITE_OK || *ppExpr==0 ); + + /* Check for mismatched parenthesis */ + if( rc==SQLITE_OK && sParse.nNest ){ + rc = SQLITE_ERROR; + } + + return rc; +} + +/* +** Parameters z and n contain a pointer to and length of a buffer containing +** an fts3 query expression, respectively. This function attempts to parse the +** query expression and create a tree of Fts3Expr structures representing the +** parsed expression. If successful, *ppExpr is set to point to the head +** of the parsed expression tree and SQLITE_OK is returned. If an error +** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse +** error) is returned and *ppExpr is set to 0. +** +** If parameter n is a negative number, then z is assumed to point to a +** nul-terminated string and the length is determined using strlen(). +** +** The first parameter, pTokenizer, is passed the fts3 tokenizer module to +** use to normalize query tokens while parsing the expression. The azCol[] +** array, which is assumed to contain nCol entries, should contain the names +** of each column in the target fts3 table, in order from left to right. +** Column names must be nul-terminated strings. +** +** The iDefaultCol parameter should be passed the index of the table column +** that appears on the left-hand-side of the MATCH operator (the default +** column to match against for tokens for which a column name is not explicitly +** specified as part of the query string), or -1 if tokens may by default +** match any table column. +*/ +SQLITE_PRIVATE int sqlite3Fts3ExprParse( + sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ + int iLangid, /* Language id for tokenizer */ + char **azCol, /* Array of column names for fts3 table */ + int bFts4, /* True to allow FTS4-only syntax */ + int nCol, /* Number of entries in azCol[] */ + int iDefaultCol, /* Default column to query */ + const char *z, int n, /* Text of MATCH query */ + Fts3Expr **ppExpr, /* OUT: Parsed query structure */ + char **pzErr /* OUT: Error message (sqlite3_malloc) */ +){ + int rc = fts3ExprParseUnbalanced( + pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr + ); + + /* Rebalance the expression. And check that its depth does not exceed + ** SQLITE_FTS3_MAX_EXPR_DEPTH. */ + if( rc==SQLITE_OK && *ppExpr ){ + rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); + if( rc==SQLITE_OK ){ + rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); + } + } + + if( rc!=SQLITE_OK ){ + sqlite3Fts3ExprFree(*ppExpr); + *ppExpr = 0; + if( rc==SQLITE_TOOBIG ){ + *pzErr = sqlite3_mprintf( + "FTS expression tree is too large (maximum depth %d)", + SQLITE_FTS3_MAX_EXPR_DEPTH + ); + rc = SQLITE_ERROR; + }else if( rc==SQLITE_ERROR ){ + *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z); + } + } + + return rc; +} + +/* +** Free a single node of an expression tree. +*/ +static void fts3FreeExprNode(Fts3Expr *p){ + assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 ); + sqlite3Fts3EvalPhraseCleanup(p->pPhrase); + sqlite3_free(p->aMI); + sqlite3_free(p); +} + +/* +** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse(). +** +** This function would be simpler if it recursively called itself. But +** that would mean passing a sufficiently large expression to ExprParse() +** could cause a stack overflow. +*/ +SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){ + Fts3Expr *p; + assert( pDel==0 || pDel->pParent==0 ); + for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){ + assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft ); + } + while( p ){ + Fts3Expr *pParent = p->pParent; + fts3FreeExprNode(p); + if( pParent && p==pParent->pLeft && pParent->pRight ){ + p = pParent->pRight; + while( p && (p->pLeft || p->pRight) ){ + assert( p==p->pParent->pRight || p==p->pParent->pLeft ); + p = (p->pLeft ? p->pLeft : p->pRight); + } + }else{ + p = pParent; + } + } +} + +/**************************************************************************** +***************************************************************************** +** Everything after this point is just test code. +*/ + +#ifdef SQLITE_TEST + +/* #include */ + +/* +** Function to query the hash-table of tokenizers (see README.tokenizers). +*/ +static int queryTestTokenizer( + sqlite3 *db, + const char *zName, + const sqlite3_tokenizer_module **pp +){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts3_tokenizer(?)"; + + *pp = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ + memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + } + } + + return sqlite3_finalize(pStmt); +} + +/* +** Return a pointer to a buffer containing a text representation of the +** expression passed as the first argument. The buffer is obtained from +** sqlite3_malloc(). It is the responsibility of the caller to use +** sqlite3_free() to release the memory. If an OOM condition is encountered, +** NULL is returned. +** +** If the second argument is not NULL, then its contents are prepended to +** the returned expression text and then freed using sqlite3_free(). +*/ +static char *exprToString(Fts3Expr *pExpr, char *zBuf){ + if( pExpr==0 ){ + return sqlite3_mprintf(""); + } + switch( pExpr->eType ){ + case FTSQUERY_PHRASE: { + Fts3Phrase *pPhrase = pExpr->pPhrase; + int i; + zBuf = sqlite3_mprintf( + "%zPHRASE %d 0", zBuf, pPhrase->iColumn); + for(i=0; zBuf && inToken; i++){ + zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, + pPhrase->aToken[i].n, pPhrase->aToken[i].z, + (pPhrase->aToken[i].isPrefix?"+":"") + ); + } + return zBuf; + } + + case FTSQUERY_NEAR: + zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear); + break; + case FTSQUERY_NOT: + zBuf = sqlite3_mprintf("%zNOT ", zBuf); + break; + case FTSQUERY_AND: + zBuf = sqlite3_mprintf("%zAND ", zBuf); + break; + case FTSQUERY_OR: + zBuf = sqlite3_mprintf("%zOR ", zBuf); + break; + } + + if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf); + if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf); + if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf); + + if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf); + if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf); + + return zBuf; +} + +/* +** This is the implementation of a scalar SQL function used to test the +** expression parser. It should be called as follows: +** +** fts3_exprtest(, , , ...); +** +** The first argument, , is the name of the fts3 tokenizer used +** to parse the query expression (see README.tokenizers). The second argument +** is the query expression to parse. Each subsequent argument is the name +** of a column of the fts3 table that the query expression may refer to. +** For example: +** +** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2'); +*/ +static void fts3ExprTest( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3_tokenizer_module const *pModule = 0; + sqlite3_tokenizer *pTokenizer = 0; + int rc; + char **azCol = 0; + const char *zExpr; + int nExpr; + int nCol; + int ii; + Fts3Expr *pExpr; + char *zBuf = 0; + sqlite3 *db = sqlite3_context_db_handle(context); + + if( argc<3 ){ + sqlite3_result_error(context, + "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1 + ); + return; + } + + rc = queryTestTokenizer(db, + (const char *)sqlite3_value_text(argv[0]), &pModule); + if( rc==SQLITE_NOMEM ){ + sqlite3_result_error_nomem(context); + goto exprtest_out; + }else if( !pModule ){ + sqlite3_result_error(context, "No such tokenizer module", -1); + goto exprtest_out; + } + + rc = pModule->xCreate(0, 0, &pTokenizer); + assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); + if( rc==SQLITE_NOMEM ){ + sqlite3_result_error_nomem(context); + goto exprtest_out; + } + pTokenizer->pModule = pModule; + + zExpr = (const char *)sqlite3_value_text(argv[1]); + nExpr = sqlite3_value_bytes(argv[1]); + nCol = argc-2; + azCol = (char **)sqlite3_malloc(nCol*sizeof(char *)); + if( !azCol ){ + sqlite3_result_error_nomem(context); + goto exprtest_out; + } + for(ii=0; iixDestroy(pTokenizer); + } + sqlite3_free(azCol); +} + +/* +** Register the query expression parser test function fts3_exprtest() +** with database connection db. +*/ +SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){ + int rc = sqlite3_create_function( + db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0 + ); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", + -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0 + ); + } + return rc; +} + +#endif +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ + +/************** End of fts3_expr.c *******************************************/ +/************** Begin file fts3_hash.c ***************************************/ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the implementation of generic hash-tables used in SQLite. +** We've modified it slightly to serve as a standalone hash table +** implementation for the full-text indexing module. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* #include */ +/* #include */ +/* #include */ + + +/* +** Malloc and Free functions +*/ +static void *fts3HashMalloc(int n){ + void *p = sqlite3_malloc(n); + if( p ){ + memset(p, 0, n); + } + return p; +} +static void fts3HashFree(void *p){ + sqlite3_free(p); +} + +/* Turn bulk memory into a hash table object by initializing the +** fields of the Hash structure. +** +** "pNew" is a pointer to the hash table that is to be initialized. +** keyClass is one of the constants +** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass +** determines what kind of key the hash table will use. "copyKey" is +** true if the hash table should make its own private copy of keys and +** false if it should just use the supplied pointer. +*/ +SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){ + assert( pNew!=0 ); + assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY ); + pNew->keyClass = keyClass; + pNew->copyKey = copyKey; + pNew->first = 0; + pNew->count = 0; + pNew->htsize = 0; + pNew->ht = 0; +} + +/* Remove all entries from a hash table. Reclaim all memory. +** Call this routine to delete a hash table or to reset a hash table +** to the empty state. +*/ +SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){ + Fts3HashElem *elem; /* For looping over all elements of the table */ + + assert( pH!=0 ); + elem = pH->first; + pH->first = 0; + fts3HashFree(pH->ht); + pH->ht = 0; + pH->htsize = 0; + while( elem ){ + Fts3HashElem *next_elem = elem->next; + if( pH->copyKey && elem->pKey ){ + fts3HashFree(elem->pKey); + } + fts3HashFree(elem); + elem = next_elem; + } + pH->count = 0; +} + +/* +** Hash and comparison functions when the mode is FTS3_HASH_STRING +*/ +static int fts3StrHash(const void *pKey, int nKey){ + const char *z = (const char *)pKey; + int h = 0; + if( nKey<=0 ) nKey = (int) strlen(z); + while( nKey > 0 ){ + h = (h<<3) ^ h ^ *z++; + nKey--; + } + return h & 0x7fffffff; +} +static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return strncmp((const char*)pKey1,(const char*)pKey2,n1); +} + +/* +** Hash and comparison functions when the mode is FTS3_HASH_BINARY +*/ +static int fts3BinHash(const void *pKey, int nKey){ + int h = 0; + const char *z = (const char *)pKey; + while( nKey-- > 0 ){ + h = (h<<3) ^ h ^ *(z++); + } + return h & 0x7fffffff; +} +static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return memcmp(pKey1,pKey2,n1); +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** The C syntax in this function definition may be unfamilar to some +** programmers, so we provide the following additional explanation: +** +** The name of the function is "ftsHashFunction". The function takes a +** single parameter "keyClass". The return value of ftsHashFunction() +** is a pointer to another function. Specifically, the return value +** of ftsHashFunction() is a pointer to a function that takes two parameters +** with types "const void*" and "int" and returns an "int". +*/ +static int (*ftsHashFunction(int keyClass))(const void*,int){ + if( keyClass==FTS3_HASH_STRING ){ + return &fts3StrHash; + }else{ + assert( keyClass==FTS3_HASH_BINARY ); + return &fts3BinHash; + } +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** For help in interpreted the obscure C code in the function definition, +** see the header comment on the previous function. +*/ +static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){ + if( keyClass==FTS3_HASH_STRING ){ + return &fts3StrCompare; + }else{ + assert( keyClass==FTS3_HASH_BINARY ); + return &fts3BinCompare; + } +} + +/* Link an element into the hash table +*/ +static void fts3HashInsertElement( + Fts3Hash *pH, /* The complete hash table */ + struct _fts3ht *pEntry, /* The entry into which pNew is inserted */ + Fts3HashElem *pNew /* The element to be inserted */ +){ + Fts3HashElem *pHead; /* First element already in pEntry */ + pHead = pEntry->chain; + if( pHead ){ + pNew->next = pHead; + pNew->prev = pHead->prev; + if( pHead->prev ){ pHead->prev->next = pNew; } + else { pH->first = pNew; } + pHead->prev = pNew; + }else{ + pNew->next = pH->first; + if( pH->first ){ pH->first->prev = pNew; } + pNew->prev = 0; + pH->first = pNew; + } + pEntry->count++; + pEntry->chain = pNew; +} + + +/* Resize the hash table so that it cantains "new_size" buckets. +** "new_size" must be a power of 2. The hash table might fail +** to resize if sqliteMalloc() fails. +** +** Return non-zero if a memory allocation error occurs. +*/ +static int fts3Rehash(Fts3Hash *pH, int new_size){ + struct _fts3ht *new_ht; /* The new hash table */ + Fts3HashElem *elem, *next_elem; /* For looping over existing elements */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( (new_size & (new_size-1))==0 ); + new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) ); + if( new_ht==0 ) return 1; + fts3HashFree(pH->ht); + pH->ht = new_ht; + pH->htsize = new_size; + xHash = ftsHashFunction(pH->keyClass); + for(elem=pH->first, pH->first=0; elem; elem = next_elem){ + int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1); + next_elem = elem->next; + fts3HashInsertElement(pH, &new_ht[h], elem); + } + return 0; +} + +/* This function (for internal use only) locates an element in an +** hash table that matches the given key. The hash for this key has +** already been computed and is passed as the 4th parameter. +*/ +static Fts3HashElem *fts3FindElementByHash( + const Fts3Hash *pH, /* The pH to be searched */ + const void *pKey, /* The key we are searching for */ + int nKey, + int h /* The hash for this key. */ +){ + Fts3HashElem *elem; /* Used to loop thru the element list */ + int count; /* Number of elements left to test */ + int (*xCompare)(const void*,int,const void*,int); /* comparison function */ + + if( pH->ht ){ + struct _fts3ht *pEntry = &pH->ht[h]; + elem = pEntry->chain; + count = pEntry->count; + xCompare = ftsCompareFunction(pH->keyClass); + while( count-- && elem ){ + if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ + return elem; + } + elem = elem->next; + } + } + return 0; +} + +/* Remove a single entry from the hash table given a pointer to that +** element and a hash on the element's key. +*/ +static void fts3RemoveElementByHash( + Fts3Hash *pH, /* The pH containing "elem" */ + Fts3HashElem* elem, /* The element to be removed from the pH */ + int h /* Hash value for the element */ +){ + struct _fts3ht *pEntry; + if( elem->prev ){ + elem->prev->next = elem->next; + }else{ + pH->first = elem->next; + } + if( elem->next ){ + elem->next->prev = elem->prev; + } + pEntry = &pH->ht[h]; + if( pEntry->chain==elem ){ + pEntry->chain = elem->next; + } + pEntry->count--; + if( pEntry->count<=0 ){ + pEntry->chain = 0; + } + if( pH->copyKey && elem->pKey ){ + fts3HashFree(elem->pKey); + } + fts3HashFree( elem ); + pH->count--; + if( pH->count<=0 ){ + assert( pH->first==0 ); + assert( pH->count==0 ); + fts3HashClear(pH); + } +} + +SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem( + const Fts3Hash *pH, + const void *pKey, + int nKey +){ + int h; /* A hash on key */ + int (*xHash)(const void*,int); /* The hash function */ + + if( pH==0 || pH->ht==0 ) return 0; + xHash = ftsHashFunction(pH->keyClass); + assert( xHash!=0 ); + h = (*xHash)(pKey,nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1)); +} + +/* +** Attempt to locate an element of the hash table pH with a key +** that matches pKey,nKey. Return the data for this element if it is +** found, or NULL if there is no match. +*/ +SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){ + Fts3HashElem *pElem; /* The element that matches key (if any) */ + + pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey); + return pElem ? pElem->data : 0; +} + +/* Insert an element into the hash table pH. The key is pKey,nKey +** and the data is "data". +** +** If no element exists with a matching key, then a new +** element is created. A copy of the key is made if the copyKey +** flag is set. NULL is returned. +** +** If another element already exists with the same key, then the +** new data replaces the old data and the old data is returned. +** The key is not copied in this instance. If a malloc fails, then +** the new data is returned and the hash table is unchanged. +** +** If the "data" parameter to this function is NULL, then the +** element corresponding to "key" is removed from the hash table. +*/ +SQLITE_PRIVATE void *sqlite3Fts3HashInsert( + Fts3Hash *pH, /* The hash table to insert into */ + const void *pKey, /* The key */ + int nKey, /* Number of bytes in the key */ + void *data /* The data */ +){ + int hraw; /* Raw hash value of the key */ + int h; /* the hash of the key modulo hash table size */ + Fts3HashElem *elem; /* Used to loop thru the element list */ + Fts3HashElem *new_elem; /* New element added to the pH */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( pH!=0 ); + xHash = ftsHashFunction(pH->keyClass); + assert( xHash!=0 ); + hraw = (*xHash)(pKey, nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + elem = fts3FindElementByHash(pH,pKey,nKey,h); + if( elem ){ + void *old_data = elem->data; + if( data==0 ){ + fts3RemoveElementByHash(pH,elem,h); + }else{ + elem->data = data; + } + return old_data; + } + if( data==0 ) return 0; + if( (pH->htsize==0 && fts3Rehash(pH,8)) + || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2)) + ){ + pH->count = 0; + return data; + } + assert( pH->htsize>0 ); + new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) ); + if( new_elem==0 ) return data; + if( pH->copyKey && pKey!=0 ){ + new_elem->pKey = fts3HashMalloc( nKey ); + if( new_elem->pKey==0 ){ + fts3HashFree(new_elem); + return data; + } + memcpy((void*)new_elem->pKey, pKey, nKey); + }else{ + new_elem->pKey = (void*)pKey; + } + new_elem->nKey = nKey; + pH->count++; + assert( pH->htsize>0 ); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + fts3HashInsertElement(pH, &pH->ht[h], new_elem); + new_elem->data = data; + return 0; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ + +/************** End of fts3_hash.c *******************************************/ +/************** Begin file fts3_porter.c *************************************/ +/* +** 2006 September 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Implementation of the full-text-search tokenizer that implements +** a Porter stemmer. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* #include */ +/* #include */ +/* #include */ +/* #include */ + + +/* +** Class derived from sqlite3_tokenizer +*/ +typedef struct porter_tokenizer { + sqlite3_tokenizer base; /* Base class */ +} porter_tokenizer; + +/* +** Class derived from sqlite3_tokenizer_cursor +*/ +typedef struct porter_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *zInput; /* input we are tokenizing */ + int nInput; /* size of the input */ + int iOffset; /* current position in zInput */ + int iToken; /* index of next token to be returned */ + char *zToken; /* storage for current token */ + int nAllocated; /* space allocated to zToken buffer */ +} porter_tokenizer_cursor; + + +/* +** Create a new tokenizer instance. +*/ +static int porterCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer +){ + porter_tokenizer *t; + + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + + t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t)); + if( t==NULL ) return SQLITE_NOMEM; + memset(t, 0, sizeof(*t)); + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int porterDestroy(sqlite3_tokenizer *pTokenizer){ + sqlite3_free(pTokenizer); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is zInput[0..nInput-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int porterOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *zInput, int nInput, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + porter_tokenizer_cursor *c; + + UNUSED_PARAMETER(pTokenizer); + + c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); + if( c==NULL ) return SQLITE_NOMEM; + + c->zInput = zInput; + if( zInput==0 ){ + c->nInput = 0; + }else if( nInput<0 ){ + c->nInput = (int)strlen(zInput); + }else{ + c->nInput = nInput; + } + c->iOffset = 0; /* start tokenizing at the beginning */ + c->iToken = 0; + c->zToken = NULL; /* no space allocated, yet. */ + c->nAllocated = 0; + + *ppCursor = &c->base; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** porterOpen() above. +*/ +static int porterClose(sqlite3_tokenizer_cursor *pCursor){ + porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; + sqlite3_free(c->zToken); + sqlite3_free(c); + return SQLITE_OK; +} +/* +** Vowel or consonant +*/ +static const char cType[] = { + 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 2, 1 +}; + +/* +** isConsonant() and isVowel() determine if their first character in +** the string they point to is a consonant or a vowel, according +** to Porter ruls. +** +** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'. +** 'Y' is a consonant unless it follows another consonant, +** in which case it is a vowel. +** +** In these routine, the letters are in reverse order. So the 'y' rule +** is that 'y' is a consonant unless it is followed by another +** consonent. +*/ +static int isVowel(const char*); +static int isConsonant(const char *z){ + int j; + char x = *z; + if( x==0 ) return 0; + assert( x>='a' && x<='z' ); + j = cType[x-'a']; + if( j<2 ) return j; + return z[1]==0 || isVowel(z + 1); +} +static int isVowel(const char *z){ + int j; + char x = *z; + if( x==0 ) return 0; + assert( x>='a' && x<='z' ); + j = cType[x-'a']; + if( j<2 ) return 1-j; + return isConsonant(z + 1); +} + +/* +** Let any sequence of one or more vowels be represented by V and let +** C be sequence of one or more consonants. Then every word can be +** represented as: +** +** [C] (VC){m} [V] +** +** In prose: A word is an optional consonant followed by zero or +** vowel-consonant pairs followed by an optional vowel. "m" is the +** number of vowel consonant pairs. This routine computes the value +** of m for the first i bytes of a word. +** +** Return true if the m-value for z is 1 or more. In other words, +** return true if z contains at least one vowel that is followed +** by a consonant. +** +** In this routine z[] is in reverse order. So we are really looking +** for an instance of of a consonant followed by a vowel. +*/ +static int m_gt_0(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* Like mgt0 above except we are looking for a value of m which is +** exactly 1 +*/ +static int m_eq_1(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + if( *z==0 ) return 0; + while( isVowel(z) ){ z++; } + if( *z==0 ) return 1; + while( isConsonant(z) ){ z++; } + return *z==0; +} + +/* Like mgt0 above except we are looking for a value of m>1 instead +** or m>0 +*/ +static int m_gt_1(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + if( *z==0 ) return 0; + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* +** Return TRUE if there is a vowel anywhere within z[0..n-1] +*/ +static int hasVowel(const char *z){ + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* +** Return TRUE if the word ends in a double consonant. +** +** The text is reversed here. So we are really looking at +** the first two characters of z[]. +*/ +static int doubleConsonant(const char *z){ + return isConsonant(z) && z[0]==z[1]; +} + +/* +** Return TRUE if the word ends with three letters which +** are consonant-vowel-consonent and where the final consonant +** is not 'w', 'x', or 'y'. +** +** The word is reversed here. So we are really checking the +** first three letters and the first one cannot be in [wxy]. +*/ +static int star_oh(const char *z){ + return + isConsonant(z) && + z[0]!='w' && z[0]!='x' && z[0]!='y' && + isVowel(z+1) && + isConsonant(z+2); +} + +/* +** If the word ends with zFrom and xCond() is true for the stem +** of the word that preceeds the zFrom ending, then change the +** ending to zTo. +** +** The input word *pz and zFrom are both in reverse order. zTo +** is in normal order. +** +** Return TRUE if zFrom matches. Return FALSE if zFrom does not +** match. Not that TRUE is returned even if xCond() fails and +** no substitution occurs. +*/ +static int stem( + char **pz, /* The word being stemmed (Reversed) */ + const char *zFrom, /* If the ending matches this... (Reversed) */ + const char *zTo, /* ... change the ending to this (not reversed) */ + int (*xCond)(const char*) /* Condition that must be true */ +){ + char *z = *pz; + while( *zFrom && *zFrom==*z ){ z++; zFrom++; } + if( *zFrom!=0 ) return 0; + if( xCond && !xCond(z) ) return 1; + while( *zTo ){ + *(--z) = *(zTo++); + } + *pz = z; + return 1; +} + +/* +** This is the fallback stemmer used when the porter stemmer is +** inappropriate. The input word is copied into the output with +** US-ASCII case folding. If the input word is too long (more +** than 20 bytes if it contains no digits or more than 6 bytes if +** it contains digits) then word is truncated to 20 or 6 bytes +** by taking 10 or 3 bytes from the beginning and end. +*/ +static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){ + int i, mx, j; + int hasDigit = 0; + for(i=0; i='A' && c<='Z' ){ + zOut[i] = c - 'A' + 'a'; + }else{ + if( c>='0' && c<='9' ) hasDigit = 1; + zOut[i] = c; + } + } + mx = hasDigit ? 3 : 10; + if( nIn>mx*2 ){ + for(j=mx, i=nIn-mx; i=(int)sizeof(zReverse)-7 ){ + /* The word is too big or too small for the porter stemmer. + ** Fallback to the copy stemmer */ + copy_stemmer(zIn, nIn, zOut, pnOut); + return; + } + for(i=0, j=sizeof(zReverse)-6; i='A' && c<='Z' ){ + zReverse[j] = c + 'a' - 'A'; + }else if( c>='a' && c<='z' ){ + zReverse[j] = c; + }else{ + /* The use of a character not in [a-zA-Z] means that we fallback + ** to the copy stemmer */ + copy_stemmer(zIn, nIn, zOut, pnOut); + return; + } + } + memset(&zReverse[sizeof(zReverse)-5], 0, 5); + z = &zReverse[j+1]; + + + /* Step 1a */ + if( z[0]=='s' ){ + if( + !stem(&z, "sess", "ss", 0) && + !stem(&z, "sei", "i", 0) && + !stem(&z, "ss", "ss", 0) + ){ + z++; + } + } + + /* Step 1b */ + z2 = z; + if( stem(&z, "dee", "ee", m_gt_0) ){ + /* Do nothing. The work was all in the test */ + }else if( + (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel)) + && z!=z2 + ){ + if( stem(&z, "ta", "ate", 0) || + stem(&z, "lb", "ble", 0) || + stem(&z, "zi", "ize", 0) ){ + /* Do nothing. The work was all in the test */ + }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){ + z++; + }else if( m_eq_1(z) && star_oh(z) ){ + *(--z) = 'e'; + } + } + + /* Step 1c */ + if( z[0]=='y' && hasVowel(z+1) ){ + z[0] = 'i'; + } + + /* Step 2 */ + switch( z[1] ){ + case 'a': + stem(&z, "lanoita", "ate", m_gt_0) || + stem(&z, "lanoit", "tion", m_gt_0); + break; + case 'c': + stem(&z, "icne", "ence", m_gt_0) || + stem(&z, "icna", "ance", m_gt_0); + break; + case 'e': + stem(&z, "rezi", "ize", m_gt_0); + break; + case 'g': + stem(&z, "igol", "log", m_gt_0); + break; + case 'l': + stem(&z, "ilb", "ble", m_gt_0) || + stem(&z, "illa", "al", m_gt_0) || + stem(&z, "iltne", "ent", m_gt_0) || + stem(&z, "ile", "e", m_gt_0) || + stem(&z, "ilsuo", "ous", m_gt_0); + break; + case 'o': + stem(&z, "noitazi", "ize", m_gt_0) || + stem(&z, "noita", "ate", m_gt_0) || + stem(&z, "rota", "ate", m_gt_0); + break; + case 's': + stem(&z, "msila", "al", m_gt_0) || + stem(&z, "ssenevi", "ive", m_gt_0) || + stem(&z, "ssenluf", "ful", m_gt_0) || + stem(&z, "ssensuo", "ous", m_gt_0); + break; + case 't': + stem(&z, "itila", "al", m_gt_0) || + stem(&z, "itivi", "ive", m_gt_0) || + stem(&z, "itilib", "ble", m_gt_0); + break; + } + + /* Step 3 */ + switch( z[0] ){ + case 'e': + stem(&z, "etaci", "ic", m_gt_0) || + stem(&z, "evita", "", m_gt_0) || + stem(&z, "ezila", "al", m_gt_0); + break; + case 'i': + stem(&z, "itici", "ic", m_gt_0); + break; + case 'l': + stem(&z, "laci", "ic", m_gt_0) || + stem(&z, "luf", "", m_gt_0); + break; + case 's': + stem(&z, "ssen", "", m_gt_0); + break; + } + + /* Step 4 */ + switch( z[1] ){ + case 'a': + if( z[0]=='l' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'c': + if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){ + z += 4; + } + break; + case 'e': + if( z[0]=='r' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'i': + if( z[0]=='c' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'l': + if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){ + z += 4; + } + break; + case 'n': + if( z[0]=='t' ){ + if( z[2]=='a' ){ + if( m_gt_1(z+3) ){ + z += 3; + } + }else if( z[2]=='e' ){ + stem(&z, "tneme", "", m_gt_1) || + stem(&z, "tnem", "", m_gt_1) || + stem(&z, "tne", "", m_gt_1); + } + } + break; + case 'o': + if( z[0]=='u' ){ + if( m_gt_1(z+2) ){ + z += 2; + } + }else if( z[3]=='s' || z[3]=='t' ){ + stem(&z, "noi", "", m_gt_1); + } + break; + case 's': + if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){ + z += 3; + } + break; + case 't': + stem(&z, "eta", "", m_gt_1) || + stem(&z, "iti", "", m_gt_1); + break; + case 'u': + if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){ + z += 3; + } + break; + case 'v': + case 'z': + if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){ + z += 3; + } + break; + } + + /* Step 5a */ + if( z[0]=='e' ){ + if( m_gt_1(z+1) ){ + z++; + }else if( m_eq_1(z+1) && !star_oh(z+1) ){ + z++; + } + } + + /* Step 5b */ + if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){ + z++; + } + + /* z[] is now the stemmed word in reverse order. Flip it back + ** around into forward order and return. + */ + *pnOut = i = (int)strlen(z); + zOut[i] = 0; + while( *z ){ + zOut[--i] = *(z++); + } +} + +/* +** Characters that can be part of a token. We assume any character +** whose value is greater than 0x80 (any UTF character) can be +** part of a token. In other words, delimiters all must have +** values of 0x7f or lower. +*/ +static const char porterIdChar[] = { +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ +}; +#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30])) + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to porterOpen(). +*/ +static int porterNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */ + const char **pzToken, /* OUT: *pzToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; + const char *z = c->zInput; + + while( c->iOffsetnInput ){ + int iStartOffset, ch; + + /* Scan past delimiter characters */ + while( c->iOffsetnInput && isDelim(z[c->iOffset]) ){ + c->iOffset++; + } + + /* Count non-delimiter characters. */ + iStartOffset = c->iOffset; + while( c->iOffsetnInput && !isDelim(z[c->iOffset]) ){ + c->iOffset++; + } + + if( c->iOffset>iStartOffset ){ + int n = c->iOffset-iStartOffset; + if( n>c->nAllocated ){ + char *pNew; + c->nAllocated = n+20; + pNew = sqlite3_realloc(c->zToken, c->nAllocated); + if( !pNew ) return SQLITE_NOMEM; + c->zToken = pNew; + } + porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes); + *pzToken = c->zToken; + *piStartOffset = iStartOffset; + *piEndOffset = c->iOffset; + *piPosition = c->iToken++; + return SQLITE_OK; + } + } + return SQLITE_DONE; +} + +/* +** The set of routines that implement the porter-stemmer tokenizer +*/ +static const sqlite3_tokenizer_module porterTokenizerModule = { + 0, + porterCreate, + porterDestroy, + porterOpen, + porterClose, + porterNext, + 0 +}; + +/* +** Allocate a new porter tokenizer. Return a pointer to the new +** tokenizer in *ppModule +*/ +SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &porterTokenizerModule; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ + +/************** End of fts3_porter.c *****************************************/ +/************** Begin file fts3_tokenizer.c **********************************/ +/* +** 2007 June 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This is part of an SQLite module implementing full-text search. +** This particular file implements the generic tokenizer interface. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* #include */ +/* #include */ + +/* +** Implementation of the SQL scalar function for accessing the underlying +** hash table. This function may be called as follows: +** +** SELECT (); +** SELECT (, ); +** +** where is the name passed as the second argument +** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer'). +** +** If the argument is specified, it must be a blob value +** containing a pointer to be stored as the hash data corresponding +** to the string . If is not specified, then +** the string must already exist in the has table. Otherwise, +** an error is returned. +** +** Whether or not the argument is specified, the value returned +** is a blob containing the pointer stored as the hash data corresponding +** to string (after the hash-table is updated, if applicable). +*/ +static void scalarFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + Fts3Hash *pHash; + void *pPtr = 0; + const unsigned char *zName; + int nName; + + assert( argc==1 || argc==2 ); + + pHash = (Fts3Hash *)sqlite3_user_data(context); + + zName = sqlite3_value_text(argv[0]); + nName = sqlite3_value_bytes(argv[0])+1; + + if( argc==2 ){ + void *pOld; + int n = sqlite3_value_bytes(argv[1]); + if( n!=sizeof(pPtr) ){ + sqlite3_result_error(context, "argument type mismatch", -1); + return; + } + pPtr = *(void **)sqlite3_value_blob(argv[1]); + pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr); + if( pOld==pPtr ){ + sqlite3_result_error(context, "out of memory", -1); + return; + } + }else{ + pPtr = sqlite3Fts3HashFind(pHash, zName, nName); + if( !pPtr ){ + char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); + return; + } + } + + sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT); +} + +SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){ + static const char isFtsIdChar[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ + 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ + }; + return (c&0x80 || isFtsIdChar[(int)(c)]); +} + +SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){ + const char *z1; + const char *z2 = 0; + + /* Find the start of the next token. */ + z1 = zStr; + while( z2==0 ){ + char c = *z1; + switch( c ){ + case '\0': return 0; /* No more tokens here */ + case '\'': + case '"': + case '`': { + z2 = z1; + while( *++z2 && (*z2!=c || *++z2==c) ); + break; + } + case '[': + z2 = &z1[1]; + while( *z2 && z2[0]!=']' ) z2++; + if( *z2 ) z2++; + break; + + default: + if( sqlite3Fts3IsIdChar(*z1) ){ + z2 = &z1[1]; + while( sqlite3Fts3IsIdChar(*z2) ) z2++; + }else{ + z1++; + } + } + } + + *pn = (int)(z2-z1); + return z1; +} + +SQLITE_PRIVATE int sqlite3Fts3InitTokenizer( + Fts3Hash *pHash, /* Tokenizer hash table */ + const char *zArg, /* Tokenizer name */ + sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */ + char **pzErr /* OUT: Set to malloced error message */ +){ + int rc; + char *z = (char *)zArg; + int n = 0; + char *zCopy; + char *zEnd; /* Pointer to nul-term of zCopy */ + sqlite3_tokenizer_module *m; + + zCopy = sqlite3_mprintf("%s", zArg); + if( !zCopy ) return SQLITE_NOMEM; + zEnd = &zCopy[strlen(zCopy)]; + + z = (char *)sqlite3Fts3NextToken(zCopy, &n); + z[n] = '\0'; + sqlite3Fts3Dequote(z); + + m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1); + if( !m ){ + *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z); + rc = SQLITE_ERROR; + }else{ + char const **aArg = 0; + int iArg = 0; + z = &z[n+1]; + while( zxCreate(iArg, aArg, ppTok); + assert( rc!=SQLITE_OK || *ppTok ); + if( rc!=SQLITE_OK ){ + *pzErr = sqlite3_mprintf("unknown tokenizer"); + }else{ + (*ppTok)->pModule = m; + } + sqlite3_free((void *)aArg); + } + + sqlite3_free(zCopy); + return rc; +} + + +#ifdef SQLITE_TEST + +#include +/* #include */ + +/* +** Implementation of a special SQL scalar function for testing tokenizers +** designed to be used in concert with the Tcl testing framework. This +** function must be called with two or more arguments: +** +** SELECT (, ..., ); +** +** where is the name passed as the second argument +** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer') +** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test'). +** +** The return value is a string that may be interpreted as a Tcl +** list. For each token in the , three elements are +** added to the returned list. The first is the token position, the +** second is the token text (folded, stemmed, etc.) and the third is the +** substring of associated with the token. For example, +** using the built-in "simple" tokenizer: +** +** SELECT fts_tokenizer_test('simple', 'I don't see how'); +** +** will return the string: +** +** "{0 i I 1 dont don't 2 see see 3 how how}" +** +*/ +static void testFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + Fts3Hash *pHash; + sqlite3_tokenizer_module *p; + sqlite3_tokenizer *pTokenizer = 0; + sqlite3_tokenizer_cursor *pCsr = 0; + + const char *zErr = 0; + + const char *zName; + int nName; + const char *zInput; + int nInput; + + const char *azArg[64]; + + const char *zToken; + int nToken = 0; + int iStart = 0; + int iEnd = 0; + int iPos = 0; + int i; + + Tcl_Obj *pRet; + + if( argc<2 ){ + sqlite3_result_error(context, "insufficient arguments", -1); + return; + } + + nName = sqlite3_value_bytes(argv[0]); + zName = (const char *)sqlite3_value_text(argv[0]); + nInput = sqlite3_value_bytes(argv[argc-1]); + zInput = (const char *)sqlite3_value_text(argv[argc-1]); + + pHash = (Fts3Hash *)sqlite3_user_data(context); + p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); + + if( !p ){ + char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); + return; + } + + pRet = Tcl_NewObj(); + Tcl_IncrRefCount(pRet); + + for(i=1; ixCreate(argc-2, azArg, &pTokenizer) ){ + zErr = "error in xCreate()"; + goto finish; + } + pTokenizer->pModule = p; + if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){ + zErr = "error in xOpen()"; + goto finish; + } + + while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){ + Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); + zToken = &zInput[iStart]; + nToken = iEnd-iStart; + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); + } + + if( SQLITE_OK!=p->xClose(pCsr) ){ + zErr = "error in xClose()"; + goto finish; + } + if( SQLITE_OK!=p->xDestroy(pTokenizer) ){ + zErr = "error in xDestroy()"; + goto finish; + } + +finish: + if( zErr ){ + sqlite3_result_error(context, zErr, -1); + }else{ + sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); + } + Tcl_DecrRefCount(pRet); +} + +static +int registerTokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module *p +){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts3_tokenizer(?, ?)"; + + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); + sqlite3_step(pStmt); + + return sqlite3_finalize(pStmt); +} + +static +int queryTokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module **pp +){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts3_tokenizer(?)"; + + *pp = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ + memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + } + } + + return sqlite3_finalize(pStmt); +} + +SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); + +/* +** Implementation of the scalar function fts3_tokenizer_internal_test(). +** This function is used for testing only, it is not included in the +** build unless SQLITE_TEST is defined. +** +** The purpose of this is to test that the fts3_tokenizer() function +** can be used as designed by the C-code in the queryTokenizer and +** registerTokenizer() functions above. These two functions are repeated +** in the README.tokenizer file as an example, so it is important to +** test them. +** +** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar +** function with no arguments. An assert() will fail if a problem is +** detected. i.e.: +** +** SELECT fts3_tokenizer_internal_test(); +** +*/ +static void intTestFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int rc; + const sqlite3_tokenizer_module *p1; + const sqlite3_tokenizer_module *p2; + sqlite3 *db = (sqlite3 *)sqlite3_user_data(context); + + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + + /* Test the query function */ + sqlite3Fts3SimpleTokenizerModule(&p1); + rc = queryTokenizer(db, "simple", &p2); + assert( rc==SQLITE_OK ); + assert( p1==p2 ); + rc = queryTokenizer(db, "nosuchtokenizer", &p2); + assert( rc==SQLITE_ERROR ); + assert( p2==0 ); + assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") ); + + /* Test the storage function */ + rc = registerTokenizer(db, "nosuchtokenizer", p1); + assert( rc==SQLITE_OK ); + rc = queryTokenizer(db, "nosuchtokenizer", &p2); + assert( rc==SQLITE_OK ); + assert( p2==p1 ); + + sqlite3_result_text(context, "ok", -1, SQLITE_STATIC); +} + +#endif + +/* +** Set up SQL objects in database db used to access the contents of +** the hash table pointed to by argument pHash. The hash table must +** been initialized to use string keys, and to take a private copy +** of the key when a value is inserted. i.e. by a call similar to: +** +** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); +** +** This function adds a scalar function (see header comment above +** scalarFunc() in this file for details) and, if ENABLE_TABLE is +** defined at compilation time, a temporary virtual table (see header +** comment above struct HashTableVtab) to the database schema. Both +** provide read/write access to the contents of *pHash. +** +** The third argument to this function, zName, is used as the name +** of both the scalar and, if created, the virtual table. +*/ +SQLITE_PRIVATE int sqlite3Fts3InitHashTable( + sqlite3 *db, + Fts3Hash *pHash, + const char *zName +){ + int rc = SQLITE_OK; + void *p = (void *)pHash; + const int any = SQLITE_ANY; + +#ifdef SQLITE_TEST + char *zTest = 0; + char *zTest2 = 0; + void *pdb = (void *)db; + zTest = sqlite3_mprintf("%s_test", zName); + zTest2 = sqlite3_mprintf("%s_internal_test", zName); + if( !zTest || !zTest2 ){ + rc = SQLITE_NOMEM; + } +#endif + + if( SQLITE_OK==rc ){ + rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0); + } + if( SQLITE_OK==rc ){ + rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0); + } +#ifdef SQLITE_TEST + if( SQLITE_OK==rc ){ + rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0); + } + if( SQLITE_OK==rc ){ + rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0); + } +#endif + +#ifdef SQLITE_TEST + sqlite3_free(zTest); + sqlite3_free(zTest2); +#endif + + return rc; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ + +/************** End of fts3_tokenizer.c **************************************/ +/************** Begin file fts3_tokenizer1.c *********************************/ +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** Implementation of the "simple" full-text-search tokenizer. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* #include */ +/* #include */ +/* #include */ +/* #include */ + + +typedef struct simple_tokenizer { + sqlite3_tokenizer base; + char delim[128]; /* flag ASCII delimiters */ +} simple_tokenizer; + +typedef struct simple_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *pInput; /* input we are tokenizing */ + int nBytes; /* size of the input */ + int iOffset; /* current position in pInput */ + int iToken; /* index of next token to be returned */ + char *pToken; /* storage for current token */ + int nTokenAllocated; /* space allocated to zToken buffer */ +} simple_tokenizer_cursor; + + +static int simpleDelim(simple_tokenizer *t, unsigned char c){ + return c<0x80 && t->delim[c]; +} +static int fts3_isalnum(int x){ + return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z'); +} + +/* +** Create a new tokenizer instance. +*/ +static int simpleCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer +){ + simple_tokenizer *t; + + t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t)); + if( t==NULL ) return SQLITE_NOMEM; + memset(t, 0, sizeof(*t)); + + /* TODO(shess) Delimiters need to remain the same from run to run, + ** else we need to reindex. One solution would be a meta-table to + ** track such information in the database, then we'd only want this + ** information on the initial create. + */ + if( argc>1 ){ + int i, n = (int)strlen(argv[1]); + for(i=0; i=0x80 ){ + sqlite3_free(t); + return SQLITE_ERROR; + } + t->delim[ch] = 1; + } + } else { + /* Mark non-alphanumeric ASCII characters as delimiters */ + int i; + for(i=1; i<0x80; i++){ + t->delim[i] = !fts3_isalnum(i) ? -1 : 0; + } + } + + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ + sqlite3_free(pTokenizer); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is pInput[0..nBytes-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int simpleOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *pInput, int nBytes, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + simple_tokenizer_cursor *c; + + UNUSED_PARAMETER(pTokenizer); + + c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); + if( c==NULL ) return SQLITE_NOMEM; + + c->pInput = pInput; + if( pInput==0 ){ + c->nBytes = 0; + }else if( nBytes<0 ){ + c->nBytes = (int)strlen(pInput); + }else{ + c->nBytes = nBytes; + } + c->iOffset = 0; /* start tokenizing at the beginning */ + c->iToken = 0; + c->pToken = NULL; /* no space allocated, yet. */ + c->nTokenAllocated = 0; + + *ppCursor = &c->base; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** simpleOpen() above. +*/ +static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + sqlite3_free(c->pToken); + sqlite3_free(c); + return SQLITE_OK; +} + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to simpleOpen(). +*/ +static int simpleNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer; + unsigned char *p = (unsigned char *)c->pInput; + + while( c->iOffsetnBytes ){ + int iStartOffset; + + /* Scan past delimiter characters */ + while( c->iOffsetnBytes && simpleDelim(t, p[c->iOffset]) ){ + c->iOffset++; + } + + /* Count non-delimiter characters. */ + iStartOffset = c->iOffset; + while( c->iOffsetnBytes && !simpleDelim(t, p[c->iOffset]) ){ + c->iOffset++; + } + + if( c->iOffset>iStartOffset ){ + int i, n = c->iOffset-iStartOffset; + if( n>c->nTokenAllocated ){ + char *pNew; + c->nTokenAllocated = n+20; + pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated); + if( !pNew ) return SQLITE_NOMEM; + c->pToken = pNew; + } + for(i=0; ipToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch); + } + *ppToken = c->pToken; + *pnBytes = n; + *piStartOffset = iStartOffset; + *piEndOffset = c->iOffset; + *piPosition = c->iToken++; + + return SQLITE_OK; + } + } + return SQLITE_DONE; +} + +/* +** The set of routines that implement the simple tokenizer +*/ +static const sqlite3_tokenizer_module simpleTokenizerModule = { + 0, + simpleCreate, + simpleDestroy, + simpleOpen, + simpleClose, + simpleNext, + 0, +}; + +/* +** Allocate a new simple tokenizer. Return a pointer to the new +** tokenizer in *ppModule +*/ +SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &simpleTokenizerModule; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ + +/************** End of fts3_tokenizer1.c *************************************/ +/************** Begin file fts3_tokenize_vtab.c ******************************/ +/* +** 2013 Apr 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code for the "fts3tokenize" virtual table module. +** An fts3tokenize virtual table is created as follows: +** +** CREATE VIRTUAL TABLE USING fts3tokenize( +** , , ... +** ); +** +** The table created has the following schema: +** +** CREATE TABLE (input, token, start, end, position) +** +** When queried, the query must include a WHERE clause of type: +** +** input = +** +** The virtual table module tokenizes this , using the FTS3 +** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE +** statement and returns one row for each token in the result. With +** fields set as follows: +** +** input: Always set to a copy of +** token: A token from the input. +** start: Byte offset of the token within the input . +** end: Byte offset of the byte immediately following the end of the +** token within the input string. +** pos: Token offset of token within input. +** +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* #include */ +/* #include */ + +typedef struct Fts3tokTable Fts3tokTable; +typedef struct Fts3tokCursor Fts3tokCursor; + +/* +** Virtual table structure. +*/ +struct Fts3tokTable { + sqlite3_vtab base; /* Base class used by SQLite core */ + const sqlite3_tokenizer_module *pMod; + sqlite3_tokenizer *pTok; +}; + +/* +** Virtual table cursor structure. +*/ +struct Fts3tokCursor { + sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + char *zInput; /* Input string */ + sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */ + int iRowid; /* Current 'rowid' value */ + const char *zToken; /* Current 'token' value */ + int nToken; /* Size of zToken in bytes */ + int iStart; /* Current 'start' value */ + int iEnd; /* Current 'end' value */ + int iPos; /* Current 'pos' value */ +}; + +/* +** Query FTS for the tokenizer implementation named zName. +*/ +static int fts3tokQueryTokenizer( + Fts3Hash *pHash, + const char *zName, + const sqlite3_tokenizer_module **pp, + char **pzErr +){ + sqlite3_tokenizer_module *p; + int nName = (int)strlen(zName); + + p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); + if( !p ){ + *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName); + return SQLITE_ERROR; + } + + *pp = p; + return SQLITE_OK; +} + +/* +** The second argument, argv[], is an array of pointers to nul-terminated +** strings. This function makes a copy of the array and strings into a +** single block of memory. It then dequotes any of the strings that appear +** to be quoted. +** +** If successful, output parameter *pazDequote is set to point at the +** array of dequoted strings and SQLITE_OK is returned. The caller is +** responsible for eventually calling sqlite3_free() to free the array +** in this case. Or, if an error occurs, an SQLite error code is returned. +** The final value of *pazDequote is undefined in this case. +*/ +static int fts3tokDequoteArray( + int argc, /* Number of elements in argv[] */ + const char * const *argv, /* Input array */ + char ***pazDequote /* Output array */ +){ + int rc = SQLITE_OK; /* Return code */ + if( argc==0 ){ + *pazDequote = 0; + }else{ + int i; + int nByte = 0; + char **azDequote; + + for(i=0; ixCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok); + } + + if( rc==SQLITE_OK ){ + pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable)); + if( pTab==0 ){ + rc = SQLITE_NOMEM; + } + } + + if( rc==SQLITE_OK ){ + memset(pTab, 0, sizeof(Fts3tokTable)); + pTab->pMod = pMod; + pTab->pTok = pTok; + *ppVtab = &pTab->base; + }else{ + if( pTok ){ + pMod->xDestroy(pTok); + } + } + + sqlite3_free(azDequote); + return rc; +} + +/* +** This function does the work for both the xDisconnect and xDestroy methods. +** These tables have no persistent representation of their own, so xDisconnect +** and xDestroy are identical operations. +*/ +static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){ + Fts3tokTable *pTab = (Fts3tokTable *)pVtab; + + pTab->pMod->xDestroy(pTab->pTok); + sqlite3_free(pTab); + return SQLITE_OK; +} + +/* +** xBestIndex - Analyze a WHERE and ORDER BY clause. +*/ +static int fts3tokBestIndexMethod( + sqlite3_vtab *pVTab, + sqlite3_index_info *pInfo +){ + int i; + UNUSED_PARAMETER(pVTab); + + for(i=0; inConstraint; i++){ + if( pInfo->aConstraint[i].usable + && pInfo->aConstraint[i].iColumn==0 + && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + pInfo->idxNum = 1; + pInfo->aConstraintUsage[i].argvIndex = 1; + pInfo->aConstraintUsage[i].omit = 1; + pInfo->estimatedCost = 1; + return SQLITE_OK; + } + } + + pInfo->idxNum = 0; + assert( pInfo->estimatedCost>1000000.0 ); + + return SQLITE_OK; +} + +/* +** xOpen - Open a cursor. +*/ +static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ + Fts3tokCursor *pCsr; + UNUSED_PARAMETER(pVTab); + + pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor)); + if( pCsr==0 ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(Fts3tokCursor)); + + *ppCsr = (sqlite3_vtab_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** Reset the tokenizer cursor passed as the only argument. As if it had +** just been returned by fts3tokOpenMethod(). +*/ +static void fts3tokResetCursor(Fts3tokCursor *pCsr){ + if( pCsr->pCsr ){ + Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab); + pTab->pMod->xClose(pCsr->pCsr); + pCsr->pCsr = 0; + } + sqlite3_free(pCsr->zInput); + pCsr->zInput = 0; + pCsr->zToken = 0; + pCsr->nToken = 0; + pCsr->iStart = 0; + pCsr->iEnd = 0; + pCsr->iPos = 0; + pCsr->iRowid = 0; +} + +/* +** xClose - Close a cursor. +*/ +static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + + fts3tokResetCursor(pCsr); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** xNext - Advance the cursor to the next row, if any. +*/ +static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); + int rc; /* Return code */ + + pCsr->iRowid++; + rc = pTab->pMod->xNext(pCsr->pCsr, + &pCsr->zToken, &pCsr->nToken, + &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos + ); + + if( rc!=SQLITE_OK ){ + fts3tokResetCursor(pCsr); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + } + + return rc; +} + +/* +** xFilter - Initialize a cursor to point at the start of its data. +*/ +static int fts3tokFilterMethod( + sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + int idxNum, /* Strategy index */ + const char *idxStr, /* Unused */ + int nVal, /* Number of elements in apVal */ + sqlite3_value **apVal /* Arguments for the indexing scheme */ +){ + int rc = SQLITE_ERROR; + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); + UNUSED_PARAMETER(idxStr); + UNUSED_PARAMETER(nVal); + + fts3tokResetCursor(pCsr); + if( idxNum==1 ){ + const char *zByte = (const char *)sqlite3_value_text(apVal[0]); + int nByte = sqlite3_value_bytes(apVal[0]); + pCsr->zInput = sqlite3_malloc(nByte+1); + if( pCsr->zInput==0 ){ + rc = SQLITE_NOMEM; + }else{ + memcpy(pCsr->zInput, zByte, nByte); + pCsr->zInput[nByte] = 0; + rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr); + if( rc==SQLITE_OK ){ + pCsr->pCsr->pTokenizer = pTab->pTok; + } + } + } + + if( rc!=SQLITE_OK ) return rc; + return fts3tokNextMethod(pCursor); +} + +/* +** xEof - Return true if the cursor is at EOF, or false otherwise. +*/ +static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + return (pCsr->zToken==0); +} + +/* +** xColumn - Return a column value. +*/ +static int fts3tokColumnMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + int iCol /* Index of column to read value from */ +){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + + /* CREATE TABLE x(input, token, start, end, position) */ + switch( iCol ){ + case 0: + sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT); + break; + case 1: + sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT); + break; + case 2: + sqlite3_result_int(pCtx, pCsr->iStart); + break; + case 3: + sqlite3_result_int(pCtx, pCsr->iEnd); + break; + default: + assert( iCol==4 ); + sqlite3_result_int(pCtx, pCsr->iPos); + break; + } + return SQLITE_OK; +} + +/* +** xRowid - Return the current rowid for the cursor. +*/ +static int fts3tokRowidMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite_int64 *pRowid /* OUT: Rowid value */ +){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + *pRowid = (sqlite3_int64)pCsr->iRowid; + return SQLITE_OK; +} + +/* +** Register the fts3tok module with database connection db. Return SQLITE_OK +** if successful or an error code if sqlite3_create_module() fails. +*/ +SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){ + static const sqlite3_module fts3tok_module = { + 0, /* iVersion */ + fts3tokConnectMethod, /* xCreate */ + fts3tokConnectMethod, /* xConnect */ + fts3tokBestIndexMethod, /* xBestIndex */ + fts3tokDisconnectMethod, /* xDisconnect */ + fts3tokDisconnectMethod, /* xDestroy */ + fts3tokOpenMethod, /* xOpen */ + fts3tokCloseMethod, /* xClose */ + fts3tokFilterMethod, /* xFilter */ + fts3tokNextMethod, /* xNext */ + fts3tokEofMethod, /* xEof */ + fts3tokColumnMethod, /* xColumn */ + fts3tokRowidMethod, /* xRowid */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindFunction */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0 /* xRollbackTo */ + }; + int rc; /* Return code */ + + rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash); + return rc; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ + +/************** End of fts3_tokenize_vtab.c **********************************/ +/************** Begin file fts3_write.c **************************************/ +/* +** 2009 Oct 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file is part of the SQLite FTS3 extension module. Specifically, +** this file contains code to insert, update and delete rows from FTS3 +** tables. It also contains code to merge FTS3 b-tree segments. Some +** of the sub-routines used to merge segments are also used by the query +** code in fts3.c. +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* #include */ +/* #include */ +/* #include */ + + +#define FTS_MAX_APPENDABLE_HEIGHT 16 + +/* +** When full-text index nodes are loaded from disk, the buffer that they +** are loaded into has the following number of bytes of padding at the end +** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer +** of 920 bytes is allocated for it. +** +** This means that if we have a pointer into a buffer containing node data, +** it is always safe to read up to two varints from it without risking an +** overread, even if the node data is corrupted. +*/ +#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2) + +/* +** Under certain circumstances, b-tree nodes (doclists) can be loaded into +** memory incrementally instead of all at once. This can be a big performance +** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext() +** method before retrieving all query results (as may happen, for example, +** if a query has a LIMIT clause). +** +** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD +** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes. +** The code is written so that the hard lower-limit for each of these values +** is 1. Clearly such small values would be inefficient, but can be useful +** for testing purposes. +** +** If this module is built with SQLITE_TEST defined, these constants may +** be overridden at runtime for testing purposes. File fts3_test.c contains +** a Tcl interface to read and write the values. +*/ +#ifdef SQLITE_TEST +int test_fts3_node_chunksize = (4*1024); +int test_fts3_node_chunk_threshold = (4*1024)*4; +# define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize +# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold +#else +# define FTS3_NODE_CHUNKSIZE (4*1024) +# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4) +#endif + +/* +** The two values that may be meaningfully bound to the :1 parameter in +** statements SQL_REPLACE_STAT and SQL_SELECT_STAT. +*/ +#define FTS_STAT_DOCTOTAL 0 +#define FTS_STAT_INCRMERGEHINT 1 +#define FTS_STAT_AUTOINCRMERGE 2 + +/* +** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic +** and incremental merge operation that takes place. This is used for +** debugging FTS only, it should not usually be turned on in production +** systems. +*/ +#ifdef FTS3_LOG_MERGES +static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){ + sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel); +} +#else +#define fts3LogMerge(x, y) +#endif + + +typedef struct PendingList PendingList; +typedef struct SegmentNode SegmentNode; +typedef struct SegmentWriter SegmentWriter; + +/* +** An instance of the following data structure is used to build doclists +** incrementally. See function fts3PendingListAppend() for details. +*/ +struct PendingList { + int nData; + char *aData; + int nSpace; + sqlite3_int64 iLastDocid; + sqlite3_int64 iLastCol; + sqlite3_int64 iLastPos; +}; + + +/* +** Each cursor has a (possibly empty) linked list of the following objects. +*/ +struct Fts3DeferredToken { + Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */ + int iCol; /* Column token must occur in */ + Fts3DeferredToken *pNext; /* Next in list of deferred tokens */ + PendingList *pList; /* Doclist is assembled here */ +}; + +/* +** An instance of this structure is used to iterate through the terms on +** a contiguous set of segment b-tree leaf nodes. Although the details of +** this structure are only manipulated by code in this file, opaque handles +** of type Fts3SegReader* are also used by code in fts3.c to iterate through +** terms when querying the full-text index. See functions: +** +** sqlite3Fts3SegReaderNew() +** sqlite3Fts3SegReaderFree() +** sqlite3Fts3SegReaderIterate() +** +** Methods used to manipulate Fts3SegReader structures: +** +** fts3SegReaderNext() +** fts3SegReaderFirstDocid() +** fts3SegReaderNextDocid() +*/ +struct Fts3SegReader { + int iIdx; /* Index within level, or 0x7FFFFFFF for PT */ + u8 bLookup; /* True for a lookup only */ + u8 rootOnly; /* True for a root-only reader */ + + sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */ + sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */ + sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */ + sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */ + + char *aNode; /* Pointer to node data (or NULL) */ + int nNode; /* Size of buffer at aNode (or 0) */ + int nPopulate; /* If >0, bytes of buffer aNode[] loaded */ + sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */ + + Fts3HashElem **ppNextElem; + + /* Variables set by fts3SegReaderNext(). These may be read directly + ** by the caller. They are valid from the time SegmentReaderNew() returns + ** until SegmentReaderNext() returns something other than SQLITE_OK + ** (i.e. SQLITE_DONE). + */ + int nTerm; /* Number of bytes in current term */ + char *zTerm; /* Pointer to current term */ + int nTermAlloc; /* Allocated size of zTerm buffer */ + char *aDoclist; /* Pointer to doclist of current entry */ + int nDoclist; /* Size of doclist in current entry */ + + /* The following variables are used by fts3SegReaderNextDocid() to iterate + ** through the current doclist (aDoclist/nDoclist). + */ + char *pOffsetList; + int nOffsetList; /* For descending pending seg-readers only */ + sqlite3_int64 iDocid; +}; + +#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0) +#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0) + +/* +** An instance of this structure is used to create a segment b-tree in the +** database. The internal details of this type are only accessed by the +** following functions: +** +** fts3SegWriterAdd() +** fts3SegWriterFlush() +** fts3SegWriterFree() +*/ +struct SegmentWriter { + SegmentNode *pTree; /* Pointer to interior tree structure */ + sqlite3_int64 iFirst; /* First slot in %_segments written */ + sqlite3_int64 iFree; /* Next free slot in %_segments */ + char *zTerm; /* Pointer to previous term buffer */ + int nTerm; /* Number of bytes in zTerm */ + int nMalloc; /* Size of malloc'd buffer at zMalloc */ + char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ + int nSize; /* Size of allocation at aData */ + int nData; /* Bytes of data in aData */ + char *aData; /* Pointer to block from malloc() */ +}; + +/* +** Type SegmentNode is used by the following three functions to create +** the interior part of the segment b+-tree structures (everything except +** the leaf nodes). These functions and type are only ever used by code +** within the fts3SegWriterXXX() family of functions described above. +** +** fts3NodeAddTerm() +** fts3NodeWrite() +** fts3NodeFree() +** +** When a b+tree is written to the database (either as a result of a merge +** or the pending-terms table being flushed), leaves are written into the +** database file as soon as they are completely populated. The interior of +** the tree is assembled in memory and written out only once all leaves have +** been populated and stored. This is Ok, as the b+-tree fanout is usually +** very large, meaning that the interior of the tree consumes relatively +** little memory. +*/ +struct SegmentNode { + SegmentNode *pParent; /* Parent node (or NULL for root node) */ + SegmentNode *pRight; /* Pointer to right-sibling */ + SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */ + int nEntry; /* Number of terms written to node so far */ + char *zTerm; /* Pointer to previous term buffer */ + int nTerm; /* Number of bytes in zTerm */ + int nMalloc; /* Size of malloc'd buffer at zMalloc */ + char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ + int nData; /* Bytes of valid data so far */ + char *aData; /* Node data */ +}; + +/* +** Valid values for the second argument to fts3SqlStmt(). +*/ +#define SQL_DELETE_CONTENT 0 +#define SQL_IS_EMPTY 1 +#define SQL_DELETE_ALL_CONTENT 2 +#define SQL_DELETE_ALL_SEGMENTS 3 +#define SQL_DELETE_ALL_SEGDIR 4 +#define SQL_DELETE_ALL_DOCSIZE 5 +#define SQL_DELETE_ALL_STAT 6 +#define SQL_SELECT_CONTENT_BY_ROWID 7 +#define SQL_NEXT_SEGMENT_INDEX 8 +#define SQL_INSERT_SEGMENTS 9 +#define SQL_NEXT_SEGMENTS_ID 10 +#define SQL_INSERT_SEGDIR 11 +#define SQL_SELECT_LEVEL 12 +#define SQL_SELECT_LEVEL_RANGE 13 +#define SQL_SELECT_LEVEL_COUNT 14 +#define SQL_SELECT_SEGDIR_MAX_LEVEL 15 +#define SQL_DELETE_SEGDIR_LEVEL 16 +#define SQL_DELETE_SEGMENTS_RANGE 17 +#define SQL_CONTENT_INSERT 18 +#define SQL_DELETE_DOCSIZE 19 +#define SQL_REPLACE_DOCSIZE 20 +#define SQL_SELECT_DOCSIZE 21 +#define SQL_SELECT_STAT 22 +#define SQL_REPLACE_STAT 23 + +#define SQL_SELECT_ALL_PREFIX_LEVEL 24 +#define SQL_DELETE_ALL_TERMS_SEGDIR 25 +#define SQL_DELETE_SEGDIR_RANGE 26 +#define SQL_SELECT_ALL_LANGID 27 +#define SQL_FIND_MERGE_LEVEL 28 +#define SQL_MAX_LEAF_NODE_ESTIMATE 29 +#define SQL_DELETE_SEGDIR_ENTRY 30 +#define SQL_SHIFT_SEGDIR_ENTRY 31 +#define SQL_SELECT_SEGDIR 32 +#define SQL_CHOMP_SEGDIR 33 +#define SQL_SEGMENT_IS_APPENDABLE 34 +#define SQL_SELECT_INDEXES 35 +#define SQL_SELECT_MXLEVEL 36 + +/* +** This function is used to obtain an SQLite prepared statement handle +** for the statement identified by the second argument. If successful, +** *pp is set to the requested statement handle and SQLITE_OK returned. +** Otherwise, an SQLite error code is returned and *pp is set to 0. +** +** If argument apVal is not NULL, then it must point to an array with +** at least as many entries as the requested statement has bound +** parameters. The values are bound to the statements parameters before +** returning. +*/ +static int fts3SqlStmt( + Fts3Table *p, /* Virtual table handle */ + int eStmt, /* One of the SQL_XXX constants above */ + sqlite3_stmt **pp, /* OUT: Statement handle */ + sqlite3_value **apVal /* Values to bind to statement */ +){ + const char *azSql[] = { +/* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?", +/* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)", +/* 2 */ "DELETE FROM %Q.'%q_content'", +/* 3 */ "DELETE FROM %Q.'%q_segments'", +/* 4 */ "DELETE FROM %Q.'%q_segdir'", +/* 5 */ "DELETE FROM %Q.'%q_docsize'", +/* 6 */ "DELETE FROM %Q.'%q_stat'", +/* 7 */ "SELECT %s WHERE rowid=?", +/* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1", +/* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)", +/* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)", +/* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)", + + /* Return segments in order from oldest to newest.*/ +/* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root " + "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC", +/* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root " + "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?" + "ORDER BY level DESC, idx ASC", + +/* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?", +/* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", + +/* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?", +/* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?", +/* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)", +/* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?", +/* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", +/* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?", +/* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?", +/* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)", +/* 24 */ "", +/* 25 */ "", + +/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", +/* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'", + +/* This statement is used to determine which level to read the input from +** when performing an incremental merge. It returns the absolute level number +** of the oldest level in the db that contains at least ? segments. Or, +** if no level in the FTS index contains more than ? segments, the statement +** returns zero rows. */ +/* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?" + " ORDER BY (level %% 1024) ASC LIMIT 1", + +/* Estimate the upper limit on the number of leaf nodes in a new segment +** created by merging the oldest :2 segments from absolute level :1. See +** function sqlite3Fts3Incrmerge() for details. */ +/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) " + " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?", + +/* SQL_DELETE_SEGDIR_ENTRY +** Delete the %_segdir entry on absolute level :1 with index :2. */ +/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", + +/* SQL_SHIFT_SEGDIR_ENTRY +** Modify the idx value for the segment with idx=:3 on absolute level :2 +** to :1. */ +/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?", + +/* SQL_SELECT_SEGDIR +** Read a single entry from the %_segdir table. The entry from absolute +** level :1 with index value :2. */ +/* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root " + "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", + +/* SQL_CHOMP_SEGDIR +** Update the start_block (:1) and root (:2) fields of the %_segdir +** entry located on absolute level :3 with index :4. */ +/* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?" + "WHERE level = ? AND idx = ?", + +/* SQL_SEGMENT_IS_APPENDABLE +** Return a single row if the segment with end_block=? is appendable. Or +** no rows otherwise. */ +/* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL", + +/* SQL_SELECT_INDEXES +** Return the list of valid segment indexes for absolute level ? */ +/* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC", + +/* SQL_SELECT_MXLEVEL +** Return the largest relative level in the FTS index or indexes. */ +/* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'" + }; + int rc = SQLITE_OK; + sqlite3_stmt *pStmt; + + assert( SizeofArray(azSql)==SizeofArray(p->aStmt) ); + assert( eStmt=0 ); + + pStmt = p->aStmt[eStmt]; + if( !pStmt ){ + char *zSql; + if( eStmt==SQL_CONTENT_INSERT ){ + zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist); + }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){ + zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist); + }else{ + zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName); + } + if( !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL); + sqlite3_free(zSql); + assert( rc==SQLITE_OK || pStmt==0 ); + p->aStmt[eStmt] = pStmt; + } + } + if( apVal ){ + int i; + int nParam = sqlite3_bind_parameter_count(pStmt); + for(i=0; rc==SQLITE_OK && inPendingData==0 ){ + sqlite3_stmt *pStmt; + rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_null(pStmt, 1); + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + } + } + + return rc; +} + +/* +** FTS maintains a separate indexes for each language-id (a 32-bit integer). +** Within each language id, a separate index is maintained to store the +** document terms, and each configured prefix size (configured the FTS +** "prefix=" option). And each index consists of multiple levels ("relative +** levels"). +** +** All three of these values (the language id, the specific index and the +** level within the index) are encoded in 64-bit integer values stored +** in the %_segdir table on disk. This function is used to convert three +** separate component values into the single 64-bit integer value that +** can be used to query the %_segdir table. +** +** Specifically, each language-id/index combination is allocated 1024 +** 64-bit integer level values ("absolute levels"). The main terms index +** for language-id 0 is allocate values 0-1023. The first prefix index +** (if any) for language-id 0 is allocated values 1024-2047. And so on. +** Language 1 indexes are allocated immediately following language 0. +** +** So, for a system with nPrefix prefix indexes configured, the block of +** absolute levels that corresponds to language-id iLangid and index +** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024). +*/ +static sqlite3_int64 getAbsoluteLevel( + Fts3Table *p, /* FTS3 table handle */ + int iLangid, /* Language id */ + int iIndex, /* Index in p->aIndex[] */ + int iLevel /* Level of segments */ +){ + sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */ + assert( iLangid>=0 ); + assert( p->nIndex>0 ); + assert( iIndex>=0 && iIndexnIndex ); + + iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL; + return iBase + iLevel; +} + +/* +** Set *ppStmt to a statement handle that may be used to iterate through +** all rows in the %_segdir table, from oldest to newest. If successful, +** return SQLITE_OK. If an error occurs while preparing the statement, +** return an SQLite error code. +** +** There is only ever one instance of this SQL statement compiled for +** each FTS3 table. +** +** The statement returns the following columns from the %_segdir table: +** +** 0: idx +** 1: start_block +** 2: leaves_end_block +** 3: end_block +** 4: root +*/ +SQLITE_PRIVATE int sqlite3Fts3AllSegdirs( + Fts3Table *p, /* FTS3 table */ + int iLangid, /* Language being queried */ + int iIndex, /* Index for p->aIndex[] */ + int iLevel, /* Level to select (relative level) */ + sqlite3_stmt **ppStmt /* OUT: Compiled statement */ +){ + int rc; + sqlite3_stmt *pStmt = 0; + + assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 ); + assert( iLevel=0 && iIndexnIndex ); + + if( iLevel<0 ){ + /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */ + rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); + sqlite3_bind_int64(pStmt, 2, + getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) + ); + } + }else{ + /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */ + rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel)); + } + } + *ppStmt = pStmt; + return rc; +} + + +/* +** Append a single varint to a PendingList buffer. SQLITE_OK is returned +** if successful, or an SQLite error code otherwise. +** +** This function also serves to allocate the PendingList structure itself. +** For example, to create a new PendingList structure containing two +** varints: +** +** PendingList *p = 0; +** fts3PendingListAppendVarint(&p, 1); +** fts3PendingListAppendVarint(&p, 2); +*/ +static int fts3PendingListAppendVarint( + PendingList **pp, /* IN/OUT: Pointer to PendingList struct */ + sqlite3_int64 i /* Value to append to data */ +){ + PendingList *p = *pp; + + /* Allocate or grow the PendingList as required. */ + if( !p ){ + p = sqlite3_malloc(sizeof(*p) + 100); + if( !p ){ + return SQLITE_NOMEM; + } + p->nSpace = 100; + p->aData = (char *)&p[1]; + p->nData = 0; + } + else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){ + int nNew = p->nSpace * 2; + p = sqlite3_realloc(p, sizeof(*p) + nNew); + if( !p ){ + sqlite3_free(*pp); + *pp = 0; + return SQLITE_NOMEM; + } + p->nSpace = nNew; + p->aData = (char *)&p[1]; + } + + /* Append the new serialized varint to the end of the list. */ + p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i); + p->aData[p->nData] = '\0'; + *pp = p; + return SQLITE_OK; +} + +/* +** Add a docid/column/position entry to a PendingList structure. Non-zero +** is returned if the structure is sqlite3_realloced as part of adding +** the entry. Otherwise, zero. +** +** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning. +** Zero is always returned in this case. Otherwise, if no OOM error occurs, +** it is set to SQLITE_OK. +*/ +static int fts3PendingListAppend( + PendingList **pp, /* IN/OUT: PendingList structure */ + sqlite3_int64 iDocid, /* Docid for entry to add */ + sqlite3_int64 iCol, /* Column for entry to add */ + sqlite3_int64 iPos, /* Position of term for entry to add */ + int *pRc /* OUT: Return code */ +){ + PendingList *p = *pp; + int rc = SQLITE_OK; + + assert( !p || p->iLastDocid<=iDocid ); + + if( !p || p->iLastDocid!=iDocid ){ + sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0); + if( p ){ + assert( p->nDatanSpace ); + assert( p->aData[p->nData]==0 ); + p->nData++; + } + if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){ + goto pendinglistappend_out; + } + p->iLastCol = -1; + p->iLastPos = 0; + p->iLastDocid = iDocid; + } + if( iCol>0 && p->iLastCol!=iCol ){ + if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1)) + || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol)) + ){ + goto pendinglistappend_out; + } + p->iLastCol = iCol; + p->iLastPos = 0; + } + if( iCol>=0 ){ + assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) ); + rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos); + if( rc==SQLITE_OK ){ + p->iLastPos = iPos; + } + } + + pendinglistappend_out: + *pRc = rc; + if( p!=*pp ){ + *pp = p; + return 1; + } + return 0; +} + +/* +** Free a PendingList object allocated by fts3PendingListAppend(). +*/ +static void fts3PendingListDelete(PendingList *pList){ + sqlite3_free(pList); +} + +/* +** Add an entry to one of the pending-terms hash tables. +*/ +static int fts3PendingTermsAddOne( + Fts3Table *p, + int iCol, + int iPos, + Fts3Hash *pHash, /* Pending terms hash table to add entry to */ + const char *zToken, + int nToken +){ + PendingList *pList; + int rc = SQLITE_OK; + + pList = (PendingList *)fts3HashFind(pHash, zToken, nToken); + if( pList ){ + p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem)); + } + if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){ + if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){ + /* Malloc failed while inserting the new entry. This can only + ** happen if there was no previous entry for this token. + */ + assert( 0==fts3HashFind(pHash, zToken, nToken) ); + sqlite3_free(pList); + rc = SQLITE_NOMEM; + } + } + if( rc==SQLITE_OK ){ + p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem)); + } + return rc; +} + +/* +** Tokenize the nul-terminated string zText and add all tokens to the +** pending-terms hash-table. The docid used is that currently stored in +** p->iPrevDocid, and the column is specified by argument iCol. +** +** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. +*/ +static int fts3PendingTermsAdd( + Fts3Table *p, /* Table into which text will be inserted */ + int iLangid, /* Language id to use */ + const char *zText, /* Text of document to be inserted */ + int iCol, /* Column into which text is being inserted */ + u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */ +){ + int rc; + int iStart = 0; + int iEnd = 0; + int iPos = 0; + int nWord = 0; + + char const *zToken; + int nToken = 0; + + sqlite3_tokenizer *pTokenizer = p->pTokenizer; + sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + sqlite3_tokenizer_cursor *pCsr; + int (*xNext)(sqlite3_tokenizer_cursor *pCursor, + const char**,int*,int*,int*,int*); + + assert( pTokenizer && pModule ); + + /* If the user has inserted a NULL value, this function may be called with + ** zText==0. In this case, add zero token entries to the hash table and + ** return early. */ + if( zText==0 ){ + *pnWord = 0; + return SQLITE_OK; + } + + rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr); + if( rc!=SQLITE_OK ){ + return rc; + } + + xNext = pModule->xNext; + while( SQLITE_OK==rc + && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos)) + ){ + int i; + if( iPos>=nWord ) nWord = iPos+1; + + /* Positions cannot be negative; we use -1 as a terminator internally. + ** Tokens must have a non-zero length. + */ + if( iPos<0 || !zToken || nToken<=0 ){ + rc = SQLITE_ERROR; + break; + } + + /* Add the term to the terms index */ + rc = fts3PendingTermsAddOne( + p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken + ); + + /* Add the term to each of the prefix indexes that it is not too + ** short for. */ + for(i=1; rc==SQLITE_OK && inIndex; i++){ + struct Fts3Index *pIndex = &p->aIndex[i]; + if( nTokennPrefix ) continue; + rc = fts3PendingTermsAddOne( + p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix + ); + } + } + + pModule->xClose(pCsr); + *pnWord += nWord; + return (rc==SQLITE_DONE ? SQLITE_OK : rc); +} + +/* +** Calling this function indicates that subsequent calls to +** fts3PendingTermsAdd() are to add term/position-list pairs for the +** contents of the document with docid iDocid. +*/ +static int fts3PendingTermsDocid( + Fts3Table *p, /* Full-text table handle */ + int iLangid, /* Language id of row being written */ + sqlite_int64 iDocid /* Docid of row being written */ +){ + assert( iLangid>=0 ); + + /* TODO(shess) Explore whether partially flushing the buffer on + ** forced-flush would provide better performance. I suspect that if + ** we ordered the doclists by size and flushed the largest until the + ** buffer was half empty, that would let the less frequent terms + ** generate longer doclists. + */ + if( iDocid<=p->iPrevDocid + || p->iPrevLangid!=iLangid + || p->nPendingData>p->nMaxPendingData + ){ + int rc = sqlite3Fts3PendingTermsFlush(p); + if( rc!=SQLITE_OK ) return rc; + } + p->iPrevDocid = iDocid; + p->iPrevLangid = iLangid; + return SQLITE_OK; +} + +/* +** Discard the contents of the pending-terms hash tables. +*/ +SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){ + int i; + for(i=0; inIndex; i++){ + Fts3HashElem *pElem; + Fts3Hash *pHash = &p->aIndex[i].hPending; + for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){ + PendingList *pList = (PendingList *)fts3HashData(pElem); + fts3PendingListDelete(pList); + } + fts3HashClear(pHash); + } + p->nPendingData = 0; +} + +/* +** This function is called by the xUpdate() method as part of an INSERT +** operation. It adds entries for each term in the new record to the +** pendingTerms hash table. +** +** Argument apVal is the same as the similarly named argument passed to +** fts3InsertData(). Parameter iDocid is the docid of the new row. +*/ +static int fts3InsertTerms( + Fts3Table *p, + int iLangid, + sqlite3_value **apVal, + u32 *aSz +){ + int i; /* Iterator variable */ + for(i=2; inColumn+2; i++){ + int iCol = i-2; + if( p->abNotindexed[iCol]==0 ){ + const char *zText = (const char *)sqlite3_value_text(apVal[i]); + int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]); + if( rc!=SQLITE_OK ){ + return rc; + } + aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]); + } + } + return SQLITE_OK; +} + +/* +** This function is called by the xUpdate() method for an INSERT operation. +** The apVal parameter is passed a copy of the apVal argument passed by +** SQLite to the xUpdate() method. i.e: +** +** apVal[0] Not used for INSERT. +** apVal[1] rowid +** apVal[2] Left-most user-defined column +** ... +** apVal[p->nColumn+1] Right-most user-defined column +** apVal[p->nColumn+2] Hidden column with same name as table +** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid) +** apVal[p->nColumn+4] Hidden languageid column +*/ +static int fts3InsertData( + Fts3Table *p, /* Full-text table */ + sqlite3_value **apVal, /* Array of values to insert */ + sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */ +){ + int rc; /* Return code */ + sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */ + + if( p->zContentTbl ){ + sqlite3_value *pRowid = apVal[p->nColumn+3]; + if( sqlite3_value_type(pRowid)==SQLITE_NULL ){ + pRowid = apVal[1]; + } + if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){ + return SQLITE_CONSTRAINT; + } + *piDocid = sqlite3_value_int64(pRowid); + return SQLITE_OK; + } + + /* Locate the statement handle used to insert data into the %_content + ** table. The SQL for this statement is: + ** + ** INSERT INTO %_content VALUES(?, ?, ?, ...) + ** + ** The statement features N '?' variables, where N is the number of user + ** defined columns in the FTS3 table, plus one for the docid field. + */ + rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]); + if( rc==SQLITE_OK && p->zLanguageid ){ + rc = sqlite3_bind_int( + pContentInsert, p->nColumn+2, + sqlite3_value_int(apVal[p->nColumn+4]) + ); + } + if( rc!=SQLITE_OK ) return rc; + + /* There is a quirk here. The users INSERT statement may have specified + ** a value for the "rowid" field, for the "docid" field, or for both. + ** Which is a problem, since "rowid" and "docid" are aliases for the + ** same value. For example: + ** + ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2); + ** + ** In FTS3, this is an error. It is an error to specify non-NULL values + ** for both docid and some other rowid alias. + */ + if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){ + if( SQLITE_NULL==sqlite3_value_type(apVal[0]) + && SQLITE_NULL!=sqlite3_value_type(apVal[1]) + ){ + /* A rowid/docid conflict. */ + return SQLITE_ERROR; + } + rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]); + if( rc!=SQLITE_OK ) return rc; + } + + /* Execute the statement to insert the record. Set *piDocid to the + ** new docid value. + */ + sqlite3_step(pContentInsert); + rc = sqlite3_reset(pContentInsert); + + *piDocid = sqlite3_last_insert_rowid(p->db); + return rc; +} + + + +/* +** Remove all data from the FTS3 table. Clear the hash table containing +** pending terms. +*/ +static int fts3DeleteAll(Fts3Table *p, int bContent){ + int rc = SQLITE_OK; /* Return code */ + + /* Discard the contents of the pending-terms hash table. */ + sqlite3Fts3PendingTermsClear(p); + + /* Delete everything from the shadow tables. Except, leave %_content as + ** is if bContent is false. */ + assert( p->zContentTbl==0 || bContent==0 ); + if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0); + fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0); + fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0); + if( p->bHasDocsize ){ + fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0); + } + if( p->bHasStat ){ + fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0); + } + return rc; +} + +/* +** +*/ +static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){ + int iLangid = 0; + if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1); + return iLangid; +} + +/* +** The first element in the apVal[] array is assumed to contain the docid +** (an integer) of a row about to be deleted. Remove all terms from the +** full-text index. +*/ +static void fts3DeleteTerms( + int *pRC, /* Result code */ + Fts3Table *p, /* The FTS table to delete from */ + sqlite3_value *pRowid, /* The docid to be deleted */ + u32 *aSz, /* Sizes of deleted document written here */ + int *pbFound /* OUT: Set to true if row really does exist */ +){ + int rc; + sqlite3_stmt *pSelect; + + assert( *pbFound==0 ); + if( *pRC ) return; + rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid); + if( rc==SQLITE_OK ){ + if( SQLITE_ROW==sqlite3_step(pSelect) ){ + int i; + int iLangid = langidFromSelect(p, pSelect); + rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0)); + for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){ + int iCol = i-1; + if( p->abNotindexed[iCol]==0 ){ + const char *zText = (const char *)sqlite3_column_text(pSelect, i); + rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]); + aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i); + } + } + if( rc!=SQLITE_OK ){ + sqlite3_reset(pSelect); + *pRC = rc; + return; + } + *pbFound = 1; + } + rc = sqlite3_reset(pSelect); + }else{ + sqlite3_reset(pSelect); + } + *pRC = rc; +} + +/* +** Forward declaration to account for the circular dependency between +** functions fts3SegmentMerge() and fts3AllocateSegdirIdx(). +*/ +static int fts3SegmentMerge(Fts3Table *, int, int, int); + +/* +** This function allocates a new level iLevel index in the segdir table. +** Usually, indexes are allocated within a level sequentially starting +** with 0, so the allocated index is one greater than the value returned +** by: +** +** SELECT max(idx) FROM %_segdir WHERE level = :iLevel +** +** However, if there are already FTS3_MERGE_COUNT indexes at the requested +** level, they are merged into a single level (iLevel+1) segment and the +** allocated index is 0. +** +** If successful, *piIdx is set to the allocated index slot and SQLITE_OK +** returned. Otherwise, an SQLite error code is returned. +*/ +static int fts3AllocateSegdirIdx( + Fts3Table *p, + int iLangid, /* Language id */ + int iIndex, /* Index for p->aIndex */ + int iLevel, + int *piIdx +){ + int rc; /* Return Code */ + sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */ + int iNext = 0; /* Result of query pNextIdx */ + + assert( iLangid>=0 ); + assert( p->nIndex>=1 ); + + /* Set variable iNext to the next available segdir index at level iLevel. */ + rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64( + pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) + ); + if( SQLITE_ROW==sqlite3_step(pNextIdx) ){ + iNext = sqlite3_column_int(pNextIdx, 0); + } + rc = sqlite3_reset(pNextIdx); + } + + if( rc==SQLITE_OK ){ + /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already + ** full, merge all segments in level iLevel into a single iLevel+1 + ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise, + ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext. + */ + if( iNext>=FTS3_MERGE_COUNT ){ + fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel)); + rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel); + *piIdx = 0; + }else{ + *piIdx = iNext; + } + } + + return rc; +} + +/* +** The %_segments table is declared as follows: +** +** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB) +** +** This function reads data from a single row of the %_segments table. The +** specific row is identified by the iBlockid parameter. If paBlob is not +** NULL, then a buffer is allocated using sqlite3_malloc() and populated +** with the contents of the blob stored in the "block" column of the +** identified table row is. Whether or not paBlob is NULL, *pnBlob is set +** to the size of the blob in bytes before returning. +** +** If an error occurs, or the table does not contain the specified row, +** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If +** paBlob is non-NULL, then it is the responsibility of the caller to +** eventually free the returned buffer. +** +** This function may leave an open sqlite3_blob* handle in the +** Fts3Table.pSegments variable. This handle is reused by subsequent calls +** to this function. The handle may be closed by calling the +** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy +** performance improvement, but the blob handle should always be closed +** before control is returned to the user (to prevent a lock being held +** on the database file for longer than necessary). Thus, any virtual table +** method (xFilter etc.) that may directly or indirectly call this function +** must call sqlite3Fts3SegmentsClose() before returning. +*/ +SQLITE_PRIVATE int sqlite3Fts3ReadBlock( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */ + char **paBlob, /* OUT: Blob data in malloc'd buffer */ + int *pnBlob, /* OUT: Size of blob data */ + int *pnLoad /* OUT: Bytes actually loaded */ +){ + int rc; /* Return code */ + + /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */ + assert( pnBlob ); + + if( p->pSegments ){ + rc = sqlite3_blob_reopen(p->pSegments, iBlockid); + }else{ + if( 0==p->zSegmentsTbl ){ + p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName); + if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM; + } + rc = sqlite3_blob_open( + p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments + ); + } + + if( rc==SQLITE_OK ){ + int nByte = sqlite3_blob_bytes(p->pSegments); + *pnBlob = nByte; + if( paBlob ){ + char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING); + if( !aByte ){ + rc = SQLITE_NOMEM; + }else{ + if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){ + nByte = FTS3_NODE_CHUNKSIZE; + *pnLoad = nByte; + } + rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0); + memset(&aByte[nByte], 0, FTS3_NODE_PADDING); + if( rc!=SQLITE_OK ){ + sqlite3_free(aByte); + aByte = 0; + } + } + *paBlob = aByte; + } + } + + return rc; +} + +/* +** Close the blob handle at p->pSegments, if it is open. See comments above +** the sqlite3Fts3ReadBlock() function for details. +*/ +SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){ + sqlite3_blob_close(p->pSegments); + p->pSegments = 0; +} + +static int fts3SegReaderIncrRead(Fts3SegReader *pReader){ + int nRead; /* Number of bytes to read */ + int rc; /* Return code */ + + nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE); + rc = sqlite3_blob_read( + pReader->pBlob, + &pReader->aNode[pReader->nPopulate], + nRead, + pReader->nPopulate + ); + + if( rc==SQLITE_OK ){ + pReader->nPopulate += nRead; + memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING); + if( pReader->nPopulate==pReader->nNode ){ + sqlite3_blob_close(pReader->pBlob); + pReader->pBlob = 0; + pReader->nPopulate = 0; + } + } + return rc; +} + +static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){ + int rc = SQLITE_OK; + assert( !pReader->pBlob + || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode]) + ); + while( pReader->pBlob && rc==SQLITE_OK + && (pFrom - pReader->aNode + nByte)>pReader->nPopulate + ){ + rc = fts3SegReaderIncrRead(pReader); + } + return rc; +} + +/* +** Set an Fts3SegReader cursor to point at EOF. +*/ +static void fts3SegReaderSetEof(Fts3SegReader *pSeg){ + if( !fts3SegReaderIsRootOnly(pSeg) ){ + sqlite3_free(pSeg->aNode); + sqlite3_blob_close(pSeg->pBlob); + pSeg->pBlob = 0; + } + pSeg->aNode = 0; +} + +/* +** Move the iterator passed as the first argument to the next term in the +** segment. If successful, SQLITE_OK is returned. If there is no next term, +** SQLITE_DONE. Otherwise, an SQLite error code. +*/ +static int fts3SegReaderNext( + Fts3Table *p, + Fts3SegReader *pReader, + int bIncr +){ + int rc; /* Return code of various sub-routines */ + char *pNext; /* Cursor variable */ + int nPrefix; /* Number of bytes in term prefix */ + int nSuffix; /* Number of bytes in term suffix */ + + if( !pReader->aDoclist ){ + pNext = pReader->aNode; + }else{ + pNext = &pReader->aDoclist[pReader->nDoclist]; + } + + if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){ + + if( fts3SegReaderIsPending(pReader) ){ + Fts3HashElem *pElem = *(pReader->ppNextElem); + if( pElem==0 ){ + pReader->aNode = 0; + }else{ + PendingList *pList = (PendingList *)fts3HashData(pElem); + pReader->zTerm = (char *)fts3HashKey(pElem); + pReader->nTerm = fts3HashKeysize(pElem); + pReader->nNode = pReader->nDoclist = pList->nData + 1; + pReader->aNode = pReader->aDoclist = pList->aData; + pReader->ppNextElem++; + assert( pReader->aNode ); + } + return SQLITE_OK; + } + + fts3SegReaderSetEof(pReader); + + /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf + ** blocks have already been traversed. */ + assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock ); + if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){ + return SQLITE_OK; + } + + rc = sqlite3Fts3ReadBlock( + p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, + (bIncr ? &pReader->nPopulate : 0) + ); + if( rc!=SQLITE_OK ) return rc; + assert( pReader->pBlob==0 ); + if( bIncr && pReader->nPopulatenNode ){ + pReader->pBlob = p->pSegments; + p->pSegments = 0; + } + pNext = pReader->aNode; + } + + assert( !fts3SegReaderIsPending(pReader) ); + + rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2); + if( rc!=SQLITE_OK ) return rc; + + /* Because of the FTS3_NODE_PADDING bytes of padding, the following is + ** safe (no risk of overread) even if the node data is corrupted. */ + pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix); + pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix); + if( nPrefix<0 || nSuffix<=0 + || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] + ){ + return FTS_CORRUPT_VTAB; + } + + if( nPrefix+nSuffix>pReader->nTermAlloc ){ + int nNew = (nPrefix+nSuffix)*2; + char *zNew = sqlite3_realloc(pReader->zTerm, nNew); + if( !zNew ){ + return SQLITE_NOMEM; + } + pReader->zTerm = zNew; + pReader->nTermAlloc = nNew; + } + + rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX); + if( rc!=SQLITE_OK ) return rc; + + memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix); + pReader->nTerm = nPrefix+nSuffix; + pNext += nSuffix; + pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist); + pReader->aDoclist = pNext; + pReader->pOffsetList = 0; + + /* Check that the doclist does not appear to extend past the end of the + ** b-tree node. And that the final byte of the doclist is 0x00. If either + ** of these statements is untrue, then the data structure is corrupt. + */ + if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] + || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1]) + ){ + return FTS_CORRUPT_VTAB; + } + return SQLITE_OK; +} + +/* +** Set the SegReader to point to the first docid in the doclist associated +** with the current term. +*/ +static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){ + int rc = SQLITE_OK; + assert( pReader->aDoclist ); + assert( !pReader->pOffsetList ); + if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ + u8 bEof = 0; + pReader->iDocid = 0; + pReader->nOffsetList = 0; + sqlite3Fts3DoclistPrev(0, + pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, + &pReader->iDocid, &pReader->nOffsetList, &bEof + ); + }else{ + rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX); + if( rc==SQLITE_OK ){ + int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid); + pReader->pOffsetList = &pReader->aDoclist[n]; + } + } + return rc; +} + +/* +** Advance the SegReader to point to the next docid in the doclist +** associated with the current term. +** +** If arguments ppOffsetList and pnOffsetList are not NULL, then +** *ppOffsetList is set to point to the first column-offset list +** in the doclist entry (i.e. immediately past the docid varint). +** *pnOffsetList is set to the length of the set of column-offset +** lists, not including the nul-terminator byte. For example: +*/ +static int fts3SegReaderNextDocid( + Fts3Table *pTab, + Fts3SegReader *pReader, /* Reader to advance to next docid */ + char **ppOffsetList, /* OUT: Pointer to current position-list */ + int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */ +){ + int rc = SQLITE_OK; + char *p = pReader->pOffsetList; + char c = 0; + + assert( p ); + + if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ + /* A pending-terms seg-reader for an FTS4 table that uses order=desc. + ** Pending-terms doclists are always built up in ascending order, so + ** we have to iterate through them backwards here. */ + u8 bEof = 0; + if( ppOffsetList ){ + *ppOffsetList = pReader->pOffsetList; + *pnOffsetList = pReader->nOffsetList - 1; + } + sqlite3Fts3DoclistPrev(0, + pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid, + &pReader->nOffsetList, &bEof + ); + if( bEof ){ + pReader->pOffsetList = 0; + }else{ + pReader->pOffsetList = p; + } + }else{ + char *pEnd = &pReader->aDoclist[pReader->nDoclist]; + + /* Pointer p currently points at the first byte of an offset list. The + ** following block advances it to point one byte past the end of + ** the same offset list. */ + while( 1 ){ + + /* The following line of code (and the "p++" below the while() loop) is + ** normally all that is required to move pointer p to the desired + ** position. The exception is if this node is being loaded from disk + ** incrementally and pointer "p" now points to the first byte past + ** the populated part of pReader->aNode[]. + */ + while( *p | c ) c = *p++ & 0x80; + assert( *p==0 ); + + if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break; + rc = fts3SegReaderIncrRead(pReader); + if( rc!=SQLITE_OK ) return rc; + } + p++; + + /* If required, populate the output variables with a pointer to and the + ** size of the previous offset-list. + */ + if( ppOffsetList ){ + *ppOffsetList = pReader->pOffsetList; + *pnOffsetList = (int)(p - pReader->pOffsetList - 1); + } + + /* List may have been edited in place by fts3EvalNearTrim() */ + while( p=pEnd ){ + pReader->pOffsetList = 0; + }else{ + rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX); + if( rc==SQLITE_OK ){ + sqlite3_int64 iDelta; + pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta); + if( pTab->bDescIdx ){ + pReader->iDocid -= iDelta; + }else{ + pReader->iDocid += iDelta; + } + } + } + } + + return SQLITE_OK; +} + + +SQLITE_PRIVATE int sqlite3Fts3MsrOvfl( + Fts3Cursor *pCsr, + Fts3MultiSegReader *pMsr, + int *pnOvfl +){ + Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; + int nOvfl = 0; + int ii; + int rc = SQLITE_OK; + int pgsz = p->nPgsz; + + assert( p->bFts4 ); + assert( pgsz>0 ); + + for(ii=0; rc==SQLITE_OK && iinSegment; ii++){ + Fts3SegReader *pReader = pMsr->apSegment[ii]; + if( !fts3SegReaderIsPending(pReader) + && !fts3SegReaderIsRootOnly(pReader) + ){ + sqlite3_int64 jj; + for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){ + int nBlob; + rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0); + if( rc!=SQLITE_OK ) break; + if( (nBlob+35)>pgsz ){ + nOvfl += (nBlob + 34)/pgsz; + } + } + } + } + *pnOvfl = nOvfl; + return rc; +} + +/* +** Free all allocations associated with the iterator passed as the +** second argument. +*/ +SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){ + if( pReader && !fts3SegReaderIsPending(pReader) ){ + sqlite3_free(pReader->zTerm); + if( !fts3SegReaderIsRootOnly(pReader) ){ + sqlite3_free(pReader->aNode); + sqlite3_blob_close(pReader->pBlob); + } + } + sqlite3_free(pReader); +} + +/* +** Allocate a new SegReader object. +*/ +SQLITE_PRIVATE int sqlite3Fts3SegReaderNew( + int iAge, /* Segment "age". */ + int bLookup, /* True for a lookup only */ + sqlite3_int64 iStartLeaf, /* First leaf to traverse */ + sqlite3_int64 iEndLeaf, /* Final leaf to traverse */ + sqlite3_int64 iEndBlock, /* Final block of segment */ + const char *zRoot, /* Buffer containing root node */ + int nRoot, /* Size of buffer containing root node */ + Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */ +){ + Fts3SegReader *pReader; /* Newly allocated SegReader object */ + int nExtra = 0; /* Bytes to allocate segment root node */ + + assert( iStartLeaf<=iEndLeaf ); + if( iStartLeaf==0 ){ + nExtra = nRoot + FTS3_NODE_PADDING; + } + + pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra); + if( !pReader ){ + return SQLITE_NOMEM; + } + memset(pReader, 0, sizeof(Fts3SegReader)); + pReader->iIdx = iAge; + pReader->bLookup = bLookup!=0; + pReader->iStartBlock = iStartLeaf; + pReader->iLeafEndBlock = iEndLeaf; + pReader->iEndBlock = iEndBlock; + + if( nExtra ){ + /* The entire segment is stored in the root node. */ + pReader->aNode = (char *)&pReader[1]; + pReader->rootOnly = 1; + pReader->nNode = nRoot; + memcpy(pReader->aNode, zRoot, nRoot); + memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING); + }else{ + pReader->iCurrentBlock = iStartLeaf-1; + } + *ppReader = pReader; + return SQLITE_OK; +} + +/* +** This is a comparison function used as a qsort() callback when sorting +** an array of pending terms by term. This occurs as part of flushing +** the contents of the pending-terms hash table to the database. +*/ +static int fts3CompareElemByTerm(const void *lhs, const void *rhs){ + char *z1 = fts3HashKey(*(Fts3HashElem **)lhs); + char *z2 = fts3HashKey(*(Fts3HashElem **)rhs); + int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs); + int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs); + + int n = (n1aIndex */ + const char *zTerm, /* Term to search for */ + int nTerm, /* Size of buffer zTerm */ + int bPrefix, /* True for a prefix iterator */ + Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */ +){ + Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */ + Fts3HashElem *pE; /* Iterator variable */ + Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */ + int nElem = 0; /* Size of array at aElem */ + int rc = SQLITE_OK; /* Return Code */ + Fts3Hash *pHash; + + pHash = &p->aIndex[iIndex].hPending; + if( bPrefix ){ + int nAlloc = 0; /* Size of allocated array at aElem */ + + for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){ + char *zKey = (char *)fts3HashKey(pE); + int nKey = fts3HashKeysize(pE); + if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){ + if( nElem==nAlloc ){ + Fts3HashElem **aElem2; + nAlloc += 16; + aElem2 = (Fts3HashElem **)sqlite3_realloc( + aElem, nAlloc*sizeof(Fts3HashElem *) + ); + if( !aElem2 ){ + rc = SQLITE_NOMEM; + nElem = 0; + break; + } + aElem = aElem2; + } + + aElem[nElem++] = pE; + } + } + + /* If more than one term matches the prefix, sort the Fts3HashElem + ** objects in term order using qsort(). This uses the same comparison + ** callback as is used when flushing terms to disk. + */ + if( nElem>1 ){ + qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm); + } + + }else{ + /* The query is a simple term lookup that matches at most one term in + ** the index. All that is required is a straight hash-lookup. + ** + ** Because the stack address of pE may be accessed via the aElem pointer + ** below, the "Fts3HashElem *pE" must be declared so that it is valid + ** within this entire function, not just this "else{...}" block. + */ + pE = fts3HashFindElem(pHash, zTerm, nTerm); + if( pE ){ + aElem = &pE; + nElem = 1; + } + } + + if( nElem>0 ){ + int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); + pReader = (Fts3SegReader *)sqlite3_malloc(nByte); + if( !pReader ){ + rc = SQLITE_NOMEM; + }else{ + memset(pReader, 0, nByte); + pReader->iIdx = 0x7FFFFFFF; + pReader->ppNextElem = (Fts3HashElem **)&pReader[1]; + memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *)); + } + } + + if( bPrefix ){ + sqlite3_free(aElem); + } + *ppReader = pReader; + return rc; +} + +/* +** Compare the entries pointed to by two Fts3SegReader structures. +** Comparison is as follows: +** +** 1) EOF is greater than not EOF. +** +** 2) The current terms (if any) are compared using memcmp(). If one +** term is a prefix of another, the longer term is considered the +** larger. +** +** 3) By segment age. An older segment is considered larger. +*/ +static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ + int rc; + if( pLhs->aNode && pRhs->aNode ){ + int rc2 = pLhs->nTerm - pRhs->nTerm; + if( rc2<0 ){ + rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm); + }else{ + rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm); + } + if( rc==0 ){ + rc = rc2; + } + }else{ + rc = (pLhs->aNode==0) - (pRhs->aNode==0); + } + if( rc==0 ){ + rc = pRhs->iIdx - pLhs->iIdx; + } + assert( rc!=0 ); + return rc; +} + +/* +** A different comparison function for SegReader structures. In this +** version, it is assumed that each SegReader points to an entry in +** a doclist for identical terms. Comparison is made as follows: +** +** 1) EOF (end of doclist in this case) is greater than not EOF. +** +** 2) By current docid. +** +** 3) By segment age. An older segment is considered larger. +*/ +static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ + int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); + if( rc==0 ){ + if( pLhs->iDocid==pRhs->iDocid ){ + rc = pRhs->iIdx - pLhs->iIdx; + }else{ + rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1; + } + } + assert( pLhs->aNode && pRhs->aNode ); + return rc; +} +static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ + int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); + if( rc==0 ){ + if( pLhs->iDocid==pRhs->iDocid ){ + rc = pRhs->iIdx - pLhs->iIdx; + }else{ + rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1; + } + } + assert( pLhs->aNode && pRhs->aNode ); + return rc; +} + +/* +** Compare the term that the Fts3SegReader object passed as the first argument +** points to with the term specified by arguments zTerm and nTerm. +** +** If the pSeg iterator is already at EOF, return 0. Otherwise, return +** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are +** equal, or +ve if the pSeg term is greater than zTerm/nTerm. +*/ +static int fts3SegReaderTermCmp( + Fts3SegReader *pSeg, /* Segment reader object */ + const char *zTerm, /* Term to compare to */ + int nTerm /* Size of term zTerm in bytes */ +){ + int res = 0; + if( pSeg->aNode ){ + if( pSeg->nTerm>nTerm ){ + res = memcmp(pSeg->zTerm, zTerm, nTerm); + }else{ + res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm); + } + if( res==0 ){ + res = pSeg->nTerm-nTerm; + } + } + return res; +} + +/* +** Argument apSegment is an array of nSegment elements. It is known that +** the final (nSegment-nSuspect) members are already in sorted order +** (according to the comparison function provided). This function shuffles +** the array around until all entries are in sorted order. +*/ +static void fts3SegReaderSort( + Fts3SegReader **apSegment, /* Array to sort entries of */ + int nSegment, /* Size of apSegment array */ + int nSuspect, /* Unsorted entry count */ + int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */ +){ + int i; /* Iterator variable */ + + assert( nSuspect<=nSegment ); + + if( nSuspect==nSegment ) nSuspect--; + for(i=nSuspect-1; i>=0; i--){ + int j; + for(j=i; j<(nSegment-1); j++){ + Fts3SegReader *pTmp; + if( xCmp(apSegment[j], apSegment[j+1])<0 ) break; + pTmp = apSegment[j+1]; + apSegment[j+1] = apSegment[j]; + apSegment[j] = pTmp; + } + } + +#ifndef NDEBUG + /* Check that the list really is sorted now. */ + for(i=0; i<(nSuspect-1); i++){ + assert( xCmp(apSegment[i], apSegment[i+1])<0 ); + } +#endif +} + +/* +** Insert a record into the %_segments table. +*/ +static int fts3WriteSegment( + Fts3Table *p, /* Virtual table handle */ + sqlite3_int64 iBlock, /* Block id for new block */ + char *z, /* Pointer to buffer containing block data */ + int n /* Size of buffer z in bytes */ +){ + sqlite3_stmt *pStmt; + int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pStmt, 1, iBlock); + sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC); + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + } + return rc; +} + +/* +** Find the largest relative level number in the table. If successful, set +** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs, +** set *pnMax to zero and return an SQLite error code. +*/ +SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){ + int rc; + int mxLevel = 0; + sqlite3_stmt *pStmt = 0; + + rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0); + if( rc==SQLITE_OK ){ + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + mxLevel = sqlite3_column_int(pStmt, 0); + } + rc = sqlite3_reset(pStmt); + } + *pnMax = mxLevel; + return rc; +} + +/* +** Insert a record into the %_segdir table. +*/ +static int fts3WriteSegdir( + Fts3Table *p, /* Virtual table handle */ + sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */ + int iIdx, /* Value for "idx" field */ + sqlite3_int64 iStartBlock, /* Value for "start_block" field */ + sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */ + sqlite3_int64 iEndBlock, /* Value for "end_block" field */ + char *zRoot, /* Blob value for "root" field */ + int nRoot /* Number of bytes in buffer zRoot */ +){ + sqlite3_stmt *pStmt; + int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pStmt, 1, iLevel); + sqlite3_bind_int(pStmt, 2, iIdx); + sqlite3_bind_int64(pStmt, 3, iStartBlock); + sqlite3_bind_int64(pStmt, 4, iLeafEndBlock); + sqlite3_bind_int64(pStmt, 5, iEndBlock); + sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC); + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + } + return rc; +} + +/* +** Return the size of the common prefix (if any) shared by zPrev and +** zNext, in bytes. For example, +** +** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3 +** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2 +** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0 +*/ +static int fts3PrefixCompress( + const char *zPrev, /* Buffer containing previous term */ + int nPrev, /* Size of buffer zPrev in bytes */ + const char *zNext, /* Buffer containing next term */ + int nNext /* Size of buffer zNext in bytes */ +){ + int n; + UNUSED_PARAMETER(nNext); + for(n=0; nnData; /* Current size of node in bytes */ + int nReq = nData; /* Required space after adding zTerm */ + int nPrefix; /* Number of bytes of prefix compression */ + int nSuffix; /* Suffix length */ + + nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm); + nSuffix = nTerm-nPrefix; + + nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix; + if( nReq<=p->nNodeSize || !pTree->zTerm ){ + + if( nReq>p->nNodeSize ){ + /* An unusual case: this is the first term to be added to the node + ** and the static node buffer (p->nNodeSize bytes) is not large + ** enough. Use a separately malloced buffer instead This wastes + ** p->nNodeSize bytes, but since this scenario only comes about when + ** the database contain two terms that share a prefix of almost 2KB, + ** this is not expected to be a serious problem. + */ + assert( pTree->aData==(char *)&pTree[1] ); + pTree->aData = (char *)sqlite3_malloc(nReq); + if( !pTree->aData ){ + return SQLITE_NOMEM; + } + } + + if( pTree->zTerm ){ + /* There is no prefix-length field for first term in a node */ + nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix); + } + + nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix); + memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix); + pTree->nData = nData + nSuffix; + pTree->nEntry++; + + if( isCopyTerm ){ + if( pTree->nMalloczMalloc, nTerm*2); + if( !zNew ){ + return SQLITE_NOMEM; + } + pTree->nMalloc = nTerm*2; + pTree->zMalloc = zNew; + } + pTree->zTerm = pTree->zMalloc; + memcpy(pTree->zTerm, zTerm, nTerm); + pTree->nTerm = nTerm; + }else{ + pTree->zTerm = (char *)zTerm; + pTree->nTerm = nTerm; + } + return SQLITE_OK; + } + } + + /* If control flows to here, it was not possible to append zTerm to the + ** current node. Create a new node (a right-sibling of the current node). + ** If this is the first node in the tree, the term is added to it. + ** + ** Otherwise, the term is not added to the new node, it is left empty for + ** now. Instead, the term is inserted into the parent of pTree. If pTree + ** has no parent, one is created here. + */ + pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize); + if( !pNew ){ + return SQLITE_NOMEM; + } + memset(pNew, 0, sizeof(SegmentNode)); + pNew->nData = 1 + FTS3_VARINT_MAX; + pNew->aData = (char *)&pNew[1]; + + if( pTree ){ + SegmentNode *pParent = pTree->pParent; + rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm); + if( pTree->pParent==0 ){ + pTree->pParent = pParent; + } + pTree->pRight = pNew; + pNew->pLeftmost = pTree->pLeftmost; + pNew->pParent = pParent; + pNew->zMalloc = pTree->zMalloc; + pNew->nMalloc = pTree->nMalloc; + pTree->zMalloc = 0; + }else{ + pNew->pLeftmost = pNew; + rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); + } + + *ppTree = pNew; + return rc; +} + +/* +** Helper function for fts3NodeWrite(). +*/ +static int fts3TreeFinishNode( + SegmentNode *pTree, + int iHeight, + sqlite3_int64 iLeftChild +){ + int nStart; + assert( iHeight>=1 && iHeight<128 ); + nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild); + pTree->aData[nStart] = (char)iHeight; + sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild); + return nStart; +} + +/* +** Write the buffer for the segment node pTree and all of its peers to the +** database. Then call this function recursively to write the parent of +** pTree and its peers to the database. +** +** Except, if pTree is a root node, do not write it to the database. Instead, +** set output variables *paRoot and *pnRoot to contain the root node. +** +** If successful, SQLITE_OK is returned and output variable *piLast is +** set to the largest blockid written to the database (or zero if no +** blocks were written to the db). Otherwise, an SQLite error code is +** returned. +*/ +static int fts3NodeWrite( + Fts3Table *p, /* Virtual table handle */ + SegmentNode *pTree, /* SegmentNode handle */ + int iHeight, /* Height of this node in tree */ + sqlite3_int64 iLeaf, /* Block id of first leaf node */ + sqlite3_int64 iFree, /* Block id of next free slot in %_segments */ + sqlite3_int64 *piLast, /* OUT: Block id of last entry written */ + char **paRoot, /* OUT: Data for root node */ + int *pnRoot /* OUT: Size of root node in bytes */ +){ + int rc = SQLITE_OK; + + if( !pTree->pParent ){ + /* Root node of the tree. */ + int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf); + *piLast = iFree-1; + *pnRoot = pTree->nData - nStart; + *paRoot = &pTree->aData[nStart]; + }else{ + SegmentNode *pIter; + sqlite3_int64 iNextFree = iFree; + sqlite3_int64 iNextLeaf = iLeaf; + for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){ + int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf); + int nWrite = pIter->nData - nStart; + + rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite); + iNextFree++; + iNextLeaf += (pIter->nEntry+1); + } + if( rc==SQLITE_OK ){ + assert( iNextLeaf==iFree ); + rc = fts3NodeWrite( + p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot + ); + } + } + + return rc; +} + +/* +** Free all memory allocations associated with the tree pTree. +*/ +static void fts3NodeFree(SegmentNode *pTree){ + if( pTree ){ + SegmentNode *p = pTree->pLeftmost; + fts3NodeFree(p->pParent); + while( p ){ + SegmentNode *pRight = p->pRight; + if( p->aData!=(char *)&p[1] ){ + sqlite3_free(p->aData); + } + assert( pRight==0 || p->zMalloc==0 ); + sqlite3_free(p->zMalloc); + sqlite3_free(p); + p = pRight; + } + } +} + +/* +** Add a term to the segment being constructed by the SegmentWriter object +** *ppWriter. When adding the first term to a segment, *ppWriter should +** be passed NULL. This function will allocate a new SegmentWriter object +** and return it via the input/output variable *ppWriter in this case. +** +** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. +*/ +static int fts3SegWriterAdd( + Fts3Table *p, /* Virtual table handle */ + SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */ + int isCopyTerm, /* True if buffer zTerm must be copied */ + const char *zTerm, /* Pointer to buffer containing term */ + int nTerm, /* Size of term in bytes */ + const char *aDoclist, /* Pointer to buffer containing doclist */ + int nDoclist /* Size of doclist in bytes */ +){ + int nPrefix; /* Size of term prefix in bytes */ + int nSuffix; /* Size of term suffix in bytes */ + int nReq; /* Number of bytes required on leaf page */ + int nData; + SegmentWriter *pWriter = *ppWriter; + + if( !pWriter ){ + int rc; + sqlite3_stmt *pStmt; + + /* Allocate the SegmentWriter structure */ + pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter)); + if( !pWriter ) return SQLITE_NOMEM; + memset(pWriter, 0, sizeof(SegmentWriter)); + *ppWriter = pWriter; + + /* Allocate a buffer in which to accumulate data */ + pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize); + if( !pWriter->aData ) return SQLITE_NOMEM; + pWriter->nSize = p->nNodeSize; + + /* Find the next free blockid in the %_segments table */ + rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + pWriter->iFree = sqlite3_column_int64(pStmt, 0); + pWriter->iFirst = pWriter->iFree; + } + rc = sqlite3_reset(pStmt); + if( rc!=SQLITE_OK ) return rc; + } + nData = pWriter->nData; + + nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm); + nSuffix = nTerm-nPrefix; + + /* Figure out how many bytes are required by this new entry */ + nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */ + sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */ + nSuffix + /* Term suffix */ + sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ + nDoclist; /* Doclist data */ + + if( nData>0 && nData+nReq>p->nNodeSize ){ + int rc; + + /* The current leaf node is full. Write it out to the database. */ + rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData); + if( rc!=SQLITE_OK ) return rc; + p->nLeafAdd++; + + /* Add the current term to the interior node tree. The term added to + ** the interior tree must: + ** + ** a) be greater than the largest term on the leaf node just written + ** to the database (still available in pWriter->zTerm), and + ** + ** b) be less than or equal to the term about to be added to the new + ** leaf node (zTerm/nTerm). + ** + ** In other words, it must be the prefix of zTerm 1 byte longer than + ** the common prefix (if any) of zTerm and pWriter->zTerm. + */ + assert( nPrefixpTree, isCopyTerm, zTerm, nPrefix+1); + if( rc!=SQLITE_OK ) return rc; + + nData = 0; + pWriter->nTerm = 0; + + nPrefix = 0; + nSuffix = nTerm; + nReq = 1 + /* varint containing prefix size */ + sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */ + nTerm + /* Term suffix */ + sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ + nDoclist; /* Doclist data */ + } + + /* If the buffer currently allocated is too small for this entry, realloc + ** the buffer to make it large enough. + */ + if( nReq>pWriter->nSize ){ + char *aNew = sqlite3_realloc(pWriter->aData, nReq); + if( !aNew ) return SQLITE_NOMEM; + pWriter->aData = aNew; + pWriter->nSize = nReq; + } + assert( nData+nReq<=pWriter->nSize ); + + /* Append the prefix-compressed term and doclist to the buffer. */ + nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix); + nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix); + memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); + nData += nSuffix; + nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); + memcpy(&pWriter->aData[nData], aDoclist, nDoclist); + pWriter->nData = nData + nDoclist; + + /* Save the current term so that it can be used to prefix-compress the next. + ** If the isCopyTerm parameter is true, then the buffer pointed to by + ** zTerm is transient, so take a copy of the term data. Otherwise, just + ** store a copy of the pointer. + */ + if( isCopyTerm ){ + if( nTerm>pWriter->nMalloc ){ + char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2); + if( !zNew ){ + return SQLITE_NOMEM; + } + pWriter->nMalloc = nTerm*2; + pWriter->zMalloc = zNew; + pWriter->zTerm = zNew; + } + assert( pWriter->zTerm==pWriter->zMalloc ); + memcpy(pWriter->zTerm, zTerm, nTerm); + }else{ + pWriter->zTerm = (char *)zTerm; + } + pWriter->nTerm = nTerm; + + return SQLITE_OK; +} + +/* +** Flush all data associated with the SegmentWriter object pWriter to the +** database. This function must be called after all terms have been added +** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is +** returned. Otherwise, an SQLite error code. +*/ +static int fts3SegWriterFlush( + Fts3Table *p, /* Virtual table handle */ + SegmentWriter *pWriter, /* SegmentWriter to flush to the db */ + sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */ + int iIdx /* Value for 'idx' column of %_segdir */ +){ + int rc; /* Return code */ + if( pWriter->pTree ){ + sqlite3_int64 iLast = 0; /* Largest block id written to database */ + sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */ + char *zRoot = NULL; /* Pointer to buffer containing root node */ + int nRoot = 0; /* Size of buffer zRoot */ + + iLastLeaf = pWriter->iFree; + rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData); + if( rc==SQLITE_OK ){ + rc = fts3NodeWrite(p, pWriter->pTree, 1, + pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot); + } + if( rc==SQLITE_OK ){ + rc = fts3WriteSegdir( + p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot); + } + }else{ + /* The entire tree fits on the root node. Write it to the segdir table. */ + rc = fts3WriteSegdir( + p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData); + } + p->nLeafAdd++; + return rc; +} + +/* +** Release all memory held by the SegmentWriter object passed as the +** first argument. +*/ +static void fts3SegWriterFree(SegmentWriter *pWriter){ + if( pWriter ){ + sqlite3_free(pWriter->aData); + sqlite3_free(pWriter->zMalloc); + fts3NodeFree(pWriter->pTree); + sqlite3_free(pWriter); + } +} + +/* +** The first value in the apVal[] array is assumed to contain an integer. +** This function tests if there exist any documents with docid values that +** are different from that integer. i.e. if deleting the document with docid +** pRowid would mean the FTS3 table were empty. +** +** If successful, *pisEmpty is set to true if the table is empty except for +** document pRowid, or false otherwise, and SQLITE_OK is returned. If an +** error occurs, an SQLite error code is returned. +*/ +static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){ + sqlite3_stmt *pStmt; + int rc; + if( p->zContentTbl ){ + /* If using the content=xxx option, assume the table is never empty */ + *pisEmpty = 0; + rc = SQLITE_OK; + }else{ + rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid); + if( rc==SQLITE_OK ){ + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + *pisEmpty = sqlite3_column_int(pStmt, 0); + } + rc = sqlite3_reset(pStmt); + } + } + return rc; +} + +/* +** Set *pnMax to the largest segment level in the database for the index +** iIndex. +** +** Segment levels are stored in the 'level' column of the %_segdir table. +** +** Return SQLITE_OK if successful, or an SQLite error code if not. +*/ +static int fts3SegmentMaxLevel( + Fts3Table *p, + int iLangid, + int iIndex, + sqlite3_int64 *pnMax +){ + sqlite3_stmt *pStmt; + int rc; + assert( iIndex>=0 && iIndexnIndex ); + + /* Set pStmt to the compiled version of: + ** + ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? + ** + ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR). + */ + rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); + sqlite3_bind_int64(pStmt, 2, + getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) + ); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + *pnMax = sqlite3_column_int64(pStmt, 0); + } + return sqlite3_reset(pStmt); +} + +/* +** Delete all entries in the %_segments table associated with the segment +** opened with seg-reader pSeg. This function does not affect the contents +** of the %_segdir table. +*/ +static int fts3DeleteSegment( + Fts3Table *p, /* FTS table handle */ + Fts3SegReader *pSeg /* Segment to delete */ +){ + int rc = SQLITE_OK; /* Return code */ + if( pSeg->iStartBlock ){ + sqlite3_stmt *pDelete; /* SQL statement to delete rows */ + rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock); + sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock); + sqlite3_step(pDelete); + rc = sqlite3_reset(pDelete); + } + } + return rc; +} + +/* +** This function is used after merging multiple segments into a single large +** segment to delete the old, now redundant, segment b-trees. Specifically, +** it: +** +** 1) Deletes all %_segments entries for the segments associated with +** each of the SegReader objects in the array passed as the third +** argument, and +** +** 2) deletes all %_segdir entries with level iLevel, or all %_segdir +** entries regardless of level if (iLevel<0). +** +** SQLITE_OK is returned if successful, otherwise an SQLite error code. +*/ +static int fts3DeleteSegdir( + Fts3Table *p, /* Virtual table handle */ + int iLangid, /* Language id */ + int iIndex, /* Index for p->aIndex */ + int iLevel, /* Level of %_segdir entries to delete */ + Fts3SegReader **apSegment, /* Array of SegReader objects */ + int nReader /* Size of array apSegment */ +){ + int rc = SQLITE_OK; /* Return Code */ + int i; /* Iterator variable */ + sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */ + + for(i=0; rc==SQLITE_OK && i=0 || iLevel==FTS3_SEGCURSOR_ALL ); + if( iLevel==FTS3_SEGCURSOR_ALL ){ + rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); + sqlite3_bind_int64(pDelete, 2, + getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) + ); + } + }else{ + rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64( + pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) + ); + } + } + + if( rc==SQLITE_OK ){ + sqlite3_step(pDelete); + rc = sqlite3_reset(pDelete); + } + + return rc; +} + +/* +** When this function is called, buffer *ppList (size *pnList bytes) contains +** a position list that may (or may not) feature multiple columns. This +** function adjusts the pointer *ppList and the length *pnList so that they +** identify the subset of the position list that corresponds to column iCol. +** +** If there are no entries in the input position list for column iCol, then +** *pnList is set to zero before returning. +** +** If parameter bZero is non-zero, then any part of the input list following +** the end of the output list is zeroed before returning. +*/ +static void fts3ColumnFilter( + int iCol, /* Column to filter on */ + int bZero, /* Zero out anything following *ppList */ + char **ppList, /* IN/OUT: Pointer to position list */ + int *pnList /* IN/OUT: Size of buffer *ppList in bytes */ +){ + char *pList = *ppList; + int nList = *pnList; + char *pEnd = &pList[nList]; + int iCurrent = 0; + char *p = pList; + + assert( iCol>=0 ); + while( 1 ){ + char c = 0; + while( ppMsr->nBuffer ){ + char *pNew; + pMsr->nBuffer = nList*2; + pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer); + if( !pNew ) return SQLITE_NOMEM; + pMsr->aBuffer = pNew; + } + + memcpy(pMsr->aBuffer, pList, nList); + return SQLITE_OK; +} + +SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */ + sqlite3_int64 *piDocid, /* OUT: Docid value */ + char **paPoslist, /* OUT: Pointer to position list */ + int *pnPoslist /* OUT: Size of position list in bytes */ +){ + int nMerge = pMsr->nAdvance; + Fts3SegReader **apSegment = pMsr->apSegment; + int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( + p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp + ); + + if( nMerge==0 ){ + *paPoslist = 0; + return SQLITE_OK; + } + + while( 1 ){ + Fts3SegReader *pSeg; + pSeg = pMsr->apSegment[0]; + + if( pSeg->pOffsetList==0 ){ + *paPoslist = 0; + break; + }else{ + int rc; + char *pList; + int nList; + int j; + sqlite3_int64 iDocid = apSegment[0]->iDocid; + + rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); + j = 1; + while( rc==SQLITE_OK + && jpOffsetList + && apSegment[j]->iDocid==iDocid + ){ + rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0); + j++; + } + if( rc!=SQLITE_OK ) return rc; + fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp); + + if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){ + rc = fts3MsrBufferData(pMsr, pList, nList+1); + if( rc!=SQLITE_OK ) return rc; + assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 ); + pList = pMsr->aBuffer; + } + + if( pMsr->iColFilter>=0 ){ + fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList); + } + + if( nList>0 ){ + *paPoslist = pList; + *piDocid = iDocid; + *pnPoslist = nList; + break; + } + } + } + + return SQLITE_OK; +} + +static int fts3SegReaderStart( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pCsr, /* Cursor object */ + const char *zTerm, /* Term searched for (or NULL) */ + int nTerm /* Length of zTerm in bytes */ +){ + int i; + int nSeg = pCsr->nSegment; + + /* If the Fts3SegFilter defines a specific term (or term prefix) to search + ** for, then advance each segment iterator until it points to a term of + ** equal or greater value than the specified term. This prevents many + ** unnecessary merge/sort operations for the case where single segment + ** b-tree leaf nodes contain more than one term. + */ + for(i=0; pCsr->bRestart==0 && inSegment; i++){ + int res = 0; + Fts3SegReader *pSeg = pCsr->apSegment[i]; + do { + int rc = fts3SegReaderNext(p, pSeg, 0); + if( rc!=SQLITE_OK ) return rc; + }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 ); + + if( pSeg->bLookup && res!=0 ){ + fts3SegReaderSetEof(pSeg); + } + } + fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp); + + return SQLITE_OK; +} + +SQLITE_PRIVATE int sqlite3Fts3SegReaderStart( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pCsr, /* Cursor object */ + Fts3SegFilter *pFilter /* Restrictions on range of iteration */ +){ + pCsr->pFilter = pFilter; + return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm); +} + +SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pCsr, /* Cursor object */ + int iCol, /* Column to match on. */ + const char *zTerm, /* Term to iterate through a doclist for */ + int nTerm /* Number of bytes in zTerm */ +){ + int i; + int rc; + int nSegment = pCsr->nSegment; + int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( + p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp + ); + + assert( pCsr->pFilter==0 ); + assert( zTerm && nTerm>0 ); + + /* Advance each segment iterator until it points to the term zTerm/nTerm. */ + rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm); + if( rc!=SQLITE_OK ) return rc; + + /* Determine how many of the segments actually point to zTerm/nTerm. */ + for(i=0; iapSegment[i]; + if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){ + break; + } + } + pCsr->nAdvance = i; + + /* Advance each of the segments to point to the first docid. */ + for(i=0; inAdvance; i++){ + rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]); + if( rc!=SQLITE_OK ) return rc; + } + fts3SegReaderSort(pCsr->apSegment, i, i, xCmp); + + assert( iCol<0 || iColnColumn ); + pCsr->iColFilter = iCol; + + return SQLITE_OK; +} + +/* +** This function is called on a MultiSegReader that has been started using +** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also +** have been made. Calling this function puts the MultiSegReader in such +** a state that if the next two calls are: +** +** sqlite3Fts3SegReaderStart() +** sqlite3Fts3SegReaderStep() +** +** then the entire doclist for the term is available in +** MultiSegReader.aDoclist/nDoclist. +*/ +SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){ + int i; /* Used to iterate through segment-readers */ + + assert( pCsr->zTerm==0 ); + assert( pCsr->nTerm==0 ); + assert( pCsr->aDoclist==0 ); + assert( pCsr->nDoclist==0 ); + + pCsr->nAdvance = 0; + pCsr->bRestart = 1; + for(i=0; inSegment; i++){ + pCsr->apSegment[i]->pOffsetList = 0; + pCsr->apSegment[i]->nOffsetList = 0; + pCsr->apSegment[i]->iDocid = 0; + } + + return SQLITE_OK; +} + + +SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pCsr /* Cursor object */ +){ + int rc = SQLITE_OK; + + int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY); + int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS); + int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER); + int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX); + int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN); + int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST); + + Fts3SegReader **apSegment = pCsr->apSegment; + int nSegment = pCsr->nSegment; + Fts3SegFilter *pFilter = pCsr->pFilter; + int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( + p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp + ); + + if( pCsr->nSegment==0 ) return SQLITE_OK; + + do { + int nMerge; + int i; + + /* Advance the first pCsr->nAdvance entries in the apSegment[] array + ** forward. Then sort the list in order of current term again. + */ + for(i=0; inAdvance; i++){ + Fts3SegReader *pSeg = apSegment[i]; + if( pSeg->bLookup ){ + fts3SegReaderSetEof(pSeg); + }else{ + rc = fts3SegReaderNext(p, pSeg, 0); + } + if( rc!=SQLITE_OK ) return rc; + } + fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp); + pCsr->nAdvance = 0; + + /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */ + assert( rc==SQLITE_OK ); + if( apSegment[0]->aNode==0 ) break; + + pCsr->nTerm = apSegment[0]->nTerm; + pCsr->zTerm = apSegment[0]->zTerm; + + /* If this is a prefix-search, and if the term that apSegment[0] points + ** to does not share a suffix with pFilter->zTerm/nTerm, then all + ** required callbacks have been made. In this case exit early. + ** + ** Similarly, if this is a search for an exact match, and the first term + ** of segment apSegment[0] is not a match, exit early. + */ + if( pFilter->zTerm && !isScan ){ + if( pCsr->nTermnTerm + || (!isPrefix && pCsr->nTerm>pFilter->nTerm) + || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) + ){ + break; + } + } + + nMerge = 1; + while( nMergeaNode + && apSegment[nMerge]->nTerm==pCsr->nTerm + && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm) + ){ + nMerge++; + } + + assert( isIgnoreEmpty || (isRequirePos && !isColFilter) ); + if( nMerge==1 + && !isIgnoreEmpty + && !isFirst + && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0) + ){ + pCsr->nDoclist = apSegment[0]->nDoclist; + if( fts3SegReaderIsPending(apSegment[0]) ){ + rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist); + pCsr->aDoclist = pCsr->aBuffer; + }else{ + pCsr->aDoclist = apSegment[0]->aDoclist; + } + if( rc==SQLITE_OK ) rc = SQLITE_ROW; + }else{ + int nDoclist = 0; /* Size of doclist */ + sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */ + + /* The current term of the first nMerge entries in the array + ** of Fts3SegReader objects is the same. The doclists must be merged + ** and a single term returned with the merged doclist. + */ + for(i=0; ipOffsetList ){ + int j; /* Number of segments that share a docid */ + char *pList = 0; + int nList = 0; + int nByte; + sqlite3_int64 iDocid = apSegment[0]->iDocid; + fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); + j = 1; + while( jpOffsetList + && apSegment[j]->iDocid==iDocid + ){ + fts3SegReaderNextDocid(p, apSegment[j], 0, 0); + j++; + } + + if( isColFilter ){ + fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList); + } + + if( !isIgnoreEmpty || nList>0 ){ + + /* Calculate the 'docid' delta value to write into the merged + ** doclist. */ + sqlite3_int64 iDelta; + if( p->bDescIdx && nDoclist>0 ){ + iDelta = iPrev - iDocid; + }else{ + iDelta = iDocid - iPrev; + } + assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) ); + assert( nDoclist>0 || iDelta==iDocid ); + + nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0); + if( nDoclist+nByte>pCsr->nBuffer ){ + char *aNew; + pCsr->nBuffer = (nDoclist+nByte)*2; + aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer); + if( !aNew ){ + return SQLITE_NOMEM; + } + pCsr->aBuffer = aNew; + } + + if( isFirst ){ + char *a = &pCsr->aBuffer[nDoclist]; + int nWrite; + + nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a); + if( nWrite ){ + iPrev = iDocid; + nDoclist += nWrite; + } + }else{ + nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta); + iPrev = iDocid; + if( isRequirePos ){ + memcpy(&pCsr->aBuffer[nDoclist], pList, nList); + nDoclist += nList; + pCsr->aBuffer[nDoclist++] = '\0'; + } + } + } + + fts3SegReaderSort(apSegment, nMerge, j, xCmp); + } + if( nDoclist>0 ){ + pCsr->aDoclist = pCsr->aBuffer; + pCsr->nDoclist = nDoclist; + rc = SQLITE_ROW; + } + } + pCsr->nAdvance = nMerge; + }while( rc==SQLITE_OK ); + + return rc; +} + + +SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish( + Fts3MultiSegReader *pCsr /* Cursor object */ +){ + if( pCsr ){ + int i; + for(i=0; inSegment; i++){ + sqlite3Fts3SegReaderFree(pCsr->apSegment[i]); + } + sqlite3_free(pCsr->apSegment); + sqlite3_free(pCsr->aBuffer); + + pCsr->nSegment = 0; + pCsr->apSegment = 0; + pCsr->aBuffer = 0; + } +} + +/* +** Merge all level iLevel segments in the database into a single +** iLevel+1 segment. Or, if iLevel<0, merge all segments into a +** single segment with a level equal to the numerically largest level +** currently present in the database. +** +** If this function is called with iLevel<0, but there is only one +** segment in the database, SQLITE_DONE is returned immediately. +** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, +** an SQLite error code is returned. +*/ +static int fts3SegmentMerge( + Fts3Table *p, + int iLangid, /* Language id to merge */ + int iIndex, /* Index in p->aIndex[] to merge */ + int iLevel /* Level to merge */ +){ + int rc; /* Return code */ + int iIdx = 0; /* Index of new segment */ + sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */ + SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */ + Fts3SegFilter filter; /* Segment term filter condition */ + Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */ + int bIgnoreEmpty = 0; /* True to ignore empty segments */ + + assert( iLevel==FTS3_SEGCURSOR_ALL + || iLevel==FTS3_SEGCURSOR_PENDING + || iLevel>=0 + ); + assert( iLevel=0 && iIndexnIndex ); + + rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr); + if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished; + + if( iLevel==FTS3_SEGCURSOR_ALL ){ + /* This call is to merge all segments in the database to a single + ** segment. The level of the new segment is equal to the numerically + ** greatest segment level currently present in the database for this + ** index. The idx of the new segment is always 0. */ + if( csr.nSegment==1 ){ + rc = SQLITE_DONE; + goto finished; + } + rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel); + bIgnoreEmpty = 1; + + }else if( iLevel==FTS3_SEGCURSOR_PENDING ){ + iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0); + rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx); + }else{ + /* This call is to merge all segments at level iLevel. find the next + ** available segment index at level iLevel+1. The call to + ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to + ** a single iLevel+2 segment if necessary. */ + rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx); + iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1); + } + if( rc!=SQLITE_OK ) goto finished; + assert( csr.nSegment>0 ); + assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) ); + assert( iNewLevelnIndex; i++){ + rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + } + sqlite3Fts3PendingTermsClear(p); + + /* Determine the auto-incr-merge setting if unknown. If enabled, + ** estimate the number of leaf blocks of content to be written + */ + if( rc==SQLITE_OK && p->bHasStat + && p->bAutoincrmerge==0xff && p->nLeafAdd>0 + ){ + sqlite3_stmt *pStmt = 0; + rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); + rc = sqlite3_step(pStmt); + p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0)); + rc = sqlite3_reset(pStmt); + } + } + return rc; +} + +/* +** Encode N integers as varints into a blob. +*/ +static void fts3EncodeIntArray( + int N, /* The number of integers to encode */ + u32 *a, /* The integer values */ + char *zBuf, /* Write the BLOB here */ + int *pNBuf /* Write number of bytes if zBuf[] used here */ +){ + int i, j; + for(i=j=0; iiPrevDocid. The sizes are encoded as +** a blob of varints. +*/ +static void fts3InsertDocsize( + int *pRC, /* Result code */ + Fts3Table *p, /* Table into which to insert */ + u32 *aSz /* Sizes of each column, in tokens */ +){ + char *pBlob; /* The BLOB encoding of the document size */ + int nBlob; /* Number of bytes in the BLOB */ + sqlite3_stmt *pStmt; /* Statement used to insert the encoding */ + int rc; /* Result code from subfunctions */ + + if( *pRC ) return; + pBlob = sqlite3_malloc( 10*p->nColumn ); + if( pBlob==0 ){ + *pRC = SQLITE_NOMEM; + return; + } + fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob); + rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0); + if( rc ){ + sqlite3_free(pBlob); + *pRC = rc; + return; + } + sqlite3_bind_int64(pStmt, 1, p->iPrevDocid); + sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free); + sqlite3_step(pStmt); + *pRC = sqlite3_reset(pStmt); +} + +/* +** Record 0 of the %_stat table contains a blob consisting of N varints, +** where N is the number of user defined columns in the fts3 table plus +** two. If nCol is the number of user defined columns, then values of the +** varints are set as follows: +** +** Varint 0: Total number of rows in the table. +** +** Varint 1..nCol: For each column, the total number of tokens stored in +** the column for all rows of the table. +** +** Varint 1+nCol: The total size, in bytes, of all text values in all +** columns of all rows of the table. +** +*/ +static void fts3UpdateDocTotals( + int *pRC, /* The result code */ + Fts3Table *p, /* Table being updated */ + u32 *aSzIns, /* Size increases */ + u32 *aSzDel, /* Size decreases */ + int nChng /* Change in the number of documents */ +){ + char *pBlob; /* Storage for BLOB written into %_stat */ + int nBlob; /* Size of BLOB written into %_stat */ + u32 *a; /* Array of integers that becomes the BLOB */ + sqlite3_stmt *pStmt; /* Statement for reading and writing */ + int i; /* Loop counter */ + int rc; /* Result code from subfunctions */ + + const int nStat = p->nColumn+2; + + if( *pRC ) return; + a = sqlite3_malloc( (sizeof(u32)+10)*nStat ); + if( a==0 ){ + *pRC = SQLITE_NOMEM; + return; + } + pBlob = (char*)&a[nStat]; + rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); + if( rc ){ + sqlite3_free(a); + *pRC = rc; + return; + } + sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); + if( sqlite3_step(pStmt)==SQLITE_ROW ){ + fts3DecodeIntArray(nStat, a, + sqlite3_column_blob(pStmt, 0), + sqlite3_column_bytes(pStmt, 0)); + }else{ + memset(a, 0, sizeof(u32)*(nStat) ); + } + rc = sqlite3_reset(pStmt); + if( rc!=SQLITE_OK ){ + sqlite3_free(a); + *pRC = rc; + return; + } + if( nChng<0 && a[0]<(u32)(-nChng) ){ + a[0] = 0; + }else{ + a[0] += nChng; + } + for(i=0; inColumn+1; i++){ + u32 x = a[i+1]; + if( x+aSzIns[i] < aSzDel[i] ){ + x = 0; + }else{ + x = x + aSzIns[i] - aSzDel[i]; + } + a[i+1] = x; + } + fts3EncodeIntArray(nStat, a, pBlob, &nBlob); + rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); + if( rc ){ + sqlite3_free(a); + *pRC = rc; + return; + } + sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); + sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC); + sqlite3_step(pStmt); + *pRC = sqlite3_reset(pStmt); + sqlite3_free(a); +} + +/* +** Merge the entire database so that there is one segment for each +** iIndex/iLangid combination. +*/ +static int fts3DoOptimize(Fts3Table *p, int bReturnDone){ + int bSeenDone = 0; + int rc; + sqlite3_stmt *pAllLangid = 0; + + rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); + if( rc==SQLITE_OK ){ + int rc2; + sqlite3_bind_int(pAllLangid, 1, p->nIndex); + while( sqlite3_step(pAllLangid)==SQLITE_ROW ){ + int i; + int iLangid = sqlite3_column_int(pAllLangid, 0); + for(i=0; rc==SQLITE_OK && inIndex; i++){ + rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL); + if( rc==SQLITE_DONE ){ + bSeenDone = 1; + rc = SQLITE_OK; + } + } + } + rc2 = sqlite3_reset(pAllLangid); + if( rc==SQLITE_OK ) rc = rc2; + } + + sqlite3Fts3SegmentsClose(p); + sqlite3Fts3PendingTermsClear(p); + + return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc; +} + +/* +** This function is called when the user executes the following statement: +** +** INSERT INTO () VALUES('rebuild'); +** +** The entire FTS index is discarded and rebuilt. If the table is one +** created using the content=xxx option, then the new index is based on +** the current contents of the xxx table. Otherwise, it is rebuilt based +** on the contents of the %_content table. +*/ +static int fts3DoRebuild(Fts3Table *p){ + int rc; /* Return Code */ + + rc = fts3DeleteAll(p, 0); + if( rc==SQLITE_OK ){ + u32 *aSz = 0; + u32 *aSzIns = 0; + u32 *aSzDel = 0; + sqlite3_stmt *pStmt = 0; + int nEntry = 0; + + /* Compose and prepare an SQL statement to loop through the content table */ + char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); + if( !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + } + + if( rc==SQLITE_OK ){ + int nByte = sizeof(u32) * (p->nColumn+1)*3; + aSz = (u32 *)sqlite3_malloc(nByte); + if( aSz==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(aSz, 0, nByte); + aSzIns = &aSz[p->nColumn+1]; + aSzDel = &aSzIns[p->nColumn+1]; + } + } + + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ + int iCol; + int iLangid = langidFromSelect(p, pStmt); + rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0)); + memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1)); + for(iCol=0; rc==SQLITE_OK && iColnColumn; iCol++){ + if( p->abNotindexed[iCol]==0 ){ + const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1); + rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]); + aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1); + } + } + if( p->bHasDocsize ){ + fts3InsertDocsize(&rc, p, aSz); + } + if( rc!=SQLITE_OK ){ + sqlite3_finalize(pStmt); + pStmt = 0; + }else{ + nEntry++; + for(iCol=0; iCol<=p->nColumn; iCol++){ + aSzIns[iCol] += aSz[iCol]; + } + } + } + if( p->bFts4 ){ + fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry); + } + sqlite3_free(aSz); + + if( pStmt ){ + int rc2 = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + + return rc; +} + + +/* +** This function opens a cursor used to read the input data for an +** incremental merge operation. Specifically, it opens a cursor to scan +** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute +** level iAbsLevel. +*/ +static int fts3IncrmergeCsr( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level to open */ + int nSeg, /* Number of segments to merge */ + Fts3MultiSegReader *pCsr /* Cursor object to populate */ +){ + int rc; /* Return Code */ + sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */ + int nByte; /* Bytes allocated at pCsr->apSegment[] */ + + /* Allocate space for the Fts3MultiSegReader.aCsr[] array */ + memset(pCsr, 0, sizeof(*pCsr)); + nByte = sizeof(Fts3SegReader *) * nSeg; + pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte); + + if( pCsr->apSegment==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pCsr->apSegment, 0, nByte); + rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); + } + if( rc==SQLITE_OK ){ + int i; + int rc2; + sqlite3_bind_int64(pStmt, 1, iAbsLevel); + assert( pCsr->nSegment==0 ); + for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && iapSegment[i] + ); + pCsr->nSegment++; + } + rc2 = sqlite3_reset(pStmt); + if( rc==SQLITE_OK ) rc = rc2; + } + + return rc; +} + +typedef struct IncrmergeWriter IncrmergeWriter; +typedef struct NodeWriter NodeWriter; +typedef struct Blob Blob; +typedef struct NodeReader NodeReader; + +/* +** An instance of the following structure is used as a dynamic buffer +** to build up nodes or other blobs of data in. +** +** The function blobGrowBuffer() is used to extend the allocation. +*/ +struct Blob { + char *a; /* Pointer to allocation */ + int n; /* Number of valid bytes of data in a[] */ + int nAlloc; /* Allocated size of a[] (nAlloc>=n) */ +}; + +/* +** This structure is used to build up buffers containing segment b-tree +** nodes (blocks). +*/ +struct NodeWriter { + sqlite3_int64 iBlock; /* Current block id */ + Blob key; /* Last key written to the current block */ + Blob block; /* Current block image */ +}; + +/* +** An object of this type contains the state required to create or append +** to an appendable b-tree segment. +*/ +struct IncrmergeWriter { + int nLeafEst; /* Space allocated for leaf blocks */ + int nWork; /* Number of leaf pages flushed */ + sqlite3_int64 iAbsLevel; /* Absolute level of input segments */ + int iIdx; /* Index of *output* segment in iAbsLevel+1 */ + sqlite3_int64 iStart; /* Block number of first allocated block */ + sqlite3_int64 iEnd; /* Block number of last allocated block */ + NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT]; +}; + +/* +** An object of the following type is used to read data from a single +** FTS segment node. See the following functions: +** +** nodeReaderInit() +** nodeReaderNext() +** nodeReaderRelease() +*/ +struct NodeReader { + const char *aNode; + int nNode; + int iOff; /* Current offset within aNode[] */ + + /* Output variables. Containing the current node entry. */ + sqlite3_int64 iChild; /* Pointer to child node */ + Blob term; /* Current term */ + const char *aDoclist; /* Pointer to doclist */ + int nDoclist; /* Size of doclist in bytes */ +}; + +/* +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** Otherwise, if the allocation at pBlob->a is not already at least nMin +** bytes in size, extend (realloc) it to be so. +** +** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a +** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc +** to reflect the new size of the pBlob->a[] buffer. +*/ +static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){ + if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){ + int nAlloc = nMin; + char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc); + if( a ){ + pBlob->nAlloc = nAlloc; + pBlob->a = a; + }else{ + *pRc = SQLITE_NOMEM; + } + } +} + +/* +** Attempt to advance the node-reader object passed as the first argument to +** the next entry on the node. +** +** Return an error code if an error occurs (SQLITE_NOMEM is possible). +** Otherwise return SQLITE_OK. If there is no next entry on the node +** (e.g. because the current entry is the last) set NodeReader->aNode to +** NULL to indicate EOF. Otherwise, populate the NodeReader structure output +** variables for the new entry. +*/ +static int nodeReaderNext(NodeReader *p){ + int bFirst = (p->term.n==0); /* True for first term on the node */ + int nPrefix = 0; /* Bytes to copy from previous term */ + int nSuffix = 0; /* Bytes to append to the prefix */ + int rc = SQLITE_OK; /* Return code */ + + assert( p->aNode ); + if( p->iChild && bFirst==0 ) p->iChild++; + if( p->iOff>=p->nNode ){ + /* EOF */ + p->aNode = 0; + }else{ + if( bFirst==0 ){ + p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix); + } + p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix); + + blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc); + if( rc==SQLITE_OK ){ + memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix); + p->term.n = nPrefix+nSuffix; + p->iOff += nSuffix; + if( p->iChild==0 ){ + p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist); + p->aDoclist = &p->aNode[p->iOff]; + p->iOff += p->nDoclist; + } + } + } + + assert( p->iOff<=p->nNode ); + + return rc; +} + +/* +** Release all dynamic resources held by node-reader object *p. +*/ +static void nodeReaderRelease(NodeReader *p){ + sqlite3_free(p->term.a); +} + +/* +** Initialize a node-reader object to read the node in buffer aNode/nNode. +** +** If successful, SQLITE_OK is returned and the NodeReader object set to +** point to the first entry on the node (if any). Otherwise, an SQLite +** error code is returned. +*/ +static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){ + memset(p, 0, sizeof(NodeReader)); + p->aNode = aNode; + p->nNode = nNode; + + /* Figure out if this is a leaf or an internal node. */ + if( p->aNode[0] ){ + /* An internal node. */ + p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild); + }else{ + p->iOff = 1; + } + + return nodeReaderNext(p); +} + +/* +** This function is called while writing an FTS segment each time a leaf o +** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed +** to be greater than the largest key on the node just written, but smaller +** than or equal to the first key that will be written to the next leaf +** node. +** +** The block id of the leaf node just written to disk may be found in +** (pWriter->aNodeWriter[0].iBlock) when this function is called. +*/ +static int fts3IncrmergePush( + Fts3Table *p, /* Fts3 table handle */ + IncrmergeWriter *pWriter, /* Writer object */ + const char *zTerm, /* Term to write to internal node */ + int nTerm /* Bytes at zTerm */ +){ + sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock; + int iLayer; + + assert( nTerm>0 ); + for(iLayer=1; ALWAYS(iLayeraNodeWriter[iLayer]; + int rc = SQLITE_OK; + int nPrefix; + int nSuffix; + int nSpace; + + /* Figure out how much space the key will consume if it is written to + ** the current node of layer iLayer. Due to the prefix compression, + ** the space required changes depending on which node the key is to + ** be added to. */ + nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm); + nSuffix = nTerm - nPrefix; + nSpace = sqlite3Fts3VarintLen(nPrefix); + nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; + + if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ + /* If the current node of layer iLayer contains zero keys, or if adding + ** the key to it will not cause it to grow to larger than nNodeSize + ** bytes in size, write the key here. */ + + Blob *pBlk = &pNode->block; + if( pBlk->n==0 ){ + blobGrowBuffer(pBlk, p->nNodeSize, &rc); + if( rc==SQLITE_OK ){ + pBlk->a[0] = (char)iLayer; + pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr); + } + } + blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc); + blobGrowBuffer(&pNode->key, nTerm, &rc); + + if( rc==SQLITE_OK ){ + if( pNode->key.n ){ + pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix); + } + pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix); + memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix); + pBlk->n += nSuffix; + + memcpy(pNode->key.a, zTerm, nTerm); + pNode->key.n = nTerm; + } + }else{ + /* Otherwise, flush the current node of layer iLayer to disk. + ** Then allocate a new, empty sibling node. The key will be written + ** into the parent of this node. */ + rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); + + assert( pNode->block.nAlloc>=p->nNodeSize ); + pNode->block.a[0] = (char)iLayer; + pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1); + + iNextPtr = pNode->iBlock; + pNode->iBlock++; + pNode->key.n = 0; + } + + if( rc!=SQLITE_OK || iNextPtr==0 ) return rc; + iPtr = iNextPtr; + } + + assert( 0 ); + return 0; +} + +/* +** Append a term and (optionally) doclist to the FTS segment node currently +** stored in blob *pNode. The node need not contain any terms, but the +** header must be written before this function is called. +** +** A node header is a single 0x00 byte for a leaf node, or a height varint +** followed by the left-hand-child varint for an internal node. +** +** The term to be appended is passed via arguments zTerm/nTerm. For a +** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal +** node, both aDoclist and nDoclist must be passed 0. +** +** If the size of the value in blob pPrev is zero, then this is the first +** term written to the node. Otherwise, pPrev contains a copy of the +** previous term. Before this function returns, it is updated to contain a +** copy of zTerm/nTerm. +** +** It is assumed that the buffer associated with pNode is already large +** enough to accommodate the new entry. The buffer associated with pPrev +** is extended by this function if requrired. +** +** If an error (i.e. OOM condition) occurs, an SQLite error code is +** returned. Otherwise, SQLITE_OK. +*/ +static int fts3AppendToNode( + Blob *pNode, /* Current node image to append to */ + Blob *pPrev, /* Buffer containing previous term written */ + const char *zTerm, /* New term to write */ + int nTerm, /* Size of zTerm in bytes */ + const char *aDoclist, /* Doclist (or NULL) to write */ + int nDoclist /* Size of aDoclist in bytes */ +){ + int rc = SQLITE_OK; /* Return code */ + int bFirst = (pPrev->n==0); /* True if this is the first term written */ + int nPrefix; /* Size of term prefix in bytes */ + int nSuffix; /* Size of term suffix in bytes */ + + /* Node must have already been started. There must be a doclist for a + ** leaf node, and there must not be a doclist for an internal node. */ + assert( pNode->n>0 ); + assert( (pNode->a[0]=='\0')==(aDoclist!=0) ); + + blobGrowBuffer(pPrev, nTerm, &rc); + if( rc!=SQLITE_OK ) return rc; + + nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm); + nSuffix = nTerm - nPrefix; + memcpy(pPrev->a, zTerm, nTerm); + pPrev->n = nTerm; + + if( bFirst==0 ){ + pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix); + } + pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix); + memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix); + pNode->n += nSuffix; + + if( aDoclist ){ + pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist); + memcpy(&pNode->a[pNode->n], aDoclist, nDoclist); + pNode->n += nDoclist; + } + + assert( pNode->n<=pNode->nAlloc ); + + return SQLITE_OK; +} + +/* +** Append the current term and doclist pointed to by cursor pCsr to the +** appendable b-tree segment opened for writing by pWriter. +** +** Return SQLITE_OK if successful, or an SQLite error code otherwise. +*/ +static int fts3IncrmergeAppend( + Fts3Table *p, /* Fts3 table handle */ + IncrmergeWriter *pWriter, /* Writer object */ + Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */ +){ + const char *zTerm = pCsr->zTerm; + int nTerm = pCsr->nTerm; + const char *aDoclist = pCsr->aDoclist; + int nDoclist = pCsr->nDoclist; + int rc = SQLITE_OK; /* Return code */ + int nSpace; /* Total space in bytes required on leaf */ + int nPrefix; /* Size of prefix shared with previous term */ + int nSuffix; /* Size of suffix (nTerm - nPrefix) */ + NodeWriter *pLeaf; /* Object used to write leaf nodes */ + + pLeaf = &pWriter->aNodeWriter[0]; + nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm); + nSuffix = nTerm - nPrefix; + + nSpace = sqlite3Fts3VarintLen(nPrefix); + nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; + nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; + + /* If the current block is not empty, and if adding this term/doclist + ** to the current block would make it larger than Fts3Table.nNodeSize + ** bytes, write this block out to the database. */ + if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){ + rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n); + pWriter->nWork++; + + /* Add the current term to the parent node. The term added to the + ** parent must: + ** + ** a) be greater than the largest term on the leaf node just written + ** to the database (still available in pLeaf->key), and + ** + ** b) be less than or equal to the term about to be added to the new + ** leaf node (zTerm/nTerm). + ** + ** In other words, it must be the prefix of zTerm 1 byte longer than + ** the common prefix (if any) of zTerm and pWriter->zTerm. + */ + if( rc==SQLITE_OK ){ + rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1); + } + + /* Advance to the next output block */ + pLeaf->iBlock++; + pLeaf->key.n = 0; + pLeaf->block.n = 0; + + nSuffix = nTerm; + nSpace = 1; + nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; + nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; + } + + blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc); + + if( rc==SQLITE_OK ){ + if( pLeaf->block.n==0 ){ + pLeaf->block.n = 1; + pLeaf->block.a[0] = '\0'; + } + rc = fts3AppendToNode( + &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist + ); + } + + return rc; +} + +/* +** This function is called to release all dynamic resources held by the +** merge-writer object pWriter, and if no error has occurred, to flush +** all outstanding node buffers held by pWriter to disk. +** +** If *pRc is not SQLITE_OK when this function is called, then no attempt +** is made to write any data to disk. Instead, this function serves only +** to release outstanding resources. +** +** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while +** flushing buffers to disk, *pRc is set to an SQLite error code before +** returning. +*/ +static void fts3IncrmergeRelease( + Fts3Table *p, /* FTS3 table handle */ + IncrmergeWriter *pWriter, /* Merge-writer object */ + int *pRc /* IN/OUT: Error code */ +){ + int i; /* Used to iterate through non-root layers */ + int iRoot; /* Index of root in pWriter->aNodeWriter */ + NodeWriter *pRoot; /* NodeWriter for root node */ + int rc = *pRc; /* Error code */ + + /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment + ** root node. If the segment fits entirely on a single leaf node, iRoot + ** will be set to 0. If the root node is the parent of the leaves, iRoot + ** will be 1. And so on. */ + for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){ + NodeWriter *pNode = &pWriter->aNodeWriter[iRoot]; + if( pNode->block.n>0 ) break; + assert( *pRc || pNode->block.nAlloc==0 ); + assert( *pRc || pNode->key.nAlloc==0 ); + sqlite3_free(pNode->block.a); + sqlite3_free(pNode->key.a); + } + + /* Empty output segment. This is a no-op. */ + if( iRoot<0 ) return; + + /* The entire output segment fits on a single node. Normally, this means + ** the node would be stored as a blob in the "root" column of the %_segdir + ** table. However, this is not permitted in this case. The problem is that + ** space has already been reserved in the %_segments table, and so the + ** start_block and end_block fields of the %_segdir table must be populated. + ** And, by design or by accident, released versions of FTS cannot handle + ** segments that fit entirely on the root node with start_block!=0. + ** + ** Instead, create a synthetic root node that contains nothing but a + ** pointer to the single content node. So that the segment consists of a + ** single leaf and a single interior (root) node. + ** + ** Todo: Better might be to defer allocating space in the %_segments + ** table until we are sure it is needed. + */ + if( iRoot==0 ){ + Blob *pBlock = &pWriter->aNodeWriter[1].block; + blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc); + if( rc==SQLITE_OK ){ + pBlock->a[0] = 0x01; + pBlock->n = 1 + sqlite3Fts3PutVarint( + &pBlock->a[1], pWriter->aNodeWriter[0].iBlock + ); + } + iRoot = 1; + } + pRoot = &pWriter->aNodeWriter[iRoot]; + + /* Flush all currently outstanding nodes to disk. */ + for(i=0; iaNodeWriter[i]; + if( pNode->block.n>0 && rc==SQLITE_OK ){ + rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); + } + sqlite3_free(pNode->block.a); + sqlite3_free(pNode->key.a); + } + + /* Write the %_segdir record. */ + if( rc==SQLITE_OK ){ + rc = fts3WriteSegdir(p, + pWriter->iAbsLevel+1, /* level */ + pWriter->iIdx, /* idx */ + pWriter->iStart, /* start_block */ + pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */ + pWriter->iEnd, /* end_block */ + pRoot->block.a, pRoot->block.n /* root */ + ); + } + sqlite3_free(pRoot->block.a); + sqlite3_free(pRoot->key.a); + + *pRc = rc; +} + +/* +** Compare the term in buffer zLhs (size in bytes nLhs) with that in +** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of +** the other, it is considered to be smaller than the other. +** +** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve +** if it is greater. +*/ +static int fts3TermCmp( + const char *zLhs, int nLhs, /* LHS of comparison */ + const char *zRhs, int nRhs /* RHS of comparison */ +){ + int nCmp = MIN(nLhs, nRhs); + int res; + + res = memcmp(zLhs, zRhs, nCmp); + if( res==0 ) res = nLhs - nRhs; + + return res; +} + + +/* +** Query to see if the entry in the %_segments table with blockid iEnd is +** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before +** returning. Otherwise, set *pbRes to 0. +** +** Or, if an error occurs while querying the database, return an SQLite +** error code. The final value of *pbRes is undefined in this case. +** +** This is used to test if a segment is an "appendable" segment. If it +** is, then a NULL entry has been inserted into the %_segments table +** with blockid %_segdir.end_block. +*/ +static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){ + int bRes = 0; /* Result to set *pbRes to */ + sqlite3_stmt *pCheck = 0; /* Statement to query database with */ + int rc; /* Return code */ + + rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pCheck, 1, iEnd); + if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1; + rc = sqlite3_reset(pCheck); + } + + *pbRes = bRes; + return rc; +} + +/* +** This function is called when initializing an incremental-merge operation. +** It checks if the existing segment with index value iIdx at absolute level +** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the +** merge-writer object *pWriter is initialized to write to it. +** +** An existing segment can be appended to by an incremental merge if: +** +** * It was initially created as an appendable segment (with all required +** space pre-allocated), and +** +** * The first key read from the input (arguments zKey and nKey) is +** greater than the largest key currently stored in the potential +** output segment. +*/ +static int fts3IncrmergeLoad( + Fts3Table *p, /* Fts3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ + int iIdx, /* Index of candidate output segment */ + const char *zKey, /* First key to write */ + int nKey, /* Number of bytes in nKey */ + IncrmergeWriter *pWriter /* Populate this object */ +){ + int rc; /* Return code */ + sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */ + + rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0); + if( rc==SQLITE_OK ){ + sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */ + sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */ + sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */ + const char *aRoot = 0; /* Pointer to %_segdir.root buffer */ + int nRoot = 0; /* Size of aRoot[] in bytes */ + int rc2; /* Return code from sqlite3_reset() */ + int bAppendable = 0; /* Set to true if segment is appendable */ + + /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */ + sqlite3_bind_int64(pSelect, 1, iAbsLevel+1); + sqlite3_bind_int(pSelect, 2, iIdx); + if( sqlite3_step(pSelect)==SQLITE_ROW ){ + iStart = sqlite3_column_int64(pSelect, 1); + iLeafEnd = sqlite3_column_int64(pSelect, 2); + iEnd = sqlite3_column_int64(pSelect, 3); + nRoot = sqlite3_column_bytes(pSelect, 4); + aRoot = sqlite3_column_blob(pSelect, 4); + }else{ + return sqlite3_reset(pSelect); + } + + /* Check for the zero-length marker in the %_segments table */ + rc = fts3IsAppendable(p, iEnd, &bAppendable); + + /* Check that zKey/nKey is larger than the largest key the candidate */ + if( rc==SQLITE_OK && bAppendable ){ + char *aLeaf = 0; + int nLeaf = 0; + + rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0); + if( rc==SQLITE_OK ){ + NodeReader reader; + for(rc = nodeReaderInit(&reader, aLeaf, nLeaf); + rc==SQLITE_OK && reader.aNode; + rc = nodeReaderNext(&reader) + ){ + assert( reader.aNode ); + } + if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){ + bAppendable = 0; + } + nodeReaderRelease(&reader); + } + sqlite3_free(aLeaf); + } + + if( rc==SQLITE_OK && bAppendable ){ + /* It is possible to append to this segment. Set up the IncrmergeWriter + ** object to do so. */ + int i; + int nHeight = (int)aRoot[0]; + NodeWriter *pNode; + + pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT; + pWriter->iStart = iStart; + pWriter->iEnd = iEnd; + pWriter->iAbsLevel = iAbsLevel; + pWriter->iIdx = iIdx; + + for(i=nHeight+1; iaNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; + } + + pNode = &pWriter->aNodeWriter[nHeight]; + pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight; + blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc); + if( rc==SQLITE_OK ){ + memcpy(pNode->block.a, aRoot, nRoot); + pNode->block.n = nRoot; + } + + for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){ + NodeReader reader; + pNode = &pWriter->aNodeWriter[i]; + + rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n); + while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader); + blobGrowBuffer(&pNode->key, reader.term.n, &rc); + if( rc==SQLITE_OK ){ + memcpy(pNode->key.a, reader.term.a, reader.term.n); + pNode->key.n = reader.term.n; + if( i>0 ){ + char *aBlock = 0; + int nBlock = 0; + pNode = &pWriter->aNodeWriter[i-1]; + pNode->iBlock = reader.iChild; + rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0); + blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc); + if( rc==SQLITE_OK ){ + memcpy(pNode->block.a, aBlock, nBlock); + pNode->block.n = nBlock; + } + sqlite3_free(aBlock); + } + } + nodeReaderRelease(&reader); + } + } + + rc2 = sqlite3_reset(pSelect); + if( rc==SQLITE_OK ) rc = rc2; + } + + return rc; +} + +/* +** Determine the largest segment index value that exists within absolute +** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus +** one before returning SQLITE_OK. Or, if there are no segments at all +** within level iAbsLevel, set *piIdx to zero. +** +** If an error occurs, return an SQLite error code. The final value of +** *piIdx is undefined in this case. +*/ +static int fts3IncrmergeOutputIdx( + Fts3Table *p, /* FTS Table handle */ + sqlite3_int64 iAbsLevel, /* Absolute index of input segments */ + int *piIdx /* OUT: Next free index at iAbsLevel+1 */ +){ + int rc; + sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */ + + rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1); + sqlite3_step(pOutputIdx); + *piIdx = sqlite3_column_int(pOutputIdx, 0); + rc = sqlite3_reset(pOutputIdx); + } + + return rc; +} + +/* +** Allocate an appendable output segment on absolute level iAbsLevel+1 +** with idx value iIdx. +** +** In the %_segdir table, a segment is defined by the values in three +** columns: +** +** start_block +** leaves_end_block +** end_block +** +** When an appendable segment is allocated, it is estimated that the +** maximum number of leaf blocks that may be required is the sum of the +** number of leaf blocks consumed by the input segments, plus the number +** of input segments, multiplied by two. This value is stored in stack +** variable nLeafEst. +** +** A total of 16*nLeafEst blocks are allocated when an appendable segment +** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous +** array of leaf nodes starts at the first block allocated. The array +** of interior nodes that are parents of the leaf nodes start at block +** (start_block + (1 + end_block - start_block) / 16). And so on. +** +** In the actual code below, the value "16" is replaced with the +** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT. +*/ +static int fts3IncrmergeWriter( + Fts3Table *p, /* Fts3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ + int iIdx, /* Index of new output segment */ + Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */ + IncrmergeWriter *pWriter /* Populate this object */ +){ + int rc; /* Return Code */ + int i; /* Iterator variable */ + int nLeafEst = 0; /* Blocks allocated for leaf nodes */ + sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */ + sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */ + + /* Calculate nLeafEst. */ + rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pLeafEst, 1, iAbsLevel); + sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment); + if( SQLITE_ROW==sqlite3_step(pLeafEst) ){ + nLeafEst = sqlite3_column_int(pLeafEst, 0); + } + rc = sqlite3_reset(pLeafEst); + } + if( rc!=SQLITE_OK ) return rc; + + /* Calculate the first block to use in the output segment */ + rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0); + if( rc==SQLITE_OK ){ + if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){ + pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0); + pWriter->iEnd = pWriter->iStart - 1; + pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT; + } + rc = sqlite3_reset(pFirstBlock); + } + if( rc!=SQLITE_OK ) return rc; + + /* Insert the marker in the %_segments table to make sure nobody tries + ** to steal the space just allocated. This is also used to identify + ** appendable segments. */ + rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0); + if( rc!=SQLITE_OK ) return rc; + + pWriter->iAbsLevel = iAbsLevel; + pWriter->nLeafEst = nLeafEst; + pWriter->iIdx = iIdx; + + /* Set up the array of NodeWriter objects */ + for(i=0; iaNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; + } + return SQLITE_OK; +} + +/* +** Remove an entry from the %_segdir table. This involves running the +** following two statements: +** +** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx +** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx +** +** The DELETE statement removes the specific %_segdir level. The UPDATE +** statement ensures that the remaining segments have contiguously allocated +** idx values. +*/ +static int fts3RemoveSegdirEntry( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level to delete from */ + int iIdx /* Index of %_segdir entry to delete */ +){ + int rc; /* Return code */ + sqlite3_stmt *pDelete = 0; /* DELETE statement */ + + rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pDelete, 1, iAbsLevel); + sqlite3_bind_int(pDelete, 2, iIdx); + sqlite3_step(pDelete); + rc = sqlite3_reset(pDelete); + } + + return rc; +} + +/* +** One or more segments have just been removed from absolute level iAbsLevel. +** Update the 'idx' values of the remaining segments in the level so that +** the idx values are a contiguous sequence starting from 0. +*/ +static int fts3RepackSegdirLevel( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iAbsLevel /* Absolute level to repack */ +){ + int rc; /* Return code */ + int *aIdx = 0; /* Array of remaining idx values */ + int nIdx = 0; /* Valid entries in aIdx[] */ + int nAlloc = 0; /* Allocated size of aIdx[] */ + int i; /* Iterator variable */ + sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */ + sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */ + + rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0); + if( rc==SQLITE_OK ){ + int rc2; + sqlite3_bind_int64(pSelect, 1, iAbsLevel); + while( SQLITE_ROW==sqlite3_step(pSelect) ){ + if( nIdx>=nAlloc ){ + int *aNew; + nAlloc += 16; + aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int)); + if( !aNew ){ + rc = SQLITE_NOMEM; + break; + } + aIdx = aNew; + } + aIdx[nIdx++] = sqlite3_column_int(pSelect, 0); + } + rc2 = sqlite3_reset(pSelect); + if( rc==SQLITE_OK ) rc = rc2; + } + + if( rc==SQLITE_OK ){ + rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0); + } + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pUpdate, 2, iAbsLevel); + } + + assert( p->bIgnoreSavepoint==0 ); + p->bIgnoreSavepoint = 1; + for(i=0; rc==SQLITE_OK && ibIgnoreSavepoint = 0; + + sqlite3_free(aIdx); + return rc; +} + +static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){ + pNode->a[0] = (char)iHeight; + if( iChild ){ + assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) ); + pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild); + }else{ + assert( pNode->nAlloc>=1 ); + pNode->n = 1; + } +} + +/* +** The first two arguments are a pointer to and the size of a segment b-tree +** node. The node may be a leaf or an internal node. +** +** This function creates a new node image in blob object *pNew by copying +** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes) +** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode. +*/ +static int fts3TruncateNode( + const char *aNode, /* Current node image */ + int nNode, /* Size of aNode in bytes */ + Blob *pNew, /* OUT: Write new node image here */ + const char *zTerm, /* Omit all terms smaller than this */ + int nTerm, /* Size of zTerm in bytes */ + sqlite3_int64 *piBlock /* OUT: Block number in next layer down */ +){ + NodeReader reader; /* Reader object */ + Blob prev = {0, 0, 0}; /* Previous term written to new node */ + int rc = SQLITE_OK; /* Return code */ + int bLeaf = aNode[0]=='\0'; /* True for a leaf node */ + + /* Allocate required output space */ + blobGrowBuffer(pNew, nNode, &rc); + if( rc!=SQLITE_OK ) return rc; + pNew->n = 0; + + /* Populate new node buffer */ + for(rc = nodeReaderInit(&reader, aNode, nNode); + rc==SQLITE_OK && reader.aNode; + rc = nodeReaderNext(&reader) + ){ + if( pNew->n==0 ){ + int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm); + if( res<0 || (bLeaf==0 && res==0) ) continue; + fts3StartNode(pNew, (int)aNode[0], reader.iChild); + *piBlock = reader.iChild; + } + rc = fts3AppendToNode( + pNew, &prev, reader.term.a, reader.term.n, + reader.aDoclist, reader.nDoclist + ); + if( rc!=SQLITE_OK ) break; + } + if( pNew->n==0 ){ + fts3StartNode(pNew, (int)aNode[0], reader.iChild); + *piBlock = reader.iChild; + } + assert( pNew->n<=pNew->nAlloc ); + + nodeReaderRelease(&reader); + sqlite3_free(prev.a); + return rc; +} + +/* +** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute +** level iAbsLevel. This may involve deleting entries from the %_segments +** table, and modifying existing entries in both the %_segments and %_segdir +** tables. +** +** SQLITE_OK is returned if the segment is updated successfully. Or an +** SQLite error code otherwise. +*/ +static int fts3TruncateSegment( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */ + int iIdx, /* Index within level of segment to modify */ + const char *zTerm, /* Remove terms smaller than this */ + int nTerm /* Number of bytes in buffer zTerm */ +){ + int rc = SQLITE_OK; /* Return code */ + Blob root = {0,0,0}; /* New root page image */ + Blob block = {0,0,0}; /* Buffer used for any other block */ + sqlite3_int64 iBlock = 0; /* Block id */ + sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */ + sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */ + sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */ + + rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0); + if( rc==SQLITE_OK ){ + int rc2; /* sqlite3_reset() return code */ + sqlite3_bind_int64(pFetch, 1, iAbsLevel); + sqlite3_bind_int(pFetch, 2, iIdx); + if( SQLITE_ROW==sqlite3_step(pFetch) ){ + const char *aRoot = sqlite3_column_blob(pFetch, 4); + int nRoot = sqlite3_column_bytes(pFetch, 4); + iOldStart = sqlite3_column_int64(pFetch, 1); + rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock); + } + rc2 = sqlite3_reset(pFetch); + if( rc==SQLITE_OK ) rc = rc2; + } + + while( rc==SQLITE_OK && iBlock ){ + char *aBlock = 0; + int nBlock = 0; + iNewStart = iBlock; + + rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0); + if( rc==SQLITE_OK ){ + rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock); + } + if( rc==SQLITE_OK ){ + rc = fts3WriteSegment(p, iNewStart, block.a, block.n); + } + sqlite3_free(aBlock); + } + + /* Variable iNewStart now contains the first valid leaf node. */ + if( rc==SQLITE_OK && iNewStart ){ + sqlite3_stmt *pDel = 0; + rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pDel, 1, iOldStart); + sqlite3_bind_int64(pDel, 2, iNewStart-1); + sqlite3_step(pDel); + rc = sqlite3_reset(pDel); + } + } + + if( rc==SQLITE_OK ){ + sqlite3_stmt *pChomp = 0; + rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pChomp, 1, iNewStart); + sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC); + sqlite3_bind_int64(pChomp, 3, iAbsLevel); + sqlite3_bind_int(pChomp, 4, iIdx); + sqlite3_step(pChomp); + rc = sqlite3_reset(pChomp); + } + } + + sqlite3_free(root.a); + sqlite3_free(block.a); + return rc; +} + +/* +** This function is called after an incrmental-merge operation has run to +** merge (or partially merge) two or more segments from absolute level +** iAbsLevel. +** +** Each input segment is either removed from the db completely (if all of +** its data was copied to the output segment by the incrmerge operation) +** or modified in place so that it no longer contains those entries that +** have been duplicated in the output segment. +*/ +static int fts3IncrmergeChomp( + Fts3Table *p, /* FTS table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level containing segments */ + Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */ + int *pnRem /* Number of segments not deleted */ +){ + int i; + int nRem = 0; + int rc = SQLITE_OK; + + for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){ + Fts3SegReader *pSeg = 0; + int j; + + /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding + ** somewhere in the pCsr->apSegment[] array. */ + for(j=0; ALWAYS(jnSegment); j++){ + pSeg = pCsr->apSegment[j]; + if( pSeg->iIdx==i ) break; + } + assert( jnSegment && pSeg->iIdx==i ); + + if( pSeg->aNode==0 ){ + /* Seg-reader is at EOF. Remove the entire input segment. */ + rc = fts3DeleteSegment(p, pSeg); + if( rc==SQLITE_OK ){ + rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx); + } + *pnRem = 0; + }else{ + /* The incremental merge did not copy all the data from this + ** segment to the upper level. The segment is modified in place + ** so that it contains no keys smaller than zTerm/nTerm. */ + const char *zTerm = pSeg->zTerm; + int nTerm = pSeg->nTerm; + rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm); + nRem++; + } + } + + if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){ + rc = fts3RepackSegdirLevel(p, iAbsLevel); + } + + *pnRem = nRem; + return rc; +} + +/* +** Store an incr-merge hint in the database. +*/ +static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){ + sqlite3_stmt *pReplace = 0; + int rc; /* Return code */ + + rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT); + sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC); + sqlite3_step(pReplace); + rc = sqlite3_reset(pReplace); + } + + return rc; +} + +/* +** Load an incr-merge hint from the database. The incr-merge hint, if one +** exists, is stored in the rowid==1 row of the %_stat table. +** +** If successful, populate blob *pHint with the value read from the %_stat +** table and return SQLITE_OK. Otherwise, if an error occurs, return an +** SQLite error code. +*/ +static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){ + sqlite3_stmt *pSelect = 0; + int rc; + + pHint->n = 0; + rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0); + if( rc==SQLITE_OK ){ + int rc2; + sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT); + if( SQLITE_ROW==sqlite3_step(pSelect) ){ + const char *aHint = sqlite3_column_blob(pSelect, 0); + int nHint = sqlite3_column_bytes(pSelect, 0); + if( aHint ){ + blobGrowBuffer(pHint, nHint, &rc); + if( rc==SQLITE_OK ){ + memcpy(pHint->a, aHint, nHint); + pHint->n = nHint; + } + } + } + rc2 = sqlite3_reset(pSelect); + if( rc==SQLITE_OK ) rc = rc2; + } + + return rc; +} + +/* +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** Otherwise, append an entry to the hint stored in blob *pHint. Each entry +** consists of two varints, the absolute level number of the input segments +** and the number of input segments. +** +** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs, +** set *pRc to an SQLite error code before returning. +*/ +static void fts3IncrmergeHintPush( + Blob *pHint, /* Hint blob to append to */ + i64 iAbsLevel, /* First varint to store in hint */ + int nInput, /* Second varint to store in hint */ + int *pRc /* IN/OUT: Error code */ +){ + blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc); + if( *pRc==SQLITE_OK ){ + pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel); + pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput); + } +} + +/* +** Read the last entry (most recently pushed) from the hint blob *pHint +** and then remove the entry. Write the two values read to *piAbsLevel and +** *pnInput before returning. +** +** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does +** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB. +*/ +static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){ + const int nHint = pHint->n; + int i; + + i = pHint->n-2; + while( i>0 && (pHint->a[i-1] & 0x80) ) i--; + while( i>0 && (pHint->a[i-1] & 0x80) ) i--; + + pHint->n = i; + i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel); + i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput); + if( i!=nHint ) return SQLITE_CORRUPT_VTAB; + + return SQLITE_OK; +} + + +/* +** Attempt an incremental merge that writes nMerge leaf blocks. +** +** Incremental merges happen nMin segments at a time. The two +** segments to be merged are the nMin oldest segments (the ones with +** the smallest indexes) in the highest level that contains at least +** nMin segments. Multiple merges might occur in an attempt to write the +** quota of nMerge leaf blocks. +*/ +SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ + int rc; /* Return code */ + int nRem = nMerge; /* Number of leaf pages yet to be written */ + Fts3MultiSegReader *pCsr; /* Cursor used to read input data */ + Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */ + IncrmergeWriter *pWriter; /* Writer object */ + int nSeg = 0; /* Number of input segments */ + sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */ + Blob hint = {0, 0, 0}; /* Hint read from %_stat table */ + int bDirtyHint = 0; /* True if blob 'hint' has been modified */ + + /* Allocate space for the cursor, filter and writer objects */ + const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter); + pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc); + if( !pWriter ) return SQLITE_NOMEM; + pFilter = (Fts3SegFilter *)&pWriter[1]; + pCsr = (Fts3MultiSegReader *)&pFilter[1]; + + rc = fts3IncrmergeHintLoad(p, &hint); + while( rc==SQLITE_OK && nRem>0 ){ + const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex; + sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */ + int bUseHint = 0; /* True if attempting to append */ + + /* Search the %_segdir table for the absolute level with the smallest + ** relative level number that contains at least nMin segments, if any. + ** If one is found, set iAbsLevel to the absolute level number and + ** nSeg to nMin. If no level with at least nMin segments can be found, + ** set nSeg to -1. + */ + rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0); + sqlite3_bind_int(pFindLevel, 1, nMin); + if( sqlite3_step(pFindLevel)==SQLITE_ROW ){ + iAbsLevel = sqlite3_column_int64(pFindLevel, 0); + nSeg = nMin; + }else{ + nSeg = -1; + } + rc = sqlite3_reset(pFindLevel); + + /* If the hint read from the %_stat table is not empty, check if the + ** last entry in it specifies a relative level smaller than or equal + ** to the level identified by the block above (if any). If so, this + ** iteration of the loop will work on merging at the hinted level. + */ + if( rc==SQLITE_OK && hint.n ){ + int nHint = hint.n; + sqlite3_int64 iHintAbsLevel = 0; /* Hint level */ + int nHintSeg = 0; /* Hint number of segments */ + + rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg); + if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){ + iAbsLevel = iHintAbsLevel; + nSeg = nHintSeg; + bUseHint = 1; + bDirtyHint = 1; + }else{ + /* This undoes the effect of the HintPop() above - so that no entry + ** is removed from the hint blob. */ + hint.n = nHint; + } + } + + /* If nSeg is less that zero, then there is no level with at least + ** nMin segments and no hint in the %_stat table. No work to do. + ** Exit early in this case. */ + if( nSeg<0 ) break; + + /* Open a cursor to iterate through the contents of the oldest nSeg + ** indexes of absolute level iAbsLevel. If this cursor is opened using + ** the 'hint' parameters, it is possible that there are less than nSeg + ** segments available in level iAbsLevel. In this case, no work is + ** done on iAbsLevel - fall through to the next iteration of the loop + ** to start work on some other level. */ + memset(pWriter, 0, nAlloc); + pFilter->flags = FTS3_SEGMENT_REQUIRE_POS; + if( rc==SQLITE_OK ){ + rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr); + } + if( SQLITE_OK==rc && pCsr->nSegment==nSeg + && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter)) + && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr)) + ){ + int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */ + rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx); + if( rc==SQLITE_OK ){ + if( bUseHint && iIdx>0 ){ + const char *zKey = pCsr->zTerm; + int nKey = pCsr->nTerm; + rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter); + }else{ + rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter); + } + } + + if( rc==SQLITE_OK && pWriter->nLeafEst ){ + fts3LogMerge(nSeg, iAbsLevel); + do { + rc = fts3IncrmergeAppend(p, pWriter, pCsr); + if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr); + if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK; + }while( rc==SQLITE_ROW ); + + /* Update or delete the input segments */ + if( rc==SQLITE_OK ){ + nRem -= (1 + pWriter->nWork); + rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg); + if( nSeg!=0 ){ + bDirtyHint = 1; + fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc); + } + } + } + + fts3IncrmergeRelease(p, pWriter, &rc); + } + + sqlite3Fts3SegReaderFinish(pCsr); + } + + /* Write the hint values into the %_stat table for the next incr-merger */ + if( bDirtyHint && rc==SQLITE_OK ){ + rc = fts3IncrmergeHintStore(p, &hint); + } + + sqlite3_free(pWriter); + sqlite3_free(hint.a); + return rc; +} + +/* +** Convert the text beginning at *pz into an integer and return +** its value. Advance *pz to point to the first character past +** the integer. +*/ +static int fts3Getint(const char **pz){ + const char *z = *pz; + int i = 0; + while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0'; + *pz = z; + return i; +} + +/* +** Process statements of the form: +** +** INSERT INTO table(table) VALUES('merge=A,B'); +** +** A and B are integers that decode to be the number of leaf pages +** written for the merge, and the minimum number of segments on a level +** before it will be selected for a merge, respectively. +*/ +static int fts3DoIncrmerge( + Fts3Table *p, /* FTS3 table handle */ + const char *zParam /* Nul-terminated string containing "A,B" */ +){ + int rc; + int nMin = (FTS3_MERGE_COUNT / 2); + int nMerge = 0; + const char *z = zParam; + + /* Read the first integer value */ + nMerge = fts3Getint(&z); + + /* If the first integer value is followed by a ',', read the second + ** integer value. */ + if( z[0]==',' && z[1]!='\0' ){ + z++; + nMin = fts3Getint(&z); + } + + if( z[0]!='\0' || nMin<2 ){ + rc = SQLITE_ERROR; + }else{ + rc = SQLITE_OK; + if( !p->bHasStat ){ + assert( p->bFts4==0 ); + sqlite3Fts3CreateStatTable(&rc, p); + } + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3Incrmerge(p, nMerge, nMin); + } + sqlite3Fts3SegmentsClose(p); + } + return rc; +} + +/* +** Process statements of the form: +** +** INSERT INTO table(table) VALUES('automerge=X'); +** +** where X is an integer. X==0 means to turn automerge off. X!=0 means +** turn it on. The setting is persistent. +*/ +static int fts3DoAutoincrmerge( + Fts3Table *p, /* FTS3 table handle */ + const char *zParam /* Nul-terminated string containing boolean */ +){ + int rc = SQLITE_OK; + sqlite3_stmt *pStmt = 0; + p->bAutoincrmerge = fts3Getint(&zParam)!=0; + if( !p->bHasStat ){ + assert( p->bFts4==0 ); + sqlite3Fts3CreateStatTable(&rc, p); + if( rc ) return rc; + } + rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); + if( rc ) return rc; + sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); + sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge); + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + return rc; +} + +/* +** Return a 64-bit checksum for the FTS index entry specified by the +** arguments to this function. +*/ +static u64 fts3ChecksumEntry( + const char *zTerm, /* Pointer to buffer containing term */ + int nTerm, /* Size of zTerm in bytes */ + int iLangid, /* Language id for current row */ + int iIndex, /* Index (0..Fts3Table.nIndex-1) */ + i64 iDocid, /* Docid for current row. */ + int iCol, /* Column number */ + int iPos /* Position */ +){ + int i; + u64 ret = (u64)iDocid; + + ret += (ret<<3) + iLangid; + ret += (ret<<3) + iIndex; + ret += (ret<<3) + iCol; + ret += (ret<<3) + iPos; + for(i=0; inIndex-1) */ + int *pRc /* OUT: Return code */ +){ + Fts3SegFilter filter; + Fts3MultiSegReader csr; + int rc; + u64 cksum = 0; + + assert( *pRc==SQLITE_OK ); + + memset(&filter, 0, sizeof(filter)); + memset(&csr, 0, sizeof(csr)); + filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; + filter.flags |= FTS3_SEGMENT_SCAN; + + rc = sqlite3Fts3SegReaderCursor( + p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr + ); + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3SegReaderStart(p, &csr, &filter); + } + + if( rc==SQLITE_OK ){ + while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){ + char *pCsr = csr.aDoclist; + char *pEnd = &pCsr[csr.nDoclist]; + + i64 iDocid = 0; + i64 iCol = 0; + i64 iPos = 0; + + pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid); + while( pCsrnIndex); + while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){ + int iLangid = sqlite3_column_int(pAllLangid, 0); + int i; + for(i=0; inIndex; i++){ + cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc); + } + } + rc2 = sqlite3_reset(pAllLangid); + if( rc==SQLITE_OK ) rc = rc2; + } + + /* This block calculates the checksum according to the %_content table */ + rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); + if( rc==SQLITE_OK ){ + sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule; + sqlite3_stmt *pStmt = 0; + char *zSql; + + zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); + if( !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + } + + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ + i64 iDocid = sqlite3_column_int64(pStmt, 0); + int iLang = langidFromSelect(p, pStmt); + int iCol; + + for(iCol=0; rc==SQLITE_OK && iColnColumn; iCol++){ + const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1); + int nText = sqlite3_column_bytes(pStmt, iCol+1); + sqlite3_tokenizer_cursor *pT = 0; + + rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT); + while( rc==SQLITE_OK ){ + char const *zToken; /* Buffer containing token */ + int nToken = 0; /* Number of bytes in token */ + int iDum1 = 0, iDum2 = 0; /* Dummy variables */ + int iPos = 0; /* Position of token in zText */ + + rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos); + if( rc==SQLITE_OK ){ + int i; + cksum2 = cksum2 ^ fts3ChecksumEntry( + zToken, nToken, iLang, 0, iDocid, iCol, iPos + ); + for(i=1; inIndex; i++){ + if( p->aIndex[i].nPrefix<=nToken ){ + cksum2 = cksum2 ^ fts3ChecksumEntry( + zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos + ); + } + } + } + } + if( pT ) pModule->xClose(pT); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + } + } + + sqlite3_finalize(pStmt); + } + + *pbOk = (cksum1==cksum2); + return rc; +} + +/* +** Run the integrity-check. If no error occurs and the current contents of +** the FTS index are correct, return SQLITE_OK. Or, if the contents of the +** FTS index are incorrect, return SQLITE_CORRUPT_VTAB. +** +** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite +** error code. +** +** The integrity-check works as follows. For each token and indexed token +** prefix in the document set, a 64-bit checksum is calculated (by code +** in fts3ChecksumEntry()) based on the following: +** +** + The index number (0 for the main index, 1 for the first prefix +** index etc.), +** + The token (or token prefix) text itself, +** + The language-id of the row it appears in, +** + The docid of the row it appears in, +** + The column it appears in, and +** + The tokens position within that column. +** +** The checksums for all entries in the index are XORed together to create +** a single checksum for the entire index. +** +** The integrity-check code calculates the same checksum in two ways: +** +** 1. By scanning the contents of the FTS index, and +** 2. By scanning and tokenizing the content table. +** +** If the two checksums are identical, the integrity-check is deemed to have +** passed. +*/ +static int fts3DoIntegrityCheck( + Fts3Table *p /* FTS3 table handle */ +){ + int rc; + int bOk = 0; + rc = fts3IntegrityCheck(p, &bOk); + if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB; + return rc; +} + +/* +** Handle a 'special' INSERT of the form: +** +** "INSERT INTO tbl(tbl) VALUES()" +** +** Argument pVal contains the result of . Currently the only +** meaningful value to insert is the text 'optimize'. +*/ +static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){ + int rc; /* Return Code */ + const char *zVal = (const char *)sqlite3_value_text(pVal); + int nVal = sqlite3_value_bytes(pVal); + + if( !zVal ){ + return SQLITE_NOMEM; + }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){ + rc = fts3DoOptimize(p, 0); + }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){ + rc = fts3DoRebuild(p); + }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){ + rc = fts3DoIntegrityCheck(p); + }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){ + rc = fts3DoIncrmerge(p, &zVal[6]); + }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){ + rc = fts3DoAutoincrmerge(p, &zVal[10]); +#ifdef SQLITE_TEST + }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){ + p->nNodeSize = atoi(&zVal[9]); + rc = SQLITE_OK; + }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ + p->nMaxPendingData = atoi(&zVal[11]); + rc = SQLITE_OK; + }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){ + p->bNoIncrDoclist = atoi(&zVal[21]); + rc = SQLITE_OK; +#endif + }else{ + rc = SQLITE_ERROR; + } + + return rc; +} + +#ifndef SQLITE_DISABLE_FTS4_DEFERRED +/* +** Delete all cached deferred doclists. Deferred doclists are cached +** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function. +*/ +SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){ + Fts3DeferredToken *pDef; + for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){ + fts3PendingListDelete(pDef->pList); + pDef->pList = 0; + } +} + +/* +** Free all entries in the pCsr->pDeffered list. Entries are added to +** this list using sqlite3Fts3DeferToken(). +*/ +SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){ + Fts3DeferredToken *pDef; + Fts3DeferredToken *pNext; + for(pDef=pCsr->pDeferred; pDef; pDef=pNext){ + pNext = pDef->pNext; + fts3PendingListDelete(pDef->pList); + sqlite3_free(pDef); + } + pCsr->pDeferred = 0; +} + +/* +** Generate deferred-doclists for all tokens in the pCsr->pDeferred list +** based on the row that pCsr currently points to. +** +** A deferred-doclist is like any other doclist with position information +** included, except that it only contains entries for a single row of the +** table, not for all rows. +*/ +SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){ + int rc = SQLITE_OK; /* Return code */ + if( pCsr->pDeferred ){ + int i; /* Used to iterate through table columns */ + sqlite3_int64 iDocid; /* Docid of the row pCsr points to */ + Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */ + + Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; + sqlite3_tokenizer *pT = p->pTokenizer; + sqlite3_tokenizer_module const *pModule = pT->pModule; + + assert( pCsr->isRequireSeek==0 ); + iDocid = sqlite3_column_int64(pCsr->pStmt, 0); + + for(i=0; inColumn && rc==SQLITE_OK; i++){ + if( p->abNotindexed[i]==0 ){ + const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1); + sqlite3_tokenizer_cursor *pTC = 0; + + rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC); + while( rc==SQLITE_OK ){ + char const *zToken; /* Buffer containing token */ + int nToken = 0; /* Number of bytes in token */ + int iDum1 = 0, iDum2 = 0; /* Dummy variables */ + int iPos = 0; /* Position of token in zText */ + + rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos); + for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ + Fts3PhraseToken *pPT = pDef->pToken; + if( (pDef->iCol>=p->nColumn || pDef->iCol==i) + && (pPT->bFirst==0 || iPos==0) + && (pPT->n==nToken || (pPT->isPrefix && pPT->nz, pPT->n)) + ){ + fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc); + } + } + } + if( pTC ) pModule->xClose(pTC); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + } + } + + for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ + if( pDef->pList ){ + rc = fts3PendingListAppendVarint(&pDef->pList, 0); + } + } + } + + return rc; +} + +SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList( + Fts3DeferredToken *p, + char **ppData, + int *pnData +){ + char *pRet; + int nSkip; + sqlite3_int64 dummy; + + *ppData = 0; + *pnData = 0; + + if( p->pList==0 ){ + return SQLITE_OK; + } + + pRet = (char *)sqlite3_malloc(p->pList->nData); + if( !pRet ) return SQLITE_NOMEM; + + nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy); + *pnData = p->pList->nData - nSkip; + *ppData = pRet; + + memcpy(pRet, &p->pList->aData[nSkip], *pnData); + return SQLITE_OK; +} + +/* +** Add an entry for token pToken to the pCsr->pDeferred list. +*/ +SQLITE_PRIVATE int sqlite3Fts3DeferToken( + Fts3Cursor *pCsr, /* Fts3 table cursor */ + Fts3PhraseToken *pToken, /* Token to defer */ + int iCol /* Column that token must appear in (or -1) */ +){ + Fts3DeferredToken *pDeferred; + pDeferred = sqlite3_malloc(sizeof(*pDeferred)); + if( !pDeferred ){ + return SQLITE_NOMEM; + } + memset(pDeferred, 0, sizeof(*pDeferred)); + pDeferred->pToken = pToken; + pDeferred->pNext = pCsr->pDeferred; + pDeferred->iCol = iCol; + pCsr->pDeferred = pDeferred; + + assert( pToken->pDeferred==0 ); + pToken->pDeferred = pDeferred; + + return SQLITE_OK; +} +#endif + +/* +** SQLite value pRowid contains the rowid of a row that may or may not be +** present in the FTS3 table. If it is, delete it and adjust the contents +** of subsiduary data structures accordingly. +*/ +static int fts3DeleteByRowid( + Fts3Table *p, + sqlite3_value *pRowid, + int *pnChng, /* IN/OUT: Decrement if row is deleted */ + u32 *aSzDel +){ + int rc = SQLITE_OK; /* Return code */ + int bFound = 0; /* True if *pRowid really is in the table */ + + fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound); + if( bFound && rc==SQLITE_OK ){ + int isEmpty = 0; /* Deleting *pRowid leaves the table empty */ + rc = fts3IsEmpty(p, pRowid, &isEmpty); + if( rc==SQLITE_OK ){ + if( isEmpty ){ + /* Deleting this row means the whole table is empty. In this case + ** delete the contents of all three tables and throw away any + ** data in the pendingTerms hash table. */ + rc = fts3DeleteAll(p, 1); + *pnChng = 0; + memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2); + }else{ + *pnChng = *pnChng - 1; + if( p->zContentTbl==0 ){ + fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid); + } + if( p->bHasDocsize ){ + fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid); + } + } + } + } + + return rc; +} + +/* +** This function does the work for the xUpdate method of FTS3 virtual +** tables. The schema of the virtual table being: +** +** CREATE TABLE
( +** , +**
HIDDEN, +** docid HIDDEN, +** HIDDEN +** ); +** +** +*/ +SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( + sqlite3_vtab *pVtab, /* FTS3 vtab object */ + int nArg, /* Size of argument array */ + sqlite3_value **apVal, /* Array of arguments */ + sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ +){ + Fts3Table *p = (Fts3Table *)pVtab; + int rc = SQLITE_OK; /* Return Code */ + int isRemove = 0; /* True for an UPDATE or DELETE */ + u32 *aSzIns = 0; /* Sizes of inserted documents */ + u32 *aSzDel = 0; /* Sizes of deleted documents */ + int nChng = 0; /* Net change in number of documents */ + int bInsertDone = 0; + + assert( p->pSegments==0 ); + assert( + nArg==1 /* DELETE operations */ + || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */ + ); + + /* Check for a "special" INSERT operation. One of the form: + ** + ** INSERT INTO xyz(xyz) VALUES('command'); + */ + if( nArg>1 + && sqlite3_value_type(apVal[0])==SQLITE_NULL + && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL + ){ + rc = fts3SpecialInsert(p, apVal[p->nColumn+2]); + goto update_out; + } + + if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){ + rc = SQLITE_CONSTRAINT; + goto update_out; + } + + /* Allocate space to hold the change in document sizes */ + aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 ); + if( aSzDel==0 ){ + rc = SQLITE_NOMEM; + goto update_out; + } + aSzIns = &aSzDel[p->nColumn+1]; + memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2); + + rc = fts3Writelock(p); + if( rc!=SQLITE_OK ) goto update_out; + + /* If this is an INSERT operation, or an UPDATE that modifies the rowid + ** value, then this operation requires constraint handling. + ** + ** If the on-conflict mode is REPLACE, this means that the existing row + ** should be deleted from the database before inserting the new row. Or, + ** if the on-conflict mode is other than REPLACE, then this method must + ** detect the conflict and return SQLITE_CONSTRAINT before beginning to + ** modify the database file. + */ + if( nArg>1 && p->zContentTbl==0 ){ + /* Find the value object that holds the new rowid value. */ + sqlite3_value *pNewRowid = apVal[3+p->nColumn]; + if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){ + pNewRowid = apVal[1]; + } + + if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( + sqlite3_value_type(apVal[0])==SQLITE_NULL + || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid) + )){ + /* The new rowid is not NULL (in this case the rowid will be + ** automatically assigned and there is no chance of a conflict), and + ** the statement is either an INSERT or an UPDATE that modifies the + ** rowid column. So if the conflict mode is REPLACE, then delete any + ** existing row with rowid=pNewRowid. + ** + ** Or, if the conflict mode is not REPLACE, insert the new record into + ** the %_content table. If we hit the duplicate rowid constraint (or any + ** other error) while doing so, return immediately. + ** + ** This branch may also run if pNewRowid contains a value that cannot + ** be losslessly converted to an integer. In this case, the eventual + ** call to fts3InsertData() (either just below or further on in this + ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is + ** invoked, it will delete zero rows (since no row will have + ** docid=$pNewRowid if $pNewRowid is not an integer value). + */ + if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){ + rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel); + }else{ + rc = fts3InsertData(p, apVal, pRowid); + bInsertDone = 1; + } + } + } + if( rc!=SQLITE_OK ){ + goto update_out; + } + + /* If this is a DELETE or UPDATE operation, remove the old record. */ + if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ + assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER ); + rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel); + isRemove = 1; + } + + /* If this is an INSERT or UPDATE operation, insert the new record. */ + if( nArg>1 && rc==SQLITE_OK ){ + int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]); + if( bInsertDone==0 ){ + rc = fts3InsertData(p, apVal, pRowid); + if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){ + rc = FTS_CORRUPT_VTAB; + } + } + if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){ + rc = fts3PendingTermsDocid(p, iLangid, *pRowid); + } + if( rc==SQLITE_OK ){ + assert( p->iPrevDocid==*pRowid ); + rc = fts3InsertTerms(p, iLangid, apVal, aSzIns); + } + if( p->bHasDocsize ){ + fts3InsertDocsize(&rc, p, aSzIns); + } + nChng++; + } + + if( p->bFts4 ){ + fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng); + } + + update_out: + sqlite3_free(aSzDel); + sqlite3Fts3SegmentsClose(p); + return rc; +} + +/* +** Flush any data in the pending-terms hash table to disk. If successful, +** merge all segments in the database (including the new segment, if +** there was any data to flush) into a single segment. +*/ +SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){ + int rc; + rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0); + if( rc==SQLITE_OK ){ + rc = fts3DoOptimize(p, 1); + if( rc==SQLITE_OK || rc==SQLITE_DONE ){ + int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); + if( rc2!=SQLITE_OK ) rc = rc2; + }else{ + sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0); + sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); + } + } + sqlite3Fts3SegmentsClose(p); + return rc; +} + +#endif + +/************** End of fts3_write.c ******************************************/ +/************** Begin file fts3_snippet.c ************************************/ +/* +** 2009 Oct 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* #include */ +/* #include */ + +/* +** Characters that may appear in the second argument to matchinfo(). +*/ +#define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */ +#define FTS3_MATCHINFO_NCOL 'c' /* 1 value */ +#define FTS3_MATCHINFO_NDOC 'n' /* 1 value */ +#define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */ +#define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */ +#define FTS3_MATCHINFO_LCS 's' /* nCol values */ +#define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */ + +/* +** The default value for the second argument to matchinfo(). +*/ +#define FTS3_MATCHINFO_DEFAULT "pcx" + + +/* +** Used as an fts3ExprIterate() context when loading phrase doclists to +** Fts3Expr.aDoclist[]/nDoclist. +*/ +typedef struct LoadDoclistCtx LoadDoclistCtx; +struct LoadDoclistCtx { + Fts3Cursor *pCsr; /* FTS3 Cursor */ + int nPhrase; /* Number of phrases seen so far */ + int nToken; /* Number of tokens seen so far */ +}; + +/* +** The following types are used as part of the implementation of the +** fts3BestSnippet() routine. +*/ +typedef struct SnippetIter SnippetIter; +typedef struct SnippetPhrase SnippetPhrase; +typedef struct SnippetFragment SnippetFragment; + +struct SnippetIter { + Fts3Cursor *pCsr; /* Cursor snippet is being generated from */ + int iCol; /* Extract snippet from this column */ + int nSnippet; /* Requested snippet length (in tokens) */ + int nPhrase; /* Number of phrases in query */ + SnippetPhrase *aPhrase; /* Array of size nPhrase */ + int iCurrent; /* First token of current snippet */ +}; + +struct SnippetPhrase { + int nToken; /* Number of tokens in phrase */ + char *pList; /* Pointer to start of phrase position list */ + int iHead; /* Next value in position list */ + char *pHead; /* Position list data following iHead */ + int iTail; /* Next value in trailing position list */ + char *pTail; /* Position list data following iTail */ +}; + +struct SnippetFragment { + int iCol; /* Column snippet is extracted from */ + int iPos; /* Index of first token in snippet */ + u64 covered; /* Mask of query phrases covered */ + u64 hlmask; /* Mask of snippet terms to highlight */ +}; + +/* +** This type is used as an fts3ExprIterate() context object while +** accumulating the data returned by the matchinfo() function. +*/ +typedef struct MatchInfo MatchInfo; +struct MatchInfo { + Fts3Cursor *pCursor; /* FTS3 Cursor */ + int nCol; /* Number of columns in table */ + int nPhrase; /* Number of matchable phrases in query */ + sqlite3_int64 nDoc; /* Number of docs in database */ + u32 *aMatchinfo; /* Pre-allocated buffer */ +}; + + + +/* +** The snippet() and offsets() functions both return text values. An instance +** of the following structure is used to accumulate those values while the +** functions are running. See fts3StringAppend() for details. +*/ +typedef struct StrBuffer StrBuffer; +struct StrBuffer { + char *z; /* Pointer to buffer containing string */ + int n; /* Length of z in bytes (excl. nul-term) */ + int nAlloc; /* Allocated size of buffer z in bytes */ +}; + + +/* +** This function is used to help iterate through a position-list. A position +** list is a list of unique integers, sorted from smallest to largest. Each +** element of the list is represented by an FTS3 varint that takes the value +** of the difference between the current element and the previous one plus +** two. For example, to store the position-list: +** +** 4 9 113 +** +** the three varints: +** +** 6 7 106 +** +** are encoded. +** +** When this function is called, *pp points to the start of an element of +** the list. *piPos contains the value of the previous entry in the list. +** After it returns, *piPos contains the value of the next element of the +** list and *pp is advanced to the following varint. +*/ +static void fts3GetDeltaPosition(char **pp, int *piPos){ + int iVal; + *pp += sqlite3Fts3GetVarint32(*pp, &iVal); + *piPos += (iVal-2); +} + +/* +** Helper function for fts3ExprIterate() (see below). +*/ +static int fts3ExprIterate2( + Fts3Expr *pExpr, /* Expression to iterate phrases of */ + int *piPhrase, /* Pointer to phrase counter */ + int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ + void *pCtx /* Second argument to pass to callback */ +){ + int rc; /* Return code */ + int eType = pExpr->eType; /* Type of expression node pExpr */ + + if( eType!=FTSQUERY_PHRASE ){ + assert( pExpr->pLeft && pExpr->pRight ); + rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx); + if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){ + rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx); + } + }else{ + rc = x(pExpr, *piPhrase, pCtx); + (*piPhrase)++; + } + return rc; +} + +/* +** Iterate through all phrase nodes in an FTS3 query, except those that +** are part of a sub-tree that is the right-hand-side of a NOT operator. +** For each phrase node found, the supplied callback function is invoked. +** +** If the callback function returns anything other than SQLITE_OK, +** the iteration is abandoned and the error code returned immediately. +** Otherwise, SQLITE_OK is returned after a callback has been made for +** all eligible phrase nodes. +*/ +static int fts3ExprIterate( + Fts3Expr *pExpr, /* Expression to iterate phrases of */ + int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ + void *pCtx /* Second argument to pass to callback */ +){ + int iPhrase = 0; /* Variable used as the phrase counter */ + return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx); +} + +/* +** This is an fts3ExprIterate() callback used while loading the doclists +** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also +** fts3ExprLoadDoclists(). +*/ +static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ + int rc = SQLITE_OK; + Fts3Phrase *pPhrase = pExpr->pPhrase; + LoadDoclistCtx *p = (LoadDoclistCtx *)ctx; + + UNUSED_PARAMETER(iPhrase); + + p->nPhrase++; + p->nToken += pPhrase->nToken; + + return rc; +} + +/* +** Load the doclists for each phrase in the query associated with FTS3 cursor +** pCsr. +** +** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable +** phrases in the expression (all phrases except those directly or +** indirectly descended from the right-hand-side of a NOT operator). If +** pnToken is not NULL, then it is set to the number of tokens in all +** matchable phrases of the expression. +*/ +static int fts3ExprLoadDoclists( + Fts3Cursor *pCsr, /* Fts3 cursor for current query */ + int *pnPhrase, /* OUT: Number of phrases in query */ + int *pnToken /* OUT: Number of tokens in query */ +){ + int rc; /* Return Code */ + LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */ + sCtx.pCsr = pCsr; + rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx); + if( pnPhrase ) *pnPhrase = sCtx.nPhrase; + if( pnToken ) *pnToken = sCtx.nToken; + return rc; +} + +static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ + (*(int *)ctx)++; + UNUSED_PARAMETER(pExpr); + UNUSED_PARAMETER(iPhrase); + return SQLITE_OK; +} +static int fts3ExprPhraseCount(Fts3Expr *pExpr){ + int nPhrase = 0; + (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase); + return nPhrase; +} + +/* +** Advance the position list iterator specified by the first two +** arguments so that it points to the first element with a value greater +** than or equal to parameter iNext. +*/ +static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){ + char *pIter = *ppIter; + if( pIter ){ + int iIter = *piIter; + + while( iIteriCurrent<0 ){ + /* The SnippetIter object has just been initialized. The first snippet + ** candidate always starts at offset 0 (even if this candidate has a + ** score of 0.0). + */ + pIter->iCurrent = 0; + + /* Advance the 'head' iterator of each phrase to the first offset that + ** is greater than or equal to (iNext+nSnippet). + */ + for(i=0; inPhrase; i++){ + SnippetPhrase *pPhrase = &pIter->aPhrase[i]; + fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet); + } + }else{ + int iStart; + int iEnd = 0x7FFFFFFF; + + for(i=0; inPhrase; i++){ + SnippetPhrase *pPhrase = &pIter->aPhrase[i]; + if( pPhrase->pHead && pPhrase->iHeadiHead; + } + } + if( iEnd==0x7FFFFFFF ){ + return 1; + } + + pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1; + for(i=0; inPhrase; i++){ + SnippetPhrase *pPhrase = &pIter->aPhrase[i]; + fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1); + fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart); + } + } + + return 0; +} + +/* +** Retrieve information about the current candidate snippet of snippet +** iterator pIter. +*/ +static void fts3SnippetDetails( + SnippetIter *pIter, /* Snippet iterator */ + u64 mCovered, /* Bitmask of phrases already covered */ + int *piToken, /* OUT: First token of proposed snippet */ + int *piScore, /* OUT: "Score" for this snippet */ + u64 *pmCover, /* OUT: Bitmask of phrases covered */ + u64 *pmHighlight /* OUT: Bitmask of terms to highlight */ +){ + int iStart = pIter->iCurrent; /* First token of snippet */ + int iScore = 0; /* Score of this snippet */ + int i; /* Loop counter */ + u64 mCover = 0; /* Mask of phrases covered by this snippet */ + u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */ + + for(i=0; inPhrase; i++){ + SnippetPhrase *pPhrase = &pIter->aPhrase[i]; + if( pPhrase->pTail ){ + char *pCsr = pPhrase->pTail; + int iCsr = pPhrase->iTail; + + while( iCsr<(iStart+pIter->nSnippet) ){ + int j; + u64 mPhrase = (u64)1 << i; + u64 mPos = (u64)1 << (iCsr - iStart); + assert( iCsr>=iStart ); + if( (mCover|mCovered)&mPhrase ){ + iScore++; + }else{ + iScore += 1000; + } + mCover |= mPhrase; + + for(j=0; jnToken; j++){ + mHighlight |= (mPos>>j); + } + + if( 0==(*pCsr & 0x0FE) ) break; + fts3GetDeltaPosition(&pCsr, &iCsr); + } + } + } + + /* Set the output variables before returning. */ + *piToken = iStart; + *piScore = iScore; + *pmCover = mCover; + *pmHighlight = mHighlight; +} + +/* +** This function is an fts3ExprIterate() callback used by fts3BestSnippet(). +** Each invocation populates an element of the SnippetIter.aPhrase[] array. +*/ +static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){ + SnippetIter *p = (SnippetIter *)ctx; + SnippetPhrase *pPhrase = &p->aPhrase[iPhrase]; + char *pCsr; + int rc; + + pPhrase->nToken = pExpr->pPhrase->nToken; + rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr); + assert( rc==SQLITE_OK || pCsr==0 ); + if( pCsr ){ + int iFirst = 0; + pPhrase->pList = pCsr; + fts3GetDeltaPosition(&pCsr, &iFirst); + assert( iFirst>=0 ); + pPhrase->pHead = pCsr; + pPhrase->pTail = pCsr; + pPhrase->iHead = iFirst; + pPhrase->iTail = iFirst; + }else{ + assert( rc!=SQLITE_OK || ( + pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 + )); + } + + return rc; +} + +/* +** Select the fragment of text consisting of nFragment contiguous tokens +** from column iCol that represent the "best" snippet. The best snippet +** is the snippet with the highest score, where scores are calculated +** by adding: +** +** (a) +1 point for each occurrence of a matchable phrase in the snippet. +** +** (b) +1000 points for the first occurrence of each matchable phrase in +** the snippet for which the corresponding mCovered bit is not set. +** +** The selected snippet parameters are stored in structure *pFragment before +** returning. The score of the selected snippet is stored in *piScore +** before returning. +*/ +static int fts3BestSnippet( + int nSnippet, /* Desired snippet length */ + Fts3Cursor *pCsr, /* Cursor to create snippet for */ + int iCol, /* Index of column to create snippet from */ + u64 mCovered, /* Mask of phrases already covered */ + u64 *pmSeen, /* IN/OUT: Mask of phrases seen */ + SnippetFragment *pFragment, /* OUT: Best snippet found */ + int *piScore /* OUT: Score of snippet pFragment */ +){ + int rc; /* Return Code */ + int nList; /* Number of phrases in expression */ + SnippetIter sIter; /* Iterates through snippet candidates */ + int nByte; /* Number of bytes of space to allocate */ + int iBestScore = -1; /* Best snippet score found so far */ + int i; /* Loop counter */ + + memset(&sIter, 0, sizeof(sIter)); + + /* Iterate through the phrases in the expression to count them. The same + ** callback makes sure the doclists are loaded for each phrase. + */ + rc = fts3ExprLoadDoclists(pCsr, &nList, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Now that it is known how many phrases there are, allocate and zero + ** the required space using malloc(). + */ + nByte = sizeof(SnippetPhrase) * nList; + sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte); + if( !sIter.aPhrase ){ + return SQLITE_NOMEM; + } + memset(sIter.aPhrase, 0, nByte); + + /* Initialize the contents of the SnippetIter object. Then iterate through + ** the set of phrases in the expression to populate the aPhrase[] array. + */ + sIter.pCsr = pCsr; + sIter.iCol = iCol; + sIter.nSnippet = nSnippet; + sIter.nPhrase = nList; + sIter.iCurrent = -1; + (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter); + + /* Set the *pmSeen output variable. */ + for(i=0; iiCol = iCol; + while( !fts3SnippetNextCandidate(&sIter) ){ + int iPos; + int iScore; + u64 mCover; + u64 mHighlight; + fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight); + assert( iScore>=0 ); + if( iScore>iBestScore ){ + pFragment->iPos = iPos; + pFragment->hlmask = mHighlight; + pFragment->covered = mCover; + iBestScore = iScore; + } + } + + sqlite3_free(sIter.aPhrase); + *piScore = iBestScore; + return SQLITE_OK; +} + + +/* +** Append a string to the string-buffer passed as the first argument. +** +** If nAppend is negative, then the length of the string zAppend is +** determined using strlen(). +*/ +static int fts3StringAppend( + StrBuffer *pStr, /* Buffer to append to */ + const char *zAppend, /* Pointer to data to append to buffer */ + int nAppend /* Size of zAppend in bytes (or -1) */ +){ + if( nAppend<0 ){ + nAppend = (int)strlen(zAppend); + } + + /* If there is insufficient space allocated at StrBuffer.z, use realloc() + ** to grow the buffer until so that it is big enough to accomadate the + ** appended data. + */ + if( pStr->n+nAppend+1>=pStr->nAlloc ){ + int nAlloc = pStr->nAlloc+nAppend+100; + char *zNew = sqlite3_realloc(pStr->z, nAlloc); + if( !zNew ){ + return SQLITE_NOMEM; + } + pStr->z = zNew; + pStr->nAlloc = nAlloc; + } + assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) ); + + /* Append the data to the string buffer. */ + memcpy(&pStr->z[pStr->n], zAppend, nAppend); + pStr->n += nAppend; + pStr->z[pStr->n] = '\0'; + + return SQLITE_OK; +} + +/* +** The fts3BestSnippet() function often selects snippets that end with a +** query term. That is, the final term of the snippet is always a term +** that requires highlighting. For example, if 'X' is a highlighted term +** and '.' is a non-highlighted term, BestSnippet() may select: +** +** ........X.....X +** +** This function "shifts" the beginning of the snippet forward in the +** document so that there are approximately the same number of +** non-highlighted terms to the right of the final highlighted term as there +** are to the left of the first highlighted term. For example, to this: +** +** ....X.....X.... +** +** This is done as part of extracting the snippet text, not when selecting +** the snippet. Snippet selection is done based on doclists only, so there +** is no way for fts3BestSnippet() to know whether or not the document +** actually contains terms that follow the final highlighted term. +*/ +static int fts3SnippetShift( + Fts3Table *pTab, /* FTS3 table snippet comes from */ + int iLangid, /* Language id to use in tokenizing */ + int nSnippet, /* Number of tokens desired for snippet */ + const char *zDoc, /* Document text to extract snippet from */ + int nDoc, /* Size of buffer zDoc in bytes */ + int *piPos, /* IN/OUT: First token of snippet */ + u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */ +){ + u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */ + + if( hlmask ){ + int nLeft; /* Tokens to the left of first highlight */ + int nRight; /* Tokens to the right of last highlight */ + int nDesired; /* Ideal number of tokens to shift forward */ + + for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++); + for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++); + nDesired = (nLeft-nRight)/2; + + /* Ideally, the start of the snippet should be pushed forward in the + ** document nDesired tokens. This block checks if there are actually + ** nDesired tokens to the right of the snippet. If so, *piPos and + ** *pHlMask are updated to shift the snippet nDesired tokens to the + ** right. Otherwise, the snippet is shifted by the number of tokens + ** available. + */ + if( nDesired>0 ){ + int nShift; /* Number of tokens to shift snippet by */ + int iCurrent = 0; /* Token counter */ + int rc; /* Return Code */ + sqlite3_tokenizer_module *pMod; + sqlite3_tokenizer_cursor *pC; + pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; + + /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired) + ** or more tokens in zDoc/nDoc. + */ + rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC); + if( rc!=SQLITE_OK ){ + return rc; + } + while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){ + const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0; + rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent); + } + pMod->xClose(pC); + if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; } + + nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet; + assert( nShift<=nDesired ); + if( nShift>0 ){ + *piPos += nShift; + *pHlmask = hlmask >> nShift; + } + } + } + return SQLITE_OK; +} + +/* +** Extract the snippet text for fragment pFragment from cursor pCsr and +** append it to string buffer pOut. +*/ +static int fts3SnippetText( + Fts3Cursor *pCsr, /* FTS3 Cursor */ + SnippetFragment *pFragment, /* Snippet to extract */ + int iFragment, /* Fragment number */ + int isLast, /* True for final fragment in snippet */ + int nSnippet, /* Number of tokens in extracted snippet */ + const char *zOpen, /* String inserted before highlighted term */ + const char *zClose, /* String inserted after highlighted term */ + const char *zEllipsis, /* String inserted between snippets */ + StrBuffer *pOut /* Write output here */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc; /* Return code */ + const char *zDoc; /* Document text to extract snippet from */ + int nDoc; /* Size of zDoc in bytes */ + int iCurrent = 0; /* Current token number of document */ + int iEnd = 0; /* Byte offset of end of current token */ + int isShiftDone = 0; /* True after snippet is shifted */ + int iPos = pFragment->iPos; /* First token of snippet */ + u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */ + int iCol = pFragment->iCol+1; /* Query column to extract text from */ + sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */ + sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */ + + zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol); + if( zDoc==0 ){ + if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){ + return SQLITE_NOMEM; + } + return SQLITE_OK; + } + nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol); + + /* Open a token cursor on the document. */ + pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; + rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC); + if( rc!=SQLITE_OK ){ + return rc; + } + + while( rc==SQLITE_OK ){ + const char *ZDUMMY; /* Dummy argument used with tokenizer */ + int DUMMY1 = -1; /* Dummy argument used with tokenizer */ + int iBegin = 0; /* Offset in zDoc of start of token */ + int iFin = 0; /* Offset in zDoc of end of token */ + int isHighlight = 0; /* True for highlighted terms */ + + /* Variable DUMMY1 is initialized to a negative value above. Elsewhere + ** in the FTS code the variable that the third argument to xNext points to + ** is initialized to zero before the first (*but not necessarily + ** subsequent*) call to xNext(). This is done for a particular application + ** that needs to know whether or not the tokenizer is being used for + ** snippet generation or for some other purpose. + ** + ** Extreme care is required when writing code to depend on this + ** initialization. It is not a documented part of the tokenizer interface. + ** If a tokenizer is used directly by any code outside of FTS, this + ** convention might not be respected. */ + rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_DONE ){ + /* Special case - the last token of the snippet is also the last token + ** of the column. Append any punctuation that occurred between the end + ** of the previous token and the end of the document to the output. + ** Then break out of the loop. */ + rc = fts3StringAppend(pOut, &zDoc[iEnd], -1); + } + break; + } + if( iCurrentiLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask + ); + isShiftDone = 1; + + /* Now that the shift has been done, check if the initial "..." are + ** required. They are required if (a) this is not the first fragment, + ** or (b) this fragment does not begin at position 0 of its column. + */ + if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){ + rc = fts3StringAppend(pOut, zEllipsis, -1); + } + if( rc!=SQLITE_OK || iCurrent=(iPos+nSnippet) ){ + if( isLast ){ + rc = fts3StringAppend(pOut, zEllipsis, -1); + } + break; + } + + /* Set isHighlight to true if this term should be highlighted. */ + isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0; + + if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd); + if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1); + if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin); + if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1); + + iEnd = iFin; + } + + pMod->xClose(pC); + return rc; +} + + +/* +** This function is used to count the entries in a column-list (a +** delta-encoded list of term offsets within a single column of a single +** row). When this function is called, *ppCollist should point to the +** beginning of the first varint in the column-list (the varint that +** contains the position of the first matching term in the column data). +** Before returning, *ppCollist is set to point to the first byte after +** the last varint in the column-list (either the 0x00 signifying the end +** of the position-list, or the 0x01 that precedes the column number of +** the next column in the position-list). +** +** The number of elements in the column-list is returned. +*/ +static int fts3ColumnlistCount(char **ppCollist){ + char *pEnd = *ppCollist; + char c = 0; + int nEntry = 0; + + /* A column-list is terminated by either a 0x01 or 0x00. */ + while( 0xFE & (*pEnd | c) ){ + c = *pEnd++ & 0x80; + if( !c ) nEntry++; + } + + *ppCollist = pEnd; + return nEntry; +} + +/* +** fts3ExprIterate() callback used to collect the "global" matchinfo stats +** for a single query. +** +** fts3ExprIterate() callback to load the 'global' elements of a +** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements +** of the matchinfo array that are constant for all rows returned by the +** current query. +** +** Argument pCtx is actually a pointer to a struct of type MatchInfo. This +** function populates Matchinfo.aMatchinfo[] as follows: +** +** for(iCol=0; iColpCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol] + ); +} + +/* +** fts3ExprIterate() callback used to collect the "local" part of the +** FTS3_MATCHINFO_HITS array. The local stats are those elements of the +** array that are different for each row returned by the query. +*/ +static int fts3ExprLocalHitsCb( + Fts3Expr *pExpr, /* Phrase expression node */ + int iPhrase, /* Phrase number */ + void *pCtx /* Pointer to MatchInfo structure */ +){ + int rc = SQLITE_OK; + MatchInfo *p = (MatchInfo *)pCtx; + int iStart = iPhrase * p->nCol * 3; + int i; + + for(i=0; inCol && rc==SQLITE_OK; i++){ + char *pCsr; + rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr); + if( pCsr ){ + p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr); + }else{ + p->aMatchinfo[iStart+i*3] = 0; + } + } + + return rc; +} + +static int fts3MatchinfoCheck( + Fts3Table *pTab, + char cArg, + char **pzErr +){ + if( (cArg==FTS3_MATCHINFO_NPHRASE) + || (cArg==FTS3_MATCHINFO_NCOL) + || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4) + || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4) + || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize) + || (cArg==FTS3_MATCHINFO_LCS) + || (cArg==FTS3_MATCHINFO_HITS) + ){ + return SQLITE_OK; + } + *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg); + return SQLITE_ERROR; +} + +static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ + int nVal; /* Number of integers output by cArg */ + + switch( cArg ){ + case FTS3_MATCHINFO_NDOC: + case FTS3_MATCHINFO_NPHRASE: + case FTS3_MATCHINFO_NCOL: + nVal = 1; + break; + + case FTS3_MATCHINFO_AVGLENGTH: + case FTS3_MATCHINFO_LENGTH: + case FTS3_MATCHINFO_LCS: + nVal = pInfo->nCol; + break; + + default: + assert( cArg==FTS3_MATCHINFO_HITS ); + nVal = pInfo->nCol * pInfo->nPhrase * 3; + break; + } + + return nVal; +} + +static int fts3MatchinfoSelectDoctotal( + Fts3Table *pTab, + sqlite3_stmt **ppStmt, + sqlite3_int64 *pnDoc, + const char **paLen +){ + sqlite3_stmt *pStmt; + const char *a; + sqlite3_int64 nDoc; + + if( !*ppStmt ){ + int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt); + if( rc!=SQLITE_OK ) return rc; + } + pStmt = *ppStmt; + assert( sqlite3_data_count(pStmt)==1 ); + + a = sqlite3_column_blob(pStmt, 0); + a += sqlite3Fts3GetVarint(a, &nDoc); + if( nDoc==0 ) return FTS_CORRUPT_VTAB; + *pnDoc = (u32)nDoc; + + if( paLen ) *paLen = a; + return SQLITE_OK; +} + +/* +** An instance of the following structure is used to store state while +** iterating through a multi-column position-list corresponding to the +** hits for a single phrase on a single row in order to calculate the +** values for a matchinfo() FTS3_MATCHINFO_LCS request. +*/ +typedef struct LcsIterator LcsIterator; +struct LcsIterator { + Fts3Expr *pExpr; /* Pointer to phrase expression */ + int iPosOffset; /* Tokens count up to end of this phrase */ + char *pRead; /* Cursor used to iterate through aDoclist */ + int iPos; /* Current position */ +}; + +/* +** If LcsIterator.iCol is set to the following value, the iterator has +** finished iterating through all offsets for all columns. +*/ +#define LCS_ITERATOR_FINISHED 0x7FFFFFFF; + +static int fts3MatchinfoLcsCb( + Fts3Expr *pExpr, /* Phrase expression node */ + int iPhrase, /* Phrase number (numbered from zero) */ + void *pCtx /* Pointer to MatchInfo structure */ +){ + LcsIterator *aIter = (LcsIterator *)pCtx; + aIter[iPhrase].pExpr = pExpr; + return SQLITE_OK; +} + +/* +** Advance the iterator passed as an argument to the next position. Return +** 1 if the iterator is at EOF or if it now points to the start of the +** position list for the next column. +*/ +static int fts3LcsIteratorAdvance(LcsIterator *pIter){ + char *pRead = pIter->pRead; + sqlite3_int64 iRead; + int rc = 0; + + pRead += sqlite3Fts3GetVarint(pRead, &iRead); + if( iRead==0 || iRead==1 ){ + pRead = 0; + rc = 1; + }else{ + pIter->iPos += (int)(iRead-2); + } + + pIter->pRead = pRead; + return rc; +} + +/* +** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. +** +** If the call is successful, the longest-common-substring lengths for each +** column are written into the first nCol elements of the pInfo->aMatchinfo[] +** array before returning. SQLITE_OK is returned in this case. +** +** Otherwise, if an error occurs, an SQLite error code is returned and the +** data written to the first nCol elements of pInfo->aMatchinfo[] is +** undefined. +*/ +static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){ + LcsIterator *aIter; + int i; + int iCol; + int nToken = 0; + + /* Allocate and populate the array of LcsIterator objects. The array + ** contains one element for each matchable phrase in the query. + **/ + aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase); + if( !aIter ) return SQLITE_NOMEM; + memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase); + (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter); + + for(i=0; inPhrase; i++){ + LcsIterator *pIter = &aIter[i]; + nToken -= pIter->pExpr->pPhrase->nToken; + pIter->iPosOffset = nToken; + } + + for(iCol=0; iColnCol; iCol++){ + int nLcs = 0; /* LCS value for this column */ + int nLive = 0; /* Number of iterators in aIter not at EOF */ + + for(i=0; inPhrase; i++){ + int rc; + LcsIterator *pIt = &aIter[i]; + rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead); + if( rc!=SQLITE_OK ) return rc; + if( pIt->pRead ){ + pIt->iPos = pIt->iPosOffset; + fts3LcsIteratorAdvance(&aIter[i]); + nLive++; + } + } + + while( nLive>0 ){ + LcsIterator *pAdv = 0; /* The iterator to advance by one position */ + int nThisLcs = 0; /* LCS for the current iterator positions */ + + for(i=0; inPhrase; i++){ + LcsIterator *pIter = &aIter[i]; + if( pIter->pRead==0 ){ + /* This iterator is already at EOF for this column. */ + nThisLcs = 0; + }else{ + if( pAdv==0 || pIter->iPosiPos ){ + pAdv = pIter; + } + if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){ + nThisLcs++; + }else{ + nThisLcs = 1; + } + if( nThisLcs>nLcs ) nLcs = nThisLcs; + } + } + if( fts3LcsIteratorAdvance(pAdv) ) nLive--; + } + + pInfo->aMatchinfo[iCol] = nLcs; + } + + sqlite3_free(aIter); + return SQLITE_OK; +} + +/* +** Populate the buffer pInfo->aMatchinfo[] with an array of integers to +** be returned by the matchinfo() function. Argument zArg contains the +** format string passed as the second argument to matchinfo (or the +** default value "pcx" if no second argument was specified). The format +** string has already been validated and the pInfo->aMatchinfo[] array +** is guaranteed to be large enough for the output. +** +** If bGlobal is true, then populate all fields of the matchinfo() output. +** If it is false, then assume that those fields that do not change between +** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS) +** have already been populated. +** +** Return SQLITE_OK if successful, or an SQLite error code if an error +** occurs. If a value other than SQLITE_OK is returned, the state the +** pInfo->aMatchinfo[] buffer is left in is undefined. +*/ +static int fts3MatchinfoValues( + Fts3Cursor *pCsr, /* FTS3 cursor object */ + int bGlobal, /* True to grab the global stats */ + MatchInfo *pInfo, /* Matchinfo context object */ + const char *zArg /* Matchinfo format string */ +){ + int rc = SQLITE_OK; + int i; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + sqlite3_stmt *pSelect = 0; + + for(i=0; rc==SQLITE_OK && zArg[i]; i++){ + + switch( zArg[i] ){ + case FTS3_MATCHINFO_NPHRASE: + if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase; + break; + + case FTS3_MATCHINFO_NCOL: + if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol; + break; + + case FTS3_MATCHINFO_NDOC: + if( bGlobal ){ + sqlite3_int64 nDoc = 0; + rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0); + pInfo->aMatchinfo[0] = (u32)nDoc; + } + break; + + case FTS3_MATCHINFO_AVGLENGTH: + if( bGlobal ){ + sqlite3_int64 nDoc; /* Number of rows in table */ + const char *a; /* Aggregate column length array */ + + rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a); + if( rc==SQLITE_OK ){ + int iCol; + for(iCol=0; iColnCol; iCol++){ + u32 iVal; + sqlite3_int64 nToken; + a += sqlite3Fts3GetVarint(a, &nToken); + iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc); + pInfo->aMatchinfo[iCol] = iVal; + } + } + } + break; + + case FTS3_MATCHINFO_LENGTH: { + sqlite3_stmt *pSelectDocsize = 0; + rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize); + if( rc==SQLITE_OK ){ + int iCol; + const char *a = sqlite3_column_blob(pSelectDocsize, 0); + for(iCol=0; iColnCol; iCol++){ + sqlite3_int64 nToken; + a += sqlite3Fts3GetVarint(a, &nToken); + pInfo->aMatchinfo[iCol] = (u32)nToken; + } + } + sqlite3_reset(pSelectDocsize); + break; + } + + case FTS3_MATCHINFO_LCS: + rc = fts3ExprLoadDoclists(pCsr, 0, 0); + if( rc==SQLITE_OK ){ + rc = fts3MatchinfoLcs(pCsr, pInfo); + } + break; + + default: { + Fts3Expr *pExpr; + assert( zArg[i]==FTS3_MATCHINFO_HITS ); + pExpr = pCsr->pExpr; + rc = fts3ExprLoadDoclists(pCsr, 0, 0); + if( rc!=SQLITE_OK ) break; + if( bGlobal ){ + if( pCsr->pDeferred ){ + rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0); + if( rc!=SQLITE_OK ) break; + } + rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo); + if( rc!=SQLITE_OK ) break; + } + (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo); + break; + } + } + + pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]); + } + + sqlite3_reset(pSelect); + return rc; +} + + +/* +** Populate pCsr->aMatchinfo[] with data for the current row. The +** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32). +*/ +static int fts3GetMatchinfo( + Fts3Cursor *pCsr, /* FTS3 Cursor object */ + const char *zArg /* Second argument to matchinfo() function */ +){ + MatchInfo sInfo; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; + int bGlobal = 0; /* Collect 'global' stats as well as local */ + + memset(&sInfo, 0, sizeof(MatchInfo)); + sInfo.pCursor = pCsr; + sInfo.nCol = pTab->nColumn; + + /* If there is cached matchinfo() data, but the format string for the + ** cache does not match the format string for this request, discard + ** the cached data. */ + if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){ + assert( pCsr->aMatchinfo ); + sqlite3_free(pCsr->aMatchinfo); + pCsr->zMatchinfo = 0; + pCsr->aMatchinfo = 0; + } + + /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the + ** matchinfo function has been called for this query. In this case + ** allocate the array used to accumulate the matchinfo data and + ** initialize those elements that are constant for every row. + */ + if( pCsr->aMatchinfo==0 ){ + int nMatchinfo = 0; /* Number of u32 elements in match-info */ + int nArg; /* Bytes in zArg */ + int i; /* Used to iterate through zArg */ + + /* Determine the number of phrases in the query */ + pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr); + sInfo.nPhrase = pCsr->nPhrase; + + /* Determine the number of integers in the buffer returned by this call. */ + for(i=0; zArg[i]; i++){ + nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]); + } + + /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */ + nArg = (int)strlen(zArg); + pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1); + if( !pCsr->aMatchinfo ) return SQLITE_NOMEM; + + pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo]; + pCsr->nMatchinfo = nMatchinfo; + memcpy(pCsr->zMatchinfo, zArg, nArg+1); + memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo); + pCsr->isMatchinfoNeeded = 1; + bGlobal = 1; + } + + sInfo.aMatchinfo = pCsr->aMatchinfo; + sInfo.nPhrase = pCsr->nPhrase; + if( pCsr->isMatchinfoNeeded ){ + rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg); + pCsr->isMatchinfoNeeded = 0; + } + + return rc; +} + +/* +** Implementation of snippet() function. +*/ +SQLITE_PRIVATE void sqlite3Fts3Snippet( + sqlite3_context *pCtx, /* SQLite function call context */ + Fts3Cursor *pCsr, /* Cursor object */ + const char *zStart, /* Snippet start text - "" */ + const char *zEnd, /* Snippet end text - "" */ + const char *zEllipsis, /* Snippet ellipsis text - "..." */ + int iCol, /* Extract snippet from this column */ + int nToken /* Approximate number of tokens in snippet */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; + int i; + StrBuffer res = {0, 0, 0}; + + /* The returned text includes up to four fragments of text extracted from + ** the data in the current row. The first iteration of the for(...) loop + ** below attempts to locate a single fragment of text nToken tokens in + ** size that contains at least one instance of all phrases in the query + ** expression that appear in the current row. If such a fragment of text + ** cannot be found, the second iteration of the loop attempts to locate + ** a pair of fragments, and so on. + */ + int nSnippet = 0; /* Number of fragments in this snippet */ + SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */ + int nFToken = -1; /* Number of tokens in each fragment */ + + if( !pCsr->pExpr ){ + sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); + return; + } + + for(nSnippet=1; 1; nSnippet++){ + + int iSnip; /* Loop counter 0..nSnippet-1 */ + u64 mCovered = 0; /* Bitmask of phrases covered by snippet */ + u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */ + + if( nToken>=0 ){ + nFToken = (nToken+nSnippet-1) / nSnippet; + }else{ + nFToken = -1 * nToken; + } + + for(iSnip=0; iSnipnColumn; iRead++){ + SnippetFragment sF = {0, 0, 0, 0}; + int iS; + if( iCol>=0 && iRead!=iCol ) continue; + + /* Find the best snippet of nFToken tokens in column iRead. */ + rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS); + if( rc!=SQLITE_OK ){ + goto snippet_out; + } + if( iS>iBestScore ){ + *pFragment = sF; + iBestScore = iS; + } + } + + mCovered |= pFragment->covered; + } + + /* If all query phrases seen by fts3BestSnippet() are present in at least + ** one of the nSnippet snippet fragments, break out of the loop. + */ + assert( (mCovered&mSeen)==mCovered ); + if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break; + } + + assert( nFToken>0 ); + + for(i=0; ipCsr, pExpr, p->iCol, &pList); + nTerm = pExpr->pPhrase->nToken; + if( pList ){ + fts3GetDeltaPosition(&pList, &iPos); + assert( iPos>=0 ); + } + + for(iTerm=0; iTermaTerm[p->iTerm++]; + pT->iOff = nTerm-iTerm-1; + pT->pList = pList; + pT->iPos = iPos; + } + + return rc; +} + +/* +** Implementation of offsets() function. +*/ +SQLITE_PRIVATE void sqlite3Fts3Offsets( + sqlite3_context *pCtx, /* SQLite function call context */ + Fts3Cursor *pCsr /* Cursor object */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule; + int rc; /* Return Code */ + int nToken; /* Number of tokens in query */ + int iCol; /* Column currently being processed */ + StrBuffer res = {0, 0, 0}; /* Result string */ + TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */ + + if( !pCsr->pExpr ){ + sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); + return; + } + + memset(&sCtx, 0, sizeof(sCtx)); + assert( pCsr->isRequireSeek==0 ); + + /* Count the number of terms in the query */ + rc = fts3ExprLoadDoclists(pCsr, 0, &nToken); + if( rc!=SQLITE_OK ) goto offsets_out; + + /* Allocate the array of TermOffset iterators. */ + sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken); + if( 0==sCtx.aTerm ){ + rc = SQLITE_NOMEM; + goto offsets_out; + } + sCtx.iDocid = pCsr->iPrevId; + sCtx.pCsr = pCsr; + + /* Loop through the table columns, appending offset information to + ** string-buffer res for each column. + */ + for(iCol=0; iColnColumn; iCol++){ + sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */ + const char *ZDUMMY; /* Dummy argument used with xNext() */ + int NDUMMY = 0; /* Dummy argument used with xNext() */ + int iStart = 0; + int iEnd = 0; + int iCurrent = 0; + const char *zDoc; + int nDoc; + + /* Initialize the contents of sCtx.aTerm[] for column iCol. There is + ** no way that this operation can fail, so the return code from + ** fts3ExprIterate() can be discarded. + */ + sCtx.iCol = iCol; + sCtx.iTerm = 0; + (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx); + + /* Retreive the text stored in column iCol. If an SQL NULL is stored + ** in column iCol, jump immediately to the next iteration of the loop. + ** If an OOM occurs while retrieving the data (this can happen if SQLite + ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM + ** to the caller. + */ + zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1); + nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1); + if( zDoc==0 ){ + if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){ + continue; + } + rc = SQLITE_NOMEM; + goto offsets_out; + } + + /* Initialize a tokenizer iterator to iterate through column iCol. */ + rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, + zDoc, nDoc, &pC + ); + if( rc!=SQLITE_OK ) goto offsets_out; + + rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); + while( rc==SQLITE_OK ){ + int i; /* Used to loop through terms */ + int iMinPos = 0x7FFFFFFF; /* Position of next token */ + TermOffset *pTerm = 0; /* TermOffset associated with next token */ + + for(i=0; ipList && (pT->iPos-pT->iOff)iPos-pT->iOff; + pTerm = pT; + } + } + + if( !pTerm ){ + /* All offsets for this column have been gathered. */ + rc = SQLITE_DONE; + }else{ + assert( iCurrent<=iMinPos ); + if( 0==(0xFE&*pTerm->pList) ){ + pTerm->pList = 0; + }else{ + fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos); + } + while( rc==SQLITE_OK && iCurrentxNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); + } + if( rc==SQLITE_OK ){ + char aBuffer[64]; + sqlite3_snprintf(sizeof(aBuffer), aBuffer, + "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart + ); + rc = fts3StringAppend(&res, aBuffer, -1); + }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){ + rc = FTS_CORRUPT_VTAB; + } + } + } + if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + } + + pMod->xClose(pC); + if( rc!=SQLITE_OK ) goto offsets_out; + } + + offsets_out: + sqlite3_free(sCtx.aTerm); + assert( rc!=SQLITE_DONE ); + sqlite3Fts3SegmentsClose(pTab); + if( rc!=SQLITE_OK ){ + sqlite3_result_error_code(pCtx, rc); + sqlite3_free(res.z); + }else{ + sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free); + } + return; +} + +/* +** Implementation of matchinfo() function. +*/ +SQLITE_PRIVATE void sqlite3Fts3Matchinfo( + sqlite3_context *pContext, /* Function call context */ + Fts3Cursor *pCsr, /* FTS3 table cursor */ + const char *zArg /* Second arg to matchinfo() function */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc; + int i; + const char *zFormat; + + if( zArg ){ + for(i=0; zArg[i]; i++){ + char *zErr = 0; + if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){ + sqlite3_result_error(pContext, zErr, -1); + sqlite3_free(zErr); + return; + } + } + zFormat = zArg; + }else{ + zFormat = FTS3_MATCHINFO_DEFAULT; + } + + if( !pCsr->pExpr ){ + sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC); + return; + } + + /* Retrieve matchinfo() data. */ + rc = fts3GetMatchinfo(pCsr, zFormat); + sqlite3Fts3SegmentsClose(pTab); + + if( rc!=SQLITE_OK ){ + sqlite3_result_error_code(pContext, rc); + }else{ + int n = pCsr->nMatchinfo * sizeof(u32); + sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT); + } +} + +#endif + +/************** End of fts3_snippet.c ****************************************/ +/************** Begin file fts3_unicode.c ************************************/ +/* +** 2012 May 24 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** Implementation of the "unicode" full-text-search tokenizer. +*/ + +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* #include */ +/* #include */ +/* #include */ +/* #include */ + + +/* +** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied +** from the sqlite3 source file utf.c. If this file is compiled as part +** of the amalgamation, they are not required. +*/ +#ifndef SQLITE_AMALGAMATION + +static const unsigned char sqlite3Utf8Trans1[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, +}; + +#define READ_UTF8(zIn, zTerm, c) \ + c = *(zIn++); \ + if( c>=0xc0 ){ \ + c = sqlite3Utf8Trans1[c-0xc0]; \ + while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ + c = (c<<6) + (0x3f & *(zIn++)); \ + } \ + if( c<0x80 \ + || (c&0xFFFFF800)==0xD800 \ + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ + } + +#define WRITE_UTF8(zOut, c) { \ + if( c<0x00080 ){ \ + *zOut++ = (u8)(c&0xFF); \ + } \ + else if( c<0x00800 ){ \ + *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ + else if( c<0x10000 ){ \ + *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + }else{ \ + *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ + *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ +} + +#endif /* ifndef SQLITE_AMALGAMATION */ + +typedef struct unicode_tokenizer unicode_tokenizer; +typedef struct unicode_cursor unicode_cursor; + +struct unicode_tokenizer { + sqlite3_tokenizer base; + int bRemoveDiacritic; + int nException; + int *aiException; +}; + +struct unicode_cursor { + sqlite3_tokenizer_cursor base; + const unsigned char *aInput; /* Input text being tokenized */ + int nInput; /* Size of aInput[] in bytes */ + int iOff; /* Current offset within aInput[] */ + int iToken; /* Index of next token to be returned */ + char *zToken; /* storage for current token */ + int nAlloc; /* space allocated at zToken */ +}; + + +/* +** Destroy a tokenizer allocated by unicodeCreate(). +*/ +static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){ + if( pTokenizer ){ + unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer; + sqlite3_free(p->aiException); + sqlite3_free(p); + } + return SQLITE_OK; +} + +/* +** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE +** statement has specified that the tokenizer for this table shall consider +** all characters in string zIn/nIn to be separators (if bAlnum==0) or +** token characters (if bAlnum==1). +** +** For each codepoint in the zIn/nIn string, this function checks if the +** sqlite3FtsUnicodeIsalnum() function already returns the desired result. +** If so, no action is taken. Otherwise, the codepoint is added to the +** unicode_tokenizer.aiException[] array. For the purposes of tokenization, +** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all +** codepoints in the aiException[] array. +** +** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic() +** identifies as a diacritic) occurs in the zIn/nIn string it is ignored. +** It is not possible to change the behavior of the tokenizer with respect +** to these codepoints. +*/ +static int unicodeAddExceptions( + unicode_tokenizer *p, /* Tokenizer to add exceptions to */ + int bAlnum, /* Replace Isalnum() return value with this */ + const char *zIn, /* Array of characters to make exceptions */ + int nIn /* Length of z in bytes */ +){ + const unsigned char *z = (const unsigned char *)zIn; + const unsigned char *zTerm = &z[nIn]; + int iCode; + int nEntry = 0; + + assert( bAlnum==0 || bAlnum==1 ); + + while( zaiException, (p->nException+nEntry)*sizeof(int)); + if( aNew==0 ) return SQLITE_NOMEM; + nNew = p->nException; + + z = (const unsigned char *)zIn; + while( zi; j--) aNew[j] = aNew[j-1]; + aNew[i] = iCode; + nNew++; + } + } + p->aiException = aNew; + p->nException = nNew; + } + + return SQLITE_OK; +} + +/* +** Return true if the p->aiException[] array contains the value iCode. +*/ +static int unicodeIsException(unicode_tokenizer *p, int iCode){ + if( p->nException>0 ){ + int *a = p->aiException; + int iLo = 0; + int iHi = p->nException-1; + + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + if( iCode==a[iTest] ){ + return 1; + }else if( iCode>a[iTest] ){ + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + } + + return 0; +} + +/* +** Return true if, for the purposes of tokenization, codepoint iCode is +** considered a token character (not a separator). +*/ +static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){ + assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); + return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode); +} + +/* +** Create a new tokenizer instance. +*/ +static int unicodeCreate( + int nArg, /* Size of array argv[] */ + const char * const *azArg, /* Tokenizer creation arguments */ + sqlite3_tokenizer **pp /* OUT: New tokenizer handle */ +){ + unicode_tokenizer *pNew; /* New tokenizer object */ + int i; + int rc = SQLITE_OK; + + pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer)); + if( pNew==NULL ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(unicode_tokenizer)); + pNew->bRemoveDiacritic = 1; + + for(i=0; rc==SQLITE_OK && ibRemoveDiacritic = 1; + } + else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){ + pNew->bRemoveDiacritic = 0; + } + else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){ + rc = unicodeAddExceptions(pNew, 1, &z[11], n-11); + } + else if( n>=11 && memcmp("separators=", z, 11)==0 ){ + rc = unicodeAddExceptions(pNew, 0, &z[11], n-11); + } + else{ + /* Unrecognized argument */ + rc = SQLITE_ERROR; + } + } + + if( rc!=SQLITE_OK ){ + unicodeDestroy((sqlite3_tokenizer *)pNew); + pNew = 0; + } + *pp = (sqlite3_tokenizer *)pNew; + return rc; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is pInput[0..nBytes-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int unicodeOpen( + sqlite3_tokenizer *p, /* The tokenizer */ + const char *aInput, /* Input string */ + int nInput, /* Size of string aInput in bytes */ + sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */ +){ + unicode_cursor *pCsr; + + pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor)); + if( pCsr==0 ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(unicode_cursor)); + + pCsr->aInput = (const unsigned char *)aInput; + if( aInput==0 ){ + pCsr->nInput = 0; + }else if( nInput<0 ){ + pCsr->nInput = (int)strlen(aInput); + }else{ + pCsr->nInput = nInput; + } + + *pp = &pCsr->base; + UNUSED_PARAMETER(p); + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** simpleOpen() above. +*/ +static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){ + unicode_cursor *pCsr = (unicode_cursor *) pCursor; + sqlite3_free(pCsr->zToken); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to simpleOpen(). +*/ +static int unicodeNext( + sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */ + const char **paToken, /* OUT: Token text */ + int *pnToken, /* OUT: Number of bytes at *paToken */ + int *piStart, /* OUT: Starting offset of token */ + int *piEnd, /* OUT: Ending offset of token */ + int *piPos /* OUT: Position integer of token */ +){ + unicode_cursor *pCsr = (unicode_cursor *)pC; + unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer); + int iCode; + char *zOut; + const unsigned char *z = &pCsr->aInput[pCsr->iOff]; + const unsigned char *zStart = z; + const unsigned char *zEnd; + const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput]; + + /* Scan past any delimiter characters before the start of the next token. + ** Return SQLITE_DONE early if this takes us all the way to the end of + ** the input. */ + while( z=zTerm ) return SQLITE_DONE; + + zOut = pCsr->zToken; + do { + int iOut; + + /* Grow the output buffer if required. */ + if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){ + char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64); + if( !zNew ) return SQLITE_NOMEM; + zOut = &zNew[zOut - pCsr->zToken]; + pCsr->zToken = zNew; + pCsr->nAlloc += 64; + } + + /* Write the folded case of the last character read to the output */ + zEnd = z; + iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic); + if( iOut ){ + WRITE_UTF8(zOut, iOut); + } + + /* If the cursor is not at EOF, read the next character */ + if( z>=zTerm ) break; + READ_UTF8(z, zTerm, iCode); + }while( unicodeIsAlnum(p, iCode) + || sqlite3FtsUnicodeIsdiacritic(iCode) + ); + + /* Set the output variables and return. */ + pCsr->iOff = (z - pCsr->aInput); + *paToken = pCsr->zToken; + *pnToken = zOut - pCsr->zToken; + *piStart = (zStart - pCsr->aInput); + *piEnd = (zEnd - pCsr->aInput); + *piPos = pCsr->iToken++; + return SQLITE_OK; +} + +/* +** Set *ppModule to a pointer to the sqlite3_tokenizer_module +** structure for the unicode tokenizer. +*/ +SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){ + static const sqlite3_tokenizer_module module = { + 0, + unicodeCreate, + unicodeDestroy, + unicodeOpen, + unicodeClose, + unicodeNext, + 0, + }; + *ppModule = &module; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ +#endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */ + +/************** End of fts3_unicode.c ****************************************/ +/************** Begin file fts3_unicode2.c ***********************************/ +/* +** 2012 May 25 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +*/ + +/* +** DO NOT EDIT THIS MACHINE GENERATED FILE. +*/ + +#if defined(SQLITE_ENABLE_FTS4_UNICODE61) +#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) + +/* #include */ + +/* +** Return true if the argument corresponds to a unicode codepoint +** classified as either a letter or a number. Otherwise false. +** +** The results are undefined if the value passed to this function +** is less than zero. +*/ +SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){ + /* Each unsigned integer in the following array corresponds to a contiguous + ** range of unicode codepoints that are not either letters or numbers (i.e. + ** codepoints for which this function should return 0). + ** + ** The most significant 22 bits in each 32-bit value contain the first + ** codepoint in the range. The least significant 10 bits are used to store + ** the size of the range (always at least 1). In other words, the value + ** ((C<<22) + N) represents a range of N codepoints starting with codepoint + ** C. It is not possible to represent a range larger than 1023 codepoints + ** using this format. + */ + const static unsigned int aEntry[] = { + 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07, + 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01, + 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401, + 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01, + 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01, + 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802, + 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F, + 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401, + 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804, + 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403, + 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812, + 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001, + 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802, + 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805, + 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401, + 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03, + 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807, + 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001, + 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01, + 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804, + 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001, + 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802, + 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01, + 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06, + 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007, + 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006, + 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417, + 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14, + 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07, + 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01, + 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001, + 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802, + 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F, + 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002, + 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802, + 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006, + 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D, + 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802, + 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027, + 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403, + 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805, + 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04, + 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401, + 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005, + 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B, + 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A, + 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001, + 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59, + 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807, + 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01, + 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E, + 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100, + 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10, + 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402, + 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804, + 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012, + 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004, + 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002, + 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803, + 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07, + 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02, + 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802, + 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013, + 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06, + 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003, + 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01, + 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403, + 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009, + 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003, + 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003, + 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E, + 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046, + 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401, + 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401, + 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F, + 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C, + 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002, + 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025, + 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6, + 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46, + 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060, + 0x380400F0, + }; + static const unsigned int aAscii[4] = { + 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001, + }; + + if( c<128 ){ + return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 ); + }else if( c<(1<<22) ){ + unsigned int key = (((unsigned int)c)<<10) | 0x000003FF; + int iRes; + int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; + int iLo = 0; + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + if( key >= aEntry[iTest] ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + assert( aEntry[0]=aEntry[iRes] ); + return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF))); + } + return 1; +} + + +/* +** If the argument is a codepoint corresponding to a lowercase letter +** in the ASCII range with a diacritic added, return the codepoint +** of the ASCII letter only. For example, if passed 235 - "LATIN +** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER +** E"). The resuls of passing a codepoint that corresponds to an +** uppercase letter are undefined. +*/ +static int remove_diacritic(int c){ + unsigned short aDia[] = { + 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995, + 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286, + 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732, + 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336, + 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928, + 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234, + 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504, + 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529, + 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, + 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, + 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, + 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, + 62924, 63050, 63082, 63274, 63390, + }; + char aChar[] = { + '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c', + 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r', + 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o', + 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r', + 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h', + 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't', + 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a', + 'e', 'i', 'o', 'u', 'y', + }; + + unsigned int key = (((unsigned int)c)<<3) | 0x00000007; + int iRes = 0; + int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1; + int iLo = 0; + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + if( key >= aDia[iTest] ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + assert( key>=aDia[iRes] ); + return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]); +}; + + +/* +** Return true if the argument interpreted as a unicode codepoint +** is a diacritical modifier character. +*/ +SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){ + unsigned int mask0 = 0x08029FDF; + unsigned int mask1 = 0x000361F8; + if( c<768 || c>817 ) return 0; + return (c < 768+32) ? + (mask0 & (1 << (c-768))) : + (mask1 & (1 << (c-768-32))); +} + + +/* +** Interpret the argument as a unicode codepoint. If the codepoint +** is an upper case character that has a lower case equivalent, +** return the codepoint corresponding to the lower case version. +** Otherwise, return a copy of the argument. +** +** The results are undefined if the value passed to this function +** is less than zero. +*/ +SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ + /* Each entry in the following array defines a rule for folding a range + ** of codepoints to lower case. The rule applies to a range of nRange + ** codepoints starting at codepoint iCode. + ** + ** If the least significant bit in flags is clear, then the rule applies + ** to all nRange codepoints (i.e. all nRange codepoints are upper case and + ** need to be folded). Or, if it is set, then the rule only applies to + ** every second codepoint in the range, starting with codepoint C. + ** + ** The 7 most significant bits in flags are an index into the aiOff[] + ** array. If a specific codepoint C does require folding, then its lower + ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF). + ** + ** The contents of this array are generated by parsing the CaseFolding.txt + ** file distributed as part of the "Unicode Character Database". See + ** http://www.unicode.org for details. + */ + static const struct TableEntry { + unsigned short iCode; + unsigned char flags; + unsigned char nRange; + } aEntry[] = { + {65, 14, 26}, {181, 64, 1}, {192, 14, 23}, + {216, 14, 7}, {256, 1, 48}, {306, 1, 6}, + {313, 1, 16}, {330, 1, 46}, {376, 116, 1}, + {377, 1, 6}, {383, 104, 1}, {385, 50, 1}, + {386, 1, 4}, {390, 44, 1}, {391, 0, 1}, + {393, 42, 2}, {395, 0, 1}, {398, 32, 1}, + {399, 38, 1}, {400, 40, 1}, {401, 0, 1}, + {403, 42, 1}, {404, 46, 1}, {406, 52, 1}, + {407, 48, 1}, {408, 0, 1}, {412, 52, 1}, + {413, 54, 1}, {415, 56, 1}, {416, 1, 6}, + {422, 60, 1}, {423, 0, 1}, {425, 60, 1}, + {428, 0, 1}, {430, 60, 1}, {431, 0, 1}, + {433, 58, 2}, {435, 1, 4}, {439, 62, 1}, + {440, 0, 1}, {444, 0, 1}, {452, 2, 1}, + {453, 0, 1}, {455, 2, 1}, {456, 0, 1}, + {458, 2, 1}, {459, 1, 18}, {478, 1, 18}, + {497, 2, 1}, {498, 1, 4}, {502, 122, 1}, + {503, 134, 1}, {504, 1, 40}, {544, 110, 1}, + {546, 1, 18}, {570, 70, 1}, {571, 0, 1}, + {573, 108, 1}, {574, 68, 1}, {577, 0, 1}, + {579, 106, 1}, {580, 28, 1}, {581, 30, 1}, + {582, 1, 10}, {837, 36, 1}, {880, 1, 4}, + {886, 0, 1}, {902, 18, 1}, {904, 16, 3}, + {908, 26, 1}, {910, 24, 2}, {913, 14, 17}, + {931, 14, 9}, {962, 0, 1}, {975, 4, 1}, + {976, 140, 1}, {977, 142, 1}, {981, 146, 1}, + {982, 144, 1}, {984, 1, 24}, {1008, 136, 1}, + {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1}, + {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1}, + {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32}, + {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1}, + {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38}, + {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1}, + {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1}, + {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6}, + {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6}, + {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8}, + {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2}, + {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1}, + {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2}, + {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2}, + {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2}, + {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1}, + {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16}, + {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47}, + {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1}, + {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1}, + {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1}, + {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2}, + {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1}, + {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14}, + {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1}, + {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1}, + {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1}, + {65313, 14, 26}, + }; + static const unsigned short aiOff[] = { + 1, 2, 8, 15, 16, 26, 28, 32, + 37, 38, 40, 48, 63, 64, 69, 71, + 79, 80, 116, 202, 203, 205, 206, 207, + 209, 210, 211, 213, 214, 217, 218, 219, + 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721, + 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, + 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, + 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, + 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, + 65514, 65521, 65527, 65528, 65529, + }; + + int ret = c; + + assert( c>=0 ); + assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 ); + + if( c<128 ){ + if( c>='A' && c<='Z' ) ret = c + ('a' - 'A'); + }else if( c<65536 ){ + int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; + int iLo = 0; + int iRes = -1; + + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + int cmp = (c - aEntry[iTest].iCode); + if( cmp>=0 ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + assert( iRes<0 || c>=aEntry[iRes].iCode ); + + if( iRes>=0 ){ + const struct TableEntry *p = &aEntry[iRes]; + if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){ + ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF; + assert( ret>0 ); + } + } + + if( bRemoveDiacritic ) ret = remove_diacritic(ret); + } + + else if( c>=66560 && c<66600 ){ + ret = c + 40; + } + + return ret; +} +#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */ +#endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */ + +/************** End of fts3_unicode2.c ***************************************/ +/************** Begin file rtree.c *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code for implementations of the r-tree and r*-tree +** algorithms packaged as an SQLite virtual table module. +*/ + +/* +** Database Format of R-Tree Tables +** -------------------------------- +** +** The data structure for a single virtual r-tree table is stored in three +** native SQLite tables declared as follows. In each case, the '%' character +** in the table name is replaced with the user-supplied name of the r-tree +** table. +** +** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB) +** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER) +** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER) +** +** The data for each node of the r-tree structure is stored in the %_node +** table. For each node that is not the root node of the r-tree, there is +** an entry in the %_parent table associating the node with its parent. +** And for each row of data in the table, there is an entry in the %_rowid +** table that maps from the entries rowid to the id of the node that it +** is stored on. +** +** The root node of an r-tree always exists, even if the r-tree table is +** empty. The nodeno of the root node is always 1. All other nodes in the +** table must be the same size as the root node. The content of each node +** is formatted as follows: +** +** 1. If the node is the root node (node 1), then the first 2 bytes +** of the node contain the tree depth as a big-endian integer. +** For non-root nodes, the first 2 bytes are left unused. +** +** 2. The next 2 bytes contain the number of entries currently +** stored in the node. +** +** 3. The remainder of the node contains the node entries. Each entry +** consists of a single 8-byte integer followed by an even number +** of 4-byte coordinates. For leaf nodes the integer is the rowid +** of a record. For internal nodes it is the node number of a +** child page. +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE) + +/* +** This file contains an implementation of a couple of different variants +** of the r-tree algorithm. See the README file for further details. The +** same data-structure is used for all, but the algorithms for insert and +** delete operations vary. The variants used are selected at compile time +** by defining the following symbols: +*/ + +/* Either, both or none of the following may be set to activate +** r*tree variant algorithms. +*/ +#define VARIANT_RSTARTREE_CHOOSESUBTREE 0 +#define VARIANT_RSTARTREE_REINSERT 1 + +/* +** Exactly one of the following must be set to 1. +*/ +#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0 +#define VARIANT_GUTTMAN_LINEAR_SPLIT 0 +#define VARIANT_RSTARTREE_SPLIT 1 + +#define VARIANT_GUTTMAN_SPLIT \ + (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT) + +#if VARIANT_GUTTMAN_QUADRATIC_SPLIT + #define PickNext QuadraticPickNext + #define PickSeeds QuadraticPickSeeds + #define AssignCells splitNodeGuttman +#endif +#if VARIANT_GUTTMAN_LINEAR_SPLIT + #define PickNext LinearPickNext + #define PickSeeds LinearPickSeeds + #define AssignCells splitNodeGuttman +#endif +#if VARIANT_RSTARTREE_SPLIT + #define AssignCells splitNodeStartree +#endif + +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif + +#ifndef SQLITE_CORE + SQLITE_EXTENSION_INIT1 +#else +#endif + +/* #include */ +/* #include */ + +#ifndef SQLITE_AMALGAMATION +#include "sqlite3rtree.h" +typedef sqlite3_int64 i64; +typedef unsigned char u8; +typedef unsigned int u32; +#endif + +/* The following macro is used to suppress compiler warnings. +*/ +#ifndef UNUSED_PARAMETER +# define UNUSED_PARAMETER(x) (void)(x) +#endif + +typedef struct Rtree Rtree; +typedef struct RtreeCursor RtreeCursor; +typedef struct RtreeNode RtreeNode; +typedef struct RtreeCell RtreeCell; +typedef struct RtreeConstraint RtreeConstraint; +typedef struct RtreeMatchArg RtreeMatchArg; +typedef struct RtreeGeomCallback RtreeGeomCallback; +typedef union RtreeCoord RtreeCoord; + +/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */ +#define RTREE_MAX_DIMENSIONS 5 + +/* Size of hash table Rtree.aHash. This hash table is not expected to +** ever contain very many entries, so a fixed number of buckets is +** used. +*/ +#define HASHSIZE 128 + +/* +** An rtree virtual-table object. +*/ +struct Rtree { + sqlite3_vtab base; + sqlite3 *db; /* Host database connection */ + int iNodeSize; /* Size in bytes of each node in the node table */ + int nDim; /* Number of dimensions */ + int nBytesPerCell; /* Bytes consumed per cell */ + int iDepth; /* Current depth of the r-tree structure */ + char *zDb; /* Name of database containing r-tree table */ + char *zName; /* Name of r-tree table */ + RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ + int nBusy; /* Current number of users of this structure */ + + /* List of nodes removed during a CondenseTree operation. List is + ** linked together via the pointer normally used for hash chains - + ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree + ** headed by the node (leaf nodes have RtreeNode.iNode==0). + */ + RtreeNode *pDeleted; + int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */ + + /* Statements to read/write/delete a record from xxx_node */ + sqlite3_stmt *pReadNode; + sqlite3_stmt *pWriteNode; + sqlite3_stmt *pDeleteNode; + + /* Statements to read/write/delete a record from xxx_rowid */ + sqlite3_stmt *pReadRowid; + sqlite3_stmt *pWriteRowid; + sqlite3_stmt *pDeleteRowid; + + /* Statements to read/write/delete a record from xxx_parent */ + sqlite3_stmt *pReadParent; + sqlite3_stmt *pWriteParent; + sqlite3_stmt *pDeleteParent; + + int eCoordType; +}; + +/* Possible values for eCoordType: */ +#define RTREE_COORD_REAL32 0 +#define RTREE_COORD_INT32 1 + +/* +** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will +** only deal with integer coordinates. No floating point operations +** will be done. +*/ +#ifdef SQLITE_RTREE_INT_ONLY + typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */ + typedef int RtreeValue; /* Low accuracy coordinate */ +#else + typedef double RtreeDValue; /* High accuracy coordinate */ + typedef float RtreeValue; /* Low accuracy coordinate */ +#endif + +/* +** The minimum number of cells allowed for a node is a third of the +** maximum. In Gutman's notation: +** +** m = M/3 +** +** If an R*-tree "Reinsert" operation is required, the same number of +** cells are removed from the overfull node and reinserted into the tree. +*/ +#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3) +#define RTREE_REINSERT(p) RTREE_MINCELLS(p) +#define RTREE_MAXCELLS 51 + +/* +** The smallest possible node-size is (512-64)==448 bytes. And the largest +** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates). +** Therefore all non-root nodes must contain at least 3 entries. Since +** 2^40 is greater than 2^64, an r-tree structure always has a depth of +** 40 or less. +*/ +#define RTREE_MAX_DEPTH 40 + +/* +** An rtree cursor object. +*/ +struct RtreeCursor { + sqlite3_vtab_cursor base; + RtreeNode *pNode; /* Node cursor is currently pointing at */ + int iCell; /* Index of current cell in pNode */ + int iStrategy; /* Copy of idxNum search parameter */ + int nConstraint; /* Number of entries in aConstraint */ + RtreeConstraint *aConstraint; /* Search constraints. */ +}; + +union RtreeCoord { + RtreeValue f; + int i; +}; + +/* +** The argument is an RtreeCoord. Return the value stored within the RtreeCoord +** formatted as a RtreeDValue (double or int64). This macro assumes that local +** variable pRtree points to the Rtree structure associated with the +** RtreeCoord. +*/ +#ifdef SQLITE_RTREE_INT_ONLY +# define DCOORD(coord) ((RtreeDValue)coord.i) +#else +# define DCOORD(coord) ( \ + (pRtree->eCoordType==RTREE_COORD_REAL32) ? \ + ((double)coord.f) : \ + ((double)coord.i) \ + ) +#endif + +/* +** A search constraint. +*/ +struct RtreeConstraint { + int iCoord; /* Index of constrained coordinate */ + int op; /* Constraining operation */ + RtreeDValue rValue; /* Constraint value. */ + int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*); + sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */ +}; + +/* Possible values for RtreeConstraint.op */ +#define RTREE_EQ 0x41 +#define RTREE_LE 0x42 +#define RTREE_LT 0x43 +#define RTREE_GE 0x44 +#define RTREE_GT 0x45 +#define RTREE_MATCH 0x46 + +/* +** An rtree structure node. +*/ +struct RtreeNode { + RtreeNode *pParent; /* Parent node */ + i64 iNode; + int nRef; + int isDirty; + u8 *zData; + RtreeNode *pNext; /* Next node in this hash chain */ +}; +#define NCELL(pNode) readInt16(&(pNode)->zData[2]) + +/* +** Structure to store a deserialized rtree record. +*/ +struct RtreeCell { + i64 iRowid; + RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; +}; + + +/* +** Value for the first field of every RtreeMatchArg object. The MATCH +** operator tests that the first field of a blob operand matches this +** value to avoid operating on invalid blobs (which could cause a segfault). +*/ +#define RTREE_GEOMETRY_MAGIC 0x891245AB + +/* +** An instance of this structure must be supplied as a blob argument to +** the right-hand-side of an SQL MATCH operator used to constrain an +** r-tree query. +*/ +struct RtreeMatchArg { + u32 magic; /* Always RTREE_GEOMETRY_MAGIC */ + int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *); + void *pContext; + int nParam; + RtreeDValue aParam[1]; +}; + +/* +** When a geometry callback is created (see sqlite3_rtree_geometry_callback), +** a single instance of the following structure is allocated. It is used +** as the context for the user-function created by by s_r_g_c(). The object +** is eventually deleted by the destructor mechanism provided by +** sqlite3_create_function_v2() (which is called by s_r_g_c() to create +** the geometry callback function). +*/ +struct RtreeGeomCallback { + int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*); + void *pContext; +}; + +#ifndef MAX +# define MAX(x,y) ((x) < (y) ? (y) : (x)) +#endif +#ifndef MIN +# define MIN(x,y) ((x) > (y) ? (y) : (x)) +#endif + +/* +** Functions to deserialize a 16 bit integer, 32 bit real number and +** 64 bit integer. The deserialized value is returned. +*/ +static int readInt16(u8 *p){ + return (p[0]<<8) + p[1]; +} +static void readCoord(u8 *p, RtreeCoord *pCoord){ + u32 i = ( + (((u32)p[0]) << 24) + + (((u32)p[1]) << 16) + + (((u32)p[2]) << 8) + + (((u32)p[3]) << 0) + ); + *(u32 *)pCoord = i; +} +static i64 readInt64(u8 *p){ + return ( + (((i64)p[0]) << 56) + + (((i64)p[1]) << 48) + + (((i64)p[2]) << 40) + + (((i64)p[3]) << 32) + + (((i64)p[4]) << 24) + + (((i64)p[5]) << 16) + + (((i64)p[6]) << 8) + + (((i64)p[7]) << 0) + ); +} + +/* +** Functions to serialize a 16 bit integer, 32 bit real number and +** 64 bit integer. The value returned is the number of bytes written +** to the argument buffer (always 2, 4 and 8 respectively). +*/ +static int writeInt16(u8 *p, int i){ + p[0] = (i>> 8)&0xFF; + p[1] = (i>> 0)&0xFF; + return 2; +} +static int writeCoord(u8 *p, RtreeCoord *pCoord){ + u32 i; + assert( sizeof(RtreeCoord)==4 ); + assert( sizeof(u32)==4 ); + i = *(u32 *)pCoord; + p[0] = (i>>24)&0xFF; + p[1] = (i>>16)&0xFF; + p[2] = (i>> 8)&0xFF; + p[3] = (i>> 0)&0xFF; + return 4; +} +static int writeInt64(u8 *p, i64 i){ + p[0] = (i>>56)&0xFF; + p[1] = (i>>48)&0xFF; + p[2] = (i>>40)&0xFF; + p[3] = (i>>32)&0xFF; + p[4] = (i>>24)&0xFF; + p[5] = (i>>16)&0xFF; + p[6] = (i>> 8)&0xFF; + p[7] = (i>> 0)&0xFF; + return 8; +} + +/* +** Increment the reference count of node p. +*/ +static void nodeReference(RtreeNode *p){ + if( p ){ + p->nRef++; + } +} + +/* +** Clear the content of node p (set all bytes to 0x00). +*/ +static void nodeZero(Rtree *pRtree, RtreeNode *p){ + memset(&p->zData[2], 0, pRtree->iNodeSize-2); + p->isDirty = 1; +} + +/* +** Given a node number iNode, return the corresponding key to use +** in the Rtree.aHash table. +*/ +static int nodeHash(i64 iNode){ + return ( + (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ + (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0) + ) % HASHSIZE; +} + +/* +** Search the node hash table for node iNode. If found, return a pointer +** to it. Otherwise, return 0. +*/ +static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){ + RtreeNode *p; + for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext); + return p; +} + +/* +** Add node pNode to the node hash table. +*/ +static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){ + int iHash; + assert( pNode->pNext==0 ); + iHash = nodeHash(pNode->iNode); + pNode->pNext = pRtree->aHash[iHash]; + pRtree->aHash[iHash] = pNode; +} + +/* +** Remove node pNode from the node hash table. +*/ +static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){ + RtreeNode **pp; + if( pNode->iNode!=0 ){ + pp = &pRtree->aHash[nodeHash(pNode->iNode)]; + for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); } + *pp = pNode->pNext; + pNode->pNext = 0; + } +} + +/* +** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0), +** indicating that node has not yet been assigned a node number. It is +** assigned a node number when nodeWrite() is called to write the +** node contents out to the database. +*/ +static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){ + RtreeNode *pNode; + pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); + if( pNode ){ + memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize); + pNode->zData = (u8 *)&pNode[1]; + pNode->nRef = 1; + pNode->pParent = pParent; + pNode->isDirty = 1; + nodeReference(pParent); + } + return pNode; +} + +/* +** Obtain a reference to an r-tree node. +*/ +static int +nodeAcquire( + Rtree *pRtree, /* R-tree structure */ + i64 iNode, /* Node number to load */ + RtreeNode *pParent, /* Either the parent node or NULL */ + RtreeNode **ppNode /* OUT: Acquired node */ +){ + int rc; + int rc2 = SQLITE_OK; + RtreeNode *pNode; + + /* Check if the requested node is already in the hash table. If so, + ** increase its reference count and return it. + */ + if( (pNode = nodeHashLookup(pRtree, iNode)) ){ + assert( !pParent || !pNode->pParent || pNode->pParent==pParent ); + if( pParent && !pNode->pParent ){ + nodeReference(pParent); + pNode->pParent = pParent; + } + pNode->nRef++; + *ppNode = pNode; + return SQLITE_OK; + } + + sqlite3_bind_int64(pRtree->pReadNode, 1, iNode); + rc = sqlite3_step(pRtree->pReadNode); + if( rc==SQLITE_ROW ){ + const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0); + if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){ + pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize); + if( !pNode ){ + rc2 = SQLITE_NOMEM; + }else{ + pNode->pParent = pParent; + pNode->zData = (u8 *)&pNode[1]; + pNode->nRef = 1; + pNode->iNode = iNode; + pNode->isDirty = 0; + pNode->pNext = 0; + memcpy(pNode->zData, zBlob, pRtree->iNodeSize); + nodeReference(pParent); + } + } + } + rc = sqlite3_reset(pRtree->pReadNode); + if( rc==SQLITE_OK ) rc = rc2; + + /* If the root node was just loaded, set pRtree->iDepth to the height + ** of the r-tree structure. A height of zero means all data is stored on + ** the root node. A height of one means the children of the root node + ** are the leaves, and so on. If the depth as specified on the root node + ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt. + */ + if( pNode && iNode==1 ){ + pRtree->iDepth = readInt16(pNode->zData); + if( pRtree->iDepth>RTREE_MAX_DEPTH ){ + rc = SQLITE_CORRUPT_VTAB; + } + } + + /* If no error has occurred so far, check if the "number of entries" + ** field on the node is too large. If so, set the return code to + ** SQLITE_CORRUPT_VTAB. + */ + if( pNode && rc==SQLITE_OK ){ + if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){ + rc = SQLITE_CORRUPT_VTAB; + } + } + + if( rc==SQLITE_OK ){ + if( pNode!=0 ){ + nodeHashInsert(pRtree, pNode); + }else{ + rc = SQLITE_CORRUPT_VTAB; + } + *ppNode = pNode; + }else{ + sqlite3_free(pNode); + *ppNode = 0; + } + + return rc; +} + +/* +** Overwrite cell iCell of node pNode with the contents of pCell. +*/ +static void nodeOverwriteCell( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell, + int iCell +){ + int ii; + u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; + p += writeInt64(p, pCell->iRowid); + for(ii=0; ii<(pRtree->nDim*2); ii++){ + p += writeCoord(p, &pCell->aCoord[ii]); + } + pNode->isDirty = 1; +} + +/* +** Remove cell the cell with index iCell from node pNode. +*/ +static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){ + u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; + u8 *pSrc = &pDst[pRtree->nBytesPerCell]; + int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell; + memmove(pDst, pSrc, nByte); + writeInt16(&pNode->zData[2], NCELL(pNode)-1); + pNode->isDirty = 1; +} + +/* +** Insert the contents of cell pCell into node pNode. If the insert +** is successful, return SQLITE_OK. +** +** If there is not enough free space in pNode, return SQLITE_FULL. +*/ +static int +nodeInsertCell( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell +){ + int nCell; /* Current number of cells in pNode */ + int nMaxCell; /* Maximum number of cells for pNode */ + + nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell; + nCell = NCELL(pNode); + + assert( nCell<=nMaxCell ); + if( nCellzData[2], nCell+1); + pNode->isDirty = 1; + } + + return (nCell==nMaxCell); +} + +/* +** If the node is dirty, write it out to the database. +*/ +static int +nodeWrite(Rtree *pRtree, RtreeNode *pNode){ + int rc = SQLITE_OK; + if( pNode->isDirty ){ + sqlite3_stmt *p = pRtree->pWriteNode; + if( pNode->iNode ){ + sqlite3_bind_int64(p, 1, pNode->iNode); + }else{ + sqlite3_bind_null(p, 1); + } + sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); + sqlite3_step(p); + pNode->isDirty = 0; + rc = sqlite3_reset(p); + if( pNode->iNode==0 && rc==SQLITE_OK ){ + pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); + nodeHashInsert(pRtree, pNode); + } + } + return rc; +} + +/* +** Release a reference to a node. If the node is dirty and the reference +** count drops to zero, the node data is written to the database. +*/ +static int +nodeRelease(Rtree *pRtree, RtreeNode *pNode){ + int rc = SQLITE_OK; + if( pNode ){ + assert( pNode->nRef>0 ); + pNode->nRef--; + if( pNode->nRef==0 ){ + if( pNode->iNode==1 ){ + pRtree->iDepth = -1; + } + if( pNode->pParent ){ + rc = nodeRelease(pRtree, pNode->pParent); + } + if( rc==SQLITE_OK ){ + rc = nodeWrite(pRtree, pNode); + } + nodeHashDelete(pRtree, pNode); + sqlite3_free(pNode); + } + } + return rc; +} + +/* +** Return the 64-bit integer value associated with cell iCell of +** node pNode. If pNode is a leaf node, this is a rowid. If it is +** an internal node, then the 64-bit integer is a child page number. +*/ +static i64 nodeGetRowid( + Rtree *pRtree, + RtreeNode *pNode, + int iCell +){ + assert( iCellzData[4 + pRtree->nBytesPerCell*iCell]); +} + +/* +** Return coordinate iCoord from cell iCell in node pNode. +*/ +static void nodeGetCoord( + Rtree *pRtree, + RtreeNode *pNode, + int iCell, + int iCoord, + RtreeCoord *pCoord /* Space to write result to */ +){ + readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord); +} + +/* +** Deserialize cell iCell of node pNode. Populate the structure pointed +** to by pCell with the results. +*/ +static void nodeGetCell( + Rtree *pRtree, + RtreeNode *pNode, + int iCell, + RtreeCell *pCell +){ + int ii; + pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell); + for(ii=0; iinDim*2; ii++){ + nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]); + } +} + + +/* Forward declaration for the function that does the work of +** the virtual table module xCreate() and xConnect() methods. +*/ +static int rtreeInit( + sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int +); + +/* +** Rtree virtual table module xCreate method. +*/ +static int rtreeCreate( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1); +} + +/* +** Rtree virtual table module xConnect method. +*/ +static int rtreeConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0); +} + +/* +** Increment the r-tree reference count. +*/ +static void rtreeReference(Rtree *pRtree){ + pRtree->nBusy++; +} + +/* +** Decrement the r-tree reference count. When the reference count reaches +** zero the structure is deleted. +*/ +static void rtreeRelease(Rtree *pRtree){ + pRtree->nBusy--; + if( pRtree->nBusy==0 ){ + sqlite3_finalize(pRtree->pReadNode); + sqlite3_finalize(pRtree->pWriteNode); + sqlite3_finalize(pRtree->pDeleteNode); + sqlite3_finalize(pRtree->pReadRowid); + sqlite3_finalize(pRtree->pWriteRowid); + sqlite3_finalize(pRtree->pDeleteRowid); + sqlite3_finalize(pRtree->pReadParent); + sqlite3_finalize(pRtree->pWriteParent); + sqlite3_finalize(pRtree->pDeleteParent); + sqlite3_free(pRtree); + } +} + +/* +** Rtree virtual table module xDisconnect method. +*/ +static int rtreeDisconnect(sqlite3_vtab *pVtab){ + rtreeRelease((Rtree *)pVtab); + return SQLITE_OK; +} + +/* +** Rtree virtual table module xDestroy method. +*/ +static int rtreeDestroy(sqlite3_vtab *pVtab){ + Rtree *pRtree = (Rtree *)pVtab; + int rc; + char *zCreate = sqlite3_mprintf( + "DROP TABLE '%q'.'%q_node';" + "DROP TABLE '%q'.'%q_rowid';" + "DROP TABLE '%q'.'%q_parent';", + pRtree->zDb, pRtree->zName, + pRtree->zDb, pRtree->zName, + pRtree->zDb, pRtree->zName + ); + if( !zCreate ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0); + sqlite3_free(zCreate); + } + if( rc==SQLITE_OK ){ + rtreeRelease(pRtree); + } + + return rc; +} + +/* +** Rtree virtual table module xOpen method. +*/ +static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + int rc = SQLITE_NOMEM; + RtreeCursor *pCsr; + + pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor)); + if( pCsr ){ + memset(pCsr, 0, sizeof(RtreeCursor)); + pCsr->base.pVtab = pVTab; + rc = SQLITE_OK; + } + *ppCursor = (sqlite3_vtab_cursor *)pCsr; + + return rc; +} + + +/* +** Free the RtreeCursor.aConstraint[] array and its contents. +*/ +static void freeCursorConstraints(RtreeCursor *pCsr){ + if( pCsr->aConstraint ){ + int i; /* Used to iterate through constraint array */ + for(i=0; inConstraint; i++){ + sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom; + if( pGeom ){ + if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser); + sqlite3_free(pGeom); + } + } + sqlite3_free(pCsr->aConstraint); + pCsr->aConstraint = 0; + } +} + +/* +** Rtree virtual table module xClose method. +*/ +static int rtreeClose(sqlite3_vtab_cursor *cur){ + Rtree *pRtree = (Rtree *)(cur->pVtab); + int rc; + RtreeCursor *pCsr = (RtreeCursor *)cur; + freeCursorConstraints(pCsr); + rc = nodeRelease(pRtree, pCsr->pNode); + sqlite3_free(pCsr); + return rc; +} + +/* +** Rtree virtual table module xEof method. +** +** Return non-zero if the cursor does not currently point to a valid +** record (i.e if the scan has finished), or zero otherwise. +*/ +static int rtreeEof(sqlite3_vtab_cursor *cur){ + RtreeCursor *pCsr = (RtreeCursor *)cur; + return (pCsr->pNode==0); +} + +/* +** The r-tree constraint passed as the second argument to this function is +** guaranteed to be a MATCH constraint. +*/ +static int testRtreeGeom( + Rtree *pRtree, /* R-Tree object */ + RtreeConstraint *pConstraint, /* MATCH constraint to test */ + RtreeCell *pCell, /* Cell to test */ + int *pbRes /* OUT: Test result */ +){ + int i; + RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2]; + int nCoord = pRtree->nDim*2; + + assert( pConstraint->op==RTREE_MATCH ); + assert( pConstraint->pGeom ); + + for(i=0; iaCoord[i]); + } + return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes); +} + +/* +** Cursor pCursor currently points to a cell in a non-leaf page. +** Set *pbEof to true if the sub-tree headed by the cell is filtered +** (excluded) by the constraints in the pCursor->aConstraint[] +** array, or false otherwise. +** +** Return SQLITE_OK if successful or an SQLite error code if an error +** occurs within a geometry callback. +*/ +static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){ + RtreeCell cell; + int ii; + int bRes = 0; + int rc = SQLITE_OK; + + nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell); + for(ii=0; bRes==0 && iinConstraint; ii++){ + RtreeConstraint *p = &pCursor->aConstraint[ii]; + RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]); + RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]); + + assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE + || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH + ); + + switch( p->op ){ + case RTREE_LE: case RTREE_LT: + bRes = p->rValuerValue>cell_max; + break; + + case RTREE_EQ: + bRes = (p->rValue>cell_max || p->rValueop==RTREE_MATCH ); + rc = testRtreeGeom(pRtree, p, &cell, &bRes); + bRes = !bRes; + break; + } + } + } + + *pbEof = bRes; + return rc; +} + +/* +** Test if the cell that cursor pCursor currently points to +** would be filtered (excluded) by the constraints in the +** pCursor->aConstraint[] array. If so, set *pbEof to true before +** returning. If the cell is not filtered (excluded) by the constraints, +** set pbEof to zero. +** +** Return SQLITE_OK if successful or an SQLite error code if an error +** occurs within a geometry callback. +** +** This function assumes that the cell is part of a leaf node. +*/ +static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){ + RtreeCell cell; + int ii; + *pbEof = 0; + + nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell); + for(ii=0; iinConstraint; ii++){ + RtreeConstraint *p = &pCursor->aConstraint[ii]; + RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]); + int res; + assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE + || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH + ); + switch( p->op ){ + case RTREE_LE: res = (coord<=p->rValue); break; + case RTREE_LT: res = (coordrValue); break; + case RTREE_GE: res = (coord>=p->rValue); break; + case RTREE_GT: res = (coord>p->rValue); break; + case RTREE_EQ: res = (coord==p->rValue); break; + default: { + int rc; + assert( p->op==RTREE_MATCH ); + rc = testRtreeGeom(pRtree, p, &cell, &res); + if( rc!=SQLITE_OK ){ + return rc; + } + break; + } + } + + if( !res ){ + *pbEof = 1; + return SQLITE_OK; + } + } + + return SQLITE_OK; +} + +/* +** Cursor pCursor currently points at a node that heads a sub-tree of +** height iHeight (if iHeight==0, then the node is a leaf). Descend +** to point to the left-most cell of the sub-tree that matches the +** configured constraints. +*/ +static int descendToCell( + Rtree *pRtree, + RtreeCursor *pCursor, + int iHeight, + int *pEof /* OUT: Set to true if cannot descend */ +){ + int isEof; + int rc; + int ii; + RtreeNode *pChild; + sqlite3_int64 iRowid; + + RtreeNode *pSavedNode = pCursor->pNode; + int iSavedCell = pCursor->iCell; + + assert( iHeight>=0 ); + + if( iHeight==0 ){ + rc = testRtreeEntry(pRtree, pCursor, &isEof); + }else{ + rc = testRtreeCell(pRtree, pCursor, &isEof); + } + if( rc!=SQLITE_OK || isEof || iHeight==0 ){ + goto descend_to_cell_out; + } + + iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell); + rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild); + if( rc!=SQLITE_OK ){ + goto descend_to_cell_out; + } + + nodeRelease(pRtree, pCursor->pNode); + pCursor->pNode = pChild; + isEof = 1; + for(ii=0; isEof && iiiCell = ii; + rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof); + if( rc!=SQLITE_OK ){ + goto descend_to_cell_out; + } + } + + if( isEof ){ + assert( pCursor->pNode==pChild ); + nodeReference(pSavedNode); + nodeRelease(pRtree, pChild); + pCursor->pNode = pSavedNode; + pCursor->iCell = iSavedCell; + } + +descend_to_cell_out: + *pEof = isEof; + return rc; +} + +/* +** One of the cells in node pNode is guaranteed to have a 64-bit +** integer value equal to iRowid. Return the index of this cell. +*/ +static int nodeRowidIndex( + Rtree *pRtree, + RtreeNode *pNode, + i64 iRowid, + int *piIndex +){ + int ii; + int nCell = NCELL(pNode); + for(ii=0; iipParent; + if( pParent ){ + return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex); + } + *piIndex = -1; + return SQLITE_OK; +} + +/* +** Rtree virtual table module xNext method. +*/ +static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ + Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab); + RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; + int rc = SQLITE_OK; + + /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is + ** already at EOF. It is against the rules to call the xNext() method of + ** a cursor that has already reached EOF. + */ + assert( pCsr->pNode ); + + if( pCsr->iStrategy==1 ){ + /* This "scan" is a direct lookup by rowid. There is no next entry. */ + nodeRelease(pRtree, pCsr->pNode); + pCsr->pNode = 0; + }else{ + /* Move to the next entry that matches the configured constraints. */ + int iHeight = 0; + while( pCsr->pNode ){ + RtreeNode *pNode = pCsr->pNode; + int nCell = NCELL(pNode); + for(pCsr->iCell++; pCsr->iCelliCell++){ + int isEof; + rc = descendToCell(pRtree, pCsr, iHeight, &isEof); + if( rc!=SQLITE_OK || !isEof ){ + return rc; + } + } + pCsr->pNode = pNode->pParent; + rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell); + if( rc!=SQLITE_OK ){ + return rc; + } + nodeReference(pCsr->pNode); + nodeRelease(pRtree, pNode); + iHeight++; + } + } + + return rc; +} + +/* +** Rtree virtual table module xRowid method. +*/ +static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ + Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; + RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; + + assert(pCsr->pNode); + *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell); + + return SQLITE_OK; +} + +/* +** Rtree virtual table module xColumn method. +*/ +static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + Rtree *pRtree = (Rtree *)cur->pVtab; + RtreeCursor *pCsr = (RtreeCursor *)cur; + + if( i==0 ){ + i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell); + sqlite3_result_int64(ctx, iRowid); + }else{ + RtreeCoord c; + nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c); +#ifndef SQLITE_RTREE_INT_ONLY + if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ + sqlite3_result_double(ctx, c.f); + }else +#endif + { + assert( pRtree->eCoordType==RTREE_COORD_INT32 ); + sqlite3_result_int(ctx, c.i); + } + } + + return SQLITE_OK; +} + +/* +** Use nodeAcquire() to obtain the leaf node containing the record with +** rowid iRowid. If successful, set *ppLeaf to point to the node and +** return SQLITE_OK. If there is no such record in the table, set +** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf +** to zero and return an SQLite error code. +*/ +static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){ + int rc; + *ppLeaf = 0; + sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); + if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ + i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0); + rc = nodeAcquire(pRtree, iNode, 0, ppLeaf); + sqlite3_reset(pRtree->pReadRowid); + }else{ + rc = sqlite3_reset(pRtree->pReadRowid); + } + return rc; +} + +/* +** This function is called to configure the RtreeConstraint object passed +** as the second argument for a MATCH constraint. The value passed as the +** first argument to this function is the right-hand operand to the MATCH +** operator. +*/ +static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){ + RtreeMatchArg *p; + sqlite3_rtree_geometry *pGeom; + int nBlob; + + /* Check that value is actually a blob. */ + if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR; + + /* Check that the blob is roughly the right size. */ + nBlob = sqlite3_value_bytes(pValue); + if( nBlob<(int)sizeof(RtreeMatchArg) + || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0 + ){ + return SQLITE_ERROR; + } + + pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc( + sizeof(sqlite3_rtree_geometry) + nBlob + ); + if( !pGeom ) return SQLITE_NOMEM; + memset(pGeom, 0, sizeof(sqlite3_rtree_geometry)); + p = (RtreeMatchArg *)&pGeom[1]; + + memcpy(p, sqlite3_value_blob(pValue), nBlob); + if( p->magic!=RTREE_GEOMETRY_MAGIC + || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue)) + ){ + sqlite3_free(pGeom); + return SQLITE_ERROR; + } + + pGeom->pContext = p->pContext; + pGeom->nParam = p->nParam; + pGeom->aParam = p->aParam; + + pCons->xGeom = p->xGeom; + pCons->pGeom = pGeom; + return SQLITE_OK; +} + +/* +** Rtree virtual table module xFilter method. +*/ +static int rtreeFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; + RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; + + RtreeNode *pRoot = 0; + int ii; + int rc = SQLITE_OK; + + rtreeReference(pRtree); + + freeCursorConstraints(pCsr); + pCsr->iStrategy = idxNum; + + if( idxNum==1 ){ + /* Special case - lookup by rowid. */ + RtreeNode *pLeaf; /* Leaf on which the required cell resides */ + i64 iRowid = sqlite3_value_int64(argv[0]); + rc = findLeafNode(pRtree, iRowid, &pLeaf); + pCsr->pNode = pLeaf; + if( pLeaf ){ + assert( rc==SQLITE_OK ); + rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell); + } + }else{ + /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array + ** with the configured constraints. + */ + if( argc>0 ){ + pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc); + pCsr->nConstraint = argc; + if( !pCsr->aConstraint ){ + rc = SQLITE_NOMEM; + }else{ + memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc); + assert( (idxStr==0 && argc==0) + || (idxStr && (int)strlen(idxStr)==argc*2) ); + for(ii=0; iiaConstraint[ii]; + p->op = idxStr[ii*2]; + p->iCoord = idxStr[ii*2+1]-'a'; + if( p->op==RTREE_MATCH ){ + /* A MATCH operator. The right-hand-side must be a blob that + ** can be cast into an RtreeMatchArg object. One created using + ** an sqlite3_rtree_geometry_callback() SQL user function. + */ + rc = deserializeGeometry(argv[ii], p); + if( rc!=SQLITE_OK ){ + break; + } + }else{ +#ifdef SQLITE_RTREE_INT_ONLY + p->rValue = sqlite3_value_int64(argv[ii]); +#else + p->rValue = sqlite3_value_double(argv[ii]); +#endif + } + } + } + } + + if( rc==SQLITE_OK ){ + pCsr->pNode = 0; + rc = nodeAcquire(pRtree, 1, 0, &pRoot); + } + if( rc==SQLITE_OK ){ + int isEof = 1; + int nCell = NCELL(pRoot); + pCsr->pNode = pRoot; + for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCelliCell++){ + assert( pCsr->pNode==pRoot ); + rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof); + if( !isEof ){ + break; + } + } + if( rc==SQLITE_OK && isEof ){ + assert( pCsr->pNode==pRoot ); + nodeRelease(pRtree, pRoot); + pCsr->pNode = 0; + } + assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCellpNode) ); + } + } + + rtreeRelease(pRtree); + return rc; +} + +/* +** Rtree virtual table module xBestIndex method. There are three +** table scan strategies to choose from (in order from most to +** least desirable): +** +** idxNum idxStr Strategy +** ------------------------------------------------ +** 1 Unused Direct lookup by rowid. +** 2 See below R-tree query or full-table scan. +** ------------------------------------------------ +** +** If strategy 1 is used, then idxStr is not meaningful. If strategy +** 2 is used, idxStr is formatted to contain 2 bytes for each +** constraint used. The first two bytes of idxStr correspond to +** the constraint in sqlite3_index_info.aConstraintUsage[] with +** (argvIndex==1) etc. +** +** The first of each pair of bytes in idxStr identifies the constraint +** operator as follows: +** +** Operator Byte Value +** ---------------------- +** = 0x41 ('A') +** <= 0x42 ('B') +** < 0x43 ('C') +** >= 0x44 ('D') +** > 0x45 ('E') +** MATCH 0x46 ('F') +** ---------------------- +** +** The second of each pair of bytes identifies the coordinate column +** to which the constraint applies. The leftmost coordinate column +** is 'a', the second from the left 'b' etc. +*/ +static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int rc = SQLITE_OK; + int ii; + + int iIdx = 0; + char zIdxStr[RTREE_MAX_DIMENSIONS*8+1]; + memset(zIdxStr, 0, sizeof(zIdxStr)); + UNUSED_PARAMETER(tab); + + assert( pIdxInfo->idxStr==0 ); + for(ii=0; iinConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){ + struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; + + if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + /* We have an equality constraint on the rowid. Use strategy 1. */ + int jj; + for(jj=0; jjaConstraintUsage[jj].argvIndex = 0; + pIdxInfo->aConstraintUsage[jj].omit = 0; + } + pIdxInfo->idxNum = 1; + pIdxInfo->aConstraintUsage[ii].argvIndex = 1; + pIdxInfo->aConstraintUsage[jj].omit = 1; + + /* This strategy involves a two rowid lookups on an B-Tree structures + ** and then a linear search of an R-Tree node. This should be + ** considered almost as quick as a direct rowid lookup (for which + ** sqlite uses an internal cost of 0.0). + */ + pIdxInfo->estimatedCost = 10.0; + return SQLITE_OK; + } + + if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){ + u8 op; + switch( p->op ){ + case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; + case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; + case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; + case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; + case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; + default: + assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH ); + op = RTREE_MATCH; + break; + } + zIdxStr[iIdx++] = op; + zIdxStr[iIdx++] = p->iColumn - 1 + 'a'; + pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2); + pIdxInfo->aConstraintUsage[ii].omit = 1; + } + } + + pIdxInfo->idxNum = 2; + pIdxInfo->needToFreeIdxStr = 1; + if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ + return SQLITE_NOMEM; + } + assert( iIdx>=0 ); + pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1)); + return rc; +} + +/* +** Return the N-dimensional volumn of the cell stored in *p. +*/ +static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){ + RtreeDValue area = (RtreeDValue)1; + int ii; + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]))); + } + return area; +} + +/* +** Return the margin length of cell p. The margin length is the sum +** of the objects size in each dimension. +*/ +static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){ + RtreeDValue margin = (RtreeDValue)0; + int ii; + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); + } + return margin; +} + +/* +** Store the union of cells p1 and p2 in p1. +*/ +static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ + int ii; + if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f); + p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f); + } + }else{ + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i); + p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i); + } + } +} + +/* +** Return true if the area covered by p2 is a subset of the area covered +** by p1. False otherwise. +*/ +static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ + int ii; + int isInt = (pRtree->eCoordType==RTREE_COORD_INT32); + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + RtreeCoord *a1 = &p1->aCoord[ii]; + RtreeCoord *a2 = &p2->aCoord[ii]; + if( (!isInt && (a2[0].fa1[1].f)) + || ( isInt && (a2[0].ia1[1].i)) + ){ + return 0; + } + } + return 1; +} + +/* +** Return the amount cell p would grow by if it were unioned with pCell. +*/ +static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){ + RtreeDValue area; + RtreeCell cell; + memcpy(&cell, p, sizeof(RtreeCell)); + area = cellArea(pRtree, &cell); + cellUnion(pRtree, &cell, pCell); + return (cellArea(pRtree, &cell)-area); +} + +#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT +static RtreeDValue cellOverlap( + Rtree *pRtree, + RtreeCell *p, + RtreeCell *aCell, + int nCell, + int iExclude +){ + int ii; + RtreeDValue overlap = 0.0; + for(ii=0; iinDim*2); jj+=2){ + RtreeDValue x1, x2; + + x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj])); + x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1])); + + if( x2iDepth-iHeight); ii++){ + int iCell; + sqlite3_int64 iBest = 0; + + RtreeDValue fMinGrowth = 0.0; + RtreeDValue fMinArea = 0.0; +#if VARIANT_RSTARTREE_CHOOSESUBTREE + RtreeDValue fMinOverlap = 0.0; + RtreeDValue overlap; +#endif + + int nCell = NCELL(pNode); + RtreeCell cell; + RtreeNode *pChild; + + RtreeCell *aCell = 0; + +#if VARIANT_RSTARTREE_CHOOSESUBTREE + if( ii==(pRtree->iDepth-1) ){ + int jj; + aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell); + if( !aCell ){ + rc = SQLITE_NOMEM; + nodeRelease(pRtree, pNode); + pNode = 0; + continue; + } + for(jj=0; jjiDepth-1) ){ + overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell); + }else{ + overlap = 0.0; + } + if( (iCell==0) + || (overlappParent ){ + RtreeNode *pParent = p->pParent; + RtreeCell cell; + int iCell; + + if( nodeParentIndex(pRtree, p, &iCell) ){ + return SQLITE_CORRUPT_VTAB; + } + + nodeGetCell(pRtree, pParent, iCell, &cell); + if( !cellContains(pRtree, &cell, pCell) ){ + cellUnion(pRtree, &cell, pCell); + nodeOverwriteCell(pRtree, pParent, &cell, iCell); + } + + p = pParent; + } + return SQLITE_OK; +} + +/* +** Write mapping (iRowid->iNode) to the _rowid table. +*/ +static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){ + sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); + sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); + sqlite3_step(pRtree->pWriteRowid); + return sqlite3_reset(pRtree->pWriteRowid); +} + +/* +** Write mapping (iNode->iPar) to the _parent table. +*/ +static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){ + sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); + sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); + sqlite3_step(pRtree->pWriteParent); + return sqlite3_reset(pRtree->pWriteParent); +} + +static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int); + +#if VARIANT_GUTTMAN_LINEAR_SPLIT +/* +** Implementation of the linear variant of the PickNext() function from +** Guttman[84]. +*/ +static RtreeCell *LinearPickNext( + Rtree *pRtree, + RtreeCell *aCell, + int nCell, + RtreeCell *pLeftBox, + RtreeCell *pRightBox, + int *aiUsed +){ + int ii; + for(ii=0; aiUsed[ii]; ii++); + aiUsed[ii] = 1; + return &aCell[ii]; +} + +/* +** Implementation of the linear variant of the PickSeeds() function from +** Guttman[84]. +*/ +static void LinearPickSeeds( + Rtree *pRtree, + RtreeCell *aCell, + int nCell, + int *piLeftSeed, + int *piRightSeed +){ + int i; + int iLeftSeed = 0; + int iRightSeed = 1; + RtreeDValue maxNormalInnerWidth = (RtreeDValue)0; + + /* Pick two "seed" cells from the array of cells. The algorithm used + ** here is the LinearPickSeeds algorithm from Gutman[1984]. The + ** indices of the two seed cells in the array are stored in local + ** variables iLeftSeek and iRightSeed. + */ + for(i=0; inDim; i++){ + RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]); + RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]); + RtreeDValue x3 = x1; + RtreeDValue x4 = x2; + int jj; + + int iCellLeft = 0; + int iCellRight = 0; + + for(jj=1; jjx4 ) x4 = right; + if( left>x3 ){ + x3 = left; + iCellRight = jj; + } + if( rightmaxNormalInnerWidth ){ + iLeftSeed = iCellLeft; + iRightSeed = iCellRight; + } + } + } + + *piLeftSeed = iLeftSeed; + *piRightSeed = iRightSeed; +} +#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */ + +#if VARIANT_GUTTMAN_QUADRATIC_SPLIT +/* +** Implementation of the quadratic variant of the PickNext() function from +** Guttman[84]. +*/ +static RtreeCell *QuadraticPickNext( + Rtree *pRtree, + RtreeCell *aCell, + int nCell, + RtreeCell *pLeftBox, + RtreeCell *pRightBox, + int *aiUsed +){ + #define FABS(a) ((a)<0.0?-1.0*(a):(a)) + + int iSelect = -1; + RtreeDValue fDiff; + int ii; + for(ii=0; iifDiff ){ + fDiff = diff; + iSelect = ii; + } + } + } + aiUsed[iSelect] = 1; + return &aCell[iSelect]; +} + +/* +** Implementation of the quadratic variant of the PickSeeds() function from +** Guttman[84]. +*/ +static void QuadraticPickSeeds( + Rtree *pRtree, + RtreeCell *aCell, + int nCell, + int *piLeftSeed, + int *piRightSeed +){ + int ii; + int jj; + + int iLeftSeed = 0; + int iRightSeed = 1; + RtreeDValue fWaste = 0.0; + + for(ii=0; iifWaste ){ + iLeftSeed = ii; + iRightSeed = jj; + fWaste = waste; + } + } + } + + *piLeftSeed = iLeftSeed; + *piRightSeed = iRightSeed; +} +#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */ + +/* +** Arguments aIdx, aDistance and aSpare all point to arrays of size +** nIdx. The aIdx array contains the set of integers from 0 to +** (nIdx-1) in no particular order. This function sorts the values +** in aIdx according to the indexed values in aDistance. For +** example, assuming the inputs: +** +** aIdx = { 0, 1, 2, 3 } +** aDistance = { 5.0, 2.0, 7.0, 6.0 } +** +** this function sets the aIdx array to contain: +** +** aIdx = { 0, 1, 2, 3 } +** +** The aSpare array is used as temporary working space by the +** sorting algorithm. +*/ +static void SortByDistance( + int *aIdx, + int nIdx, + RtreeDValue *aDistance, + int *aSpare +){ + if( nIdx>1 ){ + int iLeft = 0; + int iRight = 0; + + int nLeft = nIdx/2; + int nRight = nIdx-nLeft; + int *aLeft = aIdx; + int *aRight = &aIdx[nLeft]; + + SortByDistance(aLeft, nLeft, aDistance, aSpare); + SortByDistance(aRight, nRight, aDistance, aSpare); + + memcpy(aSpare, aLeft, sizeof(int)*nLeft); + aLeft = aSpare; + + while( iLeft1 ){ + + int iLeft = 0; + int iRight = 0; + + int nLeft = nIdx/2; + int nRight = nIdx-nLeft; + int *aLeft = aIdx; + int *aRight = &aIdx[nLeft]; + + SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare); + SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare); + + memcpy(aSpare, aLeft, sizeof(int)*nLeft); + aLeft = aSpare; + while( iLeftnDim+1)*(sizeof(int*)+nCell*sizeof(int)); + + aaSorted = (int **)sqlite3_malloc(nByte); + if( !aaSorted ){ + return SQLITE_NOMEM; + } + + aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell]; + memset(aaSorted, 0, nByte); + for(ii=0; iinDim; ii++){ + int jj; + aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell]; + for(jj=0; jjnDim; ii++){ + RtreeDValue margin = 0.0; + RtreeDValue fBestOverlap = 0.0; + RtreeDValue fBestArea = 0.0; + int iBestLeft = 0; + int nLeft; + + for( + nLeft=RTREE_MINCELLS(pRtree); + nLeft<=(nCell-RTREE_MINCELLS(pRtree)); + nLeft++ + ){ + RtreeCell left; + RtreeCell right; + int kk; + RtreeDValue overlap; + RtreeDValue area; + + memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell)); + memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell)); + for(kk=1; kk<(nCell-1); kk++){ + if( kk0; i--){ + RtreeCell *pNext; + pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed); + RtreeDValue diff = + cellGrowth(pRtree, pBboxLeft, pNext) - + cellGrowth(pRtree, pBboxRight, pNext) + ; + if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i) + || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i)) + ){ + nodeInsertCell(pRtree, pRight, pNext); + cellUnion(pRtree, pBboxRight, pNext); + }else{ + nodeInsertCell(pRtree, pLeft, pNext); + cellUnion(pRtree, pBboxLeft, pNext); + } + } + + sqlite3_free(aiUsed); + return SQLITE_OK; +} +#endif + +static int updateMapping( + Rtree *pRtree, + i64 iRowid, + RtreeNode *pNode, + int iHeight +){ + int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64); + xSetMapping = ((iHeight==0)?rowidWrite:parentWrite); + if( iHeight>0 ){ + RtreeNode *pChild = nodeHashLookup(pRtree, iRowid); + if( pChild ){ + nodeRelease(pRtree, pChild->pParent); + nodeReference(pNode); + pChild->pParent = pNode; + } + } + return xSetMapping(pRtree, iRowid, pNode->iNode); +} + +static int SplitNode( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell, + int iHeight +){ + int i; + int newCellIsRight = 0; + + int rc = SQLITE_OK; + int nCell = NCELL(pNode); + RtreeCell *aCell; + int *aiUsed; + + RtreeNode *pLeft = 0; + RtreeNode *pRight = 0; + + RtreeCell leftbbox; + RtreeCell rightbbox; + + /* Allocate an array and populate it with a copy of pCell and + ** all cells from node pLeft. Then zero the original node. + */ + aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); + if( !aCell ){ + rc = SQLITE_NOMEM; + goto splitnode_out; + } + aiUsed = (int *)&aCell[nCell+1]; + memset(aiUsed, 0, sizeof(int)*(nCell+1)); + for(i=0; iiNode==1 ){ + pRight = nodeNew(pRtree, pNode); + pLeft = nodeNew(pRtree, pNode); + pRtree->iDepth++; + pNode->isDirty = 1; + writeInt16(pNode->zData, pRtree->iDepth); + }else{ + pLeft = pNode; + pRight = nodeNew(pRtree, pLeft->pParent); + nodeReference(pLeft); + } + + if( !pLeft || !pRight ){ + rc = SQLITE_NOMEM; + goto splitnode_out; + } + + memset(pLeft->zData, 0, pRtree->iNodeSize); + memset(pRight->zData, 0, pRtree->iNodeSize); + + rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox); + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + + /* Ensure both child nodes have node numbers assigned to them by calling + ** nodeWrite(). Node pRight always needs a node number, as it was created + ** by nodeNew() above. But node pLeft sometimes already has a node number. + ** In this case avoid the all to nodeWrite(). + */ + if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)) + || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) + ){ + goto splitnode_out; + } + + rightbbox.iRowid = pRight->iNode; + leftbbox.iRowid = pLeft->iNode; + + if( pNode->iNode==1 ){ + rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + }else{ + RtreeNode *pParent = pLeft->pParent; + int iCell; + rc = nodeParentIndex(pRtree, pLeft, &iCell); + if( rc==SQLITE_OK ){ + nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); + rc = AdjustTree(pRtree, pParent, &leftbbox); + } + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + } + if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ + goto splitnode_out; + } + + for(i=0; iiRowid ){ + newCellIsRight = 1; + } + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + } + if( pNode->iNode==1 ){ + for(i=0; iiRowid, pLeft, iHeight); + } + + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pRight); + pRight = 0; + } + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pLeft); + pLeft = 0; + } + +splitnode_out: + nodeRelease(pRtree, pRight); + nodeRelease(pRtree, pLeft); + sqlite3_free(aCell); + return rc; +} + +/* +** If node pLeaf is not the root of the r-tree and its pParent pointer is +** still NULL, load all ancestor nodes of pLeaf into memory and populate +** the pLeaf->pParent chain all the way up to the root node. +** +** This operation is required when a row is deleted (or updated - an update +** is implemented as a delete followed by an insert). SQLite provides the +** rowid of the row to delete, which can be used to find the leaf on which +** the entry resides (argument pLeaf). Once the leaf is located, this +** function is called to determine its ancestry. +*/ +static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ + int rc = SQLITE_OK; + RtreeNode *pChild = pLeaf; + while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){ + int rc2 = SQLITE_OK; /* sqlite3_reset() return code */ + sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode); + rc = sqlite3_step(pRtree->pReadParent); + if( rc==SQLITE_ROW ){ + RtreeNode *pTest; /* Used to test for reference loops */ + i64 iNode; /* Node number of parent node */ + + /* Before setting pChild->pParent, test that we are not creating a + ** loop of references (as we would if, say, pChild==pParent). We don't + ** want to do this as it leads to a memory leak when trying to delete + ** the referenced counted node structures. + */ + iNode = sqlite3_column_int64(pRtree->pReadParent, 0); + for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent); + if( !pTest ){ + rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent); + } + } + rc = sqlite3_reset(pRtree->pReadParent); + if( rc==SQLITE_OK ) rc = rc2; + if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB; + pChild = pChild->pParent; + } + return rc; +} + +static int deleteCell(Rtree *, RtreeNode *, int, int); + +static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){ + int rc; + int rc2; + RtreeNode *pParent = 0; + int iCell; + + assert( pNode->nRef==1 ); + + /* Remove the entry in the parent cell. */ + rc = nodeParentIndex(pRtree, pNode, &iCell); + if( rc==SQLITE_OK ){ + pParent = pNode->pParent; + pNode->pParent = 0; + rc = deleteCell(pRtree, pParent, iCell, iHeight+1); + } + rc2 = nodeRelease(pRtree, pParent); + if( rc==SQLITE_OK ){ + rc = rc2; + } + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Remove the xxx_node entry. */ + sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); + sqlite3_step(pRtree->pDeleteNode); + if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){ + return rc; + } + + /* Remove the xxx_parent entry. */ + sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); + sqlite3_step(pRtree->pDeleteParent); + if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){ + return rc; + } + + /* Remove the node from the in-memory hash table and link it into + ** the Rtree.pDeleted list. Its contents will be re-inserted later on. + */ + nodeHashDelete(pRtree, pNode); + pNode->iNode = iHeight; + pNode->pNext = pRtree->pDeleted; + pNode->nRef++; + pRtree->pDeleted = pNode; + + return SQLITE_OK; +} + +static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){ + RtreeNode *pParent = pNode->pParent; + int rc = SQLITE_OK; + if( pParent ){ + int ii; + int nCell = NCELL(pNode); + RtreeCell box; /* Bounding box for pNode */ + nodeGetCell(pRtree, pNode, 0, &box); + for(ii=1; iiiNode; + rc = nodeParentIndex(pRtree, pNode, &ii); + if( rc==SQLITE_OK ){ + nodeOverwriteCell(pRtree, pParent, &box, ii); + rc = fixBoundingBox(pRtree, pParent); + } + } + return rc; +} + +/* +** Delete the cell at index iCell of node pNode. After removing the +** cell, adjust the r-tree data structure if required. +*/ +static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){ + RtreeNode *pParent; + int rc; + + if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){ + return rc; + } + + /* Remove the cell from the node. This call just moves bytes around + ** the in-memory node image, so it cannot fail. + */ + nodeDeleteCell(pRtree, pNode, iCell); + + /* If the node is not the tree root and now has less than the minimum + ** number of cells, remove it from the tree. Otherwise, update the + ** cell in the parent node so that it tightly contains the updated + ** node. + */ + pParent = pNode->pParent; + assert( pParent || pNode->iNode==1 ); + if( pParent ){ + if( NCELL(pNode)nDim; iDim++){ + aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]); + aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]); + } + } + for(iDim=0; iDimnDim; iDim++){ + aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2)); + } + + for(ii=0; iinDim; iDim++){ + RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - + DCOORD(aCell[ii].aCoord[iDim*2])); + aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]); + } + } + + SortByDistance(aOrder, nCell, aDistance, aSpare); + nodeZero(pRtree, pNode); + + for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){ + RtreeCell *p = &aCell[aOrder[ii]]; + nodeInsertCell(pRtree, pNode, p); + if( p->iRowid==pCell->iRowid ){ + if( iHeight==0 ){ + rc = rowidWrite(pRtree, p->iRowid, pNode->iNode); + }else{ + rc = parentWrite(pRtree, p->iRowid, pNode->iNode); + } + } + } + if( rc==SQLITE_OK ){ + rc = fixBoundingBox(pRtree, pNode); + } + for(; rc==SQLITE_OK && iiiNode currently contains + ** the height of the sub-tree headed by the cell. + */ + RtreeNode *pInsert; + RtreeCell *p = &aCell[aOrder[ii]]; + rc = ChooseLeaf(pRtree, p, iHeight, &pInsert); + if( rc==SQLITE_OK ){ + int rc2; + rc = rtreeInsertCell(pRtree, pInsert, p, iHeight); + rc2 = nodeRelease(pRtree, pInsert); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + + sqlite3_free(aCell); + return rc; +} + +/* +** Insert cell pCell into node pNode. Node pNode is the head of a +** subtree iHeight high (leaf nodes have iHeight==0). +*/ +static int rtreeInsertCell( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell, + int iHeight +){ + int rc = SQLITE_OK; + if( iHeight>0 ){ + RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid); + if( pChild ){ + nodeRelease(pRtree, pChild->pParent); + nodeReference(pNode); + pChild->pParent = pNode; + } + } + if( nodeInsertCell(pRtree, pNode, pCell) ){ +#if VARIANT_RSTARTREE_REINSERT + if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){ + rc = SplitNode(pRtree, pNode, pCell, iHeight); + }else{ + pRtree->iReinsertHeight = iHeight; + rc = Reinsert(pRtree, pNode, pCell, iHeight); + } +#else + rc = SplitNode(pRtree, pNode, pCell, iHeight); +#endif + }else{ + rc = AdjustTree(pRtree, pNode, pCell); + if( rc==SQLITE_OK ){ + if( iHeight==0 ){ + rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode); + }else{ + rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode); + } + } + } + return rc; +} + +static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){ + int ii; + int rc = SQLITE_OK; + int nCell = NCELL(pNode); + + for(ii=0; rc==SQLITE_OK && iiiNode currently contains + ** the height of the sub-tree headed by the cell. + */ + rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert); + if( rc==SQLITE_OK ){ + int rc2; + rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode); + rc2 = nodeRelease(pRtree, pInsert); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + return rc; +} + +/* +** Select a currently unused rowid for a new r-tree record. +*/ +static int newRowid(Rtree *pRtree, i64 *piRowid){ + int rc; + sqlite3_bind_null(pRtree->pWriteRowid, 1); + sqlite3_bind_null(pRtree->pWriteRowid, 2); + sqlite3_step(pRtree->pWriteRowid); + rc = sqlite3_reset(pRtree->pWriteRowid); + *piRowid = sqlite3_last_insert_rowid(pRtree->db); + return rc; +} + +/* +** Remove the entry with rowid=iDelete from the r-tree structure. +*/ +static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ + int rc; /* Return code */ + RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */ + int iCell; /* Index of iDelete cell in pLeaf */ + RtreeNode *pRoot; /* Root node of rtree structure */ + + + /* Obtain a reference to the root node to initialize Rtree.iDepth */ + rc = nodeAcquire(pRtree, 1, 0, &pRoot); + + /* Obtain a reference to the leaf node that contains the entry + ** about to be deleted. + */ + if( rc==SQLITE_OK ){ + rc = findLeafNode(pRtree, iDelete, &pLeaf); + } + + /* Delete the cell in question from the leaf node. */ + if( rc==SQLITE_OK ){ + int rc2; + rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell); + if( rc==SQLITE_OK ){ + rc = deleteCell(pRtree, pLeaf, iCell, 0); + } + rc2 = nodeRelease(pRtree, pLeaf); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + + /* Delete the corresponding entry in the _rowid table. */ + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); + sqlite3_step(pRtree->pDeleteRowid); + rc = sqlite3_reset(pRtree->pDeleteRowid); + } + + /* Check if the root node now has exactly one child. If so, remove + ** it, schedule the contents of the child for reinsertion and + ** reduce the tree height by one. + ** + ** This is equivalent to copying the contents of the child into + ** the root node (the operation that Gutman's paper says to perform + ** in this scenario). + */ + if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){ + int rc2; + RtreeNode *pChild; + i64 iChild = nodeGetRowid(pRtree, pRoot, 0); + rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); + if( rc==SQLITE_OK ){ + rc = removeNode(pRtree, pChild, pRtree->iDepth-1); + } + rc2 = nodeRelease(pRtree, pChild); + if( rc==SQLITE_OK ) rc = rc2; + if( rc==SQLITE_OK ){ + pRtree->iDepth--; + writeInt16(pRoot->zData, pRtree->iDepth); + pRoot->isDirty = 1; + } + } + + /* Re-insert the contents of any underfull nodes removed from the tree. */ + for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){ + if( rc==SQLITE_OK ){ + rc = reinsertNodeContent(pRtree, pLeaf); + } + pRtree->pDeleted = pLeaf->pNext; + sqlite3_free(pLeaf); + } + + /* Release the reference to the root node. */ + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pRoot); + }else{ + nodeRelease(pRtree, pRoot); + } + + return rc; +} + +/* +** Rounding constants for float->double conversion. +*/ +#define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */ +#define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */ + +#if !defined(SQLITE_RTREE_INT_ONLY) +/* +** Convert an sqlite3_value into an RtreeValue (presumably a float) +** while taking care to round toward negative or positive, respectively. +*/ +static RtreeValue rtreeValueDown(sqlite3_value *v){ + double d = sqlite3_value_double(v); + float f = (float)d; + if( f>d ){ + f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS)); + } + return f; +} +static RtreeValue rtreeValueUp(sqlite3_value *v){ + double d = sqlite3_value_double(v); + float f = (float)d; + if( f1 */ + int bHaveRowid = 0; /* Set to 1 after new rowid is determined */ + + rtreeReference(pRtree); + assert(nData>=1); + + /* Constraint handling. A write operation on an r-tree table may return + ** SQLITE_CONSTRAINT for two reasons: + ** + ** 1. A duplicate rowid value, or + ** 2. The supplied data violates the "x2>=x1" constraint. + ** + ** In the first case, if the conflict-handling mode is REPLACE, then + ** the conflicting row can be removed before proceeding. In the second + ** case, SQLITE_CONSTRAINT must be returned regardless of the + ** conflict-handling mode specified by the user. + */ + if( nData>1 ){ + int ii; + + /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */ + assert( nData==(pRtree->nDim*2 + 3) ); +#ifndef SQLITE_RTREE_INT_ONLY + if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]); + cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]); + if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){ + rc = SQLITE_CONSTRAINT; + goto constraint; + } + } + }else +#endif + { + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]); + cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]); + if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){ + rc = SQLITE_CONSTRAINT; + goto constraint; + } + } + } + + /* If a rowid value was supplied, check if it is already present in + ** the table. If so, the constraint has failed. */ + if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){ + cell.iRowid = sqlite3_value_int64(azData[2]); + if( sqlite3_value_type(azData[0])==SQLITE_NULL + || sqlite3_value_int64(azData[0])!=cell.iRowid + ){ + int steprc; + sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); + steprc = sqlite3_step(pRtree->pReadRowid); + rc = sqlite3_reset(pRtree->pReadRowid); + if( SQLITE_ROW==steprc ){ + if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ + rc = rtreeDeleteRowid(pRtree, cell.iRowid); + }else{ + rc = SQLITE_CONSTRAINT; + goto constraint; + } + } + } + bHaveRowid = 1; + } + } + + /* If azData[0] is not an SQL NULL value, it is the rowid of a + ** record to delete from the r-tree table. The following block does + ** just that. + */ + if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){ + rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0])); + } + + /* If the azData[] array contains more than one element, elements + ** (azData[2]..azData[argc-1]) contain a new record to insert into + ** the r-tree structure. + */ + if( rc==SQLITE_OK && nData>1 ){ + /* Insert the new record into the r-tree */ + RtreeNode *pLeaf = 0; + + /* Figure out the rowid of the new row. */ + if( bHaveRowid==0 ){ + rc = newRowid(pRtree, &cell.iRowid); + } + *pRowid = cell.iRowid; + + if( rc==SQLITE_OK ){ + rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); + } + if( rc==SQLITE_OK ){ + int rc2; + pRtree->iReinsertHeight = -1; + rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); + rc2 = nodeRelease(pRtree, pLeaf); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + +constraint: + rtreeRelease(pRtree); + return rc; +} + +/* +** The xRename method for rtree module virtual tables. +*/ +static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ + Rtree *pRtree = (Rtree *)pVtab; + int rc = SQLITE_NOMEM; + char *zSql = sqlite3_mprintf( + "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";" + "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";" + "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";" + , pRtree->zDb, pRtree->zName, zNewName + , pRtree->zDb, pRtree->zName, zNewName + , pRtree->zDb, pRtree->zName, zNewName + ); + if( zSql ){ + rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } + return rc; +} + +static sqlite3_module rtreeModule = { + 0, /* iVersion */ + rtreeCreate, /* xCreate - create a table */ + rtreeConnect, /* xConnect - connect to an existing table */ + rtreeBestIndex, /* xBestIndex - Determine search strategy */ + rtreeDisconnect, /* xDisconnect - Disconnect from a table */ + rtreeDestroy, /* xDestroy - Drop a table */ + rtreeOpen, /* xOpen - open a cursor */ + rtreeClose, /* xClose - close a cursor */ + rtreeFilter, /* xFilter - configure scan constraints */ + rtreeNext, /* xNext - advance a cursor */ + rtreeEof, /* xEof */ + rtreeColumn, /* xColumn - read data */ + rtreeRowid, /* xRowid - read data */ + rtreeUpdate, /* xUpdate - write data */ + 0, /* xBegin - begin transaction */ + 0, /* xSync - sync transaction */ + 0, /* xCommit - commit transaction */ + 0, /* xRollback - rollback transaction */ + 0, /* xFindFunction - function overloading */ + rtreeRename, /* xRename - rename the table */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0 /* xRollbackTo */ +}; + +static int rtreeSqlInit( + Rtree *pRtree, + sqlite3 *db, + const char *zDb, + const char *zPrefix, + int isCreate +){ + int rc = SQLITE_OK; + + #define N_STATEMENT 9 + static const char *azSql[N_STATEMENT] = { + /* Read and write the xxx_node table */ + "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1", + "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)", + "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1", + + /* Read and write the xxx_rowid table */ + "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1", + "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)", + "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1", + + /* Read and write the xxx_parent table */ + "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1", + "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)", + "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1" + }; + sqlite3_stmt **appStmt[N_STATEMENT]; + int i; + + pRtree->db = db; + + if( isCreate ){ + char *zCreate = sqlite3_mprintf( +"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);" +"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);" +"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);" +"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))", + zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize + ); + if( !zCreate ){ + return SQLITE_NOMEM; + } + rc = sqlite3_exec(db, zCreate, 0, 0, 0); + sqlite3_free(zCreate); + if( rc!=SQLITE_OK ){ + return rc; + } + } + + appStmt[0] = &pRtree->pReadNode; + appStmt[1] = &pRtree->pWriteNode; + appStmt[2] = &pRtree->pDeleteNode; + appStmt[3] = &pRtree->pReadRowid; + appStmt[4] = &pRtree->pWriteRowid; + appStmt[5] = &pRtree->pDeleteRowid; + appStmt[6] = &pRtree->pReadParent; + appStmt[7] = &pRtree->pWriteParent; + appStmt[8] = &pRtree->pDeleteParent; + + for(i=0; iiNodeSize is populated and SQLITE_OK returned. +** Otherwise, an SQLite error code is returned. +** +** If this function is being called as part of an xConnect(), then the rtree +** table already exists. In this case the node-size is determined by inspecting +** the root node of the tree. +** +** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. +** This ensures that each node is stored on a single database page. If the +** database page-size is so large that more than RTREE_MAXCELLS entries +** would fit in a single node, use a smaller node-size. +*/ +static int getNodeSize( + sqlite3 *db, /* Database handle */ + Rtree *pRtree, /* Rtree handle */ + int isCreate, /* True for xCreate, false for xConnect */ + char **pzErr /* OUT: Error message, if any */ +){ + int rc; + char *zSql; + if( isCreate ){ + int iPageSize = 0; + zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb); + rc = getIntFromStmt(db, zSql, &iPageSize); + if( rc==SQLITE_OK ){ + pRtree->iNodeSize = iPageSize-64; + if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)iNodeSize ){ + pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS; + } + }else{ + *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + } + }else{ + zSql = sqlite3_mprintf( + "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1", + pRtree->zDb, pRtree->zName + ); + rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize); + if( rc!=SQLITE_OK ){ + *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + } + } + + sqlite3_free(zSql); + return rc; +} + +/* +** This function is the implementation of both the xConnect and xCreate +** methods of the r-tree virtual table. +** +** argv[0] -> module name +** argv[1] -> database name +** argv[2] -> table name +** argv[...] -> column names... +*/ +static int rtreeInit( + sqlite3 *db, /* Database connection */ + void *pAux, /* One of the RTREE_COORD_* constants */ + int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ + sqlite3_vtab **ppVtab, /* OUT: New virtual table */ + char **pzErr, /* OUT: Error message, if any */ + int isCreate /* True for xCreate, false for xConnect */ +){ + int rc = SQLITE_OK; + Rtree *pRtree; + int nDb; /* Length of string argv[1] */ + int nName; /* Length of string argv[2] */ + int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32); + + const char *aErrMsg[] = { + 0, /* 0 */ + "Wrong number of columns for an rtree table", /* 1 */ + "Too few columns for an rtree table", /* 2 */ + "Too many columns for an rtree table" /* 3 */ + }; + + int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2; + if( aErrMsg[iErr] ){ + *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); + return SQLITE_ERROR; + } + + sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); + + /* Allocate the sqlite3_vtab structure */ + nDb = (int)strlen(argv[1]); + nName = (int)strlen(argv[2]); + pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2); + if( !pRtree ){ + return SQLITE_NOMEM; + } + memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); + pRtree->nBusy = 1; + pRtree->base.pModule = &rtreeModule; + pRtree->zDb = (char *)&pRtree[1]; + pRtree->zName = &pRtree->zDb[nDb+1]; + pRtree->nDim = (argc-4)/2; + pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2; + pRtree->eCoordType = eCoordType; + memcpy(pRtree->zDb, argv[1], nDb); + memcpy(pRtree->zName, argv[2], nName); + + /* Figure out the node size to use. */ + rc = getNodeSize(db, pRtree, isCreate, pzErr); + + /* Create/Connect to the underlying relational database schema. If + ** that is successful, call sqlite3_declare_vtab() to configure + ** the r-tree table schema. + */ + if( rc==SQLITE_OK ){ + if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){ + *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + }else{ + char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]); + char *zTmp; + int ii; + for(ii=4; zSql && ii*2 coordinates. +*/ +static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ + char *zText = 0; + RtreeNode node; + Rtree tree; + int ii; + + UNUSED_PARAMETER(nArg); + memset(&node, 0, sizeof(RtreeNode)); + memset(&tree, 0, sizeof(Rtree)); + tree.nDim = sqlite3_value_int(apArg[0]); + tree.nBytesPerCell = 8 + 8 * tree.nDim; + node.zData = (u8 *)sqlite3_value_blob(apArg[1]); + + for(ii=0; iimagic = RTREE_GEOMETRY_MAGIC; + pBlob->xGeom = pGeomCtx->xGeom; + pBlob->pContext = pGeomCtx->pContext; + pBlob->nParam = nArg; + for(i=0; iaParam[i] = sqlite3_value_int64(aArg[i]); +#else + pBlob->aParam[i] = sqlite3_value_double(aArg[i]); +#endif + } + sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free); + } +} + +/* +** Register a new geometry function for use with the r-tree MATCH operator. +*/ +SQLITE_API int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, + int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *), + void *pContext +){ + RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ + + /* Allocate and populate the context object. */ + pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); + if( !pGeomCtx ) return SQLITE_NOMEM; + pGeomCtx->xGeom = xGeom; + pGeomCtx->pContext = pContext; + + /* Create the new user-function. Register a destructor function to delete + ** the context object when it is no longer required. */ + return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, + (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free + ); +} + +#if !SQLITE_CORE +#ifdef _WIN32 +__declspec(dllexport) +#endif +SQLITE_API int sqlite3_rtree_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi) + return sqlite3RtreeInit(db); +} +#endif + +#endif + +/************** End of rtree.c ***********************************************/ +/************** Begin file icu.c *********************************************/ +/* +** 2007 May 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $ +** +** This file implements an integration between the ICU library +** ("International Components for Unicode", an open-source library +** for handling unicode data) and SQLite. The integration uses +** ICU to provide the following to SQLite: +** +** * An implementation of the SQL regexp() function (and hence REGEXP +** operator) using the ICU uregex_XX() APIs. +** +** * Implementations of the SQL scalar upper() and lower() functions +** for case mapping. +** +** * Integration of ICU and SQLite collation sequences. +** +** * An implementation of the LIKE operator that uses ICU to +** provide case-independent matching. +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) + +/* Include ICU headers */ +#include +#include +#include +#include + +/* #include */ + +#ifndef SQLITE_CORE + SQLITE_EXTENSION_INIT1 +#else +#endif + +/* +** Maximum length (in bytes) of the pattern in a LIKE or GLOB +** operator. +*/ +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 +#endif + +/* +** Version of sqlite3_free() that is always a function, never a macro. +*/ +static void xFree(void *p){ + sqlite3_free(p); +} + +/* +** Compare two UTF-8 strings for equality where the first string is +** a "LIKE" expression. Return true (1) if they are the same and +** false (0) if they are different. +*/ +static int icuLikeCompare( + const uint8_t *zPattern, /* LIKE pattern */ + const uint8_t *zString, /* The UTF-8 string to compare against */ + const UChar32 uEsc /* The escape character */ +){ + static const int MATCH_ONE = (UChar32)'_'; + static const int MATCH_ALL = (UChar32)'%'; + + int iPattern = 0; /* Current byte index in zPattern */ + int iString = 0; /* Current byte index in zString */ + + int prevEscape = 0; /* True if the previous character was uEsc */ + + while( zPattern[iPattern]!=0 ){ + + /* Read (and consume) the next character from the input pattern. */ + UChar32 uPattern; + U8_NEXT_UNSAFE(zPattern, iPattern, uPattern); + assert(uPattern!=0); + + /* There are now 4 possibilities: + ** + ** 1. uPattern is an unescaped match-all character "%", + ** 2. uPattern is an unescaped match-one character "_", + ** 3. uPattern is an unescaped escape character, or + ** 4. uPattern is to be handled as an ordinary character + */ + if( !prevEscape && uPattern==MATCH_ALL ){ + /* Case 1. */ + uint8_t c; + + /* Skip any MATCH_ALL or MATCH_ONE characters that follow a + ** MATCH_ALL. For each MATCH_ONE, skip one character in the + ** test string. + */ + while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){ + if( c==MATCH_ONE ){ + if( zString[iString]==0 ) return 0; + U8_FWD_1_UNSAFE(zString, iString); + } + iPattern++; + } + + if( zPattern[iPattern]==0 ) return 1; + + while( zString[iString] ){ + if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){ + return 1; + } + U8_FWD_1_UNSAFE(zString, iString); + } + return 0; + + }else if( !prevEscape && uPattern==MATCH_ONE ){ + /* Case 2. */ + if( zString[iString]==0 ) return 0; + U8_FWD_1_UNSAFE(zString, iString); + + }else if( !prevEscape && uPattern==uEsc){ + /* Case 3. */ + prevEscape = 1; + + }else{ + /* Case 4. */ + UChar32 uString; + U8_NEXT_UNSAFE(zString, iString, uString); + uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT); + uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT); + if( uString!=uPattern ){ + return 0; + } + prevEscape = 0; + } + } + + return zString[iString]==0; +} + +/* +** Implementation of the like() SQL function. This function implements +** the build-in LIKE operator. The first argument to the function is the +** pattern and the second argument is the string. So, the SQL statements: +** +** A LIKE B +** +** is implemented as like(B, A). If there is an escape character E, +** +** A LIKE B ESCAPE E +** +** is mapped to like(B, A, E). +*/ +static void icuLikeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zA = sqlite3_value_text(argv[0]); + const unsigned char *zB = sqlite3_value_text(argv[1]); + UChar32 uEsc = 0; + + /* Limit the length of the LIKE or GLOB pattern to avoid problems + ** of deep recursion and N*N behavior in patternCompare(). + */ + if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){ + sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); + return; + } + + + if( argc==3 ){ + /* The escape character string must consist of a single UTF-8 character. + ** Otherwise, return an error. + */ + int nE= sqlite3_value_bytes(argv[2]); + const unsigned char *zE = sqlite3_value_text(argv[2]); + int i = 0; + if( zE==0 ) return; + U8_NEXT(zE, i, nE, uEsc); + if( i!=nE){ + sqlite3_result_error(context, + "ESCAPE expression must be a single character", -1); + return; + } + } + + if( zA && zB ){ + sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc)); + } +} + +/* +** This function is called when an ICU function called from within +** the implementation of an SQL scalar function returns an error. +** +** The scalar function context passed as the first argument is +** loaded with an error message based on the following two args. +*/ +static void icuFunctionError( + sqlite3_context *pCtx, /* SQLite scalar function context */ + const char *zName, /* Name of ICU function that failed */ + UErrorCode e /* Error code returned by ICU function */ +){ + char zBuf[128]; + sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e)); + zBuf[127] = '\0'; + sqlite3_result_error(pCtx, zBuf, -1); +} + +/* +** Function to delete compiled regexp objects. Registered as +** a destructor function with sqlite3_set_auxdata(). +*/ +static void icuRegexpDelete(void *p){ + URegularExpression *pExpr = (URegularExpression *)p; + uregex_close(pExpr); +} + +/* +** Implementation of SQLite REGEXP operator. This scalar function takes +** two arguments. The first is a regular expression pattern to compile +** the second is a string to match against that pattern. If either +** argument is an SQL NULL, then NULL Is returned. Otherwise, the result +** is 1 if the string matches the pattern, or 0 otherwise. +** +** SQLite maps the regexp() function to the regexp() operator such +** that the following two are equivalent: +** +** zString REGEXP zPattern +** regexp(zPattern, zString) +** +** Uses the following ICU regexp APIs: +** +** uregex_open() +** uregex_matches() +** uregex_close() +*/ +static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ + UErrorCode status = U_ZERO_ERROR; + URegularExpression *pExpr; + UBool res; + const UChar *zString = sqlite3_value_text16(apArg[1]); + + (void)nArg; /* Unused parameter */ + + /* If the left hand side of the regexp operator is NULL, + ** then the result is also NULL. + */ + if( !zString ){ + return; + } + + pExpr = sqlite3_get_auxdata(p, 0); + if( !pExpr ){ + const UChar *zPattern = sqlite3_value_text16(apArg[0]); + if( !zPattern ){ + return; + } + pExpr = uregex_open(zPattern, -1, 0, 0, &status); + + if( U_SUCCESS(status) ){ + sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete); + }else{ + assert(!pExpr); + icuFunctionError(p, "uregex_open", status); + return; + } + } + + /* Configure the text that the regular expression operates on. */ + uregex_setText(pExpr, zString, -1, &status); + if( !U_SUCCESS(status) ){ + icuFunctionError(p, "uregex_setText", status); + return; + } + + /* Attempt the match */ + res = uregex_matches(pExpr, 0, &status); + if( !U_SUCCESS(status) ){ + icuFunctionError(p, "uregex_matches", status); + return; + } + + /* Set the text that the regular expression operates on to a NULL + ** pointer. This is not really necessary, but it is tidier than + ** leaving the regular expression object configured with an invalid + ** pointer after this function returns. + */ + uregex_setText(pExpr, 0, 0, &status); + + /* Return 1 or 0. */ + sqlite3_result_int(p, res ? 1 : 0); +} + +/* +** Implementations of scalar functions for case mapping - upper() and +** lower(). Function upper() converts its input to upper-case (ABC). +** Function lower() converts to lower-case (abc). +** +** ICU provides two types of case mapping, "general" case mapping and +** "language specific". Refer to ICU documentation for the differences +** between the two. +** +** To utilise "general" case mapping, the upper() or lower() scalar +** functions are invoked with one argument: +** +** upper('ABC') -> 'abc' +** lower('abc') -> 'ABC' +** +** To access ICU "language specific" case mapping, upper() or lower() +** should be invoked with two arguments. The second argument is the name +** of the locale to use. Passing an empty string ("") or SQL NULL value +** as the second argument is the same as invoking the 1 argument version +** of upper() or lower(). +** +** lower('I', 'en_us') -> 'i' +** lower('I', 'tr_tr') -> 'ı' (small dotless i) +** +** http://www.icu-project.org/userguide/posix.html#case_mappings +*/ +static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ + const UChar *zInput; + UChar *zOutput; + int nInput; + int nOutput; + + UErrorCode status = U_ZERO_ERROR; + const char *zLocale = 0; + + assert(nArg==1 || nArg==2); + if( nArg==2 ){ + zLocale = (const char *)sqlite3_value_text(apArg[1]); + } + + zInput = sqlite3_value_text16(apArg[0]); + if( !zInput ){ + return; + } + nInput = sqlite3_value_bytes16(apArg[0]); + + nOutput = nInput * 2 + 2; + zOutput = sqlite3_malloc(nOutput); + if( !zOutput ){ + return; + } + + if( sqlite3_user_data(p) ){ + u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status); + }else{ + u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status); + } + + if( !U_SUCCESS(status) ){ + icuFunctionError(p, "u_strToLower()/u_strToUpper", status); + return; + } + + sqlite3_result_text16(p, zOutput, -1, xFree); +} + +/* +** Collation sequence destructor function. The pCtx argument points to +** a UCollator structure previously allocated using ucol_open(). +*/ +static void icuCollationDel(void *pCtx){ + UCollator *p = (UCollator *)pCtx; + ucol_close(p); +} + +/* +** Collation sequence comparison function. The pCtx argument points to +** a UCollator structure previously allocated using ucol_open(). +*/ +static int icuCollationColl( + void *pCtx, + int nLeft, + const void *zLeft, + int nRight, + const void *zRight +){ + UCollationResult res; + UCollator *p = (UCollator *)pCtx; + res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2); + switch( res ){ + case UCOL_LESS: return -1; + case UCOL_GREATER: return +1; + case UCOL_EQUAL: return 0; + } + assert(!"Unexpected return value from ucol_strcoll()"); + return 0; +} + +/* +** Implementation of the scalar function icu_load_collation(). +** +** This scalar function is used to add ICU collation based collation +** types to an SQLite database connection. It is intended to be called +** as follows: +** +** SELECT icu_load_collation(, ); +** +** Where is a string containing an ICU locale identifier (i.e. +** "en_AU", "tr_TR" etc.) and is the name of the +** collation sequence to create. +*/ +static void icuLoadCollation( + sqlite3_context *p, + int nArg, + sqlite3_value **apArg +){ + sqlite3 *db = (sqlite3 *)sqlite3_user_data(p); + UErrorCode status = U_ZERO_ERROR; + const char *zLocale; /* Locale identifier - (eg. "jp_JP") */ + const char *zName; /* SQL Collation sequence name (eg. "japanese") */ + UCollator *pUCollator; /* ICU library collation object */ + int rc; /* Return code from sqlite3_create_collation_x() */ + + assert(nArg==2); + zLocale = (const char *)sqlite3_value_text(apArg[0]); + zName = (const char *)sqlite3_value_text(apArg[1]); + + if( !zLocale || !zName ){ + return; + } + + pUCollator = ucol_open(zLocale, &status); + if( !U_SUCCESS(status) ){ + icuFunctionError(p, "ucol_open", status); + return; + } + assert(p); + + rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, + icuCollationColl, icuCollationDel + ); + if( rc!=SQLITE_OK ){ + ucol_close(pUCollator); + sqlite3_result_error(p, "Error registering collation function", -1); + } +} + +/* +** Register the ICU extension functions with database db. +*/ +SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){ + struct IcuScalar { + const char *zName; /* Function name */ + int nArg; /* Number of arguments */ + int enc; /* Optimal text encoding */ + void *pContext; /* sqlite3_user_data() context */ + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); + } scalars[] = { + {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc}, + + {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16}, + {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16}, + {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16}, + {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16}, + + {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16}, + {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16}, + {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16}, + {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16}, + + {"like", 2, SQLITE_UTF8, 0, icuLikeFunc}, + {"like", 3, SQLITE_UTF8, 0, icuLikeFunc}, + + {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation}, + }; + + int rc = SQLITE_OK; + int i; + + for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){ + struct IcuScalar *p = &scalars[i]; + rc = sqlite3_create_function( + db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0 + ); + } + + return rc; +} + +#if !SQLITE_CORE +#ifdef _WIN32 +__declspec(dllexport) +#endif +SQLITE_API int sqlite3_icu_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi) + return sqlite3IcuInit(db); +} +#endif + +#endif + +/************** End of icu.c *************************************************/ +/************** Begin file fts3_icu.c ****************************************/ +/* +** 2007 June 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements a tokenizer for fts3 based on the ICU library. +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) +#ifdef SQLITE_ENABLE_ICU + +/* #include */ +/* #include */ + +#include +/* #include */ +/* #include */ +#include + +typedef struct IcuTokenizer IcuTokenizer; +typedef struct IcuCursor IcuCursor; + +struct IcuTokenizer { + sqlite3_tokenizer base; + char *zLocale; +}; + +struct IcuCursor { + sqlite3_tokenizer_cursor base; + + UBreakIterator *pIter; /* ICU break-iterator object */ + int nChar; /* Number of UChar elements in pInput */ + UChar *aChar; /* Copy of input using utf-16 encoding */ + int *aOffset; /* Offsets of each character in utf-8 input */ + + int nBuffer; + char *zBuffer; + + int iToken; +}; + +/* +** Create a new tokenizer instance. +*/ +static int icuCreate( + int argc, /* Number of entries in argv[] */ + const char * const *argv, /* Tokenizer creation arguments */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ +){ + IcuTokenizer *p; + int n = 0; + + if( argc>0 ){ + n = strlen(argv[0])+1; + } + p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n); + if( !p ){ + return SQLITE_NOMEM; + } + memset(p, 0, sizeof(IcuTokenizer)); + + if( n ){ + p->zLocale = (char *)&p[1]; + memcpy(p->zLocale, argv[0], n); + } + + *ppTokenizer = (sqlite3_tokenizer *)p; + + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int icuDestroy(sqlite3_tokenizer *pTokenizer){ + IcuTokenizer *p = (IcuTokenizer *)pTokenizer; + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is pInput[0..nBytes-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int icuOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *zInput, /* Input string */ + int nInput, /* Length of zInput in bytes */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + IcuTokenizer *p = (IcuTokenizer *)pTokenizer; + IcuCursor *pCsr; + + const int32_t opt = U_FOLD_CASE_DEFAULT; + UErrorCode status = U_ZERO_ERROR; + int nChar; + + UChar32 c; + int iInput = 0; + int iOut = 0; + + *ppCursor = 0; + + if( zInput==0 ){ + nInput = 0; + zInput = ""; + }else if( nInput<0 ){ + nInput = strlen(zInput); + } + nChar = nInput+1; + pCsr = (IcuCursor *)sqlite3_malloc( + sizeof(IcuCursor) + /* IcuCursor */ + ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */ + (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */ + ); + if( !pCsr ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(IcuCursor)); + pCsr->aChar = (UChar *)&pCsr[1]; + pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3]; + + pCsr->aOffset[iOut] = iInput; + U8_NEXT(zInput, iInput, nInput, c); + while( c>0 ){ + int isError = 0; + c = u_foldCase(c, opt); + U16_APPEND(pCsr->aChar, iOut, nChar, c, isError); + if( isError ){ + sqlite3_free(pCsr); + return SQLITE_ERROR; + } + pCsr->aOffset[iOut] = iInput; + + if( iInputpIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status); + if( !U_SUCCESS(status) ){ + sqlite3_free(pCsr); + return SQLITE_ERROR; + } + pCsr->nChar = iOut; + + ubrk_first(pCsr->pIter); + *ppCursor = (sqlite3_tokenizer_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to icuOpen(). +*/ +static int icuClose(sqlite3_tokenizer_cursor *pCursor){ + IcuCursor *pCsr = (IcuCursor *)pCursor; + ubrk_close(pCsr->pIter); + sqlite3_free(pCsr->zBuffer); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** Extract the next token from a tokenization cursor. +*/ +static int icuNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + IcuCursor *pCsr = (IcuCursor *)pCursor; + + int iStart = 0; + int iEnd = 0; + int nByte = 0; + + while( iStart==iEnd ){ + UChar32 c; + + iStart = ubrk_current(pCsr->pIter); + iEnd = ubrk_next(pCsr->pIter); + if( iEnd==UBRK_DONE ){ + return SQLITE_DONE; + } + + while( iStartaChar, iWhite, pCsr->nChar, c); + if( u_isspace(c) ){ + iStart = iWhite; + }else{ + break; + } + } + assert(iStart<=iEnd); + } + + do { + UErrorCode status = U_ZERO_ERROR; + if( nByte ){ + char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte); + if( !zNew ){ + return SQLITE_NOMEM; + } + pCsr->zBuffer = zNew; + pCsr->nBuffer = nByte; + } + + u_strToUTF8( + pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */ + &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */ + &status /* Output success/failure */ + ); + } while( nByte>pCsr->nBuffer ); + + *ppToken = pCsr->zBuffer; + *pnBytes = nByte; + *piStartOffset = pCsr->aOffset[iStart]; + *piEndOffset = pCsr->aOffset[iEnd]; + *piPosition = pCsr->iToken++; + + return SQLITE_OK; +} + +/* +** The set of routines that implement the simple tokenizer +*/ +static const sqlite3_tokenizer_module icuTokenizerModule = { + 0, /* iVersion */ + icuCreate, /* xCreate */ + icuDestroy, /* xCreate */ + icuOpen, /* xOpen */ + icuClose, /* xClose */ + icuNext, /* xNext */ +}; + +/* +** Set *ppModule to point at the implementation of the ICU tokenizer. +*/ +SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &icuTokenizerModule; +} + +#endif /* defined(SQLITE_ENABLE_ICU) */ +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ + +/************** End of fts3_icu.c ********************************************/ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/sqlite3.h b/components/external/SQLite-3.8.1/SQLiteLib/sqlite3.h new file mode 100644 index 0000000000000000000000000000000000000000..2dd1158d5bbb6594c4e75291a76a19845a3459e9 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/sqlite3.h @@ -0,0 +1,7299 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve the right to make minor changes +** if experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ +#include /* Needed for the definition of va_list */ + +/* +** Make sure we can call this stuff from C++. +*/ +#ifdef __cplusplus +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +#ifndef SQLITE_API +# define SQLITE_API +#endif + + +/* +** These no-op macros are used in front of interfaces to mark those +** interfaces as either deprecated or experimental. New applications +** should not use deprecated interfaces - they are support for backwards +** compatibility only. Application writers should be aware that +** experimental interfaces are subject to change in point releases. +** +** These macros used to resolve to various kinds of compiler magic that +** would generate warning messages when they were used. But that +** compiler magic ended up generating such a flurry of bug reports +** that we have taken it all out and gone back to using simple +** noop macros. +*/ +#define SQLITE_DEPRECATED +#define SQLITE_EXPERIMENTAL + +/* +** Ensure these symbols were not defined by some previous header file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers +** +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header +** evaluates to a string literal that is the SQLite version in the +** format "X.Y.Z" where X is the major version number (always 3 for +** SQLite3) and Y is the minor version number and Z is the release number.)^ +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same +** numbers used in [SQLITE_VERSION].)^ +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also +** be larger than the release from which it is derived. Either Y will +** be held constant and Z will be incremented or else Y will be incremented +** and Z will be reset to zero. +** +** Since version 3.6.18, SQLite source code has been stored in the +** Fossil configuration management +** system. ^The SQLITE_SOURCE_ID macro evaluates to +** a string which identifies a particular check-in of SQLite +** within its configuration management system. ^The SQLITE_SOURCE_ID +** string contains the date and time of the check-in (UTC) and an SHA1 +** hash of the entire source tree. +** +** See also: [sqlite3_libversion()], +** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** [sqlite_version()] and [sqlite_source_id()]. +*/ +#define SQLITE_VERSION "3.8.1" +#define SQLITE_VERSION_NUMBER 3008001 +#define SQLITE_SOURCE_ID "2013-10-17 12:57:35 c78be6d786c19073b3a6730dfe3fb1be54f5657a" + +/* +** CAPI3REF: Run-Time Library Version Numbers +** KEYWORDS: sqlite3_version, sqlite3_sourceid +** +** These interfaces provide the same information as the [SQLITE_VERSION], +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros +** but are associated with the library instead of the header file. ^(Cautious +** programmers might include assert() statements in their application to +** verify that values returned by these interfaces match the macros in +** the header, and thus insure that the application is +** compiled with matching library and header files. +** +**
+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+** 
)^ +** +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The sqlite3_libversion() function returns a pointer to the +** to the sqlite3_version[] string constant. The sqlite3_libversion() +** function is provided for use in DLLs since DLL users usually do not have +** direct access to string constants within the DLL. ^The +** sqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns +** a pointer to a string constant whose value is the same as the +** [SQLITE_SOURCE_ID] C preprocessor macro. +** +** See also: [sqlite_version()] and [sqlite_source_id()]. +*/ +SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; +SQLITE_API const char *sqlite3_libversion(void); +SQLITE_API const char *sqlite3_sourceid(void); +SQLITE_API int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Run-Time Library Compilation Options Diagnostics +** +** ^The sqlite3_compileoption_used() function returns 0 or 1 +** indicating whether the specified option was defined at +** compile time. ^The SQLITE_ prefix may be omitted from the +** option name passed to sqlite3_compileoption_used(). +** +** ^The sqlite3_compileoption_get() function allows iterating +** over the list of options that were defined at compile time by +** returning the N-th compile time option string. ^If N is out of range, +** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** prefix is omitted from any strings returned by +** sqlite3_compileoption_get(). +** +** ^Support for the diagnostic functions sqlite3_compileoption_used() +** and sqlite3_compileoption_get() may be omitted by specifying the +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. +** +** See also: SQL functions [sqlite_compileoption_used()] and +** [sqlite_compileoption_get()] and the [compile_options pragma]. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +SQLITE_API int sqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *sqlite3_compileoption_get(int N); +#endif + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe +** +** ^The sqlite3_threadsafe() function returns zero if and only if +** SQLite was compiled with mutexing code omitted due to the +** [SQLITE_THREADSAFE] compile-time option being set to 0. +** +** SQLite can be compiled with or without mutexes. When +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes +** are enabled and SQLite is threadsafe. When the +** [SQLITE_THREADSAFE] macro is 0, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite concurrently from more than one thread. +** +** Enabling mutexes incurs a measurable performance penalty. +** So if speed is of utmost importance, it makes sense to disable +** the mutexes. But for maximum safety, mutexes should be enabled. +** ^The default behavior is for mutexes to be enabled. +** +** This interface can be used by an application to make sure that the +** version of SQLite that it is linking against was compiled with +** the desired setting of the [SQLITE_THREADSAFE] macro. +** +** This interface only reports on the compile-time mutex setting +** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but +** can be fully or partially disabled using a call to [sqlite3_config()] +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], +** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the +** sqlite3_threadsafe() function shows only the compile-time setting of +** thread safety, not any run-time changes to that setting made by +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() +** is unchanged by calls to sqlite3_config().)^ +** +** See the [threading mode] documentation for additional information. +*/ +SQLITE_API int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle +** KEYWORDS: {database connection} {database connections} +** +** Each open SQLite database is represented by a pointer to an instance of +** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] +** and [sqlite3_close_v2()] are its destructors. There are many other +** interfaces (such as +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on an +** sqlite3 object. +*/ +typedef struct sqlite3 sqlite3; + +/* +** CAPI3REF: 64-Bit Integer Types +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The sqlite_int64 and sqlite_uint64 types are supported for backwards +** compatibility only. +** +** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** between -9223372036854775808 and +9223372036854775807 inclusive. ^The +** sqlite3_uint64 and sqlite_uint64 types can store integer values +** between 0 and +18446744073709551615 inclusive. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection +** +** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors +** for the [sqlite3] object. +** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if +** the [sqlite3] object is successfully destroyed and all associated +** resources are deallocated. +** +** ^If the database connection is associated with unfinalized prepared +** statements or unfinished sqlite3_backup objects then sqlite3_close() +** will leave the database connection open and return [SQLITE_BUSY]. +** ^If sqlite3_close_v2() is called with unfinalized prepared statements +** and unfinished sqlite3_backups, then the database connection becomes +** an unusable "zombie" which will automatically be deallocated when the +** last prepared statement is finalized or the last sqlite3_backup is +** finished. The sqlite3_close_v2() interface is intended for use with +** host languages that are garbage collected, and where the order in which +** destructors are called is arbitrary. +** +** Applications should [sqlite3_finalize | finalize] all [prepared statements], +** [sqlite3_blob_close | close] all [BLOB handles], and +** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated +** with the [sqlite3] object prior to attempting to close the object. ^If +** sqlite3_close_v2() is called on a [database connection] that still has +** outstanding [prepared statements], [BLOB handles], and/or +** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation +** of resources is deferred until all [prepared statements], [BLOB handles], +** and [sqlite3_backup] objects are also destroyed. +** +** ^If an [sqlite3] object is destroyed while a transaction is open, +** the transaction is automatically rolled back. +** +** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] +** must be either a NULL +** pointer or an [sqlite3] object pointer obtained +** from [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()], and not previously closed. +** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer +** argument is a harmless no-op. +*/ +SQLITE_API int sqlite3_close(sqlite3*); +SQLITE_API int sqlite3_close_v2(sqlite3*); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface +** +** The sqlite3_exec() interface is a convenience wrapper around +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** that allows an application to run multiple statements of SQL +** without having to use a lot of C code. +** +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** semicolon-separate SQL statements passed into its 2nd argument, +** in the context of the [database connection] passed in as its 1st +** argument. ^If the callback function of the 3rd argument to +** sqlite3_exec() is not NULL, then it is invoked for each result row +** coming out of the evaluated SQL statements. ^The 4th argument to +** sqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to sqlite3_exec() +** is NULL, then no callback is ever invoked and result rows are +** ignored. +** +** ^If an error occurs while evaluating the SQL statements passed into +** sqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** is not NULL then any error message is written into memory obtained +** from [sqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [sqlite3_free()] +** on error message strings returned through the 5th parameter of +** of sqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** NULL before returning. +** +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** routine returns SQLITE_ABORT without invoking the callback again and +** without running any subsequent SQL statements. +** +** ^The 2nd argument to the sqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** callback is an array of pointers to strings obtained as if from +** [sqlite3_column_text()], one for each column. ^If an element of a +** result row is NULL then the corresponding string pointer for the +** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** sqlite3_exec() callback is an array of pointers to strings where each +** entry represents the name of corresponding result column as obtained +** from [sqlite3_column_name()]. +** +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** to an empty string, or a pointer that contains only whitespace and/or +** SQL comments, then no SQL statements are evaluated and the database +** is not changed. +** +** Restrictions: +** +**
    +**
  • The application must insure that the 1st parameter to sqlite3_exec() +** is a valid and open [database connection]. +**
  • The application must not close [database connection] specified by +** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +**
  • The application must not modify the SQL statement text passed into +** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +**
+*/ +SQLITE_API int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes +** KEYWORDS: SQLITE_OK {error code} {error codes} +** KEYWORDS: {result code} {result codes} +** +** Many SQLite functions return an integer result code from the set shown +** here in order to indicate success or failure. +** +** New error codes may be added in future versions of SQLite. +** +** See also: [SQLITE_IOERR_READ | extended result codes], +** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes]. +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ +#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes +** KEYWORDS: {extended error code} {extended error codes} +** KEYWORDS: {extended result code} {extended result codes} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that many of +** these result codes are too coarse-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. The extended result codes are enabled or disabled +** on a per database connection basis using the +** [sqlite3_extended_result_codes()] API. +** +** Some of the available extended result codes are listed here. +** One may expect the number of extended result codes will be expand +** over time. Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) +#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) +#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) +#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) +#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) +#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) +#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) +#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) +#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) +#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) +#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) +#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) +#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) +#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) +#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) +#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) +#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) +#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) +#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) +#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) +#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) +#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) +#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) +#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) +#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) +#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) +#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) +#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) +#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) +#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) +#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) +#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) +#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) +#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) +#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) +#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) + +/* +** CAPI3REF: Flags For File Open Operations +** +** These bit values are intended for use in the +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter to the [sqlite3_vfs.xOpen] method. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ +#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ +#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ +#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ + +/* Reserved: 0x00F00000 */ + +/* +** CAPI3REF: Device Characteristics +** +** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** object returns an integer which is a vector of these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that +** after reboot following a crash or power loss, the only bytes in a +** file that were written at the application level might have changed +** and that adjacent bytes, even bytes within the same sector are +** guaranteed to be unchanged. +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 +#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 + +/* +** CAPI3REF: File Locking Levels +** +** SQLite uses one of these integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags +** +** When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of +** these integer values as the second argument. +** +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. If the lower four bits of the flag +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. +** If the lower four bits equal SQLITE_SYNC_FULL, that means +** to use Mac OS X style fullsync instead of fsync(). +** +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL +** settings. The [synchronous pragma] determines when calls to the +** xSync VFS method occur and applies uniformly across all platforms. +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how +** energetic or rigorous or forceful the sync operations are and +** only make a difference on Mac OSX for the default SQLite code. +** (Third-party VFS implementations might also make the distinction +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the +** operating systems natively supported by SQLite, only Mac OSX +** cares about the difference.) +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + +/* +** CAPI3REF: OS Interface Open File Handle +** +** An [sqlite3_file] object represents an open file in the +** [sqlite3_vfs | OS interface layer]. Individual OS interface +** implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object +** +** Every file opened by the [sqlite3_vfs.xOpen] method populates an +** [sqlite3_file] object (or, more commonly, a subclass of the +** [sqlite3_file] object) with a pointer to an instance of this object. +** This object defines the methods used to perform various operations +** against the open file represented by the [sqlite3_file] object. +** +** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method +** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The +** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] +** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element +** to NULL. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] +** flag may be ORed in to indicate that only the data of the file +** and not its inode needs to be synced. +** +** The integer values to xLock() and xUnlock() are one of +**
    +**
  • [SQLITE_LOCK_NONE], +**
  • [SQLITE_LOCK_SHARED], +**
  • [SQLITE_LOCK_RESERVED], +**
  • [SQLITE_LOCK_PENDING], or +**
  • [SQLITE_LOCK_EXCLUSIVE]. +**
+** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method checks whether any database connection, +** either in this process or in some other process, is holding a RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false otherwise. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument is an +** integer opcode. The third argument is a generic pointer intended to +** point to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves all opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. VFS implementations should +** return [SQLITE_NOTFOUND] for file control opcodes that they do not +** recognize. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
    +**
  • [SQLITE_IOCAP_ATOMIC] +**
  • [SQLITE_IOCAP_ATOMIC512] +**
  • [SQLITE_IOCAP_ATOMIC1K] +**
  • [SQLITE_IOCAP_ATOMIC2K] +**
  • [SQLITE_IOCAP_ATOMIC4K] +**
  • [SQLITE_IOCAP_ATOMIC8K] +**
  • [SQLITE_IOCAP_ATOMIC16K] +**
  • [SQLITE_IOCAP_ATOMIC32K] +**
  • [SQLITE_IOCAP_ATOMIC64K] +**
  • [SQLITE_IOCAP_SAFE_APPEND] +**
  • [SQLITE_IOCAP_SEQUENTIAL] +**
+** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +** +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill +** in the unread portions of the buffer with zeros. A VFS that +** fails to zero-fill short reads might seem to work. However, +** failure to zero-fill short reads will eventually lead to +** database corruption. +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Methods above are valid for version 1 */ + int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(sqlite3_file*); + int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + /* Methods above are valid for version 2 */ + int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); + int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); + /* Methods above are valid for version 3 */ + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** interface. +** +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode causes the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +**
    +**
  • [[SQLITE_FCNTL_SIZE_HINT]] +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS +** layer a hint of how large the database file will grow to be during the +** current transaction. This hint is not guaranteed to be accurate but it +** is often close. The underlying VFS might choose to preallocate database +** file space based on this hint in order to help writes to the database +** file run faster. +** +**
  • [[SQLITE_FCNTL_CHUNK_SIZE]] +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS +** extends and truncates the database file in chunks of a size specified +** by the user. The fourth argument to [sqlite3_file_control()] should +** point to an integer (type int) containing the new chunk-size to use +** for the nominated database. Allocating database file space in large +** chunks (say 1MB at a time), may reduce file-system fragmentation and +** improve performance on some systems. +** +**
  • [[SQLITE_FCNTL_FILE_POINTER]] +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with a particular database +** connection. See the [sqlite3_file_control()] documentation for +** additional information. +** +**
  • [[SQLITE_FCNTL_SYNC_OMITTED]] +** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by +** SQLite and sent to all VFSes in place of a call to the xSync method +** when the database connection has [PRAGMA synchronous] set to OFF.)^ +** Some specialized VFSes need this signal in order to operate correctly +** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most +** VFSes do not need this signal and should silently ignore this opcode. +** Applications should not call [sqlite3_file_control()] with this +** opcode as doing so may disrupt the operation of the specialized VFSes +** that do require it. +** +**
  • [[SQLITE_FCNTL_WIN32_AV_RETRY]] +** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic +** retry counts and intervals for certain disk I/O operations for the +** windows [VFS] in order to provide robustness in the presence of +** anti-virus programs. By default, the windows VFS will retry file read, +** file write, and file delete operations up to 10 times, with a delay +** of 25 milliseconds before the first retry and with the delay increasing +** by an additional 25 milliseconds with each subsequent retry. This +** opcode allows these two values (10 retries and 25 milliseconds of delay) +** to be adjusted. The values are changed for all database connections +** within the same process. The argument is a pointer to an array of two +** integers where the first integer i the new retry count and the second +** integer is the delay. If either integer is negative, then the setting +** is not changed but instead the prior value of that setting is written +** into the array entry, allowing the current retry settings to be +** interrogated. The zDbName parameter is ignored. +** +**
  • [[SQLITE_FCNTL_PERSIST_WAL]] +** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the +** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary +** write ahead log and shared memory files used for transaction control +** are automatically deleted when the latest connection to the database +** closes. Setting persistent WAL mode causes those files to persist after +** close. Persisting the files is useful when other processes that do not +** have write permission on the directory containing the database file want +** to read the database file, as the WAL and shared memory files must exist +** in order for the database to be readable. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable persistent WAL mode or 1 to enable persistent +** WAL mode. If the integer is -1, then it is overwritten with the current +** WAL persistence setting. +** +**
  • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] +** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the +** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting +** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the +** xDeviceCharacteristics methods. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage +** mode. If the integer is -1, then it is overwritten with the current +** zero-damage mode setting. +** +**
  • [[SQLITE_FCNTL_OVERWRITE]] +** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening +** a write transaction to indicate that, unless it is rolled back for some +** reason, the entire database file will be overwritten by the current +** transaction. This is used by VACUUM operations. +** +**
  • [[SQLITE_FCNTL_VFSNAME]] +** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of +** all [VFSes] in the VFS stack. The names are of all VFS shims and the +** final bottom-level VFS are written into memory obtained from +** [sqlite3_malloc()] and the result is stored in the char* variable +** that the fourth parameter of [sqlite3_file_control()] points to. +** The caller is responsible for freeing the memory when done. As with +** all file-control actions, there is no guarantee that this will actually +** do anything. Callers should initialize the char* variable to a NULL +** pointer in case this file-control is not implemented. This file-control +** is intended for diagnostic use only. +** +**
  • [[SQLITE_FCNTL_PRAGMA]] +** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] +** file control is sent to the open [sqlite3_file] object corresponding +** to the database file to which the pragma statement refers. ^The argument +** to the [SQLITE_FCNTL_PRAGMA] file control is an array of +** pointers to strings (char**) in which the second element of the array +** is the name of the pragma and the third element is the argument to the +** pragma or NULL if the pragma has no argument. ^The handler for an +** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element +** of the char** argument point to a string obtained from [sqlite3_mprintf()] +** or the equivalent and that string will become the result of the pragma or +** the error message if the pragma fails. ^If the +** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal +** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] +** file control returns [SQLITE_OK], then the parser assumes that the +** VFS has handled the PRAGMA itself and the parser generates a no-op +** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns +** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means +** that the VFS encountered an error while handling the [PRAGMA] and the +** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] +** file control occurs at the beginning of pragma statement analysis and so +** it is able to override built-in [PRAGMA] statements. +** +**
  • [[SQLITE_FCNTL_BUSYHANDLER]] +** ^The [SQLITE_FCNTL_BUSYHANDLER] +** file-control may be invoked by SQLite on the database file handle +** shortly after it is opened in order to provide a custom VFS with access +** to the connections busy-handler callback. The argument is of type (void **) +** - an array of two (void *) values. The first (void *) actually points +** to a function of type (int (*)(void *)). In order to invoke the connections +** busy-handler, this function should be invoked with the second (void *) in +** the array as the only argument. If it returns non-zero, then the operation +** should be retried. If it returns zero, the custom VFS should abandon the +** current operation. +** +**
  • [[SQLITE_FCNTL_TEMPFILENAME]] +** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control +** to have SQLite generate a +** temporary filename using the same algorithm that is followed to generate +** temporary filenames for TEMP tables and other internal uses. The +** argument should be a char** which will be filled with the filename +** written into memory obtained from [sqlite3_malloc()]. The caller should +** invoke [sqlite3_free()] on the result to avoid a memory leak. +** +**
  • [[SQLITE_FCNTL_MMAP_SIZE]] +** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the +** maximum number of bytes that will be used for memory-mapped I/O. +** The argument is a pointer to a value of type sqlite3_int64 that +** is an advisory maximum number of bytes in the file to memory map. The +** pointer is overwritten with the old value. The limit is not changed if +** the value originally pointed to is negative, and so the current limit +** can be queried by passing in a pointer to a negative number. This +** file-control is used internally to implement [PRAGMA mmap_size]. +** +**
+*/ +#define SQLITE_FCNTL_LOCKSTATE 1 +#define SQLITE_GET_LOCKPROXYFILE 2 +#define SQLITE_SET_LOCKPROXYFILE 3 +#define SQLITE_LAST_ERRNO 4 +#define SQLITE_FCNTL_SIZE_HINT 5 +#define SQLITE_FCNTL_CHUNK_SIZE 6 +#define SQLITE_FCNTL_FILE_POINTER 7 +#define SQLITE_FCNTL_SYNC_OMITTED 8 +#define SQLITE_FCNTL_WIN32_AV_RETRY 9 +#define SQLITE_FCNTL_PERSIST_WAL 10 +#define SQLITE_FCNTL_OVERWRITE 11 +#define SQLITE_FCNTL_VFSNAME 12 +#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 +#define SQLITE_FCNTL_PRAGMA 14 +#define SQLITE_FCNTL_BUSYHANDLER 15 +#define SQLITE_FCNTL_TEMPFILENAME 16 +#define SQLITE_FCNTL_MMAP_SIZE 18 + +/* +** CAPI3REF: Mutex Handle +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object +** +** An instance of the sqlite3_vfs object defines the interface between +** the SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". See +** the [VFS | VFS documentation] for further information. +** +** The value of the iVersion field is initially 1 but may be larger in +** future versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. Note that the structure +** of the sqlite3_vfs object changes in the transaction between +** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not +** modified. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered sqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. Neither the application code nor the VFS +** implementation should use the pNext pointer. +** +** The pNext field is the only field in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** [[sqlite3_vfs.xOpen]] +** ^SQLite guarantees that the zFilename parameter to xOpen +** is either a NULL pointer or string obtained +** from xFullPathname() with an optional suffix added. +** ^If a suffix is added to the zFilename parameter, it will +** consist of a single "-" character followed by no more than +** 11 alphanumeric and/or "-" characters. +** ^SQLite further guarantees that +** the string will be valid and unchanged until xClose() is +** called. Because of the previous sentence, +** the [sqlite3_file] can safely store a pointer to the +** filename if it needs to remember the filename for some reason. +** If the zFilename parameter to xOpen is a NULL pointer then xOpen +** must invent its own temporary name for the file. ^Whenever the +** xFilename parameter is NULL it will also be the case that the +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. +** +** The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. +** +** ^(SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
    +**
  • [SQLITE_OPEN_MAIN_DB] +**
  • [SQLITE_OPEN_MAIN_JOURNAL] +**
  • [SQLITE_OPEN_TEMP_DB] +**
  • [SQLITE_OPEN_TEMP_JOURNAL] +**
  • [SQLITE_OPEN_TRANSIENT_DB] +**
  • [SQLITE_OPEN_SUBJOURNAL] +**
  • [SQLITE_OPEN_MASTER_JOURNAL] +**
  • [SQLITE_OPEN_WAL] +**
)^ +** +** The file I/O implementation can use the object type flags to +** change the way it deals with files. For example, an application +** that does not care about crash recovery or rollback might make +** the open of a journal file a no-op. Writes to this journal would +** also be no-ops, and any attempt to read the journal would return +** SQLITE_IOERR. Or the implementation might recognize that a database +** file will be doing page-aligned sector reads and writes in a random +** order and set up its I/O subsystem accordingly. +** +** SQLite might also add one of the following flags to the xOpen method: +** +**
    +**
  • [SQLITE_OPEN_DELETEONCLOSE] +**
  • [SQLITE_OPEN_EXCLUSIVE] +**
+** +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases and their journals, transient +** databases, and subjournals. +** +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction +** with the [SQLITE_OPEN_CREATE] flag, which are both directly +** analogous to the O_EXCL and O_CREAT flags of the POSIX open() +** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the +** SQLITE_OPEN_CREATE, is used to indicate that file should always +** be created, and that it is an error if it already exists. +** It is not used to indicate the file should be opened +** for exclusive access. +** +** ^At least szOsFile bytes of memory are allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. The xOpen method does not have to +** allocate the structure; it should just fill it in. Note that +** the xOpen method must set the sqlite3_file.pMethods to either +** a valid [sqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** element will be valid after xOpen returns regardless of the success +** or failure of the xOpen call. +** +** [[sqlite3_vfs.xAccess]] +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test whether a file is at least readable. The file can be a +** directory. +** +** ^SQLite will always allocate at least mxPathname+1 bytes for the +** output buffer xFullPathname. The exact size of the output buffer +** is also passed as a parameter to both methods. If the output buffer +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is +** handled as a fatal error by SQLite, vfs implementations should endeavor +** to prevent this by setting mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() +** interfaces are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. +** The xSleep() method causes the calling thread to sleep for at +** least the number of microseconds given. ^The xCurrentTime() +** method returns a Julian Day Number for the current date and time as +** a floating point value. +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian +** Day Number multiplied by 86400000 (the number of milliseconds in +** a 24-hour day). +** ^SQLite will use the xCurrentTimeInt64() method to get the current +** date and time if that method is available (if iVersion is 2 or +** greater and the function pointer is not NULL) and will fall back +** to xCurrentTime() if xCurrentTimeInt64() is unavailable. +** +** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces +** are not used by the SQLite core. These optional interfaces are provided +** by some VFSes to facilitate testing of the VFS code. By overriding +** system calls with functions under its control, a test program can +** simulate faults and error conditions that would otherwise be difficult +** or impossible to induce. The set of system calls that can be overridden +** varies from one VFS to another, and from one version of the same VFS to the +** next. Applications that use these interfaces must be prepared for any +** or all of these interfaces to be NULL or for their behavior to change +** from one release to the next. Applications must not attempt to access +** any of these methods if the iVersion of the VFS is less than 3. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +typedef void (*sqlite3_syscall_ptr)(void); +struct sqlite3_vfs { + int iVersion; /* Structure version number (currently 3) */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + int (*xGetLastError)(sqlite3_vfs*, int, char *); + /* + ** The methods above are in version 1 of the sqlite_vfs object + ** definition. Those that follow are added in version 2 or later + */ + int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + /* + ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + ** Those below are for version 3 and greater. + */ + int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); + sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); + const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); + /* + ** The methods above are in versions 1 through 3 of the sqlite_vfs object. + ** New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. + */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method +** +** These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. They determine +** what kind of permissions the xAccess method is looking for. +** With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks whether the file exists. +** With SQLITE_ACCESS_READWRITE, the xAccess method +** checks whether the named directory is both readable and writable +** (in other words, if files can be added, removed, and renamed within +** the directory). +** The SQLITE_ACCESS_READWRITE constant is currently used only by the +** [temp_store_directory pragma], though this could change in a future +** release of SQLite. +** With SQLITE_ACCESS_READ, the xAccess method +** checks whether the file is readable. The SQLITE_ACCESS_READ constant is +** currently unused, though it might be used in a future release of +** SQLite. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ +#define SQLITE_ACCESS_READ 2 /* Unused */ + +/* +** CAPI3REF: Flags for the xShmLock VFS method +** +** These integer constants define the various locking operations +** allowed by the xShmLock method of [sqlite3_io_methods]. The +** following are the only legal combinations of flags to the +** xShmLock method: +** +**
    +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE +**
+** +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as +** was given no the corresponding lock. +** +** The xShmLock method can transition between unlocked and SHARED or +** between unlocked and EXCLUSIVE. It cannot transition between SHARED +** and EXCLUSIVE. +*/ +#define SQLITE_SHM_UNLOCK 1 +#define SQLITE_SHM_LOCK 2 +#define SQLITE_SHM_SHARED 4 +#define SQLITE_SHM_EXCLUSIVE 8 + +/* +** CAPI3REF: Maximum xShmLock index +** +** The xShmLock method on [sqlite3_io_methods] may use values +** between 0 and this upper bound as its "offset" argument. +** The SQLite core will never attempt to acquire or release a +** lock outside of this range +*/ +#define SQLITE_SHM_NLOCK 8 + + +/* +** CAPI3REF: Initialize The SQLite Library +** +** ^The sqlite3_initialize() routine initializes the +** SQLite library. ^The sqlite3_shutdown() routine +** deallocates any resources that were allocated by sqlite3_initialize(). +** These routines are designed to aid in process initialization and +** shutdown on embedded systems. Workstation applications using +** SQLite normally do not need to invoke either of these routines. +** +** A call to sqlite3_initialize() is an "effective" call if it is +** the first time sqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time sqlite3_initialize() is invoked +** following a call to sqlite3_shutdown(). ^(Only an effective call +** of sqlite3_initialize() does any initialization. All other calls +** are harmless no-ops.)^ +** +** A call to sqlite3_shutdown() is an "effective" call if it is the first +** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only +** an effective call to sqlite3_shutdown() does any deinitialization. +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() +** is not. The sqlite3_shutdown() interface must only be called from a +** single thread. All open [database connections] must be closed and all +** other SQLite resources must be deallocated prior to invoking +** sqlite3_shutdown(). +** +** Among other things, ^sqlite3_initialize() will invoke +** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() +** will invoke sqlite3_os_end(). +** +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, sqlite3_initialize() is unable to initialize +** the library (perhaps it is unable to allocate a needed resource such +** as a mutex) it returns an [error code] other than [SQLITE_OK]. +** +** ^The sqlite3_initialize() routine is called internally by many other +** SQLite interfaces so that an application usually does not need to +** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] +** calls sqlite3_initialize() so the SQLite library will be automatically +** initialized when [sqlite3_open()] is called if it has not be initialized +** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] +** compile-time option, then the automatic calls to sqlite3_initialize() +** are omitted and the application must call sqlite3_initialize() directly +** prior to using any other SQLite interface. For maximum portability, +** it is recommended that applications always invoke sqlite3_initialize() +** directly prior to using any other SQLite interface. Future releases +** of SQLite may require this. In other words, the behavior exhibited +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the +** default behavior in some future release of SQLite. +** +** The sqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The sqlite3_os_end() +** routine undoes the effect of sqlite3_os_init(). Typical tasks +** performed by these routines include allocation or deallocation +** of static resources, initialization of global variables, +** setting up a default [sqlite3_vfs] module, or setting up +** a default configuration using [sqlite3_config()]. +** +** The application should never invoke either sqlite3_os_init() +** or sqlite3_os_end() directly. The application should only invoke +** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() +** interface is called automatically by sqlite3_initialize() and +** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate +** implementations for sqlite3_os_init() and sqlite3_os_end() +** are built into SQLite when it is compiled for Unix, Windows, or OS/2. +** When [custom builds | built for other platforms] +** (using the [SQLITE_OS_OTHER=1] compile-time +** option) the application must supply a suitable implementation for +** sqlite3_os_init() and sqlite3_os_end(). An application-supplied +** implementation of sqlite3_os_init() or sqlite3_os_end() +** must return [SQLITE_OK] on success and some other [error code] upon +** failure. +*/ +SQLITE_API int sqlite3_initialize(void); +SQLITE_API int sqlite3_shutdown(void); +SQLITE_API int sqlite3_os_init(void); +SQLITE_API int sqlite3_os_end(void); + +/* +** CAPI3REF: Configuring The SQLite Library +** +** The sqlite3_config() interface is used to make global configuration +** changes to SQLite in order to tune SQLite to the specific needs of +** the application. The default configuration is recommended for most +** applications and so this routine is usually not necessary. It is +** provided to support rare applications with unusual needs. +** +** The sqlite3_config() interface is not threadsafe. The application +** must insure that no other SQLite interfaces are invoked by other +** threads while sqlite3_config() is running. Furthermore, sqlite3_config() +** may only be invoked prior to library initialization using +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before +** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. +** Note, however, that ^sqlite3_config() can be called as part of the +** implementation of an application-defined [sqlite3_os_init()]. +** +** The first argument to sqlite3_config() is an integer +** [configuration option] that determines +** what property of SQLite is to be configured. Subsequent arguments +** vary depending on the [configuration option] +** in the first argument. +** +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^If the option is unknown or SQLite is unable to set the option +** then this routine returns a non-zero [error code]. +*/ +SQLITE_API int sqlite3_config(int, ...); + +/* +** CAPI3REF: Configure database connections +** +** The sqlite3_db_config() interface is used to make configuration +** changes to a [database connection]. The interface is similar to +** [sqlite3_config()] except that the changes apply to a single +** [database connection] (specified in the first argument). +** +** The second argument to sqlite3_db_config(D,V,...) is the +** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code +** that indicates what aspect of the [database connection] is being configured. +** Subsequent arguments vary depending on the configuration verb. +** +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** the call is considered successful. +*/ +SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Memory Allocation Routines +** +** An instance of this object defines the interface between SQLite +** and low-level memory allocation routines. +** +** This object is used in only one place in the SQLite interface. +** A pointer to an instance of this object is the argument to +** [sqlite3_config()] when the configuration option is +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. +** By creating an instance of this object +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** during configuration, an application can specify an alternative +** memory allocation subsystem for SQLite to use for all of its +** dynamic memory needs. +** +** Note that SQLite comes with several [built-in memory allocators] +** that are perfectly adequate for the overwhelming majority of applications +** and that this object is only useful to a tiny minority of applications +** with specialized memory allocation requirements. This object is +** also used during testing of SQLite in order to specify an alternative +** memory allocator that simulates memory out-of-memory conditions in +** order to verify that SQLite recovers gracefully from such +** conditions. +** +** The xMalloc, xRealloc, and xFree methods must work like the +** malloc(), realloc() and free() functions from the standard C library. +** ^SQLite guarantees that the second argument to +** xRealloc is always a value returned by a prior call to xRoundup. +** +** xSize should return the allocated size of a memory allocation +** previously obtained from xMalloc or xRealloc. The allocated size +** is always at least as big as the requested size but may be larger. +** +** The xRoundup method returns what would be the allocated size of +** a memory allocation given a particular requested size. Most memory +** allocators round up memory allocations at least to the next multiple +** of 8. Some allocators round up to a larger multiple or to a power of 2. +** Every memory allocation request coming in through [sqlite3_malloc()] +** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** that causes the corresponding memory allocation to fail. +** +** The xInit method initializes the memory allocator. (For example, +** it might allocate any require mutexes or initialize internal data +** structures. The xShutdown method is invoked (indirectly) by +** [sqlite3_shutdown()] and should deallocate any resources acquired +** by xInit. The pAppData pointer is used as the only parameter to +** xInit and xShutdown. +** +** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes +** the xInit method, so the xInit method need not be threadsafe. The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. For all other methods, SQLite +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which +** it is by default) and so the methods are automatically serialized. +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other +** methods must be threadsafe or else make their own arrangements for +** serialization. +** +** SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +*/ +typedef struct sqlite3_mem_methods sqlite3_mem_methods; +struct sqlite3_mem_methods { + void *(*xMalloc)(int); /* Memory allocation function */ + void (*xFree)(void*); /* Free a prior allocation */ + void *(*xRealloc)(void*,int); /* Resize an allocation */ + int (*xSize)(void*); /* Return the size of an allocation */ + int (*xRoundup)(int); /* Round up request size to allocation size */ + int (*xInit)(void*); /* Initialize the memory allocator */ + void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + void *pAppData; /* Argument to xInit() and xShutdown() */ +}; + +/* +** CAPI3REF: Configuration Options +** KEYWORDS: {configuration option} +** +** These constants are the available integer configuration options that +** can be passed as the first argument to the [sqlite3_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_config()] to make sure that +** the call worked. The [sqlite3_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+** [[SQLITE_CONFIG_SINGLETHREAD]]
SQLITE_CONFIG_SINGLETHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Single-thread. In other words, it disables +** all mutexing and puts SQLite into a mode where it can only be used +** by a single thread. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to change the [threading mode] from its default +** value of Single-thread and so [sqlite3_config()] will return +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD +** configuration option.
+** +** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Multi-thread. In other words, it disables +** mutexing on [database connection] and [prepared statement] objects. +** The application is responsible for serializing access to +** [database connections] and [prepared statements]. But other mutexes +** are enabled so that SQLite will be safe to use in a multi-threaded +** environment as long as no two threads attempt to use the same +** [database connection] at the same time. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Multi-thread [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_MULTITHREAD configuration option.
+** +** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Serialized. In other words, this option enables +** all mutexes including the recursive +** mutexes on [database connection] and [prepared statement] objects. +** In this mode (which is the default when SQLite is compiled with +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access +** to [database connections] and [prepared statements] so that the +** application is free to use the same [database connection] or the +** same [prepared statement] in different threads at the same time. +** ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Serialized [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_SERIALIZED configuration option.
+** +** [[SQLITE_CONFIG_MALLOC]]
SQLITE_CONFIG_MALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The argument specifies +** alternative low-level memory allocation routines to be used in place of +** the memory allocation routines built into SQLite.)^ ^SQLite makes +** its own private copy of the content of the [sqlite3_mem_methods] structure +** before the [sqlite3_config()] call returns.
+** +** [[SQLITE_CONFIG_GETMALLOC]]
SQLITE_CONFIG_GETMALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] +** structure is filled with the currently defined memory allocation routines.)^ +** This option can be used to overload the default memory allocation +** routines with a wrapper that simulations memory allocation failure or +** tracks memory usage, for example.
+** +** [[SQLITE_CONFIG_MEMSTATUS]]
SQLITE_CONFIG_MEMSTATUS
+**
^This option takes single argument of type int, interpreted as a +** boolean, which enables or disables the collection of memory allocation +** statistics. ^(When memory allocation statistics are disabled, the +** following SQLite interfaces become non-operational: +**
    +**
  • [sqlite3_memory_used()] +**
  • [sqlite3_memory_highwater()] +**
  • [sqlite3_soft_heap_limit64()] +**
  • [sqlite3_status()] +**
)^ +** ^Memory allocation statistics are enabled by default unless SQLite is +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory +** allocation statistics are disabled by default. +**
+** +** [[SQLITE_CONFIG_SCRATCH]]
SQLITE_CONFIG_SCRATCH
+**
^This option specifies a static memory buffer that SQLite can use for +** scratch memory. There are three arguments: A pointer an 8-byte +** aligned memory buffer from which the scratch allocations will be +** drawn, the size of each scratch allocation (sz), +** and the maximum number of scratch allocations (N). The sz +** argument must be a multiple of 16. +** The first argument must be a pointer to an 8-byte aligned buffer +** of at least sz*N bytes of memory. +** ^SQLite will use no more than two scratch buffers per thread. So +** N should be set to twice the expected maximum number of threads. +** ^SQLite will never require a scratch buffer that is more than 6 +** times the database page size. ^If SQLite needs needs additional +** scratch memory beyond what is provided by this configuration option, then +** [sqlite3_malloc()] will be used to obtain the memory needed.
+** +** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
+**
^This option specifies a static memory buffer that SQLite can use for +** the database page cache with the default page cache implementation. +** This configuration should not be used if an application-define page +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option. +** There are three arguments to this option: A pointer to 8-byte aligned +** memory, the size of each page buffer (sz), and the number of pages (N). +** The sz argument should be the size of the largest database page +** (a power of two between 512 and 32768) plus a little extra for each +** page header. ^The page header size is 20 to 40 bytes depending on +** the host architecture. ^It is harmless, apart from the wasted memory, +** to make sz a little too large. The first +** argument should point to an allocation of at least sz*N bytes of memory. +** ^SQLite will use the memory provided by the first argument to satisfy its +** memory needs for the first N pages that it adds to cache. ^If additional +** page cache memory is needed beyond what is provided by this option, then +** SQLite goes to [sqlite3_malloc()] for the additional storage space. +** The pointer in the first argument must +** be aligned to an 8-byte boundary or subsequent behavior of SQLite +** will be undefined.
+** +** [[SQLITE_CONFIG_HEAP]]
SQLITE_CONFIG_HEAP
+**
^This option specifies a static memory buffer that SQLite will use +** for all of its dynamic memory allocation needs beyond those provided +** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. +** There are three arguments: An 8-byte aligned pointer to the memory, +** the number of bytes in the memory buffer, and the minimum allocation size. +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts +** to using its default memory allocator (the system malloc() implementation), +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the +** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or +** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory +** allocator is engaged to handle all of SQLites memory allocation needs. +** The first pointer (the memory pointer) must be aligned to an 8-byte +** boundary or subsequent behavior of SQLite will be undefined. +** The minimum allocation size is capped at 2**12. Reasonable values +** for the minimum allocation size are 2**5 through 2**8.
+** +** [[SQLITE_CONFIG_MUTEX]]
SQLITE_CONFIG_MUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The argument specifies +** alternative low-level mutex routines to be used in place +** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the +** content of the [sqlite3_mutex_methods] structure before the call to +** [sqlite3_config()] returns. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_GETMUTEX]]
SQLITE_CONFIG_GETMUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The +** [sqlite3_mutex_methods] +** structure is filled with the currently defined mutex routines.)^ +** This option can be used to overload the default mutex allocation +** routines with a wrapper used to track mutex usage for performance +** profiling or testing, for example. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
+**
^(This option takes two arguments that determine the default +** memory allocation for the lookaside memory allocator on each +** [database connection]. The first argument is the +** size of each lookaside buffer slot and the second is the number of +** slots allocated to each database connection.)^ ^(This option sets the +** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] +** verb to [sqlite3_db_config()] can be used to change the lookaside +** configuration on individual connections.)^
+** +** [[SQLITE_CONFIG_PCACHE2]]
SQLITE_CONFIG_PCACHE2
+**
^(This option takes a single argument which is a pointer to +** an [sqlite3_pcache_methods2] object. This object specifies the interface +** to a custom page cache implementation.)^ ^SQLite makes a copy of the +** object and uses it for page cache memory allocations.
+** +** [[SQLITE_CONFIG_GETPCACHE2]]
SQLITE_CONFIG_GETPCACHE2
+**
^(This option takes a single argument which is a pointer to an +** [sqlite3_pcache_methods2] object. SQLite copies of the current +** page cache implementation into that object.)^
+** +** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
+**
The SQLITE_CONFIG_LOG option is used to configure the SQLite +** global [error log]. +** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a +** function with a call signature of void(*)(void*,int,const char*), +** and a pointer to void. ^If the function pointer is not NULL, it is +** invoked by [sqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is +** passed through as the first parameter to the application-defined logger +** function whenever that function is invoked. ^The second parameter to +** the logger function is a copy of the first parameter to the corresponding +** [sqlite3_log()] call and is intended to be a [result code] or an +** [extended result code]. ^The third parameter passed to the logger is +** log message after formatting via [sqlite3_snprintf()]. +** The SQLite logging interface is not reentrant; the logger function +** supplied by the application must not invoke any SQLite interface. +** In a multi-threaded application, the application-defined logger +** function must be threadsafe.
+** +** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI +**
^(This option takes a single argument of type int. If non-zero, then +** URI handling is globally enabled. If the parameter is zero, then URI handling +** is globally disabled.)^ ^If URI handling is globally enabled, all filenames +** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or +** specified as part of [ATTACH] commands are interpreted as URIs, regardless +** of whether or not the [SQLITE_OPEN_URI] flag is set when the database +** connection is opened. ^If it is globally disabled, filenames are +** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the +** database connection is opened. ^(By default, URI handling is globally +** disabled. The default value may be changed by compiling with the +** [SQLITE_USE_URI] symbol defined.)^ +** +** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
SQLITE_CONFIG_COVERING_INDEX_SCAN +**
^This option takes a single integer argument which is interpreted as +** a boolean in order to enable or disable the use of covering indices for +** full table scans in the query optimizer. ^The default setting is determined +** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" +** if that compile-time option is omitted. +** The ability to disable the use of covering indices for full table scans +** is because some incorrectly coded legacy applications might malfunction +** when the optimization is enabled. Providing the ability to +** disable the optimization allows the older, buggy application code to work +** without change even with newer versions of SQLite. +** +** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] +**
SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE +**
These options are obsolete and should not be used by new code. +** They are retained for backwards compatibility but are now no-ops. +**
+** +** [[SQLITE_CONFIG_SQLLOG]] +**
SQLITE_CONFIG_SQLLOG +**
This option is only available if sqlite is compiled with the +** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should +** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). +** The second should be of type (void*). The callback is invoked by the library +** in three separate circumstances, identified by the value passed as the +** fourth parameter. If the fourth parameter is 0, then the database connection +** passed as the second argument has just been opened. The third argument +** points to a buffer containing the name of the main database file. If the +** fourth parameter is 1, then the SQL statement that the third parameter +** points to has just been executed. Or, if the fourth parameter is 2, then +** the connection being passed as the second parameter is being closed. The +** third parameter is passed NULL In this case. An example of using this +** configuration option can be seen in the "test_sqllog.c" source file in +** the canonical SQLite source tree.
+** +** [[SQLITE_CONFIG_MMAP_SIZE]] +**
SQLITE_CONFIG_MMAP_SIZE +**
^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values +** that are the default mmap size limit (the default setting for +** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. +** ^The default setting can be overridden by each database connection using +** either the [PRAGMA mmap_size] command, or by using the +** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size +** cannot be changed at run-time. Nor may the maximum allowed mmap size +** exceed the compile-time maximum mmap size set by the +** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ +** ^If either argument to this option is negative, then that argument is +** changed to its compile-time default. +**
+*/ +#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ +#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ +#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ +#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ +#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ +#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ +#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ +#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ +#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ +#define SQLITE_CONFIG_PCACHE 14 /* no-op */ +#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ +#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ +#define SQLITE_CONFIG_URI 17 /* int */ +#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ +#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ +#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ + +/* +** CAPI3REF: Database Connection Configuration Options +** +** These constants are the available integer configuration options that +** can be passed as the second argument to the [sqlite3_db_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_db_config()] to make sure that +** the call worked. ^The [sqlite3_db_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+**
SQLITE_DBCONFIG_LOOKASIDE
+**
^This option takes three additional arguments that determine the +** [lookaside memory allocator] configuration for the [database connection]. +** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** pointer to a memory buffer to use for lookaside memory. +** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb +** may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the +** size of each lookaside buffer slot. ^The third argument is the number of +** slots. The size of the buffer in the first argument must be greater than +** or equal to the product of the second and third arguments. The buffer +** must be aligned to an 8-byte boundary. ^If the second argument to +** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally +** rounded down to the next smaller multiple of 8. ^(The lookaside memory +** configuration for a database connection can only be changed when that +** connection is not currently using lookaside memory, or in other words +** when the "current value" returned by +** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. +** Any attempt to change the lookaside memory configuration when lookaside +** memory is in use leaves the configuration unchanged and returns +** [SQLITE_BUSY].)^
+** +**
SQLITE_DBCONFIG_ENABLE_FKEY
+**
^This option is used to enable or disable the enforcement of +** [foreign key constraints]. There should be two additional arguments. +** The first argument is an integer which is 0 to disable FK enforcement, +** positive to enable FK enforcement or negative to leave FK enforcement +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether FK enforcement is off or on +** following this call. The second parameter may be a NULL pointer, in +** which case the FK enforcement setting is not reported back.
+** +**
SQLITE_DBCONFIG_ENABLE_TRIGGER
+**
^This option is used to enable or disable [CREATE TRIGGER | triggers]. +** There should be two additional arguments. +** The first argument is an integer which is 0 to disable triggers, +** positive to enable triggers or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether triggers are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the trigger setting is not reported back.
+** +**
+*/ +#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ +#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ + + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes +** +** ^The sqlite3_extended_result_codes() routine enables or disables the +** [extended result codes] feature of SQLite. ^The extended result +** codes are disabled by default for historical compatibility. +*/ +SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid +** +** ^Each entry in an SQLite table has a unique 64-bit signed +** integer key called the [ROWID | "rowid"]. ^The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. ^If +** the table has a column of type [INTEGER PRIMARY KEY] then that column +** is another alias for the rowid. +** +** ^This routine returns the [rowid] of the most recent +** successful [INSERT] into the database from the [database connection] +** in the first argument. ^As of SQLite version 3.7.7, this routines +** records the last insert rowid of both ordinary tables and [virtual tables]. +** ^If no successful [INSERT]s +** have ever occurred on that database connection, zero is returned. +** +** ^(If an [INSERT] occurs within a trigger or within a [virtual table] +** method, then this routine will return the [rowid] of the inserted +** row as long as the trigger or virtual table method is running. +** But once the trigger or virtual table method ends, the value returned +** by this routine reverts to what it was before the trigger or virtual +** table method began.)^ +** +** ^An [INSERT] that fails due to a constraint violation is not a +** successful [INSERT] and does not change the value returned by this +** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. ^(When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface.)^ +** +** ^For the purposes of this routine, an [INSERT] is considered to +** be successful even if it is subsequently rolled back. +** +** This function is accessible to SQL statements via the +** [last_insert_rowid() SQL function]. +** +** If a separate thread performs a new [INSERT] on the same +** database connection while the [sqlite3_last_insert_rowid()] +** function is running and thus changes the last insert [rowid], +** then the value returned by [sqlite3_last_insert_rowid()] is +** unpredictable and might not equal either the old or the new +** last insert [rowid]. +*/ +SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified +** +** ^This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the [database connection] specified by the first parameter. +** ^(Only changes that are directly specified by the [INSERT], [UPDATE], +** or [DELETE] statement are counted. Auxiliary changes caused by +** triggers or [foreign key actions] are not counted.)^ Use the +** [sqlite3_total_changes()] function to find the total number of changes +** including changes caused by triggers and foreign key actions. +** +** ^Changes to a view that are simulated by an [INSTEAD OF trigger] +** are not counted. Only real table changes are counted. +** +** ^(A "row change" is a change to a single row of a single table +** caused by an INSERT, DELETE, or UPDATE statement. Rows that +** are changed as side effects of [REPLACE] constraint resolution, +** rollback, ABORT processing, [DROP TABLE], or by any other +** mechanisms do not count as direct row changes.)^ +** +** A "trigger context" is a scope of execution that begins and +** ends with the script of a [CREATE TRIGGER | trigger]. +** Most SQL statements are +** evaluated outside of any trigger. This is the "top level" +** trigger context. If a trigger fires from the top level, a +** new trigger context is entered for the duration of that one +** trigger. Subtriggers create subcontexts for their duration. +** +** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does +** not create a new trigger context. +** +** ^This function returns the number of direct row changes in the +** most recent INSERT, UPDATE, or DELETE statement within the same +** trigger context. +** +** ^Thus, when called from the top level, this function returns the +** number of changes in the most recent INSERT, UPDATE, or DELETE +** that also occurred at the top level. ^(Within the body of a trigger, +** the sqlite3_changes() interface can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** However, the number returned does not include changes +** caused by subtriggers since those have their own context.)^ +** +** See also the [sqlite3_total_changes()] interface, the +** [count_changes pragma], and the [changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified +** +** ^This function returns the number of row changes caused by [INSERT], +** [UPDATE] or [DELETE] statements since the [database connection] was opened. +** ^(The count returned by sqlite3_total_changes() includes all changes +** from all [CREATE TRIGGER | trigger] contexts and changes made by +** [foreign key actions]. However, +** the count does not include changes used to implement [REPLACE] constraints, +** do rollbacks or ABORT processing, or [DROP TABLE] processing. The +** count does not include rows of views that fire an [INSTEAD OF trigger], +** though if the INSTEAD OF trigger makes changes of its own, those changes +** are counted.)^ +** ^The sqlite3_total_changes() function counts the changes as soon as +** the statement that makes them is completed (when the statement handle +** is passed to [sqlite3_reset()] or [sqlite3_finalize()]). +** +** See also the [sqlite3_changes()] interface, the +** [count_changes pragma], and the [total_changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query +** +** ^This function causes any pending database operation to abort and +** return at its earliest opportunity. This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** ^It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. But it +** is not safe to call this routine with a [database connection] that +** is closed or might close before sqlite3_interrupt() returns. +** +** ^If an SQL operation is very nearly finished at the time when +** sqlite3_interrupt() is called, then it might not have an opportunity +** to be interrupted and might continue to completion. +** +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE +** that is inside an explicit transaction, then the entire transaction +** will be rolled back automatically. +** +** ^The sqlite3_interrupt(D) call is in effect until all currently running +** SQL statements on [database connection] D complete. ^Any new SQL statements +** that are started after the sqlite3_interrupt() call and before the +** running statements reaches zero are interrupted as if they had been +** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the running statement count reaches zero are +** not effected by the sqlite3_interrupt(). +** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** SQL statements is a no-op and has no effect on SQL statements +** that are started after the sqlite3_interrupt() call returns. +** +** If the database connection closes while [sqlite3_interrupt()] +** is running then bad things will likely happen. +*/ +SQLITE_API void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete +** +** These routines are useful during command-line input to determine if the +** currently entered text seems to form a complete SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. ^These routines return 1 if the input string +** appears to be a complete SQL statement. ^A statement is judged to be +** complete if it ends with a semicolon token and is not a prefix of a +** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within +** string literals or quoted identifier names or comments are not +** independent tokens (they are part of the token in which they are +** embedded) and thus do not count as a statement terminator. ^Whitespace +** and comments that follow the final semicolon are ignored. +** +** ^These routines return 0 if the statement is incomplete. ^If a +** memory allocation fails, then SQLITE_NOMEM is returned. +** +** ^These routines do not parse the SQL statements thus +** will not detect syntactically incorrect SQL. +** +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked +** automatically by sqlite3_complete16(). If that initialization fails, +** then the return value from sqlite3_complete16() will be non-zero +** regardless of whether or not the input SQL is complete.)^ +** +** The input to [sqlite3_complete()] must be a zero-terminated +** UTF-8 string. +** +** The input to [sqlite3_complete16()] must be a zero-terminated +** UTF-16 string in native byte order. +*/ +SQLITE_API int sqlite3_complete(const char *sql); +SQLITE_API int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors +** +** ^This routine sets a callback function that might be invoked whenever +** an attempt is made to open a database table that another thread +** or process has locked. +** +** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. ^If the busy callback +** is not NULL, then the callback might be invoked with two arguments. +** +** ^The first argument to the busy handler is a copy of the void* pointer which +** is the third argument to sqlite3_busy_handler(). ^The second argument to +** the busy handler callback is the number of times that the busy handler has +** been invoked for this locking event. ^If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** ^If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that it will be invoked +** when there is lock contention. ^If SQLite determines that invoking the busy +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** ^The default busy callback is NULL. +** +** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. ^If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion +** forces an automatic rollback of the changes. See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** ^(There can only be a single busy handler defined for each +** [database connection]. Setting a new busy handler clears any +** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** will also set or clear the busy handler. +** +** The busy callback should not take any actions which modify the +** database connection that invoked the busy handler. Any such actions +** result in undefined behavior. +** +** A busy handler must not close the database connection +** or [prepared statement] that invoked the busy handler. +*/ +SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout +** +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** for a specified amount of time when a table is locked. ^The handler +** will sleep multiple times until at least "ms" milliseconds of sleeping +** have accumulated. ^After at least "ms" milliseconds of sleeping, +** the handler returns 0 which causes [sqlite3_step()] to return +** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** ^Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** ^(There can only be a single busy handler for a particular +** [database connection] any any given moment. If another busy handler +** was defined (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared.)^ +*/ +SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries +** +** This is a legacy interface that is preserved for backwards compatibility. +** Use of this interface is not recommended. +** +** Definition: A result table is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** The table conceptually has a number of rows and columns. But +** these numbers are not part of the result table itself. These +** numbers are obtained separately. Let N be the number of rows +** and M be the number of columns. +** +** A result table is an array of pointers to zero-terminated UTF-8 strings. +** There are (N+1)*M elements in the array. The first M pointers point +** to zero-terminated strings that contain the names of the columns. +** The remaining entries all point to query results. NULL values result +** in NULL pointers. All other values are in their UTF-8 zero-terminated +** string representation as returned by [sqlite3_column_text()]. +** +** A result table might consist of one or more memory allocations. +** It is not safe to pass a result table directly to [sqlite3_free()]. +** A result table should be deallocated using [sqlite3_free_table()]. +** +** ^(As an example of the result table format, suppose a query result +** is as follows: +** +**
+**        Name        | Age
+**        -----------------------
+**        Alice       | 43
+**        Bob         | 28
+**        Cindy       | 21
+** 
+** +** There are two column (M==2) and three rows (N==3). Thus the +** result table has 8 entries. Suppose the result table is stored +** in an array names azResult. Then azResult holds this content: +** +**
+**        azResult[0] = "Name";
+**        azResult[1] = "Age";
+**        azResult[2] = "Alice";
+**        azResult[3] = "43";
+**        azResult[4] = "Bob";
+**        azResult[5] = "28";
+**        azResult[6] = "Cindy";
+**        azResult[7] = "21";
+** 
)^ +** +** ^The sqlite3_get_table() function evaluates one or more +** semicolon-separated SQL statements in the zero-terminated UTF-8 +** string of its 2nd parameter and returns a result table to the +** pointer given in its 3rd parameter. +** +** After the application has finished with the result from sqlite3_get_table(), +** it must pass the result table pointer to sqlite3_free_table() in order to +** release the memory that was malloced. Because of the way the +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling +** function must not try to call [sqlite3_free()] directly. Only +** [sqlite3_free_table()] is able to release the memory properly and safely. +** +** The sqlite3_get_table() interface is implemented as a wrapper around +** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** to any internal data structures of SQLite. It uses only the public +** interface defined here. As a consequence, errors that occur in the +** wrapper layer outside of the internal [sqlite3_exec()] call are not +** reflected in subsequent calls to [sqlite3_errcode()] or +** [sqlite3_errmsg()]. +*/ +SQLITE_API int sqlite3_get_table( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + char ***pazResult, /* Results of the query */ + int *pnRow, /* Number of result rows written here */ + int *pnColumn, /* Number of result columns written here */ + char **pzErrmsg /* Error msg written here */ +); +SQLITE_API void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions +** +** These routines are work-alikes of the "printf()" family of functions +** from the standard C library. +** +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** The strings returned by these two routines should be +** released by [sqlite3_free()]. ^Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. Note that the order of the +** first two parameters is reversed from snprintf().)^ This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. ^(Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer.)^ We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. ^The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. So the longest string that can be completely +** written will be n-1 characters. +** +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf() formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** ^(The %q option works like %s in that it substitutes a nul-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal.)^ By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, assume the string variable zText contains text as follows: +** +**
+**  char *zText = "It's a happy day!";
+** 
+** +** One can use this text in an SQL statement as follows: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
+**  INSERT INTO table1 VALUES('It''s a happy day!')
+** 
+** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
+**  INSERT INTO table1 VALUES('It's a happy day!');
+** 
+** +** This second example is an SQL syntax error. As a general rule you should +** always use %q instead of %s when inserting text into a string literal. +** +** ^(The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Additionally, if the parameter in the +** argument list is a NULL pointer, %Q substitutes the text "NULL" (without +** single quotes).)^ So, for example, one could say: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** ^(The "%z" formatting option works like "%s" but with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string.)^ +*/ +SQLITE_API char *sqlite3_mprintf(const char*,...); +SQLITE_API char *sqlite3_vmprintf(const char*, va_list); +SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); + +/* +** CAPI3REF: Memory Allocation Subsystem +** +** The SQLite core uses these three routines for all of its own +** internal memory allocation needs. "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** Windows VFS uses native malloc() and free() for some operations. +** +** ^The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** ^If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. ^If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** ^Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. ^The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** +** ^(The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter.)^ ^ If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** ^If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** ^sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** ^If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** ^If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** ^The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary, or to a +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time +** option is used. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be used. +** +** Prior to SQLite version 3.7.10, the Windows OS interface layer called +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular Windows +** installation. Memory allocation errors were detected, but +** they were reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +** +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else pointers obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** not yet been released. +** +** The application must not read or write any part of +** a block of memory after it has been released using +** [sqlite3_free()] or [sqlite3_realloc()]. +*/ +SQLITE_API void *sqlite3_malloc(int); +SQLITE_API void *sqlite3_realloc(void*, int); +SQLITE_API void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** routines, which form the built-in memory allocation subsystem. +** +** ^The [sqlite3_memory_used()] routine returns the number of bytes +** of memory currently outstanding (malloced but not freed). +** ^The [sqlite3_memory_highwater()] routine returns the maximum +** value of [sqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [sqlite3_memory_used()] and +** [sqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [sqlite3_malloc()], +** but not overhead added by the any underlying system library +** routines that [sqlite3_malloc()] may call. +** +** ^The memory high-water mark is reset to the current value of +** [sqlite3_memory_used()] if and only if the parameter to +** [sqlite3_memory_highwater()] is true. ^The value returned +** by [sqlite3_memory_highwater(1)] is the high-water mark +** prior to the reset. +*/ +SQLITE_API sqlite3_int64 sqlite3_memory_used(void); +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Pseudo-Random Number Generator +** +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to +** select random [ROWID | ROWIDs] when inserting new records into a table that +** already uses the largest possible [ROWID]. The PRNG is also used for +** the build-in random() and randomblob() SQL functions. This interface allows +** applications to access the same PRNG for other purposes. +** +** ^A call to this routine stores N bytes of randomness into buffer P. +** +** ^The first time this routine is invoked (either internally or by +** the application) the PRNG is seeded using randomness obtained +** from the xRandomness method of the default [sqlite3_vfs] object. +** ^On all subsequent invocations, the pseudo-randomness is generated +** internally and without recourse to the [sqlite3_vfs] xRandomness +** method. +*/ +SQLITE_API void sqlite3_randomness(int N, void *P); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks +** +** ^This routine registers an authorizer callback with a particular +** [database connection], supplied in the first argument. +** ^The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. ^The authorizer callback should +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. ^If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. ^When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer will fail with an error message explaining that +** access is denied. +** +** ^The first parameter to the authorizer callback is a copy of the third +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** to the callback is an integer [SQLITE_COPY | action code] that specifies +** the particular action to be authorized. ^The third through sixth parameters +** to the callback are zero-terminated strings that contain additional +** details about the action to be authorized. +** +** ^If the action code is [SQLITE_READ] +** and the callback returns [SQLITE_IGNORE] then the +** [prepared statement] statement is constructed to substitute +** a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] +** return can be used to deny an untrusted user access to individual +** columns of a table. +** ^If the action code is [SQLITE_DELETE] and the callback returns +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the +** [truncate optimization] is disabled and all rows are deleted individually. +** +** An authorizer is used when [sqlite3_prepare | preparing] +** SQL statements from an untrusted source, to ensure that the SQL statements +** do not try to access data they are not allowed to see, or that they do not +** try to execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being [sqlite3_prepare | prepared] that +** disallows everything except [SELECT] statements. +** +** Applications that need to process SQL from untrusted sources +** might also consider lowering resource limits using [sqlite3_limit()] +** and limiting database size using the [max_page_count] [PRAGMA] +** in addition to using an authorizer. +** +** ^(Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call.)^ ^Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. +** +** The authorizer callback must not do anything that will modify +** the database connection that invoked the authorizer callback. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [sqlite3_step()] due to a +** schema change. Hence, the application should ensure that the +** correct authorizer callback remains in place during the [sqlite3_step()]. +** +** ^Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [sqlite3_step()], unless +** as stated in the previous paragraph, sqlite3_step() invokes +** sqlite3_prepare_v2() to reprepare a statement after a schema change. +*/ +SQLITE_API int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +** +** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code] +** from the [sqlite3_vtab_on_conflict()] interface. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorize certain SQL statement actions. The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. +** +** These action code values signify what kind of operation is to be +** authorized. The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. ^(The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* Operation NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* NULL Function Name */ +#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** ^The callback function registered by sqlite3_trace() is invoked at +** various times when an SQL statement is being run by [sqlite3_step()]. +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** SQL statement text as the statement first begins executing. +** ^(Additional sqlite3_trace() callbacks might occur +** as each triggered subprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger.)^ +** +** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit +** the length of [bound parameter] expansion in the output of sqlite3_trace(). +** +** ^The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. ^The profile callback contains +** the original statement text and an estimate of wall-clock time +** of how long that statement took to run. ^The profile callback +** time is in units of nanoseconds, however the current implementation +** is only capable of millisecond resolution so the six least significant +** digits in the time are meaningless. Future versions of SQLite +** might provide greater resolution on the profiler callback. The +** sqlite3_profile() function is considered experimental and is +** subject to change in future versions of SQLite. +*/ +SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks +** +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** function X to be invoked periodically during long running calls to +** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for +** database connection D. An example use for this +** interface is to keep a GUI updated during a large query. +** +** ^The parameter P is passed through as the only parameter to the +** callback function X. ^The parameter N is the approximate number of +** [virtual machine instructions] that are evaluated between successive +** invocations of the callback X. ^If N is less than one then the progress +** handler is disabled. +** +** ^Only a single progress handler may be defined at one time per +** [database connection]; setting a new progress handler cancels the +** old one. ^Setting parameter X to NULL disables the progress handler. +** ^The progress handler is also disabled by setting N to a value less +** than 1. +** +** ^If the progress callback returns non-zero, the operation is +** interrupted. This feature can be used to implement a +** "Cancel" button on a GUI progress dialog box. +** +** The progress handler callback must not do anything that will modify +** the database connection that invoked the progress handler. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +*/ +SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection +** +** ^These routines open an SQLite database file as specified by the +** filename argument. ^The filename argument is interpreted as UTF-8 for +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte +** order for sqlite3_open16(). ^(A [database connection] handle is usually +** returned in *ppDb, even if an error occurs. The only exception is that +** if SQLite is unable to allocate memory to hold the [sqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** object.)^ ^(If the database is opened (and/or created) successfully, then +** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error following a failure of any +** of the sqlite3_open() routines. +** +** ^The default encoding for the database will be UTF-8 if +** sqlite3_open() or sqlite3_open_v2() is called and +** UTF-16 in the native byte order if sqlite3_open16() is used. +** +** Whether or not an error occurs when it is opened, resources +** associated with the [database connection] handle should be released by +** passing it to [sqlite3_close()] when it is no longer required. +** +** The sqlite3_open_v2() interface works like sqlite3_open() +** except that it accepts two additional parameters for additional control +** over the new database connection. ^(The flags parameter to +** sqlite3_open_v2() can take one of +** the following three values, optionally combined with the +** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], +** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ +** +**
+** ^(
[SQLITE_OPEN_READONLY]
+**
The database is opened in read-only mode. If the database does not +** already exist, an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE]
+**
The database is opened for reading and writing if possible, or reading +** only if the file is write protected by the operating system. In either +** case the database must already exist, otherwise an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
+**
The database is opened for reading and writing, and is created if +** it does not already exist. This is the behavior that is always used for +** sqlite3_open() and sqlite3_open16().
)^ +**
+** +** If the 3rd parameter to sqlite3_open_v2() is not one of the +** combinations shown above optionally combined with other +** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] +** then the behavior is undefined. +** +** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection +** opens in the multi-thread [threading mode] as long as the single-thread +** mode has not been set at compile-time or start-time. ^If the +** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens +** in the serialized [threading mode] unless single-thread was +** previously selected at compile-time or start-time. +** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be +** eligible to use [shared cache mode], regardless of whether or not shared +** cache is enabled using [sqlite3_enable_shared_cache()]. ^The +** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not +** participate in [shared cache mode] even if it is enabled. +** +** ^The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system interface that +** the new database connection should use. ^If the fourth parameter is +** a NULL pointer then the default [sqlite3_vfs] object is used. +** +** ^If the filename is ":memory:", then a private, temporary in-memory database +** is created for the connection. ^This in-memory database will vanish when +** the database connection is closed. Future versions of SQLite might +** make use of additional special filenames that begin with the ":" character. +** It is recommended that when a database filename actually does begin with +** a ":" character you should prefix the filename with a pathname such as +** "./" to avoid ambiguity. +** +** ^If the filename is an empty string, then a private, temporary +** on-disk database will be created. ^This private database will be +** automatically deleted as soon as the database connection is closed. +** +** [[URI filenames in sqlite3_open()]]

URI Filenames

+** +** ^If [URI filename] interpretation is enabled, and the filename argument +** begins with "file:", then the filename is interpreted as a URI. ^URI +** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is +** set in the fourth argument to sqlite3_open_v2(), or if it has +** been enabled globally using the [SQLITE_CONFIG_URI] option with the +** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. +** As of SQLite version 3.7.7, URI filename interpretation is turned off +** by default, but future releases of SQLite might enable URI filename +** interpretation by default. See "[URI filenames]" for additional +** information. +** +** URI filenames are parsed according to RFC 3986. ^If the URI contains an +** authority, then it must be either an empty string or the string +** "localhost". ^If the authority is not an empty string or "localhost", an +** error is returned to the caller. ^The fragment component of a URI, if +** present, is ignored. +** +** ^SQLite uses the path component of the URI as the name of the disk file +** which contains the database. ^If the path begins with a '/' character, +** then it is interpreted as an absolute path. ^If the path does not begin +** with a '/' (meaning that the authority section is omitted from the URI) +** then the path is interpreted as a relative path. +** ^On windows, the first component of an absolute path +** is a drive specification (e.g. "C:"). +** +** [[core URI query parameters]] +** The query component of a URI may contain parameters that are interpreted +** either by SQLite itself, or by a [VFS | custom VFS implementation]. +** SQLite interprets the following three query parameters: +** +**
    +**
  • vfs: ^The "vfs" parameter may be used to specify the name of +** a VFS object that provides the operating system interface that should +** be used to access the database file on disk. ^If this option is set to +** an empty string the default VFS object is used. ^Specifying an unknown +** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is +** present, then the VFS specified by the option takes precedence over +** the value passed as the fourth parameter to sqlite3_open_v2(). +** +**
  • mode: ^(The mode parameter may be set to either "ro", "rw", +** "rwc", or "memory". Attempting to set it to any other value is +** an error)^. +** ^If "ro" is specified, then the database is opened for read-only +** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the +** third argument to sqlite3_open_v2(). ^If the mode option is set to +** "rw", then the database is opened for read-write (but not create) +** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had +** been set. ^Value "rwc" is equivalent to setting both +** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is +** set to "memory" then a pure [in-memory database] that never reads +** or writes from disk is used. ^It is an error to specify a value for +** the mode parameter that is less restrictive than that specified by +** the flags passed in the third parameter to sqlite3_open_v2(). +** +**
  • cache: ^The cache parameter may be set to either "shared" or +** "private". ^Setting it to "shared" is equivalent to setting the +** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to +** sqlite3_open_v2(). ^Setting the cache parameter to "private" is +** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. +** ^If sqlite3_open_v2() is used and the "cache" parameter is present in +** a URI filename, its value overrides any behavior requested by setting +** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. +**
+** +** ^Specifying an unknown parameter in the query component of a URI is not an +** error. Future versions of SQLite might understand additional query +** parameters. See "[query parameters with special meaning to SQLite]" for +** additional information. +** +** [[URI filename examples]]

URI filename examples

+** +**
+**
URI filenames Results +**
file:data.db +** Open the file "data.db" in the current directory. +**
file:/home/fred/data.db
+** file:///home/fred/data.db
+** file://localhost/home/fred/data.db
+** Open the database file "/home/fred/data.db". +**
file://darkstar/home/fred/data.db +** An error. "darkstar" is not a recognized authority. +**
+** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db +** Windows only: Open the file "data.db" on fred's desktop on drive +** C:. Note that the %20 escaping in this example is not strictly +** necessary - space characters can be used literally +** in URI filenames. +**
file:data.db?mode=ro&cache=private +** Open file "data.db" in the current directory for read-only access. +** Regardless of whether or not shared-cache mode is enabled by +** default, use a private cache. +**
file:/home/fred/data.db?vfs=unix-nolock +** Open file "/home/fred/data.db". Use the special VFS "unix-nolock". +**
file:data.db?mode=readonly +** An error. "readonly" is not a valid option for the "mode" parameter. +**
+** +** ^URI hexadecimal escape sequences (%HH) are supported within the path and +** query components of a URI. A hexadecimal escape sequence consists of a +** percent sign - "%" - followed by exactly two hexadecimal digits +** specifying an octet value. ^Before the path or query components of a +** URI filename are interpreted, they are encoded using UTF-8 and all +** hexadecimal escape sequences replaced by a single byte containing the +** corresponding octet. If this process generates an invalid UTF-8 encoding, +** the results are undefined. +** +** Note to Windows users: The encoding used for the filename argument +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** sqlite3_open() or sqlite3_open_v2(). +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various +** features that require the use of temporary files may fail. +** +** See also: [sqlite3_temp_directory] +*/ +SQLITE_API int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Obtain Values For URI Parameters +** +** These are utility routines, useful to VFS implementations, that check +** to see if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of that query parameter. +** +** If F is the database filename pointer passed into the xOpen() method of +** a VFS implementation when the flags parameter to xOpen() has one or +** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and +** P is the name of the query parameter, then +** sqlite3_uri_parameter(F,P) returns the value of the P +** parameter if it exists or a NULL pointer if P does not appear as a +** query parameter on F. If P is a query parameter of F +** has no explicit value, then sqlite3_uri_parameter(F,P) returns +** a pointer to an empty string. +** +** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean +** parameter and returns true (1) or false (0) according to the value +** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the +** value of query parameter P is one of "yes", "true", or "on" in any +** case or if the value begins with a non-zero number. The +** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of +** query parameter P is one of "no", "false", or "off" in any case or +** if the value begins with a numeric zero. If P is not a query +** parameter on F or if the value of P is does not match any of the +** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). +** +** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a +** 64-bit signed integer and returns that integer, or D if P does not +** exist. If the value of P is something other than an integer, then +** zero is returned. +** +** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and +** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and +** is not a database file pathname pointer that SQLite passed into the xOpen +** VFS method, then the behavior of this routine is undefined and probably +** undesirable. +*/ +SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); +SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); +SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); + + +/* +** CAPI3REF: Error Codes And Messages +** +** ^The sqlite3_errcode() interface returns the numeric [result code] or +** [extended result code] for the most recent failed sqlite3_* API call +** associated with a [database connection]. If a prior API call failed +** but the most recent API call succeeded, the return value from +** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode() +** interface is the same except that it always returns the +** [extended result code] even when extended result codes are +** disabled. +** +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF-8 or UTF-16 respectively. +** ^(Memory to hold the error message string is managed internally. +** The application does not need to worry about freeing the result. +** However, the error string might be overwritten or deallocated by +** subsequent calls to other SQLite interface functions.)^ +** +** ^The sqlite3_errstr() interface returns the English-language text +** that describes the [result code], as UTF-8. +** ^(Memory to hold the error message string is managed internally +** and must not be freed by the application)^. +** +** When the serialized [threading mode] is in use, it might be the +** case that a second error occurs on a separate thread in between +** the time of the first error and the call to these interfaces. +** When that happens, the second error will be reported since these +** interfaces always report the most recent result. To avoid +** this, each thread can obtain exclusive use of the [database connection] D +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** all calls to the interfaces listed here are completed. +** +** If an interface fails with SQLITE_MISUSE, that means the interface +** was invoked incorrectly by the application. In that case, the +** error code and message may or may not be set. +*/ +SQLITE_API int sqlite3_errcode(sqlite3 *db); +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); +SQLITE_API const char *sqlite3_errmsg(sqlite3*); +SQLITE_API const void *sqlite3_errmsg16(sqlite3*); +SQLITE_API const char *sqlite3_errstr(int); + +/* +** CAPI3REF: SQL Statement Object +** KEYWORDS: {prepared statement} {prepared statements} +** +** An instance of this object represents a single SQL statement. +** This object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
    +**
  1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
  2. Bind values to [host parameters] using the sqlite3_bind_*() +** interfaces. +**
  3. Run the SQL by calling [sqlite3_step()] one or more times. +**
  4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
  5. Destroy the object using [sqlite3_finalize()]. +**
+** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Run-time Limits +** +** ^(This interface allows the size of various constructs to be limited +** on a connection by connection basis. The first parameter is the +** [database connection] whose limit is to be set or queried. The +** second parameter is one of the [limit categories] that define a +** class of constructs to be size limited. The third parameter is the +** new limit for that construct.)^ +** +** ^If the new limit is a negative number, the limit is unchanged. +** ^(For each limit category SQLITE_LIMIT_NAME there is a +** [limits | hard upper bound] +** set at compile-time by a C preprocessor macro called +** [limits | SQLITE_MAX_NAME]. +** (The "_LIMIT_" in the name is changed to "_MAX_".))^ +** ^Attempts to increase a limit above its hard upper bound are +** silently truncated to the hard upper bound. +** +** ^Regardless of whether or not the limit was changed, the +** [sqlite3_limit()] interface returns the prior value of the limit. +** ^Hence, to find the current value of a limit without changing it, +** simply invoke this interface with the third parameter set to -1. +** +** Run-time limits are intended for use in applications that manage +** both their own internal database and also databases that are controlled +** by untrusted external sources. An example application might be a +** web browser that has its own databases for storing history and +** separate databases controlled by JavaScript applications downloaded +** off the Internet. The internal databases can be given the +** large, default limits. Databases managed by external sources can +** be given much smaller limits designed to prevent a denial of service +** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** interface to further control untrusted SQL. The size of the database +** created by an untrusted script can be contained using the +** [max_page_count] [PRAGMA]. +** +** New run-time limit categories may be added in future releases. +*/ +SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); + +/* +** CAPI3REF: Run-Time Limit Categories +** KEYWORDS: {limit category} {*limit categories} +** +** These constants define various performance limits +** that can be lowered at run-time using [sqlite3_limit()]. +** The synopsis of the meanings of the various limits is shown below. +** Additional information is available at [limits | Limits in SQLite]. +** +**
+** [[SQLITE_LIMIT_LENGTH]] ^(
SQLITE_LIMIT_LENGTH
+**
The maximum size of any string or BLOB or table row, in bytes.
)^ +** +** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
SQLITE_LIMIT_SQL_LENGTH
+**
The maximum length of an SQL statement, in bytes.
)^ +** +** [[SQLITE_LIMIT_COLUMN]] ^(
SQLITE_LIMIT_COLUMN
+**
The maximum number of columns in a table definition or in the +** result set of a [SELECT] or the maximum number of columns in an index +** or in an ORDER BY or GROUP BY clause.
)^ +** +** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
SQLITE_LIMIT_EXPR_DEPTH
+**
The maximum depth of the parse tree on any expression.
)^ +** +** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
SQLITE_LIMIT_COMPOUND_SELECT
+**
The maximum number of terms in a compound SELECT statement.
)^ +** +** [[SQLITE_LIMIT_VDBE_OP]] ^(
SQLITE_LIMIT_VDBE_OP
+**
The maximum number of instructions in a virtual machine program +** used to implement an SQL statement. This limit is not currently +** enforced, though that might be added in some future release of +** SQLite.
)^ +** +** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
SQLITE_LIMIT_FUNCTION_ARG
+**
The maximum number of arguments on a function.
)^ +** +** [[SQLITE_LIMIT_ATTACHED]] ^(
SQLITE_LIMIT_ATTACHED
+**
The maximum number of [ATTACH | attached databases].)^
+** +** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] +** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
+**
The maximum length of the pattern argument to the [LIKE] or +** [GLOB] operators.
)^ +** +** [[SQLITE_LIMIT_VARIABLE_NUMBER]] +** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
+**
The maximum index number of any [parameter] in an SQL statement.)^ +** +** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
SQLITE_LIMIT_TRIGGER_DEPTH
+**
The maximum depth of recursion for triggers.
)^ +**
+*/ +#define SQLITE_LIMIT_LENGTH 0 +#define SQLITE_LIMIT_SQL_LENGTH 1 +#define SQLITE_LIMIT_COLUMN 2 +#define SQLITE_LIMIT_EXPR_DEPTH 3 +#define SQLITE_LIMIT_COMPOUND_SELECT 4 +#define SQLITE_LIMIT_VDBE_OP 5 +#define SQLITE_LIMIT_FUNCTION_ARG 6 +#define SQLITE_LIMIT_ATTACHED 7 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 +#define SQLITE_LIMIT_VARIABLE_NUMBER 9 +#define SQLITE_LIMIT_TRIGGER_DEPTH 10 + +/* +** CAPI3REF: Compiling An SQL Statement +** KEYWORDS: {SQL statement compiler} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** The first argument, "db", is a [database connection] obtained from a +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or +** [sqlite3_open16()]. The database connection must not have been closed. +** +** The second argument, "zSql", is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. +** +** ^If the nByte argument is less than zero, then zSql is read up to the +** first zero terminator. ^If nByte is non-negative, then it is the maximum +** number of bytes read from zSql. ^When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** the nByte-th byte, whichever comes first. If the caller knows +** that the supplied string is nul-terminated, then there is a small +** performance advantage to be gained by passing an nByte parameter that +** is equal to the number of bytes in the input string including +** the nul-terminator bytes as this saves SQLite from having to +** make a copy of the input string. +** +** ^If pzTail is not NULL then *pzTail is made to point to the first byte +** past the end of the first SQL statement in zSql. These routines only +** compile the first statement in zSql, so *pzTail is left pointing to +** what remains uncompiled. +** +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be +** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** to NULL. ^If the input text contains no SQL (if the input is an empty +** string or a comment) then *ppStmt is set to NULL. +** The calling procedure is responsible for deleting the compiled +** SQL statement using [sqlite3_finalize()] after it has finished with it. +** ppStmt may not be NULL. +** +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** otherwise an [error code] is returned. +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** ^In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [sqlite3_step()] interface to +** behave differently in three ways: +** +**
    +**
  1. +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] +** retries will occur before sqlite3_step() gives up and returns an error. +**
  2. +** +**
  3. +** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** [error codes] or [extended error codes]. ^The legacy behavior was that +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [sqlite3_reset()] +** in order to find the underlying cause of the problem. With the "v2" prepare +** interfaces, the underlying reason for the error is returned immediately. +**
  4. +** +**
  5. +** ^If the specific value bound to [parameter | host parameter] in the +** WHERE clause might influence the choice of query plan for a statement, +** then the statement will be automatically recompiled, as if there had been +** a schema change, on the first [sqlite3_step()] call following any change +** to the [sqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of WHERE-clause [parameter] might influence the +** choice of query plan if the parameter is the left-hand side of a [LIKE] +** or [GLOB] operator or if the parameter is compared to an indexed column +** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. +** the +**
  6. +**
+*/ +SQLITE_API int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPI3REF: Retrieving Statement SQL +** +** ^This interface can be used to retrieve a saved copy of the original +** SQL text used to create a [prepared statement] if that statement was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. +*/ +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If An SQL Statement Writes The Database +** +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** and only if the [prepared statement] X makes no direct changes to +** the content of the database file. +** +** Note that [application-defined SQL functions] or +** [virtual tables] might change the database indirectly as a side effect. +** ^(For example, if an application defines a function "eval()" that +** calls [sqlite3_exec()], then the following SQL statement would +** change the database file through side-effects: +** +**
+**    SELECT eval('DELETE FROM t1') FROM t2;
+** 
+** +** But because the [SELECT] statement does not change the database file +** directly, sqlite3_stmt_readonly() would still return true.)^ +** +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** since the statements themselves do not actually modify the database but +** rather they control the timing of when other statements modify the +** database. ^The [ATTACH] and [DETACH] statements also cause +** sqlite3_stmt_readonly() to return true since, while those statements +** change the configuration of a database connection, they do not make +** changes to the content of the database files on disk. +*/ +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If A Prepared Statement Has Been Reset +** +** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the +** [prepared statement] S has been stepped at least once using +** [sqlite3_step(S)] but has not run to completion and/or has not +** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) +** interface returns false if S is a NULL pointer. If S is not a +** NULL pointer and is not a pointer to a valid [prepared statement] +** object, then the behavior is undefined and probably undesirable. +** +** This interface can be used in combination [sqlite3_next_stmt()] +** to locate all prepared statements associated with a database +** connection that are in need of being reset. This can be used, +** for example, in diagnostic routines to search for prepared +** statements that are holding a transaction open. +*/ +SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); + +/* +** CAPI3REF: Dynamically Typed Value Object +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** +** SQLite uses the sqlite3_value object to represent all values +** that can be stored in a database table. SQLite uses dynamic typing +** for the values it stores. ^Values stored in sqlite3_value objects +** can be integers, floating point values, strings, BLOBs, or NULL. +** +** An sqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected sqlite3_value. Other interfaces +** will accept either a protected or an unprotected sqlite3_value. +** Every interface that accepts sqlite3_value arguments specifies +** whether or not it requires a protected sqlite3_value. +** +** The terms "protected" and "unprotected" refer to whether or not +** a mutex is held. An internal mutex is held for a protected +** sqlite3_value object but no mutex is held for an unprotected +** sqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** or if SQLite is run in one of reduced mutex modes +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] +** then there is no distinction between protected and unprotected +** sqlite3_value objects and they can be used interchangeably. However, +** for maximum code portability it is recommended that applications +** still make the distinction between protected and unprotected +** sqlite3_value objects even when not strictly required. +** +** ^The sqlite3_value objects that are passed as parameters into the +** implementation of [application-defined SQL functions] are protected. +** ^The sqlite3_value object returned by +** [sqlite3_column_value()] is unprotected. +** Unprotected sqlite3_value objects may only be used with +** [sqlite3_result_value()] and [sqlite3_bind_value()]. +** The [sqlite3_value_blob | sqlite3_value_type()] family of +** interfaces require protected sqlite3_value objects. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. ^A pointer to an sqlite3_context object +** is always first parameter to [application-defined SQL functions]. +** The application-defined SQL function implementation will pass this +** pointer through into calls to [sqlite3_result_int | sqlite3_result()], +** [sqlite3_aggregate_context()], [sqlite3_user_data()], +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], +** and/or [sqlite3_set_auxdata()]. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements +** KEYWORDS: {host parameter} {host parameters} {host parameter name} +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** literals may be replaced by a [parameter] that matches one of following +** templates: +** +**
    +**
  • ? +**
  • ?NNN +**
  • :VVV +**
  • @VVV +**
  • $VVV +**
+** +** In the templates above, NNN represents an integer literal, +** and VVV represents an alphanumeric identifier.)^ ^The values of these +** parameters (also called "host parameter names" or "SQL parameters") +** can be set using the sqlite3_bind_*() routines defined here. +** +** ^The first argument to the sqlite3_bind_*() routines is always +** a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. +** +** ^The second argument is the index of the SQL parameter to be set. +** ^The leftmost SQL parameter has an index of 1. ^When the same named +** SQL parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** ^The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_index()] API if desired. ^The index +** for "?NNN" parameters is the value of NNN. +** ^The NNN value must be between 1 and the [sqlite3_limit()] +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). +** +** ^The third argument is the value to bind to the parameter. +** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter +** is ignored and the end result is the same as sqlite3_bind_null(). +** +** ^(In those routines that have a fourth argument, its value is the +** number of bytes in the parameter. To be clear: the value is the +** number of bytes in the value, not the number of characters.)^ +** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** is negative, then the length of the string is +** the number of bytes up to the first zero terminator. +** If the fourth parameter to sqlite3_bind_blob() is negative, then +** the behavior is undefined. +** If a non-negative fourth parameter is provided to sqlite3_bind_text() +** or sqlite3_bind_text16() then that parameter must be the byte offset +** where the NUL terminator would occur assuming the string were NUL +** terminated. If any NUL characters occur at byte offsets less than +** the value of the fourth parameter then the resulting string value will +** contain embedded NULs. The result of expressions involving strings +** with embedded NULs is undefined. +** +** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** string after SQLite has finished with it. ^The destructor is called +** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), +** sqlite3_bind_text(), or sqlite3_bind_text16() fails. +** ^If the fifth argument is +** the special value [SQLITE_STATIC], then SQLite assumes that the +** information is in static, unmanaged space and does not need to be freed. +** ^If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. +** +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeroes. ^A zeroblob uses a fixed amount of memory +** (just an integer to hold its size) while it is being processed. +** Zeroblobs are intended to serve as placeholders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | incremental BLOB I/O] routines. +** ^A negative value for the zeroblob results in a zero-length BLOB. +** +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** for the [prepared statement] or with a prepared statement for which +** [sqlite3_step()] has been called more recently than [sqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** routine is passed a [prepared statement] that has been finalized, the +** result is undefined and probably harmful. +** +** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Unbound parameters are interpreted as NULL. +** +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** [error code] if anything goes wrong. +** ^[SQLITE_RANGE] is returned if the parameter +** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. +** +** See also: [sqlite3_bind_parameter_count()], +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); +SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); +SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of SQL Parameters +** +** ^This routine can be used to find the number of [SQL parameters] +** in a [prepared statement]. SQL parameters are tokens of the +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as +** placeholders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** ^(This routine actually returns the index of the largest (rightmost) +** parameter. For all forms except ?NNN, this will correspond to the +** number of unique parameters. If parameters of the ?NNN form are used, +** there may be gaps in the list.)^ +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_name()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter +** +** ^The sqlite3_bind_parameter_name(P,N) interface returns +** the name of the N-th [SQL parameter] in the [prepared statement] P. +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" +** respectively. +** In other words, the initial ":" or "$" or "@" or "?" +** is included as part of the name.)^ +** ^Parameters of the form "?" without a following integer have no name +** and are referred to as "nameless" or "anonymous parameters". +** +** ^The first host parameter has an index of 1, not 0. +** +** ^If the value N is out of range or if the N-th parameter is +** nameless, then NULL is returned. ^The returned string is +** always in UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name +** +** ^Return the index of an SQL parameter given its name. ^The +** index value returned is suitable for use as the second +** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** is returned if no matching parameter is found. ^The parameter +** name must be given in UTF-8 even if the original statement +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement +** +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset +** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Use this routine to reset all host parameters to NULL. +*/ +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set +** +** ^Return the number of columns in the result set returned by the +** [prepared statement]. ^This routine returns 0 if pStmt is an SQL +** statement that does not return data (for example an [UPDATE]). +** +** See also: [sqlite3_data_count()] +*/ +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set +** +** ^These routines return the name assigned to a particular column +** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF-8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF-16 string. ^The first parameter is the [prepared statement] +** that implements the [SELECT] statement. ^The second parameter is the +** column number. ^The leftmost column is number 0. +** +** ^The returned string pointer is valid until either the [prepared statement] +** is destroyed by [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the next call to +** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** +** ^If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +** +** ^The name of a result column is the value of the "AS" clause for +** that column, if there is an AS clause. If there is no AS clause +** then the name of the column is unspecified and may change from +** one release of SQLite to the next. +*/ +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result +** +** ^These routines provide a means to determine the database, table, and +** table column that is the origin of a particular result column in +** [SELECT] statement. +** ^The name of the database or table or column can be returned as +** either a UTF-8 or UTF-16 string. ^The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. +** ^The returned string is valid until the [prepared statement] is destroyed +** using [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the same information is requested +** again in a different encoding. +** +** ^The names returned are the original un-aliased names of the +** database, table, and column. +** +** ^The first argument to these interfaces is a [prepared statement]. +** ^These functions return information about the Nth result column returned by +** the statement, where N is the second function argument. +** ^The left-most column is column 0 for these routines. +** +** ^If the Nth column returned by the statement is an expression or +** subquery and is not a column value, then all of these functions return +** NULL. ^These routine might also return NULL if a memory allocation error +** occurs. ^Otherwise, they return the name of the attached database, table, +** or column that query result column was extracted from. +** +** ^As with all other SQLite APIs, those whose names end with "16" return +** UTF-16 encoded strings and the other functions return UTF-8. +** +** ^These APIs are only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. +** +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +** +** If two or more threads call one or more +** [sqlite3_column_database_name | column metadata interfaces] +** for the same [prepared statement] and result column +** at the same time then the results are undefined. +*/ +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result +** +** ^(The first parameter is a [prepared statement]. +** If this statement is a [SELECT] statement and the Nth column of the +** returned result set of that [SELECT] is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned.)^ ^If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** ^The returned string is always UTF-8 encoded. +** +** ^(For example, given the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** and the following statement to be compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** this routine would return the string "VARIANT" for the second result +** column (i==1), and a NULL pointer for the first result column (i==0).)^ +** +** ^SQLite uses dynamic run-time typing. ^So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. ^Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement +** +** After a [prepared statement] has been prepared using either +** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** must be called one or more times to evaluate the statement. +** +** The details of the behavior of the sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** ^In the legacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** ^With the "v2" interface, any of the other [result codes] or +** [extended result codes] might be returned as well. +** +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. ^If the statement is a [COMMIT] +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a [COMMIT] and occurs within an +** explicit transaction then you should rollback the transaction before +** continuing. +** +** ^[SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] +** is returned each time a new row of data is ready for processing by the +** caller. The values may be accessed using the [column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** ^With the legacy interface, a more specific error code (for example, +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [prepared statement]. ^In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** For all versions of SQLite up to and including 3.6.23.1, a call to +** [sqlite3_reset()] was required after sqlite3_step() returned anything +** other than [SQLITE_ROW] before any subsequent invocation of +** sqlite3_step(). Failure to reset the prepared statement using +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began +** calling [sqlite3_reset()] automatically in this circumstance rather +** than returning [SQLITE_MISUSE]. This is not considered a compatibility +** break because any application that ever receives an SQLITE_MISUSE error +** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option +** can be used to restore the legacy behavior. +** +** Goofy Interface Alert: In the legacy interface, the sqlite3_step() +** API always returns a generic error code, [SQLITE_ERROR], following any +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** specific [error codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** then the more specific [error codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +SQLITE_API int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set +** +** ^The sqlite3_data_count(P) interface returns the number of columns in the +** current row of the result set of [prepared statement] P. +** ^If prepared statement P does not have results ready to return +** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of +** interfaces) then sqlite3_data_count(P) returns 0. +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** ^The sqlite3_data_count(P) routine returns 0 if the previous call to +** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) +** will return non-zero if previous call to [sqlite3_step](P) returned +** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] +** where it always returns zero since each step of that multi-step +** pragma returns 0 columns of data. +** +** See also: [sqlite3_column_count()] +*/ +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes +** KEYWORDS: SQLITE_TEXT +** +** ^(Every value in SQLite has one of five fundamental datatypes: +** +**
    +**
  • 64-bit signed integer +**
  • 64-bit IEEE floating point number +**
  • string +**
  • BLOB +**
  • NULL +**
)^ +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Result Values From A Query +** KEYWORDS: {column access functions} +** +** These routines form the "result set" interface. +** +** ^These routines return information about a single column of the current +** result row of a query. ^In every case the first argument is a pointer +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] +** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** and the second argument is the index of the column for which information +** should be returned. ^The leftmost column of the result set has the index 0. +** ^The number of columns in the result can be determined using +** [sqlite3_column_count()]. +** +** If the SQL statement does not currently point to a valid row, or if the +** column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** ^The sqlite3_column_type() routine returns the +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. ^The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** the string to UTF-16 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes16() uses +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** +** ^The values returned by [sqlite3_column_bytes()] and +** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** of the string. ^For clarity: the values returned by +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** bytes in the string, not the number of characters. +** +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even empty strings, are always zero-terminated. ^The return +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** ^The object returned by [sqlite3_column_value()] is an +** [unprotected sqlite3_value] object. An unprotected sqlite3_value object +** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. +** If the [unprotected sqlite3_value] object returned by +** [sqlite3_column_value()] is used in any other way, including calls +** to routines like [sqlite3_value_int()], [sqlite3_value_text()], +** or [sqlite3_value_bytes()], then the behavior is undefined. +** +** These routines attempt to convert the value where appropriate. ^For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to perform the +** conversion automatically. ^(The following table details the conversions +** that are applied: +** +**
+** +**
Internal
Type
Requested
Type
Conversion +** +**
NULL INTEGER Result is 0 +**
NULL FLOAT Result is 0.0 +**
NULL TEXT Result is NULL pointer +**
NULL BLOB Result is NULL pointer +**
INTEGER FLOAT Convert from integer to float +**
INTEGER TEXT ASCII rendering of the integer +**
INTEGER BLOB Same as INTEGER->TEXT +**
FLOAT INTEGER Convert from float to integer +**
FLOAT TEXT ASCII rendering of the float +**
FLOAT BLOB Same as FLOAT->TEXT +**
TEXT INTEGER Use atoi() +**
TEXT FLOAT Use atof() +**
TEXT BLOB No change +**
BLOB INTEGER Convert to TEXT then use atoi() +**
BLOB FLOAT Convert to TEXT then use atof() +**
BLOB TEXT Add a zero terminator if needed +**
+**
)^ +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** own equivalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
    +**
  • The initial content is a BLOB and sqlite3_column_text() or +** sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.
  • +**
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.
  • +**
  • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.
  • +**
+** +** ^Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer references will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometimes they +** are not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
    +**
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • +**
+** +** In other words, you should call sqlite3_column_text(), +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result +** into the desired format, then invoke sqlite3_column_bytes() or +** sqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to sqlite3_column_text() or sqlite3_column_blob() with calls to +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() +** with calls to sqlite3_column_bytes(). +** +** ^The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** ^(If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM].)^ +*/ +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object +** +** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^If the most recent evaluation of the statement encountered no errors +** or if the statement is never been evaluated, then sqlite3_finalize() returns +** SQLITE_OK. ^If the most recent evaluation of statement S failed, then +** sqlite3_finalize(S) returns the appropriate [error code] or +** [extended error code]. +** +** ^The sqlite3_finalize(S) routine can be called at any point during +** the life cycle of [prepared statement] S: +** before statement S is ever evaluated, after +** one or more calls to [sqlite3_reset()], or after any call +** to [sqlite3_step()] regardless of whether or not the statement has +** completed execution. +** +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** +** The application must finalize every [prepared statement] in order to avoid +** resource leaks. It is a grievous error for the application to try to use +** a prepared statement after it has been finalized. Any use of a prepared +** statement after it has been finalized can result in undefined and +** undesirable behavior such as segfaults and heap corruption. +*/ +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object +** +** The sqlite3_reset() function is called to reset a [prepared statement] +** object back to its initial state, ready to be re-executed. +** ^Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +** +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** back to the beginning of its program. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], +** or if [sqlite3_step(S)] has never before been called on S, +** then [sqlite3_reset(S)] returns [SQLITE_OK]. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S indicated an error, then +** [sqlite3_reset(S)] returns an appropriate [error code]. +** +** ^The [sqlite3_reset(S)] interface does not change the values +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +*/ +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions +** KEYWORDS: {function creation routines} +** KEYWORDS: {application-defined SQL function} +** KEYWORDS: {application-defined SQL functions} +** +** ^These functions (collectively known as "function creation routines") +** are used to add SQL functions or aggregates or to redefine the behavior +** of existing SQL functions or aggregates. The only differences between +** these routines are the text encoding expected for +** the second parameter (the name of the function being created) +** and the presence or absence of a destructor callback for +** the application data pointer. +** +** ^The first parameter is the [database connection] to which the SQL +** function is to be added. ^If an application uses more than one database +** connection then application-defined SQL functions must be added +** to each database connection separately. +** +** ^The second parameter is the name of the SQL function to be created or +** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 +** representation, exclusive of the zero-terminator. ^Note that the name +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. +** ^Any attempt to create a function with a longer name +** will result in [SQLITE_MISUSE] being returned. +** +** ^The third parameter (nArg) +** is the number of arguments that the SQL function or +** aggregate takes. ^If this parameter is -1, then the SQL function or +** aggregate may take any number of arguments between 0 and the limit +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** parameter is less than -1 or greater than 127 then the behavior is +** undefined. +** +** ^The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Every SQL function implementation must be able to work +** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. ^An application may +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** ^When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what text +** encoding is used, then the fourth argument should be [SQLITE_ANY]. +** +** ^(The fifth parameter is an arbitrary pointer. The implementation of the +** function can gain access to this pointer using [sqlite3_user_data()].)^ +** +** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL function or +** aggregate. ^A scalar SQL function requires an implementation of the xFunc +** callback only; NULL pointers must be passed as the xStep and xFinal +** parameters. ^An aggregate SQL function requires an implementation of xStep +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing +** SQL function or aggregate, pass NULL pointers for all three function +** callbacks. +** +** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, +** then it is destructor for the application data pointer. +** The destructor is invoked when the function is deleted, either by being +** overloaded or when the database connection closes.)^ +** ^The destructor is also invoked if the call to +** sqlite3_create_function_v2() fails. +** ^When the destructor callback of the tenth parameter is invoked, it +** is passed a single argument which is a copy of the application data +** pointer which was the fifth parameter to sqlite3_create_function_v2(). +** +** ^It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing preferred text encodings. ^SQLite will use +** the implementation that most closely matches the way in which the +** SQL function is used. ^A function implementation with a non-negative +** nArg parameter is a better match than a function implementation with +** a negative nArg. ^A function where the preferred text encoding +** matches the database encoding is a better +** match than a function where the encoding is different. +** ^A function where the encoding difference is between UTF16le and UTF16be +** is a closer match than a function where the encoding difference is +** between UTF8 and UTF16. +** +** ^Built-in functions may be overloaded by new application-defined functions. +** +** ^An application-defined function is permitted to call other +** SQLite interfaces. However, such calls must not +** close the database connection nor finalize or reset the prepared +** statement in which the function is running. +*/ +SQLITE_API int sqlite3_create_function( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*) +); + +/* +** CAPI3REF: Text Encodings +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Deprecated Functions +** DEPRECATED +** +** These functions are [deprecated]. In order to maintain +** backwards compatibility with older code, these functions continue +** to be supported. However, new applications should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you what they do. +*/ +#ifndef SQLITE_OMIT_DEPRECATED +SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); +SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); +SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), + void*,sqlite3_int64); +#endif + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 3rd parameter to these callbacks is an array of pointers to +** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work only with [protected sqlite3_value] objects. +** Any attempt to use these routines on an [unprotected sqlite3_value] +** object results in undefined behavior. +** +** ^These routines work just like the corresponding [column access functions] +** except that these routines take a single [protected sqlite3_value] object +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** +** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** in the native byte-order of the host machine. ^The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF-16 strings as big-endian and little-endian respectively. +** +** ^(The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words, if the value is a string that looks like a number) +** then the conversion is performed. Otherwise no conversion occurs. +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ +** +** Please pay particular attention to the fact that the pointer returned +** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the [sqlite3_value*] parameters. +*/ +SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); +SQLITE_API double sqlite3_value_double(sqlite3_value*); +SQLITE_API int sqlite3_value_int(sqlite3_value*); +SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); +SQLITE_API int sqlite3_value_type(sqlite3_value*); +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context +** +** Implementations of aggregate SQL functions use this +** routine to allocate memory for storing their state. +** +** ^The first time the sqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite +** allocates N of memory, zeroes out that memory, and returns a pointer +** to the new memory. ^On second and subsequent calls to +** sqlite3_aggregate_context() for the same aggregate function instance, +** the same buffer is returned. Sqlite3_aggregate_context() is normally +** called once for each invocation of the xStep callback and then one +** last time when the xFinal callback is invoked. ^(When no rows match +** an aggregate query, the xStep() callback of the aggregate function +** implementation is never called and xFinal() is called exactly once. +** In those cases, sqlite3_aggregate_context() might be called for the +** first time from within xFinal().)^ +** +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer +** when first called if N is less than or equal to zero or if a memory +** allocate error occurs. +** +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** determined by the N parameter on first successful call. Changing the +** value of N in subsequent call to sqlite3_aggregate_context() within +** the same aggregate function instance will not resize the memory +** allocation.)^ Within the xFinal callback, it is customary to set +** N=0 in calls to sqlite3_aggregate_context(C,N) so that no +** pointless memory allocations occur. +** +** ^SQLite automatically frees the memory allocated by +** sqlite3_aggregate_context() when the aggregate query concludes. +** +** The first parameter must be a copy of the +** [sqlite3_context | SQL function context] that is the first parameter +** to the xStep or xFinal callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions +** +** ^The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +** +** This routine must be called from the same thread in which +** the application-defined function is running. +*/ +SQLITE_API void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Database Connection For Functions +** +** ^The sqlite3_context_db_handle() interface returns a copy of +** the pointer to the [database connection] (the 1st parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +*/ +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data +** +** These functions may be used by (non-aggregate) SQL functions to +** associate metadata with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated metadata may be preserved. An example +** of where this might be useful is in a regular-expression matching +** function. The compiled version of the regular expression can be stored as +** metadata associated with the pattern string. +** Then as long as the pattern string remains the same, +** the compiled regular expression can be reused on multiple +** invocations of the same function. +** +** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. ^If there is no metadata +** associated with the function argument, this sqlite3_get_auxdata() interface +** returns a NULL pointer. +** +** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th +** argument of the application-defined function. ^Subsequent +** calls to sqlite3_get_auxdata(C,N) return P from the most recent +** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or +** NULL if the metadata has been discarded. +** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, +** SQLite will invoke the destructor function X with parameter P exactly +** once, when the metadata is discarded. +** SQLite is free to discard the metadata at any time, including:
    +**
  • when the corresponding function parameter changes, or +**
  • when [sqlite3_reset()] or [sqlite3_finalize()] is called for the +** SQL statement, or +**
  • when sqlite3_set_auxdata() is invoked again on the same parameter, or +**
  • during the original sqlite3_set_auxdata() call when a memory +** allocation error occurs.
)^ +** +** Note the last bullet in particular. The destructor X in +** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the +** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() +** should be called near the end of the function implementation and the +** function implementation should not make any use of P after +** sqlite3_set_auxdata() has been called. +** +** ^(In practice, metadata is preserved between function calls for +** function parameters that are compile-time constants, including literal +** values and [parameters] and expressions composed from the same.)^ +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); +SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior +** +** These are special values for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. ^The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the [parameter binding] family of +** functions used to bind values to host parameters in prepared statements. +** Refer to the [SQL parameter] documentation for additional information. +** +** ^The sqlite3_result_blob() interface sets the result from +** an application-defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** +** ^The sqlite3_result_zeroblob() interfaces set the result of +** the application-defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** ^The sqlite3_result_double() interface sets the result from +** an application-defined function to be a floating point value specified +** by its 2nd argument. +** +** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** ^SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. ^SQLite interprets the error +** message string from sqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from sqlite3_result_error16() as UTF-16 in native +** byte order. ^If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** ^If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** ^The sqlite3_result_error() and sqlite3_result_error16() +** routines make a private copy of the error message text before +** they return. Hence, the calling function can deallocate or +** modify the text after they return without harm. +** ^The sqlite3_result_error_code() function changes the error code +** returned by SQLite as a result of an error in a function. ^By default, +** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() +** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** +** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an +** error indicating that a string or BLOB is too long to represent. +** +** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an +** error indicating that a memory allocation failed. +** +** ^The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** ^The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** ^The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** ^The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** ^SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. If the 3rd parameter is non-negative, then it +** must be the byte offset into the string where the NUL terminator would +** appear if the string where NUL terminated. If any NUL characters occur +** in the string at a byte offset that is less than the value of the 3rd +** parameter, then the resulting string will contain embedded NULs and the +** result of expressions operating on strings with embedded NULs is undefined. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or BLOB result when it has +** finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces or to +** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** assumes that the text or BLOB result is in constant space and does not +** copy the content of the parameter nor call a destructor on the content +** when it has finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** ^The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the +** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that the [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** ^A [protected sqlite3_value] object may always be used where an +** [unprotected sqlite3_value] object is required, so either +** kind of [sqlite3_value] object can be used with this interface. +** +** If these routines are called from within the different thread +** than the one containing the application-defined function that received +** the [sqlite3_context] pointer, the results are undefined. +*/ +SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_double(sqlite3_context*, double); +SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); +SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); +SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +SQLITE_API void sqlite3_result_null(sqlite3_context*); +SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences +** +** ^These functions add, remove, or modify a [collation] associated +** with the [database connection] specified as the first argument. +** +** ^The name of the collation is a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for sqlite3_create_collation16(). +** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** considered to be the same name. +** +** ^(The third argument (eTextRep) must be one of the constants: +**
    +**
  • [SQLITE_UTF8], +**
  • [SQLITE_UTF16LE], +**
  • [SQLITE_UTF16BE], +**
  • [SQLITE_UTF16], or +**
  • [SQLITE_UTF16_ALIGNED]. +**
)^ +** ^The eTextRep argument determines the encoding of strings passed +** to the collating function callback, xCallback. +** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep +** force strings to be UTF16 with native byte order. +** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin +** on an even byte address. +** +** ^The fourth argument, pArg, is an application data pointer that is passed +** through as the first argument to the collating function callback. +** +** ^The fifth argument, xCallback, is a pointer to the collating function. +** ^Multiple collating functions can be registered using the same name but +** with different eTextRep parameters and SQLite will use whichever +** function requires the least amount of data transformation. +** ^If the xCallback argument is NULL then the collating function is +** deleted. ^When all collating functions having the same name are deleted, +** that collation is no longer usable. +** +** ^The collating function callback is invoked with a copy of the pArg +** application data pointer and with two strings in the encoding specified +** by the eTextRep argument. The collating function must return an +** integer that is negative, zero, or positive +** if the first string is less than, equal to, or greater than the second, +** respectively. A collating function must always return the same answer +** given the same inputs. If two or more collating functions are registered +** to the same collation name (using different eTextRep values) then all +** must give an equivalent answer when invoked with equivalent strings. +** The collating function must obey the following properties for all +** strings A, B, and C: +** +**
    +**
  1. If A==B then B==A. +**
  2. If A==B and B==C then A==C. +**
  3. If A<B THEN B>A. +**
  4. If A<B and B<C then A<C. +**
+** +** If a collating function fails any of the above constraints and that +** collating function is registered and used, then the behavior of SQLite +** is undefined. +** +** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** with the addition that the xDestroy callback is invoked on pArg when +** the collating function is deleted. +** ^Collating functions are deleted when they are overridden by later +** calls to the collation creation functions or when the +** [database connection] is closed using [sqlite3_close()]. +** +** ^The xDestroy callback is not called if the +** sqlite3_create_collation_v2() function fails. Applications that invoke +** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** check the return code and dispose of the application data pointer +** themselves rather than expecting SQLite to deal with it for them. +** This is different from every other SQLite interface. The inconsistency +** is unfortunate but cannot be changed without breaking backwards +** compatibility. +** +** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +*/ +SQLITE_API int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); +SQLITE_API int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +SQLITE_API int sqlite3_create_collation16( + sqlite3*, + const void *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks +** +** ^To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** [database connection] to be invoked whenever an undefined collation +** sequence is required. +** +** ^If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** the names are passed as UTF-16 in machine native byte order. +** ^A call to either function replaces the existing collation-needed callback. +** +** ^(When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). The second argument is the database +** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE], indicating the most desirable form of the collation +** sequence function required. The fourth parameter is the name of the +** required collation sequence.)^ +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +SQLITE_API int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +SQLITE_API int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +#ifdef SQLITE_HAS_CODEC +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); +SQLITE_API int sqlite3_key_v2( + sqlite3 *db, /* Database to be rekeyed */ + const char *zDbName, /* Name of the database */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); +SQLITE_API int sqlite3_rekey_v2( + sqlite3 *db, /* Database to be rekeyed */ + const char *zDbName, /* Name of the database */ + const void *pKey, int nKey /* The new key */ +); + +/* +** Specify the activation key for a SEE database. Unless +** activated, none of the SEE routines will work. +*/ +SQLITE_API void sqlite3_activate_see( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +#ifdef SQLITE_ENABLE_CEROD +/* +** Specify the activation key for a CEROD database. Unless +** activated, none of the CEROD routines will work. +*/ +SQLITE_API void sqlite3_activate_cerod( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +/* +** CAPI3REF: Suspend Execution For A Short Time +** +** The sqlite3_sleep() function causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** ^SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. If the xSleep() method +** of the default VFS is not implemented correctly, or not implemented at +** all, then the behavior of sqlite3_sleep() may deviate from the description +** in the previous paragraphs. +*/ +SQLITE_API int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all temporary files +** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** will be placed in that directory.)^ ^If this variable +** is a NULL pointer, then SQLite performs a search for an appropriate +** temporary file directory. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [temp_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [temp_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [temp_store_directory pragma] should be avoided. +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various +** features that require the use of temporary files may fail. Here is an +** example of how to do this using C++ with the Windows Runtime: +** +**
+** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
+**       TemporaryFolder->Path->Data();
+** char zPathBuf[MAX_PATH + 1];
+** memset(zPathBuf, 0, sizeof(zPathBuf));
+** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
+**       NULL, NULL);
+** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
+** 
+*/ +SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Name Of The Folder Holding Database Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all database files +** specified with a relative pathname and created or accessed by +** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed +** to be relative to that directory.)^ ^If this variable is a NULL +** pointer, then SQLite assumes that all database files specified +** with a relative pathname are relative to the current directory +** for the process. Only the windows VFS makes use of this global +** variable; it is ignored by the unix VFS. +** +** Changing the value of this variable while a database connection is +** open can result in a corrupt database. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [data_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [data_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [data_store_directory pragma] should be avoided. +*/ +SQLITE_API SQLITE_EXTERN char *sqlite3_data_directory; + +/* +** CAPI3REF: Test For Auto-Commit Mode +** KEYWORDS: {autocommit mode} +** +** ^The sqlite3_get_autocommit() interface returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. ^Autocommit mode is on by default. +** ^Autocommit mode is disabled by a [BEGIN] statement. +** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** +** If certain kinds of errors occur on a statement within a multi-statement +** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. The only way to +** find out whether SQLite automatically rolled back the transaction after +** an error is to use this function. +** +** If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. +*/ +SQLITE_API int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement +** +** ^The sqlite3_db_handle interface returns the [database connection] handle +** to which a [prepared statement] belongs. ^The [database connection] +** returned by sqlite3_db_handle is the same [database connection] +** that was the first argument +** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** create the statement in the first place. +*/ +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + +/* +** CAPI3REF: Return The Filename For A Database Connection +** +** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename +** associated with database N of connection D. ^The main database file +** has the name "main". If there is no attached database N on the database +** connection D, or if database N is a temporary or in-memory database, then +** a NULL pointer is returned. +** +** ^The filename returned by this function is the output of the +** xFullPathname method of the [VFS]. ^In other words, the filename +** will be an absolute pathname, even if the filename used +** to open the database originally was a URI or relative pathname. +*/ +SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Determine if a database is read-only +** +** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N +** of connection D is read-only, 0 if it is read/write, or -1 if N is not +** the name of a database on connection D. +*/ +SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Find the next prepared statement +** +** ^This interface returns a pointer to the next [prepared statement] after +** pStmt associated with the [database connection] pDb. ^If pStmt is NULL +** then this interface returns a pointer to the first prepared statement +** associated with the database connection pDb. ^If no prepared statement +** satisfies the conditions of this routine, it returns NULL. +** +** The [database connection] pointer D in a call to +** [sqlite3_next_stmt(D,S)] must refer to an open database +** connection and in particular must not be a NULL pointer. +*/ +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks +** +** ^The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is [COMMIT | committed]. +** ^Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** ^The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. +** ^Any callback set by a previous call to sqlite3_rollback_hook() +** for the same database connection is overridden. +** ^The pArg argument is passed through to the callback. +** ^If the callback on a commit hook function returns non-zero, +** then the commit is converted into a rollback. +** +** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** return the P argument from the previous call of the same function +** on the same [database connection] D, or NULL for +** the first call for each function on D. +** +** The commit and rollback hook callbacks are not reentrant. +** The callback implementation must not do anything that will modify +** the database connection that invoked the callback. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the commit +** or rollback hook in the first place. +** Note that running any other SQL statements, including SELECT statements, +** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify +** the database connections for the meaning of "modify" in this paragraph. +** +** ^Registering a NULL function disables the callback. +** +** ^When the commit hook callback routine returns zero, the [COMMIT] +** operation is allowed to continue normally. ^If the commit hook +** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. +** ^The rollback hook is invoked on a rollback that results from a commit +** hook returning non-zero, just as it would be with any other rollback. +** +** ^For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** ^The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** +** See also the [sqlite3_update_hook()] interface. +*/ +SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks +** +** ^The sqlite3_update_hook() interface registers a callback function +** with the [database connection] identified by the first argument +** to be invoked whenever a row is updated, inserted or deleted. +** ^Any callback set by a previous call to this function +** for the same database connection is overridden. +** +** ^The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** ^The first argument to the callback is a copy of the third argument +** to sqlite3_update_hook(). +** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], +** or [SQLITE_UPDATE], depending on the operation that caused the callback +** to be invoked. +** ^The third and fourth arguments to the callback contain pointers to the +** database and table name containing the affected row. +** ^The final callback parameter is the [rowid] of the row. +** ^In the case of an update, this is the [rowid] after the update takes place. +** +** ^(The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence).)^ +** +** ^In the current implementation, the update hook +** is not invoked when duplication rows are deleted because of an +** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook +** invoked when rows are deleted using the [truncate optimization]. +** The exceptions defined in this paragraph might change in a future +** release of SQLite. +** +** The update hook implementation must not do anything that will modify +** the database connection that invoked the update hook. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the update hook. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^The sqlite3_update_hook(D,C,P) function +** returns the P argument from the previous call +** on the same [database connection] D, or NULL for +** the first call on D. +** +** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] +** interfaces. +*/ +SQLITE_API void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache +** +** ^(This routine enables or disables the sharing of the database cache +** and schema data structures between [database connection | connections] +** to the same database. Sharing is enabled if the argument is true +** and disabled if the argument is false.)^ +** +** ^Cache sharing is enabled and disabled for an entire process. +** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, +** sharing was enabled or disabled for each thread separately. +** +** ^(The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** Existing database connections continue use the sharing mode +** that was in effect at the time they were opened.)^ +** +** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled +** successfully. An [error code] is returned otherwise.)^ +** +** ^Shared cache is disabled by default. But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +** +** This interface is threadsafe on processors where writing a +** 32-bit integer is atomic. +** +** See Also: [SQLite Shared-Cache Mode] +*/ +SQLITE_API int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory +** +** ^The sqlite3_release_memory() interface attempts to free N bytes +** of heap memory by deallocating non-essential memory allocations +** held by the database library. Memory used to cache database +** pages to improve performance is an example of non-essential memory. +** ^sqlite3_release_memory() returns the number of bytes actually freed, +** which might be more or less than the amount requested. +** ^The sqlite3_release_memory() routine is a no-op returning zero +** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** See also: [sqlite3_db_release_memory()] +*/ +SQLITE_API int sqlite3_release_memory(int); + +/* +** CAPI3REF: Free Memory Used By A Database Connection +** +** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap +** memory as possible from database connection D. Unlike the +** [sqlite3_release_memory()] interface, this interface is effect even +** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is +** omitted. +** +** See also: [sqlite3_release_memory()] +*/ +SQLITE_API int sqlite3_db_release_memory(sqlite3*); + +/* +** CAPI3REF: Impose A Limit On Heap Size +** +** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** soft limit on the amount of heap memory that may be allocated by SQLite. +** ^SQLite strives to keep heap memory utilization below the soft heap +** limit by reducing the number of pages held in the page cache +** as heap memory usages approaches the limit. +** ^The soft heap limit is "soft" because even though SQLite strives to stay +** below the limit, it will exceed the limit rather than generate +** an [SQLITE_NOMEM] error. In other words, the soft heap limit +** is advisory only. +** +** ^The return value from sqlite3_soft_heap_limit64() is the size of +** the soft heap limit prior to the call, or negative in the case of an +** error. ^If the argument N is negative +** then no change is made to the soft heap limit. Hence, the current +** size of the soft heap limit can be determined by invoking +** sqlite3_soft_heap_limit64() with a negative argument. +** +** ^If the argument N is zero then the soft heap limit is disabled. +** +** ^(The soft heap limit is not enforced in the current implementation +** if one or more of following conditions are true: +** +**
    +**
  • The soft heap limit is set to zero. +**
  • Memory accounting is disabled using a combination of the +** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. +**
  • An alternative page cache implementation is specified using +** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). +**
  • The page cache allocates from its own memory pool supplied +** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** from the heap. +**
)^ +** +** Beginning with SQLite version 3.7.3, the soft heap limit is enforced +** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] +** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], +** the soft heap limit is enforced on every memory allocation. Without +** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced +** when memory is allocated by the page cache. Testing suggests that because +** the page cache is the predominate memory user in SQLite, most +** applications will achieve adequate soft heap limit enforcement without +** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** The circumstances under which SQLite will enforce the soft heap limit may +** changes in future releases of SQLite. +*/ +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); + +/* +** CAPI3REF: Deprecated Soft Heap Limit Interface +** DEPRECATED +** +** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** interface. This routine is provided for historical compatibility +** only. All new applications should use the +** [sqlite3_soft_heap_limit64()] interface rather than this one. +*/ +SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); + + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table +** +** ^This routine returns metadata about a specific column of a specific +** database table accessible using the [database connection] handle +** passed as the first function argument. +** +** ^The column is identified by the second, third and fourth parameters to +** this function. ^The second parameter is either the name of the database +** (i.e. "main", "temp", or an attached database) containing the specified +** table or NULL. ^If it is NULL, then all attached databases are searched +** for the table using the same algorithm used by the database engine to +** resolve unqualified table references. +** +** ^The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** ^Metadata is returned by writing to the memory locations passed as the 5th +** and subsequent parameters to this function. ^Any of these arguments may be +** NULL, in which case the corresponding element of metadata is omitted. +** +** ^(
+** +**
Parameter Output
Type
Description +** +**
5th const char* Data type +**
6th const char* Name of default collation sequence +**
7th int True if column has a NOT NULL constraint +**
8th int True if column is part of the PRIMARY KEY +**
9th int True if column is [AUTOINCREMENT] +**
+**
)^ +** +** ^The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any SQLite API function. +** +** ^If the specified table is actually a view, an [error code] is returned. +** +** ^If the specified column is "rowid", "oid" or "_rowid_" and an +** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. ^(If there is no +** explicitly declared [INTEGER PRIMARY KEY] column, then the output +** parameters are set as follows: +** +**
+**     data type: "INTEGER"
+**     collation sequence: "BINARY"
+**     not null: 0
+**     primary key: 1
+**     auto increment: 0
+** 
)^ +** +** ^(This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an [error code] is returned and an error message left +** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^ +** +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +*/ +SQLITE_API int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension +** +** ^This interface loads an SQLite extension library from the named file. +** +** ^The sqlite3_load_extension() interface attempts to load an +** [SQLite extension] library contained in the file zFile. If +** the file cannot be loaded directly, attempts are made to load +** with various operating-system specific extensions added. +** So for example, if "samplelib" cannot be loaded, then names like +** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might +** be tried also. +** +** ^The entry point is zProc. +** ^(zProc may be 0, in which case SQLite will try to come up with an +** entry point name on its own. It first tries "sqlite3_extension_init". +** If that does not work, it constructs a name "sqlite3_X_init" where the +** X is consists of the lower-case equivalent of all ASCII alphabetic +** characters in the filename from the last "/" to the first following +** "." and omitting any initial "lib".)^ +** ^The sqlite3_load_extension() interface returns +** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** ^If an error occurs and pzErrMsg is not 0, then the +** [sqlite3_load_extension()] interface shall attempt to +** fill *pzErrMsg with error message text stored in memory +** obtained from [sqlite3_malloc()]. The calling function +** should free this memory by calling [sqlite3_free()]. +** +** ^Extension loading must be enabled using +** [sqlite3_enable_load_extension()] prior to calling this API, +** otherwise an error will be returned. +** +** See also the [load_extension() SQL function]. +*/ +SQLITE_API int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading +** +** ^So as not to open security holes in older applications that are +** unprepared to deal with [extension loading], and as a means of disabling +** [extension loading] while evaluating user-entered SQL, the following API +** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** +** ^Extension loading is off by default. +** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** to turn extension loading on and call it with onoff==0 to turn +** it back off again. +*/ +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Automatically Load Statically Linked Extensions +** +** ^This interface causes the xEntryPoint() function to be invoked for +** each new [database connection] that is created. The idea here is that +** xEntryPoint() is the entry point for a statically linked [SQLite extension] +** that is to be automatically loaded into all new database connections. +** +** ^(Even though the function prototype shows that xEntryPoint() takes +** no arguments and returns void, SQLite invokes xEntryPoint() with three +** arguments and expects and integer result as if the signature of the +** entry point where as follows: +** +**
+**    int xEntryPoint(
+**      sqlite3 *db,
+**      const char **pzErrMsg,
+**      const struct sqlite3_api_routines *pThunk
+**    );
+** 
)^ +** +** If the xEntryPoint routine encounters an error, it should make *pzErrMsg +** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg +** is NULL before calling the xEntryPoint(). ^SQLite will invoke +** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], +** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** +** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** on the list of automatic extensions is a harmless no-op. ^No entry point +** will be called more than once for each database connection that is opened. +** +** See also: [sqlite3_reset_auto_extension()] +** and [sqlite3_cancel_auto_extension()] +*/ +SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Cancel Automatic Extension Loading +** +** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the +** initialization routine X that was registered using a prior call to +** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] +** routine returns 1 if initialization routine X was successfully +** unregistered and it returns 0 if X was not on the list of initialization +** routines. +*/ +SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Reset Automatic Extension Loading +** +** ^This interface disables all automatic extensions previously +** registered using [sqlite3_auto_extension()]. +*/ +SQLITE_API void sqlite3_reset_auto_extension(void); + +/* +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** CAPI3REF: Virtual Table Object +** KEYWORDS: sqlite3_module {virtual table module} +** +** This structure, sometimes called a "virtual table module", +** defines the implementation of a [virtual tables]. +** This structure consists mostly of methods for the module. +** +** ^A virtual table module is created by filling in a persistent +** instance of this structure and passing a pointer to that instance +** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** ^The registration remains valid until it is replaced by a different +** module or until the [database connection] closes. The content +** of this structure must not change while it is registered with +** any database connection. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + /* The methods above are in version 1 of the sqlite_module object. Those + ** below are for version 2 and greater. */ + int (*xSavepoint)(sqlite3_vtab *pVTab, int); + int (*xRelease)(sqlite3_vtab *pVTab, int); + int (*xRollbackTo)(sqlite3_vtab *pVTab, int); +}; + +/* +** CAPI3REF: Virtual Table Indexing Information +** KEYWORDS: sqlite3_index_info +** +** The sqlite3_index_info structure and its substructures is used as part +** of the [virtual table] interface to +** pass information into and receive the reply from the [xBestIndex] +** method of a [virtual table module]. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** ^(The aConstraint[] array records WHERE clause constraints of the form: +** +**
column OP expr
+** +** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is +** stored in aConstraint[].op using one of the +** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ +** ^(The index of the column is stored in +** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot.)^ +** +** ^The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** ^The aConstraint[] array only reports WHERE clause terms that are +** relevant to the particular virtual table being queried. +** +** ^Information about the ORDER BY clause is stored in aOrderBy[]. +** ^Each term of aOrderBy records a column of the ORDER BY clause. +** +** The [xBestIndex] method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. ^If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite.)^ +** +** ^The idxNum and idxPtr values are recorded and passed into the +** [xFilter] method. +** ^[sqlite3_free()] is used to free idxPtr if and only if +** needToFreeIdxPtr is true. +** +** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** ^The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; + +/* +** CAPI3REF: Virtual Table Constraint Operator Codes +** +** These macros defined the allowed values for the +** [sqlite3_index_info].aConstraint[].op field. Each value represents +** an operator that is part of a constraint term in the wHERE clause of +** a query that uses a [virtual table]. +*/ +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** CAPI3REF: Register A Virtual Table Implementation +** +** ^These routines are used to register a new [virtual table module] name. +** ^Module names must be registered before +** creating a new [virtual table] using the module and before using a +** preexisting [virtual table] for the module. +** +** ^The module name is registered on the [database connection] specified +** by the first parameter. ^The name of the module is given by the +** second parameter. ^The third parameter is a pointer to +** the implementation of the [virtual table module]. ^The fourth +** parameter is an arbitrary client data pointer that is passed through +** into the [xCreate] and [xConnect] methods of the virtual table module +** when a new virtual table is be being created or reinitialized. +** +** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** is a pointer to a destructor for the pClientData. ^SQLite will +** invoke the destructor function (if it is not NULL) when SQLite +** no longer needs the pClientData pointer. ^The destructor will also +** be invoked if the call to sqlite3_create_module_v2() fails. +** ^The sqlite3_create_module() +** interface is equivalent to sqlite3_create_module_v2() with a NULL +** destructor. +*/ +SQLITE_API int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData /* Client data for xCreate/xConnect */ +); +SQLITE_API int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** CAPI3REF: Virtual Table Instance Object +** KEYWORDS: sqlite3_vtab +** +** Every [virtual table module] implementation uses a subclass +** of this object to describe a particular instance +** of the [virtual table]. Each subclass will +** be tailored to the specific needs of the module implementation. +** The purpose of this superclass is to define certain fields that are +** common to all module implementations. +** +** ^Virtual tables methods can set an error message by assigning a +** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [sqlite3_free()] +** prior to assigning a new string to zErrMsg. ^After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* NO LONGER USED */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Virtual Table Cursor Object +** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** +** Every [virtual table module] implementation uses a subclass of the +** following structure to describe cursors that point into the +** [virtual table] and are used +** to loop through the virtual table. Cursors are created using the +** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods +** of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Declare The Schema Of A Virtual Table +** +** ^The [xCreate] and [xConnect] methods of a +** [virtual table module] call this interface +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); + +/* +** CAPI3REF: Overload A Function For A Virtual Table +** +** ^(Virtual tables can provide alternative implementations of functions +** using the [xFindFunction] method of the [virtual table module]. +** But global versions of those functions +** must exist in order to be overloaded.)^ +** +** ^(This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created.)^ ^The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a placeholder function that can be overloaded +** by a [virtual table]. +*/ +SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB +** KEYWORDS: {BLOB handle} {BLOB handles} +** +** An instance of this object represents an open BLOB on which +** [sqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [sqlite3_blob_open()] +** and destroyed by [sqlite3_blob_close()]. +** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the BLOB. +** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O +** +** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located +** in row iRow, column zColumn, table zTable in database zDb; +** in other words, the same BLOB that would be selected by: +** +**
+**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
+** 
)^ +** +** ^If the flags parameter is non-zero, then the BLOB is opened for read +** and write access. ^If it is zero, the BLOB is opened for read access. +** ^It is not possible to open a column that is part of an index or primary +** key for writing. ^If [foreign key constraints] are enabled, it is +** not possible to open a column that is part of a [child key] for writing. +** +** ^Note that the database name is not the filename that contains +** the database but rather the symbolic name of the database that +** appears after the AS keyword when the database is connected using [ATTACH]. +** ^For the main database file, the database name is "main". +** ^For TEMP tables, the database name is "temp". +** +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written +** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set +** to be a null pointer.)^ +** ^This function sets the [database connection] error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related +** functions. ^Note that the *ppBlob variable is always initialized in a +** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob +** regardless of the success or failure of this routine. +** +** ^(If the row that a BLOB handle points to is modified by an +** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects +** then the BLOB handle is marked as "expired". +** This is true if any column of the row is changed, even a column +** other than the one the BLOB handle is open on.)^ +** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. +** ^(Changes written into a BLOB prior to the BLOB expiring are not +** rolled back by the expiration of the BLOB. Such changes will eventually +** commit if the transaction continues to completion.)^ +** +** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** the opened blob. ^The size of a blob may not be changed by this +** interface. Use the [UPDATE] SQL command to change the size of a +** blob. +** +** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** and the built-in [zeroblob] SQL function can be used, if desired, +** to create an empty, zero-filled blob in which to read or write using +** this interface. +** +** To avoid a resource leak, every open [BLOB handle] should eventually +** be released by a call to [sqlite3_blob_close()]. +*/ +SQLITE_API int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Move a BLOB Handle to a New Row +** +** ^This function is used to move an existing blob handle so that it points +** to a different row of the same database table. ^The new row is identified +** by the rowid value passed as the second argument. Only the row can be +** changed. ^The database, table and column on which the blob handle is open +** remain the same. Moving an existing blob handle to a new row can be +** faster than closing the existing handle and opening a new one. +** +** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** it must exist and there must be either a blob or text value stored in +** the nominated column.)^ ^If the new row is not present in the table, or if +** it does not contain a blob or text value, or if another error occurs, an +** SQLite error code is returned and the blob handle is considered aborted. +** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or +** [sqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** always returns zero. +** +** ^This function sets the database handle error code and message. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); + +/* +** CAPI3REF: Close A BLOB Handle +** +** ^Closes an open [BLOB handle]. +** +** ^Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in [autocommit mode]. +** ^If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. +** +** ^(Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. Any errors that occur during +** closing are reported as a non-zero return value.)^ +** +** ^(The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed.)^ +** +** ^Calling this routine with a null pointer (such as would be returned +** by a failed call to [sqlite3_blob_open()]) is a harmless no-op. +*/ +SQLITE_API int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB +** +** ^Returns the size in bytes of the BLOB accessible via the +** successfully opened [BLOB handle] in its only argument. ^The +** incremental blob I/O routines can only read or overwriting existing +** blob content; they cannot change the size of a blob. +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +*/ +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally +** +** ^(This function is used to read data from an open [BLOB handle] into a +** caller-supplied buffer. N bytes of data are copied into buffer Z +** from the open BLOB, starting at offset iOffset.)^ +** +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is +** less than zero, [SQLITE_ERROR] is returned and no data is read. +** ^The size of the blob (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to read from an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. +** +** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_write()]. +*/ +SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally +** +** ^This function is used to write data into an open [BLOB handle] from a +** caller-supplied buffer. ^N bytes of data are copied from the buffer Z +** into the open BLOB, starting at offset iOffset. +** +** ^If the [BLOB handle] passed as the first argument was not opened for +** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** this function returns [SQLITE_READONLY]. +** +** ^This function may only modify the contents of the BLOB; it is +** not possible to increase the size of a BLOB using this API. +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is written. ^If N is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** The size of the BLOB (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to write to an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred +** before the [BLOB handle] expired are not rolled back by the +** expiration of the handle, though of course those changes might +** have been overwritten by the statement that expired the BLOB handle +** or by other independent statements. +** +** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_read()]. +*/ +SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most SQLite builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^Names are case sensitive. +** ^Names are zero-terminated UTF-8 strings. +** ^If there is no match, a NULL pointer is returned. +** ^If zVfsName is NULL then the default VFS is returned. +** +** ^New VFSes are registered with sqlite3_vfs_register(). +** ^Each new VFS becomes the default VFS if the makeDflt flag is set. +** ^The same VFS can be registered multiple times without injury. +** ^To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. If two different VFSes with the +** same name are registered, the behavior is undefined. If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^(If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary.)^ +*/ +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. ^(The following +** implementations are available in the SQLite core: +** +**
    +**
  • SQLITE_MUTEX_PTHREADS +**
  • SQLITE_MUTEX_W32 +**
  • SQLITE_MUTEX_NOOP +**
)^ +** +** ^The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and +** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix +** and Windows. +** +** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. In this case the +** application must supply a custom mutex implementation using the +** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function +** before calling sqlite3_initialize() or any other public sqlite3_ +** function that calls sqlite3_initialize().)^ +** +** ^The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^If it returns NULL +** that means that a mutex could not be allocated. ^SQLite +** will unwind its stack and return an error. ^(The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_LRU2 +**
)^ +** +** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) +** cause sqlite3_mutex_alloc() to create +** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. ^SQLite will only request a recursive mutex in +** cases where it really needs one. ^If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return +** a pointer to a static preexisting mutex. ^Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. ^But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +** +** ^The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. ^SQLite is careful to deallocate every +** dynamic mutex that it allocates. The dynamic mutexes must not be in +** use when they are deallocated. Attempting to deallocate a static +** mutex results in undefined behavior. ^SQLite never deallocates +** a static mutex. +** +** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. ^If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** upon successful entry. ^(Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter.)^ ^(If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** SQLite will never exhibit +** such behavior in its own use of mutexes.)^ +** +** ^(Some systems (for example, Windows 95) do not support the operation +** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** will always return SQLITE_BUSY. The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^ +** +** ^The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. ^(The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. SQLite will +** never do either.)^ +** +** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or +** sqlite3_mutex_leave() is a NULL pointer, then all three routines +** behave as no-ops. +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Methods Object +** +** An instance of this structure defines the low-level routines +** used to allocate and use mutexes. +** +** Usually, the default mutex implementations provided by SQLite are +** sufficient, however the user has the option of substituting a custom +** implementation for specialized deployments or systems for which SQLite +** does not provide a suitable implementation. In this case, the user +** creates and populates an instance of this structure to pass +** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** Additionally, an instance of this structure can be used as an +** output variable when querying the system for the current mutex +** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. +** +** ^The xMutexInit method defined by this structure is invoked as +** part of system initialization by the sqlite3_initialize() function. +** ^The xMutexInit routine is called by SQLite exactly once for each +** effective call to [sqlite3_initialize()]. +** +** ^The xMutexEnd method defined by this structure is invoked as +** part of system shutdown by the sqlite3_shutdown() function. The +** implementation of this method is expected to release all outstanding +** resources obtained by the mutex methods implementation, especially +** those obtained by the xMutexInit method. ^The xMutexEnd() +** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** +** ^(The remaining seven methods defined by this structure (xMutexAlloc, +** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and +** xMutexNotheld) implement the following interfaces (respectively): +** +**
    +**
  • [sqlite3_mutex_alloc()]
  • +**
  • [sqlite3_mutex_free()]
  • +**
  • [sqlite3_mutex_enter()]
  • +**
  • [sqlite3_mutex_try()]
  • +**
  • [sqlite3_mutex_leave()]
  • +**
  • [sqlite3_mutex_held()]
  • +**
  • [sqlite3_mutex_notheld()]
  • +**
)^ +** +** The only difference is that the public sqlite3_XXX functions enumerated +** above silently ignore any invocations that pass a NULL pointer instead +** of a valid mutex handle. The implementations of the methods defined +** by this structure are not required to handle this case, the results +** of passing a NULL pointer instead of a valid mutex handle are undefined +** (i.e. it is acceptable to provide an implementation that segfaults if +** it is passed a NULL pointer). +** +** The xMutexInit() method must be threadsafe. ^It must be harmless to +** invoke xMutexInit() multiple times within the same process and without +** intervening calls to xMutexEnd(). Second and subsequent calls to +** xMutexInit() must be no-ops. +** +** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory +** allocation for a static mutex. ^However xMutexAlloc() may use SQLite +** memory allocation for a fast or recursive mutex. +** +** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** called, but only if the prior call to xMutexInit returned SQLITE_OK. +** If xMutexInit fails in any way, it is expected to clean up after itself +** prior to returning. +*/ +typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; +struct sqlite3_mutex_methods { + int (*xMutexInit)(void); + int (*xMutexEnd)(void); + sqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(sqlite3_mutex *); + void (*xMutexEnter)(sqlite3_mutex *); + int (*xMutexTry)(sqlite3_mutex *); + void (*xMutexLeave)(sqlite3_mutex *); + int (*xMutexHeld)(sqlite3_mutex *); + int (*xMutexNotheld)(sqlite3_mutex *); +}; + +/* +** CAPI3REF: Mutex Verification Routines +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. ^The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. ^The SQLite core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. ^External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** ^These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. +** +** ^The implementation is not required to provide versions of these +** routines that actually work. If the implementation does not provide working +** versions of these routines, it should at least provide stubs that always +** return true so that one does not get spurious assertion failures. +** +** ^If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. ^The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +#ifndef NDEBUG +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); +#endif + +/* +** CAPI3REF: Mutex Types +** +** The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. +** +** The set of static mutexes may change from one SQLite release to the +** next. Applications that override the built-in mutex logic must be +** prepared to accommodate additional static mutexes. +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ +#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ + +/* +** CAPI3REF: Retrieve the mutex for a database connection +** +** ^This interface returns a pointer the [sqlite3_mutex] object that +** serializes access to the [database connection] given in the argument +** when the [threading mode] is Serialized. +** ^If the [threading mode] is Single-thread or Multi-thread then this +** routine returns a NULL pointer. +*/ +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); + +/* +** CAPI3REF: Low-Level Control Of Database Files +** +** ^The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. ^The +** name of the database is "main" for the main database or "temp" for the +** TEMP database, or the name that appears after the AS keyword for +** databases that are added using the [ATTACH] SQL command. +** ^A NULL pointer can be used in place of "main" to refer to the +** main database file. +** ^The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. ^The return value of the xFileControl +** method becomes the return value of this routine. +** +** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes +** a pointer to the underlying [sqlite3_file] object to be written into +** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER +** case is a short-circuit path which does not actually invoke the +** underlying sqlite3_io_methods.xFileControl method. +** +** ^If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. ^This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. The underlying xFileControl method might +** also return SQLITE_ERROR. There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** CAPI3REF: Testing Interface +** +** ^The sqlite3_test_control() interface is used to read out internal +** state of SQLite and to inject faults into SQLite for testing +** purposes. ^The first parameter is an operation code that determines +** the number, meaning, and operation of all subsequent parameters. +** +** This interface is not for use by applications. It exists solely +** for verifying the correct operation of the SQLite library. Depending +** on how the SQLite library is compiled, this interface might not exist. +** +** The details of the operation codes, their meanings, the parameters +** they take, and what they do are all subject to change without notice. +** Unlike most of the SQLite API, this function is not guaranteed to +** operate consistently from one release to the next. +*/ +SQLITE_API int sqlite3_test_control(int op, ...); + +/* +** CAPI3REF: Testing Interface Operation Codes +** +** These constants are the valid operation code parameters used +** as the first argument to [sqlite3_test_control()]. +** +** These parameters and their meanings are subject to change +** without notice. These values are for testing purposes only. +** Applications should not use any of these parameters or the +** [sqlite3_test_control()] interface. +*/ +#define SQLITE_TESTCTRL_FIRST 5 +#define SQLITE_TESTCTRL_PRNG_SAVE 5 +#define SQLITE_TESTCTRL_PRNG_RESTORE 6 +#define SQLITE_TESTCTRL_PRNG_RESET 7 +#define SQLITE_TESTCTRL_BITVEC_TEST 8 +#define SQLITE_TESTCTRL_FAULT_INSTALL 9 +#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 +#define SQLITE_TESTCTRL_PENDING_BYTE 11 +#define SQLITE_TESTCTRL_ASSERT 12 +#define SQLITE_TESTCTRL_ALWAYS 13 +#define SQLITE_TESTCTRL_RESERVE 14 +#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 +#define SQLITE_TESTCTRL_ISKEYWORD 16 +#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 +#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 +#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 +#define SQLITE_TESTCTRL_LAST 19 + +/* +** CAPI3REF: SQLite Runtime Status +** +** ^This interface is used to retrieve runtime status information +** about the performance of SQLite, and optionally to reset various +** highwater marks. ^The first argument is an integer code for +** the specific parameter to measure. ^(Recognized integer codes +** are of the form [status parameters | SQLITE_STATUS_...].)^ +** ^The current value of the parameter is returned into *pCurrent. +** ^The highest recorded value is returned in *pHighwater. ^If the +** resetFlag is true, then the highest record value is reset after +** *pHighwater is written. ^(Some parameters do not record the highest +** value. For those parameters +** nothing is written into *pHighwater and the resetFlag is ignored.)^ +** ^(Other parameters record only the highwater mark and not the current +** value. For these latter parameters nothing is written into *pCurrent.)^ +** +** ^The sqlite3_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** This routine is threadsafe but is not atomic. This routine can be +** called while other threads are running the same or different SQLite +** interfaces. However the values returned in *pCurrent and +** *pHighwater reflect the status of SQLite at different points in time +** and it is possible that another thread might change the parameter +** in between the times when *pCurrent and *pHighwater are written. +** +** See also: [sqlite3_db_status()] +*/ +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); + + +/* +** CAPI3REF: Status Parameters +** KEYWORDS: {status parameters} +** +** These integer constants designate various run-time status parameters +** that can be returned by [sqlite3_status()]. +** +**
+** [[SQLITE_STATUS_MEMORY_USED]] ^(
SQLITE_STATUS_MEMORY_USED
+**
This parameter is the current amount of memory checked out +** using [sqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [sqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Scratch memory +** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache +** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in +** this parameter. The amount returned is the sum of the allocation +** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ +** +** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
SQLITE_STATUS_MALLOC_SIZE
+**
This parameter records the largest memory allocation request +** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** internal equivalents). Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
+**
This parameter records the number of separate memory allocations +** currently checked out.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
SQLITE_STATUS_PAGECACHE_USED
+**
This parameter returns the number of pages used out of the +** [pagecache memory allocator] that was configured using +** [SQLITE_CONFIG_PAGECACHE]. The +** value returned is in pages, not in bytes.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] +** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
+**
This parameter returns the number of bytes of page cache +** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] +** buffer and where forced to overflow to [sqlite3_malloc()]. The +** returned value includes allocations that overflowed because they +** where too large (they were larger than the "sz" parameter to +** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because +** no space was left in the page cache.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
SQLITE_STATUS_PAGECACHE_SIZE
+**
This parameter records the largest memory allocation request +** handed to [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_SCRATCH_USED]] ^(
SQLITE_STATUS_SCRATCH_USED
+**
This parameter returns the number of allocations used out of the +** [scratch memory allocator] configured using +** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not +** in bytes. Since a single thread may only have one scratch allocation +** outstanding at time, this parameter also reports the number of threads +** using scratch memory at the same time.
)^ +** +** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
+**
This parameter returns the number of bytes of scratch memory +** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] +** buffer and where forced to overflow to [sqlite3_malloc()]. The values +** returned include overflows because the requested allocation was too +** larger (that is, because the requested allocation was larger than the +** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer +** slots were available. +**
)^ +** +** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(
SQLITE_STATUS_SCRATCH_SIZE
+**
This parameter records the largest memory allocation request +** handed to [scratch memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_PARSER_STACK]] ^(
SQLITE_STATUS_PARSER_STACK
+**
This parameter records the deepest parser stack. It is only +** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ +**
+** +** New status parameters may be added from time to time. +*/ +#define SQLITE_STATUS_MEMORY_USED 0 +#define SQLITE_STATUS_PAGECACHE_USED 1 +#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 +#define SQLITE_STATUS_SCRATCH_USED 3 +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 +#define SQLITE_STATUS_MALLOC_SIZE 5 +#define SQLITE_STATUS_PARSER_STACK 6 +#define SQLITE_STATUS_PAGECACHE_SIZE 7 +#define SQLITE_STATUS_SCRATCH_SIZE 8 +#define SQLITE_STATUS_MALLOC_COUNT 9 + +/* +** CAPI3REF: Database Connection Status +** +** ^This interface is used to retrieve runtime status information +** about a single [database connection]. ^The first argument is the +** database connection object to be interrogated. ^The second argument +** is an integer constant, taken from the set of +** [SQLITE_DBSTATUS options], that +** determines the parameter to interrogate. The set of +** [SQLITE_DBSTATUS options] is likely +** to grow in future releases of SQLite. +** +** ^The current value of the requested parameter is written into *pCur +** and the highest instantaneous value is written into *pHiwtr. ^If +** the resetFlg is true, then the highest instantaneous value is +** reset back down to the current value. +** +** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +*/ +SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + +/* +** CAPI3REF: Status Parameters for database connections +** KEYWORDS: {SQLITE_DBSTATUS options} +** +** These constants are the available integer "verbs" that can be passed as +** the second argument to the [sqlite3_db_status()] interface. +** +** New verbs may be added in future releases of SQLite. Existing verbs +** might be discontinued. Applications should check the return code from +** [sqlite3_db_status()] to make sure that the call worked. +** The [sqlite3_db_status()] interface will return a non-zero error code +** if a discontinued or unsupported verb is invoked. +** +**
+** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
+**
This parameter returns the number of lookaside memory slots currently +** checked out.
)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
+**
This parameter returns the number malloc attempts that were +** satisfied using lookaside memory. Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to the amount of +** memory requested being larger than the lookaside slot size. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to all lookaside +** memory already being in use. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used by all pager caches associated with the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** +** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used to store the schema for all databases associated +** with the connection - main, temp, and any [ATTACH]-ed databases.)^ +** ^The full amount of memory used by the schemas is reported, even if the +** schema memory is shared with other database connections due to +** [shared cache mode] being enabled. +** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** +** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
+**
This parameter returns the approximate number of of bytes of heap +** and lookaside memory used by all prepared statements associated with +** the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
SQLITE_DBSTATUS_CACHE_HIT
+**
This parameter returns the number of pager cache hits that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
SQLITE_DBSTATUS_CACHE_MISS
+**
This parameter returns the number of pager cache misses that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
SQLITE_DBSTATUS_CACHE_WRITE
+**
This parameter returns the number of dirty cache entries that have +** been written to disk. Specifically, the number of pages written to the +** wal file in wal mode databases, or the number of pages written to the +** database file in rollback mode databases. Any pages written as part of +** transaction rollback or database recovery operations are not included. +** If an IO or other error occurs while writing a page to disk, the effect +** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The +** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. +**
+** +** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(
SQLITE_DBSTATUS_DEFERRED_FKS
+**
This parameter returns zero for the current value if and only if +** all foreign key constraints (deferred or immediate) have been +** resolved.)^ ^The highwater mark is always 0. +**
+**
+*/ +#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 +#define SQLITE_DBSTATUS_CACHE_USED 1 +#define SQLITE_DBSTATUS_SCHEMA_USED 2 +#define SQLITE_DBSTATUS_STMT_USED 3 +#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 +#define SQLITE_DBSTATUS_CACHE_HIT 7 +#define SQLITE_DBSTATUS_CACHE_MISS 8 +#define SQLITE_DBSTATUS_CACHE_WRITE 9 +#define SQLITE_DBSTATUS_DEFERRED_FKS 10 +#define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */ + + +/* +** CAPI3REF: Prepared Statement Status +** +** ^(Each prepared statement maintains various +** [SQLITE_STMTSTATUS counters] that measure the number +** of times it has performed specific operations.)^ These counters can +** be used to monitor the performance characteristics of the prepared +** statements. For example, if the number of table steps greatly exceeds +** the number of table searches or result rows, that would tend to indicate +** that the prepared statement is using a full table scan rather than +** an index. +** +** ^(This interface is used to retrieve and reset counter values from +** a [prepared statement]. The first argument is the prepared statement +** object to be interrogated. The second argument +** is an integer code for a specific [SQLITE_STMTSTATUS counter] +** to be interrogated.)^ +** ^The current value of the requested counter is returned. +** ^If the resetFlg is true, then the counter is reset to zero after this +** interface call returns. +** +** See also: [sqlite3_status()] and [sqlite3_db_status()]. +*/ +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + +/* +** CAPI3REF: Status Parameters for prepared statements +** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} +** +** These preprocessor macros define integer codes that name counter +** values associated with the [sqlite3_stmt_status()] interface. +** The meanings of the various counters are as follows: +** +**
+** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
SQLITE_STMTSTATUS_FULLSCAN_STEP
+**
^This is the number of times that SQLite has stepped forward in +** a table as part of a full table scan. Large numbers for this counter +** may indicate opportunities for performance improvement through +** careful use of indices.
+** +** [[SQLITE_STMTSTATUS_SORT]]
SQLITE_STMTSTATUS_SORT
+**
^This is the number of sort operations that have occurred. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance through careful use of indices.
+** +** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
+**
^This is the number of rows inserted into transient indices that +** were created automatically in order to help joins run faster. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance by adding permanent indices that do not +** need to be reinitialized each time the statement is run.
+** +** [[SQLITE_STMTSTATUS_VM_STEP]]
SQLITE_STMTSTATUS_VM_STEP
+**
^This is the number of virtual machine operations executed +** by the prepared statement if that number is less than or equal +** to 2147483647. The number of virtual machine operations can be +** used as a proxy for the total work done by the prepared statement. +** If the number of virtual machine operations exceeds 2147483647 +** then the value returned by this statement status code is undefined. +**
+**
+*/ +#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 +#define SQLITE_STMTSTATUS_SORT 2 +#define SQLITE_STMTSTATUS_AUTOINDEX 3 +#define SQLITE_STMTSTATUS_VM_STEP 4 + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache type is opaque. It is implemented by +** the pluggable module. The SQLite core has no knowledge of +** its size or internal structure and never deals with the +** sqlite3_pcache object except by holding and passing pointers +** to the object. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache sqlite3_pcache; + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache_page object represents a single page in the +** page cache. The page cache will allocate instances of this +** object. Various methods of the page cache use pointers to instances +** of this object as parameters or as their return value. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache_page sqlite3_pcache_page; +struct sqlite3_pcache_page { + void *pBuf; /* The content of the page */ + void *pExtra; /* Extra information associated with the page */ +}; + +/* +** CAPI3REF: Application Defined Page Cache. +** KEYWORDS: {page cache} +** +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can +** register an alternative page cache implementation by passing in an +** instance of the sqlite3_pcache_methods2 structure.)^ +** In many applications, most of the heap memory allocated by +** SQLite is used for the page cache. +** By implementing a +** custom page cache using this API, an application can better control +** the amount of memory consumed by SQLite, the way in which +** that memory is allocated and released, and the policies used to +** determine exactly which parts of a database file are cached and for +** how long. +** +** The alternative page cache mechanism is an +** extreme measure that is only needed by the most demanding applications. +** The built-in page cache is recommended for most uses. +** +** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an +** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** the application may discard the parameter after the call to +** [sqlite3_config()] returns.)^ +** +** [[the xInit() page cache method]] +** ^(The xInit() method is called once for each effective +** call to [sqlite3_initialize()])^ +** (usually only once during the lifetime of the process). ^(The xInit() +** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ +** The intent of the xInit() method is to set up global data structures +** required by the custom page cache implementation. +** ^(If the xInit() method is NULL, then the +** built-in default page cache is used instead of the application defined +** page cache.)^ +** +** [[the xShutdown() page cache method]] +** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** It can be used to clean up +** any outstanding resources before process shutdown, if required. +** ^The xShutdown() method may be NULL. +** +** ^SQLite automatically serializes calls to the xInit method, +** so the xInit method need not be threadsafe. ^The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. All other methods must be threadsafe +** in multithreaded applications. +** +** ^SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +** +** [[the xCreate() page cache methods]] +** ^SQLite invokes the xCreate() method to construct a new cache instance. +** SQLite will typically create one cache instance for each open database file, +** though this is not guaranteed. ^The +** first parameter, szPage, is the size in bytes of the pages that must +** be allocated by the cache. ^szPage will always a power of two. ^The +** second parameter szExtra is a number of bytes of extra storage +** associated with each page cache entry. ^The szExtra parameter will +** a number less than 250. SQLite will use the +** extra szExtra bytes on each page to store metadata about the underlying +** database page on disk. The value passed into szExtra depends +** on the SQLite version, the target platform, and how SQLite was compiled. +** ^The third argument to xCreate(), bPurgeable, is true if the cache being +** created will be used to cache database pages of a file stored on disk, or +** false if it is used for an in-memory database. The cache implementation +** does not have to do anything special based with the value of bPurgeable; +** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will +** never invoke xUnpin() except to deliberately delete a page. +** ^In other words, calls to xUnpin() on a cache with bPurgeable set to +** false will always have the "discard" flag set to true. +** ^Hence, a cache created with bPurgeable false will +** never contain any unpinned pages. +** +** [[the xCachesize() page cache method]] +** ^(The xCachesize() method may be called at any time by SQLite to set the +** suggested maximum cache-size (number of pages stored by) the cache +** instance passed as the first argument. This is the value configured using +** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable +** parameter, the implementation is not required to do anything with this +** value; it is advisory only. +** +** [[the xPagecount() page cache methods]] +** The xPagecount() method must return the number of pages currently +** stored in the cache, both pinned and unpinned. +** +** [[the xFetch() page cache methods]] +** The xFetch() method locates a page in the cache and returns a pointer to +** an sqlite3_pcache_page object associated with that page, or a NULL pointer. +** The pBuf element of the returned sqlite3_pcache_page object will be a +** pointer to a buffer of szPage bytes used to store the content of a +** single database page. The pExtra element of sqlite3_pcache_page will be +** a pointer to the szExtra bytes of extra storage that SQLite has requested +** for each entry in the page cache. +** +** The page to be fetched is determined by the key. ^The minimum key value +** is 1. After it has been retrieved using xFetch, the page is considered +** to be "pinned". +** +** If the requested page is already in the page cache, then the page cache +** implementation must return a pointer to the page buffer with its content +** intact. If the requested page is not already in the cache, then the +** cache implementation should use the value of the createFlag +** parameter to help it determined what action to take: +** +** +**
createFlag Behavior when page is not already in cache +**
0 Do not allocate a new page. Return NULL. +**
1 Allocate a new page if it easy and convenient to do so. +** Otherwise return NULL. +**
2 Make every effort to allocate a new page. Only return +** NULL if allocating a new page is effectively impossible. +**
+** +** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite +** will only use a createFlag of 2 after a prior call with a createFlag of 1 +** failed.)^ In between the to xFetch() calls, SQLite may +** attempt to unpin one or more cache pages by spilling the content of +** pinned pages to disk and synching the operating system disk cache. +** +** [[the xUnpin() page cache method]] +** ^xUnpin() is called by SQLite with a pointer to a currently pinned page +** as its second argument. If the third parameter, discard, is non-zero, +** then the page must be evicted from the cache. +** ^If the discard parameter is +** zero, then the page may be discarded or retained at the discretion of +** page cache implementation. ^The page cache implementation +** may choose to evict unpinned pages at any time. +** +** The cache must not perform any reference counting. A single +** call to xUnpin() unpins the page regardless of the number of prior calls +** to xFetch(). +** +** [[the xRekey() page cache methods]] +** The xRekey() method is used to change the key value associated with the +** page passed as the second argument. If the cache +** previously contains an entry associated with newKey, it must be +** discarded. ^Any prior cache entry associated with newKey is guaranteed not +** to be pinned. +** +** When SQLite calls the xTruncate() method, the cache must discard all +** existing cache entries with page numbers (keys) greater than or equal +** to the value of the iLimit parameter passed to xTruncate(). If any +** of these pages are pinned, they are implicitly unpinned, meaning that +** they can be safely discarded. +** +** [[the xDestroy() page cache method]] +** ^The xDestroy() method is used to delete a cache allocated by xCreate(). +** All resources associated with the specified cache should be freed. ^After +** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] +** handle invalid, and will not use it with any other sqlite3_pcache_methods2 +** functions. +** +** [[the xShrink() page cache method]] +** ^SQLite invokes the xShrink() method when it wants the page cache to +** free up as much of heap memory as possible. The page cache implementation +** is not obligated to free any memory, but well-behaved implementations should +** do their best. +*/ +typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; +struct sqlite3_pcache_methods2 { + int iVersion; + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); + void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, + unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); + void (*xShrink)(sqlite3_pcache*); +}; + +/* +** This is the obsolete pcache_methods object that has now been replaced +** by sqlite3_pcache_methods2. This object is not used by SQLite. It is +** retained in the header file for backwards compatibility only. +*/ +typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; +struct sqlite3_pcache_methods { + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, void*, int discard); + void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); +}; + + +/* +** CAPI3REF: Online Backup Object +** +** The sqlite3_backup object records state information about an ongoing +** online backup operation. ^The sqlite3_backup object is created by +** a call to [sqlite3_backup_init()] and is destroyed by a call to +** [sqlite3_backup_finish()]. +** +** See Also: [Using the SQLite Online Backup API] +*/ +typedef struct sqlite3_backup sqlite3_backup; + +/* +** CAPI3REF: Online Backup API. +** +** The backup API copies the content of one database into another. +** It is useful either for creating backups of databases or +** for copying in-memory databases to or from persistent files. +** +** See Also: [Using the SQLite Online Backup API] +** +** ^SQLite holds a write transaction open on the destination database file +** for the duration of the backup operation. +** ^The source database is read-locked only while it is being read; +** it is not locked continuously for the entire backup operation. +** ^Thus, the backup may be performed on a live source database without +** preventing other database connections from +** reading or writing to the source database while the backup is underway. +** +** ^(To perform a backup operation: +**
    +**
  1. sqlite3_backup_init() is called once to initialize the +** backup, +**
  2. sqlite3_backup_step() is called one or more times to transfer +** the data between the two databases, and finally +**
  3. sqlite3_backup_finish() is called to release all resources +** associated with the backup operation. +**
)^ +** There should be exactly one call to sqlite3_backup_finish() for each +** successful call to sqlite3_backup_init(). +** +** [[sqlite3_backup_init()]] sqlite3_backup_init() +** +** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** [database connection] associated with the destination database +** and the database name, respectively. +** ^The database name is "main" for the main database, "temp" for the +** temporary database, or the name specified after the AS keyword in +** an [ATTACH] statement for an attached database. +** ^The S and M arguments passed to +** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** and database name of the source database, respectively. +** ^The source and destination [database connections] (parameters S and D) +** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** an error. +** +** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** returned and an error code and error message are stored in the +** destination [database connection] D. +** ^The error code and message for the failed call to sqlite3_backup_init() +** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or +** [sqlite3_errmsg16()] functions. +** ^A successful call to sqlite3_backup_init() returns a pointer to an +** [sqlite3_backup] object. +** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and +** sqlite3_backup_finish() functions to perform the specified backup +** operation. +** +** [[sqlite3_backup_step()]] sqlite3_backup_step() +** +** ^Function sqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [sqlite3_backup] object B. +** ^If N is negative, all remaining source pages are copied. +** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** are still more pages to be copied, then the function returns [SQLITE_OK]. +** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** from source to destination, then it returns [SQLITE_DONE]. +** ^If an error occurs while running sqlite3_backup_step(B,N), +** then an [error code] is returned. ^As well as [SQLITE_OK] and +** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. +** +** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +**
    +**
  1. the destination database was opened read-only, or +**
  2. the destination database is using write-ahead-log journaling +** and the destination and source page sizes differ, or +**
  3. the destination database is an in-memory database and the +** destination and source page sizes differ. +**
)^ +** +** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then +** the [sqlite3_busy_handler | busy-handler function] +** is invoked (if one is specified). ^If the +** busy-handler returns non-zero before the lock is available, then +** [SQLITE_BUSY] is returned to the caller. ^In this case the call to +** sqlite3_backup_step() can be retried later. ^If the source +** [database connection] +** is being used to write to the source database when sqlite3_backup_step() +** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this +** case the call to sqlite3_backup_step() can be retried later on. ^(If +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or +** [SQLITE_READONLY] is returned, then +** there is no point in retrying the call to sqlite3_backup_step(). These +** errors are considered fatal.)^ The application must accept +** that the backup operation has failed and pass the backup operation handle +** to the sqlite3_backup_finish() to release associated resources. +** +** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** on the destination file. ^The exclusive lock is not released until either +** sqlite3_backup_finish() is called or the backup operation is complete +** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** sqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the sqlite3_backup_step() call. +** ^Because the source database is not locked between calls to +** sqlite3_backup_step(), the source database may be modified mid-way +** through the backup process. ^If the source database is modified by an +** external process or via a database connection other than the one being +** used by the backup operation, then the backup will be automatically +** restarted by the next call to sqlite3_backup_step(). ^If the source +** database is modified by the using the same database connection as is used +** by the backup operation, then the backup database is automatically +** updated at the same time. +** +** [[sqlite3_backup_finish()]] sqlite3_backup_finish() +** +** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** application wishes to abandon the backup operation, the application +** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). +** ^The sqlite3_backup_finish() interfaces releases all +** resources associated with the [sqlite3_backup] object. +** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** active write-transaction on the destination database is rolled back. +** The [sqlite3_backup] object is invalid +** and may not be used following a call to sqlite3_backup_finish(). +** +** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no +** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() completed. +** ^If an out-of-memory condition or IO error occurred during any prior +** sqlite3_backup_step() call on the same [sqlite3_backup] object, then +** sqlite3_backup_finish() returns the corresponding [error code]. +** +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** is not a permanent error and does not affect the return value of +** sqlite3_backup_finish(). +** +** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]] +** sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** +** ^Each call to sqlite3_backup_step() sets two values inside +** the [sqlite3_backup] object: the number of pages still to be backed +** up and the total number of pages in the source database file. +** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces +** retrieve these two values, respectively. +** +** ^The values returned by these functions are only updated by +** sqlite3_backup_step(). ^If the source database is modified during a backup +** operation, then the values are not updated to account for any extra +** pages that need to be updated or the size of the source database file +** changing. +** +** Concurrent Usage of Database Handles +** +** ^The source [database connection] may be used by the application for other +** purposes while a backup operation is underway or being initialized. +** ^If SQLite is compiled and configured to support threadsafe database +** connections, then the source database connection may be used concurrently +** from within other threads. +** +** However, the application must guarantee that the destination +** [database connection] is not passed to any other API (by any thread) after +** sqlite3_backup_init() is called and before the corresponding call to +** sqlite3_backup_finish(). SQLite does not currently check to see +** if the application incorrectly accesses the destination [database connection] +** and so no error code is reported, but the operations may malfunction +** nevertheless. Use of the destination database connection while a +** backup is in progress might also also cause a mutex deadlock. +** +** If running in [shared cache mode], the application must +** guarantee that the shared cache used by the destination database +** is not accessed while the backup is running. In practice this means +** that the application must guarantee that the disk file being +** backed up to is not accessed by any connection within the process, +** not just the specific connection that was passed to sqlite3_backup_init(). +** +** The [sqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to sqlite3_backup_step(). +** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** APIs are not strictly speaking threadsafe. If they are invoked at the +** same time as another thread is invoking sqlite3_backup_step() it is +** possible that they return invalid values. +*/ +SQLITE_API sqlite3_backup *sqlite3_backup_init( + sqlite3 *pDest, /* Destination database handle */ + const char *zDestName, /* Destination database name */ + sqlite3 *pSource, /* Source database handle */ + const char *zSourceName /* Source database name */ +); +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); + +/* +** CAPI3REF: Unlock Notification +** +** ^When running in shared-cache mode, a database operation may fail with +** an [SQLITE_LOCKED] error if the required locks on the shared-cache or +** individual tables within the shared-cache cannot be obtained. See +** [SQLite Shared-Cache Mode] for a description of shared-cache locking. +** ^This API may be used to register a callback that SQLite will invoke +** when the connection currently holding the required lock relinquishes it. +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. +** +** See Also: [Using the SQLite Unlock Notification Feature]. +** +** ^Shared-cache locks are released when a database connection concludes +** its current transaction, either by committing it or rolling it back. +** +** ^When a connection (known as the blocked connection) fails to obtain a +** shared-cache lock and SQLITE_LOCKED is returned to the caller, the +** identity of the database connection (the blocking connection) that +** has locked the required resource is stored internally. ^After an +** application receives an SQLITE_LOCKED error, it may call the +** sqlite3_unlock_notify() method with the blocked connection handle as +** the first argument to register for a callback that will be invoked +** when the blocking connections current transaction is concluded. ^The +** callback is invoked from within the [sqlite3_step] or [sqlite3_close] +** call that concludes the blocking connections transaction. +** +** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** there is a chance that the blocking connection will have already +** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** If this happens, then the specified callback is invoked immediately, +** from within the call to sqlite3_unlock_notify().)^ +** +** ^If the blocked connection is attempting to obtain a write-lock on a +** shared-cache table, and more than one other connection currently holds +** a read-lock on the same table, then SQLite arbitrarily selects one of +** the other connections to use as the blocking connection. +** +** ^(There may be at most one unlock-notify callback registered by a +** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection already has a registered unlock-notify callback, +** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** called with a NULL pointer as its second argument, then any existing +** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback may also be canceled by closing the blocked +** connection using [sqlite3_close()]. +** +** The unlock-notify callback is not reentrant. If an application invokes +** any sqlite3_xxx API functions from within an unlock-notify callback, a +** crash or deadlock may be the result. +** +** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** returns SQLITE_OK. +** +** Callback Invocation Details +** +** When an unlock-notify callback is registered, the application provides a +** single void* pointer that is passed to the callback when it is invoked. +** However, the signature of the callback function allows SQLite to pass +** it an array of void* context pointers. The first argument passed to +** an unlock-notify callback is a pointer to an array of void* pointers, +** and the second is the number of entries in the array. +** +** When a blocking connections transaction is concluded, there may be +** more than one blocked connection that has registered for an unlock-notify +** callback. ^If two or more such blocked connections have specified the +** same callback function, then instead of invoking the callback function +** multiple times, it is invoked once with the set of void* context pointers +** specified by the blocked connections bundled together into an array. +** This gives the application an opportunity to prioritize any actions +** related to the set of unblocked database connections. +** +** Deadlock Detection +** +** Assuming that after registering for an unlock-notify callback a +** database waits for the callback to be issued before taking any further +** action (a reasonable assumption), then using this API may cause the +** application to deadlock. For example, if connection X is waiting for +** connection Y's transaction to be concluded, and similarly connection +** Y is waiting on connection X's transaction, then neither connection +** will proceed and the system may remain deadlocked indefinitely. +** +** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to sqlite3_unlock_notify() would put the +** system in a deadlocked state, then SQLITE_LOCKED is returned and no +** unlock-notify callback is registered. The system is said to be in +** a deadlocked state if connection A has registered for an unlock-notify +** callback on the conclusion of connection B's transaction, and connection +** B has itself registered for an unlock-notify callback when connection +** A's transaction is concluded. ^Indirect deadlock is also detected, so +** the system is also considered to be deadlocked if connection B has +** registered for an unlock-notify callback on the conclusion of connection +** C's transaction, where connection C is waiting on connection A. ^Any +** number of levels of indirection are allowed. +** +** The "DROP TABLE" Exception +** +** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call sqlite3_unlock_notify(). There is however, +** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, +** SQLite checks if there are any currently executing SELECT statements +** that belong to the same connection. If there are, SQLITE_LOCKED is +** returned. In this case there is no "blocking connection", so invoking +** sqlite3_unlock_notify() results in the unlock-notify callback being +** invoked immediately. If the application then re-attempts the "DROP TABLE" +** or "DROP INDEX" query, an infinite loop might be the result. +** +** One way around this problem is to check the extended error code returned +** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in +** the special "DROP TABLE/INDEX" case, the extended error code is just +** SQLITE_LOCKED.)^ +*/ +SQLITE_API int sqlite3_unlock_notify( + sqlite3 *pBlocked, /* Waiting connection */ + void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ + void *pNotifyArg /* Argument to pass to xNotify */ +); + + +/* +** CAPI3REF: String Comparison +** +** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications +** and extensions to compare the contents of two buffers containing UTF-8 +** strings in a case-independent fashion, using the same definition of "case +** independence" that SQLite uses internally when comparing identifiers. +*/ +SQLITE_API int sqlite3_stricmp(const char *, const char *); +SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); + +/* +** CAPI3REF: String Globbing +* +** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches +** the glob pattern P, and it returns non-zero if string X does not match +** the glob pattern P. ^The definition of glob pattern matching used in +** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the +** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case +** sensitive. +** +** Note that this routine returns zero on a match and non-zero if the strings +** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +*/ +SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); + +/* +** CAPI3REF: Error Logging Interface +** +** ^The [sqlite3_log()] interface writes a message into the [error log] +** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^If logging is enabled, the zFormat string and subsequent arguments are +** used with [sqlite3_snprintf()] to generate the final output string. +** +** The sqlite3_log() interface is intended for use by extensions such as +** virtual tables, collating functions, and SQL functions. While there is +** nothing to prevent an application from calling sqlite3_log(), doing so +** is considered bad form. +** +** The zFormat string must not be NULL. +** +** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** will not use dynamically allocated memory. The log message is stored in +** a fixed-length buffer on the stack. If the log message is longer than +** a few hundred characters, it will be truncated to the length of the +** buffer. +*/ +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); + +/* +** CAPI3REF: Write-Ahead Log Commit Hook +** +** ^The [sqlite3_wal_hook()] function is used to register a callback that +** will be invoked each time a database connection commits data to a +** [write-ahead log] (i.e. whenever a transaction is committed in +** [journal_mode | journal_mode=WAL mode]). +** +** ^The callback is invoked by SQLite after the commit has taken place and +** the associated write-lock on the database released, so the implementation +** may read, write or [checkpoint] the database as required. +** +** ^The first parameter passed to the callback function when it is invoked +** is a copy of the third parameter passed to sqlite3_wal_hook() when +** registering the callback. ^The second is a copy of the database handle. +** ^The third parameter is the name of the database that was written to - +** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter +** is the number of pages currently in the write-ahead log file, +** including those that were just committed. +** +** The callback function should normally return [SQLITE_OK]. ^If an error +** code is returned, that error will propagate back up through the +** SQLite code base to cause the statement that provoked the callback +** to report an error, though the commit will have still occurred. If the +** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value +** that does not correspond to any valid SQLite error code, the results +** are undefined. +** +** A single database handle may have at most a single write-ahead log callback +** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** previously registered write-ahead log callback. ^Note that the +** [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will +** those overwrite any prior [sqlite3_wal_hook()] settings. +*/ +SQLITE_API void *sqlite3_wal_hook( + sqlite3*, + int(*)(void *,sqlite3*,const char*,int), + void* +); + +/* +** CAPI3REF: Configure an auto-checkpoint +** +** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [sqlite3_wal_hook()] that causes any database on [database connection] D +** to automatically [checkpoint] +** after committing a transaction if there are N or +** more frames in the [write-ahead log] file. ^Passing zero or +** a negative value as the nFrame parameter disables automatic +** checkpoints entirely. +** +** ^The callback registered by this function replaces any existing callback +** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback +** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** configured by this function. +** +** ^The [wal_autocheckpoint pragma] can be used to invoke this interface +** from SQL. +** +** ^Every new [database connection] defaults to having the auto-checkpoint +** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] +** pages. The use of this interface +** is only necessary if the default setting is found to be suboptimal +** for a particular application. +*/ +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); + +/* +** CAPI3REF: Checkpoint a database +** +** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X +** on [database connection] D to be [checkpointed]. ^If X is NULL or an +** empty string, then a checkpoint is run on all databases of +** connection D. ^If the database connection D is not in +** [WAL | write-ahead log mode] then this interface is a harmless no-op. +** +** ^The [wal_checkpoint pragma] can be used to invoke this interface +** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] can be used to cause this interface to be +** run whenever the WAL reaches a certain size threshold. +** +** See also: [sqlite3_wal_checkpoint_v2()] +*/ +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Checkpoint a database +** +** Run a checkpoint operation on WAL database zDb attached to database +** handle db. The specific operation is determined by the value of the +** eMode parameter: +** +**
+**
SQLITE_CHECKPOINT_PASSIVE
+** Checkpoint as many frames as possible without waiting for any database +** readers or writers to finish. Sync the db file if all frames in the log +** are checkpointed. This mode is the same as calling +** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked. +** +**
SQLITE_CHECKPOINT_FULL
+** This mode blocks (calls the busy-handler callback) until there is no +** database writer and all readers are reading from the most recent database +** snapshot. It then checkpoints all frames in the log file and syncs the +** database file. This call blocks database writers while it is running, +** but not database readers. +** +**
SQLITE_CHECKPOINT_RESTART
+** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after +** checkpointing the log file it blocks (calls the busy-handler callback) +** until all readers are reading from the database file only. This ensures +** that the next client to write to the database file restarts the log file +** from the beginning. This call blocks database writers while it is running, +** but not database readers. +**
+** +** If pnLog is not NULL, then *pnLog is set to the total number of frames in +** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to +** the total number of checkpointed frames (including any that were already +** checkpointed when this function is called). *pnLog and *pnCkpt may be +** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK. +** If no values are available because of an error, they are both set to -1 +** before returning to communicate this to the caller. +** +** All calls obtain an exclusive "checkpoint" lock on the database file. If +** any other process is running a checkpoint operation at the same time, the +** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a +** busy-handler configured, it will not be invoked in this case. +** +** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive +** "writer" lock on the database file. If the writer lock cannot be obtained +** immediately, and a busy-handler is configured, it is invoked and the writer +** lock retried until either the busy-handler returns 0 or the lock is +** successfully obtained. The busy-handler is also invoked while waiting for +** database readers as described above. If the busy-handler returns 0 before +** the writer lock is obtained or while waiting for database readers, the +** checkpoint operation proceeds from that point in the same way as +** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible +** without blocking any further. SQLITE_BUSY is returned in this case. +** +** If parameter zDb is NULL or points to a zero length string, then the +** specified operation is attempted on all WAL databases. In this case the +** values written to output parameters *pnLog and *pnCkpt are undefined. If +** an SQLITE_BUSY error is encountered when processing one or more of the +** attached WAL databases, the operation is still attempted on any remaining +** attached databases and SQLITE_BUSY is returned to the caller. If any other +** error occurs while processing an attached database, processing is abandoned +** and the error code returned to the caller immediately. If no error +** (SQLITE_BUSY or otherwise) is encountered while processing the attached +** databases, SQLITE_OK is returned. +** +** If database zDb is the name of an attached database that is not in WAL +** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If +** zDb is not NULL (or a zero length string) and is not the name of any +** attached database, SQLITE_ERROR is returned to the caller. +*/ +SQLITE_API int sqlite3_wal_checkpoint_v2( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + int *pnLog, /* OUT: Size of WAL log in frames */ + int *pnCkpt /* OUT: Total number of frames checkpointed */ +); + +/* +** CAPI3REF: Checkpoint operation parameters +** +** These constants can be used as the 3rd parameter to +** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()] +** documentation for additional information about the meaning and use of +** each of these values. +*/ +#define SQLITE_CHECKPOINT_PASSIVE 0 +#define SQLITE_CHECKPOINT_FULL 1 +#define SQLITE_CHECKPOINT_RESTART 2 + +/* +** CAPI3REF: Virtual Table Interface Configuration +** +** This function may be called by either the [xConnect] or [xCreate] method +** of a [virtual table] implementation to configure +** various facets of the virtual table interface. +** +** If this interface is invoked outside the context of an xConnect or +** xCreate virtual table method then the behavior is undefined. +** +** At present, there is only one option that may be configured using +** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options +** may be added in the future. +*/ +SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Virtual Table Configuration Options +** +** These macros define the various options to the +** [sqlite3_vtab_config()] interface that [virtual table] implementations +** can use to customize and optimize their behavior. +** +**
+**
SQLITE_VTAB_CONSTRAINT_SUPPORT +**
Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, +** where X is an integer. If X is zero, then the [virtual table] whose +** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not +** support constraints. In this configuration (which is the default) if +** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire +** statement is rolled back as if [ON CONFLICT | OR ABORT] had been +** specified as part of the users SQL statement, regardless of the actual +** ON CONFLICT mode specified. +** +** If X is non-zero, then the virtual table implementation guarantees +** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before +** any modifications to internal or persistent data structures have been made. +** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite +** is able to roll back a statement or database transaction, and abandon +** or continue processing the current SQL statement as appropriate. +** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns +** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode +** had been ABORT. +** +** Virtual table implementations that are required to handle OR REPLACE +** must do so within the [xUpdate] method. If a call to the +** [sqlite3_vtab_on_conflict()] function indicates that the current ON +** CONFLICT policy is REPLACE, the virtual table implementation should +** silently replace the appropriate rows within the xUpdate callback and +** return SQLITE_OK. Or, if this is not possible, it may return +** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT +** constraint handling. +**
+*/ +#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 + +/* +** CAPI3REF: Determine The Virtual Table Conflict Policy +** +** This function may only be called from within a call to the [xUpdate] method +** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The +** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], +** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode +** of the SQL statement that triggered the call to the [xUpdate] method of the +** [virtual table]. +*/ +SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); + +/* +** CAPI3REF: Conflict resolution modes +** +** These constants are returned by [sqlite3_vtab_on_conflict()] to +** inform a [virtual table] implementation what the [ON CONFLICT] mode +** is for the SQL statement being evaluated. +** +** Note that the [SQLITE_IGNORE] constant is also used as a potential +** return value from the [sqlite3_set_authorizer()] callback and that +** [SQLITE_ABORT] is also a [result code]. +*/ +#define SQLITE_ROLLBACK 1 +/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ +#define SQLITE_FAIL 3 +/* #define SQLITE_ABORT 4 // Also an error code */ +#define SQLITE_REPLACE 5 + + + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#ifdef __cplusplus +} /* End of the 'extern "C"' block */ +#endif +#endif /* _SQLITE3_H_ */ + +/* +** 2010 August 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ + +#ifndef _SQLITE3RTREE_H_ +#define _SQLITE3RTREE_H_ + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; + +/* +** Register a geometry callback named zGeom that can be used as part of an +** R-Tree geometry query as follows: +** +** SELECT ... FROM WHERE MATCH $zGeom(... params ...) +*/ +SQLITE_API int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, +#ifdef SQLITE_RTREE_INT_ONLY + int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes), +#else + int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes), +#endif + void *pContext +); + + +/* +** A pointer to a structure of the following type is passed as the first +** argument to callbacks registered using rtree_geometry_callback(). +*/ +struct sqlite3_rtree_geometry { + void *pContext; /* Copy of pContext passed to s_r_g_c() */ + int nParam; /* Size of array aParam[] */ + double *aParam; /* Parameters passed to SQL geom function */ + void *pUser; /* Callback implementation user data */ + void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ +}; + + +#ifdef __cplusplus +} /* end of the 'extern "C"' block */ +#endif + +#endif /* ifndef _SQLITE3RTREE_H_ */ + diff --git a/components/external/SQLite-3.8.1/SQLiteLib/sqlite3ext.h b/components/external/SQLite-3.8.1/SQLiteLib/sqlite3ext.h new file mode 100644 index 0000000000000000000000000000000000000000..ecf93f62f6cd9c3bf5044e781556e06fe011ec0e --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/sqlite3ext.h @@ -0,0 +1,487 @@ +/* +** 2006 June 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the SQLite interface for use by +** shared libraries that want to be imported as extensions into +** an SQLite instance. Shared libraries that intend to be loaded +** as extensions by SQLite should #include this file instead of +** sqlite3.h. +*/ +#ifndef _SQLITE3EXT_H_ +#define _SQLITE3EXT_H_ +#include "sqlite3.h" + +typedef struct sqlite3_api_routines sqlite3_api_routines; + +/* +** The following structure holds pointers to all of the SQLite API +** routines. +** +** WARNING: In order to maintain backwards compatibility, add new +** interfaces to the end of this structure only. If you insert new +** interfaces in the middle of this structure, then older different +** versions of SQLite will not be able to load each others' shared +** libraries! +*/ +struct sqlite3_api_routines { + void * (*aggregate_context)(sqlite3_context*,int nBytes); + int (*aggregate_count)(sqlite3_context*); + int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); + int (*bind_double)(sqlite3_stmt*,int,double); + int (*bind_int)(sqlite3_stmt*,int,int); + int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); + int (*bind_null)(sqlite3_stmt*,int); + int (*bind_parameter_count)(sqlite3_stmt*); + int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); + const char * (*bind_parameter_name)(sqlite3_stmt*,int); + int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); + int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); + int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); + int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); + int (*busy_timeout)(sqlite3*,int ms); + int (*changes)(sqlite3*); + int (*close)(sqlite3*); + int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, + int eTextRep,const char*)); + int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, + int eTextRep,const void*)); + const void * (*column_blob)(sqlite3_stmt*,int iCol); + int (*column_bytes)(sqlite3_stmt*,int iCol); + int (*column_bytes16)(sqlite3_stmt*,int iCol); + int (*column_count)(sqlite3_stmt*pStmt); + const char * (*column_database_name)(sqlite3_stmt*,int); + const void * (*column_database_name16)(sqlite3_stmt*,int); + const char * (*column_decltype)(sqlite3_stmt*,int i); + const void * (*column_decltype16)(sqlite3_stmt*,int); + double (*column_double)(sqlite3_stmt*,int iCol); + int (*column_int)(sqlite3_stmt*,int iCol); + sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); + const char * (*column_name)(sqlite3_stmt*,int); + const void * (*column_name16)(sqlite3_stmt*,int); + const char * (*column_origin_name)(sqlite3_stmt*,int); + const void * (*column_origin_name16)(sqlite3_stmt*,int); + const char * (*column_table_name)(sqlite3_stmt*,int); + const void * (*column_table_name16)(sqlite3_stmt*,int); + const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); + const void * (*column_text16)(sqlite3_stmt*,int iCol); + int (*column_type)(sqlite3_stmt*,int iCol); + sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); + void * (*commit_hook)(sqlite3*,int(*)(void*),void*); + int (*complete)(const char*sql); + int (*complete16)(const void*sql); + int (*create_collation)(sqlite3*,const char*,int,void*, + int(*)(void*,int,const void*,int,const void*)); + int (*create_collation16)(sqlite3*,const void*,int,void*, + int(*)(void*,int,const void*,int,const void*)); + int (*create_function)(sqlite3*,const char*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*)); + int (*create_function16)(sqlite3*,const void*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*)); + int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); + int (*data_count)(sqlite3_stmt*pStmt); + sqlite3 * (*db_handle)(sqlite3_stmt*); + int (*declare_vtab)(sqlite3*,const char*); + int (*enable_shared_cache)(int); + int (*errcode)(sqlite3*db); + const char * (*errmsg)(sqlite3*); + const void * (*errmsg16)(sqlite3*); + int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); + int (*expired)(sqlite3_stmt*); + int (*finalize)(sqlite3_stmt*pStmt); + void (*free)(void*); + void (*free_table)(char**result); + int (*get_autocommit)(sqlite3*); + void * (*get_auxdata)(sqlite3_context*,int); + int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); + int (*global_recover)(void); + void (*interruptx)(sqlite3*); + sqlite_int64 (*last_insert_rowid)(sqlite3*); + const char * (*libversion)(void); + int (*libversion_number)(void); + void *(*malloc)(int); + char * (*mprintf)(const char*,...); + int (*open)(const char*,sqlite3**); + int (*open16)(const void*,sqlite3**); + int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); + void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); + void *(*realloc)(void*,int); + int (*reset)(sqlite3_stmt*pStmt); + void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_double)(sqlite3_context*,double); + void (*result_error)(sqlite3_context*,const char*,int); + void (*result_error16)(sqlite3_context*,const void*,int); + void (*result_int)(sqlite3_context*,int); + void (*result_int64)(sqlite3_context*,sqlite_int64); + void (*result_null)(sqlite3_context*); + void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); + void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_value)(sqlite3_context*,sqlite3_value*); + void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); + int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, + const char*,const char*),void*); + void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); + char * (*snprintf)(int,char*,const char*,...); + int (*step)(sqlite3_stmt*); + int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, + char const**,char const**,int*,int*,int*); + void (*thread_cleanup)(void); + int (*total_changes)(sqlite3*); + void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); + int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); + void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, + sqlite_int64),void*); + void * (*user_data)(sqlite3_context*); + const void * (*value_blob)(sqlite3_value*); + int (*value_bytes)(sqlite3_value*); + int (*value_bytes16)(sqlite3_value*); + double (*value_double)(sqlite3_value*); + int (*value_int)(sqlite3_value*); + sqlite_int64 (*value_int64)(sqlite3_value*); + int (*value_numeric_type)(sqlite3_value*); + const unsigned char * (*value_text)(sqlite3_value*); + const void * (*value_text16)(sqlite3_value*); + const void * (*value_text16be)(sqlite3_value*); + const void * (*value_text16le)(sqlite3_value*); + int (*value_type)(sqlite3_value*); + char *(*vmprintf)(const char*,va_list); + /* Added ??? */ + int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); + /* Added by 3.3.13 */ + int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + int (*clear_bindings)(sqlite3_stmt*); + /* Added by 3.4.1 */ + int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, + void (*xDestroy)(void *)); + /* Added by 3.5.0 */ + int (*bind_zeroblob)(sqlite3_stmt*,int,int); + int (*blob_bytes)(sqlite3_blob*); + int (*blob_close)(sqlite3_blob*); + int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, + int,sqlite3_blob**); + int (*blob_read)(sqlite3_blob*,void*,int,int); + int (*blob_write)(sqlite3_blob*,const void*,int,int); + int (*create_collation_v2)(sqlite3*,const char*,int,void*, + int(*)(void*,int,const void*,int,const void*), + void(*)(void*)); + int (*file_control)(sqlite3*,const char*,int,void*); + sqlite3_int64 (*memory_highwater)(int); + sqlite3_int64 (*memory_used)(void); + sqlite3_mutex *(*mutex_alloc)(int); + void (*mutex_enter)(sqlite3_mutex*); + void (*mutex_free)(sqlite3_mutex*); + void (*mutex_leave)(sqlite3_mutex*); + int (*mutex_try)(sqlite3_mutex*); + int (*open_v2)(const char*,sqlite3**,int,const char*); + int (*release_memory)(int); + void (*result_error_nomem)(sqlite3_context*); + void (*result_error_toobig)(sqlite3_context*); + int (*sleep)(int); + void (*soft_heap_limit)(int); + sqlite3_vfs *(*vfs_find)(const char*); + int (*vfs_register)(sqlite3_vfs*,int); + int (*vfs_unregister)(sqlite3_vfs*); + int (*xthreadsafe)(void); + void (*result_zeroblob)(sqlite3_context*,int); + void (*result_error_code)(sqlite3_context*,int); + int (*test_control)(int, ...); + void (*randomness)(int,void*); + sqlite3 *(*context_db_handle)(sqlite3_context*); + int (*extended_result_codes)(sqlite3*,int); + int (*limit)(sqlite3*,int,int); + sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); + const char *(*sql)(sqlite3_stmt*); + int (*status)(int,int*,int*,int); + int (*backup_finish)(sqlite3_backup*); + sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); + int (*backup_pagecount)(sqlite3_backup*); + int (*backup_remaining)(sqlite3_backup*); + int (*backup_step)(sqlite3_backup*,int); + const char *(*compileoption_get)(int); + int (*compileoption_used)(const char*); + int (*create_function_v2)(sqlite3*,const char*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*)); + int (*db_config)(sqlite3*,int,...); + sqlite3_mutex *(*db_mutex)(sqlite3*); + int (*db_status)(sqlite3*,int,int*,int*,int); + int (*extended_errcode)(sqlite3*); + void (*log)(int,const char*,...); + sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); + const char *(*sourceid)(void); + int (*stmt_status)(sqlite3_stmt*,int,int); + int (*strnicmp)(const char*,const char*,int); + int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); + int (*wal_autocheckpoint)(sqlite3*,int); + int (*wal_checkpoint)(sqlite3*,const char*); + void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); + int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); + int (*vtab_config)(sqlite3*,int op,...); + int (*vtab_on_conflict)(sqlite3*); + /* Version 3.7.16 and later */ + int (*close_v2)(sqlite3*); + const char *(*db_filename)(sqlite3*,const char*); + int (*db_readonly)(sqlite3*,const char*); + int (*db_release_memory)(sqlite3*); + const char *(*errstr)(int); + int (*stmt_busy)(sqlite3_stmt*); + int (*stmt_readonly)(sqlite3_stmt*); + int (*stricmp)(const char*,const char*); + int (*uri_boolean)(const char*,const char*,int); + sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); + const char *(*uri_parameter)(const char*,const char*); + char *(*vsnprintf)(int,char*,const char*,va_list); + int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); +}; + +/* +** The following macros redefine the API routines so that they are +** redirected throught the global sqlite3_api structure. +** +** This header file is also used by the loadext.c source file +** (part of the main SQLite library - not an extension) so that +** it can get access to the sqlite3_api_routines structure +** definition. But the main library does not want to redefine +** the API. So the redefinition macros are only valid if the +** SQLITE_CORE macros is undefined. +*/ +#ifndef SQLITE_CORE +#define sqlite3_aggregate_context sqlite3_api->aggregate_context +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_aggregate_count sqlite3_api->aggregate_count +#endif +#define sqlite3_bind_blob sqlite3_api->bind_blob +#define sqlite3_bind_double sqlite3_api->bind_double +#define sqlite3_bind_int sqlite3_api->bind_int +#define sqlite3_bind_int64 sqlite3_api->bind_int64 +#define sqlite3_bind_null sqlite3_api->bind_null +#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count +#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index +#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name +#define sqlite3_bind_text sqlite3_api->bind_text +#define sqlite3_bind_text16 sqlite3_api->bind_text16 +#define sqlite3_bind_value sqlite3_api->bind_value +#define sqlite3_busy_handler sqlite3_api->busy_handler +#define sqlite3_busy_timeout sqlite3_api->busy_timeout +#define sqlite3_changes sqlite3_api->changes +#define sqlite3_close sqlite3_api->close +#define sqlite3_collation_needed sqlite3_api->collation_needed +#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 +#define sqlite3_column_blob sqlite3_api->column_blob +#define sqlite3_column_bytes sqlite3_api->column_bytes +#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 +#define sqlite3_column_count sqlite3_api->column_count +#define sqlite3_column_database_name sqlite3_api->column_database_name +#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 +#define sqlite3_column_decltype sqlite3_api->column_decltype +#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 +#define sqlite3_column_double sqlite3_api->column_double +#define sqlite3_column_int sqlite3_api->column_int +#define sqlite3_column_int64 sqlite3_api->column_int64 +#define sqlite3_column_name sqlite3_api->column_name +#define sqlite3_column_name16 sqlite3_api->column_name16 +#define sqlite3_column_origin_name sqlite3_api->column_origin_name +#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 +#define sqlite3_column_table_name sqlite3_api->column_table_name +#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 +#define sqlite3_column_text sqlite3_api->column_text +#define sqlite3_column_text16 sqlite3_api->column_text16 +#define sqlite3_column_type sqlite3_api->column_type +#define sqlite3_column_value sqlite3_api->column_value +#define sqlite3_commit_hook sqlite3_api->commit_hook +#define sqlite3_complete sqlite3_api->complete +#define sqlite3_complete16 sqlite3_api->complete16 +#define sqlite3_create_collation sqlite3_api->create_collation +#define sqlite3_create_collation16 sqlite3_api->create_collation16 +#define sqlite3_create_function sqlite3_api->create_function +#define sqlite3_create_function16 sqlite3_api->create_function16 +#define sqlite3_create_module sqlite3_api->create_module +#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 +#define sqlite3_data_count sqlite3_api->data_count +#define sqlite3_db_handle sqlite3_api->db_handle +#define sqlite3_declare_vtab sqlite3_api->declare_vtab +#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache +#define sqlite3_errcode sqlite3_api->errcode +#define sqlite3_errmsg sqlite3_api->errmsg +#define sqlite3_errmsg16 sqlite3_api->errmsg16 +#define sqlite3_exec sqlite3_api->exec +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_expired sqlite3_api->expired +#endif +#define sqlite3_finalize sqlite3_api->finalize +#define sqlite3_free sqlite3_api->free +#define sqlite3_free_table sqlite3_api->free_table +#define sqlite3_get_autocommit sqlite3_api->get_autocommit +#define sqlite3_get_auxdata sqlite3_api->get_auxdata +#define sqlite3_get_table sqlite3_api->get_table +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_global_recover sqlite3_api->global_recover +#endif +#define sqlite3_interrupt sqlite3_api->interruptx +#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid +#define sqlite3_libversion sqlite3_api->libversion +#define sqlite3_libversion_number sqlite3_api->libversion_number +#define sqlite3_malloc sqlite3_api->malloc +#define sqlite3_mprintf sqlite3_api->mprintf +#define sqlite3_open sqlite3_api->open +#define sqlite3_open16 sqlite3_api->open16 +#define sqlite3_prepare sqlite3_api->prepare +#define sqlite3_prepare16 sqlite3_api->prepare16 +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_profile sqlite3_api->profile +#define sqlite3_progress_handler sqlite3_api->progress_handler +#define sqlite3_realloc sqlite3_api->realloc +#define sqlite3_reset sqlite3_api->reset +#define sqlite3_result_blob sqlite3_api->result_blob +#define sqlite3_result_double sqlite3_api->result_double +#define sqlite3_result_error sqlite3_api->result_error +#define sqlite3_result_error16 sqlite3_api->result_error16 +#define sqlite3_result_int sqlite3_api->result_int +#define sqlite3_result_int64 sqlite3_api->result_int64 +#define sqlite3_result_null sqlite3_api->result_null +#define sqlite3_result_text sqlite3_api->result_text +#define sqlite3_result_text16 sqlite3_api->result_text16 +#define sqlite3_result_text16be sqlite3_api->result_text16be +#define sqlite3_result_text16le sqlite3_api->result_text16le +#define sqlite3_result_value sqlite3_api->result_value +#define sqlite3_rollback_hook sqlite3_api->rollback_hook +#define sqlite3_set_authorizer sqlite3_api->set_authorizer +#define sqlite3_set_auxdata sqlite3_api->set_auxdata +#define sqlite3_snprintf sqlite3_api->snprintf +#define sqlite3_step sqlite3_api->step +#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata +#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup +#define sqlite3_total_changes sqlite3_api->total_changes +#define sqlite3_trace sqlite3_api->trace +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings +#endif +#define sqlite3_update_hook sqlite3_api->update_hook +#define sqlite3_user_data sqlite3_api->user_data +#define sqlite3_value_blob sqlite3_api->value_blob +#define sqlite3_value_bytes sqlite3_api->value_bytes +#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 +#define sqlite3_value_double sqlite3_api->value_double +#define sqlite3_value_int sqlite3_api->value_int +#define sqlite3_value_int64 sqlite3_api->value_int64 +#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type +#define sqlite3_value_text sqlite3_api->value_text +#define sqlite3_value_text16 sqlite3_api->value_text16 +#define sqlite3_value_text16be sqlite3_api->value_text16be +#define sqlite3_value_text16le sqlite3_api->value_text16le +#define sqlite3_value_type sqlite3_api->value_type +#define sqlite3_vmprintf sqlite3_api->vmprintf +#define sqlite3_overload_function sqlite3_api->overload_function +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_clear_bindings sqlite3_api->clear_bindings +#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob +#define sqlite3_blob_bytes sqlite3_api->blob_bytes +#define sqlite3_blob_close sqlite3_api->blob_close +#define sqlite3_blob_open sqlite3_api->blob_open +#define sqlite3_blob_read sqlite3_api->blob_read +#define sqlite3_blob_write sqlite3_api->blob_write +#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 +#define sqlite3_file_control sqlite3_api->file_control +#define sqlite3_memory_highwater sqlite3_api->memory_highwater +#define sqlite3_memory_used sqlite3_api->memory_used +#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc +#define sqlite3_mutex_enter sqlite3_api->mutex_enter +#define sqlite3_mutex_free sqlite3_api->mutex_free +#define sqlite3_mutex_leave sqlite3_api->mutex_leave +#define sqlite3_mutex_try sqlite3_api->mutex_try +#define sqlite3_open_v2 sqlite3_api->open_v2 +#define sqlite3_release_memory sqlite3_api->release_memory +#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem +#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig +#define sqlite3_sleep sqlite3_api->sleep +#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit +#define sqlite3_vfs_find sqlite3_api->vfs_find +#define sqlite3_vfs_register sqlite3_api->vfs_register +#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister +#define sqlite3_threadsafe sqlite3_api->xthreadsafe +#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob +#define sqlite3_result_error_code sqlite3_api->result_error_code +#define sqlite3_test_control sqlite3_api->test_control +#define sqlite3_randomness sqlite3_api->randomness +#define sqlite3_context_db_handle sqlite3_api->context_db_handle +#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes +#define sqlite3_limit sqlite3_api->limit +#define sqlite3_next_stmt sqlite3_api->next_stmt +#define sqlite3_sql sqlite3_api->sql +#define sqlite3_status sqlite3_api->status +#define sqlite3_backup_finish sqlite3_api->backup_finish +#define sqlite3_backup_init sqlite3_api->backup_init +#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount +#define sqlite3_backup_remaining sqlite3_api->backup_remaining +#define sqlite3_backup_step sqlite3_api->backup_step +#define sqlite3_compileoption_get sqlite3_api->compileoption_get +#define sqlite3_compileoption_used sqlite3_api->compileoption_used +#define sqlite3_create_function_v2 sqlite3_api->create_function_v2 +#define sqlite3_db_config sqlite3_api->db_config +#define sqlite3_db_mutex sqlite3_api->db_mutex +#define sqlite3_db_status sqlite3_api->db_status +#define sqlite3_extended_errcode sqlite3_api->extended_errcode +#define sqlite3_log sqlite3_api->log +#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 +#define sqlite3_sourceid sqlite3_api->sourceid +#define sqlite3_stmt_status sqlite3_api->stmt_status +#define sqlite3_strnicmp sqlite3_api->strnicmp +#define sqlite3_unlock_notify sqlite3_api->unlock_notify +#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint +#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint +#define sqlite3_wal_hook sqlite3_api->wal_hook +#define sqlite3_blob_reopen sqlite3_api->blob_reopen +#define sqlite3_vtab_config sqlite3_api->vtab_config +#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict +/* Version 3.7.16 and later */ +#define sqlite3_close_v2 sqlite3_api->close_v2 +#define sqlite3_db_filename sqlite3_api->db_filename +#define sqlite3_db_readonly sqlite3_api->db_readonly +#define sqlite3_db_release_memory sqlite3_api->db_release_memory +#define sqlite3_errstr sqlite3_api->errstr +#define sqlite3_stmt_busy sqlite3_api->stmt_busy +#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly +#define sqlite3_stricmp sqlite3_api->stricmp +#define sqlite3_uri_boolean sqlite3_api->uri_boolean +#define sqlite3_uri_int64 sqlite3_api->uri_int64 +#define sqlite3_uri_parameter sqlite3_api->uri_parameter +#define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf +#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 +#endif /* SQLITE_CORE */ + +#ifndef SQLITE_CORE + /* This case when the file really is being compiled as a loadable + ** extension */ +# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; +# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; +# define SQLITE_EXTENSION_INIT3 \ + extern const sqlite3_api_routines *sqlite3_api; +#else + /* This case when the file is being statically linked into the + ** application */ +# define SQLITE_EXTENSION_INIT1 /*no-op*/ +# define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */ +# define SQLITE_EXTENSION_INIT3 /*no-op*/ +#endif + +#endif /* _SQLITE3EXT_H_ */ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test1.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test1.c new file mode 100644 index 0000000000000000000000000000000000000000..d8a9e52d215059158567c4c5b6015810cb944f34 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test1.c @@ -0,0 +1,6549 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing all sorts of SQLite interfaces. This code +** is not included in the SQLite library. It is used for automated +** testing of the SQLite library. +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" +#include "tcl.h" +#include +#include + +/* +** This is a copy of the first part of the SqliteDb structure in +** tclsqlite.c. We need it here so that the get_sqlite_pointer routine +** can extract the sqlite3* pointer from an existing Tcl SQLite +** connection. +*/ +struct SqliteDb { + sqlite3 *db; +}; + +/* +** Convert text generated by the "%p" conversion format back into +** a pointer. +*/ +static int testHexToInt(int h){ + if( h>='0' && h<='9' ){ + return h - '0'; + }else if( h>='a' && h<='f' ){ + return h - 'a' + 10; + }else{ + assert( h>='A' && h<='F' ); + return h - 'A' + 10; + } +} +void *sqlite3TestTextToPtr(const char *z){ + void *p; + u64 v; + u32 v2; + if( z[0]=='0' && z[1]=='x' ){ + z += 2; + } + v = 0; + while( *z ){ + v = (v<<4) + testHexToInt(*z); + z++; + } + if( sizeof(p)==sizeof(v) ){ + memcpy(&p, &v, sizeof(p)); + }else{ + assert( sizeof(p)==sizeof(v2) ); + v2 = (u32)v; + memcpy(&p, &v2, sizeof(p)); + } + return p; +} + + +/* +** A TCL command that returns the address of the sqlite* pointer +** for an sqlite connection instance. Bad things happen if the +** input is not an sqlite connection. +*/ +static int get_sqlite_pointer( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct SqliteDb *p; + Tcl_CmdInfo cmdInfo; + char zBuf[100]; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SQLITE-CONNECTION"); + return TCL_ERROR; + } + if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){ + Tcl_AppendResult(interp, "command not found: ", + Tcl_GetString(objv[1]), (char*)0); + return TCL_ERROR; + } + p = (struct SqliteDb*)cmdInfo.objClientData; + sprintf(zBuf, "%p", p->db); + if( strncmp(zBuf,"0x",2) ){ + sprintf(zBuf, "0x%p", p->db); + } + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Decode a pointer to an sqlite3 object. +*/ +int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb){ + struct SqliteDb *p; + Tcl_CmdInfo cmdInfo; + if( Tcl_GetCommandInfo(interp, zA, &cmdInfo) ){ + p = (struct SqliteDb*)cmdInfo.objClientData; + *ppDb = p->db; + }else{ + *ppDb = (sqlite3*)sqlite3TestTextToPtr(zA); + } + return TCL_OK; +} + +extern const char *sqlite3ErrName(int); +#define t1ErrorName sqlite3ErrName + +/* +** Convert an sqlite3_stmt* into an sqlite3*. This depends on the +** fact that the sqlite3* is the first field in the Vdbe structure. +*/ +#define StmtToDb(X) sqlite3_db_handle(X) + +/* +** Check a return value to make sure it agrees with the results +** from sqlite3_errcode. +*/ +int sqlite3TestErrCode(Tcl_Interp *interp, sqlite3 *db, int rc){ + if( sqlite3_threadsafe()==0 && rc!=SQLITE_MISUSE && rc!=SQLITE_OK + && sqlite3_errcode(db)!=rc ){ + char zBuf[200]; + int r2 = sqlite3_errcode(db); + sprintf(zBuf, "error code %s (%d) does not match sqlite3_errcode %s (%d)", + t1ErrorName(rc), rc, t1ErrorName(r2), r2); + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, zBuf, 0); + return 1; + } + return 0; +} + +/* +** Decode a pointer to an sqlite3_stmt object. +*/ +static int getStmtPointer( + Tcl_Interp *interp, + const char *zArg, + sqlite3_stmt **ppStmt +){ + *ppStmt = (sqlite3_stmt*)sqlite3TestTextToPtr(zArg); + return TCL_OK; +} + +/* +** Generate a text representation of a pointer that can be understood +** by the getDbPointer and getVmPointer routines above. +** +** The problem is, on some machines (Solaris) if you do a printf with +** "%p" you cannot turn around and do a scanf with the same "%p" and +** get your pointer back. You have to prepend a "0x" before it will +** work. Or at least that is what is reported to me (drh). But this +** behavior varies from machine to machine. The solution used her is +** to test the string right after it is generated to see if it can be +** understood by scanf, and if not, try prepending an "0x" to see if +** that helps. If nothing works, a fatal error is generated. +*/ +int sqlite3TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p){ + sqlite3_snprintf(100, zPtr, "%p", p); + return TCL_OK; +} + +/* +** The callback routine for sqlite3_exec_printf(). +*/ +static int exec_printf_cb(void *pArg, int argc, char **argv, char **name){ + Tcl_DString *str = (Tcl_DString*)pArg; + int i; + + if( Tcl_DStringLength(str)==0 ){ + for(i=0; imutex); + return TCL_OK; +} +static int db_leave( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + sqlite3_mutex_leave(db->mutex); + return TCL_OK; +} + +/* +** Usage: sqlite3_exec DB SQL +** +** Invoke the sqlite3_exec interface using the open database DB +*/ +static int test_exec( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + Tcl_DString str; + int rc; + char *zErr = 0; + char *zSql; + int i, j; + char zBuf[30]; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB SQL", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + Tcl_DStringInit(&str); + zSql = sqlite3_mprintf("%s", argv[2]); + for(i=j=0; zSql[i];){ + if( zSql[i]=='%' ){ + zSql[j++] = (testHexToInt(zSql[i+1])<<4) + testHexToInt(zSql[i+2]); + i += 3; + }else{ + zSql[j++] = zSql[i++]; + } + } + zSql[j] = 0; + rc = sqlite3_exec(db, zSql, exec_printf_cb, &str, &zErr); + sqlite3_free(zSql); + sprintf(zBuf, "%d", rc); + Tcl_AppendElement(interp, zBuf); + Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr); + Tcl_DStringFree(&str); + if( zErr ) sqlite3_free(zErr); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Usage: sqlite3_exec_nr DB SQL +** +** Invoke the sqlite3_exec interface using the open database DB. Discard +** all results +*/ +static int test_exec_nr( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + int rc; + char *zErr = 0; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB SQL", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_exec(db, argv[2], 0, 0, &zErr); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_z_test SEPARATOR ARG0 ARG1 ... +** +** Test the %z format of sqlite_mprintf(). Use multiple mprintf() calls to +** concatenate arg0 through argn using separator as the separator. +** Return the result. +*/ +static int test_mprintf_z( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + char *zResult = 0; + int i; + + for(i=2; isizeof(zStr) ) n = sizeof(zStr); + sqlite3_snprintf(sizeof(zStr), zStr, "abcdefghijklmnopqrstuvwxyz"); + sqlite3_snprintf(n, zStr, zFormat, a1); + Tcl_AppendResult(interp, zStr, 0); + return TCL_OK; +} + +#ifndef SQLITE_OMIT_GET_TABLE + +/* +** Usage: sqlite3_get_table_printf DB FORMAT STRING ?--no-counts? +** +** Invoke the sqlite3_get_table_printf() interface using the open database +** DB. The SQL is the string FORMAT. The format string should contain +** one %s or %q. STRING is the value inserted into %s or %q. +*/ +static int test_get_table_printf( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + Tcl_DString str; + int rc; + char *zErr = 0; + int nRow, nCol; + char **aResult; + int i; + char zBuf[30]; + char *zSql; + int resCount = -1; + if( argc==5 ){ + if( Tcl_GetInt(interp, argv[4], &resCount) ) return TCL_ERROR; + } + if( argc!=4 && argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB FORMAT STRING ?COUNT?", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + Tcl_DStringInit(&str); + zSql = sqlite3_mprintf(argv[2],argv[3]); + if( argc==5 ){ + rc = sqlite3_get_table(db, zSql, &aResult, 0, 0, &zErr); + }else{ + rc = sqlite3_get_table(db, zSql, &aResult, &nRow, &nCol, &zErr); + resCount = (nRow+1)*nCol; + } + sqlite3_free(zSql); + sprintf(zBuf, "%d", rc); + Tcl_AppendElement(interp, zBuf); + if( rc==SQLITE_OK ){ + if( argc==4 ){ + sprintf(zBuf, "%d", nRow); + Tcl_AppendElement(interp, zBuf); + sprintf(zBuf, "%d", nCol); + Tcl_AppendElement(interp, zBuf); + } + for(i=0; inUsed + n + 2 > p->nAlloc ){ + char *zNew; + p->nAlloc = p->nAlloc*2 + n + 200; + zNew = sqlite3_realloc(p->z, p->nAlloc); + if( zNew==0 ){ + sqlite3_free(p->z); + memset(p, 0, sizeof(*p)); + return; + } + p->z = zNew; + } + if( divider && p->nUsed>0 ){ + p->z[p->nUsed++] = divider; + } + memcpy(&p->z[p->nUsed], z, n+1); + p->nUsed += n; +} + +/* +** Invoked for each callback from sqlite3ExecFunc +*/ +static int execFuncCallback(void *pData, int argc, char **argv, char **NotUsed){ + struct dstr *p = (struct dstr*)pData; + int i; + for(i=0; imutex); + pVal = sqlite3ValueNew(db); + sqlite3ValueSetStr(pVal, -1, "x_sqlite_exec", SQLITE_UTF8, SQLITE_STATIC); + zUtf16 = sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); + if( db->mallocFailed ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_create_function16(db, zUtf16, + 1, SQLITE_UTF16, db, sqlite3ExecFunc, 0, 0); + } + sqlite3ValueFree(pVal); + sqlite3_mutex_leave(db->mutex); + } +#endif + + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + +/* +** Routines to implement the x_count() aggregate function. +** +** x_count() counts the number of non-null arguments. But there are +** some twists for testing purposes. +** +** If the argument to x_count() is 40 then a UTF-8 error is reported +** on the step function. If x_count(41) is seen, then a UTF-16 error +** is reported on the step function. If the total count is 42, then +** a UTF-8 error is reported on the finalize function. +*/ +typedef struct t1CountCtx t1CountCtx; +struct t1CountCtx { + int n; +}; +static void t1CountStep( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + t1CountCtx *p; + p = sqlite3_aggregate_context(context, sizeof(*p)); + if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0]) ) && p ){ + p->n++; + } + if( argc>0 ){ + int v = sqlite3_value_int(argv[0]); + if( v==40 ){ + sqlite3_result_error(context, "value of 40 handed to x_count", -1); +#ifndef SQLITE_OMIT_UTF16 + }else if( v==41 ){ + const char zUtf16ErrMsg[] = { 0, 0x61, 0, 0x62, 0, 0x63, 0, 0, 0}; + sqlite3_result_error16(context, &zUtf16ErrMsg[1-SQLITE_BIGENDIAN], -1); +#endif + } + } +} +static void t1CountFinalize(sqlite3_context *context){ + t1CountCtx *p; + p = sqlite3_aggregate_context(context, sizeof(*p)); + if( p ){ + if( p->n==42 ){ + sqlite3_result_error(context, "x_count totals to 42", -1); + }else{ + sqlite3_result_int(context, p ? p->n : 0); + } + } +} + +#ifndef SQLITE_OMIT_DEPRECATED +static void legacyCountStep( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + /* no-op */ +} + +static void legacyCountFinalize(sqlite3_context *context){ + sqlite3_result_int(context, sqlite3_aggregate_count(context)); +} +#endif + +/* +** Usage: sqlite3_create_aggregate DB +** +** Call the sqlite3_create_function API on the given database in order +** to create a function named "x_count". This function is similar +** to the built-in count() function, with a few special quirks +** for testing the sqlite3_result_error() APIs. +** +** The original motivation for this routine was to be able to call the +** sqlite3_create_aggregate function while a query is in progress in order +** to test the SQLITE_MISUSE detection logic. See misuse.test. +** +** This routine was later extended to test the use of sqlite3_result_error() +** within aggregate functions. +** +** Later: It is now also extended to register the aggregate function +** "legacy_count()" with the supplied database handle. This is used +** to test the deprecated sqlite3_aggregate_count() API. +*/ +static int test_create_aggregate( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FILENAME\"", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_create_function(db, "x_count", 0, SQLITE_UTF8, 0, 0, + t1CountStep,t1CountFinalize); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "x_count", 1, SQLITE_UTF8, 0, 0, + t1CountStep,t1CountFinalize); + } +#ifndef SQLITE_OMIT_DEPRECATED + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "legacy_count", 0, SQLITE_ANY, 0, 0, + legacyCountStep, legacyCountFinalize + ); + } +#endif + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + + +/* +** Usage: printf TEXT +** +** Send output to printf. Use this rather than puts to merge the output +** in the correct sequence with debugging printfs inserted into C code. +** Puts uses a separate buffer and debugging statements will be out of +** sequence if it is used. +*/ +static int test_printf( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " TEXT\"", 0); + return TCL_ERROR; + } + printf("%s\n", argv[1]); + return TCL_OK; +} + + + +/* +** Usage: sqlite3_mprintf_int FORMAT INTEGER INTEGER INTEGER +** +** Call mprintf with three integer arguments +*/ +static int sqlite3_mprintf_int( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int a[3], i; + char *z; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT INT\"", 0); + return TCL_ERROR; + } + for(i=2; i<5; i++){ + if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR; + } + z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_int64 FORMAT INTEGER INTEGER INTEGER +** +** Call mprintf with three 64-bit integer arguments +*/ +static int sqlite3_mprintf_int64( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int i; + sqlite_int64 a[3]; + char *z; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT INT\"", 0); + return TCL_ERROR; + } + for(i=2; i<5; i++){ + if( sqlite3Atoi64(argv[i], &a[i-2], 1000000, SQLITE_UTF8) ){ + Tcl_AppendResult(interp, "argument is not a valid 64-bit integer", 0); + return TCL_ERROR; + } + } + z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_long FORMAT INTEGER INTEGER INTEGER +** +** Call mprintf with three long integer arguments. This might be the +** same as sqlite3_mprintf_int or sqlite3_mprintf_int64, depending on +** platform. +*/ +static int sqlite3_mprintf_long( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int i; + long int a[3]; + int b[3]; + char *z; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT INT\"", 0); + return TCL_ERROR; + } + for(i=2; i<5; i++){ + if( Tcl_GetInt(interp, argv[i], &b[i-2]) ) return TCL_ERROR; + a[i-2] = (long int)b[i-2]; + a[i-2] &= (((u64)1)<<(sizeof(int)*8))-1; + } + z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_str FORMAT INTEGER INTEGER STRING +** +** Call mprintf with two integer arguments and one string argument +*/ +static int sqlite3_mprintf_str( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int a[3], i; + char *z; + if( argc<4 || argc>5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT ?STRING?\"", 0); + return TCL_ERROR; + } + for(i=2; i<4; i++){ + if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR; + } + z = sqlite3_mprintf(argv[1], a[0], a[1], argc>4 ? argv[4] : NULL); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_snprintf_str INTEGER FORMAT INTEGER INTEGER STRING +** +** Call mprintf with two integer arguments and one string argument +*/ +static int sqlite3_snprintf_str( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int a[3], i; + int n; + char *z; + if( argc<5 || argc>6 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " INT FORMAT INT INT ?STRING?\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[1], &n) ) return TCL_ERROR; + if( n<0 ){ + Tcl_AppendResult(interp, "N must be non-negative", 0); + return TCL_ERROR; + } + for(i=3; i<5; i++){ + if( Tcl_GetInt(interp, argv[i], &a[i-3]) ) return TCL_ERROR; + } + z = sqlite3_malloc( n+1 ); + sqlite3_snprintf(n, z, argv[2], a[0], a[1], argc>4 ? argv[5] : NULL); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_double FORMAT INTEGER INTEGER DOUBLE +** +** Call mprintf with two integer arguments and one double argument +*/ +static int sqlite3_mprintf_double( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int a[3], i; + double r; + char *z; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT DOUBLE\"", 0); + return TCL_ERROR; + } + for(i=2; i<4; i++){ + if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR; + } + if( Tcl_GetDouble(interp, argv[4], &r) ) return TCL_ERROR; + z = sqlite3_mprintf(argv[1], a[0], a[1], r); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_scaled FORMAT DOUBLE DOUBLE +** +** Call mprintf with a single double argument which is the product of the +** two arguments given above. This is used to generate overflow and underflow +** doubles to test that they are converted properly. +*/ +static int sqlite3_mprintf_scaled( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int i; + double r[2]; + char *z; + if( argc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT DOUBLE DOUBLE\"", 0); + return TCL_ERROR; + } + for(i=2; i<4; i++){ + if( Tcl_GetDouble(interp, argv[i], &r[i-2]) ) return TCL_ERROR; + } + z = sqlite3_mprintf(argv[1], r[0]*r[1]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_stronly FORMAT STRING +** +** Call mprintf with a single double argument which is the product of the +** two arguments given above. This is used to generate overflow and underflow +** doubles to test that they are converted properly. +*/ +static int sqlite3_mprintf_stronly( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + char *z; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT STRING\"", 0); + return TCL_ERROR; + } + z = sqlite3_mprintf(argv[1], argv[2]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_hexdouble FORMAT HEX +** +** Call mprintf with a single double argument which is derived from the +** hexadecimal encoding of an IEEE double. +*/ +static int sqlite3_mprintf_hexdouble( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + char *z; + double r; + unsigned int x1, x2; + sqlite_uint64 d; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT STRING\"", 0); + return TCL_ERROR; + } + if( sscanf(argv[2], "%08x%08x", &x2, &x1)!=2 ){ + Tcl_AppendResult(interp, "2nd argument should be 16-characters of hex", 0); + return TCL_ERROR; + } + d = x2; + d = (d<<32) + x1; + memcpy(&r, &d, sizeof(r)); + z = sqlite3_mprintf(argv[1], r); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_enable_shared_cache ?BOOLEAN? +** +*/ +#if !defined(SQLITE_OMIT_SHARED_CACHE) +static int test_enable_shared( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int rc; + int enable; + int ret = 0; + + if( objc!=2 && objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?BOOLEAN?"); + return TCL_ERROR; + } + ret = sqlite3GlobalConfig.sharedCacheEnabled; + + if( objc==2 ){ + if( Tcl_GetBooleanFromObj(interp, objv[1], &enable) ){ + return TCL_ERROR; + } + rc = sqlite3_enable_shared_cache(enable); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3ErrStr(rc), TCL_STATIC); + return TCL_ERROR; + } + } + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(ret)); + return TCL_OK; +} +#endif + + + +/* +** Usage: sqlite3_extended_result_codes DB BOOLEAN +** +*/ +static int test_extended_result_codes( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int enable; + sqlite3 *db; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( Tcl_GetBooleanFromObj(interp, objv[2], &enable) ) return TCL_ERROR; + sqlite3_extended_result_codes(db, enable); + return TCL_OK; +} + +/* +** Usage: sqlite3_libversion_number +** +*/ +static int test_libversion_number( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_libversion_number())); + return TCL_OK; +} + +/* +** Usage: sqlite3_table_column_metadata DB dbname tblname colname +** +*/ +#ifdef SQLITE_ENABLE_COLUMN_METADATA +static int test_table_column_metadata( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + const char *zDb; + const char *zTbl; + const char *zCol; + int rc; + Tcl_Obj *pRet; + + const char *zDatatype; + const char *zCollseq; + int notnull; + int primarykey; + int autoincrement; + + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB dbname tblname colname"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zDb = Tcl_GetString(objv[2]); + zTbl = Tcl_GetString(objv[3]); + zCol = Tcl_GetString(objv[4]); + + if( strlen(zDb)==0 ) zDb = 0; + + rc = sqlite3_table_column_metadata(db, zDb, zTbl, zCol, + &zDatatype, &zCollseq, ¬null, &primarykey, &autoincrement); + + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3_errmsg(db), 0); + return TCL_ERROR; + } + + pRet = Tcl_NewObj(); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zDatatype, -1)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zCollseq, -1)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(notnull)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(primarykey)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(autoincrement)); + Tcl_SetObjResult(interp, pRet); + + return TCL_OK; +} +#endif + +#ifndef SQLITE_OMIT_INCRBLOB + +static int blobHandleFromObj( + Tcl_Interp *interp, + Tcl_Obj *pObj, + sqlite3_blob **ppBlob +){ + char *z; + int n; + + z = Tcl_GetStringFromObj(pObj, &n); + if( n==0 ){ + *ppBlob = 0; + }else{ + int notUsed; + Tcl_Channel channel; + ClientData instanceData; + + channel = Tcl_GetChannel(interp, z, ¬Used); + if( !channel ) return TCL_ERROR; + + Tcl_Flush(channel); + Tcl_Seek(channel, 0, SEEK_SET); + + instanceData = Tcl_GetChannelInstanceData(channel); + *ppBlob = *((sqlite3_blob **)instanceData); + } + + return TCL_OK; +} + +/* +** sqlite3_blob_bytes CHANNEL +*/ +static int test_blob_bytes( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_blob *pBlob; + int nByte; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + nByte = sqlite3_blob_bytes(pBlob); + Tcl_SetObjResult(interp, Tcl_NewIntObj(nByte)); + + return TCL_OK; +} + +/* +** sqlite3_blob_close CHANNEL +*/ +static int test_blob_close( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_blob *pBlob; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + sqlite3_blob_close(pBlob); + + return TCL_OK; +} + +/* +** sqlite3_blob_read CHANNEL OFFSET N +** +** This command is used to test the sqlite3_blob_read() in ways that +** the Tcl channel interface does not. The first argument should +** be the name of a valid channel created by the [incrblob] method +** of a database handle. This function calls sqlite3_blob_read() +** to read N bytes from offset OFFSET from the underlying SQLite +** blob handle. +** +** On success, a byte-array object containing the read data is +** returned. On failure, the interpreter result is set to the +** text representation of the returned error code (i.e. "SQLITE_NOMEM") +** and a Tcl exception is thrown. +*/ +static int test_blob_read( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_blob *pBlob; + int nByte; + int iOffset; + unsigned char *zBuf = 0; + int rc; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL OFFSET N"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iOffset) + || TCL_OK!=Tcl_GetIntFromObj(interp, objv[3], &nByte) + ){ + return TCL_ERROR; + } + + if( nByte>0 ){ + zBuf = (unsigned char *)Tcl_Alloc(nByte); + } + rc = sqlite3_blob_read(pBlob, zBuf, nByte, iOffset); + if( rc==SQLITE_OK ){ + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(zBuf, nByte)); + }else{ + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + } + Tcl_Free((char *)zBuf); + + return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR); +} + +/* +** sqlite3_blob_write CHANNEL OFFSET DATA ?NDATA? +** +** This command is used to test the sqlite3_blob_write() in ways that +** the Tcl channel interface does not. The first argument should +** be the name of a valid channel created by the [incrblob] method +** of a database handle. This function calls sqlite3_blob_write() +** to write the DATA byte-array to the underlying SQLite blob handle. +** at offset OFFSET. +** +** On success, an empty string is returned. On failure, the interpreter +** result is set to the text representation of the returned error code +** (i.e. "SQLITE_NOMEM") and a Tcl exception is thrown. +*/ +static int test_blob_write( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_blob *pBlob; + int iOffset; + int rc; + + unsigned char *zBuf; + int nBuf; + + if( objc!=4 && objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL OFFSET DATA ?NDATA?"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iOffset) ){ + return TCL_ERROR; + } + + zBuf = Tcl_GetByteArrayFromObj(objv[3], &nBuf); + if( objc==5 && Tcl_GetIntFromObj(interp, objv[4], &nBuf) ){ + return TCL_ERROR; + } + rc = sqlite3_blob_write(pBlob, zBuf, nBuf, iOffset); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + } + + return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR); +} + +static int test_blob_reopen( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_WideInt iRowid; + sqlite3_blob *pBlob; + int rc; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL ROWID"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + if( Tcl_GetWideIntFromObj(interp, objv[2], &iRowid) ) return TCL_ERROR; + + rc = sqlite3_blob_reopen(pBlob, iRowid); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + } + + return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR); +} + +#endif + +/* +** Usage: sqlite3_create_collation_v2 DB-HANDLE NAME CMP-PROC DEL-PROC +** +** This Tcl proc is used for testing the experimental +** sqlite3_create_collation_v2() interface. +*/ +struct TestCollationX { + Tcl_Interp *interp; + Tcl_Obj *pCmp; + Tcl_Obj *pDel; +}; +typedef struct TestCollationX TestCollationX; +static void testCreateCollationDel(void *pCtx){ + TestCollationX *p = (TestCollationX *)pCtx; + + int rc = Tcl_EvalObjEx(p->interp, p->pDel, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL); + if( rc!=TCL_OK ){ + Tcl_BackgroundError(p->interp); + } + + Tcl_DecrRefCount(p->pCmp); + Tcl_DecrRefCount(p->pDel); + sqlite3_free((void *)p); +} +static int testCreateCollationCmp( + void *pCtx, + int nLeft, + const void *zLeft, + int nRight, + const void *zRight +){ + TestCollationX *p = (TestCollationX *)pCtx; + Tcl_Obj *pScript = Tcl_DuplicateObj(p->pCmp); + int iRes = 0; + + Tcl_IncrRefCount(pScript); + Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj((char *)zLeft, nLeft)); + Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj((char *)zRight,nRight)); + + if( TCL_OK!=Tcl_EvalObjEx(p->interp, pScript, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL) + || TCL_OK!=Tcl_GetIntFromObj(p->interp, Tcl_GetObjResult(p->interp), &iRes) + ){ + Tcl_BackgroundError(p->interp); + } + Tcl_DecrRefCount(pScript); + + return iRes; +} +static int test_create_collation_v2( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + TestCollationX *p; + sqlite3 *db; + int rc; + + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE NAME CMP-PROC DEL-PROC"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + p = (TestCollationX *)sqlite3_malloc(sizeof(TestCollationX)); + p->pCmp = objv[3]; + p->pDel = objv[4]; + p->interp = interp; + Tcl_IncrRefCount(p->pCmp); + Tcl_IncrRefCount(p->pDel); + + rc = sqlite3_create_collation_v2(db, Tcl_GetString(objv[2]), 16, + (void *)p, testCreateCollationCmp, testCreateCollationDel + ); + if( rc!=SQLITE_MISUSE ){ + Tcl_AppendResult(interp, "sqlite3_create_collate_v2() failed to detect " + "an invalid encoding", (char*)0); + return TCL_ERROR; + } + rc = sqlite3_create_collation_v2(db, Tcl_GetString(objv[2]), SQLITE_UTF8, + (void *)p, testCreateCollationCmp, testCreateCollationDel + ); + return TCL_OK; +} + +/* +** USAGE: sqlite3_create_function_v2 DB NAME NARG ENC ?SWITCHES? +** +** Available switches are: +** +** -func SCRIPT +** -step SCRIPT +** -final SCRIPT +** -destroy SCRIPT +*/ +typedef struct CreateFunctionV2 CreateFunctionV2; +struct CreateFunctionV2 { + Tcl_Interp *interp; + Tcl_Obj *pFunc; /* Script for function invocation */ + Tcl_Obj *pStep; /* Script for agg. step invocation */ + Tcl_Obj *pFinal; /* Script for agg. finalization invocation */ + Tcl_Obj *pDestroy; /* Destructor script */ +}; +static void cf2Func(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ +} +static void cf2Step(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ +} +static void cf2Final(sqlite3_context *ctx){ +} +static void cf2Destroy(void *pUser){ + CreateFunctionV2 *p = (CreateFunctionV2 *)pUser; + + if( p->interp && p->pDestroy ){ + int rc = Tcl_EvalObjEx(p->interp, p->pDestroy, 0); + if( rc!=TCL_OK ) Tcl_BackgroundError(p->interp); + } + + if( p->pFunc ) Tcl_DecrRefCount(p->pFunc); + if( p->pStep ) Tcl_DecrRefCount(p->pStep); + if( p->pFinal ) Tcl_DecrRefCount(p->pFinal); + if( p->pDestroy ) Tcl_DecrRefCount(p->pDestroy); + sqlite3_free(p); +} +static int test_create_function_v2( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The invoking TCL interpreter */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + const char *zFunc; + int nArg; + int enc; + CreateFunctionV2 *p; + int i; + int rc; + + struct EncTable { + const char *zEnc; + int enc; + } aEnc[] = { + {"utf8", SQLITE_UTF8 }, + {"utf16", SQLITE_UTF16 }, + {"utf16le", SQLITE_UTF16LE }, + {"utf16be", SQLITE_UTF16BE }, + {"any", SQLITE_ANY }, + {"0", 0 } + }; + + if( objc<5 || (objc%2)==0 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB NAME NARG ENC SWITCHES..."); + return TCL_ERROR; + } + + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zFunc = Tcl_GetString(objv[2]); + if( Tcl_GetIntFromObj(interp, objv[3], &nArg) ) return TCL_ERROR; + if( Tcl_GetIndexFromObjStruct(interp, objv[4], aEnc, sizeof(aEnc[0]), + "encoding", 0, &enc) + ){ + return TCL_ERROR; + } + enc = aEnc[enc].enc; + + p = sqlite3_malloc(sizeof(CreateFunctionV2)); + assert( p ); + memset(p, 0, sizeof(CreateFunctionV2)); + p->interp = interp; + + for(i=5; ipFunc = objv[i+1]; break; + case 1: p->pStep = objv[i+1]; break; + case 2: p->pFinal = objv[i+1]; break; + case 3: p->pDestroy = objv[i+1]; break; + } + } + if( p->pFunc ) p->pFunc = Tcl_DuplicateObj(p->pFunc); + if( p->pStep ) p->pStep = Tcl_DuplicateObj(p->pStep); + if( p->pFinal ) p->pFinal = Tcl_DuplicateObj(p->pFinal); + if( p->pDestroy ) p->pDestroy = Tcl_DuplicateObj(p->pDestroy); + + if( p->pFunc ) Tcl_IncrRefCount(p->pFunc); + if( p->pStep ) Tcl_IncrRefCount(p->pStep); + if( p->pFinal ) Tcl_IncrRefCount(p->pFinal); + if( p->pDestroy ) Tcl_IncrRefCount(p->pDestroy); + + rc = sqlite3_create_function_v2(db, zFunc, nArg, enc, (void *)p, + (p->pFunc ? cf2Func : 0), + (p->pStep ? cf2Step : 0), + (p->pFinal ? cf2Final : 0), + cf2Destroy + ); + if( rc!=SQLITE_OK ){ + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: sqlite3_load_extension DB-HANDLE FILE ?PROC? +*/ +static int test_load_extension( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_CmdInfo cmdInfo; + sqlite3 *db; + int rc; + char *zDb; + char *zFile; + char *zProc = 0; + char *zErr = 0; + + if( objc!=4 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE FILE ?PROC?"); + return TCL_ERROR; + } + zDb = Tcl_GetString(objv[1]); + zFile = Tcl_GetString(objv[2]); + if( objc==4 ){ + zProc = Tcl_GetString(objv[3]); + } + + /* Extract the C database handle from the Tcl command name */ + if( !Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){ + Tcl_AppendResult(interp, "command not found: ", zDb, (char*)0); + return TCL_ERROR; + } + db = ((struct SqliteDb*)cmdInfo.objClientData)->db; + assert(db); + + /* Call the underlying C function. If an error occurs, set rc to + ** TCL_ERROR and load any error string into the interpreter. If no + ** error occurs, set rc to TCL_OK. + */ +#ifdef SQLITE_OMIT_LOAD_EXTENSION + rc = SQLITE_ERROR; + zErr = sqlite3_mprintf("this build omits sqlite3_load_extension()"); +#else + rc = sqlite3_load_extension(db, zFile, zProc, &zErr); +#endif + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, zErr ? zErr : "", TCL_VOLATILE); + rc = TCL_ERROR; + }else{ + rc = TCL_OK; + } + sqlite3_free(zErr); + + return rc; +} + +/* +** Usage: sqlite3_enable_load_extension DB-HANDLE ONOFF +*/ +static int test_enable_load( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_CmdInfo cmdInfo; + sqlite3 *db; + char *zDb; + int onoff; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE ONOFF"); + return TCL_ERROR; + } + zDb = Tcl_GetString(objv[1]); + + /* Extract the C database handle from the Tcl command name */ + if( !Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){ + Tcl_AppendResult(interp, "command not found: ", zDb, (char*)0); + return TCL_ERROR; + } + db = ((struct SqliteDb*)cmdInfo.objClientData)->db; + assert(db); + + /* Get the onoff parameter */ + if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){ + return TCL_ERROR; + } + +#ifdef SQLITE_OMIT_LOAD_EXTENSION + Tcl_AppendResult(interp, "this build omits sqlite3_load_extension()"); + return TCL_ERROR; +#else + sqlite3_enable_load_extension(db, onoff); + return TCL_OK; +#endif +} + +/* +** Usage: sqlite_abort +** +** Shutdown the process immediately. This is not a clean shutdown. +** This command is used to test the recoverability of a database in +** the event of a program crash. +*/ +static int sqlite_abort( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ +#if defined(_MSC_VER) + /* We do this, otherwise the test will halt with a popup message + * that we have to click away before the test will continue. + */ + _set_abort_behavior( 0, _CALL_REPORTFAULT ); +#endif + exit(255); + assert( interp==0 ); /* This will always fail */ + return TCL_OK; +} + +/* +** The following routine is a user-defined SQL function whose purpose +** is to test the sqlite_set_result() API. +*/ +static void testFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + while( argc>=2 ){ + const char *zArg0 = (char*)sqlite3_value_text(argv[0]); + if( zArg0 ){ + if( 0==sqlite3StrICmp(zArg0, "int") ){ + sqlite3_result_int(context, sqlite3_value_int(argv[1])); + }else if( sqlite3StrICmp(zArg0,"int64")==0 ){ + sqlite3_result_int64(context, sqlite3_value_int64(argv[1])); + }else if( sqlite3StrICmp(zArg0,"string")==0 ){ + sqlite3_result_text(context, (char*)sqlite3_value_text(argv[1]), -1, + SQLITE_TRANSIENT); + }else if( sqlite3StrICmp(zArg0,"double")==0 ){ + sqlite3_result_double(context, sqlite3_value_double(argv[1])); + }else if( sqlite3StrICmp(zArg0,"null")==0 ){ + sqlite3_result_null(context); + }else if( sqlite3StrICmp(zArg0,"value")==0 ){ + sqlite3_result_value(context, argv[sqlite3_value_int(argv[1])]); + }else{ + goto error_out; + } + }else{ + goto error_out; + } + argc -= 2; + argv += 2; + } + return; + +error_out: + sqlite3_result_error(context,"first argument should be one of: " + "int int64 string double null value", -1); +} + +/* +** Usage: sqlite_register_test_function DB NAME +** +** Register the test SQL function on the database DB under the name NAME. +*/ +static int test_register_func( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + int rc; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB FUNCTION-NAME", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_create_function(db, argv[2], -1, SQLITE_UTF8, 0, + testFunc, 0, 0); + if( rc!=0 ){ + Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0); + return TCL_ERROR; + } + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Usage: sqlite3_finalize STMT +** +** Finalize a statement handle. +*/ +static int test_finalize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + sqlite3 *db = 0; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + + if( pStmt ){ + db = StmtToDb(pStmt); + } + rc = sqlite3_finalize(pStmt); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); + if( db && sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Usage: sqlite3_stmt_status STMT CODE RESETFLAG +** +** Get the value of a status counter from a statement. +*/ +static int test_stmt_status( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int iValue; + int i, op, resetFlag; + const char *zOpName; + sqlite3_stmt *pStmt; + + static const struct { + const char *zName; + int op; + } aOp[] = { + { "SQLITE_STMTSTATUS_FULLSCAN_STEP", SQLITE_STMTSTATUS_FULLSCAN_STEP }, + { "SQLITE_STMTSTATUS_SORT", SQLITE_STMTSTATUS_SORT }, + { "SQLITE_STMTSTATUS_AUTOINDEX", SQLITE_STMTSTATUS_AUTOINDEX }, + { "SQLITE_STMTSTATUS_VM_STEP", SQLITE_STMTSTATUS_VM_STEP }, + }; + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT PARAMETER RESETFLAG"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + zOpName = Tcl_GetString(objv[2]); + for(i=0; i=ArraySize(aOp) ){ + if( Tcl_GetIntFromObj(interp, objv[2], &op) ) return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[3], &resetFlag) ) return TCL_ERROR; + iValue = sqlite3_stmt_status(pStmt, op, resetFlag); + Tcl_SetObjResult(interp, Tcl_NewIntObj(iValue)); + return TCL_OK; +} + +/* +** Usage: sqlite3_next_stmt DB STMT +** +** Return the next statment in sequence after STMT. +*/ +static int test_next_stmt( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + sqlite3 *db = 0; + char zBuf[50]; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " DB STMT", 0); + return TCL_ERROR; + } + + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( getStmtPointer(interp, Tcl_GetString(objv[2]), &pStmt) ) return TCL_ERROR; + pStmt = sqlite3_next_stmt(db, pStmt); + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_stmt_readonly STMT +** +** Return true if STMT is a NULL pointer or a pointer to a statement +** that is guaranteed to leave the database unmodified. +*/ +static int test_stmt_readonly( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + rc = sqlite3_stmt_readonly(pStmt); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc)); + return TCL_OK; +} + +/* +** Usage: sqlite3_stmt_busy STMT +** +** Return true if STMT is a non-NULL pointer to a statement +** that has been stepped but not to completion. +*/ +static int test_stmt_busy( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + rc = sqlite3_stmt_busy(pStmt); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc)); + return TCL_OK; +} + +/* +** Usage: uses_stmt_journal STMT +** +** Return true if STMT uses a statement journal. +*/ +static int uses_stmt_journal( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + sqlite3_stmt_readonly(pStmt); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(((Vdbe *)pStmt)->usesStmtJournal)); + return TCL_OK; +} + + +/* +** Usage: sqlite3_reset STMT +** +** Reset a statement handle. +*/ +static int test_reset( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + + rc = sqlite3_reset(pStmt); + if( pStmt && sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ){ + return TCL_ERROR; + } + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); +/* + if( rc ){ + return TCL_ERROR; + } +*/ + return TCL_OK; +} + +/* +** Usage: sqlite3_expired STMT +** +** Return TRUE if a recompilation of the statement is recommended. +*/ +static int test_expired( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_stmt *pStmt; + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(sqlite3_expired(pStmt))); +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_transfer_bindings FROMSTMT TOSTMT +** +** Transfer all bindings from FROMSTMT over to TOSTMT +*/ +static int test_transfer_bind( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_stmt *pStmt1, *pStmt2; + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " FROM-STMT TO-STMT", 0); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt1)) return TCL_ERROR; + if( getStmtPointer(interp, Tcl_GetString(objv[2]), &pStmt2)) return TCL_ERROR; + Tcl_SetObjResult(interp, + Tcl_NewIntObj(sqlite3_transfer_bindings(pStmt1,pStmt2))); +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_changes DB +** +** Return the number of changes made to the database by the last SQL +** execution. +*/ +static int test_changes( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_changes(db))); + return TCL_OK; +} + +/* +** This is the "static_bind_value" that variables are bound to when +** the FLAG option of sqlite3_bind is "static" +*/ +static char *sqlite_static_bind_value = 0; +static int sqlite_static_bind_nbyte = 0; + +/* +** Usage: sqlite3_bind VM IDX VALUE FLAGS +** +** Sets the value of the IDX-th occurrence of "?" in the original SQL +** string. VALUE is the new value. If FLAGS=="null" then VALUE is +** ignored and the value is set to NULL. If FLAGS=="static" then +** the value is set to the value of a static variable named +** "sqlite_static_bind_value". If FLAGS=="normal" then a copy +** of the VALUE is made. If FLAGS=="blob10" then a VALUE is ignored +** an a 10-byte blob "abc\000xyz\000pq" is inserted. +*/ +static int test_bind( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3_stmt *pStmt; + int rc; + int idx; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " VM IDX VALUE (null|static|normal)\"", 0); + return TCL_ERROR; + } + if( getStmtPointer(interp, argv[1], &pStmt) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[2], &idx) ) return TCL_ERROR; + if( strcmp(argv[4],"null")==0 ){ + rc = sqlite3_bind_null(pStmt, idx); + }else if( strcmp(argv[4],"static")==0 ){ + rc = sqlite3_bind_text(pStmt, idx, sqlite_static_bind_value, -1, 0); + }else if( strcmp(argv[4],"static-nbytes")==0 ){ + rc = sqlite3_bind_text(pStmt, idx, sqlite_static_bind_value, + sqlite_static_bind_nbyte, 0); + }else if( strcmp(argv[4],"normal")==0 ){ + rc = sqlite3_bind_text(pStmt, idx, argv[3], -1, SQLITE_TRANSIENT); + }else if( strcmp(argv[4],"blob10")==0 ){ + rc = sqlite3_bind_text(pStmt, idx, "abc\000xyz\000pq", 10, SQLITE_STATIC); + }else{ + Tcl_AppendResult(interp, "4th argument should be " + "\"null\" or \"static\" or \"normal\"", 0); + return TCL_ERROR; + } + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc ){ + char zBuf[50]; + sprintf(zBuf, "(%d) ", rc); + Tcl_AppendResult(interp, zBuf, sqlite3ErrStr(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Usage: add_test_collate +** +** This function is used to test that SQLite selects the correct collation +** sequence callback when multiple versions (for different text encodings) +** are available. +** +** Calling this routine registers the collation sequence "test_collate" +** with database handle . The second argument must be a list of three +** boolean values. If the first is true, then a version of test_collate is +** registered for UTF-8, if the second is true, a version is registered for +** UTF-16le, if the third is true, a UTF-16be version is available. +** Previous versions of test_collate are deleted. +** +** The collation sequence test_collate is implemented by calling the +** following TCL script: +** +** "test_collate " +** +** The and are the two values being compared, encoded in UTF-8. +** The parameter is the encoding of the collation function that +** SQLite selected to call. The TCL test script implements the +** "test_collate" proc. +** +** Note that this will only work with one intepreter at a time, as the +** interp pointer to use when evaluating the TCL script is stored in +** pTestCollateInterp. +*/ +static Tcl_Interp* pTestCollateInterp; +static int test_collate_func( + void *pCtx, + int nA, const void *zA, + int nB, const void *zB +){ + Tcl_Interp *i = pTestCollateInterp; + int encin = SQLITE_PTR_TO_INT(pCtx); + int res; + int n; + + sqlite3_value *pVal; + Tcl_Obj *pX; + + pX = Tcl_NewStringObj("test_collate", -1); + Tcl_IncrRefCount(pX); + + switch( encin ){ + case SQLITE_UTF8: + Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-8",-1)); + break; + case SQLITE_UTF16LE: + Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16LE",-1)); + break; + case SQLITE_UTF16BE: + Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16BE",-1)); + break; + default: + assert(0); + } + + sqlite3BeginBenignMalloc(); + pVal = sqlite3ValueNew(0); + if( pVal ){ + sqlite3ValueSetStr(pVal, nA, zA, encin, SQLITE_STATIC); + n = sqlite3_value_bytes(pVal); + Tcl_ListObjAppendElement(i,pX, + Tcl_NewStringObj((char*)sqlite3_value_text(pVal),n)); + sqlite3ValueSetStr(pVal, nB, zB, encin, SQLITE_STATIC); + n = sqlite3_value_bytes(pVal); + Tcl_ListObjAppendElement(i,pX, + Tcl_NewStringObj((char*)sqlite3_value_text(pVal),n)); + sqlite3ValueFree(pVal); + } + sqlite3EndBenignMalloc(); + + Tcl_EvalObjEx(i, pX, 0); + Tcl_DecrRefCount(pX); + Tcl_GetIntFromObj(i, Tcl_GetObjResult(i), &res); + return res; +} +static int test_collate( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int val; + sqlite3_value *pVal; + int rc; + + if( objc!=5 ) goto bad_args; + pTestCollateInterp = interp; + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR; + rc = sqlite3_create_collation(db, "test_collate", SQLITE_UTF8, + (void *)SQLITE_UTF8, val?test_collate_func:0); + if( rc==SQLITE_OK ){ + const void *zUtf16; + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &val) ) return TCL_ERROR; + rc = sqlite3_create_collation(db, "test_collate", SQLITE_UTF16LE, + (void *)SQLITE_UTF16LE, val?test_collate_func:0); + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR; + +#if 0 + if( sqlite3_iMallocFail>0 ){ + sqlite3_iMallocFail++; + } +#endif + sqlite3_mutex_enter(db->mutex); + pVal = sqlite3ValueNew(db); + sqlite3ValueSetStr(pVal, -1, "test_collate", SQLITE_UTF8, SQLITE_STATIC); + zUtf16 = sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); + if( db->mallocFailed ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_create_collation16(db, zUtf16, SQLITE_UTF16BE, + (void *)SQLITE_UTF16BE, val?test_collate_func:0); + } + sqlite3ValueFree(pVal); + sqlite3_mutex_leave(db->mutex); + } + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; + +bad_args: + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; +} + +/* +** When the collation needed callback is invoked, record the name of +** the requested collating function here. The recorded name is linked +** to a TCL variable and used to make sure that the requested collation +** name is correct. +*/ +static char zNeededCollation[200]; +static char *pzNeededCollation = zNeededCollation; + + +/* +** Called when a collating sequence is needed. Registered using +** sqlite3_collation_needed16(). +*/ +static void test_collate_needed_cb( + void *pCtx, + sqlite3 *db, + int eTextRep, + const void *pName +){ + int enc = ENC(db); + int i; + char *z; + for(z = (char*)pName, i=0; *z || z[1]; z++){ + if( *z ) zNeededCollation[i++] = *z; + } + zNeededCollation[i] = 0; + sqlite3_create_collation( + db, "test_collate", ENC(db), SQLITE_INT_TO_PTR(enc), test_collate_func); +} + +/* +** Usage: add_test_collate_needed DB +*/ +static int test_collate_needed( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int rc; + + if( objc!=2 ) goto bad_args; + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_collation_needed16(db, 0, test_collate_needed_cb); + zNeededCollation[0] = 0; + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; + +bad_args: + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; +} + +/* +** tclcmd: add_alignment_test_collations DB +** +** Add two new collating sequences to the database DB +** +** utf16_aligned +** utf16_unaligned +** +** Both collating sequences use the same sort order as BINARY. +** The only difference is that the utf16_aligned collating +** sequence is declared with the SQLITE_UTF16_ALIGNED flag. +** Both collating functions increment the unaligned utf16 counter +** whenever they see a string that begins on an odd byte boundary. +*/ +static int unaligned_string_counter = 0; +static int alignmentCollFunc( + void *NotUsed, + int nKey1, const void *pKey1, + int nKey2, const void *pKey2 +){ + int rc, n; + n = nKey10 && 1==(1&(SQLITE_PTR_TO_INT(pKey1))) ) unaligned_string_counter++; + if( nKey2>0 && 1==(1&(SQLITE_PTR_TO_INT(pKey2))) ) unaligned_string_counter++; + rc = memcmp(pKey1, pKey2, n); + if( rc==0 ){ + rc = nKey1 - nKey2; + } + return rc; +} +static int add_alignment_test_collations( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + if( objc>=2 ){ + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + sqlite3_create_collation(db, "utf16_unaligned", SQLITE_UTF16, + 0, alignmentCollFunc); + sqlite3_create_collation(db, "utf16_aligned", SQLITE_UTF16_ALIGNED, + 0, alignmentCollFunc); + } + return SQLITE_OK; +} +#endif /* !defined(SQLITE_OMIT_UTF16) */ + +/* +** Usage: add_test_function +** +** This function is used to test that SQLite selects the correct user +** function callback when multiple versions (for different text encodings) +** are available. +** +** Calling this routine registers up to three versions of the user function +** "test_function" with database handle . If the second argument is +** true, then a version of test_function is registered for UTF-8, if the +** third is true, a version is registered for UTF-16le, if the fourth is +** true, a UTF-16be version is available. Previous versions of +** test_function are deleted. +** +** The user function is implemented by calling the following TCL script: +** +** "test_function " +** +** Where is one of UTF-8, UTF-16LE or UTF16BE, and is the +** single argument passed to the SQL function. The value returned by +** the TCL script is used as the return value of the SQL function. It +** is passed to SQLite using UTF-16BE for a UTF-8 test_function(), UTF-8 +** for a UTF-16LE test_function(), and UTF-16LE for an implementation that +** prefers UTF-16BE. +*/ +#ifndef SQLITE_OMIT_UTF16 +static void test_function_utf8( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + Tcl_Interp *interp; + Tcl_Obj *pX; + sqlite3_value *pVal; + interp = (Tcl_Interp *)sqlite3_user_data(pCtx); + pX = Tcl_NewStringObj("test_function", -1); + Tcl_IncrRefCount(pX); + Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-8", -1)); + Tcl_ListObjAppendElement(interp, pX, + Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1)); + Tcl_EvalObjEx(interp, pX, 0); + Tcl_DecrRefCount(pX); + sqlite3_result_text(pCtx, Tcl_GetStringResult(interp), -1, SQLITE_TRANSIENT); + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), + SQLITE_UTF8, SQLITE_STATIC); + sqlite3_result_text16be(pCtx, sqlite3_value_text16be(pVal), + -1, SQLITE_TRANSIENT); + sqlite3ValueFree(pVal); +} +static void test_function_utf16le( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + Tcl_Interp *interp; + Tcl_Obj *pX; + sqlite3_value *pVal; + interp = (Tcl_Interp *)sqlite3_user_data(pCtx); + pX = Tcl_NewStringObj("test_function", -1); + Tcl_IncrRefCount(pX); + Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16LE", -1)); + Tcl_ListObjAppendElement(interp, pX, + Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1)); + Tcl_EvalObjEx(interp, pX, 0); + Tcl_DecrRefCount(pX); + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), + SQLITE_UTF8, SQLITE_STATIC); + sqlite3_result_text(pCtx,(char*)sqlite3_value_text(pVal),-1,SQLITE_TRANSIENT); + sqlite3ValueFree(pVal); +} +static void test_function_utf16be( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + Tcl_Interp *interp; + Tcl_Obj *pX; + sqlite3_value *pVal; + interp = (Tcl_Interp *)sqlite3_user_data(pCtx); + pX = Tcl_NewStringObj("test_function", -1); + Tcl_IncrRefCount(pX); + Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16BE", -1)); + Tcl_ListObjAppendElement(interp, pX, + Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1)); + Tcl_EvalObjEx(interp, pX, 0); + Tcl_DecrRefCount(pX); + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), + SQLITE_UTF8, SQLITE_STATIC); + sqlite3_result_text16(pCtx, sqlite3_value_text16le(pVal), + -1, SQLITE_TRANSIENT); + sqlite3_result_text16be(pCtx, sqlite3_value_text16le(pVal), + -1, SQLITE_TRANSIENT); + sqlite3_result_text16le(pCtx, sqlite3_value_text16le(pVal), + -1, SQLITE_TRANSIENT); + sqlite3ValueFree(pVal); +} +#endif /* SQLITE_OMIT_UTF16 */ +static int test_function( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3 *db; + int val; + + if( objc!=5 ) goto bad_args; + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR; + if( val ){ + sqlite3_create_function(db, "test_function", 1, SQLITE_UTF8, + interp, test_function_utf8, 0, 0); + } + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &val) ) return TCL_ERROR; + if( val ){ + sqlite3_create_function(db, "test_function", 1, SQLITE_UTF16LE, + interp, test_function_utf16le, 0, 0); + } + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR; + if( val ){ + sqlite3_create_function(db, "test_function", 1, SQLITE_UTF16BE, + interp, test_function_utf16be, 0, 0); + } + + return TCL_OK; +bad_args: + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_ERROR; +} + +/* +** Usage: sqlite3_test_errstr +** +** Test that the english language string equivalents for sqlite error codes +** are sane. The parameter is an integer representing an sqlite error code. +** The result is a list of two elements, the string representation of the +** error code and the english language explanation. +*/ +static int test_errstr( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + char *zCode; + int i; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + } + + zCode = Tcl_GetString(objv[1]); + for(i=0; i<200; i++){ + if( 0==strcmp(t1ErrorName(i), zCode) ) break; + } + Tcl_SetResult(interp, (char *)sqlite3ErrStr(i), 0); + return TCL_OK; +} + +/* +** Usage: breakpoint +** +** This routine exists for one purpose - to provide a place to put a +** breakpoint with GDB that can be triggered using TCL code. The use +** for this is when a particular test fails on (say) the 1485th iteration. +** In the TCL test script, we can add code like this: +** +** if {$i==1485} breakpoint +** +** Then run testfixture in the debugger and wait for the breakpoint to +** fire. Then additional breakpoints can be set to trace down the bug. +*/ +static int test_breakpoint( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + return TCL_OK; /* Do nothing */ +} + +/* +** Usage: sqlite3_bind_zeroblob STMT IDX N +** +** Test the sqlite3_bind_zeroblob interface. STMT is a prepared statement. +** IDX is the index of a wildcard in the prepared statement. This command +** binds a N-byte zero-filled BLOB to the wildcard. +*/ +static int test_bind_zeroblob( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int n; + int rc; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT IDX N"); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &n) ) return TCL_ERROR; + + rc = sqlite3_bind_zeroblob(pStmt, idx, n); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_int STMT N VALUE +** +** Test the sqlite3_bind_int interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a 32-bit integer VALUE to that wildcard. +*/ +static int test_bind_int( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int value; + int rc; + + if( objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &value) ) return TCL_ERROR; + + rc = sqlite3_bind_int(pStmt, idx, value); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + + +/* +** Usage: sqlite3_bind_int64 STMT N VALUE +** +** Test the sqlite3_bind_int64 interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a 64-bit integer VALUE to that wildcard. +*/ +static int test_bind_int64( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + Tcl_WideInt value; + int rc; + + if( objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + if( Tcl_GetWideIntFromObj(interp, objv[3], &value) ) return TCL_ERROR; + + rc = sqlite3_bind_int64(pStmt, idx, value); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + + +/* +** Usage: sqlite3_bind_double STMT N VALUE +** +** Test the sqlite3_bind_double interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a 64-bit integer VALUE to that wildcard. +*/ +static int test_bind_double( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + double value; + int rc; + const char *zVal; + int i; + static const struct { + const char *zName; /* Name of the special floating point value */ + unsigned int iUpper; /* Upper 32 bits */ + unsigned int iLower; /* Lower 32 bits */ + } aSpecialFp[] = { + { "NaN", 0x7fffffff, 0xffffffff }, + { "SNaN", 0x7ff7ffff, 0xffffffff }, + { "-NaN", 0xffffffff, 0xffffffff }, + { "-SNaN", 0xfff7ffff, 0xffffffff }, + { "+Inf", 0x7ff00000, 0x00000000 }, + { "-Inf", 0xfff00000, 0x00000000 }, + { "Epsilon", 0x00000000, 0x00000001 }, + { "-Epsilon", 0x80000000, 0x00000001 }, + { "NaN0", 0x7ff80000, 0x00000000 }, + { "-NaN0", 0xfff80000, 0x00000000 }, + }; + + if( objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + + /* Intercept the string "NaN" and generate a NaN value for it. + ** All other strings are passed through to Tcl_GetDoubleFromObj(). + ** Tcl_GetDoubleFromObj() should understand "NaN" but some versions + ** contain a bug. + */ + zVal = Tcl_GetString(objv[3]); + for(i=0; i=sizeof(aSpecialFp)/sizeof(aSpecialFp[0]) && + Tcl_GetDoubleFromObj(interp, objv[3], &value) ){ + return TCL_ERROR; + } + rc = sqlite3_bind_double(pStmt, idx, value); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_null STMT N +** +** Test the sqlite3_bind_null interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a NULL to the wildcard. +*/ +static int test_bind_null( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int rc; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + + rc = sqlite3_bind_null(pStmt, idx); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_text STMT N STRING BYTES +** +** Test the sqlite3_bind_text interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a UTF-8 string STRING to the wildcard. The string is BYTES bytes +** long. +*/ +static int test_bind_text( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int bytes; + char *value; + int rc; + + if( objc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE BYTES", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + value = (char*)Tcl_GetByteArrayFromObj(objv[3], &bytes); + if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR; + + rc = sqlite3_bind_text(pStmt, idx, value, bytes, SQLITE_TRANSIENT); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_text16 ?-static? STMT N STRING BYTES +** +** Test the sqlite3_bind_text16 interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a UTF-16 string STRING to the wildcard. The string is BYTES bytes +** long. +*/ +static int test_bind_text16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3_stmt *pStmt; + int idx; + int bytes; + char *value; + int rc; + + void (*xDel)(void*) = (objc==6?SQLITE_STATIC:SQLITE_TRANSIENT); + Tcl_Obj *oStmt = objv[objc-4]; + Tcl_Obj *oN = objv[objc-3]; + Tcl_Obj *oString = objv[objc-2]; + Tcl_Obj *oBytes = objv[objc-1]; + + if( objc!=5 && objc!=6){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE BYTES", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(oStmt), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, oN, &idx) ) return TCL_ERROR; + value = (char*)Tcl_GetByteArrayFromObj(oString, 0); + if( Tcl_GetIntFromObj(interp, oBytes, &bytes) ) return TCL_ERROR; + + rc = sqlite3_bind_text16(pStmt, idx, (void *)value, bytes, xDel); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_blob ?-static? STMT N DATA BYTES +** +** Test the sqlite3_bind_blob interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a BLOB to the wildcard. The BLOB is BYTES bytes in size. +*/ +static int test_bind_blob( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int bytes; + char *value; + int rc; + sqlite3_destructor_type xDestructor = SQLITE_TRANSIENT; + + if( objc!=5 && objc!=6 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N DATA BYTES", 0); + return TCL_ERROR; + } + + if( objc==6 ){ + xDestructor = SQLITE_STATIC; + objv++; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + value = Tcl_GetString(objv[3]); + if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR; + + rc = sqlite3_bind_blob(pStmt, idx, value, bytes, xDestructor); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_parameter_count STMT +** +** Return the number of wildcards in the given statement. +*/ +static int test_bind_parameter_count( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_bind_parameter_count(pStmt))); + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_parameter_name STMT N +** +** Return the name of the Nth wildcard. The first wildcard is 1. +** An empty string is returned if N is out of range or if the wildcard +** is nameless. +*/ +static int test_bind_parameter_name( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int i; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT N"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &i) ) return TCL_ERROR; + Tcl_SetObjResult(interp, + Tcl_NewStringObj(sqlite3_bind_parameter_name(pStmt,i),-1) + ); + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_parameter_index STMT NAME +** +** Return the index of the wildcard called NAME. Return 0 if there is +** no such wildcard. +*/ +static int test_bind_parameter_index( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT NAME"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetObjResult(interp, + Tcl_NewIntObj( + sqlite3_bind_parameter_index(pStmt,Tcl_GetString(objv[2])) + ) + ); + return TCL_OK; +} + +/* +** Usage: sqlite3_clear_bindings STMT +** +*/ +static int test_clear_bindings( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_clear_bindings(pStmt))); + return TCL_OK; +} + +/* +** Usage: sqlite3_sleep MILLISECONDS +*/ +static int test_sleep( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int ms; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "MILLISECONDS"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &ms) ){ + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_sleep(ms))); + return TCL_OK; +} + +/* +** Usage: sqlite3_extended_errcode DB +** +** Return the string representation of the most recent sqlite3_* API +** error code. e.g. "SQLITE_ERROR". +*/ +static int test_ex_errcode( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_extended_errcode(db); + Tcl_AppendResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + + +/* +** Usage: sqlite3_errcode DB +** +** Return the string representation of the most recent sqlite3_* API +** error code. e.g. "SQLITE_ERROR". +*/ +static int test_errcode( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_errcode(db); + Tcl_AppendResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + +/* +** Usage: sqlite3_errmsg DB +** +** Returns the UTF-8 representation of the error message string for the +** most recent sqlite3_* API call. +*/ +static int test_errmsg( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zErr; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + zErr = sqlite3_errmsg(db); + Tcl_SetObjResult(interp, Tcl_NewStringObj(zErr, -1)); + return TCL_OK; +} + +/* +** Usage: test_errmsg16 DB +** +** Returns the UTF-16 representation of the error message string for the +** most recent sqlite3_* API call. This is a byte array object at the TCL +** level, and it includes the 0x00 0x00 terminator bytes at the end of the +** UTF-16 string. +*/ +static int test_errmsg16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3 *db; + const void *zErr; + const char *z; + int bytes = 0; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + zErr = sqlite3_errmsg16(db); + if( zErr ){ + z = zErr; + for(bytes=0; z[bytes] || z[bytes+1]; bytes+=2){} + } + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(zErr, bytes)); +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_prepare DB sql bytes ?tailvar? +** +** Compile up to bytes of the supplied SQL string using +** database handle . The parameter is the name of a global +** variable that is set to the unused portion of (if any). A +** STMT handle is returned. +*/ +static int test_prepare( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zSql; + int bytes; + const char *zTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetString(objv[2]); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + rc = sqlite3_prepare(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0); + Tcl_ResetResult(interp); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( zTail && objc>=5 ){ + if( bytes>=0 ){ + bytes = bytes - (int)(zTail-zSql); + } + if( (int)strlen(zTail) bytes of the supplied SQL string using +** database handle . The parameter is the name of a global +** variable that is set to the unused portion of (if any). A +** STMT handle is returned. +*/ +static int test_prepare_v2( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zSql; + int bytes; + const char *zTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetString(objv[2]); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + rc = sqlite3_prepare_v2(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0); + assert(rc==SQLITE_OK || pStmt==0); + Tcl_ResetResult(interp); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( zTail && objc>=5 ){ + if( bytes>=0 ){ + bytes = bytes - (int)(zTail-zSql); + } + Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0); + } + if( rc!=SQLITE_OK ){ + assert( pStmt==0 ); + sprintf(zBuf, "(%d) ", rc); + Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0); + return TCL_ERROR; + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_prepare_tkt3134 DB +** +** Generate a prepared statement for a zero-byte string as a test +** for ticket #3134. The string should be preceeded by a zero byte. +*/ +static int test_prepare_tkt3134( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + static const char zSql[] = "\000SELECT 1"; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_prepare_v2(db, &zSql[1], 0, &pStmt, 0); + assert(rc==SQLITE_OK || pStmt==0); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + assert( pStmt==0 ); + sprintf(zBuf, "(%d) ", rc); + Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0); + return TCL_ERROR; + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_prepare16 DB sql bytes tailvar +** +** Compile up to bytes of the supplied SQL string using +** database handle . The parameter is the name of a global +** variable that is set to the unused portion of (if any). A +** STMT handle is returned. +*/ +static int test_prepare16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3 *db; + const void *zSql; + const void *zTail = 0; + Tcl_Obj *pTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + int bytes; /* The integer specified as arg 3 */ + int objlen; /* The byte-array length of arg 2 */ + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetByteArrayFromObj(objv[2], &objlen); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + rc = sqlite3_prepare16(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( rc ){ + return TCL_ERROR; + } + + if( objc>=5 ){ + if( zTail ){ + objlen = objlen - (int)((u8 *)zTail-(u8 *)zSql); + }else{ + objlen = 0; + } + pTail = Tcl_NewByteArrayObj((u8 *)zTail, objlen); + Tcl_IncrRefCount(pTail); + Tcl_ObjSetVar2(interp, objv[4], 0, pTail, 0); + Tcl_DecrRefCount(pTail); + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + } + Tcl_AppendResult(interp, zBuf, 0); +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_prepare16_v2 DB sql bytes ?tailvar? +** +** Compile up to bytes of the supplied SQL string using +** database handle . The parameter is the name of a global +** variable that is set to the unused portion of (if any). A +** STMT handle is returned. +*/ +static int test_prepare16_v2( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3 *db; + const void *zSql; + const void *zTail = 0; + Tcl_Obj *pTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + int bytes; /* The integer specified as arg 3 */ + int objlen; /* The byte-array length of arg 2 */ + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetByteArrayFromObj(objv[2], &objlen); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + rc = sqlite3_prepare16_v2(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( rc ){ + return TCL_ERROR; + } + + if( objc>=5 ){ + if( zTail ){ + objlen = objlen - (int)((u8 *)zTail-(u8 *)zSql); + }else{ + objlen = 0; + } + pTail = Tcl_NewByteArrayObj((u8 *)zTail, objlen); + Tcl_IncrRefCount(pTail); + Tcl_ObjSetVar2(interp, objv[4], 0, pTail, 0); + Tcl_DecrRefCount(pTail); + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + } + Tcl_AppendResult(interp, zBuf, 0); +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_open filename ?options-list? +*/ +static int test_open( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; + sqlite3 *db; + char zBuf[100]; + + if( objc!=3 && objc!=2 && objc!=1 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " filename options-list", 0); + return TCL_ERROR; + } + + zFilename = objc>1 ? Tcl_GetString(objv[1]) : 0; + sqlite3_open(zFilename, &db); + + if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: sqlite3_open_v2 FILENAME FLAGS VFS +*/ +static int test_open_v2( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; + const char *zVfs; + int flags = 0; + sqlite3 *db; + int rc; + char zBuf[100]; + + int nFlag; + Tcl_Obj **apFlag; + int i; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME FLAGS VFS"); + return TCL_ERROR; + } + zFilename = Tcl_GetString(objv[1]); + zVfs = Tcl_GetString(objv[3]); + if( zVfs[0]==0x00 ) zVfs = 0; + + rc = Tcl_ListObjGetElements(interp, objv[2], &nFlag, &apFlag); + if( rc!=TCL_OK ) return rc; + for(i=0; i +** +** Return 1 if the supplied argument is a complete SQL statement, or zero +** otherwise. +*/ +static int test_complete16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#if !defined(SQLITE_OMIT_COMPLETE) && !defined(SQLITE_OMIT_UTF16) + char *zBuf; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + zBuf = (char*)Tcl_GetByteArrayFromObj(objv[1], 0); + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_complete16(zBuf))); +#endif /* SQLITE_OMIT_COMPLETE && SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_step STMT +** +** Advance the statement to the next row. +*/ +static int test_step( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + rc = sqlite3_step(pStmt); + + /* if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ) return TCL_ERROR; */ + Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + +static int test_sql( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetResult(interp, (char *)sqlite3_sql(pStmt), TCL_VOLATILE); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_count STMT +** +** Return the number of columns returned by the sql statement STMT. +*/ +static int test_column_count( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_column_count(pStmt))); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_type STMT column +** +** Return the type of the data in column 'column' of the current row. +*/ +static int test_column_type( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + int tp; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + tp = sqlite3_column_type(pStmt, col); + switch( tp ){ + case SQLITE_INTEGER: + Tcl_SetResult(interp, "INTEGER", TCL_STATIC); + break; + case SQLITE_NULL: + Tcl_SetResult(interp, "NULL", TCL_STATIC); + break; + case SQLITE_FLOAT: + Tcl_SetResult(interp, "FLOAT", TCL_STATIC); + break; + case SQLITE_TEXT: + Tcl_SetResult(interp, "TEXT", TCL_STATIC); + break; + case SQLITE_BLOB: + Tcl_SetResult(interp, "BLOB", TCL_STATIC); + break; + default: + assert(0); + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_column_int64 STMT column +** +** Return the data in column 'column' of the current row cast as an +** wide (64-bit) integer. +*/ +static int test_column_int64( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + i64 iVal; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + iVal = sqlite3_column_int64(pStmt, col); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(iVal)); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_blob STMT column +*/ +static int test_column_blob( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + + int len; + const void *pBlob; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + len = sqlite3_column_bytes(pStmt, col); + pBlob = sqlite3_column_blob(pStmt, col); + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pBlob, len)); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_double STMT column +** +** Return the data in column 'column' of the current row cast as a double. +*/ +static int test_column_double( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + double rVal; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + rVal = sqlite3_column_double(pStmt, col); + Tcl_SetObjResult(interp, Tcl_NewDoubleObj(rVal)); + return TCL_OK; +} + +/* +** Usage: sqlite3_data_count STMT +** +** Return the number of columns returned by the sql statement STMT. +*/ +static int test_data_count( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_data_count(pStmt))); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_text STMT column +** +** Usage: sqlite3_column_decltype STMT column +** +** Usage: sqlite3_column_name STMT column +*/ +static int test_stmt_utf8( + void * clientData, /* Pointer to SQLite API function to be invoke */ + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + const char *(*xFunc)(sqlite3_stmt*, int); + const char *zRet; + + xFunc = (const char *(*)(sqlite3_stmt*, int))clientData; + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + zRet = xFunc(pStmt, col); + if( zRet ){ + Tcl_SetResult(interp, (char *)zRet, 0); + } + return TCL_OK; +} + +static int test_global_recover( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_DEPRECATED + int rc; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + rc = sqlite3_global_recover(); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_column_text STMT column +** +** Usage: sqlite3_column_decltype STMT column +** +** Usage: sqlite3_column_name STMT column +*/ +static int test_stmt_utf16( + void * clientData, /* Pointer to SQLite API function to be invoked */ + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3_stmt *pStmt; + int col; + Tcl_Obj *pRet; + const void *zName16; + const void *(*xFunc)(sqlite3_stmt*, int); + + xFunc = (const void *(*)(sqlite3_stmt*, int))clientData; + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + zName16 = xFunc(pStmt, col); + if( zName16 ){ + int n; + const char *z = zName16; + for(n=0; z[n] || z[n+1]; n+=2){} + pRet = Tcl_NewByteArrayObj(zName16, n+2); + Tcl_SetObjResult(interp, pRet); + } +#endif /* SQLITE_OMIT_UTF16 */ + + return TCL_OK; +} + +/* +** Usage: sqlite3_column_int STMT column +** +** Usage: sqlite3_column_bytes STMT column +** +** Usage: sqlite3_column_bytes16 STMT column +** +*/ +static int test_stmt_int( + void * clientData, /* Pointer to SQLite API function to be invoked */ + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + int (*xFunc)(sqlite3_stmt*, int); + + xFunc = (int (*)(sqlite3_stmt*, int))clientData; + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + Tcl_SetObjResult(interp, Tcl_NewIntObj(xFunc(pStmt, col))); + return TCL_OK; +} + +/* +** Usage: sqlite_set_magic DB MAGIC-NUMBER +** +** Set the db->magic value. This is used to test error recovery logic. +*/ +static int sqlite_set_magic( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + sqlite3 *db; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB MAGIC", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + if( strcmp(argv[2], "SQLITE_MAGIC_OPEN")==0 ){ + db->magic = SQLITE_MAGIC_OPEN; + }else if( strcmp(argv[2], "SQLITE_MAGIC_CLOSED")==0 ){ + db->magic = SQLITE_MAGIC_CLOSED; + }else if( strcmp(argv[2], "SQLITE_MAGIC_BUSY")==0 ){ + db->magic = SQLITE_MAGIC_BUSY; + }else if( strcmp(argv[2], "SQLITE_MAGIC_ERROR")==0 ){ + db->magic = SQLITE_MAGIC_ERROR; + }else if( Tcl_GetInt(interp, argv[2], (int*)&db->magic) ){ + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: sqlite3_interrupt DB +** +** Trigger an interrupt on DB +*/ +static int test_interrupt( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + sqlite3 *db; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + sqlite3_interrupt(db); + return TCL_OK; +} + +static u8 *sqlite3_stack_baseline = 0; + +/* +** Fill the stack with a known bitpattern. +*/ +static void prepStack(void){ + int i; + u32 bigBuf[65536]; + for(i=0; i=0 && ((u32*)sqlite3_stack_baseline)[-i]==0xdeadbeef; i--){} + Tcl_SetObjResult(interp, Tcl_NewIntObj(i*4)); + return TCL_OK; +} + +/* +** Usage: sqlite_delete_function DB function-name +** +** Delete the user function 'function-name' from database handle DB. It +** is assumed that the user function was created as UTF8, any number of +** arguments (the way the TCL interface does it). +*/ +static int delete_function( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + int rc; + sqlite3 *db; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB function-name", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_create_function(db, argv[2], -1, SQLITE_UTF8, 0, 0, 0, 0); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** Usage: sqlite_delete_collation DB collation-name +** +** Delete the collation sequence 'collation-name' from database handle +** DB. It is assumed that the collation sequence was created as UTF8 (the +** way the TCL interface does it). +*/ +static int delete_collation( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + int rc; + sqlite3 *db; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB function-name", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_create_collation(db, argv[2], SQLITE_UTF8, 0, 0); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** Usage: sqlite3_get_autocommit DB +** +** Return true if the database DB is currently in auto-commit mode. +** Return false if not. +*/ +static int get_autocommit( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + char zBuf[30]; + sqlite3 *db; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + sprintf(zBuf, "%d", sqlite3_get_autocommit(db)); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: sqlite3_busy_timeout DB MS +** +** Set the busy timeout. This is more easily done using the timeout +** method of the TCL interface. But we need a way to test the case +** where it returns SQLITE_MISUSE. +*/ +static int test_busy_timeout( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + int rc, ms; + sqlite3 *db; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[2], &ms) ) return TCL_ERROR; + rc = sqlite3_busy_timeout(db, ms); + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_OK; +} + +/* +** Usage: tcl_variable_type VARIABLENAME +** +** Return the name of the internal representation for the +** value of the given variable. +*/ +static int tcl_variable_type( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Obj *pVar; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "VARIABLE"); + return TCL_ERROR; + } + pVar = Tcl_GetVar2Ex(interp, Tcl_GetString(objv[1]), 0, TCL_LEAVE_ERR_MSG); + if( pVar==0 ) return TCL_ERROR; + if( pVar->typePtr ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(pVar->typePtr->name, -1)); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_release_memory ?N? +** +** Attempt to release memory currently held but not actually required. +** The integer N is the number of bytes we are trying to release. The +** return value is the amount of memory actually released. +*/ +static int test_release_memory( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO) + int N; + int amt; + if( objc!=1 && objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?N?"); + return TCL_ERROR; + } + if( objc==2 ){ + if( Tcl_GetIntFromObj(interp, objv[1], &N) ) return TCL_ERROR; + }else{ + N = -1; + } + amt = sqlite3_release_memory(N); + Tcl_SetObjResult(interp, Tcl_NewIntObj(amt)); +#endif + return TCL_OK; +} + + +/* +** Usage: sqlite3_db_release_memory DB +** +** Attempt to release memory currently held by database DB. Return the +** result code (which in the current implementation is always zero). +*/ +static int test_db_release_memory( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int rc; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_db_release_memory(db); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** Usage: sqlite3_db_filename DB DBNAME +** +** Return the name of a file associated with a database. +*/ +static int test_db_filename( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zDbName; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB DBNAME"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zDbName = Tcl_GetString(objv[2]); + Tcl_AppendResult(interp, sqlite3_db_filename(db, zDbName), (void*)0); + return TCL_OK; +} + +/* +** Usage: sqlite3_db_readonly DB DBNAME +** +** Return 1 or 0 if DBNAME is readonly or not. Return -1 if DBNAME does +** not exist. +*/ +static int test_db_readonly( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zDbName; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB DBNAME"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zDbName = Tcl_GetString(objv[2]); + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_db_readonly(db, zDbName))); + return TCL_OK; +} + +/* +** Usage: sqlite3_soft_heap_limit ?N? +** +** Query or set the soft heap limit for the current thread. The +** limit is only changed if the N is present. The previous limit +** is returned. +*/ +static int test_soft_heap_limit( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_int64 amt; + Tcl_WideInt N = -1; + if( objc!=1 && objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?N?"); + return TCL_ERROR; + } + if( objc==2 ){ + if( Tcl_GetWideIntFromObj(interp, objv[1], &N) ) return TCL_ERROR; + } + amt = sqlite3_soft_heap_limit64(N); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(amt)); + return TCL_OK; +} + +/* +** Usage: sqlite3_thread_cleanup +** +** Call the sqlite3_thread_cleanup API. +*/ +static int test_thread_cleanup( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_thread_cleanup(); +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_pager_refcounts DB +** +** Return a list of numbers which are the PagerRefcount for all +** pagers on each database connection. +*/ +static int test_pager_refcounts( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int i; + int v, *a; + Tcl_Obj *pResult; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + pResult = Tcl_NewObj(); + for(i=0; inDb; i++){ + if( db->aDb[i].pBt==0 ){ + v = -1; + }else{ + sqlite3_mutex_enter(db->mutex); + a = sqlite3PagerStats(sqlite3BtreePager(db->aDb[i].pBt)); + v = a[0]; + sqlite3_mutex_leave(db->mutex); + } + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(v)); + } + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + + +/* +** tclcmd: working_64bit_int +** +** Some TCL builds (ex: cygwin) do not support 64-bit integers. This +** leads to a number of test failures. The present command checks the +** TCL build to see whether or not it supports 64-bit integers. It +** returns TRUE if it does and FALSE if not. +** +** This command is used to warn users that their TCL build is defective +** and that the errors they are seeing in the test scripts might be +** a result of their defective TCL rather than problems in SQLite. +*/ +static int working_64bit_int( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_Obj *pTestObj; + int working = 0; + + pTestObj = Tcl_NewWideIntObj(1000000*(i64)1234567890); + working = strcmp(Tcl_GetString(pTestObj), "1234567890000000")==0; + Tcl_DecrRefCount(pTestObj); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(working)); + return TCL_OK; +} + + +/* +** tclcmd: vfs_unlink_test +** +** This TCL command unregisters the primary VFS and then registers +** it back again. This is used to test the ability to register a +** VFS when none are previously registered, and the ability to +** unregister the only available VFS. Ticket #2738 +*/ +static int vfs_unlink_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int i; + sqlite3_vfs *pMain; + sqlite3_vfs *apVfs[20]; + sqlite3_vfs one, two; + + sqlite3_vfs_unregister(0); /* Unregister of NULL is harmless */ + one.zName = "__one"; + two.zName = "__two"; + + /* Calling sqlite3_vfs_register with 2nd argument of 0 does not + ** change the default VFS + */ + pMain = sqlite3_vfs_find(0); + sqlite3_vfs_register(&one, 0); + assert( pMain==0 || pMain==sqlite3_vfs_find(0) ); + sqlite3_vfs_register(&two, 0); + assert( pMain==0 || pMain==sqlite3_vfs_find(0) ); + + /* We can find a VFS by its name */ + assert( sqlite3_vfs_find("__one")==&one ); + assert( sqlite3_vfs_find("__two")==&two ); + + /* Calling sqlite_vfs_register with non-zero second parameter changes the + ** default VFS, even if the 1st parameter is an existig VFS that is + ** previously registered as the non-default. + */ + sqlite3_vfs_register(&one, 1); + assert( sqlite3_vfs_find("__one")==&one ); + assert( sqlite3_vfs_find("__two")==&two ); + assert( sqlite3_vfs_find(0)==&one ); + sqlite3_vfs_register(&two, 1); + assert( sqlite3_vfs_find("__one")==&one ); + assert( sqlite3_vfs_find("__two")==&two ); + assert( sqlite3_vfs_find(0)==&two ); + if( pMain ){ + sqlite3_vfs_register(pMain, 1); + assert( sqlite3_vfs_find("__one")==&one ); + assert( sqlite3_vfs_find("__two")==&two ); + assert( sqlite3_vfs_find(0)==pMain ); + } + + /* Unlink the default VFS. Repeat until there are no more VFSes + ** registered. + */ + for(i=0; izName) ); + sqlite3_vfs_unregister(apVfs[i]); + assert( 0==sqlite3_vfs_find(apVfs[i]->zName) ); + } + } + assert( 0==sqlite3_vfs_find(0) ); + + /* Register the main VFS as non-default (will be made default, since + ** it'll be the only one in existence). + */ + sqlite3_vfs_register(pMain, 0); + assert( sqlite3_vfs_find(0)==pMain ); + + /* Un-register the main VFS again to restore an empty VFS list */ + sqlite3_vfs_unregister(pMain); + assert( 0==sqlite3_vfs_find(0) ); + + /* Relink all VFSes in reverse order. */ + for(i=sizeof(apVfs)/sizeof(apVfs[0])-1; i>=0; i--){ + if( apVfs[i] ){ + sqlite3_vfs_register(apVfs[i], 1); + assert( apVfs[i]==sqlite3_vfs_find(0) ); + assert( apVfs[i]==sqlite3_vfs_find(apVfs[i]->zName) ); + } + } + + /* Unregister out sample VFSes. */ + sqlite3_vfs_unregister(&one); + sqlite3_vfs_unregister(&two); + + /* Unregistering a VFS that is not currently registered is harmless */ + sqlite3_vfs_unregister(&one); + sqlite3_vfs_unregister(&two); + assert( sqlite3_vfs_find("__one")==0 ); + assert( sqlite3_vfs_find("__two")==0 ); + + /* We should be left with the original default VFS back as the + ** original */ + assert( sqlite3_vfs_find(0)==pMain ); + + return TCL_OK; +} + +/* +** tclcmd: vfs_initfail_test +** +** This TCL command attempts to vfs_find and vfs_register when the +** sqlite3_initialize() interface is failing. All calls should fail. +*/ +static int vfs_initfail_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_vfs one; + one.zName = "__one"; + + if( sqlite3_vfs_find(0) ) return TCL_ERROR; + sqlite3_vfs_register(&one, 0); + if( sqlite3_vfs_find(0) ) return TCL_ERROR; + sqlite3_vfs_register(&one, 1); + if( sqlite3_vfs_find(0) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Saved VFSes +*/ +static sqlite3_vfs *apVfs[20]; +static int nVfs = 0; + +/* +** tclcmd: vfs_unregister_all +** +** Unregister all VFSes. +*/ +static int vfs_unregister_all( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int i; + for(i=0; ipNext){ + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(pVfs->zName, -1)); + } + Tcl_SetObjResult(interp, pRet); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_limit DB ID VALUE +** +** This TCL command runs the sqlite3_limit interface and +** verifies correct operation of the same. +*/ +static int test_limit( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + int rc; + static const struct { + char *zName; + int id; + } aId[] = { + { "SQLITE_LIMIT_LENGTH", SQLITE_LIMIT_LENGTH }, + { "SQLITE_LIMIT_SQL_LENGTH", SQLITE_LIMIT_SQL_LENGTH }, + { "SQLITE_LIMIT_COLUMN", SQLITE_LIMIT_COLUMN }, + { "SQLITE_LIMIT_EXPR_DEPTH", SQLITE_LIMIT_EXPR_DEPTH }, + { "SQLITE_LIMIT_COMPOUND_SELECT", SQLITE_LIMIT_COMPOUND_SELECT }, + { "SQLITE_LIMIT_VDBE_OP", SQLITE_LIMIT_VDBE_OP }, + { "SQLITE_LIMIT_FUNCTION_ARG", SQLITE_LIMIT_FUNCTION_ARG }, + { "SQLITE_LIMIT_ATTACHED", SQLITE_LIMIT_ATTACHED }, + { "SQLITE_LIMIT_LIKE_PATTERN_LENGTH", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, + { "SQLITE_LIMIT_VARIABLE_NUMBER", SQLITE_LIMIT_VARIABLE_NUMBER }, + { "SQLITE_LIMIT_TRIGGER_DEPTH", SQLITE_LIMIT_TRIGGER_DEPTH }, + + /* Out of range test cases */ + { "SQLITE_LIMIT_TOOSMALL", -1, }, + { "SQLITE_LIMIT_TOOBIG", SQLITE_LIMIT_TRIGGER_DEPTH+1 }, + }; + int i, id; + int val; + const char *zId; + + if( objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " DB ID VALUE", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zId = Tcl_GetString(objv[2]); + for(i=0; i=sizeof(aId)/sizeof(aId[0]) ){ + Tcl_AppendResult(interp, "unknown limit type: ", zId, (char*)0); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[3], &val) ) return TCL_ERROR; + rc = sqlite3_limit(db, id, val); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: save_prng_state +** +** Save the state of the pseudo-random number generator. +** At the same time, verify that sqlite3_test_control works even when +** called with an out-of-range opcode. +*/ +static int save_prng_state( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int rc = sqlite3_test_control(9999); + assert( rc==0 ); + rc = sqlite3_test_control(-1); + assert( rc==0 ); + sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SAVE); + return TCL_OK; +} +/* +** tclcmd: restore_prng_state +*/ +static int restore_prng_state( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_test_control(SQLITE_TESTCTRL_PRNG_RESTORE); + return TCL_OK; +} +/* +** tclcmd: reset_prng_state +*/ +static int reset_prng_state( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_test_control(SQLITE_TESTCTRL_PRNG_RESET); + return TCL_OK; +} + +/* +** tclcmd: pcache_stats +*/ +static int test_pcache_stats( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int nMin; + int nMax; + int nCurrent; + int nRecyclable; + Tcl_Obj *pRet; + + sqlite3PcacheStats(&nCurrent, &nMax, &nMin, &nRecyclable); + + pRet = Tcl_NewObj(); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("current", -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nCurrent)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("max", -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nMax)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("min", -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nMin)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("recyclable", -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nRecyclable)); + + Tcl_SetObjResult(interp, pRet); + + return TCL_OK; +} + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY +static void test_unlock_notify_cb(void **aArg, int nArg){ + int ii; + for(ii=0; ii2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SCRIPT"); + return TCL_ERROR; + } + if( logcallback.pObj ){ + Tcl_DecrRefCount(logcallback.pObj); + logcallback.pObj = 0; + logcallback.pInterp = 0; + sqlite3_config(SQLITE_CONFIG_LOG, 0, 0); + } + if( objc>1 ){ + logcallback.pObj = objv[1]; + Tcl_IncrRefCount(logcallback.pObj); + logcallback.pInterp = interp; + sqlite3_config(SQLITE_CONFIG_LOG, xLogcallback, 0); + } + return TCL_OK; +} + +/* +** tcl_objproc COMMANDNAME ARGS... +** +** Run a TCL command using its objProc interface. Throw an error if +** the command has no objProc interface. +*/ +static int runAsObjProc( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_CmdInfo cmdInfo; + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "COMMAND ..."); + return TCL_ERROR; + } + if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){ + Tcl_AppendResult(interp, "command not found: ", + Tcl_GetString(objv[1]), (char*)0); + return TCL_ERROR; + } + if( cmdInfo.objProc==0 ){ + Tcl_AppendResult(interp, "command has no objProc: ", + Tcl_GetString(objv[1]), (char*)0); + return TCL_ERROR; + } + return cmdInfo.objProc(cmdInfo.objClientData, interp, objc-1, objv+1); +} + +#ifndef SQLITE_OMIT_EXPLAIN +/* +** WARNING: The following function, printExplainQueryPlan() is an exact +** copy of example code from eqp.in (eqp.html). If this code is modified, +** then the documentation copy needs to be modified as well. +*/ +/* +** Argument pStmt is a prepared SQL statement. This function compiles +** an EXPLAIN QUERY PLAN command to report on the prepared statement, +** and prints the report to stdout using printf(). +*/ +int printExplainQueryPlan(sqlite3_stmt *pStmt){ + const char *zSql; /* Input SQL */ + char *zExplain; /* SQL with EXPLAIN QUERY PLAN prepended */ + sqlite3_stmt *pExplain; /* Compiled EXPLAIN QUERY PLAN command */ + int rc; /* Return code from sqlite3_prepare_v2() */ + + zSql = sqlite3_sql(pStmt); + if( zSql==0 ) return SQLITE_ERROR; + + zExplain = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zSql); + if( zExplain==0 ) return SQLITE_NOMEM; + + rc = sqlite3_prepare_v2(sqlite3_db_handle(pStmt), zExplain, -1, &pExplain, 0); + sqlite3_free(zExplain); + if( rc!=SQLITE_OK ) return rc; + + while( SQLITE_ROW==sqlite3_step(pExplain) ){ + int iSelectid = sqlite3_column_int(pExplain, 0); + int iOrder = sqlite3_column_int(pExplain, 1); + int iFrom = sqlite3_column_int(pExplain, 2); + const char *zDetail = (const char *)sqlite3_column_text(pExplain, 3); + + printf("%d %d %d %s\n", iSelectid, iOrder, iFrom, zDetail); + } + + return sqlite3_finalize(pExplain); +} + +static int test_print_eqp( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + rc = printExplainQueryPlan(pStmt); + /* This is needed on Windows so that a test case using this + ** function can open a read pipe and get the output of + ** printExplainQueryPlan() immediately. + */ + fflush(stdout); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} +#endif /* SQLITE_OMIT_EXPLAIN */ + +/* +** sqlite3_test_control VERB ARGS... +*/ +static int test_test_control( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct Verb { + const char *zName; + int i; + } aVerb[] = { + { "SQLITE_TESTCTRL_LOCALTIME_FAULT", SQLITE_TESTCTRL_LOCALTIME_FAULT }, + }; + int iVerb; + int iFlag; + int rc; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "VERB ARGS..."); + return TCL_ERROR; + } + + rc = Tcl_GetIndexFromObjStruct( + interp, objv[1], aVerb, sizeof(aVerb[0]), "VERB", 0, &iVerb + ); + if( rc!=TCL_OK ) return rc; + + iFlag = aVerb[iVerb].i; + switch( iFlag ){ + case SQLITE_TESTCTRL_LOCALTIME_FAULT: { + int val; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "ONOFF"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR; + sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, val); + break; + } + } + + Tcl_ResetResult(interp); + return TCL_OK; +} + +#if SQLITE_OS_UNIX +#include +#include + +static int test_getrusage( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + char buf[1024]; + struct rusage r; + memset(&r, 0, sizeof(r)); + getrusage(RUSAGE_SELF, &r); + + sprintf(buf, "ru_utime=%d.%06d ru_stime=%d.%06d ru_minflt=%d ru_majflt=%d", + (int)r.ru_utime.tv_sec, (int)r.ru_utime.tv_usec, + (int)r.ru_stime.tv_sec, (int)r.ru_stime.tv_usec, + (int)r.ru_minflt, (int)r.ru_majflt + ); + Tcl_SetObjResult(interp, Tcl_NewStringObj(buf, -1)); + return TCL_OK; +} +#endif + +#if SQLITE_OS_WIN +/* +** Information passed from the main thread into the windows file locker +** background thread. +*/ +struct win32FileLocker { + char *evName; /* Name of event to signal thread startup */ + HANDLE h; /* Handle of the file to be locked */ + int delay1; /* Delay before locking */ + int delay2; /* Delay before unlocking */ + int ok; /* Finished ok */ + int err; /* True if an error occurs */ +}; +#endif + + +#if SQLITE_OS_WIN +#include +/* +** The background thread that does file locking. +*/ +static void win32_file_locker(void *pAppData){ + struct win32FileLocker *p = (struct win32FileLocker*)pAppData; + if( p->evName ){ + HANDLE ev = OpenEvent(EVENT_MODIFY_STATE, FALSE, p->evName); + if ( ev ){ + SetEvent(ev); + CloseHandle(ev); + } + } + if( p->delay1 ) Sleep(p->delay1); + if( LockFile(p->h, 0, 0, 100000000, 0) ){ + Sleep(p->delay2); + UnlockFile(p->h, 0, 0, 100000000, 0); + p->ok = 1; + }else{ + p->err = 1; + } + CloseHandle(p->h); + p->h = 0; + p->delay1 = 0; + p->delay2 = 0; +} +#endif + +#if SQLITE_OS_WIN +/* +** lock_win32_file FILENAME DELAY1 DELAY2 +** +** Get an exclusive manditory lock on file for DELAY2 milliseconds. +** Wait DELAY1 milliseconds before acquiring the lock. +*/ +static int win32_file_lock( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + static struct win32FileLocker x = { "win32_file_lock", 0, 0, 0, 0, 0 }; + const char *zFilename; + char zBuf[200]; + int retry = 0; + HANDLE ev; + DWORD wResult; + + if( objc!=4 && objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME DELAY1 DELAY2"); + return TCL_ERROR; + } + if( objc==1 ){ + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d %d %d %d %d", + x.ok, x.err, x.delay1, x.delay2, x.h); + Tcl_AppendResult(interp, zBuf, (char*)0); + return TCL_OK; + } + while( x.h && retry<30 ){ + retry++; + Sleep(100); + } + if( x.h ){ + Tcl_AppendResult(interp, "busy", (char*)0); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[2], &x.delay1) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &x.delay2) ) return TCL_ERROR; + zFilename = Tcl_GetString(objv[1]); + x.h = CreateFile(zFilename, GENERIC_READ|GENERIC_WRITE, + FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, 0); + if( !x.h ){ + Tcl_AppendResult(interp, "cannot open file: ", zFilename, (char*)0); + return TCL_ERROR; + } + ev = CreateEvent(NULL, TRUE, FALSE, x.evName); + if ( !ev ){ + Tcl_AppendResult(interp, "cannot create event: ", x.evName, (char*)0); + return TCL_ERROR; + } + _beginthread(win32_file_locker, 0, (void*)&x); + Sleep(0); + if ( (wResult = WaitForSingleObject(ev, 10000))!=WAIT_OBJECT_0 ){ + sqlite3_snprintf(sizeof(zBuf), zBuf, "0x%x", wResult); + Tcl_AppendResult(interp, "wait failed: ", zBuf, (char*)0); + CloseHandle(ev); + return TCL_ERROR; + } + CloseHandle(ev); + return TCL_OK; +} + +/* +** exists_win32_path PATH +** +** Returns non-zero if the specified path exists, whose fully qualified name +** may exceed 260 characters if it is prefixed with "\\?\". +*/ +static int win32_exists_path( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PATH"); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewBooleanObj( + GetFileAttributesW( Tcl_GetUnicode(objv[1]))!=INVALID_FILE_ATTRIBUTES )); + return TCL_OK; +} + +/* +** find_win32_file PATTERN +** +** Returns a list of entries in a directory that match the specified pattern, +** whose fully qualified name may exceed 248 characters if it is prefixed with +** "\\?\". +*/ +static int win32_find_file( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + HANDLE hFindFile = INVALID_HANDLE_VALUE; + WIN32_FIND_DATAW findData; + Tcl_Obj *listObj; + DWORD lastErrno; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PATTERN"); + return TCL_ERROR; + } + hFindFile = FindFirstFileW(Tcl_GetUnicode(objv[1]), &findData); + if( hFindFile==INVALID_HANDLE_VALUE ){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + listObj = Tcl_NewObj(); + Tcl_IncrRefCount(listObj); + do { + Tcl_ListObjAppendElement(interp, listObj, Tcl_NewUnicodeObj( + findData.cFileName, -1)); + Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj( + findData.dwFileAttributes)); + } while( FindNextFileW(hFindFile, &findData) ); + lastErrno = GetLastError(); + if( lastErrno!=NO_ERROR && lastErrno!=ERROR_NO_MORE_FILES ){ + FindClose(hFindFile); + Tcl_DecrRefCount(listObj); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + FindClose(hFindFile); + Tcl_SetObjResult(interp, listObj); + return TCL_OK; +} + +/* +** delete_win32_file FILENAME +** +** Deletes the specified file, whose fully qualified name may exceed 260 +** characters if it is prefixed with "\\?\". +*/ +static int win32_delete_file( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } + if( !DeleteFileW(Tcl_GetUnicode(objv[1])) ){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + Tcl_ResetResult(interp); + return TCL_OK; +} + +/* +** make_win32_dir DIRECTORY +** +** Creates the specified directory, whose fully qualified name may exceed 248 +** characters if it is prefixed with "\\?\". +*/ +static int win32_mkdir( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DIRECTORY"); + return TCL_ERROR; + } + if( !CreateDirectoryW(Tcl_GetUnicode(objv[1]), NULL) ){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + Tcl_ResetResult(interp); + return TCL_OK; +} + +/* +** remove_win32_dir DIRECTORY +** +** Removes the specified directory, whose fully qualified name may exceed 248 +** characters if it is prefixed with "\\?\". +*/ +static int win32_rmdir( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DIRECTORY"); + return TCL_ERROR; + } + if( !RemoveDirectoryW(Tcl_GetUnicode(objv[1])) ){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + Tcl_ResetResult(interp); + return TCL_OK; +} +#endif + + +/* +** optimization_control DB OPT BOOLEAN +** +** Enable or disable query optimizations using the sqlite3_test_control() +** interface. Disable if BOOLEAN is false and enable if BOOLEAN is true. +** OPT is the name of the optimization to be disabled. +*/ +static int optimization_control( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int i; + sqlite3 *db; + const char *zOpt; + int onoff; + int mask = 0; + static const struct { + const char *zOptName; + int mask; + } aOpt[] = { + { "all", SQLITE_AllOpts }, + { "none", 0 }, + { "query-flattener", SQLITE_QueryFlattener }, + { "column-cache", SQLITE_ColumnCache }, + { "groupby-order", SQLITE_GroupByOrder }, + { "factor-constants", SQLITE_FactorOutConst }, + { "real-as-int", SQLITE_IdxRealAsInt }, + { "distinct-opt", SQLITE_DistinctOpt }, + { "cover-idx-scan", SQLITE_CoverIdxScan }, + { "order-by-idx-join", SQLITE_OrderByIdxJoin }, + { "transitive", SQLITE_Transitive }, + { "subquery-coroutine", SQLITE_SubqCoroutine }, + { "omit-noop-join", SQLITE_OmitNoopJoin }, + { "stat3", SQLITE_Stat3 }, + }; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB OPT BOOLEAN"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( Tcl_GetBooleanFromObj(interp, objv[3], &onoff) ) return TCL_ERROR; + zOpt = Tcl_GetString(objv[2]); + for(i=0; i=sizeof(aOpt)/sizeof(aOpt[0]) ){ + Tcl_AppendResult(interp, "unknown optimization - should be one of:", + (char*)0); + for(i=0; i=ArraySize(aExtension) ){ + Tcl_AppendResult(interp, "no such extension: ", zName, (char*)0); + return TCL_ERROR; + } + rc = aExtension[i].pInit(db, &zErrMsg, 0); + if( rc!=SQLITE_OK || zErrMsg ){ + Tcl_AppendResult(interp, "initialization of ", zName, " failed: ", zErrMsg, + (char*)0); + sqlite3_free(zErrMsg); + return TCL_ERROR; + } + } + return TCL_OK; +} + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest1_Init(Tcl_Interp *interp){ + extern int sqlite3_search_count; + extern int sqlite3_found_count; + extern int sqlite3_interrupt_count; + extern int sqlite3_open_file_count; + extern int sqlite3_sort_count; + extern int sqlite3_current_time; +#if SQLITE_OS_UNIX && defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE + extern int sqlite3_hostid_num; +#endif + extern int sqlite3_max_blobsize; + extern int sqlite3BtreeSharedCacheReport(void*, + Tcl_Interp*,int,Tcl_Obj*CONST*); + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "db_enter", (Tcl_CmdProc*)db_enter }, + { "db_leave", (Tcl_CmdProc*)db_leave }, + { "sqlite3_mprintf_int", (Tcl_CmdProc*)sqlite3_mprintf_int }, + { "sqlite3_mprintf_int64", (Tcl_CmdProc*)sqlite3_mprintf_int64 }, + { "sqlite3_mprintf_long", (Tcl_CmdProc*)sqlite3_mprintf_long }, + { "sqlite3_mprintf_str", (Tcl_CmdProc*)sqlite3_mprintf_str }, + { "sqlite3_snprintf_str", (Tcl_CmdProc*)sqlite3_snprintf_str }, + { "sqlite3_mprintf_stronly", (Tcl_CmdProc*)sqlite3_mprintf_stronly}, + { "sqlite3_mprintf_double", (Tcl_CmdProc*)sqlite3_mprintf_double }, + { "sqlite3_mprintf_scaled", (Tcl_CmdProc*)sqlite3_mprintf_scaled }, + { "sqlite3_mprintf_hexdouble", (Tcl_CmdProc*)sqlite3_mprintf_hexdouble}, + { "sqlite3_mprintf_z_test", (Tcl_CmdProc*)test_mprintf_z }, + { "sqlite3_mprintf_n_test", (Tcl_CmdProc*)test_mprintf_n }, + { "sqlite3_snprintf_int", (Tcl_CmdProc*)test_snprintf_int }, + { "sqlite3_last_insert_rowid", (Tcl_CmdProc*)test_last_rowid }, + { "sqlite3_exec_printf", (Tcl_CmdProc*)test_exec_printf }, + { "sqlite3_exec_hex", (Tcl_CmdProc*)test_exec_hex }, + { "sqlite3_exec", (Tcl_CmdProc*)test_exec }, + { "sqlite3_exec_nr", (Tcl_CmdProc*)test_exec_nr }, +#ifndef SQLITE_OMIT_GET_TABLE + { "sqlite3_get_table_printf", (Tcl_CmdProc*)test_get_table_printf }, +#endif + { "sqlite3_close", (Tcl_CmdProc*)sqlite_test_close }, + { "sqlite3_close_v2", (Tcl_CmdProc*)sqlite_test_close_v2 }, + { "sqlite3_create_function", (Tcl_CmdProc*)test_create_function }, + { "sqlite3_create_aggregate", (Tcl_CmdProc*)test_create_aggregate }, + { "sqlite_register_test_function", (Tcl_CmdProc*)test_register_func }, + { "sqlite_abort", (Tcl_CmdProc*)sqlite_abort }, + { "sqlite_bind", (Tcl_CmdProc*)test_bind }, + { "breakpoint", (Tcl_CmdProc*)test_breakpoint }, + { "sqlite3_key", (Tcl_CmdProc*)test_key }, + { "sqlite3_rekey", (Tcl_CmdProc*)test_rekey }, + { "sqlite_set_magic", (Tcl_CmdProc*)sqlite_set_magic }, + { "sqlite3_interrupt", (Tcl_CmdProc*)test_interrupt }, + { "sqlite_delete_function", (Tcl_CmdProc*)delete_function }, + { "sqlite_delete_collation", (Tcl_CmdProc*)delete_collation }, + { "sqlite3_get_autocommit", (Tcl_CmdProc*)get_autocommit }, + { "sqlite3_stack_used", (Tcl_CmdProc*)test_stack_used }, + { "sqlite3_busy_timeout", (Tcl_CmdProc*)test_busy_timeout }, + { "printf", (Tcl_CmdProc*)test_printf }, + { "sqlite3IoTrace", (Tcl_CmdProc*)test_io_trace }, + }; + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "sqlite3_connection_pointer", get_sqlite_pointer, 0 }, + { "sqlite3_bind_int", test_bind_int, 0 }, + { "sqlite3_bind_zeroblob", test_bind_zeroblob, 0 }, + { "sqlite3_bind_int64", test_bind_int64, 0 }, + { "sqlite3_bind_double", test_bind_double, 0 }, + { "sqlite3_bind_null", test_bind_null ,0 }, + { "sqlite3_bind_text", test_bind_text ,0 }, + { "sqlite3_bind_text16", test_bind_text16 ,0 }, + { "sqlite3_bind_blob", test_bind_blob ,0 }, + { "sqlite3_bind_parameter_count", test_bind_parameter_count, 0}, + { "sqlite3_bind_parameter_name", test_bind_parameter_name, 0}, + { "sqlite3_bind_parameter_index", test_bind_parameter_index, 0}, + { "sqlite3_clear_bindings", test_clear_bindings, 0}, + { "sqlite3_sleep", test_sleep, 0}, + { "sqlite3_errcode", test_errcode ,0 }, + { "sqlite3_extended_errcode", test_ex_errcode ,0 }, + { "sqlite3_errmsg", test_errmsg ,0 }, + { "sqlite3_errmsg16", test_errmsg16 ,0 }, + { "sqlite3_open", test_open ,0 }, + { "sqlite3_open16", test_open16 ,0 }, + { "sqlite3_open_v2", test_open_v2 ,0 }, + { "sqlite3_complete16", test_complete16 ,0 }, + + { "sqlite3_prepare", test_prepare ,0 }, + { "sqlite3_prepare16", test_prepare16 ,0 }, + { "sqlite3_prepare_v2", test_prepare_v2 ,0 }, + { "sqlite3_prepare_tkt3134", test_prepare_tkt3134, 0}, + { "sqlite3_prepare16_v2", test_prepare16_v2 ,0 }, + { "sqlite3_finalize", test_finalize ,0 }, + { "sqlite3_stmt_status", test_stmt_status ,0 }, + { "sqlite3_reset", test_reset ,0 }, + { "sqlite3_expired", test_expired ,0 }, + { "sqlite3_transfer_bindings", test_transfer_bind ,0 }, + { "sqlite3_changes", test_changes ,0 }, + { "sqlite3_step", test_step ,0 }, + { "sqlite3_sql", test_sql ,0 }, + { "sqlite3_next_stmt", test_next_stmt ,0 }, + { "sqlite3_stmt_readonly", test_stmt_readonly ,0 }, + { "sqlite3_stmt_busy", test_stmt_busy ,0 }, + { "uses_stmt_journal", uses_stmt_journal ,0 }, + + { "sqlite3_release_memory", test_release_memory, 0}, + { "sqlite3_db_release_memory", test_db_release_memory, 0}, + { "sqlite3_db_filename", test_db_filename, 0}, + { "sqlite3_db_readonly", test_db_readonly, 0}, + { "sqlite3_soft_heap_limit", test_soft_heap_limit, 0}, + { "sqlite3_thread_cleanup", test_thread_cleanup, 0}, + { "sqlite3_pager_refcounts", test_pager_refcounts, 0}, + + { "sqlite3_load_extension", test_load_extension, 0}, + { "sqlite3_enable_load_extension", test_enable_load, 0}, + { "sqlite3_extended_result_codes", test_extended_result_codes, 0}, + { "sqlite3_limit", test_limit, 0}, + + { "save_prng_state", save_prng_state, 0 }, + { "restore_prng_state", restore_prng_state, 0 }, + { "reset_prng_state", reset_prng_state, 0 }, + { "optimization_control", optimization_control,0}, +#if SQLITE_OS_WIN + { "lock_win32_file", win32_file_lock, 0 }, + { "exists_win32_path", win32_exists_path, 0 }, + { "find_win32_file", win32_find_file, 0 }, + { "delete_win32_file", win32_delete_file, 0 }, + { "make_win32_dir", win32_mkdir, 0 }, + { "remove_win32_dir", win32_rmdir, 0 }, +#endif + { "tcl_objproc", runAsObjProc, 0 }, + + /* sqlite3_column_*() API */ + { "sqlite3_column_count", test_column_count ,0 }, + { "sqlite3_data_count", test_data_count ,0 }, + { "sqlite3_column_type", test_column_type ,0 }, + { "sqlite3_column_blob", test_column_blob ,0 }, + { "sqlite3_column_double", test_column_double ,0 }, + { "sqlite3_column_int64", test_column_int64 ,0 }, + { "sqlite3_column_text", test_stmt_utf8, (void*)sqlite3_column_text }, + { "sqlite3_column_name", test_stmt_utf8, (void*)sqlite3_column_name }, + { "sqlite3_column_int", test_stmt_int, (void*)sqlite3_column_int }, + { "sqlite3_column_bytes", test_stmt_int, (void*)sqlite3_column_bytes}, +#ifndef SQLITE_OMIT_DECLTYPE + { "sqlite3_column_decltype",test_stmt_utf8,(void*)sqlite3_column_decltype}, +#endif +#ifdef SQLITE_ENABLE_COLUMN_METADATA +{ "sqlite3_column_database_name",test_stmt_utf8,(void*)sqlite3_column_database_name}, +{ "sqlite3_column_table_name",test_stmt_utf8,(void*)sqlite3_column_table_name}, +{ "sqlite3_column_origin_name",test_stmt_utf8,(void*)sqlite3_column_origin_name}, +#endif + +#ifndef SQLITE_OMIT_UTF16 + { "sqlite3_column_bytes16", test_stmt_int, (void*)sqlite3_column_bytes16 }, + { "sqlite3_column_text16", test_stmt_utf16, (void*)sqlite3_column_text16}, + { "sqlite3_column_name16", test_stmt_utf16, (void*)sqlite3_column_name16}, + { "add_alignment_test_collations", add_alignment_test_collations, 0 }, +#ifndef SQLITE_OMIT_DECLTYPE + { "sqlite3_column_decltype16",test_stmt_utf16,(void*)sqlite3_column_decltype16}, +#endif +#ifdef SQLITE_ENABLE_COLUMN_METADATA +{"sqlite3_column_database_name16", + test_stmt_utf16, (void*)sqlite3_column_database_name16}, +{"sqlite3_column_table_name16", test_stmt_utf16, (void*)sqlite3_column_table_name16}, +{"sqlite3_column_origin_name16", test_stmt_utf16, (void*)sqlite3_column_origin_name16}, +#endif +#endif + { "sqlite3_create_collation_v2", test_create_collation_v2, 0 }, + { "sqlite3_global_recover", test_global_recover, 0 }, + { "working_64bit_int", working_64bit_int, 0 }, + { "vfs_unlink_test", vfs_unlink_test, 0 }, + { "vfs_initfail_test", vfs_initfail_test, 0 }, + { "vfs_unregister_all", vfs_unregister_all, 0 }, + { "vfs_reregister_all", vfs_reregister_all, 0 }, + { "file_control_test", file_control_test, 0 }, + { "file_control_lasterrno_test", file_control_lasterrno_test, 0 }, + { "file_control_lockproxy_test", file_control_lockproxy_test, 0 }, + { "file_control_chunksize_test", file_control_chunksize_test, 0 }, + { "file_control_sizehint_test", file_control_sizehint_test, 0 }, + { "file_control_win32_av_retry", file_control_win32_av_retry, 0 }, + { "file_control_persist_wal", file_control_persist_wal, 0 }, + { "file_control_powersafe_overwrite",file_control_powersafe_overwrite,0}, + { "file_control_vfsname", file_control_vfsname, 0 }, + { "file_control_tempfilename", file_control_tempfilename, 0 }, + { "sqlite3_vfs_list", vfs_list, 0 }, + { "sqlite3_create_function_v2", test_create_function_v2, 0 }, + + /* Functions from os.h */ +#ifndef SQLITE_OMIT_UTF16 + { "add_test_collate", test_collate, 0 }, + { "add_test_collate_needed", test_collate_needed, 0 }, + { "add_test_function", test_function, 0 }, +#endif + { "sqlite3_test_errstr", test_errstr, 0 }, + { "tcl_variable_type", tcl_variable_type, 0 }, +#ifndef SQLITE_OMIT_SHARED_CACHE + { "sqlite3_enable_shared_cache", test_enable_shared, 0 }, + { "sqlite3_shared_cache_report", sqlite3BtreeSharedCacheReport, 0}, +#endif + { "sqlite3_libversion_number", test_libversion_number, 0 }, +#ifdef SQLITE_ENABLE_COLUMN_METADATA + { "sqlite3_table_column_metadata", test_table_column_metadata, 0 }, +#endif +#ifndef SQLITE_OMIT_INCRBLOB + { "sqlite3_blob_read", test_blob_read, 0 }, + { "sqlite3_blob_write", test_blob_write, 0 }, + { "sqlite3_blob_reopen", test_blob_reopen, 0 }, + { "sqlite3_blob_bytes", test_blob_bytes, 0 }, + { "sqlite3_blob_close", test_blob_close, 0 }, +#endif + { "pcache_stats", test_pcache_stats, 0 }, +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + { "sqlite3_unlock_notify", test_unlock_notify, 0 }, +#endif + { "sqlite3_wal_checkpoint", test_wal_checkpoint, 0 }, + { "sqlite3_wal_checkpoint_v2",test_wal_checkpoint_v2, 0 }, + { "test_sqlite3_log", test_sqlite3_log, 0 }, +#ifndef SQLITE_OMIT_EXPLAIN + { "print_explain_query_plan", test_print_eqp, 0 }, +#endif + { "sqlite3_test_control", test_test_control }, +#if SQLITE_OS_UNIX + { "getrusage", test_getrusage }, +#endif + { "load_static_extension", tclLoadStaticExtensionCmd }, + }; + static int bitmask_size = sizeof(Bitmask)*8; + int i; + extern int sqlite3_sync_count, sqlite3_fullsync_count; + extern int sqlite3_opentemp_count; + extern int sqlite3_like_count; + extern int sqlite3_xferopt_count; + extern int sqlite3_pager_readdb_count; + extern int sqlite3_pager_writedb_count; + extern int sqlite3_pager_writej_count; +#if SQLITE_OS_WIN + extern int sqlite3_os_type; +#endif +#ifdef SQLITE_DEBUG + extern int sqlite3WhereTrace; + extern int sqlite3OSTrace; + extern int sqlite3WalTrace; +#endif +#ifdef SQLITE_TEST +#ifdef SQLITE_ENABLE_FTS3 + extern int sqlite3_fts3_enable_parentheses; +#endif +#endif + + for(i=0; i +#include +#include "finsh.h" + +static int callback(void *NotUsed, int argc, char **argv, char **azColName){ + int i; + for(i=0; i +#include +#include + +extern const char *sqlite3ErrName(int); + +/* +** Page size and reserved size used for testing. +*/ +static int test_pagesize = 1024; + +/* +** Dummy page reinitializer +*/ +static void pager_test_reiniter(DbPage *pNotUsed){ + return; +} + +/* +** Usage: pager_open FILENAME N-PAGE +** +** Open a new pager +*/ +static int pager_open( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + u32 pageSize; + Pager *pPager; + int nPage; + int rc; + char zBuf[100]; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FILENAME N-PAGE\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[2], &nPage) ) return TCL_ERROR; + rc = sqlite3PagerOpen(sqlite3_vfs_find(0), &pPager, argv[1], 0, 0, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MAIN_DB, + pager_test_reiniter); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3PagerSetCachesize(pPager, nPage); + pageSize = test_pagesize; + sqlite3PagerSetPagesize(pPager, &pageSize, -1); + sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPager); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: pager_close ID +** +** Close the given pager. +*/ +static int pager_close( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerClose(pPager); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_rollback ID +** +** Rollback changes +*/ +static int pager_rollback( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerRollback(pPager); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_commit ID +** +** Commit all changes +*/ +static int pager_commit( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerCommitPhaseOne(pPager, 0, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + rc = sqlite3PagerCommitPhaseTwo(pPager); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_stmt_begin ID +** +** Start a new checkpoint. +*/ +static int pager_stmt_begin( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerOpenSavepoint(pPager, 1); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_stmt_rollback ID +** +** Rollback changes to a checkpoint +*/ +static int pager_stmt_rollback( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, 0); + sqlite3PagerSavepoint(pPager, SAVEPOINT_RELEASE, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_stmt_commit ID +** +** Commit changes to a checkpoint +*/ +static int pager_stmt_commit( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_RELEASE, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_stats ID +** +** Return pager statistics. +*/ +static int pager_stats( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int i, *a; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + a = sqlite3PagerStats(pPager); + for(i=0; i<9; i++){ + static char *zName[] = { + "ref", "page", "max", "size", "state", "err", + "hit", "miss", "ovfl", + }; + char zBuf[100]; + Tcl_AppendElement(interp, zName[i]); + sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",a[i]); + Tcl_AppendElement(interp, zBuf); + } + return TCL_OK; +} + +/* +** Usage: pager_pagecount ID +** +** Return the size of the database file. +*/ +static int pager_pagecount( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + char zBuf[100]; + int nPage; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + sqlite3PagerPagecount(pPager, &nPage); + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nPage); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: page_get ID PGNO +** +** Return a pointer to a page from the database. +*/ +static int page_get( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + char zBuf[100]; + DbPage *pPage; + int pgno; + int rc; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID PGNO\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &pgno) ) return TCL_ERROR; + rc = sqlite3PagerSharedLock(pPager); + if( rc==SQLITE_OK ){ + rc = sqlite3PagerGet(pPager, pgno, &pPage); + } + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPage); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: page_lookup ID PGNO +** +** Return a pointer to a page if the page is already in cache. +** If not in cache, return an empty string. +*/ +static int page_lookup( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + char zBuf[100]; + DbPage *pPage; + int pgno; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID PGNO\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &pgno) ) return TCL_ERROR; + pPage = sqlite3PagerLookup(pPager, pgno); + if( pPage ){ + sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPage); + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +/* +** Usage: pager_truncate ID PGNO +*/ +static int pager_truncate( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int pgno; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID PGNO\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &pgno) ) return TCL_ERROR; + sqlite3PagerTruncateImage(pPager, pgno); + return TCL_OK; +} + + +/* +** Usage: page_unref PAGE +** +** Drop a pointer to a page. +*/ +static int page_unref( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + DbPage *pPage; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PAGE\"", 0); + return TCL_ERROR; + } + pPage = (DbPage *)sqlite3TestTextToPtr(argv[1]); + sqlite3PagerUnref(pPage); + return TCL_OK; +} + +/* +** Usage: page_read PAGE +** +** Return the content of a page +*/ +static int page_read( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + char zBuf[100]; + DbPage *pPage; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PAGE\"", 0); + return TCL_ERROR; + } + pPage = sqlite3TestTextToPtr(argv[1]); + memcpy(zBuf, sqlite3PagerGetData(pPage), sizeof(zBuf)); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: page_number PAGE +** +** Return the page number for a page. +*/ +static int page_number( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + char zBuf[100]; + DbPage *pPage; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PAGE\"", 0); + return TCL_ERROR; + } + pPage = (DbPage *)sqlite3TestTextToPtr(argv[1]); + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", sqlite3PagerPagenumber(pPage)); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: page_write PAGE DATA +** +** Write something into a page. +*/ +static int page_write( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + DbPage *pPage; + char *pData; + int rc; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PAGE DATA\"", 0); + return TCL_ERROR; + } + pPage = (DbPage *)sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerWrite(pPage); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + pData = sqlite3PagerGetData(pPage); + strncpy(pData, argv[2], test_pagesize-1); + pData[test_pagesize-1] = 0; + return TCL_OK; +} + +#ifndef SQLITE_OMIT_DISKIO +/* +** Usage: fake_big_file N FILENAME +** +** Write a few bytes at the N megabyte point of FILENAME. This will +** create a large file. If the file was a valid SQLite database, then +** the next time the database is opened, SQLite will begin allocating +** new pages after N. If N is 2096 or bigger, this will test the +** ability of SQLite to write to large files. +*/ +static int fake_big_file( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + sqlite3_vfs *pVfs; + sqlite3_file *fd = 0; + int rc; + int n; + i64 offset; + char *zFile; + int nFile; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " N-MEGABYTES FILE\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[1], &n) ) return TCL_ERROR; + + pVfs = sqlite3_vfs_find(0); + nFile = (int)strlen(argv[2]); + zFile = sqlite3_malloc( nFile+2 ); + if( zFile==0 ) return TCL_ERROR; + memcpy(zFile, argv[2], nFile+1); + zFile[nFile+1] = 0; + rc = sqlite3OsOpenMalloc(pVfs, zFile, &fd, + (SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB), 0 + ); + if( rc ){ + Tcl_AppendResult(interp, "open failed: ", sqlite3ErrName(rc), 0); + sqlite3_free(zFile); + return TCL_ERROR; + } + offset = n; + offset *= 1024*1024; + rc = sqlite3OsWrite(fd, "Hello, World!", 14, offset); + sqlite3OsCloseFree(fd); + sqlite3_free(zFile); + if( rc ){ + Tcl_AppendResult(interp, "write failed: ", sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} +#endif + + +/* +** test_control_pending_byte PENDING_BYTE +** +** Set the PENDING_BYTE using the sqlite3_test_control() interface. +*/ +static int testPendingByte( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int pbyte; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PENDING-BYTE\"", (void*)0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[1], &pbyte) ) return TCL_ERROR; + rc = sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, pbyte); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** sqlite3BitvecBuiltinTest SIZE PROGRAM +** +** Invoke the SQLITE_TESTCTRL_BITVEC_TEST operator on test_control. +** See comments on sqlite3BitvecBuiltinTest() for additional information. +*/ +static int testBitvecBuiltinTest( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int sz, rc; + int nProg = 0; + int aProg[100]; + const char *z; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " SIZE PROGRAM\"", (void*)0); + } + if( Tcl_GetInt(interp, argv[1], &sz) ) return TCL_ERROR; + z = argv[2]; + while( nProg<99 && *z ){ + while( *z && !sqlite3Isdigit(*z) ){ z++; } + if( *z==0 ) break; + aProg[nProg++] = atoi(z); + while( sqlite3Isdigit(*z) ){ z++; } + } + aProg[nProg] = 0; + rc = sqlite3_test_control(SQLITE_TESTCTRL_BITVEC_TEST, sz, aProg); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest2_Init(Tcl_Interp *interp){ + extern int sqlite3_io_error_persist; + extern int sqlite3_io_error_pending; + extern int sqlite3_io_error_hit; + extern int sqlite3_io_error_hardhit; + extern int sqlite3_diskfull_pending; + extern int sqlite3_diskfull; + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "pager_open", (Tcl_CmdProc*)pager_open }, + { "pager_close", (Tcl_CmdProc*)pager_close }, + { "pager_commit", (Tcl_CmdProc*)pager_commit }, + { "pager_rollback", (Tcl_CmdProc*)pager_rollback }, + { "pager_stmt_begin", (Tcl_CmdProc*)pager_stmt_begin }, + { "pager_stmt_commit", (Tcl_CmdProc*)pager_stmt_commit }, + { "pager_stmt_rollback", (Tcl_CmdProc*)pager_stmt_rollback }, + { "pager_stats", (Tcl_CmdProc*)pager_stats }, + { "pager_pagecount", (Tcl_CmdProc*)pager_pagecount }, + { "page_get", (Tcl_CmdProc*)page_get }, + { "page_lookup", (Tcl_CmdProc*)page_lookup }, + { "page_unref", (Tcl_CmdProc*)page_unref }, + { "page_read", (Tcl_CmdProc*)page_read }, + { "page_write", (Tcl_CmdProc*)page_write }, + { "page_number", (Tcl_CmdProc*)page_number }, + { "pager_truncate", (Tcl_CmdProc*)pager_truncate }, +#ifndef SQLITE_OMIT_DISKIO + { "fake_big_file", (Tcl_CmdProc*)fake_big_file }, +#endif + { "sqlite3BitvecBuiltinTest",(Tcl_CmdProc*)testBitvecBuiltinTest }, + { "sqlite3_test_control_pending_byte", (Tcl_CmdProc*)testPendingByte }, + }; + int i; + for(i=0; i +#include + +extern const char *sqlite3ErrName(int); + +/* +** A bogus sqlite3 connection structure for use in the btree +** tests. +*/ +static sqlite3 sDb; +static int nRefSqlite3 = 0; + +/* +** Usage: btree_open FILENAME NCACHE +** +** Open a new database +*/ +static int btree_open( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int rc, nCache; + char zBuf[100]; + int n; + char *zFilename; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FILENAME NCACHE FLAGS\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[2], &nCache) ) return TCL_ERROR; + nRefSqlite3++; + if( nRefSqlite3==1 ){ + sDb.pVfs = sqlite3_vfs_find(0); + sDb.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); + sqlite3_mutex_enter(sDb.mutex); + } + n = (int)strlen(argv[1]); + zFilename = sqlite3_malloc( n+2 ); + if( zFilename==0 ) return TCL_ERROR; + memcpy(zFilename, argv[1], n+1); + zFilename[n+1] = 0; + rc = sqlite3BtreeOpen(sDb.pVfs, zFilename, &sDb, &pBt, 0, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MAIN_DB); + sqlite3_free(zFilename); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3BtreeSetCacheSize(pBt, nCache); + sqlite3_snprintf(sizeof(zBuf), zBuf,"%p", pBt); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: btree_close ID +** +** Close the given database. +*/ +static int btree_close( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3BtreeClose(pBt); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + nRefSqlite3--; + if( nRefSqlite3==0 ){ + sqlite3_mutex_leave(sDb.mutex); + sqlite3_mutex_free(sDb.mutex); + sDb.mutex = 0; + sDb.pVfs = 0; + } + return TCL_OK; +} + + +/* +** Usage: btree_begin_transaction ID +** +** Start a new transaction +*/ +static int btree_begin_transaction( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pBt); + rc = sqlite3BtreeBeginTrans(pBt, 1); + sqlite3BtreeLeave(pBt); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: btree_pager_stats ID +** +** Returns pager statistics +*/ +static int btree_pager_stats( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int i; + int *a; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + + /* Normally in this file, with a b-tree handle opened using the + ** [btree_open] command it is safe to call sqlite3BtreeEnter() directly. + ** But this function is sometimes called with a btree handle obtained + ** from an open SQLite connection (using [btree_from_db]). In this case + ** we need to obtain the mutex for the controlling SQLite handle before + ** it is safe to call sqlite3BtreeEnter(). + */ + sqlite3_mutex_enter(pBt->db->mutex); + + sqlite3BtreeEnter(pBt); + a = sqlite3PagerStats(sqlite3BtreePager(pBt)); + for(i=0; i<11; i++){ + static char *zName[] = { + "ref", "page", "max", "size", "state", "err", + "hit", "miss", "ovfl", "read", "write" + }; + char zBuf[100]; + Tcl_AppendElement(interp, zName[i]); + sqlite3_snprintf(sizeof(zBuf), zBuf,"%d",a[i]); + Tcl_AppendElement(interp, zBuf); + } + sqlite3BtreeLeave(pBt); + + /* Release the mutex on the SQLite handle that controls this b-tree */ + sqlite3_mutex_leave(pBt->db->mutex); + return TCL_OK; +} + +/* +** Usage: btree_cursor ID TABLENUM WRITEABLE +** +** Create a new cursor. Return the ID for the cursor. +*/ +static int btree_cursor( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int iTable; + BtCursor *pCur; + int rc = SQLITE_OK; + int wrFlag; + char zBuf[30]; + + if( argc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID TABLENUM WRITEABLE\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &iTable) ) return TCL_ERROR; + if( Tcl_GetBoolean(interp, argv[3], &wrFlag) ) return TCL_ERROR; + pCur = (BtCursor *)ckalloc(sqlite3BtreeCursorSize()); + memset(pCur, 0, sqlite3BtreeCursorSize()); + sqlite3BtreeEnter(pBt); +#ifndef SQLITE_OMIT_SHARED_CACHE + rc = sqlite3BtreeLockTable(pBt, iTable, wrFlag); +#endif + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeCursor(pBt, iTable, wrFlag, 0, pCur); + } + sqlite3BtreeLeave(pBt); + if( rc ){ + ckfree((char *)pCur); + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3_snprintf(sizeof(zBuf), zBuf,"%p", pCur); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** Usage: btree_close_cursor ID +** +** Close a cursor opened using btree_cursor. +*/ +static int btree_close_cursor( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + Btree *pBt; + int rc; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + pBt = pCur->pBtree; + sqlite3BtreeEnter(pBt); + rc = sqlite3BtreeCloseCursor(pCur); + sqlite3BtreeLeave(pBt); + ckfree((char *)pCur); + if( rc ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return SQLITE_OK; +} + +/* +** Usage: btree_next ID +** +** Move the cursor to the next entry in the table. Return 0 on success +** or 1 if the cursor was already on the last entry in the table or if +** the table is empty. +*/ +static int btree_next( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + int rc; + int res = 0; + char zBuf[100]; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pCur->pBtree); + rc = sqlite3BtreeNext(pCur, &res); + sqlite3BtreeLeave(pCur->pBtree); + if( rc ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",res); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** Usage: btree_first ID +** +** Move the cursor to the first entry in the table. Return 0 if the +** cursor was left point to something and 1 if the table is empty. +*/ +static int btree_first( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + int rc; + int res = 0; + char zBuf[100]; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pCur->pBtree); + rc = sqlite3BtreeFirst(pCur, &res); + sqlite3BtreeLeave(pCur->pBtree); + if( rc ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",res); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** Usage: btree_eof ID +** +** Return TRUE if the given cursor is not pointing at a valid entry. +** Return FALSE if the cursor does point to a valid entry. +*/ +static int btree_eof( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + int rc; + char zBuf[50]; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pCur->pBtree); + rc = sqlite3BtreeEof(pCur); + sqlite3BtreeLeave(pCur->pBtree); + sqlite3_snprintf(sizeof(zBuf),zBuf, "%d", rc); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** Usage: btree_payload_size ID +** +** Return the number of bytes of payload +*/ +static int btree_payload_size( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + int n2; + u64 n1; + char zBuf[50]; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pCur->pBtree); + + /* The cursor may be in "require-seek" state. If this is the case, the + ** call to BtreeDataSize() will fix it. */ + sqlite3BtreeDataSize(pCur, (u32*)&n2); + if( pCur->apPage[pCur->iPage]->intKey ){ + n1 = 0; + }else{ + sqlite3BtreeKeySize(pCur, (i64*)&n1); + } + sqlite3BtreeLeave(pCur->pBtree); + sqlite3_snprintf(sizeof(zBuf),zBuf, "%d", (int)(n1+n2)); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** usage: varint_test START MULTIPLIER COUNT INCREMENT +** +** This command tests the putVarint() and getVarint() +** routines, both for accuracy and for speed. +** +** An integer is written using putVarint() and read back with +** getVarint() and varified to be unchanged. This repeats COUNT +** times. The first integer is START*MULTIPLIER. Each iteration +** increases the integer by INCREMENT. +** +** This command returns nothing if it works. It returns an error message +** if something goes wrong. +*/ +static int btree_varint_test( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + u32 start, mult, count, incr; + u64 in, out; + int n1, n2, i, j; + unsigned char zBuf[100]; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " START MULTIPLIER COUNT INCREMENT\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[1], (int*)&start) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[2], (int*)&mult) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[3], (int*)&count) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[4], (int*)&incr) ) return TCL_ERROR; + in = start; + in *= mult; + for(i=0; i<(int)count; i++){ + char zErr[200]; + n1 = putVarint(zBuf, in); + if( n1>9 || n1<1 ){ + sprintf(zErr, "putVarint returned %d - should be between 1 and 9", n1); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + n2 = getVarint(zBuf, &out); + if( n1!=n2 ){ + sprintf(zErr, "putVarint returned %d and getVarint returned %d", n1, n2); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + if( in!=out ){ + sprintf(zErr, "Wrote 0x%016llx and got back 0x%016llx", in, out); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + if( (in & 0xffffffff)==in ){ + u32 out32; + n2 = getVarint32(zBuf, out32); + out = out32; + if( n1!=n2 ){ + sprintf(zErr, "putVarint returned %d and GetVarint32 returned %d", + n1, n2); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + if( in!=out ){ + sprintf(zErr, "Wrote 0x%016llx and got back 0x%016llx from GetVarint32", + in, out); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + } + + /* In order to get realistic timings, run getVarint 19 more times. + ** This is because getVarint is called about 20 times more often + ** than putVarint. + */ + for(j=0; j<19; j++){ + getVarint(zBuf, &out); + } + in += incr; + } + return TCL_OK; +} + +/* +** usage: btree_from_db DB-HANDLE +** +** This command returns the btree handle for the main database associated +** with the database-handle passed as the argument. Example usage: +** +** sqlite3 db test.db +** set bt [btree_from_db db] +*/ +static int btree_from_db( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + char zBuf[100]; + Tcl_CmdInfo info; + sqlite3 *db; + Btree *pBt; + int iDb = 0; + + if( argc!=2 && argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB-HANDLE ?N?\"", 0); + return TCL_ERROR; + } + + if( 1!=Tcl_GetCommandInfo(interp, argv[1], &info) ){ + Tcl_AppendResult(interp, "No such db-handle: \"", argv[1], "\"", 0); + return TCL_ERROR; + } + if( argc==3 ){ + iDb = atoi(argv[2]); + } + + db = *((sqlite3 **)info.objClientData); + assert( db ); + + pBt = db->aDb[iDb].pBt; + sqlite3_snprintf(sizeof(zBuf), zBuf, "%p", pBt); + Tcl_SetResult(interp, zBuf, TCL_VOLATILE); + return TCL_OK; +} + +/* +** Usage: btree_ismemdb ID +** +** Return true if the B-Tree is in-memory. +*/ +static int btree_ismemdb( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int res; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + sqlite3_mutex_enter(pBt->db->mutex); + sqlite3BtreeEnter(pBt); + res = sqlite3PagerIsMemdb(sqlite3BtreePager(pBt)); + sqlite3BtreeLeave(pBt); + sqlite3_mutex_leave(pBt->db->mutex); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(res)); + return SQLITE_OK; +} + +/* +** usage: btree_set_cache_size ID NCACHE +** +** Set the size of the cache used by btree $ID. +*/ +static int btree_set_cache_size( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int nCache; + Btree *pBt; + + if( argc!=3 ){ + Tcl_AppendResult( + interp, "wrong # args: should be \"", argv[0], " BT NCACHE\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &nCache) ) return TCL_ERROR; + + sqlite3_mutex_enter(pBt->db->mutex); + sqlite3BtreeEnter(pBt); + sqlite3BtreeSetCacheSize(pBt, nCache); + sqlite3BtreeLeave(pBt); + sqlite3_mutex_leave(pBt->db->mutex); + return TCL_OK; +} + + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest3_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "btree_open", (Tcl_CmdProc*)btree_open }, + { "btree_close", (Tcl_CmdProc*)btree_close }, + { "btree_begin_transaction", (Tcl_CmdProc*)btree_begin_transaction }, + { "btree_pager_stats", (Tcl_CmdProc*)btree_pager_stats }, + { "btree_cursor", (Tcl_CmdProc*)btree_cursor }, + { "btree_close_cursor", (Tcl_CmdProc*)btree_close_cursor }, + { "btree_next", (Tcl_CmdProc*)btree_next }, + { "btree_eof", (Tcl_CmdProc*)btree_eof }, + { "btree_payload_size", (Tcl_CmdProc*)btree_payload_size }, + { "btree_first", (Tcl_CmdProc*)btree_first }, + { "btree_varint_test", (Tcl_CmdProc*)btree_varint_test }, + { "btree_from_db", (Tcl_CmdProc*)btree_from_db }, + { "btree_ismemdb", (Tcl_CmdProc*)btree_ismemdb }, + { "btree_set_cache_size", (Tcl_CmdProc*)btree_set_cache_size } + }; + int i; + + for(i=0; i +#include +#include +#include +#include + +extern const char *sqlite3ErrName(int); + +/* +** Each thread is controlled by an instance of the following +** structure. +*/ +typedef struct Thread Thread; +struct Thread { + /* The first group of fields are writable by the master and read-only + ** to the thread. */ + char *zFilename; /* Name of database file */ + void (*xOp)(Thread*); /* next operation to do */ + char *zArg; /* argument usable by xOp */ + int opnum; /* Operation number */ + int busy; /* True if this thread is in use */ + + /* The next group of fields are writable by the thread but read-only to the + ** master. */ + int completed; /* Number of operations completed */ + sqlite3 *db; /* Open database */ + sqlite3_stmt *pStmt; /* Pending operation */ + char *zErr; /* operation error */ + char *zStaticErr; /* Static error message */ + int rc; /* operation return code */ + int argc; /* number of columns in result */ + const char *argv[100]; /* result columns */ + const char *colv[100]; /* result column names */ +}; + +/* +** There can be as many as 26 threads running at once. Each is named +** by a capital letter: A, B, C, ..., Y, Z. +*/ +#define N_THREAD 26 +static Thread threadset[N_THREAD]; + + +/* +** The main loop for a thread. Threads use busy waiting. +*/ +static void *thread_main(void *pArg){ + Thread *p = (Thread*)pArg; + if( p->db ){ + sqlite3_close(p->db); + } + sqlite3_open(p->zFilename, &p->db); + if( SQLITE_OK!=sqlite3_errcode(p->db) ){ + p->zErr = strdup(sqlite3_errmsg(p->db)); + sqlite3_close(p->db); + p->db = 0; + } + p->pStmt = 0; + p->completed = 1; + while( p->opnum<=p->completed ) sched_yield(); + while( p->xOp ){ + if( p->zErr && p->zErr!=p->zStaticErr ){ + sqlite3_free(p->zErr); + p->zErr = 0; + } + (*p->xOp)(p); + p->completed++; + while( p->opnum<=p->completed ) sched_yield(); + } + if( p->pStmt ){ + sqlite3_finalize(p->pStmt); + p->pStmt = 0; + } + if( p->db ){ + sqlite3_close(p->db); + p->db = 0; + } + if( p->zErr && p->zErr!=p->zStaticErr ){ + sqlite3_free(p->zErr); + p->zErr = 0; + } + p->completed++; +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_thread_cleanup(); +#endif + return 0; +} + +/* +** Get a thread ID which is an upper case letter. Return the index. +** If the argument is not a valid thread ID put an error message in +** the interpreter and return -1. +*/ +static int parse_thread_id(Tcl_Interp *interp, const char *zArg){ + if( zArg==0 || zArg[0]==0 || zArg[1]!=0 || !isupper((unsigned char)zArg[0]) ){ + Tcl_AppendResult(interp, "thread ID must be an upper case letter", 0); + return -1; + } + return zArg[0] - 'A'; +} + +/* +** Usage: thread_create NAME FILENAME +** +** NAME should be an upper case letter. Start the thread running with +** an open connection to the given database. +*/ +static int tcl_thread_create( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + pthread_t x; + int rc; + + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID FILENAME", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( threadset[i].busy ){ + Tcl_AppendResult(interp, "thread ", argv[1], " is already running", 0); + return TCL_ERROR; + } + threadset[i].busy = 1; + sqlite3_free(threadset[i].zFilename); + threadset[i].zFilename = sqlite3_mprintf("%s", argv[2]); + threadset[i].opnum = 1; + threadset[i].completed = 0; + rc = pthread_create(&x, 0, thread_main, &threadset[i]); + if( rc ){ + Tcl_AppendResult(interp, "failed to create the thread", 0); + sqlite3_free(threadset[i].zFilename); + threadset[i].busy = 0; + return TCL_ERROR; + } + pthread_detach(x); + return TCL_OK; +} + +/* +** Wait for a thread to reach its idle state. +*/ +static void thread_wait(Thread *p){ + while( p->opnum>p->completed ) sched_yield(); +} + +/* +** Usage: thread_wait ID +** +** Wait on thread ID to reach its idle state. +*/ +static int tcl_thread_wait( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + return TCL_OK; +} + +/* +** Stop a thread. +*/ +static void stop_thread(Thread *p){ + thread_wait(p); + p->xOp = 0; + p->opnum++; + thread_wait(p); + sqlite3_free(p->zArg); + p->zArg = 0; + sqlite3_free(p->zFilename); + p->zFilename = 0; + p->busy = 0; +} + +/* +** Usage: thread_halt ID +** +** Cause a thread to shut itself down. Wait for the shutdown to be +** completed. If ID is "*" then stop all threads. +*/ +static int tcl_thread_halt( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + if( argv[1][0]=='*' && argv[1][1]==0 ){ + for(i=0; i=threadset[i].argc ){ + Tcl_AppendResult(interp, "column number out of range", 0); + return TCL_ERROR; + } + Tcl_AppendResult(interp, threadset[i].argv[n], 0); + return TCL_OK; +} + +/* +** Usage: thread_colname ID N +** +** Wait on the most recent thread_step to complete, then return the +** name of the N-th columns in the result set. +*/ +static int tcl_thread_colname( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + int n; + + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID N", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR; + thread_wait(&threadset[i]); + if( n<0 || n>=threadset[i].argc ){ + Tcl_AppendResult(interp, "column number out of range", 0); + return TCL_ERROR; + } + Tcl_AppendResult(interp, threadset[i].colv[n], 0); + return TCL_OK; +} + +/* +** Usage: thread_result ID +** +** Wait on the most recent operation to complete, then return the +** result code from that operation. +*/ +static int tcl_thread_result( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + const char *zName; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + zName = sqlite3ErrName(threadset[i].rc); + Tcl_AppendResult(interp, zName, 0); + return TCL_OK; +} + +/* +** Usage: thread_error ID +** +** Wait on the most recent operation to complete, then return the +** error string. +*/ +static int tcl_thread_error( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + Tcl_AppendResult(interp, threadset[i].zErr, 0); + return TCL_OK; +} + +/* +** This procedure runs in the thread to compile an SQL statement. +*/ +static void do_compile(Thread *p){ + if( p->db==0 ){ + p->zErr = p->zStaticErr = "no database is open"; + p->rc = SQLITE_ERROR; + return; + } + if( p->pStmt ){ + sqlite3_finalize(p->pStmt); + p->pStmt = 0; + } + p->rc = sqlite3_prepare(p->db, p->zArg, -1, &p->pStmt, 0); +} + +/* +** Usage: thread_compile ID SQL +** +** Compile a new virtual machine. +*/ +static int tcl_thread_compile( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID SQL", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + threadset[i].xOp = do_compile; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = sqlite3_mprintf("%s", argv[2]); + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to step the virtual machine. +*/ +static void do_step(Thread *p){ + int i; + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_step(p->pStmt); + if( p->rc==SQLITE_ROW ){ + p->argc = sqlite3_column_count(p->pStmt); + for(i=0; ipStmt); i++){ + p->argv[i] = (char*)sqlite3_column_text(p->pStmt, i); + } + for(i=0; iargc; i++){ + p->colv[i] = sqlite3_column_name(p->pStmt, i); + } + } +} + +/* +** Usage: thread_step ID +** +** Advance the virtual machine by one step +*/ +static int tcl_thread_step( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + threadset[i].xOp = do_step; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to finalize a virtual machine. +*/ +static void do_finalize(Thread *p){ + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_finalize(p->pStmt); + p->pStmt = 0; +} + +/* +** Usage: thread_finalize ID +** +** Finalize the virtual machine. +*/ +static int tcl_thread_finalize( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + threadset[i].xOp = do_finalize; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = 0; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** Usage: thread_swap ID ID +** +** Interchange the sqlite* pointer between two threads. +*/ +static int tcl_thread_swap( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i, j; + sqlite3 *temp; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID1 ID2", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + j = parse_thread_id(interp, argv[2]); + if( j<0 ) return TCL_ERROR; + if( !threadset[j].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[j]); + temp = threadset[i].db; + threadset[i].db = threadset[j].db; + threadset[j].db = temp; + return TCL_OK; +} + +/* +** Usage: thread_db_get ID +** +** Return the database connection pointer for the given thread. Then +** remove the pointer from the thread itself. Afterwards, the thread +** can be stopped and the connection can be used by the main thread. +*/ +static int tcl_thread_db_get( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + char zBuf[100]; + extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*); + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + sqlite3TestMakePointerStr(interp, zBuf, threadset[i].db); + threadset[i].db = 0; + Tcl_AppendResult(interp, zBuf, (char*)0); + return TCL_OK; +} + +/* +** Usage: thread_db_put ID DB +** +*/ +static int tcl_thread_db_put( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*); + extern void *sqlite3TestTextToPtr(const char *); + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID DB", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + assert( !threadset[i].db ); + threadset[i].db = (sqlite3*)sqlite3TestTextToPtr(argv[2]); + return TCL_OK; +} + +/* +** Usage: thread_stmt_get ID +** +** Return the database stmt pointer for the given thread. Then +** remove the pointer from the thread itself. +*/ +static int tcl_thread_stmt_get( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + char zBuf[100]; + extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*); + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + sqlite3TestMakePointerStr(interp, zBuf, threadset[i].pStmt); + threadset[i].pStmt = 0; + Tcl_AppendResult(interp, zBuf, (char*)0); + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest4_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "thread_create", (Tcl_CmdProc*)tcl_thread_create }, + { "thread_wait", (Tcl_CmdProc*)tcl_thread_wait }, + { "thread_halt", (Tcl_CmdProc*)tcl_thread_halt }, + { "thread_argc", (Tcl_CmdProc*)tcl_thread_argc }, + { "thread_argv", (Tcl_CmdProc*)tcl_thread_argv }, + { "thread_colname", (Tcl_CmdProc*)tcl_thread_colname }, + { "thread_result", (Tcl_CmdProc*)tcl_thread_result }, + { "thread_error", (Tcl_CmdProc*)tcl_thread_error }, + { "thread_compile", (Tcl_CmdProc*)tcl_thread_compile }, + { "thread_step", (Tcl_CmdProc*)tcl_thread_step }, + { "thread_finalize", (Tcl_CmdProc*)tcl_thread_finalize }, + { "thread_swap", (Tcl_CmdProc*)tcl_thread_swap }, + { "thread_db_get", (Tcl_CmdProc*)tcl_thread_db_get }, + { "thread_db_put", (Tcl_CmdProc*)tcl_thread_db_put }, + { "thread_stmt_get", (Tcl_CmdProc*)tcl_thread_stmt_get }, + }; + int i; + + for(i=0; i +#include + +/* +** The first argument is a TCL UTF-8 string. Return the byte array +** object with the encoded representation of the string, including +** the NULL terminator. +*/ +static int binarize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int len; + char *bytes; + Tcl_Obj *pRet; + assert(objc==2); + + bytes = Tcl_GetStringFromObj(objv[1], &len); + pRet = Tcl_NewByteArrayObj((u8*)bytes, len+1); + Tcl_SetObjResult(interp, pRet); + return TCL_OK; +} + +/* +** Usage: test_value_overhead . +** +** This routine is used to test the overhead of calls to +** sqlite3_value_text(), on a value that contains a UTF-8 string. The idea +** is to figure out whether or not it is a problem to use sqlite3_value +** structures with collation sequence functions. +** +** If is 0, then the calls to sqlite3_value_text() are not +** actually made. +*/ +static int test_value_overhead( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int do_calls; + int repeat_count; + int i; + Mem val; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; + } + + if( Tcl_GetIntFromObj(interp, objv[1], &repeat_count) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &do_calls) ) return TCL_ERROR; + + val.flags = MEM_Str|MEM_Term|MEM_Static; + val.z = "hello world"; + val.type = SQLITE_TEXT; + val.enc = SQLITE_UTF8; + + for(i=0; izName; pEnc++){ + if( 0==sqlite3StrICmp(z, pEnc->zName) ){ + break; + } + } + if( !pEnc->enc ){ + Tcl_AppendResult(interp, "No such encoding: ", z, 0); + } + if( pEnc->enc==SQLITE_UTF16 ){ + return SQLITE_UTF16NATIVE; + } + return pEnc->enc; +} + +/* +** Usage: test_translate ?? +** +*/ +static int test_translate( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + u8 enc_from; + u8 enc_to; + sqlite3_value *pVal; + + char *z; + int len; + void (*xDel)(void *p) = SQLITE_STATIC; + + if( objc!=4 && objc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), + " ", 0 + ); + return TCL_ERROR; + } + if( objc==5 ){ + xDel = sqlite3_free; + } + + enc_from = name_to_enc(interp, objv[2]); + if( !enc_from ) return TCL_ERROR; + enc_to = name_to_enc(interp, objv[3]); + if( !enc_to ) return TCL_ERROR; + + pVal = sqlite3ValueNew(0); + + if( enc_from==SQLITE_UTF8 ){ + z = Tcl_GetString(objv[1]); + if( objc==5 ){ + z = sqlite3_mprintf("%s", z); + } + sqlite3ValueSetStr(pVal, -1, z, enc_from, xDel); + }else{ + z = (char*)Tcl_GetByteArrayFromObj(objv[1], &len); + if( objc==5 ){ + char *zTmp = z; + z = sqlite3_malloc(len); + memcpy(z, zTmp, len); + } + sqlite3ValueSetStr(pVal, -1, z, enc_from, xDel); + } + + z = (char *)sqlite3ValueText(pVal, enc_to); + len = sqlite3ValueBytes(pVal, enc_to) + (enc_to==SQLITE_UTF8?1:2); + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj((u8*)z, len)); + + sqlite3ValueFree(pVal); + + return TCL_OK; +} + +/* +** Usage: translate_selftest +** +** Call sqlite3UtfSelfTest() to run the internal tests for unicode +** translation. If there is a problem an assert() will fail. +**/ +void sqlite3UtfSelfTest(void); +static int test_translate_selftest( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3UtfSelfTest(); +#endif + return SQLITE_OK; +} + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest5_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aCmd[] = { + { "binarize", (Tcl_ObjCmdProc*)binarize }, + { "test_value_overhead", (Tcl_ObjCmdProc*)test_value_overhead }, + { "test_translate", (Tcl_ObjCmdProc*)test_translate }, + { "translate_selftest", (Tcl_ObjCmdProc*)test_translate_selftest}, + }; + int i; + for(i=0; iflags&SQLITE_OPEN_MAIN_DB) ){ + iSkip = 512; + } + if( (iAmt-iSkip)>0 ){ + rc = sqlite3OsWrite(p->pRealFile, &z[iSkip], (int)(iAmt-iSkip), iOff+iSkip); + } + return rc; +} + +/* +** Flush the write-list as if xSync() had been called on file handle +** pFile. If isCrash is true, simulate a crash. +*/ +static int writeListSync(CrashFile *pFile, int isCrash){ + int rc = SQLITE_OK; + int iDc = g.iDeviceCharacteristics; + + WriteBuffer *pWrite; + WriteBuffer **ppPtr; + + /* If this is not a crash simulation, set pFinal to point to the + ** last element of the write-list that is associated with file handle + ** pFile. + ** + ** If this is a crash simulation, set pFinal to an arbitrarily selected + ** element of the write-list. + */ + WriteBuffer *pFinal = 0; + if( !isCrash ){ + for(pWrite=g.pWriteList; pWrite; pWrite=pWrite->pNext){ + if( pWrite->pFile==pFile ){ + pFinal = pWrite; + } + } + }else if( iDc&(SQLITE_IOCAP_SEQUENTIAL|SQLITE_IOCAP_SAFE_APPEND) ){ + int nWrite = 0; + int iFinal; + for(pWrite=g.pWriteList; pWrite; pWrite=pWrite->pNext) nWrite++; + sqlite3_randomness(sizeof(int), &iFinal); + iFinal = ((iFinal<0)?-1*iFinal:iFinal)%nWrite; + for(pWrite=g.pWriteList; iFinal>0; pWrite=pWrite->pNext) iFinal--; + pFinal = pWrite; + } + +#ifdef TRACE_CRASHTEST + printf("Sync %s (is %s crash)\n", pFile->zName, (isCrash?"a":"not a")); +#endif + + ppPtr = &g.pWriteList; + for(pWrite=*ppPtr; rc==SQLITE_OK && pWrite; pWrite=*ppPtr){ + sqlite3_file *pRealFile = pWrite->pFile->pRealFile; + + /* (eAction==1) -> write block out normally, + ** (eAction==2) -> do nothing, + ** (eAction==3) -> trash sectors. + */ + int eAction = 0; + if( !isCrash ){ + eAction = 2; + if( (pWrite->pFile==pFile || iDc&SQLITE_IOCAP_SEQUENTIAL) ){ + eAction = 1; + } + }else{ + char random; + sqlite3_randomness(1, &random); + + /* Do not select option 3 (sector trashing) if the IOCAP_ATOMIC flag + ** is set or this is an OsTruncate(), not an Oswrite(). + */ + if( (iDc&SQLITE_IOCAP_ATOMIC) || (pWrite->zBuf==0) ){ + random &= 0x01; + } + + /* If IOCAP_SEQUENTIAL is set and this is not the final entry + ** in the truncated write-list, always select option 1 (write + ** out correctly). + */ + if( (iDc&SQLITE_IOCAP_SEQUENTIAL && pWrite!=pFinal) ){ + random = 0; + } + + /* If IOCAP_SAFE_APPEND is set and this OsWrite() operation is + ** an append (first byte of the written region is 1 byte past the + ** current EOF), always select option 1 (write out correctly). + */ + if( iDc&SQLITE_IOCAP_SAFE_APPEND && pWrite->zBuf ){ + i64 iSize; + sqlite3OsFileSize(pRealFile, &iSize); + if( iSize==pWrite->iOffset ){ + random = 0; + } + } + + if( (random&0x06)==0x06 ){ + eAction = 3; + }else{ + eAction = ((random&0x01)?2:1); + } + } + + switch( eAction ){ + case 1: { /* Write out correctly */ + if( pWrite->zBuf ){ + rc = writeDbFile( + pWrite->pFile, pWrite->zBuf, pWrite->nBuf, pWrite->iOffset + ); + }else{ + rc = sqlite3OsTruncate(pRealFile, pWrite->iOffset); + } + *ppPtr = pWrite->pNext; +#ifdef TRACE_CRASHTEST + if( isCrash ){ + printf("Writing %d bytes @ %d (%s)\n", + pWrite->nBuf, (int)pWrite->iOffset, pWrite->pFile->zName + ); + } +#endif + crash_free(pWrite); + break; + } + case 2: { /* Do nothing */ + ppPtr = &pWrite->pNext; +#ifdef TRACE_CRASHTEST + if( isCrash ){ + printf("Omiting %d bytes @ %d (%s)\n", + pWrite->nBuf, (int)pWrite->iOffset, pWrite->pFile->zName + ); + } +#endif + break; + } + case 3: { /* Trash sectors */ + u8 *zGarbage; + int iFirst = (int)(pWrite->iOffset/g.iSectorSize); + int iLast = (int)((pWrite->iOffset+pWrite->nBuf-1)/g.iSectorSize); + + assert(pWrite->zBuf); + +#ifdef TRACE_CRASHTEST + printf("Trashing %d sectors @ %lld (sector %d) (%s)\n", + 1+iLast-iFirst, pWrite->iOffset, iFirst, pWrite->pFile->zName + ); +#endif + + zGarbage = crash_malloc(g.iSectorSize); + if( zGarbage ){ + sqlite3_int64 i; + for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){ + sqlite3_randomness(g.iSectorSize, zGarbage); + rc = writeDbFile( + pWrite->pFile, zGarbage, g.iSectorSize, i*g.iSectorSize + ); + } + crash_free(zGarbage); + }else{ + rc = SQLITE_NOMEM; + } + + ppPtr = &pWrite->pNext; + break; + } + + default: + assert(!"Cannot happen"); + } + + if( pWrite==pFinal ) break; + } + + if( rc==SQLITE_OK && isCrash ){ + exit(-1); + } + + for(pWrite=g.pWriteList; pWrite && pWrite->pNext; pWrite=pWrite->pNext); + g.pWriteListEnd = pWrite; + + return rc; +} + +/* +** Add an entry to the end of the write-list. +*/ +static int writeListAppend( + sqlite3_file *pFile, + sqlite3_int64 iOffset, + const u8 *zBuf, + int nBuf +){ + WriteBuffer *pNew; + + assert((zBuf && nBuf) || (!nBuf && !zBuf)); + + pNew = (WriteBuffer *)crash_malloc(sizeof(WriteBuffer) + nBuf); + if( pNew==0 ){ + fprintf(stderr, "out of memory in the crash simulator\n"); + } + memset(pNew, 0, sizeof(WriteBuffer)+nBuf); + pNew->iOffset = iOffset; + pNew->nBuf = nBuf; + pNew->pFile = (CrashFile *)pFile; + if( zBuf ){ + pNew->zBuf = (u8 *)&pNew[1]; + memcpy(pNew->zBuf, zBuf, nBuf); + } + + if( g.pWriteList ){ + assert(g.pWriteListEnd); + g.pWriteListEnd->pNext = pNew; + }else{ + g.pWriteList = pNew; + } + g.pWriteListEnd = pNew; + + return SQLITE_OK; +} + +/* +** Close a crash-file. +*/ +static int cfClose(sqlite3_file *pFile){ + CrashFile *pCrash = (CrashFile *)pFile; + writeListSync(pCrash, 0); + sqlite3OsClose(pCrash->pRealFile); + return SQLITE_OK; +} + +/* +** Read data from a crash-file. +*/ +static int cfRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + CrashFile *pCrash = (CrashFile *)pFile; + + /* Check the file-size to see if this is a short-read */ + if( pCrash->iSize<(iOfst+iAmt) ){ + return SQLITE_IOERR_SHORT_READ; + } + + memcpy(zBuf, &pCrash->zData[iOfst], iAmt); + return SQLITE_OK; +} + +/* +** Write data to a crash-file. +*/ +static int cfWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + CrashFile *pCrash = (CrashFile *)pFile; + if( iAmt+iOfst>pCrash->iSize ){ + pCrash->iSize = (int)(iAmt+iOfst); + } + while( pCrash->iSize>pCrash->nData ){ + u8 *zNew; + int nNew = (pCrash->nData*2) + 4096; + zNew = crash_realloc(pCrash->zData, nNew); + if( !zNew ){ + return SQLITE_NOMEM; + } + memset(&zNew[pCrash->nData], 0, nNew-pCrash->nData); + pCrash->nData = nNew; + pCrash->zData = zNew; + } + memcpy(&pCrash->zData[iOfst], zBuf, iAmt); + return writeListAppend(pFile, iOfst, zBuf, iAmt); +} + +/* +** Truncate a crash-file. +*/ +static int cfTruncate(sqlite3_file *pFile, sqlite_int64 size){ + CrashFile *pCrash = (CrashFile *)pFile; + assert(size>=0); + if( pCrash->iSize>size ){ + pCrash->iSize = (int)size; + } + return writeListAppend(pFile, size, 0, 0); +} + +/* +** Sync a crash-file. +*/ +static int cfSync(sqlite3_file *pFile, int flags){ + CrashFile *pCrash = (CrashFile *)pFile; + int isCrash = 0; + + const char *zName = pCrash->zName; + const char *zCrashFile = g.zCrashFile; + int nName = (int)strlen(zName); + int nCrashFile = (int)strlen(zCrashFile); + + if( nCrashFile>0 && zCrashFile[nCrashFile-1]=='*' ){ + nCrashFile--; + if( nName>nCrashFile ) nName = nCrashFile; + } + +#ifdef TRACE_CRASHTEST + printf("cfSync(): nName = %d, nCrashFile = %d, zName = %s, zCrashFile = %s\n", + nName, nCrashFile, zName, zCrashFile); +#endif + + if( nName==nCrashFile && 0==memcmp(zName, zCrashFile, nName) ){ +#ifdef TRACE_CRASHTEST + printf("cfSync(): name matched, g.iCrash = %d\n", g.iCrash); +#endif + if( (--g.iCrash)==0 ) isCrash = 1; + } + + return writeListSync(pCrash, isCrash); +} + +/* +** Return the current file-size of the crash-file. +*/ +static int cfFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + CrashFile *pCrash = (CrashFile *)pFile; + *pSize = (i64)pCrash->iSize; + return SQLITE_OK; +} + +/* +** Calls related to file-locks are passed on to the real file handle. +*/ +static int cfLock(sqlite3_file *pFile, int eLock){ + return sqlite3OsLock(((CrashFile *)pFile)->pRealFile, eLock); +} +static int cfUnlock(sqlite3_file *pFile, int eLock){ + return sqlite3OsUnlock(((CrashFile *)pFile)->pRealFile, eLock); +} +static int cfCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + return sqlite3OsCheckReservedLock(((CrashFile *)pFile)->pRealFile, pResOut); +} +static int cfFileControl(sqlite3_file *pFile, int op, void *pArg){ + if( op==SQLITE_FCNTL_SIZE_HINT ){ + CrashFile *pCrash = (CrashFile *)pFile; + i64 nByte = *(i64 *)pArg; + if( nByte>pCrash->iSize ){ + if( SQLITE_OK==writeListAppend(pFile, nByte, 0, 0) ){ + pCrash->iSize = (int)nByte; + } + } + return SQLITE_OK; + } + return sqlite3OsFileControl(((CrashFile *)pFile)->pRealFile, op, pArg); +} + +/* +** The xSectorSize() and xDeviceCharacteristics() functions return +** the global values configured by the [sqlite_crashparams] tcl +* interface. +*/ +static int cfSectorSize(sqlite3_file *pFile){ + return g.iSectorSize; +} +static int cfDeviceCharacteristics(sqlite3_file *pFile){ + return g.iDeviceCharacteristics; +} + +/* +** Pass-throughs for WAL support. +*/ +static int cfShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ + return sqlite3OsShmLock(((CrashFile*)pFile)->pRealFile, ofst, n, flags); +} +static void cfShmBarrier(sqlite3_file *pFile){ + sqlite3OsShmBarrier(((CrashFile*)pFile)->pRealFile); +} +static int cfShmUnmap(sqlite3_file *pFile, int delFlag){ + return sqlite3OsShmUnmap(((CrashFile*)pFile)->pRealFile, delFlag); +} +static int cfShmMap( + sqlite3_file *pFile, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int sz, /* Size of regions */ + int w, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + return sqlite3OsShmMap(((CrashFile*)pFile)->pRealFile, iRegion, sz, w, pp); +} + +static const sqlite3_io_methods CrashFileVtab = { + 2, /* iVersion */ + cfClose, /* xClose */ + cfRead, /* xRead */ + cfWrite, /* xWrite */ + cfTruncate, /* xTruncate */ + cfSync, /* xSync */ + cfFileSize, /* xFileSize */ + cfLock, /* xLock */ + cfUnlock, /* xUnlock */ + cfCheckReservedLock, /* xCheckReservedLock */ + cfFileControl, /* xFileControl */ + cfSectorSize, /* xSectorSize */ + cfDeviceCharacteristics, /* xDeviceCharacteristics */ + cfShmMap, /* xShmMap */ + cfShmLock, /* xShmLock */ + cfShmBarrier, /* xShmBarrier */ + cfShmUnmap /* xShmUnmap */ +}; + +/* +** Application data for the crash VFS +*/ +struct crashAppData { + sqlite3_vfs *pOrig; /* Wrapped vfs structure */ +}; + +/* +** Open a crash-file file handle. +** +** The caller will have allocated pVfs->szOsFile bytes of space +** at pFile. This file uses this space for the CrashFile structure +** and allocates space for the "real" file structure using +** sqlite3_malloc(). The assumption here is (pVfs->szOsFile) is +** equal or greater than sizeof(CrashFile). +*/ +static int cfOpen( + sqlite3_vfs *pCfVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + int rc; + CrashFile *pWrapper = (CrashFile *)pFile; + sqlite3_file *pReal = (sqlite3_file*)&pWrapper[1]; + + memset(pWrapper, 0, sizeof(CrashFile)); + rc = sqlite3OsOpen(pVfs, zName, pReal, flags, pOutFlags); + + if( rc==SQLITE_OK ){ + i64 iSize; + pWrapper->pMethod = &CrashFileVtab; + pWrapper->zName = (char *)zName; + pWrapper->pRealFile = pReal; + rc = sqlite3OsFileSize(pReal, &iSize); + pWrapper->iSize = (int)iSize; + pWrapper->flags = flags; + } + if( rc==SQLITE_OK ){ + pWrapper->nData = (4096 + pWrapper->iSize); + pWrapper->zData = crash_malloc(pWrapper->nData); + if( pWrapper->zData ){ + /* os_unix.c contains an assert() that fails if the caller attempts + ** to read data from the 512-byte locking region of a file opened + ** with the SQLITE_OPEN_MAIN_DB flag. This region of a database file + ** never contains valid data anyhow. So avoid doing such a read here. + ** + ** UPDATE: It also contains an assert() verifying that each call + ** to the xRead() method reads less than 128KB of data. + */ + const int isDb = (flags&SQLITE_OPEN_MAIN_DB); + i64 iOff; + + memset(pWrapper->zData, 0, pWrapper->nData); + for(iOff=0; iOffiSize; iOff += 512){ + int nRead = pWrapper->iSize - (int)iOff; + if( nRead>512 ) nRead = 512; + if( isDb && iOff==PENDING_BYTE ) continue; + rc = sqlite3OsRead(pReal, &pWrapper->zData[iOff], nRead, iOff); + } + }else{ + rc = SQLITE_NOMEM; + } + } + if( rc!=SQLITE_OK && pWrapper->pMethod ){ + sqlite3OsClose(pFile); + } + return rc; +} + +static int cfDelete(sqlite3_vfs *pCfVfs, const char *zPath, int dirSync){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xDelete(pVfs, zPath, dirSync); +} +static int cfAccess( + sqlite3_vfs *pCfVfs, + const char *zPath, + int flags, + int *pResOut +){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xAccess(pVfs, zPath, flags, pResOut); +} +static int cfFullPathname( + sqlite3_vfs *pCfVfs, + const char *zPath, + int nPathOut, + char *zPathOut +){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); +} +static void *cfDlOpen(sqlite3_vfs *pCfVfs, const char *zPath){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xDlOpen(pVfs, zPath); +} +static void cfDlError(sqlite3_vfs *pCfVfs, int nByte, char *zErrMsg){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + pVfs->xDlError(pVfs, nByte, zErrMsg); +} +static void (*cfDlSym(sqlite3_vfs *pCfVfs, void *pH, const char *zSym))(void){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xDlSym(pVfs, pH, zSym); +} +static void cfDlClose(sqlite3_vfs *pCfVfs, void *pHandle){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + pVfs->xDlClose(pVfs, pHandle); +} +static int cfRandomness(sqlite3_vfs *pCfVfs, int nByte, char *zBufOut){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xRandomness(pVfs, nByte, zBufOut); +} +static int cfSleep(sqlite3_vfs *pCfVfs, int nMicro){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xSleep(pVfs, nMicro); +} +static int cfCurrentTime(sqlite3_vfs *pCfVfs, double *pTimeOut){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xCurrentTime(pVfs, pTimeOut); +} + +static int processDevSymArgs( + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[], + int *piDeviceChar, + int *piSectorSize +){ + struct DeviceFlag { + char *zName; + int iValue; + } aFlag[] = { + { "atomic", SQLITE_IOCAP_ATOMIC }, + { "atomic512", SQLITE_IOCAP_ATOMIC512 }, + { "atomic1k", SQLITE_IOCAP_ATOMIC1K }, + { "atomic2k", SQLITE_IOCAP_ATOMIC2K }, + { "atomic4k", SQLITE_IOCAP_ATOMIC4K }, + { "atomic8k", SQLITE_IOCAP_ATOMIC8K }, + { "atomic16k", SQLITE_IOCAP_ATOMIC16K }, + { "atomic32k", SQLITE_IOCAP_ATOMIC32K }, + { "atomic64k", SQLITE_IOCAP_ATOMIC64K }, + { "sequential", SQLITE_IOCAP_SEQUENTIAL }, + { "safe_append", SQLITE_IOCAP_SAFE_APPEND }, + { "powersafe_overwrite", SQLITE_IOCAP_POWERSAFE_OVERWRITE }, + { 0, 0 } + }; + + int i; + int iDc = 0; + int iSectorSize = 0; + int setSectorsize = 0; + int setDeviceChar = 0; + + for(i=0; i11 || nOpt<2 || strncmp("-sectorsize", zOpt, nOpt)) + && (nOpt>16 || nOpt<2 || strncmp("-characteristics", zOpt, nOpt)) + ){ + Tcl_AppendResult(interp, + "Bad option: \"", zOpt, + "\" - must be \"-characteristics\" or \"-sectorsize\"", 0 + ); + return TCL_ERROR; + } + if( i==objc-1 ){ + Tcl_AppendResult(interp, "Option requires an argument: \"", zOpt, "\"",0); + return TCL_ERROR; + } + + if( zOpt[1]=='s' ){ + if( Tcl_GetIntFromObj(interp, objv[i+1], &iSectorSize) ){ + return TCL_ERROR; + } + setSectorsize = 1; + }else{ + int j; + Tcl_Obj **apObj; + int nObj; + if( Tcl_ListObjGetElements(interp, objv[i+1], &nObj, &apObj) ){ + return TCL_ERROR; + } + for(j=0; jmxPathname; + crashVfs.pAppData = (void *)pOriginalVfs; + crashVfs.szOsFile = sizeof(CrashFile) + pOriginalVfs->szOsFile; + sqlite3_vfs_register(&crashVfs, 0); + }else{ + crashVfs.pAppData = 0; + sqlite3_vfs_unregister(&crashVfs); + } + + return TCL_OK; +} + +/* +** tclcmd: sqlite_crashparams ?OPTIONS? DELAY CRASHFILE +** +** This procedure implements a TCL command that enables crash testing +** in testfixture. Once enabled, crash testing cannot be disabled. +** +** Available options are "-characteristics" and "-sectorsize". Both require +** an argument. For -sectorsize, this is the simulated sector size in +** bytes. For -characteristics, the argument must be a list of io-capability +** flags to simulate. Valid flags are "atomic", "atomic512", "atomic1K", +** "atomic2K", "atomic4K", "atomic8K", "atomic16K", "atomic32K", +** "atomic64K", "sequential" and "safe_append". +** +** Example: +** +** sqlite_crashparams -sect 1024 -char {atomic sequential} ./test.db 1 +** +*/ +static int crashParamsObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int iDelay; + const char *zCrashFile; + int nCrashFile, iDc, iSectorSize; + + iDc = -1; + iSectorSize = -1; + + if( objc<3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?OPTIONS? DELAY CRASHFILE"); + goto error; + } + + zCrashFile = Tcl_GetStringFromObj(objv[objc-1], &nCrashFile); + if( nCrashFile>=sizeof(g.zCrashFile) ){ + Tcl_AppendResult(interp, "Filename is too long: \"", zCrashFile, "\"", 0); + goto error; + } + if( Tcl_GetIntFromObj(interp, objv[objc-2], &iDelay) ){ + goto error; + } + + if( processDevSymArgs(interp, objc-3, &objv[1], &iDc, &iSectorSize) ){ + return TCL_ERROR; + } + + if( iDc>=0 ){ + g.iDeviceCharacteristics = iDc; + } + if( iSectorSize>=0 ){ + g.iSectorSize = iSectorSize; + } + + g.iCrash = iDelay; + memcpy(g.zCrashFile, zCrashFile, nCrashFile+1); + sqlite3CrashTestEnable = 1; + return TCL_OK; + +error: + return TCL_ERROR; +} + +static int devSymObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + void devsym_register(int iDeviceChar, int iSectorSize); + + int iDc = -1; + int iSectorSize = -1; + + if( processDevSymArgs(interp, objc-1, &objv[1], &iDc, &iSectorSize) ){ + return TCL_ERROR; + } + devsym_register(iDc, iSectorSize); + + return TCL_OK; +} + +/* +** tclcmd: register_jt_vfs ?-default? PARENT-VFS +*/ +static int jtObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int jt_register(char *, int); + char *zParent = 0; + + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?-default? PARENT-VFS"); + return TCL_ERROR; + } + zParent = Tcl_GetString(objv[1]); + if( objc==3 ){ + if( strcmp(zParent, "-default") ){ + Tcl_AppendResult(interp, + "bad option \"", zParent, "\": must be -default", 0 + ); + return TCL_ERROR; + } + zParent = Tcl_GetString(objv[2]); + } + + if( !(*zParent) ){ + zParent = 0; + } + if( jt_register(zParent, objc==3) ){ + Tcl_AppendResult(interp, "Error in jt_register", 0); + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** tclcmd: unregister_jt_vfs +*/ +static int jtUnregisterObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + void jt_unregister(void); + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + jt_unregister(); + return TCL_OK; +} + +#endif /* SQLITE_OMIT_DISKIO */ + +/* +** This procedure registers the TCL procedures defined in this file. +*/ +int Sqlitetest6_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_DISKIO + Tcl_CreateObjCommand(interp, "sqlite3_crash_enable", crashEnableCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_crashparams", crashParamsObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_simulate_device", devSymObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "register_jt_vfs", jtObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "unregister_jt_vfs", jtUnregisterObjCmd, 0, 0); +#endif + return TCL_OK; +} + +#endif /* SQLITE_TEST */ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test7.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test7.c new file mode 100644 index 0000000000000000000000000000000000000000..93bf1e4898b004ce10dc131a1f4258b8a3f20aaf --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test7.c @@ -0,0 +1,714 @@ +/* +** 2006 January 09 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing the client/server version of the SQLite library. +** Derived from test4.c. +*/ +#include "sqliteInt.h" +#include "tcl.h" + +/* +** This test only works on UNIX with a SQLITE_THREADSAFE build that includes +** the SQLITE_SERVER option. +*/ +#if defined(SQLITE_SERVER) && !defined(SQLITE_OMIT_SHARED_CACHE) && \ + SQLITE_OS_UNIX && SQLITE_THREADSAFE + +#include +#include +#include +#include +#include + +/* +** Interfaces defined in server.c +*/ +int sqlite3_client_open(const char*, sqlite3**); +int sqlite3_client_prepare(sqlite3*,const char*,int, + sqlite3_stmt**,const char**); +int sqlite3_client_step(sqlite3_stmt*); +int sqlite3_client_reset(sqlite3_stmt*); +int sqlite3_client_finalize(sqlite3_stmt*); +int sqlite3_client_close(sqlite3*); +int sqlite3_server_start(void); +int sqlite3_server_stop(void); +void sqlite3_server_start2(int *pnDecr); + +/* +** Each thread is controlled by an instance of the following +** structure. +*/ +typedef struct Thread Thread; +struct Thread { + /* The first group of fields are writable by the supervisor thread + ** and read-only to the client threads + */ + char *zFilename; /* Name of database file */ + void (*xOp)(Thread*); /* next operation to do */ + char *zArg; /* argument usable by xOp */ + volatile int opnum; /* Operation number */ + volatile int busy; /* True if this thread is in use */ + + /* The next group of fields are writable by the client threads + ** but read-only to the superviser thread. + */ + volatile int completed; /* Number of operations completed */ + sqlite3 *db; /* Open database */ + sqlite3_stmt *pStmt; /* Pending operation */ + char *zErr; /* operation error */ + char *zStaticErr; /* Static error message */ + int rc; /* operation return code */ + int argc; /* number of columns in result */ + const char *argv[100]; /* result columns */ + const char *colv[100]; /* result column names */ + + /* Initialized to 1 by the supervisor thread when the client is + ** created, and then deemed read-only to the supervisor thread. + ** Is set to 0 by the server thread belonging to this client + ** just before it exits. + */ + int nServer; /* Number of server threads running */ +}; + +/* +** There can be as many as 26 threads running at once. Each is named +** by a capital letter: A, B, C, ..., Y, Z. +*/ +#define N_THREAD 26 +static Thread threadset[N_THREAD]; + +/* +** The main loop for a thread. Threads use busy waiting. +*/ +static void *client_main(void *pArg){ + Thread *p = (Thread*)pArg; + if( p->db ){ + sqlite3_client_close(p->db); + } + sqlite3_client_open(p->zFilename, &p->db); + if( SQLITE_OK!=sqlite3_errcode(p->db) ){ + p->zErr = strdup(sqlite3_errmsg(p->db)); + sqlite3_client_close(p->db); + p->db = 0; + } + p->pStmt = 0; + p->completed = 1; + while( p->opnum<=p->completed ) sched_yield(); + while( p->xOp ){ + if( p->zErr && p->zErr!=p->zStaticErr ){ + sqlite3_free(p->zErr); + p->zErr = 0; + } + (*p->xOp)(p); + p->completed++; + while( p->opnum<=p->completed ) sched_yield(); + } + if( p->pStmt ){ + sqlite3_client_finalize(p->pStmt); + p->pStmt = 0; + } + if( p->db ){ + sqlite3_client_close(p->db); + p->db = 0; + } + if( p->zErr && p->zErr!=p->zStaticErr ){ + sqlite3_free(p->zErr); + p->zErr = 0; + } + p->completed++; +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_thread_cleanup(); +#endif + return 0; +} + +/* +** Get a thread ID which is an upper case letter. Return the index. +** If the argument is not a valid thread ID put an error message in +** the interpreter and return -1. +*/ +static int parse_client_id(Tcl_Interp *interp, const char *zArg){ + if( zArg==0 || zArg[0]==0 || zArg[1]!=0 || !isupper((unsigned char)zArg[0]) ){ + Tcl_AppendResult(interp, "thread ID must be an upper case letter", 0); + return -1; + } + return zArg[0] - 'A'; +} + +/* +** Usage: client_create NAME FILENAME +** +** NAME should be an upper case letter. Start the thread running with +** an open connection to the given database. +*/ +static int tcl_client_create( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + pthread_t x; + int rc; + + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID FILENAME", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( threadset[i].busy ){ + Tcl_AppendResult(interp, "thread ", argv[1], " is already running", 0); + return TCL_ERROR; + } + threadset[i].busy = 1; + sqlite3_free(threadset[i].zFilename); + threadset[i].zFilename = sqlite3_mprintf("%s", argv[2]); + threadset[i].opnum = 1; + threadset[i].completed = 0; + rc = pthread_create(&x, 0, client_main, &threadset[i]); + if( rc ){ + Tcl_AppendResult(interp, "failed to create the thread", 0); + sqlite3_free(threadset[i].zFilename); + threadset[i].busy = 0; + return TCL_ERROR; + } + pthread_detach(x); + if( threadset[i].nServer==0 ){ + threadset[i].nServer = 1; + sqlite3_server_start2(&threadset[i].nServer); + } + return TCL_OK; +} + +/* +** Wait for a thread to reach its idle state. +*/ +static void client_wait(Thread *p){ + while( p->opnum>p->completed ) sched_yield(); +} + +/* +** Usage: client_wait ID +** +** Wait on thread ID to reach its idle state. +*/ +static int tcl_client_wait( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + return TCL_OK; +} + +/* +** Stop a thread. +*/ +static void stop_thread(Thread *p){ + client_wait(p); + p->xOp = 0; + p->opnum++; + client_wait(p); + sqlite3_free(p->zArg); + p->zArg = 0; + sqlite3_free(p->zFilename); + p->zFilename = 0; + p->busy = 0; +} + +/* +** Usage: client_halt ID +** +** Cause a client thread to shut itself down. Wait for the shutdown to be +** completed. If ID is "*" then stop all client threads. +*/ +static int tcl_client_halt( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + if( argv[1][0]=='*' && argv[1][1]==0 ){ + for(i=0; i=N_THREAD ){ + sqlite3_server_stop(); + while( 1 ){ + for(i=0; i=threadset[i].argc ){ + Tcl_AppendResult(interp, "column number out of range", 0); + return TCL_ERROR; + } + Tcl_AppendResult(interp, threadset[i].argv[n], 0); + return TCL_OK; +} + +/* +** Usage: client_colname ID N +** +** Wait on the most recent client_step to complete, then return the +** name of the N-th columns in the result set. +*/ +static int tcl_client_colname( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + int n; + + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID N", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR; + client_wait(&threadset[i]); + if( n<0 || n>=threadset[i].argc ){ + Tcl_AppendResult(interp, "column number out of range", 0); + return TCL_ERROR; + } + Tcl_AppendResult(interp, threadset[i].colv[n], 0); + return TCL_OK; +} + +extern const char *sqlite3ErrName(int); + +/* +** Usage: client_result ID +** +** Wait on the most recent operation to complete, then return the +** result code from that operation. +*/ +static int tcl_client_result( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + const char *zName; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + zName = sqlite3ErrName(threadset[i].rc); + Tcl_AppendResult(interp, zName, 0); + return TCL_OK; +} + +/* +** Usage: client_error ID +** +** Wait on the most recent operation to complete, then return the +** error string. +*/ +static int tcl_client_error( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + Tcl_AppendResult(interp, threadset[i].zErr, 0); + return TCL_OK; +} + +/* +** This procedure runs in the thread to compile an SQL statement. +*/ +static void do_compile(Thread *p){ + if( p->db==0 ){ + p->zErr = p->zStaticErr = "no database is open"; + p->rc = SQLITE_ERROR; + return; + } + if( p->pStmt ){ + sqlite3_client_finalize(p->pStmt); + p->pStmt = 0; + } + p->rc = sqlite3_client_prepare(p->db, p->zArg, -1, &p->pStmt, 0); +} + +/* +** Usage: client_compile ID SQL +** +** Compile a new virtual machine. +*/ +static int tcl_client_compile( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID SQL", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + threadset[i].xOp = do_compile; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = sqlite3_mprintf("%s", argv[2]); + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to step the virtual machine. +*/ +static void do_step(Thread *p){ + int i; + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_client_step(p->pStmt); + if( p->rc==SQLITE_ROW ){ + p->argc = sqlite3_column_count(p->pStmt); + for(i=0; ipStmt); i++){ + p->argv[i] = (char*)sqlite3_column_text(p->pStmt, i); + } + for(i=0; iargc; i++){ + p->colv[i] = sqlite3_column_name(p->pStmt, i); + } + } +} + +/* +** Usage: client_step ID +** +** Advance the virtual machine by one step +*/ +static int tcl_client_step( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + threadset[i].xOp = do_step; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to finalize a virtual machine. +*/ +static void do_finalize(Thread *p){ + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_client_finalize(p->pStmt); + p->pStmt = 0; +} + +/* +** Usage: client_finalize ID +** +** Finalize the virtual machine. +*/ +static int tcl_client_finalize( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + threadset[i].xOp = do_finalize; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = 0; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to reset a virtual machine. +*/ +static void do_reset(Thread *p){ + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_client_reset(p->pStmt); + p->pStmt = 0; +} + +/* +** Usage: client_reset ID +** +** Finalize the virtual machine. +*/ +static int tcl_client_reset( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + threadset[i].xOp = do_reset; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = 0; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** Usage: client_swap ID ID +** +** Interchange the sqlite* pointer between two threads. +*/ +static int tcl_client_swap( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i, j; + sqlite3 *temp; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID1 ID2", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + j = parse_client_id(interp, argv[2]); + if( j<0 ) return TCL_ERROR; + if( !threadset[j].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[j]); + temp = threadset[i].db; + threadset[i].db = threadset[j].db; + threadset[j].db = temp; + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest7_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "client_create", (Tcl_CmdProc*)tcl_client_create }, + { "client_wait", (Tcl_CmdProc*)tcl_client_wait }, + { "client_halt", (Tcl_CmdProc*)tcl_client_halt }, + { "client_argc", (Tcl_CmdProc*)tcl_client_argc }, + { "client_argv", (Tcl_CmdProc*)tcl_client_argv }, + { "client_colname", (Tcl_CmdProc*)tcl_client_colname }, + { "client_result", (Tcl_CmdProc*)tcl_client_result }, + { "client_error", (Tcl_CmdProc*)tcl_client_error }, + { "client_compile", (Tcl_CmdProc*)tcl_client_compile }, + { "client_step", (Tcl_CmdProc*)tcl_client_step }, + { "client_reset", (Tcl_CmdProc*)tcl_client_reset }, + { "client_finalize", (Tcl_CmdProc*)tcl_client_finalize }, + { "client_swap", (Tcl_CmdProc*)tcl_client_swap }, + }; + int i; + + for(i=0; i +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +typedef struct echo_vtab echo_vtab; +typedef struct echo_cursor echo_cursor; + +/* +** The test module defined in this file uses four global Tcl variables to +** commicate with test-scripts: +** +** $::echo_module +** $::echo_module_sync_fail +** $::echo_module_begin_fail +** $::echo_module_cost +** +** The variable ::echo_module is a list. Each time one of the following +** methods is called, one or more elements are appended to the list. +** This is used for automated testing of virtual table modules. +** +** The ::echo_module_sync_fail variable is set by test scripts and read +** by code in this file. If it is set to the name of a real table in the +** the database, then all xSync operations on echo virtual tables that +** use the named table as a backing store will fail. +*/ + +/* +** Errors can be provoked within the following echo virtual table methods: +** +** xBestIndex xOpen xFilter xNext +** xColumn xRowid xUpdate xSync +** xBegin xRename +** +** This is done by setting the global tcl variable: +** +** echo_module_fail($method,$tbl) +** +** where $method is set to the name of the virtual table method to fail +** (i.e. "xBestIndex") and $tbl is the name of the table being echoed (not +** the name of the virtual table, the name of the underlying real table). +*/ + +/* +** An echo virtual-table object. +** +** echo.vtab.aIndex is an array of booleans. The nth entry is true if +** the nth column of the real table is the left-most column of an index +** (implicit or otherwise). In other words, if SQLite can optimize +** a query like "SELECT * FROM real_table WHERE col = ?". +** +** Member variable aCol[] contains copies of the column names of the real +** table. +*/ +struct echo_vtab { + sqlite3_vtab base; + Tcl_Interp *interp; /* Tcl interpreter containing debug variables */ + sqlite3 *db; /* Database connection */ + + int isPattern; + int inTransaction; /* True if within a transaction */ + char *zThis; /* Name of the echo table */ + char *zTableName; /* Name of the real table */ + char *zLogName; /* Name of the log table */ + int nCol; /* Number of columns in the real table */ + int *aIndex; /* Array of size nCol. True if column has an index */ + char **aCol; /* Array of size nCol. Column names */ +}; + +/* An echo cursor object */ +struct echo_cursor { + sqlite3_vtab_cursor base; + sqlite3_stmt *pStmt; +}; + +static int simulateVtabError(echo_vtab *p, const char *zMethod){ + const char *zErr; + char zVarname[128]; + zVarname[127] = '\0'; + sqlite3_snprintf(127, zVarname, "echo_module_fail(%s,%s)", zMethod, p->zTableName); + zErr = Tcl_GetVar(p->interp, zVarname, TCL_GLOBAL_ONLY); + if( zErr ){ + p->base.zErrMsg = sqlite3_mprintf("echo-vtab-error: %s", zErr); + } + return (zErr!=0); +} + +/* +** Convert an SQL-style quoted string into a normal string by removing +** the quote characters. The conversion is done in-place. If the +** input does not begin with a quote character, then this routine +** is a no-op. +** +** Examples: +** +** "abc" becomes abc +** 'xyz' becomes xyz +** [pqr] becomes pqr +** `mno` becomes mno +*/ +static void dequoteString(char *z){ + int quote; + int i, j; + if( z==0 ) return; + quote = z[0]; + switch( quote ){ + case '\'': break; + case '"': break; + case '`': break; /* For MySQL compatibility */ + case '[': quote = ']'; break; /* For MS SqlServer compatibility */ + default: return; + } + for(i=1, j=0; z[i]; i++){ + if( z[i]==quote ){ + if( z[i+1]==quote ){ + z[j++] = quote; + i++; + }else{ + z[j++] = 0; + break; + } + }else{ + z[j++] = z[i]; + } + } +} + +/* +** Retrieve the column names for the table named zTab via database +** connection db. SQLITE_OK is returned on success, or an sqlite error +** code otherwise. +** +** If successful, the number of columns is written to *pnCol. *paCol is +** set to point at sqlite3_malloc()'d space containing the array of +** nCol column names. The caller is responsible for calling sqlite3_free +** on *paCol. +*/ +static int getColumnNames( + sqlite3 *db, + const char *zTab, + char ***paCol, + int *pnCol +){ + char **aCol = 0; + char *zSql; + sqlite3_stmt *pStmt = 0; + int rc = SQLITE_OK; + int nCol = 0; + + /* Prepare the statement "SELECT * FROM ". The column names + ** of the result set of the compiled SELECT will be the same as + ** the column names of table . + */ + zSql = sqlite3_mprintf("SELECT * FROM %Q", zTab); + if( !zSql ){ + rc = SQLITE_NOMEM; + goto out; + } + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + + if( rc==SQLITE_OK ){ + int ii; + int nBytes; + char *zSpace; + nCol = sqlite3_column_count(pStmt); + + /* Figure out how much space to allocate for the array of column names + ** (including space for the strings themselves). Then allocate it. + */ + nBytes = sizeof(char *) * nCol; + for(ii=0; ii=0 && cidzTableName ){ + sqlite3_stmt *pStmt = 0; + rc = sqlite3_prepare(db, + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", + -1, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_text(pStmt, 1, pVtab->zTableName, -1, 0); + if( sqlite3_step(pStmt)==SQLITE_ROW ){ + int rc2; + const char *zCreateTable = (const char *)sqlite3_column_text(pStmt, 0); + rc = sqlite3_declare_vtab(db, zCreateTable); + rc2 = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } else { + rc = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ){ + rc = SQLITE_ERROR; + } + } + if( rc==SQLITE_OK ){ + rc = getColumnNames(db, pVtab->zTableName, &pVtab->aCol, &pVtab->nCol); + } + if( rc==SQLITE_OK ){ + rc = getIndexArray(db, pVtab->zTableName, pVtab->nCol, &pVtab->aIndex); + } + } + } + + return rc; +} + +/* +** This function frees all runtime structures associated with the virtual +** table pVtab. +*/ +static int echoDestructor(sqlite3_vtab *pVtab){ + echo_vtab *p = (echo_vtab*)pVtab; + sqlite3_free(p->aIndex); + sqlite3_free(p->aCol); + sqlite3_free(p->zThis); + sqlite3_free(p->zTableName); + sqlite3_free(p->zLogName); + sqlite3_free(p); + return 0; +} + +typedef struct EchoModule EchoModule; +struct EchoModule { + Tcl_Interp *interp; +}; + +/* +** This function is called to do the work of the xConnect() method - +** to allocate the required in-memory structures for a newly connected +** virtual table. +*/ +static int echoConstructor( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int rc; + int i; + echo_vtab *pVtab; + + /* Allocate the sqlite3_vtab/echo_vtab structure itself */ + pVtab = sqlite3MallocZero( sizeof(*pVtab) ); + if( !pVtab ){ + return SQLITE_NOMEM; + } + pVtab->interp = ((EchoModule *)pAux)->interp; + pVtab->db = db; + + /* Allocate echo_vtab.zThis */ + pVtab->zThis = sqlite3_mprintf("%s", argv[2]); + if( !pVtab->zThis ){ + echoDestructor((sqlite3_vtab *)pVtab); + return SQLITE_NOMEM; + } + + /* Allocate echo_vtab.zTableName */ + if( argc>3 ){ + pVtab->zTableName = sqlite3_mprintf("%s", argv[3]); + dequoteString(pVtab->zTableName); + if( pVtab->zTableName && pVtab->zTableName[0]=='*' ){ + char *z = sqlite3_mprintf("%s%s", argv[2], &(pVtab->zTableName[1])); + sqlite3_free(pVtab->zTableName); + pVtab->zTableName = z; + pVtab->isPattern = 1; + } + if( !pVtab->zTableName ){ + echoDestructor((sqlite3_vtab *)pVtab); + return SQLITE_NOMEM; + } + } + + /* Log the arguments to this function to Tcl var ::echo_module */ + for(i=0; iinterp, argv[i]); + } + + /* Invoke sqlite3_declare_vtab and set up other members of the echo_vtab + ** structure. If an error occurs, delete the sqlite3_vtab structure and + ** return an error code. + */ + rc = echoDeclareVtab(pVtab, db); + if( rc!=SQLITE_OK ){ + echoDestructor((sqlite3_vtab *)pVtab); + return rc; + } + + /* Success. Set *ppVtab and return */ + *ppVtab = &pVtab->base; + return SQLITE_OK; +} + +/* +** Echo virtual table module xCreate method. +*/ +static int echoCreate( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int rc = SQLITE_OK; + appendToEchoModule(((EchoModule *)pAux)->interp, "xCreate"); + rc = echoConstructor(db, pAux, argc, argv, ppVtab, pzErr); + + /* If there were two arguments passed to the module at the SQL level + ** (i.e. "CREATE VIRTUAL TABLE tbl USING echo(arg1, arg2)"), then + ** the second argument is used as a table name. Attempt to create + ** such a table with a single column, "logmsg". This table will + ** be used to log calls to the xUpdate method. It will be deleted + ** when the virtual table is DROPed. + ** + ** Note: The main point of this is to test that we can drop tables + ** from within an xDestroy method call. + */ + if( rc==SQLITE_OK && argc==5 ){ + char *zSql; + echo_vtab *pVtab = *(echo_vtab **)ppVtab; + pVtab->zLogName = sqlite3_mprintf("%s", argv[4]); + zSql = sqlite3_mprintf("CREATE TABLE %Q(logmsg)", pVtab->zLogName); + rc = sqlite3_exec(db, zSql, 0, 0, 0); + sqlite3_free(zSql); + if( rc!=SQLITE_OK ){ + *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + } + } + + if( *ppVtab && rc!=SQLITE_OK ){ + echoDestructor(*ppVtab); + *ppVtab = 0; + } + + if( rc==SQLITE_OK ){ + (*(echo_vtab**)ppVtab)->inTransaction = 1; + } + + return rc; +} + +/* +** Echo virtual table module xConnect method. +*/ +static int echoConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + appendToEchoModule(((EchoModule *)pAux)->interp, "xConnect"); + return echoConstructor(db, pAux, argc, argv, ppVtab, pzErr); +} + +/* +** Echo virtual table module xDisconnect method. +*/ +static int echoDisconnect(sqlite3_vtab *pVtab){ + appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDisconnect"); + return echoDestructor(pVtab); +} + +/* +** Echo virtual table module xDestroy method. +*/ +static int echoDestroy(sqlite3_vtab *pVtab){ + int rc = SQLITE_OK; + echo_vtab *p = (echo_vtab *)pVtab; + appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDestroy"); + + /* Drop the "log" table, if one exists (see echoCreate() for details) */ + if( p && p->zLogName ){ + char *zSql; + zSql = sqlite3_mprintf("DROP TABLE %Q", p->zLogName); + rc = sqlite3_exec(p->db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } + + if( rc==SQLITE_OK ){ + rc = echoDestructor(pVtab); + } + return rc; +} + +/* +** Echo virtual table module xOpen method. +*/ +static int echoOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + echo_cursor *pCur; + if( simulateVtabError((echo_vtab *)pVTab, "xOpen") ){ + return SQLITE_ERROR; + } + pCur = sqlite3MallocZero(sizeof(echo_cursor)); + *ppCursor = (sqlite3_vtab_cursor *)pCur; + return (pCur ? SQLITE_OK : SQLITE_NOMEM); +} + +/* +** Echo virtual table module xClose method. +*/ +static int echoClose(sqlite3_vtab_cursor *cur){ + int rc; + echo_cursor *pCur = (echo_cursor *)cur; + sqlite3_stmt *pStmt = pCur->pStmt; + pCur->pStmt = 0; + sqlite3_free(pCur); + rc = sqlite3_finalize(pStmt); + return rc; +} + +/* +** Return non-zero if the cursor does not currently point to a valid record +** (i.e if the scan has finished), or zero otherwise. +*/ +static int echoEof(sqlite3_vtab_cursor *cur){ + return (((echo_cursor *)cur)->pStmt ? 0 : 1); +} + +/* +** Echo virtual table module xNext method. +*/ +static int echoNext(sqlite3_vtab_cursor *cur){ + int rc = SQLITE_OK; + echo_cursor *pCur = (echo_cursor *)cur; + + if( simulateVtabError((echo_vtab *)(cur->pVtab), "xNext") ){ + return SQLITE_ERROR; + } + + if( pCur->pStmt ){ + rc = sqlite3_step(pCur->pStmt); + if( rc==SQLITE_ROW ){ + rc = SQLITE_OK; + }else{ + rc = sqlite3_finalize(pCur->pStmt); + pCur->pStmt = 0; + } + } + + return rc; +} + +/* +** Echo virtual table module xColumn method. +*/ +static int echoColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + int iCol = i + 1; + sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt; + + if( simulateVtabError((echo_vtab *)(cur->pVtab), "xColumn") ){ + return SQLITE_ERROR; + } + + if( !pStmt ){ + sqlite3_result_null(ctx); + }else{ + assert( sqlite3_data_count(pStmt)>iCol ); + sqlite3_result_value(ctx, sqlite3_column_value(pStmt, iCol)); + } + return SQLITE_OK; +} + +/* +** Echo virtual table module xRowid method. +*/ +static int echoRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt; + + if( simulateVtabError((echo_vtab *)(cur->pVtab), "xRowid") ){ + return SQLITE_ERROR; + } + + *pRowid = sqlite3_column_int64(pStmt, 0); + return SQLITE_OK; +} + +/* +** Compute a simple hash of the null terminated string zString. +** +** This module uses only sqlite3_index_info.idxStr, not +** sqlite3_index_info.idxNum. So to test idxNum, when idxStr is set +** in echoBestIndex(), idxNum is set to the corresponding hash value. +** In echoFilter(), code assert()s that the supplied idxNum value is +** indeed the hash of the supplied idxStr. +*/ +static int hashString(const char *zString){ + int val = 0; + int ii; + for(ii=0; zString[ii]; ii++){ + val = (val << 3) + (int)zString[ii]; + } + return val; +} + +/* +** Echo virtual table module xFilter method. +*/ +static int echoFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + int rc; + int i; + + echo_cursor *pCur = (echo_cursor *)pVtabCursor; + echo_vtab *pVtab = (echo_vtab *)pVtabCursor->pVtab; + sqlite3 *db = pVtab->db; + + if( simulateVtabError(pVtab, "xFilter") ){ + return SQLITE_ERROR; + } + + /* Check that idxNum matches idxStr */ + assert( idxNum==hashString(idxStr) ); + + /* Log arguments to the ::echo_module Tcl variable */ + appendToEchoModule(pVtab->interp, "xFilter"); + appendToEchoModule(pVtab->interp, idxStr); + for(i=0; iinterp, (const char*)sqlite3_value_text(argv[i])); + } + + sqlite3_finalize(pCur->pStmt); + pCur->pStmt = 0; + + /* Prepare the SQL statement created by echoBestIndex and bind the + ** runtime parameters passed to this function to it. + */ + rc = sqlite3_prepare(db, idxStr, -1, &pCur->pStmt, 0); + assert( pCur->pStmt || rc!=SQLITE_OK ); + for(i=0; rc==SQLITE_OK && ipStmt, i+1, argv[i]); + } + + /* If everything was successful, advance to the first row of the scan */ + if( rc==SQLITE_OK ){ + rc = echoNext(pVtabCursor); + } + + return rc; +} + + +/* +** A helper function used by echoUpdate() and echoBestIndex() for +** manipulating strings in concert with the sqlite3_mprintf() function. +** +** Parameter pzStr points to a pointer to a string allocated with +** sqlite3_mprintf. The second parameter, zAppend, points to another +** string. The two strings are concatenated together and *pzStr +** set to point at the result. The initial buffer pointed to by *pzStr +** is deallocated via sqlite3_free(). +** +** If the third argument, doFree, is true, then sqlite3_free() is +** also called to free the buffer pointed to by zAppend. +*/ +static void string_concat(char **pzStr, char *zAppend, int doFree, int *pRc){ + char *zIn = *pzStr; + if( !zAppend && doFree && *pRc==SQLITE_OK ){ + *pRc = SQLITE_NOMEM; + } + if( *pRc!=SQLITE_OK ){ + sqlite3_free(zIn); + zIn = 0; + }else{ + if( zIn ){ + char *zTemp = zIn; + zIn = sqlite3_mprintf("%s%s", zIn, zAppend); + sqlite3_free(zTemp); + }else{ + zIn = sqlite3_mprintf("%s", zAppend); + } + if( !zIn ){ + *pRc = SQLITE_NOMEM; + } + } + *pzStr = zIn; + if( doFree ){ + sqlite3_free(zAppend); + } +} + +/* +** The echo module implements the subset of query constraints and sort +** orders that may take advantage of SQLite indices on the underlying +** real table. For example, if the real table is declared as: +** +** CREATE TABLE real(a, b, c); +** CREATE INDEX real_index ON real(b); +** +** then the echo module handles WHERE or ORDER BY clauses that refer +** to the column "b", but not "a" or "c". If a multi-column index is +** present, only its left most column is considered. +** +** This xBestIndex method encodes the proposed search strategy as +** an SQL query on the real table underlying the virtual echo module +** table and stores the query in sqlite3_index_info.idxStr. The SQL +** statement is of the form: +** +** SELECT rowid, * FROM ?? ?? +** +** where the and are determined +** by the contents of the structure pointed to by the pIdxInfo argument. +*/ +static int echoBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int ii; + char *zQuery = 0; + char *zNew; + int nArg = 0; + const char *zSep = "WHERE"; + echo_vtab *pVtab = (echo_vtab *)tab; + sqlite3_stmt *pStmt = 0; + Tcl_Interp *interp = pVtab->interp; + + int nRow; + int useIdx = 0; + int rc = SQLITE_OK; + int useCost = 0; + double cost; + int isIgnoreUsable = 0; + if( Tcl_GetVar(interp, "echo_module_ignore_usable", TCL_GLOBAL_ONLY) ){ + isIgnoreUsable = 1; + } + + if( simulateVtabError(pVtab, "xBestIndex") ){ + return SQLITE_ERROR; + } + + /* Determine the number of rows in the table and store this value in local + ** variable nRow. The 'estimated-cost' of the scan will be the number of + ** rows in the table for a linear scan, or the log (base 2) of the + ** number of rows if the proposed scan uses an index. + */ + if( Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY) ){ + cost = atof(Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY)); + useCost = 1; + } else { + zQuery = sqlite3_mprintf("SELECT count(*) FROM %Q", pVtab->zTableName); + if( !zQuery ){ + return SQLITE_NOMEM; + } + rc = sqlite3_prepare(pVtab->db, zQuery, -1, &pStmt, 0); + sqlite3_free(zQuery); + if( rc!=SQLITE_OK ){ + return rc; + } + sqlite3_step(pStmt); + nRow = sqlite3_column_int(pStmt, 0); + rc = sqlite3_finalize(pStmt); + if( rc!=SQLITE_OK ){ + return rc; + } + } + + zQuery = sqlite3_mprintf("SELECT rowid, * FROM %Q", pVtab->zTableName); + if( !zQuery ){ + return SQLITE_NOMEM; + } + for(ii=0; iinConstraint; ii++){ + const struct sqlite3_index_constraint *pConstraint; + struct sqlite3_index_constraint_usage *pUsage; + int iCol; + + pConstraint = &pIdxInfo->aConstraint[ii]; + pUsage = &pIdxInfo->aConstraintUsage[ii]; + + if( !isIgnoreUsable && !pConstraint->usable ) continue; + + iCol = pConstraint->iColumn; + if( iCol<0 || pVtab->aIndex[iCol] ){ + char *zCol = iCol>=0 ? pVtab->aCol[iCol] : "rowid"; + char *zOp = 0; + useIdx = 1; + switch( pConstraint->op ){ + case SQLITE_INDEX_CONSTRAINT_EQ: + zOp = "="; break; + case SQLITE_INDEX_CONSTRAINT_LT: + zOp = "<"; break; + case SQLITE_INDEX_CONSTRAINT_GT: + zOp = ">"; break; + case SQLITE_INDEX_CONSTRAINT_LE: + zOp = "<="; break; + case SQLITE_INDEX_CONSTRAINT_GE: + zOp = ">="; break; + case SQLITE_INDEX_CONSTRAINT_MATCH: + zOp = "LIKE"; break; + } + if( zOp[0]=='L' ){ + zNew = sqlite3_mprintf(" %s %s LIKE (SELECT '%%'||?||'%%')", + zSep, zCol); + } else { + zNew = sqlite3_mprintf(" %s %s %s ?", zSep, zCol, zOp); + } + string_concat(&zQuery, zNew, 1, &rc); + + zSep = "AND"; + pUsage->argvIndex = ++nArg; + pUsage->omit = 1; + } + } + + /* If there is only one term in the ORDER BY clause, and it is + ** on a column that this virtual table has an index for, then consume + ** the ORDER BY clause. + */ + if( pIdxInfo->nOrderBy==1 && ( + pIdxInfo->aOrderBy->iColumn<0 || + pVtab->aIndex[pIdxInfo->aOrderBy->iColumn]) ){ + int iCol = pIdxInfo->aOrderBy->iColumn; + char *zCol = iCol>=0 ? pVtab->aCol[iCol] : "rowid"; + char *zDir = pIdxInfo->aOrderBy->desc?"DESC":"ASC"; + zNew = sqlite3_mprintf(" ORDER BY %s %s", zCol, zDir); + string_concat(&zQuery, zNew, 1, &rc); + pIdxInfo->orderByConsumed = 1; + } + + appendToEchoModule(pVtab->interp, "xBestIndex");; + appendToEchoModule(pVtab->interp, zQuery); + + if( !zQuery ){ + return rc; + } + pIdxInfo->idxNum = hashString(zQuery); + pIdxInfo->idxStr = zQuery; + pIdxInfo->needToFreeIdxStr = 1; + if( useCost ){ + pIdxInfo->estimatedCost = cost; + }else if( useIdx ){ + /* Approximation of log2(nRow). */ + for( ii=0; ii<(sizeof(int)*8); ii++ ){ + if( nRow & (1<estimatedCost = (double)ii; + } + } + }else{ + pIdxInfo->estimatedCost = (double)nRow; + } + return rc; +} + +/* +** The xUpdate method for echo module virtual tables. +** +** apData[0] apData[1] apData[2..] +** +** INTEGER DELETE +** +** INTEGER NULL (nCol args) UPDATE (do not set rowid) +** INTEGER INTEGER (nCol args) UPDATE (with SET rowid = ) +** +** NULL NULL (nCol args) INSERT INTO (automatic rowid value) +** NULL INTEGER (nCol args) INSERT (incl. rowid value) +** +*/ +int echoUpdate( + sqlite3_vtab *tab, + int nData, + sqlite3_value **apData, + sqlite_int64 *pRowid +){ + echo_vtab *pVtab = (echo_vtab *)tab; + sqlite3 *db = pVtab->db; + int rc = SQLITE_OK; + + sqlite3_stmt *pStmt; + char *z = 0; /* SQL statement to execute */ + int bindArgZero = 0; /* True to bind apData[0] to sql var no. nData */ + int bindArgOne = 0; /* True to bind apData[1] to sql var no. 1 */ + int i; /* Counter variable used by for loops */ + + assert( nData==pVtab->nCol+2 || nData==1 ); + + /* Ticket #3083 - make sure we always start a transaction prior to + ** making any changes to a virtual table */ + assert( pVtab->inTransaction ); + + if( simulateVtabError(pVtab, "xUpdate") ){ + return SQLITE_ERROR; + } + + /* If apData[0] is an integer and nData>1 then do an UPDATE */ + if( nData>1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){ + char *zSep = " SET"; + z = sqlite3_mprintf("UPDATE %Q", pVtab->zTableName); + if( !z ){ + rc = SQLITE_NOMEM; + } + + bindArgOne = (apData[1] && sqlite3_value_type(apData[1])==SQLITE_INTEGER); + bindArgZero = 1; + + if( bindArgOne ){ + string_concat(&z, " SET rowid=?1 ", 0, &rc); + zSep = ","; + } + for(i=2; iaCol[i-2], i), 1, &rc); + zSep = ","; + } + string_concat(&z, sqlite3_mprintf(" WHERE rowid=?%d", nData), 1, &rc); + } + + /* If apData[0] is an integer and nData==1 then do a DELETE */ + else if( nData==1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){ + z = sqlite3_mprintf("DELETE FROM %Q WHERE rowid = ?1", pVtab->zTableName); + if( !z ){ + rc = SQLITE_NOMEM; + } + bindArgZero = 1; + } + + /* If the first argument is NULL and there are more than two args, INSERT */ + else if( nData>2 && sqlite3_value_type(apData[0])==SQLITE_NULL ){ + int ii; + char *zInsert = 0; + char *zValues = 0; + + zInsert = sqlite3_mprintf("INSERT INTO %Q (", pVtab->zTableName); + if( !zInsert ){ + rc = SQLITE_NOMEM; + } + if( sqlite3_value_type(apData[1])==SQLITE_INTEGER ){ + bindArgOne = 1; + zValues = sqlite3_mprintf("?"); + string_concat(&zInsert, "rowid", 0, &rc); + } + + assert((pVtab->nCol+2)==nData); + for(ii=2; iiaCol[ii-2]), 1, &rc); + string_concat(&zValues, + sqlite3_mprintf("%s?%d", zValues?", ":"", ii), 1, &rc); + } + + string_concat(&z, zInsert, 1, &rc); + string_concat(&z, ") VALUES(", 0, &rc); + string_concat(&z, zValues, 1, &rc); + string_concat(&z, ")", 0, &rc); + } + + /* Anything else is an error */ + else{ + assert(0); + return SQLITE_ERROR; + } + + if( rc==SQLITE_OK ){ + rc = sqlite3_prepare(db, z, -1, &pStmt, 0); + } + assert( rc!=SQLITE_OK || pStmt ); + sqlite3_free(z); + if( rc==SQLITE_OK ) { + if( bindArgZero ){ + sqlite3_bind_value(pStmt, nData, apData[0]); + } + if( bindArgOne ){ + sqlite3_bind_value(pStmt, 1, apData[1]); + } + for(i=2; izErrMsg = sqlite3_mprintf("echo-vtab-error: %s", sqlite3_errmsg(db)); + } + + return rc; +} + +/* +** xBegin, xSync, xCommit and xRollback callbacks for echo module +** virtual tables. Do nothing other than add the name of the callback +** to the $::echo_module Tcl variable. +*/ +static int echoTransactionCall(sqlite3_vtab *tab, const char *zCall){ + char *z; + echo_vtab *pVtab = (echo_vtab *)tab; + z = sqlite3_mprintf("echo(%s)", pVtab->zTableName); + if( z==0 ) return SQLITE_NOMEM; + appendToEchoModule(pVtab->interp, zCall); + appendToEchoModule(pVtab->interp, z); + sqlite3_free(z); + return SQLITE_OK; +} +static int echoBegin(sqlite3_vtab *tab){ + int rc; + echo_vtab *pVtab = (echo_vtab *)tab; + Tcl_Interp *interp = pVtab->interp; + const char *zVal; + + /* Ticket #3083 - do not start a transaction if we are already in + ** a transaction */ + assert( !pVtab->inTransaction ); + + if( simulateVtabError(pVtab, "xBegin") ){ + return SQLITE_ERROR; + } + + rc = echoTransactionCall(tab, "xBegin"); + + if( rc==SQLITE_OK ){ + /* Check if the $::echo_module_begin_fail variable is defined. If it is, + ** and it is set to the name of the real table underlying this virtual + ** echo module table, then cause this xSync operation to fail. + */ + zVal = Tcl_GetVar(interp, "echo_module_begin_fail", TCL_GLOBAL_ONLY); + if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){ + rc = SQLITE_ERROR; + } + } + if( rc==SQLITE_OK ){ + pVtab->inTransaction = 1; + } + return rc; +} +static int echoSync(sqlite3_vtab *tab){ + int rc; + echo_vtab *pVtab = (echo_vtab *)tab; + Tcl_Interp *interp = pVtab->interp; + const char *zVal; + + /* Ticket #3083 - Only call xSync if we have previously started a + ** transaction */ + assert( pVtab->inTransaction ); + + if( simulateVtabError(pVtab, "xSync") ){ + return SQLITE_ERROR; + } + + rc = echoTransactionCall(tab, "xSync"); + + if( rc==SQLITE_OK ){ + /* Check if the $::echo_module_sync_fail variable is defined. If it is, + ** and it is set to the name of the real table underlying this virtual + ** echo module table, then cause this xSync operation to fail. + */ + zVal = Tcl_GetVar(interp, "echo_module_sync_fail", TCL_GLOBAL_ONLY); + if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){ + rc = -1; + } + } + return rc; +} +static int echoCommit(sqlite3_vtab *tab){ + echo_vtab *pVtab = (echo_vtab*)tab; + int rc; + + /* Ticket #3083 - Only call xCommit if we have previously started + ** a transaction */ + assert( pVtab->inTransaction ); + + if( simulateVtabError(pVtab, "xCommit") ){ + return SQLITE_ERROR; + } + + sqlite3BeginBenignMalloc(); + rc = echoTransactionCall(tab, "xCommit"); + sqlite3EndBenignMalloc(); + pVtab->inTransaction = 0; + return rc; +} +static int echoRollback(sqlite3_vtab *tab){ + int rc; + echo_vtab *pVtab = (echo_vtab*)tab; + + /* Ticket #3083 - Only call xRollback if we have previously started + ** a transaction */ + assert( pVtab->inTransaction ); + + rc = echoTransactionCall(tab, "xRollback"); + pVtab->inTransaction = 0; + return rc; +} + +/* +** Implementation of "GLOB" function on the echo module. Pass +** all arguments to the ::echo_glob_overload procedure of TCL +** and return the result of that procedure as a string. +*/ +static void overloadedGlobFunction( + sqlite3_context *pContext, + int nArg, + sqlite3_value **apArg +){ + Tcl_Interp *interp = sqlite3_user_data(pContext); + Tcl_DString str; + int i; + int rc; + Tcl_DStringInit(&str); + Tcl_DStringAppendElement(&str, "::echo_glob_overload"); + for(i=0; iinterp; + Tcl_CmdInfo info; + if( strcmp(zFuncName,"glob")!=0 ){ + return 0; + } + if( Tcl_GetCommandInfo(interp, "::echo_glob_overload", &info)==0 ){ + return 0; + } + *pxFunc = overloadedGlobFunction; + *ppArg = interp; + return 1; +} + +static int echoRename(sqlite3_vtab *vtab, const char *zNewName){ + int rc = SQLITE_OK; + echo_vtab *p = (echo_vtab *)vtab; + + if( simulateVtabError(p, "xRename") ){ + return SQLITE_ERROR; + } + + if( p->isPattern ){ + int nThis = (int)strlen(p->zThis); + char *zSql = sqlite3_mprintf("ALTER TABLE %s RENAME TO %s%s", + p->zTableName, zNewName, &p->zTableName[nThis] + ); + rc = sqlite3_exec(p->db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } + + return rc; +} + +static int echoSavepoint(sqlite3_vtab *pVTab, int iSavepoint){ + assert( pVTab ); + return SQLITE_OK; +} + +static int echoRelease(sqlite3_vtab *pVTab, int iSavepoint){ + assert( pVTab ); + return SQLITE_OK; +} + +static int echoRollbackTo(sqlite3_vtab *pVTab, int iSavepoint){ + assert( pVTab ); + return SQLITE_OK; +} + +/* +** A virtual table module that merely "echos" the contents of another +** table (like an SQL VIEW). +*/ +static sqlite3_module echoModule = { + 1, /* iVersion */ + echoCreate, + echoConnect, + echoBestIndex, + echoDisconnect, + echoDestroy, + echoOpen, /* xOpen - open a cursor */ + echoClose, /* xClose - close a cursor */ + echoFilter, /* xFilter - configure scan constraints */ + echoNext, /* xNext - advance a cursor */ + echoEof, /* xEof */ + echoColumn, /* xColumn - read data */ + echoRowid, /* xRowid - read data */ + echoUpdate, /* xUpdate - write data */ + echoBegin, /* xBegin - begin transaction */ + echoSync, /* xSync - sync transaction */ + echoCommit, /* xCommit - commit transaction */ + echoRollback, /* xRollback - rollback transaction */ + echoFindFunction, /* xFindFunction - function overloading */ + echoRename /* xRename - rename the table */ +}; + +static sqlite3_module echoModuleV2 = { + 2, /* iVersion */ + echoCreate, + echoConnect, + echoBestIndex, + echoDisconnect, + echoDestroy, + echoOpen, /* xOpen - open a cursor */ + echoClose, /* xClose - close a cursor */ + echoFilter, /* xFilter - configure scan constraints */ + echoNext, /* xNext - advance a cursor */ + echoEof, /* xEof */ + echoColumn, /* xColumn - read data */ + echoRowid, /* xRowid - read data */ + echoUpdate, /* xUpdate - write data */ + echoBegin, /* xBegin - begin transaction */ + echoSync, /* xSync - sync transaction */ + echoCommit, /* xCommit - commit transaction */ + echoRollback, /* xRollback - rollback transaction */ + echoFindFunction, /* xFindFunction - function overloading */ + echoRename, /* xRename - rename the table */ + echoSavepoint, + echoRelease, + echoRollbackTo +}; + +/* +** Decode a pointer to an sqlite3 object. +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); +extern const char *sqlite3ErrName(int); + +static void moduleDestroy(void *p){ + sqlite3_free(p); +} + +/* +** Register the echo virtual table module. +*/ +static int register_echo_module( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int rc; + sqlite3 *db; + EchoModule *pMod; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + /* Virtual table module "echo" */ + pMod = sqlite3_malloc(sizeof(EchoModule)); + pMod->interp = interp; + rc = sqlite3_create_module_v2( + db, "echo", &echoModule, (void*)pMod, moduleDestroy + ); + + /* Virtual table module "echo_v2" */ + if( rc==SQLITE_OK ){ + pMod = sqlite3_malloc(sizeof(EchoModule)); + pMod->interp = interp; + rc = sqlite3_create_module_v2(db, "echo_v2", + &echoModuleV2, (void*)pMod, moduleDestroy + ); + } + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** Tcl interface to sqlite3_declare_vtab, invoked as follows from Tcl: +** +** sqlite3_declare_vtab DB SQL +*/ +static int declare_vtab( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + int rc; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB SQL"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_declare_vtab(db, Tcl_GetString(objv[2])); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE); + return TCL_ERROR; + } + return TCL_OK; +} + +#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest8_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "register_echo_module", register_echo_module, 0 }, + { "sqlite3_declare_vtab", declare_vtab, 0 }, + }; + int i; + for(i=0; i +#include + +/* +** c_collation_test +*/ +static int c_collation_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + const char *zErrFunction = "N/A"; + sqlite3 *db; + + int rc; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + /* Open a database. */ + rc = sqlite3_open(":memory:", &db); + if( rc!=SQLITE_OK ){ + zErrFunction = "sqlite3_open"; + goto error_out; + } + + rc = sqlite3_create_collation(db, "collate", 456, 0, 0); + if( rc!=SQLITE_MISUSE ){ + sqlite3_close(db); + zErrFunction = "sqlite3_create_collation"; + goto error_out; + } + + sqlite3_close(db); + return TCL_OK; + +error_out: + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "Error testing function: ", zErrFunction, 0); + return TCL_ERROR; +} + +/* +** c_realloc_test +*/ +static int c_realloc_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + void *p; + const char *zErrFunction = "N/A"; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + p = sqlite3_malloc(5); + if( !p ){ + zErrFunction = "sqlite3_malloc"; + goto error_out; + } + + /* Test that realloc()ing a block of memory to a negative size is + ** the same as free()ing that memory. + */ + p = sqlite3_realloc(p, -1); + if( p ){ + zErrFunction = "sqlite3_realloc"; + goto error_out; + } + + return TCL_OK; + +error_out: + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "Error testing function: ", zErrFunction, 0); + return TCL_ERROR; +} + + +/* +** c_misuse_test +*/ +static int c_misuse_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + const char *zErrFunction = "N/A"; + sqlite3 *db = 0; + sqlite3_stmt *pStmt; + int rc; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + /* Open a database. Then close it again. We need to do this so that + ** we have a "closed database handle" to pass to various API functions. + */ + rc = sqlite3_open(":memory:", &db); + if( rc!=SQLITE_OK ){ + zErrFunction = "sqlite3_open"; + goto error_out; + } + sqlite3_close(db); + + + rc = sqlite3_errcode(db); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_errcode"; + goto error_out; + } + + pStmt = (sqlite3_stmt*)1234; + rc = sqlite3_prepare(db, 0, 0, &pStmt, 0); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_prepare"; + goto error_out; + } + assert( pStmt==0 ); /* Verify that pStmt is zeroed even on a MISUSE error */ + + pStmt = (sqlite3_stmt*)1234; + rc = sqlite3_prepare_v2(db, 0, 0, &pStmt, 0); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_prepare_v2"; + goto error_out; + } + assert( pStmt==0 ); + +#ifndef SQLITE_OMIT_UTF16 + pStmt = (sqlite3_stmt*)1234; + rc = sqlite3_prepare16(db, 0, 0, &pStmt, 0); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_prepare16"; + goto error_out; + } + assert( pStmt==0 ); + pStmt = (sqlite3_stmt*)1234; + rc = sqlite3_prepare16_v2(db, 0, 0, &pStmt, 0); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_prepare16_v2"; + goto error_out; + } + assert( pStmt==0 ); +#endif + + return TCL_OK; + +error_out: + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "Error testing function: ", zErrFunction, 0); + return TCL_ERROR; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest9_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "c_misuse_test", c_misuse_test, 0 }, + { "c_realloc_test", c_realloc_test, 0 }, + { "c_collation_test", c_collation_test, 0 }, + }; + int i; + for(i=0; i + +#ifdef SQLITE_ENABLE_ASYNCIO + +#include "sqlite3async.h" +#include "sqlite3.h" +#include + +/* From main.c */ +extern const char *sqlite3ErrName(int); + + +struct TestAsyncGlobal { + int isInstalled; /* True when async VFS is installed */ +} testasync_g = { 0 }; + +TCL_DECLARE_MUTEX(testasync_g_writerMutex); + +/* +** sqlite3async_initialize PARENT-VFS ISDEFAULT +*/ +static int testAsyncInit( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zParent; + int isDefault; + int rc; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PARENT-VFS ISDEFAULT"); + return TCL_ERROR; + } + zParent = Tcl_GetString(objv[1]); + if( !*zParent ) { + zParent = 0; + } + if( Tcl_GetBooleanFromObj(interp, objv[2], &isDefault) ){ + return TCL_ERROR; + } + + rc = sqlite3async_initialize(zParent, isDefault); + if( rc!=SQLITE_OK ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** sqlite3async_shutdown +*/ +static int testAsyncShutdown( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3async_shutdown(); + return TCL_OK; +} + +static Tcl_ThreadCreateType tclWriterThread(ClientData pIsStarted){ + Tcl_MutexLock(&testasync_g_writerMutex); + *((int *)pIsStarted) = 1; + sqlite3async_run(); + Tcl_MutexUnlock(&testasync_g_writerMutex); + Tcl_ExitThread(0); + TCL_THREAD_CREATE_RETURN; +} + +/* +** sqlite3async_start +** +** Start a new writer thread. +*/ +static int testAsyncStart( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + volatile int isStarted = 0; + ClientData threadData = (ClientData)&isStarted; + + Tcl_ThreadId x; + const int nStack = TCL_THREAD_STACK_DEFAULT; + const int flags = TCL_THREAD_NOFLAGS; + int rc; + + rc = Tcl_CreateThread(&x, tclWriterThread, threadData, nStack, flags); + if( rc!=TCL_OK ){ + Tcl_AppendResult(interp, "Tcl_CreateThread() failed", 0); + return TCL_ERROR; + } + + while( isStarted==0 ) { /* Busy loop */ } + return TCL_OK; +} + +/* +** sqlite3async_wait +** +** Wait for the current writer thread to terminate. +** +** If the current writer thread is set to run forever then this +** command would block forever. To prevent that, an error is returned. +*/ +static int testAsyncWait( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int eCond; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + sqlite3async_control(SQLITEASYNC_GET_HALT, &eCond); + if( eCond==SQLITEASYNC_HALT_NEVER ){ + Tcl_AppendResult(interp, "would block forever", (char*)0); + return TCL_ERROR; + } + + Tcl_MutexLock(&testasync_g_writerMutex); + Tcl_MutexUnlock(&testasync_g_writerMutex); + return TCL_OK; +} + +/* +** sqlite3async_control OPTION ?VALUE? +*/ +static int testAsyncControl( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = SQLITE_OK; + int aeOpt[] = { SQLITEASYNC_HALT, SQLITEASYNC_DELAY, SQLITEASYNC_LOCKFILES }; + const char *azOpt[] = { "halt", "delay", "lockfiles", 0 }; + const char *az[] = { "never", "now", "idle", 0 }; + int iVal; + int eOpt; + + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "OPTION ?VALUE?"); + return TCL_ERROR; + } + if( Tcl_GetIndexFromObj(interp, objv[1], azOpt, "option", 0, &eOpt) ){ + return TCL_ERROR; + } + eOpt = aeOpt[eOpt]; + + if( objc==3 ){ + switch( eOpt ){ + case SQLITEASYNC_HALT: { + assert( SQLITEASYNC_HALT_NEVER==0 ); + assert( SQLITEASYNC_HALT_NOW==1 ); + assert( SQLITEASYNC_HALT_IDLE==2 ); + if( Tcl_GetIndexFromObj(interp, objv[2], az, "value", 0, &iVal) ){ + return TCL_ERROR; + } + break; + } + case SQLITEASYNC_DELAY: + if( Tcl_GetIntFromObj(interp, objv[2], &iVal) ){ + return TCL_ERROR; + } + break; + + case SQLITEASYNC_LOCKFILES: + if( Tcl_GetBooleanFromObj(interp, objv[2], &iVal) ){ + return TCL_ERROR; + } + break; + } + + rc = sqlite3async_control(eOpt, iVal); + } + + if( rc==SQLITE_OK ){ + rc = sqlite3async_control( + eOpt==SQLITEASYNC_HALT ? SQLITEASYNC_GET_HALT : + eOpt==SQLITEASYNC_DELAY ? SQLITEASYNC_GET_DELAY : + SQLITEASYNC_GET_LOCKFILES, &iVal); + } + + if( rc!=SQLITE_OK ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); + return TCL_ERROR; + } + + if( eOpt==SQLITEASYNC_HALT ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(az[iVal], -1)); + }else{ + Tcl_SetObjResult(interp, Tcl_NewIntObj(iVal)); + } + + return TCL_OK; +} + +#endif /* SQLITE_ENABLE_ASYNCIO */ + +/* +** This routine registers the custom TCL commands defined in this +** module. This should be the only procedure visible from outside +** of this module. +*/ +int Sqlitetestasync_Init(Tcl_Interp *interp){ +#ifdef SQLITE_ENABLE_ASYNCIO + Tcl_CreateObjCommand(interp,"sqlite3async_start",testAsyncStart,0,0); + Tcl_CreateObjCommand(interp,"sqlite3async_wait",testAsyncWait,0,0); + + Tcl_CreateObjCommand(interp,"sqlite3async_control",testAsyncControl,0,0); + Tcl_CreateObjCommand(interp,"sqlite3async_initialize",testAsyncInit,0,0); + Tcl_CreateObjCommand(interp,"sqlite3async_shutdown",testAsyncShutdown,0,0); +#endif /* SQLITE_ENABLE_ASYNCIO */ + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_autoext.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_autoext.c new file mode 100644 index 0000000000000000000000000000000000000000..a5236d23908d45e00c0cc13dd78d3397692ec167 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_autoext.c @@ -0,0 +1,221 @@ +/* +** 2006 August 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Test extension for testing the sqlite3_auto_extension() function. +*/ +#include "tcl.h" +#include "sqlite3ext.h" + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +SQLITE_EXTENSION_INIT1 + +/* +** The sqr() SQL function returns the square of its input value. +*/ +static void sqrFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + double r = sqlite3_value_double(argv[0]); + sqlite3_result_double(context, r*r); +} + +/* +** This is the entry point to register the extension for the sqr() function. +*/ +static int sqr_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi); + sqlite3_create_function(db, "sqr", 1, SQLITE_ANY, 0, sqrFunc, 0, 0); + return 0; +} + +/* +** The cube() SQL function returns the cube of its input value. +*/ +static void cubeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + double r = sqlite3_value_double(argv[0]); + sqlite3_result_double(context, r*r*r); +} + +/* +** This is the entry point to register the extension for the cube() function. +*/ +static int cube_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi); + sqlite3_create_function(db, "cube", 1, SQLITE_ANY, 0, cubeFunc, 0, 0); + return 0; +} + +/* +** This is a broken extension entry point +*/ +static int broken_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + char *zErr; + SQLITE_EXTENSION_INIT2(pApi); + zErr = sqlite3_mprintf("broken autoext!"); + *pzErrMsg = zErr; + return 1; +} + +/* +** tclcmd: sqlite3_auto_extension_sqr +** +** Register the "sqr" extension to be loaded automatically. +*/ +static int autoExtSqrObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_auto_extension((void*)sqr_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_cancel_auto_extension_sqr +** +** Unregister the "sqr" extension. +*/ +static int cancelAutoExtSqrObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_cancel_auto_extension((void*)sqr_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_auto_extension_cube +** +** Register the "cube" extension to be loaded automatically. +*/ +static int autoExtCubeObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_auto_extension((void*)cube_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_cancel_auto_extension_cube +** +** Unregister the "cube" extension. +*/ +static int cancelAutoExtCubeObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_cancel_auto_extension((void*)cube_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_auto_extension_broken +** +** Register the broken extension to be loaded automatically. +*/ +static int autoExtBrokenObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_auto_extension((void*)broken_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_cancel_auto_extension_broken +** +** Unregister the broken extension. +*/ +static int cancelAutoExtBrokenObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_cancel_auto_extension((void*)broken_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + + +/* +** tclcmd: sqlite3_reset_auto_extension +** +** Reset all auto-extensions +*/ +static int resetAutoExtObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_reset_auto_extension(); + return SQLITE_OK; +} + + +/* +** This procedure registers the TCL procs defined in this file. +*/ +int Sqlitetest_autoext_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_LOAD_EXTENSION + Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_sqr", + autoExtSqrObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_cube", + autoExtCubeObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_broken", + autoExtBrokenObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_cancel_auto_extension_sqr", + cancelAutoExtSqrObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_cancel_auto_extension_cube", + cancelAutoExtCubeObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_cancel_auto_extension_broken", + cancelAutoExtBrokenObjCmd, 0, 0); +#endif + Tcl_CreateObjCommand(interp, "sqlite3_reset_auto_extension", + resetAutoExtObjCmd, 0, 0); + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_backup.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_backup.c new file mode 100644 index 0000000000000000000000000000000000000000..e967424a290f738aecfdac578e9b87a4c4ae8d7f --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_backup.c @@ -0,0 +1,150 @@ +/* +** 2009 January 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains test logic for the sqlite3_backup() interface. +** +*/ + +#include "tcl.h" +#include +#include + +/* These functions are implemented in main.c. */ +extern const char *sqlite3ErrName(int); + +/* These functions are implemented in test1.c. */ +extern int getDbPointer(Tcl_Interp *, const char *, sqlite3 **); + +static int backupTestCmd( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const*objv +){ + enum BackupSubCommandEnum { + BACKUP_STEP, BACKUP_FINISH, BACKUP_REMAINING, BACKUP_PAGECOUNT + }; + struct BackupSubCommand { + const char *zCmd; + enum BackupSubCommandEnum eCmd; + int nArg; + const char *zArg; + } aSub[] = { + {"step", BACKUP_STEP , 1, "npage" }, + {"finish", BACKUP_FINISH , 0, "" }, + {"remaining", BACKUP_REMAINING , 0, "" }, + {"pagecount", BACKUP_PAGECOUNT , 0, "" }, + {0, 0, 0, 0} + }; + + sqlite3_backup *p = (sqlite3_backup *)clientData; + int iCmd; + int rc; + + rc = Tcl_GetIndexFromObjStruct( + interp, objv[1], aSub, sizeof(aSub[0]), "option", 0, &iCmd + ); + if( rc!=TCL_OK ){ + return rc; + } + if( objc!=(2 + aSub[iCmd].nArg) ){ + Tcl_WrongNumArgs(interp, 2, objv, aSub[iCmd].zArg); + return TCL_ERROR; + } + + switch( aSub[iCmd].eCmd ){ + + case BACKUP_FINISH: { + const char *zCmdName; + Tcl_CmdInfo cmdInfo; + zCmdName = Tcl_GetString(objv[0]); + Tcl_GetCommandInfo(interp, zCmdName, &cmdInfo); + cmdInfo.deleteProc = 0; + Tcl_SetCommandInfo(interp, zCmdName, &cmdInfo); + Tcl_DeleteCommand(interp, zCmdName); + + rc = sqlite3_backup_finish(p); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + break; + } + + case BACKUP_STEP: { + int nPage; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &nPage) ){ + return TCL_ERROR; + } + rc = sqlite3_backup_step(p, nPage); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + break; + } + + case BACKUP_REMAINING: + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_backup_remaining(p))); + break; + + case BACKUP_PAGECOUNT: + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_backup_pagecount(p))); + break; + } + + return TCL_OK; +} + +static void backupTestFinish(ClientData clientData){ + sqlite3_backup *pBackup = (sqlite3_backup *)clientData; + sqlite3_backup_finish(pBackup); +} + +/* +** sqlite3_backup CMDNAME DESTHANDLE DESTNAME SRCHANDLE SRCNAME +** +*/ +static int backupTestInit( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const*objv +){ + sqlite3_backup *pBackup; + sqlite3 *pDestDb; + sqlite3 *pSrcDb; + const char *zDestName; + const char *zSrcName; + const char *zCmd; + + if( objc!=6 ){ + Tcl_WrongNumArgs( + interp, 1, objv, "CMDNAME DESTHANDLE DESTNAME SRCHANDLE SRCNAME" + ); + return TCL_ERROR; + } + + zCmd = Tcl_GetString(objv[1]); + getDbPointer(interp, Tcl_GetString(objv[2]), &pDestDb); + zDestName = Tcl_GetString(objv[3]); + getDbPointer(interp, Tcl_GetString(objv[4]), &pSrcDb); + zSrcName = Tcl_GetString(objv[5]); + + pBackup = sqlite3_backup_init(pDestDb, zDestName, pSrcDb, zSrcName); + if( !pBackup ){ + Tcl_AppendResult(interp, "sqlite3_backup_init() failed", 0); + return TCL_ERROR; + } + + Tcl_CreateObjCommand(interp, zCmd, backupTestCmd, pBackup, backupTestFinish); + Tcl_SetObjResult(interp, objv[1]); + return TCL_OK; +} + +int Sqlitetestbackup_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "sqlite3_backup", backupTestInit, 0, 0); + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_btree.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_btree.c new file mode 100644 index 0000000000000000000000000000000000000000..db72889b2afb6272828dda866dccf122a49a7299 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_btree.c @@ -0,0 +1,62 @@ +/* +** 2007 May 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing the btree.c module in SQLite. This code +** is not included in the SQLite library. It is used for automated +** testing of the SQLite library. +*/ +#include "btreeInt.h" +#include + +/* +** Usage: sqlite3_shared_cache_report +** +** Return a list of file that are shared and the number of +** references to each file. +*/ +int sqlite3BtreeSharedCacheReport( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_SHARED_CACHE + extern BtShared *sqlite3SharedCacheList; + BtShared *pBt; + Tcl_Obj *pRet = Tcl_NewObj(); + for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ + const char *zFile = sqlite3PagerFilename(pBt->pPager, 1); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(zFile, -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(pBt->nRef)); + } + Tcl_SetObjResult(interp, pRet); +#endif + return TCL_OK; +} + +/* +** Print debugging information about all cursors to standard output. +*/ +void sqlite3BtreeCursorList(Btree *p){ +#ifdef SQLITE_DEBUG + BtCursor *pCur; + BtShared *pBt = p->pBt; + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ + MemPage *pPage = pCur->apPage[pCur->iPage]; + char *zMode = pCur->wrFlag ? "rw" : "ro"; + sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n", + pCur, pCur->pgnoRoot, zMode, + pPage ? pPage->pgno : 0, pCur->aiIdx[pCur->iPage], + (pCur->eState==CURSOR_VALID) ? "" : " eof" + ); + } +#endif +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_config.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_config.c new file mode 100644 index 0000000000000000000000000000000000000000..de1822e3b13143d97cc03acfdcaf115e3628b9d9 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_config.c @@ -0,0 +1,656 @@ +/* +** 2007 May 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used for testing the SQLite system. +** None of the code in this file goes into a deliverable build. +** +** The focus of this file is providing the TCL testing layer +** access to compile-time constants. +*/ + +#include "sqliteLimit.h" + +#include "sqliteInt.h" +#include "tcl.h" +#include +#include + +/* +** Macro to stringify the results of the evaluation a pre-processor +** macro. i.e. so that STRINGVALUE(SQLITE_NOMEM) -> "7". +*/ +#define STRINGVALUE2(x) #x +#define STRINGVALUE(x) STRINGVALUE2(x) + +/* +** This routine sets entries in the global ::sqlite_options() array variable +** according to the compile-time configuration of the database. Test +** procedures use this to determine when tests should be omitted. +*/ +static void set_options(Tcl_Interp *interp){ +#ifdef HAVE_MALLOC_USABLE_SIZE + Tcl_SetVar2(interp, "sqlite_options", "malloc_usable_size", "1", + TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "malloc_usable_size", "0", + TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_32BIT_ROWID + Tcl_SetVar2(interp, "sqlite_options", "rowid32", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "rowid32", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_CASE_SENSITIVE_LIKE + Tcl_SetVar2(interp, "sqlite_options","casesensitivelike","1",TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options","casesensitivelike","0",TCL_GLOBAL_ONLY); +#endif + +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT + Tcl_SetVar2(interp, "sqlite_options", "curdir", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "curdir", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DEBUG + Tcl_SetVar2(interp, "sqlite_options", "debug", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "debug", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DIRECT_OVERFLOW_READ + Tcl_SetVar2(interp, "sqlite_options", "direct_read", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "direct_read", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DISABLE_DIRSYNC + Tcl_SetVar2(interp, "sqlite_options", "dirsync", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "dirsync", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DISABLE_LFS + Tcl_SetVar2(interp, "sqlite_options", "lfs", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "lfs", "1", TCL_GLOBAL_ONLY); +#endif + +#if SQLITE_MAX_MMAP_SIZE>0 + Tcl_SetVar2(interp, "sqlite_options", "mmap", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mmap", "0", TCL_GLOBAL_ONLY); +#endif + +#if 1 /* def SQLITE_MEMDEBUG */ + Tcl_SetVar2(interp, "sqlite_options", "memdebug", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "memdebug", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_8_3_NAMES + Tcl_SetVar2(interp, "sqlite_options", "8_3_names", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "8_3_names", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_MEMSYS3 + Tcl_SetVar2(interp, "sqlite_options", "mem3", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mem3", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_MEMSYS5 + Tcl_SetVar2(interp, "sqlite_options", "mem5", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mem5", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_MUTEX_OMIT + Tcl_SetVar2(interp, "sqlite_options", "mutex", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mutex", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_MUTEX_NOOP + Tcl_SetVar2(interp, "sqlite_options", "mutex_noop", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mutex_noop", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_ALTERTABLE + Tcl_SetVar2(interp, "sqlite_options", "altertable", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "altertable", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_ANALYZE + Tcl_SetVar2(interp, "sqlite_options", "analyze", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "analyze", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + Tcl_SetVar2(interp, "sqlite_options", "atomicwrite", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "atomicwrite", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_ATTACH + Tcl_SetVar2(interp, "sqlite_options", "attach", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "attach", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTHORIZATION + Tcl_SetVar2(interp, "sqlite_options", "auth", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "auth", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTOINCREMENT + Tcl_SetVar2(interp, "sqlite_options", "autoinc", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "autoinc", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTOMATIC_INDEX + Tcl_SetVar2(interp, "sqlite_options", "autoindex", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "autoindex", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTORESET + Tcl_SetVar2(interp, "sqlite_options", "autoreset", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "autoreset", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTOVACUUM + Tcl_SetVar2(interp, "sqlite_options", "autovacuum", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "autovacuum", "1", TCL_GLOBAL_ONLY); +#endif /* SQLITE_OMIT_AUTOVACUUM */ +#if !defined(SQLITE_DEFAULT_AUTOVACUUM) + Tcl_SetVar2(interp,"sqlite_options","default_autovacuum","0",TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "default_autovacuum", + STRINGVALUE(SQLITE_DEFAULT_AUTOVACUUM), TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION + Tcl_SetVar2(interp, "sqlite_options", "between_opt", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "between_opt", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_BUILTIN_TEST + Tcl_SetVar2(interp, "sqlite_options", "builtin_test", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "builtin_test", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_BLOB_LITERAL + Tcl_SetVar2(interp, "sqlite_options", "bloblit", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "bloblit", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_CAST + Tcl_SetVar2(interp, "sqlite_options", "cast", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "cast", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_CHECK + Tcl_SetVar2(interp, "sqlite_options", "check", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "check", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_COLUMN_METADATA + Tcl_SetVar2(interp, "sqlite_options", "columnmetadata", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "columnmetadata", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK + Tcl_SetVar2(interp, "sqlite_options", "oversize_cell_check", "1", + TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "oversize_cell_check", "0", + TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS + Tcl_SetVar2(interp, "sqlite_options", "compileoption_diags", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "compileoption_diags", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_COMPLETE + Tcl_SetVar2(interp, "sqlite_options", "complete", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "complete", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_COMPOUND_SELECT + Tcl_SetVar2(interp, "sqlite_options", "compound", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "compound", "1", TCL_GLOBAL_ONLY); +#endif + + Tcl_SetVar2(interp, "sqlite_options", "conflict", "1", TCL_GLOBAL_ONLY); + +#if SQLITE_OS_UNIX + Tcl_SetVar2(interp, "sqlite_options", "crashtest", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "crashtest", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_DATETIME_FUNCS + Tcl_SetVar2(interp, "sqlite_options", "datetime", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "datetime", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_DECLTYPE + Tcl_SetVar2(interp, "sqlite_options", "decltype", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "decltype", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_DEPRECATED + Tcl_SetVar2(interp, "sqlite_options", "deprecated", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "deprecated", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_DISKIO + Tcl_SetVar2(interp, "sqlite_options", "diskio", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "diskio", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_EXPLAIN + Tcl_SetVar2(interp, "sqlite_options", "explain", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "explain", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_FLOATING_POINT + Tcl_SetVar2(interp, "sqlite_options", "floatingpoint", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "floatingpoint", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_FOREIGN_KEY + Tcl_SetVar2(interp, "sqlite_options", "foreignkey", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "foreignkey", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_FTS1 + Tcl_SetVar2(interp, "sqlite_options", "fts1", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts1", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_FTS2 + Tcl_SetVar2(interp, "sqlite_options", "fts2", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts2", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_FTS3 + Tcl_SetVar2(interp, "sqlite_options", "fts3", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts3", "0", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_ENABLE_FTS4_UNICODE61) + Tcl_SetVar2(interp, "sqlite_options", "fts3_unicode", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts3_unicode", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DISABLE_FTS4_DEFERRED + Tcl_SetVar2(interp, "sqlite_options", "fts4_deferred", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts4_deferred", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_GET_TABLE + Tcl_SetVar2(interp, "sqlite_options", "gettable", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "gettable", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_ICU + Tcl_SetVar2(interp, "sqlite_options", "icu", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "icu", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_INCRBLOB + Tcl_SetVar2(interp, "sqlite_options", "incrblob", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "incrblob", "1", TCL_GLOBAL_ONLY); +#endif /* SQLITE_OMIT_AUTOVACUUM */ + +#ifdef SQLITE_OMIT_INTEGRITY_CHECK + Tcl_SetVar2(interp, "sqlite_options", "integrityck", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "integrityck", "1", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_DEFAULT_FILE_FORMAT) && SQLITE_DEFAULT_FILE_FORMAT==1 + Tcl_SetVar2(interp, "sqlite_options", "legacyformat", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "legacyformat", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION + Tcl_SetVar2(interp, "sqlite_options", "like_opt", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "like_opt", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_LOAD_EXTENSION + Tcl_SetVar2(interp, "sqlite_options", "load_ext", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "load_ext", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_LOCALTIME + Tcl_SetVar2(interp, "sqlite_options", "localtime", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "localtime", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_LOOKASIDE + Tcl_SetVar2(interp, "sqlite_options", "lookaside", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "lookaside", "1", TCL_GLOBAL_ONLY); +#endif + +Tcl_SetVar2(interp, "sqlite_options", "long_double", + sizeof(LONGDOUBLE_TYPE)>sizeof(double) ? "1" : "0", + TCL_GLOBAL_ONLY); + +#ifdef SQLITE_OMIT_MEMORYDB + Tcl_SetVar2(interp, "sqlite_options", "memorydb", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "memorydb", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT + Tcl_SetVar2(interp, "sqlite_options", "memorymanage", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "memorymanage", "0", TCL_GLOBAL_ONLY); +#endif + +Tcl_SetVar2(interp, "sqlite_options", "mergesort", "1", TCL_GLOBAL_ONLY); + +#ifdef SQLITE_OMIT_OR_OPTIMIZATION + Tcl_SetVar2(interp, "sqlite_options", "or_opt", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "or_opt", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_PAGER_PRAGMAS + Tcl_SetVar2(interp, "sqlite_options", "pager_pragmas", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "pager_pragmas", "1", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_OMIT_PRAGMA) || defined(SQLITE_OMIT_FLAG_PRAGMAS) + Tcl_SetVar2(interp, "sqlite_options", "pragma", "0", TCL_GLOBAL_ONLY); + Tcl_SetVar2(interp, "sqlite_options", "integrityck", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "pragma", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_PROGRESS_CALLBACK + Tcl_SetVar2(interp, "sqlite_options", "progress", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "progress", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_REINDEX + Tcl_SetVar2(interp, "sqlite_options", "reindex", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "reindex", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_RTREE + Tcl_SetVar2(interp, "sqlite_options", "rtree", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "rtree", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_RTREE_INT_ONLY + Tcl_SetVar2(interp, "sqlite_options", "rtree_int_only", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "rtree_int_only", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS + Tcl_SetVar2(interp, "sqlite_options", "schema_pragmas", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "schema_pragmas", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS + Tcl_SetVar2(interp, "sqlite_options", "schema_version", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "schema_version", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_STAT4 + Tcl_SetVar2(interp, "sqlite_options", "stat4", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "stat4", "0", TCL_GLOBAL_ONLY); +#endif +#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4) + Tcl_SetVar2(interp, "sqlite_options", "stat3", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "stat3", "0", TCL_GLOBAL_ONLY); +#endif + +#if !defined(SQLITE_ENABLE_LOCKING_STYLE) +# if defined(__APPLE__) +# define SQLITE_ENABLE_LOCKING_STYLE 1 +# else +# define SQLITE_ENABLE_LOCKING_STYLE 0 +# endif +#endif +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) + Tcl_SetVar2(interp,"sqlite_options","lock_proxy_pragmas","1",TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp,"sqlite_options","lock_proxy_pragmas","0",TCL_GLOBAL_ONLY); +#endif +#if defined(SQLITE_PREFER_PROXY_LOCKING) && defined(__APPLE__) + Tcl_SetVar2(interp,"sqlite_options","prefer_proxy_locking","1",TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp,"sqlite_options","prefer_proxy_locking","0",TCL_GLOBAL_ONLY); +#endif + + +#ifdef SQLITE_OMIT_SHARED_CACHE + Tcl_SetVar2(interp, "sqlite_options", "shared_cache", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "shared_cache", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_SUBQUERY + Tcl_SetVar2(interp, "sqlite_options", "subquery", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "subquery", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_TCL_VARIABLE + Tcl_SetVar2(interp, "sqlite_options", "tclvar", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "tclvar", "1", TCL_GLOBAL_ONLY); +#endif + + Tcl_SetVar2(interp, "sqlite_options", "threadsafe", + STRINGVALUE(SQLITE_THREADSAFE), TCL_GLOBAL_ONLY); + assert( sqlite3_threadsafe()==SQLITE_THREADSAFE ); + +#ifdef SQLITE_OMIT_TEMPDB + Tcl_SetVar2(interp, "sqlite_options", "tempdb", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "tempdb", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_TRACE + Tcl_SetVar2(interp, "sqlite_options", "trace", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "trace", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_TRIGGER + Tcl_SetVar2(interp, "sqlite_options", "trigger", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "trigger", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION + Tcl_SetVar2(interp, "sqlite_options", "truncate_opt", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "truncate_opt", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_UTF16 + Tcl_SetVar2(interp, "sqlite_options", "utf16", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "utf16", "1", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_OMIT_VACUUM) || defined(SQLITE_OMIT_ATTACH) + Tcl_SetVar2(interp, "sqlite_options", "vacuum", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "vacuum", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_VIEW + Tcl_SetVar2(interp, "sqlite_options", "view", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "view", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_VIRTUALTABLE + Tcl_SetVar2(interp, "sqlite_options", "vtab", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "vtab", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_WAL + Tcl_SetVar2(interp, "sqlite_options", "wal", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "wal", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_WSD + Tcl_SetVar2(interp, "sqlite_options", "wsd", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "wsd", "1", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) + Tcl_SetVar2(interp, "sqlite_options", "update_delete_limit", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "update_delete_limit", "0", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_ENABLE_UNLOCK_NOTIFY) + Tcl_SetVar2(interp, "sqlite_options", "unlock_notify", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "unlock_notify", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_SECURE_DELETE + Tcl_SetVar2(interp, "sqlite_options", "secure_delete", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "secure_delete", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_MULTIPLEX_EXT_OVWR + Tcl_SetVar2(interp, "sqlite_options", "multiplex_ext_overwrite", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "multiplex_ext_overwrite", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef YYTRACKMAXSTACKDEPTH + Tcl_SetVar2(interp, "sqlite_options", "yytrackmaxstackdepth", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "yytrackmaxstackdepth", "0", TCL_GLOBAL_ONLY); +#endif + +#define LINKVAR(x) { \ + static const int cv_ ## x = SQLITE_ ## x; \ + Tcl_LinkVar(interp, "SQLITE_" #x, (char *)&(cv_ ## x), \ + TCL_LINK_INT | TCL_LINK_READ_ONLY); } + + LINKVAR( MAX_LENGTH ); + LINKVAR( MAX_COLUMN ); + LINKVAR( MAX_SQL_LENGTH ); + LINKVAR( MAX_EXPR_DEPTH ); + LINKVAR( MAX_COMPOUND_SELECT ); + LINKVAR( MAX_VDBE_OP ); + LINKVAR( MAX_FUNCTION_ARG ); + LINKVAR( MAX_VARIABLE_NUMBER ); + LINKVAR( MAX_PAGE_SIZE ); + LINKVAR( MAX_PAGE_COUNT ); + LINKVAR( MAX_LIKE_PATTERN_LENGTH ); + LINKVAR( MAX_TRIGGER_DEPTH ); + LINKVAR( DEFAULT_TEMP_CACHE_SIZE ); + LINKVAR( DEFAULT_CACHE_SIZE ); + LINKVAR( DEFAULT_PAGE_SIZE ); + LINKVAR( DEFAULT_FILE_FORMAT ); + LINKVAR( MAX_ATTACHED ); + LINKVAR( MAX_DEFAULT_PAGE_SIZE ); + + { + static const int cv_TEMP_STORE = SQLITE_TEMP_STORE; + Tcl_LinkVar(interp, "TEMP_STORE", (char *)&(cv_TEMP_STORE), + TCL_LINK_INT | TCL_LINK_READ_ONLY); + } + +#ifdef _MSC_VER + { + static const int cv__MSC_VER = 1; + Tcl_LinkVar(interp, "_MSC_VER", (char *)&(cv__MSC_VER), + TCL_LINK_INT | TCL_LINK_READ_ONLY); + } +#endif +#ifdef __GNUC__ + { + static const int cv___GNUC__ = 1; + Tcl_LinkVar(interp, "__GNUC__", (char *)&(cv___GNUC__), + TCL_LINK_INT | TCL_LINK_READ_ONLY); + } +#endif +} + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqliteconfig_Init(Tcl_Interp *interp){ + set_options(interp); + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_demovfs.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_demovfs.c new file mode 100644 index 0000000000000000000000000000000000000000..c63b0a8b7a19bc398e1edb5d523757f2a0973e88 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_demovfs.c @@ -0,0 +1,679 @@ +/* +** 2010 April 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements an example of a simple VFS implementation that +** omits complex features often not required or not possible on embedded +** platforms. Code is included to buffer writes to the journal file, +** which can be a significant performance improvement on some embedded +** platforms. +** +** OVERVIEW +** +** The code in this file implements a minimal SQLite VFS that can be +** used on Linux and other posix-like operating systems. The following +** system calls are used: +** +** File-system: access(), unlink(), getcwd() +** File IO: open(), read(), write(), fsync(), close(), fstat() +** Other: sleep(), usleep(), time() +** +** The following VFS features are omitted: +** +** 1. File locking. The user must ensure that there is at most one +** connection to each database when using this VFS. Multiple +** connections to a single shared-cache count as a single connection +** for the purposes of the previous statement. +** +** 2. The loading of dynamic extensions (shared libraries). +** +** 3. Temporary files. The user must configure SQLite to use in-memory +** temp files when using this VFS. The easiest way to do this is to +** compile with: +** +** -DSQLITE_TEMP_STORE=3 +** +** 4. File truncation. As of version 3.6.24, SQLite may run without +** a working xTruncate() call, providing the user does not configure +** SQLite to use "journal_mode=truncate", or use both +** "journal_mode=persist" and ATTACHed databases. +** +** It is assumed that the system uses UNIX-like path-names. Specifically, +** that '/' characters are used to separate path components and that +** a path-name is a relative path unless it begins with a '/'. And that +** no UTF-8 encoded paths are greater than 512 bytes in length. +** +** JOURNAL WRITE-BUFFERING +** +** To commit a transaction to the database, SQLite first writes rollback +** information into the journal file. This usually consists of 4 steps: +** +** 1. The rollback information is sequentially written into the journal +** file, starting at the start of the file. +** 2. The journal file is synced to disk. +** 3. A modification is made to the first few bytes of the journal file. +** 4. The journal file is synced to disk again. +** +** Most of the data is written in step 1 using a series of calls to the +** VFS xWrite() method. The buffers passed to the xWrite() calls are of +** various sizes. For example, as of version 3.6.24, when committing a +** transaction that modifies 3 pages of a database file that uses 4096 +** byte pages residing on a media with 512 byte sectors, SQLite makes +** eleven calls to the xWrite() method to create the rollback journal, +** as follows: +** +** Write offset | Bytes written +** ---------------------------- +** 0 512 +** 512 4 +** 516 4096 +** 4612 4 +** 4616 4 +** 4620 4096 +** 8716 4 +** 8720 4 +** 8724 4096 +** 12820 4 +** ++++++++++++SYNC+++++++++++ +** 0 12 +** ++++++++++++SYNC+++++++++++ +** +** On many operating systems, this is an efficient way to write to a file. +** However, on some embedded systems that do not cache writes in OS +** buffers it is much more efficient to write data in blocks that are +** an integer multiple of the sector-size in size and aligned at the +** start of a sector. +** +** To work around this, the code in this file allocates a fixed size +** buffer of SQLITE_DEMOVFS_BUFFERSZ using sqlite3_malloc() whenever a +** journal file is opened. It uses the buffer to coalesce sequential +** writes into aligned SQLITE_DEMOVFS_BUFFERSZ blocks. When SQLite +** invokes the xSync() method to sync the contents of the file to disk, +** all accumulated data is written out, even if it does not constitute +** a complete block. This means the actual IO to create the rollback +** journal for the example transaction above is this: +** +** Write offset | Bytes written +** ---------------------------- +** 0 8192 +** 8192 4632 +** ++++++++++++SYNC+++++++++++ +** 0 12 +** ++++++++++++SYNC+++++++++++ +** +** Much more efficient if the underlying OS is not caching write +** operations. +*/ + +#if !defined(SQLITE_TEST) || SQLITE_OS_UNIX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* +** Size of the write buffer used by journal files in bytes. +*/ +#ifndef SQLITE_DEMOVFS_BUFFERSZ +# define SQLITE_DEMOVFS_BUFFERSZ 8192 +#endif + +/* +** The maximum pathname length supported by this VFS. +*/ +#define MAXPATHNAME 512 + +/* +** When using this VFS, the sqlite3_file* handles that SQLite uses are +** actually pointers to instances of type DemoFile. +*/ +typedef struct DemoFile DemoFile; +struct DemoFile { + sqlite3_file base; /* Base class. Must be first. */ + int fd; /* File descriptor */ + + char *aBuffer; /* Pointer to malloc'd buffer */ + int nBuffer; /* Valid bytes of data in zBuffer */ + sqlite3_int64 iBufferOfst; /* Offset in file of zBuffer[0] */ +}; + +/* +** Write directly to the file passed as the first argument. Even if the +** file has a write-buffer (DemoFile.aBuffer), ignore it. +*/ +static int demoDirectWrite( + DemoFile *p, /* File handle */ + const void *zBuf, /* Buffer containing data to write */ + int iAmt, /* Size of data to write in bytes */ + sqlite_int64 iOfst /* File offset to write to */ +){ + off_t ofst; /* Return value from lseek() */ + size_t nWrite; /* Return value from write() */ + + ofst = lseek(p->fd, iOfst, SEEK_SET); + if( ofst!=iOfst ){ + return SQLITE_IOERR_WRITE; + } + + nWrite = write(p->fd, zBuf, iAmt); + if( nWrite!=iAmt ){ + return SQLITE_IOERR_WRITE; + } + + return SQLITE_OK; +} + +/* +** Flush the contents of the DemoFile.aBuffer buffer to disk. This is a +** no-op if this particular file does not have a buffer (i.e. it is not +** a journal file) or if the buffer is currently empty. +*/ +static int demoFlushBuffer(DemoFile *p){ + int rc = SQLITE_OK; + if( p->nBuffer ){ + rc = demoDirectWrite(p, p->aBuffer, p->nBuffer, p->iBufferOfst); + p->nBuffer = 0; + } + return rc; +} + +/* +** Close a file. +*/ +static int demoClose(sqlite3_file *pFile){ + int rc; + DemoFile *p = (DemoFile*)pFile; + rc = demoFlushBuffer(p); + sqlite3_free(p->aBuffer); + close(p->fd); + return rc; +} + +/* +** Read data from a file. +*/ +static int demoRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + DemoFile *p = (DemoFile*)pFile; + off_t ofst; /* Return value from lseek() */ + int nRead; /* Return value from read() */ + int rc; /* Return code from demoFlushBuffer() */ + + /* Flush any data in the write buffer to disk in case this operation + ** is trying to read data the file-region currently cached in the buffer. + ** It would be possible to detect this case and possibly save an + ** unnecessary write here, but in practice SQLite will rarely read from + ** a journal file when there is data cached in the write-buffer. + */ + rc = demoFlushBuffer(p); + if( rc!=SQLITE_OK ){ + return rc; + } + + ofst = lseek(p->fd, iOfst, SEEK_SET); + if( ofst!=iOfst ){ + return SQLITE_IOERR_READ; + } + nRead = read(p->fd, zBuf, iAmt); + + if( nRead==iAmt ){ + return SQLITE_OK; + }else if( nRead>=0 ){ + return SQLITE_IOERR_SHORT_READ; + } + + return SQLITE_IOERR_READ; +} + +/* +** Write data to a crash-file. +*/ +static int demoWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + DemoFile *p = (DemoFile*)pFile; + + if( p->aBuffer ){ + char *z = (char *)zBuf; /* Pointer to remaining data to write */ + int n = iAmt; /* Number of bytes at z */ + sqlite3_int64 i = iOfst; /* File offset to write to */ + + while( n>0 ){ + int nCopy; /* Number of bytes to copy into buffer */ + + /* If the buffer is full, or if this data is not being written directly + ** following the data already buffered, flush the buffer. Flushing + ** the buffer is a no-op if it is empty. + */ + if( p->nBuffer==SQLITE_DEMOVFS_BUFFERSZ || p->iBufferOfst+p->nBuffer!=i ){ + int rc = demoFlushBuffer(p); + if( rc!=SQLITE_OK ){ + return rc; + } + } + assert( p->nBuffer==0 || p->iBufferOfst+p->nBuffer==i ); + p->iBufferOfst = i - p->nBuffer; + + /* Copy as much data as possible into the buffer. */ + nCopy = SQLITE_DEMOVFS_BUFFERSZ - p->nBuffer; + if( nCopy>n ){ + nCopy = n; + } + memcpy(&p->aBuffer[p->nBuffer], z, nCopy); + p->nBuffer += nCopy; + + n -= nCopy; + i += nCopy; + z += nCopy; + } + }else{ + return demoDirectWrite(p, zBuf, iAmt, iOfst); + } + + return SQLITE_OK; +} + +/* +** Truncate a file. This is a no-op for this VFS (see header comments at +** the top of the file). +*/ +static int demoTruncate(sqlite3_file *pFile, sqlite_int64 size){ +#if 0 + if( ftruncate(((DemoFile *)pFile)->fd, size) ) return SQLITE_IOERR_TRUNCATE; +#endif + return SQLITE_OK; +} + +/* +** Sync the contents of the file to the persistent media. +*/ +static int demoSync(sqlite3_file *pFile, int flags){ + DemoFile *p = (DemoFile*)pFile; + int rc; + + rc = demoFlushBuffer(p); + if( rc!=SQLITE_OK ){ + return rc; + } + + rc = fsync(p->fd); + return (rc==0 ? SQLITE_OK : SQLITE_IOERR_FSYNC); +} + +/* +** Write the size of the file in bytes to *pSize. +*/ +static int demoFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + DemoFile *p = (DemoFile*)pFile; + int rc; /* Return code from fstat() call */ + struct stat sStat; /* Output of fstat() call */ + + /* Flush the contents of the buffer to disk. As with the flush in the + ** demoRead() method, it would be possible to avoid this and save a write + ** here and there. But in practice this comes up so infrequently it is + ** not worth the trouble. + */ + rc = demoFlushBuffer(p); + if( rc!=SQLITE_OK ){ + return rc; + } + + rc = fstat(p->fd, &sStat); + if( rc!=0 ) return SQLITE_IOERR_FSTAT; + *pSize = sStat.st_size; + return SQLITE_OK; +} + +/* +** Locking functions. The xLock() and xUnlock() methods are both no-ops. +** The xCheckReservedLock() always indicates that no other process holds +** a reserved lock on the database file. This ensures that if a hot-journal +** file is found in the file-system it is rolled back. +*/ +static int demoLock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} +static int demoUnlock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} +static int demoCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + *pResOut = 0; + return SQLITE_OK; +} + +/* +** No xFileControl() verbs are implemented by this VFS. +*/ +static int demoFileControl(sqlite3_file *pFile, int op, void *pArg){ + return SQLITE_OK; +} + +/* +** The xSectorSize() and xDeviceCharacteristics() methods. These two +** may return special values allowing SQLite to optimize file-system +** access to some extent. But it is also safe to simply return 0. +*/ +static int demoSectorSize(sqlite3_file *pFile){ + return 0; +} +static int demoDeviceCharacteristics(sqlite3_file *pFile){ + return 0; +} + +/* +** Open a file handle. +*/ +static int demoOpen( + sqlite3_vfs *pVfs, /* VFS */ + const char *zName, /* File to open, or 0 for a temp file */ + sqlite3_file *pFile, /* Pointer to DemoFile struct to populate */ + int flags, /* Input SQLITE_OPEN_XXX flags */ + int *pOutFlags /* Output SQLITE_OPEN_XXX flags (or NULL) */ +){ + static const sqlite3_io_methods demoio = { + 1, /* iVersion */ + demoClose, /* xClose */ + demoRead, /* xRead */ + demoWrite, /* xWrite */ + demoTruncate, /* xTruncate */ + demoSync, /* xSync */ + demoFileSize, /* xFileSize */ + demoLock, /* xLock */ + demoUnlock, /* xUnlock */ + demoCheckReservedLock, /* xCheckReservedLock */ + demoFileControl, /* xFileControl */ + demoSectorSize, /* xSectorSize */ + demoDeviceCharacteristics /* xDeviceCharacteristics */ + }; + + DemoFile *p = (DemoFile*)pFile; /* Populate this structure */ + int oflags = 0; /* flags to pass to open() call */ + char *aBuf = 0; + + if( zName==0 ){ + return SQLITE_IOERR; + } + + if( flags&SQLITE_OPEN_MAIN_JOURNAL ){ + aBuf = (char *)sqlite3_malloc(SQLITE_DEMOVFS_BUFFERSZ); + if( !aBuf ){ + return SQLITE_NOMEM; + } + } + + if( flags&SQLITE_OPEN_EXCLUSIVE ) oflags |= O_EXCL; + if( flags&SQLITE_OPEN_CREATE ) oflags |= O_CREAT; + if( flags&SQLITE_OPEN_READONLY ) oflags |= O_RDONLY; + if( flags&SQLITE_OPEN_READWRITE ) oflags |= O_RDWR; + + memset(p, 0, sizeof(DemoFile)); + p->fd = open(zName, oflags, 0600); + if( p->fd<0 ){ + sqlite3_free(aBuf); + return SQLITE_CANTOPEN; + } + p->aBuffer = aBuf; + + if( pOutFlags ){ + *pOutFlags = flags; + } + p->base.pMethods = &demoio; + return SQLITE_OK; +} + +/* +** Delete the file identified by argument zPath. If the dirSync parameter +** is non-zero, then ensure the file-system modification to delete the +** file has been synced to disk before returning. +*/ +static int demoDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc; /* Return code */ + + rc = unlink(zPath); + if( rc!=0 && errno==ENOENT ) return SQLITE_OK; + + if( rc==0 && dirSync ){ + int dfd; /* File descriptor open on directory */ + int i; /* Iterator variable */ + char zDir[MAXPATHNAME+1]; /* Name of directory containing file zPath */ + + /* Figure out the directory name from the path of the file deleted. */ + sqlite3_snprintf(MAXPATHNAME, zDir, "%s", zPath); + zDir[MAXPATHNAME] = '\0'; + for(i=strlen(zDir); i>1 && zDir[i]!='/'; i++); + zDir[i] = '\0'; + + /* Open a file-descriptor on the directory. Sync. Close. */ + dfd = open(zDir, O_RDONLY, 0); + if( dfd<0 ){ + rc = -1; + }else{ + rc = fsync(dfd); + close(dfd); + } + } + return (rc==0 ? SQLITE_OK : SQLITE_IOERR_DELETE); +} + +#ifndef F_OK +# define F_OK 0 +#endif +#ifndef R_OK +# define R_OK 4 +#endif +#ifndef W_OK +# define W_OK 2 +#endif + +/* +** Query the file-system to see if the named file exists, is readable or +** is both readable and writable. +*/ +static int demoAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + int rc; /* access() return code */ + int eAccess = F_OK; /* Second argument to access() */ + + assert( flags==SQLITE_ACCESS_EXISTS /* access(zPath, F_OK) */ + || flags==SQLITE_ACCESS_READ /* access(zPath, R_OK) */ + || flags==SQLITE_ACCESS_READWRITE /* access(zPath, R_OK|W_OK) */ + ); + + if( flags==SQLITE_ACCESS_READWRITE ) eAccess = R_OK|W_OK; + if( flags==SQLITE_ACCESS_READ ) eAccess = R_OK; + + rc = access(zPath, eAccess); + *pResOut = (rc==0); + return SQLITE_OK; +} + +/* +** Argument zPath points to a nul-terminated string containing a file path. +** If zPath is an absolute path, then it is copied as is into the output +** buffer. Otherwise, if it is a relative path, then the equivalent full +** path is written to the output buffer. +** +** This function assumes that paths are UNIX style. Specifically, that: +** +** 1. Path components are separated by a '/'. and +** 2. Full paths begin with a '/' character. +*/ +static int demoFullPathname( + sqlite3_vfs *pVfs, /* VFS */ + const char *zPath, /* Input path (possibly a relative path) */ + int nPathOut, /* Size of output buffer in bytes */ + char *zPathOut /* Pointer to output buffer */ +){ + char zDir[MAXPATHNAME+1]; + if( zPath[0]=='/' ){ + zDir[0] = '\0'; + }else{ + if( getcwd(zDir, sizeof(zDir))==0 ) return SQLITE_IOERR; + } + zDir[MAXPATHNAME] = '\0'; + + sqlite3_snprintf(nPathOut, zPathOut, "%s/%s", zDir, zPath); + zPathOut[nPathOut-1] = '\0'; + + return SQLITE_OK; +} + +/* +** The following four VFS methods: +** +** xDlOpen +** xDlError +** xDlSym +** xDlClose +** +** are supposed to implement the functionality needed by SQLite to load +** extensions compiled as shared objects. This simple VFS does not support +** this functionality, so the following functions are no-ops. +*/ +static void *demoDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return 0; +} +static void demoDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + sqlite3_snprintf(nByte, zErrMsg, "Loadable extensions are not supported"); + zErrMsg[nByte-1] = '\0'; +} +static void (*demoDlSym(sqlite3_vfs *pVfs, void *pH, const char *z))(void){ + return 0; +} +static void demoDlClose(sqlite3_vfs *pVfs, void *pHandle){ + return; +} + +/* +** Parameter zByte points to a buffer nByte bytes in size. Populate this +** buffer with pseudo-random data. +*/ +static int demoRandomness(sqlite3_vfs *pVfs, int nByte, char *zByte){ + return SQLITE_OK; +} + +/* +** Sleep for at least nMicro microseconds. Return the (approximate) number +** of microseconds slept for. +*/ +static int demoSleep(sqlite3_vfs *pVfs, int nMicro){ + sleep(nMicro / 1000000); + usleep(nMicro % 1000000); + return nMicro; +} + +/* +** Set *pTime to the current UTC time expressed as a Julian day. Return +** SQLITE_OK if successful, or an error code otherwise. +** +** http://en.wikipedia.org/wiki/Julian_day +** +** This implementation is not very good. The current time is rounded to +** an integer number of seconds. Also, assuming time_t is a signed 32-bit +** value, it will stop working some time in the year 2038 AD (the so-called +** "year 2038" problem that afflicts systems that store time this way). +*/ +static int demoCurrentTime(sqlite3_vfs *pVfs, double *pTime){ + time_t t = time(0); + *pTime = t/86400.0 + 2440587.5; + return SQLITE_OK; +} + +/* +** This function returns a pointer to the VFS implemented in this file. +** To make the VFS available to SQLite: +** +** sqlite3_vfs_register(sqlite3_demovfs(), 0); +*/ +sqlite3_vfs *sqlite3_demovfs(void){ + static sqlite3_vfs demovfs = { + 1, /* iVersion */ + sizeof(DemoFile), /* szOsFile */ + MAXPATHNAME, /* mxPathname */ + 0, /* pNext */ + "demo", /* zName */ + 0, /* pAppData */ + demoOpen, /* xOpen */ + demoDelete, /* xDelete */ + demoAccess, /* xAccess */ + demoFullPathname, /* xFullPathname */ + demoDlOpen, /* xDlOpen */ + demoDlError, /* xDlError */ + demoDlSym, /* xDlSym */ + demoDlClose, /* xDlClose */ + demoRandomness, /* xRandomness */ + demoSleep, /* xSleep */ + demoCurrentTime, /* xCurrentTime */ + }; + return &demovfs; +} + +#endif /* !defined(SQLITE_TEST) || SQLITE_OS_UNIX */ + + +#ifdef SQLITE_TEST + +#include + +#if SQLITE_OS_UNIX +static int register_demovfs( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_vfs_register(sqlite3_demovfs(), 1); + return TCL_OK; +} +static int unregister_demovfs( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_vfs_unregister(sqlite3_demovfs()); + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest_demovfs_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "register_demovfs", register_demovfs, 0, 0); + Tcl_CreateObjCommand(interp, "unregister_demovfs", unregister_demovfs, 0, 0); + return TCL_OK; +} + +#else +int Sqlitetest_demovfs_Init(Tcl_Interp *interp){ return TCL_OK; } +#endif + +#endif /* SQLITE_TEST */ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_devsym.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_devsym.c new file mode 100644 index 0000000000000000000000000000000000000000..21f0f684d861116770defcdecd532ba3eeaba975 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_devsym.c @@ -0,0 +1,398 @@ +/* +** 2008 Jan 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code that modified the OS layer in order to simulate +** different device types (by overriding the return values of the +** xDeviceCharacteristics() and xSectorSize() methods). +*/ +#if SQLITE_TEST /* This file is used for testing only */ + +#include "sqlite3.h" +#include "sqliteInt.h" + +/* +** Maximum pathname length supported by the devsym backend. +*/ +#define DEVSYM_MAX_PATHNAME 512 + +/* +** Name used to identify this VFS. +*/ +#define DEVSYM_VFS_NAME "devsym" + +typedef struct devsym_file devsym_file; +struct devsym_file { + sqlite3_file base; + sqlite3_file *pReal; +}; + +/* +** Method declarations for devsym_file. +*/ +static int devsymClose(sqlite3_file*); +static int devsymRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int devsymWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); +static int devsymTruncate(sqlite3_file*, sqlite3_int64 size); +static int devsymSync(sqlite3_file*, int flags); +static int devsymFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int devsymLock(sqlite3_file*, int); +static int devsymUnlock(sqlite3_file*, int); +static int devsymCheckReservedLock(sqlite3_file*, int *); +static int devsymFileControl(sqlite3_file*, int op, void *pArg); +static int devsymSectorSize(sqlite3_file*); +static int devsymDeviceCharacteristics(sqlite3_file*); +static int devsymShmLock(sqlite3_file*,int,int,int); +static int devsymShmMap(sqlite3_file*,int,int,int, void volatile **); +static void devsymShmBarrier(sqlite3_file*); +static int devsymShmUnmap(sqlite3_file*,int); + +/* +** Method declarations for devsym_vfs. +*/ +static int devsymOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int devsymDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int devsymAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int devsymFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +static void *devsymDlOpen(sqlite3_vfs*, const char *zFilename); +static void devsymDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*devsymDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void); +static void devsymDlClose(sqlite3_vfs*, void*); +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +static int devsymRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int devsymSleep(sqlite3_vfs*, int microseconds); +static int devsymCurrentTime(sqlite3_vfs*, double*); + +static sqlite3_vfs devsym_vfs = { + 2, /* iVersion */ + sizeof(devsym_file), /* szOsFile */ + DEVSYM_MAX_PATHNAME, /* mxPathname */ + 0, /* pNext */ + DEVSYM_VFS_NAME, /* zName */ + 0, /* pAppData */ + devsymOpen, /* xOpen */ + devsymDelete, /* xDelete */ + devsymAccess, /* xAccess */ + devsymFullPathname, /* xFullPathname */ +#ifndef SQLITE_OMIT_LOAD_EXTENSION + devsymDlOpen, /* xDlOpen */ + devsymDlError, /* xDlError */ + devsymDlSym, /* xDlSym */ + devsymDlClose, /* xDlClose */ +#else + 0, /* xDlOpen */ + 0, /* xDlError */ + 0, /* xDlSym */ + 0, /* xDlClose */ +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + devsymRandomness, /* xRandomness */ + devsymSleep, /* xSleep */ + devsymCurrentTime, /* xCurrentTime */ + 0, /* xGetLastError */ + 0 /* xCurrentTimeInt64 */ +}; + +static sqlite3_io_methods devsym_io_methods = { + 2, /* iVersion */ + devsymClose, /* xClose */ + devsymRead, /* xRead */ + devsymWrite, /* xWrite */ + devsymTruncate, /* xTruncate */ + devsymSync, /* xSync */ + devsymFileSize, /* xFileSize */ + devsymLock, /* xLock */ + devsymUnlock, /* xUnlock */ + devsymCheckReservedLock, /* xCheckReservedLock */ + devsymFileControl, /* xFileControl */ + devsymSectorSize, /* xSectorSize */ + devsymDeviceCharacteristics, /* xDeviceCharacteristics */ + devsymShmMap, /* xShmMap */ + devsymShmLock, /* xShmLock */ + devsymShmBarrier, /* xShmBarrier */ + devsymShmUnmap /* xShmUnmap */ +}; + +struct DevsymGlobal { + sqlite3_vfs *pVfs; + int iDeviceChar; + int iSectorSize; +}; +struct DevsymGlobal g = {0, 0, 512}; + +/* +** Close an devsym-file. +*/ +static int devsymClose(sqlite3_file *pFile){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsClose(p->pReal); +} + +/* +** Read data from an devsym-file. +*/ +static int devsymRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst); +} + +/* +** Write data to an devsym-file. +*/ +static int devsymWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst); +} + +/* +** Truncate an devsym-file. +*/ +static int devsymTruncate(sqlite3_file *pFile, sqlite_int64 size){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsTruncate(p->pReal, size); +} + +/* +** Sync an devsym-file. +*/ +static int devsymSync(sqlite3_file *pFile, int flags){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsSync(p->pReal, flags); +} + +/* +** Return the current file-size of an devsym-file. +*/ +static int devsymFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsFileSize(p->pReal, pSize); +} + +/* +** Lock an devsym-file. +*/ +static int devsymLock(sqlite3_file *pFile, int eLock){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsLock(p->pReal, eLock); +} + +/* +** Unlock an devsym-file. +*/ +static int devsymUnlock(sqlite3_file *pFile, int eLock){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsUnlock(p->pReal, eLock); +} + +/* +** Check if another file-handle holds a RESERVED lock on an devsym-file. +*/ +static int devsymCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsCheckReservedLock(p->pReal, pResOut); +} + +/* +** File control method. For custom operations on an devsym-file. +*/ +static int devsymFileControl(sqlite3_file *pFile, int op, void *pArg){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsFileControl(p->pReal, op, pArg); +} + +/* +** Return the sector-size in bytes for an devsym-file. +*/ +static int devsymSectorSize(sqlite3_file *pFile){ + return g.iSectorSize; +} + +/* +** Return the device characteristic flags supported by an devsym-file. +*/ +static int devsymDeviceCharacteristics(sqlite3_file *pFile){ + return g.iDeviceChar; +} + +/* +** Shared-memory methods are all pass-thrus. +*/ +static int devsymShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsShmLock(p->pReal, ofst, n, flags); +} +static int devsymShmMap( + sqlite3_file *pFile, + int iRegion, + int szRegion, + int isWrite, + void volatile **pp +){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsShmMap(p->pReal, iRegion, szRegion, isWrite, pp); +} +static void devsymShmBarrier(sqlite3_file *pFile){ + devsym_file *p = (devsym_file *)pFile; + sqlite3OsShmBarrier(p->pReal); +} +static int devsymShmUnmap(sqlite3_file *pFile, int delFlag){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsShmUnmap(p->pReal, delFlag); +} + + + +/* +** Open an devsym file handle. +*/ +static int devsymOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + devsym_file *p = (devsym_file *)pFile; + p->pReal = (sqlite3_file *)&p[1]; + rc = sqlite3OsOpen(g.pVfs, zName, p->pReal, flags, pOutFlags); + if( p->pReal->pMethods ){ + pFile->pMethods = &devsym_io_methods; + } + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int devsymDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + return sqlite3OsDelete(g.pVfs, zPath, dirSync); +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int devsymAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + return sqlite3OsAccess(g.pVfs, zPath, flags, pResOut); +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (DEVSYM_MAX_PATHNAME+1) bytes. +*/ +static int devsymFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + return sqlite3OsFullPathname(g.pVfs, zPath, nOut, zOut); +} + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *devsymDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return sqlite3OsDlOpen(g.pVfs, zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void devsymDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + sqlite3OsDlError(g.pVfs, nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*devsymDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return sqlite3OsDlSym(g.pVfs, p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void devsymDlClose(sqlite3_vfs *pVfs, void *pHandle){ + sqlite3OsDlClose(g.pVfs, pHandle); +} +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int devsymRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return sqlite3OsRandomness(g.pVfs, nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int devsymSleep(sqlite3_vfs *pVfs, int nMicro){ + return sqlite3OsSleep(g.pVfs, nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int devsymCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + return g.pVfs->xCurrentTime(g.pVfs, pTimeOut); +} + + +/* +** This procedure registers the devsym vfs with SQLite. If the argument is +** true, the devsym vfs becomes the new default vfs. It is the only publicly +** available function in this file. +*/ +void devsym_register(int iDeviceChar, int iSectorSize){ + if( g.pVfs==0 ){ + g.pVfs = sqlite3_vfs_find(0); + devsym_vfs.szOsFile += g.pVfs->szOsFile; + sqlite3_vfs_register(&devsym_vfs, 0); + } + if( iDeviceChar>=0 ){ + g.iDeviceChar = iDeviceChar; + }else{ + g.iDeviceChar = 0; + } + if( iSectorSize>=0 ){ + g.iSectorSize = iSectorSize; + }else{ + g.iSectorSize = 512; + } +} + +#endif diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_fs.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_fs.c new file mode 100644 index 0000000000000000000000000000000000000000..417c81b49f2a44c5f41c8ff6f5d684377f22b184 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_fs.c @@ -0,0 +1,335 @@ +/* +** 2013 Jan 11 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing the virtual table interfaces. This code +** is not included in the SQLite library. It is used for automated +** testing of the SQLite library. +** +** The FS virtual table is created as follows: +** +** CREATE VIRTUAL TABLE tbl USING fs(idx); +** +** where idx is the name of a table in the db with 2 columns. The virtual +** table also has two columns - file path and file contents. +** +** The first column of table idx must be an IPK, and the second contains file +** paths. For example: +** +** CREATE TABLE idx(id INTEGER PRIMARY KEY, path TEXT); +** INSERT INTO idx VALUES(4, '/etc/passwd'); +** +** Adding the row to the idx table automatically creates a row in the +** virtual table with rowid=4, path=/etc/passwd and a text field that +** contains data read from file /etc/passwd on disk. +*/ +#include "sqliteInt.h" +#include "tcl.h" + +#include +#include +#include +#include +#include + +#if SQLITE_OS_UNIX +# include +#endif +#if SQLITE_OS_WIN +# include +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +typedef struct fs_vtab fs_vtab; +typedef struct fs_cursor fs_cursor; + +/* +** A fs virtual-table object +*/ +struct fs_vtab { + sqlite3_vtab base; + sqlite3 *db; + char *zDb; /* Name of db containing zTbl */ + char *zTbl; /* Name of docid->file map table */ +}; + +/* A fs cursor object */ +struct fs_cursor { + sqlite3_vtab_cursor base; + sqlite3_stmt *pStmt; + char *zBuf; + int nBuf; + int nAlloc; +}; + +/* +** This function is the implementation of both the xConnect and xCreate +** methods of the fs virtual table. +** +** The argv[] array contains the following: +** +** argv[0] -> module name ("fs") +** argv[1] -> database name +** argv[2] -> table name +** argv[...] -> other module argument fields. +*/ +static int fsConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + fs_vtab *pVtab; + int nByte; + const char *zTbl; + const char *zDb = argv[1]; + + if( argc!=4 ){ + *pzErr = sqlite3_mprintf("wrong number of arguments"); + return SQLITE_ERROR; + } + zTbl = argv[3]; + + nByte = sizeof(fs_vtab) + (int)strlen(zTbl) + 1 + (int)strlen(zDb) + 1; + pVtab = (fs_vtab *)sqlite3MallocZero( nByte ); + if( !pVtab ) return SQLITE_NOMEM; + + pVtab->zTbl = (char *)&pVtab[1]; + pVtab->zDb = &pVtab->zTbl[strlen(zTbl)+1]; + pVtab->db = db; + memcpy(pVtab->zTbl, zTbl, strlen(zTbl)); + memcpy(pVtab->zDb, zDb, strlen(zDb)); + *ppVtab = &pVtab->base; + sqlite3_declare_vtab(db, "CREATE TABLE xyz(path TEXT, data TEXT)"); + + return SQLITE_OK; +} +/* Note that for this virtual table, the xCreate and xConnect +** methods are identical. */ + +static int fsDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} +/* The xDisconnect and xDestroy methods are also the same */ + +/* +** Open a new fs cursor. +*/ +static int fsOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + fs_cursor *pCur; + pCur = sqlite3MallocZero(sizeof(fs_cursor)); + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Close a fs cursor. +*/ +static int fsClose(sqlite3_vtab_cursor *cur){ + fs_cursor *pCur = (fs_cursor *)cur; + sqlite3_finalize(pCur->pStmt); + sqlite3_free(pCur->zBuf); + sqlite3_free(pCur); + return SQLITE_OK; +} + +static int fsNext(sqlite3_vtab_cursor *cur){ + fs_cursor *pCur = (fs_cursor *)cur; + int rc; + + rc = sqlite3_step(pCur->pStmt); + if( rc==SQLITE_ROW || rc==SQLITE_DONE ) rc = SQLITE_OK; + + return rc; +} + +static int fsFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + int rc; + fs_cursor *pCur = (fs_cursor *)pVtabCursor; + fs_vtab *p = (fs_vtab *)(pVtabCursor->pVtab); + + assert( (idxNum==0 && argc==0) || (idxNum==1 && argc==1) ); + if( idxNum==1 ){ + char *zStmt = sqlite3_mprintf( + "SELECT * FROM %Q.%Q WHERE rowid=?", p->zDb, p->zTbl); + if( !zStmt ) return SQLITE_NOMEM; + rc = sqlite3_prepare_v2(p->db, zStmt, -1, &pCur->pStmt, 0); + sqlite3_free(zStmt); + if( rc==SQLITE_OK ){ + sqlite3_bind_value(pCur->pStmt, 1, argv[0]); + } + }else{ + char *zStmt = sqlite3_mprintf("SELECT * FROM %Q.%Q", p->zDb, p->zTbl); + if( !zStmt ) return SQLITE_NOMEM; + rc = sqlite3_prepare_v2(p->db, zStmt, -1, &pCur->pStmt, 0); + sqlite3_free(zStmt); + } + + if( rc==SQLITE_OK ){ + rc = fsNext(pVtabCursor); + } + return rc; +} + +static int fsColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + fs_cursor *pCur = (fs_cursor*)cur; + + assert( i==0 || i==1 ); + if( i==0 ){ + sqlite3_result_value(ctx, sqlite3_column_value(pCur->pStmt, 0)); + }else{ + const char *zFile = (const char *)sqlite3_column_text(pCur->pStmt, 1); + struct stat sbuf; + int fd; + int n; + + fd = open(zFile, O_RDONLY); + if( fd<0 ) return SQLITE_IOERR; + fstat(fd, &sbuf); + + if( sbuf.st_size>=pCur->nAlloc ){ + int nNew = sbuf.st_size*2; + char *zNew; + if( nNew<1024 ) nNew = 1024; + + zNew = sqlite3Realloc(pCur->zBuf, nNew); + if( zNew==0 ){ + close(fd); + return SQLITE_NOMEM; + } + pCur->zBuf = zNew; + pCur->nAlloc = nNew; + } + + n = (int)read(fd, pCur->zBuf, sbuf.st_size); + close(fd); + if( n!=sbuf.st_size ) return SQLITE_ERROR; + pCur->nBuf = sbuf.st_size; + pCur->zBuf[pCur->nBuf] = '\0'; + + sqlite3_result_text(ctx, pCur->zBuf, -1, SQLITE_TRANSIENT); + } + return SQLITE_OK; +} + +static int fsRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + fs_cursor *pCur = (fs_cursor*)cur; + *pRowid = sqlite3_column_int64(pCur->pStmt, 0); + return SQLITE_OK; +} + +static int fsEof(sqlite3_vtab_cursor *cur){ + fs_cursor *pCur = (fs_cursor*)cur; + return (sqlite3_data_count(pCur->pStmt)==0); +} + +static int fsBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int ii; + + for(ii=0; iinConstraint; ii++){ + struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii]; + if( pCons->iColumn<0 && pCons->usable + && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + struct sqlite3_index_constraint_usage *pUsage; + pUsage = &pIdxInfo->aConstraintUsage[ii]; + pUsage->omit = 0; + pUsage->argvIndex = 1; + pIdxInfo->idxNum = 1; + pIdxInfo->estimatedCost = 1.0; + break; + } + } + + return SQLITE_OK; +} + +/* +** A virtual table module that provides read-only access to a +** Tcl global variable namespace. +*/ +static sqlite3_module fsModule = { + 0, /* iVersion */ + fsConnect, + fsConnect, + fsBestIndex, + fsDisconnect, + fsDisconnect, + fsOpen, /* xOpen - open a cursor */ + fsClose, /* xClose - close a cursor */ + fsFilter, /* xFilter - configure scan constraints */ + fsNext, /* xNext - advance a cursor */ + fsEof, /* xEof - check for end of scan */ + fsColumn, /* xColumn - read data */ + fsRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +/* +** Decode a pointer to an sqlite3 object. +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); + +/* +** Register the echo virtual table module. +*/ +static int register_fs_module( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_create_module(db, "fs", &fsModule, (void *)interp); +#endif + return TCL_OK; +} + +#endif + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetestfs_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "register_fs_module", register_fs_module, 0 }, + }; + int i; + for(i=0; i +#include +#include + +#include "sqliteInt.h" +#include "vdbeInt.h" + + +/* +** Allocate nByte bytes of space using sqlite3_malloc(). If the +** allocation fails, call sqlite3_result_error_nomem() to notify +** the database handle that malloc() has failed. +*/ +static void *testContextMalloc(sqlite3_context *context, int nByte){ + char *z = sqlite3_malloc(nByte); + if( !z && nByte>0 ){ + sqlite3_result_error_nomem(context); + } + return z; +} + +/* +** This function generates a string of random characters. Used for +** generating test data. +*/ +static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){ + static const unsigned char zSrc[] = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + ".-!,:*^+=_|?/<> "; + int iMin, iMax, n, r, i; + unsigned char zBuf[1000]; + + /* It used to be possible to call randstr() with any number of arguments, + ** but now it is registered with SQLite as requiring exactly 2. + */ + assert(argc==2); + + iMin = sqlite3_value_int(argv[0]); + if( iMin<0 ) iMin = 0; + if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1; + iMax = sqlite3_value_int(argv[1]); + if( iMax=sizeof(zBuf) ) iMax = sizeof(zBuf)-1; + n = iMin; + if( iMax>iMin ){ + sqlite3_randomness(sizeof(r), &r); + r &= 0x7fffffff; + n += r%(iMax + 1 - iMin); + } + assert( n='0' && c<='9' ){ + return c - '0'; + }else if( c>='a' && c<='f' ){ + return c - 'a' + 10; + }else if( c>='A' && c<='F' ){ + return c - 'A' + 10; + } + return 0; +} + +/* +** Convert hex to binary. +*/ +static void testHexToBin(const char *zIn, char *zOut){ + while( zIn[0] && zIn[1] ){ + *(zOut++) = (testHexChar(zIn[0])<<4) + testHexChar(zIn[1]); + zIn += 2; + } +} + +/* +** hex_to_utf16be(HEX) +** +** Convert the input string from HEX into binary. Then return the +** result using sqlite3_result_text16le(). +*/ +#ifndef SQLITE_OMIT_UTF16 +static void testHexToUtf16be( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + int n; + const char *zIn; + char *zOut; + assert( nArg==1 ); + n = sqlite3_value_bytes(argv[0]); + zIn = (const char*)sqlite3_value_text(argv[0]); + zOut = sqlite3_malloc( n/2 ); + if( zOut==0 ){ + sqlite3_result_error_nomem(pCtx); + }else{ + testHexToBin(zIn, zOut); + sqlite3_result_text16be(pCtx, zOut, n/2, sqlite3_free); + } +} +#endif + +/* +** hex_to_utf8(HEX) +** +** Convert the input string from HEX into binary. Then return the +** result using sqlite3_result_text16le(). +*/ +static void testHexToUtf8( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + int n; + const char *zIn; + char *zOut; + assert( nArg==1 ); + n = sqlite3_value_bytes(argv[0]); + zIn = (const char*)sqlite3_value_text(argv[0]); + zOut = sqlite3_malloc( n/2 ); + if( zOut==0 ){ + sqlite3_result_error_nomem(pCtx); + }else{ + testHexToBin(zIn, zOut); + sqlite3_result_text(pCtx, zOut, n/2, sqlite3_free); + } +} + +/* +** hex_to_utf16le(HEX) +** +** Convert the input string from HEX into binary. Then return the +** result using sqlite3_result_text16le(). +*/ +#ifndef SQLITE_OMIT_UTF16 +static void testHexToUtf16le( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + int n; + const char *zIn; + char *zOut; + assert( nArg==1 ); + n = sqlite3_value_bytes(argv[0]); + zIn = (const char*)sqlite3_value_text(argv[0]); + zOut = sqlite3_malloc( n/2 ); + if( zOut==0 ){ + sqlite3_result_error_nomem(pCtx); + }else{ + testHexToBin(zIn, zOut); + sqlite3_result_text16le(pCtx, zOut, n/2, sqlite3_free); + } +} +#endif + +/* +** SQL function: real2hex(X) +** +** If argument X is a real number, then convert it into a string which is +** the big-endian hexadecimal representation of the ieee754 encoding of +** that number. If X is not a real number, return NULL. +*/ +static void real2hex( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + union { + sqlite3_uint64 i; + double r; + unsigned char x[8]; + } v; + char zOut[20]; + int i; + int bigEndian; + v.i = 1; + bigEndian = v.x[0]==0; + v.r = sqlite3_value_double(argv[0]); + for(i=0; i<8; i++){ + if( bigEndian ){ + zOut[i*2] = "0123456789abcdef"[v.x[i]>>4]; + zOut[i*2+1] = "0123456789abcdef"[v.x[i]&0xf]; + }else{ + zOut[14-i*2] = "0123456789abcdef"[v.x[i]>>4]; + zOut[14-i*2+1] = "0123456789abcdef"[v.x[i]&0xf]; + } + } + zOut[16] = 0; + sqlite3_result_text(context, zOut, -1, SQLITE_TRANSIENT); +} + +/* +** tclcmd: test_extract(record, field) +** +** This function implements an SQL user-function that accepts a blob +** containing a formatted database record as the first argument. The +** second argument is the index of the field within that record to +** extract and return. +*/ +static void test_extract( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + u8 *pRec; + u8 *pEndHdr; /* Points to one byte past record header */ + u8 *pHdr; /* Current point in record header */ + u8 *pBody; /* Current point in record data */ + u64 nHdr; /* Bytes in record header */ + int iIdx; /* Required field */ + int iCurrent = 0; /* Current field */ + + assert( argc==2 ); + pRec = (u8*)sqlite3_value_blob(argv[0]); + iIdx = sqlite3_value_int(argv[1]); + + pHdr = pRec + sqlite3GetVarint(pRec, &nHdr); + pBody = pEndHdr = &pRec[nHdr]; + + for(iCurrent=0; pHdr> 4) & 0x0F)]; + hex[1] = hexdigit[(z[i] & 0x0F)]; + hex[2] = '\0'; + Tcl_AppendStringsToObj(pVal, hex, 0); + } + Tcl_AppendStringsToObj(pVal, "'", 0); + break; + } + + case SQLITE_FLOAT: + pVal = Tcl_NewDoubleObj(sqlite3_value_double(&mem)); + break; + + case SQLITE_INTEGER: + pVal = Tcl_NewWideIntObj(sqlite3_value_int64(&mem)); + break; + + case SQLITE_NULL: + pVal = Tcl_NewStringObj("NULL", -1); + break; + + default: + assert( 0 ); + } + + Tcl_ListObjAppendElement(0, pRet, pVal); + + if( mem.zMalloc ){ + sqlite3DbFree(db, mem.zMalloc); + } + } + + sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); + Tcl_DecrRefCount(pRet); +} + + +static int registerTestFunctions(sqlite3 *db){ + static const struct { + char *zName; + signed char nArg; + unsigned char eTextRep; /* 1: UTF-16. 0: UTF-8 */ + void (*xFunc)(sqlite3_context*,int,sqlite3_value **); + } aFuncs[] = { + { "randstr", 2, SQLITE_UTF8, randStr }, + { "test_destructor", 1, SQLITE_UTF8, test_destructor}, +#ifndef SQLITE_OMIT_UTF16 + { "test_destructor16", 1, SQLITE_UTF8, test_destructor16}, + { "hex_to_utf16be", 1, SQLITE_UTF8, testHexToUtf16be}, + { "hex_to_utf16le", 1, SQLITE_UTF8, testHexToUtf16le}, +#endif + { "hex_to_utf8", 1, SQLITE_UTF8, testHexToUtf8}, + { "test_destructor_count", 0, SQLITE_UTF8, test_destructor_count}, + { "test_auxdata", -1, SQLITE_UTF8, test_auxdata}, + { "test_error", 1, SQLITE_UTF8, test_error}, + { "test_error", 2, SQLITE_UTF8, test_error}, + { "test_eval", 1, SQLITE_UTF8, test_eval}, + { "test_isolation", 2, SQLITE_UTF8, test_isolation}, + { "test_counter", 1, SQLITE_UTF8, counterFunc}, + { "real2hex", 1, SQLITE_UTF8, real2hex}, + { "test_decode", 1, SQLITE_UTF8, test_decode}, + { "test_extract", 2, SQLITE_UTF8, test_extract}, + }; + int i; + + for(i=0; i +#include +#include + + +/* +** Convert binary to hex. The input zBuf[] contains N bytes of +** binary data. zBuf[] is 2*n+1 bytes long. Overwrite zBuf[] +** with a hexadecimal representation of its original binary input. +*/ +void sqlite3TestBinToHex(unsigned char *zBuf, int N){ + const unsigned char zHex[] = "0123456789ABCDEF"; + int i, j; + unsigned char c; + i = N*2; + zBuf[i--] = 0; + for(j=N-1; j>=0; j--){ + c = zBuf[j]; + zBuf[i--] = zHex[c&0xf]; + zBuf[i--] = zHex[c>>4]; + } + assert( i==-1 ); +} + +/* +** Convert hex to binary. The input zIn[] contains N bytes of +** hexadecimal. Convert this into binary and write aOut[] with +** the binary data. Spaces in the original input are ignored. +** Return the number of bytes of binary rendered. +*/ +int sqlite3TestHexToBin(const unsigned char *zIn, int N, unsigned char *aOut){ + const unsigned char aMap[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 0, 0, 0, 0, 0, 0, + 0,11,12,13,14,15,16, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0,11,12,13,14,15,16, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + }; + int i, j; + int hi=1; + unsigned char c; + + for(i=j=0; i=4 ){ + memcpy(aNum, aOut, 4); + }else{ + memset(aNum, 0, sizeof(aNum)); + memcpy(&aNum[4-nOut], aOut, nOut); + } + sqlite3_free(aOut); + val = (aNum[0]<<24) | (aNum[1]<<16) | (aNum[2]<<8) | aNum[3]; + Tcl_SetObjResult(interp, Tcl_NewIntObj(val)); + return TCL_OK; +} + + +/* +** USAGE: hexio_render_int16 INTEGER +** +** Render INTEGER has a 16-bit big-endian integer in hexadecimal. +*/ +static int hexio_render_int16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int val; + unsigned char aNum[10]; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "INTEGER"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &val) ) return TCL_ERROR; + aNum[0] = val>>8; + aNum[1] = val; + sqlite3TestBinToHex(aNum, 2); + Tcl_SetObjResult(interp, Tcl_NewStringObj((char*)aNum, 4)); + return TCL_OK; +} + + +/* +** USAGE: hexio_render_int32 INTEGER +** +** Render INTEGER has a 32-bit big-endian integer in hexadecimal. +*/ +static int hexio_render_int32( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int val; + unsigned char aNum[10]; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "INTEGER"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &val) ) return TCL_ERROR; + aNum[0] = val>>24; + aNum[1] = val>>16; + aNum[2] = val>>8; + aNum[3] = val; + sqlite3TestBinToHex(aNum, 4); + Tcl_SetObjResult(interp, Tcl_NewStringObj((char*)aNum, 8)); + return TCL_OK; +} + +/* +** USAGE: utf8_to_utf8 HEX +** +** The argument is a UTF8 string represented in hexadecimal. +** The UTF8 might not be well-formed. Run this string through +** sqlite3Utf8to8() convert it back to hex and return the result. +*/ +static int utf8_to_utf8( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifdef SQLITE_DEBUG + int n; + int nOut; + const unsigned char *zOrig; + unsigned char *z; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HEX"); + return TCL_ERROR; + } + zOrig = (unsigned char *)Tcl_GetStringFromObj(objv[1], &n); + z = sqlite3_malloc( n+3 ); + n = sqlite3TestHexToBin(zOrig, n, z); + z[n] = 0; + nOut = sqlite3Utf8To8(z); + sqlite3TestBinToHex(z,nOut); + Tcl_AppendResult(interp, (char*)z, 0); + sqlite3_free(z); + return TCL_OK; +#else + Tcl_AppendResult(interp, + "[utf8_to_utf8] unavailable - SQLITE_DEBUG not defined", 0 + ); + return TCL_ERROR; +#endif +} + +static int getFts3Varint(const char *p, sqlite_int64 *v){ + const unsigned char *q = (const unsigned char *) p; + sqlite_uint64 x = 0, y = 1; + while( (*q & 0x80) == 0x80 ){ + x += y * (*q++ & 0x7f); + y <<= 7; + } + x += y * (*q++); + *v = (sqlite_int64) x; + return (int) (q - (unsigned char *)p); +} + + +/* +** USAGE: read_fts3varint BLOB VARNAME +** +** Read a varint from the start of BLOB. Set variable VARNAME to contain +** the interpreted value. Return the number of bytes of BLOB consumed. +*/ +static int read_fts3varint( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int nBlob; + unsigned char *zBlob; + sqlite3_int64 iVal; + int nVal; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BLOB VARNAME"); + return TCL_ERROR; + } + zBlob = Tcl_GetByteArrayFromObj(objv[1], &nBlob); + + nVal = getFts3Varint((char*)zBlob, (sqlite3_int64 *)(&iVal)); + Tcl_ObjSetVar2(interp, objv[2], 0, Tcl_NewWideIntObj(iVal), 0); + Tcl_SetObjResult(interp, Tcl_NewIntObj(nVal)); + return TCL_OK; +} + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest_hexio_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aObjCmd[] = { + { "hexio_read", hexio_read }, + { "hexio_write", hexio_write }, + { "hexio_get_int", hexio_get_int }, + { "hexio_render_int16", hexio_render_int16 }, + { "hexio_render_int32", hexio_render_int32 }, + { "utf8_to_utf8", utf8_to_utf8 }, + { "read_fts3varint", read_fts3varint }, + }; + int i; + for(i=0; i +#include + +static struct Wrapped { + sqlite3_pcache_methods2 pcache; + sqlite3_mem_methods mem; + sqlite3_mutex_methods mutex; + + int mem_init; /* True if mem subsystem is initalized */ + int mem_fail; /* True to fail mem subsystem inialization */ + int mutex_init; /* True if mutex subsystem is initalized */ + int mutex_fail; /* True to fail mutex subsystem inialization */ + int pcache_init; /* True if pcache subsystem is initalized */ + int pcache_fail; /* True to fail pcache subsystem inialization */ +} wrapped; + +static int wrMemInit(void *pAppData){ + int rc; + if( wrapped.mem_fail ){ + rc = SQLITE_ERROR; + }else{ + rc = wrapped.mem.xInit(wrapped.mem.pAppData); + } + if( rc==SQLITE_OK ){ + wrapped.mem_init = 1; + } + return rc; +} +static void wrMemShutdown(void *pAppData){ + wrapped.mem.xShutdown(wrapped.mem.pAppData); + wrapped.mem_init = 0; +} +static void *wrMemMalloc(int n) {return wrapped.mem.xMalloc(n);} +static void wrMemFree(void *p) {wrapped.mem.xFree(p);} +static void *wrMemRealloc(void *p, int n) {return wrapped.mem.xRealloc(p, n);} +static int wrMemSize(void *p) {return wrapped.mem.xSize(p);} +static int wrMemRoundup(int n) {return wrapped.mem.xRoundup(n);} + + +static int wrMutexInit(void){ + int rc; + if( wrapped.mutex_fail ){ + rc = SQLITE_ERROR; + }else{ + rc = wrapped.mutex.xMutexInit(); + } + if( rc==SQLITE_OK ){ + wrapped.mutex_init = 1; + } + return rc; +} +static int wrMutexEnd(void){ + wrapped.mutex.xMutexEnd(); + wrapped.mutex_init = 0; + return SQLITE_OK; +} +static sqlite3_mutex *wrMutexAlloc(int e){ + return wrapped.mutex.xMutexAlloc(e); +} +static void wrMutexFree(sqlite3_mutex *p){ + wrapped.mutex.xMutexFree(p); +} +static void wrMutexEnter(sqlite3_mutex *p){ + wrapped.mutex.xMutexEnter(p); +} +static int wrMutexTry(sqlite3_mutex *p){ + return wrapped.mutex.xMutexTry(p); +} +static void wrMutexLeave(sqlite3_mutex *p){ + wrapped.mutex.xMutexLeave(p); +} +static int wrMutexHeld(sqlite3_mutex *p){ + return wrapped.mutex.xMutexHeld(p); +} +static int wrMutexNotheld(sqlite3_mutex *p){ + return wrapped.mutex.xMutexNotheld(p); +} + + + +static int wrPCacheInit(void *pArg){ + int rc; + if( wrapped.pcache_fail ){ + rc = SQLITE_ERROR; + }else{ + rc = wrapped.pcache.xInit(wrapped.pcache.pArg); + } + if( rc==SQLITE_OK ){ + wrapped.pcache_init = 1; + } + return rc; +} +static void wrPCacheShutdown(void *pArg){ + wrapped.pcache.xShutdown(wrapped.pcache.pArg); + wrapped.pcache_init = 0; +} + +static sqlite3_pcache *wrPCacheCreate(int a, int b, int c){ + return wrapped.pcache.xCreate(a, b, c); +} +static void wrPCacheCachesize(sqlite3_pcache *p, int n){ + wrapped.pcache.xCachesize(p, n); +} +static int wrPCachePagecount(sqlite3_pcache *p){ + return wrapped.pcache.xPagecount(p); +} +static sqlite3_pcache_page *wrPCacheFetch(sqlite3_pcache *p, unsigned a, int b){ + return wrapped.pcache.xFetch(p, a, b); +} +static void wrPCacheUnpin(sqlite3_pcache *p, sqlite3_pcache_page *a, int b){ + wrapped.pcache.xUnpin(p, a, b); +} +static void wrPCacheRekey( + sqlite3_pcache *p, + sqlite3_pcache_page *a, + unsigned b, + unsigned c +){ + wrapped.pcache.xRekey(p, a, b, c); +} +static void wrPCacheTruncate(sqlite3_pcache *p, unsigned a){ + wrapped.pcache.xTruncate(p, a); +} +static void wrPCacheDestroy(sqlite3_pcache *p){ + wrapped.pcache.xDestroy(p); +} + +static void installInitWrappers(void){ + sqlite3_mutex_methods mutexmethods = { + wrMutexInit, wrMutexEnd, wrMutexAlloc, + wrMutexFree, wrMutexEnter, wrMutexTry, + wrMutexLeave, wrMutexHeld, wrMutexNotheld + }; + sqlite3_pcache_methods2 pcachemethods = { + 1, 0, + wrPCacheInit, wrPCacheShutdown, wrPCacheCreate, + wrPCacheCachesize, wrPCachePagecount, wrPCacheFetch, + wrPCacheUnpin, wrPCacheRekey, wrPCacheTruncate, + wrPCacheDestroy + }; + sqlite3_mem_methods memmethods = { + wrMemMalloc, wrMemFree, wrMemRealloc, + wrMemSize, wrMemRoundup, wrMemInit, + wrMemShutdown, + 0 + }; + + memset(&wrapped, 0, sizeof(wrapped)); + + sqlite3_shutdown(); + sqlite3_config(SQLITE_CONFIG_GETMUTEX, &wrapped.mutex); + sqlite3_config(SQLITE_CONFIG_GETMALLOC, &wrapped.mem); + sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &wrapped.pcache); + sqlite3_config(SQLITE_CONFIG_MUTEX, &mutexmethods); + sqlite3_config(SQLITE_CONFIG_MALLOC, &memmethods); + sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcachemethods); +} + +static int init_wrapper_install( + ClientData clientData, /* Unused */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int i; + installInitWrappers(); + for(i=1; i +#include + + +/* +** Definition of the sqlite3_intarray object. +** +** The internal representation of an intarray object is subject +** to change, is not externally visible, and should be used by +** the implementation of intarray only. This object is opaque +** to users. +*/ +struct sqlite3_intarray { + int n; /* Number of elements in the array */ + sqlite3_int64 *a; /* Contents of the array */ + void (*xFree)(void*); /* Function used to free a[] */ +}; + +/* Objects used internally by the virtual table implementation */ +typedef struct intarray_vtab intarray_vtab; +typedef struct intarray_cursor intarray_cursor; + +/* A intarray table object */ +struct intarray_vtab { + sqlite3_vtab base; /* Base class */ + sqlite3_intarray *pContent; /* Content of the integer array */ +}; + +/* A intarray cursor object */ +struct intarray_cursor { + sqlite3_vtab_cursor base; /* Base class */ + int i; /* Current cursor position */ +}; + +/* +** None of this works unless we have virtual tables. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Free an sqlite3_intarray object. +*/ +static void intarrayFree(sqlite3_intarray *p){ + if( p->xFree ){ + p->xFree(p->a); + } + sqlite3_free(p); +} + +/* +** Table destructor for the intarray module. +*/ +static int intarrayDestroy(sqlite3_vtab *p){ + intarray_vtab *pVtab = (intarray_vtab*)p; + sqlite3_free(pVtab); + return 0; +} + +/* +** Table constructor for the intarray module. +*/ +static int intarrayCreate( + sqlite3 *db, /* Database where module is created */ + void *pAux, /* clientdata for the module */ + int argc, /* Number of arguments */ + const char *const*argv, /* Value for all arguments */ + sqlite3_vtab **ppVtab, /* Write the new virtual table object here */ + char **pzErr /* Put error message text here */ +){ + int rc = SQLITE_NOMEM; + intarray_vtab *pVtab = sqlite3_malloc(sizeof(intarray_vtab)); + + if( pVtab ){ + memset(pVtab, 0, sizeof(intarray_vtab)); + pVtab->pContent = (sqlite3_intarray*)pAux; + rc = sqlite3_declare_vtab(db, "CREATE TABLE x(value INTEGER PRIMARY KEY)"); + } + *ppVtab = (sqlite3_vtab *)pVtab; + return rc; +} + +/* +** Open a new cursor on the intarray table. +*/ +static int intarrayOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + int rc = SQLITE_NOMEM; + intarray_cursor *pCur; + pCur = sqlite3_malloc(sizeof(intarray_cursor)); + if( pCur ){ + memset(pCur, 0, sizeof(intarray_cursor)); + *ppCursor = (sqlite3_vtab_cursor *)pCur; + rc = SQLITE_OK; + } + return rc; +} + +/* +** Close a intarray table cursor. +*/ +static int intarrayClose(sqlite3_vtab_cursor *cur){ + intarray_cursor *pCur = (intarray_cursor *)cur; + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Retrieve a column of data. +*/ +static int intarrayColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + intarray_cursor *pCur = (intarray_cursor*)cur; + intarray_vtab *pVtab = (intarray_vtab*)cur->pVtab; + if( pCur->i>=0 && pCur->ipContent->n ){ + sqlite3_result_int64(ctx, pVtab->pContent->a[pCur->i]); + } + return SQLITE_OK; +} + +/* +** Retrieve the current rowid. +*/ +static int intarrayRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + intarray_cursor *pCur = (intarray_cursor *)cur; + *pRowid = pCur->i; + return SQLITE_OK; +} + +static int intarrayEof(sqlite3_vtab_cursor *cur){ + intarray_cursor *pCur = (intarray_cursor *)cur; + intarray_vtab *pVtab = (intarray_vtab *)cur->pVtab; + return pCur->i>=pVtab->pContent->n; +} + +/* +** Advance the cursor to the next row. +*/ +static int intarrayNext(sqlite3_vtab_cursor *cur){ + intarray_cursor *pCur = (intarray_cursor *)cur; + pCur->i++; + return SQLITE_OK; +} + +/* +** Reset a intarray table cursor. +*/ +static int intarrayFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + intarray_cursor *pCur = (intarray_cursor *)pVtabCursor; + pCur->i = 0; + return SQLITE_OK; +} + +/* +** Analyse the WHERE condition. +*/ +static int intarrayBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + return SQLITE_OK; +} + +/* +** A virtual table module that merely echos method calls into TCL +** variables. +*/ +static sqlite3_module intarrayModule = { + 0, /* iVersion */ + intarrayCreate, /* xCreate - create a new virtual table */ + intarrayCreate, /* xConnect - connect to an existing vtab */ + intarrayBestIndex, /* xBestIndex - find the best query index */ + intarrayDestroy, /* xDisconnect - disconnect a vtab */ + intarrayDestroy, /* xDestroy - destroy a vtab */ + intarrayOpen, /* xOpen - open a cursor */ + intarrayClose, /* xClose - close a cursor */ + intarrayFilter, /* xFilter - configure scan constraints */ + intarrayNext, /* xNext - advance a cursor */ + intarrayEof, /* xEof */ + intarrayColumn, /* xColumn - read data */ + intarrayRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ + +/* +** Invoke this routine to create a specific instance of an intarray object. +** The new intarray object is returned by the 3rd parameter. +** +** Each intarray object corresponds to a virtual table in the TEMP table +** with a name of zName. +** +** Destroy the intarray object by dropping the virtual table. If not done +** explicitly by the application, the virtual table will be dropped implicitly +** by the system when the database connection is closed. +*/ +int sqlite3_intarray_create( + sqlite3 *db, + const char *zName, + sqlite3_intarray **ppReturn +){ + int rc = SQLITE_OK; +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_intarray *p; + + *ppReturn = p = sqlite3_malloc( sizeof(*p) ); + if( p==0 ){ + return SQLITE_NOMEM; + } + memset(p, 0, sizeof(*p)); + rc = sqlite3_create_module_v2(db, zName, &intarrayModule, p, + (void(*)(void*))intarrayFree); + if( rc==SQLITE_OK ){ + char *zSql; + zSql = sqlite3_mprintf("CREATE VIRTUAL TABLE temp.%Q USING %Q", + zName, zName); + rc = sqlite3_exec(db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } +#endif + return rc; +} + +/* +** Bind a new array array of integers to a specific intarray object. +** +** The array of integers bound must be unchanged for the duration of +** any query against the corresponding virtual table. If the integer +** array does change or is deallocated undefined behavior will result. +*/ +int sqlite3_intarray_bind( + sqlite3_intarray *pIntArray, /* The intarray object to bind to */ + int nElements, /* Number of elements in the intarray */ + sqlite3_int64 *aElements, /* Content of the intarray */ + void (*xFree)(void*) /* How to dispose of the intarray when done */ +){ + if( pIntArray->xFree ){ + pIntArray->xFree(pIntArray->a); + } + pIntArray->n = nElements; + pIntArray->a = aElements; + pIntArray->xFree = xFree; + return SQLITE_OK; +} + + +/***************************************************************************** +** Everything below is interface for testing this module. +*/ +#ifdef SQLITE_TEST +#include + +/* +** Routines to encode and decode pointers +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); +extern void *sqlite3TestTextToPtr(const char*); +extern int sqlite3TestMakePointerStr(Tcl_Interp*, char *zPtr, void*); +extern const char *sqlite3ErrName(int); + +/* +** sqlite3_intarray_create DB NAME +** +** Invoke the sqlite3_intarray_create interface. A string that becomes +** the first parameter to sqlite3_intarray_bind. +*/ +static int test_intarray_create( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + const char *zName; + sqlite3_intarray *pArray; + int rc = SQLITE_OK; + char zPtr[100]; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zName = Tcl_GetString(objv[2]); +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = sqlite3_intarray_create(db, zName, &pArray); +#endif + if( rc!=SQLITE_OK ){ + assert( pArray==0 ); + Tcl_AppendResult(interp, sqlite3ErrName(rc), (char*)0); + return TCL_ERROR; + } + sqlite3TestMakePointerStr(interp, zPtr, pArray); + Tcl_AppendResult(interp, zPtr, (char*)0); + return TCL_OK; +} + +/* +** sqlite3_intarray_bind INTARRAY ?VALUE ...? +** +** Invoke the sqlite3_intarray_bind interface on the given array of integers. +*/ +static int test_intarray_bind( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_intarray *pArray; + int rc = SQLITE_OK; + int i, n; + sqlite3_int64 *a; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "INTARRAY"); + return TCL_ERROR; + } + pArray = (sqlite3_intarray*)sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + n = objc - 2; +#ifndef SQLITE_OMIT_VIRTUALTABLE + a = sqlite3_malloc( sizeof(a[0])*n ); + if( a==0 ){ + Tcl_AppendResult(interp, "SQLITE_NOMEM", (char*)0); + return TCL_ERROR; + } + for(i=0; ipWritable); + sqlite3_free(p->aCksum); + p->pWritable = 0; + p->aCksum = 0; + p->nSync = 0; +} + +/* +** Close an jt-file. +*/ +static int jtClose(sqlite3_file *pFile){ + jt_file **pp; + jt_file *p = (jt_file *)pFile; + + closeTransaction(p); + enterJtMutex(); + if( p->zName ){ + for(pp=&g.pList; *pp!=p; pp=&(*pp)->pNext); + *pp = p->pNext; + } + leaveJtMutex(); + return sqlite3OsClose(p->pReal); +} + +/* +** Read data from an jt-file. +*/ +static int jtRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst); +} + +/* +** Parameter zJournal is the name of a journal file that is currently +** open. This function locates and returns the handle opened on the +** corresponding database file by the pager that currently has the +** journal file opened. This file-handle is identified by the +** following properties: +** +** a) SQLITE_OPEN_MAIN_DB was specified when the file was opened. +** +** b) The file-name specified when the file was opened matches +** all but the final 8 characters of the journal file name. +** +** c) There is currently a reserved lock on the file. +**/ +static jt_file *locateDatabaseHandle(const char *zJournal){ + jt_file *pMain = 0; + enterJtMutex(); + for(pMain=g.pList; pMain; pMain=pMain->pNext){ + int nName = (int)(strlen(zJournal) - strlen("-journal")); + if( (pMain->flags&SQLITE_OPEN_MAIN_DB) + && ((int)strlen(pMain->zName)==nName) + && 0==memcmp(pMain->zName, zJournal, nName) + && (pMain->eLock>=SQLITE_LOCK_RESERVED) + ){ + break; + } + } + leaveJtMutex(); + return pMain; +} + +/* +** Parameter z points to a buffer of 4 bytes in size containing a +** unsigned 32-bit integer stored in big-endian format. Decode the +** integer and return its value. +*/ +static u32 decodeUint32(const unsigned char *z){ + return (z[0]<<24) + (z[1]<<16) + (z[2]<<8) + z[3]; +} + +/* +** Calculate a checksum from the buffer of length n bytes pointed to +** by parameter z. +*/ +static u32 genCksum(const unsigned char *z, int n){ + int i; + u32 cksum = 0; + for(i=0; ipReal; + int rc = SQLITE_OK; + + closeTransaction(pMain); + aData = sqlite3_malloc(pMain->nPagesize); + pMain->pWritable = sqlite3BitvecCreate(pMain->nPage); + pMain->aCksum = sqlite3_malloc(sizeof(u32) * (pMain->nPage + 1)); + pJournal->iMaxOff = 0; + + if( !pMain->pWritable || !pMain->aCksum || !aData ){ + rc = SQLITE_IOERR_NOMEM; + }else if( pMain->nPage>0 ){ + u32 iTrunk; + int iSave; + int iSave2; + + stop_ioerr_simulation(&iSave, &iSave2); + + /* Read the database free-list. Add the page-number for each free-list + ** leaf to the jt_file.pWritable bitvec. + */ + rc = sqlite3OsRead(p, aData, pMain->nPagesize, 0); + if( rc==SQLITE_OK ){ + u32 nDbsize = decodeUint32(&aData[28]); + if( nDbsize>0 && memcmp(&aData[24], &aData[92], 4)==0 ){ + u32 iPg; + for(iPg=nDbsize+1; iPg<=pMain->nPage; iPg++){ + sqlite3BitvecSet(pMain->pWritable, iPg); + } + } + } + iTrunk = decodeUint32(&aData[32]); + while( rc==SQLITE_OK && iTrunk>0 ){ + u32 nLeaf; + u32 iLeaf; + sqlite3_int64 iOff = (i64)(iTrunk-1)*pMain->nPagesize; + rc = sqlite3OsRead(p, aData, pMain->nPagesize, iOff); + nLeaf = decodeUint32(&aData[4]); + for(iLeaf=0; rc==SQLITE_OK && iLeafpWritable, pgno); + } + iTrunk = decodeUint32(aData); + } + + /* Calculate and store a checksum for each page in the database file. */ + if( rc==SQLITE_OK ){ + int ii; + for(ii=0; rc==SQLITE_OK && ii<(int)pMain->nPage; ii++){ + i64 iOff = (i64)(pMain->nPagesize) * (i64)ii; + if( iOff==PENDING_BYTE ) continue; + rc = sqlite3OsRead(pMain->pReal, aData, pMain->nPagesize, iOff); + pMain->aCksum[ii] = genCksum(aData, pMain->nPagesize); + if( ii+1==pMain->nPage && rc==SQLITE_IOERR_SHORT_READ ) rc = SQLITE_OK; + } + } + + start_ioerr_simulation(iSave, iSave2); + } + + sqlite3_free(aData); + return rc; +} + +/* +** The first argument to this function is a handle open on a journal file. +** This function reads the journal file and adds the page number for each +** page in the journal to the Bitvec object passed as the second argument. +*/ +static int readJournalFile(jt_file *p, jt_file *pMain){ + int rc = SQLITE_OK; + unsigned char zBuf[28]; + sqlite3_file *pReal = p->pReal; + sqlite3_int64 iOff = 0; + sqlite3_int64 iSize = p->iMaxOff; + unsigned char *aPage; + int iSave; + int iSave2; + + aPage = sqlite3_malloc(pMain->nPagesize); + if( !aPage ){ + return SQLITE_IOERR_NOMEM; + } + + stop_ioerr_simulation(&iSave, &iSave2); + + while( rc==SQLITE_OK && iOff=(iOff+nSector) ){ + rc = sqlite3OsRead(pReal, zBuf, 28, iOff); + if( rc!=SQLITE_OK || 0==decodeJournalHdr(zBuf, 0, 0, 0, 0) ){ + continue; + } + } + nRec = (u32)((iSize-iOff) / (pMain->nPagesize+8)); + } + + /* Read all the records that follow the journal-header just read. */ + for(ii=0; rc==SQLITE_OK && ii0 && pgno<=pMain->nPage ){ + if( 0==sqlite3BitvecTest(pMain->pWritable, pgno) ){ + rc = sqlite3OsRead(pReal, aPage, pMain->nPagesize, iOff+4); + if( rc==SQLITE_OK ){ + u32 cksum = genCksum(aPage, pMain->nPagesize); + assert( cksum==pMain->aCksum[pgno-1] ); + } + } + sqlite3BitvecSet(pMain->pWritable, pgno); + } + iOff += (8 + pMain->nPagesize); + } + } + + iOff = ((iOff + (nSector-1)) / nSector) * nSector; + } + +finish_rjf: + start_ioerr_simulation(iSave, iSave2); + sqlite3_free(aPage); + if( rc==SQLITE_IOERR_SHORT_READ ){ + rc = SQLITE_OK; + } + return rc; +} + +/* +** Write data to an jt-file. +*/ +static int jtWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc; + jt_file *p = (jt_file *)pFile; + if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){ + if( iOfst==0 ){ + jt_file *pMain = locateDatabaseHandle(p->zName); + assert( pMain ); + + if( iAmt==28 ){ + /* Zeroing the first journal-file header. This is the end of a + ** transaction. */ + closeTransaction(pMain); + }else if( iAmt!=12 ){ + /* Writing the first journal header to a journal file. This happens + ** when a transaction is first started. */ + u8 *z = (u8 *)zBuf; + pMain->nPage = decodeUint32(&z[16]); + pMain->nPagesize = decodeUint32(&z[24]); + if( SQLITE_OK!=(rc=openTransaction(pMain, p)) ){ + return rc; + } + } + } + if( p->iMaxOff<(iOfst + iAmt) ){ + p->iMaxOff = iOfst + iAmt; + } + } + + if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){ + if( iAmt<(int)p->nPagesize + && p->nPagesize%iAmt==0 + && iOfst>=(PENDING_BYTE+512) + && iOfst+iAmt<=PENDING_BYTE+p->nPagesize + ){ + /* No-op. This special case is hit when the backup code is copying a + ** to a database with a larger page-size than the source database and + ** it needs to fill in the non-locking-region part of the original + ** pending-byte page. + */ + }else{ + u32 pgno = (u32)(iOfst/p->nPagesize + 1); + assert( (iAmt==1||iAmt==p->nPagesize) && ((iOfst+iAmt)%p->nPagesize)==0 ); + assert( pgno<=p->nPage || p->nSync>0 ); + assert( pgno>p->nPage || sqlite3BitvecTest(p->pWritable, pgno) ); + } + } + + rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst); + if( (p->flags&SQLITE_OPEN_MAIN_JOURNAL) && iAmt==12 ){ + jt_file *pMain = locateDatabaseHandle(p->zName); + int rc2 = readJournalFile(p, pMain); + if( rc==SQLITE_OK ) rc = rc2; + } + return rc; +} + +/* +** Truncate an jt-file. +*/ +static int jtTruncate(sqlite3_file *pFile, sqlite_int64 size){ + jt_file *p = (jt_file *)pFile; + if( p->flags&SQLITE_OPEN_MAIN_JOURNAL && size==0 ){ + /* Truncating a journal file. This is the end of a transaction. */ + jt_file *pMain = locateDatabaseHandle(p->zName); + closeTransaction(pMain); + } + if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){ + u32 pgno; + u32 locking_page = (u32)(PENDING_BYTE/p->nPagesize+1); + for(pgno=(u32)(size/p->nPagesize+1); pgno<=p->nPage; pgno++){ + assert( pgno==locking_page || sqlite3BitvecTest(p->pWritable, pgno) ); + } + } + return sqlite3OsTruncate(p->pReal, size); +} + +/* +** Sync an jt-file. +*/ +static int jtSync(sqlite3_file *pFile, int flags){ + jt_file *p = (jt_file *)pFile; + + if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){ + int rc; + jt_file *pMain; /* The associated database file */ + + /* The journal file is being synced. At this point, we inspect the + ** contents of the file up to this point and set each bit in the + ** jt_file.pWritable bitvec of the main database file associated with + ** this journal file. + */ + pMain = locateDatabaseHandle(p->zName); + assert(pMain); + + /* Set the bitvec values */ + if( pMain->pWritable ){ + pMain->nSync++; + rc = readJournalFile(p, pMain); + if( rc!=SQLITE_OK ){ + return rc; + } + } + } + + return sqlite3OsSync(p->pReal, flags); +} + +/* +** Return the current file-size of an jt-file. +*/ +static int jtFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsFileSize(p->pReal, pSize); +} + +/* +** Lock an jt-file. +*/ +static int jtLock(sqlite3_file *pFile, int eLock){ + int rc; + jt_file *p = (jt_file *)pFile; + rc = sqlite3OsLock(p->pReal, eLock); + if( rc==SQLITE_OK && eLock>p->eLock ){ + p->eLock = eLock; + } + return rc; +} + +/* +** Unlock an jt-file. +*/ +static int jtUnlock(sqlite3_file *pFile, int eLock){ + int rc; + jt_file *p = (jt_file *)pFile; + rc = sqlite3OsUnlock(p->pReal, eLock); + if( rc==SQLITE_OK && eLockeLock ){ + p->eLock = eLock; + } + return rc; +} + +/* +** Check if another file-handle holds a RESERVED lock on an jt-file. +*/ +static int jtCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsCheckReservedLock(p->pReal, pResOut); +} + +/* +** File control method. For custom operations on an jt-file. +*/ +static int jtFileControl(sqlite3_file *pFile, int op, void *pArg){ + jt_file *p = (jt_file *)pFile; + return p->pReal->pMethods->xFileControl(p->pReal, op, pArg); +} + +/* +** Return the sector-size in bytes for an jt-file. +*/ +static int jtSectorSize(sqlite3_file *pFile){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsSectorSize(p->pReal); +} + +/* +** Return the device characteristic flags supported by an jt-file. +*/ +static int jtDeviceCharacteristics(sqlite3_file *pFile){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsDeviceCharacteristics(p->pReal); +} + +/* +** Open an jt file handle. +*/ +static int jtOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + jt_file *p = (jt_file *)pFile; + pFile->pMethods = 0; + p->pReal = (sqlite3_file *)&p[1]; + p->pReal->pMethods = 0; + rc = sqlite3OsOpen(g.pVfs, zName, p->pReal, flags, pOutFlags); + assert( rc==SQLITE_OK || p->pReal->pMethods==0 ); + if( rc==SQLITE_OK ){ + pFile->pMethods = &jt_io_methods; + p->eLock = 0; + p->zName = zName; + p->flags = flags; + p->pNext = 0; + p->pWritable = 0; + p->aCksum = 0; + enterJtMutex(); + if( zName ){ + p->pNext = g.pList; + g.pList = p; + } + leaveJtMutex(); + } + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int jtDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int nPath = (int)strlen(zPath); + if( nPath>8 && 0==strcmp("-journal", &zPath[nPath-8]) ){ + /* Deleting a journal file. The end of a transaction. */ + jt_file *pMain = locateDatabaseHandle(zPath); + if( pMain ){ + closeTransaction(pMain); + } + } + + return sqlite3OsDelete(g.pVfs, zPath, dirSync); +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int jtAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + return sqlite3OsAccess(g.pVfs, zPath, flags, pResOut); +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (JT_MAX_PATHNAME+1) bytes. +*/ +static int jtFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + return sqlite3OsFullPathname(g.pVfs, zPath, nOut, zOut); +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *jtDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return g.pVfs->xDlOpen(g.pVfs, zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void jtDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + g.pVfs->xDlError(g.pVfs, nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*jtDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return g.pVfs->xDlSym(g.pVfs, p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void jtDlClose(sqlite3_vfs *pVfs, void *pHandle){ + g.pVfs->xDlClose(g.pVfs, pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int jtRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return sqlite3OsRandomness(g.pVfs, nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int jtSleep(sqlite3_vfs *pVfs, int nMicro){ + return sqlite3OsSleep(g.pVfs, nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int jtCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + return g.pVfs->xCurrentTime(g.pVfs, pTimeOut); +} +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int jtCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ + return g.pVfs->xCurrentTimeInt64(g.pVfs, pTimeOut); +} + +/************************************************************************** +** Start of public API. +*/ + +/* +** Configure the jt VFS as a wrapper around the VFS named by parameter +** zWrap. If the isDefault parameter is true, then the jt VFS is installed +** as the new default VFS for SQLite connections. If isDefault is not +** true, then the jt VFS is installed as non-default. In this case it +** is available via its name, "jt". +*/ +int jt_register(char *zWrap, int isDefault){ + g.pVfs = sqlite3_vfs_find(zWrap); + if( g.pVfs==0 ){ + return SQLITE_ERROR; + } + jt_vfs.szOsFile = sizeof(jt_file) + g.pVfs->szOsFile; + if( g.pVfs->iVersion==1 ){ + jt_vfs.iVersion = 1; + }else if( g.pVfs->xCurrentTimeInt64==0 ){ + jt_vfs.xCurrentTimeInt64 = 0; + } + sqlite3_vfs_register(&jt_vfs, isDefault); + return SQLITE_OK; +} + +/* +** Uninstall the jt VFS, if it is installed. +*/ +void jt_unregister(void){ + sqlite3_vfs_unregister(&jt_vfs); +} + +#endif diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_loadext.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_loadext.c new file mode 100644 index 0000000000000000000000000000000000000000..1137e3a9aae92906b8289f6c3daa61f0d070f55a --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_loadext.c @@ -0,0 +1,122 @@ +/* +** 2006 June 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Test extension for testing the sqlite3_load_extension() function. +*/ +#include +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 + +/* +** The half() SQL function returns half of its input value. +*/ +static void halfFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3_result_double(context, 0.5*sqlite3_value_double(argv[0])); +} + +/* +** SQL functions to call the sqlite3_status function and return results. +*/ +static void statusFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int op, mx, cur, resetFlag, rc; + if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){ + op = sqlite3_value_int(argv[0]); + }else if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){ + int i; + const char *zName; + static const struct { + const char *zName; + int op; + } aOp[] = { + { "MEMORY_USED", SQLITE_STATUS_MEMORY_USED }, + { "PAGECACHE_USED", SQLITE_STATUS_PAGECACHE_USED }, + { "PAGECACHE_OVERFLOW", SQLITE_STATUS_PAGECACHE_OVERFLOW }, + { "SCRATCH_USED", SQLITE_STATUS_SCRATCH_USED }, + { "SCRATCH_OVERFLOW", SQLITE_STATUS_SCRATCH_OVERFLOW }, + { "MALLOC_SIZE", SQLITE_STATUS_MALLOC_SIZE }, + }; + int nOp = sizeof(aOp)/sizeof(aOp[0]); + zName = (const char*)sqlite3_value_text(argv[0]); + for(i=0; i=nOp ){ + char *zMsg = sqlite3_mprintf("unknown status property: %s", zName); + sqlite3_result_error(context, zMsg, -1); + sqlite3_free(zMsg); + return; + } + }else{ + sqlite3_result_error(context, "unknown status type", -1); + return; + } + if( argc==2 ){ + resetFlag = sqlite3_value_int(argv[1]); + }else{ + resetFlag = 0; + } + rc = sqlite3_status(op, &cur, &mx, resetFlag); + if( rc!=SQLITE_OK ){ + char *zMsg = sqlite3_mprintf("sqlite3_status(%d,...) returns %d", op, rc); + sqlite3_result_error(context, zMsg, -1); + sqlite3_free(zMsg); + return; + } + if( argc==2 ){ + sqlite3_result_int(context, mx); + }else{ + sqlite3_result_int(context, cur); + } +} + +/* +** Extension load function. +*/ +int testloadext_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int nErr = 0; + SQLITE_EXTENSION_INIT2(pApi); + nErr |= sqlite3_create_function(db, "half", 1, SQLITE_ANY, 0, halfFunc, 0, 0); + nErr |= sqlite3_create_function(db, "sqlite3_status", 1, SQLITE_ANY, 0, + statusFunc, 0, 0); + nErr |= sqlite3_create_function(db, "sqlite3_status", 2, SQLITE_ANY, 0, + statusFunc, 0, 0); + return nErr ? SQLITE_ERROR : SQLITE_OK; +} + +/* +** Another extension entry point. This one always fails. +*/ +int testbrokenext_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + char *zErr; + SQLITE_EXTENSION_INIT2(pApi); + zErr = sqlite3_mprintf("broken!"); + *pzErrMsg = zErr; + return 1; +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_malloc.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_malloc.c new file mode 100644 index 0000000000000000000000000000000000000000..f513e24bf4cddb353fbb16461f5a4af7848d14c7 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_malloc.c @@ -0,0 +1,1494 @@ +/* +** 2007 August 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used to implement test interfaces to the +** memory allocation subsystem. +*/ +#include "sqliteInt.h" +#include "tcl.h" +#include +#include +#include + +/* +** This structure is used to encapsulate the global state variables used +** by malloc() fault simulation. +*/ +static struct MemFault { + int iCountdown; /* Number of pending successes before a failure */ + int nRepeat; /* Number of times to repeat the failure */ + int nBenign; /* Number of benign failures seen since last config */ + int nFail; /* Number of failures seen since last config */ + u8 enable; /* True if enabled */ + int isInstalled; /* True if the fault simulation layer is installed */ + int isBenignMode; /* True if malloc failures are considered benign */ + sqlite3_mem_methods m; /* 'Real' malloc implementation */ +} memfault; + +/* +** This routine exists as a place to set a breakpoint that will +** fire on any simulated malloc() failure. +*/ +static void sqlite3Fault(void){ + static int cnt = 0; + cnt++; +} + +/* +** Check to see if a fault should be simulated. Return true to simulate +** the fault. Return false if the fault should not be simulated. +*/ +static int faultsimStep(void){ + if( likely(!memfault.enable) ){ + return 0; + } + if( memfault.iCountdown>0 ){ + memfault.iCountdown--; + return 0; + } + sqlite3Fault(); + memfault.nFail++; + if( memfault.isBenignMode>0 ){ + memfault.nBenign++; + } + memfault.nRepeat--; + if( memfault.nRepeat<=0 ){ + memfault.enable = 0; + } + return 1; +} + +/* +** A version of sqlite3_mem_methods.xMalloc() that includes fault simulation +** logic. +*/ +static void *faultsimMalloc(int n){ + void *p = 0; + if( !faultsimStep() ){ + p = memfault.m.xMalloc(n); + } + return p; +} + + +/* +** A version of sqlite3_mem_methods.xRealloc() that includes fault simulation +** logic. +*/ +static void *faultsimRealloc(void *pOld, int n){ + void *p = 0; + if( !faultsimStep() ){ + p = memfault.m.xRealloc(pOld, n); + } + return p; +} + +/* +** The following method calls are passed directly through to the underlying +** malloc system: +** +** xFree +** xSize +** xRoundup +** xInit +** xShutdown +*/ +static void faultsimFree(void *p){ + memfault.m.xFree(p); +} +static int faultsimSize(void *p){ + return memfault.m.xSize(p); +} +static int faultsimRoundup(int n){ + return memfault.m.xRoundup(n); +} +static int faultsimInit(void *p){ + return memfault.m.xInit(memfault.m.pAppData); +} +static void faultsimShutdown(void *p){ + memfault.m.xShutdown(memfault.m.pAppData); +} + +/* +** This routine configures the malloc failure simulation. After +** calling this routine, the next nDelay mallocs will succeed, followed +** by a block of nRepeat failures, after which malloc() calls will begin +** to succeed again. +*/ +static void faultsimConfig(int nDelay, int nRepeat){ + memfault.iCountdown = nDelay; + memfault.nRepeat = nRepeat; + memfault.nBenign = 0; + memfault.nFail = 0; + memfault.enable = nDelay>=0; + + /* Sometimes, when running multi-threaded tests, the isBenignMode + ** variable is not properly incremented/decremented so that it is + ** 0 when not inside a benign malloc block. This doesn't affect + ** the multi-threaded tests, as they do not use this system. But + ** it does affect OOM tests run later in the same process. So + ** zero the variable here, just to be sure. + */ + memfault.isBenignMode = 0; +} + +/* +** Return the number of faults (both hard and benign faults) that have +** occurred since the injector was last configured. +*/ +static int faultsimFailures(void){ + return memfault.nFail; +} + +/* +** Return the number of benign faults that have occurred since the +** injector was last configured. +*/ +static int faultsimBenignFailures(void){ + return memfault.nBenign; +} + +/* +** Return the number of successes that will occur before the next failure. +** If no failures are scheduled, return -1. +*/ +static int faultsimPending(void){ + if( memfault.enable ){ + return memfault.iCountdown; + }else{ + return -1; + } +} + + +static void faultsimBeginBenign(void){ + memfault.isBenignMode++; +} +static void faultsimEndBenign(void){ + memfault.isBenignMode--; +} + +/* +** Add or remove the fault-simulation layer using sqlite3_config(). If +** the argument is non-zero, the +*/ +static int faultsimInstall(int install){ + static struct sqlite3_mem_methods m = { + faultsimMalloc, /* xMalloc */ + faultsimFree, /* xFree */ + faultsimRealloc, /* xRealloc */ + faultsimSize, /* xSize */ + faultsimRoundup, /* xRoundup */ + faultsimInit, /* xInit */ + faultsimShutdown, /* xShutdown */ + 0 /* pAppData */ + }; + int rc; + + install = (install ? 1 : 0); + assert(memfault.isInstalled==1 || memfault.isInstalled==0); + + if( install==memfault.isInstalled ){ + return SQLITE_ERROR; + } + + if( install ){ + rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memfault.m); + assert(memfault.m.xMalloc); + if( rc==SQLITE_OK ){ + rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &m); + } + sqlite3_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, + faultsimBeginBenign, faultsimEndBenign + ); + }else{ + sqlite3_mem_methods m; + assert(memfault.m.xMalloc); + + /* One should be able to reset the default memory allocator by storing + ** a zeroed allocator then calling GETMALLOC. */ + memset(&m, 0, sizeof(m)); + sqlite3_config(SQLITE_CONFIG_MALLOC, &m); + sqlite3_config(SQLITE_CONFIG_GETMALLOC, &m); + assert( memcmp(&m, &memfault.m, sizeof(m))==0 ); + + rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memfault.m); + sqlite3_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 0, 0); + } + + if( rc==SQLITE_OK ){ + memfault.isInstalled = 1; + } + return rc; +} + +#ifdef SQLITE_TEST + +/* +** This function is implemented in main.c. Returns a pointer to a static +** buffer containing the symbolic SQLite error code that corresponds to +** the least-significant 8-bits of the integer passed as an argument. +** For example: +** +** sqlite3ErrName(1) -> "SQLITE_ERROR" +*/ +extern const char *sqlite3ErrName(int); + +/* +** Transform pointers to text and back again +*/ +static void pointerToText(void *p, char *z){ + static const char zHex[] = "0123456789abcdef"; + int i, k; + unsigned int u; + sqlite3_uint64 n; + if( p==0 ){ + strcpy(z, "0"); + return; + } + if( sizeof(n)==sizeof(p) ){ + memcpy(&n, &p, sizeof(p)); + }else if( sizeof(u)==sizeof(p) ){ + memcpy(&u, &p, sizeof(u)); + n = u; + }else{ + assert( 0 ); + } + for(i=0, k=sizeof(p)*2-1; i>= 4; + } + z[sizeof(p)*2] = 0; +} +static int hexToInt(int h){ + if( h>='0' && h<='9' ){ + return h - '0'; + }else if( h>='a' && h<='f' ){ + return h - 'a' + 10; + }else{ + return -1; + } +} +static int textToPointer(const char *z, void **pp){ + sqlite3_uint64 n = 0; + int i; + unsigned int u; + for(i=0; isizeof(zBin)*2 ) n = sizeof(zBin)*2; + n = sqlite3TestHexToBin(zHex, n, zBin); + if( n==0 ){ + Tcl_AppendResult(interp, "no data", (char*)0); + return TCL_ERROR; + } + zOut = p; + for(i=0; i0 ){ + if( size>(sizeof(zHex)-1)/2 ){ + n = (sizeof(zHex)-1)/2; + }else{ + n = size; + } + memcpy(zHex, zBin, n); + zBin += n; + size -= n; + sqlite3TestBinToHex(zHex, n); + Tcl_AppendResult(interp, zHex, (char*)0); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_memory_used +** +** Raw test interface for sqlite3_memory_used(). +*/ +static int test_memory_used( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(sqlite3_memory_used())); + return TCL_OK; +} + +/* +** Usage: sqlite3_memory_highwater ?RESETFLAG? +** +** Raw test interface for sqlite3_memory_highwater(). +*/ +static int test_memory_highwater( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int resetFlag = 0; + if( objc!=1 && objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?RESET?"); + return TCL_ERROR; + } + if( objc==2 ){ + if( Tcl_GetBooleanFromObj(interp, objv[1], &resetFlag) ) return TCL_ERROR; + } + Tcl_SetObjResult(interp, + Tcl_NewWideIntObj(sqlite3_memory_highwater(resetFlag))); + return TCL_OK; +} + +/* +** Usage: sqlite3_memdebug_backtrace DEPTH +** +** Set the depth of backtracing. If SQLITE_MEMDEBUG is not defined +** then this routine is a no-op. +*/ +static int test_memdebug_backtrace( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int depth; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DEPT"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &depth) ) return TCL_ERROR; +#ifdef SQLITE_MEMDEBUG + { + extern void sqlite3MemdebugBacktrace(int); + sqlite3MemdebugBacktrace(depth); + } +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_memdebug_dump FILENAME +** +** Write a summary of unfreed memory to FILENAME. +*/ +static int test_memdebug_dump( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } +#if defined(SQLITE_MEMDEBUG) || defined(SQLITE_MEMORY_SIZE) \ + || defined(SQLITE_POW2_MEMORY_SIZE) + { + extern void sqlite3MemdebugDump(const char*); + sqlite3MemdebugDump(Tcl_GetString(objv[1])); + } +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_memdebug_malloc_count +** +** Return the total number of times malloc() has been called. +*/ +static int test_memdebug_malloc_count( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int nMalloc = -1; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } +#if defined(SQLITE_MEMDEBUG) + { + extern int sqlite3MemdebugMallocCount(); + nMalloc = sqlite3MemdebugMallocCount(); + } +#endif + Tcl_SetObjResult(interp, Tcl_NewIntObj(nMalloc)); + return TCL_OK; +} + + +/* +** Usage: sqlite3_memdebug_fail COUNTER ?OPTIONS? +** +** where options are: +** +** -repeat +** -benigncnt +** +** Arrange for a simulated malloc() failure after COUNTER successes. +** If a repeat count is specified, the fault is repeated that many +** times. +** +** Each call to this routine overrides the prior counter value. +** This routine returns the number of simulated failures that have +** happened since the previous call to this routine. +** +** To disable simulated failures, use a COUNTER of -1. +*/ +static int test_memdebug_fail( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int ii; + int iFail; + int nRepeat = 1; + Tcl_Obj *pBenignCnt = 0; + int nBenign; + int nFail = 0; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "COUNTER ?OPTIONS?"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &iFail) ) return TCL_ERROR; + + for(ii=2; ii1 && strncmp(zOption, "-repeat", nOption)==0 ){ + if( ii==(objc-1) ){ + zErr = "option requires an argument: "; + }else{ + if( Tcl_GetIntFromObj(interp, objv[ii+1], &nRepeat) ){ + return TCL_ERROR; + } + } + }else if( nOption>1 && strncmp(zOption, "-benigncnt", nOption)==0 ){ + if( ii==(objc-1) ){ + zErr = "option requires an argument: "; + }else{ + pBenignCnt = objv[ii+1]; + } + }else{ + zErr = "unknown option: "; + } + + if( zErr ){ + Tcl_AppendResult(interp, zErr, zOption, 0); + return TCL_ERROR; + } + } + + nBenign = faultsimBenignFailures(); + nFail = faultsimFailures(); + faultsimConfig(iFail, nRepeat); + + if( pBenignCnt ){ + Tcl_ObjSetVar2(interp, pBenignCnt, 0, Tcl_NewIntObj(nBenign), 0); + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(nFail)); + return TCL_OK; +} + +/* +** Usage: sqlite3_memdebug_pending +** +** Return the number of malloc() calls that will succeed before a +** simulated failure occurs. A negative return value indicates that +** no malloc() failure is scheduled. +*/ +static int test_memdebug_pending( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int nPending; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + nPending = faultsimPending(); + Tcl_SetObjResult(interp, Tcl_NewIntObj(nPending)); + return TCL_OK; +} + + +/* +** Usage: sqlite3_memdebug_settitle TITLE +** +** Set a title string stored with each allocation. The TITLE is +** typically the name of the test that was running when the +** allocation occurred. The TITLE is stored with the allocation +** and can be used to figure out which tests are leaking memory. +** +** Each title overwrite the previous. +*/ +static int test_memdebug_settitle( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "TITLE"); + return TCL_ERROR; + } +#ifdef SQLITE_MEMDEBUG + { + const char *zTitle; + extern int sqlite3MemdebugSettitle(const char*); + zTitle = Tcl_GetString(objv[1]); + sqlite3MemdebugSettitle(zTitle); + } +#endif + return TCL_OK; +} + +#define MALLOC_LOG_FRAMES 10 +#define MALLOC_LOG_KEYINTS ( \ + 10 * ((sizeof(int)>=sizeof(void*)) ? 1 : sizeof(void*)/sizeof(int)) \ +) +static Tcl_HashTable aMallocLog; +static int mallocLogEnabled = 0; + +typedef struct MallocLog MallocLog; +struct MallocLog { + int nCall; + int nByte; +}; + +#ifdef SQLITE_MEMDEBUG +static void test_memdebug_callback(int nByte, int nFrame, void **aFrame){ + if( mallocLogEnabled ){ + MallocLog *pLog; + Tcl_HashEntry *pEntry; + int isNew; + + int aKey[MALLOC_LOG_KEYINTS]; + unsigned int nKey = sizeof(int)*MALLOC_LOG_KEYINTS; + + memset(aKey, 0, nKey); + if( (sizeof(void*)*nFrame)nCall++; + pLog->nByte += nByte; + } +} +#endif /* SQLITE_MEMDEBUG */ + +static void test_memdebug_log_clear(void){ + Tcl_HashSearch search; + Tcl_HashEntry *pEntry; + for( + pEntry=Tcl_FirstHashEntry(&aMallocLog, &search); + pEntry; + pEntry=Tcl_NextHashEntry(&search) + ){ + MallocLog *pLog = (MallocLog *)Tcl_GetHashValue(pEntry); + Tcl_Free((char *)pLog); + } + Tcl_DeleteHashTable(&aMallocLog); + Tcl_InitHashTable(&aMallocLog, MALLOC_LOG_KEYINTS); +} + +static int test_memdebug_log( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + static int isInit = 0; + int iSub; + + static const char *MB_strs[] = { "start", "stop", "dump", "clear", "sync" }; + enum MB_enum { + MB_LOG_START, MB_LOG_STOP, MB_LOG_DUMP, MB_LOG_CLEAR, MB_LOG_SYNC + }; + + if( !isInit ){ +#ifdef SQLITE_MEMDEBUG + extern void sqlite3MemdebugBacktraceCallback( + void (*xBacktrace)(int, int, void **)); + sqlite3MemdebugBacktraceCallback(test_memdebug_callback); +#endif + Tcl_InitHashTable(&aMallocLog, MALLOC_LOG_KEYINTS); + isInit = 1; + } + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND ..."); + } + if( Tcl_GetIndexFromObj(interp, objv[1], MB_strs, "sub-command", 0, &iSub) ){ + return TCL_ERROR; + } + + switch( (enum MB_enum)iSub ){ + case MB_LOG_START: + mallocLogEnabled = 1; + break; + case MB_LOG_STOP: + mallocLogEnabled = 0; + break; + case MB_LOG_DUMP: { + Tcl_HashSearch search; + Tcl_HashEntry *pEntry; + Tcl_Obj *pRet = Tcl_NewObj(); + + assert(sizeof(Tcl_WideInt)>=sizeof(void*)); + + for( + pEntry=Tcl_FirstHashEntry(&aMallocLog, &search); + pEntry; + pEntry=Tcl_NextHashEntry(&search) + ){ + Tcl_Obj *apElem[MALLOC_LOG_FRAMES+2]; + MallocLog *pLog = (MallocLog *)Tcl_GetHashValue(pEntry); + Tcl_WideInt *aKey = (Tcl_WideInt *)Tcl_GetHashKey(&aMallocLog, pEntry); + int ii; + + apElem[0] = Tcl_NewIntObj(pLog->nCall); + apElem[1] = Tcl_NewIntObj(pLog->nByte); + for(ii=0; ii5 ){ + Tcl_WrongNumArgs(interp, 1, objv, + "INSTALLFLAG DISCARDCHANCE PRNGSEEED HIGHSTRESS"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &installFlag) ) return TCL_ERROR; + if( objc>=3 && Tcl_GetIntFromObj(interp, objv[2], &discardChance) ){ + return TCL_ERROR; + } + if( objc>=4 && Tcl_GetIntFromObj(interp, objv[3], &prngSeed) ){ + return TCL_ERROR; + } + if( objc>=5 && Tcl_GetIntFromObj(interp, objv[4], &highStress) ){ + return TCL_ERROR; + } + if( discardChance<0 || discardChance>100 ){ + Tcl_AppendResult(interp, "discard-chance should be between 0 and 100", + (char*)0); + return TCL_ERROR; + } + installTestPCache(installFlag, (unsigned)discardChance, (unsigned)prngSeed, + (unsigned)highStress); + return TCL_OK; +} + +/* +** Usage: sqlite3_config_memstatus BOOLEAN +** +** Enable or disable memory status reporting using SQLITE_CONFIG_MEMSTATUS. +*/ +static int test_config_memstatus( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int enable, rc; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[1], &enable) ) return TCL_ERROR; + rc = sqlite3_config(SQLITE_CONFIG_MEMSTATUS, enable); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** Usage: sqlite3_config_lookaside SIZE COUNT +** +*/ +static int test_config_lookaside( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int sz, cnt; + Tcl_Obj *pRet; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SIZE COUNT"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &sz) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &cnt) ) return TCL_ERROR; + pRet = Tcl_NewObj(); + Tcl_ListObjAppendElement( + interp, pRet, Tcl_NewIntObj(sqlite3GlobalConfig.szLookaside) + ); + Tcl_ListObjAppendElement( + interp, pRet, Tcl_NewIntObj(sqlite3GlobalConfig.nLookaside) + ); + sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, cnt); + Tcl_SetObjResult(interp, pRet); + return TCL_OK; +} + + +/* +** Usage: sqlite3_db_config_lookaside CONNECTION BUFID SIZE COUNT +** +** There are two static buffers with BUFID 1 and 2. Each static buffer +** is 10KB in size. A BUFID of 0 indicates that the buffer should be NULL +** which will cause sqlite3_db_config() to allocate space on its own. +*/ +static int test_db_config_lookaside( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + int sz, cnt; + sqlite3 *db; + int bufid; + static char azBuf[2][10000]; + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BUFID SIZE COUNT"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &bufid) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &sz) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[4], &cnt) ) return TCL_ERROR; + if( bufid==0 ){ + rc = sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE, 0, sz, cnt); + }else if( bufid>=1 && bufid<=2 && sz*cnt<=sizeof(azBuf[0]) ){ + rc = sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE, azBuf[bufid], sz,cnt); + }else{ + Tcl_AppendResult(interp, "illegal arguments - see documentation", (char*)0); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** Usage: sqlite3_config_heap NBYTE NMINALLOC +*/ +static int test_config_heap( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + static char *zBuf; /* Use this memory */ + int nByte; /* Size of buffer to pass to sqlite3_config() */ + int nMinAlloc; /* Size of minimum allocation */ + int rc; /* Return code of sqlite3_config() */ + + Tcl_Obj * CONST *aArg = &objv[1]; + int nArg = objc-1; + + if( nArg!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "NBYTE NMINALLOC"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, aArg[0], &nByte) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, aArg[1], &nMinAlloc) ) return TCL_ERROR; + + if( nByte==0 ){ + free( zBuf ); + zBuf = 0; + rc = sqlite3_config(SQLITE_CONFIG_HEAP, (void*)0, 0, 0); + }else{ + zBuf = realloc(zBuf, nByte); + rc = sqlite3_config(SQLITE_CONFIG_HEAP, zBuf, nByte, nMinAlloc); + } + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** Usage: sqlite3_config_error [DB] +** +** Invoke sqlite3_config() or sqlite3_db_config() with invalid +** opcodes and verify that they return errors. +*/ +static int test_config_error( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + + if( objc!=2 && objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, "[DB]"); + return TCL_ERROR; + } + if( objc==2 ){ + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( sqlite3_db_config(db, 99999)!=SQLITE_ERROR ){ + Tcl_AppendResult(interp, + "sqlite3_db_config(db, 99999) does not return SQLITE_ERROR", + (char*)0); + return TCL_ERROR; + } + }else{ + if( sqlite3_config(99999)!=SQLITE_ERROR ){ + Tcl_AppendResult(interp, + "sqlite3_config(99999) does not return SQLITE_ERROR", + (char*)0); + return TCL_ERROR; + } + } + return TCL_OK; +} + +/* +** Usage: sqlite3_config_uri BOOLEAN +** +** Enables or disables interpretation of URI parameters by default using +** SQLITE_CONFIG_URI. +*/ +static int test_config_uri( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + int bOpenUri; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOL"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[1], &bOpenUri) ){ + return TCL_ERROR; + } + + rc = sqlite3_config(SQLITE_CONFIG_URI, bOpenUri); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + + return TCL_OK; +} + +/* +** Usage: sqlite3_config_cis BOOLEAN +** +** Enables or disables the use of the covering-index scan optimization. +** SQLITE_CONFIG_COVERING_INDEX_SCAN. +*/ +static int test_config_cis( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + int bUseCis; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOL"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[1], &bUseCis) ){ + return TCL_ERROR; + } + + rc = sqlite3_config(SQLITE_CONFIG_COVERING_INDEX_SCAN, bUseCis); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + + return TCL_OK; +} + +/* +** Usage: sqlite3_dump_memsys3 FILENAME +** sqlite3_dump_memsys5 FILENAME +** +** Write a summary of unfreed memsys3 allocations to FILENAME. +*/ +static int test_dump_memsys3( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } + + switch( SQLITE_PTR_TO_INT(clientData) ){ + case 3: { +#ifdef SQLITE_ENABLE_MEMSYS3 + extern void sqlite3Memsys3Dump(const char*); + sqlite3Memsys3Dump(Tcl_GetString(objv[1])); + break; +#endif + } + case 5: { +#ifdef SQLITE_ENABLE_MEMSYS5 + extern void sqlite3Memsys5Dump(const char*); + sqlite3Memsys5Dump(Tcl_GetString(objv[1])); + break; +#endif + } + } + return TCL_OK; +} + +/* +** Usage: sqlite3_status OPCODE RESETFLAG +** +** Return a list of three elements which are the sqlite3_status() return +** code, the current value, and the high-water mark value. +*/ +static int test_status( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc, iValue, mxValue; + int i, op, resetFlag; + const char *zOpName; + static const struct { + const char *zName; + int op; + } aOp[] = { + { "SQLITE_STATUS_MEMORY_USED", SQLITE_STATUS_MEMORY_USED }, + { "SQLITE_STATUS_MALLOC_SIZE", SQLITE_STATUS_MALLOC_SIZE }, + { "SQLITE_STATUS_PAGECACHE_USED", SQLITE_STATUS_PAGECACHE_USED }, + { "SQLITE_STATUS_PAGECACHE_OVERFLOW", SQLITE_STATUS_PAGECACHE_OVERFLOW }, + { "SQLITE_STATUS_PAGECACHE_SIZE", SQLITE_STATUS_PAGECACHE_SIZE }, + { "SQLITE_STATUS_SCRATCH_USED", SQLITE_STATUS_SCRATCH_USED }, + { "SQLITE_STATUS_SCRATCH_OVERFLOW", SQLITE_STATUS_SCRATCH_OVERFLOW }, + { "SQLITE_STATUS_SCRATCH_SIZE", SQLITE_STATUS_SCRATCH_SIZE }, + { "SQLITE_STATUS_PARSER_STACK", SQLITE_STATUS_PARSER_STACK }, + { "SQLITE_STATUS_MALLOC_COUNT", SQLITE_STATUS_MALLOC_COUNT }, + }; + Tcl_Obj *pResult; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PARAMETER RESETFLAG"); + return TCL_ERROR; + } + zOpName = Tcl_GetString(objv[1]); + for(i=0; i=ArraySize(aOp) ){ + if( Tcl_GetIntFromObj(interp, objv[1], &op) ) return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[2], &resetFlag) ) return TCL_ERROR; + iValue = 0; + mxValue = 0; + rc = sqlite3_status(op, &iValue, &mxValue, resetFlag); + pResult = Tcl_NewObj(); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(rc)); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(iValue)); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(mxValue)); + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + +/* +** Usage: sqlite3_db_status DATABASE OPCODE RESETFLAG +** +** Return a list of three elements which are the sqlite3_db_status() return +** code, the current value, and the high-water mark value. +*/ +static int test_db_status( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc, iValue, mxValue; + int i, op, resetFlag; + const char *zOpName; + sqlite3 *db; + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + static const struct { + const char *zName; + int op; + } aOp[] = { + { "LOOKASIDE_USED", SQLITE_DBSTATUS_LOOKASIDE_USED }, + { "CACHE_USED", SQLITE_DBSTATUS_CACHE_USED }, + { "SCHEMA_USED", SQLITE_DBSTATUS_SCHEMA_USED }, + { "STMT_USED", SQLITE_DBSTATUS_STMT_USED }, + { "LOOKASIDE_HIT", SQLITE_DBSTATUS_LOOKASIDE_HIT }, + { "LOOKASIDE_MISS_SIZE", SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE }, + { "LOOKASIDE_MISS_FULL", SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL }, + { "CACHE_HIT", SQLITE_DBSTATUS_CACHE_HIT }, + { "CACHE_MISS", SQLITE_DBSTATUS_CACHE_MISS }, + { "CACHE_WRITE", SQLITE_DBSTATUS_CACHE_WRITE }, + { "DEFERRED_FKS", SQLITE_DBSTATUS_DEFERRED_FKS } + }; + Tcl_Obj *pResult; + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB PARAMETER RESETFLAG"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zOpName = Tcl_GetString(objv[2]); + if( memcmp(zOpName, "SQLITE_", 7)==0 ) zOpName += 7; + if( memcmp(zOpName, "DBSTATUS_", 9)==0 ) zOpName += 9; + for(i=0; i=ArraySize(aOp) ){ + if( Tcl_GetIntFromObj(interp, objv[2], &op) ) return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[3], &resetFlag) ) return TCL_ERROR; + iValue = 0; + mxValue = 0; + rc = sqlite3_db_status(db, op, &iValue, &mxValue, resetFlag); + pResult = Tcl_NewObj(); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(rc)); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(iValue)); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(mxValue)); + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + +/* +** install_malloc_faultsim BOOLEAN +*/ +static int test_install_malloc_faultsim( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + int isInstall; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN"); + return TCL_ERROR; + } + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[1], &isInstall) ){ + return TCL_ERROR; + } + rc = faultsimInstall(isInstall); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** sqlite3_install_memsys3 +*/ +static int test_install_memsys3( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = SQLITE_MISUSE; +#ifdef SQLITE_ENABLE_MEMSYS3 + const sqlite3_mem_methods *sqlite3MemGetMemsys3(void); + rc = sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetMemsys3()); +#endif + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +static int test_vfs_oom_test( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + extern int sqlite3_memdebug_vfs_oom_test; + if( objc>2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?INTEGER?"); + return TCL_ERROR; + }else if( objc==2 ){ + int iNew; + if( Tcl_GetIntFromObj(interp, objv[1], &iNew) ) return TCL_ERROR; + sqlite3_memdebug_vfs_oom_test = iNew; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_memdebug_vfs_oom_test)); + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest_malloc_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + int clientData; + } aObjCmd[] = { + { "sqlite3_malloc", test_malloc ,0 }, + { "sqlite3_realloc", test_realloc ,0 }, + { "sqlite3_free", test_free ,0 }, + { "memset", test_memset ,0 }, + { "memget", test_memget ,0 }, + { "sqlite3_memory_used", test_memory_used ,0 }, + { "sqlite3_memory_highwater", test_memory_highwater ,0 }, + { "sqlite3_memdebug_backtrace", test_memdebug_backtrace ,0 }, + { "sqlite3_memdebug_dump", test_memdebug_dump ,0 }, + { "sqlite3_memdebug_fail", test_memdebug_fail ,0 }, + { "sqlite3_memdebug_pending", test_memdebug_pending ,0 }, + { "sqlite3_memdebug_settitle", test_memdebug_settitle ,0 }, + { "sqlite3_memdebug_malloc_count", test_memdebug_malloc_count ,0 }, + { "sqlite3_memdebug_log", test_memdebug_log ,0 }, + { "sqlite3_config_scratch", test_config_scratch ,0 }, + { "sqlite3_config_pagecache", test_config_pagecache ,0 }, + { "sqlite3_config_alt_pcache", test_alt_pcache ,0 }, + { "sqlite3_status", test_status ,0 }, + { "sqlite3_db_status", test_db_status ,0 }, + { "install_malloc_faultsim", test_install_malloc_faultsim ,0 }, + { "sqlite3_config_heap", test_config_heap ,0 }, + { "sqlite3_config_memstatus", test_config_memstatus ,0 }, + { "sqlite3_config_lookaside", test_config_lookaside ,0 }, + { "sqlite3_config_error", test_config_error ,0 }, + { "sqlite3_config_uri", test_config_uri ,0 }, + { "sqlite3_config_cis", test_config_cis ,0 }, + { "sqlite3_db_config_lookaside",test_db_config_lookaside ,0 }, + { "sqlite3_dump_memsys3", test_dump_memsys3 ,3 }, + { "sqlite3_dump_memsys5", test_dump_memsys3 ,5 }, + { "sqlite3_install_memsys3", test_install_memsys3 ,0 }, + { "sqlite3_memdebug_vfs_oom_test", test_vfs_oom_test ,0 }, + }; + int i; + for(i=0; i +#include +#include +#include "test_multiplex.h" + +#ifndef SQLITE_CORE + #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ +#endif +#include "sqlite3ext.h" + +/* +** These should be defined to be the same as the values in +** sqliteInt.h. They are defined separately here so that +** the multiplex VFS shim can be built as a loadable +** module. +*/ +#define UNUSED_PARAMETER(x) (void)(x) +#define MAX_PAGE_SIZE 0x10000 +#define DEFAULT_SECTOR_SIZE 0x1000 + +/* +** For a build without mutexes, no-op the mutex calls. +*/ +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0 +#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) +#define sqlite3_mutex_free(X) +#define sqlite3_mutex_enter(X) +#define sqlite3_mutex_try(X) SQLITE_OK +#define sqlite3_mutex_leave(X) +#define sqlite3_mutex_held(X) ((void)(X),1) +#define sqlite3_mutex_notheld(X) ((void)(X),1) +#endif /* SQLITE_THREADSAFE==0 */ + +/* Maximum chunk number */ +#define MX_CHUNK_NUMBER 299 + +/* First chunk for rollback journal files */ +#define SQLITE_MULTIPLEX_JOURNAL_8_3_OFFSET 400 +#define SQLITE_MULTIPLEX_WAL_8_3_OFFSET 700 + + +/************************ Shim Definitions ******************************/ + +#ifndef SQLITE_MULTIPLEX_VFS_NAME +# define SQLITE_MULTIPLEX_VFS_NAME "multiplex" +#endif + +/* This is the limit on the chunk size. It may be changed by calling +** the xFileControl() interface. It will be rounded up to a +** multiple of MAX_PAGE_SIZE. We default it here to 2GiB less 64KiB. +*/ +#ifndef SQLITE_MULTIPLEX_CHUNK_SIZE +# define SQLITE_MULTIPLEX_CHUNK_SIZE 2147418112 +#endif + +/* This used to be the default limit on number of chunks, but +** it is no longer enforced. There is currently no limit to the +** number of chunks. +** +** May be changed by calling the xFileControl() interface. +*/ +#ifndef SQLITE_MULTIPLEX_MAX_CHUNKS +# define SQLITE_MULTIPLEX_MAX_CHUNKS 12 +#endif + +/************************ Object Definitions ******************************/ + +/* Forward declaration of all object types */ +typedef struct multiplexGroup multiplexGroup; +typedef struct multiplexConn multiplexConn; + +/* +** A "multiplex group" is a collection of files that collectively +** makeup a single SQLite DB file. This allows the size of the DB +** to exceed the limits imposed by the file system. +** +** There is an instance of the following object for each defined multiplex +** group. +*/ +struct multiplexGroup { + struct multiplexReal { /* For each chunk */ + sqlite3_file *p; /* Handle for the chunk */ + char *z; /* Name of this chunk */ + } *aReal; /* list of all chunks */ + int nReal; /* Number of chunks */ + char *zName; /* Base filename of this group */ + int nName; /* Length of base filename */ + int flags; /* Flags used for original opening */ + unsigned int szChunk; /* Chunk size used for this group */ + unsigned char bEnabled; /* TRUE to use Multiplex VFS for this file */ + unsigned char bTruncate; /* TRUE to enable truncation of databases */ + multiplexGroup *pNext, *pPrev; /* Doubly linked list of all group objects */ +}; + +/* +** An instance of the following object represents each open connection +** to a file that is multiplex'ed. This object is a +** subclass of sqlite3_file. The sqlite3_file object for the underlying +** VFS is appended to this structure. +*/ +struct multiplexConn { + sqlite3_file base; /* Base class - must be first */ + multiplexGroup *pGroup; /* The underlying group of files */ +}; + +/************************* Global Variables **********************************/ +/* +** All global variables used by this file are containing within the following +** gMultiplex structure. +*/ +static struct { + /* The pOrigVfs is the real, original underlying VFS implementation. + ** Most operations pass-through to the real VFS. This value is read-only + ** during operation. It is only modified at start-time and thus does not + ** require a mutex. + */ + sqlite3_vfs *pOrigVfs; + + /* The sThisVfs is the VFS structure used by this shim. It is initialized + ** at start-time and thus does not require a mutex + */ + sqlite3_vfs sThisVfs; + + /* The sIoMethods defines the methods used by sqlite3_file objects + ** associated with this shim. It is initialized at start-time and does + ** not require a mutex. + ** + ** When the underlying VFS is called to open a file, it might return + ** either a version 1 or a version 2 sqlite3_file object. This shim + ** has to create a wrapper sqlite3_file of the same version. Hence + ** there are two I/O method structures, one for version 1 and the other + ** for version 2. + */ + sqlite3_io_methods sIoMethodsV1; + sqlite3_io_methods sIoMethodsV2; + + /* True when this shim has been initialized. + */ + int isInitialized; + + /* For run-time access any of the other global data structures in this + ** shim, the following mutex must be held. + */ + sqlite3_mutex *pMutex; + + /* List of multiplexGroup objects. + */ + multiplexGroup *pGroups; +} gMultiplex; + +/************************* Utility Routines *********************************/ +/* +** Acquire and release the mutex used to serialize access to the +** list of multiplexGroups. +*/ +static void multiplexEnter(void){ sqlite3_mutex_enter(gMultiplex.pMutex); } +static void multiplexLeave(void){ sqlite3_mutex_leave(gMultiplex.pMutex); } + +/* +** Compute a string length that is limited to what can be stored in +** lower 30 bits of a 32-bit signed integer. +** +** The value returned will never be negative. Nor will it ever be greater +** than the actual length of the string. For very long strings (greater +** than 1GiB) the value returned might be less than the true string length. +*/ +static int multiplexStrlen30(const char *z){ + const char *z2 = z; + if( z==0 ) return 0; + while( *z2 ){ z2++; } + return 0x3fffffff & (int)(z2 - z); +} + +/* +** Generate the file-name for chunk iChunk of the group with base name +** zBase. The file-name is written to buffer zOut before returning. Buffer +** zOut must be allocated by the caller so that it is at least (nBase+5) +** bytes in size, where nBase is the length of zBase, not including the +** nul-terminator. +** +** If iChunk is 0 (or 400 - the number for the first journal file chunk), +** the output is a copy of the input string. Otherwise, if +** SQLITE_ENABLE_8_3_NAMES is not defined or the input buffer does not contain +** a "." character, then the output is a copy of the input string with the +** three-digit zero-padded decimal representation if iChunk appended to it. +** For example: +** +** zBase="test.db", iChunk=4 -> zOut="test.db004" +** +** Or, if SQLITE_ENABLE_8_3_NAMES is defined and the input buffer contains +** a "." character, then everything after the "." is replaced by the +** three-digit representation of iChunk. +** +** zBase="test.db", iChunk=4 -> zOut="test.004" +** +** The output buffer string is terminated by 2 0x00 bytes. This makes it safe +** to pass to sqlite3_uri_parameter() and similar. +*/ +static void multiplexFilename( + const char *zBase, /* Filename for chunk 0 */ + int nBase, /* Size of zBase in bytes (without \0) */ + int flags, /* Flags used to open file */ + int iChunk, /* Chunk to generate filename for */ + char *zOut /* Buffer to write generated name to */ +){ + int n = nBase; + memcpy(zOut, zBase, n+1); + if( iChunk!=0 && iChunk<=MX_CHUNK_NUMBER ){ +#ifdef SQLITE_ENABLE_8_3_NAMES + int i; + for(i=n-1; i>0 && i>=n-4 && zOut[i]!='.'; i--){} + if( i>=n-4 ) n = i+1; + if( flags & SQLITE_OPEN_MAIN_JOURNAL ){ + /* The extensions on overflow files for main databases are 001, 002, + ** 003 and so forth. To avoid name collisions, add 400 to the + ** extensions of journal files so that they are 401, 402, 403, .... + */ + iChunk += SQLITE_MULTIPLEX_JOURNAL_8_3_OFFSET; + }else if( flags & SQLITE_OPEN_WAL ){ + /* To avoid name collisions, add 700 to the + ** extensions of WAL files so that they are 701, 702, 703, .... + */ + iChunk += SQLITE_MULTIPLEX_WAL_8_3_OFFSET; + } +#endif + sqlite3_snprintf(4,&zOut[n],"%03d",iChunk); + n += 3; + } + + assert( zOut[n]=='\0' ); + zOut[n+1] = '\0'; +} + +/* Compute the filename for the iChunk-th chunk +*/ +static int multiplexSubFilename(multiplexGroup *pGroup, int iChunk){ + if( iChunk>=pGroup->nReal ){ + struct multiplexReal *p; + p = sqlite3_realloc(pGroup->aReal, (iChunk+1)*sizeof(*p)); + if( p==0 ){ + return SQLITE_NOMEM; + } + memset(&p[pGroup->nReal], 0, sizeof(p[0])*(iChunk+1-pGroup->nReal)); + pGroup->aReal = p; + pGroup->nReal = iChunk+1; + } + if( pGroup->zName && pGroup->aReal[iChunk].z==0 ){ + char *z; + int n = pGroup->nName; + pGroup->aReal[iChunk].z = z = sqlite3_malloc( n+5 ); + if( z==0 ){ + return SQLITE_NOMEM; + } + multiplexFilename(pGroup->zName, pGroup->nName, pGroup->flags, iChunk, z); + } + return SQLITE_OK; +} + +/* Translate an sqlite3_file* that is really a multiplexGroup* into +** the sqlite3_file* for the underlying original VFS. +** +** For chunk 0, the pGroup->flags determines whether or not a new file +** is created if it does not already exist. For chunks 1 and higher, the +** file is created only if createFlag is 1. +*/ +static sqlite3_file *multiplexSubOpen( + multiplexGroup *pGroup, /* The multiplexor group */ + int iChunk, /* Which chunk to open. 0==original file */ + int *rc, /* Result code in and out */ + int *pOutFlags, /* Output flags */ + int createFlag /* True to create if iChunk>0 */ +){ + sqlite3_file *pSubOpen = 0; + sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs; /* Real VFS */ + +#ifdef SQLITE_ENABLE_8_3_NAMES + /* If JOURNAL_8_3_OFFSET is set to (say) 400, then any overflow files are + ** part of a database journal are named db.401, db.402, and so on. A + ** database may therefore not grow to larger than 400 chunks. Attempting + ** to open chunk 401 indicates the database is full. */ + if( iChunk>=SQLITE_MULTIPLEX_JOURNAL_8_3_OFFSET ){ + sqlite3_log(SQLITE_FULL, "multiplexed chunk overflow: %s", pGroup->zName); + *rc = SQLITE_FULL; + return 0; + } +#endif + + *rc = multiplexSubFilename(pGroup, iChunk); + if( (*rc)==SQLITE_OK && (pSubOpen = pGroup->aReal[iChunk].p)==0 ){ + int flags, bExists; + flags = pGroup->flags; + if( createFlag ){ + flags |= SQLITE_OPEN_CREATE; + }else if( iChunk==0 ){ + /* Fall through */ + }else if( pGroup->aReal[iChunk].z==0 ){ + return 0; + }else{ + *rc = pOrigVfs->xAccess(pOrigVfs, pGroup->aReal[iChunk].z, + SQLITE_ACCESS_EXISTS, &bExists); + if( *rc || !bExists ){ + if( *rc ){ + sqlite3_log(*rc, "multiplexor.xAccess failure on %s", + pGroup->aReal[iChunk].z); + } + return 0; + } + flags &= ~SQLITE_OPEN_CREATE; + } + pSubOpen = sqlite3_malloc( pOrigVfs->szOsFile ); + if( pSubOpen==0 ){ + *rc = SQLITE_IOERR_NOMEM; + return 0; + } + pGroup->aReal[iChunk].p = pSubOpen; + *rc = pOrigVfs->xOpen(pOrigVfs, pGroup->aReal[iChunk].z, pSubOpen, + flags, pOutFlags); + if( (*rc)!=SQLITE_OK ){ + sqlite3_log(*rc, "multiplexor.xOpen failure on %s", + pGroup->aReal[iChunk].z); + sqlite3_free(pSubOpen); + pGroup->aReal[iChunk].p = 0; + return 0; + } + } + return pSubOpen; +} + +/* +** Return the size, in bytes, of chunk number iChunk. If that chunk +** does not exist, then return 0. This function does not distingish between +** non-existant files and zero-length files. +*/ +static sqlite3_int64 multiplexSubSize( + multiplexGroup *pGroup, /* The multiplexor group */ + int iChunk, /* Which chunk to open. 0==original file */ + int *rc /* Result code in and out */ +){ + sqlite3_file *pSub; + sqlite3_int64 sz = 0; + + if( *rc ) return 0; + pSub = multiplexSubOpen(pGroup, iChunk, rc, NULL, 0); + if( pSub==0 ) return 0; + *rc = pSub->pMethods->xFileSize(pSub, &sz); + return sz; +} + +/* +** This is the implementation of the multiplex_control() SQL function. +*/ +static void multiplexControlFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int rc = SQLITE_OK; + sqlite3 *db = sqlite3_context_db_handle(context); + int op; + int iVal; + + if( !db || argc!=2 ){ + rc = SQLITE_ERROR; + }else{ + /* extract params */ + op = sqlite3_value_int(argv[0]); + iVal = sqlite3_value_int(argv[1]); + /* map function op to file_control op */ + switch( op ){ + case 1: + op = MULTIPLEX_CTRL_ENABLE; + break; + case 2: + op = MULTIPLEX_CTRL_SET_CHUNK_SIZE; + break; + case 3: + op = MULTIPLEX_CTRL_SET_MAX_CHUNKS; + break; + default: + rc = SQLITE_NOTFOUND; + break; + } + } + if( rc==SQLITE_OK ){ + rc = sqlite3_file_control(db, 0, op, &iVal); + } + sqlite3_result_error_code(context, rc); +} + +/* +** This is the entry point to register the auto-extension for the +** multiplex_control() function. +*/ +static int multiplexFuncInit( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc; + rc = sqlite3_create_function(db, "multiplex_control", 2, SQLITE_ANY, + 0, multiplexControlFunc, 0, 0); + return rc; +} + +/* +** Close a single sub-file in the connection group. +*/ +static void multiplexSubClose( + multiplexGroup *pGroup, + int iChunk, + sqlite3_vfs *pOrigVfs +){ + sqlite3_file *pSubOpen = pGroup->aReal[iChunk].p; + if( pSubOpen ){ + pSubOpen->pMethods->xClose(pSubOpen); + if( pOrigVfs && pGroup->aReal[iChunk].z ){ + pOrigVfs->xDelete(pOrigVfs, pGroup->aReal[iChunk].z, 0); + } + sqlite3_free(pGroup->aReal[iChunk].p); + } + sqlite3_free(pGroup->aReal[iChunk].z); + memset(&pGroup->aReal[iChunk], 0, sizeof(pGroup->aReal[iChunk])); +} + +/* +** Deallocate memory held by a multiplexGroup +*/ +static void multiplexFreeComponents(multiplexGroup *pGroup){ + int i; + for(i=0; inReal; i++){ multiplexSubClose(pGroup, i, 0); } + sqlite3_free(pGroup->aReal); + pGroup->aReal = 0; + pGroup->nReal = 0; +} + + +/************************* VFS Method Wrappers *****************************/ + +/* +** This is the xOpen method used for the "multiplex" VFS. +** +** Most of the work is done by the underlying original VFS. This method +** simply links the new file into the appropriate multiplex group if it is a +** file that needs to be tracked. +*/ +static int multiplexOpen( + sqlite3_vfs *pVfs, /* The multiplex VFS */ + const char *zName, /* Name of file to be opened */ + sqlite3_file *pConn, /* Fill in this file descriptor */ + int flags, /* Flags to control the opening */ + int *pOutFlags /* Flags showing results of opening */ +){ + int rc = SQLITE_OK; /* Result code */ + multiplexConn *pMultiplexOpen; /* The new multiplex file descriptor */ + multiplexGroup *pGroup = 0; /* Corresponding multiplexGroup object */ + sqlite3_file *pSubOpen = 0; /* Real file descriptor */ + sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs; /* Real VFS */ + int nName = 0; + int sz = 0; + char *zToFree = 0; + + UNUSED_PARAMETER(pVfs); + memset(pConn, 0, pVfs->szOsFile); + assert( zName || (flags & SQLITE_OPEN_DELETEONCLOSE) ); + + /* We need to create a group structure and manage + ** access to this group of files. + */ + multiplexEnter(); + pMultiplexOpen = (multiplexConn*)pConn; + + if( rc==SQLITE_OK ){ + /* allocate space for group */ + nName = zName ? multiplexStrlen30(zName) : 0; + sz = sizeof(multiplexGroup) /* multiplexGroup */ + + nName + 1; /* zName */ + pGroup = sqlite3_malloc( sz ); + if( pGroup==0 ){ + rc = SQLITE_NOMEM; + } + } + + if( rc==SQLITE_OK ){ + const char *zUri = (flags & SQLITE_OPEN_URI) ? zName : 0; + /* assign pointers to extra space allocated */ + memset(pGroup, 0, sz); + pMultiplexOpen->pGroup = pGroup; + pGroup->bEnabled = -1; + pGroup->bTruncate = sqlite3_uri_boolean(zUri, "truncate", + (flags & SQLITE_OPEN_MAIN_DB)==0); + pGroup->szChunk = (int)sqlite3_uri_int64(zUri, "chunksize", + SQLITE_MULTIPLEX_CHUNK_SIZE); + pGroup->szChunk = (pGroup->szChunk+0xffff)&~0xffff; + if( zName ){ + char *p = (char *)&pGroup[1]; + pGroup->zName = p; + memcpy(pGroup->zName, zName, nName+1); + pGroup->nName = nName; + } + if( pGroup->bEnabled ){ + /* Make sure that the chunksize is such that the pending byte does not + ** falls at the end of a chunk. A region of up to 64K following + ** the pending byte is never written, so if the pending byte occurs + ** near the end of a chunk, that chunk will be too small. */ +#ifndef SQLITE_OMIT_WSD + extern int sqlite3PendingByte; +#else + int sqlite3PendingByte = 0x40000000; +#endif + while( (sqlite3PendingByte % pGroup->szChunk)>=(pGroup->szChunk-65536) ){ + pGroup->szChunk += 65536; + } + } + pGroup->flags = flags; + rc = multiplexSubFilename(pGroup, 1); + if( rc==SQLITE_OK ){ + pSubOpen = multiplexSubOpen(pGroup, 0, &rc, pOutFlags, 0); + if( pSubOpen==0 && rc==SQLITE_OK ) rc = SQLITE_CANTOPEN; + } + if( rc==SQLITE_OK ){ + sqlite3_int64 sz; + + rc = pSubOpen->pMethods->xFileSize(pSubOpen, &sz); + if( rc==SQLITE_OK && zName ){ + int bExists; + if( sz==0 ){ + if( flags & SQLITE_OPEN_MAIN_JOURNAL ){ + /* If opening a main journal file and the first chunk is zero + ** bytes in size, delete any subsequent chunks from the + ** file-system. */ + int iChunk = 1; + do { + rc = pOrigVfs->xAccess(pOrigVfs, + pGroup->aReal[iChunk].z, SQLITE_ACCESS_EXISTS, &bExists + ); + if( rc==SQLITE_OK && bExists ){ + rc = pOrigVfs->xDelete(pOrigVfs, pGroup->aReal[iChunk].z, 0); + if( rc==SQLITE_OK ){ + rc = multiplexSubFilename(pGroup, ++iChunk); + } + } + }while( rc==SQLITE_OK && bExists ); + } + }else{ + /* If the first overflow file exists and if the size of the main file + ** is different from the chunk size, that means the chunk size is set + ** set incorrectly. So fix it. + ** + ** Or, if the first overflow file does not exist and the main file is + ** larger than the chunk size, that means the chunk size is too small. + ** But we have no way of determining the intended chunk size, so + ** just disable the multiplexor all togethre. + */ + rc = pOrigVfs->xAccess(pOrigVfs, pGroup->aReal[1].z, + SQLITE_ACCESS_EXISTS, &bExists); + bExists = multiplexSubSize(pGroup, 1, &rc)>0; + if( rc==SQLITE_OK && bExists && sz==(sz&0xffff0000) && sz>0 + && sz!=pGroup->szChunk ){ + pGroup->szChunk = (int)sz; + }else if( rc==SQLITE_OK && !bExists && sz>pGroup->szChunk ){ + pGroup->bEnabled = 0; + } + } + } + } + + if( rc==SQLITE_OK ){ + if( pSubOpen->pMethods->iVersion==1 ){ + pMultiplexOpen->base.pMethods = &gMultiplex.sIoMethodsV1; + }else{ + pMultiplexOpen->base.pMethods = &gMultiplex.sIoMethodsV2; + } + /* place this group at the head of our list */ + pGroup->pNext = gMultiplex.pGroups; + if( gMultiplex.pGroups ) gMultiplex.pGroups->pPrev = pGroup; + gMultiplex.pGroups = pGroup; + }else{ + multiplexFreeComponents(pGroup); + sqlite3_free(pGroup); + } + } + multiplexLeave(); + sqlite3_free(zToFree); + return rc; +} + +/* +** This is the xDelete method used for the "multiplex" VFS. +** It attempts to delete the filename specified. +*/ +static int multiplexDelete( + sqlite3_vfs *pVfs, /* The multiplex VFS */ + const char *zName, /* Name of file to delete */ + int syncDir +){ + int rc; + sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs; /* Real VFS */ + rc = pOrigVfs->xDelete(pOrigVfs, zName, syncDir); + if( rc==SQLITE_OK ){ + /* If the main chunk was deleted successfully, also delete any subsequent + ** chunks - starting with the last (highest numbered). + */ + int nName = (int)strlen(zName); + char *z; + z = sqlite3_malloc(nName + 5); + if( z==0 ){ + rc = SQLITE_IOERR_NOMEM; + }else{ + int iChunk = 0; + int bExists; + do{ + multiplexFilename(zName, nName, SQLITE_OPEN_MAIN_JOURNAL, ++iChunk, z); + rc = pOrigVfs->xAccess(pOrigVfs, z, SQLITE_ACCESS_EXISTS, &bExists); + }while( rc==SQLITE_OK && bExists ); + while( rc==SQLITE_OK && iChunk>1 ){ + multiplexFilename(zName, nName, SQLITE_OPEN_MAIN_JOURNAL, --iChunk, z); + rc = pOrigVfs->xDelete(pOrigVfs, z, syncDir); + } + if( rc==SQLITE_OK ){ + iChunk = 0; + do{ + multiplexFilename(zName, nName, SQLITE_OPEN_WAL, ++iChunk, z); + rc = pOrigVfs->xAccess(pOrigVfs, z, SQLITE_ACCESS_EXISTS, &bExists); + }while( rc==SQLITE_OK && bExists ); + while( rc==SQLITE_OK && iChunk>1 ){ + multiplexFilename(zName, nName, SQLITE_OPEN_WAL, --iChunk, z); + rc = pOrigVfs->xDelete(pOrigVfs, z, syncDir); + } + } + } + sqlite3_free(z); + } + return rc; +} + +static int multiplexAccess(sqlite3_vfs *a, const char *b, int c, int *d){ + return gMultiplex.pOrigVfs->xAccess(gMultiplex.pOrigVfs, b, c, d); +} +static int multiplexFullPathname(sqlite3_vfs *a, const char *b, int c, char *d){ + return gMultiplex.pOrigVfs->xFullPathname(gMultiplex.pOrigVfs, b, c, d); +} +static void *multiplexDlOpen(sqlite3_vfs *a, const char *b){ + return gMultiplex.pOrigVfs->xDlOpen(gMultiplex.pOrigVfs, b); +} +static void multiplexDlError(sqlite3_vfs *a, int b, char *c){ + gMultiplex.pOrigVfs->xDlError(gMultiplex.pOrigVfs, b, c); +} +static void (*multiplexDlSym(sqlite3_vfs *a, void *b, const char *c))(void){ + return gMultiplex.pOrigVfs->xDlSym(gMultiplex.pOrigVfs, b, c); +} +static void multiplexDlClose(sqlite3_vfs *a, void *b){ + gMultiplex.pOrigVfs->xDlClose(gMultiplex.pOrigVfs, b); +} +static int multiplexRandomness(sqlite3_vfs *a, int b, char *c){ + return gMultiplex.pOrigVfs->xRandomness(gMultiplex.pOrigVfs, b, c); +} +static int multiplexSleep(sqlite3_vfs *a, int b){ + return gMultiplex.pOrigVfs->xSleep(gMultiplex.pOrigVfs, b); +} +static int multiplexCurrentTime(sqlite3_vfs *a, double *b){ + return gMultiplex.pOrigVfs->xCurrentTime(gMultiplex.pOrigVfs, b); +} +static int multiplexGetLastError(sqlite3_vfs *a, int b, char *c){ + return gMultiplex.pOrigVfs->xGetLastError(gMultiplex.pOrigVfs, b, c); +} +static int multiplexCurrentTimeInt64(sqlite3_vfs *a, sqlite3_int64 *b){ + return gMultiplex.pOrigVfs->xCurrentTimeInt64(gMultiplex.pOrigVfs, b); +} + +/************************ I/O Method Wrappers *******************************/ + +/* xClose requests get passed through to the original VFS. +** We loop over all open chunk handles and close them. +** The group structure for this file is unlinked from +** our list of groups and freed. +*/ +static int multiplexClose(sqlite3_file *pConn){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + multiplexEnter(); + multiplexFreeComponents(pGroup); + /* remove from linked list */ + if( pGroup->pNext ) pGroup->pNext->pPrev = pGroup->pPrev; + if( pGroup->pPrev ){ + pGroup->pPrev->pNext = pGroup->pNext; + }else{ + gMultiplex.pGroups = pGroup->pNext; + } + sqlite3_free(pGroup); + multiplexLeave(); + return rc; +} + +/* Pass xRead requests thru to the original VFS after +** determining the correct chunk to operate on. +** Break up reads across chunk boundaries. +*/ +static int multiplexRead( + sqlite3_file *pConn, + void *pBuf, + int iAmt, + sqlite3_int64 iOfst +){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + multiplexEnter(); + if( !pGroup->bEnabled ){ + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen==0 ){ + rc = SQLITE_IOERR_READ; + }else{ + rc = pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt, iOfst); + } + }else{ + while( iAmt > 0 ){ + int i = (int)(iOfst / pGroup->szChunk); + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1); + if( pSubOpen ){ + int extra = ((int)(iOfst % pGroup->szChunk) + iAmt) - pGroup->szChunk; + if( extra<0 ) extra = 0; + iAmt -= extra; + rc = pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt, + iOfst % pGroup->szChunk); + if( rc!=SQLITE_OK ) break; + pBuf = (char *)pBuf + iAmt; + iOfst += iAmt; + iAmt = extra; + }else{ + rc = SQLITE_IOERR_READ; + break; + } + } + } + multiplexLeave(); + return rc; +} + +/* Pass xWrite requests thru to the original VFS after +** determining the correct chunk to operate on. +** Break up writes across chunk boundaries. +*/ +static int multiplexWrite( + sqlite3_file *pConn, + const void *pBuf, + int iAmt, + sqlite3_int64 iOfst +){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + multiplexEnter(); + if( !pGroup->bEnabled ){ + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen==0 ){ + rc = SQLITE_IOERR_WRITE; + }else{ + rc = pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt, iOfst); + } + }else{ + while( rc==SQLITE_OK && iAmt>0 ){ + int i = (int)(iOfst / pGroup->szChunk); + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1); + if( pSubOpen ){ + int extra = ((int)(iOfst % pGroup->szChunk) + iAmt) - + pGroup->szChunk; + if( extra<0 ) extra = 0; + iAmt -= extra; + rc = pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt, + iOfst % pGroup->szChunk); + pBuf = (char *)pBuf + iAmt; + iOfst += iAmt; + iAmt = extra; + } + } + } + multiplexLeave(); + return rc; +} + +/* Pass xTruncate requests thru to the original VFS after +** determining the correct chunk to operate on. Delete any +** chunks above the truncate mark. +*/ +static int multiplexTruncate(sqlite3_file *pConn, sqlite3_int64 size){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + multiplexEnter(); + if( !pGroup->bEnabled ){ + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen==0 ){ + rc = SQLITE_IOERR_TRUNCATE; + }else{ + rc = pSubOpen->pMethods->xTruncate(pSubOpen, size); + } + }else{ + int i; + int iBaseGroup = (int)(size / pGroup->szChunk); + sqlite3_file *pSubOpen; + sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs; /* Real VFS */ + /* delete the chunks above the truncate limit */ + for(i = pGroup->nReal-1; i>iBaseGroup && rc==SQLITE_OK; i--){ + if( pGroup->bTruncate ){ + multiplexSubClose(pGroup, i, pOrigVfs); + }else{ + pSubOpen = multiplexSubOpen(pGroup, i, &rc, 0, 0); + if( pSubOpen ){ + rc = pSubOpen->pMethods->xTruncate(pSubOpen, 0); + } + } + } + if( rc==SQLITE_OK ){ + pSubOpen = multiplexSubOpen(pGroup, iBaseGroup, &rc, 0, 0); + if( pSubOpen ){ + rc = pSubOpen->pMethods->xTruncate(pSubOpen, size % pGroup->szChunk); + } + } + if( rc ) rc = SQLITE_IOERR_TRUNCATE; + } + multiplexLeave(); + return rc; +} + +/* Pass xSync requests through to the original VFS without change +*/ +static int multiplexSync(sqlite3_file *pConn, int flags){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + int i; + multiplexEnter(); + for(i=0; inReal; i++){ + sqlite3_file *pSubOpen = pGroup->aReal[i].p; + if( pSubOpen ){ + int rc2 = pSubOpen->pMethods->xSync(pSubOpen, flags); + if( rc2!=SQLITE_OK ) rc = rc2; + } + } + multiplexLeave(); + return rc; +} + +/* Pass xFileSize requests through to the original VFS. +** Aggregate the size of all the chunks before returning. +*/ +static int multiplexFileSize(sqlite3_file *pConn, sqlite3_int64 *pSize){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + int i; + multiplexEnter(); + if( !pGroup->bEnabled ){ + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen==0 ){ + rc = SQLITE_IOERR_FSTAT; + }else{ + rc = pSubOpen->pMethods->xFileSize(pSubOpen, pSize); + } + }else{ + *pSize = 0; + for(i=0; rc==SQLITE_OK; i++){ + sqlite3_int64 sz = multiplexSubSize(pGroup, i, &rc); + if( sz==0 ) break; + *pSize = i*(sqlite3_int64)pGroup->szChunk + sz; + } + } + multiplexLeave(); + return rc; +} + +/* Pass xLock requests through to the original VFS unchanged. +*/ +static int multiplexLock(sqlite3_file *pConn, int lock){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xLock(pSubOpen, lock); + } + return SQLITE_BUSY; +} + +/* Pass xUnlock requests through to the original VFS unchanged. +*/ +static int multiplexUnlock(sqlite3_file *pConn, int lock){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xUnlock(pSubOpen, lock); + } + return SQLITE_IOERR_UNLOCK; +} + +/* Pass xCheckReservedLock requests through to the original VFS unchanged. +*/ +static int multiplexCheckReservedLock(sqlite3_file *pConn, int *pResOut){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xCheckReservedLock(pSubOpen, pResOut); + } + return SQLITE_IOERR_CHECKRESERVEDLOCK; +} + +/* Pass xFileControl requests through to the original VFS unchanged, +** except for any MULTIPLEX_CTRL_* requests here. +*/ +static int multiplexFileControl(sqlite3_file *pConn, int op, void *pArg){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_ERROR; + sqlite3_file *pSubOpen; + + if( !gMultiplex.isInitialized ) return SQLITE_MISUSE; + switch( op ){ + case MULTIPLEX_CTRL_ENABLE: + if( pArg ) { + int bEnabled = *(int *)pArg; + pGroup->bEnabled = bEnabled; + rc = SQLITE_OK; + } + break; + case MULTIPLEX_CTRL_SET_CHUNK_SIZE: + if( pArg ) { + unsigned int szChunk = *(unsigned*)pArg; + if( szChunk<1 ){ + rc = SQLITE_MISUSE; + }else{ + /* Round up to nearest multiple of MAX_PAGE_SIZE. */ + szChunk = (szChunk + (MAX_PAGE_SIZE-1)); + szChunk &= ~(MAX_PAGE_SIZE-1); + pGroup->szChunk = szChunk; + rc = SQLITE_OK; + } + } + break; + case MULTIPLEX_CTRL_SET_MAX_CHUNKS: + rc = SQLITE_OK; + break; + case SQLITE_FCNTL_SIZE_HINT: + case SQLITE_FCNTL_CHUNK_SIZE: + /* no-op these */ + rc = SQLITE_OK; + break; + default: + pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + rc = pSubOpen->pMethods->xFileControl(pSubOpen, op, pArg); + if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){ + *(char**)pArg = sqlite3_mprintf("multiplex/%z", *(char**)pArg); + } + } + break; + } + return rc; +} + +/* Pass xSectorSize requests through to the original VFS unchanged. +*/ +static int multiplexSectorSize(sqlite3_file *pConn){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen && pSubOpen->pMethods->xSectorSize ){ + return pSubOpen->pMethods->xSectorSize(pSubOpen); + } + return DEFAULT_SECTOR_SIZE; +} + +/* Pass xDeviceCharacteristics requests through to the original VFS unchanged. +*/ +static int multiplexDeviceCharacteristics(sqlite3_file *pConn){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xDeviceCharacteristics(pSubOpen); + } + return 0; +} + +/* Pass xShmMap requests through to the original VFS unchanged. +*/ +static int multiplexShmMap( + sqlite3_file *pConn, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int szRegion, /* Size of regions */ + int bExtend, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xShmMap(pSubOpen, iRegion, szRegion, bExtend,pp); + } + return SQLITE_IOERR; +} + +/* Pass xShmLock requests through to the original VFS unchanged. +*/ +static int multiplexShmLock( + sqlite3_file *pConn, /* Database file holding the shared memory */ + int ofst, /* First lock to acquire or release */ + int n, /* Number of locks to acquire or release */ + int flags /* What to do with the lock */ +){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xShmLock(pSubOpen, ofst, n, flags); + } + return SQLITE_BUSY; +} + +/* Pass xShmBarrier requests through to the original VFS unchanged. +*/ +static void multiplexShmBarrier(sqlite3_file *pConn){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + pSubOpen->pMethods->xShmBarrier(pSubOpen); + } +} + +/* Pass xShmUnmap requests through to the original VFS unchanged. +*/ +static int multiplexShmUnmap(sqlite3_file *pConn, int deleteFlag){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xShmUnmap(pSubOpen, deleteFlag); + } + return SQLITE_OK; +} + +/************************** Public Interfaces *****************************/ +/* +** CAPI: Initialize the multiplex VFS shim - sqlite3_multiplex_initialize() +** +** Use the VFS named zOrigVfsName as the VFS that does the actual work. +** Use the default if zOrigVfsName==NULL. +** +** The multiplex VFS shim is named "multiplex". It will become the default +** VFS if makeDefault is non-zero. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once +** during start-up. +*/ +int sqlite3_multiplex_initialize(const char *zOrigVfsName, int makeDefault){ + sqlite3_vfs *pOrigVfs; + if( gMultiplex.isInitialized ) return SQLITE_MISUSE; + pOrigVfs = sqlite3_vfs_find(zOrigVfsName); + if( pOrigVfs==0 ) return SQLITE_ERROR; + assert( pOrigVfs!=&gMultiplex.sThisVfs ); + gMultiplex.pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( !gMultiplex.pMutex ){ + return SQLITE_NOMEM; + } + gMultiplex.pGroups = NULL; + gMultiplex.isInitialized = 1; + gMultiplex.pOrigVfs = pOrigVfs; + gMultiplex.sThisVfs = *pOrigVfs; + gMultiplex.sThisVfs.szOsFile += sizeof(multiplexConn); + gMultiplex.sThisVfs.zName = SQLITE_MULTIPLEX_VFS_NAME; + gMultiplex.sThisVfs.xOpen = multiplexOpen; + gMultiplex.sThisVfs.xDelete = multiplexDelete; + gMultiplex.sThisVfs.xAccess = multiplexAccess; + gMultiplex.sThisVfs.xFullPathname = multiplexFullPathname; + gMultiplex.sThisVfs.xDlOpen = multiplexDlOpen; + gMultiplex.sThisVfs.xDlError = multiplexDlError; + gMultiplex.sThisVfs.xDlSym = multiplexDlSym; + gMultiplex.sThisVfs.xDlClose = multiplexDlClose; + gMultiplex.sThisVfs.xRandomness = multiplexRandomness; + gMultiplex.sThisVfs.xSleep = multiplexSleep; + gMultiplex.sThisVfs.xCurrentTime = multiplexCurrentTime; + gMultiplex.sThisVfs.xGetLastError = multiplexGetLastError; + gMultiplex.sThisVfs.xCurrentTimeInt64 = multiplexCurrentTimeInt64; + + gMultiplex.sIoMethodsV1.iVersion = 1; + gMultiplex.sIoMethodsV1.xClose = multiplexClose; + gMultiplex.sIoMethodsV1.xRead = multiplexRead; + gMultiplex.sIoMethodsV1.xWrite = multiplexWrite; + gMultiplex.sIoMethodsV1.xTruncate = multiplexTruncate; + gMultiplex.sIoMethodsV1.xSync = multiplexSync; + gMultiplex.sIoMethodsV1.xFileSize = multiplexFileSize; + gMultiplex.sIoMethodsV1.xLock = multiplexLock; + gMultiplex.sIoMethodsV1.xUnlock = multiplexUnlock; + gMultiplex.sIoMethodsV1.xCheckReservedLock = multiplexCheckReservedLock; + gMultiplex.sIoMethodsV1.xFileControl = multiplexFileControl; + gMultiplex.sIoMethodsV1.xSectorSize = multiplexSectorSize; + gMultiplex.sIoMethodsV1.xDeviceCharacteristics = + multiplexDeviceCharacteristics; + gMultiplex.sIoMethodsV2 = gMultiplex.sIoMethodsV1; + gMultiplex.sIoMethodsV2.iVersion = 2; + gMultiplex.sIoMethodsV2.xShmMap = multiplexShmMap; + gMultiplex.sIoMethodsV2.xShmLock = multiplexShmLock; + gMultiplex.sIoMethodsV2.xShmBarrier = multiplexShmBarrier; + gMultiplex.sIoMethodsV2.xShmUnmap = multiplexShmUnmap; + sqlite3_vfs_register(&gMultiplex.sThisVfs, makeDefault); + + sqlite3_auto_extension((void*)multiplexFuncInit); + + return SQLITE_OK; +} + +/* +** CAPI: Shutdown the multiplex system - sqlite3_multiplex_shutdown() +** +** All SQLite database connections must be closed before calling this +** routine. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once while +** shutting down in order to free all remaining multiplex groups. +*/ +int sqlite3_multiplex_shutdown(void){ + if( gMultiplex.isInitialized==0 ) return SQLITE_MISUSE; + if( gMultiplex.pGroups ) return SQLITE_MISUSE; + gMultiplex.isInitialized = 0; + sqlite3_mutex_free(gMultiplex.pMutex); + sqlite3_vfs_unregister(&gMultiplex.sThisVfs); + memset(&gMultiplex, 0, sizeof(gMultiplex)); + return SQLITE_OK; +} + +/***************************** Test Code ***********************************/ +#ifdef SQLITE_TEST +#include +extern const char *sqlite3ErrName(int); + + +/* +** tclcmd: sqlite3_multiplex_initialize NAME MAKEDEFAULT +*/ +static int test_multiplex_initialize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zName; /* Name of new multiplex VFS */ + int makeDefault; /* True to make the new VFS the default */ + int rc; /* Value returned by multiplex_initialize() */ + + UNUSED_PARAMETER(clientData); + + /* Process arguments */ + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "NAME MAKEDEFAULT"); + return TCL_ERROR; + } + zName = Tcl_GetString(objv[1]); + if( Tcl_GetBooleanFromObj(interp, objv[2], &makeDefault) ) return TCL_ERROR; + if( zName[0]=='\0' ) zName = 0; + + /* Call sqlite3_multiplex_initialize() */ + rc = sqlite3_multiplex_initialize(zName, makeDefault); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + + return TCL_OK; +} + +/* +** tclcmd: sqlite3_multiplex_shutdown +*/ +static int test_multiplex_shutdown( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; /* Value returned by multiplex_shutdown() */ + + UNUSED_PARAMETER(clientData); + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + /* Call sqlite3_multiplex_shutdown() */ + rc = sqlite3_multiplex_shutdown(); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + + return TCL_OK; +} + +/* +** tclcmd: sqlite3_multiplex_dump +*/ +static int test_multiplex_dump( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Obj *pResult; + Tcl_Obj *pGroupTerm; + multiplexGroup *pGroup; + int i; + int nChunks = 0; + + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); + + pResult = Tcl_NewObj(); + multiplexEnter(); + for(pGroup=gMultiplex.pGroups; pGroup; pGroup=pGroup->pNext){ + pGroupTerm = Tcl_NewObj(); + + if( pGroup->zName ){ + pGroup->zName[pGroup->nName] = '\0'; + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewStringObj(pGroup->zName, -1)); + }else{ + Tcl_ListObjAppendElement(interp, pGroupTerm, Tcl_NewObj()); + } + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(pGroup->nName)); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(pGroup->flags)); + + /* count number of chunks with open handles */ + for(i=0; inReal; i++){ + if( pGroup->aReal[i].p!=0 ) nChunks++; + } + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(nChunks)); + + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(pGroup->szChunk)); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(pGroup->nReal)); + + Tcl_ListObjAppendElement(interp, pResult, pGroupTerm); + } + multiplexLeave(); + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + +/* +** Tclcmd: test_multiplex_control HANDLE DBNAME SUB-COMMAND ?INT-VALUE? +*/ +static int test_multiplex_control( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; /* Return code from file_control() */ + int idx; /* Index in aSub[] */ + Tcl_CmdInfo cmdInfo; /* Command info structure for HANDLE */ + sqlite3 *db; /* Underlying db handle for HANDLE */ + int iValue = 0; + void *pArg = 0; + + struct SubCommand { + const char *zName; + int op; + int argtype; + } aSub[] = { + { "enable", MULTIPLEX_CTRL_ENABLE, 1 }, + { "chunk_size", MULTIPLEX_CTRL_SET_CHUNK_SIZE, 1 }, + { "max_chunks", MULTIPLEX_CTRL_SET_MAX_CHUNKS, 1 }, + { 0, 0, 0 } + }; + + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE DBNAME SUB-COMMAND INT-VALUE"); + return TCL_ERROR; + } + + if( 0==Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){ + Tcl_AppendResult(interp, "expected database handle, got \"", 0); + Tcl_AppendResult(interp, Tcl_GetString(objv[1]), "\"", 0); + return TCL_ERROR; + }else{ + db = *(sqlite3 **)cmdInfo.objClientData; + } + + rc = Tcl_GetIndexFromObjStruct( + interp, objv[3], aSub, sizeof(aSub[0]), "sub-command", 0, &idx + ); + if( rc!=TCL_OK ) return rc; + + switch( aSub[idx].argtype ){ + case 1: + if( Tcl_GetIntFromObj(interp, objv[4], &iValue) ){ + return TCL_ERROR; + } + pArg = (void *)&iValue; + break; + default: + Tcl_WrongNumArgs(interp, 4, objv, "SUB-COMMAND"); + return TCL_ERROR; + } + + rc = sqlite3_file_control(db, Tcl_GetString(objv[2]), aSub[idx].op, pArg); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + return (rc==SQLITE_OK) ? TCL_OK : TCL_ERROR; +} + +/* +** This routine registers the custom TCL commands defined in this +** module. This should be the only procedure visible from outside +** of this module. +*/ +int Sqlitemultiplex_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aCmd[] = { + { "sqlite3_multiplex_initialize", test_multiplex_initialize }, + { "sqlite3_multiplex_shutdown", test_multiplex_shutdown }, + { "sqlite3_multiplex_dump", test_multiplex_dump }, + { "sqlite3_multiplex_control", test_multiplex_control }, + }; + int i; + + for(i=0; i,); +** +** =1 MULTIPLEX_CTRL_ENABLE +** =0 disable +** =1 enable +** +** =2 MULTIPLEX_CTRL_SET_CHUNK_SIZE +** int, chunk size +** +** =3 MULTIPLEX_CTRL_SET_MAX_CHUNKS +** int, max chunks +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once +** during start-up. +*/ +extern int sqlite3_multiplex_initialize(const char *zOrigVfsName, int makeDefault); + +/* +** CAPI: Shutdown the multiplex system - sqlite3_multiplex_shutdown() +** +** All SQLite database connections must be closed before calling this +** routine. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once while +** shutting down in order to free all remaining multiplex groups. +*/ +extern int sqlite3_multiplex_shutdown(void); + +#ifdef __cplusplus +} /* End of the 'extern "C"' block */ +#endif + +#endif /* _TEST_MULTIPLEX_H */ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_mutex.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_mutex.c new file mode 100644 index 0000000000000000000000000000000000000000..c9b4a29ab75c77ea5f36b5193256d70fe6580e95 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_mutex.c @@ -0,0 +1,439 @@ +/* +** 2008 June 18 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains test logic for the sqlite3_mutex interfaces. +*/ + +#include "tcl.h" +#include "sqlite3.h" +#include "sqliteInt.h" +#include +#include +#include + +/* defined in main.c */ +extern const char *sqlite3ErrName(int); + +/* A countable mutex */ +struct sqlite3_mutex { + sqlite3_mutex *pReal; + int eType; +}; + +/* State variables */ +static struct test_mutex_globals { + int isInstalled; /* True if installed */ + int disableInit; /* True to cause sqlite3_initalize() to fail */ + int disableTry; /* True to force sqlite3_mutex_try() to fail */ + int isInit; /* True if initialized */ + sqlite3_mutex_methods m; /* Interface to "real" mutex system */ + int aCounter[8]; /* Number of grabs of each type of mutex */ + sqlite3_mutex aStatic[6]; /* The six static mutexes */ +} g = {0}; + +/* Return true if the countable mutex is currently held */ +static int counterMutexHeld(sqlite3_mutex *p){ + return g.m.xMutexHeld(p->pReal); +} + +/* Return true if the countable mutex is not currently held */ +static int counterMutexNotheld(sqlite3_mutex *p){ + return g.m.xMutexNotheld(p->pReal); +} + +/* Initialize the countable mutex interface +** Or, if g.disableInit is non-zero, then do not initialize but instead +** return the value of g.disableInit as the result code. This can be used +** to simulate an initialization failure. +*/ +static int counterMutexInit(void){ + int rc; + if( g.disableInit ) return g.disableInit; + rc = g.m.xMutexInit(); + g.isInit = 1; + return rc; +} + +/* +** Uninitialize the mutex subsystem +*/ +static int counterMutexEnd(void){ + g.isInit = 0; + return g.m.xMutexEnd(); +} + +/* +** Allocate a countable mutex +*/ +static sqlite3_mutex *counterMutexAlloc(int eType){ + sqlite3_mutex *pReal; + sqlite3_mutex *pRet = 0; + + assert( g.isInit ); + assert(eType<8 && eType>=0); + + pReal = g.m.xMutexAlloc(eType); + if( !pReal ) return 0; + + if( eType==SQLITE_MUTEX_FAST || eType==SQLITE_MUTEX_RECURSIVE ){ + pRet = (sqlite3_mutex *)malloc(sizeof(sqlite3_mutex)); + }else{ + pRet = &g.aStatic[eType-2]; + } + + pRet->eType = eType; + pRet->pReal = pReal; + return pRet; +} + +/* +** Free a countable mutex +*/ +static void counterMutexFree(sqlite3_mutex *p){ + assert( g.isInit ); + g.m.xMutexFree(p->pReal); + if( p->eType==SQLITE_MUTEX_FAST || p->eType==SQLITE_MUTEX_RECURSIVE ){ + free(p); + } +} + +/* +** Enter a countable mutex. Block until entry is safe. +*/ +static void counterMutexEnter(sqlite3_mutex *p){ + assert( g.isInit ); + g.aCounter[p->eType]++; + g.m.xMutexEnter(p->pReal); +} + +/* +** Try to enter a mutex. Return true on success. +*/ +static int counterMutexTry(sqlite3_mutex *p){ + assert( g.isInit ); + g.aCounter[p->eType]++; + if( g.disableTry ) return SQLITE_BUSY; + return g.m.xMutexTry(p->pReal); +} + +/* Leave a mutex +*/ +static void counterMutexLeave(sqlite3_mutex *p){ + assert( g.isInit ); + g.m.xMutexLeave(p->pReal); +} + +/* +** sqlite3_shutdown +*/ +static int test_shutdown( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + rc = sqlite3_shutdown(); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** sqlite3_initialize +*/ +static int test_initialize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + rc = sqlite3_initialize(); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** install_mutex_counters BOOLEAN +*/ +static int test_install_mutex_counters( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = SQLITE_OK; + int isInstall; + + sqlite3_mutex_methods counter_methods = { + counterMutexInit, + counterMutexEnd, + counterMutexAlloc, + counterMutexFree, + counterMutexEnter, + counterMutexTry, + counterMutexLeave, + counterMutexHeld, + counterMutexNotheld + }; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN"); + return TCL_ERROR; + } + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[1], &isInstall) ){ + return TCL_ERROR; + } + + assert(isInstall==0 || isInstall==1); + assert(g.isInstalled==0 || g.isInstalled==1); + if( isInstall==g.isInstalled ){ + Tcl_AppendResult(interp, "mutex counters are ", 0); + Tcl_AppendResult(interp, isInstall?"already installed":"not installed", 0); + return TCL_ERROR; + } + + if( isInstall ){ + assert( g.m.xMutexAlloc==0 ); + rc = sqlite3_config(SQLITE_CONFIG_GETMUTEX, &g.m); + if( rc==SQLITE_OK ){ + sqlite3_config(SQLITE_CONFIG_MUTEX, &counter_methods); + } + g.disableTry = 0; + }else{ + assert( g.m.xMutexAlloc ); + rc = sqlite3_config(SQLITE_CONFIG_MUTEX, &g.m); + memset(&g.m, 0, sizeof(sqlite3_mutex_methods)); + } + + if( rc==SQLITE_OK ){ + g.isInstalled = isInstall; + } + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** read_mutex_counters +*/ +static int test_read_mutex_counters( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Obj *pRet; + int ii; + char *aName[8] = { + "fast", "recursive", "static_master", "static_mem", + "static_open", "static_prng", "static_lru", "static_pmem" + }; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + pRet = Tcl_NewObj(); + Tcl_IncrRefCount(pRet); + for(ii=0; ii<8; ii++){ + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(aName[ii], -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(g.aCounter[ii])); + } + Tcl_SetObjResult(interp, pRet); + Tcl_DecrRefCount(pRet); + + return TCL_OK; +} + +/* +** clear_mutex_counters +*/ +static int test_clear_mutex_counters( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int ii; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + for(ii=0; ii<8; ii++){ + g.aCounter[ii] = 0; + } + return TCL_OK; +} + +/* +** Create and free a mutex. Return the mutex pointer. The pointer +** will be invalid since the mutex has already been freed. The +** return pointer just checks to see if the mutex really was allocated. +*/ +static int test_alloc_mutex( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#if SQLITE_THREADSAFE + sqlite3_mutex *p = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + char zBuf[100]; + sqlite3_mutex_free(p); + sqlite3_snprintf(sizeof(zBuf), zBuf, "%p", p); + Tcl_AppendResult(interp, zBuf, (char*)0); +#endif + return TCL_OK; +} + +/* +** sqlite3_config OPTION +** +** OPTION can be either one of the keywords: +** +** SQLITE_CONFIG_SINGLETHREAD +** SQLITE_CONFIG_MULTITHREAD +** SQLITE_CONFIG_SERIALIZED +** +** Or OPTION can be an raw integer. +*/ +static int test_config( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct ConfigOption { + const char *zName; + int iValue; + } aOpt[] = { + {"singlethread", SQLITE_CONFIG_SINGLETHREAD}, + {"multithread", SQLITE_CONFIG_MULTITHREAD}, + {"serialized", SQLITE_CONFIG_SERIALIZED}, + {0, 0} + }; + int s = sizeof(struct ConfigOption); + int i; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + if( Tcl_GetIndexFromObjStruct(interp, objv[1], aOpt, s, "flag", 0, &i) ){ + if( Tcl_GetIntFromObj(interp, objv[1], &i) ){ + return TCL_ERROR; + } + }else{ + i = aOpt[i].iValue; + } + + rc = sqlite3_config(i); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +static sqlite3 *getDbPointer(Tcl_Interp *pInterp, Tcl_Obj *pObj){ + sqlite3 *db; + Tcl_CmdInfo info; + char *zCmd = Tcl_GetString(pObj); + if( Tcl_GetCommandInfo(pInterp, zCmd, &info) ){ + db = *((sqlite3 **)info.objClientData); + }else{ + db = (sqlite3*)sqlite3TestTextToPtr(zCmd); + } + assert( db ); + return db; +} + +static int test_enter_db_mutex( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + db = getDbPointer(interp, objv[1]); + if( !db ){ + return TCL_ERROR; + } + sqlite3_mutex_enter(sqlite3_db_mutex(db)); + return TCL_OK; +} + +static int test_leave_db_mutex( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + db = getDbPointer(interp, objv[1]); + if( !db ){ + return TCL_ERROR; + } + sqlite3_mutex_leave(sqlite3_db_mutex(db)); + return TCL_OK; +} + +int Sqlitetest_mutex_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aCmd[] = { + { "sqlite3_shutdown", (Tcl_ObjCmdProc*)test_shutdown }, + { "sqlite3_initialize", (Tcl_ObjCmdProc*)test_initialize }, + { "sqlite3_config", (Tcl_ObjCmdProc*)test_config }, + + { "enter_db_mutex", (Tcl_ObjCmdProc*)test_enter_db_mutex }, + { "leave_db_mutex", (Tcl_ObjCmdProc*)test_leave_db_mutex }, + + { "alloc_dealloc_mutex", (Tcl_ObjCmdProc*)test_alloc_mutex }, + { "install_mutex_counters", (Tcl_ObjCmdProc*)test_install_mutex_counters }, + { "read_mutex_counters", (Tcl_ObjCmdProc*)test_read_mutex_counters }, + { "clear_mutex_counters", (Tcl_ObjCmdProc*)test_clear_mutex_counters }, + }; + int i; + for(i=0; i +#include + +/* +** Maximum pathname length supported by the fs backend. +*/ +#define BLOCKSIZE 512 +#define BLOBSIZE 10485760 + +/* +** Name used to identify this VFS. +*/ +#define FS_VFS_NAME "fs" + +typedef struct fs_real_file fs_real_file; +struct fs_real_file { + sqlite3_file *pFile; + const char *zName; + int nDatabase; /* Current size of database region */ + int nJournal; /* Current size of journal region */ + int nBlob; /* Total size of allocated blob */ + int nRef; /* Number of pointers to this structure */ + fs_real_file *pNext; + fs_real_file **ppThis; +}; + +typedef struct fs_file fs_file; +struct fs_file { + sqlite3_file base; + int eType; + fs_real_file *pReal; +}; + +typedef struct tmp_file tmp_file; +struct tmp_file { + sqlite3_file base; + int nSize; + int nAlloc; + char *zAlloc; +}; + +/* Values for fs_file.eType. */ +#define DATABASE_FILE 1 +#define JOURNAL_FILE 2 + +/* +** Method declarations for fs_file. +*/ +static int fsClose(sqlite3_file*); +static int fsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int fsWrite(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); +static int fsTruncate(sqlite3_file*, sqlite3_int64 size); +static int fsSync(sqlite3_file*, int flags); +static int fsFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int fsLock(sqlite3_file*, int); +static int fsUnlock(sqlite3_file*, int); +static int fsCheckReservedLock(sqlite3_file*, int *pResOut); +static int fsFileControl(sqlite3_file*, int op, void *pArg); +static int fsSectorSize(sqlite3_file*); +static int fsDeviceCharacteristics(sqlite3_file*); + +/* +** Method declarations for tmp_file. +*/ +static int tmpClose(sqlite3_file*); +static int tmpRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int tmpWrite(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); +static int tmpTruncate(sqlite3_file*, sqlite3_int64 size); +static int tmpSync(sqlite3_file*, int flags); +static int tmpFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int tmpLock(sqlite3_file*, int); +static int tmpUnlock(sqlite3_file*, int); +static int tmpCheckReservedLock(sqlite3_file*, int *pResOut); +static int tmpFileControl(sqlite3_file*, int op, void *pArg); +static int tmpSectorSize(sqlite3_file*); +static int tmpDeviceCharacteristics(sqlite3_file*); + +/* +** Method declarations for fs_vfs. +*/ +static int fsOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int fsDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int fsAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int fsFullPathname(sqlite3_vfs*, const char *zName, int nOut,char *zOut); +static void *fsDlOpen(sqlite3_vfs*, const char *zFilename); +static void fsDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*fsDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void); +static void fsDlClose(sqlite3_vfs*, void*); +static int fsRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int fsSleep(sqlite3_vfs*, int microseconds); +static int fsCurrentTime(sqlite3_vfs*, double*); + + +typedef struct fs_vfs_t fs_vfs_t; +struct fs_vfs_t { + sqlite3_vfs base; + fs_real_file *pFileList; + sqlite3_vfs *pParent; +}; + +static fs_vfs_t fs_vfs = { + { + 1, /* iVersion */ + 0, /* szOsFile */ + 0, /* mxPathname */ + 0, /* pNext */ + FS_VFS_NAME, /* zName */ + 0, /* pAppData */ + fsOpen, /* xOpen */ + fsDelete, /* xDelete */ + fsAccess, /* xAccess */ + fsFullPathname, /* xFullPathname */ + fsDlOpen, /* xDlOpen */ + fsDlError, /* xDlError */ + fsDlSym, /* xDlSym */ + fsDlClose, /* xDlClose */ + fsRandomness, /* xRandomness */ + fsSleep, /* xSleep */ + fsCurrentTime, /* xCurrentTime */ + 0 /* xCurrentTimeInt64 */ + }, + 0, /* pFileList */ + 0 /* pParent */ +}; + +static sqlite3_io_methods fs_io_methods = { + 1, /* iVersion */ + fsClose, /* xClose */ + fsRead, /* xRead */ + fsWrite, /* xWrite */ + fsTruncate, /* xTruncate */ + fsSync, /* xSync */ + fsFileSize, /* xFileSize */ + fsLock, /* xLock */ + fsUnlock, /* xUnlock */ + fsCheckReservedLock, /* xCheckReservedLock */ + fsFileControl, /* xFileControl */ + fsSectorSize, /* xSectorSize */ + fsDeviceCharacteristics, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0 /* xShmUnmap */ +}; + + +static sqlite3_io_methods tmp_io_methods = { + 1, /* iVersion */ + tmpClose, /* xClose */ + tmpRead, /* xRead */ + tmpWrite, /* xWrite */ + tmpTruncate, /* xTruncate */ + tmpSync, /* xSync */ + tmpFileSize, /* xFileSize */ + tmpLock, /* xLock */ + tmpUnlock, /* xUnlock */ + tmpCheckReservedLock, /* xCheckReservedLock */ + tmpFileControl, /* xFileControl */ + tmpSectorSize, /* xSectorSize */ + tmpDeviceCharacteristics, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0 /* xShmUnmap */ +}; + +/* Useful macros used in several places */ +#define MIN(x,y) ((x)<(y)?(x):(y)) +#define MAX(x,y) ((x)>(y)?(x):(y)) + + +/* +** Close a tmp-file. +*/ +static int tmpClose(sqlite3_file *pFile){ + tmp_file *pTmp = (tmp_file *)pFile; + sqlite3_free(pTmp->zAlloc); + return SQLITE_OK; +} + +/* +** Read data from a tmp-file. +*/ +static int tmpRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + tmp_file *pTmp = (tmp_file *)pFile; + if( (iAmt+iOfst)>pTmp->nSize ){ + return SQLITE_IOERR_SHORT_READ; + } + memcpy(zBuf, &pTmp->zAlloc[iOfst], iAmt); + return SQLITE_OK; +} + +/* +** Write data to a tmp-file. +*/ +static int tmpWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + tmp_file *pTmp = (tmp_file *)pFile; + if( (iAmt+iOfst)>pTmp->nAlloc ){ + int nNew = (int)(2*(iAmt+iOfst+pTmp->nAlloc)); + char *zNew = sqlite3_realloc(pTmp->zAlloc, nNew); + if( !zNew ){ + return SQLITE_NOMEM; + } + pTmp->zAlloc = zNew; + pTmp->nAlloc = nNew; + } + memcpy(&pTmp->zAlloc[iOfst], zBuf, iAmt); + pTmp->nSize = (int)MAX(pTmp->nSize, iOfst+iAmt); + return SQLITE_OK; +} + +/* +** Truncate a tmp-file. +*/ +static int tmpTruncate(sqlite3_file *pFile, sqlite_int64 size){ + tmp_file *pTmp = (tmp_file *)pFile; + pTmp->nSize = (int)MIN(pTmp->nSize, size); + return SQLITE_OK; +} + +/* +** Sync a tmp-file. +*/ +static int tmpSync(sqlite3_file *pFile, int flags){ + return SQLITE_OK; +} + +/* +** Return the current file-size of a tmp-file. +*/ +static int tmpFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + tmp_file *pTmp = (tmp_file *)pFile; + *pSize = pTmp->nSize; + return SQLITE_OK; +} + +/* +** Lock a tmp-file. +*/ +static int tmpLock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} + +/* +** Unlock a tmp-file. +*/ +static int tmpUnlock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} + +/* +** Check if another file-handle holds a RESERVED lock on a tmp-file. +*/ +static int tmpCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + *pResOut = 0; + return SQLITE_OK; +} + +/* +** File control method. For custom operations on a tmp-file. +*/ +static int tmpFileControl(sqlite3_file *pFile, int op, void *pArg){ + return SQLITE_OK; +} + +/* +** Return the sector-size in bytes for a tmp-file. +*/ +static int tmpSectorSize(sqlite3_file *pFile){ + return 0; +} + +/* +** Return the device characteristic flags supported by a tmp-file. +*/ +static int tmpDeviceCharacteristics(sqlite3_file *pFile){ + return 0; +} + +/* +** Close an fs-file. +*/ +static int fsClose(sqlite3_file *pFile){ + int rc = SQLITE_OK; + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + + /* Decrement the real_file ref-count. */ + pReal->nRef--; + assert(pReal->nRef>=0); + + /* When the ref-count reaches 0, destroy the structure */ + if( pReal->nRef==0 ){ + *pReal->ppThis = pReal->pNext; + if( pReal->pNext ){ + pReal->pNext->ppThis = pReal->ppThis; + } + rc = pReal->pFile->pMethods->xClose(pReal->pFile); + sqlite3_free(pReal); + } + + return rc; +} + +/* +** Read data from an fs-file. +*/ +static int fsRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc = SQLITE_OK; + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + sqlite3_file *pF = pReal->pFile; + + if( (p->eType==DATABASE_FILE && (iAmt+iOfst)>pReal->nDatabase) + || (p->eType==JOURNAL_FILE && (iAmt+iOfst)>pReal->nJournal) + ){ + rc = SQLITE_IOERR_SHORT_READ; + }else if( p->eType==DATABASE_FILE ){ + rc = pF->pMethods->xRead(pF, zBuf, iAmt, iOfst+BLOCKSIZE); + }else{ + /* Journal file. */ + int iRem = iAmt; + int iBuf = 0; + int ii = (int)iOfst; + while( iRem>0 && rc==SQLITE_OK ){ + int iRealOff = pReal->nBlob - BLOCKSIZE*((ii/BLOCKSIZE)+1) + ii%BLOCKSIZE; + int iRealAmt = MIN(iRem, BLOCKSIZE - (iRealOff%BLOCKSIZE)); + + rc = pF->pMethods->xRead(pF, &((char *)zBuf)[iBuf], iRealAmt, iRealOff); + ii += iRealAmt; + iBuf += iRealAmt; + iRem -= iRealAmt; + } + } + + return rc; +} + +/* +** Write data to an fs-file. +*/ +static int fsWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc = SQLITE_OK; + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + sqlite3_file *pF = pReal->pFile; + + if( p->eType==DATABASE_FILE ){ + if( (iAmt+iOfst+BLOCKSIZE)>(pReal->nBlob-pReal->nJournal) ){ + rc = SQLITE_FULL; + }else{ + rc = pF->pMethods->xWrite(pF, zBuf, iAmt, iOfst+BLOCKSIZE); + if( rc==SQLITE_OK ){ + pReal->nDatabase = (int)MAX(pReal->nDatabase, iAmt+iOfst); + } + } + }else{ + /* Journal file. */ + int iRem = iAmt; + int iBuf = 0; + int ii = (int)iOfst; + while( iRem>0 && rc==SQLITE_OK ){ + int iRealOff = pReal->nBlob - BLOCKSIZE*((ii/BLOCKSIZE)+1) + ii%BLOCKSIZE; + int iRealAmt = MIN(iRem, BLOCKSIZE - (iRealOff%BLOCKSIZE)); + + if( iRealOff<(pReal->nDatabase+BLOCKSIZE) ){ + rc = SQLITE_FULL; + }else{ + rc = pF->pMethods->xWrite(pF, &((char *)zBuf)[iBuf], iRealAmt,iRealOff); + ii += iRealAmt; + iBuf += iRealAmt; + iRem -= iRealAmt; + } + } + if( rc==SQLITE_OK ){ + pReal->nJournal = (int)MAX(pReal->nJournal, iAmt+iOfst); + } + } + + return rc; +} + +/* +** Truncate an fs-file. +*/ +static int fsTruncate(sqlite3_file *pFile, sqlite_int64 size){ + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + if( p->eType==DATABASE_FILE ){ + pReal->nDatabase = (int)MIN(pReal->nDatabase, size); + }else{ + pReal->nJournal = (int)MIN(pReal->nJournal, size); + } + return SQLITE_OK; +} + +/* +** Sync an fs-file. +*/ +static int fsSync(sqlite3_file *pFile, int flags){ + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + sqlite3_file *pRealFile = pReal->pFile; + int rc = SQLITE_OK; + + if( p->eType==DATABASE_FILE ){ + unsigned char zSize[4]; + zSize[0] = (pReal->nDatabase&0xFF000000)>>24; + zSize[1] = (pReal->nDatabase&0x00FF0000)>>16; + zSize[2] = (pReal->nDatabase&0x0000FF00)>>8; + zSize[3] = (pReal->nDatabase&0x000000FF); + rc = pRealFile->pMethods->xWrite(pRealFile, zSize, 4, 0); + } + if( rc==SQLITE_OK ){ + rc = pRealFile->pMethods->xSync(pRealFile, flags&(~SQLITE_SYNC_DATAONLY)); + } + + return rc; +} + +/* +** Return the current file-size of an fs-file. +*/ +static int fsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + if( p->eType==DATABASE_FILE ){ + *pSize = pReal->nDatabase; + }else{ + *pSize = pReal->nJournal; + } + return SQLITE_OK; +} + +/* +** Lock an fs-file. +*/ +static int fsLock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} + +/* +** Unlock an fs-file. +*/ +static int fsUnlock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} + +/* +** Check if another file-handle holds a RESERVED lock on an fs-file. +*/ +static int fsCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + *pResOut = 0; + return SQLITE_OK; +} + +/* +** File control method. For custom operations on an fs-file. +*/ +static int fsFileControl(sqlite3_file *pFile, int op, void *pArg){ + return SQLITE_OK; +} + +/* +** Return the sector-size in bytes for an fs-file. +*/ +static int fsSectorSize(sqlite3_file *pFile){ + return BLOCKSIZE; +} + +/* +** Return the device characteristic flags supported by an fs-file. +*/ +static int fsDeviceCharacteristics(sqlite3_file *pFile){ + return 0; +} + +/* +** Open an fs file handle. +*/ +static int fsOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + fs_vfs_t *pFsVfs = (fs_vfs_t *)pVfs; + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = 0; + int eType; + int nName; + int rc = SQLITE_OK; + + if( 0==(flags&(SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_MAIN_JOURNAL)) ){ + tmp_file *p = (tmp_file *)pFile; + memset(p, 0, sizeof(*p)); + p->base.pMethods = &tmp_io_methods; + return SQLITE_OK; + } + + eType = ((flags&(SQLITE_OPEN_MAIN_DB))?DATABASE_FILE:JOURNAL_FILE); + p->base.pMethods = &fs_io_methods; + p->eType = eType; + + assert(strlen("-journal")==8); + nName = (int)strlen(zName)-((eType==JOURNAL_FILE)?8:0); + pReal=pFsVfs->pFileList; + for(; pReal && strncmp(pReal->zName, zName, nName); pReal=pReal->pNext); + + if( !pReal ){ + int real_flags = (flags&~(SQLITE_OPEN_MAIN_DB))|SQLITE_OPEN_TEMP_DB; + sqlite3_int64 size; + sqlite3_file *pRealFile; + sqlite3_vfs *pParent = pFsVfs->pParent; + assert(eType==DATABASE_FILE); + + pReal = (fs_real_file *)sqlite3_malloc(sizeof(*pReal)+pParent->szOsFile); + if( !pReal ){ + rc = SQLITE_NOMEM; + goto open_out; + } + memset(pReal, 0, sizeof(*pReal)+pParent->szOsFile); + pReal->zName = zName; + pReal->pFile = (sqlite3_file *)(&pReal[1]); + + rc = pParent->xOpen(pParent, zName, pReal->pFile, real_flags, pOutFlags); + if( rc!=SQLITE_OK ){ + goto open_out; + } + pRealFile = pReal->pFile; + + rc = pRealFile->pMethods->xFileSize(pRealFile, &size); + if( rc!=SQLITE_OK ){ + goto open_out; + } + if( size==0 ){ + rc = pRealFile->pMethods->xWrite(pRealFile, "\0", 1, BLOBSIZE-1); + pReal->nBlob = BLOBSIZE; + }else{ + unsigned char zS[4]; + pReal->nBlob = (int)size; + rc = pRealFile->pMethods->xRead(pRealFile, zS, 4, 0); + pReal->nDatabase = (zS[0]<<24)+(zS[1]<<16)+(zS[2]<<8)+zS[3]; + if( rc==SQLITE_OK ){ + rc = pRealFile->pMethods->xRead(pRealFile, zS, 4, pReal->nBlob-4); + if( zS[0] || zS[1] || zS[2] || zS[3] ){ + pReal->nJournal = pReal->nBlob; + } + } + } + + if( rc==SQLITE_OK ){ + pReal->pNext = pFsVfs->pFileList; + if( pReal->pNext ){ + pReal->pNext->ppThis = &pReal->pNext; + } + pReal->ppThis = &pFsVfs->pFileList; + pFsVfs->pFileList = pReal; + } + } + +open_out: + if( pReal ){ + if( rc==SQLITE_OK ){ + p->pReal = pReal; + pReal->nRef++; + }else{ + if( pReal->pFile->pMethods ){ + pReal->pFile->pMethods->xClose(pReal->pFile); + } + sqlite3_free(pReal); + } + } + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int fsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc = SQLITE_OK; + fs_vfs_t *pFsVfs = (fs_vfs_t *)pVfs; + fs_real_file *pReal; + sqlite3_file *pF; + int nName = (int)strlen(zPath) - 8; + + assert(strlen("-journal")==8); + assert(strcmp("-journal", &zPath[nName])==0); + + pReal = pFsVfs->pFileList; + for(; pReal && strncmp(pReal->zName, zPath, nName); pReal=pReal->pNext); + if( pReal ){ + pF = pReal->pFile; + rc = pF->pMethods->xWrite(pF, "\0\0\0\0", 4, pReal->nBlob-BLOCKSIZE); + if( rc==SQLITE_OK ){ + pReal->nJournal = 0; + } + } + return rc; +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int fsAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + fs_vfs_t *pFsVfs = (fs_vfs_t *)pVfs; + fs_real_file *pReal; + int isJournal = 0; + int nName = (int)strlen(zPath); + + if( flags!=SQLITE_ACCESS_EXISTS ){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xAccess(pParent, zPath, flags, pResOut); + } + + assert(strlen("-journal")==8); + if( nName>8 && strcmp("-journal", &zPath[nName-8])==0 ){ + nName -= 8; + isJournal = 1; + } + + pReal = pFsVfs->pFileList; + for(; pReal && strncmp(pReal->zName, zPath, nName); pReal=pReal->pNext); + + *pResOut = (pReal && (!isJournal || pReal->nJournal>0)); + return SQLITE_OK; +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (FS_MAX_PATHNAME+1) bytes. +*/ +static int fsFullPathname( + sqlite3_vfs *pVfs, /* Pointer to vfs object */ + const char *zPath, /* Possibly relative input path */ + int nOut, /* Size of output buffer in bytes */ + char *zOut /* Output buffer */ +){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xFullPathname(pParent, zPath, nOut, zOut); +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *fsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xDlOpen(pParent, zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void fsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + pParent->xDlError(pParent, nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*fsDlSym(sqlite3_vfs *pVfs, void *pH, const char *zSym))(void){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xDlSym(pParent, pH, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void fsDlClose(sqlite3_vfs *pVfs, void *pHandle){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + pParent->xDlClose(pParent, pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int fsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xRandomness(pParent, nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int fsSleep(sqlite3_vfs *pVfs, int nMicro){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xSleep(pParent, nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int fsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xCurrentTime(pParent, pTimeOut); +} + +/* +** This procedure registers the fs vfs with SQLite. If the argument is +** true, the fs vfs becomes the new default vfs. It is the only publicly +** available function in this file. +*/ +int fs_register(void){ + if( fs_vfs.pParent ) return SQLITE_OK; + fs_vfs.pParent = sqlite3_vfs_find(0); + fs_vfs.base.mxPathname = fs_vfs.pParent->mxPathname; + fs_vfs.base.szOsFile = MAX(sizeof(tmp_file), sizeof(fs_file)); + return sqlite3_vfs_register(&fs_vfs.base, 0); +} + +#ifdef SQLITE_TEST + int SqlitetestOnefile_Init() {return fs_register();} +#endif diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_osinst.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_osinst.c new file mode 100644 index 0000000000000000000000000000000000000000..531433313ee36c07eb21c02f3115cb7a37486c79 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_osinst.c @@ -0,0 +1,1215 @@ +/* +** 2008 April 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains the implementation of an SQLite vfs wrapper that +** adds instrumentation to all vfs and file methods. C and Tcl interfaces +** are provided to control the instrumentation. +*/ + +/* +** This module contains code for a wrapper VFS that causes a log of +** most VFS calls to be written into a nominated file on disk. The log +** is stored in a compressed binary format to reduce the amount of IO +** overhead introduced into the application by logging. +** +** All calls on sqlite3_file objects except xFileControl() are logged. +** Additionally, calls to the xAccess(), xOpen(), and xDelete() +** methods are logged. The other sqlite3_vfs object methods (xDlXXX, +** xRandomness, xSleep, xCurrentTime, xGetLastError and xCurrentTimeInt64) +** are not logged. +** +** The binary log files are read using a virtual table implementation +** also contained in this file. +** +** CREATING LOG FILES: +** +** int sqlite3_vfslog_new( +** const char *zVfs, // Name of new VFS +** const char *zParentVfs, // Name of parent VFS (or NULL) +** const char *zLog // Name of log file to write to +** ); +** +** int sqlite3_vfslog_finalize(const char *zVfs); +** +** ANNOTATING LOG FILES: +** +** To write an arbitrary message into a log file: +** +** int sqlite3_vfslog_annotate(const char *zVfs, const char *zMsg); +** +** READING LOG FILES: +** +** Log files are read using the "vfslog" virtual table implementation +** in this file. To register the virtual table with SQLite, use: +** +** int sqlite3_vfslog_register(sqlite3 *db); +** +** Then, if the log file is named "vfs.log", the following SQL command: +** +** CREATE VIRTUAL TABLE v USING vfslog('vfs.log'); +** +** creates a virtual table with 6 columns, as follows: +** +** CREATE TABLE v( +** event TEXT, // "xOpen", "xRead" etc. +** file TEXT, // Name of file this call applies to +** clicks INTEGER, // Time spent in call +** rc INTEGER, // Return value +** size INTEGER, // Bytes read or written +** offset INTEGER // File offset read or written +** ); +*/ + +#include "sqlite3.h" +#include +#include + + +/* +** Maximum pathname length supported by the vfslog backend. +*/ +#define INST_MAX_PATHNAME 512 + +#define OS_ACCESS 1 +#define OS_CHECKRESERVEDLOCK 2 +#define OS_CLOSE 3 +#define OS_CURRENTTIME 4 +#define OS_DELETE 5 +#define OS_DEVCHAR 6 +#define OS_FILECONTROL 7 +#define OS_FILESIZE 8 +#define OS_FULLPATHNAME 9 +#define OS_LOCK 11 +#define OS_OPEN 12 +#define OS_RANDOMNESS 13 +#define OS_READ 14 +#define OS_SECTORSIZE 15 +#define OS_SLEEP 16 +#define OS_SYNC 17 +#define OS_TRUNCATE 18 +#define OS_UNLOCK 19 +#define OS_WRITE 20 +#define OS_SHMUNMAP 22 +#define OS_SHMMAP 23 +#define OS_SHMLOCK 25 +#define OS_SHMBARRIER 26 +#define OS_ANNOTATE 28 + +#define OS_NUMEVENTS 29 + +#define VFSLOG_BUFFERSIZE 8192 + +typedef struct VfslogVfs VfslogVfs; +typedef struct VfslogFile VfslogFile; + +struct VfslogVfs { + sqlite3_vfs base; /* VFS methods */ + sqlite3_vfs *pVfs; /* Parent VFS */ + int iNextFileId; /* Next file id */ + sqlite3_file *pLog; /* Log file handle */ + sqlite3_int64 iOffset; /* Log file offset of start of write buffer */ + int nBuf; /* Number of valid bytes in aBuf[] */ + char aBuf[VFSLOG_BUFFERSIZE]; /* Write buffer */ +}; + +struct VfslogFile { + sqlite3_file base; /* IO methods */ + sqlite3_file *pReal; /* Underlying file handle */ + sqlite3_vfs *pVfslog; /* Associated VsflogVfs object */ + int iFileId; /* File id number */ +}; + +#define REALVFS(p) (((VfslogVfs *)(p))->pVfs) + + + +/* +** Method declarations for vfslog_file. +*/ +static int vfslogClose(sqlite3_file*); +static int vfslogRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int vfslogWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); +static int vfslogTruncate(sqlite3_file*, sqlite3_int64 size); +static int vfslogSync(sqlite3_file*, int flags); +static int vfslogFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int vfslogLock(sqlite3_file*, int); +static int vfslogUnlock(sqlite3_file*, int); +static int vfslogCheckReservedLock(sqlite3_file*, int *pResOut); +static int vfslogFileControl(sqlite3_file*, int op, void *pArg); +static int vfslogSectorSize(sqlite3_file*); +static int vfslogDeviceCharacteristics(sqlite3_file*); + +static int vfslogShmLock(sqlite3_file *pFile, int ofst, int n, int flags); +static int vfslogShmMap(sqlite3_file *pFile,int,int,int,volatile void **); +static void vfslogShmBarrier(sqlite3_file*); +static int vfslogShmUnmap(sqlite3_file *pFile, int deleteFlag); + +/* +** Method declarations for vfslog_vfs. +*/ +static int vfslogOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int vfslogDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int vfslogAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int vfslogFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); +static void *vfslogDlOpen(sqlite3_vfs*, const char *zFilename); +static void vfslogDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*vfslogDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void); +static void vfslogDlClose(sqlite3_vfs*, void*); +static int vfslogRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int vfslogSleep(sqlite3_vfs*, int microseconds); +static int vfslogCurrentTime(sqlite3_vfs*, double*); + +static int vfslogGetLastError(sqlite3_vfs*, int, char *); +static int vfslogCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); + +static sqlite3_vfs vfslog_vfs = { + 1, /* iVersion */ + sizeof(VfslogFile), /* szOsFile */ + INST_MAX_PATHNAME, /* mxPathname */ + 0, /* pNext */ + 0, /* zName */ + 0, /* pAppData */ + vfslogOpen, /* xOpen */ + vfslogDelete, /* xDelete */ + vfslogAccess, /* xAccess */ + vfslogFullPathname, /* xFullPathname */ + vfslogDlOpen, /* xDlOpen */ + vfslogDlError, /* xDlError */ + vfslogDlSym, /* xDlSym */ + vfslogDlClose, /* xDlClose */ + vfslogRandomness, /* xRandomness */ + vfslogSleep, /* xSleep */ + vfslogCurrentTime, /* xCurrentTime */ + vfslogGetLastError, /* xGetLastError */ + vfslogCurrentTimeInt64 /* xCurrentTime */ +}; + +static sqlite3_io_methods vfslog_io_methods = { + 2, /* iVersion */ + vfslogClose, /* xClose */ + vfslogRead, /* xRead */ + vfslogWrite, /* xWrite */ + vfslogTruncate, /* xTruncate */ + vfslogSync, /* xSync */ + vfslogFileSize, /* xFileSize */ + vfslogLock, /* xLock */ + vfslogUnlock, /* xUnlock */ + vfslogCheckReservedLock, /* xCheckReservedLock */ + vfslogFileControl, /* xFileControl */ + vfslogSectorSize, /* xSectorSize */ + vfslogDeviceCharacteristics, /* xDeviceCharacteristics */ + vfslogShmMap, /* xShmMap */ + vfslogShmLock, /* xShmLock */ + vfslogShmBarrier, /* xShmBarrier */ + vfslogShmUnmap /* xShmUnmap */ +}; + +#if SQLITE_OS_UNIX && !defined(NO_GETTOD) +#include +static sqlite3_uint64 vfslog_time(){ + struct timeval sTime; + gettimeofday(&sTime, 0); + return sTime.tv_usec + (sqlite3_uint64)sTime.tv_sec * 1000000; +} +#elif SQLITE_OS_WIN +#include +#include +static sqlite3_uint64 vfslog_time(){ + FILETIME ft; + sqlite3_uint64 u64time = 0; + + GetSystemTimeAsFileTime(&ft); + + u64time |= ft.dwHighDateTime; + u64time <<= 32; + u64time |= ft.dwLowDateTime; + + /* ft is 100-nanosecond intervals, we want microseconds */ + return u64time /(sqlite3_uint64)10; +} +#else +static sqlite3_uint64 vfslog_time(){ + return 0; +} +#endif + +static void vfslog_call(sqlite3_vfs *, int, int, sqlite3_int64, int, int, int); +static void vfslog_string(sqlite3_vfs *, const char *); + +/* +** Close an vfslog-file. +*/ +static int vfslogClose(sqlite3_file *pFile){ + sqlite3_uint64 t; + int rc = SQLITE_OK; + VfslogFile *p = (VfslogFile *)pFile; + + t = vfslog_time(); + if( p->pReal->pMethods ){ + rc = p->pReal->pMethods->xClose(p->pReal); + } + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_CLOSE, p->iFileId, t, rc, 0, 0); + return rc; +} + +/* +** Read data from an vfslog-file. +*/ +static int vfslogRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_READ, p->iFileId, t, rc, iAmt, (int)iOfst); + return rc; +} + +/* +** Write data to an vfslog-file. +*/ +static int vfslogWrite( + sqlite3_file *pFile, + const void *z, + int iAmt, + sqlite_int64 iOfst +){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xWrite(p->pReal, z, iAmt, iOfst); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_WRITE, p->iFileId, t, rc, iAmt, (int)iOfst); + return rc; +} + +/* +** Truncate an vfslog-file. +*/ +static int vfslogTruncate(sqlite3_file *pFile, sqlite_int64 size){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xTruncate(p->pReal, size); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_TRUNCATE, p->iFileId, t, rc, 0, (int)size); + return rc; +} + +/* +** Sync an vfslog-file. +*/ +static int vfslogSync(sqlite3_file *pFile, int flags){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xSync(p->pReal, flags); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SYNC, p->iFileId, t, rc, flags, 0); + return rc; +} + +/* +** Return the current file-size of an vfslog-file. +*/ +static int vfslogFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_FILESIZE, p->iFileId, t, rc, 0, (int)*pSize); + return rc; +} + +/* +** Lock an vfslog-file. +*/ +static int vfslogLock(sqlite3_file *pFile, int eLock){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xLock(p->pReal, eLock); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_LOCK, p->iFileId, t, rc, eLock, 0); + return rc; +} + +/* +** Unlock an vfslog-file. +*/ +static int vfslogUnlock(sqlite3_file *pFile, int eLock){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xUnlock(p->pReal, eLock); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_UNLOCK, p->iFileId, t, rc, eLock, 0); + return rc; +} + +/* +** Check if another file-handle holds a RESERVED lock on an vfslog-file. +*/ +static int vfslogCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_CHECKRESERVEDLOCK, p->iFileId, t, rc, *pResOut, 0); + return rc; +} + +/* +** File control method. For custom operations on an vfslog-file. +*/ +static int vfslogFileControl(sqlite3_file *pFile, int op, void *pArg){ + VfslogFile *p = (VfslogFile *)pFile; + int rc = p->pReal->pMethods->xFileControl(p->pReal, op, pArg); + if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){ + *(char**)pArg = sqlite3_mprintf("vfslog/%z", *(char**)pArg); + } + return rc; +} + +/* +** Return the sector-size in bytes for an vfslog-file. +*/ +static int vfslogSectorSize(sqlite3_file *pFile){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xSectorSize(p->pReal); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SECTORSIZE, p->iFileId, t, rc, 0, 0); + return rc; +} + +/* +** Return the device characteristic flags supported by an vfslog-file. +*/ +static int vfslogDeviceCharacteristics(sqlite3_file *pFile){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xDeviceCharacteristics(p->pReal); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_DEVCHAR, p->iFileId, t, rc, 0, 0); + return rc; +} + +static int vfslogShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SHMLOCK, p->iFileId, t, rc, 0, 0); + return rc; +} +static int vfslogShmMap( + sqlite3_file *pFile, + int iRegion, + int szRegion, + int isWrite, + volatile void **pp +){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SHMMAP, p->iFileId, t, rc, 0, 0); + return rc; +} +static void vfslogShmBarrier(sqlite3_file *pFile){ + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + p->pReal->pMethods->xShmBarrier(p->pReal); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SHMBARRIER, p->iFileId, t, SQLITE_OK, 0, 0); +} +static int vfslogShmUnmap(sqlite3_file *pFile, int deleteFlag){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xShmUnmap(p->pReal, deleteFlag); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SHMUNMAP, p->iFileId, t, rc, 0, 0); + return rc; +} + + +/* +** Open an vfslog file handle. +*/ +static int vfslogOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + VfslogVfs *pLog = (VfslogVfs *)pVfs; + + pFile->pMethods = &vfslog_io_methods; + p->pReal = (sqlite3_file *)&p[1]; + p->pVfslog = pVfs; + p->iFileId = ++pLog->iNextFileId; + + t = vfslog_time(); + rc = REALVFS(pVfs)->xOpen(REALVFS(pVfs), zName, p->pReal, flags, pOutFlags); + t = vfslog_time() - t; + + vfslog_call(pVfs, OS_OPEN, p->iFileId, t, rc, 0, 0); + vfslog_string(pVfs, zName); + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int vfslogDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc; + sqlite3_uint64 t; + t = vfslog_time(); + rc = REALVFS(pVfs)->xDelete(REALVFS(pVfs), zPath, dirSync); + t = vfslog_time() - t; + vfslog_call(pVfs, OS_DELETE, 0, t, rc, dirSync, 0); + vfslog_string(pVfs, zPath); + return rc; +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int vfslogAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + int rc; + sqlite3_uint64 t; + t = vfslog_time(); + rc = REALVFS(pVfs)->xAccess(REALVFS(pVfs), zPath, flags, pResOut); + t = vfslog_time() - t; + vfslog_call(pVfs, OS_ACCESS, 0, t, rc, flags, *pResOut); + vfslog_string(pVfs, zPath); + return rc; +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (INST_MAX_PATHNAME+1) bytes. +*/ +static int vfslogFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + return REALVFS(pVfs)->xFullPathname(REALVFS(pVfs), zPath, nOut, zOut); +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *vfslogDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return REALVFS(pVfs)->xDlOpen(REALVFS(pVfs), zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void vfslogDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + REALVFS(pVfs)->xDlError(REALVFS(pVfs), nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*vfslogDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return REALVFS(pVfs)->xDlSym(REALVFS(pVfs), p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void vfslogDlClose(sqlite3_vfs *pVfs, void *pHandle){ + REALVFS(pVfs)->xDlClose(REALVFS(pVfs), pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int vfslogRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return REALVFS(pVfs)->xRandomness(REALVFS(pVfs), nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int vfslogSleep(sqlite3_vfs *pVfs, int nMicro){ + return REALVFS(pVfs)->xSleep(REALVFS(pVfs), nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int vfslogCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + return REALVFS(pVfs)->xCurrentTime(REALVFS(pVfs), pTimeOut); +} + +static int vfslogGetLastError(sqlite3_vfs *pVfs, int a, char *b){ + return REALVFS(pVfs)->xGetLastError(REALVFS(pVfs), a, b); +} +static int vfslogCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){ + return REALVFS(pVfs)->xCurrentTimeInt64(REALVFS(pVfs), p); +} + +static void vfslog_flush(VfslogVfs *p){ +#ifdef SQLITE_TEST + extern int sqlite3_io_error_pending; + extern int sqlite3_io_error_persist; + extern int sqlite3_diskfull_pending; + + int pending = sqlite3_io_error_pending; + int persist = sqlite3_io_error_persist; + int diskfull = sqlite3_diskfull_pending; + + sqlite3_io_error_pending = 0; + sqlite3_io_error_persist = 0; + sqlite3_diskfull_pending = 0; +#endif + + if( p->nBuf ){ + p->pLog->pMethods->xWrite(p->pLog, p->aBuf, p->nBuf, p->iOffset); + p->iOffset += p->nBuf; + p->nBuf = 0; + } + +#ifdef SQLITE_TEST + sqlite3_io_error_pending = pending; + sqlite3_io_error_persist = persist; + sqlite3_diskfull_pending = diskfull; +#endif +} + +static void put32bits(unsigned char *p, unsigned int v){ + p[0] = v>>24; + p[1] = v>>16; + p[2] = v>>8; + p[3] = v; +} + +static void vfslog_call( + sqlite3_vfs *pVfs, + int eEvent, + int iFileid, + sqlite3_int64 nClick, + int return_code, + int size, + int offset +){ + VfslogVfs *p = (VfslogVfs *)pVfs; + unsigned char *zRec; + if( (24+p->nBuf)>sizeof(p->aBuf) ){ + vfslog_flush(p); + } + zRec = (unsigned char *)&p->aBuf[p->nBuf]; + put32bits(&zRec[0], eEvent); + put32bits(&zRec[4], iFileid); + put32bits(&zRec[8], (unsigned int)(nClick&0xffff)); + put32bits(&zRec[12], return_code); + put32bits(&zRec[16], size); + put32bits(&zRec[20], offset); + p->nBuf += 24; +} + +static void vfslog_string(sqlite3_vfs *pVfs, const char *zStr){ + VfslogVfs *p = (VfslogVfs *)pVfs; + unsigned char *zRec; + int nStr = zStr ? (int)strlen(zStr) : 0; + if( (4+nStr+p->nBuf)>sizeof(p->aBuf) ){ + vfslog_flush(p); + } + zRec = (unsigned char *)&p->aBuf[p->nBuf]; + put32bits(&zRec[0], nStr); + if( zStr ){ + memcpy(&zRec[4], zStr, nStr); + } + p->nBuf += (4 + nStr); +} + +static void vfslog_finalize(VfslogVfs *p){ + if( p->pLog->pMethods ){ + vfslog_flush(p); + p->pLog->pMethods->xClose(p->pLog); + } + sqlite3_free(p); +} + +int sqlite3_vfslog_finalize(const char *zVfs){ + sqlite3_vfs *pVfs; + pVfs = sqlite3_vfs_find(zVfs); + if( !pVfs || pVfs->xOpen!=vfslogOpen ){ + return SQLITE_ERROR; + } + sqlite3_vfs_unregister(pVfs); + vfslog_finalize((VfslogVfs *)pVfs); + return SQLITE_OK; +} + +int sqlite3_vfslog_new( + const char *zVfs, /* New VFS name */ + const char *zParentVfs, /* Parent VFS name (or NULL) */ + const char *zLog /* Log file name */ +){ + VfslogVfs *p; + sqlite3_vfs *pParent; + int nByte; + int flags; + int rc; + char *zFile; + int nVfs; + + pParent = sqlite3_vfs_find(zParentVfs); + if( !pParent ){ + return SQLITE_ERROR; + } + + nVfs = (int)strlen(zVfs); + nByte = sizeof(VfslogVfs) + pParent->szOsFile + nVfs+1+pParent->mxPathname+1; + p = (VfslogVfs *)sqlite3_malloc(nByte); + memset(p, 0, nByte); + + p->pVfs = pParent; + p->pLog = (sqlite3_file *)&p[1]; + memcpy(&p->base, &vfslog_vfs, sizeof(sqlite3_vfs)); + p->base.zName = &((char *)p->pLog)[pParent->szOsFile]; + p->base.szOsFile += pParent->szOsFile; + memcpy((char *)p->base.zName, zVfs, nVfs); + + zFile = (char *)&p->base.zName[nVfs+1]; + pParent->xFullPathname(pParent, zLog, pParent->mxPathname, zFile); + + flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MASTER_JOURNAL; + pParent->xDelete(pParent, zFile, 0); + rc = pParent->xOpen(pParent, zFile, p->pLog, flags, &flags); + if( rc==SQLITE_OK ){ + memcpy(p->aBuf, "sqlite_ostrace1.....", 20); + p->iOffset = 0; + p->nBuf = 20; + rc = sqlite3_vfs_register((sqlite3_vfs *)p, 1); + } + if( rc ){ + vfslog_finalize(p); + } + return rc; +} + +int sqlite3_vfslog_annotate(const char *zVfs, const char *zMsg){ + sqlite3_vfs *pVfs; + pVfs = sqlite3_vfs_find(zVfs); + if( !pVfs || pVfs->xOpen!=vfslogOpen ){ + return SQLITE_ERROR; + } + vfslog_call(pVfs, OS_ANNOTATE, 0, 0, 0, 0, 0); + vfslog_string(pVfs, zMsg); + return SQLITE_OK; +} + +static const char *vfslog_eventname(int eEvent){ + const char *zEvent = 0; + + switch( eEvent ){ + case OS_CLOSE: zEvent = "xClose"; break; + case OS_READ: zEvent = "xRead"; break; + case OS_WRITE: zEvent = "xWrite"; break; + case OS_TRUNCATE: zEvent = "xTruncate"; break; + case OS_SYNC: zEvent = "xSync"; break; + case OS_FILESIZE: zEvent = "xFilesize"; break; + case OS_LOCK: zEvent = "xLock"; break; + case OS_UNLOCK: zEvent = "xUnlock"; break; + case OS_CHECKRESERVEDLOCK: zEvent = "xCheckResLock"; break; + case OS_FILECONTROL: zEvent = "xFileControl"; break; + case OS_SECTORSIZE: zEvent = "xSectorSize"; break; + case OS_DEVCHAR: zEvent = "xDeviceChar"; break; + case OS_OPEN: zEvent = "xOpen"; break; + case OS_DELETE: zEvent = "xDelete"; break; + case OS_ACCESS: zEvent = "xAccess"; break; + case OS_FULLPATHNAME: zEvent = "xFullPathname"; break; + case OS_RANDOMNESS: zEvent = "xRandomness"; break; + case OS_SLEEP: zEvent = "xSleep"; break; + case OS_CURRENTTIME: zEvent = "xCurrentTime"; break; + + case OS_SHMUNMAP: zEvent = "xShmUnmap"; break; + case OS_SHMLOCK: zEvent = "xShmLock"; break; + case OS_SHMBARRIER: zEvent = "xShmBarrier"; break; + case OS_SHMMAP: zEvent = "xShmMap"; break; + + case OS_ANNOTATE: zEvent = "annotation"; break; + } + + return zEvent; +} + +typedef struct VfslogVtab VfslogVtab; +typedef struct VfslogCsr VfslogCsr; + +/* +** Virtual table type for the vfslog reader module. +*/ +struct VfslogVtab { + sqlite3_vtab base; /* Base class */ + sqlite3_file *pFd; /* File descriptor open on vfslog file */ + sqlite3_int64 nByte; /* Size of file in bytes */ + char *zFile; /* File name for pFd */ +}; + +/* +** Virtual table cursor type for the vfslog reader module. +*/ +struct VfslogCsr { + sqlite3_vtab_cursor base; /* Base class */ + sqlite3_int64 iRowid; /* Current rowid. */ + sqlite3_int64 iOffset; /* Offset of next record in file */ + char *zTransient; /* Transient 'file' string */ + int nFile; /* Size of array azFile[] */ + char **azFile; /* File strings */ + unsigned char aBuf[1024]; /* Current vfs log entry (read from file) */ +}; + +static unsigned int get32bits(unsigned char *p){ + return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; +} + +/* +** The argument must point to a buffer containing a nul-terminated string. +** If the string begins with an SQL quote character it is overwritten by +** the dequoted version. Otherwise the buffer is left unmodified. +*/ +static void dequote(char *z){ + char quote; /* Quote character (if any ) */ + quote = z[0]; + if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ + int iIn = 1; /* Index of next byte to read from input */ + int iOut = 0; /* Index of next byte to write to output */ + if( quote=='[' ) quote = ']'; + while( z[iIn] ){ + if( z[iIn]==quote ){ + if( z[iIn+1]!=quote ) break; + z[iOut++] = quote; + iIn += 2; + }else{ + z[iOut++] = z[iIn++]; + } + } + z[iOut] = '\0'; + } +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Connect to or create a vfslog virtual table. +*/ +static int vlogConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + sqlite3_vfs *pVfs; /* VFS used to read log file */ + int flags; /* flags passed to pVfs->xOpen() */ + VfslogVtab *p; + int rc; + int nByte; + char *zFile; + + *ppVtab = 0; + pVfs = sqlite3_vfs_find(0); + nByte = sizeof(VfslogVtab) + pVfs->szOsFile + pVfs->mxPathname; + p = sqlite3_malloc(nByte); + if( p==0 ) return SQLITE_NOMEM; + memset(p, 0, nByte); + + p->pFd = (sqlite3_file *)&p[1]; + p->zFile = &((char *)p->pFd)[pVfs->szOsFile]; + + zFile = sqlite3_mprintf("%s", argv[3]); + if( !zFile ){ + sqlite3_free(p); + return SQLITE_NOMEM; + } + dequote(zFile); + pVfs->xFullPathname(pVfs, zFile, pVfs->mxPathname, p->zFile); + sqlite3_free(zFile); + + flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MASTER_JOURNAL; + rc = pVfs->xOpen(pVfs, p->zFile, p->pFd, flags, &flags); + + if( rc==SQLITE_OK ){ + p->pFd->pMethods->xFileSize(p->pFd, &p->nByte); + sqlite3_declare_vtab(db, + "CREATE TABLE xxx(event, file, click, rc, size, offset)" + ); + *ppVtab = &p->base; + }else{ + sqlite3_free(p); + } + + return rc; +} + +/* +** There is no "best-index". This virtual table always does a linear +** scan of the binary VFS log file. +*/ +static int vlogBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + pIdxInfo->estimatedCost = 10.0; + return SQLITE_OK; +} + +/* +** Disconnect from or destroy a vfslog virtual table. +*/ +static int vlogDisconnect(sqlite3_vtab *pVtab){ + VfslogVtab *p = (VfslogVtab *)pVtab; + if( p->pFd->pMethods ){ + p->pFd->pMethods->xClose(p->pFd); + p->pFd->pMethods = 0; + } + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Open a new vfslog cursor. +*/ +static int vlogOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + VfslogCsr *pCsr; /* Newly allocated cursor object */ + + pCsr = sqlite3_malloc(sizeof(VfslogCsr)); + if( !pCsr ) return SQLITE_NOMEM; + memset(pCsr, 0, sizeof(VfslogCsr)); + *ppCursor = &pCsr->base; + return SQLITE_OK; +} + +/* +** Close a vfslog cursor. +*/ +static int vlogClose(sqlite3_vtab_cursor *pCursor){ + VfslogCsr *p = (VfslogCsr *)pCursor; + int i; + for(i=0; inFile; i++){ + sqlite3_free(p->azFile[i]); + } + sqlite3_free(p->azFile); + sqlite3_free(p->zTransient); + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Move a vfslog cursor to the next entry in the file. +*/ +static int vlogNext(sqlite3_vtab_cursor *pCursor){ + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + VfslogVtab *p = (VfslogVtab *)pCursor->pVtab; + int rc = SQLITE_OK; + int nRead; + + sqlite3_free(pCsr->zTransient); + pCsr->zTransient = 0; + + nRead = 24; + if( pCsr->iOffset+nRead<=p->nByte ){ + int eEvent; + rc = p->pFd->pMethods->xRead(p->pFd, pCsr->aBuf, nRead, pCsr->iOffset); + + eEvent = get32bits(pCsr->aBuf); + if( (rc==SQLITE_OK) + && (eEvent==OS_OPEN || eEvent==OS_DELETE || eEvent==OS_ACCESS) + ){ + char buf[4]; + rc = p->pFd->pMethods->xRead(p->pFd, buf, 4, pCsr->iOffset+nRead); + nRead += 4; + if( rc==SQLITE_OK ){ + int nStr = get32bits((unsigned char *)buf); + char *zStr = sqlite3_malloc(nStr+1); + rc = p->pFd->pMethods->xRead(p->pFd, zStr, nStr, pCsr->iOffset+nRead); + zStr[nStr] = '\0'; + nRead += nStr; + + if( eEvent==OS_OPEN ){ + int iFileid = get32bits(&pCsr->aBuf[4]); + if( iFileid>=pCsr->nFile ){ + int nNew = sizeof(pCsr->azFile[0])*(iFileid+1); + pCsr->azFile = (char **)sqlite3_realloc(pCsr->azFile, nNew); + nNew -= sizeof(pCsr->azFile[0])*pCsr->nFile; + memset(&pCsr->azFile[pCsr->nFile], 0, nNew); + pCsr->nFile = iFileid+1; + } + sqlite3_free(pCsr->azFile[iFileid]); + pCsr->azFile[iFileid] = zStr; + }else{ + pCsr->zTransient = zStr; + } + } + } + } + + pCsr->iRowid += 1; + pCsr->iOffset += nRead; + return rc; +} + +static int vlogEof(sqlite3_vtab_cursor *pCursor){ + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + VfslogVtab *p = (VfslogVtab *)pCursor->pVtab; + return (pCsr->iOffset>=p->nByte); +} + +static int vlogFilter( + sqlite3_vtab_cursor *pCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + pCsr->iRowid = 0; + pCsr->iOffset = 20; + return vlogNext(pCursor); +} + +static int vlogColumn( + sqlite3_vtab_cursor *pCursor, + sqlite3_context *ctx, + int i +){ + unsigned int val; + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + + assert( i<7 ); + val = get32bits(&pCsr->aBuf[4*i]); + + switch( i ){ + case 0: { + sqlite3_result_text(ctx, vfslog_eventname(val), -1, SQLITE_STATIC); + break; + } + case 1: { + char *zStr = pCsr->zTransient; + if( val!=0 && val<(unsigned)pCsr->nFile ){ + zStr = pCsr->azFile[val]; + } + sqlite3_result_text(ctx, zStr, -1, SQLITE_TRANSIENT); + break; + } + default: + sqlite3_result_int(ctx, val); + break; + } + + return SQLITE_OK; +} + +static int vlogRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + *pRowid = pCsr->iRowid; + return SQLITE_OK; +} + +int sqlite3_vfslog_register(sqlite3 *db){ + static sqlite3_module vfslog_module = { + 0, /* iVersion */ + vlogConnect, /* xCreate */ + vlogConnect, /* xConnect */ + vlogBestIndex, /* xBestIndex */ + vlogDisconnect, /* xDisconnect */ + vlogDisconnect, /* xDestroy */ + vlogOpen, /* xOpen - open a cursor */ + vlogClose, /* xClose - close a cursor */ + vlogFilter, /* xFilter - configure scan constraints */ + vlogNext, /* xNext - advance a cursor */ + vlogEof, /* xEof - check for end of scan */ + vlogColumn, /* xColumn - read data */ + vlogRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + }; + + sqlite3_create_module(db, "vfslog", &vfslog_module, 0); + return SQLITE_OK; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/************************************************************************** +*************************************************************************** +** Tcl interface starts here. +*/ + +#if defined(SQLITE_TEST) || defined(TCLSH) + +#include + +static int test_vfslog( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct SqliteDb { sqlite3 *db; }; + sqlite3 *db; + Tcl_CmdInfo cmdInfo; + int rc = SQLITE_ERROR; + + static const char *strs[] = { "annotate", "finalize", "new", "register", 0 }; + enum VL_enum { VL_ANNOTATE, VL_FINALIZE, VL_NEW, VL_REGISTER }; + int iSub; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND ..."); + return TCL_ERROR; + } + if( Tcl_GetIndexFromObj(interp, objv[1], strs, "sub-command", 0, &iSub) ){ + return TCL_ERROR; + } + + switch( (enum VL_enum)iSub ){ + case VL_ANNOTATE: { + int rc; + char *zVfs; + char *zMsg; + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 3, objv, "VFS"); + return TCL_ERROR; + } + zVfs = Tcl_GetString(objv[2]); + zMsg = Tcl_GetString(objv[3]); + rc = sqlite3_vfslog_annotate(zVfs, zMsg); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "failed", 0); + return TCL_ERROR; + } + break; + } + case VL_FINALIZE: { + int rc; + char *zVfs; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "VFS"); + return TCL_ERROR; + } + zVfs = Tcl_GetString(objv[2]); + rc = sqlite3_vfslog_finalize(zVfs); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "failed", 0); + return TCL_ERROR; + } + break; + }; + + case VL_NEW: { + int rc; + char *zVfs; + char *zParent; + char *zLog; + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 2, objv, "VFS PARENT LOGFILE"); + return TCL_ERROR; + } + zVfs = Tcl_GetString(objv[2]); + zParent = Tcl_GetString(objv[3]); + zLog = Tcl_GetString(objv[4]); + if( *zParent=='\0' ) zParent = 0; + rc = sqlite3_vfslog_new(zVfs, zParent, zLog); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "failed", 0); + return TCL_ERROR; + } + break; + }; + + case VL_REGISTER: { + char *zDb; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "DB"); + return TCL_ERROR; + } +#ifdef SQLITE_OMIT_VIRTUALTABLE + Tcl_AppendResult(interp, "vfslog not available because of " + "SQLITE_OMIT_VIRTUALTABLE", (void*)0); + return TCL_ERROR; +#else + zDb = Tcl_GetString(objv[2]); + if( Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){ + db = ((struct SqliteDb*)cmdInfo.objClientData)->db; + rc = sqlite3_vfslog_register(db); + } + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "bad sqlite3 handle: ", zDb, (void*)0); + return TCL_ERROR; + } + break; +#endif + } + } + + return TCL_OK; +} + +int SqlitetestOsinst_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "vfslog", test_vfslog, 0, 0); + return TCL_OK; +} + +#endif /* SQLITE_TEST */ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_pcache.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_pcache.c new file mode 100644 index 0000000000000000000000000000000000000000..8fcfe7e26e3ff17496b840f5d63c75783aff8162 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_pcache.c @@ -0,0 +1,467 @@ +/* +** 2008 November 18 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used for testing the SQLite system. +** None of the code in this file goes into a deliverable build. +** +** This file contains an application-defined pager cache +** implementation that can be plugged in in place of the +** default pcache. This alternative pager cache will throw +** some errors that the default cache does not. +** +** This pagecache implementation is designed for simplicity +** not speed. +*/ +#include "sqlite3.h" +#include +#include + +/* +** Global data used by this test implementation. There is no +** mutexing, which means this page cache will not work in a +** multi-threaded test. +*/ +typedef struct testpcacheGlobalType testpcacheGlobalType; +struct testpcacheGlobalType { + void *pDummy; /* Dummy allocation to simulate failures */ + int nInstance; /* Number of current instances */ + unsigned discardChance; /* Chance of discarding on an unpin (0-100) */ + unsigned prngSeed; /* Seed for the PRNG */ + unsigned highStress; /* Call xStress agressively */ +}; +static testpcacheGlobalType testpcacheGlobal; + +/* +** Initializer. +** +** Verify that the initializer is only called when the system is +** uninitialized. Allocate some memory and report SQLITE_NOMEM if +** the allocation fails. This provides a means to test the recovery +** from a failed initialization attempt. It also verifies that the +** the destructor always gets call - otherwise there would be a +** memory leak. +*/ +static int testpcacheInit(void *pArg){ + assert( pArg==(void*)&testpcacheGlobal ); + assert( testpcacheGlobal.pDummy==0 ); + assert( testpcacheGlobal.nInstance==0 ); + testpcacheGlobal.pDummy = sqlite3_malloc(10); + return testpcacheGlobal.pDummy==0 ? SQLITE_NOMEM : SQLITE_OK; +} + +/* +** Destructor +** +** Verify that this is only called after initialization. +** Free the memory allocated by the initializer. +*/ +static void testpcacheShutdown(void *pArg){ + assert( pArg==(void*)&testpcacheGlobal ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance==0 ); + sqlite3_free( testpcacheGlobal.pDummy ); + testpcacheGlobal.pDummy = 0; +} + +/* +** Number of pages in a cache. +** +** The number of pages is a hard upper bound in this test module. +** If more pages are requested, sqlite3PcacheFetch() returns NULL. +** +** If testing with in-memory temp tables, provide a larger pcache. +** Some of the test cases need this. +*/ +#if defined(SQLITE_TEMP_STORE) && SQLITE_TEMP_STORE>=2 +# define TESTPCACHE_NPAGE 499 +#else +# define TESTPCACHE_NPAGE 217 +#endif +#define TESTPCACHE_RESERVE 17 + +/* +** Magic numbers used to determine validity of the page cache. +*/ +#define TESTPCACHE_VALID 0x364585fd +#define TESTPCACHE_CLEAR 0xd42670d4 + +/* +** Private implementation of a page cache. +*/ +typedef struct testpcache testpcache; +struct testpcache { + int szPage; /* Size of each page. Multiple of 8. */ + int szExtra; /* Size of extra data that accompanies each page */ + int bPurgeable; /* True if the page cache is purgeable */ + int nFree; /* Number of unused slots in a[] */ + int nPinned; /* Number of pinned slots in a[] */ + unsigned iRand; /* State of the PRNG */ + unsigned iMagic; /* Magic number for sanity checking */ + struct testpcachePage { + sqlite3_pcache_page page; /* Base class */ + unsigned key; /* The key for this page. 0 means unallocated */ + int isPinned; /* True if the page is pinned */ + } a[TESTPCACHE_NPAGE]; /* All pages in the cache */ +}; + +/* +** Get a random number using the PRNG in the given page cache. +*/ +static unsigned testpcacheRandom(testpcache *p){ + unsigned x = 0; + int i; + for(i=0; i<4; i++){ + p->iRand = (p->iRand*69069 + 5); + x = (x<<8) | ((p->iRand>>16)&0xff); + } + return x; +} + + +/* +** Allocate a new page cache instance. +*/ +static sqlite3_pcache *testpcacheCreate( + int szPage, + int szExtra, + int bPurgeable +){ + int nMem; + char *x; + testpcache *p; + int i; + assert( testpcacheGlobal.pDummy!=0 ); + szPage = (szPage+7)&~7; + nMem = sizeof(testpcache) + TESTPCACHE_NPAGE*(szPage+szExtra); + p = sqlite3_malloc( nMem ); + if( p==0 ) return 0; + x = (char*)&p[1]; + p->szPage = szPage; + p->szExtra = szExtra; + p->nFree = TESTPCACHE_NPAGE; + p->nPinned = 0; + p->iRand = testpcacheGlobal.prngSeed; + p->bPurgeable = bPurgeable; + p->iMagic = TESTPCACHE_VALID; + for(i=0; ia[i].key = 0; + p->a[i].isPinned = 0; + p->a[i].page.pBuf = (void*)x; + p->a[i].page.pExtra = (void*)&x[szPage]; + } + testpcacheGlobal.nInstance++; + return (sqlite3_pcache*)p; +} + +/* +** Set the cache size +*/ +static void testpcacheCachesize(sqlite3_pcache *pCache, int newSize){ + testpcache *p = (testpcache*)pCache; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); +} + +/* +** Return the number of pages in the cache that are being used. +** This includes both pinned and unpinned pages. +*/ +static int testpcachePagecount(sqlite3_pcache *pCache){ + testpcache *p = (testpcache*)pCache; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + return TESTPCACHE_NPAGE - p->nFree; +} + +/* +** Fetch a page. +*/ +static sqlite3_pcache_page *testpcacheFetch( + sqlite3_pcache *pCache, + unsigned key, + int createFlag +){ + testpcache *p = (testpcache*)pCache; + int i, j; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + + /* See if the page is already in cache. Return immediately if it is */ + for(i=0; ia[i].key==key ){ + if( !p->a[i].isPinned ){ + p->nPinned++; + assert( p->nPinned <= TESTPCACHE_NPAGE - p->nFree ); + p->a[i].isPinned = 1; + } + return &p->a[i].page; + } + } + + /* If createFlag is 0, never allocate a new page */ + if( createFlag==0 ){ + return 0; + } + + /* If no pages are available, always fail */ + if( p->nPinned==TESTPCACHE_NPAGE ){ + return 0; + } + + /* Do not allocate the last TESTPCACHE_RESERVE pages unless createFlag is 2 */ + if( p->nPinned>=TESTPCACHE_NPAGE-TESTPCACHE_RESERVE && createFlag<2 ){ + return 0; + } + + /* Do not allocate if highStress is enabled and createFlag is not 2. + ** + ** The highStress setting causes pagerStress() to be called much more + ** often, which exercises the pager logic more intensely. + */ + if( testpcacheGlobal.highStress && createFlag<2 ){ + return 0; + } + + /* Find a free page to allocate if there are any free pages. + ** Withhold TESTPCACHE_RESERVE free pages until createFlag is 2. + */ + if( p->nFree>TESTPCACHE_RESERVE || (createFlag==2 && p->nFree>0) ){ + j = testpcacheRandom(p) % TESTPCACHE_NPAGE; + for(i=0; ia[j].key==0 ){ + p->a[j].key = key; + p->a[j].isPinned = 1; + memset(p->a[j].page.pBuf, 0, p->szPage); + memset(p->a[j].page.pExtra, 0, p->szExtra); + p->nPinned++; + p->nFree--; + assert( p->nPinned <= TESTPCACHE_NPAGE - p->nFree ); + return &p->a[j].page; + } + } + + /* The prior loop always finds a freepage to allocate */ + assert( 0 ); + } + + /* If this cache is not purgeable then we have to fail. + */ + if( p->bPurgeable==0 ){ + return 0; + } + + /* If there are no free pages, recycle a page. The page to + ** recycle is selected at random from all unpinned pages. + */ + j = testpcacheRandom(p) % TESTPCACHE_NPAGE; + for(i=0; ia[j].key>0 && p->a[j].isPinned==0 ){ + p->a[j].key = key; + p->a[j].isPinned = 1; + memset(p->a[j].page.pBuf, 0, p->szPage); + memset(p->a[j].page.pExtra, 0, p->szExtra); + p->nPinned++; + assert( p->nPinned <= TESTPCACHE_NPAGE - p->nFree ); + return &p->a[j].page; + } + } + + /* The previous loop always finds a page to recycle. */ + assert(0); + return 0; +} + +/* +** Unpin a page. +*/ +static void testpcacheUnpin( + sqlite3_pcache *pCache, + sqlite3_pcache_page *pOldPage, + int discard +){ + testpcache *p = (testpcache*)pCache; + int i; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + + /* Randomly discard pages as they are unpinned according to the + ** discardChance setting. If discardChance is 0, the random discard + ** never happens. If discardChance is 100, it always happens. + */ + if( p->bPurgeable + && (100-testpcacheGlobal.discardChance) <= (testpcacheRandom(p)%100) + ){ + discard = 1; + } + + for(i=0; ia[i].page==pOldPage ){ + /* The pOldPage pointer always points to a pinned page */ + assert( p->a[i].isPinned ); + p->a[i].isPinned = 0; + p->nPinned--; + assert( p->nPinned>=0 ); + if( discard ){ + p->a[i].key = 0; + p->nFree++; + assert( p->nFree<=TESTPCACHE_NPAGE ); + } + return; + } + } + + /* The pOldPage pointer always points to a valid page */ + assert( 0 ); +} + + +/* +** Rekey a single page. +*/ +static void testpcacheRekey( + sqlite3_pcache *pCache, + sqlite3_pcache_page *pOldPage, + unsigned oldKey, + unsigned newKey +){ + testpcache *p = (testpcache*)pCache; + int i; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + + /* If there already exists another page at newKey, verify that + ** the other page is unpinned and discard it. + */ + for(i=0; ia[i].key==newKey ){ + /* The new key is never a page that is already pinned */ + assert( p->a[i].isPinned==0 ); + p->a[i].key = 0; + p->nFree++; + assert( p->nFree<=TESTPCACHE_NPAGE ); + break; + } + } + + /* Find the page to be rekeyed and rekey it. + */ + for(i=0; ia[i].key==oldKey ){ + /* The oldKey and pOldPage parameters match */ + assert( &p->a[i].page==pOldPage ); + /* Page to be rekeyed must be pinned */ + assert( p->a[i].isPinned ); + p->a[i].key = newKey; + return; + } + } + + /* Rekey is always given a valid page to work with */ + assert( 0 ); +} + + +/* +** Truncate the page cache. Every page with a key of iLimit or larger +** is discarded. +*/ +static void testpcacheTruncate(sqlite3_pcache *pCache, unsigned iLimit){ + testpcache *p = (testpcache*)pCache; + unsigned int i; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + for(i=0; ia[i].key>=iLimit ){ + p->a[i].key = 0; + if( p->a[i].isPinned ){ + p->nPinned--; + assert( p->nPinned>=0 ); + } + p->nFree++; + assert( p->nFree<=TESTPCACHE_NPAGE ); + } + } +} + +/* +** Destroy a page cache. +*/ +static void testpcacheDestroy(sqlite3_pcache *pCache){ + testpcache *p = (testpcache*)pCache; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + p->iMagic = TESTPCACHE_CLEAR; + sqlite3_free(p); + testpcacheGlobal.nInstance--; +} + + +/* +** Invoke this routine to register or unregister the testing pager cache +** implemented by this file. +** +** Install the test pager cache if installFlag is 1 and uninstall it if +** installFlag is 0. +** +** When installing, discardChance is a number between 0 and 100 that +** indicates the probability of discarding a page when unpinning the +** page. 0 means never discard (unless the discard flag is set). +** 100 means always discard. +*/ +void installTestPCache( + int installFlag, /* True to install. False to uninstall. */ + unsigned discardChance, /* 0-100. Chance to discard on unpin */ + unsigned prngSeed, /* Seed for the PRNG */ + unsigned highStress /* Call xStress agressively */ +){ + static const sqlite3_pcache_methods2 testPcache = { + 1, + (void*)&testpcacheGlobal, + testpcacheInit, + testpcacheShutdown, + testpcacheCreate, + testpcacheCachesize, + testpcachePagecount, + testpcacheFetch, + testpcacheUnpin, + testpcacheRekey, + testpcacheTruncate, + testpcacheDestroy, + }; + static sqlite3_pcache_methods2 defaultPcache; + static int isInstalled = 0; + + assert( testpcacheGlobal.nInstance==0 ); + assert( testpcacheGlobal.pDummy==0 ); + assert( discardChance<=100 ); + testpcacheGlobal.discardChance = discardChance; + testpcacheGlobal.prngSeed = prngSeed ^ (prngSeed<<16); + testpcacheGlobal.highStress = highStress; + if( installFlag!=isInstalled ){ + if( installFlag ){ + sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &defaultPcache); + assert( defaultPcache.xCreate!=testpcacheCreate ); + sqlite3_config(SQLITE_CONFIG_PCACHE2, &testPcache); + }else{ + assert( defaultPcache.xCreate!=0 ); + sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultPcache); + } + isInstalled = installFlag; + } +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_quota.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_quota.c new file mode 100644 index 0000000000000000000000000000000000000000..e590996ca4b8574ab1e4185d577756664ad2495f --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_quota.c @@ -0,0 +1,2008 @@ +/* +** 2010 September 31 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains a VFS "shim" - a layer that sits in between the +** pager and the real VFS. +** +** This particular shim enforces a quota system on files. One or more +** database files are in a "quota group" that is defined by a GLOB +** pattern. A quota is set for the combined size of all files in the +** the group. A quota of zero means "no limit". If the total size +** of all files in the quota group is greater than the limit, then +** write requests that attempt to enlarge a file fail with SQLITE_FULL. +** +** However, before returning SQLITE_FULL, the write requests invoke +** a callback function that is configurable for each quota group. +** This callback has the opportunity to enlarge the quota. If the +** callback does enlarge the quota such that the total size of all +** files within the group is less than the new quota, then the write +** continues as if nothing had happened. +*/ +#include "test_quota.h" +#include +#include + +/* +** For an build without mutexes, no-op the mutex calls. +*/ +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0 +#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) +#define sqlite3_mutex_free(X) +#define sqlite3_mutex_enter(X) +#define sqlite3_mutex_try(X) SQLITE_OK +#define sqlite3_mutex_leave(X) +#define sqlite3_mutex_held(X) ((void)(X),1) +#define sqlite3_mutex_notheld(X) ((void)(X),1) +#endif /* SQLITE_THREADSAFE==0 */ + + +/* +** Figure out if we are dealing with Unix, Windows, or some other +** operating system. After the following block of preprocess macros, +** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER +** will defined to either 1 or 0. One of the four will be 1. The other +** three will be 0. +*/ +#if defined(SQLITE_OS_OTHER) +# if SQLITE_OS_OTHER==1 +# undef SQLITE_OS_UNIX +# define SQLITE_OS_UNIX 0 +# undef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# else +# undef SQLITE_OS_OTHER +# endif +#endif +#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) +# define SQLITE_OS_OTHER 0 +# ifndef SQLITE_OS_WIN +# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) \ + || defined(__MINGW32__) || defined(__BORLANDC__) +# define SQLITE_OS_WIN 1 +# define SQLITE_OS_UNIX 0 +# else +# define SQLITE_OS_WIN 0 +# define SQLITE_OS_UNIX 1 +# endif +# else +# define SQLITE_OS_UNIX 0 +# endif +#else +# ifndef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# endif +#endif + +#if SQLITE_OS_UNIX +# include +#endif +#if SQLITE_OS_WIN +# include +# include +#endif + + +/************************ Object Definitions ******************************/ + +/* Forward declaration of all object types */ +typedef struct quotaGroup quotaGroup; +typedef struct quotaConn quotaConn; +typedef struct quotaFile quotaFile; + +/* +** A "quota group" is a collection of files whose collective size we want +** to limit. Each quota group is defined by a GLOB pattern. +** +** There is an instance of the following object for each defined quota +** group. This object records the GLOB pattern that defines which files +** belong to the quota group. The object also remembers the size limit +** for the group (the quota) and the callback to be invoked when the +** sum of the sizes of the files within the group goes over the limit. +** +** A quota group must be established (using sqlite3_quota_set(...)) +** prior to opening any of the database connections that access files +** within the quota group. +*/ +struct quotaGroup { + const char *zPattern; /* Filename pattern to be quotaed */ + sqlite3_int64 iLimit; /* Upper bound on total file size */ + sqlite3_int64 iSize; /* Current size of all files */ + void (*xCallback)( /* Callback invoked when going over quota */ + const char *zFilename, /* Name of file whose size increases */ + sqlite3_int64 *piLimit, /* IN/OUT: The current limit */ + sqlite3_int64 iSize, /* Total size of all files in the group */ + void *pArg /* Client data */ + ); + void *pArg; /* Third argument to the xCallback() */ + void (*xDestroy)(void*); /* Optional destructor for pArg */ + quotaGroup *pNext, **ppPrev; /* Doubly linked list of all quota objects */ + quotaFile *pFiles; /* Files within this group */ +}; + +/* +** An instance of this structure represents a single file that is part +** of a quota group. A single file can be opened multiple times. In +** order keep multiple openings of the same file from causing the size +** of the file to count against the quota multiple times, each file +** has a unique instance of this object and multiple open connections +** to the same file each point to a single instance of this object. +*/ +struct quotaFile { + char *zFilename; /* Name of this file */ + quotaGroup *pGroup; /* Quota group to which this file belongs */ + sqlite3_int64 iSize; /* Current size of this file */ + int nRef; /* Number of times this file is open */ + int deleteOnClose; /* True to delete this file when it closes */ + quotaFile *pNext, **ppPrev; /* Linked list of files in the same group */ +}; + +/* +** An instance of the following object represents each open connection +** to a file that participates in quota tracking. This object is a +** subclass of sqlite3_file. The sqlite3_file object for the underlying +** VFS is appended to this structure. +*/ +struct quotaConn { + sqlite3_file base; /* Base class - must be first */ + quotaFile *pFile; /* The underlying file */ + /* The underlying VFS sqlite3_file is appended to this object */ +}; + +/* +** An instance of the following object records the state of an +** open file. This object is opaque to all users - the internal +** structure is only visible to the functions below. +*/ +struct quota_FILE { + FILE *f; /* Open stdio file pointer */ + sqlite3_int64 iOfst; /* Current offset into the file */ + quotaFile *pFile; /* The file record in the quota system */ +#if SQLITE_OS_WIN + char *zMbcsName; /* Full MBCS pathname of the file */ +#endif +}; + + +/************************* Global Variables **********************************/ +/* +** All global variables used by this file are containing within the following +** gQuota structure. +*/ +static struct { + /* The pOrigVfs is the real, original underlying VFS implementation. + ** Most operations pass-through to the real VFS. This value is read-only + ** during operation. It is only modified at start-time and thus does not + ** require a mutex. + */ + sqlite3_vfs *pOrigVfs; + + /* The sThisVfs is the VFS structure used by this shim. It is initialized + ** at start-time and thus does not require a mutex + */ + sqlite3_vfs sThisVfs; + + /* The sIoMethods defines the methods used by sqlite3_file objects + ** associated with this shim. It is initialized at start-time and does + ** not require a mutex. + ** + ** When the underlying VFS is called to open a file, it might return + ** either a version 1 or a version 2 sqlite3_file object. This shim + ** has to create a wrapper sqlite3_file of the same version. Hence + ** there are two I/O method structures, one for version 1 and the other + ** for version 2. + */ + sqlite3_io_methods sIoMethodsV1; + sqlite3_io_methods sIoMethodsV2; + + /* True when this shim as been initialized. + */ + int isInitialized; + + /* For run-time access any of the other global data structures in this + ** shim, the following mutex must be held. + */ + sqlite3_mutex *pMutex; + + /* List of quotaGroup objects. + */ + quotaGroup *pGroup; + +} gQuota; + +/************************* Utility Routines *********************************/ +/* +** Acquire and release the mutex used to serialize access to the +** list of quotaGroups. +*/ +static void quotaEnter(void){ sqlite3_mutex_enter(gQuota.pMutex); } +static void quotaLeave(void){ sqlite3_mutex_leave(gQuota.pMutex); } + +/* Count the number of open files in a quotaGroup +*/ +static int quotaGroupOpenFileCount(quotaGroup *pGroup){ + int N = 0; + quotaFile *pFile = pGroup->pFiles; + while( pFile ){ + if( pFile->nRef ) N++; + pFile = pFile->pNext; + } + return N; +} + +/* Remove a file from a quota group. +*/ +static void quotaRemoveFile(quotaFile *pFile){ + quotaGroup *pGroup = pFile->pGroup; + pGroup->iSize -= pFile->iSize; + *pFile->ppPrev = pFile->pNext; + if( pFile->pNext ) pFile->pNext->ppPrev = pFile->ppPrev; + sqlite3_free(pFile); +} + +/* Remove all files from a quota group. It is always the case that +** all files will be closed when this routine is called. +*/ +static void quotaRemoveAllFiles(quotaGroup *pGroup){ + while( pGroup->pFiles ){ + assert( pGroup->pFiles->nRef==0 ); + quotaRemoveFile(pGroup->pFiles); + } +} + + +/* If the reference count and threshold for a quotaGroup are both +** zero, then destroy the quotaGroup. +*/ +static void quotaGroupDeref(quotaGroup *pGroup){ + if( pGroup->iLimit==0 && quotaGroupOpenFileCount(pGroup)==0 ){ + quotaRemoveAllFiles(pGroup); + *pGroup->ppPrev = pGroup->pNext; + if( pGroup->pNext ) pGroup->pNext->ppPrev = pGroup->ppPrev; + if( pGroup->xDestroy ) pGroup->xDestroy(pGroup->pArg); + sqlite3_free(pGroup); + } +} + +/* +** Return TRUE if string z matches glob pattern zGlob. +** +** Globbing rules: +** +** '*' Matches any sequence of zero or more characters. +** +** '?' Matches exactly one character. +** +** [...] Matches one character from the enclosed list of +** characters. +** +** [^...] Matches one character not in the enclosed list. +** +** / Matches "/" or "\\" +** +*/ +static int quotaStrglob(const char *zGlob, const char *z){ + int c, c2, cx; + int invert; + int seen; + + while( (c = (*(zGlob++)))!=0 ){ + if( c=='*' ){ + while( (c=(*(zGlob++))) == '*' || c=='?' ){ + if( c=='?' && (*(z++))==0 ) return 0; + } + if( c==0 ){ + return 1; + }else if( c=='[' ){ + while( *z && quotaStrglob(zGlob-1,z)==0 ){ + z++; + } + return (*z)!=0; + } + cx = (c=='/') ? '\\' : c; + while( (c2 = (*(z++)))!=0 ){ + while( c2!=c && c2!=cx ){ + c2 = *(z++); + if( c2==0 ) return 0; + } + if( quotaStrglob(zGlob,z) ) return 1; + } + return 0; + }else if( c=='?' ){ + if( (*(z++))==0 ) return 0; + }else if( c=='[' ){ + int prior_c = 0; + seen = 0; + invert = 0; + c = *(z++); + if( c==0 ) return 0; + c2 = *(zGlob++); + if( c2=='^' ){ + invert = 1; + c2 = *(zGlob++); + } + if( c2==']' ){ + if( c==']' ) seen = 1; + c2 = *(zGlob++); + } + while( c2 && c2!=']' ){ + if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ + c2 = *(zGlob++); + if( c>=prior_c && c<=c2 ) seen = 1; + prior_c = 0; + }else{ + if( c==c2 ){ + seen = 1; + } + prior_c = c2; + } + c2 = *(zGlob++); + } + if( c2==0 || (seen ^ invert)==0 ) return 0; + }else if( c=='/' ){ + if( z[0]!='/' && z[0]!='\\' ) return 0; + z++; + }else{ + if( c!=(*(z++)) ) return 0; + } + } + return *z==0; +} + + +/* Find a quotaGroup given the filename. +** +** Return a pointer to the quotaGroup object. Return NULL if not found. +*/ +static quotaGroup *quotaGroupFind(const char *zFilename){ + quotaGroup *p; + for(p=gQuota.pGroup; p && quotaStrglob(p->zPattern, zFilename)==0; + p=p->pNext){} + return p; +} + +/* Translate an sqlite3_file* that is really a quotaConn* into +** the sqlite3_file* for the underlying original VFS. +*/ +static sqlite3_file *quotaSubOpen(sqlite3_file *pConn){ + quotaConn *p = (quotaConn*)pConn; + return (sqlite3_file*)&p[1]; +} + +/* Find a file in a quota group and return a pointer to that file. +** Return NULL if the file is not in the group. +*/ +static quotaFile *quotaFindFile( + quotaGroup *pGroup, /* Group in which to look for the file */ + const char *zName, /* Full pathname of the file */ + int createFlag /* Try to create the file if not found */ +){ + quotaFile *pFile = pGroup->pFiles; + while( pFile && strcmp(pFile->zFilename, zName)!=0 ){ + pFile = pFile->pNext; + } + if( pFile==0 && createFlag ){ + int nName = (int)(strlen(zName) & 0x3fffffff); + pFile = (quotaFile *)sqlite3_malloc( sizeof(*pFile) + nName + 1 ); + if( pFile ){ + memset(pFile, 0, sizeof(*pFile)); + pFile->zFilename = (char*)&pFile[1]; + memcpy(pFile->zFilename, zName, nName+1); + pFile->pNext = pGroup->pFiles; + if( pGroup->pFiles ) pGroup->pFiles->ppPrev = &pFile->pNext; + pFile->ppPrev = &pGroup->pFiles; + pGroup->pFiles = pFile; + pFile->pGroup = pGroup; + } + } + return pFile; +} +/* +** Translate UTF8 to MBCS for use in fopen() calls. Return a pointer to the +** translated text.. Call quota_mbcs_free() to deallocate any memory +** used to store the returned pointer when done. +*/ +static char *quota_utf8_to_mbcs(const char *zUtf8){ +#if SQLITE_OS_WIN + size_t n; /* Bytes in zUtf8 */ + int nWide; /* number of UTF-16 characters */ + int nMbcs; /* Bytes of MBCS */ + LPWSTR zTmpWide; /* The UTF16 text */ + char *zMbcs; /* The MBCS text */ + int codepage; /* Code page used by fopen() */ + + n = strlen(zUtf8); + nWide = MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, NULL, 0); + if( nWide==0 ) return 0; + zTmpWide = (LPWSTR)sqlite3_malloc( (nWide+1)*sizeof(zTmpWide[0]) ); + if( zTmpWide==0 ) return 0; + MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, zTmpWide, nWide); + codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; + nMbcs = WideCharToMultiByte(codepage, 0, zTmpWide, nWide, 0, 0, 0, 0); + zMbcs = nMbcs ? (char*)sqlite3_malloc( nMbcs+1 ) : 0; + if( zMbcs ){ + WideCharToMultiByte(codepage, 0, zTmpWide, nWide, zMbcs, nMbcs, 0, 0); + } + sqlite3_free(zTmpWide); + return zMbcs; +#else + return (char*)zUtf8; /* No-op on unix */ +#endif +} + +/* +** Deallocate any memory allocated by quota_utf8_to_mbcs(). +*/ +static void quota_mbcs_free(char *zOld){ +#if SQLITE_OS_WIN + sqlite3_free(zOld); +#else + /* No-op on unix */ +#endif +} + +/************************* VFS Method Wrappers *****************************/ +/* +** This is the xOpen method used for the "quota" VFS. +** +** Most of the work is done by the underlying original VFS. This method +** simply links the new file into the appropriate quota group if it is a +** file that needs to be tracked. +*/ +static int quotaOpen( + sqlite3_vfs *pVfs, /* The quota VFS */ + const char *zName, /* Name of file to be opened */ + sqlite3_file *pConn, /* Fill in this file descriptor */ + int flags, /* Flags to control the opening */ + int *pOutFlags /* Flags showing results of opening */ +){ + int rc; /* Result code */ + quotaConn *pQuotaOpen; /* The new quota file descriptor */ + quotaFile *pFile; /* Corresponding quotaFile obj */ + quotaGroup *pGroup; /* The group file belongs to */ + sqlite3_file *pSubOpen; /* Real file descriptor */ + sqlite3_vfs *pOrigVfs = gQuota.pOrigVfs; /* Real VFS */ + + /* If the file is not a main database file or a WAL, then use the + ** normal xOpen method. + */ + if( (flags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_WAL))==0 ){ + return pOrigVfs->xOpen(pOrigVfs, zName, pConn, flags, pOutFlags); + } + + /* If the name of the file does not match any quota group, then + ** use the normal xOpen method. + */ + quotaEnter(); + pGroup = quotaGroupFind(zName); + if( pGroup==0 ){ + rc = pOrigVfs->xOpen(pOrigVfs, zName, pConn, flags, pOutFlags); + }else{ + /* If we get to this point, it means the file needs to be quota tracked. + */ + pQuotaOpen = (quotaConn*)pConn; + pSubOpen = quotaSubOpen(pConn); + rc = pOrigVfs->xOpen(pOrigVfs, zName, pSubOpen, flags, pOutFlags); + if( rc==SQLITE_OK ){ + pFile = quotaFindFile(pGroup, zName, 1); + if( pFile==0 ){ + quotaLeave(); + pSubOpen->pMethods->xClose(pSubOpen); + return SQLITE_NOMEM; + } + pFile->deleteOnClose = (flags & SQLITE_OPEN_DELETEONCLOSE)!=0; + pFile->nRef++; + pQuotaOpen->pFile = pFile; + if( pSubOpen->pMethods->iVersion==1 ){ + pQuotaOpen->base.pMethods = &gQuota.sIoMethodsV1; + }else{ + pQuotaOpen->base.pMethods = &gQuota.sIoMethodsV2; + } + } + } + quotaLeave(); + return rc; +} + +/* +** This is the xDelete method used for the "quota" VFS. +** +** If the file being deleted is part of the quota group, then reduce +** the size of the quota group accordingly. And remove the file from +** the set of files in the quota group. +*/ +static int quotaDelete( + sqlite3_vfs *pVfs, /* The quota VFS */ + const char *zName, /* Name of file to be deleted */ + int syncDir /* Do a directory sync after deleting */ +){ + int rc; /* Result code */ + quotaFile *pFile; /* Files in the quota */ + quotaGroup *pGroup; /* The group file belongs to */ + sqlite3_vfs *pOrigVfs = gQuota.pOrigVfs; /* Real VFS */ + + /* Do the actual file delete */ + rc = pOrigVfs->xDelete(pOrigVfs, zName, syncDir); + + /* If the file just deleted is a member of a quota group, then remove + ** it from that quota group. + */ + if( rc==SQLITE_OK ){ + quotaEnter(); + pGroup = quotaGroupFind(zName); + if( pGroup ){ + pFile = quotaFindFile(pGroup, zName, 0); + if( pFile ){ + if( pFile->nRef ){ + pFile->deleteOnClose = 1; + }else{ + quotaRemoveFile(pFile); + quotaGroupDeref(pGroup); + } + } + } + quotaLeave(); + } + return rc; +} + + +/************************ I/O Method Wrappers *******************************/ + +/* xClose requests get passed through to the original VFS. But we +** also have to unlink the quotaConn from the quotaFile and quotaGroup. +** The quotaFile and/or quotaGroup are freed if they are no longer in use. +*/ +static int quotaClose(sqlite3_file *pConn){ + quotaConn *p = (quotaConn*)pConn; + quotaFile *pFile = p->pFile; + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + int rc; + rc = pSubOpen->pMethods->xClose(pSubOpen); + quotaEnter(); + pFile->nRef--; + if( pFile->nRef==0 ){ + quotaGroup *pGroup = pFile->pGroup; + if( pFile->deleteOnClose ){ + gQuota.pOrigVfs->xDelete(gQuota.pOrigVfs, pFile->zFilename, 0); + quotaRemoveFile(pFile); + } + quotaGroupDeref(pGroup); + } + quotaLeave(); + return rc; +} + +/* Pass xRead requests directory thru to the original VFS without +** further processing. +*/ +static int quotaRead( + sqlite3_file *pConn, + void *pBuf, + int iAmt, + sqlite3_int64 iOfst +){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt, iOfst); +} + +/* Check xWrite requests to see if they expand the file. If they do, +** the perform a quota check before passing them through to the +** original VFS. +*/ +static int quotaWrite( + sqlite3_file *pConn, + const void *pBuf, + int iAmt, + sqlite3_int64 iOfst +){ + quotaConn *p = (quotaConn*)pConn; + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + sqlite3_int64 iEnd = iOfst+iAmt; + quotaGroup *pGroup; + quotaFile *pFile = p->pFile; + sqlite3_int64 szNew; + + if( pFile->iSizepGroup; + quotaEnter(); + szNew = pGroup->iSize - pFile->iSize + iEnd; + if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){ + if( pGroup->xCallback ){ + pGroup->xCallback(pFile->zFilename, &pGroup->iLimit, szNew, + pGroup->pArg); + } + if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){ + quotaLeave(); + return SQLITE_FULL; + } + } + pGroup->iSize = szNew; + pFile->iSize = iEnd; + quotaLeave(); + } + return pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt, iOfst); +} + +/* Pass xTruncate requests thru to the original VFS. If the +** success, update the file size. +*/ +static int quotaTruncate(sqlite3_file *pConn, sqlite3_int64 size){ + quotaConn *p = (quotaConn*)pConn; + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + int rc = pSubOpen->pMethods->xTruncate(pSubOpen, size); + quotaFile *pFile = p->pFile; + quotaGroup *pGroup; + if( rc==SQLITE_OK ){ + quotaEnter(); + pGroup = pFile->pGroup; + pGroup->iSize -= pFile->iSize; + pFile->iSize = size; + pGroup->iSize += size; + quotaLeave(); + } + return rc; +} + +/* Pass xSync requests through to the original VFS without change +*/ +static int quotaSync(sqlite3_file *pConn, int flags){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xSync(pSubOpen, flags); +} + +/* Pass xFileSize requests through to the original VFS but then +** update the quotaGroup with the new size before returning. +*/ +static int quotaFileSize(sqlite3_file *pConn, sqlite3_int64 *pSize){ + quotaConn *p = (quotaConn*)pConn; + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + quotaFile *pFile = p->pFile; + quotaGroup *pGroup; + sqlite3_int64 sz; + int rc; + + rc = pSubOpen->pMethods->xFileSize(pSubOpen, &sz); + if( rc==SQLITE_OK ){ + quotaEnter(); + pGroup = pFile->pGroup; + pGroup->iSize -= pFile->iSize; + pFile->iSize = sz; + pGroup->iSize += sz; + quotaLeave(); + *pSize = sz; + } + return rc; +} + +/* Pass xLock requests through to the original VFS unchanged. +*/ +static int quotaLock(sqlite3_file *pConn, int lock){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xLock(pSubOpen, lock); +} + +/* Pass xUnlock requests through to the original VFS unchanged. +*/ +static int quotaUnlock(sqlite3_file *pConn, int lock){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xUnlock(pSubOpen, lock); +} + +/* Pass xCheckReservedLock requests through to the original VFS unchanged. +*/ +static int quotaCheckReservedLock(sqlite3_file *pConn, int *pResOut){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xCheckReservedLock(pSubOpen, pResOut); +} + +/* Pass xFileControl requests through to the original VFS unchanged. +*/ +static int quotaFileControl(sqlite3_file *pConn, int op, void *pArg){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + int rc = pSubOpen->pMethods->xFileControl(pSubOpen, op, pArg); +#if defined(SQLITE_FCNTL_VFSNAME) + if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){ + *(char**)pArg = sqlite3_mprintf("quota/%z", *(char**)pArg); + } +#endif + return rc; +} + +/* Pass xSectorSize requests through to the original VFS unchanged. +*/ +static int quotaSectorSize(sqlite3_file *pConn){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xSectorSize(pSubOpen); +} + +/* Pass xDeviceCharacteristics requests through to the original VFS unchanged. +*/ +static int quotaDeviceCharacteristics(sqlite3_file *pConn){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xDeviceCharacteristics(pSubOpen); +} + +/* Pass xShmMap requests through to the original VFS unchanged. +*/ +static int quotaShmMap( + sqlite3_file *pConn, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int szRegion, /* Size of regions */ + int bExtend, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xShmMap(pSubOpen, iRegion, szRegion, bExtend, pp); +} + +/* Pass xShmLock requests through to the original VFS unchanged. +*/ +static int quotaShmLock( + sqlite3_file *pConn, /* Database file holding the shared memory */ + int ofst, /* First lock to acquire or release */ + int n, /* Number of locks to acquire or release */ + int flags /* What to do with the lock */ +){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xShmLock(pSubOpen, ofst, n, flags); +} + +/* Pass xShmBarrier requests through to the original VFS unchanged. +*/ +static void quotaShmBarrier(sqlite3_file *pConn){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + pSubOpen->pMethods->xShmBarrier(pSubOpen); +} + +/* Pass xShmUnmap requests through to the original VFS unchanged. +*/ +static int quotaShmUnmap(sqlite3_file *pConn, int deleteFlag){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xShmUnmap(pSubOpen, deleteFlag); +} + +/************************** Public Interfaces *****************************/ +/* +** Initialize the quota VFS shim. Use the VFS named zOrigVfsName +** as the VFS that does the actual work. Use the default if +** zOrigVfsName==NULL. +** +** The quota VFS shim is named "quota". It will become the default +** VFS if makeDefault is non-zero. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once +** during start-up. +*/ +int sqlite3_quota_initialize(const char *zOrigVfsName, int makeDefault){ + sqlite3_vfs *pOrigVfs; + if( gQuota.isInitialized ) return SQLITE_MISUSE; + pOrigVfs = sqlite3_vfs_find(zOrigVfsName); + if( pOrigVfs==0 ) return SQLITE_ERROR; + assert( pOrigVfs!=&gQuota.sThisVfs ); + gQuota.pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( !gQuota.pMutex ){ + return SQLITE_NOMEM; + } + gQuota.isInitialized = 1; + gQuota.pOrigVfs = pOrigVfs; + gQuota.sThisVfs = *pOrigVfs; + gQuota.sThisVfs.xOpen = quotaOpen; + gQuota.sThisVfs.xDelete = quotaDelete; + gQuota.sThisVfs.szOsFile += sizeof(quotaConn); + gQuota.sThisVfs.zName = "quota"; + gQuota.sIoMethodsV1.iVersion = 1; + gQuota.sIoMethodsV1.xClose = quotaClose; + gQuota.sIoMethodsV1.xRead = quotaRead; + gQuota.sIoMethodsV1.xWrite = quotaWrite; + gQuota.sIoMethodsV1.xTruncate = quotaTruncate; + gQuota.sIoMethodsV1.xSync = quotaSync; + gQuota.sIoMethodsV1.xFileSize = quotaFileSize; + gQuota.sIoMethodsV1.xLock = quotaLock; + gQuota.sIoMethodsV1.xUnlock = quotaUnlock; + gQuota.sIoMethodsV1.xCheckReservedLock = quotaCheckReservedLock; + gQuota.sIoMethodsV1.xFileControl = quotaFileControl; + gQuota.sIoMethodsV1.xSectorSize = quotaSectorSize; + gQuota.sIoMethodsV1.xDeviceCharacteristics = quotaDeviceCharacteristics; + gQuota.sIoMethodsV2 = gQuota.sIoMethodsV1; + gQuota.sIoMethodsV2.iVersion = 2; + gQuota.sIoMethodsV2.xShmMap = quotaShmMap; + gQuota.sIoMethodsV2.xShmLock = quotaShmLock; + gQuota.sIoMethodsV2.xShmBarrier = quotaShmBarrier; + gQuota.sIoMethodsV2.xShmUnmap = quotaShmUnmap; + sqlite3_vfs_register(&gQuota.sThisVfs, makeDefault); + return SQLITE_OK; +} + +/* +** Shutdown the quota system. +** +** All SQLite database connections must be closed before calling this +** routine. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once while +** shutting down in order to free all remaining quota groups. +*/ +int sqlite3_quota_shutdown(void){ + quotaGroup *pGroup; + if( gQuota.isInitialized==0 ) return SQLITE_MISUSE; + for(pGroup=gQuota.pGroup; pGroup; pGroup=pGroup->pNext){ + if( quotaGroupOpenFileCount(pGroup)>0 ) return SQLITE_MISUSE; + } + while( gQuota.pGroup ){ + pGroup = gQuota.pGroup; + gQuota.pGroup = pGroup->pNext; + pGroup->iLimit = 0; + assert( quotaGroupOpenFileCount(pGroup)==0 ); + quotaGroupDeref(pGroup); + } + gQuota.isInitialized = 0; + sqlite3_mutex_free(gQuota.pMutex); + sqlite3_vfs_unregister(&gQuota.sThisVfs); + memset(&gQuota, 0, sizeof(gQuota)); + return SQLITE_OK; +} + +/* +** Create or destroy a quota group. +** +** The quota group is defined by the zPattern. When calling this routine +** with a zPattern for a quota group that already exists, this routine +** merely updates the iLimit, xCallback, and pArg values for that quota +** group. If zPattern is new, then a new quota group is created. +** +** If the iLimit for a quota group is set to zero, then the quota group +** is disabled and will be deleted when the last database connection using +** the quota group is closed. +** +** Calling this routine on a zPattern that does not exist and with a +** zero iLimit is a no-op. +** +** A quota group must exist with a non-zero iLimit prior to opening +** database connections if those connections are to participate in the +** quota group. Creating a quota group does not affect database connections +** that are already open. +*/ +int sqlite3_quota_set( + const char *zPattern, /* The filename pattern */ + sqlite3_int64 iLimit, /* New quota to set for this quota group */ + void (*xCallback)( /* Callback invoked when going over quota */ + const char *zFilename, /* Name of file whose size increases */ + sqlite3_int64 *piLimit, /* IN/OUT: The current limit */ + sqlite3_int64 iSize, /* Total size of all files in the group */ + void *pArg /* Client data */ + ), + void *pArg, /* client data passed thru to callback */ + void (*xDestroy)(void*) /* Optional destructor for pArg */ +){ + quotaGroup *pGroup; + quotaEnter(); + pGroup = gQuota.pGroup; + while( pGroup && strcmp(pGroup->zPattern, zPattern)!=0 ){ + pGroup = pGroup->pNext; + } + if( pGroup==0 ){ + int nPattern = (int)(strlen(zPattern) & 0x3fffffff); + if( iLimit<=0 ){ + quotaLeave(); + return SQLITE_OK; + } + pGroup = (quotaGroup *)sqlite3_malloc( sizeof(*pGroup) + nPattern + 1 ); + if( pGroup==0 ){ + quotaLeave(); + return SQLITE_NOMEM; + } + memset(pGroup, 0, sizeof(*pGroup)); + pGroup->zPattern = (char*)&pGroup[1]; + memcpy((char *)pGroup->zPattern, zPattern, nPattern+1); + if( gQuota.pGroup ) gQuota.pGroup->ppPrev = &pGroup->pNext; + pGroup->pNext = gQuota.pGroup; + pGroup->ppPrev = &gQuota.pGroup; + gQuota.pGroup = pGroup; + } + pGroup->iLimit = iLimit; + pGroup->xCallback = xCallback; + if( pGroup->xDestroy && pGroup->pArg!=pArg ){ + pGroup->xDestroy(pGroup->pArg); + } + pGroup->pArg = pArg; + pGroup->xDestroy = xDestroy; + quotaGroupDeref(pGroup); + quotaLeave(); + return SQLITE_OK; +} + +/* +** Bring the named file under quota management. Or if it is already under +** management, update its size. +*/ +int sqlite3_quota_file(const char *zFilename){ + char *zFull; + sqlite3_file *fd; + int rc; + int outFlags = 0; + sqlite3_int64 iSize; + int nAlloc = gQuota.sThisVfs.szOsFile + gQuota.sThisVfs.mxPathname+2; + + /* Allocate space for a file-handle and the full path for file zFilename */ + fd = (sqlite3_file *)sqlite3_malloc(nAlloc); + if( fd==0 ){ + rc = SQLITE_NOMEM; + }else{ + zFull = &((char *)fd)[gQuota.sThisVfs.szOsFile]; + rc = gQuota.pOrigVfs->xFullPathname(gQuota.pOrigVfs, zFilename, + gQuota.sThisVfs.mxPathname+1, zFull); + } + + if( rc==SQLITE_OK ){ + zFull[strlen(zFull)+1] = '\0'; + rc = quotaOpen(&gQuota.sThisVfs, zFull, fd, + SQLITE_OPEN_READONLY | SQLITE_OPEN_MAIN_DB, &outFlags); + if( rc==SQLITE_OK ){ + fd->pMethods->xFileSize(fd, &iSize); + fd->pMethods->xClose(fd); + }else if( rc==SQLITE_CANTOPEN ){ + quotaGroup *pGroup; + quotaFile *pFile; + quotaEnter(); + pGroup = quotaGroupFind(zFull); + if( pGroup ){ + pFile = quotaFindFile(pGroup, zFull, 0); + if( pFile ) quotaRemoveFile(pFile); + } + quotaLeave(); + } + } + + sqlite3_free(fd); + return rc; +} + +/* +** Open a potentially quotaed file for I/O. +*/ +quota_FILE *sqlite3_quota_fopen(const char *zFilename, const char *zMode){ + quota_FILE *p = 0; + char *zFull = 0; + char *zFullTranslated = 0; + int rc; + quotaGroup *pGroup; + quotaFile *pFile; + + zFull = (char*)sqlite3_malloc(gQuota.sThisVfs.mxPathname + 1); + if( zFull==0 ) return 0; + rc = gQuota.pOrigVfs->xFullPathname(gQuota.pOrigVfs, zFilename, + gQuota.sThisVfs.mxPathname+1, zFull); + if( rc ) goto quota_fopen_error; + p = (quota_FILE*)sqlite3_malloc(sizeof(*p)); + if( p==0 ) goto quota_fopen_error; + memset(p, 0, sizeof(*p)); + zFullTranslated = quota_utf8_to_mbcs(zFull); + if( zFullTranslated==0 ) goto quota_fopen_error; + p->f = fopen(zFullTranslated, zMode); + if( p->f==0 ) goto quota_fopen_error; + quotaEnter(); + pGroup = quotaGroupFind(zFull); + if( pGroup ){ + pFile = quotaFindFile(pGroup, zFull, 1); + if( pFile==0 ){ + quotaLeave(); + goto quota_fopen_error; + } + pFile->nRef++; + p->pFile = pFile; + } + quotaLeave(); + sqlite3_free(zFull); +#if SQLITE_OS_WIN + p->zMbcsName = zFullTranslated; +#endif + return p; + +quota_fopen_error: + quota_mbcs_free(zFullTranslated); + sqlite3_free(zFull); + if( p && p->f ) fclose(p->f); + sqlite3_free(p); + return 0; +} + +/* +** Read content from a quota_FILE +*/ +size_t sqlite3_quota_fread( + void *pBuf, /* Store the content here */ + size_t size, /* Size of each element */ + size_t nmemb, /* Number of elements to read */ + quota_FILE *p /* Read from this quota_FILE object */ +){ + return fread(pBuf, size, nmemb, p->f); +} + +/* +** Write content into a quota_FILE. Invoke the quota callback and block +** the write if we exceed quota. +*/ +size_t sqlite3_quota_fwrite( + const void *pBuf, /* Take content to write from here */ + size_t size, /* Size of each element */ + size_t nmemb, /* Number of elements */ + quota_FILE *p /* Write to this quota_FILE objecct */ +){ + sqlite3_int64 iOfst; + sqlite3_int64 iEnd; + sqlite3_int64 szNew; + quotaFile *pFile; + size_t rc; + + iOfst = ftell(p->f); + iEnd = iOfst + size*nmemb; + pFile = p->pFile; + if( pFile && pFile->iSizepGroup; + quotaEnter(); + szNew = pGroup->iSize - pFile->iSize + iEnd; + if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){ + if( pGroup->xCallback ){ + pGroup->xCallback(pFile->zFilename, &pGroup->iLimit, szNew, + pGroup->pArg); + } + if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){ + iEnd = pGroup->iLimit - pGroup->iSize + pFile->iSize; + nmemb = (size_t)((iEnd - iOfst)/size); + iEnd = iOfst + size*nmemb; + szNew = pGroup->iSize - pFile->iSize + iEnd; + } + } + pGroup->iSize = szNew; + pFile->iSize = iEnd; + quotaLeave(); + }else{ + pFile = 0; + } + rc = fwrite(pBuf, size, nmemb, p->f); + + /* If the write was incomplete, adjust the file size and group size + ** downward */ + if( rcpGroup->iSize += iNewEnd - pFile->iSize; + pFile->iSize = iNewEnd; + quotaLeave(); + } + return rc; +} + +/* +** Close an open quota_FILE stream. +*/ +int sqlite3_quota_fclose(quota_FILE *p){ + int rc; + quotaFile *pFile; + rc = fclose(p->f); + pFile = p->pFile; + if( pFile ){ + quotaEnter(); + pFile->nRef--; + if( pFile->nRef==0 ){ + quotaGroup *pGroup = pFile->pGroup; + if( pFile->deleteOnClose ){ + gQuota.pOrigVfs->xDelete(gQuota.pOrigVfs, pFile->zFilename, 0); + quotaRemoveFile(pFile); + } + quotaGroupDeref(pGroup); + } + quotaLeave(); + } +#if SQLITE_OS_WIN + quota_mbcs_free(p->zMbcsName); +#endif + sqlite3_free(p); + return rc; +} + +/* +** Flush memory buffers for a quota_FILE to disk. +*/ +int sqlite3_quota_fflush(quota_FILE *p, int doFsync){ + int rc; + rc = fflush(p->f); + if( rc==0 && doFsync ){ +#if SQLITE_OS_UNIX + rc = fsync(fileno(p->f)); +#endif +#if SQLITE_OS_WIN + rc = _commit(_fileno(p->f)); +#endif + } + return rc!=0; +} + +/* +** Seek on a quota_FILE stream. +*/ +int sqlite3_quota_fseek(quota_FILE *p, long offset, int whence){ + return fseek(p->f, offset, whence); +} + +/* +** rewind a quota_FILE stream. +*/ +void sqlite3_quota_rewind(quota_FILE *p){ + rewind(p->f); +} + +/* +** Tell the current location of a quota_FILE stream. +*/ +long sqlite3_quota_ftell(quota_FILE *p){ + return ftell(p->f); +} + +/* +** Test the error indicator for the given file. +*/ +int sqlite3_quota_ferror(quota_FILE *p){ + return ferror(p->f); +} + +/* +** Truncate a file to szNew bytes. +*/ +int sqlite3_quota_ftruncate(quota_FILE *p, sqlite3_int64 szNew){ + quotaFile *pFile = p->pFile; + int rc; + if( (pFile = p->pFile)!=0 && pFile->iSizeiSizepGroup; + quotaEnter(); + pGroup->iSize += szNew - pFile->iSize; + quotaLeave(); + } +#if SQLITE_OS_UNIX + rc = ftruncate(fileno(p->f), szNew); +#endif +#if SQLITE_OS_WIN +# if defined(__MINGW32__) && defined(SQLITE_TEST) + /* _chsize_s() is missing from MingW (as of 2012-11-06). Use + ** _chsize() as a work-around for testing purposes. */ + rc = _chsize(_fileno(p->f), (long)szNew); +# else + rc = _chsize_s(_fileno(p->f), szNew); +# endif +#endif + if( pFile && rc==0 ){ + quotaGroup *pGroup = pFile->pGroup; + quotaEnter(); + pGroup->iSize += szNew - pFile->iSize; + pFile->iSize = szNew; + quotaLeave(); + } + return rc; +} + +/* +** Determine the time that the given file was last modified, in +** seconds size 1970. Write the result into *pTime. Return 0 on +** success and non-zero on any kind of error. +*/ +int sqlite3_quota_file_mtime(quota_FILE *p, time_t *pTime){ + int rc; +#if SQLITE_OS_UNIX + struct stat buf; + rc = fstat(fileno(p->f), &buf); +#endif +#if SQLITE_OS_WIN + struct _stati64 buf; + rc = _stati64(p->zMbcsName, &buf); +#endif + if( rc==0 ) *pTime = buf.st_mtime; + return rc; +} + +/* +** Return the true size of the file, as reported by the operating +** system. +*/ +sqlite3_int64 sqlite3_quota_file_truesize(quota_FILE *p){ + int rc; +#if SQLITE_OS_UNIX + struct stat buf; + rc = fstat(fileno(p->f), &buf); +#endif +#if SQLITE_OS_WIN + struct _stati64 buf; + rc = _stati64(p->zMbcsName, &buf); +#endif + return rc==0 ? buf.st_size : -1; +} + +/* +** Return the size of the file, as it is known to the quota subsystem. +*/ +sqlite3_int64 sqlite3_quota_file_size(quota_FILE *p){ + return p->pFile ? p->pFile->iSize : -1; +} + +/* +** Determine the amount of data in bytes available for reading +** in the given file. +*/ +long sqlite3_quota_file_available(quota_FILE *p){ + FILE* f = p->f; + long pos1, pos2; + int rc; + pos1 = ftell(f); + if ( pos1 < 0 ) return -1; + rc = fseek(f, 0, SEEK_END); + if ( rc != 0 ) return -1; + pos2 = ftell(f); + if ( pos2 < 0 ) return -1; + rc = fseek(f, pos1, SEEK_SET); + if ( rc != 0 ) return -1; + return pos2 - pos1; +} + +/* +** Remove a managed file. Update quotas accordingly. +*/ +int sqlite3_quota_remove(const char *zFilename){ + char *zFull; /* Full pathname for zFilename */ + size_t nFull; /* Number of bytes in zFilename */ + int rc; /* Result code */ + quotaGroup *pGroup; /* Group containing zFilename */ + quotaFile *pFile; /* A file in the group */ + quotaFile *pNextFile; /* next file in the group */ + int diff; /* Difference between filenames */ + char c; /* First character past end of pattern */ + + zFull = (char*)sqlite3_malloc(gQuota.sThisVfs.mxPathname + 1); + if( zFull==0 ) return SQLITE_NOMEM; + rc = gQuota.pOrigVfs->xFullPathname(gQuota.pOrigVfs, zFilename, + gQuota.sThisVfs.mxPathname+1, zFull); + if( rc ){ + sqlite3_free(zFull); + return rc; + } + + /* Figure out the length of the full pathname. If the name ends with + ** / (or \ on windows) then remove the trailing /. + */ + nFull = strlen(zFull); + if( nFull>0 && (zFull[nFull-1]=='/' || zFull[nFull-1]=='\\') ){ + nFull--; + zFull[nFull] = 0; + } + + quotaEnter(); + pGroup = quotaGroupFind(zFull); + if( pGroup ){ + for(pFile=pGroup->pFiles; pFile && rc==SQLITE_OK; pFile=pNextFile){ + pNextFile = pFile->pNext; + diff = strncmp(zFull, pFile->zFilename, nFull); + if( diff==0 && ((c = pFile->zFilename[nFull])==0 || c=='/' || c=='\\') ){ + if( pFile->nRef ){ + pFile->deleteOnClose = 1; + }else{ + rc = gQuota.pOrigVfs->xDelete(gQuota.pOrigVfs, pFile->zFilename, 0); + quotaRemoveFile(pFile); + quotaGroupDeref(pGroup); + } + } + } + } + quotaLeave(); + sqlite3_free(zFull); + return rc; +} + +/***************************** Test Code ***********************************/ +#ifdef SQLITE_TEST +#include + +/* +** Argument passed to a TCL quota-over-limit callback. +*/ +typedef struct TclQuotaCallback TclQuotaCallback; +struct TclQuotaCallback { + Tcl_Interp *interp; /* Interpreter in which to run the script */ + Tcl_Obj *pScript; /* Script to be run */ +}; + +extern const char *sqlite3ErrName(int); + + +/* +** This is the callback from a quota-over-limit. +*/ +static void tclQuotaCallback( + const char *zFilename, /* Name of file whose size increases */ + sqlite3_int64 *piLimit, /* IN/OUT: The current limit */ + sqlite3_int64 iSize, /* Total size of all files in the group */ + void *pArg /* Client data */ +){ + TclQuotaCallback *p; /* Callback script object */ + Tcl_Obj *pEval; /* Script to evaluate */ + Tcl_Obj *pVarname; /* Name of variable to pass as 2nd arg */ + unsigned int rnd; /* Random part of pVarname */ + int rc; /* Tcl error code */ + + p = (TclQuotaCallback *)pArg; + if( p==0 ) return; + + pVarname = Tcl_NewStringObj("::piLimit_", -1); + Tcl_IncrRefCount(pVarname); + sqlite3_randomness(sizeof(rnd), (void *)&rnd); + Tcl_AppendObjToObj(pVarname, Tcl_NewIntObj((int)(rnd&0x7FFFFFFF))); + Tcl_ObjSetVar2(p->interp, pVarname, 0, Tcl_NewWideIntObj(*piLimit), 0); + + pEval = Tcl_DuplicateObj(p->pScript); + Tcl_IncrRefCount(pEval); + Tcl_ListObjAppendElement(0, pEval, Tcl_NewStringObj(zFilename, -1)); + Tcl_ListObjAppendElement(0, pEval, pVarname); + Tcl_ListObjAppendElement(0, pEval, Tcl_NewWideIntObj(iSize)); + rc = Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL); + + if( rc==TCL_OK ){ + Tcl_WideInt x; + Tcl_Obj *pLimit = Tcl_ObjGetVar2(p->interp, pVarname, 0, 0); + rc = Tcl_GetWideIntFromObj(p->interp, pLimit, &x); + *piLimit = x; + Tcl_UnsetVar(p->interp, Tcl_GetString(pVarname), 0); + } + + Tcl_DecrRefCount(pEval); + Tcl_DecrRefCount(pVarname); + if( rc!=TCL_OK ) Tcl_BackgroundError(p->interp); +} + +/* +** Destructor for a TCL quota-over-limit callback. +*/ +static void tclCallbackDestructor(void *pObj){ + TclQuotaCallback *p = (TclQuotaCallback*)pObj; + if( p ){ + Tcl_DecrRefCount(p->pScript); + sqlite3_free((char *)p); + } +} + +/* +** tclcmd: sqlite3_quota_initialize NAME MAKEDEFAULT +*/ +static int test_quota_initialize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zName; /* Name of new quota VFS */ + int makeDefault; /* True to make the new VFS the default */ + int rc; /* Value returned by quota_initialize() */ + + /* Process arguments */ + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "NAME MAKEDEFAULT"); + return TCL_ERROR; + } + zName = Tcl_GetString(objv[1]); + if( Tcl_GetBooleanFromObj(interp, objv[2], &makeDefault) ) return TCL_ERROR; + if( zName[0]=='\0' ) zName = 0; + + /* Call sqlite3_quota_initialize() */ + rc = sqlite3_quota_initialize(zName, makeDefault); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_shutdown +*/ +static int test_quota_shutdown( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; /* Value returned by quota_shutdown() */ + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + /* Call sqlite3_quota_shutdown() */ + rc = sqlite3_quota_shutdown(); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_set PATTERN LIMIT SCRIPT +*/ +static int test_quota_set( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zPattern; /* File pattern to configure */ + Tcl_WideInt iLimit; /* Initial quota in bytes */ + Tcl_Obj *pScript; /* Tcl script to invoke to increase quota */ + int rc; /* Value returned by quota_set() */ + TclQuotaCallback *p; /* Callback object */ + int nScript; /* Length of callback script */ + void (*xDestroy)(void*); /* Optional destructor for pArg */ + void (*xCallback)(const char *, sqlite3_int64 *, sqlite3_int64, void *); + + /* Process arguments */ + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PATTERN LIMIT SCRIPT"); + return TCL_ERROR; + } + zPattern = Tcl_GetString(objv[1]); + if( Tcl_GetWideIntFromObj(interp, objv[2], &iLimit) ) return TCL_ERROR; + pScript = objv[3]; + Tcl_GetStringFromObj(pScript, &nScript); + + if( nScript>0 ){ + /* Allocate a TclQuotaCallback object */ + p = (TclQuotaCallback *)sqlite3_malloc(sizeof(TclQuotaCallback)); + if( !p ){ + Tcl_SetResult(interp, (char *)"SQLITE_NOMEM", TCL_STATIC); + return TCL_OK; + } + memset(p, 0, sizeof(TclQuotaCallback)); + p->interp = interp; + Tcl_IncrRefCount(pScript); + p->pScript = pScript; + xDestroy = tclCallbackDestructor; + xCallback = tclQuotaCallback; + }else{ + p = 0; + xDestroy = 0; + xCallback = 0; + } + + /* Invoke sqlite3_quota_set() */ + rc = sqlite3_quota_set(zPattern, iLimit, xCallback, (void*)p, xDestroy); + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file FILENAME +*/ +static int test_quota_file( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; /* File pattern to configure */ + int rc; /* Value returned by quota_file() */ + + /* Process arguments */ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } + zFilename = Tcl_GetString(objv[1]); + + /* Invoke sqlite3_quota_file() */ + rc = sqlite3_quota_file(zFilename); + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_dump +*/ +static int test_quota_dump( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Obj *pResult; + Tcl_Obj *pGroupTerm; + Tcl_Obj *pFileTerm; + quotaGroup *pGroup; + quotaFile *pFile; + + pResult = Tcl_NewObj(); + quotaEnter(); + for(pGroup=gQuota.pGroup; pGroup; pGroup=pGroup->pNext){ + pGroupTerm = Tcl_NewObj(); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewStringObj(pGroup->zPattern, -1)); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewWideIntObj(pGroup->iLimit)); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewWideIntObj(pGroup->iSize)); + for(pFile=pGroup->pFiles; pFile; pFile=pFile->pNext){ + int i; + char zTemp[1000]; + pFileTerm = Tcl_NewObj(); + sqlite3_snprintf(sizeof(zTemp), zTemp, "%s", pFile->zFilename); + for(i=0; zTemp[i]; i++){ if( zTemp[i]=='\\' ) zTemp[i] = '/'; } + Tcl_ListObjAppendElement(interp, pFileTerm, + Tcl_NewStringObj(zTemp, -1)); + Tcl_ListObjAppendElement(interp, pFileTerm, + Tcl_NewWideIntObj(pFile->iSize)); + Tcl_ListObjAppendElement(interp, pFileTerm, + Tcl_NewWideIntObj(pFile->nRef)); + Tcl_ListObjAppendElement(interp, pFileTerm, + Tcl_NewWideIntObj(pFile->deleteOnClose)); + Tcl_ListObjAppendElement(interp, pGroupTerm, pFileTerm); + } + Tcl_ListObjAppendElement(interp, pResult, pGroupTerm); + } + quotaLeave(); + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fopen FILENAME MODE +*/ +static int test_quota_fopen( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; /* File pattern to configure */ + const char *zMode; /* Mode string */ + quota_FILE *p; /* Open string object */ + char zReturn[50]; /* Name of pointer to return */ + + /* Process arguments */ + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME MODE"); + return TCL_ERROR; + } + zFilename = Tcl_GetString(objv[1]); + zMode = Tcl_GetString(objv[2]); + p = sqlite3_quota_fopen(zFilename, zMode); + sqlite3_snprintf(sizeof(zReturn), zReturn, "%p", p); + Tcl_SetResult(interp, zReturn, TCL_VOLATILE); + return TCL_OK; +} + +/* Defined in test1.c */ +extern void *sqlite3TestTextToPtr(const char*); + +/* +** tclcmd: sqlite3_quota_fread HANDLE SIZE NELEM +*/ +static int test_quota_fread( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + char *zBuf; + int sz; + int nElem; + size_t got; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE SIZE NELEM"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( Tcl_GetIntFromObj(interp, objv[2], &sz) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &nElem) ) return TCL_ERROR; + zBuf = (char*)sqlite3_malloc( sz*nElem + 1 ); + if( zBuf==0 ){ + Tcl_SetResult(interp, "out of memory", TCL_STATIC); + return TCL_ERROR; + } + got = sqlite3_quota_fread(zBuf, sz, nElem, p); + zBuf[got*sz] = 0; + Tcl_SetResult(interp, zBuf, TCL_VOLATILE); + sqlite3_free(zBuf); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fwrite HANDLE SIZE NELEM CONTENT +*/ +static int test_quota_fwrite( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + char *zBuf; + int sz; + int nElem; + size_t got; + + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE SIZE NELEM CONTENT"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( Tcl_GetIntFromObj(interp, objv[2], &sz) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &nElem) ) return TCL_ERROR; + zBuf = Tcl_GetString(objv[4]); + got = sqlite3_quota_fwrite(zBuf, sz, nElem, p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(got)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fclose HANDLE +*/ +static int test_quota_fclose( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + rc = sqlite3_quota_fclose(p); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fflush HANDLE ?HARDSYNC? +*/ +static int test_quota_fflush( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + int rc; + int doSync = 0; + + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE ?HARDSYNC?"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( objc==3 ){ + if( Tcl_GetBooleanFromObj(interp, objv[2], &doSync) ) return TCL_ERROR; + } + rc = sqlite3_quota_fflush(p, doSync); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fseek HANDLE OFFSET WHENCE +*/ +static int test_quota_fseek( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + int ofst; + const char *zWhence; + int whence; + int rc; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE OFFSET WHENCE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( Tcl_GetIntFromObj(interp, objv[2], &ofst) ) return TCL_ERROR; + zWhence = Tcl_GetString(objv[3]); + if( strcmp(zWhence, "SEEK_SET")==0 ){ + whence = SEEK_SET; + }else if( strcmp(zWhence, "SEEK_CUR")==0 ){ + whence = SEEK_CUR; + }else if( strcmp(zWhence, "SEEK_END")==0 ){ + whence = SEEK_END; + }else{ + Tcl_AppendResult(interp, + "WHENCE should be SEEK_SET, SEEK_CUR, or SEEK_END", (char*)0); + return TCL_ERROR; + } + rc = sqlite3_quota_fseek(p, ofst, whence); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_rewind HANDLE +*/ +static int test_quota_rewind( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + sqlite3_quota_rewind(p); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_ftell HANDLE +*/ +static int test_quota_ftell( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_ftell(p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(x)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_ftruncate HANDLE SIZE +*/ +static int test_quota_ftruncate( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + Tcl_WideInt w; + int rc; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE SIZE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( Tcl_GetWideIntFromObj(interp, objv[2], &w) ) return TCL_ERROR; + x = (sqlite3_int64)w; + rc = sqlite3_quota_ftruncate(p, x); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file_size HANDLE +*/ +static int test_quota_file_size( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_file_size(p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(x)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file_truesize HANDLE +*/ +static int test_quota_file_truesize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_file_truesize(p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(x)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file_mtime HANDLE +*/ +static int test_quota_file_mtime( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + time_t t; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + t = 0; + sqlite3_quota_file_mtime(p, &t); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(t)); + return TCL_OK; +} + + +/* +** tclcmd: sqlite3_quota_remove FILENAME +*/ +static int test_quota_remove( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; /* File pattern to configure */ + int rc; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } + zFilename = Tcl_GetString(objv[1]); + rc = sqlite3_quota_remove(zFilename); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_glob PATTERN TEXT +** +** Test the glob pattern matching. Return 1 if TEXT matches PATTERN +** and return 0 if it does not. +*/ +static int test_quota_glob( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zPattern; /* The glob pattern */ + const char *zText; /* Text to compare agains the pattern */ + int rc; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PATTERN TEXT"); + return TCL_ERROR; + } + zPattern = Tcl_GetString(objv[1]); + zText = Tcl_GetString(objv[2]); + rc = quotaStrglob(zPattern, zText); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file_available HANDLE +** +** Return the number of bytes from the current file point to the end of +** the file. +*/ +static int test_quota_file_available( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_file_available(p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(x)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_ferror HANDLE +** +** Return true if the file handle is in the error state. +*/ +static int test_quota_ferror( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + int x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_ferror(p); + Tcl_SetObjResult(interp, Tcl_NewIntObj(x)); + return TCL_OK; +} + +/* +** This routine registers the custom TCL commands defined in this +** module. This should be the only procedure visible from outside +** of this module. +*/ +int Sqlitequota_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aCmd[] = { + { "sqlite3_quota_initialize", test_quota_initialize }, + { "sqlite3_quota_shutdown", test_quota_shutdown }, + { "sqlite3_quota_set", test_quota_set }, + { "sqlite3_quota_file", test_quota_file }, + { "sqlite3_quota_dump", test_quota_dump }, + { "sqlite3_quota_fopen", test_quota_fopen }, + { "sqlite3_quota_fread", test_quota_fread }, + { "sqlite3_quota_fwrite", test_quota_fwrite }, + { "sqlite3_quota_fclose", test_quota_fclose }, + { "sqlite3_quota_fflush", test_quota_fflush }, + { "sqlite3_quota_fseek", test_quota_fseek }, + { "sqlite3_quota_rewind", test_quota_rewind }, + { "sqlite3_quota_ftell", test_quota_ftell }, + { "sqlite3_quota_ftruncate", test_quota_ftruncate }, + { "sqlite3_quota_file_size", test_quota_file_size }, + { "sqlite3_quota_file_truesize", test_quota_file_truesize }, + { "sqlite3_quota_file_mtime", test_quota_file_mtime }, + { "sqlite3_quota_remove", test_quota_remove }, + { "sqlite3_quota_glob", test_quota_glob }, + { "sqlite3_quota_file_available",test_quota_file_available }, + { "sqlite3_quota_ferror", test_quota_ferror }, + }; + int i; + + for(i=0; i +#include +#include +#if SQLITE_OS_UNIX +# include +#endif +#if SQLITE_OS_WIN +# include +#endif + +/* Make this callable from C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Initialize the quota VFS shim. Use the VFS named zOrigVfsName +** as the VFS that does the actual work. Use the default if +** zOrigVfsName==NULL. +** +** The quota VFS shim is named "quota". It will become the default +** VFS if makeDefault is non-zero. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once +** during start-up. +*/ +int sqlite3_quota_initialize(const char *zOrigVfsName, int makeDefault); + +/* +** Shutdown the quota system. +** +** All SQLite database connections must be closed before calling this +** routine. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once while +** shutting down in order to free all remaining quota groups. +*/ +int sqlite3_quota_shutdown(void); + +/* +** Create or destroy a quota group. +** +** The quota group is defined by the zPattern. When calling this routine +** with a zPattern for a quota group that already exists, this routine +** merely updates the iLimit, xCallback, and pArg values for that quota +** group. If zPattern is new, then a new quota group is created. +** +** The zPattern is always compared against the full pathname of the file. +** Even if APIs are called with relative pathnames, SQLite converts the +** name to a full pathname before comparing it against zPattern. zPattern +** is a glob pattern with the following matching rules: +** +** '*' Matches any sequence of zero or more characters. +** +** '?' Matches exactly one character. +** +** [...] Matches one character from the enclosed list of +** characters. "]" can be part of the list if it is +** the first character. Within the list "X-Y" matches +** characters X or Y or any character in between the +** two. Ex: "[0-9]" matches any digit. +** +** [^...] Matches one character not in the enclosed list. +** +** / Matches either / or \. This allows glob patterns +** containing / to work on both unix and windows. +** +** Note that, unlike unix shell globbing, the directory separator "/" +** can match a wildcard. So, for example, the pattern "/abc/xyz/" "*" +** matches any files anywhere in the directory hierarchy beneath +** /abc/xyz. +** +** The glob algorithm works on bytes. Multi-byte UTF8 characters are +** matched as if each byte were a separate character. +** +** If the iLimit for a quota group is set to zero, then the quota group +** is disabled and will be deleted when the last database connection using +** the quota group is closed. +** +** Calling this routine on a zPattern that does not exist and with a +** zero iLimit is a no-op. +** +** A quota group must exist with a non-zero iLimit prior to opening +** database connections if those connections are to participate in the +** quota group. Creating a quota group does not affect database connections +** that are already open. +** +** The patterns that define the various quota groups should be distinct. +** If the same filename matches more than one quota group pattern, then +** the behavior of this package is undefined. +*/ +int sqlite3_quota_set( + const char *zPattern, /* The filename pattern */ + sqlite3_int64 iLimit, /* New quota to set for this quota group */ + void (*xCallback)( /* Callback invoked when going over quota */ + const char *zFilename, /* Name of file whose size increases */ + sqlite3_int64 *piLimit, /* IN/OUT: The current limit */ + sqlite3_int64 iSize, /* Total size of all files in the group */ + void *pArg /* Client data */ + ), + void *pArg, /* client data passed thru to callback */ + void (*xDestroy)(void*) /* Optional destructor for pArg */ +); + +/* +** Bring the named file under quota management, assuming its name matches +** the glob pattern of some quota group. Or if it is already under +** management, update its size. If zFilename does not match the glob +** pattern of any quota group, this routine is a no-op. +*/ +int sqlite3_quota_file(const char *zFilename); + +/* +** The following object serves the same role as FILE in the standard C +** library. It represents an open connection to a file on disk for I/O. +** +** A single quota_FILE should not be used by two or more threads at the +** same time. Multiple threads can be using different quota_FILE objects +** simultaneously, but not the same quota_FILE object. +*/ +typedef struct quota_FILE quota_FILE; + +/* +** Create a new quota_FILE object used to read and/or write to the +** file zFilename. The zMode parameter is as with standard library zMode. +*/ +quota_FILE *sqlite3_quota_fopen(const char *zFilename, const char *zMode); + +/* +** Perform I/O against a quota_FILE object. When doing writes, the +** quota mechanism may result in a short write, in order to prevent +** the sum of sizes of all files from going over quota. +*/ +size_t sqlite3_quota_fread(void*, size_t, size_t, quota_FILE*); +size_t sqlite3_quota_fwrite(const void*, size_t, size_t, quota_FILE*); + +/* +** Flush all written content held in memory buffers out to disk. +** This is the equivalent of fflush() in the standard library. +** +** If the hardSync parameter is true (non-zero) then this routine +** also forces OS buffers to disk - the equivalent of fsync(). +** +** This routine return zero on success and non-zero if something goes +** wrong. +*/ +int sqlite3_quota_fflush(quota_FILE*, int hardSync); + +/* +** Close a quota_FILE object and free all associated resources. The +** file remains under quota management. +*/ +int sqlite3_quota_fclose(quota_FILE*); + +/* +** Move the read/write pointer for a quota_FILE object. Or tell the +** current location of the read/write pointer. +*/ +int sqlite3_quota_fseek(quota_FILE*, long, int); +void sqlite3_quota_rewind(quota_FILE*); +long sqlite3_quota_ftell(quota_FILE*); + +/* +** Test the error indicator for the given file. +** +** Return non-zero if the error indicator is set. +*/ +int sqlite3_quota_ferror(quota_FILE*); + +/* +** Truncate a file previously opened by sqlite3_quota_fopen(). Return +** zero on success and non-zero on any kind of failure. +** +** The newSize argument must be less than or equal to the current file size. +** Any attempt to "truncate" a file to a larger size results in +** undefined behavior. +*/ +int sqlite3_quota_ftruncate(quota_FILE*, sqlite3_int64 newSize); + +/* +** Return the last modification time of the opened file, in seconds +** since 1970. +*/ +int sqlite3_quota_file_mtime(quota_FILE*, time_t *pTime); + +/* +** Return the size of the file as it is known to the quota system. +** +** This size might be different from the true size of the file on +** disk if some outside process has modified the file without using the +** quota mechanism, or if calls to sqlite3_quota_fwrite() have occurred +** which have increased the file size, but those writes have not yet been +** forced to disk using sqlite3_quota_fflush(). +** +** Return -1 if the file is not participating in quota management. +*/ +sqlite3_int64 sqlite3_quota_file_size(quota_FILE*); + +/* +** Return the true size of the file. +** +** The true size should be the same as the size of the file as known +** to the quota system, however the sizes might be different if the +** file has been extended or truncated via some outside process or if +** pending writes have not yet been flushed to disk. +** +** Return -1 if the file does not exist or if the size of the file +** cannot be determined for some reason. +*/ +sqlite3_int64 sqlite3_quota_file_truesize(quota_FILE*); + +/* +** Determine the amount of data in bytes available for reading +** in the given file. +** +** Return -1 if the amount cannot be determined for some reason. +*/ +long sqlite3_quota_file_available(quota_FILE*); + +/* +** Delete a file from the disk, if that file is under quota management. +** Adjust quotas accordingly. +** +** If zFilename is the name of a directory that matches one of the +** quota glob patterns, then all files under quota management that +** are contained within that directory are deleted. +** +** A standard SQLite result code is returned (SQLITE_OK, SQLITE_NOMEM, etc.) +** When deleting a directory of files, if the deletion of any one +** file fails (for example due to an I/O error), then this routine +** returns immediately, with the error code, and does not try to +** delete any of the other files in the specified directory. +** +** All files are removed from quota management and deleted from disk. +** However, no attempt is made to remove empty directories. +** +** This routine is a no-op for files that are not under quota management. +*/ +int sqlite3_quota_remove(const char *zFilename); + +#ifdef __cplusplus +} /* end of the 'extern "C"' block */ +#endif +#endif /* _QUOTA_H_ */ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_rtree.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_rtree.c new file mode 100644 index 0000000000000000000000000000000000000000..e1966c243736b1c773c6fa515bdcee85063fbe57 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_rtree.c @@ -0,0 +1,305 @@ +/* +** 2010 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing all sorts of SQLite interfaces. This code +** is not included in the SQLite library. +*/ + +#include +#include + +/* Solely for the UNUSED_PARAMETER() macro. */ +#include "sqliteInt.h" + +#ifdef SQLITE_ENABLE_RTREE +/* +** Type used to cache parameter information for the "circle" r-tree geometry +** callback. +*/ +typedef struct Circle Circle; +struct Circle { + struct Box { + double xmin; + double xmax; + double ymin; + double ymax; + } aBox[2]; + double centerx; + double centery; + double radius; +}; + +/* +** Destructor function for Circle objects allocated by circle_geom(). +*/ +static void circle_del(void *p){ + sqlite3_free(p); +} + +/* +** Implementation of "circle" r-tree geometry callback. +*/ +static int circle_geom( + sqlite3_rtree_geometry *p, + int nCoord, +#ifdef SQLITE_RTREE_INT_ONLY + sqlite3_int64 *aCoord, +#else + double *aCoord, +#endif + int *pRes +){ + int i; /* Iterator variable */ + Circle *pCircle; /* Structure defining circular region */ + double xmin, xmax; /* X dimensions of box being tested */ + double ymin, ymax; /* X dimensions of box being tested */ + + if( p->pUser==0 ){ + /* If pUser is still 0, then the parameter values have not been tested + ** for correctness or stored into a Circle structure yet. Do this now. */ + + /* This geometry callback is for use with a 2-dimensional r-tree table. + ** Return an error if the table does not have exactly 2 dimensions. */ + if( nCoord!=4 ) return SQLITE_ERROR; + + /* Test that the correct number of parameters (3) have been supplied, + ** and that the parameters are in range (that the radius of the circle + ** radius is greater than zero). */ + if( p->nParam!=3 || p->aParam[2]<0.0 ) return SQLITE_ERROR; + + /* Allocate a structure to cache parameter data in. Return SQLITE_NOMEM + ** if the allocation fails. */ + pCircle = (Circle *)(p->pUser = sqlite3_malloc(sizeof(Circle))); + if( !pCircle ) return SQLITE_NOMEM; + p->xDelUser = circle_del; + + /* Record the center and radius of the circular region. One way that + ** tested bounding boxes that intersect the circular region are detected + ** is by testing if each corner of the bounding box lies within radius + ** units of the center of the circle. */ + pCircle->centerx = p->aParam[0]; + pCircle->centery = p->aParam[1]; + pCircle->radius = p->aParam[2]; + + /* Define two bounding box regions. The first, aBox[0], extends to + ** infinity in the X dimension. It covers the same range of the Y dimension + ** as the circular region. The second, aBox[1], extends to infinity in + ** the Y dimension and is constrained to the range of the circle in the + ** X dimension. + ** + ** Then imagine each box is split in half along its short axis by a line + ** that intersects the center of the circular region. A bounding box + ** being tested can be said to intersect the circular region if it contains + ** points from each half of either of the two infinite bounding boxes. + */ + pCircle->aBox[0].xmin = pCircle->centerx; + pCircle->aBox[0].xmax = pCircle->centerx; + pCircle->aBox[0].ymin = pCircle->centery + pCircle->radius; + pCircle->aBox[0].ymax = pCircle->centery - pCircle->radius; + pCircle->aBox[1].xmin = pCircle->centerx + pCircle->radius; + pCircle->aBox[1].xmax = pCircle->centerx - pCircle->radius; + pCircle->aBox[1].ymin = pCircle->centery; + pCircle->aBox[1].ymax = pCircle->centery; + } + + pCircle = (Circle *)p->pUser; + xmin = aCoord[0]; + xmax = aCoord[1]; + ymin = aCoord[2]; + ymax = aCoord[3]; + + /* Check if any of the 4 corners of the bounding-box being tested lie + ** inside the circular region. If they do, then the bounding-box does + ** intersect the region of interest. Set the output variable to true and + ** return SQLITE_OK in this case. */ + for(i=0; i<4; i++){ + double x = (i&0x01) ? xmax : xmin; + double y = (i&0x02) ? ymax : ymin; + double d2; + + d2 = (x-pCircle->centerx)*(x-pCircle->centerx); + d2 += (y-pCircle->centery)*(y-pCircle->centery); + if( d2<(pCircle->radius*pCircle->radius) ){ + *pRes = 1; + return SQLITE_OK; + } + } + + /* Check if the bounding box covers any other part of the circular region. + ** See comments above for a description of how this test works. If it does + ** cover part of the circular region, set the output variable to true + ** and return SQLITE_OK. */ + for(i=0; i<2; i++){ + if( xmin<=pCircle->aBox[i].xmin + && xmax>=pCircle->aBox[i].xmax + && ymin<=pCircle->aBox[i].ymin + && ymax>=pCircle->aBox[i].ymax + ){ + *pRes = 1; + return SQLITE_OK; + } + } + + /* The specified bounding box does not intersect the circular region. Set + ** the output variable to zero and return SQLITE_OK. */ + *pRes = 0; + return SQLITE_OK; +} + +/* END of implementation of "circle" geometry callback. +************************************************************************** +*************************************************************************/ + +#include +#include "tcl.h" + +typedef struct Cube Cube; +struct Cube { + double x; + double y; + double z; + double width; + double height; + double depth; +}; + +static void cube_context_free(void *p){ + sqlite3_free(p); +} + +/* +** The context pointer registered along with the 'cube' callback is +** always ((void *)&gHere). This is just to facilitate testing, it is not +** actually used for anything. +*/ +static int gHere = 42; + +/* +** Implementation of a simple r-tree geom callback to test for intersection +** of r-tree rows with a "cube" shape. Cubes are defined by six scalar +** coordinates as follows: +** +** cube(x, y, z, width, height, depth) +** +** The width, height and depth parameters must all be greater than zero. +*/ +static int cube_geom( + sqlite3_rtree_geometry *p, + int nCoord, +#ifdef SQLITE_RTREE_INT_ONLY + sqlite3_int64 *aCoord, +#else + double *aCoord, +#endif + int *piRes +){ + Cube *pCube = (Cube *)p->pUser; + + assert( p->pContext==(void *)&gHere ); + + if( pCube==0 ){ + if( p->nParam!=6 || nCoord!=6 + || p->aParam[3]<=0.0 || p->aParam[4]<=0.0 || p->aParam[5]<=0.0 + ){ + return SQLITE_ERROR; + } + pCube = (Cube *)sqlite3_malloc(sizeof(Cube)); + if( !pCube ){ + return SQLITE_NOMEM; + } + pCube->x = p->aParam[0]; + pCube->y = p->aParam[1]; + pCube->z = p->aParam[2]; + pCube->width = p->aParam[3]; + pCube->height = p->aParam[4]; + pCube->depth = p->aParam[5]; + + p->pUser = (void *)pCube; + p->xDelUser = cube_context_free; + } + + assert( nCoord==6 ); + *piRes = 0; + if( aCoord[0]<=(pCube->x+pCube->width) + && aCoord[1]>=pCube->x + && aCoord[2]<=(pCube->y+pCube->height) + && aCoord[3]>=pCube->y + && aCoord[4]<=(pCube->z+pCube->depth) + && aCoord[5]>=pCube->z + ){ + *piRes = 1; + } + + return SQLITE_OK; +} +#endif /* SQLITE_ENABLE_RTREE */ + +static int register_cube_geom( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_ENABLE_RTREE + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(interp); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); +#else + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + extern const char *sqlite3ErrName(int); + sqlite3 *db; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_rtree_geometry_callback(db, "cube", cube_geom, (void *)&gHere); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); +#endif + return TCL_OK; +} + +static int register_circle_geom( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_ENABLE_RTREE + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(interp); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); +#else + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + extern const char *sqlite3ErrName(int); + sqlite3 *db; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_rtree_geometry_callback(db, "circle", circle_geom, 0); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); +#endif + return TCL_OK; +} + +int Sqlitetestrtree_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "register_cube_geom", register_cube_geom, 0, 0); + Tcl_CreateObjCommand(interp, "register_circle_geom",register_circle_geom,0,0); + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_schema.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_schema.c new file mode 100644 index 0000000000000000000000000000000000000000..00a9f4dd903baf64fa27ab1ebe223a8a80d6bee0 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_schema.c @@ -0,0 +1,362 @@ +/* +** 2006 June 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing the virtual table interfaces. This code +** is not included in the SQLite library. It is used for automated +** testing of the SQLite library. +*/ + +/* The code in this file defines a sqlite3 virtual-table module that +** provides a read-only view of the current database schema. There is one +** row in the schema table for each column in the database schema. +*/ +#define SCHEMA \ +"CREATE TABLE x(" \ + "database," /* Name of database (i.e. main, temp etc.) */ \ + "tablename," /* Name of table */ \ + "cid," /* Column number (from left-to-right, 0 upward) */ \ + "name," /* Column name */ \ + "type," /* Specified type (i.e. VARCHAR(32)) */ \ + "not_null," /* Boolean. True if NOT NULL was specified */ \ + "dflt_value," /* Default value for this column */ \ + "pk" /* True if this column is part of the primary key */ \ +")" + +/* If SQLITE_TEST is defined this code is preprocessed for use as part +** of the sqlite test binary "testfixture". Otherwise it is preprocessed +** to be compiled into an sqlite dynamic extension. +*/ +#ifdef SQLITE_TEST + #include "sqliteInt.h" + #include "tcl.h" +#else + #include "sqlite3ext.h" + SQLITE_EXTENSION_INIT1 +#endif + +#include +#include +#include + +typedef struct schema_vtab schema_vtab; +typedef struct schema_cursor schema_cursor; + +/* A schema table object */ +struct schema_vtab { + sqlite3_vtab base; + sqlite3 *db; +}; + +/* A schema table cursor object */ +struct schema_cursor { + sqlite3_vtab_cursor base; + sqlite3_stmt *pDbList; + sqlite3_stmt *pTableList; + sqlite3_stmt *pColumnList; + int rowid; +}; + +/* +** None of this works unless we have virtual tables. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Table destructor for the schema module. +*/ +static int schemaDestroy(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return 0; +} + +/* +** Table constructor for the schema module. +*/ +static int schemaCreate( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int rc = SQLITE_NOMEM; + schema_vtab *pVtab = sqlite3_malloc(sizeof(schema_vtab)); + if( pVtab ){ + memset(pVtab, 0, sizeof(schema_vtab)); + pVtab->db = db; +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = sqlite3_declare_vtab(db, SCHEMA); +#endif + } + *ppVtab = (sqlite3_vtab *)pVtab; + return rc; +} + +/* +** Open a new cursor on the schema table. +*/ +static int schemaOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + int rc = SQLITE_NOMEM; + schema_cursor *pCur; + pCur = sqlite3_malloc(sizeof(schema_cursor)); + if( pCur ){ + memset(pCur, 0, sizeof(schema_cursor)); + *ppCursor = (sqlite3_vtab_cursor *)pCur; + rc = SQLITE_OK; + } + return rc; +} + +/* +** Close a schema table cursor. +*/ +static int schemaClose(sqlite3_vtab_cursor *cur){ + schema_cursor *pCur = (schema_cursor *)cur; + sqlite3_finalize(pCur->pDbList); + sqlite3_finalize(pCur->pTableList); + sqlite3_finalize(pCur->pColumnList); + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Retrieve a column of data. +*/ +static int schemaColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + schema_cursor *pCur = (schema_cursor *)cur; + switch( i ){ + case 0: + sqlite3_result_value(ctx, sqlite3_column_value(pCur->pDbList, 1)); + break; + case 1: + sqlite3_result_value(ctx, sqlite3_column_value(pCur->pTableList, 0)); + break; + default: + sqlite3_result_value(ctx, sqlite3_column_value(pCur->pColumnList, i-2)); + break; + } + return SQLITE_OK; +} + +/* +** Retrieve the current rowid. +*/ +static int schemaRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + schema_cursor *pCur = (schema_cursor *)cur; + *pRowid = pCur->rowid; + return SQLITE_OK; +} + +static int finalize(sqlite3_stmt **ppStmt){ + int rc = sqlite3_finalize(*ppStmt); + *ppStmt = 0; + return rc; +} + +static int schemaEof(sqlite3_vtab_cursor *cur){ + schema_cursor *pCur = (schema_cursor *)cur; + return (pCur->pDbList ? 0 : 1); +} + +/* +** Advance the cursor to the next row. +*/ +static int schemaNext(sqlite3_vtab_cursor *cur){ + int rc = SQLITE_OK; + schema_cursor *pCur = (schema_cursor *)cur; + schema_vtab *pVtab = (schema_vtab *)(cur->pVtab); + char *zSql = 0; + + while( !pCur->pColumnList || SQLITE_ROW!=sqlite3_step(pCur->pColumnList) ){ + if( SQLITE_OK!=(rc = finalize(&pCur->pColumnList)) ) goto next_exit; + + while( !pCur->pTableList || SQLITE_ROW!=sqlite3_step(pCur->pTableList) ){ + if( SQLITE_OK!=(rc = finalize(&pCur->pTableList)) ) goto next_exit; + + assert(pCur->pDbList); + while( SQLITE_ROW!=sqlite3_step(pCur->pDbList) ){ + rc = finalize(&pCur->pDbList); + goto next_exit; + } + + /* Set zSql to the SQL to pull the list of tables from the + ** sqlite_master (or sqlite_temp_master) table of the database + ** identfied by the row pointed to by the SQL statement pCur->pDbList + ** (iterating through a "PRAGMA database_list;" statement). + */ + if( sqlite3_column_int(pCur->pDbList, 0)==1 ){ + zSql = sqlite3_mprintf( + "SELECT name FROM sqlite_temp_master WHERE type='table'" + ); + }else{ + sqlite3_stmt *pDbList = pCur->pDbList; + zSql = sqlite3_mprintf( + "SELECT name FROM %Q.sqlite_master WHERE type='table'", + sqlite3_column_text(pDbList, 1) + ); + } + if( !zSql ){ + rc = SQLITE_NOMEM; + goto next_exit; + } + + rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pTableList, 0); + sqlite3_free(zSql); + if( rc!=SQLITE_OK ) goto next_exit; + } + + /* Set zSql to the SQL to the table_info pragma for the table currently + ** identified by the rows pointed to by statements pCur->pDbList and + ** pCur->pTableList. + */ + zSql = sqlite3_mprintf("PRAGMA %Q.table_info(%Q)", + sqlite3_column_text(pCur->pDbList, 1), + sqlite3_column_text(pCur->pTableList, 0) + ); + + if( !zSql ){ + rc = SQLITE_NOMEM; + goto next_exit; + } + rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pColumnList, 0); + sqlite3_free(zSql); + if( rc!=SQLITE_OK ) goto next_exit; + } + pCur->rowid++; + +next_exit: + /* TODO: Handle rc */ + return rc; +} + +/* +** Reset a schema table cursor. +*/ +static int schemaFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + int rc; + schema_vtab *pVtab = (schema_vtab *)(pVtabCursor->pVtab); + schema_cursor *pCur = (schema_cursor *)pVtabCursor; + pCur->rowid = 0; + finalize(&pCur->pTableList); + finalize(&pCur->pColumnList); + finalize(&pCur->pDbList); + rc = sqlite3_prepare(pVtab->db,"PRAGMA database_list", -1, &pCur->pDbList, 0); + return (rc==SQLITE_OK ? schemaNext(pVtabCursor) : rc); +} + +/* +** Analyse the WHERE condition. +*/ +static int schemaBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + return SQLITE_OK; +} + +/* +** A virtual table module that merely echos method calls into TCL +** variables. +*/ +static sqlite3_module schemaModule = { + 0, /* iVersion */ + schemaCreate, + schemaCreate, + schemaBestIndex, + schemaDestroy, + schemaDestroy, + schemaOpen, /* xOpen - open a cursor */ + schemaClose, /* xClose - close a cursor */ + schemaFilter, /* xFilter - configure scan constraints */ + schemaNext, /* xNext - advance a cursor */ + schemaEof, /* xEof */ + schemaColumn, /* xColumn - read data */ + schemaRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ + +#ifdef SQLITE_TEST + +/* +** Decode a pointer to an sqlite3 object. +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); + +/* +** Register the schema virtual table module. +*/ +static int register_schema_module( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_create_module(db, "schema", &schemaModule, 0); +#endif + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetestschema_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "register_schema_module", register_schema_module, 0 }, + }; + int i; + for(i=0; i +#include "sqlite3.h" + +/* +** Messages are passed from client to server and back again as +** instances of the following structure. +*/ +typedef struct SqlMessage SqlMessage; +struct SqlMessage { + int op; /* Opcode for the message */ + sqlite3 *pDb; /* The SQLite connection */ + sqlite3_stmt *pStmt; /* A specific statement */ + int errCode; /* Error code returned */ + const char *zIn; /* Input filename or SQL statement */ + int nByte; /* Size of the zIn parameter for prepare() */ + const char *zOut; /* Tail of the SQL statement */ + SqlMessage *pNext; /* Next message in the queue */ + SqlMessage *pPrev; /* Previous message in the queue */ + pthread_mutex_t clientMutex; /* Hold this mutex to access the message */ + pthread_cond_t clientWakeup; /* Signal to wake up the client */ +}; + +/* +** Legal values for SqlMessage.op +*/ +#define MSG_Open 1 /* sqlite3_open(zIn, &pDb) */ +#define MSG_Prepare 2 /* sqlite3_prepare(pDb, zIn, nByte, &pStmt, &zOut) */ +#define MSG_Step 3 /* sqlite3_step(pStmt) */ +#define MSG_Reset 4 /* sqlite3_reset(pStmt) */ +#define MSG_Finalize 5 /* sqlite3_finalize(pStmt) */ +#define MSG_Close 6 /* sqlite3_close(pDb) */ +#define MSG_Done 7 /* Server has finished with this message */ + + +/* +** State information about the server is stored in a static variable +** named "g" as follows: +*/ +static struct ServerState { + pthread_mutex_t queueMutex; /* Hold this mutex to access the msg queue */ + pthread_mutex_t serverMutex; /* Held by the server while it is running */ + pthread_cond_t serverWakeup; /* Signal this condvar to wake up the server */ + volatile int serverHalt; /* Server halts itself when true */ + SqlMessage *pQueueHead; /* Head of the message queue */ + SqlMessage *pQueueTail; /* Tail of the message queue */ +} g = { + PTHREAD_MUTEX_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER, + PTHREAD_COND_INITIALIZER, +}; + +/* +** Send a message to the server. Block until we get a reply. +** +** The mutex and condition variable in the message are uninitialized +** when this routine is called. This routine takes care of +** initializing them and destroying them when it has finished. +*/ +static void sendToServer(SqlMessage *pMsg){ + /* Initialize the mutex and condition variable on the message + */ + pthread_mutex_init(&pMsg->clientMutex, 0); + pthread_cond_init(&pMsg->clientWakeup, 0); + + /* Add the message to the head of the server's message queue. + */ + pthread_mutex_lock(&g.queueMutex); + pMsg->pNext = g.pQueueHead; + if( g.pQueueHead==0 ){ + g.pQueueTail = pMsg; + }else{ + g.pQueueHead->pPrev = pMsg; + } + pMsg->pPrev = 0; + g.pQueueHead = pMsg; + pthread_mutex_unlock(&g.queueMutex); + + /* Signal the server that the new message has be queued, then + ** block waiting for the server to process the message. + */ + pthread_mutex_lock(&pMsg->clientMutex); + pthread_cond_signal(&g.serverWakeup); + while( pMsg->op!=MSG_Done ){ + pthread_cond_wait(&pMsg->clientWakeup, &pMsg->clientMutex); + } + pthread_mutex_unlock(&pMsg->clientMutex); + + /* Destroy the mutex and condition variable of the message. + */ + pthread_mutex_destroy(&pMsg->clientMutex); + pthread_cond_destroy(&pMsg->clientWakeup); +} + +/* +** The following 6 routines are client-side implementations of the +** core SQLite interfaces: +** +** sqlite3_open +** sqlite3_prepare +** sqlite3_step +** sqlite3_reset +** sqlite3_finalize +** sqlite3_close +** +** Clients should use the following client-side routines instead of +** the core routines above. +** +** sqlite3_client_open +** sqlite3_client_prepare +** sqlite3_client_step +** sqlite3_client_reset +** sqlite3_client_finalize +** sqlite3_client_close +** +** Each of these routines creates a message for the desired operation, +** sends that message to the server, waits for the server to process +** then message and return a response. +*/ +int sqlite3_client_open(const char *zDatabaseName, sqlite3 **ppDb){ + SqlMessage msg; + msg.op = MSG_Open; + msg.zIn = zDatabaseName; + sendToServer(&msg); + *ppDb = msg.pDb; + return msg.errCode; +} +int sqlite3_client_prepare( + sqlite3 *pDb, + const char *zSql, + int nByte, + sqlite3_stmt **ppStmt, + const char **pzTail +){ + SqlMessage msg; + msg.op = MSG_Prepare; + msg.pDb = pDb; + msg.zIn = zSql; + msg.nByte = nByte; + sendToServer(&msg); + *ppStmt = msg.pStmt; + if( pzTail ) *pzTail = msg.zOut; + return msg.errCode; +} +int sqlite3_client_step(sqlite3_stmt *pStmt){ + SqlMessage msg; + msg.op = MSG_Step; + msg.pStmt = pStmt; + sendToServer(&msg); + return msg.errCode; +} +int sqlite3_client_reset(sqlite3_stmt *pStmt){ + SqlMessage msg; + msg.op = MSG_Reset; + msg.pStmt = pStmt; + sendToServer(&msg); + return msg.errCode; +} +int sqlite3_client_finalize(sqlite3_stmt *pStmt){ + SqlMessage msg; + msg.op = MSG_Finalize; + msg.pStmt = pStmt; + sendToServer(&msg); + return msg.errCode; +} +int sqlite3_client_close(sqlite3 *pDb){ + SqlMessage msg; + msg.op = MSG_Close; + msg.pDb = pDb; + sendToServer(&msg); + return msg.errCode; +} + +/* +** This routine implements the server. To start the server, first +** make sure g.serverHalt is false, then create a new detached thread +** on this procedure. See the sqlite3_server_start() routine below +** for an example. This procedure loops until g.serverHalt becomes +** true. +*/ +void *sqlite3_server(void *NotUsed){ + if( pthread_mutex_trylock(&g.serverMutex) ){ + return 0; /* Another server is already running */ + } + sqlite3_enable_shared_cache(1); + while( !g.serverHalt ){ + SqlMessage *pMsg; + + /* Remove the last message from the message queue. + */ + pthread_mutex_lock(&g.queueMutex); + while( g.pQueueTail==0 && g.serverHalt==0 ){ + pthread_cond_wait(&g.serverWakeup, &g.queueMutex); + } + pMsg = g.pQueueTail; + if( pMsg ){ + if( pMsg->pPrev ){ + pMsg->pPrev->pNext = 0; + }else{ + g.pQueueHead = 0; + } + g.pQueueTail = pMsg->pPrev; + } + pthread_mutex_unlock(&g.queueMutex); + if( pMsg==0 ) break; + + /* Process the message just removed + */ + pthread_mutex_lock(&pMsg->clientMutex); + switch( pMsg->op ){ + case MSG_Open: { + pMsg->errCode = sqlite3_open(pMsg->zIn, &pMsg->pDb); + break; + } + case MSG_Prepare: { + pMsg->errCode = sqlite3_prepare(pMsg->pDb, pMsg->zIn, pMsg->nByte, + &pMsg->pStmt, &pMsg->zOut); + break; + } + case MSG_Step: { + pMsg->errCode = sqlite3_step(pMsg->pStmt); + break; + } + case MSG_Reset: { + pMsg->errCode = sqlite3_reset(pMsg->pStmt); + break; + } + case MSG_Finalize: { + pMsg->errCode = sqlite3_finalize(pMsg->pStmt); + break; + } + case MSG_Close: { + pMsg->errCode = sqlite3_close(pMsg->pDb); + break; + } + } + + /* Signal the client that the message has been processed. + */ + pMsg->op = MSG_Done; + pthread_mutex_unlock(&pMsg->clientMutex); + pthread_cond_signal(&pMsg->clientWakeup); + } + pthread_mutex_unlock(&g.serverMutex); + return 0; +} + +/* +** Start a server thread if one is not already running. If there +** is aleady a server thread running, the new thread will quickly +** die and this routine is effectively a no-op. +*/ +void sqlite3_server_start(void){ + pthread_t x; + int rc; + g.serverHalt = 0; + rc = pthread_create(&x, 0, sqlite3_server, 0); + if( rc==0 ){ + pthread_detach(x); + } +} + +/* +** A wrapper around sqlite3_server() that decrements the int variable +** pointed to by the first argument after the sqlite3_server() call +** returns. +*/ +static void *serverWrapper(void *pnDecr){ + void *p = sqlite3_server(0); + (*(int*)pnDecr)--; + return p; +} + +/* +** This function is the similar to sqlite3_server_start(), except that +** the integer pointed to by the first argument is decremented when +** the server thread exits. +*/ +void sqlite3_server_start2(int *pnDecr){ + pthread_t x; + int rc; + g.serverHalt = 0; + rc = pthread_create(&x, 0, serverWrapper, (void*)pnDecr); + if( rc==0 ){ + pthread_detach(x); + } +} + +/* +** If a server thread is running, then stop it. If no server is +** running, this routine is effectively a no-op. +** +** This routine waits until the server has actually stopped before +** returning. +*/ +void sqlite3_server_stop(void){ + g.serverHalt = 1; + pthread_cond_broadcast(&g.serverWakeup); + pthread_mutex_lock(&g.serverMutex); + pthread_mutex_unlock(&g.serverMutex); +} + +#endif /* SQLITE_OS_UNIX && SQLITE_THREADSAFE */ +#endif /* defined(SQLITE_SERVER) */ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_sqllog.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_sqllog.c new file mode 100644 index 0000000000000000000000000000000000000000..4aa68b7c429323b8eebe6c9c2d07fc660d8d47c9 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_sqllog.c @@ -0,0 +1,507 @@ +/* +** 2012 November 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** OVERVIEW +** +** This file contains experimental code used to record data from live +** SQLite applications that may be useful for offline analysis. +** Specifically, this module can be used to capture the following +** information: +** +** 1) The initial contents of all database files opened by the +** application, and +** +** 2) All SQL statements executed by the application. +** +** The captured information can then be used to run (for example) +** performance analysis looking for slow queries or to look for +** optimization opportunities in either the application or in SQLite +** itself. +** +** USAGE +** +** To use this module, SQLite must be compiled with the SQLITE_ENABLE_SQLLOG +** pre-processor symbol defined and this file linked into the application. +** One way to link this file into the application is to append the content +** of this file onto the end of the "sqlite3.c" amalgamation and then +** recompile the application as normal except with the addition of the +** -DSQLITE_ENABLE_SQLLOG option. +** +** At runtime, logging is enabled by setting environment variable +** SQLITE_SQLLOG_DIR to the name of a directory in which to store logged +** data. The logging directory must already exist. +** +** Usually, if the application opens the same database file more than once +** (either by attaching it or by using more than one database handle), only +** a single copy is made. This behavior may be overridden (so that a +** separate copy is taken each time the database file is opened or attached) +** by setting the environment variable SQLITE_SQLLOG_REUSE_FILES to 0. +** +** OUTPUT: +** +** The SQLITE_SQLLOG_DIR is populated with three types of files: +** +** sqllog_N.db - Copies of database files. N may be any integer. +** +** sqllog_N.sql - A list of SQL statements executed by a single +** connection. N may be any integer. +** +** sqllog.idx - An index mapping from integer N to a database +** file name - indicating the full path of the +** database from which sqllog_N.db was copied. +** +** ERROR HANDLING: +** +** This module attempts to make a best effort to continue logging if an +** IO or other error is encountered. For example, if a log file cannot +** be opened logs are not collected for that connection, but other +** logging proceeds as expected. Errors are logged by calling sqlite3_log(). +*/ + +#ifndef _SQLITE3_H_ +#include "sqlite3.h" +#endif +#include +#include +#include +#include + +#include +#include +static int getProcessId(void){ +#if SQLITE_OS_WIN + return (int)_getpid(); +#else + return (int)getpid(); +#endif +} + +/* Names of environment variables to be used */ +#define ENVIRONMENT_VARIABLE1_NAME "SQLITE_SQLLOG_DIR" +#define ENVIRONMENT_VARIABLE2_NAME "SQLITE_SQLLOG_REUSE_FILES" + +/* Assume that all database and database file names are shorted than this. */ +#define SQLLOG_NAMESZ 512 + +/* Maximum number of simultaneous database connections the process may +** open (if any more are opened an error is logged using sqlite3_log() +** and processing is halted). +*/ +#define MAX_CONNECTIONS 256 + +/* There is one instance of this object for each SQLite database connection +** that is being logged. +*/ +struct SLConn { + int isErr; /* True if an error has occurred */ + sqlite3 *db; /* Connection handle */ + int iLog; /* First integer value used in file names */ + FILE *fd; /* File descriptor for log file */ +}; + +/* This object is a singleton that keeps track of all data loggers. +*/ +static struct SLGlobal { + /* Protected by MUTEX_STATIC_MASTER */ + sqlite3_mutex *mutex; /* Recursive mutex */ + int nConn; /* Size of aConn[] array */ + + /* Protected by SLGlobal.mutex */ + int bReuse; /* True to avoid extra copies of db files */ + char zPrefix[SQLLOG_NAMESZ]; /* Prefix for all created files */ + char zIdx[SQLLOG_NAMESZ]; /* Full path to *.idx file */ + int iNextLog; /* Used to allocate file names */ + int iNextDb; /* Used to allocate database file names */ + int bRec; /* True if testSqllog() is called rec. */ + int iClock; /* Clock value */ + struct SLConn aConn[MAX_CONNECTIONS]; +} sqllogglobal; + +/* +** Return true if c is an ASCII whitespace character. +*/ +static int sqllog_isspace(char c){ + return (c==' ' || c=='\t' || c=='\n' || c=='\v' || c=='\f' || c=='\r'); +} + +/* +** The first argument points to a nul-terminated string containing an SQL +** command. Before returning, this function sets *pz to point to the start +** of the first token in this command, and *pn to the number of bytes in +** the token. This is used to check if the SQL command is an "ATTACH" or +** not. +*/ +static void sqllogTokenize(const char *z, const char **pz, int *pn){ + const char *p = z; + int n; + + /* Skip past any whitespace */ + while( sqllog_isspace(*p) ){ + p++; + } + + /* Figure out how long the first token is */ + *pz = p; + n = 0; + while( (p[n]>='a' && p[n]<='z') || (p[n]>='A' && p[n]<='Z') ) n++; + *pn = n; +} + +/* +** Check if the logs directory already contains a copy of database file +** zFile. If so, return a pointer to the full path of the copy. Otherwise, +** return NULL. +** +** If a non-NULL value is returned, then the caller must arrange to +** eventually free it using sqlite3_free(). +*/ +static char *sqllogFindFile(const char *zFile){ + char *zRet = 0; + FILE *fd = 0; + + /* Open the index file for reading */ + fd = fopen(sqllogglobal.zIdx, "r"); + if( fd==0 ){ + sqlite3_log(SQLITE_IOERR, "sqllogFindFile(): error in fopen()"); + return 0; + } + + /* Loop through each entry in the index file. If zFile is not NULL and the + ** entry is a match, then set zRet to point to the filename of the existing + ** copy and break out of the loop. */ + while( feof(fd)==0 ){ + char zLine[SQLLOG_NAMESZ*2+5]; + if( fgets(zLine, sizeof(zLine), fd) ){ + int n; + char *z; + + zLine[sizeof(zLine)-1] = '\0'; + z = zLine; + while( *z>='0' && *z<='9' ) z++; + while( *z==' ' ) z++; + + n = strlen(z); + while( n>0 && sqllog_isspace(z[n-1]) ) n--; + + if( n==strlen(zFile) && 0==memcmp(zFile, z, n) ){ + char zBuf[16]; + memset(zBuf, 0, sizeof(zBuf)); + z = zLine; + while( *z>='0' && *z<='9' ){ + zBuf[z-zLine] = *z; + z++; + } + zRet = sqlite3_mprintf("%s_%s.db", sqllogglobal.zPrefix, zBuf); + break; + } + } + } + + if( ferror(fd) ){ + sqlite3_log(SQLITE_IOERR, "sqllogFindFile(): error reading index file"); + } + + fclose(fd); + return zRet; +} + +static int sqllogFindAttached( + struct SLConn *p, /* Database connection */ + const char *zSearch, /* Name to search for (or NULL) */ + char *zName, /* OUT: Name of attached database */ + char *zFile /* OUT: Name of attached file */ +){ + sqlite3_stmt *pStmt; + int rc; + + /* The "PRAGMA database_list" command returns a list of databases in the + ** order that they were attached. So a newly attached database is + ** described by the last row returned. */ + assert( sqllogglobal.bRec==0 ); + sqllogglobal.bRec = 1; + rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); + if( rc==SQLITE_OK ){ + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + const char *zVal1; int nVal1; + const char *zVal2; int nVal2; + + zVal1 = (const char*)sqlite3_column_text(pStmt, 1); + nVal1 = sqlite3_column_bytes(pStmt, 1); + memcpy(zName, zVal1, nVal1+1); + + zVal2 = (const char*)sqlite3_column_text(pStmt, 2); + nVal2 = sqlite3_column_bytes(pStmt, 2); + memcpy(zFile, zVal2, nVal2+1); + + if( zSearch && strlen(zSearch)==nVal1 + && 0==sqlite3_strnicmp(zSearch, zVal1, nVal1) + ){ + break; + } + } + rc = sqlite3_finalize(pStmt); + } + sqllogglobal.bRec = 0; + + if( rc!=SQLITE_OK ){ + sqlite3_log(rc, "sqllogFindAttached(): error in \"PRAGMA database_list\""); + } + return rc; +} + + +/* +** Parameter zSearch is the name of a database attached to the database +** connection associated with the first argument. This function creates +** a backup of this database in the logs directory. +** +** The name used for the backup file is automatically generated. Call +** it zFile. +** +** If the bLog parameter is true, then a statement of the following form +** is written to the log file associated with *p: +** +** ATTACH 'zFile' AS 'zName'; +** +** Otherwise, if bLog is false, a comment is added to the log file: +** +** -- Main database file is 'zFile' +** +** The SLGlobal.mutex mutex is always held when this function is called. +*/ +static void sqllogCopydb(struct SLConn *p, const char *zSearch, int bLog){ + char zName[SQLLOG_NAMESZ]; /* Attached database name */ + char zFile[SQLLOG_NAMESZ]; /* Database file name */ + char *zFree; + char *zInit = 0; + int rc; + + rc = sqllogFindAttached(p, zSearch, zName, zFile); + if( rc!=SQLITE_OK ) return; + + if( zFile[0]=='\0' ){ + zInit = sqlite3_mprintf(""); + }else{ + if( sqllogglobal.bReuse ){ + zInit = sqllogFindFile(zFile); + }else{ + zInit = 0; + } + if( zInit==0 ){ + int rc; + sqlite3 *copy = 0; + int iDb; + + /* Generate a file-name to use for the copy of this database */ + iDb = sqllogglobal.iNextDb++; + zInit = sqlite3_mprintf("%s_%d.db", sqllogglobal.zPrefix, iDb); + + /* Create the backup */ + assert( sqllogglobal.bRec==0 ); + sqllogglobal.bRec = 1; + rc = sqlite3_open(zInit, ©); + if( rc==SQLITE_OK ){ + sqlite3_backup *pBak; + sqlite3_exec(copy, "PRAGMA synchronous = 0", 0, 0, 0); + pBak = sqlite3_backup_init(copy, "main", p->db, zName); + if( pBak ){ + sqlite3_backup_step(pBak, -1); + rc = sqlite3_backup_finish(pBak); + }else{ + rc = sqlite3_errcode(copy); + } + sqlite3_close(copy); + } + sqllogglobal.bRec = 0; + + if( rc==SQLITE_OK ){ + /* Write an entry into the database index file */ + FILE *fd = fopen(sqllogglobal.zIdx, "a"); + if( fd ){ + fprintf(fd, "%d %s\n", iDb, zFile); + fclose(fd); + } + }else{ + sqlite3_log(rc, "sqllogCopydb(): error backing up database"); + } + } + } + + if( bLog ){ + zFree = sqlite3_mprintf("ATTACH '%q' AS '%q'; -- clock=%d\n", + zInit, zName, sqllogglobal.iClock++ + ); + }else{ + zFree = sqlite3_mprintf("-- Main database is '%q'\n", zInit); + } + fprintf(p->fd, "%s", zFree); + sqlite3_free(zFree); + + sqlite3_free(zInit); +} + +/* +** If it is not already open, open the log file for connection *p. +** +** The SLGlobal.mutex mutex is always held when this function is called. +*/ +static void sqllogOpenlog(struct SLConn *p){ + /* If the log file has not yet been opened, open it now. */ + if( p->fd==0 ){ + char *zLog; + + /* If it is still NULL, have global.zPrefix point to a copy of + ** environment variable $ENVIRONMENT_VARIABLE1_NAME. */ + if( sqllogglobal.zPrefix[0]==0 ){ + FILE *fd; + char *zVar = getenv(ENVIRONMENT_VARIABLE1_NAME); + if( zVar==0 || strlen(zVar)+10>=(sizeof(sqllogglobal.zPrefix)) ) return; + sprintf(sqllogglobal.zPrefix, "%s/sqllog_%d", zVar, getProcessId()); + sprintf(sqllogglobal.zIdx, "%s.idx", sqllogglobal.zPrefix); + if( getenv(ENVIRONMENT_VARIABLE2_NAME) ){ + sqllogglobal.bReuse = atoi(getenv(ENVIRONMENT_VARIABLE2_NAME)); + } + fd = fopen(sqllogglobal.zIdx, "w"); + if( fd ) fclose(fd); + } + + /* Open the log file */ + zLog = sqlite3_mprintf("%s_%d.sql", sqllogglobal.zPrefix, p->iLog); + p->fd = fopen(zLog, "w"); + sqlite3_free(zLog); + if( p->fd==0 ){ + sqlite3_log(SQLITE_IOERR, "sqllogOpenlog(): Failed to open log file"); + } + } +} + +/* +** This function is called if the SQLLOG callback is invoked to report +** execution of an SQL statement. Parameter p is the connection the statement +** was executed by and parameter zSql is the text of the statement itself. +*/ +static void testSqllogStmt(struct SLConn *p, const char *zSql){ + const char *zFirst; /* Pointer to first token in zSql */ + int nFirst; /* Size of token zFirst in bytes */ + + sqllogTokenize(zSql, &zFirst, &nFirst); + if( nFirst!=6 || 0!=sqlite3_strnicmp("ATTACH", zFirst, 6) ){ + /* Not an ATTACH statement. Write this directly to the log. */ + fprintf(p->fd, "%s; -- clock=%d\n", zSql, sqllogglobal.iClock++); + }else{ + /* This is an ATTACH statement. Copy the database. */ + sqllogCopydb(p, 0, 1); + } +} + +/* +** The SQLITE_CONFIG_SQLLOG callback registered by sqlite3_init_sqllog(). +** +** The eType parameter has the following values: +** +** 0: Opening a new database connection. zSql is the name of the +** file being opened. db is a pointer to the newly created database +** connection. +** +** 1: An SQL statement has run to completion. zSql is the text of the +** SQL statement with all parameters expanded to their actual values. +** +** 2: Closing a database connection. zSql is NULL. The db pointer to +** the database connection being closed has already been shut down +** and cannot be used for any further SQL. +** +** The pCtx parameter is a copy of the pointer that was originally passed +** into the sqlite3_config(SQLITE_CONFIG_SQLLOG) statement. In this +** particular implementation, pCtx is always a pointer to the +** sqllogglobal global variable define above. +*/ +static void testSqllog(void *pCtx, sqlite3 *db, const char *zSql, int eType){ + struct SLConn *p = 0; + sqlite3_mutex *master = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); + + assert( eType==0 || eType==1 || eType==2 ); + assert( (eType==2)==(zSql==0) ); + + /* This is a database open command. */ + if( eType==0 ){ + sqlite3_mutex_enter(master); + if( sqllogglobal.mutex==0 ){ + sqllogglobal.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE); + } + p = &sqllogglobal.aConn[sqllogglobal.nConn++]; + p->fd = 0; + p->db = db; + p->iLog = sqllogglobal.iNextLog++; + sqlite3_mutex_leave(master); + + /* Open the log and take a copy of the main database file */ + sqlite3_mutex_enter(sqllogglobal.mutex); + if( sqllogglobal.bRec==0 ){ + sqllogOpenlog(p); + if( p->fd ) sqllogCopydb(p, "main", 0); + } + sqlite3_mutex_leave(sqllogglobal.mutex); + } + + else{ + + int i; + for(i=0; idb==db ) break; + } + if( i==sqllogglobal.nConn ) return; + + /* A database handle close command */ + if( eType==2 ){ + sqlite3_mutex_enter(master); + if( p->fd ) fclose(p->fd); + p->db = 0; + p->fd = 0; + + sqllogglobal.nConn--; + if( sqllogglobal.nConn==0 ){ + sqlite3_mutex_free(sqllogglobal.mutex); + sqllogglobal.mutex = 0; + }else{ + int nShift = &sqllogglobal.aConn[sqllogglobal.nConn] - p; + if( nShift>0 ){ + memmove(p, &p[1], nShift*sizeof(struct SLConn)); + } + } + sqlite3_mutex_leave(master); + + /* An ordinary SQL command. */ + }else if( p->fd ){ + sqlite3_mutex_enter(sqllogglobal.mutex); + if( sqllogglobal.bRec==0 ){ + testSqllogStmt(p, zSql); + } + sqlite3_mutex_leave(sqllogglobal.mutex); + } + } +} + +/* +** This function is called either before sqlite3_initialized() or by it. +** It checks if the SQLITE_SQLLOG_DIR variable is defined, and if so +** registers an SQLITE_CONFIG_SQLLOG callback to record the applications +** database activity. +*/ +void sqlite3_init_sqllog(void){ + if( getenv(ENVIRONMENT_VARIABLE1_NAME) ){ + if( SQLITE_OK==sqlite3_config(SQLITE_CONFIG_SQLLOG, testSqllog, 0) ){ + memset(&sqllogglobal, 0, sizeof(sqllogglobal)); + sqllogglobal.bReuse = 1; + } + } +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_stat.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_stat.c new file mode 100644 index 0000000000000000000000000000000000000000..d4c902b5ea111ad58a737112c28f0038434c85c0 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_stat.c @@ -0,0 +1,639 @@ +/* +** 2010 July 12 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains an implementation of the "dbstat" virtual table. +** +** The dbstat virtual table is used to extract low-level formatting +** information from an SQLite database in order to implement the +** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script +** for an example implementation. +*/ + +#ifndef SQLITE_AMALGAMATION +# include "sqliteInt.h" +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Page paths: +** +** The value of the 'path' column describes the path taken from the +** root-node of the b-tree structure to each page. The value of the +** root-node path is '/'. +** +** The value of the path for the left-most child page of the root of +** a b-tree is '/000/'. (Btrees store content ordered from left to right +** so the pages to the left have smaller keys than the pages to the right.) +** The next to left-most child of the root page is +** '/001', and so on, each sibling page identified by a 3-digit hex +** value. The children of the 451st left-most sibling have paths such +** as '/1c2/000/, '/1c2/001/' etc. +** +** Overflow pages are specified by appending a '+' character and a +** six-digit hexadecimal value to the path to the cell they are linked +** from. For example, the three overflow pages in a chain linked from +** the left-most cell of the 450th child of the root page are identified +** by the paths: +** +** '/1c2/000+000000' // First page in overflow chain +** '/1c2/000+000001' // Second page in overflow chain +** '/1c2/000+000002' // Third page in overflow chain +** +** If the paths are sorted using the BINARY collation sequence, then +** the overflow pages associated with a cell will appear earlier in the +** sort-order than its child page: +** +** '/1c2/000/' // Left-most child of 451st child of root +*/ +#define VTAB_SCHEMA \ + "CREATE TABLE xx( " \ + " name STRING, /* Name of table or index */" \ + " path INTEGER, /* Path to page from root */" \ + " pageno INTEGER, /* Page number */" \ + " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */" \ + " ncell INTEGER, /* Cells on page (0 for overflow) */" \ + " payload INTEGER, /* Bytes of payload on this page */" \ + " unused INTEGER, /* Bytes of unused space on this page */" \ + " mx_payload INTEGER, /* Largest payload size of all cells */" \ + " pgoffset INTEGER, /* Offset of page in file */" \ + " pgsize INTEGER /* Size of the page */" \ + ");" + + +typedef struct StatTable StatTable; +typedef struct StatCursor StatCursor; +typedef struct StatPage StatPage; +typedef struct StatCell StatCell; + +struct StatCell { + int nLocal; /* Bytes of local payload */ + u32 iChildPg; /* Child node (or 0 if this is a leaf) */ + int nOvfl; /* Entries in aOvfl[] */ + u32 *aOvfl; /* Array of overflow page numbers */ + int nLastOvfl; /* Bytes of payload on final overflow page */ + int iOvfl; /* Iterates through aOvfl[] */ +}; + +struct StatPage { + u32 iPgno; + DbPage *pPg; + int iCell; + + char *zPath; /* Path to this page */ + + /* Variables populated by statDecodePage(): */ + u8 flags; /* Copy of flags byte */ + int nCell; /* Number of cells on page */ + int nUnused; /* Number of unused bytes on page */ + StatCell *aCell; /* Array of parsed cells */ + u32 iRightChildPg; /* Right-child page number (or 0) */ + int nMxPayload; /* Largest payload of any cell on this page */ +}; + +struct StatCursor { + sqlite3_vtab_cursor base; + sqlite3_stmt *pStmt; /* Iterates through set of root pages */ + int isEof; /* After pStmt has returned SQLITE_DONE */ + + StatPage aPage[32]; + int iPage; /* Current entry in aPage[] */ + + /* Values to return. */ + char *zName; /* Value of 'name' column */ + char *zPath; /* Value of 'path' column */ + u32 iPageno; /* Value of 'pageno' column */ + char *zPagetype; /* Value of 'pagetype' column */ + int nCell; /* Value of 'ncell' column */ + int nPayload; /* Value of 'payload' column */ + int nUnused; /* Value of 'unused' column */ + int nMxPayload; /* Value of 'mx_payload' column */ + i64 iOffset; /* Value of 'pgOffset' column */ + int szPage; /* Value of 'pgSize' column */ +}; + +struct StatTable { + sqlite3_vtab base; + sqlite3 *db; +}; + +#ifndef get2byte +# define get2byte(x) ((x)[0]<<8 | (x)[1]) +#endif + +/* +** Connect to or create a statvfs virtual table. +*/ +static int statConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + StatTable *pTab; + + pTab = (StatTable *)sqlite3_malloc(sizeof(StatTable)); + memset(pTab, 0, sizeof(StatTable)); + pTab->db = db; + + sqlite3_declare_vtab(db, VTAB_SCHEMA); + *ppVtab = &pTab->base; + return SQLITE_OK; +} + +/* +** Disconnect from or destroy a statvfs virtual table. +*/ +static int statDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} + +/* +** There is no "best-index". This virtual table always does a linear +** scan of the binary VFS log file. +*/ +static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + + /* Records are always returned in ascending order of (name, path). + ** If this will satisfy the client, set the orderByConsumed flag so that + ** SQLite does not do an external sort. + */ + if( ( pIdxInfo->nOrderBy==1 + && pIdxInfo->aOrderBy[0].iColumn==0 + && pIdxInfo->aOrderBy[0].desc==0 + ) || + ( pIdxInfo->nOrderBy==2 + && pIdxInfo->aOrderBy[0].iColumn==0 + && pIdxInfo->aOrderBy[0].desc==0 + && pIdxInfo->aOrderBy[1].iColumn==1 + && pIdxInfo->aOrderBy[1].desc==0 + ) + ){ + pIdxInfo->orderByConsumed = 1; + } + + pIdxInfo->estimatedCost = 10.0; + return SQLITE_OK; +} + +/* +** Open a new statvfs cursor. +*/ +static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + StatTable *pTab = (StatTable *)pVTab; + StatCursor *pCsr; + int rc; + + pCsr = (StatCursor *)sqlite3_malloc(sizeof(StatCursor)); + memset(pCsr, 0, sizeof(StatCursor)); + pCsr->base.pVtab = pVTab; + + rc = sqlite3_prepare_v2(pTab->db, + "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type" + " UNION ALL " + "SELECT name, rootpage, type FROM sqlite_master WHERE rootpage!=0" + " ORDER BY name", -1, + &pCsr->pStmt, 0 + ); + if( rc!=SQLITE_OK ){ + sqlite3_free(pCsr); + return rc; + } + + *ppCursor = (sqlite3_vtab_cursor *)pCsr; + return SQLITE_OK; +} + +static void statClearPage(StatPage *p){ + int i; + for(i=0; inCell; i++){ + sqlite3_free(p->aCell[i].aOvfl); + } + sqlite3PagerUnref(p->pPg); + sqlite3_free(p->aCell); + sqlite3_free(p->zPath); + memset(p, 0, sizeof(StatPage)); +} + +static void statResetCsr(StatCursor *pCsr){ + int i; + sqlite3_reset(pCsr->pStmt); + for(i=0; iaPage); i++){ + statClearPage(&pCsr->aPage[i]); + } + pCsr->iPage = 0; + sqlite3_free(pCsr->zPath); + pCsr->zPath = 0; +} + +/* +** Close a statvfs cursor. +*/ +static int statClose(sqlite3_vtab_cursor *pCursor){ + StatCursor *pCsr = (StatCursor *)pCursor; + statResetCsr(pCsr); + sqlite3_finalize(pCsr->pStmt); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +static void getLocalPayload( + int nUsable, /* Usable bytes per page */ + u8 flags, /* Page flags */ + int nTotal, /* Total record (payload) size */ + int *pnLocal /* OUT: Bytes stored locally */ +){ + int nLocal; + int nMinLocal; + int nMaxLocal; + + if( flags==0x0D ){ /* Table leaf node */ + nMinLocal = (nUsable - 12) * 32 / 255 - 23; + nMaxLocal = nUsable - 35; + }else{ /* Index interior and leaf nodes */ + nMinLocal = (nUsable - 12) * 32 / 255 - 23; + nMaxLocal = (nUsable - 12) * 64 / 255 - 23; + } + + nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4); + if( nLocal>nMaxLocal ) nLocal = nMinLocal; + *pnLocal = nLocal; +} + +static int statDecodePage(Btree *pBt, StatPage *p){ + int nUnused; + int iOff; + int nHdr; + int isLeaf; + int szPage; + + u8 *aData = sqlite3PagerGetData(p->pPg); + u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0]; + + p->flags = aHdr[0]; + p->nCell = get2byte(&aHdr[3]); + p->nMxPayload = 0; + + isLeaf = (p->flags==0x0A || p->flags==0x0D); + nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100; + + nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell; + nUnused += (int)aHdr[7]; + iOff = get2byte(&aHdr[1]); + while( iOff ){ + nUnused += get2byte(&aData[iOff+2]); + iOff = get2byte(&aData[iOff]); + } + p->nUnused = nUnused; + p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]); + szPage = sqlite3BtreeGetPageSize(pBt); + + if( p->nCell ){ + int i; /* Used to iterate through cells */ + int nUsable = szPage - sqlite3BtreeGetReserve(pBt); + + p->aCell = sqlite3_malloc((p->nCell+1) * sizeof(StatCell)); + memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell)); + + for(i=0; inCell; i++){ + StatCell *pCell = &p->aCell[i]; + + iOff = get2byte(&aData[nHdr+i*2]); + if( !isLeaf ){ + pCell->iChildPg = sqlite3Get4byte(&aData[iOff]); + iOff += 4; + } + if( p->flags==0x05 ){ + /* A table interior node. nPayload==0. */ + }else{ + u32 nPayload; /* Bytes of payload total (local+overflow) */ + int nLocal; /* Bytes of payload stored locally */ + iOff += getVarint32(&aData[iOff], nPayload); + if( p->flags==0x0D ){ + u64 dummy; + iOff += sqlite3GetVarint(&aData[iOff], &dummy); + } + if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload; + getLocalPayload(nUsable, p->flags, nPayload, &nLocal); + pCell->nLocal = nLocal; + assert( nLocal>=0 ); + assert( nPayload>=(u32)nLocal ); + assert( nLocal<=(nUsable-35) ); + if( nPayload>(u32)nLocal ){ + int j; + int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4); + pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4); + pCell->nOvfl = nOvfl; + pCell->aOvfl = sqlite3_malloc(sizeof(u32)*nOvfl); + pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]); + for(j=1; jaOvfl[j-1]; + DbPage *pPg = 0; + rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg); + if( rc!=SQLITE_OK ){ + assert( pPg==0 ); + return rc; + } + pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg)); + sqlite3PagerUnref(pPg); + } + } + } + } + } + + return SQLITE_OK; +} + +/* +** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on +** the current value of pCsr->iPageno. +*/ +static void statSizeAndOffset(StatCursor *pCsr){ + StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab; + Btree *pBt = pTab->db->aDb[0].pBt; + Pager *pPager = sqlite3BtreePager(pBt); + sqlite3_file *fd; + sqlite3_int64 x[2]; + + /* The default page size and offset */ + pCsr->szPage = sqlite3BtreeGetPageSize(pBt); + pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1); + + /* If connected to a ZIPVFS backend, override the page size and + ** offset with actual values obtained from ZIPVFS. + */ + fd = sqlite3PagerFile(pPager); + x[0] = pCsr->iPageno; + if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){ + pCsr->iOffset = x[0]; + pCsr->szPage = (int)x[1]; + } +} + +/* +** Move a statvfs cursor to the next entry in the file. +*/ +static int statNext(sqlite3_vtab_cursor *pCursor){ + int rc; + int nPayload; + StatCursor *pCsr = (StatCursor *)pCursor; + StatTable *pTab = (StatTable *)pCursor->pVtab; + Btree *pBt = pTab->db->aDb[0].pBt; + Pager *pPager = sqlite3BtreePager(pBt); + + sqlite3_free(pCsr->zPath); + pCsr->zPath = 0; + + if( pCsr->aPage[0].pPg==0 ){ + rc = sqlite3_step(pCsr->pStmt); + if( rc==SQLITE_ROW ){ + int nPage; + u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1); + sqlite3PagerPagecount(pPager, &nPage); + if( nPage==0 ){ + pCsr->isEof = 1; + return sqlite3_reset(pCsr->pStmt); + } + rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg); + pCsr->aPage[0].iPgno = iRoot; + pCsr->aPage[0].iCell = 0; + pCsr->aPage[0].zPath = sqlite3_mprintf("/"); + pCsr->iPage = 0; + }else{ + pCsr->isEof = 1; + return sqlite3_reset(pCsr->pStmt); + } + }else{ + + /* Page p itself has already been visited. */ + StatPage *p = &pCsr->aPage[pCsr->iPage]; + + while( p->iCellnCell ){ + StatCell *pCell = &p->aCell[p->iCell]; + if( pCell->iOvflnOvfl ){ + int nUsable = sqlite3BtreeGetPageSize(pBt)-sqlite3BtreeGetReserve(pBt); + pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0); + pCsr->iPageno = pCell->aOvfl[pCell->iOvfl]; + pCsr->zPagetype = "overflow"; + pCsr->nCell = 0; + pCsr->nMxPayload = 0; + pCsr->zPath = sqlite3_mprintf( + "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl + ); + if( pCell->iOvflnOvfl-1 ){ + pCsr->nUnused = 0; + pCsr->nPayload = nUsable - 4; + }else{ + pCsr->nPayload = pCell->nLastOvfl; + pCsr->nUnused = nUsable - 4 - pCsr->nPayload; + } + pCell->iOvfl++; + statSizeAndOffset(pCsr); + return SQLITE_OK; + } + if( p->iRightChildPg ) break; + p->iCell++; + } + + while( !p->iRightChildPg || p->iCell>p->nCell ){ + statClearPage(p); + if( pCsr->iPage==0 ) return statNext(pCursor); + pCsr->iPage--; + p = &pCsr->aPage[pCsr->iPage]; + } + pCsr->iPage++; + assert( p==&pCsr->aPage[pCsr->iPage-1] ); + + if( p->iCell==p->nCell ){ + p[1].iPgno = p->iRightChildPg; + }else{ + p[1].iPgno = p->aCell[p->iCell].iChildPg; + } + rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg); + p[1].iCell = 0; + p[1].zPath = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell); + p->iCell++; + } + + + /* Populate the StatCursor fields with the values to be returned + ** by the xColumn() and xRowid() methods. + */ + if( rc==SQLITE_OK ){ + int i; + StatPage *p = &pCsr->aPage[pCsr->iPage]; + pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0); + pCsr->iPageno = p->iPgno; + + statDecodePage(pBt, p); + statSizeAndOffset(pCsr); + + switch( p->flags ){ + case 0x05: /* table internal */ + case 0x02: /* index internal */ + pCsr->zPagetype = "internal"; + break; + case 0x0D: /* table leaf */ + case 0x0A: /* index leaf */ + pCsr->zPagetype = "leaf"; + break; + default: + pCsr->zPagetype = "corrupted"; + break; + } + pCsr->nCell = p->nCell; + pCsr->nUnused = p->nUnused; + pCsr->nMxPayload = p->nMxPayload; + pCsr->zPath = sqlite3_mprintf("%s", p->zPath); + nPayload = 0; + for(i=0; inCell; i++){ + nPayload += p->aCell[i].nLocal; + } + pCsr->nPayload = nPayload; + } + + return rc; +} + +static int statEof(sqlite3_vtab_cursor *pCursor){ + StatCursor *pCsr = (StatCursor *)pCursor; + return pCsr->isEof; +} + +static int statFilter( + sqlite3_vtab_cursor *pCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + StatCursor *pCsr = (StatCursor *)pCursor; + + statResetCsr(pCsr); + return statNext(pCursor); +} + +static int statColumn( + sqlite3_vtab_cursor *pCursor, + sqlite3_context *ctx, + int i +){ + StatCursor *pCsr = (StatCursor *)pCursor; + switch( i ){ + case 0: /* name */ + sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_STATIC); + break; + case 1: /* path */ + sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT); + break; + case 2: /* pageno */ + sqlite3_result_int64(ctx, pCsr->iPageno); + break; + case 3: /* pagetype */ + sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC); + break; + case 4: /* ncell */ + sqlite3_result_int(ctx, pCsr->nCell); + break; + case 5: /* payload */ + sqlite3_result_int(ctx, pCsr->nPayload); + break; + case 6: /* unused */ + sqlite3_result_int(ctx, pCsr->nUnused); + break; + case 7: /* mx_payload */ + sqlite3_result_int(ctx, pCsr->nMxPayload); + break; + case 8: /* pgoffset */ + sqlite3_result_int64(ctx, pCsr->iOffset); + break; + case 9: /* pgsize */ + sqlite3_result_int(ctx, pCsr->szPage); + break; + } + return SQLITE_OK; +} + +static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + StatCursor *pCsr = (StatCursor *)pCursor; + *pRowid = pCsr->iPageno; + return SQLITE_OK; +} + +int sqlite3_dbstat_register(sqlite3 *db){ + static sqlite3_module dbstat_module = { + 0, /* iVersion */ + statConnect, /* xCreate */ + statConnect, /* xConnect */ + statBestIndex, /* xBestIndex */ + statDisconnect, /* xDisconnect */ + statDisconnect, /* xDestroy */ + statOpen, /* xOpen - open a cursor */ + statClose, /* xClose - close a cursor */ + statFilter, /* xFilter - configure scan constraints */ + statNext, /* xNext - advance a cursor */ + statEof, /* xEof - check for end of scan */ + statColumn, /* xColumn - read data */ + statRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + }; + sqlite3_create_module(db, "dbstat", &dbstat_module, 0); + return SQLITE_OK; +} + +#endif + +#if defined(SQLITE_TEST) || TCLSH==2 +#include + +static int test_dbstat( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifdef SQLITE_OMIT_VIRTUALTABLE + Tcl_AppendResult(interp, "dbstat not available because of " + "SQLITE_OMIT_VIRTUALTABLE", (void*)0); + return TCL_ERROR; +#else + struct SqliteDb { sqlite3 *db; }; + char *zDb; + Tcl_CmdInfo cmdInfo; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + + zDb = Tcl_GetString(objv[1]); + if( Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){ + sqlite3* db = ((struct SqliteDb*)cmdInfo.objClientData)->db; + sqlite3_dbstat_register(db); + } + return TCL_OK; +#endif +} + +int SqlitetestStat_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "register_dbstat_vtab", test_dbstat, 0, 0); + return TCL_OK; +} +#endif /* if defined(SQLITE_TEST) || TCLSH==2 */ diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_superlock.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_superlock.c new file mode 100644 index 0000000000000000000000000000000000000000..936fcad0c56f6bc85809742f6ae1c1eeb8b7d2f1 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_superlock.c @@ -0,0 +1,356 @@ +/* +** 2010 November 19 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Example code for obtaining an exclusive lock on an SQLite database +** file. This method is complicated, but works for both WAL and rollback +** mode database files. The interface to the example code in this file +** consists of the following two functions: +** +** sqlite3demo_superlock() +** sqlite3demo_superunlock() +*/ + +#include +#include /* memset(), strlen() */ +#include /* assert() */ + +/* +** A structure to collect a busy-handler callback and argument and a count +** of the number of times it has been invoked. +*/ +struct SuperlockBusy { + int (*xBusy)(void*,int); /* Pointer to busy-handler function */ + void *pBusyArg; /* First arg to pass to xBusy */ + int nBusy; /* Number of times xBusy has been invoked */ +}; +typedef struct SuperlockBusy SuperlockBusy; + +/* +** An instance of the following structure is allocated for each active +** superlock. The opaque handle returned by sqlite3demo_superlock() is +** actually a pointer to an instance of this structure. +*/ +struct Superlock { + sqlite3 *db; /* Database handle used to lock db */ + int bWal; /* True if db is a WAL database */ +}; +typedef struct Superlock Superlock; + +/* +** The pCtx pointer passed to this function is actually a pointer to a +** SuperlockBusy structure. Invoke the busy-handler function encapsulated +** by the structure and return the result. +*/ +static int superlockBusyHandler(void *pCtx, int UNUSED){ + SuperlockBusy *pBusy = (SuperlockBusy *)pCtx; + if( pBusy->xBusy==0 ) return 0; + return pBusy->xBusy(pBusy->pBusyArg, pBusy->nBusy++); +} + +/* +** This function is used to determine if the main database file for +** connection db is open in WAL mode or not. If no error occurs and the +** database file is in WAL mode, set *pbWal to true and return SQLITE_OK. +** If it is not in WAL mode, set *pbWal to false. +** +** If an error occurs, return an SQLite error code. The value of *pbWal +** is undefined in this case. +*/ +static int superlockIsWal(Superlock *pLock){ + int rc; /* Return Code */ + sqlite3_stmt *pStmt; /* Compiled PRAGMA journal_mode statement */ + + rc = sqlite3_prepare(pLock->db, "PRAGMA main.journal_mode", -1, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + + pLock->bWal = 0; + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + const char *zMode = (const char *)sqlite3_column_text(pStmt, 0); + if( zMode && strlen(zMode)==3 && sqlite3_strnicmp("wal", zMode, 3)==0 ){ + pLock->bWal = 1; + } + } + + return sqlite3_finalize(pStmt); +} + +/* +** Obtain an exclusive shm-lock on nByte bytes starting at offset idx +** of the file fd. If the lock cannot be obtained immediately, invoke +** the busy-handler until either it is obtained or the busy-handler +** callback returns 0. +*/ +static int superlockShmLock( + sqlite3_file *fd, /* Database file handle */ + int idx, /* Offset of shm-lock to obtain */ + int nByte, /* Number of consective bytes to lock */ + SuperlockBusy *pBusy /* Busy-handler wrapper object */ +){ + int rc; + int (*xShmLock)(sqlite3_file*, int, int, int) = fd->pMethods->xShmLock; + do { + rc = xShmLock(fd, idx, nByte, SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE); + }while( rc==SQLITE_BUSY && superlockBusyHandler((void *)pBusy, 0) ); + return rc; +} + +/* +** Obtain the extra locks on the database file required for WAL databases. +** Invoke the supplied busy-handler as required. +*/ +static int superlockWalLock( + sqlite3 *db, /* Database handle open on WAL database */ + SuperlockBusy *pBusy /* Busy handler wrapper object */ +){ + int rc; /* Return code */ + sqlite3_file *fd = 0; /* Main database file handle */ + void volatile *p = 0; /* Pointer to first page of shared memory */ + + /* Obtain a pointer to the sqlite3_file object open on the main db file. */ + rc = sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, (void *)&fd); + if( rc!=SQLITE_OK ) return rc; + + /* Obtain the "recovery" lock. Normally, this lock is only obtained by + ** clients running database recovery. + */ + rc = superlockShmLock(fd, 2, 1, pBusy); + if( rc!=SQLITE_OK ) return rc; + + /* Zero the start of the first shared-memory page. This means that any + ** clients that open read or write transactions from this point on will + ** have to run recovery before proceeding. Since they need the "recovery" + ** lock that this process is holding to do that, no new read or write + ** transactions may now be opened. Nor can a checkpoint be run, for the + ** same reason. + */ + rc = fd->pMethods->xShmMap(fd, 0, 32*1024, 1, &p); + if( rc!=SQLITE_OK ) return rc; + memset((void *)p, 0, 32); + + /* Obtain exclusive locks on all the "read-lock" slots. Once these locks + ** are held, it is guaranteed that there are no active reader, writer or + ** checkpointer clients. + */ + rc = superlockShmLock(fd, 3, SQLITE_SHM_NLOCK-3, pBusy); + return rc; +} + +/* +** Release a superlock held on a database file. The argument passed to +** this function must have been obtained from a successful call to +** sqlite3demo_superlock(). +*/ +void sqlite3demo_superunlock(void *pLock){ + Superlock *p = (Superlock *)pLock; + if( p->bWal ){ + int rc; /* Return code */ + int flags = SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE; + sqlite3_file *fd = 0; + rc = sqlite3_file_control(p->db, "main", SQLITE_FCNTL_FILE_POINTER, (void *)&fd); + if( rc==SQLITE_OK ){ + fd->pMethods->xShmLock(fd, 2, 1, flags); + fd->pMethods->xShmLock(fd, 3, SQLITE_SHM_NLOCK-3, flags); + } + } + sqlite3_close(p->db); + sqlite3_free(p); +} + +/* +** Obtain a superlock on the database file identified by zPath, using the +** locking primitives provided by VFS zVfs. If successful, SQLITE_OK is +** returned and output variable *ppLock is populated with an opaque handle +** that may be used with sqlite3demo_superunlock() to release the lock. +** +** If an error occurs, *ppLock is set to 0 and an SQLite error code +** (e.g. SQLITE_BUSY) is returned. +** +** If a required lock cannot be obtained immediately and the xBusy parameter +** to this function is not NULL, then xBusy is invoked in the same way +** as a busy-handler registered with SQLite (using sqlite3_busy_handler()) +** until either the lock can be obtained or the busy-handler function returns +** 0 (indicating "give up"). +*/ +int sqlite3demo_superlock( + const char *zPath, /* Path to database file to lock */ + const char *zVfs, /* VFS to use to access database file */ + int (*xBusy)(void*,int), /* Busy handler callback */ + void *pBusyArg, /* Context arg for busy handler */ + void **ppLock /* OUT: Context to pass to superunlock() */ +){ + SuperlockBusy busy = {0, 0, 0}; /* Busy handler wrapper object */ + int rc; /* Return code */ + Superlock *pLock; + + pLock = sqlite3_malloc(sizeof(Superlock)); + if( !pLock ) return SQLITE_NOMEM; + memset(pLock, 0, sizeof(Superlock)); + + /* Open a database handle on the file to superlock. */ + rc = sqlite3_open_v2( + zPath, &pLock->db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs + ); + + /* Install a busy-handler and execute a BEGIN EXCLUSIVE. If this is not + ** a WAL database, this is all we need to do. + ** + ** A wrapper function is used to invoke the busy-handler instead of + ** registering the busy-handler function supplied by the user directly + ** with SQLite. This is because the same busy-handler function may be + ** invoked directly later on when attempting to obtain the extra locks + ** required in WAL mode. By using the wrapper, we are able to guarantee + ** that the "nBusy" integer parameter passed to the users busy-handler + ** represents the total number of busy-handler invocations made within + ** this call to sqlite3demo_superlock(), including any made during the + ** "BEGIN EXCLUSIVE". + */ + if( rc==SQLITE_OK ){ + busy.xBusy = xBusy; + busy.pBusyArg = pBusyArg; + sqlite3_busy_handler(pLock->db, superlockBusyHandler, (void *)&busy); + rc = sqlite3_exec(pLock->db, "BEGIN EXCLUSIVE", 0, 0, 0); + } + + /* If the BEGIN EXCLUSIVE was executed successfully and this is a WAL + ** database, call superlockWalLock() to obtain the extra locks required + ** to prevent readers, writers and/or checkpointers from accessing the + ** db while this process is holding the superlock. + ** + ** Before attempting any WAL locks, commit the transaction started above + ** to drop the WAL read and write locks currently held. Otherwise, the + ** new WAL locks may conflict with the old. + */ + if( rc==SQLITE_OK ){ + if( SQLITE_OK==(rc = superlockIsWal(pLock)) && pLock->bWal ){ + rc = sqlite3_exec(pLock->db, "COMMIT", 0, 0, 0); + if( rc==SQLITE_OK ){ + rc = superlockWalLock(pLock->db, &busy); + } + } + } + + if( rc!=SQLITE_OK ){ + sqlite3demo_superunlock(pLock); + *ppLock = 0; + }else{ + *ppLock = pLock; + } + + return rc; +} + +/* +** End of example code. Everything below here is the test harness. +************************************************************************** +************************************************************************** +*************************************************************************/ + + +#ifdef SQLITE_TEST + +#include + +struct InterpAndScript { + Tcl_Interp *interp; + Tcl_Obj *pScript; +}; +typedef struct InterpAndScript InterpAndScript; + +static void superunlock_del(ClientData cd){ + sqlite3demo_superunlock((void *)cd); +} + +static int superunlock_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + Tcl_DeleteCommand(interp, Tcl_GetString(objv[0])); + return TCL_OK; +} + +static int superlock_busy(void *pCtx, int nBusy){ + InterpAndScript *p = (InterpAndScript *)pCtx; + Tcl_Obj *pEval; /* Script to evaluate */ + int iVal = 0; /* Value to return */ + + pEval = Tcl_DuplicateObj(p->pScript); + Tcl_IncrRefCount(pEval); + Tcl_ListObjAppendElement(p->interp, pEval, Tcl_NewIntObj(nBusy)); + Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL); + Tcl_GetIntFromObj(p->interp, Tcl_GetObjResult(p->interp), &iVal); + Tcl_DecrRefCount(pEval); + + return iVal; +} + +/* +** Tclcmd: sqlite3demo_superlock CMDNAME PATH VFS BUSY-HANDLER-SCRIPT +*/ +static int superlock_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + void *pLock; /* Lock context */ + char *zPath; + char *zVfs = 0; + InterpAndScript busy = {0, 0}; + int (*xBusy)(void*,int) = 0; /* Busy handler callback */ + int rc; /* Return code from sqlite3demo_superlock() */ + + if( objc<3 || objc>5 ){ + Tcl_WrongNumArgs( + interp, 1, objv, "CMDNAME PATH ?VFS? ?BUSY-HANDLER-SCRIPT?"); + return TCL_ERROR; + } + + zPath = Tcl_GetString(objv[2]); + + if( objc>3 ){ + zVfs = Tcl_GetString(objv[3]); + if( strlen(zVfs)==0 ) zVfs = 0; + } + if( objc>4 ){ + busy.interp = interp; + busy.pScript = objv[4]; + xBusy = superlock_busy; + } + + rc = sqlite3demo_superlock(zPath, zVfs, xBusy, &busy, &pLock); + assert( rc==SQLITE_OK || pLock==0 ); + assert( rc!=SQLITE_OK || pLock!=0 ); + + if( rc!=SQLITE_OK ){ + extern const char *sqlite3ErrStr(int); + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0); + return TCL_ERROR; + } + + Tcl_CreateObjCommand( + interp, Tcl_GetString(objv[1]), superunlock_cmd, pLock, superunlock_del + ); + Tcl_SetObjResult(interp, objv[1]); + return TCL_OK; +} + +int SqliteSuperlock_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "sqlite3demo_superlock", superlock_cmd, 0, 0); + return TCL_OK; +} +#endif diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_syscall.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_syscall.c new file mode 100644 index 0000000000000000000000000000000000000000..7c0873c16d843202f30e2db9459fa29975ea5e68 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_syscall.c @@ -0,0 +1,705 @@ +/* +** 2011 March 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** The code in this file implements a Tcl interface used to test error +** handling in the os_unix.c module. Wrapper functions that support fault +** injection are registered as the low-level OS functions using the +** xSetSystemCall() method of the VFS. The Tcl interface is as follows: +** +** +** test_syscall install LIST +** Install wrapper functions for all system calls in argument LIST. +** LIST must be a list consisting of zero or more of the following +** literal values: +** +** open close access getcwd stat fstat +** ftruncate fcntl read pread pread64 write +** pwrite pwrite64 fchmod fallocate mmap +** +** test_syscall uninstall +** Uninstall all wrapper functions. +** +** test_syscall fault ?COUNT PERSIST? +** If [test_syscall fault] is invoked without the two arguments, fault +** injection is disabled. Otherwise, fault injection is configured to +** cause a failure on the COUNT'th next call to a system call with a +** wrapper function installed. A COUNT value of 1 means fail the next +** system call. +** +** Argument PERSIST is interpreted as a boolean. If true, the all +** system calls following the initial failure also fail. Otherwise, only +** the single transient failure is injected. +** +** test_syscall errno CALL ERRNO +** Set the value that the global "errno" is set to following a fault +** in call CALL. Argument CALL must be one of the system call names +** listed above (under [test_syscall install]). ERRNO is a symbolic +** name (i.e. "EACCES"). Not all errno codes are supported. Add extra +** to the aErrno table in function test_syscall_errno() below as +** required. +** +** test_syscall reset ?SYSTEM-CALL? +** With no argument, this is an alias for the [uninstall] command. However, +** this command uses a VFS call of the form: +** +** xSetSystemCall(pVfs, 0, 0); +** +** To restore the default system calls. The [uninstall] command restores +** each system call individually by calling (i.e.): +** +** xSetSystemCall(pVfs, "open", 0); +** +** With an argument, this command attempts to reset the system call named +** by the parameter using the same method as [uninstall]. +** +** test_syscall exists SYSTEM-CALL +** Return true if the named system call exists. Or false otherwise. +** +** test_syscall list +** Return a list of all system calls. The list is constructed using +** the xNextSystemCall() VFS method. +*/ + +#include "sqliteInt.h" +#include "sqlite3.h" +#include "tcl.h" +#include +#include +#include + +#if SQLITE_OS_UNIX + +/* From main.c */ +extern const char *sqlite3ErrName(int); + +#include +#include +#include + +static struct TestSyscallGlobal { + int bPersist; /* 1 for persistent errors, 0 for transient */ + int nCount; /* Fail after this many more calls */ + int nFail; /* Number of failures that have occurred */ +} gSyscall = { 0, 0 }; + +static int ts_open(const char *, int, int); +static int ts_close(int fd); +static int ts_access(const char *zPath, int mode); +static char *ts_getcwd(char *zPath, size_t nPath); +static int ts_stat(const char *zPath, struct stat *p); +static int ts_fstat(int fd, struct stat *p); +static int ts_ftruncate(int fd, off_t n); +static int ts_fcntl(int fd, int cmd, ... ); +static int ts_read(int fd, void *aBuf, size_t nBuf); +static int ts_pread(int fd, void *aBuf, size_t nBuf, off_t off); +static int ts_pread64(int fd, void *aBuf, size_t nBuf, off_t off); +static int ts_write(int fd, const void *aBuf, size_t nBuf); +static int ts_pwrite(int fd, const void *aBuf, size_t nBuf, off_t off); +static int ts_pwrite64(int fd, const void *aBuf, size_t nBuf, off_t off); +static int ts_fchmod(int fd, mode_t mode); +static int ts_fallocate(int fd, off_t off, off_t len); +static void *ts_mmap(void *, size_t, int, int, int, off_t); +static void *ts_mremap(void*, size_t, size_t, int, ...); + +struct TestSyscallArray { + const char *zName; + sqlite3_syscall_ptr xTest; + sqlite3_syscall_ptr xOrig; + int default_errno; /* Default value for errno following errors */ + int custom_errno; /* Current value for errno if error */ +} aSyscall[] = { + /* 0 */ { "open", (sqlite3_syscall_ptr)ts_open, 0, EACCES, 0 }, + /* 1 */ { "close", (sqlite3_syscall_ptr)ts_close, 0, 0, 0 }, + /* 2 */ { "access", (sqlite3_syscall_ptr)ts_access, 0, 0, 0 }, + /* 3 */ { "getcwd", (sqlite3_syscall_ptr)ts_getcwd, 0, 0, 0 }, + /* 4 */ { "stat", (sqlite3_syscall_ptr)ts_stat, 0, 0, 0 }, + /* 5 */ { "fstat", (sqlite3_syscall_ptr)ts_fstat, 0, 0, 0 }, + /* 6 */ { "ftruncate", (sqlite3_syscall_ptr)ts_ftruncate, 0, EIO, 0 }, + /* 7 */ { "fcntl", (sqlite3_syscall_ptr)ts_fcntl, 0, EACCES, 0 }, + /* 8 */ { "read", (sqlite3_syscall_ptr)ts_read, 0, 0, 0 }, + /* 9 */ { "pread", (sqlite3_syscall_ptr)ts_pread, 0, 0, 0 }, + /* 10 */ { "pread64", (sqlite3_syscall_ptr)ts_pread64, 0, 0, 0 }, + /* 11 */ { "write", (sqlite3_syscall_ptr)ts_write, 0, 0, 0 }, + /* 12 */ { "pwrite", (sqlite3_syscall_ptr)ts_pwrite, 0, 0, 0 }, + /* 13 */ { "pwrite64", (sqlite3_syscall_ptr)ts_pwrite64, 0, 0, 0 }, + /* 14 */ { "fchmod", (sqlite3_syscall_ptr)ts_fchmod, 0, 0, 0 }, + /* 15 */ { "fallocate", (sqlite3_syscall_ptr)ts_fallocate, 0, 0, 0 }, + /* 16 */ { "mmap", (sqlite3_syscall_ptr)ts_mmap, 0, 0, 0 }, + /* 17 */ { "mremap", (sqlite3_syscall_ptr)ts_mremap, 0, 0, 0 }, + { 0, 0, 0, 0, 0 } +}; + +#define orig_open ((int(*)(const char *, int, int))aSyscall[0].xOrig) +#define orig_close ((int(*)(int))aSyscall[1].xOrig) +#define orig_access ((int(*)(const char*,int))aSyscall[2].xOrig) +#define orig_getcwd ((char*(*)(char*,size_t))aSyscall[3].xOrig) +#define orig_stat ((int(*)(const char*,struct stat*))aSyscall[4].xOrig) +#define orig_fstat ((int(*)(int,struct stat*))aSyscall[5].xOrig) +#define orig_ftruncate ((int(*)(int,off_t))aSyscall[6].xOrig) +#define orig_fcntl ((int(*)(int,int,...))aSyscall[7].xOrig) +#define orig_read ((ssize_t(*)(int,void*,size_t))aSyscall[8].xOrig) +#define orig_pread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].xOrig) +#define orig_pread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].xOrig) +#define orig_write ((ssize_t(*)(int,const void*,size_t))aSyscall[11].xOrig) +#define orig_pwrite ((ssize_t(*)(int,const void*,size_t,off_t))\ + aSyscall[12].xOrig) +#define orig_pwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\ + aSyscall[13].xOrig) +#define orig_fchmod ((int(*)(int,mode_t))aSyscall[14].xOrig) +#define orig_fallocate ((int(*)(int,off_t,off_t))aSyscall[15].xOrig) +#define orig_mmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[16].xOrig) +#define orig_mremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[17].xOrig) + +/* +** This function is called exactly once from within each invocation of a +** system call wrapper in this file. It returns 1 if the function should +** fail, or 0 if it should succeed. +*/ +static int tsIsFail(void){ + gSyscall.nCount--; + if( gSyscall.nCount==0 || (gSyscall.nFail && gSyscall.bPersist) ){ + gSyscall.nFail++; + return 1; + } + return 0; +} + +/* +** Return the current error-number value for function zFunc. zFunc must be +** the name of a system call in the aSyscall[] table. +** +** Usually, the current error-number is the value that errno should be set +** to if the named system call fails. The exception is "fallocate". See +** comments above the implementation of ts_fallocate() for details. +*/ +static int tsErrno(const char *zFunc){ + int i; + int nFunc = strlen(zFunc); + for(i=0; aSyscall[i].zName; i++){ + if( strlen(aSyscall[i].zName)!=nFunc ) continue; + if( memcmp(aSyscall[i].zName, zFunc, nFunc) ) continue; + return aSyscall[i].custom_errno; + } + + assert(0); + return 0; +} + +/* +** A wrapper around tsIsFail(). If tsIsFail() returns non-zero, set the +** value of errno before returning. +*/ +static int tsIsFailErrno(const char *zFunc){ + if( tsIsFail() ){ + errno = tsErrno(zFunc); + return 1; + } + return 0; +} + +/* +** A wrapper around open(). +*/ +static int ts_open(const char *zFile, int flags, int mode){ + if( tsIsFailErrno("open") ){ + return -1; + } + return orig_open(zFile, flags, mode); +} + +/* +** A wrapper around close(). +*/ +static int ts_close(int fd){ + if( tsIsFail() ){ + /* Even if simulating an error, close the original file-descriptor. + ** This is to stop the test process from running out of file-descriptors + ** when running a long test. If a call to close() appears to fail, SQLite + ** never attempts to use the file-descriptor afterwards (or even to close + ** it a second time). */ + orig_close(fd); + return -1; + } + return orig_close(fd); +} + +/* +** A wrapper around access(). +*/ +static int ts_access(const char *zPath, int mode){ + if( tsIsFail() ){ + return -1; + } + return orig_access(zPath, mode); +} + +/* +** A wrapper around getcwd(). +*/ +static char *ts_getcwd(char *zPath, size_t nPath){ + if( tsIsFail() ){ + return NULL; + } + return orig_getcwd(zPath, nPath); +} + +/* +** A wrapper around stat(). +*/ +static int ts_stat(const char *zPath, struct stat *p){ + if( tsIsFail() ){ + return -1; + } + return orig_stat(zPath, p); +} + +/* +** A wrapper around fstat(). +*/ +static int ts_fstat(int fd, struct stat *p){ + if( tsIsFailErrno("fstat") ){ + return -1; + } + return orig_fstat(fd, p); +} + +/* +** A wrapper around ftruncate(). +*/ +static int ts_ftruncate(int fd, off_t n){ + if( tsIsFailErrno("ftruncate") ){ + return -1; + } + return orig_ftruncate(fd, n); +} + +/* +** A wrapper around fcntl(). +*/ +static int ts_fcntl(int fd, int cmd, ... ){ + va_list ap; + void *pArg; + if( tsIsFailErrno("fcntl") ){ + return -1; + } + va_start(ap, cmd); + pArg = va_arg(ap, void *); + return orig_fcntl(fd, cmd, pArg); +} + +/* +** A wrapper around read(). +*/ +static int ts_read(int fd, void *aBuf, size_t nBuf){ + if( tsIsFailErrno("read") ){ + return -1; + } + return orig_read(fd, aBuf, nBuf); +} + +/* +** A wrapper around pread(). +*/ +static int ts_pread(int fd, void *aBuf, size_t nBuf, off_t off){ + if( tsIsFailErrno("pread") ){ + return -1; + } + return orig_pread(fd, aBuf, nBuf, off); +} + +/* +** A wrapper around pread64(). +*/ +static int ts_pread64(int fd, void *aBuf, size_t nBuf, off_t off){ + if( tsIsFailErrno("pread64") ){ + return -1; + } + return orig_pread64(fd, aBuf, nBuf, off); +} + +/* +** A wrapper around write(). +*/ +static int ts_write(int fd, const void *aBuf, size_t nBuf){ + if( tsIsFailErrno("write") ){ + if( tsErrno("write")==EINTR ) orig_write(fd, aBuf, nBuf/2); + return -1; + } + return orig_write(fd, aBuf, nBuf); +} + +/* +** A wrapper around pwrite(). +*/ +static int ts_pwrite(int fd, const void *aBuf, size_t nBuf, off_t off){ + if( tsIsFailErrno("pwrite") ){ + return -1; + } + return orig_pwrite(fd, aBuf, nBuf, off); +} + +/* +** A wrapper around pwrite64(). +*/ +static int ts_pwrite64(int fd, const void *aBuf, size_t nBuf, off_t off){ + if( tsIsFailErrno("pwrite64") ){ + return -1; + } + return orig_pwrite64(fd, aBuf, nBuf, off); +} + +/* +** A wrapper around fchmod(). +*/ +static int ts_fchmod(int fd, mode_t mode){ + if( tsIsFail() ){ + return -1; + } + return orig_fchmod(fd, mode); +} + +/* +** A wrapper around fallocate(). +** +** SQLite assumes that the fallocate() function is compatible with +** posix_fallocate(). According to the Linux man page (2009-09-30): +** +** posix_fallocate() returns zero on success, or an error number on +** failure. Note that errno is not set. +*/ +static int ts_fallocate(int fd, off_t off, off_t len){ + if( tsIsFail() ){ + return tsErrno("fallocate"); + } + return orig_fallocate(fd, off, len); +} + +static void *ts_mmap( + void *pAddr, + size_t nByte, + int prot, + int flags, + int fd, + off_t iOff +){ + if( tsIsFailErrno("mmap") ){ + return MAP_FAILED; + } + return orig_mmap(pAddr, nByte, prot, flags, fd, iOff); +} + +static void *ts_mremap(void *a, size_t b, size_t c, int d, ...){ + va_list ap; + void *pArg; + if( tsIsFailErrno("mremap") ){ + return MAP_FAILED; + } + va_start(ap, d); + pArg = va_arg(ap, void *); + return orig_mremap(a, b, c, d, pArg); +} + +static int test_syscall_install( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + int nElem; + int i; + Tcl_Obj **apElem; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SYSCALL-LIST"); + return TCL_ERROR; + } + if( Tcl_ListObjGetElements(interp, objv[2], &nElem, &apElem) ){ + return TCL_ERROR; + } + pVfs = sqlite3_vfs_find(0); + + for(i=0; ixGetSystemCall(pVfs, aSyscall[iCall].zName); + pVfs->xSetSystemCall(pVfs, aSyscall[iCall].zName, aSyscall[iCall].xTest); + } + aSyscall[iCall].custom_errno = aSyscall[iCall].default_errno; + } + + return TCL_OK; +} + +static int test_syscall_uninstall( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + int i; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + for(i=0; aSyscall[i].zName; i++){ + if( aSyscall[i].xOrig ){ + pVfs->xSetSystemCall(pVfs, aSyscall[i].zName, 0); + aSyscall[i].xOrig = 0; + } + } + return TCL_OK; +} + +static int test_syscall_reset( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + int i; + int rc; + + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + if( objc==2 ){ + rc = pVfs->xSetSystemCall(pVfs, 0, 0); + for(i=0; aSyscall[i].zName; i++) aSyscall[i].xOrig = 0; + }else{ + int nFunc; + char *zFunc = Tcl_GetStringFromObj(objv[2], &nFunc); + rc = pVfs->xSetSystemCall(pVfs, Tcl_GetString(objv[2]), 0); + for(i=0; rc==SQLITE_OK && aSyscall[i].zName; i++){ + if( strlen(aSyscall[i].zName)!=nFunc ) continue; + if( memcmp(aSyscall[i].zName, zFunc, nFunc) ) continue; + aSyscall[i].xOrig = 0; + } + } + if( rc!=SQLITE_OK ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); + return TCL_ERROR; + } + + Tcl_ResetResult(interp); + return TCL_OK; +} + +static int test_syscall_exists( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + sqlite3_syscall_ptr x; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + x = pVfs->xGetSystemCall(pVfs, Tcl_GetString(objv[2])); + + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(x!=0)); + return TCL_OK; +} + +static int test_syscall_fault( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int nCount = 0; + int bPersist = 0; + + if( objc!=2 && objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?COUNT PERSIST?"); + return TCL_ERROR; + } + + if( objc==4 ){ + if( Tcl_GetIntFromObj(interp, objv[2], &nCount) + || Tcl_GetBooleanFromObj(interp, objv[3], &bPersist) + ){ + return TCL_ERROR; + } + } + + Tcl_SetObjResult(interp, Tcl_NewIntObj(gSyscall.nFail)); + gSyscall.nCount = nCount; + gSyscall.bPersist = bPersist; + gSyscall.nFail = 0; + return TCL_OK; +} + +static int test_syscall_errno( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int iCall; + int iErrno; + int rc; + + struct Errno { + const char *z; + int i; + } aErrno[] = { + { "EACCES", EACCES }, + { "EINTR", EINTR }, + { "EIO", EIO }, + { "EOVERFLOW", EOVERFLOW }, + { "ENOMEM", ENOMEM }, + { "EAGAIN", EAGAIN }, + { "ETIMEDOUT", ETIMEDOUT }, + { "EBUSY", EBUSY }, + { "EPERM", EPERM }, + { "EDEADLK", EDEADLK }, + { "ENOLCK", ENOLCK }, + { 0, 0 } + }; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SYSCALL ERRNO"); + return TCL_ERROR; + } + + rc = Tcl_GetIndexFromObjStruct(interp, + objv[2], aSyscall, sizeof(aSyscall[0]), "system-call", 0, &iCall + ); + if( rc!=TCL_OK ) return rc; + rc = Tcl_GetIndexFromObjStruct(interp, + objv[3], aErrno, sizeof(aErrno[0]), "errno", 0, &iErrno + ); + if( rc!=TCL_OK ) return rc; + + aSyscall[iCall].custom_errno = aErrno[iErrno].i; + return TCL_OK; +} + +static int test_syscall_list( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zSys; + sqlite3_vfs *pVfs; + Tcl_Obj *pList; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + pList = Tcl_NewObj(); + Tcl_IncrRefCount(pList); + for(zSys = pVfs->xNextSystemCall(pVfs, 0); + zSys!=0; + zSys = pVfs->xNextSystemCall(pVfs, zSys) + ){ + Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj(zSys, -1)); + } + + Tcl_SetObjResult(interp, pList); + Tcl_DecrRefCount(pList); + return TCL_OK; +} + +static int test_syscall_defaultvfs( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + Tcl_SetObjResult(interp, Tcl_NewStringObj(pVfs->zName, -1)); + return TCL_OK; +} + +static int test_syscall( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct SyscallCmd { + const char *zName; + Tcl_ObjCmdProc *xCmd; + } aCmd[] = { + { "fault", test_syscall_fault }, + { "install", test_syscall_install }, + { "uninstall", test_syscall_uninstall }, + { "reset", test_syscall_reset }, + { "errno", test_syscall_errno }, + { "exists", test_syscall_exists }, + { "list", test_syscall_list }, + { "defaultvfs", test_syscall_defaultvfs }, + { 0, 0 } + }; + int iCmd; + int rc; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND ..."); + return TCL_ERROR; + } + rc = Tcl_GetIndexFromObjStruct(interp, + objv[1], aCmd, sizeof(aCmd[0]), "sub-command", 0, &iCmd + ); + if( rc!=TCL_OK ) return rc; + return aCmd[iCmd].xCmd(clientData, interp, objc, objv); +} + +int SqlitetestSyscall_Init(Tcl_Interp *interp){ + struct SyscallCmd { + const char *zName; + Tcl_ObjCmdProc *xCmd; + } aCmd[] = { + { "test_syscall", test_syscall}, + }; + int i; + + for(i=0; i +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +typedef struct tclvar_vtab tclvar_vtab; +typedef struct tclvar_cursor tclvar_cursor; + +/* +** A tclvar virtual-table object +*/ +struct tclvar_vtab { + sqlite3_vtab base; + Tcl_Interp *interp; +}; + +/* A tclvar cursor object */ +struct tclvar_cursor { + sqlite3_vtab_cursor base; + + Tcl_Obj *pList1; /* Result of [info vars ?pattern?] */ + Tcl_Obj *pList2; /* Result of [array names [lindex $pList1 $i1]] */ + int i1; /* Current item in pList1 */ + int i2; /* Current item (if any) in pList2 */ +}; + +/* Methods for the tclvar module */ +static int tclvarConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + tclvar_vtab *pVtab; + static const char zSchema[] = + "CREATE TABLE whatever(name TEXT, arrayname TEXT, value TEXT)"; + pVtab = sqlite3MallocZero( sizeof(*pVtab) ); + if( pVtab==0 ) return SQLITE_NOMEM; + *ppVtab = &pVtab->base; + pVtab->interp = (Tcl_Interp *)pAux; + sqlite3_declare_vtab(db, zSchema); + return SQLITE_OK; +} +/* Note that for this virtual table, the xCreate and xConnect +** methods are identical. */ + +static int tclvarDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} +/* The xDisconnect and xDestroy methods are also the same */ + +/* +** Open a new tclvar cursor. +*/ +static int tclvarOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + tclvar_cursor *pCur; + pCur = sqlite3MallocZero(sizeof(tclvar_cursor)); + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Close a tclvar cursor. +*/ +static int tclvarClose(sqlite3_vtab_cursor *cur){ + tclvar_cursor *pCur = (tclvar_cursor *)cur; + if( pCur->pList1 ){ + Tcl_DecrRefCount(pCur->pList1); + } + if( pCur->pList2 ){ + Tcl_DecrRefCount(pCur->pList2); + } + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Returns 1 if data is ready, or 0 if not. +*/ +static int next2(Tcl_Interp *interp, tclvar_cursor *pCur, Tcl_Obj *pObj){ + Tcl_Obj *p; + + if( pObj ){ + if( !pCur->pList2 ){ + p = Tcl_NewStringObj("array names", -1); + Tcl_IncrRefCount(p); + Tcl_ListObjAppendElement(0, p, pObj); + Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL); + Tcl_DecrRefCount(p); + pCur->pList2 = Tcl_GetObjResult(interp); + Tcl_IncrRefCount(pCur->pList2); + assert( pCur->i2==0 ); + }else{ + int n = 0; + pCur->i2++; + Tcl_ListObjLength(0, pCur->pList2, &n); + if( pCur->i2>=n ){ + Tcl_DecrRefCount(pCur->pList2); + pCur->pList2 = 0; + pCur->i2 = 0; + return 0; + } + } + } + + return 1; +} + +static int tclvarNext(sqlite3_vtab_cursor *cur){ + Tcl_Obj *pObj; + int n = 0; + int ok = 0; + + tclvar_cursor *pCur = (tclvar_cursor *)cur; + Tcl_Interp *interp = ((tclvar_vtab *)(cur->pVtab))->interp; + + Tcl_ListObjLength(0, pCur->pList1, &n); + while( !ok && pCur->i1pList1, pCur->i1, &pObj); + ok = next2(interp, pCur, pObj); + if( !ok ){ + pCur->i1++; + } + } + + return 0; +} + +static int tclvarFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + tclvar_cursor *pCur = (tclvar_cursor *)pVtabCursor; + Tcl_Interp *interp = ((tclvar_vtab *)(pVtabCursor->pVtab))->interp; + + Tcl_Obj *p = Tcl_NewStringObj("info vars", -1); + Tcl_IncrRefCount(p); + + assert( argc==0 || argc==1 ); + if( argc==1 ){ + Tcl_Obj *pArg = Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1); + Tcl_ListObjAppendElement(0, p, pArg); + } + Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL); + if( pCur->pList1 ){ + Tcl_DecrRefCount(pCur->pList1); + } + if( pCur->pList2 ){ + Tcl_DecrRefCount(pCur->pList2); + pCur->pList2 = 0; + } + pCur->i1 = 0; + pCur->i2 = 0; + pCur->pList1 = Tcl_GetObjResult(interp); + Tcl_IncrRefCount(pCur->pList1); + assert( pCur->i1==0 && pCur->i2==0 && pCur->pList2==0 ); + + Tcl_DecrRefCount(p); + return tclvarNext(pVtabCursor); +} + +static int tclvarColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + Tcl_Obj *p1; + Tcl_Obj *p2; + const char *z1; + const char *z2 = ""; + tclvar_cursor *pCur = (tclvar_cursor*)cur; + Tcl_Interp *interp = ((tclvar_vtab *)cur->pVtab)->interp; + + Tcl_ListObjIndex(interp, pCur->pList1, pCur->i1, &p1); + Tcl_ListObjIndex(interp, pCur->pList2, pCur->i2, &p2); + z1 = Tcl_GetString(p1); + if( p2 ){ + z2 = Tcl_GetString(p2); + } + switch (i) { + case 0: { + sqlite3_result_text(ctx, z1, -1, SQLITE_TRANSIENT); + break; + } + case 1: { + sqlite3_result_text(ctx, z2, -1, SQLITE_TRANSIENT); + break; + } + case 2: { + Tcl_Obj *pVal = Tcl_GetVar2Ex(interp, z1, *z2?z2:0, TCL_GLOBAL_ONLY); + sqlite3_result_text(ctx, Tcl_GetString(pVal), -1, SQLITE_TRANSIENT); + break; + } + } + return SQLITE_OK; +} + +static int tclvarRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + *pRowid = 0; + return SQLITE_OK; +} + +static int tclvarEof(sqlite3_vtab_cursor *cur){ + tclvar_cursor *pCur = (tclvar_cursor*)cur; + return (pCur->pList2?0:1); +} + +static int tclvarBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int ii; + + for(ii=0; iinConstraint; ii++){ + struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii]; + if( pCons->iColumn==0 && pCons->usable + && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + struct sqlite3_index_constraint_usage *pUsage; + pUsage = &pIdxInfo->aConstraintUsage[ii]; + pUsage->omit = 0; + pUsage->argvIndex = 1; + return SQLITE_OK; + } + } + + for(ii=0; iinConstraint; ii++){ + struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii]; + if( pCons->iColumn==0 && pCons->usable + && pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ + struct sqlite3_index_constraint_usage *pUsage; + pUsage = &pIdxInfo->aConstraintUsage[ii]; + pUsage->omit = 1; + pUsage->argvIndex = 1; + return SQLITE_OK; + } + } + + return SQLITE_OK; +} + +/* +** A virtual table module that provides read-only access to a +** Tcl global variable namespace. +*/ +static sqlite3_module tclvarModule = { + 0, /* iVersion */ + tclvarConnect, + tclvarConnect, + tclvarBestIndex, + tclvarDisconnect, + tclvarDisconnect, + tclvarOpen, /* xOpen - open a cursor */ + tclvarClose, /* xClose - close a cursor */ + tclvarFilter, /* xFilter - configure scan constraints */ + tclvarNext, /* xNext - advance a cursor */ + tclvarEof, /* xEof - check for end of scan */ + tclvarColumn, /* xColumn - read data */ + tclvarRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +/* +** Decode a pointer to an sqlite3 object. +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); + +/* +** Register the echo virtual table module. +*/ +static int register_tclvar_module( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_create_module(db, "tclvar", &tclvarModule, (void *)interp); +#endif + return TCL_OK; +} + +#endif + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetesttclvar_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "register_tclvar_module", register_tclvar_module, 0 }, + }; + int i; + for(i=0; i + +#if SQLITE_THREADSAFE + +#include + +#if !defined(_MSC_VER) +#include +#endif + +/* +** One of these is allocated for each thread created by [sqlthread spawn]. +*/ +typedef struct SqlThread SqlThread; +struct SqlThread { + Tcl_ThreadId parent; /* Thread id of parent thread */ + Tcl_Interp *interp; /* Parent interpreter */ + char *zScript; /* The script to execute. */ + char *zVarname; /* Varname in parent script */ +}; + +/* +** A custom Tcl_Event type used by this module. When the event is +** handled, script zScript is evaluated in interpreter interp. If +** the evaluation throws an exception (returns TCL_ERROR), then the +** error is handled by Tcl_BackgroundError(). If no error occurs, +** the result is simply discarded. +*/ +typedef struct EvalEvent EvalEvent; +struct EvalEvent { + Tcl_Event base; /* Base class of type Tcl_Event */ + char *zScript; /* The script to execute. */ + Tcl_Interp *interp; /* The interpreter to execute it in. */ +}; + +static Tcl_ObjCmdProc sqlthread_proc; +static Tcl_ObjCmdProc clock_seconds_proc; +#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) +static Tcl_ObjCmdProc blocking_step_proc; +static Tcl_ObjCmdProc blocking_prepare_v2_proc; +#endif +int Sqlitetest1_Init(Tcl_Interp *); +int Sqlite3_Init(Tcl_Interp *); + +/* Functions from main.c */ +extern const char *sqlite3ErrName(int); + +/* Functions from test1.c */ +extern void *sqlite3TestTextToPtr(const char *); +extern int getDbPointer(Tcl_Interp *, const char *, sqlite3 **); +extern int sqlite3TestMakePointerStr(Tcl_Interp *, char *, void *); +extern int sqlite3TestErrCode(Tcl_Interp *, sqlite3 *, int); + +/* +** Handler for events of type EvalEvent. +*/ +static int tclScriptEvent(Tcl_Event *evPtr, int flags){ + int rc; + EvalEvent *p = (EvalEvent *)evPtr; + rc = Tcl_Eval(p->interp, p->zScript); + if( rc!=TCL_OK ){ + Tcl_BackgroundError(p->interp); + } + UNUSED_PARAMETER(flags); + return 1; +} + +/* +** Register an EvalEvent to evaluate the script pScript in the +** parent interpreter/thread of SqlThread p. +*/ +static void postToParent(SqlThread *p, Tcl_Obj *pScript){ + EvalEvent *pEvent; + char *zMsg; + int nMsg; + + zMsg = Tcl_GetStringFromObj(pScript, &nMsg); + pEvent = (EvalEvent *)ckalloc(sizeof(EvalEvent)+nMsg+1); + pEvent->base.nextPtr = 0; + pEvent->base.proc = tclScriptEvent; + pEvent->zScript = (char *)&pEvent[1]; + memcpy(pEvent->zScript, zMsg, nMsg+1); + pEvent->interp = p->interp; + + Tcl_ThreadQueueEvent(p->parent, (Tcl_Event *)pEvent, TCL_QUEUE_TAIL); + Tcl_ThreadAlert(p->parent); +} + +/* +** The main function for threads created with [sqlthread spawn]. +*/ +static Tcl_ThreadCreateType tclScriptThread(ClientData pSqlThread){ + Tcl_Interp *interp; + Tcl_Obj *pRes; + Tcl_Obj *pList; + int rc; + SqlThread *p = (SqlThread *)pSqlThread; + extern int Sqlitetest_mutex_Init(Tcl_Interp*); + + interp = Tcl_CreateInterp(); + Tcl_CreateObjCommand(interp, "clock_seconds", clock_seconds_proc, 0, 0); + Tcl_CreateObjCommand(interp, "sqlthread", sqlthread_proc, pSqlThread, 0); +#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) + Tcl_CreateObjCommand(interp, "sqlite3_blocking_step", blocking_step_proc,0,0); + Tcl_CreateObjCommand(interp, + "sqlite3_blocking_prepare_v2", blocking_prepare_v2_proc, (void *)1, 0); + Tcl_CreateObjCommand(interp, + "sqlite3_nonblocking_prepare_v2", blocking_prepare_v2_proc, 0, 0); +#endif + Sqlitetest1_Init(interp); + Sqlitetest_mutex_Init(interp); + Sqlite3_Init(interp); + + rc = Tcl_Eval(interp, p->zScript); + pRes = Tcl_GetObjResult(interp); + pList = Tcl_NewObj(); + Tcl_IncrRefCount(pList); + Tcl_IncrRefCount(pRes); + + if( rc!=TCL_OK ){ + Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj("error", -1)); + Tcl_ListObjAppendElement(interp, pList, pRes); + postToParent(p, pList); + Tcl_DecrRefCount(pList); + pList = Tcl_NewObj(); + } + + Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj("set", -1)); + Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj(p->zVarname, -1)); + Tcl_ListObjAppendElement(interp, pList, pRes); + postToParent(p, pList); + + ckfree((void *)p); + Tcl_DecrRefCount(pList); + Tcl_DecrRefCount(pRes); + Tcl_DeleteInterp(interp); + while( Tcl_DoOneEvent(TCL_ALL_EVENTS|TCL_DONT_WAIT) ); + Tcl_ExitThread(0); + TCL_THREAD_CREATE_RETURN; +} + +/* +** sqlthread spawn VARNAME SCRIPT +** +** Spawn a new thread with its own Tcl interpreter and run the +** specified SCRIPT(s) in it. The thread terminates after running +** the script. The result of the script is stored in the variable +** VARNAME. +** +** The caller can wait for the script to terminate using [vwait VARNAME]. +*/ +static int sqlthread_spawn( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_ThreadId x; + SqlThread *pNew; + int rc; + + int nVarname; char *zVarname; + int nScript; char *zScript; + + /* Parameters for thread creation */ + const int nStack = TCL_THREAD_STACK_DEFAULT; + const int flags = TCL_THREAD_NOFLAGS; + + assert(objc==4); + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + + zVarname = Tcl_GetStringFromObj(objv[2], &nVarname); + zScript = Tcl_GetStringFromObj(objv[3], &nScript); + + pNew = (SqlThread *)ckalloc(sizeof(SqlThread)+nVarname+nScript+2); + pNew->zVarname = (char *)&pNew[1]; + pNew->zScript = (char *)&pNew->zVarname[nVarname+1]; + memcpy(pNew->zVarname, zVarname, nVarname+1); + memcpy(pNew->zScript, zScript, nScript+1); + pNew->parent = Tcl_GetCurrentThread(); + pNew->interp = interp; + + rc = Tcl_CreateThread(&x, tclScriptThread, (void *)pNew, nStack, flags); + if( rc!=TCL_OK ){ + Tcl_AppendResult(interp, "Error in Tcl_CreateThread()", 0); + ckfree((char *)pNew); + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** sqlthread parent SCRIPT +** +** This can be called by spawned threads only. It sends the specified +** script back to the parent thread for execution. The result of +** evaluating the SCRIPT is returned. The parent thread must enter +** the event loop for this to work - otherwise the caller will +** block indefinitely. +** +** NOTE: At the moment, this doesn't work. FIXME. +*/ +static int sqlthread_parent( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + EvalEvent *pEvent; + char *zMsg; + int nMsg; + SqlThread *p = (SqlThread *)clientData; + + assert(objc==3); + UNUSED_PARAMETER(objc); + + if( p==0 ){ + Tcl_AppendResult(interp, "no parent thread", 0); + return TCL_ERROR; + } + + zMsg = Tcl_GetStringFromObj(objv[2], &nMsg); + pEvent = (EvalEvent *)ckalloc(sizeof(EvalEvent)+nMsg+1); + pEvent->base.nextPtr = 0; + pEvent->base.proc = tclScriptEvent; + pEvent->zScript = (char *)&pEvent[1]; + memcpy(pEvent->zScript, zMsg, nMsg+1); + pEvent->interp = p->interp; + Tcl_ThreadQueueEvent(p->parent, (Tcl_Event *)pEvent, TCL_QUEUE_TAIL); + Tcl_ThreadAlert(p->parent); + + return TCL_OK; +} + +static int xBusy(void *pArg, int nBusy){ + UNUSED_PARAMETER(pArg); + UNUSED_PARAMETER(nBusy); + sqlite3_sleep(50); + return 1; /* Try again... */ +} + +/* +** sqlthread open +** +** Open a database handle and return the string representation of +** the pointer value. +*/ +static int sqlthread_open( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int sqlite3TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p); + + const char *zFilename; + sqlite3 *db; + char zBuf[100]; + extern void Md5_Register(sqlite3*); + + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + + zFilename = Tcl_GetString(objv[2]); + sqlite3_open(zFilename, &db); +#ifdef SQLITE_HAS_CODEC + if( db && objc>=4 ){ + const char *zKey; + int nKey; + int rc; + zKey = Tcl_GetStringFromObj(objv[3], &nKey); + rc = sqlite3_key(db, zKey, nKey); + if( rc!=SQLITE_OK ){ + char *zErrMsg = sqlite3_mprintf("error %d: %s", rc, sqlite3_errmsg(db)); + sqlite3_close(db); + Tcl_AppendResult(interp, zErrMsg, (char*)0); + sqlite3_free(zErrMsg); + return TCL_ERROR; + } + } +#endif + Md5_Register(db); + sqlite3_busy_handler(db, xBusy, 0); + + if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + + return TCL_OK; +} + + +/* +** sqlthread open +** +** Return the current thread-id (Tcl_GetCurrentThread()) cast to +** an integer. +*/ +static int sqlthread_id( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_ThreadId id = Tcl_GetCurrentThread(); + Tcl_SetObjResult(interp, Tcl_NewIntObj(SQLITE_PTR_TO_INT(id))); + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); + return TCL_OK; +} + + +/* +** Dispatch routine for the sub-commands of [sqlthread]. +*/ +static int sqlthread_proc( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct SubCommand { + char *zName; + Tcl_ObjCmdProc *xProc; + int nArg; + char *zUsage; + } aSub[] = { + {"parent", sqlthread_parent, 1, "SCRIPT"}, + {"spawn", sqlthread_spawn, 2, "VARNAME SCRIPT"}, + {"open", sqlthread_open, 1, "DBNAME"}, + {"id", sqlthread_id, 0, ""}, + {0, 0, 0} + }; + struct SubCommand *pSub; + int rc; + int iIndex; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND"); + return TCL_ERROR; + } + + rc = Tcl_GetIndexFromObjStruct( + interp, objv[1], aSub, sizeof(aSub[0]), "sub-command", 0, &iIndex + ); + if( rc!=TCL_OK ) return rc; + pSub = &aSub[iIndex]; + + if( objc<(pSub->nArg+2) ){ + Tcl_WrongNumArgs(interp, 2, objv, pSub->zUsage); + return TCL_ERROR; + } + + return pSub->xProc(clientData, interp, objc, objv); +} + +/* +** The [clock_seconds] command. This is more or less the same as the +** regular tcl [clock seconds], except that it is available in testfixture +** when linked against both Tcl 8.4 and 8.5. Because [clock seconds] is +** implemented as a script in Tcl 8.5, it is not usually available to +** testfixture. +*/ +static int clock_seconds_proc( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Time now; + Tcl_GetTime(&now); + Tcl_SetObjResult(interp, Tcl_NewIntObj(now.sec)); + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); + return TCL_OK; +} + +/************************************************************************* +** This block contains the implementation of the [sqlite3_blocking_step] +** command available to threads created by [sqlthread spawn] commands. It +** is only available on UNIX for now. This is because pthread condition +** variables are used. +** +** The source code for the C functions sqlite3_blocking_step(), +** blocking_step_notify() and the structure UnlockNotification is +** automatically extracted from this file and used as part of the +** documentation for the sqlite3_unlock_notify() API function. This +** should be considered if these functions are to be extended (i.e. to +** support windows) in the future. +*/ +#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) + +/* BEGIN_SQLITE_BLOCKING_STEP */ +/* This example uses the pthreads API */ +#include + +/* +** A pointer to an instance of this structure is passed as the user-context +** pointer when registering for an unlock-notify callback. +*/ +typedef struct UnlockNotification UnlockNotification; +struct UnlockNotification { + int fired; /* True after unlock event has occurred */ + pthread_cond_t cond; /* Condition variable to wait on */ + pthread_mutex_t mutex; /* Mutex to protect structure */ +}; + +/* +** This function is an unlock-notify callback registered with SQLite. +*/ +static void unlock_notify_cb(void **apArg, int nArg){ + int i; + for(i=0; imutex); + p->fired = 1; + pthread_cond_signal(&p->cond); + pthread_mutex_unlock(&p->mutex); + } +} + +/* +** This function assumes that an SQLite API call (either sqlite3_prepare_v2() +** or sqlite3_step()) has just returned SQLITE_LOCKED. The argument is the +** associated database connection. +** +** This function calls sqlite3_unlock_notify() to register for an +** unlock-notify callback, then blocks until that callback is delivered +** and returns SQLITE_OK. The caller should then retry the failed operation. +** +** Or, if sqlite3_unlock_notify() indicates that to block would deadlock +** the system, then this function returns SQLITE_LOCKED immediately. In +** this case the caller should not retry the operation and should roll +** back the current transaction (if any). +*/ +static int wait_for_unlock_notify(sqlite3 *db){ + int rc; + UnlockNotification un; + + /* Initialize the UnlockNotification structure. */ + un.fired = 0; + pthread_mutex_init(&un.mutex, 0); + pthread_cond_init(&un.cond, 0); + + /* Register for an unlock-notify callback. */ + rc = sqlite3_unlock_notify(db, unlock_notify_cb, (void *)&un); + assert( rc==SQLITE_LOCKED || rc==SQLITE_OK ); + + /* The call to sqlite3_unlock_notify() always returns either SQLITE_LOCKED + ** or SQLITE_OK. + ** + ** If SQLITE_LOCKED was returned, then the system is deadlocked. In this + ** case this function needs to return SQLITE_LOCKED to the caller so + ** that the current transaction can be rolled back. Otherwise, block + ** until the unlock-notify callback is invoked, then return SQLITE_OK. + */ + if( rc==SQLITE_OK ){ + pthread_mutex_lock(&un.mutex); + if( !un.fired ){ + pthread_cond_wait(&un.cond, &un.mutex); + } + pthread_mutex_unlock(&un.mutex); + } + + /* Destroy the mutex and condition variables. */ + pthread_cond_destroy(&un.cond); + pthread_mutex_destroy(&un.mutex); + + return rc; +} + +/* +** This function is a wrapper around the SQLite function sqlite3_step(). +** It functions in the same way as step(), except that if a required +** shared-cache lock cannot be obtained, this function may block waiting for +** the lock to become available. In this scenario the normal API step() +** function always returns SQLITE_LOCKED. +** +** If this function returns SQLITE_LOCKED, the caller should rollback +** the current transaction (if any) and try again later. Otherwise, the +** system may become deadlocked. +*/ +int sqlite3_blocking_step(sqlite3_stmt *pStmt){ + int rc; + while( SQLITE_LOCKED==(rc = sqlite3_step(pStmt)) ){ + rc = wait_for_unlock_notify(sqlite3_db_handle(pStmt)); + if( rc!=SQLITE_OK ) break; + sqlite3_reset(pStmt); + } + return rc; +} + +/* +** This function is a wrapper around the SQLite function sqlite3_prepare_v2(). +** It functions in the same way as prepare_v2(), except that if a required +** shared-cache lock cannot be obtained, this function may block waiting for +** the lock to become available. In this scenario the normal API prepare_v2() +** function always returns SQLITE_LOCKED. +** +** If this function returns SQLITE_LOCKED, the caller should rollback +** the current transaction (if any) and try again later. Otherwise, the +** system may become deadlocked. +*/ +int sqlite3_blocking_prepare_v2( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nSql, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pz /* OUT: End of parsed string */ +){ + int rc; + while( SQLITE_LOCKED==(rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, pz)) ){ + rc = wait_for_unlock_notify(db); + if( rc!=SQLITE_OK ) break; + } + return rc; +} +/* END_SQLITE_BLOCKING_STEP */ + +/* +** Usage: sqlite3_blocking_step STMT +** +** Advance the statement to the next row. +*/ +static int blocking_step_proc( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + + pStmt = (sqlite3_stmt*)sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + rc = sqlite3_blocking_step(pStmt); + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), 0); + return TCL_OK; +} + +/* +** Usage: sqlite3_blocking_prepare_v2 DB sql bytes ?tailvar? +** Usage: sqlite3_nonblocking_prepare_v2 DB sql bytes ?tailvar? +*/ +static int blocking_prepare_v2_proc( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zSql; + int bytes; + const char *zTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + int isBlocking = !(clientData==0); + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetString(objv[2]); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + if( isBlocking ){ + rc = sqlite3_blocking_prepare_v2(db, zSql, bytes, &pStmt, &zTail); + }else{ + rc = sqlite3_prepare_v2(db, zSql, bytes, &pStmt, &zTail); + } + + assert(rc==SQLITE_OK || pStmt==0); + if( zTail && objc>=5 ){ + if( bytes>=0 ){ + bytes = bytes - (zTail-zSql); + } + Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0); + } + if( rc!=SQLITE_OK ){ + assert( pStmt==0 ); + sprintf(zBuf, "%s ", (char *)sqlite3ErrName(rc)); + Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0); + return TCL_ERROR; + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +#endif /* SQLITE_OS_UNIX && SQLITE_ENABLE_UNLOCK_NOTIFY */ +/* +** End of implementation of [sqlite3_blocking_step]. +************************************************************************/ + +/* +** Register commands with the TCL interpreter. +*/ +int SqlitetestThread_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "sqlthread", sqlthread_proc, 0, 0); + Tcl_CreateObjCommand(interp, "clock_seconds", clock_seconds_proc, 0, 0); +#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) + Tcl_CreateObjCommand(interp, "sqlite3_blocking_step", blocking_step_proc,0,0); + Tcl_CreateObjCommand(interp, + "sqlite3_blocking_prepare_v2", blocking_prepare_v2_proc, (void *)1, 0); + Tcl_CreateObjCommand(interp, + "sqlite3_nonblocking_prepare_v2", blocking_prepare_v2_proc, 0, 0); +#endif + return TCL_OK; +} +#else +int SqlitetestThread_Init(Tcl_Interp *interp){ + return TCL_OK; +} +#endif diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_vfs.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_vfs.c new file mode 100644 index 0000000000000000000000000000000000000000..613b0fce77482b74116d23e9f59d0899ae56e078 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_vfs.c @@ -0,0 +1,1510 @@ +/* +** 2010 May 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains the implementation of the Tcl [testvfs] command, +** used to create SQLite VFS implementations with various properties and +** instrumentation to support testing SQLite. +** +** testvfs VFSNAME ?OPTIONS? +** +** Available options are: +** +** -noshm BOOLEAN (True to omit shm methods. Default false) +** -default BOOLEAN (True to make the vfs default. Default false) +** -szosfile INTEGER (Value for sqlite3_vfs.szOsFile) +** -mxpathname INTEGER (Value for sqlite3_vfs.mxPathname) +** -iversion INTEGER (Value for sqlite3_vfs.iVersion) +*/ +#if SQLITE_TEST /* This file is used for testing only */ + +#include "sqlite3.h" +#include "sqliteInt.h" +#include + +typedef struct Testvfs Testvfs; +typedef struct TestvfsShm TestvfsShm; +typedef struct TestvfsBuffer TestvfsBuffer; +typedef struct TestvfsFile TestvfsFile; +typedef struct TestvfsFd TestvfsFd; + +/* +** An open file handle. +*/ +struct TestvfsFile { + sqlite3_file base; /* Base class. Must be first */ + TestvfsFd *pFd; /* File data */ +}; +#define tvfsGetFd(pFile) (((TestvfsFile *)pFile)->pFd) + +struct TestvfsFd { + sqlite3_vfs *pVfs; /* The VFS */ + const char *zFilename; /* Filename as passed to xOpen() */ + sqlite3_file *pReal; /* The real, underlying file descriptor */ + Tcl_Obj *pShmId; /* Shared memory id for Tcl callbacks */ + + TestvfsBuffer *pShm; /* Shared memory buffer */ + u32 excllock; /* Mask of exclusive locks */ + u32 sharedlock; /* Mask of shared locks */ + TestvfsFd *pNext; /* Next handle opened on the same file */ +}; + + +#define FAULT_INJECT_NONE 0 +#define FAULT_INJECT_TRANSIENT 1 +#define FAULT_INJECT_PERSISTENT 2 + +typedef struct TestFaultInject TestFaultInject; +struct TestFaultInject { + int iCnt; /* Remaining calls before fault injection */ + int eFault; /* A FAULT_INJECT_* value */ + int nFail; /* Number of faults injected */ +}; + +/* +** An instance of this structure is allocated for each VFS created. The +** sqlite3_vfs.pAppData field of the VFS structure registered with SQLite +** is set to point to it. +*/ +struct Testvfs { + char *zName; /* Name of this VFS */ + sqlite3_vfs *pParent; /* The VFS to use for file IO */ + sqlite3_vfs *pVfs; /* The testvfs registered with SQLite */ + Tcl_Interp *interp; /* Interpreter to run script in */ + Tcl_Obj *pScript; /* Script to execute */ + TestvfsBuffer *pBuffer; /* List of shared buffers */ + int isNoshm; + int isFullshm; + + int mask; /* Mask controlling [script] and [ioerr] */ + + TestFaultInject ioerr_err; + TestFaultInject full_err; + TestFaultInject cantopen_err; + +#if 0 + int iIoerrCnt; + int ioerr; + int nIoerrFail; + int iFullCnt; + int fullerr; + int nFullFail; +#endif + + int iDevchar; + int iSectorsize; +}; + +/* +** The Testvfs.mask variable is set to a combination of the following. +** If a bit is clear in Testvfs.mask, then calls made by SQLite to the +** corresponding VFS method is ignored for purposes of: +** +** + Simulating IO errors, and +** + Invoking the Tcl callback script. +*/ +#define TESTVFS_SHMOPEN_MASK 0x00000001 +#define TESTVFS_SHMLOCK_MASK 0x00000010 +#define TESTVFS_SHMMAP_MASK 0x00000020 +#define TESTVFS_SHMBARRIER_MASK 0x00000040 +#define TESTVFS_SHMCLOSE_MASK 0x00000080 + +#define TESTVFS_OPEN_MASK 0x00000100 +#define TESTVFS_SYNC_MASK 0x00000200 +#define TESTVFS_DELETE_MASK 0x00000400 +#define TESTVFS_CLOSE_MASK 0x00000800 +#define TESTVFS_WRITE_MASK 0x00001000 +#define TESTVFS_TRUNCATE_MASK 0x00002000 +#define TESTVFS_ACCESS_MASK 0x00004000 +#define TESTVFS_FULLPATHNAME_MASK 0x00008000 +#define TESTVFS_READ_MASK 0x00010000 +#define TESTVFS_UNLOCK_MASK 0x00020000 + +#define TESTVFS_ALL_MASK 0x0003FFFF + + +#define TESTVFS_MAX_PAGES 1024 + +/* +** A shared-memory buffer. There is one of these objects for each shared +** memory region opened by clients. If two clients open the same file, +** there are two TestvfsFile structures but only one TestvfsBuffer structure. +*/ +struct TestvfsBuffer { + char *zFile; /* Associated file name */ + int pgsz; /* Page size */ + u8 *aPage[TESTVFS_MAX_PAGES]; /* Array of ckalloc'd pages */ + TestvfsFd *pFile; /* List of open handles */ + TestvfsBuffer *pNext; /* Next in linked list of all buffers */ +}; + + +#define PARENTVFS(x) (((Testvfs *)((x)->pAppData))->pParent) + +#define TESTVFS_MAX_ARGS 12 + + +/* +** Method declarations for TestvfsFile. +*/ +static int tvfsClose(sqlite3_file*); +static int tvfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int tvfsWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); +static int tvfsTruncate(sqlite3_file*, sqlite3_int64 size); +static int tvfsSync(sqlite3_file*, int flags); +static int tvfsFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int tvfsLock(sqlite3_file*, int); +static int tvfsUnlock(sqlite3_file*, int); +static int tvfsCheckReservedLock(sqlite3_file*, int *); +static int tvfsFileControl(sqlite3_file*, int op, void *pArg); +static int tvfsSectorSize(sqlite3_file*); +static int tvfsDeviceCharacteristics(sqlite3_file*); + +/* +** Method declarations for tvfs_vfs. +*/ +static int tvfsOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int tvfsDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int tvfsAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int tvfsFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +static void *tvfsDlOpen(sqlite3_vfs*, const char *zFilename); +static void tvfsDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*tvfsDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void); +static void tvfsDlClose(sqlite3_vfs*, void*); +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +static int tvfsRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int tvfsSleep(sqlite3_vfs*, int microseconds); +static int tvfsCurrentTime(sqlite3_vfs*, double*); + +static int tvfsShmOpen(sqlite3_file*); +static int tvfsShmLock(sqlite3_file*, int , int, int); +static int tvfsShmMap(sqlite3_file*,int,int,int, void volatile **); +static void tvfsShmBarrier(sqlite3_file*); +static int tvfsShmUnmap(sqlite3_file*, int); + +static int tvfsFetch(sqlite3_file*, sqlite3_int64, int, void**); +static int tvfsUnfetch(sqlite3_file*, sqlite3_int64, void*); + +static sqlite3_io_methods tvfs_io_methods = { + 3, /* iVersion */ + tvfsClose, /* xClose */ + tvfsRead, /* xRead */ + tvfsWrite, /* xWrite */ + tvfsTruncate, /* xTruncate */ + tvfsSync, /* xSync */ + tvfsFileSize, /* xFileSize */ + tvfsLock, /* xLock */ + tvfsUnlock, /* xUnlock */ + tvfsCheckReservedLock, /* xCheckReservedLock */ + tvfsFileControl, /* xFileControl */ + tvfsSectorSize, /* xSectorSize */ + tvfsDeviceCharacteristics, /* xDeviceCharacteristics */ + tvfsShmMap, /* xShmMap */ + tvfsShmLock, /* xShmLock */ + tvfsShmBarrier, /* xShmBarrier */ + tvfsShmUnmap, /* xShmUnmap */ + tvfsFetch, + tvfsUnfetch +}; + +static int tvfsResultCode(Testvfs *p, int *pRc){ + struct errcode { + int eCode; + const char *zCode; + } aCode[] = { + { SQLITE_OK, "SQLITE_OK" }, + { SQLITE_ERROR, "SQLITE_ERROR" }, + { SQLITE_IOERR, "SQLITE_IOERR" }, + { SQLITE_LOCKED, "SQLITE_LOCKED" }, + { SQLITE_BUSY, "SQLITE_BUSY" }, + }; + + const char *z; + int i; + + z = Tcl_GetStringResult(p->interp); + for(i=0; ieFault ){ + p->iCnt--; + if( p->iCnt==0 || (p->iCnt<0 && p->eFault==FAULT_INJECT_PERSISTENT ) ){ + ret = 1; + p->nFail++; + } + } + return ret; +} + + +static int tvfsInjectIoerr(Testvfs *p){ + return tvfsInjectFault(&p->ioerr_err); +} + +static int tvfsInjectFullerr(Testvfs *p){ + return tvfsInjectFault(&p->full_err); +} +static int tvfsInjectCantopenerr(Testvfs *p){ + return tvfsInjectFault(&p->cantopen_err); +} + + +static void tvfsExecTcl( + Testvfs *p, + const char *zMethod, + Tcl_Obj *arg1, + Tcl_Obj *arg2, + Tcl_Obj *arg3, + Tcl_Obj *arg4 +){ + int rc; /* Return code from Tcl_EvalObj() */ + Tcl_Obj *pEval; + assert( p->pScript ); + + assert( zMethod ); + assert( p ); + assert( arg2==0 || arg1!=0 ); + assert( arg3==0 || arg2!=0 ); + + pEval = Tcl_DuplicateObj(p->pScript); + Tcl_IncrRefCount(p->pScript); + Tcl_ListObjAppendElement(p->interp, pEval, Tcl_NewStringObj(zMethod, -1)); + if( arg1 ) Tcl_ListObjAppendElement(p->interp, pEval, arg1); + if( arg2 ) Tcl_ListObjAppendElement(p->interp, pEval, arg2); + if( arg3 ) Tcl_ListObjAppendElement(p->interp, pEval, arg3); + if( arg4 ) Tcl_ListObjAppendElement(p->interp, pEval, arg4); + + rc = Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL); + if( rc!=TCL_OK ){ + Tcl_BackgroundError(p->interp); + Tcl_ResetResult(p->interp); + } +} + + +/* +** Close an tvfs-file. +*/ +static int tvfsClose(sqlite3_file *pFile){ + int rc; + TestvfsFile *pTestfile = (TestvfsFile *)pFile; + TestvfsFd *pFd = pTestfile->pFd; + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_CLOSE_MASK ){ + tvfsExecTcl(p, "xClose", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, 0, 0 + ); + } + + if( pFd->pShmId ){ + Tcl_DecrRefCount(pFd->pShmId); + pFd->pShmId = 0; + } + if( pFile->pMethods ){ + ckfree((char *)pFile->pMethods); + } + rc = sqlite3OsClose(pFd->pReal); + ckfree((char *)pFd); + pTestfile->pFd = 0; + return rc; +} + +/* +** Read data from an tvfs-file. +*/ +static int tvfsRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + if( p->pScript && p->mask&TESTVFS_READ_MASK ){ + tvfsExecTcl(p, "xRead", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, 0, 0 + ); + tvfsResultCode(p, &rc); + } + if( rc==SQLITE_OK && p->mask&TESTVFS_READ_MASK && tvfsInjectIoerr(p) ){ + rc = SQLITE_IOERR; + } + if( rc==SQLITE_OK ){ + rc = sqlite3OsRead(pFd->pReal, zBuf, iAmt, iOfst); + } + return rc; +} + +/* +** Write data to an tvfs-file. +*/ +static int tvfsWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_WRITE_MASK ){ + tvfsExecTcl(p, "xWrite", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, + Tcl_NewWideIntObj(iOfst), Tcl_NewIntObj(iAmt) + ); + tvfsResultCode(p, &rc); + } + + if( rc==SQLITE_OK && tvfsInjectFullerr(p) ){ + rc = SQLITE_FULL; + } + if( rc==SQLITE_OK && p->mask&TESTVFS_WRITE_MASK && tvfsInjectIoerr(p) ){ + rc = SQLITE_IOERR; + } + + if( rc==SQLITE_OK ){ + rc = sqlite3OsWrite(pFd->pReal, zBuf, iAmt, iOfst); + } + return rc; +} + +/* +** Truncate an tvfs-file. +*/ +static int tvfsTruncate(sqlite3_file *pFile, sqlite_int64 size){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_TRUNCATE_MASK ){ + tvfsExecTcl(p, "xTruncate", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, 0, 0 + ); + tvfsResultCode(p, &rc); + } + + if( rc==SQLITE_OK ){ + rc = sqlite3OsTruncate(pFd->pReal, size); + } + return rc; +} + +/* +** Sync an tvfs-file. +*/ +static int tvfsSync(sqlite3_file *pFile, int flags){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_SYNC_MASK ){ + char *zFlags; + + switch( flags ){ + case SQLITE_SYNC_NORMAL: + zFlags = "normal"; + break; + case SQLITE_SYNC_FULL: + zFlags = "full"; + break; + case SQLITE_SYNC_NORMAL|SQLITE_SYNC_DATAONLY: + zFlags = "normal|dataonly"; + break; + case SQLITE_SYNC_FULL|SQLITE_SYNC_DATAONLY: + zFlags = "full|dataonly"; + break; + default: + assert(0); + } + + tvfsExecTcl(p, "xSync", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, + Tcl_NewStringObj(zFlags, -1), 0 + ); + tvfsResultCode(p, &rc); + } + + if( rc==SQLITE_OK && tvfsInjectFullerr(p) ) rc = SQLITE_FULL; + + if( rc==SQLITE_OK ){ + rc = sqlite3OsSync(pFd->pReal, flags); + } + + return rc; +} + +/* +** Return the current file-size of an tvfs-file. +*/ +static int tvfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + TestvfsFd *p = tvfsGetFd(pFile); + return sqlite3OsFileSize(p->pReal, pSize); +} + +/* +** Lock an tvfs-file. +*/ +static int tvfsLock(sqlite3_file *pFile, int eLock){ + TestvfsFd *p = tvfsGetFd(pFile); + return sqlite3OsLock(p->pReal, eLock); +} + +/* +** Unlock an tvfs-file. +*/ +static int tvfsUnlock(sqlite3_file *pFile, int eLock){ + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + if( p->mask&TESTVFS_WRITE_MASK && tvfsInjectIoerr(p) ){ + return SQLITE_IOERR_UNLOCK; + } + return sqlite3OsUnlock(pFd->pReal, eLock); +} + +/* +** Check if another file-handle holds a RESERVED lock on an tvfs-file. +*/ +static int tvfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + TestvfsFd *p = tvfsGetFd(pFile); + return sqlite3OsCheckReservedLock(p->pReal, pResOut); +} + +/* +** File control method. For custom operations on an tvfs-file. +*/ +static int tvfsFileControl(sqlite3_file *pFile, int op, void *pArg){ + TestvfsFd *p = tvfsGetFd(pFile); + if( op==SQLITE_FCNTL_PRAGMA ){ + char **argv = (char**)pArg; + if( sqlite3_stricmp(argv[1],"error")==0 ){ + int rc = SQLITE_ERROR; + if( argv[2] ){ + const char *z = argv[2]; + int x = atoi(z); + if( x ){ + rc = x; + while( sqlite3Isdigit(z[0]) ){ z++; } + while( sqlite3Isspace(z[0]) ){ z++; } + } + if( z[0] ) argv[0] = sqlite3_mprintf("%s", z); + } + return rc; + } + if( sqlite3_stricmp(argv[1], "filename")==0 ){ + argv[0] = sqlite3_mprintf("%s", p->zFilename); + return SQLITE_OK; + } + } + return sqlite3OsFileControl(p->pReal, op, pArg); +} + +/* +** Return the sector-size in bytes for an tvfs-file. +*/ +static int tvfsSectorSize(sqlite3_file *pFile){ + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + if( p->iSectorsize>=0 ){ + return p->iSectorsize; + } + return sqlite3OsSectorSize(pFd->pReal); +} + +/* +** Return the device characteristic flags supported by an tvfs-file. +*/ +static int tvfsDeviceCharacteristics(sqlite3_file *pFile){ + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + if( p->iDevchar>=0 ){ + return p->iDevchar; + } + return sqlite3OsDeviceCharacteristics(pFd->pReal); +} + +/* +** Open an tvfs file handle. +*/ +static int tvfsOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + TestvfsFile *pTestfile = (TestvfsFile *)pFile; + TestvfsFd *pFd; + Tcl_Obj *pId = 0; + Testvfs *p = (Testvfs *)pVfs->pAppData; + + pFd = (TestvfsFd *)ckalloc(sizeof(TestvfsFd) + PARENTVFS(pVfs)->szOsFile); + memset(pFd, 0, sizeof(TestvfsFd) + PARENTVFS(pVfs)->szOsFile); + pFd->pShm = 0; + pFd->pShmId = 0; + pFd->zFilename = zName; + pFd->pVfs = pVfs; + pFd->pReal = (sqlite3_file *)&pFd[1]; + memset(pTestfile, 0, sizeof(TestvfsFile)); + pTestfile->pFd = pFd; + + /* Evaluate the Tcl script: + ** + ** SCRIPT xOpen FILENAME KEY-VALUE-ARGS + ** + ** If the script returns an SQLite error code other than SQLITE_OK, an + ** error is returned to the caller. If it returns SQLITE_OK, the new + ** connection is named "anon". Otherwise, the value returned by the + ** script is used as the connection name. + */ + Tcl_ResetResult(p->interp); + if( p->pScript && p->mask&TESTVFS_OPEN_MASK ){ + Tcl_Obj *pArg = Tcl_NewObj(); + Tcl_IncrRefCount(pArg); + if( flags&SQLITE_OPEN_MAIN_DB ){ + const char *z = &zName[strlen(zName)+1]; + while( *z ){ + Tcl_ListObjAppendElement(0, pArg, Tcl_NewStringObj(z, -1)); + z += strlen(z) + 1; + Tcl_ListObjAppendElement(0, pArg, Tcl_NewStringObj(z, -1)); + z += strlen(z) + 1; + } + } + tvfsExecTcl(p, "xOpen", Tcl_NewStringObj(pFd->zFilename, -1), pArg, 0, 0); + Tcl_DecrRefCount(pArg); + if( tvfsResultCode(p, &rc) ){ + if( rc!=SQLITE_OK ) return rc; + }else{ + pId = Tcl_GetObjResult(p->interp); + } + } + + if( (p->mask&TESTVFS_OPEN_MASK) && tvfsInjectIoerr(p) ) return SQLITE_IOERR; + if( tvfsInjectCantopenerr(p) ) return SQLITE_CANTOPEN; + if( tvfsInjectFullerr(p) ) return SQLITE_FULL; + + if( !pId ){ + pId = Tcl_NewStringObj("anon", -1); + } + Tcl_IncrRefCount(pId); + pFd->pShmId = pId; + Tcl_ResetResult(p->interp); + + rc = sqlite3OsOpen(PARENTVFS(pVfs), zName, pFd->pReal, flags, pOutFlags); + if( pFd->pReal->pMethods ){ + sqlite3_io_methods *pMethods; + int nByte; + + if( pVfs->iVersion>1 ){ + nByte = sizeof(sqlite3_io_methods); + }else{ + nByte = offsetof(sqlite3_io_methods, xShmMap); + } + + pMethods = (sqlite3_io_methods *)ckalloc(nByte); + memcpy(pMethods, &tvfs_io_methods, nByte); + pMethods->iVersion = pFd->pReal->pMethods->iVersion; + if( pMethods->iVersion>pVfs->iVersion ){ + pMethods->iVersion = pVfs->iVersion; + } + if( pVfs->iVersion>1 && ((Testvfs *)pVfs->pAppData)->isNoshm ){ + pMethods->xShmUnmap = 0; + pMethods->xShmLock = 0; + pMethods->xShmBarrier = 0; + pMethods->xShmMap = 0; + } + pFile->pMethods = pMethods; + } + + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int tvfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc = SQLITE_OK; + Testvfs *p = (Testvfs *)pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_DELETE_MASK ){ + tvfsExecTcl(p, "xDelete", + Tcl_NewStringObj(zPath, -1), Tcl_NewIntObj(dirSync), 0, 0 + ); + tvfsResultCode(p, &rc); + } + if( rc==SQLITE_OK ){ + rc = sqlite3OsDelete(PARENTVFS(pVfs), zPath, dirSync); + } + return rc; +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int tvfsAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + Testvfs *p = (Testvfs *)pVfs->pAppData; + if( p->pScript && p->mask&TESTVFS_ACCESS_MASK ){ + int rc; + char *zArg = 0; + if( flags==SQLITE_ACCESS_EXISTS ) zArg = "SQLITE_ACCESS_EXISTS"; + if( flags==SQLITE_ACCESS_READWRITE ) zArg = "SQLITE_ACCESS_READWRITE"; + if( flags==SQLITE_ACCESS_READ ) zArg = "SQLITE_ACCESS_READ"; + tvfsExecTcl(p, "xAccess", + Tcl_NewStringObj(zPath, -1), Tcl_NewStringObj(zArg, -1), 0, 0 + ); + if( tvfsResultCode(p, &rc) ){ + if( rc!=SQLITE_OK ) return rc; + }else{ + Tcl_Interp *interp = p->interp; + if( TCL_OK==Tcl_GetBooleanFromObj(0, Tcl_GetObjResult(interp), pResOut) ){ + return SQLITE_OK; + } + } + } + return sqlite3OsAccess(PARENTVFS(pVfs), zPath, flags, pResOut); +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (DEVSYM_MAX_PATHNAME+1) bytes. +*/ +static int tvfsFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + Testvfs *p = (Testvfs *)pVfs->pAppData; + if( p->pScript && p->mask&TESTVFS_FULLPATHNAME_MASK ){ + int rc; + tvfsExecTcl(p, "xFullPathname", Tcl_NewStringObj(zPath, -1), 0, 0, 0); + if( tvfsResultCode(p, &rc) ){ + if( rc!=SQLITE_OK ) return rc; + } + } + return sqlite3OsFullPathname(PARENTVFS(pVfs), zPath, nOut, zOut); +} + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *tvfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return sqlite3OsDlOpen(PARENTVFS(pVfs), zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void tvfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + sqlite3OsDlError(PARENTVFS(pVfs), nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*tvfsDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return sqlite3OsDlSym(PARENTVFS(pVfs), p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void tvfsDlClose(sqlite3_vfs *pVfs, void *pHandle){ + sqlite3OsDlClose(PARENTVFS(pVfs), pHandle); +} +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int tvfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return sqlite3OsRandomness(PARENTVFS(pVfs), nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int tvfsSleep(sqlite3_vfs *pVfs, int nMicro){ + return sqlite3OsSleep(PARENTVFS(pVfs), nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int tvfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + return PARENTVFS(pVfs)->xCurrentTime(PARENTVFS(pVfs), pTimeOut); +} + +static int tvfsShmOpen(sqlite3_file *pFile){ + Testvfs *p; + int rc = SQLITE_OK; /* Return code */ + TestvfsBuffer *pBuffer; /* Buffer to open connection to */ + TestvfsFd *pFd; /* The testvfs file structure */ + + pFd = tvfsGetFd(pFile); + p = (Testvfs *)pFd->pVfs->pAppData; + assert( 0==p->isFullshm ); + assert( pFd->pShmId && pFd->pShm==0 && pFd->pNext==0 ); + + /* Evaluate the Tcl script: + ** + ** SCRIPT xShmOpen FILENAME + */ + Tcl_ResetResult(p->interp); + if( p->pScript && p->mask&TESTVFS_SHMOPEN_MASK ){ + tvfsExecTcl(p, "xShmOpen", Tcl_NewStringObj(pFd->zFilename, -1), 0, 0, 0); + if( tvfsResultCode(p, &rc) ){ + if( rc!=SQLITE_OK ) return rc; + } + } + + assert( rc==SQLITE_OK ); + if( p->mask&TESTVFS_SHMOPEN_MASK && tvfsInjectIoerr(p) ){ + return SQLITE_IOERR; + } + + /* Search for a TestvfsBuffer. Create a new one if required. */ + for(pBuffer=p->pBuffer; pBuffer; pBuffer=pBuffer->pNext){ + if( 0==strcmp(pFd->zFilename, pBuffer->zFile) ) break; + } + if( !pBuffer ){ + int nByte = sizeof(TestvfsBuffer) + (int)strlen(pFd->zFilename) + 1; + pBuffer = (TestvfsBuffer *)ckalloc(nByte); + memset(pBuffer, 0, nByte); + pBuffer->zFile = (char *)&pBuffer[1]; + strcpy(pBuffer->zFile, pFd->zFilename); + pBuffer->pNext = p->pBuffer; + p->pBuffer = pBuffer; + } + + /* Connect the TestvfsBuffer to the new TestvfsShm handle and return. */ + pFd->pNext = pBuffer->pFile; + pBuffer->pFile = pFd; + pFd->pShm = pBuffer; + return SQLITE_OK; +} + +static void tvfsAllocPage(TestvfsBuffer *p, int iPage, int pgsz){ + assert( iPageaPage[iPage]==0 ){ + p->aPage[iPage] = (u8 *)ckalloc(pgsz); + memset(p->aPage[iPage], 0, pgsz); + p->pgsz = pgsz; + } +} + +static int tvfsShmMap( + sqlite3_file *pFile, /* Handle open on database file */ + int iPage, /* Page to retrieve */ + int pgsz, /* Size of pages */ + int isWrite, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData); + + if( p->isFullshm ){ + return sqlite3OsShmMap(pFd->pReal, iPage, pgsz, isWrite, pp); + } + + if( 0==pFd->pShm ){ + rc = tvfsShmOpen(pFile); + if( rc!=SQLITE_OK ){ + return rc; + } + } + + if( p->pScript && p->mask&TESTVFS_SHMMAP_MASK ){ + Tcl_Obj *pArg = Tcl_NewObj(); + Tcl_IncrRefCount(pArg); + Tcl_ListObjAppendElement(p->interp, pArg, Tcl_NewIntObj(iPage)); + Tcl_ListObjAppendElement(p->interp, pArg, Tcl_NewIntObj(pgsz)); + Tcl_ListObjAppendElement(p->interp, pArg, Tcl_NewIntObj(isWrite)); + tvfsExecTcl(p, "xShmMap", + Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, pArg, 0 + ); + tvfsResultCode(p, &rc); + Tcl_DecrRefCount(pArg); + } + if( rc==SQLITE_OK && p->mask&TESTVFS_SHMMAP_MASK && tvfsInjectIoerr(p) ){ + rc = SQLITE_IOERR; + } + + if( rc==SQLITE_OK && isWrite && !pFd->pShm->aPage[iPage] ){ + tvfsAllocPage(pFd->pShm, iPage, pgsz); + } + *pp = (void volatile *)pFd->pShm->aPage[iPage]; + + return rc; +} + + +static int tvfsShmLock( + sqlite3_file *pFile, + int ofst, + int n, + int flags +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData); + int nLock; + char zLock[80]; + + if( p->isFullshm ){ + return sqlite3OsShmLock(pFd->pReal, ofst, n, flags); + } + + if( p->pScript && p->mask&TESTVFS_SHMLOCK_MASK ){ + sqlite3_snprintf(sizeof(zLock), zLock, "%d %d", ofst, n); + nLock = (int)strlen(zLock); + if( flags & SQLITE_SHM_LOCK ){ + strcpy(&zLock[nLock], " lock"); + }else{ + strcpy(&zLock[nLock], " unlock"); + } + nLock += (int)strlen(&zLock[nLock]); + if( flags & SQLITE_SHM_SHARED ){ + strcpy(&zLock[nLock], " shared"); + }else{ + strcpy(&zLock[nLock], " exclusive"); + } + tvfsExecTcl(p, "xShmLock", + Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, + Tcl_NewStringObj(zLock, -1), 0 + ); + tvfsResultCode(p, &rc); + } + + if( rc==SQLITE_OK && p->mask&TESTVFS_SHMLOCK_MASK && tvfsInjectIoerr(p) ){ + rc = SQLITE_IOERR; + } + + if( rc==SQLITE_OK ){ + int isLock = (flags & SQLITE_SHM_LOCK); + int isExcl = (flags & SQLITE_SHM_EXCLUSIVE); + u32 mask = (((1<pShm->pFile; p2; p2=p2->pNext){ + if( p2==pFd ) continue; + if( (p2->excllock&mask) || (isExcl && p2->sharedlock&mask) ){ + rc = SQLITE_BUSY; + break; + } + } + if( rc==SQLITE_OK ){ + if( isExcl ) pFd->excllock |= mask; + if( !isExcl ) pFd->sharedlock |= mask; + } + }else{ + if( isExcl ) pFd->excllock &= (~mask); + if( !isExcl ) pFd->sharedlock &= (~mask); + } + } + + return rc; +} + +static void tvfsShmBarrier(sqlite3_file *pFile){ + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData); + + if( p->isFullshm ){ + sqlite3OsShmBarrier(pFd->pReal); + return; + } + + if( p->pScript && p->mask&TESTVFS_SHMBARRIER_MASK ){ + tvfsExecTcl(p, "xShmBarrier", + Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, 0, 0 + ); + } +} + +static int tvfsShmUnmap( + sqlite3_file *pFile, + int deleteFlag +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData); + TestvfsBuffer *pBuffer = pFd->pShm; + TestvfsFd **ppFd; + + if( p->isFullshm ){ + return sqlite3OsShmUnmap(pFd->pReal, deleteFlag); + } + + if( !pBuffer ) return SQLITE_OK; + assert( pFd->pShmId && pFd->pShm ); + + if( p->pScript && p->mask&TESTVFS_SHMCLOSE_MASK ){ + tvfsExecTcl(p, "xShmUnmap", + Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, 0, 0 + ); + tvfsResultCode(p, &rc); + } + + for(ppFd=&pBuffer->pFile; *ppFd!=pFd; ppFd=&((*ppFd)->pNext)); + assert( (*ppFd)==pFd ); + *ppFd = pFd->pNext; + pFd->pNext = 0; + + if( pBuffer->pFile==0 ){ + int i; + TestvfsBuffer **pp; + for(pp=&p->pBuffer; *pp!=pBuffer; pp=&((*pp)->pNext)); + *pp = (*pp)->pNext; + for(i=0; pBuffer->aPage[i]; i++){ + ckfree((char *)pBuffer->aPage[i]); + } + ckfree((char *)pBuffer); + } + pFd->pShm = 0; + + return rc; +} + +static int tvfsFetch( + sqlite3_file *pFile, + sqlite3_int64 iOfst, + int iAmt, + void **pp +){ + TestvfsFd *pFd = tvfsGetFd(pFile); + return sqlite3OsFetch(pFd->pReal, iOfst, iAmt, pp); +} + +static int tvfsUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *p){ + TestvfsFd *pFd = tvfsGetFd(pFile); + return sqlite3OsUnfetch(pFd->pReal, iOfst, p); +} + +static int testvfs_obj_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Testvfs *p = (Testvfs *)cd; + + enum DB_enum { + CMD_SHM, CMD_DELETE, CMD_FILTER, CMD_IOERR, CMD_SCRIPT, + CMD_DEVCHAR, CMD_SECTORSIZE, CMD_FULLERR, CMD_CANTOPENERR + }; + struct TestvfsSubcmd { + char *zName; + enum DB_enum eCmd; + } aSubcmd[] = { + { "shm", CMD_SHM }, + { "delete", CMD_DELETE }, + { "filter", CMD_FILTER }, + { "ioerr", CMD_IOERR }, + { "fullerr", CMD_FULLERR }, + { "cantopenerr", CMD_CANTOPENERR }, + { "script", CMD_SCRIPT }, + { "devchar", CMD_DEVCHAR }, + { "sectorsize", CMD_SECTORSIZE }, + { 0, 0 } + }; + int i; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ..."); + return TCL_ERROR; + } + if( Tcl_GetIndexFromObjStruct( + interp, objv[1], aSubcmd, sizeof(aSubcmd[0]), "subcommand", 0, &i) + ){ + return TCL_ERROR; + } + Tcl_ResetResult(interp); + + switch( aSubcmd[i].eCmd ){ + case CMD_SHM: { + Tcl_Obj *pObj; + int i, rc; + TestvfsBuffer *pBuffer; + char *zName; + if( objc!=3 && objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "FILE ?VALUE?"); + return TCL_ERROR; + } + zName = ckalloc(p->pParent->mxPathname); + rc = p->pParent->xFullPathname( + p->pParent, Tcl_GetString(objv[2]), + p->pParent->mxPathname, zName + ); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "failed to get full path: ", + Tcl_GetString(objv[2]), 0); + ckfree(zName); + return TCL_ERROR; + } + for(pBuffer=p->pBuffer; pBuffer; pBuffer=pBuffer->pNext){ + if( 0==strcmp(pBuffer->zFile, zName) ) break; + } + ckfree(zName); + if( !pBuffer ){ + Tcl_AppendResult(interp, "no such file: ", Tcl_GetString(objv[2]), 0); + return TCL_ERROR; + } + if( objc==4 ){ + int n; + u8 *a = Tcl_GetByteArrayFromObj(objv[3], &n); + int pgsz = pBuffer->pgsz; + if( pgsz==0 ) pgsz = 65536; + for(i=0; i*pgszaPage[i], &a[i*pgsz], nByte); + } + } + + pObj = Tcl_NewObj(); + for(i=0; pBuffer->aPage[i]; i++){ + int pgsz = pBuffer->pgsz; + if( pgsz==0 ) pgsz = 65536; + Tcl_AppendObjToObj(pObj, Tcl_NewByteArrayObj(pBuffer->aPage[i], pgsz)); + } + Tcl_SetObjResult(interp, pObj); + break; + } + + case CMD_FILTER: { + static struct VfsMethod { + char *zName; + int mask; + } vfsmethod [] = { + { "xShmOpen", TESTVFS_SHMOPEN_MASK }, + { "xShmLock", TESTVFS_SHMLOCK_MASK }, + { "xShmBarrier", TESTVFS_SHMBARRIER_MASK }, + { "xShmUnmap", TESTVFS_SHMCLOSE_MASK }, + { "xShmMap", TESTVFS_SHMMAP_MASK }, + { "xSync", TESTVFS_SYNC_MASK }, + { "xDelete", TESTVFS_DELETE_MASK }, + { "xWrite", TESTVFS_WRITE_MASK }, + { "xRead", TESTVFS_READ_MASK }, + { "xTruncate", TESTVFS_TRUNCATE_MASK }, + { "xOpen", TESTVFS_OPEN_MASK }, + { "xClose", TESTVFS_CLOSE_MASK }, + { "xAccess", TESTVFS_ACCESS_MASK }, + { "xFullPathname", TESTVFS_FULLPATHNAME_MASK }, + { "xUnlock", TESTVFS_UNLOCK_MASK }, + }; + Tcl_Obj **apElem = 0; + int nElem = 0; + int i; + int mask = 0; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "LIST"); + return TCL_ERROR; + } + if( Tcl_ListObjGetElements(interp, objv[2], &nElem, &apElem) ){ + return TCL_ERROR; + } + Tcl_ResetResult(interp); + for(i=0; imask = mask; + break; + } + + case CMD_SCRIPT: { + if( objc==3 ){ + int nByte; + if( p->pScript ){ + Tcl_DecrRefCount(p->pScript); + p->pScript = 0; + } + Tcl_GetStringFromObj(objv[2], &nByte); + if( nByte>0 ){ + p->pScript = Tcl_DuplicateObj(objv[2]); + Tcl_IncrRefCount(p->pScript); + } + }else if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); + return TCL_ERROR; + } + + Tcl_ResetResult(interp); + if( p->pScript ) Tcl_SetObjResult(interp, p->pScript); + + break; + } + + /* + ** TESTVFS ioerr ?IFAIL PERSIST? + ** + ** Where IFAIL is an integer and PERSIST is boolean. + */ + case CMD_CANTOPENERR: + case CMD_IOERR: + case CMD_FULLERR: { + TestFaultInject *pTest; + int iRet; + + switch( aSubcmd[i].eCmd ){ + case CMD_IOERR: pTest = &p->ioerr_err; break; + case CMD_FULLERR: pTest = &p->full_err; break; + case CMD_CANTOPENERR: pTest = &p->cantopen_err; break; + default: assert(0); + } + iRet = pTest->nFail; + pTest->nFail = 0; + pTest->eFault = 0; + pTest->iCnt = 0; + + if( objc==4 ){ + int iCnt, iPersist; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iCnt) + || TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &iPersist) + ){ + return TCL_ERROR; + } + pTest->eFault = iPersist?FAULT_INJECT_PERSISTENT:FAULT_INJECT_TRANSIENT; + pTest->iCnt = iCnt; + }else if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CNT PERSIST?"); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(iRet)); + break; + } + + case CMD_DELETE: { + Tcl_DeleteCommand(interp, Tcl_GetString(objv[0])); + break; + } + + case CMD_DEVCHAR: { + struct DeviceFlag { + char *zName; + int iValue; + } aFlag[] = { + { "default", -1 }, + { "atomic", SQLITE_IOCAP_ATOMIC }, + { "atomic512", SQLITE_IOCAP_ATOMIC512 }, + { "atomic1k", SQLITE_IOCAP_ATOMIC1K }, + { "atomic2k", SQLITE_IOCAP_ATOMIC2K }, + { "atomic4k", SQLITE_IOCAP_ATOMIC4K }, + { "atomic8k", SQLITE_IOCAP_ATOMIC8K }, + { "atomic16k", SQLITE_IOCAP_ATOMIC16K }, + { "atomic32k", SQLITE_IOCAP_ATOMIC32K }, + { "atomic64k", SQLITE_IOCAP_ATOMIC64K }, + { "sequential", SQLITE_IOCAP_SEQUENTIAL }, + { "safe_append", SQLITE_IOCAP_SAFE_APPEND }, + { "undeletable_when_open", SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN }, + { "powersafe_overwrite", SQLITE_IOCAP_POWERSAFE_OVERWRITE }, + { 0, 0 } + }; + Tcl_Obj *pRet; + int iFlag; + + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?ATTR-LIST?"); + return TCL_ERROR; + } + if( objc==3 ){ + int j; + int iNew = 0; + Tcl_Obj **flags = 0; + int nFlags = 0; + + if( Tcl_ListObjGetElements(interp, objv[2], &nFlags, &flags) ){ + return TCL_ERROR; + } + + for(j=0; j1 ){ + Tcl_AppendResult(interp, "bad flags: ", Tcl_GetString(objv[2]), 0); + return TCL_ERROR; + } + iNew |= aFlag[idx].iValue; + } + + p->iDevchar = iNew| 0x10000000; + } + + pRet = Tcl_NewObj(); + for(iFlag=0; iFlagiDevchar & aFlag[iFlag].iValue ){ + Tcl_ListObjAppendElement( + interp, pRet, Tcl_NewStringObj(aFlag[iFlag].zName, -1) + ); + } + } + Tcl_SetObjResult(interp, pRet); + + break; + } + + case CMD_SECTORSIZE: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?VALUE?"); + return TCL_ERROR; + } + if( objc==3 ){ + int iNew = 0; + if( Tcl_GetIntFromObj(interp, objv[2], &iNew) ){ + return TCL_ERROR; + } + p->iSectorsize = iNew; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(p->iSectorsize)); + break; + } + } + + return TCL_OK; +} + +static void testvfs_obj_del(ClientData cd){ + Testvfs *p = (Testvfs *)cd; + if( p->pScript ) Tcl_DecrRefCount(p->pScript); + sqlite3_vfs_unregister(p->pVfs); + ckfree((char *)p->pVfs); + ckfree((char *)p); +} + +/* +** Usage: testvfs VFSNAME ?SWITCHES? +** +** Switches are: +** +** -noshm BOOLEAN (True to omit shm methods. Default false) +** -default BOOLEAN (True to make the vfs default. Default false) +** +** This command creates two things when it is invoked: an SQLite VFS, and +** a Tcl command. Both are named VFSNAME. The VFS is installed. It is not +** installed as the default VFS. +** +** The VFS passes all file I/O calls through to the underlying VFS. +** +** Whenever the xShmMap method of the VFS +** is invoked, the SCRIPT is executed as follows: +** +** SCRIPT xShmMap FILENAME ID +** +** The value returned by the invocation of SCRIPT above is interpreted as +** an SQLite error code and returned to SQLite. Either a symbolic +** "SQLITE_OK" or numeric "0" value may be returned. +** +** The contents of the shared-memory buffer associated with a given file +** may be read and set using the following command: +** +** VFSNAME shm FILENAME ?NEWVALUE? +** +** When the xShmLock method is invoked by SQLite, the following script is +** run: +** +** SCRIPT xShmLock FILENAME ID LOCK +** +** where LOCK is of the form "OFFSET NBYTE lock/unlock shared/exclusive" +*/ +static int testvfs_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + static sqlite3_vfs tvfs_vfs = { + 3, /* iVersion */ + 0, /* szOsFile */ + 0, /* mxPathname */ + 0, /* pNext */ + 0, /* zName */ + 0, /* pAppData */ + tvfsOpen, /* xOpen */ + tvfsDelete, /* xDelete */ + tvfsAccess, /* xAccess */ + tvfsFullPathname, /* xFullPathname */ +#ifndef SQLITE_OMIT_LOAD_EXTENSION + tvfsDlOpen, /* xDlOpen */ + tvfsDlError, /* xDlError */ + tvfsDlSym, /* xDlSym */ + tvfsDlClose, /* xDlClose */ +#else + 0, /* xDlOpen */ + 0, /* xDlError */ + 0, /* xDlSym */ + 0, /* xDlClose */ +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + tvfsRandomness, /* xRandomness */ + tvfsSleep, /* xSleep */ + tvfsCurrentTime, /* xCurrentTime */ + 0, /* xGetLastError */ + 0, /* xCurrentTimeInt64 */ + 0, /* xSetSystemCall */ + 0, /* xGetSystemCall */ + 0, /* xNextSystemCall */ + }; + + Testvfs *p; /* New object */ + sqlite3_vfs *pVfs; /* New VFS */ + char *zVfs; + int nByte; /* Bytes of space to allocate at p */ + + int i; + int isNoshm = 0; /* True if -noshm is passed */ + int isFullshm = 0; /* True if -fullshm is passed */ + int isDefault = 0; /* True if -default is passed */ + int szOsFile = 0; /* Value passed to -szosfile */ + int mxPathname = -1; /* Value passed to -mxpathname */ + int iVersion = 3; /* Value passed to -iversion */ + + if( objc<2 || 0!=(objc%2) ) goto bad_args; + for(i=2; i2 && 0==strncmp("-noshm", zSwitch, nSwitch) ){ + if( Tcl_GetBooleanFromObj(interp, objv[i+1], &isNoshm) ){ + return TCL_ERROR; + } + if( isNoshm ) isFullshm = 0; + } + else if( nSwitch>2 && 0==strncmp("-default", zSwitch, nSwitch) ){ + if( Tcl_GetBooleanFromObj(interp, objv[i+1], &isDefault) ){ + return TCL_ERROR; + } + } + else if( nSwitch>2 && 0==strncmp("-szosfile", zSwitch, nSwitch) ){ + if( Tcl_GetIntFromObj(interp, objv[i+1], &szOsFile) ){ + return TCL_ERROR; + } + } + else if( nSwitch>2 && 0==strncmp("-mxpathname", zSwitch, nSwitch) ){ + if( Tcl_GetIntFromObj(interp, objv[i+1], &mxPathname) ){ + return TCL_ERROR; + } + } + else if( nSwitch>2 && 0==strncmp("-iversion", zSwitch, nSwitch) ){ + if( Tcl_GetIntFromObj(interp, objv[i+1], &iVersion) ){ + return TCL_ERROR; + } + } + else if( nSwitch>2 && 0==strncmp("-fullshm", zSwitch, nSwitch) ){ + if( Tcl_GetBooleanFromObj(interp, objv[i+1], &isFullshm) ){ + return TCL_ERROR; + } + if( isFullshm ) isNoshm = 0; + } + else{ + goto bad_args; + } + } + + if( szOsFileiDevchar = -1; + p->iSectorsize = -1; + + /* Create the new object command before querying SQLite for a default VFS + ** to use for 'real' IO operations. This is because creating the new VFS + ** may delete an existing [testvfs] VFS of the same name. If such a VFS + ** is currently the default, the new [testvfs] may end up calling the + ** methods of a deleted object. + */ + Tcl_CreateObjCommand(interp, zVfs, testvfs_obj_cmd, p, testvfs_obj_del); + p->pParent = sqlite3_vfs_find(0); + p->interp = interp; + + p->zName = (char *)&p[1]; + memcpy(p->zName, zVfs, strlen(zVfs)+1); + + pVfs = (sqlite3_vfs *)ckalloc(sizeof(sqlite3_vfs)); + memcpy(pVfs, &tvfs_vfs, sizeof(sqlite3_vfs)); + pVfs->pAppData = (void *)p; + pVfs->iVersion = iVersion; + pVfs->zName = p->zName; + pVfs->mxPathname = p->pParent->mxPathname; + if( mxPathname>=0 && mxPathnamemxPathname ){ + pVfs->mxPathname = mxPathname; + } + pVfs->szOsFile = szOsFile; + p->pVfs = pVfs; + p->isNoshm = isNoshm; + p->isFullshm = isFullshm; + p->mask = TESTVFS_ALL_MASK; + + sqlite3_vfs_register(pVfs, isDefault); + + return TCL_OK; + + bad_args: + Tcl_WrongNumArgs(interp, 1, objv, "VFSNAME ?-noshm BOOL? ?-default BOOL? ?-mxpathname INT? ?-szosfile INT? ?-iversion INT?"); + return TCL_ERROR; +} + +int Sqlitetestvfs_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "testvfs", testvfs_cmd, 0, 0); + return TCL_OK; +} + +#endif diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_vfstrace.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_vfstrace.c new file mode 100644 index 0000000000000000000000000000000000000000..0aacc01fe42e77feb858e4bed0cb7e04a435b210 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_vfstrace.c @@ -0,0 +1,887 @@ +/* +** 2011 March 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code implements a VFS shim that writes diagnostic +** output for each VFS call, similar to "strace". +** +** USAGE: +** +** This source file exports a single symbol which is the name of a +** function: +** +** int vfstrace_register( +** const char *zTraceName, // Name of the newly constructed VFS +** const char *zOldVfsName, // Name of the underlying VFS +** int (*xOut)(const char*,void*), // Output routine. ex: fputs +** void *pOutArg, // 2nd argument to xOut. ex: stderr +** int makeDefault // Make the new VFS the default +** ); +** +** Applications that want to trace their VFS usage must provide a callback +** function with this prototype: +** +** int traceOutput(const char *zMessage, void *pAppData); +** +** This function will "output" the trace messages, where "output" can +** mean different things to different applications. The traceOutput function +** for the command-line shell (see shell.c) is "fputs" from the standard +** library, which means that all trace output is written on the stream +** specified by the second argument. In the case of the command-line shell +** the second argument is stderr. Other applications might choose to output +** trace information to a file, over a socket, or write it into a buffer. +** +** The vfstrace_register() function creates a new "shim" VFS named by +** the zTraceName parameter. A "shim" VFS is an SQLite backend that does +** not really perform the duties of a true backend, but simply filters or +** interprets VFS calls before passing them off to another VFS which does +** the actual work. In this case the other VFS - the one that does the +** real work - is identified by the second parameter, zOldVfsName. If +** the 2nd parameter is NULL then the default VFS is used. The common +** case is for the 2nd parameter to be NULL. +** +** The third and fourth parameters are the pointer to the output function +** and the second argument to the output function. For the SQLite +** command-line shell, when the -vfstrace option is used, these parameters +** are fputs and stderr, respectively. +** +** The fifth argument is true (non-zero) to cause the newly created VFS +** to become the default VFS. The common case is for the fifth parameter +** to be true. +** +** The call to vfstrace_register() simply creates the shim VFS that does +** tracing. The application must also arrange to use the new VFS for +** all database connections that are created and for which tracing is +** desired. This can be done by specifying the trace VFS using URI filename +** notation, or by specifying the trace VFS as the 4th parameter to +** sqlite3_open_v2() or by making the trace VFS be the default (by setting +** the 5th parameter of vfstrace_register() to 1). +** +** +** ENABLING VFSTRACE IN A COMMAND-LINE SHELL +** +** The SQLite command line shell implemented by the shell.c source file +** can be used with this module. To compile in -vfstrace support, first +** gather this file (test_vfstrace.c), the shell source file (shell.c), +** and the SQLite amalgamation source files (sqlite3.c, sqlite3.h) into +** the working directory. Then compile using a command like the following: +** +** gcc -o sqlite3 -Os -I. -DSQLITE_ENABLE_VFSTRACE \ +** -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE \ +** -DHAVE_READLINE -DHAVE_USLEEP=1 \ +** shell.c test_vfstrace.c sqlite3.c -ldl -lreadline -lncurses +** +** The gcc command above works on Linux and provides (in addition to the +** -vfstrace option) support for FTS3 and FTS4, RTREE, and command-line +** editing using the readline library. The command-line shell does not +** use threads so we added -DSQLITE_THREADSAFE=0 just to make the code +** run a little faster. For compiling on a Mac, you'll probably need +** to omit the -DHAVE_READLINE, the -lreadline, and the -lncurses options. +** The compilation could be simplified to just this: +** +** gcc -DSQLITE_ENABLE_VFSTRACE \ +** shell.c test_vfstrace.c sqlite3.c -ldl -lpthread +** +** In this second example, all unnecessary options have been removed +** Note that since the code is now threadsafe, we had to add the -lpthread +** option to pull in the pthreads library. +** +** To cross-compile for windows using MinGW, a command like this might +** work: +** +** /opt/mingw/bin/i386-mingw32msvc-gcc -o sqlite3.exe -Os -I \ +** -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_VFSTRACE \ +** shell.c test_vfstrace.c sqlite3.c +** +** Similar compiler commands will work on different systems. The key +** invariants are (1) you must have -DSQLITE_ENABLE_VFSTRACE so that +** the shell.c source file will know to include the -vfstrace command-line +** option and (2) you must compile and link the three source files +** shell,c, test_vfstrace.c, and sqlite3.c. +*/ +#include +#include +#include "sqlite3.h" + +/* +** An instance of this structure is attached to the each trace VFS to +** provide auxiliary information. +*/ +typedef struct vfstrace_info vfstrace_info; +struct vfstrace_info { + sqlite3_vfs *pRootVfs; /* The underlying real VFS */ + int (*xOut)(const char*, void*); /* Send output here */ + void *pOutArg; /* First argument to xOut */ + const char *zVfsName; /* Name of this trace-VFS */ + sqlite3_vfs *pTraceVfs; /* Pointer back to the trace VFS */ +}; + +/* +** The sqlite3_file object for the trace VFS +*/ +typedef struct vfstrace_file vfstrace_file; +struct vfstrace_file { + sqlite3_file base; /* Base class. Must be first */ + vfstrace_info *pInfo; /* The trace-VFS to which this file belongs */ + const char *zFName; /* Base name of the file */ + sqlite3_file *pReal; /* The real underlying file */ +}; + +/* +** Method declarations for vfstrace_file. +*/ +static int vfstraceClose(sqlite3_file*); +static int vfstraceRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int vfstraceWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64); +static int vfstraceTruncate(sqlite3_file*, sqlite3_int64 size); +static int vfstraceSync(sqlite3_file*, int flags); +static int vfstraceFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int vfstraceLock(sqlite3_file*, int); +static int vfstraceUnlock(sqlite3_file*, int); +static int vfstraceCheckReservedLock(sqlite3_file*, int *); +static int vfstraceFileControl(sqlite3_file*, int op, void *pArg); +static int vfstraceSectorSize(sqlite3_file*); +static int vfstraceDeviceCharacteristics(sqlite3_file*); +static int vfstraceShmLock(sqlite3_file*,int,int,int); +static int vfstraceShmMap(sqlite3_file*,int,int,int, void volatile **); +static void vfstraceShmBarrier(sqlite3_file*); +static int vfstraceShmUnmap(sqlite3_file*,int); + +/* +** Method declarations for vfstrace_vfs. +*/ +static int vfstraceOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int vfstraceDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int vfstraceAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int vfstraceFullPathname(sqlite3_vfs*, const char *zName, int, char *); +static void *vfstraceDlOpen(sqlite3_vfs*, const char *zFilename); +static void vfstraceDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*vfstraceDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void); +static void vfstraceDlClose(sqlite3_vfs*, void*); +static int vfstraceRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int vfstraceSleep(sqlite3_vfs*, int microseconds); +static int vfstraceCurrentTime(sqlite3_vfs*, double*); +static int vfstraceGetLastError(sqlite3_vfs*, int, char*); +static int vfstraceCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); +static int vfstraceSetSystemCall(sqlite3_vfs*,const char*, sqlite3_syscall_ptr); +static sqlite3_syscall_ptr vfstraceGetSystemCall(sqlite3_vfs*, const char *); +static const char *vfstraceNextSystemCall(sqlite3_vfs*, const char *zName); + +/* +** Return a pointer to the tail of the pathname. Examples: +** +** /home/drh/xyzzy.txt -> xyzzy.txt +** xyzzy.txt -> xyzzy.txt +*/ +static const char *fileTail(const char *z){ + int i; + if( z==0 ) return 0; + i = strlen(z)-1; + while( i>0 && z[i-1]!='/' ){ i--; } + return &z[i]; +} + +/* +** Send trace output defined by zFormat and subsequent arguments. +*/ +static void vfstrace_printf( + vfstrace_info *pInfo, + const char *zFormat, + ... +){ + va_list ap; + char *zMsg; + va_start(ap, zFormat); + zMsg = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + pInfo->xOut(zMsg, pInfo->pOutArg); + sqlite3_free(zMsg); +} + +/* +** Convert value rc into a string and print it using zFormat. zFormat +** should have exactly one %s +*/ +static void vfstrace_print_errcode( + vfstrace_info *pInfo, + const char *zFormat, + int rc +){ + char zBuf[50]; + char *zVal; + switch( rc ){ + case SQLITE_OK: zVal = "SQLITE_OK"; break; + case SQLITE_ERROR: zVal = "SQLITE_ERROR"; break; + case SQLITE_PERM: zVal = "SQLITE_PERM"; break; + case SQLITE_ABORT: zVal = "SQLITE_ABORT"; break; + case SQLITE_BUSY: zVal = "SQLITE_BUSY"; break; + case SQLITE_NOMEM: zVal = "SQLITE_NOMEM"; break; + case SQLITE_READONLY: zVal = "SQLITE_READONLY"; break; + case SQLITE_INTERRUPT: zVal = "SQLITE_INTERRUPT"; break; + case SQLITE_IOERR: zVal = "SQLITE_IOERR"; break; + case SQLITE_CORRUPT: zVal = "SQLITE_CORRUPT"; break; + case SQLITE_FULL: zVal = "SQLITE_FULL"; break; + case SQLITE_CANTOPEN: zVal = "SQLITE_CANTOPEN"; break; + case SQLITE_PROTOCOL: zVal = "SQLITE_PROTOCOL"; break; + case SQLITE_EMPTY: zVal = "SQLITE_EMPTY"; break; + case SQLITE_SCHEMA: zVal = "SQLITE_SCHEMA"; break; + case SQLITE_CONSTRAINT: zVal = "SQLITE_CONSTRAINT"; break; + case SQLITE_MISMATCH: zVal = "SQLITE_MISMATCH"; break; + case SQLITE_MISUSE: zVal = "SQLITE_MISUSE"; break; + case SQLITE_NOLFS: zVal = "SQLITE_NOLFS"; break; + case SQLITE_IOERR_READ: zVal = "SQLITE_IOERR_READ"; break; + case SQLITE_IOERR_SHORT_READ: zVal = "SQLITE_IOERR_SHORT_READ"; break; + case SQLITE_IOERR_WRITE: zVal = "SQLITE_IOERR_WRITE"; break; + case SQLITE_IOERR_FSYNC: zVal = "SQLITE_IOERR_FSYNC"; break; + case SQLITE_IOERR_DIR_FSYNC: zVal = "SQLITE_IOERR_DIR_FSYNC"; break; + case SQLITE_IOERR_TRUNCATE: zVal = "SQLITE_IOERR_TRUNCATE"; break; + case SQLITE_IOERR_FSTAT: zVal = "SQLITE_IOERR_FSTAT"; break; + case SQLITE_IOERR_UNLOCK: zVal = "SQLITE_IOERR_UNLOCK"; break; + case SQLITE_IOERR_RDLOCK: zVal = "SQLITE_IOERR_RDLOCK"; break; + case SQLITE_IOERR_DELETE: zVal = "SQLITE_IOERR_DELETE"; break; + case SQLITE_IOERR_BLOCKED: zVal = "SQLITE_IOERR_BLOCKED"; break; + case SQLITE_IOERR_NOMEM: zVal = "SQLITE_IOERR_NOMEM"; break; + case SQLITE_IOERR_ACCESS: zVal = "SQLITE_IOERR_ACCESS"; break; + case SQLITE_IOERR_CHECKRESERVEDLOCK: + zVal = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; + case SQLITE_IOERR_LOCK: zVal = "SQLITE_IOERR_LOCK"; break; + case SQLITE_IOERR_CLOSE: zVal = "SQLITE_IOERR_CLOSE"; break; + case SQLITE_IOERR_DIR_CLOSE: zVal = "SQLITE_IOERR_DIR_CLOSE"; break; + case SQLITE_IOERR_SHMOPEN: zVal = "SQLITE_IOERR_SHMOPEN"; break; + case SQLITE_IOERR_SHMSIZE: zVal = "SQLITE_IOERR_SHMSIZE"; break; + case SQLITE_IOERR_SHMLOCK: zVal = "SQLITE_IOERR_SHMLOCK"; break; + case SQLITE_LOCKED_SHAREDCACHE: zVal = "SQLITE_LOCKED_SHAREDCACHE"; break; + case SQLITE_BUSY_RECOVERY: zVal = "SQLITE_BUSY_RECOVERY"; break; + case SQLITE_CANTOPEN_NOTEMPDIR: zVal = "SQLITE_CANTOPEN_NOTEMPDIR"; break; + default: { + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", rc); + zVal = zBuf; + break; + } + } + vfstrace_printf(pInfo, zFormat, zVal); +} + +/* +** Append to a buffer. +*/ +static void strappend(char *z, int *pI, const char *zAppend){ + int i = *pI; + while( zAppend[0] ){ z[i++] = *(zAppend++); } + z[i] = 0; + *pI = i; +} + +/* +** Close an vfstrace-file. +*/ +static int vfstraceClose(sqlite3_file *pFile){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xClose(%s)", pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xClose(p->pReal); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + if( rc==SQLITE_OK ){ + sqlite3_free((void*)p->base.pMethods); + p->base.pMethods = 0; + } + return rc; +} + +/* +** Read data from an vfstrace-file. +*/ +static int vfstraceRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xRead(%s,n=%d,ofst=%lld)", + pInfo->zVfsName, p->zFName, iAmt, iOfst); + rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Write data to an vfstrace-file. +*/ +static int vfstraceWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xWrite(%s,n=%d,ofst=%lld)", + pInfo->zVfsName, p->zFName, iAmt, iOfst); + rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Truncate an vfstrace-file. +*/ +static int vfstraceTruncate(sqlite3_file *pFile, sqlite_int64 size){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xTruncate(%s,%lld)", pInfo->zVfsName, p->zFName, + size); + rc = p->pReal->pMethods->xTruncate(p->pReal, size); + vfstrace_printf(pInfo, " -> %d\n", rc); + return rc; +} + +/* +** Sync an vfstrace-file. +*/ +static int vfstraceSync(sqlite3_file *pFile, int flags){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + int i; + char zBuf[100]; + memcpy(zBuf, "|0", 3); + i = 0; + if( flags & SQLITE_SYNC_FULL ) strappend(zBuf, &i, "|FULL"); + else if( flags & SQLITE_SYNC_NORMAL ) strappend(zBuf, &i, "|NORMAL"); + if( flags & SQLITE_SYNC_DATAONLY ) strappend(zBuf, &i, "|DATAONLY"); + if( flags & ~(SQLITE_SYNC_FULL|SQLITE_SYNC_DATAONLY) ){ + sqlite3_snprintf(sizeof(zBuf)-i, &zBuf[i], "|0x%x", flags); + } + vfstrace_printf(pInfo, "%s.xSync(%s,%s)", pInfo->zVfsName, p->zFName, + &zBuf[1]); + rc = p->pReal->pMethods->xSync(p->pReal, flags); + vfstrace_printf(pInfo, " -> %d\n", rc); + return rc; +} + +/* +** Return the current file-size of an vfstrace-file. +*/ +static int vfstraceFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xFileSize(%s)", pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); + vfstrace_print_errcode(pInfo, " -> %s,", rc); + vfstrace_printf(pInfo, " size=%lld\n", *pSize); + return rc; +} + +/* +** Return the name of a lock. +*/ +static const char *lockName(int eLock){ + const char *azLockNames[] = { + "NONE", "SHARED", "RESERVED", "PENDING", "EXCLUSIVE" + }; + if( eLock<0 || eLock>=sizeof(azLockNames)/sizeof(azLockNames[0]) ){ + return "???"; + }else{ + return azLockNames[eLock]; + } +} + +/* +** Lock an vfstrace-file. +*/ +static int vfstraceLock(sqlite3_file *pFile, int eLock){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xLock(%s,%s)", pInfo->zVfsName, p->zFName, + lockName(eLock)); + rc = p->pReal->pMethods->xLock(p->pReal, eLock); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Unlock an vfstrace-file. +*/ +static int vfstraceUnlock(sqlite3_file *pFile, int eLock){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xUnlock(%s,%s)", pInfo->zVfsName, p->zFName, + lockName(eLock)); + rc = p->pReal->pMethods->xUnlock(p->pReal, eLock); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Check if another file-handle holds a RESERVED lock on an vfstrace-file. +*/ +static int vfstraceCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xCheckReservedLock(%s,%d)", + pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); + vfstrace_print_errcode(pInfo, " -> %s", rc); + vfstrace_printf(pInfo, ", out=%d\n", *pResOut); + return rc; +} + +/* +** File control method. For custom operations on an vfstrace-file. +*/ +static int vfstraceFileControl(sqlite3_file *pFile, int op, void *pArg){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + char zBuf[100]; + char *zOp; + switch( op ){ + case SQLITE_FCNTL_LOCKSTATE: zOp = "LOCKSTATE"; break; + case SQLITE_GET_LOCKPROXYFILE: zOp = "GET_LOCKPROXYFILE"; break; + case SQLITE_SET_LOCKPROXYFILE: zOp = "SET_LOCKPROXYFILE"; break; + case SQLITE_LAST_ERRNO: zOp = "LAST_ERRNO"; break; + case SQLITE_FCNTL_SIZE_HINT: { + sqlite3_snprintf(sizeof(zBuf), zBuf, "SIZE_HINT,%lld", + *(sqlite3_int64*)pArg); + zOp = zBuf; + break; + } + case SQLITE_FCNTL_CHUNK_SIZE: { + sqlite3_snprintf(sizeof(zBuf), zBuf, "CHUNK_SIZE,%d", *(int*)pArg); + zOp = zBuf; + break; + } + case SQLITE_FCNTL_FILE_POINTER: zOp = "FILE_POINTER"; break; + case SQLITE_FCNTL_SYNC_OMITTED: zOp = "SYNC_OMITTED"; break; + case SQLITE_FCNTL_WIN32_AV_RETRY: zOp = "WIN32_AV_RETRY"; break; + case SQLITE_FCNTL_PERSIST_WAL: zOp = "PERSIST_WAL"; break; + case SQLITE_FCNTL_OVERWRITE: zOp = "OVERWRITE"; break; + case SQLITE_FCNTL_VFSNAME: zOp = "VFSNAME"; break; + case SQLITE_FCNTL_TEMPFILENAME: zOp = "TEMPFILENAME"; break; + case 0xca093fa0: zOp = "DB_UNCHANGED"; break; + case SQLITE_FCNTL_PRAGMA: { + const char *const* a = (const char*const*)pArg; + sqlite3_snprintf(sizeof(zBuf), zBuf, "PRAGMA,[%s,%s]",a[1],a[2]); + zOp = zBuf; + break; + } + default: { + sqlite3_snprintf(sizeof zBuf, zBuf, "%d", op); + zOp = zBuf; + break; + } + } + vfstrace_printf(pInfo, "%s.xFileControl(%s,%s)", + pInfo->zVfsName, p->zFName, zOp); + rc = p->pReal->pMethods->xFileControl(p->pReal, op, pArg); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){ + *(char**)pArg = sqlite3_mprintf("vfstrace.%s/%z", + pInfo->zVfsName, *(char**)pArg); + } + if( (op==SQLITE_FCNTL_PRAGMA || op==SQLITE_FCNTL_TEMPFILENAME) + && rc==SQLITE_OK && *(char**)pArg ){ + vfstrace_printf(pInfo, "%s.xFileControl(%s,%s) returns %s", + pInfo->zVfsName, p->zFName, zOp, *(char**)pArg); + } + return rc; +} + +/* +** Return the sector-size in bytes for an vfstrace-file. +*/ +static int vfstraceSectorSize(sqlite3_file *pFile){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xSectorSize(%s)", pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xSectorSize(p->pReal); + vfstrace_printf(pInfo, " -> %d\n", rc); + return rc; +} + +/* +** Return the device characteristic flags supported by an vfstrace-file. +*/ +static int vfstraceDeviceCharacteristics(sqlite3_file *pFile){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xDeviceCharacteristics(%s)", + pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xDeviceCharacteristics(p->pReal); + vfstrace_printf(pInfo, " -> 0x%08x\n", rc); + return rc; +} + +/* +** Shared-memory operations. +*/ +static int vfstraceShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + char zLck[100]; + int i = 0; + memcpy(zLck, "|0", 3); + if( flags & SQLITE_SHM_UNLOCK ) strappend(zLck, &i, "|UNLOCK"); + if( flags & SQLITE_SHM_LOCK ) strappend(zLck, &i, "|LOCK"); + if( flags & SQLITE_SHM_SHARED ) strappend(zLck, &i, "|SHARED"); + if( flags & SQLITE_SHM_EXCLUSIVE ) strappend(zLck, &i, "|EXCLUSIVE"); + if( flags & ~(0xf) ){ + sqlite3_snprintf(sizeof(zLck)-i, &zLck[i], "|0x%x", flags); + } + vfstrace_printf(pInfo, "%s.xShmLock(%s,ofst=%d,n=%d,%s)", + pInfo->zVfsName, p->zFName, ofst, n, &zLck[1]); + rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} +static int vfstraceShmMap( + sqlite3_file *pFile, + int iRegion, + int szRegion, + int isWrite, + void volatile **pp +){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xShmMap(%s,iRegion=%d,szRegion=%d,isWrite=%d,*)", + pInfo->zVfsName, p->zFName, iRegion, szRegion, isWrite); + rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} +static void vfstraceShmBarrier(sqlite3_file *pFile){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + vfstrace_printf(pInfo, "%s.xShmBarrier(%s)\n", pInfo->zVfsName, p->zFName); + p->pReal->pMethods->xShmBarrier(p->pReal); +} +static int vfstraceShmUnmap(sqlite3_file *pFile, int delFlag){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xShmUnmap(%s,delFlag=%d)", + pInfo->zVfsName, p->zFName, delFlag); + rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + + + +/* +** Open an vfstrace file handle. +*/ +static int vfstraceOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + p->pInfo = pInfo; + p->zFName = zName ? fileTail(zName) : ""; + p->pReal = (sqlite3_file *)&p[1]; + rc = pRoot->xOpen(pRoot, zName, p->pReal, flags, pOutFlags); + vfstrace_printf(pInfo, "%s.xOpen(%s,flags=0x%x)", + pInfo->zVfsName, p->zFName, flags); + if( p->pReal->pMethods ){ + sqlite3_io_methods *pNew = sqlite3_malloc( sizeof(*pNew) ); + const sqlite3_io_methods *pSub = p->pReal->pMethods; + memset(pNew, 0, sizeof(*pNew)); + pNew->iVersion = pSub->iVersion; + pNew->xClose = vfstraceClose; + pNew->xRead = vfstraceRead; + pNew->xWrite = vfstraceWrite; + pNew->xTruncate = vfstraceTruncate; + pNew->xSync = vfstraceSync; + pNew->xFileSize = vfstraceFileSize; + pNew->xLock = vfstraceLock; + pNew->xUnlock = vfstraceUnlock; + pNew->xCheckReservedLock = vfstraceCheckReservedLock; + pNew->xFileControl = vfstraceFileControl; + pNew->xSectorSize = vfstraceSectorSize; + pNew->xDeviceCharacteristics = vfstraceDeviceCharacteristics; + if( pNew->iVersion>=2 ){ + pNew->xShmMap = pSub->xShmMap ? vfstraceShmMap : 0; + pNew->xShmLock = pSub->xShmLock ? vfstraceShmLock : 0; + pNew->xShmBarrier = pSub->xShmBarrier ? vfstraceShmBarrier : 0; + pNew->xShmUnmap = pSub->xShmUnmap ? vfstraceShmUnmap : 0; + } + pFile->pMethods = pNew; + } + vfstrace_print_errcode(pInfo, " -> %s", rc); + if( pOutFlags ){ + vfstrace_printf(pInfo, ", outFlags=0x%x\n", *pOutFlags); + }else{ + vfstrace_printf(pInfo, "\n"); + } + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int vfstraceDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + int rc; + vfstrace_printf(pInfo, "%s.xDelete(\"%s\",%d)", + pInfo->zVfsName, zPath, dirSync); + rc = pRoot->xDelete(pRoot, zPath, dirSync); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int vfstraceAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + int rc; + vfstrace_printf(pInfo, "%s.xDelete(\"%s\",%d)", + pInfo->zVfsName, zPath, flags); + rc = pRoot->xAccess(pRoot, zPath, flags, pResOut); + vfstrace_print_errcode(pInfo, " -> %s", rc); + vfstrace_printf(pInfo, ", out=%d\n", *pResOut); + return rc; +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (DEVSYM_MAX_PATHNAME+1) bytes. +*/ +static int vfstraceFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + int rc; + vfstrace_printf(pInfo, "%s.xFullPathname(\"%s\")", + pInfo->zVfsName, zPath); + rc = pRoot->xFullPathname(pRoot, zPath, nOut, zOut); + vfstrace_print_errcode(pInfo, " -> %s", rc); + vfstrace_printf(pInfo, ", out=\"%.*s\"\n", nOut, zOut); + return rc; +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *vfstraceDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xDlOpen(\"%s\")\n", pInfo->zVfsName, zPath); + return pRoot->xDlOpen(pRoot, zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void vfstraceDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xDlError(%d)", pInfo->zVfsName, nByte); + pRoot->xDlError(pRoot, nByte, zErrMsg); + vfstrace_printf(pInfo, " -> \"%s\"", zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*vfstraceDlSym(sqlite3_vfs *pVfs,void *p,const char *zSym))(void){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xDlSym(\"%s\")\n", pInfo->zVfsName, zSym); + return pRoot->xDlSym(pRoot, p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void vfstraceDlClose(sqlite3_vfs *pVfs, void *pHandle){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xDlOpen()\n", pInfo->zVfsName); + pRoot->xDlClose(pRoot, pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int vfstraceRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xRandomness(%d)\n", pInfo->zVfsName, nByte); + return pRoot->xRandomness(pRoot, nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int vfstraceSleep(sqlite3_vfs *pVfs, int nMicro){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xSleep(pRoot, nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int vfstraceCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xCurrentTime(pRoot, pTimeOut); +} +static int vfstraceCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xCurrentTimeInt64(pRoot, pTimeOut); +} + +/* +** Return th3 emost recent error code and message +*/ +static int vfstraceGetLastError(sqlite3_vfs *pVfs, int iErr, char *zErr){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xGetLastError(pRoot, iErr, zErr); +} + +/* +** Override system calls. +*/ +static int vfstraceSetSystemCall( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_syscall_ptr pFunc +){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xSetSystemCall(pRoot, zName, pFunc); +} +static sqlite3_syscall_ptr vfstraceGetSystemCall( + sqlite3_vfs *pVfs, + const char *zName +){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xGetSystemCall(pRoot, zName); +} +static const char *vfstraceNextSystemCall(sqlite3_vfs *pVfs, const char *zName){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xNextSystemCall(pRoot, zName); +} + + +/* +** Clients invoke this routine to construct a new trace-vfs shim. +** +** Return SQLITE_OK on success. +** +** SQLITE_NOMEM is returned in the case of a memory allocation error. +** SQLITE_NOTFOUND is returned if zOldVfsName does not exist. +*/ +int vfstrace_register( + const char *zTraceName, /* Name of the newly constructed VFS */ + const char *zOldVfsName, /* Name of the underlying VFS */ + int (*xOut)(const char*,void*), /* Output routine. ex: fputs */ + void *pOutArg, /* 2nd argument to xOut. ex: stderr */ + int makeDefault /* True to make the new VFS the default */ +){ + sqlite3_vfs *pNew; + sqlite3_vfs *pRoot; + vfstrace_info *pInfo; + int nName; + int nByte; + + pRoot = sqlite3_vfs_find(zOldVfsName); + if( pRoot==0 ) return SQLITE_NOTFOUND; + nName = strlen(zTraceName); + nByte = sizeof(*pNew) + sizeof(*pInfo) + nName + 1; + pNew = sqlite3_malloc( nByte ); + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, nByte); + pInfo = (vfstrace_info*)&pNew[1]; + pNew->iVersion = pRoot->iVersion; + pNew->szOsFile = pRoot->szOsFile + sizeof(vfstrace_file); + pNew->mxPathname = pRoot->mxPathname; + pNew->zName = (char*)&pInfo[1]; + memcpy((char*)&pInfo[1], zTraceName, nName+1); + pNew->pAppData = pInfo; + pNew->xOpen = vfstraceOpen; + pNew->xDelete = vfstraceDelete; + pNew->xAccess = vfstraceAccess; + pNew->xFullPathname = vfstraceFullPathname; + pNew->xDlOpen = pRoot->xDlOpen==0 ? 0 : vfstraceDlOpen; + pNew->xDlError = pRoot->xDlError==0 ? 0 : vfstraceDlError; + pNew->xDlSym = pRoot->xDlSym==0 ? 0 : vfstraceDlSym; + pNew->xDlClose = pRoot->xDlClose==0 ? 0 : vfstraceDlClose; + pNew->xRandomness = vfstraceRandomness; + pNew->xSleep = vfstraceSleep; + pNew->xCurrentTime = vfstraceCurrentTime; + pNew->xGetLastError = pRoot->xGetLastError==0 ? 0 : vfstraceGetLastError; + if( pNew->iVersion>=2 ){ + pNew->xCurrentTimeInt64 = pRoot->xCurrentTimeInt64==0 ? 0 : + vfstraceCurrentTimeInt64; + if( pNew->iVersion>=3 ){ + pNew->xSetSystemCall = pRoot->xSetSystemCall==0 ? 0 : + vfstraceSetSystemCall; + pNew->xGetSystemCall = pRoot->xGetSystemCall==0 ? 0 : + vfstraceGetSystemCall; + pNew->xNextSystemCall = pRoot->xNextSystemCall==0 ? 0 : + vfstraceNextSystemCall; + } + } + pInfo->pRootVfs = pRoot; + pInfo->xOut = xOut; + pInfo->pOutArg = pOutArg; + pInfo->zVfsName = pNew->zName; + pInfo->pTraceVfs = pNew; + vfstrace_printf(pInfo, "%s.enabled_for(\"%s\")\n", + pInfo->zVfsName, pRoot->zName); + return sqlite3_vfs_register(pNew, makeDefault); +} diff --git a/components/external/SQLite-3.8.1/SQLiteLib/test/test_wsd.c b/components/external/SQLite-3.8.1/SQLiteLib/test/test_wsd.c new file mode 100644 index 0000000000000000000000000000000000000000..99e4a056581f58f4536fdb5a5df75c74698a8162 --- /dev/null +++ b/components/external/SQLite-3.8.1/SQLiteLib/test/test_wsd.c @@ -0,0 +1,84 @@ +/* +** 2008 September 1 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** The code in this file contains sample implementations of the +** sqlite3_wsd_init() and sqlite3_wsd_find() functions required if the +** SQLITE_OMIT_WSD symbol is defined at build time. +*/ + +#if defined(SQLITE_OMIT_WSD) && defined(SQLITE_TEST) + +#include "sqliteInt.h" + +#define PLS_HASHSIZE 43 + +typedef struct ProcessLocalStorage ProcessLocalStorage; +typedef struct ProcessLocalVar ProcessLocalVar; + +struct ProcessLocalStorage { + ProcessLocalVar *aData[PLS_HASHSIZE]; + int nFree; + u8 *pFree; +}; + +struct ProcessLocalVar { + void *pKey; + ProcessLocalVar *pNext; +}; + +static ProcessLocalStorage *pGlobal = 0; + +int sqlite3_wsd_init(int N, int J){ + if( !pGlobal ){ + int nMalloc = N + sizeof(ProcessLocalStorage) + J*sizeof(ProcessLocalVar); + pGlobal = (ProcessLocalStorage *)malloc(nMalloc); + if( pGlobal ){ + memset(pGlobal, 0, sizeof(ProcessLocalStorage)); + pGlobal->nFree = nMalloc - sizeof(ProcessLocalStorage); + pGlobal->pFree = (u8 *)&pGlobal[1]; + } + } + + return pGlobal ? SQLITE_OK : SQLITE_NOMEM; +} + +void *sqlite3_wsd_find(void *K, int L){ + int i; + int iHash = 0; + ProcessLocalVar *pVar; + + /* Calculate a hash of K */ + for(i=0; iaData[iHash]; pVar && pVar->pKey!=K; pVar=pVar->pNext); + + /* If no entry for K was found, create and populate a new one. */ + if( !pVar ){ + int nByte = ROUND8(sizeof(ProcessLocalVar) + L); + assert( pGlobal->nFree>=nByte ); + pVar = (ProcessLocalVar *)pGlobal->pFree; + pVar->pKey = K; + pVar->pNext = pGlobal->aData[iHash]; + pGlobal->aData[iHash] = pVar; + pGlobal->nFree -= nByte; + pGlobal->pFree += nByte; + memcpy(&pVar[1], K, L); + } + + return (void *)&pVar[1]; +} + +#endif diff --git a/components/external/SQLite-3.8.1/VERSION b/components/external/SQLite-3.8.1/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..f2807196747ffcee4ae8a36604b9cff7ebeed9ca --- /dev/null +++ b/components/external/SQLite-3.8.1/VERSION @@ -0,0 +1 @@ +3.8.1 diff --git a/components/external/SQLite-3.8.1/aclocal.m4 b/components/external/SQLite-3.8.1/aclocal.m4 new file mode 100644 index 0000000000000000000000000000000000000000..8e5151ebade66b84b1d559b404751a05d7670e37 --- /dev/null +++ b/components/external/SQLite-3.8.1/aclocal.m4 @@ -0,0 +1,7972 @@ +# generated automatically by aclocal 1.10.2 -*- Autoconf -*- + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, +# 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, +# 2006, 2007, 2008 Free Software Foundation, Inc. +# Written by Gordon Matzigkeit, 1996 +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +m4_define([_LT_COPYING], [dnl +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, +# 2006, 2007, 2008 Free Software Foundation, Inc. +# Written by Gordon Matzigkeit, 1996 +# +# This file is part of GNU Libtool. +# +# GNU Libtool is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of +# the License, or (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Libtool; see the file COPYING. If not, a copy +# can be downloaded from http://www.gnu.org/licenses/gpl.html, or +# obtained by writing to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +]) + +# serial 56 LT_INIT + + +# LT_PREREQ(VERSION) +# ------------------ +# Complain and exit if this libtool version is less that VERSION. +m4_defun([LT_PREREQ], +[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1, + [m4_default([$3], + [m4_fatal([Libtool version $1 or higher is required], + 63)])], + [$2])]) + + +# _LT_CHECK_BUILDDIR +# ------------------ +# Complain if the absolute build directory name contains unusual characters +m4_defun([_LT_CHECK_BUILDDIR], +[case `pwd` in + *\ * | *\ *) + AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;; +esac +]) + + +# LT_INIT([OPTIONS]) +# ------------------ +AC_DEFUN([LT_INIT], +[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT +AC_BEFORE([$0], [LT_LANG])dnl +AC_BEFORE([$0], [LT_OUTPUT])dnl +AC_BEFORE([$0], [LTDL_INIT])dnl +m4_require([_LT_CHECK_BUILDDIR])dnl + +dnl Autoconf doesn't catch unexpanded LT_ macros by default: +m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl +m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl +dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 +dnl unless we require an AC_DEFUNed macro: +AC_REQUIRE([LTOPTIONS_VERSION])dnl +AC_REQUIRE([LTSUGAR_VERSION])dnl +AC_REQUIRE([LTVERSION_VERSION])dnl +AC_REQUIRE([LTOBSOLETE_VERSION])dnl +m4_require([_LT_PROG_LTMAIN])dnl + +dnl Parse OPTIONS +_LT_SET_OPTIONS([$0], [$1]) + +# This can be used to rebuild libtool when needed +LIBTOOL_DEPS="$ltmain" + +# Always use our own libtool. +LIBTOOL='$(SHELL) $(top_builddir)/libtool' +AC_SUBST(LIBTOOL)dnl + +_LT_SETUP + +# Only expand once: +m4_define([LT_INIT]) +])# LT_INIT + +# Old names: +AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT]) +AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_PROG_LIBTOOL], []) +dnl AC_DEFUN([AM_PROG_LIBTOOL], []) + + +# _LT_CC_BASENAME(CC) +# ------------------- +# Calculate cc_basename. Skip known compiler wrappers and cross-prefix. +m4_defun([_LT_CC_BASENAME], +[for cc_temp in $1""; do + case $cc_temp in + compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; + distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$ECHO "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` +]) + + +# _LT_FILEUTILS_DEFAULTS +# ---------------------- +# It is okay to use these file commands and assume they have been set +# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'. +m4_defun([_LT_FILEUTILS_DEFAULTS], +[: ${CP="cp -f"} +: ${MV="mv -f"} +: ${RM="rm -f"} +])# _LT_FILEUTILS_DEFAULTS + + +# _LT_SETUP +# --------- +m4_defun([_LT_SETUP], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_CANONICAL_BUILD])dnl +_LT_DECL([], [host_alias], [0], [The host system])dnl +_LT_DECL([], [host], [0])dnl +_LT_DECL([], [host_os], [0])dnl +dnl +_LT_DECL([], [build_alias], [0], [The build system])dnl +_LT_DECL([], [build], [0])dnl +_LT_DECL([], [build_os], [0])dnl +dnl +AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([LT_PATH_LD])dnl +AC_REQUIRE([LT_PATH_NM])dnl +dnl +AC_REQUIRE([AC_PROG_LN_S])dnl +test -z "$LN_S" && LN_S="ln -s" +_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl +dnl +AC_REQUIRE([LT_CMD_MAX_LEN])dnl +_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl +_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl +dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_CHECK_SHELL_FEATURES])dnl +m4_require([_LT_CMD_RELOAD])dnl +m4_require([_LT_CHECK_MAGIC_METHOD])dnl +m4_require([_LT_CMD_OLD_ARCHIVE])dnl +m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl + +_LT_CONFIG_LIBTOOL_INIT([ +# See if we are running on zsh, and set the options which allow our +# commands through without removal of \ escapes INIT. +if test -n "\${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST +fi +]) +if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST +fi + +_LT_CHECK_OBJDIR + +m4_require([_LT_TAG_COMPILER])dnl +_LT_PROG_ECHO_BACKSLASH + +case $host_os in +aix3*) + # AIX sometimes has problems with the GCC collect2 program. For some + # reason, if we set the COLLECT_NAMES environment variable, the problems + # vanish in a puff of smoke. + if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES + fi + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +sed_quote_subst='s/\([["`$\\]]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\([["`\\]]\)/\\\1/g' + +# Sed substitution to delay expansion of an escaped shell variable in a +# double_quote_subst'ed string. +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' + +# Sed substitution to delay expansion of an escaped single quote. +delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' + +# Sed substitution to avoid accidental globbing in evaled expressions +no_glob_subst='s/\*/\\\*/g' + +# Global variables: +ofile=libtool +can_build_shared=yes + +# All known linkers require a `.a' archive for static linking (except MSVC, +# which needs '.lib'). +libext=a + +with_gnu_ld="$lt_cv_prog_gnu_ld" + +old_CC="$CC" +old_CFLAGS="$CFLAGS" + +# Set sane defaults for various variables +test -z "$CC" && CC=cc +test -z "$LTCC" && LTCC=$CC +test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS +test -z "$LD" && LD=ld +test -z "$ac_objext" && ac_objext=o + +_LT_CC_BASENAME([$compiler]) + +# Only perform the check for file, if the check method requires it +test -z "$MAGIC_CMD" && MAGIC_CMD=file +case $deplibs_check_method in +file_magic*) + if test "$file_magic_cmd" = '$MAGIC_CMD'; then + _LT_PATH_MAGIC + fi + ;; +esac + +# Use C for the default configuration in the libtool script +LT_SUPPORTED_TAG([CC]) +_LT_LANG_C_CONFIG +_LT_LANG_DEFAULT_CONFIG +_LT_CONFIG_COMMANDS +])# _LT_SETUP + + +# _LT_PROG_LTMAIN +# --------------- +# Note that this code is called both from `configure', and `config.status' +# now that we use AC_CONFIG_COMMANDS to generate libtool. Notably, +# `config.status' has no value for ac_aux_dir unless we are using Automake, +# so we pass a copy along to make sure it has a sensible value anyway. +m4_defun([_LT_PROG_LTMAIN], +[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl +_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir']) +ltmain="$ac_aux_dir/ltmain.sh" +])# _LT_PROG_LTMAIN + + + +# So that we can recreate a full libtool script including additional +# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS +# in macros and then make a single call at the end using the `libtool' +# label. + + +# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS]) +# ---------------------------------------- +# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later. +m4_define([_LT_CONFIG_LIBTOOL_INIT], +[m4_ifval([$1], + [m4_append([_LT_OUTPUT_LIBTOOL_INIT], + [$1 +])])]) + +# Initialize. +m4_define([_LT_OUTPUT_LIBTOOL_INIT]) + + +# _LT_CONFIG_LIBTOOL([COMMANDS]) +# ------------------------------ +# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later. +m4_define([_LT_CONFIG_LIBTOOL], +[m4_ifval([$1], + [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS], + [$1 +])])]) + +# Initialize. +m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS]) + + +# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS]) +# ----------------------------------------------------- +m4_defun([_LT_CONFIG_SAVE_COMMANDS], +[_LT_CONFIG_LIBTOOL([$1]) +_LT_CONFIG_LIBTOOL_INIT([$2]) +]) + + +# _LT_FORMAT_COMMENT([COMMENT]) +# ----------------------------- +# Add leading comment marks to the start of each line, and a trailing +# full-stop to the whole comment if one is not present already. +m4_define([_LT_FORMAT_COMMENT], +[m4_ifval([$1], [ +m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])], + [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.]) +)]) + + + + + +# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?]) +# ------------------------------------------------------------------- +# CONFIGNAME is the name given to the value in the libtool script. +# VARNAME is the (base) name used in the configure script. +# VALUE may be 0, 1 or 2 for a computed quote escaped value based on +# VARNAME. Any other value will be used directly. +m4_define([_LT_DECL], +[lt_if_append_uniq([lt_decl_varnames], [$2], [, ], + [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name], + [m4_ifval([$1], [$1], [$2])]) + lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3]) + m4_ifval([$4], + [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])]) + lt_dict_add_subkey([lt_decl_dict], [$2], + [tagged?], [m4_ifval([$5], [yes], [no])])]) +]) + + +# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION]) +# -------------------------------------------------------- +m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])]) + + +# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...]) +# ------------------------------------------------ +m4_define([lt_decl_tag_varnames], +[_lt_decl_filter([tagged?], [yes], $@)]) + + +# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..]) +# --------------------------------------------------------- +m4_define([_lt_decl_filter], +[m4_case([$#], + [0], [m4_fatal([$0: too few arguments: $#])], + [1], [m4_fatal([$0: too few arguments: $#: $1])], + [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)], + [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)], + [lt_dict_filter([lt_decl_dict], $@)])[]dnl +]) + + +# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...]) +# -------------------------------------------------- +m4_define([lt_decl_quote_varnames], +[_lt_decl_filter([value], [1], $@)]) + + +# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...]) +# --------------------------------------------------- +m4_define([lt_decl_dquote_varnames], +[_lt_decl_filter([value], [2], $@)]) + + +# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...]) +# --------------------------------------------------- +m4_define([lt_decl_varnames_tagged], +[m4_assert([$# <= 2])dnl +_$0(m4_quote(m4_default([$1], [[, ]])), + m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]), + m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))]) +m4_define([_lt_decl_varnames_tagged], +[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])]) + + +# lt_decl_all_varnames([SEPARATOR], [VARNAME1...]) +# ------------------------------------------------ +m4_define([lt_decl_all_varnames], +[_$0(m4_quote(m4_default([$1], [[, ]])), + m4_if([$2], [], + m4_quote(lt_decl_varnames), + m4_quote(m4_shift($@))))[]dnl +]) +m4_define([_lt_decl_all_varnames], +[lt_join($@, lt_decl_varnames_tagged([$1], + lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl +]) + + +# _LT_CONFIG_STATUS_DECLARE([VARNAME]) +# ------------------------------------ +# Quote a variable value, and forward it to `config.status' so that its +# declaration there will have the same value as in `configure'. VARNAME +# must have a single quote delimited value for this to work. +m4_define([_LT_CONFIG_STATUS_DECLARE], +[$1='`$ECHO "X$][$1" | $Xsed -e "$delay_single_quote_subst"`']) + + +# _LT_CONFIG_STATUS_DECLARATIONS +# ------------------------------ +# We delimit libtool config variables with single quotes, so when +# we write them to config.status, we have to be sure to quote all +# embedded single quotes properly. In configure, this macro expands +# each variable declared with _LT_DECL (and _LT_TAGDECL) into: +# +# ='`$ECHO "X$" | $Xsed -e "$delay_single_quote_subst"`' +m4_defun([_LT_CONFIG_STATUS_DECLARATIONS], +[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames), + [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])]) + + +# _LT_LIBTOOL_TAGS +# ---------------- +# Output comment and list of tags supported by the script +m4_defun([_LT_LIBTOOL_TAGS], +[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl +available_tags="_LT_TAGS"dnl +]) + + +# _LT_LIBTOOL_DECLARE(VARNAME, [TAG]) +# ----------------------------------- +# Extract the dictionary values for VARNAME (optionally with TAG) and +# expand to a commented shell variable setting: +# +# # Some comment about what VAR is for. +# visible_name=$lt_internal_name +m4_define([_LT_LIBTOOL_DECLARE], +[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], + [description])))[]dnl +m4_pushdef([_libtool_name], + m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl +m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])), + [0], [_libtool_name=[$]$1], + [1], [_libtool_name=$lt_[]$1], + [2], [_libtool_name=$lt_[]$1], + [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl +m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl +]) + + +# _LT_LIBTOOL_CONFIG_VARS +# ----------------------- +# Produce commented declarations of non-tagged libtool config variables +# suitable for insertion in the LIBTOOL CONFIG section of the `libtool' +# script. Tagged libtool config variables (even for the LIBTOOL CONFIG +# section) are produced by _LT_LIBTOOL_TAG_VARS. +m4_defun([_LT_LIBTOOL_CONFIG_VARS], +[m4_foreach([_lt_var], + m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)), + [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])]) + + +# _LT_LIBTOOL_TAG_VARS(TAG) +# ------------------------- +m4_define([_LT_LIBTOOL_TAG_VARS], +[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames), + [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])]) + + +# _LT_TAGVAR(VARNAME, [TAGNAME]) +# ------------------------------ +m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])]) + + +# _LT_CONFIG_COMMANDS +# ------------------- +# Send accumulated output to $CONFIG_STATUS. Thanks to the lists of +# variables for single and double quote escaping we saved from calls +# to _LT_DECL, we can put quote escaped variables declarations +# into `config.status', and then the shell code to quote escape them in +# for loops in `config.status'. Finally, any additional code accumulated +# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded. +m4_defun([_LT_CONFIG_COMMANDS], +[AC_PROVIDE_IFELSE([LT_OUTPUT], + dnl If the libtool generation code has been placed in $CONFIG_LT, + dnl instead of duplicating it all over again into config.status, + dnl then we will have config.status run $CONFIG_LT later, so it + dnl needs to know what name is stored there: + [AC_CONFIG_COMMANDS([libtool], + [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])], + dnl If the libtool generation code is destined for config.status, + dnl expand the accumulated commands and init code now: + [AC_CONFIG_COMMANDS([libtool], + [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])]) +])#_LT_CONFIG_COMMANDS + + +# Initialize. +m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT], +[ + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +sed_quote_subst='$sed_quote_subst' +double_quote_subst='$double_quote_subst' +delay_variable_subst='$delay_variable_subst' +_LT_CONFIG_STATUS_DECLARATIONS +LTCC='$LTCC' +LTCFLAGS='$LTCFLAGS' +compiler='$compiler_DEFAULT' + +# Quote evaled strings. +for var in lt_decl_all_varnames([[ \ +]], lt_decl_quote_varnames); do + case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in + *[[\\\\\\\`\\"\\\$]]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +# Double-quote double-evaled strings. +for var in lt_decl_all_varnames([[ \ +]], lt_decl_dquote_varnames); do + case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in + *[[\\\\\\\`\\"\\\$]]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +# Fix-up fallback echo if it was mangled by the above quoting rules. +case \$lt_ECHO in +*'\\\[$]0 --fallback-echo"')dnl " + lt_ECHO=\`\$ECHO "X\$lt_ECHO" | \$Xsed -e 's/\\\\\\\\\\\\\\\[$]0 --fallback-echo"\[$]/\[$]0 --fallback-echo"/'\` + ;; +esac + +_LT_OUTPUT_LIBTOOL_INIT +]) + + +# LT_OUTPUT +# --------- +# This macro allows early generation of the libtool script (before +# AC_OUTPUT is called), incase it is used in configure for compilation +# tests. +AC_DEFUN([LT_OUTPUT], +[: ${CONFIG_LT=./config.lt} +AC_MSG_NOTICE([creating $CONFIG_LT]) +cat >"$CONFIG_LT" <<_LTEOF +#! $SHELL +# Generated by $as_me. +# Run this file to recreate a libtool stub with the current configuration. + +lt_cl_silent=false +SHELL=\${CONFIG_SHELL-$SHELL} +_LTEOF + +cat >>"$CONFIG_LT" <<\_LTEOF +AS_SHELL_SANITIZE +_AS_PREPARE + +exec AS_MESSAGE_FD>&1 +exec AS_MESSAGE_LOG_FD>>config.log +{ + echo + AS_BOX([Running $as_me.]) +} >&AS_MESSAGE_LOG_FD + +lt_cl_help="\ +\`$as_me' creates a local libtool stub from the current configuration, +for use in further configure time tests before the real libtool is +generated. + +Usage: $[0] [[OPTIONS]] + + -h, --help print this help, then exit + -V, --version print version number, then exit + -q, --quiet do not print progress messages + -d, --debug don't remove temporary files + +Report bugs to ." + +lt_cl_version="\ +m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl +m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) +configured by $[0], generated by m4_PACKAGE_STRING. + +Copyright (C) 2008 Free Software Foundation, Inc. +This config.lt script is free software; the Free Software Foundation +gives unlimited permision to copy, distribute and modify it." + +while test $[#] != 0 +do + case $[1] in + --version | --v* | -V ) + echo "$lt_cl_version"; exit 0 ;; + --help | --h* | -h ) + echo "$lt_cl_help"; exit 0 ;; + --debug | --d* | -d ) + debug=: ;; + --quiet | --q* | --silent | --s* | -q ) + lt_cl_silent=: ;; + + -*) AC_MSG_ERROR([unrecognized option: $[1] +Try \`$[0] --help' for more information.]) ;; + + *) AC_MSG_ERROR([unrecognized argument: $[1] +Try \`$[0] --help' for more information.]) ;; + esac + shift +done + +if $lt_cl_silent; then + exec AS_MESSAGE_FD>/dev/null +fi +_LTEOF + +cat >>"$CONFIG_LT" <<_LTEOF +_LT_OUTPUT_LIBTOOL_COMMANDS_INIT +_LTEOF + +cat >>"$CONFIG_LT" <<\_LTEOF +AC_MSG_NOTICE([creating $ofile]) +_LT_OUTPUT_LIBTOOL_COMMANDS +AS_EXIT(0) +_LTEOF +chmod +x "$CONFIG_LT" + +# configure is writing to config.log, but config.lt does its own redirection, +# appending to config.log, which fails on DOS, as config.log is still kept +# open by configure. Here we exec the FD to /dev/null, effectively closing +# config.log, so it can be properly (re)opened and appended to by config.lt. +if test "$no_create" != yes; then + lt_cl_success=: + test "$silent" = yes && + lt_config_lt_args="$lt_config_lt_args --quiet" + exec AS_MESSAGE_LOG_FD>/dev/null + $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false + exec AS_MESSAGE_LOG_FD>>config.log + $lt_cl_success || AS_EXIT(1) +fi +])# LT_OUTPUT + + +# _LT_CONFIG(TAG) +# --------------- +# If TAG is the built-in tag, create an initial libtool script with a +# default configuration from the untagged config vars. Otherwise add code +# to config.status for appending the configuration named by TAG from the +# matching tagged config vars. +m4_defun([_LT_CONFIG], +[m4_require([_LT_FILEUTILS_DEFAULTS])dnl +_LT_CONFIG_SAVE_COMMANDS([ + m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl + m4_if(_LT_TAG, [C], [ + # See if we are running on zsh, and set the options which allow our + # commands through without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + + cfgfile="${ofile}T" + trap "$RM \"$cfgfile\"; exit 1" 1 2 15 + $RM "$cfgfile" + + cat <<_LT_EOF >> "$cfgfile" +#! $SHELL + +# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. +# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: +# NOTE: Changes made to this file will be lost: look at ltmain.sh. +# +_LT_COPYING +_LT_LIBTOOL_TAGS + +# ### BEGIN LIBTOOL CONFIG +_LT_LIBTOOL_CONFIG_VARS +_LT_LIBTOOL_TAG_VARS +# ### END LIBTOOL CONFIG + +_LT_EOF + + case $host_os in + aix3*) + cat <<\_LT_EOF >> "$cfgfile" +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +_LT_EOF + ;; + esac + + _LT_PROG_LTMAIN + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + sed '/^# Generated shell functions inserted here/q' "$ltmain" >> "$cfgfile" \ + || (rm -f "$cfgfile"; exit 1) + + _LT_PROG_XSI_SHELLFNS + + sed -n '/^# Generated shell functions inserted here/,$p' "$ltmain" >> "$cfgfile" \ + || (rm -f "$cfgfile"; exit 1) + + mv -f "$cfgfile" "$ofile" || + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" +], +[cat <<_LT_EOF >> "$ofile" + +dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded +dnl in a comment (ie after a #). +# ### BEGIN LIBTOOL TAG CONFIG: $1 +_LT_LIBTOOL_TAG_VARS(_LT_TAG) +# ### END LIBTOOL TAG CONFIG: $1 +_LT_EOF +])dnl /m4_if +], +[m4_if([$1], [], [ + PACKAGE='$PACKAGE' + VERSION='$VERSION' + TIMESTAMP='$TIMESTAMP' + RM='$RM' + ofile='$ofile'], []) +])dnl /_LT_CONFIG_SAVE_COMMANDS +])# _LT_CONFIG + + +# LT_SUPPORTED_TAG(TAG) +# --------------------- +# Trace this macro to discover what tags are supported by the libtool +# --tag option, using: +# autoconf --trace 'LT_SUPPORTED_TAG:$1' +AC_DEFUN([LT_SUPPORTED_TAG], []) + + +# C support is built-in for now +m4_define([_LT_LANG_C_enabled], []) +m4_define([_LT_TAGS], []) + + +# LT_LANG(LANG) +# ------------- +# Enable libtool support for the given language if not already enabled. +AC_DEFUN([LT_LANG], +[AC_BEFORE([$0], [LT_OUTPUT])dnl +m4_case([$1], + [C], [_LT_LANG(C)], + [C++], [_LT_LANG(CXX)], + [Java], [_LT_LANG(GCJ)], + [Fortran 77], [_LT_LANG(F77)], + [Fortran], [_LT_LANG(FC)], + [Windows Resource], [_LT_LANG(RC)], + [m4_ifdef([_LT_LANG_]$1[_CONFIG], + [_LT_LANG($1)], + [m4_fatal([$0: unsupported language: "$1"])])])dnl +])# LT_LANG + + +# _LT_LANG(LANGNAME) +# ------------------ +m4_defun([_LT_LANG], +[m4_ifdef([_LT_LANG_]$1[_enabled], [], + [LT_SUPPORTED_TAG([$1])dnl + m4_append([_LT_TAGS], [$1 ])dnl + m4_define([_LT_LANG_]$1[_enabled], [])dnl + _LT_LANG_$1_CONFIG($1)])dnl +])# _LT_LANG + + +# _LT_LANG_DEFAULT_CONFIG +# ----------------------- +m4_defun([_LT_LANG_DEFAULT_CONFIG], +[AC_PROVIDE_IFELSE([AC_PROG_CXX], + [LT_LANG(CXX)], + [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])]) + +AC_PROVIDE_IFELSE([AC_PROG_F77], + [LT_LANG(F77)], + [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])]) + +AC_PROVIDE_IFELSE([AC_PROG_FC], + [LT_LANG(FC)], + [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])]) + +dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal +dnl pulling things in needlessly. +AC_PROVIDE_IFELSE([AC_PROG_GCJ], + [LT_LANG(GCJ)], + [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], + [LT_LANG(GCJ)], + [AC_PROVIDE_IFELSE([LT_PROG_GCJ], + [LT_LANG(GCJ)], + [m4_ifdef([AC_PROG_GCJ], + [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])]) + m4_ifdef([A][M_PROG_GCJ], + [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])]) + m4_ifdef([LT_PROG_GCJ], + [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])]) + +AC_PROVIDE_IFELSE([LT_PROG_RC], + [LT_LANG(RC)], + [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])]) +])# _LT_LANG_DEFAULT_CONFIG + +# Obsolete macros: +AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) +AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) +AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) +AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_CXX], []) +dnl AC_DEFUN([AC_LIBTOOL_F77], []) +dnl AC_DEFUN([AC_LIBTOOL_FC], []) +dnl AC_DEFUN([AC_LIBTOOL_GCJ], []) + + +# _LT_TAG_COMPILER +# ---------------- +m4_defun([_LT_TAG_COMPILER], +[AC_REQUIRE([AC_PROG_CC])dnl + +_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl +_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl +_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl +_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC +])# _LT_TAG_COMPILER + + +# _LT_COMPILER_BOILERPLATE +# ------------------------ +# Check for compiler boilerplate output or warnings with +# the simple compiler test code. +m4_defun([_LT_COMPILER_BOILERPLATE], +[m4_require([_LT_DECL_SED])dnl +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$RM conftest* +])# _LT_COMPILER_BOILERPLATE + + +# _LT_LINKER_BOILERPLATE +# ---------------------- +# Check for linker boilerplate output or warnings with +# the simple link test code. +m4_defun([_LT_LINKER_BOILERPLATE], +[m4_require([_LT_DECL_SED])dnl +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$RM -r conftest* +])# _LT_LINKER_BOILERPLATE + +# _LT_REQUIRED_DARWIN_CHECKS +# ------------------------- +m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ + case $host_os in + rhapsody* | darwin*) + AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:]) + AC_CHECK_TOOL([NMEDIT], [nmedit], [:]) + AC_CHECK_TOOL([LIPO], [lipo], [:]) + AC_CHECK_TOOL([OTOOL], [otool], [:]) + AC_CHECK_TOOL([OTOOL64], [otool64], [:]) + _LT_DECL([], [DSYMUTIL], [1], + [Tool to manipulate archived DWARF debug symbol files on Mac OS X]) + _LT_DECL([], [NMEDIT], [1], + [Tool to change global to local symbols on Mac OS X]) + _LT_DECL([], [LIPO], [1], + [Tool to manipulate fat objects and archives on Mac OS X]) + _LT_DECL([], [OTOOL], [1], + [ldd/readelf like tool for Mach-O binaries on Mac OS X]) + _LT_DECL([], [OTOOL64], [1], + [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4]) + + AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod], + [lt_cv_apple_cc_single_mod=no + if test -z "${LT_MULTI_MODULE}"; then + # By default we will add the -single_module flag. You can override + # by either setting the environment variable LT_MULTI_MODULE + # non-empty at configure time, or by adding -multi_module to the + # link flags. + rm -rf libconftest.dylib* + echo "int foo(void){return 1;}" > conftest.c + echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ +-dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD + $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ + -dynamiclib -Wl,-single_module conftest.c 2>conftest.err + _lt_result=$? + if test -f libconftest.dylib && test ! -s conftest.err && test $_lt_result = 0; then + lt_cv_apple_cc_single_mod=yes + else + cat conftest.err >&AS_MESSAGE_LOG_FD + fi + rm -rf libconftest.dylib* + rm -f conftest.* + fi]) + AC_CACHE_CHECK([for -exported_symbols_list linker flag], + [lt_cv_ld_exported_symbols_list], + [lt_cv_ld_exported_symbols_list=no + save_LDFLAGS=$LDFLAGS + echo "_main" > conftest.sym + LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" + AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], + [lt_cv_ld_exported_symbols_list=yes], + [lt_cv_ld_exported_symbols_list=no]) + LDFLAGS="$save_LDFLAGS" + ]) + case $host_os in + rhapsody* | darwin1.[[012]]) + _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; + darwin1.*) + _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; + darwin*) # darwin 5.x on + # if running on 10.5 or later, the deployment target defaults + # to the OS version, if on x86, and 10.4, the deployment + # target defaults to 10.4. Don't you love it? + case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in + 10.0,*86*-darwin8*|10.0,*-darwin[[91]]*) + _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; + 10.[[012]]*) + _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; + 10.*) + _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; + esac + ;; + esac + if test "$lt_cv_apple_cc_single_mod" = "yes"; then + _lt_dar_single_mod='$single_module' + fi + if test "$lt_cv_ld_exported_symbols_list" = "yes"; then + _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' + else + _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + if test "$DSYMUTIL" != ":"; then + _lt_dsymutil='~$DSYMUTIL $lib || :' + else + _lt_dsymutil= + fi + ;; + esac +]) + + +# _LT_DARWIN_LINKER_FEATURES +# -------------------------- +# Checks for linker and compiler features on darwin +m4_defun([_LT_DARWIN_LINKER_FEATURES], +[ + m4_require([_LT_REQUIRED_DARWIN_CHECKS]) + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_automatic, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_TAGVAR(whole_archive_flag_spec, $1)='' + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined" + case $cc_basename in + ifort*) _lt_dar_can_shared=yes ;; + *) _lt_dar_can_shared=$GCC ;; + esac + if test "$_lt_dar_can_shared" = "yes"; then + output_verbose_link_cmd=echo + _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" + _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" + _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" + _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" + m4_if([$1], [CXX], +[ if test "$lt_cv_apple_cc_single_mod" != "yes"; then + _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" + _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" + fi +],[]) + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi +]) + +# _LT_SYS_MODULE_PATH_AIX +# ----------------------- +# Links a minimal program and checks the executable +# for the system default hardcoded library path. In most cases, +# this is /usr/lib:/lib, but when the MPI compilers are used +# the location of the communication and MPI libs are included too. +# If we don't find anything, use the default library path according +# to the aix ld manual. +m4_defun([_LT_SYS_MODULE_PATH_AIX], +[m4_require([_LT_DECL_SED])dnl +AC_LINK_IFELSE(AC_LANG_PROGRAM,[ +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi],[]) +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi +])# _LT_SYS_MODULE_PATH_AIX + + +# _LT_SHELL_INIT(ARG) +# ------------------- +m4_define([_LT_SHELL_INIT], +[ifdef([AC_DIVERSION_NOTICE], + [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)], + [AC_DIVERT_PUSH(NOTICE)]) +$1 +AC_DIVERT_POP +])# _LT_SHELL_INIT + + +# _LT_PROG_ECHO_BACKSLASH +# ----------------------- +# Add some code to the start of the generated configure script which +# will find an echo command which doesn't interpret backslashes. +m4_defun([_LT_PROG_ECHO_BACKSLASH], +[_LT_SHELL_INIT([ +# Check that we are running under the correct shell. +SHELL=${CONFIG_SHELL-/bin/sh} + +case X$lt_ECHO in +X*--fallback-echo) + # Remove one level of quotation (which was required for Make). + ECHO=`echo "$lt_ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','` + ;; +esac + +ECHO=${lt_ECHO-echo} +if test "X[$]1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X[$]1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' ; then + # Yippee, $ECHO works! + : +else + # Restart under the correct shell. + exec $SHELL "[$]0" --no-reexec ${1+"[$]@"} +fi + +if test "X[$]1" = X--fallback-echo; then + # used as fallback echo + shift + cat <<_LT_EOF +[$]* +_LT_EOF + exit 0 +fi + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +if test -z "$lt_ECHO"; then + if test "X${echo_test_string+set}" != Xset; then + # find a string as large as possible, as long as the shell can cope with it + for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do + # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ... + if { echo_test_string=`eval $cmd`; } 2>/dev/null && + { test "X$echo_test_string" = "X$echo_test_string"; } 2>/dev/null + then + break + fi + done + fi + + if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' && + echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + : + else + # The Solaris, AIX, and Digital Unix default echo programs unquote + # backslashes. This makes it impossible to quote backslashes using + # echo "$something" | sed 's/\\/\\\\/g' + # + # So, first we look for a working echo in the user's PATH. + + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for dir in $PATH /usr/ucb; do + IFS="$lt_save_ifs" + if (test -f $dir/echo || test -f $dir/echo$ac_exeext) && + test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + ECHO="$dir/echo" + break + fi + done + IFS="$lt_save_ifs" + + if test "X$ECHO" = Xecho; then + # We didn't find a better echo, so look for alternatives. + if test "X`{ print -r '\t'; } 2>/dev/null`" = 'X\t' && + echo_testing_string=`{ print -r "$echo_test_string"; } 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # This shell has a builtin print -r that does the trick. + ECHO='print -r' + elif { test -f /bin/ksh || test -f /bin/ksh$ac_exeext; } && + test "X$CONFIG_SHELL" != X/bin/ksh; then + # If we have ksh, try running configure again with it. + ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} + export ORIGINAL_CONFIG_SHELL + CONFIG_SHELL=/bin/ksh + export CONFIG_SHELL + exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"} + else + # Try using printf. + ECHO='printf %s\n' + if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' && + echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # Cool, printf works + : + elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL + export CONFIG_SHELL + SHELL="$CONFIG_SHELL" + export SHELL + ECHO="$CONFIG_SHELL [$]0 --fallback-echo" + elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + ECHO="$CONFIG_SHELL [$]0 --fallback-echo" + else + # maybe with a smaller string... + prev=: + + for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do + if { test "X$echo_test_string" = "X`eval $cmd`"; } 2>/dev/null + then + break + fi + prev="$cmd" + done + + if test "$prev" != 'sed 50q "[$]0"'; then + echo_test_string=`eval $prev` + export echo_test_string + exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"} + else + # Oops. We lost completely, so just stick with echo. + ECHO=echo + fi + fi + fi + fi + fi +fi + +# Copy echo and quote the copy suitably for passing to libtool from +# the Makefile, instead of quoting the original, which is used later. +lt_ECHO=$ECHO +if test "X$lt_ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then + lt_ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo" +fi + +AC_SUBST(lt_ECHO) +]) +_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts]) +_LT_DECL([], [ECHO], [1], + [An echo program that does not interpret backslashes]) +])# _LT_PROG_ECHO_BACKSLASH + + +# _LT_ENABLE_LOCK +# --------------- +m4_defun([_LT_ENABLE_LOCK], +[AC_ARG_ENABLE([libtool-lock], + [AS_HELP_STRING([--disable-libtool-lock], + [avoid locking (might break parallel builds)])]) +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + +# Some flags need to be propagated to the compiler or linker for good +# libtool support. +case $host in +ia64-*-hpux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `/usr/bin/file conftest.$ac_objext` in + *ELF-32*) + HPUX_IA64_MODE="32" + ;; + *ELF-64*) + HPUX_IA64_MODE="64" + ;; + esac + fi + rm -rf conftest* + ;; +*-*-irix6*) + # Find out which ABI we are using. + echo '[#]line __oline__ "configure"' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + if test "$lt_cv_prog_gnu_ld" = yes; then + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -melf32bsmip" + ;; + *N32*) + LD="${LD-ld} -melf32bmipn32" + ;; + *64-bit*) + LD="${LD-ld} -melf64bmip" + ;; + esac + else + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -32" + ;; + *N32*) + LD="${LD-ld} -n32" + ;; + *64-bit*) + LD="${LD-ld} -64" + ;; + esac + fi + fi + rm -rf conftest* + ;; + +x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ +s390*-*linux*|s390*-*tpf*|sparc*-*linux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `/usr/bin/file conftest.o` in + *32-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_i386_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_i386" + ;; + ppc64-*linux*|powerpc64-*linux*) + LD="${LD-ld} -m elf32ppclinux" + ;; + s390x-*linux*) + LD="${LD-ld} -m elf_s390" + ;; + sparc64-*linux*) + LD="${LD-ld} -m elf32_sparc" + ;; + esac + ;; + *64-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_x86_64_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_x86_64" + ;; + ppc*-*linux*|powerpc*-*linux*) + LD="${LD-ld} -m elf64ppc" + ;; + s390*-*linux*|s390*-*tpf*) + LD="${LD-ld} -m elf64_s390" + ;; + sparc*-*linux*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +*-*-sco3.2v5*) + # On SCO OpenServer 5, we need -belf to get full-featured binaries. + SAVE_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS -belf" + AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, + [AC_LANG_PUSH(C) + AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) + AC_LANG_POP]) + if test x"$lt_cv_cc_needs_belf" != x"yes"; then + # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf + CFLAGS="$SAVE_CFLAGS" + fi + ;; +sparc*-*solaris*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `/usr/bin/file conftest.o` in + *64-bit*) + case $lt_cv_prog_gnu_ld in + yes*) LD="${LD-ld} -m elf64_sparc" ;; + *) + if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then + LD="${LD-ld} -64" + fi + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; +esac + +need_locks="$enable_libtool_lock" +])# _LT_ENABLE_LOCK + + +# _LT_CMD_OLD_ARCHIVE +# ------------------- +m4_defun([_LT_CMD_OLD_ARCHIVE], +[AC_CHECK_TOOL(AR, ar, false) +test -z "$AR" && AR=ar +test -z "$AR_FLAGS" && AR_FLAGS=cru +_LT_DECL([], [AR], [1], [The archiver]) +_LT_DECL([], [AR_FLAGS], [1]) + +AC_CHECK_TOOL(STRIP, strip, :) +test -z "$STRIP" && STRIP=: +_LT_DECL([], [STRIP], [1], [A symbol stripping program]) + +AC_CHECK_TOOL(RANLIB, ranlib, :) +test -z "$RANLIB" && RANLIB=: +_LT_DECL([], [RANLIB], [1], + [Commands used to install an old-style archive]) + +# Determine commands to create old-style static archives. +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' +old_postinstall_cmds='chmod 644 $oldlib' +old_postuninstall_cmds= + +if test -n "$RANLIB"; then + case $host_os in + openbsd*) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib" + ;; + *) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib" + ;; + esac + old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib" +fi +_LT_DECL([], [old_postinstall_cmds], [2]) +_LT_DECL([], [old_postuninstall_cmds], [2]) +_LT_TAGDECL([], [old_archive_cmds], [2], + [Commands used to build an old-style archive]) +])# _LT_CMD_OLD_ARCHIVE + + +# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, +# [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) +# ---------------------------------------------------------------- +# Check whether the given compiler option works +AC_DEFUN([_LT_COMPILER_OPTION], +[m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_SED])dnl +AC_CACHE_CHECK([$1], [$2], + [$2=no + m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$3" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&AS_MESSAGE_LOG_FD + echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + $2=yes + fi + fi + $RM conftest* +]) + +if test x"[$]$2" = xyes; then + m4_if([$5], , :, [$5]) +else + m4_if([$6], , :, [$6]) +fi +])# _LT_COMPILER_OPTION + +# Old name: +AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], []) + + +# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, +# [ACTION-SUCCESS], [ACTION-FAILURE]) +# ---------------------------------------------------- +# Check whether the given linker option works +AC_DEFUN([_LT_LINKER_OPTION], +[m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_SED])dnl +AC_CACHE_CHECK([$1], [$2], + [$2=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $3" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&AS_MESSAGE_LOG_FD + $ECHO "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + $2=yes + fi + else + $2=yes + fi + fi + $RM -r conftest* + LDFLAGS="$save_LDFLAGS" +]) + +if test x"[$]$2" = xyes; then + m4_if([$4], , :, [$4]) +else + m4_if([$5], , :, [$5]) +fi +])# _LT_LINKER_OPTION + +# Old name: +AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], []) + + +# LT_CMD_MAX_LEN +#--------------- +AC_DEFUN([LT_CMD_MAX_LEN], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +# find the maximum length of command line arguments +AC_MSG_CHECKING([the maximum length of command line arguments]) +AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl + i=0 + teststring="ABCD" + + case $build_os in + msdosdjgpp*) + # On DJGPP, this test can blow up pretty badly due to problems in libc + # (any single argument exceeding 2000 bytes causes a buffer overrun + # during glob expansion). Even if it were fixed, the result of this + # check would be larger than it should be. + lt_cv_sys_max_cmd_len=12288; # 12K is about right + ;; + + gnu*) + # Under GNU Hurd, this test is not required because there is + # no limit to the length of command line arguments. + # Libtool will interpret -1 as no limit whatsoever + lt_cv_sys_max_cmd_len=-1; + ;; + + cygwin* | mingw* | cegcc*) + # On Win9x/ME, this test blows up -- it succeeds, but takes + # about 5 minutes as the teststring grows exponentially. + # Worse, since 9x/ME are not pre-emptively multitasking, + # you end up with a "frozen" computer, even though with patience + # the test eventually succeeds (with a max line length of 256k). + # Instead, let's just punt: use the minimum linelength reported by + # all of the supported platforms: 8192 (on NT/2K/XP). + lt_cv_sys_max_cmd_len=8192; + ;; + + amigaos*) + # On AmigaOS with pdksh, this test takes hours, literally. + # So we just punt and use a minimum line length of 8192. + lt_cv_sys_max_cmd_len=8192; + ;; + + netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) + # This has been around since 386BSD, at least. Likely further. + if test -x /sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` + elif test -x /usr/sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` + else + lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs + fi + # And add a safety zone + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + ;; + + interix*) + # We know the value 262144 and hardcode it with a safety zone (like BSD) + lt_cv_sys_max_cmd_len=196608 + ;; + + osf*) + # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure + # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not + # nice to cause kernel panics so lets avoid the loop below. + # First set a reasonable default. + lt_cv_sys_max_cmd_len=16384 + # + if test -x /sbin/sysconfig; then + case `/sbin/sysconfig -q proc exec_disable_arg_limit` in + *1*) lt_cv_sys_max_cmd_len=-1 ;; + esac + fi + ;; + sco3.2v5*) + lt_cv_sys_max_cmd_len=102400 + ;; + sysv5* | sco5v6* | sysv4.2uw2*) + kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` + if test -n "$kargmax"; then + lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'` + else + lt_cv_sys_max_cmd_len=32768 + fi + ;; + *) + lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` + if test -n "$lt_cv_sys_max_cmd_len"; then + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + else + # Make teststring a little bigger before we do anything with it. + # a 1K string should be a reasonable start. + for i in 1 2 3 4 5 6 7 8 ; do + teststring=$teststring$teststring + done + SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} + # If test is not a shell built-in, we'll probably end up computing a + # maximum length that is only half of the actual maximum length, but + # we can't tell. + while { test "X"`$SHELL [$]0 --fallback-echo "X$teststring$teststring" 2>/dev/null` \ + = "XX$teststring$teststring"; } >/dev/null 2>&1 && + test $i != 17 # 1/2 MB should be enough + do + i=`expr $i + 1` + teststring=$teststring$teststring + done + # Only check the string length outside the loop. + lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` + teststring= + # Add a significant safety factor because C++ compilers can tack on + # massive amounts of additional arguments before passing them to the + # linker. It appears as though 1/2 is a usable value. + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` + fi + ;; + esac +]) +if test -n $lt_cv_sys_max_cmd_len ; then + AC_MSG_RESULT($lt_cv_sys_max_cmd_len) +else + AC_MSG_RESULT(none) +fi +max_cmd_len=$lt_cv_sys_max_cmd_len +_LT_DECL([], [max_cmd_len], [0], + [What is the maximum length of a command?]) +])# LT_CMD_MAX_LEN + +# Old name: +AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], []) + + +# _LT_HEADER_DLFCN +# ---------------- +m4_defun([_LT_HEADER_DLFCN], +[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl +])# _LT_HEADER_DLFCN + + +# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, +# ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) +# ---------------------------------------------------------------- +m4_defun([_LT_TRY_DLOPEN_SELF], +[m4_require([_LT_HEADER_DLFCN])dnl +if test "$cross_compiling" = yes; then : + [$4] +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext <<_LT_EOF +[#line __oline__ "configure" +#include "confdefs.h" + +#if HAVE_DLFCN_H +#include +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + else + puts (dlerror ()); + + return status; +}] +_LT_EOF + if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) $1 ;; + x$lt_dlneed_uscore) $2 ;; + x$lt_dlunknown|x*) $3 ;; + esac + else : + # compilation failed + $3 + fi +fi +rm -fr conftest* +])# _LT_TRY_DLOPEN_SELF + + +# LT_SYS_DLOPEN_SELF +# ------------------ +AC_DEFUN([LT_SYS_DLOPEN_SELF], +[m4_require([_LT_HEADER_DLFCN])dnl +if test "x$enable_dlopen" != xyes; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen="load_add_on" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32* | cegcc*) + lt_cv_dlopen="LoadLibrary" + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen="dlopen" + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + AC_CHECK_LIB([dl], [dlopen], + [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[ + lt_cv_dlopen="dyld" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ]) + ;; + + *) + AC_CHECK_FUNC([shl_load], + [lt_cv_dlopen="shl_load"], + [AC_CHECK_LIB([dld], [shl_load], + [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"], + [AC_CHECK_FUNC([dlopen], + [lt_cv_dlopen="dlopen"], + [AC_CHECK_LIB([dl], [dlopen], + [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"], + [AC_CHECK_LIB([svld], [dlopen], + [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"], + [AC_CHECK_LIB([dld], [dld_link], + [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"]) + ]) + ]) + ]) + ]) + ]) + ;; + esac + + if test "x$lt_cv_dlopen" != xno; then + enable_dlopen=yes + else + enable_dlopen=no + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS="$CPPFLAGS" + test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS="$LDFLAGS" + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS="$LIBS" + LIBS="$lt_cv_dlopen_libs $LIBS" + + AC_CACHE_CHECK([whether a program can dlopen itself], + lt_cv_dlopen_self, [dnl + _LT_TRY_DLOPEN_SELF( + lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, + lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) + ]) + + if test "x$lt_cv_dlopen_self" = xyes; then + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" + AC_CACHE_CHECK([whether a statically linked program can dlopen itself], + lt_cv_dlopen_self_static, [dnl + _LT_TRY_DLOPEN_SELF( + lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, + lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) + ]) + fi + + CPPFLAGS="$save_CPPFLAGS" + LDFLAGS="$save_LDFLAGS" + LIBS="$save_LIBS" + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi +_LT_DECL([dlopen_support], [enable_dlopen], [0], + [Whether dlopen is supported]) +_LT_DECL([dlopen_self], [enable_dlopen_self], [0], + [Whether dlopen of programs is supported]) +_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], + [Whether dlopen of statically linked programs is supported]) +])# LT_SYS_DLOPEN_SELF + +# Old name: +AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], []) + + +# _LT_COMPILER_C_O([TAGNAME]) +# --------------------------- +# Check to see if options -c and -o are simultaneously supported by compiler. +# This macro does not hard code the compiler like AC_PROG_CC_C_O. +m4_defun([_LT_COMPILER_C_O], +[m4_require([_LT_DECL_SED])dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_TAG_COMPILER])dnl +AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], + [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)], + [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&AS_MESSAGE_LOG_FD + echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes + fi + fi + chmod u+w . 2>&AS_MESSAGE_LOG_FD + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* +]) +_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1], + [Does compiler simultaneously support -c and -o options?]) +])# _LT_COMPILER_C_O + + +# _LT_COMPILER_FILE_LOCKS([TAGNAME]) +# ---------------------------------- +# Check to see if we can do hard links to lock some files if needed +m4_defun([_LT_COMPILER_FILE_LOCKS], +[m4_require([_LT_ENABLE_LOCK])dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +_LT_COMPILER_C_O([$1]) + +hard_links="nottested" +if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + AC_MSG_CHECKING([if we can lock with hard links]) + hard_links=yes + $RM conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + AC_MSG_RESULT([$hard_links]) + if test "$hard_links" = no; then + AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe]) + need_locks=warn + fi +else + need_locks=no +fi +_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?]) +])# _LT_COMPILER_FILE_LOCKS + + +# _LT_CHECK_OBJDIR +# ---------------- +m4_defun([_LT_CHECK_OBJDIR], +[AC_CACHE_CHECK([for objdir], [lt_cv_objdir], +[rm -f .libs 2>/dev/null +mkdir .libs 2>/dev/null +if test -d .libs; then + lt_cv_objdir=.libs +else + # MS-DOS does not allow filenames that begin with a dot. + lt_cv_objdir=_libs +fi +rmdir .libs 2>/dev/null]) +objdir=$lt_cv_objdir +_LT_DECL([], [objdir], [0], + [The name of the directory that contains temporary libtool files])dnl +m4_pattern_allow([LT_OBJDIR])dnl +AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/", + [Define to the sub-directory in which libtool stores uninstalled libraries.]) +])# _LT_CHECK_OBJDIR + + +# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME]) +# -------------------------------------- +# Check hardcoding attributes. +m4_defun([_LT_LINKER_HARDCODE_LIBPATH], +[AC_MSG_CHECKING([how to hardcode library paths into programs]) +_LT_TAGVAR(hardcode_action, $1)= +if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" || + test -n "$_LT_TAGVAR(runpath_var, $1)" || + test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then + + # We can hardcode non-existent directories. + if test "$_LT_TAGVAR(hardcode_direct, $1)" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no && + test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then + # Linking always hardcodes the temporary library directory. + _LT_TAGVAR(hardcode_action, $1)=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + _LT_TAGVAR(hardcode_action, $1)=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + _LT_TAGVAR(hardcode_action, $1)=unsupported +fi +AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)]) + +if test "$_LT_TAGVAR(hardcode_action, $1)" = relink || + test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi +_LT_TAGDECL([], [hardcode_action], [0], + [How to hardcode a shared library path into an executable]) +])# _LT_LINKER_HARDCODE_LIBPATH + + +# _LT_CMD_STRIPLIB +# ---------------- +m4_defun([_LT_CMD_STRIPLIB], +[m4_require([_LT_DECL_EGREP]) +striplib= +old_striplib= +AC_MSG_CHECKING([whether stripping libraries is possible]) +if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + AC_MSG_RESULT([yes]) +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + old_striplib="$STRIP -S" + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + ;; + *) + AC_MSG_RESULT([no]) + ;; + esac +fi +_LT_DECL([], [old_striplib], [1], [Commands to strip libraries]) +_LT_DECL([], [striplib], [1]) +])# _LT_CMD_STRIPLIB + + +# _LT_SYS_DYNAMIC_LINKER([TAG]) +# ----------------------------- +# PORTME Fill in your ld.so characteristics +m4_defun([_LT_SYS_DYNAMIC_LINKER], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +m4_require([_LT_DECL_EGREP])dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_OBJDUMP])dnl +m4_require([_LT_DECL_SED])dnl +AC_MSG_CHECKING([dynamic linker characteristics]) +m4_if([$1], + [], [ +if test "$GCC" = yes; then + case $host_os in + darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; + *) lt_awk_arg="/^libraries:/" ;; + esac + lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if $ECHO "$lt_search_path_spec" | $GREP ';' >/dev/null ; then + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e 's/;/ /g'` + else + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + # Ok, now we have the path, separated by spaces, we can step through it + # and add multilib dir if necessary. + lt_tmp_lt_search_path_spec= + lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` + for lt_sys_path in $lt_search_path_spec; do + if test -d "$lt_sys_path/$lt_multi_os_dir"; then + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" + else + test -d "$lt_sys_path" && \ + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" + fi + done + lt_search_path_spec=`$ECHO $lt_tmp_lt_search_path_spec | awk ' +BEGIN {RS=" "; FS="/|\n";} { + lt_foo=""; + lt_count=0; + for (lt_i = NF; lt_i > 0; lt_i--) { + if ($lt_i != "" && $lt_i != ".") { + if ($lt_i == "..") { + lt_count++; + } else { + if (lt_count == 0) { + lt_foo="/" $lt_i lt_foo; + } else { + lt_count--; + } + } + } + } + if (lt_foo != "") { lt_freq[[lt_foo]]++; } + if (lt_freq[[lt_foo]] == 1) { print lt_foo; } +}'` + sys_lib_search_path_spec=`$ECHO $lt_search_path_spec` +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi]) +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix[[4-9]]*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[[01]] | aix4.[[01]].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + case $host_cpu in + powerpc) + # Since July 2007 AmigaOS4 officially supports .so libraries. + # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + ;; + m68k) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$ECHO "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + esac + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[[45]]*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32* | cegcc*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32* | yes,cegcc*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw* | cegcc*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | $GREP "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' +m4_if([$1], [],[ + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +freebsd* | dragonfly*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[[123]]*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + # Handle Gentoo/FreeBSD as it was Linux + case $host_vendor in + gentoo) + version_type=linux ;; + *) + version_type=freebsd-$objformat ;; + esac + + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + linux) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + need_lib_prefix=no + need_version=no + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[[01]]* | freebsdelf3.[[01]]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ + freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +interix[[3-9]]*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # Some binutils ld are patched to set DT_RUNPATH + save_LDFLAGS=$LDFLAGS + save_libdir=$libdir + eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \ + LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\"" + AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], + [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null], + [shlibpath_overrides_runpath=yes])]) + LDFLAGS=$save_LDFLAGS + libdir=$save_libdir + + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +*nto* | *qnx*) + version_type=qnx + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='ldqnx.so' + ;; + +openbsd*) + version_type=sunos + sys_lib_dlsearch_path_spec="/usr/lib" + need_lib_prefix=no + # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. + case $host_os in + openbsd3.3 | openbsd3.3.*) need_version=yes ;; + *) need_version=no ;; + esac + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[[89]] | openbsd2.[[89]].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=freebsd-elf + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + if test "$with_gnu_ld" = yes; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +tpf*) + # TPF is a cross-target only. Preferred cross-host = GNU/Linux. + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +AC_MSG_RESULT([$dynamic_linker]) +test "$dynamic_linker" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then + sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" +fi +if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then + sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" +fi + +_LT_DECL([], [variables_saved_for_relink], [1], + [Variables whose values should be saved in libtool wrapper scripts and + restored at link time]) +_LT_DECL([], [need_lib_prefix], [0], + [Do we need the "lib" prefix for modules?]) +_LT_DECL([], [need_version], [0], [Do we need a version for libraries?]) +_LT_DECL([], [version_type], [0], [Library versioning type]) +_LT_DECL([], [runpath_var], [0], [Shared library runtime path variable]) +_LT_DECL([], [shlibpath_var], [0],[Shared library path variable]) +_LT_DECL([], [shlibpath_overrides_runpath], [0], + [Is shlibpath searched before the hard-coded library search path?]) +_LT_DECL([], [libname_spec], [1], [Format of library name prefix]) +_LT_DECL([], [library_names_spec], [1], + [[List of archive names. First name is the real one, the rest are links. + The last name is the one that the linker finds with -lNAME]]) +_LT_DECL([], [soname_spec], [1], + [[The coded name of the library, if different from the real name]]) +_LT_DECL([], [postinstall_cmds], [2], + [Command to use after installation of a shared archive]) +_LT_DECL([], [postuninstall_cmds], [2], + [Command to use after uninstallation of a shared archive]) +_LT_DECL([], [finish_cmds], [2], + [Commands used to finish a libtool library installation in a directory]) +_LT_DECL([], [finish_eval], [1], + [[As "finish_cmds", except a single script fragment to be evaled but + not shown]]) +_LT_DECL([], [hardcode_into_libs], [0], + [Whether we should hardcode library paths into libraries]) +_LT_DECL([], [sys_lib_search_path_spec], [2], + [Compile-time system search path for libraries]) +_LT_DECL([], [sys_lib_dlsearch_path_spec], [2], + [Run-time system search path for libraries]) +])# _LT_SYS_DYNAMIC_LINKER + + +# _LT_PATH_TOOL_PREFIX(TOOL) +# -------------------------- +# find a file program which can recognize shared library +AC_DEFUN([_LT_PATH_TOOL_PREFIX], +[m4_require([_LT_DECL_EGREP])dnl +AC_MSG_CHECKING([for $1]) +AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, +[case $MAGIC_CMD in +[[\\/*] | ?:[\\/]*]) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR +dnl $ac_dummy forces splitting on constant user-supplied paths. +dnl POSIX.2 word splitting is done only on the output of word expansions, +dnl not every word. This closes a longstanding sh security hole. + ac_dummy="m4_if([$2], , $PATH, [$2])" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/$1; then + lt_cv_path_MAGIC_CMD="$ac_dir/$1" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <<_LT_EOF 1>&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +_LT_EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac]) +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + AC_MSG_RESULT($MAGIC_CMD) +else + AC_MSG_RESULT(no) +fi +_LT_DECL([], [MAGIC_CMD], [0], + [Used to examine libraries when file_magic_cmd begins with "file"])dnl +])# _LT_PATH_TOOL_PREFIX + +# Old name: +AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], []) + + +# _LT_PATH_MAGIC +# -------------- +# find a file program which can recognize a shared library +m4_defun([_LT_PATH_MAGIC], +[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) +if test -z "$lt_cv_path_MAGIC_CMD"; then + if test -n "$ac_tool_prefix"; then + _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) + else + MAGIC_CMD=: + fi +fi +])# _LT_PATH_MAGIC + + +# LT_PATH_LD +# ---------- +# find the pathname to the GNU or non-GNU linker +AC_DEFUN([LT_PATH_LD], +[AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_CANONICAL_BUILD])dnl +m4_require([_LT_DECL_SED])dnl +m4_require([_LT_DECL_EGREP])dnl + +AC_ARG_WITH([gnu-ld], + [AS_HELP_STRING([--with-gnu-ld], + [assume the C compiler uses GNU ld @<:@default=no@:>@])], + [test "$withval" = no || with_gnu_ld=yes], + [with_gnu_ld=no])dnl + +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + AC_MSG_CHECKING([for ld used by $CC]) + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [[\\/]]* | ?:[[\\/]]*) + re_direlt='/[[^/]][[^/]]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` + while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do + ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + AC_MSG_CHECKING([for GNU ld]) +else + AC_MSG_CHECKING([for non-GNU ld]) +fi +AC_CACHE_VAL(lt_cv_path_LD, +[if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some variants of GNU ld only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &1 /dev/null 2>&1; then + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + else + lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + fi + ;; + +cegcc) + # use the weaker test based on 'objdump'. See mingw*. + lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + ;; + +darwin* | rhapsody*) + lt_cv_deplibs_check_method=pass_all + ;; + +freebsd* | dragonfly*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + case $host_cpu in + i*86 ) + # Not sure whether the presence of OpenBSD here was a mistake. + # Let's accept both of them until this is cleared up. + lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + ;; + esac + else + lt_cv_deplibs_check_method=pass_all + fi + ;; + +gnu*) + lt_cv_deplibs_check_method=pass_all + ;; + +hpux10.20* | hpux11*) + lt_cv_file_magic_cmd=/usr/bin/file + case $host_cpu in + ia64*) + lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' + lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so + ;; + hppa*64*) + [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]'] + lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl + ;; + *) + lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library' + lt_cv_file_magic_test_file=/usr/lib/libc.sl + ;; + esac + ;; + +interix[[3-9]]*) + # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' + ;; + +irix5* | irix6* | nonstopux*) + case $LD in + *-32|*"-32 ") libmagic=32-bit;; + *-n32|*"-n32 ") libmagic=N32;; + *-64|*"-64 ") libmagic=64-bit;; + *) libmagic=never-match;; + esac + lt_cv_deplibs_check_method=pass_all + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + lt_cv_deplibs_check_method=pass_all + ;; + +netbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' + fi + ;; + +newos6*) + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=/usr/lib/libnls.so + ;; + +*nto* | *qnx*) + lt_cv_deplibs_check_method=pass_all + ;; + +openbsd*) + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' + fi + ;; + +osf3* | osf4* | osf5*) + lt_cv_deplibs_check_method=pass_all + ;; + +rdos*) + lt_cv_deplibs_check_method=pass_all + ;; + +solaris*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv4 | sysv4.3*) + case $host_vendor in + motorola) + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` + ;; + ncr) + lt_cv_deplibs_check_method=pass_all + ;; + sequent) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' + ;; + sni) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" + lt_cv_file_magic_test_file=/lib/libc.so + ;; + siemens) + lt_cv_deplibs_check_method=pass_all + ;; + pc) + lt_cv_deplibs_check_method=pass_all + ;; + esac + ;; + +tpf*) + lt_cv_deplibs_check_method=pass_all + ;; +esac +]) +file_magic_cmd=$lt_cv_file_magic_cmd +deplibs_check_method=$lt_cv_deplibs_check_method +test -z "$deplibs_check_method" && deplibs_check_method=unknown + +_LT_DECL([], [deplibs_check_method], [1], + [Method to check whether dependent libraries are shared objects]) +_LT_DECL([], [file_magic_cmd], [1], + [Command to use when deplibs_check_method == "file_magic"]) +])# _LT_CHECK_MAGIC_METHOD + + +# LT_PATH_NM +# ---------- +# find the pathname to a BSD- or MS-compatible name lister +AC_DEFUN([LT_PATH_NM], +[AC_REQUIRE([AC_PROG_CC])dnl +AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, +[if test -n "$NM"; then + # Let the user override the test. + lt_cv_path_NM="$NM" +else + lt_nm_to_check="${ac_tool_prefix}nm" + if test -n "$ac_tool_prefix" && test "$build" = "$host"; then + lt_nm_to_check="$lt_nm_to_check nm" + fi + for lt_tmp_nm in $lt_nm_to_check; do + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + tmp_nm="$ac_dir/$lt_tmp_nm" + if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then + # Check to see if the nm accepts a BSD-compat flag. + # Adding the `sed 1q' prevents false positives on HP-UX, which says: + # nm: unknown option "B" ignored + # Tru64's nm complains that /dev/null is an invalid object file + case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in + */dev/null* | *'Invalid file or object type'*) + lt_cv_path_NM="$tmp_nm -B" + break + ;; + *) + case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in + */dev/null*) + lt_cv_path_NM="$tmp_nm -p" + break + ;; + *) + lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but + continue # so that we can try to find one that supports BSD flags + ;; + esac + ;; + esac + fi + done + IFS="$lt_save_ifs" + done + : ${lt_cv_path_NM=no} +fi]) +if test "$lt_cv_path_NM" != "no"; then + NM="$lt_cv_path_NM" +else + # Didn't find any BSD compatible name lister, look for dumpbin. + AC_CHECK_TOOLS(DUMPBIN, ["dumpbin -symbols" "link -dump -symbols"], :) + AC_SUBST([DUMPBIN]) + if test "$DUMPBIN" != ":"; then + NM="$DUMPBIN" + fi +fi +test -z "$NM" && NM=nm +AC_SUBST([NM]) +_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl + +AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], + [lt_cv_nm_interface="BSD nm" + echo "int some_variable = 0;" > conftest.$ac_ext + (eval echo "\"\$as_me:__oline__: $ac_compile\"" >&AS_MESSAGE_LOG_FD) + (eval "$ac_compile" 2>conftest.err) + cat conftest.err >&AS_MESSAGE_LOG_FD + (eval echo "\"\$as_me:__oline__: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) + (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) + cat conftest.err >&AS_MESSAGE_LOG_FD + (eval echo "\"\$as_me:__oline__: output\"" >&AS_MESSAGE_LOG_FD) + cat conftest.out >&AS_MESSAGE_LOG_FD + if $GREP 'External.*some_variable' conftest.out > /dev/null; then + lt_cv_nm_interface="MS dumpbin" + fi + rm -f conftest*]) +])# LT_PATH_NM + +# Old names: +AU_ALIAS([AM_PROG_NM], [LT_PATH_NM]) +AU_ALIAS([AC_PROG_NM], [LT_PATH_NM]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AM_PROG_NM], []) +dnl AC_DEFUN([AC_PROG_NM], []) + + +# LT_LIB_M +# -------- +# check for math library +AC_DEFUN([LT_LIB_M], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +LIBM= +case $host in +*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*) + # These system don't have libm, or don't need it + ;; +*-ncr-sysv4.3*) + AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw") + AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") + ;; +*) + AC_CHECK_LIB(m, cos, LIBM="-lm") + ;; +esac +AC_SUBST([LIBM]) +])# LT_LIB_M + +# Old name: +AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_CHECK_LIBM], []) + + +# _LT_COMPILER_NO_RTTI([TAGNAME]) +# ------------------------------- +m4_defun([_LT_COMPILER_NO_RTTI], +[m4_require([_LT_TAG_COMPILER])dnl + +_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= + +if test "$GCC" = yes; then + _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' + + _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], + lt_cv_prog_compiler_rtti_exceptions, + [-fno-rtti -fno-exceptions], [], + [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) +fi +_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1], + [Compiler flag to turn off builtin functions]) +])# _LT_COMPILER_NO_RTTI + + +# _LT_CMD_GLOBAL_SYMBOLS +# ---------------------- +m4_defun([_LT_CMD_GLOBAL_SYMBOLS], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +AC_REQUIRE([AC_PROG_CC])dnl +AC_REQUIRE([LT_PATH_NM])dnl +AC_REQUIRE([LT_PATH_LD])dnl +m4_require([_LT_DECL_SED])dnl +m4_require([_LT_DECL_EGREP])dnl +m4_require([_LT_TAG_COMPILER])dnl + +# Check for command to grab the raw symbol name followed by C symbol from nm. +AC_MSG_CHECKING([command to parse $NM output from $compiler object]) +AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], +[ +# These are sane defaults that work on at least a few old systems. +# [They come from Ultrix. What could be older than Ultrix?!! ;)] + +# Character class describing NM global symbol codes. +symcode='[[BCDEGRST]]' + +# Regexp to match symbols that can be accessed directly from C. +sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' + +# Define system-specific variables. +case $host_os in +aix*) + symcode='[[BCDT]]' + ;; +cygwin* | mingw* | pw32* | cegcc*) + symcode='[[ABCDGISTW]]' + ;; +hpux*) + if test "$host_cpu" = ia64; then + symcode='[[ABCDEGRST]]' + fi + ;; +irix* | nonstopux*) + symcode='[[BCDEGRST]]' + ;; +osf*) + symcode='[[BCDEGQRST]]' + ;; +solaris*) + symcode='[[BDRT]]' + ;; +sco3.2v5*) + symcode='[[DT]]' + ;; +sysv4.2uw2*) + symcode='[[DT]]' + ;; +sysv5* | sco5v6* | unixware* | OpenUNIX*) + symcode='[[ABDT]]' + ;; +sysv4) + symcode='[[DFNSTU]]' + ;; +esac + +# If we're using GNU nm, then use its standard symbol codes. +case `$NM -V 2>&1` in +*GNU* | *'with BFD'*) + symcode='[[ABCDGIRSTW]]' ;; +esac + +# Transform an extracted symbol line into a proper C declaration. +# Some systems (esp. on ia64) link data and code symbols differently, +# so use this general approach. +lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" + +# Transform an extracted symbol line into symbol name and symbol address +lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p'" +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"lib\2\", (void *) \&\2},/p'" + +# Handle CRLF in mingw tool chain +opt_cr= +case $build_os in +mingw*) + opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp + ;; +esac + +# Try without a prefix underscore, then with it. +for ac_symprfx in "" "_"; do + + # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. + symxfrm="\\1 $ac_symprfx\\2 \\2" + + # Write the raw and C identifiers. + if test "$lt_cv_nm_interface" = "MS dumpbin"; then + # Fake it for dumpbin and say T for any non-static function + # and D for any global variable. + # Also find C++ and __fastcall symbols from MSVC++, + # which start with @ or ?. + lt_cv_sys_global_symbol_pipe="$AWK ['"\ +" {last_section=section; section=\$ 3};"\ +" /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ +" \$ 0!~/External *\|/{next};"\ +" / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ +" {if(hide[section]) next};"\ +" {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ +" {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ +" s[1]~/^[@?]/{print s[1], s[1]; next};"\ +" s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ +" ' prfx=^$ac_symprfx]" + else + lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" + fi + + # Check to see that the pipe works correctly. + pipe_works=no + + rm -f conftest* + cat > conftest.$ac_ext <<_LT_EOF +#ifdef __cplusplus +extern "C" { +#endif +char nm_test_var; +void nm_test_func(void); +void nm_test_func(void){} +#ifdef __cplusplus +} +#endif +int main(){nm_test_var='a';nm_test_func();return(0);} +_LT_EOF + + if AC_TRY_EVAL(ac_compile); then + # Now try to grab the symbols. + nlist=conftest.nm + if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) && test -s "$nlist"; then + # Try sorting and uniquifying the output. + if sort "$nlist" | uniq > "$nlist"T; then + mv -f "$nlist"T "$nlist" + else + rm -f "$nlist"T + fi + + # Make sure that we snagged all the symbols we need. + if $GREP ' nm_test_var$' "$nlist" >/dev/null; then + if $GREP ' nm_test_func$' "$nlist" >/dev/null; then + cat <<_LT_EOF > conftest.$ac_ext +#ifdef __cplusplus +extern "C" { +#endif + +_LT_EOF + # Now generate the symbol file. + eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' + + cat <<_LT_EOF >> conftest.$ac_ext + +/* The mapping between symbol names and symbols. */ +const struct { + const char *name; + void *address; +} +lt__PROGRAM__LTX_preloaded_symbols[[]] = +{ + { "@PROGRAM@", (void *) 0 }, +_LT_EOF + $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext + cat <<\_LT_EOF >> conftest.$ac_ext + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt__PROGRAM__LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif +_LT_EOF + # Now try linking the two files. + mv conftest.$ac_objext conftstm.$ac_objext + lt_save_LIBS="$LIBS" + lt_save_CFLAGS="$CFLAGS" + LIBS="conftstm.$ac_objext" + CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" + if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then + pipe_works=yes + fi + LIBS="$lt_save_LIBS" + CFLAGS="$lt_save_CFLAGS" + else + echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD + fi + else + echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD + fi + else + echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD + fi + else + echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD + cat conftest.$ac_ext >&5 + fi + rm -rf conftest* conftst* + + # Do not use the global_symbol_pipe unless it works. + if test "$pipe_works" = yes; then + break + else + lt_cv_sys_global_symbol_pipe= + fi +done +]) +if test -z "$lt_cv_sys_global_symbol_pipe"; then + lt_cv_sys_global_symbol_to_cdecl= +fi +if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then + AC_MSG_RESULT(failed) +else + AC_MSG_RESULT(ok) +fi + +_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1], + [Take the output of nm and produce a listing of raw symbols and C names]) +_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1], + [Transform the output of nm in a proper C declaration]) +_LT_DECL([global_symbol_to_c_name_address], + [lt_cv_sys_global_symbol_to_c_name_address], [1], + [Transform the output of nm in a C name address pair]) +_LT_DECL([global_symbol_to_c_name_address_lib_prefix], + [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1], + [Transform the output of nm in a C name address pair when lib prefix is needed]) +]) # _LT_CMD_GLOBAL_SYMBOLS + + +# _LT_COMPILER_PIC([TAGNAME]) +# --------------------------- +m4_defun([_LT_COMPILER_PIC], +[m4_require([_LT_TAG_COMPILER])dnl +_LT_TAGVAR(lt_prog_compiler_wl, $1)= +_LT_TAGVAR(lt_prog_compiler_pic, $1)= +_LT_TAGVAR(lt_prog_compiler_static, $1)= + +AC_MSG_CHECKING([for $compiler option to produce PIC]) +m4_if([$1], [CXX], [ + # C++ specific cases for pic, static, wl, etc. + if test "$GXX" = yes; then + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + mingw* | cygwin* | os2* | pw32* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + m4_if([$1], [GCJ], [], + [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) + ;; + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' + ;; + *djgpp*) + # DJGPP does not support shared libraries at all + _LT_TAGVAR(lt_prog_compiler_pic, $1)= + ;; + interix[[3-9]]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + sysv4*MP*) + if test -d /usr/nec; then + _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic + fi + ;; + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + ;; + *qnx* | *nto*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + else + case $host_os in + aix[[4-9]]*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + else + _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' + fi + ;; + chorus*) + case $cc_basename in + cxch68*) + # Green Hills C++ Compiler + # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" + ;; + esac + ;; + dgux*) + case $cc_basename in + ec++*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + ;; + ghcx*) + # Green Hills C++ Compiler + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + *) + ;; + esac + ;; + freebsd* | dragonfly*) + # FreeBSD uses GNU C++ + ;; + hpux9* | hpux10* | hpux11*) + case $cc_basename in + CC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' + if test "$host_cpu" != ia64; then + _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + fi + ;; + aCC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + ;; + esac + ;; + *) + ;; + esac + ;; + interix*) + # This is c89, which is MS Visual C++ (no shared libs) + # Anyone wants to do a port? + ;; + irix5* | irix6* | nonstopux*) + case $cc_basename in + CC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + # CC pic flag -KPIC is the default. + ;; + *) + ;; + esac + ;; + linux* | k*bsd*-gnu) + case $cc_basename in + KCC*) + # KAI C++ Compiler + _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + ecpc* ) + # old Intel C++ for x86_64 which still supported -KPIC. + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + icpc* ) + # Intel C++, used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + pgCC* | pgcpp*) + # Portland Group C++ compiler + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + cxx*) + # Compaq C++ + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + _LT_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + xlc* | xlC*) + # IBM XL 8.0 on PPC + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + ;; + esac + ;; + esac + ;; + lynxos*) + ;; + m88k*) + ;; + mvs*) + case $cc_basename in + cxx*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' + ;; + *) + ;; + esac + ;; + netbsd*) + ;; + *qnx* | *nto*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' + ;; + osf3* | osf4* | osf5*) + case $cc_basename in + KCC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' + ;; + RCC*) + # Rational C++ 2.4.1 + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + cxx*) + # Digital/Compaq C++ + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + _LT_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + *) + ;; + esac + ;; + psos*) + ;; + solaris*) + case $cc_basename in + CC*) + # Sun C++ 4.2, 5.x and Centerline C++ + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + ;; + gcx*) + # Green Hills C++ Compiler + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + ;; + *) + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + lcc*) + # Lucid + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + ;; + *) + ;; + esac + ;; + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + case $cc_basename in + CC*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + ;; + *) + ;; + esac + ;; + vxworks*) + ;; + *) + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + esac + fi +], +[ + if test "$GCC" = yes; then + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + m4_if([$1], [GCJ], [], + [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' + ;; + + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + # +Z the default + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + ;; + + interix[[3-9]]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + enable_shared=no + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic + fi + ;; + + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + else + _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + m4_if([$1], [GCJ], [], + [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) + ;; + + hpux9* | hpux10* | hpux11*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # PIC (with -KPIC) is the default. + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + linux* | k*bsd*-gnu) + case $cc_basename in + # old Intel for x86_64 which still supported -KPIC. + ecc*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + # icc used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + icc* | ifort*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + # Lahey Fortran 8.1. + lf95*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared' + _LT_TAGVAR(lt_prog_compiler_static, $1)='--static' + ;; + pgcc* | pgf77* | pgf90* | pgf95*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + ccc*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # All Alpha code is PIC. + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + xl*) + # IBM XL C 8.0/Fortran 10.1 on PPC + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C 5.9 + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + ;; + *Sun\ F*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + _LT_TAGVAR(lt_prog_compiler_wl, $1)='' + ;; + esac + ;; + esac + ;; + + newsos6) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' + ;; + + osf3* | osf4* | osf5*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + # All OSF/1 code is PIC. + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + rdos*) + _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' + ;; + + solaris*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + case $cc_basename in + f77* | f90* | f95*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; + *) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; + esac + ;; + + sunos4*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + unicos*) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + + uts4*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' + ;; + + *) + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no + ;; + esac + fi +]) +case $host_os in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + _LT_TAGVAR(lt_prog_compiler_pic, $1)= + ;; + *) + _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])" + ;; +esac +AC_MSG_RESULT([$_LT_TAGVAR(lt_prog_compiler_pic, $1)]) +_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1], + [How to pass a linker flag through the compiler]) + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then + _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works], + [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)], + [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [], + [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in + "" | " "*) ;; + *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;; + esac], + [_LT_TAGVAR(lt_prog_compiler_pic, $1)= + _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) +fi +_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1], + [Additional compiler flags for building library objects]) + +# +# Check to make sure the static flag actually works. +# +wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\" +_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], + _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1), + $lt_tmp_static_flag, + [], + [_LT_TAGVAR(lt_prog_compiler_static, $1)=]) +_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1], + [Compiler flag to prevent dynamic linking]) +])# _LT_COMPILER_PIC + + +# _LT_LINKER_SHLIBS([TAGNAME]) +# ---------------------------- +# See if the linker supports building shared libraries. +m4_defun([_LT_LINKER_SHLIBS], +[AC_REQUIRE([LT_PATH_LD])dnl +AC_REQUIRE([LT_PATH_NM])dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_EGREP])dnl +m4_require([_LT_DECL_SED])dnl +m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl +m4_require([_LT_TAG_COMPILER])dnl +AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) +m4_if([$1], [CXX], [ + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + case $host_os in + aix[[4-9]]*) + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then + _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + else + _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + fi + ;; + pw32*) + _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds" + ;; + cygwin* | mingw* | cegcc*) + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;/^.*[[ ]]__nm__/s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' + ;; + *) + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + ;; + esac + _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] +], [ + runpath_var= + _LT_TAGVAR(allow_undefined_flag, $1)= + _LT_TAGVAR(always_export_symbols, $1)=no + _LT_TAGVAR(archive_cmds, $1)= + _LT_TAGVAR(archive_expsym_cmds, $1)= + _LT_TAGVAR(compiler_needs_object, $1)=no + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no + _LT_TAGVAR(export_dynamic_flag_spec, $1)= + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + _LT_TAGVAR(hardcode_automatic, $1)=no + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_direct_absolute, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= + _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= + _LT_TAGVAR(hardcode_libdir_separator, $1)= + _LT_TAGVAR(hardcode_minus_L, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported + _LT_TAGVAR(inherit_rpath, $1)=no + _LT_TAGVAR(link_all_deplibs, $1)=unknown + _LT_TAGVAR(module_cmds, $1)= + _LT_TAGVAR(module_expsym_cmds, $1)= + _LT_TAGVAR(old_archive_from_new_cmds, $1)= + _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)= + _LT_TAGVAR(thread_safe_flag_spec, $1)= + _LT_TAGVAR(whole_archive_flag_spec, $1)= + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + _LT_TAGVAR(include_expsyms, $1)= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + # Exclude shared library initialization/finalization symbols. +dnl Note also adjust exclude_expsyms for C++ above. + extract_expsyms_cmds= + + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++) + with_gnu_ld=yes + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + _LT_TAGVAR(ld_shlibs, $1)=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + runpath_var=LD_RUN_PATH + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then + _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + _LT_TAGVAR(whole_archive_flag_spec, $1)= + fi + supports_anon_versioning=no + case `$LD -v 2>&1` in + *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + + # See if GNU ld supports shared libraries. + case $host_os in + aix[[3-9]]*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + _LT_TAGVAR(ld_shlibs, $1)=no + cat <<_LT_EOF 1>&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +_LT_EOF + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='' + ;; + m68k) + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_minus_L, $1)=yes + ;; + esac + ;; + + beos*) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, + # as there is no search path for DLLs. + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_TAGVAR(always_export_symbols, $1)=no + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + interix[[3-9]]*) + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + + gnu* | linux* | tpf* | k*bsd*-gnu) + tmp_diet=no + if test "$host_os" = linux-dietlibc; then + case $cc_basename in + diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) + esac + fi + if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ + && test "$tmp_diet" = no + then + tmp_addflag= + tmp_sharedflag='-shared' + case $cc_basename,$host_cpu in + pgcc*) # Portland Group C compiler + _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag' + ;; + pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers + _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag -Mnomain' ;; + ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 + tmp_addflag=' -i_dynamic' ;; + efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 + tmp_addflag=' -i_dynamic -nofor_main' ;; + ifc* | ifort*) # Intel Fortran compiler + tmp_addflag=' -nofor_main' ;; + lf95*) # Lahey Fortran 8.1 + _LT_TAGVAR(whole_archive_flag_spec, $1)= + tmp_sharedflag='--shared' ;; + xl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below) + tmp_sharedflag='-qmkshrobj' + tmp_addflag= ;; + esac + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) # Sun C 5.9 + _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' + _LT_TAGVAR(compiler_needs_object, $1)=yes + tmp_sharedflag='-G' ;; + *Sun\ F*) # Sun Fortran 8.3 + tmp_sharedflag='-G' ;; + esac + _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + + if test "x$supports_anon_versioning" = xyes; then + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + fi + + case $cc_basename in + xlf*) + # IBM XL Fortran 10.1 on PPC cannot create shared libs itself + _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= + _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir' + _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $compiler_flags -soname $soname -o $lib' + if test "x$supports_anon_versioning" = xyes; then + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $LD -shared $libobjs $deplibs $compiler_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' + fi + ;; + esac + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris*) + if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then + _LT_TAGVAR(ld_shlibs, $1)=no + cat <<_LT_EOF 1>&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) + _LT_TAGVAR(ld_shlibs, $1)=no + cat <<_LT_EOF 1>&2 + +*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not +*** reliably create shared libraries on SCO systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.16.91.0.3 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + ;; + *) + # For security reasons, it is highly recommended that you always + # use absolute paths for naming shared libraries, and exclude the + # DT_RUNPATH tag from executables and libraries. But doing so + # requires that you compile everything twice, which is a pain. + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + + sunos4*) + _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + *) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + + if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then + runpath_var= + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= + _LT_TAGVAR(export_dynamic_flag_spec, $1)= + _LT_TAGVAR(whole_archive_flag_spec, $1)= + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_TAGVAR(always_export_symbols, $1)=yes + _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + _LT_TAGVAR(hardcode_minus_L, $1)=yes + if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + _LT_TAGVAR(hardcode_direct, $1)=unsupported + fi + ;; + + aix[[4-9]]*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then + _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + else + _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + _LT_TAGVAR(archive_cmds, $1)='' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' + + if test "$GCC" = yes; then + case $host_os in aix4.[[012]]|aix4.[[012]].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && + strings "$collect2name" | $GREP resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + _LT_TAGVAR(hardcode_direct, $1)=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)= + fi + ;; + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + _LT_TAGVAR(always_export_symbols, $1)=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + _LT_TAGVAR(allow_undefined_flag, $1)='-berok' + # Determine the default libpath from the value encoded in an + # empty executable. + _LT_SYS_MODULE_PATH_AIX + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' + _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" + _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an + # empty executable. + _LT_SYS_MODULE_PATH_AIX + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' + _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' + # Exported symbols can be pulled into shared objects from archives + _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' + _LT_TAGVAR(archive_cmds_need_lc, $1)=yes + # This is similar to how AIX traditionally builds its shared libraries. + _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='' + ;; + m68k) + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_minus_L, $1)=yes + ;; + esac + ;; + + bsdi[[45]]*) + _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `$ECHO "X$deplibs" | $Xsed -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' + # FIXME: Should let the user specify the lib program. + _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' + _LT_TAGVAR(fix_srcfile_path, $1)='`cygpath -w "$srcfile"`' + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + ;; + + darwin* | rhapsody*) + _LT_DARWIN_LINKER_FEATURES($1) + ;; + + dgux*) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + freebsd1*) + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | dragonfly*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + hpux9*) + if test "$GCC" = yes; then + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(hardcode_direct, $1)=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + ;; + + hpux10*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + fi + if test "$with_gnu_ld" = no; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_TAGVAR(hardcode_minus_L, $1)=yes + fi + ;; + + hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case $host_cpu in + hppa*64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case $host_cpu in + hppa*64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + case $host_cpu in + hppa*64*|ia64*) + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + *) + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + _LT_TAGVAR(hardcode_minus_L, $1)=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + # Try to use the -exported_symbol ld option, if it does not + # work, assume that -exports_file does not work either and + # implicitly export all symbols. + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" + AC_LINK_IFELSE(int foo(void) {}, + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' + ) + LDFLAGS="$save_LDFLAGS" + else + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' + fi + _LT_TAGVAR(archive_cmds_need_lc, $1)='no' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(inherit_rpath, $1)=yes + _LT_TAGVAR(link_all_deplibs, $1)=yes + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + newsos6) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + *nto* | *qnx*) + ;; + + openbsd*) + if test -f /usr/libexec/ld.so; then + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + else + case $host_os in + openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*) + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + ;; + esac + fi + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + os2*) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$ECHO DATA >> $output_objdir/$libname.def~$ECHO " SINGLE NONSHARED" >> $output_objdir/$libname.def~$ECHO EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' + fi + _LT_TAGVAR(archive_cmds_need_lc, $1)='no' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + else + _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ + $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' + + # Both c and cxx compiler support -rpath directly + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + fi + _LT_TAGVAR(archive_cmds_need_lc, $1)='no' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + ;; + + solaris*) + _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' + if test "$GCC" = yes; then + wlarc='${wl}' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + else + case `$CC -V 2>&1` in + *"Compilers 5.0"*) + wlarc='' + _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' + ;; + *) + wlarc='${wl}' + _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + ;; + esac + fi + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. GCC discards it without `$wl', + # but is careful enough not to reorder. + # Supported since Solaris 2.6 (maybe 2.5.1?) + if test "$GCC" = yes; then + _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + else + _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' + fi + ;; + esac + _LT_TAGVAR(link_all_deplibs, $1)=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + sysv4) + case $host_vendor in + sni) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' + _LT_TAGVAR(hardcode_direct, $1)=no + ;; + motorola) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + sysv4.3*) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + _LT_TAGVAR(ld_shlibs, $1)=yes + fi + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) + _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' + _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + uts4*) + _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + + *) + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + + if test x$host_vendor = xsni; then + case $host in + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym' + ;; + esac + fi + fi +]) +AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) +test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no + +_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld + +_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl +_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl +_LT_DECL([], [extract_expsyms_cmds], [2], + [The commands to extract the exported symbol list from a shared archive]) + +# +# Do we need to explicitly link libc? +# +case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in +x|xyes) + # Assume -lc should be added + _LT_TAGVAR(archive_cmds_need_lc, $1)=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $_LT_TAGVAR(archive_cmds, $1) in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + AC_MSG_CHECKING([whether -lc should be explicitly linked in]) + $RM conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if AC_TRY_EVAL(ac_compile) 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) + pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1) + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1) + _LT_TAGVAR(allow_undefined_flag, $1)= + if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) + then + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + else + _LT_TAGVAR(archive_cmds_need_lc, $1)=yes + fi + _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $RM conftest* + AC_MSG_RESULT([$_LT_TAGVAR(archive_cmds_need_lc, $1)]) + ;; + esac + fi + ;; +esac + +_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0], + [Whether or not to add -lc for building shared libraries]) +_LT_TAGDECL([allow_libtool_libs_with_static_runtimes], + [enable_shared_with_static_runtimes], [0], + [Whether or not to disallow shared libs when runtime libs are static]) +_LT_TAGDECL([], [export_dynamic_flag_spec], [1], + [Compiler flag to allow reflexive dlopens]) +_LT_TAGDECL([], [whole_archive_flag_spec], [1], + [Compiler flag to generate shared objects directly from archives]) +_LT_TAGDECL([], [compiler_needs_object], [1], + [Whether the compiler copes with passing no objects directly]) +_LT_TAGDECL([], [old_archive_from_new_cmds], [2], + [Create an old-style archive from a shared archive]) +_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2], + [Create a temporary old-style archive to link instead of a shared archive]) +_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive]) +_LT_TAGDECL([], [archive_expsym_cmds], [2]) +_LT_TAGDECL([], [module_cmds], [2], + [Commands used to build a loadable module if different from building + a shared archive.]) +_LT_TAGDECL([], [module_expsym_cmds], [2]) +_LT_TAGDECL([], [with_gnu_ld], [1], + [Whether we are building with GNU ld or not]) +_LT_TAGDECL([], [allow_undefined_flag], [1], + [Flag that allows shared libraries with undefined symbols to be built]) +_LT_TAGDECL([], [no_undefined_flag], [1], + [Flag that enforces no undefined symbols]) +_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1], + [Flag to hardcode $libdir into a binary during linking. + This must work even if $libdir does not exist]) +_LT_TAGDECL([], [hardcode_libdir_flag_spec_ld], [1], + [[If ld is used when linking, flag to hardcode $libdir into a binary + during linking. This must work even if $libdir does not exist]]) +_LT_TAGDECL([], [hardcode_libdir_separator], [1], + [Whether we need a single "-rpath" flag with a separated argument]) +_LT_TAGDECL([], [hardcode_direct], [0], + [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes + DIR into the resulting binary]) +_LT_TAGDECL([], [hardcode_direct_absolute], [0], + [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes + DIR into the resulting binary and the resulting library dependency is + "absolute", i.e impossible to change by setting ${shlibpath_var} if the + library is relocated]) +_LT_TAGDECL([], [hardcode_minus_L], [0], + [Set to "yes" if using the -LDIR flag during linking hardcodes DIR + into the resulting binary]) +_LT_TAGDECL([], [hardcode_shlibpath_var], [0], + [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR + into the resulting binary]) +_LT_TAGDECL([], [hardcode_automatic], [0], + [Set to "yes" if building a shared library automatically hardcodes DIR + into the library and all subsequent libraries and executables linked + against it]) +_LT_TAGDECL([], [inherit_rpath], [0], + [Set to yes if linker adds runtime paths of dependent libraries + to runtime path list]) +_LT_TAGDECL([], [link_all_deplibs], [0], + [Whether libtool must link a program against all its dependency libraries]) +_LT_TAGDECL([], [fix_srcfile_path], [1], + [Fix the shell variable $srcfile for the compiler]) +_LT_TAGDECL([], [always_export_symbols], [0], + [Set to "yes" if exported symbols are required]) +_LT_TAGDECL([], [export_symbols_cmds], [2], + [The commands to list exported symbols]) +_LT_TAGDECL([], [exclude_expsyms], [1], + [Symbols that should not be listed in the preloaded symbols]) +_LT_TAGDECL([], [include_expsyms], [1], + [Symbols that must always be exported]) +_LT_TAGDECL([], [prelink_cmds], [2], + [Commands necessary for linking programs (against libraries) with templates]) +_LT_TAGDECL([], [file_list_spec], [1], + [Specify filename containing input files]) +dnl FIXME: Not yet implemented +dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1], +dnl [Compiler flag to generate thread safe objects]) +])# _LT_LINKER_SHLIBS + + +# _LT_LANG_C_CONFIG([TAG]) +# ------------------------ +# Ensure that the configuration variables for a C compiler are suitably +# defined. These variables are subsequently used by _LT_CONFIG to write +# the compiler configuration to `libtool'. +m4_defun([_LT_LANG_C_CONFIG], +[m4_require([_LT_DECL_EGREP])dnl +lt_save_CC="$CC" +AC_LANG_PUSH(C) + +# Source file extension for C test sources. +ac_ext=c + +# Object file extension for compiled C test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(){return(0);}' + +_LT_TAG_COMPILER +# Save the default compiler, since it gets overwritten when the other +# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. +compiler_DEFAULT=$CC + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +if test -n "$compiler"; then + _LT_COMPILER_NO_RTTI($1) + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_SYS_DYNAMIC_LINKER($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + LT_SYS_DLOPEN_SELF + _LT_CMD_STRIPLIB + + # Report which library types will actually be built + AC_MSG_CHECKING([if libtool supports shared libraries]) + AC_MSG_RESULT([$can_build_shared]) + + AC_MSG_CHECKING([whether to build shared libraries]) + test "$can_build_shared" = "no" && enable_shared=no + + # On AIX, shared libraries and static libraries use the same namespace, and + # are all built from PIC. + case $host_os in + aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + + aix[[4-9]]*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; + esac + AC_MSG_RESULT([$enable_shared]) + + AC_MSG_CHECKING([whether to build static libraries]) + # Make sure either enable_shared or enable_static is yes. + test "$enable_shared" = yes || enable_static=yes + AC_MSG_RESULT([$enable_static]) + + _LT_CONFIG($1) +fi +AC_LANG_POP +CC="$lt_save_CC" +])# _LT_LANG_C_CONFIG + + +# _LT_PROG_CXX +# ------------ +# Since AC_PROG_CXX is broken, in that it returns g++ if there is no c++ +# compiler, we have our own version here. +m4_defun([_LT_PROG_CXX], +[ +pushdef([AC_MSG_ERROR], [_lt_caught_CXX_error=yes]) +AC_PROG_CXX +if test -n "$CXX" && ( test "X$CXX" != "Xno" && + ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || + (test "X$CXX" != "Xg++"))) ; then + AC_PROG_CXXCPP +else + _lt_caught_CXX_error=yes +fi +popdef([AC_MSG_ERROR]) +])# _LT_PROG_CXX + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([_LT_PROG_CXX], []) + + +# _LT_LANG_CXX_CONFIG([TAG]) +# -------------------------- +# Ensure that the configuration variables for a C++ compiler are suitably +# defined. These variables are subsequently used by _LT_CONFIG to write +# the compiler configuration to `libtool'. +m4_defun([_LT_LANG_CXX_CONFIG], +[AC_REQUIRE([_LT_PROG_CXX])dnl +m4_require([_LT_FILEUTILS_DEFAULTS])dnl +m4_require([_LT_DECL_EGREP])dnl + +AC_LANG_PUSH(C++) +_LT_TAGVAR(archive_cmds_need_lc, $1)=no +_LT_TAGVAR(allow_undefined_flag, $1)= +_LT_TAGVAR(always_export_symbols, $1)=no +_LT_TAGVAR(archive_expsym_cmds, $1)= +_LT_TAGVAR(compiler_needs_object, $1)=no +_LT_TAGVAR(export_dynamic_flag_spec, $1)= +_LT_TAGVAR(hardcode_direct, $1)=no +_LT_TAGVAR(hardcode_direct_absolute, $1)=no +_LT_TAGVAR(hardcode_libdir_flag_spec, $1)= +_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= +_LT_TAGVAR(hardcode_libdir_separator, $1)= +_LT_TAGVAR(hardcode_minus_L, $1)=no +_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported +_LT_TAGVAR(hardcode_automatic, $1)=no +_LT_TAGVAR(inherit_rpath, $1)=no +_LT_TAGVAR(module_cmds, $1)= +_LT_TAGVAR(module_expsym_cmds, $1)= +_LT_TAGVAR(link_all_deplibs, $1)=unknown +_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_TAGVAR(no_undefined_flag, $1)= +_LT_TAGVAR(whole_archive_flag_spec, $1)= +_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no + +# Source file extension for C++ test sources. +ac_ext=cpp + +# Object file extension for compiled C++ test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# No sense in running all these tests if we already determined that +# the CXX compiler isn't working. Some variables (like enable_shared) +# are currently assumed to apply to all compilers on this platform, +# and will be corrupted by setting them based on a non-working compiler. +if test "$_lt_caught_CXX_error" != yes; then + # Code to be used in simple compile tests + lt_simple_compile_test_code="int some_variable = 0;" + + # Code to be used in simple link tests + lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' + + # ltmain only uses $CC for tagged configurations so make sure $CC is set. + _LT_TAG_COMPILER + + # save warnings/boilerplate of simple test code + _LT_COMPILER_BOILERPLATE + _LT_LINKER_BOILERPLATE + + # Allow CC to be a program name with arguments. + lt_save_CC=$CC + lt_save_LD=$LD + lt_save_GCC=$GCC + GCC=$GXX + lt_save_with_gnu_ld=$with_gnu_ld + lt_save_path_LD=$lt_cv_path_LD + if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then + lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx + else + $as_unset lt_cv_prog_gnu_ld + fi + if test -n "${lt_cv_path_LDCXX+set}"; then + lt_cv_path_LD=$lt_cv_path_LDCXX + else + $as_unset lt_cv_path_LD + fi + test -z "${LDCXX+set}" || LD=$LDCXX + CC=${CXX-"c++"} + compiler=$CC + _LT_TAGVAR(compiler, $1)=$CC + _LT_CC_BASENAME([$compiler]) + + if test -n "$compiler"; then + # We don't want -fno-exception when compiling C++ code, so set the + # no_builtin_flag separately + if test "$GXX" = yes; then + _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' + else + _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= + fi + + if test "$GXX" = yes; then + # Set up default GNU C++ configuration + + LT_PATH_LD + + # Check if GNU C++ uses GNU ld as the underlying linker, since the + # archiving commands below assume that GNU ld is being used. + if test "$with_gnu_ld" = yes; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + + # If archive_cmds runs LD, not CC, wlarc should be empty + # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to + # investigate it a little bit more. (MM) + wlarc='${wl}' + + # ancient GNU ld didn't support --whole-archive et. al. + if eval "`$CC -print-prog-name=ld` --help 2>&1" | + $GREP 'no-whole-archive' > /dev/null; then + _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + _LT_TAGVAR(whole_archive_flag_spec, $1)= + fi + else + with_gnu_ld=no + wlarc= + + # A generic and very simple default shared library creation + # command for GNU C++ for the case where it uses the native + # linker, instead of GNU ld. If possible, this setting should + # overridden to take advantage of the native linker features on + # the platform it is being used on. + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + fi + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"' + + else + GXX=no + with_gnu_ld=no + wlarc= + fi + + # PORTME: fill in a description of your system's C++ link characteristics + AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) + _LT_TAGVAR(ld_shlibs, $1)=yes + case $host_os in + aix3*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + aix[[4-9]]*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) + for ld_flag in $LDFLAGS; do + case $ld_flag in + *-brtl*) + aix_use_runtimelinking=yes + break + ;; + esac + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + _LT_TAGVAR(archive_cmds, $1)='' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' + + if test "$GXX" = yes; then + case $host_os in aix4.[[012]]|aix4.[[012]].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && + strings "$collect2name" | $GREP resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + _LT_TAGVAR(hardcode_direct, $1)=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + _LT_TAGVAR(hardcode_minus_L, $1)=yes + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)= + fi + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to + # export. + _LT_TAGVAR(always_export_symbols, $1)=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + _LT_TAGVAR(allow_undefined_flag, $1)='-berok' + # Determine the default libpath from the value encoded in an empty + # executable. + _LT_SYS_MODULE_PATH_AIX + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' + _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" + _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an + # empty executable. + _LT_SYS_MODULE_PATH_AIX + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' + _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' + # Exported symbols can be pulled into shared objects from archives + _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' + _LT_TAGVAR(archive_cmds_need_lc, $1)=yes + # This is similar to how AIX traditionally builds its shared + # libraries. + _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + beos*) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + chorus*) + case $cc_basename in + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, + # as there is no search path for DLLs. + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + _LT_TAGVAR(allow_undefined_flag, $1)=unsupported + _LT_TAGVAR(always_export_symbols, $1)=no + _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + + if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + darwin* | rhapsody*) + _LT_DARWIN_LINKER_FEATURES($1) + ;; + + dgux*) + case $cc_basename in + ec++*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + ghcx*) + # Green Hills C++ Compiler + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + freebsd[[12]]*) + # C++ shared libraries reported to be fairly broken before + # switch to ELF + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + freebsd-elf*) + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + ;; + + freebsd* | dragonfly*) + # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF + # conventions + _LT_TAGVAR(ld_shlibs, $1)=yes + ;; + + gnu*) + ;; + + hpux9*) + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, + # but as the default + # location of the library. + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + aCC*) + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' + ;; + *) + if test "$GXX" = yes; then + _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + + hpux10*|hpux11*) + if test $with_gnu_ld = no; then + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + case $host_cpu in + hppa*64*|ia64*) + ;; + *) + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + ;; + esac + fi + case $host_cpu in + hppa*64*|ia64*) + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + ;; + *) + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, + # but as the default + # location of the library. + ;; + esac + + case $cc_basename in + CC*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + aCC*) + case $host_cpu in + hppa*64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' + ;; + *) + if test "$GXX" = yes; then + if test $with_gnu_ld = no; then + case $host_cpu in + hppa*64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + ia64*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + ;; + esac + fi + else + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + + interix[[3-9]]*) + _LT_TAGVAR(hardcode_direct, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + irix5* | irix6*) + case $cc_basename in + CC*) + # SGI C++ + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' + + # Archives containing C++ object files must be created using + # "CC -ar", where "CC" is the IRIX C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' + ;; + *) + if test "$GXX" = yes; then + if test "$with_gnu_ld" = no; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` -o $lib' + fi + fi + _LT_TAGVAR(link_all_deplibs, $1)=yes + ;; + esac + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + _LT_TAGVAR(inherit_rpath, $1)=yes + ;; + + linux* | k*bsd*-gnu) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + + # Archives containing C++ object files must be created using + # "CC -Bstatic", where "CC" is the KAI C++ compiler. + _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' + ;; + icpc* | ecpc* ) + # Intel C++ + with_gnu_ld=yes + # version 8.0 and above of icpc choke on multiply defined symbols + # if we add $predep_objects and $postdep_objects, however 7.1 and + # earlier do not add the objects themselves. + case `$CC -V 2>&1` in + *"Version 7."*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + ;; + *) # Version 8.0 or newer + tmp_idyn= + case $host_cpu in + ia64*) tmp_idyn=' -i_dynamic';; + esac + _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + ;; + esac + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' + ;; + pgCC* | pgcpp*) + # Portland Group C++ compiler + case `$CC -V` in + *pgCC\ [[1-5]]* | *pgcpp\ [[1-5]]*) + _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ + compile_command="$compile_command `find $tpldir -name \*.o | $NL2SP`"' + _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ + $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | $NL2SP`~ + $RANLIB $oldlib' + _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ + $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~ + rm -rf $tpldir~ + $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ + $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' + ;; + *) # Version 6 will use weak symbols + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' + ;; + esac + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' + ;; + cxx*) + # Compaq C++ + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' + + runpath_var=LD_RUN_PATH + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' + ;; + xl*) + # IBM XL 8.0 on PPC, with GNU ld + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' + _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + if test "x$supports_anon_versioning" = xyes; then + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + fi + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' + _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' + _LT_TAGVAR(compiler_needs_object, $1)=yes + + # Not sure whether something based on + # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 + # would be better. + output_verbose_link_cmd='echo' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' + ;; + esac + ;; + esac + ;; + + lynxos*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + m88k*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + mvs*) + case $cc_basename in + cxx*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' + wlarc= + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + fi + # Workaround some broken pre-1.5 toolchains + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' + ;; + + *nto* | *qnx*) + _LT_TAGVAR(ld_shlibs, $1)=yes + ;; + + openbsd2*) + # C++ shared libraries are fairly broken + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + openbsd*) + if test -f /usr/libexec/ld.so; then + _LT_TAGVAR(hardcode_direct, $1)=yes + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_direct_absolute, $1)=yes + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' + _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + fi + output_verbose_link_cmd=echo + else + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + + osf3* | osf4* | osf5*) + case $cc_basename in + KCC*) + # Kuck and Associates, Inc. (KAI) C++ Compiler + + # KCC will only create a shared library if the output file + # ends with ".so" (or ".sl" for HP-UX), so rename the library + # to its proper name (with version) after linking. + _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + # Archives containing C++ object files must be created using + # the KAI C++ compiler. + case $host in + osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; + *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;; + esac + ;; + RCC*) + # Rational C++ 2.4.1 + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + cxx*) + case $host in + osf3*) + _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && $ECHO "X${wl}-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + ;; + *) + _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' + _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ + echo "-hidden">> $lib.exp~ + $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~ + $RM $lib.exp' + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' + ;; + esac + + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + # + # There doesn't appear to be a way to prevent this compiler from + # explicitly linking system object files so we need to strip them + # from the output so that they don't get included in the library + # dependencies. + output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' + ;; + *) + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' + case $host in + osf3*) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + ;; + esac + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=: + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"' + + else + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + fi + ;; + esac + ;; + + psos*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + lcc*) + # Lucid + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + solaris*) + case $cc_basename in + CC*) + # Sun C++ 4.2, 5.x and Centerline C++ + _LT_TAGVAR(archive_cmds_need_lc,$1)=yes + _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' + _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. + # Supported since Solaris 2.6 (maybe 2.5.1?) + _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' + ;; + esac + _LT_TAGVAR(link_all_deplibs, $1)=yes + + output_verbose_link_cmd='echo' + + # Archives containing C++ object files must be created using + # "CC -xar", where "CC" is the Sun C++ compiler. This is + # necessary to make sure instantiated templates are included + # in the archive. + _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' + ;; + gcx*) + # Green Hills C++ Compiler + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + + # The C++ compiler must be used to create the archive. + _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' + ;; + *) + # GNU C++ compiler with Solaris linker + if test "$GXX" = yes && test "$with_gnu_ld" = no; then + _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs' + if $CC --version | $GREP -v '^2\.7' > /dev/null; then + _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"' + else + # g++ 2.7 appears to require `-G' NOT `-shared' on this + # platform. + _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' + + # Commands to make compiler produce verbose output that lists + # what "hidden" libraries, object files and flags are used when + # linking a shared library. + output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"' + fi + + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir' + case $host_os in + solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; + *) + _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + ;; + esac + fi + ;; + esac + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) + _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' + _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(hardcode_shlibpath_var, $1)=no + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' + _LT_TAGVAR(hardcode_libdir_separator, $1)=':' + _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + case $cc_basename in + CC*) + _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + ;; + + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + ;; + + vxworks*) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + + *) + # FIXME: insert proper C++ library support + _LT_TAGVAR(ld_shlibs, $1)=no + ;; + esac + + AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) + test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no + + _LT_TAGVAR(GCC, $1)="$GXX" + _LT_TAGVAR(LD, $1)="$LD" + + ## CAVEAT EMPTOR: + ## There is no encapsulation within the following macros, do not change + ## the running order or otherwise move them around unless you know exactly + ## what you are doing... + _LT_SYS_HIDDEN_LIBDEPS($1) + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_SYS_DYNAMIC_LINKER($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + + _LT_CONFIG($1) + fi # test -n "$compiler" + + CC=$lt_save_CC + LDCXX=$LD + LD=$lt_save_LD + GCC=$lt_save_GCC + with_gnu_ld=$lt_save_with_gnu_ld + lt_cv_path_LDCXX=$lt_cv_path_LD + lt_cv_path_LD=$lt_save_path_LD + lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld + lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld +fi # test "$_lt_caught_CXX_error" != yes + +AC_LANG_POP +])# _LT_LANG_CXX_CONFIG + + +# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME]) +# --------------------------------- +# Figure out "hidden" library dependencies from verbose +# compiler output when linking a shared library. +# Parse the compiler output and extract the necessary +# objects, libraries and library flags. +m4_defun([_LT_SYS_HIDDEN_LIBDEPS], +[m4_require([_LT_FILEUTILS_DEFAULTS])dnl +# Dependencies to place before and after the object being linked: +_LT_TAGVAR(predep_objects, $1)= +_LT_TAGVAR(postdep_objects, $1)= +_LT_TAGVAR(predeps, $1)= +_LT_TAGVAR(postdeps, $1)= +_LT_TAGVAR(compiler_lib_search_path, $1)= + +dnl we can't use the lt_simple_compile_test_code here, +dnl because it contains code intended for an executable, +dnl not a library. It's possible we should let each +dnl tag define a new lt_????_link_test_code variable, +dnl but it's only used here... +m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF +int a; +void foo (void) { a = 0; } +_LT_EOF +], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF +class Foo +{ +public: + Foo (void) { a = 0; } +private: + int a; +}; +_LT_EOF +], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF + subroutine foo + implicit none + integer*4 a + a=0 + return + end +_LT_EOF +], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF + subroutine foo + implicit none + integer a + a=0 + return + end +_LT_EOF +], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF +public class foo { + private int a; + public void bar (void) { + a = 0; + } +}; +_LT_EOF +]) +dnl Parse the compiler output and extract the necessary +dnl objects, libraries and library flags. +if AC_TRY_EVAL(ac_compile); then + # Parse the compiler output and extract the necessary + # objects, libraries and library flags. + + # Sentinel used to keep track of whether or not we are before + # the conftest object file. + pre_test_object_deps_done=no + + for p in `eval "$output_verbose_link_cmd"`; do + case $p in + + -L* | -R* | -l*) + # Some compilers place space between "-{L,R}" and the path. + # Remove the space. + if test $p = "-L" || + test $p = "-R"; then + prev=$p + continue + else + prev= + fi + + if test "$pre_test_object_deps_done" = no; then + case $p in + -L* | -R*) + # Internal compiler library paths should come after those + # provided the user. The postdeps already come after the + # user supplied libs so there is no need to process them. + if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then + _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}" + else + _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}" + fi + ;; + # The "-l" case would never come before the object being + # linked, so don't bother handling this case. + esac + else + if test -z "$_LT_TAGVAR(postdeps, $1)"; then + _LT_TAGVAR(postdeps, $1)="${prev}${p}" + else + _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}" + fi + fi + ;; + + *.$objext) + # This assumes that the test object file only shows up + # once in the compiler output. + if test "$p" = "conftest.$objext"; then + pre_test_object_deps_done=yes + continue + fi + + if test "$pre_test_object_deps_done" = no; then + if test -z "$_LT_TAGVAR(predep_objects, $1)"; then + _LT_TAGVAR(predep_objects, $1)="$p" + else + _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p" + fi + else + if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then + _LT_TAGVAR(postdep_objects, $1)="$p" + else + _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p" + fi + fi + ;; + + *) ;; # Ignore the rest. + + esac + done + + # Clean up. + rm -f a.out a.exe +else + echo "libtool.m4: error: problem compiling $1 test program" +fi + +$RM -f confest.$objext + +# PORTME: override above test on systems where it is broken +m4_if([$1], [CXX], +[case $host_os in +interix[[3-9]]*) + # Interix 3.5 installs completely hosed .la files for C++, so rather than + # hack all around it, let's just trust "g++" to DTRT. + _LT_TAGVAR(predep_objects,$1)= + _LT_TAGVAR(postdep_objects,$1)= + _LT_TAGVAR(postdeps,$1)= + ;; + +linux*) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C++ 5.9 + + # The more standards-conforming stlport4 library is + # incompatible with the Cstd library. Avoid specifying + # it if it's in CXXFLAGS. Ignore libCrun as + # -library=stlport4 depends on it. + case " $CXX $CXXFLAGS " in + *" -library=stlport4 "*) + solaris_use_stlport4=yes + ;; + esac + + if test "$solaris_use_stlport4" != yes; then + _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' + fi + ;; + esac + ;; + +solaris*) + case $cc_basename in + CC*) + # The more standards-conforming stlport4 library is + # incompatible with the Cstd library. Avoid specifying + # it if it's in CXXFLAGS. Ignore libCrun as + # -library=stlport4 depends on it. + case " $CXX $CXXFLAGS " in + *" -library=stlport4 "*) + solaris_use_stlport4=yes + ;; + esac + + # Adding this requires a known-good setup of shared libraries for + # Sun compiler versions before 5.6, else PIC objects from an old + # archive will be linked into the output, leading to subtle bugs. + if test "$solaris_use_stlport4" != yes; then + _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' + fi + ;; + esac + ;; +esac +]) + +case " $_LT_TAGVAR(postdeps, $1) " in +*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; +esac + _LT_TAGVAR(compiler_lib_search_dirs, $1)= +if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then + _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` +fi +_LT_TAGDECL([], [compiler_lib_search_dirs], [1], + [The directories searched by this compiler when creating a shared library]) +_LT_TAGDECL([], [predep_objects], [1], + [Dependencies to place before and after the objects being linked to + create a shared library]) +_LT_TAGDECL([], [postdep_objects], [1]) +_LT_TAGDECL([], [predeps], [1]) +_LT_TAGDECL([], [postdeps], [1]) +_LT_TAGDECL([], [compiler_lib_search_path], [1], + [The library search path used internally by the compiler when linking + a shared library]) +])# _LT_SYS_HIDDEN_LIBDEPS + + +# _LT_PROG_F77 +# ------------ +# Since AC_PROG_F77 is broken, in that it returns the empty string +# if there is no fortran compiler, we have our own version here. +m4_defun([_LT_PROG_F77], +[ +pushdef([AC_MSG_ERROR], [_lt_disable_F77=yes]) +AC_PROG_F77 +if test -z "$F77" || test "X$F77" = "Xno"; then + _lt_disable_F77=yes +fi +popdef([AC_MSG_ERROR]) +])# _LT_PROG_F77 + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([_LT_PROG_F77], []) + + +# _LT_LANG_F77_CONFIG([TAG]) +# -------------------------- +# Ensure that the configuration variables for a Fortran 77 compiler are +# suitably defined. These variables are subsequently used by _LT_CONFIG +# to write the compiler configuration to `libtool'. +m4_defun([_LT_LANG_F77_CONFIG], +[AC_REQUIRE([_LT_PROG_F77])dnl +AC_LANG_PUSH(Fortran 77) + +_LT_TAGVAR(archive_cmds_need_lc, $1)=no +_LT_TAGVAR(allow_undefined_flag, $1)= +_LT_TAGVAR(always_export_symbols, $1)=no +_LT_TAGVAR(archive_expsym_cmds, $1)= +_LT_TAGVAR(export_dynamic_flag_spec, $1)= +_LT_TAGVAR(hardcode_direct, $1)=no +_LT_TAGVAR(hardcode_direct_absolute, $1)=no +_LT_TAGVAR(hardcode_libdir_flag_spec, $1)= +_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= +_LT_TAGVAR(hardcode_libdir_separator, $1)= +_LT_TAGVAR(hardcode_minus_L, $1)=no +_LT_TAGVAR(hardcode_automatic, $1)=no +_LT_TAGVAR(inherit_rpath, $1)=no +_LT_TAGVAR(module_cmds, $1)= +_LT_TAGVAR(module_expsym_cmds, $1)= +_LT_TAGVAR(link_all_deplibs, $1)=unknown +_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_TAGVAR(no_undefined_flag, $1)= +_LT_TAGVAR(whole_archive_flag_spec, $1)= +_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no + +# Source file extension for f77 test sources. +ac_ext=f + +# Object file extension for compiled f77 test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# No sense in running all these tests if we already determined that +# the F77 compiler isn't working. Some variables (like enable_shared) +# are currently assumed to apply to all compilers on this platform, +# and will be corrupted by setting them based on a non-working compiler. +if test "$_lt_disable_F77" != yes; then + # Code to be used in simple compile tests + lt_simple_compile_test_code="\ + subroutine t + return + end +" + + # Code to be used in simple link tests + lt_simple_link_test_code="\ + program t + end +" + + # ltmain only uses $CC for tagged configurations so make sure $CC is set. + _LT_TAG_COMPILER + + # save warnings/boilerplate of simple test code + _LT_COMPILER_BOILERPLATE + _LT_LINKER_BOILERPLATE + + # Allow CC to be a program name with arguments. + lt_save_CC="$CC" + lt_save_GCC=$GCC + CC=${F77-"f77"} + compiler=$CC + _LT_TAGVAR(compiler, $1)=$CC + _LT_CC_BASENAME([$compiler]) + GCC=$G77 + if test -n "$compiler"; then + AC_MSG_CHECKING([if libtool supports shared libraries]) + AC_MSG_RESULT([$can_build_shared]) + + AC_MSG_CHECKING([whether to build shared libraries]) + test "$can_build_shared" = "no" && enable_shared=no + + # On AIX, shared libraries and static libraries use the same namespace, and + # are all built from PIC. + case $host_os in + aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + aix[[4-9]]*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; + esac + AC_MSG_RESULT([$enable_shared]) + + AC_MSG_CHECKING([whether to build static libraries]) + # Make sure either enable_shared or enable_static is yes. + test "$enable_shared" = yes || enable_static=yes + AC_MSG_RESULT([$enable_static]) + + _LT_TAGVAR(GCC, $1)="$G77" + _LT_TAGVAR(LD, $1)="$LD" + + ## CAVEAT EMPTOR: + ## There is no encapsulation within the following macros, do not change + ## the running order or otherwise move them around unless you know exactly + ## what you are doing... + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_SYS_DYNAMIC_LINKER($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + + _LT_CONFIG($1) + fi # test -n "$compiler" + + GCC=$lt_save_GCC + CC="$lt_save_CC" +fi # test "$_lt_disable_F77" != yes + +AC_LANG_POP +])# _LT_LANG_F77_CONFIG + + +# _LT_PROG_FC +# ----------- +# Since AC_PROG_FC is broken, in that it returns the empty string +# if there is no fortran compiler, we have our own version here. +m4_defun([_LT_PROG_FC], +[ +pushdef([AC_MSG_ERROR], [_lt_disable_FC=yes]) +AC_PROG_FC +if test -z "$FC" || test "X$FC" = "Xno"; then + _lt_disable_FC=yes +fi +popdef([AC_MSG_ERROR]) +])# _LT_PROG_FC + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([_LT_PROG_FC], []) + + +# _LT_LANG_FC_CONFIG([TAG]) +# ------------------------- +# Ensure that the configuration variables for a Fortran compiler are +# suitably defined. These variables are subsequently used by _LT_CONFIG +# to write the compiler configuration to `libtool'. +m4_defun([_LT_LANG_FC_CONFIG], +[AC_REQUIRE([_LT_PROG_FC])dnl +AC_LANG_PUSH(Fortran) + +_LT_TAGVAR(archive_cmds_need_lc, $1)=no +_LT_TAGVAR(allow_undefined_flag, $1)= +_LT_TAGVAR(always_export_symbols, $1)=no +_LT_TAGVAR(archive_expsym_cmds, $1)= +_LT_TAGVAR(export_dynamic_flag_spec, $1)= +_LT_TAGVAR(hardcode_direct, $1)=no +_LT_TAGVAR(hardcode_direct_absolute, $1)=no +_LT_TAGVAR(hardcode_libdir_flag_spec, $1)= +_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= +_LT_TAGVAR(hardcode_libdir_separator, $1)= +_LT_TAGVAR(hardcode_minus_L, $1)=no +_LT_TAGVAR(hardcode_automatic, $1)=no +_LT_TAGVAR(inherit_rpath, $1)=no +_LT_TAGVAR(module_cmds, $1)= +_LT_TAGVAR(module_expsym_cmds, $1)= +_LT_TAGVAR(link_all_deplibs, $1)=unknown +_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds +_LT_TAGVAR(no_undefined_flag, $1)= +_LT_TAGVAR(whole_archive_flag_spec, $1)= +_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no + +# Source file extension for fc test sources. +ac_ext=${ac_fc_srcext-f} + +# Object file extension for compiled fc test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# No sense in running all these tests if we already determined that +# the FC compiler isn't working. Some variables (like enable_shared) +# are currently assumed to apply to all compilers on this platform, +# and will be corrupted by setting them based on a non-working compiler. +if test "$_lt_disable_FC" != yes; then + # Code to be used in simple compile tests + lt_simple_compile_test_code="\ + subroutine t + return + end +" + + # Code to be used in simple link tests + lt_simple_link_test_code="\ + program t + end +" + + # ltmain only uses $CC for tagged configurations so make sure $CC is set. + _LT_TAG_COMPILER + + # save warnings/boilerplate of simple test code + _LT_COMPILER_BOILERPLATE + _LT_LINKER_BOILERPLATE + + # Allow CC to be a program name with arguments. + lt_save_CC="$CC" + lt_save_GCC=$GCC + CC=${FC-"f95"} + compiler=$CC + GCC=$ac_cv_fc_compiler_gnu + + _LT_TAGVAR(compiler, $1)=$CC + _LT_CC_BASENAME([$compiler]) + + if test -n "$compiler"; then + AC_MSG_CHECKING([if libtool supports shared libraries]) + AC_MSG_RESULT([$can_build_shared]) + + AC_MSG_CHECKING([whether to build shared libraries]) + test "$can_build_shared" = "no" && enable_shared=no + + # On AIX, shared libraries and static libraries use the same namespace, and + # are all built from PIC. + case $host_os in + aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + aix[[4-9]]*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; + esac + AC_MSG_RESULT([$enable_shared]) + + AC_MSG_CHECKING([whether to build static libraries]) + # Make sure either enable_shared or enable_static is yes. + test "$enable_shared" = yes || enable_static=yes + AC_MSG_RESULT([$enable_static]) + + _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu" + _LT_TAGVAR(LD, $1)="$LD" + + ## CAVEAT EMPTOR: + ## There is no encapsulation within the following macros, do not change + ## the running order or otherwise move them around unless you know exactly + ## what you are doing... + _LT_SYS_HIDDEN_LIBDEPS($1) + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_SYS_DYNAMIC_LINKER($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + + _LT_CONFIG($1) + fi # test -n "$compiler" + + GCC=$lt_save_GCC + CC="$lt_save_CC" +fi # test "$_lt_disable_FC" != yes + +AC_LANG_POP +])# _LT_LANG_FC_CONFIG + + +# _LT_LANG_GCJ_CONFIG([TAG]) +# -------------------------- +# Ensure that the configuration variables for the GNU Java Compiler compiler +# are suitably defined. These variables are subsequently used by _LT_CONFIG +# to write the compiler configuration to `libtool'. +m4_defun([_LT_LANG_GCJ_CONFIG], +[AC_REQUIRE([LT_PROG_GCJ])dnl +AC_LANG_SAVE + +# Source file extension for Java test sources. +ac_ext=java + +# Object file extension for compiled Java test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="class foo {}" + +# Code to be used in simple link tests +lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_TAG_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +lt_save_GCC=$GCC +GCC=yes +CC=${GCJ-"gcj"} +compiler=$CC +_LT_TAGVAR(compiler, $1)=$CC +_LT_TAGVAR(LD, $1)="$LD" +_LT_CC_BASENAME([$compiler]) + +# GCJ did not exist at the time GCC didn't implicitly link libc in. +_LT_TAGVAR(archive_cmds_need_lc, $1)=no + +_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds + +if test -n "$compiler"; then + _LT_COMPILER_NO_RTTI($1) + _LT_COMPILER_PIC($1) + _LT_COMPILER_C_O($1) + _LT_COMPILER_FILE_LOCKS($1) + _LT_LINKER_SHLIBS($1) + _LT_LINKER_HARDCODE_LIBPATH($1) + + _LT_CONFIG($1) +fi + +AC_LANG_RESTORE + +GCC=$lt_save_GCC +CC="$lt_save_CC" +])# _LT_LANG_GCJ_CONFIG + + +# _LT_LANG_RC_CONFIG([TAG]) +# ------------------------- +# Ensure that the configuration variables for the Windows resource compiler +# are suitably defined. These variables are subsequently used by _LT_CONFIG +# to write the compiler configuration to `libtool'. +m4_defun([_LT_LANG_RC_CONFIG], +[AC_REQUIRE([LT_PROG_RC])dnl +AC_LANG_SAVE + +# Source file extension for RC test sources. +ac_ext=rc + +# Object file extension for compiled RC test sources. +objext=o +_LT_TAGVAR(objext, $1)=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' + +# Code to be used in simple link tests +lt_simple_link_test_code="$lt_simple_compile_test_code" + +# ltmain only uses $CC for tagged configurations so make sure $CC is set. +_LT_TAG_COMPILER + +# save warnings/boilerplate of simple test code +_LT_COMPILER_BOILERPLATE +_LT_LINKER_BOILERPLATE + +# Allow CC to be a program name with arguments. +lt_save_CC="$CC" +lt_save_GCC=$GCC +GCC= +CC=${RC-"windres"} +compiler=$CC +_LT_TAGVAR(compiler, $1)=$CC +_LT_CC_BASENAME([$compiler]) +_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes + +if test -n "$compiler"; then + : + _LT_CONFIG($1) +fi + +GCC=$lt_save_GCC +AC_LANG_RESTORE +CC="$lt_save_CC" +])# _LT_LANG_RC_CONFIG + + +# LT_PROG_GCJ +# ----------- +AC_DEFUN([LT_PROG_GCJ], +[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], + [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], + [AC_CHECK_TOOL(GCJ, gcj,) + test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2" + AC_SUBST(GCJFLAGS)])])[]dnl +]) + +# Old name: +AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([LT_AC_PROG_GCJ], []) + + +# LT_PROG_RC +# ---------- +AC_DEFUN([LT_PROG_RC], +[AC_CHECK_TOOL(RC, windres,) +]) + +# Old name: +AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([LT_AC_PROG_RC], []) + + +# _LT_DECL_EGREP +# -------------- +# If we don't have a new enough Autoconf to choose the best grep +# available, choose the one first in the user's PATH. +m4_defun([_LT_DECL_EGREP], +[AC_REQUIRE([AC_PROG_EGREP])dnl +AC_REQUIRE([AC_PROG_FGREP])dnl +test -z "$GREP" && GREP=grep +_LT_DECL([], [GREP], [1], [A grep program that handles long lines]) +_LT_DECL([], [EGREP], [1], [An ERE matcher]) +_LT_DECL([], [FGREP], [1], [A literal string matcher]) +dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too +AC_SUBST([GREP]) +]) + + +# _LT_DECL_OBJDUMP +# -------------- +# If we don't have a new enough Autoconf to choose the best objdump +# available, choose the one first in the user's PATH. +m4_defun([_LT_DECL_OBJDUMP], +[AC_CHECK_TOOL(OBJDUMP, objdump, false) +test -z "$OBJDUMP" && OBJDUMP=objdump +_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper]) +AC_SUBST([OBJDUMP]) +]) + + +# _LT_DECL_SED +# ------------ +# Check for a fully-functional sed program, that truncates +# as few characters as possible. Prefer GNU sed if found. +m4_defun([_LT_DECL_SED], +[AC_PROG_SED +test -z "$SED" && SED=sed +Xsed="$SED -e 1s/^X//" +_LT_DECL([], [SED], [1], [A sed program that does not truncate output]) +_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], + [Sed that helps us avoid accidentally triggering echo(1) options like -n]) +])# _LT_DECL_SED + +m4_ifndef([AC_PROG_SED], [ +# NOTE: This macro has been submitted for inclusion into # +# GNU Autoconf as AC_PROG_SED. When it is available in # +# a released version of Autoconf we should remove this # +# macro and use it instead. # + +m4_defun([AC_PROG_SED], +[AC_MSG_CHECKING([for a sed that does not truncate output]) +AC_CACHE_VAL(lt_cv_path_SED, +[# Loop through the user's path and test for sed and gsed. +# Then use that list of sed's as ones to test for truncation. +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for lt_ac_prog in sed gsed; do + for ac_exec_ext in '' $ac_executable_extensions; do + if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then + lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" + fi + done + done +done +IFS=$as_save_IFS +lt_ac_max=0 +lt_ac_count=0 +# Add /usr/xpg4/bin/sed as it is typically found on Solaris +# along with /bin/sed that truncates output. +for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do + test ! -f $lt_ac_sed && continue + cat /dev/null > conftest.in + lt_ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >conftest.in + # Check for GNU sed and select it if it is found. + if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then + lt_cv_path_SED=$lt_ac_sed + break + fi + while true; do + cat conftest.in conftest.in >conftest.tmp + mv conftest.tmp conftest.in + cp conftest.in conftest.nl + echo >>conftest.nl + $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break + cmp -s conftest.out conftest.nl || break + # 10000 chars as input seems more than enough + test $lt_ac_count -gt 10 && break + lt_ac_count=`expr $lt_ac_count + 1` + if test $lt_ac_count -gt $lt_ac_max; then + lt_ac_max=$lt_ac_count + lt_cv_path_SED=$lt_ac_sed + fi + done +done +]) +SED=$lt_cv_path_SED +AC_SUBST([SED]) +AC_MSG_RESULT([$SED]) +])#AC_PROG_SED +])#m4_ifndef + +# Old name: +AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([LT_AC_PROG_SED], []) + + +# _LT_CHECK_SHELL_FEATURES +# ------------------------ +# Find out whether the shell is Bourne or XSI compatible, +# or has some other useful features. +m4_defun([_LT_CHECK_SHELL_FEATURES], +[AC_MSG_CHECKING([whether the shell understands some XSI constructs]) +# Try some XSI features +xsi_shell=no +( _lt_dummy="a/b/c" + test "${_lt_dummy##*/},${_lt_dummy%/*},"${_lt_dummy%"$_lt_dummy"}, \ + = c,a/b,, \ + && eval 'test $(( 1 + 1 )) -eq 2 \ + && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ + && xsi_shell=yes +AC_MSG_RESULT([$xsi_shell]) +_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell']) + +AC_MSG_CHECKING([whether the shell understands "+="]) +lt_shell_append=no +( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \ + >/dev/null 2>&1 \ + && lt_shell_append=yes +AC_MSG_RESULT([$lt_shell_append]) +_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append']) + +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + lt_unset=unset +else + lt_unset=false +fi +_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl + +# test EBCDIC or ASCII +case `echo X|tr X '\101'` in + A) # ASCII based system + # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr + lt_SP2NL='tr \040 \012' + lt_NL2SP='tr \015\012 \040\040' + ;; + *) # EBCDIC based system + lt_SP2NL='tr \100 \n' + lt_NL2SP='tr \r\n \100\100' + ;; +esac +_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl +_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl +])# _LT_CHECK_SHELL_FEATURES + + +# _LT_PROG_XSI_SHELLFNS +# --------------------- +# Bourne and XSI compatible variants of some useful shell functions. +m4_defun([_LT_PROG_XSI_SHELLFNS], +[case $xsi_shell in + yes) + cat << \_LT_EOF >> "$cfgfile" + +# func_dirname file append nondir_replacement +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +func_dirname () +{ + case ${1} in + */*) func_dirname_result="${1%/*}${2}" ;; + * ) func_dirname_result="${3}" ;; + esac +} + +# func_basename file +func_basename () +{ + func_basename_result="${1##*/}" +} + +# func_dirname_and_basename file append nondir_replacement +# perform func_basename and func_dirname in a single function +# call: +# dirname: Compute the dirname of FILE. If nonempty, +# add APPEND to the result, otherwise set result +# to NONDIR_REPLACEMENT. +# value returned in "$func_dirname_result" +# basename: Compute filename of FILE. +# value retuned in "$func_basename_result" +# Implementation must be kept synchronized with func_dirname +# and func_basename. For efficiency, we do not delegate to +# those functions but instead duplicate the functionality here. +func_dirname_and_basename () +{ + case ${1} in + */*) func_dirname_result="${1%/*}${2}" ;; + * ) func_dirname_result="${3}" ;; + esac + func_basename_result="${1##*/}" +} + +# func_stripname prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +func_stripname () +{ + # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are + # positional parameters, so assign one to ordinary parameter first. + func_stripname_result=${3} + func_stripname_result=${func_stripname_result#"${1}"} + func_stripname_result=${func_stripname_result%"${2}"} +} + +# func_opt_split +func_opt_split () +{ + func_opt_split_opt=${1%%=*} + func_opt_split_arg=${1#*=} +} + +# func_lo2o object +func_lo2o () +{ + case ${1} in + *.lo) func_lo2o_result=${1%.lo}.${objext} ;; + *) func_lo2o_result=${1} ;; + esac +} + +# func_xform libobj-or-source +func_xform () +{ + func_xform_result=${1%.*}.lo +} + +# func_arith arithmetic-term... +func_arith () +{ + func_arith_result=$(( $[*] )) +} + +# func_len string +# STRING may not start with a hyphen. +func_len () +{ + func_len_result=${#1} +} + +_LT_EOF + ;; + *) # Bourne compatible functions. + cat << \_LT_EOF >> "$cfgfile" + +# func_dirname file append nondir_replacement +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +func_dirname () +{ + # Extract subdirectory from the argument. + func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` + if test "X$func_dirname_result" = "X${1}"; then + func_dirname_result="${3}" + else + func_dirname_result="$func_dirname_result${2}" + fi +} + +# func_basename file +func_basename () +{ + func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` +} + +dnl func_dirname_and_basename +dnl A portable version of this function is already defined in general.m4sh +dnl so there is no need for it here. + +# func_stripname prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +# func_strip_suffix prefix name +func_stripname () +{ + case ${2} in + .*) func_stripname_result=`$ECHO "X${3}" \ + | $Xsed -e "s%^${1}%%" -e "s%\\\\${2}\$%%"`;; + *) func_stripname_result=`$ECHO "X${3}" \ + | $Xsed -e "s%^${1}%%" -e "s%${2}\$%%"`;; + esac +} + +# sed scripts: +my_sed_long_opt='1s/^\(-[[^=]]*\)=.*/\1/;q' +my_sed_long_arg='1s/^-[[^=]]*=//' + +# func_opt_split +func_opt_split () +{ + func_opt_split_opt=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_opt"` + func_opt_split_arg=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_arg"` +} + +# func_lo2o object +func_lo2o () +{ + func_lo2o_result=`$ECHO "X${1}" | $Xsed -e "$lo2o"` +} + +# func_xform libobj-or-source +func_xform () +{ + func_xform_result=`$ECHO "X${1}" | $Xsed -e 's/\.[[^.]]*$/.lo/'` +} + +# func_arith arithmetic-term... +func_arith () +{ + func_arith_result=`expr "$[@]"` +} + +# func_len string +# STRING may not start with a hyphen. +func_len () +{ + func_len_result=`expr "$[1]" : ".*" 2>/dev/null || echo $max_cmd_len` +} + +_LT_EOF +esac + +case $lt_shell_append in + yes) + cat << \_LT_EOF >> "$cfgfile" + +# func_append var value +# Append VALUE to the end of shell variable VAR. +func_append () +{ + eval "$[1]+=\$[2]" +} +_LT_EOF + ;; + *) + cat << \_LT_EOF >> "$cfgfile" + +# func_append var value +# Append VALUE to the end of shell variable VAR. +func_append () +{ + eval "$[1]=\$$[1]\$[2]" +} + +_LT_EOF + ;; + esac +]) + +# Helper functions for option handling. -*- Autoconf -*- +# +# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc. +# Written by Gary V. Vaughan, 2004 +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +# serial 6 ltoptions.m4 + +# This is to help aclocal find these macros, as it can't see m4_define. +AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) + + +# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME) +# ------------------------------------------ +m4_define([_LT_MANGLE_OPTION], +[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])]) + + +# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME) +# --------------------------------------- +# Set option OPTION-NAME for macro MACRO-NAME, and if there is a +# matching handler defined, dispatch to it. Other OPTION-NAMEs are +# saved as a flag. +m4_define([_LT_SET_OPTION], +[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl +m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]), + _LT_MANGLE_DEFUN([$1], [$2]), + [m4_warning([Unknown $1 option `$2'])])[]dnl +]) + + +# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET]) +# ------------------------------------------------------------ +# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. +m4_define([_LT_IF_OPTION], +[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])]) + + +# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET) +# ------------------------------------------------------- +# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME +# are set. +m4_define([_LT_UNLESS_OPTIONS], +[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), + [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option), + [m4_define([$0_found])])])[]dnl +m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3 +])[]dnl +]) + + +# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST) +# ---------------------------------------- +# OPTION-LIST is a space-separated list of Libtool options associated +# with MACRO-NAME. If any OPTION has a matching handler declared with +# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about +# the unknown option and exit. +m4_defun([_LT_SET_OPTIONS], +[# Set options +m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), + [_LT_SET_OPTION([$1], _LT_Option)]) + +m4_if([$1],[LT_INIT],[ + dnl + dnl Simply set some default values (i.e off) if boolean options were not + dnl specified: + _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no + ]) + _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no + ]) + dnl + dnl If no reference was made to various pairs of opposing options, then + dnl we run the default mode handler for the pair. For example, if neither + dnl `shared' nor `disable-shared' was passed, we enable building of shared + dnl archives by default: + _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED]) + _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC]) + _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC]) + _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install], + [_LT_ENABLE_FAST_INSTALL]) + ]) +])# _LT_SET_OPTIONS + + + +# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME) +# ----------------------------------------- +m4_define([_LT_MANGLE_DEFUN], +[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])]) + + +# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE) +# ----------------------------------------------- +m4_define([LT_OPTION_DEFINE], +[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl +])# LT_OPTION_DEFINE + + +# dlopen +# ------ +LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes +]) + +AU_DEFUN([AC_LIBTOOL_DLOPEN], +[_LT_SET_OPTION([LT_INIT], [dlopen]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you +put the `dlopen' option into LT_INIT's first parameter.]) +]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], []) + + +# win32-dll +# --------- +# Declare package support for building win32 dll's. +LT_OPTION_DEFINE([LT_INIT], [win32-dll], +[enable_win32_dll=yes + +case $host in +*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-cegcc*) + AC_CHECK_TOOL(AS, as, false) + AC_CHECK_TOOL(DLLTOOL, dlltool, false) + AC_CHECK_TOOL(OBJDUMP, objdump, false) + ;; +esac + +test -z "$AS" && AS=as +_LT_DECL([], [AS], [0], [Assembler program])dnl + +test -z "$DLLTOOL" && DLLTOOL=dlltool +_LT_DECL([], [DLLTOOL], [0], [DLL creation program])dnl + +test -z "$OBJDUMP" && OBJDUMP=objdump +_LT_DECL([], [OBJDUMP], [0], [Object dumper program])dnl +])# win32-dll + +AU_DEFUN([AC_LIBTOOL_WIN32_DLL], +[AC_REQUIRE([AC_CANONICAL_HOST])dnl +_LT_SET_OPTION([LT_INIT], [win32-dll]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you +put the `win32-dll' option into LT_INIT's first parameter.]) +]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], []) + + +# _LT_ENABLE_SHARED([DEFAULT]) +# ---------------------------- +# implement the --enable-shared flag, and supports the `shared' and +# `disable-shared' LT_INIT options. +# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. +m4_define([_LT_ENABLE_SHARED], +[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl +AC_ARG_ENABLE([shared], + [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@], + [build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_shared=yes ;; + no) enable_shared=no ;; + *) + enable_shared=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_shared=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac], + [enable_shared=]_LT_ENABLE_SHARED_DEFAULT) + + _LT_DECL([build_libtool_libs], [enable_shared], [0], + [Whether or not to build shared libraries]) +])# _LT_ENABLE_SHARED + +LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])]) +LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])]) + +# Old names: +AC_DEFUN([AC_ENABLE_SHARED], +[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) +]) + +AC_DEFUN([AC_DISABLE_SHARED], +[_LT_SET_OPTION([LT_INIT], [disable-shared]) +]) + +AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) +AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AM_ENABLE_SHARED], []) +dnl AC_DEFUN([AM_DISABLE_SHARED], []) + + + +# _LT_ENABLE_STATIC([DEFAULT]) +# ---------------------------- +# implement the --enable-static flag, and support the `static' and +# `disable-static' LT_INIT options. +# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. +m4_define([_LT_ENABLE_STATIC], +[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl +AC_ARG_ENABLE([static], + [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@], + [build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_static=yes ;; + no) enable_static=no ;; + *) + enable_static=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_static=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac], + [enable_static=]_LT_ENABLE_STATIC_DEFAULT) + + _LT_DECL([build_old_libs], [enable_static], [0], + [Whether or not to build static libraries]) +])# _LT_ENABLE_STATIC + +LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])]) +LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])]) + +# Old names: +AC_DEFUN([AC_ENABLE_STATIC], +[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) +]) + +AC_DEFUN([AC_DISABLE_STATIC], +[_LT_SET_OPTION([LT_INIT], [disable-static]) +]) + +AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) +AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AM_ENABLE_STATIC], []) +dnl AC_DEFUN([AM_DISABLE_STATIC], []) + + + +# _LT_ENABLE_FAST_INSTALL([DEFAULT]) +# ---------------------------------- +# implement the --enable-fast-install flag, and support the `fast-install' +# and `disable-fast-install' LT_INIT options. +# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. +m4_define([_LT_ENABLE_FAST_INSTALL], +[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl +AC_ARG_ENABLE([fast-install], + [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], + [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], + [p=${PACKAGE-default} + case $enableval in + yes) enable_fast_install=yes ;; + no) enable_fast_install=no ;; + *) + enable_fast_install=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_fast_install=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac], + [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT) + +_LT_DECL([fast_install], [enable_fast_install], [0], + [Whether or not to optimize for fast installation])dnl +])# _LT_ENABLE_FAST_INSTALL + +LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])]) +LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])]) + +# Old names: +AU_DEFUN([AC_ENABLE_FAST_INSTALL], +[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you put +the `fast-install' option into LT_INIT's first parameter.]) +]) + +AU_DEFUN([AC_DISABLE_FAST_INSTALL], +[_LT_SET_OPTION([LT_INIT], [disable-fast-install]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you put +the `disable-fast-install' option into LT_INIT's first parameter.]) +]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], []) +dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) + + +# _LT_WITH_PIC([MODE]) +# -------------------- +# implement the --with-pic flag, and support the `pic-only' and `no-pic' +# LT_INIT options. +# MODE is either `yes' or `no'. If omitted, it defaults to `both'. +m4_define([_LT_WITH_PIC], +[AC_ARG_WITH([pic], + [AS_HELP_STRING([--with-pic], + [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], + [pic_mode="$withval"], + [pic_mode=default]) + +test -z "$pic_mode" && pic_mode=m4_default([$1], [default]) + +_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl +])# _LT_WITH_PIC + +LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])]) +LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])]) + +# Old name: +AU_DEFUN([AC_LIBTOOL_PICMODE], +[_LT_SET_OPTION([LT_INIT], [pic-only]) +AC_DIAGNOSE([obsolete], +[$0: Remove this warning and the call to _LT_SET_OPTION when you +put the `pic-only' option into LT_INIT's first parameter.]) +]) + +dnl aclocal-1.4 backwards compatibility: +dnl AC_DEFUN([AC_LIBTOOL_PICMODE], []) + + +m4_define([_LTDL_MODE], []) +LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive], + [m4_define([_LTDL_MODE], [nonrecursive])]) +LT_OPTION_DEFINE([LTDL_INIT], [recursive], + [m4_define([_LTDL_MODE], [recursive])]) +LT_OPTION_DEFINE([LTDL_INIT], [subproject], + [m4_define([_LTDL_MODE], [subproject])]) + +m4_define([_LTDL_TYPE], []) +LT_OPTION_DEFINE([LTDL_INIT], [installable], + [m4_define([_LTDL_TYPE], [installable])]) +LT_OPTION_DEFINE([LTDL_INIT], [convenience], + [m4_define([_LTDL_TYPE], [convenience])]) + +# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- +# +# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc. +# Written by Gary V. Vaughan, 2004 +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +# serial 6 ltsugar.m4 + +# This is to help aclocal find these macros, as it can't see m4_define. +AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) + + +# lt_join(SEP, ARG1, [ARG2...]) +# ----------------------------- +# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their +# associated separator. +# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier +# versions in m4sugar had bugs. +m4_define([lt_join], +[m4_if([$#], [1], [], + [$#], [2], [[$2]], + [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) +m4_define([_lt_join], +[m4_if([$#$2], [2], [], + [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) + + +# lt_car(LIST) +# lt_cdr(LIST) +# ------------ +# Manipulate m4 lists. +# These macros are necessary as long as will still need to support +# Autoconf-2.59 which quotes differently. +m4_define([lt_car], [[$1]]) +m4_define([lt_cdr], +[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], + [$#], 1, [], + [m4_dquote(m4_shift($@))])]) +m4_define([lt_unquote], $1) + + +# lt_append(MACRO-NAME, STRING, [SEPARATOR]) +# ------------------------------------------ +# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'. +# Note that neither SEPARATOR nor STRING are expanded; they are appended +# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). +# No SEPARATOR is output if MACRO-NAME was previously undefined (different +# than defined and empty). +# +# This macro is needed until we can rely on Autoconf 2.62, since earlier +# versions of m4sugar mistakenly expanded SEPARATOR but not STRING. +m4_define([lt_append], +[m4_define([$1], + m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) + + + +# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) +# ---------------------------------------------------------- +# Produce a SEP delimited list of all paired combinations of elements of +# PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list +# has the form PREFIXmINFIXSUFFIXn. +# Needed until we can rely on m4_combine added in Autoconf 2.62. +m4_define([lt_combine], +[m4_if(m4_eval([$# > 3]), [1], + [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl +[[m4_foreach([_Lt_prefix], [$2], + [m4_foreach([_Lt_suffix], + ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, + [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) + + +# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) +# ----------------------------------------------------------------------- +# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited +# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. +m4_define([lt_if_append_uniq], +[m4_ifdef([$1], + [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], + [lt_append([$1], [$2], [$3])$4], + [$5])], + [lt_append([$1], [$2], [$3])$4])]) + + +# lt_dict_add(DICT, KEY, VALUE) +# ----------------------------- +m4_define([lt_dict_add], +[m4_define([$1($2)], [$3])]) + + +# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) +# -------------------------------------------- +m4_define([lt_dict_add_subkey], +[m4_define([$1($2:$3)], [$4])]) + + +# lt_dict_fetch(DICT, KEY, [SUBKEY]) +# ---------------------------------- +m4_define([lt_dict_fetch], +[m4_ifval([$3], + m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), + m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) + + +# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) +# ----------------------------------------------------------------- +m4_define([lt_if_dict_fetch], +[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], + [$5], + [$6])]) + + +# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) +# -------------------------------------------------------------- +m4_define([lt_dict_filter], +[m4_if([$5], [], [], + [lt_join(m4_quote(m4_default([$4], [[, ]])), + lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), + [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl +]) + +# ltversion.m4 -- version numbers -*- Autoconf -*- +# +# Copyright (C) 2004 Free Software Foundation, Inc. +# Written by Scott James Remnant, 2004 +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +# Generated from ltversion.in. + +# serial 3012 ltversion.m4 +# This file is part of GNU Libtool + +m4_define([LT_PACKAGE_VERSION], [2.2.6]) +m4_define([LT_PACKAGE_REVISION], [1.3012]) + +AC_DEFUN([LTVERSION_VERSION], +[macro_version='2.2.6' +macro_revision='1.3012' +_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) +_LT_DECL(, macro_revision, 0) +]) + +# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- +# +# Copyright (C) 2004, 2005, 2007 Free Software Foundation, Inc. +# Written by Scott James Remnant, 2004. +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. + +# serial 4 lt~obsolete.m4 + +# These exist entirely to fool aclocal when bootstrapping libtool. +# +# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN) +# which have later been changed to m4_define as they aren't part of the +# exported API, or moved to Autoconf or Automake where they belong. +# +# The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN +# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us +# using a macro with the same name in our local m4/libtool.m4 it'll +# pull the old libtool.m4 in (it doesn't see our shiny new m4_define +# and doesn't know about Autoconf macros at all.) +# +# So we provide this file, which has a silly filename so it's always +# included after everything else. This provides aclocal with the +# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything +# because those macros already exist, or will be overwritten later. +# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. +# +# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. +# Yes, that means every name once taken will need to remain here until +# we give up compatibility with versions before 1.7, at which point +# we need to keep only those names which we still refer to. + +# This is to help aclocal find these macros, as it can't see m4_define. +AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) + +m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) +m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) +m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) +m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) +m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) +m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) +m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) +m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) +m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) +m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) +m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) +m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) +m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) +m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) +m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) +m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) +m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) +m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) +m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) +m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) +m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) +m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) +m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) +m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) +m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) +m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) +m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) +m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) +m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) +m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) +m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) +m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) +m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) +m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) +m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) +m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) +m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) +m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) +m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) +m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) +m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) +m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) +m4_ifndef([AC_LIBTOOL_RC], [AC_DEFUN([AC_LIBTOOL_RC])]) +m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) +m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) +m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) +m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) +m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) +m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) +m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) +m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) +m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) +m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) +m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) +m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) + diff --git a/components/external/SQLite-3.8.1/addopcodes.awk b/components/external/SQLite-3.8.1/addopcodes.awk new file mode 100644 index 0000000000000000000000000000000000000000..c90e1dd7f4c0f42740fb74adf78f5310b429572a --- /dev/null +++ b/components/external/SQLite-3.8.1/addopcodes.awk @@ -0,0 +1,34 @@ +#!/usr/bin/awk +# +# This script appends additional token codes to the end of the +# parse.h file that lemon generates. These extra token codes are +# not used by the parser. But they are used by the tokenizer and/or +# the code generator. +# +# +BEGIN { + max = 0 +} +/^#define TK_/ { + print $0 + if( max<$3 ) max = $3 +} +END { + printf "#define TK_%-29s %4d\n", "TO_TEXT", ++max + printf "#define TK_%-29s %4d\n", "TO_BLOB", ++max + printf "#define TK_%-29s %4d\n", "TO_NUMERIC", ++max + printf "#define TK_%-29s %4d\n", "TO_INT", ++max + printf "#define TK_%-29s %4d\n", "TO_REAL", ++max + printf "#define TK_%-29s %4d\n", "ISNOT", ++max + printf "#define TK_%-29s %4d\n", "END_OF_FILE", ++max + printf "#define TK_%-29s %4d\n", "ILLEGAL", ++max + printf "#define TK_%-29s %4d\n", "SPACE", ++max + printf "#define TK_%-29s %4d\n", "UNCLOSED_STRING", ++max + printf "#define TK_%-29s %4d\n", "FUNCTION", ++max + printf "#define TK_%-29s %4d\n", "COLUMN", ++max + printf "#define TK_%-29s %4d\n", "AGG_FUNCTION", ++max + printf "#define TK_%-29s %4d\n", "AGG_COLUMN", ++max + printf "#define TK_%-29s %4d\n", "CONST_FUNC", ++max + printf "#define TK_%-29s %4d\n", "UMINUS", ++max + printf "#define TK_%-29s %4d\n", "UPLUS", ++max +} diff --git a/components/external/SQLite-3.8.1/art/sqlite370.eps b/components/external/SQLite-3.8.1/art/sqlite370.eps new file mode 100644 index 0000000000000000000000000000000000000000..770175687eacea95135c0a47cae1c61e274e9b36 --- /dev/null +++ b/components/external/SQLite-3.8.1/art/sqlite370.eps @@ -0,0 +1,5333 @@ +%!PS-Adobe-3.1 EPSF-3.0 +%ADO_DSC_Encoding: MacOS Roman +%%Title: logo_color_eps.eps +%%Creator: Adobe Illustrator(R) 13.0 +%%For: Mary Diarte +%%CreationDate: 5/25/10 +%%BoundingBox: 0 0 372 212 +%%HiResBoundingBox: 0 0 372 211.3042 +%%CropBox: 0 0 372 211.3042 +%%LanguageLevel: 2 +%%DocumentData: Clean7Bit +%ADOBeginClientInjection: DocumentHeader "AI11EPS" +%%AI8_CreatorVersion: 13.0.2 %AI9_PrintingDataBegin %AI3_Cropmarks: 36.0000 36.0000 336.0000 175.3042 +%ADO_BuildNumber: Adobe Illustrator(R) 13.0.2 x434 R agm 4.4379 ct 5.1039 %ADO_ContainsXMP: MainFirst %AI7_Thumbnail: 128 76 8 %%BeginData: 6312 Hex Bytes %0000330000660000990000CC0033000033330033660033990033CC0033FF %0066000066330066660066990066CC0066FF009900009933009966009999 %0099CC0099FF00CC0000CC3300CC6600CC9900CCCC00CCFF00FF3300FF66 %00FF9900FFCC3300003300333300663300993300CC3300FF333300333333 %3333663333993333CC3333FF3366003366333366663366993366CC3366FF %3399003399333399663399993399CC3399FF33CC0033CC3333CC6633CC99 %33CCCC33CCFF33FF0033FF3333FF6633FF9933FFCC33FFFF660000660033 %6600666600996600CC6600FF6633006633336633666633996633CC6633FF %6666006666336666666666996666CC6666FF669900669933669966669999 %6699CC6699FF66CC0066CC3366CC6666CC9966CCCC66CCFF66FF0066FF33 %66FF6666FF9966FFCC66FFFF9900009900339900669900999900CC9900FF %9933009933339933669933999933CC9933FF996600996633996666996699 %9966CC9966FF9999009999339999669999999999CC9999FF99CC0099CC33 %99CC6699CC9999CCCC99CCFF99FF0099FF3399FF6699FF9999FFCC99FFFF %CC0000CC0033CC0066CC0099CC00CCCC00FFCC3300CC3333CC3366CC3399 %CC33CCCC33FFCC6600CC6633CC6666CC6699CC66CCCC66FFCC9900CC9933 %CC9966CC9999CC99CCCC99FFCCCC00CCCC33CCCC66CCCC99CCCCCCCCCCFF %CCFF00CCFF33CCFF66CCFF99CCFFCCCCFFFFFF0033FF0066FF0099FF00CC %FF3300FF3333FF3366FF3399FF33CCFF33FFFF6600FF6633FF6666FF6699 %FF66CCFF66FFFF9900FF9933FF9966FF9999FF99CCFF99FFFFCC00FFCC33 %FFCC66FFCC99FFCCCCFFCCFFFFFF33FFFF66FFFF99FFFFCC110000001100 %000011111111220000002200000022222222440000004400000044444444 %550000005500000055555555770000007700000077777777880000008800 %000088888888AA000000AA000000AAAAAAAABB000000BB000000BBBBBBBB %DD000000DD000000DDDDDDDDEE000000EE000000EEEEEEEE0000000000FF %00FF0000FFFFFF0000FF00FFFFFF00FFFFFF %524C45FDFCFFFDFCFFFDFCFFFDFCFFFDFCFFFDFCFFFDFCFFFD4AFFA90C0D %0C35A8FD79FF3505060506050CA8FD5AFF84360E0E0D140E0E0D140E0E0D %140E0E0D140E0E0D140E0E0D140E0E0D0D0506050C05060535FD59FF7E0E %3685608560856085608560856085608560856085608560856085600D0506 %05060506050605FD59FF365A856085618560856185608561856085618560 %856185608561856035050605060506050605067EFD58FF0D615A615A615A %615A615A615A615A615A615A615A615A615A615A5A050605060506050605 %060584FD58FF146185608561856085618560856185608561856085618560 %856161060C0506050C0606050C05067EFD58FF0D615A615A615A615A615A %615A615A615A615A615A615A615A610D0605060506060C050605060584FD %58FF0E5A855A615A855A615A855A615A855A615A855A615A855A61360605 %060506062F050605060506A8FD58FF0D5A5A615A5A5A615A5A5A615A5A5A %615A5A5A615A5A5A615A0C05060506055905060506050605FD59FF0E5A61 %5A615A615A615A615A615A615A615A615A615A615A5A050C0506052F0C06 %050C05060535FD59FF0D5A365B5A5A365B5A5A365B5A5A365B5A5A365B5A %5A365B0C0605060506590605060506050659FD59FF145A5B5A615A5B5A61 %5A5B5A615A5B5A615A5B5A615A5B360605060506350C05060506050606FD %5AFF0D5A365A365A365A365A365A365A365A365A365A365A360D05060506 %05840506050605060535FD5AFF14365B365B365B365B365B365B365B365B %365B365B365B050C0506055A0C06050C0506050CA8FD5AFF0D5A3636365A %3636365A3636365A3636365A3636365A0D060506050C5906050605060506 %0CFD5BFF0E365A365A365A365A365A365A365A365A365A365A360D050605 %06590C05060506050605A9FD5BFF0D363036303630363036303630363036 %3036303630360506050605A90506050605060535FD5CFF0EFD14360D0C05 %06055A2F06050C0506050CAFFD5CFF0D360E3630360E3630360E3630360E %3630360E36300D0506050684060506050605062FFD5DFF1436360E363636 %0E3636360E3636360E3636360E360C0605060C5905060506050606FD5EFF %0D360E360D360E360D360E360D360E360D360E360D0C0506058406060506 %05060CA9FD5EFF140E360E360E360E360E360E360E360E360E360E0D0506 %050CA806050C062F2FA9FFFF2F0C050C06350C84FD07FF5A0C0C060D050C %2FFD06FF0D0506050C0CFD3AFF0D360E140D360E140D360E140D360E140D %360E14060605062E3505060506050CFFFF0C0659FFFFA806065AFD05FF7E %0C0535A8FFFFFF590C0559FD05FF7E05062EFD3BFF0E0E360E140E360E14 %0E360E140E360E140E360E0C0506058406060506050684FF84062FFD05FF %0584FD04FF590605A9FD06FFA80C052FFD04FF84060584FD3BFF0D0E0D14 %0D0E0D140D0E0D140D0E0D140D0E0D0D050605067E06050605062FFFFF35 %055AFD05FF2F59FFFFFF7E060559FD08FF84060535FD04FF05065AFD09FF %060CFD30FF0E0E140E140E140E140E140E140E140E140E140D06050C0C5A %050C05060CFFFFFF2F0C0CFD05FFA8FD04FF0D050CFD0AFF2F0605AFFFFF %FF0C0584FD09FF0D05AFFD05FFA9FD29FF0D0E0D140D0E0D140D0E0D140D %0E0D140D0E0D0D050605590606050605AFFFFFFF5905062FFD08FF840506 %2FFD0AFFA905062EFFFFFF05065AFD0AFFA9FD05FF5A06FD29FF140E140D %140E140D140E140D140E140D140E140D0C05065906050606A9FD04FFA80C %05060CFD07FF2F060584FD0BFF0C050CFFFFFF060584FD10FF060CFD29FF %0D0E0D0E0D0E0D0E0D0E0D0E0D0E0D0E0D0E0D0E0606055A05062FFD07FF %2F0605060559FD05FF0C0506FD0CFF060605FFFFFF050659FD07FFA85A2E %0C06FFFF350506050C0684FD04FF0C06050C59FD1DFF140E140D140E140D %140E140D140E0E0D140E0E0D0E050C2F0C84FD09FF350C0506050DAFFFFF %FF0C0605FD0CFF0D0506FFFFFF060584FD07FFA92F0C050DFFFF7E5A050C %7E84AFFFFFFF060C2F0C050CA9FD1CFF0D0E0D0E0D0E0D0E0D0E0D0E0D0E %0D0E0D0E0D0E0D060C0C59FD0BFF840C0506050CA8FFFF0C0506FD0CFF06 %0605FFFFA9050659FD09FF840606FFFFFF590606FD05FF060C84FF59060C %FD1DFF0E0D140E0E0D140E0E0D140E0E0D140E0E0D140E0E06590CFD0EFF %5A0606050DFFFF0C060584FD0BFF0C050CFFFF7E060584FD0AFF050CFFFF %FF84050DFD04FF840635FFFF2F05FD1EFF0D0E0D0E0D0E0D0E0D0E0D0E0D %0E0D0E0D0E0D0E0D0C2E84FD0FFF84050605FFFF59050659FD0BFF05060C %FFFF8405065AFD09FF590606FFFFFF5A0606FD04FF59055A590C0584FD1E %FF0E0D140E0E0D140E0E0D140E0E0D140E0E0D140E0E0684FD0AFF59FD06 %FF5A050C7EFFFF0C052FFD0AFF59060584FFFF7E0C0584FD09FF84050DFF %FFFF84050DFD04FF2F0606355AFD20FF0D0E0D0E0D0E0D0E0D0E0D0E0D0E %0D0E0D0E0D0E0D0C59FD0AFF0C59FD05FFA80605A9FFFF59060584FD09FF %0C050CFFFFFF8405065AFD09FF590606FFFFFF5A062EFD04FF350559FD05 %FFA9FD1CFF140E0E0D140E0E0D140E0E0D140E0E0D140E0E0D140684FD0A %FF0C2FFD05FF84050CFD04FF2F0606FD08FF35050CAFFFFFFF7E060584FD %05FF8459FFFF84050DFFFFFF840535FFFF84847E0606FD04FF8406FD1CFF %5A0E0D0E0D0E0D0E0D0E0D0E0D0E0D0E0D0E0D0E0D0C84FD0AFF0C0559FD %04FF060659FD05FF2E0606A8FD04FFA82F050CA8FD04FF5A05062EFD05FF %0559FFFF5A0605FFFFFF590605842F0C7EFF0506065A592F055AFD1DFF5A %0E0D140E0E0D140E0E0D140E0E0D140E0E0D140CA8FD0AFF0C0C060D2F2F %050C59FD07FF7E0D052F2F590C0C065AFD05FF350506050C060D0C0C0506 %7EFF2F0C050C0C5AFFFF0C06050C84FFFFA90C06050C0635FD1FFFA98584 %A9848584A9848584A9848584A9848584355AFD0AFF84A8FF7E5A2F5AA8FD %0AFFA80C0605062EFD07FF7E845A8459845A8459845AAFFD0AFF5A84FD06 %FFA88484FD34FF3584FD1EFF0C06050659FD5BFF842FFD1FFF0C0605067E %FD5AFFA935FD20FF2F06050C59FD5AFF06FD21FF59060506062F2F5AFD7A %FF8435592F5984FDFCFFFDFCFFFDFCFFFDFCFFFDFCFFFDFCFFFDFCFFFDFC %FFFDD1FFFF %%EndData +%ADOEndClientInjection: DocumentHeader "AI11EPS" +%%Pages: 1 +%%DocumentNeededResources: +%%DocumentSuppliedResources: procset Adobe_AGM_Image 1.0 0 +%%+ procset Adobe_CoolType_Utility_T42 1.0 0 +%%+ procset Adobe_CoolType_Utility_MAKEOCF 1.23 0 +%%+ procset Adobe_CoolType_Core 2.31 0 +%%+ procset Adobe_AGM_Core 2.0 0 +%%+ procset Adobe_AGM_Utils 1.0 0 +%%DocumentFonts: +%%DocumentNeededFonts: +%%DocumentNeededFeatures: +%%DocumentSuppliedFeatures: +%%DocumentProcessColors: +%%DocumentCustomColors: (PANTONE 2905 U) +%%+ (PANTONE 309 U) +%%+ (PANTONE 3005 U) +%%CMYKCustomColor: 0.4100 0.0200 0 0 (PANTONE 2905 U) +%%+ 1 0 0.0900 0.7200 (PANTONE 309 U) +%%+ 1 0.3400 0 0.0200 (PANTONE 3005 U) +%%RGBCustomColor: +%%EndComments + + + + + + +%%BeginDefaults +%%ViewingOrientation: 1 0 0 1 +%%EndDefaults +%%BeginProlog +%%BeginResource: procset Adobe_AGM_Utils 1.0 0 +%%Version: 1.0 0 +%%Copyright: Copyright(C)2000-2006 Adobe Systems, Inc. All Rights Reserved. +systemdict/setpacking known +{currentpacking true setpacking}if +userdict/Adobe_AGM_Utils 73 dict dup begin put +/bdf +{bind def}bind def +/nd{null def}bdf +/xdf +{exch def}bdf +/ldf +{load def}bdf +/ddf +{put}bdf +/xddf +{3 -1 roll put}bdf +/xpt +{exch put}bdf +/ndf +{ + exch dup where{ + pop pop pop + }{ + xdf + }ifelse +}def +/cdndf +{ + exch dup currentdict exch known{ + pop pop + }{ + exch def + }ifelse +}def +/gx +{get exec}bdf +/ps_level + /languagelevel where{ + pop systemdict/languagelevel gx + }{ + 1 + }ifelse +def +/level2 + ps_level 2 ge +def +/level3 + ps_level 3 ge +def +/ps_version + {version cvr}stopped{-1}if +def +/set_gvm +{currentglobal exch setglobal}bdf +/reset_gvm +{setglobal}bdf +/makereadonlyarray +{ + /packedarray where{pop packedarray + }{ + array astore readonly}ifelse +}bdf +/map_reserved_ink_name +{ + dup type/stringtype eq{ + dup/Red eq{ + pop(_Red_) + }{ + dup/Green eq{ + pop(_Green_) + }{ + dup/Blue eq{ + pop(_Blue_) + }{ + dup()cvn eq{ + pop(Process) + }if + }ifelse + }ifelse + }ifelse + }if +}bdf +/AGMUTIL_GSTATE 22 dict def +/get_gstate +{ + AGMUTIL_GSTATE begin + /AGMUTIL_GSTATE_clr_spc currentcolorspace def + /AGMUTIL_GSTATE_clr_indx 0 def + /AGMUTIL_GSTATE_clr_comps 12 array def + mark currentcolor counttomark + {AGMUTIL_GSTATE_clr_comps AGMUTIL_GSTATE_clr_indx 3 -1 roll put + /AGMUTIL_GSTATE_clr_indx AGMUTIL_GSTATE_clr_indx 1 add def}repeat pop + /AGMUTIL_GSTATE_fnt rootfont def + /AGMUTIL_GSTATE_lw currentlinewidth def + /AGMUTIL_GSTATE_lc currentlinecap def + /AGMUTIL_GSTATE_lj currentlinejoin def + /AGMUTIL_GSTATE_ml currentmiterlimit def + currentdash/AGMUTIL_GSTATE_do xdf/AGMUTIL_GSTATE_da xdf + /AGMUTIL_GSTATE_sa currentstrokeadjust def + /AGMUTIL_GSTATE_clr_rnd currentcolorrendering def + /AGMUTIL_GSTATE_op currentoverprint def + /AGMUTIL_GSTATE_bg currentblackgeneration cvlit def + /AGMUTIL_GSTATE_ucr currentundercolorremoval cvlit def + currentcolortransfer cvlit/AGMUTIL_GSTATE_gy_xfer xdf cvlit/AGMUTIL_GSTATE_b_xfer xdf + cvlit/AGMUTIL_GSTATE_g_xfer xdf cvlit/AGMUTIL_GSTATE_r_xfer xdf + /AGMUTIL_GSTATE_ht currenthalftone def + /AGMUTIL_GSTATE_flt currentflat def + end +}def +/set_gstate +{ + AGMUTIL_GSTATE begin + AGMUTIL_GSTATE_clr_spc setcolorspace + AGMUTIL_GSTATE_clr_indx{AGMUTIL_GSTATE_clr_comps AGMUTIL_GSTATE_clr_indx 1 sub get + /AGMUTIL_GSTATE_clr_indx AGMUTIL_GSTATE_clr_indx 1 sub def}repeat setcolor + AGMUTIL_GSTATE_fnt setfont + AGMUTIL_GSTATE_lw setlinewidth + AGMUTIL_GSTATE_lc setlinecap + AGMUTIL_GSTATE_lj setlinejoin + AGMUTIL_GSTATE_ml setmiterlimit + AGMUTIL_GSTATE_da AGMUTIL_GSTATE_do setdash + AGMUTIL_GSTATE_sa setstrokeadjust + AGMUTIL_GSTATE_clr_rnd setcolorrendering + AGMUTIL_GSTATE_op setoverprint + AGMUTIL_GSTATE_bg cvx setblackgeneration + AGMUTIL_GSTATE_ucr cvx setundercolorremoval + AGMUTIL_GSTATE_r_xfer cvx AGMUTIL_GSTATE_g_xfer cvx AGMUTIL_GSTATE_b_xfer cvx + AGMUTIL_GSTATE_gy_xfer cvx setcolortransfer + AGMUTIL_GSTATE_ht/HalftoneType get dup 9 eq exch 100 eq or + { + currenthalftone/HalftoneType get AGMUTIL_GSTATE_ht/HalftoneType get ne + { + mark AGMUTIL_GSTATE_ht{sethalftone}stopped cleartomark + }if + }{ + AGMUTIL_GSTATE_ht sethalftone + }ifelse + AGMUTIL_GSTATE_flt setflat + end +}def +/get_gstate_and_matrix +{ + AGMUTIL_GSTATE begin + /AGMUTIL_GSTATE_ctm matrix currentmatrix def + end + get_gstate +}def +/set_gstate_and_matrix +{ + set_gstate + AGMUTIL_GSTATE begin + AGMUTIL_GSTATE_ctm setmatrix + end +}def +/AGMUTIL_str256 256 string def +/AGMUTIL_src256 256 string def +/AGMUTIL_dst64 64 string def +/AGMUTIL_srcLen nd +/AGMUTIL_ndx nd +/AGMUTIL_cpd nd +/capture_cpd{ + //Adobe_AGM_Utils/AGMUTIL_cpd currentpagedevice ddf +}def +/thold_halftone +{ + level3 + {sethalftone currenthalftone} + { + dup/HalftoneType get 3 eq + { + sethalftone currenthalftone + }{ + begin + Width Height mul{ + Thresholds read{pop}if + }repeat + end + currenthalftone + }ifelse + }ifelse +}def +/rdcmntline +{ + currentfile AGMUTIL_str256 readline pop + (%)anchorsearch{pop}if +}bdf +/filter_cmyk +{ + dup type/filetype ne{ + exch()/SubFileDecode filter + }{ + exch pop + } + ifelse + [ + exch + { + AGMUTIL_src256 readstring pop + dup length/AGMUTIL_srcLen exch def + /AGMUTIL_ndx 0 def + AGMCORE_plate_ndx 4 AGMUTIL_srcLen 1 sub{ + 1 index exch get + AGMUTIL_dst64 AGMUTIL_ndx 3 -1 roll put + /AGMUTIL_ndx AGMUTIL_ndx 1 add def + }for + pop + AGMUTIL_dst64 0 AGMUTIL_ndx getinterval + } + bind + /exec cvx + ]cvx +}bdf +/filter_indexed_devn +{ + cvi Names length mul names_index add Lookup exch get +}bdf +/filter_devn +{ + 4 dict begin + /srcStr xdf + /dstStr xdf + dup type/filetype ne{ + 0()/SubFileDecode filter + }if + [ + exch + [ + /devicen_colorspace_dict/AGMCORE_gget cvx/begin cvx + currentdict/srcStr get/readstring cvx/pop cvx + /dup cvx/length cvx 0/gt cvx[ + Adobe_AGM_Utils/AGMUTIL_ndx 0/ddf cvx + names_index Names length currentdict/srcStr get length 1 sub{ + 1/index cvx/exch cvx/get cvx + currentdict/dstStr get/AGMUTIL_ndx/load cvx 3 -1/roll cvx/put cvx + Adobe_AGM_Utils/AGMUTIL_ndx/AGMUTIL_ndx/load cvx 1/add cvx/ddf cvx + }for + currentdict/dstStr get 0/AGMUTIL_ndx/load cvx/getinterval cvx + ]cvx/if cvx + /end cvx + ]cvx + bind + /exec cvx + ]cvx + end +}bdf +/AGMUTIL_imagefile nd +/read_image_file +{ + AGMUTIL_imagefile 0 setfileposition + 10 dict begin + /imageDict xdf + /imbufLen Width BitsPerComponent mul 7 add 8 idiv def + /imbufIdx 0 def + /origDataSource imageDict/DataSource get def + /origMultipleDataSources imageDict/MultipleDataSources get def + /origDecode imageDict/Decode get def + /dstDataStr imageDict/Width get colorSpaceElemCnt mul string def + imageDict/MultipleDataSources known{MultipleDataSources}{false}ifelse + { + /imbufCnt imageDict/DataSource get length def + /imbufs imbufCnt array def + 0 1 imbufCnt 1 sub{ + /imbufIdx xdf + imbufs imbufIdx imbufLen string put + imageDict/DataSource get imbufIdx[AGMUTIL_imagefile imbufs imbufIdx get/readstring cvx/pop cvx]cvx put + }for + DeviceN_PS2{ + imageDict begin + /DataSource[DataSource/devn_sep_datasource cvx]cvx def + /MultipleDataSources false def + /Decode[0 1]def + end + }if + }{ + /imbuf imbufLen string def + Indexed_DeviceN level3 not and DeviceN_NoneName or{ + /srcDataStrs[imageDict begin + currentdict/MultipleDataSources known{MultipleDataSources{DataSource length}{1}ifelse}{1}ifelse + { + Width Decode length 2 div mul cvi string + }repeat + end]def + imageDict begin + /DataSource[AGMUTIL_imagefile Decode BitsPerComponent false 1/filter_indexed_devn load dstDataStr srcDataStrs devn_alt_datasource/exec cvx]cvx def + /Decode[0 1]def + end + }{ + imageDict/DataSource[1 string dup 0 AGMUTIL_imagefile Decode length 2 idiv string/readstring cvx/pop cvx names_index/get cvx/put cvx]cvx put + imageDict/Decode[0 1]put + }ifelse + }ifelse + imageDict exch + load exec + imageDict/DataSource origDataSource put + imageDict/MultipleDataSources origMultipleDataSources put + imageDict/Decode origDecode put + end +}bdf +/write_image_file +{ + begin + {(AGMUTIL_imagefile)(w+)file}stopped{ + false + }{ + Adobe_AGM_Utils/AGMUTIL_imagefile xddf + 2 dict begin + /imbufLen Width BitsPerComponent mul 7 add 8 idiv def + MultipleDataSources{DataSource 0 get}{DataSource}ifelse type/filetype eq{ + /imbuf imbufLen string def + }if + 1 1 Height MultipleDataSources not{Decode length 2 idiv mul}if{ + pop + MultipleDataSources{ + 0 1 DataSource length 1 sub{ + DataSource type dup + /arraytype eq{ + pop DataSource exch gx + }{ + /filetype eq{ + DataSource exch get imbuf readstring pop + }{ + DataSource exch get + }ifelse + }ifelse + AGMUTIL_imagefile exch writestring + }for + }{ + DataSource type dup + /arraytype eq{ + pop DataSource exec + }{ + /filetype eq{ + DataSource imbuf readstring pop + }{ + DataSource + }ifelse + }ifelse + AGMUTIL_imagefile exch writestring + }ifelse + }for + end + true + }ifelse + end +}bdf +/close_image_file +{ + AGMUTIL_imagefile closefile(AGMUTIL_imagefile)deletefile +}def +statusdict/product known userdict/AGMP_current_show known not and{ + /pstr statusdict/product get def + pstr(HP LaserJet 2200)eq + pstr(HP LaserJet 4000 Series)eq or + pstr(HP LaserJet 4050 Series )eq or + pstr(HP LaserJet 8000 Series)eq or + pstr(HP LaserJet 8100 Series)eq or + pstr(HP LaserJet 8150 Series)eq or + pstr(HP LaserJet 5000 Series)eq or + pstr(HP LaserJet 5100 Series)eq or + pstr(HP Color LaserJet 4500)eq or + pstr(HP Color LaserJet 4600)eq or + pstr(HP LaserJet 5Si)eq or + pstr(HP LaserJet 1200 Series)eq or + pstr(HP LaserJet 1300 Series)eq or + pstr(HP LaserJet 4100 Series)eq or + { + userdict/AGMP_current_show/show load put + userdict/show{ + currentcolorspace 0 get + /Pattern eq + {false charpath f} + {AGMP_current_show}ifelse + }put + }if + currentdict/pstr undef +}if +/consumeimagedata +{ + begin + AGMIMG_init_common + currentdict/MultipleDataSources known not + {/MultipleDataSources false def}if + MultipleDataSources + { + DataSource 0 get type + dup/filetype eq + { + 1 dict begin + /flushbuffer Width cvi string def + 1 1 Height cvi + { + pop + 0 1 DataSource length 1 sub + { + DataSource exch get + flushbuffer readstring pop pop + }for + }for + end + }if + dup/arraytype eq exch/packedarraytype eq or DataSource 0 get xcheck and + { + Width Height mul cvi + { + 0 1 DataSource length 1 sub + {dup DataSource exch gx length exch 0 ne{pop}if}for + dup 0 eq + {pop exit}if + sub dup 0 le + {exit}if + }loop + pop + }if + } + { + /DataSource load type + dup/filetype eq + { + 1 dict begin + /flushbuffer Width Decode length 2 idiv mul cvi string def + 1 1 Height{pop DataSource flushbuffer readstring pop pop}for + end + }if + dup/arraytype eq exch/packedarraytype eq or/DataSource load xcheck and + { + Height Width BitsPerComponent mul 8 BitsPerComponent sub add 8 idiv Decode length 2 idiv mul mul + { + DataSource length dup 0 eq + {pop exit}if + sub dup 0 le + {exit}if + }loop + pop + }if + }ifelse + end +}bdf +/addprocs +{ + 2{/exec load}repeat + 3 1 roll + [5 1 roll]bind cvx +}def +/modify_halftone_xfer +{ + currenthalftone dup length dict copy begin + currentdict 2 index known{ + 1 index load dup length dict copy begin + currentdict/TransferFunction known{ + /TransferFunction load + }{ + currenttransfer + }ifelse + addprocs/TransferFunction xdf + currentdict end def + currentdict end sethalftone + }{ + currentdict/TransferFunction known{ + /TransferFunction load + }{ + currenttransfer + }ifelse + addprocs/TransferFunction xdf + currentdict end sethalftone + pop + }ifelse +}def +/clonearray +{ + dup xcheck exch + dup length array exch + Adobe_AGM_Core/AGMCORE_tmp -1 ddf + { + Adobe_AGM_Core/AGMCORE_tmp 2 copy get 1 add ddf + dup type/dicttype eq + { + Adobe_AGM_Core/AGMCORE_tmp get + exch + clonedict + Adobe_AGM_Core/AGMCORE_tmp 4 -1 roll ddf + }if + dup type/arraytype eq + { + Adobe_AGM_Core/AGMCORE_tmp get exch + clonearray + Adobe_AGM_Core/AGMCORE_tmp 4 -1 roll ddf + }if + exch dup + Adobe_AGM_Core/AGMCORE_tmp get 4 -1 roll put + }forall + exch{cvx}if +}bdf +/clonedict +{ + dup length dict + begin + { + dup type/dicttype eq + {clonedict}if + dup type/arraytype eq + {clonearray}if + def + }forall + currentdict + end +}bdf +/DeviceN_PS2 +{ + /currentcolorspace AGMCORE_gget 0 get/DeviceN eq level3 not and +}bdf +/Indexed_DeviceN +{ + /indexed_colorspace_dict AGMCORE_gget dup null ne{ + dup/CSDBase known{ + /CSDBase get/CSD get_res/Names known + }{ + pop false + }ifelse + }{ + pop false + }ifelse +}bdf +/DeviceN_NoneName +{ + /Names where{ + pop + false Names + { + (None)eq or + }forall + }{ + false + }ifelse +}bdf +/DeviceN_PS2_inRip_seps +{ + /AGMCORE_in_rip_sep where + { + pop dup type dup/arraytype eq exch/packedarraytype eq or + { + dup 0 get/DeviceN eq level3 not and AGMCORE_in_rip_sep and + { + /currentcolorspace exch AGMCORE_gput + false + }{ + true + }ifelse + }{ + true + }ifelse + }{ + true + }ifelse +}bdf +/base_colorspace_type +{ + dup type/arraytype eq{0 get}if +}bdf +/currentdistillerparams where{pop currentdistillerparams/CoreDistVersion get 5000 lt}{true}ifelse +{ + /pdfmark_5{cleartomark}bind def +}{ + /pdfmark_5{pdfmark}bind def +}ifelse +/ReadBypdfmark_5 +{ + currentfile exch 0 exch/SubFileDecode filter + /currentdistillerparams where + {pop currentdistillerparams/CoreDistVersion get 5000 lt}{true}ifelse + {flushfile cleartomark} + {/PUT pdfmark}ifelse +}bdf +/xpdfm +{ + { + dup 0 get/Label eq + { + aload length[exch 1 add 1 roll/PAGELABEL + }{ + aload pop + [{ThisPage}<<5 -2 roll>>/PUT + }ifelse + pdfmark_5 + }forall +}bdf +/ds{ + Adobe_AGM_Utils begin +}bdf +/dt{ + currentdict Adobe_AGM_Utils eq{ + end + }if +}bdf +systemdict/setpacking known +{setpacking}if +%%EndResource +%%BeginResource: procset Adobe_AGM_Core 2.0 0 +%%Version: 2.0 0 +%%Copyright: Copyright(C)1997-2007 Adobe Systems, Inc. All Rights Reserved. +systemdict/setpacking known +{ + currentpacking + true setpacking +}if +userdict/Adobe_AGM_Core 209 dict dup begin put +/Adobe_AGM_Core_Id/Adobe_AGM_Core_2.0_0 def +/AGMCORE_str256 256 string def +/AGMCORE_save nd +/AGMCORE_graphicsave nd +/AGMCORE_c 0 def +/AGMCORE_m 0 def +/AGMCORE_y 0 def +/AGMCORE_k 0 def +/AGMCORE_cmykbuf 4 array def +/AGMCORE_screen[currentscreen]cvx def +/AGMCORE_tmp 0 def +/AGMCORE_&setgray nd +/AGMCORE_&setcolor nd +/AGMCORE_&setcolorspace nd +/AGMCORE_&setcmykcolor nd +/AGMCORE_cyan_plate nd +/AGMCORE_magenta_plate nd +/AGMCORE_yellow_plate nd +/AGMCORE_black_plate nd +/AGMCORE_plate_ndx nd +/AGMCORE_get_ink_data nd +/AGMCORE_is_cmyk_sep nd +/AGMCORE_host_sep nd +/AGMCORE_avoid_L2_sep_space nd +/AGMCORE_distilling nd +/AGMCORE_composite_job nd +/AGMCORE_producing_seps nd +/AGMCORE_ps_level -1 def +/AGMCORE_ps_version -1 def +/AGMCORE_environ_ok nd +/AGMCORE_CSD_cache 0 dict def +/AGMCORE_currentoverprint false def +/AGMCORE_deltaX nd +/AGMCORE_deltaY nd +/AGMCORE_name nd +/AGMCORE_sep_special nd +/AGMCORE_err_strings 4 dict def +/AGMCORE_cur_err nd +/AGMCORE_current_spot_alias false def +/AGMCORE_inverting false def +/AGMCORE_feature_dictCount nd +/AGMCORE_feature_opCount nd +/AGMCORE_feature_ctm nd +/AGMCORE_ConvertToProcess false def +/AGMCORE_Default_CTM matrix def +/AGMCORE_Default_PageSize nd +/AGMCORE_Default_flatness nd +/AGMCORE_currentbg nd +/AGMCORE_currentucr nd +/AGMCORE_pattern_paint_type 0 def +/knockout_unitsq nd +currentglobal true setglobal +[/CSA/Gradient/Procedure] +{ + /Generic/Category findresource dup length dict copy/Category defineresource pop +}forall +setglobal +/AGMCORE_key_known +{ + where{ + /Adobe_AGM_Core_Id known + }{ + false + }ifelse +}ndf +/flushinput +{ + save + 2 dict begin + /CompareBuffer 3 -1 roll def + /readbuffer 256 string def + mark + { + currentfile readbuffer{readline}stopped + {cleartomark mark} + { + not + {pop exit} + if + CompareBuffer eq + {exit} + if + }ifelse + }loop + cleartomark + end + restore +}bdf +/getspotfunction +{ + AGMCORE_screen exch pop exch pop + dup type/dicttype eq{ + dup/HalftoneType get 1 eq{ + /SpotFunction get + }{ + dup/HalftoneType get 2 eq{ + /GraySpotFunction get + }{ + pop + { + abs exch abs 2 copy add 1 gt{ + 1 sub dup mul exch 1 sub dup mul add 1 sub + }{ + dup mul exch dup mul add 1 exch sub + }ifelse + }bind + }ifelse + }ifelse + }if +}def +/np +{newpath}bdf +/clp_npth +{clip np}def +/eoclp_npth +{eoclip np}def +/npth_clp +{np clip}def +/graphic_setup +{ + /AGMCORE_graphicsave save store + concat + 0 setgray + 0 setlinecap + 0 setlinejoin + 1 setlinewidth + []0 setdash + 10 setmiterlimit + np + false setoverprint + false setstrokeadjust + //Adobe_AGM_Core/spot_alias gx + /Adobe_AGM_Image where{ + pop + Adobe_AGM_Image/spot_alias 2 copy known{ + gx + }{ + pop pop + }ifelse + }if + /sep_colorspace_dict null AGMCORE_gput + 100 dict begin + /dictstackcount countdictstack def + /showpage{}def + mark +}def +/graphic_cleanup +{ + cleartomark + dictstackcount 1 countdictstack 1 sub{end}for + end + AGMCORE_graphicsave restore +}def +/compose_error_msg +{ + grestoreall initgraphics + /Helvetica findfont 10 scalefont setfont + /AGMCORE_deltaY 100 def + /AGMCORE_deltaX 310 def + clippath pathbbox np pop pop 36 add exch 36 add exch moveto + 0 AGMCORE_deltaY rlineto AGMCORE_deltaX 0 rlineto + 0 AGMCORE_deltaY neg rlineto AGMCORE_deltaX neg 0 rlineto closepath + 0 AGMCORE_&setgray + gsave 1 AGMCORE_&setgray fill grestore + 1 setlinewidth gsave stroke grestore + currentpoint AGMCORE_deltaY 15 sub add exch 8 add exch moveto + /AGMCORE_deltaY 12 def + /AGMCORE_tmp 0 def + AGMCORE_err_strings exch get + { + dup 32 eq + { + pop + AGMCORE_str256 0 AGMCORE_tmp getinterval + stringwidth pop currentpoint pop add AGMCORE_deltaX 28 add gt + { + currentpoint AGMCORE_deltaY sub exch pop + clippath pathbbox pop pop pop 44 add exch moveto + }if + AGMCORE_str256 0 AGMCORE_tmp getinterval show( )show + 0 1 AGMCORE_str256 length 1 sub + { + AGMCORE_str256 exch 0 put + }for + /AGMCORE_tmp 0 def + }{ + AGMCORE_str256 exch AGMCORE_tmp xpt + /AGMCORE_tmp AGMCORE_tmp 1 add def + }ifelse + }forall +}bdf +/AGMCORE_CMYKDeviceNColorspaces[ + [/Separation/None/DeviceCMYK{0 0 0}] + [/Separation(Black)/DeviceCMYK{0 0 0 4 -1 roll}bind] + [/Separation(Yellow)/DeviceCMYK{0 0 3 -1 roll 0}bind] + [/DeviceN[(Yellow)(Black)]/DeviceCMYK{0 0 4 2 roll}bind] + [/Separation(Magenta)/DeviceCMYK{0 exch 0 0}bind] + [/DeviceN[(Magenta)(Black)]/DeviceCMYK{0 3 1 roll 0 exch}bind] + [/DeviceN[(Magenta)(Yellow)]/DeviceCMYK{0 3 1 roll 0}bind] + [/DeviceN[(Magenta)(Yellow)(Black)]/DeviceCMYK{0 4 1 roll}bind] + [/Separation(Cyan)/DeviceCMYK{0 0 0}] + [/DeviceN[(Cyan)(Black)]/DeviceCMYK{0 0 3 -1 roll}bind] + [/DeviceN[(Cyan)(Yellow)]/DeviceCMYK{0 exch 0}bind] + [/DeviceN[(Cyan)(Yellow)(Black)]/DeviceCMYK{0 3 1 roll}bind] + [/DeviceN[(Cyan)(Magenta)]/DeviceCMYK{0 0}] + [/DeviceN[(Cyan)(Magenta)(Black)]/DeviceCMYK{0 exch}bind] + [/DeviceN[(Cyan)(Magenta)(Yellow)]/DeviceCMYK{0}] + [/DeviceCMYK] +]def +/ds{ + Adobe_AGM_Core begin + /currentdistillerparams where + { + pop currentdistillerparams/CoreDistVersion get 5000 lt + {<>setdistillerparams}if + }if + /AGMCORE_ps_version xdf + /AGMCORE_ps_level xdf + errordict/AGM_handleerror known not{ + errordict/AGM_handleerror errordict/handleerror get put + errordict/handleerror{ + Adobe_AGM_Core begin + $error/newerror get AGMCORE_cur_err null ne and{ + $error/newerror false put + AGMCORE_cur_err compose_error_msg + }if + $error/newerror true put + end + errordict/AGM_handleerror get exec + }bind put + }if + /AGMCORE_environ_ok + ps_level AGMCORE_ps_level ge + ps_version AGMCORE_ps_version ge and + AGMCORE_ps_level -1 eq or + def + AGMCORE_environ_ok not + {/AGMCORE_cur_err/AGMCORE_bad_environ def}if + /AGMCORE_&setgray systemdict/setgray get def + level2{ + /AGMCORE_&setcolor systemdict/setcolor get def + /AGMCORE_&setcolorspace systemdict/setcolorspace get def + }if + /AGMCORE_currentbg currentblackgeneration def + /AGMCORE_currentucr currentundercolorremoval def + /AGMCORE_Default_flatness currentflat def + /AGMCORE_distilling + /product where{ + pop systemdict/setdistillerparams known product(Adobe PostScript Parser)ne and + }{ + false + }ifelse + def + /AGMCORE_GSTATE AGMCORE_key_known not{ + /AGMCORE_GSTATE 21 dict def + /AGMCORE_tmpmatrix matrix def + /AGMCORE_gstack 32 array def + /AGMCORE_gstackptr 0 def + /AGMCORE_gstacksaveptr 0 def + /AGMCORE_gstackframekeys 14 def + /AGMCORE_&gsave/gsave ldf + /AGMCORE_&grestore/grestore ldf + /AGMCORE_&grestoreall/grestoreall ldf + /AGMCORE_&save/save ldf + /AGMCORE_&setoverprint/setoverprint ldf + /AGMCORE_gdictcopy{ + begin + {def}forall + end + }def + /AGMCORE_gput{ + AGMCORE_gstack AGMCORE_gstackptr get + 3 1 roll + put + }def + /AGMCORE_gget{ + AGMCORE_gstack AGMCORE_gstackptr get + exch + get + }def + /gsave{ + AGMCORE_&gsave + AGMCORE_gstack AGMCORE_gstackptr get + AGMCORE_gstackptr 1 add + dup 32 ge{limitcheck}if + /AGMCORE_gstackptr exch store + AGMCORE_gstack AGMCORE_gstackptr get + AGMCORE_gdictcopy + }def + /grestore{ + AGMCORE_&grestore + AGMCORE_gstackptr 1 sub + dup AGMCORE_gstacksaveptr lt{1 add}if + dup AGMCORE_gstack exch get dup/AGMCORE_currentoverprint known + {/AGMCORE_currentoverprint get setoverprint}{pop}ifelse + /AGMCORE_gstackptr exch store + }def + /grestoreall{ + AGMCORE_&grestoreall + /AGMCORE_gstackptr AGMCORE_gstacksaveptr store + }def + /save{ + AGMCORE_&save + AGMCORE_gstack AGMCORE_gstackptr get + AGMCORE_gstackptr 1 add + dup 32 ge{limitcheck}if + /AGMCORE_gstackptr exch store + /AGMCORE_gstacksaveptr AGMCORE_gstackptr store + AGMCORE_gstack AGMCORE_gstackptr get + AGMCORE_gdictcopy + }def + /setoverprint{ + dup/AGMCORE_currentoverprint exch AGMCORE_gput AGMCORE_&setoverprint + }def + 0 1 AGMCORE_gstack length 1 sub{ + AGMCORE_gstack exch AGMCORE_gstackframekeys dict put + }for + }if + level3/AGMCORE_&sysshfill AGMCORE_key_known not and + { + /AGMCORE_&sysshfill systemdict/shfill get def + /AGMCORE_&sysmakepattern systemdict/makepattern get def + /AGMCORE_&usrmakepattern/makepattern load def + }if + /currentcmykcolor[0 0 0 0]AGMCORE_gput + /currentstrokeadjust false AGMCORE_gput + /currentcolorspace[/DeviceGray]AGMCORE_gput + /sep_tint 0 AGMCORE_gput + /devicen_tints[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]AGMCORE_gput + /sep_colorspace_dict null AGMCORE_gput + /devicen_colorspace_dict null AGMCORE_gput + /indexed_colorspace_dict null AGMCORE_gput + /currentcolor_intent()AGMCORE_gput + /customcolor_tint 1 AGMCORE_gput + /absolute_colorimetric_crd null AGMCORE_gput + /relative_colorimetric_crd null AGMCORE_gput + /saturation_crd null AGMCORE_gput + /perceptual_crd null AGMCORE_gput + currentcolortransfer cvlit/AGMCore_gray_xfer xdf cvlit/AGMCore_b_xfer xdf + cvlit/AGMCore_g_xfer xdf cvlit/AGMCore_r_xfer xdf + << + /MaxPatternItem currentsystemparams/MaxPatternCache get + >> + setuserparams + end +}def +/ps +{ + /setcmykcolor where{ + pop + Adobe_AGM_Core/AGMCORE_&setcmykcolor/setcmykcolor load put + }if + Adobe_AGM_Core begin + /setcmykcolor + { + 4 copy AGMCORE_cmykbuf astore/currentcmykcolor exch AGMCORE_gput + 1 sub 4 1 roll + 3{ + 3 index add neg dup 0 lt{ + pop 0 + }if + 3 1 roll + }repeat + setrgbcolor pop + }ndf + /currentcmykcolor + { + /currentcmykcolor AGMCORE_gget aload pop + }ndf + /setoverprint + {pop}ndf + /currentoverprint + {false}ndf + /AGMCORE_cyan_plate 1 0 0 0 test_cmyk_color_plate def + /AGMCORE_magenta_plate 0 1 0 0 test_cmyk_color_plate def + /AGMCORE_yellow_plate 0 0 1 0 test_cmyk_color_plate def + /AGMCORE_black_plate 0 0 0 1 test_cmyk_color_plate def + /AGMCORE_plate_ndx + AGMCORE_cyan_plate{ + 0 + }{ + AGMCORE_magenta_plate{ + 1 + }{ + AGMCORE_yellow_plate{ + 2 + }{ + AGMCORE_black_plate{ + 3 + }{ + 4 + }ifelse + }ifelse + }ifelse + }ifelse + def + /AGMCORE_have_reported_unsupported_color_space false def + /AGMCORE_report_unsupported_color_space + { + AGMCORE_have_reported_unsupported_color_space false eq + { + (Warning: Job contains content that cannot be separated with on-host methods. This content appears on the black plate, and knocks out all other plates.)== + Adobe_AGM_Core/AGMCORE_have_reported_unsupported_color_space true ddf + }if + }def + /AGMCORE_composite_job + AGMCORE_cyan_plate AGMCORE_magenta_plate and AGMCORE_yellow_plate and AGMCORE_black_plate and def + /AGMCORE_in_rip_sep + /AGMCORE_in_rip_sep where{ + pop AGMCORE_in_rip_sep + }{ + AGMCORE_distilling + { + false + }{ + userdict/Adobe_AGM_OnHost_Seps known{ + false + }{ + level2{ + currentpagedevice/Separations 2 copy known{ + get + }{ + pop pop false + }ifelse + }{ + false + }ifelse + }ifelse + }ifelse + }ifelse + def + /AGMCORE_producing_seps AGMCORE_composite_job not AGMCORE_in_rip_sep or def + /AGMCORE_host_sep AGMCORE_producing_seps AGMCORE_in_rip_sep not and def + /AGM_preserve_spots + /AGM_preserve_spots where{ + pop AGM_preserve_spots + }{ + AGMCORE_distilling AGMCORE_producing_seps or + }ifelse + def + /AGM_is_distiller_preserving_spotimages + { + currentdistillerparams/PreserveOverprintSettings known + { + currentdistillerparams/PreserveOverprintSettings get + { + currentdistillerparams/ColorConversionStrategy known + { + currentdistillerparams/ColorConversionStrategy get + /sRGB ne + }{ + true + }ifelse + }{ + false + }ifelse + }{ + false + }ifelse + }def + /convert_spot_to_process where{pop}{ + /convert_spot_to_process + { + //Adobe_AGM_Core begin + dup map_alias{ + /Name get exch pop + }if + dup dup(None)eq exch(All)eq or + { + pop false + }{ + AGMCORE_host_sep + { + gsave + 1 0 0 0 setcmykcolor currentgray 1 exch sub + 0 1 0 0 setcmykcolor currentgray 1 exch sub + 0 0 1 0 setcmykcolor currentgray 1 exch sub + 0 0 0 1 setcmykcolor currentgray 1 exch sub + add add add 0 eq + { + pop false + }{ + false setoverprint + current_spot_alias false set_spot_alias + 1 1 1 1 6 -1 roll findcmykcustomcolor 1 setcustomcolor + set_spot_alias + currentgray 1 ne + }ifelse + grestore + }{ + AGMCORE_distilling + { + pop AGM_is_distiller_preserving_spotimages not + }{ + //Adobe_AGM_Core/AGMCORE_name xddf + false + //Adobe_AGM_Core/AGMCORE_pattern_paint_type get 0 eq + AGMUTIL_cpd/OverrideSeparations known and + { + AGMUTIL_cpd/OverrideSeparations get + { + /HqnSpots/ProcSet resourcestatus + { + pop pop pop true + }if + }if + }if + { + AGMCORE_name/HqnSpots/ProcSet findresource/TestSpot gx not + }{ + gsave + [/Separation AGMCORE_name/DeviceGray{}]AGMCORE_&setcolorspace + false + AGMUTIL_cpd/SeparationColorNames 2 copy known + { + get + {AGMCORE_name eq or}forall + not + }{ + pop pop pop true + }ifelse + grestore + }ifelse + }ifelse + }ifelse + }ifelse + end + }def + }ifelse + /convert_to_process where{pop}{ + /convert_to_process + { + dup length 0 eq + { + pop false + }{ + AGMCORE_host_sep + { + dup true exch + { + dup(Cyan)eq exch + dup(Magenta)eq 3 -1 roll or exch + dup(Yellow)eq 3 -1 roll or exch + dup(Black)eq 3 -1 roll or + {pop} + {convert_spot_to_process and}ifelse + } + forall + { + true exch + { + dup(Cyan)eq exch + dup(Magenta)eq 3 -1 roll or exch + dup(Yellow)eq 3 -1 roll or exch + (Black)eq or and + }forall + not + }{pop false}ifelse + }{ + false exch + { + /PhotoshopDuotoneList where{pop false}{true}ifelse + { + dup(Cyan)eq exch + dup(Magenta)eq 3 -1 roll or exch + dup(Yellow)eq 3 -1 roll or exch + dup(Black)eq 3 -1 roll or + {pop} + {convert_spot_to_process or}ifelse + } + { + convert_spot_to_process or + } + ifelse + } + forall + }ifelse + }ifelse + }def + }ifelse + /AGMCORE_avoid_L2_sep_space + version cvr 2012 lt + level2 and + AGMCORE_producing_seps not and + def + /AGMCORE_is_cmyk_sep + AGMCORE_cyan_plate AGMCORE_magenta_plate or AGMCORE_yellow_plate or AGMCORE_black_plate or + def + /AGM_avoid_0_cmyk where{ + pop AGM_avoid_0_cmyk + }{ + AGM_preserve_spots + userdict/Adobe_AGM_OnHost_Seps known + userdict/Adobe_AGM_InRip_Seps known or + not and + }ifelse + { + /setcmykcolor[ + { + 4 copy add add add 0 eq currentoverprint and{ + pop 0.0005 + }if + }/exec cvx + /AGMCORE_&setcmykcolor load dup type/operatortype ne{ + /exec cvx + }if + ]cvx def + }if + /AGMCORE_IsSeparationAProcessColor + { + dup(Cyan)eq exch dup(Magenta)eq exch dup(Yellow)eq exch(Black)eq or or or + }def + AGMCORE_host_sep{ + /setcolortransfer + { + AGMCORE_cyan_plate{ + pop pop pop + }{ + AGMCORE_magenta_plate{ + 4 3 roll pop pop pop + }{ + AGMCORE_yellow_plate{ + 4 2 roll pop pop pop + }{ + 4 1 roll pop pop pop + }ifelse + }ifelse + }ifelse + settransfer + } + def + /AGMCORE_get_ink_data + AGMCORE_cyan_plate{ + {pop pop pop} + }{ + AGMCORE_magenta_plate{ + {4 3 roll pop pop pop} + }{ + AGMCORE_yellow_plate{ + {4 2 roll pop pop pop} + }{ + {4 1 roll pop pop pop} + }ifelse + }ifelse + }ifelse + def + /AGMCORE_RemoveProcessColorNames + { + 1 dict begin + /filtername + { + dup/Cyan eq 1 index(Cyan)eq or + {pop(_cyan_)}if + dup/Magenta eq 1 index(Magenta)eq or + {pop(_magenta_)}if + dup/Yellow eq 1 index(Yellow)eq or + {pop(_yellow_)}if + dup/Black eq 1 index(Black)eq or + {pop(_black_)}if + }def + dup type/arraytype eq + {[exch{filtername}forall]} + {filtername}ifelse + end + }def + level3{ + /AGMCORE_IsCurrentColor + { + dup AGMCORE_IsSeparationAProcessColor + { + AGMCORE_plate_ndx 0 eq + {dup(Cyan)eq exch/Cyan eq or}if + AGMCORE_plate_ndx 1 eq + {dup(Magenta)eq exch/Magenta eq or}if + AGMCORE_plate_ndx 2 eq + {dup(Yellow)eq exch/Yellow eq or}if + AGMCORE_plate_ndx 3 eq + {dup(Black)eq exch/Black eq or}if + AGMCORE_plate_ndx 4 eq + {pop false}if + }{ + gsave + false setoverprint + current_spot_alias false set_spot_alias + 1 1 1 1 6 -1 roll findcmykcustomcolor 1 setcustomcolor + set_spot_alias + currentgray 1 ne + grestore + }ifelse + }def + /AGMCORE_filter_functiondatasource + { + 5 dict begin + /data_in xdf + data_in type/stringtype eq + { + /ncomp xdf + /comp xdf + /string_out data_in length ncomp idiv string def + 0 ncomp data_in length 1 sub + { + string_out exch dup ncomp idiv exch data_in exch ncomp getinterval comp get 255 exch sub put + }for + string_out + }{ + string/string_in xdf + /string_out 1 string def + /component xdf + [ + data_in string_in/readstring cvx + [component/get cvx 255/exch cvx/sub cvx string_out/exch cvx 0/exch cvx/put cvx string_out]cvx + [/pop cvx()]cvx/ifelse cvx + ]cvx/ReusableStreamDecode filter + }ifelse + end + }def + /AGMCORE_separateShadingFunction + { + 2 dict begin + /paint? xdf + /channel xdf + dup type/dicttype eq + { + begin + FunctionType 0 eq + { + /DataSource channel Range length 2 idiv DataSource AGMCORE_filter_functiondatasource def + currentdict/Decode known + {/Decode Decode channel 2 mul 2 getinterval def}if + paint? not + {/Decode[1 1]def}if + }if + FunctionType 2 eq + { + paint? + { + /C0[C0 channel get 1 exch sub]def + /C1[C1 channel get 1 exch sub]def + }{ + /C0[1]def + /C1[1]def + }ifelse + }if + FunctionType 3 eq + { + /Functions[Functions{channel paint? AGMCORE_separateShadingFunction}forall]def + }if + currentdict/Range known + {/Range[0 1]def}if + currentdict + end}{ + channel get 0 paint? AGMCORE_separateShadingFunction + }ifelse + end + }def + /AGMCORE_separateShading + { + 3 -1 roll begin + currentdict/Function known + { + currentdict/Background known + {[1 index{Background 3 index get 1 exch sub}{1}ifelse]/Background xdf}if + Function 3 1 roll AGMCORE_separateShadingFunction/Function xdf + /ColorSpace[/DeviceGray]def + }{ + ColorSpace dup type/arraytype eq{0 get}if/DeviceCMYK eq + { + /ColorSpace[/DeviceN[/_cyan_/_magenta_/_yellow_/_black_]/DeviceCMYK{}]def + }{ + ColorSpace dup 1 get AGMCORE_RemoveProcessColorNames 1 exch put + }ifelse + ColorSpace 0 get/Separation eq + { + { + [1/exch cvx/sub cvx]cvx + }{ + [/pop cvx 1]cvx + }ifelse + ColorSpace 3 3 -1 roll put + pop + }{ + { + [exch ColorSpace 1 get length 1 sub exch sub/index cvx 1/exch cvx/sub cvx ColorSpace 1 get length 1 add 1/roll cvx ColorSpace 1 get length{/pop cvx}repeat]cvx + }{ + pop[ColorSpace 1 get length{/pop cvx}repeat cvx 1]cvx + }ifelse + ColorSpace 3 3 -1 roll bind put + }ifelse + ColorSpace 2/DeviceGray put + }ifelse + end + }def + /AGMCORE_separateShadingDict + { + dup/ColorSpace get + dup type/arraytype ne + {[exch]}if + dup 0 get/DeviceCMYK eq + { + exch begin + currentdict + AGMCORE_cyan_plate + {0 true}if + AGMCORE_magenta_plate + {1 true}if + AGMCORE_yellow_plate + {2 true}if + AGMCORE_black_plate + {3 true}if + AGMCORE_plate_ndx 4 eq + {0 false}if + dup not currentoverprint and + {/AGMCORE_ignoreshade true def}if + AGMCORE_separateShading + currentdict + end exch + }if + dup 0 get/Separation eq + { + exch begin + ColorSpace 1 get dup/None ne exch/All ne and + { + ColorSpace 1 get AGMCORE_IsCurrentColor AGMCORE_plate_ndx 4 lt and ColorSpace 1 get AGMCORE_IsSeparationAProcessColor not and + { + ColorSpace 2 get dup type/arraytype eq{0 get}if/DeviceCMYK eq + { + /ColorSpace + [ + /Separation + ColorSpace 1 get + /DeviceGray + [ + ColorSpace 3 get/exec cvx + 4 AGMCORE_plate_ndx sub -1/roll cvx + 4 1/roll cvx + 3[/pop cvx]cvx/repeat cvx + 1/exch cvx/sub cvx + ]cvx + ]def + }{ + AGMCORE_report_unsupported_color_space + AGMCORE_black_plate not + { + currentdict 0 false AGMCORE_separateShading + }if + }ifelse + }{ + currentdict ColorSpace 1 get AGMCORE_IsCurrentColor + 0 exch + dup not currentoverprint and + {/AGMCORE_ignoreshade true def}if + AGMCORE_separateShading + }ifelse + }if + currentdict + end exch + }if + dup 0 get/DeviceN eq + { + exch begin + ColorSpace 1 get convert_to_process + { + ColorSpace 2 get dup type/arraytype eq{0 get}if/DeviceCMYK eq + { + /ColorSpace + [ + /DeviceN + ColorSpace 1 get + /DeviceGray + [ + ColorSpace 3 get/exec cvx + 4 AGMCORE_plate_ndx sub -1/roll cvx + 4 1/roll cvx + 3[/pop cvx]cvx/repeat cvx + 1/exch cvx/sub cvx + ]cvx + ]def + }{ + AGMCORE_report_unsupported_color_space + AGMCORE_black_plate not + { + currentdict 0 false AGMCORE_separateShading + /ColorSpace[/DeviceGray]def + }if + }ifelse + }{ + currentdict + false -1 ColorSpace 1 get + { + AGMCORE_IsCurrentColor + { + 1 add + exch pop true exch exit + }if + 1 add + }forall + exch + dup not currentoverprint and + {/AGMCORE_ignoreshade true def}if + AGMCORE_separateShading + }ifelse + currentdict + end exch + }if + dup 0 get dup/DeviceCMYK eq exch dup/Separation eq exch/DeviceN eq or or not + { + exch begin + ColorSpace dup type/arraytype eq + {0 get}if + /DeviceGray ne + { + AGMCORE_report_unsupported_color_space + AGMCORE_black_plate not + { + ColorSpace 0 get/CIEBasedA eq + { + /ColorSpace[/Separation/_ciebaseda_/DeviceGray{}]def + }if + ColorSpace 0 get dup/CIEBasedABC eq exch dup/CIEBasedDEF eq exch/DeviceRGB eq or or + { + /ColorSpace[/DeviceN[/_red_/_green_/_blue_]/DeviceRGB{}]def + }if + ColorSpace 0 get/CIEBasedDEFG eq + { + /ColorSpace[/DeviceN[/_cyan_/_magenta_/_yellow_/_black_]/DeviceCMYK{}]def + }if + currentdict 0 false AGMCORE_separateShading + }if + }if + currentdict + end exch + }if + pop + dup/AGMCORE_ignoreshade known + { + begin + /ColorSpace[/Separation(None)/DeviceGray{}]def + currentdict end + }if + }def + /shfill + { + AGMCORE_separateShadingDict + dup/AGMCORE_ignoreshade known + {pop} + {AGMCORE_&sysshfill}ifelse + }def + /makepattern + { + exch + dup/PatternType get 2 eq + { + clonedict + begin + /Shading Shading AGMCORE_separateShadingDict def + Shading/AGMCORE_ignoreshade known + currentdict end exch + {pop<>}if + exch AGMCORE_&sysmakepattern + }{ + exch AGMCORE_&usrmakepattern + }ifelse + }def + }if + }if + AGMCORE_in_rip_sep{ + /setcustomcolor + { + exch aload pop + dup 7 1 roll inRip_spot_has_ink not { + 4{4 index mul 4 1 roll} + repeat + /DeviceCMYK setcolorspace + 6 -2 roll pop pop + }{ + //Adobe_AGM_Core begin + /AGMCORE_k xdf/AGMCORE_y xdf/AGMCORE_m xdf/AGMCORE_c xdf + end + [/Separation 4 -1 roll/DeviceCMYK + {dup AGMCORE_c mul exch dup AGMCORE_m mul exch dup AGMCORE_y mul exch AGMCORE_k mul} + ] + setcolorspace + }ifelse + setcolor + }ndf + /setseparationgray + { + [/Separation(All)/DeviceGray{}]setcolorspace_opt + 1 exch sub setcolor + }ndf + }{ + /setseparationgray + { + AGMCORE_&setgray + }ndf + }ifelse + /findcmykcustomcolor + { + 5 makereadonlyarray + }ndf + /setcustomcolor + { + exch aload pop pop + 4{4 index mul 4 1 roll}repeat + setcmykcolor pop + }ndf + /has_color + /colorimage where{ + AGMCORE_producing_seps{ + pop true + }{ + systemdict eq + }ifelse + }{ + false + }ifelse + def + /map_index + { + 1 index mul exch getinterval{255 div}forall + }bdf + /map_indexed_devn + { + Lookup Names length 3 -1 roll cvi map_index + }bdf + /n_color_components + { + base_colorspace_type + dup/DeviceGray eq{ + pop 1 + }{ + /DeviceCMYK eq{ + 4 + }{ + 3 + }ifelse + }ifelse + }bdf + level2{ + /mo/moveto ldf + /li/lineto ldf + /cv/curveto ldf + /knockout_unitsq + { + 1 setgray + 0 0 1 1 rectfill + }def + level2/setcolorspace AGMCORE_key_known not and{ + /AGMCORE_&&&setcolorspace/setcolorspace ldf + /AGMCORE_ReplaceMappedColor + { + dup type dup/arraytype eq exch/packedarraytype eq or + { + /AGMCORE_SpotAliasAry2 where{ + begin + dup 0 get dup/Separation eq + { + pop + dup length array copy + dup dup 1 get + current_spot_alias + { + dup map_alias + { + false set_spot_alias + dup 1 exch setsepcolorspace + true set_spot_alias + begin + /sep_colorspace_dict currentdict AGMCORE_gput + pop pop pop + [ + /Separation Name + CSA map_csa + MappedCSA + /sep_colorspace_proc load + ] + dup Name + end + }if + }if + map_reserved_ink_name 1 xpt + }{ + /DeviceN eq + { + dup length array copy + dup dup 1 get[ + exch{ + current_spot_alias{ + dup map_alias{ + /Name get exch pop + }if + }if + map_reserved_ink_name + }forall + ]1 xpt + }if + }ifelse + end + }if + }if + }def + /setcolorspace + { + dup type dup/arraytype eq exch/packedarraytype eq or + { + dup 0 get/Indexed eq + { + AGMCORE_distilling + { + /PhotoshopDuotoneList where + { + pop false + }{ + true + }ifelse + }{ + true + }ifelse + { + aload pop 3 -1 roll + AGMCORE_ReplaceMappedColor + 3 1 roll 4 array astore + }if + }{ + AGMCORE_ReplaceMappedColor + }ifelse + }if + DeviceN_PS2_inRip_seps{AGMCORE_&&&setcolorspace}if + }def + }if + }{ + /adj + { + currentstrokeadjust{ + transform + 0.25 sub round 0.25 add exch + 0.25 sub round 0.25 add exch + itransform + }if + }def + /mo{ + adj moveto + }def + /li{ + adj lineto + }def + /cv{ + 6 2 roll adj + 6 2 roll adj + 6 2 roll adj curveto + }def + /knockout_unitsq + { + 1 setgray + 8 8 1[8 0 0 8 0 0]{}image + }def + /currentstrokeadjust{ + /currentstrokeadjust AGMCORE_gget + }def + /setstrokeadjust{ + /currentstrokeadjust exch AGMCORE_gput + }def + /setcolorspace + { + /currentcolorspace exch AGMCORE_gput + }def + /currentcolorspace + { + /currentcolorspace AGMCORE_gget + }def + /setcolor_devicecolor + { + base_colorspace_type + dup/DeviceGray eq{ + pop setgray + }{ + /DeviceCMYK eq{ + setcmykcolor + }{ + setrgbcolor + }ifelse + }ifelse + }def + /setcolor + { + currentcolorspace 0 get + dup/DeviceGray ne{ + dup/DeviceCMYK ne{ + dup/DeviceRGB ne{ + dup/Separation eq{ + pop + currentcolorspace 3 gx + currentcolorspace 2 get + }{ + dup/Indexed eq{ + pop + currentcolorspace 3 get dup type/stringtype eq{ + currentcolorspace 1 get n_color_components + 3 -1 roll map_index + }{ + exec + }ifelse + currentcolorspace 1 get + }{ + /AGMCORE_cur_err/AGMCORE_invalid_color_space def + AGMCORE_invalid_color_space + }ifelse + }ifelse + }if + }if + }if + setcolor_devicecolor + }def + }ifelse + /sop/setoverprint ldf + /lw/setlinewidth ldf + /lc/setlinecap ldf + /lj/setlinejoin ldf + /ml/setmiterlimit ldf + /dsh/setdash ldf + /sadj/setstrokeadjust ldf + /gry/setgray ldf + /rgb/setrgbcolor ldf + /cmyk[ + /currentcolorspace[/DeviceCMYK]/AGMCORE_gput cvx + /setcmykcolor load dup type/operatortype ne{/exec cvx}if + ]cvx bdf + level3 AGMCORE_host_sep not and{ + /nzopmsc{ + 6 dict begin + /kk exch def + /yy exch def + /mm exch def + /cc exch def + /sum 0 def + cc 0 ne{/sum sum 2#1000 or def cc}if + mm 0 ne{/sum sum 2#0100 or def mm}if + yy 0 ne{/sum sum 2#0010 or def yy}if + kk 0 ne{/sum sum 2#0001 or def kk}if + AGMCORE_CMYKDeviceNColorspaces sum get setcolorspace + sum 0 eq{0}if + end + setcolor + }bdf + }{ + /nzopmsc/cmyk ldf + }ifelse + /sep/setsepcolor ldf + /devn/setdevicencolor ldf + /idx/setindexedcolor ldf + /colr/setcolor ldf + /csacrd/set_csa_crd ldf + /sepcs/setsepcolorspace ldf + /devncs/setdevicencolorspace ldf + /idxcs/setindexedcolorspace ldf + /cp/closepath ldf + /clp/clp_npth ldf + /eclp/eoclp_npth ldf + /f/fill ldf + /ef/eofill ldf + /@/stroke ldf + /nclp/npth_clp ldf + /gset/graphic_setup ldf + /gcln/graphic_cleanup ldf + /ct/concat ldf + /cf/currentfile ldf + /fl/filter ldf + /rs/readstring ldf + /AGMCORE_def_ht currenthalftone def + /clonedict Adobe_AGM_Utils begin/clonedict load end def + /clonearray Adobe_AGM_Utils begin/clonearray load end def + currentdict{ + dup xcheck 1 index type dup/arraytype eq exch/packedarraytype eq or and{ + bind + }if + def + }forall + /getrampcolor + { + /indx exch def + 0 1 NumComp 1 sub + { + dup + Samples exch get + dup type/stringtype eq{indx get}if + exch + Scaling exch get aload pop + 3 1 roll + mul add + }for + ColorSpaceFamily/Separation eq + {sep} + { + ColorSpaceFamily/DeviceN eq + {devn}{setcolor}ifelse + }ifelse + }bdf + /sssetbackground{ + aload pop + ColorSpaceFamily/Separation eq + {sep} + { + ColorSpaceFamily/DeviceN eq + {devn}{setcolor}ifelse + }ifelse + }bdf + /RadialShade + { + 40 dict begin + /ColorSpaceFamily xdf + /background xdf + /ext1 xdf + /ext0 xdf + /BBox xdf + /r2 xdf + /c2y xdf + /c2x xdf + /r1 xdf + /c1y xdf + /c1x xdf + /rampdict xdf + /setinkoverprint where{pop/setinkoverprint{pop}def}if + gsave + BBox length 0 gt + { + np + BBox 0 get BBox 1 get moveto + BBox 2 get BBox 0 get sub 0 rlineto + 0 BBox 3 get BBox 1 get sub rlineto + BBox 2 get BBox 0 get sub neg 0 rlineto + closepath + clip + np + }if + c1x c2x eq + { + c1y c2y lt{/theta 90 def}{/theta 270 def}ifelse + }{ + /slope c2y c1y sub c2x c1x sub div def + /theta slope 1 atan def + c2x c1x lt c2y c1y ge and{/theta theta 180 sub def}if + c2x c1x lt c2y c1y lt and{/theta theta 180 add def}if + }ifelse + gsave + clippath + c1x c1y translate + theta rotate + -90 rotate + {pathbbox}stopped + {0 0 0 0}if + /yMax xdf + /xMax xdf + /yMin xdf + /xMin xdf + grestore + xMax xMin eq yMax yMin eq or + { + grestore + end + }{ + /max{2 copy gt{pop}{exch pop}ifelse}bdf + /min{2 copy lt{pop}{exch pop}ifelse}bdf + rampdict begin + 40 dict begin + background length 0 gt{background sssetbackground gsave clippath fill grestore}if + gsave + c1x c1y translate + theta rotate + -90 rotate + /c2y c1x c2x sub dup mul c1y c2y sub dup mul add sqrt def + /c1y 0 def + /c1x 0 def + /c2x 0 def + ext0 + { + 0 getrampcolor + c2y r2 add r1 sub 0.0001 lt + { + c1x c1y r1 360 0 arcn + pathbbox + /aymax exch def + /axmax exch def + /aymin exch def + /axmin exch def + /bxMin xMin axmin min def + /byMin yMin aymin min def + /bxMax xMax axmax max def + /byMax yMax aymax max def + bxMin byMin moveto + bxMax byMin lineto + bxMax byMax lineto + bxMin byMax lineto + bxMin byMin lineto + eofill + }{ + c2y r1 add r2 le + { + c1x c1y r1 0 360 arc + fill + } + { + c2x c2y r2 0 360 arc fill + r1 r2 eq + { + /p1x r1 neg def + /p1y c1y def + /p2x r1 def + /p2y c1y def + p1x p1y moveto p2x p2y lineto p2x yMin lineto p1x yMin lineto + fill + }{ + /AA r2 r1 sub c2y div def + AA -1 eq + {/theta 89.99 def} + {/theta AA 1 AA dup mul sub sqrt div 1 atan def} + ifelse + /SS1 90 theta add dup sin exch cos div def + /p1x r1 SS1 SS1 mul SS1 SS1 mul 1 add div sqrt mul neg def + /p1y p1x SS1 div neg def + /SS2 90 theta sub dup sin exch cos div def + /p2x r1 SS2 SS2 mul SS2 SS2 mul 1 add div sqrt mul def + /p2y p2x SS2 div neg def + r1 r2 gt + { + /L1maxX p1x yMin p1y sub SS1 div add def + /L2maxX p2x yMin p2y sub SS2 div add def + }{ + /L1maxX 0 def + /L2maxX 0 def + }ifelse + p1x p1y moveto p2x p2y lineto L2maxX L2maxX p2x sub SS2 mul p2y add lineto + L1maxX L1maxX p1x sub SS1 mul p1y add lineto + fill + }ifelse + }ifelse + }ifelse + }if + c1x c2x sub dup mul + c1y c2y sub dup mul + add 0.5 exp + 0 dtransform + dup mul exch dup mul add 0.5 exp 72 div + 0 72 matrix defaultmatrix dtransform dup mul exch dup mul add sqrt + 72 0 matrix defaultmatrix dtransform dup mul exch dup mul add sqrt + 1 index 1 index lt{exch}if pop + /hires xdf + hires mul + /numpix xdf + /numsteps NumSamples def + /rampIndxInc 1 def + /subsampling false def + numpix 0 ne + { + NumSamples numpix div 0.5 gt + { + /numsteps numpix 2 div round cvi dup 1 le{pop 2}if def + /rampIndxInc NumSamples 1 sub numsteps div def + /subsampling true def + }if + }if + /xInc c2x c1x sub numsteps div def + /yInc c2y c1y sub numsteps div def + /rInc r2 r1 sub numsteps div def + /cx c1x def + /cy c1y def + /radius r1 def + np + xInc 0 eq yInc 0 eq rInc 0 eq and and + { + 0 getrampcolor + cx cy radius 0 360 arc + stroke + NumSamples 1 sub getrampcolor + cx cy radius 72 hires div add 0 360 arc + 0 setlinewidth + stroke + }{ + 0 + numsteps + { + dup + subsampling{round cvi}if + getrampcolor + cx cy radius 0 360 arc + /cx cx xInc add def + /cy cy yInc add def + /radius radius rInc add def + cx cy radius 360 0 arcn + eofill + rampIndxInc add + }repeat + pop + }ifelse + ext1 + { + c2y r2 add r1 lt + { + c2x c2y r2 0 360 arc + fill + }{ + c2y r1 add r2 sub 0.0001 le + { + c2x c2y r2 360 0 arcn + pathbbox + /aymax exch def + /axmax exch def + /aymin exch def + /axmin exch def + /bxMin xMin axmin min def + /byMin yMin aymin min def + /bxMax xMax axmax max def + /byMax yMax aymax max def + bxMin byMin moveto + bxMax byMin lineto + bxMax byMax lineto + bxMin byMax lineto + bxMin byMin lineto + eofill + }{ + c2x c2y r2 0 360 arc fill + r1 r2 eq + { + /p1x r2 neg def + /p1y c2y def + /p2x r2 def + /p2y c2y def + p1x p1y moveto p2x p2y lineto p2x yMax lineto p1x yMax lineto + fill + }{ + /AA r2 r1 sub c2y div def + AA -1 eq + {/theta 89.99 def} + {/theta AA 1 AA dup mul sub sqrt div 1 atan def} + ifelse + /SS1 90 theta add dup sin exch cos div def + /p1x r2 SS1 SS1 mul SS1 SS1 mul 1 add div sqrt mul neg def + /p1y c2y p1x SS1 div sub def + /SS2 90 theta sub dup sin exch cos div def + /p2x r2 SS2 SS2 mul SS2 SS2 mul 1 add div sqrt mul def + /p2y c2y p2x SS2 div sub def + r1 r2 lt + { + /L1maxX p1x yMax p1y sub SS1 div add def + /L2maxX p2x yMax p2y sub SS2 div add def + }{ + /L1maxX 0 def + /L2maxX 0 def + }ifelse + p1x p1y moveto p2x p2y lineto L2maxX L2maxX p2x sub SS2 mul p2y add lineto + L1maxX L1maxX p1x sub SS1 mul p1y add lineto + fill + }ifelse + }ifelse + }ifelse + }if + grestore + grestore + end + end + end + }ifelse + }bdf + /GenStrips + { + 40 dict begin + /ColorSpaceFamily xdf + /background xdf + /ext1 xdf + /ext0 xdf + /BBox xdf + /y2 xdf + /x2 xdf + /y1 xdf + /x1 xdf + /rampdict xdf + /setinkoverprint where{pop/setinkoverprint{pop}def}if + gsave + BBox length 0 gt + { + np + BBox 0 get BBox 1 get moveto + BBox 2 get BBox 0 get sub 0 rlineto + 0 BBox 3 get BBox 1 get sub rlineto + BBox 2 get BBox 0 get sub neg 0 rlineto + closepath + clip + np + }if + x1 x2 eq + { + y1 y2 lt{/theta 90 def}{/theta 270 def}ifelse + }{ + /slope y2 y1 sub x2 x1 sub div def + /theta slope 1 atan def + x2 x1 lt y2 y1 ge and{/theta theta 180 sub def}if + x2 x1 lt y2 y1 lt and{/theta theta 180 add def}if + } + ifelse + gsave + clippath + x1 y1 translate + theta rotate + {pathbbox}stopped + {0 0 0 0}if + /yMax exch def + /xMax exch def + /yMin exch def + /xMin exch def + grestore + xMax xMin eq yMax yMin eq or + { + grestore + end + }{ + rampdict begin + 20 dict begin + background length 0 gt{background sssetbackground gsave clippath fill grestore}if + gsave + x1 y1 translate + theta rotate + /xStart 0 def + /xEnd x2 x1 sub dup mul y2 y1 sub dup mul add 0.5 exp def + /ySpan yMax yMin sub def + /numsteps NumSamples def + /rampIndxInc 1 def + /subsampling false def + xStart 0 transform + xEnd 0 transform + 3 -1 roll + sub dup mul + 3 1 roll + sub dup mul + add 0.5 exp 72 div + 0 72 matrix defaultmatrix dtransform dup mul exch dup mul add sqrt + 72 0 matrix defaultmatrix dtransform dup mul exch dup mul add sqrt + 1 index 1 index lt{exch}if pop + mul + /numpix xdf + numpix 0 ne + { + NumSamples numpix div 0.5 gt + { + /numsteps numpix 2 div round cvi dup 1 le{pop 2}if def + /rampIndxInc NumSamples 1 sub numsteps div def + /subsampling true def + }if + }if + ext0 + { + 0 getrampcolor + xMin xStart lt + { + xMin yMin xMin neg ySpan rectfill + }if + }if + /xInc xEnd xStart sub numsteps div def + /x xStart def + 0 + numsteps + { + dup + subsampling{round cvi}if + getrampcolor + x yMin xInc ySpan rectfill + /x x xInc add def + rampIndxInc add + }repeat + pop + ext1{ + xMax xEnd gt + { + xEnd yMin xMax xEnd sub ySpan rectfill + }if + }if + grestore + grestore + end + end + end + }ifelse + }bdf +}def +/pt +{ + end +}def +/dt{ +}def +/pgsv{ + //Adobe_AGM_Core/AGMCORE_save save put +}def +/pgrs{ + //Adobe_AGM_Core/AGMCORE_save get restore +}def +systemdict/findcolorrendering known{ + /findcolorrendering systemdict/findcolorrendering get def +}if +systemdict/setcolorrendering known{ + /setcolorrendering systemdict/setcolorrendering get def +}if +/test_cmyk_color_plate +{ + gsave + setcmykcolor currentgray 1 ne + grestore +}def +/inRip_spot_has_ink +{ + dup//Adobe_AGM_Core/AGMCORE_name xddf + convert_spot_to_process not +}def +/map255_to_range +{ + 1 index sub + 3 -1 roll 255 div mul add +}def +/set_csa_crd +{ + /sep_colorspace_dict null AGMCORE_gput + begin + CSA get_csa_by_name setcolorspace_opt + set_crd + end +} +def +/map_csa +{ + currentdict/MappedCSA known{MappedCSA null ne}{false}ifelse + {pop}{get_csa_by_name/MappedCSA xdf}ifelse +}def +/setsepcolor +{ + /sep_colorspace_dict AGMCORE_gget begin + dup/sep_tint exch AGMCORE_gput + TintProc + end +}def +/setdevicencolor +{ + /devicen_colorspace_dict AGMCORE_gget begin + Names length copy + Names length 1 sub -1 0 + { + /devicen_tints AGMCORE_gget 3 1 roll xpt + }for + TintProc + end +}def +/sep_colorspace_proc +{ + /AGMCORE_tmp exch store + /sep_colorspace_dict AGMCORE_gget begin + currentdict/Components known{ + Components aload pop + TintMethod/Lab eq{ + 2{AGMCORE_tmp mul NComponents 1 roll}repeat + LMax sub AGMCORE_tmp mul LMax add NComponents 1 roll + }{ + TintMethod/Subtractive eq{ + NComponents{ + AGMCORE_tmp mul NComponents 1 roll + }repeat + }{ + NComponents{ + 1 sub AGMCORE_tmp mul 1 add NComponents 1 roll + }repeat + }ifelse + }ifelse + }{ + ColorLookup AGMCORE_tmp ColorLookup length 1 sub mul round cvi get + aload pop + }ifelse + end +}def +/sep_colorspace_gray_proc +{ + /AGMCORE_tmp exch store + /sep_colorspace_dict AGMCORE_gget begin + GrayLookup AGMCORE_tmp GrayLookup length 1 sub mul round cvi get + end +}def +/sep_proc_name +{ + dup 0 get + dup/DeviceRGB eq exch/DeviceCMYK eq or level2 not and has_color not and{ + pop[/DeviceGray] + /sep_colorspace_gray_proc + }{ + /sep_colorspace_proc + }ifelse +}def +/setsepcolorspace +{ + current_spot_alias{ + dup begin + Name map_alias{ + exch pop + }if + end + }if + dup/sep_colorspace_dict exch AGMCORE_gput + begin + CSA map_csa + /AGMCORE_sep_special Name dup()eq exch(All)eq or store + AGMCORE_avoid_L2_sep_space{ + [/Indexed MappedCSA sep_proc_name 255 exch + {255 div}/exec cvx 3 -1 roll[4 1 roll load/exec cvx]cvx + ]setcolorspace_opt + /TintProc{ + 255 mul round cvi setcolor + }bdf + }{ + MappedCSA 0 get/DeviceCMYK eq + currentdict/Components known and + AGMCORE_sep_special not and{ + /TintProc[ + Components aload pop Name findcmykcustomcolor + /exch cvx/setcustomcolor cvx + ]cvx bdf + }{ + AGMCORE_host_sep Name(All)eq and{ + /TintProc{ + 1 exch sub setseparationgray + }bdf + }{ + AGMCORE_in_rip_sep MappedCSA 0 get/DeviceCMYK eq and + AGMCORE_host_sep or + Name()eq and{ + /TintProc[ + MappedCSA sep_proc_name exch 0 get/DeviceCMYK eq{ + cvx/setcmykcolor cvx + }{ + cvx/setgray cvx + }ifelse + ]cvx bdf + }{ + AGMCORE_producing_seps MappedCSA 0 get dup/DeviceCMYK eq exch/DeviceGray eq or and AGMCORE_sep_special not and{ + /TintProc[ + /dup cvx + MappedCSA sep_proc_name cvx exch + 0 get/DeviceGray eq{ + 1/exch cvx/sub cvx 0 0 0 4 -1/roll cvx + }if + /Name cvx/findcmykcustomcolor cvx/exch cvx + AGMCORE_host_sep{ + AGMCORE_is_cmyk_sep + /Name cvx + /AGMCORE_IsSeparationAProcessColor load/exec cvx + /not cvx/and cvx + }{ + Name inRip_spot_has_ink not + }ifelse + [ + /pop cvx 1 + ]cvx/if cvx + /setcustomcolor cvx + ]cvx bdf + }{ + /TintProc{setcolor}bdf + [/Separation Name MappedCSA sep_proc_name load]setcolorspace_opt + }ifelse + }ifelse + }ifelse + }ifelse + }ifelse + set_crd + setsepcolor + end +}def +/additive_blend +{ + 3 dict begin + /numarrays xdf + /numcolors xdf + 0 1 numcolors 1 sub + { + /c1 xdf + 1 + 0 1 numarrays 1 sub + { + 1 exch add/index cvx + c1/get cvx/mul cvx + }for + numarrays 1 add 1/roll cvx + }for + numarrays[/pop cvx]cvx/repeat cvx + end +}def +/subtractive_blend +{ + 3 dict begin + /numarrays xdf + /numcolors xdf + 0 1 numcolors 1 sub + { + /c1 xdf + 1 1 + 0 1 numarrays 1 sub + { + 1 3 3 -1 roll add/index cvx + c1/get cvx/sub cvx/mul cvx + }for + /sub cvx + numarrays 1 add 1/roll cvx + }for + numarrays[/pop cvx]cvx/repeat cvx + end +}def +/exec_tint_transform +{ + /TintProc[ + /TintTransform cvx/setcolor cvx + ]cvx bdf + MappedCSA setcolorspace_opt +}bdf +/devn_makecustomcolor +{ + 2 dict begin + /names_index xdf + /Names xdf + 1 1 1 1 Names names_index get findcmykcustomcolor + /devicen_tints AGMCORE_gget names_index get setcustomcolor + Names length{pop}repeat + end +}bdf +/setdevicencolorspace +{ + dup/AliasedColorants known{false}{true}ifelse + current_spot_alias and{ + 7 dict begin + /names_index 0 def + dup/names_len exch/Names get length def + /new_names names_len array def + /new_LookupTables names_len array def + /alias_cnt 0 def + dup/Names get + { + dup map_alias{ + exch pop + dup/ColorLookup known{ + dup begin + new_LookupTables names_index ColorLookup put + end + }{ + dup/Components known{ + dup begin + new_LookupTables names_index Components put + end + }{ + dup begin + new_LookupTables names_index[null null null null]put + end + }ifelse + }ifelse + new_names names_index 3 -1 roll/Name get put + /alias_cnt alias_cnt 1 add def + }{ + /name xdf + new_names names_index name put + dup/LookupTables known{ + dup begin + new_LookupTables names_index LookupTables names_index get put + end + }{ + dup begin + new_LookupTables names_index[null null null null]put + end + }ifelse + }ifelse + /names_index names_index 1 add def + }forall + alias_cnt 0 gt{ + /AliasedColorants true def + /lut_entry_len new_LookupTables 0 get dup length 256 ge{0 get length}{length}ifelse def + 0 1 names_len 1 sub{ + /names_index xdf + new_LookupTables names_index get dup length 256 ge{0 get length}{length}ifelse lut_entry_len ne{ + /AliasedColorants false def + exit + }{ + new_LookupTables names_index get 0 get null eq{ + dup/Names get names_index get/name xdf + name(Cyan)eq name(Magenta)eq name(Yellow)eq name(Black)eq + or or or not{ + /AliasedColorants false def + exit + }if + }if + }ifelse + }for + lut_entry_len 1 eq{ + /AliasedColorants false def + }if + AliasedColorants{ + dup begin + /Names new_names def + /LookupTables new_LookupTables def + /AliasedColorants true def + /NComponents lut_entry_len def + /TintMethod NComponents 4 eq{/Subtractive}{/Additive}ifelse def + /MappedCSA TintMethod/Additive eq{/DeviceRGB}{/DeviceCMYK}ifelse def + currentdict/TTTablesIdx known not{ + /TTTablesIdx -1 def + }if + end + }if + }if + end + }if + dup/devicen_colorspace_dict exch AGMCORE_gput + begin + currentdict/AliasedColorants known{ + AliasedColorants + }{ + false + }ifelse + dup not{ + CSA map_csa + }if + /TintTransform load type/nulltype eq or{ + /TintTransform[ + 0 1 Names length 1 sub + { + /TTTablesIdx TTTablesIdx 1 add def + dup LookupTables exch get dup 0 get null eq + { + 1 index + Names exch get + dup(Cyan)eq + { + pop exch + LookupTables length exch sub + /index cvx + 0 0 0 + } + { + dup(Magenta)eq + { + pop exch + LookupTables length exch sub + /index cvx + 0/exch cvx 0 0 + }{ + (Yellow)eq + { + exch + LookupTables length exch sub + /index cvx + 0 0 3 -1/roll cvx 0 + }{ + exch + LookupTables length exch sub + /index cvx + 0 0 0 4 -1/roll cvx + }ifelse + }ifelse + }ifelse + 5 -1/roll cvx/astore cvx + }{ + dup length 1 sub + LookupTables length 4 -1 roll sub 1 add + /index cvx/mul cvx/round cvx/cvi cvx/get cvx + }ifelse + Names length TTTablesIdx add 1 add 1/roll cvx + }for + Names length[/pop cvx]cvx/repeat cvx + NComponents Names length + TintMethod/Subtractive eq + { + subtractive_blend + }{ + additive_blend + }ifelse + ]cvx bdf + }if + AGMCORE_host_sep{ + Names convert_to_process{ + exec_tint_transform + } + { + currentdict/AliasedColorants known{ + AliasedColorants not + }{ + false + }ifelse + 5 dict begin + /AvoidAliasedColorants xdf + /painted? false def + /names_index 0 def + /names_len Names length def + AvoidAliasedColorants{ + /currentspotalias current_spot_alias def + false set_spot_alias + }if + Names{ + AGMCORE_is_cmyk_sep{ + dup(Cyan)eq AGMCORE_cyan_plate and exch + dup(Magenta)eq AGMCORE_magenta_plate and exch + dup(Yellow)eq AGMCORE_yellow_plate and exch + (Black)eq AGMCORE_black_plate and or or or{ + /devicen_colorspace_dict AGMCORE_gget/TintProc[ + Names names_index/devn_makecustomcolor cvx + ]cvx ddf + /painted? true def + }if + painted?{exit}if + }{ + 0 0 0 0 5 -1 roll findcmykcustomcolor 1 setcustomcolor currentgray 0 eq{ + /devicen_colorspace_dict AGMCORE_gget/TintProc[ + Names names_index/devn_makecustomcolor cvx + ]cvx ddf + /painted? true def + exit + }if + }ifelse + /names_index names_index 1 add def + }forall + AvoidAliasedColorants{ + currentspotalias set_spot_alias + }if + painted?{ + /devicen_colorspace_dict AGMCORE_gget/names_index names_index put + }{ + /devicen_colorspace_dict AGMCORE_gget/TintProc[ + names_len[/pop cvx]cvx/repeat cvx 1/setseparationgray cvx + 0 0 0 0/setcmykcolor cvx + ]cvx ddf + }ifelse + end + }ifelse + } + { + AGMCORE_in_rip_sep{ + Names convert_to_process not + }{ + level3 + }ifelse + { + [/DeviceN Names MappedCSA/TintTransform load]setcolorspace_opt + /TintProc level3 not AGMCORE_in_rip_sep and{ + [ + Names/length cvx[/pop cvx]cvx/repeat cvx + ]cvx bdf + }{ + {setcolor}bdf + }ifelse + }{ + exec_tint_transform + }ifelse + }ifelse + set_crd + /AliasedColorants false def + end +}def +/setindexedcolorspace +{ + dup/indexed_colorspace_dict exch AGMCORE_gput + begin + currentdict/CSDBase known{ + CSDBase/CSD get_res begin + currentdict/Names known{ + currentdict devncs + }{ + 1 currentdict sepcs + }ifelse + AGMCORE_host_sep{ + 4 dict begin + /compCnt/Names where{pop Names length}{1}ifelse def + /NewLookup HiVal 1 add string def + 0 1 HiVal{ + /tableIndex xdf + Lookup dup type/stringtype eq{ + compCnt tableIndex map_index + }{ + exec + }ifelse + /Names where{ + pop setdevicencolor + }{ + setsepcolor + }ifelse + currentgray + tableIndex exch + 255 mul cvi + NewLookup 3 1 roll put + }for + [/Indexed currentcolorspace HiVal NewLookup]setcolorspace_opt + end + }{ + level3 + { + currentdict/Names known{ + [/Indexed[/DeviceN Names MappedCSA/TintTransform load]HiVal Lookup]setcolorspace_opt + }{ + [/Indexed[/Separation Name MappedCSA sep_proc_name load]HiVal Lookup]setcolorspace_opt + }ifelse + }{ + [/Indexed MappedCSA HiVal + [ + currentdict/Names known{ + Lookup dup type/stringtype eq + {/exch cvx CSDBase/CSD get_res/Names get length dup/mul cvx exch/getinterval cvx{255 div}/forall cvx} + {/exec cvx}ifelse + /TintTransform load/exec cvx + }{ + Lookup dup type/stringtype eq + {/exch cvx/get cvx 255/div cvx} + {/exec cvx}ifelse + CSDBase/CSD get_res/MappedCSA get sep_proc_name exch pop/load cvx/exec cvx + }ifelse + ]cvx + ]setcolorspace_opt + }ifelse + }ifelse + end + set_crd + } + { + CSA map_csa + AGMCORE_host_sep level2 not and{ + 0 0 0 0 setcmykcolor + }{ + [/Indexed MappedCSA + level2 not has_color not and{ + dup 0 get dup/DeviceRGB eq exch/DeviceCMYK eq or{ + pop[/DeviceGray] + }if + HiVal GrayLookup + }{ + HiVal + currentdict/RangeArray known{ + { + /indexed_colorspace_dict AGMCORE_gget begin + Lookup exch + dup HiVal gt{ + pop HiVal + }if + NComponents mul NComponents getinterval{}forall + NComponents 1 sub -1 0{ + RangeArray exch 2 mul 2 getinterval aload pop map255_to_range + NComponents 1 roll + }for + end + }bind + }{ + Lookup + }ifelse + }ifelse + ]setcolorspace_opt + set_crd + }ifelse + }ifelse + end +}def +/setindexedcolor +{ + AGMCORE_host_sep{ + /indexed_colorspace_dict AGMCORE_gget + begin + currentdict/CSDBase known{ + CSDBase/CSD get_res begin + currentdict/Names known{ + map_indexed_devn + devn + } + { + Lookup 1 3 -1 roll map_index + sep + }ifelse + end + }{ + Lookup MappedCSA/DeviceCMYK eq{4}{1}ifelse 3 -1 roll + map_index + MappedCSA/DeviceCMYK eq{setcmykcolor}{setgray}ifelse + }ifelse + end + }{ + level3 not AGMCORE_in_rip_sep and/indexed_colorspace_dict AGMCORE_gget/CSDBase known and{ + /indexed_colorspace_dict AGMCORE_gget/CSDBase get/CSD get_res begin + map_indexed_devn + devn + end + } + { + setcolor + }ifelse + }ifelse +}def +/ignoreimagedata +{ + currentoverprint not{ + gsave + dup clonedict begin + 1 setgray + /Decode[0 1]def + /DataSourcedef + /MultipleDataSources false def + /BitsPerComponent 8 def + currentdict end + systemdict/image gx + grestore + }if + consumeimagedata +}def +/add_res +{ + dup/CSD eq{ + pop + //Adobe_AGM_Core begin + /AGMCORE_CSD_cache load 3 1 roll put + end + }{ + defineresource pop + }ifelse +}def +/del_res +{ + { + aload pop exch + dup/CSD eq{ + pop + {//Adobe_AGM_Core/AGMCORE_CSD_cache get exch undef}forall + }{ + exch + {1 index undefineresource}forall + pop + }ifelse + }forall +}def +/get_res +{ + dup/CSD eq{ + pop + dup type dup/nametype eq exch/stringtype eq or{ + AGMCORE_CSD_cache exch get + }if + }{ + findresource + }ifelse +}def +/get_csa_by_name +{ + dup type dup/nametype eq exch/stringtype eq or{ + /CSA get_res + }if +}def +/paintproc_buf_init +{ + /count get 0 0 put +}def +/paintproc_buf_next +{ + dup/count get dup 0 get + dup 3 1 roll + 1 add 0 xpt + get +}def +/cachepaintproc_compress +{ + 5 dict begin + currentfile exch 0 exch/SubFileDecode filter/ReadFilter exch def + /ppdict 20 dict def + /string_size 16000 def + /readbuffer string_size string def + currentglobal true setglobal + ppdict 1 array dup 0 1 put/count xpt + setglobal + /LZWFilter + { + exch + dup length 0 eq{ + pop + }{ + ppdict dup length 1 sub 3 -1 roll put + }ifelse + {string_size}{0}ifelse string + }/LZWEncode filter def + { + ReadFilter readbuffer readstring + exch LZWFilter exch writestring + not{exit}if + }loop + LZWFilter closefile + ppdict + end +}def +/cachepaintproc +{ + 2 dict begin + currentfile exch 0 exch/SubFileDecode filter/ReadFilter exch def + /ppdict 20 dict def + currentglobal true setglobal + ppdict 1 array dup 0 1 put/count xpt + setglobal + { + ReadFilter 16000 string readstring exch + ppdict dup length 1 sub 3 -1 roll put + not{exit}if + }loop + ppdict dup dup length 1 sub()put + end +}def +/make_pattern +{ + exch clonedict exch + dup matrix currentmatrix matrix concatmatrix 0 0 3 2 roll itransform + exch 3 index/XStep get 1 index exch 2 copy div cvi mul sub sub + exch 3 index/YStep get 1 index exch 2 copy div cvi mul sub sub + matrix translate exch matrix concatmatrix + 1 index begin + BBox 0 get XStep div cvi XStep mul/xshift exch neg def + BBox 1 get YStep div cvi YStep mul/yshift exch neg def + BBox 0 get xshift add + BBox 1 get yshift add + BBox 2 get xshift add + BBox 3 get yshift add + 4 array astore + /BBox exch def + [xshift yshift/translate load null/exec load]dup + 3/PaintProc load put cvx/PaintProc exch def + end + gsave 0 setgray + makepattern + grestore +}def +/set_pattern +{ + dup/PatternType get 1 eq{ + dup/PaintType get 1 eq{ + currentoverprint sop[/DeviceGray]setcolorspace 0 setgray + }if + }if + setpattern +}def +/setcolorspace_opt +{ + dup currentcolorspace eq{pop}{setcolorspace}ifelse +}def +/updatecolorrendering +{ + currentcolorrendering/RenderingIntent known{ + currentcolorrendering/RenderingIntent get + } + { + Intent/AbsoluteColorimetric eq + { + /absolute_colorimetric_crd AGMCORE_gget dup null eq + } + { + Intent/RelativeColorimetric eq + { + /relative_colorimetric_crd AGMCORE_gget dup null eq + } + { + Intent/Saturation eq + { + /saturation_crd AGMCORE_gget dup null eq + } + { + /perceptual_crd AGMCORE_gget dup null eq + }ifelse + }ifelse + }ifelse + { + pop null + } + { + /RenderingIntent known{null}{Intent}ifelse + }ifelse + }ifelse + Intent ne{ + Intent/ColorRendering{findresource}stopped + { + pop pop systemdict/findcolorrendering known + { + Intent findcolorrendering + { + /ColorRendering findresource true exch + } + { + /ColorRendering findresource + product(Xerox Phaser 5400)ne + exch + }ifelse + dup Intent/AbsoluteColorimetric eq + { + /absolute_colorimetric_crd exch AGMCORE_gput + } + { + Intent/RelativeColorimetric eq + { + /relative_colorimetric_crd exch AGMCORE_gput + } + { + Intent/Saturation eq + { + /saturation_crd exch AGMCORE_gput + } + { + Intent/Perceptual eq + { + /perceptual_crd exch AGMCORE_gput + } + { + pop + }ifelse + }ifelse + }ifelse + }ifelse + 1 index{exch}{pop}ifelse + } + {false}ifelse + } + {true}ifelse + { + dup begin + currentdict/TransformPQR known{ + currentdict/TransformPQR get aload pop + 3{{}eq 3 1 roll}repeat or or + } + {true}ifelse + currentdict/MatrixPQR known{ + currentdict/MatrixPQR get aload pop + 1.0 eq 9 1 roll 0.0 eq 9 1 roll 0.0 eq 9 1 roll + 0.0 eq 9 1 roll 1.0 eq 9 1 roll 0.0 eq 9 1 roll + 0.0 eq 9 1 roll 0.0 eq 9 1 roll 1.0 eq + and and and and and and and and + } + {true}ifelse + end + or + { + clonedict begin + /TransformPQR[ + {4 -1 roll 3 get dup 3 1 roll sub 5 -1 roll 3 get 3 -1 roll sub div + 3 -1 roll 3 get 3 -1 roll 3 get dup 4 1 roll sub mul add}bind + {4 -1 roll 4 get dup 3 1 roll sub 5 -1 roll 4 get 3 -1 roll sub div + 3 -1 roll 4 get 3 -1 roll 4 get dup 4 1 roll sub mul add}bind + {4 -1 roll 5 get dup 3 1 roll sub 5 -1 roll 5 get 3 -1 roll sub div + 3 -1 roll 5 get 3 -1 roll 5 get dup 4 1 roll sub mul add}bind + ]def + /MatrixPQR[0.8951 -0.7502 0.0389 0.2664 1.7135 -0.0685 -0.1614 0.0367 1.0296]def + /RangePQR[-0.3227950745 2.3229645538 -1.5003771057 3.5003465881 -0.1369979095 2.136967392]def + currentdict end + }if + setcolorrendering_opt + }if + }if +}def +/set_crd +{ + AGMCORE_host_sep not level2 and{ + currentdict/ColorRendering known{ + ColorRendering/ColorRendering{findresource}stopped not{setcolorrendering_opt}if + }{ + currentdict/Intent known{ + updatecolorrendering + }if + }ifelse + currentcolorspace dup type/arraytype eq + {0 get}if + /DeviceRGB eq + { + currentdict/UCR known + {/UCR}{/AGMCORE_currentucr}ifelse + load setundercolorremoval + currentdict/BG known + {/BG}{/AGMCORE_currentbg}ifelse + load setblackgeneration + }if + }if +}def +/set_ucrbg +{ + dup null eq{pop/AGMCORE_currentbg load}{/Procedure get_res}ifelse setblackgeneration + dup null eq{pop/AGMCORE_currentucr load}{/Procedure get_res}ifelse setundercolorremoval +}def +/setcolorrendering_opt +{ + dup currentcolorrendering eq{ + pop + }{ + clonedict + begin + /Intent Intent def + currentdict + end + setcolorrendering + }ifelse +}def +/cpaint_gcomp +{ + convert_to_process//Adobe_AGM_Core/AGMCORE_ConvertToProcess xddf + //Adobe_AGM_Core/AGMCORE_ConvertToProcess get not + { + (%end_cpaint_gcomp)flushinput + }if +}def +/cpaint_gsep +{ + //Adobe_AGM_Core/AGMCORE_ConvertToProcess get + { + (%end_cpaint_gsep)flushinput + }if +}def +/cpaint_gend +{np}def +/T1_path +{ + currentfile token pop currentfile token pop mo + { + currentfile token pop dup type/stringtype eq + {pop exit}if + 0 exch rlineto + currentfile token pop dup type/stringtype eq + {pop exit}if + 0 rlineto + }loop +}def +/T1_gsave + level3 + {/clipsave} + {/gsave}ifelse + load def +/T1_grestore + level3 + {/cliprestore} + {/grestore}ifelse + load def +/set_spot_alias_ary +{ + dup inherit_aliases + //Adobe_AGM_Core/AGMCORE_SpotAliasAry xddf +}def +/set_spot_normalization_ary +{ + dup inherit_aliases + dup length + /AGMCORE_SpotAliasAry where{pop AGMCORE_SpotAliasAry length add}if + array + //Adobe_AGM_Core/AGMCORE_SpotAliasAry2 xddf + /AGMCORE_SpotAliasAry where{ + pop + AGMCORE_SpotAliasAry2 0 AGMCORE_SpotAliasAry putinterval + AGMCORE_SpotAliasAry length + }{0}ifelse + AGMCORE_SpotAliasAry2 3 1 roll exch putinterval + true set_spot_alias +}def +/inherit_aliases +{ + {dup/Name get map_alias{/CSD put}{pop}ifelse}forall +}def +/set_spot_alias +{ + /AGMCORE_SpotAliasAry2 where{ + /AGMCORE_current_spot_alias 3 -1 roll put + }{ + pop + }ifelse +}def +/current_spot_alias +{ + /AGMCORE_SpotAliasAry2 where{ + /AGMCORE_current_spot_alias get + }{ + false + }ifelse +}def +/map_alias +{ + /AGMCORE_SpotAliasAry2 where{ + begin + /AGMCORE_name xdf + false + AGMCORE_SpotAliasAry2{ + dup/Name get AGMCORE_name eq{ + /CSD get/CSD get_res + exch pop true + exit + }{ + pop + }ifelse + }forall + end + }{ + pop false + }ifelse +}bdf +/spot_alias +{ + true set_spot_alias + /AGMCORE_&setcustomcolor AGMCORE_key_known not{ + //Adobe_AGM_Core/AGMCORE_&setcustomcolor/setcustomcolor load put + }if + /customcolor_tint 1 AGMCORE_gput + //Adobe_AGM_Core begin + /setcustomcolor + { + //Adobe_AGM_Core begin + dup/customcolor_tint exch AGMCORE_gput + 1 index aload pop pop 1 eq exch 1 eq and exch 1 eq and exch 1 eq and not + current_spot_alias and{1 index 4 get map_alias}{false}ifelse + { + false set_spot_alias + /sep_colorspace_dict AGMCORE_gget null ne + 3 1 roll 2 index{ + exch pop/sep_tint AGMCORE_gget exch + }if + mark 3 1 roll + setsepcolorspace + counttomark 0 ne{ + setsepcolor + }if + pop + not{/sep_tint 1.0 AGMCORE_gput}if + pop + true set_spot_alias + }{ + AGMCORE_&setcustomcolor + }ifelse + end + }bdf + end +}def +/begin_feature +{ + Adobe_AGM_Core/AGMCORE_feature_dictCount countdictstack put + count Adobe_AGM_Core/AGMCORE_feature_opCount 3 -1 roll put + {Adobe_AGM_Core/AGMCORE_feature_ctm matrix currentmatrix put}if +}def +/end_feature +{ + 2 dict begin + /spd/setpagedevice load def + /setpagedevice{get_gstate spd set_gstate}def + stopped{$error/newerror false put}if + end + count Adobe_AGM_Core/AGMCORE_feature_opCount get sub dup 0 gt{{pop}repeat}{pop}ifelse + countdictstack Adobe_AGM_Core/AGMCORE_feature_dictCount get sub dup 0 gt{{end}repeat}{pop}ifelse + {Adobe_AGM_Core/AGMCORE_feature_ctm get setmatrix}if +}def +/set_negative +{ + //Adobe_AGM_Core begin + /AGMCORE_inverting exch def + level2{ + currentpagedevice/NegativePrint known AGMCORE_distilling not and{ + currentpagedevice/NegativePrint get//Adobe_AGM_Core/AGMCORE_inverting get ne{ + true begin_feature true{ + <>setpagedevice + }end_feature + }if + /AGMCORE_inverting false def + }if + }if + AGMCORE_inverting{ + [{1 exch sub}/exec load dup currenttransfer exch]cvx bind settransfer + AGMCORE_distilling{ + erasepage + }{ + gsave np clippath 1/setseparationgray where{pop setseparationgray}{setgray}ifelse + /AGMIRS_&fill where{pop AGMIRS_&fill}{fill}ifelse grestore + }ifelse + }if + end +}def +/lw_save_restore_override{ + /md where{ + pop + md begin + initializepage + /initializepage{}def + /pmSVsetup{}def + /endp{}def + /pse{}def + /psb{}def + /orig_showpage where + {pop} + {/orig_showpage/showpage load def} + ifelse + /showpage{orig_showpage gR}def + end + }if +}def +/pscript_showpage_override{ + /NTPSOct95 where + { + begin + showpage + save + /showpage/restore load def + /restore{exch pop}def + end + }if +}def +/driver_media_override +{ + /md where{ + pop + md/initializepage known{ + md/initializepage{}put + }if + md/rC known{ + md/rC{4{pop}repeat}put + }if + }if + /mysetup where{ + /mysetup[1 0 0 1 0 0]put + }if + Adobe_AGM_Core/AGMCORE_Default_CTM matrix currentmatrix put + level2 + {Adobe_AGM_Core/AGMCORE_Default_PageSize currentpagedevice/PageSize get put}if +}def +/driver_check_media_override +{ + /PrepsDict where + {pop} + { + Adobe_AGM_Core/AGMCORE_Default_CTM get matrix currentmatrix ne + Adobe_AGM_Core/AGMCORE_Default_PageSize get type/arraytype eq + { + Adobe_AGM_Core/AGMCORE_Default_PageSize get 0 get currentpagedevice/PageSize get 0 get eq and + Adobe_AGM_Core/AGMCORE_Default_PageSize get 1 get currentpagedevice/PageSize get 1 get eq and + }if + { + Adobe_AGM_Core/AGMCORE_Default_CTM get setmatrix + }if + }ifelse +}def +AGMCORE_err_strings begin + /AGMCORE_bad_environ(Environment not satisfactory for this job. Ensure that the PPD is correct or that the PostScript level requested is supported by this printer. )def + /AGMCORE_color_space_onhost_seps(This job contains colors that will not separate with on-host methods. )def + /AGMCORE_invalid_color_space(This job contains an invalid color space. )def +end +/set_def_ht +{AGMCORE_def_ht sethalftone}def +/set_def_flat +{AGMCORE_Default_flatness setflat}def +end +systemdict/setpacking known +{setpacking}if +%%EndResource +%%BeginResource: procset Adobe_CoolType_Core 2.31 0 %%Copyright: Copyright 1997-2006 Adobe Systems Incorporated. All Rights Reserved. %%Version: 2.31 0 10 dict begin /Adobe_CoolType_Passthru currentdict def /Adobe_CoolType_Core_Defined userdict/Adobe_CoolType_Core known def Adobe_CoolType_Core_Defined {/Adobe_CoolType_Core userdict/Adobe_CoolType_Core get def} if userdict/Adobe_CoolType_Core 70 dict dup begin put /Adobe_CoolType_Version 2.31 def /Level2? systemdict/languagelevel known dup {pop systemdict/languagelevel get 2 ge} if def Level2? not { /currentglobal false def /setglobal/pop load def /gcheck{pop false}bind def /currentpacking false def /setpacking/pop load def /SharedFontDirectory 0 dict def } if currentpacking true setpacking currentglobal false setglobal userdict/Adobe_CoolType_Data 2 copy known not {2 copy 10 dict put} if get begin /@opStackCountByLevel 32 dict def /@opStackLevel 0 def /@dictStackCountByLevel 32 dict def /@dictStackLevel 0 def end setglobal currentglobal true setglobal userdict/Adobe_CoolType_GVMFonts known not {userdict/Adobe_CoolType_GVMFonts 10 dict put} if setglobal currentglobal false setglobal userdict/Adobe_CoolType_LVMFonts known not {userdict/Adobe_CoolType_LVMFonts 10 dict put} if setglobal /ct_VMDictPut { dup gcheck{Adobe_CoolType_GVMFonts}{Adobe_CoolType_LVMFonts}ifelse 3 1 roll put }bind def /ct_VMDictUndef { dup Adobe_CoolType_GVMFonts exch known {Adobe_CoolType_GVMFonts exch undef} { dup Adobe_CoolType_LVMFonts exch known {Adobe_CoolType_LVMFonts exch undef} {pop} ifelse }ifelse }bind def /ct_str1 1 string def /ct_xshow { /_ct_na exch def /_ct_i 0 def currentpoint /_ct_y exch def /_ct_x exch def { pop pop ct_str1 exch 0 exch put ct_str1 show {_ct_na _ct_i get}stopped {pop pop} { _ct_x _ct_y moveto 0 rmoveto } ifelse /_ct_i _ct_i 1 add def currentpoint /_ct_y exch def /_ct_x exch def } exch @cshow }bind def /ct_yshow { /_ct_na exch def /_ct_i 0 def currentpoint /_ct_y exch def /_ct_x exch def { pop pop ct_str1 exch 0 exch put ct_str1 show {_ct_na _ct_i get}stopped {pop pop} { _ct_x _ct_y moveto 0 exch rmoveto } ifelse /_ct_i _ct_i 1 add def currentpoint /_ct_y exch def /_ct_x exch def } exch @cshow }bind def /ct_xyshow { /_ct_na exch def /_ct_i 0 def currentpoint /_ct_y exch def /_ct_x exch def { pop pop ct_str1 exch 0 exch put ct_str1 show {_ct_na _ct_i get}stopped {pop pop} { {_ct_na _ct_i 1 add get}stopped {pop pop pop} { _ct_x _ct_y moveto rmoveto } ifelse } ifelse /_ct_i _ct_i 2 add def currentpoint /_ct_y exch def /_ct_x exch def } exch @cshow }bind def /xsh{{@xshow}stopped{Adobe_CoolType_Data begin ct_xshow end}if}bind def /ysh{{@yshow}stopped{Adobe_CoolType_Data begin ct_yshow end}if}bind def /xysh{{@xyshow}stopped{Adobe_CoolType_Data begin ct_xyshow end}if}bind def currentglobal true setglobal /ct_T3Defs { /BuildChar { 1 index/Encoding get exch get 1 index/BuildGlyph get exec }bind def /BuildGlyph { exch begin GlyphProcs exch get exec end }bind def }bind def setglobal /@_SaveStackLevels { Adobe_CoolType_Data begin /@vmState currentglobal def false setglobal @opStackCountByLevel @opStackLevel 2 copy known not { 2 copy 3 dict dup/args 7 index 5 add array put put get } { get dup/args get dup length 3 index lt { dup length 5 add array exch 1 index exch 0 exch putinterval 1 index exch/args exch put } {pop} ifelse } ifelse begin count 1 sub 1 index lt {pop count} if dup/argCount exch def dup 0 gt { args exch 0 exch getinterval astore pop } {pop} ifelse count /restCount exch def end /@opStackLevel @opStackLevel 1 add def countdictstack 1 sub @dictStackCountByLevel exch @dictStackLevel exch put /@dictStackLevel @dictStackLevel 1 add def @vmState setglobal end }bind def /@_RestoreStackLevels { Adobe_CoolType_Data begin /@opStackLevel @opStackLevel 1 sub def @opStackCountByLevel @opStackLevel get begin count restCount sub dup 0 gt {{pop}repeat} {pop} ifelse args 0 argCount getinterval{}forall end /@dictStackLevel @dictStackLevel 1 sub def @dictStackCountByLevel @dictStackLevel get end countdictstack exch sub dup 0 gt {{end}repeat} {pop} ifelse }bind def /@_PopStackLevels { Adobe_CoolType_Data begin /@opStackLevel @opStackLevel 1 sub def /@dictStackLevel @dictStackLevel 1 sub def end }bind def /@Raise { exch cvx exch errordict exch get exec stop }bind def /@ReRaise { cvx $error/errorname get errordict exch get exec stop }bind def /@Stopped { 0 @#Stopped }bind def /@#Stopped { @_SaveStackLevels stopped {@_RestoreStackLevels true} {@_PopStackLevels false} ifelse }bind def /@Arg { Adobe_CoolType_Data begin @opStackCountByLevel @opStackLevel 1 sub get begin args exch argCount 1 sub exch sub get end end }bind def currentglobal true setglobal /CTHasResourceForAllBug Level2? { 1 dict dup /@shouldNotDisappearDictValue true def Adobe_CoolType_Data exch/@shouldNotDisappearDict exch put begin count @_SaveStackLevels {(*){pop stop}128 string/Category resourceforall} stopped pop @_RestoreStackLevels currentdict Adobe_CoolType_Data/@shouldNotDisappearDict get dup 3 1 roll ne dup 3 1 roll { /@shouldNotDisappearDictValue known { { end currentdict 1 index eq {pop exit} if } loop } if } { pop end } ifelse } {false} ifelse def true setglobal /CTHasResourceStatusBug Level2? { mark {/steveamerige/Category resourcestatus} stopped {cleartomark true} {cleartomark currentglobal not} ifelse } {false} ifelse def setglobal /CTResourceStatus { mark 3 1 roll /Category findresource begin ({ResourceStatus}stopped)0()/SubFileDecode filter cvx exec {cleartomark false} {{3 2 roll pop true}{cleartomark false}ifelse} ifelse end }bind def /CTWorkAroundBugs { Level2? { /cid_PreLoad/ProcSet resourcestatus { pop pop currentglobal mark { (*) { dup/CMap CTHasResourceStatusBug {CTResourceStatus} {resourcestatus} ifelse { pop dup 0 eq exch 1 eq or { dup/CMap findresource gcheck setglobal /CMap undefineresource } { pop CTHasResourceForAllBug {exit} {stop} ifelse } ifelse } {pop} ifelse } 128 string/CMap resourceforall } stopped {cleartomark} stopped pop setglobal } if } if }bind def /ds { Adobe_CoolType_Core begin CTWorkAroundBugs /mo/moveto load def /nf/newencodedfont load def /msf{makefont setfont}bind def /uf{dup undefinefont ct_VMDictUndef}bind def /ur/undefineresource load def /chp/charpath load def /awsh/awidthshow load def /wsh/widthshow load def /ash/ashow load def /@xshow/xshow load def /@yshow/yshow load def /@xyshow/xyshow load def /@cshow/cshow load def /sh/show load def /rp/repeat load def /.n/.notdef def end currentglobal false setglobal userdict/Adobe_CoolType_Data 2 copy known not {2 copy 10 dict put} if get begin /AddWidths? false def /CC 0 def /charcode 2 string def /@opStackCountByLevel 32 dict def /@opStackLevel 0 def /@dictStackCountByLevel 32 dict def /@dictStackLevel 0 def /InVMFontsByCMap 10 dict def /InVMDeepCopiedFonts 10 dict def end setglobal }bind def /dt { currentdict Adobe_CoolType_Core eq {end} if }bind def /ps { Adobe_CoolType_Core begin Adobe_CoolType_GVMFonts begin Adobe_CoolType_LVMFonts begin SharedFontDirectory begin }bind def /pt { end end end end }bind def /unload { systemdict/languagelevel known { systemdict/languagelevel get 2 ge { userdict/Adobe_CoolType_Core 2 copy known {undef} {pop pop} ifelse } if } if }bind def /ndf { 1 index where {pop pop pop} {dup xcheck{bind}if def} ifelse }def /findfont systemdict begin userdict begin /globaldict where{/globaldict get begin}if dup where pop exch get /globaldict where{pop end}if end end Adobe_CoolType_Core_Defined {/systemfindfont exch def} { /findfont 1 index def /systemfindfont exch def } ifelse /undefinefont {pop}ndf /copyfont { currentglobal 3 1 roll 1 index gcheck setglobal dup null eq{0}{dup length}ifelse 2 index length add 1 add dict begin exch { 1 index/FID eq {pop pop} {def} ifelse } forall dup null eq {pop} {{def}forall} ifelse currentdict end exch setglobal }bind def /copyarray { currentglobal exch dup gcheck setglobal dup length array copy exch setglobal }bind def /newencodedfont { currentglobal { SharedFontDirectory 3 index known {SharedFontDirectory 3 index get/FontReferenced known} {false} ifelse } { FontDirectory 3 index known {FontDirectory 3 index get/FontReferenced known} { SharedFontDirectory 3 index known {SharedFontDirectory 3 index get/FontReferenced known} {false} ifelse } ifelse } ifelse dup { 3 index findfont/FontReferenced get 2 index dup type/nametype eq {findfont} if ne {pop false} if } if dup { 1 index dup type/nametype eq {findfont} if dup/CharStrings known { /CharStrings get length 4 index findfont/CharStrings get length ne { pop false } if } {pop} ifelse } if { pop 1 index findfont /Encoding get exch 0 1 255 {2 copy get 3 index 3 1 roll put} for pop pop pop } { currentglobal 4 1 roll dup type/nametype eq {findfont} if dup gcheck setglobal dup dup maxlength 2 add dict begin exch { 1 index/FID ne 2 index/Encoding ne and {def} {pop pop} ifelse } forall /FontReferenced exch def /Encoding exch dup length array copy def /FontName 1 index dup type/stringtype eq{cvn}if def dup currentdict end definefont ct_VMDictPut setglobal } ifelse }bind def /SetSubstituteStrategy { $SubstituteFont begin dup type/dicttype ne {0 dict} if currentdict/$Strategies known { exch $Strategies exch 2 copy known { get 2 copy maxlength exch maxlength add dict begin {def}forall {def}forall currentdict dup/$Init known {dup/$Init get exec} if end /$Strategy exch def } {pop pop pop} ifelse } {pop pop} ifelse end }bind def /scff { $SubstituteFont begin dup type/stringtype eq {dup length exch} {null} ifelse /$sname exch def /$slen exch def /$inVMIndex $sname null eq { 1 index $str cvs dup length $slen sub $slen getinterval cvn } {$sname} ifelse def end {findfont} @Stopped { dup length 8 add string exch 1 index 0(BadFont:)putinterval 1 index exch 8 exch dup length string cvs putinterval cvn {findfont} @Stopped {pop/Courier findfont} if } if $SubstituteFont begin /$sname null def /$slen 0 def /$inVMIndex null def end }bind def /isWidthsOnlyFont { dup/WidthsOnly known {pop pop true} { dup/FDepVector known {/FDepVector get{isWidthsOnlyFont dup{exit}if}forall} { dup/FDArray known {/FDArray get{isWidthsOnlyFont dup{exit}if}forall} {pop} ifelse } ifelse } ifelse }bind def /ct_StyleDicts 4 dict dup begin /Adobe-Japan1 4 dict dup begin Level2? { /Serif /HeiseiMin-W3-83pv-RKSJ-H/Font resourcestatus {pop pop/HeiseiMin-W3} { /CIDFont/Category resourcestatus { pop pop /HeiseiMin-W3/CIDFont resourcestatus {pop pop/HeiseiMin-W3} {/Ryumin-Light} ifelse } {/Ryumin-Light} ifelse } ifelse def /SansSerif /HeiseiKakuGo-W5-83pv-RKSJ-H/Font resourcestatus {pop pop/HeiseiKakuGo-W5} { /CIDFont/Category resourcestatus { pop pop /HeiseiKakuGo-W5/CIDFont resourcestatus {pop pop/HeiseiKakuGo-W5} {/GothicBBB-Medium} ifelse } {/GothicBBB-Medium} ifelse } ifelse def /HeiseiMaruGo-W4-83pv-RKSJ-H/Font resourcestatus {pop pop/HeiseiMaruGo-W4} { /CIDFont/Category resourcestatus { pop pop /HeiseiMaruGo-W4/CIDFont resourcestatus {pop pop/HeiseiMaruGo-W4} { /Jun101-Light-RKSJ-H/Font resourcestatus {pop pop/Jun101-Light} {SansSerif} ifelse } ifelse } { /Jun101-Light-RKSJ-H/Font resourcestatus {pop pop/Jun101-Light} {SansSerif} ifelse } ifelse } ifelse /RoundSansSerif exch def /Default Serif def } { /Serif/Ryumin-Light def /SansSerif/GothicBBB-Medium def { (fonts/Jun101-Light-83pv-RKSJ-H)status }stopped {pop}{ {pop pop pop pop/Jun101-Light} {SansSerif} ifelse /RoundSansSerif exch def }ifelse /Default Serif def } ifelse end def /Adobe-Korea1 4 dict dup begin /Serif/HYSMyeongJo-Medium def /SansSerif/HYGoThic-Medium def /RoundSansSerif SansSerif def /Default Serif def end def /Adobe-GB1 4 dict dup begin /Serif/STSong-Light def /SansSerif/STHeiti-Regular def /RoundSansSerif SansSerif def /Default Serif def end def /Adobe-CNS1 4 dict dup begin /Serif/MKai-Medium def /SansSerif/MHei-Medium def /RoundSansSerif SansSerif def /Default Serif def end def end def Level2?{currentglobal true setglobal}if /ct_BoldRomanWidthProc { stringwidth 1 index 0 ne{exch .03 add exch}if setcharwidth 0 0 }bind def /ct_Type0WidthProc { dup stringwidth 0 0 moveto 2 index true charpath pathbbox 0 -1 7 index 2 div .88 setcachedevice2 pop 0 0 }bind def /ct_Type0WMode1WidthProc { dup stringwidth pop 2 div neg -0.88 2 copy moveto 0 -1 5 -1 roll true charpath pathbbox setcachedevice }bind def /cHexEncoding [/c00/c01/c02/c03/c04/c05/c06/c07/c08/c09/c0A/c0B/c0C/c0D/c0E/c0F/c10/c11/c12 /c13/c14/c15/c16/c17/c18/c19/c1A/c1B/c1C/c1D/c1E/c1F/c20/c21/c22/c23/c24/c25 /c26/c27/c28/c29/c2A/c2B/c2C/c2D/c2E/c2F/c30/c31/c32/c33/c34/c35/c36/c37/c38 /c39/c3A/c3B/c3C/c3D/c3E/c3F/c40/c41/c42/c43/c44/c45/c46/c47/c48/c49/c4A/c4B /c4C/c4D/c4E/c4F/c50/c51/c52/c53/c54/c55/c56/c57/c58/c59/c5A/c5B/c5C/c5D/c5E /c5F/c60/c61/c62/c63/c64/c65/c66/c67/c68/c69/c6A/c6B/c6C/c6D/c6E/c6F/c70/c71 /c72/c73/c74/c75/c76/c77/c78/c79/c7A/c7B/c7C/c7D/c7E/c7F/c80/c81/c82/c83/c84 /c85/c86/c87/c88/c89/c8A/c8B/c8C/c8D/c8E/c8F/c90/c91/c92/c93/c94/c95/c96/c97 /c98/c99/c9A/c9B/c9C/c9D/c9E/c9F/cA0/cA1/cA2/cA3/cA4/cA5/cA6/cA7/cA8/cA9/cAA /cAB/cAC/cAD/cAE/cAF/cB0/cB1/cB2/cB3/cB4/cB5/cB6/cB7/cB8/cB9/cBA/cBB/cBC/cBD /cBE/cBF/cC0/cC1/cC2/cC3/cC4/cC5/cC6/cC7/cC8/cC9/cCA/cCB/cCC/cCD/cCE/cCF/cD0 /cD1/cD2/cD3/cD4/cD5/cD6/cD7/cD8/cD9/cDA/cDB/cDC/cDD/cDE/cDF/cE0/cE1/cE2/cE3 /cE4/cE5/cE6/cE7/cE8/cE9/cEA/cEB/cEC/cED/cEE/cEF/cF0/cF1/cF2/cF3/cF4/cF5/cF6 /cF7/cF8/cF9/cFA/cFB/cFC/cFD/cFE/cFF]def /ct_BoldBaseFont 11 dict begin /FontType 3 def /FontMatrix[1 0 0 1 0 0]def /FontBBox[0 0 1 1]def /Encoding cHexEncoding def /_setwidthProc/ct_BoldRomanWidthProc load def /_bcstr1 1 string def /BuildChar { exch begin _basefont setfont _bcstr1 dup 0 4 -1 roll put dup _setwidthProc 3 copy moveto show _basefonto setfont moveto show end }bind def currentdict end def systemdict/composefont known { /ct_DefineIdentity-H { /Identity-H/CMap resourcestatus { pop pop } { /CIDInit/ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo 3 dict dup begin /Registry(Adobe)def /Ordering(Identity)def /Supplement 0 def end def /CMapName/Identity-H def /CMapVersion 1.000 def /CMapType 1 def 1 begincodespacerange <0000> endcodespacerange 1 begincidrange <0000>0 endcidrange endcmap CMapName currentdict/CMap defineresource pop end end } ifelse } def /ct_BoldBaseCIDFont 11 dict begin /CIDFontType 1 def /CIDFontName/ct_BoldBaseCIDFont def /FontMatrix[1 0 0 1 0 0]def /FontBBox[0 0 1 1]def /_setwidthProc/ct_Type0WidthProc load def /_bcstr2 2 string def /BuildGlyph { exch begin _basefont setfont _bcstr2 1 2 index 256 mod put _bcstr2 0 3 -1 roll 256 idiv put _bcstr2 dup _setwidthProc 3 copy moveto show _basefonto setfont moveto show end }bind def currentdict end def }if Level2?{setglobal}if /ct_CopyFont{ { 1 index/FID ne 2 index/UniqueID ne and {def}{pop pop}ifelse }forall }bind def /ct_Type0CopyFont { exch dup length dict begin ct_CopyFont [ exch FDepVector { dup/FontType get 0 eq { 1 index ct_Type0CopyFont /_ctType0 exch definefont } { /_ctBaseFont exch 2 index exec } ifelse exch } forall pop ] /FDepVector exch def currentdict end }bind def /ct_MakeBoldFont { dup/ct_SyntheticBold known { dup length 3 add dict begin ct_CopyFont /ct_StrokeWidth .03 0 FontMatrix idtransform pop def /ct_SyntheticBold true def currentdict end definefont } { dup dup length 3 add dict begin ct_CopyFont /PaintType 2 def /StrokeWidth .03 0 FontMatrix idtransform pop def /dummybold currentdict end definefont dup/FontType get dup 9 ge exch 11 le and { ct_BoldBaseCIDFont dup length 3 add dict copy begin dup/CIDSystemInfo get/CIDSystemInfo exch def ct_DefineIdentity-H /_Type0Identity/Identity-H 3 -1 roll[exch]composefont /_basefont exch def /_Type0Identity/Identity-H 3 -1 roll[exch]composefont /_basefonto exch def currentdict end /CIDFont defineresource } { ct_BoldBaseFont dup length 3 add dict copy begin /_basefont exch def /_basefonto exch def currentdict end definefont } ifelse } ifelse }bind def /ct_MakeBold{ 1 index 1 index findfont currentglobal 5 1 roll dup gcheck setglobal dup /FontType get 0 eq { dup/WMode known{dup/WMode get 1 eq}{false}ifelse version length 4 ge and {version 0 4 getinterval cvi 2015 ge} {true} ifelse {/ct_Type0WidthProc} {/ct_Type0WMode1WidthProc} ifelse ct_BoldBaseFont/_setwidthProc 3 -1 roll load put {ct_MakeBoldFont}ct_Type0CopyFont definefont } { dup/_fauxfont known not 1 index/SubstMaster known not and { ct_BoldBaseFont/_setwidthProc /ct_BoldRomanWidthProc load put ct_MakeBoldFont } { 2 index 2 index eq {exch pop } { dup length dict begin ct_CopyFont currentdict end definefont } ifelse } ifelse } ifelse pop pop pop setglobal }bind def /?str1 256 string def /?set { $SubstituteFont begin /$substituteFound false def /$fontname 1 index def /$doSmartSub false def end dup findfont $SubstituteFont begin $substituteFound {false} { dup/FontName known { dup/FontName get $fontname eq 1 index/DistillerFauxFont known not and /currentdistillerparams where {pop false 2 index isWidthsOnlyFont not and} if } {false} ifelse } ifelse exch pop /$doSmartSub true def end { 5 1 roll pop pop pop pop findfont } { 1 index findfont dup/FontType get 3 eq { 6 1 roll pop pop pop pop pop false } {pop true} ifelse { $SubstituteFont begin pop pop /$styleArray 1 index def /$regOrdering 2 index def pop pop 0 1 $styleArray length 1 sub { $styleArray exch get ct_StyleDicts $regOrdering 2 copy known { get exch 2 copy known not {pop/Default} if get dup type/nametype eq { ?str1 cvs length dup 1 add exch ?str1 exch(-)putinterval exch dup length exch ?str1 exch 3 index exch putinterval add ?str1 exch 0 exch getinterval cvn } { pop pop/Unknown } ifelse } { pop pop pop pop/Unknown } ifelse } for end findfont }if } ifelse currentglobal false setglobal 3 1 roll null copyfont definefont pop setglobal }bind def setpacking userdict/$SubstituteFont 25 dict put 1 dict begin /SubstituteFont dup $error exch 2 copy known {get} {pop pop{pop/Courier}bind} ifelse def /currentdistillerparams where dup { pop pop currentdistillerparams/CannotEmbedFontPolicy 2 copy known {get/Error eq} {pop pop false} ifelse } if not { countdictstack array dictstack 0 get begin userdict begin $SubstituteFont begin /$str 128 string def /$fontpat 128 string def /$slen 0 def /$sname null def /$match false def /$fontname null def /$substituteFound false def /$inVMIndex null def /$doSmartSub true def /$depth 0 def /$fontname null def /$italicangle 26.5 def /$dstack null def /$Strategies 10 dict dup begin /$Type3Underprint { currentglobal exch false setglobal 11 dict begin /UseFont exch $WMode 0 ne { dup length dict copy dup/WMode $WMode put /UseFont exch definefont } if def /FontName $fontname dup type/stringtype eq{cvn}if def /FontType 3 def /FontMatrix[.001 0 0 .001 0 0]def /Encoding 256 array dup 0 1 255{/.notdef put dup}for pop def /FontBBox[0 0 0 0]def /CCInfo 7 dict dup begin /cc null def /x 0 def /y 0 def end def /BuildChar { exch begin CCInfo begin 1 string dup 0 3 index put exch pop /cc exch def UseFont 1000 scalefont setfont cc stringwidth/y exch def/x exch def x y setcharwidth $SubstituteFont/$Strategy get/$Underprint get exec 0 0 moveto cc show x y moveto end end }bind def currentdict end exch setglobal }bind def /$GetaTint 2 dict dup begin /$BuildFont { dup/WMode known {dup/WMode get} {0} ifelse /$WMode exch def $fontname exch dup/FontName known { dup/FontName get dup type/stringtype eq{cvn}if } {/unnamedfont} ifelse exch Adobe_CoolType_Data/InVMDeepCopiedFonts get 1 index/FontName get known { pop Adobe_CoolType_Data/InVMDeepCopiedFonts get 1 index get null copyfont } {$deepcopyfont} ifelse exch 1 index exch/FontBasedOn exch put dup/FontName $fontname dup type/stringtype eq{cvn}if put definefont Adobe_CoolType_Data/InVMDeepCopiedFonts get begin dup/FontBasedOn get 1 index def end }bind def /$Underprint { gsave x abs y abs gt {/y 1000 def} {/x -1000 def 500 120 translate} ifelse Level2? { [/Separation(All)/DeviceCMYK{0 0 0 1 pop}] setcolorspace } {0 setgray} ifelse 10 setlinewidth x .8 mul [7 3] { y mul 8 div 120 sub x 10 div exch moveto 0 y 4 div neg rlineto dup 0 rlineto 0 y 4 div rlineto closepath gsave Level2? {.2 setcolor} {.8 setgray} ifelse fill grestore stroke } forall pop grestore }bind def end def /$Oblique 1 dict dup begin /$BuildFont { currentglobal exch dup gcheck setglobal null copyfont begin /FontBasedOn currentdict/FontName known { FontName dup type/stringtype eq{cvn}if } {/unnamedfont} ifelse def /FontName $fontname dup type/stringtype eq{cvn}if def /currentdistillerparams where {pop} { /FontInfo currentdict/FontInfo known {FontInfo null copyfont} {2 dict} ifelse dup begin /ItalicAngle $italicangle def /FontMatrix FontMatrix [1 0 ItalicAngle dup sin exch cos div 1 0 0] matrix concatmatrix readonly end 4 2 roll def def } ifelse FontName currentdict end definefont exch setglobal }bind def end def /$None 1 dict dup begin /$BuildFont{}bind def end def end def /$Oblique SetSubstituteStrategy /$findfontByEnum { dup type/stringtype eq{cvn}if dup/$fontname exch def $sname null eq {$str cvs dup length $slen sub $slen getinterval} {pop $sname} ifelse $fontpat dup 0(fonts/*)putinterval exch 7 exch putinterval /$match false def $SubstituteFont/$dstack countdictstack array dictstack put mark { $fontpat 0 $slen 7 add getinterval {/$match exch def exit} $str filenameforall } stopped { cleardictstack currentdict true $SubstituteFont/$dstack get { exch { 1 index eq {pop false} {true} ifelse } {begin false} ifelse } forall pop } if cleartomark /$slen 0 def $match false ne {$match(fonts/)anchorsearch pop pop cvn} {/Courier} ifelse }bind def /$ROS 1 dict dup begin /Adobe 4 dict dup begin /Japan1 [/Ryumin-Light/HeiseiMin-W3 /GothicBBB-Medium/HeiseiKakuGo-W5 /HeiseiMaruGo-W4/Jun101-Light]def /Korea1 [/HYSMyeongJo-Medium/HYGoThic-Medium]def /GB1 [/STSong-Light/STHeiti-Regular]def /CNS1 [/MKai-Medium/MHei-Medium]def end def end def /$cmapname null def /$deepcopyfont { dup/FontType get 0 eq { 1 dict dup/FontName/copied put copyfont begin /FDepVector FDepVector copyarray 0 1 2 index length 1 sub { 2 copy get $deepcopyfont dup/FontName/copied put /copied exch definefont 3 copy put pop pop } for def currentdict end } {$Strategies/$Type3Underprint get exec} ifelse }bind def /$buildfontname { dup/CIDFont findresource/CIDSystemInfo get begin Registry length Ordering length Supplement 8 string cvs 3 copy length 2 add add add string dup 5 1 roll dup 0 Registry putinterval dup 4 index(-)putinterval dup 4 index 1 add Ordering putinterval 4 2 roll add 1 add 2 copy(-)putinterval end 1 add 2 copy 0 exch getinterval $cmapname $fontpat cvs exch anchorsearch {pop pop 3 2 roll putinterval cvn/$cmapname exch def} {pop pop pop pop pop} ifelse length $str 1 index(-)putinterval 1 add $str 1 index $cmapname $fontpat cvs putinterval $cmapname length add $str exch 0 exch getinterval cvn }bind def /$findfontByROS { /$fontname exch def $ROS Registry 2 copy known { get Ordering 2 copy known {get} {pop pop[]} ifelse } {pop pop[]} ifelse false exch { dup/CIDFont resourcestatus { pop pop save 1 index/CIDFont findresource dup/WidthsOnly known {dup/WidthsOnly get} {false} ifelse exch pop exch restore {pop} {exch pop true exit} ifelse } {pop} ifelse } forall {$str cvs $buildfontname} { false(*) { save exch dup/CIDFont findresource dup/WidthsOnly known {dup/WidthsOnly get not} {true} ifelse exch/CIDSystemInfo get dup/Registry get Registry eq exch/Ordering get Ordering eq and and {exch restore exch pop true exit} {pop restore} ifelse } $str/CIDFont resourceforall {$buildfontname} {$fontname $findfontByEnum} ifelse } ifelse }bind def end end currentdict/$error known currentdict/languagelevel known and dup {pop $error/SubstituteFont known} if dup {$error} {Adobe_CoolType_Core} ifelse begin { /SubstituteFont /CMap/Category resourcestatus { pop pop { $SubstituteFont begin /$substituteFound true def dup length $slen gt $sname null ne or $slen 0 gt and { $sname null eq {dup $str cvs dup length $slen sub $slen getinterval cvn} {$sname} ifelse Adobe_CoolType_Data/InVMFontsByCMap get 1 index 2 copy known { get false exch { pop currentglobal { GlobalFontDirectory 1 index known {exch pop true exit} {pop} ifelse } { FontDirectory 1 index known {exch pop true exit} { GlobalFontDirectory 1 index known {exch pop true exit} {pop} ifelse } ifelse } ifelse } forall } {pop pop false} ifelse { exch pop exch pop } { dup/CMap resourcestatus { pop pop dup/$cmapname exch def /CMap findresource/CIDSystemInfo get{def}forall $findfontByROS } { 128 string cvs dup(-)search { 3 1 roll search { 3 1 roll pop {dup cvi} stopped {pop pop pop pop pop $findfontByEnum} { 4 2 roll pop pop exch length exch 2 index length 2 index sub exch 1 sub -1 0 { $str cvs dup length 4 index 0 4 index 4 3 roll add getinterval exch 1 index exch 3 index exch putinterval dup/CMap resourcestatus { pop pop 4 1 roll pop pop pop dup/$cmapname exch def /CMap findresource/CIDSystemInfo get{def}forall $findfontByROS true exit } {pop} ifelse } for dup type/booleantype eq {pop} {pop pop pop $findfontByEnum} ifelse } ifelse } {pop pop pop $findfontByEnum} ifelse } {pop pop $findfontByEnum} ifelse } ifelse } ifelse } {//SubstituteFont exec} ifelse /$slen 0 def end } } { { $SubstituteFont begin /$substituteFound true def dup length $slen gt $sname null ne or $slen 0 gt and {$findfontByEnum} {//SubstituteFont exec} ifelse end } } ifelse bind readonly def Adobe_CoolType_Core/scfindfont/systemfindfont load put } { /scfindfont { $SubstituteFont begin dup systemfindfont dup/FontName known {dup/FontName get dup 3 index ne} {/noname true} ifelse dup { /$origfontnamefound 2 index def /$origfontname 4 index def/$substituteFound true def } if exch pop { $slen 0 gt $sname null ne 3 index length $slen gt or and { pop dup $findfontByEnum findfont dup maxlength 1 add dict begin {1 index/FID eq{pop pop}{def}ifelse} forall currentdict end definefont dup/FontName known{dup/FontName get}{null}ifelse $origfontnamefound ne { $origfontname $str cvs print ( substitution revised, using )print dup/FontName known {dup/FontName get}{(unspecified font)} ifelse $str cvs print(.\n)print } if } {exch pop} ifelse } {exch pop} ifelse end }bind def } ifelse end end Adobe_CoolType_Core_Defined not { Adobe_CoolType_Core/findfont { $SubstituteFont begin $depth 0 eq { /$fontname 1 index dup type/stringtype ne{$str cvs}if def /$substituteFound false def } if /$depth $depth 1 add def end scfindfont $SubstituteFont begin /$depth $depth 1 sub def $substituteFound $depth 0 eq and { $inVMIndex null ne {dup $inVMIndex $AddInVMFont} if $doSmartSub { currentdict/$Strategy known {$Strategy/$BuildFont get exec} if } if } if end }bind put } if } if end /$AddInVMFont { exch/FontName 2 copy known { get 1 dict dup begin exch 1 index gcheck def end exch Adobe_CoolType_Data/InVMFontsByCMap get exch $DictAdd } {pop pop pop} ifelse }bind def /$DictAdd { 2 copy known not {2 copy 4 index length dict put} if Level2? not { 2 copy get dup maxlength exch length 4 index length add lt 2 copy get dup length 4 index length add exch maxlength 1 index lt { 2 mul dict begin 2 copy get{forall}def 2 copy currentdict put end } {pop} ifelse } if get begin {def} forall end }bind def end end %%EndResource currentglobal true setglobal %%BeginResource: procset Adobe_CoolType_Utility_MAKEOCF 1.23 0 %%Copyright: Copyright 1987-2006 Adobe Systems Incorporated. %%Version: 1.23 0 systemdict/languagelevel known dup {currentglobal false setglobal} {false} ifelse exch userdict/Adobe_CoolType_Utility 2 copy known {2 copy get dup maxlength 27 add dict copy} {27 dict} ifelse put Adobe_CoolType_Utility begin /@eexecStartData def /@recognizeCIDFont null def /ct_Level2? exch def /ct_Clone? 1183615869 internaldict dup /CCRun known not exch/eCCRun known not ct_Level2? and or def ct_Level2? {globaldict begin currentglobal true setglobal} if /ct_AddStdCIDMap ct_Level2? {{ mark Adobe_CoolType_Utility/@recognizeCIDFont currentdict put { ((Hex)57 StartData 0615 1e27 2c39 1c60 d8a8 cc31 fe2b f6e0 7aa3 e541 e21c 60d8 a8c9 c3d0 6d9e 1c60 d8a8 c9c2 02d7 9a1c 60d8 a849 1c60 d8a8 cc36 74f4 1144 b13b 77)0()/SubFileDecode filter cvx exec } stopped { cleartomark Adobe_CoolType_Utility/@recognizeCIDFont get countdictstack dup array dictstack exch 1 sub -1 0 { 2 copy get 3 index eq {1 index length exch sub 1 sub{end}repeat exit} {pop} ifelse } for pop pop Adobe_CoolType_Utility/@eexecStartData get eexec } {cleartomark} ifelse }} {{ Adobe_CoolType_Utility/@eexecStartData get eexec }} ifelse bind def userdict/cid_extensions known dup{cid_extensions/cid_UpdateDB known and}if { cid_extensions begin /cid_GetCIDSystemInfo { 1 index type/stringtype eq {exch cvn exch} if cid_extensions begin dup load 2 index known { 2 copy cid_GetStatusInfo dup null ne { 1 index load 3 index get dup null eq {pop pop cid_UpdateDB} { exch 1 index/Created get eq {exch pop exch pop} {pop cid_UpdateDB} ifelse } ifelse } {pop cid_UpdateDB} ifelse } {cid_UpdateDB} ifelse end }bind def end } if ct_Level2? {end setglobal} if /ct_UseNativeCapability? systemdict/composefont known def /ct_MakeOCF 35 dict def /ct_Vars 25 dict def /ct_GlyphDirProcs 6 dict def /ct_BuildCharDict 15 dict dup begin /charcode 2 string def /dst_string 1500 string def /nullstring()def /usewidths? true def end def ct_Level2?{setglobal}{pop}ifelse ct_GlyphDirProcs begin /GetGlyphDirectory { systemdict/languagelevel known {pop/CIDFont findresource/GlyphDirectory get} { 1 index/CIDFont findresource/GlyphDirectory get dup type/dicttype eq { dup dup maxlength exch length sub 2 index lt { dup length 2 index add dict copy 2 index /CIDFont findresource/GlyphDirectory 2 index put } if } if exch pop exch pop } ifelse + }def /+ { systemdict/languagelevel known { currentglobal false setglobal 3 dict begin /vm exch def } {1 dict begin} ifelse /$ exch def systemdict/languagelevel known { vm setglobal /gvm currentglobal def $ gcheck setglobal } if ?{$ begin}if }def /?{$ type/dicttype eq}def /|{ userdict/Adobe_CoolType_Data known { Adobe_CoolType_Data/AddWidths? known { currentdict Adobe_CoolType_Data begin begin AddWidths? { Adobe_CoolType_Data/CC 3 index put ?{def}{$ 3 1 roll put}ifelse CC charcode exch 1 index 0 2 index 256 idiv put 1 index exch 1 exch 256 mod put stringwidth 2 array astore currentfont/Widths get exch CC exch put } {?{def}{$ 3 1 roll put}ifelse} ifelse end end } {?{def}{$ 3 1 roll put}ifelse} ifelse } {?{def}{$ 3 1 roll put}ifelse} ifelse }def /! { ?{end}if systemdict/languagelevel known {gvm setglobal} if end }def /:{string currentfile exch readstring pop}executeonly def end ct_MakeOCF begin /ct_cHexEncoding [/c00/c01/c02/c03/c04/c05/c06/c07/c08/c09/c0A/c0B/c0C/c0D/c0E/c0F/c10/c11/c12 /c13/c14/c15/c16/c17/c18/c19/c1A/c1B/c1C/c1D/c1E/c1F/c20/c21/c22/c23/c24/c25 /c26/c27/c28/c29/c2A/c2B/c2C/c2D/c2E/c2F/c30/c31/c32/c33/c34/c35/c36/c37/c38 /c39/c3A/c3B/c3C/c3D/c3E/c3F/c40/c41/c42/c43/c44/c45/c46/c47/c48/c49/c4A/c4B /c4C/c4D/c4E/c4F/c50/c51/c52/c53/c54/c55/c56/c57/c58/c59/c5A/c5B/c5C/c5D/c5E /c5F/c60/c61/c62/c63/c64/c65/c66/c67/c68/c69/c6A/c6B/c6C/c6D/c6E/c6F/c70/c71 /c72/c73/c74/c75/c76/c77/c78/c79/c7A/c7B/c7C/c7D/c7E/c7F/c80/c81/c82/c83/c84 /c85/c86/c87/c88/c89/c8A/c8B/c8C/c8D/c8E/c8F/c90/c91/c92/c93/c94/c95/c96/c97 /c98/c99/c9A/c9B/c9C/c9D/c9E/c9F/cA0/cA1/cA2/cA3/cA4/cA5/cA6/cA7/cA8/cA9/cAA /cAB/cAC/cAD/cAE/cAF/cB0/cB1/cB2/cB3/cB4/cB5/cB6/cB7/cB8/cB9/cBA/cBB/cBC/cBD /cBE/cBF/cC0/cC1/cC2/cC3/cC4/cC5/cC6/cC7/cC8/cC9/cCA/cCB/cCC/cCD/cCE/cCF/cD0 /cD1/cD2/cD3/cD4/cD5/cD6/cD7/cD8/cD9/cDA/cDB/cDC/cDD/cDE/cDF/cE0/cE1/cE2/cE3 /cE4/cE5/cE6/cE7/cE8/cE9/cEA/cEB/cEC/cED/cEE/cEF/cF0/cF1/cF2/cF3/cF4/cF5/cF6 /cF7/cF8/cF9/cFA/cFB/cFC/cFD/cFE/cFF]def /ct_CID_STR_SIZE 8000 def /ct_mkocfStr100 100 string def /ct_defaultFontMtx[.001 0 0 .001 0 0]def /ct_1000Mtx[1000 0 0 1000 0 0]def /ct_raise{exch cvx exch errordict exch get exec stop}bind def /ct_reraise {cvx $error/errorname get(Error: )print dup( )cvs print errordict exch get exec stop }bind def /ct_cvnsi { 1 index add 1 sub 1 exch 0 4 1 roll { 2 index exch get exch 8 bitshift add } for exch pop }bind def /ct_GetInterval { Adobe_CoolType_Utility/ct_BuildCharDict get begin /dst_index 0 def dup dst_string length gt {dup string/dst_string exch def} if 1 index ct_CID_STR_SIZE idiv /arrayIndex exch def 2 index arrayIndex get 2 index arrayIndex ct_CID_STR_SIZE mul sub { dup 3 index add 2 index length le { 2 index getinterval dst_string dst_index 2 index putinterval length dst_index add/dst_index exch def exit } { 1 index length 1 index sub dup 4 1 roll getinterval dst_string dst_index 2 index putinterval pop dup dst_index add/dst_index exch def sub /arrayIndex arrayIndex 1 add def 2 index dup length arrayIndex gt {arrayIndex get} { pop exit } ifelse 0 } ifelse } loop pop pop pop dst_string 0 dst_index getinterval end }bind def ct_Level2? { /ct_resourcestatus currentglobal mark true setglobal {/unknowninstancename/Category resourcestatus} stopped {cleartomark setglobal true} {cleartomark currentglobal not exch setglobal} ifelse { { mark 3 1 roll/Category findresource begin ct_Vars/vm currentglobal put ({ResourceStatus}stopped)0()/SubFileDecode filter cvx exec {cleartomark false} {{3 2 roll pop true}{cleartomark false}ifelse} ifelse ct_Vars/vm get setglobal end } } {{resourcestatus}} ifelse bind def /CIDFont/Category ct_resourcestatus {pop pop} { currentglobal true setglobal /Generic/Category findresource dup length dict copy dup/InstanceType/dicttype put /CIDFont exch/Category defineresource pop setglobal } ifelse ct_UseNativeCapability? { /CIDInit/ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo 3 dict dup begin /Registry(Adobe)def /Ordering(Identity)def /Supplement 0 def end def /CMapName/Identity-H def /CMapVersion 1.000 def /CMapType 1 def 1 begincodespacerange <0000> endcodespacerange 1 begincidrange <0000>0 endcidrange endcmap CMapName currentdict/CMap defineresource pop end end } if } { /ct_Category 2 dict begin /CIDFont 10 dict def /ProcSet 2 dict def currentdict end def /defineresource { ct_Category 1 index 2 copy known { get dup dup maxlength exch length eq { dup length 10 add dict copy ct_Category 2 index 2 index put } if 3 index 3 index put pop exch pop } {pop pop/defineresource/undefined ct_raise} ifelse }bind def /findresource { ct_Category 1 index 2 copy known { get 2 index 2 copy known {get 3 1 roll pop pop} {pop pop/findresource/undefinedresource ct_raise} ifelse } {pop pop/findresource/undefined ct_raise} ifelse }bind def /resourcestatus { ct_Category 1 index 2 copy known { get 2 index known exch pop exch pop { 0 -1 true } { false } ifelse } {pop pop/findresource/undefined ct_raise} ifelse }bind def /ct_resourcestatus/resourcestatus load def } ifelse /ct_CIDInit 2 dict begin /ct_cidfont_stream_init { { dup(Binary)eq { pop null currentfile ct_Level2? { {cid_BYTE_COUNT()/SubFileDecode filter} stopped {pop pop pop} if } if /readstring load exit } if dup(Hex)eq { pop currentfile ct_Level2? { {null exch/ASCIIHexDecode filter/readstring} stopped {pop exch pop(>)exch/readhexstring} if } {(>)exch/readhexstring} ifelse load exit } if /StartData/typecheck ct_raise } loop cid_BYTE_COUNT ct_CID_STR_SIZE le { 2 copy cid_BYTE_COUNT string exch exec pop 1 array dup 3 -1 roll 0 exch put } { cid_BYTE_COUNT ct_CID_STR_SIZE div ceiling cvi dup array exch 2 sub 0 exch 1 exch { 2 copy 5 index ct_CID_STR_SIZE string 6 index exec pop put pop } for 2 index cid_BYTE_COUNT ct_CID_STR_SIZE mod string 3 index exec pop 1 index exch 1 index length 1 sub exch put } ifelse cid_CIDFONT exch/GlyphData exch put 2 index null eq { pop pop pop } { pop/readstring load 1 string exch { 3 copy exec pop dup length 0 eq { pop pop pop pop pop true exit } if 4 index eq { pop pop pop pop false exit } if } loop pop } ifelse }bind def /StartData { mark { currentdict dup/FDArray get 0 get/FontMatrix get 0 get 0.001 eq { dup/CDevProc known not { /CDevProc 1183615869 internaldict/stdCDevProc 2 copy known {get} { pop pop {pop pop pop pop pop 0 -1000 7 index 2 div 880} } ifelse def } if } { /CDevProc { pop pop pop pop pop 0 1 cid_temp/cid_CIDFONT get /FDArray get 0 get /FontMatrix get 0 get div 7 index 2 div 1 index 0.88 mul }def } ifelse /cid_temp 15 dict def cid_temp begin /cid_CIDFONT exch def 3 copy pop dup/cid_BYTE_COUNT exch def 0 gt { ct_cidfont_stream_init FDArray { /Private get dup/SubrMapOffset known { begin /Subrs SubrCount array def Subrs SubrMapOffset SubrCount SDBytes ct_Level2? { currentdict dup/SubrMapOffset undef dup/SubrCount undef /SDBytes undef } if end /cid_SD_BYTES exch def /cid_SUBR_COUNT exch def /cid_SUBR_MAP_OFFSET exch def /cid_SUBRS exch def cid_SUBR_COUNT 0 gt { GlyphData cid_SUBR_MAP_OFFSET cid_SD_BYTES ct_GetInterval 0 cid_SD_BYTES ct_cvnsi 0 1 cid_SUBR_COUNT 1 sub { exch 1 index 1 add cid_SD_BYTES mul cid_SUBR_MAP_OFFSET add GlyphData exch cid_SD_BYTES ct_GetInterval 0 cid_SD_BYTES ct_cvnsi cid_SUBRS 4 2 roll GlyphData exch 4 index 1 index sub ct_GetInterval dup length string copy put } for pop } if } {pop} ifelse } forall } if cleartomark pop pop end CIDFontName currentdict/CIDFont defineresource pop end end } stopped {cleartomark/StartData ct_reraise} if }bind def currentdict end def /ct_saveCIDInit { /CIDInit/ProcSet ct_resourcestatus {true} {/CIDInitC/ProcSet ct_resourcestatus} ifelse { pop pop /CIDInit/ProcSet findresource ct_UseNativeCapability? {pop null} {/CIDInit ct_CIDInit/ProcSet defineresource pop} ifelse } {/CIDInit ct_CIDInit/ProcSet defineresource pop null} ifelse ct_Vars exch/ct_oldCIDInit exch put }bind def /ct_restoreCIDInit { ct_Vars/ct_oldCIDInit get dup null ne {/CIDInit exch/ProcSet defineresource pop} {pop} ifelse }bind def /ct_BuildCharSetUp { 1 index begin CIDFont begin Adobe_CoolType_Utility/ct_BuildCharDict get begin /ct_dfCharCode exch def /ct_dfDict exch def CIDFirstByte ct_dfCharCode add dup CIDCount ge {pop 0} if /cid exch def { GlyphDirectory cid 2 copy known {get} {pop pop nullstring} ifelse dup length FDBytes sub 0 gt { dup FDBytes 0 ne {0 FDBytes ct_cvnsi} {pop 0} ifelse /fdIndex exch def dup length FDBytes sub FDBytes exch getinterval /charstring exch def exit } { pop cid 0 eq {/charstring nullstring def exit} if /cid 0 def } ifelse } loop }def /ct_SetCacheDevice { 0 0 moveto dup stringwidth 3 -1 roll true charpath pathbbox 0 -1000 7 index 2 div 880 setcachedevice2 0 0 moveto }def /ct_CloneSetCacheProc { 1 eq { stringwidth pop -2 div -880 0 -1000 setcharwidth moveto } { usewidths? { currentfont/Widths get cid 2 copy known {get exch pop aload pop} {pop pop stringwidth} ifelse } {stringwidth} ifelse setcharwidth 0 0 moveto } ifelse }def /ct_Type3ShowCharString { ct_FDDict fdIndex 2 copy known {get} { currentglobal 3 1 roll 1 index gcheck setglobal ct_Type1FontTemplate dup maxlength dict copy begin FDArray fdIndex get dup/FontMatrix 2 copy known {get} {pop pop ct_defaultFontMtx} ifelse /FontMatrix exch dup length array copy def /Private get /Private exch def /Widths rootfont/Widths get def /CharStrings 1 dict dup/.notdef dup length string copy put def currentdict end /ct_Type1Font exch definefont dup 5 1 roll put setglobal } ifelse dup/CharStrings get 1 index/Encoding get ct_dfCharCode get charstring put rootfont/WMode 2 copy known {get} {pop pop 0} ifelse exch 1000 scalefont setfont ct_str1 0 ct_dfCharCode put ct_str1 exch ct_dfSetCacheProc ct_SyntheticBold { currentpoint ct_str1 show newpath moveto ct_str1 true charpath ct_StrokeWidth setlinewidth stroke } {ct_str1 show} ifelse }def /ct_Type4ShowCharString { ct_dfDict ct_dfCharCode charstring FDArray fdIndex get dup/FontMatrix get dup ct_defaultFontMtx ct_matrixeq not {ct_1000Mtx matrix concatmatrix concat} {pop} ifelse /Private get Adobe_CoolType_Utility/ct_Level2? get not { ct_dfDict/Private 3 -1 roll {put} 1183615869 internaldict/superexec get exec } if 1183615869 internaldict Adobe_CoolType_Utility/ct_Level2? get {1 index} {3 index/Private get mark 6 1 roll} ifelse dup/RunInt known {/RunInt get} {pop/CCRun} ifelse get exec Adobe_CoolType_Utility/ct_Level2? get not {cleartomark} if }bind def /ct_BuildCharIncremental { { Adobe_CoolType_Utility/ct_MakeOCF get begin ct_BuildCharSetUp ct_ShowCharString } stopped {stop} if end end end end }bind def /BaseFontNameStr(BF00)def /ct_Type1FontTemplate 14 dict begin /FontType 1 def /FontMatrix [0.001 0 0 0.001 0 0]def /FontBBox [-250 -250 1250 1250]def /Encoding ct_cHexEncoding def /PaintType 0 def currentdict end def /BaseFontTemplate 11 dict begin /FontMatrix [0.001 0 0 0.001 0 0]def /FontBBox [-250 -250 1250 1250]def /Encoding ct_cHexEncoding def /BuildChar/ct_BuildCharIncremental load def ct_Clone? { /FontType 3 def /ct_ShowCharString/ct_Type3ShowCharString load def /ct_dfSetCacheProc/ct_CloneSetCacheProc load def /ct_SyntheticBold false def /ct_StrokeWidth 1 def } { /FontType 4 def /Private 1 dict dup/lenIV 4 put def /CharStrings 1 dict dup/.notdefput def /PaintType 0 def /ct_ShowCharString/ct_Type4ShowCharString load def } ifelse /ct_str1 1 string def currentdict end def /BaseFontDictSize BaseFontTemplate length 5 add def /ct_matrixeq { true 0 1 5 { dup 4 index exch get exch 3 index exch get eq and dup not {exit} if } for exch pop exch pop }bind def /ct_makeocf { 15 dict begin exch/WMode exch def exch/FontName exch def /FontType 0 def /FMapType 2 def dup/FontMatrix known {dup/FontMatrix get/FontMatrix exch def} {/FontMatrix matrix def} ifelse /bfCount 1 index/CIDCount get 256 idiv 1 add dup 256 gt{pop 256}if def /Encoding 256 array 0 1 bfCount 1 sub{2 copy dup put pop}for bfCount 1 255{2 copy bfCount put pop}for def /FDepVector bfCount dup 256 lt{1 add}if array def BaseFontTemplate BaseFontDictSize dict copy begin /CIDFont exch def CIDFont/FontBBox known {CIDFont/FontBBox get/FontBBox exch def} if CIDFont/CDevProc known {CIDFont/CDevProc get/CDevProc exch def} if currentdict end BaseFontNameStr 3(0)putinterval 0 1 bfCount dup 256 eq{1 sub}if { FDepVector exch 2 index BaseFontDictSize dict copy begin dup/CIDFirstByte exch 256 mul def FontType 3 eq {/ct_FDDict 2 dict def} if currentdict end 1 index 16 BaseFontNameStr 2 2 getinterval cvrs pop BaseFontNameStr exch definefont put } for ct_Clone? {/Widths 1 index/CIDFont get/GlyphDirectory get length dict def} if FontName currentdict end definefont ct_Clone? { gsave dup 1000 scalefont setfont ct_BuildCharDict begin /usewidths? false def currentfont/Widths get begin exch/CIDFont get/GlyphDirectory get { pop dup charcode exch 1 index 0 2 index 256 idiv put 1 index exch 1 exch 256 mod put stringwidth 2 array astore def } forall end /usewidths? true def end grestore } {exch pop} ifelse }bind def currentglobal true setglobal /ct_ComposeFont { ct_UseNativeCapability? { 2 index/CMap ct_resourcestatus {pop pop exch pop} { /CIDInit/ProcSet findresource begin 12 dict begin begincmap /CMapName 3 index def /CMapVersion 1.000 def /CMapType 1 def exch/WMode exch def /CIDSystemInfo 3 dict dup begin /Registry(Adobe)def /Ordering CMapName ct_mkocfStr100 cvs (Adobe-)search { pop pop (-)search { dup length string copy exch pop exch pop } {pop(Identity)} ifelse } {pop (Identity)} ifelse def /Supplement 0 def end def 1 begincodespacerange <0000> endcodespacerange 1 begincidrange <0000>0 endcidrange endcmap CMapName currentdict/CMap defineresource pop end end } ifelse composefont } { 3 2 roll pop 0 get/CIDFont findresource ct_makeocf } ifelse }bind def setglobal /ct_MakeIdentity { ct_UseNativeCapability? { 1 index/CMap ct_resourcestatus {pop pop} { /CIDInit/ProcSet findresource begin 12 dict begin begincmap /CMapName 2 index def /CMapVersion 1.000 def /CMapType 1 def /CIDSystemInfo 3 dict dup begin /Registry(Adobe)def /Ordering CMapName ct_mkocfStr100 cvs (Adobe-)search { pop pop (-)search {dup length string copy exch pop exch pop} {pop(Identity)} ifelse } {pop(Identity)} ifelse def /Supplement 0 def end def 1 begincodespacerange <0000> endcodespacerange 1 begincidrange <0000>0 endcidrange endcmap CMapName currentdict/CMap defineresource pop end end } ifelse composefont } { exch pop 0 get/CIDFont findresource ct_makeocf } ifelse }bind def currentdict readonly pop end end %%EndResource setglobal %%BeginResource: procset Adobe_CoolType_Utility_T42 1.0 0 %%Copyright: Copyright 1987-2004 Adobe Systems Incorporated. %%Version: 1.0 0 userdict/ct_T42Dict 15 dict put ct_T42Dict begin /Is2015? { version cvi 2015 ge }bind def /AllocGlyphStorage { Is2015? { pop } { {string}forall }ifelse }bind def /Type42DictBegin { 25 dict begin /FontName exch def /CharStrings 256 dict begin /.notdef 0 def currentdict end def /Encoding exch def /PaintType 0 def /FontType 42 def /FontMatrix[1 0 0 1 0 0]def 4 array astore cvx/FontBBox exch def /sfnts }bind def /Type42DictEnd { currentdict dup/FontName get exch definefont end ct_T42Dict exch dup/FontName get exch put }bind def /RD{string currentfile exch readstring pop}executeonly def /PrepFor2015 { Is2015? { /GlyphDirectory 16 dict def sfnts 0 get dup 2 index (glyx) putinterval 2 index (locx) putinterval pop pop } { pop pop }ifelse }bind def /AddT42Char { Is2015? { /GlyphDirectory get begin def end pop pop } { /sfnts get 4 index get 3 index 2 index putinterval pop pop pop pop }ifelse }bind def /T0AddT42Mtx2 { /CIDFont findresource/Metrics2 get begin def end }bind def end %%EndResource currentglobal true setglobal %%BeginFile: MMFauxFont.prc %%Copyright: Copyright 1987-2001 Adobe Systems Incorporated. %%All Rights Reserved. userdict /ct_EuroDict 10 dict put ct_EuroDict begin /ct_CopyFont { { 1 index /FID ne {def} {pop pop} ifelse} forall } def /ct_GetGlyphOutline { gsave initmatrix newpath exch findfont dup length 1 add dict begin ct_CopyFont /Encoding Encoding dup length array copy dup 4 -1 roll 0 exch put def currentdict end /ct_EuroFont exch definefont 1000 scalefont setfont 0 0 moveto [ <00> stringwidth <00> false charpath pathbbox [ {/m cvx} {/l cvx} {/c cvx} {/cp cvx} pathforall grestore counttomark 8 add } def /ct_MakeGlyphProc { ] cvx /ct_PSBuildGlyph cvx ] cvx } def /ct_PSBuildGlyph { gsave 8 -1 roll pop 7 1 roll 6 -2 roll ct_FontMatrix transform 6 2 roll 4 -2 roll ct_FontMatrix transform 4 2 roll ct_FontMatrix transform currentdict /PaintType 2 copy known {get 2 eq}{pop pop false} ifelse dup 9 1 roll { currentdict /StrokeWidth 2 copy known { get 2 div 0 ct_FontMatrix dtransform pop 5 1 roll 4 -1 roll 4 index sub 4 1 roll 3 -1 roll 4 index sub 3 1 roll exch 4 index add exch 4 index add 5 -1 roll pop } { pop pop } ifelse } if setcachedevice ct_FontMatrix concat ct_PSPathOps begin exec end { currentdict /StrokeWidth 2 copy known { get } { pop pop 0 } ifelse setlinewidth stroke } { fill } ifelse grestore } def /ct_PSPathOps 4 dict dup begin /m {moveto} def /l {lineto} def /c {curveto} def /cp {closepath} def end def /ct_matrix1000 [1000 0 0 1000 0 0] def /ct_AddGlyphProc { 2 index findfont dup length 4 add dict begin ct_CopyFont /CharStrings CharStrings dup length 1 add dict copy begin 3 1 roll def currentdict end def /ct_FontMatrix ct_matrix1000 FontMatrix matrix concatmatrix def /ct_PSBuildGlyph /ct_PSBuildGlyph load def /ct_PSPathOps /ct_PSPathOps load def currentdict end definefont pop } def systemdict /languagelevel known { /ct_AddGlyphToPrinterFont { 2 copy ct_GetGlyphOutline 3 add -1 roll restore ct_MakeGlyphProc ct_AddGlyphProc } def } { /ct_AddGlyphToPrinterFont { pop pop restore Adobe_CTFauxDict /$$$FONTNAME get /Euro Adobe_CTFauxDict /$$$SUBSTITUTEBASE get ct_EuroDict exch get ct_AddGlyphProc } def } ifelse /AdobeSansMM { 556 0 24 -19 541 703 { 541 628 m 510 669 442 703 354 703 c 201 703 117 607 101 444 c 50 444 l 25 372 l 97 372 l 97 301 l 49 301 l 24 229 l 103 229 l 124 67 209 -19 350 -19 c 435 -19 501 25 509 32 c 509 131 l 492 105 417 60 343 60 c 267 60 204 127 197 229 c 406 229 l 430 301 l 191 301 l 191 372 l 455 372 l 479 444 l 194 444 l 201 531 245 624 348 624 c 433 624 484 583 509 534 c cp 556 0 m } ct_PSBuildGlyph } def /AdobeSerifMM { 500 0 10 -12 484 692 { 347 298 m 171 298 l 170 310 170 322 170 335 c 170 362 l 362 362 l 374 403 l 172 403 l 184 580 244 642 308 642 c 380 642 434 574 457 457 c 481 462 l 474 691 l 449 691 l 433 670 429 657 410 657 c 394 657 360 692 299 692 c 204 692 94 604 73 403 c 22 403 l 10 362 l 70 362 l 69 352 69 341 69 330 c 69 319 69 308 70 298 c 22 298 l 10 257 l 73 257 l 97 57 216 -12 295 -12 c 364 -12 427 25 484 123 c 458 142 l 425 101 384 37 316 37 c 256 37 189 84 173 257 c 335 257 l cp 500 0 m } ct_PSBuildGlyph } def end %%EndFile setglobal Adobe_CoolType_Core begin /$Oblique SetSubstituteStrategy end %%BeginResource: procset Adobe_AGM_Image 1.0 0 +%%Version: 1.0 0 +%%Copyright: Copyright(C)2000-2006 Adobe Systems, Inc. All Rights Reserved. +systemdict/setpacking known +{ + currentpacking + true setpacking +}if +userdict/Adobe_AGM_Image 71 dict dup begin put +/Adobe_AGM_Image_Id/Adobe_AGM_Image_1.0_0 def +/nd{ + null def +}bind def +/AGMIMG_&image nd +/AGMIMG_&colorimage nd +/AGMIMG_&imagemask nd +/AGMIMG_mbuf()def +/AGMIMG_ybuf()def +/AGMIMG_kbuf()def +/AGMIMG_c 0 def +/AGMIMG_m 0 def +/AGMIMG_y 0 def +/AGMIMG_k 0 def +/AGMIMG_tmp nd +/AGMIMG_imagestring0 nd +/AGMIMG_imagestring1 nd +/AGMIMG_imagestring2 nd +/AGMIMG_imagestring3 nd +/AGMIMG_imagestring4 nd +/AGMIMG_imagestring5 nd +/AGMIMG_cnt nd +/AGMIMG_fsave nd +/AGMIMG_colorAry nd +/AGMIMG_override nd +/AGMIMG_name nd +/AGMIMG_maskSource nd +/AGMIMG_flushfilters nd +/invert_image_samples nd +/knockout_image_samples nd +/img nd +/sepimg nd +/devnimg nd +/idximg nd +/ds +{ + Adobe_AGM_Core begin + Adobe_AGM_Image begin + /AGMIMG_&image systemdict/image get def + /AGMIMG_&imagemask systemdict/imagemask get def + /colorimage where{ + pop + /AGMIMG_&colorimage/colorimage ldf + }if + end + end +}def +/ps +{ + Adobe_AGM_Image begin + /AGMIMG_ccimage_exists{/customcolorimage where + { + pop + /Adobe_AGM_OnHost_Seps where + { + pop false + }{ + /Adobe_AGM_InRip_Seps where + { + pop false + }{ + true + }ifelse + }ifelse + }{ + false + }ifelse + }bdf + level2{ + /invert_image_samples + { + Adobe_AGM_Image/AGMIMG_tmp Decode length ddf + /Decode[Decode 1 get Decode 0 get]def + }def + /knockout_image_samples + { + Operator/imagemask ne{ + /Decode[1 1]def + }if + }def + }{ + /invert_image_samples + { + {1 exch sub}currenttransfer addprocs settransfer + }def + /knockout_image_samples + { + {pop 1}currenttransfer addprocs settransfer + }def + }ifelse + /img/imageormask ldf + /sepimg/sep_imageormask ldf + /devnimg/devn_imageormask ldf + /idximg/indexed_imageormask ldf + /_ctype 7 def + currentdict{ + dup xcheck 1 index type dup/arraytype eq exch/packedarraytype eq or and{ + bind + }if + def + }forall +}def +/pt +{ + end +}def +/dt +{ +}def +/AGMIMG_flushfilters +{ + dup type/arraytype ne + {1 array astore}if + dup 0 get currentfile ne + {dup 0 get flushfile}if + { + dup type/filetype eq + { + dup status 1 index currentfile ne and + {closefile} + {pop} + ifelse + }{pop}ifelse + }forall +}def +/AGMIMG_init_common +{ + currentdict/T known{/ImageType/T ldf currentdict/T undef}if + currentdict/W known{/Width/W ldf currentdict/W undef}if + currentdict/H known{/Height/H ldf currentdict/H undef}if + currentdict/M known{/ImageMatrix/M ldf currentdict/M undef}if + currentdict/BC known{/BitsPerComponent/BC ldf currentdict/BC undef}if + currentdict/D known{/Decode/D ldf currentdict/D undef}if + currentdict/DS known{/DataSource/DS ldf currentdict/DS undef}if + currentdict/O known{ + /Operator/O load 1 eq{ + /imagemask + }{ + /O load 2 eq{ + /image + }{ + /colorimage + }ifelse + }ifelse + def + currentdict/O undef + }if + currentdict/HSCI known{/HostSepColorImage/HSCI ldf currentdict/HSCI undef}if + currentdict/MD known{/MultipleDataSources/MD ldf currentdict/MD undef}if + currentdict/I known{/Interpolate/I ldf currentdict/I undef}if + currentdict/SI known{/SkipImageProc/SI ldf currentdict/SI undef}if + /DataSource load xcheck not{ + DataSource type/arraytype eq{ + DataSource 0 get type/filetype eq{ + /_Filters DataSource def + currentdict/MultipleDataSources known not{ + /DataSource DataSource dup length 1 sub get def + }if + }if + }if + currentdict/MultipleDataSources known not{ + /MultipleDataSources DataSource type/arraytype eq{ + DataSource length 1 gt + } + {false}ifelse def + }if + }if + /NComponents Decode length 2 div def + currentdict/SkipImageProc known not{/SkipImageProc{false}def}if +}bdf +/imageormask_sys +{ + begin + AGMIMG_init_common + save mark + level2{ + currentdict + Operator/imagemask eq{ + AGMIMG_&imagemask + }{ + use_mask{ + process_mask AGMIMG_&image + }{ + AGMIMG_&image + }ifelse + }ifelse + }{ + Width Height + Operator/imagemask eq{ + Decode 0 get 1 eq Decode 1 get 0 eq and + ImageMatrix/DataSource load + AGMIMG_&imagemask + }{ + BitsPerComponent ImageMatrix/DataSource load + AGMIMG_&image + }ifelse + }ifelse + currentdict/_Filters known{_Filters AGMIMG_flushfilters}if + cleartomark restore + end +}def +/overprint_plate +{ + currentoverprint{ + 0 get dup type/nametype eq{ + dup/DeviceGray eq{ + pop AGMCORE_black_plate not + }{ + /DeviceCMYK eq{ + AGMCORE_is_cmyk_sep not + }if + }ifelse + }{ + false exch + { + AGMOHS_sepink eq or + }forall + not + }ifelse + }{ + pop false + }ifelse +}def +/process_mask +{ + level3{ + dup begin + /ImageType 1 def + end + 4 dict begin + /DataDict exch def + /ImageType 3 def + /InterleaveType 3 def + /MaskDict 9 dict begin + /ImageType 1 def + /Width DataDict dup/MaskWidth known{/MaskWidth}{/Width}ifelse get def + /Height DataDict dup/MaskHeight known{/MaskHeight}{/Height}ifelse get def + /ImageMatrix[Width 0 0 Height neg 0 Height]def + /NComponents 1 def + /BitsPerComponent 1 def + /Decode DataDict dup/MaskD known{/MaskD}{[1 0]}ifelse get def + /DataSource Adobe_AGM_Core/AGMIMG_maskSource get def + currentdict end def + currentdict end + }if +}def +/use_mask +{ + dup/Mask known {dup/Mask get}{false}ifelse +}def +/imageormask +{ + begin + AGMIMG_init_common + SkipImageProc{ + currentdict consumeimagedata + } + { + save mark + level2 AGMCORE_host_sep not and{ + currentdict + Operator/imagemask eq DeviceN_PS2 not and{ + imagemask + }{ + AGMCORE_in_rip_sep currentoverprint and currentcolorspace 0 get/DeviceGray eq and{ + [/Separation/Black/DeviceGray{}]setcolorspace + /Decode[Decode 1 get Decode 0 get]def + }if + use_mask{ + process_mask image + }{ + DeviceN_NoneName DeviceN_PS2 Indexed_DeviceN level3 not and or or AGMCORE_in_rip_sep and + { + Names convert_to_process not{ + 2 dict begin + /imageDict xdf + /names_index 0 def + gsave + imageDict write_image_file{ + Names{ + dup(None)ne{ + [/Separation 3 -1 roll/DeviceGray{1 exch sub}]setcolorspace + Operator imageDict read_image_file + names_index 0 eq{true setoverprint}if + /names_index names_index 1 add def + }{ + pop + }ifelse + }forall + close_image_file + }if + grestore + end + }{ + Operator/imagemask eq{ + imagemask + }{ + image + }ifelse + }ifelse + }{ + Operator/imagemask eq{ + imagemask + }{ + image + }ifelse + }ifelse + }ifelse + }ifelse + }{ + Width Height + Operator/imagemask eq{ + Decode 0 get 1 eq Decode 1 get 0 eq and + ImageMatrix/DataSource load + /Adobe_AGM_OnHost_Seps where{ + pop imagemask + }{ + currentgray 1 ne{ + currentdict imageormask_sys + }{ + currentoverprint not{ + 1 AGMCORE_&setgray + currentdict imageormask_sys + }{ + currentdict ignoreimagedata + }ifelse + }ifelse + }ifelse + }{ + BitsPerComponent ImageMatrix + MultipleDataSources{ + 0 1 NComponents 1 sub{ + DataSource exch get + }for + }{ + /DataSource load + }ifelse + Operator/colorimage eq{ + AGMCORE_host_sep{ + MultipleDataSources level2 or NComponents 4 eq and{ + AGMCORE_is_cmyk_sep{ + MultipleDataSources{ + /DataSource DataSource 0 get xcheck + { + [ + DataSource 0 get/exec cvx + DataSource 1 get/exec cvx + DataSource 2 get/exec cvx + DataSource 3 get/exec cvx + /AGMCORE_get_ink_data cvx + ]cvx + }{ + DataSource aload pop AGMCORE_get_ink_data + }ifelse def + }{ + /DataSource + Width BitsPerComponent mul 7 add 8 idiv Height mul 4 mul + /DataSource load + filter_cmyk 0()/SubFileDecode filter def + }ifelse + /Decode[Decode 0 get Decode 1 get]def + /MultipleDataSources false def + /NComponents 1 def + /Operator/image def + invert_image_samples + 1 AGMCORE_&setgray + currentdict imageormask_sys + }{ + currentoverprint not Operator/imagemask eq and{ + 1 AGMCORE_&setgray + currentdict imageormask_sys + }{ + currentdict ignoreimagedata + }ifelse + }ifelse + }{ + MultipleDataSources NComponents AGMIMG_&colorimage + }ifelse + }{ + true NComponents colorimage + }ifelse + }{ + Operator/image eq{ + AGMCORE_host_sep{ + /DoImage true def + currentdict/HostSepColorImage known{HostSepColorImage not}{false}ifelse + { + AGMCORE_black_plate not Operator/imagemask ne and{ + /DoImage false def + currentdict ignoreimagedata + }if + }if + 1 AGMCORE_&setgray + DoImage + {currentdict imageormask_sys}if + }{ + use_mask{ + process_mask image + }{ + image + }ifelse + }ifelse + }{ + Operator/knockout eq{ + pop pop pop pop pop + currentcolorspace overprint_plate not{ + knockout_unitsq + }if + }if + }ifelse + }ifelse + }ifelse + }ifelse + cleartomark restore + }ifelse + currentdict/_Filters known{_Filters AGMIMG_flushfilters}if + end +}def +/sep_imageormask +{ + /sep_colorspace_dict AGMCORE_gget begin + CSA map_csa + begin + AGMIMG_init_common + SkipImageProc{ + currentdict consumeimagedata + }{ + save mark + AGMCORE_avoid_L2_sep_space{ + /Decode[Decode 0 get 255 mul Decode 1 get 255 mul]def + }if + AGMIMG_ccimage_exists + MappedCSA 0 get/DeviceCMYK eq and + currentdict/Components known and + Name()ne and + Name(All)ne and + Operator/image eq and + AGMCORE_producing_seps not and + level2 not and + { + Width Height BitsPerComponent ImageMatrix + [ + /DataSource load/exec cvx + { + 0 1 2 index length 1 sub{ + 1 index exch + 2 copy get 255 xor put + }for + }/exec cvx + ]cvx bind + MappedCSA 0 get/DeviceCMYK eq{ + Components aload pop + }{ + 0 0 0 Components aload pop 1 exch sub + }ifelse + Name findcmykcustomcolor + customcolorimage + }{ + AGMCORE_producing_seps not{ + level2{ + //Adobe_AGM_Core/AGMCORE_pattern_paint_type get 2 ne AGMCORE_avoid_L2_sep_space not and currentcolorspace 0 get/Separation ne and{ + [/Separation Name MappedCSA sep_proc_name exch dup 0 get 15 string cvs(/Device)anchorsearch{pop pop 0 get}{pop}ifelse exch load]setcolorspace_opt + /sep_tint AGMCORE_gget setcolor + }if + currentdict imageormask + }{ + currentdict + Operator/imagemask eq{ + imageormask + }{ + sep_imageormask_lev1 + }ifelse + }ifelse + }{ + AGMCORE_host_sep{ + Operator/knockout eq{ + currentdict/ImageMatrix get concat + knockout_unitsq + }{ + currentgray 1 ne{ + AGMCORE_is_cmyk_sep Name(All)ne and{ + level2{ + Name AGMCORE_IsSeparationAProcessColor + { + Operator/imagemask eq{ + //Adobe_AGM_Core/AGMCORE_pattern_paint_type get 2 ne{ + /sep_tint AGMCORE_gget 1 exch sub AGMCORE_&setcolor + }if + }{ + invert_image_samples + }ifelse + }{ + //Adobe_AGM_Core/AGMCORE_pattern_paint_type get 2 ne{ + [/Separation Name[/DeviceGray] + { + sep_colorspace_proc AGMCORE_get_ink_data + 1 exch sub + }bind + ]AGMCORE_&setcolorspace + /sep_tint AGMCORE_gget AGMCORE_&setcolor + }if + }ifelse + currentdict imageormask_sys + }{ + currentdict + Operator/imagemask eq{ + imageormask_sys + }{ + sep_image_lev1_sep + }ifelse + }ifelse + }{ + Operator/imagemask ne{ + invert_image_samples + }if + currentdict imageormask_sys + }ifelse + }{ + currentoverprint not Name(All)eq or Operator/imagemask eq and{ + currentdict imageormask_sys + }{ + currentoverprint not + { + gsave + knockout_unitsq + grestore + }if + currentdict consumeimagedata + }ifelse + }ifelse + }ifelse + }{ + //Adobe_AGM_Core/AGMCORE_pattern_paint_type get 2 ne{ + currentcolorspace 0 get/Separation ne{ + [/Separation Name MappedCSA sep_proc_name exch 0 get exch load]setcolorspace_opt + /sep_tint AGMCORE_gget setcolor + }if + }if + currentoverprint + MappedCSA 0 get/DeviceCMYK eq and + Name AGMCORE_IsSeparationAProcessColor not and + //Adobe_AGM_Core/AGMCORE_pattern_paint_type get 2 ne{Name inRip_spot_has_ink not and}{false}ifelse + Name(All)ne and{ + imageormask_l2_overprint + }{ + currentdict imageormask + }ifelse + }ifelse + }ifelse + }ifelse + cleartomark restore + }ifelse + currentdict/_Filters known{_Filters AGMIMG_flushfilters}if + end + end +}def +/colorSpaceElemCnt +{ + mark currentcolor counttomark dup 2 add 1 roll cleartomark +}bdf +/devn_sep_datasource +{ + 1 dict begin + /dataSource xdf + [ + 0 1 dataSource length 1 sub{ + dup currentdict/dataSource get/exch cvx/get cvx/exec cvx + /exch cvx names_index/ne cvx[/pop cvx]cvx/if cvx + }for + ]cvx bind + end +}bdf +/devn_alt_datasource +{ + 11 dict begin + /convProc xdf + /origcolorSpaceElemCnt xdf + /origMultipleDataSources xdf + /origBitsPerComponent xdf + /origDecode xdf + /origDataSource xdf + /dsCnt origMultipleDataSources{origDataSource length}{1}ifelse def + /DataSource origMultipleDataSources + { + [ + BitsPerComponent 8 idiv origDecode length 2 idiv mul string + 0 1 origDecode length 2 idiv 1 sub + { + dup 7 mul 1 add index exch dup BitsPerComponent 8 idiv mul exch + origDataSource exch get 0()/SubFileDecode filter + BitsPerComponent 8 idiv string/readstring cvx/pop cvx/putinterval cvx + }for + ]bind cvx + }{origDataSource}ifelse 0()/SubFileDecode filter def + [ + origcolorSpaceElemCnt string + 0 2 origDecode length 2 sub + { + dup origDecode exch get dup 3 -1 roll 1 add origDecode exch get exch sub 2 BitsPerComponent exp 1 sub div + 1 BitsPerComponent 8 idiv{DataSource/read cvx/not cvx{0}/if cvx/mul cvx}repeat/mul cvx/add cvx + }for + /convProc load/exec cvx + origcolorSpaceElemCnt 1 sub -1 0 + { + /dup cvx 2/add cvx/index cvx + 3 1/roll cvx/exch cvx 255/mul cvx/cvi cvx/put cvx + }for + ]bind cvx 0()/SubFileDecode filter + end +}bdf +/devn_imageormask +{ + /devicen_colorspace_dict AGMCORE_gget begin + CSA map_csa + 2 dict begin + dup + /srcDataStrs[3 -1 roll begin + AGMIMG_init_common + currentdict/MultipleDataSources known{MultipleDataSources{DataSource length}{1}ifelse}{1}ifelse + { + Width Decode length 2 div mul cvi + { + dup 65535 gt{1 add 2 div cvi}{exit}ifelse + }loop + string + }repeat + end]def + /dstDataStr srcDataStrs 0 get length string def + begin + AGMIMG_init_common + SkipImageProc{ + currentdict consumeimagedata + }{ + save mark + AGMCORE_producing_seps not{ + level3 not{ + Operator/imagemask ne{ + /DataSource[[ + DataSource Decode BitsPerComponent currentdict/MultipleDataSources known{MultipleDataSources}{false}ifelse + colorSpaceElemCnt/devicen_colorspace_dict AGMCORE_gget/TintTransform get + devn_alt_datasource 1/string cvx/readstring cvx/pop cvx]cvx colorSpaceElemCnt 1 sub{dup}repeat]def + /MultipleDataSources true def + /Decode colorSpaceElemCnt[exch{0 1}repeat]def + }if + }if + currentdict imageormask + }{ + AGMCORE_host_sep{ + Names convert_to_process{ + CSA get_csa_by_name 0 get/DeviceCMYK eq{ + /DataSource + Width BitsPerComponent mul 7 add 8 idiv Height mul 4 mul + DataSource Decode BitsPerComponent currentdict/MultipleDataSources known{MultipleDataSources}{false}ifelse + 4/devicen_colorspace_dict AGMCORE_gget/TintTransform get + devn_alt_datasource + filter_cmyk 0()/SubFileDecode filter def + /MultipleDataSources false def + /Decode[1 0]def + /DeviceGray setcolorspace + currentdict imageormask_sys + }{ + AGMCORE_report_unsupported_color_space + AGMCORE_black_plate{ + /DataSource + DataSource Decode BitsPerComponent currentdict/MultipleDataSources known{MultipleDataSources}{false}ifelse + CSA get_csa_by_name 0 get/DeviceRGB eq{3}{1}ifelse/devicen_colorspace_dict AGMCORE_gget/TintTransform get + devn_alt_datasource + /MultipleDataSources false def + /Decode colorSpaceElemCnt[exch{0 1}repeat]def + currentdict imageormask_sys + }{ + gsave + knockout_unitsq + grestore + currentdict consumeimagedata + }ifelse + }ifelse + } + { + /devicen_colorspace_dict AGMCORE_gget/names_index known{ + Operator/imagemask ne{ + MultipleDataSources{ + /DataSource[DataSource devn_sep_datasource/exec cvx]cvx def + /MultipleDataSources false def + }{ + /DataSource/DataSource load dstDataStr srcDataStrs 0 get filter_devn def + }ifelse + invert_image_samples + }if + currentdict imageormask_sys + }{ + currentoverprint not Operator/imagemask eq and{ + currentdict imageormask_sys + }{ + currentoverprint not + { + gsave + knockout_unitsq + grestore + }if + currentdict consumeimagedata + }ifelse + }ifelse + }ifelse + }{ + currentdict imageormask + }ifelse + }ifelse + cleartomark restore + }ifelse + currentdict/_Filters known{_Filters AGMIMG_flushfilters}if + end + end + end +}def +/imageormask_l2_overprint +{ + currentdict + currentcmykcolor add add add 0 eq{ + currentdict consumeimagedata + }{ + level3{ + currentcmykcolor + /AGMIMG_k xdf + /AGMIMG_y xdf + /AGMIMG_m xdf + /AGMIMG_c xdf + Operator/imagemask eq{ + [/DeviceN[ + AGMIMG_c 0 ne{/Cyan}if + AGMIMG_m 0 ne{/Magenta}if + AGMIMG_y 0 ne{/Yellow}if + AGMIMG_k 0 ne{/Black}if + ]/DeviceCMYK{}]setcolorspace + AGMIMG_c 0 ne{AGMIMG_c}if + AGMIMG_m 0 ne{AGMIMG_m}if + AGMIMG_y 0 ne{AGMIMG_y}if + AGMIMG_k 0 ne{AGMIMG_k}if + setcolor + }{ + /Decode[Decode 0 get 255 mul Decode 1 get 255 mul]def + [/Indexed + [ + /DeviceN[ + AGMIMG_c 0 ne{/Cyan}if + AGMIMG_m 0 ne{/Magenta}if + AGMIMG_y 0 ne{/Yellow}if + AGMIMG_k 0 ne{/Black}if + ] + /DeviceCMYK{ + AGMIMG_k 0 eq{0}if + AGMIMG_y 0 eq{0 exch}if + AGMIMG_m 0 eq{0 3 1 roll}if + AGMIMG_c 0 eq{0 4 1 roll}if + } + ] + 255 + { + 255 div + mark exch + dup dup dup + AGMIMG_k 0 ne{ + /sep_tint AGMCORE_gget mul MappedCSA sep_proc_name exch pop load exec 4 1 roll pop pop pop + counttomark 1 roll + }{ + pop + }ifelse + AGMIMG_y 0 ne{ + /sep_tint AGMCORE_gget mul MappedCSA sep_proc_name exch pop load exec 4 2 roll pop pop pop + counttomark 1 roll + }{ + pop + }ifelse + AGMIMG_m 0 ne{ + /sep_tint AGMCORE_gget mul MappedCSA sep_proc_name exch pop load exec 4 3 roll pop pop pop + counttomark 1 roll + }{ + pop + }ifelse + AGMIMG_c 0 ne{ + /sep_tint AGMCORE_gget mul MappedCSA sep_proc_name exch pop load exec pop pop pop + counttomark 1 roll + }{ + pop + }ifelse + counttomark 1 add -1 roll pop + } + ]setcolorspace + }ifelse + imageormask_sys + }{ + write_image_file{ + currentcmykcolor + 0 ne{ + [/Separation/Black/DeviceGray{}]setcolorspace + gsave + /Black + [{1 exch sub/sep_tint AGMCORE_gget mul}/exec cvx MappedCSA sep_proc_name cvx exch pop{4 1 roll pop pop pop 1 exch sub}/exec cvx] + cvx modify_halftone_xfer + Operator currentdict read_image_file + grestore + }if + 0 ne{ + [/Separation/Yellow/DeviceGray{}]setcolorspace + gsave + /Yellow + [{1 exch sub/sep_tint AGMCORE_gget mul}/exec cvx MappedCSA sep_proc_name cvx exch pop{4 2 roll pop pop pop 1 exch sub}/exec cvx] + cvx modify_halftone_xfer + Operator currentdict read_image_file + grestore + }if + 0 ne{ + [/Separation/Magenta/DeviceGray{}]setcolorspace + gsave + /Magenta + [{1 exch sub/sep_tint AGMCORE_gget mul}/exec cvx MappedCSA sep_proc_name cvx exch pop{4 3 roll pop pop pop 1 exch sub}/exec cvx] + cvx modify_halftone_xfer + Operator currentdict read_image_file + grestore + }if + 0 ne{ + [/Separation/Cyan/DeviceGray{}]setcolorspace + gsave + /Cyan + [{1 exch sub/sep_tint AGMCORE_gget mul}/exec cvx MappedCSA sep_proc_name cvx exch pop{pop pop pop 1 exch sub}/exec cvx] + cvx modify_halftone_xfer + Operator currentdict read_image_file + grestore + }if + close_image_file + }{ + imageormask + }ifelse + }ifelse + }ifelse +}def +/indexed_imageormask +{ + begin + AGMIMG_init_common + save mark + currentdict + AGMCORE_host_sep{ + Operator/knockout eq{ + /indexed_colorspace_dict AGMCORE_gget dup/CSA known{ + /CSA get get_csa_by_name + }{ + /Names get + }ifelse + overprint_plate not{ + knockout_unitsq + }if + }{ + Indexed_DeviceN{ + /devicen_colorspace_dict AGMCORE_gget dup/names_index known exch/Names get convert_to_process or{ + indexed_image_lev2_sep + }{ + currentoverprint not{ + knockout_unitsq + }if + currentdict consumeimagedata + }ifelse + }{ + AGMCORE_is_cmyk_sep{ + Operator/imagemask eq{ + imageormask_sys + }{ + level2{ + indexed_image_lev2_sep + }{ + indexed_image_lev1_sep + }ifelse + }ifelse + }{ + currentoverprint not{ + knockout_unitsq + }if + currentdict consumeimagedata + }ifelse + }ifelse + }ifelse + }{ + level2{ + Indexed_DeviceN{ + /indexed_colorspace_dict AGMCORE_gget begin + }{ + /indexed_colorspace_dict AGMCORE_gget dup null ne + { + begin + currentdict/CSDBase known{CSDBase/CSD get_res/MappedCSA get}{CSA}ifelse + get_csa_by_name 0 get/DeviceCMYK eq ps_level 3 ge and ps_version 3015.007 lt and + AGMCORE_in_rip_sep and{ + [/Indexed[/DeviceN[/Cyan/Magenta/Yellow/Black]/DeviceCMYK{}]HiVal Lookup] + setcolorspace + }if + end + } + {pop}ifelse + }ifelse + imageormask + Indexed_DeviceN{ + end + }if + }{ + Operator/imagemask eq{ + imageormask + }{ + indexed_imageormask_lev1 + }ifelse + }ifelse + }ifelse + cleartomark restore + currentdict/_Filters known{_Filters AGMIMG_flushfilters}if + end +}def +/indexed_image_lev2_sep +{ + /indexed_colorspace_dict AGMCORE_gget begin + begin + Indexed_DeviceN not{ + currentcolorspace + dup 1/DeviceGray put + dup 3 + currentcolorspace 2 get 1 add string + 0 1 2 3 AGMCORE_get_ink_data 4 currentcolorspace 3 get length 1 sub + { + dup 4 idiv exch currentcolorspace 3 get exch get 255 exch sub 2 index 3 1 roll put + }for + put setcolorspace + }if + currentdict + Operator/imagemask eq{ + AGMIMG_&imagemask + }{ + use_mask{ + process_mask AGMIMG_&image + }{ + AGMIMG_&image + }ifelse + }ifelse + end end +}def + /OPIimage + { + dup type/dicttype ne{ + 10 dict begin + /DataSource xdf + /ImageMatrix xdf + /BitsPerComponent xdf + /Height xdf + /Width xdf + /ImageType 1 def + /Decode[0 1 def] + currentdict + end + }if + dup begin + /NComponents 1 cdndf + /MultipleDataSources false cdndf + /SkipImageProc{false}cdndf + /Decode[ + 0 + currentcolorspace 0 get/Indexed eq{ + 2 BitsPerComponent exp 1 sub + }{ + 1 + }ifelse + ]cdndf + /Operator/image cdndf + end + /sep_colorspace_dict AGMCORE_gget null eq{ + imageormask + }{ + gsave + dup begin invert_image_samples end + sep_imageormask + grestore + }ifelse + }def +/cachemask_level2 +{ + 3 dict begin + /LZWEncode filter/WriteFilter xdf + /readBuffer 256 string def + /ReadFilter + currentfile + 0(%EndMask)/SubFileDecode filter + /ASCII85Decode filter + /RunLengthDecode filter + def + { + ReadFilter readBuffer readstring exch + WriteFilter exch writestring + not{exit}if + }loop + WriteFilter closefile + end +}def +/spot_alias +{ + /mapto_sep_imageormask + { + dup type/dicttype ne{ + 12 dict begin + /ImageType 1 def + /DataSource xdf + /ImageMatrix xdf + /BitsPerComponent xdf + /Height xdf + /Width xdf + /MultipleDataSources false def + }{ + begin + }ifelse + /Decode[/customcolor_tint AGMCORE_gget 0]def + /Operator/image def + /SkipImageProc{false}def + currentdict + end + sep_imageormask + }bdf + /customcolorimage + { + Adobe_AGM_Image/AGMIMG_colorAry xddf + /customcolor_tint AGMCORE_gget + << + /Name AGMIMG_colorAry 4 get + /CSA[/DeviceCMYK] + /TintMethod/Subtractive + /TintProc null + /MappedCSA null + /NComponents 4 + /Components[AGMIMG_colorAry aload pop pop] + >> + setsepcolorspace + mapto_sep_imageormask + }ndf + Adobe_AGM_Image/AGMIMG_&customcolorimage/customcolorimage load put + /customcolorimage + { + Adobe_AGM_Image/AGMIMG_override false put + current_spot_alias{dup 4 get map_alias}{false}ifelse + { + false set_spot_alias + /customcolor_tint AGMCORE_gget exch setsepcolorspace + pop + mapto_sep_imageormask + true set_spot_alias + }{ + //Adobe_AGM_Image/AGMIMG_&customcolorimage get exec + }ifelse + }bdf +}def +/snap_to_device +{ + 6 dict begin + matrix currentmatrix + dup 0 get 0 eq 1 index 3 get 0 eq and + 1 index 1 get 0 eq 2 index 2 get 0 eq and or exch pop + { + 1 1 dtransform 0 gt exch 0 gt/AGMIMG_xSign? exch def/AGMIMG_ySign? exch def + 0 0 transform + AGMIMG_ySign?{floor 0.1 sub}{ceiling 0.1 add}ifelse exch + AGMIMG_xSign?{floor 0.1 sub}{ceiling 0.1 add}ifelse exch + itransform/AGMIMG_llY exch def/AGMIMG_llX exch def + 1 1 transform + AGMIMG_ySign?{ceiling 0.1 add}{floor 0.1 sub}ifelse exch + AGMIMG_xSign?{ceiling 0.1 add}{floor 0.1 sub}ifelse exch + itransform/AGMIMG_urY exch def/AGMIMG_urX exch def + [AGMIMG_urX AGMIMG_llX sub 0 0 AGMIMG_urY AGMIMG_llY sub AGMIMG_llX AGMIMG_llY]concat + }{ + }ifelse + end +}def +level2 not{ + /colorbuf + { + 0 1 2 index length 1 sub{ + dup 2 index exch get + 255 exch sub + 2 index + 3 1 roll + put + }for + }def + /tint_image_to_color + { + begin + Width Height BitsPerComponent ImageMatrix + /DataSource load + end + Adobe_AGM_Image begin + /AGMIMG_mbuf 0 string def + /AGMIMG_ybuf 0 string def + /AGMIMG_kbuf 0 string def + { + colorbuf dup length AGMIMG_mbuf length ne + { + dup length dup dup + /AGMIMG_mbuf exch string def + /AGMIMG_ybuf exch string def + /AGMIMG_kbuf exch string def + }if + dup AGMIMG_mbuf copy AGMIMG_ybuf copy AGMIMG_kbuf copy pop + } + addprocs + {AGMIMG_mbuf}{AGMIMG_ybuf}{AGMIMG_kbuf}true 4 colorimage + end + }def + /sep_imageormask_lev1 + { + begin + MappedCSA 0 get dup/DeviceRGB eq exch/DeviceCMYK eq or has_color not and{ + { + 255 mul round cvi GrayLookup exch get + }currenttransfer addprocs settransfer + currentdict imageormask + }{ + /sep_colorspace_dict AGMCORE_gget/Components known{ + MappedCSA 0 get/DeviceCMYK eq{ + Components aload pop + }{ + 0 0 0 Components aload pop 1 exch sub + }ifelse + Adobe_AGM_Image/AGMIMG_k xddf + Adobe_AGM_Image/AGMIMG_y xddf + Adobe_AGM_Image/AGMIMG_m xddf + Adobe_AGM_Image/AGMIMG_c xddf + AGMIMG_y 0.0 eq AGMIMG_m 0.0 eq and AGMIMG_c 0.0 eq and{ + {AGMIMG_k mul 1 exch sub}currenttransfer addprocs settransfer + currentdict imageormask + }{ + currentcolortransfer + {AGMIMG_k mul 1 exch sub}exch addprocs 4 1 roll + {AGMIMG_y mul 1 exch sub}exch addprocs 4 1 roll + {AGMIMG_m mul 1 exch sub}exch addprocs 4 1 roll + {AGMIMG_c mul 1 exch sub}exch addprocs 4 1 roll + setcolortransfer + currentdict tint_image_to_color + }ifelse + }{ + MappedCSA 0 get/DeviceGray eq{ + {255 mul round cvi ColorLookup exch get 0 get}currenttransfer addprocs settransfer + currentdict imageormask + }{ + MappedCSA 0 get/DeviceCMYK eq{ + currentcolortransfer + {255 mul round cvi ColorLookup exch get 3 get 1 exch sub}exch addprocs 4 1 roll + {255 mul round cvi ColorLookup exch get 2 get 1 exch sub}exch addprocs 4 1 roll + {255 mul round cvi ColorLookup exch get 1 get 1 exch sub}exch addprocs 4 1 roll + {255 mul round cvi ColorLookup exch get 0 get 1 exch sub}exch addprocs 4 1 roll + setcolortransfer + currentdict tint_image_to_color + }{ + currentcolortransfer + {pop 1}exch addprocs 4 1 roll + {255 mul round cvi ColorLookup exch get 2 get}exch addprocs 4 1 roll + {255 mul round cvi ColorLookup exch get 1 get}exch addprocs 4 1 roll + {255 mul round cvi ColorLookup exch get 0 get}exch addprocs 4 1 roll + setcolortransfer + currentdict tint_image_to_color + }ifelse + }ifelse + }ifelse + }ifelse + end + }def + /sep_image_lev1_sep + { + begin + /sep_colorspace_dict AGMCORE_gget/Components known{ + Components aload pop + Adobe_AGM_Image/AGMIMG_k xddf + Adobe_AGM_Image/AGMIMG_y xddf + Adobe_AGM_Image/AGMIMG_m xddf + Adobe_AGM_Image/AGMIMG_c xddf + {AGMIMG_c mul 1 exch sub} + {AGMIMG_m mul 1 exch sub} + {AGMIMG_y mul 1 exch sub} + {AGMIMG_k mul 1 exch sub} + }{ + {255 mul round cvi ColorLookup exch get 0 get 1 exch sub} + {255 mul round cvi ColorLookup exch get 1 get 1 exch sub} + {255 mul round cvi ColorLookup exch get 2 get 1 exch sub} + {255 mul round cvi ColorLookup exch get 3 get 1 exch sub} + }ifelse + AGMCORE_get_ink_data currenttransfer addprocs settransfer + currentdict imageormask_sys + end + }def + /indexed_imageormask_lev1 + { + /indexed_colorspace_dict AGMCORE_gget begin + begin + currentdict + MappedCSA 0 get dup/DeviceRGB eq exch/DeviceCMYK eq or has_color not and{ + {HiVal mul round cvi GrayLookup exch get HiVal div}currenttransfer addprocs settransfer + imageormask + }{ + MappedCSA 0 get/DeviceGray eq{ + {HiVal mul round cvi Lookup exch get HiVal div}currenttransfer addprocs settransfer + imageormask + }{ + MappedCSA 0 get/DeviceCMYK eq{ + currentcolortransfer + {4 mul HiVal mul round cvi 3 add Lookup exch get HiVal div 1 exch sub}exch addprocs 4 1 roll + {4 mul HiVal mul round cvi 2 add Lookup exch get HiVal div 1 exch sub}exch addprocs 4 1 roll + {4 mul HiVal mul round cvi 1 add Lookup exch get HiVal div 1 exch sub}exch addprocs 4 1 roll + {4 mul HiVal mul round cvi Lookup exch get HiVal div 1 exch sub}exch addprocs 4 1 roll + setcolortransfer + tint_image_to_color + }{ + currentcolortransfer + {pop 1}exch addprocs 4 1 roll + {3 mul HiVal mul round cvi 2 add Lookup exch get HiVal div}exch addprocs 4 1 roll + {3 mul HiVal mul round cvi 1 add Lookup exch get HiVal div}exch addprocs 4 1 roll + {3 mul HiVal mul round cvi Lookup exch get HiVal div}exch addprocs 4 1 roll + setcolortransfer + tint_image_to_color + }ifelse + }ifelse + }ifelse + end end + }def + /indexed_image_lev1_sep + { + /indexed_colorspace_dict AGMCORE_gget begin + begin + {4 mul HiVal mul round cvi Lookup exch get HiVal div 1 exch sub} + {4 mul HiVal mul round cvi 1 add Lookup exch get HiVal div 1 exch sub} + {4 mul HiVal mul round cvi 2 add Lookup exch get HiVal div 1 exch sub} + {4 mul HiVal mul round cvi 3 add Lookup exch get HiVal div 1 exch sub} + AGMCORE_get_ink_data currenttransfer addprocs settransfer + currentdict imageormask_sys + end end + }def +}if +end +systemdict/setpacking known +{setpacking}if +%%EndResource +currentdict Adobe_AGM_Utils eq {end} if +%%EndProlog +%%BeginSetup +Adobe_AGM_Utils begin +2 2010 Adobe_AGM_Core/ds gx +Adobe_CoolType_Core/ds get exec Adobe_AGM_Image/ds gx +currentdict Adobe_AGM_Utils eq {end} if +%%EndSetup +%%Page: (Page 1) 1 +%%EndPageComments +%%BeginPageSetup +%ADOBeginClientInjection: PageSetup Start "AI11EPS" +%AI12_RMC_Transparency: Balance=75 RasterRes=300 GradRes=150 Text=0 Stroke=1 Clip=1 OP=0 +%ADOEndClientInjection: PageSetup Start "AI11EPS" +Adobe_AGM_Utils begin +Adobe_AGM_Core/ps gx +Adobe_AGM_Utils/capture_cpd gx +Adobe_CoolType_Core/ps get exec Adobe_AGM_Image/ps gx +%ADOBeginClientInjection: PageSetup End "AI11EPS" +/currentdistillerparams where {pop currentdistillerparams /CoreDistVersion get 5000 lt} {true} ifelse { userdict /AI11_PDFMark5 /cleartomark load put userdict /AI11_ReadMetadata_PDFMark5 {flushfile cleartomark } bind put} { userdict /AI11_PDFMark5 /pdfmark load put userdict /AI11_ReadMetadata_PDFMark5 {/PUT pdfmark} bind put } ifelse [/NamespacePush AI11_PDFMark5 [/_objdef {ai_metadata_stream_123} /type /stream /OBJ AI11_PDFMark5 [{ai_metadata_stream_123} currentfile 0 (% &&end XMP packet marker&&) /SubFileDecode filter AI11_ReadMetadata_PDFMark5 + + + + application/postscript + + + Print + + + + + Adobe Illustrator CS3 + 2010-05-25T11:06:31-06:00 + 2010-05-25T11:06:31-06:00 + 2010-05-25T11:06:31-06:00 + + + + 256 + 116 + JPEG + /9j/4AAQSkZJRgABAgEAlgCWAAD/7QAsUGhvdG9zaG9wIDMuMAA4QklNA+0AAAAAABAAlgAAAAEA AQCWAAAAAQAB/+4ADkFkb2JlAGTAAAAAAf/bAIQABgQEBAUEBgUFBgkGBQYJCwgGBggLDAoKCwoK DBAMDAwMDAwQDA4PEA8ODBMTFBQTExwbGxscHx8fHx8fHx8fHwEHBwcNDA0YEBAYGhURFRofHx8f Hx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8f/8AAEQgAdAEAAwER AAIRAQMRAf/EAaIAAAAHAQEBAQEAAAAAAAAAAAQFAwIGAQAHCAkKCwEAAgIDAQEBAQEAAAAAAAAA AQACAwQFBgcICQoLEAACAQMDAgQCBgcDBAIGAnMBAgMRBAAFIRIxQVEGE2EicYEUMpGhBxWxQiPB UtHhMxZi8CRygvElQzRTkqKyY3PCNUQnk6OzNhdUZHTD0uIIJoMJChgZhJRFRqS0VtNVKBry4/PE 1OT0ZXWFlaW1xdXl9WZ2hpamtsbW5vY3R1dnd4eXp7fH1+f3OEhYaHiImKi4yNjo+Ck5SVlpeYmZ qbnJ2en5KjpKWmp6ipqqusra6voRAAICAQIDBQUEBQYECAMDbQEAAhEDBCESMUEFURNhIgZxgZEy obHwFMHR4SNCFVJicvEzJDRDghaSUyWiY7LCB3PSNeJEgxdUkwgJChgZJjZFGidkdFU38qOzwygp 0+PzhJSktMTU5PRldYWVpbXF1eX1RlZmdoaWprbG1ub2R1dnd4eXp7fH1+f3OEhYaHiImKi4yNjo +DlJWWl5iZmpucnZ6fkqOkpaanqKmqq6ytrq+v/aAAwDAQACEQMRAD8A735w/NHyr5VuVs715bnU WAb6jaIJJVVtwX5FFWvgWr7Zm6bs/JmFjaPeXB1XaOLAalvLuDGv+V92H/Uu6p/wC/1zM/kaX8+L hfy3D+bJ3/K+7D/qXdU/4Bf64/yNL+fFf5bh/Nk7/lfdh/1Luqf8Av8AXH+Rpfz4r/LcP5snf8r7 sP8AqXdU/wCAX+uP8jS/nxX+W4fzZO/5X3Yf9S7qn/AL/XH+Rpfz4r/LcP5snf8AK+7D/qXdU/4B f64/yNL+fFf5bh/Nk7/lfdh/1Luqf8Av9cf5Gl/Piv8ALcP5snf8r7sP+pd1T/gF/rj/ACNL+fFf 5bh/Nkl+s/8AOSuiaVbGSfQr5JWB+rxSlIg7DtU1oPE0NMry9lmAsyDOHa8ZmhGT5289fmr5z853 cj6pevHYk/utMgZktkHb4AfjP+U9TghjEeTTlyymd0k8ueaNf8t6lHqWiXstldxkHlG3wuAa8ZE+ y6nurCmSIBFFhGRibGxfa/5VfmFbee/KUOsLGIL2Nzb6jbLUqk6AE8K78GVgy/OlajNdlx8Jp3Wn zeJG+rMMqb3Yq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXzf5Hk+uxXuu3f73VL+4k ae4brQkNxHgKnt/DOvzjhqA+kB4rCeMmcvqJZT62YzfTvWxWnetitO9bFad62K071sVp3rYrSC1n XbLSNMuNRvH429uvJqbsx6KqjxY7DEmlp82+ZvMmoeYdXl1G9b4n+GGIGqxRg/Ci+w/E75hTlxFy YQ4QgLS0nupxDCvJyCxPZVUFmdj2VVBJPYZFkSpOEDkIaqOhO1ffFQ+gv+cRNSkTVvMWmdY5oILk exhdkPfv63h2zF1Q2Bc/QS9RHl+PvfTGYTtHYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FX Yq7FXzJ5Cl46DT/i5/4Z2OpHqeJ0v0/Fknr++Y9OS71/fGld6/vjSu9f3xpXev740rvX98aV3r++ NK8Z/NjzY2paoNItnrZWDH1aE0efo1f9T7I965iZ5702449WAgEmg3J6DKG1l/mbTx5T0uPy8wpr 98kdxr53BgjakkFj8x8Ms3+VwX9g1jE3uzlHh2PP8fj+xiGSYPov/nEPS2MnmTVWUhQLa1iegoST JJIK+1EzF1R2AdhoBuS+kMwnZuxV2KuxV2KuxV2KuxV2KuxV2KuxV2KuxV2KuxV2KuxV2KvljyZL x0an/Fr/AMM7PUD1PEaX6finvr++UU5Nu9f3xpbd6/vjS271/fGlt3r++NLbvX98aW0n82+Yv0No Vxdqf9II9K2H/Fr7A/7HdvoyGSXCLSBZp4OzMzFmNWJqSepJzWuUBT0T8rtGsdOsdR/MPW4RLpfl 6i6ZayfZu9UcfuI+oqsRIkeh8Oorlcz/AAjr9zdiAFyPIff+NywLUL+81G/uL+9lM15dyvPcTN1e SRizMfmTljUh8UPtP/nHzyu+gflhpwmUrc6qzalMp7fWAoi/5Ion05r9RK5e53Ojhw4/fu9Iyhyn Yq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXyb5Wl46XT/ixv4Z2ucep4fTH0pv9Yyq m+3fWMaW3fWMaW3fWMaW3fWMaW3fWMaW3mX5m6ybnU4dPQ/u7ReTjxkkAP4LT7zmBqpb034R1Yvp GlXur6raaXYx+reXsyQW8fSryMFFT2G+5zEJpyALNB6P+deoWGkLpP5caNJz03yzGDfyrsLjUZhy lkYVb7Ibb+Usy9srxb+o9fub85AqA5R+/q8ty1x2Vflh5Ml84edtN0QKxtZJPVv3X9i2i+KU17VH wg/zEZCc+EW2YsfHIB93xxxxRrFEoSNAFRFACqoFAAB0AzVu/ApdirsVdirsVdirsVdirsVdirsV dirsVdirsVdirsVdirsVdir5A0CXjYU/y2/hnc5Ru8HhOyZfWMqpt4nfWMaXid9YxpeJ31jGl4nf WMaXiWyXaxo0jtREBZj4AbnGl4njV/dveXs90/2p5Gc+3I1p9GaScuIkuyhGgA9X/I2xt9B0zzD+ Zuoxh7fy9A1vpSOPhkvp1CgVHgJFU/69e2Y+Xeo9/wBzl6f0gz/m8ve8ovr27v724vryVpru6kea 4mbdnkkYszH3JOXOPahih9a/84z/AJenQfKzeYr6LhqmuhWhDD4o7IbxjcbeqfjPiOOYOpyWa7na 6LFUeI9fu/a9mzGc52KuxV2KuxV2KuxV2KuxV2KuxV2KuxV2KuxV2KuxV2KuxV2KvjTS5StrT/KO d5MbvnsJUjPXOQpnxO9c40vE71zjS8TvXONLxO9c40vEgNcum/RdxGrhZJkaKOv7TMp+Ee5FaZVm HoPmzxy9QeZqrMwVQSzGgA6knNE7l7H+cjL5T8keVPy3gIW4hhGq65TiSbqbkFUsP5WMnX9njlOL 1Ey+DlZ/TGMPife8by5xXqf5R/kn5i8za9Y3msabPaeWI2E9zcTqYhOi/EscQbi7CToWXYCu9aZV lyiI83IwaczI29L7HjjSNFjjUJGgCoiigAGwAA7ZrXdgN4q7FXYq7FXYq7FXYq7FXYq7FXYq7FXY q7FXYq7FXYq7FXYq7FXxVaScYqe5zvyHzi6VvWOCl4nescaXid6xxpeJ3rHGl4nescaXiY75undo oRG9DCwd1H2hyqEb8Dmu152FdPwHYaGiTfX8FMPyV8tr5j/M7RrWVOVrBMb66FKrwtgZQrD+VnVU +nNNmnUSXc6fHxTASz8y/NH+KPPes60GL29xcMtoaAf6PFSKHYd/TQV98MI8IARlnxSMu9vyjr2t Wuo2ll5X062/TdzIsVtdvAl1dGRyOPA3AeKIg9GRFIHVsMgOvJjAkHbm+wBez/l9+W02peYr+bWL 3ToDPfXMjsxmuJGAWOMsPhQyMqJtsNyOua6uOdDZ3IPhY7kbLz3yF5LvvzV0/wDxl+YF9Pd6feSy fony/byvBZxRRu0bFlQhq8loNw1BVmau12TJ4fpi4uHCc3rmb7gyHWf+cdvJRgM/lZ7ryzrMQ5Wt 9Z3M5AcfZ5q7saf6hU5COpl13DbPQw/h2ISL/nHUeaIvM3nu08z3M11rNnJp9vcSzu0rH0xcqpDN uVKgFT3GS1NUK5MNECDK+e36XuOYrsHjX5tfn6nl/UD5Z8pwLqnmRmEMslDJFBK54iJUXeWap+z0 U7GpquZOLBe8uTgajV8J4Y81PQfyP1/zFEmp/mhr17qN5N+9/QsE5jtoeW5RuHw18REFA7E5KWcR 2gER0hnvkJ934/QyC4/5x2/KWSAxwaO9pLSkdzBdXXqofFecjrX/AFlOVjUz7206HEen2sH812X5 qflCo1fQ9Xm8x+TkZVnsdSJme2UnigZtmVd6B4yor1XxtiYZNiKLjzjkw7g3H8fjZ6n+W/5maB58 0Y32mkw3cHFdQ0+Q1kgdq0FaAOrUPFh19jUDHyYjAuZgzjIPNGecfy+8pecYIYfMNiLz6sJBayc5 I3iMvHmUZGXrwXr4YIZDHkyy4Yz+p8XweUIG/M9fJ8kzfVxrX6Ke4FOfpi69AuNqcuO+bLi9N+Vu lMKnw+dfbT7a8q+UPL3lTSv0XoNoLOy5mVo+TuWkYBWdmcsxJCjNbOZkbLu8eKMBUU4yDY7FXYq7 FXYq7FXYq7FXYq+Io2ouegPm0gv54op3PFadzxWnc8Vp3PFaYr5haZNScn7EsYA91/sYVzSa6xkP mPx9rutEAcY7wWd/lVMNB8hefPNleFwLKPRrA1oTJfPSQr/lRhUfNZk3IHx+TtMW0ZHyr5vLctaH 1P8A843flKdGsV84a1DTVb6OmlwOPigtnG8u/R5QfoT/AFiBhajLfpDs9Hgr1n4Ml/5yRt7ib8pd UaIErDLbSTAfyeui/TuwyGm+pt1o/dsP/wCcaPzT0c6JB5I1OZbbULaR/wBFM/wrPHM5kMQY/wC7 FdmoO4Ip0yzUYjfEGnRZwBwH4Pf8xHYpVp/lnS9P1/V9dtw4v9bFst8S1UP1NGjiKrTb4X3yRmSA O5rjjAkZd7Gfzq89v5M8h3d/bNx1S7IstNPXjNKCTJ/zzRWYe4AyzBDik1arLwQ25l4n/wA4teUI 9X806h5ov19YaQqrbGSpJurnlWTfqURW692B65k6mdRrvcLRY+KVno+p8wHbOxVRvbK0vrOeyvIl ntLmNop4XFVdHHFlI8CDhBo2iUQRRfFtnqOqflJ+bdykDSNDpt01vcxH4Tc2EhDgMOlXiKuvg1D2 zZECcfe6ME4p+77f7X2pa3NvdW0V1buJbedFlhlXcMjjkrD2IOa0ineAgiw+Mof/AFo4/wDgWv8A 91E5sR/d/wCb+h0k/wC9/wA8f7p9o5rXeOxV2KvJPy0/KDzR5Q8/6vrc+treaNfrKFgLO08rySB0 acMqxhkA+0p39gcycuYSjVbuDp9LLHMm9vxzet5jOcxrV/POn6d520HyiYzNf64lzLyVgBBHbxNI Gdab+oY2VfkcsGO4mXc0yzATEO9kuVtzsVdirsVfD6mgz0F84Ib5YrTuWK01zxWnc8C01zOKaSbz LFyt4pu6NxPyYf2Zre0oekSc/QSqRDL7qy1Fvyi8n+WNLiN1qHmjVLzU/qsYq5MFLOIHtRuLN4bV OaT+InuH7Xd0eCIG9kn9H63tf5Xf847eXPLcEOoeYo49Y14gMUkHK1tzT7McZ2dh/O30Ad8XJqCd hyc7BowN5bn7HsGYznIXVdLsNW0260zUIRPZXkTQ3ELdGRxQio3HsR0wxJBsMZREhR5PjL81PyY8 x+Rb2S5RHvfLrv8A6LqaCvAE7JOF+w46V+y3bwGxx5RL3ulz6c4zvyZJ+WX/ADkn5h0BodN8z+pr Ojr8K3JNbyEV6h2P75R4Oa/5VBTI5NOJcti24dXKOx3H2vqPQdf0fX9Kg1XR7pLywuRWKZK9tiCD QqwOxB3GYMomJou0hMSFjk8F/wCcv5pBB5VgDfuna+dl7FkFuFP0czmVpergdofw/H9DIf8AnE+G Nfy7v5QoEkmqzB3oKkLbwUFfAVOR1X1D3M+z/pPv/QHtOYrnuxV2Kvjn/nJm1WH817yQdbm2tpW+ YjEf6o82OA+gOl1YrIfx0fSn5N30t7+V3lqeU1dbKOGpp0grCvSn7KDMPOKmXZaWV4w+YIf/AFo4 /wDgWv8A91E5mj+7/wA39Dq5/wB7/nj/AHT7RzWu8diqR+cdS812GlLL5Y0ePWtSeVYzby3CWyRx lWJlZnpyoVC8Qa717ZOAiTuaDVllID0iy8Gb86/zdX80dI8ra1Fa6OW1Oytb+ytolk5xXEqV/eyN P9uOT7SEZlnDDhJG7rxqcpmInbcX+N3vPnC484waUreUrWzu9UaUKyX7ukKxcWLP8FCx5BRSo65i QEb9TsMpmB6Ob5V0TUPzOl/PdHL2l/52t5rmBVuy31MGO2lV0HpmMhFj5caU3zOkI8H9F1WOU/F7 5bvpPyTdfm5NqUy+c7PSLfTRCTA+mmYymfmtA3qSSDjw5dutMw5iFek7uyxHKT6gKTrzf5t0byno Fzrmry+naW4ACLQySyNskUakjkzH+poATkYQMjQbMuUQjZeNX3mv/nI7zFobeavL1lbaTozIZrLT VWGa8lt6FhJSdX57DagUttxU1zJEMUTR3LgHJnnHiGw+H6fx5Ib8kvz981eYPNdt5Z8yLFd/Xlk+ rX0cYikSSKNpaOqUQqyoRsoNfbHNgiBYTptVIyEZb28kztHjHYq7FXYq7FXYqgtYj9TTZh/KAw/2 JrmLrY3iLfpZVkD6k/KfyNb2tnofmC5iX1rfQrGy0wNQlBMhurqWn7LPLPw8eK/5W/I5snOPm9jp cI2n/RFfefvel5jua7FXYqtmhimieGZFkhkUpJG4DKysKFWB2IIxBQRb5+/N3/nG2zngn1zyRF6F 0gaS40RamOUAEk23Xi//ABX9k/s06HMxajpJ12o0dbw+X6v1MI/5xn853+kefIvL7yt+i9aEkckD V4pcRoXjkA7MeHA/PfoMs1ELj5ho0eQiYHQvRf8AnLLy9cXnlbSNbhUumk3MkVwACeMd2FHMnsA8 Kr82GU6WW5Dk6+BoHuU/+cSNYjl8sa3o+3q2l6t37lLmIJ+Btz9+HVDcFdBLYj4/j5PecxHYOxV2 Kviz/nIDUk1b83NXS0JmFu0NlGFqSZIolV0A8RKWXNlhFQDo9TK8hL658laI2heUNG0dwBLYWUEE 9DyHqpGBIQd+r1OYGSVyJdxhhwwA8nyRD/60cf8AwLX/AO6iczx/d/5v6HTz/vf88f7p9o5rXeOx V2Kvln8ywB/zk/o1B11DRif+DhzPh/dfAupy/wCMfEfofU2YDtny15V/9axn/wC2hqX/AFCT5n5P 7r4B1OH+/wDjL9L6lzAds+cP+cktXi1H8wvKvlK9u1ttEBguL+UuFRDdXBhZ5STRfTiTkCegY5m6 cVEnq6vWnimI3t+tn2q/nZo8sDaT+Xmnz+ZtYCelbR2cDrZW5+yjTSsEURr/AJO3bkvXKxgPOWwb 5asfTjFlB/kv+Ry+UJT5h190uvM8wbgqHlHarIDzCn9qRgaM3TsNty5s/FsOSNLpODeXP7nz/dWs 9pdTWtwhjuIHaKaNtiroeLA/IjO2jIEWOReJlExJB5hSwodirsVdirsVQup/8c+4/wBQ5j6v+7k2 6f6x73235ciSHy9pcUYokdpAijrssSgZxM/qL3mIege5Mci2OxV5h/zkLq8+jeTNO1aDeWw1mxuk X+Yws0gB+ZXMjTCyR5OFriREEfzv1vQdD1vTdc0i01fTJhPY3sYlgkHgeoPgynZh2O2UyiYmi5UJ iQBHJHEgAkmgG5JyLN8qflVosXmH/nIPUtY0pOehadfX1968Y4x8JGkS347ADmzhlX+UHwzYZTWP fm6fTx4stjlZP6n07rui6drmj3mkalF61jfRNDOnfiw6qezKd1PY5gxkQbDtpwEhRfKenQa/+Rf5 oRy6jG9zoN3ygN1Gvw3Nk7A8l7CWIhWKV6ileLAnPNZI7OnHFgyb/wBofWGl6pp2q6fBqOnXCXVj coJILiI8kZT4H8D4ZryCDRdxGQkLHJFYGTCvzU/M3SvInl6S7mdJdWuFZNLsK/FJJSgdlrX00O7H 6Opy3FiMj5OPqM4xjzeM/kB+VGp61ro8++aI5Pq6Sm609JxR7q5cl/rLV34Kx5Kf2m36DfJz5aHC HC0unMjxS5fe+m8wXaviu3ngb/nIcTiRfRbzWzrJUcSp1AkGvhmzA9H+b+h0UjeX/P8A98+1M1jv UHrWrWWj6TearfOI7SyheeZyQPhQVoK9z0Hvkoxs0xnMRBJ6KHljXYvMHl7T9bhhe3i1GBLiOGWn NVkFRWm3TGceE0jHPiiC+ZfzEYn/AJyk08E1A1XRQPYUtjmbD+6+B/S6qf8AjH+cPuD6tzAdw+Wf KzKv/OWExYgD9I6iKnbc2k4H45nz/uvgHU4v7/4n9L6H84eefL3lKyiuNWmb1blxFZ2MC+rdXEjE DjDEDVqV37fhmHDGZcnY5c0YDd8+/wDOUNjPpvn3QPMyW4e1ntox+8FVea0mLsrq3SqSIKEfxzM0 x9NOu10amD3j8fofRHlDX/L+veXrPUtBeM6dKg4RRBV9JqAtEyLsjrXdcw5xIO7ssU4yjceSQfmJ +aemeVTb6ZZIuq+ar+WKDT9Ejf4y0rABpSK+mtG+GvU9NqkTxYTLc7Bq1GpENhvLuQ3nv8l/L3mm 8bUYpn0zU5KetNEqvHJT9p4yVq3+UGHvXM3SdqTwjhI4ouJrOyseY8V8MmH/APQsv/fyf9OX/Zxm b/Lv9D/ZfscD+QP6f+x/a7/oWX/v5P8Apy/7OMf5d/of7L9i/wAgf0/9j+13/Qsv/fyf9OX/AGcY /wAu/wBD/ZfsX+QP6f8Asf2u/wChZf8Av5P+nL/s4x/l3+h/sv2L/IH9P/Y/td/0LL/38n/Tl/2c Y/y7/Q/2X7F/kD+n/sf2pR5v/wCcdn0zyrrGppr31hrCyuLr0DacOfoxtJx5es9K8fDIy7Y8QcPB z8/2L/Inh+vj+nfl+17x5dkSXy/pkkZ5I9pAyN4gxqQc0c/qLv8AEfSPcmGRbHYqxT8yvIEHnry/ FolxeNZQLdw3M0iIJGZIuQaNasoUsG2bengcsxZOA20Z8PiCrrdi9h+S+reVjKfIHmu70eGYlptO voo761d9hyVWCGM0Aqwq3vTLDnEvqDSNLKH0SpD6t+Xf5x+ZoZNO8w+cbWz0acUuYNKtiryKRRoy zem3FhWvxEeIOSGTHHcDdjLBmntKQr8e5nnkryN5d8maMulaHAY4a85ppCGmmkpTnK4AqfkAB2GU TyGRsuVixRgKCf5BtS7X/Luh+YdMk0zWrOO+sZd2hlFaMNgysKMrCuzKQRkoyMTYYTxxmKLy2T8l PNHlNLq7/LPzPc2BblIuh3oSe2lc/shnHFTQUDMhPi3fMgZ4y2kHDOklCzjl8Pxt9jyDWv8AnIX8 5LaafS7u6i069tmaC5C2sQlV1NGrzDgEewy8YIdziS1WXlf3PV/yt/K/yB5lsrbztqOoXHm/UbkD 1X1JqpDMlOUUlvVviTpxdmWlCBShynLllE0NnJ0+nhMcRPEXtYAAAAoBsAMxHYpB5z0LzFrWmLZ6 Hr7+XpS5M91FbpcO8ZUjgvNkMe+/JTXLMcgDuLac0JSFRPC8VP8AziFEWLnzY5cmpY2IrXxr9YzJ /Nju+39jg/ycf5w+X7WZ235T/mZbQJBF+Z98Y4xRedmkjU93eZmP0nK/Gh/N/HybRpco/j+z/jyV +YP+cf8Azd5ih9DWvzEvb22qG+rSWtIeSigb0luAlR40yQ1ERyj+Pkxlopy5zv4f8eenW3l29sfJ tp5e0vUmsrqxs7ezt9UWGORl+roqc/Rk5IeQToa9cx+IGVkOYIEQEQdwObyrV/8AnGSTWNYl1rUv OF5c6pMyu921vGH5IAEI4uOPEKAKdMyBqQBQDhy0JJsy3937XqnlLQ/MGkWssGseYJdfZivoSzQQ wNGqggisQq/LxYk5jzkDyFOZihKP1HieX+f/APnHS417znN5o0LXf0Rc3MiTyRmNy0c6AD1YpUdW BYry9j38L8eooUQ4uXRmUuIFlXkb8mdI8u6n+ndW1C58y+ZqUGrX7MxjFKfukZpCp47VZmPhTITz kihsG3FpRE8RPFJk3nTyVoHnHQ5NG1qEyWzsHjljIWWKRQQskTENRhUjoR2O2VwmYmw3ZcQmKLw9 v+cUtbs7qQ6R5t9C3kBBJhkjk4mo4t6clG2PtXwzKGqHc686A3sWefll+QegeSdTOsz3smsa0Ayw 3UqCKOIOKMyR8pDzIJBYudsqy5zIU5ODSCBu7L1HMdy3Yq7FXYq7FXYqhdW06LUtKvNOmNIr2CW3 kNK0WVCh2+TYYmjbGceKJHex/wDKu+ku/wAvdC9ZDHc2lsthdRt9pZrEm1lB9+cJyzMKmWrSyvGP l8tmVZU3uxV2KuxV2KuxV2KuxV2KvI/zw/JGHzpbnWtFVIfM9ugUqSES7jXokhOwkUbI5/1W2oVy MObh2PJwtVpeP1R+r73gX5e+fvNP5V+aJoby0mS2chNV0e4DRMwHSRQw+F1/ZboR7ZlzgJhwMWWW OX3h9WeXPzX/AC+8wael7Za3axBh8dtdSpbzxnuHjkYH6RUHsTmDLDIHk7WGpxyF3XvZFpmr6Tqt u1zpl7Bf26uY2mtpUmQOtKqWQsKivTKzEjm2xmJCwbReBk7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq 7FXYq7FXYq7FVsXpcT6XHjyavGlOXI8+nflWvviUBdil2KuxV2KuxV2KuxV2KuxV2KsV8+/8q1+p L/jb9G+jQ+h9f9P1KVHL0eX7yvjwy3Hx/wALRm8P+OnlUP8A0KN9cHD6t6vI/b/SXpV/2f7un4Zk fvvxThD8tfX/AGT2fyp/hL9Dx/4U+pfojkeH6O9L0OdBy/uvh5dK138cxZ8V+p2GLgr01XknGQbH Yq7FXYq7FXYq7FXYq7FXYq7FX//Z + + + + + + uuid:EB89571B7F69DF11AF0CB9E432C5A167 + uuid:EC89571B7F69DF11AF0CB9E432C5A167 + + uuid:EA89571B7F69DF11AF0CB9E432C5A167 + uuid:E989571B7F69DF11AF0CB9E432C5A167 + + + + Print + + + + 300.000000 + 200.000000 + Points + + 1 + False + False + + + PANTONE 3005 U + PANTONE 309 U + PANTONE 2905 U + + + + + + Default Swatch Group + 0 + + + + PANTONE 3005 U + SPOT + 100.000000 + CMYK + 100.000000 + 34.000000 + 0.000000 + 2.000000 + + + PANTONE 2905 U + SPOT + 100.000000 + CMYK + 41.000000 + 2.000000 + 0.000000 + 0.000000 + + + PANTONE 309 U + SPOT + 100.000000 + CMYK + 100.000000 + 0.000000 + 9.000000 + 72.000000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + % &&end XMP packet marker&& [{ai_metadata_stream_123} <> /PUT AI11_PDFMark5 [/Document 1 dict begin /Metadata {ai_metadata_stream_123} def currentdict end /BDC AI11_PDFMark5 +%ADOEndClientInjection: PageSetup End "AI11EPS" +%%EndPageSetup +1 -1 scale 0 -211.304 translate +pgsv +[1 0 0 1 0 0 ]ct +gsave +np +gsave +0 0 mo +0 211.304 li +372 211.304 li +372 0 li +cp +clp +[1 0 0 1 0 0 ]ct +103.096 139.708 mo +103.039 138.986 103.005 138.517 103.005 138.517 cv +103.005 138.517 100.816 123.759 98.21 119.355 cv +97.7979 118.657 98.2549 115.79 99.4053 111.543 cv +100.078 112.706 102.917 117.68 103.487 119.283 cv +104.129 121.095 104.264 121.614 104.264 121.614 cv +104.264 121.614 102.707 113.603 100.152 108.928 cv +100.712 107.038 101.381 104.949 102.138 102.716 cv +103.106 104.414 105.423 108.525 105.933 109.951 cv +106.036 110.244 106.123 110.493 106.201 110.721 cv +106.226 110.584 106.251 110.447 106.276 110.31 cv +105.691 107.828 104.542 103.509 102.969 100.318 cv +106.459 82.1528 118.362 57.8726 130.565 47.0405 cv +50.96 47.0405 li +45.625 47.0405 41.2598 51.4063 41.2598 56.7407 cv +41.2598 144.53 li +41.2598 149.865 45.625 154.23 50.96 154.23 cv +103.39 154.23 li +103.012 149.654 102.886 144.591 103.096 139.708 cv +cp +false sop +/0 +<< +/Name (PANTONE 3005 U) +/0 +[/DeviceCMYK] /CSA add_res +/CSA /0 get_csa_by_name +/MappedCSA /0 /CSA get_res +/TintMethod /Subtractive +/TintProc null +/NComponents 4 +/Components [ 1 0.34 0 0.02 ] +>> +/CSD add_res +1 /0 /CSD get_res sepcs +1 sep +f +161.875 105.281 mo +163.221 105.281 li +163.221 116.492 li +161.795 116.492 li +161.469 113.393 160.348 110.974 158.432 109.234 cv +156.514 107.497 154.104 106.626 151.196 106.626 cv +148.612 106.626 146.534 107.279 144.958 108.583 cv +143.382 109.886 142.594 111.626 142.594 113.801 cv +142.594 115.812 143.246 117.646 144.551 119.303 cv +145.854 120.962 148.682 123.093 153.031 125.706 cv +158.085 128.722 161.482 131.355 163.221 133.613 cv +164.96 135.868 165.829 138.45 165.829 141.358 cv +165.829 145.108 164.502 148.315 161.844 150.978 cv +159.182 153.642 155.979 154.973 152.236 154.973 cv +150.064 154.973 147.297 154.375 143.932 153.178 cv +142.549 152.689 141.666 152.447 141.287 152.447 cv +140.499 152.447 139.89 153.057 139.455 154.281 cv +138.028 154.281 li +138.028 141.358 li +139.455 141.358 li +139.481 144.919 140.642 147.772 142.934 149.92 cv +145.226 152.065 147.904 153.138 150.968 153.138 cv +153.873 153.138 156.196 152.366 157.948 150.814 cv +159.697 149.263 160.572 147.197 160.572 144.612 cv +160.572 142.681 159.852 140.832 158.415 139.065 cv +156.979 137.296 153.972 135.018 149.4 132.227 cv +145.674 129.923 143.186 128.11 141.937 126.776 cv +140.688 125.443 139.765 123.982 139.168 122.39 cv +138.571 120.801 138.272 119.052 138.272 117.15 cv +138.272 113.48 139.476 110.502 141.881 108.217 cv +144.286 105.934 147.418 104.792 151.276 104.792 cv +153.396 104.792 155.707 105.213 158.207 106.055 cv +159.374 106.436 160.19 106.626 160.651 106.626 cv +161.034 106.626 161.291 106.545 161.425 106.382 cv +161.563 106.218 161.713 105.852 161.875 105.281 cv +cp +/1 +<< +/Name (PANTONE 309 U) +/CSA /0 get_csa_by_name +/MappedCSA /0 /CSA get_res +/TintMethod /Subtractive +/TintProc null +/NComponents 4 +/Components [ 1 0 0.09 0.72 ] +>> +/CSD add_res +1 /1 /CSD get_res sepcs +1 sep +f +216.34 130.229 mo +216.34 122.917 214.667 117.157 211.324 112.944 cv +207.98 108.732 203.66 106.626 198.358 106.626 cv +192.733 106.626 188.244 108.741 184.888 112.964 cv +181.53 117.192 179.855 122.837 179.855 129.903 cv +179.855 136.779 181.519 142.372 184.847 146.679 cv +188.178 150.986 192.518 153.138 197.871 153.138 cv +203.443 153.138 207.913 151.053 211.282 146.881 cv +214.651 142.708 216.34 137.158 216.34 130.229 cv +cp +224.653 166.999 mo +225.182 168.304 li +222.846 169.364 220.197 169.894 217.235 169.894 cv +214.789 169.894 212.518 169.573 210.426 168.936 cv +208.336 168.296 206.369 167.319 204.537 166 cv +202.703 164.682 200.466 162.487 197.83 159.418 cv +195.491 156.699 193.698 155.012 192.449 154.361 cv +186.986 153.249 182.294 150.365 178.365 145.721 cv +174.438 141.074 172.474 135.772 172.474 129.821 cv +172.474 125.391 173.602 121.221 175.857 117.307 cv +178.113 113.393 181.171 110.329 185.033 108.116 cv +188.889 105.899 193.17 104.792 197.871 104.792 cv +205.128 104.792 211.242 107.205 216.217 112.028 cv +221.188 116.85 223.674 122.783 223.674 129.821 cv +223.674 135.748 221.76 141.023 217.928 145.657 cv +214.095 150.293 209.189 153.194 203.212 154.361 cv +203.784 154.819 204.806 155.976 206.272 157.826 cv +209.391 161.687 212 164.306 214.091 165.678 cv +216.185 167.046 218.264 167.734 220.331 167.734 cv +221.854 167.734 223.297 167.488 224.653 166.999 cv +cp +f +259.776 146.473 mo +258.979 154.111 li +227.787 154.111 li +227.853 152.591 li +229.544 152.418 230.729 151.984 231.42 151.291 cv +232.11 150.593 232.459 148.992 232.485 146.473 cv +232.521 112.728 li +232.509 110.965 232.423 109.75 232.277 109.087 cv +231.885 107.234 230.135 106.309 227.005 106.309 cv +226.938 104.792 li +243.22 104.792 li +243.282 106.309 li +241.546 106.427 240.358 106.895 239.693 107.717 cv +239.035 108.542 238.709 110.213 238.71 112.728 cv +238.585 146.826 li +238.59 147.406 238.639 147.937 238.747 148.429 cv +239.27 150.917 241.243 152.158 244.665 152.158 cv +247.604 152.158 li +251.407 152.158 254.046 151.73 255.535 150.876 cv +257.02 150.028 257.964 148.557 258.371 146.473 cv +259.776 146.473 li +cp +f +270.119 113.882 mo +270.855 113.882 271.533 114.14 272.159 114.658 cv +272.778 115.174 273.181 115.812 273.336 116.571 cv +273.487 117.307 273.362 117.946 272.959 118.489 cv +272.556 119.032 271.992 119.303 271.256 119.303 cv +270.495 119.303 269.786 119.032 269.13 118.489 cv +268.47 117.946 268.066 117.307 267.916 116.571 cv +267.761 115.812 267.886 115.174 268.33 114.658 cv +268.764 114.14 269.358 113.882 270.119 113.882 cv +cp +275.101 125.583 mo +275.051 146.943 li +275.06 148.436 275.136 149.497 275.269 150.124 cv +275.441 150.994 275.827 151.583 276.406 151.895 cv +276.995 152.209 278.309 152.366 280.348 152.366 cv +280.395 153.792 li +265.72 153.792 li +265.755 152.366 li +267.767 152.366 269.003 152.18 269.474 151.814 cv +269.941 151.449 270.181 150.218 270.207 148.125 cv +270.299 133.002 li +270.282 132.177 270.23 131.532 270.133 131.064 cv +269.845 129.666 268.923 128.965 267.373 128.965 cv +264.189 129.372 li +264.174 127.701 li +273.424 125.583 li +275.101 125.583 li +cp +f +299.717 126.315 mo +299.787 128.597 li +292.118 128.597 li +292.063 147.671 li +292.063 148.191 292.094 148.638 292.183 149.021 cv +292.508 150.597 293.372 151.387 294.761 151.387 cv +297.021 151.387 299.6 149.906 302.527 146.943 cv +303.758 147.981 li +299.704 152.48 295.83 154.728 292.135 154.728 cv +289.581 154.728 288.058 153.559 287.563 151.222 cv +287.359 150.246 287.257 148.315 287.249 145.434 cv +287.354 128.597 li +282.338 128.597 li +282.28 127.172 li +286.584 126.738 289.38 124.034 290.673 119.06 cv +292.14 119.06 li +292.127 126.315 li +299.717 126.315 li +cp +f +311.427 140.01 mo +319.449 138.461 323.033 135.679 322.196 131.658 cv +322.025 130.839 321.502 130.092 320.645 129.414 cv +319.776 128.734 318.904 128.394 318.011 128.394 cv +315.972 128.394 314.303 129.597 313.017 132.001 cv +311.721 134.407 311.198 137.078 311.427 140.01 cv +cp +311.381 141.522 mo +311.449 142.227 311.544 142.894 311.677 143.518 cv +312.7 148.409 315.455 150.855 319.937 150.855 cv +323.197 150.855 327.513 148.887 329.655 144.946 cv +330.741 146.066 li +329.398 149.104 327.935 151.306 326.357 152.675 cv +324.783 154.045 321.037 154.728 318.351 154.728 cv +315.466 154.728 313.074 153.92 311.172 152.303 cv +309.267 150.685 308.014 148.396 307.389 145.434 cv +306.327 140.378 307.15 135.782 309.851 131.634 cv +312.566 127.493 316.063 125.417 320.356 125.417 cv +322.045 125.417 325.076 125.848 326.24 126.703 cv +327.389 127.558 328.122 128.707 328.426 130.146 cv +328.937 132.567 326.205 134.854 323.48 137.016 cv +320.753 139.177 316.713 140.678 311.381 141.522 cv +cp +f +99.4053 111.543 mo +100.078 112.706 102.917 117.68 103.487 119.283 cv +104.129 121.095 104.264 121.614 104.264 121.614 cv +104.264 121.614 102.707 113.603 100.152 108.928 cv +100.712 107.038 101.381 104.949 102.138 102.716 cv +103.023 104.269 105.034 107.836 105.761 109.526 cv +105.788 109.207 105.815 108.888 105.843 108.572 cv +105.199 106.097 104.221 102.857 102.969 100.318 cv +106.183 83.5933 116.528 61.6929 127.673 49.8696 cv +50.96 49.8696 li +47.1719 49.8696 44.0889 52.9521 44.0889 56.7407 cv +44.0889 138.125 li +61.4629 131.457 82.4121 125.362 100.442 125.623 cv +99.7725 123.042 99.0107 120.708 98.21 119.355 cv +97.7979 118.657 98.2549 115.79 99.4053 111.543 cv +cp +/2 +<< +/Names [ +(PANTONE 2905 U) +(PANTONE 3005 U) +] +/CSA /0 get_csa_by_name +/TintMethod /Subtractive +/TintProc null +/MappedCSA null +/TintTransform +/0 { +1 3 1 roll 1 3 1 roll 1 3 1 roll 1 3 1 +roll 6 -1 roll 2 index 0.41 mul 1 cvr exch sub mul 1 index +1 mul 1 cvr exch sub mul 1 cvr exch sub 6 1 roll 5 +-1 roll 2 index 0.02 mul 1 cvr exch sub mul 1 index 0.34 mul +1 cvr exch sub mul 1 cvr exch sub 5 1 roll 4 -1 roll +2 index 0 mul 1 cvr exch sub mul 1 index 0 mul 1 cvr +exch sub mul 1 cvr exch sub 4 1 roll 3 -1 roll 2 index +0 mul 1 cvr exch sub mul 1 index 0.02 mul 1 cvr exch sub +mul 1 cvr exch sub 3 1 roll pop pop +} bind /Procedure add_res +/0 /Procedure get_res +>> +/CSD add_res +/2 /CSD get_res devncs +level3{ +gsave +clp +[-4.01667e-06 91.8907 -91.8907 -4.01667e-06 85.8809 49.8696 ]ct +/0 +<< +/ShadingType 2 +/ColorSpace [/DeviceN /devicen_colorspace_dict AGMCORE_gget begin /Names load /MappedCSA load /TintTransform load end] +/Coords [0 0 1 0 ] +/Domain [0 1 ] +/Extend[ true true] +/Function +<< +/Domain[0 1 ] +/FunctionType 3 +/Functions [ +<< +/Domain[0 1 ] +/FunctionType 2 +/C0 [0 1 ] +/C1 [1 0 ] +/N 1.3901 +>> +<< +/Domain[0 1 ] +/FunctionType 2 +/C0 [0 1 ] +/C1 [0 1 ] +/N 1 +>> +] +/Bounds [0.920245 ] +/Encode [1 0 0 1 ] +>> +>>/Gradient add_res /0 /Gradient get_res clonedict shfill grestore +}if +level3 not{ +gsave +[-4.01667e-06 91.8907 -91.8907 -4.01667e-06 85.8809 49.8696 ]ct +clp +/0 { +<< +/NumSamples 256 +/NumComp 2 +/Scaling[[0.00392157 0 ][0.00392157 0 ]] +/Samples[ +<~s8Dikq=jUToC;>$4p- +%1/1`;$.4?Pj,pX][+sA'N*Zc=A)]BS3 +(`*r''bh;p&eP]e%h9'Y$k*LO$4."E#R:P<"U,#3!s8T+!W`<&zzzzz!!!!!~> +<~!!*0)"U>;?$OmRW&JGio(E",2*?QCI,:"T`.4Qi"/hf"91c73O3]fGf5=%V'77Kd=8k_rS:f1+i$P?>?t!MTAS,UiC27[(DfKf=FEVkQH$apeIXm!$K8#&8Ll%%KNK0'^P*;,qQC+)/S"-%ATV8*TUnsuf +WN*##Xfek3Z*UgF[^WcW]">Vg^;%J"_Sa=2`lH0Bb0/#RcHjkbdaHUoe^i@)g"P38gtgiEi8ESRj5f=` +k3(sll0@U#m-X3.n*oi:o()DDo_%nNp@n@Wq>'m`qtp +] +>> +0 0 1 0 []true true [] +/DeviceN +GenStrips +} /Gradient add_res /0 /Gradient get_res exec grestore +}if +np +149.133 44.167 mo +143.681 39.3052 137.08 41.2583 130.565 47.0405 cv +129.598 47.8994 128.633 48.8516 127.673 49.8696 cv +116.528 61.6929 106.183 83.5933 102.969 100.318 cv +104.221 102.857 105.199 106.097 105.843 108.572 cv +106.008 109.207 106.157 109.803 106.276 110.31 cv +106.559 111.51 106.711 112.288 106.711 112.288 cv +106.711 112.288 106.611 111.91 106.201 110.721 cv +106.123 110.493 106.036 110.244 105.933 109.951 cv +105.889 109.83 105.828 109.683 105.761 109.526 cv +105.034 107.836 103.023 104.269 102.138 102.716 cv +101.381 104.949 100.712 107.038 100.152 108.928 cv +102.707 113.603 104.264 121.614 104.264 121.614 cv +104.264 121.614 104.129 121.095 103.487 119.283 cv +102.917 117.68 100.078 112.706 99.4053 111.543 cv +98.2549 115.79 97.7979 118.657 98.21 119.355 cv +99.0107 120.708 99.7725 123.042 100.442 125.623 cv +101.954 131.438 103.005 138.517 103.005 138.517 cv +103.005 138.517 103.039 138.986 103.096 139.708 cv +102.886 144.591 103.012 149.654 103.39 154.23 cv +103.891 160.288 104.834 165.492 106.036 168.277 cv +106.852 167.832 li +105.087 162.345 104.37 155.154 104.684 146.861 cv +105.159 134.185 108.076 118.898 113.466 102.965 cv +122.572 78.9131 135.206 59.6152 146.769 50.3994 cv +136.23 59.917 121.966 90.7261 117.696 102.135 cv +112.915 114.911 109.527 126.9 107.485 138.387 cv +111.008 127.618 122.399 122.989 122.399 122.989 cv +122.399 122.989 127.986 116.099 134.515 106.255 cv +130.604 107.147 124.182 108.674 122.031 109.578 cv +118.858 110.909 118.003 111.363 118.003 111.363 cv +118.003 111.363 128.281 105.104 137.099 102.27 cv +149.226 83.1704 162.438 56.0361 149.133 44.167 cv +cp +1 /1 /CSD get_res sepcs +1 sep +f +0.5 lw +0 lc +0 lj +4 ml +[] 0 dsh +true sadj +27 175.304 mo +0 175.304 li +/3 +<< +/Name (All) +/CSA /0 get_csa_by_name +/MappedCSA /0 /CSA get_res +/TintMethod /Subtractive +/TintProc null +/NComponents 4 +/Components [ 1 1 1 1 ] +>> +/CSD add_res +1 /3 /CSD get_res sepcs +1 sep +@ +36 184.304 mo +36 211.304 li +@ +27 36 mo +0 36 li +@ +36 27 mo +36 0 li +@ +345 36 mo +372 36 li +@ +336 27 mo +336 0 li +@ +345 175.304 mo +372 175.304 li +@ +336 184.304 mo +336 211.304 li +@ +%ADOBeginClientInjection: EndPageContent "AI11EPS" +userdict /annotatepage 2 copy known {get exec}{pop pop} ifelse +%ADOEndClientInjection: EndPageContent "AI11EPS" +grestore +grestore +pgrs +%%PageTrailer +%ADOBeginClientInjection: PageTrailer Start "AI11EPS" +[/EMC AI11_PDFMark5 [/NamespacePop AI11_PDFMark5 +%ADOEndClientInjection: PageTrailer Start "AI11EPS" +[ +[/CSA [/0 ]] +[/CSD [/0 /1 /2 /3 ]] +[/Gradient [/0 ]] +[/Procedure [/0 ]] +] del_res +Adobe_AGM_Image/pt gx +Adobe_CoolType_Core/pt get exec Adobe_AGM_Core/pt gx +currentdict Adobe_AGM_Utils eq {end} if +%%Trailer +Adobe_AGM_Image/dt get exec +Adobe_CoolType_Core/dt get exec Adobe_AGM_Core/dt get exec +%%EOF +%AI9_PrintingDataEnd userdict /AI9_read_buffer 256 string put userdict begin /ai9_skip_data { mark { currentfile AI9_read_buffer { readline } stopped { } { not { exit } if (%AI9_PrivateDataEnd) eq { exit } if } ifelse } loop cleartomark } def end userdict /ai9_skip_data get exec %AI9_PrivateDataBegin %!PS-Adobe-3.0 EPSF-3.0 %%Creator: Adobe Illustrator(R) 11.0 %%AI8_CreatorVersion: 13.0.2 %%For: (Mary Diarte) () %%Title: (logo_color_eps.eps) %%CreationDate: 5/25/10 11:06 AM %AI9_DataStream %Gb"-6Bp2f2Pp#o2n/pqR,4,%FCG'cqcS6#7\b,MND(@139M]b(.+f4cF,#U)U>4f'lQ=CZga0;4=HqR+.hQ;lS]&LdEc>u@I.>23 %q]F^Dqtf,mGOPRXQT*6<^3Q#^]MCJ(9'2$brlaWb^%u/7-/D=Fni+nSD+m-X<]f0h<-*C3hW?NRp>"X*b9,WUHM?s1&+qVd5. %q`!t.r:$QY@eYrRS($[^Y>4ON]RB>?-JqPuoARsO7-Dhq=33@?bLaTo$t5LppPVL"+66G_;E"Vp$lPXedl-E %f\r+m++O(\r[knTjqhClIe3HoroSIcl4e19q3S5Cs4r6Tg&tH.m=5(!rb6'5bF@`Sf_44`DPgGmRtgB[JFB2ck)1d=>MFY\SU'T^ %Df'`(IdsVVHhH4\+$P-unaZ;LGQ79$4Ehn(J,f5]L]?1"qeUklES7hPDM(`iorZ[%fMm-9i0iK;HMdZ1(E[#CP1hnO`g^!`%_m%t %[T9d%ee_Y:(Ya7?CN"gNe98q#]2C+Ae(=TLT3f;/pFgH6rSlr)G9>`Bn4-[EY?nsh7+cq_q"ALpeZ*uU"Q+,&*S(`=2$/\^"6K$I!"B]C\>(a9E-*SQ,CA@Y[&$N`prU*>H@fGL35.pm'j)Dni6N7XLPi5u7J(3:4nrFl"^#SNb %pW`]h]q&lKrUne7K&?Uua1)*Bm`"KMD:Z,7dnOO^\SF1smdT5rM_B"3\*iCn]_XiOGCTSt>AIsqn)=;2i;[!>s8?8shS[Z/*YSA] %hg/)USkec34d?Z08dYJh$#6:>[8K&VUs3)::9@?j[LYK+/(CR6C;FiX5LeEUU"4Z':[[uHc$g1G:+,i1F@lk25+UX/dtsZi*`IQf %5P.GA(7pcZ]f0<6s%j*C"TLh@(mBoC^4R$6s%iqi"TQBLAL?VD(_cfXJ&-s!IqX]$M->WG_>c3,p^'b6'>0N@PMQhX?sN1ce2a'" %-L1asV`CVWUfioCQ=pG9eFXc`)#T%j0KrWJRMC,a`WuO]?SFNEJ,#X^%M8CWC;K]'Ip,:X %&t2mJ5J0j4!.$9m,ATdIUKN@U1iG-&1ihkEoUPbHn"l=]]r6[5TFQoU0G?n\:Xc9,>8SI[&%)\X@=0mZoITnNF^T=R$c-Z44#D$N %#/Y8o@DN\p2X!/0$K6U'$X$DsGNp3n3k^mB%=0WW,%IC^6S3RF[8,&sp[k/Ne'94TVDY9^Tb^Du+oL`>SXqQCaDUB,9BN565%1qY %IE+Qs]&Sn=oY/I'bC(D(7l$:tFIs$,X7TKM9C:/kekZ!kT0sDGJ"39PqG6s@5_&O#oJ'^k8GIh)oeX$8jnsVoj(j"uk-k#k^Oc::E",u7_Aq#0;c`kGD?SlQaT@EJo2e*A.h80H]D/*n@ %FmGl>`pL4+mMXUl(_")pfQIMm0E6]L_f*%[gq2.h)-4*[YuMasF*HE#46cP\1B+);V11[hZN9ZV/%3p@?MRCk/<7>qq5iTNGL08* %e"qPu^\_Ad#'&/tRaoe+Ai&j)[s2TTT?dIP4WjYATAQ#-376K@L"U9\hodX/]7tV& %3BD0I"&NKFHhA%b9d+p2gFCM2a$FJG>",TbT]bn#eka9BrF2Z^4Gu]lYIJNFs-.M3^D,:mD4K]4oF,NlqenG')BK2JF=5[83&i"" %#9sZN#>hZST2(2p0HPJMnO>2S'C\Zn]P@6%G;A'X2eRWWSE"NM&pKkp9A%1HXDGI&24ibR!d"ibu:^OrUD85Q0 %4`KET\Z#.*@mG3tp/iNOlTCA=^77[^N'6gdg7G\iG72$(&%Ejo0V#t7)7CYPJj%'fT?e5FZneI=corR)`-d].,mZuUC^N=XQ*G\P %[-`@D3DYJ2Q.E$Fe9D%eQ8;,\&^mb\F'Oq&6ln]YieiE6679CjS(Esp`Y?6FWN/&.E2a8L&BoZKb] %kA;7+n^>(t%\Ksp>@c\hSENqQD*KI+0M+oprTj44&jKnI.r(05LEi6*.-@q*UeM._GbQ.a^!!W %KQST*J5;u$O47CPoBW@7JZ6kReeL[2hAqFGaUC7YMk"1eJs+\kraqUFm&*)@)K@MB41^C[kR:i2SHFD=ck`\hltSXMYFB*L47sLP %0&Y"<";WJXOc+;%#>d#2$q>Q&Vph5460O_WG'c8*KoQh,UOFEokLY$>YgQ!Q^1]_5r-%KU@Jkei&"nkHNEb:`0Tt#Y*V2cmB+r>4 %E*roq0`KkLmb?^Si==ZY^k]qA+:cl7fA;]:Lt!:rde7Z,i"\gYg/St%lq!6On0s`73:X,Pifo64L=,'&;8kH%$M+\p]j>2j,._s5 %%^jjaiqVqGY[GgrqtG$FhXlHQ2ST%Wrlt?/kWA_`^\R`V`ui&D,7XYNc#;IJg99Cbl,Q %nV9?cr;QZl2ql%B=5$@Q,8BGCFhH`bI,Nh!hpG-$ho$7qDq]X7pfI3UXPM\"]PC)WE& %&$Ol=gNEkjk<=mohgQ)r'fTM"n\t7+Ye)"WGf#nV?\-48?G(XTiJQ`m`nfEuC];l^b,!b6Y*HV"p?BrHZ'A7Z>-Y3>B-e?<^Md')X&@r>T0j85MR1tisR %3FZ^CVu^VIEDKD9.iq>s-+8D@"S7$i=C;n`+:%*=[R?E+/12k.LoLt:%Z>6O@#8!)d>r,NO16)uSCSq1bn5_$SYJ*(7tW^u'9pta %`F]?`G %`-Y_!+?E]E.D+bpCMGE("]*giL#+$rO!Sb%=;$tE"ZMjM`o3M/4"c?,NmZ2o\F@p.=ec:]%#a#`IMVUA5:.sEX[,H.mgo@1[3QCuQ`R#sWEOIKmY8%!EfabaJ&e7QHAU*Im&[^"nRF:./B[gQcB^#XU%AIYr@&h8^6hQ#IR8$d %EhBhrhk5I$0b8]jRKg[m/EZO^2aoOAcW`S3K1)U<5on6Z6s0`m7jk/r%d?YTE`/!81brL$4rf[b=PVc?Md^gq`gVF''i+Kj4$c[0\?V#MHR)3_I#-SjiDhjAh"5=g0:VF(1@ikr_NXfTA0=Z=ZBlet`1+U*es(4]koU\MY>\>C:dq %"TrZ.c(XgsY4]*/*p;,OfLFlTW%9F8:9E!#2Xn=:$.ZEYaDGg(RjHtSbC[aINU20OHIq;f[V=$(_IK']h\O&rVq,.@JOI])KboLj!V4hZ+oiN`Y %Ts60_147-N`-XoE>snF>U-rbN+chW!Y"Q0J6nd-0oLtK."0H(Em_1\o3&K-ltnhE5eD[LMJa[af.8O/^Gr/uc/TV3'=Kqi/lq(u/I='cEp0ZQ2(3$S`J+Ro9:>TE`_dmgMCYQ$HkN0.CX/XG([1D1>Q$+>fW*u6X[8>sCT'WCrEjrFsgdCC/5/=9r %m7=%qek4cZ\Z3>[`$:=[?W3M!p=4Jjg.7D"4NJ/2nheY4I9#`)V2M9]b9jMO0Oh,V$P@i;:a$=8?&<\lK&$c)$+I-O^$WRVCn[&Y %n.$=dG4]-f"Au*0W]&Sq2MGNZ9Eiu2^YhL:C,*rdp!<,ZUdeL\5&,m3lT9UNpppOQNS+)hkNH4'p$L_5Gr.!eWp'N=RZ<%.D2Dq; %f"\TR4au8YeDR+F_&ONjfe87dK\n.$FM)P>EAs4a9d6ZAfG\.YO[2/cPC1;_g*uB:F;=toA/2]04`)[O]]jo'N %=_fh_er@:Rf"*Zh"dS;i>^+bf)!h.9=;+op=D@q#[5-7K:.Jlk-Y/s.Kbieg(h_UUOX'G?`%)Lfgc/hsbjcb-@UP%D(N'I2EkoKf %M13@oNau06_'ODPP^d(m[UW,qhlZ %Q+:KfN5bS^j+a94O&>-jecV4_7I!%?m+[E6+*Uu.,Z2)d/n2X>H\Q4\7JH7R:kk#g+tp"@Ht)[R*?uahhm(.sc33>`6E:Z7#!$u^ %8KVQ-oT$n(&Y_^E(?&DLk"0YZTCqg*i:&aU=tpi.5!5bdIprV?jLX-;/\B9%LW1(+mN)%2jmac%39Q0D/:ktn3j=[@0s`MTr\STdM/PZ^dj0-bP$_DsBTa;j2*eXrW;XbJjO`-TeG4J+BaSp+btkJ,VeS[+?"5>r=69fTOJpd%7Bma(6u@O?Hhsqm1tnQTHG,B\@6g\gh8kOR"XF %r,`^QQ\>sfJcQtg^2]U$*C$=(i&$[nQ9i%4Ei3J=7LCkK#aa)d'k4C'gq:f9(aG-2LF\t-FZ %U%96cc)Ib6366q\S9Vnnml0c^l[Ea:fOid6D=h6]h8&6Q2KqPV0A]gAOR;:mbMJ?/A9fda[nur=A\,O9mp&-M1KtDeX %fG>&Un_)g+"cN?QeTZLPcC#B-hQTU0W$B&:o8>tcf*e62+Rf\ %5,jnQi%3!^[[>)on[!"MU`cZ,*ft>okXT2;2&8)l %b<-(W_6C]Pg09$L=+9B^mq7[OaJB`>%tme_HHTr5fB8i`Vh&bh"ETHfS^P$rV\CFNNbB/c(#K^=IL:^k68<%k.\fhJNQX\2'gXP(-afec%A8iU2%$5=R`bU3+d"F#>MO*UM5g0iMn?#VV' %KbSdR>>WdZ8;8$+l#dFNI'7HeD#7[70D0j.=FY)a9shB.gF&c]FF\DFA8aaOIH/4^Z8%<'QXB7r\MXp=jNPC3Y3,82j]>_\][S)h %=tQ#JeP^+YAS!.o-`k0O.[:*+4m^R5Mi)GQ*jS5pKG*9(`&H*XgFrKh+E?kgKf3EPQ3(2XpplA %0EIClCn5Lr<(>&e#?DNL_WjJ/E(`T5VuVq3qWmGbo?.6.UNbPCW<`(qdDoPL548!LnI9,IiLaAH)Z88IfOQeEi@OMtnrO(-?5X^$ %gfl'hXI'H0O%\S@`m!5uXR4?"D.akNpEJ;[-JA#@=o+Em4sjl\1c[+Om<=ID$H7-g8hWXs"IZ1pld;Dl$;jdVVC0YIE9+7% %""Eb;?Ukc53=4M]qTWfL+KDWfhqo=R/C+CB>1&b/h'A6J5t %+s^Fs(Pr-:n8bjn\i?YocC]o1;_=DI:i#fu3Cce]DBXFtE:Mo"N`4t%]I^1&/@6s&VNMX8[`5tYcRjiH9))/Cs.W0=^5iES+,.d+t^k\X3Fcmr!TGZQU) %cWl*N^<5K#O+(%%k_JI-1lFGM(=:S5bKTBaSc-5ZmP\k)oZ4GOafe^HWs]-7I:05LKmS(9Wp]/$JLg%>gTJAqlRqWB\?c+>m51)I %Q*0t"eOQ@W[#H`fgsE=_RDUU7bUMFb=QnX6>RNrrS/0GA0grApCFF2!+lYh"=b,L`m(UUfGI=1C5DW`d4:R;4^ %#;u8oo)#'&l$lu^s,F,ZAk9sc.Bic:)>t)^>g2?Fb2g=.a'Y&*Et$keL]9,^s"])=B('*&mcVOeAsKiTT!c>rm%4L0EP2+IZ5YDD %lSn/N46Gg8?@fL",nK?t\sp[J@<@uA"Lf,ZoZ@Wbq<+aQa^#Tc7Hn,/8]qXYTa/Jd'_P?QD2PKhbu@qR9?=DgBr'3X0TrM5Pd;-XVar*;qIs=;uMrDX<(Cj'<0:QFl?,gH(0i>n"YO4 %kfM[Ef@a6]Ya9\1:9T!67b1:.?KgBt/pD9)eDXXjq$s]!N7W&;FY:.]qsKb)XaTf!(\r'0B!(D`5$lWV)D:9QH;-n+Dt3@l%Nu1* %6X^4>Vr$C.FqXWof6*0V\1!tE9I92FNfd(AP4(Tro@2\sK22sUX;ZJ\'2K'$2>G\ZI1?2CWe3sQTg1g8gmH(E2K+CV-?-`j %M8q''[Sned`e>\L^XJs\W]nWZWWo#G3HJ'jV/**?/u_l-YL+l#QPWV.DrRj]`)fptJo_,\E9d%fZc)SG-\Ec8MT^@I@0WH9cf]L\oj %+hd'tEti]hX0X790,J\Pe[t.)\[LLlCnse$@a9JrJ5U_KiuangR+XWMX$VWH29rIlZF\,\?fj;^dLS#%0RC'43.'-%R6,i*0B+^! %YLbdYLX*Hs/8%nZCu:=13p*X$i&n"elrRf?2a5OkSqg:fKbaIMFNU+M\`ZmLRS\:` %8>nXHV`[bOI-)%WUM5q4,fr`9B=X)dabqU#0"JpB<=%e>B@q9cr9-Oa8SR$q*:sa:i7Z$69ZS^/I,s)'hL9bm"r;4njNOom^QgS. %&"*H@(jHb3p3^7'hD#c6AhGt4l,hF/YO4H@g+"?B4kt$f^%a@b_QX %bT^3o7&5d?ZbnkO&4oWQ((Lp"imJWJm5nS1,Hdua2%7!.)&I%C9-YeO[N(Y&D`r0*l`0/[Y3(W=>qb%-\h)71Z[-Lr#.l?t5&tB( %V/,EMa##CGVp*AQl?':9a@S!&VbYBf]_0j0&pF-(WMWM?:1':UG$6HH\^PAgAY$C?-0RLScObQUVaF4GIcAEte?aMDJ^of93SK5B %j5^p@B;6H7HAE&!?V[g(d9@%VGqFer5MG5/mnA89"eAd=mV9C&COTF=q&AKMh`%_SC,7eJ0?X,Ljs:DH\tdTQK=k7/oPmm^2LGCi %fu$H*f>=R1/kq=rDD4 %>l%j1$nfY).:Sk2ELDo.1Y\Y7inhqVFKq&aAgnD<7dTI&0\4EeWdHVc\Qk!7GgsoVW-"He-cVf3I?k[IM-e6S0B87spb#mlki'rA %a7o#LSU5V)KmE/F(\_n"k*+4-s3:,bh;1*]?? %/Xj"6"#IlQ.:GJt@jMGDAr$ZL+Fg$DM]k6iiDD7a9[*$b>Yt7%a;nV)H,g0&*%Sr?cU?=ZB2aY52N45q8@,fLH(.b,RjDkc1CK;& %$TWK,`TbOJ#k:pl%8W7Co^(P.V-$=_.P*;#bRVi`g9O:EtYu.O`LRb?`/_K\If?9]NhjMI"0L%C[bjt\I=lR[M %X2FKa5O+P)iV]@=jX2*\V7"N(DZ$p?1s/XVJU55+rQGUcYLJ8+1M<$BbYla/.^9(%GM$*UEsmDFagEZ1rO';M0'De3bS"Gk_NG9D %ZPK7d3C1r=c=\XfS#BmC]/;>(:I`b[,O)(foM^a2pDEZX=moV17cSOd!<,3_:'\R/N#XaJ;RnANo.[Hdq/*^T5\P[)=deQB(*W@fO$;LVANAu!4 %j3[GkO-"ijoEBsP`7TD$dH&+%$EJm.1$[Vq*.V8,9r$HBohA[dMg9BMJD=o^=bQ_'Oac;[qqfih0ai]!M) %e0dHQM,/QZ;kNj7-U.40n3J;Fo@2^U>_>i'Osb%ePI9Jn>4Q2UH*Wb6K[u;6hl\?aXs`,092.SFG!5YE4o'7a^piVYioDQJj=0*L %.H9D;ioDQJj:`b5SkL>(-BY5(#+qeUjYqG,Dt'"Ki$lE,QVW*#q$m>rZ[;ZK-2`uk^MhXumgo+jGd6qpqPh-r52D";D7OVriQ?m^ %)'g+ErQlp$8QZn?L(oQR**pUicu0mNcF1K!WgufO,EIe?I4:"*B"i+E>X:P+oD>L?oV"IWraLrVc1XnDlZPD;Z^c!I'9:`UF"Hp`ZcaSr##uP6bTL5#VSo+-pm7VLQ!eJui(5\="I#,I<5\T@GG",/9NT6XBq&nm`rWW82A;[j<-r$u %l=]PM\FosYIkDLt2g/hq:l$7J-7n*Rb?Ll+N/?JFg7m#&!'.f3q[GW#9IFWK't5cqYt7*NYPD4isMX:)S'("L(.k2Y[Dk%,PC %n*4kEYGYsF69lOmkm]*l#Y6C`6j3PsrLP#n7[K1`l!lINqMbb?T\p4b7l21t;+Z])*@AA6;*-c&#=f53f+F$H_O3p8W$r^.KemT) %W%T,JL83&@QXEd0W/'jFSn^iqp.n@X#n&bYT]6CuplG9m`_P5kQ4Y.NNjY!.nA'srcZe3Epnn4f6qKL39 %G.F56s5-l/i0G-'^iEA3.=d?X@LeKJ9riW0mqdV:rlHi:Rp1gRo@4QhJa@=1iT#CS<4LE8:4YM*^";5gI)<^Ld0sNf\&2H`L,%<7 %@BME(R-X,nf9p'kolc]S1X)@rb&Kc9-fpeSa'Y^P?m%'q2MDTcip%oR'$Js8cH;[O4n1Ka`,9T=G.;#H=6?1W+SSAPQ]8l%Tp- %Xd"f\?7)t^(cAUXpUlTeKo@VD>q]`/+f!4$*e@^D.d26q[GMc@Xaad58i@u>!1ultGj,j3@mF]OR %S`Ya:RKNCcgo9(YXjlfB]nq]G!C<:LD;A:d*XAoBVO3.l9-.p5pa!Ji7l>j?dAdc+fLU^d[5Kj5BPfUPG8Cn$263nNj]jro]/211F0#buGMT48qZkZl$gR.L17\Jp$&6.*jc!A.A4"@'gHfWb)7JiiJ>]Re?+m_BA) %"uc4f"$b!K\=H=Q`[S>JZ!3*6H>_cC/*E#S@)c0T&2Wnb&Z_80K-3lLLg>)+CcYP'"gro\Kp1k2@L3]0k7JS%Z#tr3;_6^5([IAA %Z&Q.CA^iur9k7`,(*fb[b.=]kNr_pE[>&joR;YRu:8MXr(%P8$W?,rEA!2QeC:"GkEk'9p@p46f49CcLk %H-=K[[d)mLC""0S]=EK:C=ElM6nIfUGWZc9njAREi<#g7MOP^W=XlNbSr^.Q_QK2[FSjY[6-j-&aDpSrY_N-!"=L:>! %nLK31O5oGDU-T0--&-lA.CGL).qMcHWpI`7pm6&oND(3n%U6ng!0<0i#5J2D=j6&GmUt+DkQsPM&,L\#k2.UFE@B[qE4]%p19jZF %PbN[n/)i,.'Z4,OV'p\]+M4L'7l(\nJ&X_?Yj%bqArO4)h.GTWk?KsXTIT27ihJ\Q45O[uogqS%A=*d"XHF3*7-'.0&s4F`8jntu %1_F^?!ej%bE#oohe&)Is#*lM3MajOGO-:LBbE8#,VJ&BHH:a$X(Str6elB&W)s,N2mW(&YlRG'D!t/al0_3EM.SgL[XEk%%8Z4$^ %,oN]']Q,Bm*p^s'k/iKK,*O %Oq#fuJ@\0Y5Ef#r3"6u<6kY:qM"i0_Em^']>&ogfTAU,3f922@Ec8DAg%e0#c9bQXcq7i2TWn-;Vjom? %k=9![d3HW)3o+N$-HXlhZShDL9k+aj&Ar003,ZgaF=B^Ye;StM4ADXc*]'aVu=>PDs"P]_mYZaK:$WdZ'`6]rQF+@ega'1$Z.< %n&Hl[C>.0B2/o#k\'Tb6pgm*,H1i&$;_mQp_)h4m=H)4LLI?N+a/InqbbO;YCs?d``MbG!X,icYY/aV-qA@,rmgW6fKqEQZo9GO8 %bTt``;6;AFZ?pX(D42GW;<264kajN?bRB;;Y39#A3R<7VA"n^nZ9_?7qPYh2%:d)>M^=:+n&B_X5S&h.c8epL0$sL0RM7((H<-3Y %Z8PM;>\Nk[26"9*6`F>6gQKheF5L&_g&oAma0i!E2QsH1>c@7mh%R8@:RpgD=XN4sm)QGCa2js[P^$`:_F\=XV=Bm``\G&6)(2\J %B[B!HI#-J$X'JP7M4`U_7@Q)J@@"kmXVeK/9+B.:koNI/_+R?DC(_%;Yd]ej/(p?:&sW)2nits2#HE$6MPI,G]Ut&2DT"<3YL^P)RSfiU#Y@60KL]5%;,i5>P8K7AoLn?4"\\4(+Lps.m,jV %c`qbUbO^7PGppi5iYTn05JOXH4.Jc#BEh?*l.Y+4baeh)b635FW*9!k;_0Q`]i`L`i0d_TL=[bc94uVq@,RV3I4b:s"a8N`p#%P %^;f&c4icTO$K?GJN+'t4`/\4'`8e(I1P8Dj[Tj3Og.g?0Q>/?u-ieGmO(u/@H)sQ(!+%WPcDDV&_/#lO,M#DcM,4;B*`[)GTS5M7 %>:L1s_lV1S1k2MmC'E_%qP;E2Do//P'@kg.D;:j_F6oP<#$kCeX@=/XJ/qX2VAl#X0O_VIfod?;>nM66A+&nR[5FtdQ5Rln'#EhT %B73@s/:(rPs,G]ja16T8c,BZ%oACR)KGD-IB_Z"-^R[^BkSa1Ra %$:W94Gg]pis.;+MS^f:k5r/sB`\PY*2r=@cBsmWF^YuI_\%(Vigb"!pGPmF-m$S2bQ.Rl=mOBAq:Wgh:6]FQmj<9:liOG#Md3C`4 %+d"NdfemGP%#:2AZ4'0.7a8-S!,!a[%KE_^#=gaXc@-3%9NRL,Ik`HMH!E(ni;2]W4QbV##(N?O2fhD=ZUKiK,0!I%AM>Ec;ta1h %A#da-V;e("+dI/;Fqo1da07@@-L,E=Njr#R75EjGpl*,:bSYo.jM9%bdJRekcaVn]1[H@lkFKVk8Xu6fWc>\?`iMn7()GH))\g5^ %P-t!=;M4M'LJh`\0$;Hj>e09'A`KB#oo5,?.;d@tnLr`=5%q6'`G>N-7"4$#b]qmXk9uC0E,k?1\U6!Y_opqIK@dYn:pca`5^2BY %XTb!RTp@.1g]aj\qfh!KOuAM+-;7n58J)75q1XoO=]RRb#&28N'uN5?Cc,<9;p5FO9j?A/(rfM`@krcn7GsKh`afj&)`-**+d.)_ %\o-P#\paaPiEnJrR_-->GKcKJ[fp&e`IY@XVdq&J^RF%O %H!RtjA^"^K"C5ot;cSm0r,[U-c;)W&Fq@-#fVgm<%,k:=#oP,5[rH=IZ%r/BR*/Vj7S>@sm`)4A$mV?Q^qf<9PRuD`@FnL+id+g7 %j,1[ejBYFh_NghDGTo+sgI>0#J[+=;*g"r+G2iTdIO)bU>P()iG#ZCi^YtBgp>8k]*_@7Dje>tTBVC4,hbLq31]:dt4mnX(dC0rK %AN]`O]lVfidF`WC7"NOnR?i%P/MI.cH(!L;Gj_$S9,H-%Hd(94,'s*DVQaoIfO8=t'4%b7k=Y)gCl1R(V0;h!U$"$_u %KJN %oP?W8T_",9o-B-M1o00Y %bht?T92G40k6GBRu$=1kN'OPUC9NJ,>@9^LLa#IC!"rV %l#L^ea.4]&o2M]A=p/lqEBYqOL3V%a.a\idSi%%PI:Y+YMhrL5fsj._I=9u&B?KKN+SWhq`Zc4@+f=!6,$Np;hW\F1@m0A,%S(Wg %5&e7__21SX3.C8d_3o0#i.OX1!/"u#M/F)jM'=@K-Eos*c_rtfABBnN?R:@!ft=lG+bs'U>_J'BXi3M^AL:%9(jCP %*CM]1l$ek4Dj\ReP([*WPC,S?qrNu[K!#Y)`SHaud(L'UGFW7qqQ^^Qp4-d8-(@\t=tMTm=FeJ)CFK9jJ[6hEC+gY+*')JSf=-Nr %k)mTnCrYP$Y]QbUO#L0]#:"^P>QdV\6B>!5?PL$4?K\cCY,Rm)6D=M*rESt\,AZXH>:hl(jpQj;8OY:A[SO$>M3h;CZk?:<%bETFbKd>R0;V=NY7IWX[* %\_pC%5Ohr(&`C$8_QUiQ%ugN>5I>\Idso2L`?b%J3\jTrc)Z>02G?relX<;X,0;sf1nIjV77j@'8Jg"BM]!.M>'5o#K8Y+)2L3BQ\^R?9 %GOne%L:'N\$CR+]FYY65HRDYhNIm3oM=[K-583<@AbqZkDpA^]Qef[-#2,C&&t=6NcFTo-0f>GePrtd'22IpM>^Zk<20p$H %b56Ig@if($[ad/?CSj:7!U4pPo+tMfH2>ge,uHC2L+N6=D]D!*V/K=a1ZNLMNkT(Z^7P(?5KiqL>3>cGQ_3_UG.r6B5-rDVG<%J: %G4s6*.A+-p-f8)A\WDQl>aL$1qNQ?i;X=;#'%bs/:t.Tg,O*OJ_5m0@"]nO.;bA8\W7l5i6[R1oAA=O&lfoks/t=00B"FEDB3'QA %ihda^9T!07PZ`tXoto\`V8M:bB]])!YRsUr=a3jE67K6_,dZErISK@Z'e^6>"D`,k:[ %=Z$\9*e1;Sf,L;A9Ac8mjHp>HZ?[,BI8dD2K7<`kY=R/!hNoMPHK.#k_\Fb]u0X?$Y@LPa:]ADm&?pjb']:^A6%NG@,cCrU/_3GMbQ12Oo9W %(Zm[6_`*:`\bkmV%tFNB`Q+%C5.p4%TUUD`=H$P_pFlPaIV`SIc=$I75IWlVC]!4C2:0+qKUZ?+r9OBQDSCh9^GF3)-rY$D9aJ2_ %2DN2-]J\#_NStXtn,`H7!@E!k!;@8;@/BZ1p;5]*lBApWhd`3r$O8>t3S;t*.#m2!i-[Vs<,VbMD]=FOHYnKp,^hk9T]q!=WO(`IoFkuH7g:`n5$*0C9>>7q$f6Go`(&cjKp!R,A"^<=Gq(FWBZ[YbRG-^Z&t)p/&&@HREle?dg=tmJ!)$h%;Za%6d)OYkL+M`fGT1LHVu]Q$ %c*9"sE.$PtPR@OsqiG9de]dEONK(s_TSBAB+K+uc4E`:S#fk.Z63"DG18e$[k;536CT2@DQ=.g?i^%-nE[f^R`S]*Y6ltQe,U+g!2k-IX2C8-gSQT2 %DsM6ZGJ2[776oic^A1R:%j)=c?[dD$rnWJCJ%k`aJU[+t%H>[2?f(^YY6O?iKioGOIc1J@`M.q0uSms0qsEREU=W %Xmt2lPU6OHAMBlMBnTtG3'Zg'Jdmu!J/aXDIr.o`dqZD.s+WlSakX %+l]j5/Go^f6u??73!?_06V]pP/NZN/?o1e180;pXg-.)#G=cqd"YNU*`.A@Ff(O2)\.)N5(`hg. %NnUNQs6ODf')_Hhk@q6so!Ut18E-M/2)csb5X_G#!;$TK+Z%JG4Cf?:FLSE0&-?aeLUq>NCPiN'dK;a"lQcorp:`ER)^V!#`V.dq %*T9M%kG!.I2Kk8WE1?h8NO:"=1)4RLLb\K?VMJp?Q4bg4K;G4W-__"Y(G^-1X`]hQW&(uH('M(:Q'(LD%O?9H4V)e"r;`]agMR?" %9EK$o.1JZu*GAC7K>+E1$NT._am>j*V'7Snop$*h@A3t[cA@j2_plCJ=Bj8tcMApET*"\&A&4+ggJ %Q?6b)6,*ksiM6FrULO"/aVCm;*mk=(ntO40m0!m/%cHMkE'':^Nk?XNOYbqPa@c>]eP[UZYeU8Z`oSVk0*XsAD$'g6-Q[5OF/oVu %WP,st;a6tt.<=77nSeZO)HcXVQNOQf,+VGrCP0c\`GGtq;BSiX9dI)6-S.L3oc?ob#`&)k/QWLf85p"Wi?IfdJYTPLQPm@m[Y\PF %`aFS=j%V!.`(56+A2.<NGrGE`BO+KV8Ab>6UFa`aS4:@F4(XmOYXLcPbMaS&a2r5[^Ap:N'al49JaA"s@R^W*KCMR4r"r#`'r2 %!_u<*BS[jR%a;XF^t_j3r=/io6QcgP!ENF##:Mrl`"16ZP>l*:*.WGM)Y,Z1-Gcl4UH!)j`<^4OZ04##$1K:H:i*%eU0D@`PFEE, %Jr;VKagE22^iGCHj8`e0(H?mt%Fbpm(d\pEQ&bNg[0'/Y^Lig8^YruA4IRU3Zlt2B]p&[lg0Nt(8glNn(Dc$\D %k6>BF]UPfG"_tZK9VNK*Zl]qedt1.;AHEWF%Int4?r@)^^gf_dq)O(U#i&c'8I^i5]G-d?83DA(-LYN440Qo+q:hiNk^*`UU_1s( %#t3dr5_jY8kQ"IA!]R.)h//m*i\&_P(>)*r)N^Ne8k'k?7a$LLoqALW6#R^C%#gDa\M4W6b7LC]+WD80?Ks-+V$NIK,VoqKSUmSO %K-$iD)lR'K:%?_acph6LC4VpM^^u3C<*3@N^4G[iH_1F-"La0YWs4_#10%;me\Kg+g,ar/?UgPo`UaEk?kFf7P)cRU(,]KtP=Q;mQthc*L;QP# %LfO)3`,_Tt\"0fklQ+A%;#du!Ms&Wgbh?JrN?Y.g1+clNO[7B7$)$Jb=gGn*m;@N_54)ME"E,Isdt"jp(T)VkD/N_GcmNQ.!a)dF %:.pI3!'8ddOQb`eIrJ]C"Ro"#m/d:oMQheCN?HDn"%krLWXu'S4"fdh&LM"2qW./L7EHX#Q9FY^E8>]LfF7_g!SC*G<5;!f%agZA5tg.44>$.t;^)k?O-%.$<,F_r=! %6.n1T-FQrLXEK4#-3:EG#D$>i!3i3m"BeTn1H8p74$,nc[%6k],[bYuj8fa+Bf8^E/sZ\M*5WW$AI]+WV%d@8Cs`HM'flqp[qNS2 %A5`Q,[NSeqkU&UVe?2"GA]Z>XE>G;29IKRlmtpo+iO:9.<>O@$(UJ<%YfM'WPUNE$MM#^3>I!45F'9TOph"c,,$.UM?ka\Xq:f_`Gb]$"Emiqm':Hf4d2Z\90j%'DAZJ%Q?"uiLWWe']--ZCD%U&hU+j15YJT[F""L9um1be'J0"qFHuD,r@k0F&V80"lgn %8\,%M),GK$OepMtZ(s=P7sa+([n.<'IEsd< %'hg/RKNNK5b)qk>h#m'AZLJ:6-o@U#Jha)-5mM?A,tG5Q`tBXL(hko0;8^BYQ#8_2&6(Y)@;@Z\D#$UG).so89?de[fLZ0/l*3kD %3qs>4d?qL54@Cc?;TbDnjA]u(8:;VUAN\3%F&Qe0#Um+jGa$\@D7-C+EoOP>S,c4Ar;ffBP%-YT1BL)KMHiDXShmlJTQ5?XnSrO) %$c^&?69qTo++.VX,_61%,A/$A)rsHp(eNA6%Y3.Tl>pi;q_[1BLFsf&Lbp=^nJ?`^g&3N %i#FTS\p*86S_,A<0?9@G4KR9pHP(r="?J2P:gt;lX6t$0.lO.dR=N!Yq'7ON!okP,"a"aJG!"kY#6XWBM,8b90#(!nNd)gB"4#*N %<)9)4ciZG7W[1.Em"'&qd%:h?'GA?p,-XbXB+sTh^ogQb/:]QrCfFCK$Fs,^&51/KKJBET]j_b3U(o/dRJgSim %LV,snFuH3QmSe#2ME86k,="NU%Zl3U"*U[P%#"nCScDd&jb-`o?4OfVMG@C,.geWR>GRG^8H\*HGs@C*jS>U,8BjRaORs7,Z]X/+ %Kd"c7e%3,nhQjhMTZZC?SPa>jF1&>Cq>=Y.]@m84:gSl^S.j7m@d?%5U)a8;1Pkt!N]+9c'UVLSglB1Q%&f#RAJ/N%9nM.XC',c) %oWFGaf(Fh$-8sfqk)#ptaKXSPo9kf#Z5<+O]HYKhZXRH\i)mODJOcb,?H#MDP\[)$Kq.6!n]Wk+P_0!n,?8h\V%%#A&M2\#oM5`* %Fe+>s#\4N8QtL]WWe*S#[>Kh_"?^e,6suQr(C2BV@,asiZD7`0;e:G;.2sYR:;YH^&F>>-J;)KN3nqFU!72A-Nkg0;>6M5H$q5lo %'ZNHX>$5[1C8dOg)1k[`"uP>,Q[_G8F. %?!Qe[;Zif]bS*X0K2C/[#!,r>#"-QMXXi/AW2cGSQ/*;s0P7?j8!QPb0\BV>1=g8Bl^/6%c_< %V:?j')o+nB$K5ed5:JItFB/Jtf^Y2g#%FU\/t]+$#Ut<7T]rrej"R`O(o@MQbbDsk@%Wto%:ma)2M)+T/UQ=X7ZJlXMe06=HWNnN %9FW8`:=PAe6X^(ScBn>_C7kkpplWD(0f79fY-K$T3d!1XQI9.T%_`js1458Yi/*4Y[Na %7"l`d$$HD0i0/,9PLJ\laiLOe0sh^`]c[S%UHFUoY^HZ&!4/Xa#pDkBUt%b!WfDYOeM6%Q5oX3,H^I5\M7jCF5dH9:L&nOW*hgmA %,4f+%EEqVY!!#QaMJ0r(J\H3q^j=:60i&:K[$$i:KbZ-*2G20"9/QD8\gk^%FMs8ad6kX0`@8mfMUdunan0fj>>'fOlFgId%Xn#e %L'@.]_2=E`\"WO'm5Z`?7sR3H4[UA*JPB[?m:EsnDrj[3%4YAAU8FS&]Z;O?l$`#Md88.mfpZ5BKQE2A?n&k5AU-MpT)`6q$:$S)&8>Ra*LpKU%XfXrZdLF)SaP/WPDu/inO\&B %H88LY;$4]Mg>7A)&kEuXVGZT6TkPO[ZBuiTiPVCogch.LfWqOe!"tq;HGZb_W&S,r4Bf]4:$H;4h %MRV"]f`E;\b!Ah31BdP?8Q`Alp9?krO<.EAC(qU)'SN^C,SMpiLOY1r%B1G+]IqPSeQ5IO>c[?7aV-Hb]\%3(JfFN9Y*58:m_-94 %&O]q3dAT=&S7$F+.fnhC;#9UL)?qfWnYtTb2'_[j7$%YH^.XD?"Ld<[LmAYX#+65M4[G%t8CMY1k98u=S(6!925VPepL7nYOR7Z,7.ET+sKl:_6dF!JWOcPDkNWq;R#MR_Wc5*6*&1f,s-VU=&EaYQinL!X*oWerq)3b?NjN7]P_gjHE-JK'Da=u0U %_"2BETOq1(Lg_-&QV7I=iqP.@i:7kDQ:ZX-qNV7CNI23Ik_guQR^T`#kClUio.J.p190CI(q^h?,$@4,Wo=I3_),gq3\nuXUK*[L %M<8NfW'k&ZnCE,aN9DW.Yd;[:;@8U[[Wpq?;t%OFZbt0`1YX23Ur"^&G0d"n]%@>T"td<\jtfg0S&n$U22QXl[(9Bsjc5Tm%Hu>0 %&#g?GK3++dNoCp5PX=u*P6QmZG0102DN_AdV(X&V?UQ7uY#lQD*7VD00Il<+:e"IHYaI$ak(VfQR!;;UJSYaI%QG'TTrp!cl6Q1: %;0FrP*WbRP;JT?t?is$#-Dp["rQVX\]#WLcV$e'e5k.n#*=P*,2j,]:/;/9-Rh-:87SOfP.o.WQrD-m062kD/mZBiO4_:2kHkWrptjmk/YYU!?QJ %jFeK%OA:mJ-9\.O*E,s(VpmmWVof,cg\A(U8fE`*Rj9VjZ:[t4@"f*K2:Hfr-e<)=phAA2igPHbV,!jU3L.8mot6gg"ADrF26$9X %^p]jtA=<"]446,?dO5?Z,-$FT!R-Z[U[d1N`fn1V/O.@cJ12nSBEM0JQ$6]f:TN7FHrZh_TGeZY5m1dH:24/b;5[(R5Km^AXAl@T %W=\^&W"XEO:g3'_&Y5eT.LjIsFQ'_9)$)OF79mU+JaUCjl9>7QEFJ'1aBP)n[`D.J?JSD9]N&oZ3X:@6$.M4EYGg%L66lqh<[;Gm %+$<(j.MoCK'\;@K$AE[[!NTB/'p0Y%<$kXAZNfg;1eL"9*-CnBc4]T$;l=Cr)ji4>!3X76HOr(,LauLEkUNj9.PYV0#Tejp$L3e8 %6J1[e:i$m`Hl%T!aPH>QP1E`QXC??@"es'mlhMn6Xp?CSrjo!n@"9//fQ?)T8S!a>)L# %3Ku"+JWJf_,ITpb*gCu&"J.1b51*]-0i\Z"P'BT@4Z!:FX$'W97PDBhp8;sCJ!W`e;@fclogc/'?f./OSKF!pX)8`W]X]+E80h#R %_W69GC?utc5R-"DIq0#;:/u/YU:GoV3K'B8Q2!hIXI_[UO]K*[Z5BM@Qt0I#B96`;j4#>23g7sP]#?3)"BqG'b$3VR)]Wf`2k"jpt>-:.*3Bn.Wi\oq`$QpuqOTWYS%!_9:^"6(EO7N`DM %W)X,UAp*>:b%e('o0sVWZ(($+$bOEb7%'F/(WFHf4YdR?8-Q@bT1Z\X%#@_]*#8ZbQ[Qg86fZSc3>dOjJ`"g%$`fkfX[aY %L6T2o=cXH,P+nXeL.R\XkQ/UeaihW+U&cRSXAHD0dhGATiqh,I8mst:!k&j)4saFpopc^%S^mC,b!V+1b-VRNZ>\-KPDL",eZbq< %3ARW+ZJ9I%KC#XI!'LocN"S)5<+C[T2n3:1T/5-)1N2M7EZ?.R<#870=;"d3I3qM1JASu\e>]2@4!M %:1#?.+eTL=,WlO\1XAUk(kk^WfE/*C]sMR5kY!ps$ikR6JATka)4*BJJ]a=e5.R_s]Z-Y]Tq4\[N4p"]WYd>(-GYR1-92`i4TcHuh1U&;u %R7B*I5""XW7iL@Y^eR&7(("^mBjgI9K")"GL]PSj!*N!X@$ONEkGsehFo!PV8^^A.`e@ArXGrjf6S:/5GVob#S2H.lAW+D.@^1$jZ@[J( %UansnPUEXDfLZtm'B-k\'VcI+#Se'_1-%Ws"%?c7:pI=0>Bg"52_YES/tm@M@jG0;p>!!V!c='"7'AOa+DFYu;JP*>rEp6(5d*0# %G>;Gg]UE`Enct@'(5V.8*4eD-+T"F7L8bE7AFduicJZL#f81LJd"@_Y`IJld!tBXc,ZL8_?+PnAMoOtet\%Bh2 %dDItCncngHc@SJu_'!shL89\oRX>UdNGK)oZT+J5>9?A:1GIuC]2k\>\fZ5Ff-p3-(CdP*-99n'YY$6.F>$D`;>(E%rn-I!aqOsg %\uoc"8'sn5-+"Vfh/#)t,AIWc-9k990^s,@CCYt(Tkm/kPN;"eTqa>d+KGG[\CjNDaVm"o2"t+;7_"%d,]^,_\=28)%E(\FQ7Q.b %YTO6?DC6iQe.epI"Grj"0`^^=ankL7-(o<7!fee54Tm78OoiIV[&Z/?%NCcl7'Ii!T[>Tt6'#kOm:?nC-dbMLHN*%JXon(l6?po+ %^#pdrn`n9+*$1%[DK5fB[l4@78P)Bc:EH.LOs',.F!FP#--7$"@JV[Mhr#;PFAP5Y([g28(8ek`.Cu:0,=2Um[BNE@`5YN^6hB?r()" %i!Q3Md6L+W$92e=#^`MFr`>YS\SD2(iYXJNOVJeuNnC(l2Mh]i.FYoX9d6Q;53_<(P\K6;1c&!9g4_k>t_b"bM1Cu`Q%@r-%Ues)c0RWL2B=MZM4`P6"+0DQ$YA=a,!BEg %VQ(FXkQ02(f1RGgE/kKNXi0362GAsqJW6&dXs,Jc;,(GVpN+Bjae4GW0$c?(cjoDT[##a4HuRP!M5Z7TiO&).MXiTP+?%JTP0^T`k>r&X;X\3%#9KB %p='GJ+aC`W#e(9h3_D"1jItF&DLnf"QW@#eF<<>2R?0gR=iX?@BJt]UH"*)FN'XLTcJ.Ua-[C>dW>\inN;6ZY=3V`dYmSe\>XWXg %)P?3INDS'<8#Gp:J#1gErM9E%<[k_,Z&46*+cnO0"g]]:qlWZWp^HH,!CD%cZO8GXX>5%E;q_%m#-8i96QVK=')W!ea33bY^nKiC %^-[R2kV*BB\==Ul\")f*Qj>e+>2>QXH(Mm<_6YDkg;c!WmH>O1>n0SJJ1*G'B)pCec=VSMZPhu28Sed#P"lb:Y;r)'<72["QJ#\h %#)<&]FsH1OeHf58jr!9t!3kTC;#$2neB^&rJ!#\^nT"3;#5+SHV<\]&-j4)/:+k*/)>^ET9(.TWq43(8\*[uo5!f2TScKEUAg;eY %G2W=_Z"O^IpOOlXSUAg.!P^?r)fV^f+U>[hGL>No:*F*4'6k;jP;WWg#i`Xo0`b3_?l]YpQ!J3b8qM4aYh3e7dF@Y]#4KtX4.1r- %>]u:HfIi>GHe\PWD;"oZ[FcJkQj`"%HHT^A(RWm;9u'.7>&pJo=?ukBrl.&506'((7kbub=g`,Y77"YrOOf@.1Xri\^=ECGln;Kt %5EREG-VXgVOU^@u$G`W3BLF8/DrncU?Q*;g7g*T9!D-Raer:P$-](e&#l9jR]Ur\#YmCUW7N8l"_"!ABrphKo&7t9rCn0Eo0$o.D %\:]ukiR-@nOp2hoiu&,2*\Z2/d\kHK+iSF^q96=E'_4\R>Rul/H(=heE`U4'E5R\k"50_f1G]ek>=q8\QY[^0(C^FMooisr7f[RC %+PtbM=66cmf+.d0%+#DXKR`j %$I;#%s/.CXR5$$9W1g>6O;7in*)s0s_%:u0$&'V0i6E87ScoG>it2\bR+[hK,'_+;cUK['TG65gK0[Bq:'76>Xu*rV9ABeR4o.^] %PZ&B9X]Whh)WH#B*+`k1EAZnXl!d_X`"jl4'ne?V<'o0@Ii<1$"\*T:H*WRA-;&\B)?3$LrGhEBQ-dFl1^a9Q]\>k`8 %&9)cf./[L0UDRkDAJfAZ5h8G;c3a)?N75=Pa.b=`:.U%a^8\Yo$(lP.O\R1bmQ9B_b=^:)!?uh^'oWeg!i%bijoN\l+;!uhg%cI* %7DP(%'o_a4"RUGidKAlQXg2pkG`pFSS/&np;PNe+AC#DK7h*[iPn?m%39W0n:eHsZ9tfV0%WbY+$O,i&nKf=A]pQrG+_Uj&NPd^W %aF5BDLaP9saji-H?ZHD(D$oN)'otJ;T>6)V0J$!keo9%I5k6-I'OCWhML'\Mf%<<.kT`5] %*pd*M`sN!._8M00#i%im<#.8Q0X(mk0Y=fipIgc0M:.[[]X"CcM)I3R+\:340uW*cfrHl"`$=oI]B+!LK?TYOQeXjH,5$piAEok+ %Kqc@*#6cFZO9T0OHr%scA-B3BHo2peMTK0J)l:aY7u??ELFRhq<"6s%OU@E+0/98L%JFf&p^;34PJjVMe"J49/3JcB?QgT&=L*<5MOu0rj_W8Oc-qKA;\=[M6IpL>UMt]m//sHGISGA[=SgU+0os]ND %^kl\(F/SbLS@De>3Dn"@MB[;[c-ekp$GK@BO#A;2RrW'\R!(hr;B3am&8hh)!m4YDaA=;*Bsk7"]%u<*PjoR`b^_L8FA&$S %f_%M-N:$\3PFH]"KI^;c4-0(=H$%2p?_dB\O]s480rTeVElAWgJeWAt8=634,TsYkjf5sOWbeN/"\0eKW-D4?`W60/jW+HRK,^$% %Q0%oG9,H]a-grA&KsS,'9M:=mQ"q*iqpW^Z*N:GM+YfgX4oqQSUO`KC-d8)`>oIBm0A!%BGn_Rcj@6)<2'.W2:#ff(g4M0IiP\<* %J?Q,%WKu//17?$Hg%LZ:-dSnGq9g-_KT:*J%6Df]D?,)fZiR!tPf&bTK+rur<8m0I07gS+%WDnuJ?l)/bG%]5K#a9p0XPfA6?&\n %6./20iqSHpg61#uAfX"fX:,Jfe:>3PWb@]N>h%lSd4gYK]FRq/1VD8$k?k!>=Tt*O&)K)T%JaP5FNB>UaXK%H>:,A/o>?=!0gB.s %<44YRDb:+kPGpm#,aOs!dfW8Fgq?=MPcJ)Cj%_m"m1=rfPApVNr]+kGhI)+jTc6*2hCol!.c03W1Fn(6D5qtT/'<0f_BEG5O!X9) %%1$LY#Nr2HXj/GF@fo*us"D0o"02[qRoRuKJe'bbN9qDM.+#J*2)_i>b1C)HS+$I#Z0 %.">FNPuMl^+HfS+;HdZ5lH?'7XNP3`"M18R]qS).TX&6qTQX2aHIaReM*2(Z2`.18EH**D8&g-]hk7NaJ<3'*32-cT[&9GT.9SYCY_[UPJkjlCC=cH(#V_sP_@SUea5K,Gi-ht(ko""3,&?rmcS@>#Hc7>(kAm8JC6&s %=j?8QA8A=d$guN@>_"#aO& %.OI=c1\;AJrN$E!^>Q:5n%3P(fO6RZ3R2@N5a9dZ+>?f93$js5<\,rNC.`";kNF5M7*3FP.$B_J"?t<=Gm6- %p$FmD]=hn_:0r3*M7Dd@db1JM*-PA-XD:7U%s,h3hZ4!cd:o&8@up=Qe7)12DD=s*C%gWUFh>0e#d9TID"42i7!7a>9nj+d"%lC0 %<\%;=k2`UU&I(i0\WgZ21K %S]KhYk!6'bR8d6K9R*BJfLm?a,EN*j=LIH5$kI`Qdq.TA#uHAl+d6ElDTM,]^b@pn0\Q$,,`2RLD(B5I-MMT;be>5ADO&I/fk=#Y %P8>Sp_2F]1cqa%J\1&kj#@J[(E%s?Z3/TZ(&!U"Gk`aQlJBIU\1/RA@*+D"ZKnpAR+Qnh]J7GDMTN+*d\$DZh^R,3n3ic.j&KQf1 %W<(A%1I.MIiXCkZF?^p3'+daVrT1L8Ij4A-lMIB3lO\U7QW?UMs4XS7"JW,5,o=B>&B^Q2LB0Z_mdKV`LYK<46;l*EPJCU>( %%c#1_h-I%j>f!i9m+KgJU6I&Ffb,.7f\0tGagKf'!J$jKBi59E!D3mt[cX9d`rpXDJ12okk)!MP(@C/d0;_hAi/*\qI_f%1RKNm0 %m#$SD[cc@qmqWg-p&-5ZU=.OiBJnOE"T.>WHCZ %R-6(8TEq^[(HU(5L:GSN'h;Y-R_C]U]eP!je'3Hi0[;eF3QL.6q9^["!_uGVI@!mFUce_#Q:aAH'.&)H$(_BZPG[l@,JY7Z2/m8g^bk(/Xb$0#]9JsC)P/%J_El`bDe_PAObcE1a>T4q=KGGbr(N=oc>1kBA %hV&6@UZRIOls6ks"kK=so3=B#65ZATSGRY4P'-[.\IRVrX;]h#?bQoV9Gqi]d,[c:P^X+M[=cm)Q<,A1<$r%Q]fqt@//$b)-%ATTp0]e*Fp]\7Mb$C`"+60o-$;">>j'Ijn\Ht`TK%a\Wgq'Zs=ff<_a[(rnXI0Q\# %SSs23[81e^iije=TGSJam5':nYhq7=YAP$u&9B`p4cjePJo<0Vi9C^6r_J4@[4U:./*N6;]qTX5j^/oaBjCcB%-Qt@<3TbBtn#c._oB1j1Tq.r[E %V6D*^XK@W;,qfuE0=n3+B:-npbUOCV$Xil&HDBgL/8N1@#cl:HOkN0BQ[<38,G-ASN;uG0TTA$o[%]NG#B9GgA3%!EfN;Wm.reoH %7/ZRLL.gGjCDL5Q\G$ZA_ODX6/HKYrE1&ZJgm:A1"Ge#BOZ+%^i5<6k.c88G*R!TfesS %gqq[K6[VQP"Q-(Eb@(dYF2UWq8d1NiVme5:c''2J!6tB!!#/kM^roHWY8D*WlEIkE6AGN!FE#cT%[s\Tb&N]oE8ZutTtEWe<26bY %AT7qEkNioCP3g#$osOl.2q%63';X4P5qPZ#`bulNW0YU7#-lXb.%:4=N(m08aTV3o %Z5?1pnsGM#J8sn-EYgL9/^""NUp4>.p^U4/afU-t?u_i=a:qc$^*@f]LK&2PZG]ju-9ACH,&pl\afsD.^7X[&$_@Wo8B=OH&]tL6 %1)lQkf6SsKmKBIh:kSY*!ti@epS)Uqb/>"B&B-U#!"3QY<`?RY/,_L?QB$X.26W'lE/fk6)CZG4fFRLF_6/RB4B %jEV?T%8MnL96??u>mNC[j"I[Ag@B?H0J:O1>2X'HSsr#_c@TeBKMX["+Y&>Ig7_YEiXgB*B:1lb.0.(2BnY\f3\&mi(q=.NYDlM^fnliHT%gRD %6ERB@8/U.oasl?"Z=WOM1cWi3_NFS?QIU=r3]0AQK2_?`=S%j*8JDdlk>c=#_+((q"1jQ(csX4+hS(266n!q(b\JN@4&H7%o/d1c %VB\gb\j7n"5Z]0^JD83.9d*mQWbF/Cfd?h$)\)lO%5J6+7q-dH81sts/UB]]<_5Usn8%e.Of%+QIYRqC`>l[94+KQoF_7J"FNHd!LC(4%j\/@TRJUtB=7L#4qZSmcbArbmk:/`F:+LOWq+C0f4To>Eo2e(mHn8`Eh %@;9NkA4T,O.HVX(EJ$&8F9e2>DE1A-^ %CG[[__4$Fde>CFu?j?)$pQ(]Fh%R0aq,6P5B6H %Up6"f:iY0*fdmH@L,3rtX&hD..H9#PR&h^PQ!(=8d&!VfKc%p(m>="6N20C1QKaB!_FSkl1(OV0jS/_r%rAo*'gs?$.-mcGb$'ah %S>VYnG5k[d"\(fuR!PW/ED=plk,!#d=Rk$Xadaq.3q<@@2=nu?1n)!RCkN]Zh["X?+-+9[]0GXfE1^_-Fs7/I$gVsKj@2eb2I",X %^E3c%c)bh2"6**d8kfNVa]cUklDbTA$Y&5K;+"f7JY7A3/D0/*,a0h9%oHK;A>E1e+Hs>r#i![d`-;A=C/e)rj^]VVaDr3h!-TGZ %2=TY:H;a;'28TWM\8oSH);)K'%\GAMTL`'b%"d#OU2HRPbi8CP4$Z/FT;?r[M3mggIHPRM#jAnIF!A4nVX'o[.WefAt[(0qB&98nkR\j/=#< %'8ul48uVDRLbehSnW^quT5+[QK:4Vd6E=;K!0,S>e>GUK2e>?^b>%o[+A>>W-HGBo9aj\3eB5WXidD:U_SN!.(/'g^HABoQ+Ot8' %ENi?SM&M]iP_9s=:p:LJr:(>_1G11tK0q3,8/S'>JeSHp"FO_%YWRfQ+,LoZFsK!=9=i8V.iKnk7`Qb< %MSrdWA]5HB?l1#TP4,,mCD#Zc0kne=_Fc60$8FT@^-Gb!V0BM*Y;Tj0d1!3tjGs*cAc5.n64"_S]g*N&CusXNW#iVQ1''[(>4b2( %h:VqM[R'X!g<8iHUU!J7gi?gje3kLh@O3Y(+bk5,OH,!HQZXikGR+SWYUi`f7@(k`,7#dKJ.bA5bHdr[h2hpVo*D.hYJj?g+k$lF %K9?A0cn6=bZE3D/V@hB@5J@IEPo]8tV%6$^`"aBg0-a[HS#4q9EhNMDdH-,8%iL@*`@Hh@Uq'+=@u<(9@VNtG,2+"SW$C8/#nGsn %-j]/^[2:)Tq$T]8'k+f>isfBqo'b)Nb!emEB9.fpfAu".j2K*G %-4WugHKgSM=Ct>A0aSl*g-OYYi'5#:D-EX3^`:6U0$?AC9gD`(e3rRJ05/:uW=9`e"q:N&3:]ZM@Tc!LK+Hs4L1"C8-DG4+JL0fp %Q3M$$J1gu9j(Q$d5*(Y,b`bk'oH@UnODQE/m/Z)PM&)3,)ikB?kBBG=]U\a,:f+bcsbdT %Glbs7,MQD@i!:>1VnH@Pl)a;ggIG&T6)e;2V^M'dtYim)J,jflB% %gH-0/KH?+P%^P&Y1'3m3nrhpLj^C/TLIdATG%5J0O+[U>66k'Gh22\)?R$U[%7nDo4p\2M8Z?%NZ@bTmFQjq/5SA@Y+I:M>NM:;6 %3g""52CFnT/d)SMadRdcFdb[@=ksFc164U+1TtGo$#0(5:I?B1hMi,[qa@.L1&B]u0fqM>_A!M#$[mIadXY6V^ %-`L\_*SCmIGmDmU;18j,@eiEX?mH<[b"p<):Ldh/36(5iY2[Yaefa%C\Uc)>,`FURIun9"WhGu7^%O%jY1!*):Qg#KP4V"#4qJGc %#Md=-#cHb`puc;JXG_GN\qQYsF$t#?LTsV3buQc!SB$&nI!'bI\E`M.;n!OcEk*?2ia+YX1)&%l'9P60(nHM.So3mj2bIa8U.AV; %NBUO(<;O,pYo3boNIRCQQ(!N0l:,0(UU@[q?/6@%M0Q:FBUJueDT8>D`2cVO[e6ERjs&q5\um!-2\iYX&`7e6,iEdo?kZu$NCB@n %>O99fG,$3.,:C*#QCIE3'="$*ELu!Bd$a+F;5@nb-FFZ)g5U6GN/F0aTTs3FDHuUm(uFPWkX>\O71j_gNdH?!U\JDG[M.i:((pN8 %ft+\MT'jO":W-d>`,BiE]k=+WRgAS&XEcHM]c4fENHLkRMr+f6n&F'W`8u2Qpq+rQ'?gG^(4e*q^aqE1_dh'P46Z5ZFSHLrGSXmO %)&iL/0%7]@.n#.YU<>F!J=!"hYirAuFI=kp//hg.NWQXVW@=XeSMje%>l>f_Gnl7R& %Q %>mA%rgL#^OYYQCoV&J]@'$g%a2I)#C45+QGDH*tiC3l1"5jaQU&`6L-\Nn@u+4LGim[M/SJ4eg^qV=#]+DO72DK$h'NrnHN@T&:PF0$!]3+*a,6]ZW&o_+jnUWhrl(bE@GLoJ'`Xn_9Nr=bA.oAq'5Vpb*.(sT^-6UFO6*Rg#h\5Km-r5= %&+hjG2Tb8G4EnY@[mkjg.1YuEWgk]@c6NEdQ`R+*l8)'5A-WHr%^"(^"d'3gQ`b"]g??FD=lhQ!np_%Fd_K??bY&#dm*IO_;E8l5 %T6^W;'4b!hii*6AW\0iBQhm`&OYt+TeKs(@U$.rF-[SJl8a=5M%3] %>meed2]80&>h-1$gs/gq("lU$EBDXa7XO!JEES[R`M4@%+8t);N5MX7R0[996DJ[H6HBhd9=6)Y&4[#>.iM!'5[SuE?*\Vcc30HW3qNm %EAtaO/oGPN`i^8?2\EUPNUlCh"3s@Geel;B/E1L$@N4@[Mh[aXSErXHG2k;)@lO:)Sp*\X:.1.$Of$s%eCjWI-J#RD'g!!ngPrZ/ %`oTt6n93i?qiS^9;8c2IEAoe$2NGTpOfDkiRXR0m"lSIM0SK,AGB=B\Q#48EP<$UraDR<)p,f3o0*a.57pQGNOkaoo/# %cB9fp8XB`pJi0CJYgV]D\XU()bOI@2*7JJeRGt!0iN='ggh\b*9X*\R1$s'CH"Ql!)Qo\b.o;9mW67(U`Ci&*@5RHoFd\BS=d2C7 %90I$e5)I_mh,BXVC77Mib;[s_VOD)$C)F-4\ZmK+[/-:s'C8s[9O8spY:`&l"IE5WGHAta2To^`0V%>[croe`0$ia;PI/M>3l,pl@7BSSVp9=bNd+^=%'Db%f.JlG'Sl#`h^mO_b-AP"@6;GPgZ?GG %@*tNVge@l4Di_oIbP9h'#O^%HG8Z1Jm)0Q"`Y4l_I=C60PO]^ZEl68Zj`6sOI3*ArGM&]=R&;<6Wk3Z0ZeX/t-+h'l4i+eeAa/XR %Gq\.U*dGPKK]4fCisee0LX1@"q7Ob2hW7\.k$IN([.ie>Hc5A9MYJfjr%.=7LcW;gAj=Cbhdspuo'&qhmrs'R4,j.Pm/Pm8!Ss7I %ZhXhq\I,oN%D!Dg]%I^BBbdKX0_A7#FE0E9jF&";\+"BMXDfJC<2II1eA@F %8mV:i$)4;";Q#f\W^dd]5qCK^T^%\?9b:NO8[,dJ=VK:g*?))HY=iurJ_+ZC/0"B!Uf<[-Ckbi(6pK6G.[qPEHZY5\e;bOf %a=^o^"M&'(LpBZV3QH$j&7P8L1FK^j2d&,PFI`f<4W>(jK]/9GftKO]Wfq>(:W\*6@U?9j8K30`e?[h/et,^J\3b %%Toli"imoJ>CU`]$l?*uqkpEZ-"a#mGjk.MSo3YpRAGls$%h$`a=C]O*/s6)I3Rl"WRD*'c(&%B6;=DU]JAp[Ge;0fWfMnbpSAZWB(u %s6k@R[04Di9PF6:7ebdP)T&-&d3*WW6g9M7GPcO+gDpN>tV[f5j7IRJ55L(pJ1hfp6akeaLFaZd1B/dH/J';a46]LQupMF1. %k>tS\YW\5Dd">,mDm/'US=]]Lk2b\IcVG?6A4\j(Tc'%/)sVnNo@_C1mIe_O$\jh*[MFn,07U]bGCI/7.=?sZTJA8!m6A6CHb9-# %D_UPfVS0gQV$<.<)ba&P@![0@;Y8:n^KdDGgRCl@@5?)S-$ILARbp!r(=V,Lg076tMeR)a4W01B_!J5K[&EEIC,NOL?o9NM__,%c %7qWph0#%;SjN[?NTCoL(GK^FUhp?])h:(cgMt^/>nIA\;o4n'4gG^e25+J619pTIpD7rnY3XPH1JC6/"fIFjZ`5g(c>, %Qej8Q+5]3#!I=Y;mCT^Z4(c[">1.=)W*!t%52u/3.h9UKiBC**hu.qGqUbI?rOkQsrrTPg5ieJB?X2Lda"KYP)f+gAp[M^D"-\X+ %]\Ya-J22N@02?DFYHQg=Sm3iaTZni*]NOh;OE^/3hO^7/I=$:GBR!"C+5ot-nM%ZSpWqGmBD3:@iJCjgndi)Ws6Qhtn!@"&9C;Z[ %Z`*3iHbT4RrJ4Xmhlb;/DSK=bd!lpggY''K!5IK6AVW+*qq9V+lO%"!Rd>0t]f5t?C\p %^"_CfO&5KsEhg-P"K%JU3s'^Yc+'D4Ju[QqZ)VaBG&fc\YjB^SG&hYQqr?ekm=I4bgH3T%a0N@5[s%RJp..RFkHgX"cCjWL8.A_7 %+Zua\s)Jk,j%4^%T480S?u$cVo2X[GpQF*S36Bae8WL!X090qqcMi1iVIP\)h_?,MP5rbh_tiNKS!,eomh^qYP^@Yui<^>c]=U;? %3PROVE0In42VXk-Dgq]UqVq@,H2V9#2#mM4oXNZ&'8U4'&=Kf\LA'BKVp:uQh1iY9G6Dja'&I&WUk:fmo&83ddtoGY1A/,"lWKk\ %D>i$AhhJ8hHIN!*FN:,ck>@cH..2KtpQo+LgC"eMjb%"LLsW5SKqRd&6=YL0hh(5[l/pa)[3sf%q+J9Y+&B&Bc7Zgo]/VlXA1MR^ %n_h[gqtu0(]plG*`1rk90@&JRHuX1QG'S7Rqra08GNc!84=RJ&^GOY^b@8;6hpqlsXlOu4NF2ABf@`(AD[R70.JN>l2"*]^rj1^- %Eje-ZDKQ@2IXf(IiG[aO[A;upFd7G@Ds_EAbb&gkenS1m,!ist=2VJJU:8>8/oT&h/f(-J/fnFX:G.)Vq)ENDNE4Qraj%+;70Oe4 %oUg'@pQ5DcJNJdID4qp7p3M;LGl8IZTC;\:$TLt]ck^M5Df;d3(T_$roa!b!X8-&bjRi*Cjnh,WNgk4!AKO*(C]=s`))$eBd8 %@H6>XhR8n01i;EFp#aNpmJ2M`/ZL*=+X#t5lsrD/)^OK#TKH9:M03<]pqY9J7VEOt.lPIWO %nG73P+qmKPO5Gl%qb^Hq8N#5.Pa#keVT0(2S35_1tK=h*@\p=iMqHePMr41m^>!VL0A %4mf_Vme5.:F1ctSqq#]LKmhPFr\/`sBa>(dH.]CVU'@N3rBhYdk1&@66LF_hU"gm7Q42eR'TYGO+D %[\qBrB.(/AQL"cLdB2T@fG;0^8YdF)IS#FLXbUXEC;nb-3I=DJqj-pGqiRui.pfY4[WQ(@Q%[tCIK'GuW_[g0No'ATQ?;Cr(DHDh %K!kO*@k?a=W>]!Q,L(SII[[kBBh,sUqf]?SS*GS+Qs(g'!9cqOqL[6ZKii)jDBF/l498?hPFM0u+"trX(MH=R]eaMLh!Xp+Q2@M\ %72=J4=FQ8Lb8mHtgYZ-$D_1WAQ4H21iQflMYF!M\r@R.1Q?%IJfko1:QL\a1f'dN+pU?C!laPU*;Ehg+ZbN?lVIdHqQ[?'P@kk3-K95+7hu`AnhihnTHp=9+0oA4V-dLVsZsleQ`m]_hNkZtKS$:BF)#+H;nuGI`RF %q8=NAYtrRUZ_0J:lS&;:F4#U.1JYh$O.ZVNH1L[CMnST=Z$dGTW?C(%4#50:Z1hPjI2ANfqKq,=hKQ7!?0ltUHf)e#q(=;f0_'AF %5'l[Dq%@iFQ49`4oY!ALd+A.S@J6:gI7XA9fD$tQj=cVcq_j;rKm+79CQIsm,?],(UW/AZUNND>40420mEcnbd)Rk^c'n0:W!hWp7?dddR&04'9MpZJ8JKD %$\i0[$.th:EUO4dNcE]u!kpo'p7?e1Y_-ghQ67aPRD'roDngX.-Hqp\sOEFFhTGE:^lfX7qs1/W9YH'"Wh+m";e/lMB8io@q_CIqS'oJ7AO<^KAp[;;kg7ZhN6(h/2VC\5Uo9 %4N%-bon$]Fq@P3lgIrea[dCO_f9ZkG!LA%bNU8/lTe&2IpIlu^-Buj2Q9>o((\*mjj8I6smk;gUhEA@$cBCFC0r;>/Pl32_,OE+! %>qPGf]8@e9;"JPC&?.%-+^30HFnAY7VYQ&8*Aa/H)mhPmp.!NfB\FD"H_]h^(ek6]GKm!RFl-6;aZfgDBh97e_/T7slg$Jo %gmfqJ*VWU`N`f(PKY7:u`2kVMP2=b92K'W',OW$X/oBp#hK/.&e])]Z=1J*jfU@6kMuaFu3*hc\FR,k(Z=[q?b^Xt:FEbkPq]F^& %S=KTNonl/h5G+I;hgYKa-#VF\[iZE_H)G,4[R=Ff_ff^Ir$l07XnDTD>U\@,EBM3Mq]-(27[@DY4;r"l=7m[cM->(3qf`b8\_:C+N-` %Y^4'3j*U`?n*p9-3.)NQ:g^H$IsR%W^">of]mJ1ZhOhBdD0t/'6Ih\6SoENjr+W0%3s'^i-dNK:9NuZ:-n7"6CZ#(Hm,[=,p;b@_ %-1pp.Zg@56o!Y-$pJXi]kLh(t8R$P+/a3+L4j"PAh#1*Y5KY&;.,,aql95U-G)XA@@'agO^^rjW;(.Ik6Yp])u1,.;-o#),M.$2h/PW+`68^IhJd)dgB%- %'*i@&!r5/8JqrJPg0k2:^HTJ1`.N@4A06E<"VYU.Dip?d:g:O^J^53giu_'KiH5[\HMf(D]ZrQYUs@1Hh.,eESPG]$j\qJ2ANY8-dps%t8TV"%5sK^UX&5>86g:=F4<0kJH>/M3$OEj2g\\s%09C0Ib_:+jlMXT!ZhIeE[40>E"6[9jZi`Gq;qVl %d4[#ZqXa"Pq`eig#0QuEfg/Lg*U7%M.TmJrST/@dM.1UpF%!8r[,1T.2^m748nhYNg)gN7'8neUo$+M9mn7;Cp!5/PQoD&fDGK&Y %(KG%CmI.;hcBen&#*X'!_mAp"jF)<#rL'E]H?Cq>U:`Mq8o+3$3_[BBe\<`/BmZ5,1Fr:SHSDtIdLdSd!:qFH.iSh&gV7Ytr+_LnP*tF8bANY)d@hEk`_,<.h\k*c/1I/_=dVm^j1AK/YO;<9V7Uj2dV,rUN %#s-6LC/a9@dB]4P;TO.Ic;Mfsob!.D4+JYrf)V806Q$-0N&SobYcMNAHtfNCN%((c1,X["(`G]:pd$!<;Xg?'=o&&LnM"XIB\CFj %2*I@lYn#?u;9nhb>FmDGAf;e-A,Zn#k'+#dQ[dQNn*p@R*D0JJ]&T.WNMW+m!Zpr!#7h&q?N%D?W2_0lbPg_#0/J[g!*p6nmp3(q %oUFtR(.Z6,%DHXshb:]jrp[)gqp4hO?@DMDe\D(s%_84dP7GpL"mu-M?Dh49'pUm7V_T)\><2etf@8pUcin4q%#?P-Iba_hk>\na %j(BQ24#+dlNbZ`mCOY1A@W\l'>j!Ap.o;*!-Xo.0&Bjf#f6 %OW%<]4tOH_IQWoZ->*tVE^k%?k7k*o%0PK,K%"Am0DVn)D-W(djNNM"NP(0q<'P:M-iDqF8c'j %lM0H"iqs&Pi2hrVhS8r-ooJG)@d_'I.kgbNhk'dAQ0qSI"j4QYPiNAp.b@rS8.09AU_?E %gM$r65t>""MdlY?Nm,)l]cQfgXS6M3lIhZYIlegRY2?oFb5,m9>[;5+MXofPZbVROWu')i'5]XpS=G5lY2)1[Hd,u"3L(=IqrX5- %YM[Gchc;DA1>1?koB6!Kp?8Z4ad*B6gShFX0j*ZYp[t7I>FUH23A?dVA*_H#sOfCFA$S[JbTrNC:t"u %JJYg#7@YB:$n`k[AYG.6h/]l=MuhJ%r("coY+2;tZ[o>sE[Ej$6rW0qZ.MRc,brgcqm*\0%89p#b4%u;_J1n[A\0L^q7PtnUL7>*n`4=m<=&-rU#Xn5G.n,SO3"OHLd?9HOYbJ_sF7%rTaDkk.f*N.MI:(LVKIP %>cbYcEF,`XgU!Ba?bN-[.a\1[TDoCX/?d@U]kdVM@=e",T3qP9EE<,5p$+%t^MSG,N3^1XUW!B-GCe`t]mn[$#n9B9QqSgSDam21)Gl?fhT@\r_s&4CFo&")Xn"G?n#H6_=XOGO6!+hEu7MZN\(b_=/:*i$ZCb[,3h4&,mE+t*=gfT?a %Gfcc+n&XKQQo+W^eoj;:5PtT6.@`_WEp77dDo(B^(\1-Q4nDfR)iS.G@#a^%?BNbU4kKO6S9NRa1-->Llg_mL7"Q<(cZ14+2;`4:RJ2[Wt,U\FOk9_bCVQB-&UOZ?2qb %HL/LQ4I4*Ef'.:C'CVVbEpHa_3QFJ^(jX0mI?l^7j9uG?]&]_1*H^JmBmFY"_Iq7,kfguOY&$)6O8X?8$<_54kPMl)dGd\(\]4PA-T"]A.2-rRKbYZ?(Kf2R#".=eGA*KB3 %T'&!#al]6jVHk&6,ZEITJb3J3PfGrZ]\"538(ALcG7Q2,.HJY:gV2ju[T4a/3b(3VF]/%`84Vsf5qYn-&NG/@[e>YX:?E8oa %h9V^;8'UM3H+3H3GFWL++W*@ch3I)4U30rnhl,f+#[q_3=i='m7dn=.6N3\+o7Jt1^Ld>qF,%)#B$JBIG&cQ'.q6)(=S(@r"jWR' %D\.pkJoh)Onf;a`2*OJ@iiUY]+5)Op*hl`2G>8Ib0.:H:msQY^Ts9Hc"n"M)HCuZETi>uU60(1#V;_6kqcl,s)Bl`a4LiXrT<4"\ %+!3B_`aIIiQkJeX74=6)f_kkQ^rE[FW^-7*.QLNFUK=Mt6q]BcP9?oPf*,G&.Y&C3H_k8RlpO]W[QjgSpR6BGD?5JpPXLT.3Zc`C)m$n!d-TqQU@.T8%DSTg]IhjUW0$Xsl0BGj3CqLh(Pj.B5CgJ_) %PQS2iloZ*egm;_?pQVYX_)af/(-o&TL7\P:HG(o(.- %D?o'bbR&.71ut\o/gCYE'J"'t':?&gQjm2^mSlZ3X=j:2MT+j1F!>)f`g&!L-nLd8"OB*Y?*(*K*l/lC<_=GICef8/daK<$;E!J&W.400V_lN#l^b0jfM^BNN1gUR,$ %31^A&+$$fffr"NRZJQtsf9T8oP'o*.#\;&BhH&_7Y)CaY7CDO.JQ&-B %!F5pQNkUf:Yhu0O*4-Z+i0-n"@iLq`DNBk=dIVC;]o(-Qcq!f[0)@p#*ZK,,TF9NWiqUk=:'^SsC)tbSo!)9D!NWP-eIICj.Q_$\ %euCh%NF*!KghbF;cFpY-\nko)n0phrj.6K-V*-J$T4uWPrk"k"b&?D1%@k^U&Z7AQ%Jt(R_J4b/3WKDi#JALcVj$`)plML0[%0Fo %@";F8TshQ/eFHE<)83?"#"5/ER?-tEOB:_apGYQU_)-HWGUl_$DE<[QI^EnN6`>'[FUhkZRUF$H %c@H1sUJ5Mj\?fm^!DUmL.;m$?Q#5d>96fcPo\J_LAU(8C<"i,\b=t(>Oj*>>33<.J1`KJF:Kk)sjUF?bLc^m)rjW4Z@)&nGSZ$aH(Pjr+bD8 %eAgA,>V:YMQ_1a#FQ*5EA\9S,_mp2fr*:BJh"KU8%*iFt#oH*!8=aCiAF9GgJ]GmL %-4N]t(Wlc5:6KY7P*70OhIQ[%JKY'P,V]=07j1&7Teh5WEL&%kibLGhOfIOALr8dbg/LC!@&?Y(@Z#La-5U]IiSrkea< %b6&bn@%AH]bW3B*!IQ@H,ckCLo%<,@9Cnn,A+-YpjnKB\W3tX(/"OWrC%OH5 %5qYcW=g99#'NA$LBJ$r7Z,cs39gDGBHa?:^1:mS/6VaEZ:&g+^D1,BB>;&RW+WJ;7Nsia9[ZLcdYD'2?ZFgD1E&5]_:GRa.(9b&c %[B):GSdlLbl>k[!AV2t12,>b/UD6S+XYRFC`9C5eYq-r*']Jr::W_00pW7?$a_/@kV4cNMQhigd#)T#R$fPQIS^TU#f%8%%aDO&n %D-[934Cq&ei4$!Ib0gSVY,rmDdIdPKP8+=?Dn<]% %en3qb+4d\C[!79NB."`KN)iOReKph]RBXfE[28=%nEI+>RgBN?ODnG\1mV9>M\Y_igV"^#eR9BN.)@ZFV,E*$B6#n %H1UjJ"^!ufl*[f43X-'86`P&AAeR3`)3mJD!Mue %VHian.[3d5\rT"J&eF9=]6tMGE6L6^<9#m,pk-)h4>\#\b"i@'D?8gCe(U9g7A3mGW'Mj"IKR"7]EJSd80Et`_nMB.H=HrF+Ls'h %8VFr'/('E`XT@(Ga2CMfN.S*A3V"_;5(PB;"TVAZ0rsCKTI;Q]$j&\HPZFXOrKujY(0(KhL7CrgUoUhgAu,ObKZ"[njc#?<'H>KK %o<,$Jgf?D!mn694K6';2<3,^q\BRGD99*V6rV@)nqY7bPA"kt/XOE)-"98Zj`+?nL-r`)E'=_+,^R2&n!X>9_1UeSfc8'<"jE@*cf %"LRAb<-l?Eg0cM%$\ffei;=52:hCW)'B"te/&#`rY3'5=ME@\(2h<)Vg)6C,Te&(+$VKnb?=%p3D/7F7Wq`t@[.quD>K %YioU%?rP$?_`S%ai#8[X.Itk-+Mo`EhE2ZtAt]c,3L(a2U17mCO9YpO7QJ@BA((Ob5SPBugpko2KT8VjA;f*HbgqC-l^jO`%3a:\ %kF`r4aU!XI7s7@gojSN&QLll0m5e1]5sD/O7<&S8!ZK+j#g3>h@*JscObGin>r;qeQ0\K%=53kRL/E)&R_fOgYc\n,H?!G>'mU6+ %5CfIQ)o/tW$L]O6;Rfj[W]r$B9s1JD4b+fRT#/$'HYaBuFr;dIL,o*T*,hl97YXXk9^[e_nN5k&9A8qJ,)\-nk[)AIAV\7e&:Up% %DI+1YU=eJqk`mSdj&%eYcX0-<@M_2La^uB3*'7Ar^ti0]i:jl3q*>ak_2k,/WElS9^mHD7(l)B4Cme'^7rkMnA%TLTB?0G4l$dKedmUpqH@&bSG>3jfV/q_V/7h3]ONT]r2B`:\6>R'4\[#YS,TBc%),VNa6XP."7WHOd9SRlS#"'5:&i2$MPXY"T*&0rH %]/bhjXS8MYLMj7Rcp#p]9Gb4_b#E36!;p-4&Sj[SQPM!7p]fD2!cN]F88*gc8mpAh7b39T)HYE0)\'h3A\#I3KEK5SodL7T4RrS` %XZCE5nrfHO)GMhD@CTLY.$i.FORCgZ5eWq\F."DB@RT_T.6(_11[?nHo+Sa%kCt:j!Fkm#i%&!(``qL,1JTbK?OuQ-Z&.Q?0)\Kf %6;T6B$LCN?@p,R(PUm:MK;kPafti4)fUi;=N(?-YnZo)Sp>rQ-@De4Uq80dh):\H2qCR&Y+6f(m0Z;34g3?ga#hHWE[SF49UEKh+.=k8m1/3Nu/%iiP?9fs6*j\m[];LGjUS[pW^PnpSn4Lrb( %i/f%!!@*2A&(bP.A>b8pgY49TLeH>TGVmg?AH>KKt"!Z*eer+$B>NU>H_lEp1%+;c!,=4?/6T6B?b['._\-?^:R% %/lhYQ8$"Ib9i!XR$r$AJ`rSE2A__:Y#80_/=C+.ub5d(2$$;8WgRgO#*X6aG-85fY?V#eA,7mf$5^Ih)&\V'Vr#DC^Q0%.['E^Ko3J2*/$l7b4^MS^s:I_9$E,^J1jaVIQAJ %:i7(g#=ogi?t(lO1c=h$#QUpXH'ZAq1?Dkp*/]=7-$C?a9S'CcaptQVkKkZGJB([U=uIYk %0;O@7ThiRZ)P`QJZY!#Rbj4:,3EQ>3U[Gm4eT%]&`DSjTbC@dPn(%4t*oGXO %rC[!l\8=NeG;m$cs\m.DBD3#W=tQu^)eKT4l7[HX:6l]1>_4l/037pbe_fDOB%_DSMWFh]!G8.IsZ0cHh@Qb#M0Yi5E!(Zfhu\\^#X %%N2@3_])J1FF+L3'nj\3<1U<4&Gk!t[Q)p^*J_XG-EG2aoIQU>>C'10O=D&ReAX< %3&rg#/LU'(K0rtB0@@bf@]-!U0_6uAQ!kQ-CZH:%JXAA#u)rGZ2'cA!*Y:^cQ5eXA33N$-^/jt1nV=TLegOA.A)+usp]+"Z6bmLIW(uu'n(0n:$*nSiPVW`IH@)NAGU8J2R&^8+XTh:ga/XQg0YD--2IObNqitR+aUPV<1Y8db>3/3=eMF@!U+i%L;8q[E]SVBF5baIZWA]hl=FO`9h5[0t-q$Tb#A;0>\1k,Afq`6d0b %K:0Y=)2NEl_Do!^;3Jj0WA3'`JN3Q;>"EW)F9=;6L[c!#g;1"qR,V4sj.p`AKT`Rq!EX]%5A%1KE@?adRK37;0s1h6E[G\^T>Nnq %=G.1K0gV2FeI3E1k\_ee"mU-mIEEf>'r[e%8GU.q$PWa[*$Aq;6imAS(5![HK,oMuSZGHXZWu;Cj7&MSl,tE?jcU3[E+3CU$Lm]9+MrOCcE'9O;@6Q(Ob,L19c^<<% %`?A9`1\lB*;+QGSG3;2QM6KY4Ka+\;+[ZFY:j/X:)L#N=Ht=B8cXFJHba1Pp,6B-Wf' %i6.PQpc?8O]&G?_KRdkrj>$A/oar0KXJ,K>60nmU$UPO&*/KoG\;_q&#AO&ib<';lTK!+0 %A]&#&'am&@pL.bP1L$./NgqRV)T^<`Z^#2.N_N:fDQ(p5buo!:ZbV;Vj/j"ASe1P$;iK2f,ktnPp%&U+?gt/3GZbO>=%,JQO>LqF %Bn,Kuk#XY!%=E6Nn!sKWEeiQ,h$%hjFLE!,mB2Kgd,sckBKm,7,+Ir#ND_embK3&Q1eNSN^gO31F?3CZCL*M;s %eK2$D*0`BP%GJqBUB35*lp>(3ldBsG%h"OqN7D6_=c0/!U;aUsM#I/lIN?5b-$5oRZK%#*^H8'CZHK14PRH9T$$Lt2?Q1*eXd[i+9j9jh/Vq(sdXjP6*;M.G( %2pR.B?3AM\>^*BpX3b'.p;_*#@LE1fd*89De\LG4)-:(%!5\s1kn,/VDi>E\.eqYi\6r:"Ft=DQ\q/XZoeM.n]@*BAEQ=+G9F.20 %m.1mO^\63\*UX-#5-L!RF`D]`XObE^kHlZXI(9ej@*&cgLa;#2nKrKH!)u))m;0TCeXGj&Ca@PkFV7.PT''K"PVr?UX#G/47^*]1ZUR3d*_:hI*8M=3^VGcR"4t-jaYF#QEK0^(SFsso>[c3Cj11nc>7^D25$Dk_T].E1\ab%d8Dpin %H,qr-^a[S1*>Kg4*7K4ccs,oPFA-oA!53n-cjAgYN[,(](6PHRGBTg'`/iJ$L_2*LUrD'tZOLPo4+>Bh4nD4LW"K`>;gG1u'#n$lG_'IYBTSTbSVg7RJ3>cl9'f %$$c?!2^Dt7h2Tf'l:E@-Vl&e$]Wq.eX6goKL8@Z/]3=hWn_)n`^>pk92Vl3q$jTpApIL@VKY:D;-@e%4amFdK\aDf\k4KN!c;RR- %@V3b,bKgF9bX\-g+<%/`kofjTm2;#99b=`M2i!kt`H!Iq@,ipeflW/uNZ5Ni%BqO^)N1D&kK2T%cGPV5C]+TM=(edK%V5X`a!ADoFWtiD)jD6`ufs7nj:3BLjaj0"r[C^^pV?kOEF\LcRj=c7B#HM%lnZ=R=#\=uqfLslOB,,<\%NF]rBZ5BZDKT7em97;p>'ZCdY96J%FZ'[#*NT(&T2[2t% %DLbb\;-=1@AcWu)eDGD.=/4F_*J*:e:1n0 %b7%EP4!l5lDSV`SHi`*M;HZHQS?].)i0Yq0U2g:E%62T,)BLl`,_NF(j?P\Y(B@^^AOk`hYMcW.ASL4Y5o:>=A;2io'Np_Y841,l[_eG_ %fa'0gZd(,?<-]mN'IAaeU0(NtQUNO:,(t5pad!u9"rP?^0*kKT39#\a1JugnBok$3TF=!7$`n`uTj],G&?%.W]:sU#(7)r*q,/gb%*$s4PYCr3.D8;eA+mJ,=GerQ@kece?+FY5 %^oT=]`I893h:t.Z^,gf"g;\KqS9ROocVI?o?iL$#p&rOH=qWB,6qu&>"0oga7aOiJa=LT36]O;3Tdk:3'=<"81i+u/Is.-\`ChQp %UFoLA`$.s0qn57QK!,I&.hMY3b@U'^+21]!ksnm[d`rPGou$b4FdI8l7Y"m6jqaE-F:-@Z]^ %.Oon!P,EoK,>)HBdKJ7B!(rh3AXfR&e6!6d@?_"WM.Nn'kY+;U/j-gLhoM,Te+"P'`Jiu!aM@-NU`WbaI0`N]>D/(Y/2M"'i]@gp %orU#_#:k9=<>&\lOW1/@8&YYHQaL6=F([p/U]b+nXV_9:K@GG\#R,;MhQ=@&luR"koL3+NeL@]J;bnLe/76('UP6-bq(lFS&eW+Gb=@jUF-j@T*)^IA5!Wu-&/I,s&l57kd:k&Xs+Hu>`1F9k+ %,n3d8i(D+Jed#sP@V'!]=67LA9Z\OqP1?Le-B0PlUe48O3)3EK'R?1p"@2`N&NZZI5d_XLat]AZackfnPUU,uQ/e"NQ(i/PagX"6 %5+alm$7#]D,MZ'T91L,k&fH,%V3>kfP3K(4OqOn,W-KnXD4pO('gG$Z4p.@mBrAK\,sR,-qu`?]O;fr0kpH4,aUecAOjS]E5]84] %#4?BuhWS[/:QX>Xo6i$L'sKBQtqB!C@E^YD-dK')3hDD1[I8@=K?9ak0.CM-l-#JkQIAlL1%$I\9egJj?>&ehHeo;hD2G3A\[ln!,O.g*jJs$"Y3EY)T&tE\E61GoJ8E5hG?trr %$>G2*AAR"4Ba^#`0bQ$cEt3W$BhNag'&VXr+Q(h?jpGgrHd09Xq?c5fV;G5UEjfOOP*DG'V)^'h1 %iC9La(C"0@K)nEd1X/d6+8JN]1T'/##i-PpX%1B-N)fWqAWrgZI96sFZ7mZne6W,O0mNE"si+AG1e,q.?YfsEuo_K %]b.YN0G&i3T6%X-dk4g%@F:hlHhh@& %OWc4gLP+e&nJW,Q[IOS;4;OPZ`#^OZ_&tNEk:f%/%X#A&/TjYl>q$gOP+#&oMEqV!W,O0$hXQ??f?t_Ng!73V(XPqO1UB!:0,gJH %!q>RI]&\)b-I@?NjJ\Rk-^a'aqub^H*:O(_Ag]ojD'4(Rb;IHV(n%=MJtiLu=<-qr3ep22b@FE],n$D.bBO6`Y2N$!BHVO/eBJn; %VJ)g9Rc^VL[a["Xlk`^Qc,SVn^D:q!q!#-:*?nCM^'_41Z;(^o]s?q:Q:rA33G^Z:(8,4."`W^gQ)SiQ"nKPW\oKc:A!dHfu %$`#('b4L[4Z,eC'TO`kP-4F^T0sYg(ohpX#kYU5kR!9X*1C\G9U.ti@Uoe.3f!(2GiK)c9R9oG:b+Y>f`H3"%Nk^C7p5KPL^i:5m %W0#NkigD><-](J]ca\3HK;.&9W/AM_/O#ZuV!"m+.%R@P'8GpD@<5=o:P\EJE+"*%I2r'?#m)^T\0BZ>N?*"nj[^=B!O&",O+nI( %>iZht6M3h'0dAKePE$];A-/rJ[BQL)5f'J'L=R+Df.!ER5V#G,EgheR,&#%Up+*O&2IqSHe>RRJ%S;70>Q6I3g\YR]]91Bqq3C'p($pP9[-s!5WBF=J@`7OF:f%f_Jo>qb!Ff;*%%Jc+t'UI)U4- %K%J[X.>5XuCl1(sHZNjbf50GbP26762fRGF2^^lkH/R3b`mtUBm5lr$@UMYi6!B`$GPgHL:."cF[:]_*kWQrpr_rSD1c#jMBY]T\ %qL['Icg7a&Q2U9_[((JYXOmd?M5';9)&n`)ES6O90L]b:$HOt'F2d<(Y:nk?M7$f3GZ`WMf08p_=(ji.9WOf9T1ap)$B^USc6Ec9 %(Hd`\jrKQ^]^0db].\QWi2Ikl@A#YhfL%9<8JY\gSnH+'H`,_QHj5FN&F^3G-V4g+(nh&*/6WOJ^`G^P?S\*"acbDGC>^UF-/hG: %7o&#%V'ItsR%&VJ%/;R1D,d7a*dg7]N[dHF#[msE/04>ITqZY3i%&?fWCi,<+SoR<'0o,!NcTmCOr"PF7hY1i_O@+t2X?E2.(I;TjZSX;u[c%+Q7YVnfO>30.tL22+^HWteM^#)V[,HZK0U5nqBpqt6=G$a/^re$]?!Q'%ULXGd*f%(9/mh='(G %6*&2&9r`(P1/>W,e;@Is=AY*)j'i2MlraG$o9u=u83l>E`tIa]SmtAIMM1@k,f7#(YYV %iB#?9-f2pH^+ga;)r:fS`Z-aK!0#m(YDMHM%YH#8I11!8#V,uGX@+ujE&HQ0?TFc@[,1D50+ncAVsK&qQ-%WbS)*bVSXBbqU`H5Ksj5:pfLA<,Z?/\:tF45"Ac]%h(O35*Au5'=?O'TV6o(+7okha+!jB`@L$%"V5GE61A<'-?"A"ZT#.e2E3!kdB)54ZI7%g:g(FT %`Af87jN8$OT0KP+@!lAA!r@^!cj9HO=lV,IA(Gtn$o\gpT:_:ZP!B+(koiJ@n%qR11[b6=lr@5 %[+pS$_$5]K^aPk:%+%;POY@92JLI&2(LI0!Oh[Af$phSk^*W5>hkV2sGu/1._!B:_,srI)hdIp,1jC%@rD2P>DdDqI9$cNsppr2C1`1nIg[B#H+($,f[rT_5LW0R7"`7 %_B:'u(82@%d0f[l(a`LUf^[m=rh_p*hg@ndN@%h5]SJsRj%DSu1!l#:$Ep,mjJF95?-]bT31hGprXYPN<@Jbk_F%(\T#j %6R.8;_TgI-KEH+?XSo7]^'-8]`B)p#F*rnS>cgm:fsNQG"aics/1aZO:cf9WBK=Eg17n)1L5'ZF_._lPnIGLq!n$Km'uY>EFF]H^ %L/1ulrKOYe4$NQW9kc-UTVt(/!#i^u9U^e%3G,+>!NWG&[AmnU3\^ZOSnR\57N`_0.Ycdn-n>SK(s1l+_+)(MiU%*>09A:kd3UN) %2=6Hjd5TPXdc%H7MG=mOOWtnZCB.Fga,H\"5d3M+*%BC9oG>Le@TdWJ?'r/lJs,X&m$'RO_];QIn`)TS3KV0KU6b2,fGF3HHSVoM %E>q1T?)5P;Yd6/7SHQ0;!:If67BQC#!?+8lB@(1k@r\T+@e?6OG#iqoI;OGto=:J@:(Wf/o`>-&SkIX+3NPmlJch-h5iIFT=&sp] %7uh`nclj><.=F_kO+*+"Zp:,4+HE8L`/8:3EBX+hKu(EIfKTM>VjRStr+%f''1+NIM1RWFg,d%0XYg4X&N8K_mI=i]Wdlg.IAYqL %]4?=[Yl()TI,o^n-mWI4HEb0EZ6#^kKY;K%:GND+ZR`WaZ%mG#n$o!SWqV"/hY*>S&7&m)96LHi^iXQ44lt65n)[/oS-*(hg5a+:4^\KaReMHpA+92RY=bRb %^fM.@.V'jQSC^2$n9=fsR1a8=Bc&[:mV)O,(nDqI+M'^qoJMBDH %K6@ukDN\DMEHG&l/V)B51(*A']("4*Guu@%=agZXYJE=f\gEsVV67Y< %K@kag$K@c^7k'@D&g4"/7j/`O-tMmAOMXSgiJJKt`fi<$)6G'$`Sc0U#1/QdU!r3q%g9o#&/0fFj)X'Eei)c0G^)j/1\FQa',s[*NcU:mNhhWb47^s1s>CedC7[Jl!UMNh^gKL9#.cOE91M&-@N?odQ %\Rj=TdSKu_oc=N;'%1KS63%2?P#?pAi]q"9$d)'[6PZi9!Qii+$B+7J#b.V4rP7sa+n_-*+DK>WCF@"5b"As\aO-?Y?NX5McklcO %Vo;fs/"mu:lm"2^UU)D+OQ*ci^)1a=7lF20g*,N!bmG/>8Cpf^frc;$1&%2kMI>Kpoh6JNN"f39$$/7<9P9hS"k7LcEbY2O>UIBg3kj%\VI6 %kDdgA,bZpnh:M-FN7g7'j(G];"W8d,AI!sg/GW=A`5#W000R>jcP@H4-Hm373CK8;/aRN8Y2P,-b31%%N8 %q5`4QQuS?R-t@]8hDrucK.hcP#)o7.25=j>J4g+"rh,c %6pWP*Vm)8K-d57J:uFNfC)%tu<1i^h1(0"+jghNRnOU_7)n&0<3.T@KBJi>s%O7r!3to7:&J'@Fh(kB.`O\auIh8'BW;`H9OT/Aa %4IH[T'F%GL2!#sX\)Muj_FtZZVsIjOSKD`88:(=[E#QT2Xt!*[,6-'T"@=('r!+t5_P,V'3)NEjC5#!p%A9XA&/k6So`3ot,CdiQ %7-SD3KP.fN1%_p\JUu%g+mX41*_;5jd7C:rS\_-Mk6ukR0K!'W)Q4-AI0Z.D*t(@@-paW`XKY< %.?bqc!@l4rXpun"$D:(77K^F7p,8>V`hS_%=Ya\#_OE5q"D!rL<'b$0H#56I?^)(/M,f?iK?HnWZNIcN0A>C^9Yh'.?UQ<-p,"o( %4QHc6\.=jDe"G=UY:1&6_A:J<5NdJDA(f$IAeeAJY@PK4;+F4Zsh0((?*H:_p^]5pZWA""s\#7Jh]TTGW5I6=roG<"+4A:pd+(s,9<6D>'E#"[eZW6Z0g!@q--/cp]( %Qn&Vh5rNrf#A97\4huWl(F?I;RdgE<5A=`p5=2=7a**3j]%]'5SM:&cI %F64/JH:JH$m012&)"#/i6R3S-f=b %J_NE]3of4[Q%')A!dMo;Hqaj[BZ0oO,mtrB+aK_J5%e9k;au-uYj(+o6OH5mRfM7Q>rDnM(CVr^[hoEmnFcJdY:39V(eUq2XVgOF %!U1U2fp.GT,UH3d8:d`g(B0\gA/0WEM'5k9QPi>++B+7ZNAr)ZbnRNO_GY5@6B$Qr^h&@Ub(+ua>62WU)D3/6A>fWE@0'"&3HgEf %=hotDgeEpd9M*H5;'Q.-'jCo&WbC:t/I;XJ,r@FYQ1.Y6X>"o;i%bq!8-"%oUH8hXb.sEbb.)mW?VtX,(`_ZmV9ZFMLV'O*c4J56 %D4U6f`u@L1pCa,]N$S$h$V>?\7W[p9QA")`<^J*BDGJW;&TZf`&\rH5?fYF5U'Zo%&n&sbZe0;_$,SuI*C8t7?3Uu4(MLStq+[dk %8U0o*m%c0gjkrRbOXMVPBP'3YGG@,Dig=]8fWYeHTY"EOdQj6=Mk,hKV^RX(7imjYb*mG=94.L]-rVkc9s#35['0MiYY'2'CZdq<[o./o)-i? %lC+64W!C.OT9Q,mohgAJ)C?O_bA%uMs)YW(=#IGJUe4>',Xaq<!95hZk)%1)Llh/K?B[J9PRTO?#f[?1bApJ? %,KlhE/d)M2]QNiBY\'oWJqF+R`WVF.kkk9??HfX864%'5.1$MOED@_OSCALZ.#Rs/i+ZT&Kb]##$qE'<@5H;lVTPot/l:paJWd,V %9XmS&R;_WbrM5+0V\,+:H/Z>b`Kc6:15Q&9CX]'X!>c-C`fTb>+#k1P)0/8N$9eJ,&Dq,p&5V@`6_-M4)+jtfL=#Ob^_(u[(8Dbi %-9Aej;h,N,=Ni8>liX]Y6&%)E@:]<&* %da8:G8I:)FVih''im.rNKiN.7P^S+n./;BK@']:;r;s'ce,iH@1K,u`d0KSkc>d"-m&1-dn1*50BJo^no7nQW)_LWDgIRH %Me@/95:7S8k?.[IA]VEAB]6`=%\?<+7R\gN+<)lRarVWnWZR %bU2hEA]6;kYEFhF3b2)]7O%L*L>X3/Q1H16IFD+&kQR9T0X,'N!fmCN-n#tA\4k:'0o<4fEq6/-$!e^F*RYiU0;0o[PbpiscH$B@ %%\--A7EJL/N]#fU!V<'u.L84X<-7LoNl3(p%gR8VGB9]iXOA"[bK/&1`/&!oHdRZQ^(tQ3ZFim,827HpSpl30$\j$o=eIbhbWop* %"H8pmi.H*:`Br&bL^Jq*^?d>2)M:J7"N$;GJ'+7KMM]Mk$%-\3G(VFR*5gb]0-biO&eN2X[WGJ\4+q,-'`0Nq8qC+fa^#Qn2pJn\q[n=? %=Y/u(+N_$Y1D0?'5l)D'c6cNM5UEhtgVU7I#pf2*-4Q#1@V'.d(l1aR^C$'O@%=p#WoY@5Z:PBai]qY,AL!BCJ5?pV,&;SHr.8I9 %rRb18G[i!;%VRl9'o.jX_D[BrV&C13G=g#+RD>`d&/G^nop*7rC^@mO%F>F/9LA4gD(d`]^u5<#Yn=;h(tFF(J>#8:pbD)8"Q(nY %?nqjUM3f(Y9%2eqXL8fV5/]O;,Z<4kJ\2.LE?L43ZpPc_M70:^Hr7+rTIspIQ^XZn?lfXW&m316$%2OtPJC3HUWFXa&I_Pm?+V#n+JNXNo8-XYg#Qg_[@7UGf1789W]mi/:rN.s-*\n;=l#-1Tp-%Rq %/%'0EY$oj!InR4$4$O:palCY5l$@=\4E'^AoJnq^k-D*CIo2L/7.A!%iE.3O!<+@PhHuW %'L.M38pW@O89(@pZiTW]cpF9gi4aX5[NadIaLOs*alr728>qT#GFp0s/b6Ru-<;7IM?BNTL9LmmAd>&>m69u>2q4A=E%n4"hSm'Z %+Y"+"Tif,N/n9Yg25UkB)aV[REl&JX?HWW9A=.t490R$^+Y1G^!+b^8+PC6!>iY8O8J%'4bYPWr/4\^h>u/C*dr_!kCCq7#/0V?$QRZDEC,CARiqjX9*CEOhgUAHS:(h*Q?]#U" %9\eah7?C2Q;H0=.<^[:;AB\A_$<<5LY0c35"(T+q"j.R1,DrG_j=iS139_/LD^.[m*:f7c#ElX>gs+uu#+M*Ou&jcYq`5a$Gb`W>&Ak4DLX+ZnR %";"FR+pL_6BJLsPPB^J41(QXd"sROhjGb@p'[)8%#]jTg!1:WUM6.hcEWRLteBHhZL)a>);.a(paGkG#V_8k8eN1)J]HkSM+E?l9Ma.NTXd+=2mdf1+L9E=_ulXKGI*ZU8:E>Z8fa#<*lt'"qHKU"5jW&-<0-Q7Es-6raWcCSf$Qi)*?:,\#u@Cd/7XJD%3ohOl'$TPBF %i=J/"5G;-l)%HO8Q@`.n"H%dRAG]#[+d>m%!b!^8&PE?E/IOP`GccN68CFQ+W/t[q6F;E$30O2qAirRQX/$7j_kdbjU#*7=kT@uA %^ireG$$/-NO?H+@E)%"_OqaFECJ1on+M+/H\MtZT=DZU>0-a.R^t+)?!N@M83Zr8J:2#=I5]o=H1Yq#^b?^/Z6osmMpeLXT?7@GaA=E-GX3O&4UC5E+j%c0q@QCH5"V/e_;PYbMDh9Y)e=/<.$:7AMUZ^gVkH4c %#UnjD%dgg*W.<\lVq<5!2N#7W4(@U2eN)#jo;3+M9TSqN%J^d:aCC6#AcY=)K9[b9,FnN>6(fbRJT].*lq*6i2\f*f+E1F%Eh5:@ %`9!Zj^rFk26hi9T(pL8aoFdS#uP)Fjjr'jS)pJLfmq@eiCFFKR9U %#=*sQc6NT'U\G#l&6!KmMZ>XMfo?oT7oiZZ09`_?!]dgLA-kZ(og6YIZQ[G@GnL6b;q4h(k6S(r3C'?\_8*aepp;bY[TfWMZ".MT %^h?%c37\eL'6"@:*`j]BL'2E5^4^b,-H:HWi,$3C'l7Z@dK/#d6M;K5d<0T8PYVrL10)W3tKJ9(:>'W8_ZX$P@K0/*O`+<#B5iMRB/T->IuFd@_WsGL[iA(3j:\LD*#1kiTFSLP)sb[OW6&8#W5,GrJjU=WRIFMQORI!"7W-2`Zlo$L`qa\6ZR?U\CF]&?Wb.E-V".(1r_?S"aAu*&WV9 %gJDC59DO,7LS:d\ORLi]Q37^%6MNm)'S;6Rd1L8)nJ;j+37p<1Z>=BPUJ;4F5XpqSOsLbH&p#dc`+9bu-=VfZ,_cs2"!so9;Dqh; %!a3\:E\*j2&gU?rdV+":7KnR1[[c!C5uF#XW?%H<`a3.OHU('c/0tlQMoT?X7j?eT5UX:%3E?j,!WXhoV8V&/ZXbLN.%leBNd39K %PUo.:6!1h:W?#ql;pp[=^c?lS62OrF?O$]7KBE6;f8u_#+mGI)ktihY2`WSmaZOFTaMM8MFsE %9SQ4c@W]e-0FTBp6BF8oj9qI^7Li'b^>_C1a=4rQCEV>.#+Lbt9hm\LO\\"D>`\b>pcQF:I%Q6tnEsgVqSgF)@O`"tj@PdR,`Mtn %"=!BSGV%(]EDjAlaJ8D63u_-AT6M1uPOKI]=C-Q;.WnXcl2b"!0Ppm=9$!B[7*4^\,-EPodNe=9M$:jYPu[H.bg8%LW<2,.e:9=^ %5VriG\IKqc.'as9H4hk>7%Z'!*eu"NFs*e7'oifK:_5>.N^W:KO@IXYA>6WgP,q=6_Fl+aLBh[.-s()OP)uES)I4$Zi06h,'4auZ %%\GI'Wb:=2fMj=<;^pc.m6q>BL(GoRB=<]>58B#P7hHJ<]?\b3(^A@*Jjr94gPUP-LKr*b4"qPr*AXa=C*#W:;sLGU*g8-T.73q_ %bbmQ^on,EW\qU`QEIjr;h&S"-88:!+dkcbX",9`-?\\ %8ui:c4LpKUSH9u205ML,NAfjj8(cNnURkrHkfSVU26K;L5uDM@)I^P-d*)7Q0)iXurWA;/-7&CGR;?nQ8'"er3'1pW2`Po3Ld$B^ %+qhOA#r@kajU<\,aWYKY/Op`eF[>f*n1kf^NUS]`'F0G5!_eB#_'pr)^h>Ha9U@kh"$s'lNIhh!I+THs`NJE\QkF'>a?i/>Yt-2p %%q5rDeScCA15"G-_LMgnecTG3pBcV/F[V:*92JhkC<_(5`X]s98@6=.>X9\QOM/`mX7i>6;;@NoN]%[^+ekio/d@6-GbIRp6>*": %j0D!+$W-LN)tIN.pGL$Vk-A#giK<-S-")]aTc!cF4+YoHKrP2bfPqI(?Yd`AZK=+b,QcsA&HN%e-">`?[J;),ThGHSXBV>(R1/8O %X"?;979WA`BGLZD/_Fp%@#5%+D+^c$(dSko*,2pVY4W07F7QdB\-4GF.9lBQZ>a7Y2kato#o3Z9J4`bu()D-Nca0#j=Pgd0_+HsL %3N*2lFEhfC]&F&4G[OJe#l?JGD>X(S&dB?V'0Khr$i)f!-mfaD;Zg/T/Ibg=f.%Xe_7$"foh94^%4L/)LcdC'ltCDhJOP$:!Z\QV %eoMGg!ccF,G+D>e5VrV6ctDQa,SCAjT^*C*Xp*($)OSK-"X&*oJS1&XQ9*r=^lSf:21>jSNSsA8/(nItL"dZDj1pn7a68bI_M3mo %D*&m8E3]h+)S44',f9VXCRW1l,0gN8<'rAp#k8[N9FR_@L(*H^ES<'VdL[BI,Vq^86U_3(ZpN'OZtAl`fJB"-;2l0e$@V;BJXNfqu4Z>aC#eb/>PKOAmcN0's?pD&B'R1RY`hOS04G]ZMlN:pMYV-?34rtqq9cC&-t2,FYu&!dRU1XTV>]0PD<"#dYB`b)/f+&LUZeXAT>'8'!`)D,Wi-oL3d.F,^Bn2sFL:cX1LMep+>Ga:XiH!pnLF7*qpEXm$,F!&76n?G.`\KC\3uEkM;CInNK.&^O%;nYUj?Od1]d"`]WZ+gr38*G27)jt$0bQ%m %U5kIPQ9%9e>!h!E>Y(!X:?EL)i(UgE)(6L4ObEkf0%K8nWYV;sQ-a/cq1&l9"r8C*"E-8tV\7']3/iWp$c4ua)$iWfm3+T.cX>=Z %V=!rF>`Sp=-+"tO)Q889XtAC9_m4LiBL+%;E%jTg@9]ld%O'.8Y(8R^i,h*?88'l?2Nbo(Q2B-Q;"c[iQO-((JB%YH!pd]_e2F)P %>N2h4HRT"cF6Xq0IKpie(^`Sa:i-OO"Sb!HOlHP"SHq2g$8^VGPU`[@>)+X7Jb=h^j0>2:3/p7`/Wh/;N_I5:$\P3H*Ce<_6X;R0 %nS9WpA'["R&];JJ\5nb$/A1X$7#oGn6MJ3Io3ii-<9fc_qG7E^##TVg^]l#5mq)qd(TrN*XHj>@(5/oR;E[cd^N^5`U//'=&K0rm %L`tG=o!6C-UCluMCehn.mK;D"-^V2d:lP;oH]bA@Xur\Rro]LU]QU81AP+aKo:T,F2QZt]]<*6DuNMTG!r`t$TNj:`+jVG=Y#AX]-KJV>e7ka<:*NV<7"S-:TMQ]e[;T/H]&qH_l@OE)\9 %h3d,.EYsiDBnKrCJRE"&Bg;\)a\i6SZU6`_5$a+X)?fJ=E7b]@Sjm3CY3TtS5tI6 %#X&L71Bk;u_fk:>(qTp,L;sB2M$h@Bi(Mo,f<0bu>f(/>U*7O'[1TKBY8%P*k)+8rBr*Gi+[sXa#'F%Q(Q(WC9?N_;?N2"TT1r-s[+Cir*MJ>F]/@agG_Jr@CSo %!D@)'\Q!b`7V"6$&17-s67.h`b131=)5J<9jB7AUpK\7XNmcV^:J2nq;:Heac!cMR3@h(-FZ)5qde0F.TOh&MH]!R=!s"#W>a*&K %--k/Koh,%u0Ii6lB\P)$9B)rdE:m/bQF7:SVl?QQ63=t+.@qAX@M(qh'FQieQ_C0/1/EdV>&M.'Va_g)rY1N28Nn1/"%Q*j-r>h( %B0eGV@#kC*Vlc![f>*#Z=b1+STQ+:!OCT'(\A0m&LuoC#Cf8X.$."Q`2+J3AT\"oriXiNm'?T_LHk(96DZl="#X"\4L1Z=c*l9A1 %-++d:72uWCVQa;t>bS7>OD?]d;6aUH-]ejH#Ct96]"D\&CRN/k)%,lKB^%4N'P\I/pk5oj9uWBnF;.6/J0Dc?Qp2g)#g($M5%>VW %$6sg'+U)=I(gNt<0cl#h6dgo)!"R`e3fXNM.,s]m[`sLEoDtVW]U53_ZXUmB*)*TrWdk^r$#OP-UNKjA7:WPfH!Y*(;a;])(pqc8f@bD=+W..1,eAs!S)h!l@B`@(VjkGHCD9s]eDI##N(Tm %mL#-M&QjuQmW7&@9I$2A@#O`t2jUEl_ZVi*96:5/:IY_I+gLu0o.g\H91c]8<`?rK&1Y5:L?)uV)&>j("(Ua*Ru\+l#H]-^k8/)H %.Dg#H)Z%Y[0fKZkJLbP/#QfX"%Ln3c<@gFqN6c!EI3S6E"eRM?KG=e'a-],Tb8>RJOAp3=!WZ4c=r_cf/>#jb,P6Je$gVh"Y%[3) %#V9@+!N^Hlb,,tucThiY),Ek^SmYjB:sL9( %raGN)?nHu!A9aU]/oXc4L(bU23$9'e"Hn4#K7hAZ)5k8;V:_"l"H:/g^Y#U'(lWuU7oooq#r>O9%Y13=+T7Z.\WH=mW![TpiA#R\ %0msm;]Qmc#:r0\P\<8=PH\&O\_b`-Gob^'#"B&PVAG+57GVbt13`I"[c3fjt1e!.?**l&NZ_:VN,!&jqntIPXhpKsY!8WQaBfK^k %(!Sao! %LY,Y==$o%<$-(B#A&Y<^P:I@lTS+sX6kg)j^_!(i5)*DGZ0VB7cYfKP'W*&%``N>\gbH89>SMr)FD_up]=7VH_emW %$lu.lR]FP?i@n5o9GF9/^!*6U'L"Dh*t),!iWrQ"B]?'29,rV:o#dA&&2iO;@VW0h)ZmZS:i[$9]HN_t_`@?3&J>Kq`:PbO-2HRNh=K&GX(U_BA9g#6QeMB5o^9W;b8N_Z5:TKjn[ %"`FSj53gab,0pfX@65)il<=t3D.(?<;\"m&+@!gg6;"9_3RRK/>7Z;c^]l<2-bCCF]T8"d"Jg"cXKJ&!. %asSFP)?r)%`b.(mOlRFm?k78qeO4.M?mHS#S3Xi@r<1_9kn=O3!+`&q0`qhF3]dO?95MfT,89+^3BGI,Yp+ZSGVM@9kJ=PT86@6j %5@N&mV'S6SNjM`t.p*h:q)@CSAbG:SL1\ODRQT5U-(`+cO>OODi(H,i3%sr,>aM9$JZ0 %.fg^LZJSKTcBGajaRF2.'R$7h[HWe#@8Q(mmlJIW!\$FX@@?Ir5buLu7ir@A"n[\+!GHAe?%]a,/p*RX*nKm<(rI"Or.Jq`N6r&F %*lUs2[37+GC)f!i;Ge.UMh0.tg!sUG)Jlj_+;#cRR-EGj93Fi[BKW0J;R^"t@=JI\X*0qb"S)m9(1cn=h6&8_Hli^60Rsh5AWeJ8Z54`_,'R7La1b#d^9:AHq(S9lJ9#JA# %YjL\D@W7BD-o6 %;"g7n-sRFn#7-U"3*=&V3Y7TglHMm)M?*#Z+I7!//XV(pC<:!:0_H@Z3%n+Zgm;+JaKDCW"QcOa[>(VhnkNWtr)%bZ9,FU2WLo)%)hZJ+:Rh=!LL`7OLdH8eD6rpc`Z'8[S%CS\KpQW'fh]oXRRrZcZB]r>q.jB&H %PQ>gI>K6=B1#6:q38?8Q\[+tq^;UY68>4ZhL$[cC=g'S,gE,nK/G`P.90eC]RmKUsK]/U8#,AS%_[2LrM/,oI^DX0_f-t_6\e=N_)-b:CjVr'=L34PmE:T\sc26^)HX%[iKm!kYn:l'8rS@ %3B3P/(,;a1C^;NR'Lp.uYTZ>o'*+aN;;e>AW?+F*]i5]6a]SWGcjl1mVSaYJI+]KAl4b7J7T*;^VF)`e"2>B=7V,3 %=CcqqEi&ts+d(/4_+q(ar;hS20\T2fMrbF]_,:Lh<27ZhN#F/fBY:>ZR<151,52>:6X\.K+''`bd0SA3C'&J+PpX1pTYs"9.&SM% %Vk+dG]_*[6>0JA!TJ$m3m%+P\G\lSqVB-c*OR_8->J;QEdP6HSUh>`J4h:VC,&r^NdpfGI,X8gSp]R4pGiSQ%Nu_mr;ioc0\r5&\ %OA-aY$p[a7U-oDB'`dtk+(qP5K-aC"=%EW16.[LV&$04\8msHN@P^mN9O3\(_YXrqCXB[=*>#/i6GU6EUZpTDIH?]1"Obla,](VX %0he!(Mi3d.!kTt*5f@.@aa>EOr/dqf%c0W,1Ncpmci=fE[!XYr[0=/]k+TWjjFWS/,='3NbAE&Ij4iR!LB.Oh\f4(fJJb0M%G'PZ %&W%Ya73WdI<:eS^$b6%jB!E,/AK%)*B!S*TPR)]I(JTJPVYk`)2l*:p@R^sIc\(gRTG^-&Z6L1"/_U:d4[Z6'&Oh0lr%,"0TjuHbO6Oj!@MiT@ %#%7=5j@'+R!aTFU+sK:j,>3qBjaYY;5l$cY*:&>a,"0XAR$:%I*?5,T.<#M#NbFMQ,tmJkUb3R/N:T?3*t!p\gQEj+5]7*F@N8!E %U&ct;'7aop_I=(ELe=#t\mBs-7Q.buYC%/HN+94ZJ!Wt-!Gr9h5X?MaO@),!M[Xp7&2H1l53joVLu)CBXPKd %#/Q[F821eI`Lb-`OCS?V9=QH_TE>6(:]!`1#U_Acik#oWZ:9[B-r)S]"nsA$b9iKs4d!00?IR=X'1@/o2$%_HV',X@7F1]oj?Gu$ %F(3uIeUjW]"9J(pPCTe2KIq6G+cV$e^^UnF9/1=>Nnc(Q+Y=%iK.EIs4FMma_@,-C"#b?g(/KJ!FN(nC):]ecM&,8Z@PB_FS(e-9 %:=76ASg[\G\@NYF*tdO&J/VdlO:&L$(o8JV3^TD!O"bhd!_-83$eT*MAH4g?AtqfUQ@])EOoV`M"g41`2]4DH%^6$S2`V9i3Sa=E %0ms904cHB$2M0a7U4h$b=L?MPiio$""1QC6Wf>m:OZ`d8,We*M#NNueW5-=Q*Bk9a6Ottr!0Vt-8\mRs;ImIBTB0"O0ufkrS>%I2 %l6ZS4350d.97S:r6t8NdjG-F)aQ#c%faS(G"9U7'#mEnt=;'PF]aEi%J4*I]B2MlcO"FtY657Bf\)j]2X>(:iACZHSc-YXT>2.up %EM4Z"HR@jh;E4s5Ulp1g:ru9c5c.A(+CjA%-=W)fr*ZMd^_J8Gp0\U0E>s+RM-5%RY5EgE1M3H:49kl1M!;Mo&VZpsTXq_mVQMb3 %d@piA[-Hj0e%j=KO73.RbafdUL/+.i&k+I+Z;":*Q%QhHj^g(+U5*dF@[RN*VM,qU>c/Q/>R6hs.6N=;k6@I)P>qg-qMGi0utF\b2G%H1,'aQD8OY)!N"hX)Ka%]P2]+Wo]hC`2CpP$>"Gl/JJ@=Dge^s:D$5h(q,O@A %?neXmjE+^h,@H-)"JQI==25Rt)oQ;i\dG@q;;$:8,;')7,/`EKi*i8eS1J83gPe7*'=):;&t`$eEt!4D+jIn1D[52E/OfuO">Yp4 %M:q*N-#576&<]@>E65L5M[JL5/BJLeA8\\fHhn*U)cMkUA1Bhd\25e-0:9^XZ2b8D^pI3),8%^ncu01_'0<"l(MA*k*'05$S6J[C %_WAd6\-hD20f1"@C`'=N5Gg3t:[\dlaUpmHaB6ha+hJ@!91dN!$u?-$[CL;eij608^M@U!+.!T>.&,;Q4H@7eh%@*Jl^9F_2kPBm %B#Z*@[D<-*-Bg1U)p,VEanB,*CDudh=P\M)(7M;.WQmN_N)'RF@Z/6fBT0Q,*t.,O0eh0$"!)gq<-tGa5N(T8MTnUY$FjYQaMMao %MhpT5/?kh5KBY^^AW;CM>Y_+`0>T(VF^6K.'SKZY6DL]Bb9A/Wg)!))^Sg%PcrTLPd\a27M""7bFc$J^oWE^Qc7q_WrN5Qp<'M^? %Ls.Ehdp"HfR:,,_$2>Z8O!_l1n8,6L"%H^_B5:memqC7C]H5pfO]gOYoeU["D:?R*gH>.e\SenTa8CmYaf5=UG0AE^9hi-9c/SpTl+uH6T`<;Ec9R11-p.9T_'9FZC&K\qdA,]7i4XfUp2+jT$C66m<;q*_K;cp %6T"TC)+40("9KIl'bi'9N$2Kk*sP1ln/_!c:]1O.\hH7c^cHHfLAYh=M7ig"/sdC^+r\k;a)D)"\uYAVi&FR:"71"k@M")[=gp_\`eYdJKu]%3=on[XW=H^AlT/ph/``5&+&N^EqB\3gZ=IW0>Z!JP9UOIC;O[^?7)1*H %@VpP1d3Q(%c6\1hBM2"MdWq/j>3U'fU!)\(O8rZe6F=^>+GAgsi"@rALrh#(N$!\Dj"/+/;3#0P:eU%9DtukeGA;,l3#D$+(1rt6 %1';8Y3)X-B0F4m,rdNU5CJK8Y2WMb&^'Y@:kD/:>!1Y-_4,D.Im>387T$S?>K[C\\fsZXBQ/keFfd+s9F.^ap)"B> %`9e]'!Tm0VA9Npql(l!0dFNh!$*m"`=%"=d9$5Yg2-?R:aAIiSf)eNq6:2Q'4qN06N\sMJ@Sd"(1FNNiTR-mM*1ru>iSnmF8>2EU %a5MbpU?l7*Ohpd=>aX4T1fB@99;s9UVWl5"JP=`.5!sBId2&$DV,pP_jLBLCR1.6KD^X9@.%[(!2;mKLW=D2TE2%3f7$ff[Or.", %Fg;*#CW*(4D=h'&k*/u@`&/4iNW>Jdc&up`i3^*&M]g\=lm-gt>4LA\^'(S?\`pB+;]#os"$^6!L;5U5;Kn\AR3`g[D'eGI29$+P %bUPeYBM3NjfOlKkLo(/%98Bs>C('Q2;DCfk/S7G7VN#h@1XPb:7CmiIHgZPt2Q#t]iW`LtOmS3."F0&?UGn`NnNUujOB%?rT[AThN:l1R*>q4qo %MjnuR%uI#QFsn5bs)Sg&WM`\pQZjEBrnV`Le[=jJRo&b,.sRr[$s/?3N>ficL-r(Cc]mF7("5#lOF4sUm%jWY3oaq2lu3.:nu.8Y %Wl>T($'LXS/jFJ=]gt_$Onec7BGWfDl.+(49,Xf^(qg:V@K7Z,7-oNEmfeQY"(+a=Du,r%<%h!@IlGL"aY-H:idD;aI9OFq,3ltq %NhT8qV;F0u5:!#E7KF[%Z?JXO]43=1:;s<),gBh#ZHu!!V/e*VQ@Mfun19Hu'-fgT73pUpe`"Z]$)/]A.$ktkl<*YtmLLT"q5-lBcM;`J=ZKk&iL$)(r1KQ)dD*L,UZq9d^7.gUQ5&c>aSl:abAY[9%%5`rYM[e.d;'XK_ %,\Rc&$I`Gt'G4hR)'d/!4X.q4-q9.21Id>*H]/l+HU\-YgIplZcj22[9^Om&k8=IXC'cV&:5TgXh"]BejN^E-1^"ae,")%`8Ji>\ %>RsqXEEj(m]o_N@#*RFL@h:O^/b0F'/g8s\=Xb%d-Ur0@r1f!r"o^mb_-1#)TU?M$?617d=]H.nc!56FB?I %%eu)_\i(aaY3Q9@U(Jot)j-iB&=Ys>pBVoP0LXG(jU\,)d5Kuu]d)IF",(Q"4YnAQ)16qtVAYYgfWlZeiHE=<7hVUf+=JA#9$fF# %D$0)3SB(]IkQ"`T_j:r+d+.>!U,OETJYZ[DAD]_LZR!ejg.P"H8DlV0k7N?c9+:kF,Irh&N0q+",+<@;D_dKf:>ZY?I2=t`;9P%9 %d26`=BfA#>/_-$DeKacFE7QOh=3AgXq3#$f9>6fE'_:sp;_6VQAl?dsrO5\5OYXVJV!J\bXZ;3D0RPQ^:K2,Q*;P3D=#b%+T=X,g %r\c/Z(VPEg\RN8-XS$Ab_cE'$Gn=!haNoY"]PQ,E^"DcpT]kn6\^k>eVLMgpbW5<6K.dZS0-'R]"2Z5$]JP;[[8ARdLVNJi"/U2W %%sm7/Tmee7rU!Xh?Z&kYB>no+I(!0qX%>5EQb!oFPKa)@o'7MpRYVI*4;jq[7\3iboDru %f9q#seZ*cTe#J_%\XZ'Q1/X=RO<2Vj@.T-qEp3mk1==1s&U72c!TSiq8B@,3!C]Pa&A8JiN!2]&8,!h9OE%X-i,Ar;R#+fj%KiSJ %E&,A()j[/q6M4cNEQj"?>E'b!JB#CG&0^9DE-T0;@gTG:=;PZq,B5)ELhE'#5'1nFOsUgKZf.a:!LC5d4qCVZX,86[+QK8R@14Vl %Ik6a+!B31m5U:HBfF/tOE?uFQd9,uEeL.5:EN%qOAAoHd>o!de&@<>549iBsT$J]G/BmKl!-sW`>bW[0X(o.Ad;+Q.P9;bS7CW)A %2e]8mb!X:hTbn#KA!*jJQ*;QU)'[6@D:lbs`"[mF7@19p)_EQUr?fTJ8=+B$SQjN*@CoC,/p/'F$lgUrpcJOG!:Y7dAHE\k$,R&R %PTNW8,QVu:LquGX(k/n9`%+L"C^>M*C8I:;a93(O^4n^Z3(-:Z[sSD.`>AV"$=^.Q_fJ.T?NMr<"BQ6:>H#msZt6aNLjNcn5HKGK %Eb)PrO_?$7;LJZ]8g>#?+k-gp,"Ou[paYd7fUTV[AE"+2kCR`]SKSD`V&fs/aPjS6D!'iSa#p"[nkF=:8A?%&;=J$@i!8qCqPEilj,"a8e+3SLT1]f4p %Ra$p^I$=.W!D1`uH-Zi)D6sTlR6SjOcl32Y%&L)_=pT-cki,RK$\@Mu=!9kQ)!E\?e;7-:OTEm3nJ3-.65Xiu;oOfh`F\4fc!XtW,iQ0C6'!(1 %35K8S&FOGH5!u.Rem.QH])%\shLY:>Y"g[%J@neM0tRL-*risQ.XR%3+mK1A4ima54^nJW$,Y:;@,MCqSr"=r'I_-^D5^Mg3eF<` %Nc7LC%RUq[G*rC^VW:Z,d6\DtOKCqT[:"aNJjRD(QVl^XfCX/s(KGh&gD;M]lkSS9g*D^#T7CSg+l+H))r4:R+^Fi%#"tSbNYYu+ %=KR.O!2D/[1I`/`,_1Pgpd6i[6(5]0=H)n&H]6:'V+\uXmVS-Z&uU[#>(jAAOC2hal=b):d3l<7BHI:V^*QqB_nD=,T,>N!*dWdn:GWlUqifVKcjI>p$,3oY\:%ctRp:;l;hP_igt#TLZHoAE8]WbtJ;?c,Q'ioN %VS^MJU7j*j77?&oQ7lB+ng[QLIpsXCFSYb'j:WW)-AbP-8_^9C0JK!HNW"ufX*E1ol^^&j3@"YRW$:uNjZ!,tMPJaGqj %F^6KQ><,VH*.:C54i1DWkNa+ng7&%r1hh*;U0`6GUMndY5?E@3.)_X;_68tB-F<+/u[NU06BQ$K35IbS:H3B%U4_Ru]r!,6J %lm6[>)3bqGf0UB].&&]4?F2!EMYd[Q/$kTYcOe/]U/!Deo(;Mli@d[/\ZfV%a:?5nbm!O'H6,]40nrG^k\El4Le,!RlL?RFX@NnF %FlJ5@OuH6!i(q>OGa+d>9aVFLbr(qT+DUPhBX.XRQ,.L8A[-''H&8_tD2*^#VHH'b2NeM:GU`"f+Gp073s\E,GNM.;lTpR-8HoFN+`OE %FHVG\,ae]4=>\l2JpfI-TU'S6C2Ae/lEdhLi'Ab"59G8i^E/=PjkR`[%9B^uT%*)AC(j`(9-W$2\Mf*kl\KHjRe3],npI5i0eV27\#'PO?8`.ZIUImE$P`(12bc;_j&Of4PlQ;W`n53DGW3Ul]q %iKJl="fee98BESC!&p;c&@<#h$oHi!%Q+PC3Y\5+Jnt#f^.pB*V',Uj_+T@B`R&`WW?a`B;GIBeiJ;MBO`g`VVB',N'?B9\0bVb\ %h?u$6>XrlsW]C[-3D0Em0h1UE"U-,]>/&WbJa!7XRG+FF[?'Pb5\#S[tfs,GK^&)3B8>!J9, %XRkg%BNMGOE&%Ape1O,lL?sT/;A=A7!BYt/2?HB91P0%d^m)[,"?/'P3._aq$9/)[E&5>A7/3&NcQ-UOH.?uGION4CndVCZVLX3* %IE(UJ`^@Yj9Xkehj+5ST53E#n!MaXDGl]OK&V94Ud/]5%cghBpTDMp]2A"">P7rq<]>8s5Jd=8d8c'RH)V@rZ*fQ\F`eP^A.E4,0 %iL\NW1V:gb*.oeAQVbhq3Ec!=RQhaMISfjY#.PcX0m+U=(p4`\Z%$"Q_1e[(;m8.g %"IX=EZlVTPJnGiDJml$H:MQV-=&&r&?YU_F82.st_aqV9b2l<)%NHoq:\B[%cb[]u)EP4B=(00r%:@_<4b2u+Y\cer`#)rZl:bD/ %K"1lQ-s'f^W9,)6`Y%*^@5+>qQJL*Gbp>Vt48%RB32VmXh-X %WP4on+3br`=>5ET7mZAGU'b<1mLrK\U0T)Z9I;&rE,%1n_lu/.MTSO6Oit:gN!`>Y%Zkn&9W7EEJKR*Dkt\rC2)m"Ze3^]Lf2*NU %gX5dp5Bp7-!Z:lWNPWlJ'uLbP<<-If/?TN;j;SH2&CD[H0WAH8Z*]c*XQ88`LY;dkgdCl;[]iqc_a1BF+CE05hR67COA7tDg,)p7 %;1+FO`pY!)Y]"_D,t_E75c`N<]50c^_Mic^J+P>*OTAu*7Rc+UV(s:VGmCsUYUPMA^o`;sp]`CR;BnmKfhdlI%"I@ZZ7-%sTITF2 %%0pK3P%$T57tFAqRkRat$okC72F9dR5CkoDQ`l/W5ZCDu_Ogng`e1J-X7(nJSf:FE?qV9?n7b>LQYC>9[LAJI2O1Y3]<'R8F`kSZogs,,X]('Pb'mFg^IhF?mcG&Hhd3A#D\cB.aE_!"_NWdC^rqREO %9L#&la>fO`PdHlu(C_KjN_lG5LImaZCd#$A7BIq;Uh#:2=d>^kGVBV/t$nr-_=*&5fq6O6E&-V'[)JNS2FN1m+9%Q9 %Vu-JZ>+D,?^TPW)+T@ZRGB^A8a"2iF3oFK\%QC'C#o=UYo]V&RWZGG+6^0`[`t3Ah?nqp#^(I,Tgu6J9;#:C4GsLnp+,6_CJe^&6 %r6_W(7/`;k"r+ibUUnXp7Q#/'W>qcRaq&th3M[*?6p6bVrj%,(O=C>^UAXL>PXOeGLmf_Vr+/<:`*Dcfj\8FL*;QN%h\.%\22Yi- %UtgH`.?q-%-W;I*HOhNi,#(e+6WBIZ+jki@RMe\XA#P,PhH(;8@>045*`K1?& %;%F)DV%5<:_'d_Rgi!2t>b^Q$0LoAtFm8%T,qe?>b %$^YNsW@aLi:NsH)7mW6]bf-J"re*.Zs#1A_&,sNqIb\W:d`\E1NN]eK+"sCl%=,)OO1a%=IBp!SOUmKNF6E"gWJ7a6YB;WXZQ]>J %5Pn>Aa7)t??^UNAN(oLPrWDW^;j6RKIsu@"n+$Si47?oh_FJR$b8DaS6u>opN3f%:Ipf.>1H8Z4-.%p\rp&!m(f?h#N#\*s%3LlW %P^0`j9(L?YYUnh#_>J),4Gr$r!>E?k3MET;Pj50GaPQG7O$;2bj.u-(@&7sN&)dJ\A?#m2/^Wcjq*AiYN+' %V4SWm%Nnq3$&/KFBJ)s\FqOW+0`8_;7,T/VO!!3r+oS//n5944UXko;IaMp1dDA,4oSN^QdK[Wqn!:N+iin2uq>`K8p7ZlE=0KPKdr&0(lMV" %YWp\)\DD/>Y86iaf^BIMJ3h0)$FM)FraDqW<[)N`r>6FZ?riBKQabJQ336D9rY2t51UeR0`qL1G>]=(i-e6:DZIZ&\L6.a*u_.cKMa'Wr[Tt_5cD,&9Fg@rX)paIqe>!jpn %H_!Y%48fK1gbdGs@ZWo=.`C`!^?G7QBq=a,I;/@9'CO[*".k#D %O"']]@ct=o$)Yc#Rh&`<1ER[>T68b5pb"N=*2L@K`S.?f\l[Ya=K$]?s%3 %&c>^'mn[$a%ThLFI[uaJ-i;o8&\`^rIE!p8kOVABGc %0Ql5JjG.5LoB)^@U4]F^2FT%KB1)5598$I]D@f=N.9.reD59CT?;gjic&cHRF?nGpj_L>NGBT %aue+LRd0X^X^(\6lM"lj2HIDaIOgUGImG'0=:@M%=c;O>#QOB&$,L!<5kJe %Qm5&D^qo$HJ:JK(%XU>j$`a)!Fo:,t[esERr4if-8e8Pe%%sOVmUd+?D,5o-l5Lo;%MVd/'L;^BDilo]<'@s/V'E^TEqH?qCt::b`#H4L"r`D&HH&pSUX@O*Cia?cTQ9eb8HPiQZ(Gri`NmHW-jAO"1%`<8!n$QQsFAOh2GE2r"!^1-3mWoSr$Ba66oUaY>; %Wo[$ar*P$b:UU,"Q9Wpjmnuk6INd>2<6`2$PrF2dQ(P)PUI$c6:Al9ao9BUN1[+XY_/B6(A\g54e&lK$]Oh,#.e$5LEL-KkEKEc& %7qsK%Pa,$\JGOKCL\5#YO)F&O%;;eHX0mB\(,@`^rhMTTmhuriUn/ZS!QJ%4L1OM$4>B!3["bTJeF0N1:5stBTWq>\@KcJ1*7$<$ %bks2Tcj]Af,QI`I6?C8;=pKOXlel^-H`*1GWI8H5A\m1YCYa)#Br[#eh8We0:>1?U#:P#1f$0[/[(Kn),Tq/U,\dB,ss[cO,["o0G`16Msu\ %VSc+7BgHGWF3/I:/jJEW$JX?!gfiORWglMp:UDL]4.rkCeuWBCK9LYd[>[CZA7IK4kIM>hD/hbj:JO5TIro_co4\$"k-Y$17[ %@EM8Hf1XVm",HPdq#./jJ,bYglG&L)GEkF_3NQLC_!:K6.dR'ZZL72AB"Z[.H/(!\H5GsdF+=ke?Uia)A'[oiHh:;0jiN-q?bNTg %-9M'(rE*nqR2MC9+Bg_K6G$1"ob&%FDS'9Df?T8]bAJp);mZG)pAF9M5=dpLWm,s9lE,\^^")KR&'UF+e*7F8> %.rc0e][7WV@HQI8Y[40RNPDOBlf,N^IAKrehWrIbm8.G(g8:Kj8IDS!<`^YbXs^/rhT9r%_C`XIpnbt^V^_t:B%e8%+^ %;*QnmPh,IlSa(Z?0XJ=Wn8,F2c#rpY\fO[QTU`]3[gp!LFhMpcbn<$D;nMlk$*[%ka$C]8A'aYjh"sJ3CJSXLn@]oP/`-25daX\; %$Kd3!@"3fl:78YFgrnaVQ^\lI0\jlfGj`nG1_CcbQE]MX@H$D7(03EU0dcJGi$n/8qMD\86XCQ!6O.m"&+[9Y"N4qbk%0>1&:]gF %gf7]$?Whg7%2X3nC^C4;Ti>F]^p;o,DdBms"#g\cl0*Kc]\S*Ur]_60jgkZ6.b2]?.s8!/WHP6Nm7@c:S]h+>Wqg\9Kg1jP8F+gE %Dq(9Qc)tXg^3@app%tH:H07-jp^NWr[gR]5(t>ME,8gA*4OM,kjef$LVdd2DSs_`GQG:saJ\P[7*r^W#\,-f>AA`k$c-6.>Cp_^< %=f'DelfU3Tdf39F28o(#e&<@"+)=leW]-s6>)V**plt[`s4./+WR7njO'96'DrkkT2&6uADu-Tk\<43bmu:uc<`s1W,O$NRqF,%p %7Fp/H-DgekVE2iC8B]!Pp:JW9Xf<;<3Pi2(c#H_K^Vl2CrVPTVmqDOsk"M.PB4@V(YF!QS[7N:UXfM:K*V>V8'-D@1qB,0>pq4aD %YMX6s\")fWgP7;m15LX'kG][al$!!Fc\3:\:Geu]TDEu!`VodCF'a(4Z9n;oDu"IK %NV["3M\Un<:1-,lIE`l,.OI12qF03/^\oY2$Ii-[_/3P%+sbQ%@L`4.YhK?i5",nK@n0)GJ$3e_%uqItT.quh4.1;0IV %9t+$DK)sq+ptma,R2JA@NR(_AgqBf^Ps>>XKALckP,07Jk!,/GG7HO?9'pN&4R,b_^\FP[W/YYapss]U?X?Gss8(C8nF`[6W:q[N %:j(7eG4CRHQs6\.6okTDZuOGPZHX1r4`R5C_O[Wcos\9(WK\ZjI2N6PnP(18`pI+92!FR^IU46C\#335WEjNX&SX?;5J( %@ZBnddoeGlN7a?G\a@g>UEL\`P?PF#bMMD,C3k%GTp*$(BiQRj^6O$X_``>NEXul&BUdC",548fJ25IqH:"9D+:R4OI"bBW_06Q>(iLFZ\M]lj]!1bfK]olFjWP[[&oY7mH0lX59VE %LYR'?frOeK15@h>I)%Lm2>,me,^GI;rjpX_>cUZG>^"j\*OZ=nM9bj6qAn*oI.rq5WA&su\Xg%[R?d6@hg.0/dnAu:Y3j6_QFm+e %G.CgWP6e=';gmiRUeNKKh?U/IQ32kq;/NF;\$n9oO`%cT1Yb#nh9ntJ`.;`[A$n$IS(2i"HsVj:Ij6uSAk'D!(&,B*A9Q.ubFA'6 %/T];,aO3)R+d?Zd_/Xikb!]jNp8up(,Puqnr+g!Y_U\`GST;-,g4@LhmlE2sn=Y@_RZ>q%^?tCAqk/)^7@!lE63;4hm,%=(bUMKkZe$K4I373--,^abDu8rO%@#?)J.L>E";q/F*)JPd;Dq6WK$[IC,frDg<#b*m=>PVg)W$l\D&=L2W\gT(;m/;sr"2EQ^_pYf4?D+X8SK9_+:1hV"[UG5-eaEB3tk\Y%QM %:tgKF*H1P\[jJ+QW+NO>_*71@uP5Cu*Jda*Z\lhU)-Y&48QYAeS?C^$!hNf.hk$hZXEZZ3uA5O+I`8niP,EQoQM)[5LeX-%=NureihP[#\drhp!?klo<7f77M8q27;;(jSlI=*Md2CeD>kY9FjGS-A]P6&8H@PLF,m32@kfpSHEUhH4gG: %m^%c1-uS%#cP8=,Gd=:DO3SM(Fo-::Z:0IQ/4[/*jj%H/HKcCZ5l9PMl)%N\B,JsI#b:F,#FY=2#>4ZA+F*S1`1.@NW7Pr=o"VO_J.?*,tf'+^d8]rb(f:"0VH*K?2K^.rkY7Im:0@Tnu'm'kXNiJ,YQQJG(3n6KgW>7-!REONeP6/+WXM"u=# %Z`@'3JZ8Rq5$(\9X'`ADD?&N4HG,n8. %0N3aTLtn54GbI*\jGlZ`Rrg0n,6i(kJ[_Wk2ThSeWsRO/)a-)i'"&M-=iML%Ce*Y8>/W-ieH5CeZ&[]ME2CJG3&FXu()V$B4DX"C %46efT>8Q[2RWW+c::E&Ko@A2tgD_r68OaV$at@FAt?a3=0oQR!.P,);Sf3g?g34W]=n8Z'kAjHG.^EXu)K`&QiA?0q\jI?it'K<"'cG+"L?);Uc7n>T.?mJ^1\Q9GlC"07g9,ug))2(KC&fSeN %iDrS[C$>Kuim;P$^O(8'je1>s`=TpT8[h$F'^=r7G%3-CC=Hrs^5ps/fV[*^NLNMiVI+7T-f@P@hNN?F0l<#AhKD8.Kc:L@1,5lK %Opl3V]/c4]ZA1697c]jR_91%8EGTHT-oRI^@?4l_NVXKs:c2p1 %.V$C!CsX-ml.DYT1Qd]dH>`Z&-*DXEWf1EffVmS?M'$\1X4t.cin;_^S9qqk[$5i74'0RE\Z_C\LUj0=qZe5*1Z,92arg-NR(tmZ %"&Ni"O/oaa^fC*kK%V@r%5WVX]LcD>`^mN9Gi2JZR\YNB#&GSQIqKdI*GdL*88OH@rEI>/Jnc##r9'd472WV-)`2XIeYB$>tJdn>"IN]NHc-0P0A@[(+nrB\n*&JhJY=k2lIe)]9t`9J\[To %'ME(PQn:_#l)T%/o=,&"g9#P[WnVFBMX<7p@,O$K\hY.0eUZ5+ci*=GjWQU*BW3/9@G+,n^:X:YagPn;/F='FW2?^PC)6cd3c^l!kg8VZ@d=q %/gB-XWF=e*Wo6HGhFq3?!(j6;UPR3oja+D;/_nCOJ?diN3ptRg0Ha5U7i5@Vc/6Gs %V;j)F!&Ei!)5Yho==)/_`'O+;%eBuT?c8<]=fQRVa.sEDk!B+$JVK)j8h/3tT\/Fs.n"mLmq7BKKDI5f,WV8/,X_Y]Y=rMBP %aGs4?=1\(MX[enAS(qj8eS8XT,GdQ%Z`3$Z6hm*ANe\O3Rapss=',6Lp`U\5/:9i;0qOBb>P'XuO;-I*f&jSQH;J]M#@-o]Y?g.2 %\aCB2Em8T`keq3">FX<$QWU11s]CfH=MP>;AVa>Vf1`M]5](VB[3@)WtP8)lErkK"Yf10pEQH\2oR$^)j'RS\"40: %[j4&:`d[1I!9`kg!IStZ*Z0)fNr%j<023<+m/(>!Y/lYY#/*U0]MS#m!,oP/ %rYUU+aQ#tXf#rI)`r2Ue\6W+/[)b1W:cg^B@(9cs %S;*7Loh`i[jEVD2KiN&c"Xn'/O1!+bGlQ'qrC?;mf%rN;]NTcr\77bWcfR0t>Ks46bLX@td_3W1a+\hbWV=bdrI!(@Yd3eFCOONS %[^,ehn_Qb0VW*q#XhA,nFIWSjd49Yp?7m-,2c`-p4kWqAm.<2^0&FY,Of5?c.C>l;7=;0`#M<2eV8=[1SbE4&lKPcs''l3j't]3"W:do\7"h>5%8/+l\"eU1m#g#Hmm %iPSB-pZU"+)#sNRlHYYX1[D07I,)fN.Z^&,:\RnVrT8m5Fl-Qo?.c]*A_UJ"?86S`Q/YR-6qs0N\E:Q2NTs-LYZt5pC[O?Vb:_B: %%KE(m?ZFoL;DG.ZV"V<3C %.c"[<:@F$g[,JMcTB$j\tU1c-s)NlBdj0E$b1-cIA'JGbZI,-??+$[trkHA6p4YND/kDl_qrS56,b$OMgZIS7'r/[`de2,X! %Rr:MU]?sPF]/Hog5@$dM"c]AHF'5`rG4FR*Z\n@R\h25]X?Tg86Rr:&ccg9uR0tBfkNu#YUYEJ.mB#ZfH%mg`\Fm#&(@TB)6G=Ih %8l'$h_rL>@o0`ro?-UTr/j-h8.hs"8hUlgLe:2Kp"5:$>@pbSf\b&#?*/:lLgnW/B %iQ=60[s;km4Xnsnh*n)^n8qY@KVh+4`pQmqCraKM[[-ksJs6%?WOVoG0@SUP"V$L+2IGP=5NVW3Ko;M;0OL>O98.-P'Ue-G2;$&1 %]Vf\B^:jO6ds(WN`t+c=`\93L7T%nnDI(T>e>loX!Jdq>Mj66g_9o.7\MoX/Wh!n_JEoZ5*]3O%u?G2nt?!B!@5Nq@qCbE/' %>,=aGb$2:92rSB1qWfAO!?R=lR2GOjpQ'M5H[PZLGM)+AM77h3I]h>\A&ggHHErc^EI--'R>nIjq>G-ifRL88f_p,4-E`:TO,=aa %a.Eug^gX3a2Lk0&5==tr<_XS`pH8+!Y],>D:lBppYCR`Qb;Mm=_U5)=]78%[>&q"6("X^=m)>+W=JX^t/>Rk5[bBC@mNct#l@A7uI+U4-)`)SM++Tsqi7P$Mnf_6a$S*@/2>mRrj.R9VoDA<$2#[8DIIC_268@s_2W&jiY*D)]\9t!gaqpVuKonG\H-n*YR-+(cm+1OSR@4e5 %cATdk2m6iF8n\+_-QB,+_7bQIPIJm".a(#7M%_VC+KZs/gSp_PM?/Pel3^jRWFfb@'UBP\n$*N(k226LVYntg];;$GrGW#7JE-qe %TRnjR)mjetIl"]]i=oW]qs),WP!?#/%U2H,F%?2rk2sPKnm(b;7VO*;m>+Y[3$0SVoRcK)a'WobL&:tm0J$Ke',.,t:lrPW?Q'S9 %r7/sU_jpa8kHMJFII_Yc#4GJ,QYGU3Q4.GI1U>Gd#'J %c*%;6[r(I1qshhU86'>82QdHW3tsl<2!h]^rDN1/S$PH[Mmp?Fd@@mLo'I)hc,ofph`n3N@;smj5%68?W:;V-9'p0Wm!$l/]I2DS %Y[4udc9J'?]X$-R.m\%PET(Zk['3eBJ%EL4Q(4b*/on)&rDG(BKG>SeYJJ%rS::-/qZ.NEG%o:ok)9a[PZ%$bSb@>N!"PSZP\(NL %s%2H>2ULs)p7e3DW4Gh%I't(3[ncl0V2fItL:-.0V7V.uDuN*r8YJ;U.Bi^JWd+&[@8$.T;ULr:DUJhZ9bm)HO;QTI[7AiDcBVc5 %o^U%UdUqh-ZS`[["((r6`J;Y*"2D.RPCI_ZTt]Wqq2uKjS($'GX-Z=(V;cl&IY]n/qiTiEhjbc*]._GkOcGs?3EYaQe[cHt529@F %=Pl/$PF_Ad8Zgq!Mu<8)JeIG]/tt/6!g]-Jq.o<\^$#]<#V];Zc%Z7ca@hofGEK:#Bm`;)IFiBa8a0gak]W7u/Nc*DJ!Cfiq\uRh %:@B_+n`jGdn,;%hjPhV!R[f8a&La.H_VnoBeKk>(F.f$bQW#b9aE[?F8T#E@83d=#XZXIjrh %1>(Ui>(3R-h:Uu:n"*hDI&_!K3dX@d&c5bj1Y?;li!$em]j@eSitjk1KklY(WXLQRG#j(p>/Nhh8m:eX;j(Z;rSEo-80#8'giH!qn;*X-b89n %%60)NG&ZqdEuWqOG`t3K>lM62rtJ_:'n>gCX\2@#U$Lq,ZJ%%F:R$D#iH=C$okHMc;JZ5H;_@S%]oB5A.^eIF=K@orE8J-117t0i %1/0@*P/iS)Ia+2@g>RGE-hD_0gPWShpF?[JAN&FZ)Ad/'>efm]=8#EK<]d!8phALnej["=K3.Ff,9('TQ"p!ilX5p#fqK(mHX&&M %]^+?mZ#&PA_1TP-(;JEZ8l;+.W;!N\Y/o#7UFRRiD+3pIomU"X1?[gTu %9&;D1i:t^;UXIhJ7n;kA(-ZP`qU2R?%ZR^A1pADpO*4B#G9n]A-'NOAH))g,4?>/m<\?.AGsO8D"akOec>k>+<%O!jd% %(@r0PbUn6n[p3jd<9hM94+?V1NAfRH4(.ARTBk2AP`"r_N4N+GK6o7Eo;;ilgl#+;)LL_t(GDi.C,9+Rq^g7^V5[%0/;GZ %k:8K7;RQ7N)",8ap6Xc-\C2jt5H2t`]:Z]NV-Kd<+3gLYrM!=7>^7hQ$d0WL04(_3PGi*,3m*aHc&9-\9()2_/EiQ``VGR]]r.^^ %HJY.Y\AdiU@s3D&1_/ZugjD3e?Fj*`Z$jB[\7P42XY&BLSaaYJ1#mr/H[_9JR3I*9oThO;2=*nl>DGc(luo8?lNCB$k1EuK7#ESHDk2g44sj842q!l.uB`U_F-LTT73O+H"< %f/KtSrS>ml[JCgQ;%u;<--43b`a3Y!s(X-oCY-8=G3R-HU8PpPB3(uE)\$mIY1CJ4$+o-.S_*BbNLM&^=f'ZfqiLqEYfGbTG,KX` %RX;:S`YTNelDkF+i.jeike(t&g7m]b^W\Y*#@Cr'd`1n(=#lPnrISs5A$;0reQ;VQ\YGYGf&28AG)P,"H;@gNq5,'=_^g/lRghk\ %!;e9^LMFj&Wk/dr0=T":6.fMHCnA,.B5_L.r92DGc1:&bqt]BkUY#`%HRpLl4F?m)X`Q_g[nh,^4*Ld6$5^k(R9IPl:VJ<@Hi'Yp %aN-Q[F%_B%#aFF#+YYj2Y^?QMYk2o:o#2LW@;6Ec6U1gpeJ$aW"hRmp)V"$b0Fa'2Ub@5;^ %5o'+L@d_d11Nc&cRV&'1n(dPpmIsh#WUmp_U'-_'n]K$Nk;T6`T<'C+0j?`gho3(QdonrTro'Br4Nn_qn($OhG-6)[W:Rgj^Z[m6 %SMc_!'5sk">.dh8d %./*1>fipJoIl-E=n8,%fX67f%BDmnEd`1>$ERG`fiB\Us,DsFP=$0?GQD %`QTmE+:D9>f=mPk#905!^"uIFBc?WVY@`#]X;&h/`@(??MSEbAei)DkCi=([,W7Y\-iU%IG>gLo*)&[(,ZII_-Trr!DrTfZGE;b^0$(;JiD7:VDdm-JqZDkH#5-Al2KmbXFA=KjGjWIRF4-s9#Fu\Q?2Fu %XV;5)HElXRWuJ)]?g%C=p9@cuGko`bqYj?%@p(ikr8OBLcV)qsR1%7s\s2@BO1Ss!UP'55b-uOI,pZ %ra28NM>\(YcMM[01rKM]gYhMWoLbK2%FXVCUukd^7=\C0>gH*d)ms^9\Q02YHPjmi1YuT:n%n"\<7;5AQE'^DI_WTEds,5HVgo+6 %48o-3_KV:1Y\*a$9FWDf;>4.GfcDc,XM'=3n[55ROSl[g7'!..=1RRU/1^em)37[sZIG]MIZHq^A9Er/QrB`>>FcPK8<;+[BJiF>)aR#a!A/p`NWb"CR1rduJ\,(6+U[7I[`[uiJ)\50:Y+[AO=/$Yh0TVRA+ihIs/n#R''iSO %AVqdGepd&'a%1l0fkoo;c$:A-a5b'/CYXd-cRCpKR3_*^G<^GF)o.[7GMG*?g_4FT]mX/RV)G8*3:>Q-H#6[$TR;at)I![I4RW,A %D_)+;on;XKN$3hr]<.#r#p:I>`qBEJ?lE1 %mGb%Ro?/1]R12b'?i+EX6$F3L>qd33ecNb':o2UMD,0$Kh[PcboR\c1/8?GK-hNU%#/(@t%"$-WD\(^HTY;P^Qg#5#GP-F?akpF` %TSL_&b&t4.r$H#>kbrl@2Q/9"L(u>>_Z1S*AC1>N;5@FYK3f8c!e8)Rghb>/@$E7+5uCi=XgNPnr6ffOK6!+Jro*UrL"W-78B6k+ %FE=X$(_fH%G?$,g/-md0G3ZQs6]47b*NIa@?^n3?]/VeZIN@4pIAXVKQ(kSmb<\LJ\+HNmTL]!6nRQaLK7b4ZKDL0,JSW68adg$QB9blIE(BH-jFG=)hZFGA4('?f:HnF^\B`Xl[;hi[[h=9F!`<)h1s"Rf7WUAIO4..*Adg&ZVEB9[!aD`#^B] %KBUg,d/)55U#hp`&*:,KZ,gNm^!BQbTpB@UBJhKE^\(o$dm7oQo[#9?)+>G:VK>Z2[MlM>h2^-p`LnT@gW/Gt`cTSi8T,-8dV>m[ %:RPqG@aG@?ln/2lj"r5>\jonbM#OQD)98c,X %17gAl3?7ZnnR;&nkq[2pH(=gq_4\YrERW.jQ%D5DP7?q$O^Zq,Rqd(SXb$?Uhn(8%-G-AO %V;:Oi[!%oO35anSK[CG:-Gm_mcYSgb'A;ra9msO5HG*[GJ*K..5IWmIBbV %mj$dM,d8'Arf2EC`+>jj>C8Z+MKJ,9@K,ZYY!7?f/CZ5bSK:g,cN4dNXbdQeTfUa&I=>f-F@CGc8>g&CMf1,L=38Btbjb#T^0KI@ %OmpJ@#JX%dCFX(3^6d"_?PRa&](^oC`OA?G?goste4a(oTA=;NN'FT`hj1$53MGtNrp>!.pj!if,NN&BMHsK%InlRBqrU[]Zp&ul %aT5oAmEaZDp,*Bjhp-MKh78u$cc]+.p?q,!^&79HhlWmf9tp#'^f*;NN[BYGh[`m,`Td*X_#2qgWq.;.4P_po2V>+EgkPbD-fu*^ %O,ooJCq:Alj7hg"DjftVAM*e3h_$@OETZLuipVQkg:+%YjCk?JJm)lA#9K(n^VrcJpK8I=-V>L$G'XiOHjl*u+*)NUXf[B'.W.Z@b\l" %klXFVE"q&:r0aU+j/T=J@<]*Z?TA&OSJHOVFRe;L\/-=9X'uP%i-;E+o9jpsCBk4sS%^!Y3ke5FYX(;'K%Nmt(&.,lAse)'fhVe( %&;e=]M7[\l`*G(mf-?[nFGPFb"*=1o>l5$S[,as,&4$..e([L>>[%>%DpjTfJJ]7V]ao0>/fN`%`G8"-9#_0l\B9Q/$GAPhFnL_/:7G854gHRas\R%-HY-%!s]Q(!tW++lP %C3=/a(($`MLQ0==cFOKHUIqr0h.hguKBAu9_Spq;ohIuI;63U(.@Q)#*BNG%2lm9ALI:?s/I6@)9fQmU#-oun2M=jeKe=Pi77O"`S%`gZrm;#)ZQ'iDu:9f7TXPi5u.R3A+WUeMSc]!&=[4#6@U^N_baXb(U4oCGaq1`=>okOli2!cB3rq/0Vt>X*b8P%aUJ$;*7r2Z^jQU4?EL`:Y)_>6S>A*P)7oL`#njh*Va+F_rP34XJ]^o/o&+\ %AtU]e_R3'5c>5OGNYCb[.P3)g>cCJ&]%dQ=Su4V0?Z>]1K'kS70KFD1F!eWt=ll;92Tma"C@F6n--Prb4VsM1c<:b8p"-+E4G,@8E1a1N4j[R]T&5"'A1OP/4BNl1X' %ftNn,P2/."<*dEqQMm?/2U:+l903egqD!nGD.6_dBM2f8"p3A*%:TOMdOpb>FbbP):C\(hN\qV^Ysg!`(WT\kRX1g>gI;]s4VBo; %m5:"Z\/]?hH,?f"AP[P^S;ue'$`?+.nr&L`d!;V\0RBSZm),;tofPGVOZ00oGr*HrQ %g+=V[A]13$ll7Pgg,Soq^qq-"`Tj+Vgj"_;`ZALGK;t:6V1nYGNR>Jg^"[Vg&r?1s*lT=Ia64 %-TCo':H1@;>;DRXS@g&-eh%M.E5g3KFluE\P(df\dp!u/c?OY7+\oZpD+P2>ik&7*A]62p@%dDP[p2@Is)LNrHqM!*"\u'\nq7nY %#1q/g1gq,iQ@*ZC.4oeK(-X_'bVC,Smt5Bs\DA<+IIP:>:%SoWmIUNq_2#9LZ8l$+gur4LYt[22XG0oHg3+B\UBr\=KJ5P,ESrb8 %8rm&FEN(J]"mspQ*.P0.O?*-TaqJX?Wgc#lA:7&Z]W8a>`To-9#q,1!:KDXIB5@FZa!Q %.BS*Pg1o90[m`N,_8'4?If7m/?_dphq'OAetb35*DV?7'dp%F-0HguA'"d- %QH._"Z!?O6U=*YM\/+Df.g?YQh+^U;s`M#@Kc+^$DZ]qk(\X/)K-i!BBgaoU]D)=g4X@XtlPP<%K2`E,QUrObnc7eb@l5n3W %-!6U!CCr0]j@62XV:,bqE(TFc=J(.OZ1/ctba@htm@%I@j[sqe=$g`4dYEA78f+gQ/,6D5>#U*@ns7?Td7n)8L%XQfbNJbL=Jg6BbJTtLJAi)&ki0`)bid^0Blg="+8u]-MKrIk3+.$.[oirj^i>qf=5(!H48Y9q[T/a/+0`8Up@.0kWh3,!<1FiMWrK#gY6< %/ee+B0T#P4VXq*j)(@d0[Sk?b\<,MrTS4MR.o8)Hfq*3LiKo+KQLk`T>m2:h4j=H'`ifTV/B9dbGL9NlUWH?miM$uQCm:<.S_)eD%%A@YWg")'1a(r5D8Oh/+Yr-P][D,:mHn27I^4S= %&"&r8):DN//8iCH?-NR/"B#Ohg7R^lQ6Aura_c*e6mk.=TDk@fn.P.dkAXS#)K3::h-ZFl]mic;mu"UIoYE@g/W:d4T8jld005F_ %3,@XYKp*!lI_+5^mP-.[?8Lp)(A%'"n[oG#>T@:..'p%CjTXQn %o%4pC.pe`NC[/eM3]dZ'[P`<-'s:UhVinUf[T3oK$(['_SAC5L.r`2nH[D^)o9IcgtarW %S1b^?mD[u4kllOWrStm``J\P<2s;60BgdH[hQ)ED>qPJn/Ub=<1]AD5H2+h?(Z)73kWN%+c@c2Sq=Ln#Ok[i6C?<*i@R9E+s1GYD %$0Rtfh+\6CPV@=\`;c*B_uKeX8S3G'C5H`^*,'AV\PD?0f;&]*^PH.[=*#>J18:E5X9JL:aWu=69#B'ntnm]s&_XZ3oZsX\a/cD*rXm %LCTI3BR7kD(rpZ.N5Y=")-%=Ya.>Znotb[GG40FCl#X.Oeg3+/%YT_k)nA@/+=pmK0'CU:(*hI0H"oPS>3LhOg*b,>!)DbHtXDcL#3lU:+qSGkl/&2qA %WrXT4%5YOn"adU.Z*WoHm*HX=\U*ngdG7T&e?QcQ*8E>[IkIP#Jqft&[b"3SG&8$lSD"9-GiK`1ge9Kd-Fb<;+B(f*42!qe4qi^s %D!e:387sH$?`m2]A0WYAI/48aMs2g)i9d5]ss$?2Sfe,LqKhQa*96#IPqrh,AXF(>.3PI:.uYJc/?HsB)-6tIPJ_UL%AfT8G1JHDU%>Qb\23/MJ:GLfTiUkkgZTG %q#:XufOC\s4No5U?I$5.RgN8,4A&M"$fuKK$][-Fp>skbf*jCpokU?DB^PN1@XBWW691I6O-'15!2brj+ITn<\243%5)W3/>I!B1`>i>;XO' %l?i6#1!LZUj@ifK'uLMuJDtYoXt/u-!i$Ob=BlY]YKJhJ*H=6Q3KA?H[76C\.rhu:nl377=-sUE;E]P."n&qrh:W\&=u+/h:6ERqgq1Y@1s!J?"58,+mmO,$_*qI@T=R$Wu`#T=bq1Xnrg["BWe= %Xp^fVF,WgqNAKE"fK[\1&tJKTGJ#Q5*2,B_eoKd2QZ=(3'Q\^D#Jn8\9:2AJU_S*ERG+\1t30u$\;NV-HM3puH95r>cL?cV/$'a!Ih/@D-I %be_tfCL?8`cfQL8+>(:,N.I[Y!T*`4/Hf4bCpAXGc]MF+DsnbmBO5V-rS?kWNYaX_Oe&p4BldTF-3J5="84CA3"[k1af?ru>1qtB %2X:ukF^:JQ.ik'dm*V4-2Y=KD>rF[iW20fTc>HYe"7f`4:/#U^liNu['hI!4G`W=eWAQUtRe4W[WOHshT95QfVtS(qSH.Z.SYdLN %g$@o,Dg3Si_Ca"d^"$1!3k-OWk7or>Lo#@R5qT">7pFV1l-C0Qn'RploSUc!g)5enYu]W&MJd3/YY*bp0YG\._9S/8S"bMZ0YneS %lP3C'B?5C'<3U^[rAplbF0Eo*<3TNebM($`92mTSJre/5N!H<>j5KUD5Z#:/QsfSM]\]?6bqQu7hY-7V'teJ^[U647_.K'BS%&@! %M$c/1S1j(`.bG.CljJ-!$9#d)X1Rg@.bLgQTBE.\1JI9n`AU-gRpgp9.CK^9fTK^8U4UWD_0QXC)cX&pA)tnRSt^h]0YtJrf;N'j %hr@lV-$b.N2QL%ef,o).MI?aG<0sQA'o5hM:r-b2@,jCOS"kQo34!RT$8u+fi=3==TRtEB_7!I;[8=\OAFl46_OI6NbpI(($+Up' %GY,&1%tC`4+]kCi>ua4oN=%QgS)n>cP-)ki3%!D&;c1$f@eVr0;p68nfKH[qGfmA\]8>q$;LBP!S(KnP8G:#TG8&_@MbS)`=R4e] %p/<`1rH6skCl^1)pnh(^fO?d"=M&bjgZP@(V`^H]S(R]CA[Q`eN%T:Gg=2\^4%:$u`tk.G6TMsa)g\mI0WaY]M_916/RIV"T=QM$ %LY1TH-bDV[]8%de^Kk_7]%B0SGh(R1bg=>+SZTE6_`bT`4gs"kmb=Cmf>NQX6l3JU(7R`ac%M/p<:-2U@Jdm`-?VfG_Tn7(SpuMt&@?/\9St(G4\'`V@DT`9SJ>]JA+%#tA(FQ8Y:ZJPh`p`J@FKaO6G`PYF0kF,[C\SG8ru %j[G^7EijpP(hK2k:-?HC)t3+!;ZE4pPa?CLX5A$e*i&)e^-3LA/LQ$an*@<@o3>^pc)V,_`]@l=EMfZkO0HnJdb40XF),0Sf?RX3 %_E+m;n9T_0etA3GHGRc$3W=d(onm %FVaBf1<2GfHYKa9@^M>Xi^R$_blI(e.dJtCH1SYtS7%mF",p4_rsJ(.RJjG<1&,HUK7]`1d3c<>_[3,rl@cAUQS^VW$Ir!BX\ %5JoN8l/[>GFk-h3HdC5s=QcNeUjmu=[XJ%6B38fKMT=FHhAkitN%DWX3iA:35s[R/JnA+tpUFi2K\d'dljJ,lCR.Jq6K\,rhVaji %;9_aie2;6jp8DRT7c"R*Cl`<8:A+hBCl`>>Gse_b>dM'E.o`i.kRF]J*n@pu:>tkcc1\)JS$t)`_DU)m9.]slhVaji;9]<&Xc7,) %J'8`$#1m[PC0'6/]IC#:*nBTbH@p"A7l@&rnH.;rCnK%8h^Q2uY1XlH]QAeoR^hK;C>d^Z2;:32)M3;l>k>g)QVbpW %lB<7KRdKElFZH:XE6\+3AjC==NGCGCg`4uQSrtJ2B!2aWp:+`34Z2cLf>9E"OKHYgf]$6PME*-("F?qC(/a7)_8FEua+?gH>m5-s %]7:'N<5JEr>m7D]]3nteXA_;8._?6tlVV4p_5#.*Sm8P(]*Jbsq($^71I_03(Xnj^f=TFgFK0XWDgeuG(B+n.?!U#3Vj1Pj %N]:(:@(Je5@P!EuV:>g8R'V!1hF6M#73:@LSjYH`!T7/mmj>UJL`;_"ni0^"nPl+:`/S"N'6-FX!#g$l+n?jN:4 %EJD*SXZNl(SgJaBd>WUQF\3sd!k_55LfL#>fCLO"aL1CAb)MgPSa3Opb"4k`-qKi)N445:M+Co519j>PS*ir&)+:_qbCsqhfgc!I6UT>9,='u',_6r*gTV307pQ2KCa&O[-'u+-@DVhs>h$`Kik;S&rp>_h.aG@%,K/D=!/=9rR/FQ@=;(2s5Fj>n( %NSM$68)m=GlbC?j.6?2!I2c"mmb"@"d[^q*n^&-Y6TRm>;c49:0"[dA=T(+^JAUAr00tR4Yr_:?p][`"bE]7:9?NkoBncDBc6AZCe4DEms-KiolAo %:1I#lj,I!q#J %/RbUQ\jn*%HN'reVaf6gb[P^foD;o9ptN=,@quXTRhI;Sl#OGOhHS3CW3B@]FH>i5O^HtXnkrhe'9ON$B)@0jkAQX)GrnG=3iM)A %CDk%?'Q\E/_<2qW$Mg4Tp$A9un..pHo_g8t-o_-#,$!sgl`sTjWDgM\@"TuF6c'")]nACm[9hrm^K2-;CTXW_\cdmhm49!SV-4f&Rh(mbgRuItVfl+S45G3-s)fW;IY&;u+JQW"&Wa:5Y2-3*_n9NIHdU`>;]!l?"e//O!6K5b6r_ %h!`h-%/WkN"-rlKK^kCXI]T#K9#q5.Q0^;2lnG'Hb3Jklh>HRe6>%3Le!\eL$d,T:hYT?dXh*.f+BBe; %q"e9B.ioG6RIU'>aeir:mBAhMS)F4<,ZXL*%I5l9PH:DF++>TDYeG)qeoF]7%oJ%=&PEk86CKBI3b><*SR#1E7/!4PhV\"*o=[_c %WZQt?Wr@+'V/AJD0@Xk&pRSmtdXTd6k\Q#hT(MSQkOPZ?Ff+[EolM,LV4RFaK@KM?A&K0'O"Xt9nKcQq`foBLl$/MahG43Jlt`,n %9#pbqi2TP6fD`ImiDiJUq9Nub5pd33L'C_1gUfpikBD;Mgh"!nMpQN..;h)iqQ]ugnLBd'*=W.IX<2Gc#JCd=X#Ka5%q89"4-;_n %4FZJ>_IBiD-tYoB %rPLf(>u2mtWn:u#WD[,K24fWKQUtk'322eUf5"eB*bgo[-6g6]o""^-Ii!BQ-u\QVUD2SV6Vb>m4Fm:d)5b@Y$P[/dg@tA1RS/P^Ppj[NgYO(Jj/Bb %%J!E@oDEOpp%\J8pWbq`aYQH7=h^:c:Z$g&*tQ,>j5OE+pO;"l*=a"F9d"$,"'6UV0<[heC#GW>_ob`d%pe!GMA[+O6H/lclZ8c7 %LMrE3#'Mq43>:\3Qp5bhIUoX?iSsGh#ghM %f)HJ+YFX_5@jc;8da*.*j&7pf/t+T&/h!Te)p/"\C"Ijr2S([B"B$"&q9$f$VsXHeP7aRbO5.e9';N"l*N"mN]h%9u=Im6PXZ[d3 %[0N]Z&lsLf(W`4s#6"lC'2A2!Wuq=fH3Dt_JPi^[Ti)KR;PAY9_a09qOr(Z.7krQc#O+kX%9=DF/f+F-"L:$1d:^5if>^nmG4oiI %?^\bRq\;:#_Cdm;nd;;Imu$::*7GAeSOVZ(oQ]1au/C^a=58=L'a]nAKif!/t14(rb]Eu2&Z%bcqeccq;Q;! %aSei"2+)spf)kfM)pllXt"@bDR?egdi#@+PR>4kH-$5 %BW?>s?N7ms'UmE#2p9cmkJt=t=g-2i5L=G1Wrs%m%oV(D41e'+T$4'QNAetncVBt?O5j2;f&In4?g5K)oEl;akC3+drjJ0(lG$A> %??P4%Ge#?[]punYKMJPO?]ARbd1>D(-:]nLrH'DfQ=j94&q[GpFng*ik/b90g"6d((/d*H7>P:Z%.gZUiIKJ]Z==c/De( %#q2jY*$o/0\$c*&iqBuf;YS"bZm>4$JAO%0UbYrGOB#^]drO&;>1);.(o6>$([fXO+^s#Y;b)\uXYZr98Xi %&+*L=9^q^CrcU$%!(Z\ZY7MErE>Z(V5n_Vg*>'FM03k24^'hbR=#oqA\_9Rr7:4mZh<.W8%+t/o1%X6"Z1j+"4C[q7RH^k=Ecf.n %@gA]3oT&PBS\03CprTM='E$k6+8m-aiYV)=_nPo@kH2%>mk6ALI6$aEemP[&K>(,0K927[`5#7Dqa!isjN"3Ra="7;ZKId-90Wtf %-\mS$[eIN.]CJ64F"'gYa:1T/n!NRQ=o'd75/LR^l^=\6/UdC%U#4ZE9T$Q^W6+XK^3BBpJVIfnRF&1`Z!]cUJ&$td9b^_Z6Gfa3ud#5XI$Mto`!M[fbg.t+NGjq0$O)I[smAa^'ro3NJ.\4-JMtE^Ln1N\8e8@GFZ(GbA %j%-"G3H/8]UYQ/d0!r3>B>h0ANur9heKL(m1)-*7/sn<"e%NuoM15ei-3VD,9ZN:XrWaS^nY7eRD9:I5h?hr&1R3AXX>CF8akg'!NQB);]K>VmIRLC$<.tG/"PmR<_OLQ#gra;aOX: %W<+q`^g*MSuD"@mHR/'@J&+_T7+Xb#3mE0>nS\30p(@M#$C-4\[1`,>'AfP`u0376"STa]VJ%]-H['.8[jC0Q7ZDZH%8Q1@Wb=Mh(8kS]b %QGu"8f&\m8BJNr7Hg9a-Y@(H]?ugX*'[V$%ZWf?Kan?@S>`9PIc,P %SSI2f6-4::\^sep-hf5u[R!&Mp5&mKI'J+m!(u54*IX:cl?WC-C%42DjGIA;L_O=G^eae$J\>S<5M61Yr+naYRf`NB>j>!e&Ha"b1:CQ1LZ %Pttb+5!39!Kkp1";`_1QdP7Lk$+"S'-:P4'm\^2n&!KUi:MQDZ<,Cd:b\5`[a].g7?.17_IS)"A/gf\+8m*nq`)iCF?CJ:`V[(s* %h&3'm'O.),\@6PXAMU6T*C$ZpOtZ$6;@]Uh2b_=0oSfF9FtBQPP:rS>n%WSaA5WSL;uqjM4lWB6jciTZGTh;);poE-FH\2"XU=2g %\\?5)/4KrXD-4oFWaUS62;9s0]9dF'Fd!WkpQH=*57$Z(rF;_5GPI9]odZ,gPN#BtZ$HrqFH %*h2WtRt^N40>_:pKC>n'DZ53qX>E#PIq"0lZ7dRBH<.,7WhXR6[_$48SM:ihg2Y87HBu-6*ag&/S>jX_s6u[ha]*_,EkcD3<;VIL %bB&Z>?nID,lKVeg_c6G'?"9mG4f7SL,u\dg[S54,@k)`s\Z?^cPpHic'XA_ %f>:s3VE2it%F(8tNfJ.EJYa,Aq0pQ]f$m[mHA_(',u]f4/X_JGkNb9(VOD=f.QMnd]Y<.o_pH!L@O#*`l*gB)=D1_*c:J7V)gTO4M7Btn(Hh7Q]@*^;S@gIQIEh-O'KN;h5Z?A%.?kVh;tZcr@4Er%0Gt*]"mOMQr5V), %@4@!`#ZI!0j&'Th>%+GY%U&+sg&:#[pJ%%_p=GP.g@#\JVXh'Mb:`rj)<1Vg^"5ORZIB9(p&3(,6J6cg9P#/B=R.C^GZWS0.Ds3H8dS+"(X5t1hPT4P0mab-F]P'=[b:#e0&AnacZaqrhhQ%>b_3-e5qlFlTRS*;A5/XnGZ %5EpYr=mN&,MJ)U)Y^323]oP*\.K`<]3-e5qHL9JQ.Dj2u7]L'Hb'5\)[IgGg7]L'H9$P2T)6*=`gjoQgaqn;1;K_;&@9,[+WgVal %[cP]>RCKOaa]q7prVrOn8D0eZ)E'b3a0W=&U">q=q:!fV>E"_ekB,\3260+3CI:DZHVtl!?Q4kbk!aEkI;Pq/UZt\Qg\>6+SI&_2q8lu9eO"t_%Hm_#?dH'p9/[B1' %Qs$,4Gj"miNlL[YSUsmO=[RaOiiqa1?^t.i/YD5G_GOGirH*Em@`i=0GTeL3^OMJp(02aq>B(DWES#u25B,Cn1Um(ml2&989"hHdA5aQ[Y %;l$"J<"P1Lb0V$ic+dQR)VX/op%N.G;#a,R$Y"SQ^]^REYnU!P,Eln@&ZRL\N8BS+oe?MBlG?dP"(VZ+NP8ZkCkR%'jhnfh)-q/q6pIFb$)co6S.G=Tnc-\m&Kd"K8i %DDs8oEr=Z_gT,Vej;1Xo\(ao97OX,^\SCg!07/tZmrHXtbrsI0RRt_PMgd^2ERV&Oc]3_o`<_n!m/'5bTD^`25=\)&Q+ru5_8!i[ %1'Nj29j[uM+*7mIKpd(,du?>K)B>f\>iqCdU-fd_D-"m)mTZ^$7c%^ZS5uN-`M`2"9X`n.03Z'Ns.k#d`R.m6,LK^#f %P%1`b.A+.g'H7=]P<_#*h"cP41R+>$iGaBMR"So*h^6K%WP9N4auo*'U8*XQF@DXo`:?b]?6%gA[tX@i*L4Ai[N!3Gb]."Ggei%T %)Cl'aEA*>ef>\B7Y*gDs+%0Uj"=r;c&b$#>@eM^GFc^gN]sq,jWpKa'r+@NUAGVf8?qlNJD=+qm@s"I0:0G %HutWUk3t&r<1p*Pl0-l+MXZuIL=khP-srqnKan>2iW;^.]t%o2NFkl7ikX %R_'YlJWTS]+d(lBW,qAeefib=Ok@'S*QE8F<#7E6nH39/%!33#3LG(if1>qG?RL.[/Kk1gC[@d)$#`Od9hl1dm2_Ttci&#`9Xe!N?7bd1i %q<4&:IN]?8"_F&\q9uhOKL<^ts'ZrYFMO8Nh&Y]b*\_1C2Z=\7j'(.RE_G+_,dtjE&$g8i+:e.2g%hqp\@3/K7QgG7geC%6(FrHK#(Z+>BMrP)`S[.>,5-6J,XAa96@/9=r/C74D>\$>:o+99.Y`d[d" %WF-2Ee:d)e4T%`%bMUmJkagK]f>OO/IbnjlJNn!WcSt#,[*qBupaP\GC'TeFMSZG64Z%J+El?IP`;`46bu-5=IrS^Gm)7bM'RL+o %(.4n8f@^lGAE>@ld&JB_;>_WF9oXX%d;1qernP-oZqo#EUJ\P54QtW"+cZRgNs_QbB[EPW03M@5f46 %R!VV.7L!(Q4GMGVjuAdPh!?(GP96K"gr*jNZJWJf,PUminZ*NX,p&1Y*PF"5r).TeNaM8DVg=m>VUfoF+]0YB#:H(dnGRB'9gd.>GknuW2j'G)dO?u:M0`LB %rCW,D5Mu:CaC>Y\krqJK?+>R@%4Y]W!,C7rSSiVd4o]4XE!*nf0Y/q2D?/!'WVH58$1S2iZgQA?]c3VNRBdZ[Go_A0Jn>%NfAW&7 %C+TWt?ADlC(sj+MGo_?r$Z_R80X&AIO;F)\bj4aknbEUpR+L:5Q;]C@?s\UqMS/0A9HkZ%IX)#I+Ah,qh %TPD&*3(1k##aGQgDEF3<[`?KE\OMX$J/uNoPbXH=rX/:"oV:=E-\j+*;Of7MILI_1hfNo.rT]$@*qNJEStn6='lq;NrJejOgf"FoaArr*3q.\WgS<>PhNSN2_BmpqpDGme[Y>p-'Q0YJEgM1N#L/HMUs0+D;jG.^KkBOVU6`TJ[)We=[ %ee_R1)F\S6(7^dm>D#BD\$\Mt15K0^s(#2MjomBU]m].t(7aV4jsJI>IfM2N/B.$J?fuZ1k\\/(=gbXW=#sb>3\!j@+Iomjf!,%P %l`Jd<[_@(95r_RuH%k?aVhAEdqc6D`Cr93^$Y/;SG6dEAKlj4!;]/\0\!G9X+gu\hJ`rOXK2YT,.E"4e(bdEo;jFoRoA%'VT(7YShs2%coA5;s&f84%a_NY3n&lUcr-o2mrq`p?UhU2o?T1m-g>!)- %^C+k<7q]\FVB0E!Ta)P4H'G?A/F)?caGI67aej]B9t]n:_id_!"e-&JDd'I2TO?4bgpgnD6,=o!.;`1ml(DDtD<6KuRgoc`nOfqn %9/[e)Cr5UY>-dCc?k[e%b7.*&*>E=QQXXc3ZK\#i'6NfB-(>AO2LWE$9/[e)Ck>F=Zt.WOmA)DFEQP)16#g6i/D5,A %YR.VMC!!6)Jk]Tkj-!+A"e35#8iF#tMql,n;1D07GOU_Y4R6#0KpYk/H9jVCQk@6tmkS>i\8>L+$V*Bg%_60ud:ihB6n?iMF;Cnu %&+c^tj4hQ1Oh)Y<"4j5S4'4[eVh:ma\%-Rms8Q7-DIEdni;WAI2WZLl]CWMRk-W<\mp?F8 %i(MB%_TfOCH1aU8)I=ArVlsdu\G;RdbO=8E4EfVtFu:V#]>8Sj[6q.6oF_-!Ja0]($dNrHUQdSn$blg39%q)#1Mf,*Xo;qiT?eUb %+.7msd":YqPuccbf6g=NZJXEO7HqG:Iuo=]UjoaI&bY&(@k7gk-'"G2'>EDm"*IYH&8f'$k[qiYddMsphgZ=8`dHmJIH>p-m-IO\ %=67C28bKIkN@D-fZFl^.7?E`58bijI]2*/;WUTeZ#FkO@6"m5.VR$m6J:G]OhEHChh>\OTIIrj'577CFIhU6Gc%oR4cbfu/>H9no %R/D,cNbh_3Fa?*iN2QK4rq'^qgE$=g])H7:D+N.":J/!q$$LUQh%];u[:KcJTe:d.Er7gt);PI>?O& %_%*Ys?stL8kI(L:%`X.SqB7GT-t5i$k9Tu/Pi.3HBP//_fP:9d/tNUXH:t'oP"9h6AJfNi*\q21W'8_i%rV'E/Ht%`YZ*0 %Ql;GbC^Kk?6Z5QC1!T2l[lC0+d__:q`Y0%ZD[Cf]jXFVrVPn`+U3W729dMc4J4VI\L`@R46=?Gm6:iL)%nUbA@\=C-%1P+GcP"4$ %>7qHp^cW:75nl!2B24'9j(A[c&3_n?L`bja7D?c#0#@nH,4VH2RMT*("iF.CnpnYNj>.%:`su6cLH.qG6(hq^JjeW[`&LQA$()qK %SYbHHK5H/DGQtTB*ee)lp^P-\GnFX<13&V6F`E8J.#8<"%$18cCBEc$O6(aG(RGukjEX\S-cL@fKDh8u_'Bm)-q3_IoZ-K*"!O<5 %$+PV]@G01V$dZj^?l-4MUU:Z=rVE?Z:^BER1No#f31/h#iJ:?9-EnY8i1K(:cfg+^j6D&k9sF?E%/"81-3[q(a$TK?O&kQ?&7G(UEYXtTt9)4H>W__Vu>(<$:ib]CiW0F*/oKp:_%>m!V\$`h:&PU;W1_G?C?#:R%o %+WGAF!s4FEM^"2m8TBmO(mNQ=6A1A-\cNDC"st$Dp^M0q8.DL68lc-e"X["7csHjgTgbakd#nWZ:2mM]R;Y?B5n+s!LI@PW5XIm" %;FU_]7)]@oP\Alcm":G"XYs$rJV>H;K1g_OnXtCL?6fW21b>'84_"c.6&93E5L7DCM5GhDS-7h:a]ae'KfDGNe>`tf8"fBS:B)7E %$=j4rCfWgK"'S<]gat05F*cm;H-f+O%jKFerrb4komdJ[&"KCQi'SLN\gZim_nm0^Ugl]$"k(2[3eF%c1-&0LP,*Q0c9J@__A;5F %6PE>b'^RK4$j.E6L493j,b+j0?_UYg8392D$8W6A#Eof687*KlR#pK#0us`q!g%EO"sb3;.8XC*Da6cg!dNCucj\,6Lr6"Y:kT+# %#AXAj!p#@hK#],'JN5`dM"2E`"s_:'UU2/;-%RI:Z7&hY"<*ed.P#PX8s5%SU+1.*GG'LI%OD<+.WM\F$.LU:$6mb,3'..U(X/%/ %!.fbs80D7OCP+AK'EM5N:_VfR8ed]q?tY$(Pq<_IDF$U>_*@^UMg.<8!r;!NAfna,GcQknFFde\?p]e+@DOUmN>EEW-n`?D'^];3l9(!^2@qnd81^?kaL,0b7lSr!&*+;8&\Pb.T?0M`quI]c1ErJ>rZq"tZ-6 %Nqca6BMG3[=O8Y(Eg.^Zh%MJC/9k&`0_B".EEVX0^sAZ!5k=(I0IpN=ZK:]8,_4'8ha&>@&eA!<"LNd,+selaPU&nQg;&gWVZMXZ %/?BIra"_6Nd#1-s`.C>:.'c'jdp^oL%5NKL%V1-#TjnQH$]ebM?6AG=%V?6S,!Nq6C'."p7*EKH9d70s.,mK#4oli;2!;,NRRKRIr!PU, %Yq2"\(n(N/T3H7ECbJ9jX3#qL5sGSk$]"rFT]g2oL<+uXN(h*^=p,I'f7K%/JSl[UImFu\lBJXu1GF%2@Ud<%(1d__%Lg7Me!pE] %KhmQh2MsnU71#MfE575bNIK\D*tP0aMg:10]>UaDHmO`6j>-"MmkSAKB4JGpRjRs9Gi["2o]:rs!a$a<6FYB:cl9aTko %ggHDh5TOpe*5kjOM0B>3cClmaW!E:,!gn*?bU(R^#SeTcN&ko$llJ?cKErPk:*DV1"r'.>ZQLEZ`rrskqU3".\W.oI7WQ#U`9cP"<&W(Bq6]J[&:3ffHBV16QUM/^-*smp6I)8oDZIN]aMPac;Q0CU%*Z>6,X-+([DBP8#U21i"uU(_?@S,m_=n1,D>DF).2=SZr57USGh%6t/YQ^+h/d11C64>.?d)bVN#3M(?4K!f.)q2qKR\,_]oi(8OOB1W1O]-,`o;&iHN1m4"&7n-%*,`W()JlN^S85s'V6_M%Fa8kp#m8I"gOROI!39274J=sbJ %MG91e"<(EV?tmLS3&JNF/8c40F)_*eWb7nL*6D$U$91o]%$,pg"CfNP/MJm''DnssJh\@1!;`KFl36P]UrTt_"p*hFSY5^+9#S7e %epp%F(sNiM)g(\66WkURF-]qfj6GE,JMf]_#u3NYV?q?H8.u2K)"+0R=]Ln9io:^@$QHl/jH0sE]S[0:;hTE&1l4)pM$'Z;BF!TM %C`lmm)Mn2u5aeCHL\6i_L1d05GeZc^(`=qIPUC>\BL8r+clgE'(,Sjn %&?r+C^l8S#?P)^hKM4Zh[m9).:+Np#!q@\CM51:i#EAWaX=[QB"D3q':\(S8.i!=DScKacBK%4m0k/\_quepnIL3T="g3SIf$f)# %MOBg<:-aS*P+Wm$Hrg`^[$cI)LeaEtONAbm$.BW"nKXCBCMErH(l%$!rGQ(N);22:mOj-K8O==j:=\8iQn4PZXl^l_ %ak4B_JhTtMOTnua40b$C4TmZ/7s,6@.+!j09rJN:&.9Zo>4AY>oTKq\*.fsni=0B'a=8oSc3SI?:T:rk;\D$-;KbtO&p)@n?=jtD %WCSG:EsNW(14Db-M_l3I"sX*@qik!!A9j %JO%>?#`kXbKB["idgI.("po]\FL_P-9uh,sMBa@.0S9BD,T2)*]a:tW'f#8k8F.g6%LW>A3HUX0#H$$+dA>kG>S@=doA:)aY5/E

HqETt:bpS2,*K85WfV1>M0[XUNdMunKCZ;T!j2b,PIVSGI6qDbLd]JV>R*V<,R1+i':c(q7NP,K_\>\kN#A]"JG %T^`Eu'C9CjOi.$+*9*8-3KTqrOYA;S_!NI!`VkQPW=:UmaiR$F2n4VLL,]CCE_YI`M+k\fHDl7t7Y,*pBfrS]Gn7ms!YUQ?M$Ak- %R/,fVa`*:7oDb5"4@)P]:pdkQQu+#B^k=94n;1j^Y_%T+K,l%!!bF(=C)e4bNT"Osbnp#Ip/l'BEM`P2V,&.E=o^R3I;^ %jp,tG7Zp.e`c])"BME29,qLXKDjm2`J]"HOQrBFrY+oPC12dd[A]IFh4cg5;i+`@fL\_<5%e(-@!AOKsN!p-;OHc=B!fB=95RHB0 %KGSrd+MtWn<_eS2.?4P6-0TKgU8Sc'Kbt>WqlUHdZTSlDnBLE?pLj!$oeu6PI,KFZ;M6$2a!>C-F=ID/U@-C#g<./*@X&4fs2Vs: %0U2f"/d?s&#+C$oAn$=qXWQXb(:8K`Ua/u9FIPM:i]Xi>a'sRgZ@2\5QqmjE\U)2qWtB>mBKH*d]Der@0VH^YU!KX %6+;BY2Wf7@F[Ep;#ijl5UHMmD&aoNME?Uu_@5s4F9hA(7T^`39^W`g.T95h638R%QQ6jR"=pEsOU[Uk==fUJ=__Q,iP^T$^o_OS[_Q!l@&QiaA"Ose?h6#l!Tcl7 %LndL@JBB&Qa9o!o>6&]jaS:5GUaCh[ %AJr0M&0Fck=hn'J^8('_?QBZ97+;Dr@tS8[:0]ajp@$RfapSl!R'?eUJp^-bhD!K?JMk$C'TiA6h&ap@R((*a)SuhT.*uu=#X3i& %82qqM/2*W&$>`%p5RM!TE^H4fO^!XA`P;Ir)io7X,VM[Hcd>]gG^QclN_u/#p`q.;D?$eS@5._s8:^L*DX*CQbL0B4hL$*nQbkg)Z#mra'Gd'l_"]$e]j#qJ/t!"b@9]-UU[RnI)lUPN^\3pC8aj, %?_&#tQ:0.04oaKR/]OR[:-uA"DYZ)jHTWrS!,;-)ceB3?+=F&/:UO'9g<>&I++_C7)*DldNPMj4TadW',Y;_##+2m%mU%3c]R)em %[%?FPR5\918,LpGE9dJ*YB\[:?g~> %AI9_PrivateDataEnd \ No newline at end of file diff --git a/components/external/SQLite-3.8.1/art/sqlite370.ico b/components/external/SQLite-3.8.1/art/sqlite370.ico new file mode 100644 index 0000000000000000000000000000000000000000..0e8139434b269a3c61e96425e4766a1b3c7486cf Binary files /dev/null and b/components/external/SQLite-3.8.1/art/sqlite370.ico differ diff --git a/components/external/SQLite-3.8.1/art/sqlite370.jpg b/components/external/SQLite-3.8.1/art/sqlite370.jpg new file mode 100644 index 0000000000000000000000000000000000000000..840afa92bc13f0039c1d3f632c765b6e95ae7d35 Binary files /dev/null and b/components/external/SQLite-3.8.1/art/sqlite370.jpg differ diff --git a/components/external/SQLite-3.8.1/autoconf/INSTALL b/components/external/SQLite-3.8.1/autoconf/INSTALL new file mode 100644 index 0000000000000000000000000000000000000000..a1e89e18ad20c227845f2099cb9894c799265d19 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/INSTALL @@ -0,0 +1,370 @@ +Installation Instructions +************************* + +Copyright (C) 1994-1996, 1999-2002, 2004-2011 Free Software Foundation, +Inc. + + Copying and distribution of this file, with or without modification, +are permitted in any medium without royalty provided the copyright +notice and this notice are preserved. This file is offered as-is, +without warranty of any kind. + +Basic Installation +================== + + Briefly, the shell commands `./configure; make; make install' should +configure, build, and install this package. The following +more-detailed instructions are generic; see the `README' file for +instructions specific to this package. Some packages provide this +`INSTALL' file but do not implement all of the features documented +below. The lack of an optional feature in a given package is not +necessarily a bug. More recommendations for GNU packages can be found +in *note Makefile Conventions: (standards)Makefile Conventions. + + The `configure' shell script attempts to guess correct values for +various system-dependent variables used during compilation. It uses +those values to create a `Makefile' in each directory of the package. +It may also create one or more `.h' files containing system-dependent +definitions. Finally, it creates a shell script `config.status' that +you can run in the future to recreate the current configuration, and a +file `config.log' containing compiler output (useful mainly for +debugging `configure'). + + It can also use an optional file (typically called `config.cache' +and enabled with `--cache-file=config.cache' or simply `-C') that saves +the results of its tests to speed up reconfiguring. Caching is +disabled by default to prevent problems with accidental use of stale +cache files. + + If you need to do unusual things to compile the package, please try +to figure out how `configure' could check whether to do them, and mail +diffs or instructions to the address given in the `README' so they can +be considered for the next release. If you are using the cache, and at +some point `config.cache' contains results you don't want to keep, you +may remove or edit it. + + The file `configure.ac' (or `configure.in') is used to create +`configure' by a program called `autoconf'. You need `configure.ac' if +you want to change it or regenerate `configure' using a newer version +of `autoconf'. + + The simplest way to compile this package is: + + 1. `cd' to the directory containing the package's source code and type + `./configure' to configure the package for your system. + + Running `configure' might take a while. While running, it prints + some messages telling which features it is checking for. + + 2. Type `make' to compile the package. + + 3. Optionally, type `make check' to run any self-tests that come with + the package, generally using the just-built uninstalled binaries. + + 4. Type `make install' to install the programs and any data files and + documentation. When installing into a prefix owned by root, it is + recommended that the package be configured and built as a regular + user, and only the `make install' phase executed with root + privileges. + + 5. Optionally, type `make installcheck' to repeat any self-tests, but + this time using the binaries in their final installed location. + This target does not install anything. Running this target as a + regular user, particularly if the prior `make install' required + root privileges, verifies that the installation completed + correctly. + + 6. You can remove the program binaries and object files from the + source code directory by typing `make clean'. To also remove the + files that `configure' created (so you can compile the package for + a different kind of computer), type `make distclean'. There is + also a `make maintainer-clean' target, but that is intended mainly + for the package's developers. If you use it, you may have to get + all sorts of other programs in order to regenerate files that came + with the distribution. + + 7. Often, you can also type `make uninstall' to remove the installed + files again. In practice, not all packages have tested that + uninstallation works correctly, even though it is required by the + GNU Coding Standards. + + 8. Some packages, particularly those that use Automake, provide `make + distcheck', which can by used by developers to test that all other + targets like `make install' and `make uninstall' work correctly. + This target is generally not run by end users. + +Compilers and Options +===================== + + Some systems require unusual options for compilation or linking that +the `configure' script does not know about. Run `./configure --help' +for details on some of the pertinent environment variables. + + You can give `configure' initial values for configuration parameters +by setting variables in the command line or in the environment. Here +is an example: + + ./configure CC=c99 CFLAGS=-g LIBS=-lposix + + *Note Defining Variables::, for more details. + +Compiling For Multiple Architectures +==================================== + + You can compile the package for more than one kind of computer at the +same time, by placing the object files for each architecture in their +own directory. To do this, you can use GNU `make'. `cd' to the +directory where you want the object files and executables to go and run +the `configure' script. `configure' automatically checks for the +source code in the directory that `configure' is in and in `..'. This +is known as a "VPATH" build. + + With a non-GNU `make', it is safer to compile the package for one +architecture at a time in the source code directory. After you have +installed the package for one architecture, use `make distclean' before +reconfiguring for another architecture. + + On MacOS X 10.5 and later systems, you can create libraries and +executables that work on multiple system types--known as "fat" or +"universal" binaries--by specifying multiple `-arch' options to the +compiler but only a single `-arch' option to the preprocessor. Like +this: + + ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ + CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ + CPP="gcc -E" CXXCPP="g++ -E" + + This is not guaranteed to produce working output in all cases, you +may have to build one architecture at a time and combine the results +using the `lipo' tool if you have problems. + +Installation Names +================== + + By default, `make install' installs the package's commands under +`/usr/local/bin', include files under `/usr/local/include', etc. You +can specify an installation prefix other than `/usr/local' by giving +`configure' the option `--prefix=PREFIX', where PREFIX must be an +absolute file name. + + You can specify separate installation prefixes for +architecture-specific files and architecture-independent files. If you +pass the option `--exec-prefix=PREFIX' to `configure', the package uses +PREFIX as the prefix for installing programs and libraries. +Documentation and other data files still use the regular prefix. + + In addition, if you use an unusual directory layout you can give +options like `--bindir=DIR' to specify different values for particular +kinds of files. Run `configure --help' for a list of the directories +you can set and what kinds of files go in them. In general, the +default for these options is expressed in terms of `${prefix}', so that +specifying just `--prefix' will affect all of the other directory +specifications that were not explicitly provided. + + The most portable way to affect installation locations is to pass the +correct locations to `configure'; however, many packages provide one or +both of the following shortcuts of passing variable assignments to the +`make install' command line to change installation locations without +having to reconfigure or recompile. + + The first method involves providing an override variable for each +affected directory. For example, `make install +prefix=/alternate/directory' will choose an alternate location for all +directory configuration variables that were expressed in terms of +`${prefix}'. Any directories that were specified during `configure', +but not in terms of `${prefix}', must each be overridden at install +time for the entire installation to be relocated. The approach of +makefile variable overrides for each directory variable is required by +the GNU Coding Standards, and ideally causes no recompilation. +However, some platforms have known limitations with the semantics of +shared libraries that end up requiring recompilation when using this +method, particularly noticeable in packages that use GNU Libtool. + + The second method involves providing the `DESTDIR' variable. For +example, `make install DESTDIR=/alternate/directory' will prepend +`/alternate/directory' before all installation names. The approach of +`DESTDIR' overrides is not required by the GNU Coding Standards, and +does not work on platforms that have drive letters. On the other hand, +it does better at avoiding recompilation issues, and works well even +when some directory options were not specified in terms of `${prefix}' +at `configure' time. + +Optional Features +================= + + If the package supports it, you can cause programs to be installed +with an extra prefix or suffix on their names by giving `configure' the +option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. + + Some packages pay attention to `--enable-FEATURE' options to +`configure', where FEATURE indicates an optional part of the package. +They may also pay attention to `--with-PACKAGE' options, where PACKAGE +is something like `gnu-as' or `x' (for the X Window System). The +`README' should mention any `--enable-' and `--with-' options that the +package recognizes. + + For packages that use the X Window System, `configure' can usually +find the X include and library files automatically, but if it doesn't, +you can use the `configure' options `--x-includes=DIR' and +`--x-libraries=DIR' to specify their locations. + + Some packages offer the ability to configure how verbose the +execution of `make' will be. For these packages, running `./configure +--enable-silent-rules' sets the default to minimal output, which can be +overridden with `make V=1'; while running `./configure +--disable-silent-rules' sets the default to verbose, which can be +overridden with `make V=0'. + +Particular systems +================== + + On HP-UX, the default C compiler is not ANSI C compatible. If GNU +CC is not installed, it is recommended to use the following options in +order to use an ANSI C compiler: + + ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" + +and if that doesn't work, install pre-built binaries of GCC for HP-UX. + + HP-UX `make' updates targets which have the same time stamps as +their prerequisites, which makes it generally unusable when shipped +generated files such as `configure' are involved. Use GNU `make' +instead. + + On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot +parse its `' header file. The option `-nodtk' can be used as +a workaround. If GNU CC is not installed, it is therefore recommended +to try + + ./configure CC="cc" + +and if that doesn't work, try + + ./configure CC="cc -nodtk" + + On Solaris, don't put `/usr/ucb' early in your `PATH'. This +directory contains several dysfunctional programs; working variants of +these programs are available in `/usr/bin'. So, if you need `/usr/ucb' +in your `PATH', put it _after_ `/usr/bin'. + + On Haiku, software installed for all users goes in `/boot/common', +not `/usr/local'. It is recommended to use the following options: + + ./configure --prefix=/boot/common + +Specifying the System Type +========================== + + There may be some features `configure' cannot figure out +automatically, but needs to determine by the type of machine the package +will run on. Usually, assuming the package is built to be run on the +_same_ architectures, `configure' can figure that out, but if it prints +a message saying it cannot guess the machine type, give it the +`--build=TYPE' option. TYPE can either be a short name for the system +type, such as `sun4', or a canonical name which has the form: + + CPU-COMPANY-SYSTEM + +where SYSTEM can have one of these forms: + + OS + KERNEL-OS + + See the file `config.sub' for the possible values of each field. If +`config.sub' isn't included in this package, then this package doesn't +need to know the machine type. + + If you are _building_ compiler tools for cross-compiling, you should +use the option `--target=TYPE' to select the type of system they will +produce code for. + + If you want to _use_ a cross compiler, that generates code for a +platform different from the build platform, you should specify the +"host" platform (i.e., that on which the generated programs will +eventually be run) with `--host=TYPE'. + +Sharing Defaults +================ + + If you want to set default values for `configure' scripts to share, +you can create a site shell script called `config.site' that gives +default values for variables like `CC', `cache_file', and `prefix'. +`configure' looks for `PREFIX/share/config.site' if it exists, then +`PREFIX/etc/config.site' if it exists. Or, you can set the +`CONFIG_SITE' environment variable to the location of the site script. +A warning: not all `configure' scripts look for a site script. + +Defining Variables +================== + + Variables not defined in a site shell script can be set in the +environment passed to `configure'. However, some packages may run +configure again during the build, and the customized values of these +variables may be lost. In order to avoid this problem, you should set +them in the `configure' command line, using `VAR=value'. For example: + + ./configure CC=/usr/local2/bin/gcc + +causes the specified `gcc' to be used as the C compiler (unless it is +overridden in the site shell script). + +Unfortunately, this technique does not work for `CONFIG_SHELL' due to +an Autoconf bug. Until the bug is fixed you can use this workaround: + + CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash + +`configure' Invocation +====================== + + `configure' recognizes the following options to control how it +operates. + +`--help' +`-h' + Print a summary of all of the options to `configure', and exit. + +`--help=short' +`--help=recursive' + Print a summary of the options unique to this package's + `configure', and exit. The `short' variant lists options used + only in the top level, while the `recursive' variant lists options + also present in any nested packages. + +`--version' +`-V' + Print the version of Autoconf used to generate the `configure' + script, and exit. + +`--cache-file=FILE' + Enable the cache: use and save the results of the tests in FILE, + traditionally `config.cache'. FILE defaults to `/dev/null' to + disable caching. + +`--config-cache' +`-C' + Alias for `--cache-file=config.cache'. + +`--quiet' +`--silent' +`-q' + Do not print messages saying which checks are being made. To + suppress all normal output, redirect it to `/dev/null' (any error + messages will still be shown). + +`--srcdir=DIR' + Look for the package's source code in directory DIR. Usually + `configure' can determine that directory automatically. + +`--prefix=DIR' + Use DIR as the installation prefix. *note Installation Names:: + for more details, including other options available for fine-tuning + the installation locations. + +`--no-create' +`-n' + Run the configure checks, but stop before creating any output + files. + +`configure' also accepts some other, not widely useful, options. Run +`configure --help' for more details. + diff --git a/components/external/SQLite-3.8.1/autoconf/Makefile.am b/components/external/SQLite-3.8.1/autoconf/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..6fc4f33c0e5a7331107ead6d6b6a110b467dccd7 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/Makefile.am @@ -0,0 +1,19 @@ + +AM_CFLAGS = @THREADSAFE_FLAGS@ @DYNAMIC_EXTENSION_FLAGS@ -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE + +lib_LTLIBRARIES = libsqlite3.la +libsqlite3_la_SOURCES = sqlite3.c +libsqlite3_la_LDFLAGS = -no-undefined -version-info 8:6:8 + +bin_PROGRAMS = sqlite3 +sqlite3_SOURCES = shell.c sqlite3.h +sqlite3_LDADD = $(top_builddir)/libsqlite3.la @READLINE_LIBS@ +sqlite3_DEPENDENCIES = $(top_builddir)/libsqlite3.la + +include_HEADERS = sqlite3.h sqlite3ext.h + +EXTRA_DIST = sqlite3.1 tea +pkgconfigdir = ${libdir}/pkgconfig +pkgconfig_DATA = sqlite3.pc + +man_MANS = sqlite3.1 diff --git a/components/external/SQLite-3.8.1/autoconf/README b/components/external/SQLite-3.8.1/autoconf/README new file mode 100644 index 0000000000000000000000000000000000000000..dd8cca24bdee04159fafb271dda11e5a222a1080 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/README @@ -0,0 +1,32 @@ + +This package contains: + + * the SQLite library amalgamation (single file) source code distribution, + * the shell.c file used to build the sqlite3 shell too, and + * the sqlite3.h and sqlite3ext.h header files required to link programs + and sqlite extensions against the installed libary. + * autoconf/automake installation infrastucture. + +The generic installation instructions for autoconf/automake are found +in the INSTALL file. + +The following SQLite specific boolean options are supported: + + --enable-readline use readline in shell tool [default=yes] + --enable-threadsafe build a thread-safe library [default=yes] + --enable-dynamic-extensions support loadable extensions [default=yes] + +The default value for the CFLAGS variable (options passed to the C +compiler) includes debugging symbols in the build, resulting in larger +binaries than are necessary. Override it on the configure command +line like this: + + $ CFLAGS="-Os" ./configure + +to produce a smaller installation footprint. + +Other SQLite compilation parameters can also be set using CFLAGS. For +example: + + $ CFLAGS="-Os -DSQLITE_OMIT_TRIGGERS" ./configure + diff --git a/components/external/SQLite-3.8.1/autoconf/README.first b/components/external/SQLite-3.8.1/autoconf/README.first new file mode 100644 index 0000000000000000000000000000000000000000..6676228ad674cfe43af4d4761a5d13c302ff830f --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/README.first @@ -0,0 +1,57 @@ + +This file describes how to use the files in this directory to create a new +version of the "autoconf-amalgamation" package. + +1. The following files should have executable permission: + + chmod 755 install-sh + chmod 755 missing + chmod 755 depcomp + chmod 755 config.sub + chmod 755 config.guess + +2. Copy new versions of the following SQLite files into this directory: + + sqlite3.c + sqlite3.h + sqlite3ext.h + sqlite3.1 + sqlite3.pc.in + shell.c + +3. Update the SQLite version number in the AC_INIT macro in file + configure.ac: + + AC_INIT(sqlite, 3.6.3, http://www.sqlite.org) + +4. Run the following commands to push the version number change through + to the generated files. + + aclocal + autoconf + automake + +5. Create the tclsqlite3.c file in the tea/generic directory. As follows: + + mkdir -p tea/generic + echo "#ifdef USE_SYSTEM_SQLITE" > tea/generic/tclsqlite3.c + echo "# include " >> tea/generic/tclsqlite3.c + echo "#else" >> tea/generic/tclsqlite3.c + echo "#include \"../../sqlite3.c\"" >> tea/generic/tclsqlite3.c + echo "#endif" >> tea/generic/tclsqlite3.c + cat ../src/tclsqlite.c >> tea/generic/tclsqlite3.c + +6. Update the SQLite version in the AC_INIT macro in file tea/configure.in: + + AC_INIT([sqlite], [3.6.3]) + +7. From the 'tea' directory, run the following commands: + + autoconf + rm -rf autom4te.cache + +8. Run "./configure && make dist". This builds a distribution package + named something like "sqlite-3.6.3.tar.gz". Rename to + "sqlite-amalgamation-3.6.3.tar.gz" and use. + + diff --git a/components/external/SQLite-3.8.1/autoconf/config.guess b/components/external/SQLite-3.8.1/autoconf/config.guess new file mode 100644 index 0000000000000000000000000000000000000000..d622a44e551f209d5e8c5462b3fe53a162f7b330 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/config.guess @@ -0,0 +1,1530 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +# 2011, 2012 Free Software Foundation, Inc. + +timestamp='2012-02-10' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Originally written by Per Bothner. Please send patches (context +# diff format) to and include a ChangeLog +# entry. +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# You can get the latest version of this script from: +# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, +2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +trap 'exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +set_cc_for_build=' +trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; +trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; +: ${TMPDIR=/tmp} ; + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; +dummy=$tmp/dummy ; +tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int x;" > $dummy.c ; + for c in cc gcc c89 c99 ; do + if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac ; set_cc_for_build= ;' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ + /usr/sbin/$sysctl 2>/dev/null || echo unknown)` + case "${UNAME_MACHINE_ARCH}" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + sh5el) machine=sh5le-unknown ;; + *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE_ARCH}" in + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ELF__ + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "${UNAME_VERSION}" in + Debian*) + release='-gnu' + ;; + *) + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit ;; + *:OpenBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} + exit ;; + *:ekkoBSD:*:*) + echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + exit ;; + *:SolidBSD:*:*) + echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} + exit ;; + macppc:MirBSD:*:*) + echo powerpc-unknown-mirbsd${UNAME_RELEASE} + exit ;; + *:MirBSD:*:*) + echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + exit ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE="alpha" ;; + "EV4.5 (21064)") + UNAME_MACHINE="alpha" ;; + "LCA4 (21066/21068)") + UNAME_MACHINE="alpha" ;; + "EV5 (21164)") + UNAME_MACHINE="alphaev5" ;; + "EV5.6 (21164A)") + UNAME_MACHINE="alphaev56" ;; + "EV5.6 (21164PC)") + UNAME_MACHINE="alphapca56" ;; + "EV5.7 (21164PC)") + UNAME_MACHINE="alphapca57" ;; + "EV6 (21264)") + UNAME_MACHINE="alphaev6" ;; + "EV6.7 (21264A)") + UNAME_MACHINE="alphaev67" ;; + "EV6.8CB (21264C)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8AL (21264B)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8CX (21264D)") + UNAME_MACHINE="alphaev68" ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE="alphaev69" ;; + "EV7 (21364)") + UNAME_MACHINE="alphaev7" ;; + "EV7.9 (21364A)") + UNAME_MACHINE="alphaev79" ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Reset EXIT trap before exiting to avoid spurious non-zero exit code. + exitcode=$? + trap '' 0 + exit $exitcode ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit ;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-morphos + exit ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit ;; + *:z/VM:*:*) + echo s390-ibm-zvmoe + exit ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit ;; + arm:riscos:*:*|arm:RISCOS:*:*) + echo arm-unknown-riscos + exit ;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit ;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7; exit ;; + esac ;; + s390x:SunOS:*:*) + echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) + echo i386-pc-auroraux${UNAME_RELEASE} + exit ;; + i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) + eval $set_cc_for_build + SUN_ARCH="i386" + # If there is a compiler, see if it is configured for 64-bit objects. + # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. + # This test works for both compilers. + if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then + if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + SUN_ARCH="x86_64" + fi + fi + echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit ;; + m68k:machten:*:*) + echo m68k-apple-machten${UNAME_RELEASE} + exit ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && + dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`$dummy $dummyarg` && + { echo "$SYSTEM_NAME"; exit; } + echo mips-mips-riscos${UNAME_RELEASE} + exit ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` + then + echo "$SYSTEM_NAME" + else + echo rs6000-ibm-aix3.2.5 + fi + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit ;; + *:AIX:*:[4567]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ ${HP_ARCH} = "hppa2.0w" ] + then + eval $set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | + grep -q __LP64__ + then + HP_ARCH="hppa2.0w" + else + HP_ARCH="hppa64" + fi + fi + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + echo unknown-hitachi-hiuxwe2 + exit ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + *:UNICOS/mp:*:*) + echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:FreeBSD:*:*) + UNAME_PROCESSOR=`/usr/bin/uname -p` + case ${UNAME_PROCESSOR} in + amd64) + echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + *) + echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + esac + exit ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit ;; + *:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit ;; + i*:MSYS*:*) + echo ${UNAME_MACHINE}-pc-msys + exit ;; + i*:windows32*:*) + # uname -m includes "-pc" on this system. + echo ${UNAME_MACHINE}-mingw32 + exit ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit ;; + *:Interix*:*) + case ${UNAME_MACHINE} in + x86) + echo i586-pc-interix${UNAME_RELEASE} + exit ;; + authenticamd | genuineintel | EM64T) + echo x86_64-unknown-interix${UNAME_RELEASE} + exit ;; + IA64) + echo ia64-unknown-interix${UNAME_RELEASE} + exit ;; + esac ;; + [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) + echo i${UNAME_MACHINE}-pc-mks + exit ;; + 8664:Windows_NT:*) + echo x86_64-pc-mks + exit ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i586-pc-interix + exit ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + echo x86_64-unknown-cygwin + exit ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + *:GNU:*:*) + # the GNU system + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu + exit ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit ;; + aarch64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + aarch64_be:Linux:*:*) + UNAME_MACHINE=aarch64_be + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep -q ld.so.1 + if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi + echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} + exit ;; + arm*:Linux:*:*) + eval $set_cc_for_build + if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_EABI__ + then + echo ${UNAME_MACHINE}-unknown-linux-gnu + else + if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_PCS_VFP + then + echo ${UNAME_MACHINE}-unknown-linux-gnueabi + else + echo ${UNAME_MACHINE}-unknown-linux-gnueabihf + fi + fi + exit ;; + avr32*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + cris:Linux:*:*) + echo ${UNAME_MACHINE}-axis-linux-gnu + exit ;; + crisv32:Linux:*:*) + echo ${UNAME_MACHINE}-axis-linux-gnu + exit ;; + frv:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + hexagon:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + i*86:Linux:*:*) + LIBC=gnu + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #ifdef __dietlibc__ + LIBC=dietlibc + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` + echo "${UNAME_MACHINE}-pc-linux-${LIBC}" + exit ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m32r*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + mips:Linux:*:* | mips64:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef ${UNAME_MACHINE} + #undef ${UNAME_MACHINE}el + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=${UNAME_MACHINE}el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=${UNAME_MACHINE} + #else + CPU= + #endif + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } + ;; + or32:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + padre:Linux:*:*) + echo sparc-unknown-linux-gnu + exit ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-gnu + exit ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-gnu ;; + PA8*) echo hppa2.0-unknown-linux-gnu ;; + *) echo hppa-unknown-linux-gnu ;; + esac + exit ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-gnu + exit ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-gnu + exit ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit ;; + sh64*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + tile*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + vax:Linux:*:*) + echo ${UNAME_MACHINE}-dec-linux-gnu + exit ;; + x86_64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + xtensa*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit ;; + i*86:syllable:*:*) + echo ${UNAME_MACHINE}-pc-syllable + exit ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i586. + # Note: whatever this is, it MUST be the same as what config.sub + # prints for the "djgpp" host, or else GDB configury will decide that + # this is a cross-build. + echo i586-pc-msdosdjgpp + exit ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4; exit; } ;; + NCR*:*:4.2:* | MPRAS*:*:4.2:*) + OS_REL='.3' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + echo ${UNAME_MACHINE}-stratus-vos + exit ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit ;; + BePC:Haiku:*:*) # Haiku running on Intel PC compatible. + echo i586-pc-haiku + exit ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux${UNAME_RELEASE} + exit ;; + SX-7:SUPER-UX:*:*) + echo sx7-nec-superux${UNAME_RELEASE} + exit ;; + SX-8:SUPER-UX:*:*) + echo sx8-nec-superux${UNAME_RELEASE} + exit ;; + SX-8R:SUPER-UX:*:*) + echo sx8r-nec-superux${UNAME_RELEASE} + exit ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown + case $UNAME_PROCESSOR in + i386) + eval $set_cc_for_build + if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then + if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + UNAME_PROCESSOR="x86_64" + fi + fi ;; + unknown) UNAME_PROCESSOR=powerpc ;; + esac + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = "x86"; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + exit ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit ;; + NEO-?:NONSTOP_KERNEL:*:*) + echo neo-tandem-nsk${UNAME_RELEASE} + exit ;; + NSE-?:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk${UNAME_RELEASE} + exit ;; + NSR-?:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux${UNAME_RELEASE} + exit ;; + *:DragonFly:*:*) + echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case "${UNAME_MACHINE}" in + A*) echo alpha-dec-vms ; exit ;; + I*) echo ia64-dec-vms ; exit ;; + V*) echo vax-dec-vms ; exit ;; + esac ;; + *:XENIX:*:SysV) + echo i386-pc-xenix + exit ;; + i*86:skyos:*:*) + echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' + exit ;; + i*86:rdos:*:*) + echo ${UNAME_MACHINE}-pc-rdos + exit ;; + i*86:AROS:*:*) + echo ${UNAME_MACHINE}-pc-aros + exit ;; + x86_64:VMkernel:*:*) + echo ${UNAME_MACHINE}-unknown-esx + exit ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +eval $set_cc_for_build +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix\n"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + c34*) + echo c34-convex-bsd + exit ;; + c38*) + echo c38-convex-bsd + exit ;; + c4*) + echo c4-convex-bsd + exit ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/components/external/SQLite-3.8.1/autoconf/config.sub b/components/external/SQLite-3.8.1/autoconf/config.sub new file mode 100644 index 0000000000000000000000000000000000000000..c894da45500c4af1bf5688e713a8895622d18182 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/config.sub @@ -0,0 +1,1773 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +# 2011, 2012 Free Software Foundation, Inc. + +timestamp='2012-02-10' + +# This file is (in principle) common to ALL GNU software. +# The presence of a machine in this file suggests that SOME GNU software +# can handle that machine. It does not imply ALL GNU software can. +# +# This file is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Please send patches to . Submit a context +# diff and a properly formatted GNU ChangeLog entry. +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# You can get the latest version of this script from: +# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, +2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit ;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ + linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ + knetbsd*-gnu* | netbsd*-gnu* | \ + kopensolaris*-gnu* | \ + storm-chaos* | os2-emx* | rtmk-nova*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + android-linux) + os=-linux-android + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis | -knuth | -cray | -microblaze) + os= + basic_machine=$1 + ;; + -bluegene*) + os=-cnk + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -chorusos*) + os=-chorusos + basic_machine=$1 + ;; + -chorusrdb) + os=-chorusrdb + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco6) + os=-sco5v6 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5v6*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + 1750a | 580 \ + | a29k \ + | aarch64 | aarch64_be \ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ + | am33_2.0 \ + | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ + | be32 | be64 \ + | bfin \ + | c4x | clipper \ + | d10v | d30v | dlx | dsp16xx \ + | epiphany \ + | fido | fr30 | frv \ + | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | hexagon \ + | i370 | i860 | i960 | ia64 \ + | ip2k | iq2000 \ + | le32 | le64 \ + | lm32 \ + | m32c | m32r | m32rle | m68000 | m68k | m88k \ + | maxq | mb | microblaze | mcore | mep | metag \ + | mips | mipsbe | mipseb | mipsel | mipsle \ + | mips16 \ + | mips64 | mips64el \ + | mips64octeon | mips64octeonel \ + | mips64orion | mips64orionel \ + | mips64r5900 | mips64r5900el \ + | mips64vr | mips64vrel \ + | mips64vr4100 | mips64vr4100el \ + | mips64vr4300 | mips64vr4300el \ + | mips64vr5000 | mips64vr5000el \ + | mips64vr5900 | mips64vr5900el \ + | mipsisa32 | mipsisa32el \ + | mipsisa32r2 | mipsisa32r2el \ + | mipsisa64 | mipsisa64el \ + | mipsisa64r2 | mipsisa64r2el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ + | mipstx39 | mipstx39el \ + | mn10200 | mn10300 \ + | moxie \ + | mt \ + | msp430 \ + | nds32 | nds32le | nds32be \ + | nios | nios2 \ + | ns16k | ns32k \ + | open8 \ + | or32 \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle \ + | pyramid \ + | rl78 | rx \ + | score \ + | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ + | sh64 | sh64le \ + | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ + | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ + | spu \ + | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ + | ubicom32 \ + | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ + | we32k \ + | x86 | xc16x | xstormy16 | xtensa \ + | z8k | z80) + basic_machine=$basic_machine-unknown + ;; + c54x) + basic_machine=tic54x-unknown + ;; + c55x) + basic_machine=tic55x-unknown + ;; + c6x) + basic_machine=tic6x-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip) + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + ;; + ms1) + basic_machine=mt-unknown + ;; + + strongarm | thumb | xscale) + basic_machine=arm-unknown + ;; + xgate) + basic_machine=$basic_machine-unknown + os=-none + ;; + xscaleeb) + basic_machine=armeb-unknown + ;; + + xscaleel) + basic_machine=armel-unknown + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + 580-* \ + | a29k-* \ + | aarch64-* | aarch64_be-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ + | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ + | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ + | avr-* | avr32-* \ + | be32-* | be64-* \ + | bfin-* | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c4x-* \ + | clipper-* | craynv-* | cydra-* \ + | d10v-* | d30v-* | dlx-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ + | h8300-* | h8500-* \ + | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ + | hexagon-* \ + | i*86-* | i860-* | i960-* | ia64-* \ + | ip2k-* | iq2000-* \ + | le32-* | le64-* \ + | lm32-* \ + | m32c-* | m32r-* | m32rle-* \ + | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ + | m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \ + | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ + | mips16-* \ + | mips64-* | mips64el-* \ + | mips64octeon-* | mips64octeonel-* \ + | mips64orion-* | mips64orionel-* \ + | mips64r5900-* | mips64r5900el-* \ + | mips64vr-* | mips64vrel-* \ + | mips64vr4100-* | mips64vr4100el-* \ + | mips64vr4300-* | mips64vr4300el-* \ + | mips64vr5000-* | mips64vr5000el-* \ + | mips64vr5900-* | mips64vr5900el-* \ + | mipsisa32-* | mipsisa32el-* \ + | mipsisa32r2-* | mipsisa32r2el-* \ + | mipsisa64-* | mipsisa64el-* \ + | mipsisa64r2-* | mipsisa64r2el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ + | mipstx39-* | mipstx39el-* \ + | mmix-* \ + | mt-* \ + | msp430-* \ + | nds32-* | nds32le-* | nds32be-* \ + | nios-* | nios2-* \ + | none-* | np1-* | ns16k-* | ns32k-* \ + | open8-* \ + | orion-* \ + | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ + | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ + | pyramid-* \ + | rl78-* | romp-* | rs6000-* | rx-* \ + | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ + | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ + | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ + | sparclite-* \ + | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \ + | tahoe-* \ + | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ + | tile*-* \ + | tron-* \ + | ubicom32-* \ + | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ + | vax-* \ + | we32k-* \ + | x86-* | x86_64-* | xc16x-* | xps100-* \ + | xstormy16-* | xtensa*-* \ + | ymp-* \ + | z8k-* | z80-*) + ;; + # Recognize the basic CPU types without company name, with glob match. + xtensa*) + basic_machine=$basic_machine-unknown + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + abacus) + basic_machine=abacus-unknown + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amd64) + basic_machine=x86_64-pc + ;; + amd64-*) + basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aros) + basic_machine=i386-pc + os=-aros + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + blackfin) + basic_machine=bfin-unknown + os=-linux + ;; + blackfin-*) + basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` + os=-linux + ;; + bluegene*) + basic_machine=powerpc-ibm + os=-cnk + ;; + c54x-*) + basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + c55x-*) + basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + c6x-*) + basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + c90) + basic_machine=c90-cray + os=-unicos + ;; + cegcc) + basic_machine=arm-unknown + os=-cegcc + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | j90) + basic_machine=j90-cray + os=-unicos + ;; + craynv) + basic_machine=craynv-cray + os=-unicosmp + ;; + cr16 | cr16-*) + basic_machine=cr16-unknown + os=-elf + ;; + crds | unos) + basic_machine=m68k-crds + ;; + crisv32 | crisv32-* | etraxfs*) + basic_machine=crisv32-axis + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + crx) + basic_machine=crx-unknown + os=-elf + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + decsystem10* | dec10*) + basic_machine=pdp10-dec + os=-tops10 + ;; + decsystem20* | dec20*) + basic_machine=pdp10-dec + os=-tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + dicos) + basic_machine=i686-pc + os=-dicos + ;; + djgpp) + basic_machine=i586-pc + os=-msdosdjgpp + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m68knommu) + basic_machine=m68k-unknown + os=-linux + ;; + m68knommu-*) + basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` + os=-linux + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + microblaze) + basic_machine=microblaze-xilinx + ;; + mingw32) + basic_machine=i386-pc + os=-mingw32 + ;; + mingw32ce) + basic_machine=arm-unknown + os=-mingw32ce + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + morphos) + basic_machine=powerpc-unknown + os=-morphos + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + ms1-*) + basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` + ;; + msys) + basic_machine=i386-pc + os=-msys + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + nacl) + basic_machine=le32-unknown + os=-nacl + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + neo-tandem) + basic_machine=neo-tandem + ;; + nse-tandem) + basic_machine=nse-tandem + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + openrisc | openrisc-*) + basic_machine=or32-unknown + ;; + os400) + basic_machine=powerpc-ibm + os=-os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + parisc) + basic_machine=hppa-unknown + os=-linux + ;; + parisc-*) + basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` + os=-linux + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pc98) + basic_machine=i386-pc + ;; + pc98-*) + basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium | p5 | k5 | k6 | nexgen | viac3) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon | athlon_*) + basic_machine=i686-pc + ;; + pentiumii | pentium2 | pentiumiii | pentium3) + basic_machine=i686-pc + ;; + pentium4) + basic_machine=i786-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium4-*) + basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc | ppcbe) basic_machine=powerpc-unknown + ;; + ppc-* | ppcbe-*) + basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64) basic_machine=powerpc64-unknown + ;; + ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64le | powerpc64little | ppc64-le | powerpc64-little) + basic_machine=powerpc64le-unknown + ;; + ppc64le-* | powerpc64little-*) + basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rdos) + basic_machine=i386-pc + os=-rdos + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + s390 | s390-*) + basic_machine=s390-ibm + ;; + s390x | s390x-*) + basic_machine=s390x-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sb1) + basic_machine=mipsisa64sb1-unknown + ;; + sb1el) + basic_machine=mipsisa64sb1el-unknown + ;; + sde) + basic_machine=mipsisa32-sde + os=-elf + ;; + sei) + basic_machine=mips-sei + os=-seiux + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sh5el) + basic_machine=sh5le-unknown + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparclite-wrs | simso-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + strongarm-* | thumb-*) + basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=alphaev5-cray + os=-unicos + ;; + t90) + basic_machine=t90-cray + os=-unicos + ;; + tile*) + basic_machine=$basic_machine-unknown + os=-linux-gnu + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + toad1) + basic_machine=pdp10-xkl + os=-tops20 + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + tpf) + basic_machine=s390x-ibm + os=-tpf + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + xbox) + basic_machine=i686-pc + os=-mingw32 + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + xscale-* | xscalee[bl]-*) + basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` + ;; + ymp) + basic_machine=ymp-cray + os=-unicos + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + z80-*-coff) + basic_machine=z80-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + romp) + basic_machine=romp-ibm + ;; + mmix) + basic_machine=mmix-knuth + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) + basic_machine=sh-unknown + ;; + sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -auroraux) + os=-auroraux + ;; + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ + | -sym* | -kopensolaris* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* | -aros* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ + | -openbsd* | -solidbsd* \ + | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ + | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -chorusos* | -chorusrdb* | -cegcc* \ + | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -linux-gnu* | -linux-android* \ + | -linux-newlib* | -linux-uclibc* \ + | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ + | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ + | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ + | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ + | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto-qnx*) + ;; + -nto*) + os=`echo $os | sed -e 's|nto|nto-qnx|'` + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux-dietlibc) + os=-linux-dietlibc + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -os400*) + os=-os400 + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -atheos*) + os=-atheos + ;; + -syllable*) + os=-syllable + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -nova*) + os=-rtmk-nova + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -tpf*) + os=-tpf + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -aros*) + os=-aros + ;; + -kaos*) + os=-kaos + ;; + -zvmoe) + os=-zvmoe + ;; + -dicos*) + os=-dicos + ;; + -nacl*) + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + score-*) + os=-elf + ;; + spu-*) + os=-elf + ;; + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + c4x-* | tic4x-*) + os=-coff + ;; + tic54x-*) + os=-coff + ;; + tic55x-*) + os=-coff + ;; + tic6x-*) + os=-coff + ;; + # This must come before the *-dec entry. + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + ;; + m68*-cisco) + os=-aout + ;; + mep-*) + os=-elf + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + or32-*) + os=-coff + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-haiku) + os=-haiku + ;; + *-ibm) + os=-aix + ;; + *-knuth) + os=-mmixware + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -cnk*|-aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -os400*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -tpf*) + vendor=ibm + ;; + -vxsim* | -vxworks* | -windiss*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + -vos*) + vendor=stratus + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/components/external/SQLite-3.8.1/autoconf/configure.ac b/components/external/SQLite-3.8.1/autoconf/configure.ac new file mode 100644 index 0000000000000000000000000000000000000000..46b6563edca3742643298f873ef40585f3d6edd4 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/configure.ac @@ -0,0 +1,108 @@ + +#----------------------------------------------------------------------- +# Supports the following non-standard switches. +# +# --enable-threadsafe +# --enable-readline +# --enable-dynamic-extensions +# + +AC_PREREQ(2.61) +AC_INIT(sqlite, 3.7.5, http://www.sqlite.org) +AC_CONFIG_SRCDIR([sqlite3.c]) + +# Use automake. +AM_INIT_AUTOMAKE([foreign]) + +AC_SYS_LARGEFILE + +# Check for required programs. +AC_PROG_CC +AC_PROG_RANLIB +AC_PROG_LIBTOOL +AC_PROG_MKDIR_P + +# Check for library functions that SQLite can optionally use. +AC_CHECK_FUNCS([fdatasync usleep fullfsync localtime_r gmtime_r]) +AC_FUNC_STRERROR_R + +AC_CONFIG_FILES([Makefile sqlite3.pc]) +AC_SUBST(BUILD_CFLAGS) + +#----------------------------------------------------------------------- +# --enable-readline +# +AC_ARG_ENABLE(readline, [AS_HELP_STRING( + [--enable-readline], + [use readline in shell tool (yes, no) [default=yes]])], + [], [enable_readline=yes]) +if test x"$enable_readline" != xno ; then + sLIBS=$LIBS + LIBS="" + AC_SEARCH_LIBS(tgetent, curses ncurses ncursesw, [], []) + AC_SEARCH_LIBS(readline, readline, [], [enable_readline=no]) + AC_CHECK_FUNCS(readline, [], []) + READLINE_LIBS=$LIBS + LIBS=$sLIBS +fi +AC_SUBST(READLINE_LIBS) +#----------------------------------------------------------------------- + +#----------------------------------------------------------------------- +# --enable-threadsafe +# +AC_ARG_ENABLE(threadsafe, [AS_HELP_STRING( + [--enable-threadsafe], [build a thread-safe library [default=yes]])], + [], [enable_threadsafe=yes]) +THREADSAFE_FLAGS=-DSQLITE_THREADSAFE=0 +if test x"$enable_threadsafe" != "xno"; then + THREADSAFE_FLAGS="-D_REENTRANT=1 -DSQLITE_THREADSAFE=1" + AC_SEARCH_LIBS(pthread_create, pthread) +fi +AC_SUBST(THREADSAFE_FLAGS) +#----------------------------------------------------------------------- + +#----------------------------------------------------------------------- +# --enable-dynamic-extensions +# +AC_ARG_ENABLE(dynamic-extensions, [AS_HELP_STRING( + [--enable-dynamic-extensions], [support loadable extensions [default=yes]])], + [], [enable_dynamic_extensions=yes]) +if test x"$enable_dynamic_extensions" != "xno"; then + AC_SEARCH_LIBS(dlopen, dl) +else + DYNAMIC_EXTENSION_FLAGS=-DSQLITE_OMIT_LOAD_EXTENSION=1 +fi +AC_MSG_CHECKING([for whether to support dynamic extensions]) +AC_MSG_RESULT($enable_dynamic_extensions) +AC_SUBST(DYNAMIC_EXTENSION_FLAGS) +#----------------------------------------------------------------------- + +AC_CHECK_FUNCS(posix_fallocate) + +#----------------------------------------------------------------------- +# UPDATE: Maybe it's better if users just set CFLAGS before invoking +# configure. This option doesn't really add much... +# +# --enable-tempstore +# +# AC_ARG_ENABLE(tempstore, [AS_HELP_STRING( +# [--enable-tempstore], +# [in-memory temporary tables (never, no, yes, always) [default=no]])], +# [], [enable_tempstore=no]) +# AC_MSG_CHECKING([for whether or not to store temp tables in-memory]) +# case "$enable_tempstore" in +# never ) TEMP_STORE=0 ;; +# no ) TEMP_STORE=1 ;; +# always ) TEMP_STORE=3 ;; +# yes ) TEMP_STORE=3 ;; +# * ) +# TEMP_STORE=1 +# enable_tempstore=yes +# ;; +# esac +# AC_MSG_RESULT($enable_tempstore) +# AC_SUBST(TEMP_STORE) +#----------------------------------------------------------------------- + +AC_OUTPUT diff --git a/components/external/SQLite-3.8.1/autoconf/depcomp b/components/external/SQLite-3.8.1/autoconf/depcomp new file mode 100644 index 0000000000000000000000000000000000000000..25a39e6cd5c82d7276f6ccc62ef5e7ba1cc9776f --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/depcomp @@ -0,0 +1,708 @@ +#! /bin/sh +# depcomp - compile a program generating dependencies as side-effects + +scriptversion=2012-03-27.16; # UTC + +# Copyright (C) 1999, 2000, 2003, 2004, 2005, 2006, 2007, 2009, 2010, +# 2011, 2012 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Originally written by Alexandre Oliva . + +case $1 in + '') + echo "$0: No command. Try '$0 --help' for more information." 1>&2 + exit 1; + ;; + -h | --h*) + cat <<\EOF +Usage: depcomp [--help] [--version] PROGRAM [ARGS] + +Run PROGRAMS ARGS to compile a file, generating dependencies +as side-effects. + +Environment variables: + depmode Dependency tracking mode. + source Source file read by 'PROGRAMS ARGS'. + object Object file output by 'PROGRAMS ARGS'. + DEPDIR directory where to store dependencies. + depfile Dependency file to output. + tmpdepfile Temporary file to use when outputting dependencies. + libtool Whether libtool is used (yes/no). + +Report bugs to . +EOF + exit $? + ;; + -v | --v*) + echo "depcomp $scriptversion" + exit $? + ;; +esac + +# A tabulation character. +tab=' ' +# A newline character. +nl=' +' + +if test -z "$depmode" || test -z "$source" || test -z "$object"; then + echo "depcomp: Variables source, object and depmode must be set" 1>&2 + exit 1 +fi + +# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. +depfile=${depfile-`echo "$object" | + sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} +tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} + +rm -f "$tmpdepfile" + +# Some modes work just like other modes, but use different flags. We +# parameterize here, but still list the modes in the big case below, +# to make depend.m4 easier to write. Note that we *cannot* use a case +# here, because this file can only contain one case statement. +if test "$depmode" = hp; then + # HP compiler uses -M and no extra arg. + gccflag=-M + depmode=gcc +fi + +if test "$depmode" = dashXmstdout; then + # This is just like dashmstdout with a different argument. + dashmflag=-xM + depmode=dashmstdout +fi + +cygpath_u="cygpath -u -f -" +if test "$depmode" = msvcmsys; then + # This is just like msvisualcpp but w/o cygpath translation. + # Just convert the backslash-escaped backslashes to single forward + # slashes to satisfy depend.m4 + cygpath_u='sed s,\\\\,/,g' + depmode=msvisualcpp +fi + +if test "$depmode" = msvc7msys; then + # This is just like msvc7 but w/o cygpath translation. + # Just convert the backslash-escaped backslashes to single forward + # slashes to satisfy depend.m4 + cygpath_u='sed s,\\\\,/,g' + depmode=msvc7 +fi + +if test "$depmode" = xlc; then + # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency informations. + gccflag=-qmakedep=gcc,-MF + depmode=gcc +fi + +case "$depmode" in +gcc3) +## gcc 3 implements dependency tracking that does exactly what +## we want. Yay! Note: for some reason libtool 1.4 doesn't like +## it if -MD -MP comes after the -MF stuff. Hmm. +## Unfortunately, FreeBSD c89 acceptance of flags depends upon +## the command line argument order; so add the flags where they +## appear in depend2.am. Note that the slowdown incurred here +## affects only configure: in makefiles, %FASTDEP% shortcuts this. + for arg + do + case $arg in + -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; + *) set fnord "$@" "$arg" ;; + esac + shift # fnord + shift # $arg + done + "$@" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + mv "$tmpdepfile" "$depfile" + ;; + +gcc) +## There are various ways to get dependency output from gcc. Here's +## why we pick this rather obscure method: +## - Don't want to use -MD because we'd like the dependencies to end +## up in a subdir. Having to rename by hand is ugly. +## (We might end up doing this anyway to support other compilers.) +## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like +## -MM, not -M (despite what the docs say). +## - Using -M directly means running the compiler twice (even worse +## than renaming). + if test -z "$gccflag"; then + gccflag=-MD, + fi + "$@" -Wp,"$gccflag$tmpdepfile" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + echo "$object : \\" > "$depfile" + alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz +## The second -e expression handles DOS-style file names with drive letters. + sed -e 's/^[^:]*: / /' \ + -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" +## This next piece of magic avoids the "deleted header file" problem. +## The problem is that when a header file which appears in a .P file +## is deleted, the dependency causes make to die (because there is +## typically no way to rebuild the header). We avoid this by adding +## dummy dependencies for each header file. Too bad gcc doesn't do +## this for us directly. + tr ' ' "$nl" < "$tmpdepfile" | +## Some versions of gcc put a space before the ':'. On the theory +## that the space means something, we add a space to the output as +## well. hp depmode also adds that space, but also prefixes the VPATH +## to the object. Take care to not repeat it in the output. +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ + | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +hp) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +sgi) + if test "$libtool" = yes; then + "$@" "-Wp,-MDupdate,$tmpdepfile" + else + "$@" -MDupdate "$tmpdepfile" + fi + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + + if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files + echo "$object : \\" > "$depfile" + + # Clip off the initial element (the dependent). Don't try to be + # clever and replace this with sed code, as IRIX sed won't handle + # lines with more than a fixed number of characters (4096 in + # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; + # the IRIX cc adds comments like '#:fec' to the end of the + # dependency line. + tr ' ' "$nl" < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \ + tr "$nl" ' ' >> "$depfile" + echo >> "$depfile" + + # The second pass generates a dummy entry for each header file. + tr ' ' "$nl" < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ + >> "$depfile" + else + # The sourcefile does not contain any dependencies, so just + # store a dummy comment line, to avoid errors with the Makefile + # "include basename.Plo" scheme. + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +xlc) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +aix) + # The C for AIX Compiler uses -M and outputs the dependencies + # in a .u file. In older versions, this file always lives in the + # current directory. Also, the AIX compiler puts '$object:' at the + # start of each line; $object doesn't have directory information. + # Version 6 uses the directory in both cases. + dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` + test "x$dir" = "x$object" && dir= + base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` + if test "$libtool" = yes; then + tmpdepfile1=$dir$base.u + tmpdepfile2=$base.u + tmpdepfile3=$dir.libs/$base.u + "$@" -Wc,-M + else + tmpdepfile1=$dir$base.u + tmpdepfile2=$dir$base.u + tmpdepfile3=$dir$base.u + "$@" -M + fi + stat=$? + + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" + exit $stat + fi + + for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" + do + test -f "$tmpdepfile" && break + done + if test -f "$tmpdepfile"; then + # Each line is of the form 'foo.o: dependent.h'. + # Do two passes, one to just change these to + # '$object: dependent.h' and one to simply 'dependent.h:'. + sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" + sed -e 's,^.*\.[a-z]*:['"$tab"' ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" + else + # The sourcefile does not contain any dependencies, so just + # store a dummy comment line, to avoid errors with the Makefile + # "include basename.Plo" scheme. + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +icc) + # Intel's C compiler anf tcc (Tiny C Compiler) understand '-MD -MF file'. + # However on + # $CC -MD -MF foo.d -c -o sub/foo.o sub/foo.c + # ICC 7.0 will fill foo.d with something like + # foo.o: sub/foo.c + # foo.o: sub/foo.h + # which is wrong. We want + # sub/foo.o: sub/foo.c + # sub/foo.o: sub/foo.h + # sub/foo.c: + # sub/foo.h: + # ICC 7.1 will output + # foo.o: sub/foo.c sub/foo.h + # and will wrap long lines using '\': + # foo.o: sub/foo.c ... \ + # sub/foo.h ... \ + # ... + # tcc 0.9.26 (FIXME still under development at the moment of writing) + # will emit a similar output, but also prepend the continuation lines + # with horizontal tabulation characters. + "$@" -MD -MF "$tmpdepfile" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + # Each line is of the form 'foo.o: dependent.h', + # or 'foo.o: dep1.h dep2.h \', or ' dep3.h dep4.h \'. + # Do two passes, one to just change these to + # '$object: dependent.h' and one to simply 'dependent.h:'. + sed -e "s/^[ $tab][ $tab]*/ /" -e "s,^[^:]*:,$object :," \ + < "$tmpdepfile" > "$depfile" + sed ' + s/[ '"$tab"'][ '"$tab"']*/ /g + s/^ *// + s/ *\\*$// + s/^[^:]*: *// + /^$/d + /:$/d + s/$/ :/ + ' < "$tmpdepfile" >> "$depfile" + rm -f "$tmpdepfile" + ;; + +hp2) + # The "hp" stanza above does not work with aCC (C++) and HP's ia64 + # compilers, which have integrated preprocessors. The correct option + # to use with these is +Maked; it writes dependencies to a file named + # 'foo.d', which lands next to the object file, wherever that + # happens to be. + # Much of this is similar to the tru64 case; see comments there. + dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` + test "x$dir" = "x$object" && dir= + base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` + if test "$libtool" = yes; then + tmpdepfile1=$dir$base.d + tmpdepfile2=$dir.libs/$base.d + "$@" -Wc,+Maked + else + tmpdepfile1=$dir$base.d + tmpdepfile2=$dir$base.d + "$@" +Maked + fi + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile1" "$tmpdepfile2" + exit $stat + fi + + for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" + do + test -f "$tmpdepfile" && break + done + if test -f "$tmpdepfile"; then + sed -e "s,^.*\.[a-z]*:,$object:," "$tmpdepfile" > "$depfile" + # Add 'dependent.h:' lines. + sed -ne '2,${ + s/^ *// + s/ \\*$// + s/$/:/ + p + }' "$tmpdepfile" >> "$depfile" + else + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" "$tmpdepfile2" + ;; + +tru64) + # The Tru64 compiler uses -MD to generate dependencies as a side + # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. + # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put + # dependencies in 'foo.d' instead, so we check for that too. + # Subdirectories are respected. + dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` + test "x$dir" = "x$object" && dir= + base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` + + if test "$libtool" = yes; then + # With Tru64 cc, shared objects can also be used to make a + # static library. This mechanism is used in libtool 1.4 series to + # handle both shared and static libraries in a single compilation. + # With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d. + # + # With libtool 1.5 this exception was removed, and libtool now + # generates 2 separate objects for the 2 libraries. These two + # compilations output dependencies in $dir.libs/$base.o.d and + # in $dir$base.o.d. We have to check for both files, because + # one of the two compilations can be disabled. We should prefer + # $dir$base.o.d over $dir.libs/$base.o.d because the latter is + # automatically cleaned when .libs/ is deleted, while ignoring + # the former would cause a distcleancheck panic. + tmpdepfile1=$dir.libs/$base.lo.d # libtool 1.4 + tmpdepfile2=$dir$base.o.d # libtool 1.5 + tmpdepfile3=$dir.libs/$base.o.d # libtool 1.5 + tmpdepfile4=$dir.libs/$base.d # Compaq CCC V6.2-504 + "$@" -Wc,-MD + else + tmpdepfile1=$dir$base.o.d + tmpdepfile2=$dir$base.d + tmpdepfile3=$dir$base.d + tmpdepfile4=$dir$base.d + "$@" -MD + fi + + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" + exit $stat + fi + + for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" + do + test -f "$tmpdepfile" && break + done + if test -f "$tmpdepfile"; then + sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" + sed -e 's,^.*\.[a-z]*:['"$tab"' ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" + else + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +msvc7) + if test "$libtool" = yes; then + showIncludes=-Wc,-showIncludes + else + showIncludes=-showIncludes + fi + "$@" $showIncludes > "$tmpdepfile" + stat=$? + grep -v '^Note: including file: ' "$tmpdepfile" + if test "$stat" = 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + echo "$object : \\" > "$depfile" + # The first sed program below extracts the file names and escapes + # backslashes for cygpath. The second sed program outputs the file + # name when reading, but also accumulates all include files in the + # hold buffer in order to output them again at the end. This only + # works with sed implementations that can handle large buffers. + sed < "$tmpdepfile" -n ' +/^Note: including file: *\(.*\)/ { + s//\1/ + s/\\/\\\\/g + p +}' | $cygpath_u | sort -u | sed -n ' +s/ /\\ /g +s/\(.*\)/'"$tab"'\1 \\/p +s/.\(.*\) \\/\1:/ +H +$ { + s/.*/'"$tab"'/ + G + p +}' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +msvc7msys) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +#nosideeffect) + # This comment above is used by automake to tell side-effect + # dependency tracking mechanisms from slower ones. + +dashmstdout) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout, regardless of -o. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test "X$1" != 'X--mode=compile'; do + shift + done + shift + fi + + # Remove '-o $object'. + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + test -z "$dashmflag" && dashmflag=-M + # Require at least two characters before searching for ':' + # in the target name. This is to cope with DOS-style filenames: + # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. + "$@" $dashmflag | + sed 's:^['"$tab"' ]*[^:'"$tab"' ][^:][^:]*\:['"$tab"' ]*:'"$object"'\: :' > "$tmpdepfile" + rm -f "$depfile" + cat < "$tmpdepfile" > "$depfile" + tr ' ' "$nl" < "$tmpdepfile" | \ +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +dashXmstdout) + # This case only exists to satisfy depend.m4. It is never actually + # run, as this mode is specially recognized in the preamble. + exit 1 + ;; + +makedepend) + "$@" || exit $? + # Remove any Libtool call + if test "$libtool" = yes; then + while test "X$1" != 'X--mode=compile'; do + shift + done + shift + fi + # X makedepend + shift + cleared=no eat=no + for arg + do + case $cleared in + no) + set ""; shift + cleared=yes ;; + esac + if test $eat = yes; then + eat=no + continue + fi + case "$arg" in + -D*|-I*) + set fnord "$@" "$arg"; shift ;; + # Strip any option that makedepend may not understand. Remove + # the object too, otherwise makedepend will parse it as a source file. + -arch) + eat=yes ;; + -*|$object) + ;; + *) + set fnord "$@" "$arg"; shift ;; + esac + done + obj_suffix=`echo "$object" | sed 's/^.*\././'` + touch "$tmpdepfile" + ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" + rm -f "$depfile" + # makedepend may prepend the VPATH from the source file name to the object. + # No need to regex-escape $object, excess matching of '.' is harmless. + sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" + sed '1,2d' "$tmpdepfile" | tr ' ' "$nl" | \ +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" "$tmpdepfile".bak + ;; + +cpp) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test "X$1" != 'X--mode=compile'; do + shift + done + shift + fi + + # Remove '-o $object'. + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + "$@" -E | + sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ + -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' | + sed '$ s: \\$::' > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + cat < "$tmpdepfile" >> "$depfile" + sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +msvisualcpp) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test "X$1" != 'X--mode=compile'; do + shift + done + shift + fi + + IFS=" " + for arg + do + case "$arg" in + -o) + shift + ;; + $object) + shift + ;; + "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") + set fnord "$@" + shift + shift + ;; + *) + set fnord "$@" "$arg" + shift + shift + ;; + esac + done + "$@" -E 2>/dev/null | + sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" + echo "$tab" >> "$depfile" + sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +msvcmsys) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +none) + exec "$@" + ;; + +*) + echo "Unknown depmode $depmode" 1>&2 + exit 1 + ;; +esac + +exit 0 + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC" +# time-stamp-end: "; # UTC" +# End: diff --git a/components/external/SQLite-3.8.1/autoconf/install-sh b/components/external/SQLite-3.8.1/autoconf/install-sh new file mode 100644 index 0000000000000000000000000000000000000000..a9244eb0786534553fdd9eb0050bb4b172bad0a3 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/install-sh @@ -0,0 +1,527 @@ +#!/bin/sh +# install - install a program, script, or datafile + +scriptversion=2011-01-19.21; # UTC + +# This originates from X11R5 (mit/util/scripts/install.sh), which was +# later released in X11R6 (xc/config/util/install.sh) with the +# following copyright and license. +# +# Copyright (C) 1994 X Consortium +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Except as contained in this notice, the name of the X Consortium shall not +# be used in advertising or otherwise to promote the sale, use or other deal- +# ings in this Software without prior written authorization from the X Consor- +# tium. +# +# +# FSF changes to this file are in the public domain. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# `make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. + +nl=' +' +IFS=" "" $nl" + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit=${DOITPROG-} +if test -z "$doit"; then + doit_exec=exec +else + doit_exec=$doit +fi + +# Put in absolute file names if you don't have them in your path; +# or use environment vars. + +chgrpprog=${CHGRPPROG-chgrp} +chmodprog=${CHMODPROG-chmod} +chownprog=${CHOWNPROG-chown} +cmpprog=${CMPPROG-cmp} +cpprog=${CPPROG-cp} +mkdirprog=${MKDIRPROG-mkdir} +mvprog=${MVPROG-mv} +rmprog=${RMPROG-rm} +stripprog=${STRIPPROG-strip} + +posix_glob='?' +initialize_posix_glob=' + test "$posix_glob" != "?" || { + if (set -f) 2>/dev/null; then + posix_glob= + else + posix_glob=: + fi + } +' + +posix_mkdir= + +# Desired mode of installed file. +mode=0755 + +chgrpcmd= +chmodcmd=$chmodprog +chowncmd= +mvcmd=$mvprog +rmcmd="$rmprog -f" +stripcmd= + +src= +dst= +dir_arg= +dst_arg= + +copy_on_change=false +no_target_directory= + +usage="\ +Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE + or: $0 [OPTION]... SRCFILES... DIRECTORY + or: $0 [OPTION]... -t DIRECTORY SRCFILES... + or: $0 [OPTION]... -d DIRECTORIES... + +In the 1st form, copy SRCFILE to DSTFILE. +In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. +In the 4th, create DIRECTORIES. + +Options: + --help display this help and exit. + --version display version info and exit. + + -c (ignored) + -C install only if different (preserve the last data modification time) + -d create directories instead of installing files. + -g GROUP $chgrpprog installed files to GROUP. + -m MODE $chmodprog installed files to MODE. + -o USER $chownprog installed files to USER. + -s $stripprog installed files. + -t DIRECTORY install into DIRECTORY. + -T report an error if DSTFILE is a directory. + +Environment variables override the default commands: + CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG + RMPROG STRIPPROG +" + +while test $# -ne 0; do + case $1 in + -c) ;; + + -C) copy_on_change=true;; + + -d) dir_arg=true;; + + -g) chgrpcmd="$chgrpprog $2" + shift;; + + --help) echo "$usage"; exit $?;; + + -m) mode=$2 + case $mode in + *' '* | *' '* | *' +'* | *'*'* | *'?'* | *'['*) + echo "$0: invalid mode: $mode" >&2 + exit 1;; + esac + shift;; + + -o) chowncmd="$chownprog $2" + shift;; + + -s) stripcmd=$stripprog;; + + -t) dst_arg=$2 + # Protect names problematic for `test' and other utilities. + case $dst_arg in + -* | [=\(\)!]) dst_arg=./$dst_arg;; + esac + shift;; + + -T) no_target_directory=true;; + + --version) echo "$0 $scriptversion"; exit $?;; + + --) shift + break;; + + -*) echo "$0: invalid option: $1" >&2 + exit 1;; + + *) break;; + esac + shift +done + +if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then + # When -d is used, all remaining arguments are directories to create. + # When -t is used, the destination is already specified. + # Otherwise, the last argument is the destination. Remove it from $@. + for arg + do + if test -n "$dst_arg"; then + # $@ is not empty: it contains at least $arg. + set fnord "$@" "$dst_arg" + shift # fnord + fi + shift # arg + dst_arg=$arg + # Protect names problematic for `test' and other utilities. + case $dst_arg in + -* | [=\(\)!]) dst_arg=./$dst_arg;; + esac + done +fi + +if test $# -eq 0; then + if test -z "$dir_arg"; then + echo "$0: no input file specified." >&2 + exit 1 + fi + # It's OK to call `install-sh -d' without argument. + # This can happen when creating conditional directories. + exit 0 +fi + +if test -z "$dir_arg"; then + do_exit='(exit $ret); exit $ret' + trap "ret=129; $do_exit" 1 + trap "ret=130; $do_exit" 2 + trap "ret=141; $do_exit" 13 + trap "ret=143; $do_exit" 15 + + # Set umask so as not to create temps with too-generous modes. + # However, 'strip' requires both read and write access to temps. + case $mode in + # Optimize common cases. + *644) cp_umask=133;; + *755) cp_umask=22;; + + *[0-7]) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw='% 200' + fi + cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; + *) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw=,u+rw + fi + cp_umask=$mode$u_plus_rw;; + esac +fi + +for src +do + # Protect names problematic for `test' and other utilities. + case $src in + -* | [=\(\)!]) src=./$src;; + esac + + if test -n "$dir_arg"; then + dst=$src + dstdir=$dst + test -d "$dstdir" + dstdir_status=$? + else + + # Waiting for this to be detected by the "$cpprog $src $dsttmp" command + # might cause directories to be created, which would be especially bad + # if $src (and thus $dsttmp) contains '*'. + if test ! -f "$src" && test ! -d "$src"; then + echo "$0: $src does not exist." >&2 + exit 1 + fi + + if test -z "$dst_arg"; then + echo "$0: no destination specified." >&2 + exit 1 + fi + dst=$dst_arg + + # If destination is a directory, append the input filename; won't work + # if double slashes aren't ignored. + if test -d "$dst"; then + if test -n "$no_target_directory"; then + echo "$0: $dst_arg: Is a directory" >&2 + exit 1 + fi + dstdir=$dst + dst=$dstdir/`basename "$src"` + dstdir_status=0 + else + # Prefer dirname, but fall back on a substitute if dirname fails. + dstdir=` + (dirname "$dst") 2>/dev/null || + expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$dst" : 'X\(//\)[^/]' \| \ + X"$dst" : 'X\(//\)$' \| \ + X"$dst" : 'X\(/\)' \| . 2>/dev/null || + echo X"$dst" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q' + ` + + test -d "$dstdir" + dstdir_status=$? + fi + fi + + obsolete_mkdir_used=false + + if test $dstdir_status != 0; then + case $posix_mkdir in + '') + # Create intermediate dirs using mode 755 as modified by the umask. + # This is like FreeBSD 'install' as of 1997-10-28. + umask=`umask` + case $stripcmd.$umask in + # Optimize common cases. + *[2367][2367]) mkdir_umask=$umask;; + .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; + + *[0-7]) + mkdir_umask=`expr $umask + 22 \ + - $umask % 100 % 40 + $umask % 20 \ + - $umask % 10 % 4 + $umask % 2 + `;; + *) mkdir_umask=$umask,go-w;; + esac + + # With -d, create the new directory with the user-specified mode. + # Otherwise, rely on $mkdir_umask. + if test -n "$dir_arg"; then + mkdir_mode=-m$mode + else + mkdir_mode= + fi + + posix_mkdir=false + case $umask in + *[123567][0-7][0-7]) + # POSIX mkdir -p sets u+wx bits regardless of umask, which + # is incompatible with FreeBSD 'install' when (umask & 300) != 0. + ;; + *) + tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ + trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 + + if (umask $mkdir_umask && + exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 + then + if test -z "$dir_arg" || { + # Check for POSIX incompatibilities with -m. + # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or + # other-writeable bit of parent directory when it shouldn't. + # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. + ls_ld_tmpdir=`ls -ld "$tmpdir"` + case $ls_ld_tmpdir in + d????-?r-*) different_mode=700;; + d????-?--*) different_mode=755;; + *) false;; + esac && + $mkdirprog -m$different_mode -p -- "$tmpdir" && { + ls_ld_tmpdir_1=`ls -ld "$tmpdir"` + test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" + } + } + then posix_mkdir=: + fi + rmdir "$tmpdir/d" "$tmpdir" + else + # Remove any dirs left behind by ancient mkdir implementations. + rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null + fi + trap '' 0;; + esac;; + esac + + if + $posix_mkdir && ( + umask $mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" + ) + then : + else + + # The umask is ridiculous, or mkdir does not conform to POSIX, + # or it failed possibly due to a race condition. Create the + # directory the slow way, step by step, checking for races as we go. + + case $dstdir in + /*) prefix='/';; + [-=\(\)!]*) prefix='./';; + *) prefix='';; + esac + + eval "$initialize_posix_glob" + + oIFS=$IFS + IFS=/ + $posix_glob set -f + set fnord $dstdir + shift + $posix_glob set +f + IFS=$oIFS + + prefixes= + + for d + do + test X"$d" = X && continue + + prefix=$prefix$d + if test -d "$prefix"; then + prefixes= + else + if $posix_mkdir; then + (umask=$mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break + # Don't fail if two instances are running concurrently. + test -d "$prefix" || exit 1 + else + case $prefix in + *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; + *) qprefix=$prefix;; + esac + prefixes="$prefixes '$qprefix'" + fi + fi + prefix=$prefix/ + done + + if test -n "$prefixes"; then + # Don't fail if two instances are running concurrently. + (umask $mkdir_umask && + eval "\$doit_exec \$mkdirprog $prefixes") || + test -d "$dstdir" || exit 1 + obsolete_mkdir_used=true + fi + fi + fi + + if test -n "$dir_arg"; then + { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && + { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && + { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || + test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 + else + + # Make a couple of temp file names in the proper directory. + dsttmp=$dstdir/_inst.$$_ + rmtmp=$dstdir/_rm.$$_ + + # Trap to clean up those temp files at exit. + trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 + + # Copy the file name to the temp name. + (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && + + # and set any options; do chmod last to preserve setuid bits. + # + # If any of these fail, we abort the whole thing. If we want to + # ignore errors from any of these, just make sure not to ignore + # errors from the above "$doit $cpprog $src $dsttmp" command. + # + { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && + { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && + { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && + { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && + + # If -C, don't bother to copy if it wouldn't change the file. + if $copy_on_change && + old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && + new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && + + eval "$initialize_posix_glob" && + $posix_glob set -f && + set X $old && old=:$2:$4:$5:$6 && + set X $new && new=:$2:$4:$5:$6 && + $posix_glob set +f && + + test "$old" = "$new" && + $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 + then + rm -f "$dsttmp" + else + # Rename the file to the real destination. + $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || + + # The rename failed, perhaps because mv can't rename something else + # to itself, or perhaps because mv is so ancient that it does not + # support -f. + { + # Now remove or move aside any old file at destination location. + # We try this two ways since rm can't unlink itself on some + # systems and the destination file might be busy for other + # reasons. In this case, the final cleanup might fail but the new + # file should still install successfully. + { + test ! -f "$dst" || + $doit $rmcmd -f "$dst" 2>/dev/null || + { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && + { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } + } || + { echo "$0: cannot unlink or rename $dst" >&2 + (exit 1); exit 1 + } + } && + + # Now rename the file to the real destination. + $doit $mvcmd "$dsttmp" "$dst" + } + fi || exit 1 + + trap '' 0 + fi +done + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC" +# time-stamp-end: "; # UTC" +# End: diff --git a/components/external/SQLite-3.8.1/autoconf/ltmain.sh b/components/external/SQLite-3.8.1/autoconf/ltmain.sh new file mode 100644 index 0000000000000000000000000000000000000000..6a2f1166a9faedeae061e75acc6ac6ff389134b1 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/ltmain.sh @@ -0,0 +1,9655 @@ + +# libtool (GNU libtool) 2.4.2 +# Written by Gordon Matzigkeit , 1996 + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, +# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. +# This is free software; see the source for copying conditions. There is NO +# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +# GNU Libtool is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Libtool; see the file COPYING. If not, a copy +# can be downloaded from http://www.gnu.org/licenses/gpl.html, +# or obtained by writing to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +# Usage: $progname [OPTION]... [MODE-ARG]... +# +# Provide generalized library-building support services. +# +# --config show all configuration variables +# --debug enable verbose shell tracing +# -n, --dry-run display commands without modifying any files +# --features display basic configuration information and exit +# --mode=MODE use operation mode MODE +# --preserve-dup-deps don't remove duplicate dependency libraries +# --quiet, --silent don't print informational messages +# --no-quiet, --no-silent +# print informational messages (default) +# --no-warn don't display warning messages +# --tag=TAG use configuration variables from tag TAG +# -v, --verbose print more informational messages than default +# --no-verbose don't print the extra informational messages +# --version print version information +# -h, --help, --help-all print short, long, or detailed help message +# +# MODE must be one of the following: +# +# clean remove files from the build directory +# compile compile a source file into a libtool object +# execute automatically set library path, then run a program +# finish complete the installation of libtool libraries +# install install libraries or executables +# link create a library or an executable +# uninstall remove libraries from an installed directory +# +# MODE-ARGS vary depending on the MODE. When passed as first option, +# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that. +# Try `$progname --help --mode=MODE' for a more detailed description of MODE. +# +# When reporting a bug, please describe a test case to reproduce it and +# include the following information: +# +# host-triplet: $host +# shell: $SHELL +# compiler: $LTCC +# compiler flags: $LTCFLAGS +# linker: $LD (gnu? $with_gnu_ld) +# $progname: (GNU libtool) 2.4.2 +# automake: $automake_version +# autoconf: $autoconf_version +# +# Report bugs to . +# GNU libtool home page: . +# General help using GNU software: . + +PROGRAM=libtool +PACKAGE=libtool +VERSION=2.4.2 +TIMESTAMP="" +package_revision=1.3337 + +# Be Bourne compatible +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac +fi +BIN_SH=xpg4; export BIN_SH # for Tru64 +DUALCASE=1; export DUALCASE # for MKS sh + +# A function that is used when there is no print builtin or printf. +func_fallback_echo () +{ + eval 'cat <<_LTECHO_EOF +$1 +_LTECHO_EOF' +} + +# NLS nuisances: We save the old values to restore during execute mode. +lt_user_locale= +lt_safe_locale= +for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES +do + eval "if test \"\${$lt_var+set}\" = set; then + save_$lt_var=\$$lt_var + $lt_var=C + export $lt_var + lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" + lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" + fi" +done +LC_ALL=C +LANGUAGE=C +export LANGUAGE LC_ALL + +$lt_unset CDPATH + + +# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh +# is ksh but when the shell is invoked as "sh" and the current value of +# the _XPG environment variable is not equal to 1 (one), the special +# positional parameter $0, within a function call, is the name of the +# function. +progpath="$0" + + + +: ${CP="cp -f"} +test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'} +: ${MAKE="make"} +: ${MKDIR="mkdir"} +: ${MV="mv -f"} +: ${RM="rm -f"} +: ${SHELL="${CONFIG_SHELL-/bin/sh}"} +: ${Xsed="$SED -e 1s/^X//"} + +# Global variables: +EXIT_SUCCESS=0 +EXIT_FAILURE=1 +EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. +EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. + +exit_status=$EXIT_SUCCESS + +# Make sure IFS has a sensible default +lt_nl=' +' +IFS=" $lt_nl" + +dirname="s,/[^/]*$,," +basename="s,^.*/,," + +# func_dirname file append nondir_replacement +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +func_dirname () +{ + func_dirname_result=`$ECHO "${1}" | $SED "$dirname"` + if test "X$func_dirname_result" = "X${1}"; then + func_dirname_result="${3}" + else + func_dirname_result="$func_dirname_result${2}" + fi +} # func_dirname may be replaced by extended shell implementation + + +# func_basename file +func_basename () +{ + func_basename_result=`$ECHO "${1}" | $SED "$basename"` +} # func_basename may be replaced by extended shell implementation + + +# func_dirname_and_basename file append nondir_replacement +# perform func_basename and func_dirname in a single function +# call: +# dirname: Compute the dirname of FILE. If nonempty, +# add APPEND to the result, otherwise set result +# to NONDIR_REPLACEMENT. +# value returned in "$func_dirname_result" +# basename: Compute filename of FILE. +# value retuned in "$func_basename_result" +# Implementation must be kept synchronized with func_dirname +# and func_basename. For efficiency, we do not delegate to +# those functions but instead duplicate the functionality here. +func_dirname_and_basename () +{ + # Extract subdirectory from the argument. + func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"` + if test "X$func_dirname_result" = "X${1}"; then + func_dirname_result="${3}" + else + func_dirname_result="$func_dirname_result${2}" + fi + func_basename_result=`$ECHO "${1}" | $SED -e "$basename"` +} # func_dirname_and_basename may be replaced by extended shell implementation + + +# func_stripname prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +# func_strip_suffix prefix name +func_stripname () +{ + case ${2} in + .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; + *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; + esac +} # func_stripname may be replaced by extended shell implementation + + +# These SED scripts presuppose an absolute path with a trailing slash. +pathcar='s,^/\([^/]*\).*$,\1,' +pathcdr='s,^/[^/]*,,' +removedotparts=':dotsl + s@/\./@/@g + t dotsl + s,/\.$,/,' +collapseslashes='s@/\{1,\}@/@g' +finalslash='s,/*$,/,' + +# func_normal_abspath PATH +# Remove doubled-up and trailing slashes, "." path components, +# and cancel out any ".." path components in PATH after making +# it an absolute path. +# value returned in "$func_normal_abspath_result" +func_normal_abspath () +{ + # Start from root dir and reassemble the path. + func_normal_abspath_result= + func_normal_abspath_tpath=$1 + func_normal_abspath_altnamespace= + case $func_normal_abspath_tpath in + "") + # Empty path, that just means $cwd. + func_stripname '' '/' "`pwd`" + func_normal_abspath_result=$func_stripname_result + return + ;; + # The next three entries are used to spot a run of precisely + # two leading slashes without using negated character classes; + # we take advantage of case's first-match behaviour. + ///*) + # Unusual form of absolute path, do nothing. + ;; + //*) + # Not necessarily an ordinary path; POSIX reserves leading '//' + # and for example Cygwin uses it to access remote file shares + # over CIFS/SMB, so we conserve a leading double slash if found. + func_normal_abspath_altnamespace=/ + ;; + /*) + # Absolute path, do nothing. + ;; + *) + # Relative path, prepend $cwd. + func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath + ;; + esac + # Cancel out all the simple stuff to save iterations. We also want + # the path to end with a slash for ease of parsing, so make sure + # there is one (and only one) here. + func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ + -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"` + while :; do + # Processed it all yet? + if test "$func_normal_abspath_tpath" = / ; then + # If we ascended to the root using ".." the result may be empty now. + if test -z "$func_normal_abspath_result" ; then + func_normal_abspath_result=/ + fi + break + fi + func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ + -e "$pathcar"` + func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ + -e "$pathcdr"` + # Figure out what to do with it + case $func_normal_abspath_tcomponent in + "") + # Trailing empty path component, ignore it. + ;; + ..) + # Parent dir; strip last assembled component from result. + func_dirname "$func_normal_abspath_result" + func_normal_abspath_result=$func_dirname_result + ;; + *) + # Actual path component, append it. + func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent + ;; + esac + done + # Restore leading double-slash if one was found on entry. + func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result +} + +# func_relative_path SRCDIR DSTDIR +# generates a relative path from SRCDIR to DSTDIR, with a trailing +# slash if non-empty, suitable for immediately appending a filename +# without needing to append a separator. +# value returned in "$func_relative_path_result" +func_relative_path () +{ + func_relative_path_result= + func_normal_abspath "$1" + func_relative_path_tlibdir=$func_normal_abspath_result + func_normal_abspath "$2" + func_relative_path_tbindir=$func_normal_abspath_result + + # Ascend the tree starting from libdir + while :; do + # check if we have found a prefix of bindir + case $func_relative_path_tbindir in + $func_relative_path_tlibdir) + # found an exact match + func_relative_path_tcancelled= + break + ;; + $func_relative_path_tlibdir*) + # found a matching prefix + func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" + func_relative_path_tcancelled=$func_stripname_result + if test -z "$func_relative_path_result"; then + func_relative_path_result=. + fi + break + ;; + *) + func_dirname $func_relative_path_tlibdir + func_relative_path_tlibdir=${func_dirname_result} + if test "x$func_relative_path_tlibdir" = x ; then + # Have to descend all the way to the root! + func_relative_path_result=../$func_relative_path_result + func_relative_path_tcancelled=$func_relative_path_tbindir + break + fi + func_relative_path_result=../$func_relative_path_result + ;; + esac + done + + # Now calculate path; take care to avoid doubling-up slashes. + func_stripname '' '/' "$func_relative_path_result" + func_relative_path_result=$func_stripname_result + func_stripname '/' '/' "$func_relative_path_tcancelled" + if test "x$func_stripname_result" != x ; then + func_relative_path_result=${func_relative_path_result}/${func_stripname_result} + fi + + # Normalisation. If bindir is libdir, return empty string, + # else relative path ending with a slash; either way, target + # file name can be directly appended. + if test ! -z "$func_relative_path_result"; then + func_stripname './' '' "$func_relative_path_result/" + func_relative_path_result=$func_stripname_result + fi +} + +# The name of this program: +func_dirname_and_basename "$progpath" +progname=$func_basename_result + +# Make sure we have an absolute path for reexecution: +case $progpath in + [\\/]*|[A-Za-z]:\\*) ;; + *[\\/]*) + progdir=$func_dirname_result + progdir=`cd "$progdir" && pwd` + progpath="$progdir/$progname" + ;; + *) + save_IFS="$IFS" + IFS=${PATH_SEPARATOR-:} + for progdir in $PATH; do + IFS="$save_IFS" + test -x "$progdir/$progname" && break + done + IFS="$save_IFS" + test -n "$progdir" || progdir=`pwd` + progpath="$progdir/$progname" + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed="${SED}"' -e 1s/^X//' +sed_quote_subst='s/\([`"$\\]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\(["`\\]\)/\\\1/g' + +# Sed substitution that turns a string into a regex matching for the +# string literally. +sed_make_literal_regex='s,[].[^$\\*\/],\\&,g' + +# Sed substitution that converts a w32 file name or path +# which contains forward slashes, into one that contains +# (escaped) backslashes. A very naive implementation. +lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' + +# Re-`\' parameter expansions in output of double_quote_subst that were +# `\'-ed in input to the same. If an odd number of `\' preceded a '$' +# in input to double_quote_subst, that '$' was protected from expansion. +# Since each input `\' is now two `\'s, look for any number of runs of +# four `\'s followed by two `\'s and then a '$'. `\' that '$'. +bs='\\' +bs2='\\\\' +bs4='\\\\\\\\' +dollar='\$' +sed_double_backslash="\ + s/$bs4/&\\ +/g + s/^$bs2$dollar/$bs&/ + s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g + s/\n//g" + +# Standard options: +opt_dry_run=false +opt_help=false +opt_quiet=false +opt_verbose=false +opt_warning=: + +# func_echo arg... +# Echo program name prefixed message, along with the current mode +# name if it has been set yet. +func_echo () +{ + $ECHO "$progname: ${opt_mode+$opt_mode: }$*" +} + +# func_verbose arg... +# Echo program name prefixed message in verbose mode only. +func_verbose () +{ + $opt_verbose && func_echo ${1+"$@"} + + # A bug in bash halts the script if the last line of a function + # fails when set -e is in force, so we need another command to + # work around that: + : +} + +# func_echo_all arg... +# Invoke $ECHO with all args, space-separated. +func_echo_all () +{ + $ECHO "$*" +} + +# func_error arg... +# Echo program name prefixed message to standard error. +func_error () +{ + $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2 +} + +# func_warning arg... +# Echo program name prefixed warning message to standard error. +func_warning () +{ + $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2 + + # bash bug again: + : +} + +# func_fatal_error arg... +# Echo program name prefixed message to standard error, and exit. +func_fatal_error () +{ + func_error ${1+"$@"} + exit $EXIT_FAILURE +} + +# func_fatal_help arg... +# Echo program name prefixed message to standard error, followed by +# a help hint, and exit. +func_fatal_help () +{ + func_error ${1+"$@"} + func_fatal_error "$help" +} +help="Try \`$progname --help' for more information." ## default + + +# func_grep expression filename +# Check whether EXPRESSION matches any line of FILENAME, without output. +func_grep () +{ + $GREP "$1" "$2" >/dev/null 2>&1 +} + + +# func_mkdir_p directory-path +# Make sure the entire path to DIRECTORY-PATH is available. +func_mkdir_p () +{ + my_directory_path="$1" + my_dir_list= + + if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then + + # Protect directory names starting with `-' + case $my_directory_path in + -*) my_directory_path="./$my_directory_path" ;; + esac + + # While some portion of DIR does not yet exist... + while test ! -d "$my_directory_path"; do + # ...make a list in topmost first order. Use a colon delimited + # list incase some portion of path contains whitespace. + my_dir_list="$my_directory_path:$my_dir_list" + + # If the last portion added has no slash in it, the list is done + case $my_directory_path in */*) ;; *) break ;; esac + + # ...otherwise throw away the child directory and loop + my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"` + done + my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'` + + save_mkdir_p_IFS="$IFS"; IFS=':' + for my_dir in $my_dir_list; do + IFS="$save_mkdir_p_IFS" + # mkdir can fail with a `File exist' error if two processes + # try to create one of the directories concurrently. Don't + # stop in that case! + $MKDIR "$my_dir" 2>/dev/null || : + done + IFS="$save_mkdir_p_IFS" + + # Bail out if we (or some other process) failed to create a directory. + test -d "$my_directory_path" || \ + func_fatal_error "Failed to create \`$1'" + fi +} + + +# func_mktempdir [string] +# Make a temporary directory that won't clash with other running +# libtool processes, and avoids race conditions if possible. If +# given, STRING is the basename for that directory. +func_mktempdir () +{ + my_template="${TMPDIR-/tmp}/${1-$progname}" + + if test "$opt_dry_run" = ":"; then + # Return a directory name, but don't create it in dry-run mode + my_tmpdir="${my_template}-$$" + else + + # If mktemp works, use that first and foremost + my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` + + if test ! -d "$my_tmpdir"; then + # Failing that, at least try and use $RANDOM to avoid a race + my_tmpdir="${my_template}-${RANDOM-0}$$" + + save_mktempdir_umask=`umask` + umask 0077 + $MKDIR "$my_tmpdir" + umask $save_mktempdir_umask + fi + + # If we're not in dry-run mode, bomb out on failure + test -d "$my_tmpdir" || \ + func_fatal_error "cannot create temporary directory \`$my_tmpdir'" + fi + + $ECHO "$my_tmpdir" +} + + +# func_quote_for_eval arg +# Aesthetically quote ARG to be evaled later. +# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT +# is double-quoted, suitable for a subsequent eval, whereas +# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters +# which are still active within double quotes backslashified. +func_quote_for_eval () +{ + case $1 in + *[\\\`\"\$]*) + func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;; + *) + func_quote_for_eval_unquoted_result="$1" ;; + esac + + case $func_quote_for_eval_unquoted_result in + # Double-quote args containing shell metacharacters to delay + # word splitting, command substitution and and variable + # expansion for a subsequent eval. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" + ;; + *) + func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" + esac +} + + +# func_quote_for_expand arg +# Aesthetically quote ARG to be evaled later; same as above, +# but do not quote variable references. +func_quote_for_expand () +{ + case $1 in + *[\\\`\"]*) + my_arg=`$ECHO "$1" | $SED \ + -e "$double_quote_subst" -e "$sed_double_backslash"` ;; + *) + my_arg="$1" ;; + esac + + case $my_arg in + # Double-quote args containing shell metacharacters to delay + # word splitting and command substitution for a subsequent eval. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + my_arg="\"$my_arg\"" + ;; + esac + + func_quote_for_expand_result="$my_arg" +} + + +# func_show_eval cmd [fail_exp] +# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. +func_show_eval () +{ + my_cmd="$1" + my_fail_exp="${2-:}" + + ${opt_silent-false} || { + func_quote_for_expand "$my_cmd" + eval "func_echo $func_quote_for_expand_result" + } + + if ${opt_dry_run-false}; then :; else + eval "$my_cmd" + my_status=$? + if test "$my_status" -eq 0; then :; else + eval "(exit $my_status); $my_fail_exp" + fi + fi +} + + +# func_show_eval_locale cmd [fail_exp] +# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. Use the saved locale for evaluation. +func_show_eval_locale () +{ + my_cmd="$1" + my_fail_exp="${2-:}" + + ${opt_silent-false} || { + func_quote_for_expand "$my_cmd" + eval "func_echo $func_quote_for_expand_result" + } + + if ${opt_dry_run-false}; then :; else + eval "$lt_user_locale + $my_cmd" + my_status=$? + eval "$lt_safe_locale" + if test "$my_status" -eq 0; then :; else + eval "(exit $my_status); $my_fail_exp" + fi + fi +} + +# func_tr_sh +# Turn $1 into a string suitable for a shell variable name. +# Result is stored in $func_tr_sh_result. All characters +# not in the set a-zA-Z0-9_ are replaced with '_'. Further, +# if $1 begins with a digit, a '_' is prepended as well. +func_tr_sh () +{ + case $1 in + [0-9]* | *[!a-zA-Z0-9_]*) + func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'` + ;; + * ) + func_tr_sh_result=$1 + ;; + esac +} + + +# func_version +# Echo version message to standard output and exit. +func_version () +{ + $opt_debug + + $SED -n '/(C)/!b go + :more + /\./!{ + N + s/\n# / / + b more + } + :go + /^# '$PROGRAM' (GNU /,/# warranty; / { + s/^# // + s/^# *$// + s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ + p + }' < "$progpath" + exit $? +} + +# func_usage +# Echo short help message to standard output and exit. +func_usage () +{ + $opt_debug + + $SED -n '/^# Usage:/,/^# *.*--help/ { + s/^# // + s/^# *$// + s/\$progname/'$progname'/ + p + }' < "$progpath" + echo + $ECHO "run \`$progname --help | more' for full usage" + exit $? +} + +# func_help [NOEXIT] +# Echo long help message to standard output and exit, +# unless 'noexit' is passed as argument. +func_help () +{ + $opt_debug + + $SED -n '/^# Usage:/,/# Report bugs to/ { + :print + s/^# // + s/^# *$// + s*\$progname*'$progname'* + s*\$host*'"$host"'* + s*\$SHELL*'"$SHELL"'* + s*\$LTCC*'"$LTCC"'* + s*\$LTCFLAGS*'"$LTCFLAGS"'* + s*\$LD*'"$LD"'* + s/\$with_gnu_ld/'"$with_gnu_ld"'/ + s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/ + s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/ + p + d + } + /^# .* home page:/b print + /^# General help using/b print + ' < "$progpath" + ret=$? + if test -z "$1"; then + exit $ret + fi +} + +# func_missing_arg argname +# Echo program name prefixed message to standard error and set global +# exit_cmd. +func_missing_arg () +{ + $opt_debug + + func_error "missing argument for $1." + exit_cmd=exit +} + + +# func_split_short_opt shortopt +# Set func_split_short_opt_name and func_split_short_opt_arg shell +# variables after splitting SHORTOPT after the 2nd character. +func_split_short_opt () +{ + my_sed_short_opt='1s/^\(..\).*$/\1/;q' + my_sed_short_rest='1s/^..\(.*\)$/\1/;q' + + func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"` + func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"` +} # func_split_short_opt may be replaced by extended shell implementation + + +# func_split_long_opt longopt +# Set func_split_long_opt_name and func_split_long_opt_arg shell +# variables after splitting LONGOPT at the `=' sign. +func_split_long_opt () +{ + my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q' + my_sed_long_arg='1s/^--[^=]*=//' + + func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"` + func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"` +} # func_split_long_opt may be replaced by extended shell implementation + +exit_cmd=: + + + + + +magic="%%%MAGIC variable%%%" +magic_exe="%%%MAGIC EXE variable%%%" + +# Global variables. +nonopt= +preserve_args= +lo2o="s/\\.lo\$/.${objext}/" +o2lo="s/\\.${objext}\$/.lo/" +extracted_archives= +extracted_serial=0 + +# If this variable is set in any of the actions, the command in it +# will be execed at the end. This prevents here-documents from being +# left over by shells. +exec_cmd= + +# func_append var value +# Append VALUE to the end of shell variable VAR. +func_append () +{ + eval "${1}=\$${1}\${2}" +} # func_append may be replaced by extended shell implementation + +# func_append_quoted var value +# Quote VALUE and append to the end of shell variable VAR, separated +# by a space. +func_append_quoted () +{ + func_quote_for_eval "${2}" + eval "${1}=\$${1}\\ \$func_quote_for_eval_result" +} # func_append_quoted may be replaced by extended shell implementation + + +# func_arith arithmetic-term... +func_arith () +{ + func_arith_result=`expr "${@}"` +} # func_arith may be replaced by extended shell implementation + + +# func_len string +# STRING may not start with a hyphen. +func_len () +{ + func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len` +} # func_len may be replaced by extended shell implementation + + +# func_lo2o object +func_lo2o () +{ + func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"` +} # func_lo2o may be replaced by extended shell implementation + + +# func_xform libobj-or-source +func_xform () +{ + func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'` +} # func_xform may be replaced by extended shell implementation + + +# func_fatal_configuration arg... +# Echo program name prefixed message to standard error, followed by +# a configuration failure hint, and exit. +func_fatal_configuration () +{ + func_error ${1+"$@"} + func_error "See the $PACKAGE documentation for more information." + func_fatal_error "Fatal configuration error." +} + + +# func_config +# Display the configuration for all the tags in this script. +func_config () +{ + re_begincf='^# ### BEGIN LIBTOOL' + re_endcf='^# ### END LIBTOOL' + + # Default configuration. + $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" + + # Now print the configurations for the tags. + for tagname in $taglist; do + $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" + done + + exit $? +} + +# func_features +# Display the features supported by this script. +func_features () +{ + echo "host: $host" + if test "$build_libtool_libs" = yes; then + echo "enable shared libraries" + else + echo "disable shared libraries" + fi + if test "$build_old_libs" = yes; then + echo "enable static libraries" + else + echo "disable static libraries" + fi + + exit $? +} + +# func_enable_tag tagname +# Verify that TAGNAME is valid, and either flag an error and exit, or +# enable the TAGNAME tag. We also add TAGNAME to the global $taglist +# variable here. +func_enable_tag () +{ + # Global variable: + tagname="$1" + + re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" + re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" + sed_extractcf="/$re_begincf/,/$re_endcf/p" + + # Validate tagname. + case $tagname in + *[!-_A-Za-z0-9,/]*) + func_fatal_error "invalid tag name: $tagname" + ;; + esac + + # Don't test for the "default" C tag, as we know it's + # there but not specially marked. + case $tagname in + CC) ;; + *) + if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then + taglist="$taglist $tagname" + + # Evaluate the configuration. Be careful to quote the path + # and the sed script, to avoid splitting on whitespace, but + # also don't use non-portable quotes within backquotes within + # quotes we have to do it in 2 steps: + extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` + eval "$extractedcf" + else + func_error "ignoring unknown tag $tagname" + fi + ;; + esac +} + +# func_check_version_match +# Ensure that we are using m4 macros, and libtool script from the same +# release of libtool. +func_check_version_match () +{ + if test "$package_revision" != "$macro_revision"; then + if test "$VERSION" != "$macro_version"; then + if test -z "$macro_version"; then + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from an older release. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from $PACKAGE $macro_version. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + fi + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, +$progname: but the definition of this LT_INIT comes from revision $macro_revision. +$progname: You should recreate aclocal.m4 with macros from revision $package_revision +$progname: of $PACKAGE $VERSION and run autoconf again. +_LT_EOF + fi + + exit $EXIT_MISMATCH + fi +} + + +# Shorthand for --mode=foo, only valid as the first argument +case $1 in +clean|clea|cle|cl) + shift; set dummy --mode clean ${1+"$@"}; shift + ;; +compile|compil|compi|comp|com|co|c) + shift; set dummy --mode compile ${1+"$@"}; shift + ;; +execute|execut|execu|exec|exe|ex|e) + shift; set dummy --mode execute ${1+"$@"}; shift + ;; +finish|finis|fini|fin|fi|f) + shift; set dummy --mode finish ${1+"$@"}; shift + ;; +install|instal|insta|inst|ins|in|i) + shift; set dummy --mode install ${1+"$@"}; shift + ;; +link|lin|li|l) + shift; set dummy --mode link ${1+"$@"}; shift + ;; +uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) + shift; set dummy --mode uninstall ${1+"$@"}; shift + ;; +esac + + + +# Option defaults: +opt_debug=: +opt_dry_run=false +opt_config=false +opt_preserve_dup_deps=false +opt_features=false +opt_finish=false +opt_help=false +opt_help_all=false +opt_silent=: +opt_warning=: +opt_verbose=: +opt_silent=false +opt_verbose=false + + +# Parse options once, thoroughly. This comes as soon as possible in the +# script to make things like `--version' happen as quickly as we can. +{ + # this just eases exit handling + while test $# -gt 0; do + opt="$1" + shift + case $opt in + --debug|-x) opt_debug='set -x' + func_echo "enabling shell trace mode" + $opt_debug + ;; + --dry-run|--dryrun|-n) + opt_dry_run=: + ;; + --config) + opt_config=: +func_config + ;; + --dlopen|-dlopen) + optarg="$1" + opt_dlopen="${opt_dlopen+$opt_dlopen +}$optarg" + shift + ;; + --preserve-dup-deps) + opt_preserve_dup_deps=: + ;; + --features) + opt_features=: +func_features + ;; + --finish) + opt_finish=: +set dummy --mode finish ${1+"$@"}; shift + ;; + --help) + opt_help=: + ;; + --help-all) + opt_help_all=: +opt_help=': help-all' + ;; + --mode) + test $# = 0 && func_missing_arg $opt && break + optarg="$1" + opt_mode="$optarg" +case $optarg in + # Valid mode arguments: + clean|compile|execute|finish|install|link|relink|uninstall) ;; + + # Catch anything else as an error + *) func_error "invalid argument for $opt" + exit_cmd=exit + break + ;; +esac + shift + ;; + --no-silent|--no-quiet) + opt_silent=false +func_append preserve_args " $opt" + ;; + --no-warning|--no-warn) + opt_warning=false +func_append preserve_args " $opt" + ;; + --no-verbose) + opt_verbose=false +func_append preserve_args " $opt" + ;; + --silent|--quiet) + opt_silent=: +func_append preserve_args " $opt" + opt_verbose=false + ;; + --verbose|-v) + opt_verbose=: +func_append preserve_args " $opt" +opt_silent=false + ;; + --tag) + test $# = 0 && func_missing_arg $opt && break + optarg="$1" + opt_tag="$optarg" +func_append preserve_args " $opt $optarg" +func_enable_tag "$optarg" + shift + ;; + + -\?|-h) func_usage ;; + --help) func_help ;; + --version) func_version ;; + + # Separate optargs to long options: + --*=*) + func_split_long_opt "$opt" + set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"} + shift + ;; + + # Separate non-argument short options: + -\?*|-h*|-n*|-v*) + func_split_short_opt "$opt" + set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"} + shift + ;; + + --) break ;; + -*) func_fatal_help "unrecognized option \`$opt'" ;; + *) set dummy "$opt" ${1+"$@"}; shift; break ;; + esac + done + + # Validate options: + + # save first non-option argument + if test "$#" -gt 0; then + nonopt="$opt" + shift + fi + + # preserve --debug + test "$opt_debug" = : || func_append preserve_args " --debug" + + case $host in + *cygwin* | *mingw* | *pw32* | *cegcc*) + # don't eliminate duplications in $postdeps and $predeps + opt_duplicate_compiler_generated_deps=: + ;; + *) + opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps + ;; + esac + + $opt_help || { + # Sanity checks first: + func_check_version_match + + if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then + func_fatal_configuration "not configured to build any kind of library" + fi + + # Darwin sucks + eval std_shrext=\"$shrext_cmds\" + + # Only execute mode is allowed to have -dlopen flags. + if test -n "$opt_dlopen" && test "$opt_mode" != execute; then + func_error "unrecognized option \`-dlopen'" + $ECHO "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Change the help message to a mode-specific one. + generic_help="$help" + help="Try \`$progname --help --mode=$opt_mode' for more information." + } + + + # Bail if the options were screwed + $exit_cmd $EXIT_FAILURE +} + + + + +## ----------- ## +## Main. ## +## ----------- ## + +# func_lalib_p file +# True iff FILE is a libtool `.la' library or `.lo' object file. +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_lalib_p () +{ + test -f "$1" && + $SED -e 4q "$1" 2>/dev/null \ + | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 +} + +# func_lalib_unsafe_p file +# True iff FILE is a libtool `.la' library or `.lo' object file. +# This function implements the same check as func_lalib_p without +# resorting to external programs. To this end, it redirects stdin and +# closes it afterwards, without saving the original file descriptor. +# As a safety measure, use it only where a negative result would be +# fatal anyway. Works if `file' does not exist. +func_lalib_unsafe_p () +{ + lalib_p=no + if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then + for lalib_p_l in 1 2 3 4 + do + read lalib_p_line + case "$lalib_p_line" in + \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; + esac + done + exec 0<&5 5<&- + fi + test "$lalib_p" = yes +} + +# func_ltwrapper_script_p file +# True iff FILE is a libtool wrapper script +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_script_p () +{ + func_lalib_p "$1" +} + +# func_ltwrapper_executable_p file +# True iff FILE is a libtool wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_executable_p () +{ + func_ltwrapper_exec_suffix= + case $1 in + *.exe) ;; + *) func_ltwrapper_exec_suffix=.exe ;; + esac + $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 +} + +# func_ltwrapper_scriptname file +# Assumes file is an ltwrapper_executable +# uses $file to determine the appropriate filename for a +# temporary ltwrapper_script. +func_ltwrapper_scriptname () +{ + func_dirname_and_basename "$1" "" "." + func_stripname '' '.exe' "$func_basename_result" + func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" +} + +# func_ltwrapper_p file +# True iff FILE is a libtool wrapper script or wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_p () +{ + func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" +} + + +# func_execute_cmds commands fail_cmd +# Execute tilde-delimited COMMANDS. +# If FAIL_CMD is given, eval that upon failure. +# FAIL_CMD may read-access the current command in variable CMD! +func_execute_cmds () +{ + $opt_debug + save_ifs=$IFS; IFS='~' + for cmd in $1; do + IFS=$save_ifs + eval cmd=\"$cmd\" + func_show_eval "$cmd" "${2-:}" + done + IFS=$save_ifs +} + + +# func_source file +# Source FILE, adding directory component if necessary. +# Note that it is not necessary on cygwin/mingw to append a dot to +# FILE even if both FILE and FILE.exe exist: automatic-append-.exe +# behavior happens only for exec(3), not for open(2)! Also, sourcing +# `FILE.' does not work on cygwin managed mounts. +func_source () +{ + $opt_debug + case $1 in + */* | *\\*) . "$1" ;; + *) . "./$1" ;; + esac +} + + +# func_resolve_sysroot PATH +# Replace a leading = in PATH with a sysroot. Store the result into +# func_resolve_sysroot_result +func_resolve_sysroot () +{ + func_resolve_sysroot_result=$1 + case $func_resolve_sysroot_result in + =*) + func_stripname '=' '' "$func_resolve_sysroot_result" + func_resolve_sysroot_result=$lt_sysroot$func_stripname_result + ;; + esac +} + +# func_replace_sysroot PATH +# If PATH begins with the sysroot, replace it with = and +# store the result into func_replace_sysroot_result. +func_replace_sysroot () +{ + case "$lt_sysroot:$1" in + ?*:"$lt_sysroot"*) + func_stripname "$lt_sysroot" '' "$1" + func_replace_sysroot_result="=$func_stripname_result" + ;; + *) + # Including no sysroot. + func_replace_sysroot_result=$1 + ;; + esac +} + +# func_infer_tag arg +# Infer tagged configuration to use if any are available and +# if one wasn't chosen via the "--tag" command line option. +# Only attempt this if the compiler in the base compile +# command doesn't match the default compiler. +# arg is usually of the form 'gcc ...' +func_infer_tag () +{ + $opt_debug + if test -n "$available_tags" && test -z "$tagname"; then + CC_quoted= + for arg in $CC; do + func_append_quoted CC_quoted "$arg" + done + CC_expanded=`func_echo_all $CC` + CC_quoted_expanded=`func_echo_all $CC_quoted` + case $@ in + # Blanks in the command may have been stripped by the calling shell, + # but not from the CC environment variable when configure was run. + " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ + " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; + # Blanks at the start of $base_compile will cause this to fail + # if we don't check for them as well. + *) + for z in $available_tags; do + if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then + # Evaluate the configuration. + eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" + CC_quoted= + for arg in $CC; do + # Double-quote args containing other shell metacharacters. + func_append_quoted CC_quoted "$arg" + done + CC_expanded=`func_echo_all $CC` + CC_quoted_expanded=`func_echo_all $CC_quoted` + case "$@ " in + " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ + " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) + # The compiler in the base compile command matches + # the one in the tagged configuration. + # Assume this is the tagged configuration we want. + tagname=$z + break + ;; + esac + fi + done + # If $tagname still isn't set, then no tagged configuration + # was found and let the user know that the "--tag" command + # line option must be used. + if test -z "$tagname"; then + func_echo "unable to infer tagged configuration" + func_fatal_error "specify a tag with \`--tag'" +# else +# func_verbose "using $tagname tagged configuration" + fi + ;; + esac + fi +} + + + +# func_write_libtool_object output_name pic_name nonpic_name +# Create a libtool object file (analogous to a ".la" file), +# but don't create it if we're doing a dry run. +func_write_libtool_object () +{ + write_libobj=${1} + if test "$build_libtool_libs" = yes; then + write_lobj=\'${2}\' + else + write_lobj=none + fi + + if test "$build_old_libs" = yes; then + write_oldobj=\'${3}\' + else + write_oldobj=none + fi + + $opt_dry_run || { + cat >${write_libobj}T </dev/null` + if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then + func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | + $SED -e "$lt_sed_naive_backslashify"` + else + func_convert_core_file_wine_to_w32_result= + fi + fi +} +# end: func_convert_core_file_wine_to_w32 + + +# func_convert_core_path_wine_to_w32 ARG +# Helper function used by path conversion functions when $build is *nix, and +# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly +# configured wine environment available, with the winepath program in $build's +# $PATH. Assumes ARG has no leading or trailing path separator characters. +# +# ARG is path to be converted from $build format to win32. +# Result is available in $func_convert_core_path_wine_to_w32_result. +# Unconvertible file (directory) names in ARG are skipped; if no directory names +# are convertible, then the result may be empty. +func_convert_core_path_wine_to_w32 () +{ + $opt_debug + # unfortunately, winepath doesn't convert paths, only file names + func_convert_core_path_wine_to_w32_result="" + if test -n "$1"; then + oldIFS=$IFS + IFS=: + for func_convert_core_path_wine_to_w32_f in $1; do + IFS=$oldIFS + func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" + if test -n "$func_convert_core_file_wine_to_w32_result" ; then + if test -z "$func_convert_core_path_wine_to_w32_result"; then + func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result" + else + func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" + fi + fi + done + IFS=$oldIFS + fi +} +# end: func_convert_core_path_wine_to_w32 + + +# func_cygpath ARGS... +# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when +# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) +# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or +# (2), returns the Cygwin file name or path in func_cygpath_result (input +# file name or path is assumed to be in w32 format, as previously converted +# from $build's *nix or MSYS format). In case (3), returns the w32 file name +# or path in func_cygpath_result (input file name or path is assumed to be in +# Cygwin format). Returns an empty string on error. +# +# ARGS are passed to cygpath, with the last one being the file name or path to +# be converted. +# +# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH +# environment variable; do not put it in $PATH. +func_cygpath () +{ + $opt_debug + if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then + func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` + if test "$?" -ne 0; then + # on failure, ensure result is empty + func_cygpath_result= + fi + else + func_cygpath_result= + func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'" + fi +} +#end: func_cygpath + + +# func_convert_core_msys_to_w32 ARG +# Convert file name or path ARG from MSYS format to w32 format. Return +# result in func_convert_core_msys_to_w32_result. +func_convert_core_msys_to_w32 () +{ + $opt_debug + # awkward: cmd appends spaces to result + func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | + $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"` +} +#end: func_convert_core_msys_to_w32 + + +# func_convert_file_check ARG1 ARG2 +# Verify that ARG1 (a file name in $build format) was converted to $host +# format in ARG2. Otherwise, emit an error message, but continue (resetting +# func_to_host_file_result to ARG1). +func_convert_file_check () +{ + $opt_debug + if test -z "$2" && test -n "$1" ; then + func_error "Could not determine host file name corresponding to" + func_error " \`$1'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback: + func_to_host_file_result="$1" + fi +} +# end func_convert_file_check + + +# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH +# Verify that FROM_PATH (a path in $build format) was converted to $host +# format in TO_PATH. Otherwise, emit an error message, but continue, resetting +# func_to_host_file_result to a simplistic fallback value (see below). +func_convert_path_check () +{ + $opt_debug + if test -z "$4" && test -n "$3"; then + func_error "Could not determine the host path corresponding to" + func_error " \`$3'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback. This is a deliberately simplistic "conversion" and + # should not be "improved". See libtool.info. + if test "x$1" != "x$2"; then + lt_replace_pathsep_chars="s|$1|$2|g" + func_to_host_path_result=`echo "$3" | + $SED -e "$lt_replace_pathsep_chars"` + else + func_to_host_path_result="$3" + fi + fi +} +# end func_convert_path_check + + +# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG +# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT +# and appending REPL if ORIG matches BACKPAT. +func_convert_path_front_back_pathsep () +{ + $opt_debug + case $4 in + $1 ) func_to_host_path_result="$3$func_to_host_path_result" + ;; + esac + case $4 in + $2 ) func_append func_to_host_path_result "$3" + ;; + esac +} +# end func_convert_path_front_back_pathsep + + +################################################## +# $build to $host FILE NAME CONVERSION FUNCTIONS # +################################################## +# invoked via `$to_host_file_cmd ARG' +# +# In each case, ARG is the path to be converted from $build to $host format. +# Result will be available in $func_to_host_file_result. + + +# func_to_host_file ARG +# Converts the file name ARG from $build format to $host format. Return result +# in func_to_host_file_result. +func_to_host_file () +{ + $opt_debug + $to_host_file_cmd "$1" +} +# end func_to_host_file + + +# func_to_tool_file ARG LAZY +# converts the file name ARG from $build format to toolchain format. Return +# result in func_to_tool_file_result. If the conversion in use is listed +# in (the comma separated) LAZY, no conversion takes place. +func_to_tool_file () +{ + $opt_debug + case ,$2, in + *,"$to_tool_file_cmd",*) + func_to_tool_file_result=$1 + ;; + *) + $to_tool_file_cmd "$1" + func_to_tool_file_result=$func_to_host_file_result + ;; + esac +} +# end func_to_tool_file + + +# func_convert_file_noop ARG +# Copy ARG to func_to_host_file_result. +func_convert_file_noop () +{ + func_to_host_file_result="$1" +} +# end func_convert_file_noop + + +# func_convert_file_msys_to_w32 ARG +# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic +# conversion to w32 is not available inside the cwrapper. Returns result in +# func_to_host_file_result. +func_convert_file_msys_to_w32 () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + func_convert_core_msys_to_w32 "$1" + func_to_host_file_result="$func_convert_core_msys_to_w32_result" + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_msys_to_w32 + + +# func_convert_file_cygwin_to_w32 ARG +# Convert file name ARG from Cygwin to w32 format. Returns result in +# func_to_host_file_result. +func_convert_file_cygwin_to_w32 () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + # because $build is cygwin, we call "the" cygpath in $PATH; no need to use + # LT_CYGPATH in this case. + func_to_host_file_result=`cygpath -m "$1"` + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_cygwin_to_w32 + + +# func_convert_file_nix_to_w32 ARG +# Convert file name ARG from *nix to w32 format. Requires a wine environment +# and a working winepath. Returns result in func_to_host_file_result. +func_convert_file_nix_to_w32 () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + func_convert_core_file_wine_to_w32 "$1" + func_to_host_file_result="$func_convert_core_file_wine_to_w32_result" + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_nix_to_w32 + + +# func_convert_file_msys_to_cygwin ARG +# Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. +# Returns result in func_to_host_file_result. +func_convert_file_msys_to_cygwin () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + func_convert_core_msys_to_w32 "$1" + func_cygpath -u "$func_convert_core_msys_to_w32_result" + func_to_host_file_result="$func_cygpath_result" + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_msys_to_cygwin + + +# func_convert_file_nix_to_cygwin ARG +# Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed +# in a wine environment, working winepath, and LT_CYGPATH set. Returns result +# in func_to_host_file_result. +func_convert_file_nix_to_cygwin () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. + func_convert_core_file_wine_to_w32 "$1" + func_cygpath -u "$func_convert_core_file_wine_to_w32_result" + func_to_host_file_result="$func_cygpath_result" + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_nix_to_cygwin + + +############################################# +# $build to $host PATH CONVERSION FUNCTIONS # +############################################# +# invoked via `$to_host_path_cmd ARG' +# +# In each case, ARG is the path to be converted from $build to $host format. +# The result will be available in $func_to_host_path_result. +# +# Path separators are also converted from $build format to $host format. If +# ARG begins or ends with a path separator character, it is preserved (but +# converted to $host format) on output. +# +# All path conversion functions are named using the following convention: +# file name conversion function : func_convert_file_X_to_Y () +# path conversion function : func_convert_path_X_to_Y () +# where, for any given $build/$host combination the 'X_to_Y' value is the +# same. If conversion functions are added for new $build/$host combinations, +# the two new functions must follow this pattern, or func_init_to_host_path_cmd +# will break. + + +# func_init_to_host_path_cmd +# Ensures that function "pointer" variable $to_host_path_cmd is set to the +# appropriate value, based on the value of $to_host_file_cmd. +to_host_path_cmd= +func_init_to_host_path_cmd () +{ + $opt_debug + if test -z "$to_host_path_cmd"; then + func_stripname 'func_convert_file_' '' "$to_host_file_cmd" + to_host_path_cmd="func_convert_path_${func_stripname_result}" + fi +} + + +# func_to_host_path ARG +# Converts the path ARG from $build format to $host format. Return result +# in func_to_host_path_result. +func_to_host_path () +{ + $opt_debug + func_init_to_host_path_cmd + $to_host_path_cmd "$1" +} +# end func_to_host_path + + +# func_convert_path_noop ARG +# Copy ARG to func_to_host_path_result. +func_convert_path_noop () +{ + func_to_host_path_result="$1" +} +# end func_convert_path_noop + + +# func_convert_path_msys_to_w32 ARG +# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic +# conversion to w32 is not available inside the cwrapper. Returns result in +# func_to_host_path_result. +func_convert_path_msys_to_w32 () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # Remove leading and trailing path separator characters from ARG. MSYS + # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; + # and winepath ignores them completely. + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" + func_to_host_path_result="$func_convert_core_msys_to_w32_result" + func_convert_path_check : ";" \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" + fi +} +# end func_convert_path_msys_to_w32 + + +# func_convert_path_cygwin_to_w32 ARG +# Convert path ARG from Cygwin to w32 format. Returns result in +# func_to_host_file_result. +func_convert_path_cygwin_to_w32 () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # See func_convert_path_msys_to_w32: + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` + func_convert_path_check : ";" \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" + fi +} +# end func_convert_path_cygwin_to_w32 + + +# func_convert_path_nix_to_w32 ARG +# Convert path ARG from *nix to w32 format. Requires a wine environment and +# a working winepath. Returns result in func_to_host_file_result. +func_convert_path_nix_to_w32 () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # See func_convert_path_msys_to_w32: + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" + func_to_host_path_result="$func_convert_core_path_wine_to_w32_result" + func_convert_path_check : ";" \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" + fi +} +# end func_convert_path_nix_to_w32 + + +# func_convert_path_msys_to_cygwin ARG +# Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. +# Returns result in func_to_host_file_result. +func_convert_path_msys_to_cygwin () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # See func_convert_path_msys_to_w32: + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" + func_cygpath -u -p "$func_convert_core_msys_to_w32_result" + func_to_host_path_result="$func_cygpath_result" + func_convert_path_check : : \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" : "$1" + fi +} +# end func_convert_path_msys_to_cygwin + + +# func_convert_path_nix_to_cygwin ARG +# Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a +# a wine environment, working winepath, and LT_CYGPATH set. Returns result in +# func_to_host_file_result. +func_convert_path_nix_to_cygwin () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # Remove leading and trailing path separator characters from + # ARG. msys behavior is inconsistent here, cygpath turns them + # into '.;' and ';.', and winepath ignores them completely. + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" + func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" + func_to_host_path_result="$func_cygpath_result" + func_convert_path_check : : \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" : "$1" + fi +} +# end func_convert_path_nix_to_cygwin + + +# func_mode_compile arg... +func_mode_compile () +{ + $opt_debug + # Get the compilation command and the source file. + base_compile= + srcfile="$nonopt" # always keep a non-empty value in "srcfile" + suppress_opt=yes + suppress_output= + arg_mode=normal + libobj= + later= + pie_flag= + + for arg + do + case $arg_mode in + arg ) + # do not "continue". Instead, add this to base_compile + lastarg="$arg" + arg_mode=normal + ;; + + target ) + libobj="$arg" + arg_mode=normal + continue + ;; + + normal ) + # Accept any command-line options. + case $arg in + -o) + test -n "$libobj" && \ + func_fatal_error "you cannot specify \`-o' more than once" + arg_mode=target + continue + ;; + + -pie | -fpie | -fPIE) + func_append pie_flag " $arg" + continue + ;; + + -shared | -static | -prefer-pic | -prefer-non-pic) + func_append later " $arg" + continue + ;; + + -no-suppress) + suppress_opt=no + continue + ;; + + -Xcompiler) + arg_mode=arg # the next one goes into the "base_compile" arg list + continue # The current "srcfile" will either be retained or + ;; # replaced later. I would guess that would be a bug. + + -Wc,*) + func_stripname '-Wc,' '' "$arg" + args=$func_stripname_result + lastarg= + save_ifs="$IFS"; IFS=',' + for arg in $args; do + IFS="$save_ifs" + func_append_quoted lastarg "$arg" + done + IFS="$save_ifs" + func_stripname ' ' '' "$lastarg" + lastarg=$func_stripname_result + + # Add the arguments to base_compile. + func_append base_compile " $lastarg" + continue + ;; + + *) + # Accept the current argument as the source file. + # The previous "srcfile" becomes the current argument. + # + lastarg="$srcfile" + srcfile="$arg" + ;; + esac # case $arg + ;; + esac # case $arg_mode + + # Aesthetically quote the previous argument. + func_append_quoted base_compile "$lastarg" + done # for arg + + case $arg_mode in + arg) + func_fatal_error "you must specify an argument for -Xcompile" + ;; + target) + func_fatal_error "you must specify a target with \`-o'" + ;; + *) + # Get the name of the library object. + test -z "$libobj" && { + func_basename "$srcfile" + libobj="$func_basename_result" + } + ;; + esac + + # Recognize several different file suffixes. + # If the user specifies -o file.o, it is replaced with file.lo + case $libobj in + *.[cCFSifmso] | \ + *.ada | *.adb | *.ads | *.asm | \ + *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ + *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) + func_xform "$libobj" + libobj=$func_xform_result + ;; + esac + + case $libobj in + *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; + *) + func_fatal_error "cannot determine name of library object from \`$libobj'" + ;; + esac + + func_infer_tag $base_compile + + for arg in $later; do + case $arg in + -shared) + test "$build_libtool_libs" != yes && \ + func_fatal_configuration "can not build a shared library" + build_old_libs=no + continue + ;; + + -static) + build_libtool_libs=no + build_old_libs=yes + continue + ;; + + -prefer-pic) + pic_mode=yes + continue + ;; + + -prefer-non-pic) + pic_mode=no + continue + ;; + esac + done + + func_quote_for_eval "$libobj" + test "X$libobj" != "X$func_quote_for_eval_result" \ + && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ + && func_warning "libobj name \`$libobj' may not contain shell special characters." + func_dirname_and_basename "$obj" "/" "" + objname="$func_basename_result" + xdir="$func_dirname_result" + lobj=${xdir}$objdir/$objname + + test -z "$base_compile" && \ + func_fatal_help "you must specify a compilation command" + + # Delete any leftover library objects. + if test "$build_old_libs" = yes; then + removelist="$obj $lobj $libobj ${libobj}T" + else + removelist="$lobj $libobj ${libobj}T" + fi + + # On Cygwin there's no "real" PIC flag so we must build both object types + case $host_os in + cygwin* | mingw* | pw32* | os2* | cegcc*) + pic_mode=default + ;; + esac + if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then + # non-PIC code in shared libraries is not supported + pic_mode=default + fi + + # Calculate the filename of the output object if compiler does + # not support -o with -c + if test "$compiler_c_o" = no; then + output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext} + lockfile="$output_obj.lock" + else + output_obj= + need_locks=no + lockfile= + fi + + # Lock this critical section if it is needed + # We use this script file to make the link, it avoids creating a new file + if test "$need_locks" = yes; then + until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do + func_echo "Waiting for $lockfile to be removed" + sleep 2 + done + elif test "$need_locks" = warn; then + if test -f "$lockfile"; then + $ECHO "\ +*** ERROR, $lockfile exists and contains: +`cat $lockfile 2>/dev/null` + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + func_append removelist " $output_obj" + $ECHO "$srcfile" > "$lockfile" + fi + + $opt_dry_run || $RM $removelist + func_append removelist " $lockfile" + trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 + + func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 + srcfile=$func_to_tool_file_result + func_quote_for_eval "$srcfile" + qsrcfile=$func_quote_for_eval_result + + # Only build a PIC object if we are building libtool libraries. + if test "$build_libtool_libs" = yes; then + # Without this assignment, base_compile gets emptied. + fbsd_hideous_sh_bug=$base_compile + + if test "$pic_mode" != no; then + command="$base_compile $qsrcfile $pic_flag" + else + # Don't build PIC code + command="$base_compile $qsrcfile" + fi + + func_mkdir_p "$xdir$objdir" + + if test -z "$output_obj"; then + # Place PIC objects in $objdir + func_append command " -o $lobj" + fi + + func_show_eval_locale "$command" \ + 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' + + if test "$need_locks" = warn && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed, then go on to compile the next one + if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then + func_show_eval '$MV "$output_obj" "$lobj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + + # Allow error messages only from the first compilation. + if test "$suppress_opt" = yes; then + suppress_output=' >/dev/null 2>&1' + fi + fi + + # Only build a position-dependent object if we build old libraries. + if test "$build_old_libs" = yes; then + if test "$pic_mode" != yes; then + # Don't build PIC code + command="$base_compile $qsrcfile$pie_flag" + else + command="$base_compile $qsrcfile $pic_flag" + fi + if test "$compiler_c_o" = yes; then + func_append command " -o $obj" + fi + + # Suppress compiler output if we already did a PIC compilation. + func_append command "$suppress_output" + func_show_eval_locale "$command" \ + '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' + + if test "$need_locks" = warn && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed + if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then + func_show_eval '$MV "$output_obj" "$obj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + fi + + $opt_dry_run || { + func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" + + # Unlock the critical section if it was locked + if test "$need_locks" != no; then + removelist=$lockfile + $RM "$lockfile" + fi + } + + exit $EXIT_SUCCESS +} + +$opt_help || { + test "$opt_mode" = compile && func_mode_compile ${1+"$@"} +} + +func_mode_help () +{ + # We need to display help for each of the modes. + case $opt_mode in + "") + # Generic help is extracted from the usage comments + # at the start of this file. + func_help + ;; + + clean) + $ECHO \ +"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... + +Remove files from the build directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, object or program, all the files associated +with it are deleted. Otherwise, only FILE itself is deleted using RM." + ;; + + compile) + $ECHO \ +"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE + +Compile a source file into a libtool library object. + +This mode accepts the following additional options: + + -o OUTPUT-FILE set the output file name to OUTPUT-FILE + -no-suppress do not suppress compiler output for multiple passes + -prefer-pic try to build PIC objects only + -prefer-non-pic try to build non-PIC objects only + -shared do not build a \`.o' file suitable for static linking + -static only build a \`.o' file suitable for static linking + -Wc,FLAG pass FLAG directly to the compiler + +COMPILE-COMMAND is a command to be used in creating a \`standard' object file +from the given SOURCEFILE. + +The output file name is determined by removing the directory component from +SOURCEFILE, then substituting the C source code suffix \`.c' with the +library object suffix, \`.lo'." + ;; + + execute) + $ECHO \ +"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... + +Automatically set library path, then run a program. + +This mode accepts the following additional options: + + -dlopen FILE add the directory containing FILE to the library path + +This mode sets the library path environment variable according to \`-dlopen' +flags. + +If any of the ARGS are libtool executable wrappers, then they are translated +into their corresponding uninstalled binary, and any of their required library +directories are added to the library path. + +Then, COMMAND is executed, with ARGS as arguments." + ;; + + finish) + $ECHO \ +"Usage: $progname [OPTION]... --mode=finish [LIBDIR]... + +Complete the installation of libtool libraries. + +Each LIBDIR is a directory that contains libtool libraries. + +The commands that this mode executes may require superuser privileges. Use +the \`--dry-run' option if you just want to see what would be executed." + ;; + + install) + $ECHO \ +"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... + +Install executables or libraries. + +INSTALL-COMMAND is the installation command. The first component should be +either the \`install' or \`cp' program. + +The following components of INSTALL-COMMAND are treated specially: + + -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation + +The rest of the components are interpreted as arguments to that command (only +BSD-compatible install options are recognized)." + ;; + + link) + $ECHO \ +"Usage: $progname [OPTION]... --mode=link LINK-COMMAND... + +Link object files or libraries together to form another library, or to +create an executable program. + +LINK-COMMAND is a command using the C compiler that you would use to create +a program from several object files. + +The following components of LINK-COMMAND are treated specially: + + -all-static do not do any dynamic linking at all + -avoid-version do not add a version suffix if possible + -bindir BINDIR specify path to binaries directory (for systems where + libraries must be found in the PATH setting at runtime) + -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime + -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols + -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) + -export-symbols SYMFILE + try to export only the symbols listed in SYMFILE + -export-symbols-regex REGEX + try to export only the symbols matching REGEX + -LLIBDIR search LIBDIR for required installed libraries + -lNAME OUTPUT-FILE requires the installed library libNAME + -module build a library that can dlopened + -no-fast-install disable the fast-install mode + -no-install link a not-installable executable + -no-undefined declare that a library does not refer to external symbols + -o OUTPUT-FILE create OUTPUT-FILE from the specified objects + -objectlist FILE Use a list of object files found in FILE to specify objects + -precious-files-regex REGEX + don't remove output files matching REGEX + -release RELEASE specify package release information + -rpath LIBDIR the created library will eventually be installed in LIBDIR + -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries + -shared only do dynamic linking of libtool libraries + -shrext SUFFIX override the standard shared library file extension + -static do not do any dynamic linking of uninstalled libtool libraries + -static-libtool-libs + do not do any dynamic linking of libtool libraries + -version-info CURRENT[:REVISION[:AGE]] + specify library version info [each variable defaults to 0] + -weak LIBNAME declare that the target provides the LIBNAME interface + -Wc,FLAG + -Xcompiler FLAG pass linker-specific FLAG directly to the compiler + -Wl,FLAG + -Xlinker FLAG pass linker-specific FLAG directly to the linker + -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) + +All other options (arguments beginning with \`-') are ignored. + +Every other argument is treated as a filename. Files ending in \`.la' are +treated as uninstalled libtool libraries, other files are standard or library +object files. + +If the OUTPUT-FILE ends in \`.la', then a libtool library is created, +only library objects (\`.lo' files) may be specified, and \`-rpath' is +required, except when creating a convenience library. + +If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created +using \`ar' and \`ranlib', or on Windows using \`lib'. + +If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file +is created, otherwise an executable program is created." + ;; + + uninstall) + $ECHO \ +"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... + +Remove libraries from an installation directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, all the files associated with it are deleted. +Otherwise, only FILE itself is deleted using RM." + ;; + + *) + func_fatal_help "invalid operation mode \`$opt_mode'" + ;; + esac + + echo + $ECHO "Try \`$progname --help' for more information about other modes." +} + +# Now that we've collected a possible --mode arg, show help if necessary +if $opt_help; then + if test "$opt_help" = :; then + func_mode_help + else + { + func_help noexit + for opt_mode in compile link execute install finish uninstall clean; do + func_mode_help + done + } | sed -n '1p; 2,$s/^Usage:/ or: /p' + { + func_help noexit + for opt_mode in compile link execute install finish uninstall clean; do + echo + func_mode_help + done + } | + sed '1d + /^When reporting/,/^Report/{ + H + d + } + $x + /information about other modes/d + /more detailed .*MODE/d + s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' + fi + exit $? +fi + + +# func_mode_execute arg... +func_mode_execute () +{ + $opt_debug + # The first argument is the command name. + cmd="$nonopt" + test -z "$cmd" && \ + func_fatal_help "you must specify a COMMAND" + + # Handle -dlopen flags immediately. + for file in $opt_dlopen; do + test -f "$file" \ + || func_fatal_help "\`$file' is not a file" + + dir= + case $file in + *.la) + func_resolve_sysroot "$file" + file=$func_resolve_sysroot_result + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "\`$lib' is not a valid libtool archive" + + # Read the libtool library. + dlname= + library_names= + func_source "$file" + + # Skip this library if it cannot be dlopened. + if test -z "$dlname"; then + # Warn if it was a shared library. + test -n "$library_names" && \ + func_warning "\`$file' was not linked with \`-export-dynamic'" + continue + fi + + func_dirname "$file" "" "." + dir="$func_dirname_result" + + if test -f "$dir/$objdir/$dlname"; then + func_append dir "/$objdir" + else + if test ! -f "$dir/$dlname"; then + func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" + fi + fi + ;; + + *.lo) + # Just add the directory containing the .lo file. + func_dirname "$file" "" "." + dir="$func_dirname_result" + ;; + + *) + func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" + continue + ;; + esac + + # Get the absolute pathname. + absdir=`cd "$dir" && pwd` + test -n "$absdir" && dir="$absdir" + + # Now add the directory to shlibpath_var. + if eval "test -z \"\$$shlibpath_var\""; then + eval "$shlibpath_var=\"\$dir\"" + else + eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" + fi + done + + # This variable tells wrapper scripts just to set shlibpath_var + # rather than running their programs. + libtool_execute_magic="$magic" + + # Check if any of the arguments is a wrapper script. + args= + for file + do + case $file in + -* | *.la | *.lo ) ;; + *) + # Do a test to see if this is really a libtool program. + if func_ltwrapper_script_p "$file"; then + func_source "$file" + # Transform arg to wrapped name. + file="$progdir/$program" + elif func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + func_source "$func_ltwrapper_scriptname_result" + # Transform arg to wrapped name. + file="$progdir/$program" + fi + ;; + esac + # Quote arguments (to preserve shell metacharacters). + func_append_quoted args "$file" + done + + if test "X$opt_dry_run" = Xfalse; then + if test -n "$shlibpath_var"; then + # Export the shlibpath_var. + eval "export $shlibpath_var" + fi + + # Restore saved environment variables + for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES + do + eval "if test \"\${save_$lt_var+set}\" = set; then + $lt_var=\$save_$lt_var; export $lt_var + else + $lt_unset $lt_var + fi" + done + + # Now prepare to actually exec the command. + exec_cmd="\$cmd$args" + else + # Display what would be done. + if test -n "$shlibpath_var"; then + eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" + echo "export $shlibpath_var" + fi + $ECHO "$cmd$args" + exit $EXIT_SUCCESS + fi +} + +test "$opt_mode" = execute && func_mode_execute ${1+"$@"} + + +# func_mode_finish arg... +func_mode_finish () +{ + $opt_debug + libs= + libdirs= + admincmds= + + for opt in "$nonopt" ${1+"$@"} + do + if test -d "$opt"; then + func_append libdirs " $opt" + + elif test -f "$opt"; then + if func_lalib_unsafe_p "$opt"; then + func_append libs " $opt" + else + func_warning "\`$opt' is not a valid libtool archive" + fi + + else + func_fatal_error "invalid argument \`$opt'" + fi + done + + if test -n "$libs"; then + if test -n "$lt_sysroot"; then + sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` + sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" + else + sysroot_cmd= + fi + + # Remove sysroot references + if $opt_dry_run; then + for lib in $libs; do + echo "removing references to $lt_sysroot and \`=' prefixes from $lib" + done + else + tmpdir=`func_mktempdir` + for lib in $libs; do + sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ + > $tmpdir/tmp-la + mv -f $tmpdir/tmp-la $lib + done + ${RM}r "$tmpdir" + fi + fi + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + for libdir in $libdirs; do + if test -n "$finish_cmds"; then + # Do each command in the finish commands. + func_execute_cmds "$finish_cmds" 'admincmds="$admincmds +'"$cmd"'"' + fi + if test -n "$finish_eval"; then + # Do the single finish_eval. + eval cmds=\"$finish_eval\" + $opt_dry_run || eval "$cmds" || func_append admincmds " + $cmds" + fi + done + fi + + # Exit here if they wanted silent mode. + $opt_silent && exit $EXIT_SUCCESS + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + echo "----------------------------------------------------------------------" + echo "Libraries have been installed in:" + for libdir in $libdirs; do + $ECHO " $libdir" + done + echo + echo "If you ever happen to want to link against installed libraries" + echo "in a given directory, LIBDIR, you must either use libtool, and" + echo "specify the full pathname of the library, or use the \`-LLIBDIR'" + echo "flag during linking and do at least one of the following:" + if test -n "$shlibpath_var"; then + echo " - add LIBDIR to the \`$shlibpath_var' environment variable" + echo " during execution" + fi + if test -n "$runpath_var"; then + echo " - add LIBDIR to the \`$runpath_var' environment variable" + echo " during linking" + fi + if test -n "$hardcode_libdir_flag_spec"; then + libdir=LIBDIR + eval flag=\"$hardcode_libdir_flag_spec\" + + $ECHO " - use the \`$flag' linker flag" + fi + if test -n "$admincmds"; then + $ECHO " - have your system administrator run these commands:$admincmds" + fi + if test -f /etc/ld.so.conf; then + echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" + fi + echo + + echo "See any operating system documentation about shared libraries for" + case $host in + solaris2.[6789]|solaris2.1[0-9]) + echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" + echo "pages." + ;; + *) + echo "more information, such as the ld(1) and ld.so(8) manual pages." + ;; + esac + echo "----------------------------------------------------------------------" + fi + exit $EXIT_SUCCESS +} + +test "$opt_mode" = finish && func_mode_finish ${1+"$@"} + + +# func_mode_install arg... +func_mode_install () +{ + $opt_debug + # There may be an optional sh(1) argument at the beginning of + # install_prog (especially on Windows NT). + if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || + # Allow the use of GNU shtool's install command. + case $nonopt in *shtool*) :;; *) false;; esac; then + # Aesthetically quote it. + func_quote_for_eval "$nonopt" + install_prog="$func_quote_for_eval_result " + arg=$1 + shift + else + install_prog= + arg=$nonopt + fi + + # The real first argument should be the name of the installation program. + # Aesthetically quote it. + func_quote_for_eval "$arg" + func_append install_prog "$func_quote_for_eval_result" + install_shared_prog=$install_prog + case " $install_prog " in + *[\\\ /]cp\ *) install_cp=: ;; + *) install_cp=false ;; + esac + + # We need to accept at least all the BSD install flags. + dest= + files= + opts= + prev= + install_type= + isdir=no + stripme= + no_mode=: + for arg + do + arg2= + if test -n "$dest"; then + func_append files " $dest" + dest=$arg + continue + fi + + case $arg in + -d) isdir=yes ;; + -f) + if $install_cp; then :; else + prev=$arg + fi + ;; + -g | -m | -o) + prev=$arg + ;; + -s) + stripme=" -s" + continue + ;; + -*) + ;; + *) + # If the previous option needed an argument, then skip it. + if test -n "$prev"; then + if test "x$prev" = x-m && test -n "$install_override_mode"; then + arg2=$install_override_mode + no_mode=false + fi + prev= + else + dest=$arg + continue + fi + ;; + esac + + # Aesthetically quote the argument. + func_quote_for_eval "$arg" + func_append install_prog " $func_quote_for_eval_result" + if test -n "$arg2"; then + func_quote_for_eval "$arg2" + fi + func_append install_shared_prog " $func_quote_for_eval_result" + done + + test -z "$install_prog" && \ + func_fatal_help "you must specify an install program" + + test -n "$prev" && \ + func_fatal_help "the \`$prev' option requires an argument" + + if test -n "$install_override_mode" && $no_mode; then + if $install_cp; then :; else + func_quote_for_eval "$install_override_mode" + func_append install_shared_prog " -m $func_quote_for_eval_result" + fi + fi + + if test -z "$files"; then + if test -z "$dest"; then + func_fatal_help "no file or destination specified" + else + func_fatal_help "you must specify a destination" + fi + fi + + # Strip any trailing slash from the destination. + func_stripname '' '/' "$dest" + dest=$func_stripname_result + + # Check to see that the destination is a directory. + test -d "$dest" && isdir=yes + if test "$isdir" = yes; then + destdir="$dest" + destname= + else + func_dirname_and_basename "$dest" "" "." + destdir="$func_dirname_result" + destname="$func_basename_result" + + # Not a directory, so check to see that there is only one file specified. + set dummy $files; shift + test "$#" -gt 1 && \ + func_fatal_help "\`$dest' is not a directory" + fi + case $destdir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + for file in $files; do + case $file in + *.lo) ;; + *) + func_fatal_help "\`$destdir' must be an absolute directory name" + ;; + esac + done + ;; + esac + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + staticlibs= + future_libdirs= + current_libdirs= + for file in $files; do + + # Do each installation. + case $file in + *.$libext) + # Do the static libraries later. + func_append staticlibs " $file" + ;; + + *.la) + func_resolve_sysroot "$file" + file=$func_resolve_sysroot_result + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "\`$file' is not a valid libtool archive" + + library_names= + old_library= + relink_command= + func_source "$file" + + # Add the libdir to current_libdirs if it is the destination. + if test "X$destdir" = "X$libdir"; then + case "$current_libdirs " in + *" $libdir "*) ;; + *) func_append current_libdirs " $libdir" ;; + esac + else + # Note the libdir as a future libdir. + case "$future_libdirs " in + *" $libdir "*) ;; + *) func_append future_libdirs " $libdir" ;; + esac + fi + + func_dirname "$file" "/" "" + dir="$func_dirname_result" + func_append dir "$objdir" + + if test -n "$relink_command"; then + # Determine the prefix the user has applied to our future dir. + inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` + + # Don't allow the user to place us outside of our expected + # location b/c this prevents finding dependent libraries that + # are installed to the same prefix. + # At present, this check doesn't affect windows .dll's that + # are installed into $libdir/../bin (currently, that works fine) + # but it's something to keep an eye on. + test "$inst_prefix_dir" = "$destdir" && \ + func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" + + if test -n "$inst_prefix_dir"; then + # Stick the inst_prefix_dir data into the link command. + relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` + else + relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` + fi + + func_warning "relinking \`$file'" + func_show_eval "$relink_command" \ + 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' + fi + + # See the names of the shared library. + set dummy $library_names; shift + if test -n "$1"; then + realname="$1" + shift + + srcname="$realname" + test -n "$relink_command" && srcname="$realname"T + + # Install the shared library and build the symlinks. + func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ + 'exit $?' + tstripme="$stripme" + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + case $realname in + *.dll.a) + tstripme="" + ;; + esac + ;; + esac + if test -n "$tstripme" && test -n "$striplib"; then + func_show_eval "$striplib $destdir/$realname" 'exit $?' + fi + + if test "$#" -gt 0; then + # Delete the old symlinks, and create new ones. + # Try `ln -sf' first, because the `ln' binary might depend on + # the symlink we replace! Solaris /bin/ln does not understand -f, + # so we also need to try rm && ln -s. + for linkname + do + test "$linkname" != "$realname" \ + && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" + done + fi + + # Do each command in the postinstall commands. + lib="$destdir/$realname" + func_execute_cmds "$postinstall_cmds" 'exit $?' + fi + + # Install the pseudo-library for information purposes. + func_basename "$file" + name="$func_basename_result" + instname="$dir/$name"i + func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' + + # Maybe install the static library, too. + test -n "$old_library" && func_append staticlibs " $dir/$old_library" + ;; + + *.lo) + # Install (i.e. copy) a libtool object. + + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + func_basename "$file" + destfile="$func_basename_result" + destfile="$destdir/$destfile" + fi + + # Deduce the name of the destination old-style object file. + case $destfile in + *.lo) + func_lo2o "$destfile" + staticdest=$func_lo2o_result + ;; + *.$objext) + staticdest="$destfile" + destfile= + ;; + *) + func_fatal_help "cannot copy a libtool object to \`$destfile'" + ;; + esac + + # Install the libtool object if requested. + test -n "$destfile" && \ + func_show_eval "$install_prog $file $destfile" 'exit $?' + + # Install the old object if enabled. + if test "$build_old_libs" = yes; then + # Deduce the name of the old-style object file. + func_lo2o "$file" + staticobj=$func_lo2o_result + func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' + fi + exit $EXIT_SUCCESS + ;; + + *) + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + func_basename "$file" + destfile="$func_basename_result" + destfile="$destdir/$destfile" + fi + + # If the file is missing, and there is a .exe on the end, strip it + # because it is most likely a libtool script we actually want to + # install + stripped_ext="" + case $file in + *.exe) + if test ! -f "$file"; then + func_stripname '' '.exe' "$file" + file=$func_stripname_result + stripped_ext=".exe" + fi + ;; + esac + + # Do a test to see if this is really a libtool program. + case $host in + *cygwin* | *mingw*) + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + wrapper=$func_ltwrapper_scriptname_result + else + func_stripname '' '.exe' "$file" + wrapper=$func_stripname_result + fi + ;; + *) + wrapper=$file + ;; + esac + if func_ltwrapper_script_p "$wrapper"; then + notinst_deplibs= + relink_command= + + func_source "$wrapper" + + # Check the variables that should have been set. + test -z "$generated_by_libtool_version" && \ + func_fatal_error "invalid libtool wrapper script \`$wrapper'" + + finalize=yes + for lib in $notinst_deplibs; do + # Check to see that each library is installed. + libdir= + if test -f "$lib"; then + func_source "$lib" + fi + libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test + if test -n "$libdir" && test ! -f "$libfile"; then + func_warning "\`$lib' has not been installed in \`$libdir'" + finalize=no + fi + done + + relink_command= + func_source "$wrapper" + + outputname= + if test "$fast_install" = no && test -n "$relink_command"; then + $opt_dry_run || { + if test "$finalize" = yes; then + tmpdir=`func_mktempdir` + func_basename "$file$stripped_ext" + file="$func_basename_result" + outputname="$tmpdir/$file" + # Replace the output file specification. + relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` + + $opt_silent || { + func_quote_for_expand "$relink_command" + eval "func_echo $func_quote_for_expand_result" + } + if eval "$relink_command"; then : + else + func_error "error: relink \`$file' with the above command before installing it" + $opt_dry_run || ${RM}r "$tmpdir" + continue + fi + file="$outputname" + else + func_warning "cannot relink \`$file'" + fi + } + else + # Install the binary that we compiled earlier. + file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` + fi + fi + + # remove .exe since cygwin /usr/bin/install will append another + # one anyway + case $install_prog,$host in + */usr/bin/install*,*cygwin*) + case $file:$destfile in + *.exe:*.exe) + # this is ok + ;; + *.exe:*) + destfile=$destfile.exe + ;; + *:*.exe) + func_stripname '' '.exe' "$destfile" + destfile=$func_stripname_result + ;; + esac + ;; + esac + func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' + $opt_dry_run || if test -n "$outputname"; then + ${RM}r "$tmpdir" + fi + ;; + esac + done + + for file in $staticlibs; do + func_basename "$file" + name="$func_basename_result" + + # Set up the ranlib parameters. + oldlib="$destdir/$name" + func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 + tool_oldlib=$func_to_tool_file_result + + func_show_eval "$install_prog \$file \$oldlib" 'exit $?' + + if test -n "$stripme" && test -n "$old_striplib"; then + func_show_eval "$old_striplib $tool_oldlib" 'exit $?' + fi + + # Do each command in the postinstall commands. + func_execute_cmds "$old_postinstall_cmds" 'exit $?' + done + + test -n "$future_libdirs" && \ + func_warning "remember to run \`$progname --finish$future_libdirs'" + + if test -n "$current_libdirs"; then + # Maybe just do a dry run. + $opt_dry_run && current_libdirs=" -n$current_libdirs" + exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' + else + exit $EXIT_SUCCESS + fi +} + +test "$opt_mode" = install && func_mode_install ${1+"$@"} + + +# func_generate_dlsyms outputname originator pic_p +# Extract symbols from dlprefiles and create ${outputname}S.o with +# a dlpreopen symbol table. +func_generate_dlsyms () +{ + $opt_debug + my_outputname="$1" + my_originator="$2" + my_pic_p="${3-no}" + my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` + my_dlsyms= + + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + if test -n "$NM" && test -n "$global_symbol_pipe"; then + my_dlsyms="${my_outputname}S.c" + else + func_error "not configured to extract global symbols from dlpreopened files" + fi + fi + + if test -n "$my_dlsyms"; then + case $my_dlsyms in + "") ;; + *.c) + # Discover the nlist of each of the dlfiles. + nlist="$output_objdir/${my_outputname}.nm" + + func_show_eval "$RM $nlist ${nlist}S ${nlist}T" + + # Parse the name list into a source file. + func_verbose "creating $output_objdir/$my_dlsyms" + + $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ +/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ +/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ + +#ifdef __cplusplus +extern \"C\" { +#endif + +#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) +#pragma GCC diagnostic ignored \"-Wstrict-prototypes\" +#endif + +/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ +#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) +/* DATA imports from DLLs on WIN32 con't be const, because runtime + relocations are performed -- see ld's documentation on pseudo-relocs. */ +# define LT_DLSYM_CONST +#elif defined(__osf__) +/* This system does not cope well with relocations in const data. */ +# define LT_DLSYM_CONST +#else +# define LT_DLSYM_CONST const +#endif + +/* External symbol declarations for the compiler. */\ +" + + if test "$dlself" = yes; then + func_verbose "generating symbol list for \`$output'" + + $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" + + # Add our own program objects to the symbol list. + progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` + for progfile in $progfiles; do + func_to_tool_file "$progfile" func_convert_file_msys_to_w32 + func_verbose "extracting global C symbols from \`$func_to_tool_file_result'" + $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" + done + + if test -n "$exclude_expsyms"; then + $opt_dry_run || { + eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + if test -n "$export_symbols_regex"; then + $opt_dry_run || { + eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + export_symbols="$output_objdir/$outputname.exp" + $opt_dry_run || { + $RM $export_symbols + eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' + case $host in + *cygwin* | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' + ;; + esac + } + else + $opt_dry_run || { + eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' + eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + case $host in + *cygwin* | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' + ;; + esac + } + fi + fi + + for dlprefile in $dlprefiles; do + func_verbose "extracting global C symbols from \`$dlprefile'" + func_basename "$dlprefile" + name="$func_basename_result" + case $host in + *cygwin* | *mingw* | *cegcc* ) + # if an import library, we need to obtain dlname + if func_win32_import_lib_p "$dlprefile"; then + func_tr_sh "$dlprefile" + eval "curr_lafile=\$libfile_$func_tr_sh_result" + dlprefile_dlbasename="" + if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then + # Use subshell, to avoid clobbering current variable values + dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` + if test -n "$dlprefile_dlname" ; then + func_basename "$dlprefile_dlname" + dlprefile_dlbasename="$func_basename_result" + else + # no lafile. user explicitly requested -dlpreopen . + $sharedlib_from_linklib_cmd "$dlprefile" + dlprefile_dlbasename=$sharedlib_from_linklib_result + fi + fi + $opt_dry_run || { + if test -n "$dlprefile_dlbasename" ; then + eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' + else + func_warning "Could not compute DLL name from $name" + eval '$ECHO ": $name " >> "$nlist"' + fi + func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | + $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" + } + else # not an import lib + $opt_dry_run || { + eval '$ECHO ": $name " >> "$nlist"' + func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" + } + fi + ;; + *) + $opt_dry_run || { + eval '$ECHO ": $name " >> "$nlist"' + func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" + } + ;; + esac + done + + $opt_dry_run || { + # Make sure we have at least an empty file. + test -f "$nlist" || : > "$nlist" + + if test -n "$exclude_expsyms"; then + $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T + $MV "$nlist"T "$nlist" + fi + + # Try sorting and uniquifying the output. + if $GREP -v "^: " < "$nlist" | + if sort -k 3 /dev/null 2>&1; then + sort -k 3 + else + sort +2 + fi | + uniq > "$nlist"S; then + : + else + $GREP -v "^: " < "$nlist" > "$nlist"S + fi + + if test -f "$nlist"S; then + eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' + else + echo '/* NONE */' >> "$output_objdir/$my_dlsyms" + fi + + echo >> "$output_objdir/$my_dlsyms" "\ + +/* The mapping between symbol names and symbols. */ +typedef struct { + const char *name; + void *address; +} lt_dlsymlist; +extern LT_DLSYM_CONST lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[]; +LT_DLSYM_CONST lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[] = +{\ + { \"$my_originator\", (void *) 0 }," + + case $need_lib_prefix in + no) + eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + *) + eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + esac + echo >> "$output_objdir/$my_dlsyms" "\ + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt_${my_prefix}_LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif\ +" + } # !$opt_dry_run + + pic_flag_for_symtable= + case "$compile_command " in + *" -static "*) ;; + *) + case $host in + # compiling the symbol table file with pic_flag works around + # a FreeBSD bug that causes programs to crash when -lm is + # linked before any other PIC object. But we must not use + # pic_flag when linking with -static. The problem exists in + # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. + *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) + pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; + *-*-hpux*) + pic_flag_for_symtable=" $pic_flag" ;; + *) + if test "X$my_pic_p" != Xno; then + pic_flag_for_symtable=" $pic_flag" + fi + ;; + esac + ;; + esac + symtab_cflags= + for arg in $LTCFLAGS; do + case $arg in + -pie | -fpie | -fPIE) ;; + *) func_append symtab_cflags " $arg" ;; + esac + done + + # Now compile the dynamic symbol file. + func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' + + # Clean up the generated files. + func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' + + # Transform the symbol file into the correct name. + symfileobj="$output_objdir/${my_outputname}S.$objext" + case $host in + *cygwin* | *mingw* | *cegcc* ) + if test -f "$output_objdir/$my_outputname.def"; then + compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + else + compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` + fi + ;; + *) + compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` + ;; + esac + ;; + *) + func_fatal_error "unknown suffix for \`$my_dlsyms'" + ;; + esac + else + # We keep going just in case the user didn't refer to + # lt_preloaded_symbols. The linker will fail if global_symbol_pipe + # really was required. + + # Nullify the symbol file. + compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` + fi +} + +# func_win32_libid arg +# return the library type of file 'arg' +# +# Need a lot of goo to handle *both* DLLs and import libs +# Has to be a shell function in order to 'eat' the argument +# that is supplied when $file_magic_command is called. +# Despite the name, also deal with 64 bit binaries. +func_win32_libid () +{ + $opt_debug + win32_libid_type="unknown" + win32_fileres=`file -L $1 2>/dev/null` + case $win32_fileres in + *ar\ archive\ import\ library*) # definitely import + win32_libid_type="x86 archive import" + ;; + *ar\ archive*) # could be an import, or static + # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. + if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | + $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then + func_to_tool_file "$1" func_convert_file_msys_to_w32 + win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | + $SED -n -e ' + 1,100{ + / I /{ + s,.*,import, + p + q + } + }'` + case $win32_nmres in + import*) win32_libid_type="x86 archive import";; + *) win32_libid_type="x86 archive static";; + esac + fi + ;; + *DLL*) + win32_libid_type="x86 DLL" + ;; + *executable*) # but shell scripts are "executable" too... + case $win32_fileres in + *MS\ Windows\ PE\ Intel*) + win32_libid_type="x86 DLL" + ;; + esac + ;; + esac + $ECHO "$win32_libid_type" +} + +# func_cygming_dll_for_implib ARG +# +# Platform-specific function to extract the +# name of the DLL associated with the specified +# import library ARG. +# Invoked by eval'ing the libtool variable +# $sharedlib_from_linklib_cmd +# Result is available in the variable +# $sharedlib_from_linklib_result +func_cygming_dll_for_implib () +{ + $opt_debug + sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` +} + +# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs +# +# The is the core of a fallback implementation of a +# platform-specific function to extract the name of the +# DLL associated with the specified import library LIBNAME. +# +# SECTION_NAME is either .idata$6 or .idata$7, depending +# on the platform and compiler that created the implib. +# +# Echos the name of the DLL associated with the +# specified import library. +func_cygming_dll_for_implib_fallback_core () +{ + $opt_debug + match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` + $OBJDUMP -s --section "$1" "$2" 2>/dev/null | + $SED '/^Contents of section '"$match_literal"':/{ + # Place marker at beginning of archive member dllname section + s/.*/====MARK====/ + p + d + } + # These lines can sometimes be longer than 43 characters, but + # are always uninteresting + /:[ ]*file format pe[i]\{,1\}-/d + /^In archive [^:]*:/d + # Ensure marker is printed + /^====MARK====/p + # Remove all lines with less than 43 characters + /^.\{43\}/!d + # From remaining lines, remove first 43 characters + s/^.\{43\}//' | + $SED -n ' + # Join marker and all lines until next marker into a single line + /^====MARK====/ b para + H + $ b para + b + :para + x + s/\n//g + # Remove the marker + s/^====MARK====// + # Remove trailing dots and whitespace + s/[\. \t]*$// + # Print + /./p' | + # we now have a list, one entry per line, of the stringified + # contents of the appropriate section of all members of the + # archive which possess that section. Heuristic: eliminate + # all those which have a first or second character that is + # a '.' (that is, objdump's representation of an unprintable + # character.) This should work for all archives with less than + # 0x302f exports -- but will fail for DLLs whose name actually + # begins with a literal '.' or a single character followed by + # a '.'. + # + # Of those that remain, print the first one. + $SED -e '/^\./d;/^.\./d;q' +} + +# func_cygming_gnu_implib_p ARG +# This predicate returns with zero status (TRUE) if +# ARG is a GNU/binutils-style import library. Returns +# with nonzero status (FALSE) otherwise. +func_cygming_gnu_implib_p () +{ + $opt_debug + func_to_tool_file "$1" func_convert_file_msys_to_w32 + func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` + test -n "$func_cygming_gnu_implib_tmp" +} + +# func_cygming_ms_implib_p ARG +# This predicate returns with zero status (TRUE) if +# ARG is an MS-style import library. Returns +# with nonzero status (FALSE) otherwise. +func_cygming_ms_implib_p () +{ + $opt_debug + func_to_tool_file "$1" func_convert_file_msys_to_w32 + func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` + test -n "$func_cygming_ms_implib_tmp" +} + +# func_cygming_dll_for_implib_fallback ARG +# Platform-specific function to extract the +# name of the DLL associated with the specified +# import library ARG. +# +# This fallback implementation is for use when $DLLTOOL +# does not support the --identify-strict option. +# Invoked by eval'ing the libtool variable +# $sharedlib_from_linklib_cmd +# Result is available in the variable +# $sharedlib_from_linklib_result +func_cygming_dll_for_implib_fallback () +{ + $opt_debug + if func_cygming_gnu_implib_p "$1" ; then + # binutils import library + sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` + elif func_cygming_ms_implib_p "$1" ; then + # ms-generated import library + sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` + else + # unknown + sharedlib_from_linklib_result="" + fi +} + + +# func_extract_an_archive dir oldlib +func_extract_an_archive () +{ + $opt_debug + f_ex_an_ar_dir="$1"; shift + f_ex_an_ar_oldlib="$1" + if test "$lock_old_archive_extraction" = yes; then + lockfile=$f_ex_an_ar_oldlib.lock + until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do + func_echo "Waiting for $lockfile to be removed" + sleep 2 + done + fi + func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ + 'stat=$?; rm -f "$lockfile"; exit $stat' + if test "$lock_old_archive_extraction" = yes; then + $opt_dry_run || rm -f "$lockfile" + fi + if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then + : + else + func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" + fi +} + + +# func_extract_archives gentop oldlib ... +func_extract_archives () +{ + $opt_debug + my_gentop="$1"; shift + my_oldlibs=${1+"$@"} + my_oldobjs="" + my_xlib="" + my_xabs="" + my_xdir="" + + for my_xlib in $my_oldlibs; do + # Extract the objects. + case $my_xlib in + [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; + *) my_xabs=`pwd`"/$my_xlib" ;; + esac + func_basename "$my_xlib" + my_xlib="$func_basename_result" + my_xlib_u=$my_xlib + while :; do + case " $extracted_archives " in + *" $my_xlib_u "*) + func_arith $extracted_serial + 1 + extracted_serial=$func_arith_result + my_xlib_u=lt$extracted_serial-$my_xlib ;; + *) break ;; + esac + done + extracted_archives="$extracted_archives $my_xlib_u" + my_xdir="$my_gentop/$my_xlib_u" + + func_mkdir_p "$my_xdir" + + case $host in + *-darwin*) + func_verbose "Extracting $my_xabs" + # Do not bother doing anything if just a dry run + $opt_dry_run || { + darwin_orig_dir=`pwd` + cd $my_xdir || exit $? + darwin_archive=$my_xabs + darwin_curdir=`pwd` + darwin_base_archive=`basename "$darwin_archive"` + darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` + if test -n "$darwin_arches"; then + darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` + darwin_arch= + func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" + for darwin_arch in $darwin_arches ; do + func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" + $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" + cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" + func_extract_an_archive "`pwd`" "${darwin_base_archive}" + cd "$darwin_curdir" + $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" + done # $darwin_arches + ## Okay now we've a bunch of thin objects, gotta fatten them up :) + darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` + darwin_file= + darwin_files= + for darwin_file in $darwin_filelist; do + darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` + $LIPO -create -output "$darwin_file" $darwin_files + done # $darwin_filelist + $RM -rf unfat-$$ + cd "$darwin_orig_dir" + else + cd $darwin_orig_dir + func_extract_an_archive "$my_xdir" "$my_xabs" + fi # $darwin_arches + } # !$opt_dry_run + ;; + *) + func_extract_an_archive "$my_xdir" "$my_xabs" + ;; + esac + my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` + done + + func_extract_archives_result="$my_oldobjs" +} + + +# func_emit_wrapper [arg=no] +# +# Emit a libtool wrapper script on stdout. +# Don't directly open a file because we may want to +# incorporate the script contents within a cygwin/mingw +# wrapper executable. Must ONLY be called from within +# func_mode_link because it depends on a number of variables +# set therein. +# +# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR +# variable will take. If 'yes', then the emitted script +# will assume that the directory in which it is stored is +# the $objdir directory. This is a cygwin/mingw-specific +# behavior. +func_emit_wrapper () +{ + func_emit_wrapper_arg1=${1-no} + + $ECHO "\ +#! $SHELL + +# $output - temporary wrapper script for $objdir/$outputname +# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION +# +# The $output program cannot be directly executed until all the libtool +# libraries that it depends on are installed. +# +# This wrapper script should never be moved out of the build directory. +# If it is, it will not operate correctly. + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +sed_quote_subst='$sed_quote_subst' + +# Be Bourne compatible +if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac +fi +BIN_SH=xpg4; export BIN_SH # for Tru64 +DUALCASE=1; export DUALCASE # for MKS sh + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +relink_command=\"$relink_command\" + +# This environment variable determines our operation mode. +if test \"\$libtool_install_magic\" = \"$magic\"; then + # install mode needs the following variables: + generated_by_libtool_version='$macro_version' + notinst_deplibs='$notinst_deplibs' +else + # When we are sourced in execute mode, \$file and \$ECHO are already set. + if test \"\$libtool_execute_magic\" != \"$magic\"; then + file=\"\$0\"" + + qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` + $ECHO "\ + +# A function that is used when there is no print builtin or printf. +func_fallback_echo () +{ + eval 'cat <<_LTECHO_EOF +\$1 +_LTECHO_EOF' +} + ECHO=\"$qECHO\" + fi + +# Very basic option parsing. These options are (a) specific to +# the libtool wrapper, (b) are identical between the wrapper +# /script/ and the wrapper /executable/ which is used only on +# windows platforms, and (c) all begin with the string "--lt-" +# (application programs are unlikely to have options which match +# this pattern). +# +# There are only two supported options: --lt-debug and +# --lt-dump-script. There is, deliberately, no --lt-help. +# +# The first argument to this parsing function should be the +# script's $0 value, followed by "$@". +lt_option_debug= +func_parse_lt_options () +{ + lt_script_arg0=\$0 + shift + for lt_opt + do + case \"\$lt_opt\" in + --lt-debug) lt_option_debug=1 ;; + --lt-dump-script) + lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` + test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. + lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` + cat \"\$lt_dump_D/\$lt_dump_F\" + exit 0 + ;; + --lt-*) + \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 + exit 1 + ;; + esac + done + + # Print the debug banner immediately: + if test -n \"\$lt_option_debug\"; then + echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2 + fi +} + +# Used when --lt-debug. Prints its arguments to stdout +# (redirection is the responsibility of the caller) +func_lt_dump_args () +{ + lt_dump_args_N=1; + for lt_arg + do + \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\" + lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` + done +} + +# Core function for launching the target application +func_exec_program_core () +{ +" + case $host in + # Backslashes separate directories on plain windows + *-*-mingw | *-*-os2* | *-cegcc*) + $ECHO "\ + if test -n \"\$lt_option_debug\"; then + \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2 + func_lt_dump_args \${1+\"\$@\"} 1>&2 + fi + exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} +" + ;; + + *) + $ECHO "\ + if test -n \"\$lt_option_debug\"; then + \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2 + func_lt_dump_args \${1+\"\$@\"} 1>&2 + fi + exec \"\$progdir/\$program\" \${1+\"\$@\"} +" + ;; + esac + $ECHO "\ + \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 + exit 1 +} + +# A function to encapsulate launching the target application +# Strips options in the --lt-* namespace from \$@ and +# launches target application with the remaining arguments. +func_exec_program () +{ + case \" \$* \" in + *\\ --lt-*) + for lt_wr_arg + do + case \$lt_wr_arg in + --lt-*) ;; + *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; + esac + shift + done ;; + esac + func_exec_program_core \${1+\"\$@\"} +} + + # Parse options + func_parse_lt_options \"\$0\" \${1+\"\$@\"} + + # Find the directory that this script lives in. + thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` + test \"x\$thisdir\" = \"x\$file\" && thisdir=. + + # Follow symbolic links until we get to the real thisdir. + file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` + while test -n \"\$file\"; do + destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` + + # If there was a directory component, then change thisdir. + if test \"x\$destdir\" != \"x\$file\"; then + case \"\$destdir\" in + [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; + *) thisdir=\"\$thisdir/\$destdir\" ;; + esac + fi + + file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` + file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` + done + + # Usually 'no', except on cygwin/mingw when embedded into + # the cwrapper. + WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 + if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then + # special case for '.' + if test \"\$thisdir\" = \".\"; then + thisdir=\`pwd\` + fi + # remove .libs from thisdir + case \"\$thisdir\" in + *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; + $objdir ) thisdir=. ;; + esac + fi + + # Try to get the absolute directory name. + absdir=\`cd \"\$thisdir\" && pwd\` + test -n \"\$absdir\" && thisdir=\"\$absdir\" +" + + if test "$fast_install" = yes; then + $ECHO "\ + program=lt-'$outputname'$exeext + progdir=\"\$thisdir/$objdir\" + + if test ! -f \"\$progdir/\$program\" || + { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ + test \"X\$file\" != \"X\$progdir/\$program\"; }; then + + file=\"\$\$-\$program\" + + if test ! -d \"\$progdir\"; then + $MKDIR \"\$progdir\" + else + $RM \"\$progdir/\$file\" + fi" + + $ECHO "\ + + # relink executable if necessary + if test -n \"\$relink_command\"; then + if relink_command_output=\`eval \$relink_command 2>&1\`; then : + else + $ECHO \"\$relink_command_output\" >&2 + $RM \"\$progdir/\$file\" + exit 1 + fi + fi + + $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || + { $RM \"\$progdir/\$program\"; + $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } + $RM \"\$progdir/\$file\" + fi" + else + $ECHO "\ + program='$outputname' + progdir=\"\$thisdir/$objdir\" +" + fi + + $ECHO "\ + + if test -f \"\$progdir/\$program\"; then" + + # fixup the dll searchpath if we need to. + # + # Fix the DLL searchpath if we need to. Do this before prepending + # to shlibpath, because on Windows, both are PATH and uninstalled + # libraries must come first. + if test -n "$dllsearchpath"; then + $ECHO "\ + # Add the dll search path components to the executable PATH + PATH=$dllsearchpath:\$PATH +" + fi + + # Export our shlibpath_var if we have one. + if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then + $ECHO "\ + # Add our own library path to $shlibpath_var + $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" + + # Some systems cannot cope with colon-terminated $shlibpath_var + # The second colon is a workaround for a bug in BeOS R4 sed + $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` + + export $shlibpath_var +" + fi + + $ECHO "\ + if test \"\$libtool_execute_magic\" != \"$magic\"; then + # Run the actual program with our arguments. + func_exec_program \${1+\"\$@\"} + fi + else + # The program doesn't exist. + \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 + \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 + \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 + exit 1 + fi +fi\ +" +} + + +# func_emit_cwrapperexe_src +# emit the source code for a wrapper executable on stdout +# Must ONLY be called from within func_mode_link because +# it depends on a number of variable set therein. +func_emit_cwrapperexe_src () +{ + cat < +#include +#ifdef _MSC_VER +# include +# include +# include +#else +# include +# include +# ifdef __CYGWIN__ +# include +# endif +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +/* declarations of non-ANSI functions */ +#if defined(__MINGW32__) +# ifdef __STRICT_ANSI__ +int _putenv (const char *); +# endif +#elif defined(__CYGWIN__) +# ifdef __STRICT_ANSI__ +char *realpath (const char *, char *); +int putenv (char *); +int setenv (const char *, const char *, int); +# endif +/* #elif defined (other platforms) ... */ +#endif + +/* portability defines, excluding path handling macros */ +#if defined(_MSC_VER) +# define setmode _setmode +# define stat _stat +# define chmod _chmod +# define getcwd _getcwd +# define putenv _putenv +# define S_IXUSR _S_IEXEC +# ifndef _INTPTR_T_DEFINED +# define _INTPTR_T_DEFINED +# define intptr_t int +# endif +#elif defined(__MINGW32__) +# define setmode _setmode +# define stat _stat +# define chmod _chmod +# define getcwd _getcwd +# define putenv _putenv +#elif defined(__CYGWIN__) +# define HAVE_SETENV +# define FOPEN_WB "wb" +/* #elif defined (other platforms) ... */ +#endif + +#if defined(PATH_MAX) +# define LT_PATHMAX PATH_MAX +#elif defined(MAXPATHLEN) +# define LT_PATHMAX MAXPATHLEN +#else +# define LT_PATHMAX 1024 +#endif + +#ifndef S_IXOTH +# define S_IXOTH 0 +#endif +#ifndef S_IXGRP +# define S_IXGRP 0 +#endif + +/* path handling portability macros */ +#ifndef DIR_SEPARATOR +# define DIR_SEPARATOR '/' +# define PATH_SEPARATOR ':' +#endif + +#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ + defined (__OS2__) +# define HAVE_DOS_BASED_FILE_SYSTEM +# define FOPEN_WB "wb" +# ifndef DIR_SEPARATOR_2 +# define DIR_SEPARATOR_2 '\\' +# endif +# ifndef PATH_SEPARATOR_2 +# define PATH_SEPARATOR_2 ';' +# endif +#endif + +#ifndef DIR_SEPARATOR_2 +# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) +#else /* DIR_SEPARATOR_2 */ +# define IS_DIR_SEPARATOR(ch) \ + (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) +#endif /* DIR_SEPARATOR_2 */ + +#ifndef PATH_SEPARATOR_2 +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) +#else /* PATH_SEPARATOR_2 */ +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) +#endif /* PATH_SEPARATOR_2 */ + +#ifndef FOPEN_WB +# define FOPEN_WB "w" +#endif +#ifndef _O_BINARY +# define _O_BINARY 0 +#endif + +#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) +#define XFREE(stale) do { \ + if (stale) { free ((void *) stale); stale = 0; } \ +} while (0) + +#if defined(LT_DEBUGWRAPPER) +static int lt_debug = 1; +#else +static int lt_debug = 0; +#endif + +const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ + +void *xmalloc (size_t num); +char *xstrdup (const char *string); +const char *base_name (const char *name); +char *find_executable (const char *wrapper); +char *chase_symlinks (const char *pathspec); +int make_executable (const char *path); +int check_executable (const char *path); +char *strendzap (char *str, const char *pat); +void lt_debugprintf (const char *file, int line, const char *fmt, ...); +void lt_fatal (const char *file, int line, const char *message, ...); +static const char *nonnull (const char *s); +static const char *nonempty (const char *s); +void lt_setenv (const char *name, const char *value); +char *lt_extend_str (const char *orig_value, const char *add, int to_end); +void lt_update_exe_path (const char *name, const char *value); +void lt_update_lib_path (const char *name, const char *value); +char **prepare_spawn (char **argv); +void lt_dump_script (FILE *f); +EOF + + cat <= 0) + && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) + return 1; + else + return 0; +} + +int +make_executable (const char *path) +{ + int rval = 0; + struct stat st; + + lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", + nonempty (path)); + if ((!path) || (!*path)) + return 0; + + if (stat (path, &st) >= 0) + { + rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); + } + return rval; +} + +/* Searches for the full path of the wrapper. Returns + newly allocated full path name if found, NULL otherwise + Does not chase symlinks, even on platforms that support them. +*/ +char * +find_executable (const char *wrapper) +{ + int has_slash = 0; + const char *p; + const char *p_next; + /* static buffer for getcwd */ + char tmp[LT_PATHMAX + 1]; + int tmp_len; + char *concat_name; + + lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", + nonempty (wrapper)); + + if ((wrapper == NULL) || (*wrapper == '\0')) + return NULL; + + /* Absolute path? */ +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + else + { +#endif + if (IS_DIR_SEPARATOR (wrapper[0])) + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + } +#endif + + for (p = wrapper; *p; p++) + if (*p == '/') + { + has_slash = 1; + break; + } + if (!has_slash) + { + /* no slashes; search PATH */ + const char *path = getenv ("PATH"); + if (path != NULL) + { + for (p = path; *p; p = p_next) + { + const char *q; + size_t p_len; + for (q = p; *q; q++) + if (IS_PATH_SEPARATOR (*q)) + break; + p_len = q - p; + p_next = (*q == '\0' ? q : q + 1); + if (p_len == 0) + { + /* empty path: current directory */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", + nonnull (strerror (errno))); + tmp_len = strlen (tmp); + concat_name = + XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + } + else + { + concat_name = + XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, p, p_len); + concat_name[p_len] = '/'; + strcpy (concat_name + p_len + 1, wrapper); + } + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + } + /* not found in PATH; assume curdir */ + } + /* Relative path | not found in path: prepend cwd */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", + nonnull (strerror (errno))); + tmp_len = strlen (tmp); + concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + return NULL; +} + +char * +chase_symlinks (const char *pathspec) +{ +#ifndef S_ISLNK + return xstrdup (pathspec); +#else + char buf[LT_PATHMAX]; + struct stat s; + char *tmp_pathspec = xstrdup (pathspec); + char *p; + int has_symlinks = 0; + while (strlen (tmp_pathspec) && !has_symlinks) + { + lt_debugprintf (__FILE__, __LINE__, + "checking path component for symlinks: %s\n", + tmp_pathspec); + if (lstat (tmp_pathspec, &s) == 0) + { + if (S_ISLNK (s.st_mode) != 0) + { + has_symlinks = 1; + break; + } + + /* search backwards for last DIR_SEPARATOR */ + p = tmp_pathspec + strlen (tmp_pathspec) - 1; + while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + p--; + if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + { + /* no more DIR_SEPARATORS left */ + break; + } + *p = '\0'; + } + else + { + lt_fatal (__FILE__, __LINE__, + "error accessing file \"%s\": %s", + tmp_pathspec, nonnull (strerror (errno))); + } + } + XFREE (tmp_pathspec); + + if (!has_symlinks) + { + return xstrdup (pathspec); + } + + tmp_pathspec = realpath (pathspec, buf); + if (tmp_pathspec == 0) + { + lt_fatal (__FILE__, __LINE__, + "could not follow symlinks for %s", pathspec); + } + return xstrdup (tmp_pathspec); +#endif +} + +char * +strendzap (char *str, const char *pat) +{ + size_t len, patlen; + + assert (str != NULL); + assert (pat != NULL); + + len = strlen (str); + patlen = strlen (pat); + + if (patlen <= len) + { + str += len - patlen; + if (strcmp (str, pat) == 0) + *str = '\0'; + } + return str; +} + +void +lt_debugprintf (const char *file, int line, const char *fmt, ...) +{ + va_list args; + if (lt_debug) + { + (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); + va_start (args, fmt); + (void) vfprintf (stderr, fmt, args); + va_end (args); + } +} + +static void +lt_error_core (int exit_status, const char *file, + int line, const char *mode, + const char *message, va_list ap) +{ + fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); + vfprintf (stderr, message, ap); + fprintf (stderr, ".\n"); + + if (exit_status >= 0) + exit (exit_status); +} + +void +lt_fatal (const char *file, int line, const char *message, ...) +{ + va_list ap; + va_start (ap, message); + lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); + va_end (ap); +} + +static const char * +nonnull (const char *s) +{ + return s ? s : "(null)"; +} + +static const char * +nonempty (const char *s) +{ + return (s && !*s) ? "(empty)" : nonnull (s); +} + +void +lt_setenv (const char *name, const char *value) +{ + lt_debugprintf (__FILE__, __LINE__, + "(lt_setenv) setting '%s' to '%s'\n", + nonnull (name), nonnull (value)); + { +#ifdef HAVE_SETENV + /* always make a copy, for consistency with !HAVE_SETENV */ + char *str = xstrdup (value); + setenv (name, str, 1); +#else + int len = strlen (name) + 1 + strlen (value) + 1; + char *str = XMALLOC (char, len); + sprintf (str, "%s=%s", name, value); + if (putenv (str) != EXIT_SUCCESS) + { + XFREE (str); + } +#endif + } +} + +char * +lt_extend_str (const char *orig_value, const char *add, int to_end) +{ + char *new_value; + if (orig_value && *orig_value) + { + int orig_value_len = strlen (orig_value); + int add_len = strlen (add); + new_value = XMALLOC (char, add_len + orig_value_len + 1); + if (to_end) + { + strcpy (new_value, orig_value); + strcpy (new_value + orig_value_len, add); + } + else + { + strcpy (new_value, add); + strcpy (new_value + add_len, orig_value); + } + } + else + { + new_value = xstrdup (add); + } + return new_value; +} + +void +lt_update_exe_path (const char *name, const char *value) +{ + lt_debugprintf (__FILE__, __LINE__, + "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", + nonnull (name), nonnull (value)); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + /* some systems can't cope with a ':'-terminated path #' */ + int len = strlen (new_value); + while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) + { + new_value[len-1] = '\0'; + } + lt_setenv (name, new_value); + XFREE (new_value); + } +} + +void +lt_update_lib_path (const char *name, const char *value) +{ + lt_debugprintf (__FILE__, __LINE__, + "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", + nonnull (name), nonnull (value)); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + lt_setenv (name, new_value); + XFREE (new_value); + } +} + +EOF + case $host_os in + mingw*) + cat <<"EOF" + +/* Prepares an argument vector before calling spawn(). + Note that spawn() does not by itself call the command interpreter + (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : + ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&v); + v.dwPlatformId == VER_PLATFORM_WIN32_NT; + }) ? "cmd.exe" : "command.com"). + Instead it simply concatenates the arguments, separated by ' ', and calls + CreateProcess(). We must quote the arguments since Win32 CreateProcess() + interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a + special way: + - Space and tab are interpreted as delimiters. They are not treated as + delimiters if they are surrounded by double quotes: "...". + - Unescaped double quotes are removed from the input. Their only effect is + that within double quotes, space and tab are treated like normal + characters. + - Backslashes not followed by double quotes are not special. + - But 2*n+1 backslashes followed by a double quote become + n backslashes followed by a double quote (n >= 0): + \" -> " + \\\" -> \" + \\\\\" -> \\" + */ +#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" +#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" +char ** +prepare_spawn (char **argv) +{ + size_t argc; + char **new_argv; + size_t i; + + /* Count number of arguments. */ + for (argc = 0; argv[argc] != NULL; argc++) + ; + + /* Allocate new argument vector. */ + new_argv = XMALLOC (char *, argc + 1); + + /* Put quoted arguments into the new argument vector. */ + for (i = 0; i < argc; i++) + { + const char *string = argv[i]; + + if (string[0] == '\0') + new_argv[i] = xstrdup ("\"\""); + else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) + { + int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); + size_t length; + unsigned int backslashes; + const char *s; + char *quoted_string; + char *p; + + length = 0; + backslashes = 0; + if (quote_around) + length++; + for (s = string; *s != '\0'; s++) + { + char c = *s; + if (c == '"') + length += backslashes + 1; + length++; + if (c == '\\') + backslashes++; + else + backslashes = 0; + } + if (quote_around) + length += backslashes + 1; + + quoted_string = XMALLOC (char, length + 1); + + p = quoted_string; + backslashes = 0; + if (quote_around) + *p++ = '"'; + for (s = string; *s != '\0'; s++) + { + char c = *s; + if (c == '"') + { + unsigned int j; + for (j = backslashes + 1; j > 0; j--) + *p++ = '\\'; + } + *p++ = c; + if (c == '\\') + backslashes++; + else + backslashes = 0; + } + if (quote_around) + { + unsigned int j; + for (j = backslashes; j > 0; j--) + *p++ = '\\'; + *p++ = '"'; + } + *p = '\0'; + + new_argv[i] = quoted_string; + } + else + new_argv[i] = (char *) string; + } + new_argv[argc] = NULL; + + return new_argv; +} +EOF + ;; + esac + + cat <<"EOF" +void lt_dump_script (FILE* f) +{ +EOF + func_emit_wrapper yes | + $SED -n -e ' +s/^\(.\{79\}\)\(..*\)/\1\ +\2/ +h +s/\([\\"]\)/\\\1/g +s/$/\\n/ +s/\([^\n]*\).*/ fputs ("\1", f);/p +g +D' + cat <<"EOF" +} +EOF +} +# end: func_emit_cwrapperexe_src + +# func_win32_import_lib_p ARG +# True if ARG is an import lib, as indicated by $file_magic_cmd +func_win32_import_lib_p () +{ + $opt_debug + case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in + *import*) : ;; + *) false ;; + esac +} + +# func_mode_link arg... +func_mode_link () +{ + $opt_debug + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + # It is impossible to link a dll without this setting, and + # we shouldn't force the makefile maintainer to figure out + # which system we are compiling for in order to pass an extra + # flag for every libtool invocation. + # allow_undefined=no + + # FIXME: Unfortunately, there are problems with the above when trying + # to make a dll which has undefined symbols, in which case not + # even a static library is built. For now, we need to specify + # -no-undefined on the libtool link line when we can be certain + # that all symbols are satisfied, otherwise we get a static library. + allow_undefined=yes + ;; + *) + allow_undefined=yes + ;; + esac + libtool_args=$nonopt + base_compile="$nonopt $@" + compile_command=$nonopt + finalize_command=$nonopt + + compile_rpath= + finalize_rpath= + compile_shlibpath= + finalize_shlibpath= + convenience= + old_convenience= + deplibs= + old_deplibs= + compiler_flags= + linker_flags= + dllsearchpath= + lib_search_path=`pwd` + inst_prefix_dir= + new_inherited_linker_flags= + + avoid_version=no + bindir= + dlfiles= + dlprefiles= + dlself=no + export_dynamic=no + export_symbols= + export_symbols_regex= + generated= + libobjs= + ltlibs= + module=no + no_install=no + objs= + non_pic_objects= + precious_files_regex= + prefer_static_libs=no + preload=no + prev= + prevarg= + release= + rpath= + xrpath= + perm_rpath= + temp_rpath= + thread_safe=no + vinfo= + vinfo_number=no + weak_libs= + single_module="${wl}-single_module" + func_infer_tag $base_compile + + # We need to know -static, to get the right output filenames. + for arg + do + case $arg in + -shared) + test "$build_libtool_libs" != yes && \ + func_fatal_configuration "can not build a shared library" + build_old_libs=no + break + ;; + -all-static | -static | -static-libtool-libs) + case $arg in + -all-static) + if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then + func_warning "complete static linking is impossible in this configuration" + fi + if test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + -static) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=built + ;; + -static-libtool-libs) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + esac + build_libtool_libs=no + build_old_libs=yes + break + ;; + esac + done + + # See if our shared archives depend on static archives. + test -n "$old_archive_from_new_cmds" && build_old_libs=yes + + # Go through the arguments, transforming them on the way. + while test "$#" -gt 0; do + arg="$1" + shift + func_quote_for_eval "$arg" + qarg=$func_quote_for_eval_unquoted_result + func_append libtool_args " $func_quote_for_eval_result" + + # If the previous option needs an argument, assign it. + if test -n "$prev"; then + case $prev in + output) + func_append compile_command " @OUTPUT@" + func_append finalize_command " @OUTPUT@" + ;; + esac + + case $prev in + bindir) + bindir="$arg" + prev= + continue + ;; + dlfiles|dlprefiles) + if test "$preload" = no; then + # Add the symbol object into the linking commands. + func_append compile_command " @SYMFILE@" + func_append finalize_command " @SYMFILE@" + preload=yes + fi + case $arg in + *.la | *.lo) ;; # We handle these cases below. + force) + if test "$dlself" = no; then + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + self) + if test "$prev" = dlprefiles; then + dlself=yes + elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then + dlself=yes + else + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + *) + if test "$prev" = dlfiles; then + func_append dlfiles " $arg" + else + func_append dlprefiles " $arg" + fi + prev= + continue + ;; + esac + ;; + expsyms) + export_symbols="$arg" + test -f "$arg" \ + || func_fatal_error "symbol file \`$arg' does not exist" + prev= + continue + ;; + expsyms_regex) + export_symbols_regex="$arg" + prev= + continue + ;; + framework) + case $host in + *-*-darwin*) + case "$deplibs " in + *" $qarg.ltframework "*) ;; + *) func_append deplibs " $qarg.ltframework" # this is fixed later + ;; + esac + ;; + esac + prev= + continue + ;; + inst_prefix) + inst_prefix_dir="$arg" + prev= + continue + ;; + objectlist) + if test -f "$arg"; then + save_arg=$arg + moreargs= + for fil in `cat "$save_arg"` + do +# func_append moreargs " $fil" + arg=$fil + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test "$pic_object" = none && + test "$non_pic_object" = none; then + func_fatal_error "cannot find name of object for \`$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + func_append dlfiles " $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + func_append dlprefiles " $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object="$pic_object" + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "\`$arg' is not a valid libtool object" + fi + fi + done + else + func_fatal_error "link input file \`$arg' does not exist" + fi + arg=$save_arg + prev= + continue + ;; + precious_regex) + precious_files_regex="$arg" + prev= + continue + ;; + release) + release="-$arg" + prev= + continue + ;; + rpath | xrpath) + # We need an absolute path. + case $arg in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + if test "$prev" = rpath; then + case "$rpath " in + *" $arg "*) ;; + *) func_append rpath " $arg" ;; + esac + else + case "$xrpath " in + *" $arg "*) ;; + *) func_append xrpath " $arg" ;; + esac + fi + prev= + continue + ;; + shrext) + shrext_cmds="$arg" + prev= + continue + ;; + weak) + func_append weak_libs " $arg" + prev= + continue + ;; + xcclinker) + func_append linker_flags " $qarg" + func_append compiler_flags " $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xcompiler) + func_append compiler_flags " $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xlinker) + func_append linker_flags " $qarg" + func_append compiler_flags " $wl$qarg" + prev= + func_append compile_command " $wl$qarg" + func_append finalize_command " $wl$qarg" + continue + ;; + *) + eval "$prev=\"\$arg\"" + prev= + continue + ;; + esac + fi # test -n "$prev" + + prevarg="$arg" + + case $arg in + -all-static) + if test -n "$link_static_flag"; then + # See comment for -static flag below, for more details. + func_append compile_command " $link_static_flag" + func_append finalize_command " $link_static_flag" + fi + continue + ;; + + -allow-undefined) + # FIXME: remove this flag sometime in the future. + func_fatal_error "\`-allow-undefined' must not be used because it is the default" + ;; + + -avoid-version) + avoid_version=yes + continue + ;; + + -bindir) + prev=bindir + continue + ;; + + -dlopen) + prev=dlfiles + continue + ;; + + -dlpreopen) + prev=dlprefiles + continue + ;; + + -export-dynamic) + export_dynamic=yes + continue + ;; + + -export-symbols | -export-symbols-regex) + if test -n "$export_symbols" || test -n "$export_symbols_regex"; then + func_fatal_error "more than one -exported-symbols argument is not allowed" + fi + if test "X$arg" = "X-export-symbols"; then + prev=expsyms + else + prev=expsyms_regex + fi + continue + ;; + + -framework) + prev=framework + continue + ;; + + -inst-prefix-dir) + prev=inst_prefix + continue + ;; + + # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* + # so, if we see these flags be careful not to treat them like -L + -L[A-Z][A-Z]*:*) + case $with_gcc/$host in + no/*-*-irix* | /*-*-irix*) + func_append compile_command " $arg" + func_append finalize_command " $arg" + ;; + esac + continue + ;; + + -L*) + func_stripname "-L" '' "$arg" + if test -z "$func_stripname_result"; then + if test "$#" -gt 0; then + func_fatal_error "require no space between \`-L' and \`$1'" + else + func_fatal_error "need path for \`-L' option" + fi + fi + func_resolve_sysroot "$func_stripname_result" + dir=$func_resolve_sysroot_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + absdir=`cd "$dir" && pwd` + test -z "$absdir" && \ + func_fatal_error "cannot determine absolute directory name of \`$dir'" + dir="$absdir" + ;; + esac + case "$deplibs " in + *" -L$dir "* | *" $arg "*) + # Will only happen for absolute or sysroot arguments + ;; + *) + # Preserve sysroot, but never include relative directories + case $dir in + [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; + *) func_append deplibs " -L$dir" ;; + esac + func_append lib_search_path " $dir" + ;; + esac + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$dir:"*) ;; + ::) dllsearchpath=$dir;; + *) func_append dllsearchpath ":$dir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) func_append dllsearchpath ":$testbindir";; + esac + ;; + esac + continue + ;; + + -l*) + if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) + # These systems don't actually have a C or math library (as such) + continue + ;; + *-*-os2*) + # These systems don't actually have a C library (as such) + test "X$arg" = "X-lc" && continue + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc due to us having libc/libc_r. + test "X$arg" = "X-lc" && continue + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C and math libraries are in the System framework + func_append deplibs " System.ltframework" + continue + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + test "X$arg" = "X-lc" && continue + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + test "X$arg" = "X-lc" && continue + ;; + esac + elif test "X$arg" = "X-lc_r"; then + case $host in + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc_r directly, use -pthread flag. + continue + ;; + esac + fi + func_append deplibs " $arg" + continue + ;; + + -module) + module=yes + continue + ;; + + # Tru64 UNIX uses -model [arg] to determine the layout of C++ + # classes, name mangling, and exception handling. + # Darwin uses the -arch flag to determine output architecture. + -model|-arch|-isysroot|--sysroot) + func_append compiler_flags " $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + prev=xcompiler + continue + ;; + + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ + |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) + func_append compiler_flags " $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + case "$new_inherited_linker_flags " in + *" $arg "*) ;; + * ) func_append new_inherited_linker_flags " $arg" ;; + esac + continue + ;; + + -multi_module) + single_module="${wl}-multi_module" + continue + ;; + + -no-fast-install) + fast_install=no + continue + ;; + + -no-install) + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) + # The PATH hackery in wrapper scripts is required on Windows + # and Darwin in order for the loader to find any dlls it needs. + func_warning "\`-no-install' is ignored for $host" + func_warning "assuming \`-no-fast-install' instead" + fast_install=no + ;; + *) no_install=yes ;; + esac + continue + ;; + + -no-undefined) + allow_undefined=no + continue + ;; + + -objectlist) + prev=objectlist + continue + ;; + + -o) prev=output ;; + + -precious-files-regex) + prev=precious_regex + continue + ;; + + -release) + prev=release + continue + ;; + + -rpath) + prev=rpath + continue + ;; + + -R) + prev=xrpath + continue + ;; + + -R*) + func_stripname '-R' '' "$arg" + dir=$func_stripname_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + =*) + func_stripname '=' '' "$dir" + dir=$lt_sysroot$func_stripname_result + ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + case "$xrpath " in + *" $dir "*) ;; + *) func_append xrpath " $dir" ;; + esac + continue + ;; + + -shared) + # The effects of -shared are defined in a previous loop. + continue + ;; + + -shrext) + prev=shrext + continue + ;; + + -static | -static-libtool-libs) + # The effects of -static are defined in a previous loop. + # We used to do the same as -all-static on platforms that + # didn't have a PIC flag, but the assumption that the effects + # would be equivalent was wrong. It would break on at least + # Digital Unix and AIX. + continue + ;; + + -thread-safe) + thread_safe=yes + continue + ;; + + -version-info) + prev=vinfo + continue + ;; + + -version-number) + prev=vinfo + vinfo_number=yes + continue + ;; + + -weak) + prev=weak + continue + ;; + + -Wc,*) + func_stripname '-Wc,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + func_quote_for_eval "$flag" + func_append arg " $func_quote_for_eval_result" + func_append compiler_flags " $func_quote_for_eval_result" + done + IFS="$save_ifs" + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Wl,*) + func_stripname '-Wl,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + func_quote_for_eval "$flag" + func_append arg " $wl$func_quote_for_eval_result" + func_append compiler_flags " $wl$func_quote_for_eval_result" + func_append linker_flags " $func_quote_for_eval_result" + done + IFS="$save_ifs" + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Xcompiler) + prev=xcompiler + continue + ;; + + -Xlinker) + prev=xlinker + continue + ;; + + -XCClinker) + prev=xcclinker + continue + ;; + + # -msg_* for osf cc + -msg_*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + + # Flags to be passed through unchanged, with rationale: + # -64, -mips[0-9] enable 64-bit mode for the SGI compiler + # -r[0-9][0-9]* specify processor for the SGI compiler + # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler + # +DA*, +DD* enable 64-bit mode for the HP compiler + # -q* compiler args for the IBM compiler + # -m*, -t[45]*, -txscale* architecture-specific flags for GCC + # -F/path path to uninstalled frameworks, gcc on darwin + # -p, -pg, --coverage, -fprofile-* profiling flags for GCC + # @file GCC response files + # -tp=* Portland pgcc target processor selection + # --sysroot=* for sysroot support + # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization + -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ + -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ + -O*|-flto*|-fwhopr*|-fuse-linker-plugin) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + func_append compile_command " $arg" + func_append finalize_command " $arg" + func_append compiler_flags " $arg" + continue + ;; + + # Some other compiler flag. + -* | +*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + + *.$objext) + # A standard object. + func_append objs " $arg" + ;; + + *.lo) + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test "$pic_object" = none && + test "$non_pic_object" = none; then + func_fatal_error "cannot find name of object for \`$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + func_append dlfiles " $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + func_append dlprefiles " $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object="$pic_object" + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "\`$arg' is not a valid libtool object" + fi + fi + ;; + + *.$libext) + # An archive. + func_append deplibs " $arg" + func_append old_deplibs " $arg" + continue + ;; + + *.la) + # A libtool-controlled library. + + func_resolve_sysroot "$arg" + if test "$prev" = dlfiles; then + # This library was specified with -dlopen. + func_append dlfiles " $func_resolve_sysroot_result" + prev= + elif test "$prev" = dlprefiles; then + # The library was specified with -dlpreopen. + func_append dlprefiles " $func_resolve_sysroot_result" + prev= + else + func_append deplibs " $func_resolve_sysroot_result" + fi + continue + ;; + + # Some other compiler argument. + *) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + esac # arg + + # Now actually substitute the argument into the commands. + if test -n "$arg"; then + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + done # argument parsing loop + + test -n "$prev" && \ + func_fatal_help "the \`$prevarg' option requires an argument" + + if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then + eval arg=\"$export_dynamic_flag_spec\" + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + + oldlibs= + # calculate the name of the file, without its directory + func_basename "$output" + outputname="$func_basename_result" + libobjs_save="$libobjs" + + if test -n "$shlibpath_var"; then + # get the directories listed in $shlibpath_var + eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\` + else + shlib_search_path= + fi + eval sys_lib_search_path=\"$sys_lib_search_path_spec\" + eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" + + func_dirname "$output" "/" "" + output_objdir="$func_dirname_result$objdir" + func_to_tool_file "$output_objdir/" + tool_output_objdir=$func_to_tool_file_result + # Create the object directory. + func_mkdir_p "$output_objdir" + + # Determine the type of output + case $output in + "") + func_fatal_help "you must specify an output file" + ;; + *.$libext) linkmode=oldlib ;; + *.lo | *.$objext) linkmode=obj ;; + *.la) linkmode=lib ;; + *) linkmode=prog ;; # Anything else should be a program. + esac + + specialdeplibs= + + libs= + # Find all interdependent deplibs by searching for libraries + # that are linked more than once (e.g. -la -lb -la) + for deplib in $deplibs; do + if $opt_preserve_dup_deps ; then + case "$libs " in + *" $deplib "*) func_append specialdeplibs " $deplib" ;; + esac + fi + func_append libs " $deplib" + done + + if test "$linkmode" = lib; then + libs="$predeps $libs $compiler_lib_search_path $postdeps" + + # Compute libraries that are listed more than once in $predeps + # $postdeps and mark them as special (i.e., whose duplicates are + # not to be eliminated). + pre_post_deps= + if $opt_duplicate_compiler_generated_deps; then + for pre_post_dep in $predeps $postdeps; do + case "$pre_post_deps " in + *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; + esac + func_append pre_post_deps " $pre_post_dep" + done + fi + pre_post_deps= + fi + + deplibs= + newdependency_libs= + newlib_search_path= + need_relink=no # whether we're linking any uninstalled libtool libraries + notinst_deplibs= # not-installed libtool libraries + notinst_path= # paths that contain not-installed libtool libraries + + case $linkmode in + lib) + passes="conv dlpreopen link" + for file in $dlfiles $dlprefiles; do + case $file in + *.la) ;; + *) + func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" + ;; + esac + done + ;; + prog) + compile_deplibs= + finalize_deplibs= + alldeplibs=no + newdlfiles= + newdlprefiles= + passes="conv scan dlopen dlpreopen link" + ;; + *) passes="conv" + ;; + esac + + for pass in $passes; do + # The preopen pass in lib mode reverses $deplibs; put it back here + # so that -L comes before libs that need it for instance... + if test "$linkmode,$pass" = "lib,link"; then + ## FIXME: Find the place where the list is rebuilt in the wrong + ## order, and fix it there properly + tmp_deplibs= + for deplib in $deplibs; do + tmp_deplibs="$deplib $tmp_deplibs" + done + deplibs="$tmp_deplibs" + fi + + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan"; then + libs="$deplibs" + deplibs= + fi + if test "$linkmode" = prog; then + case $pass in + dlopen) libs="$dlfiles" ;; + dlpreopen) libs="$dlprefiles" ;; + link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; + esac + fi + if test "$linkmode,$pass" = "lib,dlpreopen"; then + # Collect and forward deplibs of preopened libtool libs + for lib in $dlprefiles; do + # Ignore non-libtool-libs + dependency_libs= + func_resolve_sysroot "$lib" + case $lib in + *.la) func_source "$func_resolve_sysroot_result" ;; + esac + + # Collect preopened libtool deplibs, except any this library + # has declared as weak libs + for deplib in $dependency_libs; do + func_basename "$deplib" + deplib_base=$func_basename_result + case " $weak_libs " in + *" $deplib_base "*) ;; + *) func_append deplibs " $deplib" ;; + esac + done + done + libs="$dlprefiles" + fi + if test "$pass" = dlopen; then + # Collect dlpreopened libraries + save_deplibs="$deplibs" + deplibs= + fi + + for deplib in $libs; do + lib= + found=no + case $deplib in + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ + |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + func_append compiler_flags " $deplib" + if test "$linkmode" = lib ; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) func_append new_inherited_linker_flags " $deplib" ;; + esac + fi + fi + continue + ;; + -l*) + if test "$linkmode" != lib && test "$linkmode" != prog; then + func_warning "\`-l' is ignored for archives/objects" + continue + fi + func_stripname '-l' '' "$deplib" + name=$func_stripname_result + if test "$linkmode" = lib; then + searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" + else + searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" + fi + for searchdir in $searchdirs; do + for search_ext in .la $std_shrext .so .a; do + # Search the libtool library + lib="$searchdir/lib${name}${search_ext}" + if test -f "$lib"; then + if test "$search_ext" = ".la"; then + found=yes + else + found=no + fi + break 2 + fi + done + done + if test "$found" != yes; then + # deplib doesn't seem to be a libtool library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + else # deplib is a libtool library + # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, + # We need to do some special things here, and not later. + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $deplib "*) + if func_lalib_p "$lib"; then + library_names= + old_library= + func_source "$lib" + for l in $old_library $library_names; do + ll="$l" + done + if test "X$ll" = "X$old_library" ; then # only static version available + found=no + func_dirname "$lib" "" "." + ladir="$func_dirname_result" + lib=$ladir/$old_library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + fi + fi + ;; + *) ;; + esac + fi + fi + ;; # -l + *.ltframework) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + if test "$linkmode" = lib ; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) func_append new_inherited_linker_flags " $deplib" ;; + esac + fi + fi + continue + ;; + -L*) + case $linkmode in + lib) + deplibs="$deplib $deplibs" + test "$pass" = conv && continue + newdependency_libs="$deplib $newdependency_libs" + func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + func_append newlib_search_path " $func_resolve_sysroot_result" + ;; + prog) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + if test "$pass" = scan; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + func_append newlib_search_path " $func_resolve_sysroot_result" + ;; + *) + func_warning "\`-L' is ignored for archives/objects" + ;; + esac # linkmode + continue + ;; # -L + -R*) + if test "$pass" = link; then + func_stripname '-R' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + dir=$func_resolve_sysroot_result + # Make sure the xrpath contains only unique directories. + case "$xrpath " in + *" $dir "*) ;; + *) func_append xrpath " $dir" ;; + esac + fi + deplibs="$deplib $deplibs" + continue + ;; + *.la) + func_resolve_sysroot "$deplib" + lib=$func_resolve_sysroot_result + ;; + *.$libext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + case $linkmode in + lib) + # Linking convenience modules into shared libraries is allowed, + # but linking other static libraries is non-portable. + case " $dlpreconveniencelibs " in + *" $deplib "*) ;; + *) + valid_a_lib=no + case $deplibs_check_method in + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ + | $EGREP "$match_pattern_regex" > /dev/null; then + valid_a_lib=yes + fi + ;; + pass_all) + valid_a_lib=yes + ;; + esac + if test "$valid_a_lib" != yes; then + echo + $ECHO "*** Warning: Trying to link with static lib archive $deplib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have" + echo "*** because the file extensions .$libext of this argument makes me believe" + echo "*** that it is just a static archive that I should not use here." + else + echo + $ECHO "*** Warning: Linking the shared library $output against the" + $ECHO "*** static library $deplib is not portable!" + deplibs="$deplib $deplibs" + fi + ;; + esac + continue + ;; + prog) + if test "$pass" != link; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + continue + ;; + esac # linkmode + ;; # *.$libext + *.lo | *.$objext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + elif test "$linkmode" = prog; then + if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then + # If there is no dlopen support or we're linking statically, + # we need to preload. + func_append newdlprefiles " $deplib" + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + func_append newdlfiles " $deplib" + fi + fi + continue + ;; + %DEPLIBS%) + alldeplibs=yes + continue + ;; + esac # case $deplib + + if test "$found" = yes || test -f "$lib"; then : + else + func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" + fi + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$lib" \ + || func_fatal_error "\`$lib' is not a valid libtool archive" + + func_dirname "$lib" "" "." + ladir="$func_dirname_result" + + dlname= + dlopen= + dlpreopen= + libdir= + library_names= + old_library= + inherited_linker_flags= + # If the library was installed with an old release of libtool, + # it will not redefine variables installed, or shouldnotlink + installed=yes + shouldnotlink=no + avoidtemprpath= + + + # Read the .la file + func_source "$lib" + + # Convert "-framework foo" to "foo.ltframework" + if test -n "$inherited_linker_flags"; then + tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` + for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do + case " $new_inherited_linker_flags " in + *" $tmp_inherited_linker_flag "*) ;; + *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; + esac + done + fi + dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan" || + { test "$linkmode" != prog && test "$linkmode" != lib; }; then + test -n "$dlopen" && func_append dlfiles " $dlopen" + test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" + fi + + if test "$pass" = conv; then + # Only check for convenience libraries + deplibs="$lib $deplibs" + if test -z "$libdir"; then + if test -z "$old_library"; then + func_fatal_error "cannot find name of link library for \`$lib'" + fi + # It is a libtool convenience library, so add in its objects. + func_append convenience " $ladir/$objdir/$old_library" + func_append old_convenience " $ladir/$objdir/$old_library" + elif test "$linkmode" != prog && test "$linkmode" != lib; then + func_fatal_error "\`$lib' is not a convenience library" + fi + tmp_libs= + for deplib in $dependency_libs; do + deplibs="$deplib $deplibs" + if $opt_preserve_dup_deps ; then + case "$tmp_libs " in + *" $deplib "*) func_append specialdeplibs " $deplib" ;; + esac + fi + func_append tmp_libs " $deplib" + done + continue + fi # $pass = conv + + + # Get the name of the library we link against. + linklib= + if test -n "$old_library" && + { test "$prefer_static_libs" = yes || + test "$prefer_static_libs,$installed" = "built,no"; }; then + linklib=$old_library + else + for l in $old_library $library_names; do + linklib="$l" + done + fi + if test -z "$linklib"; then + func_fatal_error "cannot find name of link library for \`$lib'" + fi + + # This library was specified with -dlopen. + if test "$pass" = dlopen; then + if test -z "$libdir"; then + func_fatal_error "cannot -dlopen a convenience library: \`$lib'" + fi + if test -z "$dlname" || + test "$dlopen_support" != yes || + test "$build_libtool_libs" = no; then + # If there is no dlname, no dlopen support or we're linking + # statically, we need to preload. We also need to preload any + # dependent libraries so libltdl's deplib preloader doesn't + # bomb out in the load deplibs phase. + func_append dlprefiles " $lib $dependency_libs" + else + func_append newdlfiles " $lib" + fi + continue + fi # $pass = dlopen + + # We need an absolute path. + case $ladir in + [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; + *) + abs_ladir=`cd "$ladir" && pwd` + if test -z "$abs_ladir"; then + func_warning "cannot determine absolute directory name of \`$ladir'" + func_warning "passing it literally to the linker, although it might fail" + abs_ladir="$ladir" + fi + ;; + esac + func_basename "$lib" + laname="$func_basename_result" + + # Find the relevant object directory and library name. + if test "X$installed" = Xyes; then + if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then + #func_warning "library \`$lib' was moved." + dir="$ladir" + absdir="$abs_ladir" + libdir="$abs_ladir" + else + dir="$lt_sysroot$libdir" + absdir="$lt_sysroot$libdir" + fi + test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes + else + if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then + dir="$ladir" + absdir="$abs_ladir" + # Remove this search path later + func_append notinst_path " $abs_ladir" + else + dir="$ladir/$objdir" + absdir="$abs_ladir/$objdir" + # Remove this search path later + func_append notinst_path " $abs_ladir" + fi + fi # $installed = yes + func_stripname 'lib' '.la' "$laname" + name=$func_stripname_result + + # This library was specified with -dlpreopen. + if test "$pass" = dlpreopen; then + if test -z "$libdir" && test "$linkmode" = prog; then + func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" + fi + case "$host" in + # special handling for platforms with PE-DLLs. + *cygwin* | *mingw* | *cegcc* ) + # Linker will automatically link against shared library if both + # static and shared are present. Therefore, ensure we extract + # symbols from the import library if a shared library is present + # (otherwise, the dlopen module name will be incorrect). We do + # this by putting the import library name into $newdlprefiles. + # We recover the dlopen module name by 'saving' the la file + # name in a special purpose variable, and (later) extracting the + # dlname from the la file. + if test -n "$dlname"; then + func_tr_sh "$dir/$linklib" + eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" + func_append newdlprefiles " $dir/$linklib" + else + func_append newdlprefiles " $dir/$old_library" + # Keep a list of preopened convenience libraries to check + # that they are being used correctly in the link pass. + test -z "$libdir" && \ + func_append dlpreconveniencelibs " $dir/$old_library" + fi + ;; + * ) + # Prefer using a static library (so that no silly _DYNAMIC symbols + # are required to link). + if test -n "$old_library"; then + func_append newdlprefiles " $dir/$old_library" + # Keep a list of preopened convenience libraries to check + # that they are being used correctly in the link pass. + test -z "$libdir" && \ + func_append dlpreconveniencelibs " $dir/$old_library" + # Otherwise, use the dlname, so that lt_dlopen finds it. + elif test -n "$dlname"; then + func_append newdlprefiles " $dir/$dlname" + else + func_append newdlprefiles " $dir/$linklib" + fi + ;; + esac + fi # $pass = dlpreopen + + if test -z "$libdir"; then + # Link the convenience library + if test "$linkmode" = lib; then + deplibs="$dir/$old_library $deplibs" + elif test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$dir/$old_library $compile_deplibs" + finalize_deplibs="$dir/$old_library $finalize_deplibs" + else + deplibs="$lib $deplibs" # used for prog,scan pass + fi + continue + fi + + + if test "$linkmode" = prog && test "$pass" != link; then + func_append newlib_search_path " $ladir" + deplibs="$lib $deplibs" + + linkalldeplibs=no + if test "$link_all_deplibs" != no || test -z "$library_names" || + test "$build_libtool_libs" = no; then + linkalldeplibs=yes + fi + + tmp_libs= + for deplib in $dependency_libs; do + case $deplib in + -L*) func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + func_append newlib_search_path " $func_resolve_sysroot_result" + ;; + esac + # Need to link against all dependency_libs? + if test "$linkalldeplibs" = yes; then + deplibs="$deplib $deplibs" + else + # Need to hardcode shared library paths + # or/and link against static libraries + newdependency_libs="$deplib $newdependency_libs" + fi + if $opt_preserve_dup_deps ; then + case "$tmp_libs " in + *" $deplib "*) func_append specialdeplibs " $deplib" ;; + esac + fi + func_append tmp_libs " $deplib" + done # for deplib + continue + fi # $linkmode = prog... + + if test "$linkmode,$pass" = "prog,link"; then + if test -n "$library_names" && + { { test "$prefer_static_libs" = no || + test "$prefer_static_libs,$installed" = "built,yes"; } || + test -z "$old_library"; }; then + # We need to hardcode the library path + if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then + # Make sure the rpath contains only unique directories. + case "$temp_rpath:" in + *"$absdir:"*) ;; + *) func_append temp_rpath "$absdir:" ;; + esac + fi + + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) func_append compile_rpath " $absdir" ;; + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + ;; + esac + fi # $linkmode,$pass = prog,link... + + if test "$alldeplibs" = yes && + { test "$deplibs_check_method" = pass_all || + { test "$build_libtool_libs" = yes && + test -n "$library_names"; }; }; then + # We only need to search for static libraries + continue + fi + fi + + link_static=no # Whether the deplib will be linked statically + use_static_libs=$prefer_static_libs + if test "$use_static_libs" = built && test "$installed" = yes; then + use_static_libs=no + fi + if test -n "$library_names" && + { test "$use_static_libs" = no || test -z "$old_library"; }; then + case $host in + *cygwin* | *mingw* | *cegcc*) + # No point in relinking DLLs because paths are not encoded + func_append notinst_deplibs " $lib" + need_relink=no + ;; + *) + if test "$installed" = no; then + func_append notinst_deplibs " $lib" + need_relink=yes + fi + ;; + esac + # This is a shared library + + # Warn about portability, can't link against -module's on some + # systems (darwin). Don't bleat about dlopened modules though! + dlopenmodule="" + for dlpremoduletest in $dlprefiles; do + if test "X$dlpremoduletest" = "X$lib"; then + dlopenmodule="$dlpremoduletest" + break + fi + done + if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then + echo + if test "$linkmode" = prog; then + $ECHO "*** Warning: Linking the executable $output against the loadable module" + else + $ECHO "*** Warning: Linking the shared library $output against the loadable module" + fi + $ECHO "*** $linklib is not portable!" + fi + if test "$linkmode" = lib && + test "$hardcode_into_libs" = yes; then + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) func_append compile_rpath " $absdir" ;; + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + ;; + esac + fi + + if test -n "$old_archive_from_expsyms_cmds"; then + # figure out the soname + set dummy $library_names + shift + realname="$1" + shift + libname=`eval "\\$ECHO \"$libname_spec\""` + # use dlname if we got it. it's perfectly good, no? + if test -n "$dlname"; then + soname="$dlname" + elif test -n "$soname_spec"; then + # bleh windows + case $host in + *cygwin* | mingw* | *cegcc*) + func_arith $current - $age + major=$func_arith_result + versuffix="-$major" + ;; + esac + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + + # Make a new name for the extract_expsyms_cmds to use + soroot="$soname" + func_basename "$soroot" + soname="$func_basename_result" + func_stripname 'lib' '.dll' "$soname" + newlib=libimp-$func_stripname_result.a + + # If the library has no export list, then create one now + if test -f "$output_objdir/$soname-def"; then : + else + func_verbose "extracting exported symbol list from \`$soname'" + func_execute_cmds "$extract_expsyms_cmds" 'exit $?' + fi + + # Create $newlib + if test -f "$output_objdir/$newlib"; then :; else + func_verbose "generating import library for \`$soname'" + func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' + fi + # make sure the library variables are pointing to the new library + dir=$output_objdir + linklib=$newlib + fi # test -n "$old_archive_from_expsyms_cmds" + + if test "$linkmode" = prog || test "$opt_mode" != relink; then + add_shlibpath= + add_dir= + add= + lib_linked=yes + case $hardcode_action in + immediate | unsupported) + if test "$hardcode_direct" = no; then + add="$dir/$linklib" + case $host in + *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; + *-*-sysv4*uw2*) add_dir="-L$dir" ;; + *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ + *-*-unixware7*) add_dir="-L$dir" ;; + *-*-darwin* ) + # if the lib is a (non-dlopened) module then we can not + # link against it, someone is ignoring the earlier warnings + if /usr/bin/file -L $add 2> /dev/null | + $GREP ": [^:]* bundle" >/dev/null ; then + if test "X$dlopenmodule" != "X$lib"; then + $ECHO "*** Warning: lib $linklib is a module, not a shared library" + if test -z "$old_library" ; then + echo + echo "*** And there doesn't seem to be a static archive available" + echo "*** The link will probably fail, sorry" + else + add="$dir/$old_library" + fi + elif test -n "$old_library"; then + add="$dir/$old_library" + fi + fi + esac + elif test "$hardcode_minus_L" = no; then + case $host in + *-*-sunos*) add_shlibpath="$dir" ;; + esac + add_dir="-L$dir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = no; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + relink) + if test "$hardcode_direct" = yes && + test "$hardcode_direct_absolute" = no; then + add="$dir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$absdir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + func_append add_dir " -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + *) lib_linked=no ;; + esac + + if test "$lib_linked" != yes; then + func_fatal_configuration "unsupported hardcode properties" + fi + + if test -n "$add_shlibpath"; then + case :$compile_shlibpath: in + *":$add_shlibpath:"*) ;; + *) func_append compile_shlibpath "$add_shlibpath:" ;; + esac + fi + if test "$linkmode" = prog; then + test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" + test -n "$add" && compile_deplibs="$add $compile_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + if test "$hardcode_direct" != yes && + test "$hardcode_minus_L" != yes && + test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) func_append finalize_shlibpath "$libdir:" ;; + esac + fi + fi + fi + + if test "$linkmode" = prog || test "$opt_mode" = relink; then + add_shlibpath= + add_dir= + add= + # Finalize command for both is simple: just hardcode it. + if test "$hardcode_direct" = yes && + test "$hardcode_direct_absolute" = no; then + add="$libdir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$libdir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) func_append finalize_shlibpath "$libdir:" ;; + esac + add="-l$name" + elif test "$hardcode_automatic" = yes; then + if test -n "$inst_prefix_dir" && + test -f "$inst_prefix_dir$libdir/$linklib" ; then + add="$inst_prefix_dir$libdir/$linklib" + else + add="$libdir/$linklib" + fi + else + # We cannot seem to hardcode it, guess we'll fake it. + add_dir="-L$libdir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + func_append add_dir " -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + fi + + if test "$linkmode" = prog; then + test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" + test -n "$add" && finalize_deplibs="$add $finalize_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + fi + fi + elif test "$linkmode" = prog; then + # Here we assume that one of hardcode_direct or hardcode_minus_L + # is not unsupported. This is valid on all known static and + # shared platforms. + if test "$hardcode_direct" != unsupported; then + test -n "$old_library" && linklib="$old_library" + compile_deplibs="$dir/$linklib $compile_deplibs" + finalize_deplibs="$dir/$linklib $finalize_deplibs" + else + compile_deplibs="-l$name -L$dir $compile_deplibs" + finalize_deplibs="-l$name -L$dir $finalize_deplibs" + fi + elif test "$build_libtool_libs" = yes; then + # Not a shared library + if test "$deplibs_check_method" != pass_all; then + # We're trying link a shared library against a static one + # but the system doesn't support it. + + # Just print a warning and add the library to dependency_libs so + # that the program can be linked against the static library. + echo + $ECHO "*** Warning: This system can not link to static lib archive $lib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have." + if test "$module" = yes; then + echo "*** But as you try to build a module library, libtool will still create " + echo "*** a static module, that should work as long as the dlopening application" + echo "*** is linked with the -dlopen flag to resolve symbols at runtime." + if test -z "$global_symbol_pipe"; then + echo + echo "*** However, this would only work if libtool was able to extract symbol" + echo "*** lists from a program, using \`nm' or equivalent, but libtool could" + echo "*** not find such a program. So, this module is probably useless." + echo "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + else + deplibs="$dir/$old_library $deplibs" + link_static=yes + fi + fi # link shared/static library? + + if test "$linkmode" = lib; then + if test -n "$dependency_libs" && + { test "$hardcode_into_libs" != yes || + test "$build_old_libs" = yes || + test "$link_static" = yes; }; then + # Extract -R from dependency_libs + temp_deplibs= + for libdir in $dependency_libs; do + case $libdir in + -R*) func_stripname '-R' '' "$libdir" + temp_xrpath=$func_stripname_result + case " $xrpath " in + *" $temp_xrpath "*) ;; + *) func_append xrpath " $temp_xrpath";; + esac;; + *) func_append temp_deplibs " $libdir";; + esac + done + dependency_libs="$temp_deplibs" + fi + + func_append newlib_search_path " $absdir" + # Link against this library + test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" + # ... and its dependency_libs + tmp_libs= + for deplib in $dependency_libs; do + newdependency_libs="$deplib $newdependency_libs" + case $deplib in + -L*) func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result";; + *) func_resolve_sysroot "$deplib" ;; + esac + if $opt_preserve_dup_deps ; then + case "$tmp_libs " in + *" $func_resolve_sysroot_result "*) + func_append specialdeplibs " $func_resolve_sysroot_result" ;; + esac + fi + func_append tmp_libs " $func_resolve_sysroot_result" + done + + if test "$link_all_deplibs" != no; then + # Add the search paths of all dependency libraries + for deplib in $dependency_libs; do + path= + case $deplib in + -L*) path="$deplib" ;; + *.la) + func_resolve_sysroot "$deplib" + deplib=$func_resolve_sysroot_result + func_dirname "$deplib" "" "." + dir=$func_dirname_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; + *) + absdir=`cd "$dir" && pwd` + if test -z "$absdir"; then + func_warning "cannot determine absolute directory name of \`$dir'" + absdir="$dir" + fi + ;; + esac + if $GREP "^installed=no" $deplib > /dev/null; then + case $host in + *-*-darwin*) + depdepl= + eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` + if test -n "$deplibrary_names" ; then + for tmp in $deplibrary_names ; do + depdepl=$tmp + done + if test -f "$absdir/$objdir/$depdepl" ; then + depdepl="$absdir/$objdir/$depdepl" + darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + if test -z "$darwin_install_name"; then + darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + fi + func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" + func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}" + path= + fi + fi + ;; + *) + path="-L$absdir/$objdir" + ;; + esac + else + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + test -z "$libdir" && \ + func_fatal_error "\`$deplib' is not a valid libtool archive" + #test "$absdir" != "$libdir" && \ + # func_warning "\`$deplib' seems to be moved" + + path="-L$absdir" + fi + ;; + esac + case " $deplibs " in + *" $path "*) ;; + *) deplibs="$path $deplibs" ;; + esac + done + fi # link_all_deplibs != no + fi # linkmode = lib + done # for deplib in $libs + if test "$pass" = link; then + if test "$linkmode" = "prog"; then + compile_deplibs="$new_inherited_linker_flags $compile_deplibs" + finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" + else + compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + fi + fi + dependency_libs="$newdependency_libs" + if test "$pass" = dlpreopen; then + # Link the dlpreopened libraries before other libraries + for deplib in $save_deplibs; do + deplibs="$deplib $deplibs" + done + fi + if test "$pass" != dlopen; then + if test "$pass" != conv; then + # Make sure lib_search_path contains only unique directories. + lib_search_path= + for dir in $newlib_search_path; do + case "$lib_search_path " in + *" $dir "*) ;; + *) func_append lib_search_path " $dir" ;; + esac + done + newlib_search_path= + fi + + if test "$linkmode,$pass" != "prog,link"; then + vars="deplibs" + else + vars="compile_deplibs finalize_deplibs" + fi + for var in $vars dependency_libs; do + # Add libraries to $var in reverse order + eval tmp_libs=\"\$$var\" + new_libs= + for deplib in $tmp_libs; do + # FIXME: Pedantically, this is the right thing to do, so + # that some nasty dependency loop isn't accidentally + # broken: + #new_libs="$deplib $new_libs" + # Pragmatically, this seems to cause very few problems in + # practice: + case $deplib in + -L*) new_libs="$deplib $new_libs" ;; + -R*) ;; + *) + # And here is the reason: when a library appears more + # than once as an explicit dependence of a library, or + # is implicitly linked in more than once by the + # compiler, it is considered special, and multiple + # occurrences thereof are not removed. Compare this + # with having the same library being listed as a + # dependency of multiple other libraries: in this case, + # we know (pedantically, we assume) the library does not + # need to be listed more than once, so we keep only the + # last copy. This is not always right, but it is rare + # enough that we require users that really mean to play + # such unportable linking tricks to link the library + # using -Wl,-lname, so that libtool does not consider it + # for duplicate removal. + case " $specialdeplibs " in + *" $deplib "*) new_libs="$deplib $new_libs" ;; + *) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$deplib $new_libs" ;; + esac + ;; + esac + ;; + esac + done + tmp_libs= + for deplib in $new_libs; do + case $deplib in + -L*) + case " $tmp_libs " in + *" $deplib "*) ;; + *) func_append tmp_libs " $deplib" ;; + esac + ;; + *) func_append tmp_libs " $deplib" ;; + esac + done + eval $var=\"$tmp_libs\" + done # for var + fi + # Last step: remove runtime libs from dependency_libs + # (they stay in deplibs) + tmp_libs= + for i in $dependency_libs ; do + case " $predeps $postdeps $compiler_lib_search_path " in + *" $i "*) + i="" + ;; + esac + if test -n "$i" ; then + func_append tmp_libs " $i" + fi + done + dependency_libs=$tmp_libs + done # for pass + if test "$linkmode" = prog; then + dlfiles="$newdlfiles" + fi + if test "$linkmode" = prog || test "$linkmode" = lib; then + dlprefiles="$newdlprefiles" + fi + + case $linkmode in + oldlib) + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + func_warning "\`-dlopen' is ignored for archives" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "\`-l' and \`-L' are ignored for archives" ;; + esac + + test -n "$rpath" && \ + func_warning "\`-rpath' is ignored for archives" + + test -n "$xrpath" && \ + func_warning "\`-R' is ignored for archives" + + test -n "$vinfo" && \ + func_warning "\`-version-info/-version-number' is ignored for archives" + + test -n "$release" && \ + func_warning "\`-release' is ignored for archives" + + test -n "$export_symbols$export_symbols_regex" && \ + func_warning "\`-export-symbols' is ignored for archives" + + # Now set the variables for building old libraries. + build_libtool_libs=no + oldlibs="$output" + func_append objs "$old_deplibs" + ;; + + lib) + # Make sure we only generate libraries of the form `libNAME.la'. + case $outputname in + lib*) + func_stripname 'lib' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + ;; + *) + test "$module" = no && \ + func_fatal_help "libtool library \`$output' must begin with \`lib'" + + if test "$need_lib_prefix" != no; then + # Add the "lib" prefix for modules if required + func_stripname '' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + else + func_stripname '' '.la' "$outputname" + libname=$func_stripname_result + fi + ;; + esac + + if test -n "$objs"; then + if test "$deplibs_check_method" != pass_all; then + func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" + else + echo + $ECHO "*** Warning: Linking the shared library $output against the non-libtool" + $ECHO "*** objects $objs is not portable!" + func_append libobjs " $objs" + fi + fi + + test "$dlself" != no && \ + func_warning "\`-dlopen self' is ignored for libtool libraries" + + set dummy $rpath + shift + test "$#" -gt 1 && \ + func_warning "ignoring multiple \`-rpath's for a libtool library" + + install_libdir="$1" + + oldlibs= + if test -z "$rpath"; then + if test "$build_libtool_libs" = yes; then + # Building a libtool convenience library. + # Some compilers have problems with a `.al' extension so + # convenience libraries should have the same extension an + # archive normally would. + oldlibs="$output_objdir/$libname.$libext $oldlibs" + build_libtool_libs=convenience + build_old_libs=yes + fi + + test -n "$vinfo" && \ + func_warning "\`-version-info/-version-number' is ignored for convenience libraries" + + test -n "$release" && \ + func_warning "\`-release' is ignored for convenience libraries" + else + + # Parse the version information argument. + save_ifs="$IFS"; IFS=':' + set dummy $vinfo 0 0 0 + shift + IFS="$save_ifs" + + test -n "$7" && \ + func_fatal_help "too many parameters to \`-version-info'" + + # convert absolute version numbers to libtool ages + # this retains compatibility with .la files and attempts + # to make the code below a bit more comprehensible + + case $vinfo_number in + yes) + number_major="$1" + number_minor="$2" + number_revision="$3" + # + # There are really only two kinds -- those that + # use the current revision as the major version + # and those that subtract age and use age as + # a minor version. But, then there is irix + # which has an extra 1 added just for fun + # + case $version_type in + # correct linux to gnu/linux during the next big refactor + darwin|linux|osf|windows|none) + func_arith $number_major + $number_minor + current=$func_arith_result + age="$number_minor" + revision="$number_revision" + ;; + freebsd-aout|freebsd-elf|qnx|sunos) + current="$number_major" + revision="$number_minor" + age="0" + ;; + irix|nonstopux) + func_arith $number_major + $number_minor + current=$func_arith_result + age="$number_minor" + revision="$number_minor" + lt_irix_increment=no + ;; + esac + ;; + no) + current="$1" + revision="$2" + age="$3" + ;; + esac + + # Check that each of the things are valid numbers. + case $current in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "CURRENT \`$current' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + case $revision in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "REVISION \`$revision' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + case $age in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "AGE \`$age' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + if test "$age" -gt "$current"; then + func_error "AGE \`$age' is greater than the current interface number \`$current'" + func_fatal_error "\`$vinfo' is not valid version information" + fi + + # Calculate the version variables. + major= + versuffix= + verstring= + case $version_type in + none) ;; + + darwin) + # Like Linux, but with the current version available in + # verstring for coding it into the library header + func_arith $current - $age + major=.$func_arith_result + versuffix="$major.$age.$revision" + # Darwin ld doesn't like 0 for these options... + func_arith $current + 1 + minor_current=$func_arith_result + xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" + verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" + ;; + + freebsd-aout) + major=".$current" + versuffix=".$current.$revision"; + ;; + + freebsd-elf) + major=".$current" + versuffix=".$current" + ;; + + irix | nonstopux) + if test "X$lt_irix_increment" = "Xno"; then + func_arith $current - $age + else + func_arith $current - $age + 1 + fi + major=$func_arith_result + + case $version_type in + nonstopux) verstring_prefix=nonstopux ;; + *) verstring_prefix=sgi ;; + esac + verstring="$verstring_prefix$major.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$revision + while test "$loop" -ne 0; do + func_arith $revision - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring="$verstring_prefix$major.$iface:$verstring" + done + + # Before this point, $major must not contain `.'. + major=.$major + versuffix="$major.$revision" + ;; + + linux) # correct to gnu/linux during the next big refactor + func_arith $current - $age + major=.$func_arith_result + versuffix="$major.$age.$revision" + ;; + + osf) + func_arith $current - $age + major=.$func_arith_result + versuffix=".$current.$age.$revision" + verstring="$current.$age.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$age + while test "$loop" -ne 0; do + func_arith $current - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring="$verstring:${iface}.0" + done + + # Make executables depend on our current version. + func_append verstring ":${current}.0" + ;; + + qnx) + major=".$current" + versuffix=".$current" + ;; + + sunos) + major=".$current" + versuffix=".$current.$revision" + ;; + + windows) + # Use '-' rather than '.', since we only want one + # extension on DOS 8.3 filesystems. + func_arith $current - $age + major=$func_arith_result + versuffix="-$major" + ;; + + *) + func_fatal_configuration "unknown library version type \`$version_type'" + ;; + esac + + # Clear the version info if we defaulted, and they specified a release. + if test -z "$vinfo" && test -n "$release"; then + major= + case $version_type in + darwin) + # we can't check for "0.0" in archive_cmds due to quoting + # problems, so we reset it completely + verstring= + ;; + *) + verstring="0.0" + ;; + esac + if test "$need_version" = no; then + versuffix= + else + versuffix=".0.0" + fi + fi + + # Remove version info from name if versioning should be avoided + if test "$avoid_version" = yes && test "$need_version" = no; then + major= + versuffix= + verstring="" + fi + + # Check to see if the archive will have undefined symbols. + if test "$allow_undefined" = yes; then + if test "$allow_undefined_flag" = unsupported; then + func_warning "undefined symbols not allowed in $host shared libraries" + build_libtool_libs=no + build_old_libs=yes + fi + else + # Don't allow undefined symbols. + allow_undefined_flag="$no_undefined_flag" + fi + + fi + + func_generate_dlsyms "$libname" "$libname" "yes" + func_append libobjs " $symfileobj" + test "X$libobjs" = "X " && libobjs= + + if test "$opt_mode" != relink; then + # Remove our outputs, but don't remove object files since they + # may have been created when compiling PIC objects. + removelist= + tempremovelist=`$ECHO "$output_objdir/*"` + for p in $tempremovelist; do + case $p in + *.$objext | *.gcno) + ;; + $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) + if test "X$precious_files_regex" != "X"; then + if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 + then + continue + fi + fi + func_append removelist " $p" + ;; + *) ;; + esac + done + test -n "$removelist" && \ + func_show_eval "${RM}r \$removelist" + fi + + # Now set the variables for building old libraries. + if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then + func_append oldlibs " $output_objdir/$libname.$libext" + + # Transform .lo files to .o files. + oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP` + fi + + # Eliminate all temporary directories. + #for path in $notinst_path; do + # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` + # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` + # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` + #done + + if test -n "$xrpath"; then + # If the user specified any rpath flags, then add them. + temp_xrpath= + for libdir in $xrpath; do + func_replace_sysroot "$libdir" + func_append temp_xrpath " -R$func_replace_sysroot_result" + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + done + if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then + dependency_libs="$temp_xrpath $dependency_libs" + fi + fi + + # Make sure dlfiles contains only unique files that won't be dlpreopened + old_dlfiles="$dlfiles" + dlfiles= + for lib in $old_dlfiles; do + case " $dlprefiles $dlfiles " in + *" $lib "*) ;; + *) func_append dlfiles " $lib" ;; + esac + done + + # Make sure dlprefiles contains only unique files + old_dlprefiles="$dlprefiles" + dlprefiles= + for lib in $old_dlprefiles; do + case "$dlprefiles " in + *" $lib "*) ;; + *) func_append dlprefiles " $lib" ;; + esac + done + + if test "$build_libtool_libs" = yes; then + if test -n "$rpath"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) + # these systems don't actually have a c library (as such)! + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C library is in the System framework + func_append deplibs " System.ltframework" + ;; + *-*-netbsd*) + # Don't link with libc until the a.out ld.so is fixed. + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc due to us having libc/libc_r. + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + ;; + *) + # Add libc to deplibs on all other systems if necessary. + if test "$build_libtool_need_lc" = "yes"; then + func_append deplibs " -lc" + fi + ;; + esac + fi + + # Transform deplibs into only deplibs that can be linked in shared. + name_save=$name + libname_save=$libname + release_save=$release + versuffix_save=$versuffix + major_save=$major + # I'm not sure if I'm treating the release correctly. I think + # release should show up in the -l (ie -lgmp5) so we don't want to + # add it in twice. Is that correct? + release="" + versuffix="" + major="" + newdeplibs= + droppeddeps=no + case $deplibs_check_method in + pass_all) + # Don't check for shared/static. Everything works. + # This might be a little naive. We might want to check + # whether the library exists or not. But this is on + # osf3 & osf4 and I'm not really sure... Just + # implementing what was already the behavior. + newdeplibs=$deplibs + ;; + test_compile) + # This code stresses the "libraries are programs" paradigm to its + # limits. Maybe even breaks it. We compile a program, linking it + # against the deplibs as a proxy for the library. Then we can check + # whether they linked in statically or dynamically with ldd. + $opt_dry_run || $RM conftest.c + cat > conftest.c </dev/null` + $nocaseglob + else + potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` + fi + for potent_lib in $potential_libs; do + # Follow soft links. + if ls -lLd "$potent_lib" 2>/dev/null | + $GREP " -> " >/dev/null; then + continue + fi + # The statement above tries to avoid entering an + # endless loop below, in case of cyclic links. + # We might still enter an endless loop, since a link + # loop can be closed while we follow links, + # but so what? + potlib="$potent_lib" + while test -h "$potlib" 2>/dev/null; do + potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` + case $potliblink in + [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; + *) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";; + esac + done + if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | + $SED -e 10q | + $EGREP "$file_magic_regex" > /dev/null; then + func_append newdeplibs " $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + echo + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have" + echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $ECHO "*** with $libname but no candidates were found. (...for file magic test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a file magic. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + func_append newdeplibs " $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + for a_deplib in $deplibs; do + case $a_deplib in + -l*) + func_stripname -l '' "$a_deplib" + name=$func_stripname_result + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $a_deplib "*) + func_append newdeplibs " $a_deplib" + a_deplib="" + ;; + esac + fi + if test -n "$a_deplib" ; then + libname=`eval "\\$ECHO \"$libname_spec\""` + for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do + potential_libs=`ls $i/$libname[.-]* 2>/dev/null` + for potent_lib in $potential_libs; do + potlib="$potent_lib" # see symlink-check above in file_magic test + if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ + $EGREP "$match_pattern_regex" > /dev/null; then + func_append newdeplibs " $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + echo + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have" + echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a regex pattern. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + func_append newdeplibs " $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + none | unknown | *) + newdeplibs="" + tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + for i in $predeps $postdeps ; do + # can't use Xsed below, because $i might contain '/' + tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"` + done + fi + case $tmp_deplibs in + *[!\ \ ]*) + echo + if test "X$deplibs_check_method" = "Xnone"; then + echo "*** Warning: inter-library dependencies are not supported in this platform." + else + echo "*** Warning: inter-library dependencies are not known to be supported." + fi + echo "*** All declared inter-library dependencies are being dropped." + droppeddeps=yes + ;; + esac + ;; + esac + versuffix=$versuffix_save + major=$major_save + release=$release_save + libname=$libname_save + name=$name_save + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library with the System framework + newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` + ;; + esac + + if test "$droppeddeps" = yes; then + if test "$module" = yes; then + echo + echo "*** Warning: libtool could not satisfy all declared inter-library" + $ECHO "*** dependencies of module $libname. Therefore, libtool will create" + echo "*** a static module, that should work as long as the dlopening" + echo "*** application is linked with the -dlopen flag." + if test -z "$global_symbol_pipe"; then + echo + echo "*** However, this would only work if libtool was able to extract symbol" + echo "*** lists from a program, using \`nm' or equivalent, but libtool could" + echo "*** not find such a program. So, this module is probably useless." + echo "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + else + echo "*** The inter-library dependencies that have been dropped here will be" + echo "*** automatically added whenever a program is linked with this library" + echo "*** or is declared to -dlopen it." + + if test "$allow_undefined" = no; then + echo + echo "*** Since this library must not contain undefined symbols," + echo "*** because either the platform does not support them or" + echo "*** it was explicitly requested with -no-undefined," + echo "*** libtool will only create a static version of it." + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + fi + fi + # Done checking deplibs! + deplibs=$newdeplibs + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + case $host in + *-*-darwin*) + newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $deplibs " in + *" -L$path/$objdir "*) + func_append new_libs " -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) func_append new_libs " $deplib" ;; + esac + ;; + *) func_append new_libs " $deplib" ;; + esac + done + deplibs="$new_libs" + + # All the library-specific variables (install_libdir is set above). + library_names= + old_library= + dlname= + + # Test again, we may have decided not to build it any more + if test "$build_libtool_libs" = yes; then + # Remove ${wl} instances when linking with ld. + # FIXME: should test the right _cmds variable. + case $archive_cmds in + *\$LD\ *) wl= ;; + esac + if test "$hardcode_into_libs" = yes; then + # Hardcode the library paths + hardcode_libdirs= + dep_rpath= + rpath="$finalize_rpath" + test "$opt_mode" != relink && rpath="$compile_rpath$rpath" + for libdir in $rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + func_replace_sysroot "$libdir" + libdir=$func_replace_sysroot_result + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + func_append dep_rpath " $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) func_append perm_rpath " $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" + fi + if test -n "$runpath_var" && test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + func_append rpath "$dir:" + done + eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" + fi + test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" + fi + + shlibpath="$finalize_shlibpath" + test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath" + if test -n "$shlibpath"; then + eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" + fi + + # Get the real and link names of the library. + eval shared_ext=\"$shrext_cmds\" + eval library_names=\"$library_names_spec\" + set dummy $library_names + shift + realname="$1" + shift + + if test -n "$soname_spec"; then + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + if test -z "$dlname"; then + dlname=$soname + fi + + lib="$output_objdir/$realname" + linknames= + for link + do + func_append linknames " $link" + done + + # Use standard objects if they are pic + test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` + test "X$libobjs" = "X " && libobjs= + + delfiles= + if test -n "$export_symbols" && test -n "$include_expsyms"; then + $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" + export_symbols="$output_objdir/$libname.uexp" + func_append delfiles " $export_symbols" + fi + + orig_export_symbols= + case $host_os in + cygwin* | mingw* | cegcc*) + if test -n "$export_symbols" && test -z "$export_symbols_regex"; then + # exporting using user supplied symfile + if test "x`$SED 1q $export_symbols`" != xEXPORTS; then + # and it's NOT already a .def file. Must figure out + # which of the given symbols are data symbols and tag + # them as such. So, trigger use of export_symbols_cmds. + # export_symbols gets reassigned inside the "prepare + # the list of exported symbols" if statement, so the + # include_expsyms logic still works. + orig_export_symbols="$export_symbols" + export_symbols= + always_export_symbols=yes + fi + fi + ;; + esac + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then + func_verbose "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $opt_dry_run || $RM $export_symbols + cmds=$export_symbols_cmds + save_ifs="$IFS"; IFS='~' + for cmd1 in $cmds; do + IFS="$save_ifs" + # Take the normal branch if the nm_file_list_spec branch + # doesn't work or if tool conversion is not needed. + case $nm_file_list_spec~$to_tool_file_cmd in + *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) + try_normal_branch=yes + eval cmd=\"$cmd1\" + func_len " $cmd" + len=$func_len_result + ;; + *) + try_normal_branch=no + ;; + esac + if test "$try_normal_branch" = yes \ + && { test "$len" -lt "$max_cmd_len" \ + || test "$max_cmd_len" -le -1; } + then + func_show_eval "$cmd" 'exit $?' + skipped_export=false + elif test -n "$nm_file_list_spec"; then + func_basename "$output" + output_la=$func_basename_result + save_libobjs=$libobjs + save_output=$output + output=${output_objdir}/${output_la}.nm + func_to_tool_file "$output" + libobjs=$nm_file_list_spec$func_to_tool_file_result + func_append delfiles " $output" + func_verbose "creating $NM input file list: $output" + for obj in $save_libobjs; do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" + done > "$output" + eval cmd=\"$cmd1\" + func_show_eval "$cmd" 'exit $?' + output=$save_output + libobjs=$save_libobjs + skipped_export=false + else + # The command line is too long to execute in one step. + func_verbose "using reloadable object file for export list..." + skipped_export=: + # Break out early, otherwise skipped_export may be + # set to false by a later but shorter cmd. + break + fi + done + IFS="$save_ifs" + if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + fi + + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols="$export_symbols" + test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" + $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' + fi + + if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + func_append delfiles " $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + + tmp_deplibs= + for test_deplib in $deplibs; do + case " $convenience " in + *" $test_deplib "*) ;; + *) + func_append tmp_deplibs " $test_deplib" + ;; + esac + done + deplibs="$tmp_deplibs" + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec" && + test "$compiler_needs_object" = yes && + test -z "$libobjs"; then + # extract the archives, so we have objects to list. + # TODO: could optimize this to just extract one archive. + whole_archive_flag_spec= + fi + if test -n "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + else + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + + func_extract_archives $gentop $convenience + func_append libobjs " $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + fi + + if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then + eval flag=\"$thread_safe_flag_spec\" + func_append linker_flags " $flag" + fi + + # Make a backup of the uninstalled library when relinking + if test "$opt_mode" = relink; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? + fi + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + eval test_cmds=\"$module_expsym_cmds\" + cmds=$module_expsym_cmds + else + eval test_cmds=\"$module_cmds\" + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + eval test_cmds=\"$archive_expsym_cmds\" + cmds=$archive_expsym_cmds + else + eval test_cmds=\"$archive_cmds\" + cmds=$archive_cmds + fi + fi + + if test "X$skipped_export" != "X:" && + func_len " $test_cmds" && + len=$func_len_result && + test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + : + else + # The command line is too long to link in one step, link piecewise + # or, if using GNU ld and skipped_export is not :, use a linker + # script. + + # Save the value of $output and $libobjs because we want to + # use them later. If we have whole_archive_flag_spec, we + # want to use save_libobjs as it was before + # whole_archive_flag_spec was expanded, because we can't + # assume the linker understands whole_archive_flag_spec. + # This may have to be revisited, in case too many + # convenience libraries get linked in and end up exceeding + # the spec. + if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + fi + save_output=$output + func_basename "$output" + output_la=$func_basename_result + + # Clear the reloadable object creation command queue and + # initialize k to one. + test_cmds= + concat_cmds= + objlist= + last_robj= + k=1 + + if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then + output=${output_objdir}/${output_la}.lnkscript + func_verbose "creating GNU ld script: $output" + echo 'INPUT (' > $output + for obj in $save_libobjs + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" >> $output + done + echo ')' >> $output + func_append delfiles " $output" + func_to_tool_file "$output" + output=$func_to_tool_file_result + elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then + output=${output_objdir}/${output_la}.lnk + func_verbose "creating linker input file list: $output" + : > $output + set x $save_libobjs + shift + firstobj= + if test "$compiler_needs_object" = yes; then + firstobj="$1 " + shift + fi + for obj + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" >> $output + done + func_append delfiles " $output" + func_to_tool_file "$output" + output=$firstobj\"$file_list_spec$func_to_tool_file_result\" + else + if test -n "$save_libobjs"; then + func_verbose "creating reloadable object files..." + output=$output_objdir/$output_la-${k}.$objext + eval test_cmds=\"$reload_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + + # Loop over the list of objects to be linked. + for obj in $save_libobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + if test "X$objlist" = X || + test "$len" -lt "$max_cmd_len"; then + func_append objlist " $obj" + else + # The command $test_cmds is almost too long, add a + # command to the queue. + if test "$k" -eq 1 ; then + # The first file doesn't have a previous command to add. + reload_objs=$objlist + eval concat_cmds=\"$reload_cmds\" + else + # All subsequent reloadable object files will link in + # the last one created. + reload_objs="$objlist $last_robj" + eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" + fi + last_robj=$output_objdir/$output_la-${k}.$objext + func_arith $k + 1 + k=$func_arith_result + output=$output_objdir/$output_la-${k}.$objext + objlist=" $obj" + func_len " $last_robj" + func_arith $len0 + $func_len_result + len=$func_arith_result + fi + done + # Handle the remaining objects by creating one last + # reloadable object file. All subsequent reloadable object + # files will link in the last one created. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + reload_objs="$objlist $last_robj" + eval concat_cmds=\"\${concat_cmds}$reload_cmds\" + if test -n "$last_robj"; then + eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" + fi + func_append delfiles " $output" + + else + output= + fi + + if ${skipped_export-false}; then + func_verbose "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $opt_dry_run || $RM $export_symbols + libobjs=$output + # Append the command to create the export file. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" + if test -n "$last_robj"; then + eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" + fi + fi + + test -n "$save_libobjs" && + func_verbose "creating a temporary reloadable object file: $output" + + # Loop through the commands generated above and execute them. + save_ifs="$IFS"; IFS='~' + for cmd in $concat_cmds; do + IFS="$save_ifs" + $opt_silent || { + func_quote_for_expand "$cmd" + eval "func_echo $func_quote_for_expand_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test "$opt_mode" = relink; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS="$save_ifs" + + if test -n "$export_symbols_regex" && ${skipped_export-false}; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + + if ${skipped_export-false}; then + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols="$export_symbols" + test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" + $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' + fi + + if test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + func_append delfiles " $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + fi + + libobjs=$output + # Restore the value of output. + output=$save_output + + if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + fi + # Expand the library linking commands again to reset the + # value of $libobjs for piecewise linking. + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + cmds=$module_expsym_cmds + else + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + cmds=$archive_expsym_cmds + else + cmds=$archive_cmds + fi + fi + fi + + if test -n "$delfiles"; then + # Append the command to remove temporary files to $cmds. + eval cmds=\"\$cmds~\$RM $delfiles\" + fi + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + + func_extract_archives $gentop $dlprefiles + func_append libobjs " $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $opt_silent || { + func_quote_for_expand "$cmd" + eval "func_echo $func_quote_for_expand_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test "$opt_mode" = relink; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS="$save_ifs" + + # Restore the uninstalled library and exit + if test "$opt_mode" = relink; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? + + if test -n "$convenience"; then + if test -z "$whole_archive_flag_spec"; then + func_show_eval '${RM}r "$gentop"' + fi + fi + + exit $EXIT_SUCCESS + fi + + # Create links to the real library. + for linkname in $linknames; do + if test "$realname" != "$linkname"; then + func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' + fi + done + + # If -module or -export-dynamic was specified, set the dlname. + if test "$module" = yes || test "$export_dynamic" = yes; then + # On all known operating systems, these are identical. + dlname="$soname" + fi + fi + ;; + + obj) + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + func_warning "\`-dlopen' is ignored for objects" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "\`-l' and \`-L' are ignored for objects" ;; + esac + + test -n "$rpath" && \ + func_warning "\`-rpath' is ignored for objects" + + test -n "$xrpath" && \ + func_warning "\`-R' is ignored for objects" + + test -n "$vinfo" && \ + func_warning "\`-version-info' is ignored for objects" + + test -n "$release" && \ + func_warning "\`-release' is ignored for objects" + + case $output in + *.lo) + test -n "$objs$old_deplibs" && \ + func_fatal_error "cannot build library object \`$output' from non-libtool objects" + + libobj=$output + func_lo2o "$libobj" + obj=$func_lo2o_result + ;; + *) + libobj= + obj="$output" + ;; + esac + + # Delete the old objects. + $opt_dry_run || $RM $obj $libobj + + # Objects from convenience libraries. This assumes + # single-version convenience libraries. Whenever we create + # different ones for PIC/non-PIC, this we'll have to duplicate + # the extraction. + reload_conv_objs= + gentop= + # reload_cmds runs $LD directly, so let us get rid of + # -Wl from whole_archive_flag_spec and hope we can get by with + # turning comma into space.. + wl= + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec"; then + eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" + reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` + else + gentop="$output_objdir/${obj}x" + func_append generated " $gentop" + + func_extract_archives $gentop $convenience + reload_conv_objs="$reload_objs $func_extract_archives_result" + fi + fi + + # If we're not building shared, we need to use non_pic_objs + test "$build_libtool_libs" != yes && libobjs="$non_pic_objects" + + # Create the old-style object. + reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test + + output="$obj" + func_execute_cmds "$reload_cmds" 'exit $?' + + # Exit if we aren't doing a library object file. + if test -z "$libobj"; then + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + fi + + if test "$build_libtool_libs" != yes; then + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + # Create an invalid libtool object if no PIC, so that we don't + # accidentally link it into a program. + # $show "echo timestamp > $libobj" + # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? + exit $EXIT_SUCCESS + fi + + if test -n "$pic_flag" || test "$pic_mode" != default; then + # Only do commands if we really have different PIC objects. + reload_objs="$libobjs $reload_conv_objs" + output="$libobj" + func_execute_cmds "$reload_cmds" 'exit $?' + fi + + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + ;; + + prog) + case $host in + *cygwin*) func_stripname '' '.exe' "$output" + output=$func_stripname_result.exe;; + esac + test -n "$vinfo" && \ + func_warning "\`-version-info' is ignored for programs" + + test -n "$release" && \ + func_warning "\`-release' is ignored for programs" + + test "$preload" = yes \ + && test "$dlopen_support" = unknown \ + && test "$dlopen_self" = unknown \ + && test "$dlopen_self_static" = unknown && \ + func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library is the System framework + compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` + finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` + ;; + esac + + case $host in + *-*-darwin*) + # Don't allow lazy linking, it breaks C++ global constructors + # But is supposedly fixed on 10.4 or later (yay!). + if test "$tagname" = CXX ; then + case ${MACOSX_DEPLOYMENT_TARGET-10.0} in + 10.[0123]) + func_append compile_command " ${wl}-bind_at_load" + func_append finalize_command " ${wl}-bind_at_load" + ;; + esac + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $compile_deplibs " in + *" -L$path/$objdir "*) + func_append new_libs " -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $compile_deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) func_append new_libs " $deplib" ;; + esac + ;; + *) func_append new_libs " $deplib" ;; + esac + done + compile_deplibs="$new_libs" + + + func_append compile_command " $compile_deplibs" + func_append finalize_command " $finalize_deplibs" + + if test -n "$rpath$xrpath"; then + # If the user specified any rpath flags, then add them. + for libdir in $rpath $xrpath; do + # This is the magic to use -rpath. + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + done + fi + + # Now hardcode the library paths + rpath= + hardcode_libdirs= + for libdir in $compile_rpath $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + func_append rpath " $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) func_append perm_rpath " $libdir" ;; + esac + fi + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$libdir:"*) ;; + ::) dllsearchpath=$libdir;; + *) func_append dllsearchpath ":$libdir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) func_append dllsearchpath ":$testbindir";; + esac + ;; + esac + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + compile_rpath="$rpath" + + rpath= + hardcode_libdirs= + for libdir in $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + func_append rpath " $flag" + fi + elif test -n "$runpath_var"; then + case "$finalize_perm_rpath " in + *" $libdir "*) ;; + *) func_append finalize_perm_rpath " $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + finalize_rpath="$rpath" + + if test -n "$libobjs" && test "$build_old_libs" = yes; then + # Transform all the library objects into standard objects. + compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` + finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` + fi + + func_generate_dlsyms "$outputname" "@PROGRAM@" "no" + + # template prelinking step + if test -n "$prelink_cmds"; then + func_execute_cmds "$prelink_cmds" 'exit $?' + fi + + wrappers_required=yes + case $host in + *cegcc* | *mingw32ce*) + # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. + wrappers_required=no + ;; + *cygwin* | *mingw* ) + if test "$build_libtool_libs" != yes; then + wrappers_required=no + fi + ;; + *) + if test "$need_relink" = no || test "$build_libtool_libs" != yes; then + wrappers_required=no + fi + ;; + esac + if test "$wrappers_required" = no; then + # Replace the output file specification. + compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` + link_command="$compile_command$compile_rpath" + + # We have no uninstalled library dependencies, so finalize right now. + exit_status=0 + func_show_eval "$link_command" 'exit_status=$?' + + if test -n "$postlink_cmds"; then + func_to_tool_file "$output" + postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` + func_execute_cmds "$postlink_cmds" 'exit $?' + fi + + # Delete the generated files. + if test -f "$output_objdir/${outputname}S.${objext}"; then + func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' + fi + + exit $exit_status + fi + + if test -n "$compile_shlibpath$finalize_shlibpath"; then + compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" + fi + if test -n "$finalize_shlibpath"; then + finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" + fi + + compile_var= + finalize_var= + if test -n "$runpath_var"; then + if test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + func_append rpath "$dir:" + done + compile_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + if test -n "$finalize_perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $finalize_perm_rpath; do + func_append rpath "$dir:" + done + finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + fi + + if test "$no_install" = yes; then + # We don't need to create a wrapper script. + link_command="$compile_var$compile_command$compile_rpath" + # Replace the output file specification. + link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` + # Delete the old output file. + $opt_dry_run || $RM $output + # Link the executable and exit + func_show_eval "$link_command" 'exit $?' + + if test -n "$postlink_cmds"; then + func_to_tool_file "$output" + postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` + func_execute_cmds "$postlink_cmds" 'exit $?' + fi + + exit $EXIT_SUCCESS + fi + + if test "$hardcode_action" = relink; then + # Fast installation is not supported + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + + func_warning "this platform does not like uninstalled shared libraries" + func_warning "\`$output' will be relinked during installation" + else + if test "$fast_install" != no; then + link_command="$finalize_var$compile_command$finalize_rpath" + if test "$fast_install" = yes; then + relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` + else + # fast_install is set to needless + relink_command= + fi + else + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + fi + fi + + # Replace the output file specification. + link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` + + # Delete the old output files. + $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname + + func_show_eval "$link_command" 'exit $?' + + if test -n "$postlink_cmds"; then + func_to_tool_file "$output_objdir/$outputname" + postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` + func_execute_cmds "$postlink_cmds" 'exit $?' + fi + + # Now create the wrapper script. + func_verbose "creating $output" + + # Quote the relink command for shipping. + if test -n "$relink_command"; then + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_for_eval "$var_value" + relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" + fi + done + relink_command="(cd `pwd`; $relink_command)" + relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` + fi + + # Only actually do things if not in dry run mode. + $opt_dry_run || { + # win32 will think the script is a binary if it has + # a .exe suffix, so we strip it off here. + case $output in + *.exe) func_stripname '' '.exe' "$output" + output=$func_stripname_result ;; + esac + # test for cygwin because mv fails w/o .exe extensions + case $host in + *cygwin*) + exeext=.exe + func_stripname '' '.exe' "$outputname" + outputname=$func_stripname_result ;; + *) exeext= ;; + esac + case $host in + *cygwin* | *mingw* ) + func_dirname_and_basename "$output" "" "." + output_name=$func_basename_result + output_path=$func_dirname_result + cwrappersource="$output_path/$objdir/lt-$output_name.c" + cwrapper="$output_path/$output_name.exe" + $RM $cwrappersource $cwrapper + trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 + + func_emit_cwrapperexe_src > $cwrappersource + + # The wrapper executable is built using the $host compiler, + # because it contains $host paths and files. If cross- + # compiling, it, like the target executable, must be + # executed on the $host or under an emulation environment. + $opt_dry_run || { + $LTCC $LTCFLAGS -o $cwrapper $cwrappersource + $STRIP $cwrapper + } + + # Now, create the wrapper script for func_source use: + func_ltwrapper_scriptname $cwrapper + $RM $func_ltwrapper_scriptname_result + trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 + $opt_dry_run || { + # note: this script will not be executed, so do not chmod. + if test "x$build" = "x$host" ; then + $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result + else + func_emit_wrapper no > $func_ltwrapper_scriptname_result + fi + } + ;; + * ) + $RM $output + trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 + + func_emit_wrapper no > $output + chmod +x $output + ;; + esac + } + exit $EXIT_SUCCESS + ;; + esac + + # See if we need to build an old-fashioned archive. + for oldlib in $oldlibs; do + + if test "$build_libtool_libs" = convenience; then + oldobjs="$libobjs_save $symfileobj" + addlibs="$convenience" + build_libtool_libs=no + else + if test "$build_libtool_libs" = module; then + oldobjs="$libobjs_save" + build_libtool_libs=no + else + oldobjs="$old_deplibs $non_pic_objects" + if test "$preload" = yes && test -f "$symfileobj"; then + func_append oldobjs " $symfileobj" + fi + fi + addlibs="$old_convenience" + fi + + if test -n "$addlibs"; then + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + + func_extract_archives $gentop $addlibs + func_append oldobjs " $func_extract_archives_result" + fi + + # Do each command in the archive commands. + if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then + cmds=$old_archive_from_new_cmds + else + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + + func_extract_archives $gentop $dlprefiles + func_append oldobjs " $func_extract_archives_result" + fi + + # POSIX demands no paths to be encoded in archives. We have + # to avoid creating archives with duplicate basenames if we + # might have to extract them afterwards, e.g., when creating a + # static archive out of a convenience library, or when linking + # the entirety of a libtool archive into another (currently + # not supported by libtool). + if (for obj in $oldobjs + do + func_basename "$obj" + $ECHO "$func_basename_result" + done | sort | sort -uc >/dev/null 2>&1); then + : + else + echo "copying selected object files to avoid basename conflicts..." + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + func_mkdir_p "$gentop" + save_oldobjs=$oldobjs + oldobjs= + counter=1 + for obj in $save_oldobjs + do + func_basename "$obj" + objbase="$func_basename_result" + case " $oldobjs " in + " ") oldobjs=$obj ;; + *[\ /]"$objbase "*) + while :; do + # Make sure we don't pick an alternate name that also + # overlaps. + newobj=lt$counter-$objbase + func_arith $counter + 1 + counter=$func_arith_result + case " $oldobjs " in + *[\ /]"$newobj "*) ;; + *) if test ! -f "$gentop/$newobj"; then break; fi ;; + esac + done + func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" + func_append oldobjs " $gentop/$newobj" + ;; + *) func_append oldobjs " $obj" ;; + esac + done + fi + func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 + tool_oldlib=$func_to_tool_file_result + eval cmds=\"$old_archive_cmds\" + + func_len " $cmds" + len=$func_len_result + if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + cmds=$old_archive_cmds + elif test -n "$archiver_list_spec"; then + func_verbose "using command file archive linking..." + for obj in $oldobjs + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" + done > $output_objdir/$libname.libcmd + func_to_tool_file "$output_objdir/$libname.libcmd" + oldobjs=" $archiver_list_spec$func_to_tool_file_result" + cmds=$old_archive_cmds + else + # the command line is too long to link in one step, link in parts + func_verbose "using piecewise archive linking..." + save_RANLIB=$RANLIB + RANLIB=: + objlist= + concat_cmds= + save_oldobjs=$oldobjs + oldobjs= + # Is there a better way of finding the last object in the list? + for obj in $save_oldobjs + do + last_oldobj=$obj + done + eval test_cmds=\"$old_archive_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + for obj in $save_oldobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + func_append objlist " $obj" + if test "$len" -lt "$max_cmd_len"; then + : + else + # the above command should be used before it gets too long + oldobjs=$objlist + if test "$obj" = "$last_oldobj" ; then + RANLIB=$save_RANLIB + fi + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" + objlist= + len=$len0 + fi + done + RANLIB=$save_RANLIB + oldobjs=$objlist + if test "X$oldobjs" = "X" ; then + eval cmds=\"\$concat_cmds\" + else + eval cmds=\"\$concat_cmds~\$old_archive_cmds\" + fi + fi + fi + func_execute_cmds "$cmds" 'exit $?' + done + + test -n "$generated" && \ + func_show_eval "${RM}r$generated" + + # Now create the libtool archive. + case $output in + *.la) + old_library= + test "$build_old_libs" = yes && old_library="$libname.$libext" + func_verbose "creating $output" + + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_for_eval "$var_value" + relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" + fi + done + # Quote the link command for shipping. + relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" + relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` + if test "$hardcode_automatic" = yes ; then + relink_command= + fi + + # Only create the output if not a dry run. + $opt_dry_run || { + for installed in no yes; do + if test "$installed" = yes; then + if test -z "$install_libdir"; then + break + fi + output="$output_objdir/$outputname"i + # Replace all uninstalled libtool libraries with the installed ones + newdependency_libs= + for deplib in $dependency_libs; do + case $deplib in + *.la) + func_basename "$deplib" + name="$func_basename_result" + func_resolve_sysroot "$deplib" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` + test -z "$libdir" && \ + func_fatal_error "\`$deplib' is not a valid libtool archive" + func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" + ;; + -L*) + func_stripname -L '' "$deplib" + func_replace_sysroot "$func_stripname_result" + func_append newdependency_libs " -L$func_replace_sysroot_result" + ;; + -R*) + func_stripname -R '' "$deplib" + func_replace_sysroot "$func_stripname_result" + func_append newdependency_libs " -R$func_replace_sysroot_result" + ;; + *) func_append newdependency_libs " $deplib" ;; + esac + done + dependency_libs="$newdependency_libs" + newdlfiles= + + for lib in $dlfiles; do + case $lib in + *.la) + func_basename "$lib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "\`$lib' is not a valid libtool archive" + func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" + ;; + *) func_append newdlfiles " $lib" ;; + esac + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + *.la) + # Only pass preopened files to the pseudo-archive (for + # eventual linking with the app. that links it) if we + # didn't already link the preopened objects directly into + # the library: + func_basename "$lib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "\`$lib' is not a valid libtool archive" + func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" + ;; + esac + done + dlprefiles="$newdlprefiles" + else + newdlfiles= + for lib in $dlfiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + func_append newdlfiles " $abs" + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + func_append newdlprefiles " $abs" + done + dlprefiles="$newdlprefiles" + fi + $RM $output + # place dlname in correct position for cygwin + # In fact, it would be nice if we could use this code for all target + # systems that can't hard-code library paths into their executables + # and that have no shared library path variable independent of PATH, + # but it turns out we can't easily determine that from inspecting + # libtool variables, so we have to hard-code the OSs to which it + # applies here; at the moment, that means platforms that use the PE + # object format with DLL files. See the long comment at the top of + # tests/bindir.at for full details. + tdlname=$dlname + case $host,$output,$installed,$module,$dlname in + *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) + # If a -bindir argument was supplied, place the dll there. + if test "x$bindir" != x ; + then + func_relative_path "$install_libdir" "$bindir" + tdlname=$func_relative_path_result$dlname + else + # Otherwise fall back on heuristic. + tdlname=../bin/$dlname + fi + ;; + esac + $ECHO > $output "\ +# $outputname - a libtool library file +# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION +# +# Please DO NOT delete this file! +# It is necessary for linking the library. + +# The name that we can dlopen(3). +dlname='$tdlname' + +# Names of this library. +library_names='$library_names' + +# The name of the static archive. +old_library='$old_library' + +# Linker flags that can not go in dependency_libs. +inherited_linker_flags='$new_inherited_linker_flags' + +# Libraries that this one depends upon. +dependency_libs='$dependency_libs' + +# Names of additional weak libraries provided by this library +weak_library_names='$weak_libs' + +# Version information for $libname. +current=$current +age=$age +revision=$revision + +# Is this an already installed library? +installed=$installed + +# Should we warn about portability when linking against -modules? +shouldnotlink=$module + +# Files to dlopen/dlpreopen +dlopen='$dlfiles' +dlpreopen='$dlprefiles' + +# Directory that this library needs to be installed in: +libdir='$install_libdir'" + if test "$installed" = no && test "$need_relink" = yes; then + $ECHO >> $output "\ +relink_command=\"$relink_command\"" + fi + done + } + + # Do a symbolic link so that the libtool archive can be found in + # LD_LIBRARY_PATH before the program is installed. + func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' + ;; + esac + exit $EXIT_SUCCESS +} + +{ test "$opt_mode" = link || test "$opt_mode" = relink; } && + func_mode_link ${1+"$@"} + + +# func_mode_uninstall arg... +func_mode_uninstall () +{ + $opt_debug + RM="$nonopt" + files= + rmforce= + exit_status=0 + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + for arg + do + case $arg in + -f) func_append RM " $arg"; rmforce=yes ;; + -*) func_append RM " $arg" ;; + *) func_append files " $arg" ;; + esac + done + + test -z "$RM" && \ + func_fatal_help "you must specify an RM program" + + rmdirs= + + for file in $files; do + func_dirname "$file" "" "." + dir="$func_dirname_result" + if test "X$dir" = X.; then + odir="$objdir" + else + odir="$dir/$objdir" + fi + func_basename "$file" + name="$func_basename_result" + test "$opt_mode" = uninstall && odir="$dir" + + # Remember odir for removal later, being careful to avoid duplicates + if test "$opt_mode" = clean; then + case " $rmdirs " in + *" $odir "*) ;; + *) func_append rmdirs " $odir" ;; + esac + fi + + # Don't error if the file doesn't exist and rm -f was used. + if { test -L "$file"; } >/dev/null 2>&1 || + { test -h "$file"; } >/dev/null 2>&1 || + test -f "$file"; then + : + elif test -d "$file"; then + exit_status=1 + continue + elif test "$rmforce" = yes; then + continue + fi + + rmfiles="$file" + + case $name in + *.la) + # Possibly a libtool archive, so verify it. + if func_lalib_p "$file"; then + func_source $dir/$name + + # Delete the libtool libraries and symlinks. + for n in $library_names; do + func_append rmfiles " $odir/$n" + done + test -n "$old_library" && func_append rmfiles " $odir/$old_library" + + case "$opt_mode" in + clean) + case " $library_names " in + *" $dlname "*) ;; + *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; + esac + test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" + ;; + uninstall) + if test -n "$library_names"; then + # Do each command in the postuninstall commands. + func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' + fi + + if test -n "$old_library"; then + # Do each command in the old_postuninstall commands. + func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' + fi + # FIXME: should reinstall the best remaining shared library. + ;; + esac + fi + ;; + + *.lo) + # Possibly a libtool object, so verify it. + if func_lalib_p "$file"; then + + # Read the .lo file + func_source $dir/$name + + # Add PIC object to the list of files to remove. + if test -n "$pic_object" && + test "$pic_object" != none; then + func_append rmfiles " $dir/$pic_object" + fi + + # Add non-PIC object to the list of files to remove. + if test -n "$non_pic_object" && + test "$non_pic_object" != none; then + func_append rmfiles " $dir/$non_pic_object" + fi + fi + ;; + + *) + if test "$opt_mode" = clean ; then + noexename=$name + case $file in + *.exe) + func_stripname '' '.exe' "$file" + file=$func_stripname_result + func_stripname '' '.exe' "$name" + noexename=$func_stripname_result + # $file with .exe has already been added to rmfiles, + # add $file without .exe + func_append rmfiles " $file" + ;; + esac + # Do a test to see if this is a libtool program. + if func_ltwrapper_p "$file"; then + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + relink_command= + func_source $func_ltwrapper_scriptname_result + func_append rmfiles " $func_ltwrapper_scriptname_result" + else + relink_command= + func_source $dir/$noexename + fi + + # note $name still contains .exe if it was in $file originally + # as does the version of $file that was added into $rmfiles + func_append rmfiles " $odir/$name $odir/${name}S.${objext}" + if test "$fast_install" = yes && test -n "$relink_command"; then + func_append rmfiles " $odir/lt-$name" + fi + if test "X$noexename" != "X$name" ; then + func_append rmfiles " $odir/lt-${noexename}.c" + fi + fi + fi + ;; + esac + func_show_eval "$RM $rmfiles" 'exit_status=1' + done + + # Try to remove the ${objdir}s in the directories where we deleted files + for dir in $rmdirs; do + if test -d "$dir"; then + func_show_eval "rmdir $dir >/dev/null 2>&1" + fi + done + + exit $exit_status +} + +{ test "$opt_mode" = uninstall || test "$opt_mode" = clean; } && + func_mode_uninstall ${1+"$@"} + +test -z "$opt_mode" && { + help="$generic_help" + func_fatal_help "you must specify a MODE" +} + +test -z "$exec_cmd" && \ + func_fatal_help "invalid operation mode \`$opt_mode'" + +if test -n "$exec_cmd"; then + eval exec "$exec_cmd" + exit $EXIT_FAILURE +fi + +exit $exit_status + + +# The TAGs below are defined such that we never get into a situation +# in which we disable both kinds of libraries. Given conflicting +# choices, we go for a static library, that is the most portable, +# since we can't tell whether shared libraries were disabled because +# the user asked for that or because the platform doesn't support +# them. This is particularly important on AIX, because we don't +# support having both static and shared libraries enabled at the same +# time on that platform, so we default to a shared-only configuration. +# If a disable-shared tag is given, we'll fallback to a static-only +# configuration. But we'll never go from static-only to shared-only. + +# ### BEGIN LIBTOOL TAG CONFIG: disable-shared +build_libtool_libs=no +build_old_libs=yes +# ### END LIBTOOL TAG CONFIG: disable-shared + +# ### BEGIN LIBTOOL TAG CONFIG: disable-static +build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` +# ### END LIBTOOL TAG CONFIG: disable-static + +# Local Variables: +# mode:shell-script +# sh-indentation:2 +# End: +# vi:sw=2 + diff --git a/components/external/SQLite-3.8.1/autoconf/missing b/components/external/SQLite-3.8.1/autoconf/missing new file mode 100644 index 0000000000000000000000000000000000000000..86a8fc31e3c2aa268688a5be47d161c586772e78 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/missing @@ -0,0 +1,331 @@ +#! /bin/sh +# Common stub for a few missing GNU programs while installing. + +scriptversion=2012-01-06.13; # UTC + +# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006, +# 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. +# Originally by Fran,cois Pinard , 1996. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +if test $# -eq 0; then + echo 1>&2 "Try \`$0 --help' for more information" + exit 1 +fi + +run=: +sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p' +sed_minuso='s/.* -o \([^ ]*\).*/\1/p' + +# In the cases where this matters, `missing' is being run in the +# srcdir already. +if test -f configure.ac; then + configure_ac=configure.ac +else + configure_ac=configure.in +fi + +msg="missing on your system" + +case $1 in +--run) + # Try to run requested program, and just exit if it succeeds. + run= + shift + "$@" && exit 0 + # Exit code 63 means version mismatch. This often happens + # when the user try to use an ancient version of a tool on + # a file that requires a minimum version. In this case we + # we should proceed has if the program had been absent, or + # if --run hadn't been passed. + if test $? = 63; then + run=: + msg="probably too old" + fi + ;; + + -h|--h|--he|--hel|--help) + echo "\ +$0 [OPTION]... PROGRAM [ARGUMENT]... + +Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an +error status if there is no known handling for PROGRAM. + +Options: + -h, --help display this help and exit + -v, --version output version information and exit + --run try to run the given command, and emulate it if it fails + +Supported PROGRAM values: + aclocal touch file \`aclocal.m4' + autoconf touch file \`configure' + autoheader touch file \`config.h.in' + autom4te touch the output file, or create a stub one + automake touch all \`Makefile.in' files + bison create \`y.tab.[ch]', if possible, from existing .[ch] + flex create \`lex.yy.c', if possible, from existing .c + help2man touch the output file + lex create \`lex.yy.c', if possible, from existing .c + makeinfo touch the output file + yacc create \`y.tab.[ch]', if possible, from existing .[ch] + +Version suffixes to PROGRAM as well as the prefixes \`gnu-', \`gnu', and +\`g' are ignored when checking the name. + +Send bug reports to ." + exit $? + ;; + + -v|--v|--ve|--ver|--vers|--versi|--versio|--version) + echo "missing $scriptversion (GNU Automake)" + exit $? + ;; + + -*) + echo 1>&2 "$0: Unknown \`$1' option" + echo 1>&2 "Try \`$0 --help' for more information" + exit 1 + ;; + +esac + +# normalize program name to check for. +program=`echo "$1" | sed ' + s/^gnu-//; t + s/^gnu//; t + s/^g//; t'` + +# Now exit if we have it, but it failed. Also exit now if we +# don't have it and --version was passed (most likely to detect +# the program). This is about non-GNU programs, so use $1 not +# $program. +case $1 in + lex*|yacc*) + # Not GNU programs, they don't have --version. + ;; + + *) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + elif test "x$2" = "x--version" || test "x$2" = "x--help"; then + # Could not run --version or --help. This is probably someone + # running `$TOOL --version' or `$TOOL --help' to check whether + # $TOOL exists and not knowing $TOOL uses missing. + exit 1 + fi + ;; +esac + +# If it does not exist, or fails to run (possibly an outdated version), +# try to emulate it. +case $program in + aclocal*) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`acinclude.m4' or \`${configure_ac}'. You might want + to install the \`Automake' and \`Perl' packages. Grab them from + any GNU archive site." + touch aclocal.m4 + ;; + + autoconf*) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`${configure_ac}'. You might want to install the + \`Autoconf' and \`GNU m4' packages. Grab them from any GNU + archive site." + touch configure + ;; + + autoheader*) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`acconfig.h' or \`${configure_ac}'. You might want + to install the \`Autoconf' and \`GNU m4' packages. Grab them + from any GNU archive site." + files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}` + test -z "$files" && files="config.h" + touch_files= + for f in $files; do + case $f in + *:*) touch_files="$touch_files "`echo "$f" | + sed -e 's/^[^:]*://' -e 's/:.*//'`;; + *) touch_files="$touch_files $f.in";; + esac + done + touch $touch_files + ;; + + automake*) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'. + You might want to install the \`Automake' and \`Perl' packages. + Grab them from any GNU archive site." + find . -type f -name Makefile.am -print | + sed 's/\.am$/.in/' | + while read f; do touch "$f"; done + ;; + + autom4te*) + echo 1>&2 "\ +WARNING: \`$1' is needed, but is $msg. + You might have modified some files without having the + proper tools for further handling them. + You can get \`$1' as part of \`Autoconf' from any GNU + archive site." + + file=`echo "$*" | sed -n "$sed_output"` + test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` + if test -f "$file"; then + touch $file + else + test -z "$file" || exec >$file + echo "#! /bin/sh" + echo "# Created by GNU Automake missing as a replacement of" + echo "# $ $@" + echo "exit 0" + chmod +x $file + exit 1 + fi + ;; + + bison*|yacc*) + echo 1>&2 "\ +WARNING: \`$1' $msg. You should only need it if + you modified a \`.y' file. You may need the \`Bison' package + in order for those modifications to take effect. You can get + \`Bison' from any GNU archive site." + rm -f y.tab.c y.tab.h + if test $# -ne 1; then + eval LASTARG=\${$#} + case $LASTARG in + *.y) + SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` + if test -f "$SRCFILE"; then + cp "$SRCFILE" y.tab.c + fi + SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` + if test -f "$SRCFILE"; then + cp "$SRCFILE" y.tab.h + fi + ;; + esac + fi + if test ! -f y.tab.h; then + echo >y.tab.h + fi + if test ! -f y.tab.c; then + echo 'main() { return 0; }' >y.tab.c + fi + ;; + + lex*|flex*) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified a \`.l' file. You may need the \`Flex' package + in order for those modifications to take effect. You can get + \`Flex' from any GNU archive site." + rm -f lex.yy.c + if test $# -ne 1; then + eval LASTARG=\${$#} + case $LASTARG in + *.l) + SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` + if test -f "$SRCFILE"; then + cp "$SRCFILE" lex.yy.c + fi + ;; + esac + fi + if test ! -f lex.yy.c; then + echo 'main() { return 0; }' >lex.yy.c + fi + ;; + + help2man*) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified a dependency of a manual page. You may need the + \`Help2man' package in order for those modifications to take + effect. You can get \`Help2man' from any GNU archive site." + + file=`echo "$*" | sed -n "$sed_output"` + test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` + if test -f "$file"; then + touch $file + else + test -z "$file" || exec >$file + echo ".ab help2man is required to generate this page" + exit $? + fi + ;; + + makeinfo*) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified a \`.texi' or \`.texinfo' file, or any other file + indirectly affecting the aspect of the manual. The spurious + call might also be the consequence of using a buggy \`make' (AIX, + DU, IRIX). You might want to install the \`Texinfo' package or + the \`GNU make' package. Grab either from any GNU archive site." + # The file to touch is that specified with -o ... + file=`echo "$*" | sed -n "$sed_output"` + test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` + if test -z "$file"; then + # ... or it is the one specified with @setfilename ... + infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` + file=`sed -n ' + /^@setfilename/{ + s/.* \([^ ]*\) *$/\1/ + p + q + }' $infile` + # ... or it is derived from the source name (dir/f.texi becomes f.info) + test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info + fi + # If the file does not exist, the user really needs makeinfo; + # let's fail without touching anything. + test -f $file || exit 1 + touch $file + ;; + + *) + echo 1>&2 "\ +WARNING: \`$1' is needed, and is $msg. + You might have modified some files without having the + proper tools for further handling them. Check the \`README' file, + it often tells you about the needed prerequisites for installing + this package. You may also peek at any GNU archive site, in case + some other package would contain this missing \`$1' program." + exit 1 + ;; +esac + +exit 0 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC" +# time-stamp-end: "; # UTC" +# End: diff --git a/components/external/SQLite-3.8.1/autoconf/tea/Makefile.in b/components/external/SQLite-3.8.1/autoconf/tea/Makefile.in new file mode 100644 index 0000000000000000000000000000000000000000..08b1a44182583706cfa0d618ce4b73d667566636 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/Makefile.in @@ -0,0 +1,439 @@ +# Makefile.in -- +# +# This file is a Makefile for Sample TEA Extension. If it has the name +# "Makefile.in" then it is a template for a Makefile; to generate the +# actual Makefile, run "./configure", which is a configuration script +# generated by the "autoconf" program (constructs like "@foo@" will get +# replaced in the actual Makefile. +# +# Copyright (c) 1999 Scriptics Corporation. +# Copyright (c) 2002-2005 ActiveState Corporation. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# RCS: @(#) $Id: Makefile.in,v 1.59 2005/07/26 19:17:02 mdejong Exp $ + +#======================================================================== +# Add additional lines to handle any additional AC_SUBST cases that +# have been added in a customized configure script. +#======================================================================== + +#SAMPLE_NEW_VAR = @SAMPLE_NEW_VAR@ + +#======================================================================== +# Nothing of the variables below this line should need to be changed. +# Please check the TARGETS section below to make sure the make targets +# are correct. +#======================================================================== + +#======================================================================== +# The names of the source files is defined in the configure script. +# The object files are used for linking into the final library. +# This will be used when a dist target is added to the Makefile. +# It is not important to specify the directory, as long as it is the +# $(srcdir) or in the generic, win or unix subdirectory. +#======================================================================== + +PKG_SOURCES = @PKG_SOURCES@ +PKG_OBJECTS = @PKG_OBJECTS@ + +PKG_STUB_SOURCES = @PKG_STUB_SOURCES@ +PKG_STUB_OBJECTS = @PKG_STUB_OBJECTS@ + +#======================================================================== +# PKG_TCL_SOURCES identifies Tcl runtime files that are associated with +# this package that need to be installed, if any. +#======================================================================== + +PKG_TCL_SOURCES = @PKG_TCL_SOURCES@ + +#======================================================================== +# This is a list of public header files to be installed, if any. +#======================================================================== + +PKG_HEADERS = @PKG_HEADERS@ + +#======================================================================== +# "PKG_LIB_FILE" refers to the library (dynamic or static as per +# configuration options) composed of the named objects. +#======================================================================== + +PKG_LIB_FILE = @PKG_LIB_FILE@ +PKG_STUB_LIB_FILE = @PKG_STUB_LIB_FILE@ + +lib_BINARIES = $(PKG_LIB_FILE) +BINARIES = $(lib_BINARIES) + +SHELL = @SHELL@ + +srcdir = @srcdir@ +prefix = @prefix@ +exec_prefix = @exec_prefix@ + +bindir = @bindir@ +libdir = @libdir@ +datadir = @datadir@ +mandir = @mandir@ +includedir = @includedir@ + +DESTDIR = + +PKG_DIR = $(PACKAGE_NAME)$(PACKAGE_VERSION) +pkgdatadir = $(datadir)/$(PKG_DIR) +pkglibdir = $(libdir)/$(PKG_DIR) +pkgincludedir = $(includedir)/$(PKG_DIR) + +top_builddir = . + +INSTALL = @INSTALL@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ + +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +CC = @CC@ +CFLAGS_DEFAULT = @CFLAGS_DEFAULT@ +CFLAGS_WARNING = @CFLAGS_WARNING@ +CLEANFILES = @CLEANFILES@ +EXEEXT = @EXEEXT@ +LDFLAGS_DEFAULT = @LDFLAGS_DEFAULT@ +MAKE_LIB = @MAKE_LIB@ +MAKE_SHARED_LIB = @MAKE_SHARED_LIB@ +MAKE_STATIC_LIB = @MAKE_STATIC_LIB@ +MAKE_STUB_LIB = @MAKE_STUB_LIB@ +OBJEXT = @OBJEXT@ +RANLIB = @RANLIB@ +RANLIB_STUB = @RANLIB_STUB@ +SHLIB_CFLAGS = @SHLIB_CFLAGS@ +SHLIB_LD = @SHLIB_LD@ +SHLIB_LD_LIBS = @SHLIB_LD_LIBS@ +STLIB_LD = @STLIB_LD@ +#TCL_DEFS = @TCL_DEFS@ +TCL_BIN_DIR = @TCL_BIN_DIR@ +TCL_SRC_DIR = @TCL_SRC_DIR@ +#TK_BIN_DIR = @TK_BIN_DIR@ +#TK_SRC_DIR = @TK_SRC_DIR@ + +# This is no longer necessary even for packages that use private Tcl headers +#TCL_TOP_DIR_NATIVE = @TCL_TOP_DIR_NATIVE@ +# Not used, but retained for reference of what libs Tcl required +#TCL_LIBS = @TCL_LIBS@ + +#======================================================================== +# TCLLIBPATH seeds the auto_path in Tcl's init.tcl so we can test our +# package without installing. The other environment variables allow us +# to test against an uninstalled Tcl. Add special env vars that you +# require for testing here (like TCLX_LIBRARY). +#======================================================================== + +EXTRA_PATH = $(top_builddir):$(TCL_BIN_DIR) +#EXTRA_PATH = $(top_builddir):$(TCL_BIN_DIR):$(TK_BIN_DIR) +TCLLIBPATH = $(top_builddir) +TCLSH_ENV = TCL_LIBRARY=`@CYGPATH@ $(TCL_SRC_DIR)/library` \ + @LD_LIBRARY_PATH_VAR@="$(EXTRA_PATH):$(@LD_LIBRARY_PATH_VAR@)" \ + PATH="$(EXTRA_PATH):$(PATH)" \ + TCLLIBPATH="$(TCLLIBPATH)" +# TK_LIBRARY=`@CYGPATH@ $(TK_SRC_DIR)/library` + +TCLSH_PROG = @TCLSH_PROG@ +TCLSH = $(TCLSH_ENV) $(TCLSH_PROG) + +#WISH_PROG = @WISH_PROG@ +#WISH = $(TCLSH_ENV) $(WISH_PROG) + + +SHARED_BUILD = @SHARED_BUILD@ + +INCLUDES = @PKG_INCLUDES@ @TCL_INCLUDES@ -I$(srcdir)/.. +#INCLUDES = @PKG_INCLUDES@ @TCL_INCLUDES@ @TK_INCLUDES@ @TK_XINCLUDES@ + +PKG_CFLAGS = @PKG_CFLAGS@ + +# TCL_DEFS is not strictly need here, but if you remove it, then you +# must make sure that configure.in checks for the necessary components +# that your library may use. TCL_DEFS can actually be a problem if +# you do not compile with a similar machine setup as the Tcl core was +# compiled with. +#DEFS = $(TCL_DEFS) @DEFS@ $(PKG_CFLAGS) +DEFS = @DEFS@ $(PKG_CFLAGS) + +CONFIG_CLEAN_FILES = Makefile pkgIndex.tcl + +CPPFLAGS = @CPPFLAGS@ +LIBS = @PKG_LIBS@ @LIBS@ +AR = @AR@ +CFLAGS = @CFLAGS@ +COMPILE = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) + +#======================================================================== +# Start of user-definable TARGETS section +#======================================================================== + +#======================================================================== +# TEA TARGETS. Please note that the "libraries:" target refers to platform +# independent files, and the "binaries:" target inclues executable programs and +# platform-dependent libraries. Modify these targets so that they install +# the various pieces of your package. The make and install rules +# for the BINARIES that you specified above have already been done. +#======================================================================== + +all: binaries libraries doc + +#======================================================================== +# The binaries target builds executable programs, Windows .dll's, unix +# shared/static libraries, and any other platform-dependent files. +# The list of targets to build for "binaries:" is specified at the top +# of the Makefile, in the "BINARIES" variable. +#======================================================================== + +binaries: $(BINARIES) + +libraries: + + +#======================================================================== +# Your doc target should differentiate from doc builds (by the developer) +# and doc installs (see install-doc), which just install the docs on the +# end user machine when building from source. +#======================================================================== + +doc: + @echo "If you have documentation to create, place the commands to" + @echo "build the docs in the 'doc:' target. For example:" + @echo " xml2nroff sample.xml > sample.n" + @echo " xml2html sample.xml > sample.html" + +install: all install-binaries install-libraries install-doc + +install-binaries: binaries install-lib-binaries install-bin-binaries + +#======================================================================== +# This rule installs platform-independent files, such as header files. +# The list=...; for p in $$list handles the empty list case x-platform. +#======================================================================== + +install-libraries: libraries + @mkdir -p $(DESTDIR)$(includedir) + @echo "Installing header files in $(DESTDIR)$(includedir)" + @list='$(PKG_HEADERS)'; for i in $$list; do \ + echo "Installing $(srcdir)/$$i" ; \ + $(INSTALL_DATA) $(srcdir)/$$i $(DESTDIR)$(includedir) ; \ + done; + +#======================================================================== +# Install documentation. Unix manpages should go in the $(mandir) +# directory. +#======================================================================== + +install-doc: doc + @mkdir -p $(DESTDIR)$(mandir)/mann + @echo "Installing documentation in $(DESTDIR)$(mandir)" + @list='$(srcdir)/doc/*.n'; for i in $$list; do \ + echo "Installing $$i"; \ + rm -f $(DESTDIR)$(mandir)/mann/`basename $$i`; \ + $(INSTALL_DATA) $$i $(DESTDIR)$(mandir)/mann ; \ + done + +test: binaries libraries + @echo "SQLite TEA distribution does not include tests" + +shell: binaries libraries + @$(TCLSH) $(SCRIPT) + +gdb: + $(TCLSH_ENV) gdb $(TCLSH_PROG) $(SCRIPT) + +depend: + +#======================================================================== +# $(PKG_LIB_FILE) should be listed as part of the BINARIES variable +# mentioned above. That will ensure that this target is built when you +# run "make binaries". +# +# The $(PKG_OBJECTS) objects are created and linked into the final +# library. In most cases these object files will correspond to the +# source files above. +#======================================================================== + +$(PKG_LIB_FILE): $(PKG_OBJECTS) + -rm -f $(PKG_LIB_FILE) + ${MAKE_LIB} + $(RANLIB) $(PKG_LIB_FILE) + +$(PKG_STUB_LIB_FILE): $(PKG_STUB_OBJECTS) + -rm -f $(PKG_STUB_LIB_FILE) + ${MAKE_STUB_LIB} + $(RANLIB_STUB) $(PKG_STUB_LIB_FILE) + +#======================================================================== +# We need to enumerate the list of .c to .o lines here. +# +# In the following lines, $(srcdir) refers to the toplevel directory +# containing your extension. If your sources are in a subdirectory, +# you will have to modify the paths to reflect this: +# +# sample.$(OBJEXT): $(srcdir)/generic/sample.c +# $(COMPILE) -c `@CYGPATH@ $(srcdir)/generic/sample.c` -o $@ +# +# Setting the VPATH variable to a list of paths will cause the makefile +# to look into these paths when resolving .c to .obj dependencies. +# As necessary, add $(srcdir):$(srcdir)/compat:.... +#======================================================================== + +VPATH = $(srcdir):$(srcdir)/generic:$(srcdir)/unix:$(srcdir)/win + +.c.@OBJEXT@: + $(COMPILE) -c `@CYGPATH@ $<` -o $@ + +#======================================================================== +# Distribution creation +# You may need to tweak this target to make it work correctly. +#======================================================================== + +#COMPRESS = tar cvf $(PKG_DIR).tar $(PKG_DIR); compress $(PKG_DIR).tar +COMPRESS = gtar zcvf $(PKG_DIR).tar.gz $(PKG_DIR) +DIST_ROOT = /tmp/dist +DIST_DIR = $(DIST_ROOT)/$(PKG_DIR) + +dist-clean: + rm -rf $(DIST_DIR) $(DIST_ROOT)/$(PKG_DIR).tar.* + +dist: dist-clean + mkdir -p $(DIST_DIR) + cp -p $(srcdir)/README* $(srcdir)/license* \ + $(srcdir)/aclocal.m4 $(srcdir)/configure $(srcdir)/*.in \ + $(DIST_DIR)/ + chmod 664 $(DIST_DIR)/Makefile.in $(DIST_DIR)/aclocal.m4 + chmod 775 $(DIST_DIR)/configure $(DIST_DIR)/configure.in + + for i in $(srcdir)/*.[ch]; do \ + if [ -f $$i ]; then \ + cp -p $$i $(DIST_DIR)/ ; \ + fi; \ + done; + + mkdir $(DIST_DIR)/tclconfig + cp $(srcdir)/tclconfig/install-sh $(srcdir)/tclconfig/tcl.m4 \ + $(DIST_DIR)/tclconfig/ + chmod 664 $(DIST_DIR)/tclconfig/tcl.m4 + chmod +x $(DIST_DIR)/tclconfig/install-sh + + list='demos doc generic library mac tests unix win'; \ + for p in $$list; do \ + if test -d $(srcdir)/$$p ; then \ + mkdir $(DIST_DIR)/$$p; \ + cp -p $(srcdir)/$$p/*.* $(DIST_DIR)/$$p/; \ + fi; \ + done + + (cd $(DIST_ROOT); $(COMPRESS);) + +#======================================================================== +# End of user-definable section +#======================================================================== + +#======================================================================== +# Don't modify the file to clean here. Instead, set the "CLEANFILES" +# variable in configure.in +#======================================================================== + +clean: + -test -z "$(BINARIES)" || rm -f $(BINARIES) + -rm -f *.$(OBJEXT) core *.core + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) + +distclean: clean + -rm -f *.tab.c + -rm -f $(CONFIG_CLEAN_FILES) + -rm -f config.cache config.log config.status + +#======================================================================== +# Install binary object libraries. On Windows this includes both .dll and +# .lib files. Because the .lib files are not explicitly listed anywhere, +# we need to deduce their existence from the .dll file of the same name. +# Library files go into the lib directory. +# In addition, this will generate the pkgIndex.tcl +# file in the install location (assuming it can find a usable tclsh shell) +# +# You should not have to modify this target. +#======================================================================== + +install-lib-binaries: binaries + @mkdir -p $(DESTDIR)$(pkglibdir) + @list='$(lib_BINARIES)'; for p in $$list; do \ + if test -f $$p; then \ + echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p"; \ + $(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p; \ + stub=`echo $$p|sed -e "s/.*\(stub\).*/\1/"`; \ + if test "x$$stub" = "xstub"; then \ + echo " $(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p"; \ + $(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p; \ + else \ + echo " $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p"; \ + $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p; \ + fi; \ + ext=`echo $$p|sed -e "s/.*\.//"`; \ + if test "x$$ext" = "xdll"; then \ + lib=`basename $$p|sed -e 's/.[^.]*$$//'`.lib; \ + if test -f $$lib; then \ + echo " $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib"; \ + $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib; \ + fi; \ + fi; \ + fi; \ + done + @list='$(PKG_TCL_SOURCES)'; for p in $$list; do \ + if test -f $(srcdir)/$$p; then \ + destp=`basename $$p`; \ + echo " Install $$destp $(DESTDIR)$(pkglibdir)/$$destp"; \ + $(INSTALL_DATA) $(srcdir)/$$p $(DESTDIR)$(pkglibdir)/$$destp; \ + fi; \ + done + @if test "x$(SHARED_BUILD)" = "x1"; then \ + echo " Install pkgIndex.tcl $(DESTDIR)$(pkglibdir)"; \ + $(INSTALL_DATA) pkgIndex.tcl $(DESTDIR)$(pkglibdir); \ + fi + +#======================================================================== +# Install binary executables (e.g. .exe files and dependent .dll files) +# This is for files that must go in the bin directory (located next to +# wish and tclsh), like dependent .dll files on Windows. +# +# You should not have to modify this target, except to define bin_BINARIES +# above if necessary. +#======================================================================== + +install-bin-binaries: binaries + @mkdir -p $(DESTDIR)$(bindir) + @list='$(bin_BINARIES)'; for p in $$list; do \ + if test -f $$p; then \ + echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p"; \ + $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p; \ + fi; \ + done + +.SUFFIXES: .c .$(OBJEXT) + +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + cd $(top_builddir) \ + && CONFIG_FILES=$@ CONFIG_HEADERS= $(SHELL) ./config.status + +uninstall-binaries: + list='$(lib_BINARIES)'; for p in $$list; do \ + rm -f $(DESTDIR)$(pkglibdir)/$$p; \ + done + list='$(PKG_TCL_SOURCES)'; for p in $$list; do \ + p=`basename $$p`; \ + rm -f $(DESTDIR)$(pkglibdir)/$$p; \ + done + list='$(bin_BINARIES)'; for p in $$list; do \ + rm -f $(DESTDIR)$(bindir)/$$p; \ + done + +.PHONY: all binaries clean depend distclean doc install libraries test + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/components/external/SQLite-3.8.1/autoconf/tea/README b/components/external/SQLite-3.8.1/autoconf/tea/README new file mode 100644 index 0000000000000000000000000000000000000000..99dc8b8f03cda56e80e8dbf594bfe1feb3f880ae --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/README @@ -0,0 +1,36 @@ +This is the SQLite extension for Tcl using the Tcl Extension +Architecture (TEA). For additional information on SQLite see + + http://www.sqlite.org/ + + +UNIX BUILD +========== + +Building under most UNIX systems is easy, just run the configure script +and then run make. For more information about the build process, see +the tcl/unix/README file in the Tcl src dist. The following minimal +example will install the extension in the /opt/tcl directory. + + $ cd sqlite-*-tea + $ ./configure --prefix=/opt/tcl + $ make + $ make install + +WINDOWS BUILD +============= + +The recommended method to build extensions under windows is to use the +Msys + Mingw build process. This provides a Unix-style build while +generating native Windows binaries. Using the Msys + Mingw build tools +means that you can use the same configure script as per the Unix build +to create a Makefile. See the tcl/win/README file for the URL of +the Msys + Mingw download. + +If you have VC++ then you may wish to use the files in the win +subdirectory and build the extension using just VC++. These files have +been designed to be as generic as possible but will require some +additional maintenance by the project developer to synchronise with +the TEA configure.in and Makefile.in files. Instructions for using the +VC++ makefile are written in the first part of the Makefile.vc +file. diff --git a/components/external/SQLite-3.8.1/autoconf/tea/aclocal.m4 b/components/external/SQLite-3.8.1/autoconf/tea/aclocal.m4 new file mode 100644 index 0000000000000000000000000000000000000000..0b057391d2919535a4427b09987c06287eb6e05e --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/aclocal.m4 @@ -0,0 +1,9 @@ +# +# Include the TEA standard macro set +# + +builtin(include,tclconfig/tcl.m4) + +# +# Add here whatever m4 macros you want to define for your package +# diff --git a/components/external/SQLite-3.8.1/autoconf/tea/configure.in b/components/external/SQLite-3.8.1/autoconf/tea/configure.in new file mode 100644 index 0000000000000000000000000000000000000000..ec9c565c6feb82c36ff0b64dbed43cd1b5d5c761 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/configure.in @@ -0,0 +1,200 @@ +#!/bin/bash -norc +dnl This file is an input file used by the GNU "autoconf" program to +dnl generate the file "configure", which is run during Tcl installation +dnl to configure the system for the local environment. +# +# RCS: @(#) $Id: configure.in,v 1.43 2005/07/26 19:17:05 mdejong Exp $ + +#----------------------------------------------------------------------- +# Sample configure.in for Tcl Extensions. The only places you should +# need to modify this file are marked by the string __CHANGE__ +#----------------------------------------------------------------------- + +#----------------------------------------------------------------------- +# __CHANGE__ +# Set your package name and version numbers here. +# +# This initializes the environment with PACKAGE_NAME and PACKAGE_VERSION +# set as provided. These will also be added as -D defs in your Makefile +# so you can encode the package version directly into the source files. +#----------------------------------------------------------------------- + +AC_INIT([sqlite], [3.7.4]) + +#-------------------------------------------------------------------- +# Call TEA_INIT as the first TEA_ macro to set up initial vars. +# This will define a ${TEA_PLATFORM} variable == "unix" or "windows" +# as well as PKG_LIB_FILE and PKG_STUB_LIB_FILE. +#-------------------------------------------------------------------- + +TEA_INIT([3.9]) + +AC_CONFIG_AUX_DIR(tclconfig) + +#-------------------------------------------------------------------- +# Load the tclConfig.sh file +#-------------------------------------------------------------------- + +TEA_PATH_TCLCONFIG +TEA_LOAD_TCLCONFIG + +#-------------------------------------------------------------------- +# Load the tkConfig.sh file if necessary (Tk extension) +#-------------------------------------------------------------------- + +#TEA_PATH_TKCONFIG +#TEA_LOAD_TKCONFIG + +#----------------------------------------------------------------------- +# Handle the --prefix=... option by defaulting to what Tcl gave. +# Must be called after TEA_LOAD_TCLCONFIG and before TEA_SETUP_COMPILER. +#----------------------------------------------------------------------- + +TEA_PREFIX + +#----------------------------------------------------------------------- +# Standard compiler checks. +# This sets up CC by using the CC env var, or looks for gcc otherwise. +# This also calls AC_PROG_CC, AC_PROG_INSTALL and a few others to create +# the basic setup necessary to compile executables. +#----------------------------------------------------------------------- + +TEA_SETUP_COMPILER + +#----------------------------------------------------------------------- +# __CHANGE__ +# Specify the C source files to compile in TEA_ADD_SOURCES, +# public headers that need to be installed in TEA_ADD_HEADERS, +# stub library C source files to compile in TEA_ADD_STUB_SOURCES, +# and runtime Tcl library files in TEA_ADD_TCL_SOURCES. +# This defines PKG(_STUB)_SOURCES, PKG(_STUB)_OBJECTS, PKG_HEADERS +# and PKG_TCL_SOURCES. +#----------------------------------------------------------------------- + +TEA_ADD_SOURCES([tclsqlite3.c]) +TEA_ADD_HEADERS([]) +TEA_ADD_INCLUDES([-I\"`\${CYGPATH} \${srcdir}/generic`\"]) +TEA_ADD_LIBS([]) +TEA_ADD_CFLAGS([-DSQLITE_ENABLE_FTS3=1]) +TEA_ADD_CFLAGS([-DSQLITE_3_SUFFIX_ONLY=1]) +TEA_ADD_CFLAGS([-DSQLITE_ENABLE_RTREE=1]) +TEA_ADD_CFLAGS([-DSQLITE_OMIT_DEPRECATED=1]) +TEA_ADD_STUB_SOURCES([]) +TEA_ADD_TCL_SOURCES([]) + +#-------------------------------------------------------------------- +# The --with-system-sqlite causes the TCL bindings to SQLite to use +# the system shared library for SQLite rather than statically linking +# against its own private copy. This is dangerous and leads to +# undersirable dependences and is not recommended. +# Patchs from rmax. +#-------------------------------------------------------------------- +AC_ARG_WITH([system-sqlite], + [AC_HELP_STRING([--with-system-sqlite], + [use a system-supplied libsqlite3 instead of the bundled one])], + [], [with_system_sqlite=no]) +if test x$with_system_sqlite != xno; then + AC_CHECK_HEADER([sqlite3.h], + [AC_CHECK_LIB([sqlite3],[sqlite3_initialize], + [AC_DEFINE(USE_SYSTEM_SQLITE) + LIBS="$LIBS -lsqlite3"])]) +fi + +#-------------------------------------------------------------------- +# __CHANGE__ +# Choose which headers you need. Extension authors should try very +# hard to only rely on the Tcl public header files. Internal headers +# contain private data structures and are subject to change without +# notice. +# This MUST be called after TEA_LOAD_TCLCONFIG / TEA_LOAD_TKCONFIG +#-------------------------------------------------------------------- + +TEA_PUBLIC_TCL_HEADERS +#TEA_PRIVATE_TCL_HEADERS + +#TEA_PUBLIC_TK_HEADERS +#TEA_PRIVATE_TK_HEADERS +#TEA_PATH_X + +#-------------------------------------------------------------------- +# Check whether --enable-threads or --disable-threads was given. +# This auto-enables if Tcl was compiled threaded. +#-------------------------------------------------------------------- + +TEA_ENABLE_THREADS +if test "${TCL_THREADS}" = "1" ; then + AC_DEFINE(SQLITE_THREADSAFE, 1, [Trigger sqlite threadsafe build]) + # Not automatically added by Tcl because its assumed Tcl links to them, + # but it may not if it isn't really a threaded build. + TEA_ADD_LIBS([$THREADS_LIBS]) +else + AC_DEFINE(SQLITE_THREADSAFE, 0, [Trigger sqlite non-threadsafe build]) +fi + +#-------------------------------------------------------------------- +# The statement below defines a collection of symbols related to +# building as a shared library instead of a static library. +#-------------------------------------------------------------------- + +TEA_ENABLE_SHARED + +#-------------------------------------------------------------------- +# This macro figures out what flags to use with the compiler/linker +# when building shared/static debug/optimized objects. This information +# can be taken from the tclConfig.sh file, but this figures it all out. +#-------------------------------------------------------------------- + +TEA_CONFIG_CFLAGS + +#-------------------------------------------------------------------- +# Set the default compiler switches based on the --enable-symbols option. +#-------------------------------------------------------------------- + +TEA_ENABLE_SYMBOLS + +#-------------------------------------------------------------------- +# Everyone should be linking against the Tcl stub library. If you +# can't for some reason, remove this definition. If you aren't using +# stubs, you also need to modify the SHLIB_LD_LIBS setting below to +# link against the non-stubbed Tcl library. Add Tk too if necessary. +#-------------------------------------------------------------------- + +AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs]) +#AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs]) + + +#-------------------------------------------------------------------- +# Redefine fdatasync as fsync on systems that lack fdatasync +#-------------------------------------------------------------------- + +AC_CHECK_FUNC(fdatasync, , AC_DEFINE(fdatasync, fsync)) + +AC_FUNC_STRERROR_R + + +#-------------------------------------------------------------------- +# This macro generates a line to use when building a library. It +# depends on values set by the TEA_ENABLE_SHARED, TEA_ENABLE_SYMBOLS, +# and TEA_LOAD_TCLCONFIG macros above. +#-------------------------------------------------------------------- + +TEA_MAKE_LIB + +#-------------------------------------------------------------------- +# Determine the name of the tclsh and/or wish executables in the +# Tcl and Tk build directories or the location they were installed +# into. These paths are used to support running test cases only, +# the Makefile should not be making use of these paths to generate +# a pkgIndex.tcl file or anything else at extension build time. +#-------------------------------------------------------------------- + +TEA_PROG_TCLSH +#TEA_PROG_WISH + +#-------------------------------------------------------------------- +# Finally, substitute all of the various values into the Makefile. +# You may alternatively have a special pkgIndex.tcl.in or other files +# which require substituting th AC variables in. Include these here. +#-------------------------------------------------------------------- + +AC_OUTPUT([Makefile pkgIndex.tcl]) diff --git a/components/external/SQLite-3.8.1/autoconf/tea/doc/sqlite3.n b/components/external/SQLite-3.8.1/autoconf/tea/doc/sqlite3.n new file mode 100644 index 0000000000000000000000000000000000000000..cee765f94c4d8e20779147dec09cb9df309a8f8a --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/doc/sqlite3.n @@ -0,0 +1,15 @@ +.TH sqlite3 n 4.1 "Tcl-Extensions" +.HS sqlite3 tcl +.BS +.SH NAME +sqlite3 \- an interface to the SQLite3 database engine +.SH SYNOPSIS +\fBsqlite3\fI command_name ?filename?\fR +.br +.SH DESCRIPTION +SQLite3 is a self-contains, zero-configuration, transactional SQL database +engine. This extension provides an easy to use interface for accessing +SQLite database files from Tcl. +.PP +For full documentation see http://www.sqlite.org/ and +in particular http://www.sqlite.org/tclsqlite.html. diff --git a/components/external/SQLite-3.8.1/autoconf/tea/license.terms b/components/external/SQLite-3.8.1/autoconf/tea/license.terms new file mode 100644 index 0000000000000000000000000000000000000000..723c4cd3c6e91a9f86ee9fe667923a316ba17d03 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/license.terms @@ -0,0 +1,6 @@ +The author disclaims copyright to this source code. In place of +a legal notice, here is a blessing: + + May you do good and not evil. + May you find forgiveness for yourself and forgive others. + May you share freely, never taking more than you give. diff --git a/components/external/SQLite-3.8.1/autoconf/tea/pkgIndex.tcl.in b/components/external/SQLite-3.8.1/autoconf/tea/pkgIndex.tcl.in new file mode 100644 index 0000000000000000000000000000000000000000..bc585f73b3007cf63086532cddc38bfe4a246236 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/pkgIndex.tcl.in @@ -0,0 +1,7 @@ +# +# Tcl package index file +# +# Note sqlite*3* init specifically +# +package ifneeded sqlite3 @PACKAGE_VERSION@ \ + [list load [file join $dir @PKG_LIB_FILE@] Sqlite3] diff --git a/components/external/SQLite-3.8.1/autoconf/tea/tclconfig/install-sh b/components/external/SQLite-3.8.1/autoconf/tea/tclconfig/install-sh new file mode 100644 index 0000000000000000000000000000000000000000..0ff4b6a08e8077bdb9374c2d1bc8bec4e1f1eea4 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/tclconfig/install-sh @@ -0,0 +1,119 @@ +#!/bin/sh + +# +# install - install a program, script, or datafile +# This comes from X11R5; it is not part of GNU. +# +# $XConsortium: install.sh,v 1.2 89/12/18 14:47:22 jim Exp $ +# +# This script is compatible with the BSD install script, but was written +# from scratch. +# + + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" + + +# put in absolute paths if you don't have them in your path; or use env. vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" + +instcmd="$mvprog" +chmodcmd="" +chowncmd="" +chgrpcmd="" +stripcmd="" +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src="" +dst="" + +while [ x"$1" != x ]; do + case $1 in + -c) instcmd="$cpprog" + shift + continue;; + + -m) chmodcmd="$chmodprog $2" + shift + shift + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + -s) stripcmd="$stripprog" + shift + continue;; + + *) if [ x"$src" = x ] + then + src=$1 + else + dst=$1 + fi + shift + continue;; + esac +done + +if [ x"$src" = x ] +then + echo "install: no input file specified" + exit 1 +fi + +if [ x"$dst" = x ] +then + echo "install: no destination specified" + exit 1 +fi + + +# If destination is a directory, append the input filename; if your system +# does not like double slashes in filenames, you may need to add some logic + +if [ -d $dst ] +then + dst="$dst"/`basename $src` +fi + +# Make a temp file name in the proper directory. + +dstdir=`dirname $dst` +dsttmp=$dstdir/#inst.$$# + +# Move or copy the file name to the temp name + +$doit $instcmd $src $dsttmp + +# and set any options; do chmod last to preserve setuid bits + +if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; fi +if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; fi +if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; fi +if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; fi + +# Now rename the file to the real destination. + +$doit $rmcmd $dst +$doit $mvcmd $dsttmp $dst + + +exit 0 diff --git a/components/external/SQLite-3.8.1/autoconf/tea/tclconfig/tcl.m4 b/components/external/SQLite-3.8.1/autoconf/tea/tclconfig/tcl.m4 new file mode 100644 index 0000000000000000000000000000000000000000..f910bc2a1f267cdad86eef4a68462ae037b0fd37 --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/tclconfig/tcl.m4 @@ -0,0 +1,3997 @@ +# tcl.m4 -- +# +# This file provides a set of autoconf macros to help TEA-enable +# a Tcl extension. +# +# Copyright (c) 1999-2000 Ajuba Solutions. +# Copyright (c) 2002-2005 ActiveState Corporation. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# RCS: @(#) $Id: tcl.m4,v 1.145 2010/08/17 00:33:40 hobbs Exp $ + +AC_PREREQ(2.57) + +dnl TEA extensions pass us the version of TEA they think they +dnl are compatible with (must be set in TEA_INIT below) +dnl TEA_VERSION="3.9" + +# Possible values for key variables defined: +# +# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem') +# TEA_PLATFORM - windows unix +# + +#------------------------------------------------------------------------ +# TEA_PATH_TCLCONFIG -- +# +# Locate the tclConfig.sh file and perform a sanity check on +# the Tcl compile flags +# +# Arguments: +# none +# +# Results: +# +# Adds the following arguments to configure: +# --with-tcl=... +# +# Defines the following vars: +# TCL_BIN_DIR Full path to the directory containing +# the tclConfig.sh file +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PATH_TCLCONFIG], [ + dnl TEA specific: Make sure we are initialized + AC_REQUIRE([TEA_INIT]) + # + # Ok, lets find the tcl configuration + # First, look for one uninstalled. + # the alternative search directory is invoked by --with-tcl + # + + if test x"${no_tcl}" = x ; then + # we reset no_tcl in case something fails here + no_tcl=true + AC_ARG_WITH(tcl, + AC_HELP_STRING([--with-tcl], + [directory containing tcl configuration (tclConfig.sh)]), + with_tclconfig="${withval}") + AC_MSG_CHECKING([for Tcl configuration]) + AC_CACHE_VAL(ac_cv_c_tclconfig,[ + + # First check to see if --with-tcl was specified. + if test x"${with_tclconfig}" != x ; then + case "${with_tclconfig}" in + */tclConfig.sh ) + if test -f "${with_tclconfig}"; then + AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself]) + with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`" + fi ;; + esac + if test -f "${with_tclconfig}/tclConfig.sh" ; then + ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`" + else + AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh]) + fi + fi + + # then check for a private Tcl installation + if test x"${ac_cv_c_tclconfig}" = x ; then + for i in \ + ../tcl \ + `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \ + ../../tcl \ + `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \ + ../../../tcl \ + `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do + if test "${TEA_PLATFORM}" = "windows" \ + -a -f "$i/win/tclConfig.sh" ; then + ac_cv_c_tclconfig="`(cd $i/win; pwd)`" + break + fi + if test -f "$i/unix/tclConfig.sh" ; then + ac_cv_c_tclconfig="`(cd $i/unix; pwd)`" + break + fi + done + fi + + # on Darwin, check in Framework installation locations + if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then + for i in `ls -d ~/Library/Frameworks 2>/dev/null` \ + `ls -d /Library/Frameworks 2>/dev/null` \ + `ls -d /Network/Library/Frameworks 2>/dev/null` \ + `ls -d /System/Library/Frameworks 2>/dev/null` \ + ; do + if test -f "$i/Tcl.framework/tclConfig.sh" ; then + ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`" + break + fi + done + fi + + # TEA specific: on Windows, check in common installation locations + if test "${TEA_PLATFORM}" = "windows" \ + -a x"${ac_cv_c_tclconfig}" = x ; then + for i in `ls -d C:/Tcl/lib 2>/dev/null` \ + `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \ + ; do + if test -f "$i/tclConfig.sh" ; then + ac_cv_c_tclconfig="`(cd $i; pwd)`" + break + fi + done + fi + + # check in a few common install locations + if test x"${ac_cv_c_tclconfig}" = x ; then + for i in `ls -d ${libdir} 2>/dev/null` \ + `ls -d ${exec_prefix}/lib 2>/dev/null` \ + `ls -d ${prefix}/lib 2>/dev/null` \ + `ls -d /usr/local/lib 2>/dev/null` \ + `ls -d /usr/contrib/lib 2>/dev/null` \ + `ls -d /usr/lib 2>/dev/null` \ + `ls -d /usr/lib64 2>/dev/null` \ + ; do + if test -f "$i/tclConfig.sh" ; then + ac_cv_c_tclconfig="`(cd $i; pwd)`" + break + fi + done + fi + + # check in a few other private locations + if test x"${ac_cv_c_tclconfig}" = x ; then + for i in \ + ${srcdir}/../tcl \ + `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do + if test "${TEA_PLATFORM}" = "windows" \ + -a -f "$i/win/tclConfig.sh" ; then + ac_cv_c_tclconfig="`(cd $i/win; pwd)`" + break + fi + if test -f "$i/unix/tclConfig.sh" ; then + ac_cv_c_tclconfig="`(cd $i/unix; pwd)`" + break + fi + done + fi + ]) + + if test x"${ac_cv_c_tclconfig}" = x ; then + TCL_BIN_DIR="# no Tcl configs found" + AC_MSG_ERROR([Can't find Tcl configuration definitions]) + else + no_tcl= + TCL_BIN_DIR="${ac_cv_c_tclconfig}" + AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh]) + fi + fi +]) + +#------------------------------------------------------------------------ +# TEA_PATH_TKCONFIG -- +# +# Locate the tkConfig.sh file +# +# Arguments: +# none +# +# Results: +# +# Adds the following arguments to configure: +# --with-tk=... +# +# Defines the following vars: +# TK_BIN_DIR Full path to the directory containing +# the tkConfig.sh file +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PATH_TKCONFIG], [ + # + # Ok, lets find the tk configuration + # First, look for one uninstalled. + # the alternative search directory is invoked by --with-tk + # + + if test x"${no_tk}" = x ; then + # we reset no_tk in case something fails here + no_tk=true + AC_ARG_WITH(tk, + AC_HELP_STRING([--with-tk], + [directory containing tk configuration (tkConfig.sh)]), + with_tkconfig="${withval}") + AC_MSG_CHECKING([for Tk configuration]) + AC_CACHE_VAL(ac_cv_c_tkconfig,[ + + # First check to see if --with-tkconfig was specified. + if test x"${with_tkconfig}" != x ; then + case "${with_tkconfig}" in + */tkConfig.sh ) + if test -f "${with_tkconfig}"; then + AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself]) + with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`" + fi ;; + esac + if test -f "${with_tkconfig}/tkConfig.sh" ; then + ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`" + else + AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh]) + fi + fi + + # then check for a private Tk library + if test x"${ac_cv_c_tkconfig}" = x ; then + for i in \ + ../tk \ + `ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \ + ../../tk \ + `ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \ + ../../../tk \ + `ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do + if test "${TEA_PLATFORM}" = "windows" \ + -a -f "$i/win/tkConfig.sh" ; then + ac_cv_c_tkconfig="`(cd $i/win; pwd)`" + break + fi + if test -f "$i/unix/tkConfig.sh" ; then + ac_cv_c_tkconfig="`(cd $i/unix; pwd)`" + break + fi + done + fi + + # on Darwin, check in Framework installation locations + if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then + for i in `ls -d ~/Library/Frameworks 2>/dev/null` \ + `ls -d /Library/Frameworks 2>/dev/null` \ + `ls -d /Network/Library/Frameworks 2>/dev/null` \ + `ls -d /System/Library/Frameworks 2>/dev/null` \ + ; do + if test -f "$i/Tk.framework/tkConfig.sh" ; then + ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`" + break + fi + done + fi + + # check in a few common install locations + if test x"${ac_cv_c_tkconfig}" = x ; then + for i in `ls -d ${libdir} 2>/dev/null` \ + `ls -d ${exec_prefix}/lib 2>/dev/null` \ + `ls -d ${prefix}/lib 2>/dev/null` \ + `ls -d /usr/local/lib 2>/dev/null` \ + `ls -d /usr/contrib/lib 2>/dev/null` \ + `ls -d /usr/lib 2>/dev/null` \ + `ls -d /usr/lib64 2>/dev/null` \ + ; do + if test -f "$i/tkConfig.sh" ; then + ac_cv_c_tkconfig="`(cd $i; pwd)`" + break + fi + done + fi + + # TEA specific: on Windows, check in common installation locations + if test "${TEA_PLATFORM}" = "windows" \ + -a x"${ac_cv_c_tkconfig}" = x ; then + for i in `ls -d C:/Tcl/lib 2>/dev/null` \ + `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \ + ; do + if test -f "$i/tkConfig.sh" ; then + ac_cv_c_tkconfig="`(cd $i; pwd)`" + break + fi + done + fi + + # check in a few other private locations + if test x"${ac_cv_c_tkconfig}" = x ; then + for i in \ + ${srcdir}/../tk \ + `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do + if test "${TEA_PLATFORM}" = "windows" \ + -a -f "$i/win/tkConfig.sh" ; then + ac_cv_c_tkconfig="`(cd $i/win; pwd)`" + break + fi + if test -f "$i/unix/tkConfig.sh" ; then + ac_cv_c_tkconfig="`(cd $i/unix; pwd)`" + break + fi + done + fi + ]) + + if test x"${ac_cv_c_tkconfig}" = x ; then + TK_BIN_DIR="# no Tk configs found" + AC_MSG_ERROR([Can't find Tk configuration definitions]) + else + no_tk= + TK_BIN_DIR="${ac_cv_c_tkconfig}" + AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh]) + fi + fi +]) + +#------------------------------------------------------------------------ +# TEA_LOAD_TCLCONFIG -- +# +# Load the tclConfig.sh file +# +# Arguments: +# +# Requires the following vars to be set: +# TCL_BIN_DIR +# +# Results: +# +# Subst the following vars: +# TCL_BIN_DIR +# TCL_SRC_DIR +# TCL_LIB_FILE +# +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_LOAD_TCLCONFIG], [ + AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh]) + + if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then + AC_MSG_RESULT([loading]) + . "${TCL_BIN_DIR}/tclConfig.sh" + else + AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh]) + fi + + # eval is required to do the TCL_DBGX substitution + eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\"" + eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\"" + + # If the TCL_BIN_DIR is the build directory (not the install directory), + # then set the common variable name to the value of the build variables. + # For example, the variable TCL_LIB_SPEC will be set to the value + # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC + # instead of TCL_BUILD_LIB_SPEC since it will work with both an + # installed and uninstalled version of Tcl. + if test -f "${TCL_BIN_DIR}/Makefile" ; then + TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}" + TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}" + TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}" + elif test "`uname -s`" = "Darwin"; then + # If Tcl was built as a framework, attempt to use the libraries + # from the framework at the given location so that linking works + # against Tcl.framework installed in an arbitrary location. + case ${TCL_DEFS} in + *TCL_FRAMEWORK*) + if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then + for i in "`cd "${TCL_BIN_DIR}"; pwd`" \ + "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do + if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then + TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}" + break + fi + done + fi + if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then + TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}" | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}" + TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}" + fi + ;; + esac + fi + + # eval is required to do the TCL_DBGX substitution + eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\"" + eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\"" + eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\"" + eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\"" + + AC_SUBST(TCL_VERSION) + AC_SUBST(TCL_PATCH_LEVEL) + AC_SUBST(TCL_BIN_DIR) + AC_SUBST(TCL_SRC_DIR) + + AC_SUBST(TCL_LIB_FILE) + AC_SUBST(TCL_LIB_FLAG) + AC_SUBST(TCL_LIB_SPEC) + + AC_SUBST(TCL_STUB_LIB_FILE) + AC_SUBST(TCL_STUB_LIB_FLAG) + AC_SUBST(TCL_STUB_LIB_SPEC) + + case "`uname -s`" in + *CYGWIN_*) + AC_MSG_CHECKING([for cygwin variant]) + case ${TCL_EXTRA_CFLAGS} in + *-mwin32*|*-mno-cygwin*) + TEA_PLATFORM="windows" + CFLAGS="$CFLAGS -mwin32" + AC_MSG_RESULT([win32]) + ;; + *) + TEA_PLATFORM="unix" + AC_MSG_RESULT([unix]) + ;; + esac + EXEEXT=".exe" + ;; + *) + ;; + esac + + # Do this here as we have fully defined TEA_PLATFORM now + if test "${TEA_PLATFORM}" = "windows" ; then + # The BUILD_$pkg is to define the correct extern storage class + # handling when making this package + AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}) + CLEANFILES="$CLEANFILES *.lib *.dll *.pdb" + fi + + # TEA specific: + AC_SUBST(CLEANFILES) + AC_SUBST(TCL_LIBS) + AC_SUBST(TCL_DEFS) + AC_SUBST(TCL_EXTRA_CFLAGS) + AC_SUBST(TCL_LD_FLAGS) + AC_SUBST(TCL_SHLIB_LD_LIBS) +]) + +#------------------------------------------------------------------------ +# TEA_LOAD_TKCONFIG -- +# +# Load the tkConfig.sh file +# +# Arguments: +# +# Requires the following vars to be set: +# TK_BIN_DIR +# +# Results: +# +# Sets the following vars that should be in tkConfig.sh: +# TK_BIN_DIR +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_LOAD_TKCONFIG], [ + AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh]) + + if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then + AC_MSG_RESULT([loading]) + . "${TK_BIN_DIR}/tkConfig.sh" + else + AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh]) + fi + + # eval is required to do the TK_DBGX substitution + eval "TK_LIB_FILE=\"${TK_LIB_FILE}\"" + eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\"" + + # If the TK_BIN_DIR is the build directory (not the install directory), + # then set the common variable name to the value of the build variables. + # For example, the variable TK_LIB_SPEC will be set to the value + # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC + # instead of TK_BUILD_LIB_SPEC since it will work with both an + # installed and uninstalled version of Tcl. + if test -f "${TK_BIN_DIR}/Makefile" ; then + TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}" + TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}" + TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}" + elif test "`uname -s`" = "Darwin"; then + # If Tk was built as a framework, attempt to use the libraries + # from the framework at the given location so that linking works + # against Tk.framework installed in an arbitrary location. + case ${TK_DEFS} in + *TK_FRAMEWORK*) + if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then + for i in "`cd "${TK_BIN_DIR}"; pwd`" \ + "`cd "${TK_BIN_DIR}"/../..; pwd`"; do + if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then + TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}" + break + fi + done + fi + if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then + TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}" | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}" + TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}" + fi + ;; + esac + fi + + # eval is required to do the TK_DBGX substitution + eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\"" + eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\"" + eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\"" + eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\"" + + # TEA specific: Ensure windowingsystem is defined + if test "${TEA_PLATFORM}" = "unix" ; then + case ${TK_DEFS} in + *MAC_OSX_TK*) + AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?]) + TEA_WINDOWINGSYSTEM="aqua" + ;; + *) + TEA_WINDOWINGSYSTEM="x11" + ;; + esac + elif test "${TEA_PLATFORM}" = "windows" ; then + TEA_WINDOWINGSYSTEM="win32" + fi + + AC_SUBST(TK_VERSION) + AC_SUBST(TK_BIN_DIR) + AC_SUBST(TK_SRC_DIR) + + AC_SUBST(TK_LIB_FILE) + AC_SUBST(TK_LIB_FLAG) + AC_SUBST(TK_LIB_SPEC) + + AC_SUBST(TK_STUB_LIB_FILE) + AC_SUBST(TK_STUB_LIB_FLAG) + AC_SUBST(TK_STUB_LIB_SPEC) + + # TEA specific: + AC_SUBST(TK_LIBS) + AC_SUBST(TK_XINCLUDES) +]) + +#------------------------------------------------------------------------ +# TEA_PROG_TCLSH +# Determine the fully qualified path name of the tclsh executable +# in the Tcl build directory or the tclsh installed in a bin +# directory. This macro will correctly determine the name +# of the tclsh executable even if tclsh has not yet been +# built in the build directory. The tclsh found is always +# associated with a tclConfig.sh file. This tclsh should be used +# only for running extension test cases. It should never be +# or generation of files (like pkgIndex.tcl) at build time. +# +# Arguments +# none +# +# Results +# Subst's the following values: +# TCLSH_PROG +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PROG_TCLSH], [ + AC_MSG_CHECKING([for tclsh]) + if test -f "${TCL_BIN_DIR}/Makefile" ; then + # tclConfig.sh is in Tcl build directory + if test "${TEA_PLATFORM}" = "windows"; then + TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" + else + TCLSH_PROG="${TCL_BIN_DIR}/tclsh" + fi + else + # tclConfig.sh is in install location + if test "${TEA_PLATFORM}" = "windows"; then + TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" + else + TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}" + fi + list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \ + `ls -d ${TCL_BIN_DIR}/.. 2>/dev/null` \ + `ls -d ${TCL_PREFIX}/bin 2>/dev/null`" + for i in $list ; do + if test -f "$i/${TCLSH_PROG}" ; then + REAL_TCL_BIN_DIR="`cd "$i"; pwd`/" + break + fi + done + TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}" + fi + AC_MSG_RESULT([${TCLSH_PROG}]) + AC_SUBST(TCLSH_PROG) +]) + +#------------------------------------------------------------------------ +# TEA_PROG_WISH +# Determine the fully qualified path name of the wish executable +# in the Tk build directory or the wish installed in a bin +# directory. This macro will correctly determine the name +# of the wish executable even if wish has not yet been +# built in the build directory. The wish found is always +# associated with a tkConfig.sh file. This wish should be used +# only for running extension test cases. It should never be +# or generation of files (like pkgIndex.tcl) at build time. +# +# Arguments +# none +# +# Results +# Subst's the following values: +# WISH_PROG +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PROG_WISH], [ + AC_MSG_CHECKING([for wish]) + if test -f "${TK_BIN_DIR}/Makefile" ; then + # tkConfig.sh is in Tk build directory + if test "${TEA_PLATFORM}" = "windows"; then + WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" + else + WISH_PROG="${TK_BIN_DIR}/wish" + fi + else + # tkConfig.sh is in install location + if test "${TEA_PLATFORM}" = "windows"; then + WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" + else + WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}" + fi + list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \ + `ls -d ${TK_BIN_DIR}/.. 2>/dev/null` \ + `ls -d ${TK_PREFIX}/bin 2>/dev/null`" + for i in $list ; do + if test -f "$i/${WISH_PROG}" ; then + REAL_TK_BIN_DIR="`cd "$i"; pwd`/" + break + fi + done + WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}" + fi + AC_MSG_RESULT([${WISH_PROG}]) + AC_SUBST(WISH_PROG) +]) + +#------------------------------------------------------------------------ +# TEA_ENABLE_SHARED -- +# +# Allows the building of shared libraries +# +# Arguments: +# none +# +# Results: +# +# Adds the following arguments to configure: +# --enable-shared=yes|no +# +# Defines the following vars: +# STATIC_BUILD Used for building import/export libraries +# on Windows. +# +# Sets the following vars: +# SHARED_BUILD Value of 1 or 0 +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_ENABLE_SHARED], [ + AC_MSG_CHECKING([how to build libraries]) + AC_ARG_ENABLE(shared, + AC_HELP_STRING([--enable-shared], + [build and link with shared libraries (default: on)]), + [tcl_ok=$enableval], [tcl_ok=yes]) + + if test "${enable_shared+set}" = set; then + enableval="$enable_shared" + tcl_ok=$enableval + else + tcl_ok=yes + fi + + if test "$tcl_ok" = "yes" ; then + AC_MSG_RESULT([shared]) + SHARED_BUILD=1 + else + AC_MSG_RESULT([static]) + SHARED_BUILD=0 + AC_DEFINE(STATIC_BUILD, 1, [Is this a static build?]) + fi + AC_SUBST(SHARED_BUILD) +]) + +#------------------------------------------------------------------------ +# TEA_ENABLE_THREADS -- +# +# Specify if thread support should be enabled. If "yes" is specified +# as an arg (optional), threads are enabled by default, "no" means +# threads are disabled. "yes" is the default. +# +# TCL_THREADS is checked so that if you are compiling an extension +# against a threaded core, your extension must be compiled threaded +# as well. +# +# Note that it is legal to have a thread enabled extension run in a +# threaded or non-threaded Tcl core, but a non-threaded extension may +# only run in a non-threaded Tcl core. +# +# Arguments: +# none +# +# Results: +# +# Adds the following arguments to configure: +# --enable-threads +# +# Sets the following vars: +# THREADS_LIBS Thread library(s) +# +# Defines the following vars: +# TCL_THREADS +# _REENTRANT +# _THREAD_SAFE +# +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_ENABLE_THREADS], [ + AC_ARG_ENABLE(threads, + AC_HELP_STRING([--enable-threads], + [build with threads]), + [tcl_ok=$enableval], [tcl_ok=yes]) + + if test "${enable_threads+set}" = set; then + enableval="$enable_threads" + tcl_ok=$enableval + else + tcl_ok=yes + fi + + if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then + TCL_THREADS=1 + + if test "${TEA_PLATFORM}" != "windows" ; then + # We are always OK on Windows, so check what this platform wants: + + # USE_THREAD_ALLOC tells us to try the special thread-based + # allocator that significantly reduces lock contention + AC_DEFINE(USE_THREAD_ALLOC, 1, + [Do we want to use the threaded memory allocator?]) + AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?]) + if test "`uname -s`" = "SunOS" ; then + AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1, + [Do we really want to follow the standard? Yes we do!]) + fi + AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?]) + AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no) + if test "$tcl_ok" = "no"; then + # Check a little harder for __pthread_mutex_init in the same + # library, as some systems hide it there until pthread.h is + # defined. We could alternatively do an AC_TRY_COMPILE with + # pthread.h, but that will work with libpthread really doesn't + # exist, like AIX 4.2. [Bug: 4359] + AC_CHECK_LIB(pthread, __pthread_mutex_init, + tcl_ok=yes, tcl_ok=no) + fi + + if test "$tcl_ok" = "yes"; then + # The space is needed + THREADS_LIBS=" -lpthread" + else + AC_CHECK_LIB(pthreads, pthread_mutex_init, + tcl_ok=yes, tcl_ok=no) + if test "$tcl_ok" = "yes"; then + # The space is needed + THREADS_LIBS=" -lpthreads" + else + AC_CHECK_LIB(c, pthread_mutex_init, + tcl_ok=yes, tcl_ok=no) + if test "$tcl_ok" = "no"; then + AC_CHECK_LIB(c_r, pthread_mutex_init, + tcl_ok=yes, tcl_ok=no) + if test "$tcl_ok" = "yes"; then + # The space is needed + THREADS_LIBS=" -pthread" + else + TCL_THREADS=0 + AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled]) + fi + fi + fi + fi + fi + else + TCL_THREADS=0 + fi + # Do checking message here to not mess up interleaved configure output + AC_MSG_CHECKING([for building with threads]) + if test "${TCL_THREADS}" = 1; then + AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?]) + AC_MSG_RESULT([yes (default)]) + else + AC_MSG_RESULT([no]) + fi + # TCL_THREADS sanity checking. See if our request for building with + # threads is the same as the way Tcl was built. If not, warn the user. + case ${TCL_DEFS} in + *THREADS=1*) + if test "${TCL_THREADS}" = "0"; then + AC_MSG_WARN([ + Building ${PACKAGE_NAME} without threads enabled, but building against Tcl + that IS thread-enabled. It is recommended to use --enable-threads.]) + fi + ;; + *) + if test "${TCL_THREADS}" = "1"; then + AC_MSG_WARN([ + --enable-threads requested, but building against a Tcl that is NOT + thread-enabled. This is an OK configuration that will also run in + a thread-enabled core.]) + fi + ;; + esac + AC_SUBST(TCL_THREADS) +]) + +#------------------------------------------------------------------------ +# TEA_ENABLE_SYMBOLS -- +# +# Specify if debugging symbols should be used. +# Memory (TCL_MEM_DEBUG) debugging can also be enabled. +# +# Arguments: +# none +# +# TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives +# the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted. +# Requires the following vars to be set in the Makefile: +# CFLAGS_DEFAULT +# LDFLAGS_DEFAULT +# +# Results: +# +# Adds the following arguments to configure: +# --enable-symbols +# +# Defines the following vars: +# CFLAGS_DEFAULT Sets to $(CFLAGS_DEBUG) if true +# Sets to $(CFLAGS_OPTIMIZE) if false +# LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true +# Sets to $(LDFLAGS_OPTIMIZE) if false +# DBGX Formerly used as debug library extension; +# always blank now. +# +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_ENABLE_SYMBOLS], [ + dnl TEA specific: Make sure we are initialized + AC_REQUIRE([TEA_CONFIG_CFLAGS]) + AC_MSG_CHECKING([for build with symbols]) + AC_ARG_ENABLE(symbols, + AC_HELP_STRING([--enable-symbols], + [build with debugging symbols (default: off)]), + [tcl_ok=$enableval], [tcl_ok=no]) + DBGX="" + if test "$tcl_ok" = "no"; then + CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE}" + LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}" + AC_MSG_RESULT([no]) + else + CFLAGS_DEFAULT="${CFLAGS_DEBUG}" + LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}" + if test "$tcl_ok" = "yes"; then + AC_MSG_RESULT([yes (standard debugging)]) + fi + fi + # TEA specific: + if test "${TEA_PLATFORM}" != "windows" ; then + LDFLAGS_DEFAULT="${LDFLAGS}" + fi + AC_SUBST(CFLAGS_DEFAULT) + AC_SUBST(LDFLAGS_DEFAULT) + AC_SUBST(TCL_DBGX) + + if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then + AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?]) + fi + + if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then + if test "$tcl_ok" = "all"; then + AC_MSG_RESULT([enabled symbols mem debugging]) + else + AC_MSG_RESULT([enabled $tcl_ok debugging]) + fi + fi +]) + +#------------------------------------------------------------------------ +# TEA_ENABLE_LANGINFO -- +# +# Allows use of modern nl_langinfo check for better l10n. +# This is only relevant for Unix. +# +# Arguments: +# none +# +# Results: +# +# Adds the following arguments to configure: +# --enable-langinfo=yes|no (default is yes) +# +# Defines the following vars: +# HAVE_LANGINFO Triggers use of nl_langinfo if defined. +# +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_ENABLE_LANGINFO], [ + AC_ARG_ENABLE(langinfo, + AC_HELP_STRING([--enable-langinfo], + [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]), + [langinfo_ok=$enableval], [langinfo_ok=yes]) + + HAVE_LANGINFO=0 + if test "$langinfo_ok" = "yes"; then + AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no]) + fi + AC_MSG_CHECKING([whether to use nl_langinfo]) + if test "$langinfo_ok" = "yes"; then + AC_CACHE_VAL(tcl_cv_langinfo_h, [ + AC_TRY_COMPILE([#include ], [nl_langinfo(CODESET);], + [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])]) + AC_MSG_RESULT([$tcl_cv_langinfo_h]) + if test $tcl_cv_langinfo_h = yes; then + AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?]) + fi + else + AC_MSG_RESULT([$langinfo_ok]) + fi +]) + +#-------------------------------------------------------------------- +# TEA_CONFIG_SYSTEM +# +# Determine what the system is (some things cannot be easily checked +# on a feature-driven basis, alas). This can usually be done via the +# "uname" command. +# +# Arguments: +# none +# +# Results: +# Defines the following var: +# +# system - System/platform/version identification code. +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_CONFIG_SYSTEM], [ + AC_CACHE_CHECK([system version], tcl_cv_sys_version, [ + # TEA specific: + if test "${TEA_PLATFORM}" = "windows" ; then + tcl_cv_sys_version=windows + else + tcl_cv_sys_version=`uname -s`-`uname -r` + if test "$?" -ne 0 ; then + AC_MSG_WARN([can't find uname command]) + tcl_cv_sys_version=unknown + else + if test "`uname -s`" = "AIX" ; then + tcl_cv_sys_version=AIX-`uname -v`.`uname -r` + fi + fi + fi + ]) + system=$tcl_cv_sys_version +]) + +#-------------------------------------------------------------------- +# TEA_CONFIG_CFLAGS +# +# Try to determine the proper flags to pass to the compiler +# for building shared libraries and other such nonsense. +# +# Arguments: +# none +# +# Results: +# +# Defines and substitutes the following vars: +# +# DL_OBJS, DL_LIBS - removed for TEA, only needed by core. +# LDFLAGS - Flags to pass to the compiler when linking object +# files into an executable application binary such +# as tclsh. +# LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib", +# that tell the run-time dynamic linker where to look +# for shared libraries such as libtcl.so. Depends on +# the variable LIB_RUNTIME_DIR in the Makefile. Could +# be the same as CC_SEARCH_FLAGS if ${CC} is used to link. +# CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib", +# that tell the run-time dynamic linker where to look +# for shared libraries such as libtcl.so. Depends on +# the variable LIB_RUNTIME_DIR in the Makefile. +# SHLIB_CFLAGS - Flags to pass to cc when compiling the components +# of a shared library (may request position-independent +# code, among other things). +# SHLIB_LD - Base command to use for combining object files +# into a shared library. +# SHLIB_LD_LIBS - Dependent libraries for the linker to scan when +# creating shared libraries. This symbol typically +# goes at the end of the "ld" commands that build +# shared libraries. The value of the symbol defaults to +# "${LIBS}" if all of the dependent libraries should +# be specified when creating a shared library. If +# dependent libraries should not be specified (as on +# SunOS 4.x, where they cause the link to fail, or in +# general if Tcl and Tk aren't themselves shared +# libraries), then this symbol has an empty string +# as its value. +# SHLIB_SUFFIX - Suffix to use for the names of dynamically loadable +# extensions. An empty string means we don't know how +# to use shared libraries on this platform. +# LIB_SUFFIX - Specifies everything that comes after the "libfoo" +# in a static or shared library name, using the $VERSION variable +# to put the version in the right place. This is used +# by platforms that need non-standard library names. +# Examples: ${VERSION}.so.1.1 on NetBSD, since it needs +# to have a version after the .so, and ${VERSION}.a +# on AIX, since a shared library needs to have +# a .a extension whereas shared objects for loadable +# extensions have a .so extension. Defaults to +# ${VERSION}${SHLIB_SUFFIX}. +# CFLAGS_DEBUG - +# Flags used when running the compiler in debug mode +# CFLAGS_OPTIMIZE - +# Flags used when running the compiler in optimize mode +# CFLAGS - Additional CFLAGS added as necessary (usually 64-bit) +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_CONFIG_CFLAGS], [ + dnl TEA specific: Make sure we are initialized + AC_REQUIRE([TEA_INIT]) + + # Step 0.a: Enable 64 bit support? + + AC_MSG_CHECKING([if 64bit support is requested]) + AC_ARG_ENABLE(64bit, + AC_HELP_STRING([--enable-64bit], + [enable 64bit support (default: off)]), + [do64bit=$enableval], [do64bit=no]) + AC_MSG_RESULT([$do64bit]) + + # Step 0.b: Enable Solaris 64 bit VIS support? + + AC_MSG_CHECKING([if 64bit Sparc VIS support is requested]) + AC_ARG_ENABLE(64bit-vis, + AC_HELP_STRING([--enable-64bit-vis], + [enable 64bit Sparc VIS support (default: off)]), + [do64bitVIS=$enableval], [do64bitVIS=no]) + AC_MSG_RESULT([$do64bitVIS]) + # Force 64bit on with VIS + AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes]) + + # Step 0.c: Check if visibility support is available. Do this here so + # that platform specific alternatives can be used below if this fails. + + AC_CACHE_CHECK([if compiler supports visibility "hidden"], + tcl_cv_cc_visibility_hidden, [ + hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror" + AC_TRY_LINK([ + extern __attribute__((__visibility__("hidden"))) void f(void); + void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes, + tcl_cv_cc_visibility_hidden=no) + CFLAGS=$hold_cflags]) + AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [ + AC_DEFINE(MODULE_SCOPE, + [extern __attribute__((__visibility__("hidden")))], + [Compiler support for module scope symbols]) + ]) + + # Step 0.d: Disable -rpath support? + + AC_MSG_CHECKING([if rpath support is requested]) + AC_ARG_ENABLE(rpath, + AC_HELP_STRING([--disable-rpath], + [disable rpath support (default: on)]), + [doRpath=$enableval], [doRpath=yes]) + AC_MSG_RESULT([$doRpath]) + + # TEA specific: Cross-compiling options for Windows/CE builds? + + AS_IF([test "${TEA_PLATFORM}" = windows], [ + AC_MSG_CHECKING([if Windows/CE build is requested]) + AC_ARG_ENABLE(wince, + AC_HELP_STRING([--enable-wince], + [enable Win/CE support (where applicable)]), + [doWince=$enableval], [doWince=no]) + AC_MSG_RESULT([$doWince]) + ]) + + # Set the variable "system" to hold the name and version number + # for the system. + + TEA_CONFIG_SYSTEM + + # Require ranlib early so we can override it in special cases below. + + AC_REQUIRE([AC_PROG_RANLIB]) + + # Set configuration options based on system name and version. + # This is similar to Tcl's unix/tcl.m4 except that we've added a + # "windows" case and removed some core-only vars. + + do64bit_ok=no + # default to '{$LIBS}' and set to "" on per-platform necessary basis + SHLIB_LD_LIBS='${LIBS}' + # When ld needs options to work in 64-bit mode, put them in + # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load] + # is disabled by the user. [Bug 1016796] + LDFLAGS_ARCH="" + UNSHARED_LIB_SUFFIX="" + # TEA specific: use PACKAGE_VERSION instead of VERSION + TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`' + ECHO_VERSION='`echo ${PACKAGE_VERSION}`' + TCL_LIB_VERSIONS_OK=ok + CFLAGS_DEBUG=-g + CFLAGS_OPTIMIZE=-O + AS_IF([test "$GCC" = yes], [ + # TEA specific: + CFLAGS_OPTIMIZE=-O2 + CFLAGS_WARNING="-Wall" + ], [CFLAGS_WARNING=""]) +dnl FIXME: Replace AC_CHECK_PROG with AC_CHECK_TOOL once cross compiling is fixed. +dnl AC_CHECK_TOOL(AR, ar) + AC_CHECK_PROG(AR, ar, ar) + STLIB_LD='${AR} cr' + LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH" + AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION="1.0"]) + case $system in + # TEA specific: + windows) + # This is a 2-stage check to make sure we have the 64-bit SDK + # We have to know where the SDK is installed. + # This magic is based on MS Platform SDK for Win2003 SP1 - hobbs + # MACHINE is IX86 for LINK, but this is used by the manifest, + # which requires x86|amd64|ia64. + MACHINE="X86" + if test "$do64bit" != "no" ; then + if test "x${MSSDK}x" = "xx" ; then + MSSDK="C:/Progra~1/Microsoft Platform SDK" + fi + MSSDK=`echo "$MSSDK" | sed -e 's!\\\!/!g'` + PATH64="" + case "$do64bit" in + amd64|x64|yes) + MACHINE="AMD64" ; # default to AMD64 64-bit build + PATH64="${MSSDK}/Bin/Win64/x86/AMD64" + ;; + ia64) + MACHINE="IA64" + PATH64="${MSSDK}/Bin/Win64" + ;; + esac + if test ! -d "${PATH64}" ; then + AC_MSG_WARN([Could not find 64-bit $MACHINE SDK to enable 64bit mode]) + AC_MSG_WARN([Ensure latest Platform SDK is installed]) + do64bit="no" + else + AC_MSG_RESULT([ Using 64-bit $MACHINE mode]) + do64bit_ok="yes" + fi + fi + + if test "$doWince" != "no" ; then + if test "$do64bit" != "no" ; then + AC_MSG_ERROR([Windows/CE and 64-bit builds incompatible]) + fi + if test "$GCC" = "yes" ; then + AC_MSG_ERROR([Windows/CE and GCC builds incompatible]) + fi + TEA_PATH_CELIB + # Set defaults for common evc4/PPC2003 setup + # Currently Tcl requires 300+, possibly 420+ for sockets + CEVERSION=420; # could be 211 300 301 400 420 ... + TARGETCPU=ARMV4; # could be ARMV4 ARM MIPS SH3 X86 ... + ARCH=ARM; # could be ARM MIPS X86EM ... + PLATFORM="Pocket PC 2003"; # or "Pocket PC 2002" + if test "$doWince" != "yes"; then + # If !yes then the user specified something + # Reset ARCH to allow user to skip specifying it + ARCH= + eval `echo $doWince | awk -F, '{ \ + if (length([$]1)) { printf "CEVERSION=\"%s\"\n", [$]1; \ + if ([$]1 < 400) { printf "PLATFORM=\"Pocket PC 2002\"\n" } }; \ + if (length([$]2)) { printf "TARGETCPU=\"%s\"\n", toupper([$]2) }; \ + if (length([$]3)) { printf "ARCH=\"%s\"\n", toupper([$]3) }; \ + if (length([$]4)) { printf "PLATFORM=\"%s\"\n", [$]4 }; \ + }'` + if test "x${ARCH}" = "x" ; then + ARCH=$TARGETCPU; + fi + fi + OSVERSION=WCE$CEVERSION; + if test "x${WCEROOT}" = "x" ; then + WCEROOT="C:/Program Files/Microsoft eMbedded C++ 4.0" + if test ! -d "${WCEROOT}" ; then + WCEROOT="C:/Program Files/Microsoft eMbedded Tools" + fi + fi + if test "x${SDKROOT}" = "x" ; then + SDKROOT="C:/Program Files/Windows CE Tools" + if test ! -d "${SDKROOT}" ; then + SDKROOT="C:/Windows CE Tools" + fi + fi + WCEROOT=`echo "$WCEROOT" | sed -e 's!\\\!/!g'` + SDKROOT=`echo "$SDKROOT" | sed -e 's!\\\!/!g'` + if test ! -d "${SDKROOT}/${OSVERSION}/${PLATFORM}/Lib/${TARGETCPU}" \ + -o ! -d "${WCEROOT}/EVC/${OSVERSION}/bin"; then + AC_MSG_ERROR([could not find PocketPC SDK or target compiler to enable WinCE mode [$CEVERSION,$TARGETCPU,$ARCH,$PLATFORM]]) + doWince="no" + else + # We could PATH_NOSPACE these, but that's not important, + # as long as we quote them when used. + CEINCLUDE="${SDKROOT}/${OSVERSION}/${PLATFORM}/include" + if test -d "${CEINCLUDE}/${TARGETCPU}" ; then + CEINCLUDE="${CEINCLUDE}/${TARGETCPU}" + fi + CELIBPATH="${SDKROOT}/${OSVERSION}/${PLATFORM}/Lib/${TARGETCPU}" + fi + fi + + if test "$GCC" != "yes" ; then + if test "${SHARED_BUILD}" = "0" ; then + runtime=-MT + else + runtime=-MD + fi + + if test "$do64bit" != "no" ; then + # All this magic is necessary for the Win64 SDK RC1 - hobbs + CC="\"${PATH64}/cl.exe\"" + CFLAGS="${CFLAGS} -I\"${MSSDK}/Include\" -I\"${MSSDK}/Include/crt\" -I\"${MSSDK}/Include/crt/sys\"" + RC="\"${MSSDK}/bin/rc.exe\"" + lflags="-nologo -MACHINE:${MACHINE} -LIBPATH:\"${MSSDK}/Lib/${MACHINE}\"" + LINKBIN="\"${PATH64}/link.exe\"" + CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d" + CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}" + # Avoid 'unresolved external symbol __security_cookie' + # errors, c.f. http://support.microsoft.com/?id=894573 + TEA_ADD_LIBS([bufferoverflowU.lib]) + elif test "$doWince" != "no" ; then + CEBINROOT="${WCEROOT}/EVC/${OSVERSION}/bin" + if test "${TARGETCPU}" = "X86"; then + CC="\"${CEBINROOT}/cl.exe\"" + else + CC="\"${CEBINROOT}/cl${ARCH}.exe\"" + fi + CFLAGS="$CFLAGS -I\"${CELIB_DIR}/inc\" -I\"${CEINCLUDE}\"" + RC="\"${WCEROOT}/Common/EVC/bin/rc.exe\"" + arch=`echo ${ARCH} | awk '{print tolower([$]0)}'` + defs="${ARCH} _${ARCH}_ ${arch} PALM_SIZE _MT _WINDOWS" + if test "${SHARED_BUILD}" = "1" ; then + # Static CE builds require static celib as well + defs="${defs} _DLL" + fi + for i in $defs ; do + AC_DEFINE_UNQUOTED($i, 1, [WinCE def ]$i) + done + AC_DEFINE_UNQUOTED(_WIN32_WCE, $CEVERSION, [_WIN32_WCE version]) + AC_DEFINE_UNQUOTED(UNDER_CE, $CEVERSION, [UNDER_CE version]) + CFLAGS_DEBUG="-nologo -Zi -Od" + CFLAGS_OPTIMIZE="-nologo -Ox" + lversion=`echo ${CEVERSION} | sed -e 's/\(.\)\(..\)/\1\.\2/'` + lflags="-MACHINE:${ARCH} -LIBPATH:\"${CELIBPATH}\" -subsystem:windowsce,${lversion} -nologo" + LINKBIN="\"${CEBINROOT}/link.exe\"" + AC_SUBST(CELIB_DIR) + else + RC="rc" + lflags="-nologo" + LINKBIN="link" + CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d" + CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}" + fi + fi + + if test "$GCC" = "yes"; then + # mingw gcc mode + RC="windres" + CFLAGS_DEBUG="-g" + CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer" + SHLIB_LD="$CC -shared" + UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a' + LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}" + LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}" + else + SHLIB_LD="${LINKBIN} -dll ${lflags}" + # link -lib only works when -lib is the first arg + STLIB_LD="${LINKBIN} -lib ${lflags}" + UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib' + PATHTYPE=-w + # For information on what debugtype is most useful, see: + # http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp + # and also + # http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx + # This essentially turns it all on. + LDFLAGS_DEBUG="-debug -debugtype:cv" + LDFLAGS_OPTIMIZE="-release" + if test "$doWince" != "no" ; then + LDFLAGS_CONSOLE="-link ${lflags}" + LDFLAGS_WINDOW=${LDFLAGS_CONSOLE} + else + LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}" + LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}" + fi + fi + + SHLIB_SUFFIX=".dll" + SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll' + + TCL_LIB_VERSIONS_OK=nodots + ;; + AIX-*) + AS_IF([test "${TCL_THREADS}" = "1" -a "$GCC" != "yes"], [ + # AIX requires the _r compiler when gcc isn't being used + case "${CC}" in + *_r|*_r\ *) + # ok ... + ;; + *) + # Make sure only first arg gets _r + CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'` + ;; + esac + AC_MSG_RESULT([Using $CC for compiling with threads]) + ]) + LIBS="$LIBS -lc" + SHLIB_CFLAGS="" + SHLIB_SUFFIX=".so" + + LD_LIBRARY_PATH_VAR="LIBPATH" + + # Check to enable 64-bit flags for compiler/linker + AS_IF([test "$do64bit" = yes], [ + AS_IF([test "$GCC" = yes], [ + AC_MSG_WARN([64bit mode not supported with GCC on $system]) + ], [ + do64bit_ok=yes + CFLAGS="$CFLAGS -q64" + LDFLAGS_ARCH="-q64" + RANLIB="${RANLIB} -X64" + AR="${AR} -X64" + SHLIB_LD_FLAGS="-b64" + ]) + ]) + + AS_IF([test "`uname -m`" = ia64], [ + # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC + SHLIB_LD="/usr/ccs/bin/ld -G -z text" + AS_IF([test "$GCC" = yes], [ + CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}' + ], [ + CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}' + ]) + LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}' + ], [ + AS_IF([test "$GCC" = yes], [ + SHLIB_LD='${CC} -shared -Wl,-bexpall' + ], [ + SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry" + LDFLAGS="$LDFLAGS -brtl" + ]) + SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}" + CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS} + ]) + ;; + BeOS*) + SHLIB_CFLAGS="-fPIC" + SHLIB_LD='${CC} -nostart' + SHLIB_SUFFIX=".so" + + #----------------------------------------------------------- + # Check for inet_ntoa in -lbind, for BeOS (which also needs + # -lsocket, even if the network functions are in -lnet which + # is always linked to, for compatibility. + #----------------------------------------------------------- + AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"]) + ;; + BSD/OS-4.*) + SHLIB_CFLAGS="-export-dynamic -fPIC" + SHLIB_LD='${CC} -shared' + SHLIB_SUFFIX=".so" + LDFLAGS="$LDFLAGS -export-dynamic" + CC_SEARCH_FLAGS="" + LD_SEARCH_FLAGS="" + ;; + CYGWIN_*) + SHLIB_CFLAGS="" + SHLIB_LD='${CC} -shared' + SHLIB_SUFFIX=".dll" + EXE_SUFFIX=".exe" + CC_SEARCH_FLAGS="" + LD_SEARCH_FLAGS="" + ;; + Haiku*) + LDFLAGS="$LDFLAGS -Wl,--export-dynamic" + SHLIB_CFLAGS="-fPIC" + SHLIB_SUFFIX=".so" + SHLIB_LD='${CC} -shared ${CFLAGS} ${LDFLAGS}' + AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"]) + ;; + HP-UX-*.11.*) + # Use updated header definitions where possible + AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?]) + # TEA specific: Needed by Tcl, but not most extensions + #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?]) + #LIBS="$LIBS -lxnet" # Use the XOPEN network library + + AS_IF([test "`uname -m`" = ia64], [ + SHLIB_SUFFIX=".so" + # Use newer C++ library for C++ extensions + #if test "$GCC" != "yes" ; then + # CPPFLAGS="-AA" + #fi + ], [ + SHLIB_SUFFIX=".sl" + ]) + AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no) + AS_IF([test "$tcl_ok" = yes], [ + LDFLAGS="$LDFLAGS -E" + CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.' + LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.' + LD_LIBRARY_PATH_VAR="SHLIB_PATH" + ]) + AS_IF([test "$GCC" = yes], [ + SHLIB_LD='${CC} -shared' + LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS} + ], [ + CFLAGS="$CFLAGS -z" + # Users may want PA-RISC 1.1/2.0 portable code - needs HP cc + #CFLAGS="$CFLAGS +DAportable" + SHLIB_CFLAGS="+z" + SHLIB_LD="ld -b" + ]) + + # Check to enable 64-bit flags for compiler/linker + AS_IF([test "$do64bit" = "yes"], [ + AS_IF([test "$GCC" = yes], [ + case `${CC} -dumpmachine` in + hppa64*) + # 64-bit gcc in use. Fix flags for GNU ld. + do64bit_ok=yes + SHLIB_LD='${CC} -shared' + AS_IF([test $doRpath = yes], [ + CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}']) + LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS} + ;; + *) + AC_MSG_WARN([64bit mode not supported with GCC on $system]) + ;; + esac + ], [ + do64bit_ok=yes + CFLAGS="$CFLAGS +DD64" + LDFLAGS_ARCH="+DD64" + ]) + ]) ;; + IRIX-6.*) + SHLIB_CFLAGS="" + SHLIB_LD="ld -n32 -shared -rdata_shared" + SHLIB_SUFFIX=".so" + AS_IF([test $doRpath = yes], [ + CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}']) + AS_IF([test "$GCC" = yes], [ + CFLAGS="$CFLAGS -mabi=n32" + LDFLAGS="$LDFLAGS -mabi=n32" + ], [ + case $system in + IRIX-6.3) + # Use to build 6.2 compatible binaries on 6.3. + CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS" + ;; + *) + CFLAGS="$CFLAGS -n32" + ;; + esac + LDFLAGS="$LDFLAGS -n32" + ]) + ;; + IRIX64-6.*) + SHLIB_CFLAGS="" + SHLIB_LD="ld -n32 -shared -rdata_shared" + SHLIB_SUFFIX=".so" + AS_IF([test $doRpath = yes], [ + CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}']) + + # Check to enable 64-bit flags for compiler/linker + + AS_IF([test "$do64bit" = yes], [ + AS_IF([test "$GCC" = yes], [ + AC_MSG_WARN([64bit mode not supported by gcc]) + ], [ + do64bit_ok=yes + SHLIB_LD="ld -64 -shared -rdata_shared" + CFLAGS="$CFLAGS -64" + LDFLAGS_ARCH="-64" + ]) + ]) + ;; + Linux*) + SHLIB_CFLAGS="-fPIC" + SHLIB_SUFFIX=".so" + + # TEA specific: + CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer" + + # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS + SHLIB_LD='${CC} -shared ${CFLAGS} ${LDFLAGS_DEFAULT}' + LDFLAGS="$LDFLAGS -Wl,--export-dynamic" + AS_IF([test $doRpath = yes], [ + CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}']) + LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS} + AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"]) + AS_IF([test $do64bit = yes], [ + AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [ + hold_cflags=$CFLAGS + CFLAGS="$CFLAGS -m64" + AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no) + CFLAGS=$hold_cflags]) + AS_IF([test $tcl_cv_cc_m64 = yes], [ + CFLAGS="$CFLAGS -m64" + do64bit_ok=yes + ]) + ]) + + # The combo of gcc + glibc has a bug related to inlining of + # functions like strtod(). The -fno-builtin flag should address + # this problem but it does not work. The -fno-inline flag is kind + # of overkill but it works. Disable inlining only when one of the + # files in compat/*.c is being linked in. + + AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"]) + + ;; + GNU*) + SHLIB_CFLAGS="-fPIC" + SHLIB_SUFFIX=".so" + + SHLIB_LD='${CC} -shared' + LDFLAGS="$LDFLAGS -Wl,--export-dynamic" + CC_SEARCH_FLAGS="" + LD_SEARCH_FLAGS="" + AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"]) + ;; + Lynx*) + SHLIB_CFLAGS="-fPIC" + SHLIB_SUFFIX=".so" + CFLAGS_OPTIMIZE=-02 + SHLIB_LD='${CC} -shared' + LD_FLAGS="-Wl,--export-dynamic" + AS_IF([test $doRpath = yes], [ + CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}']) + ;; + OpenBSD-*) + SHLIB_CFLAGS="-fPIC" + SHLIB_LD='${CC} -shared ${SHLIB_CFLAGS}' + SHLIB_SUFFIX=".so" + AS_IF([test $doRpath = yes], [ + CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}']) + LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS} + SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so.${SHLIB_VERSION}' + AC_CACHE_CHECK([for ELF], tcl_cv_ld_elf, [ + AC_EGREP_CPP(yes, [ +#ifdef __ELF__ + yes +#endif + ], tcl_cv_ld_elf=yes, tcl_cv_ld_elf=no)]) + AS_IF([test $tcl_cv_ld_elf = yes], [ + LDFLAGS=-Wl,-export-dynamic + ], [LDFLAGS=""]) + AS_IF([test "${TCL_THREADS}" = "1"], [ + # OpenBSD builds and links with -pthread, never -lpthread. + LIBS=`echo $LIBS | sed s/-lpthread//` + CFLAGS="$CFLAGS -pthread" + SHLIB_CFLAGS="$SHLIB_CFLAGS -pthread" + ]) + # OpenBSD doesn't do version numbers with dots. + UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a' + TCL_LIB_VERSIONS_OK=nodots + ;; + NetBSD-*|FreeBSD-[[3-4]].*) + # FreeBSD 3.* and greater have ELF. + # NetBSD 2.* has ELF and can use 'cc -shared' to build shared libs + SHLIB_CFLAGS="-fPIC" + SHLIB_LD='${CC} -shared ${SHLIB_CFLAGS}' + SHLIB_SUFFIX=".so" + LDFLAGS="$LDFLAGS -export-dynamic" + AS_IF([test $doRpath = yes], [ + CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}']) + LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS} + AS_IF([test "${TCL_THREADS}" = "1"], [ + # The -pthread needs to go in the CFLAGS, not LIBS + LIBS=`echo $LIBS | sed s/-pthread//` + CFLAGS="$CFLAGS -pthread" + LDFLAGS="$LDFLAGS -pthread" + ]) + case $system in + FreeBSD-3.*) + # FreeBSD-3 doesn't handle version numbers with dots. + UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a' + SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so' + TCL_LIB_VERSIONS_OK=nodots + ;; + esac + ;; + FreeBSD-*) + # This configuration from FreeBSD Ports. + SHLIB_CFLAGS="-fPIC" + SHLIB_LD="${CC} -shared" + TCL_SHLIB_LD_EXTRAS="-soname \$[@]" + SHLIB_SUFFIX=".so" + LDFLAGS="" + AS_IF([test $doRpath = yes], [ + CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}']) + AS_IF([test "${TCL_THREADS}" = "1"], [ + # The -pthread needs to go in the LDFLAGS, not LIBS + LIBS=`echo $LIBS | sed s/-pthread//` + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + LDFLAGS="$LDFLAGS $PTHREAD_LIBS"]) + # Version numbers are dot-stripped by system policy. + TCL_TRIM_DOTS=`echo ${VERSION} | tr -d .` + UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a' + SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1' + TCL_LIB_VERSIONS_OK=nodots + ;; + Darwin-*) + CFLAGS_OPTIMIZE="-Os" + SHLIB_CFLAGS="-fno-common" + # To avoid discrepancies between what headers configure sees during + # preprocessing tests and compiling tests, move any -isysroot and + # -mmacosx-version-min flags from CFLAGS to CPPFLAGS: + CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \ + awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \ + if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`" + CFLAGS="`echo " ${CFLAGS}" | \ + awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \ + if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`" + AS_IF([test $do64bit = yes], [ + case `arch` in + ppc) + AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag], + tcl_cv_cc_arch_ppc64, [ + hold_cflags=$CFLAGS + CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5" + AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes, + tcl_cv_cc_arch_ppc64=no) + CFLAGS=$hold_cflags]) + AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [ + CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5" + do64bit_ok=yes + ]);; + i386) + AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag], + tcl_cv_cc_arch_x86_64, [ + hold_cflags=$CFLAGS + CFLAGS="$CFLAGS -arch x86_64" + AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes, + tcl_cv_cc_arch_x86_64=no) + CFLAGS=$hold_cflags]) + AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [ + CFLAGS="$CFLAGS -arch x86_64" + do64bit_ok=yes + ]);; + *) + AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);; + esac + ], [ + # Check for combined 32-bit and 64-bit fat build + AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \ + && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [ + fat_32_64=yes]) + ]) + # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS + SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}' + AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [ + hold_ldflags=$LDFLAGS + LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module" + AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no) + LDFLAGS=$hold_ldflags]) + AS_IF([test $tcl_cv_ld_single_module = yes], [ + SHLIB_LD="${SHLIB_LD} -Wl,-single_module" + ]) + # TEA specific: link shlib with current and compatiblity version flags + vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d` + SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}" + SHLIB_SUFFIX=".dylib" + # Don't use -prebind when building for Mac OS X 10.4 or later only: + AS_IF([test "`echo "${MACOSX_DEPLOYMENT_TARGET}" | awk -F '10\\.' '{print int([$]2)}'`" -lt 4 -a \ + "`echo "${CPPFLAGS}" | awk -F '-mmacosx-version-min=10\\.' '{print int([$]2)}'`" -lt 4], [ + LDFLAGS="$LDFLAGS -prebind"]) + LDFLAGS="$LDFLAGS -headerpad_max_install_names" + AC_CACHE_CHECK([if ld accepts -search_paths_first flag], + tcl_cv_ld_search_paths_first, [ + hold_ldflags=$LDFLAGS + LDFLAGS="$LDFLAGS -Wl,-search_paths_first" + AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes, + tcl_cv_ld_search_paths_first=no) + LDFLAGS=$hold_ldflags]) + AS_IF([test $tcl_cv_ld_search_paths_first = yes], [ + LDFLAGS="$LDFLAGS -Wl,-search_paths_first" + ]) + AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [ + AC_DEFINE(MODULE_SCOPE, [__private_extern__], + [Compiler support for module scope symbols]) + tcl_cv_cc_visibility_hidden=yes + ]) + CC_SEARCH_FLAGS="" + LD_SEARCH_FLAGS="" + LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH" + # TEA specific: for combined 32 & 64 bit fat builds of Tk + # extensions, verify that 64-bit build is possible. + AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [ + AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [ + AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [ + for v in CFLAGS CPPFLAGS LDFLAGS; do + eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"' + done + CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include" + LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11" + AC_TRY_LINK([#include ], [XrmInitialize();], + tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no) + for v in CFLAGS CPPFLAGS LDFLAGS; do + eval $v'="$hold_'$v'"' + done]) + ]) + AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [ + AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [ + for v in CFLAGS CPPFLAGS LDFLAGS; do + eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"' + done + CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}" + LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}" + AC_TRY_LINK([#include ], [Tk_InitStubs(NULL, "", 0);], + tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no) + for v in CFLAGS CPPFLAGS LDFLAGS; do + eval $v'="$hold_'$v'"' + done]) + ]) + # remove 64-bit arch flags from CFLAGS et al. if configuration + # does not support 64-bit. + AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [ + AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags]) + for v in CFLAGS CPPFLAGS LDFLAGS; do + eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"' + done]) + ]) + ;; + OS/390-*) + CFLAGS_OPTIMIZE="" # Optimizer is buggy + AC_DEFINE(_OE_SOCKETS, 1, # needed in sys/socket.h + [Should OS/390 do the right thing with sockets?]) + ;; + OSF1-V*) + # Digital OSF/1 + SHLIB_CFLAGS="" + AS_IF([test "$SHARED_BUILD" = 1], [ + SHLIB_LD='ld -shared -expect_unresolved "*"' + ], [ + SHLIB_LD='ld -non_shared -expect_unresolved "*"' + ]) + SHLIB_SUFFIX=".so" + AS_IF([test $doRpath = yes], [ + CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}']) + AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [ + CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"]) + # see pthread_intro(3) for pthread support on osf1, k.furukawa + AS_IF([test "${TCL_THREADS}" = 1], [ + CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE" + CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64" + LIBS=`echo $LIBS | sed s/-lpthreads//` + AS_IF([test "$GCC" = yes], [ + LIBS="$LIBS -lpthread -lmach -lexc" + ], [ + CFLAGS="$CFLAGS -pthread" + LDFLAGS="$LDFLAGS -pthread" + ]) + ]) + ;; + QNX-6*) + # QNX RTP + # This may work for all QNX, but it was only reported for v6. + SHLIB_CFLAGS="-fPIC" + SHLIB_LD="ld -Bshareable -x" + SHLIB_LD_LIBS="" + SHLIB_SUFFIX=".so" + CC_SEARCH_FLAGS="" + LD_SEARCH_FLAGS="" + ;; + SCO_SV-3.2*) + AS_IF([test "$GCC" = yes], [ + SHLIB_CFLAGS="-fPIC -melf" + LDFLAGS="$LDFLAGS -melf -Wl,-Bexport" + ], [ + SHLIB_CFLAGS="-Kpic -belf" + LDFLAGS="$LDFLAGS -belf -Wl,-Bexport" + ]) + SHLIB_LD="ld -G" + SHLIB_LD_LIBS="" + SHLIB_SUFFIX=".so" + CC_SEARCH_FLAGS="" + LD_SEARCH_FLAGS="" + ;; + SunOS-5.[[0-6]]) + # Careful to not let 5.10+ fall into this case + + # Note: If _REENTRANT isn't defined, then Solaris + # won't define thread-safe library routines. + + AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?]) + AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1, + [Do we really want to follow the standard? Yes we do!]) + + SHLIB_CFLAGS="-KPIC" + SHLIB_SUFFIX=".so" + AS_IF([test "$GCC" = yes], [ + SHLIB_LD='${CC} -shared' + CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS} + ], [ + SHLIB_LD="/usr/ccs/bin/ld -G -z text" + CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS} + ]) + ;; + SunOS-5*) + # Note: If _REENTRANT isn't defined, then Solaris + # won't define thread-safe library routines. + + AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?]) + AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1, + [Do we really want to follow the standard? Yes we do!]) + + SHLIB_CFLAGS="-KPIC" + + # Check to enable 64-bit flags for compiler/linker + AS_IF([test "$do64bit" = yes], [ + arch=`isainfo` + AS_IF([test "$arch" = "sparcv9 sparc"], [ + AS_IF([test "$GCC" = yes], [ + AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [ + AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system]) + ], [ + do64bit_ok=yes + CFLAGS="$CFLAGS -m64 -mcpu=v9" + LDFLAGS="$LDFLAGS -m64 -mcpu=v9" + SHLIB_CFLAGS="-fPIC" + ]) + ], [ + do64bit_ok=yes + AS_IF([test "$do64bitVIS" = yes], [ + CFLAGS="$CFLAGS -xarch=v9a" + LDFLAGS_ARCH="-xarch=v9a" + ], [ + CFLAGS="$CFLAGS -xarch=v9" + LDFLAGS_ARCH="-xarch=v9" + ]) + # Solaris 64 uses this as well + #LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64" + ]) + ], [AS_IF([test "$arch" = "amd64 i386"], [ + AS_IF([test "$GCC" = yes], [ + case $system in + SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*) + do64bit_ok=yes + CFLAGS="$CFLAGS -m64" + LDFLAGS="$LDFLAGS -m64";; + *) + AC_MSG_WARN([64bit mode not supported with GCC on $system]);; + esac + ], [ + do64bit_ok=yes + case $system in + SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*) + CFLAGS="$CFLAGS -m64" + LDFLAGS="$LDFLAGS -m64";; + *) + CFLAGS="$CFLAGS -xarch=amd64" + LDFLAGS="$LDFLAGS -xarch=amd64";; + esac + ]) + ], [AC_MSG_WARN([64bit mode not supported for $arch])])]) + ]) + + SHLIB_SUFFIX=".so" + AS_IF([test "$GCC" = yes], [ + SHLIB_LD='${CC} -shared' + CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS} + AS_IF([test "$do64bit_ok" = yes], [ + AS_IF([test "$arch" = "sparcv9 sparc"], [ + # We need to specify -static-libgcc or we need to + # add the path to the sparv9 libgcc. + # JH: static-libgcc is necessary for core Tcl, but may + # not be necessary for extensions. + SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc" + # for finding sparcv9 libgcc, get the regular libgcc + # path, remove so name and append 'sparcv9' + #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..." + #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir" + ], [AS_IF([test "$arch" = "amd64 i386"], [ + # JH: static-libgcc is necessary for core Tcl, but may + # not be necessary for extensions. + SHLIB_LD="$SHLIB_LD -m64 -static-libgcc" + ])]) + ]) + ], [ + case $system in + SunOS-5.[[1-9]][[0-9]]*) + # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS + SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';; + *) + SHLIB_LD='/usr/ccs/bin/ld -G -z text';; + esac + CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}' + LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}' + ]) + ;; + esac + + AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [ + AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform]) + ]) + +dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so +dnl # until the end of configure, as configure's compile and link tests use +dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's +dnl # preprocessing tests use only CPPFLAGS. + AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""]) + + # Add in the arch flags late to ensure it wasn't removed. + # Not necessary in TEA, but this is aligned with core + LDFLAGS="$LDFLAGS $LDFLAGS_ARCH" + + # If we're running gcc, then change the C flags for compiling shared + # libraries to the right flags for gcc, instead of those for the + # standard manufacturer compiler. + + AS_IF([test "$GCC" = yes], [ + case $system in + AIX-*) ;; + BSD/OS*) ;; + CYGWIN_*) ;; + IRIX*) ;; + NetBSD-*|FreeBSD-*|OpenBSD-*) ;; + Darwin-*) ;; + SCO_SV-3.2*) ;; + windows) ;; + *) SHLIB_CFLAGS="-fPIC" ;; + esac]) + + AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [ + AC_DEFINE(MODULE_SCOPE, [extern], + [No Compiler support for module scope symbols]) + AC_DEFINE(NO_VIZ) + ]) + + AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [ + # TEA specific: use PACKAGE_VERSION instead of VERSION + SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}']) + AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [ + # TEA specific: use PACKAGE_VERSION instead of VERSION + UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a']) + + AC_SUBST(CFLAGS_DEBUG) + AC_SUBST(CFLAGS_OPTIMIZE) + AC_SUBST(CFLAGS_WARNING) + + AC_SUBST(STLIB_LD) + AC_SUBST(SHLIB_LD) + + AC_SUBST(SHLIB_LD_LIBS) + AC_SUBST(SHLIB_CFLAGS) + + AC_SUBST(LD_LIBRARY_PATH_VAR) + + # These must be called after we do the basic CFLAGS checks and + # verify any possible 64-bit or similar switches are necessary + TEA_TCL_EARLY_FLAGS + TEA_TCL_64BIT_FLAGS +]) + +#-------------------------------------------------------------------- +# TEA_SERIAL_PORT +# +# Determine which interface to use to talk to the serial port. +# Note that #include lines must begin in leftmost column for +# some compilers to recognize them as preprocessor directives, +# and some build environments have stdin not pointing at a +# pseudo-terminal (usually /dev/null instead.) +# +# Arguments: +# none +# +# Results: +# +# Defines only one of the following vars: +# HAVE_SYS_MODEM_H +# USE_TERMIOS +# USE_TERMIO +# USE_SGTTY +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_SERIAL_PORT], [ + AC_CHECK_HEADERS(sys/modem.h) + AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [ + AC_TRY_RUN([ +#include + +int main() { + struct termios t; + if (tcgetattr(0, &t) == 0) { + cfsetospeed(&t, 0); + t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB; + return 0; + } + return 1; +}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no) + if test $tcl_cv_api_serial = no ; then + AC_TRY_RUN([ +#include + +int main() { + struct termio t; + if (ioctl(0, TCGETA, &t) == 0) { + t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB; + return 0; + } + return 1; +}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no) + fi + if test $tcl_cv_api_serial = no ; then + AC_TRY_RUN([ +#include + +int main() { + struct sgttyb t; + if (ioctl(0, TIOCGETP, &t) == 0) { + t.sg_ospeed = 0; + t.sg_flags |= ODDP | EVENP | RAW; + return 0; + } + return 1; +}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no) + fi + if test $tcl_cv_api_serial = no ; then + AC_TRY_RUN([ +#include +#include + +int main() { + struct termios t; + if (tcgetattr(0, &t) == 0 + || errno == ENOTTY || errno == ENXIO || errno == EINVAL) { + cfsetospeed(&t, 0); + t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB; + return 0; + } + return 1; +}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no) + fi + if test $tcl_cv_api_serial = no; then + AC_TRY_RUN([ +#include +#include + +int main() { + struct termio t; + if (ioctl(0, TCGETA, &t) == 0 + || errno == ENOTTY || errno == ENXIO || errno == EINVAL) { + t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB; + return 0; + } + return 1; + }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no) + fi + if test $tcl_cv_api_serial = no; then + AC_TRY_RUN([ +#include +#include + +int main() { + struct sgttyb t; + if (ioctl(0, TIOCGETP, &t) == 0 + || errno == ENOTTY || errno == ENXIO || errno == EINVAL) { + t.sg_ospeed = 0; + t.sg_flags |= ODDP | EVENP | RAW; + return 0; + } + return 1; +}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none) + fi]) + case $tcl_cv_api_serial in + termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);; + termio) AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);; + sgtty) AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);; + esac +]) + +#-------------------------------------------------------------------- +# TEA_MISSING_POSIX_HEADERS +# +# Supply substitutes for missing POSIX header files. Special +# notes: +# - stdlib.h doesn't define strtol, strtoul, or +# strtod in some versions of SunOS +# - some versions of string.h don't declare procedures such +# as strstr +# +# Arguments: +# none +# +# Results: +# +# Defines some of the following vars: +# NO_DIRENT_H +# NO_ERRNO_H +# NO_VALUES_H +# HAVE_LIMITS_H or NO_LIMITS_H +# NO_STDLIB_H +# NO_STRING_H +# NO_SYS_WAIT_H +# NO_DLFCN_H +# HAVE_SYS_PARAM_H +# +# HAVE_STRING_H ? +# +# tkUnixPort.h checks for HAVE_LIMITS_H, so do both HAVE and +# CHECK on limits.h +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_MISSING_POSIX_HEADERS], [ + AC_CACHE_CHECK([dirent.h], tcl_cv_dirent_h, [ + AC_TRY_LINK([#include +#include ], [ +#ifndef _POSIX_SOURCE +# ifdef __Lynx__ + /* + * Generate compilation error to make the test fail: Lynx headers + * are only valid if really in the POSIX environment. + */ + + missing_procedure(); +# endif +#endif +DIR *d; +struct dirent *entryPtr; +char *p; +d = opendir("foobar"); +entryPtr = readdir(d); +p = entryPtr->d_name; +closedir(d); +], tcl_cv_dirent_h=yes, tcl_cv_dirent_h=no)]) + + if test $tcl_cv_dirent_h = no; then + AC_DEFINE(NO_DIRENT_H, 1, [Do we have ?]) + fi + + # TEA specific: + AC_CHECK_HEADER(errno.h, , [AC_DEFINE(NO_ERRNO_H, 1, [Do we have ?])]) + AC_CHECK_HEADER(float.h, , [AC_DEFINE(NO_FLOAT_H, 1, [Do we have ?])]) + AC_CHECK_HEADER(values.h, , [AC_DEFINE(NO_VALUES_H, 1, [Do we have ?])]) + AC_CHECK_HEADER(limits.h, + [AC_DEFINE(HAVE_LIMITS_H, 1, [Do we have ?])], + [AC_DEFINE(NO_LIMITS_H, 1, [Do we have ?])]) + AC_CHECK_HEADER(stdlib.h, tcl_ok=1, tcl_ok=0) + AC_EGREP_HEADER(strtol, stdlib.h, , tcl_ok=0) + AC_EGREP_HEADER(strtoul, stdlib.h, , tcl_ok=0) + AC_EGREP_HEADER(strtod, stdlib.h, , tcl_ok=0) + if test $tcl_ok = 0; then + AC_DEFINE(NO_STDLIB_H, 1, [Do we have ?]) + fi + AC_CHECK_HEADER(string.h, tcl_ok=1, tcl_ok=0) + AC_EGREP_HEADER(strstr, string.h, , tcl_ok=0) + AC_EGREP_HEADER(strerror, string.h, , tcl_ok=0) + + # See also memmove check below for a place where NO_STRING_H can be + # set and why. + + if test $tcl_ok = 0; then + AC_DEFINE(NO_STRING_H, 1, [Do we have ?]) + fi + + AC_CHECK_HEADER(sys/wait.h, , [AC_DEFINE(NO_SYS_WAIT_H, 1, [Do we have ?])]) + AC_CHECK_HEADER(dlfcn.h, , [AC_DEFINE(NO_DLFCN_H, 1, [Do we have ?])]) + + # OS/390 lacks sys/param.h (and doesn't need it, by chance). + AC_HAVE_HEADERS(sys/param.h) +]) + +#-------------------------------------------------------------------- +# TEA_PATH_X +# +# Locate the X11 header files and the X11 library archive. Try +# the ac_path_x macro first, but if it doesn't find the X stuff +# (e.g. because there's no xmkmf program) then check through +# a list of possible directories. Under some conditions the +# autoconf macro will return an include directory that contains +# no include files, so double-check its result just to be safe. +# +# This should be called after TEA_CONFIG_CFLAGS as setting the +# LIBS line can confuse some configure macro magic. +# +# Arguments: +# none +# +# Results: +# +# Sets the following vars: +# XINCLUDES +# XLIBSW +# PKG_LIBS (appends to) +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_PATH_X], [ + if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then + TEA_PATH_UNIX_X + fi +]) + +AC_DEFUN([TEA_PATH_UNIX_X], [ + AC_PATH_X + not_really_there="" + if test "$no_x" = ""; then + if test "$x_includes" = ""; then + AC_TRY_CPP([#include ], , not_really_there="yes") + else + if test ! -r $x_includes/X11/Intrinsic.h; then + not_really_there="yes" + fi + fi + fi + if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then + AC_MSG_CHECKING([for X11 header files]) + found_xincludes="no" + AC_TRY_CPP([#include ], found_xincludes="yes", found_xincludes="no") + if test "$found_xincludes" = "no"; then + dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include" + for i in $dirs ; do + if test -r $i/X11/Intrinsic.h; then + AC_MSG_RESULT([$i]) + XINCLUDES=" -I$i" + found_xincludes="yes" + break + fi + done + fi + else + if test "$x_includes" != ""; then + XINCLUDES="-I$x_includes" + found_xincludes="yes" + fi + fi + if test "$found_xincludes" = "no"; then + AC_MSG_RESULT([couldn't find any!]) + fi + + if test "$no_x" = yes; then + AC_MSG_CHECKING([for X11 libraries]) + XLIBSW=nope + dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib" + for i in $dirs ; do + if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then + AC_MSG_RESULT([$i]) + XLIBSW="-L$i -lX11" + x_libraries="$i" + break + fi + done + else + if test "$x_libraries" = ""; then + XLIBSW=-lX11 + else + XLIBSW="-L$x_libraries -lX11" + fi + fi + if test "$XLIBSW" = nope ; then + AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow) + fi + if test "$XLIBSW" = nope ; then + AC_MSG_RESULT([could not find any! Using -lX11.]) + XLIBSW=-lX11 + fi + # TEA specific: + if test x"${XLIBSW}" != x ; then + PKG_LIBS="${PKG_LIBS} ${XLIBSW}" + fi +]) + +#-------------------------------------------------------------------- +# TEA_BLOCKING_STYLE +# +# The statements below check for systems where POSIX-style +# non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented. +# On these systems (mostly older ones), use the old BSD-style +# FIONBIO approach instead. +# +# Arguments: +# none +# +# Results: +# +# Defines some of the following vars: +# HAVE_SYS_IOCTL_H +# HAVE_SYS_FILIO_H +# USE_FIONBIO +# O_NONBLOCK +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_BLOCKING_STYLE], [ + AC_CHECK_HEADERS(sys/ioctl.h) + AC_CHECK_HEADERS(sys/filio.h) + TEA_CONFIG_SYSTEM + AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O]) + case $system in + OSF*) + AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?]) + AC_MSG_RESULT([FIONBIO]) + ;; + *) + AC_MSG_RESULT([O_NONBLOCK]) + ;; + esac +]) + +#-------------------------------------------------------------------- +# TEA_TIME_HANDLER +# +# Checks how the system deals with time.h, what time structures +# are used on the system, and what fields the structures have. +# +# Arguments: +# none +# +# Results: +# +# Defines some of the following vars: +# USE_DELTA_FOR_TZ +# HAVE_TM_GMTOFF +# HAVE_TM_TZADJ +# HAVE_TIMEZONE_VAR +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_TIME_HANDLER], [ + AC_CHECK_HEADERS(sys/time.h) + AC_HEADER_TIME + AC_STRUCT_TIMEZONE + + AC_CHECK_FUNCS(gmtime_r localtime_r) + + AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [ + AC_TRY_COMPILE([#include ], [struct tm tm; tm.tm_tzadj;], + tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)]) + if test $tcl_cv_member_tm_tzadj = yes ; then + AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?]) + fi + + AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [ + AC_TRY_COMPILE([#include ], [struct tm tm; tm.tm_gmtoff;], + tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)]) + if test $tcl_cv_member_tm_gmtoff = yes ; then + AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?]) + fi + + # + # Its important to include time.h in this check, as some systems + # (like convex) have timezone functions, etc. + # + AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [ + AC_TRY_COMPILE([#include ], + [extern long timezone; + timezone += 1; + exit (0);], + tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)]) + if test $tcl_cv_timezone_long = yes ; then + AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?]) + else + # + # On some systems (eg IRIX 6.2), timezone is a time_t and not a long. + # + AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [ + AC_TRY_COMPILE([#include ], + [extern time_t timezone; + timezone += 1; + exit (0);], + tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)]) + if test $tcl_cv_timezone_time = yes ; then + AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?]) + fi + fi +]) + +#-------------------------------------------------------------------- +# TEA_BUGGY_STRTOD +# +# Under Solaris 2.4, strtod returns the wrong value for the +# terminating character under some conditions. Check for this +# and if the problem exists use a substitute procedure +# "fixstrtod" (provided by Tcl) that corrects the error. +# Also, on Compaq's Tru64 Unix 5.0, +# strtod(" ") returns 0.0 instead of a failure to convert. +# +# Arguments: +# none +# +# Results: +# +# Might defines some of the following vars: +# strtod (=fixstrtod) +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_BUGGY_STRTOD], [ + AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0) + if test "$tcl_strtod" = 1; then + AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[ + AC_TRY_RUN([ + extern double strtod(); + int main() { + char *infString="Inf", *nanString="NaN", *spaceString=" "; + char *term; + double value; + value = strtod(infString, &term); + if ((term != infString) && (term[-1] == 0)) { + exit(1); + } + value = strtod(nanString, &term); + if ((term != nanString) && (term[-1] == 0)) { + exit(1); + } + value = strtod(spaceString, &term); + if (term == (spaceString+1)) { + exit(1); + } + exit(0); + }], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy, + tcl_cv_strtod_buggy=buggy)]) + if test "$tcl_cv_strtod_buggy" = buggy; then + AC_LIBOBJ([fixstrtod]) + USE_COMPAT=1 + AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?]) + fi + fi +]) + +#-------------------------------------------------------------------- +# TEA_TCL_LINK_LIBS +# +# Search for the libraries needed to link the Tcl shell. +# Things like the math library (-lm) and socket stuff (-lsocket vs. +# -lnsl) are dealt with here. +# +# Arguments: +# Requires the following vars to be set in the Makefile: +# DL_LIBS (not in TEA, only needed in core) +# LIBS +# MATH_LIBS +# +# Results: +# +# Subst's the following var: +# TCL_LIBS +# MATH_LIBS +# +# Might append to the following vars: +# LIBS +# +# Might define the following vars: +# HAVE_NET_ERRNO_H +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_TCL_LINK_LIBS], [ + #-------------------------------------------------------------------- + # On a few very rare systems, all of the libm.a stuff is + # already in libc.a. Set compiler flags accordingly. + # Also, Linux requires the "ieee" library for math to work + # right (and it must appear before "-lm"). + #-------------------------------------------------------------------- + + AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm") + AC_CHECK_LIB(ieee, main, [MATH_LIBS="-lieee $MATH_LIBS"]) + + #-------------------------------------------------------------------- + # Interactive UNIX requires -linet instead of -lsocket, plus it + # needs net/errno.h to define the socket-related error codes. + #-------------------------------------------------------------------- + + AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"]) + AC_CHECK_HEADER(net/errno.h, [ + AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have ?])]) + + #-------------------------------------------------------------------- + # Check for the existence of the -lsocket and -lnsl libraries. + # The order here is important, so that they end up in the right + # order in the command line generated by make. Here are some + # special considerations: + # 1. Use "connect" and "accept" to check for -lsocket, and + # "gethostbyname" to check for -lnsl. + # 2. Use each function name only once: can't redo a check because + # autoconf caches the results of the last check and won't redo it. + # 3. Use -lnsl and -lsocket only if they supply procedures that + # aren't already present in the normal libraries. This is because + # IRIX 5.2 has libraries, but they aren't needed and they're + # bogus: they goof up name resolution if used. + # 4. On some SVR4 systems, can't use -lsocket without -lnsl too. + # To get around this problem, check for both libraries together + # if -lsocket doesn't work by itself. + #-------------------------------------------------------------------- + + tcl_checkBoth=0 + AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1) + if test "$tcl_checkSocket" = 1; then + AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt, + LIBS="$LIBS -lsocket", tcl_checkBoth=1)]) + fi + if test "$tcl_checkBoth" = 1; then + tk_oldLibs=$LIBS + LIBS="$LIBS -lsocket -lnsl" + AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs]) + fi + AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname, + [LIBS="$LIBS -lnsl"])]) + + # TEA specific: Don't perform the eval of the libraries here because + # DL_LIBS won't be set until we call TEA_CONFIG_CFLAGS + + TCL_LIBS='${DL_LIBS} ${LIBS} ${MATH_LIBS}' + AC_SUBST(TCL_LIBS) + AC_SUBST(MATH_LIBS) +]) + +#-------------------------------------------------------------------- +# TEA_TCL_EARLY_FLAGS +# +# Check for what flags are needed to be passed so the correct OS +# features are available. +# +# Arguments: +# None +# +# Results: +# +# Might define the following vars: +# _ISOC99_SOURCE +# _LARGEFILE64_SOURCE +# _LARGEFILE_SOURCE64 +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_TCL_EARLY_FLAG],[ + AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]), + AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no, + AC_TRY_COMPILE([[#define ]$1[ 1 +]$2], $3, + [tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes, + [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no))) + if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then + AC_DEFINE($1, 1, [Add the ]$1[ flag when building]) + tcl_flags="$tcl_flags $1" + fi +]) + +AC_DEFUN([TEA_TCL_EARLY_FLAGS],[ + AC_MSG_CHECKING([for required early compiler flags]) + tcl_flags="" + TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include ], + [char *p = (char *)strtoll; char *q = (char *)strtoull;]) + TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include ], + [struct stat64 buf; int i = stat64("/", &buf);]) + TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include ], + [char *p = (char *)open64;]) + if test "x${tcl_flags}" = "x" ; then + AC_MSG_RESULT([none]) + else + AC_MSG_RESULT([${tcl_flags}]) + fi +]) + +#-------------------------------------------------------------------- +# TEA_TCL_64BIT_FLAGS +# +# Check for what is defined in the way of 64-bit features. +# +# Arguments: +# None +# +# Results: +# +# Might define the following vars: +# TCL_WIDE_INT_IS_LONG +# TCL_WIDE_INT_TYPE +# HAVE_STRUCT_DIRENT64 +# HAVE_STRUCT_STAT64 +# HAVE_TYPE_OFF64_T +# +#-------------------------------------------------------------------- + +AC_DEFUN([TEA_TCL_64BIT_FLAGS], [ + AC_MSG_CHECKING([for 64-bit integer type]) + AC_CACHE_VAL(tcl_cv_type_64bit,[ + tcl_cv_type_64bit=none + # See if the compiler knows natively about __int64 + AC_TRY_COMPILE(,[__int64 value = (__int64) 0;], + tcl_type_64bit=__int64, tcl_type_64bit="long long") + # See if we should use long anyway Note that we substitute in the + # type that is our current guess for a 64-bit type inside this check + # program, so it should be modified only carefully... + AC_TRY_COMPILE(,[switch (0) { + case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ; + }],tcl_cv_type_64bit=${tcl_type_64bit})]) + if test "${tcl_cv_type_64bit}" = none ; then + AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Are wide integers to be implemented with C 'long's?]) + AC_MSG_RESULT([using long]) + elif test "${tcl_cv_type_64bit}" = "__int64" \ + -a "${TEA_PLATFORM}" = "windows" ; then + # TEA specific: We actually want to use the default tcl.h checks in + # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER* + AC_MSG_RESULT([using Tcl header defaults]) + else + AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit}, + [What type should be used to define wide integers?]) + AC_MSG_RESULT([${tcl_cv_type_64bit}]) + + # Now check for auxiliary declarations + AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[ + AC_TRY_COMPILE([#include +#include ],[struct dirent64 p;], + tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)]) + if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then + AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in ?]) + fi + + AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[ + AC_TRY_COMPILE([#include ],[struct stat64 p; +], + tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)]) + if test "x${tcl_cv_struct_stat64}" = "xyes" ; then + AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in ?]) + fi + + AC_CHECK_FUNCS(open64 lseek64) + AC_MSG_CHECKING([for off64_t]) + AC_CACHE_VAL(tcl_cv_type_off64_t,[ + AC_TRY_COMPILE([#include ],[off64_t offset; +], + tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)]) + dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the + dnl functions lseek64 and open64 are defined. + if test "x${tcl_cv_type_off64_t}" = "xyes" && \ + test "x${ac_cv_func_lseek64}" = "xyes" && \ + test "x${ac_cv_func_open64}" = "xyes" ; then + AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in ?]) + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + fi +]) + +## +## Here ends the standard Tcl configuration bits and starts the +## TEA specific functions +## + +#------------------------------------------------------------------------ +# TEA_INIT -- +# +# Init various Tcl Extension Architecture (TEA) variables. +# This should be the first called TEA_* macro. +# +# Arguments: +# none +# +# Results: +# +# Defines and substs the following vars: +# CYGPATH +# EXEEXT +# Defines only: +# TEA_VERSION +# TEA_INITED +# TEA_PLATFORM (windows or unix) +# +# "cygpath" is used on windows to generate native path names for include +# files. These variables should only be used with the compiler and linker +# since they generate native path names. +# +# EXEEXT +# Select the executable extension based on the host type. This +# is a lightweight replacement for AC_EXEEXT that doesn't require +# a compiler. +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_INIT], [ + # TEA extensions pass this us the version of TEA they think they + # are compatible with. + TEA_VERSION="3.9" + + AC_MSG_CHECKING([for correct TEA configuration]) + if test x"${PACKAGE_NAME}" = x ; then + AC_MSG_ERROR([ +The PACKAGE_NAME variable must be defined by your TEA configure.in]) + fi + if test x"$1" = x ; then + AC_MSG_ERROR([ +TEA version not specified.]) + elif test "$1" != "${TEA_VERSION}" ; then + AC_MSG_RESULT([warning: requested TEA version "$1", have "${TEA_VERSION}"]) + else + AC_MSG_RESULT([ok (TEA ${TEA_VERSION})]) + fi + case "`uname -s`" in + *win32*|*WIN32*|*MINGW32_*) + AC_CHECK_PROG(CYGPATH, cygpath, cygpath -w, echo) + EXEEXT=".exe" + TEA_PLATFORM="windows" + ;; + *CYGWIN_*) + CYGPATH=echo + EXEEXT=".exe" + # TEA_PLATFORM is determined later in LOAD_TCLCONFIG + ;; + *) + CYGPATH=echo + EXEEXT="" + TEA_PLATFORM="unix" + ;; + esac + + # Check if exec_prefix is set. If not use fall back to prefix. + # Note when adjusted, so that TEA_PREFIX can correct for this. + # This is needed for recursive configures, since autoconf propagates + # $prefix, but not $exec_prefix (doh!). + if test x$exec_prefix = xNONE ; then + exec_prefix_default=yes + exec_prefix=$prefix + fi + + AC_SUBST(EXEEXT) + AC_SUBST(CYGPATH) + + # This package name must be replaced statically for AC_SUBST to work + AC_SUBST(PKG_LIB_FILE) + # Substitute STUB_LIB_FILE in case package creates a stub library too. + AC_SUBST(PKG_STUB_LIB_FILE) + + # We AC_SUBST these here to ensure they are subst'ed, + # in case the user doesn't call TEA_ADD_... + AC_SUBST(PKG_STUB_SOURCES) + AC_SUBST(PKG_STUB_OBJECTS) + AC_SUBST(PKG_TCL_SOURCES) + AC_SUBST(PKG_HEADERS) + AC_SUBST(PKG_INCLUDES) + AC_SUBST(PKG_LIBS) + AC_SUBST(PKG_CFLAGS) +]) + +#------------------------------------------------------------------------ +# TEA_ADD_SOURCES -- +# +# Specify one or more source files. Users should check for +# the right platform before adding to their list. +# It is not important to specify the directory, as long as it is +# in the generic, win or unix subdirectory of $(srcdir). +# +# Arguments: +# one or more file names +# +# Results: +# +# Defines and substs the following vars: +# PKG_SOURCES +# PKG_OBJECTS +#------------------------------------------------------------------------ +AC_DEFUN([TEA_ADD_SOURCES], [ + vars="$@" + for i in $vars; do + case $i in + [\$]*) + # allow $-var names + PKG_SOURCES="$PKG_SOURCES $i" + PKG_OBJECTS="$PKG_OBJECTS $i" + ;; + *) + # check for existence - allows for generic/win/unix VPATH + # To add more dirs here (like 'src'), you have to update VPATH + # in Makefile.in as well + if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \ + -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \ + -a ! -f "${srcdir}/macosx/$i" \ + ; then + AC_MSG_ERROR([could not find source file '$i']) + fi + PKG_SOURCES="$PKG_SOURCES $i" + # this assumes it is in a VPATH dir + i=`basename $i` + # handle user calling this before or after TEA_SETUP_COMPILER + if test x"${OBJEXT}" != x ; then + j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}" + else + j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}" + fi + PKG_OBJECTS="$PKG_OBJECTS $j" + ;; + esac + done + AC_SUBST(PKG_SOURCES) + AC_SUBST(PKG_OBJECTS) +]) + +#------------------------------------------------------------------------ +# TEA_ADD_STUB_SOURCES -- +# +# Specify one or more source files. Users should check for +# the right platform before adding to their list. +# It is not important to specify the directory, as long as it is +# in the generic, win or unix subdirectory of $(srcdir). +# +# Arguments: +# one or more file names +# +# Results: +# +# Defines and substs the following vars: +# PKG_STUB_SOURCES +# PKG_STUB_OBJECTS +#------------------------------------------------------------------------ +AC_DEFUN([TEA_ADD_STUB_SOURCES], [ + vars="$@" + for i in $vars; do + # check for existence - allows for generic/win/unix VPATH + if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \ + -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \ + -a ! -f "${srcdir}/macosx/$i" \ + ; then + AC_MSG_ERROR([could not find stub source file '$i']) + fi + PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i" + # this assumes it is in a VPATH dir + i=`basename $i` + # handle user calling this before or after TEA_SETUP_COMPILER + if test x"${OBJEXT}" != x ; then + j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}" + else + j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}" + fi + PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j" + done + AC_SUBST(PKG_STUB_SOURCES) + AC_SUBST(PKG_STUB_OBJECTS) +]) + +#------------------------------------------------------------------------ +# TEA_ADD_TCL_SOURCES -- +# +# Specify one or more Tcl source files. These should be platform +# independent runtime files. +# +# Arguments: +# one or more file names +# +# Results: +# +# Defines and substs the following vars: +# PKG_TCL_SOURCES +#------------------------------------------------------------------------ +AC_DEFUN([TEA_ADD_TCL_SOURCES], [ + vars="$@" + for i in $vars; do + # check for existence, be strict because it is installed + if test ! -f "${srcdir}/$i" ; then + AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i']) + fi + PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i" + done + AC_SUBST(PKG_TCL_SOURCES) +]) + +#------------------------------------------------------------------------ +# TEA_ADD_HEADERS -- +# +# Specify one or more source headers. Users should check for +# the right platform before adding to their list. +# +# Arguments: +# one or more file names +# +# Results: +# +# Defines and substs the following vars: +# PKG_HEADERS +#------------------------------------------------------------------------ +AC_DEFUN([TEA_ADD_HEADERS], [ + vars="$@" + for i in $vars; do + # check for existence, be strict because it is installed + if test ! -f "${srcdir}/$i" ; then + AC_MSG_ERROR([could not find header file '${srcdir}/$i']) + fi + PKG_HEADERS="$PKG_HEADERS $i" + done + AC_SUBST(PKG_HEADERS) +]) + +#------------------------------------------------------------------------ +# TEA_ADD_INCLUDES -- +# +# Specify one or more include dirs. Users should check for +# the right platform before adding to their list. +# +# Arguments: +# one or more file names +# +# Results: +# +# Defines and substs the following vars: +# PKG_INCLUDES +#------------------------------------------------------------------------ +AC_DEFUN([TEA_ADD_INCLUDES], [ + vars="$@" + for i in $vars; do + PKG_INCLUDES="$PKG_INCLUDES $i" + done + AC_SUBST(PKG_INCLUDES) +]) + +#------------------------------------------------------------------------ +# TEA_ADD_LIBS -- +# +# Specify one or more libraries. Users should check for +# the right platform before adding to their list. For Windows, +# libraries provided in "foo.lib" format will be converted to +# "-lfoo" when using GCC (mingw). +# +# Arguments: +# one or more file names +# +# Results: +# +# Defines and substs the following vars: +# PKG_LIBS +#------------------------------------------------------------------------ +AC_DEFUN([TEA_ADD_LIBS], [ + vars="$@" + for i in $vars; do + if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then + # Convert foo.lib to -lfoo for GCC. No-op if not *.lib + i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'` + fi + PKG_LIBS="$PKG_LIBS $i" + done + AC_SUBST(PKG_LIBS) +]) + +#------------------------------------------------------------------------ +# TEA_ADD_CFLAGS -- +# +# Specify one or more CFLAGS. Users should check for +# the right platform before adding to their list. +# +# Arguments: +# one or more file names +# +# Results: +# +# Defines and substs the following vars: +# PKG_CFLAGS +#------------------------------------------------------------------------ +AC_DEFUN([TEA_ADD_CFLAGS], [ + PKG_CFLAGS="$PKG_CFLAGS $@" + AC_SUBST(PKG_CFLAGS) +]) + +#------------------------------------------------------------------------ +# TEA_PREFIX -- +# +# Handle the --prefix=... option by defaulting to what Tcl gave +# +# Arguments: +# none +# +# Results: +# +# If --prefix or --exec-prefix was not specified, $prefix and +# $exec_prefix will be set to the values given to Tcl when it was +# configured. +#------------------------------------------------------------------------ +AC_DEFUN([TEA_PREFIX], [ + if test "${prefix}" = "NONE"; then + prefix_default=yes + if test x"${TCL_PREFIX}" != x; then + AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}]) + prefix=${TCL_PREFIX} + else + AC_MSG_NOTICE([--prefix defaulting to /usr/local]) + prefix=/usr/local + fi + fi + if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \ + -o x"${exec_prefix_default}" = x"yes" ; then + if test x"${TCL_EXEC_PREFIX}" != x; then + AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}]) + exec_prefix=${TCL_EXEC_PREFIX} + else + AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}]) + exec_prefix=$prefix + fi + fi +]) + +#------------------------------------------------------------------------ +# TEA_SETUP_COMPILER_CC -- +# +# Do compiler checks the way we want. This is just a replacement +# for AC_PROG_CC in TEA configure.in files to make them cleaner. +# +# Arguments: +# none +# +# Results: +# +# Sets up CC var and other standard bits we need to make executables. +#------------------------------------------------------------------------ +AC_DEFUN([TEA_SETUP_COMPILER_CC], [ + # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE) + # in this macro, they need to go into TEA_SETUP_COMPILER instead. + + # If the user did not set CFLAGS, set it now to keep + # the AC_PROG_CC macro from adding "-g -O2". + if test "${CFLAGS+set}" != "set" ; then + CFLAGS="" + fi + + AC_PROG_CC + AC_PROG_CPP + + AC_PROG_INSTALL + + #-------------------------------------------------------------------- + # Checks to see if the make program sets the $MAKE variable. + #-------------------------------------------------------------------- + + AC_PROG_MAKE_SET + + #-------------------------------------------------------------------- + # Find ranlib + #-------------------------------------------------------------------- + + AC_PROG_RANLIB + + #-------------------------------------------------------------------- + # Determines the correct binary file extension (.o, .obj, .exe etc.) + #-------------------------------------------------------------------- + + AC_OBJEXT + AC_EXEEXT +]) + +#------------------------------------------------------------------------ +# TEA_SETUP_COMPILER -- +# +# Do compiler checks that use the compiler. This must go after +# TEA_SETUP_COMPILER_CC, which does the actual compiler check. +# +# Arguments: +# none +# +# Results: +# +# Sets up CC var and other standard bits we need to make executables. +#------------------------------------------------------------------------ +AC_DEFUN([TEA_SETUP_COMPILER], [ + # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here. + AC_REQUIRE([TEA_SETUP_COMPILER_CC]) + + #------------------------------------------------------------------------ + # If we're using GCC, see if the compiler understands -pipe. If so, use it. + # It makes compiling go faster. (This is only a performance feature.) + #------------------------------------------------------------------------ + + if test -z "$no_pipe" -a -n "$GCC"; then + AC_CACHE_CHECK([if the compiler understands -pipe], + tcl_cv_cc_pipe, [ + hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe" + AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no) + CFLAGS=$hold_cflags]) + if test $tcl_cv_cc_pipe = yes; then + CFLAGS="$CFLAGS -pipe" + fi + fi + + #-------------------------------------------------------------------- + # Common compiler flag setup + #-------------------------------------------------------------------- + + AC_C_BIGENDIAN + if test "${TEA_PLATFORM}" = "unix" ; then + TEA_TCL_LINK_LIBS + TEA_MISSING_POSIX_HEADERS + # Let the user call this, because if it triggers, they will + # need a compat/strtod.c that is correct. Users can also + # use Tcl_GetDouble(FromObj) instead. + #TEA_BUGGY_STRTOD + fi +]) + +#------------------------------------------------------------------------ +# TEA_MAKE_LIB -- +# +# Generate a line that can be used to build a shared/unshared library +# in a platform independent manner. +# +# Arguments: +# none +# +# Requires: +# +# Results: +# +# Defines the following vars: +# CFLAGS - Done late here to note disturb other AC macros +# MAKE_LIB - Command to execute to build the Tcl library; +# differs depending on whether or not Tcl is being +# compiled as a shared library. +# MAKE_SHARED_LIB Makefile rule for building a shared library +# MAKE_STATIC_LIB Makefile rule for building a static library +# MAKE_STUB_LIB Makefile rule for building a stub library +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_MAKE_LIB], [ + if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then + MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)" + MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)" + MAKE_STUB_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_STUB_OBJECTS)" + else + MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)" + MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}" + MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)" + fi + + if test "${SHARED_BUILD}" = "1" ; then + MAKE_LIB="${MAKE_SHARED_LIB} " + else + MAKE_LIB="${MAKE_STATIC_LIB} " + fi + + #-------------------------------------------------------------------- + # Shared libraries and static libraries have different names. + # Use the double eval to make sure any variables in the suffix is + # substituted. (@@@ Might not be necessary anymore) + #-------------------------------------------------------------------- + + if test "${TEA_PLATFORM}" = "windows" ; then + if test "${SHARED_BUILD}" = "1" ; then + # We force the unresolved linking of symbols that are really in + # the private libraries of Tcl and Tk. + SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\"" + if test x"${TK_BIN_DIR}" != x ; then + SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\"" + fi + eval eval "PKG_LIB_FILE=${PACKAGE_NAME}${SHARED_LIB_SUFFIX}" + else + eval eval "PKG_LIB_FILE=${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}" + fi + # Some packages build their own stubs libraries + eval eval "PKG_STUB_LIB_FILE=${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}" + if test "$GCC" = "yes"; then + PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE} + fi + # These aren't needed on Windows (either MSVC or gcc) + RANLIB=: + RANLIB_STUB=: + else + RANLIB_STUB="${RANLIB}" + if test "${SHARED_BUILD}" = "1" ; then + SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}" + if test x"${TK_BIN_DIR}" != x ; then + SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}" + fi + eval eval "PKG_LIB_FILE=lib${PACKAGE_NAME}${SHARED_LIB_SUFFIX}" + RANLIB=: + else + eval eval "PKG_LIB_FILE=lib${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}" + fi + # Some packages build their own stubs libraries + eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}" + fi + + # These are escaped so that only CFLAGS is picked up at configure time. + # The other values will be substituted at make time. + CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}" + if test "${SHARED_BUILD}" = "1" ; then + CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}" + fi + + AC_SUBST(MAKE_LIB) + AC_SUBST(MAKE_SHARED_LIB) + AC_SUBST(MAKE_STATIC_LIB) + AC_SUBST(MAKE_STUB_LIB) + AC_SUBST(RANLIB_STUB) +]) + +#------------------------------------------------------------------------ +# TEA_LIB_SPEC -- +# +# Compute the name of an existing object library located in libdir +# from the given base name and produce the appropriate linker flags. +# +# Arguments: +# basename The base name of the library without version +# numbers, extensions, or "lib" prefixes. +# extra_dir Extra directory in which to search for the +# library. This location is used first, then +# $prefix/$exec-prefix, then some defaults. +# +# Requires: +# TEA_INIT and TEA_PREFIX must be called first. +# +# Results: +# +# Defines the following vars: +# ${basename}_LIB_NAME The computed library name. +# ${basename}_LIB_SPEC The computed linker flags. +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_LIB_SPEC], [ + AC_MSG_CHECKING([for $1 library]) + + # Look in exec-prefix for the library (defined by TEA_PREFIX). + + tea_lib_name_dir="${exec_prefix}/lib" + + # Or in a user-specified location. + + if test x"$2" != x ; then + tea_extra_lib_dir=$2 + else + tea_extra_lib_dir=NONE + fi + + for i in \ + `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \ + `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \ + `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \ + `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \ + `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \ + `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \ + `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \ + `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \ + `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \ + `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do + if test -f "$i" ; then + tea_lib_name_dir=`dirname $i` + $1_LIB_NAME=`basename $i` + $1_LIB_PATH_NAME=$i + break + fi + done + + if test "${TEA_PLATFORM}" = "windows"; then + $1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\" + else + # Strip off the leading "lib" and trailing ".a" or ".so" + + tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'` + $1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}" + fi + + if test "x${$1_LIB_NAME}" = x ; then + AC_MSG_ERROR([not found]) + else + AC_MSG_RESULT([${$1_LIB_SPEC}]) + fi +]) + +#------------------------------------------------------------------------ +# TEA_PRIVATE_TCL_HEADERS -- +# +# Locate the private Tcl include files +# +# Arguments: +# +# Requires: +# TCL_SRC_DIR Assumes that TEA_LOAD_TCLCONFIG has +# already been called. +# +# Results: +# +# Substs the following vars: +# TCL_TOP_DIR_NATIVE +# TCL_INCLUDES +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [ + # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh} + AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS]) + AC_MSG_CHECKING([for Tcl private include files]) + + TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}` + TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\" + + # Check to see if tclPort.h isn't already with the public headers + # Don't look for tclInt.h because that resides with tcl.h in the core + # sources, but the Port headers are in a different directory + if test "${TEA_PLATFORM}" = "windows" -a \ + -f "${ac_cv_c_tclh}/tclWinPort.h"; then + result="private headers found with public headers" + elif test "${TEA_PLATFORM}" = "unix" -a \ + -f "${ac_cv_c_tclh}/tclUnixPort.h"; then + result="private headers found with public headers" + else + TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\" + if test "${TEA_PLATFORM}" = "windows"; then + TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\" + else + TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\" + fi + # Overwrite the previous TCL_INCLUDES as this should capture both + # public and private headers in the same set. + # We want to ensure these are substituted so as not to require + # any *_NATIVE vars be defined in the Makefile + TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}" + if test "`uname -s`" = "Darwin"; then + # If Tcl was built as a framework, attempt to use + # the framework's Headers and PrivateHeaders directories + case ${TCL_DEFS} in + *TCL_FRAMEWORK*) + if test -d "${TCL_BIN_DIR}/Headers" -a \ + -d "${TCL_BIN_DIR}/PrivateHeaders"; then + TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}" + else + TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`" + fi + ;; + esac + result="Using ${TCL_INCLUDES}" + else + if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then + AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}]) + fi + result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}" + fi + fi + + AC_SUBST(TCL_TOP_DIR_NATIVE) + + AC_SUBST(TCL_INCLUDES) + AC_MSG_RESULT([${result}]) +]) + +#------------------------------------------------------------------------ +# TEA_PUBLIC_TCL_HEADERS -- +# +# Locate the installed public Tcl header files +# +# Arguments: +# None. +# +# Requires: +# CYGPATH must be set +# +# Results: +# +# Adds a --with-tclinclude switch to configure. +# Result is cached. +# +# Substs the following vars: +# TCL_INCLUDES +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [ + AC_MSG_CHECKING([for Tcl public headers]) + + AC_ARG_WITH(tclinclude, [ --with-tclinclude directory containing the public Tcl header files], with_tclinclude=${withval}) + + AC_CACHE_VAL(ac_cv_c_tclh, [ + # Use the value from --with-tclinclude, if it was given + + if test x"${with_tclinclude}" != x ; then + if test -f "${with_tclinclude}/tcl.h" ; then + ac_cv_c_tclh=${with_tclinclude} + else + AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h]) + fi + else + list="" + if test "`uname -s`" = "Darwin"; then + # If Tcl was built as a framework, attempt to use + # the framework's Headers directory + case ${TCL_DEFS} in + *TCL_FRAMEWORK*) + list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`" + ;; + esac + fi + + # Look in the source dir only if Tcl is not installed, + # and in that situation, look there before installed locations. + if test -f "${TCL_BIN_DIR}/Makefile" ; then + list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`" + fi + + # Check order: pkg --prefix location, Tcl's --prefix location, + # relative to directory of tclConfig.sh. + + eval "temp_includedir=${includedir}" + list="$list \ + `ls -d ${temp_includedir} 2>/dev/null` \ + `ls -d ${TCL_PREFIX}/include 2>/dev/null` \ + `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`" + if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then + list="$list /usr/local/include /usr/include" + if test x"${TCL_INCLUDE_SPEC}" != x ; then + d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'` + list="$list `ls -d ${d} 2>/dev/null`" + fi + fi + for i in $list ; do + if test -f "$i/tcl.h" ; then + ac_cv_c_tclh=$i + break + fi + done + fi + ]) + + # Print a message based on how we determined the include path + + if test x"${ac_cv_c_tclh}" = x ; then + AC_MSG_ERROR([tcl.h not found. Please specify its location with --with-tclinclude]) + else + AC_MSG_RESULT([${ac_cv_c_tclh}]) + fi + + # Convert to a native path and substitute into the output files. + + INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}` + + TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\" + + AC_SUBST(TCL_INCLUDES) +]) + +#------------------------------------------------------------------------ +# TEA_PRIVATE_TK_HEADERS -- +# +# Locate the private Tk include files +# +# Arguments: +# +# Requires: +# TK_SRC_DIR Assumes that TEA_LOAD_TKCONFIG has +# already been called. +# +# Results: +# +# Substs the following vars: +# TK_INCLUDES +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [ + # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh} + AC_REQUIRE([TEA_PUBLIC_TK_HEADERS]) + AC_MSG_CHECKING([for Tk private include files]) + + TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}` + TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\" + + # Check to see if tkPort.h isn't already with the public headers + # Don't look for tkInt.h because that resides with tk.h in the core + # sources, but the Port headers are in a different directory + if test "${TEA_PLATFORM}" = "windows" -a \ + -f "${ac_cv_c_tkh}/tkWinPort.h"; then + result="private headers found with public headers" + elif test "${TEA_PLATFORM}" = "unix" -a \ + -f "${ac_cv_c_tkh}/tkUnixPort.h"; then + result="private headers found with public headers" + else + TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\" + TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\" + if test "${TEA_PLATFORM}" = "windows"; then + TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\" + else + TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\" + fi + # Overwrite the previous TK_INCLUDES as this should capture both + # public and private headers in the same set. + # We want to ensure these are substituted so as not to require + # any *_NATIVE vars be defined in the Makefile + TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}" + # Detect and add ttk subdir + if test -d "${TK_SRC_DIR}/generic/ttk"; then + TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\"" + fi + if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then + TK_INCLUDES="${TK_INCLUDES} -I\"${TK_XLIB_DIR_NATIVE}\"" + fi + if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then + TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\"" + fi + if test "`uname -s`" = "Darwin"; then + # If Tk was built as a framework, attempt to use + # the framework's Headers and PrivateHeaders directories + case ${TK_DEFS} in + *TK_FRAMEWORK*) + if test -d "${TK_BIN_DIR}/Headers" -a \ + -d "${TK_BIN_DIR}/PrivateHeaders"; then + TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}" + else + TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`" + fi + ;; + esac + result="Using ${TK_INCLUDES}" + else + if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then + AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}]) + fi + result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}" + fi + fi + + AC_SUBST(TK_TOP_DIR_NATIVE) + AC_SUBST(TK_XLIB_DIR_NATIVE) + + AC_SUBST(TK_INCLUDES) + AC_MSG_RESULT([${result}]) +]) + +#------------------------------------------------------------------------ +# TEA_PUBLIC_TK_HEADERS -- +# +# Locate the installed public Tk header files +# +# Arguments: +# None. +# +# Requires: +# CYGPATH must be set +# +# Results: +# +# Adds a --with-tkinclude switch to configure. +# Result is cached. +# +# Substs the following vars: +# TK_INCLUDES +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [ + AC_MSG_CHECKING([for Tk public headers]) + + AC_ARG_WITH(tkinclude, [ --with-tkinclude directory containing the public Tk header files], with_tkinclude=${withval}) + + AC_CACHE_VAL(ac_cv_c_tkh, [ + # Use the value from --with-tkinclude, if it was given + + if test x"${with_tkinclude}" != x ; then + if test -f "${with_tkinclude}/tk.h" ; then + ac_cv_c_tkh=${with_tkinclude} + else + AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h]) + fi + else + list="" + if test "`uname -s`" = "Darwin"; then + # If Tk was built as a framework, attempt to use + # the framework's Headers directory. + case ${TK_DEFS} in + *TK_FRAMEWORK*) + list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`" + ;; + esac + fi + + # Look in the source dir only if Tk is not installed, + # and in that situation, look there before installed locations. + if test -f "${TK_BIN_DIR}/Makefile" ; then + list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`" + fi + + # Check order: pkg --prefix location, Tk's --prefix location, + # relative to directory of tkConfig.sh, Tcl's --prefix location, + # relative to directory of tclConfig.sh. + + eval "temp_includedir=${includedir}" + list="$list \ + `ls -d ${temp_includedir} 2>/dev/null` \ + `ls -d ${TK_PREFIX}/include 2>/dev/null` \ + `ls -d ${TK_BIN_DIR}/../include 2>/dev/null` \ + `ls -d ${TCL_PREFIX}/include 2>/dev/null` \ + `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`" + if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then + list="$list /usr/local/include /usr/include" + if test x"${TK_INCLUDE_SPEC}" != x ; then + d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'` + list="$list `ls -d ${d} 2>/dev/null`" + fi + fi + for i in $list ; do + if test -f "$i/tk.h" ; then + ac_cv_c_tkh=$i + break + fi + done + fi + ]) + + # Print a message based on how we determined the include path + + if test x"${ac_cv_c_tkh}" = x ; then + AC_MSG_ERROR([tk.h not found. Please specify its location with --with-tkinclude]) + else + AC_MSG_RESULT([${ac_cv_c_tkh}]) + fi + + # Convert to a native path and substitute into the output files. + + INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}` + + TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\" + + AC_SUBST(TK_INCLUDES) + + if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then + # On Windows and Aqua, we need the X compat headers + AC_MSG_CHECKING([for X11 header files]) + if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then + INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`" + TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\" + AC_SUBST(TK_XINCLUDES) + fi + AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}]) + fi +]) + +#------------------------------------------------------------------------ +# TEA_PATH_CONFIG -- +# +# Locate the ${1}Config.sh file and perform a sanity check on +# the ${1} compile flags. These are used by packages like +# [incr Tk] that load *Config.sh files from more than Tcl and Tk. +# +# Arguments: +# none +# +# Results: +# +# Adds the following arguments to configure: +# --with-$1=... +# +# Defines the following vars: +# $1_BIN_DIR Full path to the directory containing +# the $1Config.sh file +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PATH_CONFIG], [ + # + # Ok, lets find the $1 configuration + # First, look for one uninstalled. + # the alternative search directory is invoked by --with-$1 + # + + if test x"${no_$1}" = x ; then + # we reset no_$1 in case something fails here + no_$1=true + AC_ARG_WITH($1, [ --with-$1 directory containing $1 configuration ($1Config.sh)], with_$1config=${withval}) + AC_MSG_CHECKING([for $1 configuration]) + AC_CACHE_VAL(ac_cv_c_$1config,[ + + # First check to see if --with-$1 was specified. + if test x"${with_$1config}" != x ; then + case ${with_$1config} in + */$1Config.sh ) + if test -f ${with_$1config}; then + AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself]) + with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'` + fi;; + esac + if test -f "${with_$1config}/$1Config.sh" ; then + ac_cv_c_$1config=`(cd ${with_$1config}; pwd)` + else + AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh]) + fi + fi + + # then check for a private $1 installation + if test x"${ac_cv_c_$1config}" = x ; then + for i in \ + ../$1 \ + `ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \ + `ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \ + `ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \ + ../../$1 \ + `ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \ + `ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \ + `ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \ + ../../../$1 \ + `ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \ + `ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \ + `ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \ + ${srcdir}/../$1 \ + `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \ + `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \ + `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \ + ; do + if test -f "$i/$1Config.sh" ; then + ac_cv_c_$1config=`(cd $i; pwd)` + break + fi + if test -f "$i/unix/$1Config.sh" ; then + ac_cv_c_$1config=`(cd $i/unix; pwd)` + break + fi + done + fi + + # check in a few common install locations + if test x"${ac_cv_c_$1config}" = x ; then + for i in `ls -d ${libdir} 2>/dev/null` \ + `ls -d ${exec_prefix}/lib 2>/dev/null` \ + `ls -d ${prefix}/lib 2>/dev/null` \ + `ls -d /usr/local/lib 2>/dev/null` \ + `ls -d /usr/contrib/lib 2>/dev/null` \ + `ls -d /usr/lib 2>/dev/null` \ + `ls -d /usr/lib64 2>/dev/null` \ + ; do + if test -f "$i/$1Config.sh" ; then + ac_cv_c_$1config=`(cd $i; pwd)` + break + fi + done + fi + ]) + + if test x"${ac_cv_c_$1config}" = x ; then + $1_BIN_DIR="# no $1 configs found" + AC_MSG_WARN([Cannot find $1 configuration definitions]) + exit 0 + else + no_$1= + $1_BIN_DIR=${ac_cv_c_$1config} + AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh]) + fi + fi +]) + +#------------------------------------------------------------------------ +# TEA_LOAD_CONFIG -- +# +# Load the $1Config.sh file +# +# Arguments: +# +# Requires the following vars to be set: +# $1_BIN_DIR +# +# Results: +# +# Subst the following vars: +# $1_SRC_DIR +# $1_LIB_FILE +# $1_LIB_SPEC +# +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_LOAD_CONFIG], [ + AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh]) + + if test -f "${$1_BIN_DIR}/$1Config.sh" ; then + AC_MSG_RESULT([loading]) + . "${$1_BIN_DIR}/$1Config.sh" + else + AC_MSG_RESULT([file not found]) + fi + + # + # If the $1_BIN_DIR is the build directory (not the install directory), + # then set the common variable name to the value of the build variables. + # For example, the variable $1_LIB_SPEC will be set to the value + # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC + # instead of $1_BUILD_LIB_SPEC since it will work with both an + # installed and uninstalled version of Tcl. + # + + if test -f "${$1_BIN_DIR}/Makefile" ; then + AC_MSG_WARN([Found Makefile - using build library specs for $1]) + $1_LIB_SPEC=${$1_BUILD_LIB_SPEC} + $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC} + $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH} + fi + + AC_SUBST($1_VERSION) + AC_SUBST($1_BIN_DIR) + AC_SUBST($1_SRC_DIR) + + AC_SUBST($1_LIB_FILE) + AC_SUBST($1_LIB_SPEC) + + AC_SUBST($1_STUB_LIB_FILE) + AC_SUBST($1_STUB_LIB_SPEC) + AC_SUBST($1_STUB_LIB_PATH) + + # Allow the caller to prevent this auto-check by specifying any 2nd arg + AS_IF([test "x$2" = x], [ + # Check both upper and lower-case variants + # If a dev wanted non-stubs libs, this function could take an option + # to not use _STUB in the paths below + AS_IF([test "x${$1_STUB_LIB_SPEC}" = x], + [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)], + [TEA_LOAD_CONFIG_LIB($1_STUB)]) + ]) +]) + +#------------------------------------------------------------------------ +# TEA_LOAD_CONFIG_LIB -- +# +# Helper function to load correct library from another extension's +# ${PACKAGE}Config.sh. +# +# Results: +# Adds to LIBS the appropriate extension library +# +#------------------------------------------------------------------------ +AC_DEFUN([TEA_LOAD_CONFIG_LIB], [ + AC_MSG_CHECKING([For $1 library for LIBS]) + # This simplifies the use of stub libraries by automatically adding + # the stub lib to your path. Normally this would add to SHLIB_LD_LIBS, + # but this is called before CONFIG_CFLAGS. More importantly, this adds + # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD. + if test "x${$1_LIB_SPEC}" != "x" ; then + if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then + TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"]) + AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}]) + else + TEA_ADD_LIBS([${$1_LIB_SPEC}]) + AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}]) + fi + else + AC_MSG_RESULT([file not found]) + fi +]) + +#------------------------------------------------------------------------ +# TEA_EXPORT_CONFIG -- +# +# Define the data to insert into the ${PACKAGE}Config.sh file +# +# Arguments: +# +# Requires the following vars to be set: +# $1 +# +# Results: +# Subst the following vars: +# +#------------------------------------------------------------------------ + +AC_DEFUN(TEA_EXPORT_CONFIG, [ + #-------------------------------------------------------------------- + # These are for $1Config.sh + #-------------------------------------------------------------------- + + # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib) + eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}" + if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then + eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}" + eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}" + else + eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}" + eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}" + fi + $1_BUILD_LIB_SPEC="-L`pwd` ${$1_LIB_FLAG}" + $1_LIB_SPEC="-L${pkglibdir} ${$1_LIB_FLAG}" + $1_BUILD_STUB_LIB_SPEC="-L`pwd` [$]{$1_STUB_LIB_FLAG}" + $1_STUB_LIB_SPEC="-L${pkglibdir} [$]{$1_STUB_LIB_FLAG}" + $1_BUILD_STUB_LIB_PATH="`pwd`/[$]{PKG_STUB_LIB_FILE}" + $1_STUB_LIB_PATH="${pkglibdir}/[$]{PKG_STUB_LIB_FILE}" + + AC_SUBST($1_BUILD_LIB_SPEC) + AC_SUBST($1_LIB_SPEC) + AC_SUBST($1_BUILD_STUB_LIB_SPEC) + AC_SUBST($1_STUB_LIB_SPEC) + AC_SUBST($1_BUILD_STUB_LIB_PATH) + AC_SUBST($1_STUB_LIB_PATH) + + AC_SUBST(MAJOR_VERSION) + AC_SUBST(MINOR_VERSION) + AC_SUBST(PATCHLEVEL) +]) + + +#------------------------------------------------------------------------ +# TEA_PATH_CELIB -- +# +# Locate Keuchel's celib emulation layer for targeting Win/CE +# +# Arguments: +# none +# +# Results: +# +# Adds the following arguments to configure: +# --with-celib=... +# +# Defines the following vars: +# CELIB_DIR Full path to the directory containing +# the include and platform lib files +#------------------------------------------------------------------------ + +AC_DEFUN([TEA_PATH_CELIB], [ + # First, look for one uninstalled. + # the alternative search directory is invoked by --with-celib + + if test x"${no_celib}" = x ; then + # we reset no_celib in case something fails here + no_celib=true + AC_ARG_WITH(celib,[ --with-celib=DIR use Windows/CE support library from DIR], with_celibconfig=${withval}) + AC_MSG_CHECKING([for Windows/CE celib directory]) + AC_CACHE_VAL(ac_cv_c_celibconfig,[ + # First check to see if --with-celibconfig was specified. + if test x"${with_celibconfig}" != x ; then + if test -d "${with_celibconfig}/inc" ; then + ac_cv_c_celibconfig=`(cd ${with_celibconfig}; pwd)` + else + AC_MSG_ERROR([${with_celibconfig} directory doesn't contain inc directory]) + fi + fi + + # then check for a celib library + if test x"${ac_cv_c_celibconfig}" = x ; then + for i in \ + ../celib-palm-3.0 \ + ../celib \ + ../../celib-palm-3.0 \ + ../../celib \ + `ls -dr ../celib-*3.[[0-9]]* 2>/dev/null` \ + ${srcdir}/../celib-palm-3.0 \ + ${srcdir}/../celib \ + `ls -dr ${srcdir}/../celib-*3.[[0-9]]* 2>/dev/null` \ + ; do + if test -d "$i/inc" ; then + ac_cv_c_celibconfig=`(cd $i; pwd)` + break + fi + done + fi + ]) + if test x"${ac_cv_c_celibconfig}" = x ; then + AC_MSG_ERROR([Cannot find celib support library directory]) + else + no_celib= + CELIB_DIR=${ac_cv_c_celibconfig} + CELIB_DIR=`echo "$CELIB_DIR" | sed -e 's!\\\!/!g'` + AC_MSG_RESULT([found $CELIB_DIR]) + fi + fi +]) + + +# Local Variables: +# mode: autoconf +# End: diff --git a/components/external/SQLite-3.8.1/autoconf/tea/win/makefile.vc b/components/external/SQLite-3.8.1/autoconf/tea/win/makefile.vc new file mode 100644 index 0000000000000000000000000000000000000000..a5e462770721e8673f2cb7e7009847b4280d32ee --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/win/makefile.vc @@ -0,0 +1,414 @@ +# makefile.vc -- -*- Makefile -*- +# +# Microsoft Visual C++ makefile for use with nmake.exe v1.62+ (VC++ 5.0+) +# +# This makefile is based upon the Tcl 8.4 Makefile.vc and modified to +# make it suitable as a general package makefile. Look for the word EDIT +# which marks sections that may need modification. As a minumum you will +# need to change the PROJECT, DOTVERSION and DLLOBJS variables to values +# relevant to your package. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# Copyright (c) 1995-1996 Sun Microsystems, Inc. +# Copyright (c) 1998-2000 Ajuba Solutions. +# Copyright (c) 2001 ActiveState Corporation. +# Copyright (c) 2001-2002 David Gravereaux. +# Copyright (c) 2003 Pat Thoyts +# +#------------------------------------------------------------------------- +# RCS: @(#)$Id: makefile.vc,v 1.4 2004/07/26 08:22:05 patthoyts Exp $ +#------------------------------------------------------------------------- + +!if !defined(MSDEVDIR) && !defined(MSVCDIR) && !defined(VCINSTALLDIR) && !defined(MSSDK) && !defined(WINDOWSSDKDIR) +MSG = ^ +You will need to run vcvars32.bat from Developer Studio, first, to setup^ +the environment. Jump to this line to read the new instructions. +!error $(MSG) +!endif + +#------------------------------------------------------------------------------ +# HOW TO USE this makefile: +# +# 1) It is now necessary to have %MSVCDir% set in the environment. This is +# used as a check to see if vcvars32.bat had been run prior to running +# nmake or during the installation of Microsoft Visual C++, MSVCDir had +# been set globally and the PATH adjusted. Either way is valid. +# +# You'll need to run vcvars32.bat contained in the MsDev's vc(98)/bin +# directory to setup the proper environment, if needed, for your current +# setup. This is a needed bootstrap requirement and allows the swapping of +# different environments to be easier. +# +# 2) To use the Platform SDK (not expressly needed), run setenv.bat after +# vcvars32.bat according to the instructions for it. This can also turn on +# the 64-bit compiler, if your SDK has it. +# +# 3) Targets are: +# all -- Builds everything. +# -- Builds the project (eg: nmake sample) +# test -- Builds and runs the test suite. +# install -- Installs the built binaries and libraries to $(INSTALLDIR) +# in an appropriate subdirectory. +# clean/realclean/distclean -- varying levels of cleaning. +# +# 4) Macros usable on the commandline: +# INSTALLDIR= +# Sets where to install Tcl from the built binaries. +# C:\Progra~1\Tcl is assumed when not specified. +# +# OPTS=static,msvcrt,staticpkg,threads,symbols,profile,loimpact,none +# Sets special options for the core. The default is for none. +# Any combination of the above may be used (comma separated). +# 'none' will over-ride everything to nothing. +# +# static = Builds a static library of the core instead of a +# dll. The shell will be static (and large), as well. +# msvcrt = Effects the static option only to switch it from +# using libcmt(d) as the C runtime [by default] to +# msvcrt(d). This is useful for static embedding +# support. +# staticpkg = Effects the static option only to switch +# tclshXX.exe to have the dde and reg extension linked +# inside it. +# threads = Turns on full multithreading support. +# thrdalloc = Use the thread allocator (shared global free pool). +# symbols = Adds symbols for step debugging. +# profile = Adds profiling hooks. Map file is assumed. +# loimpact = Adds a flag for how NT treats the heap to keep memory +# in use, low. This is said to impact alloc performance. +# +# STATS=memdbg,compdbg,none +# Sets optional memory and bytecode compiler debugging code added +# to the core. The default is for none. Any combination of the +# above may be used (comma separated). 'none' will over-ride +# everything to nothing. +# +# memdbg = Enables the debugging memory allocator. +# compdbg = Enables byte compilation logging. +# +# MACHINE=(IX86|IA64|ALPHA) +# Set the machine type used for the compiler, linker, and +# resource compiler. This hook is needed to tell the tools +# when alternate platforms are requested. IX86 is the default +# when not specified. +# +# TMP_DIR= +# OUT_DIR= +# Hooks to allow the intermediate and output directories to be +# changed. $(OUT_DIR) is assumed to be +# $(BINROOT)\(Release|Debug) based on if symbols are requested. +# $(TMP_DIR) will de $(OUT_DIR)\ by default. +# +# TESTPAT= +# Reads the tests requested to be run from this file. +# +# CFG_ENCODING=encoding +# name of encoding for configuration information. Defaults +# to cp1252 +# +# 5) Examples: +# +# Basic syntax of calling nmake looks like this: +# nmake [-nologo] -f makefile.vc [target|macrodef [target|macrodef] [...]] +# +# Standard (no frills) +# c:\tcl_src\win\>c:\progra~1\micros~1\vc98\bin\vcvars32.bat +# Setting environment for using Microsoft Visual C++ tools. +# c:\tcl_src\win\>nmake -f makefile.vc all +# c:\tcl_src\win\>nmake -f makefile.vc install INSTALLDIR=c:\progra~1\tcl +# +# Building for Win64 +# c:\tcl_src\win\>c:\progra~1\micros~1\vc98\bin\vcvars32.bat +# Setting environment for using Microsoft Visual C++ tools. +# c:\tcl_src\win\>c:\progra~1\platfo~1\setenv.bat /pre64 /RETAIL +# Targeting Windows pre64 RETAIL +# c:\tcl_src\win\>nmake -f makefile.vc MACHINE=IA64 +# +#------------------------------------------------------------------------------ +#============================================================================== +############################################################################### +#------------------------------------------------------------------------------ + +!if !exist("makefile.vc") +MSG = ^ +You must run this makefile only from the directory it is in.^ +Please `cd` to its location first. +!error $(MSG) +!endif + +#------------------------------------------------------------------------- +# Project specific information (EDIT) +# +# You should edit this with the name and version of your project. This +# information is used to generate the name of the package library and +# it's install location. +# +# For example, the sample extension is going to build sample04.dll and +# would install it into $(INSTALLDIR)\lib\sample04 +# +# You need to specify the object files that need to be linked into your +# binary here. +# +#------------------------------------------------------------------------- + +PROJECT = sqlite3 +!include "rules.vc" + +# nmakehelp -V will search the file for tag, skips until a +# number and returns all character until a character not in [0-9.ab] +# is read. + +!if [echo REM = This file is generated from Makefile.vc > versions.vc] +!endif +# get project version from row "AC_INIT([sqlite], [3.7.14])" +!if [echo DOTVERSION = \>> versions.vc] \ + && [nmakehlp -V ..\configure.in AC_INIT >> versions.vc] +!endif +!include "versions.vc" + +VERSION = $(DOTVERSION:.=) +STUBPREFIX = $(PROJECT)stub + +DLLOBJS = \ + $(TMP_DIR)\tclsqlite3.obj + +#------------------------------------------------------------------------- +# Target names and paths ( shouldn't need changing ) +#------------------------------------------------------------------------- + +BINROOT = . +ROOT = .. + +PRJIMPLIB = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib +PRJLIBNAME = $(PROJECT)$(VERSION)$(SUFX).$(EXT) +PRJLIB = $(OUT_DIR)\$(PRJLIBNAME) + +PRJSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib +PRJSTUBLIB = $(OUT_DIR)\$(PRJSTUBLIBNAME) + +### Make sure we use backslash only. +PRJ_INSTALL_DIR = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION) +LIB_INSTALL_DIR = $(PRJ_INSTALL_DIR) +BIN_INSTALL_DIR = $(PRJ_INSTALL_DIR) +DOC_INSTALL_DIR = $(PRJ_INSTALL_DIR) +SCRIPT_INSTALL_DIR = $(PRJ_INSTALL_DIR) +INCLUDE_INSTALL_DIR = $(_TCLDIR)\include + +### The following paths CANNOT have spaces in them. +GENERICDIR = $(ROOT)\generic +WINDIR = $(ROOT)\win +LIBDIR = $(ROOT)\library +DOCDIR = $(ROOT)\doc +TOOLSDIR = $(ROOT)\tools +COMPATDIR = $(ROOT)\compat + +#--------------------------------------------------------------------- +# Compile flags +#--------------------------------------------------------------------- + +!if !$(DEBUG) +!if $(OPTIMIZING) +### This cranks the optimization level to maximize speed +cdebug = -O2 -Op -Gs +!else +cdebug = +!endif +!else if "$(MACHINE)" == "IA64" +### Warnings are too many, can't support warnings into errors. +cdebug = -Z7 -Od -GZ +!else +cdebug = -Z7 -WX -Od -GZ +!endif + +### Declarations common to all compiler options +cflags = -nologo -c -W3 -YX -Fp$(TMP_DIR)^\ + +!if $(MSVCRT) +!if $(DEBUG) +crt = -MDd +!else +crt = -MD +!endif +!else +!if $(DEBUG) +crt = -MTd +!else +crt = -MT +!endif +!endif + +INCLUDES = $(TCL_INCLUDES) -I"$(WINDIR)" -I"$(GENERICDIR)" \ + -I"$(ROOT)\.." +BASE_CLFAGS = $(cflags) $(cdebug) $(crt) $(INCLUDES) \ + -DSQLITE_3_SUFFIX_ONLY=1 -DSQLITE_ENABLE_RTREE=1 \ + -DSQLITE_ENABLE_FTS3=1 -DSQLITE_OMIT_DEPRECATED=1 +CON_CFLAGS = $(cflags) $(cdebug) $(crt) -DCONSOLE -DSQLITE_ENABLE_FTS3=1 +TCL_CFLAGS = -DBUILD_sqlite -DUSE_TCL_STUBS \ + -DPACKAGE_VERSION="\"$(DOTVERSION)\"" $(BASE_CLFAGS) \ + $(OPTDEFINES) + +#--------------------------------------------------------------------- +# Link flags +#--------------------------------------------------------------------- + +!if $(DEBUG) +ldebug = -debug:full -debugtype:cv +!else +ldebug = -release -opt:ref -opt:icf,3 +!endif + +### Declarations common to all linker options +lflags = -nologo -machine:$(MACHINE) $(ldebug) + +!if $(PROFILE) +lflags = $(lflags) -profile +!endif + +!if $(ALIGN98_HACK) && !$(STATIC_BUILD) +### Align sections for PE size savings. +lflags = $(lflags) -opt:nowin98 +!else if !$(ALIGN98_HACK) && $(STATIC_BUILD) +### Align sections for speed in loading by choosing the virtual page size. +lflags = $(lflags) -align:4096 +!endif + +!if $(LOIMPACT) +lflags = $(lflags) -ws:aggressive +!endif + +dlllflags = $(lflags) -dll +conlflags = $(lflags) -subsystem:console +guilflags = $(lflags) -subsystem:windows +baselibs = $(TCLSTUBLIB) + +#--------------------------------------------------------------------- +# TclTest flags +#--------------------------------------------------------------------- + +!IF "$(TESTPAT)" != "" +TESTFLAGS = $(TESTFLAGS) -file $(TESTPAT) +!ENDIF + +#--------------------------------------------------------------------- +# Project specific targets (EDIT) +#--------------------------------------------------------------------- + +all: setup $(PROJECT) +$(PROJECT): setup $(PRJLIB) +install: install-binaries install-libraries install-docs + +# Tests need to ensure we load the right dll file we +# have to handle the output differently on Win9x. +# +!if "$(OS)" == "Windows_NT" || "$(MSVCDIR)" == "IDE" +test: setup $(PROJECT) + set TCL_LIBRARY=$(ROOT)/library + $(TCLSH) << +load $(PRJLIB:\=/) +cd "$(ROOT)/tests" +set argv "$(TESTFLAGS)" +source all.tcl +<< +!else +test: setup $(PROJECT) + echo Please wait while the test results are collected + set TCL_LIBRARY=$(ROOT)/library + $(TCLSH) << >tests.log +load $(PRJLIB:\=/) +cd "$(ROOT)/tests" +set argv "$(TESTFLAGS)" +source all.tcl +<< + type tests.log | more +!endif + +setup: + @if not exist $(OUT_DIR)\nul mkdir $(OUT_DIR) + @if not exist $(TMP_DIR)\nul mkdir $(TMP_DIR) + +$(PRJLIB): $(DLLOBJS) + $(link32) $(dlllflags) -out:$@ $(baselibs) @<< +$** +<< + -@del $*.exp + +$(PRJSTUBLIB): $(PRJSTUBOBJS) + $(lib32) -nologo -out:$@ $(PRJSTUBOBJS) + +#--------------------------------------------------------------------- +# Implicit rules +#--------------------------------------------------------------------- + +{$(WINDIR)}.c{$(TMP_DIR)}.obj:: + $(cc32) $(TCL_CFLAGS) -DBUILD_$(PROJECT) -Fo$(TMP_DIR)\ @<< +$< +<< + +{$(GENERICDIR)}.c{$(TMP_DIR)}.obj:: + $(cc32) $(TCL_CFLAGS) -DBUILD_$(PROJECT) -Fo$(TMP_DIR)\ @<< +$< +<< + +{$(COMPATDIR)}.c{$(TMP_DIR)}.obj:: + $(cc32) $(TCL_CFLAGS) -DBUILD_$(PROJECT) -Fo$(TMP_DIR)\ @<< +$< +<< + +{$(WINDIR)}.rc{$(TMP_DIR)}.res: + $(rc32) -fo $@ -r -i "$(GENERICDIR)" -D__WIN32__ \ +!if $(DEBUG) + -d DEBUG \ +!endif +!if $(TCL_THREADS) + -d TCL_THREADS \ +!endif +!if $(STATIC_BUILD) + -d STATIC_BUILD \ +!endif + $< + +.SUFFIXES: +.SUFFIXES:.c .rc + +#--------------------------------------------------------------------- +# Installation. (EDIT) +# +# You may need to modify this section to reflect the final distribution +# of your files and possibly to generate documentation. +# +#--------------------------------------------------------------------- + +install-binaries: + @echo Installing binaries to '$(SCRIPT_INSTALL_DIR)' + @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)" + @$(CPY) $(PRJLIB) "$(SCRIPT_INSTALL_DIR)" >NUL + +install-libraries: + @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)' + @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)" + @echo Installing package index in '$(SCRIPT_INSTALL_DIR)' + @type << >"$(SCRIPT_INSTALL_DIR)\pkgIndex.tcl" +package ifneeded $(PROJECT) $(DOTVERSION) \ + [list load [file join $$dir $(PRJLIBNAME)] sqlite3] +<< + +install-docs: + @echo Installing documentation files to '$(DOC_INSTALL_DIR)' + @if exist $(DOCDIR) $(CPY) $(DOCDIR)\*.n "$(DOC_INSTALL_DIR)" + +#--------------------------------------------------------------------- +# Clean up +#--------------------------------------------------------------------- + +clean: + @if exist $(TMP_DIR)\nul $(RMDIR) $(TMP_DIR) + @if exist $(WINDIR)\version.vc del $(WINDIR)\version.vc + +realclean: clean + @if exist $(OUT_DIR)\nul $(RMDIR) $(OUT_DIR) + +distclean: realclean + @if exist $(WINDIR)\nmakehlp.exe del $(WINDIR)\nmakehlp.exe + @if exist $(WINDIR)\nmakehlp.obj del $(WINDIR)\nmakehlp.obj diff --git a/components/external/SQLite-3.8.1/autoconf/tea/win/nmakehlp.c b/components/external/SQLite-3.8.1/autoconf/tea/win/nmakehlp.c new file mode 100644 index 0000000000000000000000000000000000000000..2868857efd62776f0d3fc2c7d6b6c033b25cdc7a --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/win/nmakehlp.c @@ -0,0 +1,694 @@ +/* + * ---------------------------------------------------------------------------- + * nmakehlp.c -- + * + * This is used to fix limitations within nmake and the environment. + * + * Copyright (c) 2002 by David Gravereaux. + * Copyright (c) 2006 by Pat Thoyts + * + * See the file "license.terms" for information on usage and redistribution of + * this file, and for a DISCLAIMER OF ALL WARRANTIES. + * ---------------------------------------------------------------------------- + */ + +#define _CRT_SECURE_NO_DEPRECATE +#include +#define NO_SHLWAPI_GDI +#define NO_SHLWAPI_STREAM +#define NO_SHLWAPI_REG +#include +#pragma comment (lib, "user32.lib") +#pragma comment (lib, "kernel32.lib") +#pragma comment (lib, "shlwapi.lib") +#include +#include + +/* + * This library is required for x64 builds with _some_ versions of MSVC + */ +#if defined(_M_IA64) || defined(_M_AMD64) +#if _MSC_VER >= 1400 && _MSC_VER < 1500 +#pragma comment(lib, "bufferoverflowU") +#endif +#endif + +/* ISO hack for dumb VC++ */ +#ifdef _MSC_VER +#define snprintf _snprintf +#endif + + + +/* protos */ + +static int CheckForCompilerFeature(const char *option); +static int CheckForLinkerFeature(const char *option); +static int IsIn(const char *string, const char *substring); +static int SubstituteFile(const char *substs, const char *filename); +static int QualifyPath(const char *path); +static const char *GetVersionFromFile(const char *filename, const char *match); +static DWORD WINAPI ReadFromPipe(LPVOID args); + +/* globals */ + +#define CHUNK 25 +#define STATICBUFFERSIZE 1000 +typedef struct { + HANDLE pipe; + char buffer[STATICBUFFERSIZE]; +} pipeinfo; + +pipeinfo Out = {INVALID_HANDLE_VALUE, '\0'}; +pipeinfo Err = {INVALID_HANDLE_VALUE, '\0'}; + +/* + * exitcodes: 0 == no, 1 == yes, 2 == error + */ + +int +main( + int argc, + char *argv[]) +{ + char msg[300]; + DWORD dwWritten; + int chars; + + /* + * Make sure children (cl.exe and link.exe) are kept quiet. + */ + + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); + + /* + * Make sure the compiler and linker aren't effected by the outside world. + */ + + SetEnvironmentVariable("CL", ""); + SetEnvironmentVariable("LINK", ""); + + if (argc > 1 && *argv[1] == '-') { + switch (*(argv[1]+1)) { + case 'c': + if (argc != 3) { + chars = snprintf(msg, sizeof(msg) - 1, + "usage: %s -c \n" + "Tests for whether cl.exe supports an option\n" + "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]); + WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars, + &dwWritten, NULL); + return 2; + } + return CheckForCompilerFeature(argv[2]); + case 'l': + if (argc != 3) { + chars = snprintf(msg, sizeof(msg) - 1, + "usage: %s -l \n" + "Tests for whether link.exe supports an option\n" + "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]); + WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars, + &dwWritten, NULL); + return 2; + } + return CheckForLinkerFeature(argv[2]); + case 'f': + if (argc == 2) { + chars = snprintf(msg, sizeof(msg) - 1, + "usage: %s -f \n" + "Find a substring within another\n" + "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]); + WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars, + &dwWritten, NULL); + return 2; + } else if (argc == 3) { + /* + * If the string is blank, there is no match. + */ + + return 0; + } else { + return IsIn(argv[2], argv[3]); + } + case 's': + if (argc == 2) { + chars = snprintf(msg, sizeof(msg) - 1, + "usage: %s -s \n" + "Perform a set of string map type substutitions on a file\n" + "exitcodes: 0\n", + argv[0]); + WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars, + &dwWritten, NULL); + return 2; + } + return SubstituteFile(argv[2], argv[3]); + case 'V': + if (argc != 4) { + chars = snprintf(msg, sizeof(msg) - 1, + "usage: %s -V filename matchstring\n" + "Extract a version from a file:\n" + "eg: pkgIndex.tcl \"package ifneeded http\"", + argv[0]); + WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars, + &dwWritten, NULL); + return 0; + } + printf("%s\n", GetVersionFromFile(argv[2], argv[3])); + return 0; + case 'Q': + if (argc != 3) { + chars = snprintf(msg, sizeof(msg) - 1, + "usage: %s -Q path\n" + "Emit the fully qualified path\n" + "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]); + WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars, + &dwWritten, NULL); + return 2; + } + return QualifyPath(argv[2]); + } + } + chars = snprintf(msg, sizeof(msg) - 1, + "usage: %s -c|-f|-l|-Q|-s|-V ...\n" + "This is a little helper app to equalize shell differences between WinNT and\n" + "Win9x and get nmake.exe to accomplish its job.\n", + argv[0]); + WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars, &dwWritten, NULL); + return 2; +} + +static int +CheckForCompilerFeature( + const char *option) +{ + STARTUPINFO si; + PROCESS_INFORMATION pi; + SECURITY_ATTRIBUTES sa; + DWORD threadID; + char msg[300]; + BOOL ok; + HANDLE hProcess, h, pipeThreads[2]; + char cmdline[100]; + + hProcess = GetCurrentProcess(); + + ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); + ZeroMemory(&si, sizeof(STARTUPINFO)); + si.cb = sizeof(STARTUPINFO); + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = INVALID_HANDLE_VALUE; + + ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES)); + sa.nLength = sizeof(SECURITY_ATTRIBUTES); + sa.lpSecurityDescriptor = NULL; + sa.bInheritHandle = FALSE; + + /* + * Create a non-inheritible pipe. + */ + + CreatePipe(&Out.pipe, &h, &sa, 0); + + /* + * Dupe the write side, make it inheritible, and close the original. + */ + + DuplicateHandle(hProcess, h, hProcess, &si.hStdOutput, 0, TRUE, + DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE); + + /* + * Same as above, but for the error side. + */ + + CreatePipe(&Err.pipe, &h, &sa, 0); + DuplicateHandle(hProcess, h, hProcess, &si.hStdError, 0, TRUE, + DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE); + + /* + * Base command line. + */ + + lstrcpy(cmdline, "cl.exe -nologo -c -TC -Zs -X -Fp.\\_junk.pch "); + + /* + * Append our option for testing + */ + + lstrcat(cmdline, option); + + /* + * Filename to compile, which exists, but is nothing and empty. + */ + + lstrcat(cmdline, " .\\nul"); + + ok = CreateProcess( + NULL, /* Module name. */ + cmdline, /* Command line. */ + NULL, /* Process handle not inheritable. */ + NULL, /* Thread handle not inheritable. */ + TRUE, /* yes, inherit handles. */ + DETACHED_PROCESS, /* No console for you. */ + NULL, /* Use parent's environment block. */ + NULL, /* Use parent's starting directory. */ + &si, /* Pointer to STARTUPINFO structure. */ + &pi); /* Pointer to PROCESS_INFORMATION structure. */ + + if (!ok) { + DWORD err = GetLastError(); + int chars = snprintf(msg, sizeof(msg) - 1, + "Tried to launch: \"%s\", but got error [%u]: ", cmdline, err); + + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS| + FORMAT_MESSAGE_MAX_WIDTH_MASK, 0L, err, 0, (LPVOID)&msg[chars], + (300-chars), 0); + WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, lstrlen(msg), &err,NULL); + return 2; + } + + /* + * Close our references to the write handles that have now been inherited. + */ + + CloseHandle(si.hStdOutput); + CloseHandle(si.hStdError); + + WaitForInputIdle(pi.hProcess, 5000); + CloseHandle(pi.hThread); + + /* + * Start the pipe reader threads. + */ + + pipeThreads[0] = CreateThread(NULL, 0, ReadFromPipe, &Out, 0, &threadID); + pipeThreads[1] = CreateThread(NULL, 0, ReadFromPipe, &Err, 0, &threadID); + + /* + * Block waiting for the process to end. + */ + + WaitForSingleObject(pi.hProcess, INFINITE); + CloseHandle(pi.hProcess); + + /* + * Wait for our pipe to get done reading, should it be a little slow. + */ + + WaitForMultipleObjects(2, pipeThreads, TRUE, 500); + CloseHandle(pipeThreads[0]); + CloseHandle(pipeThreads[1]); + + /* + * Look for the commandline warning code in both streams. + * - in MSVC 6 & 7 we get D4002, in MSVC 8 we get D9002. + */ + + return !(strstr(Out.buffer, "D4002") != NULL + || strstr(Err.buffer, "D4002") != NULL + || strstr(Out.buffer, "D9002") != NULL + || strstr(Err.buffer, "D9002") != NULL + || strstr(Out.buffer, "D2021") != NULL + || strstr(Err.buffer, "D2021") != NULL); +} + +static int +CheckForLinkerFeature( + const char *option) +{ + STARTUPINFO si; + PROCESS_INFORMATION pi; + SECURITY_ATTRIBUTES sa; + DWORD threadID; + char msg[300]; + BOOL ok; + HANDLE hProcess, h, pipeThreads[2]; + char cmdline[100]; + + hProcess = GetCurrentProcess(); + + ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); + ZeroMemory(&si, sizeof(STARTUPINFO)); + si.cb = sizeof(STARTUPINFO); + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = INVALID_HANDLE_VALUE; + + ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES)); + sa.nLength = sizeof(SECURITY_ATTRIBUTES); + sa.lpSecurityDescriptor = NULL; + sa.bInheritHandle = TRUE; + + /* + * Create a non-inheritible pipe. + */ + + CreatePipe(&Out.pipe, &h, &sa, 0); + + /* + * Dupe the write side, make it inheritible, and close the original. + */ + + DuplicateHandle(hProcess, h, hProcess, &si.hStdOutput, 0, TRUE, + DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE); + + /* + * Same as above, but for the error side. + */ + + CreatePipe(&Err.pipe, &h, &sa, 0); + DuplicateHandle(hProcess, h, hProcess, &si.hStdError, 0, TRUE, + DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE); + + /* + * Base command line. + */ + + lstrcpy(cmdline, "link.exe -nologo "); + + /* + * Append our option for testing. + */ + + lstrcat(cmdline, option); + + ok = CreateProcess( + NULL, /* Module name. */ + cmdline, /* Command line. */ + NULL, /* Process handle not inheritable. */ + NULL, /* Thread handle not inheritable. */ + TRUE, /* yes, inherit handles. */ + DETACHED_PROCESS, /* No console for you. */ + NULL, /* Use parent's environment block. */ + NULL, /* Use parent's starting directory. */ + &si, /* Pointer to STARTUPINFO structure. */ + &pi); /* Pointer to PROCESS_INFORMATION structure. */ + + if (!ok) { + DWORD err = GetLastError(); + int chars = snprintf(msg, sizeof(msg) - 1, + "Tried to launch: \"%s\", but got error [%u]: ", cmdline, err); + + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS| + FORMAT_MESSAGE_MAX_WIDTH_MASK, 0L, err, 0, (LPVOID)&msg[chars], + (300-chars), 0); + WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, lstrlen(msg), &err,NULL); + return 2; + } + + /* + * Close our references to the write handles that have now been inherited. + */ + + CloseHandle(si.hStdOutput); + CloseHandle(si.hStdError); + + WaitForInputIdle(pi.hProcess, 5000); + CloseHandle(pi.hThread); + + /* + * Start the pipe reader threads. + */ + + pipeThreads[0] = CreateThread(NULL, 0, ReadFromPipe, &Out, 0, &threadID); + pipeThreads[1] = CreateThread(NULL, 0, ReadFromPipe, &Err, 0, &threadID); + + /* + * Block waiting for the process to end. + */ + + WaitForSingleObject(pi.hProcess, INFINITE); + CloseHandle(pi.hProcess); + + /* + * Wait for our pipe to get done reading, should it be a little slow. + */ + + WaitForMultipleObjects(2, pipeThreads, TRUE, 500); + CloseHandle(pipeThreads[0]); + CloseHandle(pipeThreads[1]); + + /* + * Look for the commandline warning code in the stderr stream. + */ + + return !(strstr(Out.buffer, "LNK1117") != NULL || + strstr(Err.buffer, "LNK1117") != NULL || + strstr(Out.buffer, "LNK4044") != NULL || + strstr(Err.buffer, "LNK4044") != NULL); +} + +static DWORD WINAPI +ReadFromPipe( + LPVOID args) +{ + pipeinfo *pi = (pipeinfo *) args; + char *lastBuf = pi->buffer; + DWORD dwRead; + BOOL ok; + + again: + if (lastBuf - pi->buffer + CHUNK > STATICBUFFERSIZE) { + CloseHandle(pi->pipe); + return (DWORD)-1; + } + ok = ReadFile(pi->pipe, lastBuf, CHUNK, &dwRead, 0L); + if (!ok || dwRead == 0) { + CloseHandle(pi->pipe); + return 0; + } + lastBuf += dwRead; + goto again; + + return 0; /* makes the compiler happy */ +} + +static int +IsIn( + const char *string, + const char *substring) +{ + return (strstr(string, substring) != NULL); +} + +/* + * GetVersionFromFile -- + * Looks for a match string in a file and then returns the version + * following the match where a version is anything acceptable to + * package provide or package ifneeded. + */ + +static const char * +GetVersionFromFile( + const char *filename, + const char *match) +{ + size_t cbBuffer = 100; + static char szBuffer[100]; + char *szResult = NULL; + FILE *fp = fopen(filename, "rt"); + + if (fp != NULL) { + /* + * Read data until we see our match string. + */ + + while (fgets(szBuffer, cbBuffer, fp) != NULL) { + LPSTR p, q; + + p = strstr(szBuffer, match); + if (p != NULL) { + /* + * Skip to first digit. + */ + + while (*p && !isdigit(*p)) { + ++p; + } + + /* + * Find ending whitespace. + */ + + q = p; + while (*q && (isalnum(*q) || *q == '.')) { + ++q; + } + + memcpy(szBuffer, p, q - p); + szBuffer[q-p] = 0; + szResult = szBuffer; + break; + } + } + fclose(fp); + } + return szResult; +} + +/* + * List helpers for the SubstituteFile function + */ + +typedef struct list_item_t { + struct list_item_t *nextPtr; + char * key; + char * value; +} list_item_t; + +/* insert a list item into the list (list may be null) */ +static list_item_t * +list_insert(list_item_t **listPtrPtr, const char *key, const char *value) +{ + list_item_t *itemPtr = malloc(sizeof(list_item_t)); + if (itemPtr) { + itemPtr->key = strdup(key); + itemPtr->value = strdup(value); + itemPtr->nextPtr = NULL; + + while(*listPtrPtr) { + listPtrPtr = &(*listPtrPtr)->nextPtr; + } + *listPtrPtr = itemPtr; + } + return itemPtr; +} + +static void +list_free(list_item_t **listPtrPtr) +{ + list_item_t *tmpPtr, *listPtr = *listPtrPtr; + while (listPtr) { + tmpPtr = listPtr; + listPtr = listPtr->nextPtr; + free(tmpPtr->key); + free(tmpPtr->value); + free(tmpPtr); + } +} + +/* + * SubstituteFile -- + * As windows doesn't provide anything useful like sed and it's unreliable + * to use the tclsh you are building against (consider x-platform builds - + * eg compiling AMD64 target from IX86) we provide a simple substitution + * option here to handle autoconf style substitutions. + * The substitution file is whitespace and line delimited. The file should + * consist of lines matching the regular expression: + * \s*\S+\s+\S*$ + * + * Usage is something like: + * nmakehlp -S << $** > $@ + * @PACKAGE_NAME@ $(PACKAGE_NAME) + * @PACKAGE_VERSION@ $(PACKAGE_VERSION) + * << + */ + +static int +SubstituteFile( + const char *substitutions, + const char *filename) +{ + size_t cbBuffer = 1024; + static char szBuffer[1024], szCopy[1024]; + char *szResult = NULL; + list_item_t *substPtr = NULL; + FILE *fp, *sp; + + fp = fopen(filename, "rt"); + if (fp != NULL) { + + /* + * Build a list of substutitions from the first filename + */ + + sp = fopen(substitutions, "rt"); + if (sp != NULL) { + while (fgets(szBuffer, cbBuffer, sp) != NULL) { + char *ks, *ke, *vs, *ve; + ks = szBuffer; + while (ks && *ks && isspace(*ks)) ++ks; + ke = ks; + while (ke && *ke && !isspace(*ke)) ++ke; + vs = ke; + while (vs && *vs && isspace(*vs)) ++vs; + ve = vs; + while (ve && *ve && !(*ve == '\r' || *ve == '\n')) ++ve; + *ke = 0, *ve = 0; + list_insert(&substPtr, ks, vs); + } + fclose(sp); + } + + /* debug: dump the list */ +#ifdef _DEBUG + { + int n = 0; + list_item_t *p = NULL; + for (p = substPtr; p != NULL; p = p->nextPtr, ++n) { + fprintf(stderr, "% 3d '%s' => '%s'\n", n, p->key, p->value); + } + } +#endif + + /* + * Run the substitutions over each line of the input + */ + + while (fgets(szBuffer, cbBuffer, fp) != NULL) { + list_item_t *p = NULL; + for (p = substPtr; p != NULL; p = p->nextPtr) { + char *m = strstr(szBuffer, p->key); + if (m) { + char *cp, *op, *sp; + cp = szCopy; + op = szBuffer; + while (op != m) *cp++ = *op++; + sp = p->value; + while (sp && *sp) *cp++ = *sp++; + op += strlen(p->key); + while (*op) *cp++ = *op++; + *cp = 0; + memcpy(szBuffer, szCopy, sizeof(szCopy)); + } + } + printf(szBuffer); + } + + list_free(&substPtr); + } + fclose(fp); + return 0; +} + +/* + * QualifyPath -- + * + * This composes the current working directory with a provided path + * and returns the fully qualified and normalized path. + * Mostly needed to setup paths for testing. + */ + +static int +QualifyPath( + const char *szPath) +{ + char szCwd[MAX_PATH + 1]; + char szTmp[MAX_PATH + 1]; + char *p; + GetCurrentDirectory(MAX_PATH, szCwd); + while ((p = strchr(szPath, '/')) && *p) + *p = '\\'; + PathCombine(szTmp, szCwd, szPath); + PathCanonicalize(szCwd, szTmp); + printf("%s\n", szCwd); + return 0; +} + +/* + * Local variables: + * mode: c + * c-basic-offset: 4 + * fill-column: 78 + * indent-tabs-mode: t + * tab-width: 8 + * End: + */ diff --git a/components/external/SQLite-3.8.1/autoconf/tea/win/rules.vc b/components/external/SQLite-3.8.1/autoconf/tea/win/rules.vc new file mode 100644 index 0000000000000000000000000000000000000000..99471053c8c0a38e9571d8809402b032b250401c --- /dev/null +++ b/components/external/SQLite-3.8.1/autoconf/tea/win/rules.vc @@ -0,0 +1,711 @@ +#------------------------------------------------------------------------------ +# rules.vc -- +# +# Microsoft Visual C++ makefile include for decoding the commandline +# macros. This file does not need editing to build Tcl. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# +# Copyright (c) 2001-2003 David Gravereaux. +# Copyright (c) 2003-2008 Patrick Thoyts +#------------------------------------------------------------------------------ + +!ifndef _RULES_VC +_RULES_VC = 1 + +cc32 = $(CC) # built-in default. +link32 = link +lib32 = lib +rc32 = $(RC) # built-in default. + +!ifndef INSTALLDIR +### Assume the normal default. +_INSTALLDIR = C:\Program Files\Tcl +!else +### Fix the path separators. +_INSTALLDIR = $(INSTALLDIR:/=\) +!endif + +#---------------------------------------------------------- +# Set the proper copy method to avoid overwrite questions +# to the user when copying files and selecting the right +# "delete all" method. +#---------------------------------------------------------- + +!if "$(OS)" == "Windows_NT" +RMDIR = rmdir /S /Q +ERRNULL = 2>NUL +!if ![ver | find "4.0" > nul] +CPY = echo y | xcopy /i >NUL +COPY = copy >NUL +!else +CPY = xcopy /i /y >NUL +COPY = copy /y >NUL +!endif +!else # "$(OS)" != "Windows_NT" +CPY = xcopy /i >_JUNK.OUT # On Win98 NUL does not work here. +COPY = copy >_JUNK.OUT # On Win98 NUL does not work here. +RMDIR = deltree /Y +NULL = \NUL # Used in testing directory existence +ERRNULL = >NUL # Win9x shell cannot redirect stderr +!endif +MKDIR = mkdir + +#------------------------------------------------------------------------------ +# Determine the host and target architectures and compiler version. +#------------------------------------------------------------------------------ + +_HASH=^# +_VC_MANIFEST_EMBED_EXE= +_VC_MANIFEST_EMBED_DLL= +VCVER=0 +!if ![echo VCVERSION=_MSC_VER > vercl.x] \ + && ![echo $(_HASH)if defined(_M_IX86) >> vercl.x] \ + && ![echo ARCH=IX86 >> vercl.x] \ + && ![echo $(_HASH)elif defined(_M_AMD64) >> vercl.x] \ + && ![echo ARCH=AMD64 >> vercl.x] \ + && ![echo $(_HASH)endif >> vercl.x] \ + && ![cl -nologo -TC -P vercl.x $(ERRNULL)] +!include vercl.i +!if ![echo VCVER= ^\> vercl.vc] \ + && ![set /a $(VCVERSION) / 100 - 6 >> vercl.vc] +!include vercl.vc +!endif +!endif +!if ![del $(ERRNUL) /q/f vercl.x vercl.i vercl.vc] +!endif + +!if ![reg query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier | findstr /i x86] +NATIVE_ARCH=IX86 +!else +NATIVE_ARCH=AMD64 +!endif + +# Since MSVC8 we must deal with manifest resources. +!if $(VCVERSION) >= 1400 +_VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;1 +_VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2 +!endif + +!ifndef MACHINE +MACHINE=$(ARCH) +!endif + +!ifndef CFG_ENCODING +CFG_ENCODING = \"cp1252\" +!endif + +!message =============================================================================== + +#---------------------------------------------------------- +# build the helper app we need to overcome nmake's limiting +# environment. +#---------------------------------------------------------- + +!if !exist(nmakehlp.exe) +!if [$(cc32) -nologo nmakehlp.c -link -subsystem:console > nul] +!endif +!endif + +#---------------------------------------------------------- +# Test for compiler features +#---------------------------------------------------------- + +### test for optimizations +!if [nmakehlp -c -Ot] +!message *** Compiler has 'Optimizations' +OPTIMIZING = 1 +!else +!message *** Compiler does not have 'Optimizations' +OPTIMIZING = 0 +!endif + +OPTIMIZATIONS = + +!if [nmakehlp -c -Ot] +OPTIMIZATIONS = $(OPTIMIZATIONS) -Ot +!endif + +!if [nmakehlp -c -Oi] +OPTIMIZATIONS = $(OPTIMIZATIONS) -Oi +!endif + +!if [nmakehlp -c -Op] +OPTIMIZATIONS = $(OPTIMIZATIONS) -Op +!endif + +!if [nmakehlp -c -fp:strict] +OPTIMIZATIONS = $(OPTIMIZATIONS) -fp:strict +!endif + +!if [nmakehlp -c -Gs] +OPTIMIZATIONS = $(OPTIMIZATIONS) -Gs +!endif + +!if [nmakehlp -c -GS] +OPTIMIZATIONS = $(OPTIMIZATIONS) -GS +!endif + +!if [nmakehlp -c -GL] +OPTIMIZATIONS = $(OPTIMIZATIONS) -GL +!endif + +DEBUGFLAGS = + +!if [nmakehlp -c -RTC1] +DEBUGFLAGS = $(DEBUGFLAGS) -RTC1 +!elseif [nmakehlp -c -GZ] +DEBUGFLAGS = $(DEBUGFLAGS) -GZ +!endif + +COMPILERFLAGS =-W3 -DUNICODE -D_UNICODE + +# In v13 -GL and -YX are incompatible. +!if [nmakehlp -c -YX] +!if ![nmakehlp -c -GL] +OPTIMIZATIONS = $(OPTIMIZATIONS) -YX +!endif +!endif + +!if "$(MACHINE)" == "IX86" +### test for pentium errata +!if [nmakehlp -c -QI0f] +!message *** Compiler has 'Pentium 0x0f fix' +COMPILERFLAGS = $(COMPILERFLAGS) -QI0f +!else +!message *** Compiler does not have 'Pentium 0x0f fix' +!endif +!endif + +!if "$(MACHINE)" == "IA64" +### test for Itanium errata +!if [nmakehlp -c -QIA64_Bx] +!message *** Compiler has 'B-stepping errata workarounds' +COMPILERFLAGS = $(COMPILERFLAGS) -QIA64_Bx +!else +!message *** Compiler does not have 'B-stepping errata workarounds' +!endif +!endif + +!if "$(MACHINE)" == "IX86" +### test for -align:4096, when align:512 will do. +!if [nmakehlp -l -opt:nowin98] +!message *** Linker has 'Win98 alignment problem' +ALIGN98_HACK = 1 +!else +!message *** Linker does not have 'Win98 alignment problem' +ALIGN98_HACK = 0 +!endif +!else +ALIGN98_HACK = 0 +!endif + +LINKERFLAGS = + +!if [nmakehlp -l -ltcg] +LINKERFLAGS =-ltcg +!endif + +#---------------------------------------------------------- +# Decode the options requested. +#---------------------------------------------------------- + +!if "$(OPTS)" == "" || [nmakehlp -f "$(OPTS)" "none"] +STATIC_BUILD = 0 +TCL_THREADS = 1 +DEBUG = 0 +SYMBOLS = 0 +PROFILE = 0 +PGO = 0 +MSVCRT = 0 +LOIMPACT = 0 +TCL_USE_STATIC_PACKAGES = 0 +USE_THREAD_ALLOC = 1 +UNCHECKED = 0 +!else +!if [nmakehlp -f $(OPTS) "static"] +!message *** Doing static +STATIC_BUILD = 1 +!else +STATIC_BUILD = 0 +!endif +!if [nmakehlp -f $(OPTS) "msvcrt"] +!message *** Doing msvcrt +MSVCRT = 1 +!else +MSVCRT = 0 +!endif +!if [nmakehlp -f $(OPTS) "staticpkg"] +!message *** Doing staticpkg +TCL_USE_STATIC_PACKAGES = 1 +!else +TCL_USE_STATIC_PACKAGES = 0 +!endif +!if [nmakehlp -f $(OPTS) "nothreads"] +!message *** Compile explicitly for non-threaded tcl +TCL_THREADS = 0 +!else +TCL_THREADS = 1 +USE_THREAD_ALLOC= 1 +!endif +!if [nmakehlp -f $(OPTS) "symbols"] +!message *** Doing symbols +DEBUG = 1 +!else +DEBUG = 0 +!endif +!if [nmakehlp -f $(OPTS) "pdbs"] +!message *** Doing pdbs +SYMBOLS = 1 +!else +SYMBOLS = 0 +!endif +!if [nmakehlp -f $(OPTS) "profile"] +!message *** Doing profile +PROFILE = 1 +!else +PROFILE = 0 +!endif +!if [nmakehlp -f $(OPTS) "pgi"] +!message *** Doing profile guided optimization instrumentation +PGO = 1 +!elseif [nmakehlp -f $(OPTS) "pgo"] +!message *** Doing profile guided optimization +PGO = 2 +!else +PGO = 0 +!endif +!if [nmakehlp -f $(OPTS) "loimpact"] +!message *** Doing loimpact +LOIMPACT = 1 +!else +LOIMPACT = 0 +!endif +!if [nmakehlp -f $(OPTS) "thrdalloc"] +!message *** Doing thrdalloc +USE_THREAD_ALLOC = 1 +!endif +!if [nmakehlp -f $(OPTS) "tclalloc"] +!message *** Doing tclalloc +USE_THREAD_ALLOC = 0 +!endif +!if [nmakehlp -f $(OPTS) "unchecked"] +!message *** Doing unchecked +UNCHECKED = 1 +!else +UNCHECKED = 0 +!endif +!endif + + +!if !$(STATIC_BUILD) +# Make sure we don't build overly fat DLLs. +MSVCRT = 1 +# We shouldn't statically put the extensions inside the shell when dynamic. +TCL_USE_STATIC_PACKAGES = 0 +!endif + + +#---------------------------------------------------------- +# Figure-out how to name our intermediate and output directories. +# We wouldn't want different builds to use the same .obj files +# by accident. +#---------------------------------------------------------- + +#---------------------------------------- +# Naming convention: +# t = full thread support. +# s = static library (as opposed to an +# import library) +# g = linked to the debug enabled C +# run-time. +# x = special static build when it +# links to the dynamic C run-time. +#---------------------------------------- +SUFX = tsgx + +!if $(DEBUG) +BUILDDIRTOP = Debug +!else +BUILDDIRTOP = Release +!endif + +!if "$(MACHINE)" != "IX86" +BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE) +!endif +!if $(VCVER) > 6 +BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER) +!endif + +!if !$(DEBUG) || $(DEBUG) && $(UNCHECKED) +SUFX = $(SUFX:g=) +!endif + +TMP_DIRFULL = .\$(BUILDDIRTOP)\$(PROJECT)_ThreadedDynamicStaticX + +!if !$(STATIC_BUILD) +TMP_DIRFULL = $(TMP_DIRFULL:Static=) +SUFX = $(SUFX:s=) +EXT = dll +!if $(MSVCRT) +TMP_DIRFULL = $(TMP_DIRFULL:X=) +SUFX = $(SUFX:x=) +!endif +!else +TMP_DIRFULL = $(TMP_DIRFULL:Dynamic=) +EXT = lib +!if !$(MSVCRT) +TMP_DIRFULL = $(TMP_DIRFULL:X=) +SUFX = $(SUFX:x=) +!endif +!endif + +!if !$(TCL_THREADS) +TMP_DIRFULL = $(TMP_DIRFULL:Threaded=) +SUFX = $(SUFX:t=) +!endif + +!ifndef TMP_DIR +TMP_DIR = $(TMP_DIRFULL) +!ifndef OUT_DIR +OUT_DIR = .\$(BUILDDIRTOP) +!endif +!else +!ifndef OUT_DIR +OUT_DIR = $(TMP_DIR) +!endif +!endif + + +#---------------------------------------------------------- +# Decode the statistics requested. +#---------------------------------------------------------- + +!if "$(STATS)" == "" || [nmakehlp -f "$(STATS)" "none"] +TCL_MEM_DEBUG = 0 +TCL_COMPILE_DEBUG = 0 +!else +!if [nmakehlp -f $(STATS) "memdbg"] +!message *** Doing memdbg +TCL_MEM_DEBUG = 1 +!else +TCL_MEM_DEBUG = 0 +!endif +!if [nmakehlp -f $(STATS) "compdbg"] +!message *** Doing compdbg +TCL_COMPILE_DEBUG = 1 +!else +TCL_COMPILE_DEBUG = 0 +!endif +!endif + + +#---------------------------------------------------------- +# Decode the checks requested. +#---------------------------------------------------------- + +!if "$(CHECKS)" == "" || [nmakehlp -f "$(CHECKS)" "none"] +TCL_NO_DEPRECATED = 0 +WARNINGS = -W3 +!else +!if [nmakehlp -f $(CHECKS) "nodep"] +!message *** Doing nodep check +TCL_NO_DEPRECATED = 1 +!else +TCL_NO_DEPRECATED = 0 +!endif +!if [nmakehlp -f $(CHECKS) "fullwarn"] +!message *** Doing full warnings check +WARNINGS = -W4 +!if [nmakehlp -l -warn:3] +LINKERFLAGS = $(LINKERFLAGS) -warn:3 +!endif +!else +WARNINGS = -W3 +!endif +!if [nmakehlp -f $(CHECKS) "64bit"] && [nmakehlp -c -Wp64] +!message *** Doing 64bit portability warnings +WARNINGS = $(WARNINGS) -Wp64 +!endif +!endif + +!if $(PGO) > 1 +!if [nmakehlp -l -ltcg:pgoptimize] +LINKERFLAGS = $(LINKERFLAGS:-ltcg=) -ltcg:pgoptimize +!else +MSG=^ +This compiler does not support profile guided optimization. +!error $(MSG) +!endif +!elseif $(PGO) > 0 +!if [nmakehlp -l -ltcg:pginstrument] +LINKERFLAGS = $(LINKERFLAGS:-ltcg=) -ltcg:pginstrument +!else +MSG=^ +This compiler does not support profile guided optimization. +!error $(MSG) +!endif +!endif + +#---------------------------------------------------------- +# Set our defines now armed with our options. +#---------------------------------------------------------- + +OPTDEFINES = -DTCL_CFGVAL_ENCODING=$(CFG_ENCODING) -DSTDC_HEADERS + +!if $(TCL_MEM_DEBUG) +OPTDEFINES = $(OPTDEFINES) -DTCL_MEM_DEBUG +!endif +!if $(TCL_COMPILE_DEBUG) +OPTDEFINES = $(OPTDEFINES) -DTCL_COMPILE_DEBUG -DTCL_COMPILE_STATS +!endif +!if $(TCL_THREADS) +OPTDEFINES = $(OPTDEFINES) -DTCL_THREADS=1 +!if $(USE_THREAD_ALLOC) +OPTDEFINES = $(OPTDEFINES) -DUSE_THREAD_ALLOC=1 +!endif +!endif +!if $(STATIC_BUILD) +OPTDEFINES = $(OPTDEFINES) -DSTATIC_BUILD +!endif +!if $(TCL_NO_DEPRECATED) +OPTDEFINES = $(OPTDEFINES) -DTCL_NO_DEPRECATED +!endif + +!if !$(DEBUG) +OPTDEFINES = $(OPTDEFINES) -DNDEBUG +!if $(OPTIMIZING) +OPTDEFINES = $(OPTDEFINES) -DTCL_CFG_OPTIMIZED +!endif +!endif +!if $(PROFILE) +OPTDEFINES = $(OPTDEFINES) -DTCL_CFG_PROFILED +!endif +!if "$(MACHINE)" == "IA64" || "$(MACHINE)" == "AMD64" +OPTDEFINES = $(OPTDEFINES) -DTCL_CFG_DO64BIT +!endif +!if $(VCVERSION) < 1300 +OPTDEFINES = $(OPTDEFINES) -DNO_STRTOI64 +!endif + +#---------------------------------------------------------- +# Locate the Tcl headers to build against +#---------------------------------------------------------- + +!if "$(PROJECT)" == "tcl" + +_TCL_H = ..\generic\tcl.h + +!else + +# If INSTALLDIR set to tcl root dir then reset to the lib dir. +!if exist("$(_INSTALLDIR)\include\tcl.h") +_INSTALLDIR=$(_INSTALLDIR)\lib +!endif + +!if !defined(TCLDIR) +!if exist("$(_INSTALLDIR)\..\include\tcl.h") +TCLINSTALL = 1 +_TCLDIR = $(_INSTALLDIR)\.. +_TCL_H = $(_INSTALLDIR)\..\include\tcl.h +TCLDIR = $(_INSTALLDIR)\.. +!else +MSG=^ +Failed to find tcl.h. Set the TCLDIR macro. +!error $(MSG) +!endif +!else +_TCLDIR = $(TCLDIR:/=\) +!if exist("$(_TCLDIR)\include\tcl.h") +TCLINSTALL = 1 +_TCL_H = $(_TCLDIR)\include\tcl.h +!elseif exist("$(_TCLDIR)\generic\tcl.h") +TCLINSTALL = 0 +_TCL_H = $(_TCLDIR)\generic\tcl.h +!else +MSG =^ +Failed to find tcl.h. The TCLDIR macro does not appear correct. +!error $(MSG) +!endif +!endif +!endif + +#-------------------------------------------------------------- +# Extract various version numbers from tcl headers +# The generated file is then included in the makefile. +#-------------------------------------------------------------- + +!if [echo REM = This file is generated from rules.vc > versions.vc] +!endif +!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \ + && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc] +!endif +!if [echo TCL_MINOR_VERSION = \>> versions.vc] \ + && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc] +!endif +!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \ + && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc] +!endif + +# If building the tcl core then we need additional package versions +!if "$(PROJECT)" == "tcl" +!if [echo PKG_HTTP_VER = \>> versions.vc] \ + && [nmakehlp -V ..\library\http\pkgIndex.tcl http >> versions.vc] +!endif +!if [echo PKG_TCLTEST_VER = \>> versions.vc] \ + && [nmakehlp -V ..\library\tcltest\pkgIndex.tcl tcltest >> versions.vc] +!endif +!if [echo PKG_MSGCAT_VER = \>> versions.vc] \ + && [nmakehlp -V ..\library\msgcat\pkgIndex.tcl msgcat >> versions.vc] +!endif +!if [echo PKG_PLATFORM_VER = \>> versions.vc] \ + && [nmakehlp -V ..\library\platform\pkgIndex.tcl "platform " >> versions.vc] +!endif +!if [echo PKG_SHELL_VER = \>> versions.vc] \ + && [nmakehlp -V ..\library\platform\pkgIndex.tcl "platform::shell" >> versions.vc] +!endif +!if [echo PKG_DDE_VER = \>> versions.vc] \ + && [nmakehlp -V ..\library\dde\pkgIndex.tcl "dde " >> versions.vc] +!endif +!if [echo PKG_REG_VER =\>> versions.vc] \ + && [nmakehlp -V ..\library\reg\pkgIndex.tcl registry >> versions.vc] +!endif +!endif + +!include versions.vc + +#-------------------------------------------------------------- +# Setup tcl version dependent stuff headers +#-------------------------------------------------------------- + +!if "$(PROJECT)" != "tcl" + +TCL_VERSION = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION) + +!if $(TCL_VERSION) < 81 +TCL_DOES_STUBS = 0 +!else +TCL_DOES_STUBS = 1 +!endif + +!if $(TCLINSTALL) +TCLSH = "$(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX).exe" +!if !exist($(TCLSH)) && $(TCL_THREADS) +TCLSH = "$(_TCLDIR)\bin\tclsh$(TCL_VERSION)t$(SUFX).exe" +!endif +TCLSTUBLIB = "$(_TCLDIR)\lib\tclstub$(TCL_VERSION).lib" +TCLIMPLIB = "$(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX).lib" +TCL_LIBRARY = $(_TCLDIR)\lib +TCLREGLIB = "$(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib" +TCLDDELIB = "$(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib" +COFFBASE = \must\have\tcl\sources\to\build\this\target +TCLTOOLSDIR = \must\have\tcl\sources\to\build\this\target +TCL_INCLUDES = -I"$(_TCLDIR)\include" +!else +TCLSH = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX).exe" +!if !exist($(TCLSH)) && $(TCL_THREADS) +TCLSH = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)t$(SUFX).exe" +!endif +TCLSTUBLIB = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tclstub$(TCL_VERSION).lib" +TCLIMPLIB = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX).lib" +TCL_LIBRARY = $(_TCLDIR)\library +TCLREGLIB = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib" +TCLDDELIB = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib" +COFFBASE = "$(_TCLDIR)\win\coffbase.txt" +TCLTOOLSDIR = $(_TCLDIR)\tools +TCL_INCLUDES = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win" +!endif + +!endif + +#------------------------------------------------------------------------- +# Locate the Tk headers to build against +#------------------------------------------------------------------------- + +!if "$(PROJECT)" == "tk" +_TK_H = ..\generic\tk.h +_INSTALLDIR = $(_INSTALLDIR)\.. +!endif + +!ifdef PROJECT_REQUIRES_TK +!if !defined(TKDIR) +!if exist("$(_INSTALLDIR)\..\include\tk.h") +TKINSTALL = 1 +_TKDIR = $(_INSTALLDIR)\.. +_TK_H = $(_TKDIR)\include\tk.h +TKDIR = $(_TKDIR) +!elseif exist("$(_TCLDIR)\include\tk.h") +TKINSTALL = 1 +_TKDIR = $(_TCLDIR) +_TK_H = $(_TKDIR)\include\tk.h +TKDIR = $(_TKDIR) +!endif +!else +_TKDIR = $(TKDIR:/=\) +!if exist("$(_TKDIR)\include\tk.h") +TKINSTALL = 1 +_TK_H = $(_TKDIR)\include\tk.h +!elseif exist("$(_TKDIR)\generic\tk.h") +TKINSTALL = 0 +_TK_H = $(_TKDIR)\generic\tk.h +!else +MSG =^ +Failed to find tk.h. The TKDIR macro does not appear correct. +!error $(MSG) +!endif +!endif +!endif + +#------------------------------------------------------------------------- +# Extract Tk version numbers +#------------------------------------------------------------------------- + +!if defined(PROJECT_REQUIRES_TK) || "$(PROJECT)" == "tk" + +!if [echo TK_MAJOR_VERSION = \>> versions.vc] \ + && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc] +!endif +!if [echo TK_MINOR_VERSION = \>> versions.vc] \ + && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc] +!endif +!if [echo TK_PATCH_LEVEL = \>> versions.vc] \ + && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc] +!endif + +!include versions.vc + +TK_DOTVERSION = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION) +TK_VERSION = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION) + +!if "$(PROJECT)" != "tk" +!if $(TKINSTALL) +WISH = "$(_TKDIR)\bin\wish$(TK_VERSION)$(SUFX).exe" +TKSTUBLIB = "$(_TKDIR)\lib\tkstub$(TK_VERSION).lib" +TKIMPLIB = "$(_TKDIR)\lib\tk$(TK_VERSION)$(SUFX).lib" +TK_INCLUDES = -I"$(_TKDIR)\include" +!else +WISH = "$(_TKDIR)\win\$(BUILDDIRTOP)\wish$(TCL_VERSION)$(SUFX).exe" +TKSTUBLIB = "$(_TKDIR)\win\$(BUILDDIRTOP)\tkstub$(TCL_VERSION).lib" +TKIMPLIB = "$(_TKDIR)\win\$(BUILDDIRTOP)\tk$(TCL_VERSION)$(SUFX).lib" +TK_INCLUDES = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib" +!endif +!endif + +!endif + +#---------------------------------------------------------- +# Display stats being used. +#---------------------------------------------------------- + +!message *** Intermediate directory will be '$(TMP_DIR)' +!message *** Output directory will be '$(OUT_DIR)' +!message *** Suffix for binaries will be '$(SUFX)' +!message *** Optional defines are '$(OPTDEFINES)' +!message *** Compiler version $(VCVER). Target machine is $(MACHINE) +!message *** Host architecture is $(NATIVE_ARCH) +!message *** Compiler options '$(COMPILERFLAGS) $(OPTIMIZATIONS) $(DEBUGFLAGS) $(WARNINGS)' +!message *** Link options '$(LINKERFLAGS)' + +!endif + diff --git a/components/external/SQLite-3.8.1/config.guess b/components/external/SQLite-3.8.1/config.guess new file mode 100644 index 0000000000000000000000000000000000000000..34093cc6bb528dbeab930e84be48483393946c40 --- /dev/null +++ b/components/external/SQLite-3.8.1/config.guess @@ -0,0 +1,1535 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, +# Inc. + +timestamp='2007-07-22' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Originally written by Per Bothner . +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# The plan is that this can be called by configure scripts if you +# don't specify an explicit build system type. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +trap 'exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +set_cc_for_build=' +trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; +trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; +: ${TMPDIR=/tmp} ; + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; +dummy=$tmp/dummy ; +tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int x;" > $dummy.c ; + for c in cc gcc c89 c99 ; do + if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac ; set_cc_for_build= ;' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +if [ "${UNAME_SYSTEM}" = "Linux" ] ; then + eval $set_cc_for_build + cat << EOF > $dummy.c + #include + #ifdef __UCLIBC__ + # ifdef __UCLIBC_CONFIG_VERSION__ + LIBC=uclibc __UCLIBC_CONFIG_VERSION__ + # else + LIBC=uclibc + # endif + #else + LIBC=gnu + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep LIBC= | sed -e 's: ::g'` +fi + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ + /usr/sbin/$sysctl 2>/dev/null || echo unknown)` + case "${UNAME_MACHINE_ARCH}" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + sh5el) machine=sh5le-unknown ;; + *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE_ARCH}" in + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep __ELF__ >/dev/null + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "${UNAME_VERSION}" in + Debian*) + release='-gnu' + ;; + *) + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit ;; + *:OpenBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} + exit ;; + *:ekkoBSD:*:*) + echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + exit ;; + *:SolidBSD:*:*) + echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} + exit ;; + macppc:MirBSD:*:*) + echo powerpc-unknown-mirbsd${UNAME_RELEASE} + exit ;; + *:MirBSD:*:*) + echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + exit ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE="alpha" ;; + "EV4.5 (21064)") + UNAME_MACHINE="alpha" ;; + "LCA4 (21066/21068)") + UNAME_MACHINE="alpha" ;; + "EV5 (21164)") + UNAME_MACHINE="alphaev5" ;; + "EV5.6 (21164A)") + UNAME_MACHINE="alphaev56" ;; + "EV5.6 (21164PC)") + UNAME_MACHINE="alphapca56" ;; + "EV5.7 (21164PC)") + UNAME_MACHINE="alphapca57" ;; + "EV6 (21264)") + UNAME_MACHINE="alphaev6" ;; + "EV6.7 (21264A)") + UNAME_MACHINE="alphaev67" ;; + "EV6.8CB (21264C)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8AL (21264B)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8CX (21264D)") + UNAME_MACHINE="alphaev68" ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE="alphaev69" ;; + "EV7 (21364)") + UNAME_MACHINE="alphaev7" ;; + "EV7.9 (21364A)") + UNAME_MACHINE="alphaev79" ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + exit ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit ;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-morphos + exit ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit ;; + *:z/VM:*:*) + echo s390-ibm-zvmoe + exit ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit ;; + arm:riscos:*:*|arm:RISCOS:*:*) + echo arm-unknown-riscos + exit ;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit ;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7; exit ;; + esac ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) + echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit ;; + m68k:machten:*:*) + echo m68k-apple-machten${UNAME_RELEASE} + exit ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && + dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`$dummy $dummyarg` && + { echo "$SYSTEM_NAME"; exit; } + echo mips-mips-riscos${UNAME_RELEASE} + exit ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` + then + echo "$SYSTEM_NAME" + else + echo rs6000-ibm-aix3.2.5 + fi + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit ;; + *:AIX:*:[45]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ ${HP_ARCH} = "hppa2.0w" ] + then + eval $set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | + grep __LP64__ >/dev/null + then + HP_ARCH="hppa2.0w" + else + HP_ARCH="hppa64" + fi + fi + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + echo unknown-hitachi-hiuxwe2 + exit ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + *:UNICOS/mp:*:*) + echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:FreeBSD:*:*) + case ${UNAME_MACHINE} in + pc98) + echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + amd64) + echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + *) + echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + esac + exit ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit ;; + *:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit ;; + i*:windows32*:*) + # uname -m includes "-pc" on this system. + echo ${UNAME_MACHINE}-mingw32 + exit ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit ;; + *:Interix*:[3456]*) + case ${UNAME_MACHINE} in + x86) + echo i586-pc-interix${UNAME_RELEASE} + exit ;; + EM64T | authenticamd) + echo x86_64-unknown-interix${UNAME_RELEASE} + exit ;; + esac ;; + [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) + echo i${UNAME_MACHINE}-pc-mks + exit ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i586-pc-interix + exit ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + echo x86_64-unknown-cygwin + exit ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + *:GNU:*:*) + # the GNU system + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu + exit ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit ;; + arm*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + avr32*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + cris:Linux:*:*) + echo cris-axis-linux-${LIBC} + exit ;; + crisv32:Linux:*:*) + echo crisv32-axis-linux-${LIBC} + exit ;; + frv:Linux:*:*) + echo frv-unknown-linux-${LIBC} + exit ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + m32r*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + mips:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips + #undef mipsel + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mipsel + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips + #else + CPU= + #endif + #endif +EOF + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^CPU/{ + s: ::g + p + }'`" + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } + ;; + mips64:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips64 + #undef mips64el + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mips64el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips64 + #else + CPU= + #endif + #endif +EOF + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^CPU/{ + s: ::g + p + }'`" + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } + ;; + or32:Linux:*:*) + echo or32-unknown-linux-${LIBC} + exit ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-${LIBC} + exit ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-${LIBC} + exit ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null + if test "$?" = 0 ; then LIBC="gnulibc1" ; fi + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-${LIBC} ;; + PA8*) echo hppa2.0-unknown-linux-${LIBC} ;; + *) echo hppa-unknown-linux-${LIBC} ;; + esac + exit ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-${LIBC} + exit ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit ;; + sh64*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + vax:Linux:*:*) + echo ${UNAME_MACHINE}-dec-linux-${LIBC} + exit ;; + x86_64:Linux:*:*) + echo x86_64-unknown-linux-${LIBC} + exit ;; + xtensa:Linux:*:*) + echo xtensa-unknown-linux-${LIBC} + exit ;; + i*86:Linux:*:*) + # The BFD linker knows what the default object file format is, so + # first see if it will tell us. cd to the root directory to prevent + # problems with other programs or directories called `ld' in the path. + # Set LC_ALL=C to ensure ld outputs messages in English. + ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \ + | sed -ne '/supported targets:/!d + s/[ ][ ]*/ /g + s/.*supported targets: *// + s/ .*// + p'` + case "$ld_supported_targets" in + elf32-i386) + TENTATIVE="${UNAME_MACHINE}-pc-linux-${LIBC}" + ;; + a.out-i386-linux) + echo "${UNAME_MACHINE}-pc-linux-${LIBC}aout" + exit ;; + coff-i386) + echo "${UNAME_MACHINE}-pc-linux-${LIBC}coff" + exit ;; + "") + # Either a pre-BFD a.out linker (linux-gnuoldld) or + # one that does not give us useful --help. + echo "${UNAME_MACHINE}-pc-linux-${LIBC}oldld" + exit ;; + esac + # This should get integrated into the C code below, but now we hack + if [ "$LIBC" != "gnu" ] ; then echo "$TENTATIVE" && exit 0 ; fi + # Determine whether the default compiler is a.out or elf + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + #ifdef __ELF__ + # ifdef __GLIBC__ + # if __GLIBC__ >= 2 + LIBC=gnu + # else + LIBC=gnulibc1 + # endif + # else + LIBC=gnulibc1 + # endif + #else + #if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) + LIBC=gnu + #else + LIBC=gnuaout + #endif + #endif + #ifdef __dietlibc__ + LIBC=dietlibc + #endif +EOF + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^LIBC/{ + s: ::g + p + }'`" + test x"${LIBC}" != x && { + echo "${UNAME_MACHINE}-pc-linux-${LIBC}" + exit + } + test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; } + ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit ;; + i*86:syllable:*:*) + echo ${UNAME_MACHINE}-pc-syllable + exit ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i386. + echo i386-pc-msdosdjgpp + exit ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4; exit; } ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + echo ${UNAME_MACHINE}-stratus-vos + exit ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux${UNAME_RELEASE} + exit ;; + SX-7:SUPER-UX:*:*) + echo sx7-nec-superux${UNAME_RELEASE} + exit ;; + SX-8:SUPER-UX:*:*) + echo sx8-nec-superux${UNAME_RELEASE} + exit ;; + SX-8R:SUPER-UX:*:*) + echo sx8r-nec-superux${UNAME_RELEASE} + exit ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown + case $UNAME_PROCESSOR in + unknown) UNAME_PROCESSOR=powerpc ;; + esac + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = "x86"; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + exit ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit ;; + NSE-?:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk${UNAME_RELEASE} + exit ;; + NSR-?:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux${UNAME_RELEASE} + exit ;; + *:DragonFly:*:*) + echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case "${UNAME_MACHINE}" in + A*) echo alpha-dec-vms ; exit ;; + I*) echo ia64-dec-vms ; exit ;; + V*) echo vax-dec-vms ; exit ;; + esac ;; + *:XENIX:*:SysV) + echo i386-pc-xenix + exit ;; + i*86:skyos:*:*) + echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' + exit ;; + i*86:rdos:*:*) + echo ${UNAME_MACHINE}-pc-rdos + exit ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +eval $set_cc_for_build +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix\n"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + c34*) + echo c34-convex-bsd + exit ;; + c38*) + echo c38-convex-bsd + exit ;; + c4*) + echo c4-convex-bsd + exit ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/components/external/SQLite-3.8.1/config.h.in b/components/external/SQLite-3.8.1/config.h.in new file mode 100644 index 0000000000000000000000000000000000000000..efc1d47bc68d0238d76771ebfadf2ce291f35060 --- /dev/null +++ b/components/external/SQLite-3.8.1/config.h.in @@ -0,0 +1,113 @@ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the header file. */ +#undef HAVE_DLFCN_H + +/* Define to 1 if you have the `fdatasync' function. */ +#undef HAVE_FDATASYNC + +/* Define to 1 if you have the `gmtime_r' function. */ +#undef HAVE_GMTIME_R + +/* Define to 1 if the system has the type `int16_t'. */ +#undef HAVE_INT16_T + +/* Define to 1 if the system has the type `int32_t'. */ +#undef HAVE_INT32_T + +/* Define to 1 if the system has the type `int64_t'. */ +#undef HAVE_INT64_T + +/* Define to 1 if the system has the type `int8_t'. */ +#undef HAVE_INT8_T + +/* Define to 1 if the system has the type `intptr_t'. */ +#undef HAVE_INTPTR_T + +/* Define to 1 if you have the header file. */ +#undef HAVE_INTTYPES_H + +/* Define to 1 if you have the `localtime_r' function. */ +#undef HAVE_LOCALTIME_R + +/* Define to 1 if you have the `localtime_s' function. */ +#undef HAVE_LOCALTIME_S + +/* Define to 1 if you have the header file. */ +#undef HAVE_MALLOC_H + +/* Define to 1 if you have the `malloc_usable_size' function. */ +#undef HAVE_MALLOC_USABLE_SIZE + +/* Define to 1 if you have the header file. */ +#undef HAVE_MEMORY_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TYPES_H + +/* Define to 1 if the system has the type `uint16_t'. */ +#undef HAVE_UINT16_T + +/* Define to 1 if the system has the type `uint32_t'. */ +#undef HAVE_UINT32_T + +/* Define to 1 if the system has the type `uint64_t'. */ +#undef HAVE_UINT64_T + +/* Define to 1 if the system has the type `uint8_t'. */ +#undef HAVE_UINT8_T + +/* Define to 1 if the system has the type `uintptr_t'. */ +#undef HAVE_UINTPTR_T + +/* Define to 1 if you have the header file. */ +#undef HAVE_UNISTD_H + +/* Define to 1 if you have the `usleep' function. */ +#undef HAVE_USLEEP + +/* Define to 1 if you have the utime() library function. */ +#undef HAVE_UTIME + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#undef LT_OBJDIR + +/* Define to the address where bug reports for this package should be sent. */ +#undef PACKAGE_BUGREPORT + +/* Define to the full name of this package. */ +#undef PACKAGE_NAME + +/* Define to the full name and version of this package. */ +#undef PACKAGE_STRING + +/* Define to the one symbol short name of this package. */ +#undef PACKAGE_TARNAME + +/* Define to the version of this package. */ +#undef PACKAGE_VERSION + +/* Define to 1 if you have the ANSI C header files. */ +#undef STDC_HEADERS + +/* Number of bits in a file offset, on hosts where this is settable. */ +#undef _FILE_OFFSET_BITS + +/* Define for large files, on AIX-style hosts. */ +#undef _LARGE_FILES diff --git a/components/external/SQLite-3.8.1/config.sub b/components/external/SQLite-3.8.1/config.sub new file mode 100644 index 0000000000000000000000000000000000000000..63cdd0a35d5e7fb774e51115786ea308dd19dbae --- /dev/null +++ b/components/external/SQLite-3.8.1/config.sub @@ -0,0 +1,1644 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, +# Inc. + +timestamp='2007-06-28' + +# This file is (in principle) common to ALL GNU software. +# The presence of a machine in this file suggests that SOME GNU software +# can handle that machine. It does not imply ALL GNU software can. +# +# This file is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit ;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \ + uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \ + storm-chaos* | os2-emx* | rtmk-nova*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis | -knuth | -cray) + os= + basic_machine=$1 + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -chorusos*) + os=-chorusos + basic_machine=$1 + ;; + -chorusrdb) + os=-chorusrdb + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco6) + os=-sco5v6 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5v6*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + 1750a | 580 \ + | a29k \ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ + | am33_2.0 \ + | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ + | bfin \ + | c4x | clipper \ + | d10v | d30v | dlx | dsp16xx | dvp \ + | fido | fr30 | frv \ + | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | i370 | i860 | i960 | ia64 \ + | ip2k | iq2000 \ + | m32c | m32r | m32rle | m68000 | m68k | m88k \ + | maxq | mb | microblaze | mcore | mep \ + | mips | mipsbe | mipseb | mipsel | mipsle \ + | mips16 \ + | mips64 | mips64el \ + | mips64vr | mips64vrel \ + | mips64orion | mips64orionel \ + | mips64vr4100 | mips64vr4100el \ + | mips64vr4300 | mips64vr4300el \ + | mips64vr5000 | mips64vr5000el \ + | mips64vr5900 | mips64vr5900el \ + | mipsisa32 | mipsisa32el \ + | mipsisa32r2 | mipsisa32r2el \ + | mipsisa64 | mipsisa64el \ + | mipsisa64r2 | mipsisa64r2el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ + | mipstx39 | mipstx39el \ + | mn10200 | mn10300 \ + | mt \ + | msp430 \ + | nios | nios2 \ + | ns16k | ns32k \ + | or32 \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ + | pyramid \ + | score \ + | sh | sh[1234] | sh[24]a | sh[24]a*eb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ + | sh64 | sh64le \ + | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ + | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ + | spu | strongarm \ + | tahoe | thumb | tic4x | tic80 | tron \ + | v850 | v850e \ + | we32k \ + | x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \ + | z8k) + basic_machine=$basic_machine-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12) + # Motorola 68HC11/12. + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + ;; + ms1) + basic_machine=mt-unknown + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + 580-* \ + | a29k-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ + | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ + | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ + | avr-* | avr32-* \ + | bfin-* | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \ + | clipper-* | craynv-* | cydra-* \ + | d10v-* | d30v-* | dlx-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ + | h8300-* | h8500-* \ + | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ + | i*86-* | i860-* | i960-* | ia64-* \ + | ip2k-* | iq2000-* \ + | m32c-* | m32r-* | m32rle-* \ + | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ + | m88110-* | m88k-* | maxq-* | mcore-* \ + | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ + | mips16-* \ + | mips64-* | mips64el-* \ + | mips64vr-* | mips64vrel-* \ + | mips64orion-* | mips64orionel-* \ + | mips64vr4100-* | mips64vr4100el-* \ + | mips64vr4300-* | mips64vr4300el-* \ + | mips64vr5000-* | mips64vr5000el-* \ + | mips64vr5900-* | mips64vr5900el-* \ + | mipsisa32-* | mipsisa32el-* \ + | mipsisa32r2-* | mipsisa32r2el-* \ + | mipsisa64-* | mipsisa64el-* \ + | mipsisa64r2-* | mipsisa64r2el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ + | mipstx39-* | mipstx39el-* \ + | mmix-* \ + | mt-* \ + | msp430-* \ + | nios-* | nios2-* \ + | none-* | np1-* | ns16k-* | ns32k-* \ + | orion-* \ + | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ + | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ + | pyramid-* \ + | romp-* | rs6000-* \ + | sh-* | sh[1234]-* | sh[24]a-* | sh[24]a*eb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ + | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ + | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ + | sparclite-* \ + | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \ + | tahoe-* | thumb-* \ + | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ + | tron-* \ + | v850-* | v850e-* | vax-* \ + | we32k-* \ + | x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \ + | xstormy16-* | xtensa-* \ + | ymp-* \ + | z8k-*) + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + abacus) + basic_machine=abacus-unknown + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amd64) + basic_machine=x86_64-pc + ;; + amd64-*) + basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + c90) + basic_machine=c90-cray + os=-unicos + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | j90) + basic_machine=j90-cray + os=-unicos + ;; + craynv) + basic_machine=craynv-cray + os=-unicosmp + ;; + cr16) + basic_machine=cr16-unknown + os=-elf + ;; + crds | unos) + basic_machine=m68k-crds + ;; + crisv32 | crisv32-* | etraxfs*) + basic_machine=crisv32-axis + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + crx) + basic_machine=crx-unknown + os=-elf + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + decsystem10* | dec10*) + basic_machine=pdp10-dec + os=-tops10 + ;; + decsystem20* | dec20*) + basic_machine=pdp10-dec + os=-tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + djgpp) + basic_machine=i586-pc + os=-msdosdjgpp + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; +# I'm not sure what "Sysv32" means. Should this be sysv3.2? + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + mingw32) + basic_machine=i386-pc + os=-mingw32 + ;; + mingw32ce) + basic_machine=arm-unknown + os=-mingw32ce + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mipsEE* | ee | ps2) + basic_machine=mips64r5900el-scei + case $os in + -linux*) + ;; + *) + os=-elf + ;; + esac + ;; + iop) + basic_machine=mipsel-scei + os=-irx + ;; + dvp) + basic_machine=dvp-scei + os=-elf + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + morphos) + basic_machine=powerpc-unknown + os=-morphos + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + ms1-*) + basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + openrisc | openrisc-*) + basic_machine=or32-unknown + ;; + os400) + basic_machine=powerpc-ibm + os=-os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pc98) + basic_machine=i386-pc + ;; + pc98-*) + basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium | p5 | k5 | k6 | nexgen | viac3) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon | athlon_*) + basic_machine=i686-pc + ;; + pentiumii | pentium2 | pentiumiii | pentium3) + basic_machine=i686-pc + ;; + pentium4) + basic_machine=i786-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium4-*) + basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc) basic_machine=powerpc-unknown + ;; + ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64) basic_machine=powerpc64-unknown + ;; + ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64le | powerpc64little | ppc64-le | powerpc64-little) + basic_machine=powerpc64le-unknown + ;; + ppc64le-* | powerpc64little-*) + basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rdos) + basic_machine=i386-pc + os=-rdos + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + s390 | s390-*) + basic_machine=s390-ibm + ;; + s390x | s390x-*) + basic_machine=s390x-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sb1) + basic_machine=mipsisa64sb1-unknown + ;; + sb1el) + basic_machine=mipsisa64sb1el-unknown + ;; + sde) + basic_machine=mipsisa32-sde + os=-elf + ;; + sei) + basic_machine=mips-sei + os=-seiux + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sh5el) + basic_machine=sh5le-unknown + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparclite-wrs | simso-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=alphaev5-cray + os=-unicos + ;; + t90) + basic_machine=t90-cray + os=-unicos + ;; + tic54x | c54x*) + basic_machine=tic54x-unknown + os=-coff + ;; + tic55x | c55x*) + basic_machine=tic55x-unknown + os=-coff + ;; + tic6x | c6x*) + basic_machine=tic6x-unknown + os=-coff + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + toad1) + basic_machine=pdp10-xkl + os=-tops20 + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + tpf) + basic_machine=s390x-ibm + os=-tpf + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + xbox) + basic_machine=i686-pc + os=-mingw32 + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + ymp) + basic_machine=ymp-cray + os=-unicos + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + romp) + basic_machine=romp-ibm + ;; + mmix) + basic_machine=mmix-knuth + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele) + basic_machine=sh-unknown + ;; + sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ + | -openbsd* | -solidbsd* \ + | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ + | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -chorusos* | -chorusrdb* \ + | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \ + | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ + | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ + | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ + | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ + | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -irx*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto-qnx*) + ;; + -nto*) + os=`echo $os | sed -e 's|nto|nto-qnx|'` + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux-dietlibc) + os=-linux-dietlibc + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -os400*) + os=-os400 + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -atheos*) + os=-atheos + ;; + -syllable*) + os=-syllable + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -nova*) + os=-rtmk-nova + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -tpf*) + os=-tpf + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -aros*) + os=-aros + ;; + -kaos*) + os=-kaos + ;; + -zvmoe) + os=-zvmoe + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + score-*) + os=-elf + ;; + spu-*) + os=-elf + ;; + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + c4x-* | tic4x-*) + os=-coff + ;; + # This must come before the *-dec entry. + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + # This also exists in the configure program, but was not the + # default. + # os=-sunos4 + ;; + m68*-cisco) + os=-aout + ;; + mep-*) + os=-elf + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + or32-*) + os=-coff + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-haiku) + os=-haiku + ;; + *-ibm) + os=-aix + ;; + *-knuth) + os=-mmixware + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -os400*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -tpf*) + vendor=ibm + ;; + -vxsim* | -vxworks* | -windiss*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + -vos*) + vendor=stratus + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/components/external/SQLite-3.8.1/configure b/components/external/SQLite-3.8.1/configure new file mode 100644 index 0000000000000000000000000000000000000000..57546c1a5859b1984507170c305ec560fb98d1b6 --- /dev/null +++ b/components/external/SQLite-3.8.1/configure @@ -0,0 +1,15745 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.62 for sqlite 3.8.1. +# +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +# 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## --------------------- ## +## M4sh Initialization. ## +## --------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + + + +# PATH needs CR +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + +# Support unset when possible. +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + as_unset=unset +else + as_unset=false +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + { (exit 1); exit 1; } +fi + +# Work around bugs in pre-3.0 UWIN ksh. +for as_var in ENV MAIL MAILPATH +do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# Required to use basename. +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + + +# Name of the executable. +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# CDPATH. +$as_unset CDPATH + + +if test "x$CONFIG_SHELL" = x; then + if (eval ":") 2>/dev/null; then + as_have_required=yes +else + as_have_required=no +fi + + if test $as_have_required = yes && (eval ": +(as_func_return () { + (exit \$1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = \"\$1\" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test \$exitcode = 0) || { (exit 1); exit 1; } + +( + as_lineno_1=\$LINENO + as_lineno_2=\$LINENO + test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && + test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } +") 2> /dev/null; then + : +else + as_candidate_shells= + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + case $as_dir in + /*) + for as_base in sh bash ksh sh5; do + as_candidate_shells="$as_candidate_shells $as_dir/$as_base" + done;; + esac +done +IFS=$as_save_IFS + + + for as_shell in $as_candidate_shells $SHELL; do + # Try only shells that exist, to save several forks. + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { ("$as_shell") 2> /dev/null <<\_ASEOF +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + +: +_ASEOF +}; then + CONFIG_SHELL=$as_shell + as_have_required=yes + if { "$as_shell" 2> /dev/null <<\_ASEOF +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + +: +(as_func_return () { + (exit $1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = "$1" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test $exitcode = 0) || { (exit 1); exit 1; } + +( + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } + +_ASEOF +}; then + break +fi + +fi + + done + + if test "x$CONFIG_SHELL" != x; then + for as_var in BASH_ENV ENV + do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var + done + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} +fi + + + if test $as_have_required = no; then + echo This script requires a shell more modern than all the + echo shells that I found on your system. Please install a + echo modern shell, or manually run the script under such a + echo shell if you do have one. + { (exit 1); exit 1; } +fi + + +fi + +fi + + + +(eval "as_func_return () { + (exit \$1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = \"\$1\" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test \$exitcode = 0") || { + echo No shell found that supports shell functions. + echo Please tell bug-autoconf@gnu.org about your system, + echo including any error possibly output before this message. + echo This can help us improve future autoconf versions. + echo Configuration will now proceed without shell functions. +} + + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { + + # Create $as_me.lineno as a copy of $as_myself, but with $LINENO + # uniformly replaced by the line number. The first 'sed' inserts a + # line-number line after each line using $LINENO; the second 'sed' + # does the real work. The second script uses 'N' to pair each + # line-number line with the line containing $LINENO, and appends + # trailing '-' during substitution so that $LINENO is not a special + # case at line end. + # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the + # scripts with optimization help from Paolo Bonzini. Blame Lee + # E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { (exit 1); exit 1; }; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in +-n*) + case `echo 'x\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + *) ECHO_C='\c';; + esac;; +*) + ECHO_N='-n';; +esac +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -p' + fi +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p=: +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + + + +# Check that we are running under the correct shell. +SHELL=${CONFIG_SHELL-/bin/sh} + +case X$lt_ECHO in +X*--fallback-echo) + # Remove one level of quotation (which was required for Make). + ECHO=`echo "$lt_ECHO" | sed 's,\\\\\$\\$0,'$0','` + ;; +esac + +ECHO=${lt_ECHO-echo} +if test "X$1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X$1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' ; then + # Yippee, $ECHO works! + : +else + # Restart under the correct shell. + exec $SHELL "$0" --no-reexec ${1+"$@"} +fi + +if test "X$1" = X--fallback-echo; then + # used as fallback echo + shift + cat <<_LT_EOF +$* +_LT_EOF + exit 0 +fi + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +if test -z "$lt_ECHO"; then + if test "X${echo_test_string+set}" != Xset; then + # find a string as large as possible, as long as the shell can cope with it + for cmd in 'sed 50q "$0"' 'sed 20q "$0"' 'sed 10q "$0"' 'sed 2q "$0"' 'echo test'; do + # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ... + if { echo_test_string=`eval $cmd`; } 2>/dev/null && + { test "X$echo_test_string" = "X$echo_test_string"; } 2>/dev/null + then + break + fi + done + fi + + if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' && + echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + : + else + # The Solaris, AIX, and Digital Unix default echo programs unquote + # backslashes. This makes it impossible to quote backslashes using + # echo "$something" | sed 's/\\/\\\\/g' + # + # So, first we look for a working echo in the user's PATH. + + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for dir in $PATH /usr/ucb; do + IFS="$lt_save_ifs" + if (test -f $dir/echo || test -f $dir/echo$ac_exeext) && + test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' && + echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + ECHO="$dir/echo" + break + fi + done + IFS="$lt_save_ifs" + + if test "X$ECHO" = Xecho; then + # We didn't find a better echo, so look for alternatives. + if test "X`{ print -r '\t'; } 2>/dev/null`" = 'X\t' && + echo_testing_string=`{ print -r "$echo_test_string"; } 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # This shell has a builtin print -r that does the trick. + ECHO='print -r' + elif { test -f /bin/ksh || test -f /bin/ksh$ac_exeext; } && + test "X$CONFIG_SHELL" != X/bin/ksh; then + # If we have ksh, try running configure again with it. + ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} + export ORIGINAL_CONFIG_SHELL + CONFIG_SHELL=/bin/ksh + export CONFIG_SHELL + exec $CONFIG_SHELL "$0" --no-reexec ${1+"$@"} + else + # Try using printf. + ECHO='printf %s\n' + if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' && + echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + # Cool, printf works + : + elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL + export CONFIG_SHELL + SHELL="$CONFIG_SHELL" + export SHELL + ECHO="$CONFIG_SHELL $0 --fallback-echo" + elif echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` && + test "X$echo_testing_string" = 'X\t' && + echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` && + test "X$echo_testing_string" = "X$echo_test_string"; then + ECHO="$CONFIG_SHELL $0 --fallback-echo" + else + # maybe with a smaller string... + prev=: + + for cmd in 'echo test' 'sed 2q "$0"' 'sed 10q "$0"' 'sed 20q "$0"' 'sed 50q "$0"'; do + if { test "X$echo_test_string" = "X`eval $cmd`"; } 2>/dev/null + then + break + fi + prev="$cmd" + done + + if test "$prev" != 'sed 50q "$0"'; then + echo_test_string=`eval $prev` + export echo_test_string + exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "$0" ${1+"$@"} + else + # Oops. We lost completely, so just stick with echo. + ECHO=echo + fi + fi + fi + fi + fi +fi + +# Copy echo and quote the copy suitably for passing to libtool from +# the Makefile, instead of quoting the original, which is used later. +lt_ECHO=$ECHO +if test "X$lt_ECHO" = "X$CONFIG_SHELL $0 --fallback-echo"; then + lt_ECHO="$CONFIG_SHELL \\\$\$0 --fallback-echo" +fi + + + + +exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= +SHELL=${CONFIG_SHELL-/bin/sh} + +# Identity of this package. +PACKAGE_NAME='sqlite' +PACKAGE_TARNAME='sqlite' +PACKAGE_VERSION='3.8.1' +PACKAGE_STRING='sqlite 3.8.1' +PACKAGE_BUGREPORT='' + +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef STDC_HEADERS +# include +# include +#else +# ifdef HAVE_STDLIB_H +# include +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H +# include +# endif +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_INTTYPES_H +# include +#endif +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif" + +ac_subst_vars='SHELL +PATH_SEPARATOR +PACKAGE_NAME +PACKAGE_TARNAME +PACKAGE_VERSION +PACKAGE_STRING +PACKAGE_BUGREPORT +exec_prefix +prefix +program_transform_name +bindir +sbindir +libexecdir +datarootdir +datadir +sysconfdir +sharedstatedir +localstatedir +includedir +oldincludedir +docdir +infodir +htmldir +dvidir +pdfdir +psdir +libdir +localedir +mandir +DEFS +ECHO_C +ECHO_N +ECHO_T +LIBS +build_alias +host_alias +target_alias +LIBTOOL +build +build_cpu +build_vendor +build_os +host +host_cpu +host_vendor +host_os +CC +CFLAGS +LDFLAGS +CPPFLAGS +ac_ct_CC +EXEEXT +OBJEXT +SED +GREP +EGREP +FGREP +LD +DUMPBIN +ac_ct_DUMPBIN +NM +LN_S +OBJDUMP +AR +STRIP +RANLIB +lt_ECHO +DSYMUTIL +NMEDIT +LIPO +OTOOL +OTOOL64 +CPP +INSTALL_PROGRAM +INSTALL_SCRIPT +INSTALL_DATA +AWK +TCLSH_CMD +TCLLIBDIR +program_prefix +VERSION +RELEASE +VERSION_NUMBER +BUILD_CC +SQLITE_THREADSAFE +XTHREADCONNECT +ALLOWRELEASE +TEMP_STORE +BUILD_EXEEXT +SQLITE_OS_UNIX +SQLITE_OS_WIN +TARGET_EXEEXT +TCL_VERSION +TCL_BIN_DIR +TCL_SRC_DIR +TCL_INCLUDE_SPEC +TCL_LIB_FILE +TCL_LIB_FLAG +TCL_LIB_SPEC +TCL_STUB_LIB_FILE +TCL_STUB_LIB_FLAG +TCL_STUB_LIB_SPEC +HAVE_TCL +TARGET_READLINE_LIBS +TARGET_READLINE_INC +TARGET_HAVE_READLINE +TARGET_DEBUG +USE_AMALGAMATION +OPT_FEATURE_FLAGS +USE_GCOV +BUILD_CFLAGS +LIBOBJS +LTLIBOBJS' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_shared +enable_static +with_pic +enable_fast_install +with_gnu_ld +enable_libtool_lock +enable_largefile +with_hints +enable_threadsafe +enable_cross_thread_connections +enable_releasemode +enable_tempstore +enable_tcl +with_tcl +enable_readline +with_readline_lib +with_readline_inc +enable_debug +enable_amalgamation +enable_load_extension +enable_gcov +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CPP +TCLLIBDIR' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 + { (exit 1); exit 1; }; } + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 + { (exit 1); exit 1; }; } + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 + { (exit 1); exit 1; }; } + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 + { (exit 1); exit 1; }; } + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) { $as_echo "$as_me: error: unrecognized option: $ac_option +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; } + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid variable name: $ac_envvar" >&2 + { (exit 1); exit 1; }; } + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + { $as_echo "$as_me: error: missing argument to $ac_option" >&2 + { (exit 1); exit 1; }; } +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) { $as_echo "$as_me: error: Unrecognized options: $ac_unrecognized_opts" >&2 + { (exit 1); exit 1; }; } ;; + *) $as_echo "$as_me: WARNING: Unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + { $as_echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 + { (exit 1); exit 1; }; } +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. + If a cross compiler is detected then cross compile mode will be used." >&2 + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + { $as_echo "$as_me: error: Working directory cannot be determined" >&2 + { (exit 1); exit 1; }; } +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + { $as_echo "$as_me: error: pwd does not report name of working directory" >&2 + { (exit 1); exit 1; }; } + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + { $as_echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 + { (exit 1); exit 1; }; } +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || { $as_echo "$as_me: error: $ac_msg" >&2 + { (exit 1); exit 1; }; } + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures sqlite 3.8.1 to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/sqlite] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF + +System types: + --build=BUILD configure for building on BUILD [guessed] + --host=HOST cross-compile to build programs to run on HOST [BUILD] +_ACEOF +fi + +if test -n "$ac_init_help"; then + case $ac_init_help in + short | recursive ) echo "Configuration of sqlite 3.8.1:";; + esac + cat <<\_ACEOF + +Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --enable-shared[=PKGS] build shared libraries [default=yes] + --enable-static[=PKGS] build static libraries [default=yes] + --enable-fast-install[=PKGS] + optimize for fast installation [default=yes] + --disable-libtool-lock avoid locking (might break parallel builds) + --disable-largefile omit support for large files + --enable-threadsafe Support threadsafe operation + --enable-cross-thread-connections + Allow connection sharing across threads + --enable-releasemode Support libtool link to release mode + --enable-tempstore Use an in-ram database for temporary tables + (never,no,yes,always) + --disable-tcl do not build TCL extension + --disable-readline disable readline support [default=detect] + --enable-debug enable debugging & verbose explain + --disable-amalgamation Disable the amalgamation and instead build all files + separately + --enable-load-extension Enable loading of external extensions + --enable-gcov Enable coverage testing using gcov + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-pic try to use only PIC/non-PIC objects [default=use + both] + --with-gnu-ld assume the C compiler uses GNU ld [default=no] + --with-hints=FILE Read configuration options from FILE + --with-tcl=DIR directory containing tcl configuration + (tclConfig.sh) + --with-readline-lib specify readline library + --with-readline-inc specify readline include paths + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CPP C preprocessor + TCLLIBDIR Where to install tcl plugin + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +sqlite configure 3.8.1 +generated by GNU Autoconf 2.62 + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by sqlite $as_me 3.8.1, which was +generated by GNU Autoconf 2.62. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" +done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; + 2) + ac_configure_args1="$ac_configure_args1 '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + ac_configure_args="$ac_configure_args '$ac_arg'" + ;; + esac + done +done +$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } +$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + cat <<\_ASBOX +## ---------------- ## +## Cache variables. ## +## ---------------- ## +_ASBOX + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 +$as_echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) $as_unset $ac_var ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + cat <<\_ASBOX +## ----------------- ## +## Output variables. ## +## ----------------- ## +_ASBOX + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + cat <<\_ASBOX +## ------------------- ## +## File substitutions. ## +## ------------------- ## +_ASBOX + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + cat <<\_ASBOX +## ----------- ## +## confdefs.h. ## +## ----------- ## +_ASBOX + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + ac_site_file1=$CONFIG_SITE +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test -r "$ac_site_file"; then + { $as_echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special + # files actually), so we avoid doing that. + if test -f "$cache_file"; then + { $as_echo "$as_me:$LINENO: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:$LINENO: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:$LINENO: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:$LINENO: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:$LINENO: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + { { $as_echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 +$as_echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} + { (exit 1); exit 1; }; } +fi + + + + + + + + + + + + + + + + + + + + + + + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +sqlite_version_sanity_check=`cat $srcdir/VERSION | tr -d '\n'` +if test "$PACKAGE_VERSION" != "$sqlite_version_sanity_check" ; then +{ { $as_echo "$as_me:$LINENO: error: configure script is out of date: + configure \$PACKAGE_VERSION = $PACKAGE_VERSION + top level VERSION file = $sqlite_version_sanity_check +please regen with autoconf" >&5 +$as_echo "$as_me: error: configure script is out of date: + configure \$PACKAGE_VERSION = $PACKAGE_VERSION + top level VERSION file = $sqlite_version_sanity_check +please regen with autoconf" >&2;} + { (exit 1); exit 1; }; } +fi + +# The following RCS revision string applies to configure.in +# $Revision: 1.56 $ + +######### +# Programs needed +# +case `pwd` in + *\ * | *\ *) + { $as_echo "$as_me:$LINENO: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 +$as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; +esac + + + +macro_version='2.2.6' +macro_revision='1.3012' + + + + + + + + + + + + + +ltmain="$ac_aux_dir/ltmain.sh" + +ac_aux_dir= +for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do + if test -f "$ac_dir/install-sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install-sh -c" + break + elif test -f "$ac_dir/install.sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install.sh -c" + break + elif test -f "$ac_dir/shtool"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/shtool install -c" + break + fi +done +if test -z "$ac_aux_dir"; then + { { $as_echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 +$as_echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} + { (exit 1); exit 1; }; } +fi + +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. +ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. +ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. + + +# Make sure we can run config.sub. +$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || + { { $as_echo "$as_me:$LINENO: error: cannot run $SHELL $ac_aux_dir/config.sub" >&5 +$as_echo "$as_me: error: cannot run $SHELL $ac_aux_dir/config.sub" >&2;} + { (exit 1); exit 1; }; } + +{ $as_echo "$as_me:$LINENO: checking build system type" >&5 +$as_echo_n "checking build system type... " >&6; } +if test "${ac_cv_build+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_build_alias=$build_alias +test "x$ac_build_alias" = x && + ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` +test "x$ac_build_alias" = x && + { { $as_echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5 +$as_echo "$as_me: error: cannot guess build type; you must specify one" >&2;} + { (exit 1); exit 1; }; } +ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || + { { $as_echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&5 +$as_echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&2;} + { (exit 1); exit 1; }; } + +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_build" >&5 +$as_echo "$ac_cv_build" >&6; } +case $ac_cv_build in +*-*-*) ;; +*) { { $as_echo "$as_me:$LINENO: error: invalid value of canonical build" >&5 +$as_echo "$as_me: error: invalid value of canonical build" >&2;} + { (exit 1); exit 1; }; };; +esac +build=$ac_cv_build +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_build +shift +build_cpu=$1 +build_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +build_os=$* +IFS=$ac_save_IFS +case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac + + +{ $as_echo "$as_me:$LINENO: checking host system type" >&5 +$as_echo_n "checking host system type... " >&6; } +if test "${ac_cv_host+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build +else + ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || + { { $as_echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&5 +$as_echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&2;} + { (exit 1); exit 1; }; } +fi + +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_host" >&5 +$as_echo "$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) { { $as_echo "$as_me:$LINENO: error: invalid value of canonical host" >&5 +$as_echo "$as_me: error: invalid value of canonical host" >&2;} + { (exit 1); exit 1; }; };; +esac +host=$ac_cv_host +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: no acceptable C compiler found in \$PATH +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } + +# Provide some information about the compiler. +$as_echo "$as_me:$LINENO: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +{ (ac_try="$ac_compiler --version >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compiler --version >&5") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -v >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compiler -v >&5") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -V >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compiler -V >&5") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { (ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi + +{ $as_echo "$as_me:$LINENO: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +if test -z "$ac_file"; then + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:$LINENO: error: C compiler cannot create executables +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: C compiler cannot create executables +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } +fi + +ac_exeext=$ac_cv_exeext + +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:$LINENO: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +# FIXME: These cross compiler hacks should be removed for Autoconf 3.0 +# If not cross compiling, check that we can run a simple program. +if test "$cross_compiling" != yes; then + if { ac_try='./$ac_file' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:$LINENO: error: cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } + fi + fi +fi +{ $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +{ $as_echo "$as_me:$LINENO: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +{ $as_echo "$as_me:$LINENO: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { $as_echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +rm -f conftest$ac_cv_exeext +{ $as_echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +{ $as_echo "$as_me:$LINENO: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if test "${ac_cv_objext+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: cannot compute suffix of object files: cannot compile +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if test "${ac_cv_c_compiler_gnu+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_compiler_gnu=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_compiler_gnu=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if test "${ac_cv_prog_cc_g+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_g=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + CFLAGS="" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_g=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if test "${ac_cv_prog_cc_c89+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#include +#include +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_c89=$ac_arg +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:$LINENO: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:$LINENO: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +{ $as_echo "$as_me:$LINENO: checking for a sed that does not truncate output" >&5 +$as_echo_n "checking for a sed that does not truncate output... " >&6; } +if test "${ac_cv_path_SED+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ + for ac_i in 1 2 3 4 5 6 7; do + ac_script="$ac_script$as_nl$ac_script" + done + echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed + $as_unset ac_script || ac_script= + if test -z "$SED"; then + ac_path_SED_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in sed gsed; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_SED" && $as_test_x "$ac_path_SED"; } || continue +# Check for GNU ac_path_SED and select it if it is found. + # Check for GNU $ac_path_SED +case `"$ac_path_SED" --version 2>&1` in +*GNU*) + ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo '' >> "conftest.nl" + "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + ac_count=`expr $ac_count + 1` + if test $ac_count -gt ${ac_path_SED_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_SED="$ac_path_SED" + ac_path_SED_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_SED_found && break 3 + done + done +done +IFS=$as_save_IFS + if test -z "$ac_cv_path_SED"; then + { { $as_echo "$as_me:$LINENO: error: no acceptable sed could be found in \$PATH" >&5 +$as_echo "$as_me: error: no acceptable sed could be found in \$PATH" >&2;} + { (exit 1); exit 1; }; } + fi +else + ac_cv_path_SED=$SED +fi + +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_SED" >&5 +$as_echo "$ac_cv_path_SED" >&6; } + SED="$ac_cv_path_SED" + rm -f conftest.sed + +test -z "$SED" && SED=sed +Xsed="$SED -e 1s/^X//" + + + + + + + + + + + +{ $as_echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if test "${ac_cv_path_GREP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + ac_count=`expr $ac_count + 1` + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_GREP_found && break 3 + done + done +done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + { { $as_echo "$as_me:$LINENO: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +$as_echo "$as_me: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ $as_echo "$as_me:$LINENO: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if test "${ac_cv_path_EGREP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + ac_count=`expr $ac_count + 1` + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done +done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + { { $as_echo "$as_me:$LINENO: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +$as_echo "$as_me: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ $as_echo "$as_me:$LINENO: checking for fgrep" >&5 +$as_echo_n "checking for fgrep... " >&6; } +if test "${ac_cv_path_FGREP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 + then ac_cv_path_FGREP="$GREP -F" + else + if test -z "$FGREP"; then + ac_path_FGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in fgrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_FGREP" && $as_test_x "$ac_path_FGREP"; } || continue +# Check for GNU ac_path_FGREP and select it if it is found. + # Check for GNU $ac_path_FGREP +case `"$ac_path_FGREP" --version 2>&1` in +*GNU*) + ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'FGREP' >> "conftest.nl" + "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + ac_count=`expr $ac_count + 1` + if test $ac_count -gt ${ac_path_FGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_FGREP="$ac_path_FGREP" + ac_path_FGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_FGREP_found && break 3 + done + done +done +IFS=$as_save_IFS + if test -z "$ac_cv_path_FGREP"; then + { { $as_echo "$as_me:$LINENO: error: no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +$as_echo "$as_me: error: no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } + fi +else + ac_cv_path_FGREP=$FGREP +fi + + fi +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_FGREP" >&5 +$as_echo "$ac_cv_path_FGREP" >&6; } + FGREP="$ac_cv_path_FGREP" + + +test -z "$GREP" && GREP=grep + + + + + + + + + + + + + + + + + + + +# Check whether --with-gnu-ld was given. +if test "${with_gnu_ld+set}" = set; then + withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes +else + with_gnu_ld=no +fi + +ac_prog=ld +if test "$GCC" = yes; then + # Check if gcc -print-prog-name=ld gives a path. + { $as_echo "$as_me:$LINENO: checking for ld used by $CC" >&5 +$as_echo_n "checking for ld used by $CC... " >&6; } + case $host in + *-*-mingw*) + # gcc leaves a trailing carriage return which upsets mingw + ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; + *) + ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; + esac + case $ac_prog in + # Accept absolute paths. + [\\/]* | ?:[\\/]*) + re_direlt='/[^/][^/]*/\.\./' + # Canonicalize the pathname of ld + ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` + while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do + ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` + done + test -z "$LD" && LD="$ac_prog" + ;; + "") + # If it fails, then pretend we aren't using GCC. + ac_prog=ld + ;; + *) + # If it is relative, then search for the first ld in PATH. + with_gnu_ld=unknown + ;; + esac +elif test "$with_gnu_ld" = yes; then + { $as_echo "$as_me:$LINENO: checking for GNU ld" >&5 +$as_echo_n "checking for GNU ld... " >&6; } +else + { $as_echo "$as_me:$LINENO: checking for non-GNU ld" >&5 +$as_echo_n "checking for non-GNU ld... " >&6; } +fi +if test "${lt_cv_path_LD+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -z "$LD"; then + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then + lt_cv_path_LD="$ac_dir/$ac_prog" + # Check to see if the program is GNU ld. I'd rather use --version, + # but apparently some variants of GNU ld only accept -v. + # Break only if it was the GNU/non-GNU ld that we prefer. + case `"$lt_cv_path_LD" -v 2>&1 &5 +$as_echo "$LD" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi +test -z "$LD" && { { $as_echo "$as_me:$LINENO: error: no acceptable ld found in \$PATH" >&5 +$as_echo "$as_me: error: no acceptable ld found in \$PATH" >&2;} + { (exit 1); exit 1; }; } +{ $as_echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5 +$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } +if test "${lt_cv_prog_gnu_ld+set}" = set; then + $as_echo_n "(cached) " >&6 +else + # I'd rather use --version here, but apparently some GNU lds only accept -v. +case `$LD -v 2>&1 &5 +$as_echo "$lt_cv_prog_gnu_ld" >&6; } +with_gnu_ld=$lt_cv_prog_gnu_ld + + + + + + + + + +{ $as_echo "$as_me:$LINENO: checking for BSD- or MS-compatible name lister (nm)" >&5 +$as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; } +if test "${lt_cv_path_NM+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$NM"; then + # Let the user override the test. + lt_cv_path_NM="$NM" +else + lt_nm_to_check="${ac_tool_prefix}nm" + if test -n "$ac_tool_prefix" && test "$build" = "$host"; then + lt_nm_to_check="$lt_nm_to_check nm" + fi + for lt_tmp_nm in $lt_nm_to_check; do + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + tmp_nm="$ac_dir/$lt_tmp_nm" + if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then + # Check to see if the nm accepts a BSD-compat flag. + # Adding the `sed 1q' prevents false positives on HP-UX, which says: + # nm: unknown option "B" ignored + # Tru64's nm complains that /dev/null is an invalid object file + case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in + */dev/null* | *'Invalid file or object type'*) + lt_cv_path_NM="$tmp_nm -B" + break + ;; + *) + case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in + */dev/null*) + lt_cv_path_NM="$tmp_nm -p" + break + ;; + *) + lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but + continue # so that we can try to find one that supports BSD flags + ;; + esac + ;; + esac + fi + done + IFS="$lt_save_ifs" + done + : ${lt_cv_path_NM=no} +fi +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_path_NM" >&5 +$as_echo "$lt_cv_path_NM" >&6; } +if test "$lt_cv_path_NM" != "no"; then + NM="$lt_cv_path_NM" +else + # Didn't find any BSD compatible name lister, look for dumpbin. + if test -n "$ac_tool_prefix"; then + for ac_prog in "dumpbin -symbols" "link -dump -symbols" + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_DUMPBIN+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$DUMPBIN"; then + ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +DUMPBIN=$ac_cv_prog_DUMPBIN +if test -n "$DUMPBIN"; then + { $as_echo "$as_me:$LINENO: result: $DUMPBIN" >&5 +$as_echo "$DUMPBIN" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$DUMPBIN" && break + done +fi +if test -z "$DUMPBIN"; then + ac_ct_DUMPBIN=$DUMPBIN + for ac_prog in "dumpbin -symbols" "link -dump -symbols" +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_DUMPBIN+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_DUMPBIN"; then + ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN +if test -n "$ac_ct_DUMPBIN"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_DUMPBIN" >&5 +$as_echo "$ac_ct_DUMPBIN" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_DUMPBIN" && break +done + + if test "x$ac_ct_DUMPBIN" = x; then + DUMPBIN=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + DUMPBIN=$ac_ct_DUMPBIN + fi +fi + + + if test "$DUMPBIN" != ":"; then + NM="$DUMPBIN" + fi +fi +test -z "$NM" && NM=nm + + + + + + +{ $as_echo "$as_me:$LINENO: checking the name lister ($NM) interface" >&5 +$as_echo_n "checking the name lister ($NM) interface... " >&6; } +if test "${lt_cv_nm_interface+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_nm_interface="BSD nm" + echo "int some_variable = 0;" > conftest.$ac_ext + (eval echo "\"\$as_me:3735: $ac_compile\"" >&5) + (eval "$ac_compile" 2>conftest.err) + cat conftest.err >&5 + (eval echo "\"\$as_me:3738: $NM \\\"conftest.$ac_objext\\\"\"" >&5) + (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) + cat conftest.err >&5 + (eval echo "\"\$as_me:3741: output\"" >&5) + cat conftest.out >&5 + if $GREP 'External.*some_variable' conftest.out > /dev/null; then + lt_cv_nm_interface="MS dumpbin" + fi + rm -f conftest* +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_nm_interface" >&5 +$as_echo "$lt_cv_nm_interface" >&6; } + +{ $as_echo "$as_me:$LINENO: checking whether ln -s works" >&5 +$as_echo_n "checking whether ln -s works... " >&6; } +LN_S=$as_ln_s +if test "$LN_S" = "ln -s"; then + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no, using $LN_S" >&5 +$as_echo "no, using $LN_S" >&6; } +fi + +# find the maximum length of command line arguments +{ $as_echo "$as_me:$LINENO: checking the maximum length of command line arguments" >&5 +$as_echo_n "checking the maximum length of command line arguments... " >&6; } +if test "${lt_cv_sys_max_cmd_len+set}" = set; then + $as_echo_n "(cached) " >&6 +else + i=0 + teststring="ABCD" + + case $build_os in + msdosdjgpp*) + # On DJGPP, this test can blow up pretty badly due to problems in libc + # (any single argument exceeding 2000 bytes causes a buffer overrun + # during glob expansion). Even if it were fixed, the result of this + # check would be larger than it should be. + lt_cv_sys_max_cmd_len=12288; # 12K is about right + ;; + + gnu*) + # Under GNU Hurd, this test is not required because there is + # no limit to the length of command line arguments. + # Libtool will interpret -1 as no limit whatsoever + lt_cv_sys_max_cmd_len=-1; + ;; + + cygwin* | mingw* | cegcc*) + # On Win9x/ME, this test blows up -- it succeeds, but takes + # about 5 minutes as the teststring grows exponentially. + # Worse, since 9x/ME are not pre-emptively multitasking, + # you end up with a "frozen" computer, even though with patience + # the test eventually succeeds (with a max line length of 256k). + # Instead, let's just punt: use the minimum linelength reported by + # all of the supported platforms: 8192 (on NT/2K/XP). + lt_cv_sys_max_cmd_len=8192; + ;; + + amigaos*) + # On AmigaOS with pdksh, this test takes hours, literally. + # So we just punt and use a minimum line length of 8192. + lt_cv_sys_max_cmd_len=8192; + ;; + + netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) + # This has been around since 386BSD, at least. Likely further. + if test -x /sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` + elif test -x /usr/sbin/sysctl; then + lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` + else + lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs + fi + # And add a safety zone + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + ;; + + interix*) + # We know the value 262144 and hardcode it with a safety zone (like BSD) + lt_cv_sys_max_cmd_len=196608 + ;; + + osf*) + # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure + # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not + # nice to cause kernel panics so lets avoid the loop below. + # First set a reasonable default. + lt_cv_sys_max_cmd_len=16384 + # + if test -x /sbin/sysconfig; then + case `/sbin/sysconfig -q proc exec_disable_arg_limit` in + *1*) lt_cv_sys_max_cmd_len=-1 ;; + esac + fi + ;; + sco3.2v5*) + lt_cv_sys_max_cmd_len=102400 + ;; + sysv5* | sco5v6* | sysv4.2uw2*) + kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` + if test -n "$kargmax"; then + lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` + else + lt_cv_sys_max_cmd_len=32768 + fi + ;; + *) + lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` + if test -n "$lt_cv_sys_max_cmd_len"; then + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` + else + # Make teststring a little bigger before we do anything with it. + # a 1K string should be a reasonable start. + for i in 1 2 3 4 5 6 7 8 ; do + teststring=$teststring$teststring + done + SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} + # If test is not a shell built-in, we'll probably end up computing a + # maximum length that is only half of the actual maximum length, but + # we can't tell. + while { test "X"`$SHELL $0 --fallback-echo "X$teststring$teststring" 2>/dev/null` \ + = "XX$teststring$teststring"; } >/dev/null 2>&1 && + test $i != 17 # 1/2 MB should be enough + do + i=`expr $i + 1` + teststring=$teststring$teststring + done + # Only check the string length outside the loop. + lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` + teststring= + # Add a significant safety factor because C++ compilers can tack on + # massive amounts of additional arguments before passing them to the + # linker. It appears as though 1/2 is a usable value. + lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` + fi + ;; + esac + +fi + +if test -n $lt_cv_sys_max_cmd_len ; then + { $as_echo "$as_me:$LINENO: result: $lt_cv_sys_max_cmd_len" >&5 +$as_echo "$lt_cv_sys_max_cmd_len" >&6; } +else + { $as_echo "$as_me:$LINENO: result: none" >&5 +$as_echo "none" >&6; } +fi +max_cmd_len=$lt_cv_sys_max_cmd_len + + + + + + +: ${CP="cp -f"} +: ${MV="mv -f"} +: ${RM="rm -f"} + +{ $as_echo "$as_me:$LINENO: checking whether the shell understands some XSI constructs" >&5 +$as_echo_n "checking whether the shell understands some XSI constructs... " >&6; } +# Try some XSI features +xsi_shell=no +( _lt_dummy="a/b/c" + test "${_lt_dummy##*/},${_lt_dummy%/*},"${_lt_dummy%"$_lt_dummy"}, \ + = c,a/b,, \ + && eval 'test $(( 1 + 1 )) -eq 2 \ + && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ + && xsi_shell=yes +{ $as_echo "$as_me:$LINENO: result: $xsi_shell" >&5 +$as_echo "$xsi_shell" >&6; } + + +{ $as_echo "$as_me:$LINENO: checking whether the shell understands \"+=\"" >&5 +$as_echo_n "checking whether the shell understands \"+=\"... " >&6; } +lt_shell_append=no +( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \ + >/dev/null 2>&1 \ + && lt_shell_append=yes +{ $as_echo "$as_me:$LINENO: result: $lt_shell_append" >&5 +$as_echo "$lt_shell_append" >&6; } + + +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + lt_unset=unset +else + lt_unset=false +fi + + + + + +# test EBCDIC or ASCII +case `echo X|tr X '\101'` in + A) # ASCII based system + # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr + lt_SP2NL='tr \040 \012' + lt_NL2SP='tr \015\012 \040\040' + ;; + *) # EBCDIC based system + lt_SP2NL='tr \100 \n' + lt_NL2SP='tr \r\n \100\100' + ;; +esac + + + + + + + + + +{ $as_echo "$as_me:$LINENO: checking for $LD option to reload object files" >&5 +$as_echo_n "checking for $LD option to reload object files... " >&6; } +if test "${lt_cv_ld_reload_flag+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_ld_reload_flag='-r' +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_ld_reload_flag" >&5 +$as_echo "$lt_cv_ld_reload_flag" >&6; } +reload_flag=$lt_cv_ld_reload_flag +case $reload_flag in +"" | " "*) ;; +*) reload_flag=" $reload_flag" ;; +esac +reload_cmds='$LD$reload_flag -o $output$reload_objs' +case $host_os in + darwin*) + if test "$GCC" = yes; then + reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' + else + reload_cmds='$LD$reload_flag -o $output$reload_objs' + fi + ;; +esac + + + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. +set dummy ${ac_tool_prefix}objdump; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_OBJDUMP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$OBJDUMP"; then + ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +OBJDUMP=$ac_cv_prog_OBJDUMP +if test -n "$OBJDUMP"; then + { $as_echo "$as_me:$LINENO: result: $OBJDUMP" >&5 +$as_echo "$OBJDUMP" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OBJDUMP"; then + ac_ct_OBJDUMP=$OBJDUMP + # Extract the first word of "objdump", so it can be a program name with args. +set dummy objdump; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_OBJDUMP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_OBJDUMP"; then + ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_OBJDUMP="objdump" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP +if test -n "$ac_ct_OBJDUMP"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_OBJDUMP" >&5 +$as_echo "$ac_ct_OBJDUMP" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_OBJDUMP" = x; then + OBJDUMP="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + OBJDUMP=$ac_ct_OBJDUMP + fi +else + OBJDUMP="$ac_cv_prog_OBJDUMP" +fi + +test -z "$OBJDUMP" && OBJDUMP=objdump + + + + + + + + + +{ $as_echo "$as_me:$LINENO: checking how to recognize dependent libraries" >&5 +$as_echo_n "checking how to recognize dependent libraries... " >&6; } +if test "${lt_cv_deplibs_check_method+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_file_magic_cmd='$MAGIC_CMD' +lt_cv_file_magic_test_file= +lt_cv_deplibs_check_method='unknown' +# Need to set the preceding variable on all platforms that support +# interlibrary dependencies. +# 'none' -- dependencies not supported. +# `unknown' -- same as none, but documents that we really don't know. +# 'pass_all' -- all dependencies passed with no checks. +# 'test_compile' -- check by making test program. +# 'file_magic [[regex]]' -- check by looking for files in library path +# which responds to the $file_magic_cmd with a given extended regex. +# If you have `file' or equivalent on your system and you're not sure +# whether `pass_all' will *always* work, you probably want this one. + +case $host_os in +aix[4-9]*) + lt_cv_deplibs_check_method=pass_all + ;; + +beos*) + lt_cv_deplibs_check_method=pass_all + ;; + +bsdi[45]*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' + lt_cv_file_magic_cmd='/usr/bin/file -L' + lt_cv_file_magic_test_file=/shlib/libc.so + ;; + +cygwin*) + # func_win32_libid is a shell function defined in ltmain.sh + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + ;; + +mingw* | pw32*) + # Base MSYS/MinGW do not provide the 'file' command needed by + # func_win32_libid shell function, so use a weaker test based on 'objdump', + # unless we find 'file', for example because we are cross-compiling. + if ( file / ) >/dev/null 2>&1; then + lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' + lt_cv_file_magic_cmd='func_win32_libid' + else + lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + fi + ;; + +cegcc) + # use the weaker test based on 'objdump'. See mingw*. + lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' + lt_cv_file_magic_cmd='$OBJDUMP -f' + ;; + +darwin* | rhapsody*) + lt_cv_deplibs_check_method=pass_all + ;; + +freebsd* | dragonfly*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + case $host_cpu in + i*86 ) + # Not sure whether the presence of OpenBSD here was a mistake. + # Let's accept both of them until this is cleared up. + lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` + ;; + esac + else + lt_cv_deplibs_check_method=pass_all + fi + ;; + +gnu*) + lt_cv_deplibs_check_method=pass_all + ;; + +hpux10.20* | hpux11*) + lt_cv_file_magic_cmd=/usr/bin/file + case $host_cpu in + ia64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' + lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so + ;; + hppa*64*) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]' + lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl + ;; + *) + lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9].[0-9]) shared library' + lt_cv_file_magic_test_file=/usr/lib/libc.sl + ;; + esac + ;; + +interix[3-9]*) + # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' + ;; + +irix5* | irix6* | nonstopux*) + case $LD in + *-32|*"-32 ") libmagic=32-bit;; + *-n32|*"-n32 ") libmagic=N32;; + *-64|*"-64 ") libmagic=64-bit;; + *) libmagic=never-match;; + esac + lt_cv_deplibs_check_method=pass_all + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + lt_cv_deplibs_check_method=pass_all + ;; + +netbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' + fi + ;; + +newos6*) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' + lt_cv_file_magic_cmd=/usr/bin/file + lt_cv_file_magic_test_file=/usr/lib/libnls.so + ;; + +*nto* | *qnx*) + lt_cv_deplibs_check_method=pass_all + ;; + +openbsd*) + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' + else + lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' + fi + ;; + +osf3* | osf4* | osf5*) + lt_cv_deplibs_check_method=pass_all + ;; + +rdos*) + lt_cv_deplibs_check_method=pass_all + ;; + +solaris*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + lt_cv_deplibs_check_method=pass_all + ;; + +sysv4 | sysv4.3*) + case $host_vendor in + motorola) + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' + lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` + ;; + ncr) + lt_cv_deplibs_check_method=pass_all + ;; + sequent) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' + ;; + sni) + lt_cv_file_magic_cmd='/bin/file' + lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" + lt_cv_file_magic_test_file=/lib/libc.so + ;; + siemens) + lt_cv_deplibs_check_method=pass_all + ;; + pc) + lt_cv_deplibs_check_method=pass_all + ;; + esac + ;; + +tpf*) + lt_cv_deplibs_check_method=pass_all + ;; +esac + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_deplibs_check_method" >&5 +$as_echo "$lt_cv_deplibs_check_method" >&6; } +file_magic_cmd=$lt_cv_file_magic_cmd +deplibs_check_method=$lt_cv_deplibs_check_method +test -z "$deplibs_check_method" && deplibs_check_method=unknown + + + + + + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args. +set dummy ${ac_tool_prefix}ar; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_AR+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$AR"; then + ac_cv_prog_AR="$AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_AR="${ac_tool_prefix}ar" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +AR=$ac_cv_prog_AR +if test -n "$AR"; then + { $as_echo "$as_me:$LINENO: result: $AR" >&5 +$as_echo "$AR" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_AR"; then + ac_ct_AR=$AR + # Extract the first word of "ar", so it can be a program name with args. +set dummy ar; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_AR+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_AR"; then + ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_AR="ar" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_AR=$ac_cv_prog_ac_ct_AR +if test -n "$ac_ct_AR"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_AR" >&5 +$as_echo "$ac_ct_AR" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_AR" = x; then + AR="false" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + AR=$ac_ct_AR + fi +else + AR="$ac_cv_prog_AR" +fi + +test -z "$AR" && AR=ar +test -z "$AR_FLAGS" && AR_FLAGS=cru + + + + + + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_STRIP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + { $as_echo "$as_me:$LINENO: result: $STRIP" >&5 +$as_echo "$STRIP" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_STRIP="strip" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5 +$as_echo "$ac_ct_STRIP" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_STRIP" = x; then + STRIP=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + STRIP=$ac_ct_STRIP + fi +else + STRIP="$ac_cv_prog_STRIP" +fi + +test -z "$STRIP" && STRIP=: + + + + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_RANLIB+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + { $as_echo "$as_me:$LINENO: result: $RANLIB" >&5 +$as_echo "$RANLIB" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 +$as_echo "$ac_ct_RANLIB" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_RANLIB" = x; then + RANLIB=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + RANLIB=$ac_ct_RANLIB + fi +else + RANLIB="$ac_cv_prog_RANLIB" +fi + +test -z "$RANLIB" && RANLIB=: + + + + + + +# Determine commands to create old-style static archives. +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' +old_postinstall_cmds='chmod 644 $oldlib' +old_postuninstall_cmds= + +if test -n "$RANLIB"; then + case $host_os in + openbsd*) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib" + ;; + *) + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib" + ;; + esac + old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib" +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + + +# Check for command to grab the raw symbol name followed by C symbol from nm. +{ $as_echo "$as_me:$LINENO: checking command to parse $NM output from $compiler object" >&5 +$as_echo_n "checking command to parse $NM output from $compiler object... " >&6; } +if test "${lt_cv_sys_global_symbol_pipe+set}" = set; then + $as_echo_n "(cached) " >&6 +else + +# These are sane defaults that work on at least a few old systems. +# [They come from Ultrix. What could be older than Ultrix?!! ;)] + +# Character class describing NM global symbol codes. +symcode='[BCDEGRST]' + +# Regexp to match symbols that can be accessed directly from C. +sympat='\([_A-Za-z][_A-Za-z0-9]*\)' + +# Define system-specific variables. +case $host_os in +aix*) + symcode='[BCDT]' + ;; +cygwin* | mingw* | pw32* | cegcc*) + symcode='[ABCDGISTW]' + ;; +hpux*) + if test "$host_cpu" = ia64; then + symcode='[ABCDEGRST]' + fi + ;; +irix* | nonstopux*) + symcode='[BCDEGRST]' + ;; +osf*) + symcode='[BCDEGQRST]' + ;; +solaris*) + symcode='[BDRT]' + ;; +sco3.2v5*) + symcode='[DT]' + ;; +sysv4.2uw2*) + symcode='[DT]' + ;; +sysv5* | sco5v6* | unixware* | OpenUNIX*) + symcode='[ABDT]' + ;; +sysv4) + symcode='[DFNSTU]' + ;; +esac + +# If we're using GNU nm, then use its standard symbol codes. +case `$NM -V 2>&1` in +*GNU* | *'with BFD'*) + symcode='[ABCDGIRSTW]' ;; +esac + +# Transform an extracted symbol line into a proper C declaration. +# Some systems (esp. on ia64) link data and code symbols differently, +# so use this general approach. +lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" + +# Transform an extracted symbol line into symbol name and symbol address +lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (void *) \&\2},/p'" +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"lib\2\", (void *) \&\2},/p'" + +# Handle CRLF in mingw tool chain +opt_cr= +case $build_os in +mingw*) + opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp + ;; +esac + +# Try without a prefix underscore, then with it. +for ac_symprfx in "" "_"; do + + # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. + symxfrm="\\1 $ac_symprfx\\2 \\2" + + # Write the raw and C identifiers. + if test "$lt_cv_nm_interface" = "MS dumpbin"; then + # Fake it for dumpbin and say T for any non-static function + # and D for any global variable. + # Also find C++ and __fastcall symbols from MSVC++, + # which start with @ or ?. + lt_cv_sys_global_symbol_pipe="$AWK '"\ +" {last_section=section; section=\$ 3};"\ +" /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ +" \$ 0!~/External *\|/{next};"\ +" / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ +" {if(hide[section]) next};"\ +" {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ +" {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ +" s[1]~/^[@?]/{print s[1], s[1]; next};"\ +" s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ +" ' prfx=^$ac_symprfx" + else + lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" + fi + + # Check to see that the pipe works correctly. + pipe_works=no + + rm -f conftest* + cat > conftest.$ac_ext <<_LT_EOF +#ifdef __cplusplus +extern "C" { +#endif +char nm_test_var; +void nm_test_func(void); +void nm_test_func(void){} +#ifdef __cplusplus +} +#endif +int main(){nm_test_var='a';nm_test_func();return(0);} +_LT_EOF + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # Now try to grab the symbols. + nlist=conftest.nm + if { (eval echo "$as_me:$LINENO: \"$NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist\"") >&5 + (eval $NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s "$nlist"; then + # Try sorting and uniquifying the output. + if sort "$nlist" | uniq > "$nlist"T; then + mv -f "$nlist"T "$nlist" + else + rm -f "$nlist"T + fi + + # Make sure that we snagged all the symbols we need. + if $GREP ' nm_test_var$' "$nlist" >/dev/null; then + if $GREP ' nm_test_func$' "$nlist" >/dev/null; then + cat <<_LT_EOF > conftest.$ac_ext +#ifdef __cplusplus +extern "C" { +#endif + +_LT_EOF + # Now generate the symbol file. + eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' + + cat <<_LT_EOF >> conftest.$ac_ext + +/* The mapping between symbol names and symbols. */ +const struct { + const char *name; + void *address; +} +lt__PROGRAM__LTX_preloaded_symbols[] = +{ + { "@PROGRAM@", (void *) 0 }, +_LT_EOF + $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext + cat <<\_LT_EOF >> conftest.$ac_ext + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt__PROGRAM__LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif +_LT_EOF + # Now try linking the two files. + mv conftest.$ac_objext conftstm.$ac_objext + lt_save_LIBS="$LIBS" + lt_save_CFLAGS="$CFLAGS" + LIBS="conftstm.$ac_objext" + CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext}; then + pipe_works=yes + fi + LIBS="$lt_save_LIBS" + CFLAGS="$lt_save_CFLAGS" + else + echo "cannot find nm_test_func in $nlist" >&5 + fi + else + echo "cannot find nm_test_var in $nlist" >&5 + fi + else + echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 + fi + else + echo "$progname: failed program was:" >&5 + cat conftest.$ac_ext >&5 + fi + rm -rf conftest* conftst* + + # Do not use the global_symbol_pipe unless it works. + if test "$pipe_works" = yes; then + break + else + lt_cv_sys_global_symbol_pipe= + fi +done + +fi + +if test -z "$lt_cv_sys_global_symbol_pipe"; then + lt_cv_sys_global_symbol_to_cdecl= +fi +if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then + { $as_echo "$as_me:$LINENO: result: failed" >&5 +$as_echo "failed" >&6; } +else + { $as_echo "$as_me:$LINENO: result: ok" >&5 +$as_echo "ok" >&6; } +fi + + + + + + + + + + + + + + + + + + + + + + + +# Check whether --enable-libtool-lock was given. +if test "${enable_libtool_lock+set}" = set; then + enableval=$enable_libtool_lock; +fi + +test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes + +# Some flags need to be propagated to the compiler or linker for good +# libtool support. +case $host in +ia64-*-hpux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.$ac_objext` in + *ELF-32*) + HPUX_IA64_MODE="32" + ;; + *ELF-64*) + HPUX_IA64_MODE="64" + ;; + esac + fi + rm -rf conftest* + ;; +*-*-irix6*) + # Find out which ABI we are using. + echo '#line 4963 "configure"' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + if test "$lt_cv_prog_gnu_ld" = yes; then + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -melf32bsmip" + ;; + *N32*) + LD="${LD-ld} -melf32bmipn32" + ;; + *64-bit*) + LD="${LD-ld} -melf64bmip" + ;; + esac + else + case `/usr/bin/file conftest.$ac_objext` in + *32-bit*) + LD="${LD-ld} -32" + ;; + *N32*) + LD="${LD-ld} -n32" + ;; + *64-bit*) + LD="${LD-ld} -64" + ;; + esac + fi + fi + rm -rf conftest* + ;; + +x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ +s390*-*linux*|s390*-*tpf*|sparc*-*linux*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.o` in + *32-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_i386_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_i386" + ;; + ppc64-*linux*|powerpc64-*linux*) + LD="${LD-ld} -m elf32ppclinux" + ;; + s390x-*linux*) + LD="${LD-ld} -m elf_s390" + ;; + sparc64-*linux*) + LD="${LD-ld} -m elf32_sparc" + ;; + esac + ;; + *64-bit*) + case $host in + x86_64-*kfreebsd*-gnu) + LD="${LD-ld} -m elf_x86_64_fbsd" + ;; + x86_64-*linux*) + LD="${LD-ld} -m elf_x86_64" + ;; + ppc*-*linux*|powerpc*-*linux*) + LD="${LD-ld} -m elf64ppc" + ;; + s390*-*linux*|s390*-*tpf*) + LD="${LD-ld} -m elf64_s390" + ;; + sparc*-*linux*) + LD="${LD-ld} -m elf64_sparc" + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; + +*-*-sco3.2v5*) + # On SCO OpenServer 5, we need -belf to get full-featured binaries. + SAVE_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS -belf" + { $as_echo "$as_me:$LINENO: checking whether the C compiler needs -belf" >&5 +$as_echo_n "checking whether the C compiler needs -belf... " >&6; } +if test "${lt_cv_cc_needs_belf+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + lt_cv_cc_needs_belf=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + lt_cv_cc_needs_belf=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext + ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_cc_needs_belf" >&5 +$as_echo "$lt_cv_cc_needs_belf" >&6; } + if test x"$lt_cv_cc_needs_belf" != x"yes"; then + # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf + CFLAGS="$SAVE_CFLAGS" + fi + ;; +sparc*-*solaris*) + # Find out which ABI we are using. + echo 'int i;' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.o` in + *64-bit*) + case $lt_cv_prog_gnu_ld in + yes*) LD="${LD-ld} -m elf64_sparc" ;; + *) + if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then + LD="${LD-ld} -64" + fi + ;; + esac + ;; + esac + fi + rm -rf conftest* + ;; +esac + +need_locks="$enable_libtool_lock" + + + case $host_os in + rhapsody* | darwin*) + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. +set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_DSYMUTIL+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$DSYMUTIL"; then + ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +DSYMUTIL=$ac_cv_prog_DSYMUTIL +if test -n "$DSYMUTIL"; then + { $as_echo "$as_me:$LINENO: result: $DSYMUTIL" >&5 +$as_echo "$DSYMUTIL" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_DSYMUTIL"; then + ac_ct_DSYMUTIL=$DSYMUTIL + # Extract the first word of "dsymutil", so it can be a program name with args. +set dummy dsymutil; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_DSYMUTIL+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_DSYMUTIL"; then + ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL +if test -n "$ac_ct_DSYMUTIL"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_DSYMUTIL" >&5 +$as_echo "$ac_ct_DSYMUTIL" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_DSYMUTIL" = x; then + DSYMUTIL=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + DSYMUTIL=$ac_ct_DSYMUTIL + fi +else + DSYMUTIL="$ac_cv_prog_DSYMUTIL" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. +set dummy ${ac_tool_prefix}nmedit; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_NMEDIT+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$NMEDIT"; then + ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +NMEDIT=$ac_cv_prog_NMEDIT +if test -n "$NMEDIT"; then + { $as_echo "$as_me:$LINENO: result: $NMEDIT" >&5 +$as_echo "$NMEDIT" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_NMEDIT"; then + ac_ct_NMEDIT=$NMEDIT + # Extract the first word of "nmedit", so it can be a program name with args. +set dummy nmedit; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_NMEDIT+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_NMEDIT"; then + ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_NMEDIT="nmedit" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT +if test -n "$ac_ct_NMEDIT"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_NMEDIT" >&5 +$as_echo "$ac_ct_NMEDIT" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_NMEDIT" = x; then + NMEDIT=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + NMEDIT=$ac_ct_NMEDIT + fi +else + NMEDIT="$ac_cv_prog_NMEDIT" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. +set dummy ${ac_tool_prefix}lipo; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_LIPO+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$LIPO"; then + ac_cv_prog_LIPO="$LIPO" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_LIPO="${ac_tool_prefix}lipo" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +LIPO=$ac_cv_prog_LIPO +if test -n "$LIPO"; then + { $as_echo "$as_me:$LINENO: result: $LIPO" >&5 +$as_echo "$LIPO" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_LIPO"; then + ac_ct_LIPO=$LIPO + # Extract the first word of "lipo", so it can be a program name with args. +set dummy lipo; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_LIPO+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_LIPO"; then + ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_LIPO="lipo" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO +if test -n "$ac_ct_LIPO"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_LIPO" >&5 +$as_echo "$ac_ct_LIPO" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_LIPO" = x; then + LIPO=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + LIPO=$ac_ct_LIPO + fi +else + LIPO="$ac_cv_prog_LIPO" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. +set dummy ${ac_tool_prefix}otool; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_OTOOL+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$OTOOL"; then + ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_OTOOL="${ac_tool_prefix}otool" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +OTOOL=$ac_cv_prog_OTOOL +if test -n "$OTOOL"; then + { $as_echo "$as_me:$LINENO: result: $OTOOL" >&5 +$as_echo "$OTOOL" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OTOOL"; then + ac_ct_OTOOL=$OTOOL + # Extract the first word of "otool", so it can be a program name with args. +set dummy otool; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_OTOOL+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_OTOOL"; then + ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_OTOOL="otool" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL +if test -n "$ac_ct_OTOOL"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_OTOOL" >&5 +$as_echo "$ac_ct_OTOOL" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_OTOOL" = x; then + OTOOL=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + OTOOL=$ac_ct_OTOOL + fi +else + OTOOL="$ac_cv_prog_OTOOL" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. +set dummy ${ac_tool_prefix}otool64; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_OTOOL64+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$OTOOL64"; then + ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +OTOOL64=$ac_cv_prog_OTOOL64 +if test -n "$OTOOL64"; then + { $as_echo "$as_me:$LINENO: result: $OTOOL64" >&5 +$as_echo "$OTOOL64" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_OTOOL64"; then + ac_ct_OTOOL64=$OTOOL64 + # Extract the first word of "otool64", so it can be a program name with args. +set dummy otool64; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_OTOOL64+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_OTOOL64"; then + ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_OTOOL64="otool64" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 +if test -n "$ac_ct_OTOOL64"; then + { $as_echo "$as_me:$LINENO: result: $ac_ct_OTOOL64" >&5 +$as_echo "$ac_ct_OTOOL64" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_OTOOL64" = x; then + OTOOL64=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +$as_echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + OTOOL64=$ac_ct_OTOOL64 + fi +else + OTOOL64="$ac_cv_prog_OTOOL64" +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + + { $as_echo "$as_me:$LINENO: checking for -single_module linker flag" >&5 +$as_echo_n "checking for -single_module linker flag... " >&6; } +if test "${lt_cv_apple_cc_single_mod+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_apple_cc_single_mod=no + if test -z "${LT_MULTI_MODULE}"; then + # By default we will add the -single_module flag. You can override + # by either setting the environment variable LT_MULTI_MODULE + # non-empty at configure time, or by adding -multi_module to the + # link flags. + rm -rf libconftest.dylib* + echo "int foo(void){return 1;}" > conftest.c + echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ +-dynamiclib -Wl,-single_module conftest.c" >&5 + $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ + -dynamiclib -Wl,-single_module conftest.c 2>conftest.err + _lt_result=$? + if test -f libconftest.dylib && test ! -s conftest.err && test $_lt_result = 0; then + lt_cv_apple_cc_single_mod=yes + else + cat conftest.err >&5 + fi + rm -rf libconftest.dylib* + rm -f conftest.* + fi +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_apple_cc_single_mod" >&5 +$as_echo "$lt_cv_apple_cc_single_mod" >&6; } + { $as_echo "$as_me:$LINENO: checking for -exported_symbols_list linker flag" >&5 +$as_echo_n "checking for -exported_symbols_list linker flag... " >&6; } +if test "${lt_cv_ld_exported_symbols_list+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_ld_exported_symbols_list=no + save_LDFLAGS=$LDFLAGS + echo "_main" > conftest.sym + LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + lt_cv_ld_exported_symbols_list=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + lt_cv_ld_exported_symbols_list=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS="$save_LDFLAGS" + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_ld_exported_symbols_list" >&5 +$as_echo "$lt_cv_ld_exported_symbols_list" >&6; } + case $host_os in + rhapsody* | darwin1.[012]) + _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; + darwin1.*) + _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; + darwin*) # darwin 5.x on + # if running on 10.5 or later, the deployment target defaults + # to the OS version, if on x86, and 10.4, the deployment + # target defaults to 10.4. Don't you love it? + case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in + 10.0,*86*-darwin8*|10.0,*-darwin[91]*) + _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; + 10.[012]*) + _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; + 10.*) + _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; + esac + ;; + esac + if test "$lt_cv_apple_cc_single_mod" = "yes"; then + _lt_dar_single_mod='$single_module' + fi + if test "$lt_cv_ld_exported_symbols_list" = "yes"; then + _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' + else + _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' + fi + if test "$DSYMUTIL" != ":"; then + _lt_dsymutil='~$DSYMUTIL $lib || :' + else + _lt_dsymutil= + fi + ;; + esac + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if test "${ac_cv_prog_CPP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Broken: fails on valid input. +continue +fi + +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + # Broken: success on invalid input. +continue +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi + +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:$LINENO: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Broken: fails on valid input. +continue +fi + +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + # Broken: success on invalid input. +continue +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi + +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + : +else + { { $as_echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +{ $as_echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_header_stdc=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_header_stdc=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then + : +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + : +else + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_header_stdc=no +fi +rm -rf conftest.dSYM +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +fi +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +cat >>confdefs.h <<\_ACEOF +#define STDC_HEADERS 1 +_ACEOF + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. + + + + + + + + + +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + eval "$as_ac_Header=yes" +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_Header=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +if test `eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + +for ac_header in dlfcn.h +do +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + eval "$as_ac_Header=yes" +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_Header=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +if test `eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + +# Set options + + + + enable_dlopen=no + + + enable_win32_dll=no + + + # Check whether --enable-shared was given. +if test "${enable_shared+set}" = set; then + enableval=$enable_shared; p=${PACKAGE-default} + case $enableval in + yes) enable_shared=yes ;; + no) enable_shared=no ;; + *) + enable_shared=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_shared=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_shared=yes +fi + + + + + + + + + + # Check whether --enable-static was given. +if test "${enable_static+set}" = set; then + enableval=$enable_static; p=${PACKAGE-default} + case $enableval in + yes) enable_static=yes ;; + no) enable_static=no ;; + *) + enable_static=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_static=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_static=yes +fi + + + + + + + + + + +# Check whether --with-pic was given. +if test "${with_pic+set}" = set; then + withval=$with_pic; pic_mode="$withval" +else + pic_mode=default +fi + + +test -z "$pic_mode" && pic_mode=default + + + + + + + + # Check whether --enable-fast-install was given. +if test "${enable_fast_install+set}" = set; then + enableval=$enable_fast_install; p=${PACKAGE-default} + case $enableval in + yes) enable_fast_install=yes ;; + no) enable_fast_install=no ;; + *) + enable_fast_install=no + # Look at the argument we got. We use all the common list separators. + lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," + for pkg in $enableval; do + IFS="$lt_save_ifs" + if test "X$pkg" = "X$p"; then + enable_fast_install=yes + fi + done + IFS="$lt_save_ifs" + ;; + esac +else + enable_fast_install=yes +fi + + + + + + + + + + + +# This can be used to rebuild libtool when needed +LIBTOOL_DEPS="$ltmain" + +# Always use our own libtool. +LIBTOOL='$(SHELL) $(top_builddir)/libtool' + + + + + + + + + + + + + + + + + + + + + + + + + +test -z "$LN_S" && LN_S="ln -s" + + + + + + + + + + + + + + +if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST +fi + +{ $as_echo "$as_me:$LINENO: checking for objdir" >&5 +$as_echo_n "checking for objdir... " >&6; } +if test "${lt_cv_objdir+set}" = set; then + $as_echo_n "(cached) " >&6 +else + rm -f .libs 2>/dev/null +mkdir .libs 2>/dev/null +if test -d .libs; then + lt_cv_objdir=.libs +else + # MS-DOS does not allow filenames that begin with a dot. + lt_cv_objdir=_libs +fi +rmdir .libs 2>/dev/null +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_objdir" >&5 +$as_echo "$lt_cv_objdir" >&6; } +objdir=$lt_cv_objdir + + + + + +cat >>confdefs.h <<_ACEOF +#define LT_OBJDIR "$lt_cv_objdir/" +_ACEOF + + + + + + + + + + + + + + + + + +case $host_os in +aix3*) + # AIX sometimes has problems with the GCC collect2 program. For some + # reason, if we set the COLLECT_NAMES environment variable, the problems + # vanish in a puff of smoke. + if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES + fi + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +sed_quote_subst='s/\(["`$\\]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\(["`\\]\)/\\\1/g' + +# Sed substitution to delay expansion of an escaped shell variable in a +# double_quote_subst'ed string. +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' + +# Sed substitution to delay expansion of an escaped single quote. +delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' + +# Sed substitution to avoid accidental globbing in evaled expressions +no_glob_subst='s/\*/\\\*/g' + +# Global variables: +ofile=libtool +can_build_shared=yes + +# All known linkers require a `.a' archive for static linking (except MSVC, +# which needs '.lib'). +libext=a + +with_gnu_ld="$lt_cv_prog_gnu_ld" + +old_CC="$CC" +old_CFLAGS="$CFLAGS" + +# Set sane defaults for various variables +test -z "$CC" && CC=cc +test -z "$LTCC" && LTCC=$CC +test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS +test -z "$LD" && LD=ld +test -z "$ac_objext" && ac_objext=o + +for cc_temp in $compiler""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`$ECHO "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` + + +# Only perform the check for file, if the check method requires it +test -z "$MAGIC_CMD" && MAGIC_CMD=file +case $deplibs_check_method in +file_magic*) + if test "$file_magic_cmd" = '$MAGIC_CMD'; then + { $as_echo "$as_me:$LINENO: checking for ${ac_tool_prefix}file" >&5 +$as_echo_n "checking for ${ac_tool_prefix}file... " >&6; } +if test "${lt_cv_path_MAGIC_CMD+set}" = set; then + $as_echo_n "(cached) " >&6 +else + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/${ac_tool_prefix}file; then + lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <<_LT_EOF 1>&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +_LT_EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac +fi + +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + { $as_echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5 +$as_echo "$MAGIC_CMD" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + + + +if test -z "$lt_cv_path_MAGIC_CMD"; then + if test -n "$ac_tool_prefix"; then + { $as_echo "$as_me:$LINENO: checking for file" >&5 +$as_echo_n "checking for file... " >&6; } +if test "${lt_cv_path_MAGIC_CMD+set}" = set; then + $as_echo_n "(cached) " >&6 +else + case $MAGIC_CMD in +[\\/*] | ?:[\\/]*) + lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. + ;; +*) + lt_save_MAGIC_CMD="$MAGIC_CMD" + lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR + ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" + for ac_dir in $ac_dummy; do + IFS="$lt_save_ifs" + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/file; then + lt_cv_path_MAGIC_CMD="$ac_dir/file" + if test -n "$file_magic_test_file"; then + case $deplibs_check_method in + "file_magic "*) + file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` + MAGIC_CMD="$lt_cv_path_MAGIC_CMD" + if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | + $EGREP "$file_magic_regex" > /dev/null; then + : + else + cat <<_LT_EOF 1>&2 + +*** Warning: the command libtool uses to detect shared libraries, +*** $file_magic_cmd, produces output that libtool cannot recognize. +*** The result is that libtool may fail to recognize shared libraries +*** as such. This will affect the creation of libtool libraries that +*** depend on shared libraries, but programs linked with such libtool +*** libraries will work regardless of this problem. Nevertheless, you +*** may want to report the problem to your system manager and/or to +*** bug-libtool@gnu.org + +_LT_EOF + fi ;; + esac + fi + break + fi + done + IFS="$lt_save_ifs" + MAGIC_CMD="$lt_save_MAGIC_CMD" + ;; +esac +fi + +MAGIC_CMD="$lt_cv_path_MAGIC_CMD" +if test -n "$MAGIC_CMD"; then + { $as_echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5 +$as_echo "$MAGIC_CMD" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + else + MAGIC_CMD=: + fi +fi + + fi + ;; +esac + +# Use C for the default configuration in the libtool script + +lt_save_CC="$CC" +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +# Source file extension for C test sources. +ac_ext=c + +# Object file extension for compiled C test sources. +objext=o +objext=$objext + +# Code to be used in simple compile tests +lt_simple_compile_test_code="int some_variable = 0;" + +# Code to be used in simple link tests +lt_simple_link_test_code='int main(){return(0);}' + + + + + + + +# If no C compiler was specified, use CC. +LTCC=${LTCC-"$CC"} + +# If no C compiler flags were specified, use CFLAGS. +LTCFLAGS=${LTCFLAGS-"$CFLAGS"} + +# Allow CC to be a program name with arguments. +compiler=$CC + +# Save the default compiler, since it gets overwritten when the other +# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. +compiler_DEFAULT=$CC + +# save warnings/boilerplate of simple test code +ac_outfile=conftest.$ac_objext +echo "$lt_simple_compile_test_code" >conftest.$ac_ext +eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_compiler_boilerplate=`cat conftest.err` +$RM conftest* + +ac_outfile=conftest.$ac_objext +echo "$lt_simple_link_test_code" >conftest.$ac_ext +eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err +_lt_linker_boilerplate=`cat conftest.err` +$RM -r conftest* + + +if test -n "$compiler"; then + +lt_prog_compiler_no_builtin_flag= + +if test "$GCC" = yes; then + lt_prog_compiler_no_builtin_flag=' -fno-builtin' + + { $as_echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 +$as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } +if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_rtti_exceptions=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="-fno-rtti -fno-exceptions" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:6832: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:6836: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_rtti_exceptions=yes + fi + fi + $RM conftest* + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 +$as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; } + +if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then + lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" +else + : +fi + +fi + + + + + + + lt_prog_compiler_wl= +lt_prog_compiler_pic= +lt_prog_compiler_static= + +{ $as_echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5 +$as_echo_n "checking for $compiler option to produce PIC... " >&6; } + + if test "$GCC" = yes; then + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_static='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + lt_prog_compiler_pic='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the `-m68020' flag to GCC prevents building anything better, + # like `-m68040'. + lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic='-DDLL_EXPORT' + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic='-fno-common' + ;; + + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + ;; + + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared=no + enable_shared=no + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic='-fPIC -shared' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic=-Kconform_pic + fi + ;; + + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl='-Wl,' + if test "$host_cpu" = ia64; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + else + lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + mingw* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic='-DDLL_EXPORT' + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static='${wl}-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static='-non_shared' + ;; + + linux* | k*bsd*-gnu) + case $cc_basename in + # old Intel for x86_64 which still supported -KPIC. + ecc*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-static' + ;; + # icc used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + icc* | ifort*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + # Lahey Fortran 8.1. + lf95*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='--shared' + lt_prog_compiler_static='--static' + ;; + pgcc* | pgf77* | pgf90* | pgf95*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fpic' + lt_prog_compiler_static='-Bstatic' + ;; + ccc*) + lt_prog_compiler_wl='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + xl*) + # IBM XL C 8.0/Fortran 10.1 on PPC + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-qpic' + lt_prog_compiler_static='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + # Sun C 5.9 + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='-Wl,' + ;; + *Sun\ F*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='' + ;; + esac + ;; + esac + ;; + + newsos6) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic='-fPIC -shared' + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + + rdos*) + lt_prog_compiler_static='-non_shared' + ;; + + solaris*) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + case $cc_basename in + f77* | f90* | f95*) + lt_prog_compiler_wl='-Qoption ld ';; + *) + lt_prog_compiler_wl='-Wl,';; + esac + ;; + + sunos4*) + lt_prog_compiler_wl='-Qoption ld ' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec ;then + lt_prog_compiler_pic='-Kconform_pic' + lt_prog_compiler_static='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + unicos*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_can_build_shared=no + ;; + + uts4*) + lt_prog_compiler_pic='-pic' + lt_prog_compiler_static='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared=no + ;; + esac + fi + +case $host_os in + # For platforms which do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic= + ;; + *) + lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" + ;; +esac +{ $as_echo "$as_me:$LINENO: result: $lt_prog_compiler_pic" >&5 +$as_echo "$lt_prog_compiler_pic" >&6; } + + + + + + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic"; then + { $as_echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 +$as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } +if test "${lt_cv_prog_compiler_pic_works+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_pic_works=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic -DPIC" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:7171: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:7175: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_pic_works=yes + fi + fi + $RM conftest* + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_pic_works" >&5 +$as_echo "$lt_cv_prog_compiler_pic_works" >&6; } + +if test x"$lt_cv_prog_compiler_pic_works" = xyes; then + case $lt_prog_compiler_pic in + "" | " "*) ;; + *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; + esac +else + lt_prog_compiler_pic= + lt_prog_compiler_can_build_shared=no +fi + +fi + + + + + + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" +{ $as_echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +$as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } +if test "${lt_cv_prog_compiler_static_works+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_static_works=no + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $ECHO "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_static_works=yes + fi + else + lt_cv_prog_compiler_static_works=yes + fi + fi + $RM -r conftest* + LDFLAGS="$save_LDFLAGS" + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_static_works" >&5 +$as_echo "$lt_cv_prog_compiler_static_works" >&6; } + +if test x"$lt_cv_prog_compiler_static_works" = xyes; then + : +else + lt_prog_compiler_static= +fi + + + + + + + + { $as_echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } +if test "${lt_cv_prog_compiler_c_o+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_c_o=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:7276: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:7280: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o=yes + fi + fi + chmod u+w . 2>&5 + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o" >&5 +$as_echo "$lt_cv_prog_compiler_c_o" >&6; } + + + + + + + { $as_echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5 +$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } +if test "${lt_cv_prog_compiler_c_o+set}" = set; then + $as_echo_n "(cached) " >&6 +else + lt_cv_prog_compiler_c_o=no + $RM -r conftest 2>/dev/null + mkdir conftest + cd conftest + mkdir out + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + lt_compiler_flag="-o out/conftest2.$ac_objext" + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:7331: $lt_compile\"" >&5) + (eval "$lt_compile" 2>out/conftest.err) + ac_status=$? + cat out/conftest.err >&5 + echo "$as_me:7335: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s out/conftest2.$ac_objext + then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings + $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp + $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 + if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then + lt_cv_prog_compiler_c_o=yes + fi + fi + chmod u+w . 2>&5 + $RM conftest* + # SGI C++ compiler will create directory out/ii_files/ for + # template instantiation + test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files + $RM out/* && rmdir out + cd .. + $RM -r conftest + $RM conftest* + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o" >&5 +$as_echo "$lt_cv_prog_compiler_c_o" >&6; } + + + + +hard_links="nottested" +if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then + # do not overwrite the value of need_locks provided by the user + { $as_echo "$as_me:$LINENO: checking if we can lock with hard links" >&5 +$as_echo_n "checking if we can lock with hard links... " >&6; } + hard_links=yes + $RM conftest* + ln conftest.a conftest.b 2>/dev/null && hard_links=no + touch conftest.a + ln conftest.a conftest.b 2>&5 || hard_links=no + ln conftest.a conftest.b 2>/dev/null && hard_links=no + { $as_echo "$as_me:$LINENO: result: $hard_links" >&5 +$as_echo "$hard_links" >&6; } + if test "$hard_links" = no; then + { $as_echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 +$as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} + need_locks=warn + fi +else + need_locks=no +fi + + + + + + + { $as_echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5 +$as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } + + runpath_var= + allow_undefined_flag= + always_export_symbols=no + archive_cmds= + archive_expsym_cmds= + compiler_needs_object=no + enable_shared_with_static_runtimes=no + export_dynamic_flag_spec= + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' + hardcode_automatic=no + hardcode_direct=no + hardcode_direct_absolute=no + hardcode_libdir_flag_spec= + hardcode_libdir_flag_spec_ld= + hardcode_libdir_separator= + hardcode_minus_L=no + hardcode_shlibpath_var=unsupported + inherit_rpath=no + link_all_deplibs=unknown + module_cmds= + module_expsym_cmds= + old_archive_from_new_cmds= + old_archive_from_expsyms_cmds= + thread_safe_flag_spec= + whole_archive_flag_spec= + # include_expsyms should be a list of space-separated symbols to be *always* + # included in the symbol list + include_expsyms= + # exclude_expsyms can be an extended regexp of symbols to exclude + # it will be wrapped by ` (' and `)$', so one must not match beginning or + # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', + # as well as any symbol that contains `d'. + exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' + # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out + # platforms (ab)use it in PIC code, but their linkers get confused if + # the symbol is explicitly referenced. Since portable code cannot + # rely on this symbol name, it's probably fine to never include it in + # preloaded symbol tables. + # Exclude shared library initialization/finalization symbols. + extract_expsyms_cmds= + + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++) + with_gnu_ld=yes + ;; + openbsd*) + with_gnu_ld=no + ;; + esac + + ld_shlibs=yes + if test "$with_gnu_ld" = yes; then + # If archive_cmds runs LD, not CC, wlarc should be empty + wlarc='${wl}' + + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + runpath_var=LD_RUN_PATH + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + export_dynamic_flag_spec='${wl}--export-dynamic' + # ancient GNU ld didn't support --whole-archive et. al. + if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then + whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' + else + whole_archive_flag_spec= + fi + supports_anon_versioning=no + case `$LD -v 2>&1` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 + *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... + *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... + *\ 2.11.*) ;; # other 2.11 versions + *) supports_anon_versioning=yes ;; + esac + + # See if GNU ld supports shared libraries. + case $host_os in + aix[3-9]*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: the GNU linker, at least up to release 2.9.1, is reported +*** to be unable to reliably create shared libraries on AIX. +*** Therefore, libtool is disabling shared libraries support. If you +*** really care for shared libraries, you may want to modify your PATH +*** so that a non-GNU linker is found, and then restart. + +_LT_EOF + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='' + ;; + m68k) + archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + ;; + esac + ;; + + beos*) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + allow_undefined_flag=unsupported + # Joseph Beckenbach says some releases of gcc + # support --undefined. This deserves some investigation. FIXME + archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + else + ld_shlibs=no + fi + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, + # as there is no search path for DLLs. + hardcode_libdir_flag_spec='-L$libdir' + allow_undefined_flag=unsupported + always_export_symbols=no + enable_shared_with_static_runtimes=yes + export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' + + if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + # If the export-symbols file already is a .def file (1st line + # is EXPORTS), use it as is; otherwise, prepend... + archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then + cp $export_symbols $output_objdir/$soname.def; + else + echo EXPORTS > $output_objdir/$soname.def; + cat $export_symbols >> $output_objdir/$soname.def; + fi~ + $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' + else + ld_shlibs=no + fi + ;; + + interix[3-9]*) + hardcode_direct=no + hardcode_shlibpath_var=no + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + export_dynamic_flag_spec='${wl}-E' + # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. + # Instead, shared libraries are loaded at an image base (0x10000000 by + # default) and relocated if they conflict, which is a slow very memory + # consuming and fragmenting process. To avoid this, we pick a random, + # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link + # time. Moving up from 0x10000000 also allows more sbrk(2) space. + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' + ;; + + gnu* | linux* | tpf* | k*bsd*-gnu) + tmp_diet=no + if test "$host_os" = linux-dietlibc; then + case $cc_basename in + diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) + esac + fi + if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ + && test "$tmp_diet" = no + then + tmp_addflag= + tmp_sharedflag='-shared' + case $cc_basename,$host_cpu in + pgcc*) # Portland Group C compiler + whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag' + ;; + pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers + whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' + tmp_addflag=' $pic_flag -Mnomain' ;; + ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 + tmp_addflag=' -i_dynamic' ;; + efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 + tmp_addflag=' -i_dynamic -nofor_main' ;; + ifc* | ifort*) # Intel Fortran compiler + tmp_addflag=' -nofor_main' ;; + lf95*) # Lahey Fortran 8.1 + whole_archive_flag_spec= + tmp_sharedflag='--shared' ;; + xl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) + tmp_sharedflag='-qmkshrobj' + tmp_addflag= ;; + esac + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) # Sun C 5.9 + whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' + compiler_needs_object=yes + tmp_sharedflag='-G' ;; + *Sun\ F*) # Sun Fortran 8.3 + tmp_sharedflag='-G' ;; + esac + archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + + if test "x$supports_anon_versioning" = xyes; then + archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' + fi + + case $cc_basename in + xlf*) + # IBM XL Fortran 10.1 on PPC cannot create shared libs itself + whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' + hardcode_libdir_flag_spec= + hardcode_libdir_flag_spec_ld='-rpath $libdir' + archive_cmds='$LD -shared $libobjs $deplibs $compiler_flags -soname $soname -o $lib' + if test "x$supports_anon_versioning" = xyes; then + archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ + cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ + echo "local: *; };" >> $output_objdir/$libname.ver~ + $LD -shared $libobjs $deplibs $compiler_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' + fi + ;; + esac + else + ld_shlibs=no + fi + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' + wlarc= + else + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + fi + ;; + + solaris*) + if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: The releases 2.8.* of the GNU linker cannot reliably +*** create shared libraries on Solaris systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.9.1 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) + ld_shlibs=no + cat <<_LT_EOF 1>&2 + +*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not +*** reliably create shared libraries on SCO systems. Therefore, libtool +*** is disabling shared libraries support. We urge you to upgrade GNU +*** binutils to release 2.16.91.0.3 or newer. Another option is to modify +*** your PATH or compiler configuration so that the native linker is +*** used, and then restart. + +_LT_EOF + ;; + *) + # For security reasons, it is highly recommended that you always + # use absolute paths for naming shared libraries, and exclude the + # DT_RUNPATH tag from executables and libraries. But doing so + # requires that you compile everything twice, which is a pain. + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + esac + ;; + + sunos4*) + archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' + wlarc= + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + *) + if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' + else + ld_shlibs=no + fi + ;; + esac + + if test "$ld_shlibs" = no; then + runpath_var= + hardcode_libdir_flag_spec= + export_dynamic_flag_spec= + whole_archive_flag_spec= + fi + else + # PORTME fill in a description of your system's linker (not GNU ld) + case $host_os in + aix3*) + allow_undefined_flag=unsupported + always_export_symbols=yes + archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L=yes + if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct=unsupported + fi + ;; + + aix[4-9]*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + exp_sym_flag='-Bexport' + no_entry_flag="" + else + # If we're using GNU nm, then we don't want the "-C" option. + # -C means demangle to AIX nm, but means don't demangle with GNU nm + if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then + export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + else + export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' + fi + aix_use_runtimelinking=no + + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + ;; + esac + + exp_sym_flag='-bexport' + no_entry_flag='-bnoentry' + fi + + # When large executables or shared objects are built, AIX ld can + # have problems creating the table of contents. If linking a library + # or program results in "error TOC overflow" add -mminimal-toc to + # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not + # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. + + archive_cmds='' + hardcode_direct=yes + hardcode_direct_absolute=yes + hardcode_libdir_separator=':' + link_all_deplibs=yes + file_list_spec='${wl}-f,' + + if test "$GCC" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + # We only want to do this on AIX 4.2 and lower, the check + # below for broken collect2 doesn't work under 4.3+ + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && + strings "$collect2name" | $GREP resolve_lib_name >/dev/null + then + # We have reworked collect2 + : + else + # We have old collect2 + hardcode_direct=unsupported + # It fails to find uninstalled libraries when the uninstalled + # path is not listed in the libpath. Setting hardcode_minus_L + # to unsupported forces relinking + hardcode_minus_L=yes + hardcode_libdir_flag_spec='-L$libdir' + hardcode_libdir_separator= + fi + ;; + esac + shared_flag='-shared' + if test "$aix_use_runtimelinking" = yes; then + shared_flag="$shared_flag "'${wl}-G' + fi + else + # not using gcc + if test "$host_cpu" = ia64; then + # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release + # chokes on -Wl,-G. The following line is correct: + shared_flag='-G' + else + if test "$aix_use_runtimelinking" = yes; then + shared_flag='${wl}-G' + else + shared_flag='${wl}-bM:SRE' + fi + fi + fi + + export_dynamic_flag_spec='${wl}-bexpall' + # It seems that -bexpall does not export symbols beginning with + # underscore (_), so it is better to generate a list of symbols to export. + always_export_symbols=yes + if test "$aix_use_runtimelinking" = yes; then + # Warning - without using the other runtime loading flags (-brtl), + # -berok will link without error, but may produce a broken library. + allow_undefined_flag='-berok' + # Determine the default libpath from the value encoded in an + # empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' + allow_undefined_flag="-z nodefs" + archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" + else + # Determine the default libpath from the value encoded in an + # empty executable. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + +lt_aix_libpath_sed=' + /Import File Strings/,/^$/ { + /^0/ { + s/^0 *\(.*\)$/\1/ + p + } + }' +aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +# Check for a 64-bit object if we didn't find anything. +if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` +fi +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi + + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + # Warning - without using the other run time loading flags, + # -berok will link without error, but may produce a broken library. + no_undefined_flag=' ${wl}-bernotok' + allow_undefined_flag=' ${wl}-berok' + # Exported symbols can be pulled into shared objects from archives + whole_archive_flag_spec='$convenience' + archive_cmds_need_lc=yes + # This is similar to how AIX traditionally builds its shared libraries. + archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' + fi + fi + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' + archive_expsym_cmds='' + ;; + m68k) + archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + ;; + esac + ;; + + bsdi[45]*) + export_dynamic_flag_spec=-rdynamic + ;; + + cygwin* | mingw* | pw32* | cegcc*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec=' ' + allow_undefined_flag=unsupported + # Tell ltmain to make .lib files, not .a files. + libext=lib + # Tell ltmain to make .dll files, not .so files. + shrext_cmds=".dll" + # FIXME: Setting linknames here is a bad hack. + archive_cmds='$CC -o $lib $libobjs $compiler_flags `$ECHO "X$deplibs" | $Xsed -e '\''s/ -lc$//'\''` -link -dll~linknames=' + # The linker will automatically build a .lib file if we build a DLL. + old_archive_from_new_cmds='true' + # FIXME: Should let the user specify the lib program. + old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' + fix_srcfile_path='`cygpath -w "$srcfile"`' + enable_shared_with_static_runtimes=yes + ;; + + darwin* | rhapsody*) + + + archive_cmds_need_lc=no + hardcode_direct=no + hardcode_automatic=yes + hardcode_shlibpath_var=unsupported + whole_archive_flag_spec='' + link_all_deplibs=yes + allow_undefined_flag="$_lt_dar_allow_undefined" + case $cc_basename in + ifort*) _lt_dar_can_shared=yes ;; + *) _lt_dar_can_shared=$GCC ;; + esac + if test "$_lt_dar_can_shared" = "yes"; then + output_verbose_link_cmd=echo + archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" + module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" + archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" + module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" + + else + ld_shlibs=no + fi + + ;; + + dgux*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + freebsd1*) + ld_shlibs=no + ;; + + # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor + # support. Future versions do this automatically, but an explicit c++rt0.o + # does not break anything, and helps significantly (at the cost of a little + # extra space). + freebsd2.2*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + # Unfortunately, older versions of FreeBSD 2 do not have this feature. + freebsd2*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + # FreeBSD 3 and greater uses gcc -shared to do shared libraries. + freebsd* | dragonfly*) + archive_cmds='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + hpux9*) + if test "$GCC" = yes; then + archive_cmds='$RM $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + else + archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' + fi + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + export_dynamic_flag_spec='${wl}-E' + ;; + + hpux10*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_flag_spec_ld='+b $libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + hardcode_direct_absolute=yes + export_dynamic_flag_spec='${wl}-E' + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + fi + ;; + + hpux11*) + if test "$GCC" = yes -a "$with_gnu_ld" = no; then + case $host_cpu in + hppa*64*) + archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + else + case $host_cpu in + hppa*64*) + archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + ;; + ia64*) + archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' + ;; + *) + archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' + ;; + esac + fi + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + + case $host_cpu in + hppa*64*|ia64*) + hardcode_direct=no + hardcode_shlibpath_var=no + ;; + *) + hardcode_direct=yes + hardcode_direct_absolute=yes + export_dynamic_flag_spec='${wl}-E' + + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + ;; + esac + fi + ;; + + irix5* | irix6* | nonstopux*) + if test "$GCC" = yes; then + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + # Try to use the -exported_symbol ld option, if it does not + # work, assume that -exports_file does not work either and + # implicitly export all symbols. + save_LDFLAGS="$LDFLAGS" + LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" + cat >conftest.$ac_ext <<_ACEOF +int foo(void) {} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' + +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS="$save_LDFLAGS" + else + archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' + fi + archive_cmds_need_lc='no' + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + inherit_rpath=yes + link_all_deplibs=yes + ;; + + netbsd*) + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out + else + archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + hardcode_shlibpath_var=no + ;; + + newsos6) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_shlibpath_var=no + ;; + + *nto* | *qnx*) + ;; + + openbsd*) + if test -f /usr/libexec/ld.so; then + hardcode_direct=yes + hardcode_shlibpath_var=no + hardcode_direct_absolute=yes + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + export_dynamic_flag_spec='${wl}-E' + else + case $host_os in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-R$libdir' + ;; + *) + archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + ;; + esac + fi + else + ld_shlibs=no + fi + ;; + + os2*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + allow_undefined_flag=unsupported + archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$ECHO DATA >> $output_objdir/$libname.def~$ECHO " SINGLE NONSHARED" >> $output_objdir/$libname.def~$ECHO EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' + old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' + ;; + + osf3*) + if test "$GCC" = yes; then + allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' + fi + archive_cmds_need_lc='no' + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + ;; + + osf4* | osf5*) # as osf3* with the addition of -msym flag + if test "$GCC" = yes; then + allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + else + allow_undefined_flag=' -expect_unresolved \*' + archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' + archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ + $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' + + # Both c and cxx compiler support -rpath directly + hardcode_libdir_flag_spec='-rpath $libdir' + fi + archive_cmds_need_lc='no' + hardcode_libdir_separator=: + ;; + + solaris*) + no_undefined_flag=' -z defs' + if test "$GCC" = yes; then + wlarc='${wl}' + archive_cmds='$CC -shared ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -shared ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + else + case `$CC -V 2>&1` in + *"Compilers 5.0"*) + wlarc='' + archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' + archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' + ;; + *) + wlarc='${wl}' + archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ + $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' + ;; + esac + fi + hardcode_libdir_flag_spec='-R$libdir' + hardcode_shlibpath_var=no + case $host_os in + solaris2.[0-5] | solaris2.[0-5].*) ;; + *) + # The compiler driver will combine and reorder linker options, + # but understands `-z linker_flag'. GCC discards it without `$wl', + # but is careful enough not to reorder. + # Supported since Solaris 2.6 (maybe 2.5.1?) + if test "$GCC" = yes; then + whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' + else + whole_archive_flag_spec='-z allextract$convenience -z defaultextract' + fi + ;; + esac + link_all_deplibs=yes + ;; + + sunos4*) + if test "x$host_vendor" = xsequent; then + # Use $CC to link under sequent, because it throws in some extra .o + # files that make .init and .fini sections work. + archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' + fi + hardcode_libdir_flag_spec='-L$libdir' + hardcode_direct=yes + hardcode_minus_L=yes + hardcode_shlibpath_var=no + ;; + + sysv4) + case $host_vendor in + sni) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=yes # is this really true??? + ;; + siemens) + ## LD is ld it makes a PLAMLIB + ## CC just makes a GrossModule. + archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' + reload_cmds='$CC -r -o $output$reload_objs' + hardcode_direct=no + ;; + motorola) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_direct=no #Motorola manual says yes, but my tests say they lie + ;; + esac + runpath_var='LD_RUN_PATH' + hardcode_shlibpath_var=no + ;; + + sysv4.3*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + export_dynamic_flag_spec='-Bexport' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_shlibpath_var=no + runpath_var=LD_RUN_PATH + hardcode_runpath_var=yes + ld_shlibs=yes + fi + ;; + + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) + no_undefined_flag='${wl}-z,text' + archive_cmds_need_lc=no + hardcode_shlibpath_var=no + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + sysv5* | sco3.2v5* | sco5v6*) + # Note: We can NOT use -z defs as we might desire, because we do not + # link with -lc, and that would cause any symbols used from libc to + # always be unresolved, which means just about no library would + # ever link correctly. If we're not using GNU ld we use -z text + # though, which does catch some bad symbols but isn't as heavy-handed + # as -z defs. + no_undefined_flag='${wl}-z,text' + allow_undefined_flag='${wl}-z,nodefs' + archive_cmds_need_lc=no + hardcode_shlibpath_var=no + hardcode_libdir_flag_spec='${wl}-R,$libdir' + hardcode_libdir_separator=':' + link_all_deplibs=yes + export_dynamic_flag_spec='${wl}-Bexport' + runpath_var='LD_RUN_PATH' + + if test "$GCC" = yes; then + archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + else + archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' + fi + ;; + + uts4*) + archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' + hardcode_libdir_flag_spec='-L$libdir' + hardcode_shlibpath_var=no + ;; + + *) + ld_shlibs=no + ;; + esac + + if test x$host_vendor = xsni; then + case $host in + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + export_dynamic_flag_spec='${wl}-Blargedynsym' + ;; + esac + fi + fi + +{ $as_echo "$as_me:$LINENO: result: $ld_shlibs" >&5 +$as_echo "$ld_shlibs" >&6; } +test "$ld_shlibs" = no && can_build_shared=no + +with_gnu_ld=$with_gnu_ld + + + + + + + + + + + + + + + +# +# Do we need to explicitly link libc? +# +case "x$archive_cmds_need_lc" in +x|xyes) + # Assume -lc should be added + archive_cmds_need_lc=yes + + if test "$enable_shared" = yes && test "$GCC" = yes; then + case $archive_cmds in + *'~'*) + # FIXME: we may have to deal with multi-command sequences. + ;; + '$CC '*) + # Test whether the compiler implicitly links with -lc since on some + # systems, -lgcc has to come before -lc. If gcc already passes -lc + # to ld, don't add -lc before -lgcc. + { $as_echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5 +$as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } + $RM conftest* + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } 2>conftest.err; then + soname=conftest + lib=conftest + libobjs=conftest.$ac_objext + deplibs= + wl=$lt_prog_compiler_wl + pic_flag=$lt_prog_compiler_pic + compiler_flags=-v + linker_flags=-v + verstring= + output_objdir=. + libname=conftest + lt_save_allow_undefined_flag=$allow_undefined_flag + allow_undefined_flag= + if { (eval echo "$as_me:$LINENO: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\"") >&5 + (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + then + archive_cmds_need_lc=no + else + archive_cmds_need_lc=yes + fi + allow_undefined_flag=$lt_save_allow_undefined_flag + else + cat conftest.err 1>&5 + fi + $RM conftest* + { $as_echo "$as_me:$LINENO: result: $archive_cmds_need_lc" >&5 +$as_echo "$archive_cmds_need_lc" >&6; } + ;; + esac + fi + ;; +esac + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { $as_echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5 +$as_echo_n "checking dynamic linker characteristics... " >&6; } + +if test "$GCC" = yes; then + case $host_os in + darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; + *) lt_awk_arg="/^libraries:/" ;; + esac + lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if $ECHO "$lt_search_path_spec" | $GREP ';' >/dev/null ; then + # if the path contains ";" then we assume it to be the separator + # otherwise default to the standard path separator (i.e. ":") - it is + # assumed that no part of a normal pathname contains ";" but that should + # okay in the real world where ";" in dirpaths is itself problematic. + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e 's/;/ /g'` + else + lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + # Ok, now we have the path, separated by spaces, we can step through it + # and add multilib dir if necessary. + lt_tmp_lt_search_path_spec= + lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` + for lt_sys_path in $lt_search_path_spec; do + if test -d "$lt_sys_path/$lt_multi_os_dir"; then + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" + else + test -d "$lt_sys_path" && \ + lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" + fi + done + lt_search_path_spec=`$ECHO $lt_tmp_lt_search_path_spec | awk ' +BEGIN {RS=" "; FS="/|\n";} { + lt_foo=""; + lt_count=0; + for (lt_i = NF; lt_i > 0; lt_i--) { + if ($lt_i != "" && $lt_i != ".") { + if ($lt_i == "..") { + lt_count++; + } else { + if (lt_count == 0) { + lt_foo="/" $lt_i lt_foo; + } else { + lt_count--; + } + } + } + } + if (lt_foo != "") { lt_freq[lt_foo]++; } + if (lt_freq[lt_foo] == 1) { print lt_foo; } +}'` + sys_lib_search_path_spec=`$ECHO $lt_search_path_spec` +else + sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" +fi +library_names_spec= +libname_spec='lib$name' +soname_spec= +shrext_cmds=".so" +postinstall_cmds= +postuninstall_cmds= +finish_cmds= +finish_eval= +shlibpath_var= +shlibpath_overrides_runpath=unknown +version_type=none +dynamic_linker="$host_os ld.so" +sys_lib_dlsearch_path_spec="/lib /usr/lib" +need_lib_prefix=unknown +hardcode_into_libs=no + +# when you set need_version to no, make sure it does not cause -set_version +# flags to be left without arguments +need_version=unknown + +case $host_os in +aix3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' + shlibpath_var=LIBPATH + + # AIX 3 has no versioning support, so we append a major version to the name. + soname_spec='${libname}${release}${shared_ext}$major' + ;; + +aix[4-9]*) + version_type=linux + need_lib_prefix=no + need_version=no + hardcode_into_libs=yes + if test "$host_cpu" = ia64; then + # AIX 5 supports IA64 + library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + else + # With GCC up to 2.95.x, collect2 would create an import file + # for dependence libraries. The import file would start with + # the line `#! .'. This would cause the generated library to + # depend on `.', always an invalid library. This was fixed in + # development snapshots of GCC prior to 3.0. + case $host_os in + aix4 | aix4.[01] | aix4.[01].*) + if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' + echo ' yes ' + echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then + : + else + can_build_shared=no + fi + ;; + esac + # AIX (on Power*) has no versioning support, so currently we can not hardcode correct + # soname into executable. Probably we can add versioning support to + # collect2, so additional links can be useful in future. + if test "$aix_use_runtimelinking" = yes; then + # If using run time linking (on AIX 4.2 or later) use lib.so + # instead of lib.a to let people know that these are not + # typical AIX shared libraries. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + else + # We preserve .a as extension for shared libraries through AIX4.2 + # and later when we are not doing run time linking. + library_names_spec='${libname}${release}.a $libname.a' + soname_spec='${libname}${release}${shared_ext}$major' + fi + shlibpath_var=LIBPATH + fi + ;; + +amigaos*) + case $host_cpu in + powerpc) + # Since July 2007 AmigaOS4 officially supports .so libraries. + # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + ;; + m68k) + library_names_spec='$libname.ixlibrary $libname.a' + # Create ${libname}_ixlibrary.a entries in /sys/libs. + finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$ECHO "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' + ;; + esac + ;; + +beos*) + library_names_spec='${libname}${shared_ext}' + dynamic_linker="$host_os ld.so" + shlibpath_var=LIBRARY_PATH + ;; + +bsdi[45]*) + version_type=linux + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" + sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" + # the default ld.so.conf also contains /usr/contrib/lib and + # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow + # libtool to hard-code these into programs + ;; + +cygwin* | mingw* | pw32* | cegcc*) + version_type=windows + shrext_cmds=".dll" + need_version=no + need_lib_prefix=no + + case $GCC,$host_os in + yes,cygwin* | yes,mingw* | yes,pw32* | yes,cegcc*) + library_names_spec='$libname.dll.a' + # DLL is installed to $(libdir)/../bin by postinstall_cmds + postinstall_cmds='base_file=`basename \${file}`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ + dlpath=$dir/\$dldll~ + $RM \$dlpath' + shlibpath_overrides_runpath=yes + + case $host_os in + cygwin*) + # Cygwin DLLs use 'cyg' prefix rather than 'lib' + soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" + ;; + mingw* | cegcc*) + # MinGW DLLs use traditional 'lib' prefix + soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + sys_lib_search_path_spec=`$CC -print-search-dirs | $GREP "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` + if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then + # It is most probably a Windows format PATH printed by + # mingw gcc, but we are running on Cygwin. Gcc prints its search + # path with ; separators, and with drive letters. We can handle the + # drive letters (cygwin fileutils understands them), so leave them, + # especially as we might pass files found there to a mingw objdump, + # which wouldn't understand a cygwinified path. Ahh. + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` + else + sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` + fi + ;; + pw32*) + # pw32 DLLs use 'pw' prefix rather than 'lib' + library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' + ;; + esac + ;; + + *) + library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' + ;; + esac + dynamic_linker='Win32 ld.exe' + # FIXME: first we should search . and the directory the executable is in + shlibpath_var=PATH + ;; + +darwin* | rhapsody*) + dynamic_linker="$host_os dyld" + version_type=darwin + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' + soname_spec='${libname}${release}${major}$shared_ext' + shlibpath_overrides_runpath=yes + shlibpath_var=DYLD_LIBRARY_PATH + shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' + + sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" + sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' + ;; + +dgux*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +freebsd1*) + dynamic_linker=no + ;; + +freebsd* | dragonfly*) + # DragonFly does not have aout. When/if they implement a new + # versioning mechanism, adjust this. + if test -x /usr/bin/objformat; then + objformat=`/usr/bin/objformat` + else + case $host_os in + freebsd[123]*) objformat=aout ;; + *) objformat=elf ;; + esac + fi + # Handle Gentoo/FreeBSD as it was Linux + case $host_vendor in + gentoo) + version_type=linux ;; + *) + version_type=freebsd-$objformat ;; + esac + + case $version_type in + freebsd-elf*) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + need_version=no + need_lib_prefix=no + ;; + freebsd-*) + library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' + need_version=yes + ;; + linux) + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + need_lib_prefix=no + need_version=no + ;; + esac + shlibpath_var=LD_LIBRARY_PATH + case $host_os in + freebsd2*) + shlibpath_overrides_runpath=yes + ;; + freebsd3.[01]* | freebsdelf3.[01]*) + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ + freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + *) # from 4.6 on, and DragonFly + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + esac + ;; + +gnu*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + hardcode_into_libs=yes + ;; + +hpux9* | hpux10* | hpux11*) + # Give a soname corresponding to the major version so that dld.sl refuses to + # link against other versions. + version_type=sunos + need_lib_prefix=no + need_version=no + case $host_cpu in + ia64*) + shrext_cmds='.so' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.so" + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + if test "X$HPUX_IA64_MODE" = X32; then + sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" + else + sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" + fi + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + hppa*64*) + shrext_cmds='.sl' + hardcode_into_libs=yes + dynamic_linker="$host_os dld.sl" + shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH + shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" + sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec + ;; + *) + shrext_cmds='.sl' + dynamic_linker="$host_os dld.sl" + shlibpath_var=SHLIB_PATH + shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + ;; + esac + # HP-UX runs *really* slowly unless shared libraries are mode 555. + postinstall_cmds='chmod 555 $lib' + ;; + +interix[3-9]*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +irix5* | irix6* | nonstopux*) + case $host_os in + nonstopux*) version_type=nonstopux ;; + *) + if test "$lt_cv_prog_gnu_ld" = yes; then + version_type=linux + else + version_type=irix + fi ;; + esac + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' + case $host_os in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in # libtool.m4 will add one of these switches to LD + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") + libsuff= shlibsuff= libmagic=32-bit;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") + libsuff=32 shlibsuff=N32 libmagic=N32;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") + libsuff=64 shlibsuff=64 libmagic=64-bit;; + *) libsuff= shlibsuff= libmagic=never-match;; + esac + ;; + esac + shlibpath_var=LD_LIBRARY${shlibsuff}_PATH + shlibpath_overrides_runpath=no + sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" + sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" + hardcode_into_libs=yes + ;; + +# No shared lib support for Linux oldld, aout, or coff. +linux*oldld* | linux*aout* | linux*coff*) + dynamic_linker=no + ;; + +# This must be Linux ELF. +linux* | k*bsd*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + # Some binutils ld are patched to set DT_RUNPATH + save_LDFLAGS=$LDFLAGS + save_libdir=$libdir + eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ + LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then + shlibpath_overrides_runpath=yes +fi + +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS=$save_LDFLAGS + libdir=$save_libdir + + # This implies no fast_install, which is unacceptable. + # Some rework will be needed to allow for fast_install + # before this can be enabled. + hardcode_into_libs=yes + + # Append ld.so.conf contents to the search path + if test -f /etc/ld.so.conf; then + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + fi + + # We used to test for /lib/ld.so.1 and disable shared libraries on + # powerpc, because MkLinux only supported shared libraries with the + # GNU dynamic linker. Since this was broken with cross compilers, + # most powerpc-linux boxes support dynamic linking these days and + # people can always --disable-shared, the test was removed, and we + # assume the GNU/Linux dynamic linker is in use. + dynamic_linker='GNU/Linux ld.so' + ;; + +netbsd*) + version_type=sunos + need_lib_prefix=no + need_version=no + if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + dynamic_linker='NetBSD (a.out) ld.so' + else + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + dynamic_linker='NetBSD ld.elf_so' + fi + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + ;; + +newsos6) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + ;; + +*nto* | *qnx*) + version_type=qnx + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='ldqnx.so' + ;; + +openbsd*) + version_type=sunos + sys_lib_dlsearch_path_spec="/usr/lib" + need_lib_prefix=no + # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. + case $host_os in + openbsd3.3 | openbsd3.3.*) need_version=yes ;; + *) need_version=no ;; + esac + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' + shlibpath_var=LD_LIBRARY_PATH + if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + case $host_os in + openbsd2.[89] | openbsd2.[89].*) + shlibpath_overrides_runpath=no + ;; + *) + shlibpath_overrides_runpath=yes + ;; + esac + else + shlibpath_overrides_runpath=yes + fi + ;; + +os2*) + libname_spec='$name' + shrext_cmds=".dll" + need_lib_prefix=no + library_names_spec='$libname${shared_ext} $libname.a' + dynamic_linker='OS/2 ld.exe' + shlibpath_var=LIBPATH + ;; + +osf3* | osf4* | osf5*) + version_type=osf + need_lib_prefix=no + need_version=no + soname_spec='${libname}${release}${shared_ext}$major' + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" + sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" + ;; + +rdos*) + dynamic_linker=no + ;; + +solaris*) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + # ldd complains unless libraries are executable + postinstall_cmds='chmod +x $lib' + ;; + +sunos4*) + version_type=sunos + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' + finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + if test "$with_gnu_ld" = yes; then + need_lib_prefix=no + fi + need_version=yes + ;; + +sysv4 | sysv4.3*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + case $host_vendor in + sni) + shlibpath_overrides_runpath=no + need_lib_prefix=no + runpath_var=LD_RUN_PATH + ;; + siemens) + need_lib_prefix=no + ;; + motorola) + need_lib_prefix=no + need_version=no + shlibpath_overrides_runpath=no + sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' + ;; + esac + ;; + +sysv4*MP*) + if test -d /usr/nec ;then + version_type=linux + library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' + soname_spec='$libname${shared_ext}.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=freebsd-elf + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + if test "$with_gnu_ld" = yes; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +tpf*) + # TPF is a cross-target only. Preferred cross-host = GNU/Linux. + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +uts4*) + version_type=linux + library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' + soname_spec='${libname}${release}${shared_ext}$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +*) + dynamic_linker=no + ;; +esac +{ $as_echo "$as_me:$LINENO: result: $dynamic_linker" >&5 +$as_echo "$dynamic_linker" >&6; } +test "$dynamic_linker" = no && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test "$GCC" = yes; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then + sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" +fi +if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then + sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" +fi + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { $as_echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5 +$as_echo_n "checking how to hardcode library paths into programs... " >&6; } +hardcode_action= +if test -n "$hardcode_libdir_flag_spec" || + test -n "$runpath_var" || + test "X$hardcode_automatic" = "Xyes" ; then + + # We can hardcode non-existent directories. + if test "$hardcode_direct" != no && + # If the only mechanism to avoid hardcoding is shlibpath_var, we + # have to relink, otherwise we might link with an installed library + # when we should be linking with a yet-to-be-installed one + ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no && + test "$hardcode_minus_L" != no; then + # Linking always hardcodes the temporary library directory. + hardcode_action=relink + else + # We can link without hardcoding, and we can hardcode nonexisting dirs. + hardcode_action=immediate + fi +else + # We cannot hardcode anything, or else we can only hardcode existing + # directories. + hardcode_action=unsupported +fi +{ $as_echo "$as_me:$LINENO: result: $hardcode_action" >&5 +$as_echo "$hardcode_action" >&6; } + +if test "$hardcode_action" = relink || + test "$inherit_rpath" = yes; then + # Fast installation is not supported + enable_fast_install=no +elif test "$shlibpath_overrides_runpath" = yes || + test "$enable_shared" = no; then + # Fast installation is not necessary + enable_fast_install=needless +fi + + + + + + + if test "x$enable_dlopen" != xyes; then + enable_dlopen=unknown + enable_dlopen_self=unknown + enable_dlopen_self_static=unknown +else + lt_cv_dlopen=no + lt_cv_dlopen_libs= + + case $host_os in + beos*) + lt_cv_dlopen="load_add_on" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + ;; + + mingw* | pw32* | cegcc*) + lt_cv_dlopen="LoadLibrary" + lt_cv_dlopen_libs= + ;; + + cygwin*) + lt_cv_dlopen="dlopen" + lt_cv_dlopen_libs= + ;; + + darwin*) + # if libdl is installed we need to link against it + { $as_echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_lib_dl_dlopen=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_dl_dlopen=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + + lt_cv_dlopen="dyld" + lt_cv_dlopen_libs= + lt_cv_dlopen_self=yes + +fi + + ;; + + *) + { $as_echo "$as_me:$LINENO: checking for shl_load" >&5 +$as_echo_n "checking for shl_load... " >&6; } +if test "${ac_cv_func_shl_load+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define shl_load to an innocuous variant, in case declares shl_load. + For example, HP-UX 11i declares gettimeofday. */ +#define shl_load innocuous_shl_load + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char shl_load (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef shl_load + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char shl_load (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_shl_load || defined __stub___shl_load +choke me +#endif + +int +main () +{ +return shl_load (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_func_shl_load=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_func_shl_load=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5 +$as_echo "$ac_cv_func_shl_load" >&6; } +if test $ac_cv_func_shl_load = yes; then + lt_cv_dlopen="shl_load" +else + { $as_echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 +$as_echo_n "checking for shl_load in -ldld... " >&6; } +if test "${ac_cv_lib_dld_shl_load+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char shl_load (); +int +main () +{ +return shl_load (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_lib_dld_shl_load=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_dld_shl_load=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 +$as_echo "$ac_cv_lib_dld_shl_load" >&6; } +if test $ac_cv_lib_dld_shl_load = yes; then + lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld" +else + { $as_echo "$as_me:$LINENO: checking for dlopen" >&5 +$as_echo_n "checking for dlopen... " >&6; } +if test "${ac_cv_func_dlopen+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define dlopen to an innocuous variant, in case declares dlopen. + For example, HP-UX 11i declares gettimeofday. */ +#define dlopen innocuous_dlopen + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char dlopen (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef dlopen + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_dlopen || defined __stub___dlopen +choke me +#endif + +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_func_dlopen=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_func_dlopen=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5 +$as_echo "$ac_cv_func_dlopen" >&6; } +if test $ac_cv_func_dlopen = yes; then + lt_cv_dlopen="dlopen" +else + { $as_echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } +if test "${ac_cv_lib_dl_dlopen+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_lib_dl_dlopen=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_dl_dlopen=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test $ac_cv_lib_dl_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" +else + { $as_echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5 +$as_echo_n "checking for dlopen in -lsvld... " >&6; } +if test "${ac_cv_lib_svld_dlopen+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsvld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_lib_svld_dlopen=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_svld_dlopen=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5 +$as_echo "$ac_cv_lib_svld_dlopen" >&6; } +if test $ac_cv_lib_svld_dlopen = yes; then + lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" +else + { $as_echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5 +$as_echo_n "checking for dld_link in -ldld... " >&6; } +if test "${ac_cv_lib_dld_dld_link+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dld_link (); +int +main () +{ +return dld_link (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_lib_dld_dld_link=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_dld_dld_link=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5 +$as_echo "$ac_cv_lib_dld_dld_link" >&6; } +if test $ac_cv_lib_dld_dld_link = yes; then + lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld" +fi + + +fi + + +fi + + +fi + + +fi + + +fi + + ;; + esac + + if test "x$lt_cv_dlopen" != xno; then + enable_dlopen=yes + else + enable_dlopen=no + fi + + case $lt_cv_dlopen in + dlopen) + save_CPPFLAGS="$CPPFLAGS" + test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" + + save_LDFLAGS="$LDFLAGS" + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" + + save_LIBS="$LIBS" + LIBS="$lt_cv_dlopen_libs $LIBS" + + { $as_echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5 +$as_echo_n "checking whether a program can dlopen itself... " >&6; } +if test "${lt_cv_dlopen_self+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext <<_LT_EOF +#line 10144 "configure" +#include "confdefs.h" + +#if HAVE_DLFCN_H +#include +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + else + puts (dlerror ()); + + return status; +} +_LT_EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) >&5 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; + x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self=no + fi +fi +rm -fr conftest* + + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5 +$as_echo "$lt_cv_dlopen_self" >&6; } + + if test "x$lt_cv_dlopen_self" = xyes; then + wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" + { $as_echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5 +$as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; } +if test "${lt_cv_dlopen_self_static+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + lt_cv_dlopen_self_static=cross +else + lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 + lt_status=$lt_dlunknown + cat > conftest.$ac_ext <<_LT_EOF +#line 10240 "configure" +#include "confdefs.h" + +#if HAVE_DLFCN_H +#include +#endif + +#include + +#ifdef RTLD_GLOBAL +# define LT_DLGLOBAL RTLD_GLOBAL +#else +# ifdef DL_GLOBAL +# define LT_DLGLOBAL DL_GLOBAL +# else +# define LT_DLGLOBAL 0 +# endif +#endif + +/* We may have to define LT_DLLAZY_OR_NOW in the command line if we + find out it does not work in some platform. */ +#ifndef LT_DLLAZY_OR_NOW +# ifdef RTLD_LAZY +# define LT_DLLAZY_OR_NOW RTLD_LAZY +# else +# ifdef DL_LAZY +# define LT_DLLAZY_OR_NOW DL_LAZY +# else +# ifdef RTLD_NOW +# define LT_DLLAZY_OR_NOW RTLD_NOW +# else +# ifdef DL_NOW +# define LT_DLLAZY_OR_NOW DL_NOW +# else +# define LT_DLLAZY_OR_NOW 0 +# endif +# endif +# endif +# endif +#endif + +void fnord() { int i=42;} +int main () +{ + void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); + int status = $lt_dlunknown; + + if (self) + { + if (dlsym (self,"fnord")) status = $lt_dlno_uscore; + else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; + /* dlclose (self); */ + } + else + puts (dlerror ()); + + return status; +} +_LT_EOF + if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 + (eval $ac_link) 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then + (./conftest; exit; ) >&5 2>/dev/null + lt_status=$? + case x$lt_status in + x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; + x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; + esac + else : + # compilation failed + lt_cv_dlopen_self_static=no + fi +fi +rm -fr conftest* + + +fi +{ $as_echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5 +$as_echo "$lt_cv_dlopen_self_static" >&6; } + fi + + CPPFLAGS="$save_CPPFLAGS" + LDFLAGS="$save_LDFLAGS" + LIBS="$save_LIBS" + ;; + esac + + case $lt_cv_dlopen_self in + yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; + *) enable_dlopen_self=unknown ;; + esac + + case $lt_cv_dlopen_self_static in + yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; + *) enable_dlopen_self_static=unknown ;; + esac +fi + + + + + + + + + + + + + + + + + +striplib= +old_striplib= +{ $as_echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5 +$as_echo_n "checking whether stripping libraries is possible... " >&6; } +if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then + test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" + test -z "$striplib" && striplib="$STRIP --strip-unneeded" + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else +# FIXME - insert some real tests, host_os isn't really good enough + case $host_os in + darwin*) + if test -n "$STRIP" ; then + striplib="$STRIP -x" + old_striplib="$STRIP -S" + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } + else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + fi + ;; + *) + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + ;; + esac +fi + + + + + + + + + + + + + # Report which library types will actually be built + { $as_echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5 +$as_echo_n "checking if libtool supports shared libraries... " >&6; } + { $as_echo "$as_me:$LINENO: result: $can_build_shared" >&5 +$as_echo "$can_build_shared" >&6; } + + { $as_echo "$as_me:$LINENO: checking whether to build shared libraries" >&5 +$as_echo_n "checking whether to build shared libraries... " >&6; } + test "$can_build_shared" = "no" && enable_shared=no + + # On AIX, shared libraries and static libraries use the same namespace, and + # are all built from PIC. + case $host_os in + aix3*) + test "$enable_shared" = yes && enable_static=no + if test -n "$RANLIB"; then + archive_cmds="$archive_cmds~\$RANLIB \$lib" + postinstall_cmds='$RANLIB $lib' + fi + ;; + + aix[4-9]*) + if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then + test "$enable_shared" = yes && enable_static=no + fi + ;; + esac + { $as_echo "$as_me:$LINENO: result: $enable_shared" >&5 +$as_echo "$enable_shared" >&6; } + + { $as_echo "$as_me:$LINENO: checking whether to build static libraries" >&5 +$as_echo_n "checking whether to build static libraries... " >&6; } + # Make sure either enable_shared or enable_static is yes. + test "$enable_shared" = yes || enable_static=yes + { $as_echo "$as_me:$LINENO: result: $enable_static" >&5 +$as_echo "$enable_static" >&6; } + + + + +fi +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CC="$lt_save_CC" + + + + + + + + + + + + + + ac_config_commands="$ac_config_commands libtool" + + + + +# Only expand once: + + +# Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +# Reject install programs that cannot install multiple files. +{ $as_echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 +$as_echo_n "checking for a BSD-compatible install... " >&6; } +if test -z "$INSTALL"; then +if test "${ac_cv_path_install+set}" = set; then + $as_echo_n "(cached) " >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in + ./ | .// | /cC/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then + if test $ac_prog = install && + grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + fi + done + done + ;; +esac + +done +IFS=$as_save_IFS + +rm -rf conftest.one conftest.two conftest.dir + +fi + if test "${ac_cv_path_install+set}" = set; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. Don't cache a + # value for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + INSTALL=$ac_install_sh + fi +fi +{ $as_echo "$as_me:$LINENO: result: $INSTALL" >&5 +$as_echo "$INSTALL" >&6; } + +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' + +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' + +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' + +for ac_prog in gawk mawk nawk awk +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_AWK+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$AWK"; then + ac_cv_prog_AWK="$AWK" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_AWK="$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +AWK=$ac_cv_prog_AWK +if test -n "$AWK"; then + { $as_echo "$as_me:$LINENO: result: $AWK" >&5 +$as_echo "$AWK" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$AWK" && break +done + + +######### +# Enable large file support (if special flags are necessary) +# +# Check whether --enable-largefile was given. +if test "${enable_largefile+set}" = set; then + enableval=$enable_largefile; +fi + +if test "$enable_largefile" != no; then + + { $as_echo "$as_me:$LINENO: checking for special C compiler options needed for large files" >&5 +$as_echo_n "checking for special C compiler options needed for large files... " >&6; } +if test "${ac_cv_sys_largefile_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_sys_largefile_CC=no + if test "$GCC" != yes; then + ac_save_CC=$CC + while :; do + # IRIX 6.2 and later do not support large files by default, + # so use the C compiler's -n32 option if that helps. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF + rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + break +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext + CC="$CC -n32" + rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_sys_largefile_CC=' -n32'; break +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext + break + done + CC=$ac_save_CC + rm -f conftest.$ac_ext + fi +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sys_largefile_CC" >&5 +$as_echo "$ac_cv_sys_largefile_CC" >&6; } + if test "$ac_cv_sys_largefile_CC" != no; then + CC=$CC$ac_cv_sys_largefile_CC + fi + + { $as_echo "$as_me:$LINENO: checking for _FILE_OFFSET_BITS value needed for large files" >&5 +$as_echo_n "checking for _FILE_OFFSET_BITS value needed for large files... " >&6; } +if test "${ac_cv_sys_file_offset_bits+set}" = set; then + $as_echo_n "(cached) " >&6 +else + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_sys_file_offset_bits=no; break +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#define _FILE_OFFSET_BITS 64 +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_sys_file_offset_bits=64; break +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_cv_sys_file_offset_bits=unknown + break +done +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sys_file_offset_bits" >&5 +$as_echo "$ac_cv_sys_file_offset_bits" >&6; } +case $ac_cv_sys_file_offset_bits in #( + no | unknown) ;; + *) +cat >>confdefs.h <<_ACEOF +#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits +_ACEOF +;; +esac +rm -rf conftest* + if test $ac_cv_sys_file_offset_bits = unknown; then + { $as_echo "$as_me:$LINENO: checking for _LARGE_FILES value needed for large files" >&5 +$as_echo_n "checking for _LARGE_FILES value needed for large files... " >&6; } +if test "${ac_cv_sys_large_files+set}" = set; then + $as_echo_n "(cached) " >&6 +else + while :; do + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_sys_large_files=no; break +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#define _LARGE_FILES 1 +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_sys_large_files=1; break +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_cv_sys_large_files=unknown + break +done +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sys_large_files" >&5 +$as_echo "$ac_cv_sys_large_files" >&6; } +case $ac_cv_sys_large_files in #( + no | unknown) ;; + *) +cat >>confdefs.h <<_ACEOF +#define _LARGE_FILES $ac_cv_sys_large_files +_ACEOF +;; +esac +rm -rf conftest* + fi +fi + + +######### +# Check for needed/wanted data types +{ $as_echo "$as_me:$LINENO: checking for int8_t" >&5 +$as_echo_n "checking for int8_t... " >&6; } +if test "${ac_cv_type_int8_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_int8_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (int8_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((int8_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_int8_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_int8_t" >&5 +$as_echo "$ac_cv_type_int8_t" >&6; } +if test $ac_cv_type_int8_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_INT8_T 1 +_ACEOF + + +fi +{ $as_echo "$as_me:$LINENO: checking for int16_t" >&5 +$as_echo_n "checking for int16_t... " >&6; } +if test "${ac_cv_type_int16_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_int16_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (int16_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((int16_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_int16_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_int16_t" >&5 +$as_echo "$ac_cv_type_int16_t" >&6; } +if test $ac_cv_type_int16_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_INT16_T 1 +_ACEOF + + +fi +{ $as_echo "$as_me:$LINENO: checking for int32_t" >&5 +$as_echo_n "checking for int32_t... " >&6; } +if test "${ac_cv_type_int32_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_int32_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (int32_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((int32_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_int32_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_int32_t" >&5 +$as_echo "$ac_cv_type_int32_t" >&6; } +if test $ac_cv_type_int32_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_INT32_T 1 +_ACEOF + + +fi +{ $as_echo "$as_me:$LINENO: checking for int64_t" >&5 +$as_echo_n "checking for int64_t... " >&6; } +if test "${ac_cv_type_int64_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_int64_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (int64_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((int64_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_int64_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_int64_t" >&5 +$as_echo "$ac_cv_type_int64_t" >&6; } +if test $ac_cv_type_int64_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_INT64_T 1 +_ACEOF + + +fi +{ $as_echo "$as_me:$LINENO: checking for intptr_t" >&5 +$as_echo_n "checking for intptr_t... " >&6; } +if test "${ac_cv_type_intptr_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_intptr_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (intptr_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((intptr_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_intptr_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_intptr_t" >&5 +$as_echo "$ac_cv_type_intptr_t" >&6; } +if test $ac_cv_type_intptr_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_INTPTR_T 1 +_ACEOF + + +fi +{ $as_echo "$as_me:$LINENO: checking for uint8_t" >&5 +$as_echo_n "checking for uint8_t... " >&6; } +if test "${ac_cv_type_uint8_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_uint8_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (uint8_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((uint8_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_uint8_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uint8_t" >&5 +$as_echo "$ac_cv_type_uint8_t" >&6; } +if test $ac_cv_type_uint8_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINT8_T 1 +_ACEOF + + +fi +{ $as_echo "$as_me:$LINENO: checking for uint16_t" >&5 +$as_echo_n "checking for uint16_t... " >&6; } +if test "${ac_cv_type_uint16_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_uint16_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (uint16_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((uint16_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_uint16_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uint16_t" >&5 +$as_echo "$ac_cv_type_uint16_t" >&6; } +if test $ac_cv_type_uint16_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINT16_T 1 +_ACEOF + + +fi +{ $as_echo "$as_me:$LINENO: checking for uint32_t" >&5 +$as_echo_n "checking for uint32_t... " >&6; } +if test "${ac_cv_type_uint32_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_uint32_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (uint32_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((uint32_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_uint32_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uint32_t" >&5 +$as_echo "$ac_cv_type_uint32_t" >&6; } +if test $ac_cv_type_uint32_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINT32_T 1 +_ACEOF + + +fi +{ $as_echo "$as_me:$LINENO: checking for uint64_t" >&5 +$as_echo_n "checking for uint64_t... " >&6; } +if test "${ac_cv_type_uint64_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_uint64_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (uint64_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((uint64_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_uint64_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uint64_t" >&5 +$as_echo "$ac_cv_type_uint64_t" >&6; } +if test $ac_cv_type_uint64_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINT64_T 1 +_ACEOF + + +fi +{ $as_echo "$as_me:$LINENO: checking for uintptr_t" >&5 +$as_echo_n "checking for uintptr_t... " >&6; } +if test "${ac_cv_type_uintptr_t+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_type_uintptr_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (uintptr_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((uintptr_t))) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_uintptr_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 +$as_echo "$ac_cv_type_uintptr_t" >&6; } +if test $ac_cv_type_uintptr_t = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINTPTR_T 1 +_ACEOF + + +fi + + +######### +# Check for needed/wanted headers + + + + + +for ac_header in sys/types.h stdlib.h stdint.h inttypes.h malloc.h +do +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +fi +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:$LINENO: checking $ac_header usability" >&5 +$as_echo_n "checking $ac_header usability... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_compiler=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:$LINENO: checking $ac_header presence" >&5 +$as_echo_n "checking $ac_header presence... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <$ac_header> +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi + +rm -f conftest.err conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + + ;; +esac +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" +fi +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + +fi +if test `eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +######### +# Figure out whether or not we have these functions +# + + + + + + + +for ac_func in usleep fdatasync localtime_r gmtime_r localtime_s utime malloc_usable_size +do +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } +if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define $ac_func to an innocuous variant, in case declares $ac_func. + For example, HP-UX 11i declares gettimeofday. */ +#define $ac_func innocuous_$ac_func + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $ac_func (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $ac_func + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $ac_func (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$ac_func || defined __stub___$ac_func +choke me +#endif + +int +main () +{ +return $ac_func (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + eval "$as_ac_var=yes" +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_var=no" +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +if test `eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + + +######### +# By default, we use the amalgamation (this may be changed below...) +# +USE_AMALGAMATION=1 + +######### +# See whether we can run specific tclsh versions known to work well; +# if not, then we fall back to plain tclsh. +# TODO: try other versions before falling back? +# +for ac_prog in tclsh8.6 tclsh8.5 tclsh +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_TCLSH_CMD+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$TCLSH_CMD"; then + ac_cv_prog_TCLSH_CMD="$TCLSH_CMD" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_TCLSH_CMD="$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +TCLSH_CMD=$ac_cv_prog_TCLSH_CMD +if test -n "$TCLSH_CMD"; then + { $as_echo "$as_me:$LINENO: result: $TCLSH_CMD" >&5 +$as_echo "$TCLSH_CMD" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$TCLSH_CMD" && break +done +test -n "$TCLSH_CMD" || TCLSH_CMD="none" + +if test "$TCLSH_CMD" = "none"; then + # If we can't find a local tclsh, then building the amalgamation will fail. + # We act as though --disable-amalgamation has been used. + echo "Warning: can't find tclsh - defaulting to non-amalgamation build." + USE_AMALGAMATION=0 + TCLSH_CMD="tclsh" +fi + + + +if test "x${TCLLIBDIR+set}" != "xset" ; then + TCLLIBDIR='$(libdir)' + for i in `echo 'puts stdout $auto_path' | ${TCLSH_CMD}` ; do + TCLLIBDIR=$i + break + done + TCLLIBDIR="${TCLLIBDIR}/sqlite3" +fi + + +######### +# Set up an appropriate program prefix +# +if test "$program_prefix" = "NONE"; then + program_prefix="" +fi + + +VERSION=`cat $srcdir/VERSION | sed 's/^\([0-9]*\.*[0-9]*\).*/\1/'` +{ $as_echo "$as_me:$LINENO: Version set to $VERSION" >&5 +$as_echo "$as_me: Version set to $VERSION" >&6;} + +RELEASE=`cat $srcdir/VERSION` +{ $as_echo "$as_me:$LINENO: Release set to $RELEASE" >&5 +$as_echo "$as_me: Release set to $RELEASE" >&6;} + +VERSION_NUMBER=`cat $srcdir/VERSION \ + | sed 's/[^0-9]/ /g' \ + | awk '{printf "%d%03d%03d",$1,$2,$3}'` +{ $as_echo "$as_me:$LINENO: Version number set to $VERSION_NUMBER" >&5 +$as_echo "$as_me: Version number set to $VERSION_NUMBER" >&6;} + + +######### +# Check to see if the --with-hints=FILE option is used. If there is none, +# then check for a files named "$host.hints" and ../$hosts.hints where +# $host is the hostname of the build system. If still no hints are +# found, try looking in $system.hints and ../$system.hints where +# $system is the result of uname -s. +# + +# Check whether --with-hints was given. +if test "${with_hints+set}" = set; then + withval=$with_hints; hints=$withval +fi + +if test "$hints" = ""; then + host=`hostname | sed 's/\..*//'` + if test -r $host.hints; then + hints=$host.hints + else + if test -r ../$host.hints; then + hints=../$host.hints + fi + fi +fi +if test "$hints" = ""; then + sys=`uname -s` + if test -r $sys.hints; then + hints=$sys.hints + else + if test -r ../$sys.hints; then + hints=../$sys.hints + fi + fi +fi +if test "$hints" != ""; then + { $as_echo "$as_me:$LINENO: result: reading hints from $hints" >&5 +$as_echo "reading hints from $hints" >&6; } + . $hints +fi + +######### +# Locate a compiler for the build machine. This compiler should +# generate command-line programs that run on the build machine. +# +if test x"$cross_compiling" = xno; then + BUILD_CC=$CC + BUILD_CFLAGS=$CFLAGS +else + if test "${BUILD_CC+set}" != set; then + for ac_prog in gcc cc cl +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_BUILD_CC+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test -n "$BUILD_CC"; then + ac_cv_prog_BUILD_CC="$BUILD_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_BUILD_CC="$ac_prog" + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +BUILD_CC=$ac_cv_prog_BUILD_CC +if test -n "$BUILD_CC"; then + { $as_echo "$as_me:$LINENO: result: $BUILD_CC" >&5 +$as_echo "$BUILD_CC" >&6; } +else + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$BUILD_CC" && break +done + + fi + if test "${BUILD_CFLAGS+set}" != set; then + BUILD_CFLAGS="-g" + fi +fi + + +########## +# Do we want to support multithreaded use of sqlite +# +# Check whether --enable-threadsafe was given. +if test "${enable_threadsafe+set}" = set; then + enableval=$enable_threadsafe; +else + enable_threadsafe=yes +fi + +{ $as_echo "$as_me:$LINENO: checking whether to support threadsafe operation" >&5 +$as_echo_n "checking whether to support threadsafe operation... " >&6; } +if test "$enable_threadsafe" = "no"; then + SQLITE_THREADSAFE=0 + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +else + SQLITE_THREADSAFE=1 + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +fi + + +if test "$SQLITE_THREADSAFE" = "1"; then + { $as_echo "$as_me:$LINENO: checking for library containing pthread_create" >&5 +$as_echo_n "checking for library containing pthread_create... " >&6; } +if test "${ac_cv_search_pthread_create+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char pthread_create (); +int +main () +{ +return pthread_create (); + ; + return 0; +} +_ACEOF +for ac_lib in '' pthread; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_search_pthread_create=$ac_res +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext + if test "${ac_cv_search_pthread_create+set}" = set; then + break +fi +done +if test "${ac_cv_search_pthread_create+set}" = set; then + : +else + ac_cv_search_pthread_create=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_pthread_create" >&5 +$as_echo "$ac_cv_search_pthread_create" >&6; } +ac_res=$ac_cv_search_pthread_create +if test "$ac_res" != no; then + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +fi + +########## +# Do we want to allow a connection created in one thread to be used +# in another thread. This does not work on many Linux systems (ex: RedHat 9) +# due to bugs in the threading implementations. This is thus off by default. +# +# Check whether --enable-cross-thread-connections was given. +if test "${enable_cross_thread_connections+set}" = set; then + enableval=$enable_cross_thread_connections; +else + enable_xthreadconnect=no +fi + +{ $as_echo "$as_me:$LINENO: checking whether to allow connections to be shared across threads" >&5 +$as_echo_n "checking whether to allow connections to be shared across threads... " >&6; } +if test "$enable_xthreadconnect" = "no"; then + XTHREADCONNECT='' + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +else + XTHREADCONNECT='-DSQLITE_ALLOW_XTHREAD_CONNECT=1' + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +fi + + +########## +# Do we want to support release +# +# Check whether --enable-releasemode was given. +if test "${enable_releasemode+set}" = set; then + enableval=$enable_releasemode; +else + enable_releasemode=no +fi + +{ $as_echo "$as_me:$LINENO: checking whether to support shared library linked as release mode or not" >&5 +$as_echo_n "checking whether to support shared library linked as release mode or not... " >&6; } +if test "$enable_releasemode" = "no"; then + ALLOWRELEASE="" + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } +else + ALLOWRELEASE="-release `cat $srcdir/VERSION`" + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +fi + + +########## +# Do we want temporary databases in memory +# +# Check whether --enable-tempstore was given. +if test "${enable_tempstore+set}" = set; then + enableval=$enable_tempstore; +else + enable_tempstore=no +fi + +{ $as_echo "$as_me:$LINENO: checking whether to use an in-ram database for temporary tables" >&5 +$as_echo_n "checking whether to use an in-ram database for temporary tables... " >&6; } +case "$enable_tempstore" in + never ) + TEMP_STORE=0 + { $as_echo "$as_me:$LINENO: result: never" >&5 +$as_echo "never" >&6; } + ;; + no ) + TEMP_STORE=1 + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + ;; + yes ) + TEMP_STORE=2 + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } + ;; + always ) + TEMP_STORE=3 + { $as_echo "$as_me:$LINENO: result: always" >&5 +$as_echo "always" >&6; } + ;; + * ) + TEMP_STORE=1 + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + ;; +esac + + + +########### +# Lots of things are different if we are compiling for Windows using +# the CYGWIN environment. So check for that special case and handle +# things accordingly. +# +{ $as_echo "$as_me:$LINENO: checking if executables have the .exe suffix" >&5 +$as_echo_n "checking if executables have the .exe suffix... " >&6; } +if test "$config_BUILD_EXEEXT" = ".exe"; then + CYGWIN=yes + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:$LINENO: result: unknown" >&5 +$as_echo "unknown" >&6; } +fi +if test "$CYGWIN" != "yes"; then + { $as_echo "$as_me:$LINENO: checking host system type" >&5 +$as_echo_n "checking host system type... " >&6; } +if test "${ac_cv_host+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build +else + ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || + { { $as_echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&5 +$as_echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&2;} + { (exit 1); exit 1; }; } +fi + +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_host" >&5 +$as_echo "$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) { { $as_echo "$as_me:$LINENO: error: invalid value of canonical host" >&5 +$as_echo "$as_me: error: invalid value of canonical host" >&2;} + { (exit 1); exit 1; }; };; +esac +host=$ac_cv_host +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + +case $host_os in + *cygwin* ) CYGWIN=yes;; + * ) CYGWIN=no;; +esac + +fi +if test "$CYGWIN" = "yes"; then + BUILD_EXEEXT=.exe +else + BUILD_EXEEXT=$EXEEXT +fi +if test x"$cross_compiling" = xno; then + TARGET_EXEEXT=$BUILD_EXEEXT +else + TARGET_EXEEXT=$config_TARGET_EXEEXT +fi +if test "$TARGET_EXEEXT" = ".exe"; then + SQLITE_OS_UNIX=0 + SQLITE_OS_WIN=1 + CFLAGS="$CFLAGS -DSQLITE_OS_WIN=1" +else + SQLITE_OS_UNIX=1 + SQLITE_OS_WIN=0 + CFLAGS="$CFLAGS -DSQLITE_OS_UNIX=1" +fi + + + + + + +########## +# Figure out all the parameters needed to compile against Tcl. +# +# This code is derived from the SC_PATH_TCLCONFIG and SC_LOAD_TCLCONFIG +# macros in the in the tcl.m4 file of the standard TCL distribution. +# Those macros could not be used directly since we have to make some +# minor changes to accomodate systems that do not have TCL installed. +# +# Check whether --enable-tcl was given. +if test "${enable_tcl+set}" = set; then + enableval=$enable_tcl; use_tcl=$enableval +else + use_tcl=yes +fi + +if test "${use_tcl}" = "yes" ; then + +# Check whether --with-tcl was given. +if test "${with_tcl+set}" = set; then + withval=$with_tcl; with_tclconfig=${withval} +fi + + { $as_echo "$as_me:$LINENO: checking for Tcl configuration" >&5 +$as_echo_n "checking for Tcl configuration... " >&6; } + if test "${ac_cv_c_tclconfig+set}" = set; then + $as_echo_n "(cached) " >&6 +else + + # First check to see if --with-tcl was specified. + if test x"${with_tclconfig}" != x ; then + if test -f "${with_tclconfig}/tclConfig.sh" ; then + ac_cv_c_tclconfig=`(cd ${with_tclconfig}; pwd)` + else + { { $as_echo "$as_me:$LINENO: error: ${with_tclconfig} directory doesn't contain tclConfig.sh" >&5 +$as_echo "$as_me: error: ${with_tclconfig} directory doesn't contain tclConfig.sh" >&2;} + { (exit 1); exit 1; }; } + fi + fi + + # Start autosearch by asking tclsh + if test x"${ac_cv_c_tclconfig}" = x ; then + if test x"$cross_compiling" = xno; then + for i in `echo 'puts stdout $auto_path' | ${TCLSH_CMD}` + do + if test -f "$i/tclConfig.sh" ; then + ac_cv_c_tclconfig="$i" + break + fi + done + fi + fi + + # then check for a private Tcl installation + if test x"${ac_cv_c_tclconfig}" = x ; then + for i in \ + ../tcl \ + `ls -dr ../tcl[8-9].[0-9].[0-9]* 2>/dev/null` \ + `ls -dr ../tcl[8-9].[0-9] 2>/dev/null` \ + `ls -dr ../tcl[8-9].[0-9]* 2>/dev/null` \ + ../../tcl \ + `ls -dr ../../tcl[8-9].[0-9].[0-9]* 2>/dev/null` \ + `ls -dr ../../tcl[8-9].[0-9] 2>/dev/null` \ + `ls -dr ../../tcl[8-9].[0-9]* 2>/dev/null` \ + ../../../tcl \ + `ls -dr ../../../tcl[8-9].[0-9].[0-9]* 2>/dev/null` \ + `ls -dr ../../../tcl[8-9].[0-9] 2>/dev/null` \ + `ls -dr ../../../tcl[8-9].[0-9]* 2>/dev/null` + do + if test -f "$i/unix/tclConfig.sh" ; then + ac_cv_c_tclconfig=`(cd $i/unix; pwd)` + break + fi + done + fi + + # check in a few common install locations + if test x"${ac_cv_c_tclconfig}" = x ; then + for i in \ + `ls -d ${libdir} 2>/dev/null` \ + `ls -d /usr/local/lib 2>/dev/null` \ + `ls -d /usr/contrib/lib 2>/dev/null` \ + `ls -d /usr/lib 2>/dev/null` + do + if test -f "$i/tclConfig.sh" ; then + ac_cv_c_tclconfig=`(cd $i; pwd)` + break + fi + done + fi + + # check in a few other private locations + if test x"${ac_cv_c_tclconfig}" = x ; then + for i in \ + ${srcdir}/../tcl \ + `ls -dr ${srcdir}/../tcl[8-9].[0-9].[0-9]* 2>/dev/null` \ + `ls -dr ${srcdir}/../tcl[8-9].[0-9] 2>/dev/null` \ + `ls -dr ${srcdir}/../tcl[8-9].[0-9]* 2>/dev/null` + do + if test -f "$i/unix/tclConfig.sh" ; then + ac_cv_c_tclconfig=`(cd $i/unix; pwd)` + break + fi + done + fi + +fi + + + if test x"${ac_cv_c_tclconfig}" = x ; then + use_tcl=no + { $as_echo "$as_me:$LINENO: WARNING: Can't find Tcl configuration definitions" >&5 +$as_echo "$as_me: WARNING: Can't find Tcl configuration definitions" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: *** Without Tcl the regression tests cannot be executed ***" >&5 +$as_echo "$as_me: WARNING: *** Without Tcl the regression tests cannot be executed ***" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: *** Consider using --with-tcl=... to define location of Tcl ***" >&5 +$as_echo "$as_me: WARNING: *** Consider using --with-tcl=... to define location of Tcl ***" >&2;} + else + TCL_BIN_DIR=${ac_cv_c_tclconfig} + { $as_echo "$as_me:$LINENO: result: found $TCL_BIN_DIR/tclConfig.sh" >&5 +$as_echo "found $TCL_BIN_DIR/tclConfig.sh" >&6; } + + { $as_echo "$as_me:$LINENO: checking for existence of $TCL_BIN_DIR/tclConfig.sh" >&5 +$as_echo_n "checking for existence of $TCL_BIN_DIR/tclConfig.sh... " >&6; } + if test -f "$TCL_BIN_DIR/tclConfig.sh" ; then + { $as_echo "$as_me:$LINENO: result: loading" >&5 +$as_echo "loading" >&6; } + . $TCL_BIN_DIR/tclConfig.sh + else + { $as_echo "$as_me:$LINENO: result: file not found" >&5 +$as_echo "file not found" >&6; } + fi + + # + # If the TCL_BIN_DIR is the build directory (not the install directory), + # then set the common variable name to the value of the build variables. + # For example, the variable TCL_LIB_SPEC will be set to the value + # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC + # instead of TCL_BUILD_LIB_SPEC since it will work with both an + # installed and uninstalled version of Tcl. + # + + if test -f $TCL_BIN_DIR/Makefile ; then + TCL_LIB_SPEC=${TCL_BUILD_LIB_SPEC} + TCL_STUB_LIB_SPEC=${TCL_BUILD_STUB_LIB_SPEC} + TCL_STUB_LIB_PATH=${TCL_BUILD_STUB_LIB_PATH} + fi + + # + # eval is required to do the TCL_DBGX substitution + # + + eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\"" + eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\"" + eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\"" + + eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\"" + eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\"" + eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\"" + + + + + + + + + + + + + + fi +fi +if test "${use_tcl}" = "no" ; then + HAVE_TCL="" +else + HAVE_TCL=1 +fi + + +########## +# Figure out what C libraries are required to compile programs +# that use "readline()" library. +# +TARGET_READLINE_LIBS="" +TARGET_READLINE_INC="" +TARGET_HAVE_READLINE=0 +# Check whether --enable-readline was given. +if test "${enable_readline+set}" = set; then + enableval=$enable_readline; with_readline=$enableval +else + with_readline=auto +fi + + +if test x"$with_readline" != xno; then + found="yes" + + +# Check whether --with-readline-lib was given. +if test "${with_readline_lib+set}" = set; then + withval=$with_readline_lib; with_readline_lib=$withval +else + with_readline_lib="auto" +fi + + if test "x$with_readline_lib" = xauto; then + save_LIBS="$LIBS" + LIBS="" + { $as_echo "$as_me:$LINENO: checking for library containing tgetent" >&5 +$as_echo_n "checking for library containing tgetent... " >&6; } +if test "${ac_cv_search_tgetent+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char tgetent (); +int +main () +{ +return tgetent (); + ; + return 0; +} +_ACEOF +for ac_lib in '' readline ncurses curses termcap; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_search_tgetent=$ac_res +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext + if test "${ac_cv_search_tgetent+set}" = set; then + break +fi +done +if test "${ac_cv_search_tgetent+set}" = set; then + : +else + ac_cv_search_tgetent=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_tgetent" >&5 +$as_echo "$ac_cv_search_tgetent" >&6; } +ac_res=$ac_cv_search_tgetent +if test "$ac_res" != no; then + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + term_LIBS="$LIBS" +else + term_LIBS="" +fi + + { $as_echo "$as_me:$LINENO: checking for readline in -lreadline" >&5 +$as_echo_n "checking for readline in -lreadline... " >&6; } +if test "${ac_cv_lib_readline_readline+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lreadline $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char readline (); +int +main () +{ +return readline (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_lib_readline_readline=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_readline_readline=no +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_readline" >&5 +$as_echo "$ac_cv_lib_readline_readline" >&6; } +if test $ac_cv_lib_readline_readline = yes; then + TARGET_READLINE_LIBS="-lreadline" +else + found="no" +fi + + TARGET_READLINE_LIBS="$TARGET_READLINE_LIBS $term_LIBS" + LIBS="$save_LIBS" + else + TARGET_READLINE_LIBS="$with_readline_lib" + fi + + +# Check whether --with-readline-inc was given. +if test "${with_readline_inc+set}" = set; then + withval=$with_readline_inc; with_readline_inc=$withval +else + with_readline_inc="auto" +fi + + if test "x$with_readline_inc" = xauto; then + if test "${ac_cv_header_readline_h+set}" = set; then + { $as_echo "$as_me:$LINENO: checking for readline.h" >&5 +$as_echo_n "checking for readline.h... " >&6; } +if test "${ac_cv_header_readline_h+set}" = set; then + $as_echo_n "(cached) " >&6 +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_readline_h" >&5 +$as_echo "$ac_cv_header_readline_h" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:$LINENO: checking readline.h usability" >&5 +$as_echo_n "checking readline.h usability... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_compiler=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:$LINENO: checking readline.h presence" >&5 +$as_echo_n "checking readline.h presence... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi + +rm -f conftest.err conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { $as_echo "$as_me:$LINENO: WARNING: readline.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: readline.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: readline.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: readline.h: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { $as_echo "$as_me:$LINENO: WARNING: readline.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: readline.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: readline.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: readline.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: readline.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: readline.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: readline.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: readline.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: readline.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: readline.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: readline.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: readline.h: in the future, the compiler will take precedence" >&2;} + + ;; +esac +{ $as_echo "$as_me:$LINENO: checking for readline.h" >&5 +$as_echo_n "checking for readline.h... " >&6; } +if test "${ac_cv_header_readline_h+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_header_readline_h=$ac_header_preproc +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_readline_h" >&5 +$as_echo "$ac_cv_header_readline_h" >&6; } + +fi +if test $ac_cv_header_readline_h = yes; then + found="yes" +else + + found="no" + if test "$cross_compiling" != yes; then + for dir in /usr /usr/local /usr/local/readline /usr/contrib /mingw; do + for subdir in include include/readline; do + as_ac_File=`$as_echo "ac_cv_file_$dir/$subdir/readline.h" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $dir/$subdir/readline.h" >&5 +$as_echo_n "checking for $dir/$subdir/readline.h... " >&6; } +if { as_var=$as_ac_File; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +else + test "$cross_compiling" = yes && + { { $as_echo "$as_me:$LINENO: error: cannot check for file existence when cross compiling" >&5 +$as_echo "$as_me: error: cannot check for file existence when cross compiling" >&2;} + { (exit 1); exit 1; }; } +if test -r "$dir/$subdir/readline.h"; then + eval "$as_ac_File=yes" +else + eval "$as_ac_File=no" +fi +fi +ac_res=`eval 'as_val=${'$as_ac_File'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +if test `eval 'as_val=${'$as_ac_File'} + $as_echo "$as_val"'` = yes; then + found=yes +fi + + if test "$found" = "yes"; then + TARGET_READLINE_INC="-I$dir/$subdir" + break + fi + done + test "$found" = "yes" && break + done + fi + +fi + + + else + TARGET_READLINE_INC="$with_readline_inc" + fi + + if test x"$found" = xno; then + TARGET_READLINE_LIBS="" + TARGET_READLINE_INC="" + TARGET_HAVE_READLINE=0 + else + TARGET_HAVE_READLINE=1 + fi +fi + + + + + +########## +# Figure out what C libraries are required to compile programs +# that use "fdatasync()" function. +# +{ $as_echo "$as_me:$LINENO: checking for library containing fdatasync" >&5 +$as_echo_n "checking for library containing fdatasync... " >&6; } +if test "${ac_cv_search_fdatasync+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char fdatasync (); +int +main () +{ +return fdatasync (); + ; + return 0; +} +_ACEOF +for ac_lib in '' rt; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_search_fdatasync=$ac_res +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext + if test "${ac_cv_search_fdatasync+set}" = set; then + break +fi +done +if test "${ac_cv_search_fdatasync+set}" = set; then + : +else + ac_cv_search_fdatasync=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_fdatasync" >&5 +$as_echo "$ac_cv_search_fdatasync" >&6; } +ac_res=$ac_cv_search_fdatasync +if test "$ac_res" != no; then + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + + +######### +# check for debug enabled +# Check whether --enable-debug was given. +if test "${enable_debug+set}" = set; then + enableval=$enable_debug; use_debug=$enableval +else + use_debug=no +fi + +if test "${use_debug}" = "yes" ; then + TARGET_DEBUG="-DSQLITE_DEBUG=1" +else + TARGET_DEBUG="-DNDEBUG" +fi + + +######### +# See whether we should use the amalgamation to build +# Check whether --enable-amalgamation was given. +if test "${enable_amalgamation+set}" = set; then + enableval=$enable_amalgamation; use_amalgamation=$enableval +else + use_amalgamation=yes +fi + +if test "${use_amalgamation}" != "yes" ; then + USE_AMALGAMATION=0 +fi + + +######### +# See whether we should allow loadable extensions +# Check whether --enable-load-extension was given. +if test "${enable_load_extension+set}" = set; then + enableval=$enable_load_extension; use_loadextension=$enableval +else + use_loadextension=no +fi + +if test "${use_loadextension}" = "yes" ; then + OPT_FEATURE_FLAGS="" + { $as_echo "$as_me:$LINENO: checking for library containing dlopen" >&5 +$as_echo_n "checking for library containing dlopen... " >&6; } +if test "${ac_cv_search_dlopen+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +for ac_lib in '' dl; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then + ac_cv_search_dlopen=$ac_res +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -rf conftest.dSYM +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext + if test "${ac_cv_search_dlopen+set}" = set; then + break +fi +done +if test "${ac_cv_search_dlopen+set}" = set; then + : +else + ac_cv_search_dlopen=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_dlopen" >&5 +$as_echo "$ac_cv_search_dlopen" >&6; } +ac_res=$ac_cv_search_dlopen +if test "$ac_res" != no; then + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +else + OPT_FEATURE_FLAGS="-DSQLITE_OMIT_LOAD_EXTENSION=1" +fi + +######### +# attempt to duplicate any OMITS and ENABLES into the $(OPT_FEATURE_FLAGS) parameter +for option in $CFLAGS $CPPFLAGS +do + case $option in + -DSQLITE_OMIT*) OPT_FEATURE_FLAGS="$OPT_FEATURE_FLAGS $option";; + -DSQLITE_ENABLE*) OPT_FEATURE_FLAGS="$OPT_FEATURE_FLAGS $option";; + esac +done + + + +# attempt to remove any OMITS and ENABLES from the $(CFLAGS) parameter +ac_temp_CFLAGS="" +for option in $CFLAGS +do + case $option in + -DSQLITE_OMIT*) ;; + -DSQLITE_ENABLE*) ;; + *) ac_temp_CFLAGS="$ac_temp_CFLAGS $option";; + esac +done +CFLAGS=$ac_temp_CFLAGS + + +# attempt to remove any OMITS and ENABLES from the $(CPPFLAGS) parameter +ac_temp_CPPFLAGS="" +for option in $CPPFLAGS +do + case $option in + -DSQLITE_OMIT*) ;; + -DSQLITE_ENABLE*) ;; + *) ac_temp_CPPFLAGS="$ac_temp_CPPFLAGS $option";; + esac +done +CPPFLAGS=$ac_temp_CPPFLAGS + + +# attempt to remove any OMITS and ENABLES from the $(BUILD_CFLAGS) parameter +ac_temp_BUILD_CFLAGS="" +for option in $BUILD_CFLAGS +do + case $option in + -DSQLITE_OMIT*) ;; + -DSQLITE_ENABLE*) ;; + *) ac_temp_BUILD_CFLAGS="$ac_temp_BUILD_CFLAGS $option";; + esac +done +BUILD_CFLAGS=$ac_temp_BUILD_CFLAGS + + +######### +# See whether we should use GCOV +# Check whether --enable-gcov was given. +if test "${enable_gcov+set}" = set; then + enableval=$enable_gcov; use_gcov=$enableval +else + use_gcov=no +fi + +if test "${use_gcov}" = "yes" ; then + USE_GCOV=1 +else + USE_GCOV=0 +fi + + + +######### +# Output the config header +ac_config_headers="$ac_config_headers config.h" + + +######### +# Generate the output files. +# + +ac_config_files="$ac_config_files Makefile sqlite3.pc" + +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 +$as_echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) $as_unset $ac_var ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes (double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \). + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + test "x$cache_file" != "x/dev/null" && + { $as_echo "$as_me:$LINENO: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} + cat confcache >$cache_file + else + { $as_echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +DEFS=-DHAVE_CONFIG_H + +ac_libobjs= +ac_ltlibobjs= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" + ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + + +: ${CONFIG_STATUS=./config.status} +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ $as_echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +cat >$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false +SHELL=\${CONFIG_SHELL-$SHELL} +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +## --------------------- ## +## M4sh Initialization. ## +## --------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + + + +# PATH needs CR +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + +# Support unset when possible. +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + as_unset=unset +else + as_unset=false +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + { (exit 1); exit 1; } +fi + +# Work around bugs in pre-3.0 UWIN ksh. +for as_var in ENV MAIL MAILPATH +do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# Required to use basename. +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + + +# Name of the executable. +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# CDPATH. +$as_unset CDPATH + + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { + + # Create $as_me.lineno as a copy of $as_myself, but with $LINENO + # uniformly replaced by the line number. The first 'sed' inserts a + # line-number line after each line using $LINENO; the second 'sed' + # does the real work. The second script uses 'N' to pair each + # line-number line with the line containing $LINENO, and appends + # trailing '-' during substitution so that $LINENO is not a special + # case at line end. + # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the + # scripts with optimization help from Paolo Bonzini. Blame Lee + # E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { (exit 1); exit 1; }; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in +-n*) + case `echo 'x\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + *) ECHO_C='\c';; + esac;; +*) + ECHO_N='-n';; +esac +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -p' + fi +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p=: +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 + +# Save the log message, to keep $[0] and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by sqlite $as_me 3.8.1, which was +generated by GNU Autoconf 2.62. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" +config_commands="$ac_config_commands" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files from templates according to the +current configuration. + +Usage: $0 [OPTIONS] [FILE]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + -q, --quiet do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Configuration commands: +$config_commands + +Report bugs to ." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_version="\\ +sqlite config.status 3.8.1 +configured by $0, generated by GNU Autoconf 2.62, + with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" + +Copyright (C) 2008 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +INSTALL='$INSTALL' +AWK='$AWK' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + CONFIG_FILES="$CONFIG_FILES '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + CONFIG_HEADERS="$CONFIG_HEADERS '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + { $as_echo "$as_me: error: ambiguous option: $1 +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; };; + --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) { $as_echo "$as_me: error: unrecognized option: $1 +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; } ;; + + *) ac_config_targets="$ac_config_targets $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# +# INIT-COMMANDS +# + + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +sed_quote_subst='$sed_quote_subst' +double_quote_subst='$double_quote_subst' +delay_variable_subst='$delay_variable_subst' +macro_version='`$ECHO "X$macro_version" | $Xsed -e "$delay_single_quote_subst"`' +macro_revision='`$ECHO "X$macro_revision" | $Xsed -e "$delay_single_quote_subst"`' +enable_shared='`$ECHO "X$enable_shared" | $Xsed -e "$delay_single_quote_subst"`' +enable_static='`$ECHO "X$enable_static" | $Xsed -e "$delay_single_quote_subst"`' +pic_mode='`$ECHO "X$pic_mode" | $Xsed -e "$delay_single_quote_subst"`' +enable_fast_install='`$ECHO "X$enable_fast_install" | $Xsed -e "$delay_single_quote_subst"`' +host_alias='`$ECHO "X$host_alias" | $Xsed -e "$delay_single_quote_subst"`' +host='`$ECHO "X$host" | $Xsed -e "$delay_single_quote_subst"`' +host_os='`$ECHO "X$host_os" | $Xsed -e "$delay_single_quote_subst"`' +build_alias='`$ECHO "X$build_alias" | $Xsed -e "$delay_single_quote_subst"`' +build='`$ECHO "X$build" | $Xsed -e "$delay_single_quote_subst"`' +build_os='`$ECHO "X$build_os" | $Xsed -e "$delay_single_quote_subst"`' +SED='`$ECHO "X$SED" | $Xsed -e "$delay_single_quote_subst"`' +Xsed='`$ECHO "X$Xsed" | $Xsed -e "$delay_single_quote_subst"`' +GREP='`$ECHO "X$GREP" | $Xsed -e "$delay_single_quote_subst"`' +EGREP='`$ECHO "X$EGREP" | $Xsed -e "$delay_single_quote_subst"`' +FGREP='`$ECHO "X$FGREP" | $Xsed -e "$delay_single_quote_subst"`' +LD='`$ECHO "X$LD" | $Xsed -e "$delay_single_quote_subst"`' +NM='`$ECHO "X$NM" | $Xsed -e "$delay_single_quote_subst"`' +LN_S='`$ECHO "X$LN_S" | $Xsed -e "$delay_single_quote_subst"`' +max_cmd_len='`$ECHO "X$max_cmd_len" | $Xsed -e "$delay_single_quote_subst"`' +ac_objext='`$ECHO "X$ac_objext" | $Xsed -e "$delay_single_quote_subst"`' +exeext='`$ECHO "X$exeext" | $Xsed -e "$delay_single_quote_subst"`' +lt_unset='`$ECHO "X$lt_unset" | $Xsed -e "$delay_single_quote_subst"`' +lt_SP2NL='`$ECHO "X$lt_SP2NL" | $Xsed -e "$delay_single_quote_subst"`' +lt_NL2SP='`$ECHO "X$lt_NL2SP" | $Xsed -e "$delay_single_quote_subst"`' +reload_flag='`$ECHO "X$reload_flag" | $Xsed -e "$delay_single_quote_subst"`' +reload_cmds='`$ECHO "X$reload_cmds" | $Xsed -e "$delay_single_quote_subst"`' +OBJDUMP='`$ECHO "X$OBJDUMP" | $Xsed -e "$delay_single_quote_subst"`' +deplibs_check_method='`$ECHO "X$deplibs_check_method" | $Xsed -e "$delay_single_quote_subst"`' +file_magic_cmd='`$ECHO "X$file_magic_cmd" | $Xsed -e "$delay_single_quote_subst"`' +AR='`$ECHO "X$AR" | $Xsed -e "$delay_single_quote_subst"`' +AR_FLAGS='`$ECHO "X$AR_FLAGS" | $Xsed -e "$delay_single_quote_subst"`' +STRIP='`$ECHO "X$STRIP" | $Xsed -e "$delay_single_quote_subst"`' +RANLIB='`$ECHO "X$RANLIB" | $Xsed -e "$delay_single_quote_subst"`' +old_postinstall_cmds='`$ECHO "X$old_postinstall_cmds" | $Xsed -e "$delay_single_quote_subst"`' +old_postuninstall_cmds='`$ECHO "X$old_postuninstall_cmds" | $Xsed -e "$delay_single_quote_subst"`' +old_archive_cmds='`$ECHO "X$old_archive_cmds" | $Xsed -e "$delay_single_quote_subst"`' +CC='`$ECHO "X$CC" | $Xsed -e "$delay_single_quote_subst"`' +CFLAGS='`$ECHO "X$CFLAGS" | $Xsed -e "$delay_single_quote_subst"`' +compiler='`$ECHO "X$compiler" | $Xsed -e "$delay_single_quote_subst"`' +GCC='`$ECHO "X$GCC" | $Xsed -e "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_pipe='`$ECHO "X$lt_cv_sys_global_symbol_pipe" | $Xsed -e "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_cdecl='`$ECHO "X$lt_cv_sys_global_symbol_to_cdecl" | $Xsed -e "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "X$lt_cv_sys_global_symbol_to_c_name_address" | $Xsed -e "$delay_single_quote_subst"`' +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "X$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $Xsed -e "$delay_single_quote_subst"`' +objdir='`$ECHO "X$objdir" | $Xsed -e "$delay_single_quote_subst"`' +SHELL='`$ECHO "X$SHELL" | $Xsed -e "$delay_single_quote_subst"`' +ECHO='`$ECHO "X$ECHO" | $Xsed -e "$delay_single_quote_subst"`' +MAGIC_CMD='`$ECHO "X$MAGIC_CMD" | $Xsed -e "$delay_single_quote_subst"`' +lt_prog_compiler_no_builtin_flag='`$ECHO "X$lt_prog_compiler_no_builtin_flag" | $Xsed -e "$delay_single_quote_subst"`' +lt_prog_compiler_wl='`$ECHO "X$lt_prog_compiler_wl" | $Xsed -e "$delay_single_quote_subst"`' +lt_prog_compiler_pic='`$ECHO "X$lt_prog_compiler_pic" | $Xsed -e "$delay_single_quote_subst"`' +lt_prog_compiler_static='`$ECHO "X$lt_prog_compiler_static" | $Xsed -e "$delay_single_quote_subst"`' +lt_cv_prog_compiler_c_o='`$ECHO "X$lt_cv_prog_compiler_c_o" | $Xsed -e "$delay_single_quote_subst"`' +need_locks='`$ECHO "X$need_locks" | $Xsed -e "$delay_single_quote_subst"`' +DSYMUTIL='`$ECHO "X$DSYMUTIL" | $Xsed -e "$delay_single_quote_subst"`' +NMEDIT='`$ECHO "X$NMEDIT" | $Xsed -e "$delay_single_quote_subst"`' +LIPO='`$ECHO "X$LIPO" | $Xsed -e "$delay_single_quote_subst"`' +OTOOL='`$ECHO "X$OTOOL" | $Xsed -e "$delay_single_quote_subst"`' +OTOOL64='`$ECHO "X$OTOOL64" | $Xsed -e "$delay_single_quote_subst"`' +libext='`$ECHO "X$libext" | $Xsed -e "$delay_single_quote_subst"`' +shrext_cmds='`$ECHO "X$shrext_cmds" | $Xsed -e "$delay_single_quote_subst"`' +extract_expsyms_cmds='`$ECHO "X$extract_expsyms_cmds" | $Xsed -e "$delay_single_quote_subst"`' +archive_cmds_need_lc='`$ECHO "X$archive_cmds_need_lc" | $Xsed -e "$delay_single_quote_subst"`' +enable_shared_with_static_runtimes='`$ECHO "X$enable_shared_with_static_runtimes" | $Xsed -e "$delay_single_quote_subst"`' +export_dynamic_flag_spec='`$ECHO "X$export_dynamic_flag_spec" | $Xsed -e "$delay_single_quote_subst"`' +whole_archive_flag_spec='`$ECHO "X$whole_archive_flag_spec" | $Xsed -e "$delay_single_quote_subst"`' +compiler_needs_object='`$ECHO "X$compiler_needs_object" | $Xsed -e "$delay_single_quote_subst"`' +old_archive_from_new_cmds='`$ECHO "X$old_archive_from_new_cmds" | $Xsed -e "$delay_single_quote_subst"`' +old_archive_from_expsyms_cmds='`$ECHO "X$old_archive_from_expsyms_cmds" | $Xsed -e "$delay_single_quote_subst"`' +archive_cmds='`$ECHO "X$archive_cmds" | $Xsed -e "$delay_single_quote_subst"`' +archive_expsym_cmds='`$ECHO "X$archive_expsym_cmds" | $Xsed -e "$delay_single_quote_subst"`' +module_cmds='`$ECHO "X$module_cmds" | $Xsed -e "$delay_single_quote_subst"`' +module_expsym_cmds='`$ECHO "X$module_expsym_cmds" | $Xsed -e "$delay_single_quote_subst"`' +with_gnu_ld='`$ECHO "X$with_gnu_ld" | $Xsed -e "$delay_single_quote_subst"`' +allow_undefined_flag='`$ECHO "X$allow_undefined_flag" | $Xsed -e "$delay_single_quote_subst"`' +no_undefined_flag='`$ECHO "X$no_undefined_flag" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_libdir_flag_spec='`$ECHO "X$hardcode_libdir_flag_spec" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_libdir_flag_spec_ld='`$ECHO "X$hardcode_libdir_flag_spec_ld" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_libdir_separator='`$ECHO "X$hardcode_libdir_separator" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_direct='`$ECHO "X$hardcode_direct" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_direct_absolute='`$ECHO "X$hardcode_direct_absolute" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_minus_L='`$ECHO "X$hardcode_minus_L" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_shlibpath_var='`$ECHO "X$hardcode_shlibpath_var" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_automatic='`$ECHO "X$hardcode_automatic" | $Xsed -e "$delay_single_quote_subst"`' +inherit_rpath='`$ECHO "X$inherit_rpath" | $Xsed -e "$delay_single_quote_subst"`' +link_all_deplibs='`$ECHO "X$link_all_deplibs" | $Xsed -e "$delay_single_quote_subst"`' +fix_srcfile_path='`$ECHO "X$fix_srcfile_path" | $Xsed -e "$delay_single_quote_subst"`' +always_export_symbols='`$ECHO "X$always_export_symbols" | $Xsed -e "$delay_single_quote_subst"`' +export_symbols_cmds='`$ECHO "X$export_symbols_cmds" | $Xsed -e "$delay_single_quote_subst"`' +exclude_expsyms='`$ECHO "X$exclude_expsyms" | $Xsed -e "$delay_single_quote_subst"`' +include_expsyms='`$ECHO "X$include_expsyms" | $Xsed -e "$delay_single_quote_subst"`' +prelink_cmds='`$ECHO "X$prelink_cmds" | $Xsed -e "$delay_single_quote_subst"`' +file_list_spec='`$ECHO "X$file_list_spec" | $Xsed -e "$delay_single_quote_subst"`' +variables_saved_for_relink='`$ECHO "X$variables_saved_for_relink" | $Xsed -e "$delay_single_quote_subst"`' +need_lib_prefix='`$ECHO "X$need_lib_prefix" | $Xsed -e "$delay_single_quote_subst"`' +need_version='`$ECHO "X$need_version" | $Xsed -e "$delay_single_quote_subst"`' +version_type='`$ECHO "X$version_type" | $Xsed -e "$delay_single_quote_subst"`' +runpath_var='`$ECHO "X$runpath_var" | $Xsed -e "$delay_single_quote_subst"`' +shlibpath_var='`$ECHO "X$shlibpath_var" | $Xsed -e "$delay_single_quote_subst"`' +shlibpath_overrides_runpath='`$ECHO "X$shlibpath_overrides_runpath" | $Xsed -e "$delay_single_quote_subst"`' +libname_spec='`$ECHO "X$libname_spec" | $Xsed -e "$delay_single_quote_subst"`' +library_names_spec='`$ECHO "X$library_names_spec" | $Xsed -e "$delay_single_quote_subst"`' +soname_spec='`$ECHO "X$soname_spec" | $Xsed -e "$delay_single_quote_subst"`' +postinstall_cmds='`$ECHO "X$postinstall_cmds" | $Xsed -e "$delay_single_quote_subst"`' +postuninstall_cmds='`$ECHO "X$postuninstall_cmds" | $Xsed -e "$delay_single_quote_subst"`' +finish_cmds='`$ECHO "X$finish_cmds" | $Xsed -e "$delay_single_quote_subst"`' +finish_eval='`$ECHO "X$finish_eval" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_into_libs='`$ECHO "X$hardcode_into_libs" | $Xsed -e "$delay_single_quote_subst"`' +sys_lib_search_path_spec='`$ECHO "X$sys_lib_search_path_spec" | $Xsed -e "$delay_single_quote_subst"`' +sys_lib_dlsearch_path_spec='`$ECHO "X$sys_lib_dlsearch_path_spec" | $Xsed -e "$delay_single_quote_subst"`' +hardcode_action='`$ECHO "X$hardcode_action" | $Xsed -e "$delay_single_quote_subst"`' +enable_dlopen='`$ECHO "X$enable_dlopen" | $Xsed -e "$delay_single_quote_subst"`' +enable_dlopen_self='`$ECHO "X$enable_dlopen_self" | $Xsed -e "$delay_single_quote_subst"`' +enable_dlopen_self_static='`$ECHO "X$enable_dlopen_self_static" | $Xsed -e "$delay_single_quote_subst"`' +old_striplib='`$ECHO "X$old_striplib" | $Xsed -e "$delay_single_quote_subst"`' +striplib='`$ECHO "X$striplib" | $Xsed -e "$delay_single_quote_subst"`' + +LTCC='$LTCC' +LTCFLAGS='$LTCFLAGS' +compiler='$compiler_DEFAULT' + +# Quote evaled strings. +for var in SED \ +GREP \ +EGREP \ +FGREP \ +LD \ +NM \ +LN_S \ +lt_SP2NL \ +lt_NL2SP \ +reload_flag \ +OBJDUMP \ +deplibs_check_method \ +file_magic_cmd \ +AR \ +AR_FLAGS \ +STRIP \ +RANLIB \ +CC \ +CFLAGS \ +compiler \ +lt_cv_sys_global_symbol_pipe \ +lt_cv_sys_global_symbol_to_cdecl \ +lt_cv_sys_global_symbol_to_c_name_address \ +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ +SHELL \ +ECHO \ +lt_prog_compiler_no_builtin_flag \ +lt_prog_compiler_wl \ +lt_prog_compiler_pic \ +lt_prog_compiler_static \ +lt_cv_prog_compiler_c_o \ +need_locks \ +DSYMUTIL \ +NMEDIT \ +LIPO \ +OTOOL \ +OTOOL64 \ +shrext_cmds \ +export_dynamic_flag_spec \ +whole_archive_flag_spec \ +compiler_needs_object \ +with_gnu_ld \ +allow_undefined_flag \ +no_undefined_flag \ +hardcode_libdir_flag_spec \ +hardcode_libdir_flag_spec_ld \ +hardcode_libdir_separator \ +fix_srcfile_path \ +exclude_expsyms \ +include_expsyms \ +file_list_spec \ +variables_saved_for_relink \ +libname_spec \ +library_names_spec \ +soname_spec \ +finish_eval \ +old_striplib \ +striplib; do + case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in + *[\\\\\\\`\\"\\\$]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +# Double-quote double-evaled strings. +for var in reload_cmds \ +old_postinstall_cmds \ +old_postuninstall_cmds \ +old_archive_cmds \ +extract_expsyms_cmds \ +old_archive_from_new_cmds \ +old_archive_from_expsyms_cmds \ +archive_cmds \ +archive_expsym_cmds \ +module_cmds \ +module_expsym_cmds \ +export_symbols_cmds \ +prelink_cmds \ +postinstall_cmds \ +postuninstall_cmds \ +finish_cmds \ +sys_lib_search_path_spec \ +sys_lib_dlsearch_path_spec; do + case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in + *[\\\\\\\`\\"\\\$]*) + eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" + ;; + *) + eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" + ;; + esac +done + +# Fix-up fallback echo if it was mangled by the above quoting rules. +case \$lt_ECHO in +*'\\\$0 --fallback-echo"') lt_ECHO=\`\$ECHO "X\$lt_ECHO" | \$Xsed -e 's/\\\\\\\\\\\\\\\$0 --fallback-echo"\$/\$0 --fallback-echo"/'\` + ;; +esac + +ac_aux_dir='$ac_aux_dir' +xsi_shell='$xsi_shell' +lt_shell_append='$lt_shell_append' + +# See if we are running on zsh, and set the options which allow our +# commands through without removal of \ escapes INIT. +if test -n "\${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST +fi + + + PACKAGE='$PACKAGE' + VERSION='$VERSION' + TIMESTAMP='$TIMESTAMP' + RM='$RM' + ofile='$ofile' + + + + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; + "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "sqlite3.pc") CONFIG_FILES="$CONFIG_FILES sqlite3.pc" ;; + + *) { { $as_echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 +$as_echo "$as_me: error: invalid argument: $ac_config_target" >&2;} + { (exit 1); exit 1; }; };; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers + test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= + trap 'exit_status=$? + { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status +' 0 + trap '{ (exit 1); exit 1; }' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -n "$tmp" && test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || +{ + $as_echo "$as_me: cannot create a temporary directory in ." >&2 + { (exit 1); exit 1; } +} + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=' ' +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } +ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + + if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` = $ac_delim_num; then + break + elif $ac_last_try; then + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\).*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\).*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ + || { { $as_echo "$as_me:$LINENO: error: could not setup config files machinery" >&5 +$as_echo "$as_me: error: could not setup config files machinery" >&2;} + { (exit 1); exit 1; }; } +_ACEOF + +# VPATH may cause trouble with some makes, so we remove $(srcdir), +# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=/{ +s/:*\$(srcdir):*/:/ +s/:*\${srcdir}:*/:/ +s/:*@srcdir@:*/:/ +s/^\([^=]*=[ ]*\):*/\1/ +s/:*$// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_t=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_t"; then + break + elif $ac_last_try; then + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_HEADERS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_HEADERS" >&2;} + { (exit 1); exit 1; }; } + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + prefix = substr(line, 1, index(line, defundef) - 1) + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", line, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + { { $as_echo "$as_me:$LINENO: error: could not setup config headers machinery" >&5 +$as_echo "$as_me: error: could not setup config headers machinery" >&2;} + { (exit 1); exit 1; }; } +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) { { $as_echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5 +$as_echo "$as_me: error: Invalid tag $ac_tag." >&2;} + { (exit 1); exit 1; }; };; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + { { $as_echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 +$as_echo "$as_me: error: cannot find input file: $ac_f" >&2;} + { (exit 1); exit 1; }; };; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + ac_file_inputs="$ac_file_inputs '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:$LINENO: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$tmp/stdin" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + { as_dir="$ac_dir" + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || { { $as_echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 +$as_echo "$as_me: error: cannot create directory $as_dir" >&2;} + { (exit 1); exit 1; }; }; } + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + + case $INSTALL in + [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; + *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; + esac +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= + +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p +' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +s&@INSTALL@&$ac_INSTALL&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&2;} + + rm -f "$tmp/stdin" + case $ac_file in + -) cat "$tmp/out" && rm -f "$tmp/out";; + *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; + esac \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" + } >"$tmp/config.h" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:$LINENO: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$tmp/config.h" "$ac_file" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + fi + else + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ + || { { $as_echo "$as_me:$LINENO: error: could not create -" >&5 +$as_echo "$as_me: error: could not create -" >&2;} + { (exit 1); exit 1; }; } + fi + ;; + + :C) { $as_echo "$as_me:$LINENO: executing $ac_file commands" >&5 +$as_echo "$as_me: executing $ac_file commands" >&6;} + ;; + esac + + + case $ac_file$ac_mode in + "libtool":C) + + # See if we are running on zsh, and set the options which allow our + # commands through without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + + cfgfile="${ofile}T" + trap "$RM \"$cfgfile\"; exit 1" 1 2 15 + $RM "$cfgfile" + + cat <<_LT_EOF >> "$cfgfile" +#! $SHELL + +# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. +# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: +# NOTE: Changes made to this file will be lost: look at ltmain.sh. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, +# 2006, 2007, 2008 Free Software Foundation, Inc. +# Written by Gordon Matzigkeit, 1996 +# +# This file is part of GNU Libtool. +# +# GNU Libtool is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of +# the License, or (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Libtool; see the file COPYING. If not, a copy +# can be downloaded from http://www.gnu.org/licenses/gpl.html, or +# obtained by writing to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + +# The names of the tagged configurations supported by this script. +available_tags="" + +# ### BEGIN LIBTOOL CONFIG + +# Which release of libtool.m4 was used? +macro_version=$macro_version +macro_revision=$macro_revision + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# What type of objects to build. +pic_mode=$pic_mode + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# A sed program that does not truncate output. +SED=$lt_SED + +# Sed that helps us avoid accidentally triggering echo(1) options like -n. +Xsed="\$SED -e 1s/^X//" + +# A grep program that handles long lines. +GREP=$lt_GREP + +# An ERE matcher. +EGREP=$lt_EGREP + +# A literal string matcher. +FGREP=$lt_FGREP + +# A BSD- or MS-compatible name lister. +NM=$lt_NM + +# Whether we need soft or hard links. +LN_S=$lt_LN_S + +# What is the maximum length of a command? +max_cmd_len=$max_cmd_len + +# Object file suffix (normally "o"). +objext=$ac_objext + +# Executable file suffix (normally ""). +exeext=$exeext + +# whether the shell understands "unset". +lt_unset=$lt_unset + +# turn spaces into newlines. +SP2NL=$lt_lt_SP2NL + +# turn newlines into spaces. +NL2SP=$lt_lt_NL2SP + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# An object symbol dumper. +OBJDUMP=$lt_OBJDUMP + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == "file_magic". +file_magic_cmd=$lt_file_magic_cmd + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A symbol stripping program. +STRIP=$lt_STRIP + +# Commands used to install an old-style archive. +RANLIB=$lt_RANLIB +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# A C compiler. +LTCC=$lt_CC + +# LTCC compiler flags. +LTCFLAGS=$lt_CFLAGS + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration. +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair. +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# Transform the output of nm in a C name address pair when lib prefix is needed. +global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# An echo program that does not interpret backslashes. +ECHO=$lt_ECHO + +# Used to examine libraries when file_magic_cmd begins with "file". +MAGIC_CMD=$MAGIC_CMD + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Tool to manipulate archived DWARF debug symbol files on Mac OS X. +DSYMUTIL=$lt_DSYMUTIL + +# Tool to change global to local symbols on Mac OS X. +NMEDIT=$lt_NMEDIT + +# Tool to manipulate fat objects and archives on Mac OS X. +LIPO=$lt_LIPO + +# ldd/readelf like tool for Mach-O binaries on Mac OS X. +OTOOL=$lt_OTOOL + +# ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. +OTOOL64=$lt_OTOOL64 + +# Old archive suffix (normally "a"). +libext=$libext + +# Shared library suffix (normally ".so"). +shrext_cmds=$lt_shrext_cmds + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at link time. +variables_saved_for_relink=$lt_variables_saved_for_relink + +# Do we need the "lib" prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Library versioning type. +version_type=$version_type + +# Shared library runtime path variable. +runpath_var=$runpath_var + +# Shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Command to use after installation of a shared archive. +postinstall_cmds=$lt_postinstall_cmds + +# Command to use after uninstallation of a shared archive. +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# As "finish_cmds", except a single script fragment to be evaled but +# not shown. +finish_eval=$lt_finish_eval + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Compile-time system search path for libraries. +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries. +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + + +# The linker used to build libraries. +LD=$lt_LD + +# Commands used to build an old-style archive. +old_archive_cmds=$lt_old_archive_cmds + +# A language specific compiler. +CC=$lt_compiler + +# Is the compiler the GNU compiler? +with_gcc=$GCC + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc + +# Whether or not to disallow shared libs when runtime libs are static. +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec + +# Whether the compiler copes with passing no objects directly. +compiler_needs_object=$lt_compiler_needs_object + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds + +# Commands used to build a shared archive. +archive_cmds=$lt_archive_cmds +archive_expsym_cmds=$lt_archive_expsym_cmds + +# Commands used to build a loadable module if different from building +# a shared archive. +module_cmds=$lt_module_cmds +module_expsym_cmds=$lt_module_expsym_cmds + +# Whether we are building with GNU ld or not. +with_gnu_ld=$lt_with_gnu_ld + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag + +# Flag that enforces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec + +# If ld is used when linking, flag to hardcode \$libdir into a binary +# during linking. This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld + +# Whether we need a single "-rpath" flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator + +# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes +# DIR into the resulting binary. +hardcode_direct=$hardcode_direct + +# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes +# DIR into the resulting binary and the resulting library dependency is +# "absolute",i.e impossible to change by setting \${shlibpath_var} if the +# library is relocated. +hardcode_direct_absolute=$hardcode_direct_absolute + +# Set to "yes" if using the -LDIR flag during linking hardcodes DIR +# into the resulting binary. +hardcode_minus_L=$hardcode_minus_L + +# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR +# into the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var + +# Set to "yes" if building a shared library automatically hardcodes DIR +# into the library and all subsequent libraries and executables linked +# against it. +hardcode_automatic=$hardcode_automatic + +# Set to yes if linker adds runtime paths of dependent libraries +# to runtime path list. +inherit_rpath=$inherit_rpath + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path=$lt_fix_srcfile_path + +# Set to "yes" if exported symbols are required. +always_export_symbols=$always_export_symbols + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms + +# Commands necessary for linking programs (against libraries) with templates. +prelink_cmds=$lt_prelink_cmds + +# Specify filename containing input files. +file_list_spec=$lt_file_list_spec + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action + +# ### END LIBTOOL CONFIG + +_LT_EOF + + case $host_os in + aix3*) + cat <<\_LT_EOF >> "$cfgfile" +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +_LT_EOF + ;; + esac + + +ltmain="$ac_aux_dir/ltmain.sh" + + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + sed '/^# Generated shell functions inserted here/q' "$ltmain" >> "$cfgfile" \ + || (rm -f "$cfgfile"; exit 1) + + case $xsi_shell in + yes) + cat << \_LT_EOF >> "$cfgfile" + +# func_dirname file append nondir_replacement +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +func_dirname () +{ + case ${1} in + */*) func_dirname_result="${1%/*}${2}" ;; + * ) func_dirname_result="${3}" ;; + esac +} + +# func_basename file +func_basename () +{ + func_basename_result="${1##*/}" +} + +# func_dirname_and_basename file append nondir_replacement +# perform func_basename and func_dirname in a single function +# call: +# dirname: Compute the dirname of FILE. If nonempty, +# add APPEND to the result, otherwise set result +# to NONDIR_REPLACEMENT. +# value returned in "$func_dirname_result" +# basename: Compute filename of FILE. +# value retuned in "$func_basename_result" +# Implementation must be kept synchronized with func_dirname +# and func_basename. For efficiency, we do not delegate to +# those functions but instead duplicate the functionality here. +func_dirname_and_basename () +{ + case ${1} in + */*) func_dirname_result="${1%/*}${2}" ;; + * ) func_dirname_result="${3}" ;; + esac + func_basename_result="${1##*/}" +} + +# func_stripname prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +func_stripname () +{ + # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are + # positional parameters, so assign one to ordinary parameter first. + func_stripname_result=${3} + func_stripname_result=${func_stripname_result#"${1}"} + func_stripname_result=${func_stripname_result%"${2}"} +} + +# func_opt_split +func_opt_split () +{ + func_opt_split_opt=${1%%=*} + func_opt_split_arg=${1#*=} +} + +# func_lo2o object +func_lo2o () +{ + case ${1} in + *.lo) func_lo2o_result=${1%.lo}.${objext} ;; + *) func_lo2o_result=${1} ;; + esac +} + +# func_xform libobj-or-source +func_xform () +{ + func_xform_result=${1%.*}.lo +} + +# func_arith arithmetic-term... +func_arith () +{ + func_arith_result=$(( $* )) +} + +# func_len string +# STRING may not start with a hyphen. +func_len () +{ + func_len_result=${#1} +} + +_LT_EOF + ;; + *) # Bourne compatible functions. + cat << \_LT_EOF >> "$cfgfile" + +# func_dirname file append nondir_replacement +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +func_dirname () +{ + # Extract subdirectory from the argument. + func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` + if test "X$func_dirname_result" = "X${1}"; then + func_dirname_result="${3}" + else + func_dirname_result="$func_dirname_result${2}" + fi +} + +# func_basename file +func_basename () +{ + func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` +} + + +# func_stripname prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +# func_strip_suffix prefix name +func_stripname () +{ + case ${2} in + .*) func_stripname_result=`$ECHO "X${3}" \ + | $Xsed -e "s%^${1}%%" -e "s%\\\\${2}\$%%"`;; + *) func_stripname_result=`$ECHO "X${3}" \ + | $Xsed -e "s%^${1}%%" -e "s%${2}\$%%"`;; + esac +} + +# sed scripts: +my_sed_long_opt='1s/^\(-[^=]*\)=.*/\1/;q' +my_sed_long_arg='1s/^-[^=]*=//' + +# func_opt_split +func_opt_split () +{ + func_opt_split_opt=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_opt"` + func_opt_split_arg=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_arg"` +} + +# func_lo2o object +func_lo2o () +{ + func_lo2o_result=`$ECHO "X${1}" | $Xsed -e "$lo2o"` +} + +# func_xform libobj-or-source +func_xform () +{ + func_xform_result=`$ECHO "X${1}" | $Xsed -e 's/\.[^.]*$/.lo/'` +} + +# func_arith arithmetic-term... +func_arith () +{ + func_arith_result=`expr "$@"` +} + +# func_len string +# STRING may not start with a hyphen. +func_len () +{ + func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len` +} + +_LT_EOF +esac + +case $lt_shell_append in + yes) + cat << \_LT_EOF >> "$cfgfile" + +# func_append var value +# Append VALUE to the end of shell variable VAR. +func_append () +{ + eval "$1+=\$2" +} +_LT_EOF + ;; + *) + cat << \_LT_EOF >> "$cfgfile" + +# func_append var value +# Append VALUE to the end of shell variable VAR. +func_append () +{ + eval "$1=\$$1\$2" +} + +_LT_EOF + ;; + esac + + + sed -n '/^# Generated shell functions inserted here/,$p' "$ltmain" >> "$cfgfile" \ + || (rm -f "$cfgfile"; exit 1) + + mv -f "$cfgfile" "$ofile" || + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" + + ;; + + esac +done # for ac_tag + + +{ (exit 0); exit 0; } +_ACEOF +chmod +x $CONFIG_STATUS +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + { { $as_echo "$as_me:$LINENO: error: write failure creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: write failure creating $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || { (exit 1); exit 1; } +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:$LINENO: WARNING: Unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: Unrecognized options: $ac_unrecognized_opts" >&2;} +fi + diff --git a/components/external/SQLite-3.8.1/configure.ac b/components/external/SQLite-3.8.1/configure.ac new file mode 100644 index 0000000000000000000000000000000000000000..2e70f2c235600ded1cd487ef1341e6fd674babc7 --- /dev/null +++ b/components/external/SQLite-3.8.1/configure.ac @@ -0,0 +1,693 @@ +# +# The build process allows for using a cross-compiler. But the default +# action is to target the same platform that we are running on. The +# configure script needs to discover the following properties of the +# build and target systems: +# +# srcdir +# +# The is the name of the directory that contains the +# "configure" shell script. All source files are +# located relative to this directory. +# +# bindir +# +# The name of the directory where executables should be +# written by the "install" target of the makefile. +# +# program_prefix +# +# Add this prefix to the names of all executables that run +# on the target machine. Default: "" +# +# ENABLE_SHARED +# +# True if shared libraries should be generated. +# +# BUILD_CC +# +# The name of a command that is used to convert C +# source files into executables that run on the build +# platform. +# +# BUILD_CFLAGS +# +# Switches that the build compiler needs in order to construct +# command-line programs. +# +# BUILD_LIBS +# +# Libraries that the build compiler needs in order to construct +# command-line programs. +# +# BUILD_EXEEXT +# +# The filename extension for executables on the build +# platform. "" for Unix and ".exe" for Windows. +# +# TCL_* +# +# Lots of values are read in from the tclConfig.sh script, +# if that script is available. This values are used for +# constructing and installing the TCL extension. +# +# TARGET_READLINE_LIBS +# +# This is the library directives passed to the target linker +# that cause the executable to link against the readline library. +# This might be a switch like "-lreadline" or pathnames of library +# file like "../../src/libreadline.a". +# +# TARGET_READLINE_INC +# +# This variables define the directory that contain header +# files for the readline library. If the compiler is able +# to find on its own, then this can be blank. +# +# TARGET_EXEEXT +# +# The filename extension for executables on the +# target platform. "" for Unix and ".exe" for windows. +# +# The generated configure script will make an attempt to guess +# at all of the above parameters. You can override any of +# the guesses by setting the environment variable named +# "config_AAAA" where "AAAA" is the name of the parameter +# described above. (Exception: srcdir cannot be set this way.) +# If you have a file that sets one or more of these environment +# variables, you can invoke configure as follows: +# +# configure --with-hints=FILE +# +# where FILE is the name of the file that sets the environment +# variables. FILE should be an absolute pathname. +# +# This configure.in file is easy to reuse on other projects. Just +# change the argument to AC_INIT(). And disable any features that +# you don't need (for example BLT) by erasing or commenting out +# the corresponding code. +# +AC_INIT(sqlite, m4_esyscmd([cat VERSION | tr -d '\n'])) + +dnl Make sure the local VERSION file matches this configure script +sqlite_version_sanity_check=`cat $srcdir/VERSION | tr -d '\n'` +if test "$PACKAGE_VERSION" != "$sqlite_version_sanity_check" ; then +AC_MSG_ERROR([configure script is out of date: + configure \$PACKAGE_VERSION = $PACKAGE_VERSION + top level VERSION file = $sqlite_version_sanity_check +please regen with autoconf]) +fi + +dnl Put the RCS revision string after AC_INIT so that it will also +dnl show in in configure. +# The following RCS revision string applies to configure.in +# $Revision: 1.56 $ + +######### +# Programs needed +# +AC_PROG_LIBTOOL +AC_PROG_INSTALL +AC_PROG_AWK + +######### +# Enable large file support (if special flags are necessary) +# +AC_SYS_LARGEFILE + +######### +# Check for needed/wanted data types +AC_CHECK_TYPES([int8_t, int16_t, int32_t, int64_t, intptr_t, uint8_t, + uint16_t, uint32_t, uint64_t, uintptr_t]) + +######### +# Check for needed/wanted headers +AC_CHECK_HEADERS([sys/types.h stdlib.h stdint.h inttypes.h malloc.h]) + +######### +# Figure out whether or not we have these functions +# +AC_CHECK_FUNCS([usleep fdatasync localtime_r gmtime_r localtime_s utime malloc_usable_size]) + +######### +# By default, we use the amalgamation (this may be changed below...) +# +USE_AMALGAMATION=1 + +######### +# See whether we can run specific tclsh versions known to work well; +# if not, then we fall back to plain tclsh. +# TODO: try other versions before falling back? +# +AC_CHECK_PROGS(TCLSH_CMD, [tclsh8.6 tclsh8.5 tclsh], none) +if test "$TCLSH_CMD" = "none"; then + # If we can't find a local tclsh, then building the amalgamation will fail. + # We act as though --disable-amalgamation has been used. + echo "Warning: can't find tclsh - defaulting to non-amalgamation build." + USE_AMALGAMATION=0 + TCLSH_CMD="tclsh" +fi +AC_SUBST(TCLSH_CMD) + +AC_ARG_VAR([TCLLIBDIR], [Where to install tcl plugin]) +if test "x${TCLLIBDIR+set}" != "xset" ; then + TCLLIBDIR='$(libdir)' + for i in `echo 'puts stdout $auto_path' | ${TCLSH_CMD}` ; do + TCLLIBDIR=$i + break + done + TCLLIBDIR="${TCLLIBDIR}/sqlite3" +fi + + +######### +# Set up an appropriate program prefix +# +if test "$program_prefix" = "NONE"; then + program_prefix="" +fi +AC_SUBST(program_prefix) + +VERSION=[`cat $srcdir/VERSION | sed 's/^\([0-9]*\.*[0-9]*\).*/\1/'`] +AC_MSG_NOTICE(Version set to $VERSION) +AC_SUBST(VERSION) +RELEASE=`cat $srcdir/VERSION` +AC_MSG_NOTICE(Release set to $RELEASE) +AC_SUBST(RELEASE) +VERSION_NUMBER=[`cat $srcdir/VERSION \ + | sed 's/[^0-9]/ /g' \ + | awk '{printf "%d%03d%03d",$1,$2,$3}'`] +AC_MSG_NOTICE(Version number set to $VERSION_NUMBER) +AC_SUBST(VERSION_NUMBER) + +######### +# Check to see if the --with-hints=FILE option is used. If there is none, +# then check for a files named "$host.hints" and ../$hosts.hints where +# $host is the hostname of the build system. If still no hints are +# found, try looking in $system.hints and ../$system.hints where +# $system is the result of uname -s. +# +AC_ARG_WITH(hints, + AC_HELP_STRING([--with-hints=FILE],[Read configuration options from FILE]), + hints=$withval) +if test "$hints" = ""; then + host=`hostname | sed 's/\..*//'` + if test -r $host.hints; then + hints=$host.hints + else + if test -r ../$host.hints; then + hints=../$host.hints + fi + fi +fi +if test "$hints" = ""; then + sys=`uname -s` + if test -r $sys.hints; then + hints=$sys.hints + else + if test -r ../$sys.hints; then + hints=../$sys.hints + fi + fi +fi +if test "$hints" != ""; then + AC_MSG_RESULT(reading hints from $hints) + . $hints +fi + +######### +# Locate a compiler for the build machine. This compiler should +# generate command-line programs that run on the build machine. +# +if test x"$cross_compiling" = xno; then + BUILD_CC=$CC + BUILD_CFLAGS=$CFLAGS +else + if test "${BUILD_CC+set}" != set; then + AC_CHECK_PROGS(BUILD_CC, gcc cc cl) + fi + if test "${BUILD_CFLAGS+set}" != set; then + BUILD_CFLAGS="-g" + fi +fi +AC_SUBST(BUILD_CC) + +########## +# Do we want to support multithreaded use of sqlite +# +AC_ARG_ENABLE(threadsafe, +AC_HELP_STRING([--enable-threadsafe],[Support threadsafe operation]),,enable_threadsafe=yes) +AC_MSG_CHECKING([whether to support threadsafe operation]) +if test "$enable_threadsafe" = "no"; then + SQLITE_THREADSAFE=0 + AC_MSG_RESULT([no]) +else + SQLITE_THREADSAFE=1 + AC_MSG_RESULT([yes]) +fi +AC_SUBST(SQLITE_THREADSAFE) + +if test "$SQLITE_THREADSAFE" = "1"; then + AC_SEARCH_LIBS(pthread_create, pthread) +fi + +########## +# Do we want to allow a connection created in one thread to be used +# in another thread. This does not work on many Linux systems (ex: RedHat 9) +# due to bugs in the threading implementations. This is thus off by default. +# +AC_ARG_ENABLE(cross-thread-connections, +AC_HELP_STRING([--enable-cross-thread-connections],[Allow connection sharing across threads]),,enable_xthreadconnect=no) +AC_MSG_CHECKING([whether to allow connections to be shared across threads]) +if test "$enable_xthreadconnect" = "no"; then + XTHREADCONNECT='' + AC_MSG_RESULT([no]) +else + XTHREADCONNECT='-DSQLITE_ALLOW_XTHREAD_CONNECT=1' + AC_MSG_RESULT([yes]) +fi +AC_SUBST(XTHREADCONNECT) + +########## +# Do we want to support release +# +AC_ARG_ENABLE(releasemode, +AC_HELP_STRING([--enable-releasemode],[Support libtool link to release mode]),,enable_releasemode=no) +AC_MSG_CHECKING([whether to support shared library linked as release mode or not]) +if test "$enable_releasemode" = "no"; then + ALLOWRELEASE="" + AC_MSG_RESULT([no]) +else + ALLOWRELEASE="-release `cat $srcdir/VERSION`" + AC_MSG_RESULT([yes]) +fi +AC_SUBST(ALLOWRELEASE) + +########## +# Do we want temporary databases in memory +# +AC_ARG_ENABLE(tempstore, +AC_HELP_STRING([--enable-tempstore],[Use an in-ram database for temporary tables (never,no,yes,always)]),,enable_tempstore=no) +AC_MSG_CHECKING([whether to use an in-ram database for temporary tables]) +case "$enable_tempstore" in + never ) + TEMP_STORE=0 + AC_MSG_RESULT([never]) + ;; + no ) + TEMP_STORE=1 + AC_MSG_RESULT([no]) + ;; + yes ) + TEMP_STORE=2 + AC_MSG_RESULT([yes]) + ;; + always ) + TEMP_STORE=3 + AC_MSG_RESULT([always]) + ;; + * ) + TEMP_STORE=1 + AC_MSG_RESULT([no]) + ;; +esac + +AC_SUBST(TEMP_STORE) + +########### +# Lots of things are different if we are compiling for Windows using +# the CYGWIN environment. So check for that special case and handle +# things accordingly. +# +AC_MSG_CHECKING([if executables have the .exe suffix]) +if test "$config_BUILD_EXEEXT" = ".exe"; then + CYGWIN=yes + AC_MSG_RESULT(yes) +else + AC_MSG_RESULT(unknown) +fi +if test "$CYGWIN" != "yes"; then + AC_CYGWIN +fi +if test "$CYGWIN" = "yes"; then + BUILD_EXEEXT=.exe +else + BUILD_EXEEXT=$EXEEXT +fi +if test x"$cross_compiling" = xno; then + TARGET_EXEEXT=$BUILD_EXEEXT +else + TARGET_EXEEXT=$config_TARGET_EXEEXT +fi +if test "$TARGET_EXEEXT" = ".exe"; then + SQLITE_OS_UNIX=0 + SQLITE_OS_WIN=1 + CFLAGS="$CFLAGS -DSQLITE_OS_WIN=1" +else + SQLITE_OS_UNIX=1 + SQLITE_OS_WIN=0 + CFLAGS="$CFLAGS -DSQLITE_OS_UNIX=1" +fi + +AC_SUBST(BUILD_EXEEXT) +AC_SUBST(SQLITE_OS_UNIX) +AC_SUBST(SQLITE_OS_WIN) +AC_SUBST(TARGET_EXEEXT) + +########## +# Figure out all the parameters needed to compile against Tcl. +# +# This code is derived from the SC_PATH_TCLCONFIG and SC_LOAD_TCLCONFIG +# macros in the in the tcl.m4 file of the standard TCL distribution. +# Those macros could not be used directly since we have to make some +# minor changes to accomodate systems that do not have TCL installed. +# +AC_ARG_ENABLE(tcl, AC_HELP_STRING([--disable-tcl],[do not build TCL extension]), + [use_tcl=$enableval],[use_tcl=yes]) +if test "${use_tcl}" = "yes" ; then + AC_ARG_WITH(tcl, AC_HELP_STRING([--with-tcl=DIR],[directory containing tcl configuration (tclConfig.sh)]), with_tclconfig=${withval}) + AC_MSG_CHECKING([for Tcl configuration]) + AC_CACHE_VAL(ac_cv_c_tclconfig,[ + # First check to see if --with-tcl was specified. + if test x"${with_tclconfig}" != x ; then + if test -f "${with_tclconfig}/tclConfig.sh" ; then + ac_cv_c_tclconfig=`(cd ${with_tclconfig}; pwd)` + else + AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh]) + fi + fi + + # Start autosearch by asking tclsh + if test x"${ac_cv_c_tclconfig}" = x ; then + if test x"$cross_compiling" = xno; then + for i in `echo 'puts stdout $auto_path' | ${TCLSH_CMD}` + do + if test -f "$i/tclConfig.sh" ; then + ac_cv_c_tclconfig="$i" + break + fi + done + fi + fi + + # then check for a private Tcl installation + if test x"${ac_cv_c_tclconfig}" = x ; then + for i in \ + ../tcl \ + `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \ + ../../tcl \ + `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \ + ../../../tcl \ + `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` + do + if test -f "$i/unix/tclConfig.sh" ; then + ac_cv_c_tclconfig=`(cd $i/unix; pwd)` + break + fi + done + fi + + # check in a few common install locations + if test x"${ac_cv_c_tclconfig}" = x ; then + for i in \ + `ls -d ${libdir} 2>/dev/null` \ + `ls -d /usr/local/lib 2>/dev/null` \ + `ls -d /usr/contrib/lib 2>/dev/null` \ + `ls -d /usr/lib 2>/dev/null` + do + if test -f "$i/tclConfig.sh" ; then + ac_cv_c_tclconfig=`(cd $i; pwd)` + break + fi + done + fi + + # check in a few other private locations + if test x"${ac_cv_c_tclconfig}" = x ; then + for i in \ + ${srcdir}/../tcl \ + `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \ + `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \ + `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` + do + if test -f "$i/unix/tclConfig.sh" ; then + ac_cv_c_tclconfig=`(cd $i/unix; pwd)` + break + fi + done + fi + ]) + + if test x"${ac_cv_c_tclconfig}" = x ; then + use_tcl=no + AC_MSG_WARN(Can't find Tcl configuration definitions) + AC_MSG_WARN(*** Without Tcl the regression tests cannot be executed ***) + AC_MSG_WARN(*** Consider using --with-tcl=... to define location of Tcl ***) + else + TCL_BIN_DIR=${ac_cv_c_tclconfig} + AC_MSG_RESULT(found $TCL_BIN_DIR/tclConfig.sh) + + AC_MSG_CHECKING([for existence of $TCL_BIN_DIR/tclConfig.sh]) + if test -f "$TCL_BIN_DIR/tclConfig.sh" ; then + AC_MSG_RESULT([loading]) + . $TCL_BIN_DIR/tclConfig.sh + else + AC_MSG_RESULT([file not found]) + fi + + # + # If the TCL_BIN_DIR is the build directory (not the install directory), + # then set the common variable name to the value of the build variables. + # For example, the variable TCL_LIB_SPEC will be set to the value + # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC + # instead of TCL_BUILD_LIB_SPEC since it will work with both an + # installed and uninstalled version of Tcl. + # + + if test -f $TCL_BIN_DIR/Makefile ; then + TCL_LIB_SPEC=${TCL_BUILD_LIB_SPEC} + TCL_STUB_LIB_SPEC=${TCL_BUILD_STUB_LIB_SPEC} + TCL_STUB_LIB_PATH=${TCL_BUILD_STUB_LIB_PATH} + fi + + # + # eval is required to do the TCL_DBGX substitution + # + + eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\"" + eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\"" + eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\"" + + eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\"" + eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\"" + eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\"" + + AC_SUBST(TCL_VERSION) + AC_SUBST(TCL_BIN_DIR) + AC_SUBST(TCL_SRC_DIR) + AC_SUBST(TCL_INCLUDE_SPEC) + + AC_SUBST(TCL_LIB_FILE) + AC_SUBST(TCL_LIB_FLAG) + AC_SUBST(TCL_LIB_SPEC) + + AC_SUBST(TCL_STUB_LIB_FILE) + AC_SUBST(TCL_STUB_LIB_FLAG) + AC_SUBST(TCL_STUB_LIB_SPEC) + fi +fi +if test "${use_tcl}" = "no" ; then + HAVE_TCL="" +else + HAVE_TCL=1 +fi +AC_SUBST(HAVE_TCL) + +########## +# Figure out what C libraries are required to compile programs +# that use "readline()" library. +# +TARGET_READLINE_LIBS="" +TARGET_READLINE_INC="" +TARGET_HAVE_READLINE=0 +AC_ARG_ENABLE([readline], + [AC_HELP_STRING([--disable-readline],[disable readline support [default=detect]])], + [with_readline=$enableval], + [with_readline=auto]) + +if test x"$with_readline" != xno; then + found="yes" + + AC_ARG_WITH([readline-lib], + [AC_HELP_STRING([--with-readline-lib],[specify readline library])], + [with_readline_lib=$withval], + [with_readline_lib="auto"]) + if test "x$with_readline_lib" = xauto; then + save_LIBS="$LIBS" + LIBS="" + AC_SEARCH_LIBS(tgetent, [readline ncurses curses termcap], [term_LIBS="$LIBS"], [term_LIBS=""]) + AC_CHECK_LIB([readline], [readline], [TARGET_READLINE_LIBS="-lreadline"], [found="no"]) + TARGET_READLINE_LIBS="$TARGET_READLINE_LIBS $term_LIBS" + LIBS="$save_LIBS" + else + TARGET_READLINE_LIBS="$with_readline_lib" + fi + + AC_ARG_WITH([readline-inc], + [AC_HELP_STRING([--with-readline-inc],[specify readline include paths])], + [with_readline_inc=$withval], + [with_readline_inc="auto"]) + if test "x$with_readline_inc" = xauto; then + AC_CHECK_HEADER(readline.h, [found="yes"], [ + found="no" + if test "$cross_compiling" != yes; then + for dir in /usr /usr/local /usr/local/readline /usr/contrib /mingw; do + for subdir in include include/readline; do + AC_CHECK_FILE($dir/$subdir/readline.h, found=yes) + if test "$found" = "yes"; then + TARGET_READLINE_INC="-I$dir/$subdir" + break + fi + done + test "$found" = "yes" && break + done + fi + ]) + else + TARGET_READLINE_INC="$with_readline_inc" + fi + + if test x"$found" = xno; then + TARGET_READLINE_LIBS="" + TARGET_READLINE_INC="" + TARGET_HAVE_READLINE=0 + else + TARGET_HAVE_READLINE=1 + fi +fi + +AC_SUBST(TARGET_READLINE_LIBS) +AC_SUBST(TARGET_READLINE_INC) +AC_SUBST(TARGET_HAVE_READLINE) + +########## +# Figure out what C libraries are required to compile programs +# that use "fdatasync()" function. +# +AC_SEARCH_LIBS(fdatasync, [rt]) + +######### +# check for debug enabled +AC_ARG_ENABLE(debug, AC_HELP_STRING([--enable-debug],[enable debugging & verbose explain]), + [use_debug=$enableval],[use_debug=no]) +if test "${use_debug}" = "yes" ; then + TARGET_DEBUG="-DSQLITE_DEBUG=1" +else + TARGET_DEBUG="-DNDEBUG" +fi +AC_SUBST(TARGET_DEBUG) + +######### +# See whether we should use the amalgamation to build +AC_ARG_ENABLE(amalgamation, AC_HELP_STRING([--disable-amalgamation], + [Disable the amalgamation and instead build all files separately]), + [use_amalgamation=$enableval],[use_amalgamation=yes]) +if test "${use_amalgamation}" != "yes" ; then + USE_AMALGAMATION=0 +fi +AC_SUBST(USE_AMALGAMATION) + +######### +# See whether we should allow loadable extensions +AC_ARG_ENABLE(load-extension, AC_HELP_STRING([--enable-load-extension], + [Enable loading of external extensions]), + [use_loadextension=$enableval],[use_loadextension=no]) +if test "${use_loadextension}" = "yes" ; then + OPT_FEATURE_FLAGS="" + AC_SEARCH_LIBS(dlopen, dl) +else + OPT_FEATURE_FLAGS="-DSQLITE_OMIT_LOAD_EXTENSION=1" +fi + +######### +# attempt to duplicate any OMITS and ENABLES into the $(OPT_FEATURE_FLAGS) parameter +for option in $CFLAGS $CPPFLAGS +do + case $option in + -DSQLITE_OMIT*) OPT_FEATURE_FLAGS="$OPT_FEATURE_FLAGS $option";; + -DSQLITE_ENABLE*) OPT_FEATURE_FLAGS="$OPT_FEATURE_FLAGS $option";; + esac +done +AC_SUBST(OPT_FEATURE_FLAGS) + + +# attempt to remove any OMITS and ENABLES from the $(CFLAGS) parameter +ac_temp_CFLAGS="" +for option in $CFLAGS +do + case $option in + -DSQLITE_OMIT*) ;; + -DSQLITE_ENABLE*) ;; + *) ac_temp_CFLAGS="$ac_temp_CFLAGS $option";; + esac +done +CFLAGS=$ac_temp_CFLAGS + + +# attempt to remove any OMITS and ENABLES from the $(CPPFLAGS) parameter +ac_temp_CPPFLAGS="" +for option in $CPPFLAGS +do + case $option in + -DSQLITE_OMIT*) ;; + -DSQLITE_ENABLE*) ;; + *) ac_temp_CPPFLAGS="$ac_temp_CPPFLAGS $option";; + esac +done +CPPFLAGS=$ac_temp_CPPFLAGS + + +# attempt to remove any OMITS and ENABLES from the $(BUILD_CFLAGS) parameter +ac_temp_BUILD_CFLAGS="" +for option in $BUILD_CFLAGS +do + case $option in + -DSQLITE_OMIT*) ;; + -DSQLITE_ENABLE*) ;; + *) ac_temp_BUILD_CFLAGS="$ac_temp_BUILD_CFLAGS $option";; + esac +done +BUILD_CFLAGS=$ac_temp_BUILD_CFLAGS + + +######### +# See whether we should use GCOV +AC_ARG_ENABLE(gcov, AC_HELP_STRING([--enable-gcov], + [Enable coverage testing using gcov]), + [use_gcov=$enableval],[use_gcov=no]) +if test "${use_gcov}" = "yes" ; then + USE_GCOV=1 +else + USE_GCOV=0 +fi +AC_SUBST(USE_GCOV) + + +######### +# Output the config header +AC_CONFIG_HEADERS(config.h) + +######### +# Generate the output files. +# +AC_SUBST(BUILD_CFLAGS) +AC_OUTPUT([ +Makefile +sqlite3.pc +]) diff --git a/components/external/SQLite-3.8.1/contrib/sqlitecon.tcl b/components/external/SQLite-3.8.1/contrib/sqlitecon.tcl new file mode 100644 index 0000000000000000000000000000000000000000..b5dbcafc2a5a2a11caef7002391fb66bda47fff8 --- /dev/null +++ b/components/external/SQLite-3.8.1/contrib/sqlitecon.tcl @@ -0,0 +1,679 @@ +# A Tk console widget for SQLite. Invoke sqlitecon::create with a window name, +# a prompt string, a title to set a new top-level window, and the SQLite +# database handle. For example: +# +# sqlitecon::create .sqlcon {sql:- } {SQL Console} db +# +# A toplevel window is created that allows you to type in SQL commands to +# be processed on the spot. +# +# A limited set of dot-commands are supported: +# +# .table +# .schema ?TABLE? +# .mode list|column|multicolumn|line +# .exit +# +# In addition, a new SQL function named "edit()" is created. This function +# takes a single text argument and returns a text result. Whenever the +# the function is called, it pops up a new toplevel window containing a +# text editor screen initialized to the argument. When the "OK" button +# is pressed, whatever revised text is in the text editor is returned as +# the result of the edit() function. This allows text fields of SQL tables +# to be edited quickly and easily as follows: +# +# UPDATE table1 SET dscr = edit(dscr) WHERE rowid=15; +# + + +# Create a namespace to work in +# +namespace eval ::sqlitecon { + # do nothing +} + +# Create a console widget named $w. The prompt string is $prompt. +# The title at the top of the window is $title. The database connection +# object is $db +# +proc sqlitecon::create {w prompt title db} { + upvar #0 $w.t v + if {[winfo exists $w]} {destroy $w} + if {[info exists v]} {unset v} + toplevel $w + wm title $w $title + wm iconname $w $title + frame $w.mb -bd 2 -relief raised + pack $w.mb -side top -fill x + menubutton $w.mb.file -text File -menu $w.mb.file.m + menubutton $w.mb.edit -text Edit -menu $w.mb.edit.m + pack $w.mb.file $w.mb.edit -side left -padx 8 -pady 1 + set m [menu $w.mb.file.m -tearoff 0] + $m add command -label {Close} -command "destroy $w" + sqlitecon::create_child $w $prompt $w.mb.edit.m + set v(db) $db + $db function edit ::sqlitecon::_edit +} + +# This routine creates a console as a child window within a larger +# window. It also creates an edit menu named "$editmenu" if $editmenu!="". +# The calling function is responsible for posting the edit menu. +# +proc sqlitecon::create_child {w prompt editmenu} { + upvar #0 $w.t v + if {$editmenu!=""} { + set m [menu $editmenu -tearoff 0] + $m add command -label Cut -command "sqlitecon::Cut $w.t" + $m add command -label Copy -command "sqlitecon::Copy $w.t" + $m add command -label Paste -command "sqlitecon::Paste $w.t" + $m add command -label {Clear Screen} -command "sqlitecon::Clear $w.t" + $m add separator + $m add command -label {Save As...} -command "sqlitecon::SaveFile $w.t" + catch {$editmenu config -postcommand "sqlitecon::EnableEditMenu $w"} + } + scrollbar $w.sb -orient vertical -command "$w.t yview" + pack $w.sb -side right -fill y + text $w.t -font fixed -yscrollcommand "$w.sb set" + pack $w.t -side right -fill both -expand 1 + bindtags $w.t Sqlitecon + set v(editmenu) $editmenu + set v(history) 0 + set v(historycnt) 0 + set v(current) -1 + set v(prompt) $prompt + set v(prior) {} + set v(plength) [string length $v(prompt)] + set v(x) 0 + set v(y) 0 + set v(mode) column + set v(header) on + $w.t mark set insert end + $w.t tag config ok -foreground blue + $w.t tag config err -foreground red + $w.t insert end $v(prompt) + $w.t mark set out 1.0 + after idle "focus $w.t" +} + +bind Sqlitecon <1> {sqlitecon::Button1 %W %x %y} +bind Sqlitecon {sqlitecon::B1Motion %W %x %y} +bind Sqlitecon {sqlitecon::B1Leave %W %x %y} +bind Sqlitecon {sqlitecon::cancelMotor %W} +bind Sqlitecon {sqlitecon::cancelMotor %W} +bind Sqlitecon {sqlitecon::Insert %W %A} +bind Sqlitecon {sqlitecon::Left %W} +bind Sqlitecon {sqlitecon::Left %W} +bind Sqlitecon {sqlitecon::Right %W} +bind Sqlitecon {sqlitecon::Right %W} +bind Sqlitecon {sqlitecon::Backspace %W} +bind Sqlitecon {sqlitecon::Backspace %W} +bind Sqlitecon {sqlitecon::Delete %W} +bind Sqlitecon {sqlitecon::Delete %W} +bind Sqlitecon {sqlitecon::Home %W} +bind Sqlitecon {sqlitecon::Home %W} +bind Sqlitecon {sqlitecon::End %W} +bind Sqlitecon {sqlitecon::End %W} +bind Sqlitecon {sqlitecon::Enter %W} +bind Sqlitecon {sqlitecon::Enter %W} +bind Sqlitecon {sqlitecon::Prior %W} +bind Sqlitecon {sqlitecon::Prior %W} +bind Sqlitecon {sqlitecon::Next %W} +bind Sqlitecon {sqlitecon::Next %W} +bind Sqlitecon {sqlitecon::EraseEOL %W} +bind Sqlitecon <> {sqlitecon::Cut %W} +bind Sqlitecon <> {sqlitecon::Copy %W} +bind Sqlitecon <> {sqlitecon::Paste %W} +bind Sqlitecon <> {sqlitecon::Clear %W} + +# Insert a single character at the insertion cursor +# +proc sqlitecon::Insert {w a} { + $w insert insert $a + $w yview insert +} + +# Move the cursor one character to the left +# +proc sqlitecon::Left {w} { + upvar #0 $w v + scan [$w index insert] %d.%d row col + if {$col>$v(plength)} { + $w mark set insert "insert -1c" + } +} + +# Erase the character to the left of the cursor +# +proc sqlitecon::Backspace {w} { + upvar #0 $w v + scan [$w index insert] %d.%d row col + if {$col>$v(plength)} { + $w delete {insert -1c} + } +} + +# Erase to the end of the line +# +proc sqlitecon::EraseEOL {w} { + upvar #0 $w v + scan [$w index insert] %d.%d row col + if {$col>=$v(plength)} { + $w delete insert {insert lineend} + } +} + +# Move the cursor one character to the right +# +proc sqlitecon::Right {w} { + $w mark set insert "insert +1c" +} + +# Erase the character to the right of the cursor +# +proc sqlitecon::Delete w { + $w delete insert +} + +# Move the cursor to the beginning of the current line +# +proc sqlitecon::Home w { + upvar #0 $w v + scan [$w index insert] %d.%d row col + $w mark set insert $row.$v(plength) +} + +# Move the cursor to the end of the current line +# +proc sqlitecon::End w { + $w mark set insert {insert lineend} +} + +# Add a line to the history +# +proc sqlitecon::addHistory {w line} { + upvar #0 $w v + if {$v(historycnt)>0} { + set last [lindex $v(history) [expr $v(historycnt)-1]] + if {[string compare $last $line]} { + lappend v(history) $line + incr v(historycnt) + } + } else { + set v(history) [list $line] + set v(historycnt) 1 + } + set v(current) $v(historycnt) +} + +# Called when "Enter" is pressed. Do something with the line +# of text that was entered. +# +proc sqlitecon::Enter w { + upvar #0 $w v + scan [$w index insert] %d.%d row col + set start $row.$v(plength) + set line [$w get $start "$start lineend"] + $w insert end \n + $w mark set out end + if {$v(prior)==""} { + set cmd $line + } else { + set cmd $v(prior)\n$line + } + if {[string index $cmd 0]=="." || [$v(db) complete $cmd]} { + regsub -all {\n} [string trim $cmd] { } cmd2 + addHistory $w $cmd2 + set rc [catch {DoCommand $w $cmd} res] + if {![winfo exists $w]} return + if {$rc} { + $w insert end $res\n err + } elseif {[string length $res]>0} { + $w insert end $res\n ok + } + set v(prior) {} + $w insert end $v(prompt) + } else { + set v(prior) $cmd + regsub -all {[^ ]} $v(prompt) . x + $w insert end $x + } + $w mark set insert end + $w mark set out {insert linestart} + $w yview insert +} + +# Execute a single SQL command. Pay special attention to control +# directives that begin with "." +# +# The return value is the text output from the command, properly +# formatted. +# +proc sqlitecon::DoCommand {w cmd} { + upvar #0 $w v + set mode $v(mode) + set header $v(header) + if {[regexp {^(\.[a-z]+)} $cmd all word]} { + if {$word==".mode"} { + regexp {^.[a-z]+ +([a-z]+)} $cmd all v(mode) + return {} + } elseif {$word==".exit"} { + destroy [winfo toplevel $w] + return {} + } elseif {$word==".header"} { + regexp {^.[a-z]+ +([a-z]+)} $cmd all v(header) + return {} + } elseif {$word==".tables"} { + set mode multicolumn + set cmd {SELECT name FROM sqlite_master WHERE type='table' + UNION ALL + SELECT name FROM sqlite_temp_master WHERE type='table'} + $v(db) eval {PRAGMA database_list} { + if {$name!="temp" && $name!="main"} { + append cmd "UNION ALL SELECT name FROM $name.sqlite_master\ + WHERE type='table'" + } + } + append cmd { ORDER BY 1} + } elseif {$word==".fullschema"} { + set pattern % + regexp {^.[a-z]+ +([^ ]+)} $cmd all pattern + set mode list + set header 0 + set cmd "SELECT sql FROM sqlite_master WHERE tbl_name LIKE '$pattern' + AND sql NOT NULL UNION ALL SELECT sql FROM sqlite_temp_master + WHERE tbl_name LIKE '$pattern' AND sql NOT NULL" + $v(db) eval {PRAGMA database_list} { + if {$name!="temp" && $name!="main"} { + append cmd " UNION ALL SELECT sql FROM $name.sqlite_master\ + WHERE tbl_name LIKE '$pattern' AND sql NOT NULL" + } + } + } elseif {$word==".schema"} { + set pattern % + regexp {^.[a-z]+ +([^ ]+)} $cmd all pattern + set mode list + set header 0 + set cmd "SELECT sql FROM sqlite_master WHERE name LIKE '$pattern' + AND sql NOT NULL UNION ALL SELECT sql FROM sqlite_temp_master + WHERE name LIKE '$pattern' AND sql NOT NULL" + $v(db) eval {PRAGMA database_list} { + if {$name!="temp" && $name!="main"} { + append cmd " UNION ALL SELECT sql FROM $name.sqlite_master\ + WHERE name LIKE '$pattern' AND sql NOT NULL" + } + } + } else { + return \ + ".exit\n.mode line|list|column\n.schema ?TABLENAME?\n.tables" + } + } + set res {} + if {$mode=="list"} { + $v(db) eval $cmd x { + set sep {} + foreach col $x(*) { + append res $sep$x($col) + set sep | + } + append res \n + } + if {[info exists x(*)] && $header} { + set sep {} + set hdr {} + foreach col $x(*) { + append hdr $sep$col + set sep | + } + set res $hdr\n$res + } + } elseif {[string range $mode 0 2]=="col"} { + set y {} + $v(db) eval $cmd x { + foreach col $x(*) { + if {![info exists cw($col)] || $cw($col)<[string length $x($col)]} { + set cw($col) [string length $x($col)] + } + lappend y $x($col) + } + } + if {[info exists x(*)] && $header} { + set hdr {} + set ln {} + set dash --------------------------------------------------------------- + append dash ------------------------------------------------------------ + foreach col $x(*) { + if {![info exists cw($col)] || $cw($col)<[string length $col]} { + set cw($col) [string length $col] + } + lappend hdr $col + lappend ln [string range $dash 1 $cw($col)] + } + set y [concat $hdr $ln $y] + } + if {[info exists x(*)]} { + set format {} + set arglist {} + set arglist2 {} + set i 0 + foreach col $x(*) { + lappend arglist x$i + append arglist2 " \$x$i" + incr i + append format " %-$cw($col)s" + } + set format [string trimleft $format]\n + if {[llength $arglist]>0} { + foreach $arglist $y "append res \[format [list $format] $arglist2\]" + } + } + } elseif {$mode=="multicolumn"} { + set y [$v(db) eval $cmd] + set max 0 + foreach e $y { + if {$max<[string length $e]} {set max [string length $e]} + } + set ncol [expr {int(80/($max+2))}] + if {$ncol<1} {set ncol 1} + set nelem [llength $y] + set nrow [expr {($nelem+$ncol-1)/$ncol}] + set format "%-${max}s" + for {set i 0} {$i<$nrow} {incr i} { + set j $i + while 1 { + append res [format $format [lindex $y $j]] + incr j $nrow + if {$j>=$nelem} break + append res { } + } + append res \n + } + } else { + $v(db) eval $cmd x { + foreach col $x(*) {append res "$col = $x($col)\n"} + append res \n + } + } + return [string trimright $res] +} + +# Change the line to the previous line +# +proc sqlitecon::Prior w { + upvar #0 $w v + if {$v(current)<=0} return + incr v(current) -1 + set line [lindex $v(history) $v(current)] + sqlitecon::SetLine $w $line +} + +# Change the line to the next line +# +proc sqlitecon::Next w { + upvar #0 $w v + if {$v(current)>=$v(historycnt)} return + incr v(current) 1 + set line [lindex $v(history) $v(current)] + sqlitecon::SetLine $w $line +} + +# Change the contents of the entry line +# +proc sqlitecon::SetLine {w line} { + upvar #0 $w v + scan [$w index insert] %d.%d row col + set start $row.$v(plength) + $w delete $start end + $w insert end $line + $w mark set insert end + $w yview insert +} + +# Called when the mouse button is pressed at position $x,$y on +# the console widget. +# +proc sqlitecon::Button1 {w x y} { + global tkPriv + upvar #0 $w v + set v(mouseMoved) 0 + set v(pressX) $x + set p [sqlitecon::nearestBoundry $w $x $y] + scan [$w index insert] %d.%d ix iy + scan $p %d.%d px py + if {$px==$ix} { + $w mark set insert $p + } + $w mark set anchor $p + focus $w +} + +# Find the boundry between characters that is nearest +# to $x,$y +# +proc sqlitecon::nearestBoundry {w x y} { + set p [$w index @$x,$y] + set bb [$w bbox $p] + if {![string compare $bb ""]} {return $p} + if {($x-[lindex $bb 0])<([lindex $bb 2]/2)} {return $p} + $w index "$p + 1 char" +} + +# This routine extends the selection to the point specified by $x,$y +# +proc sqlitecon::SelectTo {w x y} { + upvar #0 $w v + set cur [sqlitecon::nearestBoundry $w $x $y] + if {[catch {$w index anchor}]} { + $w mark set anchor $cur + } + set anchor [$w index anchor] + if {[$w compare $cur != $anchor] || (abs($v(pressX) - $x) >= 3)} { + if {$v(mouseMoved)==0} { + $w tag remove sel 0.0 end + } + set v(mouseMoved) 1 + } + if {[$w compare $cur < anchor]} { + set first $cur + set last anchor + } else { + set first anchor + set last $cur + } + if {$v(mouseMoved)} { + $w tag remove sel 0.0 $first + $w tag add sel $first $last + $w tag remove sel $last end + update idletasks + } +} + +# Called whenever the mouse moves while button-1 is held down. +# +proc sqlitecon::B1Motion {w x y} { + upvar #0 $w v + set v(y) $y + set v(x) $x + sqlitecon::SelectTo $w $x $y +} + +# Called whenever the mouse leaves the boundries of the widget +# while button 1 is held down. +# +proc sqlitecon::B1Leave {w x y} { + upvar #0 $w v + set v(y) $y + set v(x) $x + sqlitecon::motor $w +} + +# This routine is called to automatically scroll the window when +# the mouse drags offscreen. +# +proc sqlitecon::motor w { + upvar #0 $w v + if {![winfo exists $w]} return + if {$v(y)>=[winfo height $w]} { + $w yview scroll 1 units + } elseif {$v(y)<0} { + $w yview scroll -1 units + } else { + return + } + sqlitecon::SelectTo $w $v(x) $v(y) + set v(timer) [after 50 sqlitecon::motor $w] +} + +# This routine cancels the scrolling motor if it is active +# +proc sqlitecon::cancelMotor w { + upvar #0 $w v + catch {after cancel $v(timer)} + catch {unset v(timer)} +} + +# Do a Copy operation on the stuff currently selected. +# +proc sqlitecon::Copy w { + if {![catch {set text [$w get sel.first sel.last]}]} { + clipboard clear -displayof $w + clipboard append -displayof $w $text + } +} + +# Return 1 if the selection exists and is contained +# entirely on the input line. Return 2 if the selection +# exists but is not entirely on the input line. Return 0 +# if the selection does not exist. +# +proc sqlitecon::canCut w { + set r [catch { + scan [$w index sel.first] %d.%d s1x s1y + scan [$w index sel.last] %d.%d s2x s2y + scan [$w index insert] %d.%d ix iy + }] + if {$r==1} {return 0} + if {$s1x==$ix && $s2x==$ix} {return 1} + return 2 +} + +# Do a Cut operation if possible. Cuts are only allowed +# if the current selection is entirely contained on the +# current input line. +# +proc sqlitecon::Cut w { + if {[sqlitecon::canCut $w]==1} { + sqlitecon::Copy $w + $w delete sel.first sel.last + } +} + +# Do a paste opeation. +# +proc sqlitecon::Paste w { + if {[sqlitecon::canCut $w]==1} { + $w delete sel.first sel.last + } + if {[catch {selection get -displayof $w -selection CLIPBOARD} topaste] + && [catch {selection get -displayof $w -selection PRIMARY} topaste]} { + return + } + if {[info exists ::$w]} { + set prior 0 + foreach line [split $topaste \n] { + if {$prior} { + sqlitecon::Enter $w + update + } + set prior 1 + $w insert insert $line + } + } else { + $w insert insert $topaste + } +} + +# Enable or disable entries in the Edit menu +# +proc sqlitecon::EnableEditMenu w { + upvar #0 $w.t v + set m $v(editmenu) + if {$m=="" || ![winfo exists $m]} return + switch [sqlitecon::canCut $w.t] { + 0 { + $m entryconf Copy -state disabled + $m entryconf Cut -state disabled + } + 1 { + $m entryconf Copy -state normal + $m entryconf Cut -state normal + } + 2 { + $m entryconf Copy -state normal + $m entryconf Cut -state disabled + } + } +} + +# Prompt the user for the name of a writable file. Then write the +# entire contents of the console screen to that file. +# +proc sqlitecon::SaveFile w { + set types { + {{Text Files} {.txt}} + {{All Files} *} + } + set f [tk_getSaveFile -filetypes $types -title "Write Screen To..."] + if {$f!=""} { + if {[catch {open $f w} fd]} { + tk_messageBox -type ok -icon error -message $fd + } else { + puts $fd [string trimright [$w get 1.0 end] \n] + close $fd + } + } +} + +# Erase everything from the console above the insertion line. +# +proc sqlitecon::Clear w { + $w delete 1.0 {insert linestart} +} + +# An in-line editor for SQL +# +proc sqlitecon::_edit {origtxt {title {}}} { + for {set i 0} {[winfo exists .ed$i]} {incr i} continue + set w .ed$i + toplevel $w + wm protocol $w WM_DELETE_WINDOW "$w.b.can invoke" + wm title $w {Inline SQL Editor} + frame $w.b + pack $w.b -side bottom -fill x + button $w.b.can -text Cancel -width 6 -command [list set ::$w 0] + button $w.b.ok -text OK -width 6 -command [list set ::$w 1] + button $w.b.cut -text Cut -width 6 -command [list ::sqlitecon::Cut $w.t] + button $w.b.copy -text Copy -width 6 -command [list ::sqlitecon::Copy $w.t] + button $w.b.paste -text Paste -width 6 -command [list ::sqlitecon::Paste $w.t] + set ::$w {} + pack $w.b.cut $w.b.copy $w.b.paste $w.b.can $w.b.ok\ + -side left -padx 5 -pady 5 -expand 1 + if {$title!=""} { + label $w.title -text $title + pack $w.title -side top -padx 5 -pady 5 + } + text $w.t -bg white -fg black -yscrollcommand [list $w.sb set] + pack $w.t -side left -fill both -expand 1 + scrollbar $w.sb -orient vertical -command [list $w.t yview] + pack $w.sb -side left -fill y + $w.t insert end $origtxt + + vwait ::$w + + if {[set ::$w]} { + set txt [string trimright [$w.t get 1.0 end]] + } else { + set txt $origtxt + } + destroy $w + return $txt +} diff --git a/components/external/SQLite-3.8.1/doc/lemon.html b/components/external/SQLite-3.8.1/doc/lemon.html new file mode 100644 index 0000000000000000000000000000000000000000..b16e35960ef9e44d390cbb4c7f7eafbc19160ae0 --- /dev/null +++ b/components/external/SQLite-3.8.1/doc/lemon.html @@ -0,0 +1,892 @@ + + +The Lemon Parser Generator + + +

The Lemon Parser Generator

+ +

Lemon is an LALR(1) parser generator for C or C++. +It does the same job as ``bison'' and ``yacc''. +But lemon is not another bison or yacc clone. It +uses a different grammar syntax which is designed to +reduce the number of coding errors. Lemon also uses a more +sophisticated parsing engine that is faster than yacc and +bison and which is both reentrant and thread-safe. +Furthermore, Lemon implements features that can be used +to eliminate resource leaks, making is suitable for use +in long-running programs such as graphical user interfaces +or embedded controllers.

+ +

This document is an introduction to the Lemon +parser generator.

+ +

Theory of Operation

+ +

The main goal of Lemon is to translate a context free grammar (CFG) +for a particular language into C code that implements a parser for +that language. +The program has two inputs: +

    +
  • The grammar specification. +
  • A parser template file. +
+Typically, only the grammar specification is supplied by the programmer. +Lemon comes with a default parser template which works fine for most +applications. But the user is free to substitute a different parser +template if desired.

+ +

Depending on command-line options, Lemon will generate between +one and three files of outputs. +

    +
  • C code to implement the parser. +
  • A header file defining an integer ID for each terminal symbol. +
  • An information file that describes the states of the generated parser + automaton. +
+By default, all three of these output files are generated. +The header file is suppressed if the ``-m'' command-line option is +used and the report file is omitted when ``-q'' is selected.

+ +

The grammar specification file uses a ``.y'' suffix, by convention. +In the examples used in this document, we'll assume the name of the +grammar file is ``gram.y''. A typical use of Lemon would be the +following command: +

+   lemon gram.y
+
+This command will generate three output files named ``gram.c'', +``gram.h'' and ``gram.out''. +The first is C code to implement the parser. The second +is the header file that defines numerical values for all +terminal symbols, and the last is the report that explains +the states used by the parser automaton.

+ +

Command Line Options

+ +

The behavior of Lemon can be modified using command-line options. +You can obtain a list of the available command-line options together +with a brief explanation of what each does by typing +

+   lemon -?
+
+As of this writing, the following command-line options are supported: +
    +
  • -b +
  • -c +
  • -g +
  • -m +
  • -q +
  • -s +
  • -x +
+The ``-b'' option reduces the amount of text in the report file by +printing only the basis of each parser state, rather than the full +configuration. +The ``-c'' option suppresses action table compression. Using -c +will make the parser a little larger and slower but it will detect +syntax errors sooner. +The ``-g'' option causes no output files to be generated at all. +Instead, the input grammar file is printed on standard output but +with all comments, actions and other extraneous text deleted. This +is a useful way to get a quick summary of a grammar. +The ``-m'' option causes the output C source file to be compatible +with the ``makeheaders'' program. +Makeheaders is a program that automatically generates header files +from C source code. When the ``-m'' option is used, the header +file is not output since the makeheaders program will take care +of generated all header files automatically. +The ``-q'' option suppresses the report file. +Using ``-s'' causes a brief summary of parser statistics to be +printed. Like this: +
+   Parser statistics: 74 terminals, 70 nonterminals, 179 rules
+                      340 states, 2026 parser table entries, 0 conflicts
+
+Finally, the ``-x'' option causes Lemon to print its version number +and then stops without attempting to read the grammar or generate a parser.

+ +

The Parser Interface

+ +

Lemon doesn't generate a complete, working program. It only generates +a few subroutines that implement a parser. This section describes +the interface to those subroutines. It is up to the programmer to +call these subroutines in an appropriate way in order to produce a +complete system.

+ +

Before a program begins using a Lemon-generated parser, the program +must first create the parser. +A new parser is created as follows: +

+   void *pParser = ParseAlloc( malloc );
+
+The ParseAlloc() routine allocates and initializes a new parser and +returns a pointer to it. +The actual data structure used to represent a parser is opaque -- +its internal structure is not visible or usable by the calling routine. +For this reason, the ParseAlloc() routine returns a pointer to void +rather than a pointer to some particular structure. +The sole argument to the ParseAlloc() routine is a pointer to the +subroutine used to allocate memory. Typically this means ``malloc()''.

+ +

After a program is finished using a parser, it can reclaim all +memory allocated by that parser by calling +

+   ParseFree(pParser, free);
+
+The first argument is the same pointer returned by ParseAlloc(). The +second argument is a pointer to the function used to release bulk +memory back to the system.

+ +

After a parser has been allocated using ParseAlloc(), the programmer +must supply the parser with a sequence of tokens (terminal symbols) to +be parsed. This is accomplished by calling the following function +once for each token: +

+   Parse(pParser, hTokenID, sTokenData, pArg);
+
+The first argument to the Parse() routine is the pointer returned by +ParseAlloc(). +The second argument is a small positive integer that tells the parse the +type of the next token in the data stream. +There is one token type for each terminal symbol in the grammar. +The gram.h file generated by Lemon contains #define statements that +map symbolic terminal symbol names into appropriate integer values. +(A value of 0 for the second argument is a special flag to the +parser to indicate that the end of input has been reached.) +The third argument is the value of the given token. By default, +the type of the third argument is integer, but the grammar will +usually redefine this type to be some kind of structure. +Typically the second argument will be a broad category of tokens +such as ``identifier'' or ``number'' and the third argument will +be the name of the identifier or the value of the number.

+ +

The Parse() function may have either three or four arguments, +depending on the grammar. If the grammar specification file request +it, the Parse() function will have a fourth parameter that can be +of any type chosen by the programmer. The parser doesn't do anything +with this argument except to pass it through to action routines. +This is a convenient mechanism for passing state information down +to the action routines without having to use global variables.

+ +

A typical use of a Lemon parser might look something like the +following: +

+   01 ParseTree *ParseFile(const char *zFilename){
+   02    Tokenizer *pTokenizer;
+   03    void *pParser;
+   04    Token sToken;
+   05    int hTokenId;
+   06    ParserState sState;
+   07
+   08    pTokenizer = TokenizerCreate(zFilename);
+   09    pParser = ParseAlloc( malloc );
+   10    InitParserState(&sState);
+   11    while( GetNextToken(pTokenizer, &hTokenId, &sToken) ){
+   12       Parse(pParser, hTokenId, sToken, &sState);
+   13    }
+   14    Parse(pParser, 0, sToken, &sState);
+   15    ParseFree(pParser, free );
+   16    TokenizerFree(pTokenizer);
+   17    return sState.treeRoot;
+   18 }
+
+This example shows a user-written routine that parses a file of +text and returns a pointer to the parse tree. +(We've omitted all error-handling from this example to keep it +simple.) +We assume the existence of some kind of tokenizer which is created +using TokenizerCreate() on line 8 and deleted by TokenizerFree() +on line 16. The GetNextToken() function on line 11 retrieves the +next token from the input file and puts its type in the +integer variable hTokenId. The sToken variable is assumed to be +some kind of structure that contains details about each token, +such as its complete text, what line it occurs on, etc.

+ +

This example also assumes the existence of structure of type +ParserState that holds state information about a particular parse. +An instance of such a structure is created on line 6 and initialized +on line 10. A pointer to this structure is passed into the Parse() +routine as the optional 4th argument. +The action routine specified by the grammar for the parser can use +the ParserState structure to hold whatever information is useful and +appropriate. In the example, we note that the treeRoot field of +the ParserState structure is left pointing to the root of the parse +tree.

+ +

The core of this example as it relates to Lemon is as follows: +

+   ParseFile(){
+      pParser = ParseAlloc( malloc );
+      while( GetNextToken(pTokenizer,&hTokenId, &sToken) ){
+         Parse(pParser, hTokenId, sToken);
+      }
+      Parse(pParser, 0, sToken);
+      ParseFree(pParser, free );
+   }
+
+Basically, what a program has to do to use a Lemon-generated parser +is first create the parser, then send it lots of tokens obtained by +tokenizing an input source. When the end of input is reached, the +Parse() routine should be called one last time with a token type +of 0. This step is necessary to inform the parser that the end of +input has been reached. Finally, we reclaim memory used by the +parser by calling ParseFree().

+ +

There is one other interface routine that should be mentioned +before we move on. +The ParseTrace() function can be used to generate debugging output +from the parser. A prototype for this routine is as follows: +

+   ParseTrace(FILE *stream, char *zPrefix);
+
+After this routine is called, a short (one-line) message is written +to the designated output stream every time the parser changes states +or calls an action routine. Each such message is prefaced using +the text given by zPrefix. This debugging output can be turned off +by calling ParseTrace() again with a first argument of NULL (0).

+ +

Differences With YACC and BISON

+ +

Programmers who have previously used the yacc or bison parser +generator will notice several important differences between yacc and/or +bison and Lemon. +

    +
  • In yacc and bison, the parser calls the tokenizer. In Lemon, + the tokenizer calls the parser. +
  • Lemon uses no global variables. Yacc and bison use global variables + to pass information between the tokenizer and parser. +
  • Lemon allows multiple parsers to be running simultaneously. Yacc + and bison do not. +
+These differences may cause some initial confusion for programmers +with prior yacc and bison experience. +But after years of experience using Lemon, I firmly +believe that the Lemon way of doing things is better.

+ +

Input File Syntax

+ +

The main purpose of the grammar specification file for Lemon is +to define the grammar for the parser. But the input file also +specifies additional information Lemon requires to do its job. +Most of the work in using Lemon is in writing an appropriate +grammar file.

+ +

The grammar file for lemon is, for the most part, free format. +It does not have sections or divisions like yacc or bison. Any +declaration can occur at any point in the file. +Lemon ignores whitespace (except where it is needed to separate +tokens) and it honors the same commenting conventions as C and C++.

+ +

Terminals and Nonterminals

+ +

A terminal symbol (token) is any string of alphanumeric +and underscore characters +that begins with an upper case letter. +A terminal can contain lowercase letters after the first character, +but the usual convention is to make terminals all upper case. +A nonterminal, on the other hand, is any string of alphanumeric +and underscore characters than begins with a lower case letter. +Again, the usual convention is to make nonterminals use all lower +case letters.

+ +

In Lemon, terminal and nonterminal symbols do not need to +be declared or identified in a separate section of the grammar file. +Lemon is able to generate a list of all terminals and nonterminals +by examining the grammar rules, and it can always distinguish a +terminal from a nonterminal by checking the case of the first +character of the name.

+ +

Yacc and bison allow terminal symbols to have either alphanumeric +names or to be individual characters included in single quotes, like +this: ')' or '$'. Lemon does not allow this alternative form for +terminal symbols. With Lemon, all symbols, terminals and nonterminals, +must have alphanumeric names.

+ +

Grammar Rules

+ +

The main component of a Lemon grammar file is a sequence of grammar +rules. +Each grammar rule consists of a nonterminal symbol followed by +the special symbol ``::='' and then a list of terminals and/or nonterminals. +The rule is terminated by a period. +The list of terminals and nonterminals on the right-hand side of the +rule can be empty. +Rules can occur in any order, except that the left-hand side of the +first rule is assumed to be the start symbol for the grammar (unless +specified otherwise using the %start directive described below.) +A typical sequence of grammar rules might look something like this: +

+  expr ::= expr PLUS expr.
+  expr ::= expr TIMES expr.
+  expr ::= LPAREN expr RPAREN.
+  expr ::= VALUE.
+
+

+ +

There is one non-terminal in this example, ``expr'', and five +terminal symbols or tokens: ``PLUS'', ``TIMES'', ``LPAREN'', +``RPAREN'' and ``VALUE''.

+ +

Like yacc and bison, Lemon allows the grammar to specify a block +of C code that will be executed whenever a grammar rule is reduced +by the parser. +In Lemon, this action is specified by putting the C code (contained +within curly braces {...}) immediately after the +period that closes the rule. +For example: +

+  expr ::= expr PLUS expr.   { printf("Doing an addition...\n"); }
+
+

+ +

In order to be useful, grammar actions must normally be linked to +their associated grammar rules. +In yacc and bison, this is accomplished by embedding a ``$$'' in the +action to stand for the value of the left-hand side of the rule and +symbols ``$1'', ``$2'', and so forth to stand for the value of +the terminal or nonterminal at position 1, 2 and so forth on the +right-hand side of the rule. +This idea is very powerful, but it is also very error-prone. The +single most common source of errors in a yacc or bison grammar is +to miscount the number of symbols on the right-hand side of a grammar +rule and say ``$7'' when you really mean ``$8''.

+ +

Lemon avoids the need to count grammar symbols by assigning symbolic +names to each symbol in a grammar rule and then using those symbolic +names in the action. +In yacc or bison, one would write this: +

+  expr -> expr PLUS expr  { $$ = $1 + $3; };
+
+But in Lemon, the same rule becomes the following: +
+  expr(A) ::= expr(B) PLUS expr(C).  { A = B+C; }
+
+In the Lemon rule, any symbol in parentheses after a grammar rule +symbol becomes a place holder for that symbol in the grammar rule. +This place holder can then be used in the associated C action to +stand for the value of that symbol.

+ +

The Lemon notation for linking a grammar rule with its reduce +action is superior to yacc/bison on several counts. +First, as mentioned above, the Lemon method avoids the need to +count grammar symbols. +Secondly, if a terminal or nonterminal in a Lemon grammar rule +includes a linking symbol in parentheses but that linking symbol +is not actually used in the reduce action, then an error message +is generated. +For example, the rule +

+  expr(A) ::= expr(B) PLUS expr(C).  { A = B; }
+
+will generate an error because the linking symbol ``C'' is used +in the grammar rule but not in the reduce action.

+ +

The Lemon notation for linking grammar rules to reduce actions +also facilitates the use of destructors for reclaiming memory +allocated by the values of terminals and nonterminals on the +right-hand side of a rule.

+ +

Precedence Rules

+ +

Lemon resolves parsing ambiguities in exactly the same way as +yacc and bison. A shift-reduce conflict is resolved in favor +of the shift, and a reduce-reduce conflict is resolved by reducing +whichever rule comes first in the grammar file.

+ +

Just like in +yacc and bison, Lemon allows a measure of control +over the resolution of paring conflicts using precedence rules. +A precedence value can be assigned to any terminal symbol +using the %left, %right or %nonassoc directives. Terminal symbols +mentioned in earlier directives have a lower precedence that +terminal symbols mentioned in later directives. For example:

+ +

+   %left AND.
+   %left OR.
+   %nonassoc EQ NE GT GE LT LE.
+   %left PLUS MINUS.
+   %left TIMES DIVIDE MOD.
+   %right EXP NOT.
+

+ +

In the preceding sequence of directives, the AND operator is +defined to have the lowest precedence. The OR operator is one +precedence level higher. And so forth. Hence, the grammar would +attempt to group the ambiguous expression +

+     a AND b OR c
+
+like this +
+     a AND (b OR c).
+
+The associativity (left, right or nonassoc) is used to determine +the grouping when the precedence is the same. AND is left-associative +in our example, so +
+     a AND b AND c
+
+is parsed like this +
+     (a AND b) AND c.
+
+The EXP operator is right-associative, though, so +
+     a EXP b EXP c
+
+is parsed like this +
+     a EXP (b EXP c).
+
+The nonassoc precedence is used for non-associative operators. +So +
+     a EQ b EQ c
+
+is an error.

+ +

The precedence of non-terminals is transferred to rules as follows: +The precedence of a grammar rule is equal to the precedence of the +left-most terminal symbol in the rule for which a precedence is +defined. This is normally what you want, but in those cases where +you want to precedence of a grammar rule to be something different, +you can specify an alternative precedence symbol by putting the +symbol in square braces after the period at the end of the rule and +before any C-code. For example:

+ +

+   expr = MINUS expr.  [NOT]
+

+ +

This rule has a precedence equal to that of the NOT symbol, not the +MINUS symbol as would have been the case by default.

+ +

With the knowledge of how precedence is assigned to terminal +symbols and individual +grammar rules, we can now explain precisely how parsing conflicts +are resolved in Lemon. Shift-reduce conflicts are resolved +as follows: +

    +
  • If either the token to be shifted or the rule to be reduced + lacks precedence information, then resolve in favor of the + shift, but report a parsing conflict. +
  • If the precedence of the token to be shifted is greater than + the precedence of the rule to reduce, then resolve in favor + of the shift. No parsing conflict is reported. +
  • If the precedence of the token it be shifted is less than the + precedence of the rule to reduce, then resolve in favor of the + reduce action. No parsing conflict is reported. +
  • If the precedences are the same and the shift token is + right-associative, then resolve in favor of the shift. + No parsing conflict is reported. +
  • If the precedences are the same the shift token is + left-associative, then resolve in favor of the reduce. + No parsing conflict is reported. +
  • Otherwise, resolve the conflict by doing the shift and + report the parsing conflict. +
+Reduce-reduce conflicts are resolved this way: +
    +
  • If either reduce rule + lacks precedence information, then resolve in favor of the + rule that appears first in the grammar and report a parsing + conflict. +
  • If both rules have precedence and the precedence is different + then resolve the dispute in favor of the rule with the highest + precedence and do not report a conflict. +
  • Otherwise, resolve the conflict by reducing by the rule that + appears first in the grammar and report a parsing conflict. +
+ +

Special Directives

+ +

The input grammar to Lemon consists of grammar rules and special +directives. We've described all the grammar rules, so now we'll +talk about the special directives.

+ +

Directives in lemon can occur in any order. You can put them before +the grammar rules, or after the grammar rules, or in the mist of the +grammar rules. It doesn't matter. The relative order of +directives used to assign precedence to terminals is important, but +other than that, the order of directives in Lemon is arbitrary.

+ +

Lemon supports the following special directives: +

    +
  • %code +
  • %default_destructor +
  • %default_type +
  • %destructor +
  • %extra_argument +
  • %include +
  • %left +
  • %name +
  • %nonassoc +
  • %parse_accept +
  • %parse_failure +
  • %right +
  • %stack_overflow +
  • %stack_size +
  • %start_symbol +
  • %syntax_error +
  • %token_destructor +
  • %token_prefix +
  • %token_type +
  • %type +
+Each of these directives will be described separately in the +following sections:

+ +

The %code directive

+ +

The %code directive is used to specify addition C/C++ code that +is added to the end of the main output file. This is similar to +the %include directive except that %include is inserted at the +beginning of the main output file.

+ +

%code is typically used to include some action routines or perhaps +a tokenizer as part of the output file.

+ +

The %default_destructor directive

+ +

The %default_destructor directive specifies a destructor to +use for non-terminals that do not have their own destructor +specified by a separate %destructor directive. See the documentation +on the %destructor directive below for additional information.

+ +

In some grammers, many different non-terminal symbols have the +same datatype and hence the same destructor. This directive is +a convenience way to specify the same destructor for all those +non-terminals using a single statement.

+ +

The %default_type directive

+ +

The %default_type directive specifies the datatype of non-terminal +symbols that do no have their own datatype defined using a separate +%type directive. See the documentation on %type below for addition +information.

+ +

The %destructor directive

+ +

The %destructor directive is used to specify a destructor for +a non-terminal symbol. +(See also the %token_destructor directive which is used to +specify a destructor for terminal symbols.)

+ +

A non-terminal's destructor is called to dispose of the +non-terminal's value whenever the non-terminal is popped from +the stack. This includes all of the following circumstances: +

    +
  • When a rule reduces and the value of a non-terminal on + the right-hand side is not linked to C code. +
  • When the stack is popped during error processing. +
  • When the ParseFree() function runs. +
+The destructor can do whatever it wants with the value of +the non-terminal, but its design is to deallocate memory +or other resources held by that non-terminal.

+ +

Consider an example: +

+   %type nt {void*}
+   %destructor nt { free($$); }
+   nt(A) ::= ID NUM.   { A = malloc( 100 ); }
+
+This example is a bit contrived but it serves to illustrate how +destructors work. The example shows a non-terminal named +``nt'' that holds values of type ``void*''. When the rule for +an ``nt'' reduces, it sets the value of the non-terminal to +space obtained from malloc(). Later, when the nt non-terminal +is popped from the stack, the destructor will fire and call +free() on this malloced space, thus avoiding a memory leak. +(Note that the symbol ``$$'' in the destructor code is replaced +by the value of the non-terminal.)

+ +

It is important to note that the value of a non-terminal is passed +to the destructor whenever the non-terminal is removed from the +stack, unless the non-terminal is used in a C-code action. If +the non-terminal is used by C-code, then it is assumed that the +C-code will take care of destroying it if it should really +be destroyed. More commonly, the value is used to build some +larger structure and we don't want to destroy it, which is why +the destructor is not called in this circumstance.

+ +

By appropriate use of destructors, it is possible to +build a parser using Lemon that can be used within a long-running +program, such as a GUI, that will not leak memory or other resources. +To do the same using yacc or bison is much more difficult.

+ +

The %extra_argument directive

+ +The %extra_argument directive instructs Lemon to add a 4th parameter +to the parameter list of the Parse() function it generates. Lemon +doesn't do anything itself with this extra argument, but it does +make the argument available to C-code action routines, destructors, +and so forth. For example, if the grammar file contains:

+ +

+    %extra_argument { MyStruct *pAbc }
+

+ +

Then the Parse() function generated will have an 4th parameter +of type ``MyStruct*'' and all action routines will have access to +a variable named ``pAbc'' that is the value of the 4th parameter +in the most recent call to Parse().

+ +

The %include directive

+ +

The %include directive specifies C code that is included at the +top of the generated parser. You can include any text you want -- +the Lemon parser generator copies it blindly. If you have multiple +%include directives in your grammar file the value of the last +%include directive overwrites all the others.The %include directive is very handy for getting some extra #include +preprocessor statements at the beginning of the generated parser. +For example:

+ +

+   %include {#include <unistd.h>}
+

+ +

This might be needed, for example, if some of the C actions in the +grammar call functions that are prototyed in unistd.h.

+ +

The %left directive

+ +The %left directive is used (along with the %right and +%nonassoc directives) to declare precedences of terminal +symbols. Every terminal symbol whose name appears after +a %left directive but before the next period (``.'') is +given the same left-associative precedence value. Subsequent +%left directives have higher precedence. For example:

+ +

+   %left AND.
+   %left OR.
+   %nonassoc EQ NE GT GE LT LE.
+   %left PLUS MINUS.
+   %left TIMES DIVIDE MOD.
+   %right EXP NOT.
+

+ +

Note the period that terminates each %left, %right or %nonassoc +directive.

+ +

LALR(1) grammars can get into a situation where they require +a large amount of stack space if you make heavy use or right-associative +operators. For this reason, it is recommended that you use %left +rather than %right whenever possible.

+ +

The %name directive

+ +

By default, the functions generated by Lemon all begin with the +five-character string ``Parse''. You can change this string to something +different using the %name directive. For instance:

+ +

+   %name Abcde
+

+ +

Putting this directive in the grammar file will cause Lemon to generate +functions named +

    +
  • AbcdeAlloc(), +
  • AbcdeFree(), +
  • AbcdeTrace(), and +
  • Abcde(). +
+The %name directive allows you to generator two or more different +parsers and link them all into the same executable. +

+ +

The %nonassoc directive

+ +

This directive is used to assign non-associative precedence to +one or more terminal symbols. See the section on precedence rules +or on the %left directive for additional information.

+ +

The %parse_accept directive

+ +

The %parse_accept directive specifies a block of C code that is +executed whenever the parser accepts its input string. To ``accept'' +an input string means that the parser was able to process all tokens +without error.

+ +

For example:

+ +

+   %parse_accept {
+      printf("parsing complete!\n");
+   }
+

+ + +

The %parse_failure directive

+ +

The %parse_failure directive specifies a block of C code that +is executed whenever the parser fails complete. This code is not +executed until the parser has tried and failed to resolve an input +error using is usual error recovery strategy. The routine is +only invoked when parsing is unable to continue.

+ +

+   %parse_failure {
+     fprintf(stderr,"Giving up.  Parser is hopelessly lost...\n");
+   }
+

+ +

The %right directive

+ +

This directive is used to assign right-associative precedence to +one or more terminal symbols. See the section on precedence rules +or on the %left directive for additional information.

+ +

The %stack_overflow directive

+ +

The %stack_overflow directive specifies a block of C code that +is executed if the parser's internal stack ever overflows. Typically +this just prints an error message. After a stack overflow, the parser +will be unable to continue and must be reset.

+ +

+   %stack_overflow {
+     fprintf(stderr,"Giving up.  Parser stack overflow\n");
+   }
+

+ +

You can help prevent parser stack overflows by avoiding the use +of right recursion and right-precedence operators in your grammar. +Use left recursion and and left-precedence operators instead, to +encourage rules to reduce sooner and keep the stack size down. +For example, do rules like this: +

+   list ::= list element.      // left-recursion.  Good!
+   list ::= .
+
+Not like this: +
+   list ::= element list.      // right-recursion.  Bad!
+   list ::= .
+
+ +

The %stack_size directive

+ +

If stack overflow is a problem and you can't resolve the trouble +by using left-recursion, then you might want to increase the size +of the parser's stack using this directive. Put an positive integer +after the %stack_size directive and Lemon will generate a parse +with a stack of the requested size. The default value is 100.

+ +

+   %stack_size 2000
+

+ +

The %start_symbol directive

+ +

By default, the start-symbol for the grammar that Lemon generates +is the first non-terminal that appears in the grammar file. But you +can choose a different start-symbol using the %start_symbol directive.

+ +

+   %start_symbol  prog
+

+ +

The %token_destructor directive

+ +

The %destructor directive assigns a destructor to a non-terminal +symbol. (See the description of the %destructor directive above.) +This directive does the same thing for all terminal symbols.

+ +

Unlike non-terminal symbols which may each have a different data type +for their values, terminals all use the same data type (defined by +the %token_type directive) and so they use a common destructor. Other +than that, the token destructor works just like the non-terminal +destructors.

+ +

The %token_prefix directive

+ +

Lemon generates #defines that assign small integer constants +to each terminal symbol in the grammar. If desired, Lemon will +add a prefix specified by this directive +to each of the #defines it generates. +So if the default output of Lemon looked like this: +

+    #define AND              1
+    #define MINUS            2
+    #define OR               3
+    #define PLUS             4
+
+You can insert a statement into the grammar like this: +
+    %token_prefix    TOKEN_
+
+to cause Lemon to produce these symbols instead: +
+    #define TOKEN_AND        1
+    #define TOKEN_MINUS      2
+    #define TOKEN_OR         3
+    #define TOKEN_PLUS       4
+
+ +

The %token_type and %type directives

+ +

These directives are used to specify the data types for values +on the parser's stack associated with terminal and non-terminal +symbols. The values of all terminal symbols must be of the same +type. This turns out to be the same data type as the 3rd parameter +to the Parse() function generated by Lemon. Typically, you will +make the value of a terminal symbol by a pointer to some kind of +token structure. Like this:

+ +

+   %token_type    {Token*}
+

+ +

If the data type of terminals is not specified, the default value +is ``int''.

+ +

Non-terminal symbols can each have their own data types. Typically +the data type of a non-terminal is a pointer to the root of a parse-tree +structure that contains all information about that non-terminal. +For example:

+ +

+   %type   expr  {Expr*}
+

+ +

Each entry on the parser's stack is actually a union containing +instances of all data types for every non-terminal and terminal symbol. +Lemon will automatically use the correct element of this union depending +on what the corresponding non-terminal or terminal symbol is. But +the grammar designer should keep in mind that the size of the union +will be the size of its largest element. So if you have a single +non-terminal whose data type requires 1K of storage, then your 100 +entry parser stack will require 100K of heap space. If you are willing +and able to pay that price, fine. You just need to know.

+ +

Error Processing

+ +

After extensive experimentation over several years, it has been +discovered that the error recovery strategy used by yacc is about +as good as it gets. And so that is what Lemon uses.

+ +

When a Lemon-generated parser encounters a syntax error, it +first invokes the code specified by the %syntax_error directive, if +any. It then enters its error recovery strategy. The error recovery +strategy is to begin popping the parsers stack until it enters a +state where it is permitted to shift a special non-terminal symbol +named ``error''. It then shifts this non-terminal and continues +parsing. But the %syntax_error routine will not be called again +until at least three new tokens have been successfully shifted.

+ +

If the parser pops its stack until the stack is empty, and it still +is unable to shift the error symbol, then the %parse_failed routine +is invoked and the parser resets itself to its start state, ready +to begin parsing a new file. This is what will happen at the very +first syntax error, of course, if there are no instances of the +``error'' non-terminal in your grammar.

+ + + diff --git a/components/external/SQLite-3.8.1/doc/pager-invariants.txt b/components/external/SQLite-3.8.1/doc/pager-invariants.txt new file mode 100644 index 0000000000000000000000000000000000000000..44444dad54bea03e7a838414f06cb8ed4bcf26b1 --- /dev/null +++ b/components/external/SQLite-3.8.1/doc/pager-invariants.txt @@ -0,0 +1,76 @@ + *** Throughout this document, a page is deemed to have been synced + automatically as soon as it is written when PRAGMA synchronous=OFF. + Otherwise, the page is not synced until the xSync method of the VFS + is called successfully on the file containing the page. + + *** Definition: A page of the database file is said to be "overwriteable" if + one or more of the following are true about the page: + + (a) The original content of the page as it was at the beginning of + the transaction has been written into the rollback journal and + synced. + + (b) The page was a freelist leaf page at the start of the transaction. + + (c) The page number is greater than the largest page that existed in + the database file at the start of the transaction. + + (1) A page of the database file is never overwritten unless one of the + following are true: + + (a) The page and all other pages on the same sector are overwriteable. + + (b) The atomic page write optimization is enabled, and the entire + transaction other than the update of the transaction sequence + number consists of a single page change. + + (2) The content of a page written into the rollback journal exactly matches + both the content in the database when the rollback journal was written + and the content in the database at the beginning of the current + transaction. + + (3) Writes to the database file are an integer multiple of the page size + in length and are aligned to a page boundary. + + (4) Reads from the database file are either aligned on a page boundary and + an integer multiple of the page size in length or are taken from the + first 100 bytes of the database file. + + (5) All writes to the database file are synced prior to the rollback journal + being deleted, truncated, or zeroed. + + (6) If a master journal file is used, then all writes to the database file + are synced prior to the master journal being deleted. + + *** Definition: Two databases (or the same database at two points it time) + are said to be "logically equivalent" if they give the same answer to + all queries. Note in particular the content of freelist leaf + pages can be changed arbitarily without effecting the logical equivalence + of the database. + + (7) At any time, if any subset, including the empty set and the total set, + of the unsynced changes to a rollback journal are removed and the + journal is rolled back, the resulting database file will be logical + equivalent to the database file at the beginning of the transaction. + + (8) When a transaction is rolled back, the xTruncate method of the VFS + is called to restore the database file to the same size it was at + the beginning of the transaction. (In some VFSes, the xTruncate + method is a no-op, but that does not change the fact the SQLite will + invoke it.) + + (9) Whenever the database file is modified, at least one bit in the range + of bytes from 24 through 39 inclusive will be changed prior to releasing + the EXCLUSIVE lock. + +(10) The pattern of bits in bytes 24 through 39 shall not repeat in less + than one billion transactions. + +(11) A database file is well-formed at the beginning and at the conclusion + of every transaction. + +(12) An EXCLUSIVE lock must be held on the database file before making + any changes to the database file. + +(13) A SHARED lock must be held on the database file before reading any + content out of the database file. diff --git a/components/external/SQLite-3.8.1/doc/vfs-shm.txt b/components/external/SQLite-3.8.1/doc/vfs-shm.txt new file mode 100644 index 0000000000000000000000000000000000000000..c1f125a12036448001be73772ac7eefcff82095f --- /dev/null +++ b/components/external/SQLite-3.8.1/doc/vfs-shm.txt @@ -0,0 +1,130 @@ +The 5 states of an historical rollback lock as implemented by the +xLock, xUnlock, and xCheckReservedLock methods of the sqlite3_io_methods +objec are: + + UNLOCKED + SHARED + RESERVED + PENDING + EXCLUSIVE + +The wal-index file has a similar locking hierarchy implemented using +the xShmLock method of the sqlite3_vfs object, but with 7 +states. Each connection to a wal-index file must be in one of +the following 7 states: + + UNLOCKED + READ + READ_FULL + WRITE + PENDING + CHECKPOINT + RECOVER + +These roughly correspond to the 5 states of a rollback lock except +that SHARED is split out into 2 states: READ and READ_FULL and +there is an extra RECOVER state used for wal-index reconstruction. + +The meanings of the various wal-index locking states is as follows: + + UNLOCKED - The wal-index is not in use. + + READ - Some prefix of the wal-index is being read. Additional + wal-index information can be appended at any time. The + newly appended content will be ignored by the holder of + the READ lock. + + READ_FULL - The entire wal-index is being read. No new information + can be added to the wal-index. The holder of a READ_FULL + lock promises never to read pages from the database file + that are available anywhere in the wal-index. + + WRITE - It is OK to append to the wal-index file and to adjust + the header to indicate the new "last valid frame". + + PENDING - Waiting on all READ locks to clear so that a + CHECKPOINT lock can be acquired. + + CHECKPOINT - It is OK to write any WAL data into the database file + and zero the last valid frame field of the wal-index + header. The wal-index file itself may not be changed + other than to zero the last valid frame field in the + header. + + RECOVER - Held during wal-index recovery. Used to prevent a + race if multiple clients try to recover a wal-index at + the same time. + + +A particular lock manager implementation may coalesce one or more of +the wal-index locking states, though with a reduction in concurrency. +For example, an implemention might implement only exclusive locking, +in which case all states would be equivalent to CHECKPOINT, meaning that +only one reader or one writer or one checkpointer could be active at a +time. Or, an implementation might combine READ and READ_FULL into +a single state equivalent to READ, meaning that a writer could +coexist with a reader, but no reader or writers could coexist with a +checkpointer. + +The lock manager must obey the following rules: + +(1) A READ cannot coexist with CHECKPOINT. +(2) A READ_FULL cannot coexist with WRITE. +(3) None of WRITE, PENDING, CHECKPOINT, or RECOVER can coexist. + +The SQLite core will obey the next set of rules. These rules are +assertions on the behavior of the SQLite core which might be verified +during testing using an instrumented lock manager. + +(5) No part of the wal-index will be read without holding either some + kind of SHM lock or an EXCLUSIVE lock on the original database. + The original database is the file named in the 2nd parameter to + the xShmOpen method. + +(6) A holder of a READ_FULL will never read any page of the database + file that is contained anywhere in the wal-index. + +(7) No part of the wal-index other than the header will be written nor + will the size of the wal-index grow without holding a WRITE or + an EXCLUSIVE on the original database file. + +(8) The wal-index header will not be written without holding one of + WRITE, CHECKPOINT, or RECOVER on the wal-index or an EXCLUSIVE on + the original database files. + +(9) A CHECKPOINT or RECOVER must be held on the wal-index, or an + EXCLUSIVE on the original database file, in order to reset the + last valid frame counter in the header of the wal-index back to zero. + +(10) A WRITE can only increase the last valid frame pointer in the header. + +The SQLite core will only ever send requests for UNLOCK, READ, WRITE, +CHECKPOINT, or RECOVER to the lock manager. The SQLite core will never +request a READ_FULL or PENDING lock though the lock manager may deliver +those locking states in response to READ and CHECKPOINT requests, +respectively, if and only if the requested READ or CHECKPOINT cannot +be delivered. + +The following are the allowed lock transitions: + + Original-State Request New-State + -------------- ---------- ---------- +(11a) UNLOCK READ READ +(11b) UNLOCK READ READ_FULL +(11c) UNLOCK CHECKPOINT PENDING +(11d) UNLOCK CHECKPOINT CHECKPOINT +(11e) READ UNLOCK UNLOCK +(11f) READ WRITE WRITE +(11g) READ RECOVER RECOVER +(11h) READ_FULL UNLOCK UNLOCK +(11i) READ_FULL WRITE WRITE +(11j) READ_FULL RECOVER RECOVER +(11k) WRITE READ READ +(11l) PENDING UNLOCK UNLOCK +(11m) PENDING CHECKPOINT CHECKPOINT +(11n) CHECKPOINT UNLOCK UNLOCK +(11o) RECOVER READ READ + +These 15 transitions are all that needs to be supported. The lock +manager implementation can assert that fact. The other 27 possible +transitions among the 7 locking states will never occur. diff --git a/components/external/SQLite-3.8.1/ext/README.txt b/components/external/SQLite-3.8.1/ext/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..009495f59ddfbb1fd364a245cf8ba7b916b0f9d6 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/README.txt @@ -0,0 +1,2 @@ +Version loadable extensions to SQLite are found in subfolders +of this folder. diff --git a/components/external/SQLite-3.8.1/ext/async/README.txt b/components/external/SQLite-3.8.1/ext/async/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..f62fa2fc17e82fccc92eb7d723e333a41f2b8f0c --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/async/README.txt @@ -0,0 +1,170 @@ +NOTE (2012-11-29): + +The functionality implemented by this extension has been superseded +by WAL-mode. This module is no longer supported or maintained. The +code is retained for historical reference only. + +------------------------------------------------------------------------------ + +Normally, when SQLite writes to a database file, it waits until the write +operation is finished before returning control to the calling application. +Since writing to the file-system is usually very slow compared with CPU +bound operations, this can be a performance bottleneck. This directory +contains an extension that causes SQLite to perform all write requests +using a separate thread running in the background. Although this does not +reduce the overall system resources (CPU, disk bandwidth etc.) at all, it +allows SQLite to return control to the caller quickly even when writing to +the database, eliminating the bottleneck. + + 1. Functionality + + 1.1 How it Works + 1.2 Limitations + 1.3 Locking and Concurrency + + 2. Compilation and Usage + + 3. Porting + + + +1. FUNCTIONALITY + + With asynchronous I/O, write requests are handled by a separate thread + running in the background. This means that the thread that initiates + a database write does not have to wait for (sometimes slow) disk I/O + to occur. The write seems to happen very quickly, though in reality + it is happening at its usual slow pace in the background. + + Asynchronous I/O appears to give better responsiveness, but at a price. + You lose the Durable property. With the default I/O backend of SQLite, + once a write completes, you know that the information you wrote is + safely on disk. With the asynchronous I/O, this is not the case. If + your program crashes or if a power loss occurs after the database + write but before the asynchronous write thread has completed, then the + database change might never make it to disk and the next user of the + database might not see your change. + + You lose Durability with asynchronous I/O, but you still retain the + other parts of ACID: Atomic, Consistent, and Isolated. Many + appliations get along fine without the Durablity. + + 1.1 How it Works + + Asynchronous I/O works by creating a special SQLite "vfs" structure + and registering it with sqlite3_vfs_register(). When files opened via + this vfs are written to (using the vfs xWrite() method), the data is not + written directly to disk, but is placed in the "write-queue" to be + handled by the background thread. + + When files opened with the asynchronous vfs are read from + (using the vfs xRead() method), the data is read from the file on + disk and the write-queue, so that from the point of view of + the vfs reader the xWrite() appears to have already completed. + + The special vfs is registered (and unregistered) by calls to the + API functions sqlite3async_initialize() and sqlite3async_shutdown(). + See section "Compilation and Usage" below for details. + + 1.2 Limitations + + In order to gain experience with the main ideas surrounding asynchronous + IO, this implementation is deliberately kept simple. Additional + capabilities may be added in the future. + + For example, as currently implemented, if writes are happening at a + steady stream that exceeds the I/O capability of the background writer + thread, the queue of pending write operations will grow without bound. + If this goes on for long enough, the host system could run out of memory. + A more sophisticated module could to keep track of the quantity of + pending writes and stop accepting new write requests when the queue of + pending writes grows too large. + + 1.3 Locking and Concurrency + + Multiple connections from within a single process that use this + implementation of asynchronous IO may access a single database + file concurrently. From the point of view of the user, if all + connections are from within a single process, there is no difference + between the concurrency offered by "normal" SQLite and SQLite + using the asynchronous backend. + + If file-locking is enabled (it is enabled by default), then connections + from multiple processes may also read and write the database file. + However concurrency is reduced as follows: + + * When a connection using asynchronous IO begins a database + transaction, the database is locked immediately. However the + lock is not released until after all relevant operations + in the write-queue have been flushed to disk. This means + (for example) that the database may remain locked for some + time after a "COMMIT" or "ROLLBACK" is issued. + + * If an application using asynchronous IO executes transactions + in quick succession, other database users may be effectively + locked out of the database. This is because when a BEGIN + is executed, a database lock is established immediately. But + when the corresponding COMMIT or ROLLBACK occurs, the lock + is not released until the relevant part of the write-queue + has been flushed through. As a result, if a COMMIT is followed + by a BEGIN before the write-queue is flushed through, the database + is never unlocked,preventing other processes from accessing + the database. + + File-locking may be disabled at runtime using the sqlite3async_control() + API (see below). This may improve performance when an NFS or other + network file-system, as the synchronous round-trips to the server be + required to establish file locks are avoided. However, if multiple + connections attempt to access the same database file when file-locking + is disabled, application crashes and database corruption is a likely + outcome. + + +2. COMPILATION AND USAGE + + The asynchronous IO extension consists of a single file of C code + (sqlite3async.c), and a header file (sqlite3async.h) that defines the + C API used by applications to activate and control the modules + functionality. + + To use the asynchronous IO extension, compile sqlite3async.c as + part of the application that uses SQLite. Then use the API defined + in sqlite3async.h to initialize and configure the module. + + The asynchronous IO VFS API is described in detail in comments in + sqlite3async.h. Using the API usually consists of the following steps: + + 1. Register the asynchronous IO VFS with SQLite by calling the + sqlite3async_initialize() function. + + 2. Create a background thread to perform write operations and call + sqlite3async_run(). + + 3. Use the normal SQLite API to read and write to databases via + the asynchronous IO VFS. + + Refer to sqlite3async.h for details. + + +3. PORTING + + Currently the asynchronous IO extension is compatible with win32 systems + and systems that support the pthreads interface, including Mac OSX, Linux, + and other varieties of Unix. + + To port the asynchronous IO extension to another platform, the user must + implement mutex and condition variable primitives for the new platform. + Currently there is no externally available interface to allow this, but + modifying the code within sqlite3async.c to include the new platforms + concurrency primitives is relatively easy. Search within sqlite3async.c + for the comment string "PORTING FUNCTIONS" for details. Then implement + new versions of each of the following: + + static void async_mutex_enter(int eMutex); + static void async_mutex_leave(int eMutex); + static void async_cond_wait(int eCond, int eMutex); + static void async_cond_signal(int eCond); + static void async_sched_yield(void); + + The functionality required of each of the above functions is described + in comments in sqlite3async.c. diff --git a/components/external/SQLite-3.8.1/ext/async/sqlite3async.c b/components/external/SQLite-3.8.1/ext/async/sqlite3async.c new file mode 100644 index 0000000000000000000000000000000000000000..4ab39cac351ace28e1f59e7ceeb3bc570234e655 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/async/sqlite3async.c @@ -0,0 +1,1701 @@ +/* +** 2005 December 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** $Id: sqlite3async.c,v 1.7 2009/07/18 11:52:04 danielk1977 Exp $ +** +** This file contains the implementation of an asynchronous IO backend +** for SQLite. +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ASYNCIO) + +#include "sqlite3async.h" +#include "sqlite3.h" +#include +#include +#include + +/* Useful macros used in several places */ +#define MIN(x,y) ((x)<(y)?(x):(y)) +#define MAX(x,y) ((x)>(y)?(x):(y)) + +#ifndef SQLITE_AMALGAMATION +/* Macro to mark parameters as unused and silence compiler warnings. */ +#define UNUSED_PARAMETER(x) (void)(x) +#endif + +/* Forward references */ +typedef struct AsyncWrite AsyncWrite; +typedef struct AsyncFile AsyncFile; +typedef struct AsyncFileData AsyncFileData; +typedef struct AsyncFileLock AsyncFileLock; +typedef struct AsyncLock AsyncLock; + +/* Enable for debugging */ +#ifndef NDEBUG +#include +static int sqlite3async_trace = 0; +# define ASYNC_TRACE(X) if( sqlite3async_trace ) asyncTrace X +static void asyncTrace(const char *zFormat, ...){ + char *z; + va_list ap; + va_start(ap, zFormat); + z = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + fprintf(stderr, "[%d] %s", 0 /* (int)pthread_self() */, z); + sqlite3_free(z); +} +#else +# define ASYNC_TRACE(X) +#endif + +/* +** THREAD SAFETY NOTES +** +** Basic rules: +** +** * Both read and write access to the global write-op queue must be +** protected by the async.queueMutex. As are the async.ioError and +** async.nFile variables. +** +** * The async.pLock list and all AsyncLock and AsyncFileLock +** structures must be protected by the async.lockMutex mutex. +** +** * The file handles from the underlying system are not assumed to +** be thread safe. +** +** * See the last two paragraphs under "The Writer Thread" for +** an assumption to do with file-handle synchronization by the Os. +** +** Deadlock prevention: +** +** There are three mutex used by the system: the "writer" mutex, +** the "queue" mutex and the "lock" mutex. Rules are: +** +** * It is illegal to block on the writer mutex when any other mutex +** are held, and +** +** * It is illegal to block on the queue mutex when the lock mutex +** is held. +** +** i.e. mutex's must be grabbed in the order "writer", "queue", "lock". +** +** File system operations (invoked by SQLite thread): +** +** xOpen +** xDelete +** xFileExists +** +** File handle operations (invoked by SQLite thread): +** +** asyncWrite, asyncClose, asyncTruncate, asyncSync +** +** The operations above add an entry to the global write-op list. They +** prepare the entry, acquire the async.queueMutex momentarily while +** list pointers are manipulated to insert the new entry, then release +** the mutex and signal the writer thread to wake up in case it happens +** to be asleep. +** +** +** asyncRead, asyncFileSize. +** +** Read operations. Both of these read from both the underlying file +** first then adjust their result based on pending writes in the +** write-op queue. So async.queueMutex is held for the duration +** of these operations to prevent other threads from changing the +** queue in mid operation. +** +** +** asyncLock, asyncUnlock, asyncCheckReservedLock +** +** These primitives implement in-process locking using a hash table +** on the file name. Files are locked correctly for connections coming +** from the same process. But other processes cannot see these locks +** and will therefore not honor them. +** +** +** The writer thread: +** +** The async.writerMutex is used to make sure only there is only +** a single writer thread running at a time. +** +** Inside the writer thread is a loop that works like this: +** +** WHILE (write-op list is not empty) +** Do IO operation at head of write-op list +** Remove entry from head of write-op list +** END WHILE +** +** The async.queueMutex is always held during the test, and when the entry is removed from the head +** of the write-op list. Sometimes it is held for the interim +** period (while the IO is performed), and sometimes it is +** relinquished. It is relinquished if (a) the IO op is an +** ASYNC_CLOSE or (b) when the file handle was opened, two of +** the underlying systems handles were opened on the same +** file-system entry. +** +** If condition (b) above is true, then one file-handle +** (AsyncFile.pBaseRead) is used exclusively by sqlite threads to read the +** file, the other (AsyncFile.pBaseWrite) by sqlite3_async_flush() +** threads to perform write() operations. This means that read +** operations are not blocked by asynchronous writes (although +** asynchronous writes may still be blocked by reads). +** +** This assumes that the OS keeps two handles open on the same file +** properly in sync. That is, any read operation that starts after a +** write operation on the same file system entry has completed returns +** data consistent with the write. We also assume that if one thread +** reads a file while another is writing it all bytes other than the +** ones actually being written contain valid data. +** +** If the above assumptions are not true, set the preprocessor symbol +** SQLITE_ASYNC_TWO_FILEHANDLES to 0. +*/ + + +#ifndef NDEBUG +# define TESTONLY( X ) X +#else +# define TESTONLY( X ) +#endif + +/* +** PORTING FUNCTIONS +** +** There are two definitions of the following functions. One for pthreads +** compatible systems and one for Win32. These functions isolate the OS +** specific code required by each platform. +** +** The system uses three mutexes and a single condition variable. To +** block on a mutex, async_mutex_enter() is called. The parameter passed +** to async_mutex_enter(), which must be one of ASYNC_MUTEX_LOCK, +** ASYNC_MUTEX_QUEUE or ASYNC_MUTEX_WRITER, identifies which of the three +** mutexes to lock. Similarly, to unlock a mutex, async_mutex_leave() is +** called with a parameter identifying the mutex being unlocked. Mutexes +** are not recursive - it is an error to call async_mutex_enter() to +** lock a mutex that is already locked, or to call async_mutex_leave() +** to unlock a mutex that is not currently locked. +** +** The async_cond_wait() and async_cond_signal() functions are modelled +** on the pthreads functions with similar names. The first parameter to +** both functions is always ASYNC_COND_QUEUE. When async_cond_wait() +** is called the mutex identified by the second parameter must be held. +** The mutex is unlocked, and the calling thread simultaneously begins +** waiting for the condition variable to be signalled by another thread. +** After another thread signals the condition variable, the calling +** thread stops waiting, locks mutex eMutex and returns. The +** async_cond_signal() function is used to signal the condition variable. +** It is assumed that the mutex used by the thread calling async_cond_wait() +** is held by the caller of async_cond_signal() (otherwise there would be +** a race condition). +** +** It is guaranteed that no other thread will call async_cond_wait() when +** there is already a thread waiting on the condition variable. +** +** The async_sched_yield() function is called to suggest to the operating +** system that it would be a good time to shift the current thread off the +** CPU. The system will still work if this function is not implemented +** (it is not currently implemented for win32), but it might be marginally +** more efficient if it is. +*/ +static void async_mutex_enter(int eMutex); +static void async_mutex_leave(int eMutex); +static void async_cond_wait(int eCond, int eMutex); +static void async_cond_signal(int eCond); +static void async_sched_yield(void); + +/* +** There are also two definitions of the following. async_os_initialize() +** is called when the asynchronous VFS is first installed, and os_shutdown() +** is called when it is uninstalled (from within sqlite3async_shutdown()). +** +** For pthreads builds, both of these functions are no-ops. For win32, +** they provide an opportunity to initialize and finalize the required +** mutex and condition variables. +** +** If async_os_initialize() returns other than zero, then the initialization +** fails and SQLITE_ERROR is returned to the user. +*/ +static int async_os_initialize(void); +static void async_os_shutdown(void); + +/* Values for use as the 'eMutex' argument of the above functions. The +** integer values assigned to these constants are important for assert() +** statements that verify that mutexes are locked in the correct order. +** Specifically, it is unsafe to try to lock mutex N while holding a lock +** on mutex M if (M<=N). +*/ +#define ASYNC_MUTEX_LOCK 0 +#define ASYNC_MUTEX_QUEUE 1 +#define ASYNC_MUTEX_WRITER 2 + +/* Values for use as the 'eCond' argument of the above functions. */ +#define ASYNC_COND_QUEUE 0 + +/************************************************************************* +** Start of OS specific code. +*/ +#if SQLITE_OS_WIN || defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) + +#include + +/* The following block contains the win32 specific code. */ + +#define mutex_held(X) (GetCurrentThreadId()==primitives.aHolder[X]) + +static struct AsyncPrimitives { + int isInit; + DWORD aHolder[3]; + CRITICAL_SECTION aMutex[3]; + HANDLE aCond[1]; +} primitives = { 0 }; + +static int async_os_initialize(void){ + if( !primitives.isInit ){ + primitives.aCond[0] = CreateEvent(NULL, TRUE, FALSE, 0); + if( primitives.aCond[0]==NULL ){ + return 1; + } + InitializeCriticalSection(&primitives.aMutex[0]); + InitializeCriticalSection(&primitives.aMutex[1]); + InitializeCriticalSection(&primitives.aMutex[2]); + primitives.isInit = 1; + } + return 0; +} +static void async_os_shutdown(void){ + if( primitives.isInit ){ + DeleteCriticalSection(&primitives.aMutex[0]); + DeleteCriticalSection(&primitives.aMutex[1]); + DeleteCriticalSection(&primitives.aMutex[2]); + CloseHandle(primitives.aCond[0]); + primitives.isInit = 0; + } +} + +/* The following block contains the Win32 specific code. */ +static void async_mutex_enter(int eMutex){ + assert( eMutex==0 || eMutex==1 || eMutex==2 ); + assert( eMutex!=2 || (!mutex_held(0) && !mutex_held(1) && !mutex_held(2)) ); + assert( eMutex!=1 || (!mutex_held(0) && !mutex_held(1)) ); + assert( eMutex!=0 || (!mutex_held(0)) ); + EnterCriticalSection(&primitives.aMutex[eMutex]); + TESTONLY( primitives.aHolder[eMutex] = GetCurrentThreadId(); ) +} +static void async_mutex_leave(int eMutex){ + assert( eMutex==0 || eMutex==1 || eMutex==2 ); + assert( mutex_held(eMutex) ); + TESTONLY( primitives.aHolder[eMutex] = 0; ) + LeaveCriticalSection(&primitives.aMutex[eMutex]); +} +static void async_cond_wait(int eCond, int eMutex){ + ResetEvent(primitives.aCond[eCond]); + async_mutex_leave(eMutex); + WaitForSingleObject(primitives.aCond[eCond], INFINITE); + async_mutex_enter(eMutex); +} +static void async_cond_signal(int eCond){ + assert( mutex_held(ASYNC_MUTEX_QUEUE) ); + SetEvent(primitives.aCond[eCond]); +} +static void async_sched_yield(void){ + Sleep(0); +} +#else + +/* The following block contains the pthreads specific code. */ +#include +#include + +#define mutex_held(X) pthread_equal(primitives.aHolder[X], pthread_self()) + +static int async_os_initialize(void) {return 0;} +static void async_os_shutdown(void) {} + +static struct AsyncPrimitives { + pthread_mutex_t aMutex[3]; + pthread_cond_t aCond[1]; + pthread_t aHolder[3]; +} primitives = { + { PTHREAD_MUTEX_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER + } , { + PTHREAD_COND_INITIALIZER + } , { 0, 0, 0 } +}; + +static void async_mutex_enter(int eMutex){ + assert( eMutex==0 || eMutex==1 || eMutex==2 ); + assert( eMutex!=2 || (!mutex_held(0) && !mutex_held(1) && !mutex_held(2)) ); + assert( eMutex!=1 || (!mutex_held(0) && !mutex_held(1)) ); + assert( eMutex!=0 || (!mutex_held(0)) ); + pthread_mutex_lock(&primitives.aMutex[eMutex]); + TESTONLY( primitives.aHolder[eMutex] = pthread_self(); ) +} +static void async_mutex_leave(int eMutex){ + assert( eMutex==0 || eMutex==1 || eMutex==2 ); + assert( mutex_held(eMutex) ); + TESTONLY( primitives.aHolder[eMutex] = 0; ) + pthread_mutex_unlock(&primitives.aMutex[eMutex]); +} +static void async_cond_wait(int eCond, int eMutex){ + assert( eMutex==0 || eMutex==1 || eMutex==2 ); + assert( mutex_held(eMutex) ); + TESTONLY( primitives.aHolder[eMutex] = 0; ) + pthread_cond_wait(&primitives.aCond[eCond], &primitives.aMutex[eMutex]); + TESTONLY( primitives.aHolder[eMutex] = pthread_self(); ) +} +static void async_cond_signal(int eCond){ + assert( mutex_held(ASYNC_MUTEX_QUEUE) ); + pthread_cond_signal(&primitives.aCond[eCond]); +} +static void async_sched_yield(void){ + sched_yield(); +} +#endif +/* +** End of OS specific code. +*************************************************************************/ + +#define assert_mutex_is_held(X) assert( mutex_held(X) ) + + +#ifndef SQLITE_ASYNC_TWO_FILEHANDLES +/* #define SQLITE_ASYNC_TWO_FILEHANDLES 0 */ +#define SQLITE_ASYNC_TWO_FILEHANDLES 1 +#endif + +/* +** State information is held in the static variable "async" defined +** as the following structure. +** +** Both async.ioError and async.nFile are protected by async.queueMutex. +*/ +static struct TestAsyncStaticData { + AsyncWrite *pQueueFirst; /* Next write operation to be processed */ + AsyncWrite *pQueueLast; /* Last write operation on the list */ + AsyncLock *pLock; /* Linked list of all AsyncLock structures */ + volatile int ioDelay; /* Extra delay between write operations */ + volatile int eHalt; /* One of the SQLITEASYNC_HALT_XXX values */ + volatile int bLockFiles; /* Current value of "lockfiles" parameter */ + int ioError; /* True if an IO error has occurred */ + int nFile; /* Number of open files (from sqlite pov) */ +} async = { 0,0,0,0,0,1,0,0 }; + +/* Possible values of AsyncWrite.op */ +#define ASYNC_NOOP 0 +#define ASYNC_WRITE 1 +#define ASYNC_SYNC 2 +#define ASYNC_TRUNCATE 3 +#define ASYNC_CLOSE 4 +#define ASYNC_DELETE 5 +#define ASYNC_OPENEXCLUSIVE 6 +#define ASYNC_UNLOCK 7 + +/* Names of opcodes. Used for debugging only. +** Make sure these stay in sync with the macros above! +*/ +static const char *azOpcodeName[] = { + "NOOP", "WRITE", "SYNC", "TRUNCATE", "CLOSE", "DELETE", "OPENEX", "UNLOCK" +}; + +/* +** Entries on the write-op queue are instances of the AsyncWrite +** structure, defined here. +** +** The interpretation of the iOffset and nByte variables varies depending +** on the value of AsyncWrite.op: +** +** ASYNC_NOOP: +** No values used. +** +** ASYNC_WRITE: +** iOffset -> Offset in file to write to. +** nByte -> Number of bytes of data to write (pointed to by zBuf). +** +** ASYNC_SYNC: +** nByte -> flags to pass to sqlite3OsSync(). +** +** ASYNC_TRUNCATE: +** iOffset -> Size to truncate file to. +** nByte -> Unused. +** +** ASYNC_CLOSE: +** iOffset -> Unused. +** nByte -> Unused. +** +** ASYNC_DELETE: +** iOffset -> Contains the "syncDir" flag. +** nByte -> Number of bytes of zBuf points to (file name). +** +** ASYNC_OPENEXCLUSIVE: +** iOffset -> Value of "delflag". +** nByte -> Number of bytes of zBuf points to (file name). +** +** ASYNC_UNLOCK: +** nByte -> Argument to sqlite3OsUnlock(). +** +** +** For an ASYNC_WRITE operation, zBuf points to the data to write to the file. +** This space is sqlite3_malloc()d along with the AsyncWrite structure in a +** single blob, so is deleted when sqlite3_free() is called on the parent +** structure. +*/ +struct AsyncWrite { + AsyncFileData *pFileData; /* File to write data to or sync */ + int op; /* One of ASYNC_xxx etc. */ + sqlite_int64 iOffset; /* See above */ + int nByte; /* See above */ + char *zBuf; /* Data to write to file (or NULL if op!=ASYNC_WRITE) */ + AsyncWrite *pNext; /* Next write operation (to any file) */ +}; + +/* +** An instance of this structure is created for each distinct open file +** (i.e. if two handles are opened on the one file, only one of these +** structures is allocated) and stored in the async.aLock hash table. The +** keys for async.aLock are the full pathnames of the opened files. +** +** AsyncLock.pList points to the head of a linked list of AsyncFileLock +** structures, one for each handle currently open on the file. +** +** If the opened file is not a main-database (the SQLITE_OPEN_MAIN_DB is +** not passed to the sqlite3OsOpen() call), or if async.bLockFiles is +** false, variables AsyncLock.pFile and AsyncLock.eLock are never used. +** Otherwise, pFile is a file handle opened on the file in question and +** used to obtain the file-system locks required by database connections +** within this process. +** +** See comments above the asyncLock() function for more details on +** the implementation of database locking used by this backend. +*/ +struct AsyncLock { + char *zFile; + int nFile; + sqlite3_file *pFile; + int eLock; + AsyncFileLock *pList; + AsyncLock *pNext; /* Next in linked list headed by async.pLock */ +}; + +/* +** An instance of the following structure is allocated along with each +** AsyncFileData structure (see AsyncFileData.lock), but is only used if the +** file was opened with the SQLITE_OPEN_MAIN_DB. +*/ +struct AsyncFileLock { + int eLock; /* Internally visible lock state (sqlite pov) */ + int eAsyncLock; /* Lock-state with write-queue unlock */ + AsyncFileLock *pNext; +}; + +/* +** The AsyncFile structure is a subclass of sqlite3_file used for +** asynchronous IO. +** +** All of the actual data for the structure is stored in the structure +** pointed to by AsyncFile.pData, which is allocated as part of the +** sqlite3OsOpen() using sqlite3_malloc(). The reason for this is that the +** lifetime of the AsyncFile structure is ended by the caller after OsClose() +** is called, but the data in AsyncFileData may be required by the +** writer thread after that point. +*/ +struct AsyncFile { + sqlite3_io_methods *pMethod; + AsyncFileData *pData; +}; +struct AsyncFileData { + char *zName; /* Underlying OS filename - used for debugging */ + int nName; /* Number of characters in zName */ + sqlite3_file *pBaseRead; /* Read handle to the underlying Os file */ + sqlite3_file *pBaseWrite; /* Write handle to the underlying Os file */ + AsyncFileLock lock; /* Lock state for this handle */ + AsyncLock *pLock; /* AsyncLock object for this file system entry */ + AsyncWrite closeOp; /* Preallocated close operation */ +}; + +/* +** Add an entry to the end of the global write-op list. pWrite should point +** to an AsyncWrite structure allocated using sqlite3_malloc(). The writer +** thread will call sqlite3_free() to free the structure after the specified +** operation has been completed. +** +** Once an AsyncWrite structure has been added to the list, it becomes the +** property of the writer thread and must not be read or modified by the +** caller. +*/ +static void addAsyncWrite(AsyncWrite *pWrite){ + /* We must hold the queue mutex in order to modify the queue pointers */ + if( pWrite->op!=ASYNC_UNLOCK ){ + async_mutex_enter(ASYNC_MUTEX_QUEUE); + } + + /* Add the record to the end of the write-op queue */ + assert( !pWrite->pNext ); + if( async.pQueueLast ){ + assert( async.pQueueFirst ); + async.pQueueLast->pNext = pWrite; + }else{ + async.pQueueFirst = pWrite; + } + async.pQueueLast = pWrite; + ASYNC_TRACE(("PUSH %p (%s %s %d)\n", pWrite, azOpcodeName[pWrite->op], + pWrite->pFileData ? pWrite->pFileData->zName : "-", pWrite->iOffset)); + + if( pWrite->op==ASYNC_CLOSE ){ + async.nFile--; + } + + /* The writer thread might have been idle because there was nothing + ** on the write-op queue for it to do. So wake it up. */ + async_cond_signal(ASYNC_COND_QUEUE); + + /* Drop the queue mutex */ + if( pWrite->op!=ASYNC_UNLOCK ){ + async_mutex_leave(ASYNC_MUTEX_QUEUE); + } +} + +/* +** Increment async.nFile in a thread-safe manner. +*/ +static void incrOpenFileCount(void){ + /* We must hold the queue mutex in order to modify async.nFile */ + async_mutex_enter(ASYNC_MUTEX_QUEUE); + if( async.nFile==0 ){ + async.ioError = SQLITE_OK; + } + async.nFile++; + async_mutex_leave(ASYNC_MUTEX_QUEUE); +} + +/* +** This is a utility function to allocate and populate a new AsyncWrite +** structure and insert it (via addAsyncWrite() ) into the global list. +*/ +static int addNewAsyncWrite( + AsyncFileData *pFileData, + int op, + sqlite3_int64 iOffset, + int nByte, + const char *zByte +){ + AsyncWrite *p; + if( op!=ASYNC_CLOSE && async.ioError ){ + return async.ioError; + } + p = sqlite3_malloc(sizeof(AsyncWrite) + (zByte?nByte:0)); + if( !p ){ + /* The upper layer does not expect operations like OsWrite() to + ** return SQLITE_NOMEM. This is partly because under normal conditions + ** SQLite is required to do rollback without calling malloc(). So + ** if malloc() fails here, treat it as an I/O error. The above + ** layer knows how to handle that. + */ + return SQLITE_IOERR; + } + p->op = op; + p->iOffset = iOffset; + p->nByte = nByte; + p->pFileData = pFileData; + p->pNext = 0; + if( zByte ){ + p->zBuf = (char *)&p[1]; + memcpy(p->zBuf, zByte, nByte); + }else{ + p->zBuf = 0; + } + addAsyncWrite(p); + return SQLITE_OK; +} + +/* +** Close the file. This just adds an entry to the write-op list, the file is +** not actually closed. +*/ +static int asyncClose(sqlite3_file *pFile){ + AsyncFileData *p = ((AsyncFile *)pFile)->pData; + + /* Unlock the file, if it is locked */ + async_mutex_enter(ASYNC_MUTEX_LOCK); + p->lock.eLock = 0; + async_mutex_leave(ASYNC_MUTEX_LOCK); + + addAsyncWrite(&p->closeOp); + return SQLITE_OK; +} + +/* +** Implementation of sqlite3OsWrite() for asynchronous files. Instead of +** writing to the underlying file, this function adds an entry to the end of +** the global AsyncWrite list. Either SQLITE_OK or SQLITE_NOMEM may be +** returned. +*/ +static int asyncWrite( + sqlite3_file *pFile, + const void *pBuf, + int amt, + sqlite3_int64 iOff +){ + AsyncFileData *p = ((AsyncFile *)pFile)->pData; + return addNewAsyncWrite(p, ASYNC_WRITE, iOff, amt, pBuf); +} + +/* +** Read data from the file. First we read from the filesystem, then adjust +** the contents of the buffer based on ASYNC_WRITE operations in the +** write-op queue. +** +** This method holds the mutex from start to finish. +*/ +static int asyncRead( + sqlite3_file *pFile, + void *zOut, + int iAmt, + sqlite3_int64 iOffset +){ + AsyncFileData *p = ((AsyncFile *)pFile)->pData; + int rc = SQLITE_OK; + sqlite3_int64 filesize = 0; + sqlite3_file *pBase = p->pBaseRead; + sqlite3_int64 iAmt64 = (sqlite3_int64)iAmt; + + /* Grab the write queue mutex for the duration of the call */ + async_mutex_enter(ASYNC_MUTEX_QUEUE); + + /* If an I/O error has previously occurred in this virtual file + ** system, then all subsequent operations fail. + */ + if( async.ioError!=SQLITE_OK ){ + rc = async.ioError; + goto asyncread_out; + } + + if( pBase->pMethods ){ + sqlite3_int64 nRead; + rc = pBase->pMethods->xFileSize(pBase, &filesize); + if( rc!=SQLITE_OK ){ + goto asyncread_out; + } + nRead = MIN(filesize - iOffset, iAmt64); + if( nRead>0 ){ + rc = pBase->pMethods->xRead(pBase, zOut, (int)nRead, iOffset); + ASYNC_TRACE(("READ %s %d bytes at %d\n", p->zName, nRead, iOffset)); + } + } + + if( rc==SQLITE_OK ){ + AsyncWrite *pWrite; + char *zName = p->zName; + + for(pWrite=async.pQueueFirst; pWrite; pWrite = pWrite->pNext){ + if( pWrite->op==ASYNC_WRITE && ( + (pWrite->pFileData==p) || + (zName && pWrite->pFileData->zName==zName) + )){ + sqlite3_int64 nCopy; + sqlite3_int64 nByte64 = (sqlite3_int64)pWrite->nByte; + + /* Set variable iBeginIn to the offset in buffer pWrite->zBuf[] from + ** which data should be copied. Set iBeginOut to the offset within + ** the output buffer to which data should be copied. If either of + ** these offsets is a negative number, set them to 0. + */ + sqlite3_int64 iBeginOut = (pWrite->iOffset-iOffset); + sqlite3_int64 iBeginIn = -iBeginOut; + if( iBeginIn<0 ) iBeginIn = 0; + if( iBeginOut<0 ) iBeginOut = 0; + + filesize = MAX(filesize, pWrite->iOffset+nByte64); + + nCopy = MIN(nByte64-iBeginIn, iAmt64-iBeginOut); + if( nCopy>0 ){ + memcpy(&((char *)zOut)[iBeginOut], &pWrite->zBuf[iBeginIn], (size_t)nCopy); + ASYNC_TRACE(("OVERREAD %d bytes at %d\n", nCopy, iBeginOut+iOffset)); + } + } + } + } + +asyncread_out: + async_mutex_leave(ASYNC_MUTEX_QUEUE); + if( rc==SQLITE_OK && filesize<(iOffset+iAmt) ){ + rc = SQLITE_IOERR_SHORT_READ; + } + return rc; +} + +/* +** Truncate the file to nByte bytes in length. This just adds an entry to +** the write-op list, no IO actually takes place. +*/ +static int asyncTruncate(sqlite3_file *pFile, sqlite3_int64 nByte){ + AsyncFileData *p = ((AsyncFile *)pFile)->pData; + return addNewAsyncWrite(p, ASYNC_TRUNCATE, nByte, 0, 0); +} + +/* +** Sync the file. This just adds an entry to the write-op list, the +** sync() is done later by sqlite3_async_flush(). +*/ +static int asyncSync(sqlite3_file *pFile, int flags){ + AsyncFileData *p = ((AsyncFile *)pFile)->pData; + return addNewAsyncWrite(p, ASYNC_SYNC, 0, flags, 0); +} + +/* +** Read the size of the file. First we read the size of the file system +** entry, then adjust for any ASYNC_WRITE or ASYNC_TRUNCATE operations +** currently in the write-op list. +** +** This method holds the mutex from start to finish. +*/ +int asyncFileSize(sqlite3_file *pFile, sqlite3_int64 *piSize){ + AsyncFileData *p = ((AsyncFile *)pFile)->pData; + int rc = SQLITE_OK; + sqlite3_int64 s = 0; + sqlite3_file *pBase; + + async_mutex_enter(ASYNC_MUTEX_QUEUE); + + /* Read the filesystem size from the base file. If pMethods is NULL, this + ** means the file hasn't been opened yet. In this case all relevant data + ** must be in the write-op queue anyway, so we can omit reading from the + ** file-system. + */ + pBase = p->pBaseRead; + if( pBase->pMethods ){ + rc = pBase->pMethods->xFileSize(pBase, &s); + } + + if( rc==SQLITE_OK ){ + AsyncWrite *pWrite; + for(pWrite=async.pQueueFirst; pWrite; pWrite = pWrite->pNext){ + if( pWrite->op==ASYNC_DELETE + && p->zName + && strcmp(p->zName, pWrite->zBuf)==0 + ){ + s = 0; + }else if( pWrite->pFileData && ( + (pWrite->pFileData==p) + || (p->zName && pWrite->pFileData->zName==p->zName) + )){ + switch( pWrite->op ){ + case ASYNC_WRITE: + s = MAX(pWrite->iOffset + (sqlite3_int64)(pWrite->nByte), s); + break; + case ASYNC_TRUNCATE: + s = MIN(s, pWrite->iOffset); + break; + } + } + } + *piSize = s; + } + async_mutex_leave(ASYNC_MUTEX_QUEUE); + return rc; +} + +/* +** Lock or unlock the actual file-system entry. +*/ +static int getFileLock(AsyncLock *pLock){ + int rc = SQLITE_OK; + AsyncFileLock *pIter; + int eRequired = 0; + + if( pLock->pFile ){ + for(pIter=pLock->pList; pIter; pIter=pIter->pNext){ + assert(pIter->eAsyncLock>=pIter->eLock); + if( pIter->eAsyncLock>eRequired ){ + eRequired = pIter->eAsyncLock; + assert(eRequired>=0 && eRequired<=SQLITE_LOCK_EXCLUSIVE); + } + } + + if( eRequired>pLock->eLock ){ + rc = pLock->pFile->pMethods->xLock(pLock->pFile, eRequired); + if( rc==SQLITE_OK ){ + pLock->eLock = eRequired; + } + } + else if( eRequiredeLock && eRequired<=SQLITE_LOCK_SHARED ){ + rc = pLock->pFile->pMethods->xUnlock(pLock->pFile, eRequired); + if( rc==SQLITE_OK ){ + pLock->eLock = eRequired; + } + } + } + + return rc; +} + +/* +** Return the AsyncLock structure from the global async.pLock list +** associated with the file-system entry identified by path zName +** (a string of nName bytes). If no such structure exists, return 0. +*/ +static AsyncLock *findLock(const char *zName, int nName){ + AsyncLock *p = async.pLock; + while( p && (p->nFile!=nName || memcmp(p->zFile, zName, nName)) ){ + p = p->pNext; + } + return p; +} + +/* +** The following two methods - asyncLock() and asyncUnlock() - are used +** to obtain and release locks on database files opened with the +** asynchronous backend. +*/ +static int asyncLock(sqlite3_file *pFile, int eLock){ + int rc = SQLITE_OK; + AsyncFileData *p = ((AsyncFile *)pFile)->pData; + + if( p->zName ){ + async_mutex_enter(ASYNC_MUTEX_LOCK); + if( p->lock.eLockpLock; + AsyncFileLock *pIter; + assert(pLock && pLock->pList); + for(pIter=pLock->pList; pIter; pIter=pIter->pNext){ + if( pIter!=&p->lock && ( + (eLock==SQLITE_LOCK_EXCLUSIVE && pIter->eLock>=SQLITE_LOCK_SHARED) || + (eLock==SQLITE_LOCK_PENDING && pIter->eLock>=SQLITE_LOCK_RESERVED) || + (eLock==SQLITE_LOCK_RESERVED && pIter->eLock>=SQLITE_LOCK_RESERVED) || + (eLock==SQLITE_LOCK_SHARED && pIter->eLock>=SQLITE_LOCK_PENDING) + )){ + rc = SQLITE_BUSY; + } + } + if( rc==SQLITE_OK ){ + p->lock.eLock = eLock; + p->lock.eAsyncLock = MAX(p->lock.eAsyncLock, eLock); + } + assert(p->lock.eAsyncLock>=p->lock.eLock); + if( rc==SQLITE_OK ){ + rc = getFileLock(pLock); + } + } + async_mutex_leave(ASYNC_MUTEX_LOCK); + } + + ASYNC_TRACE(("LOCK %d (%s) rc=%d\n", eLock, p->zName, rc)); + return rc; +} +static int asyncUnlock(sqlite3_file *pFile, int eLock){ + int rc = SQLITE_OK; + AsyncFileData *p = ((AsyncFile *)pFile)->pData; + if( p->zName ){ + AsyncFileLock *pLock = &p->lock; + async_mutex_enter(ASYNC_MUTEX_QUEUE); + async_mutex_enter(ASYNC_MUTEX_LOCK); + pLock->eLock = MIN(pLock->eLock, eLock); + rc = addNewAsyncWrite(p, ASYNC_UNLOCK, 0, eLock, 0); + async_mutex_leave(ASYNC_MUTEX_LOCK); + async_mutex_leave(ASYNC_MUTEX_QUEUE); + } + return rc; +} + +/* +** This function is called when the pager layer first opens a database file +** and is checking for a hot-journal. +*/ +static int asyncCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + int ret = 0; + AsyncFileLock *pIter; + AsyncFileData *p = ((AsyncFile *)pFile)->pData; + + async_mutex_enter(ASYNC_MUTEX_LOCK); + for(pIter=p->pLock->pList; pIter; pIter=pIter->pNext){ + if( pIter->eLock>=SQLITE_LOCK_RESERVED ){ + ret = 1; + break; + } + } + async_mutex_leave(ASYNC_MUTEX_LOCK); + + ASYNC_TRACE(("CHECK-LOCK %d (%s)\n", ret, p->zName)); + *pResOut = ret; + return SQLITE_OK; +} + +/* +** sqlite3_file_control() implementation. +*/ +static int asyncFileControl(sqlite3_file *id, int op, void *pArg){ + switch( op ){ + case SQLITE_FCNTL_LOCKSTATE: { + async_mutex_enter(ASYNC_MUTEX_LOCK); + *(int*)pArg = ((AsyncFile*)id)->pData->lock.eLock; + async_mutex_leave(ASYNC_MUTEX_LOCK); + return SQLITE_OK; + } + } + return SQLITE_NOTFOUND; +} + +/* +** Return the device characteristics and sector-size of the device. It +** is tricky to implement these correctly, as this backend might +** not have an open file handle at this point. +*/ +static int asyncSectorSize(sqlite3_file *pFile){ + UNUSED_PARAMETER(pFile); + return 512; +} +static int asyncDeviceCharacteristics(sqlite3_file *pFile){ + UNUSED_PARAMETER(pFile); + return 0; +} + +static int unlinkAsyncFile(AsyncFileData *pData){ + AsyncFileLock **ppIter; + int rc = SQLITE_OK; + + if( pData->zName ){ + AsyncLock *pLock = pData->pLock; + for(ppIter=&pLock->pList; *ppIter; ppIter=&((*ppIter)->pNext)){ + if( (*ppIter)==&pData->lock ){ + *ppIter = pData->lock.pNext; + break; + } + } + if( !pLock->pList ){ + AsyncLock **pp; + if( pLock->pFile ){ + pLock->pFile->pMethods->xClose(pLock->pFile); + } + for(pp=&async.pLock; *pp!=pLock; pp=&((*pp)->pNext)); + *pp = pLock->pNext; + sqlite3_free(pLock); + }else{ + rc = getFileLock(pLock); + } + } + + return rc; +} + +/* +** The parameter passed to this function is a copy of a 'flags' parameter +** passed to this modules xOpen() method. This function returns true +** if the file should be opened asynchronously, or false if it should +** be opened immediately. +** +** If the file is to be opened asynchronously, then asyncOpen() will add +** an entry to the event queue and the file will not actually be opened +** until the event is processed. Otherwise, the file is opened directly +** by the caller. +*/ +static int doAsynchronousOpen(int flags){ + return (flags&SQLITE_OPEN_CREATE) && ( + (flags&SQLITE_OPEN_MAIN_JOURNAL) || + (flags&SQLITE_OPEN_TEMP_JOURNAL) || + (flags&SQLITE_OPEN_DELETEONCLOSE) + ); +} + +/* +** Open a file. +*/ +static int asyncOpen( + sqlite3_vfs *pAsyncVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + static sqlite3_io_methods async_methods = { + 1, /* iVersion */ + asyncClose, /* xClose */ + asyncRead, /* xRead */ + asyncWrite, /* xWrite */ + asyncTruncate, /* xTruncate */ + asyncSync, /* xSync */ + asyncFileSize, /* xFileSize */ + asyncLock, /* xLock */ + asyncUnlock, /* xUnlock */ + asyncCheckReservedLock, /* xCheckReservedLock */ + asyncFileControl, /* xFileControl */ + asyncSectorSize, /* xSectorSize */ + asyncDeviceCharacteristics /* xDeviceCharacteristics */ + }; + + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + AsyncFile *p = (AsyncFile *)pFile; + int nName = 0; + int rc = SQLITE_OK; + int nByte; + AsyncFileData *pData; + AsyncLock *pLock = 0; + char *z; + int isAsyncOpen = doAsynchronousOpen(flags); + + /* If zName is NULL, then the upper layer is requesting an anonymous file. + ** Otherwise, allocate enough space to make a copy of the file name (along + ** with the second nul-terminator byte required by xOpen). + */ + if( zName ){ + nName = (int)strlen(zName); + } + + nByte = ( + sizeof(AsyncFileData) + /* AsyncFileData structure */ + 2 * pVfs->szOsFile + /* AsyncFileData.pBaseRead and pBaseWrite */ + nName + 2 /* AsyncFileData.zName */ + ); + z = sqlite3_malloc(nByte); + if( !z ){ + return SQLITE_NOMEM; + } + memset(z, 0, nByte); + pData = (AsyncFileData*)z; + z += sizeof(pData[0]); + pData->pBaseRead = (sqlite3_file*)z; + z += pVfs->szOsFile; + pData->pBaseWrite = (sqlite3_file*)z; + pData->closeOp.pFileData = pData; + pData->closeOp.op = ASYNC_CLOSE; + + if( zName ){ + z += pVfs->szOsFile; + pData->zName = z; + pData->nName = nName; + memcpy(pData->zName, zName, nName); + } + + if( !isAsyncOpen ){ + int flagsout; + rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseRead, flags, &flagsout); + if( rc==SQLITE_OK + && (flagsout&SQLITE_OPEN_READWRITE) + && (flags&SQLITE_OPEN_EXCLUSIVE)==0 + ){ + rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseWrite, flags, 0); + } + if( pOutFlags ){ + *pOutFlags = flagsout; + } + } + + async_mutex_enter(ASYNC_MUTEX_LOCK); + + if( zName && rc==SQLITE_OK ){ + pLock = findLock(pData->zName, pData->nName); + if( !pLock ){ + int nByte = pVfs->szOsFile + sizeof(AsyncLock) + pData->nName + 1; + pLock = (AsyncLock *)sqlite3_malloc(nByte); + if( pLock ){ + memset(pLock, 0, nByte); + if( async.bLockFiles && (flags&SQLITE_OPEN_MAIN_DB) ){ + pLock->pFile = (sqlite3_file *)&pLock[1]; + rc = pVfs->xOpen(pVfs, pData->zName, pLock->pFile, flags, 0); + if( rc!=SQLITE_OK ){ + sqlite3_free(pLock); + pLock = 0; + } + } + if( pLock ){ + pLock->nFile = pData->nName; + pLock->zFile = &((char *)(&pLock[1]))[pVfs->szOsFile]; + memcpy(pLock->zFile, pData->zName, pLock->nFile); + pLock->pNext = async.pLock; + async.pLock = pLock; + } + }else{ + rc = SQLITE_NOMEM; + } + } + } + + if( rc==SQLITE_OK ){ + p->pMethod = &async_methods; + p->pData = pData; + + /* Link AsyncFileData.lock into the linked list of + ** AsyncFileLock structures for this file. + */ + if( zName ){ + pData->lock.pNext = pLock->pList; + pLock->pList = &pData->lock; + pData->zName = pLock->zFile; + } + }else{ + if( pData->pBaseRead->pMethods ){ + pData->pBaseRead->pMethods->xClose(pData->pBaseRead); + } + if( pData->pBaseWrite->pMethods ){ + pData->pBaseWrite->pMethods->xClose(pData->pBaseWrite); + } + sqlite3_free(pData); + } + + async_mutex_leave(ASYNC_MUTEX_LOCK); + + if( rc==SQLITE_OK ){ + pData->pLock = pLock; + } + + if( rc==SQLITE_OK && isAsyncOpen ){ + rc = addNewAsyncWrite(pData, ASYNC_OPENEXCLUSIVE, (sqlite3_int64)flags,0,0); + if( rc==SQLITE_OK ){ + if( pOutFlags ) *pOutFlags = flags; + }else{ + async_mutex_enter(ASYNC_MUTEX_LOCK); + unlinkAsyncFile(pData); + async_mutex_leave(ASYNC_MUTEX_LOCK); + sqlite3_free(pData); + } + } + if( rc!=SQLITE_OK ){ + p->pMethod = 0; + }else{ + incrOpenFileCount(); + } + + return rc; +} + +/* +** Implementation of sqlite3OsDelete. Add an entry to the end of the +** write-op queue to perform the delete. +*/ +static int asyncDelete(sqlite3_vfs *pAsyncVfs, const char *z, int syncDir){ + UNUSED_PARAMETER(pAsyncVfs); + return addNewAsyncWrite(0, ASYNC_DELETE, syncDir, (int)strlen(z)+1, z); +} + +/* +** Implementation of sqlite3OsAccess. This method holds the mutex from +** start to finish. +*/ +static int asyncAccess( + sqlite3_vfs *pAsyncVfs, + const char *zName, + int flags, + int *pResOut +){ + int rc; + int ret; + AsyncWrite *p; + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + + assert(flags==SQLITE_ACCESS_READWRITE + || flags==SQLITE_ACCESS_READ + || flags==SQLITE_ACCESS_EXISTS + ); + + async_mutex_enter(ASYNC_MUTEX_QUEUE); + rc = pVfs->xAccess(pVfs, zName, flags, &ret); + if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){ + for(p=async.pQueueFirst; p; p = p->pNext){ + if( p->op==ASYNC_DELETE && 0==strcmp(p->zBuf, zName) ){ + ret = 0; + }else if( p->op==ASYNC_OPENEXCLUSIVE + && p->pFileData->zName + && 0==strcmp(p->pFileData->zName, zName) + ){ + ret = 1; + } + } + } + ASYNC_TRACE(("ACCESS(%s): %s = %d\n", + flags==SQLITE_ACCESS_READWRITE?"read-write": + flags==SQLITE_ACCESS_READ?"read":"exists" + , zName, ret) + ); + async_mutex_leave(ASYNC_MUTEX_QUEUE); + *pResOut = ret; + return rc; +} + +/* +** Fill in zPathOut with the full path to the file identified by zPath. +*/ +static int asyncFullPathname( + sqlite3_vfs *pAsyncVfs, + const char *zPath, + int nPathOut, + char *zPathOut +){ + int rc; + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + rc = pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); + + /* Because of the way intra-process file locking works, this backend + ** needs to return a canonical path. The following block assumes the + ** file-system uses unix style paths. + */ + if( rc==SQLITE_OK ){ + int i, j; + char *z = zPathOut; + int n = (int)strlen(z); + while( n>1 && z[n-1]=='/' ){ n--; } + for(i=j=0; i0 && z[j-1]!='/' ){ j--; } + if( j>0 ){ j--; } + i += 2; + continue; + } + } + z[j++] = z[i]; + } + z[j] = 0; + } + + return rc; +} +static void *asyncDlOpen(sqlite3_vfs *pAsyncVfs, const char *zPath){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + return pVfs->xDlOpen(pVfs, zPath); +} +static void asyncDlError(sqlite3_vfs *pAsyncVfs, int nByte, char *zErrMsg){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + pVfs->xDlError(pVfs, nByte, zErrMsg); +} +static void (*asyncDlSym( + sqlite3_vfs *pAsyncVfs, + void *pHandle, + const char *zSymbol +))(void){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + return pVfs->xDlSym(pVfs, pHandle, zSymbol); +} +static void asyncDlClose(sqlite3_vfs *pAsyncVfs, void *pHandle){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + pVfs->xDlClose(pVfs, pHandle); +} +static int asyncRandomness(sqlite3_vfs *pAsyncVfs, int nByte, char *zBufOut){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + return pVfs->xRandomness(pVfs, nByte, zBufOut); +} +static int asyncSleep(sqlite3_vfs *pAsyncVfs, int nMicro){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + return pVfs->xSleep(pVfs, nMicro); +} +static int asyncCurrentTime(sqlite3_vfs *pAsyncVfs, double *pTimeOut){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; + return pVfs->xCurrentTime(pVfs, pTimeOut); +} + +static sqlite3_vfs async_vfs = { + 1, /* iVersion */ + sizeof(AsyncFile), /* szOsFile */ + 0, /* mxPathname */ + 0, /* pNext */ + SQLITEASYNC_VFSNAME, /* zName */ + 0, /* pAppData */ + asyncOpen, /* xOpen */ + asyncDelete, /* xDelete */ + asyncAccess, /* xAccess */ + asyncFullPathname, /* xFullPathname */ + asyncDlOpen, /* xDlOpen */ + asyncDlError, /* xDlError */ + asyncDlSym, /* xDlSym */ + asyncDlClose, /* xDlClose */ + asyncRandomness, /* xDlError */ + asyncSleep, /* xDlSym */ + asyncCurrentTime /* xDlClose */ +}; + +/* +** This procedure runs in a separate thread, reading messages off of the +** write queue and processing them one by one. +** +** If async.writerHaltNow is true, then this procedure exits +** after processing a single message. +** +** If async.writerHaltWhenIdle is true, then this procedure exits when +** the write queue is empty. +** +** If both of the above variables are false, this procedure runs +** indefinately, waiting for operations to be added to the write queue +** and processing them in the order in which they arrive. +** +** An artifical delay of async.ioDelay milliseconds is inserted before +** each write operation in order to simulate the effect of a slow disk. +** +** Only one instance of this procedure may be running at a time. +*/ +static void asyncWriterThread(void){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)(async_vfs.pAppData); + AsyncWrite *p = 0; + int rc = SQLITE_OK; + int holdingMutex = 0; + + async_mutex_enter(ASYNC_MUTEX_WRITER); + + while( async.eHalt!=SQLITEASYNC_HALT_NOW ){ + int doNotFree = 0; + sqlite3_file *pBase = 0; + + if( !holdingMutex ){ + async_mutex_enter(ASYNC_MUTEX_QUEUE); + } + while( (p = async.pQueueFirst)==0 ){ + if( async.eHalt!=SQLITEASYNC_HALT_NEVER ){ + async_mutex_leave(ASYNC_MUTEX_QUEUE); + break; + }else{ + ASYNC_TRACE(("IDLE\n")); + async_cond_wait(ASYNC_COND_QUEUE, ASYNC_MUTEX_QUEUE); + ASYNC_TRACE(("WAKEUP\n")); + } + } + if( p==0 ) break; + holdingMutex = 1; + + /* Right now this thread is holding the mutex on the write-op queue. + ** Variable 'p' points to the first entry in the write-op queue. In + ** the general case, we hold on to the mutex for the entire body of + ** the loop. + ** + ** However in the cases enumerated below, we relinquish the mutex, + ** perform the IO, and then re-request the mutex before removing 'p' from + ** the head of the write-op queue. The idea is to increase concurrency with + ** sqlite threads. + ** + ** * An ASYNC_CLOSE operation. + ** * An ASYNC_OPENEXCLUSIVE operation. For this one, we relinquish + ** the mutex, call the underlying xOpenExclusive() function, then + ** re-aquire the mutex before seting the AsyncFile.pBaseRead + ** variable. + ** * ASYNC_SYNC and ASYNC_WRITE operations, if + ** SQLITE_ASYNC_TWO_FILEHANDLES was set at compile time and two + ** file-handles are open for the particular file being "synced". + */ + if( async.ioError!=SQLITE_OK && p->op!=ASYNC_CLOSE ){ + p->op = ASYNC_NOOP; + } + if( p->pFileData ){ + pBase = p->pFileData->pBaseWrite; + if( + p->op==ASYNC_CLOSE || + p->op==ASYNC_OPENEXCLUSIVE || + (pBase->pMethods && (p->op==ASYNC_SYNC || p->op==ASYNC_WRITE) ) + ){ + async_mutex_leave(ASYNC_MUTEX_QUEUE); + holdingMutex = 0; + } + if( !pBase->pMethods ){ + pBase = p->pFileData->pBaseRead; + } + } + + switch( p->op ){ + case ASYNC_NOOP: + break; + + case ASYNC_WRITE: + assert( pBase ); + ASYNC_TRACE(("WRITE %s %d bytes at %d\n", + p->pFileData->zName, p->nByte, p->iOffset)); + rc = pBase->pMethods->xWrite(pBase, (void *)(p->zBuf), p->nByte, p->iOffset); + break; + + case ASYNC_SYNC: + assert( pBase ); + ASYNC_TRACE(("SYNC %s\n", p->pFileData->zName)); + rc = pBase->pMethods->xSync(pBase, p->nByte); + break; + + case ASYNC_TRUNCATE: + assert( pBase ); + ASYNC_TRACE(("TRUNCATE %s to %d bytes\n", + p->pFileData->zName, p->iOffset)); + rc = pBase->pMethods->xTruncate(pBase, p->iOffset); + break; + + case ASYNC_CLOSE: { + AsyncFileData *pData = p->pFileData; + ASYNC_TRACE(("CLOSE %s\n", p->pFileData->zName)); + if( pData->pBaseWrite->pMethods ){ + pData->pBaseWrite->pMethods->xClose(pData->pBaseWrite); + } + if( pData->pBaseRead->pMethods ){ + pData->pBaseRead->pMethods->xClose(pData->pBaseRead); + } + + /* Unlink AsyncFileData.lock from the linked list of AsyncFileLock + ** structures for this file. Obtain the async.lockMutex mutex + ** before doing so. + */ + async_mutex_enter(ASYNC_MUTEX_LOCK); + rc = unlinkAsyncFile(pData); + async_mutex_leave(ASYNC_MUTEX_LOCK); + + if( !holdingMutex ){ + async_mutex_enter(ASYNC_MUTEX_QUEUE); + holdingMutex = 1; + } + assert_mutex_is_held(ASYNC_MUTEX_QUEUE); + async.pQueueFirst = p->pNext; + sqlite3_free(pData); + doNotFree = 1; + break; + } + + case ASYNC_UNLOCK: { + AsyncWrite *pIter; + AsyncFileData *pData = p->pFileData; + int eLock = p->nByte; + + /* When a file is locked by SQLite using the async backend, it is + ** locked within the 'real' file-system synchronously. When it is + ** unlocked, an ASYNC_UNLOCK event is added to the write-queue to + ** unlock the file asynchronously. The design of the async backend + ** requires that the 'real' file-system file be locked from the + ** time that SQLite first locks it (and probably reads from it) + ** until all asynchronous write events that were scheduled before + ** SQLite unlocked the file have been processed. + ** + ** This is more complex if SQLite locks and unlocks the file multiple + ** times in quick succession. For example, if SQLite does: + ** + ** lock, write, unlock, lock, write, unlock + ** + ** Each "lock" operation locks the file immediately. Each "write" + ** and "unlock" operation adds an event to the event queue. If the + ** second "lock" operation is performed before the first "unlock" + ** operation has been processed asynchronously, then the first + ** "unlock" cannot be safely processed as is, since this would mean + ** the file was unlocked when the second "write" operation is + ** processed. To work around this, when processing an ASYNC_UNLOCK + ** operation, SQLite: + ** + ** 1) Unlocks the file to the minimum of the argument passed to + ** the xUnlock() call and the current lock from SQLite's point + ** of view, and + ** + ** 2) Only unlocks the file at all if this event is the last + ** ASYNC_UNLOCK event on this file in the write-queue. + */ + assert( holdingMutex==1 ); + assert( async.pQueueFirst==p ); + for(pIter=async.pQueueFirst->pNext; pIter; pIter=pIter->pNext){ + if( pIter->pFileData==pData && pIter->op==ASYNC_UNLOCK ) break; + } + if( !pIter ){ + async_mutex_enter(ASYNC_MUTEX_LOCK); + pData->lock.eAsyncLock = MIN( + pData->lock.eAsyncLock, MAX(pData->lock.eLock, eLock) + ); + assert(pData->lock.eAsyncLock>=pData->lock.eLock); + rc = getFileLock(pData->pLock); + async_mutex_leave(ASYNC_MUTEX_LOCK); + } + break; + } + + case ASYNC_DELETE: + ASYNC_TRACE(("DELETE %s\n", p->zBuf)); + rc = pVfs->xDelete(pVfs, p->zBuf, (int)p->iOffset); + if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK; + break; + + case ASYNC_OPENEXCLUSIVE: { + int flags = (int)p->iOffset; + AsyncFileData *pData = p->pFileData; + ASYNC_TRACE(("OPEN %s flags=%d\n", p->zBuf, (int)p->iOffset)); + assert(pData->pBaseRead->pMethods==0 && pData->pBaseWrite->pMethods==0); + rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseRead, flags, 0); + assert( holdingMutex==0 ); + async_mutex_enter(ASYNC_MUTEX_QUEUE); + holdingMutex = 1; + break; + } + + default: assert(!"Illegal value for AsyncWrite.op"); + } + + /* If we didn't hang on to the mutex during the IO op, obtain it now + ** so that the AsyncWrite structure can be safely removed from the + ** global write-op queue. + */ + if( !holdingMutex ){ + async_mutex_enter(ASYNC_MUTEX_QUEUE); + holdingMutex = 1; + } + /* ASYNC_TRACE(("UNLINK %p\n", p)); */ + if( p==async.pQueueLast ){ + async.pQueueLast = 0; + } + if( !doNotFree ){ + assert_mutex_is_held(ASYNC_MUTEX_QUEUE); + async.pQueueFirst = p->pNext; + sqlite3_free(p); + } + assert( holdingMutex ); + + /* An IO error has occurred. We cannot report the error back to the + ** connection that requested the I/O since the error happened + ** asynchronously. The connection has already moved on. There + ** really is nobody to report the error to. + ** + ** The file for which the error occurred may have been a database or + ** journal file. Regardless, none of the currently queued operations + ** associated with the same database should now be performed. Nor should + ** any subsequently requested IO on either a database or journal file + ** handle for the same database be accepted until the main database + ** file handle has been closed and reopened. + ** + ** Furthermore, no further IO should be queued or performed on any file + ** handle associated with a database that may have been part of a + ** multi-file transaction that included the database associated with + ** the IO error (i.e. a database ATTACHed to the same handle at some + ** point in time). + */ + if( rc!=SQLITE_OK ){ + async.ioError = rc; + } + + if( async.ioError && !async.pQueueFirst ){ + async_mutex_enter(ASYNC_MUTEX_LOCK); + if( 0==async.pLock ){ + async.ioError = SQLITE_OK; + } + async_mutex_leave(ASYNC_MUTEX_LOCK); + } + + /* Drop the queue mutex before continuing to the next write operation + ** in order to give other threads a chance to work with the write queue. + */ + if( !async.pQueueFirst || !async.ioError ){ + async_mutex_leave(ASYNC_MUTEX_QUEUE); + holdingMutex = 0; + if( async.ioDelay>0 ){ + pVfs->xSleep(pVfs, async.ioDelay*1000); + }else{ + async_sched_yield(); + } + } + } + + async_mutex_leave(ASYNC_MUTEX_WRITER); + return; +} + +/* +** Install the asynchronous VFS. +*/ +int sqlite3async_initialize(const char *zParent, int isDefault){ + int rc = SQLITE_OK; + if( async_vfs.pAppData==0 ){ + sqlite3_vfs *pParent = sqlite3_vfs_find(zParent); + if( !pParent || async_os_initialize() ){ + rc = SQLITE_ERROR; + }else if( SQLITE_OK!=(rc = sqlite3_vfs_register(&async_vfs, isDefault)) ){ + async_os_shutdown(); + }else{ + async_vfs.pAppData = (void *)pParent; + async_vfs.mxPathname = ((sqlite3_vfs *)async_vfs.pAppData)->mxPathname; + } + } + return rc; +} + +/* +** Uninstall the asynchronous VFS. +*/ +void sqlite3async_shutdown(void){ + if( async_vfs.pAppData ){ + async_os_shutdown(); + sqlite3_vfs_unregister((sqlite3_vfs *)&async_vfs); + async_vfs.pAppData = 0; + } +} + +/* +** Process events on the write-queue. +*/ +void sqlite3async_run(void){ + asyncWriterThread(); +} + +/* +** Control/configure the asynchronous IO system. +*/ +int sqlite3async_control(int op, ...){ + va_list ap; + va_start(ap, op); + switch( op ){ + case SQLITEASYNC_HALT: { + int eWhen = va_arg(ap, int); + if( eWhen!=SQLITEASYNC_HALT_NEVER + && eWhen!=SQLITEASYNC_HALT_NOW + && eWhen!=SQLITEASYNC_HALT_IDLE + ){ + return SQLITE_MISUSE; + } + async.eHalt = eWhen; + async_mutex_enter(ASYNC_MUTEX_QUEUE); + async_cond_signal(ASYNC_COND_QUEUE); + async_mutex_leave(ASYNC_MUTEX_QUEUE); + break; + } + + case SQLITEASYNC_DELAY: { + int iDelay = va_arg(ap, int); + if( iDelay<0 ){ + return SQLITE_MISUSE; + } + async.ioDelay = iDelay; + break; + } + + case SQLITEASYNC_LOCKFILES: { + int bLock = va_arg(ap, int); + async_mutex_enter(ASYNC_MUTEX_QUEUE); + if( async.nFile || async.pQueueFirst ){ + async_mutex_leave(ASYNC_MUTEX_QUEUE); + return SQLITE_MISUSE; + } + async.bLockFiles = bLock; + async_mutex_leave(ASYNC_MUTEX_QUEUE); + break; + } + + case SQLITEASYNC_GET_HALT: { + int *peWhen = va_arg(ap, int *); + *peWhen = async.eHalt; + break; + } + case SQLITEASYNC_GET_DELAY: { + int *piDelay = va_arg(ap, int *); + *piDelay = async.ioDelay; + break; + } + case SQLITEASYNC_GET_LOCKFILES: { + int *piDelay = va_arg(ap, int *); + *piDelay = async.bLockFiles; + break; + } + + default: + return SQLITE_ERROR; + } + return SQLITE_OK; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ASYNCIO) */ + diff --git a/components/external/SQLite-3.8.1/ext/async/sqlite3async.h b/components/external/SQLite-3.8.1/ext/async/sqlite3async.h new file mode 100644 index 0000000000000000000000000000000000000000..5b20d7189a021f50d5e534290306d78c560e4183 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/async/sqlite3async.h @@ -0,0 +1,223 @@ + +#ifndef __SQLITEASYNC_H_ +#define __SQLITEASYNC_H_ 1 + +/* +** Make sure we can call this stuff from C++. +*/ +#ifdef __cplusplus +extern "C" { +#endif + +#define SQLITEASYNC_VFSNAME "sqlite3async" + +/* +** THREAD SAFETY NOTES: +** +** Of the four API functions in this file, the following are not threadsafe: +** +** sqlite3async_initialize() +** sqlite3async_shutdown() +** +** Care must be taken that neither of these functions is called while +** another thread may be calling either any sqlite3async_XXX() function +** or an sqlite3_XXX() API function related to a database handle that +** is using the asynchronous IO VFS. +** +** These functions: +** +** sqlite3async_run() +** sqlite3async_control() +** +** are threadsafe. It is quite safe to call either of these functions even +** if another thread may also be calling one of them or an sqlite3_XXX() +** function related to a database handle that uses the asynchronous IO VFS. +*/ + +/* +** Initialize the asynchronous IO VFS and register it with SQLite using +** sqlite3_vfs_register(). If the asynchronous VFS is already initialized +** and registered, this function is a no-op. The asynchronous IO VFS +** is registered as "sqlite3async". +** +** The asynchronous IO VFS does not make operating system IO requests +** directly. Instead, it uses an existing VFS implementation for all +** required file-system operations. If the first parameter to this function +** is NULL, then the current default VFS is used for IO. If it is not +** NULL, then it must be the name of an existing VFS. In other words, the +** first argument to this function is passed to sqlite3_vfs_find() to +** locate the VFS to use for all real IO operations. This VFS is known +** as the "parent VFS". +** +** If the second parameter to this function is non-zero, then the +** asynchronous IO VFS is registered as the default VFS for all SQLite +** database connections within the process. Otherwise, the asynchronous IO +** VFS is only used by connections opened using sqlite3_open_v2() that +** specifically request VFS "sqlite3async". +** +** If a parent VFS cannot be located, then SQLITE_ERROR is returned. +** In the unlikely event that operating system specific initialization +** fails (win32 systems create the required critical section and event +** objects within this function), then SQLITE_ERROR is also returned. +** Finally, if the call to sqlite3_vfs_register() returns an error, then +** the error code is returned to the user by this function. In all three +** of these cases, intialization has failed and the asynchronous IO VFS +** is not registered with SQLite. +** +** Otherwise, if no error occurs, SQLITE_OK is returned. +*/ +int sqlite3async_initialize(const char *zParent, int isDefault); + +/* +** This function unregisters the asynchronous IO VFS using +** sqlite3_vfs_unregister(). +** +** On win32 platforms, this function also releases the small number of +** critical section and event objects created by sqlite3async_initialize(). +*/ +void sqlite3async_shutdown(void); + +/* +** This function may only be called when the asynchronous IO VFS is +** installed (after a call to sqlite3async_initialize()). It processes +** zero or more queued write operations before returning. It is expected +** (but not required) that this function will be called by a different +** thread than those threads that use SQLite. The "background thread" +** that performs IO. +** +** How many queued write operations are performed before returning +** depends on the global setting configured by passing the SQLITEASYNC_HALT +** verb to sqlite3async_control() (see below for details). By default +** this function never returns - it processes all pending operations and +** then blocks waiting for new ones. +** +** If multiple simultaneous calls are made to sqlite3async_run() from two +** or more threads, then the calls are serialized internally. +*/ +void sqlite3async_run(void); + +/* +** This function may only be called when the asynchronous IO VFS is +** installed (after a call to sqlite3async_initialize()). It is used +** to query or configure various parameters that affect the operation +** of the asynchronous IO VFS. At present there are three parameters +** supported: +** +** * The "halt" parameter, which configures the circumstances under +** which the sqlite3async_run() parameter is configured. +** +** * The "delay" parameter. Setting the delay parameter to a non-zero +** value causes the sqlite3async_run() function to sleep for the +** configured number of milliseconds between each queued write +** operation. +** +** * The "lockfiles" parameter. This parameter determines whether or +** not the asynchronous IO VFS locks the database files it operates +** on. Disabling file locking can improve throughput. +** +** This function is always passed two arguments. When setting the value +** of a parameter, the first argument must be one of SQLITEASYNC_HALT, +** SQLITEASYNC_DELAY or SQLITEASYNC_LOCKFILES. The second argument must +** be passed the new value for the parameter as type "int". +** +** When querying the current value of a paramter, the first argument must +** be one of SQLITEASYNC_GET_HALT, GET_DELAY or GET_LOCKFILES. The second +** argument to this function must be of type (int *). The current value +** of the queried parameter is copied to the memory pointed to by the +** second argument. For example: +** +** int eCurrentHalt; +** int eNewHalt = SQLITEASYNC_HALT_IDLE; +** +** sqlite3async_control(SQLITEASYNC_HALT, eNewHalt); +** sqlite3async_control(SQLITEASYNC_GET_HALT, &eCurrentHalt); +** assert( eNewHalt==eCurrentHalt ); +** +** See below for more detail on each configuration parameter. +** +** SQLITEASYNC_HALT: +** +** This is used to set the value of the "halt" parameter. The second +** argument must be one of the SQLITEASYNC_HALT_XXX symbols defined +** below (either NEVER, IDLE and NOW). +** +** If the parameter is set to NEVER, then calls to sqlite3async_run() +** never return. This is the default setting. If the parameter is set +** to IDLE, then calls to sqlite3async_run() return as soon as the +** queue of pending write operations is empty. If the parameter is set +** to NOW, then calls to sqlite3async_run() return as quickly as +** possible, without processing any pending write requests. +** +** If an attempt is made to set this parameter to an integer value other +** than SQLITEASYNC_HALT_NEVER, IDLE or NOW, then sqlite3async_control() +** returns SQLITE_MISUSE and the current value of the parameter is not +** modified. +** +** Modifying the "halt" parameter affects calls to sqlite3async_run() +** made by other threads that are currently in progress. +** +** SQLITEASYNC_DELAY: +** +** This is used to set the value of the "delay" parameter. If set to +** a non-zero value, then after completing a pending write request, the +** sqlite3async_run() function sleeps for the configured number of +** milliseconds. +** +** If an attempt is made to set this parameter to a negative value, +** sqlite3async_control() returns SQLITE_MISUSE and the current value +** of the parameter is not modified. +** +** Modifying the "delay" parameter affects calls to sqlite3async_run() +** made by other threads that are currently in progress. +** +** SQLITEASYNC_LOCKFILES: +** +** This is used to set the value of the "lockfiles" parameter. This +** parameter must be set to either 0 or 1. If set to 1, then the +** asynchronous IO VFS uses the xLock() and xUnlock() methods of the +** parent VFS to lock database files being read and/or written. If +** the parameter is set to 0, then these locks are omitted. +** +** This parameter may only be set when there are no open database +** connections using the VFS and the queue of pending write requests +** is empty. Attempting to set it when this is not true, or to set it +** to a value other than 0 or 1 causes sqlite3async_control() to return +** SQLITE_MISUSE and the value of the parameter to remain unchanged. +** +** If this parameter is set to zero, then it is only safe to access the +** database via the asynchronous IO VFS from within a single process. If +** while writing to the database via the asynchronous IO VFS the database +** is also read or written from within another process, or via another +** connection that does not use the asynchronous IO VFS within the same +** process, the results are undefined (and may include crashes or database +** corruption). +** +** Alternatively, if this parameter is set to 1, then it is safe to access +** the database from multiple connections within multiple processes using +** either the asynchronous IO VFS or the parent VFS directly. +*/ +int sqlite3async_control(int op, ...); + +/* +** Values that can be used as the first argument to sqlite3async_control(). +*/ +#define SQLITEASYNC_HALT 1 +#define SQLITEASYNC_GET_HALT 2 +#define SQLITEASYNC_DELAY 3 +#define SQLITEASYNC_GET_DELAY 4 +#define SQLITEASYNC_LOCKFILES 5 +#define SQLITEASYNC_GET_LOCKFILES 6 + +/* +** If the first argument to sqlite3async_control() is SQLITEASYNC_HALT, +** the second argument should be one of the following. +*/ +#define SQLITEASYNC_HALT_NEVER 0 /* Never halt (default value) */ +#define SQLITEASYNC_HALT_NOW 1 /* Halt as soon as possible */ +#define SQLITEASYNC_HALT_IDLE 2 /* Halt when write-queue is empty */ + +#ifdef __cplusplus +} /* End of the 'extern "C"' block */ +#endif +#endif /* ifndef __SQLITEASYNC_H_ */ + diff --git a/components/external/SQLite-3.8.1/ext/fts1/README.txt b/components/external/SQLite-3.8.1/ext/fts1/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..292b7daa0b010adef0de29eee2b5dfd1e4daeb08 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/README.txt @@ -0,0 +1,2 @@ +This folder contains source code to the first full-text search +extension for SQLite. diff --git a/components/external/SQLite-3.8.1/ext/fts1/ft_hash.c b/components/external/SQLite-3.8.1/ext/fts1/ft_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..8b3a7064eebf95072f1e2aede53d28d108f57c5d --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/ft_hash.c @@ -0,0 +1,404 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the implementation of generic hash-tables used in SQLite. +** We've modified it slightly to serve as a standalone hash table +** implementation for the full-text indexing module. +*/ +#include +#include +#include + +#include "ft_hash.h" + +void *malloc_and_zero(int n){ + void *p = malloc(n); + if( p ){ + memset(p, 0, n); + } + return p; +} + +/* Turn bulk memory into a hash table object by initializing the +** fields of the Hash structure. +** +** "pNew" is a pointer to the hash table that is to be initialized. +** keyClass is one of the constants HASH_INT, HASH_POINTER, +** HASH_BINARY, or HASH_STRING. The value of keyClass +** determines what kind of key the hash table will use. "copyKey" is +** true if the hash table should make its own private copy of keys and +** false if it should just use the supplied pointer. CopyKey only makes +** sense for HASH_STRING and HASH_BINARY and is ignored +** for other key classes. +*/ +void HashInit(Hash *pNew, int keyClass, int copyKey){ + assert( pNew!=0 ); + assert( keyClass>=HASH_STRING && keyClass<=HASH_BINARY ); + pNew->keyClass = keyClass; +#if 0 + if( keyClass==HASH_POINTER || keyClass==HASH_INT ) copyKey = 0; +#endif + pNew->copyKey = copyKey; + pNew->first = 0; + pNew->count = 0; + pNew->htsize = 0; + pNew->ht = 0; + pNew->xMalloc = malloc_and_zero; + pNew->xFree = free; +} + +/* Remove all entries from a hash table. Reclaim all memory. +** Call this routine to delete a hash table or to reset a hash table +** to the empty state. +*/ +void HashClear(Hash *pH){ + HashElem *elem; /* For looping over all elements of the table */ + + assert( pH!=0 ); + elem = pH->first; + pH->first = 0; + if( pH->ht ) pH->xFree(pH->ht); + pH->ht = 0; + pH->htsize = 0; + while( elem ){ + HashElem *next_elem = elem->next; + if( pH->copyKey && elem->pKey ){ + pH->xFree(elem->pKey); + } + pH->xFree(elem); + elem = next_elem; + } + pH->count = 0; +} + +#if 0 /* NOT USED */ +/* +** Hash and comparison functions when the mode is HASH_INT +*/ +static int intHash(const void *pKey, int nKey){ + return nKey ^ (nKey<<8) ^ (nKey>>8); +} +static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + return n2 - n1; +} +#endif + +#if 0 /* NOT USED */ +/* +** Hash and comparison functions when the mode is HASH_POINTER +*/ +static int ptrHash(const void *pKey, int nKey){ + uptr x = Addr(pKey); + return x ^ (x<<8) ^ (x>>8); +} +static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( pKey1==pKey2 ) return 0; + if( pKey1 0 ){ + h = (h<<3) ^ h ^ *z++; + nKey--; + } + return h & 0x7fffffff; +} +static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return strncmp((const char*)pKey1,(const char*)pKey2,n1); +} + +/* +** Hash and comparison functions when the mode is HASH_BINARY +*/ +static int binHash(const void *pKey, int nKey){ + int h = 0; + const char *z = (const char *)pKey; + while( nKey-- > 0 ){ + h = (h<<3) ^ h ^ *(z++); + } + return h & 0x7fffffff; +} +static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return memcmp(pKey1,pKey2,n1); +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** The C syntax in this function definition may be unfamilar to some +** programmers, so we provide the following additional explanation: +** +** The name of the function is "hashFunction". The function takes a +** single parameter "keyClass". The return value of hashFunction() +** is a pointer to another function. Specifically, the return value +** of hashFunction() is a pointer to a function that takes two parameters +** with types "const void*" and "int" and returns an "int". +*/ +static int (*hashFunction(int keyClass))(const void*,int){ +#if 0 /* HASH_INT and HASH_POINTER are never used */ + switch( keyClass ){ + case HASH_INT: return &intHash; + case HASH_POINTER: return &ptrHash; + case HASH_STRING: return &strHash; + case HASH_BINARY: return &binHash;; + default: break; + } + return 0; +#else + if( keyClass==HASH_STRING ){ + return &strHash; + }else{ + assert( keyClass==HASH_BINARY ); + return &binHash; + } +#endif +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** For help in interpreted the obscure C code in the function definition, +** see the header comment on the previous function. +*/ +static int (*compareFunction(int keyClass))(const void*,int,const void*,int){ +#if 0 /* HASH_INT and HASH_POINTER are never used */ + switch( keyClass ){ + case HASH_INT: return &intCompare; + case HASH_POINTER: return &ptrCompare; + case HASH_STRING: return &strCompare; + case HASH_BINARY: return &binCompare; + default: break; + } + return 0; +#else + if( keyClass==HASH_STRING ){ + return &strCompare; + }else{ + assert( keyClass==HASH_BINARY ); + return &binCompare; + } +#endif +} + +/* Link an element into the hash table +*/ +static void insertElement( + Hash *pH, /* The complete hash table */ + struct _ht *pEntry, /* The entry into which pNew is inserted */ + HashElem *pNew /* The element to be inserted */ +){ + HashElem *pHead; /* First element already in pEntry */ + pHead = pEntry->chain; + if( pHead ){ + pNew->next = pHead; + pNew->prev = pHead->prev; + if( pHead->prev ){ pHead->prev->next = pNew; } + else { pH->first = pNew; } + pHead->prev = pNew; + }else{ + pNew->next = pH->first; + if( pH->first ){ pH->first->prev = pNew; } + pNew->prev = 0; + pH->first = pNew; + } + pEntry->count++; + pEntry->chain = pNew; +} + + +/* Resize the hash table so that it cantains "new_size" buckets. +** "new_size" must be a power of 2. The hash table might fail +** to resize if sqliteMalloc() fails. +*/ +static void rehash(Hash *pH, int new_size){ + struct _ht *new_ht; /* The new hash table */ + HashElem *elem, *next_elem; /* For looping over existing elements */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( (new_size & (new_size-1))==0 ); + new_ht = (struct _ht *)pH->xMalloc( new_size*sizeof(struct _ht) ); + if( new_ht==0 ) return; + if( pH->ht ) pH->xFree(pH->ht); + pH->ht = new_ht; + pH->htsize = new_size; + xHash = hashFunction(pH->keyClass); + for(elem=pH->first, pH->first=0; elem; elem = next_elem){ + int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1); + next_elem = elem->next; + insertElement(pH, &new_ht[h], elem); + } +} + +/* This function (for internal use only) locates an element in an +** hash table that matches the given key. The hash for this key has +** already been computed and is passed as the 4th parameter. +*/ +static HashElem *findElementGivenHash( + const Hash *pH, /* The pH to be searched */ + const void *pKey, /* The key we are searching for */ + int nKey, + int h /* The hash for this key. */ +){ + HashElem *elem; /* Used to loop thru the element list */ + int count; /* Number of elements left to test */ + int (*xCompare)(const void*,int,const void*,int); /* comparison function */ + + if( pH->ht ){ + struct _ht *pEntry = &pH->ht[h]; + elem = pEntry->chain; + count = pEntry->count; + xCompare = compareFunction(pH->keyClass); + while( count-- && elem ){ + if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ + return elem; + } + elem = elem->next; + } + } + return 0; +} + +/* Remove a single entry from the hash table given a pointer to that +** element and a hash on the element's key. +*/ +static void removeElementGivenHash( + Hash *pH, /* The pH containing "elem" */ + HashElem* elem, /* The element to be removed from the pH */ + int h /* Hash value for the element */ +){ + struct _ht *pEntry; + if( elem->prev ){ + elem->prev->next = elem->next; + }else{ + pH->first = elem->next; + } + if( elem->next ){ + elem->next->prev = elem->prev; + } + pEntry = &pH->ht[h]; + if( pEntry->chain==elem ){ + pEntry->chain = elem->next; + } + pEntry->count--; + if( pEntry->count<=0 ){ + pEntry->chain = 0; + } + if( pH->copyKey && elem->pKey ){ + pH->xFree(elem->pKey); + } + pH->xFree( elem ); + pH->count--; + if( pH->count<=0 ){ + assert( pH->first==0 ); + assert( pH->count==0 ); + HashClear(pH); + } +} + +/* Attempt to locate an element of the hash table pH with a key +** that matches pKey,nKey. Return the data for this element if it is +** found, or NULL if there is no match. +*/ +void *HashFind(const Hash *pH, const void *pKey, int nKey){ + int h; /* A hash on key */ + HashElem *elem; /* The element that matches key */ + int (*xHash)(const void*,int); /* The hash function */ + + if( pH==0 || pH->ht==0 ) return 0; + xHash = hashFunction(pH->keyClass); + assert( xHash!=0 ); + h = (*xHash)(pKey,nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1)); + return elem ? elem->data : 0; +} + +/* Insert an element into the hash table pH. The key is pKey,nKey +** and the data is "data". +** +** If no element exists with a matching key, then a new +** element is created. A copy of the key is made if the copyKey +** flag is set. NULL is returned. +** +** If another element already exists with the same key, then the +** new data replaces the old data and the old data is returned. +** The key is not copied in this instance. If a malloc fails, then +** the new data is returned and the hash table is unchanged. +** +** If the "data" parameter to this function is NULL, then the +** element corresponding to "key" is removed from the hash table. +*/ +void *HashInsert(Hash *pH, const void *pKey, int nKey, void *data){ + int hraw; /* Raw hash value of the key */ + int h; /* the hash of the key modulo hash table size */ + HashElem *elem; /* Used to loop thru the element list */ + HashElem *new_elem; /* New element added to the pH */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( pH!=0 ); + xHash = hashFunction(pH->keyClass); + assert( xHash!=0 ); + hraw = (*xHash)(pKey, nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + elem = findElementGivenHash(pH,pKey,nKey,h); + if( elem ){ + void *old_data = elem->data; + if( data==0 ){ + removeElementGivenHash(pH,elem,h); + }else{ + elem->data = data; + } + return old_data; + } + if( data==0 ) return 0; + new_elem = (HashElem*)pH->xMalloc( sizeof(HashElem) ); + if( new_elem==0 ) return data; + if( pH->copyKey && pKey!=0 ){ + new_elem->pKey = pH->xMalloc( nKey ); + if( new_elem->pKey==0 ){ + pH->xFree(new_elem); + return data; + } + memcpy((void*)new_elem->pKey, pKey, nKey); + }else{ + new_elem->pKey = (void*)pKey; + } + new_elem->nKey = nKey; + pH->count++; + if( pH->htsize==0 ){ + rehash(pH,8); + if( pH->htsize==0 ){ + pH->count = 0; + pH->xFree(new_elem); + return data; + } + } + if( pH->count > pH->htsize ){ + rehash(pH,pH->htsize*2); + } + assert( pH->htsize>0 ); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + insertElement(pH, &pH->ht[h], new_elem); + new_elem->data = data; + return 0; +} diff --git a/components/external/SQLite-3.8.1/ext/fts1/ft_hash.h b/components/external/SQLite-3.8.1/ext/fts1/ft_hash.h new file mode 100644 index 0000000000000000000000000000000000000000..95871a4590cd1265879f264697925e8c7726fbb8 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/ft_hash.h @@ -0,0 +1,111 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implementation +** used in SQLite. We've modified it slightly to serve as a standalone +** hash table implementation for the full-text indexing module. +** +*/ +#ifndef _HASH_H_ +#define _HASH_H_ + +/* Forward declarations of structures. */ +typedef struct Hash Hash; +typedef struct HashElem HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, many of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +*/ +struct Hash { + char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ + char copyKey; /* True if copy of key made on insert */ + int count; /* Number of entries in this table */ + HashElem *first; /* The first element of the array */ + void *(*xMalloc)(int); /* malloc() function to use */ + void (*xFree)(void *); /* free() function to use */ + int htsize; /* Number of buckets in the hash table */ + struct _ht { /* the hash table */ + int count; /* Number of entries with this hash */ + HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct HashElem { + HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + void *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** There are 4 different modes of operation for a hash table: +** +** HASH_INT nKey is used as the key and pKey is ignored. +** +** HASH_POINTER pKey is used as the key and nKey is ignored. +** +** HASH_STRING pKey points to a string that is nKey bytes long +** (including the null-terminator, if any). Case +** is respected in comparisons. +** +** HASH_BINARY pKey points to binary data nKey bytes long. +** memcmp() is used to compare keys. +** +** A copy of the key is made for HASH_STRING and HASH_BINARY +** if the copyKey parameter to HashInit is 1. +*/ +/* #define HASH_INT 1 // NOT USED */ +/* #define HASH_POINTER 2 // NOT USED */ +#define HASH_STRING 3 +#define HASH_BINARY 4 + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +void HashInit(Hash*, int keytype, int copyKey); +void *HashInsert(Hash*, const void *pKey, int nKey, void *pData); +void *HashFind(const Hash*, const void *pKey, int nKey); +void HashClear(Hash*); + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** Hash h; +** HashElem *p; +** ... +** for(p=HashFirst(&h); p; p=HashNext(p)){ +** SomeStructure *pData = HashData(p); +** // do something with pData +** } +*/ +#define HashFirst(H) ((H)->first) +#define HashNext(E) ((E)->next) +#define HashData(E) ((E)->data) +#define HashKey(E) ((E)->pKey) +#define HashKeysize(E) ((E)->nKey) + +/* +** Number of entries in a hash table +*/ +#define HashCount(H) ((H)->count) + +#endif /* _HASH_H_ */ diff --git a/components/external/SQLite-3.8.1/ext/fts1/fts1.c b/components/external/SQLite-3.8.1/ext/fts1/fts1.c new file mode 100644 index 0000000000000000000000000000000000000000..482cf759ba1d176e004dc0c33ab08a6cc8297665 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/fts1.c @@ -0,0 +1,3348 @@ +/* fts1 has a design flaw which can lead to database corruption (see +** below). It is recommended not to use it any longer, instead use +** fts3 (or higher). If you believe that your use of fts1 is safe, +** add -DSQLITE_ENABLE_BROKEN_FTS1=1 to your CFLAGS. +*/ +#if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)) \ + && !defined(SQLITE_ENABLE_BROKEN_FTS1) +#error fts1 has a design flaw and has been deprecated. +#endif +/* The flaw is that fts1 uses the content table's unaliased rowid as +** the unique docid. fts1 embeds the rowid in the index it builds, +** and expects the rowid to not change. The SQLite VACUUM operation +** will renumber such rowids, thereby breaking fts1. If you are using +** fts1 in a system which has disabled VACUUM, then you can continue +** to use it safely. Note that PRAGMA auto_vacuum does NOT disable +** VACUUM, though systems using auto_vacuum are unlikely to invoke +** VACUUM. +** +** fts1 should be safe even across VACUUM if you only insert documents +** and never delete. +*/ + +/* The author disclaims copyright to this source code. + * + * This is an SQLite module implementing full-text search. + */ + +/* +** The code in this file is only compiled if: +** +** * The FTS1 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS1 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS1 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) + +#if defined(SQLITE_ENABLE_FTS1) && !defined(SQLITE_CORE) +# define SQLITE_CORE 1 +#endif + +#include +#include +#include +#include +#include + +#include "fts1.h" +#include "fts1_hash.h" +#include "fts1_tokenizer.h" +#include "sqlite3.h" +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 + + +#if 0 +# define TRACE(A) printf A; fflush(stdout) +#else +# define TRACE(A) +#endif + +/* utility functions */ + +typedef struct StringBuffer { + int len; /* length, not including null terminator */ + int alloced; /* Space allocated for s[] */ + char *s; /* Content of the string */ +} StringBuffer; + +static void initStringBuffer(StringBuffer *sb){ + sb->len = 0; + sb->alloced = 100; + sb->s = malloc(100); + sb->s[0] = '\0'; +} + +static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){ + if( sb->len + nFrom >= sb->alloced ){ + sb->alloced = sb->len + nFrom + 100; + sb->s = realloc(sb->s, sb->alloced+1); + if( sb->s==0 ){ + initStringBuffer(sb); + return; + } + } + memcpy(sb->s + sb->len, zFrom, nFrom); + sb->len += nFrom; + sb->s[sb->len] = 0; +} +static void append(StringBuffer *sb, const char *zFrom){ + nappend(sb, zFrom, strlen(zFrom)); +} + +/* We encode variable-length integers in little-endian order using seven bits + * per byte as follows: +** +** KEY: +** A = 0xxxxxxx 7 bits of data and one flag bit +** B = 1xxxxxxx 7 bits of data and one flag bit +** +** 7 bits - A +** 14 bits - BA +** 21 bits - BBA +** and so on. +*/ + +/* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */ +#define VARINT_MAX 10 + +/* Write a 64-bit variable-length integer to memory starting at p[0]. + * The length of data written will be between 1 and VARINT_MAX bytes. + * The number of bytes written is returned. */ +static int putVarint(char *p, sqlite_int64 v){ + unsigned char *q = (unsigned char *) p; + sqlite_uint64 vu = v; + do{ + *q++ = (unsigned char) ((vu & 0x7f) | 0x80); + vu >>= 7; + }while( vu!=0 ); + q[-1] &= 0x7f; /* turn off high bit in final byte */ + assert( q - (unsigned char *)p <= VARINT_MAX ); + return (int) (q - (unsigned char *)p); +} + +/* Read a 64-bit variable-length integer from memory starting at p[0]. + * Return the number of bytes read, or 0 on error. + * The value is stored in *v. */ +static int getVarint(const char *p, sqlite_int64 *v){ + const unsigned char *q = (const unsigned char *) p; + sqlite_uint64 x = 0, y = 1; + while( (*q & 0x80) == 0x80 ){ + x += y * (*q++ & 0x7f); + y <<= 7; + if( q - (unsigned char *)p >= VARINT_MAX ){ /* bad data */ + assert( 0 ); + return 0; + } + } + x += y * (*q++); + *v = (sqlite_int64) x; + return (int) (q - (unsigned char *)p); +} + +static int getVarint32(const char *p, int *pi){ + sqlite_int64 i; + int ret = getVarint(p, &i); + *pi = (int) i; + assert( *pi==i ); + return ret; +} + +/*** Document lists *** + * + * A document list holds a sorted list of varint-encoded document IDs. + * + * A doclist with type DL_POSITIONS_OFFSETS is stored like this: + * + * array { + * varint docid; + * array { + * varint position; (delta from previous position plus POS_BASE) + * varint startOffset; (delta from previous startOffset) + * varint endOffset; (delta from startOffset) + * } + * } + * + * Here, array { X } means zero or more occurrences of X, adjacent in memory. + * + * A position list may hold positions for text in multiple columns. A position + * POS_COLUMN is followed by a varint containing the index of the column for + * following positions in the list. Any positions appearing before any + * occurrences of POS_COLUMN are for column 0. + * + * A doclist with type DL_POSITIONS is like the above, but holds only docids + * and positions without offset information. + * + * A doclist with type DL_DOCIDS is like the above, but holds only docids + * without positions or offset information. + * + * On disk, every document list has positions and offsets, so we don't bother + * to serialize a doclist's type. + * + * We don't yet delta-encode document IDs; doing so will probably be a + * modest win. + * + * NOTE(shess) I've thought of a slightly (1%) better offset encoding. + * After the first offset, estimate the next offset by using the + * current token position and the previous token position and offset, + * offset to handle some variance. So the estimate would be + * (iPosition*w->iStartOffset/w->iPosition-64), which is delta-encoded + * as normal. Offsets more than 64 chars from the estimate are + * encoded as the delta to the previous start offset + 128. An + * additional tiny increment can be gained by using the end offset of + * the previous token to make the estimate a tiny bit more precise. +*/ + +/* It is not safe to call isspace(), tolower(), or isalnum() on +** hi-bit-set characters. This is the same solution used in the +** tokenizer. +*/ +/* TODO(shess) The snippet-generation code should be using the +** tokenizer-generated tokens rather than doing its own local +** tokenization. +*/ +/* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */ +static int safe_isspace(char c){ + return (c&0x80)==0 ? isspace(c) : 0; +} +static int safe_tolower(char c){ + return (c&0x80)==0 ? tolower(c) : c; +} +static int safe_isalnum(char c){ + return (c&0x80)==0 ? isalnum(c) : 0; +} + +typedef enum DocListType { + DL_DOCIDS, /* docids only */ + DL_POSITIONS, /* docids + positions */ + DL_POSITIONS_OFFSETS /* docids + positions + offsets */ +} DocListType; + +/* +** By default, only positions and not offsets are stored in the doclists. +** To change this so that offsets are stored too, compile with +** +** -DDL_DEFAULT=DL_POSITIONS_OFFSETS +** +*/ +#ifndef DL_DEFAULT +# define DL_DEFAULT DL_POSITIONS +#endif + +typedef struct DocList { + char *pData; + int nData; + DocListType iType; + int iLastColumn; /* the last column written */ + int iLastPos; /* the last position written */ + int iLastOffset; /* the last start offset written */ +} DocList; + +enum { + POS_END = 0, /* end of this position list */ + POS_COLUMN, /* followed by new column number */ + POS_BASE +}; + +/* Initialize a new DocList to hold the given data. */ +static void docListInit(DocList *d, DocListType iType, + const char *pData, int nData){ + d->nData = nData; + if( nData>0 ){ + d->pData = malloc(nData); + memcpy(d->pData, pData, nData); + } else { + d->pData = NULL; + } + d->iType = iType; + d->iLastColumn = 0; + d->iLastPos = d->iLastOffset = 0; +} + +/* Create a new dynamically-allocated DocList. */ +static DocList *docListNew(DocListType iType){ + DocList *d = (DocList *) malloc(sizeof(DocList)); + docListInit(d, iType, 0, 0); + return d; +} + +static void docListDestroy(DocList *d){ + free(d->pData); +#ifndef NDEBUG + memset(d, 0x55, sizeof(*d)); +#endif +} + +static void docListDelete(DocList *d){ + docListDestroy(d); + free(d); +} + +static char *docListEnd(DocList *d){ + return d->pData + d->nData; +} + +/* Append a varint to a DocList's data. */ +static void appendVarint(DocList *d, sqlite_int64 i){ + char c[VARINT_MAX]; + int n = putVarint(c, i); + d->pData = realloc(d->pData, d->nData + n); + memcpy(d->pData + d->nData, c, n); + d->nData += n; +} + +static void docListAddDocid(DocList *d, sqlite_int64 iDocid){ + appendVarint(d, iDocid); + if( d->iType>=DL_POSITIONS ){ + appendVarint(d, POS_END); /* initially empty position list */ + d->iLastColumn = 0; + d->iLastPos = d->iLastOffset = 0; + } +} + +/* helper function for docListAddPos and docListAddPosOffset */ +static void addPos(DocList *d, int iColumn, int iPos){ + assert( d->nData>0 ); + --d->nData; /* remove previous terminator */ + if( iColumn!=d->iLastColumn ){ + assert( iColumn>d->iLastColumn ); + appendVarint(d, POS_COLUMN); + appendVarint(d, iColumn); + d->iLastColumn = iColumn; + d->iLastPos = d->iLastOffset = 0; + } + assert( iPos>=d->iLastPos ); + appendVarint(d, iPos-d->iLastPos+POS_BASE); + d->iLastPos = iPos; +} + +/* Add a position to the last position list in a doclist. */ +static void docListAddPos(DocList *d, int iColumn, int iPos){ + assert( d->iType==DL_POSITIONS ); + addPos(d, iColumn, iPos); + appendVarint(d, POS_END); /* add new terminator */ +} + +/* +** Add a position and starting and ending offsets to a doclist. +** +** If the doclist is setup to handle only positions, then insert +** the position only and ignore the offsets. +*/ +static void docListAddPosOffset( + DocList *d, /* Doclist under construction */ + int iColumn, /* Column the inserted term is part of */ + int iPos, /* Position of the inserted term */ + int iStartOffset, /* Starting offset of inserted term */ + int iEndOffset /* Ending offset of inserted term */ +){ + assert( d->iType>=DL_POSITIONS ); + addPos(d, iColumn, iPos); + if( d->iType==DL_POSITIONS_OFFSETS ){ + assert( iStartOffset>=d->iLastOffset ); + appendVarint(d, iStartOffset-d->iLastOffset); + d->iLastOffset = iStartOffset; + assert( iEndOffset>=iStartOffset ); + appendVarint(d, iEndOffset-iStartOffset); + } + appendVarint(d, POS_END); /* add new terminator */ +} + +/* +** A DocListReader object is a cursor into a doclist. Initialize +** the cursor to the beginning of the doclist by calling readerInit(). +** Then use routines +** +** peekDocid() +** readDocid() +** readPosition() +** skipPositionList() +** and so forth... +** +** to read information out of the doclist. When we reach the end +** of the doclist, atEnd() returns TRUE. +*/ +typedef struct DocListReader { + DocList *pDoclist; /* The document list we are stepping through */ + char *p; /* Pointer to next unread byte in the doclist */ + int iLastColumn; + int iLastPos; /* the last position read, or -1 when not in a position list */ +} DocListReader; + +/* +** Initialize the DocListReader r to point to the beginning of pDoclist. +*/ +static void readerInit(DocListReader *r, DocList *pDoclist){ + r->pDoclist = pDoclist; + if( pDoclist!=NULL ){ + r->p = pDoclist->pData; + } + r->iLastColumn = -1; + r->iLastPos = -1; +} + +/* +** Return TRUE if we have reached then end of pReader and there is +** nothing else left to read. +*/ +static int atEnd(DocListReader *pReader){ + return pReader->pDoclist==0 || (pReader->p >= docListEnd(pReader->pDoclist)); +} + +/* Peek at the next docid without advancing the read pointer. +*/ +static sqlite_int64 peekDocid(DocListReader *pReader){ + sqlite_int64 ret; + assert( !atEnd(pReader) ); + assert( pReader->iLastPos==-1 ); + getVarint(pReader->p, &ret); + return ret; +} + +/* Read the next docid. See also nextDocid(). +*/ +static sqlite_int64 readDocid(DocListReader *pReader){ + sqlite_int64 ret; + assert( !atEnd(pReader) ); + assert( pReader->iLastPos==-1 ); + pReader->p += getVarint(pReader->p, &ret); + if( pReader->pDoclist->iType>=DL_POSITIONS ){ + pReader->iLastColumn = 0; + pReader->iLastPos = 0; + } + return ret; +} + +/* Read the next position and column index from a position list. + * Returns the position, or -1 at the end of the list. */ +static int readPosition(DocListReader *pReader, int *iColumn){ + int i; + int iType = pReader->pDoclist->iType; + + if( pReader->iLastPos==-1 ){ + return -1; + } + assert( !atEnd(pReader) ); + + if( iTypep += getVarint32(pReader->p, &i); + if( i==POS_END ){ + pReader->iLastColumn = pReader->iLastPos = -1; + *iColumn = -1; + return -1; + } + if( i==POS_COLUMN ){ + pReader->p += getVarint32(pReader->p, &pReader->iLastColumn); + pReader->iLastPos = 0; + pReader->p += getVarint32(pReader->p, &i); + assert( i>=POS_BASE ); + } + pReader->iLastPos += ((int) i)-POS_BASE; + if( iType>=DL_POSITIONS_OFFSETS ){ + /* Skip over offsets, ignoring them for now. */ + int iStart, iEnd; + pReader->p += getVarint32(pReader->p, &iStart); + pReader->p += getVarint32(pReader->p, &iEnd); + } + *iColumn = pReader->iLastColumn; + return pReader->iLastPos; +} + +/* Skip past the end of a position list. */ +static void skipPositionList(DocListReader *pReader){ + DocList *p = pReader->pDoclist; + if( p && p->iType>=DL_POSITIONS ){ + int iColumn; + while( readPosition(pReader, &iColumn)!=-1 ){} + } +} + +/* Skip over a docid, including its position list if the doclist has + * positions. */ +static void skipDocument(DocListReader *pReader){ + readDocid(pReader); + skipPositionList(pReader); +} + +/* Skip past all docids which are less than [iDocid]. Returns 1 if a docid + * matching [iDocid] was found. */ +static int skipToDocid(DocListReader *pReader, sqlite_int64 iDocid){ + sqlite_int64 d = 0; + while( !atEnd(pReader) && (d=peekDocid(pReader))iType>=DL_POSITIONS ){ + int iPos, iCol; + const char *zDiv = ""; + printf("("); + while( (iPos = readPosition(&r, &iCol))>=0 ){ + printf("%s%d:%d", zDiv, iCol, iPos); + zDiv = ":"; + } + printf(")"); + } + } + printf("\n"); + fflush(stdout); +} +#endif /* SQLITE_DEBUG */ + +/* Trim the given doclist to contain only positions in column + * [iRestrictColumn]. */ +static void docListRestrictColumn(DocList *in, int iRestrictColumn){ + DocListReader r; + DocList out; + + assert( in->iType>=DL_POSITIONS ); + readerInit(&r, in); + docListInit(&out, DL_POSITIONS, NULL, 0); + + while( !atEnd(&r) ){ + sqlite_int64 iDocid = readDocid(&r); + int iPos, iColumn; + + docListAddDocid(&out, iDocid); + while( (iPos = readPosition(&r, &iColumn)) != -1 ){ + if( iColumn==iRestrictColumn ){ + docListAddPos(&out, iColumn, iPos); + } + } + } + + docListDestroy(in); + *in = out; +} + +/* Trim the given doclist by discarding any docids without any remaining + * positions. */ +static void docListDiscardEmpty(DocList *in) { + DocListReader r; + DocList out; + + /* TODO: It would be nice to implement this operation in place; that + * could save a significant amount of memory in queries with long doclists. */ + assert( in->iType>=DL_POSITIONS ); + readerInit(&r, in); + docListInit(&out, DL_POSITIONS, NULL, 0); + + while( !atEnd(&r) ){ + sqlite_int64 iDocid = readDocid(&r); + int match = 0; + int iPos, iColumn; + while( (iPos = readPosition(&r, &iColumn)) != -1 ){ + if( !match ){ + docListAddDocid(&out, iDocid); + match = 1; + } + docListAddPos(&out, iColumn, iPos); + } + } + + docListDestroy(in); + *in = out; +} + +/* Helper function for docListUpdate() and docListAccumulate(). +** Splices a doclist element into the doclist represented by r, +** leaving r pointing after the newly spliced element. +*/ +static void docListSpliceElement(DocListReader *r, sqlite_int64 iDocid, + const char *pSource, int nSource){ + DocList *d = r->pDoclist; + char *pTarget; + int nTarget, found; + + found = skipToDocid(r, iDocid); + + /* Describe slice in d to place pSource/nSource. */ + pTarget = r->p; + if( found ){ + skipDocument(r); + nTarget = r->p-pTarget; + }else{ + nTarget = 0; + } + + /* The sense of the following is that there are three possibilities. + ** If nTarget==nSource, we should not move any memory nor realloc. + ** If nTarget>nSource, trim target and realloc. + ** If nTargetnSource ){ + memmove(pTarget+nSource, pTarget+nTarget, docListEnd(d)-(pTarget+nTarget)); + } + if( nTarget!=nSource ){ + int iDoclist = pTarget-d->pData; + d->pData = realloc(d->pData, d->nData+nSource-nTarget); + pTarget = d->pData+iDoclist; + } + if( nTargetnData += nSource-nTarget; + r->p = pTarget+nSource; +} + +/* Insert/update pUpdate into the doclist. */ +static void docListUpdate(DocList *d, DocList *pUpdate){ + DocListReader reader; + + assert( d!=NULL && pUpdate!=NULL ); + assert( d->iType==pUpdate->iType); + + readerInit(&reader, d); + docListSpliceElement(&reader, firstDocid(pUpdate), + pUpdate->pData, pUpdate->nData); +} + +/* Propagate elements from pUpdate to pAcc, overwriting elements with +** matching docids. +*/ +static void docListAccumulate(DocList *pAcc, DocList *pUpdate){ + DocListReader accReader, updateReader; + + /* Handle edge cases where one doclist is empty. */ + assert( pAcc!=NULL ); + if( pUpdate==NULL || pUpdate->nData==0 ) return; + if( pAcc->nData==0 ){ + pAcc->pData = malloc(pUpdate->nData); + memcpy(pAcc->pData, pUpdate->pData, pUpdate->nData); + pAcc->nData = pUpdate->nData; + return; + } + + readerInit(&accReader, pAcc); + readerInit(&updateReader, pUpdate); + + while( !atEnd(&updateReader) ){ + char *pSource = updateReader.p; + sqlite_int64 iDocid = readDocid(&updateReader); + skipPositionList(&updateReader); + docListSpliceElement(&accReader, iDocid, pSource, updateReader.p-pSource); + } +} + +/* +** Read the next docid off of pIn. Return 0 if we reach the end. +* +* TODO: This assumes that docids are never 0, but they may actually be 0 since +* users can choose docids when inserting into a full-text table. Fix this. +*/ +static sqlite_int64 nextDocid(DocListReader *pIn){ + skipPositionList(pIn); + return atEnd(pIn) ? 0 : readDocid(pIn); +} + +/* +** pLeft and pRight are two DocListReaders that are pointing to +** positions lists of the same document: iDocid. +** +** If there are no instances in pLeft or pRight where the position +** of pLeft is one less than the position of pRight, then this +** routine adds nothing to pOut. +** +** If there are one or more instances where positions from pLeft +** are exactly one less than positions from pRight, then add a new +** document record to pOut. If pOut wants to hold positions, then +** include the positions from pRight that are one more than a +** position in pLeft. In other words: pRight.iPos==pLeft.iPos+1. +** +** pLeft and pRight are left pointing at the next document record. +*/ +static void mergePosList( + DocListReader *pLeft, /* Left position list */ + DocListReader *pRight, /* Right position list */ + sqlite_int64 iDocid, /* The docid from pLeft and pRight */ + DocList *pOut /* Write the merged document record here */ +){ + int iLeftCol, iLeftPos = readPosition(pLeft, &iLeftCol); + int iRightCol, iRightPos = readPosition(pRight, &iRightCol); + int match = 0; + + /* Loop until we've reached the end of both position lists. */ + while( iLeftPos!=-1 && iRightPos!=-1 ){ + if( iLeftCol==iRightCol && iLeftPos+1==iRightPos ){ + if( !match ){ + docListAddDocid(pOut, iDocid); + match = 1; + } + if( pOut->iType>=DL_POSITIONS ){ + docListAddPos(pOut, iRightCol, iRightPos); + } + iLeftPos = readPosition(pLeft, &iLeftCol); + iRightPos = readPosition(pRight, &iRightCol); + }else if( iRightCol=0 ) skipPositionList(pLeft); + if( iRightPos>=0 ) skipPositionList(pRight); +} + +/* We have two doclists: pLeft and pRight. +** Write the phrase intersection of these two doclists into pOut. +** +** A phrase intersection means that two documents only match +** if pLeft.iPos+1==pRight.iPos. +** +** The output pOut may or may not contain positions. If pOut +** does contain positions, they are the positions of pRight. +*/ +static void docListPhraseMerge( + DocList *pLeft, /* Doclist resulting from the words on the left */ + DocList *pRight, /* Doclist for the next word to the right */ + DocList *pOut /* Write the combined doclist here */ +){ + DocListReader left, right; + sqlite_int64 docidLeft, docidRight; + + readerInit(&left, pLeft); + readerInit(&right, pRight); + docidLeft = nextDocid(&left); + docidRight = nextDocid(&right); + + while( docidLeft>0 && docidRight>0 ){ + if( docidLeftiType0 && docidRight>0 ){ + if( docidLeft0 && docidRight>0 ){ + if( docidLeft<=docidRight ){ + docListAddDocid(pOut, docidLeft); + }else{ + docListAddDocid(pOut, docidRight); + } + priorLeft = docidLeft; + if( docidLeft<=docidRight ){ + docidLeft = nextDocid(&left); + } + if( docidRight>0 && docidRight<=priorLeft ){ + docidRight = nextDocid(&right); + } + } + while( docidLeft>0 ){ + docListAddDocid(pOut, docidLeft); + docidLeft = nextDocid(&left); + } + while( docidRight>0 ){ + docListAddDocid(pOut, docidRight); + docidRight = nextDocid(&right); + } +} + +/* We have two doclists: pLeft and pRight. +** Write into pOut all documents that occur in pLeft but not +** in pRight. +** +** Only docids are matched. Position information is ignored. +** +** The output pOut never holds positions. +*/ +static void docListExceptMerge( + DocList *pLeft, /* Doclist resulting from the words on the left */ + DocList *pRight, /* Doclist for the next word to the right */ + DocList *pOut /* Write the combined doclist here */ +){ + DocListReader left, right; + sqlite_int64 docidLeft, docidRight, priorLeft; + + readerInit(&left, pLeft); + readerInit(&right, pRight); + docidLeft = nextDocid(&left); + docidRight = nextDocid(&right); + + while( docidLeft>0 && docidRight>0 ){ + priorLeft = docidLeft; + if( docidLeft0 && docidRight<=priorLeft ){ + docidRight = nextDocid(&right); + } + } + while( docidLeft>0 ){ + docListAddDocid(pOut, docidLeft); + docidLeft = nextDocid(&left); + } +} + +static char *string_dup_n(const char *s, int n){ + char *str = malloc(n + 1); + memcpy(str, s, n); + str[n] = '\0'; + return str; +} + +/* Duplicate a string; the caller must free() the returned string. + * (We don't use strdup() since it is not part of the standard C library and + * may not be available everywhere.) */ +static char *string_dup(const char *s){ + return string_dup_n(s, strlen(s)); +} + +/* Format a string, replacing each occurrence of the % character with + * zDb.zName. This may be more convenient than sqlite_mprintf() + * when one string is used repeatedly in a format string. + * The caller must free() the returned string. */ +static char *string_format(const char *zFormat, + const char *zDb, const char *zName){ + const char *p; + size_t len = 0; + size_t nDb = strlen(zDb); + size_t nName = strlen(zName); + size_t nFullTableName = nDb+1+nName; + char *result; + char *r; + + /* first compute length needed */ + for(p = zFormat ; *p ; ++p){ + len += (*p=='%' ? nFullTableName : 1); + } + len += 1; /* for null terminator */ + + r = result = malloc(len); + for(p = zFormat; *p; ++p){ + if( *p=='%' ){ + memcpy(r, zDb, nDb); + r += nDb; + *r++ = '.'; + memcpy(r, zName, nName); + r += nName; + } else { + *r++ = *p; + } + } + *r++ = '\0'; + assert( r == result + len ); + return result; +} + +static int sql_exec(sqlite3 *db, const char *zDb, const char *zName, + const char *zFormat){ + char *zCommand = string_format(zFormat, zDb, zName); + int rc; + TRACE(("FTS1 sql: %s\n", zCommand)); + rc = sqlite3_exec(db, zCommand, NULL, 0, NULL); + free(zCommand); + return rc; +} + +static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName, + sqlite3_stmt **ppStmt, const char *zFormat){ + char *zCommand = string_format(zFormat, zDb, zName); + int rc; + TRACE(("FTS1 prepare: %s\n", zCommand)); + rc = sqlite3_prepare(db, zCommand, -1, ppStmt, NULL); + free(zCommand); + return rc; +} + +/* end utility functions */ + +/* Forward reference */ +typedef struct fulltext_vtab fulltext_vtab; + +/* A single term in a query is represented by an instances of +** the following structure. +*/ +typedef struct QueryTerm { + short int nPhrase; /* How many following terms are part of the same phrase */ + short int iPhrase; /* This is the i-th term of a phrase. */ + short int iColumn; /* Column of the index that must match this term */ + signed char isOr; /* this term is preceded by "OR" */ + signed char isNot; /* this term is preceded by "-" */ + char *pTerm; /* text of the term. '\000' terminated. malloced */ + int nTerm; /* Number of bytes in pTerm[] */ +} QueryTerm; + + +/* A query string is parsed into a Query structure. + * + * We could, in theory, allow query strings to be complicated + * nested expressions with precedence determined by parentheses. + * But none of the major search engines do this. (Perhaps the + * feeling is that an parenthesized expression is two complex of + * an idea for the average user to grasp.) Taking our lead from + * the major search engines, we will allow queries to be a list + * of terms (with an implied AND operator) or phrases in double-quotes, + * with a single optional "-" before each non-phrase term to designate + * negation and an optional OR connector. + * + * OR binds more tightly than the implied AND, which is what the + * major search engines seem to do. So, for example: + * + * [one two OR three] ==> one AND (two OR three) + * [one OR two three] ==> (one OR two) AND three + * + * A "-" before a term matches all entries that lack that term. + * The "-" must occur immediately before the term with in intervening + * space. This is how the search engines do it. + * + * A NOT term cannot be the right-hand operand of an OR. If this + * occurs in the query string, the NOT is ignored: + * + * [one OR -two] ==> one OR two + * + */ +typedef struct Query { + fulltext_vtab *pFts; /* The full text index */ + int nTerms; /* Number of terms in the query */ + QueryTerm *pTerms; /* Array of terms. Space obtained from malloc() */ + int nextIsOr; /* Set the isOr flag on the next inserted term */ + int nextColumn; /* Next word parsed must be in this column */ + int dfltColumn; /* The default column */ +} Query; + + +/* +** An instance of the following structure keeps track of generated +** matching-word offset information and snippets. +*/ +typedef struct Snippet { + int nMatch; /* Total number of matches */ + int nAlloc; /* Space allocated for aMatch[] */ + struct snippetMatch { /* One entry for each matching term */ + char snStatus; /* Status flag for use while constructing snippets */ + short int iCol; /* The column that contains the match */ + short int iTerm; /* The index in Query.pTerms[] of the matching term */ + short int nByte; /* Number of bytes in the term */ + int iStart; /* The offset to the first character of the term */ + } *aMatch; /* Points to space obtained from malloc */ + char *zOffset; /* Text rendering of aMatch[] */ + int nOffset; /* strlen(zOffset) */ + char *zSnippet; /* Snippet text */ + int nSnippet; /* strlen(zSnippet) */ +} Snippet; + + +typedef enum QueryType { + QUERY_GENERIC, /* table scan */ + QUERY_ROWID, /* lookup by rowid */ + QUERY_FULLTEXT /* QUERY_FULLTEXT + [i] is a full-text search for column i*/ +} QueryType; + +/* TODO(shess) CHUNK_MAX controls how much data we allow in segment 0 +** before we start aggregating into larger segments. Lower CHUNK_MAX +** means that for a given input we have more individual segments per +** term, which means more rows in the table and a bigger index (due to +** both more rows and bigger rowids). But it also reduces the average +** cost of adding new elements to the segment 0 doclist, and it seems +** to reduce the number of pages read and written during inserts. 256 +** was chosen by measuring insertion times for a certain input (first +** 10k documents of Enron corpus), though including query performance +** in the decision may argue for a larger value. +*/ +#define CHUNK_MAX 256 + +typedef enum fulltext_statement { + CONTENT_INSERT_STMT, + CONTENT_SELECT_STMT, + CONTENT_UPDATE_STMT, + CONTENT_DELETE_STMT, + + TERM_SELECT_STMT, + TERM_SELECT_ALL_STMT, + TERM_INSERT_STMT, + TERM_UPDATE_STMT, + TERM_DELETE_STMT, + + MAX_STMT /* Always at end! */ +} fulltext_statement; + +/* These must exactly match the enum above. */ +/* TODO(adam): Is there some risk that a statement (in particular, +** pTermSelectStmt) will be used in two cursors at once, e.g. if a +** query joins a virtual table to itself? If so perhaps we should +** move some of these to the cursor object. +*/ +static const char *const fulltext_zStatement[MAX_STMT] = { + /* CONTENT_INSERT */ NULL, /* generated in contentInsertStatement() */ + /* CONTENT_SELECT */ "select * from %_content where rowid = ?", + /* CONTENT_UPDATE */ NULL, /* generated in contentUpdateStatement() */ + /* CONTENT_DELETE */ "delete from %_content where rowid = ?", + + /* TERM_SELECT */ + "select rowid, doclist from %_term where term = ? and segment = ?", + /* TERM_SELECT_ALL */ + "select doclist from %_term where term = ? order by segment", + /* TERM_INSERT */ + "insert into %_term (rowid, term, segment, doclist) values (?, ?, ?, ?)", + /* TERM_UPDATE */ "update %_term set doclist = ? where rowid = ?", + /* TERM_DELETE */ "delete from %_term where rowid = ?", +}; + +/* +** A connection to a fulltext index is an instance of the following +** structure. The xCreate and xConnect methods create an instance +** of this structure and xDestroy and xDisconnect free that instance. +** All other methods receive a pointer to the structure as one of their +** arguments. +*/ +struct fulltext_vtab { + sqlite3_vtab base; /* Base class used by SQLite core */ + sqlite3 *db; /* The database connection */ + const char *zDb; /* logical database name */ + const char *zName; /* virtual table name */ + int nColumn; /* number of columns in virtual table */ + char **azColumn; /* column names. malloced */ + char **azContentColumn; /* column names in content table; malloced */ + sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ + + /* Precompiled statements which we keep as long as the table is + ** open. + */ + sqlite3_stmt *pFulltextStatements[MAX_STMT]; +}; + +/* +** When the core wants to do a query, it create a cursor using a +** call to xOpen. This structure is an instance of a cursor. It +** is destroyed by xClose. +*/ +typedef struct fulltext_cursor { + sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + QueryType iCursorType; /* Copy of sqlite3_index_info.idxNum */ + sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ + int eof; /* True if at End Of Results */ + Query q; /* Parsed query string */ + Snippet snippet; /* Cached snippet for the current row */ + int iColumn; /* Column being searched */ + DocListReader result; /* used when iCursorType == QUERY_FULLTEXT */ +} fulltext_cursor; + +static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){ + return (fulltext_vtab *) c->base.pVtab; +} + +static const sqlite3_module fulltextModule; /* forward declaration */ + +/* Append a list of strings separated by commas to a StringBuffer. */ +static void appendList(StringBuffer *sb, int nString, char **azString){ + int i; + for(i=0; i0 ) append(sb, ", "); + append(sb, azString[i]); + } +} + +/* Return a dynamically generated statement of the form + * insert into %_content (rowid, ...) values (?, ...) + */ +static const char *contentInsertStatement(fulltext_vtab *v){ + StringBuffer sb; + int i; + + initStringBuffer(&sb); + append(&sb, "insert into %_content (rowid, "); + appendList(&sb, v->nColumn, v->azContentColumn); + append(&sb, ") values (?"); + for(i=0; inColumn; ++i) + append(&sb, ", ?"); + append(&sb, ")"); + return sb.s; +} + +/* Return a dynamically generated statement of the form + * update %_content set [col_0] = ?, [col_1] = ?, ... + * where rowid = ? + */ +static const char *contentUpdateStatement(fulltext_vtab *v){ + StringBuffer sb; + int i; + + initStringBuffer(&sb); + append(&sb, "update %_content set "); + for(i=0; inColumn; ++i) { + if( i>0 ){ + append(&sb, ", "); + } + append(&sb, v->azContentColumn[i]); + append(&sb, " = ?"); + } + append(&sb, " where rowid = ?"); + return sb.s; +} + +/* Puts a freshly-prepared statement determined by iStmt in *ppStmt. +** If the indicated statement has never been prepared, it is prepared +** and cached, otherwise the cached version is reset. +*/ +static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt, + sqlite3_stmt **ppStmt){ + assert( iStmtpFulltextStatements[iStmt]==NULL ){ + const char *zStmt; + int rc; + switch( iStmt ){ + case CONTENT_INSERT_STMT: + zStmt = contentInsertStatement(v); break; + case CONTENT_UPDATE_STMT: + zStmt = contentUpdateStatement(v); break; + default: + zStmt = fulltext_zStatement[iStmt]; + } + rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt], + zStmt); + if( zStmt != fulltext_zStatement[iStmt]) free((void *) zStmt); + if( rc!=SQLITE_OK ) return rc; + } else { + int rc = sqlite3_reset(v->pFulltextStatements[iStmt]); + if( rc!=SQLITE_OK ) return rc; + } + + *ppStmt = v->pFulltextStatements[iStmt]; + return SQLITE_OK; +} + +/* Step the indicated statement, handling errors SQLITE_BUSY (by +** retrying) and SQLITE_SCHEMA (by re-preparing and transferring +** bindings to the new statement). +** TODO(adam): We should extend this function so that it can work with +** statements declared locally, not only globally cached statements. +*/ +static int sql_step_statement(fulltext_vtab *v, fulltext_statement iStmt, + sqlite3_stmt **ppStmt){ + int rc; + sqlite3_stmt *s = *ppStmt; + assert( iStmtpFulltextStatements[iStmt] ); + + while( (rc=sqlite3_step(s))!=SQLITE_DONE && rc!=SQLITE_ROW ){ + if( rc==SQLITE_BUSY ) continue; + if( rc!=SQLITE_ERROR ) return rc; + + /* If an SQLITE_SCHEMA error has occurred, then finalizing this + * statement is going to delete the fulltext_vtab structure. If + * the statement just executed is in the pFulltextStatements[] + * array, it will be finalized twice. So remove it before + * calling sqlite3_finalize(). + */ + v->pFulltextStatements[iStmt] = NULL; + rc = sqlite3_finalize(s); + break; + } + return rc; + + err: + sqlite3_finalize(s); + return rc; +} + +/* Like sql_step_statement(), but convert SQLITE_DONE to SQLITE_OK. +** Useful for statements like UPDATE, where we expect no results. +*/ +static int sql_single_step_statement(fulltext_vtab *v, + fulltext_statement iStmt, + sqlite3_stmt **ppStmt){ + int rc = sql_step_statement(v, iStmt, ppStmt); + return (rc==SQLITE_DONE) ? SQLITE_OK : rc; +} + +/* insert into %_content (rowid, ...) values ([rowid], [pValues]) */ +static int content_insert(fulltext_vtab *v, sqlite3_value *rowid, + sqlite3_value **pValues){ + sqlite3_stmt *s; + int i; + int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_value(s, 1, rowid); + if( rc!=SQLITE_OK ) return rc; + + for(i=0; inColumn; ++i){ + rc = sqlite3_bind_value(s, 2+i, pValues[i]); + if( rc!=SQLITE_OK ) return rc; + } + + return sql_single_step_statement(v, CONTENT_INSERT_STMT, &s); +} + +/* update %_content set col0 = pValues[0], col1 = pValues[1], ... + * where rowid = [iRowid] */ +static int content_update(fulltext_vtab *v, sqlite3_value **pValues, + sqlite_int64 iRowid){ + sqlite3_stmt *s; + int i; + int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + for(i=0; inColumn; ++i){ + rc = sqlite3_bind_value(s, 1+i, pValues[i]); + if( rc!=SQLITE_OK ) return rc; + } + + rc = sqlite3_bind_int64(s, 1+v->nColumn, iRowid); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, CONTENT_UPDATE_STMT, &s); +} + +static void freeStringArray(int nString, const char **pString){ + int i; + + for (i=0 ; i < nString ; ++i) { + if( pString[i]!=NULL ) free((void *) pString[i]); + } + free((void *) pString); +} + +/* select * from %_content where rowid = [iRow] + * The caller must delete the returned array and all strings in it. + * null fields will be NULL in the returned array. + * + * TODO: Perhaps we should return pointer/length strings here for consistency + * with other code which uses pointer/length. */ +static int content_select(fulltext_vtab *v, sqlite_int64 iRow, + const char ***pValues){ + sqlite3_stmt *s; + const char **values; + int i; + int rc; + + *pValues = NULL; + + rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iRow); + if( rc!=SQLITE_OK ) return rc; + + rc = sql_step_statement(v, CONTENT_SELECT_STMT, &s); + if( rc!=SQLITE_ROW ) return rc; + + values = (const char **) malloc(v->nColumn * sizeof(const char *)); + for(i=0; inColumn; ++i){ + if( sqlite3_column_type(s, i)==SQLITE_NULL ){ + values[i] = NULL; + }else{ + values[i] = string_dup((char*)sqlite3_column_text(s, i)); + } + } + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + rc = sqlite3_step(s); + if( rc==SQLITE_DONE ){ + *pValues = values; + return SQLITE_OK; + } + + freeStringArray(v->nColumn, values); + return rc; +} + +/* delete from %_content where rowid = [iRow ] */ +static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iRow); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, CONTENT_DELETE_STMT, &s); +} + +/* select rowid, doclist from %_term + * where term = [pTerm] and segment = [iSegment] + * If found, returns SQLITE_ROW; the caller must free the + * returned doclist. If no rows found, returns SQLITE_DONE. */ +static int term_select(fulltext_vtab *v, const char *pTerm, int nTerm, + int iSegment, + sqlite_int64 *rowid, DocList *out){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, TERM_SELECT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_text(s, 1, pTerm, nTerm, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int(s, 2, iSegment); + if( rc!=SQLITE_OK ) return rc; + + rc = sql_step_statement(v, TERM_SELECT_STMT, &s); + if( rc!=SQLITE_ROW ) return rc; + + *rowid = sqlite3_column_int64(s, 0); + docListInit(out, DL_DEFAULT, + sqlite3_column_blob(s, 1), sqlite3_column_bytes(s, 1)); + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + rc = sqlite3_step(s); + return rc==SQLITE_DONE ? SQLITE_ROW : rc; +} + +/* Load the segment doclists for term pTerm and merge them in +** appropriate order into out. Returns SQLITE_OK if successful. If +** there are no segments for pTerm, successfully returns an empty +** doclist in out. +** +** Each document consists of 1 or more "columns". The number of +** columns is v->nColumn. If iColumn==v->nColumn, then return +** position information about all columns. If iColumnnColumn, +** then only return position information about the iColumn-th column +** (where the first column is 0). +*/ +static int term_select_all( + fulltext_vtab *v, /* The fulltext index we are querying against */ + int iColumn, /* If nColumn ){ /* querying a single column */ + docListRestrictColumn(&old, iColumn); + } + + /* doclist contains the newer data, so write it over old. Then + ** steal accumulated result for doclist. + */ + docListAccumulate(&old, &doclist); + docListDestroy(&doclist); + doclist = old; + } + if( rc!=SQLITE_DONE ){ + docListDestroy(&doclist); + return rc; + } + + docListDiscardEmpty(&doclist); + *out = doclist; + return SQLITE_OK; +} + +/* insert into %_term (rowid, term, segment, doclist) + values ([piRowid], [pTerm], [iSegment], [doclist]) +** Lets sqlite select rowid if piRowid is NULL, else uses *piRowid. +** +** NOTE(shess) piRowid is IN, with values of "space of int64" plus +** null, it is not used to pass data back to the caller. +*/ +static int term_insert(fulltext_vtab *v, sqlite_int64 *piRowid, + const char *pTerm, int nTerm, + int iSegment, DocList *doclist){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, TERM_INSERT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + if( piRowid==NULL ){ + rc = sqlite3_bind_null(s, 1); + }else{ + rc = sqlite3_bind_int64(s, 1, *piRowid); + } + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_text(s, 2, pTerm, nTerm, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int(s, 3, iSegment); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_blob(s, 4, doclist->pData, doclist->nData, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, TERM_INSERT_STMT, &s); +} + +/* update %_term set doclist = [doclist] where rowid = [rowid] */ +static int term_update(fulltext_vtab *v, sqlite_int64 rowid, + DocList *doclist){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, TERM_UPDATE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_blob(s, 1, doclist->pData, doclist->nData, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 2, rowid); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, TERM_UPDATE_STMT, &s); +} + +static int term_delete(fulltext_vtab *v, sqlite_int64 rowid){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, TERM_DELETE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, rowid); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, TERM_DELETE_STMT, &s); +} + +/* +** Free the memory used to contain a fulltext_vtab structure. +*/ +static void fulltext_vtab_destroy(fulltext_vtab *v){ + int iStmt, i; + + TRACE(("FTS1 Destroy %p\n", v)); + for( iStmt=0; iStmtpFulltextStatements[iStmt]!=NULL ){ + sqlite3_finalize(v->pFulltextStatements[iStmt]); + v->pFulltextStatements[iStmt] = NULL; + } + } + + if( v->pTokenizer!=NULL ){ + v->pTokenizer->pModule->xDestroy(v->pTokenizer); + v->pTokenizer = NULL; + } + + free(v->azColumn); + for(i = 0; i < v->nColumn; ++i) { + sqlite3_free(v->azContentColumn[i]); + } + free(v->azContentColumn); + free(v); +} + +/* +** Token types for parsing the arguments to xConnect or xCreate. +*/ +#define TOKEN_EOF 0 /* End of file */ +#define TOKEN_SPACE 1 /* Any kind of whitespace */ +#define TOKEN_ID 2 /* An identifier */ +#define TOKEN_STRING 3 /* A string literal */ +#define TOKEN_PUNCT 4 /* A single punctuation character */ + +/* +** If X is a character that can be used in an identifier then +** IdChar(X) will be true. Otherwise it is false. +** +** For ASCII, any character with the high-order bit set is +** allowed in an identifier. For 7-bit characters, +** sqlite3IsIdChar[X] must be 1. +** +** Ticket #1066. the SQL standard does not allow '$' in the +** middle of identfiers. But many SQL implementations do. +** SQLite will allow '$' in identifiers for compatibility. +** But the feature is undocumented. +*/ +static const char isIdChar[] = { +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ + 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ +}; +#define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && isIdChar[c-0x20])) + + +/* +** Return the length of the token that begins at z[0]. +** Store the token type in *tokenType before returning. +*/ +static int getToken(const char *z, int *tokenType){ + int i, c; + switch( *z ){ + case 0: { + *tokenType = TOKEN_EOF; + return 0; + } + case ' ': case '\t': case '\n': case '\f': case '\r': { + for(i=1; safe_isspace(z[i]); i++){} + *tokenType = TOKEN_SPACE; + return i; + } + case '`': + case '\'': + case '"': { + int delim = z[0]; + for(i=1; (c=z[i])!=0; i++){ + if( c==delim ){ + if( z[i+1]==delim ){ + i++; + }else{ + break; + } + } + } + *tokenType = TOKEN_STRING; + return i + (c!=0); + } + case '[': { + for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} + *tokenType = TOKEN_ID; + return i; + } + default: { + if( !IdChar(*z) ){ + break; + } + for(i=1; IdChar(z[i]); i++){} + *tokenType = TOKEN_ID; + return i; + } + } + *tokenType = TOKEN_PUNCT; + return 1; +} + +/* +** A token extracted from a string is an instance of the following +** structure. +*/ +typedef struct Token { + const char *z; /* Pointer to token text. Not '\000' terminated */ + short int n; /* Length of the token text in bytes. */ +} Token; + +/* +** Given a input string (which is really one of the argv[] parameters +** passed into xConnect or xCreate) split the string up into tokens. +** Return an array of pointers to '\000' terminated strings, one string +** for each non-whitespace token. +** +** The returned array is terminated by a single NULL pointer. +** +** Space to hold the returned array is obtained from a single +** malloc and should be freed by passing the return value to free(). +** The individual strings within the token list are all a part of +** the single memory allocation and will all be freed at once. +*/ +static char **tokenizeString(const char *z, int *pnToken){ + int nToken = 0; + Token *aToken = malloc( strlen(z) * sizeof(aToken[0]) ); + int n = 1; + int e, i; + int totalSize = 0; + char **azToken; + char *zCopy; + while( n>0 ){ + n = getToken(z, &e); + if( e!=TOKEN_SPACE ){ + aToken[nToken].z = z; + aToken[nToken].n = n; + nToken++; + totalSize += n+1; + } + z += n; + } + azToken = (char**)malloc( nToken*sizeof(char*) + totalSize ); + zCopy = (char*)&azToken[nToken]; + nToken--; + for(i=0; i=0 ){ + azIn[j] = azIn[i]; + } + j++; + } + } + azIn[j] = 0; + } +} + + +/* +** Find the first alphanumeric token in the string zIn. Null-terminate +** this token. Remove any quotation marks. And return a pointer to +** the result. +*/ +static char *firstToken(char *zIn, char **pzTail){ + int n, ttype; + while(1){ + n = getToken(zIn, &ttype); + if( ttype==TOKEN_SPACE ){ + zIn += n; + }else if( ttype==TOKEN_EOF ){ + *pzTail = zIn; + return 0; + }else{ + zIn[n] = 0; + *pzTail = &zIn[1]; + dequoteString(zIn); + return zIn; + } + } + /*NOTREACHED*/ +} + +/* Return true if... +** +** * s begins with the string t, ignoring case +** * s is longer than t +** * The first character of s beyond t is not a alphanumeric +** +** Ignore leading space in *s. +** +** To put it another way, return true if the first token of +** s[] is t[]. +*/ +static int startsWith(const char *s, const char *t){ + while( safe_isspace(*s) ){ s++; } + while( *t ){ + if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0; + } + return *s!='_' && !safe_isalnum(*s); +} + +/* +** An instance of this structure defines the "spec" of a +** full text index. This structure is populated by parseSpec +** and use by fulltextConnect and fulltextCreate. +*/ +typedef struct TableSpec { + const char *zDb; /* Logical database name */ + const char *zName; /* Name of the full-text index */ + int nColumn; /* Number of columns to be indexed */ + char **azColumn; /* Original names of columns to be indexed */ + char **azContentColumn; /* Column names for %_content */ + char **azTokenizer; /* Name of tokenizer and its arguments */ +} TableSpec; + +/* +** Reclaim all of the memory used by a TableSpec +*/ +static void clearTableSpec(TableSpec *p) { + free(p->azColumn); + free(p->azContentColumn); + free(p->azTokenizer); +} + +/* Parse a CREATE VIRTUAL TABLE statement, which looks like this: + * + * CREATE VIRTUAL TABLE email + * USING fts1(subject, body, tokenize mytokenizer(myarg)) + * + * We return parsed information in a TableSpec structure. + * + */ +static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv, + char**pzErr){ + int i, n; + char *z, *zDummy; + char **azArg; + const char *zTokenizer = 0; /* argv[] entry describing the tokenizer */ + + assert( argc>=3 ); + /* Current interface: + ** argv[0] - module name + ** argv[1] - database name + ** argv[2] - table name + ** argv[3..] - columns, optionally followed by tokenizer specification + ** and snippet delimiters specification. + */ + + /* Make a copy of the complete argv[][] array in a single allocation. + ** The argv[][] array is read-only and transient. We can write to the + ** copy in order to modify things and the copy is persistent. + */ + memset(pSpec, 0, sizeof(*pSpec)); + for(i=n=0; izDb = azArg[1]; + pSpec->zName = azArg[2]; + pSpec->nColumn = 0; + pSpec->azColumn = azArg; + zTokenizer = "tokenize simple"; + for(i=3; inColumn] = firstToken(azArg[i], &zDummy); + pSpec->nColumn++; + } + } + if( pSpec->nColumn==0 ){ + azArg[0] = "content"; + pSpec->nColumn = 1; + } + + /* + ** Construct the list of content column names. + ** + ** Each content column name will be of the form cNNAAAA + ** where NN is the column number and AAAA is the sanitized + ** column name. "sanitized" means that special characters are + ** converted to "_". The cNN prefix guarantees that all column + ** names are unique. + ** + ** The AAAA suffix is not strictly necessary. It is included + ** for the convenience of people who might examine the generated + ** %_content table and wonder what the columns are used for. + */ + pSpec->azContentColumn = malloc( pSpec->nColumn * sizeof(char *) ); + if( pSpec->azContentColumn==0 ){ + clearTableSpec(pSpec); + return SQLITE_NOMEM; + } + for(i=0; inColumn; i++){ + char *p; + pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]); + for (p = pSpec->azContentColumn[i]; *p ; ++p) { + if( !safe_isalnum(*p) ) *p = '_'; + } + } + + /* + ** Parse the tokenizer specification string. + */ + pSpec->azTokenizer = tokenizeString(zTokenizer, &n); + tokenListToIdList(pSpec->azTokenizer); + + return SQLITE_OK; +} + +/* +** Generate a CREATE TABLE statement that describes the schema of +** the virtual table. Return a pointer to this schema string. +** +** Space is obtained from sqlite3_mprintf() and should be freed +** using sqlite3_free(). +*/ +static char *fulltextSchema( + int nColumn, /* Number of columns */ + const char *const* azColumn, /* List of columns */ + const char *zTableName /* Name of the table */ +){ + int i; + char *zSchema, *zNext; + const char *zSep = "("; + zSchema = sqlite3_mprintf("CREATE TABLE x"); + for(i=0; ibase */ + v->db = db; + v->zDb = spec->zDb; /* Freed when azColumn is freed */ + v->zName = spec->zName; /* Freed when azColumn is freed */ + v->nColumn = spec->nColumn; + v->azContentColumn = spec->azContentColumn; + spec->azContentColumn = 0; + v->azColumn = spec->azColumn; + spec->azColumn = 0; + + if( spec->azTokenizer==0 ){ + return SQLITE_NOMEM; + } + /* TODO(shess) For now, add new tokenizers as else if clauses. */ + if( spec->azTokenizer[0]==0 || startsWith(spec->azTokenizer[0], "simple") ){ + sqlite3Fts1SimpleTokenizerModule(&m); + }else if( startsWith(spec->azTokenizer[0], "porter") ){ + sqlite3Fts1PorterTokenizerModule(&m); + }else{ + *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]); + rc = SQLITE_ERROR; + goto err; + } + for(n=0; spec->azTokenizer[n]; n++){} + if( n ){ + rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1], + &v->pTokenizer); + }else{ + rc = m->xCreate(0, 0, &v->pTokenizer); + } + if( rc!=SQLITE_OK ) goto err; + v->pTokenizer->pModule = m; + + /* TODO: verify the existence of backing tables foo_content, foo_term */ + + schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn, + spec->zName); + rc = sqlite3_declare_vtab(db, schema); + sqlite3_free(schema); + if( rc!=SQLITE_OK ) goto err; + + memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements)); + + *ppVTab = &v->base; + TRACE(("FTS1 Connect %p\n", v)); + + return rc; + +err: + fulltext_vtab_destroy(v); + return rc; +} + +static int fulltextConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, + char **pzErr +){ + TableSpec spec; + int rc = parseSpec(&spec, argc, argv, pzErr); + if( rc!=SQLITE_OK ) return rc; + + rc = constructVtab(db, &spec, ppVTab, pzErr); + clearTableSpec(&spec); + return rc; +} + + /* The %_content table holds the text of each document, with + ** the rowid used as the docid. + ** + ** The %_term table maps each term to a document list blob + ** containing elements sorted by ascending docid, each element + ** encoded as: + ** + ** docid varint-encoded + ** token elements: + ** position+1 varint-encoded as delta from previous position + ** start offset varint-encoded as delta from previous start offset + ** end offset varint-encoded as delta from start offset + ** + ** The sentinel position of 0 indicates the end of the token list. + ** + ** Additionally, doclist blobs are chunked into multiple segments, + ** using segment to order the segments. New elements are added to + ** the segment at segment 0, until it exceeds CHUNK_MAX. Then + ** segment 0 is deleted, and the doclist is inserted at segment 1. + ** If there is already a doclist at segment 1, the segment 0 doclist + ** is merged with it, the segment 1 doclist is deleted, and the + ** merged doclist is inserted at segment 2, repeating those + ** operations until an insert succeeds. + ** + ** Since this structure doesn't allow us to update elements in place + ** in case of deletion or update, these are simply written to + ** segment 0 (with an empty token list in case of deletion), with + ** docListAccumulate() taking care to retain lower-segment + ** information in preference to higher-segment information. + */ + /* TODO(shess) Provide a VACUUM type operation which both removes + ** deleted elements which are no longer necessary, and duplicated + ** elements. I suspect this will probably not be necessary in + ** practice, though. + */ +static int fulltextCreate(sqlite3 *db, void *pAux, + int argc, const char * const *argv, + sqlite3_vtab **ppVTab, char **pzErr){ + int rc; + TableSpec spec; + StringBuffer schema; + TRACE(("FTS1 Create\n")); + + rc = parseSpec(&spec, argc, argv, pzErr); + if( rc!=SQLITE_OK ) return rc; + + initStringBuffer(&schema); + append(&schema, "CREATE TABLE %_content("); + appendList(&schema, spec.nColumn, spec.azContentColumn); + append(&schema, ")"); + rc = sql_exec(db, spec.zDb, spec.zName, schema.s); + free(schema.s); + if( rc!=SQLITE_OK ) goto out; + + rc = sql_exec(db, spec.zDb, spec.zName, + "create table %_term(term text, segment integer, doclist blob, " + "primary key(term, segment));"); + if( rc!=SQLITE_OK ) goto out; + + rc = constructVtab(db, &spec, ppVTab, pzErr); + +out: + clearTableSpec(&spec); + return rc; +} + +/* Decide how to handle an SQL query. */ +static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ + int i; + TRACE(("FTS1 BestIndex\n")); + + for(i=0; inConstraint; ++i){ + const struct sqlite3_index_constraint *pConstraint; + pConstraint = &pInfo->aConstraint[i]; + if( pConstraint->usable ) { + if( pConstraint->iColumn==-1 && + pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + pInfo->idxNum = QUERY_ROWID; /* lookup by rowid */ + TRACE(("FTS1 QUERY_ROWID\n")); + } else if( pConstraint->iColumn>=0 && + pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ + /* full-text search */ + pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn; + TRACE(("FTS1 QUERY_FULLTEXT %d\n", pConstraint->iColumn)); + } else continue; + + pInfo->aConstraintUsage[i].argvIndex = 1; + pInfo->aConstraintUsage[i].omit = 1; + + /* An arbitrary value for now. + * TODO: Perhaps rowid matches should be considered cheaper than + * full-text searches. */ + pInfo->estimatedCost = 1.0; + + return SQLITE_OK; + } + } + pInfo->idxNum = QUERY_GENERIC; + return SQLITE_OK; +} + +static int fulltextDisconnect(sqlite3_vtab *pVTab){ + TRACE(("FTS1 Disconnect %p\n", pVTab)); + fulltext_vtab_destroy((fulltext_vtab *)pVTab); + return SQLITE_OK; +} + +static int fulltextDestroy(sqlite3_vtab *pVTab){ + fulltext_vtab *v = (fulltext_vtab *)pVTab; + int rc; + + TRACE(("FTS1 Destroy %p\n", pVTab)); + rc = sql_exec(v->db, v->zDb, v->zName, + "drop table if exists %_content;" + "drop table if exists %_term;" + ); + if( rc!=SQLITE_OK ) return rc; + + fulltext_vtab_destroy((fulltext_vtab *)pVTab); + return SQLITE_OK; +} + +static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + fulltext_cursor *c; + + c = (fulltext_cursor *) calloc(sizeof(fulltext_cursor), 1); + /* sqlite will initialize c->base */ + *ppCursor = &c->base; + TRACE(("FTS1 Open %p: %p\n", pVTab, c)); + + return SQLITE_OK; +} + + +/* Free all of the dynamically allocated memory held by *q +*/ +static void queryClear(Query *q){ + int i; + for(i = 0; i < q->nTerms; ++i){ + free(q->pTerms[i].pTerm); + } + free(q->pTerms); + memset(q, 0, sizeof(*q)); +} + +/* Free all of the dynamically allocated memory held by the +** Snippet +*/ +static void snippetClear(Snippet *p){ + free(p->aMatch); + free(p->zOffset); + free(p->zSnippet); + memset(p, 0, sizeof(*p)); +} +/* +** Append a single entry to the p->aMatch[] log. +*/ +static void snippetAppendMatch( + Snippet *p, /* Append the entry to this snippet */ + int iCol, int iTerm, /* The column and query term */ + int iStart, int nByte /* Offset and size of the match */ +){ + int i; + struct snippetMatch *pMatch; + if( p->nMatch+1>=p->nAlloc ){ + p->nAlloc = p->nAlloc*2 + 10; + p->aMatch = realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) ); + if( p->aMatch==0 ){ + p->nMatch = 0; + p->nAlloc = 0; + return; + } + } + i = p->nMatch++; + pMatch = &p->aMatch[i]; + pMatch->iCol = iCol; + pMatch->iTerm = iTerm; + pMatch->iStart = iStart; + pMatch->nByte = nByte; +} + +/* +** Sizing information for the circular buffer used in snippetOffsetsOfColumn() +*/ +#define FTS1_ROTOR_SZ (32) +#define FTS1_ROTOR_MASK (FTS1_ROTOR_SZ-1) + +/* +** Add entries to pSnippet->aMatch[] for every match that occurs against +** document zDoc[0..nDoc-1] which is stored in column iColumn. +*/ +static void snippetOffsetsOfColumn( + Query *pQuery, + Snippet *pSnippet, + int iColumn, + const char *zDoc, + int nDoc +){ + const sqlite3_tokenizer_module *pTModule; /* The tokenizer module */ + sqlite3_tokenizer *pTokenizer; /* The specific tokenizer */ + sqlite3_tokenizer_cursor *pTCursor; /* Tokenizer cursor */ + fulltext_vtab *pVtab; /* The full text index */ + int nColumn; /* Number of columns in the index */ + const QueryTerm *aTerm; /* Query string terms */ + int nTerm; /* Number of query string terms */ + int i, j; /* Loop counters */ + int rc; /* Return code */ + unsigned int match, prevMatch; /* Phrase search bitmasks */ + const char *zToken; /* Next token from the tokenizer */ + int nToken; /* Size of zToken */ + int iBegin, iEnd, iPos; /* Offsets of beginning and end */ + + /* The following variables keep a circular buffer of the last + ** few tokens */ + unsigned int iRotor = 0; /* Index of current token */ + int iRotorBegin[FTS1_ROTOR_SZ]; /* Beginning offset of token */ + int iRotorLen[FTS1_ROTOR_SZ]; /* Length of token */ + + pVtab = pQuery->pFts; + nColumn = pVtab->nColumn; + pTokenizer = pVtab->pTokenizer; + pTModule = pTokenizer->pModule; + rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor); + if( rc ) return; + pTCursor->pTokenizer = pTokenizer; + aTerm = pQuery->pTerms; + nTerm = pQuery->nTerms; + if( nTerm>=FTS1_ROTOR_SZ ){ + nTerm = FTS1_ROTOR_SZ - 1; + } + prevMatch = 0; + while(1){ + rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos); + if( rc ) break; + iRotorBegin[iRotor&FTS1_ROTOR_MASK] = iBegin; + iRotorLen[iRotor&FTS1_ROTOR_MASK] = iEnd-iBegin; + match = 0; + for(i=0; i=0 && iCol1 && (prevMatch & (1<=0; j--){ + int k = (iRotor-j) & FTS1_ROTOR_MASK; + snippetAppendMatch(pSnippet, iColumn, i-j, + iRotorBegin[k], iRotorLen[k]); + } + } + } + prevMatch = match<<1; + iRotor++; + } + pTModule->xClose(pTCursor); +} + + +/* +** Compute all offsets for the current row of the query. +** If the offsets have already been computed, this routine is a no-op. +*/ +static void snippetAllOffsets(fulltext_cursor *p){ + int nColumn; + int iColumn, i; + int iFirst, iLast; + fulltext_vtab *pFts; + + if( p->snippet.nMatch ) return; + if( p->q.nTerms==0 ) return; + pFts = p->q.pFts; + nColumn = pFts->nColumn; + iColumn = p->iCursorType - QUERY_FULLTEXT; + if( iColumn<0 || iColumn>=nColumn ){ + iFirst = 0; + iLast = nColumn-1; + }else{ + iFirst = iColumn; + iLast = iColumn; + } + for(i=iFirst; i<=iLast; i++){ + const char *zDoc; + int nDoc; + zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1); + nDoc = sqlite3_column_bytes(p->pStmt, i+1); + snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc); + } +} + +/* +** Convert the information in the aMatch[] array of the snippet +** into the string zOffset[0..nOffset-1]. +*/ +static void snippetOffsetText(Snippet *p){ + int i; + int cnt = 0; + StringBuffer sb; + char zBuf[200]; + if( p->zOffset ) return; + initStringBuffer(&sb); + for(i=0; inMatch; i++){ + struct snippetMatch *pMatch = &p->aMatch[i]; + zBuf[0] = ' '; + sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d", + pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte); + append(&sb, zBuf); + cnt++; + } + p->zOffset = sb.s; + p->nOffset = sb.len; +} + +/* +** zDoc[0..nDoc-1] is phrase of text. aMatch[0..nMatch-1] are a set +** of matching words some of which might be in zDoc. zDoc is column +** number iCol. +** +** iBreak is suggested spot in zDoc where we could begin or end an +** excerpt. Return a value similar to iBreak but possibly adjusted +** to be a little left or right so that the break point is better. +*/ +static int wordBoundary( + int iBreak, /* The suggested break point */ + const char *zDoc, /* Document text */ + int nDoc, /* Number of bytes in zDoc[] */ + struct snippetMatch *aMatch, /* Matching words */ + int nMatch, /* Number of entries in aMatch[] */ + int iCol /* The column number for zDoc[] */ +){ + int i; + if( iBreak<=10 ){ + return 0; + } + if( iBreak>=nDoc-10 ){ + return nDoc; + } + for(i=0; i0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){ + return aMatch[i-1].iStart; + } + } + for(i=1; i<=10; i++){ + if( safe_isspace(zDoc[iBreak-i]) ){ + return iBreak - i + 1; + } + if( safe_isspace(zDoc[iBreak+i]) ){ + return iBreak + i + 1; + } + } + return iBreak; +} + +/* +** If the StringBuffer does not end in white space, add a single +** space character to the end. +*/ +static void appendWhiteSpace(StringBuffer *p){ + if( p->len==0 ) return; + if( safe_isspace(p->s[p->len-1]) ) return; + append(p, " "); +} + +/* +** Remove white space from teh end of the StringBuffer +*/ +static void trimWhiteSpace(StringBuffer *p){ + while( p->len>0 && safe_isspace(p->s[p->len-1]) ){ + p->len--; + } +} + + + +/* +** Allowed values for Snippet.aMatch[].snStatus +*/ +#define SNIPPET_IGNORE 0 /* It is ok to omit this match from the snippet */ +#define SNIPPET_DESIRED 1 /* We want to include this match in the snippet */ + +/* +** Generate the text of a snippet. +*/ +static void snippetText( + fulltext_cursor *pCursor, /* The cursor we need the snippet for */ + const char *zStartMark, /* Markup to appear before each match */ + const char *zEndMark, /* Markup to appear after each match */ + const char *zEllipsis /* Ellipsis mark */ +){ + int i, j; + struct snippetMatch *aMatch; + int nMatch; + int nDesired; + StringBuffer sb; + int tailCol; + int tailOffset; + int iCol; + int nDoc; + const char *zDoc; + int iStart, iEnd; + int tailEllipsis = 0; + int iMatch; + + + free(pCursor->snippet.zSnippet); + pCursor->snippet.zSnippet = 0; + aMatch = pCursor->snippet.aMatch; + nMatch = pCursor->snippet.nMatch; + initStringBuffer(&sb); + + for(i=0; iq.nTerms; i++){ + for(j=0; j0; i++){ + if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue; + nDesired--; + iCol = aMatch[i].iCol; + zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1); + nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1); + iStart = aMatch[i].iStart - 40; + iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol); + if( iStart<=10 ){ + iStart = 0; + } + if( iCol==tailCol && iStart<=tailOffset+20 ){ + iStart = tailOffset; + } + if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){ + trimWhiteSpace(&sb); + appendWhiteSpace(&sb); + append(&sb, zEllipsis); + appendWhiteSpace(&sb); + } + iEnd = aMatch[i].iStart + aMatch[i].nByte + 40; + iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol); + if( iEnd>=nDoc-10 ){ + iEnd = nDoc; + tailEllipsis = 0; + }else{ + tailEllipsis = 1; + } + while( iMatchsnippet.zSnippet = sb.s; + pCursor->snippet.nSnippet = sb.len; +} + + +/* +** Close the cursor. For additional information see the documentation +** on the xClose method of the virtual table interface. +*/ +static int fulltextClose(sqlite3_vtab_cursor *pCursor){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + TRACE(("FTS1 Close %p\n", c)); + sqlite3_finalize(c->pStmt); + queryClear(&c->q); + snippetClear(&c->snippet); + if( c->result.pDoclist!=NULL ){ + docListDelete(c->result.pDoclist); + } + free(c); + return SQLITE_OK; +} + +static int fulltextNext(sqlite3_vtab_cursor *pCursor){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + sqlite_int64 iDocid; + int rc; + + TRACE(("FTS1 Next %p\n", pCursor)); + snippetClear(&c->snippet); + if( c->iCursorType < QUERY_FULLTEXT ){ + /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */ + rc = sqlite3_step(c->pStmt); + switch( rc ){ + case SQLITE_ROW: + c->eof = 0; + return SQLITE_OK; + case SQLITE_DONE: + c->eof = 1; + return SQLITE_OK; + default: + c->eof = 1; + return rc; + } + } else { /* full-text query */ + rc = sqlite3_reset(c->pStmt); + if( rc!=SQLITE_OK ) return rc; + + iDocid = nextDocid(&c->result); + if( iDocid==0 ){ + c->eof = 1; + return SQLITE_OK; + } + rc = sqlite3_bind_int64(c->pStmt, 1, iDocid); + if( rc!=SQLITE_OK ) return rc; + /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */ + rc = sqlite3_step(c->pStmt); + if( rc==SQLITE_ROW ){ /* the case we expect */ + c->eof = 0; + return SQLITE_OK; + } + /* an error occurred; abort */ + return rc==SQLITE_DONE ? SQLITE_ERROR : rc; + } +} + + +/* Return a DocList corresponding to the query term *pTerm. If *pTerm +** is the first term of a phrase query, go ahead and evaluate the phrase +** query and return the doclist for the entire phrase query. +** +** The result is stored in pTerm->doclist. +*/ +static int docListOfTerm( + fulltext_vtab *v, /* The full text index */ + int iColumn, /* column to restrict to. No restrition if >=nColumn */ + QueryTerm *pQTerm, /* Term we are looking for, or 1st term of a phrase */ + DocList **ppResult /* Write the result here */ +){ + DocList *pLeft, *pRight, *pNew; + int i, rc; + + pLeft = docListNew(DL_POSITIONS); + rc = term_select_all(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pLeft); + if( rc ){ + docListDelete(pLeft); + return rc; + } + for(i=1; i<=pQTerm->nPhrase; i++){ + pRight = docListNew(DL_POSITIONS); + rc = term_select_all(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm, pRight); + if( rc ){ + docListDelete(pLeft); + return rc; + } + pNew = docListNew(inPhrase ? DL_POSITIONS : DL_DOCIDS); + docListPhraseMerge(pLeft, pRight, pNew); + docListDelete(pLeft); + docListDelete(pRight); + pLeft = pNew; + } + *ppResult = pLeft; + return SQLITE_OK; +} + +/* Add a new term pTerm[0..nTerm-1] to the query *q. +*/ +static void queryAdd(Query *q, const char *pTerm, int nTerm){ + QueryTerm *t; + ++q->nTerms; + q->pTerms = realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0])); + if( q->pTerms==0 ){ + q->nTerms = 0; + return; + } + t = &q->pTerms[q->nTerms - 1]; + memset(t, 0, sizeof(*t)); + t->pTerm = malloc(nTerm+1); + memcpy(t->pTerm, pTerm, nTerm); + t->pTerm[nTerm] = 0; + t->nTerm = nTerm; + t->isOr = q->nextIsOr; + q->nextIsOr = 0; + t->iColumn = q->nextColumn; + q->nextColumn = q->dfltColumn; +} + +/* +** Check to see if the string zToken[0...nToken-1] matches any +** column name in the virtual table. If it does, +** return the zero-indexed column number. If not, return -1. +*/ +static int checkColumnSpecifier( + fulltext_vtab *pVtab, /* The virtual table */ + const char *zToken, /* Text of the token */ + int nToken /* Number of characters in the token */ +){ + int i; + for(i=0; inColumn; i++){ + if( memcmp(pVtab->azColumn[i], zToken, nToken)==0 + && pVtab->azColumn[i][nToken]==0 ){ + return i; + } + } + return -1; +} + +/* +** Parse the text at pSegment[0..nSegment-1]. Add additional terms +** to the query being assemblied in pQuery. +** +** inPhrase is true if pSegment[0..nSegement-1] is contained within +** double-quotes. If inPhrase is true, then the first term +** is marked with the number of terms in the phrase less one and +** OR and "-" syntax is ignored. If inPhrase is false, then every +** term found is marked with nPhrase=0 and OR and "-" syntax is significant. +*/ +static int tokenizeSegment( + sqlite3_tokenizer *pTokenizer, /* The tokenizer to use */ + const char *pSegment, int nSegment, /* Query expression being parsed */ + int inPhrase, /* True if within "..." */ + Query *pQuery /* Append results here */ +){ + const sqlite3_tokenizer_module *pModule = pTokenizer->pModule; + sqlite3_tokenizer_cursor *pCursor; + int firstIndex = pQuery->nTerms; + int iCol; + int nTerm = 1; + + int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor); + if( rc!=SQLITE_OK ) return rc; + pCursor->pTokenizer = pTokenizer; + + while( 1 ){ + const char *pToken; + int nToken, iBegin, iEnd, iPos; + + rc = pModule->xNext(pCursor, + &pToken, &nToken, + &iBegin, &iEnd, &iPos); + if( rc!=SQLITE_OK ) break; + if( !inPhrase && + pSegment[iEnd]==':' && + (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){ + pQuery->nextColumn = iCol; + continue; + } + if( !inPhrase && pQuery->nTerms>0 && nToken==2 + && pSegment[iBegin]=='O' && pSegment[iBegin+1]=='R' ){ + pQuery->nextIsOr = 1; + continue; + } + queryAdd(pQuery, pToken, nToken); + if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){ + pQuery->pTerms[pQuery->nTerms-1].isNot = 1; + } + pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm; + if( inPhrase ){ + nTerm++; + } + } + + if( inPhrase && pQuery->nTerms>firstIndex ){ + pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1; + } + + return pModule->xClose(pCursor); +} + +/* Parse a query string, yielding a Query object pQuery. +** +** The calling function will need to queryClear() to clean up +** the dynamically allocated memory held by pQuery. +*/ +static int parseQuery( + fulltext_vtab *v, /* The fulltext index */ + const char *zInput, /* Input text of the query string */ + int nInput, /* Size of the input text */ + int dfltColumn, /* Default column of the index to match against */ + Query *pQuery /* Write the parse results here. */ +){ + int iInput, inPhrase = 0; + + if( zInput==0 ) nInput = 0; + if( nInput<0 ) nInput = strlen(zInput); + pQuery->nTerms = 0; + pQuery->pTerms = NULL; + pQuery->nextIsOr = 0; + pQuery->nextColumn = dfltColumn; + pQuery->dfltColumn = dfltColumn; + pQuery->pFts = v; + + for(iInput=0; iInputiInput ){ + tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase, + pQuery); + } + iInput = i; + if( i=nColumn +** they are allowed to match against any column. +*/ +static int fulltextQuery( + fulltext_vtab *v, /* The full text index */ + int iColumn, /* Match against this column by default */ + const char *zInput, /* The query string */ + int nInput, /* Number of bytes in zInput[] */ + DocList **pResult, /* Write the result doclist here */ + Query *pQuery /* Put parsed query string here */ +){ + int i, iNext, rc; + DocList *pLeft = NULL; + DocList *pRight, *pNew, *pOr; + int nNot = 0; + QueryTerm *aTerm; + + rc = parseQuery(v, zInput, nInput, iColumn, pQuery); + if( rc!=SQLITE_OK ) return rc; + + /* Merge AND terms. */ + aTerm = pQuery->pTerms; + for(i = 0; inTerms; i=iNext){ + if( aTerm[i].isNot ){ + /* Handle all NOT terms in a separate pass */ + nNot++; + iNext = i + aTerm[i].nPhrase+1; + continue; + } + iNext = i + aTerm[i].nPhrase + 1; + rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &pRight); + if( rc ){ + queryClear(pQuery); + return rc; + } + while( iNextnTerms && aTerm[iNext].isOr ){ + rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &pOr); + iNext += aTerm[iNext].nPhrase + 1; + if( rc ){ + queryClear(pQuery); + return rc; + } + pNew = docListNew(DL_DOCIDS); + docListOrMerge(pRight, pOr, pNew); + docListDelete(pRight); + docListDelete(pOr); + pRight = pNew; + } + if( pLeft==0 ){ + pLeft = pRight; + }else{ + pNew = docListNew(DL_DOCIDS); + docListAndMerge(pLeft, pRight, pNew); + docListDelete(pRight); + docListDelete(pLeft); + pLeft = pNew; + } + } + + if( nNot && pLeft==0 ){ + /* We do not yet know how to handle a query of only NOT terms */ + return SQLITE_ERROR; + } + + /* Do the EXCEPT terms */ + for(i=0; inTerms; i += aTerm[i].nPhrase + 1){ + if( !aTerm[i].isNot ) continue; + rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &pRight); + if( rc ){ + queryClear(pQuery); + docListDelete(pLeft); + return rc; + } + pNew = docListNew(DL_DOCIDS); + docListExceptMerge(pLeft, pRight, pNew); + docListDelete(pRight); + docListDelete(pLeft); + pLeft = pNew; + } + + *pResult = pLeft; + return rc; +} + +/* +** This is the xFilter interface for the virtual table. See +** the virtual table xFilter method documentation for additional +** information. +** +** If idxNum==QUERY_GENERIC then do a full table scan against +** the %_content table. +** +** If idxNum==QUERY_ROWID then do a rowid lookup for a single entry +** in the %_content table. +** +** If idxNum>=QUERY_FULLTEXT then use the full text index. The +** column on the left-hand side of the MATCH operator is column +** number idxNum-QUERY_FULLTEXT, 0 indexed. argv[0] is the right-hand +** side of the MATCH operator. +*/ +/* TODO(shess) Upgrade the cursor initialization and destruction to +** account for fulltextFilter() being called multiple times on the +** same cursor. The current solution is very fragile. Apply fix to +** fts2 as appropriate. +*/ +static int fulltextFilter( + sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + int idxNum, const char *idxStr, /* Which indexing scheme to use */ + int argc, sqlite3_value **argv /* Arguments for the indexing scheme */ +){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + fulltext_vtab *v = cursor_vtab(c); + int rc; + char *zSql; + + TRACE(("FTS1 Filter %p\n",pCursor)); + + zSql = sqlite3_mprintf("select rowid, * from %%_content %s", + idxNum==QUERY_GENERIC ? "" : "where rowid=?"); + sqlite3_finalize(c->pStmt); + rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, zSql); + sqlite3_free(zSql); + if( rc!=SQLITE_OK ) return rc; + + c->iCursorType = idxNum; + switch( idxNum ){ + case QUERY_GENERIC: + break; + + case QUERY_ROWID: + rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0])); + if( rc!=SQLITE_OK ) return rc; + break; + + default: /* full-text search */ + { + const char *zQuery = (const char *)sqlite3_value_text(argv[0]); + DocList *pResult; + assert( idxNum<=QUERY_FULLTEXT+v->nColumn); + assert( argc==1 ); + queryClear(&c->q); + rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &pResult, &c->q); + if( rc!=SQLITE_OK ) return rc; + if( c->result.pDoclist!=NULL ) docListDelete(c->result.pDoclist); + readerInit(&c->result, pResult); + break; + } + } + + return fulltextNext(pCursor); +} + +/* This is the xEof method of the virtual table. The SQLite core +** calls this routine to find out if it has reached the end of +** a query's results set. +*/ +static int fulltextEof(sqlite3_vtab_cursor *pCursor){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + return c->eof; +} + +/* This is the xColumn method of the virtual table. The SQLite +** core calls this method during a query when it needs the value +** of a column from the virtual table. This method needs to use +** one of the sqlite3_result_*() routines to store the requested +** value back in the pContext. +*/ +static int fulltextColumn(sqlite3_vtab_cursor *pCursor, + sqlite3_context *pContext, int idxCol){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + fulltext_vtab *v = cursor_vtab(c); + + if( idxColnColumn ){ + sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1); + sqlite3_result_value(pContext, pVal); + }else if( idxCol==v->nColumn ){ + /* The extra column whose name is the same as the table. + ** Return a blob which is a pointer to the cursor + */ + sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT); + } + return SQLITE_OK; +} + +/* This is the xRowid method. The SQLite core calls this routine to +** retrive the rowid for the current row of the result set. The +** rowid should be written to *pRowid. +*/ +static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + + *pRowid = sqlite3_column_int64(c->pStmt, 0); + return SQLITE_OK; +} + +/* Add all terms in [zText] to the given hash table. If [iColumn] > 0, + * we also store positions and offsets in the hash table using the given + * column number. */ +static int buildTerms(fulltext_vtab *v, fts1Hash *terms, sqlite_int64 iDocid, + const char *zText, int iColumn){ + sqlite3_tokenizer *pTokenizer = v->pTokenizer; + sqlite3_tokenizer_cursor *pCursor; + const char *pToken; + int nTokenBytes; + int iStartOffset, iEndOffset, iPosition; + int rc; + + rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor); + if( rc!=SQLITE_OK ) return rc; + + pCursor->pTokenizer = pTokenizer; + while( SQLITE_OK==pTokenizer->pModule->xNext(pCursor, + &pToken, &nTokenBytes, + &iStartOffset, &iEndOffset, + &iPosition) ){ + DocList *p; + + /* Positions can't be negative; we use -1 as a terminator internally. */ + if( iPosition<0 ){ + pTokenizer->pModule->xClose(pCursor); + return SQLITE_ERROR; + } + + p = fts1HashFind(terms, pToken, nTokenBytes); + if( p==NULL ){ + p = docListNew(DL_DEFAULT); + docListAddDocid(p, iDocid); + fts1HashInsert(terms, pToken, nTokenBytes, p); + } + if( iColumn>=0 ){ + docListAddPosOffset(p, iColumn, iPosition, iStartOffset, iEndOffset); + } + } + + /* TODO(shess) Check return? Should this be able to cause errors at + ** this point? Actually, same question about sqlite3_finalize(), + ** though one could argue that failure there means that the data is + ** not durable. *ponder* + */ + pTokenizer->pModule->xClose(pCursor); + return rc; +} + +/* Update the %_terms table to map the term [pTerm] to the given rowid. */ +static int index_insert_term(fulltext_vtab *v, const char *pTerm, int nTerm, + DocList *d){ + sqlite_int64 iIndexRow; + DocList doclist; + int iSegment = 0, rc; + + rc = term_select(v, pTerm, nTerm, iSegment, &iIndexRow, &doclist); + if( rc==SQLITE_DONE ){ + docListInit(&doclist, DL_DEFAULT, 0, 0); + docListUpdate(&doclist, d); + /* TODO(shess) Consider length(doclist)>CHUNK_MAX? */ + rc = term_insert(v, NULL, pTerm, nTerm, iSegment, &doclist); + goto err; + } + if( rc!=SQLITE_ROW ) return SQLITE_ERROR; + + docListUpdate(&doclist, d); + if( doclist.nData<=CHUNK_MAX ){ + rc = term_update(v, iIndexRow, &doclist); + goto err; + } + + /* Doclist doesn't fit, delete what's there, and accumulate + ** forward. + */ + rc = term_delete(v, iIndexRow); + if( rc!=SQLITE_OK ) goto err; + + /* Try to insert the doclist into a higher segment bucket. On + ** failure, accumulate existing doclist with the doclist from that + ** bucket, and put results in the next bucket. + */ + iSegment++; + while( (rc=term_insert(v, &iIndexRow, pTerm, nTerm, iSegment, + &doclist))!=SQLITE_OK ){ + sqlite_int64 iSegmentRow; + DocList old; + int rc2; + + /* Retain old error in case the term_insert() error was really an + ** error rather than a bounced insert. + */ + rc2 = term_select(v, pTerm, nTerm, iSegment, &iSegmentRow, &old); + if( rc2!=SQLITE_ROW ) goto err; + + rc = term_delete(v, iSegmentRow); + if( rc!=SQLITE_OK ) goto err; + + /* Reusing lowest-number deleted row keeps the index smaller. */ + if( iSegmentRownColumn ; ++i){ + char *zText = (char*)sqlite3_value_text(pValues[i]); + int rc = buildTerms(v, terms, iRowid, zText, i); + if( rc!=SQLITE_OK ) return rc; + } + return SQLITE_OK; +} + +/* Add empty doclists for all terms in the given row's content to the hash + * table [pTerms]. */ +static int deleteTerms(fulltext_vtab *v, fts1Hash *pTerms, sqlite_int64 iRowid){ + const char **pValues; + int i; + + int rc = content_select(v, iRowid, &pValues); + if( rc!=SQLITE_OK ) return rc; + + for(i = 0 ; i < v->nColumn; ++i) { + rc = buildTerms(v, pTerms, iRowid, pValues[i], -1); + if( rc!=SQLITE_OK ) break; + } + + freeStringArray(v->nColumn, pValues); + return SQLITE_OK; +} + +/* Insert a row into the %_content table; set *piRowid to be the ID of the + * new row. Fill [pTerms] with new doclists for the %_term table. */ +static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestRowid, + sqlite3_value **pValues, + sqlite_int64 *piRowid, fts1Hash *pTerms){ + int rc; + + rc = content_insert(v, pRequestRowid, pValues); /* execute an SQL INSERT */ + if( rc!=SQLITE_OK ) return rc; + *piRowid = sqlite3_last_insert_rowid(v->db); + return insertTerms(v, pTerms, *piRowid, pValues); +} + +/* Delete a row from the %_content table; fill [pTerms] with empty doclists + * to be written to the %_term table. */ +static int index_delete(fulltext_vtab *v, sqlite_int64 iRow, fts1Hash *pTerms){ + int rc = deleteTerms(v, pTerms, iRow); + if( rc!=SQLITE_OK ) return rc; + return content_delete(v, iRow); /* execute an SQL DELETE */ +} + +/* Update a row in the %_content table; fill [pTerms] with new doclists for the + * %_term table. */ +static int index_update(fulltext_vtab *v, sqlite_int64 iRow, + sqlite3_value **pValues, fts1Hash *pTerms){ + /* Generate an empty doclist for each term that previously appeared in this + * row. */ + int rc = deleteTerms(v, pTerms, iRow); + if( rc!=SQLITE_OK ) return rc; + + rc = content_update(v, pValues, iRow); /* execute an SQL UPDATE */ + if( rc!=SQLITE_OK ) return rc; + + /* Now add positions for terms which appear in the updated row. */ + return insertTerms(v, pTerms, iRow, pValues); +} + +/* This function implements the xUpdate callback; it is the top-level entry + * point for inserting, deleting or updating a row in a full-text table. */ +static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg, + sqlite_int64 *pRowid){ + fulltext_vtab *v = (fulltext_vtab *) pVtab; + fts1Hash terms; /* maps term string -> PosList */ + int rc; + fts1HashElem *e; + + TRACE(("FTS1 Update %p\n", pVtab)); + + fts1HashInit(&terms, FTS1_HASH_STRING, 1); + + if( nArg<2 ){ + rc = index_delete(v, sqlite3_value_int64(ppArg[0]), &terms); + } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){ + /* An update: + * ppArg[0] = old rowid + * ppArg[1] = new rowid + * ppArg[2..2+v->nColumn-1] = values + * ppArg[2+v->nColumn] = value for magic column (we ignore this) + */ + sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]); + if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER || + sqlite3_value_int64(ppArg[1]) != rowid ){ + rc = SQLITE_ERROR; /* we don't allow changing the rowid */ + } else { + assert( nArg==2+v->nColumn+1); + rc = index_update(v, rowid, &ppArg[2], &terms); + } + } else { + /* An insert: + * ppArg[1] = requested rowid + * ppArg[2..2+v->nColumn-1] = values + * ppArg[2+v->nColumn] = value for magic column (we ignore this) + */ + assert( nArg==2+v->nColumn+1); + rc = index_insert(v, ppArg[1], &ppArg[2], pRowid, &terms); + } + + if( rc==SQLITE_OK ){ + /* Write updated doclists to disk. */ + for(e=fts1HashFirst(&terms); e; e=fts1HashNext(e)){ + DocList *p = fts1HashData(e); + rc = index_insert_term(v, fts1HashKey(e), fts1HashKeysize(e), p); + if( rc!=SQLITE_OK ) break; + } + } + + /* clean up */ + for(e=fts1HashFirst(&terms); e; e=fts1HashNext(e)){ + DocList *p = fts1HashData(e); + docListDelete(p); + } + fts1HashClear(&terms); + + return rc; +} + +/* +** Implementation of the snippet() function for FTS1 +*/ +static void snippetFunc( + sqlite3_context *pContext, + int argc, + sqlite3_value **argv +){ + fulltext_cursor *pCursor; + if( argc<1 ) return; + if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || + sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ + sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1); + }else{ + const char *zStart = ""; + const char *zEnd = ""; + const char *zEllipsis = "..."; + memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); + if( argc>=2 ){ + zStart = (const char*)sqlite3_value_text(argv[1]); + if( argc>=3 ){ + zEnd = (const char*)sqlite3_value_text(argv[2]); + if( argc>=4 ){ + zEllipsis = (const char*)sqlite3_value_text(argv[3]); + } + } + } + snippetAllOffsets(pCursor); + snippetText(pCursor, zStart, zEnd, zEllipsis); + sqlite3_result_text(pContext, pCursor->snippet.zSnippet, + pCursor->snippet.nSnippet, SQLITE_STATIC); + } +} + +/* +** Implementation of the offsets() function for FTS1 +*/ +static void snippetOffsetsFunc( + sqlite3_context *pContext, + int argc, + sqlite3_value **argv +){ + fulltext_cursor *pCursor; + if( argc<1 ) return; + if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || + sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ + sqlite3_result_error(pContext, "illegal first argument to offsets",-1); + }else{ + memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); + snippetAllOffsets(pCursor); + snippetOffsetText(&pCursor->snippet); + sqlite3_result_text(pContext, + pCursor->snippet.zOffset, pCursor->snippet.nOffset, + SQLITE_STATIC); + } +} + +/* +** This routine implements the xFindFunction method for the FTS1 +** virtual table. +*/ +static int fulltextFindFunction( + sqlite3_vtab *pVtab, + int nArg, + const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg +){ + if( strcmp(zName,"snippet")==0 ){ + *pxFunc = snippetFunc; + return 1; + }else if( strcmp(zName,"offsets")==0 ){ + *pxFunc = snippetOffsetsFunc; + return 1; + } + return 0; +} + +/* +** Rename an fts1 table. +*/ +static int fulltextRename( + sqlite3_vtab *pVtab, + const char *zName +){ + fulltext_vtab *p = (fulltext_vtab *)pVtab; + int rc = SQLITE_NOMEM; + char *zSql = sqlite3_mprintf( + "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';" + "ALTER TABLE %Q.'%q_term' RENAME TO '%q_term';" + , p->zDb, p->zName, zName + , p->zDb, p->zName, zName + ); + if( zSql ){ + rc = sqlite3_exec(p->db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } + return rc; +} + +static const sqlite3_module fulltextModule = { + /* iVersion */ 0, + /* xCreate */ fulltextCreate, + /* xConnect */ fulltextConnect, + /* xBestIndex */ fulltextBestIndex, + /* xDisconnect */ fulltextDisconnect, + /* xDestroy */ fulltextDestroy, + /* xOpen */ fulltextOpen, + /* xClose */ fulltextClose, + /* xFilter */ fulltextFilter, + /* xNext */ fulltextNext, + /* xEof */ fulltextEof, + /* xColumn */ fulltextColumn, + /* xRowid */ fulltextRowid, + /* xUpdate */ fulltextUpdate, + /* xBegin */ 0, + /* xSync */ 0, + /* xCommit */ 0, + /* xRollback */ 0, + /* xFindFunction */ fulltextFindFunction, + /* xRename */ fulltextRename, +}; + +int sqlite3Fts1Init(sqlite3 *db){ + sqlite3_overload_function(db, "snippet", -1); + sqlite3_overload_function(db, "offsets", -1); + return sqlite3_create_module(db, "fts1", &fulltextModule, 0); +} + +#if !SQLITE_CORE +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_fts1_init(sqlite3 *db, char **pzErrMsg, + const sqlite3_api_routines *pApi){ + SQLITE_EXTENSION_INIT2(pApi) + return sqlite3Fts1Init(db); +} +#endif + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) */ diff --git a/components/external/SQLite-3.8.1/ext/fts1/fts1.h b/components/external/SQLite-3.8.1/ext/fts1/fts1.h new file mode 100644 index 0000000000000000000000000000000000000000..d55e68973321a657ed36b8b00b4df8a334291d9d --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/fts1.h @@ -0,0 +1,11 @@ +#include "sqlite3.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +int sqlite3Fts1Init(sqlite3 *db); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ diff --git a/components/external/SQLite-3.8.1/ext/fts1/fts1_hash.c b/components/external/SQLite-3.8.1/ext/fts1/fts1_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..463a52b64555b00e01845983d2874235e53d7a17 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/fts1_hash.c @@ -0,0 +1,369 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the implementation of generic hash-tables used in SQLite. +** We've modified it slightly to serve as a standalone hash table +** implementation for the full-text indexing module. +*/ +#include +#include +#include + +/* +** The code in this file is only compiled if: +** +** * The FTS1 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS1 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS1 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) + + +#include "fts1_hash.h" + +static void *malloc_and_zero(int n){ + void *p = malloc(n); + if( p ){ + memset(p, 0, n); + } + return p; +} + +/* Turn bulk memory into a hash table object by initializing the +** fields of the Hash structure. +** +** "pNew" is a pointer to the hash table that is to be initialized. +** keyClass is one of the constants +** FTS1_HASH_BINARY or FTS1_HASH_STRING. The value of keyClass +** determines what kind of key the hash table will use. "copyKey" is +** true if the hash table should make its own private copy of keys and +** false if it should just use the supplied pointer. +*/ +void sqlite3Fts1HashInit(fts1Hash *pNew, int keyClass, int copyKey){ + assert( pNew!=0 ); + assert( keyClass>=FTS1_HASH_STRING && keyClass<=FTS1_HASH_BINARY ); + pNew->keyClass = keyClass; + pNew->copyKey = copyKey; + pNew->first = 0; + pNew->count = 0; + pNew->htsize = 0; + pNew->ht = 0; + pNew->xMalloc = malloc_and_zero; + pNew->xFree = free; +} + +/* Remove all entries from a hash table. Reclaim all memory. +** Call this routine to delete a hash table or to reset a hash table +** to the empty state. +*/ +void sqlite3Fts1HashClear(fts1Hash *pH){ + fts1HashElem *elem; /* For looping over all elements of the table */ + + assert( pH!=0 ); + elem = pH->first; + pH->first = 0; + if( pH->ht ) pH->xFree(pH->ht); + pH->ht = 0; + pH->htsize = 0; + while( elem ){ + fts1HashElem *next_elem = elem->next; + if( pH->copyKey && elem->pKey ){ + pH->xFree(elem->pKey); + } + pH->xFree(elem); + elem = next_elem; + } + pH->count = 0; +} + +/* +** Hash and comparison functions when the mode is FTS1_HASH_STRING +*/ +static int strHash(const void *pKey, int nKey){ + const char *z = (const char *)pKey; + int h = 0; + if( nKey<=0 ) nKey = (int) strlen(z); + while( nKey > 0 ){ + h = (h<<3) ^ h ^ *z++; + nKey--; + } + return h & 0x7fffffff; +} +static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return strncmp((const char*)pKey1,(const char*)pKey2,n1); +} + +/* +** Hash and comparison functions when the mode is FTS1_HASH_BINARY +*/ +static int binHash(const void *pKey, int nKey){ + int h = 0; + const char *z = (const char *)pKey; + while( nKey-- > 0 ){ + h = (h<<3) ^ h ^ *(z++); + } + return h & 0x7fffffff; +} +static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return memcmp(pKey1,pKey2,n1); +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** The C syntax in this function definition may be unfamilar to some +** programmers, so we provide the following additional explanation: +** +** The name of the function is "hashFunction". The function takes a +** single parameter "keyClass". The return value of hashFunction() +** is a pointer to another function. Specifically, the return value +** of hashFunction() is a pointer to a function that takes two parameters +** with types "const void*" and "int" and returns an "int". +*/ +static int (*hashFunction(int keyClass))(const void*,int){ + if( keyClass==FTS1_HASH_STRING ){ + return &strHash; + }else{ + assert( keyClass==FTS1_HASH_BINARY ); + return &binHash; + } +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** For help in interpreted the obscure C code in the function definition, +** see the header comment on the previous function. +*/ +static int (*compareFunction(int keyClass))(const void*,int,const void*,int){ + if( keyClass==FTS1_HASH_STRING ){ + return &strCompare; + }else{ + assert( keyClass==FTS1_HASH_BINARY ); + return &binCompare; + } +} + +/* Link an element into the hash table +*/ +static void insertElement( + fts1Hash *pH, /* The complete hash table */ + struct _fts1ht *pEntry, /* The entry into which pNew is inserted */ + fts1HashElem *pNew /* The element to be inserted */ +){ + fts1HashElem *pHead; /* First element already in pEntry */ + pHead = pEntry->chain; + if( pHead ){ + pNew->next = pHead; + pNew->prev = pHead->prev; + if( pHead->prev ){ pHead->prev->next = pNew; } + else { pH->first = pNew; } + pHead->prev = pNew; + }else{ + pNew->next = pH->first; + if( pH->first ){ pH->first->prev = pNew; } + pNew->prev = 0; + pH->first = pNew; + } + pEntry->count++; + pEntry->chain = pNew; +} + + +/* Resize the hash table so that it cantains "new_size" buckets. +** "new_size" must be a power of 2. The hash table might fail +** to resize if sqliteMalloc() fails. +*/ +static void rehash(fts1Hash *pH, int new_size){ + struct _fts1ht *new_ht; /* The new hash table */ + fts1HashElem *elem, *next_elem; /* For looping over existing elements */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( (new_size & (new_size-1))==0 ); + new_ht = (struct _fts1ht *)pH->xMalloc( new_size*sizeof(struct _fts1ht) ); + if( new_ht==0 ) return; + if( pH->ht ) pH->xFree(pH->ht); + pH->ht = new_ht; + pH->htsize = new_size; + xHash = hashFunction(pH->keyClass); + for(elem=pH->first, pH->first=0; elem; elem = next_elem){ + int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1); + next_elem = elem->next; + insertElement(pH, &new_ht[h], elem); + } +} + +/* This function (for internal use only) locates an element in an +** hash table that matches the given key. The hash for this key has +** already been computed and is passed as the 4th parameter. +*/ +static fts1HashElem *findElementGivenHash( + const fts1Hash *pH, /* The pH to be searched */ + const void *pKey, /* The key we are searching for */ + int nKey, + int h /* The hash for this key. */ +){ + fts1HashElem *elem; /* Used to loop thru the element list */ + int count; /* Number of elements left to test */ + int (*xCompare)(const void*,int,const void*,int); /* comparison function */ + + if( pH->ht ){ + struct _fts1ht *pEntry = &pH->ht[h]; + elem = pEntry->chain; + count = pEntry->count; + xCompare = compareFunction(pH->keyClass); + while( count-- && elem ){ + if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ + return elem; + } + elem = elem->next; + } + } + return 0; +} + +/* Remove a single entry from the hash table given a pointer to that +** element and a hash on the element's key. +*/ +static void removeElementGivenHash( + fts1Hash *pH, /* The pH containing "elem" */ + fts1HashElem* elem, /* The element to be removed from the pH */ + int h /* Hash value for the element */ +){ + struct _fts1ht *pEntry; + if( elem->prev ){ + elem->prev->next = elem->next; + }else{ + pH->first = elem->next; + } + if( elem->next ){ + elem->next->prev = elem->prev; + } + pEntry = &pH->ht[h]; + if( pEntry->chain==elem ){ + pEntry->chain = elem->next; + } + pEntry->count--; + if( pEntry->count<=0 ){ + pEntry->chain = 0; + } + if( pH->copyKey && elem->pKey ){ + pH->xFree(elem->pKey); + } + pH->xFree( elem ); + pH->count--; + if( pH->count<=0 ){ + assert( pH->first==0 ); + assert( pH->count==0 ); + fts1HashClear(pH); + } +} + +/* Attempt to locate an element of the hash table pH with a key +** that matches pKey,nKey. Return the data for this element if it is +** found, or NULL if there is no match. +*/ +void *sqlite3Fts1HashFind(const fts1Hash *pH, const void *pKey, int nKey){ + int h; /* A hash on key */ + fts1HashElem *elem; /* The element that matches key */ + int (*xHash)(const void*,int); /* The hash function */ + + if( pH==0 || pH->ht==0 ) return 0; + xHash = hashFunction(pH->keyClass); + assert( xHash!=0 ); + h = (*xHash)(pKey,nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1)); + return elem ? elem->data : 0; +} + +/* Insert an element into the hash table pH. The key is pKey,nKey +** and the data is "data". +** +** If no element exists with a matching key, then a new +** element is created. A copy of the key is made if the copyKey +** flag is set. NULL is returned. +** +** If another element already exists with the same key, then the +** new data replaces the old data and the old data is returned. +** The key is not copied in this instance. If a malloc fails, then +** the new data is returned and the hash table is unchanged. +** +** If the "data" parameter to this function is NULL, then the +** element corresponding to "key" is removed from the hash table. +*/ +void *sqlite3Fts1HashInsert( + fts1Hash *pH, /* The hash table to insert into */ + const void *pKey, /* The key */ + int nKey, /* Number of bytes in the key */ + void *data /* The data */ +){ + int hraw; /* Raw hash value of the key */ + int h; /* the hash of the key modulo hash table size */ + fts1HashElem *elem; /* Used to loop thru the element list */ + fts1HashElem *new_elem; /* New element added to the pH */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( pH!=0 ); + xHash = hashFunction(pH->keyClass); + assert( xHash!=0 ); + hraw = (*xHash)(pKey, nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + elem = findElementGivenHash(pH,pKey,nKey,h); + if( elem ){ + void *old_data = elem->data; + if( data==0 ){ + removeElementGivenHash(pH,elem,h); + }else{ + elem->data = data; + } + return old_data; + } + if( data==0 ) return 0; + new_elem = (fts1HashElem*)pH->xMalloc( sizeof(fts1HashElem) ); + if( new_elem==0 ) return data; + if( pH->copyKey && pKey!=0 ){ + new_elem->pKey = pH->xMalloc( nKey ); + if( new_elem->pKey==0 ){ + pH->xFree(new_elem); + return data; + } + memcpy((void*)new_elem->pKey, pKey, nKey); + }else{ + new_elem->pKey = (void*)pKey; + } + new_elem->nKey = nKey; + pH->count++; + if( pH->htsize==0 ){ + rehash(pH,8); + if( pH->htsize==0 ){ + pH->count = 0; + pH->xFree(new_elem); + return data; + } + } + if( pH->count > pH->htsize ){ + rehash(pH,pH->htsize*2); + } + assert( pH->htsize>0 ); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + insertElement(pH, &pH->ht[h], new_elem); + new_elem->data = data; + return 0; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) */ diff --git a/components/external/SQLite-3.8.1/ext/fts1/fts1_hash.h b/components/external/SQLite-3.8.1/ext/fts1/fts1_hash.h new file mode 100644 index 0000000000000000000000000000000000000000..9001152931c8c45eea0bb64c87c37f3850c0a3be --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/fts1_hash.h @@ -0,0 +1,112 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implementation +** used in SQLite. We've modified it slightly to serve as a standalone +** hash table implementation for the full-text indexing module. +** +*/ +#ifndef _FTS1_HASH_H_ +#define _FTS1_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct fts1Hash fts1Hash; +typedef struct fts1HashElem fts1HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, many of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +*/ +struct fts1Hash { + char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ + char copyKey; /* True if copy of key made on insert */ + int count; /* Number of entries in this table */ + fts1HashElem *first; /* The first element of the array */ + void *(*xMalloc)(int); /* malloc() function to use */ + void (*xFree)(void *); /* free() function to use */ + int htsize; /* Number of buckets in the hash table */ + struct _fts1ht { /* the hash table */ + int count; /* Number of entries with this hash */ + fts1HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct fts1HashElem { + fts1HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + void *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** There are 2 different modes of operation for a hash table: +** +** FTS1_HASH_STRING pKey points to a string that is nKey bytes long +** (including the null-terminator, if any). Case +** is respected in comparisons. +** +** FTS1_HASH_BINARY pKey points to binary data nKey bytes long. +** memcmp() is used to compare keys. +** +** A copy of the key is made if the copyKey parameter to fts1HashInit is 1. +*/ +#define FTS1_HASH_STRING 1 +#define FTS1_HASH_BINARY 2 + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +void sqlite3Fts1HashInit(fts1Hash*, int keytype, int copyKey); +void *sqlite3Fts1HashInsert(fts1Hash*, const void *pKey, int nKey, void *pData); +void *sqlite3Fts1HashFind(const fts1Hash*, const void *pKey, int nKey); +void sqlite3Fts1HashClear(fts1Hash*); + +/* +** Shorthand for the functions above +*/ +#define fts1HashInit sqlite3Fts1HashInit +#define fts1HashInsert sqlite3Fts1HashInsert +#define fts1HashFind sqlite3Fts1HashFind +#define fts1HashClear sqlite3Fts1HashClear + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** fts1Hash h; +** fts1HashElem *p; +** ... +** for(p=fts1HashFirst(&h); p; p=fts1HashNext(p)){ +** SomeStructure *pData = fts1HashData(p); +** // do something with pData +** } +*/ +#define fts1HashFirst(H) ((H)->first) +#define fts1HashNext(E) ((E)->next) +#define fts1HashData(E) ((E)->data) +#define fts1HashKey(E) ((E)->pKey) +#define fts1HashKeysize(E) ((E)->nKey) + +/* +** Number of entries in a hash table +*/ +#define fts1HashCount(H) ((H)->count) + +#endif /* _FTS1_HASH_H_ */ diff --git a/components/external/SQLite-3.8.1/ext/fts1/fts1_porter.c b/components/external/SQLite-3.8.1/ext/fts1/fts1_porter.c new file mode 100644 index 0000000000000000000000000000000000000000..1d26236681a05feab0b72eaece40902003d0bbcb --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/fts1_porter.c @@ -0,0 +1,643 @@ +/* +** 2006 September 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Implementation of the full-text-search tokenizer that implements +** a Porter stemmer. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS1 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS1 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS1 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) + + +#include +#include +#include +#include +#include + +#include "fts1_tokenizer.h" + +/* +** Class derived from sqlite3_tokenizer +*/ +typedef struct porter_tokenizer { + sqlite3_tokenizer base; /* Base class */ +} porter_tokenizer; + +/* +** Class derived from sqlit3_tokenizer_cursor +*/ +typedef struct porter_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *zInput; /* input we are tokenizing */ + int nInput; /* size of the input */ + int iOffset; /* current position in zInput */ + int iToken; /* index of next token to be returned */ + char *zToken; /* storage for current token */ + int nAllocated; /* space allocated to zToken buffer */ +} porter_tokenizer_cursor; + + +/* Forward declaration */ +static const sqlite3_tokenizer_module porterTokenizerModule; + + +/* +** Create a new tokenizer instance. +*/ +static int porterCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer +){ + porter_tokenizer *t; + t = (porter_tokenizer *) calloc(sizeof(*t), 1); + if( t==NULL ) return SQLITE_NOMEM; + + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int porterDestroy(sqlite3_tokenizer *pTokenizer){ + free(pTokenizer); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is zInput[0..nInput-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int porterOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *zInput, int nInput, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + porter_tokenizer_cursor *c; + + c = (porter_tokenizer_cursor *) malloc(sizeof(*c)); + if( c==NULL ) return SQLITE_NOMEM; + + c->zInput = zInput; + if( zInput==0 ){ + c->nInput = 0; + }else if( nInput<0 ){ + c->nInput = (int)strlen(zInput); + }else{ + c->nInput = nInput; + } + c->iOffset = 0; /* start tokenizing at the beginning */ + c->iToken = 0; + c->zToken = NULL; /* no space allocated, yet. */ + c->nAllocated = 0; + + *ppCursor = &c->base; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** porterOpen() above. +*/ +static int porterClose(sqlite3_tokenizer_cursor *pCursor){ + porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; + free(c->zToken); + free(c); + return SQLITE_OK; +} +/* +** Vowel or consonant +*/ +static const char cType[] = { + 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 2, 1 +}; + +/* +** isConsonant() and isVowel() determine if their first character in +** the string they point to is a consonant or a vowel, according +** to Porter ruls. +** +** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'. +** 'Y' is a consonant unless it follows another consonant, +** in which case it is a vowel. +** +** In these routine, the letters are in reverse order. So the 'y' rule +** is that 'y' is a consonant unless it is followed by another +** consonent. +*/ +static int isVowel(const char*); +static int isConsonant(const char *z){ + int j; + char x = *z; + if( x==0 ) return 0; + assert( x>='a' && x<='z' ); + j = cType[x-'a']; + if( j<2 ) return j; + return z[1]==0 || isVowel(z + 1); +} +static int isVowel(const char *z){ + int j; + char x = *z; + if( x==0 ) return 0; + assert( x>='a' && x<='z' ); + j = cType[x-'a']; + if( j<2 ) return 1-j; + return isConsonant(z + 1); +} + +/* +** Let any sequence of one or more vowels be represented by V and let +** C be sequence of one or more consonants. Then every word can be +** represented as: +** +** [C] (VC){m} [V] +** +** In prose: A word is an optional consonant followed by zero or +** vowel-consonant pairs followed by an optional vowel. "m" is the +** number of vowel consonant pairs. This routine computes the value +** of m for the first i bytes of a word. +** +** Return true if the m-value for z is 1 or more. In other words, +** return true if z contains at least one vowel that is followed +** by a consonant. +** +** In this routine z[] is in reverse order. So we are really looking +** for an instance of of a consonant followed by a vowel. +*/ +static int m_gt_0(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* Like mgt0 above except we are looking for a value of m which is +** exactly 1 +*/ +static int m_eq_1(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + if( *z==0 ) return 0; + while( isVowel(z) ){ z++; } + if( *z==0 ) return 1; + while( isConsonant(z) ){ z++; } + return *z==0; +} + +/* Like mgt0 above except we are looking for a value of m>1 instead +** or m>0 +*/ +static int m_gt_1(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + if( *z==0 ) return 0; + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* +** Return TRUE if there is a vowel anywhere within z[0..n-1] +*/ +static int hasVowel(const char *z){ + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* +** Return TRUE if the word ends in a double consonant. +** +** The text is reversed here. So we are really looking at +** the first two characters of z[]. +*/ +static int doubleConsonant(const char *z){ + return isConsonant(z) && z[0]==z[1] && isConsonant(z+1); +} + +/* +** Return TRUE if the word ends with three letters which +** are consonant-vowel-consonent and where the final consonant +** is not 'w', 'x', or 'y'. +** +** The word is reversed here. So we are really checking the +** first three letters and the first one cannot be in [wxy]. +*/ +static int star_oh(const char *z){ + return + z[0]!=0 && isConsonant(z) && + z[0]!='w' && z[0]!='x' && z[0]!='y' && + z[1]!=0 && isVowel(z+1) && + z[2]!=0 && isConsonant(z+2); +} + +/* +** If the word ends with zFrom and xCond() is true for the stem +** of the word that preceeds the zFrom ending, then change the +** ending to zTo. +** +** The input word *pz and zFrom are both in reverse order. zTo +** is in normal order. +** +** Return TRUE if zFrom matches. Return FALSE if zFrom does not +** match. Not that TRUE is returned even if xCond() fails and +** no substitution occurs. +*/ +static int stem( + char **pz, /* The word being stemmed (Reversed) */ + const char *zFrom, /* If the ending matches this... (Reversed) */ + const char *zTo, /* ... change the ending to this (not reversed) */ + int (*xCond)(const char*) /* Condition that must be true */ +){ + char *z = *pz; + while( *zFrom && *zFrom==*z ){ z++; zFrom++; } + if( *zFrom!=0 ) return 0; + if( xCond && !xCond(z) ) return 1; + while( *zTo ){ + *(--z) = *(zTo++); + } + *pz = z; + return 1; +} + +/* +** This is the fallback stemmer used when the porter stemmer is +** inappropriate. The input word is copied into the output with +** US-ASCII case folding. If the input word is too long (more +** than 20 bytes if it contains no digits or more than 6 bytes if +** it contains digits) then word is truncated to 20 or 6 bytes +** by taking 10 or 3 bytes from the beginning and end. +*/ +static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){ + int i, mx, j; + int hasDigit = 0; + for(i=0; i='A' && c<='Z' ){ + zOut[i] = c - 'A' + 'a'; + }else{ + if( c>='0' && c<='9' ) hasDigit = 1; + zOut[i] = c; + } + } + mx = hasDigit ? 3 : 10; + if( nIn>mx*2 ){ + for(j=mx, i=nIn-mx; i=sizeof(zReverse)-7 ){ + /* The word is too big or too small for the porter stemmer. + ** Fallback to the copy stemmer */ + copy_stemmer(zIn, nIn, zOut, pnOut); + return; + } + for(i=0, j=sizeof(zReverse)-6; i='A' && c<='Z' ){ + zReverse[j] = c + 'a' - 'A'; + }else if( c>='a' && c<='z' ){ + zReverse[j] = c; + }else{ + /* The use of a character not in [a-zA-Z] means that we fallback + ** to the copy stemmer */ + copy_stemmer(zIn, nIn, zOut, pnOut); + return; + } + } + memset(&zReverse[sizeof(zReverse)-5], 0, 5); + z = &zReverse[j+1]; + + + /* Step 1a */ + if( z[0]=='s' ){ + if( + !stem(&z, "sess", "ss", 0) && + !stem(&z, "sei", "i", 0) && + !stem(&z, "ss", "ss", 0) + ){ + z++; + } + } + + /* Step 1b */ + z2 = z; + if( stem(&z, "dee", "ee", m_gt_0) ){ + /* Do nothing. The work was all in the test */ + }else if( + (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel)) + && z!=z2 + ){ + if( stem(&z, "ta", "ate", 0) || + stem(&z, "lb", "ble", 0) || + stem(&z, "zi", "ize", 0) ){ + /* Do nothing. The work was all in the test */ + }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){ + z++; + }else if( m_eq_1(z) && star_oh(z) ){ + *(--z) = 'e'; + } + } + + /* Step 1c */ + if( z[0]=='y' && hasVowel(z+1) ){ + z[0] = 'i'; + } + + /* Step 2 */ + switch( z[1] ){ + case 'a': + stem(&z, "lanoita", "ate", m_gt_0) || + stem(&z, "lanoit", "tion", m_gt_0); + break; + case 'c': + stem(&z, "icne", "ence", m_gt_0) || + stem(&z, "icna", "ance", m_gt_0); + break; + case 'e': + stem(&z, "rezi", "ize", m_gt_0); + break; + case 'g': + stem(&z, "igol", "log", m_gt_0); + break; + case 'l': + stem(&z, "ilb", "ble", m_gt_0) || + stem(&z, "illa", "al", m_gt_0) || + stem(&z, "iltne", "ent", m_gt_0) || + stem(&z, "ile", "e", m_gt_0) || + stem(&z, "ilsuo", "ous", m_gt_0); + break; + case 'o': + stem(&z, "noitazi", "ize", m_gt_0) || + stem(&z, "noita", "ate", m_gt_0) || + stem(&z, "rota", "ate", m_gt_0); + break; + case 's': + stem(&z, "msila", "al", m_gt_0) || + stem(&z, "ssenevi", "ive", m_gt_0) || + stem(&z, "ssenluf", "ful", m_gt_0) || + stem(&z, "ssensuo", "ous", m_gt_0); + break; + case 't': + stem(&z, "itila", "al", m_gt_0) || + stem(&z, "itivi", "ive", m_gt_0) || + stem(&z, "itilib", "ble", m_gt_0); + break; + } + + /* Step 3 */ + switch( z[0] ){ + case 'e': + stem(&z, "etaci", "ic", m_gt_0) || + stem(&z, "evita", "", m_gt_0) || + stem(&z, "ezila", "al", m_gt_0); + break; + case 'i': + stem(&z, "itici", "ic", m_gt_0); + break; + case 'l': + stem(&z, "laci", "ic", m_gt_0) || + stem(&z, "luf", "", m_gt_0); + break; + case 's': + stem(&z, "ssen", "", m_gt_0); + break; + } + + /* Step 4 */ + switch( z[1] ){ + case 'a': + if( z[0]=='l' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'c': + if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){ + z += 4; + } + break; + case 'e': + if( z[0]=='r' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'i': + if( z[0]=='c' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'l': + if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){ + z += 4; + } + break; + case 'n': + if( z[0]=='t' ){ + if( z[2]=='a' ){ + if( m_gt_1(z+3) ){ + z += 3; + } + }else if( z[2]=='e' ){ + stem(&z, "tneme", "", m_gt_1) || + stem(&z, "tnem", "", m_gt_1) || + stem(&z, "tne", "", m_gt_1); + } + } + break; + case 'o': + if( z[0]=='u' ){ + if( m_gt_1(z+2) ){ + z += 2; + } + }else if( z[3]=='s' || z[3]=='t' ){ + stem(&z, "noi", "", m_gt_1); + } + break; + case 's': + if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){ + z += 3; + } + break; + case 't': + stem(&z, "eta", "", m_gt_1) || + stem(&z, "iti", "", m_gt_1); + break; + case 'u': + if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){ + z += 3; + } + break; + case 'v': + case 'z': + if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){ + z += 3; + } + break; + } + + /* Step 5a */ + if( z[0]=='e' ){ + if( m_gt_1(z+1) ){ + z++; + }else if( m_eq_1(z+1) && !star_oh(z+1) ){ + z++; + } + } + + /* Step 5b */ + if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){ + z++; + } + + /* z[] is now the stemmed word in reverse order. Flip it back + ** around into forward order and return. + */ + *pnOut = i = strlen(z); + zOut[i] = 0; + while( *z ){ + zOut[--i] = *(z++); + } +} + +/* +** Characters that can be part of a token. We assume any character +** whose value is greater than 0x80 (any UTF character) can be +** part of a token. In other words, delimiters all must have +** values of 0x7f or lower. +*/ +static const char isIdChar[] = { +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ +}; +#define idChar(C) (((ch=C)&0x80)!=0 || (ch>0x2f && isIdChar[ch-0x30])) +#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !isIdChar[ch-0x30])) + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to porterOpen(). +*/ +static int porterNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */ + const char **pzToken, /* OUT: *pzToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; + const char *z = c->zInput; + + while( c->iOffsetnInput ){ + int iStartOffset, ch; + + /* Scan past delimiter characters */ + while( c->iOffsetnInput && isDelim(z[c->iOffset]) ){ + c->iOffset++; + } + + /* Count non-delimiter characters. */ + iStartOffset = c->iOffset; + while( c->iOffsetnInput && !isDelim(z[c->iOffset]) ){ + c->iOffset++; + } + + if( c->iOffset>iStartOffset ){ + int n = c->iOffset-iStartOffset; + if( n>c->nAllocated ){ + c->nAllocated = n+20; + c->zToken = realloc(c->zToken, c->nAllocated); + if( c->zToken==NULL ) return SQLITE_NOMEM; + } + porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes); + *pzToken = c->zToken; + *piStartOffset = iStartOffset; + *piEndOffset = c->iOffset; + *piPosition = c->iToken++; + return SQLITE_OK; + } + } + return SQLITE_DONE; +} + +/* +** The set of routines that implement the porter-stemmer tokenizer +*/ +static const sqlite3_tokenizer_module porterTokenizerModule = { + 0, + porterCreate, + porterDestroy, + porterOpen, + porterClose, + porterNext, +}; + +/* +** Allocate a new porter tokenizer. Return a pointer to the new +** tokenizer in *ppModule +*/ +void sqlite3Fts1PorterTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &porterTokenizerModule; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) */ diff --git a/components/external/SQLite-3.8.1/ext/fts1/fts1_tokenizer.h b/components/external/SQLite-3.8.1/ext/fts1/fts1_tokenizer.h new file mode 100644 index 0000000000000000000000000000000000000000..a48cb745193296d65e639191776251421a859415 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/fts1_tokenizer.h @@ -0,0 +1,90 @@ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _FTS1_TOKENIZER_H_ +#define _FTS1_TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ +#include "sqlite3.h" + +/* +** Structures used by the tokenizer interface. +*/ +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; + +struct sqlite3_tokenizer_module { + int iVersion; /* currently 0 */ + + /* + ** Create and destroy a tokenizer. argc/argv are passed down from + ** the fulltext virtual table creation to allow customization. + */ + int (*xCreate)(int argc, const char *const*argv, + sqlite3_tokenizer **ppTokenizer); + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Tokenize a particular input. Call xOpen() to prepare to + ** tokenize, xNext() repeatedly until it returns SQLITE_DONE, then + ** xClose() to free any internal state. The pInput passed to + ** xOpen() must exist until the cursor is closed. The ppToken + ** result from xNext() is only valid until the next call to xNext() + ** or until xClose() is called. + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xOpen)(sqlite3_tokenizer *pTokenizer, + const char *pInput, int nBytes, + sqlite3_tokenizer_cursor **ppCursor); + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + int (*xNext)(sqlite3_tokenizer_cursor *pCursor, + const char **ppToken, int *pnBytes, + int *piStartOffset, int *piEndOffset, int *piPosition); +}; + +struct sqlite3_tokenizer { + const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +/* +** Get the module for a tokenizer which generates tokens based on a +** set of non-token characters. The default is to break tokens at any +** non-alnum character, though the set of delimiters can also be +** specified by the first argv argument to xCreate(). +*/ +/* TODO(shess) This doesn't belong here. Need some sort of +** registration process. +*/ +void sqlite3Fts1SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); +void sqlite3Fts1PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); + +#endif /* _FTS1_TOKENIZER_H_ */ diff --git a/components/external/SQLite-3.8.1/ext/fts1/fts1_tokenizer1.c b/components/external/SQLite-3.8.1/ext/fts1/fts1_tokenizer1.c new file mode 100644 index 0000000000000000000000000000000000000000..f58fba8f8e613ffed6764ffd0868d9646cb96011 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/fts1_tokenizer1.c @@ -0,0 +1,221 @@ +/* +** The author disclaims copyright to this source code. +** +************************************************************************* +** Implementation of the "simple" full-text-search tokenizer. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS1 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS1 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS1 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) + + +#include +#include +#include +#include +#include + +#include "fts1_tokenizer.h" + +typedef struct simple_tokenizer { + sqlite3_tokenizer base; + char delim[128]; /* flag ASCII delimiters */ +} simple_tokenizer; + +typedef struct simple_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *pInput; /* input we are tokenizing */ + int nBytes; /* size of the input */ + int iOffset; /* current position in pInput */ + int iToken; /* index of next token to be returned */ + char *pToken; /* storage for current token */ + int nTokenAllocated; /* space allocated to zToken buffer */ +} simple_tokenizer_cursor; + + +/* Forward declaration */ +static const sqlite3_tokenizer_module simpleTokenizerModule; + +static int isDelim(simple_tokenizer *t, unsigned char c){ + return c<0x80 && t->delim[c]; +} + +/* +** Create a new tokenizer instance. +*/ +static int simpleCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer +){ + simple_tokenizer *t; + + t = (simple_tokenizer *) calloc(sizeof(*t), 1); + if( t==NULL ) return SQLITE_NOMEM; + + /* TODO(shess) Delimiters need to remain the same from run to run, + ** else we need to reindex. One solution would be a meta-table to + ** track such information in the database, then we'd only want this + ** information on the initial create. + */ + if( argc>1 ){ + int i, n = strlen(argv[1]); + for(i=0; i=0x80 ){ + free(t); + return SQLITE_ERROR; + } + t->delim[ch] = 1; + } + } else { + /* Mark non-alphanumeric ASCII characters as delimiters */ + int i; + for(i=1; i<0x80; i++){ + t->delim[i] = !isalnum(i); + } + } + + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ + free(pTokenizer); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is pInput[0..nBytes-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int simpleOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *pInput, int nBytes, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + simple_tokenizer_cursor *c; + + c = (simple_tokenizer_cursor *) malloc(sizeof(*c)); + if( c==NULL ) return SQLITE_NOMEM; + + c->pInput = pInput; + if( pInput==0 ){ + c->nBytes = 0; + }else if( nBytes<0 ){ + c->nBytes = (int)strlen(pInput); + }else{ + c->nBytes = nBytes; + } + c->iOffset = 0; /* start tokenizing at the beginning */ + c->iToken = 0; + c->pToken = NULL; /* no space allocated, yet. */ + c->nTokenAllocated = 0; + + *ppCursor = &c->base; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** simpleOpen() above. +*/ +static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + free(c->pToken); + free(c); + return SQLITE_OK; +} + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to simpleOpen(). +*/ +static int simpleNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer; + unsigned char *p = (unsigned char *)c->pInput; + + while( c->iOffsetnBytes ){ + int iStartOffset; + + /* Scan past delimiter characters */ + while( c->iOffsetnBytes && isDelim(t, p[c->iOffset]) ){ + c->iOffset++; + } + + /* Count non-delimiter characters. */ + iStartOffset = c->iOffset; + while( c->iOffsetnBytes && !isDelim(t, p[c->iOffset]) ){ + c->iOffset++; + } + + if( c->iOffset>iStartOffset ){ + int i, n = c->iOffset-iStartOffset; + if( n>c->nTokenAllocated ){ + c->nTokenAllocated = n+20; + c->pToken = realloc(c->pToken, c->nTokenAllocated); + if( c->pToken==NULL ) return SQLITE_NOMEM; + } + for(i=0; ipToken[i] = ch<0x80 ? tolower(ch) : ch; + } + *ppToken = c->pToken; + *pnBytes = n; + *piStartOffset = iStartOffset; + *piEndOffset = c->iOffset; + *piPosition = c->iToken++; + + return SQLITE_OK; + } + } + return SQLITE_DONE; +} + +/* +** The set of routines that implement the simple tokenizer +*/ +static const sqlite3_tokenizer_module simpleTokenizerModule = { + 0, + simpleCreate, + simpleDestroy, + simpleOpen, + simpleClose, + simpleNext, +}; + +/* +** Allocate a new simple tokenizer. Return a pointer to the new +** tokenizer in *ppModule +*/ +void sqlite3Fts1SimpleTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &simpleTokenizerModule; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) */ diff --git a/components/external/SQLite-3.8.1/ext/fts1/fulltext.c b/components/external/SQLite-3.8.1/ext/fts1/fulltext.c new file mode 100644 index 0000000000000000000000000000000000000000..313ff303e1af2dbd71234c97ec73fd94218fd931 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/fulltext.c @@ -0,0 +1,1511 @@ +/* The author disclaims copyright to this source code. + * + * This is an SQLite module implementing full-text search. + */ + +#include +#if !defined(__APPLE__) +#include +#else +#include +#endif +#include +#include +#include + +#include "fulltext.h" +#include "ft_hash.h" +#include "tokenizer.h" +#include "sqlite3.h" +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 + +/* utility functions */ + +/* We encode variable-length integers in little-endian order using seven bits + * per byte as follows: +** +** KEY: +** A = 0xxxxxxx 7 bits of data and one flag bit +** B = 1xxxxxxx 7 bits of data and one flag bit +** +** 7 bits - A +** 14 bits - BA +** 21 bits - BBA +** and so on. +*/ + +/* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */ +#define VARINT_MAX 10 + +/* Write a 64-bit variable-length integer to memory starting at p[0]. + * The length of data written will be between 1 and VARINT_MAX bytes. + * The number of bytes written is returned. */ +static int putVarint(char *p, sqlite_int64 v){ + unsigned char *q = (unsigned char *) p; + sqlite_uint64 vu = v; + do{ + *q++ = (unsigned char) ((vu & 0x7f) | 0x80); + vu >>= 7; + }while( vu!=0 ); + q[-1] &= 0x7f; /* turn off high bit in final byte */ + assert( q - (unsigned char *)p <= VARINT_MAX ); + return (int) (q - (unsigned char *)p); +} + +/* Read a 64-bit variable-length integer from memory starting at p[0]. + * Return the number of bytes read, or 0 on error. + * The value is stored in *v. */ +static int getVarint(const char *p, sqlite_int64 *v){ + const unsigned char *q = (const unsigned char *) p; + sqlite_uint64 x = 0, y = 1; + while( (*q & 0x80) == 0x80 ){ + x += y * (*q++ & 0x7f); + y <<= 7; + if( q - (unsigned char *)p >= VARINT_MAX ){ /* bad data */ + assert( 0 ); + return 0; + } + } + x += y * (*q++); + *v = (sqlite_int64) x; + return (int) (q - (unsigned char *)p); +} + +static int getVarint32(const char *p, int *pi){ + sqlite_int64 i; + int ret = getVarint(p, &i); + *pi = (int) i; + assert( *pi==i ); + return ret; +} + +/*** Document lists *** + * + * A document list holds a sorted list of varint-encoded document IDs. + * + * A doclist with type DL_POSITIONS_OFFSETS is stored like this: + * + * array { + * varint docid; + * array { + * varint position; (delta from previous position plus 1, or 0 for end) + * varint startOffset; (delta from previous startOffset) + * varint endOffset; (delta from startOffset) + * } + * } + * + * Here, array { X } means zero or more occurrences of X, adjacent in memory. + * + * A doclist with type DL_POSITIONS is like the above, but holds only docids + * and positions without offset information. + * + * A doclist with type DL_DOCIDS is like the above, but holds only docids + * without positions or offset information. + * + * On disk, every document list has positions and offsets, so we don't bother + * to serialize a doclist's type. + * + * We don't yet delta-encode document IDs; doing so will probably be a + * modest win. + * + * NOTE(shess) I've thought of a slightly (1%) better offset encoding. + * After the first offset, estimate the next offset by using the + * current token position and the previous token position and offset, + * offset to handle some variance. So the estimate would be + * (iPosition*w->iStartOffset/w->iPosition-64), which is delta-encoded + * as normal. Offsets more than 64 chars from the estimate are + * encoded as the delta to the previous start offset + 128. An + * additional tiny increment can be gained by using the end offset of + * the previous token to make the estimate a tiny bit more precise. +*/ + +typedef enum DocListType { + DL_DOCIDS, /* docids only */ + DL_POSITIONS, /* docids + positions */ + DL_POSITIONS_OFFSETS /* docids + positions + offsets */ +} DocListType; + +typedef struct DocList { + char *pData; + int nData; + DocListType iType; + int iLastPos; /* the last position written */ + int iLastOffset; /* the last start offset written */ +} DocList; + +/* Initialize a new DocList to hold the given data. */ +static void docListInit(DocList *d, DocListType iType, + const char *pData, int nData){ + d->nData = nData; + if( nData>0 ){ + d->pData = malloc(nData); + memcpy(d->pData, pData, nData); + } else { + d->pData = NULL; + } + d->iType = iType; + d->iLastPos = 0; + d->iLastOffset = 0; +} + +/* Create a new dynamically-allocated DocList. */ +static DocList *docListNew(DocListType iType){ + DocList *d = (DocList *) malloc(sizeof(DocList)); + docListInit(d, iType, 0, 0); + return d; +} + +static void docListDestroy(DocList *d){ + free(d->pData); +#ifndef NDEBUG + memset(d, 0x55, sizeof(*d)); +#endif +} + +static void docListDelete(DocList *d){ + docListDestroy(d); + free(d); +} + +static char *docListEnd(DocList *d){ + return d->pData + d->nData; +} + +/* Append a varint to a DocList's data. */ +static void appendVarint(DocList *d, sqlite_int64 i){ + char c[VARINT_MAX]; + int n = putVarint(c, i); + d->pData = realloc(d->pData, d->nData + n); + memcpy(d->pData + d->nData, c, n); + d->nData += n; +} + +static void docListAddDocid(DocList *d, sqlite_int64 iDocid){ + appendVarint(d, iDocid); + d->iLastPos = 0; +} + +/* Add a position to the last position list in a doclist. */ +static void docListAddPos(DocList *d, int iPos){ + assert( d->iType>=DL_POSITIONS ); + appendVarint(d, iPos-d->iLastPos+1); + d->iLastPos = iPos; +} + +static void docListAddPosOffset(DocList *d, int iPos, + int iStartOffset, int iEndOffset){ + assert( d->iType==DL_POSITIONS_OFFSETS ); + docListAddPos(d, iPos); + appendVarint(d, iStartOffset-d->iLastOffset); + d->iLastOffset = iStartOffset; + appendVarint(d, iEndOffset-iStartOffset); +} + +/* Terminate the last position list in the given doclist. */ +static void docListAddEndPos(DocList *d){ + appendVarint(d, 0); +} + +typedef struct DocListReader { + DocList *pDoclist; + char *p; + int iLastPos; /* the last position read */ +} DocListReader; + +static void readerInit(DocListReader *r, DocList *pDoclist){ + r->pDoclist = pDoclist; + if( pDoclist!=NULL ){ + r->p = pDoclist->pData; + } + r->iLastPos = 0; +} + +static int readerAtEnd(DocListReader *pReader){ + return pReader->p >= docListEnd(pReader->pDoclist); +} + +/* Peek at the next docid without advancing the read pointer. */ +static sqlite_int64 peekDocid(DocListReader *pReader){ + sqlite_int64 ret; + assert( !readerAtEnd(pReader) ); + getVarint(pReader->p, &ret); + return ret; +} + +/* Read the next docid. */ +static sqlite_int64 readDocid(DocListReader *pReader){ + sqlite_int64 ret; + assert( !readerAtEnd(pReader) ); + pReader->p += getVarint(pReader->p, &ret); + pReader->iLastPos = 0; + return ret; +} + +/* Read the next position from a position list. + * Returns the position, or -1 at the end of the list. */ +static int readPosition(DocListReader *pReader){ + int i; + int iType = pReader->pDoclist->iType; + assert( iType>=DL_POSITIONS ); + assert( !readerAtEnd(pReader) ); + + pReader->p += getVarint32(pReader->p, &i); + if( i==0 ){ + pReader->iLastPos = -1; + return -1; + } + pReader->iLastPos += ((int) i)-1; + if( iType>=DL_POSITIONS_OFFSETS ){ + /* Skip over offsets, ignoring them for now. */ + int iStart, iEnd; + pReader->p += getVarint32(pReader->p, &iStart); + pReader->p += getVarint32(pReader->p, &iEnd); + } + return pReader->iLastPos; +} + +/* Skip past the end of a position list. */ +static void skipPositionList(DocListReader *pReader){ + while( readPosition(pReader)!=-1 ) + ; +} + +/* Skip over a docid, including its position list if the doclist has + * positions. */ +static void skipDocument(DocListReader *pReader){ + readDocid(pReader); + if( pReader->pDoclist->iType >= DL_POSITIONS ){ + skipPositionList(pReader); + } +} + +static sqlite_int64 firstDocid(DocList *d){ + DocListReader r; + readerInit(&r, d); + return readDocid(&r); +} + +/* Doclist multi-tool. Pass pUpdate==NULL to delete the indicated docid; + * otherwise pUpdate, which must contain only the single docid [iDocid], is + * inserted (if not present) or updated (if already present). */ +static int docListUpdate(DocList *d, sqlite_int64 iDocid, DocList *pUpdate){ + int modified = 0; + DocListReader reader; + char *p; + + if( pUpdate!=NULL ){ + assert( d->iType==pUpdate->iType); + assert( iDocid==firstDocid(pUpdate) ); + } + + readerInit(&reader, d); + while( !readerAtEnd(&reader) && peekDocid(&reader)nData -= (reader.p - p); + modified = 1; + } + + /* Insert if indicated. */ + if( pUpdate!=NULL ){ + int iDoclist = p-d->pData; + docListAddEndPos(pUpdate); + + d->pData = realloc(d->pData, d->nData+pUpdate->nData); + p = d->pData + iDoclist; + + memmove(p+pUpdate->nData, p, docListEnd(d) - p); + memcpy(p, pUpdate->pData, pUpdate->nData); + d->nData += pUpdate->nData; + modified = 1; + } + + return modified; +} + +/* Split the second half of doclist d into a separate doclist d2. Returns 1 + * if successful, or 0 if d contains a single document and hence can't be + * split. */ +static int docListSplit(DocList *d, DocList *d2){ + const char *pSplitPoint = d->pData + d->nData / 2; + DocListReader reader; + + readerInit(&reader, d); + while( reader.piType, reader.p, docListEnd(d) - reader.p); + d->nData = reader.p - d->pData; + d->pData = realloc(d->pData, d->nData); + return 1; +} + +/* A DocListMerge computes the AND of an in-memory DocList [in] and a chunked + * on-disk doclist, resulting in another in-memory DocList [out]. [in] + * and [out] may or may not store position information according to the + * caller's wishes. The on-disk doclist always comes with positions. + * + * The caller must read each chunk of the on-disk doclist in succession and + * pass it to mergeBlock(). + * + * If [in] has positions, then the merge output contains only documents with + * matching positions in the two input doclists. If [in] does not have + * positions, then the merge output contains all documents common to the two + * input doclists. + * + * If [in] is NULL, then the on-disk doclist is copied to [out] directly. + * + * A merge is performed using an integer [iOffset] provided by the caller. + * [iOffset] is subtracted from each position in the on-disk doclist for the + * purpose of position comparison; this is helpful in implementing phrase + * searches. + * + * A DocListMerge is not yet able to propagate offsets through query + * processing; we should add that capability soon. +*/ +typedef struct DocListMerge { + DocListReader in; + DocList *pOut; + int iOffset; +} DocListMerge; + +static void mergeInit(DocListMerge *m, + DocList *pIn, int iOffset, DocList *pOut){ + readerInit(&m->in, pIn); + m->pOut = pOut; + m->iOffset = iOffset; + + /* can't handle offsets yet */ + assert( pIn==NULL || pIn->iType <= DL_POSITIONS ); + assert( pOut->iType <= DL_POSITIONS ); +} + +/* A helper function for mergeBlock(), below. Merge the position lists + * pointed to by m->in and pBlockReader. + * If the merge matches, write [iDocid] to m->pOut; if m->pOut + * has positions then write all matching positions as well. */ +static void mergePosList(DocListMerge *m, sqlite_int64 iDocid, + DocListReader *pBlockReader){ + int block_pos = readPosition(pBlockReader); + int in_pos = readPosition(&m->in); + int match = 0; + while( block_pos!=-1 || in_pos!=-1 ){ + if( block_pos-m->iOffset==in_pos ){ + if( !match ){ + docListAddDocid(m->pOut, iDocid); + match = 1; + } + if( m->pOut->iType >= DL_POSITIONS ){ + docListAddPos(m->pOut, in_pos); + } + block_pos = readPosition(pBlockReader); + in_pos = readPosition(&m->in); + } else if( in_pos==-1 || (block_pos!=-1 && block_pos-m->iOffsetin); + } + } + if( m->pOut->iType >= DL_POSITIONS && match ){ + docListAddEndPos(m->pOut); + } +} + +/* Merge one block of an on-disk doclist into a DocListMerge. */ +static void mergeBlock(DocListMerge *m, DocList *pBlock){ + DocListReader blockReader; + assert( pBlock->iType >= DL_POSITIONS ); + readerInit(&blockReader, pBlock); + while( !readerAtEnd(&blockReader) ){ + sqlite_int64 iDocid = readDocid(&blockReader); + if( m->in.pDoclist!=NULL ){ + while( 1 ){ + if( readerAtEnd(&m->in) ) return; /* nothing more to merge */ + if( peekDocid(&m->in)>=iDocid ) break; + skipDocument(&m->in); + } + if( peekDocid(&m->in)>iDocid ){ /* [pIn] has no match with iDocid */ + skipPositionList(&blockReader); /* skip this docid in the block */ + continue; + } + readDocid(&m->in); + } + /* We have a document match. */ + if( m->in.pDoclist==NULL || m->in.pDoclist->iType < DL_POSITIONS ){ + /* We don't need to do a poslist merge. */ + docListAddDocid(m->pOut, iDocid); + if( m->pOut->iType >= DL_POSITIONS ){ + /* Copy all positions to the output doclist. */ + while( 1 ){ + int pos = readPosition(&blockReader); + if( pos==-1 ) break; + docListAddPos(m->pOut, pos); + } + docListAddEndPos(m->pOut); + } else skipPositionList(&blockReader); + continue; + } + mergePosList(m, iDocid, &blockReader); + } +} + +static char *string_dup_n(const char *s, int n){ + char *str = malloc(n + 1); + memcpy(str, s, n); + str[n] = '\0'; + return str; +} + +/* Duplicate a string; the caller must free() the returned string. + * (We don't use strdup() since it's not part of the standard C library and + * may not be available everywhere.) */ +static char *string_dup(const char *s){ + return string_dup_n(s, strlen(s)); +} + +/* Format a string, replacing each occurrence of the % character with + * zName. This may be more convenient than sqlite_mprintf() + * when one string is used repeatedly in a format string. + * The caller must free() the returned string. */ +static char *string_format(const char *zFormat, const char *zName){ + const char *p; + size_t len = 0; + size_t nName = strlen(zName); + char *result; + char *r; + + /* first compute length needed */ + for(p = zFormat ; *p ; ++p){ + len += (*p=='%' ? nName : 1); + } + len += 1; /* for null terminator */ + + r = result = malloc(len); + for(p = zFormat; *p; ++p){ + if( *p=='%' ){ + memcpy(r, zName, nName); + r += nName; + } else { + *r++ = *p; + } + } + *r++ = '\0'; + assert( r == result + len ); + return result; +} + +static int sql_exec(sqlite3 *db, const char *zName, const char *zFormat){ + char *zCommand = string_format(zFormat, zName); + int rc = sqlite3_exec(db, zCommand, NULL, 0, NULL); + free(zCommand); + return rc; +} + +static int sql_prepare(sqlite3 *db, const char *zName, sqlite3_stmt **ppStmt, + const char *zFormat){ + char *zCommand = string_format(zFormat, zName); + int rc = sqlite3_prepare(db, zCommand, -1, ppStmt, NULL); + free(zCommand); + return rc; +} + +/* end utility functions */ + +#define QUERY_GENERIC 0 +#define QUERY_FULLTEXT 1 + +#define CHUNK_MAX 1024 + +typedef enum fulltext_statement { + CONTENT_INSERT_STMT, + CONTENT_SELECT_STMT, + CONTENT_DELETE_STMT, + + TERM_SELECT_STMT, + TERM_CHUNK_SELECT_STMT, + TERM_INSERT_STMT, + TERM_UPDATE_STMT, + TERM_DELETE_STMT, + + MAX_STMT /* Always at end! */ +} fulltext_statement; + +/* These must exactly match the enum above. */ +/* TODO(adam): Is there some risk that a statement (in particular, +** pTermSelectStmt) will be used in two cursors at once, e.g. if a +** query joins a virtual table to itself? If so perhaps we should +** move some of these to the cursor object. +*/ +static const char *fulltext_zStatement[MAX_STMT] = { + /* CONTENT_INSERT */ "insert into %_content (rowid, content) values (?, ?)", + /* CONTENT_SELECT */ "select content from %_content where rowid = ?", + /* CONTENT_DELETE */ "delete from %_content where rowid = ?", + + /* TERM_SELECT */ + "select rowid, doclist from %_term where term = ? and first = ?", + /* TERM_CHUNK_SELECT */ + "select max(first) from %_term where term = ? and first <= ?", + /* TERM_INSERT */ + "insert into %_term (term, first, doclist) values (?, ?, ?)", + /* TERM_UPDATE */ "update %_term set doclist = ? where rowid = ?", + /* TERM_DELETE */ "delete from %_term where rowid = ?", +}; + +typedef struct fulltext_vtab { + sqlite3_vtab base; + sqlite3 *db; + const char *zName; /* virtual table name */ + sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ + + /* Precompiled statements which we keep as long as the table is + ** open. + */ + sqlite3_stmt *pFulltextStatements[MAX_STMT]; +} fulltext_vtab; + +typedef struct fulltext_cursor { + sqlite3_vtab_cursor base; + int iCursorType; /* QUERY_GENERIC or QUERY_FULLTEXT */ + + sqlite3_stmt *pStmt; + + int eof; + + /* The following is used only when iCursorType == QUERY_FULLTEXT. */ + DocListReader result; +} fulltext_cursor; + +static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){ + return (fulltext_vtab *) c->base.pVtab; +} + +static sqlite3_module fulltextModule; /* forward declaration */ + +/* Puts a freshly-prepared statement determined by iStmt in *ppStmt. +** If the indicated statement has never been prepared, it is prepared +** and cached, otherwise the cached version is reset. +*/ +static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt, + sqlite3_stmt **ppStmt){ + assert( iStmtpFulltextStatements[iStmt]==NULL ){ + int rc = sql_prepare(v->db, v->zName, &v->pFulltextStatements[iStmt], + fulltext_zStatement[iStmt]); + if( rc!=SQLITE_OK ) return rc; + } else { + int rc = sqlite3_reset(v->pFulltextStatements[iStmt]); + if( rc!=SQLITE_OK ) return rc; + } + + *ppStmt = v->pFulltextStatements[iStmt]; + return SQLITE_OK; +} + +/* Step the indicated statement, handling errors SQLITE_BUSY (by +** retrying) and SQLITE_SCHEMA (by re-preparing and transferring +** bindings to the new statement). +** TODO(adam): We should extend this function so that it can work with +** statements declared locally, not only globally cached statements. +*/ +static int sql_step_statement(fulltext_vtab *v, fulltext_statement iStmt, + sqlite3_stmt **ppStmt){ + int rc; + sqlite3_stmt *s = *ppStmt; + assert( iStmtpFulltextStatements[iStmt] ); + + while( (rc=sqlite3_step(s))!=SQLITE_DONE && rc!=SQLITE_ROW ){ + sqlite3_stmt *pNewStmt; + + if( rc==SQLITE_BUSY ) continue; + if( rc!=SQLITE_ERROR ) return rc; + + rc = sqlite3_reset(s); + if( rc!=SQLITE_SCHEMA ) return SQLITE_ERROR; + + v->pFulltextStatements[iStmt] = NULL; /* Still in s */ + rc = sql_get_statement(v, iStmt, &pNewStmt); + if( rc!=SQLITE_OK ) goto err; + *ppStmt = pNewStmt; + + rc = sqlite3_transfer_bindings(s, pNewStmt); + if( rc!=SQLITE_OK ) goto err; + + rc = sqlite3_finalize(s); + if( rc!=SQLITE_OK ) return rc; + s = pNewStmt; + } + return rc; + + err: + sqlite3_finalize(s); + return rc; +} + +/* Like sql_step_statement(), but convert SQLITE_DONE to SQLITE_OK. +** Useful for statements like UPDATE, where we expect no results. +*/ +static int sql_single_step_statement(fulltext_vtab *v, + fulltext_statement iStmt, + sqlite3_stmt **ppStmt){ + int rc = sql_step_statement(v, iStmt, ppStmt); + return (rc==SQLITE_DONE) ? SQLITE_OK : rc; +} + +/* insert into %_content (rowid, content) values ([rowid], [zContent]) */ +static int content_insert(fulltext_vtab *v, sqlite3_value *rowid, + const char *zContent, int nContent){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_value(s, 1, rowid); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_text(s, 2, zContent, nContent, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, CONTENT_INSERT_STMT, &s); +} + +/* select content from %_content where rowid = [iRow] + * The caller must delete the returned string. */ +static int content_select(fulltext_vtab *v, sqlite_int64 iRow, + char **pzContent){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iRow); + if( rc!=SQLITE_OK ) return rc; + + rc = sql_step_statement(v, CONTENT_SELECT_STMT, &s); + if( rc!=SQLITE_ROW ) return rc; + + *pzContent = string_dup((const char *)sqlite3_column_text(s, 0)); + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + rc = sqlite3_step(s); + if( rc==SQLITE_DONE ) return SQLITE_OK; + + free(*pzContent); + return rc; +} + +/* delete from %_content where rowid = [iRow ] */ +static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iRow); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, CONTENT_DELETE_STMT, &s); +} + +/* select rowid, doclist from %_term where term = [zTerm] and first = [iFirst] + * If found, returns SQLITE_OK; the caller must free the returned doclist. + * If no rows found, returns SQLITE_ERROR. */ +static int term_select(fulltext_vtab *v, const char *zTerm, int nTerm, + sqlite_int64 iFirst, + sqlite_int64 *rowid, + DocList *out){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, TERM_SELECT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_text(s, 1, zTerm, nTerm, SQLITE_TRANSIENT); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 2, iFirst); + if( rc!=SQLITE_OK ) return rc; + + rc = sql_step_statement(v, TERM_SELECT_STMT, &s); + if( rc!=SQLITE_ROW ) return rc==SQLITE_DONE ? SQLITE_ERROR : rc; + + *rowid = sqlite3_column_int64(s, 0); + docListInit(out, DL_POSITIONS_OFFSETS, + sqlite3_column_blob(s, 1), sqlite3_column_bytes(s, 1)); + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + rc = sqlite3_step(s); + return rc==SQLITE_DONE ? SQLITE_OK : rc; +} + +/* select max(first) from %_term where term = [zTerm] and first <= [iFirst] + * If found, returns SQLITE_ROW and result in *piResult; if the query returns + * NULL (meaning no row found) returns SQLITE_DONE. + */ +static int term_chunk_select(fulltext_vtab *v, const char *zTerm, int nTerm, + sqlite_int64 iFirst, sqlite_int64 *piResult){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, TERM_CHUNK_SELECT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_text(s, 1, zTerm, nTerm, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 2, iFirst); + if( rc!=SQLITE_OK ) return rc; + + rc = sql_step_statement(v, TERM_CHUNK_SELECT_STMT, &s); + if( rc!=SQLITE_ROW ) return rc==SQLITE_DONE ? SQLITE_ERROR : rc; + + switch( sqlite3_column_type(s, 0) ){ + case SQLITE_NULL: + rc = SQLITE_DONE; + break; + case SQLITE_INTEGER: + *piResult = sqlite3_column_int64(s, 0); + break; + default: + return SQLITE_ERROR; + } + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + if( sqlite3_step(s) != SQLITE_DONE ) return SQLITE_ERROR; + return rc; +} + +/* insert into %_term (term, first, doclist) + values ([zTerm], [iFirst], [doclist]) */ +static int term_insert(fulltext_vtab *v, const char *zTerm, int nTerm, + sqlite_int64 iFirst, DocList *doclist){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, TERM_INSERT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_text(s, 1, zTerm, nTerm, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 2, iFirst); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_blob(s, 3, doclist->pData, doclist->nData, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, TERM_INSERT_STMT, &s); +} + +/* update %_term set doclist = [doclist] where rowid = [rowid] */ +static int term_update(fulltext_vtab *v, sqlite_int64 rowid, + DocList *doclist){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, TERM_UPDATE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_blob(s, 1, doclist->pData, doclist->nData, + SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 2, rowid); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, TERM_UPDATE_STMT, &s); +} + +static int term_delete(fulltext_vtab *v, sqlite_int64 rowid){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, TERM_DELETE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, rowid); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step_statement(v, TERM_DELETE_STMT, &s); +} + +static void fulltext_vtab_destroy(fulltext_vtab *v){ + int iStmt; + + for( iStmt=0; iStmtpFulltextStatements[iStmt]!=NULL ){ + sqlite3_finalize(v->pFulltextStatements[iStmt]); + v->pFulltextStatements[iStmt] = NULL; + } + } + + if( v->pTokenizer!=NULL ){ + v->pTokenizer->pModule->xDestroy(v->pTokenizer); + v->pTokenizer = NULL; + } + + free((void *) v->zName); + free(v); +} + +/* Current interface: +** argv[0] - module name +** argv[1] - database name +** argv[2] - table name +** argv[3] - tokenizer name (optional, a sensible default is provided) +** argv[4..] - passed to tokenizer (optional based on tokenizer) +**/ +static int fulltextConnect( + sqlite3 *db, + void *pAux, + int argc, + const char * const *argv, + sqlite3_vtab **ppVTab, + char **pzErr +){ + int rc; + fulltext_vtab *v; + sqlite3_tokenizer_module *m = NULL; + + assert( argc>=3 ); + v = (fulltext_vtab *) malloc(sizeof(fulltext_vtab)); + /* sqlite will initialize v->base */ + v->db = db; + v->zName = string_dup(argv[2]); + v->pTokenizer = NULL; + + if( argc==3 ){ + get_simple_tokenizer_module(&m); + } else { + /* TODO(shess) For now, add new tokenizers as else if clauses. */ + if( !strcmp(argv[3], "simple") ){ + get_simple_tokenizer_module(&m); + } else { + assert( "unrecognized tokenizer"==NULL ); + } + } + + /* TODO(shess) Since tokenization impacts the index, the parameters + ** to the tokenizer need to be identical when a persistent virtual + ** table is re-created. One solution would be a meta-table to track + ** such information in the database. Then we could verify that the + ** information is identical on subsequent creates. + */ + /* TODO(shess) Why isn't argv already (const char **)? */ + rc = m->xCreate(argc-3, (const char **) (argv+3), &v->pTokenizer); + if( rc!=SQLITE_OK ) return rc; + v->pTokenizer->pModule = m; + + /* TODO: verify the existence of backing tables foo_content, foo_term */ + + rc = sqlite3_declare_vtab(db, "create table x(content text)"); + if( rc!=SQLITE_OK ) return rc; + + memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements)); + + *ppVTab = &v->base; + return SQLITE_OK; +} + +static int fulltextCreate( + sqlite3 *db, + void *pAux, + int argc, + const char * const *argv, + sqlite3_vtab **ppVTab, + char **pzErr +){ + int rc; + assert( argc>=3 ); + + /* The %_content table holds the text of each full-text item, with + ** the rowid used as the docid. + ** + ** The %_term table maps each term to a document list blob + ** containing elements sorted by ascending docid, each element + ** encoded as: + ** + ** docid varint-encoded + ** token count varint-encoded + ** "count" token elements (poslist): + ** position varint-encoded as delta from previous position + ** start offset varint-encoded as delta from previous start offset + ** end offset varint-encoded as delta from start offset + ** + ** Additionally, doclist blobs can be chunked into multiple rows, + ** using "first" to order the blobs. "first" is simply the first + ** docid in the blob. + */ + /* + ** NOTE(shess) That last sentence is incorrect in the face of + ** deletion, which can leave a doclist that doesn't contain the + ** first from that row. I _believe_ this does not matter to the + ** operation of the system, but it might be reasonable to update + ** appropriately in case this assumption becomes more important. + */ + rc = sql_exec(db, argv[2], + "create table %_content(content text);" + "create table %_term(term text, first integer, doclist blob);" + "create index %_index on %_term(term, first)"); + if( rc!=SQLITE_OK ) return rc; + + return fulltextConnect(db, pAux, argc, argv, ppVTab, pzErr); +} + +/* Decide how to handle an SQL query. + * At the moment, MATCH queries can include implicit boolean ANDs; we + * haven't implemented phrase searches or OR yet. */ +static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ + int i; + + for(i=0; inConstraint; ++i){ + const struct sqlite3_index_constraint *pConstraint; + pConstraint = &pInfo->aConstraint[i]; + if( pConstraint->iColumn==0 && + pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH && + pConstraint->usable ){ /* a full-text search */ + pInfo->aConstraintUsage[i].argvIndex = 1; + pInfo->aConstraintUsage[i].omit = 1; + pInfo->idxNum = QUERY_FULLTEXT; + pInfo->estimatedCost = 1.0; /* an arbitrary value for now */ + return SQLITE_OK; + } + } + pInfo->idxNum = QUERY_GENERIC; + return SQLITE_OK; +} + +static int fulltextDisconnect(sqlite3_vtab *pVTab){ + fulltext_vtab_destroy((fulltext_vtab *)pVTab); + return SQLITE_OK; +} + +static int fulltextDestroy(sqlite3_vtab *pVTab){ + fulltext_vtab *v = (fulltext_vtab *)pVTab; + + int rc = sql_exec(v->db, v->zName, + "drop table %_content; drop table %_term"); + if( rc!=SQLITE_OK ) return rc; + + fulltext_vtab_destroy((fulltext_vtab *)pVTab); + return SQLITE_OK; +} + +static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + fulltext_cursor *c; + + c = (fulltext_cursor *) calloc(sizeof(fulltext_cursor), 1); + /* sqlite will initialize c->base */ + *ppCursor = &c->base; + + return SQLITE_OK; +} + +static int fulltextClose(sqlite3_vtab_cursor *pCursor){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + sqlite3_finalize(c->pStmt); + if( c->result.pDoclist!=NULL ){ + docListDelete(c->result.pDoclist); + } + free(c); + return SQLITE_OK; +} + +static int fulltextNext(sqlite3_vtab_cursor *pCursor){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + sqlite_int64 iDocid; + int rc; + + switch( c->iCursorType ){ + case QUERY_GENERIC: + /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */ + rc = sqlite3_step(c->pStmt); + switch( rc ){ + case SQLITE_ROW: + c->eof = 0; + return SQLITE_OK; + case SQLITE_DONE: + c->eof = 1; + return SQLITE_OK; + default: + c->eof = 1; + return rc; + } + case QUERY_FULLTEXT: + rc = sqlite3_reset(c->pStmt); + if( rc!=SQLITE_OK ) return rc; + + if( readerAtEnd(&c->result)){ + c->eof = 1; + return SQLITE_OK; + } + iDocid = readDocid(&c->result); + rc = sqlite3_bind_int64(c->pStmt, 1, iDocid); + if( rc!=SQLITE_OK ) return rc; + /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */ + rc = sqlite3_step(c->pStmt); + if( rc==SQLITE_ROW ){ /* the case we expect */ + c->eof = 0; + return SQLITE_OK; + } + /* an error occurred; abort */ + return rc==SQLITE_DONE ? SQLITE_ERROR : rc; + default: + assert( 0 ); + return SQLITE_ERROR; /* not reached */ + } +} + +static int term_select_doclist(fulltext_vtab *v, const char *pTerm, int nTerm, + sqlite3_stmt **ppStmt){ + int rc; + if( *ppStmt ){ + rc = sqlite3_reset(*ppStmt); + } else { + rc = sql_prepare(v->db, v->zName, ppStmt, + "select doclist from %_term where term = ? order by first"); + } + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_text(*ppStmt, 1, pTerm, nTerm, SQLITE_TRANSIENT); + if( rc!=SQLITE_OK ) return rc; + + return sqlite3_step(*ppStmt); /* TODO(adamd): handle schema error */ +} + +/* Read the posting list for [zTerm]; AND it with the doclist [in] to + * produce the doclist [out], using the given offset [iOffset] for phrase + * matching. + * (*pSelect) is used to hold an SQLite statement used inside this function; + * the caller should initialize *pSelect to NULL before the first call. + */ +static int query_merge(fulltext_vtab *v, sqlite3_stmt **pSelect, + const char *zTerm, + DocList *pIn, int iOffset, DocList *out){ + int rc; + DocListMerge merge; + + if( pIn!=NULL && !pIn->nData ){ + /* If [pIn] is already empty, there's no point in reading the + * posting list to AND it in; return immediately. */ + return SQLITE_OK; + } + + rc = term_select_doclist(v, zTerm, -1, pSelect); + if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc; + + mergeInit(&merge, pIn, iOffset, out); + while( rc==SQLITE_ROW ){ + DocList block; + docListInit(&block, DL_POSITIONS_OFFSETS, + sqlite3_column_blob(*pSelect, 0), + sqlite3_column_bytes(*pSelect, 0)); + mergeBlock(&merge, &block); + docListDestroy(&block); + + rc = sqlite3_step(*pSelect); + if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ + return rc; + } + } + + return SQLITE_OK; +} + +typedef struct QueryTerm { + int is_phrase; /* true if this term begins a new phrase */ + const char *zTerm; +} QueryTerm; + +/* A parsed query. + * + * As an example, parsing the query ["four score" years "new nation"] will + * yield a Query with 5 terms: + * "four", is_phrase = 1 + * "score", is_phrase = 0 + * "years", is_phrase = 1 + * "new", is_phrase = 1 + * "nation", is_phrase = 0 + */ +typedef struct Query { + int nTerms; + QueryTerm *pTerm; +} Query; + +static void query_add(Query *q, int is_phrase, const char *zTerm){ + QueryTerm *t; + ++q->nTerms; + q->pTerm = realloc(q->pTerm, q->nTerms * sizeof(q->pTerm[0])); + t = &q->pTerm[q->nTerms - 1]; + t->is_phrase = is_phrase; + t->zTerm = zTerm; +} + +static void query_free(Query *q){ + int i; + for(i = 0; i < q->nTerms; ++i){ + free((void *) q->pTerm[i].zTerm); + } + free(q->pTerm); +} + +static int tokenize_segment(sqlite3_tokenizer *pTokenizer, + const char *zQuery, int in_phrase, + Query *pQuery){ + sqlite3_tokenizer_module *pModule = pTokenizer->pModule; + sqlite3_tokenizer_cursor *pCursor; + int is_first = 1; + + int rc = pModule->xOpen(pTokenizer, zQuery, -1, &pCursor); + if( rc!=SQLITE_OK ) return rc; + pCursor->pTokenizer = pTokenizer; + + while( 1 ){ + const char *zToken; + int nToken, iStartOffset, iEndOffset, dummy_pos; + + rc = pModule->xNext(pCursor, + &zToken, &nToken, + &iStartOffset, &iEndOffset, + &dummy_pos); + if( rc!=SQLITE_OK ) break; + query_add(pQuery, !in_phrase || is_first, string_dup_n(zToken, nToken)); + is_first = 0; + } + + return pModule->xClose(pCursor); +} + +/* Parse a query string, yielding a Query object. */ +static int parse_query(fulltext_vtab *v, const char *zQuery, Query *pQuery){ + char *zQuery1 = string_dup(zQuery); + int in_phrase = 0; + char *s = zQuery1; + pQuery->nTerms = 0; + pQuery->pTerm = NULL; + + while( *s ){ + char *t = s; + while( *t ){ + if( *t=='"' ){ + *t++ = '\0'; + break; + } + ++t; + } + if( *s ){ + tokenize_segment(v->pTokenizer, s, in_phrase, pQuery); + } + s = t; + in_phrase = !in_phrase; + } + + free(zQuery1); + return SQLITE_OK; +} + +/* Perform a full-text query; return a list of documents in [pResult]. */ +static int fulltext_query(fulltext_vtab *v, const char *zQuery, + DocList **pResult){ + Query q; + int phrase_start = -1; + int i; + sqlite3_stmt *pSelect = NULL; + DocList *d = NULL; + + int rc = parse_query(v, zQuery, &q); + if( rc!=SQLITE_OK ) return rc; + + /* Merge terms. */ + for(i = 0 ; i < q.nTerms ; ++i){ + /* In each merge step, we need to generate positions whenever we're + * processing a phrase which hasn't ended yet. */ + int need_positions = iiCursorType = idxNum; + switch( idxNum ){ + case QUERY_GENERIC: + zStatement = "select rowid, content from %_content"; + break; + + case QUERY_FULLTEXT: /* full-text search */ + { + const char *zQuery = (const char *)sqlite3_value_text(argv[0]); + DocList *pResult; + assert( argc==1 ); + rc = fulltext_query(v, zQuery, &pResult); + if( rc!=SQLITE_OK ) return rc; + readerInit(&c->result, pResult); + zStatement = "select rowid, content from %_content where rowid = ?"; + break; + } + + default: + assert( 0 ); + } + + rc = sql_prepare(v->db, v->zName, &c->pStmt, zStatement); + if( rc!=SQLITE_OK ) return rc; + + return fulltextNext(pCursor); +} + +static int fulltextEof(sqlite3_vtab_cursor *pCursor){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + return c->eof; +} + +static int fulltextColumn(sqlite3_vtab_cursor *pCursor, + sqlite3_context *pContext, int idxCol){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + const char *s; + + assert( idxCol==0 ); + s = (const char *) sqlite3_column_text(c->pStmt, 1); + sqlite3_result_text(pContext, s, -1, SQLITE_TRANSIENT); + + return SQLITE_OK; +} + +static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + + *pRowid = sqlite3_column_int64(c->pStmt, 0); + return SQLITE_OK; +} + +/* Build a hash table containing all terms in zText. */ +static int build_terms(Hash *terms, sqlite3_tokenizer *pTokenizer, + const char *zText, sqlite_int64 iDocid){ + sqlite3_tokenizer_cursor *pCursor; + const char *pToken; + int nTokenBytes; + int iStartOffset, iEndOffset, iPosition; + + int rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor); + if( rc!=SQLITE_OK ) return rc; + + pCursor->pTokenizer = pTokenizer; + HashInit(terms, HASH_STRING, 1); + while( SQLITE_OK==pTokenizer->pModule->xNext(pCursor, + &pToken, &nTokenBytes, + &iStartOffset, &iEndOffset, + &iPosition) ){ + DocList *p; + + /* Positions can't be negative; we use -1 as a terminator internally. */ + if( iPosition<0 ) { + rc = SQLITE_ERROR; + goto err; + } + + p = HashFind(terms, pToken, nTokenBytes); + if( p==NULL ){ + p = docListNew(DL_POSITIONS_OFFSETS); + docListAddDocid(p, iDocid); + HashInsert(terms, pToken, nTokenBytes, p); + } + docListAddPosOffset(p, iPosition, iStartOffset, iEndOffset); + } + +err: + /* TODO(shess) Check return? Should this be able to cause errors at + ** this point? Actually, same question about sqlite3_finalize(), + ** though one could argue that failure there means that the data is + ** not durable. *ponder* + */ + pTokenizer->pModule->xClose(pCursor); + return rc; +} +/* Update the %_terms table to map the term [zTerm] to the given rowid. */ +static int index_insert_term(fulltext_vtab *v, const char *zTerm, int nTerm, + sqlite_int64 iDocid, DocList *p){ + sqlite_int64 iFirst; + sqlite_int64 iIndexRow; + DocList doclist; + + int rc = term_chunk_select(v, zTerm, nTerm, iDocid, &iFirst); + if( rc==SQLITE_DONE ){ + docListInit(&doclist, DL_POSITIONS_OFFSETS, 0, 0); + if( docListUpdate(&doclist, iDocid, p) ){ + rc = term_insert(v, zTerm, nTerm, iDocid, &doclist); + docListDestroy(&doclist); + return rc; + } + return SQLITE_OK; + } + if( rc!=SQLITE_ROW ) return SQLITE_ERROR; + + /* This word is in the index; add this document ID to its blob. */ + + rc = term_select(v, zTerm, nTerm, iFirst, &iIndexRow, &doclist); + if( rc!=SQLITE_OK ) return rc; + + if( docListUpdate(&doclist, iDocid, p) ){ + /* If the blob is too big, split it in half. */ + if( doclist.nData>CHUNK_MAX ){ + DocList half; + if( docListSplit(&doclist, &half) ){ + rc = term_insert(v, zTerm, nTerm, firstDocid(&half), &half); + docListDestroy(&half); + if( rc!=SQLITE_OK ) goto err; + } + } + rc = term_update(v, iIndexRow, &doclist); + } + +err: + docListDestroy(&doclist); + return rc; +} + +/* Insert a row into the full-text index; set *piRowid to be the ID of the + * new row. */ +static int index_insert(fulltext_vtab *v, + sqlite3_value *pRequestRowid, const char *zText, + sqlite_int64 *piRowid){ + Hash terms; /* maps term string -> PosList */ + HashElem *e; + + int rc = content_insert(v, pRequestRowid, zText, -1); + if( rc!=SQLITE_OK ) return rc; + *piRowid = sqlite3_last_insert_rowid(v->db); + + if( !zText ) return SQLITE_OK; /* nothing to index */ + + rc = build_terms(&terms, v->pTokenizer, zText, *piRowid); + if( rc!=SQLITE_OK ) return rc; + + for(e=HashFirst(&terms); e; e=HashNext(e)){ + DocList *p = HashData(e); + rc = index_insert_term(v, HashKey(e), HashKeysize(e), *piRowid, p); + if( rc!=SQLITE_OK ) break; + } + + for(e=HashFirst(&terms); e; e=HashNext(e)){ + DocList *p = HashData(e); + docListDelete(p); + } + HashClear(&terms); + return rc; +} + +static int index_delete_term(fulltext_vtab *v, const char *zTerm, int nTerm, + sqlite_int64 iDocid){ + sqlite_int64 iFirst; + sqlite_int64 iIndexRow; + DocList doclist; + + int rc = term_chunk_select(v, zTerm, nTerm, iDocid, &iFirst); + if( rc!=SQLITE_ROW ) return SQLITE_ERROR; + + rc = term_select(v, zTerm, nTerm, iFirst, &iIndexRow, &doclist); + if( rc!=SQLITE_OK ) return rc; + + if( docListUpdate(&doclist, iDocid, NULL) ){ + if( doclist.nData>0 ){ + rc = term_update(v, iIndexRow, &doclist); + } else { /* empty posting list */ + rc = term_delete(v, iIndexRow); + } + } + docListDestroy(&doclist); + return rc; +} + +/* Delete a row from the full-text index. */ +static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){ + char *zText; + Hash terms; + HashElem *e; + + int rc = content_select(v, iRow, &zText); + if( rc!=SQLITE_OK ) return rc; + + rc = build_terms(&terms, v->pTokenizer, zText, iRow); + free(zText); + if( rc!=SQLITE_OK ) return rc; + + for(e=HashFirst(&terms); e; e=HashNext(e)){ + rc = index_delete_term(v, HashKey(e), HashKeysize(e), iRow); + if( rc!=SQLITE_OK ) break; + } + for(e=HashFirst(&terms); e; e=HashNext(e)){ + DocList *p = HashData(e); + docListDelete(p); + } + HashClear(&terms); + + return content_delete(v, iRow); +} + +static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg, + sqlite_int64 *pRowid){ + fulltext_vtab *v = (fulltext_vtab *) pVtab; + + if( nArg<2 ){ + return index_delete(v, sqlite3_value_int64(ppArg[0])); + } + + if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){ + return SQLITE_ERROR; /* an update; not yet supported */ + } + + assert( nArg==3 ); /* ppArg[1] = rowid, ppArg[2] = content */ + return index_insert(v, ppArg[1], + (const char *)sqlite3_value_text(ppArg[2]), pRowid); +} + +static sqlite3_module fulltextModule = { + 0, + fulltextCreate, + fulltextConnect, + fulltextBestIndex, + fulltextDisconnect, + fulltextDestroy, + fulltextOpen, + fulltextClose, + fulltextFilter, + fulltextNext, + fulltextEof, + fulltextColumn, + fulltextRowid, + fulltextUpdate +}; + +int fulltext_init(sqlite3 *db){ + return sqlite3_create_module(db, "fulltext", &fulltextModule, 0); +} + +#if !SQLITE_CORE +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_fulltext_init(sqlite3 *db, char **pzErrMsg, + const sqlite3_api_routines *pApi){ + SQLITE_EXTENSION_INIT2(pApi) + return fulltext_init(db); +} +#endif diff --git a/components/external/SQLite-3.8.1/ext/fts1/fulltext.h b/components/external/SQLite-3.8.1/ext/fts1/fulltext.h new file mode 100644 index 0000000000000000000000000000000000000000..477dcab2ade9e39b6e3796c5642f16a825c1662e --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/fulltext.h @@ -0,0 +1,11 @@ +#include "sqlite3.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +int fulltext_init(sqlite3 *db); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ diff --git a/components/external/SQLite-3.8.1/ext/fts1/simple_tokenizer.c b/components/external/SQLite-3.8.1/ext/fts1/simple_tokenizer.c new file mode 100644 index 0000000000000000000000000000000000000000..d00a77089d871ccbd6528a943ab79045b0445a3a --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/simple_tokenizer.c @@ -0,0 +1,174 @@ +/* +** The author disclaims copyright to this source code. +** +************************************************************************* +** Implementation of the "simple" full-text-search tokenizer. +*/ + +#include +#if !defined(__APPLE__) +#include +#else +#include +#endif +#include +#include +#include + +#include "tokenizer.h" + +/* Duplicate a string; the caller must free() the returned string. + * (We don't use strdup() since it's not part of the standard C library and + * may not be available everywhere.) */ +/* TODO(shess) Copied from fulltext.c, consider util.c for such +** things. */ +static char *string_dup(const char *s){ + char *str = malloc(strlen(s) + 1); + strcpy(str, s); + return str; +} + +typedef struct simple_tokenizer { + sqlite3_tokenizer base; + const char *zDelim; /* token delimiters */ +} simple_tokenizer; + +typedef struct simple_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *pInput; /* input we are tokenizing */ + int nBytes; /* size of the input */ + const char *pCurrent; /* current position in pInput */ + int iToken; /* index of next token to be returned */ + char *zToken; /* storage for current token */ + int nTokenBytes; /* actual size of current token */ + int nTokenAllocated; /* space allocated to zToken buffer */ +} simple_tokenizer_cursor; + +static sqlite3_tokenizer_module simpleTokenizerModule;/* forward declaration */ + +static int simpleCreate( + int argc, const char **argv, + sqlite3_tokenizer **ppTokenizer +){ + simple_tokenizer *t; + + t = (simple_tokenizer *) malloc(sizeof(simple_tokenizer)); + /* TODO(shess) Delimiters need to remain the same from run to run, + ** else we need to reindex. One solution would be a meta-table to + ** track such information in the database, then we'd only want this + ** information on the initial create. + */ + if( argc>1 ){ + t->zDelim = string_dup(argv[1]); + } else { + /* Build a string excluding alphanumeric ASCII characters */ + char zDelim[0x80]; /* nul-terminated, so nul not a member */ + int i, j; + for(i=1, j=0; i<0x80; i++){ + if( !isalnum(i) ){ + zDelim[j++] = i; + } + } + zDelim[j++] = '\0'; + assert( j<=sizeof(zDelim) ); + t->zDelim = string_dup(zDelim); + } + + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ + simple_tokenizer *t = (simple_tokenizer *) pTokenizer; + + free((void *) t->zDelim); + free(t); + + return SQLITE_OK; +} + +static int simpleOpen( + sqlite3_tokenizer *pTokenizer, + const char *pInput, int nBytes, + sqlite3_tokenizer_cursor **ppCursor +){ + simple_tokenizer_cursor *c; + + c = (simple_tokenizer_cursor *) malloc(sizeof(simple_tokenizer_cursor)); + c->pInput = pInput; + c->nBytes = nBytes<0 ? (int) strlen(pInput) : nBytes; + c->pCurrent = c->pInput; /* start tokenizing at the beginning */ + c->iToken = 0; + c->zToken = NULL; /* no space allocated, yet. */ + c->nTokenBytes = 0; + c->nTokenAllocated = 0; + + *ppCursor = &c->base; + return SQLITE_OK; +} + +static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + + if( NULL!=c->zToken ){ + free(c->zToken); + } + free(c); + + return SQLITE_OK; +} + +static int simpleNext( + sqlite3_tokenizer_cursor *pCursor, + const char **ppToken, int *pnBytes, + int *piStartOffset, int *piEndOffset, int *piPosition +){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer; + int ii; + + while( c->pCurrent-c->pInputnBytes ){ + int n = (int) strcspn(c->pCurrent, t->zDelim); + if( n>0 ){ + if( n+1>c->nTokenAllocated ){ + c->zToken = realloc(c->zToken, n+1); + } + for(ii=0; iipCurrent[ii]; + c->zToken[ii] = (unsigned char)ch<0x80 ? tolower(ch) : ch; + } + c->zToken[n] = '\0'; + *ppToken = c->zToken; + *pnBytes = n; + *piStartOffset = (int) (c->pCurrent-c->pInput); + *piEndOffset = *piStartOffset+n; + *piPosition = c->iToken++; + c->pCurrent += n + 1; + + return SQLITE_OK; + } + c->pCurrent += n + 1; + /* TODO(shess) could strspn() to skip delimiters en masse. Needs + ** to happen in two places, though, which is annoying. + */ + } + return SQLITE_DONE; +} + +static sqlite3_tokenizer_module simpleTokenizerModule = { + 0, + simpleCreate, + simpleDestroy, + simpleOpen, + simpleClose, + simpleNext, +}; + +void get_simple_tokenizer_module( + sqlite3_tokenizer_module **ppModule +){ + *ppModule = &simpleTokenizerModule; +} diff --git a/components/external/SQLite-3.8.1/ext/fts1/tokenizer.h b/components/external/SQLite-3.8.1/ext/fts1/tokenizer.h new file mode 100644 index 0000000000000000000000000000000000000000..1d7bd1f6703ec2736b98d239b8621363cdfa5d04 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts1/tokenizer.h @@ -0,0 +1,89 @@ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _TOKENIZER_H_ +#define _TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ +#include "sqlite3.h" + +/* +** Structures used by the tokenizer interface. +*/ +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; + +struct sqlite3_tokenizer_module { + int iVersion; /* currently 0 */ + + /* + ** Create and destroy a tokenizer. argc/argv are passed down from + ** the fulltext virtual table creation to allow customization. + */ + int (*xCreate)(int argc, const char **argv, + sqlite3_tokenizer **ppTokenizer); + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Tokenize a particular input. Call xOpen() to prepare to + ** tokenize, xNext() repeatedly until it returns SQLITE_DONE, then + ** xClose() to free any internal state. The pInput passed to + ** xOpen() must exist until the cursor is closed. The ppToken + ** result from xNext() is only valid until the next call to xNext() + ** or until xClose() is called. + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xOpen)(sqlite3_tokenizer *pTokenizer, + const char *pInput, int nBytes, + sqlite3_tokenizer_cursor **ppCursor); + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + int (*xNext)(sqlite3_tokenizer_cursor *pCursor, + const char **ppToken, int *pnBytes, + int *piStartOffset, int *piEndOffset, int *piPosition); +}; + +struct sqlite3_tokenizer { + sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +/* +** Get the module for a tokenizer which generates tokens based on a +** set of non-token characters. The default is to break tokens at any +** non-alnum character, though the set of delimiters can also be +** specified by the first argv argument to xCreate(). +*/ +/* TODO(shess) This doesn't belong here. Need some sort of +** registration process. +*/ +void get_simple_tokenizer_module(sqlite3_tokenizer_module **ppModule); + +#endif /* _TOKENIZER_H_ */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/README.tokenizers b/components/external/SQLite-3.8.1/ext/fts2/README.tokenizers new file mode 100644 index 0000000000000000000000000000000000000000..98d2021ba1d02cef16b67eed84b2103a45adfaff --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/README.tokenizers @@ -0,0 +1,133 @@ + +1. FTS2 Tokenizers + + When creating a new full-text table, FTS2 allows the user to select + the text tokenizer implementation to be used when indexing text + by specifying a "tokenizer" clause as part of the CREATE VIRTUAL TABLE + statement: + + CREATE VIRTUAL TABLE USING fts2( + [, tokenizer []] + ); + + The built-in tokenizers (valid values to pass as ) are + "simple" and "porter". + + should consist of zero or more white-space separated + arguments to pass to the selected tokenizer implementation. The + interpretation of the arguments, if any, depends on the individual + tokenizer. + +2. Custom Tokenizers + + FTS2 allows users to provide custom tokenizer implementations. The + interface used to create a new tokenizer is defined and described in + the fts2_tokenizer.h source file. + + Registering a new FTS2 tokenizer is similar to registering a new + virtual table module with SQLite. The user passes a pointer to a + structure containing pointers to various callback functions that + make up the implementation of the new tokenizer type. For tokenizers, + the structure (defined in fts2_tokenizer.h) is called + "sqlite3_tokenizer_module". + + FTS2 does not expose a C-function that users call to register new + tokenizer types with a database handle. Instead, the pointer must + be encoded as an SQL blob value and passed to FTS2 through the SQL + engine by evaluating a special scalar function, "fts2_tokenizer()". + The fts2_tokenizer() function may be called with one or two arguments, + as follows: + + SELECT fts2_tokenizer(); + SELECT fts2_tokenizer(, ); + + Where is a string identifying the tokenizer and + is a pointer to an sqlite3_tokenizer_module + structure encoded as an SQL blob. If the second argument is present, + it is registered as tokenizer and a copy of it + returned. If only one argument is passed, a pointer to the tokenizer + implementation currently registered as is returned, + encoded as a blob. Or, if no such tokenizer exists, an SQL exception + (error) is raised. + + SECURITY: If the fts2 extension is used in an environment where potentially + malicious users may execute arbitrary SQL (i.e. gears), they should be + prevented from invoking the fts2_tokenizer() function, possibly using the + authorisation callback. + + See "Sample code" below for an example of calling the fts2_tokenizer() + function from C code. + +3. ICU Library Tokenizers + + If this extension is compiled with the SQLITE_ENABLE_ICU pre-processor + symbol defined, then there exists a built-in tokenizer named "icu" + implemented using the ICU library. The first argument passed to the + xCreate() method (see fts2_tokenizer.h) of this tokenizer may be + an ICU locale identifier. For example "tr_TR" for Turkish as used + in Turkey, or "en_AU" for English as used in Australia. For example: + + "CREATE VIRTUAL TABLE thai_text USING fts2(text, tokenizer icu th_TH)" + + The ICU tokenizer implementation is very simple. It splits the input + text according to the ICU rules for finding word boundaries and discards + any tokens that consist entirely of white-space. This may be suitable + for some applications in some locales, but not all. If more complex + processing is required, for example to implement stemming or + discard punctuation, this can be done by creating a tokenizer + implementation that uses the ICU tokenizer as part of its implementation. + + When using the ICU tokenizer this way, it is safe to overwrite the + contents of the strings returned by the xNext() method (see + fts2_tokenizer.h). + +4. Sample code. + + The following two code samples illustrate the way C code should invoke + the fts2_tokenizer() scalar function: + + int registerTokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module *p + ){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts2_tokenizer(?, ?)"; + + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); + sqlite3_step(pStmt); + + return sqlite3_finalize(pStmt); + } + + int queryTokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module **pp + ){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts2_tokenizer(?)"; + + *pp = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ + memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + } + } + + return sqlite3_finalize(pStmt); + } diff --git a/components/external/SQLite-3.8.1/ext/fts2/README.txt b/components/external/SQLite-3.8.1/ext/fts2/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..517a2a043466cac040cb45686e397c9c650bb93e --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/README.txt @@ -0,0 +1,4 @@ +This folder contains source code to the second full-text search +extension for SQLite. While the API is the same, this version uses a +substantially different storage schema from fts1, so tables will need +to be rebuilt. diff --git a/components/external/SQLite-3.8.1/ext/fts2/fts2.c b/components/external/SQLite-3.8.1/ext/fts2/fts2.c new file mode 100644 index 0000000000000000000000000000000000000000..0405fb7b1e56f9aefccebcc274131b973a16b768 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/fts2.c @@ -0,0 +1,6860 @@ +/* fts2 has a design flaw which can lead to database corruption (see +** below). It is recommended not to use it any longer, instead use +** fts3 (or higher). If you believe that your use of fts2 is safe, +** add -DSQLITE_ENABLE_BROKEN_FTS2=1 to your CFLAGS. +*/ +#if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)) \ + && !defined(SQLITE_ENABLE_BROKEN_FTS2) +#error fts2 has a design flaw and has been deprecated. +#endif +/* The flaw is that fts2 uses the content table's unaliased rowid as +** the unique docid. fts2 embeds the rowid in the index it builds, +** and expects the rowid to not change. The SQLite VACUUM operation +** will renumber such rowids, thereby breaking fts2. If you are using +** fts2 in a system which has disabled VACUUM, then you can continue +** to use it safely. Note that PRAGMA auto_vacuum does NOT disable +** VACUUM, though systems using auto_vacuum are unlikely to invoke +** VACUUM. +** +** Unlike fts1, which is safe across VACUUM if you never delete +** documents, fts2 has a second exposure to this flaw, in the segments +** table. So fts2 should be considered unsafe across VACUUM in all +** cases. +*/ + +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This is an SQLite module implementing full-text search. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS2 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS2 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS2 is defined). +*/ + +/* TODO(shess) Consider exporting this comment to an HTML file or the +** wiki. +*/ +/* The full-text index is stored in a series of b+tree (-like) +** structures called segments which map terms to doclists. The +** structures are like b+trees in layout, but are constructed from the +** bottom up in optimal fashion and are not updatable. Since trees +** are built from the bottom up, things will be described from the +** bottom up. +** +** +**** Varints **** +** The basic unit of encoding is a variable-length integer called a +** varint. We encode variable-length integers in little-endian order +** using seven bits * per byte as follows: +** +** KEY: +** A = 0xxxxxxx 7 bits of data and one flag bit +** B = 1xxxxxxx 7 bits of data and one flag bit +** +** 7 bits - A +** 14 bits - BA +** 21 bits - BBA +** and so on. +** +** This is identical to how sqlite encodes varints (see util.c). +** +** +**** Document lists **** +** A doclist (document list) holds a docid-sorted list of hits for a +** given term. Doclists hold docids, and can optionally associate +** token positions and offsets with docids. +** +** A DL_POSITIONS_OFFSETS doclist is stored like this: +** +** array { +** varint docid; +** array { (position list for column 0) +** varint position; (delta from previous position plus POS_BASE) +** varint startOffset; (delta from previous startOffset) +** varint endOffset; (delta from startOffset) +** } +** array { +** varint POS_COLUMN; (marks start of position list for new column) +** varint column; (index of new column) +** array { +** varint position; (delta from previous position plus POS_BASE) +** varint startOffset;(delta from previous startOffset) +** varint endOffset; (delta from startOffset) +** } +** } +** varint POS_END; (marks end of positions for this document. +** } +** +** Here, array { X } means zero or more occurrences of X, adjacent in +** memory. A "position" is an index of a token in the token stream +** generated by the tokenizer, while an "offset" is a byte offset, +** both based at 0. Note that POS_END and POS_COLUMN occur in the +** same logical place as the position element, and act as sentinals +** ending a position list array. +** +** A DL_POSITIONS doclist omits the startOffset and endOffset +** information. A DL_DOCIDS doclist omits both the position and +** offset information, becoming an array of varint-encoded docids. +** +** On-disk data is stored as type DL_DEFAULT, so we don't serialize +** the type. Due to how deletion is implemented in the segmentation +** system, on-disk doclists MUST store at least positions. +** +** +**** Segment leaf nodes **** +** Segment leaf nodes store terms and doclists, ordered by term. Leaf +** nodes are written using LeafWriter, and read using LeafReader (to +** iterate through a single leaf node's data) and LeavesReader (to +** iterate through a segment's entire leaf layer). Leaf nodes have +** the format: +** +** varint iHeight; (height from leaf level, always 0) +** varint nTerm; (length of first term) +** char pTerm[nTerm]; (content of first term) +** varint nDoclist; (length of term's associated doclist) +** char pDoclist[nDoclist]; (content of doclist) +** array { +** (further terms are delta-encoded) +** varint nPrefix; (length of prefix shared with previous term) +** varint nSuffix; (length of unshared suffix) +** char pTermSuffix[nSuffix];(unshared suffix of next term) +** varint nDoclist; (length of term's associated doclist) +** char pDoclist[nDoclist]; (content of doclist) +** } +** +** Here, array { X } means zero or more occurrences of X, adjacent in +** memory. +** +** Leaf nodes are broken into blocks which are stored contiguously in +** the %_segments table in sorted order. This means that when the end +** of a node is reached, the next term is in the node with the next +** greater node id. +** +** New data is spilled to a new leaf node when the current node +** exceeds LEAF_MAX bytes (default 2048). New data which itself is +** larger than STANDALONE_MIN (default 1024) is placed in a standalone +** node (a leaf node with a single term and doclist). The goal of +** these settings is to pack together groups of small doclists while +** making it efficient to directly access large doclists. The +** assumption is that large doclists represent terms which are more +** likely to be query targets. +** +** TODO(shess) It may be useful for blocking decisions to be more +** dynamic. For instance, it may make more sense to have a 2.5k leaf +** node rather than splitting into 2k and .5k nodes. My intuition is +** that this might extend through 2x or 4x the pagesize. +** +** +**** Segment interior nodes **** +** Segment interior nodes store blockids for subtree nodes and terms +** to describe what data is stored by the each subtree. Interior +** nodes are written using InteriorWriter, and read using +** InteriorReader. InteriorWriters are created as needed when +** SegmentWriter creates new leaf nodes, or when an interior node +** itself grows too big and must be split. The format of interior +** nodes: +** +** varint iHeight; (height from leaf level, always >0) +** varint iBlockid; (block id of node's leftmost subtree) +** optional { +** varint nTerm; (length of first term) +** char pTerm[nTerm]; (content of first term) +** array { +** (further terms are delta-encoded) +** varint nPrefix; (length of shared prefix with previous term) +** varint nSuffix; (length of unshared suffix) +** char pTermSuffix[nSuffix]; (unshared suffix of next term) +** } +** } +** +** Here, optional { X } means an optional element, while array { X } +** means zero or more occurrences of X, adjacent in memory. +** +** An interior node encodes n terms separating n+1 subtrees. The +** subtree blocks are contiguous, so only the first subtree's blockid +** is encoded. The subtree at iBlockid will contain all terms less +** than the first term encoded (or all terms if no term is encoded). +** Otherwise, for terms greater than or equal to pTerm[i] but less +** than pTerm[i+1], the subtree for that term will be rooted at +** iBlockid+i. Interior nodes only store enough term data to +** distinguish adjacent children (if the rightmost term of the left +** child is "something", and the leftmost term of the right child is +** "wicked", only "w" is stored). +** +** New data is spilled to a new interior node at the same height when +** the current node exceeds INTERIOR_MAX bytes (default 2048). +** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing +** interior nodes and making the tree too skinny. The interior nodes +** at a given height are naturally tracked by interior nodes at +** height+1, and so on. +** +** +**** Segment directory **** +** The segment directory in table %_segdir stores meta-information for +** merging and deleting segments, and also the root node of the +** segment's tree. +** +** The root node is the top node of the segment's tree after encoding +** the entire segment, restricted to ROOT_MAX bytes (default 1024). +** This could be either a leaf node or an interior node. If the top +** node requires more than ROOT_MAX bytes, it is flushed to %_segments +** and a new root interior node is generated (which should always fit +** within ROOT_MAX because it only needs space for 2 varints, the +** height and the blockid of the previous root). +** +** The meta-information in the segment directory is: +** level - segment level (see below) +** idx - index within level +** - (level,idx uniquely identify a segment) +** start_block - first leaf node +** leaves_end_block - last leaf node +** end_block - last block (including interior nodes) +** root - contents of root node +** +** If the root node is a leaf node, then start_block, +** leaves_end_block, and end_block are all 0. +** +** +**** Segment merging **** +** To amortize update costs, segments are groups into levels and +** merged in matches. Each increase in level represents exponentially +** more documents. +** +** New documents (actually, document updates) are tokenized and +** written individually (using LeafWriter) to a level 0 segment, with +** incrementing idx. When idx reaches MERGE_COUNT (default 16), all +** level 0 segments are merged into a single level 1 segment. Level 1 +** is populated like level 0, and eventually MERGE_COUNT level 1 +** segments are merged to a single level 2 segment (representing +** MERGE_COUNT^2 updates), and so on. +** +** A segment merge traverses all segments at a given level in +** parallel, performing a straightforward sorted merge. Since segment +** leaf nodes are written in to the %_segments table in order, this +** merge traverses the underlying sqlite disk structures efficiently. +** After the merge, all segment blocks from the merged level are +** deleted. +** +** MERGE_COUNT controls how often we merge segments. 16 seems to be +** somewhat of a sweet spot for insertion performance. 32 and 64 show +** very similar performance numbers to 16 on insertion, though they're +** a tiny bit slower (perhaps due to more overhead in merge-time +** sorting). 8 is about 20% slower than 16, 4 about 50% slower than +** 16, 2 about 66% slower than 16. +** +** At query time, high MERGE_COUNT increases the number of segments +** which need to be scanned and merged. For instance, with 100k docs +** inserted: +** +** MERGE_COUNT segments +** 16 25 +** 8 12 +** 4 10 +** 2 6 +** +** This appears to have only a moderate impact on queries for very +** frequent terms (which are somewhat dominated by segment merge +** costs), and infrequent and non-existent terms still seem to be fast +** even with many segments. +** +** TODO(shess) That said, it would be nice to have a better query-side +** argument for MERGE_COUNT of 16. Also, it is possible/likely that +** optimizations to things like doclist merging will swing the sweet +** spot around. +** +** +** +**** Handling of deletions and updates **** +** Since we're using a segmented structure, with no docid-oriented +** index into the term index, we clearly cannot simply update the term +** index when a document is deleted or updated. For deletions, we +** write an empty doclist (varint(docid) varint(POS_END)), for updates +** we simply write the new doclist. Segment merges overwrite older +** data for a particular docid with newer data, so deletes or updates +** will eventually overtake the earlier data and knock it out. The +** query logic likewise merges doclists so that newer data knocks out +** older data. +** +** TODO(shess) Provide a VACUUM type operation to clear out all +** deletions and duplications. This would basically be a forced merge +** into a single segment. +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) + +#if defined(SQLITE_ENABLE_FTS2) && !defined(SQLITE_CORE) +# define SQLITE_CORE 1 +#endif + +#include +#include +#include +#include +#include "fts2.h" +#include "fts2_hash.h" +#include "fts2_tokenizer.h" +#include "sqlite3.h" +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 + + +/* TODO(shess) MAN, this thing needs some refactoring. At minimum, it +** would be nice to order the file better, perhaps something along the +** lines of: +** +** - utility functions +** - table setup functions +** - table update functions +** - table query functions +** +** Put the query functions last because they're likely to reference +** typedefs or functions from the table update section. +*/ + +#if 0 +# define TRACE(A) printf A; fflush(stdout) +#else +# define TRACE(A) +#endif + +/* It is not safe to call isspace(), tolower(), or isalnum() on +** hi-bit-set characters. This is the same solution used in the +** tokenizer. +*/ +/* TODO(shess) The snippet-generation code should be using the +** tokenizer-generated tokens rather than doing its own local +** tokenization. +*/ +/* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */ +static int safe_isspace(char c){ + return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; +} +static int safe_tolower(char c){ + return (c>='A' && c<='Z') ? (c - 'A' + 'a') : c; +} +static int safe_isalnum(char c){ + return (c>='0' && c<='9') || (c>='A' && c<='Z') || (c>='a' && c<='z'); +} + +typedef enum DocListType { + DL_DOCIDS, /* docids only */ + DL_POSITIONS, /* docids + positions */ + DL_POSITIONS_OFFSETS /* docids + positions + offsets */ +} DocListType; + +/* +** By default, only positions and not offsets are stored in the doclists. +** To change this so that offsets are stored too, compile with +** +** -DDL_DEFAULT=DL_POSITIONS_OFFSETS +** +** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted +** into (no deletes or updates). +*/ +#ifndef DL_DEFAULT +# define DL_DEFAULT DL_POSITIONS +#endif + +enum { + POS_END = 0, /* end of this position list */ + POS_COLUMN, /* followed by new column number */ + POS_BASE +}; + +/* MERGE_COUNT controls how often we merge segments (see comment at +** top of file). +*/ +#define MERGE_COUNT 16 + +/* utility functions */ + +/* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single +** record to prevent errors of the form: +** +** my_function(SomeType *b){ +** memset(b, '\0', sizeof(b)); // sizeof(b)!=sizeof(*b) +** } +*/ +/* TODO(shess) Obvious candidates for a header file. */ +#define CLEAR(b) memset(b, '\0', sizeof(*(b))) + +#ifndef NDEBUG +# define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b))) +#else +# define SCRAMBLE(b) +#endif + +/* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */ +#define VARINT_MAX 10 + +/* Write a 64-bit variable-length integer to memory starting at p[0]. + * The length of data written will be between 1 and VARINT_MAX bytes. + * The number of bytes written is returned. */ +static int putVarint(char *p, sqlite_int64 v){ + unsigned char *q = (unsigned char *) p; + sqlite_uint64 vu = v; + do{ + *q++ = (unsigned char) ((vu & 0x7f) | 0x80); + vu >>= 7; + }while( vu!=0 ); + q[-1] &= 0x7f; /* turn off high bit in final byte */ + assert( q - (unsigned char *)p <= VARINT_MAX ); + return (int) (q - (unsigned char *)p); +} + +/* Read a 64-bit variable-length integer from memory starting at p[0]. + * Return the number of bytes read, or 0 on error. + * The value is stored in *v. */ +static int getVarint(const char *p, sqlite_int64 *v){ + const unsigned char *q = (const unsigned char *) p; + sqlite_uint64 x = 0, y = 1; + while( (*q & 0x80) == 0x80 ){ + x += y * (*q++ & 0x7f); + y <<= 7; + if( q - (unsigned char *)p >= VARINT_MAX ){ /* bad data */ + assert( 0 ); + return 0; + } + } + x += y * (*q++); + *v = (sqlite_int64) x; + return (int) (q - (unsigned char *)p); +} + +static int getVarint32(const char *p, int *pi){ + sqlite_int64 i; + int ret = getVarint(p, &i); + *pi = (int) i; + assert( *pi==i ); + return ret; +} + +/*******************************************************************/ +/* DataBuffer is used to collect data into a buffer in piecemeal +** fashion. It implements the usual distinction between amount of +** data currently stored (nData) and buffer capacity (nCapacity). +** +** dataBufferInit - create a buffer with given initial capacity. +** dataBufferReset - forget buffer's data, retaining capacity. +** dataBufferDestroy - free buffer's data. +** dataBufferSwap - swap contents of two buffers. +** dataBufferExpand - expand capacity without adding data. +** dataBufferAppend - append data. +** dataBufferAppend2 - append two pieces of data at once. +** dataBufferReplace - replace buffer's data. +*/ +typedef struct DataBuffer { + char *pData; /* Pointer to malloc'ed buffer. */ + int nCapacity; /* Size of pData buffer. */ + int nData; /* End of data loaded into pData. */ +} DataBuffer; + +static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){ + assert( nCapacity>=0 ); + pBuffer->nData = 0; + pBuffer->nCapacity = nCapacity; + pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity); +} +static void dataBufferReset(DataBuffer *pBuffer){ + pBuffer->nData = 0; +} +static void dataBufferDestroy(DataBuffer *pBuffer){ + if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData); + SCRAMBLE(pBuffer); +} +static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){ + DataBuffer tmp = *pBuffer1; + *pBuffer1 = *pBuffer2; + *pBuffer2 = tmp; +} +static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){ + assert( nAddCapacity>0 ); + /* TODO(shess) Consider expanding more aggressively. Note that the + ** underlying malloc implementation may take care of such things for + ** us already. + */ + if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){ + pBuffer->nCapacity = pBuffer->nData+nAddCapacity; + pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity); + } +} +static void dataBufferAppend(DataBuffer *pBuffer, + const char *pSource, int nSource){ + assert( nSource>0 && pSource!=NULL ); + dataBufferExpand(pBuffer, nSource); + memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource); + pBuffer->nData += nSource; +} +static void dataBufferAppend2(DataBuffer *pBuffer, + const char *pSource1, int nSource1, + const char *pSource2, int nSource2){ + assert( nSource1>0 && pSource1!=NULL ); + assert( nSource2>0 && pSource2!=NULL ); + dataBufferExpand(pBuffer, nSource1+nSource2); + memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1); + memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2); + pBuffer->nData += nSource1+nSource2; +} +static void dataBufferReplace(DataBuffer *pBuffer, + const char *pSource, int nSource){ + dataBufferReset(pBuffer); + dataBufferAppend(pBuffer, pSource, nSource); +} + +/* StringBuffer is a null-terminated version of DataBuffer. */ +typedef struct StringBuffer { + DataBuffer b; /* Includes null terminator. */ +} StringBuffer; + +static void initStringBuffer(StringBuffer *sb){ + dataBufferInit(&sb->b, 100); + dataBufferReplace(&sb->b, "", 1); +} +static int stringBufferLength(StringBuffer *sb){ + return sb->b.nData-1; +} +static char *stringBufferData(StringBuffer *sb){ + return sb->b.pData; +} +static void stringBufferDestroy(StringBuffer *sb){ + dataBufferDestroy(&sb->b); +} + +static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){ + assert( sb->b.nData>0 ); + if( nFrom>0 ){ + sb->b.nData--; + dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1); + } +} +static void append(StringBuffer *sb, const char *zFrom){ + nappend(sb, zFrom, strlen(zFrom)); +} + +/* Append a list of strings separated by commas. */ +static void appendList(StringBuffer *sb, int nString, char **azString){ + int i; + for(i=0; i0 ) append(sb, ", "); + append(sb, azString[i]); + } +} + +static int endsInWhiteSpace(StringBuffer *p){ + return stringBufferLength(p)>0 && + safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]); +} + +/* If the StringBuffer ends in something other than white space, add a +** single space character to the end. +*/ +static void appendWhiteSpace(StringBuffer *p){ + if( stringBufferLength(p)==0 ) return; + if( !endsInWhiteSpace(p) ) append(p, " "); +} + +/* Remove white space from the end of the StringBuffer */ +static void trimWhiteSpace(StringBuffer *p){ + while( endsInWhiteSpace(p) ){ + p->b.pData[--p->b.nData-1] = '\0'; + } +} + +/*******************************************************************/ +/* DLReader is used to read document elements from a doclist. The +** current docid is cached, so dlrDocid() is fast. DLReader does not +** own the doclist buffer. +** +** dlrAtEnd - true if there's no more data to read. +** dlrDocid - docid of current document. +** dlrDocData - doclist data for current document (including docid). +** dlrDocDataBytes - length of same. +** dlrAllDataBytes - length of all remaining data. +** dlrPosData - position data for current document. +** dlrPosDataLen - length of pos data for current document (incl POS_END). +** dlrStep - step to current document. +** dlrInit - initial for doclist of given type against given data. +** dlrDestroy - clean up. +** +** Expected usage is something like: +** +** DLReader reader; +** dlrInit(&reader, pData, nData); +** while( !dlrAtEnd(&reader) ){ +** // calls to dlrDocid() and kin. +** dlrStep(&reader); +** } +** dlrDestroy(&reader); +*/ +typedef struct DLReader { + DocListType iType; + const char *pData; + int nData; + + sqlite_int64 iDocid; + int nElement; +} DLReader; + +static int dlrAtEnd(DLReader *pReader){ + assert( pReader->nData>=0 ); + return pReader->nData==0; +} +static sqlite_int64 dlrDocid(DLReader *pReader){ + assert( !dlrAtEnd(pReader) ); + return pReader->iDocid; +} +static const char *dlrDocData(DLReader *pReader){ + assert( !dlrAtEnd(pReader) ); + return pReader->pData; +} +static int dlrDocDataBytes(DLReader *pReader){ + assert( !dlrAtEnd(pReader) ); + return pReader->nElement; +} +static int dlrAllDataBytes(DLReader *pReader){ + assert( !dlrAtEnd(pReader) ); + return pReader->nData; +} +/* TODO(shess) Consider adding a field to track iDocid varint length +** to make these two functions faster. This might matter (a tiny bit) +** for queries. +*/ +static const char *dlrPosData(DLReader *pReader){ + sqlite_int64 iDummy; + int n = getVarint(pReader->pData, &iDummy); + assert( !dlrAtEnd(pReader) ); + return pReader->pData+n; +} +static int dlrPosDataLen(DLReader *pReader){ + sqlite_int64 iDummy; + int n = getVarint(pReader->pData, &iDummy); + assert( !dlrAtEnd(pReader) ); + return pReader->nElement-n; +} +static void dlrStep(DLReader *pReader){ + assert( !dlrAtEnd(pReader) ); + + /* Skip past current doclist element. */ + assert( pReader->nElement<=pReader->nData ); + pReader->pData += pReader->nElement; + pReader->nData -= pReader->nElement; + + /* If there is more data, read the next doclist element. */ + if( pReader->nData!=0 ){ + sqlite_int64 iDocidDelta; + int iDummy, n = getVarint(pReader->pData, &iDocidDelta); + pReader->iDocid += iDocidDelta; + if( pReader->iType>=DL_POSITIONS ){ + assert( nnData ); + while( 1 ){ + n += getVarint32(pReader->pData+n, &iDummy); + assert( n<=pReader->nData ); + if( iDummy==POS_END ) break; + if( iDummy==POS_COLUMN ){ + n += getVarint32(pReader->pData+n, &iDummy); + assert( nnData ); + }else if( pReader->iType==DL_POSITIONS_OFFSETS ){ + n += getVarint32(pReader->pData+n, &iDummy); + n += getVarint32(pReader->pData+n, &iDummy); + assert( nnData ); + } + } + } + pReader->nElement = n; + assert( pReader->nElement<=pReader->nData ); + } +} +static void dlrInit(DLReader *pReader, DocListType iType, + const char *pData, int nData){ + assert( pData!=NULL && nData!=0 ); + pReader->iType = iType; + pReader->pData = pData; + pReader->nData = nData; + pReader->nElement = 0; + pReader->iDocid = 0; + + /* Load the first element's data. There must be a first element. */ + dlrStep(pReader); +} +static void dlrDestroy(DLReader *pReader){ + SCRAMBLE(pReader); +} + +#ifndef NDEBUG +/* Verify that the doclist can be validly decoded. Also returns the +** last docid found because it is convenient in other assertions for +** DLWriter. +*/ +static void docListValidate(DocListType iType, const char *pData, int nData, + sqlite_int64 *pLastDocid){ + sqlite_int64 iPrevDocid = 0; + assert( nData>0 ); + assert( pData!=0 ); + assert( pData+nData>pData ); + while( nData!=0 ){ + sqlite_int64 iDocidDelta; + int n = getVarint(pData, &iDocidDelta); + iPrevDocid += iDocidDelta; + if( iType>DL_DOCIDS ){ + int iDummy; + while( 1 ){ + n += getVarint32(pData+n, &iDummy); + if( iDummy==POS_END ) break; + if( iDummy==POS_COLUMN ){ + n += getVarint32(pData+n, &iDummy); + }else if( iType>DL_POSITIONS ){ + n += getVarint32(pData+n, &iDummy); + n += getVarint32(pData+n, &iDummy); + } + assert( n<=nData ); + } + } + assert( n<=nData ); + pData += n; + nData -= n; + } + if( pLastDocid ) *pLastDocid = iPrevDocid; +} +#define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o) +#else +#define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 ) +#endif + +/*******************************************************************/ +/* DLWriter is used to write doclist data to a DataBuffer. DLWriter +** always appends to the buffer and does not own it. +** +** dlwInit - initialize to write a given type doclistto a buffer. +** dlwDestroy - clear the writer's memory. Does not free buffer. +** dlwAppend - append raw doclist data to buffer. +** dlwCopy - copy next doclist from reader to writer. +** dlwAdd - construct doclist element and append to buffer. +** Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter). +*/ +typedef struct DLWriter { + DocListType iType; + DataBuffer *b; + sqlite_int64 iPrevDocid; +#ifndef NDEBUG + int has_iPrevDocid; +#endif +} DLWriter; + +static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){ + pWriter->b = b; + pWriter->iType = iType; + pWriter->iPrevDocid = 0; +#ifndef NDEBUG + pWriter->has_iPrevDocid = 0; +#endif +} +static void dlwDestroy(DLWriter *pWriter){ + SCRAMBLE(pWriter); +} +/* iFirstDocid is the first docid in the doclist in pData. It is +** needed because pData may point within a larger doclist, in which +** case the first item would be delta-encoded. +** +** iLastDocid is the final docid in the doclist in pData. It is +** needed to create the new iPrevDocid for future delta-encoding. The +** code could decode the passed doclist to recreate iLastDocid, but +** the only current user (docListMerge) already has decoded this +** information. +*/ +/* TODO(shess) This has become just a helper for docListMerge. +** Consider a refactor to make this cleaner. +*/ +static void dlwAppend(DLWriter *pWriter, + const char *pData, int nData, + sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){ + sqlite_int64 iDocid = 0; + char c[VARINT_MAX]; + int nFirstOld, nFirstNew; /* Old and new varint len of first docid. */ +#ifndef NDEBUG + sqlite_int64 iLastDocidDelta; +#endif + + /* Recode the initial docid as delta from iPrevDocid. */ + nFirstOld = getVarint(pData, &iDocid); + assert( nFirstOldiType==DL_DOCIDS) ); + nFirstNew = putVarint(c, iFirstDocid-pWriter->iPrevDocid); + + /* Verify that the incoming doclist is valid AND that it ends with + ** the expected docid. This is essential because we'll trust this + ** docid in future delta-encoding. + */ + ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta); + assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta ); + + /* Append recoded initial docid and everything else. Rest of docids + ** should have been delta-encoded from previous initial docid. + */ + if( nFirstOldb, c, nFirstNew, + pData+nFirstOld, nData-nFirstOld); + }else{ + dataBufferAppend(pWriter->b, c, nFirstNew); + } + pWriter->iPrevDocid = iLastDocid; +} +static void dlwCopy(DLWriter *pWriter, DLReader *pReader){ + dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader), + dlrDocid(pReader), dlrDocid(pReader)); +} +static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){ + char c[VARINT_MAX]; + int n = putVarint(c, iDocid-pWriter->iPrevDocid); + + /* Docids must ascend. */ + assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid ); + assert( pWriter->iType==DL_DOCIDS ); + + dataBufferAppend(pWriter->b, c, n); + pWriter->iPrevDocid = iDocid; +#ifndef NDEBUG + pWriter->has_iPrevDocid = 1; +#endif +} + +/*******************************************************************/ +/* PLReader is used to read data from a document's position list. As +** the caller steps through the list, data is cached so that varints +** only need to be decoded once. +** +** plrInit, plrDestroy - create/destroy a reader. +** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors +** plrAtEnd - at end of stream, only call plrDestroy once true. +** plrStep - step to the next element. +*/ +typedef struct PLReader { + /* These refer to the next position's data. nData will reach 0 when + ** reading the last position, so plrStep() signals EOF by setting + ** pData to NULL. + */ + const char *pData; + int nData; + + DocListType iType; + int iColumn; /* the last column read */ + int iPosition; /* the last position read */ + int iStartOffset; /* the last start offset read */ + int iEndOffset; /* the last end offset read */ +} PLReader; + +static int plrAtEnd(PLReader *pReader){ + return pReader->pData==NULL; +} +static int plrColumn(PLReader *pReader){ + assert( !plrAtEnd(pReader) ); + return pReader->iColumn; +} +static int plrPosition(PLReader *pReader){ + assert( !plrAtEnd(pReader) ); + return pReader->iPosition; +} +static int plrStartOffset(PLReader *pReader){ + assert( !plrAtEnd(pReader) ); + return pReader->iStartOffset; +} +static int plrEndOffset(PLReader *pReader){ + assert( !plrAtEnd(pReader) ); + return pReader->iEndOffset; +} +static void plrStep(PLReader *pReader){ + int i, n; + + assert( !plrAtEnd(pReader) ); + + if( pReader->nData==0 ){ + pReader->pData = NULL; + return; + } + + n = getVarint32(pReader->pData, &i); + if( i==POS_COLUMN ){ + n += getVarint32(pReader->pData+n, &pReader->iColumn); + pReader->iPosition = 0; + pReader->iStartOffset = 0; + n += getVarint32(pReader->pData+n, &i); + } + /* Should never see adjacent column changes. */ + assert( i!=POS_COLUMN ); + + if( i==POS_END ){ + pReader->nData = 0; + pReader->pData = NULL; + return; + } + + pReader->iPosition += i-POS_BASE; + if( pReader->iType==DL_POSITIONS_OFFSETS ){ + n += getVarint32(pReader->pData+n, &i); + pReader->iStartOffset += i; + n += getVarint32(pReader->pData+n, &i); + pReader->iEndOffset = pReader->iStartOffset+i; + } + assert( n<=pReader->nData ); + pReader->pData += n; + pReader->nData -= n; +} + +static void plrInit(PLReader *pReader, DLReader *pDLReader){ + pReader->pData = dlrPosData(pDLReader); + pReader->nData = dlrPosDataLen(pDLReader); + pReader->iType = pDLReader->iType; + pReader->iColumn = 0; + pReader->iPosition = 0; + pReader->iStartOffset = 0; + pReader->iEndOffset = 0; + plrStep(pReader); +} +static void plrDestroy(PLReader *pReader){ + SCRAMBLE(pReader); +} + +/*******************************************************************/ +/* PLWriter is used in constructing a document's position list. As a +** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op. +** PLWriter writes to the associated DLWriter's buffer. +** +** plwInit - init for writing a document's poslist. +** plwDestroy - clear a writer. +** plwAdd - append position and offset information. +** plwCopy - copy next position's data from reader to writer. +** plwTerminate - add any necessary doclist terminator. +** +** Calling plwAdd() after plwTerminate() may result in a corrupt +** doclist. +*/ +/* TODO(shess) Until we've written the second item, we can cache the +** first item's information. Then we'd have three states: +** +** - initialized with docid, no positions. +** - docid and one position. +** - docid and multiple positions. +** +** Only the last state needs to actually write to dlw->b, which would +** be an improvement in the DLCollector case. +*/ +typedef struct PLWriter { + DLWriter *dlw; + + int iColumn; /* the last column written */ + int iPos; /* the last position written */ + int iOffset; /* the last start offset written */ +} PLWriter; + +/* TODO(shess) In the case where the parent is reading these values +** from a PLReader, we could optimize to a copy if that PLReader has +** the same type as pWriter. +*/ +static void plwAdd(PLWriter *pWriter, int iColumn, int iPos, + int iStartOffset, int iEndOffset){ + /* Worst-case space for POS_COLUMN, iColumn, iPosDelta, + ** iStartOffsetDelta, and iEndOffsetDelta. + */ + char c[5*VARINT_MAX]; + int n = 0; + + /* Ban plwAdd() after plwTerminate(). */ + assert( pWriter->iPos!=-1 ); + + if( pWriter->dlw->iType==DL_DOCIDS ) return; + + if( iColumn!=pWriter->iColumn ){ + n += putVarint(c+n, POS_COLUMN); + n += putVarint(c+n, iColumn); + pWriter->iColumn = iColumn; + pWriter->iPos = 0; + pWriter->iOffset = 0; + } + assert( iPos>=pWriter->iPos ); + n += putVarint(c+n, POS_BASE+(iPos-pWriter->iPos)); + pWriter->iPos = iPos; + if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){ + assert( iStartOffset>=pWriter->iOffset ); + n += putVarint(c+n, iStartOffset-pWriter->iOffset); + pWriter->iOffset = iStartOffset; + assert( iEndOffset>=iStartOffset ); + n += putVarint(c+n, iEndOffset-iStartOffset); + } + dataBufferAppend(pWriter->dlw->b, c, n); +} +static void plwCopy(PLWriter *pWriter, PLReader *pReader){ + plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader), + plrStartOffset(pReader), plrEndOffset(pReader)); +} +static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){ + char c[VARINT_MAX]; + int n; + + pWriter->dlw = dlw; + + /* Docids must ascend. */ + assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid ); + n = putVarint(c, iDocid-pWriter->dlw->iPrevDocid); + dataBufferAppend(pWriter->dlw->b, c, n); + pWriter->dlw->iPrevDocid = iDocid; +#ifndef NDEBUG + pWriter->dlw->has_iPrevDocid = 1; +#endif + + pWriter->iColumn = 0; + pWriter->iPos = 0; + pWriter->iOffset = 0; +} +/* TODO(shess) Should plwDestroy() also terminate the doclist? But +** then plwDestroy() would no longer be just a destructor, it would +** also be doing work, which isn't consistent with the overall idiom. +** Another option would be for plwAdd() to always append any necessary +** terminator, so that the output is always correct. But that would +** add incremental work to the common case with the only benefit being +** API elegance. Punt for now. +*/ +static void plwTerminate(PLWriter *pWriter){ + if( pWriter->dlw->iType>DL_DOCIDS ){ + char c[VARINT_MAX]; + int n = putVarint(c, POS_END); + dataBufferAppend(pWriter->dlw->b, c, n); + } +#ifndef NDEBUG + /* Mark as terminated for assert in plwAdd(). */ + pWriter->iPos = -1; +#endif +} +static void plwDestroy(PLWriter *pWriter){ + SCRAMBLE(pWriter); +} + +/*******************************************************************/ +/* DLCollector wraps PLWriter and DLWriter to provide a +** dynamically-allocated doclist area to use during tokenization. +** +** dlcNew - malloc up and initialize a collector. +** dlcDelete - destroy a collector and all contained items. +** dlcAddPos - append position and offset information. +** dlcAddDoclist - add the collected doclist to the given buffer. +** dlcNext - terminate the current document and open another. +*/ +typedef struct DLCollector { + DataBuffer b; + DLWriter dlw; + PLWriter plw; +} DLCollector; + +/* TODO(shess) This could also be done by calling plwTerminate() and +** dataBufferAppend(). I tried that, expecting nominal performance +** differences, but it seemed to pretty reliably be worth 1% to code +** it this way. I suspect it is the incremental malloc overhead (some +** percentage of the plwTerminate() calls will cause a realloc), so +** this might be worth revisiting if the DataBuffer implementation +** changes. +*/ +static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){ + if( pCollector->dlw.iType>DL_DOCIDS ){ + char c[VARINT_MAX]; + int n = putVarint(c, POS_END); + dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n); + }else{ + dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData); + } +} +static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){ + plwTerminate(&pCollector->plw); + plwDestroy(&pCollector->plw); + plwInit(&pCollector->plw, &pCollector->dlw, iDocid); +} +static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos, + int iStartOffset, int iEndOffset){ + plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset); +} + +static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){ + DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector)); + dataBufferInit(&pCollector->b, 0); + dlwInit(&pCollector->dlw, iType, &pCollector->b); + plwInit(&pCollector->plw, &pCollector->dlw, iDocid); + return pCollector; +} +static void dlcDelete(DLCollector *pCollector){ + plwDestroy(&pCollector->plw); + dlwDestroy(&pCollector->dlw); + dataBufferDestroy(&pCollector->b); + SCRAMBLE(pCollector); + sqlite3_free(pCollector); +} + + +/* Copy the doclist data of iType in pData/nData into *out, trimming +** unnecessary data as we go. Only columns matching iColumn are +** copied, all columns copied if iColumn is -1. Elements with no +** matching columns are dropped. The output is an iOutType doclist. +*/ +/* NOTE(shess) This code is only valid after all doclists are merged. +** If this is run before merges, then doclist items which represent +** deletion will be trimmed, and will thus not effect a deletion +** during the merge. +*/ +static void docListTrim(DocListType iType, const char *pData, int nData, + int iColumn, DocListType iOutType, DataBuffer *out){ + DLReader dlReader; + DLWriter dlWriter; + + assert( iOutType<=iType ); + + dlrInit(&dlReader, iType, pData, nData); + dlwInit(&dlWriter, iOutType, out); + + while( !dlrAtEnd(&dlReader) ){ + PLReader plReader; + PLWriter plWriter; + int match = 0; + + plrInit(&plReader, &dlReader); + + while( !plrAtEnd(&plReader) ){ + if( iColumn==-1 || plrColumn(&plReader)==iColumn ){ + if( !match ){ + plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader)); + match = 1; + } + plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader), + plrStartOffset(&plReader), plrEndOffset(&plReader)); + } + plrStep(&plReader); + } + if( match ){ + plwTerminate(&plWriter); + plwDestroy(&plWriter); + } + + plrDestroy(&plReader); + dlrStep(&dlReader); + } + dlwDestroy(&dlWriter); + dlrDestroy(&dlReader); +} + +/* Used by docListMerge() to keep doclists in the ascending order by +** docid, then ascending order by age (so the newest comes first). +*/ +typedef struct OrderedDLReader { + DLReader *pReader; + + /* TODO(shess) If we assume that docListMerge pReaders is ordered by + ** age (which we do), then we could use pReader comparisons to break + ** ties. + */ + int idx; +} OrderedDLReader; + +/* Order eof to end, then by docid asc, idx desc. */ +static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){ + if( dlrAtEnd(r1->pReader) ){ + if( dlrAtEnd(r2->pReader) ) return 0; /* Both atEnd(). */ + return 1; /* Only r1 atEnd(). */ + } + if( dlrAtEnd(r2->pReader) ) return -1; /* Only r2 atEnd(). */ + + if( dlrDocid(r1->pReader)pReader) ) return -1; + if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1; + + /* Descending on idx. */ + return r2->idx-r1->idx; +} + +/* Bubble p[0] to appropriate place in p[1..n-1]. Assumes that +** p[1..n-1] is already sorted. +*/ +/* TODO(shess) Is this frequent enough to warrant a binary search? +** Before implementing that, instrument the code to check. In most +** current usage, I expect that p[0] will be less than p[1] a very +** high proportion of the time. +*/ +static void orderedDLReaderReorder(OrderedDLReader *p, int n){ + while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){ + OrderedDLReader tmp = p[0]; + p[0] = p[1]; + p[1] = tmp; + n--; + p++; + } +} + +/* Given an array of doclist readers, merge their doclist elements +** into out in sorted order (by docid), dropping elements from older +** readers when there is a duplicate docid. pReaders is assumed to be +** ordered by age, oldest first. +*/ +/* TODO(shess) nReaders must be <= MERGE_COUNT. This should probably +** be fixed. +*/ +static void docListMerge(DataBuffer *out, + DLReader *pReaders, int nReaders){ + OrderedDLReader readers[MERGE_COUNT]; + DLWriter writer; + int i, n; + const char *pStart = 0; + int nStart = 0; + sqlite_int64 iFirstDocid = 0, iLastDocid = 0; + + assert( nReaders>0 ); + if( nReaders==1 ){ + dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders)); + return; + } + + assert( nReaders<=MERGE_COUNT ); + n = 0; + for(i=0; i0 ){ + orderedDLReaderReorder(readers+i, nReaders-i); + } + + dlwInit(&writer, pReaders[0].iType, out); + while( !dlrAtEnd(readers[0].pReader) ){ + sqlite_int64 iDocid = dlrDocid(readers[0].pReader); + + /* If this is a continuation of the current buffer to copy, extend + ** that buffer. memcpy() seems to be more efficient if it has a + ** lots of data to copy. + */ + if( dlrDocData(readers[0].pReader)==pStart+nStart ){ + nStart += dlrDocDataBytes(readers[0].pReader); + }else{ + if( pStart!=0 ){ + dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid); + } + pStart = dlrDocData(readers[0].pReader); + nStart = dlrDocDataBytes(readers[0].pReader); + iFirstDocid = iDocid; + } + iLastDocid = iDocid; + dlrStep(readers[0].pReader); + + /* Drop all of the older elements with the same docid. */ + for(i=1; i0 ){ + orderedDLReaderReorder(readers+i, nReaders-i); + } + } + + /* Copy over any remaining elements. */ + if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid); + dlwDestroy(&writer); +} + +/* Helper function for posListUnion(). Compares the current position +** between left and right, returning as standard C idiom of <0 if +** left0 if left>right, and 0 if left==right. "End" always +** compares greater. +*/ +static int posListCmp(PLReader *pLeft, PLReader *pRight){ + assert( pLeft->iType==pRight->iType ); + if( pLeft->iType==DL_DOCIDS ) return 0; + + if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1; + if( plrAtEnd(pRight) ) return -1; + + if( plrColumn(pLeft)plrColumn(pRight) ) return 1; + + if( plrPosition(pLeft)plrPosition(pRight) ) return 1; + if( pLeft->iType==DL_POSITIONS ) return 0; + + if( plrStartOffset(pLeft)plrStartOffset(pRight) ) return 1; + + if( plrEndOffset(pLeft)plrEndOffset(pRight) ) return 1; + + return 0; +} + +/* Write the union of position lists in pLeft and pRight to pOut. +** "Union" in this case meaning "All unique position tuples". Should +** work with any doclist type, though both inputs and the output +** should be the same type. +*/ +static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){ + PLReader left, right; + PLWriter writer; + + assert( dlrDocid(pLeft)==dlrDocid(pRight) ); + assert( pLeft->iType==pRight->iType ); + assert( pLeft->iType==pOut->iType ); + + plrInit(&left, pLeft); + plrInit(&right, pRight); + plwInit(&writer, pOut, dlrDocid(pLeft)); + + while( !plrAtEnd(&left) || !plrAtEnd(&right) ){ + int c = posListCmp(&left, &right); + if( c<0 ){ + plwCopy(&writer, &left); + plrStep(&left); + }else if( c>0 ){ + plwCopy(&writer, &right); + plrStep(&right); + }else{ + plwCopy(&writer, &left); + plrStep(&left); + plrStep(&right); + } + } + + plwTerminate(&writer); + plwDestroy(&writer); + plrDestroy(&left); + plrDestroy(&right); +} + +/* Write the union of doclists in pLeft and pRight to pOut. For +** docids in common between the inputs, the union of the position +** lists is written. Inputs and outputs are always type DL_DEFAULT. +*/ +static void docListUnion( + const char *pLeft, int nLeft, + const char *pRight, int nRight, + DataBuffer *pOut /* Write the combined doclist here */ +){ + DLReader left, right; + DLWriter writer; + + if( nLeft==0 ){ + if( nRight!=0) dataBufferAppend(pOut, pRight, nRight); + return; + } + if( nRight==0 ){ + dataBufferAppend(pOut, pLeft, nLeft); + return; + } + + dlrInit(&left, DL_DEFAULT, pLeft, nLeft); + dlrInit(&right, DL_DEFAULT, pRight, nRight); + dlwInit(&writer, DL_DEFAULT, pOut); + + while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){ + if( dlrAtEnd(&right) ){ + dlwCopy(&writer, &left); + dlrStep(&left); + }else if( dlrAtEnd(&left) ){ + dlwCopy(&writer, &right); + dlrStep(&right); + }else if( dlrDocid(&left)dlrDocid(&right) ){ + dlwCopy(&writer, &right); + dlrStep(&right); + }else{ + posListUnion(&left, &right, &writer); + dlrStep(&left); + dlrStep(&right); + } + } + + dlrDestroy(&left); + dlrDestroy(&right); + dlwDestroy(&writer); +} + +/* pLeft and pRight are DLReaders positioned to the same docid. +** +** If there are no instances in pLeft or pRight where the position +** of pLeft is one less than the position of pRight, then this +** routine adds nothing to pOut. +** +** If there are one or more instances where positions from pLeft +** are exactly one less than positions from pRight, then add a new +** document record to pOut. If pOut wants to hold positions, then +** include the positions from pRight that are one more than a +** position in pLeft. In other words: pRight.iPos==pLeft.iPos+1. +*/ +static void posListPhraseMerge(DLReader *pLeft, DLReader *pRight, + DLWriter *pOut){ + PLReader left, right; + PLWriter writer; + int match = 0; + + assert( dlrDocid(pLeft)==dlrDocid(pRight) ); + assert( pOut->iType!=DL_POSITIONS_OFFSETS ); + + plrInit(&left, pLeft); + plrInit(&right, pRight); + + while( !plrAtEnd(&left) && !plrAtEnd(&right) ){ + if( plrColumn(&left)plrColumn(&right) ){ + plrStep(&right); + }else if( plrPosition(&left)+1plrPosition(&right) ){ + plrStep(&right); + }else{ + if( !match ){ + plwInit(&writer, pOut, dlrDocid(pLeft)); + match = 1; + } + plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0); + plrStep(&left); + plrStep(&right); + } + } + + if( match ){ + plwTerminate(&writer); + plwDestroy(&writer); + } + + plrDestroy(&left); + plrDestroy(&right); +} + +/* We have two doclists with positions: pLeft and pRight. +** Write the phrase intersection of these two doclists into pOut. +** +** A phrase intersection means that two documents only match +** if pLeft.iPos+1==pRight.iPos. +** +** iType controls the type of data written to pOut. If iType is +** DL_POSITIONS, the positions are those from pRight. +*/ +static void docListPhraseMerge( + const char *pLeft, int nLeft, + const char *pRight, int nRight, + DocListType iType, + DataBuffer *pOut /* Write the combined doclist here */ +){ + DLReader left, right; + DLWriter writer; + + if( nLeft==0 || nRight==0 ) return; + + assert( iType!=DL_POSITIONS_OFFSETS ); + + dlrInit(&left, DL_POSITIONS, pLeft, nLeft); + dlrInit(&right, DL_POSITIONS, pRight, nRight); + dlwInit(&writer, iType, pOut); + + while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){ + if( dlrDocid(&left) one AND (two OR three) + * [one OR two three] ==> (one OR two) AND three + * + * A "-" before a term matches all entries that lack that term. + * The "-" must occur immediately before the term with in intervening + * space. This is how the search engines do it. + * + * A NOT term cannot be the right-hand operand of an OR. If this + * occurs in the query string, the NOT is ignored: + * + * [one OR -two] ==> one OR two + * + */ +typedef struct Query { + fulltext_vtab *pFts; /* The full text index */ + int nTerms; /* Number of terms in the query */ + QueryTerm *pTerms; /* Array of terms. Space obtained from malloc() */ + int nextIsOr; /* Set the isOr flag on the next inserted term */ + int nextColumn; /* Next word parsed must be in this column */ + int dfltColumn; /* The default column */ +} Query; + + +/* +** An instance of the following structure keeps track of generated +** matching-word offset information and snippets. +*/ +typedef struct Snippet { + int nMatch; /* Total number of matches */ + int nAlloc; /* Space allocated for aMatch[] */ + struct snippetMatch { /* One entry for each matching term */ + char snStatus; /* Status flag for use while constructing snippets */ + short int iCol; /* The column that contains the match */ + short int iTerm; /* The index in Query.pTerms[] of the matching term */ + short int nByte; /* Number of bytes in the term */ + int iStart; /* The offset to the first character of the term */ + } *aMatch; /* Points to space obtained from malloc */ + char *zOffset; /* Text rendering of aMatch[] */ + int nOffset; /* strlen(zOffset) */ + char *zSnippet; /* Snippet text */ + int nSnippet; /* strlen(zSnippet) */ +} Snippet; + + +typedef enum QueryType { + QUERY_GENERIC, /* table scan */ + QUERY_ROWID, /* lookup by rowid */ + QUERY_FULLTEXT /* QUERY_FULLTEXT + [i] is a full-text search for column i*/ +} QueryType; + +typedef enum fulltext_statement { + CONTENT_INSERT_STMT, + CONTENT_SELECT_STMT, + CONTENT_UPDATE_STMT, + CONTENT_DELETE_STMT, + CONTENT_EXISTS_STMT, + + BLOCK_INSERT_STMT, + BLOCK_SELECT_STMT, + BLOCK_DELETE_STMT, + BLOCK_DELETE_ALL_STMT, + + SEGDIR_MAX_INDEX_STMT, + SEGDIR_SET_STMT, + SEGDIR_SELECT_LEVEL_STMT, + SEGDIR_SPAN_STMT, + SEGDIR_DELETE_STMT, + SEGDIR_SELECT_SEGMENT_STMT, + SEGDIR_SELECT_ALL_STMT, + SEGDIR_DELETE_ALL_STMT, + SEGDIR_COUNT_STMT, + + MAX_STMT /* Always at end! */ +} fulltext_statement; + +/* These must exactly match the enum above. */ +/* TODO(shess): Is there some risk that a statement will be used in two +** cursors at once, e.g. if a query joins a virtual table to itself? +** If so perhaps we should move some of these to the cursor object. +*/ +static const char *const fulltext_zStatement[MAX_STMT] = { + /* CONTENT_INSERT */ NULL, /* generated in contentInsertStatement() */ + /* CONTENT_SELECT */ "select * from %_content where rowid = ?", + /* CONTENT_UPDATE */ NULL, /* generated in contentUpdateStatement() */ + /* CONTENT_DELETE */ "delete from %_content where rowid = ?", + /* CONTENT_EXISTS */ "select rowid from %_content limit 1", + + /* BLOCK_INSERT */ "insert into %_segments values (?)", + /* BLOCK_SELECT */ "select block from %_segments where rowid = ?", + /* BLOCK_DELETE */ "delete from %_segments where rowid between ? and ?", + /* BLOCK_DELETE_ALL */ "delete from %_segments", + + /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?", + /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)", + /* SEGDIR_SELECT_LEVEL */ + "select start_block, leaves_end_block, root from %_segdir " + " where level = ? order by idx", + /* SEGDIR_SPAN */ + "select min(start_block), max(end_block) from %_segdir " + " where level = ? and start_block <> 0", + /* SEGDIR_DELETE */ "delete from %_segdir where level = ?", + + /* NOTE(shess): The first three results of the following two + ** statements must match. + */ + /* SEGDIR_SELECT_SEGMENT */ + "select start_block, leaves_end_block, root from %_segdir " + " where level = ? and idx = ?", + /* SEGDIR_SELECT_ALL */ + "select start_block, leaves_end_block, root from %_segdir " + " order by level desc, idx asc", + /* SEGDIR_DELETE_ALL */ "delete from %_segdir", + /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir", +}; + +/* +** A connection to a fulltext index is an instance of the following +** structure. The xCreate and xConnect methods create an instance +** of this structure and xDestroy and xDisconnect free that instance. +** All other methods receive a pointer to the structure as one of their +** arguments. +*/ +struct fulltext_vtab { + sqlite3_vtab base; /* Base class used by SQLite core */ + sqlite3 *db; /* The database connection */ + const char *zDb; /* logical database name */ + const char *zName; /* virtual table name */ + int nColumn; /* number of columns in virtual table */ + char **azColumn; /* column names. malloced */ + char **azContentColumn; /* column names in content table; malloced */ + sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ + + /* Precompiled statements which we keep as long as the table is + ** open. + */ + sqlite3_stmt *pFulltextStatements[MAX_STMT]; + + /* Precompiled statements used for segment merges. We run a + ** separate select across the leaf level of each tree being merged. + */ + sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT]; + /* The statement used to prepare pLeafSelectStmts. */ +#define LEAF_SELECT \ + "select block from %_segments where rowid between ? and ? order by rowid" + + /* These buffer pending index updates during transactions. + ** nPendingData estimates the memory size of the pending data. It + ** doesn't include the hash-bucket overhead, nor any malloc + ** overhead. When nPendingData exceeds kPendingThreshold, the + ** buffer is flushed even before the transaction closes. + ** pendingTerms stores the data, and is only valid when nPendingData + ** is >=0 (nPendingData<0 means pendingTerms has not been + ** initialized). iPrevDocid is the last docid written, used to make + ** certain we're inserting in sorted order. + */ + int nPendingData; +#define kPendingThreshold (1*1024*1024) + sqlite_int64 iPrevDocid; + fts2Hash pendingTerms; +}; + +/* +** When the core wants to do a query, it create a cursor using a +** call to xOpen. This structure is an instance of a cursor. It +** is destroyed by xClose. +*/ +typedef struct fulltext_cursor { + sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + QueryType iCursorType; /* Copy of sqlite3_index_info.idxNum */ + sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ + int eof; /* True if at End Of Results */ + Query q; /* Parsed query string */ + Snippet snippet; /* Cached snippet for the current row */ + int iColumn; /* Column being searched */ + DataBuffer result; /* Doclist results from fulltextQuery */ + DLReader reader; /* Result reader if result not empty */ +} fulltext_cursor; + +static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){ + return (fulltext_vtab *) c->base.pVtab; +} + +static const sqlite3_module fts2Module; /* forward declaration */ + +/* Return a dynamically generated statement of the form + * insert into %_content (rowid, ...) values (?, ...) + */ +static const char *contentInsertStatement(fulltext_vtab *v){ + StringBuffer sb; + int i; + + initStringBuffer(&sb); + append(&sb, "insert into %_content (rowid, "); + appendList(&sb, v->nColumn, v->azContentColumn); + append(&sb, ") values (?"); + for(i=0; inColumn; ++i) + append(&sb, ", ?"); + append(&sb, ")"); + return stringBufferData(&sb); +} + +/* Return a dynamically generated statement of the form + * update %_content set [col_0] = ?, [col_1] = ?, ... + * where rowid = ? + */ +static const char *contentUpdateStatement(fulltext_vtab *v){ + StringBuffer sb; + int i; + + initStringBuffer(&sb); + append(&sb, "update %_content set "); + for(i=0; inColumn; ++i) { + if( i>0 ){ + append(&sb, ", "); + } + append(&sb, v->azContentColumn[i]); + append(&sb, " = ?"); + } + append(&sb, " where rowid = ?"); + return stringBufferData(&sb); +} + +/* Puts a freshly-prepared statement determined by iStmt in *ppStmt. +** If the indicated statement has never been prepared, it is prepared +** and cached, otherwise the cached version is reset. +*/ +static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt, + sqlite3_stmt **ppStmt){ + assert( iStmtpFulltextStatements[iStmt]==NULL ){ + const char *zStmt; + int rc; + switch( iStmt ){ + case CONTENT_INSERT_STMT: + zStmt = contentInsertStatement(v); break; + case CONTENT_UPDATE_STMT: + zStmt = contentUpdateStatement(v); break; + default: + zStmt = fulltext_zStatement[iStmt]; + } + rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt], + zStmt); + if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt); + if( rc!=SQLITE_OK ) return rc; + } else { + int rc = sqlite3_reset(v->pFulltextStatements[iStmt]); + if( rc!=SQLITE_OK ) return rc; + } + + *ppStmt = v->pFulltextStatements[iStmt]; + return SQLITE_OK; +} + +/* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and +** SQLITE_ROW to SQLITE_ERROR. Useful for statements like UPDATE, +** where we expect no results. +*/ +static int sql_single_step(sqlite3_stmt *s){ + int rc = sqlite3_step(s); + return (rc==SQLITE_DONE) ? SQLITE_OK : rc; +} + +/* Like sql_get_statement(), but for special replicated LEAF_SELECT +** statements. idx -1 is a special case for an uncached version of +** the statement (used in the optimize implementation). +*/ +/* TODO(shess) Write version for generic statements and then share +** that between the cached-statement functions. +*/ +static int sql_get_leaf_statement(fulltext_vtab *v, int idx, + sqlite3_stmt **ppStmt){ + assert( idx>=-1 && idxdb, v->zDb, v->zName, ppStmt, LEAF_SELECT); + }else if( v->pLeafSelectStmts[idx]==NULL ){ + int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx], + LEAF_SELECT); + if( rc!=SQLITE_OK ) return rc; + }else{ + int rc = sqlite3_reset(v->pLeafSelectStmts[idx]); + if( rc!=SQLITE_OK ) return rc; + } + + *ppStmt = v->pLeafSelectStmts[idx]; + return SQLITE_OK; +} + +/* insert into %_content (rowid, ...) values ([rowid], [pValues]) */ +static int content_insert(fulltext_vtab *v, sqlite3_value *rowid, + sqlite3_value **pValues){ + sqlite3_stmt *s; + int i; + int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_value(s, 1, rowid); + if( rc!=SQLITE_OK ) return rc; + + for(i=0; inColumn; ++i){ + rc = sqlite3_bind_value(s, 2+i, pValues[i]); + if( rc!=SQLITE_OK ) return rc; + } + + return sql_single_step(s); +} + +/* update %_content set col0 = pValues[0], col1 = pValues[1], ... + * where rowid = [iRowid] */ +static int content_update(fulltext_vtab *v, sqlite3_value **pValues, + sqlite_int64 iRowid){ + sqlite3_stmt *s; + int i; + int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + for(i=0; inColumn; ++i){ + rc = sqlite3_bind_value(s, 1+i, pValues[i]); + if( rc!=SQLITE_OK ) return rc; + } + + rc = sqlite3_bind_int64(s, 1+v->nColumn, iRowid); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step(s); +} + +static void freeStringArray(int nString, const char **pString){ + int i; + + for (i=0 ; i < nString ; ++i) { + if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]); + } + sqlite3_free((void *) pString); +} + +/* select * from %_content where rowid = [iRow] + * The caller must delete the returned array and all strings in it. + * null fields will be NULL in the returned array. + * + * TODO: Perhaps we should return pointer/length strings here for consistency + * with other code which uses pointer/length. */ +static int content_select(fulltext_vtab *v, sqlite_int64 iRow, + const char ***pValues){ + sqlite3_stmt *s; + const char **values; + int i; + int rc; + + *pValues = NULL; + + rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iRow); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_step(s); + if( rc!=SQLITE_ROW ) return rc; + + values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *)); + for(i=0; inColumn; ++i){ + if( sqlite3_column_type(s, i)==SQLITE_NULL ){ + values[i] = NULL; + }else{ + values[i] = string_dup((char*)sqlite3_column_text(s, i)); + } + } + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + rc = sqlite3_step(s); + if( rc==SQLITE_DONE ){ + *pValues = values; + return SQLITE_OK; + } + + freeStringArray(v->nColumn, values); + return rc; +} + +/* delete from %_content where rowid = [iRow ] */ +static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iRow); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step(s); +} + +/* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if +** no rows exist, and any error in case of failure. +*/ +static int content_exists(fulltext_vtab *v){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_step(s); + if( rc!=SQLITE_ROW ) return rc; + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + rc = sqlite3_step(s); + if( rc==SQLITE_DONE ) return SQLITE_ROW; + if( rc==SQLITE_ROW ) return SQLITE_ERROR; + return rc; +} + +/* insert into %_segments values ([pData]) +** returns assigned rowid in *piBlockid +*/ +static int block_insert(fulltext_vtab *v, const char *pData, int nData, + sqlite_int64 *piBlockid){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_step(s); + if( rc==SQLITE_ROW ) return SQLITE_ERROR; + if( rc!=SQLITE_DONE ) return rc; + + *piBlockid = sqlite3_last_insert_rowid(v->db); + return SQLITE_OK; +} + +/* delete from %_segments +** where rowid between [iStartBlockid] and [iEndBlockid] +** +** Deletes the range of blocks, inclusive, used to delete the blocks +** which form a segment. +*/ +static int block_delete(fulltext_vtab *v, + sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iStartBlockid); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 2, iEndBlockid); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step(s); +} + +/* Returns SQLITE_ROW with *pidx set to the maximum segment idx found +** at iLevel. Returns SQLITE_DONE if there are no segments at +** iLevel. Otherwise returns an error. +*/ +static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int(s, 1, iLevel); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_step(s); + /* Should always get at least one row due to how max() works. */ + if( rc==SQLITE_DONE ) return SQLITE_DONE; + if( rc!=SQLITE_ROW ) return rc; + + /* NULL means that there were no inputs to max(). */ + if( SQLITE_NULL==sqlite3_column_type(s, 0) ){ + rc = sqlite3_step(s); + if( rc==SQLITE_ROW ) return SQLITE_ERROR; + return rc; + } + + *pidx = sqlite3_column_int(s, 0); + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + rc = sqlite3_step(s); + if( rc==SQLITE_ROW ) return SQLITE_ERROR; + if( rc!=SQLITE_DONE ) return rc; + return SQLITE_ROW; +} + +/* insert into %_segdir values ( +** [iLevel], [idx], +** [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid], +** [pRootData] +** ) +*/ +static int segdir_set(fulltext_vtab *v, int iLevel, int idx, + sqlite_int64 iStartBlockid, + sqlite_int64 iLeavesEndBlockid, + sqlite_int64 iEndBlockid, + const char *pRootData, int nRootData){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int(s, 1, iLevel); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int(s, 2, idx); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 3, iStartBlockid); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 5, iEndBlockid); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step(s); +} + +/* Queries %_segdir for the block span of the segments in level +** iLevel. Returns SQLITE_DONE if there are no blocks for iLevel, +** SQLITE_ROW if there are blocks, else an error. +*/ +static int segdir_span(fulltext_vtab *v, int iLevel, + sqlite_int64 *piStartBlockid, + sqlite_int64 *piEndBlockid){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int(s, 1, iLevel); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_step(s); + if( rc==SQLITE_DONE ) return SQLITE_DONE; /* Should never happen */ + if( rc!=SQLITE_ROW ) return rc; + + /* This happens if all segments at this level are entirely inline. */ + if( SQLITE_NULL==sqlite3_column_type(s, 0) ){ + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + int rc2 = sqlite3_step(s); + if( rc2==SQLITE_ROW ) return SQLITE_ERROR; + return rc2; + } + + *piStartBlockid = sqlite3_column_int64(s, 0); + *piEndBlockid = sqlite3_column_int64(s, 1); + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + rc = sqlite3_step(s); + if( rc==SQLITE_ROW ) return SQLITE_ERROR; + if( rc!=SQLITE_DONE ) return rc; + return SQLITE_ROW; +} + +/* Delete the segment blocks and segment directory records for all +** segments at iLevel. +*/ +static int segdir_delete(fulltext_vtab *v, int iLevel){ + sqlite3_stmt *s; + sqlite_int64 iStartBlockid, iEndBlockid; + int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid); + if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc; + + if( rc==SQLITE_ROW ){ + rc = block_delete(v, iStartBlockid, iEndBlockid); + if( rc!=SQLITE_OK ) return rc; + } + + /* Delete the segment directory itself. */ + rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iLevel); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step(s); +} + +/* Delete entire fts index, SQLITE_OK on success, relevant error on +** failure. +*/ +static int segdir_delete_all(fulltext_vtab *v){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sql_single_step(s); + if( rc!=SQLITE_OK ) return rc; + + rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + return sql_single_step(s); +} + +/* Returns SQLITE_OK with *pnSegments set to the number of entries in +** %_segdir and *piMaxLevel set to the highest level which has a +** segment. Otherwise returns the SQLite error which caused failure. +*/ +static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){ + sqlite3_stmt *s; + int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_step(s); + /* TODO(shess): This case should not be possible? Should stronger + ** measures be taken if it happens? + */ + if( rc==SQLITE_DONE ){ + *pnSegments = 0; + *piMaxLevel = 0; + return SQLITE_OK; + } + if( rc!=SQLITE_ROW ) return rc; + + *pnSegments = sqlite3_column_int(s, 0); + *piMaxLevel = sqlite3_column_int(s, 1); + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain locked. */ + rc = sqlite3_step(s); + if( rc==SQLITE_DONE ) return SQLITE_OK; + if( rc==SQLITE_ROW ) return SQLITE_ERROR; + return rc; +} + +/* TODO(shess) clearPendingTerms() is far down the file because +** writeZeroSegment() is far down the file because LeafWriter is far +** down the file. Consider refactoring the code to move the non-vtab +** code above the vtab code so that we don't need this forward +** reference. +*/ +static int clearPendingTerms(fulltext_vtab *v); + +/* +** Free the memory used to contain a fulltext_vtab structure. +*/ +static void fulltext_vtab_destroy(fulltext_vtab *v){ + int iStmt, i; + + TRACE(("FTS2 Destroy %p\n", v)); + for( iStmt=0; iStmtpFulltextStatements[iStmt]!=NULL ){ + sqlite3_finalize(v->pFulltextStatements[iStmt]); + v->pFulltextStatements[iStmt] = NULL; + } + } + + for( i=0; ipLeafSelectStmts[i]!=NULL ){ + sqlite3_finalize(v->pLeafSelectStmts[i]); + v->pLeafSelectStmts[i] = NULL; + } + } + + if( v->pTokenizer!=NULL ){ + v->pTokenizer->pModule->xDestroy(v->pTokenizer); + v->pTokenizer = NULL; + } + + clearPendingTerms(v); + + sqlite3_free(v->azColumn); + for(i = 0; i < v->nColumn; ++i) { + sqlite3_free(v->azContentColumn[i]); + } + sqlite3_free(v->azContentColumn); + sqlite3_free(v); +} + +/* +** Token types for parsing the arguments to xConnect or xCreate. +*/ +#define TOKEN_EOF 0 /* End of file */ +#define TOKEN_SPACE 1 /* Any kind of whitespace */ +#define TOKEN_ID 2 /* An identifier */ +#define TOKEN_STRING 3 /* A string literal */ +#define TOKEN_PUNCT 4 /* A single punctuation character */ + +/* +** If X is a character that can be used in an identifier then +** IdChar(X) will be true. Otherwise it is false. +** +** For ASCII, any character with the high-order bit set is +** allowed in an identifier. For 7-bit characters, +** sqlite3IsIdChar[X] must be 1. +** +** Ticket #1066. the SQL standard does not allow '$' in the +** middle of identfiers. But many SQL implementations do. +** SQLite will allow '$' in identifiers for compatibility. +** But the feature is undocumented. +*/ +static const char isIdChar[] = { +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ + 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ +}; +#define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && isIdChar[c-0x20])) + + +/* +** Return the length of the token that begins at z[0]. +** Store the token type in *tokenType before returning. +*/ +static int getToken(const char *z, int *tokenType){ + int i, c; + switch( *z ){ + case 0: { + *tokenType = TOKEN_EOF; + return 0; + } + case ' ': case '\t': case '\n': case '\f': case '\r': { + for(i=1; safe_isspace(z[i]); i++){} + *tokenType = TOKEN_SPACE; + return i; + } + case '`': + case '\'': + case '"': { + int delim = z[0]; + for(i=1; (c=z[i])!=0; i++){ + if( c==delim ){ + if( z[i+1]==delim ){ + i++; + }else{ + break; + } + } + } + *tokenType = TOKEN_STRING; + return i + (c!=0); + } + case '[': { + for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} + *tokenType = TOKEN_ID; + return i; + } + default: { + if( !IdChar(*z) ){ + break; + } + for(i=1; IdChar(z[i]); i++){} + *tokenType = TOKEN_ID; + return i; + } + } + *tokenType = TOKEN_PUNCT; + return 1; +} + +/* +** A token extracted from a string is an instance of the following +** structure. +*/ +typedef struct Token { + const char *z; /* Pointer to token text. Not '\000' terminated */ + short int n; /* Length of the token text in bytes. */ +} Token; + +/* +** Given a input string (which is really one of the argv[] parameters +** passed into xConnect or xCreate) split the string up into tokens. +** Return an array of pointers to '\000' terminated strings, one string +** for each non-whitespace token. +** +** The returned array is terminated by a single NULL pointer. +** +** Space to hold the returned array is obtained from a single +** malloc and should be freed by passing the return value to free(). +** The individual strings within the token list are all a part of +** the single memory allocation and will all be freed at once. +*/ +static char **tokenizeString(const char *z, int *pnToken){ + int nToken = 0; + Token *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) ); + int n = 1; + int e, i; + int totalSize = 0; + char **azToken; + char *zCopy; + while( n>0 ){ + n = getToken(z, &e); + if( e!=TOKEN_SPACE ){ + aToken[nToken].z = z; + aToken[nToken].n = n; + nToken++; + totalSize += n+1; + } + z += n; + } + azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize ); + zCopy = (char*)&azToken[nToken]; + nToken--; + for(i=0; i=0 ){ + azIn[j] = azIn[i]; + } + j++; + } + } + azIn[j] = 0; + } +} + + +/* +** Find the first alphanumeric token in the string zIn. Null-terminate +** this token. Remove any quotation marks. And return a pointer to +** the result. +*/ +static char *firstToken(char *zIn, char **pzTail){ + int n, ttype; + while(1){ + n = getToken(zIn, &ttype); + if( ttype==TOKEN_SPACE ){ + zIn += n; + }else if( ttype==TOKEN_EOF ){ + *pzTail = zIn; + return 0; + }else{ + zIn[n] = 0; + *pzTail = &zIn[1]; + dequoteString(zIn); + return zIn; + } + } + /*NOTREACHED*/ +} + +/* Return true if... +** +** * s begins with the string t, ignoring case +** * s is longer than t +** * The first character of s beyond t is not a alphanumeric +** +** Ignore leading space in *s. +** +** To put it another way, return true if the first token of +** s[] is t[]. +*/ +static int startsWith(const char *s, const char *t){ + while( safe_isspace(*s) ){ s++; } + while( *t ){ + if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0; + } + return *s!='_' && !safe_isalnum(*s); +} + +/* +** An instance of this structure defines the "spec" of a +** full text index. This structure is populated by parseSpec +** and use by fulltextConnect and fulltextCreate. +*/ +typedef struct TableSpec { + const char *zDb; /* Logical database name */ + const char *zName; /* Name of the full-text index */ + int nColumn; /* Number of columns to be indexed */ + char **azColumn; /* Original names of columns to be indexed */ + char **azContentColumn; /* Column names for %_content */ + char **azTokenizer; /* Name of tokenizer and its arguments */ +} TableSpec; + +/* +** Reclaim all of the memory used by a TableSpec +*/ +static void clearTableSpec(TableSpec *p) { + sqlite3_free(p->azColumn); + sqlite3_free(p->azContentColumn); + sqlite3_free(p->azTokenizer); +} + +/* Parse a CREATE VIRTUAL TABLE statement, which looks like this: + * + * CREATE VIRTUAL TABLE email + * USING fts2(subject, body, tokenize mytokenizer(myarg)) + * + * We return parsed information in a TableSpec structure. + * + */ +static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv, + char**pzErr){ + int i, n; + char *z, *zDummy; + char **azArg; + const char *zTokenizer = 0; /* argv[] entry describing the tokenizer */ + + assert( argc>=3 ); + /* Current interface: + ** argv[0] - module name + ** argv[1] - database name + ** argv[2] - table name + ** argv[3..] - columns, optionally followed by tokenizer specification + ** and snippet delimiters specification. + */ + + /* Make a copy of the complete argv[][] array in a single allocation. + ** The argv[][] array is read-only and transient. We can write to the + ** copy in order to modify things and the copy is persistent. + */ + CLEAR(pSpec); + for(i=n=0; izDb = azArg[1]; + pSpec->zName = azArg[2]; + pSpec->nColumn = 0; + pSpec->azColumn = azArg; + zTokenizer = "tokenize simple"; + for(i=3; inColumn] = firstToken(azArg[i], &zDummy); + pSpec->nColumn++; + } + } + if( pSpec->nColumn==0 ){ + azArg[0] = "content"; + pSpec->nColumn = 1; + } + + /* + ** Construct the list of content column names. + ** + ** Each content column name will be of the form cNNAAAA + ** where NN is the column number and AAAA is the sanitized + ** column name. "sanitized" means that special characters are + ** converted to "_". The cNN prefix guarantees that all column + ** names are unique. + ** + ** The AAAA suffix is not strictly necessary. It is included + ** for the convenience of people who might examine the generated + ** %_content table and wonder what the columns are used for. + */ + pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) ); + if( pSpec->azContentColumn==0 ){ + clearTableSpec(pSpec); + return SQLITE_NOMEM; + } + for(i=0; inColumn; i++){ + char *p; + pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]); + for (p = pSpec->azContentColumn[i]; *p ; ++p) { + if( !safe_isalnum(*p) ) *p = '_'; + } + } + + /* + ** Parse the tokenizer specification string. + */ + pSpec->azTokenizer = tokenizeString(zTokenizer, &n); + tokenListToIdList(pSpec->azTokenizer); + + return SQLITE_OK; +} + +/* +** Generate a CREATE TABLE statement that describes the schema of +** the virtual table. Return a pointer to this schema string. +** +** Space is obtained from sqlite3_mprintf() and should be freed +** using sqlite3_free(). +*/ +static char *fulltextSchema( + int nColumn, /* Number of columns */ + const char *const* azColumn, /* List of columns */ + const char *zTableName /* Name of the table */ +){ + int i; + char *zSchema, *zNext; + const char *zSep = "("; + zSchema = sqlite3_mprintf("CREATE TABLE x"); + for(i=0; ibase */ + v->db = db; + v->zDb = spec->zDb; /* Freed when azColumn is freed */ + v->zName = spec->zName; /* Freed when azColumn is freed */ + v->nColumn = spec->nColumn; + v->azContentColumn = spec->azContentColumn; + spec->azContentColumn = 0; + v->azColumn = spec->azColumn; + spec->azColumn = 0; + + if( spec->azTokenizer==0 ){ + return SQLITE_NOMEM; + } + + zTok = spec->azTokenizer[0]; + if( !zTok ){ + zTok = "simple"; + } + nTok = strlen(zTok)+1; + + m = (sqlite3_tokenizer_module *)sqlite3Fts2HashFind(pHash, zTok, nTok); + if( !m ){ + *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]); + rc = SQLITE_ERROR; + goto err; + } + + for(n=0; spec->azTokenizer[n]; n++){} + if( n ){ + rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1], + &v->pTokenizer); + }else{ + rc = m->xCreate(0, 0, &v->pTokenizer); + } + if( rc!=SQLITE_OK ) goto err; + v->pTokenizer->pModule = m; + + /* TODO: verify the existence of backing tables foo_content, foo_term */ + + schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn, + spec->zName); + rc = sqlite3_declare_vtab(db, schema); + sqlite3_free(schema); + if( rc!=SQLITE_OK ) goto err; + + memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements)); + + /* Indicate that the buffer is not live. */ + v->nPendingData = -1; + + *ppVTab = &v->base; + TRACE(("FTS2 Connect %p\n", v)); + + return rc; + +err: + fulltext_vtab_destroy(v); + return rc; +} + +static int fulltextConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, + char **pzErr +){ + TableSpec spec; + int rc = parseSpec(&spec, argc, argv, pzErr); + if( rc!=SQLITE_OK ) return rc; + + rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr); + clearTableSpec(&spec); + return rc; +} + +/* The %_content table holds the text of each document, with +** the rowid used as the docid. +*/ +/* TODO(shess) This comment needs elaboration to match the updated +** code. Work it into the top-of-file comment at that time. +*/ +static int fulltextCreate(sqlite3 *db, void *pAux, + int argc, const char * const *argv, + sqlite3_vtab **ppVTab, char **pzErr){ + int rc; + TableSpec spec; + StringBuffer schema; + TRACE(("FTS2 Create\n")); + + rc = parseSpec(&spec, argc, argv, pzErr); + if( rc!=SQLITE_OK ) return rc; + + initStringBuffer(&schema); + append(&schema, "CREATE TABLE %_content("); + appendList(&schema, spec.nColumn, spec.azContentColumn); + append(&schema, ")"); + rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema)); + stringBufferDestroy(&schema); + if( rc!=SQLITE_OK ) goto out; + + rc = sql_exec(db, spec.zDb, spec.zName, + "create table %_segments(block blob);"); + if( rc!=SQLITE_OK ) goto out; + + rc = sql_exec(db, spec.zDb, spec.zName, + "create table %_segdir(" + " level integer," + " idx integer," + " start_block integer," + " leaves_end_block integer," + " end_block integer," + " root blob," + " primary key(level, idx)" + ");"); + if( rc!=SQLITE_OK ) goto out; + + rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr); + +out: + clearTableSpec(&spec); + return rc; +} + +/* Decide how to handle an SQL query. */ +static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ + int i; + TRACE(("FTS2 BestIndex\n")); + + for(i=0; inConstraint; ++i){ + const struct sqlite3_index_constraint *pConstraint; + pConstraint = &pInfo->aConstraint[i]; + if( pConstraint->usable ) { + if( pConstraint->iColumn==-1 && + pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + pInfo->idxNum = QUERY_ROWID; /* lookup by rowid */ + TRACE(("FTS2 QUERY_ROWID\n")); + } else if( pConstraint->iColumn>=0 && + pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ + /* full-text search */ + pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn; + TRACE(("FTS2 QUERY_FULLTEXT %d\n", pConstraint->iColumn)); + } else continue; + + pInfo->aConstraintUsage[i].argvIndex = 1; + pInfo->aConstraintUsage[i].omit = 1; + + /* An arbitrary value for now. + * TODO: Perhaps rowid matches should be considered cheaper than + * full-text searches. */ + pInfo->estimatedCost = 1.0; + + return SQLITE_OK; + } + } + pInfo->idxNum = QUERY_GENERIC; + return SQLITE_OK; +} + +static int fulltextDisconnect(sqlite3_vtab *pVTab){ + TRACE(("FTS2 Disconnect %p\n", pVTab)); + fulltext_vtab_destroy((fulltext_vtab *)pVTab); + return SQLITE_OK; +} + +static int fulltextDestroy(sqlite3_vtab *pVTab){ + fulltext_vtab *v = (fulltext_vtab *)pVTab; + int rc; + + TRACE(("FTS2 Destroy %p\n", pVTab)); + rc = sql_exec(v->db, v->zDb, v->zName, + "drop table if exists %_content;" + "drop table if exists %_segments;" + "drop table if exists %_segdir;" + ); + if( rc!=SQLITE_OK ) return rc; + + fulltext_vtab_destroy((fulltext_vtab *)pVTab); + return SQLITE_OK; +} + +static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + fulltext_cursor *c; + + c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor)); + if( c ){ + memset(c, 0, sizeof(fulltext_cursor)); + /* sqlite will initialize c->base */ + *ppCursor = &c->base; + TRACE(("FTS2 Open %p: %p\n", pVTab, c)); + return SQLITE_OK; + }else{ + return SQLITE_NOMEM; + } +} + + +/* Free all of the dynamically allocated memory held by *q +*/ +static void queryClear(Query *q){ + int i; + for(i = 0; i < q->nTerms; ++i){ + sqlite3_free(q->pTerms[i].pTerm); + } + sqlite3_free(q->pTerms); + CLEAR(q); +} + +/* Free all of the dynamically allocated memory held by the +** Snippet +*/ +static void snippetClear(Snippet *p){ + sqlite3_free(p->aMatch); + sqlite3_free(p->zOffset); + sqlite3_free(p->zSnippet); + CLEAR(p); +} +/* +** Append a single entry to the p->aMatch[] log. +*/ +static void snippetAppendMatch( + Snippet *p, /* Append the entry to this snippet */ + int iCol, int iTerm, /* The column and query term */ + int iStart, int nByte /* Offset and size of the match */ +){ + int i; + struct snippetMatch *pMatch; + if( p->nMatch+1>=p->nAlloc ){ + p->nAlloc = p->nAlloc*2 + 10; + p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) ); + if( p->aMatch==0 ){ + p->nMatch = 0; + p->nAlloc = 0; + return; + } + } + i = p->nMatch++; + pMatch = &p->aMatch[i]; + pMatch->iCol = iCol; + pMatch->iTerm = iTerm; + pMatch->iStart = iStart; + pMatch->nByte = nByte; +} + +/* +** Sizing information for the circular buffer used in snippetOffsetsOfColumn() +*/ +#define FTS2_ROTOR_SZ (32) +#define FTS2_ROTOR_MASK (FTS2_ROTOR_SZ-1) + +/* +** Add entries to pSnippet->aMatch[] for every match that occurs against +** document zDoc[0..nDoc-1] which is stored in column iColumn. +*/ +static void snippetOffsetsOfColumn( + Query *pQuery, + Snippet *pSnippet, + int iColumn, + const char *zDoc, + int nDoc +){ + const sqlite3_tokenizer_module *pTModule; /* The tokenizer module */ + sqlite3_tokenizer *pTokenizer; /* The specific tokenizer */ + sqlite3_tokenizer_cursor *pTCursor; /* Tokenizer cursor */ + fulltext_vtab *pVtab; /* The full text index */ + int nColumn; /* Number of columns in the index */ + const QueryTerm *aTerm; /* Query string terms */ + int nTerm; /* Number of query string terms */ + int i, j; /* Loop counters */ + int rc; /* Return code */ + unsigned int match, prevMatch; /* Phrase search bitmasks */ + const char *zToken; /* Next token from the tokenizer */ + int nToken; /* Size of zToken */ + int iBegin, iEnd, iPos; /* Offsets of beginning and end */ + + /* The following variables keep a circular buffer of the last + ** few tokens */ + unsigned int iRotor = 0; /* Index of current token */ + int iRotorBegin[FTS2_ROTOR_SZ]; /* Beginning offset of token */ + int iRotorLen[FTS2_ROTOR_SZ]; /* Length of token */ + + pVtab = pQuery->pFts; + nColumn = pVtab->nColumn; + pTokenizer = pVtab->pTokenizer; + pTModule = pTokenizer->pModule; + rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor); + if( rc ) return; + pTCursor->pTokenizer = pTokenizer; + aTerm = pQuery->pTerms; + nTerm = pQuery->nTerms; + if( nTerm>=FTS2_ROTOR_SZ ){ + nTerm = FTS2_ROTOR_SZ - 1; + } + prevMatch = 0; + while(1){ + rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos); + if( rc ) break; + iRotorBegin[iRotor&FTS2_ROTOR_MASK] = iBegin; + iRotorLen[iRotor&FTS2_ROTOR_MASK] = iEnd-iBegin; + match = 0; + for(i=0; i=0 && iColnToken ) continue; + if( !aTerm[i].isPrefix && aTerm[i].nTerm1 && (prevMatch & (1<=0; j--){ + int k = (iRotor-j) & FTS2_ROTOR_MASK; + snippetAppendMatch(pSnippet, iColumn, i-j, + iRotorBegin[k], iRotorLen[k]); + } + } + } + prevMatch = match<<1; + iRotor++; + } + pTModule->xClose(pTCursor); +} + + +/* +** Compute all offsets for the current row of the query. +** If the offsets have already been computed, this routine is a no-op. +*/ +static void snippetAllOffsets(fulltext_cursor *p){ + int nColumn; + int iColumn, i; + int iFirst, iLast; + fulltext_vtab *pFts; + + if( p->snippet.nMatch ) return; + if( p->q.nTerms==0 ) return; + pFts = p->q.pFts; + nColumn = pFts->nColumn; + iColumn = (p->iCursorType - QUERY_FULLTEXT); + if( iColumn<0 || iColumn>=nColumn ){ + iFirst = 0; + iLast = nColumn-1; + }else{ + iFirst = iColumn; + iLast = iColumn; + } + for(i=iFirst; i<=iLast; i++){ + const char *zDoc; + int nDoc; + zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1); + nDoc = sqlite3_column_bytes(p->pStmt, i+1); + snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc); + } +} + +/* +** Convert the information in the aMatch[] array of the snippet +** into the string zOffset[0..nOffset-1]. +*/ +static void snippetOffsetText(Snippet *p){ + int i; + int cnt = 0; + StringBuffer sb; + char zBuf[200]; + if( p->zOffset ) return; + initStringBuffer(&sb); + for(i=0; inMatch; i++){ + struct snippetMatch *pMatch = &p->aMatch[i]; + zBuf[0] = ' '; + sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d", + pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte); + append(&sb, zBuf); + cnt++; + } + p->zOffset = stringBufferData(&sb); + p->nOffset = stringBufferLength(&sb); +} + +/* +** zDoc[0..nDoc-1] is phrase of text. aMatch[0..nMatch-1] are a set +** of matching words some of which might be in zDoc. zDoc is column +** number iCol. +** +** iBreak is suggested spot in zDoc where we could begin or end an +** excerpt. Return a value similar to iBreak but possibly adjusted +** to be a little left or right so that the break point is better. +*/ +static int wordBoundary( + int iBreak, /* The suggested break point */ + const char *zDoc, /* Document text */ + int nDoc, /* Number of bytes in zDoc[] */ + struct snippetMatch *aMatch, /* Matching words */ + int nMatch, /* Number of entries in aMatch[] */ + int iCol /* The column number for zDoc[] */ +){ + int i; + if( iBreak<=10 ){ + return 0; + } + if( iBreak>=nDoc-10 ){ + return nDoc; + } + for(i=0; i0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){ + return aMatch[i-1].iStart; + } + } + for(i=1; i<=10; i++){ + if( safe_isspace(zDoc[iBreak-i]) ){ + return iBreak - i + 1; + } + if( safe_isspace(zDoc[iBreak+i]) ){ + return iBreak + i + 1; + } + } + return iBreak; +} + + + +/* +** Allowed values for Snippet.aMatch[].snStatus +*/ +#define SNIPPET_IGNORE 0 /* It is ok to omit this match from the snippet */ +#define SNIPPET_DESIRED 1 /* We want to include this match in the snippet */ + +/* +** Generate the text of a snippet. +*/ +static void snippetText( + fulltext_cursor *pCursor, /* The cursor we need the snippet for */ + const char *zStartMark, /* Markup to appear before each match */ + const char *zEndMark, /* Markup to appear after each match */ + const char *zEllipsis /* Ellipsis mark */ +){ + int i, j; + struct snippetMatch *aMatch; + int nMatch; + int nDesired; + StringBuffer sb; + int tailCol; + int tailOffset; + int iCol; + int nDoc; + const char *zDoc; + int iStart, iEnd; + int tailEllipsis = 0; + int iMatch; + + + sqlite3_free(pCursor->snippet.zSnippet); + pCursor->snippet.zSnippet = 0; + aMatch = pCursor->snippet.aMatch; + nMatch = pCursor->snippet.nMatch; + initStringBuffer(&sb); + + for(i=0; iq.nTerms; i++){ + for(j=0; j0; i++){ + if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue; + nDesired--; + iCol = aMatch[i].iCol; + zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1); + nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1); + iStart = aMatch[i].iStart - 40; + iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol); + if( iStart<=10 ){ + iStart = 0; + } + if( iCol==tailCol && iStart<=tailOffset+20 ){ + iStart = tailOffset; + } + if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){ + trimWhiteSpace(&sb); + appendWhiteSpace(&sb); + append(&sb, zEllipsis); + appendWhiteSpace(&sb); + } + iEnd = aMatch[i].iStart + aMatch[i].nByte + 40; + iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol); + if( iEnd>=nDoc-10 ){ + iEnd = nDoc; + tailEllipsis = 0; + }else{ + tailEllipsis = 1; + } + while( iMatchsnippet.zSnippet = stringBufferData(&sb); + pCursor->snippet.nSnippet = stringBufferLength(&sb); +} + + +/* +** Close the cursor. For additional information see the documentation +** on the xClose method of the virtual table interface. +*/ +static int fulltextClose(sqlite3_vtab_cursor *pCursor){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + TRACE(("FTS2 Close %p\n", c)); + sqlite3_finalize(c->pStmt); + queryClear(&c->q); + snippetClear(&c->snippet); + if( c->result.nData!=0 ) dlrDestroy(&c->reader); + dataBufferDestroy(&c->result); + sqlite3_free(c); + return SQLITE_OK; +} + +static int fulltextNext(sqlite3_vtab_cursor *pCursor){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + int rc; + + TRACE(("FTS2 Next %p\n", pCursor)); + snippetClear(&c->snippet); + if( c->iCursorType < QUERY_FULLTEXT ){ + /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */ + rc = sqlite3_step(c->pStmt); + switch( rc ){ + case SQLITE_ROW: + c->eof = 0; + return SQLITE_OK; + case SQLITE_DONE: + c->eof = 1; + return SQLITE_OK; + default: + c->eof = 1; + return rc; + } + } else { /* full-text query */ + rc = sqlite3_reset(c->pStmt); + if( rc!=SQLITE_OK ) return rc; + + if( c->result.nData==0 || dlrAtEnd(&c->reader) ){ + c->eof = 1; + return SQLITE_OK; + } + rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader)); + dlrStep(&c->reader); + if( rc!=SQLITE_OK ) return rc; + /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */ + rc = sqlite3_step(c->pStmt); + if( rc==SQLITE_ROW ){ /* the case we expect */ + c->eof = 0; + return SQLITE_OK; + } + /* an error occurred; abort */ + return rc==SQLITE_DONE ? SQLITE_ERROR : rc; + } +} + + +/* TODO(shess) If we pushed LeafReader to the top of the file, or to +** another file, term_select() could be pushed above +** docListOfTerm(). +*/ +static int termSelect(fulltext_vtab *v, int iColumn, + const char *pTerm, int nTerm, int isPrefix, + DocListType iType, DataBuffer *out); + +/* Return a DocList corresponding to the query term *pTerm. If *pTerm +** is the first term of a phrase query, go ahead and evaluate the phrase +** query and return the doclist for the entire phrase query. +** +** The resulting DL_DOCIDS doclist is stored in pResult, which is +** overwritten. +*/ +static int docListOfTerm( + fulltext_vtab *v, /* The full text index */ + int iColumn, /* column to restrict to. No restriction if >=nColumn */ + QueryTerm *pQTerm, /* Term we are looking for, or 1st term of a phrase */ + DataBuffer *pResult /* Write the result here */ +){ + DataBuffer left, right, new; + int i, rc; + + /* No phrase search if no position info. */ + assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS ); + + /* This code should never be called with buffered updates. */ + assert( v->nPendingData<0 ); + + dataBufferInit(&left, 0); + rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix, + 0nPhrase ? DL_POSITIONS : DL_DOCIDS, &left); + if( rc ) return rc; + for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){ + dataBufferInit(&right, 0); + rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm, + pQTerm[i].isPrefix, DL_POSITIONS, &right); + if( rc ){ + dataBufferDestroy(&left); + return rc; + } + dataBufferInit(&new, 0); + docListPhraseMerge(left.pData, left.nData, right.pData, right.nData, + inPhrase ? DL_POSITIONS : DL_DOCIDS, &new); + dataBufferDestroy(&left); + dataBufferDestroy(&right); + left = new; + } + *pResult = left; + return SQLITE_OK; +} + +/* Add a new term pTerm[0..nTerm-1] to the query *q. +*/ +static void queryAdd(Query *q, const char *pTerm, int nTerm){ + QueryTerm *t; + ++q->nTerms; + q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0])); + if( q->pTerms==0 ){ + q->nTerms = 0; + return; + } + t = &q->pTerms[q->nTerms - 1]; + CLEAR(t); + t->pTerm = sqlite3_malloc(nTerm+1); + memcpy(t->pTerm, pTerm, nTerm); + t->pTerm[nTerm] = 0; + t->nTerm = nTerm; + t->isOr = q->nextIsOr; + t->isPrefix = 0; + q->nextIsOr = 0; + t->iColumn = q->nextColumn; + q->nextColumn = q->dfltColumn; +} + +/* +** Check to see if the string zToken[0...nToken-1] matches any +** column name in the virtual table. If it does, +** return the zero-indexed column number. If not, return -1. +*/ +static int checkColumnSpecifier( + fulltext_vtab *pVtab, /* The virtual table */ + const char *zToken, /* Text of the token */ + int nToken /* Number of characters in the token */ +){ + int i; + for(i=0; inColumn; i++){ + if( memcmp(pVtab->azColumn[i], zToken, nToken)==0 + && pVtab->azColumn[i][nToken]==0 ){ + return i; + } + } + return -1; +} + +/* +** Parse the text at pSegment[0..nSegment-1]. Add additional terms +** to the query being assemblied in pQuery. +** +** inPhrase is true if pSegment[0..nSegement-1] is contained within +** double-quotes. If inPhrase is true, then the first term +** is marked with the number of terms in the phrase less one and +** OR and "-" syntax is ignored. If inPhrase is false, then every +** term found is marked with nPhrase=0 and OR and "-" syntax is significant. +*/ +static int tokenizeSegment( + sqlite3_tokenizer *pTokenizer, /* The tokenizer to use */ + const char *pSegment, int nSegment, /* Query expression being parsed */ + int inPhrase, /* True if within "..." */ + Query *pQuery /* Append results here */ +){ + const sqlite3_tokenizer_module *pModule = pTokenizer->pModule; + sqlite3_tokenizer_cursor *pCursor; + int firstIndex = pQuery->nTerms; + int iCol; + int nTerm = 1; + + int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor); + if( rc!=SQLITE_OK ) return rc; + pCursor->pTokenizer = pTokenizer; + + while( 1 ){ + const char *pToken; + int nToken, iBegin, iEnd, iPos; + + rc = pModule->xNext(pCursor, + &pToken, &nToken, + &iBegin, &iEnd, &iPos); + if( rc!=SQLITE_OK ) break; + if( !inPhrase && + pSegment[iEnd]==':' && + (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){ + pQuery->nextColumn = iCol; + continue; + } + if( !inPhrase && pQuery->nTerms>0 && nToken==2 + && pSegment[iBegin]=='O' && pSegment[iBegin+1]=='R' ){ + pQuery->nextIsOr = 1; + continue; + } + queryAdd(pQuery, pToken, nToken); + if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){ + pQuery->pTerms[pQuery->nTerms-1].isNot = 1; + } + if( iEndpTerms[pQuery->nTerms-1].isPrefix = 1; + } + pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm; + if( inPhrase ){ + nTerm++; + } + } + + if( inPhrase && pQuery->nTerms>firstIndex ){ + pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1; + } + + return pModule->xClose(pCursor); +} + +/* Parse a query string, yielding a Query object pQuery. +** +** The calling function will need to queryClear() to clean up +** the dynamically allocated memory held by pQuery. +*/ +static int parseQuery( + fulltext_vtab *v, /* The fulltext index */ + const char *zInput, /* Input text of the query string */ + int nInput, /* Size of the input text */ + int dfltColumn, /* Default column of the index to match against */ + Query *pQuery /* Write the parse results here. */ +){ + int iInput, inPhrase = 0; + + if( zInput==0 ) nInput = 0; + if( nInput<0 ) nInput = strlen(zInput); + pQuery->nTerms = 0; + pQuery->pTerms = NULL; + pQuery->nextIsOr = 0; + pQuery->nextColumn = dfltColumn; + pQuery->dfltColumn = dfltColumn; + pQuery->pFts = v; + + for(iInput=0; iInputiInput ){ + tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase, + pQuery); + } + iInput = i; + if( i=nColumn +** they are allowed to match against any column. +*/ +static int fulltextQuery( + fulltext_vtab *v, /* The full text index */ + int iColumn, /* Match against this column by default */ + const char *zInput, /* The query string */ + int nInput, /* Number of bytes in zInput[] */ + DataBuffer *pResult, /* Write the result doclist here */ + Query *pQuery /* Put parsed query string here */ +){ + int i, iNext, rc; + DataBuffer left, right, or, new; + int nNot = 0; + QueryTerm *aTerm; + + /* TODO(shess) Instead of flushing pendingTerms, we could query for + ** the relevant term and merge the doclist into what we receive from + ** the database. Wait and see if this is a common issue, first. + ** + ** A good reason not to flush is to not generate update-related + ** error codes from here. + */ + + /* Flush any buffered updates before executing the query. */ + rc = flushPendingTerms(v); + if( rc!=SQLITE_OK ) return rc; + + /* TODO(shess) I think that the queryClear() calls below are not + ** necessary, because fulltextClose() already clears the query. + */ + rc = parseQuery(v, zInput, nInput, iColumn, pQuery); + if( rc!=SQLITE_OK ) return rc; + + /* Empty or NULL queries return no results. */ + if( pQuery->nTerms==0 ){ + dataBufferInit(pResult, 0); + return SQLITE_OK; + } + + /* Merge AND terms. */ + /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */ + aTerm = pQuery->pTerms; + for(i = 0; inTerms; i=iNext){ + if( aTerm[i].isNot ){ + /* Handle all NOT terms in a separate pass */ + nNot++; + iNext = i + aTerm[i].nPhrase+1; + continue; + } + iNext = i + aTerm[i].nPhrase + 1; + rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right); + if( rc ){ + if( i!=nNot ) dataBufferDestroy(&left); + queryClear(pQuery); + return rc; + } + while( iNextnTerms && aTerm[iNext].isOr ){ + rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or); + iNext += aTerm[iNext].nPhrase + 1; + if( rc ){ + if( i!=nNot ) dataBufferDestroy(&left); + dataBufferDestroy(&right); + queryClear(pQuery); + return rc; + } + dataBufferInit(&new, 0); + docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new); + dataBufferDestroy(&right); + dataBufferDestroy(&or); + right = new; + } + if( i==nNot ){ /* first term processed. */ + left = right; + }else{ + dataBufferInit(&new, 0); + docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new); + dataBufferDestroy(&right); + dataBufferDestroy(&left); + left = new; + } + } + + if( nNot==pQuery->nTerms ){ + /* We do not yet know how to handle a query of only NOT terms */ + return SQLITE_ERROR; + } + + /* Do the EXCEPT terms */ + for(i=0; inTerms; i += aTerm[i].nPhrase + 1){ + if( !aTerm[i].isNot ) continue; + rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right); + if( rc ){ + queryClear(pQuery); + dataBufferDestroy(&left); + return rc; + } + dataBufferInit(&new, 0); + docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new); + dataBufferDestroy(&right); + dataBufferDestroy(&left); + left = new; + } + + *pResult = left; + return rc; +} + +/* +** This is the xFilter interface for the virtual table. See +** the virtual table xFilter method documentation for additional +** information. +** +** If idxNum==QUERY_GENERIC then do a full table scan against +** the %_content table. +** +** If idxNum==QUERY_ROWID then do a rowid lookup for a single entry +** in the %_content table. +** +** If idxNum>=QUERY_FULLTEXT then use the full text index. The +** column on the left-hand side of the MATCH operator is column +** number idxNum-QUERY_FULLTEXT, 0 indexed. argv[0] is the right-hand +** side of the MATCH operator. +*/ +/* TODO(shess) Upgrade the cursor initialization and destruction to +** account for fulltextFilter() being called multiple times on the +** same cursor. The current solution is very fragile. Apply fix to +** fts2 as appropriate. +*/ +static int fulltextFilter( + sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + int idxNum, const char *idxStr, /* Which indexing scheme to use */ + int argc, sqlite3_value **argv /* Arguments for the indexing scheme */ +){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + fulltext_vtab *v = cursor_vtab(c); + int rc; + + TRACE(("FTS2 Filter %p\n",pCursor)); + + /* If the cursor has a statement that was not prepared according to + ** idxNum, clear it. I believe all calls to fulltextFilter with a + ** given cursor will have the same idxNum , but in this case it's + ** easy to be safe. + */ + if( c->pStmt && c->iCursorType!=idxNum ){ + sqlite3_finalize(c->pStmt); + c->pStmt = NULL; + } + + /* Get a fresh statement appropriate to idxNum. */ + /* TODO(shess): Add a prepared-statement cache in the vt structure. + ** The cache must handle multiple open cursors. Easier to cache the + ** statement variants at the vt to reduce malloc/realloc/free here. + ** Or we could have a StringBuffer variant which allowed stack + ** construction for small values. + */ + if( !c->pStmt ){ + char *zSql = sqlite3_mprintf("select rowid, * from %%_content %s", + idxNum==QUERY_GENERIC ? "" : "where rowid=?"); + rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, zSql); + sqlite3_free(zSql); + if( rc!=SQLITE_OK ) return rc; + c->iCursorType = idxNum; + }else{ + sqlite3_reset(c->pStmt); + assert( c->iCursorType==idxNum ); + } + + switch( idxNum ){ + case QUERY_GENERIC: + break; + + case QUERY_ROWID: + rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0])); + if( rc!=SQLITE_OK ) return rc; + break; + + default: /* full-text search */ + { + const char *zQuery = (const char *)sqlite3_value_text(argv[0]); + assert( idxNum<=QUERY_FULLTEXT+v->nColumn); + assert( argc==1 ); + queryClear(&c->q); + if( c->result.nData!=0 ){ + /* This case happens if the same cursor is used repeatedly. */ + dlrDestroy(&c->reader); + dataBufferReset(&c->result); + }else{ + dataBufferInit(&c->result, 0); + } + rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q); + if( rc!=SQLITE_OK ) return rc; + if( c->result.nData!=0 ){ + dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData); + } + break; + } + } + + return fulltextNext(pCursor); +} + +/* This is the xEof method of the virtual table. The SQLite core +** calls this routine to find out if it has reached the end of +** a query's results set. +*/ +static int fulltextEof(sqlite3_vtab_cursor *pCursor){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + return c->eof; +} + +/* This is the xColumn method of the virtual table. The SQLite +** core calls this method during a query when it needs the value +** of a column from the virtual table. This method needs to use +** one of the sqlite3_result_*() routines to store the requested +** value back in the pContext. +*/ +static int fulltextColumn(sqlite3_vtab_cursor *pCursor, + sqlite3_context *pContext, int idxCol){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + fulltext_vtab *v = cursor_vtab(c); + + if( idxColnColumn ){ + sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1); + sqlite3_result_value(pContext, pVal); + }else if( idxCol==v->nColumn ){ + /* The extra column whose name is the same as the table. + ** Return a blob which is a pointer to the cursor + */ + sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT); + } + return SQLITE_OK; +} + +/* This is the xRowid method. The SQLite core calls this routine to +** retrive the rowid for the current row of the result set. The +** rowid should be written to *pRowid. +*/ +static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + fulltext_cursor *c = (fulltext_cursor *) pCursor; + + *pRowid = sqlite3_column_int64(c->pStmt, 0); + return SQLITE_OK; +} + +/* Add all terms in [zText] to pendingTerms table. If [iColumn] > 0, +** we also store positions and offsets in the hash table using that +** column number. +*/ +static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid, + const char *zText, int iColumn){ + sqlite3_tokenizer *pTokenizer = v->pTokenizer; + sqlite3_tokenizer_cursor *pCursor; + const char *pToken; + int nTokenBytes; + int iStartOffset, iEndOffset, iPosition; + int rc; + + rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor); + if( rc!=SQLITE_OK ) return rc; + + pCursor->pTokenizer = pTokenizer; + while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor, + &pToken, &nTokenBytes, + &iStartOffset, &iEndOffset, + &iPosition)) ){ + DLCollector *p; + int nData; /* Size of doclist before our update. */ + + /* Positions can't be negative; we use -1 as a terminator + * internally. Token can't be NULL or empty. */ + if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){ + rc = SQLITE_ERROR; + break; + } + + p = fts2HashFind(&v->pendingTerms, pToken, nTokenBytes); + if( p==NULL ){ + nData = 0; + p = dlcNew(iDocid, DL_DEFAULT); + fts2HashInsert(&v->pendingTerms, pToken, nTokenBytes, p); + + /* Overhead for our hash table entry, the key, and the value. */ + v->nPendingData += sizeof(struct fts2HashElem)+sizeof(*p)+nTokenBytes; + }else{ + nData = p->b.nData; + if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid); + } + if( iColumn>=0 ){ + dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset); + } + + /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */ + v->nPendingData += p->b.nData-nData; + } + + /* TODO(shess) Check return? Should this be able to cause errors at + ** this point? Actually, same question about sqlite3_finalize(), + ** though one could argue that failure there means that the data is + ** not durable. *ponder* + */ + pTokenizer->pModule->xClose(pCursor); + if( SQLITE_DONE == rc ) return SQLITE_OK; + return rc; +} + +/* Add doclists for all terms in [pValues] to pendingTerms table. */ +static int insertTerms(fulltext_vtab *v, sqlite_int64 iRowid, + sqlite3_value **pValues){ + int i; + for(i = 0; i < v->nColumn ; ++i){ + char *zText = (char*)sqlite3_value_text(pValues[i]); + int rc = buildTerms(v, iRowid, zText, i); + if( rc!=SQLITE_OK ) return rc; + } + return SQLITE_OK; +} + +/* Add empty doclists for all terms in the given row's content to +** pendingTerms. +*/ +static int deleteTerms(fulltext_vtab *v, sqlite_int64 iRowid){ + const char **pValues; + int i, rc; + + /* TODO(shess) Should we allow such tables at all? */ + if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR; + + rc = content_select(v, iRowid, &pValues); + if( rc!=SQLITE_OK ) return rc; + + for(i = 0 ; i < v->nColumn; ++i) { + rc = buildTerms(v, iRowid, pValues[i], -1); + if( rc!=SQLITE_OK ) break; + } + + freeStringArray(v->nColumn, pValues); + return SQLITE_OK; +} + +/* TODO(shess) Refactor the code to remove this forward decl. */ +static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid); + +/* Insert a row into the %_content table; set *piRowid to be the ID of the +** new row. Add doclists for terms to pendingTerms. +*/ +static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestRowid, + sqlite3_value **pValues, sqlite_int64 *piRowid){ + int rc; + + rc = content_insert(v, pRequestRowid, pValues); /* execute an SQL INSERT */ + if( rc!=SQLITE_OK ) return rc; + + *piRowid = sqlite3_last_insert_rowid(v->db); + rc = initPendingTerms(v, *piRowid); + if( rc!=SQLITE_OK ) return rc; + + return insertTerms(v, *piRowid, pValues); +} + +/* Delete a row from the %_content table; add empty doclists for terms +** to pendingTerms. +*/ +static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){ + int rc = initPendingTerms(v, iRow); + if( rc!=SQLITE_OK ) return rc; + + rc = deleteTerms(v, iRow); + if( rc!=SQLITE_OK ) return rc; + + return content_delete(v, iRow); /* execute an SQL DELETE */ +} + +/* Update a row in the %_content table; add delete doclists to +** pendingTerms for old terms not in the new data, add insert doclists +** to pendingTerms for terms in the new data. +*/ +static int index_update(fulltext_vtab *v, sqlite_int64 iRow, + sqlite3_value **pValues){ + int rc = initPendingTerms(v, iRow); + if( rc!=SQLITE_OK ) return rc; + + /* Generate an empty doclist for each term that previously appeared in this + * row. */ + rc = deleteTerms(v, iRow); + if( rc!=SQLITE_OK ) return rc; + + rc = content_update(v, pValues, iRow); /* execute an SQL UPDATE */ + if( rc!=SQLITE_OK ) return rc; + + /* Now add positions for terms which appear in the updated row. */ + return insertTerms(v, iRow, pValues); +} + +/*******************************************************************/ +/* InteriorWriter is used to collect terms and block references into +** interior nodes in %_segments. See commentary at top of file for +** format. +*/ + +/* How large interior nodes can grow. */ +#define INTERIOR_MAX 2048 + +/* Minimum number of terms per interior node (except the root). This +** prevents large terms from making the tree too skinny - must be >0 +** so that the tree always makes progress. Note that the min tree +** fanout will be INTERIOR_MIN_TERMS+1. +*/ +#define INTERIOR_MIN_TERMS 7 +#if INTERIOR_MIN_TERMS<1 +# error INTERIOR_MIN_TERMS must be greater than 0. +#endif + +/* ROOT_MAX controls how much data is stored inline in the segment +** directory. +*/ +/* TODO(shess) Push ROOT_MAX down to whoever is writing things. It's +** only here so that interiorWriterRootInfo() and leafWriterRootInfo() +** can both see it, but if the caller passed it in, we wouldn't even +** need a define. +*/ +#define ROOT_MAX 1024 +#if ROOT_MAXterm, 0); + dataBufferReplace(&block->term, pTerm, nTerm); + + n = putVarint(c, iHeight); + n += putVarint(c+n, iChildBlock); + dataBufferInit(&block->data, INTERIOR_MAX); + dataBufferReplace(&block->data, c, n); + } + return block; +} + +#ifndef NDEBUG +/* Verify that the data is readable as an interior node. */ +static void interiorBlockValidate(InteriorBlock *pBlock){ + const char *pData = pBlock->data.pData; + int nData = pBlock->data.nData; + int n, iDummy; + sqlite_int64 iBlockid; + + assert( nData>0 ); + assert( pData!=0 ); + assert( pData+nData>pData ); + + /* Must lead with height of node as a varint(n), n>0 */ + n = getVarint32(pData, &iDummy); + assert( n>0 ); + assert( iDummy>0 ); + assert( n0 ); + assert( n<=nData ); + pData += n; + nData -= n; + + /* Zero or more terms of positive length */ + if( nData!=0 ){ + /* First term is not delta-encoded. */ + n = getVarint32(pData, &iDummy); + assert( n>0 ); + assert( iDummy>0 ); + assert( n+iDummy>0); + assert( n+iDummy<=nData ); + pData += n+iDummy; + nData -= n+iDummy; + + /* Following terms delta-encoded. */ + while( nData!=0 ){ + /* Length of shared prefix. */ + n = getVarint32(pData, &iDummy); + assert( n>0 ); + assert( iDummy>=0 ); + assert( n0 ); + assert( iDummy>0 ); + assert( n+iDummy>0); + assert( n+iDummy<=nData ); + pData += n+iDummy; + nData -= n+iDummy; + } + } +} +#define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x) +#else +#define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 ) +#endif + +typedef struct InteriorWriter { + int iHeight; /* from 0 at leaves. */ + InteriorBlock *first, *last; + struct InteriorWriter *parentWriter; + + DataBuffer term; /* Last term written to block "last". */ + sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */ +#ifndef NDEBUG + sqlite_int64 iLastChildBlock; /* for consistency checks. */ +#endif +} InteriorWriter; + +/* Initialize an interior node where pTerm[nTerm] marks the leftmost +** term in the tree. iChildBlock is the leftmost child block at the +** next level down the tree. +*/ +static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm, + sqlite_int64 iChildBlock, + InteriorWriter *pWriter){ + InteriorBlock *block; + assert( iHeight>0 ); + CLEAR(pWriter); + + pWriter->iHeight = iHeight; + pWriter->iOpeningChildBlock = iChildBlock; +#ifndef NDEBUG + pWriter->iLastChildBlock = iChildBlock; +#endif + block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm); + pWriter->last = pWriter->first = block; + ASSERT_VALID_INTERIOR_BLOCK(pWriter->last); + dataBufferInit(&pWriter->term, 0); +} + +/* Append the child node rooted at iChildBlock to the interior node, +** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree. +*/ +static void interiorWriterAppend(InteriorWriter *pWriter, + const char *pTerm, int nTerm, + sqlite_int64 iChildBlock){ + char c[VARINT_MAX+VARINT_MAX]; + int n, nPrefix = 0; + + ASSERT_VALID_INTERIOR_BLOCK(pWriter->last); + + /* The first term written into an interior node is actually + ** associated with the second child added (the first child was added + ** in interiorWriterInit, or in the if clause at the bottom of this + ** function). That term gets encoded straight up, with nPrefix left + ** at 0. + */ + if( pWriter->term.nData==0 ){ + n = putVarint(c, nTerm); + }else{ + while( nPrefixterm.nData && + pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){ + nPrefix++; + } + + n = putVarint(c, nPrefix); + n += putVarint(c+n, nTerm-nPrefix); + } + +#ifndef NDEBUG + pWriter->iLastChildBlock++; +#endif + assert( pWriter->iLastChildBlock==iChildBlock ); + + /* Overflow to a new block if the new term makes the current block + ** too big, and the current block already has enough terms. + */ + if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX && + iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){ + pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock, + pTerm, nTerm); + pWriter->last = pWriter->last->next; + pWriter->iOpeningChildBlock = iChildBlock; + dataBufferReset(&pWriter->term); + }else{ + dataBufferAppend2(&pWriter->last->data, c, n, + pTerm+nPrefix, nTerm-nPrefix); + dataBufferReplace(&pWriter->term, pTerm, nTerm); + } + ASSERT_VALID_INTERIOR_BLOCK(pWriter->last); +} + +/* Free the space used by pWriter, including the linked-list of +** InteriorBlocks, and parentWriter, if present. +*/ +static int interiorWriterDestroy(InteriorWriter *pWriter){ + InteriorBlock *block = pWriter->first; + + while( block!=NULL ){ + InteriorBlock *b = block; + block = block->next; + dataBufferDestroy(&b->term); + dataBufferDestroy(&b->data); + sqlite3_free(b); + } + if( pWriter->parentWriter!=NULL ){ + interiorWriterDestroy(pWriter->parentWriter); + sqlite3_free(pWriter->parentWriter); + } + dataBufferDestroy(&pWriter->term); + SCRAMBLE(pWriter); + return SQLITE_OK; +} + +/* If pWriter can fit entirely in ROOT_MAX, return it as the root info +** directly, leaving *piEndBlockid unchanged. Otherwise, flush +** pWriter to %_segments, building a new layer of interior nodes, and +** recursively ask for their root into. +*/ +static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter, + char **ppRootInfo, int *pnRootInfo, + sqlite_int64 *piEndBlockid){ + InteriorBlock *block = pWriter->first; + sqlite_int64 iBlockid = 0; + int rc; + + /* If we can fit the segment inline */ + if( block==pWriter->last && block->data.nDatadata.pData; + *pnRootInfo = block->data.nData; + return SQLITE_OK; + } + + /* Flush the first block to %_segments, and create a new level of + ** interior node. + */ + ASSERT_VALID_INTERIOR_BLOCK(block); + rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid); + if( rc!=SQLITE_OK ) return rc; + *piEndBlockid = iBlockid; + + pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter)); + interiorWriterInit(pWriter->iHeight+1, + block->term.pData, block->term.nData, + iBlockid, pWriter->parentWriter); + + /* Flush additional blocks and append to the higher interior + ** node. + */ + for(block=block->next; block!=NULL; block=block->next){ + ASSERT_VALID_INTERIOR_BLOCK(block); + rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid); + if( rc!=SQLITE_OK ) return rc; + *piEndBlockid = iBlockid; + + interiorWriterAppend(pWriter->parentWriter, + block->term.pData, block->term.nData, iBlockid); + } + + /* Parent node gets the chance to be the root. */ + return interiorWriterRootInfo(v, pWriter->parentWriter, + ppRootInfo, pnRootInfo, piEndBlockid); +} + +/****************************************************************/ +/* InteriorReader is used to read off the data from an interior node +** (see comment at top of file for the format). +*/ +typedef struct InteriorReader { + const char *pData; + int nData; + + DataBuffer term; /* previous term, for decoding term delta. */ + + sqlite_int64 iBlockid; +} InteriorReader; + +static void interiorReaderDestroy(InteriorReader *pReader){ + dataBufferDestroy(&pReader->term); + SCRAMBLE(pReader); +} + +/* TODO(shess) The assertions are great, but what if we're in NDEBUG +** and the blob is empty or otherwise contains suspect data? +*/ +static void interiorReaderInit(const char *pData, int nData, + InteriorReader *pReader){ + int n, nTerm; + + /* Require at least the leading flag byte */ + assert( nData>0 ); + assert( pData[0]!='\0' ); + + CLEAR(pReader); + + /* Decode the base blockid, and set the cursor to the first term. */ + n = getVarint(pData+1, &pReader->iBlockid); + assert( 1+n<=nData ); + pReader->pData = pData+1+n; + pReader->nData = nData-(1+n); + + /* A single-child interior node (such as when a leaf node was too + ** large for the segment directory) won't have any terms. + ** Otherwise, decode the first term. + */ + if( pReader->nData==0 ){ + dataBufferInit(&pReader->term, 0); + }else{ + n = getVarint32(pReader->pData, &nTerm); + dataBufferInit(&pReader->term, nTerm); + dataBufferReplace(&pReader->term, pReader->pData+n, nTerm); + assert( n+nTerm<=pReader->nData ); + pReader->pData += n+nTerm; + pReader->nData -= n+nTerm; + } +} + +static int interiorReaderAtEnd(InteriorReader *pReader){ + return pReader->term.nData==0; +} + +static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){ + return pReader->iBlockid; +} + +static int interiorReaderTermBytes(InteriorReader *pReader){ + assert( !interiorReaderAtEnd(pReader) ); + return pReader->term.nData; +} +static const char *interiorReaderTerm(InteriorReader *pReader){ + assert( !interiorReaderAtEnd(pReader) ); + return pReader->term.pData; +} + +/* Step forward to the next term in the node. */ +static void interiorReaderStep(InteriorReader *pReader){ + assert( !interiorReaderAtEnd(pReader) ); + + /* If the last term has been read, signal eof, else construct the + ** next term. + */ + if( pReader->nData==0 ){ + dataBufferReset(&pReader->term); + }else{ + int n, nPrefix, nSuffix; + + n = getVarint32(pReader->pData, &nPrefix); + n += getVarint32(pReader->pData+n, &nSuffix); + + /* Truncate the current term and append suffix data. */ + pReader->term.nData = nPrefix; + dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix); + + assert( n+nSuffix<=pReader->nData ); + pReader->pData += n+nSuffix; + pReader->nData -= n+nSuffix; + } + pReader->iBlockid++; +} + +/* Compare the current term to pTerm[nTerm], returning strcmp-style +** results. If isPrefix, equality means equal through nTerm bytes. +*/ +static int interiorReaderTermCmp(InteriorReader *pReader, + const char *pTerm, int nTerm, int isPrefix){ + const char *pReaderTerm = interiorReaderTerm(pReader); + int nReaderTerm = interiorReaderTermBytes(pReader); + int c, n = nReaderTerm0 ) return -1; + if( nTerm>0 ) return 1; + return 0; + } + + c = memcmp(pReaderTerm, pTerm, n); + if( c!=0 ) return c; + if( isPrefix && n==nTerm ) return 0; + return nReaderTerm - nTerm; +} + +/****************************************************************/ +/* LeafWriter is used to collect terms and associated doclist data +** into leaf blocks in %_segments (see top of file for format info). +** Expected usage is: +** +** LeafWriter writer; +** leafWriterInit(0, 0, &writer); +** while( sorted_terms_left_to_process ){ +** // data is doclist data for that term. +** rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData); +** if( rc!=SQLITE_OK ) goto err; +** } +** rc = leafWriterFinalize(v, &writer); +**err: +** leafWriterDestroy(&writer); +** return rc; +** +** leafWriterStep() may write a collected leaf out to %_segments. +** leafWriterFinalize() finishes writing any buffered data and stores +** a root node in %_segdir. leafWriterDestroy() frees all buffers and +** InteriorWriters allocated as part of writing this segment. +** +** TODO(shess) Document leafWriterStepMerge(). +*/ + +/* Put terms with data this big in their own block. */ +#define STANDALONE_MIN 1024 + +/* Keep leaf blocks below this size. */ +#define LEAF_MAX 2048 + +typedef struct LeafWriter { + int iLevel; + int idx; + sqlite_int64 iStartBlockid; /* needed to create the root info */ + sqlite_int64 iEndBlockid; /* when we're done writing. */ + + DataBuffer term; /* previous encoded term */ + DataBuffer data; /* encoding buffer */ + + /* bytes of first term in the current node which distinguishes that + ** term from the last term of the previous node. + */ + int nTermDistinct; + + InteriorWriter parentWriter; /* if we overflow */ + int has_parent; +} LeafWriter; + +static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){ + CLEAR(pWriter); + pWriter->iLevel = iLevel; + pWriter->idx = idx; + + dataBufferInit(&pWriter->term, 32); + + /* Start out with a reasonably sized block, though it can grow. */ + dataBufferInit(&pWriter->data, LEAF_MAX); +} + +#ifndef NDEBUG +/* Verify that the data is readable as a leaf node. */ +static void leafNodeValidate(const char *pData, int nData){ + int n, iDummy; + + if( nData==0 ) return; + assert( nData>0 ); + assert( pData!=0 ); + assert( pData+nData>pData ); + + /* Must lead with a varint(0) */ + n = getVarint32(pData, &iDummy); + assert( iDummy==0 ); + assert( n>0 ); + assert( n0 ); + assert( iDummy>0 ); + assert( n+iDummy>0 ); + assert( n+iDummy0 ); + assert( iDummy>0 ); + assert( n+iDummy>0 ); + assert( n+iDummy<=nData ); + ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL); + pData += n+iDummy; + nData -= n+iDummy; + + /* Verify that trailing terms and doclists also are readable. */ + while( nData!=0 ){ + n = getVarint32(pData, &iDummy); + assert( n>0 ); + assert( iDummy>=0 ); + assert( n0 ); + assert( iDummy>0 ); + assert( n+iDummy>0 ); + assert( n+iDummy0 ); + assert( iDummy>0 ); + assert( n+iDummy>0 ); + assert( n+iDummy<=nData ); + ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL); + pData += n+iDummy; + nData -= n+iDummy; + } +} +#define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n) +#else +#define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 ) +#endif + +/* Flush the current leaf node to %_segments, and adding the resulting +** blockid and the starting term to the interior node which will +** contain it. +*/ +static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter, + int iData, int nData){ + sqlite_int64 iBlockid = 0; + const char *pStartingTerm; + int nStartingTerm, rc, n; + + /* Must have the leading varint(0) flag, plus at least some + ** valid-looking data. + */ + assert( nData>2 ); + assert( iData>=0 ); + assert( iData+nData<=pWriter->data.nData ); + ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData); + + rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid); + if( rc!=SQLITE_OK ) return rc; + assert( iBlockid!=0 ); + + /* Reconstruct the first term in the leaf for purposes of building + ** the interior node. + */ + n = getVarint32(pWriter->data.pData+iData+1, &nStartingTerm); + pStartingTerm = pWriter->data.pData+iData+1+n; + assert( pWriter->data.nData>iData+1+n+nStartingTerm ); + assert( pWriter->nTermDistinct>0 ); + assert( pWriter->nTermDistinct<=nStartingTerm ); + nStartingTerm = pWriter->nTermDistinct; + + if( pWriter->has_parent ){ + interiorWriterAppend(&pWriter->parentWriter, + pStartingTerm, nStartingTerm, iBlockid); + }else{ + interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid, + &pWriter->parentWriter); + pWriter->has_parent = 1; + } + + /* Track the span of this segment's leaf nodes. */ + if( pWriter->iEndBlockid==0 ){ + pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid; + }else{ + pWriter->iEndBlockid++; + assert( iBlockid==pWriter->iEndBlockid ); + } + + return SQLITE_OK; +} +static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){ + int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData); + if( rc!=SQLITE_OK ) return rc; + + /* Re-initialize the output buffer. */ + dataBufferReset(&pWriter->data); + + return SQLITE_OK; +} + +/* Fetch the root info for the segment. If the entire leaf fits +** within ROOT_MAX, then it will be returned directly, otherwise it +** will be flushed and the root info will be returned from the +** interior node. *piEndBlockid is set to the blockid of the last +** interior or leaf node written to disk (0 if none are written at +** all). +*/ +static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter, + char **ppRootInfo, int *pnRootInfo, + sqlite_int64 *piEndBlockid){ + /* we can fit the segment entirely inline */ + if( !pWriter->has_parent && pWriter->data.nDatadata.pData; + *pnRootInfo = pWriter->data.nData; + *piEndBlockid = 0; + return SQLITE_OK; + } + + /* Flush remaining leaf data. */ + if( pWriter->data.nData>0 ){ + int rc = leafWriterFlush(v, pWriter); + if( rc!=SQLITE_OK ) return rc; + } + + /* We must have flushed a leaf at some point. */ + assert( pWriter->has_parent ); + + /* Tenatively set the end leaf blockid as the end blockid. If the + ** interior node can be returned inline, this will be the final + ** blockid, otherwise it will be overwritten by + ** interiorWriterRootInfo(). + */ + *piEndBlockid = pWriter->iEndBlockid; + + return interiorWriterRootInfo(v, &pWriter->parentWriter, + ppRootInfo, pnRootInfo, piEndBlockid); +} + +/* Collect the rootInfo data and store it into the segment directory. +** This has the effect of flushing the segment's leaf data to +** %_segments, and also flushing any interior nodes to %_segments. +*/ +static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){ + sqlite_int64 iEndBlockid; + char *pRootInfo; + int rc, nRootInfo; + + rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid); + if( rc!=SQLITE_OK ) return rc; + + /* Don't bother storing an entirely empty segment. */ + if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK; + + return segdir_set(v, pWriter->iLevel, pWriter->idx, + pWriter->iStartBlockid, pWriter->iEndBlockid, + iEndBlockid, pRootInfo, nRootInfo); +} + +static void leafWriterDestroy(LeafWriter *pWriter){ + if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter); + dataBufferDestroy(&pWriter->term); + dataBufferDestroy(&pWriter->data); +} + +/* Encode a term into the leafWriter, delta-encoding as appropriate. +** Returns the length of the new term which distinguishes it from the +** previous term, which can be used to set nTermDistinct when a node +** boundary is crossed. +*/ +static int leafWriterEncodeTerm(LeafWriter *pWriter, + const char *pTerm, int nTerm){ + char c[VARINT_MAX+VARINT_MAX]; + int n, nPrefix = 0; + + assert( nTerm>0 ); + while( nPrefixterm.nData && + pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){ + nPrefix++; + /* Failing this implies that the terms weren't in order. */ + assert( nPrefixdata.nData==0 ){ + /* Encode the node header and leading term as: + ** varint(0) + ** varint(nTerm) + ** char pTerm[nTerm] + */ + n = putVarint(c, '\0'); + n += putVarint(c+n, nTerm); + dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm); + }else{ + /* Delta-encode the term as: + ** varint(nPrefix) + ** varint(nSuffix) + ** char pTermSuffix[nSuffix] + */ + n = putVarint(c, nPrefix); + n += putVarint(c+n, nTerm-nPrefix); + dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix); + } + dataBufferReplace(&pWriter->term, pTerm, nTerm); + + return nPrefix+1; +} + +/* Used to avoid a memmove when a large amount of doclist data is in +** the buffer. This constructs a node and term header before +** iDoclistData and flushes the resulting complete node using +** leafWriterInternalFlush(). +*/ +static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter, + const char *pTerm, int nTerm, + int iDoclistData){ + char c[VARINT_MAX+VARINT_MAX]; + int iData, n = putVarint(c, 0); + n += putVarint(c+n, nTerm); + + /* There should always be room for the header. Even if pTerm shared + ** a substantial prefix with the previous term, the entire prefix + ** could be constructed from earlier data in the doclist, so there + ** should be room. + */ + assert( iDoclistData>=n+nTerm ); + + iData = iDoclistData-(n+nTerm); + memcpy(pWriter->data.pData+iData, c, n); + memcpy(pWriter->data.pData+iData+n, pTerm, nTerm); + + return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData); +} + +/* Push pTerm[nTerm] along with the doclist data to the leaf layer of +** %_segments. +*/ +static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter, + const char *pTerm, int nTerm, + DLReader *pReaders, int nReaders){ + char c[VARINT_MAX+VARINT_MAX]; + int iTermData = pWriter->data.nData, iDoclistData; + int i, nData, n, nActualData, nActual, rc, nTermDistinct; + + ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData); + nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm); + + /* Remember nTermDistinct if opening a new node. */ + if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct; + + iDoclistData = pWriter->data.nData; + + /* Estimate the length of the merged doclist so we can leave space + ** to encode it. + */ + for(i=0, nData=0; idata, c, n); + + docListMerge(&pWriter->data, pReaders, nReaders); + ASSERT_VALID_DOCLIST(DL_DEFAULT, + pWriter->data.pData+iDoclistData+n, + pWriter->data.nData-iDoclistData-n, NULL); + + /* The actual amount of doclist data at this point could be smaller + ** than the length we encoded. Additionally, the space required to + ** encode this length could be smaller. For small doclists, this is + ** not a big deal, we can just use memmove() to adjust things. + */ + nActualData = pWriter->data.nData-(iDoclistData+n); + nActual = putVarint(c, nActualData); + assert( nActualData<=nData ); + assert( nActual<=n ); + + /* If the new doclist is big enough for force a standalone leaf + ** node, we can immediately flush it inline without doing the + ** memmove(). + */ + /* TODO(shess) This test matches leafWriterStep(), which does this + ** test before it knows the cost to varint-encode the term and + ** doclist lengths. At some point, change to + ** pWriter->data.nData-iTermData>STANDALONE_MIN. + */ + if( nTerm+nActualData>STANDALONE_MIN ){ + /* Push leaf node from before this term. */ + if( iTermData>0 ){ + rc = leafWriterInternalFlush(v, pWriter, 0, iTermData); + if( rc!=SQLITE_OK ) return rc; + + pWriter->nTermDistinct = nTermDistinct; + } + + /* Fix the encoded doclist length. */ + iDoclistData += n - nActual; + memcpy(pWriter->data.pData+iDoclistData, c, nActual); + + /* Push the standalone leaf node. */ + rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData); + if( rc!=SQLITE_OK ) return rc; + + /* Leave the node empty. */ + dataBufferReset(&pWriter->data); + + return rc; + } + + /* At this point, we know that the doclist was small, so do the + ** memmove if indicated. + */ + if( nActualdata.pData+iDoclistData+nActual, + pWriter->data.pData+iDoclistData+n, + pWriter->data.nData-(iDoclistData+n)); + pWriter->data.nData -= n-nActual; + } + + /* Replace written length with actual length. */ + memcpy(pWriter->data.pData+iDoclistData, c, nActual); + + /* If the node is too large, break things up. */ + /* TODO(shess) This test matches leafWriterStep(), which does this + ** test before it knows the cost to varint-encode the term and + ** doclist lengths. At some point, change to + ** pWriter->data.nData>LEAF_MAX. + */ + if( iTermData+nTerm+nActualData>LEAF_MAX ){ + /* Flush out the leading data as a node */ + rc = leafWriterInternalFlush(v, pWriter, 0, iTermData); + if( rc!=SQLITE_OK ) return rc; + + pWriter->nTermDistinct = nTermDistinct; + + /* Rebuild header using the current term */ + n = putVarint(pWriter->data.pData, 0); + n += putVarint(pWriter->data.pData+n, nTerm); + memcpy(pWriter->data.pData+n, pTerm, nTerm); + n += nTerm; + + /* There should always be room, because the previous encoding + ** included all data necessary to construct the term. + */ + assert( ndata.nData-iDoclistDatadata.pData+n, + pWriter->data.pData+iDoclistData, + pWriter->data.nData-iDoclistData); + pWriter->data.nData -= iDoclistData-n; + } + ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData); + + return SQLITE_OK; +} + +/* Push pTerm[nTerm] along with the doclist data to the leaf layer of +** %_segments. +*/ +/* TODO(shess) Revise writeZeroSegment() so that doclists are +** constructed directly in pWriter->data. +*/ +static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter, + const char *pTerm, int nTerm, + const char *pData, int nData){ + int rc; + DLReader reader; + + dlrInit(&reader, DL_DEFAULT, pData, nData); + rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1); + dlrDestroy(&reader); + + return rc; +} + + +/****************************************************************/ +/* LeafReader is used to iterate over an individual leaf node. */ +typedef struct LeafReader { + DataBuffer term; /* copy of current term. */ + + const char *pData; /* data for current term. */ + int nData; +} LeafReader; + +static void leafReaderDestroy(LeafReader *pReader){ + dataBufferDestroy(&pReader->term); + SCRAMBLE(pReader); +} + +static int leafReaderAtEnd(LeafReader *pReader){ + return pReader->nData<=0; +} + +/* Access the current term. */ +static int leafReaderTermBytes(LeafReader *pReader){ + return pReader->term.nData; +} +static const char *leafReaderTerm(LeafReader *pReader){ + assert( pReader->term.nData>0 ); + return pReader->term.pData; +} + +/* Access the doclist data for the current term. */ +static int leafReaderDataBytes(LeafReader *pReader){ + int nData; + assert( pReader->term.nData>0 ); + getVarint32(pReader->pData, &nData); + return nData; +} +static const char *leafReaderData(LeafReader *pReader){ + int n, nData; + assert( pReader->term.nData>0 ); + n = getVarint32(pReader->pData, &nData); + return pReader->pData+n; +} + +static void leafReaderInit(const char *pData, int nData, + LeafReader *pReader){ + int nTerm, n; + + assert( nData>0 ); + assert( pData[0]=='\0' ); + + CLEAR(pReader); + + /* Read the first term, skipping the header byte. */ + n = getVarint32(pData+1, &nTerm); + dataBufferInit(&pReader->term, nTerm); + dataBufferReplace(&pReader->term, pData+1+n, nTerm); + + /* Position after the first term. */ + assert( 1+n+nTermpData = pData+1+n+nTerm; + pReader->nData = nData-1-n-nTerm; +} + +/* Step the reader forward to the next term. */ +static void leafReaderStep(LeafReader *pReader){ + int n, nData, nPrefix, nSuffix; + assert( !leafReaderAtEnd(pReader) ); + + /* Skip previous entry's data block. */ + n = getVarint32(pReader->pData, &nData); + assert( n+nData<=pReader->nData ); + pReader->pData += n+nData; + pReader->nData -= n+nData; + + if( !leafReaderAtEnd(pReader) ){ + /* Construct the new term using a prefix from the old term plus a + ** suffix from the leaf data. + */ + n = getVarint32(pReader->pData, &nPrefix); + n += getVarint32(pReader->pData+n, &nSuffix); + assert( n+nSuffixnData ); + pReader->term.nData = nPrefix; + dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix); + + pReader->pData += n+nSuffix; + pReader->nData -= n+nSuffix; + } +} + +/* strcmp-style comparison of pReader's current term against pTerm. +** If isPrefix, equality means equal through nTerm bytes. +*/ +static int leafReaderTermCmp(LeafReader *pReader, + const char *pTerm, int nTerm, int isPrefix){ + int c, n = pReader->term.nDataterm.nData : nTerm; + if( n==0 ){ + if( pReader->term.nData>0 ) return -1; + if(nTerm>0 ) return 1; + return 0; + } + + c = memcmp(pReader->term.pData, pTerm, n); + if( c!=0 ) return c; + if( isPrefix && n==nTerm ) return 0; + return pReader->term.nData - nTerm; +} + + +/****************************************************************/ +/* LeavesReader wraps LeafReader to allow iterating over the entire +** leaf layer of the tree. +*/ +typedef struct LeavesReader { + int idx; /* Index within the segment. */ + + sqlite3_stmt *pStmt; /* Statement we're streaming leaves from. */ + int eof; /* we've seen SQLITE_DONE from pStmt. */ + + LeafReader leafReader; /* reader for the current leaf. */ + DataBuffer rootData; /* root data for inline. */ +} LeavesReader; + +/* Access the current term. */ +static int leavesReaderTermBytes(LeavesReader *pReader){ + assert( !pReader->eof ); + return leafReaderTermBytes(&pReader->leafReader); +} +static const char *leavesReaderTerm(LeavesReader *pReader){ + assert( !pReader->eof ); + return leafReaderTerm(&pReader->leafReader); +} + +/* Access the doclist data for the current term. */ +static int leavesReaderDataBytes(LeavesReader *pReader){ + assert( !pReader->eof ); + return leafReaderDataBytes(&pReader->leafReader); +} +static const char *leavesReaderData(LeavesReader *pReader){ + assert( !pReader->eof ); + return leafReaderData(&pReader->leafReader); +} + +static int leavesReaderAtEnd(LeavesReader *pReader){ + return pReader->eof; +} + +/* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus +** leaving the statement handle open, which locks the table. +*/ +/* TODO(shess) This "solution" is not satisfactory. Really, there +** should be check-in function for all statement handles which +** arranges to call sqlite3_reset(). This most likely will require +** modification to control flow all over the place, though, so for now +** just punt. +** +** Note the current system assumes that segment merges will run to +** completion, which is why this particular probably hasn't arisen in +** this case. Probably a brittle assumption. +*/ +static int leavesReaderReset(LeavesReader *pReader){ + return sqlite3_reset(pReader->pStmt); +} + +static void leavesReaderDestroy(LeavesReader *pReader){ + /* If idx is -1, that means we're using a non-cached statement + ** handle in the optimize() case, so we need to release it. + */ + if( pReader->pStmt!=NULL && pReader->idx==-1 ){ + sqlite3_finalize(pReader->pStmt); + } + leafReaderDestroy(&pReader->leafReader); + dataBufferDestroy(&pReader->rootData); + SCRAMBLE(pReader); +} + +/* Initialize pReader with the given root data (if iStartBlockid==0 +** the leaf data was entirely contained in the root), or from the +** stream of blocks between iStartBlockid and iEndBlockid, inclusive. +*/ +static int leavesReaderInit(fulltext_vtab *v, + int idx, + sqlite_int64 iStartBlockid, + sqlite_int64 iEndBlockid, + const char *pRootData, int nRootData, + LeavesReader *pReader){ + CLEAR(pReader); + pReader->idx = idx; + + dataBufferInit(&pReader->rootData, 0); + if( iStartBlockid==0 ){ + /* Entire leaf level fit in root data. */ + dataBufferReplace(&pReader->rootData, pRootData, nRootData); + leafReaderInit(pReader->rootData.pData, pReader->rootData.nData, + &pReader->leafReader); + }else{ + sqlite3_stmt *s; + int rc = sql_get_leaf_statement(v, idx, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iStartBlockid); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 2, iEndBlockid); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_step(s); + if( rc==SQLITE_DONE ){ + pReader->eof = 1; + return SQLITE_OK; + } + if( rc!=SQLITE_ROW ) return rc; + + pReader->pStmt = s; + leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0), + sqlite3_column_bytes(pReader->pStmt, 0), + &pReader->leafReader); + } + return SQLITE_OK; +} + +/* Step the current leaf forward to the next term. If we reach the +** end of the current leaf, step forward to the next leaf block. +*/ +static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){ + assert( !leavesReaderAtEnd(pReader) ); + leafReaderStep(&pReader->leafReader); + + if( leafReaderAtEnd(&pReader->leafReader) ){ + int rc; + if( pReader->rootData.pData ){ + pReader->eof = 1; + return SQLITE_OK; + } + rc = sqlite3_step(pReader->pStmt); + if( rc!=SQLITE_ROW ){ + pReader->eof = 1; + return rc==SQLITE_DONE ? SQLITE_OK : rc; + } + leafReaderDestroy(&pReader->leafReader); + leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0), + sqlite3_column_bytes(pReader->pStmt, 0), + &pReader->leafReader); + } + return SQLITE_OK; +} + +/* Order LeavesReaders by their term, ignoring idx. Readers at eof +** always sort to the end. +*/ +static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){ + if( leavesReaderAtEnd(lr1) ){ + if( leavesReaderAtEnd(lr2) ) return 0; + return 1; + } + if( leavesReaderAtEnd(lr2) ) return -1; + + return leafReaderTermCmp(&lr1->leafReader, + leavesReaderTerm(lr2), leavesReaderTermBytes(lr2), + 0); +} + +/* Similar to leavesReaderTermCmp(), with additional ordering by idx +** so that older segments sort before newer segments. +*/ +static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){ + int c = leavesReaderTermCmp(lr1, lr2); + if( c!=0 ) return c; + return lr1->idx-lr2->idx; +} + +/* Assume that pLr[1]..pLr[nLr] are sorted. Bubble pLr[0] into its +** sorted position. +*/ +static void leavesReaderReorder(LeavesReader *pLr, int nLr){ + while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){ + LeavesReader tmp = pLr[0]; + pLr[0] = pLr[1]; + pLr[1] = tmp; + nLr--; + pLr++; + } +} + +/* Initializes pReaders with the segments from level iLevel, returning +** the number of segments in *piReaders. Leaves pReaders in sorted +** order. +*/ +static int leavesReadersInit(fulltext_vtab *v, int iLevel, + LeavesReader *pReaders, int *piReaders){ + sqlite3_stmt *s; + int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int(s, 1, iLevel); + if( rc!=SQLITE_OK ) return rc; + + i = 0; + while( (rc = sqlite3_step(s))==SQLITE_ROW ){ + sqlite_int64 iStart = sqlite3_column_int64(s, 0); + sqlite_int64 iEnd = sqlite3_column_int64(s, 1); + const char *pRootData = sqlite3_column_blob(s, 2); + int nRootData = sqlite3_column_bytes(s, 2); + + assert( i0 ){ + leavesReaderDestroy(&pReaders[i]); + } + return rc; + } + + *piReaders = i; + + /* Leave our results sorted by term, then age. */ + while( i-- ){ + leavesReaderReorder(pReaders+i, *piReaders-i); + } + return SQLITE_OK; +} + +/* Merge doclists from pReaders[nReaders] into a single doclist, which +** is written to pWriter. Assumes pReaders is ordered oldest to +** newest. +*/ +/* TODO(shess) Consider putting this inline in segmentMerge(). */ +static int leavesReadersMerge(fulltext_vtab *v, + LeavesReader *pReaders, int nReaders, + LeafWriter *pWriter){ + DLReader dlReaders[MERGE_COUNT]; + const char *pTerm = leavesReaderTerm(pReaders); + int i, nTerm = leavesReaderTermBytes(pReaders); + + assert( nReaders<=MERGE_COUNT ); + + for(i=0; i0 ){ + rc = leavesReaderStep(v, lrs+i); + if( rc!=SQLITE_OK ) goto err; + + /* Reorder by term, then by age. */ + leavesReaderReorder(lrs+i, MERGE_COUNT-i); + } + } + + for(i=0; i0 ); + + for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader); + rc=leavesReaderStep(v, pReader)){ + /* TODO(shess) Really want leavesReaderTermCmp(), but that name is + ** already taken to compare the terms of two LeavesReaders. Think + ** on a better name. [Meanwhile, break encapsulation rather than + ** use a confusing name.] + */ + int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix); + if( c>0 ) break; /* Past any possible matches. */ + if( c==0 ){ + const char *pData = leavesReaderData(pReader); + int iBuffer, nData = leavesReaderDataBytes(pReader); + + /* Find the first empty buffer. */ + for(iBuffer=0; iBuffer0 ){ + assert(pBuffers!=NULL); + memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers)); + sqlite3_free(pBuffers); + } + pBuffers = p; + } + dataBufferInit(&(pBuffers[nBuffers]), 0); + nBuffers++; + } + + /* At this point, must have an empty at iBuffer. */ + assert(iBufferpData, p->nData); + + /* dataBufferReset() could allow a large doclist to blow up + ** our memory requirements. + */ + if( p->nCapacity<1024 ){ + dataBufferReset(p); + }else{ + dataBufferDestroy(p); + dataBufferInit(p, 0); + } + } + } + } + } + + /* Union all the doclists together into *out. */ + /* TODO(shess) What if *out is big? Sigh. */ + if( rc==SQLITE_OK && nBuffers>0 ){ + int iBuffer; + for(iBuffer=0; iBuffer0 ){ + if( out->nData==0 ){ + dataBufferSwap(out, &(pBuffers[iBuffer])); + }else{ + docListAccumulateUnion(out, pBuffers[iBuffer].pData, + pBuffers[iBuffer].nData); + } + } + } + } + + while( nBuffers-- ){ + dataBufferDestroy(&(pBuffers[nBuffers])); + } + if( pBuffers!=NULL ) sqlite3_free(pBuffers); + + return rc; +} + +/* Call loadSegmentLeavesInt() with pData/nData as input. */ +static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData, + const char *pTerm, int nTerm, int isPrefix, + DataBuffer *out){ + LeavesReader reader; + int rc; + + assert( nData>1 ); + assert( *pData=='\0' ); + rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader); + if( rc!=SQLITE_OK ) return rc; + + rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out); + leavesReaderReset(&reader); + leavesReaderDestroy(&reader); + return rc; +} + +/* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to +** iEndLeaf (inclusive) as input, and merge the resulting doclist into +** out. +*/ +static int loadSegmentLeaves(fulltext_vtab *v, + sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf, + const char *pTerm, int nTerm, int isPrefix, + DataBuffer *out){ + int rc; + LeavesReader reader; + + assert( iStartLeaf<=iEndLeaf ); + rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader); + if( rc!=SQLITE_OK ) return rc; + + rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out); + leavesReaderReset(&reader); + leavesReaderDestroy(&reader); + return rc; +} + +/* Taking pData/nData as an interior node, find the sequence of child +** nodes which could include pTerm/nTerm/isPrefix. Note that the +** interior node terms logically come between the blocks, so there is +** one more blockid than there are terms (that block contains terms >= +** the last interior-node term). +*/ +/* TODO(shess) The calling code may already know that the end child is +** not worth calculating, because the end may be in a later sibling +** node. Consider whether breaking symmetry is worthwhile. I suspect +** it is not worthwhile. +*/ +static void getChildrenContaining(const char *pData, int nData, + const char *pTerm, int nTerm, int isPrefix, + sqlite_int64 *piStartChild, + sqlite_int64 *piEndChild){ + InteriorReader reader; + + assert( nData>1 ); + assert( *pData!='\0' ); + interiorReaderInit(pData, nData, &reader); + + /* Scan for the first child which could contain pTerm/nTerm. */ + while( !interiorReaderAtEnd(&reader) ){ + if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break; + interiorReaderStep(&reader); + } + *piStartChild = interiorReaderCurrentBlockid(&reader); + + /* Keep scanning to find a term greater than our term, using prefix + ** comparison if indicated. If isPrefix is false, this will be the + ** same blockid as the starting block. + */ + while( !interiorReaderAtEnd(&reader) ){ + if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break; + interiorReaderStep(&reader); + } + *piEndChild = interiorReaderCurrentBlockid(&reader); + + interiorReaderDestroy(&reader); + + /* Children must ascend, and if !prefix, both must be the same. */ + assert( *piEndChild>=*piStartChild ); + assert( isPrefix || *piStartChild==*piEndChild ); +} + +/* Read block at iBlockid and pass it with other params to +** getChildrenContaining(). +*/ +static int loadAndGetChildrenContaining( + fulltext_vtab *v, + sqlite_int64 iBlockid, + const char *pTerm, int nTerm, int isPrefix, + sqlite_int64 *piStartChild, sqlite_int64 *piEndChild +){ + sqlite3_stmt *s = NULL; + int rc; + + assert( iBlockid!=0 ); + assert( pTerm!=NULL ); + assert( nTerm!=0 ); /* TODO(shess) Why not allow this? */ + assert( piStartChild!=NULL ); + assert( piEndChild!=NULL ); + + rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_bind_int64(s, 1, iBlockid); + if( rc!=SQLITE_OK ) return rc; + + rc = sqlite3_step(s); + if( rc==SQLITE_DONE ) return SQLITE_ERROR; + if( rc!=SQLITE_ROW ) return rc; + + getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0), + pTerm, nTerm, isPrefix, piStartChild, piEndChild); + + /* We expect only one row. We must execute another sqlite3_step() + * to complete the iteration; otherwise the table will remain + * locked. */ + rc = sqlite3_step(s); + if( rc==SQLITE_ROW ) return SQLITE_ERROR; + if( rc!=SQLITE_DONE ) return rc; + + return SQLITE_OK; +} + +/* Traverse the tree represented by pData[nData] looking for +** pTerm[nTerm], placing its doclist into *out. This is internal to +** loadSegment() to make error-handling cleaner. +*/ +static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData, + sqlite_int64 iLeavesEnd, + const char *pTerm, int nTerm, int isPrefix, + DataBuffer *out){ + /* Special case where root is a leaf. */ + if( *pData=='\0' ){ + return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out); + }else{ + int rc; + sqlite_int64 iStartChild, iEndChild; + + /* Process pData as an interior node, then loop down the tree + ** until we find the set of leaf nodes to scan for the term. + */ + getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix, + &iStartChild, &iEndChild); + while( iStartChild>iLeavesEnd ){ + sqlite_int64 iNextStart, iNextEnd; + rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix, + &iNextStart, &iNextEnd); + if( rc!=SQLITE_OK ) return rc; + + /* If we've branched, follow the end branch, too. */ + if( iStartChild!=iEndChild ){ + sqlite_int64 iDummy; + rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix, + &iDummy, &iNextEnd); + if( rc!=SQLITE_OK ) return rc; + } + + assert( iNextStart<=iNextEnd ); + iStartChild = iNextStart; + iEndChild = iNextEnd; + } + assert( iStartChild<=iLeavesEnd ); + assert( iEndChild<=iLeavesEnd ); + + /* Scan through the leaf segments for doclists. */ + return loadSegmentLeaves(v, iStartChild, iEndChild, + pTerm, nTerm, isPrefix, out); + } +} + +/* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then +** merge its doclist over *out (any duplicate doclists read from the +** segment rooted at pData will overwrite those in *out). +*/ +/* TODO(shess) Consider changing this to determine the depth of the +** leaves using either the first characters of interior nodes (when +** ==1, we're one level above the leaves), or the first character of +** the root (which will describe the height of the tree directly). +** Either feels somewhat tricky to me. +*/ +/* TODO(shess) The current merge is likely to be slow for large +** doclists (though it should process from newest/smallest to +** oldest/largest, so it may not be that bad). It might be useful to +** modify things to allow for N-way merging. This could either be +** within a segment, with pairwise merges across segments, or across +** all segments at once. +*/ +static int loadSegment(fulltext_vtab *v, const char *pData, int nData, + sqlite_int64 iLeavesEnd, + const char *pTerm, int nTerm, int isPrefix, + DataBuffer *out){ + DataBuffer result; + int rc; + + assert( nData>1 ); + + /* This code should never be called with buffered updates. */ + assert( v->nPendingData<0 ); + + dataBufferInit(&result, 0); + rc = loadSegmentInt(v, pData, nData, iLeavesEnd, + pTerm, nTerm, isPrefix, &result); + if( rc==SQLITE_OK && result.nData>0 ){ + if( out->nData==0 ){ + DataBuffer tmp = *out; + *out = result; + result = tmp; + }else{ + DataBuffer merged; + DLReader readers[2]; + + dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData); + dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData); + dataBufferInit(&merged, out->nData+result.nData); + docListMerge(&merged, readers, 2); + dataBufferDestroy(out); + *out = merged; + dlrDestroy(&readers[0]); + dlrDestroy(&readers[1]); + } + } + dataBufferDestroy(&result); + return rc; +} + +/* Scan the database and merge together the posting lists for the term +** into *out. +*/ +static int termSelect(fulltext_vtab *v, int iColumn, + const char *pTerm, int nTerm, int isPrefix, + DocListType iType, DataBuffer *out){ + DataBuffer doclist; + sqlite3_stmt *s; + int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s); + if( rc!=SQLITE_OK ) return rc; + + /* This code should never be called with buffered updates. */ + assert( v->nPendingData<0 ); + + dataBufferInit(&doclist, 0); + + /* Traverse the segments from oldest to newest so that newer doclist + ** elements for given docids overwrite older elements. + */ + while( (rc = sqlite3_step(s))==SQLITE_ROW ){ + const char *pData = sqlite3_column_blob(s, 2); + const int nData = sqlite3_column_bytes(s, 2); + const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1); + rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix, + &doclist); + if( rc!=SQLITE_OK ) goto err; + } + if( rc==SQLITE_DONE ){ + if( doclist.nData!=0 ){ + /* TODO(shess) The old term_select_all() code applied the column + ** restrict as we merged segments, leading to smaller buffers. + ** This is probably worthwhile to bring back, once the new storage + ** system is checked in. + */ + if( iColumn==v->nColumn) iColumn = -1; + docListTrim(DL_DEFAULT, doclist.pData, doclist.nData, + iColumn, iType, out); + } + rc = SQLITE_OK; + } + + err: + dataBufferDestroy(&doclist); + return rc; +} + +/****************************************************************/ +/* Used to hold hashtable data for sorting. */ +typedef struct TermData { + const char *pTerm; + int nTerm; + DLCollector *pCollector; +} TermData; + +/* Orders TermData elements in strcmp fashion ( <0 for less-than, 0 +** for equal, >0 for greater-than). +*/ +static int termDataCmp(const void *av, const void *bv){ + const TermData *a = (const TermData *)av; + const TermData *b = (const TermData *)bv; + int n = a->nTermnTerm ? a->nTerm : b->nTerm; + int c = memcmp(a->pTerm, b->pTerm, n); + if( c!=0 ) return c; + return a->nTerm-b->nTerm; +} + +/* Order pTerms data by term, then write a new level 0 segment using +** LeafWriter. +*/ +static int writeZeroSegment(fulltext_vtab *v, fts2Hash *pTerms){ + fts2HashElem *e; + int idx, rc, i, n; + TermData *pData; + LeafWriter writer; + DataBuffer dl; + + /* Determine the next index at level 0, merging as necessary. */ + rc = segdirNextIndex(v, 0, &idx); + if( rc!=SQLITE_OK ) return rc; + + n = fts2HashCount(pTerms); + pData = sqlite3_malloc(n*sizeof(TermData)); + + for(i = 0, e = fts2HashFirst(pTerms); e; i++, e = fts2HashNext(e)){ + assert( i1 ) qsort(pData, n, sizeof(*pData), termDataCmp); + + /* TODO(shess) Refactor so that we can write directly to the segment + ** DataBuffer, as happens for segment merges. + */ + leafWriterInit(0, idx, &writer); + dataBufferInit(&dl, 0); + for(i=0; inPendingData>=0 ){ + fts2HashElem *e; + for(e=fts2HashFirst(&v->pendingTerms); e; e=fts2HashNext(e)){ + dlcDelete(fts2HashData(e)); + } + fts2HashClear(&v->pendingTerms); + v->nPendingData = -1; + } + return SQLITE_OK; +} + +/* If pendingTerms has data, flush it to a level-zero segment, and +** free it. +*/ +static int flushPendingTerms(fulltext_vtab *v){ + if( v->nPendingData>=0 ){ + int rc = writeZeroSegment(v, &v->pendingTerms); + if( rc==SQLITE_OK ) clearPendingTerms(v); + return rc; + } + return SQLITE_OK; +} + +/* If pendingTerms is "too big", or docid is out of order, flush it. +** Regardless, be certain that pendingTerms is initialized for use. +*/ +static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){ + /* TODO(shess) Explore whether partially flushing the buffer on + ** forced-flush would provide better performance. I suspect that if + ** we ordered the doclists by size and flushed the largest until the + ** buffer was half empty, that would let the less frequent terms + ** generate longer doclists. + */ + if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){ + int rc = flushPendingTerms(v); + if( rc!=SQLITE_OK ) return rc; + } + if( v->nPendingData<0 ){ + fts2HashInit(&v->pendingTerms, FTS2_HASH_STRING, 1); + v->nPendingData = 0; + } + v->iPrevDocid = iDocid; + return SQLITE_OK; +} + +/* This function implements the xUpdate callback; it is the top-level entry + * point for inserting, deleting or updating a row in a full-text table. */ +static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg, + sqlite_int64 *pRowid){ + fulltext_vtab *v = (fulltext_vtab *) pVtab; + int rc; + + TRACE(("FTS2 Update %p\n", pVtab)); + + if( nArg<2 ){ + rc = index_delete(v, sqlite3_value_int64(ppArg[0])); + if( rc==SQLITE_OK ){ + /* If we just deleted the last row in the table, clear out the + ** index data. + */ + rc = content_exists(v); + if( rc==SQLITE_ROW ){ + rc = SQLITE_OK; + }else if( rc==SQLITE_DONE ){ + /* Clear the pending terms so we don't flush a useless level-0 + ** segment when the transaction closes. + */ + rc = clearPendingTerms(v); + if( rc==SQLITE_OK ){ + rc = segdir_delete_all(v); + } + } + } + } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){ + /* An update: + * ppArg[0] = old rowid + * ppArg[1] = new rowid + * ppArg[2..2+v->nColumn-1] = values + * ppArg[2+v->nColumn] = value for magic column (we ignore this) + */ + sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]); + if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER || + sqlite3_value_int64(ppArg[1]) != rowid ){ + rc = SQLITE_ERROR; /* we don't allow changing the rowid */ + } else { + assert( nArg==2+v->nColumn+1); + rc = index_update(v, rowid, &ppArg[2]); + } + } else { + /* An insert: + * ppArg[1] = requested rowid + * ppArg[2..2+v->nColumn-1] = values + * ppArg[2+v->nColumn] = value for magic column (we ignore this) + */ + assert( nArg==2+v->nColumn+1); + rc = index_insert(v, ppArg[1], &ppArg[2], pRowid); + } + + return rc; +} + +static int fulltextSync(sqlite3_vtab *pVtab){ + TRACE(("FTS2 xSync()\n")); + return flushPendingTerms((fulltext_vtab *)pVtab); +} + +static int fulltextBegin(sqlite3_vtab *pVtab){ + fulltext_vtab *v = (fulltext_vtab *) pVtab; + TRACE(("FTS2 xBegin()\n")); + + /* Any buffered updates should have been cleared by the previous + ** transaction. + */ + assert( v->nPendingData<0 ); + return clearPendingTerms(v); +} + +static int fulltextCommit(sqlite3_vtab *pVtab){ + fulltext_vtab *v = (fulltext_vtab *) pVtab; + TRACE(("FTS2 xCommit()\n")); + + /* Buffered updates should have been cleared by fulltextSync(). */ + assert( v->nPendingData<0 ); + return clearPendingTerms(v); +} + +static int fulltextRollback(sqlite3_vtab *pVtab){ + TRACE(("FTS2 xRollback()\n")); + return clearPendingTerms((fulltext_vtab *)pVtab); +} + +/* +** Implementation of the snippet() function for FTS2 +*/ +static void snippetFunc( + sqlite3_context *pContext, + int argc, + sqlite3_value **argv +){ + fulltext_cursor *pCursor; + if( argc<1 ) return; + if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || + sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ + sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1); + }else{ + const char *zStart = ""; + const char *zEnd = ""; + const char *zEllipsis = "..."; + memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); + if( argc>=2 ){ + zStart = (const char*)sqlite3_value_text(argv[1]); + if( argc>=3 ){ + zEnd = (const char*)sqlite3_value_text(argv[2]); + if( argc>=4 ){ + zEllipsis = (const char*)sqlite3_value_text(argv[3]); + } + } + } + snippetAllOffsets(pCursor); + snippetText(pCursor, zStart, zEnd, zEllipsis); + sqlite3_result_text(pContext, pCursor->snippet.zSnippet, + pCursor->snippet.nSnippet, SQLITE_STATIC); + } +} + +/* +** Implementation of the offsets() function for FTS2 +*/ +static void snippetOffsetsFunc( + sqlite3_context *pContext, + int argc, + sqlite3_value **argv +){ + fulltext_cursor *pCursor; + if( argc<1 ) return; + if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || + sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ + sqlite3_result_error(pContext, "illegal first argument to offsets",-1); + }else{ + memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); + snippetAllOffsets(pCursor); + snippetOffsetText(&pCursor->snippet); + sqlite3_result_text(pContext, + pCursor->snippet.zOffset, pCursor->snippet.nOffset, + SQLITE_STATIC); + } +} + +/* OptLeavesReader is nearly identical to LeavesReader, except that +** where LeavesReader is geared towards the merging of complete +** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader +** is geared towards implementation of the optimize() function, and +** can merge all segments simultaneously. This version may be +** somewhat less efficient than LeavesReader because it merges into an +** accumulator rather than doing an N-way merge, but since segment +** size grows exponentially (so segment count logrithmically) this is +** probably not an immediate problem. +*/ +/* TODO(shess): Prove that assertion, or extend the merge code to +** merge tree fashion (like the prefix-searching code does). +*/ +/* TODO(shess): OptLeavesReader and LeavesReader could probably be +** merged with little or no loss of performance for LeavesReader. The +** merged code would need to handle >MERGE_COUNT segments, and would +** also need to be able to optionally optimize away deletes. +*/ +typedef struct OptLeavesReader { + /* Segment number, to order readers by age. */ + int segment; + LeavesReader reader; +} OptLeavesReader; + +static int optLeavesReaderAtEnd(OptLeavesReader *pReader){ + return leavesReaderAtEnd(&pReader->reader); +} +static int optLeavesReaderTermBytes(OptLeavesReader *pReader){ + return leavesReaderTermBytes(&pReader->reader); +} +static const char *optLeavesReaderData(OptLeavesReader *pReader){ + return leavesReaderData(&pReader->reader); +} +static int optLeavesReaderDataBytes(OptLeavesReader *pReader){ + return leavesReaderDataBytes(&pReader->reader); +} +static const char *optLeavesReaderTerm(OptLeavesReader *pReader){ + return leavesReaderTerm(&pReader->reader); +} +static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){ + return leavesReaderStep(v, &pReader->reader); +} +static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){ + return leavesReaderTermCmp(&lr1->reader, &lr2->reader); +} +/* Order by term ascending, segment ascending (oldest to newest), with +** exhausted readers to the end. +*/ +static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){ + int c = optLeavesReaderTermCmp(lr1, lr2); + if( c!=0 ) return c; + return lr1->segment-lr2->segment; +} +/* Bubble pLr[0] to appropriate place in pLr[1..nLr-1]. Assumes that +** pLr[1..nLr-1] is already sorted. +*/ +static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){ + while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){ + OptLeavesReader tmp = pLr[0]; + pLr[0] = pLr[1]; + pLr[1] = tmp; + nLr--; + pLr++; + } +} + +/* optimize() helper function. Put the readers in order and iterate +** through them, merging doclists for matching terms into pWriter. +** Returns SQLITE_OK on success, or the SQLite error code which +** prevented success. +*/ +static int optimizeInternal(fulltext_vtab *v, + OptLeavesReader *readers, int nReaders, + LeafWriter *pWriter){ + int i, rc = SQLITE_OK; + DataBuffer doclist, merged, tmp; + + /* Order the readers. */ + i = nReaders; + while( i-- > 0 ){ + optLeavesReaderReorder(&readers[i], nReaders-i); + } + + dataBufferInit(&doclist, LEAF_MAX); + dataBufferInit(&merged, LEAF_MAX); + + /* Exhausted readers bubble to the end, so when the first reader is + ** at eof, all are at eof. + */ + while( !optLeavesReaderAtEnd(&readers[0]) ){ + + /* Figure out how many readers share the next term. */ + for(i=1; i 0 ){ + dlrDestroy(&dlReaders[nReaders]); + } + + /* Accumulated doclist to reader 0 for next pass. */ + dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData); + } + + /* Destroy reader that was left in the pipeline. */ + dlrDestroy(&dlReaders[0]); + + /* Trim deletions from the doclist. */ + dataBufferReset(&merged); + docListTrim(DL_DEFAULT, doclist.pData, doclist.nData, + -1, DL_DEFAULT, &merged); + } + + /* Only pass doclists with hits (skip if all hits deleted). */ + if( merged.nData>0 ){ + rc = leafWriterStep(v, pWriter, + optLeavesReaderTerm(&readers[0]), + optLeavesReaderTermBytes(&readers[0]), + merged.pData, merged.nData); + if( rc!=SQLITE_OK ) goto err; + } + + /* Step merged readers to next term and reorder. */ + while( i-- > 0 ){ + rc = optLeavesReaderStep(v, &readers[i]); + if( rc!=SQLITE_OK ) goto err; + + optLeavesReaderReorder(&readers[i], nReaders-i); + } + } + + err: + dataBufferDestroy(&doclist); + dataBufferDestroy(&merged); + return rc; +} + +/* Implement optimize() function for FTS3. optimize(t) merges all +** segments in the fts index into a single segment. 't' is the magic +** table-named column. +*/ +static void optimizeFunc(sqlite3_context *pContext, + int argc, sqlite3_value **argv){ + fulltext_cursor *pCursor; + if( argc>1 ){ + sqlite3_result_error(pContext, "excess arguments to optimize()",-1); + }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || + sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ + sqlite3_result_error(pContext, "illegal first argument to optimize",-1); + }else{ + fulltext_vtab *v; + int i, rc, iMaxLevel; + OptLeavesReader *readers; + int nReaders; + LeafWriter writer; + sqlite3_stmt *s; + + memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); + v = cursor_vtab(pCursor); + + /* Flush any buffered updates before optimizing. */ + rc = flushPendingTerms(v); + if( rc!=SQLITE_OK ) goto err; + + rc = segdir_count(v, &nReaders, &iMaxLevel); + if( rc!=SQLITE_OK ) goto err; + if( nReaders==0 || nReaders==1 ){ + sqlite3_result_text(pContext, "Index already optimal", -1, + SQLITE_STATIC); + return; + } + + rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s); + if( rc!=SQLITE_OK ) goto err; + + readers = sqlite3_malloc(nReaders*sizeof(readers[0])); + if( readers==NULL ) goto err; + + /* Note that there will already be a segment at this position + ** until we call segdir_delete() on iMaxLevel. + */ + leafWriterInit(iMaxLevel, 0, &writer); + + i = 0; + while( (rc = sqlite3_step(s))==SQLITE_ROW ){ + sqlite_int64 iStart = sqlite3_column_int64(s, 0); + sqlite_int64 iEnd = sqlite3_column_int64(s, 1); + const char *pRootData = sqlite3_column_blob(s, 2); + int nRootData = sqlite3_column_bytes(s, 2); + + assert( i 0 ){ + leavesReaderDestroy(&readers[i].reader); + } + sqlite3_free(readers); + + /* If we've successfully gotten to here, delete the old segments + ** and flush the interior structure of the new segment. + */ + if( rc==SQLITE_OK ){ + for( i=0; i<=iMaxLevel; i++ ){ + rc = segdir_delete(v, i); + if( rc!=SQLITE_OK ) break; + } + + if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer); + } + + leafWriterDestroy(&writer); + + if( rc!=SQLITE_OK ) goto err; + + sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); + return; + + /* TODO(shess): Error-handling needs to be improved along the + ** lines of the dump_ functions. + */ + err: + { + char buf[512]; + sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s", + sqlite3_errmsg(sqlite3_context_db_handle(pContext))); + sqlite3_result_error(pContext, buf, -1); + } + } +} + +#ifdef SQLITE_TEST +/* Generate an error of the form ": ". If msg is NULL, +** pull the error from the context's db handle. +*/ +static void generateError(sqlite3_context *pContext, + const char *prefix, const char *msg){ + char buf[512]; + if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext)); + sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg); + sqlite3_result_error(pContext, buf, -1); +} + +/* Helper function to collect the set of terms in the segment into +** pTerms. The segment is defined by the leaf nodes between +** iStartBlockid and iEndBlockid, inclusive, or by the contents of +** pRootData if iStartBlockid is 0 (in which case the entire segment +** fit in a leaf). +*/ +static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s, + fts2Hash *pTerms){ + const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0); + const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1); + const char *pRootData = sqlite3_column_blob(s, 2); + const int nRootData = sqlite3_column_bytes(s, 2); + LeavesReader reader; + int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid, + pRootData, nRootData, &reader); + if( rc!=SQLITE_OK ) return rc; + + while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){ + const char *pTerm = leavesReaderTerm(&reader); + const int nTerm = leavesReaderTermBytes(&reader); + void *oldValue = sqlite3Fts2HashFind(pTerms, pTerm, nTerm); + void *newValue = (void *)((char *)oldValue+1); + + /* From the comment before sqlite3Fts2HashInsert in fts2_hash.c, + ** the data value passed is returned in case of malloc failure. + */ + if( newValue==sqlite3Fts2HashInsert(pTerms, pTerm, nTerm, newValue) ){ + rc = SQLITE_NOMEM; + }else{ + rc = leavesReaderStep(v, &reader); + } + } + + leavesReaderDestroy(&reader); + return rc; +} + +/* Helper function to build the result string for dump_terms(). */ +static int generateTermsResult(sqlite3_context *pContext, fts2Hash *pTerms){ + int iTerm, nTerms, nResultBytes, iByte; + char *result; + TermData *pData; + fts2HashElem *e; + + /* Iterate pTerms to generate an array of terms in pData for + ** sorting. + */ + nTerms = fts2HashCount(pTerms); + assert( nTerms>0 ); + pData = sqlite3_malloc(nTerms*sizeof(TermData)); + if( pData==NULL ) return SQLITE_NOMEM; + + nResultBytes = 0; + for(iTerm = 0, e = fts2HashFirst(pTerms); e; iTerm++, e = fts2HashNext(e)){ + nResultBytes += fts2HashKeysize(e)+1; /* Term plus trailing space */ + assert( iTerm0 ); /* nTerms>0, nResultsBytes must be, too. */ + result = sqlite3_malloc(nResultBytes); + if( result==NULL ){ + sqlite3_free(pData); + return SQLITE_NOMEM; + } + + if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp); + + /* Read the terms in order to build the result. */ + iByte = 0; + for(iTerm=0; iTerm0 ){ + rc = generateTermsResult(pContext, &terms); + if( rc==SQLITE_NOMEM ){ + generateError(pContext, "dump_terms", "out of memory"); + }else{ + assert( rc==SQLITE_OK ); + } + }else if( argc==3 ){ + /* The specific segment asked for could not be found. */ + generateError(pContext, "dump_terms", "segment not found"); + }else{ + /* No segments found. */ + /* TODO(shess): It should be impossible to reach this. This + ** case can only happen for an empty table, in which case + ** SQLite has no rows to call this function on. + */ + sqlite3_result_null(pContext); + } + } + sqlite3Fts2HashClear(&terms); + } +} + +/* Expand the DL_DEFAULT doclist in pData into a text result in +** pContext. +*/ +static void createDoclistResult(sqlite3_context *pContext, + const char *pData, int nData){ + DataBuffer dump; + DLReader dlReader; + + assert( pData!=NULL && nData>0 ); + + dataBufferInit(&dump, 0); + dlrInit(&dlReader, DL_DEFAULT, pData, nData); + for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){ + char buf[256]; + PLReader plReader; + + plrInit(&plReader, &dlReader); + if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){ + sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader)); + dataBufferAppend(&dump, buf, strlen(buf)); + }else{ + int iColumn = plrColumn(&plReader); + + sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[", + dlrDocid(&dlReader), iColumn); + dataBufferAppend(&dump, buf, strlen(buf)); + + for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){ + if( plrColumn(&plReader)!=iColumn ){ + iColumn = plrColumn(&plReader); + sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn); + assert( dump.nData>0 ); + dump.nData--; /* Overwrite trailing space. */ + assert( dump.pData[dump.nData]==' '); + dataBufferAppend(&dump, buf, strlen(buf)); + } + if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){ + sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ", + plrPosition(&plReader), + plrStartOffset(&plReader), plrEndOffset(&plReader)); + }else if( DL_DEFAULT==DL_POSITIONS ){ + sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader)); + }else{ + assert( NULL=="Unhandled DL_DEFAULT value"); + } + dataBufferAppend(&dump, buf, strlen(buf)); + } + plrDestroy(&plReader); + + assert( dump.nData>0 ); + dump.nData--; /* Overwrite trailing space. */ + assert( dump.pData[dump.nData]==' '); + dataBufferAppend(&dump, "]] ", 3); + } + } + dlrDestroy(&dlReader); + + assert( dump.nData>0 ); + dump.nData--; /* Overwrite trailing space. */ + assert( dump.pData[dump.nData]==' '); + dump.pData[dump.nData] = '\0'; + assert( dump.nData>0 ); + + /* Passes ownership of dump's buffer to pContext. */ + sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free); + dump.pData = NULL; + dump.nData = dump.nCapacity = 0; +} + +/* Implements dump_doclist() for use in inspecting the fts2 index from +** tests. TEXT result containing a string representation of the +** doclist for the indicated term. dump_doclist(t, term, level, idx) +** dumps the doclist for term from the segment specified by level, idx +** (in %_segdir), while dump_doclist(t, term) dumps the logical +** doclist for the term across all segments. The per-segment doclist +** can contain deletions, while the full-index doclist will not +** (deletions are omitted). +** +** Result formats differ with the setting of DL_DEFAULTS. Examples: +** +** DL_DOCIDS: [1] [3] [7] +** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]] +** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]] +** +** In each case the number after the outer '[' is the docid. In the +** latter two cases, the number before the inner '[' is the column +** associated with the values within. For DL_POSITIONS the numbers +** within are the positions, for DL_POSITIONS_OFFSETS they are the +** position, the start offset, and the end offset. +*/ +static void dumpDoclistFunc( + sqlite3_context *pContext, + int argc, sqlite3_value **argv +){ + fulltext_cursor *pCursor; + if( argc!=2 && argc!=4 ){ + generateError(pContext, "dump_doclist", "incorrect arguments"); + }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || + sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ + generateError(pContext, "dump_doclist", "illegal first argument"); + }else if( sqlite3_value_text(argv[1])==NULL || + sqlite3_value_text(argv[1])[0]=='\0' ){ + generateError(pContext, "dump_doclist", "empty second argument"); + }else{ + const char *pTerm = (const char *)sqlite3_value_text(argv[1]); + const int nTerm = strlen(pTerm); + fulltext_vtab *v; + int rc; + DataBuffer doclist; + + memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); + v = cursor_vtab(pCursor); + + dataBufferInit(&doclist, 0); + + /* termSelect() yields the same logical doclist that queries are + ** run against. + */ + if( argc==2 ){ + rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist); + }else{ + sqlite3_stmt *s = NULL; + + /* Get our specific segment's information. */ + rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s); + if( rc==SQLITE_OK ){ + rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2])); + if( rc==SQLITE_OK ){ + rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3])); + } + } + + if( rc==SQLITE_OK ){ + rc = sqlite3_step(s); + + if( rc==SQLITE_DONE ){ + dataBufferDestroy(&doclist); + generateError(pContext, "dump_doclist", "segment not found"); + return; + } + + /* Found a segment, load it into doclist. */ + if( rc==SQLITE_ROW ){ + const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1); + const char *pData = sqlite3_column_blob(s, 2); + const int nData = sqlite3_column_bytes(s, 2); + + /* loadSegment() is used by termSelect() to load each + ** segment's data. + */ + rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0, + &doclist); + if( rc==SQLITE_OK ){ + rc = sqlite3_step(s); + + /* Should not have more than one matching segment. */ + if( rc!=SQLITE_DONE ){ + sqlite3_reset(s); + dataBufferDestroy(&doclist); + generateError(pContext, "dump_doclist", "invalid segdir"); + return; + } + rc = SQLITE_OK; + } + } + } + + sqlite3_reset(s); + } + + if( rc==SQLITE_OK ){ + if( doclist.nData>0 ){ + createDoclistResult(pContext, doclist.pData, doclist.nData); + }else{ + /* TODO(shess): This can happen if the term is not present, or + ** if all instances of the term have been deleted and this is + ** an all-index dump. It may be interesting to distinguish + ** these cases. + */ + sqlite3_result_text(pContext, "", 0, SQLITE_STATIC); + } + }else if( rc==SQLITE_NOMEM ){ + /* Handle out-of-memory cases specially because if they are + ** generated in fts2 code they may not be reflected in the db + ** handle. + */ + /* TODO(shess): Handle this more comprehensively. + ** sqlite3ErrStr() has what I need, but is internal. + */ + generateError(pContext, "dump_doclist", "out of memory"); + }else{ + generateError(pContext, "dump_doclist", NULL); + } + + dataBufferDestroy(&doclist); + } +} +#endif + +/* +** This routine implements the xFindFunction method for the FTS2 +** virtual table. +*/ +static int fulltextFindFunction( + sqlite3_vtab *pVtab, + int nArg, + const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg +){ + if( strcmp(zName,"snippet")==0 ){ + *pxFunc = snippetFunc; + return 1; + }else if( strcmp(zName,"offsets")==0 ){ + *pxFunc = snippetOffsetsFunc; + return 1; + }else if( strcmp(zName,"optimize")==0 ){ + *pxFunc = optimizeFunc; + return 1; +#ifdef SQLITE_TEST + /* NOTE(shess): These functions are present only for testing + ** purposes. No particular effort is made to optimize their + ** execution or how they build their results. + */ + }else if( strcmp(zName,"dump_terms")==0 ){ + /* fprintf(stderr, "Found dump_terms\n"); */ + *pxFunc = dumpTermsFunc; + return 1; + }else if( strcmp(zName,"dump_doclist")==0 ){ + /* fprintf(stderr, "Found dump_doclist\n"); */ + *pxFunc = dumpDoclistFunc; + return 1; +#endif + } + return 0; +} + +/* +** Rename an fts2 table. +*/ +static int fulltextRename( + sqlite3_vtab *pVtab, + const char *zName +){ + fulltext_vtab *p = (fulltext_vtab *)pVtab; + int rc = SQLITE_NOMEM; + char *zSql = sqlite3_mprintf( + "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';" + "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';" + "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';" + , p->zDb, p->zName, zName + , p->zDb, p->zName, zName + , p->zDb, p->zName, zName + ); + if( zSql ){ + rc = sqlite3_exec(p->db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } + return rc; +} + +static const sqlite3_module fts2Module = { + /* iVersion */ 0, + /* xCreate */ fulltextCreate, + /* xConnect */ fulltextConnect, + /* xBestIndex */ fulltextBestIndex, + /* xDisconnect */ fulltextDisconnect, + /* xDestroy */ fulltextDestroy, + /* xOpen */ fulltextOpen, + /* xClose */ fulltextClose, + /* xFilter */ fulltextFilter, + /* xNext */ fulltextNext, + /* xEof */ fulltextEof, + /* xColumn */ fulltextColumn, + /* xRowid */ fulltextRowid, + /* xUpdate */ fulltextUpdate, + /* xBegin */ fulltextBegin, + /* xSync */ fulltextSync, + /* xCommit */ fulltextCommit, + /* xRollback */ fulltextRollback, + /* xFindFunction */ fulltextFindFunction, + /* xRename */ fulltextRename, +}; + +static void hashDestroy(void *p){ + fts2Hash *pHash = (fts2Hash *)p; + sqlite3Fts2HashClear(pHash); + sqlite3_free(pHash); +} + +/* +** The fts2 built-in tokenizers - "simple" and "porter" - are implemented +** in files fts2_tokenizer1.c and fts2_porter.c respectively. The following +** two forward declarations are for functions declared in these files +** used to retrieve the respective implementations. +** +** Calling sqlite3Fts2SimpleTokenizerModule() sets the value pointed +** to by the argument to point a the "simple" tokenizer implementation. +** Function ...PorterTokenizerModule() sets *pModule to point to the +** porter tokenizer/stemmer implementation. +*/ +void sqlite3Fts2SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); +void sqlite3Fts2PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); +void sqlite3Fts2IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); + +int sqlite3Fts2InitHashTable(sqlite3 *, fts2Hash *, const char *); + +/* +** Initialize the fts2 extension. If this extension is built as part +** of the sqlite library, then this function is called directly by +** SQLite. If fts2 is built as a dynamically loadable extension, this +** function is called by the sqlite3_extension_init() entry point. +*/ +int sqlite3Fts2Init(sqlite3 *db){ + int rc = SQLITE_OK; + fts2Hash *pHash = 0; + const sqlite3_tokenizer_module *pSimple = 0; + const sqlite3_tokenizer_module *pPorter = 0; + const sqlite3_tokenizer_module *pIcu = 0; + + sqlite3Fts2SimpleTokenizerModule(&pSimple); + sqlite3Fts2PorterTokenizerModule(&pPorter); +#ifdef SQLITE_ENABLE_ICU + sqlite3Fts2IcuTokenizerModule(&pIcu); +#endif + + /* Allocate and initialize the hash-table used to store tokenizers. */ + pHash = sqlite3_malloc(sizeof(fts2Hash)); + if( !pHash ){ + rc = SQLITE_NOMEM; + }else{ + sqlite3Fts2HashInit(pHash, FTS2_HASH_STRING, 1); + } + + /* Load the built-in tokenizers into the hash table */ + if( rc==SQLITE_OK ){ + if( sqlite3Fts2HashInsert(pHash, "simple", 7, (void *)pSimple) + || sqlite3Fts2HashInsert(pHash, "porter", 7, (void *)pPorter) + || (pIcu && sqlite3Fts2HashInsert(pHash, "icu", 4, (void *)pIcu)) + ){ + rc = SQLITE_NOMEM; + } + } + + /* Create the virtual table wrapper around the hash-table and overload + ** the two scalar functions. If this is successful, register the + ** module with sqlite. + */ + if( SQLITE_OK==rc + && SQLITE_OK==(rc = sqlite3Fts2InitHashTable(db, pHash, "fts2_tokenizer")) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1)) +#ifdef SQLITE_TEST + && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1)) +#endif + ){ + return sqlite3_create_module_v2( + db, "fts2", &fts2Module, (void *)pHash, hashDestroy + ); + } + + /* An error has occurred. Delete the hash table and return the error code. */ + assert( rc!=SQLITE_OK ); + if( pHash ){ + sqlite3Fts2HashClear(pHash); + sqlite3_free(pHash); + } + return rc; +} + +#if !SQLITE_CORE +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_fts2_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi) + return sqlite3Fts2Init(db); +} +#endif + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/fts2.h b/components/external/SQLite-3.8.1/ext/fts2/fts2.h new file mode 100644 index 0000000000000000000000000000000000000000..4da4c3877b06abbd2f56780e1ac8dcbdd25003cc --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/fts2.h @@ -0,0 +1,26 @@ +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file is used by programs that want to link against the +** FTS2 library. All it does is declare the sqlite3Fts2Init() interface. +*/ +#include "sqlite3.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +int sqlite3Fts2Init(sqlite3 *db); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/fts2_hash.c b/components/external/SQLite-3.8.1/ext/fts2/fts2_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..3596dcf0b80071e4c80fb35ab7ee208585d4875b --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/fts2_hash.c @@ -0,0 +1,376 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the implementation of generic hash-tables used in SQLite. +** We've modified it slightly to serve as a standalone hash table +** implementation for the full-text indexing module. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS2 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS2 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS2 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) + +#include +#include +#include + +#include "sqlite3.h" +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT3 +#include "fts2_hash.h" + +/* +** Malloc and Free functions +*/ +static void *fts2HashMalloc(int n){ + void *p = sqlite3_malloc(n); + if( p ){ + memset(p, 0, n); + } + return p; +} +static void fts2HashFree(void *p){ + sqlite3_free(p); +} + +/* Turn bulk memory into a hash table object by initializing the +** fields of the Hash structure. +** +** "pNew" is a pointer to the hash table that is to be initialized. +** keyClass is one of the constants +** FTS2_HASH_BINARY or FTS2_HASH_STRING. The value of keyClass +** determines what kind of key the hash table will use. "copyKey" is +** true if the hash table should make its own private copy of keys and +** false if it should just use the supplied pointer. +*/ +void sqlite3Fts2HashInit(fts2Hash *pNew, int keyClass, int copyKey){ + assert( pNew!=0 ); + assert( keyClass>=FTS2_HASH_STRING && keyClass<=FTS2_HASH_BINARY ); + pNew->keyClass = keyClass; + pNew->copyKey = copyKey; + pNew->first = 0; + pNew->count = 0; + pNew->htsize = 0; + pNew->ht = 0; +} + +/* Remove all entries from a hash table. Reclaim all memory. +** Call this routine to delete a hash table or to reset a hash table +** to the empty state. +*/ +void sqlite3Fts2HashClear(fts2Hash *pH){ + fts2HashElem *elem; /* For looping over all elements of the table */ + + assert( pH!=0 ); + elem = pH->first; + pH->first = 0; + fts2HashFree(pH->ht); + pH->ht = 0; + pH->htsize = 0; + while( elem ){ + fts2HashElem *next_elem = elem->next; + if( pH->copyKey && elem->pKey ){ + fts2HashFree(elem->pKey); + } + fts2HashFree(elem); + elem = next_elem; + } + pH->count = 0; +} + +/* +** Hash and comparison functions when the mode is FTS2_HASH_STRING +*/ +static int strHash(const void *pKey, int nKey){ + const char *z = (const char *)pKey; + int h = 0; + if( nKey<=0 ) nKey = (int) strlen(z); + while( nKey > 0 ){ + h = (h<<3) ^ h ^ *z++; + nKey--; + } + return h & 0x7fffffff; +} +static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return strncmp((const char*)pKey1,(const char*)pKey2,n1); +} + +/* +** Hash and comparison functions when the mode is FTS2_HASH_BINARY +*/ +static int binHash(const void *pKey, int nKey){ + int h = 0; + const char *z = (const char *)pKey; + while( nKey-- > 0 ){ + h = (h<<3) ^ h ^ *(z++); + } + return h & 0x7fffffff; +} +static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return memcmp(pKey1,pKey2,n1); +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** The C syntax in this function definition may be unfamilar to some +** programmers, so we provide the following additional explanation: +** +** The name of the function is "hashFunction". The function takes a +** single parameter "keyClass". The return value of hashFunction() +** is a pointer to another function. Specifically, the return value +** of hashFunction() is a pointer to a function that takes two parameters +** with types "const void*" and "int" and returns an "int". +*/ +static int (*hashFunction(int keyClass))(const void*,int){ + if( keyClass==FTS2_HASH_STRING ){ + return &strHash; + }else{ + assert( keyClass==FTS2_HASH_BINARY ); + return &binHash; + } +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** For help in interpreted the obscure C code in the function definition, +** see the header comment on the previous function. +*/ +static int (*compareFunction(int keyClass))(const void*,int,const void*,int){ + if( keyClass==FTS2_HASH_STRING ){ + return &strCompare; + }else{ + assert( keyClass==FTS2_HASH_BINARY ); + return &binCompare; + } +} + +/* Link an element into the hash table +*/ +static void insertElement( + fts2Hash *pH, /* The complete hash table */ + struct _fts2ht *pEntry, /* The entry into which pNew is inserted */ + fts2HashElem *pNew /* The element to be inserted */ +){ + fts2HashElem *pHead; /* First element already in pEntry */ + pHead = pEntry->chain; + if( pHead ){ + pNew->next = pHead; + pNew->prev = pHead->prev; + if( pHead->prev ){ pHead->prev->next = pNew; } + else { pH->first = pNew; } + pHead->prev = pNew; + }else{ + pNew->next = pH->first; + if( pH->first ){ pH->first->prev = pNew; } + pNew->prev = 0; + pH->first = pNew; + } + pEntry->count++; + pEntry->chain = pNew; +} + + +/* Resize the hash table so that it cantains "new_size" buckets. +** "new_size" must be a power of 2. The hash table might fail +** to resize if sqliteMalloc() fails. +*/ +static void rehash(fts2Hash *pH, int new_size){ + struct _fts2ht *new_ht; /* The new hash table */ + fts2HashElem *elem, *next_elem; /* For looping over existing elements */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( (new_size & (new_size-1))==0 ); + new_ht = (struct _fts2ht *)fts2HashMalloc( new_size*sizeof(struct _fts2ht) ); + if( new_ht==0 ) return; + fts2HashFree(pH->ht); + pH->ht = new_ht; + pH->htsize = new_size; + xHash = hashFunction(pH->keyClass); + for(elem=pH->first, pH->first=0; elem; elem = next_elem){ + int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1); + next_elem = elem->next; + insertElement(pH, &new_ht[h], elem); + } +} + +/* This function (for internal use only) locates an element in an +** hash table that matches the given key. The hash for this key has +** already been computed and is passed as the 4th parameter. +*/ +static fts2HashElem *findElementGivenHash( + const fts2Hash *pH, /* The pH to be searched */ + const void *pKey, /* The key we are searching for */ + int nKey, + int h /* The hash for this key. */ +){ + fts2HashElem *elem; /* Used to loop thru the element list */ + int count; /* Number of elements left to test */ + int (*xCompare)(const void*,int,const void*,int); /* comparison function */ + + if( pH->ht ){ + struct _fts2ht *pEntry = &pH->ht[h]; + elem = pEntry->chain; + count = pEntry->count; + xCompare = compareFunction(pH->keyClass); + while( count-- && elem ){ + if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ + return elem; + } + elem = elem->next; + } + } + return 0; +} + +/* Remove a single entry from the hash table given a pointer to that +** element and a hash on the element's key. +*/ +static void removeElementGivenHash( + fts2Hash *pH, /* The pH containing "elem" */ + fts2HashElem* elem, /* The element to be removed from the pH */ + int h /* Hash value for the element */ +){ + struct _fts2ht *pEntry; + if( elem->prev ){ + elem->prev->next = elem->next; + }else{ + pH->first = elem->next; + } + if( elem->next ){ + elem->next->prev = elem->prev; + } + pEntry = &pH->ht[h]; + if( pEntry->chain==elem ){ + pEntry->chain = elem->next; + } + pEntry->count--; + if( pEntry->count<=0 ){ + pEntry->chain = 0; + } + if( pH->copyKey && elem->pKey ){ + fts2HashFree(elem->pKey); + } + fts2HashFree( elem ); + pH->count--; + if( pH->count<=0 ){ + assert( pH->first==0 ); + assert( pH->count==0 ); + fts2HashClear(pH); + } +} + +/* Attempt to locate an element of the hash table pH with a key +** that matches pKey,nKey. Return the data for this element if it is +** found, or NULL if there is no match. +*/ +void *sqlite3Fts2HashFind(const fts2Hash *pH, const void *pKey, int nKey){ + int h; /* A hash on key */ + fts2HashElem *elem; /* The element that matches key */ + int (*xHash)(const void*,int); /* The hash function */ + + if( pH==0 || pH->ht==0 ) return 0; + xHash = hashFunction(pH->keyClass); + assert( xHash!=0 ); + h = (*xHash)(pKey,nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1)); + return elem ? elem->data : 0; +} + +/* Insert an element into the hash table pH. The key is pKey,nKey +** and the data is "data". +** +** If no element exists with a matching key, then a new +** element is created. A copy of the key is made if the copyKey +** flag is set. NULL is returned. +** +** If another element already exists with the same key, then the +** new data replaces the old data and the old data is returned. +** The key is not copied in this instance. If a malloc fails, then +** the new data is returned and the hash table is unchanged. +** +** If the "data" parameter to this function is NULL, then the +** element corresponding to "key" is removed from the hash table. +*/ +void *sqlite3Fts2HashInsert( + fts2Hash *pH, /* The hash table to insert into */ + const void *pKey, /* The key */ + int nKey, /* Number of bytes in the key */ + void *data /* The data */ +){ + int hraw; /* Raw hash value of the key */ + int h; /* the hash of the key modulo hash table size */ + fts2HashElem *elem; /* Used to loop thru the element list */ + fts2HashElem *new_elem; /* New element added to the pH */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( pH!=0 ); + xHash = hashFunction(pH->keyClass); + assert( xHash!=0 ); + hraw = (*xHash)(pKey, nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + elem = findElementGivenHash(pH,pKey,nKey,h); + if( elem ){ + void *old_data = elem->data; + if( data==0 ){ + removeElementGivenHash(pH,elem,h); + }else{ + elem->data = data; + } + return old_data; + } + if( data==0 ) return 0; + new_elem = (fts2HashElem*)fts2HashMalloc( sizeof(fts2HashElem) ); + if( new_elem==0 ) return data; + if( pH->copyKey && pKey!=0 ){ + new_elem->pKey = fts2HashMalloc( nKey ); + if( new_elem->pKey==0 ){ + fts2HashFree(new_elem); + return data; + } + memcpy((void*)new_elem->pKey, pKey, nKey); + }else{ + new_elem->pKey = (void*)pKey; + } + new_elem->nKey = nKey; + pH->count++; + if( pH->htsize==0 ){ + rehash(pH,8); + if( pH->htsize==0 ){ + pH->count = 0; + fts2HashFree(new_elem); + return data; + } + } + if( pH->count > pH->htsize ){ + rehash(pH,pH->htsize*2); + } + assert( pH->htsize>0 ); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + insertElement(pH, &pH->ht[h], new_elem); + new_elem->data = data; + return 0; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/fts2_hash.h b/components/external/SQLite-3.8.1/ext/fts2/fts2_hash.h new file mode 100644 index 0000000000000000000000000000000000000000..02936f18bbaa76eecddf7064074cfc288a410f5d --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/fts2_hash.h @@ -0,0 +1,110 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implementation +** used in SQLite. We've modified it slightly to serve as a standalone +** hash table implementation for the full-text indexing module. +** +*/ +#ifndef _FTS2_HASH_H_ +#define _FTS2_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct fts2Hash fts2Hash; +typedef struct fts2HashElem fts2HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, many of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +*/ +struct fts2Hash { + char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ + char copyKey; /* True if copy of key made on insert */ + int count; /* Number of entries in this table */ + fts2HashElem *first; /* The first element of the array */ + int htsize; /* Number of buckets in the hash table */ + struct _fts2ht { /* the hash table */ + int count; /* Number of entries with this hash */ + fts2HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct fts2HashElem { + fts2HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + void *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** There are 2 different modes of operation for a hash table: +** +** FTS2_HASH_STRING pKey points to a string that is nKey bytes long +** (including the null-terminator, if any). Case +** is respected in comparisons. +** +** FTS2_HASH_BINARY pKey points to binary data nKey bytes long. +** memcmp() is used to compare keys. +** +** A copy of the key is made if the copyKey parameter to fts2HashInit is 1. +*/ +#define FTS2_HASH_STRING 1 +#define FTS2_HASH_BINARY 2 + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +void sqlite3Fts2HashInit(fts2Hash*, int keytype, int copyKey); +void *sqlite3Fts2HashInsert(fts2Hash*, const void *pKey, int nKey, void *pData); +void *sqlite3Fts2HashFind(const fts2Hash*, const void *pKey, int nKey); +void sqlite3Fts2HashClear(fts2Hash*); + +/* +** Shorthand for the functions above +*/ +#define fts2HashInit sqlite3Fts2HashInit +#define fts2HashInsert sqlite3Fts2HashInsert +#define fts2HashFind sqlite3Fts2HashFind +#define fts2HashClear sqlite3Fts2HashClear + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** fts2Hash h; +** fts2HashElem *p; +** ... +** for(p=fts2HashFirst(&h); p; p=fts2HashNext(p)){ +** SomeStructure *pData = fts2HashData(p); +** // do something with pData +** } +*/ +#define fts2HashFirst(H) ((H)->first) +#define fts2HashNext(E) ((E)->next) +#define fts2HashData(E) ((E)->data) +#define fts2HashKey(E) ((E)->pKey) +#define fts2HashKeysize(E) ((E)->nKey) + +/* +** Number of entries in a hash table +*/ +#define fts2HashCount(H) ((H)->count) + +#endif /* _FTS2_HASH_H_ */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/fts2_icu.c b/components/external/SQLite-3.8.1/ext/fts2/fts2_icu.c new file mode 100644 index 0000000000000000000000000000000000000000..2670301f5198f3712b2afb9b87d5a45e80059201 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/fts2_icu.c @@ -0,0 +1,260 @@ +/* +** 2007 June 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements a tokenizer for fts2 based on the ICU library. +** +** $Id: fts2_icu.c,v 1.3 2008/12/18 05:30:26 danielk1977 Exp $ +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) +#ifdef SQLITE_ENABLE_ICU + +#include +#include +#include "fts2_tokenizer.h" + +#include +#include +#include +#include + +typedef struct IcuTokenizer IcuTokenizer; +typedef struct IcuCursor IcuCursor; + +struct IcuTokenizer { + sqlite3_tokenizer base; + char *zLocale; +}; + +struct IcuCursor { + sqlite3_tokenizer_cursor base; + + UBreakIterator *pIter; /* ICU break-iterator object */ + int nChar; /* Number of UChar elements in pInput */ + UChar *aChar; /* Copy of input using utf-16 encoding */ + int *aOffset; /* Offsets of each character in utf-8 input */ + + int nBuffer; + char *zBuffer; + + int iToken; +}; + +/* +** Create a new tokenizer instance. +*/ +static int icuCreate( + int argc, /* Number of entries in argv[] */ + const char * const *argv, /* Tokenizer creation arguments */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ +){ + IcuTokenizer *p; + int n = 0; + + if( argc>0 ){ + n = strlen(argv[0])+1; + } + p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n); + if( !p ){ + return SQLITE_NOMEM; + } + memset(p, 0, sizeof(IcuTokenizer)); + + if( n ){ + p->zLocale = (char *)&p[1]; + memcpy(p->zLocale, argv[0], n); + } + + *ppTokenizer = (sqlite3_tokenizer *)p; + + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int icuDestroy(sqlite3_tokenizer *pTokenizer){ + IcuTokenizer *p = (IcuTokenizer *)pTokenizer; + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is pInput[0..nBytes-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int icuOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *zInput, /* Input string */ + int nInput, /* Length of zInput in bytes */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + IcuTokenizer *p = (IcuTokenizer *)pTokenizer; + IcuCursor *pCsr; + + const int32_t opt = U_FOLD_CASE_DEFAULT; + UErrorCode status = U_ZERO_ERROR; + int nChar; + + UChar32 c; + int iInput = 0; + int iOut = 0; + + *ppCursor = 0; + + if( nInput<0 ){ + nInput = strlen(zInput); + } + nChar = nInput+1; + pCsr = (IcuCursor *)sqlite3_malloc( + sizeof(IcuCursor) + /* IcuCursor */ + ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */ + (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */ + ); + if( !pCsr ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(IcuCursor)); + pCsr->aChar = (UChar *)&pCsr[1]; + pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3]; + + pCsr->aOffset[iOut] = iInput; + U8_NEXT(zInput, iInput, nInput, c); + while( c>0 ){ + int isError = 0; + c = u_foldCase(c, opt); + U16_APPEND(pCsr->aChar, iOut, nChar, c, isError); + if( isError ){ + sqlite3_free(pCsr); + return SQLITE_ERROR; + } + pCsr->aOffset[iOut] = iInput; + + if( iInputpIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status); + if( !U_SUCCESS(status) ){ + sqlite3_free(pCsr); + return SQLITE_ERROR; + } + pCsr->nChar = iOut; + + ubrk_first(pCsr->pIter); + *ppCursor = (sqlite3_tokenizer_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to icuOpen(). +*/ +static int icuClose(sqlite3_tokenizer_cursor *pCursor){ + IcuCursor *pCsr = (IcuCursor *)pCursor; + ubrk_close(pCsr->pIter); + sqlite3_free(pCsr->zBuffer); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** Extract the next token from a tokenization cursor. +*/ +static int icuNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + IcuCursor *pCsr = (IcuCursor *)pCursor; + + int iStart = 0; + int iEnd = 0; + int nByte = 0; + + while( iStart==iEnd ){ + UChar32 c; + + iStart = ubrk_current(pCsr->pIter); + iEnd = ubrk_next(pCsr->pIter); + if( iEnd==UBRK_DONE ){ + return SQLITE_DONE; + } + + while( iStartaChar, iWhite, pCsr->nChar, c); + if( u_isspace(c) ){ + iStart = iWhite; + }else{ + break; + } + } + assert(iStart<=iEnd); + } + + do { + UErrorCode status = U_ZERO_ERROR; + if( nByte ){ + char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte); + if( !zNew ){ + return SQLITE_NOMEM; + } + pCsr->zBuffer = zNew; + pCsr->nBuffer = nByte; + } + + u_strToUTF8( + pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */ + &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */ + &status /* Output success/failure */ + ); + } while( nByte>pCsr->nBuffer ); + + *ppToken = pCsr->zBuffer; + *pnBytes = nByte; + *piStartOffset = pCsr->aOffset[iStart]; + *piEndOffset = pCsr->aOffset[iEnd]; + *piPosition = pCsr->iToken++; + + return SQLITE_OK; +} + +/* +** The set of routines that implement the simple tokenizer +*/ +static const sqlite3_tokenizer_module icuTokenizerModule = { + 0, /* iVersion */ + icuCreate, /* xCreate */ + icuDestroy, /* xCreate */ + icuOpen, /* xOpen */ + icuClose, /* xClose */ + icuNext, /* xNext */ +}; + +/* +** Set *ppModule to point at the implementation of the ICU tokenizer. +*/ +void sqlite3Fts2IcuTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &icuTokenizerModule; +} + +#endif /* defined(SQLITE_ENABLE_ICU) */ +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/fts2_porter.c b/components/external/SQLite-3.8.1/ext/fts2/fts2_porter.c new file mode 100644 index 0000000000000000000000000000000000000000..881baf7100f46eb20ddefad152bcf6007a17bced --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/fts2_porter.c @@ -0,0 +1,644 @@ +/* +** 2006 September 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Implementation of the full-text-search tokenizer that implements +** a Porter stemmer. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS2 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS2 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS2 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) + + +#include +#include +#include +#include + +#include "sqlite3.h" +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT3 +#include "fts2_tokenizer.h" + +/* +** Class derived from sqlite3_tokenizer +*/ +typedef struct porter_tokenizer { + sqlite3_tokenizer base; /* Base class */ +} porter_tokenizer; + +/* +** Class derived from sqlit3_tokenizer_cursor +*/ +typedef struct porter_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *zInput; /* input we are tokenizing */ + int nInput; /* size of the input */ + int iOffset; /* current position in zInput */ + int iToken; /* index of next token to be returned */ + char *zToken; /* storage for current token */ + int nAllocated; /* space allocated to zToken buffer */ +} porter_tokenizer_cursor; + + +/* Forward declaration */ +static const sqlite3_tokenizer_module porterTokenizerModule; + + +/* +** Create a new tokenizer instance. +*/ +static int porterCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer +){ + porter_tokenizer *t; + t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t)); + if( t==NULL ) return SQLITE_NOMEM; + memset(t, 0, sizeof(*t)); + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int porterDestroy(sqlite3_tokenizer *pTokenizer){ + sqlite3_free(pTokenizer); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is zInput[0..nInput-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int porterOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *zInput, int nInput, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + porter_tokenizer_cursor *c; + + c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); + if( c==NULL ) return SQLITE_NOMEM; + + c->zInput = zInput; + if( zInput==0 ){ + c->nInput = 0; + }else if( nInput<0 ){ + c->nInput = (int)strlen(zInput); + }else{ + c->nInput = nInput; + } + c->iOffset = 0; /* start tokenizing at the beginning */ + c->iToken = 0; + c->zToken = NULL; /* no space allocated, yet. */ + c->nAllocated = 0; + + *ppCursor = &c->base; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** porterOpen() above. +*/ +static int porterClose(sqlite3_tokenizer_cursor *pCursor){ + porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; + sqlite3_free(c->zToken); + sqlite3_free(c); + return SQLITE_OK; +} +/* +** Vowel or consonant +*/ +static const char cType[] = { + 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 2, 1 +}; + +/* +** isConsonant() and isVowel() determine if their first character in +** the string they point to is a consonant or a vowel, according +** to Porter ruls. +** +** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'. +** 'Y' is a consonant unless it follows another consonant, +** in which case it is a vowel. +** +** In these routine, the letters are in reverse order. So the 'y' rule +** is that 'y' is a consonant unless it is followed by another +** consonent. +*/ +static int isVowel(const char*); +static int isConsonant(const char *z){ + int j; + char x = *z; + if( x==0 ) return 0; + assert( x>='a' && x<='z' ); + j = cType[x-'a']; + if( j<2 ) return j; + return z[1]==0 || isVowel(z + 1); +} +static int isVowel(const char *z){ + int j; + char x = *z; + if( x==0 ) return 0; + assert( x>='a' && x<='z' ); + j = cType[x-'a']; + if( j<2 ) return 1-j; + return isConsonant(z + 1); +} + +/* +** Let any sequence of one or more vowels be represented by V and let +** C be sequence of one or more consonants. Then every word can be +** represented as: +** +** [C] (VC){m} [V] +** +** In prose: A word is an optional consonant followed by zero or +** vowel-consonant pairs followed by an optional vowel. "m" is the +** number of vowel consonant pairs. This routine computes the value +** of m for the first i bytes of a word. +** +** Return true if the m-value for z is 1 or more. In other words, +** return true if z contains at least one vowel that is followed +** by a consonant. +** +** In this routine z[] is in reverse order. So we are really looking +** for an instance of of a consonant followed by a vowel. +*/ +static int m_gt_0(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* Like mgt0 above except we are looking for a value of m which is +** exactly 1 +*/ +static int m_eq_1(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + if( *z==0 ) return 0; + while( isVowel(z) ){ z++; } + if( *z==0 ) return 1; + while( isConsonant(z) ){ z++; } + return *z==0; +} + +/* Like mgt0 above except we are looking for a value of m>1 instead +** or m>0 +*/ +static int m_gt_1(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + if( *z==0 ) return 0; + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* +** Return TRUE if there is a vowel anywhere within z[0..n-1] +*/ +static int hasVowel(const char *z){ + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* +** Return TRUE if the word ends in a double consonant. +** +** The text is reversed here. So we are really looking at +** the first two characters of z[]. +*/ +static int doubleConsonant(const char *z){ + return isConsonant(z) && z[0]==z[1] && isConsonant(z+1); +} + +/* +** Return TRUE if the word ends with three letters which +** are consonant-vowel-consonent and where the final consonant +** is not 'w', 'x', or 'y'. +** +** The word is reversed here. So we are really checking the +** first three letters and the first one cannot be in [wxy]. +*/ +static int star_oh(const char *z){ + return + z[0]!=0 && isConsonant(z) && + z[0]!='w' && z[0]!='x' && z[0]!='y' && + z[1]!=0 && isVowel(z+1) && + z[2]!=0 && isConsonant(z+2); +} + +/* +** If the word ends with zFrom and xCond() is true for the stem +** of the word that preceeds the zFrom ending, then change the +** ending to zTo. +** +** The input word *pz and zFrom are both in reverse order. zTo +** is in normal order. +** +** Return TRUE if zFrom matches. Return FALSE if zFrom does not +** match. Not that TRUE is returned even if xCond() fails and +** no substitution occurs. +*/ +static int stem( + char **pz, /* The word being stemmed (Reversed) */ + const char *zFrom, /* If the ending matches this... (Reversed) */ + const char *zTo, /* ... change the ending to this (not reversed) */ + int (*xCond)(const char*) /* Condition that must be true */ +){ + char *z = *pz; + while( *zFrom && *zFrom==*z ){ z++; zFrom++; } + if( *zFrom!=0 ) return 0; + if( xCond && !xCond(z) ) return 1; + while( *zTo ){ + *(--z) = *(zTo++); + } + *pz = z; + return 1; +} + +/* +** This is the fallback stemmer used when the porter stemmer is +** inappropriate. The input word is copied into the output with +** US-ASCII case folding. If the input word is too long (more +** than 20 bytes if it contains no digits or more than 6 bytes if +** it contains digits) then word is truncated to 20 or 6 bytes +** by taking 10 or 3 bytes from the beginning and end. +*/ +static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){ + int i, mx, j; + int hasDigit = 0; + for(i=0; i='A' && c<='Z' ){ + zOut[i] = c - 'A' + 'a'; + }else{ + if( c>='0' && c<='9' ) hasDigit = 1; + zOut[i] = c; + } + } + mx = hasDigit ? 3 : 10; + if( nIn>mx*2 ){ + for(j=mx, i=nIn-mx; i=sizeof(zReverse)-7 ){ + /* The word is too big or too small for the porter stemmer. + ** Fallback to the copy stemmer */ + copy_stemmer(zIn, nIn, zOut, pnOut); + return; + } + for(i=0, j=sizeof(zReverse)-6; i='A' && c<='Z' ){ + zReverse[j] = c + 'a' - 'A'; + }else if( c>='a' && c<='z' ){ + zReverse[j] = c; + }else{ + /* The use of a character not in [a-zA-Z] means that we fallback + ** to the copy stemmer */ + copy_stemmer(zIn, nIn, zOut, pnOut); + return; + } + } + memset(&zReverse[sizeof(zReverse)-5], 0, 5); + z = &zReverse[j+1]; + + + /* Step 1a */ + if( z[0]=='s' ){ + if( + !stem(&z, "sess", "ss", 0) && + !stem(&z, "sei", "i", 0) && + !stem(&z, "ss", "ss", 0) + ){ + z++; + } + } + + /* Step 1b */ + z2 = z; + if( stem(&z, "dee", "ee", m_gt_0) ){ + /* Do nothing. The work was all in the test */ + }else if( + (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel)) + && z!=z2 + ){ + if( stem(&z, "ta", "ate", 0) || + stem(&z, "lb", "ble", 0) || + stem(&z, "zi", "ize", 0) ){ + /* Do nothing. The work was all in the test */ + }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){ + z++; + }else if( m_eq_1(z) && star_oh(z) ){ + *(--z) = 'e'; + } + } + + /* Step 1c */ + if( z[0]=='y' && hasVowel(z+1) ){ + z[0] = 'i'; + } + + /* Step 2 */ + switch( z[1] ){ + case 'a': + stem(&z, "lanoita", "ate", m_gt_0) || + stem(&z, "lanoit", "tion", m_gt_0); + break; + case 'c': + stem(&z, "icne", "ence", m_gt_0) || + stem(&z, "icna", "ance", m_gt_0); + break; + case 'e': + stem(&z, "rezi", "ize", m_gt_0); + break; + case 'g': + stem(&z, "igol", "log", m_gt_0); + break; + case 'l': + stem(&z, "ilb", "ble", m_gt_0) || + stem(&z, "illa", "al", m_gt_0) || + stem(&z, "iltne", "ent", m_gt_0) || + stem(&z, "ile", "e", m_gt_0) || + stem(&z, "ilsuo", "ous", m_gt_0); + break; + case 'o': + stem(&z, "noitazi", "ize", m_gt_0) || + stem(&z, "noita", "ate", m_gt_0) || + stem(&z, "rota", "ate", m_gt_0); + break; + case 's': + stem(&z, "msila", "al", m_gt_0) || + stem(&z, "ssenevi", "ive", m_gt_0) || + stem(&z, "ssenluf", "ful", m_gt_0) || + stem(&z, "ssensuo", "ous", m_gt_0); + break; + case 't': + stem(&z, "itila", "al", m_gt_0) || + stem(&z, "itivi", "ive", m_gt_0) || + stem(&z, "itilib", "ble", m_gt_0); + break; + } + + /* Step 3 */ + switch( z[0] ){ + case 'e': + stem(&z, "etaci", "ic", m_gt_0) || + stem(&z, "evita", "", m_gt_0) || + stem(&z, "ezila", "al", m_gt_0); + break; + case 'i': + stem(&z, "itici", "ic", m_gt_0); + break; + case 'l': + stem(&z, "laci", "ic", m_gt_0) || + stem(&z, "luf", "", m_gt_0); + break; + case 's': + stem(&z, "ssen", "", m_gt_0); + break; + } + + /* Step 4 */ + switch( z[1] ){ + case 'a': + if( z[0]=='l' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'c': + if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){ + z += 4; + } + break; + case 'e': + if( z[0]=='r' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'i': + if( z[0]=='c' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'l': + if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){ + z += 4; + } + break; + case 'n': + if( z[0]=='t' ){ + if( z[2]=='a' ){ + if( m_gt_1(z+3) ){ + z += 3; + } + }else if( z[2]=='e' ){ + stem(&z, "tneme", "", m_gt_1) || + stem(&z, "tnem", "", m_gt_1) || + stem(&z, "tne", "", m_gt_1); + } + } + break; + case 'o': + if( z[0]=='u' ){ + if( m_gt_1(z+2) ){ + z += 2; + } + }else if( z[3]=='s' || z[3]=='t' ){ + stem(&z, "noi", "", m_gt_1); + } + break; + case 's': + if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){ + z += 3; + } + break; + case 't': + stem(&z, "eta", "", m_gt_1) || + stem(&z, "iti", "", m_gt_1); + break; + case 'u': + if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){ + z += 3; + } + break; + case 'v': + case 'z': + if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){ + z += 3; + } + break; + } + + /* Step 5a */ + if( z[0]=='e' ){ + if( m_gt_1(z+1) ){ + z++; + }else if( m_eq_1(z+1) && !star_oh(z+1) ){ + z++; + } + } + + /* Step 5b */ + if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){ + z++; + } + + /* z[] is now the stemmed word in reverse order. Flip it back + ** around into forward order and return. + */ + *pnOut = i = strlen(z); + zOut[i] = 0; + while( *z ){ + zOut[--i] = *(z++); + } +} + +/* +** Characters that can be part of a token. We assume any character +** whose value is greater than 0x80 (any UTF character) can be +** part of a token. In other words, delimiters all must have +** values of 0x7f or lower. +*/ +static const char porterIdChar[] = { +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ +}; +#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30])) + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to porterOpen(). +*/ +static int porterNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */ + const char **pzToken, /* OUT: *pzToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; + const char *z = c->zInput; + + while( c->iOffsetnInput ){ + int iStartOffset, ch; + + /* Scan past delimiter characters */ + while( c->iOffsetnInput && isDelim(z[c->iOffset]) ){ + c->iOffset++; + } + + /* Count non-delimiter characters. */ + iStartOffset = c->iOffset; + while( c->iOffsetnInput && !isDelim(z[c->iOffset]) ){ + c->iOffset++; + } + + if( c->iOffset>iStartOffset ){ + int n = c->iOffset-iStartOffset; + if( n>c->nAllocated ){ + c->nAllocated = n+20; + c->zToken = sqlite3_realloc(c->zToken, c->nAllocated); + if( c->zToken==NULL ) return SQLITE_NOMEM; + } + porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes); + *pzToken = c->zToken; + *piStartOffset = iStartOffset; + *piEndOffset = c->iOffset; + *piPosition = c->iToken++; + return SQLITE_OK; + } + } + return SQLITE_DONE; +} + +/* +** The set of routines that implement the porter-stemmer tokenizer +*/ +static const sqlite3_tokenizer_module porterTokenizerModule = { + 0, + porterCreate, + porterDestroy, + porterOpen, + porterClose, + porterNext, +}; + +/* +** Allocate a new porter tokenizer. Return a pointer to the new +** tokenizer in *ppModule +*/ +void sqlite3Fts2PorterTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &porterTokenizerModule; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/fts2_tokenizer.c b/components/external/SQLite-3.8.1/ext/fts2/fts2_tokenizer.c new file mode 100644 index 0000000000000000000000000000000000000000..a3d6a6312a9e71f1c29f5c77080ebcf959429d40 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/fts2_tokenizer.c @@ -0,0 +1,371 @@ +/* +** 2007 June 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This is part of an SQLite module implementing full-text search. +** This particular file implements the generic tokenizer interface. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS2 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS2 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS2 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) + + +#include "sqlite3.h" +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT3 + +#include "fts2_hash.h" +#include "fts2_tokenizer.h" +#include + +/* +** Implementation of the SQL scalar function for accessing the underlying +** hash table. This function may be called as follows: +** +** SELECT (); +** SELECT (, ); +** +** where is the name passed as the second argument +** to the sqlite3Fts2InitHashTable() function (e.g. 'fts2_tokenizer'). +** +** If the argument is specified, it must be a blob value +** containing a pointer to be stored as the hash data corresponding +** to the string . If is not specified, then +** the string must already exist in the has table. Otherwise, +** an error is returned. +** +** Whether or not the argument is specified, the value returned +** is a blob containing the pointer stored as the hash data corresponding +** to string (after the hash-table is updated, if applicable). +*/ +static void scalarFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + fts2Hash *pHash; + void *pPtr = 0; + const unsigned char *zName; + int nName; + + assert( argc==1 || argc==2 ); + + pHash = (fts2Hash *)sqlite3_user_data(context); + + zName = sqlite3_value_text(argv[0]); + nName = sqlite3_value_bytes(argv[0])+1; + + if( argc==2 ){ + void *pOld; + int n = sqlite3_value_bytes(argv[1]); + if( n!=sizeof(pPtr) ){ + sqlite3_result_error(context, "argument type mismatch", -1); + return; + } + pPtr = *(void **)sqlite3_value_blob(argv[1]); + pOld = sqlite3Fts2HashInsert(pHash, (void *)zName, nName, pPtr); + if( pOld==pPtr ){ + sqlite3_result_error(context, "out of memory", -1); + return; + } + }else{ + pPtr = sqlite3Fts2HashFind(pHash, zName, nName); + if( !pPtr ){ + char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); + return; + } + } + + sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT); +} + +#ifdef SQLITE_TEST + +#include +#include + +/* +** Implementation of a special SQL scalar function for testing tokenizers +** designed to be used in concert with the Tcl testing framework. This +** function must be called with two arguments: +** +** SELECT (, ); +** SELECT (, ); +** +** where is the name passed as the second argument +** to the sqlite3Fts2InitHashTable() function (e.g. 'fts2_tokenizer') +** concatenated with the string '_test' (e.g. 'fts2_tokenizer_test'). +** +** The return value is a string that may be interpreted as a Tcl +** list. For each token in the , three elements are +** added to the returned list. The first is the token position, the +** second is the token text (folded, stemmed, etc.) and the third is the +** substring of associated with the token. For example, +** using the built-in "simple" tokenizer: +** +** SELECT fts_tokenizer_test('simple', 'I don't see how'); +** +** will return the string: +** +** "{0 i I 1 dont don't 2 see see 3 how how}" +** +*/ +static void testFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + fts2Hash *pHash; + sqlite3_tokenizer_module *p; + sqlite3_tokenizer *pTokenizer = 0; + sqlite3_tokenizer_cursor *pCsr = 0; + + const char *zErr = 0; + + const char *zName; + int nName; + const char *zInput; + int nInput; + + const char *zArg = 0; + + const char *zToken; + int nToken; + int iStart; + int iEnd; + int iPos; + + Tcl_Obj *pRet; + + assert( argc==2 || argc==3 ); + + nName = sqlite3_value_bytes(argv[0]); + zName = (const char *)sqlite3_value_text(argv[0]); + nInput = sqlite3_value_bytes(argv[argc-1]); + zInput = (const char *)sqlite3_value_text(argv[argc-1]); + + if( argc==3 ){ + zArg = (const char *)sqlite3_value_text(argv[1]); + } + + pHash = (fts2Hash *)sqlite3_user_data(context); + p = (sqlite3_tokenizer_module *)sqlite3Fts2HashFind(pHash, zName, nName+1); + + if( !p ){ + char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); + return; + } + + pRet = Tcl_NewObj(); + Tcl_IncrRefCount(pRet); + + if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){ + zErr = "error in xCreate()"; + goto finish; + } + pTokenizer->pModule = p; + if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){ + zErr = "error in xOpen()"; + goto finish; + } + pCsr->pTokenizer = pTokenizer; + + while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){ + Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); + zToken = &zInput[iStart]; + nToken = iEnd-iStart; + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); + } + + if( SQLITE_OK!=p->xClose(pCsr) ){ + zErr = "error in xClose()"; + goto finish; + } + if( SQLITE_OK!=p->xDestroy(pTokenizer) ){ + zErr = "error in xDestroy()"; + goto finish; + } + +finish: + if( zErr ){ + sqlite3_result_error(context, zErr, -1); + }else{ + sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); + } + Tcl_DecrRefCount(pRet); +} + +static +int registerTokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module *p +){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts2_tokenizer(?, ?)"; + + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); + sqlite3_step(pStmt); + + return sqlite3_finalize(pStmt); +} + +static +int queryFts2Tokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module **pp +){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts2_tokenizer(?)"; + + *pp = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ + memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + } + } + + return sqlite3_finalize(pStmt); +} + +void sqlite3Fts2SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); + +/* +** Implementation of the scalar function fts2_tokenizer_internal_test(). +** This function is used for testing only, it is not included in the +** build unless SQLITE_TEST is defined. +** +** The purpose of this is to test that the fts2_tokenizer() function +** can be used as designed by the C-code in the queryFts2Tokenizer and +** registerTokenizer() functions above. These two functions are repeated +** in the README.tokenizer file as an example, so it is important to +** test them. +** +** To run the tests, evaluate the fts2_tokenizer_internal_test() scalar +** function with no arguments. An assert() will fail if a problem is +** detected. i.e.: +** +** SELECT fts2_tokenizer_internal_test(); +** +*/ +static void intTestFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int rc; + const sqlite3_tokenizer_module *p1; + const sqlite3_tokenizer_module *p2; + sqlite3 *db = (sqlite3 *)sqlite3_user_data(context); + + /* Test the query function */ + sqlite3Fts2SimpleTokenizerModule(&p1); + rc = queryFts2Tokenizer(db, "simple", &p2); + assert( rc==SQLITE_OK ); + assert( p1==p2 ); + rc = queryFts2Tokenizer(db, "nosuchtokenizer", &p2); + assert( rc==SQLITE_ERROR ); + assert( p2==0 ); + assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") ); + + /* Test the storage function */ + rc = registerTokenizer(db, "nosuchtokenizer", p1); + assert( rc==SQLITE_OK ); + rc = queryFts2Tokenizer(db, "nosuchtokenizer", &p2); + assert( rc==SQLITE_OK ); + assert( p2==p1 ); + + sqlite3_result_text(context, "ok", -1, SQLITE_STATIC); +} + +#endif + +/* +** Set up SQL objects in database db used to access the contents of +** the hash table pointed to by argument pHash. The hash table must +** been initialized to use string keys, and to take a private copy +** of the key when a value is inserted. i.e. by a call similar to: +** +** sqlite3Fts2HashInit(pHash, FTS2_HASH_STRING, 1); +** +** This function adds a scalar function (see header comment above +** scalarFunc() in this file for details) and, if ENABLE_TABLE is +** defined at compilation time, a temporary virtual table (see header +** comment above struct HashTableVtab) to the database schema. Both +** provide read/write access to the contents of *pHash. +** +** The third argument to this function, zName, is used as the name +** of both the scalar and, if created, the virtual table. +*/ +int sqlite3Fts2InitHashTable( + sqlite3 *db, + fts2Hash *pHash, + const char *zName +){ + int rc = SQLITE_OK; + void *p = (void *)pHash; + const int any = SQLITE_ANY; + char *zTest = 0; + char *zTest2 = 0; + +#ifdef SQLITE_TEST + void *pdb = (void *)db; + zTest = sqlite3_mprintf("%s_test", zName); + zTest2 = sqlite3_mprintf("%s_internal_test", zName); + if( !zTest || !zTest2 ){ + rc = SQLITE_NOMEM; + } +#endif + + if( rc!=SQLITE_OK + || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0)) + || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0)) +#ifdef SQLITE_TEST + || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0)) + || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0)) + || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0)) +#endif + ); + + sqlite3_free(zTest); + sqlite3_free(zTest2); + return rc; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/fts2_tokenizer.h b/components/external/SQLite-3.8.1/ext/fts2/fts2_tokenizer.h new file mode 100644 index 0000000000000000000000000000000000000000..8db2048d6bf36177dc8e6f0d205cd435ba947d26 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/fts2_tokenizer.h @@ -0,0 +1,145 @@ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _FTS2_TOKENIZER_H_ +#define _FTS2_TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ +#include "sqlite3.h" + +/* +** Structures used by the tokenizer interface. When a new tokenizer +** implementation is registered, the caller provides a pointer to +** an sqlite3_tokenizer_module containing pointers to the callback +** functions that make up an implementation. +** +** When an fts2 table is created, it passes any arguments passed to +** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the +** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer +** implementation. The xCreate() function in turn returns an +** sqlite3_tokenizer structure representing the specific tokenizer to +** be used for the fts2 table (customized by the tokenizer clause arguments). +** +** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() +** method is called. It returns an sqlite3_tokenizer_cursor object +** that may be used to tokenize a specific input buffer based on +** the tokenization rules supplied by a specific sqlite3_tokenizer +** object. +*/ +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; + +struct sqlite3_tokenizer_module { + + /* + ** Structure version. Should always be set to 0. + */ + int iVersion; + + /* + ** Create a new tokenizer. The values in the argv[] array are the + ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL + ** TABLE statement that created the fts2 table. For example, if + ** the following SQL is executed: + ** + ** CREATE .. USING fts2( ... , tokenizer arg1 arg2) + ** + ** then argc is set to 2, and the argv[] array contains pointers + ** to the strings "arg1" and "arg2". + ** + ** This method should return either SQLITE_OK (0), or an SQLite error + ** code. If SQLITE_OK is returned, then *ppTokenizer should be set + ** to point at the newly created tokenizer structure. The generic + ** sqlite3_tokenizer.pModule variable should not be initialized by + ** this callback. The caller will do so. + */ + int (*xCreate)( + int argc, /* Size of argv array */ + const char *const*argv, /* Tokenizer argument strings */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + ); + + /* + ** Destroy an existing tokenizer. The fts2 module calls this method + ** exactly once for each successful call to xCreate(). + */ + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Create a tokenizer cursor to tokenize an input buffer. The caller + ** is responsible for ensuring that the input buffer remains valid + ** until the cursor is closed (using the xClose() method). + */ + int (*xOpen)( + sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ + const char *pInput, int nBytes, /* Input buffer */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ + ); + + /* + ** Destroy an existing tokenizer cursor. The fts2 module calls this + ** method exactly once for each successful call to xOpen(). + */ + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + + /* + ** Retrieve the next token from the tokenizer cursor pCursor. This + ** method should either return SQLITE_OK and set the values of the + ** "OUT" variables identified below, or SQLITE_DONE to indicate that + ** the end of the buffer has been reached, or an SQLite error code. + ** + ** *ppToken should be set to point at a buffer containing the + ** normalized version of the token (i.e. after any case-folding and/or + ** stemming has been performed). *pnBytes should be set to the length + ** of this buffer in bytes. The input text that generated the token is + ** identified by the byte offsets returned in *piStartOffset and + ** *piEndOffset. + ** + ** The buffer *ppToken is set to point at is managed by the tokenizer + ** implementation. It is only required to be valid until the next call + ** to xNext() or xClose(). + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xNext)( + sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ + const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ + int *piStartOffset, /* OUT: Byte offset of token in input buffer */ + int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ + int *piPosition /* OUT: Number of tokens returned before this one */ + ); +}; + +struct sqlite3_tokenizer { + const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +#endif /* _FTS2_TOKENIZER_H_ */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/fts2_tokenizer1.c b/components/external/SQLite-3.8.1/ext/fts2/fts2_tokenizer1.c new file mode 100644 index 0000000000000000000000000000000000000000..fe4f9eb4b56200d1e34f2ed163f399702786609d --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/fts2_tokenizer1.c @@ -0,0 +1,233 @@ +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** Implementation of the "simple" full-text-search tokenizer. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS2 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS2 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS2 is defined). +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) + + +#include +#include +#include +#include + +#include "sqlite3.h" +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT3 +#include "fts2_tokenizer.h" + +typedef struct simple_tokenizer { + sqlite3_tokenizer base; + char delim[128]; /* flag ASCII delimiters */ +} simple_tokenizer; + +typedef struct simple_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *pInput; /* input we are tokenizing */ + int nBytes; /* size of the input */ + int iOffset; /* current position in pInput */ + int iToken; /* index of next token to be returned */ + char *pToken; /* storage for current token */ + int nTokenAllocated; /* space allocated to zToken buffer */ +} simple_tokenizer_cursor; + + +/* Forward declaration */ +static const sqlite3_tokenizer_module simpleTokenizerModule; + +static int simpleDelim(simple_tokenizer *t, unsigned char c){ + return c<0x80 && t->delim[c]; +} + +/* +** Create a new tokenizer instance. +*/ +static int simpleCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer +){ + simple_tokenizer *t; + + t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t)); + if( t==NULL ) return SQLITE_NOMEM; + memset(t, 0, sizeof(*t)); + + /* TODO(shess) Delimiters need to remain the same from run to run, + ** else we need to reindex. One solution would be a meta-table to + ** track such information in the database, then we'd only want this + ** information on the initial create. + */ + if( argc>1 ){ + int i, n = strlen(argv[1]); + for(i=0; i=0x80 ){ + sqlite3_free(t); + return SQLITE_ERROR; + } + t->delim[ch] = 1; + } + } else { + /* Mark non-alphanumeric ASCII characters as delimiters */ + int i; + for(i=1; i<0x80; i++){ + t->delim[i] = !((i>='0' && i<='9') || (i>='A' && i<='Z') || + (i>='a' && i<='z')); + } + } + + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ + sqlite3_free(pTokenizer); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is pInput[0..nBytes-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int simpleOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *pInput, int nBytes, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + simple_tokenizer_cursor *c; + + c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); + if( c==NULL ) return SQLITE_NOMEM; + + c->pInput = pInput; + if( pInput==0 ){ + c->nBytes = 0; + }else if( nBytes<0 ){ + c->nBytes = (int)strlen(pInput); + }else{ + c->nBytes = nBytes; + } + c->iOffset = 0; /* start tokenizing at the beginning */ + c->iToken = 0; + c->pToken = NULL; /* no space allocated, yet. */ + c->nTokenAllocated = 0; + + *ppCursor = &c->base; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** simpleOpen() above. +*/ +static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + sqlite3_free(c->pToken); + sqlite3_free(c); + return SQLITE_OK; +} + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to simpleOpen(). +*/ +static int simpleNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer; + unsigned char *p = (unsigned char *)c->pInput; + + while( c->iOffsetnBytes ){ + int iStartOffset; + + /* Scan past delimiter characters */ + while( c->iOffsetnBytes && simpleDelim(t, p[c->iOffset]) ){ + c->iOffset++; + } + + /* Count non-delimiter characters. */ + iStartOffset = c->iOffset; + while( c->iOffsetnBytes && !simpleDelim(t, p[c->iOffset]) ){ + c->iOffset++; + } + + if( c->iOffset>iStartOffset ){ + int i, n = c->iOffset-iStartOffset; + if( n>c->nTokenAllocated ){ + c->nTokenAllocated = n+20; + c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated); + if( c->pToken==NULL ) return SQLITE_NOMEM; + } + for(i=0; ipToken[i] = (ch>='A' && ch<='Z') ? (ch - 'A' + 'a') : ch; + } + *ppToken = c->pToken; + *pnBytes = n; + *piStartOffset = iStartOffset; + *piEndOffset = c->iOffset; + *piPosition = c->iToken++; + + return SQLITE_OK; + } + } + return SQLITE_DONE; +} + +/* +** The set of routines that implement the simple tokenizer +*/ +static const sqlite3_tokenizer_module simpleTokenizerModule = { + 0, + simpleCreate, + simpleDestroy, + simpleOpen, + simpleClose, + simpleNext, +}; + +/* +** Allocate a new simple tokenizer. Return a pointer to the new +** tokenizer in *ppModule +*/ +void sqlite3Fts2SimpleTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &simpleTokenizerModule; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */ diff --git a/components/external/SQLite-3.8.1/ext/fts2/mkfts2amal.tcl b/components/external/SQLite-3.8.1/ext/fts2/mkfts2amal.tcl new file mode 100644 index 0000000000000000000000000000000000000000..5c8d1e93d78f5273ec2010d51e8377c0a0bd17e2 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts2/mkfts2amal.tcl @@ -0,0 +1,116 @@ +#!/usr/bin/tclsh +# +# This script builds a single C code file holding all of FTS2 code. +# The name of the output file is fts2amal.c. To build this file, +# first do: +# +# make target_source +# +# The make target above moves all of the source code files into +# a subdirectory named "tsrc". (This script expects to find the files +# there and will not work if they are not found.) +# +# After the "tsrc" directory has been created and populated, run +# this script: +# +# tclsh mkfts2amal.tcl +# +# The amalgamated FTS2 code will be written into fts2amal.c +# + +# Open the output file and write a header comment at the beginning +# of the file. +# +set out [open fts2amal.c w] +set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1] +puts $out [subst \ +{/****************************************************************************** +** This file is an amalgamation of separate C source files from the SQLite +** Full Text Search extension 2 (fts2). By combining all the individual C +** code files into this single large file, the entire code can be compiled +** as a one translation unit. This allows many compilers to do optimizations +** that would not be possible if the files were compiled separately. It also +** makes the code easier to import into other projects. +** +** This amalgamation was generated on $today. +*/}] + +# These are the header files used by FTS2. The first time any of these +# files are seen in a #include statement in the C code, include the complete +# text of the file in-line. The file only needs to be included once. +# +foreach hdr { + fts2.h + fts2_hash.h + fts2_tokenizer.h + sqlite3.h + sqlite3ext.h +} { + set available_hdr($hdr) 1 +} + +# 78 stars used for comment formatting. +set s78 \ +{*****************************************************************************} + +# Insert a comment into the code +# +proc section_comment {text} { + global out s78 + set n [string length $text] + set nstar [expr {60 - $n}] + set stars [string range $s78 0 $nstar] + puts $out "/************** $text $stars/" +} + +# Read the source file named $filename and write it into the +# sqlite3.c output file. If any #include statements are seen, +# process them approprately. +# +proc copy_file {filename} { + global seen_hdr available_hdr out + set tail [file tail $filename] + section_comment "Begin file $tail" + set in [open $filename r] + while {![eof $in]} { + set line [gets $in] + if {[regexp {^#\s*include\s+["<]([^">]+)[">]} $line all hdr]} { + if {[info exists available_hdr($hdr)]} { + if {$available_hdr($hdr)} { + section_comment "Include $hdr in the middle of $tail" + copy_file tsrc/$hdr + section_comment "Continuing where we left off in $tail" + } + } elseif {![info exists seen_hdr($hdr)]} { + set seen_hdr($hdr) 1 + puts $out $line + } + } elseif {[regexp {^#ifdef __cplusplus} $line]} { + puts $out "#if 0" + } elseif {[regexp {^#line} $line]} { + # Skip #line directives. + } else { + puts $out $line + } + } + close $in + section_comment "End of $tail" +} + + +# Process the source files. Process files containing commonly +# used subroutines first in order to help the compiler find +# inlining opportunities. +# +foreach file { + fts2.c + fts2_hash.c + fts2_porter.c + fts2_tokenizer.c + fts2_tokenizer1.c + fts2_icu.c +} { + copy_file tsrc/$file +} + +close $out diff --git a/components/external/SQLite-3.8.1/ext/fts3/README.content b/components/external/SQLite-3.8.1/ext/fts3/README.content new file mode 100644 index 0000000000000000000000000000000000000000..ab986754df212677e3529a793815a8fa8af9e60d --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/README.content @@ -0,0 +1,178 @@ + +FTS4 CONTENT OPTION + + Normally, in order to create a full-text index on a dataset, the FTS4 + module stores a copy of all indexed documents in a specially created + database table. + + As of SQLite version 3.7.9, FTS4 supports a new option - "content" - + designed to extend FTS4 to support the creation of full-text indexes where: + + * The indexed documents are not stored within the SQLite database + at all (a "contentless" FTS4 table), or + + * The indexed documents are stored in a database table created and + managed by the user (an "external content" FTS4 table). + + Because the indexed documents themselves are usually much larger than + the full-text index, the content option can sometimes be used to achieve + significant space savings. + +CONTENTLESS FTS4 TABLES + + In order to create an FTS4 table that does not store a copy of the indexed + documents at all, the content option should be set to an empty string. + For example, the following SQL creates such an FTS4 table with three + columns - "a", "b", and "c": + + CREATE VIRTUAL TABLE t1 USING fts4(content="", a, b, c); + + Data can be inserted into such an FTS4 table using an INSERT statements. + However, unlike ordinary FTS4 tables, the user must supply an explicit + integer docid value. For example: + + -- This statement is Ok: + INSERT INTO t1(docid, a, b, c) VALUES(1, 'a b c', 'd e f', 'g h i'); + + -- This statement causes an error, as no docid value has been provided: + INSERT INTO t1(a, b, c) VALUES('j k l', 'm n o', 'p q r'); + + It is not possible to UPDATE or DELETE a row stored in a contentless FTS4 + table. Attempting to do so is an error. + + Contentless FTS4 tables also support SELECT statements. However, it is + an error to attempt to retrieve the value of any table column other than + the docid column. The auxiliary function matchinfo() may be used, but + snippet() and offsets() may not. For example: + + -- The following statements are Ok: + SELECT docid FROM t1 WHERE t1 MATCH 'xxx'; + SELECT docid FROM t1 WHERE a MATCH 'xxx'; + SELECT matchinfo(t1) FROM t1 WHERE t1 MATCH 'xxx'; + + -- The following statements all cause errors, as the value of columns + -- other than docid are required to evaluate them. + SELECT * FROM t1; + SELECT a, b FROM t1 WHERE t1 MATCH 'xxx'; + SELECT docid FROM t1 WHERE a LIKE 'xxx%'; + SELECT snippet(t1) FROM t1 WHERE t1 MATCH 'xxx'; + + Errors related to attempting to retrieve column values other than docid + are runtime errors that occur within sqlite3_step(). In some cases, for + example if the MATCH expression in a SELECT query matches zero rows, there + may be no error at all even if a statement does refer to column values + other than docid. + +EXTERNAL CONTENT FTS4 TABLES + + An "external content" FTS4 table is similar to a contentless table, except + that if evaluation of a query requires the value of a column other than + docid, FTS4 attempts to retrieve that value from a table (or view, or + virtual table) nominated by the user (hereafter referred to as the "content + table"). The FTS4 module never writes to the content table, and writing + to the content table does not affect the full-text index. It is the + responsibility of the user to ensure that the content table and the + full-text index are consistent. + + An external content FTS4 table is created by setting the content option + to the name of a table (or view, or virtual table) that may be queried by + FTS4 to retrieve column values when required. If the nominated table does + not exist, then an external content table behaves in the same way as + a contentless table. For example: + + CREATE TABLE t2(id INTEGER PRIMARY KEY, a, b, c); + CREATE VIRTUAL TABLE t3 USING fts4(content="t2", a, c); + + Assuming the nominated table does exist, then its columns must be the same + as or a superset of those defined for the FTS table. + + When a users query on the FTS table requires a column value other than + docid, FTS attempts to read this value from the corresponding column of + the row in the content table with a rowid value equal to the current FTS + docid. Or, if such a row cannot be found in the content table, a NULL + value is used instead. For example: + + CREATE TABLE t2(id INTEGER PRIMARY KEY, a, b, c, d); + CREATE VIRTUAL TABLE t3 USING fts4(content="t2", b, c); + + INSERT INTO t2 VALUES(2, 'a b', 'c d', 'e f'); + INSERT INTO t2 VALUES(3, 'g h', 'i j', 'k l'); + INSERT INTO t3(docid, b, c) SELECT id, b, c FROM t2; + + -- The following query returns a single row with two columns containing + -- the text values "i j" and "k l". + -- + -- The query uses the full-text index to discover that the MATCH + -- term matches the row with docid=3. It then retrieves the values + -- of columns b and c from the row with rowid=3 in the content table + -- to return. + -- + SELECT * FROM t3 WHERE t3 MATCH 'k'; + + -- Following the UPDATE, the query still returns a single row, this + -- time containing the text values "xxx" and "yyy". This is because the + -- full-text index still indicates that the row with docid=3 matches + -- the FTS4 query 'k', even though the documents stored in the content + -- table have been modified. + -- + UPDATE t2 SET b = 'xxx', c = 'yyy' WHERE rowid = 3; + SELECT * FROM t3 WHERE t3 MATCH 'k'; + + -- Following the DELETE below, the query returns one row containing two + -- NULL values. NULL values are returned because FTS is unable to find + -- a row with rowid=3 within the content table. + -- + DELETE FROM t2; + SELECT * FROM t3 WHERE t3 MATCH 'k'; + + When a row is deleted from an external content FTS4 table, FTS4 needs to + retrieve the column values of the row being deleted from the content table. + This is so that FTS4 can update the full-text index entries for each token + that occurs within the deleted row to indicate that that row has been + deleted. If the content table row cannot be found, or if it contains values + inconsistent with the contents of the FTS index, the results can be difficult + to predict. The FTS index may be left containing entries corresponding to the + deleted row, which can lead to seemingly nonsensical results being returned + by subsequent SELECT queries. The same applies when a row is updated, as + internally an UPDATE is the same as a DELETE followed by an INSERT. + + Instead of writing separately to the full-text index and the content table, + some users may wish to use database triggers to keep the full-text index + up to date with respect to the set of documents stored in the content table. + For example, using the tables from earlier examples: + + CREATE TRIGGER t2_bu BEFORE UPDATE ON t2 BEGIN + DELETE FROM t3 WHERE docid=old.rowid; + END; + CREATE TRIGGER t2_bd BEFORE DELETE ON t2 BEGIN + DELETE FROM t3 WHERE docid=old.rowid; + END; + + CREATE TRIGGER t2_bu AFTER UPDATE ON t2 BEGIN + INSERT INTO t3(docid, b, c) VALUES(new.rowid, new.b, new.c); + END; + CREATE TRIGGER t2_bd AFTER INSERT ON t2 BEGIN + INSERT INTO t3(docid, b, c) VALUES(new.rowid, new.b, new.c); + END; + + The DELETE trigger must be fired before the actual delete takes place + on the content table. This is so that FTS4 can still retrieve the original + values in order to update the full-text index. And the INSERT trigger must + be fired after the new row is inserted, so as to handle the case where the + rowid is assigned automatically within the system. The UPDATE trigger must + be split into two parts, one fired before and one after the update of the + content table, for the same reasons. + + FTS4 features a special command similar to the 'optimize' command that + deletes the entire full-text index and rebuilds it based on the current + set of documents in the content table. Assuming again that "t3" is the + name of the external content FTS4 table, the command is: + + INSERT INTO t3(t3) VALUES('rebuild'); + + This command may also be used with ordinary FTS4 tables, although it may + only be useful if the full-text index has somehow become corrupt. It is an + error to attempt to rebuild the full-text index maintained by a contentless + FTS4 table. + + diff --git a/components/external/SQLite-3.8.1/ext/fts3/README.syntax b/components/external/SQLite-3.8.1/ext/fts3/README.syntax new file mode 100644 index 0000000000000000000000000000000000000000..01bc80c5fbe9fce601884bf9e6dec46dab62c97e --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/README.syntax @@ -0,0 +1,209 @@ + +1. OVERVIEW + + This README file describes the syntax of the arguments that may be passed to + the FTS3 MATCH operator used for full-text queries. For example, if table + "t1" is an Fts3 virtual table, the following SQL query: + + SELECT * FROM t1 WHERE MATCH + + may be used to retrieve all rows that match a specified for full-text query. + The text "" should be replaced by either the name of the fts3 table + (in this case "t1"), or by the name of one of the columns of the fts3 + table. should be replaced by an SQL expression that + computes to a string containing an Fts3 query. + + If the left-hand-side of the MATCH operator is set to the name of the + fts3 table, then by default the query may be matched against any column + of the table. If it is set to a column name, then by default the query + may only match the specified column. In both cases this may be overriden + as part of the query text (see sections 2 and 3 below). + + As of SQLite version 3.6.8, Fts3 supports two slightly different query + formats; the standard syntax, which is used by default, and the enhanced + query syntax which can be selected by compiling with the pre-processor + symbol SQLITE_ENABLE_FTS3_PARENTHESIS defined. + + -DSQLITE_ENABLE_FTS3_PARENTHESIS + +2. STANDARD QUERY SYNTAX + + When using the standard Fts3 query syntax, a query usually consists of a + list of terms (words) separated by white-space characters. To match a + query, a row (or column) of an Fts3 table must contain each of the specified + terms. For example, the following query: + + MATCH 'hello world' + + matches rows (or columns, if is the name of a column name) that + contain at least one instance of the token "hello", and at least one + instance of the token "world". Tokens may be grouped into phrases using + quotation marks. In this case, a matching row or column must contain each + of the tokens in the phrase in the order specified, with no intervening + tokens. For example, the query: + + MATCH '"hello world" joe" + + matches the first of the following two documents, but not the second or + third: + + "'Hello world', said Joe." + "One should always greet the world with a cheery hello, thought Joe." + "How many hello world programs could their be?" + + As well as grouping tokens together by phrase, the binary NEAR operator + may be used to search for rows that contain two or more specified tokens + or phrases within a specified proximity of each other. The NEAR operator + must always be specified in upper case. The word "near" in lower or mixed + case is treated as an ordinary token. For example, the following query: + + MATCH 'engineering NEAR consultancy' + + matches rows that contain both the "engineering" and "consultancy" tokens + in the same column with not more than 10 other words between them. It does + not matter which of the two terms occurs first in the document, only that + they be seperated by only 10 tokens or less. The user may also specify + a different required proximity by adding "/N" immediately after the NEAR + operator, where N is an integer. For example: + + MATCH 'engineering NEAR/5 consultancy' + + searches for a row containing an instance of each specified token seperated + by not more than 5 other tokens. More than one NEAR operator can be used + in as sequence. For example this query: + + MATCH 'reliable NEAR/2 engineering NEAR/5 consultancy' + + searches for a row that contains an instance of the token "reliable" + seperated by not more than two tokens from an instance of "engineering", + which is in turn separated by not more than 5 other tokens from an + instance of the term "consultancy". Phrases enclosed in quotes may + also be used as arguments to the NEAR operator. + + Similar to the NEAR operator, one or more tokens or phrases may be + separated by OR operators. In this case, only one of the specified tokens + or phrases must appear in the document. For example, the query: + + MATCH 'hello OR world' + + matches rows that contain either the term "hello", or the term "world", + or both. Note that unlike in many programming languages, the OR operator + has a higher precedence than the AND operators implied between white-space + separated tokens. The following query matches documents that contain the + term 'sqlite' and at least one of the terms 'fantastic' or 'impressive', + not those that contain both 'sqlite' and 'fantastic' or 'impressive': + + MATCH 'sqlite fantastic OR impressive' + + Any token that is part of an Fts3 query expression, whether or not it is + part of a phrase enclosed in quotes, may have a '*' character appended to + it. In this case, the token matches all terms that begin with the characters + of the token, not just those that exactly match it. For example, the + following query: + + MATCH 'sql*' + + matches all rows that contain the term "SQLite", as well as those that + contain "SQL". + + A token that is not part of a quoted phrase may be preceded by a '-' + character, which indicates that matching rows must not contain the + specified term. For example, the following: + + MATCH '"database engine" -sqlite' + + matches rows that contain the phrase "database engine" but do not contain + the term "sqlite". If the '-' character occurs inside a quoted phrase, + it is ignored. It is possible to use both the '-' prefix and the '*' postfix + on a single term. At this time, all Fts3 queries must contain at least + one term or phrase that is not preceded by the '-' prefix. + + Regardless of whether or not a table name or column name is used on the + left hand side of the MATCH operator, a specific column of the fts3 table + may be associated with each token in a query by preceding a token with + a column name followed by a ':' character. For example, regardless of what + is specified for , the following query requires that column "col1" + of the table contains the term "hello", and that column "col2" of the + table contains the term "world". If the table does not contain columns + named "col1" and "col2", then an error is returned and the query is + not run. + + MATCH 'col1:hello col2:world' + + It is not possible to associate a specific table column with a quoted + phrase or a term preceded by a '-' operator. A '*' character may be + appended to a term associated with a specific column for prefix matching. + +3. ENHANCED QUERY SYNTAX + + The enhanced query syntax is quite similar to the standard query syntax, + with the following four differences: + + 1) Parenthesis are supported. When using the enhanced query syntax, + parenthesis may be used to overcome the built-in precedence of the + supplied binary operators. For example, the following query: + + MATCH '(hello world) OR (simple example)' + + matches documents that contain both "hello" and "world", and documents + that contain both "simple" and "example". It is not possible to forumlate + such a query using the standard syntax. + + 2) Instead of separating tokens and phrases by whitespace, an AND operator + may be explicitly specified. This does not change query processing at + all, but may be used to improve readability. For example, the following + query is handled identically to the one above: + + MATCH '(hello AND world) OR (simple AND example)' + + As with the OR and NEAR operators, the AND operator must be specified + in upper case. The word "and" specified in lower or mixed case is + handled as a regular token. + + 3) The '-' token prefix is not supported. Instead, a new binary operator, + NOT, is included. The NOT operator requires that the query specified + as its left-hand operator matches, but that the query specified as the + right-hand operator does not. For example, to query for all rows that + contain the term "example" but not the term "simple", the following + query could be used: + + MATCH 'example NOT simple' + + As for all other operators, the NOT operator must be specified in + upper case. Otherwise it will be treated as a regular token. + + 4) Unlike in the standard syntax, where the OR operator has a higher + precedence than the implicit AND operator, when using the enhanced + syntax implicit and explict AND operators have a higher precedence + than OR operators. Using the enhanced syntax, the following two + queries are equivalent: + + MATCH 'sqlite fantastic OR impressive' + MATCH '(sqlite AND fantastic) OR impressive' + + however, when using the standard syntax, the query: + + MATCH 'sqlite fantastic OR impressive' + + is equivalent to the enhanced syntax query: + + MATCH 'sqlite AND (fantastic OR impressive)' + + The precedence of all enhanced syntax operators, in order from highest + to lowest, is: + + NEAR (highest precedence, tightest grouping) + NOT + AND + OR (lowest precedence, loosest grouping) + + Using the advanced syntax, it is possible to specify expressions enclosed + in parenthesis as operands to the NOT, AND and OR operators. However both + the left and right hand side operands of NEAR operators must be either + tokens or phrases. Attempting the following query will return an error: + + MATCH 'sqlite NEAR (fantastic OR impressive)' + + Queries of this form must be re-written as: + + MATCH 'sqlite NEAR fantastic OR sqlite NEAR impressive' diff --git a/components/external/SQLite-3.8.1/ext/fts3/README.tokenizers b/components/external/SQLite-3.8.1/ext/fts3/README.tokenizers new file mode 100644 index 0000000000000000000000000000000000000000..7f2345a81fd0e708fc5c78dfbecc0170a4944f72 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/README.tokenizers @@ -0,0 +1,133 @@ + +1. FTS3 Tokenizers + + When creating a new full-text table, FTS3 allows the user to select + the text tokenizer implementation to be used when indexing text + by specifying a "tokenize" clause as part of the CREATE VIRTUAL TABLE + statement: + + CREATE VIRTUAL TABLE USING fts3( + [, tokenize []] + ); + + The built-in tokenizers (valid values to pass as ) are + "simple", "porter" and "unicode". + + should consist of zero or more white-space separated + arguments to pass to the selected tokenizer implementation. The + interpretation of the arguments, if any, depends on the individual + tokenizer. + +2. Custom Tokenizers + + FTS3 allows users to provide custom tokenizer implementations. The + interface used to create a new tokenizer is defined and described in + the fts3_tokenizer.h source file. + + Registering a new FTS3 tokenizer is similar to registering a new + virtual table module with SQLite. The user passes a pointer to a + structure containing pointers to various callback functions that + make up the implementation of the new tokenizer type. For tokenizers, + the structure (defined in fts3_tokenizer.h) is called + "sqlite3_tokenizer_module". + + FTS3 does not expose a C-function that users call to register new + tokenizer types with a database handle. Instead, the pointer must + be encoded as an SQL blob value and passed to FTS3 through the SQL + engine by evaluating a special scalar function, "fts3_tokenizer()". + The fts3_tokenizer() function may be called with one or two arguments, + as follows: + + SELECT fts3_tokenizer(); + SELECT fts3_tokenizer(, ); + + Where is a string identifying the tokenizer and + is a pointer to an sqlite3_tokenizer_module + structure encoded as an SQL blob. If the second argument is present, + it is registered as tokenizer and a copy of it + returned. If only one argument is passed, a pointer to the tokenizer + implementation currently registered as is returned, + encoded as a blob. Or, if no such tokenizer exists, an SQL exception + (error) is raised. + + SECURITY: If the fts3 extension is used in an environment where potentially + malicious users may execute arbitrary SQL (i.e. gears), they should be + prevented from invoking the fts3_tokenizer() function, possibly using the + authorisation callback. + + See "Sample code" below for an example of calling the fts3_tokenizer() + function from C code. + +3. ICU Library Tokenizers + + If this extension is compiled with the SQLITE_ENABLE_ICU pre-processor + symbol defined, then there exists a built-in tokenizer named "icu" + implemented using the ICU library. The first argument passed to the + xCreate() method (see fts3_tokenizer.h) of this tokenizer may be + an ICU locale identifier. For example "tr_TR" for Turkish as used + in Turkey, or "en_AU" for English as used in Australia. For example: + + "CREATE VIRTUAL TABLE thai_text USING fts3(text, tokenizer icu th_TH)" + + The ICU tokenizer implementation is very simple. It splits the input + text according to the ICU rules for finding word boundaries and discards + any tokens that consist entirely of white-space. This may be suitable + for some applications in some locales, but not all. If more complex + processing is required, for example to implement stemming or + discard punctuation, this can be done by creating a tokenizer + implementation that uses the ICU tokenizer as part of its implementation. + + When using the ICU tokenizer this way, it is safe to overwrite the + contents of the strings returned by the xNext() method (see + fts3_tokenizer.h). + +4. Sample code. + + The following two code samples illustrate the way C code should invoke + the fts3_tokenizer() scalar function: + + int registerTokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module *p + ){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts3_tokenizer(?, ?)"; + + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); + sqlite3_step(pStmt); + + return sqlite3_finalize(pStmt); + } + + int queryTokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module **pp + ){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts3_tokenizer(?)"; + + *pp = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ + memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + } + } + + return sqlite3_finalize(pStmt); + } diff --git a/components/external/SQLite-3.8.1/ext/fts3/README.txt b/components/external/SQLite-3.8.1/ext/fts3/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..517a2a043466cac040cb45686e397c9c650bb93e --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/README.txt @@ -0,0 +1,4 @@ +This folder contains source code to the second full-text search +extension for SQLite. While the API is the same, this version uses a +substantially different storage schema from fts1, so tables will need +to be rebuilt. diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3.c b/components/external/SQLite-3.8.1/ext/fts3/fts3.c new file mode 100644 index 0000000000000000000000000000000000000000..dd6d38a59db14032cdaaa429f38020d631d450c4 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3.c @@ -0,0 +1,5711 @@ +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This is an SQLite module implementing full-text search. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ + +/* The full-text index is stored in a series of b+tree (-like) +** structures called segments which map terms to doclists. The +** structures are like b+trees in layout, but are constructed from the +** bottom up in optimal fashion and are not updatable. Since trees +** are built from the bottom up, things will be described from the +** bottom up. +** +** +**** Varints **** +** The basic unit of encoding is a variable-length integer called a +** varint. We encode variable-length integers in little-endian order +** using seven bits * per byte as follows: +** +** KEY: +** A = 0xxxxxxx 7 bits of data and one flag bit +** B = 1xxxxxxx 7 bits of data and one flag bit +** +** 7 bits - A +** 14 bits - BA +** 21 bits - BBA +** and so on. +** +** This is similar in concept to how sqlite encodes "varints" but +** the encoding is not the same. SQLite varints are big-endian +** are are limited to 9 bytes in length whereas FTS3 varints are +** little-endian and can be up to 10 bytes in length (in theory). +** +** Example encodings: +** +** 1: 0x01 +** 127: 0x7f +** 128: 0x81 0x00 +** +** +**** Document lists **** +** A doclist (document list) holds a docid-sorted list of hits for a +** given term. Doclists hold docids and associated token positions. +** A docid is the unique integer identifier for a single document. +** A position is the index of a word within the document. The first +** word of the document has a position of 0. +** +** FTS3 used to optionally store character offsets using a compile-time +** option. But that functionality is no longer supported. +** +** A doclist is stored like this: +** +** array { +** varint docid; (delta from previous doclist) +** array { (position list for column 0) +** varint position; (2 more than the delta from previous position) +** } +** array { +** varint POS_COLUMN; (marks start of position list for new column) +** varint column; (index of new column) +** array { +** varint position; (2 more than the delta from previous position) +** } +** } +** varint POS_END; (marks end of positions for this document. +** } +** +** Here, array { X } means zero or more occurrences of X, adjacent in +** memory. A "position" is an index of a token in the token stream +** generated by the tokenizer. Note that POS_END and POS_COLUMN occur +** in the same logical place as the position element, and act as sentinals +** ending a position list array. POS_END is 0. POS_COLUMN is 1. +** The positions numbers are not stored literally but rather as two more +** than the difference from the prior position, or the just the position plus +** 2 for the first position. Example: +** +** label: A B C D E F G H I J K +** value: 123 5 9 1 1 14 35 0 234 72 0 +** +** The 123 value is the first docid. For column zero in this document +** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1 +** at D signals the start of a new column; the 1 at E indicates that the +** new column is column number 1. There are two positions at 12 and 45 +** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The +** 234 at I is the delta to next docid (357). It has one position 70 +** (72-2) and then terminates with the 0 at K. +** +** A "position-list" is the list of positions for multiple columns for +** a single docid. A "column-list" is the set of positions for a single +** column. Hence, a position-list consists of one or more column-lists, +** a document record consists of a docid followed by a position-list and +** a doclist consists of one or more document records. +** +** A bare doclist omits the position information, becoming an +** array of varint-encoded docids. +** +**** Segment leaf nodes **** +** Segment leaf nodes store terms and doclists, ordered by term. Leaf +** nodes are written using LeafWriter, and read using LeafReader (to +** iterate through a single leaf node's data) and LeavesReader (to +** iterate through a segment's entire leaf layer). Leaf nodes have +** the format: +** +** varint iHeight; (height from leaf level, always 0) +** varint nTerm; (length of first term) +** char pTerm[nTerm]; (content of first term) +** varint nDoclist; (length of term's associated doclist) +** char pDoclist[nDoclist]; (content of doclist) +** array { +** (further terms are delta-encoded) +** varint nPrefix; (length of prefix shared with previous term) +** varint nSuffix; (length of unshared suffix) +** char pTermSuffix[nSuffix];(unshared suffix of next term) +** varint nDoclist; (length of term's associated doclist) +** char pDoclist[nDoclist]; (content of doclist) +** } +** +** Here, array { X } means zero or more occurrences of X, adjacent in +** memory. +** +** Leaf nodes are broken into blocks which are stored contiguously in +** the %_segments table in sorted order. This means that when the end +** of a node is reached, the next term is in the node with the next +** greater node id. +** +** New data is spilled to a new leaf node when the current node +** exceeds LEAF_MAX bytes (default 2048). New data which itself is +** larger than STANDALONE_MIN (default 1024) is placed in a standalone +** node (a leaf node with a single term and doclist). The goal of +** these settings is to pack together groups of small doclists while +** making it efficient to directly access large doclists. The +** assumption is that large doclists represent terms which are more +** likely to be query targets. +** +** TODO(shess) It may be useful for blocking decisions to be more +** dynamic. For instance, it may make more sense to have a 2.5k leaf +** node rather than splitting into 2k and .5k nodes. My intuition is +** that this might extend through 2x or 4x the pagesize. +** +** +**** Segment interior nodes **** +** Segment interior nodes store blockids for subtree nodes and terms +** to describe what data is stored by the each subtree. Interior +** nodes are written using InteriorWriter, and read using +** InteriorReader. InteriorWriters are created as needed when +** SegmentWriter creates new leaf nodes, or when an interior node +** itself grows too big and must be split. The format of interior +** nodes: +** +** varint iHeight; (height from leaf level, always >0) +** varint iBlockid; (block id of node's leftmost subtree) +** optional { +** varint nTerm; (length of first term) +** char pTerm[nTerm]; (content of first term) +** array { +** (further terms are delta-encoded) +** varint nPrefix; (length of shared prefix with previous term) +** varint nSuffix; (length of unshared suffix) +** char pTermSuffix[nSuffix]; (unshared suffix of next term) +** } +** } +** +** Here, optional { X } means an optional element, while array { X } +** means zero or more occurrences of X, adjacent in memory. +** +** An interior node encodes n terms separating n+1 subtrees. The +** subtree blocks are contiguous, so only the first subtree's blockid +** is encoded. The subtree at iBlockid will contain all terms less +** than the first term encoded (or all terms if no term is encoded). +** Otherwise, for terms greater than or equal to pTerm[i] but less +** than pTerm[i+1], the subtree for that term will be rooted at +** iBlockid+i. Interior nodes only store enough term data to +** distinguish adjacent children (if the rightmost term of the left +** child is "something", and the leftmost term of the right child is +** "wicked", only "w" is stored). +** +** New data is spilled to a new interior node at the same height when +** the current node exceeds INTERIOR_MAX bytes (default 2048). +** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing +** interior nodes and making the tree too skinny. The interior nodes +** at a given height are naturally tracked by interior nodes at +** height+1, and so on. +** +** +**** Segment directory **** +** The segment directory in table %_segdir stores meta-information for +** merging and deleting segments, and also the root node of the +** segment's tree. +** +** The root node is the top node of the segment's tree after encoding +** the entire segment, restricted to ROOT_MAX bytes (default 1024). +** This could be either a leaf node or an interior node. If the top +** node requires more than ROOT_MAX bytes, it is flushed to %_segments +** and a new root interior node is generated (which should always fit +** within ROOT_MAX because it only needs space for 2 varints, the +** height and the blockid of the previous root). +** +** The meta-information in the segment directory is: +** level - segment level (see below) +** idx - index within level +** - (level,idx uniquely identify a segment) +** start_block - first leaf node +** leaves_end_block - last leaf node +** end_block - last block (including interior nodes) +** root - contents of root node +** +** If the root node is a leaf node, then start_block, +** leaves_end_block, and end_block are all 0. +** +** +**** Segment merging **** +** To amortize update costs, segments are grouped into levels and +** merged in batches. Each increase in level represents exponentially +** more documents. +** +** New documents (actually, document updates) are tokenized and +** written individually (using LeafWriter) to a level 0 segment, with +** incrementing idx. When idx reaches MERGE_COUNT (default 16), all +** level 0 segments are merged into a single level 1 segment. Level 1 +** is populated like level 0, and eventually MERGE_COUNT level 1 +** segments are merged to a single level 2 segment (representing +** MERGE_COUNT^2 updates), and so on. +** +** A segment merge traverses all segments at a given level in +** parallel, performing a straightforward sorted merge. Since segment +** leaf nodes are written in to the %_segments table in order, this +** merge traverses the underlying sqlite disk structures efficiently. +** After the merge, all segment blocks from the merged level are +** deleted. +** +** MERGE_COUNT controls how often we merge segments. 16 seems to be +** somewhat of a sweet spot for insertion performance. 32 and 64 show +** very similar performance numbers to 16 on insertion, though they're +** a tiny bit slower (perhaps due to more overhead in merge-time +** sorting). 8 is about 20% slower than 16, 4 about 50% slower than +** 16, 2 about 66% slower than 16. +** +** At query time, high MERGE_COUNT increases the number of segments +** which need to be scanned and merged. For instance, with 100k docs +** inserted: +** +** MERGE_COUNT segments +** 16 25 +** 8 12 +** 4 10 +** 2 6 +** +** This appears to have only a moderate impact on queries for very +** frequent terms (which are somewhat dominated by segment merge +** costs), and infrequent and non-existent terms still seem to be fast +** even with many segments. +** +** TODO(shess) That said, it would be nice to have a better query-side +** argument for MERGE_COUNT of 16. Also, it is possible/likely that +** optimizations to things like doclist merging will swing the sweet +** spot around. +** +** +** +**** Handling of deletions and updates **** +** Since we're using a segmented structure, with no docid-oriented +** index into the term index, we clearly cannot simply update the term +** index when a document is deleted or updated. For deletions, we +** write an empty doclist (varint(docid) varint(POS_END)), for updates +** we simply write the new doclist. Segment merges overwrite older +** data for a particular docid with newer data, so deletes or updates +** will eventually overtake the earlier data and knock it out. The +** query logic likewise merges doclists so that newer data knocks out +** older data. +*/ + +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE) +# define SQLITE_CORE 1 +#endif + +#include +#include +#include +#include +#include +#include + +#include "fts3.h" +#ifndef SQLITE_CORE +# include "sqlite3ext.h" + SQLITE_EXTENSION_INIT1 +#endif + +static int fts3EvalNext(Fts3Cursor *pCsr); +static int fts3EvalStart(Fts3Cursor *pCsr); +static int fts3TermSegReaderCursor( + Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **); + +/* +** Write a 64-bit variable-length integer to memory starting at p[0]. +** The length of data written will be between 1 and FTS3_VARINT_MAX bytes. +** The number of bytes written is returned. +*/ +int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){ + unsigned char *q = (unsigned char *) p; + sqlite_uint64 vu = v; + do{ + *q++ = (unsigned char) ((vu & 0x7f) | 0x80); + vu >>= 7; + }while( vu!=0 ); + q[-1] &= 0x7f; /* turn off high bit in final byte */ + assert( q - (unsigned char *)p <= FTS3_VARINT_MAX ); + return (int) (q - (unsigned char *)p); +} + +/* +** Read a 64-bit variable-length integer from memory starting at p[0]. +** Return the number of bytes read, or 0 on error. +** The value is stored in *v. +*/ +int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){ + const unsigned char *q = (const unsigned char *) p; + sqlite_uint64 x = 0, y = 1; + while( (*q&0x80)==0x80 && q-(unsigned char *)p>= 7; + }while( v!=0 ); + return i; +} + +/* +** Convert an SQL-style quoted string into a normal string by removing +** the quote characters. The conversion is done in-place. If the +** input does not begin with a quote character, then this routine +** is a no-op. +** +** Examples: +** +** "abc" becomes abc +** 'xyz' becomes xyz +** [pqr] becomes pqr +** `mno` becomes mno +** +*/ +void sqlite3Fts3Dequote(char *z){ + char quote; /* Quote character (if any ) */ + + quote = z[0]; + if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ + int iIn = 1; /* Index of next byte to read from input */ + int iOut = 0; /* Index of next byte to write to output */ + + /* If the first byte was a '[', then the close-quote character is a ']' */ + if( quote=='[' ) quote = ']'; + + while( ALWAYS(z[iIn]) ){ + if( z[iIn]==quote ){ + if( z[iIn+1]!=quote ) break; + z[iOut++] = quote; + iIn += 2; + }else{ + z[iOut++] = z[iIn++]; + } + } + z[iOut] = '\0'; + } +} + +/* +** Read a single varint from the doclist at *pp and advance *pp to point +** to the first byte past the end of the varint. Add the value of the varint +** to *pVal. +*/ +static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){ + sqlite3_int64 iVal; + *pp += sqlite3Fts3GetVarint(*pp, &iVal); + *pVal += iVal; +} + +/* +** When this function is called, *pp points to the first byte following a +** varint that is part of a doclist (or position-list, or any other list +** of varints). This function moves *pp to point to the start of that varint, +** and sets *pVal by the varint value. +** +** Argument pStart points to the first byte of the doclist that the +** varint is part of. +*/ +static void fts3GetReverseVarint( + char **pp, + char *pStart, + sqlite3_int64 *pVal +){ + sqlite3_int64 iVal; + char *p; + + /* Pointer p now points at the first byte past the varint we are + ** interested in. So, unless the doclist is corrupt, the 0x80 bit is + ** clear on character p[-1]. */ + for(p = (*pp)-2; p>=pStart && *p&0x80; p--); + p++; + *pp = p; + + sqlite3Fts3GetVarint(p, &iVal); + *pVal = iVal; +} + +/* +** The xDisconnect() virtual table method. +*/ +static int fts3DisconnectMethod(sqlite3_vtab *pVtab){ + Fts3Table *p = (Fts3Table *)pVtab; + int i; + + assert( p->nPendingData==0 ); + assert( p->pSegments==0 ); + + /* Free any prepared statements held */ + for(i=0; iaStmt); i++){ + sqlite3_finalize(p->aStmt[i]); + } + sqlite3_free(p->zSegmentsTbl); + sqlite3_free(p->zReadExprlist); + sqlite3_free(p->zWriteExprlist); + sqlite3_free(p->zContentTbl); + sqlite3_free(p->zLanguageid); + + /* Invoke the tokenizer destructor to free the tokenizer. */ + p->pTokenizer->pModule->xDestroy(p->pTokenizer); + + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Construct one or more SQL statements from the format string given +** and then evaluate those statements. The success code is written +** into *pRc. +** +** If *pRc is initially non-zero then this routine is a no-op. +*/ +static void fts3DbExec( + int *pRc, /* Success code */ + sqlite3 *db, /* Database in which to run SQL */ + const char *zFormat, /* Format string for SQL */ + ... /* Arguments to the format string */ +){ + va_list ap; + char *zSql; + if( *pRc ) return; + va_start(ap, zFormat); + zSql = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + if( zSql==0 ){ + *pRc = SQLITE_NOMEM; + }else{ + *pRc = sqlite3_exec(db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } +} + +/* +** The xDestroy() virtual table method. +*/ +static int fts3DestroyMethod(sqlite3_vtab *pVtab){ + Fts3Table *p = (Fts3Table *)pVtab; + int rc = SQLITE_OK; /* Return code */ + const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */ + sqlite3 *db = p->db; /* Database handle */ + + /* Drop the shadow tables */ + if( p->zContentTbl==0 ){ + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName); + } + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName); + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName); + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName); + fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName); + + /* If everything has worked, invoke fts3DisconnectMethod() to free the + ** memory associated with the Fts3Table structure and return SQLITE_OK. + ** Otherwise, return an SQLite error code. + */ + return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc); +} + + +/* +** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table +** passed as the first argument. This is done as part of the xConnect() +** and xCreate() methods. +** +** If *pRc is non-zero when this function is called, it is a no-op. +** Otherwise, if an error occurs, an SQLite error code is stored in *pRc +** before returning. +*/ +static void fts3DeclareVtab(int *pRc, Fts3Table *p){ + if( *pRc==SQLITE_OK ){ + int i; /* Iterator variable */ + int rc; /* Return code */ + char *zSql; /* SQL statement passed to declare_vtab() */ + char *zCols; /* List of user defined columns */ + const char *zLanguageid; + + zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid"); + sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); + + /* Create a list of user columns for the virtual table */ + zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]); + for(i=1; zCols && inColumn; i++){ + zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]); + } + + /* Create the whole "CREATE TABLE" statement to pass to SQLite */ + zSql = sqlite3_mprintf( + "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", + zCols, p->zName, zLanguageid + ); + if( !zCols || !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_declare_vtab(p->db, zSql); + } + + sqlite3_free(zSql); + sqlite3_free(zCols); + *pRc = rc; + } +} + +/* +** Create the %_stat table if it does not already exist. +*/ +void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){ + fts3DbExec(pRc, p->db, + "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'" + "(id INTEGER PRIMARY KEY, value BLOB);", + p->zDb, p->zName + ); + if( (*pRc)==SQLITE_OK ) p->bHasStat = 1; +} + +/* +** Create the backing store tables (%_content, %_segments and %_segdir) +** required by the FTS3 table passed as the only argument. This is done +** as part of the vtab xCreate() method. +** +** If the p->bHasDocsize boolean is true (indicating that this is an +** FTS4 table, not an FTS3 table) then also create the %_docsize and +** %_stat tables required by FTS4. +*/ +static int fts3CreateTables(Fts3Table *p){ + int rc = SQLITE_OK; /* Return code */ + int i; /* Iterator variable */ + sqlite3 *db = p->db; /* The database connection */ + + if( p->zContentTbl==0 ){ + const char *zLanguageid = p->zLanguageid; + char *zContentCols; /* Columns of %_content table */ + + /* Create a list of user columns for the content table */ + zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY"); + for(i=0; zContentCols && inColumn; i++){ + char *z = p->azColumn[i]; + zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z); + } + if( zLanguageid && zContentCols ){ + zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid); + } + if( zContentCols==0 ) rc = SQLITE_NOMEM; + + /* Create the content table */ + fts3DbExec(&rc, db, + "CREATE TABLE %Q.'%q_content'(%s)", + p->zDb, p->zName, zContentCols + ); + sqlite3_free(zContentCols); + } + + /* Create other tables */ + fts3DbExec(&rc, db, + "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);", + p->zDb, p->zName + ); + fts3DbExec(&rc, db, + "CREATE TABLE %Q.'%q_segdir'(" + "level INTEGER," + "idx INTEGER," + "start_block INTEGER," + "leaves_end_block INTEGER," + "end_block INTEGER," + "root BLOB," + "PRIMARY KEY(level, idx)" + ");", + p->zDb, p->zName + ); + if( p->bHasDocsize ){ + fts3DbExec(&rc, db, + "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);", + p->zDb, p->zName + ); + } + assert( p->bHasStat==p->bFts4 ); + if( p->bHasStat ){ + sqlite3Fts3CreateStatTable(&rc, p); + } + return rc; +} + +/* +** Store the current database page-size in bytes in p->nPgsz. +** +** If *pRc is non-zero when this function is called, it is a no-op. +** Otherwise, if an error occurs, an SQLite error code is stored in *pRc +** before returning. +*/ +static void fts3DatabasePageSize(int *pRc, Fts3Table *p){ + if( *pRc==SQLITE_OK ){ + int rc; /* Return code */ + char *zSql; /* SQL text "PRAGMA %Q.page_size" */ + sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */ + + zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb); + if( !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_step(pStmt); + p->nPgsz = sqlite3_column_int(pStmt, 0); + rc = sqlite3_finalize(pStmt); + }else if( rc==SQLITE_AUTH ){ + p->nPgsz = 1024; + rc = SQLITE_OK; + } + } + assert( p->nPgsz>0 || rc!=SQLITE_OK ); + sqlite3_free(zSql); + *pRc = rc; + } +} + +/* +** "Special" FTS4 arguments are column specifications of the following form: +** +** = +** +** There may not be whitespace surrounding the "=" character. The +** term may be quoted, but the may not. +*/ +static int fts3IsSpecialColumn( + const char *z, + int *pnKey, + char **pzValue +){ + char *zValue; + const char *zCsr = z; + + while( *zCsr!='=' ){ + if( *zCsr=='\0' ) return 0; + zCsr++; + } + + *pnKey = (int)(zCsr-z); + zValue = sqlite3_mprintf("%s", &zCsr[1]); + if( zValue ){ + sqlite3Fts3Dequote(zValue); + } + *pzValue = zValue; + return 1; +} + +/* +** Append the output of a printf() style formatting to an existing string. +*/ +static void fts3Appendf( + int *pRc, /* IN/OUT: Error code */ + char **pz, /* IN/OUT: Pointer to string buffer */ + const char *zFormat, /* Printf format string to append */ + ... /* Arguments for printf format string */ +){ + if( *pRc==SQLITE_OK ){ + va_list ap; + char *z; + va_start(ap, zFormat); + z = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + if( z && *pz ){ + char *z2 = sqlite3_mprintf("%s%s", *pz, z); + sqlite3_free(z); + z = z2; + } + if( z==0 ) *pRc = SQLITE_NOMEM; + sqlite3_free(*pz); + *pz = z; + } +} + +/* +** Return a copy of input string zInput enclosed in double-quotes (") and +** with all double quote characters escaped. For example: +** +** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\"" +** +** The pointer returned points to memory obtained from sqlite3_malloc(). It +** is the callers responsibility to call sqlite3_free() to release this +** memory. +*/ +static char *fts3QuoteId(char const *zInput){ + int nRet; + char *zRet; + nRet = 2 + (int)strlen(zInput)*2 + 1; + zRet = sqlite3_malloc(nRet); + if( zRet ){ + int i; + char *z = zRet; + *(z++) = '"'; + for(i=0; zInput[i]; i++){ + if( zInput[i]=='"' ) *(z++) = '"'; + *(z++) = zInput[i]; + } + *(z++) = '"'; + *(z++) = '\0'; + } + return zRet; +} + +/* +** Return a list of comma separated SQL expressions and a FROM clause that +** could be used in a SELECT statement such as the following: +** +** SELECT FROM %_content AS x ... +** +** to return the docid, followed by each column of text data in order +** from left to write. If parameter zFunc is not NULL, then instead of +** being returned directly each column of text data is passed to an SQL +** function named zFunc first. For example, if zFunc is "unzip" and the +** table has the three user-defined columns "a", "b", and "c", the following +** string is returned: +** +** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x" +** +** The pointer returned points to a buffer allocated by sqlite3_malloc(). It +** is the responsibility of the caller to eventually free it. +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and +** a NULL pointer is returned). Otherwise, if an OOM error is encountered +** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If +** no error occurs, *pRc is left unmodified. +*/ +static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){ + char *zRet = 0; + char *zFree = 0; + char *zFunction; + int i; + + if( p->zContentTbl==0 ){ + if( !zFunc ){ + zFunction = ""; + }else{ + zFree = zFunction = fts3QuoteId(zFunc); + } + fts3Appendf(pRc, &zRet, "docid"); + for(i=0; inColumn; i++){ + fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]); + } + if( p->zLanguageid ){ + fts3Appendf(pRc, &zRet, ", x.%Q", "langid"); + } + sqlite3_free(zFree); + }else{ + fts3Appendf(pRc, &zRet, "rowid"); + for(i=0; inColumn; i++){ + fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]); + } + if( p->zLanguageid ){ + fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid); + } + } + fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", + p->zDb, + (p->zContentTbl ? p->zContentTbl : p->zName), + (p->zContentTbl ? "" : "_content") + ); + return zRet; +} + +/* +** Return a list of N comma separated question marks, where N is the number +** of columns in the %_content table (one for the docid plus one for each +** user-defined text column). +** +** If argument zFunc is not NULL, then all but the first question mark +** is preceded by zFunc and an open bracket, and followed by a closed +** bracket. For example, if zFunc is "zip" and the FTS3 table has three +** user-defined text columns, the following string is returned: +** +** "?, zip(?), zip(?), zip(?)" +** +** The pointer returned points to a buffer allocated by sqlite3_malloc(). It +** is the responsibility of the caller to eventually free it. +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and +** a NULL pointer is returned). Otherwise, if an OOM error is encountered +** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If +** no error occurs, *pRc is left unmodified. +*/ +static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){ + char *zRet = 0; + char *zFree = 0; + char *zFunction; + int i; + + if( !zFunc ){ + zFunction = ""; + }else{ + zFree = zFunction = fts3QuoteId(zFunc); + } + fts3Appendf(pRc, &zRet, "?"); + for(i=0; inColumn; i++){ + fts3Appendf(pRc, &zRet, ",%s(?)", zFunction); + } + if( p->zLanguageid ){ + fts3Appendf(pRc, &zRet, ", ?"); + } + sqlite3_free(zFree); + return zRet; +} + +/* +** This function interprets the string at (*pp) as a non-negative integer +** value. It reads the integer and sets *pnOut to the value read, then +** sets *pp to point to the byte immediately following the last byte of +** the integer value. +** +** Only decimal digits ('0'..'9') may be part of an integer value. +** +** If *pp does not being with a decimal digit SQLITE_ERROR is returned and +** the output value undefined. Otherwise SQLITE_OK is returned. +** +** This function is used when parsing the "prefix=" FTS4 parameter. +*/ +static int fts3GobbleInt(const char **pp, int *pnOut){ + const char *p; /* Iterator pointer */ + int nInt = 0; /* Output value */ + + for(p=*pp; p[0]>='0' && p[0]<='9'; p++){ + nInt = nInt * 10 + (p[0] - '0'); + } + if( p==*pp ) return SQLITE_ERROR; + *pnOut = nInt; + *pp = p; + return SQLITE_OK; +} + +/* +** This function is called to allocate an array of Fts3Index structures +** representing the indexes maintained by the current FTS table. FTS tables +** always maintain the main "terms" index, but may also maintain one or +** more "prefix" indexes, depending on the value of the "prefix=" parameter +** (if any) specified as part of the CREATE VIRTUAL TABLE statement. +** +** Argument zParam is passed the value of the "prefix=" option if one was +** specified, or NULL otherwise. +** +** If no error occurs, SQLITE_OK is returned and *apIndex set to point to +** the allocated array. *pnIndex is set to the number of elements in the +** array. If an error does occur, an SQLite error code is returned. +** +** Regardless of whether or not an error is returned, it is the responsibility +** of the caller to call sqlite3_free() on the output array to free it. +*/ +static int fts3PrefixParameter( + const char *zParam, /* ABC in prefix=ABC parameter to parse */ + int *pnIndex, /* OUT: size of *apIndex[] array */ + struct Fts3Index **apIndex /* OUT: Array of indexes for this table */ +){ + struct Fts3Index *aIndex; /* Allocated array */ + int nIndex = 1; /* Number of entries in array */ + + if( zParam && zParam[0] ){ + const char *p; + nIndex++; + for(p=zParam; *p; p++){ + if( *p==',' ) nIndex++; + } + } + + aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex); + *apIndex = aIndex; + *pnIndex = nIndex; + if( !aIndex ){ + return SQLITE_NOMEM; + } + + memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex); + if( zParam ){ + const char *p = zParam; + int i; + for(i=1; i module name ("fts3" or "fts4") +** argv[1] -> database name +** argv[2] -> table name +** argv[...] -> "column name" and other module argument fields. +*/ +static int fts3InitVtab( + int isCreate, /* True for xCreate, false for xConnect */ + sqlite3 *db, /* The SQLite database connection */ + void *pAux, /* Hash table containing tokenizers */ + int argc, /* Number of elements in argv array */ + const char * const *argv, /* xCreate/xConnect argument array */ + sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ + char **pzErr /* Write any error message here */ +){ + Fts3Hash *pHash = (Fts3Hash *)pAux; + Fts3Table *p = 0; /* Pointer to allocated vtab */ + int rc = SQLITE_OK; /* Return code */ + int i; /* Iterator variable */ + int nByte; /* Size of allocation used for *p */ + int iCol; /* Column index */ + int nString = 0; /* Bytes required to hold all column names */ + int nCol = 0; /* Number of columns in the FTS table */ + char *zCsr; /* Space for holding column names */ + int nDb; /* Bytes required to hold database name */ + int nName; /* Bytes required to hold table name */ + int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */ + const char **aCol; /* Array of column names */ + sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */ + + int nIndex; /* Size of aIndex[] array */ + struct Fts3Index *aIndex = 0; /* Array of indexes for this table */ + + /* The results of parsing supported FTS4 key=value options: */ + int bNoDocsize = 0; /* True to omit %_docsize table */ + int bDescIdx = 0; /* True to store descending indexes */ + char *zPrefix = 0; /* Prefix parameter value (or NULL) */ + char *zCompress = 0; /* compress=? parameter (or NULL) */ + char *zUncompress = 0; /* uncompress=? parameter (or NULL) */ + char *zContent = 0; /* content=? parameter (or NULL) */ + char *zLanguageid = 0; /* languageid=? parameter (or NULL) */ + char **azNotindexed = 0; /* The set of notindexed= columns */ + int nNotindexed = 0; /* Size of azNotindexed[] array */ + + assert( strlen(argv[0])==4 ); + assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4) + || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4) + ); + + nDb = (int)strlen(argv[1]) + 1; + nName = (int)strlen(argv[2]) + 1; + + nByte = sizeof(const char *) * (argc-2); + aCol = (const char **)sqlite3_malloc(nByte); + if( aCol ){ + memset((void*)aCol, 0, nByte); + azNotindexed = (char **)sqlite3_malloc(nByte); + } + if( azNotindexed ){ + memset(azNotindexed, 0, nByte); + } + if( !aCol || !azNotindexed ){ + rc = SQLITE_NOMEM; + goto fts3_init_out; + } + + /* Loop through all of the arguments passed by the user to the FTS3/4 + ** module (i.e. all the column names and special arguments). This loop + ** does the following: + ** + ** + Figures out the number of columns the FTSX table will have, and + ** the number of bytes of space that must be allocated to store copies + ** of the column names. + ** + ** + If there is a tokenizer specification included in the arguments, + ** initializes the tokenizer pTokenizer. + */ + for(i=3; rc==SQLITE_OK && i8 + && 0==sqlite3_strnicmp(z, "tokenize", 8) + && 0==sqlite3Fts3IsIdChar(z[8]) + ){ + rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr); + } + + /* Check if it is an FTS4 special argument. */ + else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){ + struct Fts4Option { + const char *zOpt; + int nOpt; + } aFts4Opt[] = { + { "matchinfo", 9 }, /* 0 -> MATCHINFO */ + { "prefix", 6 }, /* 1 -> PREFIX */ + { "compress", 8 }, /* 2 -> COMPRESS */ + { "uncompress", 10 }, /* 3 -> UNCOMPRESS */ + { "order", 5 }, /* 4 -> ORDER */ + { "content", 7 }, /* 5 -> CONTENT */ + { "languageid", 10 }, /* 6 -> LANGUAGEID */ + { "notindexed", 10 } /* 7 -> NOTINDEXED */ + }; + + int iOpt; + if( !zVal ){ + rc = SQLITE_NOMEM; + }else{ + for(iOpt=0; iOptnOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){ + break; + } + } + if( iOpt==SizeofArray(aFts4Opt) ){ + *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z); + rc = SQLITE_ERROR; + }else{ + switch( iOpt ){ + case 0: /* MATCHINFO */ + if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){ + *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal); + rc = SQLITE_ERROR; + } + bNoDocsize = 1; + break; + + case 1: /* PREFIX */ + sqlite3_free(zPrefix); + zPrefix = zVal; + zVal = 0; + break; + + case 2: /* COMPRESS */ + sqlite3_free(zCompress); + zCompress = zVal; + zVal = 0; + break; + + case 3: /* UNCOMPRESS */ + sqlite3_free(zUncompress); + zUncompress = zVal; + zVal = 0; + break; + + case 4: /* ORDER */ + if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) + && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) + ){ + *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal); + rc = SQLITE_ERROR; + } + bDescIdx = (zVal[0]=='d' || zVal[0]=='D'); + break; + + case 5: /* CONTENT */ + sqlite3_free(zContent); + zContent = zVal; + zVal = 0; + break; + + case 6: /* LANGUAGEID */ + assert( iOpt==6 ); + sqlite3_free(zLanguageid); + zLanguageid = zVal; + zVal = 0; + break; + + case 7: /* NOTINDEXED */ + azNotindexed[nNotindexed++] = zVal; + zVal = 0; + break; + } + } + sqlite3_free(zVal); + } + } + + /* Otherwise, the argument is a column name. */ + else { + nString += (int)(strlen(z) + 1); + aCol[nCol++] = z; + } + } + + /* If a content=xxx option was specified, the following: + ** + ** 1. Ignore any compress= and uncompress= options. + ** + ** 2. If no column names were specified as part of the CREATE VIRTUAL + ** TABLE statement, use all columns from the content table. + */ + if( rc==SQLITE_OK && zContent ){ + sqlite3_free(zCompress); + sqlite3_free(zUncompress); + zCompress = 0; + zUncompress = 0; + if( nCol==0 ){ + sqlite3_free((void*)aCol); + aCol = 0; + rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString); + + /* If a languageid= option was specified, remove the language id + ** column from the aCol[] array. */ + if( rc==SQLITE_OK && zLanguageid ){ + int j; + for(j=0; jdb = db; + p->nColumn = nCol; + p->nPendingData = 0; + p->azColumn = (char **)&p[1]; + p->pTokenizer = pTokenizer; + p->nMaxPendingData = FTS3_MAX_PENDING_DATA; + p->bHasDocsize = (isFts4 && bNoDocsize==0); + p->bHasStat = isFts4; + p->bFts4 = isFts4; + p->bDescIdx = bDescIdx; + p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */ + p->zContentTbl = zContent; + p->zLanguageid = zLanguageid; + zContent = 0; + zLanguageid = 0; + TESTONLY( p->inTransaction = -1 ); + TESTONLY( p->mxSavepoint = -1 ); + + p->aIndex = (struct Fts3Index *)&p->azColumn[nCol]; + memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex); + p->nIndex = nIndex; + for(i=0; iaIndex[i].hPending, FTS3_HASH_STRING, 1); + } + p->abNotindexed = (u8 *)&p->aIndex[nIndex]; + + /* Fill in the zName and zDb fields of the vtab structure. */ + zCsr = (char *)&p->abNotindexed[nCol]; + p->zName = zCsr; + memcpy(zCsr, argv[2], nName); + zCsr += nName; + p->zDb = zCsr; + memcpy(zCsr, argv[1], nDb); + zCsr += nDb; + + /* Fill in the azColumn array */ + for(iCol=0; iColazColumn[iCol] = zCsr; + zCsr += n+1; + assert( zCsr <= &((char *)p)[nByte] ); + } + + /* Fill in the abNotindexed array */ + for(iCol=0; iColazColumn[iCol]); + for(i=0; iazColumn[iCol], zNot, n) ){ + p->abNotindexed[iCol] = 1; + sqlite3_free(zNot); + azNotindexed[i] = 0; + } + } + } + for(i=0; izReadExprlist = fts3ReadExprList(p, zUncompress, &rc); + p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc); + if( rc!=SQLITE_OK ) goto fts3_init_out; + + /* If this is an xCreate call, create the underlying tables in the + ** database. TODO: For xConnect(), it could verify that said tables exist. + */ + if( isCreate ){ + rc = fts3CreateTables(p); + } + + /* Check to see if a legacy fts3 table has been "upgraded" by the + ** addition of a %_stat table so that it can use incremental merge. + */ + if( !isFts4 && !isCreate ){ + int rc2 = SQLITE_OK; + fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2", + p->zDb, p->zName); + if( rc2==SQLITE_OK ) p->bHasStat = 1; + } + + /* Figure out the page-size for the database. This is required in order to + ** estimate the cost of loading large doclists from the database. */ + fts3DatabasePageSize(&rc, p); + p->nNodeSize = p->nPgsz-35; + + /* Declare the table schema to SQLite. */ + fts3DeclareVtab(&rc, p); + +fts3_init_out: + sqlite3_free(zPrefix); + sqlite3_free(aIndex); + sqlite3_free(zCompress); + sqlite3_free(zUncompress); + sqlite3_free(zContent); + sqlite3_free(zLanguageid); + for(i=0; ipModule->xDestroy(pTokenizer); + } + }else{ + assert( p->pSegments==0 ); + *ppVTab = &p->base; + } + return rc; +} + +/* +** The xConnect() and xCreate() methods for the virtual table. All the +** work is done in function fts3InitVtab(). +*/ +static int fts3ConnectMethod( + sqlite3 *db, /* Database connection */ + void *pAux, /* Pointer to tokenizer hash table */ + int argc, /* Number of elements in argv array */ + const char * const *argv, /* xCreate/xConnect argument array */ + sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ + char **pzErr /* OUT: sqlite3_malloc'd error message */ +){ + return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); +} +static int fts3CreateMethod( + sqlite3 *db, /* Database connection */ + void *pAux, /* Pointer to tokenizer hash table */ + int argc, /* Number of elements in argv array */ + const char * const *argv, /* xCreate/xConnect argument array */ + sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ + char **pzErr /* OUT: sqlite3_malloc'd error message */ +){ + return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); +} + +/* +** Implementation of the xBestIndex method for FTS3 tables. There +** are three possible strategies, in order of preference: +** +** 1. Direct lookup by rowid or docid. +** 2. Full-text search using a MATCH operator on a non-docid column. +** 3. Linear scan of %_content table. +*/ +static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ + Fts3Table *p = (Fts3Table *)pVTab; + int i; /* Iterator variable */ + int iCons = -1; /* Index of constraint to use */ + + int iLangidCons = -1; /* Index of langid=x constraint, if present */ + int iDocidGe = -1; /* Index of docid>=x constraint, if present */ + int iDocidLe = -1; /* Index of docid<=x constraint, if present */ + int iIdx; + + /* By default use a full table scan. This is an expensive option, + ** so search through the constraints to see if a more efficient + ** strategy is possible. + */ + pInfo->idxNum = FTS3_FULLSCAN_SEARCH; + pInfo->estimatedCost = 5000000; + for(i=0; inConstraint; i++){ + int bDocid; /* True if this constraint is on docid */ + struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; + if( pCons->usable==0 ) continue; + + bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1); + + /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */ + if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){ + pInfo->idxNum = FTS3_DOCID_SEARCH; + pInfo->estimatedCost = 1.0; + iCons = i; + } + + /* A MATCH constraint. Use a full-text search. + ** + ** If there is more than one MATCH constraint available, use the first + ** one encountered. If there is both a MATCH constraint and a direct + ** rowid/docid lookup, prefer the MATCH strategy. This is done even + ** though the rowid/docid lookup is faster than a MATCH query, selecting + ** it would lead to an "unable to use function MATCH in the requested + ** context" error. + */ + if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH + && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn + ){ + pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn; + pInfo->estimatedCost = 2.0; + iCons = i; + } + + /* Equality constraint on the langid column */ + if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ + && pCons->iColumn==p->nColumn + 2 + ){ + iLangidCons = i; + } + + if( bDocid ){ + switch( pCons->op ){ + case SQLITE_INDEX_CONSTRAINT_GE: + case SQLITE_INDEX_CONSTRAINT_GT: + iDocidGe = i; + break; + + case SQLITE_INDEX_CONSTRAINT_LE: + case SQLITE_INDEX_CONSTRAINT_LT: + iDocidLe = i; + break; + } + } + } + + iIdx = 1; + if( iCons>=0 ){ + pInfo->aConstraintUsage[iCons].argvIndex = iIdx++; + pInfo->aConstraintUsage[iCons].omit = 1; + } + if( iLangidCons>=0 ){ + pInfo->idxNum |= FTS3_HAVE_LANGID; + pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++; + } + if( iDocidGe>=0 ){ + pInfo->idxNum |= FTS3_HAVE_DOCID_GE; + pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++; + } + if( iDocidLe>=0 ){ + pInfo->idxNum |= FTS3_HAVE_DOCID_LE; + pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++; + } + + /* Regardless of the strategy selected, FTS can deliver rows in rowid (or + ** docid) order. Both ascending and descending are possible. + */ + if( pInfo->nOrderBy==1 ){ + struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0]; + if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){ + if( pOrder->desc ){ + pInfo->idxStr = "DESC"; + }else{ + pInfo->idxStr = "ASC"; + } + pInfo->orderByConsumed = 1; + } + } + + assert( p->pSegments==0 ); + return SQLITE_OK; +} + +/* +** Implementation of xOpen method. +*/ +static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ + sqlite3_vtab_cursor *pCsr; /* Allocated cursor */ + + UNUSED_PARAMETER(pVTab); + + /* Allocate a buffer large enough for an Fts3Cursor structure. If the + ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, + ** if the allocation fails, return SQLITE_NOMEM. + */ + *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor)); + if( !pCsr ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(Fts3Cursor)); + return SQLITE_OK; +} + +/* +** Close the cursor. For additional information see the documentation +** on the xClose method of the virtual table interface. +*/ +static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){ + Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; + assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); + sqlite3_finalize(pCsr->pStmt); + sqlite3Fts3ExprFree(pCsr->pExpr); + sqlite3Fts3FreeDeferredTokens(pCsr); + sqlite3_free(pCsr->aDoclist); + sqlite3_free(pCsr->aMatchinfo); + assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then +** compose and prepare an SQL statement of the form: +** +** "SELECT FROM %_content WHERE rowid = ?" +** +** (or the equivalent for a content=xxx table) and set pCsr->pStmt to +** it. If an error occurs, return an SQLite error code. +** +** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK. +*/ +static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){ + int rc = SQLITE_OK; + if( pCsr->pStmt==0 ){ + Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; + char *zSql; + zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist); + if( !zSql ) return SQLITE_NOMEM; + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); + sqlite3_free(zSql); + } + *ppStmt = pCsr->pStmt; + return rc; +} + +/* +** Position the pCsr->pStmt statement so that it is on the row +** of the %_content table that contains the last match. Return +** SQLITE_OK on success. +*/ +static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){ + int rc = SQLITE_OK; + if( pCsr->isRequireSeek ){ + sqlite3_stmt *pStmt = 0; + + rc = fts3CursorSeekStmt(pCsr, &pStmt); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); + pCsr->isRequireSeek = 0; + if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){ + return SQLITE_OK; + }else{ + rc = sqlite3_reset(pCsr->pStmt); + if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){ + /* If no row was found and no error has occurred, then the %_content + ** table is missing a row that is present in the full-text index. + ** The data structures are corrupt. */ + rc = FTS_CORRUPT_VTAB; + pCsr->isEof = 1; + } + } + } + } + + if( rc!=SQLITE_OK && pContext ){ + sqlite3_result_error_code(pContext, rc); + } + return rc; +} + +/* +** This function is used to process a single interior node when searching +** a b-tree for a term or term prefix. The node data is passed to this +** function via the zNode/nNode parameters. The term to search for is +** passed in zTerm/nTerm. +** +** If piFirst is not NULL, then this function sets *piFirst to the blockid +** of the child node that heads the sub-tree that may contain the term. +** +** If piLast is not NULL, then *piLast is set to the right-most child node +** that heads a sub-tree that may contain a term for which zTerm/nTerm is +** a prefix. +** +** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK. +*/ +static int fts3ScanInteriorNode( + const char *zTerm, /* Term to select leaves for */ + int nTerm, /* Size of term zTerm in bytes */ + const char *zNode, /* Buffer containing segment interior node */ + int nNode, /* Size of buffer at zNode */ + sqlite3_int64 *piFirst, /* OUT: Selected child node */ + sqlite3_int64 *piLast /* OUT: Selected child node */ +){ + int rc = SQLITE_OK; /* Return code */ + const char *zCsr = zNode; /* Cursor to iterate through node */ + const char *zEnd = &zCsr[nNode];/* End of interior node buffer */ + char *zBuffer = 0; /* Buffer to load terms into */ + int nAlloc = 0; /* Size of allocated buffer */ + int isFirstTerm = 1; /* True when processing first term on page */ + sqlite3_int64 iChild; /* Block id of child node to descend to */ + + /* Skip over the 'height' varint that occurs at the start of every + ** interior node. Then load the blockid of the left-child of the b-tree + ** node into variable iChild. + ** + ** Even if the data structure on disk is corrupted, this (reading two + ** varints from the buffer) does not risk an overread. If zNode is a + ** root node, then the buffer comes from a SELECT statement. SQLite does + ** not make this guarantee explicitly, but in practice there are always + ** either more than 20 bytes of allocated space following the nNode bytes of + ** contents, or two zero bytes. Or, if the node is read from the %_segments + ** table, then there are always 20 bytes of zeroed padding following the + ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details). + */ + zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); + zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); + if( zCsr>zEnd ){ + return FTS_CORRUPT_VTAB; + } + + while( zCsrzEnd ){ + rc = FTS_CORRUPT_VTAB; + goto finish_scan; + } + if( nPrefix+nSuffix>nAlloc ){ + char *zNew; + nAlloc = (nPrefix+nSuffix) * 2; + zNew = (char *)sqlite3_realloc(zBuffer, nAlloc); + if( !zNew ){ + rc = SQLITE_NOMEM; + goto finish_scan; + } + zBuffer = zNew; + } + assert( zBuffer ); + memcpy(&zBuffer[nPrefix], zCsr, nSuffix); + nBuffer = nPrefix + nSuffix; + zCsr += nSuffix; + + /* Compare the term we are searching for with the term just loaded from + ** the interior node. If the specified term is greater than or equal + ** to the term from the interior node, then all terms on the sub-tree + ** headed by node iChild are smaller than zTerm. No need to search + ** iChild. + ** + ** If the interior node term is larger than the specified term, then + ** the tree headed by iChild may contain the specified term. + */ + cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer)); + if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){ + *piFirst = iChild; + piFirst = 0; + } + + if( piLast && cmp<0 ){ + *piLast = iChild; + piLast = 0; + } + + iChild++; + }; + + if( piFirst ) *piFirst = iChild; + if( piLast ) *piLast = iChild; + + finish_scan: + sqlite3_free(zBuffer); + return rc; +} + + +/* +** The buffer pointed to by argument zNode (size nNode bytes) contains an +** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes) +** contains a term. This function searches the sub-tree headed by the zNode +** node for the range of leaf nodes that may contain the specified term +** or terms for which the specified term is a prefix. +** +** If piLeaf is not NULL, then *piLeaf is set to the blockid of the +** left-most leaf node in the tree that may contain the specified term. +** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the +** right-most leaf node that may contain a term for which the specified +** term is a prefix. +** +** It is possible that the range of returned leaf nodes does not contain +** the specified term or any terms for which it is a prefix. However, if the +** segment does contain any such terms, they are stored within the identified +** range. Because this function only inspects interior segment nodes (and +** never loads leaf nodes into memory), it is not possible to be sure. +** +** If an error occurs, an error code other than SQLITE_OK is returned. +*/ +static int fts3SelectLeaf( + Fts3Table *p, /* Virtual table handle */ + const char *zTerm, /* Term to select leaves for */ + int nTerm, /* Size of term zTerm in bytes */ + const char *zNode, /* Buffer containing segment interior node */ + int nNode, /* Size of buffer at zNode */ + sqlite3_int64 *piLeaf, /* Selected leaf node */ + sqlite3_int64 *piLeaf2 /* Selected leaf node */ +){ + int rc; /* Return code */ + int iHeight; /* Height of this node in tree */ + + assert( piLeaf || piLeaf2 ); + + sqlite3Fts3GetVarint32(zNode, &iHeight); + rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); + assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); + + if( rc==SQLITE_OK && iHeight>1 ){ + char *zBlob = 0; /* Blob read from %_segments table */ + int nBlob; /* Size of zBlob in bytes */ + + if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){ + rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0); + if( rc==SQLITE_OK ){ + rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0); + } + sqlite3_free(zBlob); + piLeaf = 0; + zBlob = 0; + } + + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0); + } + if( rc==SQLITE_OK ){ + rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); + } + sqlite3_free(zBlob); + } + + return rc; +} + +/* +** This function is used to create delta-encoded serialized lists of FTS3 +** varints. Each call to this function appends a single varint to a list. +*/ +static void fts3PutDeltaVarint( + char **pp, /* IN/OUT: Output pointer */ + sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ + sqlite3_int64 iVal /* Write this value to the list */ +){ + assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) ); + *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); + *piPrev = iVal; +} + +/* +** When this function is called, *ppPoslist is assumed to point to the +** start of a position-list. After it returns, *ppPoslist points to the +** first byte after the position-list. +** +** A position list is list of positions (delta encoded) and columns for +** a single document record of a doclist. So, in other words, this +** routine advances *ppPoslist so that it points to the next docid in +** the doclist, or to the first byte past the end of the doclist. +** +** If pp is not NULL, then the contents of the position list are copied +** to *pp. *pp is set to point to the first byte past the last byte copied +** before this function returns. +*/ +static void fts3PoslistCopy(char **pp, char **ppPoslist){ + char *pEnd = *ppPoslist; + char c = 0; + + /* The end of a position list is marked by a zero encoded as an FTS3 + ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by + ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail + ** of some other, multi-byte, value. + ** + ** The following while-loop moves pEnd to point to the first byte that is not + ** immediately preceded by a byte with the 0x80 bit set. Then increments + ** pEnd once more so that it points to the byte immediately following the + ** last byte in the position-list. + */ + while( *pEnd | c ){ + c = *pEnd++ & 0x80; + testcase( c!=0 && (*pEnd)==0 ); + } + pEnd++; /* Advance past the POS_END terminator byte */ + + if( pp ){ + int n = (int)(pEnd - *ppPoslist); + char *p = *pp; + memcpy(p, *ppPoslist, n); + p += n; + *pp = p; + } + *ppPoslist = pEnd; +} + +/* +** When this function is called, *ppPoslist is assumed to point to the +** start of a column-list. After it returns, *ppPoslist points to the +** to the terminator (POS_COLUMN or POS_END) byte of the column-list. +** +** A column-list is list of delta-encoded positions for a single column +** within a single document within a doclist. +** +** The column-list is terminated either by a POS_COLUMN varint (1) or +** a POS_END varint (0). This routine leaves *ppPoslist pointing to +** the POS_COLUMN or POS_END that terminates the column-list. +** +** If pp is not NULL, then the contents of the column-list are copied +** to *pp. *pp is set to point to the first byte past the last byte copied +** before this function returns. The POS_COLUMN or POS_END terminator +** is not copied into *pp. +*/ +static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ + char *pEnd = *ppPoslist; + char c = 0; + + /* A column-list is terminated by either a 0x01 or 0x00 byte that is + ** not part of a multi-byte varint. + */ + while( 0xFE & (*pEnd | c) ){ + c = *pEnd++ & 0x80; + testcase( c!=0 && ((*pEnd)&0xfe)==0 ); + } + if( pp ){ + int n = (int)(pEnd - *ppPoslist); + char *p = *pp; + memcpy(p, *ppPoslist, n); + p += n; + *pp = p; + } + *ppPoslist = pEnd; +} + +/* +** Value used to signify the end of an position-list. This is safe because +** it is not possible to have a document with 2^31 terms. +*/ +#define POSITION_LIST_END 0x7fffffff + +/* +** This function is used to help parse position-lists. When this function is +** called, *pp may point to the start of the next varint in the position-list +** being parsed, or it may point to 1 byte past the end of the position-list +** (in which case **pp will be a terminator bytes POS_END (0) or +** (1)). +** +** If *pp points past the end of the current position-list, set *pi to +** POSITION_LIST_END and return. Otherwise, read the next varint from *pp, +** increment the current value of *pi by the value read, and set *pp to +** point to the next value before returning. +** +** Before calling this routine *pi must be initialized to the value of +** the previous position, or zero if we are reading the first position +** in the position-list. Because positions are delta-encoded, the value +** of the previous position is needed in order to compute the value of +** the next position. +*/ +static void fts3ReadNextPos( + char **pp, /* IN/OUT: Pointer into position-list buffer */ + sqlite3_int64 *pi /* IN/OUT: Value read from position-list */ +){ + if( (**pp)&0xFE ){ + fts3GetDeltaVarint(pp, pi); + *pi -= 2; + }else{ + *pi = POSITION_LIST_END; + } +} + +/* +** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by +** the value of iCol encoded as a varint to *pp. This will start a new +** column list. +** +** Set *pp to point to the byte just after the last byte written before +** returning (do not modify it if iCol==0). Return the total number of bytes +** written (0 if iCol==0). +*/ +static int fts3PutColNumber(char **pp, int iCol){ + int n = 0; /* Number of bytes written */ + if( iCol ){ + char *p = *pp; /* Output pointer */ + n = 1 + sqlite3Fts3PutVarint(&p[1], iCol); + *p = 0x01; + *pp = &p[n]; + } + return n; +} + +/* +** Compute the union of two position lists. The output written +** into *pp contains all positions of both *pp1 and *pp2 in sorted +** order and with any duplicates removed. All pointers are +** updated appropriately. The caller is responsible for insuring +** that there is enough space in *pp to hold the complete output. +*/ +static void fts3PoslistMerge( + char **pp, /* Output buffer */ + char **pp1, /* Left input list */ + char **pp2 /* Right input list */ +){ + char *p = *pp; + char *p1 = *pp1; + char *p2 = *pp2; + + while( *p1 || *p2 ){ + int iCol1; /* The current column index in pp1 */ + int iCol2; /* The current column index in pp2 */ + + if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1); + else if( *p1==POS_END ) iCol1 = POSITION_LIST_END; + else iCol1 = 0; + + if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2); + else if( *p2==POS_END ) iCol2 = POSITION_LIST_END; + else iCol2 = 0; + + if( iCol1==iCol2 ){ + sqlite3_int64 i1 = 0; /* Last position from pp1 */ + sqlite3_int64 i2 = 0; /* Last position from pp2 */ + sqlite3_int64 iPrev = 0; + int n = fts3PutColNumber(&p, iCol1); + p1 += n; + p2 += n; + + /* At this point, both p1 and p2 point to the start of column-lists + ** for the same column (the column with index iCol1 and iCol2). + ** A column-list is a list of non-negative delta-encoded varints, each + ** incremented by 2 before being stored. Each list is terminated by a + ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists + ** and writes the results to buffer p. p is left pointing to the byte + ** after the list written. No terminator (POS_END or POS_COLUMN) is + ** written to the output. + */ + fts3GetDeltaVarint(&p1, &i1); + fts3GetDeltaVarint(&p2, &i2); + do { + fts3PutDeltaVarint(&p, &iPrev, (i1pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e. +** when the *pp1 token appears before the *pp2 token, but not more than nToken +** slots before it. +** +** e.g. nToken==1 searches for adjacent positions. +*/ +static int fts3PoslistPhraseMerge( + char **pp, /* IN/OUT: Preallocated output buffer */ + int nToken, /* Maximum difference in token positions */ + int isSaveLeft, /* Save the left position */ + int isExact, /* If *pp1 is exactly nTokens before *pp2 */ + char **pp1, /* IN/OUT: Left input list */ + char **pp2 /* IN/OUT: Right input list */ +){ + char *p = *pp; + char *p1 = *pp1; + char *p2 = *pp2; + int iCol1 = 0; + int iCol2 = 0; + + /* Never set both isSaveLeft and isExact for the same invocation. */ + assert( isSaveLeft==0 || isExact==0 ); + + assert( p!=0 && *p1!=0 && *p2!=0 ); + if( *p1==POS_COLUMN ){ + p1++; + p1 += sqlite3Fts3GetVarint32(p1, &iCol1); + } + if( *p2==POS_COLUMN ){ + p2++; + p2 += sqlite3Fts3GetVarint32(p2, &iCol2); + } + + while( 1 ){ + if( iCol1==iCol2 ){ + char *pSave = p; + sqlite3_int64 iPrev = 0; + sqlite3_int64 iPos1 = 0; + sqlite3_int64 iPos2 = 0; + + if( iCol1 ){ + *p++ = POS_COLUMN; + p += sqlite3Fts3PutVarint(p, iCol1); + } + + assert( *p1!=POS_END && *p1!=POS_COLUMN ); + assert( *p2!=POS_END && *p2!=POS_COLUMN ); + fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; + fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; + + while( 1 ){ + if( iPos2==iPos1+nToken + || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) + ){ + sqlite3_int64 iSave; + iSave = isSaveLeft ? iPos1 : iPos2; + fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2; + pSave = 0; + assert( p ); + } + if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){ + if( (*p2&0xFE)==0 ) break; + fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; + }else{ + if( (*p1&0xFE)==0 ) break; + fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; + } + } + + if( pSave ){ + assert( pp && p ); + p = pSave; + } + + fts3ColumnlistCopy(0, &p1); + fts3ColumnlistCopy(0, &p2); + assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 ); + if( 0==*p1 || 0==*p2 ) break; + + p1++; + p1 += sqlite3Fts3GetVarint32(p1, &iCol1); + p2++; + p2 += sqlite3Fts3GetVarint32(p2, &iCol2); + } + + /* Advance pointer p1 or p2 (whichever corresponds to the smaller of + ** iCol1 and iCol2) so that it points to either the 0x00 that marks the + ** end of the position list, or the 0x01 that precedes the next + ** column-number in the position list. + */ + else if( iCol1=pEnd ){ + *pp = 0; + }else{ + sqlite3_int64 iVal; + *pp += sqlite3Fts3GetVarint(*pp, &iVal); + if( bDescIdx ){ + *pVal -= iVal; + }else{ + *pVal += iVal; + } + } +} + +/* +** This function is used to write a single varint to a buffer. The varint +** is written to *pp. Before returning, *pp is set to point 1 byte past the +** end of the value written. +** +** If *pbFirst is zero when this function is called, the value written to +** the buffer is that of parameter iVal. +** +** If *pbFirst is non-zero when this function is called, then the value +** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal) +** (if bDescIdx is non-zero). +** +** Before returning, this function always sets *pbFirst to 1 and *piPrev +** to the value of parameter iVal. +*/ +static void fts3PutDeltaVarint3( + char **pp, /* IN/OUT: Output pointer */ + int bDescIdx, /* True for descending docids */ + sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ + int *pbFirst, /* IN/OUT: True after first int written */ + sqlite3_int64 iVal /* Write this value to the list */ +){ + sqlite3_int64 iWrite; + if( bDescIdx==0 || *pbFirst==0 ){ + iWrite = iVal - *piPrev; + }else{ + iWrite = *piPrev - iVal; + } + assert( *pbFirst || *piPrev==0 ); + assert( *pbFirst==0 || iWrite>0 ); + *pp += sqlite3Fts3PutVarint(*pp, iWrite); + *piPrev = iVal; + *pbFirst = 1; +} + + +/* +** This macro is used by various functions that merge doclists. The two +** arguments are 64-bit docid values. If the value of the stack variable +** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). +** Otherwise, (i2-i1). +** +** Using this makes it easier to write code that can merge doclists that are +** sorted in either ascending or descending order. +*/ +#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2)) + +/* +** This function does an "OR" merge of two doclists (output contains all +** positions contained in either argument doclist). If the docids in the +** input doclists are sorted in ascending order, parameter bDescDoclist +** should be false. If they are sorted in ascending order, it should be +** passed a non-zero value. +** +** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer +** containing the output doclist and SQLITE_OK is returned. In this case +** *pnOut is set to the number of bytes in the output doclist. +** +** If an error occurs, an SQLite error code is returned. The output values +** are undefined in this case. +*/ +static int fts3DoclistOrMerge( + int bDescDoclist, /* True if arguments are desc */ + char *a1, int n1, /* First doclist */ + char *a2, int n2, /* Second doclist */ + char **paOut, int *pnOut /* OUT: Malloc'd doclist */ +){ + sqlite3_int64 i1 = 0; + sqlite3_int64 i2 = 0; + sqlite3_int64 iPrev = 0; + char *pEnd1 = &a1[n1]; + char *pEnd2 = &a2[n2]; + char *p1 = a1; + char *p2 = a2; + char *p; + char *aOut; + int bFirstOut = 0; + + *paOut = 0; + *pnOut = 0; + + /* Allocate space for the output. Both the input and output doclists + ** are delta encoded. If they are in ascending order (bDescDoclist==0), + ** then the first docid in each list is simply encoded as a varint. For + ** each subsequent docid, the varint stored is the difference between the + ** current and previous docid (a positive number - since the list is in + ** ascending order). + ** + ** The first docid written to the output is therefore encoded using the + ** same number of bytes as it is in whichever of the input lists it is + ** read from. And each subsequent docid read from the same input list + ** consumes either the same or less bytes as it did in the input (since + ** the difference between it and the previous value in the output must + ** be a positive value less than or equal to the delta value read from + ** the input list). The same argument applies to all but the first docid + ** read from the 'other' list. And to the contents of all position lists + ** that will be copied and merged from the input to the output. + ** + ** However, if the first docid copied to the output is a negative number, + ** then the encoding of the first docid from the 'other' input list may + ** be larger in the output than it was in the input (since the delta value + ** may be a larger positive integer than the actual docid). + ** + ** The space required to store the output is therefore the sum of the + ** sizes of the two inputs, plus enough space for exactly one of the input + ** docids to grow. + ** + ** A symetric argument may be made if the doclists are in descending + ** order. + */ + aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1); + if( !aOut ) return SQLITE_NOMEM; + + p = aOut; + fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); + fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); + while( p1 || p2 ){ + sqlite3_int64 iDiff = DOCID_CMP(i1, i2); + + if( p2 && p1 && iDiff==0 ){ + fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); + fts3PoslistMerge(&p, &p1, &p2); + fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); + fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); + }else if( !p2 || (p1 && iDiff<0) ){ + fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); + fts3PoslistCopy(&p, &p1); + fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); + }else{ + fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2); + fts3PoslistCopy(&p, &p2); + fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); + } + } + + *paOut = aOut; + *pnOut = (int)(p-aOut); + assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 ); + return SQLITE_OK; +} + +/* +** This function does a "phrase" merge of two doclists. In a phrase merge, +** the output contains a copy of each position from the right-hand input +** doclist for which there is a position in the left-hand input doclist +** exactly nDist tokens before it. +** +** If the docids in the input doclists are sorted in ascending order, +** parameter bDescDoclist should be false. If they are sorted in ascending +** order, it should be passed a non-zero value. +** +** The right-hand input doclist is overwritten by this function. +*/ +static void fts3DoclistPhraseMerge( + int bDescDoclist, /* True if arguments are desc */ + int nDist, /* Distance from left to right (1=adjacent) */ + char *aLeft, int nLeft, /* Left doclist */ + char *aRight, int *pnRight /* IN/OUT: Right/output doclist */ +){ + sqlite3_int64 i1 = 0; + sqlite3_int64 i2 = 0; + sqlite3_int64 iPrev = 0; + char *pEnd1 = &aLeft[nLeft]; + char *pEnd2 = &aRight[*pnRight]; + char *p1 = aLeft; + char *p2 = aRight; + char *p; + int bFirstOut = 0; + char *aOut = aRight; + + assert( nDist>0 ); + + p = aOut; + fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); + fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); + + while( p1 && p2 ){ + sqlite3_int64 iDiff = DOCID_CMP(i1, i2); + if( iDiff==0 ){ + char *pSave = p; + sqlite3_int64 iPrevSave = iPrev; + int bFirstOutSave = bFirstOut; + + fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); + if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){ + p = pSave; + iPrev = iPrevSave; + bFirstOut = bFirstOutSave; + } + fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); + fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); + }else if( iDiff<0 ){ + fts3PoslistCopy(0, &p1); + fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); + }else{ + fts3PoslistCopy(0, &p2); + fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); + } + } + + *pnRight = (int)(p - aOut); +} + +/* +** Argument pList points to a position list nList bytes in size. This +** function checks to see if the position list contains any entries for +** a token in position 0 (of any column). If so, it writes argument iDelta +** to the output buffer pOut, followed by a position list consisting only +** of the entries from pList at position 0, and terminated by an 0x00 byte. +** The value returned is the number of bytes written to pOut (if any). +*/ +int sqlite3Fts3FirstFilter( + sqlite3_int64 iDelta, /* Varint that may be written to pOut */ + char *pList, /* Position list (no 0x00 term) */ + int nList, /* Size of pList in bytes */ + char *pOut /* Write output here */ +){ + int nOut = 0; + int bWritten = 0; /* True once iDelta has been written */ + char *p = pList; + char *pEnd = &pList[nList]; + + if( *p!=0x01 ){ + if( *p==0x02 ){ + nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta); + pOut[nOut++] = 0x02; + bWritten = 1; + } + fts3ColumnlistCopy(0, &p); + } + + while( paaOutput); i++){ + if( pTS->aaOutput[i] ){ + if( !aOut ){ + aOut = pTS->aaOutput[i]; + nOut = pTS->anOutput[i]; + pTS->aaOutput[i] = 0; + }else{ + int nNew; + char *aNew; + + int rc = fts3DoclistOrMerge(p->bDescIdx, + pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew + ); + if( rc!=SQLITE_OK ){ + sqlite3_free(aOut); + return rc; + } + + sqlite3_free(pTS->aaOutput[i]); + sqlite3_free(aOut); + pTS->aaOutput[i] = 0; + aOut = aNew; + nOut = nNew; + } + } + } + + pTS->aaOutput[0] = aOut; + pTS->anOutput[0] = nOut; + return SQLITE_OK; +} + +/* +** Merge the doclist aDoclist/nDoclist into the TermSelect object passed +** as the first argument. The merge is an "OR" merge (see function +** fts3DoclistOrMerge() for details). +** +** This function is called with the doclist for each term that matches +** a queried prefix. It merges all these doclists into one, the doclist +** for the specified prefix. Since there can be a very large number of +** doclists to merge, the merging is done pair-wise using the TermSelect +** object. +** +** This function returns SQLITE_OK if the merge is successful, or an +** SQLite error code (SQLITE_NOMEM) if an error occurs. +*/ +static int fts3TermSelectMerge( + Fts3Table *p, /* FTS table handle */ + TermSelect *pTS, /* TermSelect object to merge into */ + char *aDoclist, /* Pointer to doclist */ + int nDoclist /* Size of aDoclist in bytes */ +){ + if( pTS->aaOutput[0]==0 ){ + /* If this is the first term selected, copy the doclist to the output + ** buffer using memcpy(). */ + pTS->aaOutput[0] = sqlite3_malloc(nDoclist); + pTS->anOutput[0] = nDoclist; + if( pTS->aaOutput[0] ){ + memcpy(pTS->aaOutput[0], aDoclist, nDoclist); + }else{ + return SQLITE_NOMEM; + } + }else{ + char *aMerge = aDoclist; + int nMerge = nDoclist; + int iOut; + + for(iOut=0; iOutaaOutput); iOut++){ + if( pTS->aaOutput[iOut]==0 ){ + assert( iOut>0 ); + pTS->aaOutput[iOut] = aMerge; + pTS->anOutput[iOut] = nMerge; + break; + }else{ + char *aNew; + int nNew; + + int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, + pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew + ); + if( rc!=SQLITE_OK ){ + if( aMerge!=aDoclist ) sqlite3_free(aMerge); + return rc; + } + + if( aMerge!=aDoclist ) sqlite3_free(aMerge); + sqlite3_free(pTS->aaOutput[iOut]); + pTS->aaOutput[iOut] = 0; + + aMerge = aNew; + nMerge = nNew; + if( (iOut+1)==SizeofArray(pTS->aaOutput) ){ + pTS->aaOutput[iOut] = aMerge; + pTS->anOutput[iOut] = nMerge; + } + } + } + } + return SQLITE_OK; +} + +/* +** Append SegReader object pNew to the end of the pCsr->apSegment[] array. +*/ +static int fts3SegReaderCursorAppend( + Fts3MultiSegReader *pCsr, + Fts3SegReader *pNew +){ + if( (pCsr->nSegment%16)==0 ){ + Fts3SegReader **apNew; + int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); + apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte); + if( !apNew ){ + sqlite3Fts3SegReaderFree(pNew); + return SQLITE_NOMEM; + } + pCsr->apSegment = apNew; + } + pCsr->apSegment[pCsr->nSegment++] = pNew; + return SQLITE_OK; +} + +/* +** Add seg-reader objects to the Fts3MultiSegReader object passed as the +** 8th argument. +** +** This function returns SQLITE_OK if successful, or an SQLite error code +** otherwise. +*/ +static int fts3SegReaderCursor( + Fts3Table *p, /* FTS3 table handle */ + int iLangid, /* Language id */ + int iIndex, /* Index to search (from 0 to p->nIndex-1) */ + int iLevel, /* Level of segments to scan */ + const char *zTerm, /* Term to query for */ + int nTerm, /* Size of zTerm in bytes */ + int isPrefix, /* True for a prefix search */ + int isScan, /* True to scan from zTerm to EOF */ + Fts3MultiSegReader *pCsr /* Cursor object to populate */ +){ + int rc = SQLITE_OK; /* Error code */ + sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */ + int rc2; /* Result of sqlite3_reset() */ + + /* If iLevel is less than 0 and this is not a scan, include a seg-reader + ** for the pending-terms. If this is a scan, then this call must be being + ** made by an fts4aux module, not an FTS table. In this case calling + ** Fts3SegReaderPending might segfault, as the data structures used by + ** fts4aux are not completely populated. So it's easiest to filter these + ** calls out here. */ + if( iLevel<0 && p->aIndex ){ + Fts3SegReader *pSeg = 0; + rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg); + if( rc==SQLITE_OK && pSeg ){ + rc = fts3SegReaderCursorAppend(pCsr, pSeg); + } + } + + if( iLevel!=FTS3_SEGCURSOR_PENDING ){ + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt); + } + + while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ + Fts3SegReader *pSeg = 0; + + /* Read the values returned by the SELECT into local variables. */ + sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1); + sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2); + sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3); + int nRoot = sqlite3_column_bytes(pStmt, 4); + char const *zRoot = sqlite3_column_blob(pStmt, 4); + + /* If zTerm is not NULL, and this segment is not stored entirely on its + ** root node, the range of leaves scanned can be reduced. Do this. */ + if( iStartBlock && zTerm ){ + sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0); + rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi); + if( rc!=SQLITE_OK ) goto finished; + if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock; + } + + rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, + (isPrefix==0 && isScan==0), + iStartBlock, iLeavesEndBlock, + iEndBlock, zRoot, nRoot, &pSeg + ); + if( rc!=SQLITE_OK ) goto finished; + rc = fts3SegReaderCursorAppend(pCsr, pSeg); + } + } + + finished: + rc2 = sqlite3_reset(pStmt); + if( rc==SQLITE_DONE ) rc = rc2; + + return rc; +} + +/* +** Set up a cursor object for iterating through a full-text index or a +** single level therein. +*/ +int sqlite3Fts3SegReaderCursor( + Fts3Table *p, /* FTS3 table handle */ + int iLangid, /* Language-id to search */ + int iIndex, /* Index to search (from 0 to p->nIndex-1) */ + int iLevel, /* Level of segments to scan */ + const char *zTerm, /* Term to query for */ + int nTerm, /* Size of zTerm in bytes */ + int isPrefix, /* True for a prefix search */ + int isScan, /* True to scan from zTerm to EOF */ + Fts3MultiSegReader *pCsr /* Cursor object to populate */ +){ + assert( iIndex>=0 && iIndexnIndex ); + assert( iLevel==FTS3_SEGCURSOR_ALL + || iLevel==FTS3_SEGCURSOR_PENDING + || iLevel>=0 + ); + assert( iLevelbase.pVtab; + + if( isPrefix ){ + for(i=1; bFound==0 && inIndex; i++){ + if( p->aIndex[i].nPrefix==nTerm ){ + bFound = 1; + rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, + i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr + ); + pSegcsr->bLookup = 1; + } + } + + for(i=1; bFound==0 && inIndex; i++){ + if( p->aIndex[i].nPrefix==nTerm+1 ){ + bFound = 1; + rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, + i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr + ); + if( rc==SQLITE_OK ){ + rc = fts3SegReaderCursorAddZero( + p, pCsr->iLangid, zTerm, nTerm, pSegcsr + ); + } + } + } + } + + if( bFound==0 ){ + rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, + 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr + ); + pSegcsr->bLookup = !isPrefix; + } + } + + *ppSegcsr = pSegcsr; + return rc; +} + +/* +** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor(). +*/ +static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){ + sqlite3Fts3SegReaderFinish(pSegcsr); + sqlite3_free(pSegcsr); +} + +/* +** This function retrieves the doclist for the specified term (or term +** prefix) from the database. +*/ +static int fts3TermSelect( + Fts3Table *p, /* Virtual table handle */ + Fts3PhraseToken *pTok, /* Token to query for */ + int iColumn, /* Column to query (or -ve for all columns) */ + int *pnOut, /* OUT: Size of buffer at *ppOut */ + char **ppOut /* OUT: Malloced result buffer */ +){ + int rc; /* Return code */ + Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */ + TermSelect tsc; /* Object for pair-wise doclist merging */ + Fts3SegFilter filter; /* Segment term filter configuration */ + + pSegcsr = pTok->pSegcsr; + memset(&tsc, 0, sizeof(TermSelect)); + + filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS + | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0) + | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0) + | (iColumnnColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0); + filter.iCol = iColumn; + filter.zTerm = pTok->z; + filter.nTerm = pTok->n; + + rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter); + while( SQLITE_OK==rc + && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) + ){ + rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist); + } + + if( rc==SQLITE_OK ){ + rc = fts3TermSelectFinishMerge(p, &tsc); + } + if( rc==SQLITE_OK ){ + *ppOut = tsc.aaOutput[0]; + *pnOut = tsc.anOutput[0]; + }else{ + int i; + for(i=0; ipSegcsr = 0; + return rc; +} + +/* +** This function counts the total number of docids in the doclist stored +** in buffer aList[], size nList bytes. +** +** If the isPoslist argument is true, then it is assumed that the doclist +** contains a position-list following each docid. Otherwise, it is assumed +** that the doclist is simply a list of docids stored as delta encoded +** varints. +*/ +static int fts3DoclistCountDocids(char *aList, int nList){ + int nDoc = 0; /* Return value */ + if( aList ){ + char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */ + char *p = aList; /* Cursor */ + while( peSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){ + if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){ + pCsr->isEof = 1; + rc = sqlite3_reset(pCsr->pStmt); + }else{ + pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0); + rc = SQLITE_OK; + } + }else{ + rc = fts3EvalNext((Fts3Cursor *)pCursor); + } + assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); + return rc; +} + +/* +** The following are copied from sqliteInt.h. +** +** Constants for the largest and smallest possible 64-bit signed integers. +** These macros are designed to work correctly on both 32-bit and 64-bit +** compilers. +*/ +#ifndef SQLITE_AMALGAMATION +# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) +# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) +#endif + +/* +** If the numeric type of argument pVal is "integer", then return it +** converted to a 64-bit signed integer. Otherwise, return a copy of +** the second parameter, iDefault. +*/ +static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){ + if( pVal ){ + int eType = sqlite3_value_numeric_type(pVal); + if( eType==SQLITE_INTEGER ){ + return sqlite3_value_int64(pVal); + } + } + return iDefault; +} + +/* +** This is the xFilter interface for the virtual table. See +** the virtual table xFilter method documentation for additional +** information. +** +** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against +** the %_content table. +** +** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry +** in the %_content table. +** +** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The +** column on the left-hand side of the MATCH operator is column +** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand +** side of the MATCH operator. +*/ +static int fts3FilterMethod( + sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + int idxNum, /* Strategy index */ + const char *idxStr, /* Unused */ + int nVal, /* Number of elements in apVal */ + sqlite3_value **apVal /* Arguments for the indexing scheme */ +){ + int rc; + char *zSql; /* SQL statement used to access %_content */ + int eSearch; + Fts3Table *p = (Fts3Table *)pCursor->pVtab; + Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; + + sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */ + sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */ + sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */ + sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */ + int iIdx; + + UNUSED_PARAMETER(idxStr); + UNUSED_PARAMETER(nVal); + + eSearch = (idxNum & 0x0000FFFF); + assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) ); + assert( p->pSegments==0 ); + + /* Collect arguments into local variables */ + iIdx = 0; + if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++]; + if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++]; + if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++]; + if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++]; + assert( iIdx==nVal ); + + /* In case the cursor has been used before, clear it now. */ + sqlite3_finalize(pCsr->pStmt); + sqlite3_free(pCsr->aDoclist); + sqlite3Fts3ExprFree(pCsr->pExpr); + memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor)); + + /* Set the lower and upper bounds on docids to return */ + pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64); + pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64); + + if( idxStr ){ + pCsr->bDesc = (idxStr[0]=='D'); + }else{ + pCsr->bDesc = p->bDescIdx; + } + pCsr->eSearch = (i16)eSearch; + + if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){ + int iCol = eSearch-FTS3_FULLTEXT_SEARCH; + const char *zQuery = (const char *)sqlite3_value_text(pCons); + + if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){ + return SQLITE_NOMEM; + } + + pCsr->iLangid = 0; + if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid); + + assert( p->base.zErrMsg==0 ); + rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid, + p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, + &p->base.zErrMsg + ); + if( rc!=SQLITE_OK ){ + return rc; + } + + rc = fts3EvalStart(pCsr); + sqlite3Fts3SegmentsClose(p); + if( rc!=SQLITE_OK ) return rc; + pCsr->pNextId = pCsr->aDoclist; + pCsr->iPrevId = 0; + } + + /* Compile a SELECT statement for this cursor. For a full-table-scan, the + ** statement loops through all rows of the %_content table. For a + ** full-text query or docid lookup, the statement retrieves a single + ** row by docid. + */ + if( eSearch==FTS3_FULLSCAN_SEARCH ){ + zSql = sqlite3_mprintf( + "SELECT %s ORDER BY rowid %s", + p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC") + ); + if( zSql ){ + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); + sqlite3_free(zSql); + }else{ + rc = SQLITE_NOMEM; + } + }else if( eSearch==FTS3_DOCID_SEARCH ){ + rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt); + if( rc==SQLITE_OK ){ + rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons); + } + } + if( rc!=SQLITE_OK ) return rc; + + return fts3NextMethod(pCursor); +} + +/* +** This is the xEof method of the virtual table. SQLite calls this +** routine to find out if it has reached the end of a result set. +*/ +static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){ + return ((Fts3Cursor *)pCursor)->isEof; +} + +/* +** This is the xRowid method. The SQLite core calls this routine to +** retrieve the rowid for the current row of the result set. fts3 +** exposes %_content.docid as the rowid for the virtual table. The +** rowid should be written to *pRowid. +*/ +static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; + *pRowid = pCsr->iPrevId; + return SQLITE_OK; +} + +/* +** This is the xColumn method, called by SQLite to request a value from +** the row that the supplied cursor currently points to. +** +** If: +** +** (iCol < p->nColumn) -> The value of the iCol'th user column. +** (iCol == p->nColumn) -> Magic column with the same name as the table. +** (iCol == p->nColumn+1) -> Docid column +** (iCol == p->nColumn+2) -> Langid column +*/ +static int fts3ColumnMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + int iCol /* Index of column to read value from */ +){ + int rc = SQLITE_OK; /* Return Code */ + Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; + Fts3Table *p = (Fts3Table *)pCursor->pVtab; + + /* The column value supplied by SQLite must be in range. */ + assert( iCol>=0 && iCol<=p->nColumn+2 ); + + if( iCol==p->nColumn+1 ){ + /* This call is a request for the "docid" column. Since "docid" is an + ** alias for "rowid", use the xRowid() method to obtain the value. + */ + sqlite3_result_int64(pCtx, pCsr->iPrevId); + }else if( iCol==p->nColumn ){ + /* The extra column whose name is the same as the table. + ** Return a blob which is a pointer to the cursor. */ + sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT); + }else if( iCol==p->nColumn+2 && pCsr->pExpr ){ + sqlite3_result_int64(pCtx, pCsr->iLangid); + }else{ + /* The requested column is either a user column (one that contains + ** indexed data), or the language-id column. */ + rc = fts3CursorSeek(0, pCsr); + + if( rc==SQLITE_OK ){ + if( iCol==p->nColumn+2 ){ + int iLangid = 0; + if( p->zLanguageid ){ + iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1); + } + sqlite3_result_int(pCtx, iLangid); + }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){ + sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1)); + } + } + } + + assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); + return rc; +} + +/* +** This function is the implementation of the xUpdate callback used by +** FTS3 virtual tables. It is invoked by SQLite each time a row is to be +** inserted, updated or deleted. +*/ +static int fts3UpdateMethod( + sqlite3_vtab *pVtab, /* Virtual table handle */ + int nArg, /* Size of argument array */ + sqlite3_value **apVal, /* Array of arguments */ + sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ +){ + return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid); +} + +/* +** Implementation of xSync() method. Flush the contents of the pending-terms +** hash-table to the database. +*/ +static int fts3SyncMethod(sqlite3_vtab *pVtab){ + + /* Following an incremental-merge operation, assuming that the input + ** segments are not completely consumed (the usual case), they are updated + ** in place to remove the entries that have already been merged. This + ** involves updating the leaf block that contains the smallest unmerged + ** entry and each block (if any) between the leaf and the root node. So + ** if the height of the input segment b-trees is N, and input segments + ** are merged eight at a time, updating the input segments at the end + ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually + ** small - often between 0 and 2. So the overhead of the incremental + ** merge is somewhere between 8 and 24 blocks. To avoid this overhead + ** dwarfing the actual productive work accomplished, the incremental merge + ** is only attempted if it will write at least 64 leaf blocks. Hence + ** nMinMerge. + ** + ** Of course, updating the input segments also involves deleting a bunch + ** of blocks from the segments table. But this is not considered overhead + ** as it would also be required by a crisis-merge that used the same input + ** segments. + */ + const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */ + + Fts3Table *p = (Fts3Table*)pVtab; + int rc = sqlite3Fts3PendingTermsFlush(p); + + if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){ + int mxLevel = 0; /* Maximum relative level value in db */ + int A; /* Incr-merge parameter A */ + + rc = sqlite3Fts3MaxLevel(p, &mxLevel); + assert( rc==SQLITE_OK || mxLevel==0 ); + A = p->nLeafAdd * mxLevel; + A += (A/2); + if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8); + } + sqlite3Fts3SegmentsClose(p); + return rc; +} + +/* +** Implementation of xBegin() method. This is a no-op. +*/ +static int fts3BeginMethod(sqlite3_vtab *pVtab){ + Fts3Table *p = (Fts3Table*)pVtab; + UNUSED_PARAMETER(pVtab); + assert( p->pSegments==0 ); + assert( p->nPendingData==0 ); + assert( p->inTransaction!=1 ); + TESTONLY( p->inTransaction = 1 ); + TESTONLY( p->mxSavepoint = -1; ); + p->nLeafAdd = 0; + return SQLITE_OK; +} + +/* +** Implementation of xCommit() method. This is a no-op. The contents of +** the pending-terms hash-table have already been flushed into the database +** by fts3SyncMethod(). +*/ +static int fts3CommitMethod(sqlite3_vtab *pVtab){ + TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); + UNUSED_PARAMETER(pVtab); + assert( p->nPendingData==0 ); + assert( p->inTransaction!=0 ); + assert( p->pSegments==0 ); + TESTONLY( p->inTransaction = 0 ); + TESTONLY( p->mxSavepoint = -1; ); + return SQLITE_OK; +} + +/* +** Implementation of xRollback(). Discard the contents of the pending-terms +** hash-table. Any changes made to the database are reverted by SQLite. +*/ +static int fts3RollbackMethod(sqlite3_vtab *pVtab){ + Fts3Table *p = (Fts3Table*)pVtab; + sqlite3Fts3PendingTermsClear(p); + assert( p->inTransaction!=0 ); + TESTONLY( p->inTransaction = 0 ); + TESTONLY( p->mxSavepoint = -1; ); + return SQLITE_OK; +} + +/* +** When called, *ppPoslist must point to the byte immediately following the +** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function +** moves *ppPoslist so that it instead points to the first byte of the +** same position list. +*/ +static void fts3ReversePoslist(char *pStart, char **ppPoslist){ + char *p = &(*ppPoslist)[-2]; + char c = 0; + + while( p>pStart && (c=*p--)==0 ); + while( p>pStart && (*p & 0x80) | c ){ + c = *p--; + } + if( p>pStart ){ p = &p[2]; } + while( *p++&0x80 ); + *ppPoslist = p; +} + +/* +** Helper function used by the implementation of the overloaded snippet(), +** offsets() and optimize() SQL functions. +** +** If the value passed as the third argument is a blob of size +** sizeof(Fts3Cursor*), then the blob contents are copied to the +** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error +** message is written to context pContext and SQLITE_ERROR returned. The +** string passed via zFunc is used as part of the error message. +*/ +static int fts3FunctionArg( + sqlite3_context *pContext, /* SQL function call context */ + const char *zFunc, /* Function name */ + sqlite3_value *pVal, /* argv[0] passed to function */ + Fts3Cursor **ppCsr /* OUT: Store cursor handle here */ +){ + Fts3Cursor *pRet; + if( sqlite3_value_type(pVal)!=SQLITE_BLOB + || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *) + ){ + char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc); + sqlite3_result_error(pContext, zErr, -1); + sqlite3_free(zErr); + return SQLITE_ERROR; + } + memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *)); + *ppCsr = pRet; + return SQLITE_OK; +} + +/* +** Implementation of the snippet() function for FTS3 +*/ +static void fts3SnippetFunc( + sqlite3_context *pContext, /* SQLite function call context */ + int nVal, /* Size of apVal[] array */ + sqlite3_value **apVal /* Array of arguments */ +){ + Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ + const char *zStart = ""; + const char *zEnd = ""; + const char *zEllipsis = "..."; + int iCol = -1; + int nToken = 15; /* Default number of tokens in snippet */ + + /* There must be at least one argument passed to this function (otherwise + ** the non-overloaded version would have been called instead of this one). + */ + assert( nVal>=1 ); + + if( nVal>6 ){ + sqlite3_result_error(pContext, + "wrong number of arguments to function snippet()", -1); + return; + } + if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return; + + switch( nVal ){ + case 6: nToken = sqlite3_value_int(apVal[5]); + case 5: iCol = sqlite3_value_int(apVal[4]); + case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); + case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]); + case 2: zStart = (const char*)sqlite3_value_text(apVal[1]); + } + if( !zEllipsis || !zEnd || !zStart ){ + sqlite3_result_error_nomem(pContext); + }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ + sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); + } +} + +/* +** Implementation of the offsets() function for FTS3 +*/ +static void fts3OffsetsFunc( + sqlite3_context *pContext, /* SQLite function call context */ + int nVal, /* Size of argument array */ + sqlite3_value **apVal /* Array of arguments */ +){ + Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ + + UNUSED_PARAMETER(nVal); + + assert( nVal==1 ); + if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return; + assert( pCsr ); + if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ + sqlite3Fts3Offsets(pContext, pCsr); + } +} + +/* +** Implementation of the special optimize() function for FTS3. This +** function merges all segments in the database to a single segment. +** Example usage is: +** +** SELECT optimize(t) FROM t LIMIT 1; +** +** where 't' is the name of an FTS3 table. +*/ +static void fts3OptimizeFunc( + sqlite3_context *pContext, /* SQLite function call context */ + int nVal, /* Size of argument array */ + sqlite3_value **apVal /* Array of arguments */ +){ + int rc; /* Return code */ + Fts3Table *p; /* Virtual table handle */ + Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */ + + UNUSED_PARAMETER(nVal); + + assert( nVal==1 ); + if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return; + p = (Fts3Table *)pCursor->base.pVtab; + assert( p ); + + rc = sqlite3Fts3Optimize(p); + + switch( rc ){ + case SQLITE_OK: + sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); + break; + case SQLITE_DONE: + sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC); + break; + default: + sqlite3_result_error_code(pContext, rc); + break; + } +} + +/* +** Implementation of the matchinfo() function for FTS3 +*/ +static void fts3MatchinfoFunc( + sqlite3_context *pContext, /* SQLite function call context */ + int nVal, /* Size of argument array */ + sqlite3_value **apVal /* Array of arguments */ +){ + Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ + assert( nVal==1 || nVal==2 ); + if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){ + const char *zArg = 0; + if( nVal>1 ){ + zArg = (const char *)sqlite3_value_text(apVal[1]); + } + sqlite3Fts3Matchinfo(pContext, pCsr, zArg); + } +} + +/* +** This routine implements the xFindFunction method for the FTS3 +** virtual table. +*/ +static int fts3FindFunctionMethod( + sqlite3_vtab *pVtab, /* Virtual table handle */ + int nArg, /* Number of SQL function arguments */ + const char *zName, /* Name of SQL function */ + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ + void **ppArg /* Unused */ +){ + struct Overloaded { + const char *zName; + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); + } aOverload[] = { + { "snippet", fts3SnippetFunc }, + { "offsets", fts3OffsetsFunc }, + { "optimize", fts3OptimizeFunc }, + { "matchinfo", fts3MatchinfoFunc }, + }; + int i; /* Iterator variable */ + + UNUSED_PARAMETER(pVtab); + UNUSED_PARAMETER(nArg); + UNUSED_PARAMETER(ppArg); + + for(i=0; idb; /* Database connection */ + int rc; /* Return Code */ + + /* As it happens, the pending terms table is always empty here. This is + ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction + ** always opens a savepoint transaction. And the xSavepoint() method + ** flushes the pending terms table. But leave the (no-op) call to + ** PendingTermsFlush() in in case that changes. + */ + assert( p->nPendingData==0 ); + rc = sqlite3Fts3PendingTermsFlush(p); + + if( p->zContentTbl==0 ){ + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';", + p->zDb, p->zName, zName + ); + } + + if( p->bHasDocsize ){ + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';", + p->zDb, p->zName, zName + ); + } + if( p->bHasStat ){ + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';", + p->zDb, p->zName, zName + ); + } + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';", + p->zDb, p->zName, zName + ); + fts3DbExec(&rc, db, + "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';", + p->zDb, p->zName, zName + ); + return rc; +} + +/* +** The xSavepoint() method. +** +** Flush the contents of the pending-terms table to disk. +*/ +static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ + int rc = SQLITE_OK; + UNUSED_PARAMETER(iSavepoint); + assert( ((Fts3Table *)pVtab)->inTransaction ); + assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint ); + TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint ); + if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){ + rc = fts3SyncMethod(pVtab); + } + return rc; +} + +/* +** The xRelease() method. +** +** This is a no-op. +*/ +static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ + TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); + UNUSED_PARAMETER(iSavepoint); + UNUSED_PARAMETER(pVtab); + assert( p->inTransaction ); + assert( p->mxSavepoint >= iSavepoint ); + TESTONLY( p->mxSavepoint = iSavepoint-1 ); + return SQLITE_OK; +} + +/* +** The xRollbackTo() method. +** +** Discard the contents of the pending terms table. +*/ +static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ + Fts3Table *p = (Fts3Table*)pVtab; + UNUSED_PARAMETER(iSavepoint); + assert( p->inTransaction ); + assert( p->mxSavepoint >= iSavepoint ); + TESTONLY( p->mxSavepoint = iSavepoint ); + sqlite3Fts3PendingTermsClear(p); + return SQLITE_OK; +} + +static const sqlite3_module fts3Module = { + /* iVersion */ 2, + /* xCreate */ fts3CreateMethod, + /* xConnect */ fts3ConnectMethod, + /* xBestIndex */ fts3BestIndexMethod, + /* xDisconnect */ fts3DisconnectMethod, + /* xDestroy */ fts3DestroyMethod, + /* xOpen */ fts3OpenMethod, + /* xClose */ fts3CloseMethod, + /* xFilter */ fts3FilterMethod, + /* xNext */ fts3NextMethod, + /* xEof */ fts3EofMethod, + /* xColumn */ fts3ColumnMethod, + /* xRowid */ fts3RowidMethod, + /* xUpdate */ fts3UpdateMethod, + /* xBegin */ fts3BeginMethod, + /* xSync */ fts3SyncMethod, + /* xCommit */ fts3CommitMethod, + /* xRollback */ fts3RollbackMethod, + /* xFindFunction */ fts3FindFunctionMethod, + /* xRename */ fts3RenameMethod, + /* xSavepoint */ fts3SavepointMethod, + /* xRelease */ fts3ReleaseMethod, + /* xRollbackTo */ fts3RollbackToMethod, +}; + +/* +** This function is registered as the module destructor (called when an +** FTS3 enabled database connection is closed). It frees the memory +** allocated for the tokenizer hash table. +*/ +static void hashDestroy(void *p){ + Fts3Hash *pHash = (Fts3Hash *)p; + sqlite3Fts3HashClear(pHash); + sqlite3_free(pHash); +} + +/* +** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are +** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c +** respectively. The following three forward declarations are for functions +** declared in these files used to retrieve the respective implementations. +** +** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed +** to by the argument to point to the "simple" tokenizer implementation. +** And so on. +*/ +void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); +void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 +void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule); +#endif +#ifdef SQLITE_ENABLE_ICU +void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); +#endif + +/* +** Initialize the fts3 extension. If this extension is built as part +** of the sqlite library, then this function is called directly by +** SQLite. If fts3 is built as a dynamically loadable extension, this +** function is called by the sqlite3_extension_init() entry point. +*/ +int sqlite3Fts3Init(sqlite3 *db){ + int rc = SQLITE_OK; + Fts3Hash *pHash = 0; + const sqlite3_tokenizer_module *pSimple = 0; + const sqlite3_tokenizer_module *pPorter = 0; +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 + const sqlite3_tokenizer_module *pUnicode = 0; +#endif + +#ifdef SQLITE_ENABLE_ICU + const sqlite3_tokenizer_module *pIcu = 0; + sqlite3Fts3IcuTokenizerModule(&pIcu); +#endif + +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 + sqlite3Fts3UnicodeTokenizer(&pUnicode); +#endif + +#ifdef SQLITE_TEST + rc = sqlite3Fts3InitTerm(db); + if( rc!=SQLITE_OK ) return rc; +#endif + + rc = sqlite3Fts3InitAux(db); + if( rc!=SQLITE_OK ) return rc; + + sqlite3Fts3SimpleTokenizerModule(&pSimple); + sqlite3Fts3PorterTokenizerModule(&pPorter); + + /* Allocate and initialize the hash-table used to store tokenizers. */ + pHash = sqlite3_malloc(sizeof(Fts3Hash)); + if( !pHash ){ + rc = SQLITE_NOMEM; + }else{ + sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); + } + + /* Load the built-in tokenizers into the hash table */ + if( rc==SQLITE_OK ){ + if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple) + || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) + +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 + || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) +#endif +#ifdef SQLITE_ENABLE_ICU + || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu)) +#endif + ){ + rc = SQLITE_NOMEM; + } + } + +#ifdef SQLITE_TEST + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3ExprInitTestInterface(db); + } +#endif + + /* Create the virtual table wrapper around the hash-table and overload + ** the two scalar functions. If this is successful, register the + ** module with sqlite. + */ + if( SQLITE_OK==rc + && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer")) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2)) + && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1)) + ){ + rc = sqlite3_create_module_v2( + db, "fts3", &fts3Module, (void *)pHash, hashDestroy + ); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_module_v2( + db, "fts4", &fts3Module, (void *)pHash, 0 + ); + } + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3InitTok(db, (void *)pHash); + } + return rc; + } + + + /* An error has occurred. Delete the hash table and return the error code. */ + assert( rc!=SQLITE_OK ); + if( pHash ){ + sqlite3Fts3HashClear(pHash); + sqlite3_free(pHash); + } + return rc; +} + +/* +** Allocate an Fts3MultiSegReader for each token in the expression headed +** by pExpr. +** +** An Fts3SegReader object is a cursor that can seek or scan a range of +** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple +** Fts3SegReader objects internally to provide an interface to seek or scan +** within the union of all segments of a b-tree. Hence the name. +** +** If the allocated Fts3MultiSegReader just seeks to a single entry in a +** segment b-tree (if the term is not a prefix or it is a prefix for which +** there exists prefix b-tree of the right length) then it may be traversed +** and merged incrementally. Otherwise, it has to be merged into an in-memory +** doclist and then traversed. +*/ +static void fts3EvalAllocateReaders( + Fts3Cursor *pCsr, /* FTS cursor handle */ + Fts3Expr *pExpr, /* Allocate readers for this expression */ + int *pnToken, /* OUT: Total number of tokens in phrase. */ + int *pnOr, /* OUT: Total number of OR nodes in expr. */ + int *pRc /* IN/OUT: Error code */ +){ + if( pExpr && SQLITE_OK==*pRc ){ + if( pExpr->eType==FTSQUERY_PHRASE ){ + int i; + int nToken = pExpr->pPhrase->nToken; + *pnToken += nToken; + for(i=0; ipPhrase->aToken[i]; + int rc = fts3TermSegReaderCursor(pCsr, + pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr + ); + if( rc!=SQLITE_OK ){ + *pRc = rc; + return; + } + } + assert( pExpr->pPhrase->iDoclistToken==0 ); + pExpr->pPhrase->iDoclistToken = -1; + }else{ + *pnOr += (pExpr->eType==FTSQUERY_OR); + fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc); + fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc); + } + } +} + +/* +** Arguments pList/nList contain the doclist for token iToken of phrase p. +** It is merged into the main doclist stored in p->doclist.aAll/nAll. +** +** This function assumes that pList points to a buffer allocated using +** sqlite3_malloc(). This function takes responsibility for eventually +** freeing the buffer. +*/ +static void fts3EvalPhraseMergeToken( + Fts3Table *pTab, /* FTS Table pointer */ + Fts3Phrase *p, /* Phrase to merge pList/nList into */ + int iToken, /* Token pList/nList corresponds to */ + char *pList, /* Pointer to doclist */ + int nList /* Number of bytes in pList */ +){ + assert( iToken!=p->iDoclistToken ); + + if( pList==0 ){ + sqlite3_free(p->doclist.aAll); + p->doclist.aAll = 0; + p->doclist.nAll = 0; + } + + else if( p->iDoclistToken<0 ){ + p->doclist.aAll = pList; + p->doclist.nAll = nList; + } + + else if( p->doclist.aAll==0 ){ + sqlite3_free(pList); + } + + else { + char *pLeft; + char *pRight; + int nLeft; + int nRight; + int nDiff; + + if( p->iDoclistTokendoclist.aAll; + nLeft = p->doclist.nAll; + pRight = pList; + nRight = nList; + nDiff = iToken - p->iDoclistToken; + }else{ + pRight = p->doclist.aAll; + nRight = p->doclist.nAll; + pLeft = pList; + nLeft = nList; + nDiff = p->iDoclistToken - iToken; + } + + fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight); + sqlite3_free(pLeft); + p->doclist.aAll = pRight; + p->doclist.nAll = nRight; + } + + if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken; +} + +/* +** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist +** does not take deferred tokens into account. +** +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. +*/ +static int fts3EvalPhraseLoad( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Phrase *p /* Phrase object */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int iToken; + int rc = SQLITE_OK; + + for(iToken=0; rc==SQLITE_OK && iTokennToken; iToken++){ + Fts3PhraseToken *pToken = &p->aToken[iToken]; + assert( pToken->pDeferred==0 || pToken->pSegcsr==0 ); + + if( pToken->pSegcsr ){ + int nThis = 0; + char *pThis = 0; + rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis); + if( rc==SQLITE_OK ){ + fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis); + } + } + assert( pToken->pSegcsr==0 ); + } + + return rc; +} + +/* +** This function is called on each phrase after the position lists for +** any deferred tokens have been loaded into memory. It updates the phrases +** current position list to include only those positions that are really +** instances of the phrase (after considering deferred tokens). If this +** means that the phrase does not appear in the current row, doclist.pList +** and doclist.nList are both zeroed. +** +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. +*/ +static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ + int iToken; /* Used to iterate through phrase tokens */ + char *aPoslist = 0; /* Position list for deferred tokens */ + int nPoslist = 0; /* Number of bytes in aPoslist */ + int iPrev = -1; /* Token number of previous deferred token */ + + assert( pPhrase->doclist.bFreeList==0 ); + + for(iToken=0; iTokennToken; iToken++){ + Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; + Fts3DeferredToken *pDeferred = pToken->pDeferred; + + if( pDeferred ){ + char *pList; + int nList; + int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList); + if( rc!=SQLITE_OK ) return rc; + + if( pList==0 ){ + sqlite3_free(aPoslist); + pPhrase->doclist.pList = 0; + pPhrase->doclist.nList = 0; + return SQLITE_OK; + + }else if( aPoslist==0 ){ + aPoslist = pList; + nPoslist = nList; + + }else{ + char *aOut = pList; + char *p1 = aPoslist; + char *p2 = aOut; + + assert( iPrev>=0 ); + fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2); + sqlite3_free(aPoslist); + aPoslist = pList; + nPoslist = (int)(aOut - aPoslist); + if( nPoslist==0 ){ + sqlite3_free(aPoslist); + pPhrase->doclist.pList = 0; + pPhrase->doclist.nList = 0; + return SQLITE_OK; + } + } + iPrev = iToken; + } + } + + if( iPrev>=0 ){ + int nMaxUndeferred = pPhrase->iDoclistToken; + if( nMaxUndeferred<0 ){ + pPhrase->doclist.pList = aPoslist; + pPhrase->doclist.nList = nPoslist; + pPhrase->doclist.iDocid = pCsr->iPrevId; + pPhrase->doclist.bFreeList = 1; + }else{ + int nDistance; + char *p1; + char *p2; + char *aOut; + + if( nMaxUndeferred>iPrev ){ + p1 = aPoslist; + p2 = pPhrase->doclist.pList; + nDistance = nMaxUndeferred - iPrev; + }else{ + p1 = pPhrase->doclist.pList; + p2 = aPoslist; + nDistance = iPrev - nMaxUndeferred; + } + + aOut = (char *)sqlite3_malloc(nPoslist+8); + if( !aOut ){ + sqlite3_free(aPoslist); + return SQLITE_NOMEM; + } + + pPhrase->doclist.pList = aOut; + if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){ + pPhrase->doclist.bFreeList = 1; + pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList); + }else{ + sqlite3_free(aOut); + pPhrase->doclist.pList = 0; + pPhrase->doclist.nList = 0; + } + sqlite3_free(aPoslist); + } + } + + return SQLITE_OK; +} + +/* +** Maximum number of tokens a phrase may have to be considered for the +** incremental doclists strategy. +*/ +#define MAX_INCR_PHRASE_TOKENS 4 + +/* +** This function is called for each Fts3Phrase in a full-text query +** expression to initialize the mechanism for returning rows. Once this +** function has been called successfully on an Fts3Phrase, it may be +** used with fts3EvalPhraseNext() to iterate through the matching docids. +** +** If parameter bOptOk is true, then the phrase may (or may not) use the +** incremental loading strategy. Otherwise, the entire doclist is loaded into +** memory within this call. +** +** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. +*/ +static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; /* Error code */ + int i; + + /* Determine if doclists may be loaded from disk incrementally. This is + ** possible if the bOptOk argument is true, the FTS doclists will be + ** scanned in forward order, and the phrase consists of + ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first" + ** tokens or prefix tokens that cannot use a prefix-index. */ + int bHaveIncr = 0; + int bIncrOk = (bOptOk + && pCsr->bDesc==pTab->bDescIdx + && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 + && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 +#ifdef SQLITE_TEST + && pTab->bNoIncrDoclist==0 +#endif + ); + for(i=0; bIncrOk==1 && inToken; i++){ + Fts3PhraseToken *pToken = &p->aToken[i]; + if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){ + bIncrOk = 0; + } + if( pToken->pSegcsr ) bHaveIncr = 1; + } + + if( bIncrOk && bHaveIncr ){ + /* Use the incremental approach. */ + int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn); + for(i=0; rc==SQLITE_OK && inToken; i++){ + Fts3PhraseToken *pToken = &p->aToken[i]; + Fts3MultiSegReader *pSegcsr = pToken->pSegcsr; + if( pSegcsr ){ + rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n); + } + } + p->bIncr = 1; + }else{ + /* Load the full doclist for the phrase into memory. */ + rc = fts3EvalPhraseLoad(pCsr, p); + p->bIncr = 0; + } + + assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr ); + return rc; +} + +/* +** This function is used to iterate backwards (from the end to start) +** through doclists. It is used by this module to iterate through phrase +** doclists in reverse and by the fts3_write.c module to iterate through +** pending-terms lists when writing to databases with "order=desc". +** +** The doclist may be sorted in ascending (parameter bDescIdx==0) or +** descending (parameter bDescIdx==1) order of docid. Regardless, this +** function iterates from the end of the doclist to the beginning. +*/ +void sqlite3Fts3DoclistPrev( + int bDescIdx, /* True if the doclist is desc */ + char *aDoclist, /* Pointer to entire doclist */ + int nDoclist, /* Length of aDoclist in bytes */ + char **ppIter, /* IN/OUT: Iterator pointer */ + sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ + int *pnList, /* OUT: List length pointer */ + u8 *pbEof /* OUT: End-of-file flag */ +){ + char *p = *ppIter; + + assert( nDoclist>0 ); + assert( *pbEof==0 ); + assert( p || *piDocid==0 ); + assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) ); + + if( p==0 ){ + sqlite3_int64 iDocid = 0; + char *pNext = 0; + char *pDocid = aDoclist; + char *pEnd = &aDoclist[nDoclist]; + int iMul = 1; + + while( pDocid0 ); + assert( *pbEof==0 ); + assert( p || *piDocid==0 ); + assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) ); + + if( p==0 ){ + p = aDoclist; + p += sqlite3Fts3GetVarint(p, piDocid); + }else{ + fts3PoslistCopy(0, &p); + if( p>=&aDoclist[nDoclist] ){ + *pbEof = 1; + }else{ + sqlite3_int64 iVar; + p += sqlite3Fts3GetVarint(p, &iVar); + *piDocid += ((bDescIdx ? -1 : 1) * iVar); + } + } + + *ppIter = p; +} + +/* +** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof +** to true if EOF is reached. +*/ +static void fts3EvalDlPhraseNext( + Fts3Table *pTab, + Fts3Doclist *pDL, + u8 *pbEof +){ + char *pIter; /* Used to iterate through aAll */ + char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */ + + if( pDL->pNextDocid ){ + pIter = pDL->pNextDocid; + }else{ + pIter = pDL->aAll; + } + + if( pIter>=pEnd ){ + /* We have already reached the end of this doclist. EOF. */ + *pbEof = 1; + }else{ + sqlite3_int64 iDelta; + pIter += sqlite3Fts3GetVarint(pIter, &iDelta); + if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){ + pDL->iDocid += iDelta; + }else{ + pDL->iDocid -= iDelta; + } + pDL->pList = pIter; + fts3PoslistCopy(0, &pIter); + pDL->nList = (int)(pIter - pDL->pList); + + /* pIter now points just past the 0x00 that terminates the position- + ** list for document pDL->iDocid. However, if this position-list was + ** edited in place by fts3EvalNearTrim(), then pIter may not actually + ** point to the start of the next docid value. The following line deals + ** with this case by advancing pIter past the zero-padding added by + ** fts3EvalNearTrim(). */ + while( pIterpNextDocid = pIter; + assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter ); + *pbEof = 0; + } +} + +/* +** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext(). +*/ +typedef struct TokenDoclist TokenDoclist; +struct TokenDoclist { + int bIgnore; + sqlite3_int64 iDocid; + char *pList; + int nList; +}; + +/* +** Token pToken is an incrementally loaded token that is part of a +** multi-token phrase. Advance it to the next matching document in the +** database and populate output variable *p with the details of the new +** entry. Or, if the iterator has reached EOF, set *pbEof to true. +** +** If an error occurs, return an SQLite error code. Otherwise, return +** SQLITE_OK. +*/ +static int incrPhraseTokenNext( + Fts3Table *pTab, /* Virtual table handle */ + Fts3Phrase *pPhrase, /* Phrase to advance token of */ + int iToken, /* Specific token to advance */ + TokenDoclist *p, /* OUT: Docid and doclist for new entry */ + u8 *pbEof /* OUT: True if iterator is at EOF */ +){ + int rc = SQLITE_OK; + + if( pPhrase->iDoclistToken==iToken ){ + assert( p->bIgnore==0 ); + assert( pPhrase->aToken[iToken].pSegcsr==0 ); + fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof); + p->pList = pPhrase->doclist.pList; + p->nList = pPhrase->doclist.nList; + p->iDocid = pPhrase->doclist.iDocid; + }else{ + Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; + assert( pToken->pDeferred==0 ); + assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 ); + if( pToken->pSegcsr ){ + assert( p->bIgnore==0 ); + rc = sqlite3Fts3MsrIncrNext( + pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList + ); + if( p->pList==0 ) *pbEof = 1; + }else{ + p->bIgnore = 1; + } + } + + return rc; +} + + +/* +** The phrase iterator passed as the second argument: +** +** * features at least one token that uses an incremental doclist, and +** +** * does not contain any deferred tokens. +** +** Advance it to the next matching documnent in the database and populate +** the Fts3Doclist.pList and nList fields. +** +** If there is no "next" entry and no error occurs, then *pbEof is set to +** 1 before returning. Otherwise, if no error occurs and the iterator is +** successfully advanced, *pbEof is set to 0. +** +** If an error occurs, return an SQLite error code. Otherwise, return +** SQLITE_OK. +*/ +static int fts3EvalIncrPhraseNext( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Phrase *p, /* Phrase object to advance to next docid */ + u8 *pbEof /* OUT: Set to 1 if EOF */ +){ + int rc = SQLITE_OK; + Fts3Doclist *pDL = &p->doclist; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + u8 bEof = 0; + + /* This is only called if it is guaranteed that the phrase has at least + ** one incremental token. In which case the bIncr flag is set. */ + assert( p->bIncr==1 ); + + if( p->nToken==1 && p->bIncr ){ + rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, + &pDL->iDocid, &pDL->pList, &pDL->nList + ); + if( pDL->pList==0 ) bEof = 1; + }else{ + int bDescDoclist = pCsr->bDesc; + struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS]; + + memset(a, 0, sizeof(a)); + assert( p->nToken<=MAX_INCR_PHRASE_TOKENS ); + assert( p->iDoclistTokennToken && bEof==0; i++){ + rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); + if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){ + iMax = a[i].iDocid; + bMaxSet = 1; + } + } + assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 ); + assert( rc!=SQLITE_OK || bMaxSet ); + + /* Keep advancing iterators until they all point to the same document */ + for(i=0; inToken; i++){ + while( rc==SQLITE_OK && bEof==0 + && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 + ){ + rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); + if( DOCID_CMP(a[i].iDocid, iMax)>0 ){ + iMax = a[i].iDocid; + i = 0; + } + } + } + + /* Check if the current entries really are a phrase match */ + if( bEof==0 ){ + int nList = 0; + int nByte = a[p->nToken-1].nList; + char *aDoclist = sqlite3_malloc(nByte+1); + if( !aDoclist ) return SQLITE_NOMEM; + memcpy(aDoclist, a[p->nToken-1].pList, nByte+1); + + for(i=0; i<(p->nToken-1); i++){ + if( a[i].bIgnore==0 ){ + char *pL = a[i].pList; + char *pR = aDoclist; + char *pOut = aDoclist; + int nDist = p->nToken-1-i; + int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR); + if( res==0 ) break; + nList = (int)(pOut - aDoclist); + } + } + if( i==(p->nToken-1) ){ + pDL->iDocid = iMax; + pDL->pList = aDoclist; + pDL->nList = nList; + pDL->bFreeList = 1; + break; + } + sqlite3_free(aDoclist); + } + } + } + + *pbEof = bEof; + return rc; +} + +/* +** Attempt to move the phrase iterator to point to the next matching docid. +** If an error occurs, return an SQLite error code. Otherwise, return +** SQLITE_OK. +** +** If there is no "next" entry and no error occurs, then *pbEof is set to +** 1 before returning. Otherwise, if no error occurs and the iterator is +** successfully advanced, *pbEof is set to 0. +*/ +static int fts3EvalPhraseNext( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Phrase *p, /* Phrase object to advance to next docid */ + u8 *pbEof /* OUT: Set to 1 if EOF */ +){ + int rc = SQLITE_OK; + Fts3Doclist *pDL = &p->doclist; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + + if( p->bIncr ){ + rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof); + }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){ + sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, + &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof + ); + pDL->pList = pDL->pNextDocid; + }else{ + fts3EvalDlPhraseNext(pTab, pDL, pbEof); + } + + return rc; +} + +/* +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** Otherwise, fts3EvalPhraseStart() is called on all phrases within the +** expression. Also the Fts3Expr.bDeferred variable is set to true for any +** expressions for which all descendent tokens are deferred. +** +** If parameter bOptOk is zero, then it is guaranteed that the +** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for +** each phrase in the expression (subject to deferred token processing). +** Or, if bOptOk is non-zero, then one or more tokens within the expression +** may be loaded incrementally, meaning doclist.aAll/nAll is not available. +** +** If an error occurs within this function, *pRc is set to an SQLite error +** code before returning. +*/ +static void fts3EvalStartReaders( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Expr *pExpr, /* Expression to initialize phrases in */ + int *pRc /* IN/OUT: Error code */ +){ + if( pExpr && SQLITE_OK==*pRc ){ + if( pExpr->eType==FTSQUERY_PHRASE ){ + int i; + int nToken = pExpr->pPhrase->nToken; + for(i=0; ipPhrase->aToken[i].pDeferred==0 ) break; + } + pExpr->bDeferred = (i==nToken); + *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase); + }else{ + fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc); + fts3EvalStartReaders(pCsr, pExpr->pRight, pRc); + pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred); + } + } +} + +/* +** An array of the following structures is assembled as part of the process +** of selecting tokens to defer before the query starts executing (as part +** of the xFilter() method). There is one element in the array for each +** token in the FTS expression. +** +** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong +** to phrases that are connected only by AND and NEAR operators (not OR or +** NOT). When determining tokens to defer, each AND/NEAR cluster is considered +** separately. The root of a tokens AND/NEAR cluster is stored in +** Fts3TokenAndCost.pRoot. +*/ +typedef struct Fts3TokenAndCost Fts3TokenAndCost; +struct Fts3TokenAndCost { + Fts3Phrase *pPhrase; /* The phrase the token belongs to */ + int iToken; /* Position of token in phrase */ + Fts3PhraseToken *pToken; /* The token itself */ + Fts3Expr *pRoot; /* Root of NEAR/AND cluster */ + int nOvfl; /* Number of overflow pages to load doclist */ + int iCol; /* The column the token must match */ +}; + +/* +** This function is used to populate an allocated Fts3TokenAndCost array. +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** Otherwise, if an error occurs during execution, *pRc is set to an +** SQLite error code. +*/ +static void fts3EvalTokenCosts( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */ + Fts3Expr *pExpr, /* Expression to consider */ + Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */ + Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */ + int *pRc /* IN/OUT: Error code */ +){ + if( *pRc==SQLITE_OK ){ + if( pExpr->eType==FTSQUERY_PHRASE ){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + int i; + for(i=0; *pRc==SQLITE_OK && inToken; i++){ + Fts3TokenAndCost *pTC = (*ppTC)++; + pTC->pPhrase = pPhrase; + pTC->iToken = i; + pTC->pRoot = pRoot; + pTC->pToken = &pPhrase->aToken[i]; + pTC->iCol = pPhrase->iColumn; + *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl); + } + }else if( pExpr->eType!=FTSQUERY_NOT ){ + assert( pExpr->eType==FTSQUERY_OR + || pExpr->eType==FTSQUERY_AND + || pExpr->eType==FTSQUERY_NEAR + ); + assert( pExpr->pLeft && pExpr->pRight ); + if( pExpr->eType==FTSQUERY_OR ){ + pRoot = pExpr->pLeft; + **ppOr = pRoot; + (*ppOr)++; + } + fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc); + if( pExpr->eType==FTSQUERY_OR ){ + pRoot = pExpr->pRight; + **ppOr = pRoot; + (*ppOr)++; + } + fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc); + } + } +} + +/* +** Determine the average document (row) size in pages. If successful, +** write this value to *pnPage and return SQLITE_OK. Otherwise, return +** an SQLite error code. +** +** The average document size in pages is calculated by first calculating +** determining the average size in bytes, B. If B is less than the amount +** of data that will fit on a single leaf page of an intkey table in +** this database, then the average docsize is 1. Otherwise, it is 1 plus +** the number of overflow pages consumed by a record B bytes in size. +*/ +static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){ + if( pCsr->nRowAvg==0 ){ + /* The average document size, which is required to calculate the cost + ** of each doclist, has not yet been determined. Read the required + ** data from the %_stat table to calculate it. + ** + ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 + ** varints, where nCol is the number of columns in the FTS3 table. + ** The first varint is the number of documents currently stored in + ** the table. The following nCol varints contain the total amount of + ** data stored in all rows of each column of the table, from left + ** to right. + */ + int rc; + Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; + sqlite3_stmt *pStmt; + sqlite3_int64 nDoc = 0; + sqlite3_int64 nByte = 0; + const char *pEnd; + const char *a; + + rc = sqlite3Fts3SelectDoctotal(p, &pStmt); + if( rc!=SQLITE_OK ) return rc; + a = sqlite3_column_blob(pStmt, 0); + assert( a ); + + pEnd = &a[sqlite3_column_bytes(pStmt, 0)]; + a += sqlite3Fts3GetVarint(a, &nDoc); + while( anDoc = nDoc; + pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz); + assert( pCsr->nRowAvg>0 ); + rc = sqlite3_reset(pStmt); + if( rc!=SQLITE_OK ) return rc; + } + + *pnPage = pCsr->nRowAvg; + return SQLITE_OK; +} + +/* +** This function is called to select the tokens (if any) that will be +** deferred. The array aTC[] has already been populated when this is +** called. +** +** This function is called once for each AND/NEAR cluster in the +** expression. Each invocation determines which tokens to defer within +** the cluster with root node pRoot. See comments above the definition +** of struct Fts3TokenAndCost for more details. +** +** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken() +** called on each token to defer. Otherwise, an SQLite error code is +** returned. +*/ +static int fts3EvalSelectDeferred( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Expr *pRoot, /* Consider tokens with this root node */ + Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */ + int nTC /* Number of entries in aTC[] */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int nDocSize = 0; /* Number of pages per doc loaded */ + int rc = SQLITE_OK; /* Return code */ + int ii; /* Iterator variable for various purposes */ + int nOvfl = 0; /* Total overflow pages used by doclists */ + int nToken = 0; /* Total number of tokens in cluster */ + + int nMinEst = 0; /* The minimum count for any phrase so far. */ + int nLoad4 = 1; /* (Phrases that will be loaded)^4. */ + + /* Tokens are never deferred for FTS tables created using the content=xxx + ** option. The reason being that it is not guaranteed that the content + ** table actually contains the same data as the index. To prevent this from + ** causing any problems, the deferred token optimization is completely + ** disabled for content=xxx tables. */ + if( pTab->zContentTbl ){ + return SQLITE_OK; + } + + /* Count the tokens in this AND/NEAR cluster. If none of the doclists + ** associated with the tokens spill onto overflow pages, or if there is + ** only 1 token, exit early. No tokens to defer in this case. */ + for(ii=0; ii0 ); + + + /* Iterate through all tokens in this AND/NEAR cluster, in ascending order + ** of the number of overflow pages that will be loaded by the pager layer + ** to retrieve the entire doclist for the token from the full-text index. + ** Load the doclists for tokens that are either: + ** + ** a. The cheapest token in the entire query (i.e. the one visited by the + ** first iteration of this loop), or + ** + ** b. Part of a multi-token phrase. + ** + ** After each token doclist is loaded, merge it with the others from the + ** same phrase and count the number of documents that the merged doclist + ** contains. Set variable "nMinEst" to the smallest number of documents in + ** any phrase doclist for which 1 or more token doclists have been loaded. + ** Let nOther be the number of other phrases for which it is certain that + ** one or more tokens will not be deferred. + ** + ** Then, for each token, defer it if loading the doclist would result in + ** loading N or more overflow pages into memory, where N is computed as: + ** + ** (nMinEst + 4^nOther - 1) / (4^nOther) + */ + for(ii=0; iinOvfl) + ){ + pTC = &aTC[iTC]; + } + } + assert( pTC ); + + if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){ + /* The number of overflow pages to load for this (and therefore all + ** subsequent) tokens is greater than the estimated number of pages + ** that will be loaded if all subsequent tokens are deferred. + */ + Fts3PhraseToken *pToken = pTC->pToken; + rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol); + fts3SegReaderCursorFree(pToken->pSegcsr); + pToken->pSegcsr = 0; + }else{ + /* Set nLoad4 to the value of (4^nOther) for the next iteration of the + ** for-loop. Except, limit the value to 2^24 to prevent it from + ** overflowing the 32-bit integer it is stored in. */ + if( ii<12 ) nLoad4 = nLoad4*4; + + if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){ + /* Either this is the cheapest token in the entire query, or it is + ** part of a multi-token phrase. Either way, the entire doclist will + ** (eventually) be loaded into memory. It may as well be now. */ + Fts3PhraseToken *pToken = pTC->pToken; + int nList = 0; + char *pList = 0; + rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList); + assert( rc==SQLITE_OK || pList==0 ); + if( rc==SQLITE_OK ){ + int nCount; + fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList); + nCount = fts3DoclistCountDocids( + pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll + ); + if( ii==0 || nCountpToken = 0; + } + + return rc; +} + +/* +** This function is called from within the xFilter method. It initializes +** the full-text query currently stored in pCsr->pExpr. To iterate through +** the results of a query, the caller does: +** +** fts3EvalStart(pCsr); +** while( 1 ){ +** fts3EvalNext(pCsr); +** if( pCsr->bEof ) break; +** ... return row pCsr->iPrevId to the caller ... +** } +*/ +static int fts3EvalStart(Fts3Cursor *pCsr){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; + int nToken = 0; + int nOr = 0; + + /* Allocate a MultiSegReader for each token in the expression. */ + fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc); + + /* Determine which, if any, tokens in the expression should be deferred. */ +#ifndef SQLITE_DISABLE_FTS4_DEFERRED + if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){ + Fts3TokenAndCost *aTC; + Fts3Expr **apOr; + aTC = (Fts3TokenAndCost *)sqlite3_malloc( + sizeof(Fts3TokenAndCost) * nToken + + sizeof(Fts3Expr *) * nOr * 2 + ); + apOr = (Fts3Expr **)&aTC[nToken]; + + if( !aTC ){ + rc = SQLITE_NOMEM; + }else{ + int ii; + Fts3TokenAndCost *pTC = aTC; + Fts3Expr **ppOr = apOr; + + fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc); + nToken = (int)(pTC-aTC); + nOr = (int)(ppOr-apOr); + + if( rc==SQLITE_OK ){ + rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken); + for(ii=0; rc==SQLITE_OK && iipExpr, &rc); + return rc; +} + +/* +** Invalidate the current position list for phrase pPhrase. +*/ +static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){ + if( pPhrase->doclist.bFreeList ){ + sqlite3_free(pPhrase->doclist.pList); + } + pPhrase->doclist.pList = 0; + pPhrase->doclist.nList = 0; + pPhrase->doclist.bFreeList = 0; +} + +/* +** This function is called to edit the position list associated with +** the phrase object passed as the fifth argument according to a NEAR +** condition. For example: +** +** abc NEAR/5 "def ghi" +** +** Parameter nNear is passed the NEAR distance of the expression (5 in +** the example above). When this function is called, *paPoslist points to +** the position list, and *pnToken is the number of phrase tokens in, the +** phrase on the other side of the NEAR operator to pPhrase. For example, +** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to +** the position list associated with phrase "abc". +** +** All positions in the pPhrase position list that are not sufficiently +** close to a position in the *paPoslist position list are removed. If this +** leaves 0 positions, zero is returned. Otherwise, non-zero. +** +** Before returning, *paPoslist is set to point to the position lsit +** associated with pPhrase. And *pnToken is set to the number of tokens in +** pPhrase. +*/ +static int fts3EvalNearTrim( + int nNear, /* NEAR distance. As in "NEAR/nNear". */ + char *aTmp, /* Temporary space to use */ + char **paPoslist, /* IN/OUT: Position list */ + int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */ + Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */ +){ + int nParam1 = nNear + pPhrase->nToken; + int nParam2 = nNear + *pnToken; + int nNew; + char *p2; + char *pOut; + int res; + + assert( pPhrase->doclist.pList ); + + p2 = pOut = pPhrase->doclist.pList; + res = fts3PoslistNearMerge( + &pOut, aTmp, nParam1, nParam2, paPoslist, &p2 + ); + if( res ){ + nNew = (int)(pOut - pPhrase->doclist.pList) - 1; + assert( pPhrase->doclist.pList[nNew]=='\0' ); + assert( nNew<=pPhrase->doclist.nList && nNew>0 ); + memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew); + pPhrase->doclist.nList = nNew; + *paPoslist = pPhrase->doclist.pList; + *pnToken = pPhrase->nToken; + } + + return res; +} + +/* +** This function is a no-op if *pRc is other than SQLITE_OK when it is called. +** Otherwise, it advances the expression passed as the second argument to +** point to the next matching row in the database. Expressions iterate through +** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero, +** or descending if it is non-zero. +** +** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if +** successful, the following variables in pExpr are set: +** +** Fts3Expr.bEof (non-zero if EOF - there is no next row) +** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row) +** +** If the expression is of type FTSQUERY_PHRASE, and the expression is not +** at EOF, then the following variables are populated with the position list +** for the phrase for the visited row: +** +** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes) +** FTs3Expr.pPhrase->doclist.pList (pointer to position list) +** +** It says above that this function advances the expression to the next +** matching row. This is usually true, but there are the following exceptions: +** +** 1. Deferred tokens are not taken into account. If a phrase consists +** entirely of deferred tokens, it is assumed to match every row in +** the db. In this case the position-list is not populated at all. +** +** Or, if a phrase contains one or more deferred tokens and one or +** more non-deferred tokens, then the expression is advanced to the +** next possible match, considering only non-deferred tokens. In other +** words, if the phrase is "A B C", and "B" is deferred, the expression +** is advanced to the next row that contains an instance of "A * C", +** where "*" may match any single token. The position list in this case +** is populated as for "A * C" before returning. +** +** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is +** advanced to point to the next row that matches "x AND y". +** +** See fts3EvalTestDeferredAndNear() for details on testing if a row is +** really a match, taking into account deferred tokens and NEAR operators. +*/ +static void fts3EvalNextRow( + Fts3Cursor *pCsr, /* FTS Cursor handle */ + Fts3Expr *pExpr, /* Expr. to advance to next matching row */ + int *pRc /* IN/OUT: Error code */ +){ + if( *pRc==SQLITE_OK ){ + int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */ + assert( pExpr->bEof==0 ); + pExpr->bStart = 1; + + switch( pExpr->eType ){ + case FTSQUERY_NEAR: + case FTSQUERY_AND: { + Fts3Expr *pLeft = pExpr->pLeft; + Fts3Expr *pRight = pExpr->pRight; + assert( !pLeft->bDeferred || !pRight->bDeferred ); + + if( pLeft->bDeferred ){ + /* LHS is entirely deferred. So we assume it matches every row. + ** Advance the RHS iterator to find the next row visited. */ + fts3EvalNextRow(pCsr, pRight, pRc); + pExpr->iDocid = pRight->iDocid; + pExpr->bEof = pRight->bEof; + }else if( pRight->bDeferred ){ + /* RHS is entirely deferred. So we assume it matches every row. + ** Advance the LHS iterator to find the next row visited. */ + fts3EvalNextRow(pCsr, pLeft, pRc); + pExpr->iDocid = pLeft->iDocid; + pExpr->bEof = pLeft->bEof; + }else{ + /* Neither the RHS or LHS are deferred. */ + fts3EvalNextRow(pCsr, pLeft, pRc); + fts3EvalNextRow(pCsr, pRight, pRc); + while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){ + sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid); + if( iDiff==0 ) break; + if( iDiff<0 ){ + fts3EvalNextRow(pCsr, pLeft, pRc); + }else{ + fts3EvalNextRow(pCsr, pRight, pRc); + } + } + pExpr->iDocid = pLeft->iDocid; + pExpr->bEof = (pLeft->bEof || pRight->bEof); + } + break; + } + + case FTSQUERY_OR: { + Fts3Expr *pLeft = pExpr->pLeft; + Fts3Expr *pRight = pExpr->pRight; + sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); + + assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid ); + assert( pRight->bStart || pLeft->iDocid==pRight->iDocid ); + + if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ + fts3EvalNextRow(pCsr, pLeft, pRc); + }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){ + fts3EvalNextRow(pCsr, pRight, pRc); + }else{ + fts3EvalNextRow(pCsr, pLeft, pRc); + fts3EvalNextRow(pCsr, pRight, pRc); + } + + pExpr->bEof = (pLeft->bEof && pRight->bEof); + iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); + if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ + pExpr->iDocid = pLeft->iDocid; + }else{ + pExpr->iDocid = pRight->iDocid; + } + + break; + } + + case FTSQUERY_NOT: { + Fts3Expr *pLeft = pExpr->pLeft; + Fts3Expr *pRight = pExpr->pRight; + + if( pRight->bStart==0 ){ + fts3EvalNextRow(pCsr, pRight, pRc); + assert( *pRc!=SQLITE_OK || pRight->bStart ); + } + + fts3EvalNextRow(pCsr, pLeft, pRc); + if( pLeft->bEof==0 ){ + while( !*pRc + && !pRight->bEof + && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 + ){ + fts3EvalNextRow(pCsr, pRight, pRc); + } + } + pExpr->iDocid = pLeft->iDocid; + pExpr->bEof = pLeft->bEof; + break; + } + + default: { + Fts3Phrase *pPhrase = pExpr->pPhrase; + fts3EvalInvalidatePoslist(pPhrase); + *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof); + pExpr->iDocid = pPhrase->doclist.iDocid; + break; + } + } + } +} + +/* +** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR +** cluster, then this function returns 1 immediately. +** +** Otherwise, it checks if the current row really does match the NEAR +** expression, using the data currently stored in the position lists +** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. +** +** If the current row is a match, the position list associated with each +** phrase in the NEAR expression is edited in place to contain only those +** phrase instances sufficiently close to their peers to satisfy all NEAR +** constraints. In this case it returns 1. If the NEAR expression does not +** match the current row, 0 is returned. The position lists may or may not +** be edited if 0 is returned. +*/ +static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){ + int res = 1; + + /* The following block runs if pExpr is the root of a NEAR query. + ** For example, the query: + ** + ** "w" NEAR "x" NEAR "y" NEAR "z" + ** + ** which is represented in tree form as: + ** + ** | + ** +--NEAR--+ <-- root of NEAR query + ** | | + ** +--NEAR--+ "z" + ** | | + ** +--NEAR--+ "y" + ** | | + ** "w" "x" + ** + ** The right-hand child of a NEAR node is always a phrase. The + ** left-hand child may be either a phrase or a NEAR node. There are + ** no exceptions to this - it's the way the parser in fts3_expr.c works. + */ + if( *pRc==SQLITE_OK + && pExpr->eType==FTSQUERY_NEAR + && pExpr->bEof==0 + && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) + ){ + Fts3Expr *p; + int nTmp = 0; /* Bytes of temp space */ + char *aTmp; /* Temp space for PoslistNearMerge() */ + + /* Allocate temporary working space. */ + for(p=pExpr; p->pLeft; p=p->pLeft){ + nTmp += p->pRight->pPhrase->doclist.nList; + } + nTmp += p->pPhrase->doclist.nList; + if( nTmp==0 ){ + res = 0; + }else{ + aTmp = sqlite3_malloc(nTmp*2); + if( !aTmp ){ + *pRc = SQLITE_NOMEM; + res = 0; + }else{ + char *aPoslist = p->pPhrase->doclist.pList; + int nToken = p->pPhrase->nToken; + + for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){ + Fts3Phrase *pPhrase = p->pRight->pPhrase; + int nNear = p->nNear; + res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); + } + + aPoslist = pExpr->pRight->pPhrase->doclist.pList; + nToken = pExpr->pRight->pPhrase->nToken; + for(p=pExpr->pLeft; p && res; p=p->pLeft){ + int nNear; + Fts3Phrase *pPhrase; + assert( p->pParent && p->pParent->pLeft==p ); + nNear = p->pParent->nNear; + pPhrase = ( + p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase + ); + res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); + } + } + + sqlite3_free(aTmp); + } + } + + return res; +} + +/* +** This function is a helper function for fts3EvalTestDeferredAndNear(). +** Assuming no error occurs or has occurred, It returns non-zero if the +** expression passed as the second argument matches the row that pCsr +** currently points to, or zero if it does not. +** +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** If an error occurs during execution of this function, *pRc is set to +** the appropriate SQLite error code. In this case the returned value is +** undefined. +*/ +static int fts3EvalTestExpr( + Fts3Cursor *pCsr, /* FTS cursor handle */ + Fts3Expr *pExpr, /* Expr to test. May or may not be root. */ + int *pRc /* IN/OUT: Error code */ +){ + int bHit = 1; /* Return value */ + if( *pRc==SQLITE_OK ){ + switch( pExpr->eType ){ + case FTSQUERY_NEAR: + case FTSQUERY_AND: + bHit = ( + fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) + && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) + && fts3EvalNearTest(pExpr, pRc) + ); + + /* If the NEAR expression does not match any rows, zero the doclist for + ** all phrases involved in the NEAR. This is because the snippet(), + ** offsets() and matchinfo() functions are not supposed to recognize + ** any instances of phrases that are part of unmatched NEAR queries. + ** For example if this expression: + ** + ** ... MATCH 'a OR (b NEAR c)' + ** + ** is matched against a row containing: + ** + ** 'a b d e' + ** + ** then any snippet() should ony highlight the "a" term, not the "b" + ** (as "b" is part of a non-matching NEAR clause). + */ + if( bHit==0 + && pExpr->eType==FTSQUERY_NEAR + && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) + ){ + Fts3Expr *p; + for(p=pExpr; p->pPhrase==0; p=p->pLeft){ + if( p->pRight->iDocid==pCsr->iPrevId ){ + fts3EvalInvalidatePoslist(p->pRight->pPhrase); + } + } + if( p->iDocid==pCsr->iPrevId ){ + fts3EvalInvalidatePoslist(p->pPhrase); + } + } + + break; + + case FTSQUERY_OR: { + int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc); + int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc); + bHit = bHit1 || bHit2; + break; + } + + case FTSQUERY_NOT: + bHit = ( + fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) + && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) + ); + break; + + default: { +#ifndef SQLITE_DISABLE_FTS4_DEFERRED + if( pCsr->pDeferred + && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred) + ){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 ); + if( pExpr->bDeferred ){ + fts3EvalInvalidatePoslist(pPhrase); + } + *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase); + bHit = (pPhrase->doclist.pList!=0); + pExpr->iDocid = pCsr->iPrevId; + }else +#endif + { + bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId); + } + break; + } + } + } + return bHit; +} + +/* +** This function is called as the second part of each xNext operation when +** iterating through the results of a full-text query. At this point the +** cursor points to a row that matches the query expression, with the +** following caveats: +** +** * Up until this point, "NEAR" operators in the expression have been +** treated as "AND". +** +** * Deferred tokens have not yet been considered. +** +** If *pRc is not SQLITE_OK when this function is called, it immediately +** returns 0. Otherwise, it tests whether or not after considering NEAR +** operators and deferred tokens the current row is still a match for the +** expression. It returns 1 if both of the following are true: +** +** 1. *pRc is SQLITE_OK when this function returns, and +** +** 2. After scanning the current FTS table row for the deferred tokens, +** it is determined that the row does *not* match the query. +** +** Or, if no error occurs and it seems the current row does match the FTS +** query, return 0. +*/ +static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){ + int rc = *pRc; + int bMiss = 0; + if( rc==SQLITE_OK ){ + + /* If there are one or more deferred tokens, load the current row into + ** memory and scan it to determine the position list for each deferred + ** token. Then, see if this row is really a match, considering deferred + ** tokens and NEAR operators (neither of which were taken into account + ** earlier, by fts3EvalNextRow()). + */ + if( pCsr->pDeferred ){ + rc = fts3CursorSeek(0, pCsr); + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3CacheDeferredDoclists(pCsr); + } + } + bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc)); + + /* Free the position-lists accumulated for each deferred token above. */ + sqlite3Fts3FreeDeferredDoclists(pCsr); + *pRc = rc; + } + return (rc==SQLITE_OK && bMiss); +} + +/* +** Advance to the next document that matches the FTS expression in +** Fts3Cursor.pExpr. +*/ +static int fts3EvalNext(Fts3Cursor *pCsr){ + int rc = SQLITE_OK; /* Return Code */ + Fts3Expr *pExpr = pCsr->pExpr; + assert( pCsr->isEof==0 ); + if( pExpr==0 ){ + pCsr->isEof = 1; + }else{ + do { + if( pCsr->isRequireSeek==0 ){ + sqlite3_reset(pCsr->pStmt); + } + assert( sqlite3_data_count(pCsr->pStmt)==0 ); + fts3EvalNextRow(pCsr, pExpr, &rc); + pCsr->isEof = pExpr->bEof; + pCsr->isRequireSeek = 1; + pCsr->isMatchinfoNeeded = 1; + pCsr->iPrevId = pExpr->iDocid; + }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) ); + } + + /* Check if the cursor is past the end of the docid range specified + ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */ + if( rc==SQLITE_OK && ( + (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid) + || (pCsr->bDesc!=0 && pCsr->iPrevIdiMinDocid) + )){ + pCsr->isEof = 1; + } + + return rc; +} + +/* +** Restart interation for expression pExpr so that the next call to +** fts3EvalNext() visits the first row. Do not allow incremental +** loading or merging of phrase doclists for this iteration. +** +** If *pRc is other than SQLITE_OK when this function is called, it is +** a no-op. If an error occurs within this function, *pRc is set to an +** SQLite error code before returning. +*/ +static void fts3EvalRestart( + Fts3Cursor *pCsr, + Fts3Expr *pExpr, + int *pRc +){ + if( pExpr && *pRc==SQLITE_OK ){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + + if( pPhrase ){ + fts3EvalInvalidatePoslist(pPhrase); + if( pPhrase->bIncr ){ + int i; + for(i=0; inToken; i++){ + Fts3PhraseToken *pToken = &pPhrase->aToken[i]; + assert( pToken->pDeferred==0 ); + if( pToken->pSegcsr ){ + sqlite3Fts3MsrIncrRestart(pToken->pSegcsr); + } + } + *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase); + } + pPhrase->doclist.pNextDocid = 0; + pPhrase->doclist.iDocid = 0; + } + + pExpr->iDocid = 0; + pExpr->bEof = 0; + pExpr->bStart = 0; + + fts3EvalRestart(pCsr, pExpr->pLeft, pRc); + fts3EvalRestart(pCsr, pExpr->pRight, pRc); + } +} + +/* +** After allocating the Fts3Expr.aMI[] array for each phrase in the +** expression rooted at pExpr, the cursor iterates through all rows matched +** by pExpr, calling this function for each row. This function increments +** the values in Fts3Expr.aMI[] according to the position-list currently +** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase +** expression nodes. +*/ +static void fts3EvalUpdateCounts(Fts3Expr *pExpr){ + if( pExpr ){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + if( pPhrase && pPhrase->doclist.pList ){ + int iCol = 0; + char *p = pPhrase->doclist.pList; + + assert( *p ); + while( 1 ){ + u8 c = 0; + int iCnt = 0; + while( 0xFE & (*p | c) ){ + if( (c&0x80)==0 ) iCnt++; + c = *p++ & 0x80; + } + + /* aMI[iCol*3 + 1] = Number of occurrences + ** aMI[iCol*3 + 2] = Number of rows containing at least one instance + */ + pExpr->aMI[iCol*3 + 1] += iCnt; + pExpr->aMI[iCol*3 + 2] += (iCnt>0); + if( *p==0x00 ) break; + p++; + p += sqlite3Fts3GetVarint32(p, &iCol); + } + } + + fts3EvalUpdateCounts(pExpr->pLeft); + fts3EvalUpdateCounts(pExpr->pRight); + } +} + +/* +** Expression pExpr must be of type FTSQUERY_PHRASE. +** +** If it is not already allocated and populated, this function allocates and +** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part +** of a NEAR expression, then it also allocates and populates the same array +** for all other phrases that are part of the NEAR expression. +** +** SQLITE_OK is returned if the aMI[] array is successfully allocated and +** populated. Otherwise, if an error occurs, an SQLite error code is returned. +*/ +static int fts3EvalGatherStats( + Fts3Cursor *pCsr, /* Cursor object */ + Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */ +){ + int rc = SQLITE_OK; /* Return code */ + + assert( pExpr->eType==FTSQUERY_PHRASE ); + if( pExpr->aMI==0 ){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + Fts3Expr *pRoot; /* Root of NEAR expression */ + Fts3Expr *p; /* Iterator used for several purposes */ + + sqlite3_int64 iPrevId = pCsr->iPrevId; + sqlite3_int64 iDocid; + u8 bEof; + + /* Find the root of the NEAR expression */ + pRoot = pExpr; + while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){ + pRoot = pRoot->pParent; + } + iDocid = pRoot->iDocid; + bEof = pRoot->bEof; + assert( pRoot->bStart ); + + /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */ + for(p=pRoot; p; p=p->pLeft){ + Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight); + assert( pE->aMI==0 ); + pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32)); + if( !pE->aMI ) return SQLITE_NOMEM; + memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32)); + } + + fts3EvalRestart(pCsr, pRoot, &rc); + + while( pCsr->isEof==0 && rc==SQLITE_OK ){ + + do { + /* Ensure the %_content statement is reset. */ + if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt); + assert( sqlite3_data_count(pCsr->pStmt)==0 ); + + /* Advance to the next document */ + fts3EvalNextRow(pCsr, pRoot, &rc); + pCsr->isEof = pRoot->bEof; + pCsr->isRequireSeek = 1; + pCsr->isMatchinfoNeeded = 1; + pCsr->iPrevId = pRoot->iDocid; + }while( pCsr->isEof==0 + && pRoot->eType==FTSQUERY_NEAR + && fts3EvalTestDeferredAndNear(pCsr, &rc) + ); + + if( rc==SQLITE_OK && pCsr->isEof==0 ){ + fts3EvalUpdateCounts(pRoot); + } + } + + pCsr->isEof = 0; + pCsr->iPrevId = iPrevId; + + if( bEof ){ + pRoot->bEof = bEof; + }else{ + /* Caution: pRoot may iterate through docids in ascending or descending + ** order. For this reason, even though it seems more defensive, the + ** do loop can not be written: + ** + ** do {...} while( pRoot->iDocidbEof==0 ); + }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK ); + fts3EvalTestDeferredAndNear(pCsr, &rc); + } + } + return rc; +} + +/* +** This function is used by the matchinfo() module to query a phrase +** expression node for the following information: +** +** 1. The total number of occurrences of the phrase in each column of +** the FTS table (considering all rows), and +** +** 2. For each column, the number of rows in the table for which the +** column contains at least one instance of the phrase. +** +** If no error occurs, SQLITE_OK is returned and the values for each column +** written into the array aiOut as follows: +** +** aiOut[iCol*3 + 1] = Number of occurrences +** aiOut[iCol*3 + 2] = Number of rows containing at least one instance +** +** Caveats: +** +** * If a phrase consists entirely of deferred tokens, then all output +** values are set to the number of documents in the table. In other +** words we assume that very common tokens occur exactly once in each +** column of each row of the table. +** +** * If a phrase contains some deferred tokens (and some non-deferred +** tokens), count the potential occurrence identified by considering +** the non-deferred tokens instead of actual phrase occurrences. +** +** * If the phrase is part of a NEAR expression, then only phrase instances +** that meet the NEAR constraint are included in the counts. +*/ +int sqlite3Fts3EvalPhraseStats( + Fts3Cursor *pCsr, /* FTS cursor handle */ + Fts3Expr *pExpr, /* Phrase expression */ + u32 *aiOut /* Array to write results into (see above) */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; + int iCol; + + if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){ + assert( pCsr->nDoc>0 ); + for(iCol=0; iColnColumn; iCol++){ + aiOut[iCol*3 + 1] = (u32)pCsr->nDoc; + aiOut[iCol*3 + 2] = (u32)pCsr->nDoc; + } + }else{ + rc = fts3EvalGatherStats(pCsr, pExpr); + if( rc==SQLITE_OK ){ + assert( pExpr->aMI ); + for(iCol=0; iColnColumn; iCol++){ + aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1]; + aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2]; + } + } + } + + return rc; +} + +/* +** The expression pExpr passed as the second argument to this function +** must be of type FTSQUERY_PHRASE. +** +** The returned value is either NULL or a pointer to a buffer containing +** a position-list indicating the occurrences of the phrase in column iCol +** of the current row. +** +** More specifically, the returned buffer contains 1 varint for each +** occurrence of the phrase in the column, stored using the normal (delta+2) +** compression and is terminated by either an 0x01 or 0x00 byte. For example, +** if the requested column contains "a b X c d X X" and the position-list +** for 'X' is requested, the buffer returned may contain: +** +** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00 +** +** This function works regardless of whether or not the phrase is deferred, +** incremental, or neither. +*/ +int sqlite3Fts3EvalPhrasePoslist( + Fts3Cursor *pCsr, /* FTS3 cursor object */ + Fts3Expr *pExpr, /* Phrase to return doclist for */ + int iCol, /* Column to return position list for */ + char **ppOut /* OUT: Pointer to position list */ +){ + Fts3Phrase *pPhrase = pExpr->pPhrase; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + char *pIter; + int iThis; + sqlite3_int64 iDocid; + + /* If this phrase is applies specifically to some column other than + ** column iCol, return a NULL pointer. */ + *ppOut = 0; + assert( iCol>=0 && iColnColumn ); + if( (pPhrase->iColumnnColumn && pPhrase->iColumn!=iCol) ){ + return SQLITE_OK; + } + + iDocid = pExpr->iDocid; + pIter = pPhrase->doclist.pList; + if( iDocid!=pCsr->iPrevId || pExpr->bEof ){ + int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */ + int iMul; /* +1 if csr dir matches index dir, else -1 */ + int bOr = 0; + u8 bEof = 0; + u8 bTreeEof = 0; + Fts3Expr *p; /* Used to iterate from pExpr to root */ + Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */ + + /* Check if this phrase descends from an OR expression node. If not, + ** return NULL. Otherwise, the entry that corresponds to docid + ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the + ** tree that the node is part of has been marked as EOF, but the node + ** itself is not EOF, then it may point to an earlier entry. */ + pNear = pExpr; + for(p=pExpr->pParent; p; p=p->pParent){ + if( p->eType==FTSQUERY_OR ) bOr = 1; + if( p->eType==FTSQUERY_NEAR ) pNear = p; + if( p->bEof ) bTreeEof = 1; + } + if( bOr==0 ) return SQLITE_OK; + + /* This is the descendent of an OR node. In this case we cannot use + ** an incremental phrase. Load the entire doclist for the phrase + ** into memory in this case. */ + if( pPhrase->bIncr ){ + int rc = SQLITE_OK; + int bEofSave = pExpr->bEof; + fts3EvalRestart(pCsr, pExpr, &rc); + while( rc==SQLITE_OK && !pExpr->bEof ){ + fts3EvalNextRow(pCsr, pExpr, &rc); + if( bEofSave==0 && pExpr->iDocid==iDocid ) break; + } + pIter = pPhrase->doclist.pList; + assert( rc!=SQLITE_OK || pPhrase->bIncr==0 ); + if( rc!=SQLITE_OK ) return rc; + } + + iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1); + while( bTreeEof==1 + && pNear->bEof==0 + && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0 + ){ + int rc = SQLITE_OK; + fts3EvalNextRow(pCsr, pExpr, &rc); + if( rc!=SQLITE_OK ) return rc; + iDocid = pExpr->iDocid; + pIter = pPhrase->doclist.pList; + } + + bEof = (pPhrase->doclist.nAll==0); + assert( bDescDoclist==0 || bDescDoclist==1 ); + assert( pCsr->bDesc==0 || pCsr->bDesc==1 ); + + if( bEof==0 ){ + if( pCsr->bDesc==bDescDoclist ){ + int dummy; + if( pNear->bEof ){ + /* This expression is already at EOF. So position it to point to the + ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable + ** iDocid is already set for this entry, so all that is required is + ** to set pIter to point to the first byte of the last position-list + ** in the doclist. + ** + ** It would also be correct to set pIter and iDocid to zero. In + ** this case, the first call to sqltie3Fts4DoclistPrev() below + ** would also move the iterator to point to the last entry in the + ** doclist. However, this is expensive, as to do so it has to + ** iterate through the entire doclist from start to finish (since + ** it does not know the docid for the last entry). */ + pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1]; + fts3ReversePoslist(pPhrase->doclist.aAll, &pIter); + } + while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){ + sqlite3Fts3DoclistPrev( + bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, + &pIter, &iDocid, &dummy, &bEof + ); + } + }else{ + if( pNear->bEof ){ + pIter = 0; + iDocid = 0; + } + while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){ + sqlite3Fts3DoclistNext( + bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, + &pIter, &iDocid, &bEof + ); + } + } + } + + if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0; + } + if( pIter==0 ) return SQLITE_OK; + + if( *pIter==0x01 ){ + pIter++; + pIter += sqlite3Fts3GetVarint32(pIter, &iThis); + }else{ + iThis = 0; + } + while( iThisdoclist, and +** * any Fts3MultiSegReader objects held by phrase tokens. +*/ +void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){ + if( pPhrase ){ + int i; + sqlite3_free(pPhrase->doclist.aAll); + fts3EvalInvalidatePoslist(pPhrase); + memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist)); + for(i=0; inToken; i++){ + fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr); + pPhrase->aToken[i].pSegcsr = 0; + } + } +} + + +/* +** Return SQLITE_CORRUPT_VTAB. +*/ +#ifdef SQLITE_DEBUG +int sqlite3Fts3Corrupt(){ + return SQLITE_CORRUPT_VTAB; +} +#endif + +#if !SQLITE_CORE +/* +** Initialize API pointer table, if required. +*/ +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_fts3_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi) + return sqlite3Fts3Init(db); +} +#endif + +#endif diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3.h b/components/external/SQLite-3.8.1/ext/fts3/fts3.h new file mode 100644 index 0000000000000000000000000000000000000000..c1aa8caf0927920d6bb78d578d9c111d4161a34a --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3.h @@ -0,0 +1,26 @@ +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file is used by programs that want to link against the +** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. +*/ +#include "sqlite3.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +int sqlite3Fts3Init(sqlite3 *db); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3Int.h b/components/external/SQLite-3.8.1/ext/fts3/fts3Int.h new file mode 100644 index 0000000000000000000000000000000000000000..6986acdec691d94090e944320f2d4404a8d90a23 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3Int.h @@ -0,0 +1,591 @@ +/* +** 2009 Nov 12 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +*/ +#ifndef _FTSINT_H +#define _FTSINT_H + +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif + +/* +** FTS4 is really an extension for FTS3. It is enabled using the +** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all +** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3. +*/ +#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) +# define SQLITE_ENABLE_FTS3 +#endif + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* If not building as part of the core, include sqlite3ext.h. */ +#ifndef SQLITE_CORE +# include "sqlite3ext.h" +SQLITE_EXTENSION_INIT3 +#endif + +#include "sqlite3.h" +#include "fts3_tokenizer.h" +#include "fts3_hash.h" + +/* +** This constant determines the maximum depth of an FTS expression tree +** that the library will create and use. FTS uses recursion to perform +** various operations on the query tree, so the disadvantage of a large +** limit is that it may allow very large queries to use large amounts +** of stack space (perhaps causing a stack overflow). +*/ +#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH +# define SQLITE_FTS3_MAX_EXPR_DEPTH 12 +#endif + + +/* +** This constant controls how often segments are merged. Once there are +** FTS3_MERGE_COUNT segments of level N, they are merged into a single +** segment of level N+1. +*/ +#define FTS3_MERGE_COUNT 16 + +/* +** This is the maximum amount of data (in bytes) to store in the +** Fts3Table.pendingTerms hash table. Normally, the hash table is +** populated as documents are inserted/updated/deleted in a transaction +** and used to create a new segment when the transaction is committed. +** However if this limit is reached midway through a transaction, a new +** segment is created and the hash table cleared immediately. +*/ +#define FTS3_MAX_PENDING_DATA (1*1024*1024) + +/* +** Macro to return the number of elements in an array. SQLite has a +** similar macro called ArraySize(). Use a different name to avoid +** a collision when building an amalgamation with built-in FTS3. +*/ +#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0]))) + + +#ifndef MIN +# define MIN(x,y) ((x)<(y)?(x):(y)) +#endif +#ifndef MAX +# define MAX(x,y) ((x)>(y)?(x):(y)) +#endif + +/* +** Maximum length of a varint encoded integer. The varint format is different +** from that used by SQLite, so the maximum length is 10, not 9. +*/ +#define FTS3_VARINT_MAX 10 + +/* +** FTS4 virtual tables may maintain multiple indexes - one index of all terms +** in the document set and zero or more prefix indexes. All indexes are stored +** as one or more b+-trees in the %_segments and %_segdir tables. +** +** It is possible to determine which index a b+-tree belongs to based on the +** value stored in the "%_segdir.level" column. Given this value L, the index +** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with +** level values between 0 and 1023 (inclusive) belong to index 0, all levels +** between 1024 and 2047 to index 1, and so on. +** +** It is considered impossible for an index to use more than 1024 levels. In +** theory though this may happen, but only after at least +** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables. +*/ +#define FTS3_SEGDIR_MAXLEVEL 1024 +#define FTS3_SEGDIR_MAXLEVEL_STR "1024" + +/* +** The testcase() macro is only used by the amalgamation. If undefined, +** make it a no-op. +*/ +#ifndef testcase +# define testcase(X) +#endif + +/* +** Terminator values for position-lists and column-lists. +*/ +#define POS_COLUMN (1) /* Column-list terminator */ +#define POS_END (0) /* Position-list terminator */ + +/* +** This section provides definitions to allow the +** FTS3 extension to be compiled outside of the +** amalgamation. +*/ +#ifndef SQLITE_AMALGAMATION +/* +** Macros indicating that conditional expressions are always true or +** false. +*/ +#ifdef SQLITE_COVERAGE_TEST +# define ALWAYS(x) (1) +# define NEVER(X) (0) +#else +# define ALWAYS(x) (x) +# define NEVER(x) (x) +#endif + +/* +** Internal types used by SQLite. +*/ +typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */ +typedef short int i16; /* 2-byte (or larger) signed integer */ +typedef unsigned int u32; /* 4-byte unsigned integer */ +typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */ +typedef sqlite3_int64 i64; /* 8-byte signed integer */ + +/* +** Macro used to suppress compiler warnings for unused parameters. +*/ +#define UNUSED_PARAMETER(x) (void)(x) + +/* +** Activate assert() only if SQLITE_TEST is enabled. +*/ +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif + +/* +** The TESTONLY macro is used to enclose variable declarations or +** other bits of code that are needed to support the arguments +** within testcase() and assert() macros. +*/ +#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) +# define TESTONLY(X) X +#else +# define TESTONLY(X) +#endif + +#endif /* SQLITE_AMALGAMATION */ + +#ifdef SQLITE_DEBUG +int sqlite3Fts3Corrupt(void); +# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt() +#else +# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB +#endif + +typedef struct Fts3Table Fts3Table; +typedef struct Fts3Cursor Fts3Cursor; +typedef struct Fts3Expr Fts3Expr; +typedef struct Fts3Phrase Fts3Phrase; +typedef struct Fts3PhraseToken Fts3PhraseToken; + +typedef struct Fts3Doclist Fts3Doclist; +typedef struct Fts3SegFilter Fts3SegFilter; +typedef struct Fts3DeferredToken Fts3DeferredToken; +typedef struct Fts3SegReader Fts3SegReader; +typedef struct Fts3MultiSegReader Fts3MultiSegReader; + +/* +** A connection to a fulltext index is an instance of the following +** structure. The xCreate and xConnect methods create an instance +** of this structure and xDestroy and xDisconnect free that instance. +** All other methods receive a pointer to the structure as one of their +** arguments. +*/ +struct Fts3Table { + sqlite3_vtab base; /* Base class used by SQLite core */ + sqlite3 *db; /* The database connection */ + const char *zDb; /* logical database name */ + const char *zName; /* virtual table name */ + int nColumn; /* number of named columns in virtual table */ + char **azColumn; /* column names. malloced */ + u8 *abNotindexed; /* True for 'notindexed' columns */ + sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ + char *zContentTbl; /* content=xxx option, or NULL */ + char *zLanguageid; /* languageid=xxx option, or NULL */ + u8 bAutoincrmerge; /* True if automerge=1 */ + u32 nLeafAdd; /* Number of leaf blocks added this trans */ + + /* Precompiled statements used by the implementation. Each of these + ** statements is run and reset within a single virtual table API call. + */ + sqlite3_stmt *aStmt[37]; + + char *zReadExprlist; + char *zWriteExprlist; + + int nNodeSize; /* Soft limit for node size */ + u8 bFts4; /* True for FTS4, false for FTS3 */ + u8 bHasStat; /* True if %_stat table exists */ + u8 bHasDocsize; /* True if %_docsize table exists */ + u8 bDescIdx; /* True if doclists are in reverse order */ + u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */ + int nPgsz; /* Page size for host database */ + char *zSegmentsTbl; /* Name of %_segments table */ + sqlite3_blob *pSegments; /* Blob handle open on %_segments table */ + + /* + ** The following array of hash tables is used to buffer pending index + ** updates during transactions. All pending updates buffered at any one + ** time must share a common language-id (see the FTS4 langid= feature). + ** The current language id is stored in variable iPrevLangid. + ** + ** A single FTS4 table may have multiple full-text indexes. For each index + ** there is an entry in the aIndex[] array. Index 0 is an index of all the + ** terms that appear in the document set. Each subsequent index in aIndex[] + ** is an index of prefixes of a specific length. + ** + ** Variable nPendingData contains an estimate the memory consumed by the + ** pending data structures, including hash table overhead, but not including + ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash + ** tables are flushed to disk. Variable iPrevDocid is the docid of the most + ** recently inserted record. + */ + int nIndex; /* Size of aIndex[] */ + struct Fts3Index { + int nPrefix; /* Prefix length (0 for main terms index) */ + Fts3Hash hPending; /* Pending terms table for this index */ + } *aIndex; + int nMaxPendingData; /* Max pending data before flush to disk */ + int nPendingData; /* Current bytes of pending data */ + sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */ + int iPrevLangid; /* Langid of recently inserted document */ + +#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) + /* State variables used for validating that the transaction control + ** methods of the virtual table are called at appropriate times. These + ** values do not contribute to FTS functionality; they are used for + ** verifying the operation of the SQLite core. + */ + int inTransaction; /* True after xBegin but before xCommit/xRollback */ + int mxSavepoint; /* Largest valid xSavepoint integer */ +#endif + +#ifdef SQLITE_TEST + /* True to disable the incremental doclist optimization. This is controled + ** by special insert command 'test-no-incr-doclist'. */ + int bNoIncrDoclist; +#endif +}; + +/* +** When the core wants to read from the virtual table, it creates a +** virtual table cursor (an instance of the following structure) using +** the xOpen method. Cursors are destroyed using the xClose method. +*/ +struct Fts3Cursor { + sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + i16 eSearch; /* Search strategy (see below) */ + u8 isEof; /* True if at End Of Results */ + u8 isRequireSeek; /* True if must seek pStmt to %_content row */ + sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ + Fts3Expr *pExpr; /* Parsed MATCH query string */ + int iLangid; /* Language being queried for */ + int nPhrase; /* Number of matchable phrases in query */ + Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */ + sqlite3_int64 iPrevId; /* Previous id read from aDoclist */ + char *pNextId; /* Pointer into the body of aDoclist */ + char *aDoclist; /* List of docids for full-text queries */ + int nDoclist; /* Size of buffer at aDoclist */ + u8 bDesc; /* True to sort in descending order */ + int eEvalmode; /* An FTS3_EVAL_XX constant */ + int nRowAvg; /* Average size of database rows, in pages */ + sqlite3_int64 nDoc; /* Documents in table */ + i64 iMinDocid; /* Minimum docid to return */ + i64 iMaxDocid; /* Maximum docid to return */ + int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */ + u32 *aMatchinfo; /* Information about most recent match */ + int nMatchinfo; /* Number of elements in aMatchinfo[] */ + char *zMatchinfo; /* Matchinfo specification */ +}; + +#define FTS3_EVAL_FILTER 0 +#define FTS3_EVAL_NEXT 1 +#define FTS3_EVAL_MATCHINFO 2 + +/* +** The Fts3Cursor.eSearch member is always set to one of the following. +** Actualy, Fts3Cursor.eSearch can be greater than or equal to +** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index +** of the column to be searched. For example, in +** +** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d); +** SELECT docid FROM ex1 WHERE b MATCH 'one two three'; +** +** Because the LHS of the MATCH operator is 2nd column "b", +** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a, +** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1" +** indicating that all columns should be searched, +** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4. +*/ +#define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */ +#define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */ +#define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */ + +/* +** The lower 16-bits of the sqlite3_index_info.idxNum value set by +** the xBestIndex() method contains the Fts3Cursor.eSearch value described +** above. The upper 16-bits contain a combination of the following +** bits, used to describe extra constraints on full-text searches. +*/ +#define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */ +#define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */ +#define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */ + +struct Fts3Doclist { + char *aAll; /* Array containing doclist (or NULL) */ + int nAll; /* Size of a[] in bytes */ + char *pNextDocid; /* Pointer to next docid */ + + sqlite3_int64 iDocid; /* Current docid (if pList!=0) */ + int bFreeList; /* True if pList should be sqlite3_free()d */ + char *pList; /* Pointer to position list following iDocid */ + int nList; /* Length of position list */ +}; + +/* +** A "phrase" is a sequence of one or more tokens that must match in +** sequence. A single token is the base case and the most common case. +** For a sequence of tokens contained in double-quotes (i.e. "one two three") +** nToken will be the number of tokens in the string. +*/ +struct Fts3PhraseToken { + char *z; /* Text of the token */ + int n; /* Number of bytes in buffer z */ + int isPrefix; /* True if token ends with a "*" character */ + int bFirst; /* True if token must appear at position 0 */ + + /* Variables above this point are populated when the expression is + ** parsed (by code in fts3_expr.c). Below this point the variables are + ** used when evaluating the expression. */ + Fts3DeferredToken *pDeferred; /* Deferred token object for this token */ + Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */ +}; + +struct Fts3Phrase { + /* Cache of doclist for this phrase. */ + Fts3Doclist doclist; + int bIncr; /* True if doclist is loaded incrementally */ + int iDoclistToken; + + /* Variables below this point are populated by fts3_expr.c when parsing + ** a MATCH expression. Everything above is part of the evaluation phase. + */ + int nToken; /* Number of tokens in the phrase */ + int iColumn; /* Index of column this phrase must match */ + Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */ +}; + +/* +** A tree of these objects forms the RHS of a MATCH operator. +** +** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist +** points to a malloced buffer, size nDoclist bytes, containing the results +** of this phrase query in FTS3 doclist format. As usual, the initial +** "Length" field found in doclists stored on disk is omitted from this +** buffer. +** +** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global +** matchinfo data. If it is not NULL, it points to an array of size nCol*3, +** where nCol is the number of columns in the queried FTS table. The array +** is populated as follows: +** +** aMI[iCol*3 + 0] = Undefined +** aMI[iCol*3 + 1] = Number of occurrences +** aMI[iCol*3 + 2] = Number of rows containing at least one instance +** +** The aMI array is allocated using sqlite3_malloc(). It should be freed +** when the expression node is. +*/ +struct Fts3Expr { + int eType; /* One of the FTSQUERY_XXX values defined below */ + int nNear; /* Valid if eType==FTSQUERY_NEAR */ + Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */ + Fts3Expr *pLeft; /* Left operand */ + Fts3Expr *pRight; /* Right operand */ + Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */ + + /* The following are used by the fts3_eval.c module. */ + sqlite3_int64 iDocid; /* Current docid */ + u8 bEof; /* True this expression is at EOF already */ + u8 bStart; /* True if iDocid is valid */ + u8 bDeferred; /* True if this expression is entirely deferred */ + + u32 *aMI; +}; + +/* +** Candidate values for Fts3Query.eType. Note that the order of the first +** four values is in order of precedence when parsing expressions. For +** example, the following: +** +** "a OR b AND c NOT d NEAR e" +** +** is equivalent to: +** +** "a OR (b AND (c NOT (d NEAR e)))" +*/ +#define FTSQUERY_NEAR 1 +#define FTSQUERY_NOT 2 +#define FTSQUERY_AND 3 +#define FTSQUERY_OR 4 +#define FTSQUERY_PHRASE 5 + + +/* fts3_write.c */ +int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*); +int sqlite3Fts3PendingTermsFlush(Fts3Table *); +void sqlite3Fts3PendingTermsClear(Fts3Table *); +int sqlite3Fts3Optimize(Fts3Table *); +int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64, + sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**); +int sqlite3Fts3SegReaderPending( + Fts3Table*,int,const char*,int,int,Fts3SegReader**); +void sqlite3Fts3SegReaderFree(Fts3SegReader *); +int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **); +int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*); + +int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **); +int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **); + +#ifndef SQLITE_DISABLE_FTS4_DEFERRED +void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *); +int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int); +int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *); +void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *); +int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *); +#else +# define sqlite3Fts3FreeDeferredTokens(x) +# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK +# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK +# define sqlite3Fts3FreeDeferredDoclists(x) +# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK +#endif + +void sqlite3Fts3SegmentsClose(Fts3Table *); +int sqlite3Fts3MaxLevel(Fts3Table *, int *); + +/* Special values interpreted by sqlite3SegReaderCursor() */ +#define FTS3_SEGCURSOR_PENDING -1 +#define FTS3_SEGCURSOR_ALL -2 + +int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*); +int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *); +void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *); + +int sqlite3Fts3SegReaderCursor(Fts3Table *, + int, int, int, const char *, int, int, int, Fts3MultiSegReader *); + +/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */ +#define FTS3_SEGMENT_REQUIRE_POS 0x00000001 +#define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002 +#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004 +#define FTS3_SEGMENT_PREFIX 0x00000008 +#define FTS3_SEGMENT_SCAN 0x00000010 +#define FTS3_SEGMENT_FIRST 0x00000020 + +/* Type passed as 4th argument to SegmentReaderIterate() */ +struct Fts3SegFilter { + const char *zTerm; + int nTerm; + int iCol; + int flags; +}; + +struct Fts3MultiSegReader { + /* Used internally by sqlite3Fts3SegReaderXXX() calls */ + Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */ + int nSegment; /* Size of apSegment array */ + int nAdvance; /* How many seg-readers to advance */ + Fts3SegFilter *pFilter; /* Pointer to filter object */ + char *aBuffer; /* Buffer to merge doclists in */ + int nBuffer; /* Allocated size of aBuffer[] in bytes */ + + int iColFilter; /* If >=0, filter for this column */ + int bRestart; + + /* Used by fts3.c only. */ + int nCost; /* Cost of running iterator */ + int bLookup; /* True if a lookup of a single entry. */ + + /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */ + char *zTerm; /* Pointer to term buffer */ + int nTerm; /* Size of zTerm in bytes */ + char *aDoclist; /* Pointer to doclist buffer */ + int nDoclist; /* Size of aDoclist[] in bytes */ +}; + +int sqlite3Fts3Incrmerge(Fts3Table*,int,int); + +/* fts3.c */ +int sqlite3Fts3PutVarint(char *, sqlite3_int64); +int sqlite3Fts3GetVarint(const char *, sqlite_int64 *); +int sqlite3Fts3GetVarint32(const char *, int *); +int sqlite3Fts3VarintLen(sqlite3_uint64); +void sqlite3Fts3Dequote(char *); +void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*); +int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *); +int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *); +void sqlite3Fts3CreateStatTable(int*, Fts3Table*); + +/* fts3_tokenizer.c */ +const char *sqlite3Fts3NextToken(const char *, int *); +int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *); +int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, + sqlite3_tokenizer **, char ** +); +int sqlite3Fts3IsIdChar(char); + +/* fts3_snippet.c */ +void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*); +void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *, + const char *, const char *, int, int +); +void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *); + +/* fts3_expr.c */ +int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int, + char **, int, int, int, const char *, int, Fts3Expr **, char ** +); +void sqlite3Fts3ExprFree(Fts3Expr *); +#ifdef SQLITE_TEST +int sqlite3Fts3ExprInitTestInterface(sqlite3 *db); +int sqlite3Fts3InitTerm(sqlite3 *db); +#endif + +int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int, + sqlite3_tokenizer_cursor ** +); + +/* fts3_aux.c */ +int sqlite3Fts3InitAux(sqlite3 *db); + +void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *); + +int sqlite3Fts3MsrIncrStart( + Fts3Table*, Fts3MultiSegReader*, int, const char*, int); +int sqlite3Fts3MsrIncrNext( + Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *); +int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); +int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *); +int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr); + +/* fts3_tokenize_vtab.c */ +int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *); + +/* fts3_unicode2.c (functions generated by parsing unicode text files) */ +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 +int sqlite3FtsUnicodeFold(int, int); +int sqlite3FtsUnicodeIsalnum(int); +int sqlite3FtsUnicodeIsdiacritic(int); +#endif + +#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */ +#endif /* _FTSINT_H */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_aux.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_aux.c new file mode 100644 index 0000000000000000000000000000000000000000..c68b1a9d9be93f40b6ff81a0dddc0bfe7e0d4cfe --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_aux.c @@ -0,0 +1,550 @@ +/* +** 2011 Jan 27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +*/ +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#include +#include + +typedef struct Fts3auxTable Fts3auxTable; +typedef struct Fts3auxCursor Fts3auxCursor; + +struct Fts3auxTable { + sqlite3_vtab base; /* Base class used by SQLite core */ + Fts3Table *pFts3Tab; +}; + +struct Fts3auxCursor { + sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + Fts3MultiSegReader csr; /* Must be right after "base" */ + Fts3SegFilter filter; + char *zStop; + int nStop; /* Byte-length of string zStop */ + int iLangid; /* Language id to query */ + int isEof; /* True if cursor is at EOF */ + sqlite3_int64 iRowid; /* Current rowid */ + + int iCol; /* Current value of 'col' column */ + int nStat; /* Size of aStat[] array */ + struct Fts3auxColstats { + sqlite3_int64 nDoc; /* 'documents' values for current csr row */ + sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */ + } *aStat; +}; + +/* +** Schema of the terms table. +*/ +#define FTS3_AUX_SCHEMA \ + "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)" + +/* +** This function does all the work for both the xConnect and xCreate methods. +** These tables have no persistent representation of their own, so xConnect +** and xCreate are identical operations. +*/ +static int fts3auxConnectMethod( + sqlite3 *db, /* Database connection */ + void *pUnused, /* Unused */ + int argc, /* Number of elements in argv array */ + const char * const *argv, /* xCreate/xConnect argument array */ + sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ + char **pzErr /* OUT: sqlite3_malloc'd error message */ +){ + char const *zDb; /* Name of database (e.g. "main") */ + char const *zFts3; /* Name of fts3 table */ + int nDb; /* Result of strlen(zDb) */ + int nFts3; /* Result of strlen(zFts3) */ + int nByte; /* Bytes of space to allocate here */ + int rc; /* value returned by declare_vtab() */ + Fts3auxTable *p; /* Virtual table object to return */ + + UNUSED_PARAMETER(pUnused); + + /* The user should invoke this in one of two forms: + ** + ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table); + ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table); + */ + if( argc!=4 && argc!=5 ) goto bad_args; + + zDb = argv[1]; + nDb = (int)strlen(zDb); + if( argc==5 ){ + if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){ + zDb = argv[3]; + nDb = (int)strlen(zDb); + zFts3 = argv[4]; + }else{ + goto bad_args; + } + }else{ + zFts3 = argv[3]; + } + nFts3 = (int)strlen(zFts3); + + rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA); + if( rc!=SQLITE_OK ) return rc; + + nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2; + p = (Fts3auxTable *)sqlite3_malloc(nByte); + if( !p ) return SQLITE_NOMEM; + memset(p, 0, nByte); + + p->pFts3Tab = (Fts3Table *)&p[1]; + p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1]; + p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1]; + p->pFts3Tab->db = db; + p->pFts3Tab->nIndex = 1; + + memcpy((char *)p->pFts3Tab->zDb, zDb, nDb); + memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3); + sqlite3Fts3Dequote((char *)p->pFts3Tab->zName); + + *ppVtab = (sqlite3_vtab *)p; + return SQLITE_OK; + + bad_args: + *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor"); + return SQLITE_ERROR; +} + +/* +** This function does the work for both the xDisconnect and xDestroy methods. +** These tables have no persistent representation of their own, so xDisconnect +** and xDestroy are identical operations. +*/ +static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){ + Fts3auxTable *p = (Fts3auxTable *)pVtab; + Fts3Table *pFts3 = p->pFts3Tab; + int i; + + /* Free any prepared statements held */ + for(i=0; iaStmt); i++){ + sqlite3_finalize(pFts3->aStmt[i]); + } + sqlite3_free(pFts3->zSegmentsTbl); + sqlite3_free(p); + return SQLITE_OK; +} + +#define FTS4AUX_EQ_CONSTRAINT 1 +#define FTS4AUX_GE_CONSTRAINT 2 +#define FTS4AUX_LE_CONSTRAINT 4 + +/* +** xBestIndex - Analyze a WHERE and ORDER BY clause. +*/ +static int fts3auxBestIndexMethod( + sqlite3_vtab *pVTab, + sqlite3_index_info *pInfo +){ + int i; + int iEq = -1; + int iGe = -1; + int iLe = -1; + int iLangid = -1; + int iNext = 1; /* Next free argvIndex value */ + + UNUSED_PARAMETER(pVTab); + + /* This vtab delivers always results in "ORDER BY term ASC" order. */ + if( pInfo->nOrderBy==1 + && pInfo->aOrderBy[0].iColumn==0 + && pInfo->aOrderBy[0].desc==0 + ){ + pInfo->orderByConsumed = 1; + } + + /* Search for equality and range constraints on the "term" column. + ** And equality constraints on the hidden "languageid" column. */ + for(i=0; inConstraint; i++){ + if( pInfo->aConstraint[i].usable ){ + int op = pInfo->aConstraint[i].op; + int iCol = pInfo->aConstraint[i].iColumn; + + if( iCol==0 ){ + if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i; + if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i; + if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i; + if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i; + if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i; + } + if( iCol==4 ){ + if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i; + } + } + } + + if( iEq>=0 ){ + pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT; + pInfo->aConstraintUsage[iEq].argvIndex = iNext++; + pInfo->estimatedCost = 5; + }else{ + pInfo->idxNum = 0; + pInfo->estimatedCost = 20000; + if( iGe>=0 ){ + pInfo->idxNum += FTS4AUX_GE_CONSTRAINT; + pInfo->aConstraintUsage[iGe].argvIndex = iNext++; + pInfo->estimatedCost /= 2; + } + if( iLe>=0 ){ + pInfo->idxNum += FTS4AUX_LE_CONSTRAINT; + pInfo->aConstraintUsage[iLe].argvIndex = iNext++; + pInfo->estimatedCost /= 2; + } + } + if( iLangid>=0 ){ + pInfo->aConstraintUsage[iLangid].argvIndex = iNext++; + pInfo->estimatedCost--; + } + + return SQLITE_OK; +} + +/* +** xOpen - Open a cursor. +*/ +static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ + Fts3auxCursor *pCsr; /* Pointer to cursor object to return */ + + UNUSED_PARAMETER(pVTab); + + pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor)); + if( !pCsr ) return SQLITE_NOMEM; + memset(pCsr, 0, sizeof(Fts3auxCursor)); + + *ppCsr = (sqlite3_vtab_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** xClose - Close a cursor. +*/ +static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){ + Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + + sqlite3Fts3SegmentsClose(pFts3); + sqlite3Fts3SegReaderFinish(&pCsr->csr); + sqlite3_free((void *)pCsr->filter.zTerm); + sqlite3_free(pCsr->zStop); + sqlite3_free(pCsr->aStat); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){ + if( nSize>pCsr->nStat ){ + struct Fts3auxColstats *aNew; + aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, + sizeof(struct Fts3auxColstats) * nSize + ); + if( aNew==0 ) return SQLITE_NOMEM; + memset(&aNew[pCsr->nStat], 0, + sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat) + ); + pCsr->aStat = aNew; + pCsr->nStat = nSize; + } + return SQLITE_OK; +} + +/* +** xNext - Advance the cursor to the next row, if any. +*/ +static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; + int rc; + + /* Increment our pretend rowid value. */ + pCsr->iRowid++; + + for(pCsr->iCol++; pCsr->iColnStat; pCsr->iCol++){ + if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK; + } + + rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr); + if( rc==SQLITE_ROW ){ + int i = 0; + int nDoclist = pCsr->csr.nDoclist; + char *aDoclist = pCsr->csr.aDoclist; + int iCol; + + int eState = 0; + + if( pCsr->zStop ){ + int n = (pCsr->nStopcsr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm; + int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n); + if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){ + pCsr->isEof = 1; + return SQLITE_OK; + } + } + + if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM; + memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat); + iCol = 0; + + while( iaStat[0].nDoc++; + eState = 1; + iCol = 0; + break; + + /* State 1. In this state we are expecting either a 1, indicating + ** that the following integer will be a column number, or the + ** start of a position list for column 0. + ** + ** The only difference between state 1 and state 2 is that if the + ** integer encountered in state 1 is not 0 or 1, then we need to + ** increment the column 0 "nDoc" count for this term. + */ + case 1: + assert( iCol==0 ); + if( v>1 ){ + pCsr->aStat[1].nDoc++; + } + eState = 2; + /* fall through */ + + case 2: + if( v==0 ){ /* 0x00. Next integer will be a docid. */ + eState = 0; + }else if( v==1 ){ /* 0x01. Next integer will be a column number. */ + eState = 3; + }else{ /* 2 or greater. A position. */ + pCsr->aStat[iCol+1].nOcc++; + pCsr->aStat[0].nOcc++; + } + break; + + /* State 3. The integer just read is a column number. */ + default: assert( eState==3 ); + iCol = (int)v; + if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM; + pCsr->aStat[iCol+1].nDoc++; + eState = 2; + break; + } + } + + pCsr->iCol = 0; + rc = SQLITE_OK; + }else{ + pCsr->isEof = 1; + } + return rc; +} + +/* +** xFilter - Initialize a cursor to point at the start of its data. +*/ +static int fts3auxFilterMethod( + sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + int idxNum, /* Strategy index */ + const char *idxStr, /* Unused */ + int nVal, /* Number of elements in apVal */ + sqlite3_value **apVal /* Arguments for the indexing scheme */ +){ + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; + int rc; + int isScan = 0; + int iLangVal = 0; /* Language id to query */ + + int iEq = -1; /* Index of term=? value in apVal */ + int iGe = -1; /* Index of term>=? value in apVal */ + int iLe = -1; /* Index of term<=? value in apVal */ + int iLangid = -1; /* Index of languageid=? value in apVal */ + int iNext = 0; + + UNUSED_PARAMETER(nVal); + UNUSED_PARAMETER(idxStr); + + assert( idxStr==0 ); + assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0 + || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT + || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) + ); + + if( idxNum==FTS4AUX_EQ_CONSTRAINT ){ + iEq = iNext++; + }else{ + isScan = 1; + if( idxNum & FTS4AUX_GE_CONSTRAINT ){ + iGe = iNext++; + } + if( idxNum & FTS4AUX_LE_CONSTRAINT ){ + iLe = iNext++; + } + } + if( iNextfilter.zTerm); + sqlite3Fts3SegReaderFinish(&pCsr->csr); + sqlite3_free((void *)pCsr->filter.zTerm); + sqlite3_free(pCsr->aStat); + memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr); + + pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; + if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN; + + if( iEq>=0 || iGe>=0 ){ + const unsigned char *zStr = sqlite3_value_text(apVal[0]); + assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) ); + if( zStr ){ + pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr); + pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]); + if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM; + } + } + + if( iLe>=0 ){ + pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe])); + pCsr->nStop = sqlite3_value_bytes(apVal[iLe]); + if( pCsr->zStop==0 ) return SQLITE_NOMEM; + } + + if( iLangid>=0 ){ + iLangVal = sqlite3_value_int(apVal[iLangid]); + + /* If the user specified a negative value for the languageid, use zero + ** instead. This works, as the "languageid=?" constraint will also + ** be tested by the VDBE layer. The test will always be false (since + ** this module will not return a row with a negative languageid), and + ** so the overall query will return zero rows. */ + if( iLangVal<0 ) iLangVal = 0; + } + pCsr->iLangid = iLangVal; + + rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL, + pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr + ); + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter); + } + + if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor); + return rc; +} + +/* +** xEof - Return true if the cursor is at EOF, or false otherwise. +*/ +static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){ + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + return pCsr->isEof; +} + +/* +** xColumn - Return a column value. +*/ +static int fts3auxColumnMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + int iCol /* Index of column to read value from */ +){ + Fts3auxCursor *p = (Fts3auxCursor *)pCursor; + + assert( p->isEof==0 ); + switch( iCol ){ + case 0: /* term */ + sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT); + break; + + case 1: /* col */ + if( p->iCol ){ + sqlite3_result_int(pCtx, p->iCol-1); + }else{ + sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC); + } + break; + + case 2: /* documents */ + sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc); + break; + + case 3: /* occurrences */ + sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc); + break; + + default: /* languageid */ + assert( iCol==4 ); + sqlite3_result_int(pCtx, p->iLangid); + break; + } + + return SQLITE_OK; +} + +/* +** xRowid - Return the current rowid for the cursor. +*/ +static int fts3auxRowidMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite_int64 *pRowid /* OUT: Rowid value */ +){ + Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; + *pRowid = pCsr->iRowid; + return SQLITE_OK; +} + +/* +** Register the fts3aux module with database connection db. Return SQLITE_OK +** if successful or an error code if sqlite3_create_module() fails. +*/ +int sqlite3Fts3InitAux(sqlite3 *db){ + static const sqlite3_module fts3aux_module = { + 0, /* iVersion */ + fts3auxConnectMethod, /* xCreate */ + fts3auxConnectMethod, /* xConnect */ + fts3auxBestIndexMethod, /* xBestIndex */ + fts3auxDisconnectMethod, /* xDisconnect */ + fts3auxDisconnectMethod, /* xDestroy */ + fts3auxOpenMethod, /* xOpen */ + fts3auxCloseMethod, /* xClose */ + fts3auxFilterMethod, /* xFilter */ + fts3auxNextMethod, /* xNext */ + fts3auxEofMethod, /* xEof */ + fts3auxColumnMethod, /* xColumn */ + fts3auxRowidMethod, /* xRowid */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindFunction */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0 /* xRollbackTo */ + }; + int rc; /* Return code */ + + rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0); + return rc; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_expr.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_expr.c new file mode 100644 index 0000000000000000000000000000000000000000..29fb2887dab3a3cde63004b1eb6efee7fe839a02 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_expr.c @@ -0,0 +1,1278 @@ +/* +** 2008 Nov 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This module contains code that implements a parser for fts3 query strings +** (the right-hand argument to the MATCH operator). Because the supported +** syntax is relatively simple, the whole tokenizer/parser system is +** hand-coded. +*/ +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +/* +** By default, this module parses the legacy syntax that has been +** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS +** is defined, then it uses the new syntax. The differences between +** the new and the old syntaxes are: +** +** a) The new syntax supports parenthesis. The old does not. +** +** b) The new syntax supports the AND and NOT operators. The old does not. +** +** c) The old syntax supports the "-" token qualifier. This is not +** supported by the new syntax (it is replaced by the NOT operator). +** +** d) When using the old syntax, the OR operator has a greater precedence +** than an implicit AND. When using the new, both implicity and explicit +** AND operators have a higher precedence than OR. +** +** If compiled with SQLITE_TEST defined, then this module exports the +** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable +** to zero causes the module to use the old syntax. If it is set to +** non-zero the new syntax is activated. This is so both syntaxes can +** be tested using a single build of testfixture. +** +** The following describes the syntax supported by the fts3 MATCH +** operator in a similar format to that used by the lemon parser +** generator. This module does not use actually lemon, it uses a +** custom parser. +** +** query ::= andexpr (OR andexpr)*. +** +** andexpr ::= notexpr (AND? notexpr)*. +** +** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*. +** notexpr ::= LP query RP. +** +** nearexpr ::= phrase (NEAR distance_opt nearexpr)*. +** +** distance_opt ::= . +** distance_opt ::= / INTEGER. +** +** phrase ::= TOKEN. +** phrase ::= COLUMN:TOKEN. +** phrase ::= "TOKEN TOKEN TOKEN...". +*/ + +#ifdef SQLITE_TEST +int sqlite3_fts3_enable_parentheses = 0; +#else +# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS +# define sqlite3_fts3_enable_parentheses 1 +# else +# define sqlite3_fts3_enable_parentheses 0 +# endif +#endif + +/* +** Default span for NEAR operators. +*/ +#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10 + +#include +#include + +/* +** isNot: +** This variable is used by function getNextNode(). When getNextNode() is +** called, it sets ParseContext.isNot to true if the 'next node' is a +** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the +** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to +** zero. +*/ +typedef struct ParseContext ParseContext; +struct ParseContext { + sqlite3_tokenizer *pTokenizer; /* Tokenizer module */ + int iLangid; /* Language id used with tokenizer */ + const char **azCol; /* Array of column names for fts3 table */ + int bFts4; /* True to allow FTS4-only syntax */ + int nCol; /* Number of entries in azCol[] */ + int iDefaultCol; /* Default column to query */ + int isNot; /* True if getNextNode() sees a unary - */ + sqlite3_context *pCtx; /* Write error message here */ + int nNest; /* Number of nested brackets */ +}; + +/* +** This function is equivalent to the standard isspace() function. +** +** The standard isspace() can be awkward to use safely, because although it +** is defined to accept an argument of type int, its behavior when passed +** an integer that falls outside of the range of the unsigned char type +** is undefined (and sometimes, "undefined" means segfault). This wrapper +** is defined to accept an argument of type char, and always returns 0 for +** any values that fall outside of the range of the unsigned char type (i.e. +** negative values). +*/ +static int fts3isspace(char c){ + return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; +} + +/* +** Allocate nByte bytes of memory using sqlite3_malloc(). If successful, +** zero the memory before returning a pointer to it. If unsuccessful, +** return NULL. +*/ +static void *fts3MallocZero(int nByte){ + void *pRet = sqlite3_malloc(nByte); + if( pRet ) memset(pRet, 0, nByte); + return pRet; +} + +int sqlite3Fts3OpenTokenizer( + sqlite3_tokenizer *pTokenizer, + int iLangid, + const char *z, + int n, + sqlite3_tokenizer_cursor **ppCsr +){ + sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + sqlite3_tokenizer_cursor *pCsr = 0; + int rc; + + rc = pModule->xOpen(pTokenizer, z, n, &pCsr); + assert( rc==SQLITE_OK || pCsr==0 ); + if( rc==SQLITE_OK ){ + pCsr->pTokenizer = pTokenizer; + if( pModule->iVersion>=1 ){ + rc = pModule->xLanguageid(pCsr, iLangid); + if( rc!=SQLITE_OK ){ + pModule->xClose(pCsr); + pCsr = 0; + } + } + } + *ppCsr = pCsr; + return rc; +} + + +/* +** Extract the next token from buffer z (length n) using the tokenizer +** and other information (column names etc.) in pParse. Create an Fts3Expr +** structure of type FTSQUERY_PHRASE containing a phrase consisting of this +** single token and set *ppExpr to point to it. If the end of the buffer is +** reached before a token is found, set *ppExpr to zero. It is the +** responsibility of the caller to eventually deallocate the allocated +** Fts3Expr structure (if any) by passing it to sqlite3_free(). +** +** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation +** fails. +*/ +static int getNextToken( + ParseContext *pParse, /* fts3 query parse context */ + int iCol, /* Value for Fts3Phrase.iColumn */ + const char *z, int n, /* Input string */ + Fts3Expr **ppExpr, /* OUT: expression */ + int *pnConsumed /* OUT: Number of bytes consumed */ +){ + sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; + sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + int rc; + sqlite3_tokenizer_cursor *pCursor; + Fts3Expr *pRet = 0; + int nConsumed = 0; + + rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor); + if( rc==SQLITE_OK ){ + const char *zToken; + int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0; + int nByte; /* total space to allocate */ + + rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition); + if( rc==SQLITE_OK ){ + nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken; + pRet = (Fts3Expr *)fts3MallocZero(nByte); + if( !pRet ){ + rc = SQLITE_NOMEM; + }else{ + pRet->eType = FTSQUERY_PHRASE; + pRet->pPhrase = (Fts3Phrase *)&pRet[1]; + pRet->pPhrase->nToken = 1; + pRet->pPhrase->iColumn = iCol; + pRet->pPhrase->aToken[0].n = nToken; + pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1]; + memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken); + + if( iEndpPhrase->aToken[0].isPrefix = 1; + iEnd++; + } + + while( 1 ){ + if( !sqlite3_fts3_enable_parentheses + && iStart>0 && z[iStart-1]=='-' + ){ + pParse->isNot = 1; + iStart--; + }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){ + pRet->pPhrase->aToken[0].bFirst = 1; + iStart--; + }else{ + break; + } + } + + } + nConsumed = iEnd; + } + + pModule->xClose(pCursor); + } + + *pnConsumed = nConsumed; + *ppExpr = pRet; + return rc; +} + + +/* +** Enlarge a memory allocation. If an out-of-memory allocation occurs, +** then free the old allocation. +*/ +static void *fts3ReallocOrFree(void *pOrig, int nNew){ + void *pRet = sqlite3_realloc(pOrig, nNew); + if( !pRet ){ + sqlite3_free(pOrig); + } + return pRet; +} + +/* +** Buffer zInput, length nInput, contains the contents of a quoted string +** that appeared as part of an fts3 query expression. Neither quote character +** is included in the buffer. This function attempts to tokenize the entire +** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE +** containing the results. +** +** If successful, SQLITE_OK is returned and *ppExpr set to point at the +** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory +** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set +** to 0. +*/ +static int getNextString( + ParseContext *pParse, /* fts3 query parse context */ + const char *zInput, int nInput, /* Input string */ + Fts3Expr **ppExpr /* OUT: expression */ +){ + sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; + sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + int rc; + Fts3Expr *p = 0; + sqlite3_tokenizer_cursor *pCursor = 0; + char *zTemp = 0; + int nTemp = 0; + + const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase); + int nToken = 0; + + /* The final Fts3Expr data structure, including the Fts3Phrase, + ** Fts3PhraseToken structures token buffers are all stored as a single + ** allocation so that the expression can be freed with a single call to + ** sqlite3_free(). Setting this up requires a two pass approach. + ** + ** The first pass, in the block below, uses a tokenizer cursor to iterate + ** through the tokens in the expression. This pass uses fts3ReallocOrFree() + ** to assemble data in two dynamic buffers: + ** + ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase + ** structure, followed by the array of Fts3PhraseToken + ** structures. This pass only populates the Fts3PhraseToken array. + ** + ** Buffer zTemp: Contains copies of all tokens. + ** + ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below, + ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase + ** structures. + */ + rc = sqlite3Fts3OpenTokenizer( + pTokenizer, pParse->iLangid, zInput, nInput, &pCursor); + if( rc==SQLITE_OK ){ + int ii; + for(ii=0; rc==SQLITE_OK; ii++){ + const char *zByte; + int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0; + rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos); + if( rc==SQLITE_OK ){ + Fts3PhraseToken *pToken; + + p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken)); + if( !p ) goto no_mem; + + zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte); + if( !zTemp ) goto no_mem; + + assert( nToken==ii ); + pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii]; + memset(pToken, 0, sizeof(Fts3PhraseToken)); + + memcpy(&zTemp[nTemp], zByte, nByte); + nTemp += nByte; + + pToken->n = nByte; + pToken->isPrefix = (iEndbFirst = (iBegin>0 && zInput[iBegin-1]=='^'); + nToken = ii+1; + } + } + + pModule->xClose(pCursor); + pCursor = 0; + } + + if( rc==SQLITE_DONE ){ + int jj; + char *zBuf = 0; + + p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp); + if( !p ) goto no_mem; + memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p); + p->eType = FTSQUERY_PHRASE; + p->pPhrase = (Fts3Phrase *)&p[1]; + p->pPhrase->iColumn = pParse->iDefaultCol; + p->pPhrase->nToken = nToken; + + zBuf = (char *)&p->pPhrase->aToken[nToken]; + if( zTemp ){ + memcpy(zBuf, zTemp, nTemp); + sqlite3_free(zTemp); + }else{ + assert( nTemp==0 ); + } + + for(jj=0; jjpPhrase->nToken; jj++){ + p->pPhrase->aToken[jj].z = zBuf; + zBuf += p->pPhrase->aToken[jj].n; + } + rc = SQLITE_OK; + } + + *ppExpr = p; + return rc; +no_mem: + + if( pCursor ){ + pModule->xClose(pCursor); + } + sqlite3_free(zTemp); + sqlite3_free(p); + *ppExpr = 0; + return SQLITE_NOMEM; +} + +/* +** Function getNextNode(), which is called by fts3ExprParse(), may itself +** call fts3ExprParse(). So this forward declaration is required. +*/ +static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *); + +/* +** The output variable *ppExpr is populated with an allocated Fts3Expr +** structure, or set to 0 if the end of the input buffer is reached. +** +** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM +** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered. +** If SQLITE_ERROR is returned, pContext is populated with an error message. +*/ +static int getNextNode( + ParseContext *pParse, /* fts3 query parse context */ + const char *z, int n, /* Input string */ + Fts3Expr **ppExpr, /* OUT: expression */ + int *pnConsumed /* OUT: Number of bytes consumed */ +){ + static const struct Fts3Keyword { + char *z; /* Keyword text */ + unsigned char n; /* Length of the keyword */ + unsigned char parenOnly; /* Only valid in paren mode */ + unsigned char eType; /* Keyword code */ + } aKeyword[] = { + { "OR" , 2, 0, FTSQUERY_OR }, + { "AND", 3, 1, FTSQUERY_AND }, + { "NOT", 3, 1, FTSQUERY_NOT }, + { "NEAR", 4, 0, FTSQUERY_NEAR } + }; + int ii; + int iCol; + int iColLen; + int rc; + Fts3Expr *pRet = 0; + + const char *zInput = z; + int nInput = n; + + pParse->isNot = 0; + + /* Skip over any whitespace before checking for a keyword, an open or + ** close bracket, or a quoted string. + */ + while( nInput>0 && fts3isspace(*zInput) ){ + nInput--; + zInput++; + } + if( nInput==0 ){ + return SQLITE_DONE; + } + + /* See if we are dealing with a keyword. */ + for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){ + const struct Fts3Keyword *pKey = &aKeyword[ii]; + + if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){ + continue; + } + + if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){ + int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM; + int nKey = pKey->n; + char cNext; + + /* If this is a "NEAR" keyword, check for an explicit nearness. */ + if( pKey->eType==FTSQUERY_NEAR ){ + assert( nKey==4 ); + if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){ + nNear = 0; + for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){ + nNear = nNear * 10 + (zInput[nKey] - '0'); + } + } + } + + /* At this point this is probably a keyword. But for that to be true, + ** the next byte must contain either whitespace, an open or close + ** parenthesis, a quote character, or EOF. + */ + cNext = zInput[nKey]; + if( fts3isspace(cNext) + || cNext=='"' || cNext=='(' || cNext==')' || cNext==0 + ){ + pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr)); + if( !pRet ){ + return SQLITE_NOMEM; + } + pRet->eType = pKey->eType; + pRet->nNear = nNear; + *ppExpr = pRet; + *pnConsumed = (int)((zInput - z) + nKey); + return SQLITE_OK; + } + + /* Turns out that wasn't a keyword after all. This happens if the + ** user has supplied a token such as "ORacle". Continue. + */ + } + } + + /* Check for an open bracket. */ + if( sqlite3_fts3_enable_parentheses ){ + if( *zInput=='(' ){ + int nConsumed; + pParse->nNest++; + rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed); + if( rc==SQLITE_OK && !*ppExpr ){ + rc = SQLITE_DONE; + } + *pnConsumed = (int)((zInput - z) + 1 + nConsumed); + return rc; + } + + /* Check for a close bracket. */ + if( *zInput==')' ){ + pParse->nNest--; + *pnConsumed = (int)((zInput - z) + 1); + return SQLITE_DONE; + } + } + + /* See if we are dealing with a quoted phrase. If this is the case, then + ** search for the closing quote and pass the whole string to getNextString() + ** for processing. This is easy to do, as fts3 has no syntax for escaping + ** a quote character embedded in a string. + */ + if( *zInput=='"' ){ + for(ii=1; iiiDefaultCol; + iColLen = 0; + for(ii=0; iinCol; ii++){ + const char *zStr = pParse->azCol[ii]; + int nStr = (int)strlen(zStr); + if( nInput>nStr && zInput[nStr]==':' + && sqlite3_strnicmp(zStr, zInput, nStr)==0 + ){ + iCol = ii; + iColLen = (int)((zInput - z) + nStr + 1); + break; + } + } + rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed); + *pnConsumed += iColLen; + return rc; +} + +/* +** The argument is an Fts3Expr structure for a binary operator (any type +** except an FTSQUERY_PHRASE). Return an integer value representing the +** precedence of the operator. Lower values have a higher precedence (i.e. +** group more tightly). For example, in the C language, the == operator +** groups more tightly than ||, and would therefore have a higher precedence. +** +** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS +** is defined), the order of the operators in precedence from highest to +** lowest is: +** +** NEAR +** NOT +** AND (including implicit ANDs) +** OR +** +** Note that when using the old query syntax, the OR operator has a higher +** precedence than the AND operator. +*/ +static int opPrecedence(Fts3Expr *p){ + assert( p->eType!=FTSQUERY_PHRASE ); + if( sqlite3_fts3_enable_parentheses ){ + return p->eType; + }else if( p->eType==FTSQUERY_NEAR ){ + return 1; + }else if( p->eType==FTSQUERY_OR ){ + return 2; + } + assert( p->eType==FTSQUERY_AND ); + return 3; +} + +/* +** Argument ppHead contains a pointer to the current head of a query +** expression tree being parsed. pPrev is the expression node most recently +** inserted into the tree. This function adds pNew, which is always a binary +** operator node, into the expression tree based on the relative precedence +** of pNew and the existing nodes of the tree. This may result in the head +** of the tree changing, in which case *ppHead is set to the new root node. +*/ +static void insertBinaryOperator( + Fts3Expr **ppHead, /* Pointer to the root node of a tree */ + Fts3Expr *pPrev, /* Node most recently inserted into the tree */ + Fts3Expr *pNew /* New binary node to insert into expression tree */ +){ + Fts3Expr *pSplit = pPrev; + while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){ + pSplit = pSplit->pParent; + } + + if( pSplit->pParent ){ + assert( pSplit->pParent->pRight==pSplit ); + pSplit->pParent->pRight = pNew; + pNew->pParent = pSplit->pParent; + }else{ + *ppHead = pNew; + } + pNew->pLeft = pSplit; + pSplit->pParent = pNew; +} + +/* +** Parse the fts3 query expression found in buffer z, length n. This function +** returns either when the end of the buffer is reached or an unmatched +** closing bracket - ')' - is encountered. +** +** If successful, SQLITE_OK is returned, *ppExpr is set to point to the +** parsed form of the expression and *pnConsumed is set to the number of +** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM +** (out of memory error) or SQLITE_ERROR (parse error) is returned. +*/ +static int fts3ExprParse( + ParseContext *pParse, /* fts3 query parse context */ + const char *z, int n, /* Text of MATCH query */ + Fts3Expr **ppExpr, /* OUT: Parsed query structure */ + int *pnConsumed /* OUT: Number of bytes consumed */ +){ + Fts3Expr *pRet = 0; + Fts3Expr *pPrev = 0; + Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */ + int nIn = n; + const char *zIn = z; + int rc = SQLITE_OK; + int isRequirePhrase = 1; + + while( rc==SQLITE_OK ){ + Fts3Expr *p = 0; + int nByte = 0; + rc = getNextNode(pParse, zIn, nIn, &p, &nByte); + if( rc==SQLITE_OK ){ + int isPhrase; + + if( !sqlite3_fts3_enable_parentheses + && p->eType==FTSQUERY_PHRASE && pParse->isNot + ){ + /* Create an implicit NOT operator. */ + Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr)); + if( !pNot ){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_NOMEM; + goto exprparse_out; + } + pNot->eType = FTSQUERY_NOT; + pNot->pRight = p; + p->pParent = pNot; + if( pNotBranch ){ + pNot->pLeft = pNotBranch; + pNotBranch->pParent = pNot; + } + pNotBranch = pNot; + p = pPrev; + }else{ + int eType = p->eType; + isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft); + + /* The isRequirePhrase variable is set to true if a phrase or + ** an expression contained in parenthesis is required. If a + ** binary operator (AND, OR, NOT or NEAR) is encounted when + ** isRequirePhrase is set, this is a syntax error. + */ + if( !isPhrase && isRequirePhrase ){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_ERROR; + goto exprparse_out; + } + + if( isPhrase && !isRequirePhrase ){ + /* Insert an implicit AND operator. */ + Fts3Expr *pAnd; + assert( pRet && pPrev ); + pAnd = fts3MallocZero(sizeof(Fts3Expr)); + if( !pAnd ){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_NOMEM; + goto exprparse_out; + } + pAnd->eType = FTSQUERY_AND; + insertBinaryOperator(&pRet, pPrev, pAnd); + pPrev = pAnd; + } + + /* This test catches attempts to make either operand of a NEAR + ** operator something other than a phrase. For example, either of + ** the following: + ** + ** (bracketed expression) NEAR phrase + ** phrase NEAR (bracketed expression) + ** + ** Return an error in either case. + */ + if( pPrev && ( + (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE) + || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR) + )){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_ERROR; + goto exprparse_out; + } + + if( isPhrase ){ + if( pRet ){ + assert( pPrev && pPrev->pLeft && pPrev->pRight==0 ); + pPrev->pRight = p; + p->pParent = pPrev; + }else{ + pRet = p; + } + }else{ + insertBinaryOperator(&pRet, pPrev, p); + } + isRequirePhrase = !isPhrase; + } + assert( nByte>0 ); + } + assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) ); + nIn -= nByte; + zIn += nByte; + pPrev = p; + } + + if( rc==SQLITE_DONE && pRet && isRequirePhrase ){ + rc = SQLITE_ERROR; + } + + if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + if( !sqlite3_fts3_enable_parentheses && pNotBranch ){ + if( !pRet ){ + rc = SQLITE_ERROR; + }else{ + Fts3Expr *pIter = pNotBranch; + while( pIter->pLeft ){ + pIter = pIter->pLeft; + } + pIter->pLeft = pRet; + pRet->pParent = pIter; + pRet = pNotBranch; + } + } + } + *pnConsumed = n - nIn; + +exprparse_out: + if( rc!=SQLITE_OK ){ + sqlite3Fts3ExprFree(pRet); + sqlite3Fts3ExprFree(pNotBranch); + pRet = 0; + } + *ppExpr = pRet; + return rc; +} + +/* +** Return SQLITE_ERROR if the maximum depth of the expression tree passed +** as the only argument is more than nMaxDepth. +*/ +static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){ + int rc = SQLITE_OK; + if( p ){ + if( nMaxDepth<0 ){ + rc = SQLITE_TOOBIG; + }else{ + rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1); + if( rc==SQLITE_OK ){ + rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1); + } + } + } + return rc; +} + +/* +** This function attempts to transform the expression tree at (*pp) to +** an equivalent but more balanced form. The tree is modified in place. +** If successful, SQLITE_OK is returned and (*pp) set to point to the +** new root expression node. +** +** nMaxDepth is the maximum allowable depth of the balanced sub-tree. +** +** Otherwise, if an error occurs, an SQLite error code is returned and +** expression (*pp) freed. +*/ +static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ + int rc = SQLITE_OK; /* Return code */ + Fts3Expr *pRoot = *pp; /* Initial root node */ + Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */ + int eType = pRoot->eType; /* Type of node in this tree */ + + if( nMaxDepth==0 ){ + rc = SQLITE_ERROR; + } + + if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){ + Fts3Expr **apLeaf; + apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth); + if( 0==apLeaf ){ + rc = SQLITE_NOMEM; + }else{ + memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth); + } + + if( rc==SQLITE_OK ){ + int i; + Fts3Expr *p; + + /* Set $p to point to the left-most leaf in the tree of eType nodes. */ + for(p=pRoot; p->eType==eType; p=p->pLeft){ + assert( p->pParent==0 || p->pParent->pLeft==p ); + assert( p->pLeft && p->pRight ); + } + + /* This loop runs once for each leaf in the tree of eType nodes. */ + while( 1 ){ + int iLvl; + Fts3Expr *pParent = p->pParent; /* Current parent of p */ + + assert( pParent==0 || pParent->pLeft==p ); + p->pParent = 0; + if( pParent ){ + pParent->pLeft = 0; + }else{ + pRoot = 0; + } + rc = fts3ExprBalance(&p, nMaxDepth-1); + if( rc!=SQLITE_OK ) break; + + for(iLvl=0; p && iLvlpLeft = apLeaf[iLvl]; + pFree->pRight = p; + pFree->pLeft->pParent = pFree; + pFree->pRight->pParent = pFree; + + p = pFree; + pFree = pFree->pParent; + p->pParent = 0; + apLeaf[iLvl] = 0; + } + } + if( p ){ + sqlite3Fts3ExprFree(p); + rc = SQLITE_TOOBIG; + break; + } + + /* If that was the last leaf node, break out of the loop */ + if( pParent==0 ) break; + + /* Set $p to point to the next leaf in the tree of eType nodes */ + for(p=pParent->pRight; p->eType==eType; p=p->pLeft); + + /* Remove pParent from the original tree. */ + assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent ); + pParent->pRight->pParent = pParent->pParent; + if( pParent->pParent ){ + pParent->pParent->pLeft = pParent->pRight; + }else{ + assert( pParent==pRoot ); + pRoot = pParent->pRight; + } + + /* Link pParent into the free node list. It will be used as an + ** internal node of the new tree. */ + pParent->pParent = pFree; + pFree = pParent; + } + + if( rc==SQLITE_OK ){ + p = 0; + for(i=0; ipParent = 0; + }else{ + assert( pFree!=0 ); + pFree->pRight = p; + pFree->pLeft = apLeaf[i]; + pFree->pLeft->pParent = pFree; + pFree->pRight->pParent = pFree; + + p = pFree; + pFree = pFree->pParent; + p->pParent = 0; + } + } + } + pRoot = p; + }else{ + /* An error occurred. Delete the contents of the apLeaf[] array + ** and pFree list. Everything else is cleaned up by the call to + ** sqlite3Fts3ExprFree(pRoot) below. */ + Fts3Expr *pDel; + for(i=0; ipParent; + sqlite3_free(pDel); + } + } + + assert( pFree==0 ); + sqlite3_free( apLeaf ); + } + } + + if( rc!=SQLITE_OK ){ + sqlite3Fts3ExprFree(pRoot); + pRoot = 0; + } + *pp = pRoot; + return rc; +} + +/* +** This function is similar to sqlite3Fts3ExprParse(), with the following +** differences: +** +** 1. It does not do expression rebalancing. +** 2. It does not check that the expression does not exceed the +** maximum allowable depth. +** 3. Even if it fails, *ppExpr may still be set to point to an +** expression tree. It should be deleted using sqlite3Fts3ExprFree() +** in this case. +*/ +static int fts3ExprParseUnbalanced( + sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ + int iLangid, /* Language id for tokenizer */ + char **azCol, /* Array of column names for fts3 table */ + int bFts4, /* True to allow FTS4-only syntax */ + int nCol, /* Number of entries in azCol[] */ + int iDefaultCol, /* Default column to query */ + const char *z, int n, /* Text of MATCH query */ + Fts3Expr **ppExpr /* OUT: Parsed query structure */ +){ + int nParsed; + int rc; + ParseContext sParse; + + memset(&sParse, 0, sizeof(ParseContext)); + sParse.pTokenizer = pTokenizer; + sParse.iLangid = iLangid; + sParse.azCol = (const char **)azCol; + sParse.nCol = nCol; + sParse.iDefaultCol = iDefaultCol; + sParse.bFts4 = bFts4; + if( z==0 ){ + *ppExpr = 0; + return SQLITE_OK; + } + if( n<0 ){ + n = (int)strlen(z); + } + rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed); + assert( rc==SQLITE_OK || *ppExpr==0 ); + + /* Check for mismatched parenthesis */ + if( rc==SQLITE_OK && sParse.nNest ){ + rc = SQLITE_ERROR; + } + + return rc; +} + +/* +** Parameters z and n contain a pointer to and length of a buffer containing +** an fts3 query expression, respectively. This function attempts to parse the +** query expression and create a tree of Fts3Expr structures representing the +** parsed expression. If successful, *ppExpr is set to point to the head +** of the parsed expression tree and SQLITE_OK is returned. If an error +** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse +** error) is returned and *ppExpr is set to 0. +** +** If parameter n is a negative number, then z is assumed to point to a +** nul-terminated string and the length is determined using strlen(). +** +** The first parameter, pTokenizer, is passed the fts3 tokenizer module to +** use to normalize query tokens while parsing the expression. The azCol[] +** array, which is assumed to contain nCol entries, should contain the names +** of each column in the target fts3 table, in order from left to right. +** Column names must be nul-terminated strings. +** +** The iDefaultCol parameter should be passed the index of the table column +** that appears on the left-hand-side of the MATCH operator (the default +** column to match against for tokens for which a column name is not explicitly +** specified as part of the query string), or -1 if tokens may by default +** match any table column. +*/ +int sqlite3Fts3ExprParse( + sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ + int iLangid, /* Language id for tokenizer */ + char **azCol, /* Array of column names for fts3 table */ + int bFts4, /* True to allow FTS4-only syntax */ + int nCol, /* Number of entries in azCol[] */ + int iDefaultCol, /* Default column to query */ + const char *z, int n, /* Text of MATCH query */ + Fts3Expr **ppExpr, /* OUT: Parsed query structure */ + char **pzErr /* OUT: Error message (sqlite3_malloc) */ +){ + int rc = fts3ExprParseUnbalanced( + pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr + ); + + /* Rebalance the expression. And check that its depth does not exceed + ** SQLITE_FTS3_MAX_EXPR_DEPTH. */ + if( rc==SQLITE_OK && *ppExpr ){ + rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); + if( rc==SQLITE_OK ){ + rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); + } + } + + if( rc!=SQLITE_OK ){ + sqlite3Fts3ExprFree(*ppExpr); + *ppExpr = 0; + if( rc==SQLITE_TOOBIG ){ + *pzErr = sqlite3_mprintf( + "FTS expression tree is too large (maximum depth %d)", + SQLITE_FTS3_MAX_EXPR_DEPTH + ); + rc = SQLITE_ERROR; + }else if( rc==SQLITE_ERROR ){ + *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z); + } + } + + return rc; +} + +/* +** Free a single node of an expression tree. +*/ +static void fts3FreeExprNode(Fts3Expr *p){ + assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 ); + sqlite3Fts3EvalPhraseCleanup(p->pPhrase); + sqlite3_free(p->aMI); + sqlite3_free(p); +} + +/* +** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse(). +** +** This function would be simpler if it recursively called itself. But +** that would mean passing a sufficiently large expression to ExprParse() +** could cause a stack overflow. +*/ +void sqlite3Fts3ExprFree(Fts3Expr *pDel){ + Fts3Expr *p; + assert( pDel==0 || pDel->pParent==0 ); + for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){ + assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft ); + } + while( p ){ + Fts3Expr *pParent = p->pParent; + fts3FreeExprNode(p); + if( pParent && p==pParent->pLeft && pParent->pRight ){ + p = pParent->pRight; + while( p && (p->pLeft || p->pRight) ){ + assert( p==p->pParent->pRight || p==p->pParent->pLeft ); + p = (p->pLeft ? p->pLeft : p->pRight); + } + }else{ + p = pParent; + } + } +} + +/**************************************************************************** +***************************************************************************** +** Everything after this point is just test code. +*/ + +#ifdef SQLITE_TEST + +#include + +/* +** Function to query the hash-table of tokenizers (see README.tokenizers). +*/ +static int queryTestTokenizer( + sqlite3 *db, + const char *zName, + const sqlite3_tokenizer_module **pp +){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts3_tokenizer(?)"; + + *pp = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ + memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + } + } + + return sqlite3_finalize(pStmt); +} + +/* +** Return a pointer to a buffer containing a text representation of the +** expression passed as the first argument. The buffer is obtained from +** sqlite3_malloc(). It is the responsibility of the caller to use +** sqlite3_free() to release the memory. If an OOM condition is encountered, +** NULL is returned. +** +** If the second argument is not NULL, then its contents are prepended to +** the returned expression text and then freed using sqlite3_free(). +*/ +static char *exprToString(Fts3Expr *pExpr, char *zBuf){ + if( pExpr==0 ){ + return sqlite3_mprintf(""); + } + switch( pExpr->eType ){ + case FTSQUERY_PHRASE: { + Fts3Phrase *pPhrase = pExpr->pPhrase; + int i; + zBuf = sqlite3_mprintf( + "%zPHRASE %d 0", zBuf, pPhrase->iColumn); + for(i=0; zBuf && inToken; i++){ + zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, + pPhrase->aToken[i].n, pPhrase->aToken[i].z, + (pPhrase->aToken[i].isPrefix?"+":"") + ); + } + return zBuf; + } + + case FTSQUERY_NEAR: + zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear); + break; + case FTSQUERY_NOT: + zBuf = sqlite3_mprintf("%zNOT ", zBuf); + break; + case FTSQUERY_AND: + zBuf = sqlite3_mprintf("%zAND ", zBuf); + break; + case FTSQUERY_OR: + zBuf = sqlite3_mprintf("%zOR ", zBuf); + break; + } + + if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf); + if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf); + if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf); + + if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf); + if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf); + + return zBuf; +} + +/* +** This is the implementation of a scalar SQL function used to test the +** expression parser. It should be called as follows: +** +** fts3_exprtest(, , , ...); +** +** The first argument, , is the name of the fts3 tokenizer used +** to parse the query expression (see README.tokenizers). The second argument +** is the query expression to parse. Each subsequent argument is the name +** of a column of the fts3 table that the query expression may refer to. +** For example: +** +** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2'); +*/ +static void fts3ExprTest( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3_tokenizer_module const *pModule = 0; + sqlite3_tokenizer *pTokenizer = 0; + int rc; + char **azCol = 0; + const char *zExpr; + int nExpr; + int nCol; + int ii; + Fts3Expr *pExpr; + char *zBuf = 0; + sqlite3 *db = sqlite3_context_db_handle(context); + + if( argc<3 ){ + sqlite3_result_error(context, + "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1 + ); + return; + } + + rc = queryTestTokenizer(db, + (const char *)sqlite3_value_text(argv[0]), &pModule); + if( rc==SQLITE_NOMEM ){ + sqlite3_result_error_nomem(context); + goto exprtest_out; + }else if( !pModule ){ + sqlite3_result_error(context, "No such tokenizer module", -1); + goto exprtest_out; + } + + rc = pModule->xCreate(0, 0, &pTokenizer); + assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); + if( rc==SQLITE_NOMEM ){ + sqlite3_result_error_nomem(context); + goto exprtest_out; + } + pTokenizer->pModule = pModule; + + zExpr = (const char *)sqlite3_value_text(argv[1]); + nExpr = sqlite3_value_bytes(argv[1]); + nCol = argc-2; + azCol = (char **)sqlite3_malloc(nCol*sizeof(char *)); + if( !azCol ){ + sqlite3_result_error_nomem(context); + goto exprtest_out; + } + for(ii=0; iixDestroy(pTokenizer); + } + sqlite3_free(azCol); +} + +/* +** Register the query expression parser test function fts3_exprtest() +** with database connection db. +*/ +int sqlite3Fts3ExprInitTestInterface(sqlite3* db){ + int rc = sqlite3_create_function( + db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0 + ); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", + -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0 + ); + } + return rc; +} + +#endif +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_hash.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..57c59b587a6f9e9e1b8c768b0bdc43cd4bc93581 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_hash.c @@ -0,0 +1,383 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the implementation of generic hash-tables used in SQLite. +** We've modified it slightly to serve as a standalone hash table +** implementation for the full-text indexing module. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#include +#include +#include + +#include "fts3_hash.h" + +/* +** Malloc and Free functions +*/ +static void *fts3HashMalloc(int n){ + void *p = sqlite3_malloc(n); + if( p ){ + memset(p, 0, n); + } + return p; +} +static void fts3HashFree(void *p){ + sqlite3_free(p); +} + +/* Turn bulk memory into a hash table object by initializing the +** fields of the Hash structure. +** +** "pNew" is a pointer to the hash table that is to be initialized. +** keyClass is one of the constants +** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass +** determines what kind of key the hash table will use. "copyKey" is +** true if the hash table should make its own private copy of keys and +** false if it should just use the supplied pointer. +*/ +void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){ + assert( pNew!=0 ); + assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY ); + pNew->keyClass = keyClass; + pNew->copyKey = copyKey; + pNew->first = 0; + pNew->count = 0; + pNew->htsize = 0; + pNew->ht = 0; +} + +/* Remove all entries from a hash table. Reclaim all memory. +** Call this routine to delete a hash table or to reset a hash table +** to the empty state. +*/ +void sqlite3Fts3HashClear(Fts3Hash *pH){ + Fts3HashElem *elem; /* For looping over all elements of the table */ + + assert( pH!=0 ); + elem = pH->first; + pH->first = 0; + fts3HashFree(pH->ht); + pH->ht = 0; + pH->htsize = 0; + while( elem ){ + Fts3HashElem *next_elem = elem->next; + if( pH->copyKey && elem->pKey ){ + fts3HashFree(elem->pKey); + } + fts3HashFree(elem); + elem = next_elem; + } + pH->count = 0; +} + +/* +** Hash and comparison functions when the mode is FTS3_HASH_STRING +*/ +static int fts3StrHash(const void *pKey, int nKey){ + const char *z = (const char *)pKey; + int h = 0; + if( nKey<=0 ) nKey = (int) strlen(z); + while( nKey > 0 ){ + h = (h<<3) ^ h ^ *z++; + nKey--; + } + return h & 0x7fffffff; +} +static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return strncmp((const char*)pKey1,(const char*)pKey2,n1); +} + +/* +** Hash and comparison functions when the mode is FTS3_HASH_BINARY +*/ +static int fts3BinHash(const void *pKey, int nKey){ + int h = 0; + const char *z = (const char *)pKey; + while( nKey-- > 0 ){ + h = (h<<3) ^ h ^ *(z++); + } + return h & 0x7fffffff; +} +static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){ + if( n1!=n2 ) return 1; + return memcmp(pKey1,pKey2,n1); +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** The C syntax in this function definition may be unfamilar to some +** programmers, so we provide the following additional explanation: +** +** The name of the function is "ftsHashFunction". The function takes a +** single parameter "keyClass". The return value of ftsHashFunction() +** is a pointer to another function. Specifically, the return value +** of ftsHashFunction() is a pointer to a function that takes two parameters +** with types "const void*" and "int" and returns an "int". +*/ +static int (*ftsHashFunction(int keyClass))(const void*,int){ + if( keyClass==FTS3_HASH_STRING ){ + return &fts3StrHash; + }else{ + assert( keyClass==FTS3_HASH_BINARY ); + return &fts3BinHash; + } +} + +/* +** Return a pointer to the appropriate hash function given the key class. +** +** For help in interpreted the obscure C code in the function definition, +** see the header comment on the previous function. +*/ +static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){ + if( keyClass==FTS3_HASH_STRING ){ + return &fts3StrCompare; + }else{ + assert( keyClass==FTS3_HASH_BINARY ); + return &fts3BinCompare; + } +} + +/* Link an element into the hash table +*/ +static void fts3HashInsertElement( + Fts3Hash *pH, /* The complete hash table */ + struct _fts3ht *pEntry, /* The entry into which pNew is inserted */ + Fts3HashElem *pNew /* The element to be inserted */ +){ + Fts3HashElem *pHead; /* First element already in pEntry */ + pHead = pEntry->chain; + if( pHead ){ + pNew->next = pHead; + pNew->prev = pHead->prev; + if( pHead->prev ){ pHead->prev->next = pNew; } + else { pH->first = pNew; } + pHead->prev = pNew; + }else{ + pNew->next = pH->first; + if( pH->first ){ pH->first->prev = pNew; } + pNew->prev = 0; + pH->first = pNew; + } + pEntry->count++; + pEntry->chain = pNew; +} + + +/* Resize the hash table so that it cantains "new_size" buckets. +** "new_size" must be a power of 2. The hash table might fail +** to resize if sqliteMalloc() fails. +** +** Return non-zero if a memory allocation error occurs. +*/ +static int fts3Rehash(Fts3Hash *pH, int new_size){ + struct _fts3ht *new_ht; /* The new hash table */ + Fts3HashElem *elem, *next_elem; /* For looping over existing elements */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( (new_size & (new_size-1))==0 ); + new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) ); + if( new_ht==0 ) return 1; + fts3HashFree(pH->ht); + pH->ht = new_ht; + pH->htsize = new_size; + xHash = ftsHashFunction(pH->keyClass); + for(elem=pH->first, pH->first=0; elem; elem = next_elem){ + int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1); + next_elem = elem->next; + fts3HashInsertElement(pH, &new_ht[h], elem); + } + return 0; +} + +/* This function (for internal use only) locates an element in an +** hash table that matches the given key. The hash for this key has +** already been computed and is passed as the 4th parameter. +*/ +static Fts3HashElem *fts3FindElementByHash( + const Fts3Hash *pH, /* The pH to be searched */ + const void *pKey, /* The key we are searching for */ + int nKey, + int h /* The hash for this key. */ +){ + Fts3HashElem *elem; /* Used to loop thru the element list */ + int count; /* Number of elements left to test */ + int (*xCompare)(const void*,int,const void*,int); /* comparison function */ + + if( pH->ht ){ + struct _fts3ht *pEntry = &pH->ht[h]; + elem = pEntry->chain; + count = pEntry->count; + xCompare = ftsCompareFunction(pH->keyClass); + while( count-- && elem ){ + if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ + return elem; + } + elem = elem->next; + } + } + return 0; +} + +/* Remove a single entry from the hash table given a pointer to that +** element and a hash on the element's key. +*/ +static void fts3RemoveElementByHash( + Fts3Hash *pH, /* The pH containing "elem" */ + Fts3HashElem* elem, /* The element to be removed from the pH */ + int h /* Hash value for the element */ +){ + struct _fts3ht *pEntry; + if( elem->prev ){ + elem->prev->next = elem->next; + }else{ + pH->first = elem->next; + } + if( elem->next ){ + elem->next->prev = elem->prev; + } + pEntry = &pH->ht[h]; + if( pEntry->chain==elem ){ + pEntry->chain = elem->next; + } + pEntry->count--; + if( pEntry->count<=0 ){ + pEntry->chain = 0; + } + if( pH->copyKey && elem->pKey ){ + fts3HashFree(elem->pKey); + } + fts3HashFree( elem ); + pH->count--; + if( pH->count<=0 ){ + assert( pH->first==0 ); + assert( pH->count==0 ); + fts3HashClear(pH); + } +} + +Fts3HashElem *sqlite3Fts3HashFindElem( + const Fts3Hash *pH, + const void *pKey, + int nKey +){ + int h; /* A hash on key */ + int (*xHash)(const void*,int); /* The hash function */ + + if( pH==0 || pH->ht==0 ) return 0; + xHash = ftsHashFunction(pH->keyClass); + assert( xHash!=0 ); + h = (*xHash)(pKey,nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1)); +} + +/* +** Attempt to locate an element of the hash table pH with a key +** that matches pKey,nKey. Return the data for this element if it is +** found, or NULL if there is no match. +*/ +void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){ + Fts3HashElem *pElem; /* The element that matches key (if any) */ + + pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey); + return pElem ? pElem->data : 0; +} + +/* Insert an element into the hash table pH. The key is pKey,nKey +** and the data is "data". +** +** If no element exists with a matching key, then a new +** element is created. A copy of the key is made if the copyKey +** flag is set. NULL is returned. +** +** If another element already exists with the same key, then the +** new data replaces the old data and the old data is returned. +** The key is not copied in this instance. If a malloc fails, then +** the new data is returned and the hash table is unchanged. +** +** If the "data" parameter to this function is NULL, then the +** element corresponding to "key" is removed from the hash table. +*/ +void *sqlite3Fts3HashInsert( + Fts3Hash *pH, /* The hash table to insert into */ + const void *pKey, /* The key */ + int nKey, /* Number of bytes in the key */ + void *data /* The data */ +){ + int hraw; /* Raw hash value of the key */ + int h; /* the hash of the key modulo hash table size */ + Fts3HashElem *elem; /* Used to loop thru the element list */ + Fts3HashElem *new_elem; /* New element added to the pH */ + int (*xHash)(const void*,int); /* The hash function */ + + assert( pH!=0 ); + xHash = ftsHashFunction(pH->keyClass); + assert( xHash!=0 ); + hraw = (*xHash)(pKey, nKey); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + elem = fts3FindElementByHash(pH,pKey,nKey,h); + if( elem ){ + void *old_data = elem->data; + if( data==0 ){ + fts3RemoveElementByHash(pH,elem,h); + }else{ + elem->data = data; + } + return old_data; + } + if( data==0 ) return 0; + if( (pH->htsize==0 && fts3Rehash(pH,8)) + || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2)) + ){ + pH->count = 0; + return data; + } + assert( pH->htsize>0 ); + new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) ); + if( new_elem==0 ) return data; + if( pH->copyKey && pKey!=0 ){ + new_elem->pKey = fts3HashMalloc( nKey ); + if( new_elem->pKey==0 ){ + fts3HashFree(new_elem); + return data; + } + memcpy((void*)new_elem->pKey, pKey, nKey); + }else{ + new_elem->pKey = (void*)pKey; + } + new_elem->nKey = nKey; + pH->count++; + assert( pH->htsize>0 ); + assert( (pH->htsize & (pH->htsize-1))==0 ); + h = hraw & (pH->htsize-1); + fts3HashInsertElement(pH, &pH->ht[h], new_elem); + new_elem->data = data; + return 0; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_hash.h b/components/external/SQLite-3.8.1/ext/fts3/fts3_hash.h new file mode 100644 index 0000000000000000000000000000000000000000..dc3fcf8334fb26962bc887fb1fc30e21c543185c --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_hash.h @@ -0,0 +1,112 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implementation +** used in SQLite. We've modified it slightly to serve as a standalone +** hash table implementation for the full-text indexing module. +** +*/ +#ifndef _FTS3_HASH_H_ +#define _FTS3_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct Fts3Hash Fts3Hash; +typedef struct Fts3HashElem Fts3HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, many of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +*/ +struct Fts3Hash { + char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ + char copyKey; /* True if copy of key made on insert */ + int count; /* Number of entries in this table */ + Fts3HashElem *first; /* The first element of the array */ + int htsize; /* Number of buckets in the hash table */ + struct _fts3ht { /* the hash table */ + int count; /* Number of entries with this hash */ + Fts3HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct Fts3HashElem { + Fts3HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + void *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** There are 2 different modes of operation for a hash table: +** +** FTS3_HASH_STRING pKey points to a string that is nKey bytes long +** (including the null-terminator, if any). Case +** is respected in comparisons. +** +** FTS3_HASH_BINARY pKey points to binary data nKey bytes long. +** memcmp() is used to compare keys. +** +** A copy of the key is made if the copyKey parameter to fts3HashInit is 1. +*/ +#define FTS3_HASH_STRING 1 +#define FTS3_HASH_BINARY 2 + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey); +void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData); +void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey); +void sqlite3Fts3HashClear(Fts3Hash*); +Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int); + +/* +** Shorthand for the functions above +*/ +#define fts3HashInit sqlite3Fts3HashInit +#define fts3HashInsert sqlite3Fts3HashInsert +#define fts3HashFind sqlite3Fts3HashFind +#define fts3HashClear sqlite3Fts3HashClear +#define fts3HashFindElem sqlite3Fts3HashFindElem + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** Fts3Hash h; +** Fts3HashElem *p; +** ... +** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){ +** SomeStructure *pData = fts3HashData(p); +** // do something with pData +** } +*/ +#define fts3HashFirst(H) ((H)->first) +#define fts3HashNext(E) ((E)->next) +#define fts3HashData(E) ((E)->data) +#define fts3HashKey(E) ((E)->pKey) +#define fts3HashKeysize(E) ((E)->nKey) + +/* +** Number of entries in a hash table +*/ +#define fts3HashCount(H) ((H)->count) + +#endif /* _FTS3_HASH_H_ */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_icu.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_icu.c new file mode 100644 index 0000000000000000000000000000000000000000..52df8c7d8128e3f6e71bc0571653232eac06a9a5 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_icu.c @@ -0,0 +1,261 @@ +/* +** 2007 June 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements a tokenizer for fts3 based on the ICU library. +*/ +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) +#ifdef SQLITE_ENABLE_ICU + +#include +#include +#include "fts3_tokenizer.h" + +#include +#include +#include +#include + +typedef struct IcuTokenizer IcuTokenizer; +typedef struct IcuCursor IcuCursor; + +struct IcuTokenizer { + sqlite3_tokenizer base; + char *zLocale; +}; + +struct IcuCursor { + sqlite3_tokenizer_cursor base; + + UBreakIterator *pIter; /* ICU break-iterator object */ + int nChar; /* Number of UChar elements in pInput */ + UChar *aChar; /* Copy of input using utf-16 encoding */ + int *aOffset; /* Offsets of each character in utf-8 input */ + + int nBuffer; + char *zBuffer; + + int iToken; +}; + +/* +** Create a new tokenizer instance. +*/ +static int icuCreate( + int argc, /* Number of entries in argv[] */ + const char * const *argv, /* Tokenizer creation arguments */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ +){ + IcuTokenizer *p; + int n = 0; + + if( argc>0 ){ + n = strlen(argv[0])+1; + } + p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n); + if( !p ){ + return SQLITE_NOMEM; + } + memset(p, 0, sizeof(IcuTokenizer)); + + if( n ){ + p->zLocale = (char *)&p[1]; + memcpy(p->zLocale, argv[0], n); + } + + *ppTokenizer = (sqlite3_tokenizer *)p; + + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int icuDestroy(sqlite3_tokenizer *pTokenizer){ + IcuTokenizer *p = (IcuTokenizer *)pTokenizer; + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is pInput[0..nBytes-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int icuOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *zInput, /* Input string */ + int nInput, /* Length of zInput in bytes */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + IcuTokenizer *p = (IcuTokenizer *)pTokenizer; + IcuCursor *pCsr; + + const int32_t opt = U_FOLD_CASE_DEFAULT; + UErrorCode status = U_ZERO_ERROR; + int nChar; + + UChar32 c; + int iInput = 0; + int iOut = 0; + + *ppCursor = 0; + + if( zInput==0 ){ + nInput = 0; + zInput = ""; + }else if( nInput<0 ){ + nInput = strlen(zInput); + } + nChar = nInput+1; + pCsr = (IcuCursor *)sqlite3_malloc( + sizeof(IcuCursor) + /* IcuCursor */ + ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */ + (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */ + ); + if( !pCsr ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(IcuCursor)); + pCsr->aChar = (UChar *)&pCsr[1]; + pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3]; + + pCsr->aOffset[iOut] = iInput; + U8_NEXT(zInput, iInput, nInput, c); + while( c>0 ){ + int isError = 0; + c = u_foldCase(c, opt); + U16_APPEND(pCsr->aChar, iOut, nChar, c, isError); + if( isError ){ + sqlite3_free(pCsr); + return SQLITE_ERROR; + } + pCsr->aOffset[iOut] = iInput; + + if( iInputpIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status); + if( !U_SUCCESS(status) ){ + sqlite3_free(pCsr); + return SQLITE_ERROR; + } + pCsr->nChar = iOut; + + ubrk_first(pCsr->pIter); + *ppCursor = (sqlite3_tokenizer_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to icuOpen(). +*/ +static int icuClose(sqlite3_tokenizer_cursor *pCursor){ + IcuCursor *pCsr = (IcuCursor *)pCursor; + ubrk_close(pCsr->pIter); + sqlite3_free(pCsr->zBuffer); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** Extract the next token from a tokenization cursor. +*/ +static int icuNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + IcuCursor *pCsr = (IcuCursor *)pCursor; + + int iStart = 0; + int iEnd = 0; + int nByte = 0; + + while( iStart==iEnd ){ + UChar32 c; + + iStart = ubrk_current(pCsr->pIter); + iEnd = ubrk_next(pCsr->pIter); + if( iEnd==UBRK_DONE ){ + return SQLITE_DONE; + } + + while( iStartaChar, iWhite, pCsr->nChar, c); + if( u_isspace(c) ){ + iStart = iWhite; + }else{ + break; + } + } + assert(iStart<=iEnd); + } + + do { + UErrorCode status = U_ZERO_ERROR; + if( nByte ){ + char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte); + if( !zNew ){ + return SQLITE_NOMEM; + } + pCsr->zBuffer = zNew; + pCsr->nBuffer = nByte; + } + + u_strToUTF8( + pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */ + &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */ + &status /* Output success/failure */ + ); + } while( nByte>pCsr->nBuffer ); + + *ppToken = pCsr->zBuffer; + *pnBytes = nByte; + *piStartOffset = pCsr->aOffset[iStart]; + *piEndOffset = pCsr->aOffset[iEnd]; + *piPosition = pCsr->iToken++; + + return SQLITE_OK; +} + +/* +** The set of routines that implement the simple tokenizer +*/ +static const sqlite3_tokenizer_module icuTokenizerModule = { + 0, /* iVersion */ + icuCreate, /* xCreate */ + icuDestroy, /* xCreate */ + icuOpen, /* xOpen */ + icuClose, /* xClose */ + icuNext, /* xNext */ +}; + +/* +** Set *ppModule to point at the implementation of the ICU tokenizer. +*/ +void sqlite3Fts3IcuTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &icuTokenizerModule; +} + +#endif /* defined(SQLITE_ENABLE_ICU) */ +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_porter.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_porter.c new file mode 100644 index 0000000000000000000000000000000000000000..579745b85f37750093ebc7453a935946c35aa390 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_porter.c @@ -0,0 +1,646 @@ +/* +** 2006 September 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Implementation of the full-text-search tokenizer that implements +** a Porter stemmer. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#include +#include +#include +#include + +#include "fts3_tokenizer.h" + +/* +** Class derived from sqlite3_tokenizer +*/ +typedef struct porter_tokenizer { + sqlite3_tokenizer base; /* Base class */ +} porter_tokenizer; + +/* +** Class derived from sqlite3_tokenizer_cursor +*/ +typedef struct porter_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *zInput; /* input we are tokenizing */ + int nInput; /* size of the input */ + int iOffset; /* current position in zInput */ + int iToken; /* index of next token to be returned */ + char *zToken; /* storage for current token */ + int nAllocated; /* space allocated to zToken buffer */ +} porter_tokenizer_cursor; + + +/* +** Create a new tokenizer instance. +*/ +static int porterCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer +){ + porter_tokenizer *t; + + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + + t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t)); + if( t==NULL ) return SQLITE_NOMEM; + memset(t, 0, sizeof(*t)); + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int porterDestroy(sqlite3_tokenizer *pTokenizer){ + sqlite3_free(pTokenizer); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is zInput[0..nInput-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int porterOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *zInput, int nInput, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + porter_tokenizer_cursor *c; + + UNUSED_PARAMETER(pTokenizer); + + c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); + if( c==NULL ) return SQLITE_NOMEM; + + c->zInput = zInput; + if( zInput==0 ){ + c->nInput = 0; + }else if( nInput<0 ){ + c->nInput = (int)strlen(zInput); + }else{ + c->nInput = nInput; + } + c->iOffset = 0; /* start tokenizing at the beginning */ + c->iToken = 0; + c->zToken = NULL; /* no space allocated, yet. */ + c->nAllocated = 0; + + *ppCursor = &c->base; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** porterOpen() above. +*/ +static int porterClose(sqlite3_tokenizer_cursor *pCursor){ + porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; + sqlite3_free(c->zToken); + sqlite3_free(c); + return SQLITE_OK; +} +/* +** Vowel or consonant +*/ +static const char cType[] = { + 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 2, 1 +}; + +/* +** isConsonant() and isVowel() determine if their first character in +** the string they point to is a consonant or a vowel, according +** to Porter ruls. +** +** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'. +** 'Y' is a consonant unless it follows another consonant, +** in which case it is a vowel. +** +** In these routine, the letters are in reverse order. So the 'y' rule +** is that 'y' is a consonant unless it is followed by another +** consonent. +*/ +static int isVowel(const char*); +static int isConsonant(const char *z){ + int j; + char x = *z; + if( x==0 ) return 0; + assert( x>='a' && x<='z' ); + j = cType[x-'a']; + if( j<2 ) return j; + return z[1]==0 || isVowel(z + 1); +} +static int isVowel(const char *z){ + int j; + char x = *z; + if( x==0 ) return 0; + assert( x>='a' && x<='z' ); + j = cType[x-'a']; + if( j<2 ) return 1-j; + return isConsonant(z + 1); +} + +/* +** Let any sequence of one or more vowels be represented by V and let +** C be sequence of one or more consonants. Then every word can be +** represented as: +** +** [C] (VC){m} [V] +** +** In prose: A word is an optional consonant followed by zero or +** vowel-consonant pairs followed by an optional vowel. "m" is the +** number of vowel consonant pairs. This routine computes the value +** of m for the first i bytes of a word. +** +** Return true if the m-value for z is 1 or more. In other words, +** return true if z contains at least one vowel that is followed +** by a consonant. +** +** In this routine z[] is in reverse order. So we are really looking +** for an instance of of a consonant followed by a vowel. +*/ +static int m_gt_0(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* Like mgt0 above except we are looking for a value of m which is +** exactly 1 +*/ +static int m_eq_1(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + if( *z==0 ) return 0; + while( isVowel(z) ){ z++; } + if( *z==0 ) return 1; + while( isConsonant(z) ){ z++; } + return *z==0; +} + +/* Like mgt0 above except we are looking for a value of m>1 instead +** or m>0 +*/ +static int m_gt_1(const char *z){ + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + if( *z==0 ) return 0; + while( isVowel(z) ){ z++; } + if( *z==0 ) return 0; + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* +** Return TRUE if there is a vowel anywhere within z[0..n-1] +*/ +static int hasVowel(const char *z){ + while( isConsonant(z) ){ z++; } + return *z!=0; +} + +/* +** Return TRUE if the word ends in a double consonant. +** +** The text is reversed here. So we are really looking at +** the first two characters of z[]. +*/ +static int doubleConsonant(const char *z){ + return isConsonant(z) && z[0]==z[1]; +} + +/* +** Return TRUE if the word ends with three letters which +** are consonant-vowel-consonent and where the final consonant +** is not 'w', 'x', or 'y'. +** +** The word is reversed here. So we are really checking the +** first three letters and the first one cannot be in [wxy]. +*/ +static int star_oh(const char *z){ + return + isConsonant(z) && + z[0]!='w' && z[0]!='x' && z[0]!='y' && + isVowel(z+1) && + isConsonant(z+2); +} + +/* +** If the word ends with zFrom and xCond() is true for the stem +** of the word that preceeds the zFrom ending, then change the +** ending to zTo. +** +** The input word *pz and zFrom are both in reverse order. zTo +** is in normal order. +** +** Return TRUE if zFrom matches. Return FALSE if zFrom does not +** match. Not that TRUE is returned even if xCond() fails and +** no substitution occurs. +*/ +static int stem( + char **pz, /* The word being stemmed (Reversed) */ + const char *zFrom, /* If the ending matches this... (Reversed) */ + const char *zTo, /* ... change the ending to this (not reversed) */ + int (*xCond)(const char*) /* Condition that must be true */ +){ + char *z = *pz; + while( *zFrom && *zFrom==*z ){ z++; zFrom++; } + if( *zFrom!=0 ) return 0; + if( xCond && !xCond(z) ) return 1; + while( *zTo ){ + *(--z) = *(zTo++); + } + *pz = z; + return 1; +} + +/* +** This is the fallback stemmer used when the porter stemmer is +** inappropriate. The input word is copied into the output with +** US-ASCII case folding. If the input word is too long (more +** than 20 bytes if it contains no digits or more than 6 bytes if +** it contains digits) then word is truncated to 20 or 6 bytes +** by taking 10 or 3 bytes from the beginning and end. +*/ +static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){ + int i, mx, j; + int hasDigit = 0; + for(i=0; i='A' && c<='Z' ){ + zOut[i] = c - 'A' + 'a'; + }else{ + if( c>='0' && c<='9' ) hasDigit = 1; + zOut[i] = c; + } + } + mx = hasDigit ? 3 : 10; + if( nIn>mx*2 ){ + for(j=mx, i=nIn-mx; i=(int)sizeof(zReverse)-7 ){ + /* The word is too big or too small for the porter stemmer. + ** Fallback to the copy stemmer */ + copy_stemmer(zIn, nIn, zOut, pnOut); + return; + } + for(i=0, j=sizeof(zReverse)-6; i='A' && c<='Z' ){ + zReverse[j] = c + 'a' - 'A'; + }else if( c>='a' && c<='z' ){ + zReverse[j] = c; + }else{ + /* The use of a character not in [a-zA-Z] means that we fallback + ** to the copy stemmer */ + copy_stemmer(zIn, nIn, zOut, pnOut); + return; + } + } + memset(&zReverse[sizeof(zReverse)-5], 0, 5); + z = &zReverse[j+1]; + + + /* Step 1a */ + if( z[0]=='s' ){ + if( + !stem(&z, "sess", "ss", 0) && + !stem(&z, "sei", "i", 0) && + !stem(&z, "ss", "ss", 0) + ){ + z++; + } + } + + /* Step 1b */ + z2 = z; + if( stem(&z, "dee", "ee", m_gt_0) ){ + /* Do nothing. The work was all in the test */ + }else if( + (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel)) + && z!=z2 + ){ + if( stem(&z, "ta", "ate", 0) || + stem(&z, "lb", "ble", 0) || + stem(&z, "zi", "ize", 0) ){ + /* Do nothing. The work was all in the test */ + }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){ + z++; + }else if( m_eq_1(z) && star_oh(z) ){ + *(--z) = 'e'; + } + } + + /* Step 1c */ + if( z[0]=='y' && hasVowel(z+1) ){ + z[0] = 'i'; + } + + /* Step 2 */ + switch( z[1] ){ + case 'a': + stem(&z, "lanoita", "ate", m_gt_0) || + stem(&z, "lanoit", "tion", m_gt_0); + break; + case 'c': + stem(&z, "icne", "ence", m_gt_0) || + stem(&z, "icna", "ance", m_gt_0); + break; + case 'e': + stem(&z, "rezi", "ize", m_gt_0); + break; + case 'g': + stem(&z, "igol", "log", m_gt_0); + break; + case 'l': + stem(&z, "ilb", "ble", m_gt_0) || + stem(&z, "illa", "al", m_gt_0) || + stem(&z, "iltne", "ent", m_gt_0) || + stem(&z, "ile", "e", m_gt_0) || + stem(&z, "ilsuo", "ous", m_gt_0); + break; + case 'o': + stem(&z, "noitazi", "ize", m_gt_0) || + stem(&z, "noita", "ate", m_gt_0) || + stem(&z, "rota", "ate", m_gt_0); + break; + case 's': + stem(&z, "msila", "al", m_gt_0) || + stem(&z, "ssenevi", "ive", m_gt_0) || + stem(&z, "ssenluf", "ful", m_gt_0) || + stem(&z, "ssensuo", "ous", m_gt_0); + break; + case 't': + stem(&z, "itila", "al", m_gt_0) || + stem(&z, "itivi", "ive", m_gt_0) || + stem(&z, "itilib", "ble", m_gt_0); + break; + } + + /* Step 3 */ + switch( z[0] ){ + case 'e': + stem(&z, "etaci", "ic", m_gt_0) || + stem(&z, "evita", "", m_gt_0) || + stem(&z, "ezila", "al", m_gt_0); + break; + case 'i': + stem(&z, "itici", "ic", m_gt_0); + break; + case 'l': + stem(&z, "laci", "ic", m_gt_0) || + stem(&z, "luf", "", m_gt_0); + break; + case 's': + stem(&z, "ssen", "", m_gt_0); + break; + } + + /* Step 4 */ + switch( z[1] ){ + case 'a': + if( z[0]=='l' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'c': + if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){ + z += 4; + } + break; + case 'e': + if( z[0]=='r' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'i': + if( z[0]=='c' && m_gt_1(z+2) ){ + z += 2; + } + break; + case 'l': + if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){ + z += 4; + } + break; + case 'n': + if( z[0]=='t' ){ + if( z[2]=='a' ){ + if( m_gt_1(z+3) ){ + z += 3; + } + }else if( z[2]=='e' ){ + stem(&z, "tneme", "", m_gt_1) || + stem(&z, "tnem", "", m_gt_1) || + stem(&z, "tne", "", m_gt_1); + } + } + break; + case 'o': + if( z[0]=='u' ){ + if( m_gt_1(z+2) ){ + z += 2; + } + }else if( z[3]=='s' || z[3]=='t' ){ + stem(&z, "noi", "", m_gt_1); + } + break; + case 's': + if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){ + z += 3; + } + break; + case 't': + stem(&z, "eta", "", m_gt_1) || + stem(&z, "iti", "", m_gt_1); + break; + case 'u': + if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){ + z += 3; + } + break; + case 'v': + case 'z': + if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){ + z += 3; + } + break; + } + + /* Step 5a */ + if( z[0]=='e' ){ + if( m_gt_1(z+1) ){ + z++; + }else if( m_eq_1(z+1) && !star_oh(z+1) ){ + z++; + } + } + + /* Step 5b */ + if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){ + z++; + } + + /* z[] is now the stemmed word in reverse order. Flip it back + ** around into forward order and return. + */ + *pnOut = i = (int)strlen(z); + zOut[i] = 0; + while( *z ){ + zOut[--i] = *(z++); + } +} + +/* +** Characters that can be part of a token. We assume any character +** whose value is greater than 0x80 (any UTF character) can be +** part of a token. In other words, delimiters all must have +** values of 0x7f or lower. +*/ +static const char porterIdChar[] = { +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ +}; +#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30])) + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to porterOpen(). +*/ +static int porterNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */ + const char **pzToken, /* OUT: *pzToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; + const char *z = c->zInput; + + while( c->iOffsetnInput ){ + int iStartOffset, ch; + + /* Scan past delimiter characters */ + while( c->iOffsetnInput && isDelim(z[c->iOffset]) ){ + c->iOffset++; + } + + /* Count non-delimiter characters. */ + iStartOffset = c->iOffset; + while( c->iOffsetnInput && !isDelim(z[c->iOffset]) ){ + c->iOffset++; + } + + if( c->iOffset>iStartOffset ){ + int n = c->iOffset-iStartOffset; + if( n>c->nAllocated ){ + char *pNew; + c->nAllocated = n+20; + pNew = sqlite3_realloc(c->zToken, c->nAllocated); + if( !pNew ) return SQLITE_NOMEM; + c->zToken = pNew; + } + porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes); + *pzToken = c->zToken; + *piStartOffset = iStartOffset; + *piEndOffset = c->iOffset; + *piPosition = c->iToken++; + return SQLITE_OK; + } + } + return SQLITE_DONE; +} + +/* +** The set of routines that implement the porter-stemmer tokenizer +*/ +static const sqlite3_tokenizer_module porterTokenizerModule = { + 0, + porterCreate, + porterDestroy, + porterOpen, + porterClose, + porterNext, + 0 +}; + +/* +** Allocate a new porter tokenizer. Return a pointer to the new +** tokenizer in *ppModule +*/ +void sqlite3Fts3PorterTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &porterTokenizerModule; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_snippet.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_snippet.c new file mode 100644 index 0000000000000000000000000000000000000000..3e62799bb75abce7b7127f1c78aafa81c77d08bd --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_snippet.c @@ -0,0 +1,1521 @@ +/* +** 2009 Oct 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +*/ + +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#include +#include + +/* +** Characters that may appear in the second argument to matchinfo(). +*/ +#define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */ +#define FTS3_MATCHINFO_NCOL 'c' /* 1 value */ +#define FTS3_MATCHINFO_NDOC 'n' /* 1 value */ +#define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */ +#define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */ +#define FTS3_MATCHINFO_LCS 's' /* nCol values */ +#define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */ + +/* +** The default value for the second argument to matchinfo(). +*/ +#define FTS3_MATCHINFO_DEFAULT "pcx" + + +/* +** Used as an fts3ExprIterate() context when loading phrase doclists to +** Fts3Expr.aDoclist[]/nDoclist. +*/ +typedef struct LoadDoclistCtx LoadDoclistCtx; +struct LoadDoclistCtx { + Fts3Cursor *pCsr; /* FTS3 Cursor */ + int nPhrase; /* Number of phrases seen so far */ + int nToken; /* Number of tokens seen so far */ +}; + +/* +** The following types are used as part of the implementation of the +** fts3BestSnippet() routine. +*/ +typedef struct SnippetIter SnippetIter; +typedef struct SnippetPhrase SnippetPhrase; +typedef struct SnippetFragment SnippetFragment; + +struct SnippetIter { + Fts3Cursor *pCsr; /* Cursor snippet is being generated from */ + int iCol; /* Extract snippet from this column */ + int nSnippet; /* Requested snippet length (in tokens) */ + int nPhrase; /* Number of phrases in query */ + SnippetPhrase *aPhrase; /* Array of size nPhrase */ + int iCurrent; /* First token of current snippet */ +}; + +struct SnippetPhrase { + int nToken; /* Number of tokens in phrase */ + char *pList; /* Pointer to start of phrase position list */ + int iHead; /* Next value in position list */ + char *pHead; /* Position list data following iHead */ + int iTail; /* Next value in trailing position list */ + char *pTail; /* Position list data following iTail */ +}; + +struct SnippetFragment { + int iCol; /* Column snippet is extracted from */ + int iPos; /* Index of first token in snippet */ + u64 covered; /* Mask of query phrases covered */ + u64 hlmask; /* Mask of snippet terms to highlight */ +}; + +/* +** This type is used as an fts3ExprIterate() context object while +** accumulating the data returned by the matchinfo() function. +*/ +typedef struct MatchInfo MatchInfo; +struct MatchInfo { + Fts3Cursor *pCursor; /* FTS3 Cursor */ + int nCol; /* Number of columns in table */ + int nPhrase; /* Number of matchable phrases in query */ + sqlite3_int64 nDoc; /* Number of docs in database */ + u32 *aMatchinfo; /* Pre-allocated buffer */ +}; + + + +/* +** The snippet() and offsets() functions both return text values. An instance +** of the following structure is used to accumulate those values while the +** functions are running. See fts3StringAppend() for details. +*/ +typedef struct StrBuffer StrBuffer; +struct StrBuffer { + char *z; /* Pointer to buffer containing string */ + int n; /* Length of z in bytes (excl. nul-term) */ + int nAlloc; /* Allocated size of buffer z in bytes */ +}; + + +/* +** This function is used to help iterate through a position-list. A position +** list is a list of unique integers, sorted from smallest to largest. Each +** element of the list is represented by an FTS3 varint that takes the value +** of the difference between the current element and the previous one plus +** two. For example, to store the position-list: +** +** 4 9 113 +** +** the three varints: +** +** 6 7 106 +** +** are encoded. +** +** When this function is called, *pp points to the start of an element of +** the list. *piPos contains the value of the previous entry in the list. +** After it returns, *piPos contains the value of the next element of the +** list and *pp is advanced to the following varint. +*/ +static void fts3GetDeltaPosition(char **pp, int *piPos){ + int iVal; + *pp += sqlite3Fts3GetVarint32(*pp, &iVal); + *piPos += (iVal-2); +} + +/* +** Helper function for fts3ExprIterate() (see below). +*/ +static int fts3ExprIterate2( + Fts3Expr *pExpr, /* Expression to iterate phrases of */ + int *piPhrase, /* Pointer to phrase counter */ + int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ + void *pCtx /* Second argument to pass to callback */ +){ + int rc; /* Return code */ + int eType = pExpr->eType; /* Type of expression node pExpr */ + + if( eType!=FTSQUERY_PHRASE ){ + assert( pExpr->pLeft && pExpr->pRight ); + rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx); + if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){ + rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx); + } + }else{ + rc = x(pExpr, *piPhrase, pCtx); + (*piPhrase)++; + } + return rc; +} + +/* +** Iterate through all phrase nodes in an FTS3 query, except those that +** are part of a sub-tree that is the right-hand-side of a NOT operator. +** For each phrase node found, the supplied callback function is invoked. +** +** If the callback function returns anything other than SQLITE_OK, +** the iteration is abandoned and the error code returned immediately. +** Otherwise, SQLITE_OK is returned after a callback has been made for +** all eligible phrase nodes. +*/ +static int fts3ExprIterate( + Fts3Expr *pExpr, /* Expression to iterate phrases of */ + int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ + void *pCtx /* Second argument to pass to callback */ +){ + int iPhrase = 0; /* Variable used as the phrase counter */ + return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx); +} + +/* +** This is an fts3ExprIterate() callback used while loading the doclists +** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also +** fts3ExprLoadDoclists(). +*/ +static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ + int rc = SQLITE_OK; + Fts3Phrase *pPhrase = pExpr->pPhrase; + LoadDoclistCtx *p = (LoadDoclistCtx *)ctx; + + UNUSED_PARAMETER(iPhrase); + + p->nPhrase++; + p->nToken += pPhrase->nToken; + + return rc; +} + +/* +** Load the doclists for each phrase in the query associated with FTS3 cursor +** pCsr. +** +** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable +** phrases in the expression (all phrases except those directly or +** indirectly descended from the right-hand-side of a NOT operator). If +** pnToken is not NULL, then it is set to the number of tokens in all +** matchable phrases of the expression. +*/ +static int fts3ExprLoadDoclists( + Fts3Cursor *pCsr, /* Fts3 cursor for current query */ + int *pnPhrase, /* OUT: Number of phrases in query */ + int *pnToken /* OUT: Number of tokens in query */ +){ + int rc; /* Return Code */ + LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */ + sCtx.pCsr = pCsr; + rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx); + if( pnPhrase ) *pnPhrase = sCtx.nPhrase; + if( pnToken ) *pnToken = sCtx.nToken; + return rc; +} + +static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ + (*(int *)ctx)++; + UNUSED_PARAMETER(pExpr); + UNUSED_PARAMETER(iPhrase); + return SQLITE_OK; +} +static int fts3ExprPhraseCount(Fts3Expr *pExpr){ + int nPhrase = 0; + (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase); + return nPhrase; +} + +/* +** Advance the position list iterator specified by the first two +** arguments so that it points to the first element with a value greater +** than or equal to parameter iNext. +*/ +static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){ + char *pIter = *ppIter; + if( pIter ){ + int iIter = *piIter; + + while( iIteriCurrent<0 ){ + /* The SnippetIter object has just been initialized. The first snippet + ** candidate always starts at offset 0 (even if this candidate has a + ** score of 0.0). + */ + pIter->iCurrent = 0; + + /* Advance the 'head' iterator of each phrase to the first offset that + ** is greater than or equal to (iNext+nSnippet). + */ + for(i=0; inPhrase; i++){ + SnippetPhrase *pPhrase = &pIter->aPhrase[i]; + fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet); + } + }else{ + int iStart; + int iEnd = 0x7FFFFFFF; + + for(i=0; inPhrase; i++){ + SnippetPhrase *pPhrase = &pIter->aPhrase[i]; + if( pPhrase->pHead && pPhrase->iHeadiHead; + } + } + if( iEnd==0x7FFFFFFF ){ + return 1; + } + + pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1; + for(i=0; inPhrase; i++){ + SnippetPhrase *pPhrase = &pIter->aPhrase[i]; + fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1); + fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart); + } + } + + return 0; +} + +/* +** Retrieve information about the current candidate snippet of snippet +** iterator pIter. +*/ +static void fts3SnippetDetails( + SnippetIter *pIter, /* Snippet iterator */ + u64 mCovered, /* Bitmask of phrases already covered */ + int *piToken, /* OUT: First token of proposed snippet */ + int *piScore, /* OUT: "Score" for this snippet */ + u64 *pmCover, /* OUT: Bitmask of phrases covered */ + u64 *pmHighlight /* OUT: Bitmask of terms to highlight */ +){ + int iStart = pIter->iCurrent; /* First token of snippet */ + int iScore = 0; /* Score of this snippet */ + int i; /* Loop counter */ + u64 mCover = 0; /* Mask of phrases covered by this snippet */ + u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */ + + for(i=0; inPhrase; i++){ + SnippetPhrase *pPhrase = &pIter->aPhrase[i]; + if( pPhrase->pTail ){ + char *pCsr = pPhrase->pTail; + int iCsr = pPhrase->iTail; + + while( iCsr<(iStart+pIter->nSnippet) ){ + int j; + u64 mPhrase = (u64)1 << i; + u64 mPos = (u64)1 << (iCsr - iStart); + assert( iCsr>=iStart ); + if( (mCover|mCovered)&mPhrase ){ + iScore++; + }else{ + iScore += 1000; + } + mCover |= mPhrase; + + for(j=0; jnToken; j++){ + mHighlight |= (mPos>>j); + } + + if( 0==(*pCsr & 0x0FE) ) break; + fts3GetDeltaPosition(&pCsr, &iCsr); + } + } + } + + /* Set the output variables before returning. */ + *piToken = iStart; + *piScore = iScore; + *pmCover = mCover; + *pmHighlight = mHighlight; +} + +/* +** This function is an fts3ExprIterate() callback used by fts3BestSnippet(). +** Each invocation populates an element of the SnippetIter.aPhrase[] array. +*/ +static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){ + SnippetIter *p = (SnippetIter *)ctx; + SnippetPhrase *pPhrase = &p->aPhrase[iPhrase]; + char *pCsr; + int rc; + + pPhrase->nToken = pExpr->pPhrase->nToken; + rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr); + assert( rc==SQLITE_OK || pCsr==0 ); + if( pCsr ){ + int iFirst = 0; + pPhrase->pList = pCsr; + fts3GetDeltaPosition(&pCsr, &iFirst); + assert( iFirst>=0 ); + pPhrase->pHead = pCsr; + pPhrase->pTail = pCsr; + pPhrase->iHead = iFirst; + pPhrase->iTail = iFirst; + }else{ + assert( rc!=SQLITE_OK || ( + pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 + )); + } + + return rc; +} + +/* +** Select the fragment of text consisting of nFragment contiguous tokens +** from column iCol that represent the "best" snippet. The best snippet +** is the snippet with the highest score, where scores are calculated +** by adding: +** +** (a) +1 point for each occurrence of a matchable phrase in the snippet. +** +** (b) +1000 points for the first occurrence of each matchable phrase in +** the snippet for which the corresponding mCovered bit is not set. +** +** The selected snippet parameters are stored in structure *pFragment before +** returning. The score of the selected snippet is stored in *piScore +** before returning. +*/ +static int fts3BestSnippet( + int nSnippet, /* Desired snippet length */ + Fts3Cursor *pCsr, /* Cursor to create snippet for */ + int iCol, /* Index of column to create snippet from */ + u64 mCovered, /* Mask of phrases already covered */ + u64 *pmSeen, /* IN/OUT: Mask of phrases seen */ + SnippetFragment *pFragment, /* OUT: Best snippet found */ + int *piScore /* OUT: Score of snippet pFragment */ +){ + int rc; /* Return Code */ + int nList; /* Number of phrases in expression */ + SnippetIter sIter; /* Iterates through snippet candidates */ + int nByte; /* Number of bytes of space to allocate */ + int iBestScore = -1; /* Best snippet score found so far */ + int i; /* Loop counter */ + + memset(&sIter, 0, sizeof(sIter)); + + /* Iterate through the phrases in the expression to count them. The same + ** callback makes sure the doclists are loaded for each phrase. + */ + rc = fts3ExprLoadDoclists(pCsr, &nList, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Now that it is known how many phrases there are, allocate and zero + ** the required space using malloc(). + */ + nByte = sizeof(SnippetPhrase) * nList; + sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte); + if( !sIter.aPhrase ){ + return SQLITE_NOMEM; + } + memset(sIter.aPhrase, 0, nByte); + + /* Initialize the contents of the SnippetIter object. Then iterate through + ** the set of phrases in the expression to populate the aPhrase[] array. + */ + sIter.pCsr = pCsr; + sIter.iCol = iCol; + sIter.nSnippet = nSnippet; + sIter.nPhrase = nList; + sIter.iCurrent = -1; + (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter); + + /* Set the *pmSeen output variable. */ + for(i=0; iiCol = iCol; + while( !fts3SnippetNextCandidate(&sIter) ){ + int iPos; + int iScore; + u64 mCover; + u64 mHighlight; + fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight); + assert( iScore>=0 ); + if( iScore>iBestScore ){ + pFragment->iPos = iPos; + pFragment->hlmask = mHighlight; + pFragment->covered = mCover; + iBestScore = iScore; + } + } + + sqlite3_free(sIter.aPhrase); + *piScore = iBestScore; + return SQLITE_OK; +} + + +/* +** Append a string to the string-buffer passed as the first argument. +** +** If nAppend is negative, then the length of the string zAppend is +** determined using strlen(). +*/ +static int fts3StringAppend( + StrBuffer *pStr, /* Buffer to append to */ + const char *zAppend, /* Pointer to data to append to buffer */ + int nAppend /* Size of zAppend in bytes (or -1) */ +){ + if( nAppend<0 ){ + nAppend = (int)strlen(zAppend); + } + + /* If there is insufficient space allocated at StrBuffer.z, use realloc() + ** to grow the buffer until so that it is big enough to accomadate the + ** appended data. + */ + if( pStr->n+nAppend+1>=pStr->nAlloc ){ + int nAlloc = pStr->nAlloc+nAppend+100; + char *zNew = sqlite3_realloc(pStr->z, nAlloc); + if( !zNew ){ + return SQLITE_NOMEM; + } + pStr->z = zNew; + pStr->nAlloc = nAlloc; + } + assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) ); + + /* Append the data to the string buffer. */ + memcpy(&pStr->z[pStr->n], zAppend, nAppend); + pStr->n += nAppend; + pStr->z[pStr->n] = '\0'; + + return SQLITE_OK; +} + +/* +** The fts3BestSnippet() function often selects snippets that end with a +** query term. That is, the final term of the snippet is always a term +** that requires highlighting. For example, if 'X' is a highlighted term +** and '.' is a non-highlighted term, BestSnippet() may select: +** +** ........X.....X +** +** This function "shifts" the beginning of the snippet forward in the +** document so that there are approximately the same number of +** non-highlighted terms to the right of the final highlighted term as there +** are to the left of the first highlighted term. For example, to this: +** +** ....X.....X.... +** +** This is done as part of extracting the snippet text, not when selecting +** the snippet. Snippet selection is done based on doclists only, so there +** is no way for fts3BestSnippet() to know whether or not the document +** actually contains terms that follow the final highlighted term. +*/ +static int fts3SnippetShift( + Fts3Table *pTab, /* FTS3 table snippet comes from */ + int iLangid, /* Language id to use in tokenizing */ + int nSnippet, /* Number of tokens desired for snippet */ + const char *zDoc, /* Document text to extract snippet from */ + int nDoc, /* Size of buffer zDoc in bytes */ + int *piPos, /* IN/OUT: First token of snippet */ + u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */ +){ + u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */ + + if( hlmask ){ + int nLeft; /* Tokens to the left of first highlight */ + int nRight; /* Tokens to the right of last highlight */ + int nDesired; /* Ideal number of tokens to shift forward */ + + for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++); + for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++); + nDesired = (nLeft-nRight)/2; + + /* Ideally, the start of the snippet should be pushed forward in the + ** document nDesired tokens. This block checks if there are actually + ** nDesired tokens to the right of the snippet. If so, *piPos and + ** *pHlMask are updated to shift the snippet nDesired tokens to the + ** right. Otherwise, the snippet is shifted by the number of tokens + ** available. + */ + if( nDesired>0 ){ + int nShift; /* Number of tokens to shift snippet by */ + int iCurrent = 0; /* Token counter */ + int rc; /* Return Code */ + sqlite3_tokenizer_module *pMod; + sqlite3_tokenizer_cursor *pC; + pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; + + /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired) + ** or more tokens in zDoc/nDoc. + */ + rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC); + if( rc!=SQLITE_OK ){ + return rc; + } + while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){ + const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0; + rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent); + } + pMod->xClose(pC); + if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; } + + nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet; + assert( nShift<=nDesired ); + if( nShift>0 ){ + *piPos += nShift; + *pHlmask = hlmask >> nShift; + } + } + } + return SQLITE_OK; +} + +/* +** Extract the snippet text for fragment pFragment from cursor pCsr and +** append it to string buffer pOut. +*/ +static int fts3SnippetText( + Fts3Cursor *pCsr, /* FTS3 Cursor */ + SnippetFragment *pFragment, /* Snippet to extract */ + int iFragment, /* Fragment number */ + int isLast, /* True for final fragment in snippet */ + int nSnippet, /* Number of tokens in extracted snippet */ + const char *zOpen, /* String inserted before highlighted term */ + const char *zClose, /* String inserted after highlighted term */ + const char *zEllipsis, /* String inserted between snippets */ + StrBuffer *pOut /* Write output here */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc; /* Return code */ + const char *zDoc; /* Document text to extract snippet from */ + int nDoc; /* Size of zDoc in bytes */ + int iCurrent = 0; /* Current token number of document */ + int iEnd = 0; /* Byte offset of end of current token */ + int isShiftDone = 0; /* True after snippet is shifted */ + int iPos = pFragment->iPos; /* First token of snippet */ + u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */ + int iCol = pFragment->iCol+1; /* Query column to extract text from */ + sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */ + sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */ + + zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol); + if( zDoc==0 ){ + if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){ + return SQLITE_NOMEM; + } + return SQLITE_OK; + } + nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol); + + /* Open a token cursor on the document. */ + pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; + rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC); + if( rc!=SQLITE_OK ){ + return rc; + } + + while( rc==SQLITE_OK ){ + const char *ZDUMMY; /* Dummy argument used with tokenizer */ + int DUMMY1 = -1; /* Dummy argument used with tokenizer */ + int iBegin = 0; /* Offset in zDoc of start of token */ + int iFin = 0; /* Offset in zDoc of end of token */ + int isHighlight = 0; /* True for highlighted terms */ + + /* Variable DUMMY1 is initialized to a negative value above. Elsewhere + ** in the FTS code the variable that the third argument to xNext points to + ** is initialized to zero before the first (*but not necessarily + ** subsequent*) call to xNext(). This is done for a particular application + ** that needs to know whether or not the tokenizer is being used for + ** snippet generation or for some other purpose. + ** + ** Extreme care is required when writing code to depend on this + ** initialization. It is not a documented part of the tokenizer interface. + ** If a tokenizer is used directly by any code outside of FTS, this + ** convention might not be respected. */ + rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_DONE ){ + /* Special case - the last token of the snippet is also the last token + ** of the column. Append any punctuation that occurred between the end + ** of the previous token and the end of the document to the output. + ** Then break out of the loop. */ + rc = fts3StringAppend(pOut, &zDoc[iEnd], -1); + } + break; + } + if( iCurrentiLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask + ); + isShiftDone = 1; + + /* Now that the shift has been done, check if the initial "..." are + ** required. They are required if (a) this is not the first fragment, + ** or (b) this fragment does not begin at position 0 of its column. + */ + if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){ + rc = fts3StringAppend(pOut, zEllipsis, -1); + } + if( rc!=SQLITE_OK || iCurrent=(iPos+nSnippet) ){ + if( isLast ){ + rc = fts3StringAppend(pOut, zEllipsis, -1); + } + break; + } + + /* Set isHighlight to true if this term should be highlighted. */ + isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0; + + if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd); + if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1); + if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin); + if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1); + + iEnd = iFin; + } + + pMod->xClose(pC); + return rc; +} + + +/* +** This function is used to count the entries in a column-list (a +** delta-encoded list of term offsets within a single column of a single +** row). When this function is called, *ppCollist should point to the +** beginning of the first varint in the column-list (the varint that +** contains the position of the first matching term in the column data). +** Before returning, *ppCollist is set to point to the first byte after +** the last varint in the column-list (either the 0x00 signifying the end +** of the position-list, or the 0x01 that precedes the column number of +** the next column in the position-list). +** +** The number of elements in the column-list is returned. +*/ +static int fts3ColumnlistCount(char **ppCollist){ + char *pEnd = *ppCollist; + char c = 0; + int nEntry = 0; + + /* A column-list is terminated by either a 0x01 or 0x00. */ + while( 0xFE & (*pEnd | c) ){ + c = *pEnd++ & 0x80; + if( !c ) nEntry++; + } + + *ppCollist = pEnd; + return nEntry; +} + +/* +** fts3ExprIterate() callback used to collect the "global" matchinfo stats +** for a single query. +** +** fts3ExprIterate() callback to load the 'global' elements of a +** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements +** of the matchinfo array that are constant for all rows returned by the +** current query. +** +** Argument pCtx is actually a pointer to a struct of type MatchInfo. This +** function populates Matchinfo.aMatchinfo[] as follows: +** +** for(iCol=0; iColpCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol] + ); +} + +/* +** fts3ExprIterate() callback used to collect the "local" part of the +** FTS3_MATCHINFO_HITS array. The local stats are those elements of the +** array that are different for each row returned by the query. +*/ +static int fts3ExprLocalHitsCb( + Fts3Expr *pExpr, /* Phrase expression node */ + int iPhrase, /* Phrase number */ + void *pCtx /* Pointer to MatchInfo structure */ +){ + int rc = SQLITE_OK; + MatchInfo *p = (MatchInfo *)pCtx; + int iStart = iPhrase * p->nCol * 3; + int i; + + for(i=0; inCol && rc==SQLITE_OK; i++){ + char *pCsr; + rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr); + if( pCsr ){ + p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr); + }else{ + p->aMatchinfo[iStart+i*3] = 0; + } + } + + return rc; +} + +static int fts3MatchinfoCheck( + Fts3Table *pTab, + char cArg, + char **pzErr +){ + if( (cArg==FTS3_MATCHINFO_NPHRASE) + || (cArg==FTS3_MATCHINFO_NCOL) + || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4) + || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4) + || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize) + || (cArg==FTS3_MATCHINFO_LCS) + || (cArg==FTS3_MATCHINFO_HITS) + ){ + return SQLITE_OK; + } + *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg); + return SQLITE_ERROR; +} + +static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ + int nVal; /* Number of integers output by cArg */ + + switch( cArg ){ + case FTS3_MATCHINFO_NDOC: + case FTS3_MATCHINFO_NPHRASE: + case FTS3_MATCHINFO_NCOL: + nVal = 1; + break; + + case FTS3_MATCHINFO_AVGLENGTH: + case FTS3_MATCHINFO_LENGTH: + case FTS3_MATCHINFO_LCS: + nVal = pInfo->nCol; + break; + + default: + assert( cArg==FTS3_MATCHINFO_HITS ); + nVal = pInfo->nCol * pInfo->nPhrase * 3; + break; + } + + return nVal; +} + +static int fts3MatchinfoSelectDoctotal( + Fts3Table *pTab, + sqlite3_stmt **ppStmt, + sqlite3_int64 *pnDoc, + const char **paLen +){ + sqlite3_stmt *pStmt; + const char *a; + sqlite3_int64 nDoc; + + if( !*ppStmt ){ + int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt); + if( rc!=SQLITE_OK ) return rc; + } + pStmt = *ppStmt; + assert( sqlite3_data_count(pStmt)==1 ); + + a = sqlite3_column_blob(pStmt, 0); + a += sqlite3Fts3GetVarint(a, &nDoc); + if( nDoc==0 ) return FTS_CORRUPT_VTAB; + *pnDoc = (u32)nDoc; + + if( paLen ) *paLen = a; + return SQLITE_OK; +} + +/* +** An instance of the following structure is used to store state while +** iterating through a multi-column position-list corresponding to the +** hits for a single phrase on a single row in order to calculate the +** values for a matchinfo() FTS3_MATCHINFO_LCS request. +*/ +typedef struct LcsIterator LcsIterator; +struct LcsIterator { + Fts3Expr *pExpr; /* Pointer to phrase expression */ + int iPosOffset; /* Tokens count up to end of this phrase */ + char *pRead; /* Cursor used to iterate through aDoclist */ + int iPos; /* Current position */ +}; + +/* +** If LcsIterator.iCol is set to the following value, the iterator has +** finished iterating through all offsets for all columns. +*/ +#define LCS_ITERATOR_FINISHED 0x7FFFFFFF; + +static int fts3MatchinfoLcsCb( + Fts3Expr *pExpr, /* Phrase expression node */ + int iPhrase, /* Phrase number (numbered from zero) */ + void *pCtx /* Pointer to MatchInfo structure */ +){ + LcsIterator *aIter = (LcsIterator *)pCtx; + aIter[iPhrase].pExpr = pExpr; + return SQLITE_OK; +} + +/* +** Advance the iterator passed as an argument to the next position. Return +** 1 if the iterator is at EOF or if it now points to the start of the +** position list for the next column. +*/ +static int fts3LcsIteratorAdvance(LcsIterator *pIter){ + char *pRead = pIter->pRead; + sqlite3_int64 iRead; + int rc = 0; + + pRead += sqlite3Fts3GetVarint(pRead, &iRead); + if( iRead==0 || iRead==1 ){ + pRead = 0; + rc = 1; + }else{ + pIter->iPos += (int)(iRead-2); + } + + pIter->pRead = pRead; + return rc; +} + +/* +** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. +** +** If the call is successful, the longest-common-substring lengths for each +** column are written into the first nCol elements of the pInfo->aMatchinfo[] +** array before returning. SQLITE_OK is returned in this case. +** +** Otherwise, if an error occurs, an SQLite error code is returned and the +** data written to the first nCol elements of pInfo->aMatchinfo[] is +** undefined. +*/ +static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){ + LcsIterator *aIter; + int i; + int iCol; + int nToken = 0; + + /* Allocate and populate the array of LcsIterator objects. The array + ** contains one element for each matchable phrase in the query. + **/ + aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase); + if( !aIter ) return SQLITE_NOMEM; + memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase); + (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter); + + for(i=0; inPhrase; i++){ + LcsIterator *pIter = &aIter[i]; + nToken -= pIter->pExpr->pPhrase->nToken; + pIter->iPosOffset = nToken; + } + + for(iCol=0; iColnCol; iCol++){ + int nLcs = 0; /* LCS value for this column */ + int nLive = 0; /* Number of iterators in aIter not at EOF */ + + for(i=0; inPhrase; i++){ + int rc; + LcsIterator *pIt = &aIter[i]; + rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead); + if( rc!=SQLITE_OK ) return rc; + if( pIt->pRead ){ + pIt->iPos = pIt->iPosOffset; + fts3LcsIteratorAdvance(&aIter[i]); + nLive++; + } + } + + while( nLive>0 ){ + LcsIterator *pAdv = 0; /* The iterator to advance by one position */ + int nThisLcs = 0; /* LCS for the current iterator positions */ + + for(i=0; inPhrase; i++){ + LcsIterator *pIter = &aIter[i]; + if( pIter->pRead==0 ){ + /* This iterator is already at EOF for this column. */ + nThisLcs = 0; + }else{ + if( pAdv==0 || pIter->iPosiPos ){ + pAdv = pIter; + } + if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){ + nThisLcs++; + }else{ + nThisLcs = 1; + } + if( nThisLcs>nLcs ) nLcs = nThisLcs; + } + } + if( fts3LcsIteratorAdvance(pAdv) ) nLive--; + } + + pInfo->aMatchinfo[iCol] = nLcs; + } + + sqlite3_free(aIter); + return SQLITE_OK; +} + +/* +** Populate the buffer pInfo->aMatchinfo[] with an array of integers to +** be returned by the matchinfo() function. Argument zArg contains the +** format string passed as the second argument to matchinfo (or the +** default value "pcx" if no second argument was specified). The format +** string has already been validated and the pInfo->aMatchinfo[] array +** is guaranteed to be large enough for the output. +** +** If bGlobal is true, then populate all fields of the matchinfo() output. +** If it is false, then assume that those fields that do not change between +** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS) +** have already been populated. +** +** Return SQLITE_OK if successful, or an SQLite error code if an error +** occurs. If a value other than SQLITE_OK is returned, the state the +** pInfo->aMatchinfo[] buffer is left in is undefined. +*/ +static int fts3MatchinfoValues( + Fts3Cursor *pCsr, /* FTS3 cursor object */ + int bGlobal, /* True to grab the global stats */ + MatchInfo *pInfo, /* Matchinfo context object */ + const char *zArg /* Matchinfo format string */ +){ + int rc = SQLITE_OK; + int i; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + sqlite3_stmt *pSelect = 0; + + for(i=0; rc==SQLITE_OK && zArg[i]; i++){ + + switch( zArg[i] ){ + case FTS3_MATCHINFO_NPHRASE: + if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase; + break; + + case FTS3_MATCHINFO_NCOL: + if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol; + break; + + case FTS3_MATCHINFO_NDOC: + if( bGlobal ){ + sqlite3_int64 nDoc = 0; + rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0); + pInfo->aMatchinfo[0] = (u32)nDoc; + } + break; + + case FTS3_MATCHINFO_AVGLENGTH: + if( bGlobal ){ + sqlite3_int64 nDoc; /* Number of rows in table */ + const char *a; /* Aggregate column length array */ + + rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a); + if( rc==SQLITE_OK ){ + int iCol; + for(iCol=0; iColnCol; iCol++){ + u32 iVal; + sqlite3_int64 nToken; + a += sqlite3Fts3GetVarint(a, &nToken); + iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc); + pInfo->aMatchinfo[iCol] = iVal; + } + } + } + break; + + case FTS3_MATCHINFO_LENGTH: { + sqlite3_stmt *pSelectDocsize = 0; + rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize); + if( rc==SQLITE_OK ){ + int iCol; + const char *a = sqlite3_column_blob(pSelectDocsize, 0); + for(iCol=0; iColnCol; iCol++){ + sqlite3_int64 nToken; + a += sqlite3Fts3GetVarint(a, &nToken); + pInfo->aMatchinfo[iCol] = (u32)nToken; + } + } + sqlite3_reset(pSelectDocsize); + break; + } + + case FTS3_MATCHINFO_LCS: + rc = fts3ExprLoadDoclists(pCsr, 0, 0); + if( rc==SQLITE_OK ){ + rc = fts3MatchinfoLcs(pCsr, pInfo); + } + break; + + default: { + Fts3Expr *pExpr; + assert( zArg[i]==FTS3_MATCHINFO_HITS ); + pExpr = pCsr->pExpr; + rc = fts3ExprLoadDoclists(pCsr, 0, 0); + if( rc!=SQLITE_OK ) break; + if( bGlobal ){ + if( pCsr->pDeferred ){ + rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0); + if( rc!=SQLITE_OK ) break; + } + rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo); + if( rc!=SQLITE_OK ) break; + } + (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo); + break; + } + } + + pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]); + } + + sqlite3_reset(pSelect); + return rc; +} + + +/* +** Populate pCsr->aMatchinfo[] with data for the current row. The +** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32). +*/ +static int fts3GetMatchinfo( + Fts3Cursor *pCsr, /* FTS3 Cursor object */ + const char *zArg /* Second argument to matchinfo() function */ +){ + MatchInfo sInfo; + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; + int bGlobal = 0; /* Collect 'global' stats as well as local */ + + memset(&sInfo, 0, sizeof(MatchInfo)); + sInfo.pCursor = pCsr; + sInfo.nCol = pTab->nColumn; + + /* If there is cached matchinfo() data, but the format string for the + ** cache does not match the format string for this request, discard + ** the cached data. */ + if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){ + assert( pCsr->aMatchinfo ); + sqlite3_free(pCsr->aMatchinfo); + pCsr->zMatchinfo = 0; + pCsr->aMatchinfo = 0; + } + + /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the + ** matchinfo function has been called for this query. In this case + ** allocate the array used to accumulate the matchinfo data and + ** initialize those elements that are constant for every row. + */ + if( pCsr->aMatchinfo==0 ){ + int nMatchinfo = 0; /* Number of u32 elements in match-info */ + int nArg; /* Bytes in zArg */ + int i; /* Used to iterate through zArg */ + + /* Determine the number of phrases in the query */ + pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr); + sInfo.nPhrase = pCsr->nPhrase; + + /* Determine the number of integers in the buffer returned by this call. */ + for(i=0; zArg[i]; i++){ + nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]); + } + + /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */ + nArg = (int)strlen(zArg); + pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1); + if( !pCsr->aMatchinfo ) return SQLITE_NOMEM; + + pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo]; + pCsr->nMatchinfo = nMatchinfo; + memcpy(pCsr->zMatchinfo, zArg, nArg+1); + memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo); + pCsr->isMatchinfoNeeded = 1; + bGlobal = 1; + } + + sInfo.aMatchinfo = pCsr->aMatchinfo; + sInfo.nPhrase = pCsr->nPhrase; + if( pCsr->isMatchinfoNeeded ){ + rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg); + pCsr->isMatchinfoNeeded = 0; + } + + return rc; +} + +/* +** Implementation of snippet() function. +*/ +void sqlite3Fts3Snippet( + sqlite3_context *pCtx, /* SQLite function call context */ + Fts3Cursor *pCsr, /* Cursor object */ + const char *zStart, /* Snippet start text - "" */ + const char *zEnd, /* Snippet end text - "" */ + const char *zEllipsis, /* Snippet ellipsis text - "..." */ + int iCol, /* Extract snippet from this column */ + int nToken /* Approximate number of tokens in snippet */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc = SQLITE_OK; + int i; + StrBuffer res = {0, 0, 0}; + + /* The returned text includes up to four fragments of text extracted from + ** the data in the current row. The first iteration of the for(...) loop + ** below attempts to locate a single fragment of text nToken tokens in + ** size that contains at least one instance of all phrases in the query + ** expression that appear in the current row. If such a fragment of text + ** cannot be found, the second iteration of the loop attempts to locate + ** a pair of fragments, and so on. + */ + int nSnippet = 0; /* Number of fragments in this snippet */ + SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */ + int nFToken = -1; /* Number of tokens in each fragment */ + + if( !pCsr->pExpr ){ + sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); + return; + } + + for(nSnippet=1; 1; nSnippet++){ + + int iSnip; /* Loop counter 0..nSnippet-1 */ + u64 mCovered = 0; /* Bitmask of phrases covered by snippet */ + u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */ + + if( nToken>=0 ){ + nFToken = (nToken+nSnippet-1) / nSnippet; + }else{ + nFToken = -1 * nToken; + } + + for(iSnip=0; iSnipnColumn; iRead++){ + SnippetFragment sF = {0, 0, 0, 0}; + int iS; + if( iCol>=0 && iRead!=iCol ) continue; + + /* Find the best snippet of nFToken tokens in column iRead. */ + rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS); + if( rc!=SQLITE_OK ){ + goto snippet_out; + } + if( iS>iBestScore ){ + *pFragment = sF; + iBestScore = iS; + } + } + + mCovered |= pFragment->covered; + } + + /* If all query phrases seen by fts3BestSnippet() are present in at least + ** one of the nSnippet snippet fragments, break out of the loop. + */ + assert( (mCovered&mSeen)==mCovered ); + if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break; + } + + assert( nFToken>0 ); + + for(i=0; ipCsr, pExpr, p->iCol, &pList); + nTerm = pExpr->pPhrase->nToken; + if( pList ){ + fts3GetDeltaPosition(&pList, &iPos); + assert( iPos>=0 ); + } + + for(iTerm=0; iTermaTerm[p->iTerm++]; + pT->iOff = nTerm-iTerm-1; + pT->pList = pList; + pT->iPos = iPos; + } + + return rc; +} + +/* +** Implementation of offsets() function. +*/ +void sqlite3Fts3Offsets( + sqlite3_context *pCtx, /* SQLite function call context */ + Fts3Cursor *pCsr /* Cursor object */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule; + int rc; /* Return Code */ + int nToken; /* Number of tokens in query */ + int iCol; /* Column currently being processed */ + StrBuffer res = {0, 0, 0}; /* Result string */ + TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */ + + if( !pCsr->pExpr ){ + sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); + return; + } + + memset(&sCtx, 0, sizeof(sCtx)); + assert( pCsr->isRequireSeek==0 ); + + /* Count the number of terms in the query */ + rc = fts3ExprLoadDoclists(pCsr, 0, &nToken); + if( rc!=SQLITE_OK ) goto offsets_out; + + /* Allocate the array of TermOffset iterators. */ + sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken); + if( 0==sCtx.aTerm ){ + rc = SQLITE_NOMEM; + goto offsets_out; + } + sCtx.iDocid = pCsr->iPrevId; + sCtx.pCsr = pCsr; + + /* Loop through the table columns, appending offset information to + ** string-buffer res for each column. + */ + for(iCol=0; iColnColumn; iCol++){ + sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */ + const char *ZDUMMY; /* Dummy argument used with xNext() */ + int NDUMMY = 0; /* Dummy argument used with xNext() */ + int iStart = 0; + int iEnd = 0; + int iCurrent = 0; + const char *zDoc; + int nDoc; + + /* Initialize the contents of sCtx.aTerm[] for column iCol. There is + ** no way that this operation can fail, so the return code from + ** fts3ExprIterate() can be discarded. + */ + sCtx.iCol = iCol; + sCtx.iTerm = 0; + (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx); + + /* Retreive the text stored in column iCol. If an SQL NULL is stored + ** in column iCol, jump immediately to the next iteration of the loop. + ** If an OOM occurs while retrieving the data (this can happen if SQLite + ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM + ** to the caller. + */ + zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1); + nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1); + if( zDoc==0 ){ + if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){ + continue; + } + rc = SQLITE_NOMEM; + goto offsets_out; + } + + /* Initialize a tokenizer iterator to iterate through column iCol. */ + rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, + zDoc, nDoc, &pC + ); + if( rc!=SQLITE_OK ) goto offsets_out; + + rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); + while( rc==SQLITE_OK ){ + int i; /* Used to loop through terms */ + int iMinPos = 0x7FFFFFFF; /* Position of next token */ + TermOffset *pTerm = 0; /* TermOffset associated with next token */ + + for(i=0; ipList && (pT->iPos-pT->iOff)iPos-pT->iOff; + pTerm = pT; + } + } + + if( !pTerm ){ + /* All offsets for this column have been gathered. */ + rc = SQLITE_DONE; + }else{ + assert( iCurrent<=iMinPos ); + if( 0==(0xFE&*pTerm->pList) ){ + pTerm->pList = 0; + }else{ + fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos); + } + while( rc==SQLITE_OK && iCurrentxNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); + } + if( rc==SQLITE_OK ){ + char aBuffer[64]; + sqlite3_snprintf(sizeof(aBuffer), aBuffer, + "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart + ); + rc = fts3StringAppend(&res, aBuffer, -1); + }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){ + rc = FTS_CORRUPT_VTAB; + } + } + } + if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + } + + pMod->xClose(pC); + if( rc!=SQLITE_OK ) goto offsets_out; + } + + offsets_out: + sqlite3_free(sCtx.aTerm); + assert( rc!=SQLITE_DONE ); + sqlite3Fts3SegmentsClose(pTab); + if( rc!=SQLITE_OK ){ + sqlite3_result_error_code(pCtx, rc); + sqlite3_free(res.z); + }else{ + sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free); + } + return; +} + +/* +** Implementation of matchinfo() function. +*/ +void sqlite3Fts3Matchinfo( + sqlite3_context *pContext, /* Function call context */ + Fts3Cursor *pCsr, /* FTS3 table cursor */ + const char *zArg /* Second arg to matchinfo() function */ +){ + Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; + int rc; + int i; + const char *zFormat; + + if( zArg ){ + for(i=0; zArg[i]; i++){ + char *zErr = 0; + if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){ + sqlite3_result_error(pContext, zErr, -1); + sqlite3_free(zErr); + return; + } + } + zFormat = zArg; + }else{ + zFormat = FTS3_MATCHINFO_DEFAULT; + } + + if( !pCsr->pExpr ){ + sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC); + return; + } + + /* Retrieve matchinfo() data. */ + rc = fts3GetMatchinfo(pCsr, zFormat); + sqlite3Fts3SegmentsClose(pTab); + + if( rc!=SQLITE_OK ){ + sqlite3_result_error_code(pContext, rc); + }else{ + int n = pCsr->nMatchinfo * sizeof(u32); + sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT); + } +} + +#endif diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_term.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_term.c new file mode 100644 index 0000000000000000000000000000000000000000..c49d5cb65d7f86ab82dc822a67da4df78c2673d1 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_term.c @@ -0,0 +1,373 @@ +/* +** 2011 Jan 27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file is not part of the production FTS code. It is only used for +** testing. It contains a virtual table implementation that provides direct +** access to the full-text index of an FTS table. +*/ + +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) +#ifdef SQLITE_TEST + +#include +#include +#include + +typedef struct Fts3termTable Fts3termTable; +typedef struct Fts3termCursor Fts3termCursor; + +struct Fts3termTable { + sqlite3_vtab base; /* Base class used by SQLite core */ + int iIndex; /* Index for Fts3Table.aIndex[] */ + Fts3Table *pFts3Tab; +}; + +struct Fts3termCursor { + sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + Fts3MultiSegReader csr; /* Must be right after "base" */ + Fts3SegFilter filter; + + int isEof; /* True if cursor is at EOF */ + char *pNext; + + sqlite3_int64 iRowid; /* Current 'rowid' value */ + sqlite3_int64 iDocid; /* Current 'docid' value */ + int iCol; /* Current 'col' value */ + int iPos; /* Current 'pos' value */ +}; + +/* +** Schema of the terms table. +*/ +#define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, docid, col, pos)" + +/* +** This function does all the work for both the xConnect and xCreate methods. +** These tables have no persistent representation of their own, so xConnect +** and xCreate are identical operations. +*/ +static int fts3termConnectMethod( + sqlite3 *db, /* Database connection */ + void *pCtx, /* Non-zero for an fts4prefix table */ + int argc, /* Number of elements in argv array */ + const char * const *argv, /* xCreate/xConnect argument array */ + sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ + char **pzErr /* OUT: sqlite3_malloc'd error message */ +){ + char const *zDb; /* Name of database (e.g. "main") */ + char const *zFts3; /* Name of fts3 table */ + int nDb; /* Result of strlen(zDb) */ + int nFts3; /* Result of strlen(zFts3) */ + int nByte; /* Bytes of space to allocate here */ + int rc; /* value returned by declare_vtab() */ + Fts3termTable *p; /* Virtual table object to return */ + int iIndex = 0; + + UNUSED_PARAMETER(pCtx); + if( argc==5 ){ + iIndex = atoi(argv[4]); + argc--; + } + + /* The user should specify a single argument - the name of an fts3 table. */ + if( argc!=4 ){ + *pzErr = sqlite3_mprintf( + "wrong number of arguments to fts4term constructor" + ); + return SQLITE_ERROR; + } + + zDb = argv[1]; + nDb = (int)strlen(zDb); + zFts3 = argv[3]; + nFts3 = (int)strlen(zFts3); + + rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA); + if( rc!=SQLITE_OK ) return rc; + + nByte = sizeof(Fts3termTable) + sizeof(Fts3Table) + nDb + nFts3 + 2; + p = (Fts3termTable *)sqlite3_malloc(nByte); + if( !p ) return SQLITE_NOMEM; + memset(p, 0, nByte); + + p->pFts3Tab = (Fts3Table *)&p[1]; + p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1]; + p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1]; + p->pFts3Tab->db = db; + p->pFts3Tab->nIndex = iIndex+1; + p->iIndex = iIndex; + + memcpy((char *)p->pFts3Tab->zDb, zDb, nDb); + memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3); + sqlite3Fts3Dequote((char *)p->pFts3Tab->zName); + + *ppVtab = (sqlite3_vtab *)p; + return SQLITE_OK; +} + +/* +** This function does the work for both the xDisconnect and xDestroy methods. +** These tables have no persistent representation of their own, so xDisconnect +** and xDestroy are identical operations. +*/ +static int fts3termDisconnectMethod(sqlite3_vtab *pVtab){ + Fts3termTable *p = (Fts3termTable *)pVtab; + Fts3Table *pFts3 = p->pFts3Tab; + int i; + + /* Free any prepared statements held */ + for(i=0; iaStmt); i++){ + sqlite3_finalize(pFts3->aStmt[i]); + } + sqlite3_free(pFts3->zSegmentsTbl); + sqlite3_free(p); + return SQLITE_OK; +} + +#define FTS4AUX_EQ_CONSTRAINT 1 +#define FTS4AUX_GE_CONSTRAINT 2 +#define FTS4AUX_LE_CONSTRAINT 4 + +/* +** xBestIndex - Analyze a WHERE and ORDER BY clause. +*/ +static int fts3termBestIndexMethod( + sqlite3_vtab *pVTab, + sqlite3_index_info *pInfo +){ + UNUSED_PARAMETER(pVTab); + + /* This vtab naturally does "ORDER BY term, docid, col, pos". */ + if( pInfo->nOrderBy ){ + int i; + for(i=0; inOrderBy; i++){ + if( pInfo->aOrderBy[i].iColumn!=i || pInfo->aOrderBy[i].desc ) break; + } + if( i==pInfo->nOrderBy ){ + pInfo->orderByConsumed = 1; + } + } + + return SQLITE_OK; +} + +/* +** xOpen - Open a cursor. +*/ +static int fts3termOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ + Fts3termCursor *pCsr; /* Pointer to cursor object to return */ + + UNUSED_PARAMETER(pVTab); + + pCsr = (Fts3termCursor *)sqlite3_malloc(sizeof(Fts3termCursor)); + if( !pCsr ) return SQLITE_NOMEM; + memset(pCsr, 0, sizeof(Fts3termCursor)); + + *ppCsr = (sqlite3_vtab_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** xClose - Close a cursor. +*/ +static int fts3termCloseMethod(sqlite3_vtab_cursor *pCursor){ + Fts3Table *pFts3 = ((Fts3termTable *)pCursor->pVtab)->pFts3Tab; + Fts3termCursor *pCsr = (Fts3termCursor *)pCursor; + + sqlite3Fts3SegmentsClose(pFts3); + sqlite3Fts3SegReaderFinish(&pCsr->csr); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** xNext - Advance the cursor to the next row, if any. +*/ +static int fts3termNextMethod(sqlite3_vtab_cursor *pCursor){ + Fts3termCursor *pCsr = (Fts3termCursor *)pCursor; + Fts3Table *pFts3 = ((Fts3termTable *)pCursor->pVtab)->pFts3Tab; + int rc; + sqlite3_int64 v; + + /* Increment our pretend rowid value. */ + pCsr->iRowid++; + + /* Advance to the next term in the full-text index. */ + if( pCsr->csr.aDoclist==0 + || pCsr->pNext>=&pCsr->csr.aDoclist[pCsr->csr.nDoclist-1] + ){ + rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr); + if( rc!=SQLITE_ROW ){ + pCsr->isEof = 1; + return rc; + } + + pCsr->iCol = 0; + pCsr->iPos = 0; + pCsr->iDocid = 0; + pCsr->pNext = pCsr->csr.aDoclist; + + /* Read docid */ + pCsr->pNext += sqlite3Fts3GetVarint(pCsr->pNext, &pCsr->iDocid); + } + + pCsr->pNext += sqlite3Fts3GetVarint(pCsr->pNext, &v); + if( v==0 ){ + pCsr->pNext += sqlite3Fts3GetVarint(pCsr->pNext, &v); + pCsr->iDocid += v; + pCsr->pNext += sqlite3Fts3GetVarint(pCsr->pNext, &v); + pCsr->iCol = 0; + pCsr->iPos = 0; + } + + if( v==1 ){ + pCsr->pNext += sqlite3Fts3GetVarint(pCsr->pNext, &v); + pCsr->iCol += (int)v; + pCsr->iPos = 0; + pCsr->pNext += sqlite3Fts3GetVarint(pCsr->pNext, &v); + } + + pCsr->iPos += (int)(v - 2); + + return SQLITE_OK; +} + +/* +** xFilter - Initialize a cursor to point at the start of its data. +*/ +static int fts3termFilterMethod( + sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + int idxNum, /* Strategy index */ + const char *idxStr, /* Unused */ + int nVal, /* Number of elements in apVal */ + sqlite3_value **apVal /* Arguments for the indexing scheme */ +){ + Fts3termCursor *pCsr = (Fts3termCursor *)pCursor; + Fts3termTable *p = (Fts3termTable *)pCursor->pVtab; + Fts3Table *pFts3 = p->pFts3Tab; + int rc; + + UNUSED_PARAMETER(nVal); + UNUSED_PARAMETER(idxNum); + UNUSED_PARAMETER(idxStr); + UNUSED_PARAMETER(apVal); + + assert( idxStr==0 && idxNum==0 ); + + /* In case this cursor is being reused, close and zero it. */ + testcase(pCsr->filter.zTerm); + sqlite3Fts3SegReaderFinish(&pCsr->csr); + memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr); + + pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; + pCsr->filter.flags |= FTS3_SEGMENT_SCAN; + + rc = sqlite3Fts3SegReaderCursor(pFts3, 0, p->iIndex, FTS3_SEGCURSOR_ALL, + pCsr->filter.zTerm, pCsr->filter.nTerm, 0, 1, &pCsr->csr + ); + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter); + } + if( rc==SQLITE_OK ){ + rc = fts3termNextMethod(pCursor); + } + return rc; +} + +/* +** xEof - Return true if the cursor is at EOF, or false otherwise. +*/ +static int fts3termEofMethod(sqlite3_vtab_cursor *pCursor){ + Fts3termCursor *pCsr = (Fts3termCursor *)pCursor; + return pCsr->isEof; +} + +/* +** xColumn - Return a column value. +*/ +static int fts3termColumnMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + int iCol /* Index of column to read value from */ +){ + Fts3termCursor *p = (Fts3termCursor *)pCursor; + + assert( iCol>=0 && iCol<=3 ); + switch( iCol ){ + case 0: + sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT); + break; + case 1: + sqlite3_result_int64(pCtx, p->iDocid); + break; + case 2: + sqlite3_result_int64(pCtx, p->iCol); + break; + default: + sqlite3_result_int64(pCtx, p->iPos); + break; + } + + return SQLITE_OK; +} + +/* +** xRowid - Return the current rowid for the cursor. +*/ +static int fts3termRowidMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite_int64 *pRowid /* OUT: Rowid value */ +){ + Fts3termCursor *pCsr = (Fts3termCursor *)pCursor; + *pRowid = pCsr->iRowid; + return SQLITE_OK; +} + +/* +** Register the fts3term module with database connection db. Return SQLITE_OK +** if successful or an error code if sqlite3_create_module() fails. +*/ +int sqlite3Fts3InitTerm(sqlite3 *db){ + static const sqlite3_module fts3term_module = { + 0, /* iVersion */ + fts3termConnectMethod, /* xCreate */ + fts3termConnectMethod, /* xConnect */ + fts3termBestIndexMethod, /* xBestIndex */ + fts3termDisconnectMethod, /* xDisconnect */ + fts3termDisconnectMethod, /* xDestroy */ + fts3termOpenMethod, /* xOpen */ + fts3termCloseMethod, /* xClose */ + fts3termFilterMethod, /* xFilter */ + fts3termNextMethod, /* xNext */ + fts3termEofMethod, /* xEof */ + fts3termColumnMethod, /* xColumn */ + fts3termRowidMethod, /* xRowid */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindFunction */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0 /* xRollbackTo */ + }; + int rc; /* Return code */ + + rc = sqlite3_create_module(db, "fts4term", &fts3term_module, 0); + return rc; +} + +#endif +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_test.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_test.c new file mode 100644 index 0000000000000000000000000000000000000000..75ec6bd01d09522d12ced45932c81acf0a6e6530 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_test.c @@ -0,0 +1,535 @@ +/* +** 2011 Jun 13 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file is not part of the production FTS code. It is only used for +** testing. It contains a Tcl command that can be used to test if a document +** matches an FTS NEAR expression. +** +** As of March 2012, it also contains a version 1 tokenizer used for testing +** that the sqlite3_tokenizer_module.xLanguage() method is invoked correctly. +*/ + +#include +#include +#include + +#if defined(SQLITE_TEST) +#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) + +/* Required so that the "ifdef SQLITE_ENABLE_FTS3" below works */ +#include "fts3Int.h" + +#define NM_MAX_TOKEN 12 + +typedef struct NearPhrase NearPhrase; +typedef struct NearDocument NearDocument; +typedef struct NearToken NearToken; + +struct NearDocument { + int nToken; /* Length of token in bytes */ + NearToken *aToken; /* Token array */ +}; + +struct NearToken { + int n; /* Length of token in bytes */ + const char *z; /* Pointer to token string */ +}; + +struct NearPhrase { + int nNear; /* Preceding NEAR value */ + int nToken; /* Number of tokens in this phrase */ + NearToken aToken[NM_MAX_TOKEN]; /* Array of tokens in this phrase */ +}; + +static int nm_phrase_match( + NearPhrase *p, + NearToken *aToken +){ + int ii; + + for(ii=0; iinToken; ii++){ + NearToken *pToken = &p->aToken[ii]; + if( pToken->n>0 && pToken->z[pToken->n-1]=='*' ){ + if( aToken[ii].n<(pToken->n-1) ) return 0; + if( memcmp(aToken[ii].z, pToken->z, pToken->n-1) ) return 0; + }else{ + if( aToken[ii].n!=pToken->n ) return 0; + if( memcmp(aToken[ii].z, pToken->z, pToken->n) ) return 0; + } + } + + return 1; +} + +static int nm_near_chain( + int iDir, /* Direction to iterate through aPhrase[] */ + NearDocument *pDoc, /* Document to match against */ + int iPos, /* Position at which iPhrase was found */ + int nPhrase, /* Size of phrase array */ + NearPhrase *aPhrase, /* Phrase array */ + int iPhrase /* Index of phrase found */ +){ + int iStart; + int iStop; + int ii; + int nNear; + int iPhrase2; + NearPhrase *p; + NearPhrase *pPrev; + + assert( iDir==1 || iDir==-1 ); + + if( iDir==1 ){ + if( (iPhrase+1)==nPhrase ) return 1; + nNear = aPhrase[iPhrase+1].nNear; + }else{ + if( iPhrase==0 ) return 1; + nNear = aPhrase[iPhrase].nNear; + } + pPrev = &aPhrase[iPhrase]; + iPhrase2 = iPhrase+iDir; + p = &aPhrase[iPhrase2]; + + iStart = iPos - nNear - p->nToken; + iStop = iPos + nNear + pPrev->nToken; + + if( iStart<0 ) iStart = 0; + if( iStop > pDoc->nToken - p->nToken ) iStop = pDoc->nToken - p->nToken; + + for(ii=iStart; ii<=iStop; ii++){ + if( nm_phrase_match(p, &pDoc->aToken[ii]) ){ + if( nm_near_chain(iDir, pDoc, ii, nPhrase, aPhrase, iPhrase2) ) return 1; + } + } + + return 0; +} + +static int nm_match_count( + NearDocument *pDoc, /* Document to match against */ + int nPhrase, /* Size of phrase array */ + NearPhrase *aPhrase, /* Phrase array */ + int iPhrase /* Index of phrase to count matches for */ +){ + int nOcc = 0; + int ii; + NearPhrase *p = &aPhrase[iPhrase]; + + for(ii=0; ii<(pDoc->nToken + 1 - p->nToken); ii++){ + if( nm_phrase_match(p, &pDoc->aToken[ii]) ){ + /* Test forward NEAR chain (i>iPhrase) */ + if( 0==nm_near_chain(1, pDoc, ii, nPhrase, aPhrase, iPhrase) ) continue; + + /* Test reverse NEAR chain (iNM_MAX_TOKEN ){ + Tcl_AppendResult(interp, "Too many tokens in phrase", 0); + rc = TCL_ERROR; + goto near_match_out; + } + for(jj=0; jjz = Tcl_GetStringFromObj(apToken[jj], &pT->n); + } + aPhrase[ii].nToken = nToken; + } + for(ii=1; ii0)); + + near_match_out: + ckfree((char *)aPhrase); + ckfree((char *)doc.aToken); + return rc; +} + +/* +** Tclcmd: fts3_configure_incr_load ?CHUNKSIZE THRESHOLD? +** +** Normally, FTS uses hard-coded values to determine the minimum doclist +** size eligible for incremental loading, and the size of the chunks loaded +** when a doclist is incrementally loaded. This command allows the built-in +** values to be overridden for testing purposes. +** +** If present, the first argument is the chunksize in bytes to load doclists +** in. The second argument is the minimum doclist size in bytes to use +** incremental loading with. +** +** Whether or not the arguments are present, this command returns a list of +** two integers - the initial chunksize and threshold when the command is +** invoked. This can be used to restore the default behavior after running +** tests. For example: +** +** # Override incr-load settings for testing: +** set cfg [fts3_configure_incr_load $new_chunksize $new_threshold] +** +** .... run tests .... +** +** # Restore initial incr-load settings: +** eval fts3_configure_incr_load $cfg +*/ +static int fts3_configure_incr_load_cmd( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifdef SQLITE_ENABLE_FTS3 + extern int test_fts3_node_chunksize; + extern int test_fts3_node_chunk_threshold; + Tcl_Obj *pRet; + + if( objc!=1 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?CHUNKSIZE THRESHOLD?"); + return TCL_ERROR; + } + + pRet = Tcl_NewObj(); + Tcl_IncrRefCount(pRet); + Tcl_ListObjAppendElement( + interp, pRet, Tcl_NewIntObj(test_fts3_node_chunksize)); + Tcl_ListObjAppendElement( + interp, pRet, Tcl_NewIntObj(test_fts3_node_chunk_threshold)); + + if( objc==3 ){ + int iArg1; + int iArg2; + if( Tcl_GetIntFromObj(interp, objv[1], &iArg1) + || Tcl_GetIntFromObj(interp, objv[2], &iArg2) + ){ + Tcl_DecrRefCount(pRet); + return TCL_ERROR; + } + test_fts3_node_chunksize = iArg1; + test_fts3_node_chunk_threshold = iArg2; + } + + Tcl_SetObjResult(interp, pRet); + Tcl_DecrRefCount(pRet); +#endif + UNUSED_PARAMETER(clientData); + return TCL_OK; +} + +#ifdef SQLITE_ENABLE_FTS3 +/************************************************************************** +** Beginning of test tokenizer code. +** +** For language 0, this tokenizer is similar to the default 'simple' +** tokenizer. For other languages L, the following: +** +** * Odd numbered languages are case-sensitive. Even numbered +** languages are not. +** +** * Language ids 100 or greater are considered an error. +** +** The implementation assumes that the input contains only ASCII characters +** (i.e. those that may be encoded in UTF-8 using a single byte). +*/ +typedef struct test_tokenizer { + sqlite3_tokenizer base; +} test_tokenizer; + +typedef struct test_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *aInput; /* Input being tokenized */ + int nInput; /* Size of the input in bytes */ + int iInput; /* Current offset in aInput */ + int iToken; /* Index of next token to be returned */ + char *aBuffer; /* Buffer containing current token */ + int nBuffer; /* Number of bytes allocated at pToken */ + int iLangid; /* Configured language id */ +} test_tokenizer_cursor; + +static int testTokenizerCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer +){ + test_tokenizer *pNew; + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + + pNew = sqlite3_malloc(sizeof(test_tokenizer)); + if( !pNew ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(test_tokenizer)); + + *ppTokenizer = (sqlite3_tokenizer *)pNew; + return SQLITE_OK; +} + +static int testTokenizerDestroy(sqlite3_tokenizer *pTokenizer){ + test_tokenizer *p = (test_tokenizer *)pTokenizer; + sqlite3_free(p); + return SQLITE_OK; +} + +static int testTokenizerOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *pInput, int nBytes, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + int rc = SQLITE_OK; /* Return code */ + test_tokenizer_cursor *pCsr; /* New cursor object */ + + UNUSED_PARAMETER(pTokenizer); + + pCsr = (test_tokenizer_cursor *)sqlite3_malloc(sizeof(test_tokenizer_cursor)); + if( pCsr==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pCsr, 0, sizeof(test_tokenizer_cursor)); + pCsr->aInput = pInput; + if( nBytes<0 ){ + pCsr->nInput = (int)strlen(pInput); + }else{ + pCsr->nInput = nBytes; + } + } + + *ppCursor = (sqlite3_tokenizer_cursor *)pCsr; + return rc; +} + +static int testTokenizerClose(sqlite3_tokenizer_cursor *pCursor){ + test_tokenizer_cursor *pCsr = (test_tokenizer_cursor *)pCursor; + sqlite3_free(pCsr->aBuffer); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +static int testIsTokenChar(char c){ + return (c>='a' && c<='z') || (c>='A' && c<='Z'); +} +static int testTolower(char c){ + char ret = c; + if( ret>='A' && ret<='Z') ret = ret - ('A'-'a'); + return ret; +} + +static int testTokenizerNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by testTokenizerOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + test_tokenizer_cursor *pCsr = (test_tokenizer_cursor *)pCursor; + int rc = SQLITE_OK; + const char *p; + const char *pEnd; + + p = &pCsr->aInput[pCsr->iInput]; + pEnd = &pCsr->aInput[pCsr->nInput]; + + /* Skip past any white-space */ + assert( p<=pEnd ); + while( ppCsr->nBuffer ){ + sqlite3_free(pCsr->aBuffer); + pCsr->aBuffer = sqlite3_malloc(nToken); + } + if( pCsr->aBuffer==0 ){ + rc = SQLITE_NOMEM; + }else{ + int i; + + if( pCsr->iLangid & 0x00000001 ){ + for(i=0; iaBuffer[i] = pToken[i]; + }else{ + for(i=0; iaBuffer[i] = testTolower(pToken[i]); + } + pCsr->iToken++; + pCsr->iInput = (int)(p - pCsr->aInput); + + *ppToken = pCsr->aBuffer; + *pnBytes = nToken; + *piStartOffset = (int)(pToken - pCsr->aInput); + *piEndOffset = (int)(p - pCsr->aInput); + *piPosition = pCsr->iToken; + } + } + + return rc; +} + +static int testTokenizerLanguage( + sqlite3_tokenizer_cursor *pCursor, + int iLangid +){ + int rc = SQLITE_OK; + test_tokenizer_cursor *pCsr = (test_tokenizer_cursor *)pCursor; + pCsr->iLangid = iLangid; + if( pCsr->iLangid>=100 ){ + rc = SQLITE_ERROR; + } + return rc; +} +#endif + +static int fts3_test_tokenizer_cmd( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifdef SQLITE_ENABLE_FTS3 + static const sqlite3_tokenizer_module testTokenizerModule = { + 1, + testTokenizerCreate, + testTokenizerDestroy, + testTokenizerOpen, + testTokenizerClose, + testTokenizerNext, + testTokenizerLanguage + }; + const sqlite3_tokenizer_module *pPtr = &testTokenizerModule; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj( + (const unsigned char *)&pPtr, sizeof(sqlite3_tokenizer_module *) + )); +#endif + UNUSED_PARAMETER(clientData); + return TCL_OK; +} + +/* +** End of tokenizer code. +**************************************************************************/ + +int Sqlitetestfts3_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "fts3_near_match", fts3_near_match_cmd, 0, 0); + Tcl_CreateObjCommand(interp, + "fts3_configure_incr_load", fts3_configure_incr_load_cmd, 0, 0 + ); + Tcl_CreateObjCommand( + interp, "fts3_test_tokenizer", fts3_test_tokenizer_cmd, 0, 0 + ); + return TCL_OK; +} +#endif /* SQLITE_ENABLE_FTS3 || SQLITE_ENABLE_FTS4 */ +#endif /* ifdef SQLITE_TEST */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenize_vtab.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenize_vtab.c new file mode 100644 index 0000000000000000000000000000000000000000..364852ef82e2cb419b8b3dc0e06fbd73267990e9 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenize_vtab.c @@ -0,0 +1,454 @@ +/* +** 2013 Apr 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code for the "fts3tokenize" virtual table module. +** An fts3tokenize virtual table is created as follows: +** +** CREATE VIRTUAL TABLE USING fts3tokenize( +** , , ... +** ); +** +** The table created has the following schema: +** +** CREATE TABLE (input, token, start, end, position) +** +** When queried, the query must include a WHERE clause of type: +** +** input = +** +** The virtual table module tokenizes this , using the FTS3 +** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE +** statement and returns one row for each token in the result. With +** fields set as follows: +** +** input: Always set to a copy of +** token: A token from the input. +** start: Byte offset of the token within the input . +** end: Byte offset of the byte immediately following the end of the +** token within the input string. +** pos: Token offset of token within input. +** +*/ +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#include +#include + +typedef struct Fts3tokTable Fts3tokTable; +typedef struct Fts3tokCursor Fts3tokCursor; + +/* +** Virtual table structure. +*/ +struct Fts3tokTable { + sqlite3_vtab base; /* Base class used by SQLite core */ + const sqlite3_tokenizer_module *pMod; + sqlite3_tokenizer *pTok; +}; + +/* +** Virtual table cursor structure. +*/ +struct Fts3tokCursor { + sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + char *zInput; /* Input string */ + sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */ + int iRowid; /* Current 'rowid' value */ + const char *zToken; /* Current 'token' value */ + int nToken; /* Size of zToken in bytes */ + int iStart; /* Current 'start' value */ + int iEnd; /* Current 'end' value */ + int iPos; /* Current 'pos' value */ +}; + +/* +** Query FTS for the tokenizer implementation named zName. +*/ +static int fts3tokQueryTokenizer( + Fts3Hash *pHash, + const char *zName, + const sqlite3_tokenizer_module **pp, + char **pzErr +){ + sqlite3_tokenizer_module *p; + int nName = (int)strlen(zName); + + p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); + if( !p ){ + *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName); + return SQLITE_ERROR; + } + + *pp = p; + return SQLITE_OK; +} + +/* +** The second argument, argv[], is an array of pointers to nul-terminated +** strings. This function makes a copy of the array and strings into a +** single block of memory. It then dequotes any of the strings that appear +** to be quoted. +** +** If successful, output parameter *pazDequote is set to point at the +** array of dequoted strings and SQLITE_OK is returned. The caller is +** responsible for eventually calling sqlite3_free() to free the array +** in this case. Or, if an error occurs, an SQLite error code is returned. +** The final value of *pazDequote is undefined in this case. +*/ +static int fts3tokDequoteArray( + int argc, /* Number of elements in argv[] */ + const char * const *argv, /* Input array */ + char ***pazDequote /* Output array */ +){ + int rc = SQLITE_OK; /* Return code */ + if( argc==0 ){ + *pazDequote = 0; + }else{ + int i; + int nByte = 0; + char **azDequote; + + for(i=0; ixCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok); + } + + if( rc==SQLITE_OK ){ + pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable)); + if( pTab==0 ){ + rc = SQLITE_NOMEM; + } + } + + if( rc==SQLITE_OK ){ + memset(pTab, 0, sizeof(Fts3tokTable)); + pTab->pMod = pMod; + pTab->pTok = pTok; + *ppVtab = &pTab->base; + }else{ + if( pTok ){ + pMod->xDestroy(pTok); + } + } + + sqlite3_free(azDequote); + return rc; +} + +/* +** This function does the work for both the xDisconnect and xDestroy methods. +** These tables have no persistent representation of their own, so xDisconnect +** and xDestroy are identical operations. +*/ +static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){ + Fts3tokTable *pTab = (Fts3tokTable *)pVtab; + + pTab->pMod->xDestroy(pTab->pTok); + sqlite3_free(pTab); + return SQLITE_OK; +} + +/* +** xBestIndex - Analyze a WHERE and ORDER BY clause. +*/ +static int fts3tokBestIndexMethod( + sqlite3_vtab *pVTab, + sqlite3_index_info *pInfo +){ + int i; + UNUSED_PARAMETER(pVTab); + + for(i=0; inConstraint; i++){ + if( pInfo->aConstraint[i].usable + && pInfo->aConstraint[i].iColumn==0 + && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + pInfo->idxNum = 1; + pInfo->aConstraintUsage[i].argvIndex = 1; + pInfo->aConstraintUsage[i].omit = 1; + pInfo->estimatedCost = 1; + return SQLITE_OK; + } + } + + pInfo->idxNum = 0; + assert( pInfo->estimatedCost>1000000.0 ); + + return SQLITE_OK; +} + +/* +** xOpen - Open a cursor. +*/ +static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ + Fts3tokCursor *pCsr; + UNUSED_PARAMETER(pVTab); + + pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor)); + if( pCsr==0 ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(Fts3tokCursor)); + + *ppCsr = (sqlite3_vtab_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** Reset the tokenizer cursor passed as the only argument. As if it had +** just been returned by fts3tokOpenMethod(). +*/ +static void fts3tokResetCursor(Fts3tokCursor *pCsr){ + if( pCsr->pCsr ){ + Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab); + pTab->pMod->xClose(pCsr->pCsr); + pCsr->pCsr = 0; + } + sqlite3_free(pCsr->zInput); + pCsr->zInput = 0; + pCsr->zToken = 0; + pCsr->nToken = 0; + pCsr->iStart = 0; + pCsr->iEnd = 0; + pCsr->iPos = 0; + pCsr->iRowid = 0; +} + +/* +** xClose - Close a cursor. +*/ +static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + + fts3tokResetCursor(pCsr); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** xNext - Advance the cursor to the next row, if any. +*/ +static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); + int rc; /* Return code */ + + pCsr->iRowid++; + rc = pTab->pMod->xNext(pCsr->pCsr, + &pCsr->zToken, &pCsr->nToken, + &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos + ); + + if( rc!=SQLITE_OK ){ + fts3tokResetCursor(pCsr); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + } + + return rc; +} + +/* +** xFilter - Initialize a cursor to point at the start of its data. +*/ +static int fts3tokFilterMethod( + sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + int idxNum, /* Strategy index */ + const char *idxStr, /* Unused */ + int nVal, /* Number of elements in apVal */ + sqlite3_value **apVal /* Arguments for the indexing scheme */ +){ + int rc = SQLITE_ERROR; + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); + UNUSED_PARAMETER(idxStr); + UNUSED_PARAMETER(nVal); + + fts3tokResetCursor(pCsr); + if( idxNum==1 ){ + const char *zByte = (const char *)sqlite3_value_text(apVal[0]); + int nByte = sqlite3_value_bytes(apVal[0]); + pCsr->zInput = sqlite3_malloc(nByte+1); + if( pCsr->zInput==0 ){ + rc = SQLITE_NOMEM; + }else{ + memcpy(pCsr->zInput, zByte, nByte); + pCsr->zInput[nByte] = 0; + rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr); + if( rc==SQLITE_OK ){ + pCsr->pCsr->pTokenizer = pTab->pTok; + } + } + } + + if( rc!=SQLITE_OK ) return rc; + return fts3tokNextMethod(pCursor); +} + +/* +** xEof - Return true if the cursor is at EOF, or false otherwise. +*/ +static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + return (pCsr->zToken==0); +} + +/* +** xColumn - Return a column value. +*/ +static int fts3tokColumnMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + int iCol /* Index of column to read value from */ +){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + + /* CREATE TABLE x(input, token, start, end, position) */ + switch( iCol ){ + case 0: + sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT); + break; + case 1: + sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT); + break; + case 2: + sqlite3_result_int(pCtx, pCsr->iStart); + break; + case 3: + sqlite3_result_int(pCtx, pCsr->iEnd); + break; + default: + assert( iCol==4 ); + sqlite3_result_int(pCtx, pCsr->iPos); + break; + } + return SQLITE_OK; +} + +/* +** xRowid - Return the current rowid for the cursor. +*/ +static int fts3tokRowidMethod( + sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + sqlite_int64 *pRowid /* OUT: Rowid value */ +){ + Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; + *pRowid = (sqlite3_int64)pCsr->iRowid; + return SQLITE_OK; +} + +/* +** Register the fts3tok module with database connection db. Return SQLITE_OK +** if successful or an error code if sqlite3_create_module() fails. +*/ +int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){ + static const sqlite3_module fts3tok_module = { + 0, /* iVersion */ + fts3tokConnectMethod, /* xCreate */ + fts3tokConnectMethod, /* xConnect */ + fts3tokBestIndexMethod, /* xBestIndex */ + fts3tokDisconnectMethod, /* xDisconnect */ + fts3tokDisconnectMethod, /* xDestroy */ + fts3tokOpenMethod, /* xOpen */ + fts3tokCloseMethod, /* xClose */ + fts3tokFilterMethod, /* xFilter */ + fts3tokNextMethod, /* xNext */ + fts3tokEofMethod, /* xEof */ + fts3tokColumnMethod, /* xColumn */ + fts3tokRowidMethod, /* xRowid */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindFunction */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0 /* xRollbackTo */ + }; + int rc; /* Return code */ + + rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash); + return rc; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenizer.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenizer.c new file mode 100644 index 0000000000000000000000000000000000000000..04f84460e87be324685a16a1c9dd8c08b6e4bf0a --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenizer.c @@ -0,0 +1,488 @@ +/* +** 2007 June 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This is part of an SQLite module implementing full-text search. +** This particular file implements the generic tokenizer interface. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#include +#include + +/* +** Implementation of the SQL scalar function for accessing the underlying +** hash table. This function may be called as follows: +** +** SELECT (); +** SELECT (, ); +** +** where is the name passed as the second argument +** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer'). +** +** If the argument is specified, it must be a blob value +** containing a pointer to be stored as the hash data corresponding +** to the string . If is not specified, then +** the string must already exist in the has table. Otherwise, +** an error is returned. +** +** Whether or not the argument is specified, the value returned +** is a blob containing the pointer stored as the hash data corresponding +** to string (after the hash-table is updated, if applicable). +*/ +static void scalarFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + Fts3Hash *pHash; + void *pPtr = 0; + const unsigned char *zName; + int nName; + + assert( argc==1 || argc==2 ); + + pHash = (Fts3Hash *)sqlite3_user_data(context); + + zName = sqlite3_value_text(argv[0]); + nName = sqlite3_value_bytes(argv[0])+1; + + if( argc==2 ){ + void *pOld; + int n = sqlite3_value_bytes(argv[1]); + if( n!=sizeof(pPtr) ){ + sqlite3_result_error(context, "argument type mismatch", -1); + return; + } + pPtr = *(void **)sqlite3_value_blob(argv[1]); + pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr); + if( pOld==pPtr ){ + sqlite3_result_error(context, "out of memory", -1); + return; + } + }else{ + pPtr = sqlite3Fts3HashFind(pHash, zName, nName); + if( !pPtr ){ + char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); + return; + } + } + + sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT); +} + +int sqlite3Fts3IsIdChar(char c){ + static const char isFtsIdChar[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ + 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ + }; + return (c&0x80 || isFtsIdChar[(int)(c)]); +} + +const char *sqlite3Fts3NextToken(const char *zStr, int *pn){ + const char *z1; + const char *z2 = 0; + + /* Find the start of the next token. */ + z1 = zStr; + while( z2==0 ){ + char c = *z1; + switch( c ){ + case '\0': return 0; /* No more tokens here */ + case '\'': + case '"': + case '`': { + z2 = z1; + while( *++z2 && (*z2!=c || *++z2==c) ); + break; + } + case '[': + z2 = &z1[1]; + while( *z2 && z2[0]!=']' ) z2++; + if( *z2 ) z2++; + break; + + default: + if( sqlite3Fts3IsIdChar(*z1) ){ + z2 = &z1[1]; + while( sqlite3Fts3IsIdChar(*z2) ) z2++; + }else{ + z1++; + } + } + } + + *pn = (int)(z2-z1); + return z1; +} + +int sqlite3Fts3InitTokenizer( + Fts3Hash *pHash, /* Tokenizer hash table */ + const char *zArg, /* Tokenizer name */ + sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */ + char **pzErr /* OUT: Set to malloced error message */ +){ + int rc; + char *z = (char *)zArg; + int n = 0; + char *zCopy; + char *zEnd; /* Pointer to nul-term of zCopy */ + sqlite3_tokenizer_module *m; + + zCopy = sqlite3_mprintf("%s", zArg); + if( !zCopy ) return SQLITE_NOMEM; + zEnd = &zCopy[strlen(zCopy)]; + + z = (char *)sqlite3Fts3NextToken(zCopy, &n); + z[n] = '\0'; + sqlite3Fts3Dequote(z); + + m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1); + if( !m ){ + *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z); + rc = SQLITE_ERROR; + }else{ + char const **aArg = 0; + int iArg = 0; + z = &z[n+1]; + while( zxCreate(iArg, aArg, ppTok); + assert( rc!=SQLITE_OK || *ppTok ); + if( rc!=SQLITE_OK ){ + *pzErr = sqlite3_mprintf("unknown tokenizer"); + }else{ + (*ppTok)->pModule = m; + } + sqlite3_free((void *)aArg); + } + + sqlite3_free(zCopy); + return rc; +} + + +#ifdef SQLITE_TEST + +#include +#include + +/* +** Implementation of a special SQL scalar function for testing tokenizers +** designed to be used in concert with the Tcl testing framework. This +** function must be called with two or more arguments: +** +** SELECT (, ..., ); +** +** where is the name passed as the second argument +** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer') +** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test'). +** +** The return value is a string that may be interpreted as a Tcl +** list. For each token in the , three elements are +** added to the returned list. The first is the token position, the +** second is the token text (folded, stemmed, etc.) and the third is the +** substring of associated with the token. For example, +** using the built-in "simple" tokenizer: +** +** SELECT fts_tokenizer_test('simple', 'I don't see how'); +** +** will return the string: +** +** "{0 i I 1 dont don't 2 see see 3 how how}" +** +*/ +static void testFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + Fts3Hash *pHash; + sqlite3_tokenizer_module *p; + sqlite3_tokenizer *pTokenizer = 0; + sqlite3_tokenizer_cursor *pCsr = 0; + + const char *zErr = 0; + + const char *zName; + int nName; + const char *zInput; + int nInput; + + const char *azArg[64]; + + const char *zToken; + int nToken = 0; + int iStart = 0; + int iEnd = 0; + int iPos = 0; + int i; + + Tcl_Obj *pRet; + + if( argc<2 ){ + sqlite3_result_error(context, "insufficient arguments", -1); + return; + } + + nName = sqlite3_value_bytes(argv[0]); + zName = (const char *)sqlite3_value_text(argv[0]); + nInput = sqlite3_value_bytes(argv[argc-1]); + zInput = (const char *)sqlite3_value_text(argv[argc-1]); + + pHash = (Fts3Hash *)sqlite3_user_data(context); + p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); + + if( !p ){ + char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); + return; + } + + pRet = Tcl_NewObj(); + Tcl_IncrRefCount(pRet); + + for(i=1; ixCreate(argc-2, azArg, &pTokenizer) ){ + zErr = "error in xCreate()"; + goto finish; + } + pTokenizer->pModule = p; + if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){ + zErr = "error in xOpen()"; + goto finish; + } + + while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){ + Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); + zToken = &zInput[iStart]; + nToken = iEnd-iStart; + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); + } + + if( SQLITE_OK!=p->xClose(pCsr) ){ + zErr = "error in xClose()"; + goto finish; + } + if( SQLITE_OK!=p->xDestroy(pTokenizer) ){ + zErr = "error in xDestroy()"; + goto finish; + } + +finish: + if( zErr ){ + sqlite3_result_error(context, zErr, -1); + }else{ + sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); + } + Tcl_DecrRefCount(pRet); +} + +static +int registerTokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module *p +){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts3_tokenizer(?, ?)"; + + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); + sqlite3_step(pStmt); + + return sqlite3_finalize(pStmt); +} + +static +int queryTokenizer( + sqlite3 *db, + char *zName, + const sqlite3_tokenizer_module **pp +){ + int rc; + sqlite3_stmt *pStmt; + const char zSql[] = "SELECT fts3_tokenizer(?)"; + + *pp = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ + memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + } + } + + return sqlite3_finalize(pStmt); +} + +void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); + +/* +** Implementation of the scalar function fts3_tokenizer_internal_test(). +** This function is used for testing only, it is not included in the +** build unless SQLITE_TEST is defined. +** +** The purpose of this is to test that the fts3_tokenizer() function +** can be used as designed by the C-code in the queryTokenizer and +** registerTokenizer() functions above. These two functions are repeated +** in the README.tokenizer file as an example, so it is important to +** test them. +** +** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar +** function with no arguments. An assert() will fail if a problem is +** detected. i.e.: +** +** SELECT fts3_tokenizer_internal_test(); +** +*/ +static void intTestFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int rc; + const sqlite3_tokenizer_module *p1; + const sqlite3_tokenizer_module *p2; + sqlite3 *db = (sqlite3 *)sqlite3_user_data(context); + + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + + /* Test the query function */ + sqlite3Fts3SimpleTokenizerModule(&p1); + rc = queryTokenizer(db, "simple", &p2); + assert( rc==SQLITE_OK ); + assert( p1==p2 ); + rc = queryTokenizer(db, "nosuchtokenizer", &p2); + assert( rc==SQLITE_ERROR ); + assert( p2==0 ); + assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") ); + + /* Test the storage function */ + rc = registerTokenizer(db, "nosuchtokenizer", p1); + assert( rc==SQLITE_OK ); + rc = queryTokenizer(db, "nosuchtokenizer", &p2); + assert( rc==SQLITE_OK ); + assert( p2==p1 ); + + sqlite3_result_text(context, "ok", -1, SQLITE_STATIC); +} + +#endif + +/* +** Set up SQL objects in database db used to access the contents of +** the hash table pointed to by argument pHash. The hash table must +** been initialized to use string keys, and to take a private copy +** of the key when a value is inserted. i.e. by a call similar to: +** +** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); +** +** This function adds a scalar function (see header comment above +** scalarFunc() in this file for details) and, if ENABLE_TABLE is +** defined at compilation time, a temporary virtual table (see header +** comment above struct HashTableVtab) to the database schema. Both +** provide read/write access to the contents of *pHash. +** +** The third argument to this function, zName, is used as the name +** of both the scalar and, if created, the virtual table. +*/ +int sqlite3Fts3InitHashTable( + sqlite3 *db, + Fts3Hash *pHash, + const char *zName +){ + int rc = SQLITE_OK; + void *p = (void *)pHash; + const int any = SQLITE_ANY; + +#ifdef SQLITE_TEST + char *zTest = 0; + char *zTest2 = 0; + void *pdb = (void *)db; + zTest = sqlite3_mprintf("%s_test", zName); + zTest2 = sqlite3_mprintf("%s_internal_test", zName); + if( !zTest || !zTest2 ){ + rc = SQLITE_NOMEM; + } +#endif + + if( SQLITE_OK==rc ){ + rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0); + } + if( SQLITE_OK==rc ){ + rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0); + } +#ifdef SQLITE_TEST + if( SQLITE_OK==rc ){ + rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0); + } + if( SQLITE_OK==rc ){ + rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0); + } +#endif + +#ifdef SQLITE_TEST + sqlite3_free(zTest); + sqlite3_free(zTest2); +#endif + + return rc; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenizer.h b/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenizer.h new file mode 100644 index 0000000000000000000000000000000000000000..4a40b2b38503833bf17ded9ee2e2742e86267fc6 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenizer.h @@ -0,0 +1,161 @@ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _FTS3_TOKENIZER_H_ +#define _FTS3_TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ +#include "sqlite3.h" + +/* +** Structures used by the tokenizer interface. When a new tokenizer +** implementation is registered, the caller provides a pointer to +** an sqlite3_tokenizer_module containing pointers to the callback +** functions that make up an implementation. +** +** When an fts3 table is created, it passes any arguments passed to +** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the +** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer +** implementation. The xCreate() function in turn returns an +** sqlite3_tokenizer structure representing the specific tokenizer to +** be used for the fts3 table (customized by the tokenizer clause arguments). +** +** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() +** method is called. It returns an sqlite3_tokenizer_cursor object +** that may be used to tokenize a specific input buffer based on +** the tokenization rules supplied by a specific sqlite3_tokenizer +** object. +*/ +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; + +struct sqlite3_tokenizer_module { + + /* + ** Structure version. Should always be set to 0 or 1. + */ + int iVersion; + + /* + ** Create a new tokenizer. The values in the argv[] array are the + ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL + ** TABLE statement that created the fts3 table. For example, if + ** the following SQL is executed: + ** + ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) + ** + ** then argc is set to 2, and the argv[] array contains pointers + ** to the strings "arg1" and "arg2". + ** + ** This method should return either SQLITE_OK (0), or an SQLite error + ** code. If SQLITE_OK is returned, then *ppTokenizer should be set + ** to point at the newly created tokenizer structure. The generic + ** sqlite3_tokenizer.pModule variable should not be initialized by + ** this callback. The caller will do so. + */ + int (*xCreate)( + int argc, /* Size of argv array */ + const char *const*argv, /* Tokenizer argument strings */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + ); + + /* + ** Destroy an existing tokenizer. The fts3 module calls this method + ** exactly once for each successful call to xCreate(). + */ + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Create a tokenizer cursor to tokenize an input buffer. The caller + ** is responsible for ensuring that the input buffer remains valid + ** until the cursor is closed (using the xClose() method). + */ + int (*xOpen)( + sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ + const char *pInput, int nBytes, /* Input buffer */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ + ); + + /* + ** Destroy an existing tokenizer cursor. The fts3 module calls this + ** method exactly once for each successful call to xOpen(). + */ + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + + /* + ** Retrieve the next token from the tokenizer cursor pCursor. This + ** method should either return SQLITE_OK and set the values of the + ** "OUT" variables identified below, or SQLITE_DONE to indicate that + ** the end of the buffer has been reached, or an SQLite error code. + ** + ** *ppToken should be set to point at a buffer containing the + ** normalized version of the token (i.e. after any case-folding and/or + ** stemming has been performed). *pnBytes should be set to the length + ** of this buffer in bytes. The input text that generated the token is + ** identified by the byte offsets returned in *piStartOffset and + ** *piEndOffset. *piStartOffset should be set to the index of the first + ** byte of the token in the input buffer. *piEndOffset should be set + ** to the index of the first byte just past the end of the token in + ** the input buffer. + ** + ** The buffer *ppToken is set to point at is managed by the tokenizer + ** implementation. It is only required to be valid until the next call + ** to xNext() or xClose(). + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xNext)( + sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ + const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ + int *piStartOffset, /* OUT: Byte offset of token in input buffer */ + int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ + int *piPosition /* OUT: Number of tokens returned before this one */ + ); + + /*********************************************************************** + ** Methods below this point are only available if iVersion>=1. + */ + + /* + ** Configure the language id of a tokenizer cursor. + */ + int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid); +}; + +struct sqlite3_tokenizer { + const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +int fts3_global_term_cnt(int iTerm, int iCol); +int fts3_term_cnt(int iTerm, int iCol); + + +#endif /* _FTS3_TOKENIZER_H_ */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenizer1.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenizer1.c new file mode 100644 index 0000000000000000000000000000000000000000..deea06d92bf895a1f513f863484cfbffd0a2faa1 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_tokenizer1.c @@ -0,0 +1,234 @@ +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** Implementation of the "simple" full-text-search tokenizer. +*/ + +/* +** The code in this file is only compiled if: +** +** * The FTS3 module is being built as an extension +** (in which case SQLITE_CORE is not defined), or +** +** * The FTS3 module is being built into the core of +** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). +*/ +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#include +#include +#include +#include + +#include "fts3_tokenizer.h" + +typedef struct simple_tokenizer { + sqlite3_tokenizer base; + char delim[128]; /* flag ASCII delimiters */ +} simple_tokenizer; + +typedef struct simple_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *pInput; /* input we are tokenizing */ + int nBytes; /* size of the input */ + int iOffset; /* current position in pInput */ + int iToken; /* index of next token to be returned */ + char *pToken; /* storage for current token */ + int nTokenAllocated; /* space allocated to zToken buffer */ +} simple_tokenizer_cursor; + + +static int simpleDelim(simple_tokenizer *t, unsigned char c){ + return c<0x80 && t->delim[c]; +} +static int fts3_isalnum(int x){ + return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z'); +} + +/* +** Create a new tokenizer instance. +*/ +static int simpleCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer +){ + simple_tokenizer *t; + + t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t)); + if( t==NULL ) return SQLITE_NOMEM; + memset(t, 0, sizeof(*t)); + + /* TODO(shess) Delimiters need to remain the same from run to run, + ** else we need to reindex. One solution would be a meta-table to + ** track such information in the database, then we'd only want this + ** information on the initial create. + */ + if( argc>1 ){ + int i, n = (int)strlen(argv[1]); + for(i=0; i=0x80 ){ + sqlite3_free(t); + return SQLITE_ERROR; + } + t->delim[ch] = 1; + } + } else { + /* Mark non-alphanumeric ASCII characters as delimiters */ + int i; + for(i=1; i<0x80; i++){ + t->delim[i] = !fts3_isalnum(i) ? -1 : 0; + } + } + + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +/* +** Destroy a tokenizer +*/ +static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ + sqlite3_free(pTokenizer); + return SQLITE_OK; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is pInput[0..nBytes-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int simpleOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *pInput, int nBytes, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ +){ + simple_tokenizer_cursor *c; + + UNUSED_PARAMETER(pTokenizer); + + c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); + if( c==NULL ) return SQLITE_NOMEM; + + c->pInput = pInput; + if( pInput==0 ){ + c->nBytes = 0; + }else if( nBytes<0 ){ + c->nBytes = (int)strlen(pInput); + }else{ + c->nBytes = nBytes; + } + c->iOffset = 0; /* start tokenizing at the beginning */ + c->iToken = 0; + c->pToken = NULL; /* no space allocated, yet. */ + c->nTokenAllocated = 0; + + *ppCursor = &c->base; + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** simpleOpen() above. +*/ +static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + sqlite3_free(c->pToken); + sqlite3_free(c); + return SQLITE_OK; +} + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to simpleOpen(). +*/ +static int simpleNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; + simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer; + unsigned char *p = (unsigned char *)c->pInput; + + while( c->iOffsetnBytes ){ + int iStartOffset; + + /* Scan past delimiter characters */ + while( c->iOffsetnBytes && simpleDelim(t, p[c->iOffset]) ){ + c->iOffset++; + } + + /* Count non-delimiter characters. */ + iStartOffset = c->iOffset; + while( c->iOffsetnBytes && !simpleDelim(t, p[c->iOffset]) ){ + c->iOffset++; + } + + if( c->iOffset>iStartOffset ){ + int i, n = c->iOffset-iStartOffset; + if( n>c->nTokenAllocated ){ + char *pNew; + c->nTokenAllocated = n+20; + pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated); + if( !pNew ) return SQLITE_NOMEM; + c->pToken = pNew; + } + for(i=0; ipToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch); + } + *ppToken = c->pToken; + *pnBytes = n; + *piStartOffset = iStartOffset; + *piEndOffset = c->iOffset; + *piPosition = c->iToken++; + + return SQLITE_OK; + } + } + return SQLITE_DONE; +} + +/* +** The set of routines that implement the simple tokenizer +*/ +static const sqlite3_tokenizer_module simpleTokenizerModule = { + 0, + simpleCreate, + simpleDestroy, + simpleOpen, + simpleClose, + simpleNext, + 0, +}; + +/* +** Allocate a new simple tokenizer. Return a pointer to the new +** tokenizer in *ppModule +*/ +void sqlite3Fts3SimpleTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &simpleTokenizerModule; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_unicode.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_unicode.c new file mode 100644 index 0000000000000000000000000000000000000000..188358eade42e3262f9505c7a229c2dcec48a44d --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_unicode.c @@ -0,0 +1,393 @@ +/* +** 2012 May 24 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** Implementation of the "unicode" full-text-search tokenizer. +*/ + +#ifdef SQLITE_ENABLE_FTS4_UNICODE61 + +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#include +#include +#include +#include + +#include "fts3_tokenizer.h" + +/* +** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied +** from the sqlite3 source file utf.c. If this file is compiled as part +** of the amalgamation, they are not required. +*/ +#ifndef SQLITE_AMALGAMATION + +static const unsigned char sqlite3Utf8Trans1[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, +}; + +#define READ_UTF8(zIn, zTerm, c) \ + c = *(zIn++); \ + if( c>=0xc0 ){ \ + c = sqlite3Utf8Trans1[c-0xc0]; \ + while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ + c = (c<<6) + (0x3f & *(zIn++)); \ + } \ + if( c<0x80 \ + || (c&0xFFFFF800)==0xD800 \ + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ + } + +#define WRITE_UTF8(zOut, c) { \ + if( c<0x00080 ){ \ + *zOut++ = (u8)(c&0xFF); \ + } \ + else if( c<0x00800 ){ \ + *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ + else if( c<0x10000 ){ \ + *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + }else{ \ + *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ + *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ +} + +#endif /* ifndef SQLITE_AMALGAMATION */ + +typedef struct unicode_tokenizer unicode_tokenizer; +typedef struct unicode_cursor unicode_cursor; + +struct unicode_tokenizer { + sqlite3_tokenizer base; + int bRemoveDiacritic; + int nException; + int *aiException; +}; + +struct unicode_cursor { + sqlite3_tokenizer_cursor base; + const unsigned char *aInput; /* Input text being tokenized */ + int nInput; /* Size of aInput[] in bytes */ + int iOff; /* Current offset within aInput[] */ + int iToken; /* Index of next token to be returned */ + char *zToken; /* storage for current token */ + int nAlloc; /* space allocated at zToken */ +}; + + +/* +** Destroy a tokenizer allocated by unicodeCreate(). +*/ +static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){ + if( pTokenizer ){ + unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer; + sqlite3_free(p->aiException); + sqlite3_free(p); + } + return SQLITE_OK; +} + +/* +** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE +** statement has specified that the tokenizer for this table shall consider +** all characters in string zIn/nIn to be separators (if bAlnum==0) or +** token characters (if bAlnum==1). +** +** For each codepoint in the zIn/nIn string, this function checks if the +** sqlite3FtsUnicodeIsalnum() function already returns the desired result. +** If so, no action is taken. Otherwise, the codepoint is added to the +** unicode_tokenizer.aiException[] array. For the purposes of tokenization, +** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all +** codepoints in the aiException[] array. +** +** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic() +** identifies as a diacritic) occurs in the zIn/nIn string it is ignored. +** It is not possible to change the behavior of the tokenizer with respect +** to these codepoints. +*/ +static int unicodeAddExceptions( + unicode_tokenizer *p, /* Tokenizer to add exceptions to */ + int bAlnum, /* Replace Isalnum() return value with this */ + const char *zIn, /* Array of characters to make exceptions */ + int nIn /* Length of z in bytes */ +){ + const unsigned char *z = (const unsigned char *)zIn; + const unsigned char *zTerm = &z[nIn]; + int iCode; + int nEntry = 0; + + assert( bAlnum==0 || bAlnum==1 ); + + while( zaiException, (p->nException+nEntry)*sizeof(int)); + if( aNew==0 ) return SQLITE_NOMEM; + nNew = p->nException; + + z = (const unsigned char *)zIn; + while( zi; j--) aNew[j] = aNew[j-1]; + aNew[i] = iCode; + nNew++; + } + } + p->aiException = aNew; + p->nException = nNew; + } + + return SQLITE_OK; +} + +/* +** Return true if the p->aiException[] array contains the value iCode. +*/ +static int unicodeIsException(unicode_tokenizer *p, int iCode){ + if( p->nException>0 ){ + int *a = p->aiException; + int iLo = 0; + int iHi = p->nException-1; + + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + if( iCode==a[iTest] ){ + return 1; + }else if( iCode>a[iTest] ){ + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + } + + return 0; +} + +/* +** Return true if, for the purposes of tokenization, codepoint iCode is +** considered a token character (not a separator). +*/ +static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){ + assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); + return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode); +} + +/* +** Create a new tokenizer instance. +*/ +static int unicodeCreate( + int nArg, /* Size of array argv[] */ + const char * const *azArg, /* Tokenizer creation arguments */ + sqlite3_tokenizer **pp /* OUT: New tokenizer handle */ +){ + unicode_tokenizer *pNew; /* New tokenizer object */ + int i; + int rc = SQLITE_OK; + + pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer)); + if( pNew==NULL ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(unicode_tokenizer)); + pNew->bRemoveDiacritic = 1; + + for(i=0; rc==SQLITE_OK && ibRemoveDiacritic = 1; + } + else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){ + pNew->bRemoveDiacritic = 0; + } + else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){ + rc = unicodeAddExceptions(pNew, 1, &z[11], n-11); + } + else if( n>=11 && memcmp("separators=", z, 11)==0 ){ + rc = unicodeAddExceptions(pNew, 0, &z[11], n-11); + } + else{ + /* Unrecognized argument */ + rc = SQLITE_ERROR; + } + } + + if( rc!=SQLITE_OK ){ + unicodeDestroy((sqlite3_tokenizer *)pNew); + pNew = 0; + } + *pp = (sqlite3_tokenizer *)pNew; + return rc; +} + +/* +** Prepare to begin tokenizing a particular string. The input +** string to be tokenized is pInput[0..nBytes-1]. A cursor +** used to incrementally tokenize this string is returned in +** *ppCursor. +*/ +static int unicodeOpen( + sqlite3_tokenizer *p, /* The tokenizer */ + const char *aInput, /* Input string */ + int nInput, /* Size of string aInput in bytes */ + sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */ +){ + unicode_cursor *pCsr; + + pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor)); + if( pCsr==0 ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(unicode_cursor)); + + pCsr->aInput = (const unsigned char *)aInput; + if( aInput==0 ){ + pCsr->nInput = 0; + }else if( nInput<0 ){ + pCsr->nInput = (int)strlen(aInput); + }else{ + pCsr->nInput = nInput; + } + + *pp = &pCsr->base; + UNUSED_PARAMETER(p); + return SQLITE_OK; +} + +/* +** Close a tokenization cursor previously opened by a call to +** simpleOpen() above. +*/ +static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){ + unicode_cursor *pCsr = (unicode_cursor *) pCursor; + sqlite3_free(pCsr->zToken); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** Extract the next token from a tokenization cursor. The cursor must +** have been opened by a prior call to simpleOpen(). +*/ +static int unicodeNext( + sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */ + const char **paToken, /* OUT: Token text */ + int *pnToken, /* OUT: Number of bytes at *paToken */ + int *piStart, /* OUT: Starting offset of token */ + int *piEnd, /* OUT: Ending offset of token */ + int *piPos /* OUT: Position integer of token */ +){ + unicode_cursor *pCsr = (unicode_cursor *)pC; + unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer); + int iCode; + char *zOut; + const unsigned char *z = &pCsr->aInput[pCsr->iOff]; + const unsigned char *zStart = z; + const unsigned char *zEnd; + const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput]; + + /* Scan past any delimiter characters before the start of the next token. + ** Return SQLITE_DONE early if this takes us all the way to the end of + ** the input. */ + while( z=zTerm ) return SQLITE_DONE; + + zOut = pCsr->zToken; + do { + int iOut; + + /* Grow the output buffer if required. */ + if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){ + char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64); + if( !zNew ) return SQLITE_NOMEM; + zOut = &zNew[zOut - pCsr->zToken]; + pCsr->zToken = zNew; + pCsr->nAlloc += 64; + } + + /* Write the folded case of the last character read to the output */ + zEnd = z; + iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic); + if( iOut ){ + WRITE_UTF8(zOut, iOut); + } + + /* If the cursor is not at EOF, read the next character */ + if( z>=zTerm ) break; + READ_UTF8(z, zTerm, iCode); + }while( unicodeIsAlnum(p, iCode) + || sqlite3FtsUnicodeIsdiacritic(iCode) + ); + + /* Set the output variables and return. */ + pCsr->iOff = (z - pCsr->aInput); + *paToken = pCsr->zToken; + *pnToken = zOut - pCsr->zToken; + *piStart = (zStart - pCsr->aInput); + *piEnd = (zEnd - pCsr->aInput); + *piPos = pCsr->iToken++; + return SQLITE_OK; +} + +/* +** Set *ppModule to a pointer to the sqlite3_tokenizer_module +** structure for the unicode tokenizer. +*/ +void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){ + static const sqlite3_tokenizer_module module = { + 0, + unicodeCreate, + unicodeDestroy, + unicodeOpen, + unicodeClose, + unicodeNext, + 0, + }; + *ppModule = &module; +} + +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ +#endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_unicode2.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_unicode2.c new file mode 100644 index 0000000000000000000000000000000000000000..fba688ff9ce5fe68098eec8bee4debb613f4b1fd --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_unicode2.c @@ -0,0 +1,365 @@ +/* +** 2012 May 25 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +*/ + +/* +** DO NOT EDIT THIS MACHINE GENERATED FILE. +*/ + +#if defined(SQLITE_ENABLE_FTS4_UNICODE61) +#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) + +#include + +/* +** Return true if the argument corresponds to a unicode codepoint +** classified as either a letter or a number. Otherwise false. +** +** The results are undefined if the value passed to this function +** is less than zero. +*/ +int sqlite3FtsUnicodeIsalnum(int c){ + /* Each unsigned integer in the following array corresponds to a contiguous + ** range of unicode codepoints that are not either letters or numbers (i.e. + ** codepoints for which this function should return 0). + ** + ** The most significant 22 bits in each 32-bit value contain the first + ** codepoint in the range. The least significant 10 bits are used to store + ** the size of the range (always at least 1). In other words, the value + ** ((C<<22) + N) represents a range of N codepoints starting with codepoint + ** C. It is not possible to represent a range larger than 1023 codepoints + ** using this format. + */ + const static unsigned int aEntry[] = { + 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07, + 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01, + 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401, + 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01, + 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01, + 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802, + 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F, + 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401, + 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804, + 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403, + 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812, + 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001, + 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802, + 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805, + 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401, + 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03, + 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807, + 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001, + 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01, + 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804, + 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001, + 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802, + 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01, + 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06, + 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007, + 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006, + 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417, + 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14, + 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07, + 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01, + 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001, + 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802, + 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F, + 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002, + 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802, + 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006, + 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D, + 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802, + 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027, + 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403, + 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805, + 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04, + 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401, + 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005, + 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B, + 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A, + 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001, + 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59, + 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807, + 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01, + 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E, + 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100, + 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10, + 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402, + 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804, + 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012, + 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004, + 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002, + 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803, + 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07, + 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02, + 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802, + 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013, + 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06, + 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003, + 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01, + 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403, + 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009, + 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003, + 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003, + 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E, + 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046, + 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401, + 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401, + 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F, + 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C, + 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002, + 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025, + 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6, + 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46, + 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060, + 0x380400F0, + }; + static const unsigned int aAscii[4] = { + 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001, + }; + + if( c<128 ){ + return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 ); + }else if( c<(1<<22) ){ + unsigned int key = (((unsigned int)c)<<10) | 0x000003FF; + int iRes; + int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; + int iLo = 0; + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + if( key >= aEntry[iTest] ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + assert( aEntry[0]=aEntry[iRes] ); + return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF))); + } + return 1; +} + + +/* +** If the argument is a codepoint corresponding to a lowercase letter +** in the ASCII range with a diacritic added, return the codepoint +** of the ASCII letter only. For example, if passed 235 - "LATIN +** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER +** E"). The resuls of passing a codepoint that corresponds to an +** uppercase letter are undefined. +*/ +static int remove_diacritic(int c){ + unsigned short aDia[] = { + 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995, + 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286, + 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732, + 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336, + 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928, + 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234, + 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504, + 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529, + 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, + 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, + 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, + 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, + 62924, 63050, 63082, 63274, 63390, + }; + char aChar[] = { + '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c', + 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r', + 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o', + 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r', + 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h', + 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't', + 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a', + 'e', 'i', 'o', 'u', 'y', + }; + + unsigned int key = (((unsigned int)c)<<3) | 0x00000007; + int iRes = 0; + int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1; + int iLo = 0; + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + if( key >= aDia[iTest] ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + assert( key>=aDia[iRes] ); + return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]); +}; + + +/* +** Return true if the argument interpreted as a unicode codepoint +** is a diacritical modifier character. +*/ +int sqlite3FtsUnicodeIsdiacritic(int c){ + unsigned int mask0 = 0x08029FDF; + unsigned int mask1 = 0x000361F8; + if( c<768 || c>817 ) return 0; + return (c < 768+32) ? + (mask0 & (1 << (c-768))) : + (mask1 & (1 << (c-768-32))); +} + + +/* +** Interpret the argument as a unicode codepoint. If the codepoint +** is an upper case character that has a lower case equivalent, +** return the codepoint corresponding to the lower case version. +** Otherwise, return a copy of the argument. +** +** The results are undefined if the value passed to this function +** is less than zero. +*/ +int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ + /* Each entry in the following array defines a rule for folding a range + ** of codepoints to lower case. The rule applies to a range of nRange + ** codepoints starting at codepoint iCode. + ** + ** If the least significant bit in flags is clear, then the rule applies + ** to all nRange codepoints (i.e. all nRange codepoints are upper case and + ** need to be folded). Or, if it is set, then the rule only applies to + ** every second codepoint in the range, starting with codepoint C. + ** + ** The 7 most significant bits in flags are an index into the aiOff[] + ** array. If a specific codepoint C does require folding, then its lower + ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF). + ** + ** The contents of this array are generated by parsing the CaseFolding.txt + ** file distributed as part of the "Unicode Character Database". See + ** http://www.unicode.org for details. + */ + static const struct TableEntry { + unsigned short iCode; + unsigned char flags; + unsigned char nRange; + } aEntry[] = { + {65, 14, 26}, {181, 64, 1}, {192, 14, 23}, + {216, 14, 7}, {256, 1, 48}, {306, 1, 6}, + {313, 1, 16}, {330, 1, 46}, {376, 116, 1}, + {377, 1, 6}, {383, 104, 1}, {385, 50, 1}, + {386, 1, 4}, {390, 44, 1}, {391, 0, 1}, + {393, 42, 2}, {395, 0, 1}, {398, 32, 1}, + {399, 38, 1}, {400, 40, 1}, {401, 0, 1}, + {403, 42, 1}, {404, 46, 1}, {406, 52, 1}, + {407, 48, 1}, {408, 0, 1}, {412, 52, 1}, + {413, 54, 1}, {415, 56, 1}, {416, 1, 6}, + {422, 60, 1}, {423, 0, 1}, {425, 60, 1}, + {428, 0, 1}, {430, 60, 1}, {431, 0, 1}, + {433, 58, 2}, {435, 1, 4}, {439, 62, 1}, + {440, 0, 1}, {444, 0, 1}, {452, 2, 1}, + {453, 0, 1}, {455, 2, 1}, {456, 0, 1}, + {458, 2, 1}, {459, 1, 18}, {478, 1, 18}, + {497, 2, 1}, {498, 1, 4}, {502, 122, 1}, + {503, 134, 1}, {504, 1, 40}, {544, 110, 1}, + {546, 1, 18}, {570, 70, 1}, {571, 0, 1}, + {573, 108, 1}, {574, 68, 1}, {577, 0, 1}, + {579, 106, 1}, {580, 28, 1}, {581, 30, 1}, + {582, 1, 10}, {837, 36, 1}, {880, 1, 4}, + {886, 0, 1}, {902, 18, 1}, {904, 16, 3}, + {908, 26, 1}, {910, 24, 2}, {913, 14, 17}, + {931, 14, 9}, {962, 0, 1}, {975, 4, 1}, + {976, 140, 1}, {977, 142, 1}, {981, 146, 1}, + {982, 144, 1}, {984, 1, 24}, {1008, 136, 1}, + {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1}, + {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1}, + {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32}, + {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1}, + {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38}, + {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1}, + {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1}, + {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6}, + {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6}, + {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8}, + {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2}, + {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1}, + {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2}, + {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2}, + {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2}, + {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1}, + {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16}, + {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47}, + {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1}, + {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1}, + {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1}, + {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2}, + {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1}, + {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14}, + {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1}, + {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1}, + {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1}, + {65313, 14, 26}, + }; + static const unsigned short aiOff[] = { + 1, 2, 8, 15, 16, 26, 28, 32, + 37, 38, 40, 48, 63, 64, 69, 71, + 79, 80, 116, 202, 203, 205, 206, 207, + 209, 210, 211, 213, 214, 217, 218, 219, + 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721, + 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, + 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, + 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, + 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, + 65514, 65521, 65527, 65528, 65529, + }; + + int ret = c; + + assert( c>=0 ); + assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 ); + + if( c<128 ){ + if( c>='A' && c<='Z' ) ret = c + ('a' - 'A'); + }else if( c<65536 ){ + int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; + int iLo = 0; + int iRes = -1; + + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + int cmp = (c - aEntry[iTest].iCode); + if( cmp>=0 ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + assert( iRes<0 || c>=aEntry[iRes].iCode ); + + if( iRes>=0 ){ + const struct TableEntry *p = &aEntry[iRes]; + if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){ + ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF; + assert( ret>0 ); + } + } + + if( bRemoveDiacritic ) ret = remove_diacritic(ret); + } + + else if( c>=66560 && c<66600 ){ + ret = c + 40; + } + + return ret; +} +#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */ +#endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */ diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3_write.c b/components/external/SQLite-3.8.1/ext/fts3/fts3_write.c new file mode 100644 index 0000000000000000000000000000000000000000..794b6dcbf1ffaff0747ec1fb3e9f829ea66af056 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3_write.c @@ -0,0 +1,5419 @@ +/* +** 2009 Oct 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file is part of the SQLite FTS3 extension module. Specifically, +** this file contains code to insert, update and delete rows from FTS3 +** tables. It also contains code to merge FTS3 b-tree segments. Some +** of the sub-routines used to merge segments are also used by the query +** code in fts3.c. +*/ + +#include "fts3Int.h" +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) + +#include +#include +#include + + +#define FTS_MAX_APPENDABLE_HEIGHT 16 + +/* +** When full-text index nodes are loaded from disk, the buffer that they +** are loaded into has the following number of bytes of padding at the end +** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer +** of 920 bytes is allocated for it. +** +** This means that if we have a pointer into a buffer containing node data, +** it is always safe to read up to two varints from it without risking an +** overread, even if the node data is corrupted. +*/ +#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2) + +/* +** Under certain circumstances, b-tree nodes (doclists) can be loaded into +** memory incrementally instead of all at once. This can be a big performance +** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext() +** method before retrieving all query results (as may happen, for example, +** if a query has a LIMIT clause). +** +** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD +** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes. +** The code is written so that the hard lower-limit for each of these values +** is 1. Clearly such small values would be inefficient, but can be useful +** for testing purposes. +** +** If this module is built with SQLITE_TEST defined, these constants may +** be overridden at runtime for testing purposes. File fts3_test.c contains +** a Tcl interface to read and write the values. +*/ +#ifdef SQLITE_TEST +int test_fts3_node_chunksize = (4*1024); +int test_fts3_node_chunk_threshold = (4*1024)*4; +# define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize +# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold +#else +# define FTS3_NODE_CHUNKSIZE (4*1024) +# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4) +#endif + +/* +** The two values that may be meaningfully bound to the :1 parameter in +** statements SQL_REPLACE_STAT and SQL_SELECT_STAT. +*/ +#define FTS_STAT_DOCTOTAL 0 +#define FTS_STAT_INCRMERGEHINT 1 +#define FTS_STAT_AUTOINCRMERGE 2 + +/* +** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic +** and incremental merge operation that takes place. This is used for +** debugging FTS only, it should not usually be turned on in production +** systems. +*/ +#ifdef FTS3_LOG_MERGES +static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){ + sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel); +} +#else +#define fts3LogMerge(x, y) +#endif + + +typedef struct PendingList PendingList; +typedef struct SegmentNode SegmentNode; +typedef struct SegmentWriter SegmentWriter; + +/* +** An instance of the following data structure is used to build doclists +** incrementally. See function fts3PendingListAppend() for details. +*/ +struct PendingList { + int nData; + char *aData; + int nSpace; + sqlite3_int64 iLastDocid; + sqlite3_int64 iLastCol; + sqlite3_int64 iLastPos; +}; + + +/* +** Each cursor has a (possibly empty) linked list of the following objects. +*/ +struct Fts3DeferredToken { + Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */ + int iCol; /* Column token must occur in */ + Fts3DeferredToken *pNext; /* Next in list of deferred tokens */ + PendingList *pList; /* Doclist is assembled here */ +}; + +/* +** An instance of this structure is used to iterate through the terms on +** a contiguous set of segment b-tree leaf nodes. Although the details of +** this structure are only manipulated by code in this file, opaque handles +** of type Fts3SegReader* are also used by code in fts3.c to iterate through +** terms when querying the full-text index. See functions: +** +** sqlite3Fts3SegReaderNew() +** sqlite3Fts3SegReaderFree() +** sqlite3Fts3SegReaderIterate() +** +** Methods used to manipulate Fts3SegReader structures: +** +** fts3SegReaderNext() +** fts3SegReaderFirstDocid() +** fts3SegReaderNextDocid() +*/ +struct Fts3SegReader { + int iIdx; /* Index within level, or 0x7FFFFFFF for PT */ + u8 bLookup; /* True for a lookup only */ + u8 rootOnly; /* True for a root-only reader */ + + sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */ + sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */ + sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */ + sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */ + + char *aNode; /* Pointer to node data (or NULL) */ + int nNode; /* Size of buffer at aNode (or 0) */ + int nPopulate; /* If >0, bytes of buffer aNode[] loaded */ + sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */ + + Fts3HashElem **ppNextElem; + + /* Variables set by fts3SegReaderNext(). These may be read directly + ** by the caller. They are valid from the time SegmentReaderNew() returns + ** until SegmentReaderNext() returns something other than SQLITE_OK + ** (i.e. SQLITE_DONE). + */ + int nTerm; /* Number of bytes in current term */ + char *zTerm; /* Pointer to current term */ + int nTermAlloc; /* Allocated size of zTerm buffer */ + char *aDoclist; /* Pointer to doclist of current entry */ + int nDoclist; /* Size of doclist in current entry */ + + /* The following variables are used by fts3SegReaderNextDocid() to iterate + ** through the current doclist (aDoclist/nDoclist). + */ + char *pOffsetList; + int nOffsetList; /* For descending pending seg-readers only */ + sqlite3_int64 iDocid; +}; + +#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0) +#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0) + +/* +** An instance of this structure is used to create a segment b-tree in the +** database. The internal details of this type are only accessed by the +** following functions: +** +** fts3SegWriterAdd() +** fts3SegWriterFlush() +** fts3SegWriterFree() +*/ +struct SegmentWriter { + SegmentNode *pTree; /* Pointer to interior tree structure */ + sqlite3_int64 iFirst; /* First slot in %_segments written */ + sqlite3_int64 iFree; /* Next free slot in %_segments */ + char *zTerm; /* Pointer to previous term buffer */ + int nTerm; /* Number of bytes in zTerm */ + int nMalloc; /* Size of malloc'd buffer at zMalloc */ + char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ + int nSize; /* Size of allocation at aData */ + int nData; /* Bytes of data in aData */ + char *aData; /* Pointer to block from malloc() */ +}; + +/* +** Type SegmentNode is used by the following three functions to create +** the interior part of the segment b+-tree structures (everything except +** the leaf nodes). These functions and type are only ever used by code +** within the fts3SegWriterXXX() family of functions described above. +** +** fts3NodeAddTerm() +** fts3NodeWrite() +** fts3NodeFree() +** +** When a b+tree is written to the database (either as a result of a merge +** or the pending-terms table being flushed), leaves are written into the +** database file as soon as they are completely populated. The interior of +** the tree is assembled in memory and written out only once all leaves have +** been populated and stored. This is Ok, as the b+-tree fanout is usually +** very large, meaning that the interior of the tree consumes relatively +** little memory. +*/ +struct SegmentNode { + SegmentNode *pParent; /* Parent node (or NULL for root node) */ + SegmentNode *pRight; /* Pointer to right-sibling */ + SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */ + int nEntry; /* Number of terms written to node so far */ + char *zTerm; /* Pointer to previous term buffer */ + int nTerm; /* Number of bytes in zTerm */ + int nMalloc; /* Size of malloc'd buffer at zMalloc */ + char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ + int nData; /* Bytes of valid data so far */ + char *aData; /* Node data */ +}; + +/* +** Valid values for the second argument to fts3SqlStmt(). +*/ +#define SQL_DELETE_CONTENT 0 +#define SQL_IS_EMPTY 1 +#define SQL_DELETE_ALL_CONTENT 2 +#define SQL_DELETE_ALL_SEGMENTS 3 +#define SQL_DELETE_ALL_SEGDIR 4 +#define SQL_DELETE_ALL_DOCSIZE 5 +#define SQL_DELETE_ALL_STAT 6 +#define SQL_SELECT_CONTENT_BY_ROWID 7 +#define SQL_NEXT_SEGMENT_INDEX 8 +#define SQL_INSERT_SEGMENTS 9 +#define SQL_NEXT_SEGMENTS_ID 10 +#define SQL_INSERT_SEGDIR 11 +#define SQL_SELECT_LEVEL 12 +#define SQL_SELECT_LEVEL_RANGE 13 +#define SQL_SELECT_LEVEL_COUNT 14 +#define SQL_SELECT_SEGDIR_MAX_LEVEL 15 +#define SQL_DELETE_SEGDIR_LEVEL 16 +#define SQL_DELETE_SEGMENTS_RANGE 17 +#define SQL_CONTENT_INSERT 18 +#define SQL_DELETE_DOCSIZE 19 +#define SQL_REPLACE_DOCSIZE 20 +#define SQL_SELECT_DOCSIZE 21 +#define SQL_SELECT_STAT 22 +#define SQL_REPLACE_STAT 23 + +#define SQL_SELECT_ALL_PREFIX_LEVEL 24 +#define SQL_DELETE_ALL_TERMS_SEGDIR 25 +#define SQL_DELETE_SEGDIR_RANGE 26 +#define SQL_SELECT_ALL_LANGID 27 +#define SQL_FIND_MERGE_LEVEL 28 +#define SQL_MAX_LEAF_NODE_ESTIMATE 29 +#define SQL_DELETE_SEGDIR_ENTRY 30 +#define SQL_SHIFT_SEGDIR_ENTRY 31 +#define SQL_SELECT_SEGDIR 32 +#define SQL_CHOMP_SEGDIR 33 +#define SQL_SEGMENT_IS_APPENDABLE 34 +#define SQL_SELECT_INDEXES 35 +#define SQL_SELECT_MXLEVEL 36 + +/* +** This function is used to obtain an SQLite prepared statement handle +** for the statement identified by the second argument. If successful, +** *pp is set to the requested statement handle and SQLITE_OK returned. +** Otherwise, an SQLite error code is returned and *pp is set to 0. +** +** If argument apVal is not NULL, then it must point to an array with +** at least as many entries as the requested statement has bound +** parameters. The values are bound to the statements parameters before +** returning. +*/ +static int fts3SqlStmt( + Fts3Table *p, /* Virtual table handle */ + int eStmt, /* One of the SQL_XXX constants above */ + sqlite3_stmt **pp, /* OUT: Statement handle */ + sqlite3_value **apVal /* Values to bind to statement */ +){ + const char *azSql[] = { +/* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?", +/* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)", +/* 2 */ "DELETE FROM %Q.'%q_content'", +/* 3 */ "DELETE FROM %Q.'%q_segments'", +/* 4 */ "DELETE FROM %Q.'%q_segdir'", +/* 5 */ "DELETE FROM %Q.'%q_docsize'", +/* 6 */ "DELETE FROM %Q.'%q_stat'", +/* 7 */ "SELECT %s WHERE rowid=?", +/* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1", +/* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)", +/* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)", +/* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)", + + /* Return segments in order from oldest to newest.*/ +/* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root " + "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC", +/* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root " + "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?" + "ORDER BY level DESC, idx ASC", + +/* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?", +/* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", + +/* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?", +/* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?", +/* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)", +/* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?", +/* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", +/* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?", +/* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?", +/* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)", +/* 24 */ "", +/* 25 */ "", + +/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", +/* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'", + +/* This statement is used to determine which level to read the input from +** when performing an incremental merge. It returns the absolute level number +** of the oldest level in the db that contains at least ? segments. Or, +** if no level in the FTS index contains more than ? segments, the statement +** returns zero rows. */ +/* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?" + " ORDER BY (level %% 1024) ASC LIMIT 1", + +/* Estimate the upper limit on the number of leaf nodes in a new segment +** created by merging the oldest :2 segments from absolute level :1. See +** function sqlite3Fts3Incrmerge() for details. */ +/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) " + " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?", + +/* SQL_DELETE_SEGDIR_ENTRY +** Delete the %_segdir entry on absolute level :1 with index :2. */ +/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", + +/* SQL_SHIFT_SEGDIR_ENTRY +** Modify the idx value for the segment with idx=:3 on absolute level :2 +** to :1. */ +/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?", + +/* SQL_SELECT_SEGDIR +** Read a single entry from the %_segdir table. The entry from absolute +** level :1 with index value :2. */ +/* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root " + "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", + +/* SQL_CHOMP_SEGDIR +** Update the start_block (:1) and root (:2) fields of the %_segdir +** entry located on absolute level :3 with index :4. */ +/* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?" + "WHERE level = ? AND idx = ?", + +/* SQL_SEGMENT_IS_APPENDABLE +** Return a single row if the segment with end_block=? is appendable. Or +** no rows otherwise. */ +/* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL", + +/* SQL_SELECT_INDEXES +** Return the list of valid segment indexes for absolute level ? */ +/* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC", + +/* SQL_SELECT_MXLEVEL +** Return the largest relative level in the FTS index or indexes. */ +/* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'" + }; + int rc = SQLITE_OK; + sqlite3_stmt *pStmt; + + assert( SizeofArray(azSql)==SizeofArray(p->aStmt) ); + assert( eStmt=0 ); + + pStmt = p->aStmt[eStmt]; + if( !pStmt ){ + char *zSql; + if( eStmt==SQL_CONTENT_INSERT ){ + zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist); + }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){ + zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist); + }else{ + zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName); + } + if( !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL); + sqlite3_free(zSql); + assert( rc==SQLITE_OK || pStmt==0 ); + p->aStmt[eStmt] = pStmt; + } + } + if( apVal ){ + int i; + int nParam = sqlite3_bind_parameter_count(pStmt); + for(i=0; rc==SQLITE_OK && inPendingData==0 ){ + sqlite3_stmt *pStmt; + rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_null(pStmt, 1); + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + } + } + + return rc; +} + +/* +** FTS maintains a separate indexes for each language-id (a 32-bit integer). +** Within each language id, a separate index is maintained to store the +** document terms, and each configured prefix size (configured the FTS +** "prefix=" option). And each index consists of multiple levels ("relative +** levels"). +** +** All three of these values (the language id, the specific index and the +** level within the index) are encoded in 64-bit integer values stored +** in the %_segdir table on disk. This function is used to convert three +** separate component values into the single 64-bit integer value that +** can be used to query the %_segdir table. +** +** Specifically, each language-id/index combination is allocated 1024 +** 64-bit integer level values ("absolute levels"). The main terms index +** for language-id 0 is allocate values 0-1023. The first prefix index +** (if any) for language-id 0 is allocated values 1024-2047. And so on. +** Language 1 indexes are allocated immediately following language 0. +** +** So, for a system with nPrefix prefix indexes configured, the block of +** absolute levels that corresponds to language-id iLangid and index +** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024). +*/ +static sqlite3_int64 getAbsoluteLevel( + Fts3Table *p, /* FTS3 table handle */ + int iLangid, /* Language id */ + int iIndex, /* Index in p->aIndex[] */ + int iLevel /* Level of segments */ +){ + sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */ + assert( iLangid>=0 ); + assert( p->nIndex>0 ); + assert( iIndex>=0 && iIndexnIndex ); + + iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL; + return iBase + iLevel; +} + +/* +** Set *ppStmt to a statement handle that may be used to iterate through +** all rows in the %_segdir table, from oldest to newest. If successful, +** return SQLITE_OK. If an error occurs while preparing the statement, +** return an SQLite error code. +** +** There is only ever one instance of this SQL statement compiled for +** each FTS3 table. +** +** The statement returns the following columns from the %_segdir table: +** +** 0: idx +** 1: start_block +** 2: leaves_end_block +** 3: end_block +** 4: root +*/ +int sqlite3Fts3AllSegdirs( + Fts3Table *p, /* FTS3 table */ + int iLangid, /* Language being queried */ + int iIndex, /* Index for p->aIndex[] */ + int iLevel, /* Level to select (relative level) */ + sqlite3_stmt **ppStmt /* OUT: Compiled statement */ +){ + int rc; + sqlite3_stmt *pStmt = 0; + + assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 ); + assert( iLevel=0 && iIndexnIndex ); + + if( iLevel<0 ){ + /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */ + rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); + sqlite3_bind_int64(pStmt, 2, + getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) + ); + } + }else{ + /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */ + rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel)); + } + } + *ppStmt = pStmt; + return rc; +} + + +/* +** Append a single varint to a PendingList buffer. SQLITE_OK is returned +** if successful, or an SQLite error code otherwise. +** +** This function also serves to allocate the PendingList structure itself. +** For example, to create a new PendingList structure containing two +** varints: +** +** PendingList *p = 0; +** fts3PendingListAppendVarint(&p, 1); +** fts3PendingListAppendVarint(&p, 2); +*/ +static int fts3PendingListAppendVarint( + PendingList **pp, /* IN/OUT: Pointer to PendingList struct */ + sqlite3_int64 i /* Value to append to data */ +){ + PendingList *p = *pp; + + /* Allocate or grow the PendingList as required. */ + if( !p ){ + p = sqlite3_malloc(sizeof(*p) + 100); + if( !p ){ + return SQLITE_NOMEM; + } + p->nSpace = 100; + p->aData = (char *)&p[1]; + p->nData = 0; + } + else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){ + int nNew = p->nSpace * 2; + p = sqlite3_realloc(p, sizeof(*p) + nNew); + if( !p ){ + sqlite3_free(*pp); + *pp = 0; + return SQLITE_NOMEM; + } + p->nSpace = nNew; + p->aData = (char *)&p[1]; + } + + /* Append the new serialized varint to the end of the list. */ + p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i); + p->aData[p->nData] = '\0'; + *pp = p; + return SQLITE_OK; +} + +/* +** Add a docid/column/position entry to a PendingList structure. Non-zero +** is returned if the structure is sqlite3_realloced as part of adding +** the entry. Otherwise, zero. +** +** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning. +** Zero is always returned in this case. Otherwise, if no OOM error occurs, +** it is set to SQLITE_OK. +*/ +static int fts3PendingListAppend( + PendingList **pp, /* IN/OUT: PendingList structure */ + sqlite3_int64 iDocid, /* Docid for entry to add */ + sqlite3_int64 iCol, /* Column for entry to add */ + sqlite3_int64 iPos, /* Position of term for entry to add */ + int *pRc /* OUT: Return code */ +){ + PendingList *p = *pp; + int rc = SQLITE_OK; + + assert( !p || p->iLastDocid<=iDocid ); + + if( !p || p->iLastDocid!=iDocid ){ + sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0); + if( p ){ + assert( p->nDatanSpace ); + assert( p->aData[p->nData]==0 ); + p->nData++; + } + if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){ + goto pendinglistappend_out; + } + p->iLastCol = -1; + p->iLastPos = 0; + p->iLastDocid = iDocid; + } + if( iCol>0 && p->iLastCol!=iCol ){ + if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1)) + || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol)) + ){ + goto pendinglistappend_out; + } + p->iLastCol = iCol; + p->iLastPos = 0; + } + if( iCol>=0 ){ + assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) ); + rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos); + if( rc==SQLITE_OK ){ + p->iLastPos = iPos; + } + } + + pendinglistappend_out: + *pRc = rc; + if( p!=*pp ){ + *pp = p; + return 1; + } + return 0; +} + +/* +** Free a PendingList object allocated by fts3PendingListAppend(). +*/ +static void fts3PendingListDelete(PendingList *pList){ + sqlite3_free(pList); +} + +/* +** Add an entry to one of the pending-terms hash tables. +*/ +static int fts3PendingTermsAddOne( + Fts3Table *p, + int iCol, + int iPos, + Fts3Hash *pHash, /* Pending terms hash table to add entry to */ + const char *zToken, + int nToken +){ + PendingList *pList; + int rc = SQLITE_OK; + + pList = (PendingList *)fts3HashFind(pHash, zToken, nToken); + if( pList ){ + p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem)); + } + if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){ + if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){ + /* Malloc failed while inserting the new entry. This can only + ** happen if there was no previous entry for this token. + */ + assert( 0==fts3HashFind(pHash, zToken, nToken) ); + sqlite3_free(pList); + rc = SQLITE_NOMEM; + } + } + if( rc==SQLITE_OK ){ + p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem)); + } + return rc; +} + +/* +** Tokenize the nul-terminated string zText and add all tokens to the +** pending-terms hash-table. The docid used is that currently stored in +** p->iPrevDocid, and the column is specified by argument iCol. +** +** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. +*/ +static int fts3PendingTermsAdd( + Fts3Table *p, /* Table into which text will be inserted */ + int iLangid, /* Language id to use */ + const char *zText, /* Text of document to be inserted */ + int iCol, /* Column into which text is being inserted */ + u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */ +){ + int rc; + int iStart = 0; + int iEnd = 0; + int iPos = 0; + int nWord = 0; + + char const *zToken; + int nToken = 0; + + sqlite3_tokenizer *pTokenizer = p->pTokenizer; + sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + sqlite3_tokenizer_cursor *pCsr; + int (*xNext)(sqlite3_tokenizer_cursor *pCursor, + const char**,int*,int*,int*,int*); + + assert( pTokenizer && pModule ); + + /* If the user has inserted a NULL value, this function may be called with + ** zText==0. In this case, add zero token entries to the hash table and + ** return early. */ + if( zText==0 ){ + *pnWord = 0; + return SQLITE_OK; + } + + rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr); + if( rc!=SQLITE_OK ){ + return rc; + } + + xNext = pModule->xNext; + while( SQLITE_OK==rc + && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos)) + ){ + int i; + if( iPos>=nWord ) nWord = iPos+1; + + /* Positions cannot be negative; we use -1 as a terminator internally. + ** Tokens must have a non-zero length. + */ + if( iPos<0 || !zToken || nToken<=0 ){ + rc = SQLITE_ERROR; + break; + } + + /* Add the term to the terms index */ + rc = fts3PendingTermsAddOne( + p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken + ); + + /* Add the term to each of the prefix indexes that it is not too + ** short for. */ + for(i=1; rc==SQLITE_OK && inIndex; i++){ + struct Fts3Index *pIndex = &p->aIndex[i]; + if( nTokennPrefix ) continue; + rc = fts3PendingTermsAddOne( + p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix + ); + } + } + + pModule->xClose(pCsr); + *pnWord += nWord; + return (rc==SQLITE_DONE ? SQLITE_OK : rc); +} + +/* +** Calling this function indicates that subsequent calls to +** fts3PendingTermsAdd() are to add term/position-list pairs for the +** contents of the document with docid iDocid. +*/ +static int fts3PendingTermsDocid( + Fts3Table *p, /* Full-text table handle */ + int iLangid, /* Language id of row being written */ + sqlite_int64 iDocid /* Docid of row being written */ +){ + assert( iLangid>=0 ); + + /* TODO(shess) Explore whether partially flushing the buffer on + ** forced-flush would provide better performance. I suspect that if + ** we ordered the doclists by size and flushed the largest until the + ** buffer was half empty, that would let the less frequent terms + ** generate longer doclists. + */ + if( iDocid<=p->iPrevDocid + || p->iPrevLangid!=iLangid + || p->nPendingData>p->nMaxPendingData + ){ + int rc = sqlite3Fts3PendingTermsFlush(p); + if( rc!=SQLITE_OK ) return rc; + } + p->iPrevDocid = iDocid; + p->iPrevLangid = iLangid; + return SQLITE_OK; +} + +/* +** Discard the contents of the pending-terms hash tables. +*/ +void sqlite3Fts3PendingTermsClear(Fts3Table *p){ + int i; + for(i=0; inIndex; i++){ + Fts3HashElem *pElem; + Fts3Hash *pHash = &p->aIndex[i].hPending; + for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){ + PendingList *pList = (PendingList *)fts3HashData(pElem); + fts3PendingListDelete(pList); + } + fts3HashClear(pHash); + } + p->nPendingData = 0; +} + +/* +** This function is called by the xUpdate() method as part of an INSERT +** operation. It adds entries for each term in the new record to the +** pendingTerms hash table. +** +** Argument apVal is the same as the similarly named argument passed to +** fts3InsertData(). Parameter iDocid is the docid of the new row. +*/ +static int fts3InsertTerms( + Fts3Table *p, + int iLangid, + sqlite3_value **apVal, + u32 *aSz +){ + int i; /* Iterator variable */ + for(i=2; inColumn+2; i++){ + int iCol = i-2; + if( p->abNotindexed[iCol]==0 ){ + const char *zText = (const char *)sqlite3_value_text(apVal[i]); + int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]); + if( rc!=SQLITE_OK ){ + return rc; + } + aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]); + } + } + return SQLITE_OK; +} + +/* +** This function is called by the xUpdate() method for an INSERT operation. +** The apVal parameter is passed a copy of the apVal argument passed by +** SQLite to the xUpdate() method. i.e: +** +** apVal[0] Not used for INSERT. +** apVal[1] rowid +** apVal[2] Left-most user-defined column +** ... +** apVal[p->nColumn+1] Right-most user-defined column +** apVal[p->nColumn+2] Hidden column with same name as table +** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid) +** apVal[p->nColumn+4] Hidden languageid column +*/ +static int fts3InsertData( + Fts3Table *p, /* Full-text table */ + sqlite3_value **apVal, /* Array of values to insert */ + sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */ +){ + int rc; /* Return code */ + sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */ + + if( p->zContentTbl ){ + sqlite3_value *pRowid = apVal[p->nColumn+3]; + if( sqlite3_value_type(pRowid)==SQLITE_NULL ){ + pRowid = apVal[1]; + } + if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){ + return SQLITE_CONSTRAINT; + } + *piDocid = sqlite3_value_int64(pRowid); + return SQLITE_OK; + } + + /* Locate the statement handle used to insert data into the %_content + ** table. The SQL for this statement is: + ** + ** INSERT INTO %_content VALUES(?, ?, ?, ...) + ** + ** The statement features N '?' variables, where N is the number of user + ** defined columns in the FTS3 table, plus one for the docid field. + */ + rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]); + if( rc==SQLITE_OK && p->zLanguageid ){ + rc = sqlite3_bind_int( + pContentInsert, p->nColumn+2, + sqlite3_value_int(apVal[p->nColumn+4]) + ); + } + if( rc!=SQLITE_OK ) return rc; + + /* There is a quirk here. The users INSERT statement may have specified + ** a value for the "rowid" field, for the "docid" field, or for both. + ** Which is a problem, since "rowid" and "docid" are aliases for the + ** same value. For example: + ** + ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2); + ** + ** In FTS3, this is an error. It is an error to specify non-NULL values + ** for both docid and some other rowid alias. + */ + if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){ + if( SQLITE_NULL==sqlite3_value_type(apVal[0]) + && SQLITE_NULL!=sqlite3_value_type(apVal[1]) + ){ + /* A rowid/docid conflict. */ + return SQLITE_ERROR; + } + rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]); + if( rc!=SQLITE_OK ) return rc; + } + + /* Execute the statement to insert the record. Set *piDocid to the + ** new docid value. + */ + sqlite3_step(pContentInsert); + rc = sqlite3_reset(pContentInsert); + + *piDocid = sqlite3_last_insert_rowid(p->db); + return rc; +} + + + +/* +** Remove all data from the FTS3 table. Clear the hash table containing +** pending terms. +*/ +static int fts3DeleteAll(Fts3Table *p, int bContent){ + int rc = SQLITE_OK; /* Return code */ + + /* Discard the contents of the pending-terms hash table. */ + sqlite3Fts3PendingTermsClear(p); + + /* Delete everything from the shadow tables. Except, leave %_content as + ** is if bContent is false. */ + assert( p->zContentTbl==0 || bContent==0 ); + if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0); + fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0); + fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0); + if( p->bHasDocsize ){ + fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0); + } + if( p->bHasStat ){ + fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0); + } + return rc; +} + +/* +** +*/ +static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){ + int iLangid = 0; + if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1); + return iLangid; +} + +/* +** The first element in the apVal[] array is assumed to contain the docid +** (an integer) of a row about to be deleted. Remove all terms from the +** full-text index. +*/ +static void fts3DeleteTerms( + int *pRC, /* Result code */ + Fts3Table *p, /* The FTS table to delete from */ + sqlite3_value *pRowid, /* The docid to be deleted */ + u32 *aSz, /* Sizes of deleted document written here */ + int *pbFound /* OUT: Set to true if row really does exist */ +){ + int rc; + sqlite3_stmt *pSelect; + + assert( *pbFound==0 ); + if( *pRC ) return; + rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid); + if( rc==SQLITE_OK ){ + if( SQLITE_ROW==sqlite3_step(pSelect) ){ + int i; + int iLangid = langidFromSelect(p, pSelect); + rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0)); + for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){ + int iCol = i-1; + if( p->abNotindexed[iCol]==0 ){ + const char *zText = (const char *)sqlite3_column_text(pSelect, i); + rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]); + aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i); + } + } + if( rc!=SQLITE_OK ){ + sqlite3_reset(pSelect); + *pRC = rc; + return; + } + *pbFound = 1; + } + rc = sqlite3_reset(pSelect); + }else{ + sqlite3_reset(pSelect); + } + *pRC = rc; +} + +/* +** Forward declaration to account for the circular dependency between +** functions fts3SegmentMerge() and fts3AllocateSegdirIdx(). +*/ +static int fts3SegmentMerge(Fts3Table *, int, int, int); + +/* +** This function allocates a new level iLevel index in the segdir table. +** Usually, indexes are allocated within a level sequentially starting +** with 0, so the allocated index is one greater than the value returned +** by: +** +** SELECT max(idx) FROM %_segdir WHERE level = :iLevel +** +** However, if there are already FTS3_MERGE_COUNT indexes at the requested +** level, they are merged into a single level (iLevel+1) segment and the +** allocated index is 0. +** +** If successful, *piIdx is set to the allocated index slot and SQLITE_OK +** returned. Otherwise, an SQLite error code is returned. +*/ +static int fts3AllocateSegdirIdx( + Fts3Table *p, + int iLangid, /* Language id */ + int iIndex, /* Index for p->aIndex */ + int iLevel, + int *piIdx +){ + int rc; /* Return Code */ + sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */ + int iNext = 0; /* Result of query pNextIdx */ + + assert( iLangid>=0 ); + assert( p->nIndex>=1 ); + + /* Set variable iNext to the next available segdir index at level iLevel. */ + rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64( + pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) + ); + if( SQLITE_ROW==sqlite3_step(pNextIdx) ){ + iNext = sqlite3_column_int(pNextIdx, 0); + } + rc = sqlite3_reset(pNextIdx); + } + + if( rc==SQLITE_OK ){ + /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already + ** full, merge all segments in level iLevel into a single iLevel+1 + ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise, + ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext. + */ + if( iNext>=FTS3_MERGE_COUNT ){ + fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel)); + rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel); + *piIdx = 0; + }else{ + *piIdx = iNext; + } + } + + return rc; +} + +/* +** The %_segments table is declared as follows: +** +** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB) +** +** This function reads data from a single row of the %_segments table. The +** specific row is identified by the iBlockid parameter. If paBlob is not +** NULL, then a buffer is allocated using sqlite3_malloc() and populated +** with the contents of the blob stored in the "block" column of the +** identified table row is. Whether or not paBlob is NULL, *pnBlob is set +** to the size of the blob in bytes before returning. +** +** If an error occurs, or the table does not contain the specified row, +** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If +** paBlob is non-NULL, then it is the responsibility of the caller to +** eventually free the returned buffer. +** +** This function may leave an open sqlite3_blob* handle in the +** Fts3Table.pSegments variable. This handle is reused by subsequent calls +** to this function. The handle may be closed by calling the +** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy +** performance improvement, but the blob handle should always be closed +** before control is returned to the user (to prevent a lock being held +** on the database file for longer than necessary). Thus, any virtual table +** method (xFilter etc.) that may directly or indirectly call this function +** must call sqlite3Fts3SegmentsClose() before returning. +*/ +int sqlite3Fts3ReadBlock( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */ + char **paBlob, /* OUT: Blob data in malloc'd buffer */ + int *pnBlob, /* OUT: Size of blob data */ + int *pnLoad /* OUT: Bytes actually loaded */ +){ + int rc; /* Return code */ + + /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */ + assert( pnBlob ); + + if( p->pSegments ){ + rc = sqlite3_blob_reopen(p->pSegments, iBlockid); + }else{ + if( 0==p->zSegmentsTbl ){ + p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName); + if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM; + } + rc = sqlite3_blob_open( + p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments + ); + } + + if( rc==SQLITE_OK ){ + int nByte = sqlite3_blob_bytes(p->pSegments); + *pnBlob = nByte; + if( paBlob ){ + char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING); + if( !aByte ){ + rc = SQLITE_NOMEM; + }else{ + if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){ + nByte = FTS3_NODE_CHUNKSIZE; + *pnLoad = nByte; + } + rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0); + memset(&aByte[nByte], 0, FTS3_NODE_PADDING); + if( rc!=SQLITE_OK ){ + sqlite3_free(aByte); + aByte = 0; + } + } + *paBlob = aByte; + } + } + + return rc; +} + +/* +** Close the blob handle at p->pSegments, if it is open. See comments above +** the sqlite3Fts3ReadBlock() function for details. +*/ +void sqlite3Fts3SegmentsClose(Fts3Table *p){ + sqlite3_blob_close(p->pSegments); + p->pSegments = 0; +} + +static int fts3SegReaderIncrRead(Fts3SegReader *pReader){ + int nRead; /* Number of bytes to read */ + int rc; /* Return code */ + + nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE); + rc = sqlite3_blob_read( + pReader->pBlob, + &pReader->aNode[pReader->nPopulate], + nRead, + pReader->nPopulate + ); + + if( rc==SQLITE_OK ){ + pReader->nPopulate += nRead; + memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING); + if( pReader->nPopulate==pReader->nNode ){ + sqlite3_blob_close(pReader->pBlob); + pReader->pBlob = 0; + pReader->nPopulate = 0; + } + } + return rc; +} + +static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){ + int rc = SQLITE_OK; + assert( !pReader->pBlob + || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode]) + ); + while( pReader->pBlob && rc==SQLITE_OK + && (pFrom - pReader->aNode + nByte)>pReader->nPopulate + ){ + rc = fts3SegReaderIncrRead(pReader); + } + return rc; +} + +/* +** Set an Fts3SegReader cursor to point at EOF. +*/ +static void fts3SegReaderSetEof(Fts3SegReader *pSeg){ + if( !fts3SegReaderIsRootOnly(pSeg) ){ + sqlite3_free(pSeg->aNode); + sqlite3_blob_close(pSeg->pBlob); + pSeg->pBlob = 0; + } + pSeg->aNode = 0; +} + +/* +** Move the iterator passed as the first argument to the next term in the +** segment. If successful, SQLITE_OK is returned. If there is no next term, +** SQLITE_DONE. Otherwise, an SQLite error code. +*/ +static int fts3SegReaderNext( + Fts3Table *p, + Fts3SegReader *pReader, + int bIncr +){ + int rc; /* Return code of various sub-routines */ + char *pNext; /* Cursor variable */ + int nPrefix; /* Number of bytes in term prefix */ + int nSuffix; /* Number of bytes in term suffix */ + + if( !pReader->aDoclist ){ + pNext = pReader->aNode; + }else{ + pNext = &pReader->aDoclist[pReader->nDoclist]; + } + + if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){ + + if( fts3SegReaderIsPending(pReader) ){ + Fts3HashElem *pElem = *(pReader->ppNextElem); + if( pElem==0 ){ + pReader->aNode = 0; + }else{ + PendingList *pList = (PendingList *)fts3HashData(pElem); + pReader->zTerm = (char *)fts3HashKey(pElem); + pReader->nTerm = fts3HashKeysize(pElem); + pReader->nNode = pReader->nDoclist = pList->nData + 1; + pReader->aNode = pReader->aDoclist = pList->aData; + pReader->ppNextElem++; + assert( pReader->aNode ); + } + return SQLITE_OK; + } + + fts3SegReaderSetEof(pReader); + + /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf + ** blocks have already been traversed. */ + assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock ); + if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){ + return SQLITE_OK; + } + + rc = sqlite3Fts3ReadBlock( + p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, + (bIncr ? &pReader->nPopulate : 0) + ); + if( rc!=SQLITE_OK ) return rc; + assert( pReader->pBlob==0 ); + if( bIncr && pReader->nPopulatenNode ){ + pReader->pBlob = p->pSegments; + p->pSegments = 0; + } + pNext = pReader->aNode; + } + + assert( !fts3SegReaderIsPending(pReader) ); + + rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2); + if( rc!=SQLITE_OK ) return rc; + + /* Because of the FTS3_NODE_PADDING bytes of padding, the following is + ** safe (no risk of overread) even if the node data is corrupted. */ + pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix); + pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix); + if( nPrefix<0 || nSuffix<=0 + || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] + ){ + return FTS_CORRUPT_VTAB; + } + + if( nPrefix+nSuffix>pReader->nTermAlloc ){ + int nNew = (nPrefix+nSuffix)*2; + char *zNew = sqlite3_realloc(pReader->zTerm, nNew); + if( !zNew ){ + return SQLITE_NOMEM; + } + pReader->zTerm = zNew; + pReader->nTermAlloc = nNew; + } + + rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX); + if( rc!=SQLITE_OK ) return rc; + + memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix); + pReader->nTerm = nPrefix+nSuffix; + pNext += nSuffix; + pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist); + pReader->aDoclist = pNext; + pReader->pOffsetList = 0; + + /* Check that the doclist does not appear to extend past the end of the + ** b-tree node. And that the final byte of the doclist is 0x00. If either + ** of these statements is untrue, then the data structure is corrupt. + */ + if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] + || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1]) + ){ + return FTS_CORRUPT_VTAB; + } + return SQLITE_OK; +} + +/* +** Set the SegReader to point to the first docid in the doclist associated +** with the current term. +*/ +static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){ + int rc = SQLITE_OK; + assert( pReader->aDoclist ); + assert( !pReader->pOffsetList ); + if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ + u8 bEof = 0; + pReader->iDocid = 0; + pReader->nOffsetList = 0; + sqlite3Fts3DoclistPrev(0, + pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, + &pReader->iDocid, &pReader->nOffsetList, &bEof + ); + }else{ + rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX); + if( rc==SQLITE_OK ){ + int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid); + pReader->pOffsetList = &pReader->aDoclist[n]; + } + } + return rc; +} + +/* +** Advance the SegReader to point to the next docid in the doclist +** associated with the current term. +** +** If arguments ppOffsetList and pnOffsetList are not NULL, then +** *ppOffsetList is set to point to the first column-offset list +** in the doclist entry (i.e. immediately past the docid varint). +** *pnOffsetList is set to the length of the set of column-offset +** lists, not including the nul-terminator byte. For example: +*/ +static int fts3SegReaderNextDocid( + Fts3Table *pTab, + Fts3SegReader *pReader, /* Reader to advance to next docid */ + char **ppOffsetList, /* OUT: Pointer to current position-list */ + int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */ +){ + int rc = SQLITE_OK; + char *p = pReader->pOffsetList; + char c = 0; + + assert( p ); + + if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ + /* A pending-terms seg-reader for an FTS4 table that uses order=desc. + ** Pending-terms doclists are always built up in ascending order, so + ** we have to iterate through them backwards here. */ + u8 bEof = 0; + if( ppOffsetList ){ + *ppOffsetList = pReader->pOffsetList; + *pnOffsetList = pReader->nOffsetList - 1; + } + sqlite3Fts3DoclistPrev(0, + pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid, + &pReader->nOffsetList, &bEof + ); + if( bEof ){ + pReader->pOffsetList = 0; + }else{ + pReader->pOffsetList = p; + } + }else{ + char *pEnd = &pReader->aDoclist[pReader->nDoclist]; + + /* Pointer p currently points at the first byte of an offset list. The + ** following block advances it to point one byte past the end of + ** the same offset list. */ + while( 1 ){ + + /* The following line of code (and the "p++" below the while() loop) is + ** normally all that is required to move pointer p to the desired + ** position. The exception is if this node is being loaded from disk + ** incrementally and pointer "p" now points to the first byte past + ** the populated part of pReader->aNode[]. + */ + while( *p | c ) c = *p++ & 0x80; + assert( *p==0 ); + + if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break; + rc = fts3SegReaderIncrRead(pReader); + if( rc!=SQLITE_OK ) return rc; + } + p++; + + /* If required, populate the output variables with a pointer to and the + ** size of the previous offset-list. + */ + if( ppOffsetList ){ + *ppOffsetList = pReader->pOffsetList; + *pnOffsetList = (int)(p - pReader->pOffsetList - 1); + } + + /* List may have been edited in place by fts3EvalNearTrim() */ + while( p=pEnd ){ + pReader->pOffsetList = 0; + }else{ + rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX); + if( rc==SQLITE_OK ){ + sqlite3_int64 iDelta; + pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta); + if( pTab->bDescIdx ){ + pReader->iDocid -= iDelta; + }else{ + pReader->iDocid += iDelta; + } + } + } + } + + return SQLITE_OK; +} + + +int sqlite3Fts3MsrOvfl( + Fts3Cursor *pCsr, + Fts3MultiSegReader *pMsr, + int *pnOvfl +){ + Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; + int nOvfl = 0; + int ii; + int rc = SQLITE_OK; + int pgsz = p->nPgsz; + + assert( p->bFts4 ); + assert( pgsz>0 ); + + for(ii=0; rc==SQLITE_OK && iinSegment; ii++){ + Fts3SegReader *pReader = pMsr->apSegment[ii]; + if( !fts3SegReaderIsPending(pReader) + && !fts3SegReaderIsRootOnly(pReader) + ){ + sqlite3_int64 jj; + for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){ + int nBlob; + rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0); + if( rc!=SQLITE_OK ) break; + if( (nBlob+35)>pgsz ){ + nOvfl += (nBlob + 34)/pgsz; + } + } + } + } + *pnOvfl = nOvfl; + return rc; +} + +/* +** Free all allocations associated with the iterator passed as the +** second argument. +*/ +void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){ + if( pReader && !fts3SegReaderIsPending(pReader) ){ + sqlite3_free(pReader->zTerm); + if( !fts3SegReaderIsRootOnly(pReader) ){ + sqlite3_free(pReader->aNode); + sqlite3_blob_close(pReader->pBlob); + } + } + sqlite3_free(pReader); +} + +/* +** Allocate a new SegReader object. +*/ +int sqlite3Fts3SegReaderNew( + int iAge, /* Segment "age". */ + int bLookup, /* True for a lookup only */ + sqlite3_int64 iStartLeaf, /* First leaf to traverse */ + sqlite3_int64 iEndLeaf, /* Final leaf to traverse */ + sqlite3_int64 iEndBlock, /* Final block of segment */ + const char *zRoot, /* Buffer containing root node */ + int nRoot, /* Size of buffer containing root node */ + Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */ +){ + Fts3SegReader *pReader; /* Newly allocated SegReader object */ + int nExtra = 0; /* Bytes to allocate segment root node */ + + assert( iStartLeaf<=iEndLeaf ); + if( iStartLeaf==0 ){ + nExtra = nRoot + FTS3_NODE_PADDING; + } + + pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra); + if( !pReader ){ + return SQLITE_NOMEM; + } + memset(pReader, 0, sizeof(Fts3SegReader)); + pReader->iIdx = iAge; + pReader->bLookup = bLookup!=0; + pReader->iStartBlock = iStartLeaf; + pReader->iLeafEndBlock = iEndLeaf; + pReader->iEndBlock = iEndBlock; + + if( nExtra ){ + /* The entire segment is stored in the root node. */ + pReader->aNode = (char *)&pReader[1]; + pReader->rootOnly = 1; + pReader->nNode = nRoot; + memcpy(pReader->aNode, zRoot, nRoot); + memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING); + }else{ + pReader->iCurrentBlock = iStartLeaf-1; + } + *ppReader = pReader; + return SQLITE_OK; +} + +/* +** This is a comparison function used as a qsort() callback when sorting +** an array of pending terms by term. This occurs as part of flushing +** the contents of the pending-terms hash table to the database. +*/ +static int fts3CompareElemByTerm(const void *lhs, const void *rhs){ + char *z1 = fts3HashKey(*(Fts3HashElem **)lhs); + char *z2 = fts3HashKey(*(Fts3HashElem **)rhs); + int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs); + int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs); + + int n = (n1aIndex */ + const char *zTerm, /* Term to search for */ + int nTerm, /* Size of buffer zTerm */ + int bPrefix, /* True for a prefix iterator */ + Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */ +){ + Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */ + Fts3HashElem *pE; /* Iterator variable */ + Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */ + int nElem = 0; /* Size of array at aElem */ + int rc = SQLITE_OK; /* Return Code */ + Fts3Hash *pHash; + + pHash = &p->aIndex[iIndex].hPending; + if( bPrefix ){ + int nAlloc = 0; /* Size of allocated array at aElem */ + + for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){ + char *zKey = (char *)fts3HashKey(pE); + int nKey = fts3HashKeysize(pE); + if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){ + if( nElem==nAlloc ){ + Fts3HashElem **aElem2; + nAlloc += 16; + aElem2 = (Fts3HashElem **)sqlite3_realloc( + aElem, nAlloc*sizeof(Fts3HashElem *) + ); + if( !aElem2 ){ + rc = SQLITE_NOMEM; + nElem = 0; + break; + } + aElem = aElem2; + } + + aElem[nElem++] = pE; + } + } + + /* If more than one term matches the prefix, sort the Fts3HashElem + ** objects in term order using qsort(). This uses the same comparison + ** callback as is used when flushing terms to disk. + */ + if( nElem>1 ){ + qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm); + } + + }else{ + /* The query is a simple term lookup that matches at most one term in + ** the index. All that is required is a straight hash-lookup. + ** + ** Because the stack address of pE may be accessed via the aElem pointer + ** below, the "Fts3HashElem *pE" must be declared so that it is valid + ** within this entire function, not just this "else{...}" block. + */ + pE = fts3HashFindElem(pHash, zTerm, nTerm); + if( pE ){ + aElem = &pE; + nElem = 1; + } + } + + if( nElem>0 ){ + int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); + pReader = (Fts3SegReader *)sqlite3_malloc(nByte); + if( !pReader ){ + rc = SQLITE_NOMEM; + }else{ + memset(pReader, 0, nByte); + pReader->iIdx = 0x7FFFFFFF; + pReader->ppNextElem = (Fts3HashElem **)&pReader[1]; + memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *)); + } + } + + if( bPrefix ){ + sqlite3_free(aElem); + } + *ppReader = pReader; + return rc; +} + +/* +** Compare the entries pointed to by two Fts3SegReader structures. +** Comparison is as follows: +** +** 1) EOF is greater than not EOF. +** +** 2) The current terms (if any) are compared using memcmp(). If one +** term is a prefix of another, the longer term is considered the +** larger. +** +** 3) By segment age. An older segment is considered larger. +*/ +static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ + int rc; + if( pLhs->aNode && pRhs->aNode ){ + int rc2 = pLhs->nTerm - pRhs->nTerm; + if( rc2<0 ){ + rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm); + }else{ + rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm); + } + if( rc==0 ){ + rc = rc2; + } + }else{ + rc = (pLhs->aNode==0) - (pRhs->aNode==0); + } + if( rc==0 ){ + rc = pRhs->iIdx - pLhs->iIdx; + } + assert( rc!=0 ); + return rc; +} + +/* +** A different comparison function for SegReader structures. In this +** version, it is assumed that each SegReader points to an entry in +** a doclist for identical terms. Comparison is made as follows: +** +** 1) EOF (end of doclist in this case) is greater than not EOF. +** +** 2) By current docid. +** +** 3) By segment age. An older segment is considered larger. +*/ +static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ + int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); + if( rc==0 ){ + if( pLhs->iDocid==pRhs->iDocid ){ + rc = pRhs->iIdx - pLhs->iIdx; + }else{ + rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1; + } + } + assert( pLhs->aNode && pRhs->aNode ); + return rc; +} +static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ + int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); + if( rc==0 ){ + if( pLhs->iDocid==pRhs->iDocid ){ + rc = pRhs->iIdx - pLhs->iIdx; + }else{ + rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1; + } + } + assert( pLhs->aNode && pRhs->aNode ); + return rc; +} + +/* +** Compare the term that the Fts3SegReader object passed as the first argument +** points to with the term specified by arguments zTerm and nTerm. +** +** If the pSeg iterator is already at EOF, return 0. Otherwise, return +** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are +** equal, or +ve if the pSeg term is greater than zTerm/nTerm. +*/ +static int fts3SegReaderTermCmp( + Fts3SegReader *pSeg, /* Segment reader object */ + const char *zTerm, /* Term to compare to */ + int nTerm /* Size of term zTerm in bytes */ +){ + int res = 0; + if( pSeg->aNode ){ + if( pSeg->nTerm>nTerm ){ + res = memcmp(pSeg->zTerm, zTerm, nTerm); + }else{ + res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm); + } + if( res==0 ){ + res = pSeg->nTerm-nTerm; + } + } + return res; +} + +/* +** Argument apSegment is an array of nSegment elements. It is known that +** the final (nSegment-nSuspect) members are already in sorted order +** (according to the comparison function provided). This function shuffles +** the array around until all entries are in sorted order. +*/ +static void fts3SegReaderSort( + Fts3SegReader **apSegment, /* Array to sort entries of */ + int nSegment, /* Size of apSegment array */ + int nSuspect, /* Unsorted entry count */ + int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */ +){ + int i; /* Iterator variable */ + + assert( nSuspect<=nSegment ); + + if( nSuspect==nSegment ) nSuspect--; + for(i=nSuspect-1; i>=0; i--){ + int j; + for(j=i; j<(nSegment-1); j++){ + Fts3SegReader *pTmp; + if( xCmp(apSegment[j], apSegment[j+1])<0 ) break; + pTmp = apSegment[j+1]; + apSegment[j+1] = apSegment[j]; + apSegment[j] = pTmp; + } + } + +#ifndef NDEBUG + /* Check that the list really is sorted now. */ + for(i=0; i<(nSuspect-1); i++){ + assert( xCmp(apSegment[i], apSegment[i+1])<0 ); + } +#endif +} + +/* +** Insert a record into the %_segments table. +*/ +static int fts3WriteSegment( + Fts3Table *p, /* Virtual table handle */ + sqlite3_int64 iBlock, /* Block id for new block */ + char *z, /* Pointer to buffer containing block data */ + int n /* Size of buffer z in bytes */ +){ + sqlite3_stmt *pStmt; + int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pStmt, 1, iBlock); + sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC); + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + } + return rc; +} + +/* +** Find the largest relative level number in the table. If successful, set +** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs, +** set *pnMax to zero and return an SQLite error code. +*/ +int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){ + int rc; + int mxLevel = 0; + sqlite3_stmt *pStmt = 0; + + rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0); + if( rc==SQLITE_OK ){ + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + mxLevel = sqlite3_column_int(pStmt, 0); + } + rc = sqlite3_reset(pStmt); + } + *pnMax = mxLevel; + return rc; +} + +/* +** Insert a record into the %_segdir table. +*/ +static int fts3WriteSegdir( + Fts3Table *p, /* Virtual table handle */ + sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */ + int iIdx, /* Value for "idx" field */ + sqlite3_int64 iStartBlock, /* Value for "start_block" field */ + sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */ + sqlite3_int64 iEndBlock, /* Value for "end_block" field */ + char *zRoot, /* Blob value for "root" field */ + int nRoot /* Number of bytes in buffer zRoot */ +){ + sqlite3_stmt *pStmt; + int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pStmt, 1, iLevel); + sqlite3_bind_int(pStmt, 2, iIdx); + sqlite3_bind_int64(pStmt, 3, iStartBlock); + sqlite3_bind_int64(pStmt, 4, iLeafEndBlock); + sqlite3_bind_int64(pStmt, 5, iEndBlock); + sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC); + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + } + return rc; +} + +/* +** Return the size of the common prefix (if any) shared by zPrev and +** zNext, in bytes. For example, +** +** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3 +** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2 +** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0 +*/ +static int fts3PrefixCompress( + const char *zPrev, /* Buffer containing previous term */ + int nPrev, /* Size of buffer zPrev in bytes */ + const char *zNext, /* Buffer containing next term */ + int nNext /* Size of buffer zNext in bytes */ +){ + int n; + UNUSED_PARAMETER(nNext); + for(n=0; nnData; /* Current size of node in bytes */ + int nReq = nData; /* Required space after adding zTerm */ + int nPrefix; /* Number of bytes of prefix compression */ + int nSuffix; /* Suffix length */ + + nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm); + nSuffix = nTerm-nPrefix; + + nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix; + if( nReq<=p->nNodeSize || !pTree->zTerm ){ + + if( nReq>p->nNodeSize ){ + /* An unusual case: this is the first term to be added to the node + ** and the static node buffer (p->nNodeSize bytes) is not large + ** enough. Use a separately malloced buffer instead This wastes + ** p->nNodeSize bytes, but since this scenario only comes about when + ** the database contain two terms that share a prefix of almost 2KB, + ** this is not expected to be a serious problem. + */ + assert( pTree->aData==(char *)&pTree[1] ); + pTree->aData = (char *)sqlite3_malloc(nReq); + if( !pTree->aData ){ + return SQLITE_NOMEM; + } + } + + if( pTree->zTerm ){ + /* There is no prefix-length field for first term in a node */ + nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix); + } + + nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix); + memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix); + pTree->nData = nData + nSuffix; + pTree->nEntry++; + + if( isCopyTerm ){ + if( pTree->nMalloczMalloc, nTerm*2); + if( !zNew ){ + return SQLITE_NOMEM; + } + pTree->nMalloc = nTerm*2; + pTree->zMalloc = zNew; + } + pTree->zTerm = pTree->zMalloc; + memcpy(pTree->zTerm, zTerm, nTerm); + pTree->nTerm = nTerm; + }else{ + pTree->zTerm = (char *)zTerm; + pTree->nTerm = nTerm; + } + return SQLITE_OK; + } + } + + /* If control flows to here, it was not possible to append zTerm to the + ** current node. Create a new node (a right-sibling of the current node). + ** If this is the first node in the tree, the term is added to it. + ** + ** Otherwise, the term is not added to the new node, it is left empty for + ** now. Instead, the term is inserted into the parent of pTree. If pTree + ** has no parent, one is created here. + */ + pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize); + if( !pNew ){ + return SQLITE_NOMEM; + } + memset(pNew, 0, sizeof(SegmentNode)); + pNew->nData = 1 + FTS3_VARINT_MAX; + pNew->aData = (char *)&pNew[1]; + + if( pTree ){ + SegmentNode *pParent = pTree->pParent; + rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm); + if( pTree->pParent==0 ){ + pTree->pParent = pParent; + } + pTree->pRight = pNew; + pNew->pLeftmost = pTree->pLeftmost; + pNew->pParent = pParent; + pNew->zMalloc = pTree->zMalloc; + pNew->nMalloc = pTree->nMalloc; + pTree->zMalloc = 0; + }else{ + pNew->pLeftmost = pNew; + rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); + } + + *ppTree = pNew; + return rc; +} + +/* +** Helper function for fts3NodeWrite(). +*/ +static int fts3TreeFinishNode( + SegmentNode *pTree, + int iHeight, + sqlite3_int64 iLeftChild +){ + int nStart; + assert( iHeight>=1 && iHeight<128 ); + nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild); + pTree->aData[nStart] = (char)iHeight; + sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild); + return nStart; +} + +/* +** Write the buffer for the segment node pTree and all of its peers to the +** database. Then call this function recursively to write the parent of +** pTree and its peers to the database. +** +** Except, if pTree is a root node, do not write it to the database. Instead, +** set output variables *paRoot and *pnRoot to contain the root node. +** +** If successful, SQLITE_OK is returned and output variable *piLast is +** set to the largest blockid written to the database (or zero if no +** blocks were written to the db). Otherwise, an SQLite error code is +** returned. +*/ +static int fts3NodeWrite( + Fts3Table *p, /* Virtual table handle */ + SegmentNode *pTree, /* SegmentNode handle */ + int iHeight, /* Height of this node in tree */ + sqlite3_int64 iLeaf, /* Block id of first leaf node */ + sqlite3_int64 iFree, /* Block id of next free slot in %_segments */ + sqlite3_int64 *piLast, /* OUT: Block id of last entry written */ + char **paRoot, /* OUT: Data for root node */ + int *pnRoot /* OUT: Size of root node in bytes */ +){ + int rc = SQLITE_OK; + + if( !pTree->pParent ){ + /* Root node of the tree. */ + int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf); + *piLast = iFree-1; + *pnRoot = pTree->nData - nStart; + *paRoot = &pTree->aData[nStart]; + }else{ + SegmentNode *pIter; + sqlite3_int64 iNextFree = iFree; + sqlite3_int64 iNextLeaf = iLeaf; + for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){ + int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf); + int nWrite = pIter->nData - nStart; + + rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite); + iNextFree++; + iNextLeaf += (pIter->nEntry+1); + } + if( rc==SQLITE_OK ){ + assert( iNextLeaf==iFree ); + rc = fts3NodeWrite( + p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot + ); + } + } + + return rc; +} + +/* +** Free all memory allocations associated with the tree pTree. +*/ +static void fts3NodeFree(SegmentNode *pTree){ + if( pTree ){ + SegmentNode *p = pTree->pLeftmost; + fts3NodeFree(p->pParent); + while( p ){ + SegmentNode *pRight = p->pRight; + if( p->aData!=(char *)&p[1] ){ + sqlite3_free(p->aData); + } + assert( pRight==0 || p->zMalloc==0 ); + sqlite3_free(p->zMalloc); + sqlite3_free(p); + p = pRight; + } + } +} + +/* +** Add a term to the segment being constructed by the SegmentWriter object +** *ppWriter. When adding the first term to a segment, *ppWriter should +** be passed NULL. This function will allocate a new SegmentWriter object +** and return it via the input/output variable *ppWriter in this case. +** +** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. +*/ +static int fts3SegWriterAdd( + Fts3Table *p, /* Virtual table handle */ + SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */ + int isCopyTerm, /* True if buffer zTerm must be copied */ + const char *zTerm, /* Pointer to buffer containing term */ + int nTerm, /* Size of term in bytes */ + const char *aDoclist, /* Pointer to buffer containing doclist */ + int nDoclist /* Size of doclist in bytes */ +){ + int nPrefix; /* Size of term prefix in bytes */ + int nSuffix; /* Size of term suffix in bytes */ + int nReq; /* Number of bytes required on leaf page */ + int nData; + SegmentWriter *pWriter = *ppWriter; + + if( !pWriter ){ + int rc; + sqlite3_stmt *pStmt; + + /* Allocate the SegmentWriter structure */ + pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter)); + if( !pWriter ) return SQLITE_NOMEM; + memset(pWriter, 0, sizeof(SegmentWriter)); + *ppWriter = pWriter; + + /* Allocate a buffer in which to accumulate data */ + pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize); + if( !pWriter->aData ) return SQLITE_NOMEM; + pWriter->nSize = p->nNodeSize; + + /* Find the next free blockid in the %_segments table */ + rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + pWriter->iFree = sqlite3_column_int64(pStmt, 0); + pWriter->iFirst = pWriter->iFree; + } + rc = sqlite3_reset(pStmt); + if( rc!=SQLITE_OK ) return rc; + } + nData = pWriter->nData; + + nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm); + nSuffix = nTerm-nPrefix; + + /* Figure out how many bytes are required by this new entry */ + nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */ + sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */ + nSuffix + /* Term suffix */ + sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ + nDoclist; /* Doclist data */ + + if( nData>0 && nData+nReq>p->nNodeSize ){ + int rc; + + /* The current leaf node is full. Write it out to the database. */ + rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData); + if( rc!=SQLITE_OK ) return rc; + p->nLeafAdd++; + + /* Add the current term to the interior node tree. The term added to + ** the interior tree must: + ** + ** a) be greater than the largest term on the leaf node just written + ** to the database (still available in pWriter->zTerm), and + ** + ** b) be less than or equal to the term about to be added to the new + ** leaf node (zTerm/nTerm). + ** + ** In other words, it must be the prefix of zTerm 1 byte longer than + ** the common prefix (if any) of zTerm and pWriter->zTerm. + */ + assert( nPrefixpTree, isCopyTerm, zTerm, nPrefix+1); + if( rc!=SQLITE_OK ) return rc; + + nData = 0; + pWriter->nTerm = 0; + + nPrefix = 0; + nSuffix = nTerm; + nReq = 1 + /* varint containing prefix size */ + sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */ + nTerm + /* Term suffix */ + sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ + nDoclist; /* Doclist data */ + } + + /* If the buffer currently allocated is too small for this entry, realloc + ** the buffer to make it large enough. + */ + if( nReq>pWriter->nSize ){ + char *aNew = sqlite3_realloc(pWriter->aData, nReq); + if( !aNew ) return SQLITE_NOMEM; + pWriter->aData = aNew; + pWriter->nSize = nReq; + } + assert( nData+nReq<=pWriter->nSize ); + + /* Append the prefix-compressed term and doclist to the buffer. */ + nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix); + nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix); + memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); + nData += nSuffix; + nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); + memcpy(&pWriter->aData[nData], aDoclist, nDoclist); + pWriter->nData = nData + nDoclist; + + /* Save the current term so that it can be used to prefix-compress the next. + ** If the isCopyTerm parameter is true, then the buffer pointed to by + ** zTerm is transient, so take a copy of the term data. Otherwise, just + ** store a copy of the pointer. + */ + if( isCopyTerm ){ + if( nTerm>pWriter->nMalloc ){ + char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2); + if( !zNew ){ + return SQLITE_NOMEM; + } + pWriter->nMalloc = nTerm*2; + pWriter->zMalloc = zNew; + pWriter->zTerm = zNew; + } + assert( pWriter->zTerm==pWriter->zMalloc ); + memcpy(pWriter->zTerm, zTerm, nTerm); + }else{ + pWriter->zTerm = (char *)zTerm; + } + pWriter->nTerm = nTerm; + + return SQLITE_OK; +} + +/* +** Flush all data associated with the SegmentWriter object pWriter to the +** database. This function must be called after all terms have been added +** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is +** returned. Otherwise, an SQLite error code. +*/ +static int fts3SegWriterFlush( + Fts3Table *p, /* Virtual table handle */ + SegmentWriter *pWriter, /* SegmentWriter to flush to the db */ + sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */ + int iIdx /* Value for 'idx' column of %_segdir */ +){ + int rc; /* Return code */ + if( pWriter->pTree ){ + sqlite3_int64 iLast = 0; /* Largest block id written to database */ + sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */ + char *zRoot = NULL; /* Pointer to buffer containing root node */ + int nRoot = 0; /* Size of buffer zRoot */ + + iLastLeaf = pWriter->iFree; + rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData); + if( rc==SQLITE_OK ){ + rc = fts3NodeWrite(p, pWriter->pTree, 1, + pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot); + } + if( rc==SQLITE_OK ){ + rc = fts3WriteSegdir( + p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot); + } + }else{ + /* The entire tree fits on the root node. Write it to the segdir table. */ + rc = fts3WriteSegdir( + p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData); + } + p->nLeafAdd++; + return rc; +} + +/* +** Release all memory held by the SegmentWriter object passed as the +** first argument. +*/ +static void fts3SegWriterFree(SegmentWriter *pWriter){ + if( pWriter ){ + sqlite3_free(pWriter->aData); + sqlite3_free(pWriter->zMalloc); + fts3NodeFree(pWriter->pTree); + sqlite3_free(pWriter); + } +} + +/* +** The first value in the apVal[] array is assumed to contain an integer. +** This function tests if there exist any documents with docid values that +** are different from that integer. i.e. if deleting the document with docid +** pRowid would mean the FTS3 table were empty. +** +** If successful, *pisEmpty is set to true if the table is empty except for +** document pRowid, or false otherwise, and SQLITE_OK is returned. If an +** error occurs, an SQLite error code is returned. +*/ +static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){ + sqlite3_stmt *pStmt; + int rc; + if( p->zContentTbl ){ + /* If using the content=xxx option, assume the table is never empty */ + *pisEmpty = 0; + rc = SQLITE_OK; + }else{ + rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid); + if( rc==SQLITE_OK ){ + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + *pisEmpty = sqlite3_column_int(pStmt, 0); + } + rc = sqlite3_reset(pStmt); + } + } + return rc; +} + +/* +** Set *pnMax to the largest segment level in the database for the index +** iIndex. +** +** Segment levels are stored in the 'level' column of the %_segdir table. +** +** Return SQLITE_OK if successful, or an SQLite error code if not. +*/ +static int fts3SegmentMaxLevel( + Fts3Table *p, + int iLangid, + int iIndex, + sqlite3_int64 *pnMax +){ + sqlite3_stmt *pStmt; + int rc; + assert( iIndex>=0 && iIndexnIndex ); + + /* Set pStmt to the compiled version of: + ** + ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? + ** + ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR). + */ + rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); + sqlite3_bind_int64(pStmt, 2, + getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) + ); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + *pnMax = sqlite3_column_int64(pStmt, 0); + } + return sqlite3_reset(pStmt); +} + +/* +** Delete all entries in the %_segments table associated with the segment +** opened with seg-reader pSeg. This function does not affect the contents +** of the %_segdir table. +*/ +static int fts3DeleteSegment( + Fts3Table *p, /* FTS table handle */ + Fts3SegReader *pSeg /* Segment to delete */ +){ + int rc = SQLITE_OK; /* Return code */ + if( pSeg->iStartBlock ){ + sqlite3_stmt *pDelete; /* SQL statement to delete rows */ + rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock); + sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock); + sqlite3_step(pDelete); + rc = sqlite3_reset(pDelete); + } + } + return rc; +} + +/* +** This function is used after merging multiple segments into a single large +** segment to delete the old, now redundant, segment b-trees. Specifically, +** it: +** +** 1) Deletes all %_segments entries for the segments associated with +** each of the SegReader objects in the array passed as the third +** argument, and +** +** 2) deletes all %_segdir entries with level iLevel, or all %_segdir +** entries regardless of level if (iLevel<0). +** +** SQLITE_OK is returned if successful, otherwise an SQLite error code. +*/ +static int fts3DeleteSegdir( + Fts3Table *p, /* Virtual table handle */ + int iLangid, /* Language id */ + int iIndex, /* Index for p->aIndex */ + int iLevel, /* Level of %_segdir entries to delete */ + Fts3SegReader **apSegment, /* Array of SegReader objects */ + int nReader /* Size of array apSegment */ +){ + int rc = SQLITE_OK; /* Return Code */ + int i; /* Iterator variable */ + sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */ + + for(i=0; rc==SQLITE_OK && i=0 || iLevel==FTS3_SEGCURSOR_ALL ); + if( iLevel==FTS3_SEGCURSOR_ALL ){ + rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); + sqlite3_bind_int64(pDelete, 2, + getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) + ); + } + }else{ + rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64( + pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) + ); + } + } + + if( rc==SQLITE_OK ){ + sqlite3_step(pDelete); + rc = sqlite3_reset(pDelete); + } + + return rc; +} + +/* +** When this function is called, buffer *ppList (size *pnList bytes) contains +** a position list that may (or may not) feature multiple columns. This +** function adjusts the pointer *ppList and the length *pnList so that they +** identify the subset of the position list that corresponds to column iCol. +** +** If there are no entries in the input position list for column iCol, then +** *pnList is set to zero before returning. +** +** If parameter bZero is non-zero, then any part of the input list following +** the end of the output list is zeroed before returning. +*/ +static void fts3ColumnFilter( + int iCol, /* Column to filter on */ + int bZero, /* Zero out anything following *ppList */ + char **ppList, /* IN/OUT: Pointer to position list */ + int *pnList /* IN/OUT: Size of buffer *ppList in bytes */ +){ + char *pList = *ppList; + int nList = *pnList; + char *pEnd = &pList[nList]; + int iCurrent = 0; + char *p = pList; + + assert( iCol>=0 ); + while( 1 ){ + char c = 0; + while( ppMsr->nBuffer ){ + char *pNew; + pMsr->nBuffer = nList*2; + pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer); + if( !pNew ) return SQLITE_NOMEM; + pMsr->aBuffer = pNew; + } + + memcpy(pMsr->aBuffer, pList, nList); + return SQLITE_OK; +} + +int sqlite3Fts3MsrIncrNext( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */ + sqlite3_int64 *piDocid, /* OUT: Docid value */ + char **paPoslist, /* OUT: Pointer to position list */ + int *pnPoslist /* OUT: Size of position list in bytes */ +){ + int nMerge = pMsr->nAdvance; + Fts3SegReader **apSegment = pMsr->apSegment; + int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( + p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp + ); + + if( nMerge==0 ){ + *paPoslist = 0; + return SQLITE_OK; + } + + while( 1 ){ + Fts3SegReader *pSeg; + pSeg = pMsr->apSegment[0]; + + if( pSeg->pOffsetList==0 ){ + *paPoslist = 0; + break; + }else{ + int rc; + char *pList; + int nList; + int j; + sqlite3_int64 iDocid = apSegment[0]->iDocid; + + rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); + j = 1; + while( rc==SQLITE_OK + && jpOffsetList + && apSegment[j]->iDocid==iDocid + ){ + rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0); + j++; + } + if( rc!=SQLITE_OK ) return rc; + fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp); + + if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){ + rc = fts3MsrBufferData(pMsr, pList, nList+1); + if( rc!=SQLITE_OK ) return rc; + assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 ); + pList = pMsr->aBuffer; + } + + if( pMsr->iColFilter>=0 ){ + fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList); + } + + if( nList>0 ){ + *paPoslist = pList; + *piDocid = iDocid; + *pnPoslist = nList; + break; + } + } + } + + return SQLITE_OK; +} + +static int fts3SegReaderStart( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pCsr, /* Cursor object */ + const char *zTerm, /* Term searched for (or NULL) */ + int nTerm /* Length of zTerm in bytes */ +){ + int i; + int nSeg = pCsr->nSegment; + + /* If the Fts3SegFilter defines a specific term (or term prefix) to search + ** for, then advance each segment iterator until it points to a term of + ** equal or greater value than the specified term. This prevents many + ** unnecessary merge/sort operations for the case where single segment + ** b-tree leaf nodes contain more than one term. + */ + for(i=0; pCsr->bRestart==0 && inSegment; i++){ + int res = 0; + Fts3SegReader *pSeg = pCsr->apSegment[i]; + do { + int rc = fts3SegReaderNext(p, pSeg, 0); + if( rc!=SQLITE_OK ) return rc; + }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 ); + + if( pSeg->bLookup && res!=0 ){ + fts3SegReaderSetEof(pSeg); + } + } + fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp); + + return SQLITE_OK; +} + +int sqlite3Fts3SegReaderStart( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pCsr, /* Cursor object */ + Fts3SegFilter *pFilter /* Restrictions on range of iteration */ +){ + pCsr->pFilter = pFilter; + return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm); +} + +int sqlite3Fts3MsrIncrStart( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pCsr, /* Cursor object */ + int iCol, /* Column to match on. */ + const char *zTerm, /* Term to iterate through a doclist for */ + int nTerm /* Number of bytes in zTerm */ +){ + int i; + int rc; + int nSegment = pCsr->nSegment; + int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( + p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp + ); + + assert( pCsr->pFilter==0 ); + assert( zTerm && nTerm>0 ); + + /* Advance each segment iterator until it points to the term zTerm/nTerm. */ + rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm); + if( rc!=SQLITE_OK ) return rc; + + /* Determine how many of the segments actually point to zTerm/nTerm. */ + for(i=0; iapSegment[i]; + if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){ + break; + } + } + pCsr->nAdvance = i; + + /* Advance each of the segments to point to the first docid. */ + for(i=0; inAdvance; i++){ + rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]); + if( rc!=SQLITE_OK ) return rc; + } + fts3SegReaderSort(pCsr->apSegment, i, i, xCmp); + + assert( iCol<0 || iColnColumn ); + pCsr->iColFilter = iCol; + + return SQLITE_OK; +} + +/* +** This function is called on a MultiSegReader that has been started using +** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also +** have been made. Calling this function puts the MultiSegReader in such +** a state that if the next two calls are: +** +** sqlite3Fts3SegReaderStart() +** sqlite3Fts3SegReaderStep() +** +** then the entire doclist for the term is available in +** MultiSegReader.aDoclist/nDoclist. +*/ +int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){ + int i; /* Used to iterate through segment-readers */ + + assert( pCsr->zTerm==0 ); + assert( pCsr->nTerm==0 ); + assert( pCsr->aDoclist==0 ); + assert( pCsr->nDoclist==0 ); + + pCsr->nAdvance = 0; + pCsr->bRestart = 1; + for(i=0; inSegment; i++){ + pCsr->apSegment[i]->pOffsetList = 0; + pCsr->apSegment[i]->nOffsetList = 0; + pCsr->apSegment[i]->iDocid = 0; + } + + return SQLITE_OK; +} + + +int sqlite3Fts3SegReaderStep( + Fts3Table *p, /* Virtual table handle */ + Fts3MultiSegReader *pCsr /* Cursor object */ +){ + int rc = SQLITE_OK; + + int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY); + int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS); + int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER); + int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX); + int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN); + int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST); + + Fts3SegReader **apSegment = pCsr->apSegment; + int nSegment = pCsr->nSegment; + Fts3SegFilter *pFilter = pCsr->pFilter; + int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( + p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp + ); + + if( pCsr->nSegment==0 ) return SQLITE_OK; + + do { + int nMerge; + int i; + + /* Advance the first pCsr->nAdvance entries in the apSegment[] array + ** forward. Then sort the list in order of current term again. + */ + for(i=0; inAdvance; i++){ + Fts3SegReader *pSeg = apSegment[i]; + if( pSeg->bLookup ){ + fts3SegReaderSetEof(pSeg); + }else{ + rc = fts3SegReaderNext(p, pSeg, 0); + } + if( rc!=SQLITE_OK ) return rc; + } + fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp); + pCsr->nAdvance = 0; + + /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */ + assert( rc==SQLITE_OK ); + if( apSegment[0]->aNode==0 ) break; + + pCsr->nTerm = apSegment[0]->nTerm; + pCsr->zTerm = apSegment[0]->zTerm; + + /* If this is a prefix-search, and if the term that apSegment[0] points + ** to does not share a suffix with pFilter->zTerm/nTerm, then all + ** required callbacks have been made. In this case exit early. + ** + ** Similarly, if this is a search for an exact match, and the first term + ** of segment apSegment[0] is not a match, exit early. + */ + if( pFilter->zTerm && !isScan ){ + if( pCsr->nTermnTerm + || (!isPrefix && pCsr->nTerm>pFilter->nTerm) + || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) + ){ + break; + } + } + + nMerge = 1; + while( nMergeaNode + && apSegment[nMerge]->nTerm==pCsr->nTerm + && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm) + ){ + nMerge++; + } + + assert( isIgnoreEmpty || (isRequirePos && !isColFilter) ); + if( nMerge==1 + && !isIgnoreEmpty + && !isFirst + && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0) + ){ + pCsr->nDoclist = apSegment[0]->nDoclist; + if( fts3SegReaderIsPending(apSegment[0]) ){ + rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist); + pCsr->aDoclist = pCsr->aBuffer; + }else{ + pCsr->aDoclist = apSegment[0]->aDoclist; + } + if( rc==SQLITE_OK ) rc = SQLITE_ROW; + }else{ + int nDoclist = 0; /* Size of doclist */ + sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */ + + /* The current term of the first nMerge entries in the array + ** of Fts3SegReader objects is the same. The doclists must be merged + ** and a single term returned with the merged doclist. + */ + for(i=0; ipOffsetList ){ + int j; /* Number of segments that share a docid */ + char *pList = 0; + int nList = 0; + int nByte; + sqlite3_int64 iDocid = apSegment[0]->iDocid; + fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); + j = 1; + while( jpOffsetList + && apSegment[j]->iDocid==iDocid + ){ + fts3SegReaderNextDocid(p, apSegment[j], 0, 0); + j++; + } + + if( isColFilter ){ + fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList); + } + + if( !isIgnoreEmpty || nList>0 ){ + + /* Calculate the 'docid' delta value to write into the merged + ** doclist. */ + sqlite3_int64 iDelta; + if( p->bDescIdx && nDoclist>0 ){ + iDelta = iPrev - iDocid; + }else{ + iDelta = iDocid - iPrev; + } + assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) ); + assert( nDoclist>0 || iDelta==iDocid ); + + nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0); + if( nDoclist+nByte>pCsr->nBuffer ){ + char *aNew; + pCsr->nBuffer = (nDoclist+nByte)*2; + aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer); + if( !aNew ){ + return SQLITE_NOMEM; + } + pCsr->aBuffer = aNew; + } + + if( isFirst ){ + char *a = &pCsr->aBuffer[nDoclist]; + int nWrite; + + nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a); + if( nWrite ){ + iPrev = iDocid; + nDoclist += nWrite; + } + }else{ + nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta); + iPrev = iDocid; + if( isRequirePos ){ + memcpy(&pCsr->aBuffer[nDoclist], pList, nList); + nDoclist += nList; + pCsr->aBuffer[nDoclist++] = '\0'; + } + } + } + + fts3SegReaderSort(apSegment, nMerge, j, xCmp); + } + if( nDoclist>0 ){ + pCsr->aDoclist = pCsr->aBuffer; + pCsr->nDoclist = nDoclist; + rc = SQLITE_ROW; + } + } + pCsr->nAdvance = nMerge; + }while( rc==SQLITE_OK ); + + return rc; +} + + +void sqlite3Fts3SegReaderFinish( + Fts3MultiSegReader *pCsr /* Cursor object */ +){ + if( pCsr ){ + int i; + for(i=0; inSegment; i++){ + sqlite3Fts3SegReaderFree(pCsr->apSegment[i]); + } + sqlite3_free(pCsr->apSegment); + sqlite3_free(pCsr->aBuffer); + + pCsr->nSegment = 0; + pCsr->apSegment = 0; + pCsr->aBuffer = 0; + } +} + +/* +** Merge all level iLevel segments in the database into a single +** iLevel+1 segment. Or, if iLevel<0, merge all segments into a +** single segment with a level equal to the numerically largest level +** currently present in the database. +** +** If this function is called with iLevel<0, but there is only one +** segment in the database, SQLITE_DONE is returned immediately. +** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, +** an SQLite error code is returned. +*/ +static int fts3SegmentMerge( + Fts3Table *p, + int iLangid, /* Language id to merge */ + int iIndex, /* Index in p->aIndex[] to merge */ + int iLevel /* Level to merge */ +){ + int rc; /* Return code */ + int iIdx = 0; /* Index of new segment */ + sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */ + SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */ + Fts3SegFilter filter; /* Segment term filter condition */ + Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */ + int bIgnoreEmpty = 0; /* True to ignore empty segments */ + + assert( iLevel==FTS3_SEGCURSOR_ALL + || iLevel==FTS3_SEGCURSOR_PENDING + || iLevel>=0 + ); + assert( iLevel=0 && iIndexnIndex ); + + rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr); + if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished; + + if( iLevel==FTS3_SEGCURSOR_ALL ){ + /* This call is to merge all segments in the database to a single + ** segment. The level of the new segment is equal to the numerically + ** greatest segment level currently present in the database for this + ** index. The idx of the new segment is always 0. */ + if( csr.nSegment==1 ){ + rc = SQLITE_DONE; + goto finished; + } + rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel); + bIgnoreEmpty = 1; + + }else if( iLevel==FTS3_SEGCURSOR_PENDING ){ + iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0); + rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx); + }else{ + /* This call is to merge all segments at level iLevel. find the next + ** available segment index at level iLevel+1. The call to + ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to + ** a single iLevel+2 segment if necessary. */ + rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx); + iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1); + } + if( rc!=SQLITE_OK ) goto finished; + assert( csr.nSegment>0 ); + assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) ); + assert( iNewLevelnIndex; i++){ + rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + } + sqlite3Fts3PendingTermsClear(p); + + /* Determine the auto-incr-merge setting if unknown. If enabled, + ** estimate the number of leaf blocks of content to be written + */ + if( rc==SQLITE_OK && p->bHasStat + && p->bAutoincrmerge==0xff && p->nLeafAdd>0 + ){ + sqlite3_stmt *pStmt = 0; + rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); + rc = sqlite3_step(pStmt); + p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0)); + rc = sqlite3_reset(pStmt); + } + } + return rc; +} + +/* +** Encode N integers as varints into a blob. +*/ +static void fts3EncodeIntArray( + int N, /* The number of integers to encode */ + u32 *a, /* The integer values */ + char *zBuf, /* Write the BLOB here */ + int *pNBuf /* Write number of bytes if zBuf[] used here */ +){ + int i, j; + for(i=j=0; iiPrevDocid. The sizes are encoded as +** a blob of varints. +*/ +static void fts3InsertDocsize( + int *pRC, /* Result code */ + Fts3Table *p, /* Table into which to insert */ + u32 *aSz /* Sizes of each column, in tokens */ +){ + char *pBlob; /* The BLOB encoding of the document size */ + int nBlob; /* Number of bytes in the BLOB */ + sqlite3_stmt *pStmt; /* Statement used to insert the encoding */ + int rc; /* Result code from subfunctions */ + + if( *pRC ) return; + pBlob = sqlite3_malloc( 10*p->nColumn ); + if( pBlob==0 ){ + *pRC = SQLITE_NOMEM; + return; + } + fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob); + rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0); + if( rc ){ + sqlite3_free(pBlob); + *pRC = rc; + return; + } + sqlite3_bind_int64(pStmt, 1, p->iPrevDocid); + sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free); + sqlite3_step(pStmt); + *pRC = sqlite3_reset(pStmt); +} + +/* +** Record 0 of the %_stat table contains a blob consisting of N varints, +** where N is the number of user defined columns in the fts3 table plus +** two. If nCol is the number of user defined columns, then values of the +** varints are set as follows: +** +** Varint 0: Total number of rows in the table. +** +** Varint 1..nCol: For each column, the total number of tokens stored in +** the column for all rows of the table. +** +** Varint 1+nCol: The total size, in bytes, of all text values in all +** columns of all rows of the table. +** +*/ +static void fts3UpdateDocTotals( + int *pRC, /* The result code */ + Fts3Table *p, /* Table being updated */ + u32 *aSzIns, /* Size increases */ + u32 *aSzDel, /* Size decreases */ + int nChng /* Change in the number of documents */ +){ + char *pBlob; /* Storage for BLOB written into %_stat */ + int nBlob; /* Size of BLOB written into %_stat */ + u32 *a; /* Array of integers that becomes the BLOB */ + sqlite3_stmt *pStmt; /* Statement for reading and writing */ + int i; /* Loop counter */ + int rc; /* Result code from subfunctions */ + + const int nStat = p->nColumn+2; + + if( *pRC ) return; + a = sqlite3_malloc( (sizeof(u32)+10)*nStat ); + if( a==0 ){ + *pRC = SQLITE_NOMEM; + return; + } + pBlob = (char*)&a[nStat]; + rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); + if( rc ){ + sqlite3_free(a); + *pRC = rc; + return; + } + sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); + if( sqlite3_step(pStmt)==SQLITE_ROW ){ + fts3DecodeIntArray(nStat, a, + sqlite3_column_blob(pStmt, 0), + sqlite3_column_bytes(pStmt, 0)); + }else{ + memset(a, 0, sizeof(u32)*(nStat) ); + } + rc = sqlite3_reset(pStmt); + if( rc!=SQLITE_OK ){ + sqlite3_free(a); + *pRC = rc; + return; + } + if( nChng<0 && a[0]<(u32)(-nChng) ){ + a[0] = 0; + }else{ + a[0] += nChng; + } + for(i=0; inColumn+1; i++){ + u32 x = a[i+1]; + if( x+aSzIns[i] < aSzDel[i] ){ + x = 0; + }else{ + x = x + aSzIns[i] - aSzDel[i]; + } + a[i+1] = x; + } + fts3EncodeIntArray(nStat, a, pBlob, &nBlob); + rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); + if( rc ){ + sqlite3_free(a); + *pRC = rc; + return; + } + sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); + sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC); + sqlite3_step(pStmt); + *pRC = sqlite3_reset(pStmt); + sqlite3_free(a); +} + +/* +** Merge the entire database so that there is one segment for each +** iIndex/iLangid combination. +*/ +static int fts3DoOptimize(Fts3Table *p, int bReturnDone){ + int bSeenDone = 0; + int rc; + sqlite3_stmt *pAllLangid = 0; + + rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); + if( rc==SQLITE_OK ){ + int rc2; + sqlite3_bind_int(pAllLangid, 1, p->nIndex); + while( sqlite3_step(pAllLangid)==SQLITE_ROW ){ + int i; + int iLangid = sqlite3_column_int(pAllLangid, 0); + for(i=0; rc==SQLITE_OK && inIndex; i++){ + rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL); + if( rc==SQLITE_DONE ){ + bSeenDone = 1; + rc = SQLITE_OK; + } + } + } + rc2 = sqlite3_reset(pAllLangid); + if( rc==SQLITE_OK ) rc = rc2; + } + + sqlite3Fts3SegmentsClose(p); + sqlite3Fts3PendingTermsClear(p); + + return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc; +} + +/* +** This function is called when the user executes the following statement: +** +** INSERT INTO () VALUES('rebuild'); +** +** The entire FTS index is discarded and rebuilt. If the table is one +** created using the content=xxx option, then the new index is based on +** the current contents of the xxx table. Otherwise, it is rebuilt based +** on the contents of the %_content table. +*/ +static int fts3DoRebuild(Fts3Table *p){ + int rc; /* Return Code */ + + rc = fts3DeleteAll(p, 0); + if( rc==SQLITE_OK ){ + u32 *aSz = 0; + u32 *aSzIns = 0; + u32 *aSzDel = 0; + sqlite3_stmt *pStmt = 0; + int nEntry = 0; + + /* Compose and prepare an SQL statement to loop through the content table */ + char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); + if( !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + } + + if( rc==SQLITE_OK ){ + int nByte = sizeof(u32) * (p->nColumn+1)*3; + aSz = (u32 *)sqlite3_malloc(nByte); + if( aSz==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(aSz, 0, nByte); + aSzIns = &aSz[p->nColumn+1]; + aSzDel = &aSzIns[p->nColumn+1]; + } + } + + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ + int iCol; + int iLangid = langidFromSelect(p, pStmt); + rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0)); + memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1)); + for(iCol=0; rc==SQLITE_OK && iColnColumn; iCol++){ + if( p->abNotindexed[iCol]==0 ){ + const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1); + rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]); + aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1); + } + } + if( p->bHasDocsize ){ + fts3InsertDocsize(&rc, p, aSz); + } + if( rc!=SQLITE_OK ){ + sqlite3_finalize(pStmt); + pStmt = 0; + }else{ + nEntry++; + for(iCol=0; iCol<=p->nColumn; iCol++){ + aSzIns[iCol] += aSz[iCol]; + } + } + } + if( p->bFts4 ){ + fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry); + } + sqlite3_free(aSz); + + if( pStmt ){ + int rc2 = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + + return rc; +} + + +/* +** This function opens a cursor used to read the input data for an +** incremental merge operation. Specifically, it opens a cursor to scan +** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute +** level iAbsLevel. +*/ +static int fts3IncrmergeCsr( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level to open */ + int nSeg, /* Number of segments to merge */ + Fts3MultiSegReader *pCsr /* Cursor object to populate */ +){ + int rc; /* Return Code */ + sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */ + int nByte; /* Bytes allocated at pCsr->apSegment[] */ + + /* Allocate space for the Fts3MultiSegReader.aCsr[] array */ + memset(pCsr, 0, sizeof(*pCsr)); + nByte = sizeof(Fts3SegReader *) * nSeg; + pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte); + + if( pCsr->apSegment==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pCsr->apSegment, 0, nByte); + rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); + } + if( rc==SQLITE_OK ){ + int i; + int rc2; + sqlite3_bind_int64(pStmt, 1, iAbsLevel); + assert( pCsr->nSegment==0 ); + for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && iapSegment[i] + ); + pCsr->nSegment++; + } + rc2 = sqlite3_reset(pStmt); + if( rc==SQLITE_OK ) rc = rc2; + } + + return rc; +} + +typedef struct IncrmergeWriter IncrmergeWriter; +typedef struct NodeWriter NodeWriter; +typedef struct Blob Blob; +typedef struct NodeReader NodeReader; + +/* +** An instance of the following structure is used as a dynamic buffer +** to build up nodes or other blobs of data in. +** +** The function blobGrowBuffer() is used to extend the allocation. +*/ +struct Blob { + char *a; /* Pointer to allocation */ + int n; /* Number of valid bytes of data in a[] */ + int nAlloc; /* Allocated size of a[] (nAlloc>=n) */ +}; + +/* +** This structure is used to build up buffers containing segment b-tree +** nodes (blocks). +*/ +struct NodeWriter { + sqlite3_int64 iBlock; /* Current block id */ + Blob key; /* Last key written to the current block */ + Blob block; /* Current block image */ +}; + +/* +** An object of this type contains the state required to create or append +** to an appendable b-tree segment. +*/ +struct IncrmergeWriter { + int nLeafEst; /* Space allocated for leaf blocks */ + int nWork; /* Number of leaf pages flushed */ + sqlite3_int64 iAbsLevel; /* Absolute level of input segments */ + int iIdx; /* Index of *output* segment in iAbsLevel+1 */ + sqlite3_int64 iStart; /* Block number of first allocated block */ + sqlite3_int64 iEnd; /* Block number of last allocated block */ + NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT]; +}; + +/* +** An object of the following type is used to read data from a single +** FTS segment node. See the following functions: +** +** nodeReaderInit() +** nodeReaderNext() +** nodeReaderRelease() +*/ +struct NodeReader { + const char *aNode; + int nNode; + int iOff; /* Current offset within aNode[] */ + + /* Output variables. Containing the current node entry. */ + sqlite3_int64 iChild; /* Pointer to child node */ + Blob term; /* Current term */ + const char *aDoclist; /* Pointer to doclist */ + int nDoclist; /* Size of doclist in bytes */ +}; + +/* +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** Otherwise, if the allocation at pBlob->a is not already at least nMin +** bytes in size, extend (realloc) it to be so. +** +** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a +** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc +** to reflect the new size of the pBlob->a[] buffer. +*/ +static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){ + if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){ + int nAlloc = nMin; + char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc); + if( a ){ + pBlob->nAlloc = nAlloc; + pBlob->a = a; + }else{ + *pRc = SQLITE_NOMEM; + } + } +} + +/* +** Attempt to advance the node-reader object passed as the first argument to +** the next entry on the node. +** +** Return an error code if an error occurs (SQLITE_NOMEM is possible). +** Otherwise return SQLITE_OK. If there is no next entry on the node +** (e.g. because the current entry is the last) set NodeReader->aNode to +** NULL to indicate EOF. Otherwise, populate the NodeReader structure output +** variables for the new entry. +*/ +static int nodeReaderNext(NodeReader *p){ + int bFirst = (p->term.n==0); /* True for first term on the node */ + int nPrefix = 0; /* Bytes to copy from previous term */ + int nSuffix = 0; /* Bytes to append to the prefix */ + int rc = SQLITE_OK; /* Return code */ + + assert( p->aNode ); + if( p->iChild && bFirst==0 ) p->iChild++; + if( p->iOff>=p->nNode ){ + /* EOF */ + p->aNode = 0; + }else{ + if( bFirst==0 ){ + p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix); + } + p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix); + + blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc); + if( rc==SQLITE_OK ){ + memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix); + p->term.n = nPrefix+nSuffix; + p->iOff += nSuffix; + if( p->iChild==0 ){ + p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist); + p->aDoclist = &p->aNode[p->iOff]; + p->iOff += p->nDoclist; + } + } + } + + assert( p->iOff<=p->nNode ); + + return rc; +} + +/* +** Release all dynamic resources held by node-reader object *p. +*/ +static void nodeReaderRelease(NodeReader *p){ + sqlite3_free(p->term.a); +} + +/* +** Initialize a node-reader object to read the node in buffer aNode/nNode. +** +** If successful, SQLITE_OK is returned and the NodeReader object set to +** point to the first entry on the node (if any). Otherwise, an SQLite +** error code is returned. +*/ +static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){ + memset(p, 0, sizeof(NodeReader)); + p->aNode = aNode; + p->nNode = nNode; + + /* Figure out if this is a leaf or an internal node. */ + if( p->aNode[0] ){ + /* An internal node. */ + p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild); + }else{ + p->iOff = 1; + } + + return nodeReaderNext(p); +} + +/* +** This function is called while writing an FTS segment each time a leaf o +** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed +** to be greater than the largest key on the node just written, but smaller +** than or equal to the first key that will be written to the next leaf +** node. +** +** The block id of the leaf node just written to disk may be found in +** (pWriter->aNodeWriter[0].iBlock) when this function is called. +*/ +static int fts3IncrmergePush( + Fts3Table *p, /* Fts3 table handle */ + IncrmergeWriter *pWriter, /* Writer object */ + const char *zTerm, /* Term to write to internal node */ + int nTerm /* Bytes at zTerm */ +){ + sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock; + int iLayer; + + assert( nTerm>0 ); + for(iLayer=1; ALWAYS(iLayeraNodeWriter[iLayer]; + int rc = SQLITE_OK; + int nPrefix; + int nSuffix; + int nSpace; + + /* Figure out how much space the key will consume if it is written to + ** the current node of layer iLayer. Due to the prefix compression, + ** the space required changes depending on which node the key is to + ** be added to. */ + nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm); + nSuffix = nTerm - nPrefix; + nSpace = sqlite3Fts3VarintLen(nPrefix); + nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; + + if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ + /* If the current node of layer iLayer contains zero keys, or if adding + ** the key to it will not cause it to grow to larger than nNodeSize + ** bytes in size, write the key here. */ + + Blob *pBlk = &pNode->block; + if( pBlk->n==0 ){ + blobGrowBuffer(pBlk, p->nNodeSize, &rc); + if( rc==SQLITE_OK ){ + pBlk->a[0] = (char)iLayer; + pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr); + } + } + blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc); + blobGrowBuffer(&pNode->key, nTerm, &rc); + + if( rc==SQLITE_OK ){ + if( pNode->key.n ){ + pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix); + } + pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix); + memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix); + pBlk->n += nSuffix; + + memcpy(pNode->key.a, zTerm, nTerm); + pNode->key.n = nTerm; + } + }else{ + /* Otherwise, flush the current node of layer iLayer to disk. + ** Then allocate a new, empty sibling node. The key will be written + ** into the parent of this node. */ + rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); + + assert( pNode->block.nAlloc>=p->nNodeSize ); + pNode->block.a[0] = (char)iLayer; + pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1); + + iNextPtr = pNode->iBlock; + pNode->iBlock++; + pNode->key.n = 0; + } + + if( rc!=SQLITE_OK || iNextPtr==0 ) return rc; + iPtr = iNextPtr; + } + + assert( 0 ); + return 0; +} + +/* +** Append a term and (optionally) doclist to the FTS segment node currently +** stored in blob *pNode. The node need not contain any terms, but the +** header must be written before this function is called. +** +** A node header is a single 0x00 byte for a leaf node, or a height varint +** followed by the left-hand-child varint for an internal node. +** +** The term to be appended is passed via arguments zTerm/nTerm. For a +** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal +** node, both aDoclist and nDoclist must be passed 0. +** +** If the size of the value in blob pPrev is zero, then this is the first +** term written to the node. Otherwise, pPrev contains a copy of the +** previous term. Before this function returns, it is updated to contain a +** copy of zTerm/nTerm. +** +** It is assumed that the buffer associated with pNode is already large +** enough to accommodate the new entry. The buffer associated with pPrev +** is extended by this function if requrired. +** +** If an error (i.e. OOM condition) occurs, an SQLite error code is +** returned. Otherwise, SQLITE_OK. +*/ +static int fts3AppendToNode( + Blob *pNode, /* Current node image to append to */ + Blob *pPrev, /* Buffer containing previous term written */ + const char *zTerm, /* New term to write */ + int nTerm, /* Size of zTerm in bytes */ + const char *aDoclist, /* Doclist (or NULL) to write */ + int nDoclist /* Size of aDoclist in bytes */ +){ + int rc = SQLITE_OK; /* Return code */ + int bFirst = (pPrev->n==0); /* True if this is the first term written */ + int nPrefix; /* Size of term prefix in bytes */ + int nSuffix; /* Size of term suffix in bytes */ + + /* Node must have already been started. There must be a doclist for a + ** leaf node, and there must not be a doclist for an internal node. */ + assert( pNode->n>0 ); + assert( (pNode->a[0]=='\0')==(aDoclist!=0) ); + + blobGrowBuffer(pPrev, nTerm, &rc); + if( rc!=SQLITE_OK ) return rc; + + nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm); + nSuffix = nTerm - nPrefix; + memcpy(pPrev->a, zTerm, nTerm); + pPrev->n = nTerm; + + if( bFirst==0 ){ + pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix); + } + pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix); + memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix); + pNode->n += nSuffix; + + if( aDoclist ){ + pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist); + memcpy(&pNode->a[pNode->n], aDoclist, nDoclist); + pNode->n += nDoclist; + } + + assert( pNode->n<=pNode->nAlloc ); + + return SQLITE_OK; +} + +/* +** Append the current term and doclist pointed to by cursor pCsr to the +** appendable b-tree segment opened for writing by pWriter. +** +** Return SQLITE_OK if successful, or an SQLite error code otherwise. +*/ +static int fts3IncrmergeAppend( + Fts3Table *p, /* Fts3 table handle */ + IncrmergeWriter *pWriter, /* Writer object */ + Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */ +){ + const char *zTerm = pCsr->zTerm; + int nTerm = pCsr->nTerm; + const char *aDoclist = pCsr->aDoclist; + int nDoclist = pCsr->nDoclist; + int rc = SQLITE_OK; /* Return code */ + int nSpace; /* Total space in bytes required on leaf */ + int nPrefix; /* Size of prefix shared with previous term */ + int nSuffix; /* Size of suffix (nTerm - nPrefix) */ + NodeWriter *pLeaf; /* Object used to write leaf nodes */ + + pLeaf = &pWriter->aNodeWriter[0]; + nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm); + nSuffix = nTerm - nPrefix; + + nSpace = sqlite3Fts3VarintLen(nPrefix); + nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; + nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; + + /* If the current block is not empty, and if adding this term/doclist + ** to the current block would make it larger than Fts3Table.nNodeSize + ** bytes, write this block out to the database. */ + if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){ + rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n); + pWriter->nWork++; + + /* Add the current term to the parent node. The term added to the + ** parent must: + ** + ** a) be greater than the largest term on the leaf node just written + ** to the database (still available in pLeaf->key), and + ** + ** b) be less than or equal to the term about to be added to the new + ** leaf node (zTerm/nTerm). + ** + ** In other words, it must be the prefix of zTerm 1 byte longer than + ** the common prefix (if any) of zTerm and pWriter->zTerm. + */ + if( rc==SQLITE_OK ){ + rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1); + } + + /* Advance to the next output block */ + pLeaf->iBlock++; + pLeaf->key.n = 0; + pLeaf->block.n = 0; + + nSuffix = nTerm; + nSpace = 1; + nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; + nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; + } + + blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc); + + if( rc==SQLITE_OK ){ + if( pLeaf->block.n==0 ){ + pLeaf->block.n = 1; + pLeaf->block.a[0] = '\0'; + } + rc = fts3AppendToNode( + &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist + ); + } + + return rc; +} + +/* +** This function is called to release all dynamic resources held by the +** merge-writer object pWriter, and if no error has occurred, to flush +** all outstanding node buffers held by pWriter to disk. +** +** If *pRc is not SQLITE_OK when this function is called, then no attempt +** is made to write any data to disk. Instead, this function serves only +** to release outstanding resources. +** +** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while +** flushing buffers to disk, *pRc is set to an SQLite error code before +** returning. +*/ +static void fts3IncrmergeRelease( + Fts3Table *p, /* FTS3 table handle */ + IncrmergeWriter *pWriter, /* Merge-writer object */ + int *pRc /* IN/OUT: Error code */ +){ + int i; /* Used to iterate through non-root layers */ + int iRoot; /* Index of root in pWriter->aNodeWriter */ + NodeWriter *pRoot; /* NodeWriter for root node */ + int rc = *pRc; /* Error code */ + + /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment + ** root node. If the segment fits entirely on a single leaf node, iRoot + ** will be set to 0. If the root node is the parent of the leaves, iRoot + ** will be 1. And so on. */ + for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){ + NodeWriter *pNode = &pWriter->aNodeWriter[iRoot]; + if( pNode->block.n>0 ) break; + assert( *pRc || pNode->block.nAlloc==0 ); + assert( *pRc || pNode->key.nAlloc==0 ); + sqlite3_free(pNode->block.a); + sqlite3_free(pNode->key.a); + } + + /* Empty output segment. This is a no-op. */ + if( iRoot<0 ) return; + + /* The entire output segment fits on a single node. Normally, this means + ** the node would be stored as a blob in the "root" column of the %_segdir + ** table. However, this is not permitted in this case. The problem is that + ** space has already been reserved in the %_segments table, and so the + ** start_block and end_block fields of the %_segdir table must be populated. + ** And, by design or by accident, released versions of FTS cannot handle + ** segments that fit entirely on the root node with start_block!=0. + ** + ** Instead, create a synthetic root node that contains nothing but a + ** pointer to the single content node. So that the segment consists of a + ** single leaf and a single interior (root) node. + ** + ** Todo: Better might be to defer allocating space in the %_segments + ** table until we are sure it is needed. + */ + if( iRoot==0 ){ + Blob *pBlock = &pWriter->aNodeWriter[1].block; + blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc); + if( rc==SQLITE_OK ){ + pBlock->a[0] = 0x01; + pBlock->n = 1 + sqlite3Fts3PutVarint( + &pBlock->a[1], pWriter->aNodeWriter[0].iBlock + ); + } + iRoot = 1; + } + pRoot = &pWriter->aNodeWriter[iRoot]; + + /* Flush all currently outstanding nodes to disk. */ + for(i=0; iaNodeWriter[i]; + if( pNode->block.n>0 && rc==SQLITE_OK ){ + rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); + } + sqlite3_free(pNode->block.a); + sqlite3_free(pNode->key.a); + } + + /* Write the %_segdir record. */ + if( rc==SQLITE_OK ){ + rc = fts3WriteSegdir(p, + pWriter->iAbsLevel+1, /* level */ + pWriter->iIdx, /* idx */ + pWriter->iStart, /* start_block */ + pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */ + pWriter->iEnd, /* end_block */ + pRoot->block.a, pRoot->block.n /* root */ + ); + } + sqlite3_free(pRoot->block.a); + sqlite3_free(pRoot->key.a); + + *pRc = rc; +} + +/* +** Compare the term in buffer zLhs (size in bytes nLhs) with that in +** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of +** the other, it is considered to be smaller than the other. +** +** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve +** if it is greater. +*/ +static int fts3TermCmp( + const char *zLhs, int nLhs, /* LHS of comparison */ + const char *zRhs, int nRhs /* RHS of comparison */ +){ + int nCmp = MIN(nLhs, nRhs); + int res; + + res = memcmp(zLhs, zRhs, nCmp); + if( res==0 ) res = nLhs - nRhs; + + return res; +} + + +/* +** Query to see if the entry in the %_segments table with blockid iEnd is +** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before +** returning. Otherwise, set *pbRes to 0. +** +** Or, if an error occurs while querying the database, return an SQLite +** error code. The final value of *pbRes is undefined in this case. +** +** This is used to test if a segment is an "appendable" segment. If it +** is, then a NULL entry has been inserted into the %_segments table +** with blockid %_segdir.end_block. +*/ +static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){ + int bRes = 0; /* Result to set *pbRes to */ + sqlite3_stmt *pCheck = 0; /* Statement to query database with */ + int rc; /* Return code */ + + rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pCheck, 1, iEnd); + if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1; + rc = sqlite3_reset(pCheck); + } + + *pbRes = bRes; + return rc; +} + +/* +** This function is called when initializing an incremental-merge operation. +** It checks if the existing segment with index value iIdx at absolute level +** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the +** merge-writer object *pWriter is initialized to write to it. +** +** An existing segment can be appended to by an incremental merge if: +** +** * It was initially created as an appendable segment (with all required +** space pre-allocated), and +** +** * The first key read from the input (arguments zKey and nKey) is +** greater than the largest key currently stored in the potential +** output segment. +*/ +static int fts3IncrmergeLoad( + Fts3Table *p, /* Fts3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ + int iIdx, /* Index of candidate output segment */ + const char *zKey, /* First key to write */ + int nKey, /* Number of bytes in nKey */ + IncrmergeWriter *pWriter /* Populate this object */ +){ + int rc; /* Return code */ + sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */ + + rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0); + if( rc==SQLITE_OK ){ + sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */ + sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */ + sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */ + const char *aRoot = 0; /* Pointer to %_segdir.root buffer */ + int nRoot = 0; /* Size of aRoot[] in bytes */ + int rc2; /* Return code from sqlite3_reset() */ + int bAppendable = 0; /* Set to true if segment is appendable */ + + /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */ + sqlite3_bind_int64(pSelect, 1, iAbsLevel+1); + sqlite3_bind_int(pSelect, 2, iIdx); + if( sqlite3_step(pSelect)==SQLITE_ROW ){ + iStart = sqlite3_column_int64(pSelect, 1); + iLeafEnd = sqlite3_column_int64(pSelect, 2); + iEnd = sqlite3_column_int64(pSelect, 3); + nRoot = sqlite3_column_bytes(pSelect, 4); + aRoot = sqlite3_column_blob(pSelect, 4); + }else{ + return sqlite3_reset(pSelect); + } + + /* Check for the zero-length marker in the %_segments table */ + rc = fts3IsAppendable(p, iEnd, &bAppendable); + + /* Check that zKey/nKey is larger than the largest key the candidate */ + if( rc==SQLITE_OK && bAppendable ){ + char *aLeaf = 0; + int nLeaf = 0; + + rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0); + if( rc==SQLITE_OK ){ + NodeReader reader; + for(rc = nodeReaderInit(&reader, aLeaf, nLeaf); + rc==SQLITE_OK && reader.aNode; + rc = nodeReaderNext(&reader) + ){ + assert( reader.aNode ); + } + if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){ + bAppendable = 0; + } + nodeReaderRelease(&reader); + } + sqlite3_free(aLeaf); + } + + if( rc==SQLITE_OK && bAppendable ){ + /* It is possible to append to this segment. Set up the IncrmergeWriter + ** object to do so. */ + int i; + int nHeight = (int)aRoot[0]; + NodeWriter *pNode; + + pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT; + pWriter->iStart = iStart; + pWriter->iEnd = iEnd; + pWriter->iAbsLevel = iAbsLevel; + pWriter->iIdx = iIdx; + + for(i=nHeight+1; iaNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; + } + + pNode = &pWriter->aNodeWriter[nHeight]; + pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight; + blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc); + if( rc==SQLITE_OK ){ + memcpy(pNode->block.a, aRoot, nRoot); + pNode->block.n = nRoot; + } + + for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){ + NodeReader reader; + pNode = &pWriter->aNodeWriter[i]; + + rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n); + while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader); + blobGrowBuffer(&pNode->key, reader.term.n, &rc); + if( rc==SQLITE_OK ){ + memcpy(pNode->key.a, reader.term.a, reader.term.n); + pNode->key.n = reader.term.n; + if( i>0 ){ + char *aBlock = 0; + int nBlock = 0; + pNode = &pWriter->aNodeWriter[i-1]; + pNode->iBlock = reader.iChild; + rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0); + blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc); + if( rc==SQLITE_OK ){ + memcpy(pNode->block.a, aBlock, nBlock); + pNode->block.n = nBlock; + } + sqlite3_free(aBlock); + } + } + nodeReaderRelease(&reader); + } + } + + rc2 = sqlite3_reset(pSelect); + if( rc==SQLITE_OK ) rc = rc2; + } + + return rc; +} + +/* +** Determine the largest segment index value that exists within absolute +** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus +** one before returning SQLITE_OK. Or, if there are no segments at all +** within level iAbsLevel, set *piIdx to zero. +** +** If an error occurs, return an SQLite error code. The final value of +** *piIdx is undefined in this case. +*/ +static int fts3IncrmergeOutputIdx( + Fts3Table *p, /* FTS Table handle */ + sqlite3_int64 iAbsLevel, /* Absolute index of input segments */ + int *piIdx /* OUT: Next free index at iAbsLevel+1 */ +){ + int rc; + sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */ + + rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1); + sqlite3_step(pOutputIdx); + *piIdx = sqlite3_column_int(pOutputIdx, 0); + rc = sqlite3_reset(pOutputIdx); + } + + return rc; +} + +/* +** Allocate an appendable output segment on absolute level iAbsLevel+1 +** with idx value iIdx. +** +** In the %_segdir table, a segment is defined by the values in three +** columns: +** +** start_block +** leaves_end_block +** end_block +** +** When an appendable segment is allocated, it is estimated that the +** maximum number of leaf blocks that may be required is the sum of the +** number of leaf blocks consumed by the input segments, plus the number +** of input segments, multiplied by two. This value is stored in stack +** variable nLeafEst. +** +** A total of 16*nLeafEst blocks are allocated when an appendable segment +** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous +** array of leaf nodes starts at the first block allocated. The array +** of interior nodes that are parents of the leaf nodes start at block +** (start_block + (1 + end_block - start_block) / 16). And so on. +** +** In the actual code below, the value "16" is replaced with the +** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT. +*/ +static int fts3IncrmergeWriter( + Fts3Table *p, /* Fts3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ + int iIdx, /* Index of new output segment */ + Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */ + IncrmergeWriter *pWriter /* Populate this object */ +){ + int rc; /* Return Code */ + int i; /* Iterator variable */ + int nLeafEst = 0; /* Blocks allocated for leaf nodes */ + sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */ + sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */ + + /* Calculate nLeafEst. */ + rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pLeafEst, 1, iAbsLevel); + sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment); + if( SQLITE_ROW==sqlite3_step(pLeafEst) ){ + nLeafEst = sqlite3_column_int(pLeafEst, 0); + } + rc = sqlite3_reset(pLeafEst); + } + if( rc!=SQLITE_OK ) return rc; + + /* Calculate the first block to use in the output segment */ + rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0); + if( rc==SQLITE_OK ){ + if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){ + pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0); + pWriter->iEnd = pWriter->iStart - 1; + pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT; + } + rc = sqlite3_reset(pFirstBlock); + } + if( rc!=SQLITE_OK ) return rc; + + /* Insert the marker in the %_segments table to make sure nobody tries + ** to steal the space just allocated. This is also used to identify + ** appendable segments. */ + rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0); + if( rc!=SQLITE_OK ) return rc; + + pWriter->iAbsLevel = iAbsLevel; + pWriter->nLeafEst = nLeafEst; + pWriter->iIdx = iIdx; + + /* Set up the array of NodeWriter objects */ + for(i=0; iaNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; + } + return SQLITE_OK; +} + +/* +** Remove an entry from the %_segdir table. This involves running the +** following two statements: +** +** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx +** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx +** +** The DELETE statement removes the specific %_segdir level. The UPDATE +** statement ensures that the remaining segments have contiguously allocated +** idx values. +*/ +static int fts3RemoveSegdirEntry( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level to delete from */ + int iIdx /* Index of %_segdir entry to delete */ +){ + int rc; /* Return code */ + sqlite3_stmt *pDelete = 0; /* DELETE statement */ + + rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pDelete, 1, iAbsLevel); + sqlite3_bind_int(pDelete, 2, iIdx); + sqlite3_step(pDelete); + rc = sqlite3_reset(pDelete); + } + + return rc; +} + +/* +** One or more segments have just been removed from absolute level iAbsLevel. +** Update the 'idx' values of the remaining segments in the level so that +** the idx values are a contiguous sequence starting from 0. +*/ +static int fts3RepackSegdirLevel( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iAbsLevel /* Absolute level to repack */ +){ + int rc; /* Return code */ + int *aIdx = 0; /* Array of remaining idx values */ + int nIdx = 0; /* Valid entries in aIdx[] */ + int nAlloc = 0; /* Allocated size of aIdx[] */ + int i; /* Iterator variable */ + sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */ + sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */ + + rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0); + if( rc==SQLITE_OK ){ + int rc2; + sqlite3_bind_int64(pSelect, 1, iAbsLevel); + while( SQLITE_ROW==sqlite3_step(pSelect) ){ + if( nIdx>=nAlloc ){ + int *aNew; + nAlloc += 16; + aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int)); + if( !aNew ){ + rc = SQLITE_NOMEM; + break; + } + aIdx = aNew; + } + aIdx[nIdx++] = sqlite3_column_int(pSelect, 0); + } + rc2 = sqlite3_reset(pSelect); + if( rc==SQLITE_OK ) rc = rc2; + } + + if( rc==SQLITE_OK ){ + rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0); + } + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pUpdate, 2, iAbsLevel); + } + + assert( p->bIgnoreSavepoint==0 ); + p->bIgnoreSavepoint = 1; + for(i=0; rc==SQLITE_OK && ibIgnoreSavepoint = 0; + + sqlite3_free(aIdx); + return rc; +} + +static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){ + pNode->a[0] = (char)iHeight; + if( iChild ){ + assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) ); + pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild); + }else{ + assert( pNode->nAlloc>=1 ); + pNode->n = 1; + } +} + +/* +** The first two arguments are a pointer to and the size of a segment b-tree +** node. The node may be a leaf or an internal node. +** +** This function creates a new node image in blob object *pNew by copying +** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes) +** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode. +*/ +static int fts3TruncateNode( + const char *aNode, /* Current node image */ + int nNode, /* Size of aNode in bytes */ + Blob *pNew, /* OUT: Write new node image here */ + const char *zTerm, /* Omit all terms smaller than this */ + int nTerm, /* Size of zTerm in bytes */ + sqlite3_int64 *piBlock /* OUT: Block number in next layer down */ +){ + NodeReader reader; /* Reader object */ + Blob prev = {0, 0, 0}; /* Previous term written to new node */ + int rc = SQLITE_OK; /* Return code */ + int bLeaf = aNode[0]=='\0'; /* True for a leaf node */ + + /* Allocate required output space */ + blobGrowBuffer(pNew, nNode, &rc); + if( rc!=SQLITE_OK ) return rc; + pNew->n = 0; + + /* Populate new node buffer */ + for(rc = nodeReaderInit(&reader, aNode, nNode); + rc==SQLITE_OK && reader.aNode; + rc = nodeReaderNext(&reader) + ){ + if( pNew->n==0 ){ + int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm); + if( res<0 || (bLeaf==0 && res==0) ) continue; + fts3StartNode(pNew, (int)aNode[0], reader.iChild); + *piBlock = reader.iChild; + } + rc = fts3AppendToNode( + pNew, &prev, reader.term.a, reader.term.n, + reader.aDoclist, reader.nDoclist + ); + if( rc!=SQLITE_OK ) break; + } + if( pNew->n==0 ){ + fts3StartNode(pNew, (int)aNode[0], reader.iChild); + *piBlock = reader.iChild; + } + assert( pNew->n<=pNew->nAlloc ); + + nodeReaderRelease(&reader); + sqlite3_free(prev.a); + return rc; +} + +/* +** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute +** level iAbsLevel. This may involve deleting entries from the %_segments +** table, and modifying existing entries in both the %_segments and %_segdir +** tables. +** +** SQLITE_OK is returned if the segment is updated successfully. Or an +** SQLite error code otherwise. +*/ +static int fts3TruncateSegment( + Fts3Table *p, /* FTS3 table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */ + int iIdx, /* Index within level of segment to modify */ + const char *zTerm, /* Remove terms smaller than this */ + int nTerm /* Number of bytes in buffer zTerm */ +){ + int rc = SQLITE_OK; /* Return code */ + Blob root = {0,0,0}; /* New root page image */ + Blob block = {0,0,0}; /* Buffer used for any other block */ + sqlite3_int64 iBlock = 0; /* Block id */ + sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */ + sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */ + sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */ + + rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0); + if( rc==SQLITE_OK ){ + int rc2; /* sqlite3_reset() return code */ + sqlite3_bind_int64(pFetch, 1, iAbsLevel); + sqlite3_bind_int(pFetch, 2, iIdx); + if( SQLITE_ROW==sqlite3_step(pFetch) ){ + const char *aRoot = sqlite3_column_blob(pFetch, 4); + int nRoot = sqlite3_column_bytes(pFetch, 4); + iOldStart = sqlite3_column_int64(pFetch, 1); + rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock); + } + rc2 = sqlite3_reset(pFetch); + if( rc==SQLITE_OK ) rc = rc2; + } + + while( rc==SQLITE_OK && iBlock ){ + char *aBlock = 0; + int nBlock = 0; + iNewStart = iBlock; + + rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0); + if( rc==SQLITE_OK ){ + rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock); + } + if( rc==SQLITE_OK ){ + rc = fts3WriteSegment(p, iNewStart, block.a, block.n); + } + sqlite3_free(aBlock); + } + + /* Variable iNewStart now contains the first valid leaf node. */ + if( rc==SQLITE_OK && iNewStart ){ + sqlite3_stmt *pDel = 0; + rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pDel, 1, iOldStart); + sqlite3_bind_int64(pDel, 2, iNewStart-1); + sqlite3_step(pDel); + rc = sqlite3_reset(pDel); + } + } + + if( rc==SQLITE_OK ){ + sqlite3_stmt *pChomp = 0; + rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pChomp, 1, iNewStart); + sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC); + sqlite3_bind_int64(pChomp, 3, iAbsLevel); + sqlite3_bind_int(pChomp, 4, iIdx); + sqlite3_step(pChomp); + rc = sqlite3_reset(pChomp); + } + } + + sqlite3_free(root.a); + sqlite3_free(block.a); + return rc; +} + +/* +** This function is called after an incrmental-merge operation has run to +** merge (or partially merge) two or more segments from absolute level +** iAbsLevel. +** +** Each input segment is either removed from the db completely (if all of +** its data was copied to the output segment by the incrmerge operation) +** or modified in place so that it no longer contains those entries that +** have been duplicated in the output segment. +*/ +static int fts3IncrmergeChomp( + Fts3Table *p, /* FTS table handle */ + sqlite3_int64 iAbsLevel, /* Absolute level containing segments */ + Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */ + int *pnRem /* Number of segments not deleted */ +){ + int i; + int nRem = 0; + int rc = SQLITE_OK; + + for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){ + Fts3SegReader *pSeg = 0; + int j; + + /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding + ** somewhere in the pCsr->apSegment[] array. */ + for(j=0; ALWAYS(jnSegment); j++){ + pSeg = pCsr->apSegment[j]; + if( pSeg->iIdx==i ) break; + } + assert( jnSegment && pSeg->iIdx==i ); + + if( pSeg->aNode==0 ){ + /* Seg-reader is at EOF. Remove the entire input segment. */ + rc = fts3DeleteSegment(p, pSeg); + if( rc==SQLITE_OK ){ + rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx); + } + *pnRem = 0; + }else{ + /* The incremental merge did not copy all the data from this + ** segment to the upper level. The segment is modified in place + ** so that it contains no keys smaller than zTerm/nTerm. */ + const char *zTerm = pSeg->zTerm; + int nTerm = pSeg->nTerm; + rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm); + nRem++; + } + } + + if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){ + rc = fts3RepackSegdirLevel(p, iAbsLevel); + } + + *pnRem = nRem; + return rc; +} + +/* +** Store an incr-merge hint in the database. +*/ +static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){ + sqlite3_stmt *pReplace = 0; + int rc; /* Return code */ + + rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT); + sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC); + sqlite3_step(pReplace); + rc = sqlite3_reset(pReplace); + } + + return rc; +} + +/* +** Load an incr-merge hint from the database. The incr-merge hint, if one +** exists, is stored in the rowid==1 row of the %_stat table. +** +** If successful, populate blob *pHint with the value read from the %_stat +** table and return SQLITE_OK. Otherwise, if an error occurs, return an +** SQLite error code. +*/ +static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){ + sqlite3_stmt *pSelect = 0; + int rc; + + pHint->n = 0; + rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0); + if( rc==SQLITE_OK ){ + int rc2; + sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT); + if( SQLITE_ROW==sqlite3_step(pSelect) ){ + const char *aHint = sqlite3_column_blob(pSelect, 0); + int nHint = sqlite3_column_bytes(pSelect, 0); + if( aHint ){ + blobGrowBuffer(pHint, nHint, &rc); + if( rc==SQLITE_OK ){ + memcpy(pHint->a, aHint, nHint); + pHint->n = nHint; + } + } + } + rc2 = sqlite3_reset(pSelect); + if( rc==SQLITE_OK ) rc = rc2; + } + + return rc; +} + +/* +** If *pRc is not SQLITE_OK when this function is called, it is a no-op. +** Otherwise, append an entry to the hint stored in blob *pHint. Each entry +** consists of two varints, the absolute level number of the input segments +** and the number of input segments. +** +** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs, +** set *pRc to an SQLite error code before returning. +*/ +static void fts3IncrmergeHintPush( + Blob *pHint, /* Hint blob to append to */ + i64 iAbsLevel, /* First varint to store in hint */ + int nInput, /* Second varint to store in hint */ + int *pRc /* IN/OUT: Error code */ +){ + blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc); + if( *pRc==SQLITE_OK ){ + pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel); + pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput); + } +} + +/* +** Read the last entry (most recently pushed) from the hint blob *pHint +** and then remove the entry. Write the two values read to *piAbsLevel and +** *pnInput before returning. +** +** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does +** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB. +*/ +static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){ + const int nHint = pHint->n; + int i; + + i = pHint->n-2; + while( i>0 && (pHint->a[i-1] & 0x80) ) i--; + while( i>0 && (pHint->a[i-1] & 0x80) ) i--; + + pHint->n = i; + i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel); + i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput); + if( i!=nHint ) return SQLITE_CORRUPT_VTAB; + + return SQLITE_OK; +} + + +/* +** Attempt an incremental merge that writes nMerge leaf blocks. +** +** Incremental merges happen nMin segments at a time. The two +** segments to be merged are the nMin oldest segments (the ones with +** the smallest indexes) in the highest level that contains at least +** nMin segments. Multiple merges might occur in an attempt to write the +** quota of nMerge leaf blocks. +*/ +int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ + int rc; /* Return code */ + int nRem = nMerge; /* Number of leaf pages yet to be written */ + Fts3MultiSegReader *pCsr; /* Cursor used to read input data */ + Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */ + IncrmergeWriter *pWriter; /* Writer object */ + int nSeg = 0; /* Number of input segments */ + sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */ + Blob hint = {0, 0, 0}; /* Hint read from %_stat table */ + int bDirtyHint = 0; /* True if blob 'hint' has been modified */ + + /* Allocate space for the cursor, filter and writer objects */ + const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter); + pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc); + if( !pWriter ) return SQLITE_NOMEM; + pFilter = (Fts3SegFilter *)&pWriter[1]; + pCsr = (Fts3MultiSegReader *)&pFilter[1]; + + rc = fts3IncrmergeHintLoad(p, &hint); + while( rc==SQLITE_OK && nRem>0 ){ + const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex; + sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */ + int bUseHint = 0; /* True if attempting to append */ + + /* Search the %_segdir table for the absolute level with the smallest + ** relative level number that contains at least nMin segments, if any. + ** If one is found, set iAbsLevel to the absolute level number and + ** nSeg to nMin. If no level with at least nMin segments can be found, + ** set nSeg to -1. + */ + rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0); + sqlite3_bind_int(pFindLevel, 1, nMin); + if( sqlite3_step(pFindLevel)==SQLITE_ROW ){ + iAbsLevel = sqlite3_column_int64(pFindLevel, 0); + nSeg = nMin; + }else{ + nSeg = -1; + } + rc = sqlite3_reset(pFindLevel); + + /* If the hint read from the %_stat table is not empty, check if the + ** last entry in it specifies a relative level smaller than or equal + ** to the level identified by the block above (if any). If so, this + ** iteration of the loop will work on merging at the hinted level. + */ + if( rc==SQLITE_OK && hint.n ){ + int nHint = hint.n; + sqlite3_int64 iHintAbsLevel = 0; /* Hint level */ + int nHintSeg = 0; /* Hint number of segments */ + + rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg); + if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){ + iAbsLevel = iHintAbsLevel; + nSeg = nHintSeg; + bUseHint = 1; + bDirtyHint = 1; + }else{ + /* This undoes the effect of the HintPop() above - so that no entry + ** is removed from the hint blob. */ + hint.n = nHint; + } + } + + /* If nSeg is less that zero, then there is no level with at least + ** nMin segments and no hint in the %_stat table. No work to do. + ** Exit early in this case. */ + if( nSeg<0 ) break; + + /* Open a cursor to iterate through the contents of the oldest nSeg + ** indexes of absolute level iAbsLevel. If this cursor is opened using + ** the 'hint' parameters, it is possible that there are less than nSeg + ** segments available in level iAbsLevel. In this case, no work is + ** done on iAbsLevel - fall through to the next iteration of the loop + ** to start work on some other level. */ + memset(pWriter, 0, nAlloc); + pFilter->flags = FTS3_SEGMENT_REQUIRE_POS; + if( rc==SQLITE_OK ){ + rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr); + } + if( SQLITE_OK==rc && pCsr->nSegment==nSeg + && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter)) + && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr)) + ){ + int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */ + rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx); + if( rc==SQLITE_OK ){ + if( bUseHint && iIdx>0 ){ + const char *zKey = pCsr->zTerm; + int nKey = pCsr->nTerm; + rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter); + }else{ + rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter); + } + } + + if( rc==SQLITE_OK && pWriter->nLeafEst ){ + fts3LogMerge(nSeg, iAbsLevel); + do { + rc = fts3IncrmergeAppend(p, pWriter, pCsr); + if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr); + if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK; + }while( rc==SQLITE_ROW ); + + /* Update or delete the input segments */ + if( rc==SQLITE_OK ){ + nRem -= (1 + pWriter->nWork); + rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg); + if( nSeg!=0 ){ + bDirtyHint = 1; + fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc); + } + } + } + + fts3IncrmergeRelease(p, pWriter, &rc); + } + + sqlite3Fts3SegReaderFinish(pCsr); + } + + /* Write the hint values into the %_stat table for the next incr-merger */ + if( bDirtyHint && rc==SQLITE_OK ){ + rc = fts3IncrmergeHintStore(p, &hint); + } + + sqlite3_free(pWriter); + sqlite3_free(hint.a); + return rc; +} + +/* +** Convert the text beginning at *pz into an integer and return +** its value. Advance *pz to point to the first character past +** the integer. +*/ +static int fts3Getint(const char **pz){ + const char *z = *pz; + int i = 0; + while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0'; + *pz = z; + return i; +} + +/* +** Process statements of the form: +** +** INSERT INTO table(table) VALUES('merge=A,B'); +** +** A and B are integers that decode to be the number of leaf pages +** written for the merge, and the minimum number of segments on a level +** before it will be selected for a merge, respectively. +*/ +static int fts3DoIncrmerge( + Fts3Table *p, /* FTS3 table handle */ + const char *zParam /* Nul-terminated string containing "A,B" */ +){ + int rc; + int nMin = (FTS3_MERGE_COUNT / 2); + int nMerge = 0; + const char *z = zParam; + + /* Read the first integer value */ + nMerge = fts3Getint(&z); + + /* If the first integer value is followed by a ',', read the second + ** integer value. */ + if( z[0]==',' && z[1]!='\0' ){ + z++; + nMin = fts3Getint(&z); + } + + if( z[0]!='\0' || nMin<2 ){ + rc = SQLITE_ERROR; + }else{ + rc = SQLITE_OK; + if( !p->bHasStat ){ + assert( p->bFts4==0 ); + sqlite3Fts3CreateStatTable(&rc, p); + } + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3Incrmerge(p, nMerge, nMin); + } + sqlite3Fts3SegmentsClose(p); + } + return rc; +} + +/* +** Process statements of the form: +** +** INSERT INTO table(table) VALUES('automerge=X'); +** +** where X is an integer. X==0 means to turn automerge off. X!=0 means +** turn it on. The setting is persistent. +*/ +static int fts3DoAutoincrmerge( + Fts3Table *p, /* FTS3 table handle */ + const char *zParam /* Nul-terminated string containing boolean */ +){ + int rc = SQLITE_OK; + sqlite3_stmt *pStmt = 0; + p->bAutoincrmerge = fts3Getint(&zParam)!=0; + if( !p->bHasStat ){ + assert( p->bFts4==0 ); + sqlite3Fts3CreateStatTable(&rc, p); + if( rc ) return rc; + } + rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); + if( rc ) return rc; + sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); + sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge); + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + return rc; +} + +/* +** Return a 64-bit checksum for the FTS index entry specified by the +** arguments to this function. +*/ +static u64 fts3ChecksumEntry( + const char *zTerm, /* Pointer to buffer containing term */ + int nTerm, /* Size of zTerm in bytes */ + int iLangid, /* Language id for current row */ + int iIndex, /* Index (0..Fts3Table.nIndex-1) */ + i64 iDocid, /* Docid for current row. */ + int iCol, /* Column number */ + int iPos /* Position */ +){ + int i; + u64 ret = (u64)iDocid; + + ret += (ret<<3) + iLangid; + ret += (ret<<3) + iIndex; + ret += (ret<<3) + iCol; + ret += (ret<<3) + iPos; + for(i=0; inIndex-1) */ + int *pRc /* OUT: Return code */ +){ + Fts3SegFilter filter; + Fts3MultiSegReader csr; + int rc; + u64 cksum = 0; + + assert( *pRc==SQLITE_OK ); + + memset(&filter, 0, sizeof(filter)); + memset(&csr, 0, sizeof(csr)); + filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; + filter.flags |= FTS3_SEGMENT_SCAN; + + rc = sqlite3Fts3SegReaderCursor( + p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr + ); + if( rc==SQLITE_OK ){ + rc = sqlite3Fts3SegReaderStart(p, &csr, &filter); + } + + if( rc==SQLITE_OK ){ + while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){ + char *pCsr = csr.aDoclist; + char *pEnd = &pCsr[csr.nDoclist]; + + i64 iDocid = 0; + i64 iCol = 0; + i64 iPos = 0; + + pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid); + while( pCsrnIndex); + while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){ + int iLangid = sqlite3_column_int(pAllLangid, 0); + int i; + for(i=0; inIndex; i++){ + cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc); + } + } + rc2 = sqlite3_reset(pAllLangid); + if( rc==SQLITE_OK ) rc = rc2; + } + + /* This block calculates the checksum according to the %_content table */ + rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); + if( rc==SQLITE_OK ){ + sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule; + sqlite3_stmt *pStmt = 0; + char *zSql; + + zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); + if( !zSql ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + } + + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ + i64 iDocid = sqlite3_column_int64(pStmt, 0); + int iLang = langidFromSelect(p, pStmt); + int iCol; + + for(iCol=0; rc==SQLITE_OK && iColnColumn; iCol++){ + const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1); + int nText = sqlite3_column_bytes(pStmt, iCol+1); + sqlite3_tokenizer_cursor *pT = 0; + + rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT); + while( rc==SQLITE_OK ){ + char const *zToken; /* Buffer containing token */ + int nToken = 0; /* Number of bytes in token */ + int iDum1 = 0, iDum2 = 0; /* Dummy variables */ + int iPos = 0; /* Position of token in zText */ + + rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos); + if( rc==SQLITE_OK ){ + int i; + cksum2 = cksum2 ^ fts3ChecksumEntry( + zToken, nToken, iLang, 0, iDocid, iCol, iPos + ); + for(i=1; inIndex; i++){ + if( p->aIndex[i].nPrefix<=nToken ){ + cksum2 = cksum2 ^ fts3ChecksumEntry( + zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos + ); + } + } + } + } + if( pT ) pModule->xClose(pT); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + } + } + + sqlite3_finalize(pStmt); + } + + *pbOk = (cksum1==cksum2); + return rc; +} + +/* +** Run the integrity-check. If no error occurs and the current contents of +** the FTS index are correct, return SQLITE_OK. Or, if the contents of the +** FTS index are incorrect, return SQLITE_CORRUPT_VTAB. +** +** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite +** error code. +** +** The integrity-check works as follows. For each token and indexed token +** prefix in the document set, a 64-bit checksum is calculated (by code +** in fts3ChecksumEntry()) based on the following: +** +** + The index number (0 for the main index, 1 for the first prefix +** index etc.), +** + The token (or token prefix) text itself, +** + The language-id of the row it appears in, +** + The docid of the row it appears in, +** + The column it appears in, and +** + The tokens position within that column. +** +** The checksums for all entries in the index are XORed together to create +** a single checksum for the entire index. +** +** The integrity-check code calculates the same checksum in two ways: +** +** 1. By scanning the contents of the FTS index, and +** 2. By scanning and tokenizing the content table. +** +** If the two checksums are identical, the integrity-check is deemed to have +** passed. +*/ +static int fts3DoIntegrityCheck( + Fts3Table *p /* FTS3 table handle */ +){ + int rc; + int bOk = 0; + rc = fts3IntegrityCheck(p, &bOk); + if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB; + return rc; +} + +/* +** Handle a 'special' INSERT of the form: +** +** "INSERT INTO tbl(tbl) VALUES()" +** +** Argument pVal contains the result of . Currently the only +** meaningful value to insert is the text 'optimize'. +*/ +static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){ + int rc; /* Return Code */ + const char *zVal = (const char *)sqlite3_value_text(pVal); + int nVal = sqlite3_value_bytes(pVal); + + if( !zVal ){ + return SQLITE_NOMEM; + }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){ + rc = fts3DoOptimize(p, 0); + }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){ + rc = fts3DoRebuild(p); + }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){ + rc = fts3DoIntegrityCheck(p); + }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){ + rc = fts3DoIncrmerge(p, &zVal[6]); + }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){ + rc = fts3DoAutoincrmerge(p, &zVal[10]); +#ifdef SQLITE_TEST + }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){ + p->nNodeSize = atoi(&zVal[9]); + rc = SQLITE_OK; + }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ + p->nMaxPendingData = atoi(&zVal[11]); + rc = SQLITE_OK; + }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){ + p->bNoIncrDoclist = atoi(&zVal[21]); + rc = SQLITE_OK; +#endif + }else{ + rc = SQLITE_ERROR; + } + + return rc; +} + +#ifndef SQLITE_DISABLE_FTS4_DEFERRED +/* +** Delete all cached deferred doclists. Deferred doclists are cached +** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function. +*/ +void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){ + Fts3DeferredToken *pDef; + for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){ + fts3PendingListDelete(pDef->pList); + pDef->pList = 0; + } +} + +/* +** Free all entries in the pCsr->pDeffered list. Entries are added to +** this list using sqlite3Fts3DeferToken(). +*/ +void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){ + Fts3DeferredToken *pDef; + Fts3DeferredToken *pNext; + for(pDef=pCsr->pDeferred; pDef; pDef=pNext){ + pNext = pDef->pNext; + fts3PendingListDelete(pDef->pList); + sqlite3_free(pDef); + } + pCsr->pDeferred = 0; +} + +/* +** Generate deferred-doclists for all tokens in the pCsr->pDeferred list +** based on the row that pCsr currently points to. +** +** A deferred-doclist is like any other doclist with position information +** included, except that it only contains entries for a single row of the +** table, not for all rows. +*/ +int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){ + int rc = SQLITE_OK; /* Return code */ + if( pCsr->pDeferred ){ + int i; /* Used to iterate through table columns */ + sqlite3_int64 iDocid; /* Docid of the row pCsr points to */ + Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */ + + Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; + sqlite3_tokenizer *pT = p->pTokenizer; + sqlite3_tokenizer_module const *pModule = pT->pModule; + + assert( pCsr->isRequireSeek==0 ); + iDocid = sqlite3_column_int64(pCsr->pStmt, 0); + + for(i=0; inColumn && rc==SQLITE_OK; i++){ + if( p->abNotindexed[i]==0 ){ + const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1); + sqlite3_tokenizer_cursor *pTC = 0; + + rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC); + while( rc==SQLITE_OK ){ + char const *zToken; /* Buffer containing token */ + int nToken = 0; /* Number of bytes in token */ + int iDum1 = 0, iDum2 = 0; /* Dummy variables */ + int iPos = 0; /* Position of token in zText */ + + rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos); + for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ + Fts3PhraseToken *pPT = pDef->pToken; + if( (pDef->iCol>=p->nColumn || pDef->iCol==i) + && (pPT->bFirst==0 || iPos==0) + && (pPT->n==nToken || (pPT->isPrefix && pPT->nz, pPT->n)) + ){ + fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc); + } + } + } + if( pTC ) pModule->xClose(pTC); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + } + } + + for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ + if( pDef->pList ){ + rc = fts3PendingListAppendVarint(&pDef->pList, 0); + } + } + } + + return rc; +} + +int sqlite3Fts3DeferredTokenList( + Fts3DeferredToken *p, + char **ppData, + int *pnData +){ + char *pRet; + int nSkip; + sqlite3_int64 dummy; + + *ppData = 0; + *pnData = 0; + + if( p->pList==0 ){ + return SQLITE_OK; + } + + pRet = (char *)sqlite3_malloc(p->pList->nData); + if( !pRet ) return SQLITE_NOMEM; + + nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy); + *pnData = p->pList->nData - nSkip; + *ppData = pRet; + + memcpy(pRet, &p->pList->aData[nSkip], *pnData); + return SQLITE_OK; +} + +/* +** Add an entry for token pToken to the pCsr->pDeferred list. +*/ +int sqlite3Fts3DeferToken( + Fts3Cursor *pCsr, /* Fts3 table cursor */ + Fts3PhraseToken *pToken, /* Token to defer */ + int iCol /* Column that token must appear in (or -1) */ +){ + Fts3DeferredToken *pDeferred; + pDeferred = sqlite3_malloc(sizeof(*pDeferred)); + if( !pDeferred ){ + return SQLITE_NOMEM; + } + memset(pDeferred, 0, sizeof(*pDeferred)); + pDeferred->pToken = pToken; + pDeferred->pNext = pCsr->pDeferred; + pDeferred->iCol = iCol; + pCsr->pDeferred = pDeferred; + + assert( pToken->pDeferred==0 ); + pToken->pDeferred = pDeferred; + + return SQLITE_OK; +} +#endif + +/* +** SQLite value pRowid contains the rowid of a row that may or may not be +** present in the FTS3 table. If it is, delete it and adjust the contents +** of subsiduary data structures accordingly. +*/ +static int fts3DeleteByRowid( + Fts3Table *p, + sqlite3_value *pRowid, + int *pnChng, /* IN/OUT: Decrement if row is deleted */ + u32 *aSzDel +){ + int rc = SQLITE_OK; /* Return code */ + int bFound = 0; /* True if *pRowid really is in the table */ + + fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound); + if( bFound && rc==SQLITE_OK ){ + int isEmpty = 0; /* Deleting *pRowid leaves the table empty */ + rc = fts3IsEmpty(p, pRowid, &isEmpty); + if( rc==SQLITE_OK ){ + if( isEmpty ){ + /* Deleting this row means the whole table is empty. In this case + ** delete the contents of all three tables and throw away any + ** data in the pendingTerms hash table. */ + rc = fts3DeleteAll(p, 1); + *pnChng = 0; + memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2); + }else{ + *pnChng = *pnChng - 1; + if( p->zContentTbl==0 ){ + fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid); + } + if( p->bHasDocsize ){ + fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid); + } + } + } + } + + return rc; +} + +/* +** This function does the work for the xUpdate method of FTS3 virtual +** tables. The schema of the virtual table being: +** +** CREATE TABLE ( +** , +**
HIDDEN, +** docid HIDDEN, +** HIDDEN +** ); +** +** +*/ +int sqlite3Fts3UpdateMethod( + sqlite3_vtab *pVtab, /* FTS3 vtab object */ + int nArg, /* Size of argument array */ + sqlite3_value **apVal, /* Array of arguments */ + sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ +){ + Fts3Table *p = (Fts3Table *)pVtab; + int rc = SQLITE_OK; /* Return Code */ + int isRemove = 0; /* True for an UPDATE or DELETE */ + u32 *aSzIns = 0; /* Sizes of inserted documents */ + u32 *aSzDel = 0; /* Sizes of deleted documents */ + int nChng = 0; /* Net change in number of documents */ + int bInsertDone = 0; + + assert( p->pSegments==0 ); + assert( + nArg==1 /* DELETE operations */ + || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */ + ); + + /* Check for a "special" INSERT operation. One of the form: + ** + ** INSERT INTO xyz(xyz) VALUES('command'); + */ + if( nArg>1 + && sqlite3_value_type(apVal[0])==SQLITE_NULL + && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL + ){ + rc = fts3SpecialInsert(p, apVal[p->nColumn+2]); + goto update_out; + } + + if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){ + rc = SQLITE_CONSTRAINT; + goto update_out; + } + + /* Allocate space to hold the change in document sizes */ + aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 ); + if( aSzDel==0 ){ + rc = SQLITE_NOMEM; + goto update_out; + } + aSzIns = &aSzDel[p->nColumn+1]; + memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2); + + rc = fts3Writelock(p); + if( rc!=SQLITE_OK ) goto update_out; + + /* If this is an INSERT operation, or an UPDATE that modifies the rowid + ** value, then this operation requires constraint handling. + ** + ** If the on-conflict mode is REPLACE, this means that the existing row + ** should be deleted from the database before inserting the new row. Or, + ** if the on-conflict mode is other than REPLACE, then this method must + ** detect the conflict and return SQLITE_CONSTRAINT before beginning to + ** modify the database file. + */ + if( nArg>1 && p->zContentTbl==0 ){ + /* Find the value object that holds the new rowid value. */ + sqlite3_value *pNewRowid = apVal[3+p->nColumn]; + if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){ + pNewRowid = apVal[1]; + } + + if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( + sqlite3_value_type(apVal[0])==SQLITE_NULL + || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid) + )){ + /* The new rowid is not NULL (in this case the rowid will be + ** automatically assigned and there is no chance of a conflict), and + ** the statement is either an INSERT or an UPDATE that modifies the + ** rowid column. So if the conflict mode is REPLACE, then delete any + ** existing row with rowid=pNewRowid. + ** + ** Or, if the conflict mode is not REPLACE, insert the new record into + ** the %_content table. If we hit the duplicate rowid constraint (or any + ** other error) while doing so, return immediately. + ** + ** This branch may also run if pNewRowid contains a value that cannot + ** be losslessly converted to an integer. In this case, the eventual + ** call to fts3InsertData() (either just below or further on in this + ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is + ** invoked, it will delete zero rows (since no row will have + ** docid=$pNewRowid if $pNewRowid is not an integer value). + */ + if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){ + rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel); + }else{ + rc = fts3InsertData(p, apVal, pRowid); + bInsertDone = 1; + } + } + } + if( rc!=SQLITE_OK ){ + goto update_out; + } + + /* If this is a DELETE or UPDATE operation, remove the old record. */ + if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ + assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER ); + rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel); + isRemove = 1; + } + + /* If this is an INSERT or UPDATE operation, insert the new record. */ + if( nArg>1 && rc==SQLITE_OK ){ + int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]); + if( bInsertDone==0 ){ + rc = fts3InsertData(p, apVal, pRowid); + if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){ + rc = FTS_CORRUPT_VTAB; + } + } + if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){ + rc = fts3PendingTermsDocid(p, iLangid, *pRowid); + } + if( rc==SQLITE_OK ){ + assert( p->iPrevDocid==*pRowid ); + rc = fts3InsertTerms(p, iLangid, apVal, aSzIns); + } + if( p->bHasDocsize ){ + fts3InsertDocsize(&rc, p, aSzIns); + } + nChng++; + } + + if( p->bFts4 ){ + fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng); + } + + update_out: + sqlite3_free(aSzDel); + sqlite3Fts3SegmentsClose(p); + return rc; +} + +/* +** Flush any data in the pending-terms hash table to disk. If successful, +** merge all segments in the database (including the new segment, if +** there was any data to flush) into a single segment. +*/ +int sqlite3Fts3Optimize(Fts3Table *p){ + int rc; + rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0); + if( rc==SQLITE_OK ){ + rc = fts3DoOptimize(p, 1); + if( rc==SQLITE_OK || rc==SQLITE_DONE ){ + int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); + if( rc2!=SQLITE_OK ) rc = rc2; + }else{ + sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0); + sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); + } + } + sqlite3Fts3SegmentsClose(p); + return rc; +} + +#endif diff --git a/components/external/SQLite-3.8.1/ext/fts3/fts3speed.tcl b/components/external/SQLite-3.8.1/ext/fts3/fts3speed.tcl new file mode 100644 index 0000000000000000000000000000000000000000..377cb196065699557b0a035a1e9d74808321187a --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/fts3speed.tcl @@ -0,0 +1,122 @@ + + +#-------------------------------------------------------------------------- +# This script contains several sub-programs used to test FTS3/FTS4 +# performance. It does not run the queries directly, but generates SQL +# scripts that can be run using the shell tool. +# +# The following cases are tested: +# +# 1. Inserting documents into an FTS3 table. +# 2. Optimizing an FTS3 table (i.e. "INSERT INTO t1 VALUES('optimize')"). +# 3. Deleting documents from an FTS3 table. +# 4. Querying FTS3 tables. +# + +# Number of tokens in vocabulary. And number of tokens in each document. +# +set VOCAB_SIZE 2000 +set DOC_SIZE 100 + +set NUM_INSERTS 100000 +set NUM_SELECTS 1000 + +# Force everything in this script to be deterministic. +# +expr {srand(0)} + +proc usage {} { + puts stderr "Usage: $::argv0 " + exit -1 +} + +proc sql {sql} { + puts $::fd $sql +} + + +# Return a list of $nWord randomly generated tokens each between 2 and 10 +# characters in length. +# +proc build_vocab {nWord} { + set ret [list] + set chars [list a b c d e f g h i j k l m n o p q r s t u v w x y z] + for {set i 0} {$i<$nWord} {incr i} { + set len [expr {int((rand()*9.0)+2)}] + set term "" + for {set j 0} {$j<$len} {incr j} { + append term [lindex $chars [expr {int(rand()*[llength $chars])}]] + } + lappend ret $term + } + set ret +} + +proc select_term {} { + set n [llength $::vocab] + set t [expr int(rand()*$n*3)] + if {$t>=2*$n} { set t [expr {($t-2*$n)/100}] } + if {$t>=$n} { set t [expr {($t-$n)/10}] } + lindex $::vocab $t +} + +proc select_doc {nTerm} { + set ret [list] + for {set i 0} {$i<$nTerm} {incr i} { + lappend ret [select_term] + } + set ret +} + +proc test_1 {nInsert} { + sql "PRAGMA synchronous = OFF;" + sql "DROP TABLE IF EXISTS t1;" + sql "CREATE VIRTUAL TABLE t1 USING fts4;" + for {set i 0} {$i < $nInsert} {incr i} { + set doc [select_doc $::DOC_SIZE] + sql "INSERT INTO t1 VALUES('$doc');" + } +} + +proc test_2 {} { + sql "INSERT INTO t1(t1) VALUES('optimize');" +} + +proc test_3 {nSelect} { + for {set i 0} {$i < $nSelect} {incr i} { + sql "SELECT count(*) FROM t1 WHERE t1 MATCH '[select_term]';" + } +} + +proc test_4 {nSelect} { + for {set i 0} {$i < $nSelect} {incr i} { + sql "SELECT count(*) FROM t1 WHERE t1 MATCH '[select_term] [select_term]';" + } +} + +if {[llength $argv]!=0} usage + +set ::vocab [build_vocab $::VOCAB_SIZE] + +set ::fd [open fts3speed_insert.sql w] +test_1 $NUM_INSERTS +close $::fd + +set ::fd [open fts3speed_select.sql w] +test_3 $NUM_SELECTS +close $::fd + +set ::fd [open fts3speed_select2.sql w] +test_4 $NUM_SELECTS +close $::fd + +set ::fd [open fts3speed_optimize.sql w] +test_2 +close $::fd + +puts "Success. Created files:" +puts " fts3speed_insert.sql" +puts " fts3speed_select.sql" +puts " fts3speed_select2.sql" +puts " fts3speed_optimize.sql" + diff --git a/components/external/SQLite-3.8.1/ext/fts3/mkfts3amal.tcl b/components/external/SQLite-3.8.1/ext/fts3/mkfts3amal.tcl new file mode 100644 index 0000000000000000000000000000000000000000..059048717f9b3ca410905eda9fe0ef2a84c99243 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/mkfts3amal.tcl @@ -0,0 +1,115 @@ +#!/usr/bin/tclsh +# +# This script builds a single C code file holding all of FTS3 code. +# The name of the output file is fts3amal.c. To build this file, +# first do: +# +# make target_source +# +# The make target above moves all of the source code files into +# a subdirectory named "tsrc". (This script expects to find the files +# there and will not work if they are not found.) +# +# After the "tsrc" directory has been created and populated, run +# this script: +# +# tclsh mkfts3amal.tcl +# +# The amalgamated FTS3 code will be written into fts3amal.c +# + +# Open the output file and write a header comment at the beginning +# of the file. +# +set out [open fts3amal.c w] +set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1] +puts $out [subst \ +{/****************************************************************************** +** This file is an amalgamation of separate C source files from the SQLite +** Full Text Search extension 2 (fts3). By combining all the individual C +** code files into this single large file, the entire code can be compiled +** as a one translation unit. This allows many compilers to do optimizations +** that would not be possible if the files were compiled separately. It also +** makes the code easier to import into other projects. +** +** This amalgamation was generated on $today. +*/}] + +# These are the header files used by FTS3. The first time any of these +# files are seen in a #include statement in the C code, include the complete +# text of the file in-line. The file only needs to be included once. +# +foreach hdr { + fts3.h + fts3_hash.h + fts3_tokenizer.h + sqlite3.h + sqlite3ext.h +} { + set available_hdr($hdr) 1 +} + +# 78 stars used for comment formatting. +set s78 \ +{*****************************************************************************} + +# Insert a comment into the code +# +proc section_comment {text} { + global out s78 + set n [string length $text] + set nstar [expr {60 - $n}] + set stars [string range $s78 0 $nstar] + puts $out "/************** $text $stars/" +} + +# Read the source file named $filename and write it into the +# sqlite3.c output file. If any #include statements are seen, +# process them approprately. +# +proc copy_file {filename} { + global seen_hdr available_hdr out + set tail [file tail $filename] + section_comment "Begin file $tail" + set in [open $filename r] + while {![eof $in]} { + set line [gets $in] + if {[regexp {^#\s*include\s+["<]([^">]+)[">]} $line all hdr]} { + if {[info exists available_hdr($hdr)]} { + if {$available_hdr($hdr)} { + section_comment "Include $hdr in the middle of $tail" + copy_file tsrc/$hdr + section_comment "Continuing where we left off in $tail" + } + } elseif {![info exists seen_hdr($hdr)]} { + set seen_hdr($hdr) 1 + puts $out $line + } + } elseif {[regexp {^#ifdef __cplusplus} $line]} { + puts $out "#if 0" + } elseif {[regexp {^#line} $line]} { + # Skip #line directives. + } else { + puts $out $line + } + } + close $in + section_comment "End of $tail" +} + + +# Process the source files. Process files containing commonly +# used subroutines first in order to help the compiler find +# inlining opportunities. +# +foreach file { + fts3.c + fts3_hash.c + fts3_porter.c + fts3_tokenizer.c + fts3_tokenizer1.c +} { + copy_file tsrc/$file +} + +close $out diff --git a/components/external/SQLite-3.8.1/ext/fts3/tool/fts3view.c b/components/external/SQLite-3.8.1/ext/fts3/tool/fts3view.c new file mode 100644 index 0000000000000000000000000000000000000000..479ae9868d4fe6f68cdda45d1c439a90ab6caeec --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/tool/fts3view.c @@ -0,0 +1,874 @@ +/* +** This program is a debugging and analysis utility that displays +** information about an FTS3 or FTS4 index. +** +** Link this program against the SQLite3 amalgamation with the +** SQLITE_ENABLE_FTS4 compile-time option. Then run it as: +** +** fts3view DATABASE +** +** to get a list of all FTS3/4 tables in DATABASE, or do +** +** fts3view DATABASE TABLE COMMAND .... +** +** to see various aspects of the TABLE table. Type fts3view with no +** arguments for a list of available COMMANDs. +*/ +#include +#include +#include +#include +#include +#include "sqlite3.h" + +/* +** Extra command-line arguments: +*/ +int nExtra; +char **azExtra; + +/* +** Look for a command-line argument. +*/ +const char *findOption(const char *zName, int hasArg, const char *zDefault){ + int i; + const char *zResult = zDefault; + for(i=0; i=2000 ){ + n = 0; + pStmt = prepare(db, "SELECT count(*) FROM %s" + " WHERE col='*' AND occurrences<=%d", zAux, nDoc/1000); + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + n = sqlite3_column_int(pStmt, 0); + } + sqlite3_finalize(pStmt); + printf("Tokens used in 0.1%% or less of docs...... %9d %5.2f%%\n", + n, n*100.0/nToken); + } + + if( nDoc>=200 ){ + n = 0; + pStmt = prepare(db, "SELECT count(*) FROM %s" + " WHERE col='*' AND occurrences<=%d", zAux, nDoc/100); + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + n = sqlite3_column_int(pStmt, 0); + } + sqlite3_finalize(pStmt); + printf("Tokens used in 1%% or less of docs........ %9d %5.2f%%\n", + n, n*100.0/nToken); + } + + nTop = atoi(findOption("top", 1, "25")); + printf("The %d most common tokens:\n", nTop); + pStmt = prepare(db, + "SELECT term, documents FROM %s" + " WHERE col='*'" + " ORDER BY documents DESC, term" + " LIMIT %d", zAux, nTop); + i = 0; + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + i++; + n = sqlite3_column_int(pStmt, 1); + printf(" %2d. %-30s %9d docs %5.2f%%\n", i, + sqlite3_column_text(pStmt, 0), n, n*100.0/nDoc); + } + sqlite3_finalize(pStmt); + +end_vocab: + runSql(db, "ROLLBACK"); + sqlite3_free(zAux); +} + +/* +** Report on the number and sizes of segments +*/ +static void showSegmentStats(sqlite3 *db, const char *zTab){ + sqlite3_stmt *pStmt; + int nSeg = 0; + sqlite3_int64 szSeg = 0, mxSeg = 0; + int nIdx = 0; + sqlite3_int64 szIdx = 0, mxIdx = 0; + int nRoot = 0; + sqlite3_int64 szRoot = 0, mxRoot = 0; + sqlite3_int64 mx; + int nLeaf; + int n; + int pgsz; + int mxLevel; + int i; + + pStmt = prepare(db, + "SELECT count(*), sum(length(block)), max(length(block))" + " FROM '%q_segments'", + zTab); + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + nSeg = sqlite3_column_int(pStmt, 0); + szSeg = sqlite3_column_int64(pStmt, 1); + mxSeg = sqlite3_column_int64(pStmt, 2); + } + sqlite3_finalize(pStmt); + pStmt = prepare(db, + "SELECT count(*), sum(length(block)), max(length(block))" + " FROM '%q_segments' a JOIN '%q_segdir' b" + " WHERE a.blockid BETWEEN b.leaves_end_block+1 AND b.end_block", + zTab, zTab); + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + nIdx = sqlite3_column_int(pStmt, 0); + szIdx = sqlite3_column_int64(pStmt, 1); + mxIdx = sqlite3_column_int64(pStmt, 2); + } + sqlite3_finalize(pStmt); + pStmt = prepare(db, + "SELECT count(*), sum(length(root)), max(length(root))" + " FROM '%q_segdir'", + zTab); + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + nRoot = sqlite3_column_int(pStmt, 0); + szRoot = sqlite3_column_int64(pStmt, 1); + mxRoot = sqlite3_column_int64(pStmt, 2); + } + sqlite3_finalize(pStmt); + + printf("Number of segments....................... %9d\n", nSeg+nRoot); + printf("Number of leaf segments.................. %9d\n", nSeg-nIdx); + printf("Number of index segments................. %9d\n", nIdx); + printf("Number of root segments.................. %9d\n", nRoot); + printf("Total size of all segments............... %9lld\n", szSeg+szRoot); + printf("Total size of all leaf segments.......... %9lld\n", szSeg-szIdx); + printf("Total size of all index segments......... %9lld\n", szIdx); + printf("Total size of all root segments.......... %9lld\n", szRoot); + if( nSeg>0 ){ + printf("Average size of all segments............. %11.1f\n", + (double)(szSeg+szRoot)/(double)(nSeg+nRoot)); + printf("Average size of leaf segments............ %11.1f\n", + (double)(szSeg-szIdx)/(double)(nSeg-nIdx)); + } + if( nIdx>0 ){ + printf("Average size of index segments........... %11.1f\n", + (double)szIdx/(double)nIdx); + } + if( nRoot>0 ){ + printf("Average size of root segments............ %11.1f\n", + (double)szRoot/(double)nRoot); + } + mx = mxSeg; + if( mx%d", + zTab, zTab, pgsz-45); + n = 0; + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + n = sqlite3_column_int(pStmt, 0); + } + sqlite3_finalize(pStmt); + nLeaf = nSeg - nIdx; + printf("Leaf segments larger than %5d bytes.... %9d %5.2f%%\n", + pgsz-45, n, n*100.0/nLeaf); + + pStmt = prepare(db, "SELECT max(level%%1024) FROM '%q_segdir'", zTab); + mxLevel = 0; + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + mxLevel = sqlite3_column_int(pStmt, 0); + } + sqlite3_finalize(pStmt); + + for(i=0; i<=mxLevel; i++){ + pStmt = prepare(db, + "SELECT count(*), sum(len), avg(len), max(len), sum(len>%d)," + " count(distinct idx)" + " FROM (SELECT length(a.block) AS len, idx" + " FROM '%q_segments' a JOIN '%q_segdir' b" + " WHERE (a.blockid BETWEEN b.start_block" + " AND b.leaves_end_block)" + " AND (b.level%%1024)==%d)", + pgsz-45, zTab, zTab, i); + if( sqlite3_step(pStmt)==SQLITE_ROW + && (nLeaf = sqlite3_column_int(pStmt, 0))>0 + ){ + int nIdx = sqlite3_column_int(pStmt, 5); + sqlite3_int64 sz; + printf("For level %d:\n", i); + printf(" Number of indexes...................... %9d\n", nIdx); + printf(" Number of leaf segments................ %9d\n", nLeaf); + if( nIdx>1 ){ + printf(" Average leaf segments per index........ %11.1f\n", + (double)nLeaf/(double)nIdx); + } + printf(" Total size of all leaf segments........ %9lld\n", + (sz = sqlite3_column_int64(pStmt, 1))); + printf(" Average size of leaf segments.......... %11.1f\n", + sqlite3_column_double(pStmt, 2)); + if( nIdx>1 ){ + printf(" Average leaf segment size per index.... %11.1f\n", + (double)sz/(double)nIdx); + } + printf(" Maximum leaf segment size.............. %9lld\n", + sqlite3_column_int64(pStmt, 3)); + n = sqlite3_column_int(pStmt, 4); + printf(" Leaf segments larger than %5d bytes.. %9d %5.2f%%\n", + pgsz-45, n, n*100.0/nLeaf); + } + sqlite3_finalize(pStmt); + } +} + +/* +** Print a single "tree" line of the segdir map output. +*/ +static void printTreeLine(sqlite3_int64 iLower, sqlite3_int64 iUpper){ + printf(" tree %9lld", iLower); + if( iUpper>iLower ){ + printf(" thru %9lld (%lld blocks)", iUpper, iUpper-iLower+1); + } + printf("\n"); +} + +/* +** Check to see if the block of a %_segments entry is NULL. +*/ +static int isNullSegment(sqlite3 *db, const char *zTab, sqlite3_int64 iBlockId){ + sqlite3_stmt *pStmt; + int rc = 1; + + pStmt = prepare(db, "SELECT block IS NULL FROM '%q_segments'" + " WHERE blockid=%lld", zTab, iBlockId); + if( sqlite3_step(pStmt)==SQLITE_ROW ){ + rc = sqlite3_column_int(pStmt, 0); + } + sqlite3_finalize(pStmt); + return rc; +} + +/* +** Show a map of segments derived from the %_segdir table. +*/ +static void showSegdirMap(sqlite3 *db, const char *zTab){ + int mxIndex, iIndex; + sqlite3_stmt *pStmt = 0; + sqlite3_stmt *pStmt2 = 0; + int prevLevel; + + pStmt = prepare(db, "SELECT max(level/1024) FROM '%q_segdir'", zTab); + if( sqlite3_step(pStmt)==SQLITE_ROW ){ + mxIndex = sqlite3_column_int(pStmt, 0); + }else{ + mxIndex = 0; + } + sqlite3_finalize(pStmt); + + printf("Number of inverted indices............... %3d\n", mxIndex+1); + pStmt = prepare(db, + "SELECT level, idx, start_block, leaves_end_block, end_block, rowid" + " FROM '%q_segdir'" + " WHERE level/1024==?" + " ORDER BY level DESC, idx", + zTab); + pStmt2 = prepare(db, + "SELECT blockid FROM '%q_segments'" + " WHERE blockid BETWEEN ? AND ? ORDER BY blockid", + zTab); + for(iIndex=0; iIndex<=mxIndex; iIndex++){ + if( mxIndex>0 ){ + printf("**************************** Index %d " + "****************************\n", iIndex); + } + sqlite3_bind_int(pStmt, 1, iIndex); + prevLevel = -1; + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + int iLevel = sqlite3_column_int(pStmt, 0)%1024; + int iIdx = sqlite3_column_int(pStmt, 1); + sqlite3_int64 iStart = sqlite3_column_int64(pStmt, 2); + sqlite3_int64 iLEnd = sqlite3_column_int64(pStmt, 3); + sqlite3_int64 iEnd = sqlite3_column_int64(pStmt, 4); + char rtag[20]; + if( iLevel!=prevLevel ){ + printf("level %2d idx %2d", iLevel, iIdx); + prevLevel = iLevel; + }else{ + printf(" idx %2d", iIdx); + } + sqlite3_snprintf(sizeof(rtag), rtag, "r%lld", + sqlite3_column_int64(pStmt,5)); + printf(" root %9s\n", rtag); + if( iLEnd>iStart ){ + sqlite3_int64 iLower, iPrev, iX; + if( iLEnd+1<=iEnd ){ + sqlite3_bind_int64(pStmt2, 1, iLEnd+1); + sqlite3_bind_int64(pStmt2, 2, iEnd); + iLower = -1; + while( sqlite3_step(pStmt2)==SQLITE_ROW ){ + iX = sqlite3_column_int64(pStmt2, 0); + if( iLower<0 ){ + iLower = iPrev = iX; + }else if( iX==iPrev+1 ){ + iPrev = iX; + }else{ + printTreeLine(iLower, iPrev); + iLower = iPrev = iX; + } + } + sqlite3_reset(pStmt2); + if( iLower>=0 ){ + if( iLower==iPrev && iLower==iEnd + && isNullSegment(db,zTab,iLower) + ){ + printf(" null %9lld\n", iLower); + }else{ + printTreeLine(iLower, iPrev); + } + } + } + printf(" leaves %9lld thru %9lld (%lld blocks)\n", + iStart, iLEnd, iLEnd - iStart + 1); + } + } + sqlite3_reset(pStmt); + } + sqlite3_finalize(pStmt); + sqlite3_finalize(pStmt2); +} + +/* +** Decode a single segment block and display the results on stdout. +*/ +static void decodeSegment( + const unsigned char *aData, /* Content to print */ + int nData /* Number of bytes of content */ +){ + sqlite3_int64 iChild; + sqlite3_int64 iPrefix; + sqlite3_int64 nTerm; + sqlite3_int64 n; + sqlite3_int64 iDocsz; + int iHeight; + int i = 0; + int cnt = 0; + char zTerm[1000]; + + i += getVarint(aData, &n); + iHeight = (int)n; + printf("height: %d\n", iHeight); + if( iHeight>0 ){ + i += getVarint(aData+i, &iChild); + printf("left-child: %lld\n", iChild); + } + while( i0 ){ + i += getVarint(aData+i, &iPrefix); + }else{ + iPrefix = 0; + } + i += getVarint(aData+i, &nTerm); + if( iPrefix+nTerm+1 >= sizeof(zTerm) ){ + fprintf(stderr, "term to long\n"); + exit(1); + } + memcpy(zTerm+iPrefix, aData+i, nTerm); + zTerm[iPrefix+nTerm] = 0; + i += nTerm; + if( iHeight==0 ){ + i += getVarint(aData+i, &iDocsz); + printf("term: %-25s doclist %7lld bytes offset %d\n", zTerm, iDocsz, i); + i += iDocsz; + }else{ + printf("term: %-25s child %lld\n", zTerm, ++iChild); + } + } +} + + +/* +** Print a a blob as hex and ascii. +*/ +static void printBlob( + const unsigned char *aData, /* Content to print */ + int nData /* Number of bytes of content */ +){ + int i, j; + const char *zOfstFmt; + const int perLine = 16; + + if( (nData&~0xfff)==0 ){ + zOfstFmt = " %03x: "; + }else if( (nData&~0xffff)==0 ){ + zOfstFmt = " %04x: "; + }else if( (nData&~0xfffff)==0 ){ + zOfstFmt = " %05x: "; + }else if( (nData&~0xffffff)==0 ){ + zOfstFmt = " %06x: "; + }else{ + zOfstFmt = " %08x: "; + } + + for(i=0; inData ){ + fprintf(stdout, " "); + }else{ + fprintf(stdout,"%02x ", aData[i+j]); + } + } + for(j=0; jnData ){ + fprintf(stdout, " "); + }else{ + fprintf(stdout,"%c", isprint(aData[i+j]) ? aData[i+j] : '.'); + } + } + fprintf(stdout,"\n"); + } +} + +/* +** Convert text to a 64-bit integer +*/ +static sqlite3_int64 atoi64(const char *z){ + sqlite3_int64 v = 0; + while( z[0]>='0' && z[0]<='9' ){ + v = v*10 + z[0] - '0'; + z++; + } + return v; +} + +/* +** Return a prepared statement which, when stepped, will return in its +** first column the blob associated with segment zId. If zId begins with +** 'r' then it is a rowid of a %_segdir entry. Otherwise it is a +** %_segment entry. +*/ +static sqlite3_stmt *prepareToGetSegment( + sqlite3 *db, /* The database */ + const char *zTab, /* The FTS3/4 table name */ + const char *zId /* ID of the segment to open */ +){ + sqlite3_stmt *pStmt; + if( zId[0]=='r' ){ + pStmt = prepare(db, "SELECT root FROM '%q_segdir' WHERE rowid=%lld", + zTab, atoi64(zId+1)); + }else{ + pStmt = prepare(db, "SELECT block FROM '%q_segments' WHERE blockid=%lld", + zTab, atoi64(zId)); + } + return pStmt; +} + +/* +** Print the content of a segment or of the root of a segdir. The segment +** or root is identified by azExtra[0]. If the first character of azExtra[0] +** is 'r' then the remainder is the integer rowid of the %_segdir entry. +** If the first character of azExtra[0] is not 'r' then, then all of +** azExtra[0] is an integer which is the block number. +** +** If the --raw option is present in azExtra, then a hex dump is provided. +** Otherwise a decoding is shown. +*/ +static void showSegment(sqlite3 *db, const char *zTab){ + const unsigned char *aData; + int nData; + sqlite3_stmt *pStmt; + + pStmt = prepareToGetSegment(db, zTab, azExtra[0]); + if( sqlite3_step(pStmt)!=SQLITE_ROW ){ + sqlite3_finalize(pStmt); + return; + } + nData = sqlite3_column_bytes(pStmt, 0); + aData = sqlite3_column_blob(pStmt, 0); + printf("Segment %s of size %d bytes:\n", azExtra[0], nData); + if( findOption("raw", 0, 0)!=0 ){ + printBlob(aData, nData); + }else{ + decodeSegment(aData, nData); + } + sqlite3_finalize(pStmt); +} + +/* +** Decode a single doclist and display the results on stdout. +*/ +static void decodeDoclist( + const unsigned char *aData, /* Content to print */ + int nData /* Number of bytes of content */ +){ + sqlite3_int64 iPrevDocid = 0; + sqlite3_int64 iDocid; + sqlite3_int64 iPos; + sqlite3_int64 iPrevPos = 0; + sqlite3_int64 iCol; + int i = 0; + + while( i; ; ; # +# +# The status field is: +# C: common case folding, common mappings shared by both simple and full mappings. +# F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. +# S: simple case folding, mappings to single characters where different from F. +# T: special case for uppercase I and dotted uppercase I +# - For non-Turkic languages, this mapping is normally not used. +# - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. +# Note that the Turkic mappings do not maintain canonical equivalence without additional processing. +# See the discussions of case mapping in the Unicode Standard for more information. +# +# Usage: +# A. To do a simple case folding, use the mappings with status C + S. +# B. To do a full case folding, use the mappings with status C + F. +# +# The mappings with status T can be used or omitted depending on the desired case-folding +# behavior. (The default option is to exclude them.) +# +# ================================================================= + +# Property: Case_Folding + +# All code points not explicitly listed for Case_Folding +# have the value C for the status field, and the code point itself for the mapping field. + +# @missing: 0000..10FFFF; C; + +# ================================================================= +0041; C; 0061; # LATIN CAPITAL LETTER A +0042; C; 0062; # LATIN CAPITAL LETTER B +0043; C; 0063; # LATIN CAPITAL LETTER C +0044; C; 0064; # LATIN CAPITAL LETTER D +0045; C; 0065; # LATIN CAPITAL LETTER E +0046; C; 0066; # LATIN CAPITAL LETTER F +0047; C; 0067; # LATIN CAPITAL LETTER G +0048; C; 0068; # LATIN CAPITAL LETTER H +0049; C; 0069; # LATIN CAPITAL LETTER I +0049; T; 0131; # LATIN CAPITAL LETTER I +004A; C; 006A; # LATIN CAPITAL LETTER J +004B; C; 006B; # LATIN CAPITAL LETTER K +004C; C; 006C; # LATIN CAPITAL LETTER L +004D; C; 006D; # LATIN CAPITAL LETTER M +004E; C; 006E; # LATIN CAPITAL LETTER N +004F; C; 006F; # LATIN CAPITAL LETTER O +0050; C; 0070; # LATIN CAPITAL LETTER P +0051; C; 0071; # LATIN CAPITAL LETTER Q +0052; C; 0072; # LATIN CAPITAL LETTER R +0053; C; 0073; # LATIN CAPITAL LETTER S +0054; C; 0074; # LATIN CAPITAL LETTER T +0055; C; 0075; # LATIN CAPITAL LETTER U +0056; C; 0076; # LATIN CAPITAL LETTER V +0057; C; 0077; # LATIN CAPITAL LETTER W +0058; C; 0078; # LATIN CAPITAL LETTER X +0059; C; 0079; # LATIN CAPITAL LETTER Y +005A; C; 007A; # LATIN CAPITAL LETTER Z +00B5; C; 03BC; # MICRO SIGN +00C0; C; 00E0; # LATIN CAPITAL LETTER A WITH GRAVE +00C1; C; 00E1; # LATIN CAPITAL LETTER A WITH ACUTE +00C2; C; 00E2; # LATIN CAPITAL LETTER A WITH CIRCUMFLEX +00C3; C; 00E3; # LATIN CAPITAL LETTER A WITH TILDE +00C4; C; 00E4; # LATIN CAPITAL LETTER A WITH DIAERESIS +00C5; C; 00E5; # LATIN CAPITAL LETTER A WITH RING ABOVE +00C6; C; 00E6; # LATIN CAPITAL LETTER AE +00C7; C; 00E7; # LATIN CAPITAL LETTER C WITH CEDILLA +00C8; C; 00E8; # LATIN CAPITAL LETTER E WITH GRAVE +00C9; C; 00E9; # LATIN CAPITAL LETTER E WITH ACUTE +00CA; C; 00EA; # LATIN CAPITAL LETTER E WITH CIRCUMFLEX +00CB; C; 00EB; # LATIN CAPITAL LETTER E WITH DIAERESIS +00CC; C; 00EC; # LATIN CAPITAL LETTER I WITH GRAVE +00CD; C; 00ED; # LATIN CAPITAL LETTER I WITH ACUTE +00CE; C; 00EE; # LATIN CAPITAL LETTER I WITH CIRCUMFLEX +00CF; C; 00EF; # LATIN CAPITAL LETTER I WITH DIAERESIS +00D0; C; 00F0; # LATIN CAPITAL LETTER ETH +00D1; C; 00F1; # LATIN CAPITAL LETTER N WITH TILDE +00D2; C; 00F2; # LATIN CAPITAL LETTER O WITH GRAVE +00D3; C; 00F3; # LATIN CAPITAL LETTER O WITH ACUTE +00D4; C; 00F4; # LATIN CAPITAL LETTER O WITH CIRCUMFLEX +00D5; C; 00F5; # LATIN CAPITAL LETTER O WITH TILDE +00D6; C; 00F6; # LATIN CAPITAL LETTER O WITH DIAERESIS +00D8; C; 00F8; # LATIN CAPITAL LETTER O WITH STROKE +00D9; C; 00F9; # LATIN CAPITAL LETTER U WITH GRAVE +00DA; C; 00FA; # LATIN CAPITAL LETTER U WITH ACUTE +00DB; C; 00FB; # LATIN CAPITAL LETTER U WITH CIRCUMFLEX +00DC; C; 00FC; # LATIN CAPITAL LETTER U WITH DIAERESIS +00DD; C; 00FD; # LATIN CAPITAL LETTER Y WITH ACUTE +00DE; C; 00FE; # LATIN CAPITAL LETTER THORN +00DF; F; 0073 0073; # LATIN SMALL LETTER SHARP S +0100; C; 0101; # LATIN CAPITAL LETTER A WITH MACRON +0102; C; 0103; # LATIN CAPITAL LETTER A WITH BREVE +0104; C; 0105; # LATIN CAPITAL LETTER A WITH OGONEK +0106; C; 0107; # LATIN CAPITAL LETTER C WITH ACUTE +0108; C; 0109; # LATIN CAPITAL LETTER C WITH CIRCUMFLEX +010A; C; 010B; # LATIN CAPITAL LETTER C WITH DOT ABOVE +010C; C; 010D; # LATIN CAPITAL LETTER C WITH CARON +010E; C; 010F; # LATIN CAPITAL LETTER D WITH CARON +0110; C; 0111; # LATIN CAPITAL LETTER D WITH STROKE +0112; C; 0113; # LATIN CAPITAL LETTER E WITH MACRON +0114; C; 0115; # LATIN CAPITAL LETTER E WITH BREVE +0116; C; 0117; # LATIN CAPITAL LETTER E WITH DOT ABOVE +0118; C; 0119; # LATIN CAPITAL LETTER E WITH OGONEK +011A; C; 011B; # LATIN CAPITAL LETTER E WITH CARON +011C; C; 011D; # LATIN CAPITAL LETTER G WITH CIRCUMFLEX +011E; C; 011F; # LATIN CAPITAL LETTER G WITH BREVE +0120; C; 0121; # LATIN CAPITAL LETTER G WITH DOT ABOVE +0122; C; 0123; # LATIN CAPITAL LETTER G WITH CEDILLA +0124; C; 0125; # LATIN CAPITAL LETTER H WITH CIRCUMFLEX +0126; C; 0127; # LATIN CAPITAL LETTER H WITH STROKE +0128; C; 0129; # LATIN CAPITAL LETTER I WITH TILDE +012A; C; 012B; # LATIN CAPITAL LETTER I WITH MACRON +012C; C; 012D; # LATIN CAPITAL LETTER I WITH BREVE +012E; C; 012F; # LATIN CAPITAL LETTER I WITH OGONEK +0130; F; 0069 0307; # LATIN CAPITAL LETTER I WITH DOT ABOVE +0130; T; 0069; # LATIN CAPITAL LETTER I WITH DOT ABOVE +0132; C; 0133; # LATIN CAPITAL LIGATURE IJ +0134; C; 0135; # LATIN CAPITAL LETTER J WITH CIRCUMFLEX +0136; C; 0137; # LATIN CAPITAL LETTER K WITH CEDILLA +0139; C; 013A; # LATIN CAPITAL LETTER L WITH ACUTE +013B; C; 013C; # LATIN CAPITAL LETTER L WITH CEDILLA +013D; C; 013E; # LATIN CAPITAL LETTER L WITH CARON +013F; C; 0140; # LATIN CAPITAL LETTER L WITH MIDDLE DOT +0141; C; 0142; # LATIN CAPITAL LETTER L WITH STROKE +0143; C; 0144; # LATIN CAPITAL LETTER N WITH ACUTE +0145; C; 0146; # LATIN CAPITAL LETTER N WITH CEDILLA +0147; C; 0148; # LATIN CAPITAL LETTER N WITH CARON +0149; F; 02BC 006E; # LATIN SMALL LETTER N PRECEDED BY APOSTROPHE +014A; C; 014B; # LATIN CAPITAL LETTER ENG +014C; C; 014D; # LATIN CAPITAL LETTER O WITH MACRON +014E; C; 014F; # LATIN CAPITAL LETTER O WITH BREVE +0150; C; 0151; # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE +0152; C; 0153; # LATIN CAPITAL LIGATURE OE +0154; C; 0155; # LATIN CAPITAL LETTER R WITH ACUTE +0156; C; 0157; # LATIN CAPITAL LETTER R WITH CEDILLA +0158; C; 0159; # LATIN CAPITAL LETTER R WITH CARON +015A; C; 015B; # LATIN CAPITAL LETTER S WITH ACUTE +015C; C; 015D; # LATIN CAPITAL LETTER S WITH CIRCUMFLEX +015E; C; 015F; # LATIN CAPITAL LETTER S WITH CEDILLA +0160; C; 0161; # LATIN CAPITAL LETTER S WITH CARON +0162; C; 0163; # LATIN CAPITAL LETTER T WITH CEDILLA +0164; C; 0165; # LATIN CAPITAL LETTER T WITH CARON +0166; C; 0167; # LATIN CAPITAL LETTER T WITH STROKE +0168; C; 0169; # LATIN CAPITAL LETTER U WITH TILDE +016A; C; 016B; # LATIN CAPITAL LETTER U WITH MACRON +016C; C; 016D; # LATIN CAPITAL LETTER U WITH BREVE +016E; C; 016F; # LATIN CAPITAL LETTER U WITH RING ABOVE +0170; C; 0171; # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE +0172; C; 0173; # LATIN CAPITAL LETTER U WITH OGONEK +0174; C; 0175; # LATIN CAPITAL LETTER W WITH CIRCUMFLEX +0176; C; 0177; # LATIN CAPITAL LETTER Y WITH CIRCUMFLEX +0178; C; 00FF; # LATIN CAPITAL LETTER Y WITH DIAERESIS +0179; C; 017A; # LATIN CAPITAL LETTER Z WITH ACUTE +017B; C; 017C; # LATIN CAPITAL LETTER Z WITH DOT ABOVE +017D; C; 017E; # LATIN CAPITAL LETTER Z WITH CARON +017F; C; 0073; # LATIN SMALL LETTER LONG S +0181; C; 0253; # LATIN CAPITAL LETTER B WITH HOOK +0182; C; 0183; # LATIN CAPITAL LETTER B WITH TOPBAR +0184; C; 0185; # LATIN CAPITAL LETTER TONE SIX +0186; C; 0254; # LATIN CAPITAL LETTER OPEN O +0187; C; 0188; # LATIN CAPITAL LETTER C WITH HOOK +0189; C; 0256; # LATIN CAPITAL LETTER AFRICAN D +018A; C; 0257; # LATIN CAPITAL LETTER D WITH HOOK +018B; C; 018C; # LATIN CAPITAL LETTER D WITH TOPBAR +018E; C; 01DD; # LATIN CAPITAL LETTER REVERSED E +018F; C; 0259; # LATIN CAPITAL LETTER SCHWA +0190; C; 025B; # LATIN CAPITAL LETTER OPEN E +0191; C; 0192; # LATIN CAPITAL LETTER F WITH HOOK +0193; C; 0260; # LATIN CAPITAL LETTER G WITH HOOK +0194; C; 0263; # LATIN CAPITAL LETTER GAMMA +0196; C; 0269; # LATIN CAPITAL LETTER IOTA +0197; C; 0268; # LATIN CAPITAL LETTER I WITH STROKE +0198; C; 0199; # LATIN CAPITAL LETTER K WITH HOOK +019C; C; 026F; # LATIN CAPITAL LETTER TURNED M +019D; C; 0272; # LATIN CAPITAL LETTER N WITH LEFT HOOK +019F; C; 0275; # LATIN CAPITAL LETTER O WITH MIDDLE TILDE +01A0; C; 01A1; # LATIN CAPITAL LETTER O WITH HORN +01A2; C; 01A3; # LATIN CAPITAL LETTER OI +01A4; C; 01A5; # LATIN CAPITAL LETTER P WITH HOOK +01A6; C; 0280; # LATIN LETTER YR +01A7; C; 01A8; # LATIN CAPITAL LETTER TONE TWO +01A9; C; 0283; # LATIN CAPITAL LETTER ESH +01AC; C; 01AD; # LATIN CAPITAL LETTER T WITH HOOK +01AE; C; 0288; # LATIN CAPITAL LETTER T WITH RETROFLEX HOOK +01AF; C; 01B0; # LATIN CAPITAL LETTER U WITH HORN +01B1; C; 028A; # LATIN CAPITAL LETTER UPSILON +01B2; C; 028B; # LATIN CAPITAL LETTER V WITH HOOK +01B3; C; 01B4; # LATIN CAPITAL LETTER Y WITH HOOK +01B5; C; 01B6; # LATIN CAPITAL LETTER Z WITH STROKE +01B7; C; 0292; # LATIN CAPITAL LETTER EZH +01B8; C; 01B9; # LATIN CAPITAL LETTER EZH REVERSED +01BC; C; 01BD; # LATIN CAPITAL LETTER TONE FIVE +01C4; C; 01C6; # LATIN CAPITAL LETTER DZ WITH CARON +01C5; C; 01C6; # LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON +01C7; C; 01C9; # LATIN CAPITAL LETTER LJ +01C8; C; 01C9; # LATIN CAPITAL LETTER L WITH SMALL LETTER J +01CA; C; 01CC; # LATIN CAPITAL LETTER NJ +01CB; C; 01CC; # LATIN CAPITAL LETTER N WITH SMALL LETTER J +01CD; C; 01CE; # LATIN CAPITAL LETTER A WITH CARON +01CF; C; 01D0; # LATIN CAPITAL LETTER I WITH CARON +01D1; C; 01D2; # LATIN CAPITAL LETTER O WITH CARON +01D3; C; 01D4; # LATIN CAPITAL LETTER U WITH CARON +01D5; C; 01D6; # LATIN CAPITAL LETTER U WITH DIAERESIS AND MACRON +01D7; C; 01D8; # LATIN CAPITAL LETTER U WITH DIAERESIS AND ACUTE +01D9; C; 01DA; # LATIN CAPITAL LETTER U WITH DIAERESIS AND CARON +01DB; C; 01DC; # LATIN CAPITAL LETTER U WITH DIAERESIS AND GRAVE +01DE; C; 01DF; # LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON +01E0; C; 01E1; # LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON +01E2; C; 01E3; # LATIN CAPITAL LETTER AE WITH MACRON +01E4; C; 01E5; # LATIN CAPITAL LETTER G WITH STROKE +01E6; C; 01E7; # LATIN CAPITAL LETTER G WITH CARON +01E8; C; 01E9; # LATIN CAPITAL LETTER K WITH CARON +01EA; C; 01EB; # LATIN CAPITAL LETTER O WITH OGONEK +01EC; C; 01ED; # LATIN CAPITAL LETTER O WITH OGONEK AND MACRON +01EE; C; 01EF; # LATIN CAPITAL LETTER EZH WITH CARON +01F0; F; 006A 030C; # LATIN SMALL LETTER J WITH CARON +01F1; C; 01F3; # LATIN CAPITAL LETTER DZ +01F2; C; 01F3; # LATIN CAPITAL LETTER D WITH SMALL LETTER Z +01F4; C; 01F5; # LATIN CAPITAL LETTER G WITH ACUTE +01F6; C; 0195; # LATIN CAPITAL LETTER HWAIR +01F7; C; 01BF; # LATIN CAPITAL LETTER WYNN +01F8; C; 01F9; # LATIN CAPITAL LETTER N WITH GRAVE +01FA; C; 01FB; # LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE +01FC; C; 01FD; # LATIN CAPITAL LETTER AE WITH ACUTE +01FE; C; 01FF; # LATIN CAPITAL LETTER O WITH STROKE AND ACUTE +0200; C; 0201; # LATIN CAPITAL LETTER A WITH DOUBLE GRAVE +0202; C; 0203; # LATIN CAPITAL LETTER A WITH INVERTED BREVE +0204; C; 0205; # LATIN CAPITAL LETTER E WITH DOUBLE GRAVE +0206; C; 0207; # LATIN CAPITAL LETTER E WITH INVERTED BREVE +0208; C; 0209; # LATIN CAPITAL LETTER I WITH DOUBLE GRAVE +020A; C; 020B; # LATIN CAPITAL LETTER I WITH INVERTED BREVE +020C; C; 020D; # LATIN CAPITAL LETTER O WITH DOUBLE GRAVE +020E; C; 020F; # LATIN CAPITAL LETTER O WITH INVERTED BREVE +0210; C; 0211; # LATIN CAPITAL LETTER R WITH DOUBLE GRAVE +0212; C; 0213; # LATIN CAPITAL LETTER R WITH INVERTED BREVE +0214; C; 0215; # LATIN CAPITAL LETTER U WITH DOUBLE GRAVE +0216; C; 0217; # LATIN CAPITAL LETTER U WITH INVERTED BREVE +0218; C; 0219; # LATIN CAPITAL LETTER S WITH COMMA BELOW +021A; C; 021B; # LATIN CAPITAL LETTER T WITH COMMA BELOW +021C; C; 021D; # LATIN CAPITAL LETTER YOGH +021E; C; 021F; # LATIN CAPITAL LETTER H WITH CARON +0220; C; 019E; # LATIN CAPITAL LETTER N WITH LONG RIGHT LEG +0222; C; 0223; # LATIN CAPITAL LETTER OU +0224; C; 0225; # LATIN CAPITAL LETTER Z WITH HOOK +0226; C; 0227; # LATIN CAPITAL LETTER A WITH DOT ABOVE +0228; C; 0229; # LATIN CAPITAL LETTER E WITH CEDILLA +022A; C; 022B; # LATIN CAPITAL LETTER O WITH DIAERESIS AND MACRON +022C; C; 022D; # LATIN CAPITAL LETTER O WITH TILDE AND MACRON +022E; C; 022F; # LATIN CAPITAL LETTER O WITH DOT ABOVE +0230; C; 0231; # LATIN CAPITAL LETTER O WITH DOT ABOVE AND MACRON +0232; C; 0233; # LATIN CAPITAL LETTER Y WITH MACRON +023A; C; 2C65; # LATIN CAPITAL LETTER A WITH STROKE +023B; C; 023C; # LATIN CAPITAL LETTER C WITH STROKE +023D; C; 019A; # LATIN CAPITAL LETTER L WITH BAR +023E; C; 2C66; # LATIN CAPITAL LETTER T WITH DIAGONAL STROKE +0241; C; 0242; # LATIN CAPITAL LETTER GLOTTAL STOP +0243; C; 0180; # LATIN CAPITAL LETTER B WITH STROKE +0244; C; 0289; # LATIN CAPITAL LETTER U BAR +0245; C; 028C; # LATIN CAPITAL LETTER TURNED V +0246; C; 0247; # LATIN CAPITAL LETTER E WITH STROKE +0248; C; 0249; # LATIN CAPITAL LETTER J WITH STROKE +024A; C; 024B; # LATIN CAPITAL LETTER SMALL Q WITH HOOK TAIL +024C; C; 024D; # LATIN CAPITAL LETTER R WITH STROKE +024E; C; 024F; # LATIN CAPITAL LETTER Y WITH STROKE +0345; C; 03B9; # COMBINING GREEK YPOGEGRAMMENI +0370; C; 0371; # GREEK CAPITAL LETTER HETA +0372; C; 0373; # GREEK CAPITAL LETTER ARCHAIC SAMPI +0376; C; 0377; # GREEK CAPITAL LETTER PAMPHYLIAN DIGAMMA +0386; C; 03AC; # GREEK CAPITAL LETTER ALPHA WITH TONOS +0388; C; 03AD; # GREEK CAPITAL LETTER EPSILON WITH TONOS +0389; C; 03AE; # GREEK CAPITAL LETTER ETA WITH TONOS +038A; C; 03AF; # GREEK CAPITAL LETTER IOTA WITH TONOS +038C; C; 03CC; # GREEK CAPITAL LETTER OMICRON WITH TONOS +038E; C; 03CD; # GREEK CAPITAL LETTER UPSILON WITH TONOS +038F; C; 03CE; # GREEK CAPITAL LETTER OMEGA WITH TONOS +0390; F; 03B9 0308 0301; # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS +0391; C; 03B1; # GREEK CAPITAL LETTER ALPHA +0392; C; 03B2; # GREEK CAPITAL LETTER BETA +0393; C; 03B3; # GREEK CAPITAL LETTER GAMMA +0394; C; 03B4; # GREEK CAPITAL LETTER DELTA +0395; C; 03B5; # GREEK CAPITAL LETTER EPSILON +0396; C; 03B6; # GREEK CAPITAL LETTER ZETA +0397; C; 03B7; # GREEK CAPITAL LETTER ETA +0398; C; 03B8; # GREEK CAPITAL LETTER THETA +0399; C; 03B9; # GREEK CAPITAL LETTER IOTA +039A; C; 03BA; # GREEK CAPITAL LETTER KAPPA +039B; C; 03BB; # GREEK CAPITAL LETTER LAMDA +039C; C; 03BC; # GREEK CAPITAL LETTER MU +039D; C; 03BD; # GREEK CAPITAL LETTER NU +039E; C; 03BE; # GREEK CAPITAL LETTER XI +039F; C; 03BF; # GREEK CAPITAL LETTER OMICRON +03A0; C; 03C0; # GREEK CAPITAL LETTER PI +03A1; C; 03C1; # GREEK CAPITAL LETTER RHO +03A3; C; 03C3; # GREEK CAPITAL LETTER SIGMA +03A4; C; 03C4; # GREEK CAPITAL LETTER TAU +03A5; C; 03C5; # GREEK CAPITAL LETTER UPSILON +03A6; C; 03C6; # GREEK CAPITAL LETTER PHI +03A7; C; 03C7; # GREEK CAPITAL LETTER CHI +03A8; C; 03C8; # GREEK CAPITAL LETTER PSI +03A9; C; 03C9; # GREEK CAPITAL LETTER OMEGA +03AA; C; 03CA; # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA +03AB; C; 03CB; # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA +03B0; F; 03C5 0308 0301; # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS +03C2; C; 03C3; # GREEK SMALL LETTER FINAL SIGMA +03CF; C; 03D7; # GREEK CAPITAL KAI SYMBOL +03D0; C; 03B2; # GREEK BETA SYMBOL +03D1; C; 03B8; # GREEK THETA SYMBOL +03D5; C; 03C6; # GREEK PHI SYMBOL +03D6; C; 03C0; # GREEK PI SYMBOL +03D8; C; 03D9; # GREEK LETTER ARCHAIC KOPPA +03DA; C; 03DB; # GREEK LETTER STIGMA +03DC; C; 03DD; # GREEK LETTER DIGAMMA +03DE; C; 03DF; # GREEK LETTER KOPPA +03E0; C; 03E1; # GREEK LETTER SAMPI +03E2; C; 03E3; # COPTIC CAPITAL LETTER SHEI +03E4; C; 03E5; # COPTIC CAPITAL LETTER FEI +03E6; C; 03E7; # COPTIC CAPITAL LETTER KHEI +03E8; C; 03E9; # COPTIC CAPITAL LETTER HORI +03EA; C; 03EB; # COPTIC CAPITAL LETTER GANGIA +03EC; C; 03ED; # COPTIC CAPITAL LETTER SHIMA +03EE; C; 03EF; # COPTIC CAPITAL LETTER DEI +03F0; C; 03BA; # GREEK KAPPA SYMBOL +03F1; C; 03C1; # GREEK RHO SYMBOL +03F4; C; 03B8; # GREEK CAPITAL THETA SYMBOL +03F5; C; 03B5; # GREEK LUNATE EPSILON SYMBOL +03F7; C; 03F8; # GREEK CAPITAL LETTER SHO +03F9; C; 03F2; # GREEK CAPITAL LUNATE SIGMA SYMBOL +03FA; C; 03FB; # GREEK CAPITAL LETTER SAN +03FD; C; 037B; # GREEK CAPITAL REVERSED LUNATE SIGMA SYMBOL +03FE; C; 037C; # GREEK CAPITAL DOTTED LUNATE SIGMA SYMBOL +03FF; C; 037D; # GREEK CAPITAL REVERSED DOTTED LUNATE SIGMA SYMBOL +0400; C; 0450; # CYRILLIC CAPITAL LETTER IE WITH GRAVE +0401; C; 0451; # CYRILLIC CAPITAL LETTER IO +0402; C; 0452; # CYRILLIC CAPITAL LETTER DJE +0403; C; 0453; # CYRILLIC CAPITAL LETTER GJE +0404; C; 0454; # CYRILLIC CAPITAL LETTER UKRAINIAN IE +0405; C; 0455; # CYRILLIC CAPITAL LETTER DZE +0406; C; 0456; # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I +0407; C; 0457; # CYRILLIC CAPITAL LETTER YI +0408; C; 0458; # CYRILLIC CAPITAL LETTER JE +0409; C; 0459; # CYRILLIC CAPITAL LETTER LJE +040A; C; 045A; # CYRILLIC CAPITAL LETTER NJE +040B; C; 045B; # CYRILLIC CAPITAL LETTER TSHE +040C; C; 045C; # CYRILLIC CAPITAL LETTER KJE +040D; C; 045D; # CYRILLIC CAPITAL LETTER I WITH GRAVE +040E; C; 045E; # CYRILLIC CAPITAL LETTER SHORT U +040F; C; 045F; # CYRILLIC CAPITAL LETTER DZHE +0410; C; 0430; # CYRILLIC CAPITAL LETTER A +0411; C; 0431; # CYRILLIC CAPITAL LETTER BE +0412; C; 0432; # CYRILLIC CAPITAL LETTER VE +0413; C; 0433; # CYRILLIC CAPITAL LETTER GHE +0414; C; 0434; # CYRILLIC CAPITAL LETTER DE +0415; C; 0435; # CYRILLIC CAPITAL LETTER IE +0416; C; 0436; # CYRILLIC CAPITAL LETTER ZHE +0417; C; 0437; # CYRILLIC CAPITAL LETTER ZE +0418; C; 0438; # CYRILLIC CAPITAL LETTER I +0419; C; 0439; # CYRILLIC CAPITAL LETTER SHORT I +041A; C; 043A; # CYRILLIC CAPITAL LETTER KA +041B; C; 043B; # CYRILLIC CAPITAL LETTER EL +041C; C; 043C; # CYRILLIC CAPITAL LETTER EM +041D; C; 043D; # CYRILLIC CAPITAL LETTER EN +041E; C; 043E; # CYRILLIC CAPITAL LETTER O +041F; C; 043F; # CYRILLIC CAPITAL LETTER PE +0420; C; 0440; # CYRILLIC CAPITAL LETTER ER +0421; C; 0441; # CYRILLIC CAPITAL LETTER ES +0422; C; 0442; # CYRILLIC CAPITAL LETTER TE +0423; C; 0443; # CYRILLIC CAPITAL LETTER U +0424; C; 0444; # CYRILLIC CAPITAL LETTER EF +0425; C; 0445; # CYRILLIC CAPITAL LETTER HA +0426; C; 0446; # CYRILLIC CAPITAL LETTER TSE +0427; C; 0447; # CYRILLIC CAPITAL LETTER CHE +0428; C; 0448; # CYRILLIC CAPITAL LETTER SHA +0429; C; 0449; # CYRILLIC CAPITAL LETTER SHCHA +042A; C; 044A; # CYRILLIC CAPITAL LETTER HARD SIGN +042B; C; 044B; # CYRILLIC CAPITAL LETTER YERU +042C; C; 044C; # CYRILLIC CAPITAL LETTER SOFT SIGN +042D; C; 044D; # CYRILLIC CAPITAL LETTER E +042E; C; 044E; # CYRILLIC CAPITAL LETTER YU +042F; C; 044F; # CYRILLIC CAPITAL LETTER YA +0460; C; 0461; # CYRILLIC CAPITAL LETTER OMEGA +0462; C; 0463; # CYRILLIC CAPITAL LETTER YAT +0464; C; 0465; # CYRILLIC CAPITAL LETTER IOTIFIED E +0466; C; 0467; # CYRILLIC CAPITAL LETTER LITTLE YUS +0468; C; 0469; # CYRILLIC CAPITAL LETTER IOTIFIED LITTLE YUS +046A; C; 046B; # CYRILLIC CAPITAL LETTER BIG YUS +046C; C; 046D; # CYRILLIC CAPITAL LETTER IOTIFIED BIG YUS +046E; C; 046F; # CYRILLIC CAPITAL LETTER KSI +0470; C; 0471; # CYRILLIC CAPITAL LETTER PSI +0472; C; 0473; # CYRILLIC CAPITAL LETTER FITA +0474; C; 0475; # CYRILLIC CAPITAL LETTER IZHITSA +0476; C; 0477; # CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT +0478; C; 0479; # CYRILLIC CAPITAL LETTER UK +047A; C; 047B; # CYRILLIC CAPITAL LETTER ROUND OMEGA +047C; C; 047D; # CYRILLIC CAPITAL LETTER OMEGA WITH TITLO +047E; C; 047F; # CYRILLIC CAPITAL LETTER OT +0480; C; 0481; # CYRILLIC CAPITAL LETTER KOPPA +048A; C; 048B; # CYRILLIC CAPITAL LETTER SHORT I WITH TAIL +048C; C; 048D; # CYRILLIC CAPITAL LETTER SEMISOFT SIGN +048E; C; 048F; # CYRILLIC CAPITAL LETTER ER WITH TICK +0490; C; 0491; # CYRILLIC CAPITAL LETTER GHE WITH UPTURN +0492; C; 0493; # CYRILLIC CAPITAL LETTER GHE WITH STROKE +0494; C; 0495; # CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK +0496; C; 0497; # CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER +0498; C; 0499; # CYRILLIC CAPITAL LETTER ZE WITH DESCENDER +049A; C; 049B; # CYRILLIC CAPITAL LETTER KA WITH DESCENDER +049C; C; 049D; # CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE +049E; C; 049F; # CYRILLIC CAPITAL LETTER KA WITH STROKE +04A0; C; 04A1; # CYRILLIC CAPITAL LETTER BASHKIR KA +04A2; C; 04A3; # CYRILLIC CAPITAL LETTER EN WITH DESCENDER +04A4; C; 04A5; # CYRILLIC CAPITAL LIGATURE EN GHE +04A6; C; 04A7; # CYRILLIC CAPITAL LETTER PE WITH MIDDLE HOOK +04A8; C; 04A9; # CYRILLIC CAPITAL LETTER ABKHASIAN HA +04AA; C; 04AB; # CYRILLIC CAPITAL LETTER ES WITH DESCENDER +04AC; C; 04AD; # CYRILLIC CAPITAL LETTER TE WITH DESCENDER +04AE; C; 04AF; # CYRILLIC CAPITAL LETTER STRAIGHT U +04B0; C; 04B1; # CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE +04B2; C; 04B3; # CYRILLIC CAPITAL LETTER HA WITH DESCENDER +04B4; C; 04B5; # CYRILLIC CAPITAL LIGATURE TE TSE +04B6; C; 04B7; # CYRILLIC CAPITAL LETTER CHE WITH DESCENDER +04B8; C; 04B9; # CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE +04BA; C; 04BB; # CYRILLIC CAPITAL LETTER SHHA +04BC; C; 04BD; # CYRILLIC CAPITAL LETTER ABKHASIAN CHE +04BE; C; 04BF; # CYRILLIC CAPITAL LETTER ABKHASIAN CHE WITH DESCENDER +04C0; C; 04CF; # CYRILLIC LETTER PALOCHKA +04C1; C; 04C2; # CYRILLIC CAPITAL LETTER ZHE WITH BREVE +04C3; C; 04C4; # CYRILLIC CAPITAL LETTER KA WITH HOOK +04C5; C; 04C6; # CYRILLIC CAPITAL LETTER EL WITH TAIL +04C7; C; 04C8; # CYRILLIC CAPITAL LETTER EN WITH HOOK +04C9; C; 04CA; # CYRILLIC CAPITAL LETTER EN WITH TAIL +04CB; C; 04CC; # CYRILLIC CAPITAL LETTER KHAKASSIAN CHE +04CD; C; 04CE; # CYRILLIC CAPITAL LETTER EM WITH TAIL +04D0; C; 04D1; # CYRILLIC CAPITAL LETTER A WITH BREVE +04D2; C; 04D3; # CYRILLIC CAPITAL LETTER A WITH DIAERESIS +04D4; C; 04D5; # CYRILLIC CAPITAL LIGATURE A IE +04D6; C; 04D7; # CYRILLIC CAPITAL LETTER IE WITH BREVE +04D8; C; 04D9; # CYRILLIC CAPITAL LETTER SCHWA +04DA; C; 04DB; # CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS +04DC; C; 04DD; # CYRILLIC CAPITAL LETTER ZHE WITH DIAERESIS +04DE; C; 04DF; # CYRILLIC CAPITAL LETTER ZE WITH DIAERESIS +04E0; C; 04E1; # CYRILLIC CAPITAL LETTER ABKHASIAN DZE +04E2; C; 04E3; # CYRILLIC CAPITAL LETTER I WITH MACRON +04E4; C; 04E5; # CYRILLIC CAPITAL LETTER I WITH DIAERESIS +04E6; C; 04E7; # CYRILLIC CAPITAL LETTER O WITH DIAERESIS +04E8; C; 04E9; # CYRILLIC CAPITAL LETTER BARRED O +04EA; C; 04EB; # CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS +04EC; C; 04ED; # CYRILLIC CAPITAL LETTER E WITH DIAERESIS +04EE; C; 04EF; # CYRILLIC CAPITAL LETTER U WITH MACRON +04F0; C; 04F1; # CYRILLIC CAPITAL LETTER U WITH DIAERESIS +04F2; C; 04F3; # CYRILLIC CAPITAL LETTER U WITH DOUBLE ACUTE +04F4; C; 04F5; # CYRILLIC CAPITAL LETTER CHE WITH DIAERESIS +04F6; C; 04F7; # CYRILLIC CAPITAL LETTER GHE WITH DESCENDER +04F8; C; 04F9; # CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS +04FA; C; 04FB; # CYRILLIC CAPITAL LETTER GHE WITH STROKE AND HOOK +04FC; C; 04FD; # CYRILLIC CAPITAL LETTER HA WITH HOOK +04FE; C; 04FF; # CYRILLIC CAPITAL LETTER HA WITH STROKE +0500; C; 0501; # CYRILLIC CAPITAL LETTER KOMI DE +0502; C; 0503; # CYRILLIC CAPITAL LETTER KOMI DJE +0504; C; 0505; # CYRILLIC CAPITAL LETTER KOMI ZJE +0506; C; 0507; # CYRILLIC CAPITAL LETTER KOMI DZJE +0508; C; 0509; # CYRILLIC CAPITAL LETTER KOMI LJE +050A; C; 050B; # CYRILLIC CAPITAL LETTER KOMI NJE +050C; C; 050D; # CYRILLIC CAPITAL LETTER KOMI SJE +050E; C; 050F; # CYRILLIC CAPITAL LETTER KOMI TJE +0510; C; 0511; # CYRILLIC CAPITAL LETTER REVERSED ZE +0512; C; 0513; # CYRILLIC CAPITAL LETTER EL WITH HOOK +0514; C; 0515; # CYRILLIC CAPITAL LETTER LHA +0516; C; 0517; # CYRILLIC CAPITAL LETTER RHA +0518; C; 0519; # CYRILLIC CAPITAL LETTER YAE +051A; C; 051B; # CYRILLIC CAPITAL LETTER QA +051C; C; 051D; # CYRILLIC CAPITAL LETTER WE +051E; C; 051F; # CYRILLIC CAPITAL LETTER ALEUT KA +0520; C; 0521; # CYRILLIC CAPITAL LETTER EL WITH MIDDLE HOOK +0522; C; 0523; # CYRILLIC CAPITAL LETTER EN WITH MIDDLE HOOK +0524; C; 0525; # CYRILLIC CAPITAL LETTER PE WITH DESCENDER +0526; C; 0527; # CYRILLIC CAPITAL LETTER SHHA WITH DESCENDER +0531; C; 0561; # ARMENIAN CAPITAL LETTER AYB +0532; C; 0562; # ARMENIAN CAPITAL LETTER BEN +0533; C; 0563; # ARMENIAN CAPITAL LETTER GIM +0534; C; 0564; # ARMENIAN CAPITAL LETTER DA +0535; C; 0565; # ARMENIAN CAPITAL LETTER ECH +0536; C; 0566; # ARMENIAN CAPITAL LETTER ZA +0537; C; 0567; # ARMENIAN CAPITAL LETTER EH +0538; C; 0568; # ARMENIAN CAPITAL LETTER ET +0539; C; 0569; # ARMENIAN CAPITAL LETTER TO +053A; C; 056A; # ARMENIAN CAPITAL LETTER ZHE +053B; C; 056B; # ARMENIAN CAPITAL LETTER INI +053C; C; 056C; # ARMENIAN CAPITAL LETTER LIWN +053D; C; 056D; # ARMENIAN CAPITAL LETTER XEH +053E; C; 056E; # ARMENIAN CAPITAL LETTER CA +053F; C; 056F; # ARMENIAN CAPITAL LETTER KEN +0540; C; 0570; # ARMENIAN CAPITAL LETTER HO +0541; C; 0571; # ARMENIAN CAPITAL LETTER JA +0542; C; 0572; # ARMENIAN CAPITAL LETTER GHAD +0543; C; 0573; # ARMENIAN CAPITAL LETTER CHEH +0544; C; 0574; # ARMENIAN CAPITAL LETTER MEN +0545; C; 0575; # ARMENIAN CAPITAL LETTER YI +0546; C; 0576; # ARMENIAN CAPITAL LETTER NOW +0547; C; 0577; # ARMENIAN CAPITAL LETTER SHA +0548; C; 0578; # ARMENIAN CAPITAL LETTER VO +0549; C; 0579; # ARMENIAN CAPITAL LETTER CHA +054A; C; 057A; # ARMENIAN CAPITAL LETTER PEH +054B; C; 057B; # ARMENIAN CAPITAL LETTER JHEH +054C; C; 057C; # ARMENIAN CAPITAL LETTER RA +054D; C; 057D; # ARMENIAN CAPITAL LETTER SEH +054E; C; 057E; # ARMENIAN CAPITAL LETTER VEW +054F; C; 057F; # ARMENIAN CAPITAL LETTER TIWN +0550; C; 0580; # ARMENIAN CAPITAL LETTER REH +0551; C; 0581; # ARMENIAN CAPITAL LETTER CO +0552; C; 0582; # ARMENIAN CAPITAL LETTER YIWN +0553; C; 0583; # ARMENIAN CAPITAL LETTER PIWR +0554; C; 0584; # ARMENIAN CAPITAL LETTER KEH +0555; C; 0585; # ARMENIAN CAPITAL LETTER OH +0556; C; 0586; # ARMENIAN CAPITAL LETTER FEH +0587; F; 0565 0582; # ARMENIAN SMALL LIGATURE ECH YIWN +10A0; C; 2D00; # GEORGIAN CAPITAL LETTER AN +10A1; C; 2D01; # GEORGIAN CAPITAL LETTER BAN +10A2; C; 2D02; # GEORGIAN CAPITAL LETTER GAN +10A3; C; 2D03; # GEORGIAN CAPITAL LETTER DON +10A4; C; 2D04; # GEORGIAN CAPITAL LETTER EN +10A5; C; 2D05; # GEORGIAN CAPITAL LETTER VIN +10A6; C; 2D06; # GEORGIAN CAPITAL LETTER ZEN +10A7; C; 2D07; # GEORGIAN CAPITAL LETTER TAN +10A8; C; 2D08; # GEORGIAN CAPITAL LETTER IN +10A9; C; 2D09; # GEORGIAN CAPITAL LETTER KAN +10AA; C; 2D0A; # GEORGIAN CAPITAL LETTER LAS +10AB; C; 2D0B; # GEORGIAN CAPITAL LETTER MAN +10AC; C; 2D0C; # GEORGIAN CAPITAL LETTER NAR +10AD; C; 2D0D; # GEORGIAN CAPITAL LETTER ON +10AE; C; 2D0E; # GEORGIAN CAPITAL LETTER PAR +10AF; C; 2D0F; # GEORGIAN CAPITAL LETTER ZHAR +10B0; C; 2D10; # GEORGIAN CAPITAL LETTER RAE +10B1; C; 2D11; # GEORGIAN CAPITAL LETTER SAN +10B2; C; 2D12; # GEORGIAN CAPITAL LETTER TAR +10B3; C; 2D13; # GEORGIAN CAPITAL LETTER UN +10B4; C; 2D14; # GEORGIAN CAPITAL LETTER PHAR +10B5; C; 2D15; # GEORGIAN CAPITAL LETTER KHAR +10B6; C; 2D16; # GEORGIAN CAPITAL LETTER GHAN +10B7; C; 2D17; # GEORGIAN CAPITAL LETTER QAR +10B8; C; 2D18; # GEORGIAN CAPITAL LETTER SHIN +10B9; C; 2D19; # GEORGIAN CAPITAL LETTER CHIN +10BA; C; 2D1A; # GEORGIAN CAPITAL LETTER CAN +10BB; C; 2D1B; # GEORGIAN CAPITAL LETTER JIL +10BC; C; 2D1C; # GEORGIAN CAPITAL LETTER CIL +10BD; C; 2D1D; # GEORGIAN CAPITAL LETTER CHAR +10BE; C; 2D1E; # GEORGIAN CAPITAL LETTER XAN +10BF; C; 2D1F; # GEORGIAN CAPITAL LETTER JHAN +10C0; C; 2D20; # GEORGIAN CAPITAL LETTER HAE +10C1; C; 2D21; # GEORGIAN CAPITAL LETTER HE +10C2; C; 2D22; # GEORGIAN CAPITAL LETTER HIE +10C3; C; 2D23; # GEORGIAN CAPITAL LETTER WE +10C4; C; 2D24; # GEORGIAN CAPITAL LETTER HAR +10C5; C; 2D25; # GEORGIAN CAPITAL LETTER HOE +10C7; C; 2D27; # GEORGIAN CAPITAL LETTER YN +10CD; C; 2D2D; # GEORGIAN CAPITAL LETTER AEN +1E00; C; 1E01; # LATIN CAPITAL LETTER A WITH RING BELOW +1E02; C; 1E03; # LATIN CAPITAL LETTER B WITH DOT ABOVE +1E04; C; 1E05; # LATIN CAPITAL LETTER B WITH DOT BELOW +1E06; C; 1E07; # LATIN CAPITAL LETTER B WITH LINE BELOW +1E08; C; 1E09; # LATIN CAPITAL LETTER C WITH CEDILLA AND ACUTE +1E0A; C; 1E0B; # LATIN CAPITAL LETTER D WITH DOT ABOVE +1E0C; C; 1E0D; # LATIN CAPITAL LETTER D WITH DOT BELOW +1E0E; C; 1E0F; # LATIN CAPITAL LETTER D WITH LINE BELOW +1E10; C; 1E11; # LATIN CAPITAL LETTER D WITH CEDILLA +1E12; C; 1E13; # LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW +1E14; C; 1E15; # LATIN CAPITAL LETTER E WITH MACRON AND GRAVE +1E16; C; 1E17; # LATIN CAPITAL LETTER E WITH MACRON AND ACUTE +1E18; C; 1E19; # LATIN CAPITAL LETTER E WITH CIRCUMFLEX BELOW +1E1A; C; 1E1B; # LATIN CAPITAL LETTER E WITH TILDE BELOW +1E1C; C; 1E1D; # LATIN CAPITAL LETTER E WITH CEDILLA AND BREVE +1E1E; C; 1E1F; # LATIN CAPITAL LETTER F WITH DOT ABOVE +1E20; C; 1E21; # LATIN CAPITAL LETTER G WITH MACRON +1E22; C; 1E23; # LATIN CAPITAL LETTER H WITH DOT ABOVE +1E24; C; 1E25; # LATIN CAPITAL LETTER H WITH DOT BELOW +1E26; C; 1E27; # LATIN CAPITAL LETTER H WITH DIAERESIS +1E28; C; 1E29; # LATIN CAPITAL LETTER H WITH CEDILLA +1E2A; C; 1E2B; # LATIN CAPITAL LETTER H WITH BREVE BELOW +1E2C; C; 1E2D; # LATIN CAPITAL LETTER I WITH TILDE BELOW +1E2E; C; 1E2F; # LATIN CAPITAL LETTER I WITH DIAERESIS AND ACUTE +1E30; C; 1E31; # LATIN CAPITAL LETTER K WITH ACUTE +1E32; C; 1E33; # LATIN CAPITAL LETTER K WITH DOT BELOW +1E34; C; 1E35; # LATIN CAPITAL LETTER K WITH LINE BELOW +1E36; C; 1E37; # LATIN CAPITAL LETTER L WITH DOT BELOW +1E38; C; 1E39; # LATIN CAPITAL LETTER L WITH DOT BELOW AND MACRON +1E3A; C; 1E3B; # LATIN CAPITAL LETTER L WITH LINE BELOW +1E3C; C; 1E3D; # LATIN CAPITAL LETTER L WITH CIRCUMFLEX BELOW +1E3E; C; 1E3F; # LATIN CAPITAL LETTER M WITH ACUTE +1E40; C; 1E41; # LATIN CAPITAL LETTER M WITH DOT ABOVE +1E42; C; 1E43; # LATIN CAPITAL LETTER M WITH DOT BELOW +1E44; C; 1E45; # LATIN CAPITAL LETTER N WITH DOT ABOVE +1E46; C; 1E47; # LATIN CAPITAL LETTER N WITH DOT BELOW +1E48; C; 1E49; # LATIN CAPITAL LETTER N WITH LINE BELOW +1E4A; C; 1E4B; # LATIN CAPITAL LETTER N WITH CIRCUMFLEX BELOW +1E4C; C; 1E4D; # LATIN CAPITAL LETTER O WITH TILDE AND ACUTE +1E4E; C; 1E4F; # LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS +1E50; C; 1E51; # LATIN CAPITAL LETTER O WITH MACRON AND GRAVE +1E52; C; 1E53; # LATIN CAPITAL LETTER O WITH MACRON AND ACUTE +1E54; C; 1E55; # LATIN CAPITAL LETTER P WITH ACUTE +1E56; C; 1E57; # LATIN CAPITAL LETTER P WITH DOT ABOVE +1E58; C; 1E59; # LATIN CAPITAL LETTER R WITH DOT ABOVE +1E5A; C; 1E5B; # LATIN CAPITAL LETTER R WITH DOT BELOW +1E5C; C; 1E5D; # LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON +1E5E; C; 1E5F; # LATIN CAPITAL LETTER R WITH LINE BELOW +1E60; C; 1E61; # LATIN CAPITAL LETTER S WITH DOT ABOVE +1E62; C; 1E63; # LATIN CAPITAL LETTER S WITH DOT BELOW +1E64; C; 1E65; # LATIN CAPITAL LETTER S WITH ACUTE AND DOT ABOVE +1E66; C; 1E67; # LATIN CAPITAL LETTER S WITH CARON AND DOT ABOVE +1E68; C; 1E69; # LATIN CAPITAL LETTER S WITH DOT BELOW AND DOT ABOVE +1E6A; C; 1E6B; # LATIN CAPITAL LETTER T WITH DOT ABOVE +1E6C; C; 1E6D; # LATIN CAPITAL LETTER T WITH DOT BELOW +1E6E; C; 1E6F; # LATIN CAPITAL LETTER T WITH LINE BELOW +1E70; C; 1E71; # LATIN CAPITAL LETTER T WITH CIRCUMFLEX BELOW +1E72; C; 1E73; # LATIN CAPITAL LETTER U WITH DIAERESIS BELOW +1E74; C; 1E75; # LATIN CAPITAL LETTER U WITH TILDE BELOW +1E76; C; 1E77; # LATIN CAPITAL LETTER U WITH CIRCUMFLEX BELOW +1E78; C; 1E79; # LATIN CAPITAL LETTER U WITH TILDE AND ACUTE +1E7A; C; 1E7B; # LATIN CAPITAL LETTER U WITH MACRON AND DIAERESIS +1E7C; C; 1E7D; # LATIN CAPITAL LETTER V WITH TILDE +1E7E; C; 1E7F; # LATIN CAPITAL LETTER V WITH DOT BELOW +1E80; C; 1E81; # LATIN CAPITAL LETTER W WITH GRAVE +1E82; C; 1E83; # LATIN CAPITAL LETTER W WITH ACUTE +1E84; C; 1E85; # LATIN CAPITAL LETTER W WITH DIAERESIS +1E86; C; 1E87; # LATIN CAPITAL LETTER W WITH DOT ABOVE +1E88; C; 1E89; # LATIN CAPITAL LETTER W WITH DOT BELOW +1E8A; C; 1E8B; # LATIN CAPITAL LETTER X WITH DOT ABOVE +1E8C; C; 1E8D; # LATIN CAPITAL LETTER X WITH DIAERESIS +1E8E; C; 1E8F; # LATIN CAPITAL LETTER Y WITH DOT ABOVE +1E90; C; 1E91; # LATIN CAPITAL LETTER Z WITH CIRCUMFLEX +1E92; C; 1E93; # LATIN CAPITAL LETTER Z WITH DOT BELOW +1E94; C; 1E95; # LATIN CAPITAL LETTER Z WITH LINE BELOW +1E96; F; 0068 0331; # LATIN SMALL LETTER H WITH LINE BELOW +1E97; F; 0074 0308; # LATIN SMALL LETTER T WITH DIAERESIS +1E98; F; 0077 030A; # LATIN SMALL LETTER W WITH RING ABOVE +1E99; F; 0079 030A; # LATIN SMALL LETTER Y WITH RING ABOVE +1E9A; F; 0061 02BE; # LATIN SMALL LETTER A WITH RIGHT HALF RING +1E9B; C; 1E61; # LATIN SMALL LETTER LONG S WITH DOT ABOVE +1E9E; F; 0073 0073; # LATIN CAPITAL LETTER SHARP S +1E9E; S; 00DF; # LATIN CAPITAL LETTER SHARP S +1EA0; C; 1EA1; # LATIN CAPITAL LETTER A WITH DOT BELOW +1EA2; C; 1EA3; # LATIN CAPITAL LETTER A WITH HOOK ABOVE +1EA4; C; 1EA5; # LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE +1EA6; C; 1EA7; # LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE +1EA8; C; 1EA9; # LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE +1EAA; C; 1EAB; # LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE +1EAC; C; 1EAD; # LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW +1EAE; C; 1EAF; # LATIN CAPITAL LETTER A WITH BREVE AND ACUTE +1EB0; C; 1EB1; # LATIN CAPITAL LETTER A WITH BREVE AND GRAVE +1EB2; C; 1EB3; # LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE +1EB4; C; 1EB5; # LATIN CAPITAL LETTER A WITH BREVE AND TILDE +1EB6; C; 1EB7; # LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW +1EB8; C; 1EB9; # LATIN CAPITAL LETTER E WITH DOT BELOW +1EBA; C; 1EBB; # LATIN CAPITAL LETTER E WITH HOOK ABOVE +1EBC; C; 1EBD; # LATIN CAPITAL LETTER E WITH TILDE +1EBE; C; 1EBF; # LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE +1EC0; C; 1EC1; # LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE +1EC2; C; 1EC3; # LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE +1EC4; C; 1EC5; # LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE +1EC6; C; 1EC7; # LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW +1EC8; C; 1EC9; # LATIN CAPITAL LETTER I WITH HOOK ABOVE +1ECA; C; 1ECB; # LATIN CAPITAL LETTER I WITH DOT BELOW +1ECC; C; 1ECD; # LATIN CAPITAL LETTER O WITH DOT BELOW +1ECE; C; 1ECF; # LATIN CAPITAL LETTER O WITH HOOK ABOVE +1ED0; C; 1ED1; # LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE +1ED2; C; 1ED3; # LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE +1ED4; C; 1ED5; # LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE +1ED6; C; 1ED7; # LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE +1ED8; C; 1ED9; # LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW +1EDA; C; 1EDB; # LATIN CAPITAL LETTER O WITH HORN AND ACUTE +1EDC; C; 1EDD; # LATIN CAPITAL LETTER O WITH HORN AND GRAVE +1EDE; C; 1EDF; # LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE +1EE0; C; 1EE1; # LATIN CAPITAL LETTER O WITH HORN AND TILDE +1EE2; C; 1EE3; # LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW +1EE4; C; 1EE5; # LATIN CAPITAL LETTER U WITH DOT BELOW +1EE6; C; 1EE7; # LATIN CAPITAL LETTER U WITH HOOK ABOVE +1EE8; C; 1EE9; # LATIN CAPITAL LETTER U WITH HORN AND ACUTE +1EEA; C; 1EEB; # LATIN CAPITAL LETTER U WITH HORN AND GRAVE +1EEC; C; 1EED; # LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE +1EEE; C; 1EEF; # LATIN CAPITAL LETTER U WITH HORN AND TILDE +1EF0; C; 1EF1; # LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW +1EF2; C; 1EF3; # LATIN CAPITAL LETTER Y WITH GRAVE +1EF4; C; 1EF5; # LATIN CAPITAL LETTER Y WITH DOT BELOW +1EF6; C; 1EF7; # LATIN CAPITAL LETTER Y WITH HOOK ABOVE +1EF8; C; 1EF9; # LATIN CAPITAL LETTER Y WITH TILDE +1EFA; C; 1EFB; # LATIN CAPITAL LETTER MIDDLE-WELSH LL +1EFC; C; 1EFD; # LATIN CAPITAL LETTER MIDDLE-WELSH V +1EFE; C; 1EFF; # LATIN CAPITAL LETTER Y WITH LOOP +1F08; C; 1F00; # GREEK CAPITAL LETTER ALPHA WITH PSILI +1F09; C; 1F01; # GREEK CAPITAL LETTER ALPHA WITH DASIA +1F0A; C; 1F02; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA +1F0B; C; 1F03; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA +1F0C; C; 1F04; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA +1F0D; C; 1F05; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA +1F0E; C; 1F06; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI +1F0F; C; 1F07; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI +1F18; C; 1F10; # GREEK CAPITAL LETTER EPSILON WITH PSILI +1F19; C; 1F11; # GREEK CAPITAL LETTER EPSILON WITH DASIA +1F1A; C; 1F12; # GREEK CAPITAL LETTER EPSILON WITH PSILI AND VARIA +1F1B; C; 1F13; # GREEK CAPITAL LETTER EPSILON WITH DASIA AND VARIA +1F1C; C; 1F14; # GREEK CAPITAL LETTER EPSILON WITH PSILI AND OXIA +1F1D; C; 1F15; # GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA +1F28; C; 1F20; # GREEK CAPITAL LETTER ETA WITH PSILI +1F29; C; 1F21; # GREEK CAPITAL LETTER ETA WITH DASIA +1F2A; C; 1F22; # GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA +1F2B; C; 1F23; # GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA +1F2C; C; 1F24; # GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA +1F2D; C; 1F25; # GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA +1F2E; C; 1F26; # GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI +1F2F; C; 1F27; # GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI +1F38; C; 1F30; # GREEK CAPITAL LETTER IOTA WITH PSILI +1F39; C; 1F31; # GREEK CAPITAL LETTER IOTA WITH DASIA +1F3A; C; 1F32; # GREEK CAPITAL LETTER IOTA WITH PSILI AND VARIA +1F3B; C; 1F33; # GREEK CAPITAL LETTER IOTA WITH DASIA AND VARIA +1F3C; C; 1F34; # GREEK CAPITAL LETTER IOTA WITH PSILI AND OXIA +1F3D; C; 1F35; # GREEK CAPITAL LETTER IOTA WITH DASIA AND OXIA +1F3E; C; 1F36; # GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI +1F3F; C; 1F37; # GREEK CAPITAL LETTER IOTA WITH DASIA AND PERISPOMENI +1F48; C; 1F40; # GREEK CAPITAL LETTER OMICRON WITH PSILI +1F49; C; 1F41; # GREEK CAPITAL LETTER OMICRON WITH DASIA +1F4A; C; 1F42; # GREEK CAPITAL LETTER OMICRON WITH PSILI AND VARIA +1F4B; C; 1F43; # GREEK CAPITAL LETTER OMICRON WITH DASIA AND VARIA +1F4C; C; 1F44; # GREEK CAPITAL LETTER OMICRON WITH PSILI AND OXIA +1F4D; C; 1F45; # GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA +1F50; F; 03C5 0313; # GREEK SMALL LETTER UPSILON WITH PSILI +1F52; F; 03C5 0313 0300; # GREEK SMALL LETTER UPSILON WITH PSILI AND VARIA +1F54; F; 03C5 0313 0301; # GREEK SMALL LETTER UPSILON WITH PSILI AND OXIA +1F56; F; 03C5 0313 0342; # GREEK SMALL LETTER UPSILON WITH PSILI AND PERISPOMENI +1F59; C; 1F51; # GREEK CAPITAL LETTER UPSILON WITH DASIA +1F5B; C; 1F53; # GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA +1F5D; C; 1F55; # GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA +1F5F; C; 1F57; # GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI +1F68; C; 1F60; # GREEK CAPITAL LETTER OMEGA WITH PSILI +1F69; C; 1F61; # GREEK CAPITAL LETTER OMEGA WITH DASIA +1F6A; C; 1F62; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA +1F6B; C; 1F63; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA +1F6C; C; 1F64; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA +1F6D; C; 1F65; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA +1F6E; C; 1F66; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI +1F6F; C; 1F67; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI +1F80; F; 1F00 03B9; # GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI +1F81; F; 1F01 03B9; # GREEK SMALL LETTER ALPHA WITH DASIA AND YPOGEGRAMMENI +1F82; F; 1F02 03B9; # GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA AND YPOGEGRAMMENI +1F83; F; 1F03 03B9; # GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA AND YPOGEGRAMMENI +1F84; F; 1F04 03B9; # GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA AND YPOGEGRAMMENI +1F85; F; 1F05 03B9; # GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA AND YPOGEGRAMMENI +1F86; F; 1F06 03B9; # GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI +1F87; F; 1F07 03B9; # GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI +1F88; F; 1F00 03B9; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI +1F88; S; 1F80; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI +1F89; F; 1F01 03B9; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI +1F89; S; 1F81; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI +1F8A; F; 1F02 03B9; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI +1F8A; S; 1F82; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI +1F8B; F; 1F03 03B9; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI +1F8B; S; 1F83; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI +1F8C; F; 1F04 03B9; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI +1F8C; S; 1F84; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI +1F8D; F; 1F05 03B9; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI +1F8D; S; 1F85; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI +1F8E; F; 1F06 03B9; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI +1F8E; S; 1F86; # GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI +1F8F; F; 1F07 03B9; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI +1F8F; S; 1F87; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI +1F90; F; 1F20 03B9; # GREEK SMALL LETTER ETA WITH PSILI AND YPOGEGRAMMENI +1F91; F; 1F21 03B9; # GREEK SMALL LETTER ETA WITH DASIA AND YPOGEGRAMMENI +1F92; F; 1F22 03B9; # GREEK SMALL LETTER ETA WITH PSILI AND VARIA AND YPOGEGRAMMENI +1F93; F; 1F23 03B9; # GREEK SMALL LETTER ETA WITH DASIA AND VARIA AND YPOGEGRAMMENI +1F94; F; 1F24 03B9; # GREEK SMALL LETTER ETA WITH PSILI AND OXIA AND YPOGEGRAMMENI +1F95; F; 1F25 03B9; # GREEK SMALL LETTER ETA WITH DASIA AND OXIA AND YPOGEGRAMMENI +1F96; F; 1F26 03B9; # GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI +1F97; F; 1F27 03B9; # GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI +1F98; F; 1F20 03B9; # GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI +1F98; S; 1F90; # GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI +1F99; F; 1F21 03B9; # GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI +1F99; S; 1F91; # GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI +1F9A; F; 1F22 03B9; # GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI +1F9A; S; 1F92; # GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI +1F9B; F; 1F23 03B9; # GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI +1F9B; S; 1F93; # GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI +1F9C; F; 1F24 03B9; # GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI +1F9C; S; 1F94; # GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI +1F9D; F; 1F25 03B9; # GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI +1F9D; S; 1F95; # GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI +1F9E; F; 1F26 03B9; # GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI +1F9E; S; 1F96; # GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI +1F9F; F; 1F27 03B9; # GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI +1F9F; S; 1F97; # GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI +1FA0; F; 1F60 03B9; # GREEK SMALL LETTER OMEGA WITH PSILI AND YPOGEGRAMMENI +1FA1; F; 1F61 03B9; # GREEK SMALL LETTER OMEGA WITH DASIA AND YPOGEGRAMMENI +1FA2; F; 1F62 03B9; # GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA AND YPOGEGRAMMENI +1FA3; F; 1F63 03B9; # GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA AND YPOGEGRAMMENI +1FA4; F; 1F64 03B9; # GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA AND YPOGEGRAMMENI +1FA5; F; 1F65 03B9; # GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA AND YPOGEGRAMMENI +1FA6; F; 1F66 03B9; # GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI +1FA7; F; 1F67 03B9; # GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI +1FA8; F; 1F60 03B9; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI +1FA8; S; 1FA0; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI +1FA9; F; 1F61 03B9; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI +1FA9; S; 1FA1; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI +1FAA; F; 1F62 03B9; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI +1FAA; S; 1FA2; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI +1FAB; F; 1F63 03B9; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI +1FAB; S; 1FA3; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI +1FAC; F; 1F64 03B9; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI +1FAC; S; 1FA4; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI +1FAD; F; 1F65 03B9; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI +1FAD; S; 1FA5; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI +1FAE; F; 1F66 03B9; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI +1FAE; S; 1FA6; # GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI +1FAF; F; 1F67 03B9; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI +1FAF; S; 1FA7; # GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI +1FB2; F; 1F70 03B9; # GREEK SMALL LETTER ALPHA WITH VARIA AND YPOGEGRAMMENI +1FB3; F; 03B1 03B9; # GREEK SMALL LETTER ALPHA WITH YPOGEGRAMMENI +1FB4; F; 03AC 03B9; # GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI +1FB6; F; 03B1 0342; # GREEK SMALL LETTER ALPHA WITH PERISPOMENI +1FB7; F; 03B1 0342 03B9; # GREEK SMALL LETTER ALPHA WITH PERISPOMENI AND YPOGEGRAMMENI +1FB8; C; 1FB0; # GREEK CAPITAL LETTER ALPHA WITH VRACHY +1FB9; C; 1FB1; # GREEK CAPITAL LETTER ALPHA WITH MACRON +1FBA; C; 1F70; # GREEK CAPITAL LETTER ALPHA WITH VARIA +1FBB; C; 1F71; # GREEK CAPITAL LETTER ALPHA WITH OXIA +1FBC; F; 03B1 03B9; # GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI +1FBC; S; 1FB3; # GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI +1FBE; C; 03B9; # GREEK PROSGEGRAMMENI +1FC2; F; 1F74 03B9; # GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI +1FC3; F; 03B7 03B9; # GREEK SMALL LETTER ETA WITH YPOGEGRAMMENI +1FC4; F; 03AE 03B9; # GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI +1FC6; F; 03B7 0342; # GREEK SMALL LETTER ETA WITH PERISPOMENI +1FC7; F; 03B7 0342 03B9; # GREEK SMALL LETTER ETA WITH PERISPOMENI AND YPOGEGRAMMENI +1FC8; C; 1F72; # GREEK CAPITAL LETTER EPSILON WITH VARIA +1FC9; C; 1F73; # GREEK CAPITAL LETTER EPSILON WITH OXIA +1FCA; C; 1F74; # GREEK CAPITAL LETTER ETA WITH VARIA +1FCB; C; 1F75; # GREEK CAPITAL LETTER ETA WITH OXIA +1FCC; F; 03B7 03B9; # GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI +1FCC; S; 1FC3; # GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI +1FD2; F; 03B9 0308 0300; # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND VARIA +1FD3; F; 03B9 0308 0301; # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA +1FD6; F; 03B9 0342; # GREEK SMALL LETTER IOTA WITH PERISPOMENI +1FD7; F; 03B9 0308 0342; # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND PERISPOMENI +1FD8; C; 1FD0; # GREEK CAPITAL LETTER IOTA WITH VRACHY +1FD9; C; 1FD1; # GREEK CAPITAL LETTER IOTA WITH MACRON +1FDA; C; 1F76; # GREEK CAPITAL LETTER IOTA WITH VARIA +1FDB; C; 1F77; # GREEK CAPITAL LETTER IOTA WITH OXIA +1FE2; F; 03C5 0308 0300; # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND VARIA +1FE3; F; 03C5 0308 0301; # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA +1FE4; F; 03C1 0313; # GREEK SMALL LETTER RHO WITH PSILI +1FE6; F; 03C5 0342; # GREEK SMALL LETTER UPSILON WITH PERISPOMENI +1FE7; F; 03C5 0308 0342; # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND PERISPOMENI +1FE8; C; 1FE0; # GREEK CAPITAL LETTER UPSILON WITH VRACHY +1FE9; C; 1FE1; # GREEK CAPITAL LETTER UPSILON WITH MACRON +1FEA; C; 1F7A; # GREEK CAPITAL LETTER UPSILON WITH VARIA +1FEB; C; 1F7B; # GREEK CAPITAL LETTER UPSILON WITH OXIA +1FEC; C; 1FE5; # GREEK CAPITAL LETTER RHO WITH DASIA +1FF2; F; 1F7C 03B9; # GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI +1FF3; F; 03C9 03B9; # GREEK SMALL LETTER OMEGA WITH YPOGEGRAMMENI +1FF4; F; 03CE 03B9; # GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI +1FF6; F; 03C9 0342; # GREEK SMALL LETTER OMEGA WITH PERISPOMENI +1FF7; F; 03C9 0342 03B9; # GREEK SMALL LETTER OMEGA WITH PERISPOMENI AND YPOGEGRAMMENI +1FF8; C; 1F78; # GREEK CAPITAL LETTER OMICRON WITH VARIA +1FF9; C; 1F79; # GREEK CAPITAL LETTER OMICRON WITH OXIA +1FFA; C; 1F7C; # GREEK CAPITAL LETTER OMEGA WITH VARIA +1FFB; C; 1F7D; # GREEK CAPITAL LETTER OMEGA WITH OXIA +1FFC; F; 03C9 03B9; # GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI +1FFC; S; 1FF3; # GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI +2126; C; 03C9; # OHM SIGN +212A; C; 006B; # KELVIN SIGN +212B; C; 00E5; # ANGSTROM SIGN +2132; C; 214E; # TURNED CAPITAL F +2160; C; 2170; # ROMAN NUMERAL ONE +2161; C; 2171; # ROMAN NUMERAL TWO +2162; C; 2172; # ROMAN NUMERAL THREE +2163; C; 2173; # ROMAN NUMERAL FOUR +2164; C; 2174; # ROMAN NUMERAL FIVE +2165; C; 2175; # ROMAN NUMERAL SIX +2166; C; 2176; # ROMAN NUMERAL SEVEN +2167; C; 2177; # ROMAN NUMERAL EIGHT +2168; C; 2178; # ROMAN NUMERAL NINE +2169; C; 2179; # ROMAN NUMERAL TEN +216A; C; 217A; # ROMAN NUMERAL ELEVEN +216B; C; 217B; # ROMAN NUMERAL TWELVE +216C; C; 217C; # ROMAN NUMERAL FIFTY +216D; C; 217D; # ROMAN NUMERAL ONE HUNDRED +216E; C; 217E; # ROMAN NUMERAL FIVE HUNDRED +216F; C; 217F; # ROMAN NUMERAL ONE THOUSAND +2183; C; 2184; # ROMAN NUMERAL REVERSED ONE HUNDRED +24B6; C; 24D0; # CIRCLED LATIN CAPITAL LETTER A +24B7; C; 24D1; # CIRCLED LATIN CAPITAL LETTER B +24B8; C; 24D2; # CIRCLED LATIN CAPITAL LETTER C +24B9; C; 24D3; # CIRCLED LATIN CAPITAL LETTER D +24BA; C; 24D4; # CIRCLED LATIN CAPITAL LETTER E +24BB; C; 24D5; # CIRCLED LATIN CAPITAL LETTER F +24BC; C; 24D6; # CIRCLED LATIN CAPITAL LETTER G +24BD; C; 24D7; # CIRCLED LATIN CAPITAL LETTER H +24BE; C; 24D8; # CIRCLED LATIN CAPITAL LETTER I +24BF; C; 24D9; # CIRCLED LATIN CAPITAL LETTER J +24C0; C; 24DA; # CIRCLED LATIN CAPITAL LETTER K +24C1; C; 24DB; # CIRCLED LATIN CAPITAL LETTER L +24C2; C; 24DC; # CIRCLED LATIN CAPITAL LETTER M +24C3; C; 24DD; # CIRCLED LATIN CAPITAL LETTER N +24C4; C; 24DE; # CIRCLED LATIN CAPITAL LETTER O +24C5; C; 24DF; # CIRCLED LATIN CAPITAL LETTER P +24C6; C; 24E0; # CIRCLED LATIN CAPITAL LETTER Q +24C7; C; 24E1; # CIRCLED LATIN CAPITAL LETTER R +24C8; C; 24E2; # CIRCLED LATIN CAPITAL LETTER S +24C9; C; 24E3; # CIRCLED LATIN CAPITAL LETTER T +24CA; C; 24E4; # CIRCLED LATIN CAPITAL LETTER U +24CB; C; 24E5; # CIRCLED LATIN CAPITAL LETTER V +24CC; C; 24E6; # CIRCLED LATIN CAPITAL LETTER W +24CD; C; 24E7; # CIRCLED LATIN CAPITAL LETTER X +24CE; C; 24E8; # CIRCLED LATIN CAPITAL LETTER Y +24CF; C; 24E9; # CIRCLED LATIN CAPITAL LETTER Z +2C00; C; 2C30; # GLAGOLITIC CAPITAL LETTER AZU +2C01; C; 2C31; # GLAGOLITIC CAPITAL LETTER BUKY +2C02; C; 2C32; # GLAGOLITIC CAPITAL LETTER VEDE +2C03; C; 2C33; # GLAGOLITIC CAPITAL LETTER GLAGOLI +2C04; C; 2C34; # GLAGOLITIC CAPITAL LETTER DOBRO +2C05; C; 2C35; # GLAGOLITIC CAPITAL LETTER YESTU +2C06; C; 2C36; # GLAGOLITIC CAPITAL LETTER ZHIVETE +2C07; C; 2C37; # GLAGOLITIC CAPITAL LETTER DZELO +2C08; C; 2C38; # GLAGOLITIC CAPITAL LETTER ZEMLJA +2C09; C; 2C39; # GLAGOLITIC CAPITAL LETTER IZHE +2C0A; C; 2C3A; # GLAGOLITIC CAPITAL LETTER INITIAL IZHE +2C0B; C; 2C3B; # GLAGOLITIC CAPITAL LETTER I +2C0C; C; 2C3C; # GLAGOLITIC CAPITAL LETTER DJERVI +2C0D; C; 2C3D; # GLAGOLITIC CAPITAL LETTER KAKO +2C0E; C; 2C3E; # GLAGOLITIC CAPITAL LETTER LJUDIJE +2C0F; C; 2C3F; # GLAGOLITIC CAPITAL LETTER MYSLITE +2C10; C; 2C40; # GLAGOLITIC CAPITAL LETTER NASHI +2C11; C; 2C41; # GLAGOLITIC CAPITAL LETTER ONU +2C12; C; 2C42; # GLAGOLITIC CAPITAL LETTER POKOJI +2C13; C; 2C43; # GLAGOLITIC CAPITAL LETTER RITSI +2C14; C; 2C44; # GLAGOLITIC CAPITAL LETTER SLOVO +2C15; C; 2C45; # GLAGOLITIC CAPITAL LETTER TVRIDO +2C16; C; 2C46; # GLAGOLITIC CAPITAL LETTER UKU +2C17; C; 2C47; # GLAGOLITIC CAPITAL LETTER FRITU +2C18; C; 2C48; # GLAGOLITIC CAPITAL LETTER HERU +2C19; C; 2C49; # GLAGOLITIC CAPITAL LETTER OTU +2C1A; C; 2C4A; # GLAGOLITIC CAPITAL LETTER PE +2C1B; C; 2C4B; # GLAGOLITIC CAPITAL LETTER SHTA +2C1C; C; 2C4C; # GLAGOLITIC CAPITAL LETTER TSI +2C1D; C; 2C4D; # GLAGOLITIC CAPITAL LETTER CHRIVI +2C1E; C; 2C4E; # GLAGOLITIC CAPITAL LETTER SHA +2C1F; C; 2C4F; # GLAGOLITIC CAPITAL LETTER YERU +2C20; C; 2C50; # GLAGOLITIC CAPITAL LETTER YERI +2C21; C; 2C51; # GLAGOLITIC CAPITAL LETTER YATI +2C22; C; 2C52; # GLAGOLITIC CAPITAL LETTER SPIDERY HA +2C23; C; 2C53; # GLAGOLITIC CAPITAL LETTER YU +2C24; C; 2C54; # GLAGOLITIC CAPITAL LETTER SMALL YUS +2C25; C; 2C55; # GLAGOLITIC CAPITAL LETTER SMALL YUS WITH TAIL +2C26; C; 2C56; # GLAGOLITIC CAPITAL LETTER YO +2C27; C; 2C57; # GLAGOLITIC CAPITAL LETTER IOTATED SMALL YUS +2C28; C; 2C58; # GLAGOLITIC CAPITAL LETTER BIG YUS +2C29; C; 2C59; # GLAGOLITIC CAPITAL LETTER IOTATED BIG YUS +2C2A; C; 2C5A; # GLAGOLITIC CAPITAL LETTER FITA +2C2B; C; 2C5B; # GLAGOLITIC CAPITAL LETTER IZHITSA +2C2C; C; 2C5C; # GLAGOLITIC CAPITAL LETTER SHTAPIC +2C2D; C; 2C5D; # GLAGOLITIC CAPITAL LETTER TROKUTASTI A +2C2E; C; 2C5E; # GLAGOLITIC CAPITAL LETTER LATINATE MYSLITE +2C60; C; 2C61; # LATIN CAPITAL LETTER L WITH DOUBLE BAR +2C62; C; 026B; # LATIN CAPITAL LETTER L WITH MIDDLE TILDE +2C63; C; 1D7D; # LATIN CAPITAL LETTER P WITH STROKE +2C64; C; 027D; # LATIN CAPITAL LETTER R WITH TAIL +2C67; C; 2C68; # LATIN CAPITAL LETTER H WITH DESCENDER +2C69; C; 2C6A; # LATIN CAPITAL LETTER K WITH DESCENDER +2C6B; C; 2C6C; # LATIN CAPITAL LETTER Z WITH DESCENDER +2C6D; C; 0251; # LATIN CAPITAL LETTER ALPHA +2C6E; C; 0271; # LATIN CAPITAL LETTER M WITH HOOK +2C6F; C; 0250; # LATIN CAPITAL LETTER TURNED A +2C70; C; 0252; # LATIN CAPITAL LETTER TURNED ALPHA +2C72; C; 2C73; # LATIN CAPITAL LETTER W WITH HOOK +2C75; C; 2C76; # LATIN CAPITAL LETTER HALF H +2C7E; C; 023F; # LATIN CAPITAL LETTER S WITH SWASH TAIL +2C7F; C; 0240; # LATIN CAPITAL LETTER Z WITH SWASH TAIL +2C80; C; 2C81; # COPTIC CAPITAL LETTER ALFA +2C82; C; 2C83; # COPTIC CAPITAL LETTER VIDA +2C84; C; 2C85; # COPTIC CAPITAL LETTER GAMMA +2C86; C; 2C87; # COPTIC CAPITAL LETTER DALDA +2C88; C; 2C89; # COPTIC CAPITAL LETTER EIE +2C8A; C; 2C8B; # COPTIC CAPITAL LETTER SOU +2C8C; C; 2C8D; # COPTIC CAPITAL LETTER ZATA +2C8E; C; 2C8F; # COPTIC CAPITAL LETTER HATE +2C90; C; 2C91; # COPTIC CAPITAL LETTER THETHE +2C92; C; 2C93; # COPTIC CAPITAL LETTER IAUDA +2C94; C; 2C95; # COPTIC CAPITAL LETTER KAPA +2C96; C; 2C97; # COPTIC CAPITAL LETTER LAULA +2C98; C; 2C99; # COPTIC CAPITAL LETTER MI +2C9A; C; 2C9B; # COPTIC CAPITAL LETTER NI +2C9C; C; 2C9D; # COPTIC CAPITAL LETTER KSI +2C9E; C; 2C9F; # COPTIC CAPITAL LETTER O +2CA0; C; 2CA1; # COPTIC CAPITAL LETTER PI +2CA2; C; 2CA3; # COPTIC CAPITAL LETTER RO +2CA4; C; 2CA5; # COPTIC CAPITAL LETTER SIMA +2CA6; C; 2CA7; # COPTIC CAPITAL LETTER TAU +2CA8; C; 2CA9; # COPTIC CAPITAL LETTER UA +2CAA; C; 2CAB; # COPTIC CAPITAL LETTER FI +2CAC; C; 2CAD; # COPTIC CAPITAL LETTER KHI +2CAE; C; 2CAF; # COPTIC CAPITAL LETTER PSI +2CB0; C; 2CB1; # COPTIC CAPITAL LETTER OOU +2CB2; C; 2CB3; # COPTIC CAPITAL LETTER DIALECT-P ALEF +2CB4; C; 2CB5; # COPTIC CAPITAL LETTER OLD COPTIC AIN +2CB6; C; 2CB7; # COPTIC CAPITAL LETTER CRYPTOGRAMMIC EIE +2CB8; C; 2CB9; # COPTIC CAPITAL LETTER DIALECT-P KAPA +2CBA; C; 2CBB; # COPTIC CAPITAL LETTER DIALECT-P NI +2CBC; C; 2CBD; # COPTIC CAPITAL LETTER CRYPTOGRAMMIC NI +2CBE; C; 2CBF; # COPTIC CAPITAL LETTER OLD COPTIC OOU +2CC0; C; 2CC1; # COPTIC CAPITAL LETTER SAMPI +2CC2; C; 2CC3; # COPTIC CAPITAL LETTER CROSSED SHEI +2CC4; C; 2CC5; # COPTIC CAPITAL LETTER OLD COPTIC SHEI +2CC6; C; 2CC7; # COPTIC CAPITAL LETTER OLD COPTIC ESH +2CC8; C; 2CC9; # COPTIC CAPITAL LETTER AKHMIMIC KHEI +2CCA; C; 2CCB; # COPTIC CAPITAL LETTER DIALECT-P HORI +2CCC; C; 2CCD; # COPTIC CAPITAL LETTER OLD COPTIC HORI +2CCE; C; 2CCF; # COPTIC CAPITAL LETTER OLD COPTIC HA +2CD0; C; 2CD1; # COPTIC CAPITAL LETTER L-SHAPED HA +2CD2; C; 2CD3; # COPTIC CAPITAL LETTER OLD COPTIC HEI +2CD4; C; 2CD5; # COPTIC CAPITAL LETTER OLD COPTIC HAT +2CD6; C; 2CD7; # COPTIC CAPITAL LETTER OLD COPTIC GANGIA +2CD8; C; 2CD9; # COPTIC CAPITAL LETTER OLD COPTIC DJA +2CDA; C; 2CDB; # COPTIC CAPITAL LETTER OLD COPTIC SHIMA +2CDC; C; 2CDD; # COPTIC CAPITAL LETTER OLD NUBIAN SHIMA +2CDE; C; 2CDF; # COPTIC CAPITAL LETTER OLD NUBIAN NGI +2CE0; C; 2CE1; # COPTIC CAPITAL LETTER OLD NUBIAN NYI +2CE2; C; 2CE3; # COPTIC CAPITAL LETTER OLD NUBIAN WAU +2CEB; C; 2CEC; # COPTIC CAPITAL LETTER CRYPTOGRAMMIC SHEI +2CED; C; 2CEE; # COPTIC CAPITAL LETTER CRYPTOGRAMMIC GANGIA +2CF2; C; 2CF3; # COPTIC CAPITAL LETTER BOHAIRIC KHEI +A640; C; A641; # CYRILLIC CAPITAL LETTER ZEMLYA +A642; C; A643; # CYRILLIC CAPITAL LETTER DZELO +A644; C; A645; # CYRILLIC CAPITAL LETTER REVERSED DZE +A646; C; A647; # CYRILLIC CAPITAL LETTER IOTA +A648; C; A649; # CYRILLIC CAPITAL LETTER DJERV +A64A; C; A64B; # CYRILLIC CAPITAL LETTER MONOGRAPH UK +A64C; C; A64D; # CYRILLIC CAPITAL LETTER BROAD OMEGA +A64E; C; A64F; # CYRILLIC CAPITAL LETTER NEUTRAL YER +A650; C; A651; # CYRILLIC CAPITAL LETTER YERU WITH BACK YER +A652; C; A653; # CYRILLIC CAPITAL LETTER IOTIFIED YAT +A654; C; A655; # CYRILLIC CAPITAL LETTER REVERSED YU +A656; C; A657; # CYRILLIC CAPITAL LETTER IOTIFIED A +A658; C; A659; # CYRILLIC CAPITAL LETTER CLOSED LITTLE YUS +A65A; C; A65B; # CYRILLIC CAPITAL LETTER BLENDED YUS +A65C; C; A65D; # CYRILLIC CAPITAL LETTER IOTIFIED CLOSED LITTLE YUS +A65E; C; A65F; # CYRILLIC CAPITAL LETTER YN +A660; C; A661; # CYRILLIC CAPITAL LETTER REVERSED TSE +A662; C; A663; # CYRILLIC CAPITAL LETTER SOFT DE +A664; C; A665; # CYRILLIC CAPITAL LETTER SOFT EL +A666; C; A667; # CYRILLIC CAPITAL LETTER SOFT EM +A668; C; A669; # CYRILLIC CAPITAL LETTER MONOCULAR O +A66A; C; A66B; # CYRILLIC CAPITAL LETTER BINOCULAR O +A66C; C; A66D; # CYRILLIC CAPITAL LETTER DOUBLE MONOCULAR O +A680; C; A681; # CYRILLIC CAPITAL LETTER DWE +A682; C; A683; # CYRILLIC CAPITAL LETTER DZWE +A684; C; A685; # CYRILLIC CAPITAL LETTER ZHWE +A686; C; A687; # CYRILLIC CAPITAL LETTER CCHE +A688; C; A689; # CYRILLIC CAPITAL LETTER DZZE +A68A; C; A68B; # CYRILLIC CAPITAL LETTER TE WITH MIDDLE HOOK +A68C; C; A68D; # CYRILLIC CAPITAL LETTER TWE +A68E; C; A68F; # CYRILLIC CAPITAL LETTER TSWE +A690; C; A691; # CYRILLIC CAPITAL LETTER TSSE +A692; C; A693; # CYRILLIC CAPITAL LETTER TCHE +A694; C; A695; # CYRILLIC CAPITAL LETTER HWE +A696; C; A697; # CYRILLIC CAPITAL LETTER SHWE +A722; C; A723; # LATIN CAPITAL LETTER EGYPTOLOGICAL ALEF +A724; C; A725; # LATIN CAPITAL LETTER EGYPTOLOGICAL AIN +A726; C; A727; # LATIN CAPITAL LETTER HENG +A728; C; A729; # LATIN CAPITAL LETTER TZ +A72A; C; A72B; # LATIN CAPITAL LETTER TRESILLO +A72C; C; A72D; # LATIN CAPITAL LETTER CUATRILLO +A72E; C; A72F; # LATIN CAPITAL LETTER CUATRILLO WITH COMMA +A732; C; A733; # LATIN CAPITAL LETTER AA +A734; C; A735; # LATIN CAPITAL LETTER AO +A736; C; A737; # LATIN CAPITAL LETTER AU +A738; C; A739; # LATIN CAPITAL LETTER AV +A73A; C; A73B; # LATIN CAPITAL LETTER AV WITH HORIZONTAL BAR +A73C; C; A73D; # LATIN CAPITAL LETTER AY +A73E; C; A73F; # LATIN CAPITAL LETTER REVERSED C WITH DOT +A740; C; A741; # LATIN CAPITAL LETTER K WITH STROKE +A742; C; A743; # LATIN CAPITAL LETTER K WITH DIAGONAL STROKE +A744; C; A745; # LATIN CAPITAL LETTER K WITH STROKE AND DIAGONAL STROKE +A746; C; A747; # LATIN CAPITAL LETTER BROKEN L +A748; C; A749; # LATIN CAPITAL LETTER L WITH HIGH STROKE +A74A; C; A74B; # LATIN CAPITAL LETTER O WITH LONG STROKE OVERLAY +A74C; C; A74D; # LATIN CAPITAL LETTER O WITH LOOP +A74E; C; A74F; # LATIN CAPITAL LETTER OO +A750; C; A751; # LATIN CAPITAL LETTER P WITH STROKE THROUGH DESCENDER +A752; C; A753; # LATIN CAPITAL LETTER P WITH FLOURISH +A754; C; A755; # LATIN CAPITAL LETTER P WITH SQUIRREL TAIL +A756; C; A757; # LATIN CAPITAL LETTER Q WITH STROKE THROUGH DESCENDER +A758; C; A759; # LATIN CAPITAL LETTER Q WITH DIAGONAL STROKE +A75A; C; A75B; # LATIN CAPITAL LETTER R ROTUNDA +A75C; C; A75D; # LATIN CAPITAL LETTER RUM ROTUNDA +A75E; C; A75F; # LATIN CAPITAL LETTER V WITH DIAGONAL STROKE +A760; C; A761; # LATIN CAPITAL LETTER VY +A762; C; A763; # LATIN CAPITAL LETTER VISIGOTHIC Z +A764; C; A765; # LATIN CAPITAL LETTER THORN WITH STROKE +A766; C; A767; # LATIN CAPITAL LETTER THORN WITH STROKE THROUGH DESCENDER +A768; C; A769; # LATIN CAPITAL LETTER VEND +A76A; C; A76B; # LATIN CAPITAL LETTER ET +A76C; C; A76D; # LATIN CAPITAL LETTER IS +A76E; C; A76F; # LATIN CAPITAL LETTER CON +A779; C; A77A; # LATIN CAPITAL LETTER INSULAR D +A77B; C; A77C; # LATIN CAPITAL LETTER INSULAR F +A77D; C; 1D79; # LATIN CAPITAL LETTER INSULAR G +A77E; C; A77F; # LATIN CAPITAL LETTER TURNED INSULAR G +A780; C; A781; # LATIN CAPITAL LETTER TURNED L +A782; C; A783; # LATIN CAPITAL LETTER INSULAR R +A784; C; A785; # LATIN CAPITAL LETTER INSULAR S +A786; C; A787; # LATIN CAPITAL LETTER INSULAR T +A78B; C; A78C; # LATIN CAPITAL LETTER SALTILLO +A78D; C; 0265; # LATIN CAPITAL LETTER TURNED H +A790; C; A791; # LATIN CAPITAL LETTER N WITH DESCENDER +A792; C; A793; # LATIN CAPITAL LETTER C WITH BAR +A7A0; C; A7A1; # LATIN CAPITAL LETTER G WITH OBLIQUE STROKE +A7A2; C; A7A3; # LATIN CAPITAL LETTER K WITH OBLIQUE STROKE +A7A4; C; A7A5; # LATIN CAPITAL LETTER N WITH OBLIQUE STROKE +A7A6; C; A7A7; # LATIN CAPITAL LETTER R WITH OBLIQUE STROKE +A7A8; C; A7A9; # LATIN CAPITAL LETTER S WITH OBLIQUE STROKE +A7AA; C; 0266; # LATIN CAPITAL LETTER H WITH HOOK +FB00; F; 0066 0066; # LATIN SMALL LIGATURE FF +FB01; F; 0066 0069; # LATIN SMALL LIGATURE FI +FB02; F; 0066 006C; # LATIN SMALL LIGATURE FL +FB03; F; 0066 0066 0069; # LATIN SMALL LIGATURE FFI +FB04; F; 0066 0066 006C; # LATIN SMALL LIGATURE FFL +FB05; F; 0073 0074; # LATIN SMALL LIGATURE LONG S T +FB06; F; 0073 0074; # LATIN SMALL LIGATURE ST +FB13; F; 0574 0576; # ARMENIAN SMALL LIGATURE MEN NOW +FB14; F; 0574 0565; # ARMENIAN SMALL LIGATURE MEN ECH +FB15; F; 0574 056B; # ARMENIAN SMALL LIGATURE MEN INI +FB16; F; 057E 0576; # ARMENIAN SMALL LIGATURE VEW NOW +FB17; F; 0574 056D; # ARMENIAN SMALL LIGATURE MEN XEH +FF21; C; FF41; # FULLWIDTH LATIN CAPITAL LETTER A +FF22; C; FF42; # FULLWIDTH LATIN CAPITAL LETTER B +FF23; C; FF43; # FULLWIDTH LATIN CAPITAL LETTER C +FF24; C; FF44; # FULLWIDTH LATIN CAPITAL LETTER D +FF25; C; FF45; # FULLWIDTH LATIN CAPITAL LETTER E +FF26; C; FF46; # FULLWIDTH LATIN CAPITAL LETTER F +FF27; C; FF47; # FULLWIDTH LATIN CAPITAL LETTER G +FF28; C; FF48; # FULLWIDTH LATIN CAPITAL LETTER H +FF29; C; FF49; # FULLWIDTH LATIN CAPITAL LETTER I +FF2A; C; FF4A; # FULLWIDTH LATIN CAPITAL LETTER J +FF2B; C; FF4B; # FULLWIDTH LATIN CAPITAL LETTER K +FF2C; C; FF4C; # FULLWIDTH LATIN CAPITAL LETTER L +FF2D; C; FF4D; # FULLWIDTH LATIN CAPITAL LETTER M +FF2E; C; FF4E; # FULLWIDTH LATIN CAPITAL LETTER N +FF2F; C; FF4F; # FULLWIDTH LATIN CAPITAL LETTER O +FF30; C; FF50; # FULLWIDTH LATIN CAPITAL LETTER P +FF31; C; FF51; # FULLWIDTH LATIN CAPITAL LETTER Q +FF32; C; FF52; # FULLWIDTH LATIN CAPITAL LETTER R +FF33; C; FF53; # FULLWIDTH LATIN CAPITAL LETTER S +FF34; C; FF54; # FULLWIDTH LATIN CAPITAL LETTER T +FF35; C; FF55; # FULLWIDTH LATIN CAPITAL LETTER U +FF36; C; FF56; # FULLWIDTH LATIN CAPITAL LETTER V +FF37; C; FF57; # FULLWIDTH LATIN CAPITAL LETTER W +FF38; C; FF58; # FULLWIDTH LATIN CAPITAL LETTER X +FF39; C; FF59; # FULLWIDTH LATIN CAPITAL LETTER Y +FF3A; C; FF5A; # FULLWIDTH LATIN CAPITAL LETTER Z +10400; C; 10428; # DESERET CAPITAL LETTER LONG I +10401; C; 10429; # DESERET CAPITAL LETTER LONG E +10402; C; 1042A; # DESERET CAPITAL LETTER LONG A +10403; C; 1042B; # DESERET CAPITAL LETTER LONG AH +10404; C; 1042C; # DESERET CAPITAL LETTER LONG O +10405; C; 1042D; # DESERET CAPITAL LETTER LONG OO +10406; C; 1042E; # DESERET CAPITAL LETTER SHORT I +10407; C; 1042F; # DESERET CAPITAL LETTER SHORT E +10408; C; 10430; # DESERET CAPITAL LETTER SHORT A +10409; C; 10431; # DESERET CAPITAL LETTER SHORT AH +1040A; C; 10432; # DESERET CAPITAL LETTER SHORT O +1040B; C; 10433; # DESERET CAPITAL LETTER SHORT OO +1040C; C; 10434; # DESERET CAPITAL LETTER AY +1040D; C; 10435; # DESERET CAPITAL LETTER OW +1040E; C; 10436; # DESERET CAPITAL LETTER WU +1040F; C; 10437; # DESERET CAPITAL LETTER YEE +10410; C; 10438; # DESERET CAPITAL LETTER H +10411; C; 10439; # DESERET CAPITAL LETTER PEE +10412; C; 1043A; # DESERET CAPITAL LETTER BEE +10413; C; 1043B; # DESERET CAPITAL LETTER TEE +10414; C; 1043C; # DESERET CAPITAL LETTER DEE +10415; C; 1043D; # DESERET CAPITAL LETTER CHEE +10416; C; 1043E; # DESERET CAPITAL LETTER JEE +10417; C; 1043F; # DESERET CAPITAL LETTER KAY +10418; C; 10440; # DESERET CAPITAL LETTER GAY +10419; C; 10441; # DESERET CAPITAL LETTER EF +1041A; C; 10442; # DESERET CAPITAL LETTER VEE +1041B; C; 10443; # DESERET CAPITAL LETTER ETH +1041C; C; 10444; # DESERET CAPITAL LETTER THEE +1041D; C; 10445; # DESERET CAPITAL LETTER ES +1041E; C; 10446; # DESERET CAPITAL LETTER ZEE +1041F; C; 10447; # DESERET CAPITAL LETTER ESH +10420; C; 10448; # DESERET CAPITAL LETTER ZHEE +10421; C; 10449; # DESERET CAPITAL LETTER ER +10422; C; 1044A; # DESERET CAPITAL LETTER EL +10423; C; 1044B; # DESERET CAPITAL LETTER EM +10424; C; 1044C; # DESERET CAPITAL LETTER EN +10425; C; 1044D; # DESERET CAPITAL LETTER ENG +10426; C; 1044E; # DESERET CAPITAL LETTER OI +10427; C; 1044F; # DESERET CAPITAL LETTER EW diff --git a/components/external/SQLite-3.8.1/ext/fts3/unicode/UnicodeData.txt b/components/external/SQLite-3.8.1/ext/fts3/unicode/UnicodeData.txt new file mode 100644 index 0000000000000000000000000000000000000000..9f204050c6bb2e587cb1c3154372b8131f9e2f28 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/unicode/UnicodeData.txt @@ -0,0 +1,24428 @@ +0000;;Cc;0;BN;;;;;N;NULL;;;; +0001;;Cc;0;BN;;;;;N;START OF HEADING;;;; +0002;;Cc;0;BN;;;;;N;START OF TEXT;;;; +0003;;Cc;0;BN;;;;;N;END OF TEXT;;;; +0004;;Cc;0;BN;;;;;N;END OF TRANSMISSION;;;; +0005;;Cc;0;BN;;;;;N;ENQUIRY;;;; +0006;;Cc;0;BN;;;;;N;ACKNOWLEDGE;;;; +0007;;Cc;0;BN;;;;;N;BELL;;;; +0008;;Cc;0;BN;;;;;N;BACKSPACE;;;; +0009;;Cc;0;S;;;;;N;CHARACTER TABULATION;;;; +000A;;Cc;0;B;;;;;N;LINE FEED (LF);;;; +000B;;Cc;0;S;;;;;N;LINE TABULATION;;;; +000C;;Cc;0;WS;;;;;N;FORM FEED (FF);;;; +000D;;Cc;0;B;;;;;N;CARRIAGE RETURN (CR);;;; +000E;;Cc;0;BN;;;;;N;SHIFT OUT;;;; +000F;;Cc;0;BN;;;;;N;SHIFT IN;;;; +0010;;Cc;0;BN;;;;;N;DATA LINK ESCAPE;;;; +0011;;Cc;0;BN;;;;;N;DEVICE CONTROL ONE;;;; +0012;;Cc;0;BN;;;;;N;DEVICE CONTROL TWO;;;; +0013;;Cc;0;BN;;;;;N;DEVICE CONTROL THREE;;;; +0014;;Cc;0;BN;;;;;N;DEVICE CONTROL FOUR;;;; +0015;;Cc;0;BN;;;;;N;NEGATIVE ACKNOWLEDGE;;;; +0016;;Cc;0;BN;;;;;N;SYNCHRONOUS IDLE;;;; +0017;;Cc;0;BN;;;;;N;END OF TRANSMISSION BLOCK;;;; +0018;;Cc;0;BN;;;;;N;CANCEL;;;; +0019;;Cc;0;BN;;;;;N;END OF MEDIUM;;;; +001A;;Cc;0;BN;;;;;N;SUBSTITUTE;;;; +001B;;Cc;0;BN;;;;;N;ESCAPE;;;; +001C;;Cc;0;B;;;;;N;INFORMATION SEPARATOR FOUR;;;; +001D;;Cc;0;B;;;;;N;INFORMATION SEPARATOR THREE;;;; +001E;;Cc;0;B;;;;;N;INFORMATION SEPARATOR TWO;;;; +001F;;Cc;0;S;;;;;N;INFORMATION SEPARATOR ONE;;;; +0020;SPACE;Zs;0;WS;;;;;N;;;;; +0021;EXCLAMATION MARK;Po;0;ON;;;;;N;;;;; +0022;QUOTATION MARK;Po;0;ON;;;;;N;;;;; +0023;NUMBER SIGN;Po;0;ET;;;;;N;;;;; +0024;DOLLAR SIGN;Sc;0;ET;;;;;N;;;;; +0025;PERCENT SIGN;Po;0;ET;;;;;N;;;;; +0026;AMPERSAND;Po;0;ON;;;;;N;;;;; +0027;APOSTROPHE;Po;0;ON;;;;;N;APOSTROPHE-QUOTE;;;; +0028;LEFT PARENTHESIS;Ps;0;ON;;;;;Y;OPENING PARENTHESIS;;;; +0029;RIGHT PARENTHESIS;Pe;0;ON;;;;;Y;CLOSING PARENTHESIS;;;; +002A;ASTERISK;Po;0;ON;;;;;N;;;;; +002B;PLUS SIGN;Sm;0;ES;;;;;N;;;;; +002C;COMMA;Po;0;CS;;;;;N;;;;; +002D;HYPHEN-MINUS;Pd;0;ES;;;;;N;;;;; +002E;FULL STOP;Po;0;CS;;;;;N;PERIOD;;;; +002F;SOLIDUS;Po;0;CS;;;;;N;SLASH;;;; +0030;DIGIT ZERO;Nd;0;EN;;0;0;0;N;;;;; +0031;DIGIT ONE;Nd;0;EN;;1;1;1;N;;;;; +0032;DIGIT TWO;Nd;0;EN;;2;2;2;N;;;;; +0033;DIGIT THREE;Nd;0;EN;;3;3;3;N;;;;; +0034;DIGIT FOUR;Nd;0;EN;;4;4;4;N;;;;; +0035;DIGIT FIVE;Nd;0;EN;;5;5;5;N;;;;; +0036;DIGIT SIX;Nd;0;EN;;6;6;6;N;;;;; +0037;DIGIT SEVEN;Nd;0;EN;;7;7;7;N;;;;; +0038;DIGIT EIGHT;Nd;0;EN;;8;8;8;N;;;;; +0039;DIGIT NINE;Nd;0;EN;;9;9;9;N;;;;; +003A;COLON;Po;0;CS;;;;;N;;;;; +003B;SEMICOLON;Po;0;ON;;;;;N;;;;; +003C;LESS-THAN SIGN;Sm;0;ON;;;;;Y;;;;; +003D;EQUALS SIGN;Sm;0;ON;;;;;N;;;;; +003E;GREATER-THAN SIGN;Sm;0;ON;;;;;Y;;;;; +003F;QUESTION MARK;Po;0;ON;;;;;N;;;;; +0040;COMMERCIAL AT;Po;0;ON;;;;;N;;;;; +0041;LATIN CAPITAL LETTER A;Lu;0;L;;;;;N;;;;0061; +0042;LATIN CAPITAL LETTER B;Lu;0;L;;;;;N;;;;0062; +0043;LATIN CAPITAL LETTER C;Lu;0;L;;;;;N;;;;0063; +0044;LATIN CAPITAL LETTER D;Lu;0;L;;;;;N;;;;0064; +0045;LATIN CAPITAL LETTER E;Lu;0;L;;;;;N;;;;0065; +0046;LATIN CAPITAL LETTER F;Lu;0;L;;;;;N;;;;0066; +0047;LATIN CAPITAL LETTER G;Lu;0;L;;;;;N;;;;0067; +0048;LATIN CAPITAL LETTER H;Lu;0;L;;;;;N;;;;0068; +0049;LATIN CAPITAL LETTER I;Lu;0;L;;;;;N;;;;0069; +004A;LATIN CAPITAL LETTER J;Lu;0;L;;;;;N;;;;006A; +004B;LATIN CAPITAL LETTER K;Lu;0;L;;;;;N;;;;006B; +004C;LATIN CAPITAL LETTER L;Lu;0;L;;;;;N;;;;006C; +004D;LATIN CAPITAL LETTER M;Lu;0;L;;;;;N;;;;006D; +004E;LATIN CAPITAL LETTER N;Lu;0;L;;;;;N;;;;006E; +004F;LATIN CAPITAL LETTER O;Lu;0;L;;;;;N;;;;006F; +0050;LATIN CAPITAL LETTER P;Lu;0;L;;;;;N;;;;0070; +0051;LATIN CAPITAL LETTER Q;Lu;0;L;;;;;N;;;;0071; +0052;LATIN CAPITAL LETTER R;Lu;0;L;;;;;N;;;;0072; +0053;LATIN CAPITAL LETTER S;Lu;0;L;;;;;N;;;;0073; +0054;LATIN CAPITAL LETTER T;Lu;0;L;;;;;N;;;;0074; +0055;LATIN CAPITAL LETTER U;Lu;0;L;;;;;N;;;;0075; +0056;LATIN CAPITAL LETTER V;Lu;0;L;;;;;N;;;;0076; +0057;LATIN CAPITAL LETTER W;Lu;0;L;;;;;N;;;;0077; +0058;LATIN CAPITAL LETTER X;Lu;0;L;;;;;N;;;;0078; +0059;LATIN CAPITAL LETTER Y;Lu;0;L;;;;;N;;;;0079; +005A;LATIN CAPITAL LETTER Z;Lu;0;L;;;;;N;;;;007A; +005B;LEFT SQUARE BRACKET;Ps;0;ON;;;;;Y;OPENING SQUARE BRACKET;;;; +005C;REVERSE SOLIDUS;Po;0;ON;;;;;N;BACKSLASH;;;; +005D;RIGHT SQUARE BRACKET;Pe;0;ON;;;;;Y;CLOSING SQUARE BRACKET;;;; +005E;CIRCUMFLEX ACCENT;Sk;0;ON;;;;;N;SPACING CIRCUMFLEX;;;; +005F;LOW LINE;Pc;0;ON;;;;;N;SPACING UNDERSCORE;;;; +0060;GRAVE ACCENT;Sk;0;ON;;;;;N;SPACING GRAVE;;;; +0061;LATIN SMALL LETTER A;Ll;0;L;;;;;N;;;0041;;0041 +0062;LATIN SMALL LETTER B;Ll;0;L;;;;;N;;;0042;;0042 +0063;LATIN SMALL LETTER C;Ll;0;L;;;;;N;;;0043;;0043 +0064;LATIN SMALL LETTER D;Ll;0;L;;;;;N;;;0044;;0044 +0065;LATIN SMALL LETTER E;Ll;0;L;;;;;N;;;0045;;0045 +0066;LATIN SMALL LETTER F;Ll;0;L;;;;;N;;;0046;;0046 +0067;LATIN SMALL LETTER G;Ll;0;L;;;;;N;;;0047;;0047 +0068;LATIN SMALL LETTER H;Ll;0;L;;;;;N;;;0048;;0048 +0069;LATIN SMALL LETTER I;Ll;0;L;;;;;N;;;0049;;0049 +006A;LATIN SMALL LETTER J;Ll;0;L;;;;;N;;;004A;;004A +006B;LATIN SMALL LETTER K;Ll;0;L;;;;;N;;;004B;;004B +006C;LATIN SMALL LETTER L;Ll;0;L;;;;;N;;;004C;;004C +006D;LATIN SMALL LETTER M;Ll;0;L;;;;;N;;;004D;;004D +006E;LATIN SMALL LETTER N;Ll;0;L;;;;;N;;;004E;;004E +006F;LATIN SMALL LETTER O;Ll;0;L;;;;;N;;;004F;;004F +0070;LATIN SMALL LETTER P;Ll;0;L;;;;;N;;;0050;;0050 +0071;LATIN SMALL LETTER Q;Ll;0;L;;;;;N;;;0051;;0051 +0072;LATIN SMALL LETTER R;Ll;0;L;;;;;N;;;0052;;0052 +0073;LATIN SMALL LETTER S;Ll;0;L;;;;;N;;;0053;;0053 +0074;LATIN SMALL LETTER T;Ll;0;L;;;;;N;;;0054;;0054 +0075;LATIN SMALL LETTER U;Ll;0;L;;;;;N;;;0055;;0055 +0076;LATIN SMALL LETTER V;Ll;0;L;;;;;N;;;0056;;0056 +0077;LATIN SMALL LETTER W;Ll;0;L;;;;;N;;;0057;;0057 +0078;LATIN SMALL LETTER X;Ll;0;L;;;;;N;;;0058;;0058 +0079;LATIN SMALL LETTER Y;Ll;0;L;;;;;N;;;0059;;0059 +007A;LATIN SMALL LETTER Z;Ll;0;L;;;;;N;;;005A;;005A +007B;LEFT CURLY BRACKET;Ps;0;ON;;;;;Y;OPENING CURLY BRACKET;;;; +007C;VERTICAL LINE;Sm;0;ON;;;;;N;VERTICAL BAR;;;; +007D;RIGHT CURLY BRACKET;Pe;0;ON;;;;;Y;CLOSING CURLY BRACKET;;;; +007E;TILDE;Sm;0;ON;;;;;N;;;;; +007F;;Cc;0;BN;;;;;N;DELETE;;;; +0080;;Cc;0;BN;;;;;N;;;;; +0081;;Cc;0;BN;;;;;N;;;;; +0082;;Cc;0;BN;;;;;N;BREAK PERMITTED HERE;;;; +0083;;Cc;0;BN;;;;;N;NO BREAK HERE;;;; +0084;;Cc;0;BN;;;;;N;;;;; +0085;;Cc;0;B;;;;;N;NEXT LINE (NEL);;;; +0086;;Cc;0;BN;;;;;N;START OF SELECTED AREA;;;; +0087;;Cc;0;BN;;;;;N;END OF SELECTED AREA;;;; +0088;;Cc;0;BN;;;;;N;CHARACTER TABULATION SET;;;; +0089;;Cc;0;BN;;;;;N;CHARACTER TABULATION WITH JUSTIFICATION;;;; +008A;;Cc;0;BN;;;;;N;LINE TABULATION SET;;;; +008B;;Cc;0;BN;;;;;N;PARTIAL LINE FORWARD;;;; +008C;;Cc;0;BN;;;;;N;PARTIAL LINE BACKWARD;;;; +008D;;Cc;0;BN;;;;;N;REVERSE LINE FEED;;;; +008E;;Cc;0;BN;;;;;N;SINGLE SHIFT TWO;;;; +008F;;Cc;0;BN;;;;;N;SINGLE SHIFT THREE;;;; +0090;;Cc;0;BN;;;;;N;DEVICE CONTROL STRING;;;; +0091;;Cc;0;BN;;;;;N;PRIVATE USE ONE;;;; +0092;;Cc;0;BN;;;;;N;PRIVATE USE TWO;;;; +0093;;Cc;0;BN;;;;;N;SET TRANSMIT STATE;;;; +0094;;Cc;0;BN;;;;;N;CANCEL CHARACTER;;;; +0095;;Cc;0;BN;;;;;N;MESSAGE WAITING;;;; +0096;;Cc;0;BN;;;;;N;START OF GUARDED AREA;;;; +0097;;Cc;0;BN;;;;;N;END OF GUARDED AREA;;;; +0098;;Cc;0;BN;;;;;N;START OF STRING;;;; +0099;;Cc;0;BN;;;;;N;;;;; +009A;;Cc;0;BN;;;;;N;SINGLE CHARACTER INTRODUCER;;;; +009B;;Cc;0;BN;;;;;N;CONTROL SEQUENCE INTRODUCER;;;; +009C;;Cc;0;BN;;;;;N;STRING TERMINATOR;;;; +009D;;Cc;0;BN;;;;;N;OPERATING SYSTEM COMMAND;;;; +009E;;Cc;0;BN;;;;;N;PRIVACY MESSAGE;;;; +009F;;Cc;0;BN;;;;;N;APPLICATION PROGRAM COMMAND;;;; +00A0;NO-BREAK SPACE;Zs;0;CS; 0020;;;;N;NON-BREAKING SPACE;;;; +00A1;INVERTED EXCLAMATION MARK;Po;0;ON;;;;;N;;;;; +00A2;CENT SIGN;Sc;0;ET;;;;;N;;;;; +00A3;POUND SIGN;Sc;0;ET;;;;;N;;;;; +00A4;CURRENCY SIGN;Sc;0;ET;;;;;N;;;;; +00A5;YEN SIGN;Sc;0;ET;;;;;N;;;;; +00A6;BROKEN BAR;So;0;ON;;;;;N;BROKEN VERTICAL BAR;;;; +00A7;SECTION SIGN;Po;0;ON;;;;;N;;;;; +00A8;DIAERESIS;Sk;0;ON; 0020 0308;;;;N;SPACING DIAERESIS;;;; +00A9;COPYRIGHT SIGN;So;0;ON;;;;;N;;;;; +00AA;FEMININE ORDINAL INDICATOR;Lo;0;L; 0061;;;;N;;;;; +00AB;LEFT-POINTING DOUBLE ANGLE QUOTATION MARK;Pi;0;ON;;;;;Y;LEFT POINTING GUILLEMET;;;; +00AC;NOT SIGN;Sm;0;ON;;;;;N;;;;; +00AD;SOFT HYPHEN;Cf;0;BN;;;;;N;;;;; +00AE;REGISTERED SIGN;So;0;ON;;;;;N;REGISTERED TRADE MARK SIGN;;;; +00AF;MACRON;Sk;0;ON; 0020 0304;;;;N;SPACING MACRON;;;; +00B0;DEGREE SIGN;So;0;ET;;;;;N;;;;; +00B1;PLUS-MINUS SIGN;Sm;0;ET;;;;;N;PLUS-OR-MINUS SIGN;;;; +00B2;SUPERSCRIPT TWO;No;0;EN; 0032;;2;2;N;SUPERSCRIPT DIGIT TWO;;;; +00B3;SUPERSCRIPT THREE;No;0;EN; 0033;;3;3;N;SUPERSCRIPT DIGIT THREE;;;; +00B4;ACUTE ACCENT;Sk;0;ON; 0020 0301;;;;N;SPACING ACUTE;;;; +00B5;MICRO SIGN;Ll;0;L; 03BC;;;;N;;;039C;;039C +00B6;PILCROW SIGN;Po;0;ON;;;;;N;PARAGRAPH SIGN;;;; +00B7;MIDDLE DOT;Po;0;ON;;;;;N;;;;; +00B8;CEDILLA;Sk;0;ON; 0020 0327;;;;N;SPACING CEDILLA;;;; +00B9;SUPERSCRIPT ONE;No;0;EN; 0031;;1;1;N;SUPERSCRIPT DIGIT ONE;;;; +00BA;MASCULINE ORDINAL INDICATOR;Lo;0;L; 006F;;;;N;;;;; +00BB;RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK;Pf;0;ON;;;;;Y;RIGHT POINTING GUILLEMET;;;; +00BC;VULGAR FRACTION ONE QUARTER;No;0;ON; 0031 2044 0034;;;1/4;N;FRACTION ONE QUARTER;;;; +00BD;VULGAR FRACTION ONE HALF;No;0;ON; 0031 2044 0032;;;1/2;N;FRACTION ONE HALF;;;; +00BE;VULGAR FRACTION THREE QUARTERS;No;0;ON; 0033 2044 0034;;;3/4;N;FRACTION THREE QUARTERS;;;; +00BF;INVERTED QUESTION MARK;Po;0;ON;;;;;N;;;;; +00C0;LATIN CAPITAL LETTER A WITH GRAVE;Lu;0;L;0041 0300;;;;N;LATIN CAPITAL LETTER A GRAVE;;;00E0; +00C1;LATIN CAPITAL LETTER A WITH ACUTE;Lu;0;L;0041 0301;;;;N;LATIN CAPITAL LETTER A ACUTE;;;00E1; +00C2;LATIN CAPITAL LETTER A WITH CIRCUMFLEX;Lu;0;L;0041 0302;;;;N;LATIN CAPITAL LETTER A CIRCUMFLEX;;;00E2; +00C3;LATIN CAPITAL LETTER A WITH TILDE;Lu;0;L;0041 0303;;;;N;LATIN CAPITAL LETTER A TILDE;;;00E3; +00C4;LATIN CAPITAL LETTER A WITH DIAERESIS;Lu;0;L;0041 0308;;;;N;LATIN CAPITAL LETTER A DIAERESIS;;;00E4; +00C5;LATIN CAPITAL LETTER A WITH RING ABOVE;Lu;0;L;0041 030A;;;;N;LATIN CAPITAL LETTER A RING;;;00E5; +00C6;LATIN CAPITAL LETTER AE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER A E;;;00E6; +00C7;LATIN CAPITAL LETTER C WITH CEDILLA;Lu;0;L;0043 0327;;;;N;LATIN CAPITAL LETTER C CEDILLA;;;00E7; +00C8;LATIN CAPITAL LETTER E WITH GRAVE;Lu;0;L;0045 0300;;;;N;LATIN CAPITAL LETTER E GRAVE;;;00E8; +00C9;LATIN CAPITAL LETTER E WITH ACUTE;Lu;0;L;0045 0301;;;;N;LATIN CAPITAL LETTER E ACUTE;;;00E9; +00CA;LATIN CAPITAL LETTER E WITH CIRCUMFLEX;Lu;0;L;0045 0302;;;;N;LATIN CAPITAL LETTER E CIRCUMFLEX;;;00EA; +00CB;LATIN CAPITAL LETTER E WITH DIAERESIS;Lu;0;L;0045 0308;;;;N;LATIN CAPITAL LETTER E DIAERESIS;;;00EB; +00CC;LATIN CAPITAL LETTER I WITH GRAVE;Lu;0;L;0049 0300;;;;N;LATIN CAPITAL LETTER I GRAVE;;;00EC; +00CD;LATIN CAPITAL LETTER I WITH ACUTE;Lu;0;L;0049 0301;;;;N;LATIN CAPITAL LETTER I ACUTE;;;00ED; +00CE;LATIN CAPITAL LETTER I WITH CIRCUMFLEX;Lu;0;L;0049 0302;;;;N;LATIN CAPITAL LETTER I CIRCUMFLEX;;;00EE; +00CF;LATIN CAPITAL LETTER I WITH DIAERESIS;Lu;0;L;0049 0308;;;;N;LATIN CAPITAL LETTER I DIAERESIS;;;00EF; +00D0;LATIN CAPITAL LETTER ETH;Lu;0;L;;;;;N;;;;00F0; +00D1;LATIN CAPITAL LETTER N WITH TILDE;Lu;0;L;004E 0303;;;;N;LATIN CAPITAL LETTER N TILDE;;;00F1; +00D2;LATIN CAPITAL LETTER O WITH GRAVE;Lu;0;L;004F 0300;;;;N;LATIN CAPITAL LETTER O GRAVE;;;00F2; +00D3;LATIN CAPITAL LETTER O WITH ACUTE;Lu;0;L;004F 0301;;;;N;LATIN CAPITAL LETTER O ACUTE;;;00F3; +00D4;LATIN CAPITAL LETTER O WITH CIRCUMFLEX;Lu;0;L;004F 0302;;;;N;LATIN CAPITAL LETTER O CIRCUMFLEX;;;00F4; +00D5;LATIN CAPITAL LETTER O WITH TILDE;Lu;0;L;004F 0303;;;;N;LATIN CAPITAL LETTER O TILDE;;;00F5; +00D6;LATIN CAPITAL LETTER O WITH DIAERESIS;Lu;0;L;004F 0308;;;;N;LATIN CAPITAL LETTER O DIAERESIS;;;00F6; +00D7;MULTIPLICATION SIGN;Sm;0;ON;;;;;N;;;;; +00D8;LATIN CAPITAL LETTER O WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER O SLASH;;;00F8; +00D9;LATIN CAPITAL LETTER U WITH GRAVE;Lu;0;L;0055 0300;;;;N;LATIN CAPITAL LETTER U GRAVE;;;00F9; +00DA;LATIN CAPITAL LETTER U WITH ACUTE;Lu;0;L;0055 0301;;;;N;LATIN CAPITAL LETTER U ACUTE;;;00FA; +00DB;LATIN CAPITAL LETTER U WITH CIRCUMFLEX;Lu;0;L;0055 0302;;;;N;LATIN CAPITAL LETTER U CIRCUMFLEX;;;00FB; +00DC;LATIN CAPITAL LETTER U WITH DIAERESIS;Lu;0;L;0055 0308;;;;N;LATIN CAPITAL LETTER U DIAERESIS;;;00FC; +00DD;LATIN CAPITAL LETTER Y WITH ACUTE;Lu;0;L;0059 0301;;;;N;LATIN CAPITAL LETTER Y ACUTE;;;00FD; +00DE;LATIN CAPITAL LETTER THORN;Lu;0;L;;;;;N;;;;00FE; +00DF;LATIN SMALL LETTER SHARP S;Ll;0;L;;;;;N;;;;; +00E0;LATIN SMALL LETTER A WITH GRAVE;Ll;0;L;0061 0300;;;;N;LATIN SMALL LETTER A GRAVE;;00C0;;00C0 +00E1;LATIN SMALL LETTER A WITH ACUTE;Ll;0;L;0061 0301;;;;N;LATIN SMALL LETTER A ACUTE;;00C1;;00C1 +00E2;LATIN SMALL LETTER A WITH CIRCUMFLEX;Ll;0;L;0061 0302;;;;N;LATIN SMALL LETTER A CIRCUMFLEX;;00C2;;00C2 +00E3;LATIN SMALL LETTER A WITH TILDE;Ll;0;L;0061 0303;;;;N;LATIN SMALL LETTER A TILDE;;00C3;;00C3 +00E4;LATIN SMALL LETTER A WITH DIAERESIS;Ll;0;L;0061 0308;;;;N;LATIN SMALL LETTER A DIAERESIS;;00C4;;00C4 +00E5;LATIN SMALL LETTER A WITH RING ABOVE;Ll;0;L;0061 030A;;;;N;LATIN SMALL LETTER A RING;;00C5;;00C5 +00E6;LATIN SMALL LETTER AE;Ll;0;L;;;;;N;LATIN SMALL LETTER A E;;00C6;;00C6 +00E7;LATIN SMALL LETTER C WITH CEDILLA;Ll;0;L;0063 0327;;;;N;LATIN SMALL LETTER C CEDILLA;;00C7;;00C7 +00E8;LATIN SMALL LETTER E WITH GRAVE;Ll;0;L;0065 0300;;;;N;LATIN SMALL LETTER E GRAVE;;00C8;;00C8 +00E9;LATIN SMALL LETTER E WITH ACUTE;Ll;0;L;0065 0301;;;;N;LATIN SMALL LETTER E ACUTE;;00C9;;00C9 +00EA;LATIN SMALL LETTER E WITH CIRCUMFLEX;Ll;0;L;0065 0302;;;;N;LATIN SMALL LETTER E CIRCUMFLEX;;00CA;;00CA +00EB;LATIN SMALL LETTER E WITH DIAERESIS;Ll;0;L;0065 0308;;;;N;LATIN SMALL LETTER E DIAERESIS;;00CB;;00CB +00EC;LATIN SMALL LETTER I WITH GRAVE;Ll;0;L;0069 0300;;;;N;LATIN SMALL LETTER I GRAVE;;00CC;;00CC +00ED;LATIN SMALL LETTER I WITH ACUTE;Ll;0;L;0069 0301;;;;N;LATIN SMALL LETTER I ACUTE;;00CD;;00CD +00EE;LATIN SMALL LETTER I WITH CIRCUMFLEX;Ll;0;L;0069 0302;;;;N;LATIN SMALL LETTER I CIRCUMFLEX;;00CE;;00CE +00EF;LATIN SMALL LETTER I WITH DIAERESIS;Ll;0;L;0069 0308;;;;N;LATIN SMALL LETTER I DIAERESIS;;00CF;;00CF +00F0;LATIN SMALL LETTER ETH;Ll;0;L;;;;;N;;;00D0;;00D0 +00F1;LATIN SMALL LETTER N WITH TILDE;Ll;0;L;006E 0303;;;;N;LATIN SMALL LETTER N TILDE;;00D1;;00D1 +00F2;LATIN SMALL LETTER O WITH GRAVE;Ll;0;L;006F 0300;;;;N;LATIN SMALL LETTER O GRAVE;;00D2;;00D2 +00F3;LATIN SMALL LETTER O WITH ACUTE;Ll;0;L;006F 0301;;;;N;LATIN SMALL LETTER O ACUTE;;00D3;;00D3 +00F4;LATIN SMALL LETTER O WITH CIRCUMFLEX;Ll;0;L;006F 0302;;;;N;LATIN SMALL LETTER O CIRCUMFLEX;;00D4;;00D4 +00F5;LATIN SMALL LETTER O WITH TILDE;Ll;0;L;006F 0303;;;;N;LATIN SMALL LETTER O TILDE;;00D5;;00D5 +00F6;LATIN SMALL LETTER O WITH DIAERESIS;Ll;0;L;006F 0308;;;;N;LATIN SMALL LETTER O DIAERESIS;;00D6;;00D6 +00F7;DIVISION SIGN;Sm;0;ON;;;;;N;;;;; +00F8;LATIN SMALL LETTER O WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER O SLASH;;00D8;;00D8 +00F9;LATIN SMALL LETTER U WITH GRAVE;Ll;0;L;0075 0300;;;;N;LATIN SMALL LETTER U GRAVE;;00D9;;00D9 +00FA;LATIN SMALL LETTER U WITH ACUTE;Ll;0;L;0075 0301;;;;N;LATIN SMALL LETTER U ACUTE;;00DA;;00DA +00FB;LATIN SMALL LETTER U WITH CIRCUMFLEX;Ll;0;L;0075 0302;;;;N;LATIN SMALL LETTER U CIRCUMFLEX;;00DB;;00DB +00FC;LATIN SMALL LETTER U WITH DIAERESIS;Ll;0;L;0075 0308;;;;N;LATIN SMALL LETTER U DIAERESIS;;00DC;;00DC +00FD;LATIN SMALL LETTER Y WITH ACUTE;Ll;0;L;0079 0301;;;;N;LATIN SMALL LETTER Y ACUTE;;00DD;;00DD +00FE;LATIN SMALL LETTER THORN;Ll;0;L;;;;;N;;;00DE;;00DE +00FF;LATIN SMALL LETTER Y WITH DIAERESIS;Ll;0;L;0079 0308;;;;N;LATIN SMALL LETTER Y DIAERESIS;;0178;;0178 +0100;LATIN CAPITAL LETTER A WITH MACRON;Lu;0;L;0041 0304;;;;N;LATIN CAPITAL LETTER A MACRON;;;0101; +0101;LATIN SMALL LETTER A WITH MACRON;Ll;0;L;0061 0304;;;;N;LATIN SMALL LETTER A MACRON;;0100;;0100 +0102;LATIN CAPITAL LETTER A WITH BREVE;Lu;0;L;0041 0306;;;;N;LATIN CAPITAL LETTER A BREVE;;;0103; +0103;LATIN SMALL LETTER A WITH BREVE;Ll;0;L;0061 0306;;;;N;LATIN SMALL LETTER A BREVE;;0102;;0102 +0104;LATIN CAPITAL LETTER A WITH OGONEK;Lu;0;L;0041 0328;;;;N;LATIN CAPITAL LETTER A OGONEK;;;0105; +0105;LATIN SMALL LETTER A WITH OGONEK;Ll;0;L;0061 0328;;;;N;LATIN SMALL LETTER A OGONEK;;0104;;0104 +0106;LATIN CAPITAL LETTER C WITH ACUTE;Lu;0;L;0043 0301;;;;N;LATIN CAPITAL LETTER C ACUTE;;;0107; +0107;LATIN SMALL LETTER C WITH ACUTE;Ll;0;L;0063 0301;;;;N;LATIN SMALL LETTER C ACUTE;;0106;;0106 +0108;LATIN CAPITAL LETTER C WITH CIRCUMFLEX;Lu;0;L;0043 0302;;;;N;LATIN CAPITAL LETTER C CIRCUMFLEX;;;0109; +0109;LATIN SMALL LETTER C WITH CIRCUMFLEX;Ll;0;L;0063 0302;;;;N;LATIN SMALL LETTER C CIRCUMFLEX;;0108;;0108 +010A;LATIN CAPITAL LETTER C WITH DOT ABOVE;Lu;0;L;0043 0307;;;;N;LATIN CAPITAL LETTER C DOT;;;010B; +010B;LATIN SMALL LETTER C WITH DOT ABOVE;Ll;0;L;0063 0307;;;;N;LATIN SMALL LETTER C DOT;;010A;;010A +010C;LATIN CAPITAL LETTER C WITH CARON;Lu;0;L;0043 030C;;;;N;LATIN CAPITAL LETTER C HACEK;;;010D; +010D;LATIN SMALL LETTER C WITH CARON;Ll;0;L;0063 030C;;;;N;LATIN SMALL LETTER C HACEK;;010C;;010C +010E;LATIN CAPITAL LETTER D WITH CARON;Lu;0;L;0044 030C;;;;N;LATIN CAPITAL LETTER D HACEK;;;010F; +010F;LATIN SMALL LETTER D WITH CARON;Ll;0;L;0064 030C;;;;N;LATIN SMALL LETTER D HACEK;;010E;;010E +0110;LATIN CAPITAL LETTER D WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER D BAR;;;0111; +0111;LATIN SMALL LETTER D WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER D BAR;;0110;;0110 +0112;LATIN CAPITAL LETTER E WITH MACRON;Lu;0;L;0045 0304;;;;N;LATIN CAPITAL LETTER E MACRON;;;0113; +0113;LATIN SMALL LETTER E WITH MACRON;Ll;0;L;0065 0304;;;;N;LATIN SMALL LETTER E MACRON;;0112;;0112 +0114;LATIN CAPITAL LETTER E WITH BREVE;Lu;0;L;0045 0306;;;;N;LATIN CAPITAL LETTER E BREVE;;;0115; +0115;LATIN SMALL LETTER E WITH BREVE;Ll;0;L;0065 0306;;;;N;LATIN SMALL LETTER E BREVE;;0114;;0114 +0116;LATIN CAPITAL LETTER E WITH DOT ABOVE;Lu;0;L;0045 0307;;;;N;LATIN CAPITAL LETTER E DOT;;;0117; +0117;LATIN SMALL LETTER E WITH DOT ABOVE;Ll;0;L;0065 0307;;;;N;LATIN SMALL LETTER E DOT;;0116;;0116 +0118;LATIN CAPITAL LETTER E WITH OGONEK;Lu;0;L;0045 0328;;;;N;LATIN CAPITAL LETTER E OGONEK;;;0119; +0119;LATIN SMALL LETTER E WITH OGONEK;Ll;0;L;0065 0328;;;;N;LATIN SMALL LETTER E OGONEK;;0118;;0118 +011A;LATIN CAPITAL LETTER E WITH CARON;Lu;0;L;0045 030C;;;;N;LATIN CAPITAL LETTER E HACEK;;;011B; +011B;LATIN SMALL LETTER E WITH CARON;Ll;0;L;0065 030C;;;;N;LATIN SMALL LETTER E HACEK;;011A;;011A +011C;LATIN CAPITAL LETTER G WITH CIRCUMFLEX;Lu;0;L;0047 0302;;;;N;LATIN CAPITAL LETTER G CIRCUMFLEX;;;011D; +011D;LATIN SMALL LETTER G WITH CIRCUMFLEX;Ll;0;L;0067 0302;;;;N;LATIN SMALL LETTER G CIRCUMFLEX;;011C;;011C +011E;LATIN CAPITAL LETTER G WITH BREVE;Lu;0;L;0047 0306;;;;N;LATIN CAPITAL LETTER G BREVE;;;011F; +011F;LATIN SMALL LETTER G WITH BREVE;Ll;0;L;0067 0306;;;;N;LATIN SMALL LETTER G BREVE;;011E;;011E +0120;LATIN CAPITAL LETTER G WITH DOT ABOVE;Lu;0;L;0047 0307;;;;N;LATIN CAPITAL LETTER G DOT;;;0121; +0121;LATIN SMALL LETTER G WITH DOT ABOVE;Ll;0;L;0067 0307;;;;N;LATIN SMALL LETTER G DOT;;0120;;0120 +0122;LATIN CAPITAL LETTER G WITH CEDILLA;Lu;0;L;0047 0327;;;;N;LATIN CAPITAL LETTER G CEDILLA;;;0123; +0123;LATIN SMALL LETTER G WITH CEDILLA;Ll;0;L;0067 0327;;;;N;LATIN SMALL LETTER G CEDILLA;;0122;;0122 +0124;LATIN CAPITAL LETTER H WITH CIRCUMFLEX;Lu;0;L;0048 0302;;;;N;LATIN CAPITAL LETTER H CIRCUMFLEX;;;0125; +0125;LATIN SMALL LETTER H WITH CIRCUMFLEX;Ll;0;L;0068 0302;;;;N;LATIN SMALL LETTER H CIRCUMFLEX;;0124;;0124 +0126;LATIN CAPITAL LETTER H WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER H BAR;;;0127; +0127;LATIN SMALL LETTER H WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER H BAR;;0126;;0126 +0128;LATIN CAPITAL LETTER I WITH TILDE;Lu;0;L;0049 0303;;;;N;LATIN CAPITAL LETTER I TILDE;;;0129; +0129;LATIN SMALL LETTER I WITH TILDE;Ll;0;L;0069 0303;;;;N;LATIN SMALL LETTER I TILDE;;0128;;0128 +012A;LATIN CAPITAL LETTER I WITH MACRON;Lu;0;L;0049 0304;;;;N;LATIN CAPITAL LETTER I MACRON;;;012B; +012B;LATIN SMALL LETTER I WITH MACRON;Ll;0;L;0069 0304;;;;N;LATIN SMALL LETTER I MACRON;;012A;;012A +012C;LATIN CAPITAL LETTER I WITH BREVE;Lu;0;L;0049 0306;;;;N;LATIN CAPITAL LETTER I BREVE;;;012D; +012D;LATIN SMALL LETTER I WITH BREVE;Ll;0;L;0069 0306;;;;N;LATIN SMALL LETTER I BREVE;;012C;;012C +012E;LATIN CAPITAL LETTER I WITH OGONEK;Lu;0;L;0049 0328;;;;N;LATIN CAPITAL LETTER I OGONEK;;;012F; +012F;LATIN SMALL LETTER I WITH OGONEK;Ll;0;L;0069 0328;;;;N;LATIN SMALL LETTER I OGONEK;;012E;;012E +0130;LATIN CAPITAL LETTER I WITH DOT ABOVE;Lu;0;L;0049 0307;;;;N;LATIN CAPITAL LETTER I DOT;;;0069; +0131;LATIN SMALL LETTER DOTLESS I;Ll;0;L;;;;;N;;;0049;;0049 +0132;LATIN CAPITAL LIGATURE IJ;Lu;0;L; 0049 004A;;;;N;LATIN CAPITAL LETTER I J;;;0133; +0133;LATIN SMALL LIGATURE IJ;Ll;0;L; 0069 006A;;;;N;LATIN SMALL LETTER I J;;0132;;0132 +0134;LATIN CAPITAL LETTER J WITH CIRCUMFLEX;Lu;0;L;004A 0302;;;;N;LATIN CAPITAL LETTER J CIRCUMFLEX;;;0135; +0135;LATIN SMALL LETTER J WITH CIRCUMFLEX;Ll;0;L;006A 0302;;;;N;LATIN SMALL LETTER J CIRCUMFLEX;;0134;;0134 +0136;LATIN CAPITAL LETTER K WITH CEDILLA;Lu;0;L;004B 0327;;;;N;LATIN CAPITAL LETTER K CEDILLA;;;0137; +0137;LATIN SMALL LETTER K WITH CEDILLA;Ll;0;L;006B 0327;;;;N;LATIN SMALL LETTER K CEDILLA;;0136;;0136 +0138;LATIN SMALL LETTER KRA;Ll;0;L;;;;;N;;;;; +0139;LATIN CAPITAL LETTER L WITH ACUTE;Lu;0;L;004C 0301;;;;N;LATIN CAPITAL LETTER L ACUTE;;;013A; +013A;LATIN SMALL LETTER L WITH ACUTE;Ll;0;L;006C 0301;;;;N;LATIN SMALL LETTER L ACUTE;;0139;;0139 +013B;LATIN CAPITAL LETTER L WITH CEDILLA;Lu;0;L;004C 0327;;;;N;LATIN CAPITAL LETTER L CEDILLA;;;013C; +013C;LATIN SMALL LETTER L WITH CEDILLA;Ll;0;L;006C 0327;;;;N;LATIN SMALL LETTER L CEDILLA;;013B;;013B +013D;LATIN CAPITAL LETTER L WITH CARON;Lu;0;L;004C 030C;;;;N;LATIN CAPITAL LETTER L HACEK;;;013E; +013E;LATIN SMALL LETTER L WITH CARON;Ll;0;L;006C 030C;;;;N;LATIN SMALL LETTER L HACEK;;013D;;013D +013F;LATIN CAPITAL LETTER L WITH MIDDLE DOT;Lu;0;L; 004C 00B7;;;;N;;;;0140; +0140;LATIN SMALL LETTER L WITH MIDDLE DOT;Ll;0;L; 006C 00B7;;;;N;;;013F;;013F +0141;LATIN CAPITAL LETTER L WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER L SLASH;;;0142; +0142;LATIN SMALL LETTER L WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER L SLASH;;0141;;0141 +0143;LATIN CAPITAL LETTER N WITH ACUTE;Lu;0;L;004E 0301;;;;N;LATIN CAPITAL LETTER N ACUTE;;;0144; +0144;LATIN SMALL LETTER N WITH ACUTE;Ll;0;L;006E 0301;;;;N;LATIN SMALL LETTER N ACUTE;;0143;;0143 +0145;LATIN CAPITAL LETTER N WITH CEDILLA;Lu;0;L;004E 0327;;;;N;LATIN CAPITAL LETTER N CEDILLA;;;0146; +0146;LATIN SMALL LETTER N WITH CEDILLA;Ll;0;L;006E 0327;;;;N;LATIN SMALL LETTER N CEDILLA;;0145;;0145 +0147;LATIN CAPITAL LETTER N WITH CARON;Lu;0;L;004E 030C;;;;N;LATIN CAPITAL LETTER N HACEK;;;0148; +0148;LATIN SMALL LETTER N WITH CARON;Ll;0;L;006E 030C;;;;N;LATIN SMALL LETTER N HACEK;;0147;;0147 +0149;LATIN SMALL LETTER N PRECEDED BY APOSTROPHE;Ll;0;L; 02BC 006E;;;;N;LATIN SMALL LETTER APOSTROPHE N;;;; +014A;LATIN CAPITAL LETTER ENG;Lu;0;L;;;;;N;;;;014B; +014B;LATIN SMALL LETTER ENG;Ll;0;L;;;;;N;;;014A;;014A +014C;LATIN CAPITAL LETTER O WITH MACRON;Lu;0;L;004F 0304;;;;N;LATIN CAPITAL LETTER O MACRON;;;014D; +014D;LATIN SMALL LETTER O WITH MACRON;Ll;0;L;006F 0304;;;;N;LATIN SMALL LETTER O MACRON;;014C;;014C +014E;LATIN CAPITAL LETTER O WITH BREVE;Lu;0;L;004F 0306;;;;N;LATIN CAPITAL LETTER O BREVE;;;014F; +014F;LATIN SMALL LETTER O WITH BREVE;Ll;0;L;006F 0306;;;;N;LATIN SMALL LETTER O BREVE;;014E;;014E +0150;LATIN CAPITAL LETTER O WITH DOUBLE ACUTE;Lu;0;L;004F 030B;;;;N;LATIN CAPITAL LETTER O DOUBLE ACUTE;;;0151; +0151;LATIN SMALL LETTER O WITH DOUBLE ACUTE;Ll;0;L;006F 030B;;;;N;LATIN SMALL LETTER O DOUBLE ACUTE;;0150;;0150 +0152;LATIN CAPITAL LIGATURE OE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER O E;;;0153; +0153;LATIN SMALL LIGATURE OE;Ll;0;L;;;;;N;LATIN SMALL LETTER O E;;0152;;0152 +0154;LATIN CAPITAL LETTER R WITH ACUTE;Lu;0;L;0052 0301;;;;N;LATIN CAPITAL LETTER R ACUTE;;;0155; +0155;LATIN SMALL LETTER R WITH ACUTE;Ll;0;L;0072 0301;;;;N;LATIN SMALL LETTER R ACUTE;;0154;;0154 +0156;LATIN CAPITAL LETTER R WITH CEDILLA;Lu;0;L;0052 0327;;;;N;LATIN CAPITAL LETTER R CEDILLA;;;0157; +0157;LATIN SMALL LETTER R WITH CEDILLA;Ll;0;L;0072 0327;;;;N;LATIN SMALL LETTER R CEDILLA;;0156;;0156 +0158;LATIN CAPITAL LETTER R WITH CARON;Lu;0;L;0052 030C;;;;N;LATIN CAPITAL LETTER R HACEK;;;0159; +0159;LATIN SMALL LETTER R WITH CARON;Ll;0;L;0072 030C;;;;N;LATIN SMALL LETTER R HACEK;;0158;;0158 +015A;LATIN CAPITAL LETTER S WITH ACUTE;Lu;0;L;0053 0301;;;;N;LATIN CAPITAL LETTER S ACUTE;;;015B; +015B;LATIN SMALL LETTER S WITH ACUTE;Ll;0;L;0073 0301;;;;N;LATIN SMALL LETTER S ACUTE;;015A;;015A +015C;LATIN CAPITAL LETTER S WITH CIRCUMFLEX;Lu;0;L;0053 0302;;;;N;LATIN CAPITAL LETTER S CIRCUMFLEX;;;015D; +015D;LATIN SMALL LETTER S WITH CIRCUMFLEX;Ll;0;L;0073 0302;;;;N;LATIN SMALL LETTER S CIRCUMFLEX;;015C;;015C +015E;LATIN CAPITAL LETTER S WITH CEDILLA;Lu;0;L;0053 0327;;;;N;LATIN CAPITAL LETTER S CEDILLA;;;015F; +015F;LATIN SMALL LETTER S WITH CEDILLA;Ll;0;L;0073 0327;;;;N;LATIN SMALL LETTER S CEDILLA;;015E;;015E +0160;LATIN CAPITAL LETTER S WITH CARON;Lu;0;L;0053 030C;;;;N;LATIN CAPITAL LETTER S HACEK;;;0161; +0161;LATIN SMALL LETTER S WITH CARON;Ll;0;L;0073 030C;;;;N;LATIN SMALL LETTER S HACEK;;0160;;0160 +0162;LATIN CAPITAL LETTER T WITH CEDILLA;Lu;0;L;0054 0327;;;;N;LATIN CAPITAL LETTER T CEDILLA;;;0163; +0163;LATIN SMALL LETTER T WITH CEDILLA;Ll;0;L;0074 0327;;;;N;LATIN SMALL LETTER T CEDILLA;;0162;;0162 +0164;LATIN CAPITAL LETTER T WITH CARON;Lu;0;L;0054 030C;;;;N;LATIN CAPITAL LETTER T HACEK;;;0165; +0165;LATIN SMALL LETTER T WITH CARON;Ll;0;L;0074 030C;;;;N;LATIN SMALL LETTER T HACEK;;0164;;0164 +0166;LATIN CAPITAL LETTER T WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER T BAR;;;0167; +0167;LATIN SMALL LETTER T WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER T BAR;;0166;;0166 +0168;LATIN CAPITAL LETTER U WITH TILDE;Lu;0;L;0055 0303;;;;N;LATIN CAPITAL LETTER U TILDE;;;0169; +0169;LATIN SMALL LETTER U WITH TILDE;Ll;0;L;0075 0303;;;;N;LATIN SMALL LETTER U TILDE;;0168;;0168 +016A;LATIN CAPITAL LETTER U WITH MACRON;Lu;0;L;0055 0304;;;;N;LATIN CAPITAL LETTER U MACRON;;;016B; +016B;LATIN SMALL LETTER U WITH MACRON;Ll;0;L;0075 0304;;;;N;LATIN SMALL LETTER U MACRON;;016A;;016A +016C;LATIN CAPITAL LETTER U WITH BREVE;Lu;0;L;0055 0306;;;;N;LATIN CAPITAL LETTER U BREVE;;;016D; +016D;LATIN SMALL LETTER U WITH BREVE;Ll;0;L;0075 0306;;;;N;LATIN SMALL LETTER U BREVE;;016C;;016C +016E;LATIN CAPITAL LETTER U WITH RING ABOVE;Lu;0;L;0055 030A;;;;N;LATIN CAPITAL LETTER U RING;;;016F; +016F;LATIN SMALL LETTER U WITH RING ABOVE;Ll;0;L;0075 030A;;;;N;LATIN SMALL LETTER U RING;;016E;;016E +0170;LATIN CAPITAL LETTER U WITH DOUBLE ACUTE;Lu;0;L;0055 030B;;;;N;LATIN CAPITAL LETTER U DOUBLE ACUTE;;;0171; +0171;LATIN SMALL LETTER U WITH DOUBLE ACUTE;Ll;0;L;0075 030B;;;;N;LATIN SMALL LETTER U DOUBLE ACUTE;;0170;;0170 +0172;LATIN CAPITAL LETTER U WITH OGONEK;Lu;0;L;0055 0328;;;;N;LATIN CAPITAL LETTER U OGONEK;;;0173; +0173;LATIN SMALL LETTER U WITH OGONEK;Ll;0;L;0075 0328;;;;N;LATIN SMALL LETTER U OGONEK;;0172;;0172 +0174;LATIN CAPITAL LETTER W WITH CIRCUMFLEX;Lu;0;L;0057 0302;;;;N;LATIN CAPITAL LETTER W CIRCUMFLEX;;;0175; +0175;LATIN SMALL LETTER W WITH CIRCUMFLEX;Ll;0;L;0077 0302;;;;N;LATIN SMALL LETTER W CIRCUMFLEX;;0174;;0174 +0176;LATIN CAPITAL LETTER Y WITH CIRCUMFLEX;Lu;0;L;0059 0302;;;;N;LATIN CAPITAL LETTER Y CIRCUMFLEX;;;0177; +0177;LATIN SMALL LETTER Y WITH CIRCUMFLEX;Ll;0;L;0079 0302;;;;N;LATIN SMALL LETTER Y CIRCUMFLEX;;0176;;0176 +0178;LATIN CAPITAL LETTER Y WITH DIAERESIS;Lu;0;L;0059 0308;;;;N;LATIN CAPITAL LETTER Y DIAERESIS;;;00FF; +0179;LATIN CAPITAL LETTER Z WITH ACUTE;Lu;0;L;005A 0301;;;;N;LATIN CAPITAL LETTER Z ACUTE;;;017A; +017A;LATIN SMALL LETTER Z WITH ACUTE;Ll;0;L;007A 0301;;;;N;LATIN SMALL LETTER Z ACUTE;;0179;;0179 +017B;LATIN CAPITAL LETTER Z WITH DOT ABOVE;Lu;0;L;005A 0307;;;;N;LATIN CAPITAL LETTER Z DOT;;;017C; +017C;LATIN SMALL LETTER Z WITH DOT ABOVE;Ll;0;L;007A 0307;;;;N;LATIN SMALL LETTER Z DOT;;017B;;017B +017D;LATIN CAPITAL LETTER Z WITH CARON;Lu;0;L;005A 030C;;;;N;LATIN CAPITAL LETTER Z HACEK;;;017E; +017E;LATIN SMALL LETTER Z WITH CARON;Ll;0;L;007A 030C;;;;N;LATIN SMALL LETTER Z HACEK;;017D;;017D +017F;LATIN SMALL LETTER LONG S;Ll;0;L; 0073;;;;N;;;0053;;0053 +0180;LATIN SMALL LETTER B WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER B BAR;;0243;;0243 +0181;LATIN CAPITAL LETTER B WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER B HOOK;;;0253; +0182;LATIN CAPITAL LETTER B WITH TOPBAR;Lu;0;L;;;;;N;LATIN CAPITAL LETTER B TOPBAR;;;0183; +0183;LATIN SMALL LETTER B WITH TOPBAR;Ll;0;L;;;;;N;LATIN SMALL LETTER B TOPBAR;;0182;;0182 +0184;LATIN CAPITAL LETTER TONE SIX;Lu;0;L;;;;;N;;;;0185; +0185;LATIN SMALL LETTER TONE SIX;Ll;0;L;;;;;N;;;0184;;0184 +0186;LATIN CAPITAL LETTER OPEN O;Lu;0;L;;;;;N;;;;0254; +0187;LATIN CAPITAL LETTER C WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER C HOOK;;;0188; +0188;LATIN SMALL LETTER C WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER C HOOK;;0187;;0187 +0189;LATIN CAPITAL LETTER AFRICAN D;Lu;0;L;;;;;N;;;;0256; +018A;LATIN CAPITAL LETTER D WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER D HOOK;;;0257; +018B;LATIN CAPITAL LETTER D WITH TOPBAR;Lu;0;L;;;;;N;LATIN CAPITAL LETTER D TOPBAR;;;018C; +018C;LATIN SMALL LETTER D WITH TOPBAR;Ll;0;L;;;;;N;LATIN SMALL LETTER D TOPBAR;;018B;;018B +018D;LATIN SMALL LETTER TURNED DELTA;Ll;0;L;;;;;N;;;;; +018E;LATIN CAPITAL LETTER REVERSED E;Lu;0;L;;;;;N;LATIN CAPITAL LETTER TURNED E;;;01DD; +018F;LATIN CAPITAL LETTER SCHWA;Lu;0;L;;;;;N;;;;0259; +0190;LATIN CAPITAL LETTER OPEN E;Lu;0;L;;;;;N;LATIN CAPITAL LETTER EPSILON;;;025B; +0191;LATIN CAPITAL LETTER F WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER F HOOK;;;0192; +0192;LATIN SMALL LETTER F WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER SCRIPT F;;0191;;0191 +0193;LATIN CAPITAL LETTER G WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER G HOOK;;;0260; +0194;LATIN CAPITAL LETTER GAMMA;Lu;0;L;;;;;N;;;;0263; +0195;LATIN SMALL LETTER HV;Ll;0;L;;;;;N;LATIN SMALL LETTER H V;;01F6;;01F6 +0196;LATIN CAPITAL LETTER IOTA;Lu;0;L;;;;;N;;;;0269; +0197;LATIN CAPITAL LETTER I WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER BARRED I;;;0268; +0198;LATIN CAPITAL LETTER K WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER K HOOK;;;0199; +0199;LATIN SMALL LETTER K WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER K HOOK;;0198;;0198 +019A;LATIN SMALL LETTER L WITH BAR;Ll;0;L;;;;;N;LATIN SMALL LETTER BARRED L;;023D;;023D +019B;LATIN SMALL LETTER LAMBDA WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER BARRED LAMBDA;;;; +019C;LATIN CAPITAL LETTER TURNED M;Lu;0;L;;;;;N;;;;026F; +019D;LATIN CAPITAL LETTER N WITH LEFT HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER N HOOK;;;0272; +019E;LATIN SMALL LETTER N WITH LONG RIGHT LEG;Ll;0;L;;;;;N;;;0220;;0220 +019F;LATIN CAPITAL LETTER O WITH MIDDLE TILDE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER BARRED O;;;0275; +01A0;LATIN CAPITAL LETTER O WITH HORN;Lu;0;L;004F 031B;;;;N;LATIN CAPITAL LETTER O HORN;;;01A1; +01A1;LATIN SMALL LETTER O WITH HORN;Ll;0;L;006F 031B;;;;N;LATIN SMALL LETTER O HORN;;01A0;;01A0 +01A2;LATIN CAPITAL LETTER OI;Lu;0;L;;;;;N;LATIN CAPITAL LETTER O I;;;01A3; +01A3;LATIN SMALL LETTER OI;Ll;0;L;;;;;N;LATIN SMALL LETTER O I;;01A2;;01A2 +01A4;LATIN CAPITAL LETTER P WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER P HOOK;;;01A5; +01A5;LATIN SMALL LETTER P WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER P HOOK;;01A4;;01A4 +01A6;LATIN LETTER YR;Lu;0;L;;;;;N;LATIN LETTER Y R;;;0280; +01A7;LATIN CAPITAL LETTER TONE TWO;Lu;0;L;;;;;N;;;;01A8; +01A8;LATIN SMALL LETTER TONE TWO;Ll;0;L;;;;;N;;;01A7;;01A7 +01A9;LATIN CAPITAL LETTER ESH;Lu;0;L;;;;;N;;;;0283; +01AA;LATIN LETTER REVERSED ESH LOOP;Ll;0;L;;;;;N;;;;; +01AB;LATIN SMALL LETTER T WITH PALATAL HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER T PALATAL HOOK;;;; +01AC;LATIN CAPITAL LETTER T WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER T HOOK;;;01AD; +01AD;LATIN SMALL LETTER T WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER T HOOK;;01AC;;01AC +01AE;LATIN CAPITAL LETTER T WITH RETROFLEX HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER T RETROFLEX HOOK;;;0288; +01AF;LATIN CAPITAL LETTER U WITH HORN;Lu;0;L;0055 031B;;;;N;LATIN CAPITAL LETTER U HORN;;;01B0; +01B0;LATIN SMALL LETTER U WITH HORN;Ll;0;L;0075 031B;;;;N;LATIN SMALL LETTER U HORN;;01AF;;01AF +01B1;LATIN CAPITAL LETTER UPSILON;Lu;0;L;;;;;N;;;;028A; +01B2;LATIN CAPITAL LETTER V WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER SCRIPT V;;;028B; +01B3;LATIN CAPITAL LETTER Y WITH HOOK;Lu;0;L;;;;;N;LATIN CAPITAL LETTER Y HOOK;;;01B4; +01B4;LATIN SMALL LETTER Y WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER Y HOOK;;01B3;;01B3 +01B5;LATIN CAPITAL LETTER Z WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER Z BAR;;;01B6; +01B6;LATIN SMALL LETTER Z WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER Z BAR;;01B5;;01B5 +01B7;LATIN CAPITAL LETTER EZH;Lu;0;L;;;;;N;LATIN CAPITAL LETTER YOGH;;;0292; +01B8;LATIN CAPITAL LETTER EZH REVERSED;Lu;0;L;;;;;N;LATIN CAPITAL LETTER REVERSED YOGH;;;01B9; +01B9;LATIN SMALL LETTER EZH REVERSED;Ll;0;L;;;;;N;LATIN SMALL LETTER REVERSED YOGH;;01B8;;01B8 +01BA;LATIN SMALL LETTER EZH WITH TAIL;Ll;0;L;;;;;N;LATIN SMALL LETTER YOGH WITH TAIL;;;; +01BB;LATIN LETTER TWO WITH STROKE;Lo;0;L;;;;;N;LATIN LETTER TWO BAR;;;; +01BC;LATIN CAPITAL LETTER TONE FIVE;Lu;0;L;;;;;N;;;;01BD; +01BD;LATIN SMALL LETTER TONE FIVE;Ll;0;L;;;;;N;;;01BC;;01BC +01BE;LATIN LETTER INVERTED GLOTTAL STOP WITH STROKE;Ll;0;L;;;;;N;LATIN LETTER INVERTED GLOTTAL STOP BAR;;;; +01BF;LATIN LETTER WYNN;Ll;0;L;;;;;N;;;01F7;;01F7 +01C0;LATIN LETTER DENTAL CLICK;Lo;0;L;;;;;N;LATIN LETTER PIPE;;;; +01C1;LATIN LETTER LATERAL CLICK;Lo;0;L;;;;;N;LATIN LETTER DOUBLE PIPE;;;; +01C2;LATIN LETTER ALVEOLAR CLICK;Lo;0;L;;;;;N;LATIN LETTER PIPE DOUBLE BAR;;;; +01C3;LATIN LETTER RETROFLEX CLICK;Lo;0;L;;;;;N;LATIN LETTER EXCLAMATION MARK;;;; +01C4;LATIN CAPITAL LETTER DZ WITH CARON;Lu;0;L; 0044 017D;;;;N;LATIN CAPITAL LETTER D Z HACEK;;;01C6;01C5 +01C5;LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON;Lt;0;L; 0044 017E;;;;N;LATIN LETTER CAPITAL D SMALL Z HACEK;;01C4;01C6;01C5 +01C6;LATIN SMALL LETTER DZ WITH CARON;Ll;0;L; 0064 017E;;;;N;LATIN SMALL LETTER D Z HACEK;;01C4;;01C5 +01C7;LATIN CAPITAL LETTER LJ;Lu;0;L; 004C 004A;;;;N;LATIN CAPITAL LETTER L J;;;01C9;01C8 +01C8;LATIN CAPITAL LETTER L WITH SMALL LETTER J;Lt;0;L; 004C 006A;;;;N;LATIN LETTER CAPITAL L SMALL J;;01C7;01C9;01C8 +01C9;LATIN SMALL LETTER LJ;Ll;0;L; 006C 006A;;;;N;LATIN SMALL LETTER L J;;01C7;;01C8 +01CA;LATIN CAPITAL LETTER NJ;Lu;0;L; 004E 004A;;;;N;LATIN CAPITAL LETTER N J;;;01CC;01CB +01CB;LATIN CAPITAL LETTER N WITH SMALL LETTER J;Lt;0;L; 004E 006A;;;;N;LATIN LETTER CAPITAL N SMALL J;;01CA;01CC;01CB +01CC;LATIN SMALL LETTER NJ;Ll;0;L; 006E 006A;;;;N;LATIN SMALL LETTER N J;;01CA;;01CB +01CD;LATIN CAPITAL LETTER A WITH CARON;Lu;0;L;0041 030C;;;;N;LATIN CAPITAL LETTER A HACEK;;;01CE; +01CE;LATIN SMALL LETTER A WITH CARON;Ll;0;L;0061 030C;;;;N;LATIN SMALL LETTER A HACEK;;01CD;;01CD +01CF;LATIN CAPITAL LETTER I WITH CARON;Lu;0;L;0049 030C;;;;N;LATIN CAPITAL LETTER I HACEK;;;01D0; +01D0;LATIN SMALL LETTER I WITH CARON;Ll;0;L;0069 030C;;;;N;LATIN SMALL LETTER I HACEK;;01CF;;01CF +01D1;LATIN CAPITAL LETTER O WITH CARON;Lu;0;L;004F 030C;;;;N;LATIN CAPITAL LETTER O HACEK;;;01D2; +01D2;LATIN SMALL LETTER O WITH CARON;Ll;0;L;006F 030C;;;;N;LATIN SMALL LETTER O HACEK;;01D1;;01D1 +01D3;LATIN CAPITAL LETTER U WITH CARON;Lu;0;L;0055 030C;;;;N;LATIN CAPITAL LETTER U HACEK;;;01D4; +01D4;LATIN SMALL LETTER U WITH CARON;Ll;0;L;0075 030C;;;;N;LATIN SMALL LETTER U HACEK;;01D3;;01D3 +01D5;LATIN CAPITAL LETTER U WITH DIAERESIS AND MACRON;Lu;0;L;00DC 0304;;;;N;LATIN CAPITAL LETTER U DIAERESIS MACRON;;;01D6; +01D6;LATIN SMALL LETTER U WITH DIAERESIS AND MACRON;Ll;0;L;00FC 0304;;;;N;LATIN SMALL LETTER U DIAERESIS MACRON;;01D5;;01D5 +01D7;LATIN CAPITAL LETTER U WITH DIAERESIS AND ACUTE;Lu;0;L;00DC 0301;;;;N;LATIN CAPITAL LETTER U DIAERESIS ACUTE;;;01D8; +01D8;LATIN SMALL LETTER U WITH DIAERESIS AND ACUTE;Ll;0;L;00FC 0301;;;;N;LATIN SMALL LETTER U DIAERESIS ACUTE;;01D7;;01D7 +01D9;LATIN CAPITAL LETTER U WITH DIAERESIS AND CARON;Lu;0;L;00DC 030C;;;;N;LATIN CAPITAL LETTER U DIAERESIS HACEK;;;01DA; +01DA;LATIN SMALL LETTER U WITH DIAERESIS AND CARON;Ll;0;L;00FC 030C;;;;N;LATIN SMALL LETTER U DIAERESIS HACEK;;01D9;;01D9 +01DB;LATIN CAPITAL LETTER U WITH DIAERESIS AND GRAVE;Lu;0;L;00DC 0300;;;;N;LATIN CAPITAL LETTER U DIAERESIS GRAVE;;;01DC; +01DC;LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE;Ll;0;L;00FC 0300;;;;N;LATIN SMALL LETTER U DIAERESIS GRAVE;;01DB;;01DB +01DD;LATIN SMALL LETTER TURNED E;Ll;0;L;;;;;N;;;018E;;018E +01DE;LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON;Lu;0;L;00C4 0304;;;;N;LATIN CAPITAL LETTER A DIAERESIS MACRON;;;01DF; +01DF;LATIN SMALL LETTER A WITH DIAERESIS AND MACRON;Ll;0;L;00E4 0304;;;;N;LATIN SMALL LETTER A DIAERESIS MACRON;;01DE;;01DE +01E0;LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON;Lu;0;L;0226 0304;;;;N;LATIN CAPITAL LETTER A DOT MACRON;;;01E1; +01E1;LATIN SMALL LETTER A WITH DOT ABOVE AND MACRON;Ll;0;L;0227 0304;;;;N;LATIN SMALL LETTER A DOT MACRON;;01E0;;01E0 +01E2;LATIN CAPITAL LETTER AE WITH MACRON;Lu;0;L;00C6 0304;;;;N;LATIN CAPITAL LETTER A E MACRON;;;01E3; +01E3;LATIN SMALL LETTER AE WITH MACRON;Ll;0;L;00E6 0304;;;;N;LATIN SMALL LETTER A E MACRON;;01E2;;01E2 +01E4;LATIN CAPITAL LETTER G WITH STROKE;Lu;0;L;;;;;N;LATIN CAPITAL LETTER G BAR;;;01E5; +01E5;LATIN SMALL LETTER G WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER G BAR;;01E4;;01E4 +01E6;LATIN CAPITAL LETTER G WITH CARON;Lu;0;L;0047 030C;;;;N;LATIN CAPITAL LETTER G HACEK;;;01E7; +01E7;LATIN SMALL LETTER G WITH CARON;Ll;0;L;0067 030C;;;;N;LATIN SMALL LETTER G HACEK;;01E6;;01E6 +01E8;LATIN CAPITAL LETTER K WITH CARON;Lu;0;L;004B 030C;;;;N;LATIN CAPITAL LETTER K HACEK;;;01E9; +01E9;LATIN SMALL LETTER K WITH CARON;Ll;0;L;006B 030C;;;;N;LATIN SMALL LETTER K HACEK;;01E8;;01E8 +01EA;LATIN CAPITAL LETTER O WITH OGONEK;Lu;0;L;004F 0328;;;;N;LATIN CAPITAL LETTER O OGONEK;;;01EB; +01EB;LATIN SMALL LETTER O WITH OGONEK;Ll;0;L;006F 0328;;;;N;LATIN SMALL LETTER O OGONEK;;01EA;;01EA +01EC;LATIN CAPITAL LETTER O WITH OGONEK AND MACRON;Lu;0;L;01EA 0304;;;;N;LATIN CAPITAL LETTER O OGONEK MACRON;;;01ED; +01ED;LATIN SMALL LETTER O WITH OGONEK AND MACRON;Ll;0;L;01EB 0304;;;;N;LATIN SMALL LETTER O OGONEK MACRON;;01EC;;01EC +01EE;LATIN CAPITAL LETTER EZH WITH CARON;Lu;0;L;01B7 030C;;;;N;LATIN CAPITAL LETTER YOGH HACEK;;;01EF; +01EF;LATIN SMALL LETTER EZH WITH CARON;Ll;0;L;0292 030C;;;;N;LATIN SMALL LETTER YOGH HACEK;;01EE;;01EE +01F0;LATIN SMALL LETTER J WITH CARON;Ll;0;L;006A 030C;;;;N;LATIN SMALL LETTER J HACEK;;;; +01F1;LATIN CAPITAL LETTER DZ;Lu;0;L; 0044 005A;;;;N;;;;01F3;01F2 +01F2;LATIN CAPITAL LETTER D WITH SMALL LETTER Z;Lt;0;L; 0044 007A;;;;N;;;01F1;01F3;01F2 +01F3;LATIN SMALL LETTER DZ;Ll;0;L; 0064 007A;;;;N;;;01F1;;01F2 +01F4;LATIN CAPITAL LETTER G WITH ACUTE;Lu;0;L;0047 0301;;;;N;;;;01F5; +01F5;LATIN SMALL LETTER G WITH ACUTE;Ll;0;L;0067 0301;;;;N;;;01F4;;01F4 +01F6;LATIN CAPITAL LETTER HWAIR;Lu;0;L;;;;;N;;;;0195; +01F7;LATIN CAPITAL LETTER WYNN;Lu;0;L;;;;;N;;;;01BF; +01F8;LATIN CAPITAL LETTER N WITH GRAVE;Lu;0;L;004E 0300;;;;N;;;;01F9; +01F9;LATIN SMALL LETTER N WITH GRAVE;Ll;0;L;006E 0300;;;;N;;;01F8;;01F8 +01FA;LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE;Lu;0;L;00C5 0301;;;;N;;;;01FB; +01FB;LATIN SMALL LETTER A WITH RING ABOVE AND ACUTE;Ll;0;L;00E5 0301;;;;N;;;01FA;;01FA +01FC;LATIN CAPITAL LETTER AE WITH ACUTE;Lu;0;L;00C6 0301;;;;N;;;;01FD; +01FD;LATIN SMALL LETTER AE WITH ACUTE;Ll;0;L;00E6 0301;;;;N;;;01FC;;01FC +01FE;LATIN CAPITAL LETTER O WITH STROKE AND ACUTE;Lu;0;L;00D8 0301;;;;N;;;;01FF; +01FF;LATIN SMALL LETTER O WITH STROKE AND ACUTE;Ll;0;L;00F8 0301;;;;N;;;01FE;;01FE +0200;LATIN CAPITAL LETTER A WITH DOUBLE GRAVE;Lu;0;L;0041 030F;;;;N;;;;0201; +0201;LATIN SMALL LETTER A WITH DOUBLE GRAVE;Ll;0;L;0061 030F;;;;N;;;0200;;0200 +0202;LATIN CAPITAL LETTER A WITH INVERTED BREVE;Lu;0;L;0041 0311;;;;N;;;;0203; +0203;LATIN SMALL LETTER A WITH INVERTED BREVE;Ll;0;L;0061 0311;;;;N;;;0202;;0202 +0204;LATIN CAPITAL LETTER E WITH DOUBLE GRAVE;Lu;0;L;0045 030F;;;;N;;;;0205; +0205;LATIN SMALL LETTER E WITH DOUBLE GRAVE;Ll;0;L;0065 030F;;;;N;;;0204;;0204 +0206;LATIN CAPITAL LETTER E WITH INVERTED BREVE;Lu;0;L;0045 0311;;;;N;;;;0207; +0207;LATIN SMALL LETTER E WITH INVERTED BREVE;Ll;0;L;0065 0311;;;;N;;;0206;;0206 +0208;LATIN CAPITAL LETTER I WITH DOUBLE GRAVE;Lu;0;L;0049 030F;;;;N;;;;0209; +0209;LATIN SMALL LETTER I WITH DOUBLE GRAVE;Ll;0;L;0069 030F;;;;N;;;0208;;0208 +020A;LATIN CAPITAL LETTER I WITH INVERTED BREVE;Lu;0;L;0049 0311;;;;N;;;;020B; +020B;LATIN SMALL LETTER I WITH INVERTED BREVE;Ll;0;L;0069 0311;;;;N;;;020A;;020A +020C;LATIN CAPITAL LETTER O WITH DOUBLE GRAVE;Lu;0;L;004F 030F;;;;N;;;;020D; +020D;LATIN SMALL LETTER O WITH DOUBLE GRAVE;Ll;0;L;006F 030F;;;;N;;;020C;;020C +020E;LATIN CAPITAL LETTER O WITH INVERTED BREVE;Lu;0;L;004F 0311;;;;N;;;;020F; +020F;LATIN SMALL LETTER O WITH INVERTED BREVE;Ll;0;L;006F 0311;;;;N;;;020E;;020E +0210;LATIN CAPITAL LETTER R WITH DOUBLE GRAVE;Lu;0;L;0052 030F;;;;N;;;;0211; +0211;LATIN SMALL LETTER R WITH DOUBLE GRAVE;Ll;0;L;0072 030F;;;;N;;;0210;;0210 +0212;LATIN CAPITAL LETTER R WITH INVERTED BREVE;Lu;0;L;0052 0311;;;;N;;;;0213; +0213;LATIN SMALL LETTER R WITH INVERTED BREVE;Ll;0;L;0072 0311;;;;N;;;0212;;0212 +0214;LATIN CAPITAL LETTER U WITH DOUBLE GRAVE;Lu;0;L;0055 030F;;;;N;;;;0215; +0215;LATIN SMALL LETTER U WITH DOUBLE GRAVE;Ll;0;L;0075 030F;;;;N;;;0214;;0214 +0216;LATIN CAPITAL LETTER U WITH INVERTED BREVE;Lu;0;L;0055 0311;;;;N;;;;0217; +0217;LATIN SMALL LETTER U WITH INVERTED BREVE;Ll;0;L;0075 0311;;;;N;;;0216;;0216 +0218;LATIN CAPITAL LETTER S WITH COMMA BELOW;Lu;0;L;0053 0326;;;;N;;;;0219; +0219;LATIN SMALL LETTER S WITH COMMA BELOW;Ll;0;L;0073 0326;;;;N;;;0218;;0218 +021A;LATIN CAPITAL LETTER T WITH COMMA BELOW;Lu;0;L;0054 0326;;;;N;;;;021B; +021B;LATIN SMALL LETTER T WITH COMMA BELOW;Ll;0;L;0074 0326;;;;N;;;021A;;021A +021C;LATIN CAPITAL LETTER YOGH;Lu;0;L;;;;;N;;;;021D; +021D;LATIN SMALL LETTER YOGH;Ll;0;L;;;;;N;;;021C;;021C +021E;LATIN CAPITAL LETTER H WITH CARON;Lu;0;L;0048 030C;;;;N;;;;021F; +021F;LATIN SMALL LETTER H WITH CARON;Ll;0;L;0068 030C;;;;N;;;021E;;021E +0220;LATIN CAPITAL LETTER N WITH LONG RIGHT LEG;Lu;0;L;;;;;N;;;;019E; +0221;LATIN SMALL LETTER D WITH CURL;Ll;0;L;;;;;N;;;;; +0222;LATIN CAPITAL LETTER OU;Lu;0;L;;;;;N;;;;0223; +0223;LATIN SMALL LETTER OU;Ll;0;L;;;;;N;;;0222;;0222 +0224;LATIN CAPITAL LETTER Z WITH HOOK;Lu;0;L;;;;;N;;;;0225; +0225;LATIN SMALL LETTER Z WITH HOOK;Ll;0;L;;;;;N;;;0224;;0224 +0226;LATIN CAPITAL LETTER A WITH DOT ABOVE;Lu;0;L;0041 0307;;;;N;;;;0227; +0227;LATIN SMALL LETTER A WITH DOT ABOVE;Ll;0;L;0061 0307;;;;N;;;0226;;0226 +0228;LATIN CAPITAL LETTER E WITH CEDILLA;Lu;0;L;0045 0327;;;;N;;;;0229; +0229;LATIN SMALL LETTER E WITH CEDILLA;Ll;0;L;0065 0327;;;;N;;;0228;;0228 +022A;LATIN CAPITAL LETTER O WITH DIAERESIS AND MACRON;Lu;0;L;00D6 0304;;;;N;;;;022B; +022B;LATIN SMALL LETTER O WITH DIAERESIS AND MACRON;Ll;0;L;00F6 0304;;;;N;;;022A;;022A +022C;LATIN CAPITAL LETTER O WITH TILDE AND MACRON;Lu;0;L;00D5 0304;;;;N;;;;022D; +022D;LATIN SMALL LETTER O WITH TILDE AND MACRON;Ll;0;L;00F5 0304;;;;N;;;022C;;022C +022E;LATIN CAPITAL LETTER O WITH DOT ABOVE;Lu;0;L;004F 0307;;;;N;;;;022F; +022F;LATIN SMALL LETTER O WITH DOT ABOVE;Ll;0;L;006F 0307;;;;N;;;022E;;022E +0230;LATIN CAPITAL LETTER O WITH DOT ABOVE AND MACRON;Lu;0;L;022E 0304;;;;N;;;;0231; +0231;LATIN SMALL LETTER O WITH DOT ABOVE AND MACRON;Ll;0;L;022F 0304;;;;N;;;0230;;0230 +0232;LATIN CAPITAL LETTER Y WITH MACRON;Lu;0;L;0059 0304;;;;N;;;;0233; +0233;LATIN SMALL LETTER Y WITH MACRON;Ll;0;L;0079 0304;;;;N;;;0232;;0232 +0234;LATIN SMALL LETTER L WITH CURL;Ll;0;L;;;;;N;;;;; +0235;LATIN SMALL LETTER N WITH CURL;Ll;0;L;;;;;N;;;;; +0236;LATIN SMALL LETTER T WITH CURL;Ll;0;L;;;;;N;;;;; +0237;LATIN SMALL LETTER DOTLESS J;Ll;0;L;;;;;N;;;;; +0238;LATIN SMALL LETTER DB DIGRAPH;Ll;0;L;;;;;N;;;;; +0239;LATIN SMALL LETTER QP DIGRAPH;Ll;0;L;;;;;N;;;;; +023A;LATIN CAPITAL LETTER A WITH STROKE;Lu;0;L;;;;;N;;;;2C65; +023B;LATIN CAPITAL LETTER C WITH STROKE;Lu;0;L;;;;;N;;;;023C; +023C;LATIN SMALL LETTER C WITH STROKE;Ll;0;L;;;;;N;;;023B;;023B +023D;LATIN CAPITAL LETTER L WITH BAR;Lu;0;L;;;;;N;;;;019A; +023E;LATIN CAPITAL LETTER T WITH DIAGONAL STROKE;Lu;0;L;;;;;N;;;;2C66; +023F;LATIN SMALL LETTER S WITH SWASH TAIL;Ll;0;L;;;;;N;;;2C7E;;2C7E +0240;LATIN SMALL LETTER Z WITH SWASH TAIL;Ll;0;L;;;;;N;;;2C7F;;2C7F +0241;LATIN CAPITAL LETTER GLOTTAL STOP;Lu;0;L;;;;;N;;;;0242; +0242;LATIN SMALL LETTER GLOTTAL STOP;Ll;0;L;;;;;N;;;0241;;0241 +0243;LATIN CAPITAL LETTER B WITH STROKE;Lu;0;L;;;;;N;;;;0180; +0244;LATIN CAPITAL LETTER U BAR;Lu;0;L;;;;;N;;;;0289; +0245;LATIN CAPITAL LETTER TURNED V;Lu;0;L;;;;;N;;;;028C; +0246;LATIN CAPITAL LETTER E WITH STROKE;Lu;0;L;;;;;N;;;;0247; +0247;LATIN SMALL LETTER E WITH STROKE;Ll;0;L;;;;;N;;;0246;;0246 +0248;LATIN CAPITAL LETTER J WITH STROKE;Lu;0;L;;;;;N;;;;0249; +0249;LATIN SMALL LETTER J WITH STROKE;Ll;0;L;;;;;N;;;0248;;0248 +024A;LATIN CAPITAL LETTER SMALL Q WITH HOOK TAIL;Lu;0;L;;;;;N;;;;024B; +024B;LATIN SMALL LETTER Q WITH HOOK TAIL;Ll;0;L;;;;;N;;;024A;;024A +024C;LATIN CAPITAL LETTER R WITH STROKE;Lu;0;L;;;;;N;;;;024D; +024D;LATIN SMALL LETTER R WITH STROKE;Ll;0;L;;;;;N;;;024C;;024C +024E;LATIN CAPITAL LETTER Y WITH STROKE;Lu;0;L;;;;;N;;;;024F; +024F;LATIN SMALL LETTER Y WITH STROKE;Ll;0;L;;;;;N;;;024E;;024E +0250;LATIN SMALL LETTER TURNED A;Ll;0;L;;;;;N;;;2C6F;;2C6F +0251;LATIN SMALL LETTER ALPHA;Ll;0;L;;;;;N;LATIN SMALL LETTER SCRIPT A;;2C6D;;2C6D +0252;LATIN SMALL LETTER TURNED ALPHA;Ll;0;L;;;;;N;LATIN SMALL LETTER TURNED SCRIPT A;;2C70;;2C70 +0253;LATIN SMALL LETTER B WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER B HOOK;;0181;;0181 +0254;LATIN SMALL LETTER OPEN O;Ll;0;L;;;;;N;;;0186;;0186 +0255;LATIN SMALL LETTER C WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER C CURL;;;; +0256;LATIN SMALL LETTER D WITH TAIL;Ll;0;L;;;;;N;LATIN SMALL LETTER D RETROFLEX HOOK;;0189;;0189 +0257;LATIN SMALL LETTER D WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER D HOOK;;018A;;018A +0258;LATIN SMALL LETTER REVERSED E;Ll;0;L;;;;;N;;;;; +0259;LATIN SMALL LETTER SCHWA;Ll;0;L;;;;;N;;;018F;;018F +025A;LATIN SMALL LETTER SCHWA WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER SCHWA HOOK;;;; +025B;LATIN SMALL LETTER OPEN E;Ll;0;L;;;;;N;LATIN SMALL LETTER EPSILON;;0190;;0190 +025C;LATIN SMALL LETTER REVERSED OPEN E;Ll;0;L;;;;;N;LATIN SMALL LETTER REVERSED EPSILON;;;; +025D;LATIN SMALL LETTER REVERSED OPEN E WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER REVERSED EPSILON HOOK;;;; +025E;LATIN SMALL LETTER CLOSED REVERSED OPEN E;Ll;0;L;;;;;N;LATIN SMALL LETTER CLOSED REVERSED EPSILON;;;; +025F;LATIN SMALL LETTER DOTLESS J WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER DOTLESS J BAR;;;; +0260;LATIN SMALL LETTER G WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER G HOOK;;0193;;0193 +0261;LATIN SMALL LETTER SCRIPT G;Ll;0;L;;;;;N;;;;; +0262;LATIN LETTER SMALL CAPITAL G;Ll;0;L;;;;;N;;;;; +0263;LATIN SMALL LETTER GAMMA;Ll;0;L;;;;;N;;;0194;;0194 +0264;LATIN SMALL LETTER RAMS HORN;Ll;0;L;;;;;N;LATIN SMALL LETTER BABY GAMMA;;;; +0265;LATIN SMALL LETTER TURNED H;Ll;0;L;;;;;N;;;A78D;;A78D +0266;LATIN SMALL LETTER H WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER H HOOK;;A7AA;;A7AA +0267;LATIN SMALL LETTER HENG WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER HENG HOOK;;;; +0268;LATIN SMALL LETTER I WITH STROKE;Ll;0;L;;;;;N;LATIN SMALL LETTER BARRED I;;0197;;0197 +0269;LATIN SMALL LETTER IOTA;Ll;0;L;;;;;N;;;0196;;0196 +026A;LATIN LETTER SMALL CAPITAL I;Ll;0;L;;;;;N;;;;; +026B;LATIN SMALL LETTER L WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;2C62;;2C62 +026C;LATIN SMALL LETTER L WITH BELT;Ll;0;L;;;;;N;LATIN SMALL LETTER L BELT;;;; +026D;LATIN SMALL LETTER L WITH RETROFLEX HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER L RETROFLEX HOOK;;;; +026E;LATIN SMALL LETTER LEZH;Ll;0;L;;;;;N;LATIN SMALL LETTER L YOGH;;;; +026F;LATIN SMALL LETTER TURNED M;Ll;0;L;;;;;N;;;019C;;019C +0270;LATIN SMALL LETTER TURNED M WITH LONG LEG;Ll;0;L;;;;;N;;;;; +0271;LATIN SMALL LETTER M WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER M HOOK;;2C6E;;2C6E +0272;LATIN SMALL LETTER N WITH LEFT HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER N HOOK;;019D;;019D +0273;LATIN SMALL LETTER N WITH RETROFLEX HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER N RETROFLEX HOOK;;;; +0274;LATIN LETTER SMALL CAPITAL N;Ll;0;L;;;;;N;;;;; +0275;LATIN SMALL LETTER BARRED O;Ll;0;L;;;;;N;;;019F;;019F +0276;LATIN LETTER SMALL CAPITAL OE;Ll;0;L;;;;;N;LATIN LETTER SMALL CAPITAL O E;;;; +0277;LATIN SMALL LETTER CLOSED OMEGA;Ll;0;L;;;;;N;;;;; +0278;LATIN SMALL LETTER PHI;Ll;0;L;;;;;N;;;;; +0279;LATIN SMALL LETTER TURNED R;Ll;0;L;;;;;N;;;;; +027A;LATIN SMALL LETTER TURNED R WITH LONG LEG;Ll;0;L;;;;;N;;;;; +027B;LATIN SMALL LETTER TURNED R WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER TURNED R HOOK;;;; +027C;LATIN SMALL LETTER R WITH LONG LEG;Ll;0;L;;;;;N;;;;; +027D;LATIN SMALL LETTER R WITH TAIL;Ll;0;L;;;;;N;LATIN SMALL LETTER R HOOK;;2C64;;2C64 +027E;LATIN SMALL LETTER R WITH FISHHOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER FISHHOOK R;;;; +027F;LATIN SMALL LETTER REVERSED R WITH FISHHOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER REVERSED FISHHOOK R;;;; +0280;LATIN LETTER SMALL CAPITAL R;Ll;0;L;;;;;N;;;01A6;;01A6 +0281;LATIN LETTER SMALL CAPITAL INVERTED R;Ll;0;L;;;;;N;;;;; +0282;LATIN SMALL LETTER S WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER S HOOK;;;; +0283;LATIN SMALL LETTER ESH;Ll;0;L;;;;;N;;;01A9;;01A9 +0284;LATIN SMALL LETTER DOTLESS J WITH STROKE AND HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER DOTLESS J BAR HOOK;;;; +0285;LATIN SMALL LETTER SQUAT REVERSED ESH;Ll;0;L;;;;;N;;;;; +0286;LATIN SMALL LETTER ESH WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER ESH CURL;;;; +0287;LATIN SMALL LETTER TURNED T;Ll;0;L;;;;;N;;;;; +0288;LATIN SMALL LETTER T WITH RETROFLEX HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER T RETROFLEX HOOK;;01AE;;01AE +0289;LATIN SMALL LETTER U BAR;Ll;0;L;;;;;N;;;0244;;0244 +028A;LATIN SMALL LETTER UPSILON;Ll;0;L;;;;;N;;;01B1;;01B1 +028B;LATIN SMALL LETTER V WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER SCRIPT V;;01B2;;01B2 +028C;LATIN SMALL LETTER TURNED V;Ll;0;L;;;;;N;;;0245;;0245 +028D;LATIN SMALL LETTER TURNED W;Ll;0;L;;;;;N;;;;; +028E;LATIN SMALL LETTER TURNED Y;Ll;0;L;;;;;N;;;;; +028F;LATIN LETTER SMALL CAPITAL Y;Ll;0;L;;;;;N;;;;; +0290;LATIN SMALL LETTER Z WITH RETROFLEX HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER Z RETROFLEX HOOK;;;; +0291;LATIN SMALL LETTER Z WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER Z CURL;;;; +0292;LATIN SMALL LETTER EZH;Ll;0;L;;;;;N;LATIN SMALL LETTER YOGH;;01B7;;01B7 +0293;LATIN SMALL LETTER EZH WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER YOGH CURL;;;; +0294;LATIN LETTER GLOTTAL STOP;Lo;0;L;;;;;N;;;;; +0295;LATIN LETTER PHARYNGEAL VOICED FRICATIVE;Ll;0;L;;;;;N;LATIN LETTER REVERSED GLOTTAL STOP;;;; +0296;LATIN LETTER INVERTED GLOTTAL STOP;Ll;0;L;;;;;N;;;;; +0297;LATIN LETTER STRETCHED C;Ll;0;L;;;;;N;;;;; +0298;LATIN LETTER BILABIAL CLICK;Ll;0;L;;;;;N;LATIN LETTER BULLSEYE;;;; +0299;LATIN LETTER SMALL CAPITAL B;Ll;0;L;;;;;N;;;;; +029A;LATIN SMALL LETTER CLOSED OPEN E;Ll;0;L;;;;;N;LATIN SMALL LETTER CLOSED EPSILON;;;; +029B;LATIN LETTER SMALL CAPITAL G WITH HOOK;Ll;0;L;;;;;N;LATIN LETTER SMALL CAPITAL G HOOK;;;; +029C;LATIN LETTER SMALL CAPITAL H;Ll;0;L;;;;;N;;;;; +029D;LATIN SMALL LETTER J WITH CROSSED-TAIL;Ll;0;L;;;;;N;LATIN SMALL LETTER CROSSED-TAIL J;;;; +029E;LATIN SMALL LETTER TURNED K;Ll;0;L;;;;;N;;;;; +029F;LATIN LETTER SMALL CAPITAL L;Ll;0;L;;;;;N;;;;; +02A0;LATIN SMALL LETTER Q WITH HOOK;Ll;0;L;;;;;N;LATIN SMALL LETTER Q HOOK;;;; +02A1;LATIN LETTER GLOTTAL STOP WITH STROKE;Ll;0;L;;;;;N;LATIN LETTER GLOTTAL STOP BAR;;;; +02A2;LATIN LETTER REVERSED GLOTTAL STOP WITH STROKE;Ll;0;L;;;;;N;LATIN LETTER REVERSED GLOTTAL STOP BAR;;;; +02A3;LATIN SMALL LETTER DZ DIGRAPH;Ll;0;L;;;;;N;LATIN SMALL LETTER D Z;;;; +02A4;LATIN SMALL LETTER DEZH DIGRAPH;Ll;0;L;;;;;N;LATIN SMALL LETTER D YOGH;;;; +02A5;LATIN SMALL LETTER DZ DIGRAPH WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER D Z CURL;;;; +02A6;LATIN SMALL LETTER TS DIGRAPH;Ll;0;L;;;;;N;LATIN SMALL LETTER T S;;;; +02A7;LATIN SMALL LETTER TESH DIGRAPH;Ll;0;L;;;;;N;LATIN SMALL LETTER T ESH;;;; +02A8;LATIN SMALL LETTER TC DIGRAPH WITH CURL;Ll;0;L;;;;;N;LATIN SMALL LETTER T C CURL;;;; +02A9;LATIN SMALL LETTER FENG DIGRAPH;Ll;0;L;;;;;N;;;;; +02AA;LATIN SMALL LETTER LS DIGRAPH;Ll;0;L;;;;;N;;;;; +02AB;LATIN SMALL LETTER LZ DIGRAPH;Ll;0;L;;;;;N;;;;; +02AC;LATIN LETTER BILABIAL PERCUSSIVE;Ll;0;L;;;;;N;;;;; +02AD;LATIN LETTER BIDENTAL PERCUSSIVE;Ll;0;L;;;;;N;;;;; +02AE;LATIN SMALL LETTER TURNED H WITH FISHHOOK;Ll;0;L;;;;;N;;;;; +02AF;LATIN SMALL LETTER TURNED H WITH FISHHOOK AND TAIL;Ll;0;L;;;;;N;;;;; +02B0;MODIFIER LETTER SMALL H;Lm;0;L; 0068;;;;N;;;;; +02B1;MODIFIER LETTER SMALL H WITH HOOK;Lm;0;L; 0266;;;;N;MODIFIER LETTER SMALL H HOOK;;;; +02B2;MODIFIER LETTER SMALL J;Lm;0;L; 006A;;;;N;;;;; +02B3;MODIFIER LETTER SMALL R;Lm;0;L; 0072;;;;N;;;;; +02B4;MODIFIER LETTER SMALL TURNED R;Lm;0;L; 0279;;;;N;;;;; +02B5;MODIFIER LETTER SMALL TURNED R WITH HOOK;Lm;0;L; 027B;;;;N;MODIFIER LETTER SMALL TURNED R HOOK;;;; +02B6;MODIFIER LETTER SMALL CAPITAL INVERTED R;Lm;0;L; 0281;;;;N;;;;; +02B7;MODIFIER LETTER SMALL W;Lm;0;L; 0077;;;;N;;;;; +02B8;MODIFIER LETTER SMALL Y;Lm;0;L; 0079;;;;N;;;;; +02B9;MODIFIER LETTER PRIME;Lm;0;ON;;;;;N;;;;; +02BA;MODIFIER LETTER DOUBLE PRIME;Lm;0;ON;;;;;N;;;;; +02BB;MODIFIER LETTER TURNED COMMA;Lm;0;L;;;;;N;;;;; +02BC;MODIFIER LETTER APOSTROPHE;Lm;0;L;;;;;N;;;;; +02BD;MODIFIER LETTER REVERSED COMMA;Lm;0;L;;;;;N;;;;; +02BE;MODIFIER LETTER RIGHT HALF RING;Lm;0;L;;;;;N;;;;; +02BF;MODIFIER LETTER LEFT HALF RING;Lm;0;L;;;;;N;;;;; +02C0;MODIFIER LETTER GLOTTAL STOP;Lm;0;L;;;;;N;;;;; +02C1;MODIFIER LETTER REVERSED GLOTTAL STOP;Lm;0;L;;;;;N;;;;; +02C2;MODIFIER LETTER LEFT ARROWHEAD;Sk;0;ON;;;;;N;;;;; +02C3;MODIFIER LETTER RIGHT ARROWHEAD;Sk;0;ON;;;;;N;;;;; +02C4;MODIFIER LETTER UP ARROWHEAD;Sk;0;ON;;;;;N;;;;; +02C5;MODIFIER LETTER DOWN ARROWHEAD;Sk;0;ON;;;;;N;;;;; +02C6;MODIFIER LETTER CIRCUMFLEX ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER CIRCUMFLEX;;;; +02C7;CARON;Lm;0;ON;;;;;N;MODIFIER LETTER HACEK;;;; +02C8;MODIFIER LETTER VERTICAL LINE;Lm;0;ON;;;;;N;;;;; +02C9;MODIFIER LETTER MACRON;Lm;0;ON;;;;;N;;;;; +02CA;MODIFIER LETTER ACUTE ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER ACUTE;;;; +02CB;MODIFIER LETTER GRAVE ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER GRAVE;;;; +02CC;MODIFIER LETTER LOW VERTICAL LINE;Lm;0;ON;;;;;N;;;;; +02CD;MODIFIER LETTER LOW MACRON;Lm;0;ON;;;;;N;;;;; +02CE;MODIFIER LETTER LOW GRAVE ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER LOW GRAVE;;;; +02CF;MODIFIER LETTER LOW ACUTE ACCENT;Lm;0;ON;;;;;N;MODIFIER LETTER LOW ACUTE;;;; +02D0;MODIFIER LETTER TRIANGULAR COLON;Lm;0;L;;;;;N;;;;; +02D1;MODIFIER LETTER HALF TRIANGULAR COLON;Lm;0;L;;;;;N;;;;; +02D2;MODIFIER LETTER CENTRED RIGHT HALF RING;Sk;0;ON;;;;;N;MODIFIER LETTER CENTERED RIGHT HALF RING;;;; +02D3;MODIFIER LETTER CENTRED LEFT HALF RING;Sk;0;ON;;;;;N;MODIFIER LETTER CENTERED LEFT HALF RING;;;; +02D4;MODIFIER LETTER UP TACK;Sk;0;ON;;;;;N;;;;; +02D5;MODIFIER LETTER DOWN TACK;Sk;0;ON;;;;;N;;;;; +02D6;MODIFIER LETTER PLUS SIGN;Sk;0;ON;;;;;N;;;;; +02D7;MODIFIER LETTER MINUS SIGN;Sk;0;ON;;;;;N;;;;; +02D8;BREVE;Sk;0;ON; 0020 0306;;;;N;SPACING BREVE;;;; +02D9;DOT ABOVE;Sk;0;ON; 0020 0307;;;;N;SPACING DOT ABOVE;;;; +02DA;RING ABOVE;Sk;0;ON; 0020 030A;;;;N;SPACING RING ABOVE;;;; +02DB;OGONEK;Sk;0;ON; 0020 0328;;;;N;SPACING OGONEK;;;; +02DC;SMALL TILDE;Sk;0;ON; 0020 0303;;;;N;SPACING TILDE;;;; +02DD;DOUBLE ACUTE ACCENT;Sk;0;ON; 0020 030B;;;;N;SPACING DOUBLE ACUTE;;;; +02DE;MODIFIER LETTER RHOTIC HOOK;Sk;0;ON;;;;;N;;;;; +02DF;MODIFIER LETTER CROSS ACCENT;Sk;0;ON;;;;;N;;;;; +02E0;MODIFIER LETTER SMALL GAMMA;Lm;0;L; 0263;;;;N;;;;; +02E1;MODIFIER LETTER SMALL L;Lm;0;L; 006C;;;;N;;;;; +02E2;MODIFIER LETTER SMALL S;Lm;0;L; 0073;;;;N;;;;; +02E3;MODIFIER LETTER SMALL X;Lm;0;L; 0078;;;;N;;;;; +02E4;MODIFIER LETTER SMALL REVERSED GLOTTAL STOP;Lm;0;L; 0295;;;;N;;;;; +02E5;MODIFIER LETTER EXTRA-HIGH TONE BAR;Sk;0;ON;;;;;N;;;;; +02E6;MODIFIER LETTER HIGH TONE BAR;Sk;0;ON;;;;;N;;;;; +02E7;MODIFIER LETTER MID TONE BAR;Sk;0;ON;;;;;N;;;;; +02E8;MODIFIER LETTER LOW TONE BAR;Sk;0;ON;;;;;N;;;;; +02E9;MODIFIER LETTER EXTRA-LOW TONE BAR;Sk;0;ON;;;;;N;;;;; +02EA;MODIFIER LETTER YIN DEPARTING TONE MARK;Sk;0;ON;;;;;N;;;;; +02EB;MODIFIER LETTER YANG DEPARTING TONE MARK;Sk;0;ON;;;;;N;;;;; +02EC;MODIFIER LETTER VOICING;Lm;0;ON;;;;;N;;;;; +02ED;MODIFIER LETTER UNASPIRATED;Sk;0;ON;;;;;N;;;;; +02EE;MODIFIER LETTER DOUBLE APOSTROPHE;Lm;0;L;;;;;N;;;;; +02EF;MODIFIER LETTER LOW DOWN ARROWHEAD;Sk;0;ON;;;;;N;;;;; +02F0;MODIFIER LETTER LOW UP ARROWHEAD;Sk;0;ON;;;;;N;;;;; +02F1;MODIFIER LETTER LOW LEFT ARROWHEAD;Sk;0;ON;;;;;N;;;;; +02F2;MODIFIER LETTER LOW RIGHT ARROWHEAD;Sk;0;ON;;;;;N;;;;; +02F3;MODIFIER LETTER LOW RING;Sk;0;ON;;;;;N;;;;; +02F4;MODIFIER LETTER MIDDLE GRAVE ACCENT;Sk;0;ON;;;;;N;;;;; +02F5;MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT;Sk;0;ON;;;;;N;;;;; +02F6;MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT;Sk;0;ON;;;;;N;;;;; +02F7;MODIFIER LETTER LOW TILDE;Sk;0;ON;;;;;N;;;;; +02F8;MODIFIER LETTER RAISED COLON;Sk;0;ON;;;;;N;;;;; +02F9;MODIFIER LETTER BEGIN HIGH TONE;Sk;0;ON;;;;;N;;;;; +02FA;MODIFIER LETTER END HIGH TONE;Sk;0;ON;;;;;N;;;;; +02FB;MODIFIER LETTER BEGIN LOW TONE;Sk;0;ON;;;;;N;;;;; +02FC;MODIFIER LETTER END LOW TONE;Sk;0;ON;;;;;N;;;;; +02FD;MODIFIER LETTER SHELF;Sk;0;ON;;;;;N;;;;; +02FE;MODIFIER LETTER OPEN SHELF;Sk;0;ON;;;;;N;;;;; +02FF;MODIFIER LETTER LOW LEFT ARROW;Sk;0;ON;;;;;N;;;;; +0300;COMBINING GRAVE ACCENT;Mn;230;NSM;;;;;N;NON-SPACING GRAVE;;;; +0301;COMBINING ACUTE ACCENT;Mn;230;NSM;;;;;N;NON-SPACING ACUTE;;;; +0302;COMBINING CIRCUMFLEX ACCENT;Mn;230;NSM;;;;;N;NON-SPACING CIRCUMFLEX;;;; +0303;COMBINING TILDE;Mn;230;NSM;;;;;N;NON-SPACING TILDE;;;; +0304;COMBINING MACRON;Mn;230;NSM;;;;;N;NON-SPACING MACRON;;;; +0305;COMBINING OVERLINE;Mn;230;NSM;;;;;N;NON-SPACING OVERSCORE;;;; +0306;COMBINING BREVE;Mn;230;NSM;;;;;N;NON-SPACING BREVE;;;; +0307;COMBINING DOT ABOVE;Mn;230;NSM;;;;;N;NON-SPACING DOT ABOVE;;;; +0308;COMBINING DIAERESIS;Mn;230;NSM;;;;;N;NON-SPACING DIAERESIS;;;; +0309;COMBINING HOOK ABOVE;Mn;230;NSM;;;;;N;NON-SPACING HOOK ABOVE;;;; +030A;COMBINING RING ABOVE;Mn;230;NSM;;;;;N;NON-SPACING RING ABOVE;;;; +030B;COMBINING DOUBLE ACUTE ACCENT;Mn;230;NSM;;;;;N;NON-SPACING DOUBLE ACUTE;;;; +030C;COMBINING CARON;Mn;230;NSM;;;;;N;NON-SPACING HACEK;;;; +030D;COMBINING VERTICAL LINE ABOVE;Mn;230;NSM;;;;;N;NON-SPACING VERTICAL LINE ABOVE;;;; +030E;COMBINING DOUBLE VERTICAL LINE ABOVE;Mn;230;NSM;;;;;N;NON-SPACING DOUBLE VERTICAL LINE ABOVE;;;; +030F;COMBINING DOUBLE GRAVE ACCENT;Mn;230;NSM;;;;;N;NON-SPACING DOUBLE GRAVE;;;; +0310;COMBINING CANDRABINDU;Mn;230;NSM;;;;;N;NON-SPACING CANDRABINDU;;;; +0311;COMBINING INVERTED BREVE;Mn;230;NSM;;;;;N;NON-SPACING INVERTED BREVE;;;; +0312;COMBINING TURNED COMMA ABOVE;Mn;230;NSM;;;;;N;NON-SPACING TURNED COMMA ABOVE;;;; +0313;COMBINING COMMA ABOVE;Mn;230;NSM;;;;;N;NON-SPACING COMMA ABOVE;;;; +0314;COMBINING REVERSED COMMA ABOVE;Mn;230;NSM;;;;;N;NON-SPACING REVERSED COMMA ABOVE;;;; +0315;COMBINING COMMA ABOVE RIGHT;Mn;232;NSM;;;;;N;NON-SPACING COMMA ABOVE RIGHT;;;; +0316;COMBINING GRAVE ACCENT BELOW;Mn;220;NSM;;;;;N;NON-SPACING GRAVE BELOW;;;; +0317;COMBINING ACUTE ACCENT BELOW;Mn;220;NSM;;;;;N;NON-SPACING ACUTE BELOW;;;; +0318;COMBINING LEFT TACK BELOW;Mn;220;NSM;;;;;N;NON-SPACING LEFT TACK BELOW;;;; +0319;COMBINING RIGHT TACK BELOW;Mn;220;NSM;;;;;N;NON-SPACING RIGHT TACK BELOW;;;; +031A;COMBINING LEFT ANGLE ABOVE;Mn;232;NSM;;;;;N;NON-SPACING LEFT ANGLE ABOVE;;;; +031B;COMBINING HORN;Mn;216;NSM;;;;;N;NON-SPACING HORN;;;; +031C;COMBINING LEFT HALF RING BELOW;Mn;220;NSM;;;;;N;NON-SPACING LEFT HALF RING BELOW;;;; +031D;COMBINING UP TACK BELOW;Mn;220;NSM;;;;;N;NON-SPACING UP TACK BELOW;;;; +031E;COMBINING DOWN TACK BELOW;Mn;220;NSM;;;;;N;NON-SPACING DOWN TACK BELOW;;;; +031F;COMBINING PLUS SIGN BELOW;Mn;220;NSM;;;;;N;NON-SPACING PLUS SIGN BELOW;;;; +0320;COMBINING MINUS SIGN BELOW;Mn;220;NSM;;;;;N;NON-SPACING MINUS SIGN BELOW;;;; +0321;COMBINING PALATALIZED HOOK BELOW;Mn;202;NSM;;;;;N;NON-SPACING PALATALIZED HOOK BELOW;;;; +0322;COMBINING RETROFLEX HOOK BELOW;Mn;202;NSM;;;;;N;NON-SPACING RETROFLEX HOOK BELOW;;;; +0323;COMBINING DOT BELOW;Mn;220;NSM;;;;;N;NON-SPACING DOT BELOW;;;; +0324;COMBINING DIAERESIS BELOW;Mn;220;NSM;;;;;N;NON-SPACING DOUBLE DOT BELOW;;;; +0325;COMBINING RING BELOW;Mn;220;NSM;;;;;N;NON-SPACING RING BELOW;;;; +0326;COMBINING COMMA BELOW;Mn;220;NSM;;;;;N;NON-SPACING COMMA BELOW;;;; +0327;COMBINING CEDILLA;Mn;202;NSM;;;;;N;NON-SPACING CEDILLA;;;; +0328;COMBINING OGONEK;Mn;202;NSM;;;;;N;NON-SPACING OGONEK;;;; +0329;COMBINING VERTICAL LINE BELOW;Mn;220;NSM;;;;;N;NON-SPACING VERTICAL LINE BELOW;;;; +032A;COMBINING BRIDGE BELOW;Mn;220;NSM;;;;;N;NON-SPACING BRIDGE BELOW;;;; +032B;COMBINING INVERTED DOUBLE ARCH BELOW;Mn;220;NSM;;;;;N;NON-SPACING INVERTED DOUBLE ARCH BELOW;;;; +032C;COMBINING CARON BELOW;Mn;220;NSM;;;;;N;NON-SPACING HACEK BELOW;;;; +032D;COMBINING CIRCUMFLEX ACCENT BELOW;Mn;220;NSM;;;;;N;NON-SPACING CIRCUMFLEX BELOW;;;; +032E;COMBINING BREVE BELOW;Mn;220;NSM;;;;;N;NON-SPACING BREVE BELOW;;;; +032F;COMBINING INVERTED BREVE BELOW;Mn;220;NSM;;;;;N;NON-SPACING INVERTED BREVE BELOW;;;; +0330;COMBINING TILDE BELOW;Mn;220;NSM;;;;;N;NON-SPACING TILDE BELOW;;;; +0331;COMBINING MACRON BELOW;Mn;220;NSM;;;;;N;NON-SPACING MACRON BELOW;;;; +0332;COMBINING LOW LINE;Mn;220;NSM;;;;;N;NON-SPACING UNDERSCORE;;;; +0333;COMBINING DOUBLE LOW LINE;Mn;220;NSM;;;;;N;NON-SPACING DOUBLE UNDERSCORE;;;; +0334;COMBINING TILDE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING TILDE OVERLAY;;;; +0335;COMBINING SHORT STROKE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING SHORT BAR OVERLAY;;;; +0336;COMBINING LONG STROKE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING LONG BAR OVERLAY;;;; +0337;COMBINING SHORT SOLIDUS OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING SHORT SLASH OVERLAY;;;; +0338;COMBINING LONG SOLIDUS OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING LONG SLASH OVERLAY;;;; +0339;COMBINING RIGHT HALF RING BELOW;Mn;220;NSM;;;;;N;NON-SPACING RIGHT HALF RING BELOW;;;; +033A;COMBINING INVERTED BRIDGE BELOW;Mn;220;NSM;;;;;N;NON-SPACING INVERTED BRIDGE BELOW;;;; +033B;COMBINING SQUARE BELOW;Mn;220;NSM;;;;;N;NON-SPACING SQUARE BELOW;;;; +033C;COMBINING SEAGULL BELOW;Mn;220;NSM;;;;;N;NON-SPACING SEAGULL BELOW;;;; +033D;COMBINING X ABOVE;Mn;230;NSM;;;;;N;NON-SPACING X ABOVE;;;; +033E;COMBINING VERTICAL TILDE;Mn;230;NSM;;;;;N;NON-SPACING VERTICAL TILDE;;;; +033F;COMBINING DOUBLE OVERLINE;Mn;230;NSM;;;;;N;NON-SPACING DOUBLE OVERSCORE;;;; +0340;COMBINING GRAVE TONE MARK;Mn;230;NSM;0300;;;;N;NON-SPACING GRAVE TONE MARK;;;; +0341;COMBINING ACUTE TONE MARK;Mn;230;NSM;0301;;;;N;NON-SPACING ACUTE TONE MARK;;;; +0342;COMBINING GREEK PERISPOMENI;Mn;230;NSM;;;;;N;;;;; +0343;COMBINING GREEK KORONIS;Mn;230;NSM;0313;;;;N;;;;; +0344;COMBINING GREEK DIALYTIKA TONOS;Mn;230;NSM;0308 0301;;;;N;GREEK NON-SPACING DIAERESIS TONOS;;;; +0345;COMBINING GREEK YPOGEGRAMMENI;Mn;240;NSM;;;;;N;GREEK NON-SPACING IOTA BELOW;;0399;;0399 +0346;COMBINING BRIDGE ABOVE;Mn;230;NSM;;;;;N;;;;; +0347;COMBINING EQUALS SIGN BELOW;Mn;220;NSM;;;;;N;;;;; +0348;COMBINING DOUBLE VERTICAL LINE BELOW;Mn;220;NSM;;;;;N;;;;; +0349;COMBINING LEFT ANGLE BELOW;Mn;220;NSM;;;;;N;;;;; +034A;COMBINING NOT TILDE ABOVE;Mn;230;NSM;;;;;N;;;;; +034B;COMBINING HOMOTHETIC ABOVE;Mn;230;NSM;;;;;N;;;;; +034C;COMBINING ALMOST EQUAL TO ABOVE;Mn;230;NSM;;;;;N;;;;; +034D;COMBINING LEFT RIGHT ARROW BELOW;Mn;220;NSM;;;;;N;;;;; +034E;COMBINING UPWARDS ARROW BELOW;Mn;220;NSM;;;;;N;;;;; +034F;COMBINING GRAPHEME JOINER;Mn;0;NSM;;;;;N;;;;; +0350;COMBINING RIGHT ARROWHEAD ABOVE;Mn;230;NSM;;;;;N;;;;; +0351;COMBINING LEFT HALF RING ABOVE;Mn;230;NSM;;;;;N;;;;; +0352;COMBINING FERMATA;Mn;230;NSM;;;;;N;;;;; +0353;COMBINING X BELOW;Mn;220;NSM;;;;;N;;;;; +0354;COMBINING LEFT ARROWHEAD BELOW;Mn;220;NSM;;;;;N;;;;; +0355;COMBINING RIGHT ARROWHEAD BELOW;Mn;220;NSM;;;;;N;;;;; +0356;COMBINING RIGHT ARROWHEAD AND UP ARROWHEAD BELOW;Mn;220;NSM;;;;;N;;;;; +0357;COMBINING RIGHT HALF RING ABOVE;Mn;230;NSM;;;;;N;;;;; +0358;COMBINING DOT ABOVE RIGHT;Mn;232;NSM;;;;;N;;;;; +0359;COMBINING ASTERISK BELOW;Mn;220;NSM;;;;;N;;;;; +035A;COMBINING DOUBLE RING BELOW;Mn;220;NSM;;;;;N;;;;; +035B;COMBINING ZIGZAG ABOVE;Mn;230;NSM;;;;;N;;;;; +035C;COMBINING DOUBLE BREVE BELOW;Mn;233;NSM;;;;;N;;;;; +035D;COMBINING DOUBLE BREVE;Mn;234;NSM;;;;;N;;;;; +035E;COMBINING DOUBLE MACRON;Mn;234;NSM;;;;;N;;;;; +035F;COMBINING DOUBLE MACRON BELOW;Mn;233;NSM;;;;;N;;;;; +0360;COMBINING DOUBLE TILDE;Mn;234;NSM;;;;;N;;;;; +0361;COMBINING DOUBLE INVERTED BREVE;Mn;234;NSM;;;;;N;;;;; +0362;COMBINING DOUBLE RIGHTWARDS ARROW BELOW;Mn;233;NSM;;;;;N;;;;; +0363;COMBINING LATIN SMALL LETTER A;Mn;230;NSM;;;;;N;;;;; +0364;COMBINING LATIN SMALL LETTER E;Mn;230;NSM;;;;;N;;;;; +0365;COMBINING LATIN SMALL LETTER I;Mn;230;NSM;;;;;N;;;;; +0366;COMBINING LATIN SMALL LETTER O;Mn;230;NSM;;;;;N;;;;; +0367;COMBINING LATIN SMALL LETTER U;Mn;230;NSM;;;;;N;;;;; +0368;COMBINING LATIN SMALL LETTER C;Mn;230;NSM;;;;;N;;;;; +0369;COMBINING LATIN SMALL LETTER D;Mn;230;NSM;;;;;N;;;;; +036A;COMBINING LATIN SMALL LETTER H;Mn;230;NSM;;;;;N;;;;; +036B;COMBINING LATIN SMALL LETTER M;Mn;230;NSM;;;;;N;;;;; +036C;COMBINING LATIN SMALL LETTER R;Mn;230;NSM;;;;;N;;;;; +036D;COMBINING LATIN SMALL LETTER T;Mn;230;NSM;;;;;N;;;;; +036E;COMBINING LATIN SMALL LETTER V;Mn;230;NSM;;;;;N;;;;; +036F;COMBINING LATIN SMALL LETTER X;Mn;230;NSM;;;;;N;;;;; +0370;GREEK CAPITAL LETTER HETA;Lu;0;L;;;;;N;;;;0371; +0371;GREEK SMALL LETTER HETA;Ll;0;L;;;;;N;;;0370;;0370 +0372;GREEK CAPITAL LETTER ARCHAIC SAMPI;Lu;0;L;;;;;N;;;;0373; +0373;GREEK SMALL LETTER ARCHAIC SAMPI;Ll;0;L;;;;;N;;;0372;;0372 +0374;GREEK NUMERAL SIGN;Lm;0;ON;02B9;;;;N;GREEK UPPER NUMERAL SIGN;;;; +0375;GREEK LOWER NUMERAL SIGN;Sk;0;ON;;;;;N;;;;; +0376;GREEK CAPITAL LETTER PAMPHYLIAN DIGAMMA;Lu;0;L;;;;;N;;;;0377; +0377;GREEK SMALL LETTER PAMPHYLIAN DIGAMMA;Ll;0;L;;;;;N;;;0376;;0376 +037A;GREEK YPOGEGRAMMENI;Lm;0;L; 0020 0345;;;;N;GREEK SPACING IOTA BELOW;;;; +037B;GREEK SMALL REVERSED LUNATE SIGMA SYMBOL;Ll;0;L;;;;;N;;;03FD;;03FD +037C;GREEK SMALL DOTTED LUNATE SIGMA SYMBOL;Ll;0;L;;;;;N;;;03FE;;03FE +037D;GREEK SMALL REVERSED DOTTED LUNATE SIGMA SYMBOL;Ll;0;L;;;;;N;;;03FF;;03FF +037E;GREEK QUESTION MARK;Po;0;ON;003B;;;;N;;;;; +0384;GREEK TONOS;Sk;0;ON; 0020 0301;;;;N;GREEK SPACING TONOS;;;; +0385;GREEK DIALYTIKA TONOS;Sk;0;ON;00A8 0301;;;;N;GREEK SPACING DIAERESIS TONOS;;;; +0386;GREEK CAPITAL LETTER ALPHA WITH TONOS;Lu;0;L;0391 0301;;;;N;GREEK CAPITAL LETTER ALPHA TONOS;;;03AC; +0387;GREEK ANO TELEIA;Po;0;ON;00B7;;;;N;;;;; +0388;GREEK CAPITAL LETTER EPSILON WITH TONOS;Lu;0;L;0395 0301;;;;N;GREEK CAPITAL LETTER EPSILON TONOS;;;03AD; +0389;GREEK CAPITAL LETTER ETA WITH TONOS;Lu;0;L;0397 0301;;;;N;GREEK CAPITAL LETTER ETA TONOS;;;03AE; +038A;GREEK CAPITAL LETTER IOTA WITH TONOS;Lu;0;L;0399 0301;;;;N;GREEK CAPITAL LETTER IOTA TONOS;;;03AF; +038C;GREEK CAPITAL LETTER OMICRON WITH TONOS;Lu;0;L;039F 0301;;;;N;GREEK CAPITAL LETTER OMICRON TONOS;;;03CC; +038E;GREEK CAPITAL LETTER UPSILON WITH TONOS;Lu;0;L;03A5 0301;;;;N;GREEK CAPITAL LETTER UPSILON TONOS;;;03CD; +038F;GREEK CAPITAL LETTER OMEGA WITH TONOS;Lu;0;L;03A9 0301;;;;N;GREEK CAPITAL LETTER OMEGA TONOS;;;03CE; +0390;GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS;Ll;0;L;03CA 0301;;;;N;GREEK SMALL LETTER IOTA DIAERESIS TONOS;;;; +0391;GREEK CAPITAL LETTER ALPHA;Lu;0;L;;;;;N;;;;03B1; +0392;GREEK CAPITAL LETTER BETA;Lu;0;L;;;;;N;;;;03B2; +0393;GREEK CAPITAL LETTER GAMMA;Lu;0;L;;;;;N;;;;03B3; +0394;GREEK CAPITAL LETTER DELTA;Lu;0;L;;;;;N;;;;03B4; +0395;GREEK CAPITAL LETTER EPSILON;Lu;0;L;;;;;N;;;;03B5; +0396;GREEK CAPITAL LETTER ZETA;Lu;0;L;;;;;N;;;;03B6; +0397;GREEK CAPITAL LETTER ETA;Lu;0;L;;;;;N;;;;03B7; +0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8; +0399;GREEK CAPITAL LETTER IOTA;Lu;0;L;;;;;N;;;;03B9; +039A;GREEK CAPITAL LETTER KAPPA;Lu;0;L;;;;;N;;;;03BA; +039B;GREEK CAPITAL LETTER LAMDA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER LAMBDA;;;03BB; +039C;GREEK CAPITAL LETTER MU;Lu;0;L;;;;;N;;;;03BC; +039D;GREEK CAPITAL LETTER NU;Lu;0;L;;;;;N;;;;03BD; +039E;GREEK CAPITAL LETTER XI;Lu;0;L;;;;;N;;;;03BE; +039F;GREEK CAPITAL LETTER OMICRON;Lu;0;L;;;;;N;;;;03BF; +03A0;GREEK CAPITAL LETTER PI;Lu;0;L;;;;;N;;;;03C0; +03A1;GREEK CAPITAL LETTER RHO;Lu;0;L;;;;;N;;;;03C1; +03A3;GREEK CAPITAL LETTER SIGMA;Lu;0;L;;;;;N;;;;03C3; +03A4;GREEK CAPITAL LETTER TAU;Lu;0;L;;;;;N;;;;03C4; +03A5;GREEK CAPITAL LETTER UPSILON;Lu;0;L;;;;;N;;;;03C5; +03A6;GREEK CAPITAL LETTER PHI;Lu;0;L;;;;;N;;;;03C6; +03A7;GREEK CAPITAL LETTER CHI;Lu;0;L;;;;;N;;;;03C7; +03A8;GREEK CAPITAL LETTER PSI;Lu;0;L;;;;;N;;;;03C8; +03A9;GREEK CAPITAL LETTER OMEGA;Lu;0;L;;;;;N;;;;03C9; +03AA;GREEK CAPITAL LETTER IOTA WITH DIALYTIKA;Lu;0;L;0399 0308;;;;N;GREEK CAPITAL LETTER IOTA DIAERESIS;;;03CA; +03AB;GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA;Lu;0;L;03A5 0308;;;;N;GREEK CAPITAL LETTER UPSILON DIAERESIS;;;03CB; +03AC;GREEK SMALL LETTER ALPHA WITH TONOS;Ll;0;L;03B1 0301;;;;N;GREEK SMALL LETTER ALPHA TONOS;;0386;;0386 +03AD;GREEK SMALL LETTER EPSILON WITH TONOS;Ll;0;L;03B5 0301;;;;N;GREEK SMALL LETTER EPSILON TONOS;;0388;;0388 +03AE;GREEK SMALL LETTER ETA WITH TONOS;Ll;0;L;03B7 0301;;;;N;GREEK SMALL LETTER ETA TONOS;;0389;;0389 +03AF;GREEK SMALL LETTER IOTA WITH TONOS;Ll;0;L;03B9 0301;;;;N;GREEK SMALL LETTER IOTA TONOS;;038A;;038A +03B0;GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS;Ll;0;L;03CB 0301;;;;N;GREEK SMALL LETTER UPSILON DIAERESIS TONOS;;;; +03B1;GREEK SMALL LETTER ALPHA;Ll;0;L;;;;;N;;;0391;;0391 +03B2;GREEK SMALL LETTER BETA;Ll;0;L;;;;;N;;;0392;;0392 +03B3;GREEK SMALL LETTER GAMMA;Ll;0;L;;;;;N;;;0393;;0393 +03B4;GREEK SMALL LETTER DELTA;Ll;0;L;;;;;N;;;0394;;0394 +03B5;GREEK SMALL LETTER EPSILON;Ll;0;L;;;;;N;;;0395;;0395 +03B6;GREEK SMALL LETTER ZETA;Ll;0;L;;;;;N;;;0396;;0396 +03B7;GREEK SMALL LETTER ETA;Ll;0;L;;;;;N;;;0397;;0397 +03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 +03B9;GREEK SMALL LETTER IOTA;Ll;0;L;;;;;N;;;0399;;0399 +03BA;GREEK SMALL LETTER KAPPA;Ll;0;L;;;;;N;;;039A;;039A +03BB;GREEK SMALL LETTER LAMDA;Ll;0;L;;;;;N;GREEK SMALL LETTER LAMBDA;;039B;;039B +03BC;GREEK SMALL LETTER MU;Ll;0;L;;;;;N;;;039C;;039C +03BD;GREEK SMALL LETTER NU;Ll;0;L;;;;;N;;;039D;;039D +03BE;GREEK SMALL LETTER XI;Ll;0;L;;;;;N;;;039E;;039E +03BF;GREEK SMALL LETTER OMICRON;Ll;0;L;;;;;N;;;039F;;039F +03C0;GREEK SMALL LETTER PI;Ll;0;L;;;;;N;;;03A0;;03A0 +03C1;GREEK SMALL LETTER RHO;Ll;0;L;;;;;N;;;03A1;;03A1 +03C2;GREEK SMALL LETTER FINAL SIGMA;Ll;0;L;;;;;N;;;03A3;;03A3 +03C3;GREEK SMALL LETTER SIGMA;Ll;0;L;;;;;N;;;03A3;;03A3 +03C4;GREEK SMALL LETTER TAU;Ll;0;L;;;;;N;;;03A4;;03A4 +03C5;GREEK SMALL LETTER UPSILON;Ll;0;L;;;;;N;;;03A5;;03A5 +03C6;GREEK SMALL LETTER PHI;Ll;0;L;;;;;N;;;03A6;;03A6 +03C7;GREEK SMALL LETTER CHI;Ll;0;L;;;;;N;;;03A7;;03A7 +03C8;GREEK SMALL LETTER PSI;Ll;0;L;;;;;N;;;03A8;;03A8 +03C9;GREEK SMALL LETTER OMEGA;Ll;0;L;;;;;N;;;03A9;;03A9 +03CA;GREEK SMALL LETTER IOTA WITH DIALYTIKA;Ll;0;L;03B9 0308;;;;N;GREEK SMALL LETTER IOTA DIAERESIS;;03AA;;03AA +03CB;GREEK SMALL LETTER UPSILON WITH DIALYTIKA;Ll;0;L;03C5 0308;;;;N;GREEK SMALL LETTER UPSILON DIAERESIS;;03AB;;03AB +03CC;GREEK SMALL LETTER OMICRON WITH TONOS;Ll;0;L;03BF 0301;;;;N;GREEK SMALL LETTER OMICRON TONOS;;038C;;038C +03CD;GREEK SMALL LETTER UPSILON WITH TONOS;Ll;0;L;03C5 0301;;;;N;GREEK SMALL LETTER UPSILON TONOS;;038E;;038E +03CE;GREEK SMALL LETTER OMEGA WITH TONOS;Ll;0;L;03C9 0301;;;;N;GREEK SMALL LETTER OMEGA TONOS;;038F;;038F +03CF;GREEK CAPITAL KAI SYMBOL;Lu;0;L;;;;;N;;;;03D7; +03D0;GREEK BETA SYMBOL;Ll;0;L; 03B2;;;;N;GREEK SMALL LETTER CURLED BETA;;0392;;0392 +03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 +03D2;GREEK UPSILON WITH HOOK SYMBOL;Lu;0;L; 03A5;;;;N;GREEK CAPITAL LETTER UPSILON HOOK;;;; +03D3;GREEK UPSILON WITH ACUTE AND HOOK SYMBOL;Lu;0;L;03D2 0301;;;;N;GREEK CAPITAL LETTER UPSILON HOOK TONOS;;;; +03D4;GREEK UPSILON WITH DIAERESIS AND HOOK SYMBOL;Lu;0;L;03D2 0308;;;;N;GREEK CAPITAL LETTER UPSILON HOOK DIAERESIS;;;; +03D5;GREEK PHI SYMBOL;Ll;0;L; 03C6;;;;N;GREEK SMALL LETTER SCRIPT PHI;;03A6;;03A6 +03D6;GREEK PI SYMBOL;Ll;0;L; 03C0;;;;N;GREEK SMALL LETTER OMEGA PI;;03A0;;03A0 +03D7;GREEK KAI SYMBOL;Ll;0;L;;;;;N;;;03CF;;03CF +03D8;GREEK LETTER ARCHAIC KOPPA;Lu;0;L;;;;;N;;;;03D9; +03D9;GREEK SMALL LETTER ARCHAIC KOPPA;Ll;0;L;;;;;N;;;03D8;;03D8 +03DA;GREEK LETTER STIGMA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER STIGMA;;;03DB; +03DB;GREEK SMALL LETTER STIGMA;Ll;0;L;;;;;N;;;03DA;;03DA +03DC;GREEK LETTER DIGAMMA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER DIGAMMA;;;03DD; +03DD;GREEK SMALL LETTER DIGAMMA;Ll;0;L;;;;;N;;;03DC;;03DC +03DE;GREEK LETTER KOPPA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER KOPPA;;;03DF; +03DF;GREEK SMALL LETTER KOPPA;Ll;0;L;;;;;N;;;03DE;;03DE +03E0;GREEK LETTER SAMPI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER SAMPI;;;03E1; +03E1;GREEK SMALL LETTER SAMPI;Ll;0;L;;;;;N;;;03E0;;03E0 +03E2;COPTIC CAPITAL LETTER SHEI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER SHEI;;;03E3; +03E3;COPTIC SMALL LETTER SHEI;Ll;0;L;;;;;N;GREEK SMALL LETTER SHEI;;03E2;;03E2 +03E4;COPTIC CAPITAL LETTER FEI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER FEI;;;03E5; +03E5;COPTIC SMALL LETTER FEI;Ll;0;L;;;;;N;GREEK SMALL LETTER FEI;;03E4;;03E4 +03E6;COPTIC CAPITAL LETTER KHEI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER KHEI;;;03E7; +03E7;COPTIC SMALL LETTER KHEI;Ll;0;L;;;;;N;GREEK SMALL LETTER KHEI;;03E6;;03E6 +03E8;COPTIC CAPITAL LETTER HORI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER HORI;;;03E9; +03E9;COPTIC SMALL LETTER HORI;Ll;0;L;;;;;N;GREEK SMALL LETTER HORI;;03E8;;03E8 +03EA;COPTIC CAPITAL LETTER GANGIA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER GANGIA;;;03EB; +03EB;COPTIC SMALL LETTER GANGIA;Ll;0;L;;;;;N;GREEK SMALL LETTER GANGIA;;03EA;;03EA +03EC;COPTIC CAPITAL LETTER SHIMA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER SHIMA;;;03ED; +03ED;COPTIC SMALL LETTER SHIMA;Ll;0;L;;;;;N;GREEK SMALL LETTER SHIMA;;03EC;;03EC +03EE;COPTIC CAPITAL LETTER DEI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER DEI;;;03EF; +03EF;COPTIC SMALL LETTER DEI;Ll;0;L;;;;;N;GREEK SMALL LETTER DEI;;03EE;;03EE +03F0;GREEK KAPPA SYMBOL;Ll;0;L; 03BA;;;;N;GREEK SMALL LETTER SCRIPT KAPPA;;039A;;039A +03F1;GREEK RHO SYMBOL;Ll;0;L; 03C1;;;;N;GREEK SMALL LETTER TAILED RHO;;03A1;;03A1 +03F2;GREEK LUNATE SIGMA SYMBOL;Ll;0;L; 03C2;;;;N;GREEK SMALL LETTER LUNATE SIGMA;;03F9;;03F9 +03F3;GREEK LETTER YOT;Ll;0;L;;;;;N;;;;; +03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8; +03F5;GREEK LUNATE EPSILON SYMBOL;Ll;0;L; 03B5;;;;N;;;0395;;0395 +03F6;GREEK REVERSED LUNATE EPSILON SYMBOL;Sm;0;ON;;;;;N;;;;; +03F7;GREEK CAPITAL LETTER SHO;Lu;0;L;;;;;N;;;;03F8; +03F8;GREEK SMALL LETTER SHO;Ll;0;L;;;;;N;;;03F7;;03F7 +03F9;GREEK CAPITAL LUNATE SIGMA SYMBOL;Lu;0;L; 03A3;;;;N;;;;03F2; +03FA;GREEK CAPITAL LETTER SAN;Lu;0;L;;;;;N;;;;03FB; +03FB;GREEK SMALL LETTER SAN;Ll;0;L;;;;;N;;;03FA;;03FA +03FC;GREEK RHO WITH STROKE SYMBOL;Ll;0;L;;;;;N;;;;; +03FD;GREEK CAPITAL REVERSED LUNATE SIGMA SYMBOL;Lu;0;L;;;;;N;;;;037B; +03FE;GREEK CAPITAL DOTTED LUNATE SIGMA SYMBOL;Lu;0;L;;;;;N;;;;037C; +03FF;GREEK CAPITAL REVERSED DOTTED LUNATE SIGMA SYMBOL;Lu;0;L;;;;;N;;;;037D; +0400;CYRILLIC CAPITAL LETTER IE WITH GRAVE;Lu;0;L;0415 0300;;;;N;;;;0450; +0401;CYRILLIC CAPITAL LETTER IO;Lu;0;L;0415 0308;;;;N;;;;0451; +0402;CYRILLIC CAPITAL LETTER DJE;Lu;0;L;;;;;N;;;;0452; +0403;CYRILLIC CAPITAL LETTER GJE;Lu;0;L;0413 0301;;;;N;;;;0453; +0404;CYRILLIC CAPITAL LETTER UKRAINIAN IE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER E;;;0454; +0405;CYRILLIC CAPITAL LETTER DZE;Lu;0;L;;;;;N;;;;0455; +0406;CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER I;;;0456; +0407;CYRILLIC CAPITAL LETTER YI;Lu;0;L;0406 0308;;;;N;;;;0457; +0408;CYRILLIC CAPITAL LETTER JE;Lu;0;L;;;;;N;;;;0458; +0409;CYRILLIC CAPITAL LETTER LJE;Lu;0;L;;;;;N;;;;0459; +040A;CYRILLIC CAPITAL LETTER NJE;Lu;0;L;;;;;N;;;;045A; +040B;CYRILLIC CAPITAL LETTER TSHE;Lu;0;L;;;;;N;;;;045B; +040C;CYRILLIC CAPITAL LETTER KJE;Lu;0;L;041A 0301;;;;N;;;;045C; +040D;CYRILLIC CAPITAL LETTER I WITH GRAVE;Lu;0;L;0418 0300;;;;N;;;;045D; +040E;CYRILLIC CAPITAL LETTER SHORT U;Lu;0;L;0423 0306;;;;N;;;;045E; +040F;CYRILLIC CAPITAL LETTER DZHE;Lu;0;L;;;;;N;;;;045F; +0410;CYRILLIC CAPITAL LETTER A;Lu;0;L;;;;;N;;;;0430; +0411;CYRILLIC CAPITAL LETTER BE;Lu;0;L;;;;;N;;;;0431; +0412;CYRILLIC CAPITAL LETTER VE;Lu;0;L;;;;;N;;;;0432; +0413;CYRILLIC CAPITAL LETTER GHE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER GE;;;0433; +0414;CYRILLIC CAPITAL LETTER DE;Lu;0;L;;;;;N;;;;0434; +0415;CYRILLIC CAPITAL LETTER IE;Lu;0;L;;;;;N;;;;0435; +0416;CYRILLIC CAPITAL LETTER ZHE;Lu;0;L;;;;;N;;;;0436; +0417;CYRILLIC CAPITAL LETTER ZE;Lu;0;L;;;;;N;;;;0437; +0418;CYRILLIC CAPITAL LETTER I;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER II;;;0438; +0419;CYRILLIC CAPITAL LETTER SHORT I;Lu;0;L;0418 0306;;;;N;CYRILLIC CAPITAL LETTER SHORT II;;;0439; +041A;CYRILLIC CAPITAL LETTER KA;Lu;0;L;;;;;N;;;;043A; +041B;CYRILLIC CAPITAL LETTER EL;Lu;0;L;;;;;N;;;;043B; +041C;CYRILLIC CAPITAL LETTER EM;Lu;0;L;;;;;N;;;;043C; +041D;CYRILLIC CAPITAL LETTER EN;Lu;0;L;;;;;N;;;;043D; +041E;CYRILLIC CAPITAL LETTER O;Lu;0;L;;;;;N;;;;043E; +041F;CYRILLIC CAPITAL LETTER PE;Lu;0;L;;;;;N;;;;043F; +0420;CYRILLIC CAPITAL LETTER ER;Lu;0;L;;;;;N;;;;0440; +0421;CYRILLIC CAPITAL LETTER ES;Lu;0;L;;;;;N;;;;0441; +0422;CYRILLIC CAPITAL LETTER TE;Lu;0;L;;;;;N;;;;0442; +0423;CYRILLIC CAPITAL LETTER U;Lu;0;L;;;;;N;;;;0443; +0424;CYRILLIC CAPITAL LETTER EF;Lu;0;L;;;;;N;;;;0444; +0425;CYRILLIC CAPITAL LETTER HA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KHA;;;0445; +0426;CYRILLIC CAPITAL LETTER TSE;Lu;0;L;;;;;N;;;;0446; +0427;CYRILLIC CAPITAL LETTER CHE;Lu;0;L;;;;;N;;;;0447; +0428;CYRILLIC CAPITAL LETTER SHA;Lu;0;L;;;;;N;;;;0448; +0429;CYRILLIC CAPITAL LETTER SHCHA;Lu;0;L;;;;;N;;;;0449; +042A;CYRILLIC CAPITAL LETTER HARD SIGN;Lu;0;L;;;;;N;;;;044A; +042B;CYRILLIC CAPITAL LETTER YERU;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER YERI;;;044B; +042C;CYRILLIC CAPITAL LETTER SOFT SIGN;Lu;0;L;;;;;N;;;;044C; +042D;CYRILLIC CAPITAL LETTER E;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER REVERSED E;;;044D; +042E;CYRILLIC CAPITAL LETTER YU;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER IU;;;044E; +042F;CYRILLIC CAPITAL LETTER YA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER IA;;;044F; +0430;CYRILLIC SMALL LETTER A;Ll;0;L;;;;;N;;;0410;;0410 +0431;CYRILLIC SMALL LETTER BE;Ll;0;L;;;;;N;;;0411;;0411 +0432;CYRILLIC SMALL LETTER VE;Ll;0;L;;;;;N;;;0412;;0412 +0433;CYRILLIC SMALL LETTER GHE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER GE;;0413;;0413 +0434;CYRILLIC SMALL LETTER DE;Ll;0;L;;;;;N;;;0414;;0414 +0435;CYRILLIC SMALL LETTER IE;Ll;0;L;;;;;N;;;0415;;0415 +0436;CYRILLIC SMALL LETTER ZHE;Ll;0;L;;;;;N;;;0416;;0416 +0437;CYRILLIC SMALL LETTER ZE;Ll;0;L;;;;;N;;;0417;;0417 +0438;CYRILLIC SMALL LETTER I;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER II;;0418;;0418 +0439;CYRILLIC SMALL LETTER SHORT I;Ll;0;L;0438 0306;;;;N;CYRILLIC SMALL LETTER SHORT II;;0419;;0419 +043A;CYRILLIC SMALL LETTER KA;Ll;0;L;;;;;N;;;041A;;041A +043B;CYRILLIC SMALL LETTER EL;Ll;0;L;;;;;N;;;041B;;041B +043C;CYRILLIC SMALL LETTER EM;Ll;0;L;;;;;N;;;041C;;041C +043D;CYRILLIC SMALL LETTER EN;Ll;0;L;;;;;N;;;041D;;041D +043E;CYRILLIC SMALL LETTER O;Ll;0;L;;;;;N;;;041E;;041E +043F;CYRILLIC SMALL LETTER PE;Ll;0;L;;;;;N;;;041F;;041F +0440;CYRILLIC SMALL LETTER ER;Ll;0;L;;;;;N;;;0420;;0420 +0441;CYRILLIC SMALL LETTER ES;Ll;0;L;;;;;N;;;0421;;0421 +0442;CYRILLIC SMALL LETTER TE;Ll;0;L;;;;;N;;;0422;;0422 +0443;CYRILLIC SMALL LETTER U;Ll;0;L;;;;;N;;;0423;;0423 +0444;CYRILLIC SMALL LETTER EF;Ll;0;L;;;;;N;;;0424;;0424 +0445;CYRILLIC SMALL LETTER HA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KHA;;0425;;0425 +0446;CYRILLIC SMALL LETTER TSE;Ll;0;L;;;;;N;;;0426;;0426 +0447;CYRILLIC SMALL LETTER CHE;Ll;0;L;;;;;N;;;0427;;0427 +0448;CYRILLIC SMALL LETTER SHA;Ll;0;L;;;;;N;;;0428;;0428 +0449;CYRILLIC SMALL LETTER SHCHA;Ll;0;L;;;;;N;;;0429;;0429 +044A;CYRILLIC SMALL LETTER HARD SIGN;Ll;0;L;;;;;N;;;042A;;042A +044B;CYRILLIC SMALL LETTER YERU;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER YERI;;042B;;042B +044C;CYRILLIC SMALL LETTER SOFT SIGN;Ll;0;L;;;;;N;;;042C;;042C +044D;CYRILLIC SMALL LETTER E;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER REVERSED E;;042D;;042D +044E;CYRILLIC SMALL LETTER YU;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER IU;;042E;;042E +044F;CYRILLIC SMALL LETTER YA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER IA;;042F;;042F +0450;CYRILLIC SMALL LETTER IE WITH GRAVE;Ll;0;L;0435 0300;;;;N;;;0400;;0400 +0451;CYRILLIC SMALL LETTER IO;Ll;0;L;0435 0308;;;;N;;;0401;;0401 +0452;CYRILLIC SMALL LETTER DJE;Ll;0;L;;;;;N;;;0402;;0402 +0453;CYRILLIC SMALL LETTER GJE;Ll;0;L;0433 0301;;;;N;;;0403;;0403 +0454;CYRILLIC SMALL LETTER UKRAINIAN IE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER E;;0404;;0404 +0455;CYRILLIC SMALL LETTER DZE;Ll;0;L;;;;;N;;;0405;;0405 +0456;CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER I;;0406;;0406 +0457;CYRILLIC SMALL LETTER YI;Ll;0;L;0456 0308;;;;N;;;0407;;0407 +0458;CYRILLIC SMALL LETTER JE;Ll;0;L;;;;;N;;;0408;;0408 +0459;CYRILLIC SMALL LETTER LJE;Ll;0;L;;;;;N;;;0409;;0409 +045A;CYRILLIC SMALL LETTER NJE;Ll;0;L;;;;;N;;;040A;;040A +045B;CYRILLIC SMALL LETTER TSHE;Ll;0;L;;;;;N;;;040B;;040B +045C;CYRILLIC SMALL LETTER KJE;Ll;0;L;043A 0301;;;;N;;;040C;;040C +045D;CYRILLIC SMALL LETTER I WITH GRAVE;Ll;0;L;0438 0300;;;;N;;;040D;;040D +045E;CYRILLIC SMALL LETTER SHORT U;Ll;0;L;0443 0306;;;;N;;;040E;;040E +045F;CYRILLIC SMALL LETTER DZHE;Ll;0;L;;;;;N;;;040F;;040F +0460;CYRILLIC CAPITAL LETTER OMEGA;Lu;0;L;;;;;N;;;;0461; +0461;CYRILLIC SMALL LETTER OMEGA;Ll;0;L;;;;;N;;;0460;;0460 +0462;CYRILLIC CAPITAL LETTER YAT;Lu;0;L;;;;;N;;;;0463; +0463;CYRILLIC SMALL LETTER YAT;Ll;0;L;;;;;N;;;0462;;0462 +0464;CYRILLIC CAPITAL LETTER IOTIFIED E;Lu;0;L;;;;;N;;;;0465; +0465;CYRILLIC SMALL LETTER IOTIFIED E;Ll;0;L;;;;;N;;;0464;;0464 +0466;CYRILLIC CAPITAL LETTER LITTLE YUS;Lu;0;L;;;;;N;;;;0467; +0467;CYRILLIC SMALL LETTER LITTLE YUS;Ll;0;L;;;;;N;;;0466;;0466 +0468;CYRILLIC CAPITAL LETTER IOTIFIED LITTLE YUS;Lu;0;L;;;;;N;;;;0469; +0469;CYRILLIC SMALL LETTER IOTIFIED LITTLE YUS;Ll;0;L;;;;;N;;;0468;;0468 +046A;CYRILLIC CAPITAL LETTER BIG YUS;Lu;0;L;;;;;N;;;;046B; +046B;CYRILLIC SMALL LETTER BIG YUS;Ll;0;L;;;;;N;;;046A;;046A +046C;CYRILLIC CAPITAL LETTER IOTIFIED BIG YUS;Lu;0;L;;;;;N;;;;046D; +046D;CYRILLIC SMALL LETTER IOTIFIED BIG YUS;Ll;0;L;;;;;N;;;046C;;046C +046E;CYRILLIC CAPITAL LETTER KSI;Lu;0;L;;;;;N;;;;046F; +046F;CYRILLIC SMALL LETTER KSI;Ll;0;L;;;;;N;;;046E;;046E +0470;CYRILLIC CAPITAL LETTER PSI;Lu;0;L;;;;;N;;;;0471; +0471;CYRILLIC SMALL LETTER PSI;Ll;0;L;;;;;N;;;0470;;0470 +0472;CYRILLIC CAPITAL LETTER FITA;Lu;0;L;;;;;N;;;;0473; +0473;CYRILLIC SMALL LETTER FITA;Ll;0;L;;;;;N;;;0472;;0472 +0474;CYRILLIC CAPITAL LETTER IZHITSA;Lu;0;L;;;;;N;;;;0475; +0475;CYRILLIC SMALL LETTER IZHITSA;Ll;0;L;;;;;N;;;0474;;0474 +0476;CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT;Lu;0;L;0474 030F;;;;N;CYRILLIC CAPITAL LETTER IZHITSA DOUBLE GRAVE;;;0477; +0477;CYRILLIC SMALL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT;Ll;0;L;0475 030F;;;;N;CYRILLIC SMALL LETTER IZHITSA DOUBLE GRAVE;;0476;;0476 +0478;CYRILLIC CAPITAL LETTER UK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER UK DIGRAPH;;;0479; +0479;CYRILLIC SMALL LETTER UK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER UK DIGRAPH;;0478;;0478 +047A;CYRILLIC CAPITAL LETTER ROUND OMEGA;Lu;0;L;;;;;N;;;;047B; +047B;CYRILLIC SMALL LETTER ROUND OMEGA;Ll;0;L;;;;;N;;;047A;;047A +047C;CYRILLIC CAPITAL LETTER OMEGA WITH TITLO;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER OMEGA TITLO;;;047D; +047D;CYRILLIC SMALL LETTER OMEGA WITH TITLO;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER OMEGA TITLO;;047C;;047C +047E;CYRILLIC CAPITAL LETTER OT;Lu;0;L;;;;;N;;;;047F; +047F;CYRILLIC SMALL LETTER OT;Ll;0;L;;;;;N;;;047E;;047E +0480;CYRILLIC CAPITAL LETTER KOPPA;Lu;0;L;;;;;N;;;;0481; +0481;CYRILLIC SMALL LETTER KOPPA;Ll;0;L;;;;;N;;;0480;;0480 +0482;CYRILLIC THOUSANDS SIGN;So;0;L;;;;;N;;;;; +0483;COMBINING CYRILLIC TITLO;Mn;230;NSM;;;;;N;CYRILLIC NON-SPACING TITLO;;;; +0484;COMBINING CYRILLIC PALATALIZATION;Mn;230;NSM;;;;;N;CYRILLIC NON-SPACING PALATALIZATION;;;; +0485;COMBINING CYRILLIC DASIA PNEUMATA;Mn;230;NSM;;;;;N;CYRILLIC NON-SPACING DASIA PNEUMATA;;;; +0486;COMBINING CYRILLIC PSILI PNEUMATA;Mn;230;NSM;;;;;N;CYRILLIC NON-SPACING PSILI PNEUMATA;;;; +0487;COMBINING CYRILLIC POKRYTIE;Mn;230;NSM;;;;;N;;;;; +0488;COMBINING CYRILLIC HUNDRED THOUSANDS SIGN;Me;0;NSM;;;;;N;;;;; +0489;COMBINING CYRILLIC MILLIONS SIGN;Me;0;NSM;;;;;N;;;;; +048A;CYRILLIC CAPITAL LETTER SHORT I WITH TAIL;Lu;0;L;;;;;N;;;;048B; +048B;CYRILLIC SMALL LETTER SHORT I WITH TAIL;Ll;0;L;;;;;N;;;048A;;048A +048C;CYRILLIC CAPITAL LETTER SEMISOFT SIGN;Lu;0;L;;;;;N;;;;048D; +048D;CYRILLIC SMALL LETTER SEMISOFT SIGN;Ll;0;L;;;;;N;;;048C;;048C +048E;CYRILLIC CAPITAL LETTER ER WITH TICK;Lu;0;L;;;;;N;;;;048F; +048F;CYRILLIC SMALL LETTER ER WITH TICK;Ll;0;L;;;;;N;;;048E;;048E +0490;CYRILLIC CAPITAL LETTER GHE WITH UPTURN;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER GE WITH UPTURN;;;0491; +0491;CYRILLIC SMALL LETTER GHE WITH UPTURN;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER GE WITH UPTURN;;0490;;0490 +0492;CYRILLIC CAPITAL LETTER GHE WITH STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER GE BAR;;;0493; +0493;CYRILLIC SMALL LETTER GHE WITH STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER GE BAR;;0492;;0492 +0494;CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER GE HOOK;;;0495; +0495;CYRILLIC SMALL LETTER GHE WITH MIDDLE HOOK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER GE HOOK;;0494;;0494 +0496;CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER ZHE WITH RIGHT DESCENDER;;;0497; +0497;CYRILLIC SMALL LETTER ZHE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER ZHE WITH RIGHT DESCENDER;;0496;;0496 +0498;CYRILLIC CAPITAL LETTER ZE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER ZE CEDILLA;;;0499; +0499;CYRILLIC SMALL LETTER ZE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER ZE CEDILLA;;0498;;0498 +049A;CYRILLIC CAPITAL LETTER KA WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KA WITH RIGHT DESCENDER;;;049B; +049B;CYRILLIC SMALL LETTER KA WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KA WITH RIGHT DESCENDER;;049A;;049A +049C;CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KA VERTICAL BAR;;;049D; +049D;CYRILLIC SMALL LETTER KA WITH VERTICAL STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KA VERTICAL BAR;;049C;;049C +049E;CYRILLIC CAPITAL LETTER KA WITH STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KA BAR;;;049F; +049F;CYRILLIC SMALL LETTER KA WITH STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KA BAR;;049E;;049E +04A0;CYRILLIC CAPITAL LETTER BASHKIR KA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER REVERSED GE KA;;;04A1; +04A1;CYRILLIC SMALL LETTER BASHKIR KA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER REVERSED GE KA;;04A0;;04A0 +04A2;CYRILLIC CAPITAL LETTER EN WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER EN WITH RIGHT DESCENDER;;;04A3; +04A3;CYRILLIC SMALL LETTER EN WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER EN WITH RIGHT DESCENDER;;04A2;;04A2 +04A4;CYRILLIC CAPITAL LIGATURE EN GHE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER EN GE;;;04A5; +04A5;CYRILLIC SMALL LIGATURE EN GHE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER EN GE;;04A4;;04A4 +04A6;CYRILLIC CAPITAL LETTER PE WITH MIDDLE HOOK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER PE HOOK;;;04A7; +04A7;CYRILLIC SMALL LETTER PE WITH MIDDLE HOOK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER PE HOOK;;04A6;;04A6 +04A8;CYRILLIC CAPITAL LETTER ABKHASIAN HA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER O HOOK;;;04A9; +04A9;CYRILLIC SMALL LETTER ABKHASIAN HA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER O HOOK;;04A8;;04A8 +04AA;CYRILLIC CAPITAL LETTER ES WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER ES CEDILLA;;;04AB; +04AB;CYRILLIC SMALL LETTER ES WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER ES CEDILLA;;04AA;;04AA +04AC;CYRILLIC CAPITAL LETTER TE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER TE WITH RIGHT DESCENDER;;;04AD; +04AD;CYRILLIC SMALL LETTER TE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER TE WITH RIGHT DESCENDER;;04AC;;04AC +04AE;CYRILLIC CAPITAL LETTER STRAIGHT U;Lu;0;L;;;;;N;;;;04AF; +04AF;CYRILLIC SMALL LETTER STRAIGHT U;Ll;0;L;;;;;N;;;04AE;;04AE +04B0;CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER STRAIGHT U BAR;;;04B1; +04B1;CYRILLIC SMALL LETTER STRAIGHT U WITH STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER STRAIGHT U BAR;;04B0;;04B0 +04B2;CYRILLIC CAPITAL LETTER HA WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KHA WITH RIGHT DESCENDER;;;04B3; +04B3;CYRILLIC SMALL LETTER HA WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KHA WITH RIGHT DESCENDER;;04B2;;04B2 +04B4;CYRILLIC CAPITAL LIGATURE TE TSE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER TE TSE;;;04B5; +04B5;CYRILLIC SMALL LIGATURE TE TSE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER TE TSE;;04B4;;04B4 +04B6;CYRILLIC CAPITAL LETTER CHE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER CHE WITH RIGHT DESCENDER;;;04B7; +04B7;CYRILLIC SMALL LETTER CHE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER CHE WITH RIGHT DESCENDER;;04B6;;04B6 +04B8;CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER CHE VERTICAL BAR;;;04B9; +04B9;CYRILLIC SMALL LETTER CHE WITH VERTICAL STROKE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER CHE VERTICAL BAR;;04B8;;04B8 +04BA;CYRILLIC CAPITAL LETTER SHHA;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER H;;;04BB; +04BB;CYRILLIC SMALL LETTER SHHA;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER H;;04BA;;04BA +04BC;CYRILLIC CAPITAL LETTER ABKHASIAN CHE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER IE HOOK;;;04BD; +04BD;CYRILLIC SMALL LETTER ABKHASIAN CHE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER IE HOOK;;04BC;;04BC +04BE;CYRILLIC CAPITAL LETTER ABKHASIAN CHE WITH DESCENDER;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER IE HOOK OGONEK;;;04BF; +04BF;CYRILLIC SMALL LETTER ABKHASIAN CHE WITH DESCENDER;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER IE HOOK OGONEK;;04BE;;04BE +04C0;CYRILLIC LETTER PALOCHKA;Lu;0;L;;;;;N;CYRILLIC LETTER I;;;04CF; +04C1;CYRILLIC CAPITAL LETTER ZHE WITH BREVE;Lu;0;L;0416 0306;;;;N;CYRILLIC CAPITAL LETTER SHORT ZHE;;;04C2; +04C2;CYRILLIC SMALL LETTER ZHE WITH BREVE;Ll;0;L;0436 0306;;;;N;CYRILLIC SMALL LETTER SHORT ZHE;;04C1;;04C1 +04C3;CYRILLIC CAPITAL LETTER KA WITH HOOK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER KA HOOK;;;04C4; +04C4;CYRILLIC SMALL LETTER KA WITH HOOK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER KA HOOK;;04C3;;04C3 +04C5;CYRILLIC CAPITAL LETTER EL WITH TAIL;Lu;0;L;;;;;N;;;;04C6; +04C6;CYRILLIC SMALL LETTER EL WITH TAIL;Ll;0;L;;;;;N;;;04C5;;04C5 +04C7;CYRILLIC CAPITAL LETTER EN WITH HOOK;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER EN HOOK;;;04C8; +04C8;CYRILLIC SMALL LETTER EN WITH HOOK;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER EN HOOK;;04C7;;04C7 +04C9;CYRILLIC CAPITAL LETTER EN WITH TAIL;Lu;0;L;;;;;N;;;;04CA; +04CA;CYRILLIC SMALL LETTER EN WITH TAIL;Ll;0;L;;;;;N;;;04C9;;04C9 +04CB;CYRILLIC CAPITAL LETTER KHAKASSIAN CHE;Lu;0;L;;;;;N;CYRILLIC CAPITAL LETTER CHE WITH LEFT DESCENDER;;;04CC; +04CC;CYRILLIC SMALL LETTER KHAKASSIAN CHE;Ll;0;L;;;;;N;CYRILLIC SMALL LETTER CHE WITH LEFT DESCENDER;;04CB;;04CB +04CD;CYRILLIC CAPITAL LETTER EM WITH TAIL;Lu;0;L;;;;;N;;;;04CE; +04CE;CYRILLIC SMALL LETTER EM WITH TAIL;Ll;0;L;;;;;N;;;04CD;;04CD +04CF;CYRILLIC SMALL LETTER PALOCHKA;Ll;0;L;;;;;N;;;04C0;;04C0 +04D0;CYRILLIC CAPITAL LETTER A WITH BREVE;Lu;0;L;0410 0306;;;;N;;;;04D1; +04D1;CYRILLIC SMALL LETTER A WITH BREVE;Ll;0;L;0430 0306;;;;N;;;04D0;;04D0 +04D2;CYRILLIC CAPITAL LETTER A WITH DIAERESIS;Lu;0;L;0410 0308;;;;N;;;;04D3; +04D3;CYRILLIC SMALL LETTER A WITH DIAERESIS;Ll;0;L;0430 0308;;;;N;;;04D2;;04D2 +04D4;CYRILLIC CAPITAL LIGATURE A IE;Lu;0;L;;;;;N;;;;04D5; +04D5;CYRILLIC SMALL LIGATURE A IE;Ll;0;L;;;;;N;;;04D4;;04D4 +04D6;CYRILLIC CAPITAL LETTER IE WITH BREVE;Lu;0;L;0415 0306;;;;N;;;;04D7; +04D7;CYRILLIC SMALL LETTER IE WITH BREVE;Ll;0;L;0435 0306;;;;N;;;04D6;;04D6 +04D8;CYRILLIC CAPITAL LETTER SCHWA;Lu;0;L;;;;;N;;;;04D9; +04D9;CYRILLIC SMALL LETTER SCHWA;Ll;0;L;;;;;N;;;04D8;;04D8 +04DA;CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS;Lu;0;L;04D8 0308;;;;N;;;;04DB; +04DB;CYRILLIC SMALL LETTER SCHWA WITH DIAERESIS;Ll;0;L;04D9 0308;;;;N;;;04DA;;04DA +04DC;CYRILLIC CAPITAL LETTER ZHE WITH DIAERESIS;Lu;0;L;0416 0308;;;;N;;;;04DD; +04DD;CYRILLIC SMALL LETTER ZHE WITH DIAERESIS;Ll;0;L;0436 0308;;;;N;;;04DC;;04DC +04DE;CYRILLIC CAPITAL LETTER ZE WITH DIAERESIS;Lu;0;L;0417 0308;;;;N;;;;04DF; +04DF;CYRILLIC SMALL LETTER ZE WITH DIAERESIS;Ll;0;L;0437 0308;;;;N;;;04DE;;04DE +04E0;CYRILLIC CAPITAL LETTER ABKHASIAN DZE;Lu;0;L;;;;;N;;;;04E1; +04E1;CYRILLIC SMALL LETTER ABKHASIAN DZE;Ll;0;L;;;;;N;;;04E0;;04E0 +04E2;CYRILLIC CAPITAL LETTER I WITH MACRON;Lu;0;L;0418 0304;;;;N;;;;04E3; +04E3;CYRILLIC SMALL LETTER I WITH MACRON;Ll;0;L;0438 0304;;;;N;;;04E2;;04E2 +04E4;CYRILLIC CAPITAL LETTER I WITH DIAERESIS;Lu;0;L;0418 0308;;;;N;;;;04E5; +04E5;CYRILLIC SMALL LETTER I WITH DIAERESIS;Ll;0;L;0438 0308;;;;N;;;04E4;;04E4 +04E6;CYRILLIC CAPITAL LETTER O WITH DIAERESIS;Lu;0;L;041E 0308;;;;N;;;;04E7; +04E7;CYRILLIC SMALL LETTER O WITH DIAERESIS;Ll;0;L;043E 0308;;;;N;;;04E6;;04E6 +04E8;CYRILLIC CAPITAL LETTER BARRED O;Lu;0;L;;;;;N;;;;04E9; +04E9;CYRILLIC SMALL LETTER BARRED O;Ll;0;L;;;;;N;;;04E8;;04E8 +04EA;CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS;Lu;0;L;04E8 0308;;;;N;;;;04EB; +04EB;CYRILLIC SMALL LETTER BARRED O WITH DIAERESIS;Ll;0;L;04E9 0308;;;;N;;;04EA;;04EA +04EC;CYRILLIC CAPITAL LETTER E WITH DIAERESIS;Lu;0;L;042D 0308;;;;N;;;;04ED; +04ED;CYRILLIC SMALL LETTER E WITH DIAERESIS;Ll;0;L;044D 0308;;;;N;;;04EC;;04EC +04EE;CYRILLIC CAPITAL LETTER U WITH MACRON;Lu;0;L;0423 0304;;;;N;;;;04EF; +04EF;CYRILLIC SMALL LETTER U WITH MACRON;Ll;0;L;0443 0304;;;;N;;;04EE;;04EE +04F0;CYRILLIC CAPITAL LETTER U WITH DIAERESIS;Lu;0;L;0423 0308;;;;N;;;;04F1; +04F1;CYRILLIC SMALL LETTER U WITH DIAERESIS;Ll;0;L;0443 0308;;;;N;;;04F0;;04F0 +04F2;CYRILLIC CAPITAL LETTER U WITH DOUBLE ACUTE;Lu;0;L;0423 030B;;;;N;;;;04F3; +04F3;CYRILLIC SMALL LETTER U WITH DOUBLE ACUTE;Ll;0;L;0443 030B;;;;N;;;04F2;;04F2 +04F4;CYRILLIC CAPITAL LETTER CHE WITH DIAERESIS;Lu;0;L;0427 0308;;;;N;;;;04F5; +04F5;CYRILLIC SMALL LETTER CHE WITH DIAERESIS;Ll;0;L;0447 0308;;;;N;;;04F4;;04F4 +04F6;CYRILLIC CAPITAL LETTER GHE WITH DESCENDER;Lu;0;L;;;;;N;;;;04F7; +04F7;CYRILLIC SMALL LETTER GHE WITH DESCENDER;Ll;0;L;;;;;N;;;04F6;;04F6 +04F8;CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS;Lu;0;L;042B 0308;;;;N;;;;04F9; +04F9;CYRILLIC SMALL LETTER YERU WITH DIAERESIS;Ll;0;L;044B 0308;;;;N;;;04F8;;04F8 +04FA;CYRILLIC CAPITAL LETTER GHE WITH STROKE AND HOOK;Lu;0;L;;;;;N;;;;04FB; +04FB;CYRILLIC SMALL LETTER GHE WITH STROKE AND HOOK;Ll;0;L;;;;;N;;;04FA;;04FA +04FC;CYRILLIC CAPITAL LETTER HA WITH HOOK;Lu;0;L;;;;;N;;;;04FD; +04FD;CYRILLIC SMALL LETTER HA WITH HOOK;Ll;0;L;;;;;N;;;04FC;;04FC +04FE;CYRILLIC CAPITAL LETTER HA WITH STROKE;Lu;0;L;;;;;N;;;;04FF; +04FF;CYRILLIC SMALL LETTER HA WITH STROKE;Ll;0;L;;;;;N;;;04FE;;04FE +0500;CYRILLIC CAPITAL LETTER KOMI DE;Lu;0;L;;;;;N;;;;0501; +0501;CYRILLIC SMALL LETTER KOMI DE;Ll;0;L;;;;;N;;;0500;;0500 +0502;CYRILLIC CAPITAL LETTER KOMI DJE;Lu;0;L;;;;;N;;;;0503; +0503;CYRILLIC SMALL LETTER KOMI DJE;Ll;0;L;;;;;N;;;0502;;0502 +0504;CYRILLIC CAPITAL LETTER KOMI ZJE;Lu;0;L;;;;;N;;;;0505; +0505;CYRILLIC SMALL LETTER KOMI ZJE;Ll;0;L;;;;;N;;;0504;;0504 +0506;CYRILLIC CAPITAL LETTER KOMI DZJE;Lu;0;L;;;;;N;;;;0507; +0507;CYRILLIC SMALL LETTER KOMI DZJE;Ll;0;L;;;;;N;;;0506;;0506 +0508;CYRILLIC CAPITAL LETTER KOMI LJE;Lu;0;L;;;;;N;;;;0509; +0509;CYRILLIC SMALL LETTER KOMI LJE;Ll;0;L;;;;;N;;;0508;;0508 +050A;CYRILLIC CAPITAL LETTER KOMI NJE;Lu;0;L;;;;;N;;;;050B; +050B;CYRILLIC SMALL LETTER KOMI NJE;Ll;0;L;;;;;N;;;050A;;050A +050C;CYRILLIC CAPITAL LETTER KOMI SJE;Lu;0;L;;;;;N;;;;050D; +050D;CYRILLIC SMALL LETTER KOMI SJE;Ll;0;L;;;;;N;;;050C;;050C +050E;CYRILLIC CAPITAL LETTER KOMI TJE;Lu;0;L;;;;;N;;;;050F; +050F;CYRILLIC SMALL LETTER KOMI TJE;Ll;0;L;;;;;N;;;050E;;050E +0510;CYRILLIC CAPITAL LETTER REVERSED ZE;Lu;0;L;;;;;N;;;;0511; +0511;CYRILLIC SMALL LETTER REVERSED ZE;Ll;0;L;;;;;N;;;0510;;0510 +0512;CYRILLIC CAPITAL LETTER EL WITH HOOK;Lu;0;L;;;;;N;;;;0513; +0513;CYRILLIC SMALL LETTER EL WITH HOOK;Ll;0;L;;;;;N;;;0512;;0512 +0514;CYRILLIC CAPITAL LETTER LHA;Lu;0;L;;;;;N;;;;0515; +0515;CYRILLIC SMALL LETTER LHA;Ll;0;L;;;;;N;;;0514;;0514 +0516;CYRILLIC CAPITAL LETTER RHA;Lu;0;L;;;;;N;;;;0517; +0517;CYRILLIC SMALL LETTER RHA;Ll;0;L;;;;;N;;;0516;;0516 +0518;CYRILLIC CAPITAL LETTER YAE;Lu;0;L;;;;;N;;;;0519; +0519;CYRILLIC SMALL LETTER YAE;Ll;0;L;;;;;N;;;0518;;0518 +051A;CYRILLIC CAPITAL LETTER QA;Lu;0;L;;;;;N;;;;051B; +051B;CYRILLIC SMALL LETTER QA;Ll;0;L;;;;;N;;;051A;;051A +051C;CYRILLIC CAPITAL LETTER WE;Lu;0;L;;;;;N;;;;051D; +051D;CYRILLIC SMALL LETTER WE;Ll;0;L;;;;;N;;;051C;;051C +051E;CYRILLIC CAPITAL LETTER ALEUT KA;Lu;0;L;;;;;N;;;;051F; +051F;CYRILLIC SMALL LETTER ALEUT KA;Ll;0;L;;;;;N;;;051E;;051E +0520;CYRILLIC CAPITAL LETTER EL WITH MIDDLE HOOK;Lu;0;L;;;;;N;;;;0521; +0521;CYRILLIC SMALL LETTER EL WITH MIDDLE HOOK;Ll;0;L;;;;;N;;;0520;;0520 +0522;CYRILLIC CAPITAL LETTER EN WITH MIDDLE HOOK;Lu;0;L;;;;;N;;;;0523; +0523;CYRILLIC SMALL LETTER EN WITH MIDDLE HOOK;Ll;0;L;;;;;N;;;0522;;0522 +0524;CYRILLIC CAPITAL LETTER PE WITH DESCENDER;Lu;0;L;;;;;N;;;;0525; +0525;CYRILLIC SMALL LETTER PE WITH DESCENDER;Ll;0;L;;;;;N;;;0524;;0524 +0526;CYRILLIC CAPITAL LETTER SHHA WITH DESCENDER;Lu;0;L;;;;;N;;;;0527; +0527;CYRILLIC SMALL LETTER SHHA WITH DESCENDER;Ll;0;L;;;;;N;;;0526;;0526 +0531;ARMENIAN CAPITAL LETTER AYB;Lu;0;L;;;;;N;;;;0561; +0532;ARMENIAN CAPITAL LETTER BEN;Lu;0;L;;;;;N;;;;0562; +0533;ARMENIAN CAPITAL LETTER GIM;Lu;0;L;;;;;N;;;;0563; +0534;ARMENIAN CAPITAL LETTER DA;Lu;0;L;;;;;N;;;;0564; +0535;ARMENIAN CAPITAL LETTER ECH;Lu;0;L;;;;;N;;;;0565; +0536;ARMENIAN CAPITAL LETTER ZA;Lu;0;L;;;;;N;;;;0566; +0537;ARMENIAN CAPITAL LETTER EH;Lu;0;L;;;;;N;;;;0567; +0538;ARMENIAN CAPITAL LETTER ET;Lu;0;L;;;;;N;;;;0568; +0539;ARMENIAN CAPITAL LETTER TO;Lu;0;L;;;;;N;;;;0569; +053A;ARMENIAN CAPITAL LETTER ZHE;Lu;0;L;;;;;N;;;;056A; +053B;ARMENIAN CAPITAL LETTER INI;Lu;0;L;;;;;N;;;;056B; +053C;ARMENIAN CAPITAL LETTER LIWN;Lu;0;L;;;;;N;;;;056C; +053D;ARMENIAN CAPITAL LETTER XEH;Lu;0;L;;;;;N;;;;056D; +053E;ARMENIAN CAPITAL LETTER CA;Lu;0;L;;;;;N;;;;056E; +053F;ARMENIAN CAPITAL LETTER KEN;Lu;0;L;;;;;N;;;;056F; +0540;ARMENIAN CAPITAL LETTER HO;Lu;0;L;;;;;N;;;;0570; +0541;ARMENIAN CAPITAL LETTER JA;Lu;0;L;;;;;N;;;;0571; +0542;ARMENIAN CAPITAL LETTER GHAD;Lu;0;L;;;;;N;ARMENIAN CAPITAL LETTER LAD;;;0572; +0543;ARMENIAN CAPITAL LETTER CHEH;Lu;0;L;;;;;N;;;;0573; +0544;ARMENIAN CAPITAL LETTER MEN;Lu;0;L;;;;;N;;;;0574; +0545;ARMENIAN CAPITAL LETTER YI;Lu;0;L;;;;;N;;;;0575; +0546;ARMENIAN CAPITAL LETTER NOW;Lu;0;L;;;;;N;;;;0576; +0547;ARMENIAN CAPITAL LETTER SHA;Lu;0;L;;;;;N;;;;0577; +0548;ARMENIAN CAPITAL LETTER VO;Lu;0;L;;;;;N;;;;0578; +0549;ARMENIAN CAPITAL LETTER CHA;Lu;0;L;;;;;N;;;;0579; +054A;ARMENIAN CAPITAL LETTER PEH;Lu;0;L;;;;;N;;;;057A; +054B;ARMENIAN CAPITAL LETTER JHEH;Lu;0;L;;;;;N;;;;057B; +054C;ARMENIAN CAPITAL LETTER RA;Lu;0;L;;;;;N;;;;057C; +054D;ARMENIAN CAPITAL LETTER SEH;Lu;0;L;;;;;N;;;;057D; +054E;ARMENIAN CAPITAL LETTER VEW;Lu;0;L;;;;;N;;;;057E; +054F;ARMENIAN CAPITAL LETTER TIWN;Lu;0;L;;;;;N;;;;057F; +0550;ARMENIAN CAPITAL LETTER REH;Lu;0;L;;;;;N;;;;0580; +0551;ARMENIAN CAPITAL LETTER CO;Lu;0;L;;;;;N;;;;0581; +0552;ARMENIAN CAPITAL LETTER YIWN;Lu;0;L;;;;;N;;;;0582; +0553;ARMENIAN CAPITAL LETTER PIWR;Lu;0;L;;;;;N;;;;0583; +0554;ARMENIAN CAPITAL LETTER KEH;Lu;0;L;;;;;N;;;;0584; +0555;ARMENIAN CAPITAL LETTER OH;Lu;0;L;;;;;N;;;;0585; +0556;ARMENIAN CAPITAL LETTER FEH;Lu;0;L;;;;;N;;;;0586; +0559;ARMENIAN MODIFIER LETTER LEFT HALF RING;Lm;0;L;;;;;N;;;;; +055A;ARMENIAN APOSTROPHE;Po;0;L;;;;;N;ARMENIAN MODIFIER LETTER RIGHT HALF RING;;;; +055B;ARMENIAN EMPHASIS MARK;Po;0;L;;;;;N;;;;; +055C;ARMENIAN EXCLAMATION MARK;Po;0;L;;;;;N;;;;; +055D;ARMENIAN COMMA;Po;0;L;;;;;N;;;;; +055E;ARMENIAN QUESTION MARK;Po;0;L;;;;;N;;;;; +055F;ARMENIAN ABBREVIATION MARK;Po;0;L;;;;;N;;;;; +0561;ARMENIAN SMALL LETTER AYB;Ll;0;L;;;;;N;;;0531;;0531 +0562;ARMENIAN SMALL LETTER BEN;Ll;0;L;;;;;N;;;0532;;0532 +0563;ARMENIAN SMALL LETTER GIM;Ll;0;L;;;;;N;;;0533;;0533 +0564;ARMENIAN SMALL LETTER DA;Ll;0;L;;;;;N;;;0534;;0534 +0565;ARMENIAN SMALL LETTER ECH;Ll;0;L;;;;;N;;;0535;;0535 +0566;ARMENIAN SMALL LETTER ZA;Ll;0;L;;;;;N;;;0536;;0536 +0567;ARMENIAN SMALL LETTER EH;Ll;0;L;;;;;N;;;0537;;0537 +0568;ARMENIAN SMALL LETTER ET;Ll;0;L;;;;;N;;;0538;;0538 +0569;ARMENIAN SMALL LETTER TO;Ll;0;L;;;;;N;;;0539;;0539 +056A;ARMENIAN SMALL LETTER ZHE;Ll;0;L;;;;;N;;;053A;;053A +056B;ARMENIAN SMALL LETTER INI;Ll;0;L;;;;;N;;;053B;;053B +056C;ARMENIAN SMALL LETTER LIWN;Ll;0;L;;;;;N;;;053C;;053C +056D;ARMENIAN SMALL LETTER XEH;Ll;0;L;;;;;N;;;053D;;053D +056E;ARMENIAN SMALL LETTER CA;Ll;0;L;;;;;N;;;053E;;053E +056F;ARMENIAN SMALL LETTER KEN;Ll;0;L;;;;;N;;;053F;;053F +0570;ARMENIAN SMALL LETTER HO;Ll;0;L;;;;;N;;;0540;;0540 +0571;ARMENIAN SMALL LETTER JA;Ll;0;L;;;;;N;;;0541;;0541 +0572;ARMENIAN SMALL LETTER GHAD;Ll;0;L;;;;;N;ARMENIAN SMALL LETTER LAD;;0542;;0542 +0573;ARMENIAN SMALL LETTER CHEH;Ll;0;L;;;;;N;;;0543;;0543 +0574;ARMENIAN SMALL LETTER MEN;Ll;0;L;;;;;N;;;0544;;0544 +0575;ARMENIAN SMALL LETTER YI;Ll;0;L;;;;;N;;;0545;;0545 +0576;ARMENIAN SMALL LETTER NOW;Ll;0;L;;;;;N;;;0546;;0546 +0577;ARMENIAN SMALL LETTER SHA;Ll;0;L;;;;;N;;;0547;;0547 +0578;ARMENIAN SMALL LETTER VO;Ll;0;L;;;;;N;;;0548;;0548 +0579;ARMENIAN SMALL LETTER CHA;Ll;0;L;;;;;N;;;0549;;0549 +057A;ARMENIAN SMALL LETTER PEH;Ll;0;L;;;;;N;;;054A;;054A +057B;ARMENIAN SMALL LETTER JHEH;Ll;0;L;;;;;N;;;054B;;054B +057C;ARMENIAN SMALL LETTER RA;Ll;0;L;;;;;N;;;054C;;054C +057D;ARMENIAN SMALL LETTER SEH;Ll;0;L;;;;;N;;;054D;;054D +057E;ARMENIAN SMALL LETTER VEW;Ll;0;L;;;;;N;;;054E;;054E +057F;ARMENIAN SMALL LETTER TIWN;Ll;0;L;;;;;N;;;054F;;054F +0580;ARMENIAN SMALL LETTER REH;Ll;0;L;;;;;N;;;0550;;0550 +0581;ARMENIAN SMALL LETTER CO;Ll;0;L;;;;;N;;;0551;;0551 +0582;ARMENIAN SMALL LETTER YIWN;Ll;0;L;;;;;N;;;0552;;0552 +0583;ARMENIAN SMALL LETTER PIWR;Ll;0;L;;;;;N;;;0553;;0553 +0584;ARMENIAN SMALL LETTER KEH;Ll;0;L;;;;;N;;;0554;;0554 +0585;ARMENIAN SMALL LETTER OH;Ll;0;L;;;;;N;;;0555;;0555 +0586;ARMENIAN SMALL LETTER FEH;Ll;0;L;;;;;N;;;0556;;0556 +0587;ARMENIAN SMALL LIGATURE ECH YIWN;Ll;0;L; 0565 0582;;;;N;;;;; +0589;ARMENIAN FULL STOP;Po;0;L;;;;;N;ARMENIAN PERIOD;;;; +058A;ARMENIAN HYPHEN;Pd;0;ON;;;;;N;;;;; +058F;ARMENIAN DRAM SIGN;Sc;0;ET;;;;;N;;;;; +0591;HEBREW ACCENT ETNAHTA;Mn;220;NSM;;;;;N;;;;; +0592;HEBREW ACCENT SEGOL;Mn;230;NSM;;;;;N;;;;; +0593;HEBREW ACCENT SHALSHELET;Mn;230;NSM;;;;;N;;;;; +0594;HEBREW ACCENT ZAQEF QATAN;Mn;230;NSM;;;;;N;;;;; +0595;HEBREW ACCENT ZAQEF GADOL;Mn;230;NSM;;;;;N;;;;; +0596;HEBREW ACCENT TIPEHA;Mn;220;NSM;;;;;N;;;;; +0597;HEBREW ACCENT REVIA;Mn;230;NSM;;;;;N;;;;; +0598;HEBREW ACCENT ZARQA;Mn;230;NSM;;;;;N;;;;; +0599;HEBREW ACCENT PASHTA;Mn;230;NSM;;;;;N;;;;; +059A;HEBREW ACCENT YETIV;Mn;222;NSM;;;;;N;;;;; +059B;HEBREW ACCENT TEVIR;Mn;220;NSM;;;;;N;;;;; +059C;HEBREW ACCENT GERESH;Mn;230;NSM;;;;;N;;;;; +059D;HEBREW ACCENT GERESH MUQDAM;Mn;230;NSM;;;;;N;;;;; +059E;HEBREW ACCENT GERSHAYIM;Mn;230;NSM;;;;;N;;;;; +059F;HEBREW ACCENT QARNEY PARA;Mn;230;NSM;;;;;N;;;;; +05A0;HEBREW ACCENT TELISHA GEDOLA;Mn;230;NSM;;;;;N;;;;; +05A1;HEBREW ACCENT PAZER;Mn;230;NSM;;;;;N;;;;; +05A2;HEBREW ACCENT ATNAH HAFUKH;Mn;220;NSM;;;;;N;;;;; +05A3;HEBREW ACCENT MUNAH;Mn;220;NSM;;;;;N;;;;; +05A4;HEBREW ACCENT MAHAPAKH;Mn;220;NSM;;;;;N;;;;; +05A5;HEBREW ACCENT MERKHA;Mn;220;NSM;;;;;N;;;;; +05A6;HEBREW ACCENT MERKHA KEFULA;Mn;220;NSM;;;;;N;;;;; +05A7;HEBREW ACCENT DARGA;Mn;220;NSM;;;;;N;;;;; +05A8;HEBREW ACCENT QADMA;Mn;230;NSM;;;;;N;;;;; +05A9;HEBREW ACCENT TELISHA QETANA;Mn;230;NSM;;;;;N;;;;; +05AA;HEBREW ACCENT YERAH BEN YOMO;Mn;220;NSM;;;;;N;;;;; +05AB;HEBREW ACCENT OLE;Mn;230;NSM;;;;;N;;;;; +05AC;HEBREW ACCENT ILUY;Mn;230;NSM;;;;;N;;;;; +05AD;HEBREW ACCENT DEHI;Mn;222;NSM;;;;;N;;;;; +05AE;HEBREW ACCENT ZINOR;Mn;228;NSM;;;;;N;;;;; +05AF;HEBREW MARK MASORA CIRCLE;Mn;230;NSM;;;;;N;;;;; +05B0;HEBREW POINT SHEVA;Mn;10;NSM;;;;;N;;;;; +05B1;HEBREW POINT HATAF SEGOL;Mn;11;NSM;;;;;N;;;;; +05B2;HEBREW POINT HATAF PATAH;Mn;12;NSM;;;;;N;;;;; +05B3;HEBREW POINT HATAF QAMATS;Mn;13;NSM;;;;;N;;;;; +05B4;HEBREW POINT HIRIQ;Mn;14;NSM;;;;;N;;;;; +05B5;HEBREW POINT TSERE;Mn;15;NSM;;;;;N;;;;; +05B6;HEBREW POINT SEGOL;Mn;16;NSM;;;;;N;;;;; +05B7;HEBREW POINT PATAH;Mn;17;NSM;;;;;N;;;;; +05B8;HEBREW POINT QAMATS;Mn;18;NSM;;;;;N;;;;; +05B9;HEBREW POINT HOLAM;Mn;19;NSM;;;;;N;;;;; +05BA;HEBREW POINT HOLAM HASER FOR VAV;Mn;19;NSM;;;;;N;;;;; +05BB;HEBREW POINT QUBUTS;Mn;20;NSM;;;;;N;;;;; +05BC;HEBREW POINT DAGESH OR MAPIQ;Mn;21;NSM;;;;;N;HEBREW POINT DAGESH;;;; +05BD;HEBREW POINT METEG;Mn;22;NSM;;;;;N;;;;; +05BE;HEBREW PUNCTUATION MAQAF;Pd;0;R;;;;;N;;;;; +05BF;HEBREW POINT RAFE;Mn;23;NSM;;;;;N;;;;; +05C0;HEBREW PUNCTUATION PASEQ;Po;0;R;;;;;N;HEBREW POINT PASEQ;;;; +05C1;HEBREW POINT SHIN DOT;Mn;24;NSM;;;;;N;;;;; +05C2;HEBREW POINT SIN DOT;Mn;25;NSM;;;;;N;;;;; +05C3;HEBREW PUNCTUATION SOF PASUQ;Po;0;R;;;;;N;;;;; +05C4;HEBREW MARK UPPER DOT;Mn;230;NSM;;;;;N;;;;; +05C5;HEBREW MARK LOWER DOT;Mn;220;NSM;;;;;N;;;;; +05C6;HEBREW PUNCTUATION NUN HAFUKHA;Po;0;R;;;;;N;;;;; +05C7;HEBREW POINT QAMATS QATAN;Mn;18;NSM;;;;;N;;;;; +05D0;HEBREW LETTER ALEF;Lo;0;R;;;;;N;;;;; +05D1;HEBREW LETTER BET;Lo;0;R;;;;;N;;;;; +05D2;HEBREW LETTER GIMEL;Lo;0;R;;;;;N;;;;; +05D3;HEBREW LETTER DALET;Lo;0;R;;;;;N;;;;; +05D4;HEBREW LETTER HE;Lo;0;R;;;;;N;;;;; +05D5;HEBREW LETTER VAV;Lo;0;R;;;;;N;;;;; +05D6;HEBREW LETTER ZAYIN;Lo;0;R;;;;;N;;;;; +05D7;HEBREW LETTER HET;Lo;0;R;;;;;N;;;;; +05D8;HEBREW LETTER TET;Lo;0;R;;;;;N;;;;; +05D9;HEBREW LETTER YOD;Lo;0;R;;;;;N;;;;; +05DA;HEBREW LETTER FINAL KAF;Lo;0;R;;;;;N;;;;; +05DB;HEBREW LETTER KAF;Lo;0;R;;;;;N;;;;; +05DC;HEBREW LETTER LAMED;Lo;0;R;;;;;N;;;;; +05DD;HEBREW LETTER FINAL MEM;Lo;0;R;;;;;N;;;;; +05DE;HEBREW LETTER MEM;Lo;0;R;;;;;N;;;;; +05DF;HEBREW LETTER FINAL NUN;Lo;0;R;;;;;N;;;;; +05E0;HEBREW LETTER NUN;Lo;0;R;;;;;N;;;;; +05E1;HEBREW LETTER SAMEKH;Lo;0;R;;;;;N;;;;; +05E2;HEBREW LETTER AYIN;Lo;0;R;;;;;N;;;;; +05E3;HEBREW LETTER FINAL PE;Lo;0;R;;;;;N;;;;; +05E4;HEBREW LETTER PE;Lo;0;R;;;;;N;;;;; +05E5;HEBREW LETTER FINAL TSADI;Lo;0;R;;;;;N;;;;; +05E6;HEBREW LETTER TSADI;Lo;0;R;;;;;N;;;;; +05E7;HEBREW LETTER QOF;Lo;0;R;;;;;N;;;;; +05E8;HEBREW LETTER RESH;Lo;0;R;;;;;N;;;;; +05E9;HEBREW LETTER SHIN;Lo;0;R;;;;;N;;;;; +05EA;HEBREW LETTER TAV;Lo;0;R;;;;;N;;;;; +05F0;HEBREW LIGATURE YIDDISH DOUBLE VAV;Lo;0;R;;;;;N;HEBREW LETTER DOUBLE VAV;;;; +05F1;HEBREW LIGATURE YIDDISH VAV YOD;Lo;0;R;;;;;N;HEBREW LETTER VAV YOD;;;; +05F2;HEBREW LIGATURE YIDDISH DOUBLE YOD;Lo;0;R;;;;;N;HEBREW LETTER DOUBLE YOD;;;; +05F3;HEBREW PUNCTUATION GERESH;Po;0;R;;;;;N;;;;; +05F4;HEBREW PUNCTUATION GERSHAYIM;Po;0;R;;;;;N;;;;; +0600;ARABIC NUMBER SIGN;Cf;0;AN;;;;;N;;;;; +0601;ARABIC SIGN SANAH;Cf;0;AN;;;;;N;;;;; +0602;ARABIC FOOTNOTE MARKER;Cf;0;AN;;;;;N;;;;; +0603;ARABIC SIGN SAFHA;Cf;0;AN;;;;;N;;;;; +0604;ARABIC SIGN SAMVAT;Cf;0;AN;;;;;N;;;;; +0606;ARABIC-INDIC CUBE ROOT;Sm;0;ON;;;;;N;;;;; +0607;ARABIC-INDIC FOURTH ROOT;Sm;0;ON;;;;;N;;;;; +0608;ARABIC RAY;Sm;0;AL;;;;;N;;;;; +0609;ARABIC-INDIC PER MILLE SIGN;Po;0;ET;;;;;N;;;;; +060A;ARABIC-INDIC PER TEN THOUSAND SIGN;Po;0;ET;;;;;N;;;;; +060B;AFGHANI SIGN;Sc;0;AL;;;;;N;;;;; +060C;ARABIC COMMA;Po;0;CS;;;;;N;;;;; +060D;ARABIC DATE SEPARATOR;Po;0;AL;;;;;N;;;;; +060E;ARABIC POETIC VERSE SIGN;So;0;ON;;;;;N;;;;; +060F;ARABIC SIGN MISRA;So;0;ON;;;;;N;;;;; +0610;ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM;Mn;230;NSM;;;;;N;;;;; +0611;ARABIC SIGN ALAYHE ASSALLAM;Mn;230;NSM;;;;;N;;;;; +0612;ARABIC SIGN RAHMATULLAH ALAYHE;Mn;230;NSM;;;;;N;;;;; +0613;ARABIC SIGN RADI ALLAHOU ANHU;Mn;230;NSM;;;;;N;;;;; +0614;ARABIC SIGN TAKHALLUS;Mn;230;NSM;;;;;N;;;;; +0615;ARABIC SMALL HIGH TAH;Mn;230;NSM;;;;;N;;;;; +0616;ARABIC SMALL HIGH LIGATURE ALEF WITH LAM WITH YEH;Mn;230;NSM;;;;;N;;;;; +0617;ARABIC SMALL HIGH ZAIN;Mn;230;NSM;;;;;N;;;;; +0618;ARABIC SMALL FATHA;Mn;30;NSM;;;;;N;;;;; +0619;ARABIC SMALL DAMMA;Mn;31;NSM;;;;;N;;;;; +061A;ARABIC SMALL KASRA;Mn;32;NSM;;;;;N;;;;; +061B;ARABIC SEMICOLON;Po;0;AL;;;;;N;;;;; +061E;ARABIC TRIPLE DOT PUNCTUATION MARK;Po;0;AL;;;;;N;;;;; +061F;ARABIC QUESTION MARK;Po;0;AL;;;;;N;;;;; +0620;ARABIC LETTER KASHMIRI YEH;Lo;0;AL;;;;;N;;;;; +0621;ARABIC LETTER HAMZA;Lo;0;AL;;;;;N;ARABIC LETTER HAMZAH;;;; +0622;ARABIC LETTER ALEF WITH MADDA ABOVE;Lo;0;AL;0627 0653;;;;N;ARABIC LETTER MADDAH ON ALEF;;;; +0623;ARABIC LETTER ALEF WITH HAMZA ABOVE;Lo;0;AL;0627 0654;;;;N;ARABIC LETTER HAMZAH ON ALEF;;;; +0624;ARABIC LETTER WAW WITH HAMZA ABOVE;Lo;0;AL;0648 0654;;;;N;ARABIC LETTER HAMZAH ON WAW;;;; +0625;ARABIC LETTER ALEF WITH HAMZA BELOW;Lo;0;AL;0627 0655;;;;N;ARABIC LETTER HAMZAH UNDER ALEF;;;; +0626;ARABIC LETTER YEH WITH HAMZA ABOVE;Lo;0;AL;064A 0654;;;;N;ARABIC LETTER HAMZAH ON YA;;;; +0627;ARABIC LETTER ALEF;Lo;0;AL;;;;;N;;;;; +0628;ARABIC LETTER BEH;Lo;0;AL;;;;;N;ARABIC LETTER BAA;;;; +0629;ARABIC LETTER TEH MARBUTA;Lo;0;AL;;;;;N;ARABIC LETTER TAA MARBUTAH;;;; +062A;ARABIC LETTER TEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA;;;; +062B;ARABIC LETTER THEH;Lo;0;AL;;;;;N;ARABIC LETTER THAA;;;; +062C;ARABIC LETTER JEEM;Lo;0;AL;;;;;N;;;;; +062D;ARABIC LETTER HAH;Lo;0;AL;;;;;N;ARABIC LETTER HAA;;;; +062E;ARABIC LETTER KHAH;Lo;0;AL;;;;;N;ARABIC LETTER KHAA;;;; +062F;ARABIC LETTER DAL;Lo;0;AL;;;;;N;;;;; +0630;ARABIC LETTER THAL;Lo;0;AL;;;;;N;;;;; +0631;ARABIC LETTER REH;Lo;0;AL;;;;;N;ARABIC LETTER RA;;;; +0632;ARABIC LETTER ZAIN;Lo;0;AL;;;;;N;;;;; +0633;ARABIC LETTER SEEN;Lo;0;AL;;;;;N;;;;; +0634;ARABIC LETTER SHEEN;Lo;0;AL;;;;;N;;;;; +0635;ARABIC LETTER SAD;Lo;0;AL;;;;;N;;;;; +0636;ARABIC LETTER DAD;Lo;0;AL;;;;;N;;;;; +0637;ARABIC LETTER TAH;Lo;0;AL;;;;;N;;;;; +0638;ARABIC LETTER ZAH;Lo;0;AL;;;;;N;ARABIC LETTER DHAH;;;; +0639;ARABIC LETTER AIN;Lo;0;AL;;;;;N;;;;; +063A;ARABIC LETTER GHAIN;Lo;0;AL;;;;;N;;;;; +063B;ARABIC LETTER KEHEH WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +063C;ARABIC LETTER KEHEH WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;;;;; +063D;ARABIC LETTER FARSI YEH WITH INVERTED V;Lo;0;AL;;;;;N;;;;; +063E;ARABIC LETTER FARSI YEH WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +063F;ARABIC LETTER FARSI YEH WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +0640;ARABIC TATWEEL;Lm;0;AL;;;;;N;;;;; +0641;ARABIC LETTER FEH;Lo;0;AL;;;;;N;ARABIC LETTER FA;;;; +0642;ARABIC LETTER QAF;Lo;0;AL;;;;;N;;;;; +0643;ARABIC LETTER KAF;Lo;0;AL;;;;;N;ARABIC LETTER CAF;;;; +0644;ARABIC LETTER LAM;Lo;0;AL;;;;;N;;;;; +0645;ARABIC LETTER MEEM;Lo;0;AL;;;;;N;;;;; +0646;ARABIC LETTER NOON;Lo;0;AL;;;;;N;;;;; +0647;ARABIC LETTER HEH;Lo;0;AL;;;;;N;ARABIC LETTER HA;;;; +0648;ARABIC LETTER WAW;Lo;0;AL;;;;;N;;;;; +0649;ARABIC LETTER ALEF MAKSURA;Lo;0;AL;;;;;N;ARABIC LETTER ALEF MAQSURAH;;;; +064A;ARABIC LETTER YEH;Lo;0;AL;;;;;N;ARABIC LETTER YA;;;; +064B;ARABIC FATHATAN;Mn;27;NSM;;;;;N;;;;; +064C;ARABIC DAMMATAN;Mn;28;NSM;;;;;N;;;;; +064D;ARABIC KASRATAN;Mn;29;NSM;;;;;N;;;;; +064E;ARABIC FATHA;Mn;30;NSM;;;;;N;ARABIC FATHAH;;;; +064F;ARABIC DAMMA;Mn;31;NSM;;;;;N;ARABIC DAMMAH;;;; +0650;ARABIC KASRA;Mn;32;NSM;;;;;N;ARABIC KASRAH;;;; +0651;ARABIC SHADDA;Mn;33;NSM;;;;;N;ARABIC SHADDAH;;;; +0652;ARABIC SUKUN;Mn;34;NSM;;;;;N;;;;; +0653;ARABIC MADDAH ABOVE;Mn;230;NSM;;;;;N;;;;; +0654;ARABIC HAMZA ABOVE;Mn;230;NSM;;;;;N;;;;; +0655;ARABIC HAMZA BELOW;Mn;220;NSM;;;;;N;;;;; +0656;ARABIC SUBSCRIPT ALEF;Mn;220;NSM;;;;;N;;;;; +0657;ARABIC INVERTED DAMMA;Mn;230;NSM;;;;;N;;;;; +0658;ARABIC MARK NOON GHUNNA;Mn;230;NSM;;;;;N;;;;; +0659;ARABIC ZWARAKAY;Mn;230;NSM;;;;;N;;;;; +065A;ARABIC VOWEL SIGN SMALL V ABOVE;Mn;230;NSM;;;;;N;;;;; +065B;ARABIC VOWEL SIGN INVERTED SMALL V ABOVE;Mn;230;NSM;;;;;N;;;;; +065C;ARABIC VOWEL SIGN DOT BELOW;Mn;220;NSM;;;;;N;;;;; +065D;ARABIC REVERSED DAMMA;Mn;230;NSM;;;;;N;;;;; +065E;ARABIC FATHA WITH TWO DOTS;Mn;230;NSM;;;;;N;;;;; +065F;ARABIC WAVY HAMZA BELOW;Mn;220;NSM;;;;;N;;;;; +0660;ARABIC-INDIC DIGIT ZERO;Nd;0;AN;;0;0;0;N;;;;; +0661;ARABIC-INDIC DIGIT ONE;Nd;0;AN;;1;1;1;N;;;;; +0662;ARABIC-INDIC DIGIT TWO;Nd;0;AN;;2;2;2;N;;;;; +0663;ARABIC-INDIC DIGIT THREE;Nd;0;AN;;3;3;3;N;;;;; +0664;ARABIC-INDIC DIGIT FOUR;Nd;0;AN;;4;4;4;N;;;;; +0665;ARABIC-INDIC DIGIT FIVE;Nd;0;AN;;5;5;5;N;;;;; +0666;ARABIC-INDIC DIGIT SIX;Nd;0;AN;;6;6;6;N;;;;; +0667;ARABIC-INDIC DIGIT SEVEN;Nd;0;AN;;7;7;7;N;;;;; +0668;ARABIC-INDIC DIGIT EIGHT;Nd;0;AN;;8;8;8;N;;;;; +0669;ARABIC-INDIC DIGIT NINE;Nd;0;AN;;9;9;9;N;;;;; +066A;ARABIC PERCENT SIGN;Po;0;ET;;;;;N;;;;; +066B;ARABIC DECIMAL SEPARATOR;Po;0;AN;;;;;N;;;;; +066C;ARABIC THOUSANDS SEPARATOR;Po;0;AN;;;;;N;;;;; +066D;ARABIC FIVE POINTED STAR;Po;0;AL;;;;;N;;;;; +066E;ARABIC LETTER DOTLESS BEH;Lo;0;AL;;;;;N;;;;; +066F;ARABIC LETTER DOTLESS QAF;Lo;0;AL;;;;;N;;;;; +0670;ARABIC LETTER SUPERSCRIPT ALEF;Mn;35;NSM;;;;;N;ARABIC ALEF ABOVE;;;; +0671;ARABIC LETTER ALEF WASLA;Lo;0;AL;;;;;N;ARABIC LETTER HAMZAT WASL ON ALEF;;;; +0672;ARABIC LETTER ALEF WITH WAVY HAMZA ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER WAVY HAMZAH ON ALEF;;;; +0673;ARABIC LETTER ALEF WITH WAVY HAMZA BELOW;Lo;0;AL;;;;;N;ARABIC LETTER WAVY HAMZAH UNDER ALEF;;;; +0674;ARABIC LETTER HIGH HAMZA;Lo;0;AL;;;;;N;ARABIC LETTER HIGH HAMZAH;;;; +0675;ARABIC LETTER HIGH HAMZA ALEF;Lo;0;AL; 0627 0674;;;;N;ARABIC LETTER HIGH HAMZAH ALEF;;;; +0676;ARABIC LETTER HIGH HAMZA WAW;Lo;0;AL; 0648 0674;;;;N;ARABIC LETTER HIGH HAMZAH WAW;;;; +0677;ARABIC LETTER U WITH HAMZA ABOVE;Lo;0;AL; 06C7 0674;;;;N;ARABIC LETTER HIGH HAMZAH WAW WITH DAMMAH;;;; +0678;ARABIC LETTER HIGH HAMZA YEH;Lo;0;AL; 064A 0674;;;;N;ARABIC LETTER HIGH HAMZAH YA;;;; +0679;ARABIC LETTER TTEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH SMALL TAH;;;; +067A;ARABIC LETTER TTEHEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH TWO DOTS VERTICAL ABOVE;;;; +067B;ARABIC LETTER BEEH;Lo;0;AL;;;;;N;ARABIC LETTER BAA WITH TWO DOTS VERTICAL BELOW;;;; +067C;ARABIC LETTER TEH WITH RING;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH RING;;;; +067D;ARABIC LETTER TEH WITH THREE DOTS ABOVE DOWNWARDS;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH THREE DOTS ABOVE DOWNWARD;;;; +067E;ARABIC LETTER PEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH THREE DOTS BELOW;;;; +067F;ARABIC LETTER TEHEH;Lo;0;AL;;;;;N;ARABIC LETTER TAA WITH FOUR DOTS ABOVE;;;; +0680;ARABIC LETTER BEHEH;Lo;0;AL;;;;;N;ARABIC LETTER BAA WITH FOUR DOTS BELOW;;;; +0681;ARABIC LETTER HAH WITH HAMZA ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER HAMZAH ON HAA;;;; +0682;ARABIC LETTER HAH WITH TWO DOTS VERTICAL ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH TWO DOTS VERTICAL ABOVE;;;; +0683;ARABIC LETTER NYEH;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH MIDDLE TWO DOTS;;;; +0684;ARABIC LETTER DYEH;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH MIDDLE TWO DOTS VERTICAL;;;; +0685;ARABIC LETTER HAH WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH THREE DOTS ABOVE;;;; +0686;ARABIC LETTER TCHEH;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH MIDDLE THREE DOTS DOWNWARD;;;; +0687;ARABIC LETTER TCHEHEH;Lo;0;AL;;;;;N;ARABIC LETTER HAA WITH MIDDLE FOUR DOTS;;;; +0688;ARABIC LETTER DDAL;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH SMALL TAH;;;; +0689;ARABIC LETTER DAL WITH RING;Lo;0;AL;;;;;N;;;;; +068A;ARABIC LETTER DAL WITH DOT BELOW;Lo;0;AL;;;;;N;;;;; +068B;ARABIC LETTER DAL WITH DOT BELOW AND SMALL TAH;Lo;0;AL;;;;;N;;;;; +068C;ARABIC LETTER DAHAL;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH TWO DOTS ABOVE;;;; +068D;ARABIC LETTER DDAHAL;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH TWO DOTS BELOW;;;; +068E;ARABIC LETTER DUL;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH THREE DOTS ABOVE;;;; +068F;ARABIC LETTER DAL WITH THREE DOTS ABOVE DOWNWARDS;Lo;0;AL;;;;;N;ARABIC LETTER DAL WITH THREE DOTS ABOVE DOWNWARD;;;; +0690;ARABIC LETTER DAL WITH FOUR DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +0691;ARABIC LETTER RREH;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH SMALL TAH;;;; +0692;ARABIC LETTER REH WITH SMALL V;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH SMALL V;;;; +0693;ARABIC LETTER REH WITH RING;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH RING;;;; +0694;ARABIC LETTER REH WITH DOT BELOW;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH DOT BELOW;;;; +0695;ARABIC LETTER REH WITH SMALL V BELOW;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH SMALL V BELOW;;;; +0696;ARABIC LETTER REH WITH DOT BELOW AND DOT ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH DOT BELOW AND DOT ABOVE;;;; +0697;ARABIC LETTER REH WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH TWO DOTS ABOVE;;;; +0698;ARABIC LETTER JEH;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH THREE DOTS ABOVE;;;; +0699;ARABIC LETTER REH WITH FOUR DOTS ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER RA WITH FOUR DOTS ABOVE;;;; +069A;ARABIC LETTER SEEN WITH DOT BELOW AND DOT ABOVE;Lo;0;AL;;;;;N;;;;; +069B;ARABIC LETTER SEEN WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;;;;; +069C;ARABIC LETTER SEEN WITH THREE DOTS BELOW AND THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +069D;ARABIC LETTER SAD WITH TWO DOTS BELOW;Lo;0;AL;;;;;N;;;;; +069E;ARABIC LETTER SAD WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +069F;ARABIC LETTER TAH WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +06A0;ARABIC LETTER AIN WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +06A1;ARABIC LETTER DOTLESS FEH;Lo;0;AL;;;;;N;ARABIC LETTER DOTLESS FA;;;; +06A2;ARABIC LETTER FEH WITH DOT MOVED BELOW;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH DOT MOVED BELOW;;;; +06A3;ARABIC LETTER FEH WITH DOT BELOW;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH DOT BELOW;;;; +06A4;ARABIC LETTER VEH;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH THREE DOTS ABOVE;;;; +06A5;ARABIC LETTER FEH WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH THREE DOTS BELOW;;;; +06A6;ARABIC LETTER PEHEH;Lo;0;AL;;;;;N;ARABIC LETTER FA WITH FOUR DOTS ABOVE;;;; +06A7;ARABIC LETTER QAF WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;; +06A8;ARABIC LETTER QAF WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +06A9;ARABIC LETTER KEHEH;Lo;0;AL;;;;;N;ARABIC LETTER OPEN CAF;;;; +06AA;ARABIC LETTER SWASH KAF;Lo;0;AL;;;;;N;ARABIC LETTER SWASH CAF;;;; +06AB;ARABIC LETTER KAF WITH RING;Lo;0;AL;;;;;N;ARABIC LETTER CAF WITH RING;;;; +06AC;ARABIC LETTER KAF WITH DOT ABOVE;Lo;0;AL;;;;;N;ARABIC LETTER CAF WITH DOT ABOVE;;;; +06AD;ARABIC LETTER NG;Lo;0;AL;;;;;N;ARABIC LETTER CAF WITH THREE DOTS ABOVE;;;; +06AE;ARABIC LETTER KAF WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;ARABIC LETTER CAF WITH THREE DOTS BELOW;;;; +06AF;ARABIC LETTER GAF;Lo;0;AL;;;;;N;;;;; +06B0;ARABIC LETTER GAF WITH RING;Lo;0;AL;;;;;N;;;;; +06B1;ARABIC LETTER NGOEH;Lo;0;AL;;;;;N;ARABIC LETTER GAF WITH TWO DOTS ABOVE;;;; +06B2;ARABIC LETTER GAF WITH TWO DOTS BELOW;Lo;0;AL;;;;;N;;;;; +06B3;ARABIC LETTER GUEH;Lo;0;AL;;;;;N;ARABIC LETTER GAF WITH TWO DOTS VERTICAL BELOW;;;; +06B4;ARABIC LETTER GAF WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +06B5;ARABIC LETTER LAM WITH SMALL V;Lo;0;AL;;;;;N;;;;; +06B6;ARABIC LETTER LAM WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;; +06B7;ARABIC LETTER LAM WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +06B8;ARABIC LETTER LAM WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;;;;; +06B9;ARABIC LETTER NOON WITH DOT BELOW;Lo;0;AL;;;;;N;;;;; +06BA;ARABIC LETTER NOON GHUNNA;Lo;0;AL;;;;;N;ARABIC LETTER DOTLESS NOON;;;; +06BB;ARABIC LETTER RNOON;Lo;0;AL;;;;;N;ARABIC LETTER DOTLESS NOON WITH SMALL TAH;;;; +06BC;ARABIC LETTER NOON WITH RING;Lo;0;AL;;;;;N;;;;; +06BD;ARABIC LETTER NOON WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +06BE;ARABIC LETTER HEH DOACHASHMEE;Lo;0;AL;;;;;N;ARABIC LETTER KNOTTED HA;;;; +06BF;ARABIC LETTER TCHEH WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;; +06C0;ARABIC LETTER HEH WITH YEH ABOVE;Lo;0;AL;06D5 0654;;;;N;ARABIC LETTER HAMZAH ON HA;;;; +06C1;ARABIC LETTER HEH GOAL;Lo;0;AL;;;;;N;ARABIC LETTER HA GOAL;;;; +06C2;ARABIC LETTER HEH GOAL WITH HAMZA ABOVE;Lo;0;AL;06C1 0654;;;;N;ARABIC LETTER HAMZAH ON HA GOAL;;;; +06C3;ARABIC LETTER TEH MARBUTA GOAL;Lo;0;AL;;;;;N;ARABIC LETTER TAA MARBUTAH GOAL;;;; +06C4;ARABIC LETTER WAW WITH RING;Lo;0;AL;;;;;N;;;;; +06C5;ARABIC LETTER KIRGHIZ OE;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH BAR;;;; +06C6;ARABIC LETTER OE;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH SMALL V;;;; +06C7;ARABIC LETTER U;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH DAMMAH;;;; +06C8;ARABIC LETTER YU;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH ALEF ABOVE;;;; +06C9;ARABIC LETTER KIRGHIZ YU;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH INVERTED SMALL V;;;; +06CA;ARABIC LETTER WAW WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +06CB;ARABIC LETTER VE;Lo;0;AL;;;;;N;ARABIC LETTER WAW WITH THREE DOTS ABOVE;;;; +06CC;ARABIC LETTER FARSI YEH;Lo;0;AL;;;;;N;ARABIC LETTER DOTLESS YA;;;; +06CD;ARABIC LETTER YEH WITH TAIL;Lo;0;AL;;;;;N;ARABIC LETTER YA WITH TAIL;;;; +06CE;ARABIC LETTER YEH WITH SMALL V;Lo;0;AL;;;;;N;ARABIC LETTER YA WITH SMALL V;;;; +06CF;ARABIC LETTER WAW WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;; +06D0;ARABIC LETTER E;Lo;0;AL;;;;;N;ARABIC LETTER YA WITH TWO DOTS VERTICAL BELOW;;;; +06D1;ARABIC LETTER YEH WITH THREE DOTS BELOW;Lo;0;AL;;;;;N;ARABIC LETTER YA WITH THREE DOTS BELOW;;;; +06D2;ARABIC LETTER YEH BARREE;Lo;0;AL;;;;;N;ARABIC LETTER YA BARREE;;;; +06D3;ARABIC LETTER YEH BARREE WITH HAMZA ABOVE;Lo;0;AL;06D2 0654;;;;N;ARABIC LETTER HAMZAH ON YA BARREE;;;; +06D4;ARABIC FULL STOP;Po;0;AL;;;;;N;ARABIC PERIOD;;;; +06D5;ARABIC LETTER AE;Lo;0;AL;;;;;N;;;;; +06D6;ARABIC SMALL HIGH LIGATURE SAD WITH LAM WITH ALEF MAKSURA;Mn;230;NSM;;;;;N;;;;; +06D7;ARABIC SMALL HIGH LIGATURE QAF WITH LAM WITH ALEF MAKSURA;Mn;230;NSM;;;;;N;;;;; +06D8;ARABIC SMALL HIGH MEEM INITIAL FORM;Mn;230;NSM;;;;;N;;;;; +06D9;ARABIC SMALL HIGH LAM ALEF;Mn;230;NSM;;;;;N;;;;; +06DA;ARABIC SMALL HIGH JEEM;Mn;230;NSM;;;;;N;;;;; +06DB;ARABIC SMALL HIGH THREE DOTS;Mn;230;NSM;;;;;N;;;;; +06DC;ARABIC SMALL HIGH SEEN;Mn;230;NSM;;;;;N;;;;; +06DD;ARABIC END OF AYAH;Cf;0;AN;;;;;N;;;;; +06DE;ARABIC START OF RUB EL HIZB;So;0;ON;;;;;N;;;;; +06DF;ARABIC SMALL HIGH ROUNDED ZERO;Mn;230;NSM;;;;;N;;;;; +06E0;ARABIC SMALL HIGH UPRIGHT RECTANGULAR ZERO;Mn;230;NSM;;;;;N;;;;; +06E1;ARABIC SMALL HIGH DOTLESS HEAD OF KHAH;Mn;230;NSM;;;;;N;;;;; +06E2;ARABIC SMALL HIGH MEEM ISOLATED FORM;Mn;230;NSM;;;;;N;;;;; +06E3;ARABIC SMALL LOW SEEN;Mn;220;NSM;;;;;N;;;;; +06E4;ARABIC SMALL HIGH MADDA;Mn;230;NSM;;;;;N;;;;; +06E5;ARABIC SMALL WAW;Lm;0;AL;;;;;N;;;;; +06E6;ARABIC SMALL YEH;Lm;0;AL;;;;;N;;;;; +06E7;ARABIC SMALL HIGH YEH;Mn;230;NSM;;;;;N;;;;; +06E8;ARABIC SMALL HIGH NOON;Mn;230;NSM;;;;;N;;;;; +06E9;ARABIC PLACE OF SAJDAH;So;0;ON;;;;;N;;;;; +06EA;ARABIC EMPTY CENTRE LOW STOP;Mn;220;NSM;;;;;N;;;;; +06EB;ARABIC EMPTY CENTRE HIGH STOP;Mn;230;NSM;;;;;N;;;;; +06EC;ARABIC ROUNDED HIGH STOP WITH FILLED CENTRE;Mn;230;NSM;;;;;N;;;;; +06ED;ARABIC SMALL LOW MEEM;Mn;220;NSM;;;;;N;;;;; +06EE;ARABIC LETTER DAL WITH INVERTED V;Lo;0;AL;;;;;N;;;;; +06EF;ARABIC LETTER REH WITH INVERTED V;Lo;0;AL;;;;;N;;;;; +06F0;EXTENDED ARABIC-INDIC DIGIT ZERO;Nd;0;EN;;0;0;0;N;EASTERN ARABIC-INDIC DIGIT ZERO;;;; +06F1;EXTENDED ARABIC-INDIC DIGIT ONE;Nd;0;EN;;1;1;1;N;EASTERN ARABIC-INDIC DIGIT ONE;;;; +06F2;EXTENDED ARABIC-INDIC DIGIT TWO;Nd;0;EN;;2;2;2;N;EASTERN ARABIC-INDIC DIGIT TWO;;;; +06F3;EXTENDED ARABIC-INDIC DIGIT THREE;Nd;0;EN;;3;3;3;N;EASTERN ARABIC-INDIC DIGIT THREE;;;; +06F4;EXTENDED ARABIC-INDIC DIGIT FOUR;Nd;0;EN;;4;4;4;N;EASTERN ARABIC-INDIC DIGIT FOUR;;;; +06F5;EXTENDED ARABIC-INDIC DIGIT FIVE;Nd;0;EN;;5;5;5;N;EASTERN ARABIC-INDIC DIGIT FIVE;;;; +06F6;EXTENDED ARABIC-INDIC DIGIT SIX;Nd;0;EN;;6;6;6;N;EASTERN ARABIC-INDIC DIGIT SIX;;;; +06F7;EXTENDED ARABIC-INDIC DIGIT SEVEN;Nd;0;EN;;7;7;7;N;EASTERN ARABIC-INDIC DIGIT SEVEN;;;; +06F8;EXTENDED ARABIC-INDIC DIGIT EIGHT;Nd;0;EN;;8;8;8;N;EASTERN ARABIC-INDIC DIGIT EIGHT;;;; +06F9;EXTENDED ARABIC-INDIC DIGIT NINE;Nd;0;EN;;9;9;9;N;EASTERN ARABIC-INDIC DIGIT NINE;;;; +06FA;ARABIC LETTER SHEEN WITH DOT BELOW;Lo;0;AL;;;;;N;;;;; +06FB;ARABIC LETTER DAD WITH DOT BELOW;Lo;0;AL;;;;;N;;;;; +06FC;ARABIC LETTER GHAIN WITH DOT BELOW;Lo;0;AL;;;;;N;;;;; +06FD;ARABIC SIGN SINDHI AMPERSAND;So;0;AL;;;;;N;;;;; +06FE;ARABIC SIGN SINDHI POSTPOSITION MEN;So;0;AL;;;;;N;;;;; +06FF;ARABIC LETTER HEH WITH INVERTED V;Lo;0;AL;;;;;N;;;;; +0700;SYRIAC END OF PARAGRAPH;Po;0;AL;;;;;N;;;;; +0701;SYRIAC SUPRALINEAR FULL STOP;Po;0;AL;;;;;N;;;;; +0702;SYRIAC SUBLINEAR FULL STOP;Po;0;AL;;;;;N;;;;; +0703;SYRIAC SUPRALINEAR COLON;Po;0;AL;;;;;N;;;;; +0704;SYRIAC SUBLINEAR COLON;Po;0;AL;;;;;N;;;;; +0705;SYRIAC HORIZONTAL COLON;Po;0;AL;;;;;N;;;;; +0706;SYRIAC COLON SKEWED LEFT;Po;0;AL;;;;;N;;;;; +0707;SYRIAC COLON SKEWED RIGHT;Po;0;AL;;;;;N;;;;; +0708;SYRIAC SUPRALINEAR COLON SKEWED LEFT;Po;0;AL;;;;;N;;;;; +0709;SYRIAC SUBLINEAR COLON SKEWED RIGHT;Po;0;AL;;;;;N;;;;; +070A;SYRIAC CONTRACTION;Po;0;AL;;;;;N;;;;; +070B;SYRIAC HARKLEAN OBELUS;Po;0;AL;;;;;N;;;;; +070C;SYRIAC HARKLEAN METOBELUS;Po;0;AL;;;;;N;;;;; +070D;SYRIAC HARKLEAN ASTERISCUS;Po;0;AL;;;;;N;;;;; +070F;SYRIAC ABBREVIATION MARK;Cf;0;AL;;;;;N;;;;; +0710;SYRIAC LETTER ALAPH;Lo;0;AL;;;;;N;;;;; +0711;SYRIAC LETTER SUPERSCRIPT ALAPH;Mn;36;NSM;;;;;N;;;;; +0712;SYRIAC LETTER BETH;Lo;0;AL;;;;;N;;;;; +0713;SYRIAC LETTER GAMAL;Lo;0;AL;;;;;N;;;;; +0714;SYRIAC LETTER GAMAL GARSHUNI;Lo;0;AL;;;;;N;;;;; +0715;SYRIAC LETTER DALATH;Lo;0;AL;;;;;N;;;;; +0716;SYRIAC LETTER DOTLESS DALATH RISH;Lo;0;AL;;;;;N;;;;; +0717;SYRIAC LETTER HE;Lo;0;AL;;;;;N;;;;; +0718;SYRIAC LETTER WAW;Lo;0;AL;;;;;N;;;;; +0719;SYRIAC LETTER ZAIN;Lo;0;AL;;;;;N;;;;; +071A;SYRIAC LETTER HETH;Lo;0;AL;;;;;N;;;;; +071B;SYRIAC LETTER TETH;Lo;0;AL;;;;;N;;;;; +071C;SYRIAC LETTER TETH GARSHUNI;Lo;0;AL;;;;;N;;;;; +071D;SYRIAC LETTER YUDH;Lo;0;AL;;;;;N;;;;; +071E;SYRIAC LETTER YUDH HE;Lo;0;AL;;;;;N;;;;; +071F;SYRIAC LETTER KAPH;Lo;0;AL;;;;;N;;;;; +0720;SYRIAC LETTER LAMADH;Lo;0;AL;;;;;N;;;;; +0721;SYRIAC LETTER MIM;Lo;0;AL;;;;;N;;;;; +0722;SYRIAC LETTER NUN;Lo;0;AL;;;;;N;;;;; +0723;SYRIAC LETTER SEMKATH;Lo;0;AL;;;;;N;;;;; +0724;SYRIAC LETTER FINAL SEMKATH;Lo;0;AL;;;;;N;;;;; +0725;SYRIAC LETTER E;Lo;0;AL;;;;;N;;;;; +0726;SYRIAC LETTER PE;Lo;0;AL;;;;;N;;;;; +0727;SYRIAC LETTER REVERSED PE;Lo;0;AL;;;;;N;;;;; +0728;SYRIAC LETTER SADHE;Lo;0;AL;;;;;N;;;;; +0729;SYRIAC LETTER QAPH;Lo;0;AL;;;;;N;;;;; +072A;SYRIAC LETTER RISH;Lo;0;AL;;;;;N;;;;; +072B;SYRIAC LETTER SHIN;Lo;0;AL;;;;;N;;;;; +072C;SYRIAC LETTER TAW;Lo;0;AL;;;;;N;;;;; +072D;SYRIAC LETTER PERSIAN BHETH;Lo;0;AL;;;;;N;;;;; +072E;SYRIAC LETTER PERSIAN GHAMAL;Lo;0;AL;;;;;N;;;;; +072F;SYRIAC LETTER PERSIAN DHALATH;Lo;0;AL;;;;;N;;;;; +0730;SYRIAC PTHAHA ABOVE;Mn;230;NSM;;;;;N;;;;; +0731;SYRIAC PTHAHA BELOW;Mn;220;NSM;;;;;N;;;;; +0732;SYRIAC PTHAHA DOTTED;Mn;230;NSM;;;;;N;;;;; +0733;SYRIAC ZQAPHA ABOVE;Mn;230;NSM;;;;;N;;;;; +0734;SYRIAC ZQAPHA BELOW;Mn;220;NSM;;;;;N;;;;; +0735;SYRIAC ZQAPHA DOTTED;Mn;230;NSM;;;;;N;;;;; +0736;SYRIAC RBASA ABOVE;Mn;230;NSM;;;;;N;;;;; +0737;SYRIAC RBASA BELOW;Mn;220;NSM;;;;;N;;;;; +0738;SYRIAC DOTTED ZLAMA HORIZONTAL;Mn;220;NSM;;;;;N;;;;; +0739;SYRIAC DOTTED ZLAMA ANGULAR;Mn;220;NSM;;;;;N;;;;; +073A;SYRIAC HBASA ABOVE;Mn;230;NSM;;;;;N;;;;; +073B;SYRIAC HBASA BELOW;Mn;220;NSM;;;;;N;;;;; +073C;SYRIAC HBASA-ESASA DOTTED;Mn;220;NSM;;;;;N;;;;; +073D;SYRIAC ESASA ABOVE;Mn;230;NSM;;;;;N;;;;; +073E;SYRIAC ESASA BELOW;Mn;220;NSM;;;;;N;;;;; +073F;SYRIAC RWAHA;Mn;230;NSM;;;;;N;;;;; +0740;SYRIAC FEMININE DOT;Mn;230;NSM;;;;;N;;;;; +0741;SYRIAC QUSHSHAYA;Mn;230;NSM;;;;;N;;;;; +0742;SYRIAC RUKKAKHA;Mn;220;NSM;;;;;N;;;;; +0743;SYRIAC TWO VERTICAL DOTS ABOVE;Mn;230;NSM;;;;;N;;;;; +0744;SYRIAC TWO VERTICAL DOTS BELOW;Mn;220;NSM;;;;;N;;;;; +0745;SYRIAC THREE DOTS ABOVE;Mn;230;NSM;;;;;N;;;;; +0746;SYRIAC THREE DOTS BELOW;Mn;220;NSM;;;;;N;;;;; +0747;SYRIAC OBLIQUE LINE ABOVE;Mn;230;NSM;;;;;N;;;;; +0748;SYRIAC OBLIQUE LINE BELOW;Mn;220;NSM;;;;;N;;;;; +0749;SYRIAC MUSIC;Mn;230;NSM;;;;;N;;;;; +074A;SYRIAC BARREKH;Mn;230;NSM;;;;;N;;;;; +074D;SYRIAC LETTER SOGDIAN ZHAIN;Lo;0;AL;;;;;N;;;;; +074E;SYRIAC LETTER SOGDIAN KHAPH;Lo;0;AL;;;;;N;;;;; +074F;SYRIAC LETTER SOGDIAN FE;Lo;0;AL;;;;;N;;;;; +0750;ARABIC LETTER BEH WITH THREE DOTS HORIZONTALLY BELOW;Lo;0;AL;;;;;N;;;;; +0751;ARABIC LETTER BEH WITH DOT BELOW AND THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +0752;ARABIC LETTER BEH WITH THREE DOTS POINTING UPWARDS BELOW;Lo;0;AL;;;;;N;;;;; +0753;ARABIC LETTER BEH WITH THREE DOTS POINTING UPWARDS BELOW AND TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +0754;ARABIC LETTER BEH WITH TWO DOTS BELOW AND DOT ABOVE;Lo;0;AL;;;;;N;;;;; +0755;ARABIC LETTER BEH WITH INVERTED SMALL V BELOW;Lo;0;AL;;;;;N;;;;; +0756;ARABIC LETTER BEH WITH SMALL V;Lo;0;AL;;;;;N;;;;; +0757;ARABIC LETTER HAH WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +0758;ARABIC LETTER HAH WITH THREE DOTS POINTING UPWARDS BELOW;Lo;0;AL;;;;;N;;;;; +0759;ARABIC LETTER DAL WITH TWO DOTS VERTICALLY BELOW AND SMALL TAH;Lo;0;AL;;;;;N;;;;; +075A;ARABIC LETTER DAL WITH INVERTED SMALL V BELOW;Lo;0;AL;;;;;N;;;;; +075B;ARABIC LETTER REH WITH STROKE;Lo;0;AL;;;;;N;;;;; +075C;ARABIC LETTER SEEN WITH FOUR DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +075D;ARABIC LETTER AIN WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +075E;ARABIC LETTER AIN WITH THREE DOTS POINTING DOWNWARDS ABOVE;Lo;0;AL;;;;;N;;;;; +075F;ARABIC LETTER AIN WITH TWO DOTS VERTICALLY ABOVE;Lo;0;AL;;;;;N;;;;; +0760;ARABIC LETTER FEH WITH TWO DOTS BELOW;Lo;0;AL;;;;;N;;;;; +0761;ARABIC LETTER FEH WITH THREE DOTS POINTING UPWARDS BELOW;Lo;0;AL;;;;;N;;;;; +0762;ARABIC LETTER KEHEH WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;; +0763;ARABIC LETTER KEHEH WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +0764;ARABIC LETTER KEHEH WITH THREE DOTS POINTING UPWARDS BELOW;Lo;0;AL;;;;;N;;;;; +0765;ARABIC LETTER MEEM WITH DOT ABOVE;Lo;0;AL;;;;;N;;;;; +0766;ARABIC LETTER MEEM WITH DOT BELOW;Lo;0;AL;;;;;N;;;;; +0767;ARABIC LETTER NOON WITH TWO DOTS BELOW;Lo;0;AL;;;;;N;;;;; +0768;ARABIC LETTER NOON WITH SMALL TAH;Lo;0;AL;;;;;N;;;;; +0769;ARABIC LETTER NOON WITH SMALL V;Lo;0;AL;;;;;N;;;;; +076A;ARABIC LETTER LAM WITH BAR;Lo;0;AL;;;;;N;;;;; +076B;ARABIC LETTER REH WITH TWO DOTS VERTICALLY ABOVE;Lo;0;AL;;;;;N;;;;; +076C;ARABIC LETTER REH WITH HAMZA ABOVE;Lo;0;AL;;;;;N;;;;; +076D;ARABIC LETTER SEEN WITH TWO DOTS VERTICALLY ABOVE;Lo;0;AL;;;;;N;;;;; +076E;ARABIC LETTER HAH WITH SMALL ARABIC LETTER TAH BELOW;Lo;0;AL;;;;;N;;;;; +076F;ARABIC LETTER HAH WITH SMALL ARABIC LETTER TAH AND TWO DOTS;Lo;0;AL;;;;;N;;;;; +0770;ARABIC LETTER SEEN WITH SMALL ARABIC LETTER TAH AND TWO DOTS;Lo;0;AL;;;;;N;;;;; +0771;ARABIC LETTER REH WITH SMALL ARABIC LETTER TAH AND TWO DOTS;Lo;0;AL;;;;;N;;;;; +0772;ARABIC LETTER HAH WITH SMALL ARABIC LETTER TAH ABOVE;Lo;0;AL;;;;;N;;;;; +0773;ARABIC LETTER ALEF WITH EXTENDED ARABIC-INDIC DIGIT TWO ABOVE;Lo;0;AL;;;;;N;;;;; +0774;ARABIC LETTER ALEF WITH EXTENDED ARABIC-INDIC DIGIT THREE ABOVE;Lo;0;AL;;;;;N;;;;; +0775;ARABIC LETTER FARSI YEH WITH EXTENDED ARABIC-INDIC DIGIT TWO ABOVE;Lo;0;AL;;;;;N;;;;; +0776;ARABIC LETTER FARSI YEH WITH EXTENDED ARABIC-INDIC DIGIT THREE ABOVE;Lo;0;AL;;;;;N;;;;; +0777;ARABIC LETTER FARSI YEH WITH EXTENDED ARABIC-INDIC DIGIT FOUR BELOW;Lo;0;AL;;;;;N;;;;; +0778;ARABIC LETTER WAW WITH EXTENDED ARABIC-INDIC DIGIT TWO ABOVE;Lo;0;AL;;;;;N;;;;; +0779;ARABIC LETTER WAW WITH EXTENDED ARABIC-INDIC DIGIT THREE ABOVE;Lo;0;AL;;;;;N;;;;; +077A;ARABIC LETTER YEH BARREE WITH EXTENDED ARABIC-INDIC DIGIT TWO ABOVE;Lo;0;AL;;;;;N;;;;; +077B;ARABIC LETTER YEH BARREE WITH EXTENDED ARABIC-INDIC DIGIT THREE ABOVE;Lo;0;AL;;;;;N;;;;; +077C;ARABIC LETTER HAH WITH EXTENDED ARABIC-INDIC DIGIT FOUR BELOW;Lo;0;AL;;;;;N;;;;; +077D;ARABIC LETTER SEEN WITH EXTENDED ARABIC-INDIC DIGIT FOUR ABOVE;Lo;0;AL;;;;;N;;;;; +077E;ARABIC LETTER SEEN WITH INVERTED V;Lo;0;AL;;;;;N;;;;; +077F;ARABIC LETTER KAF WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +0780;THAANA LETTER HAA;Lo;0;AL;;;;;N;;;;; +0781;THAANA LETTER SHAVIYANI;Lo;0;AL;;;;;N;;;;; +0782;THAANA LETTER NOONU;Lo;0;AL;;;;;N;;;;; +0783;THAANA LETTER RAA;Lo;0;AL;;;;;N;;;;; +0784;THAANA LETTER BAA;Lo;0;AL;;;;;N;;;;; +0785;THAANA LETTER LHAVIYANI;Lo;0;AL;;;;;N;;;;; +0786;THAANA LETTER KAAFU;Lo;0;AL;;;;;N;;;;; +0787;THAANA LETTER ALIFU;Lo;0;AL;;;;;N;;;;; +0788;THAANA LETTER VAAVU;Lo;0;AL;;;;;N;;;;; +0789;THAANA LETTER MEEMU;Lo;0;AL;;;;;N;;;;; +078A;THAANA LETTER FAAFU;Lo;0;AL;;;;;N;;;;; +078B;THAANA LETTER DHAALU;Lo;0;AL;;;;;N;;;;; +078C;THAANA LETTER THAA;Lo;0;AL;;;;;N;;;;; +078D;THAANA LETTER LAAMU;Lo;0;AL;;;;;N;;;;; +078E;THAANA LETTER GAAFU;Lo;0;AL;;;;;N;;;;; +078F;THAANA LETTER GNAVIYANI;Lo;0;AL;;;;;N;;;;; +0790;THAANA LETTER SEENU;Lo;0;AL;;;;;N;;;;; +0791;THAANA LETTER DAVIYANI;Lo;0;AL;;;;;N;;;;; +0792;THAANA LETTER ZAVIYANI;Lo;0;AL;;;;;N;;;;; +0793;THAANA LETTER TAVIYANI;Lo;0;AL;;;;;N;;;;; +0794;THAANA LETTER YAA;Lo;0;AL;;;;;N;;;;; +0795;THAANA LETTER PAVIYANI;Lo;0;AL;;;;;N;;;;; +0796;THAANA LETTER JAVIYANI;Lo;0;AL;;;;;N;;;;; +0797;THAANA LETTER CHAVIYANI;Lo;0;AL;;;;;N;;;;; +0798;THAANA LETTER TTAA;Lo;0;AL;;;;;N;;;;; +0799;THAANA LETTER HHAA;Lo;0;AL;;;;;N;;;;; +079A;THAANA LETTER KHAA;Lo;0;AL;;;;;N;;;;; +079B;THAANA LETTER THAALU;Lo;0;AL;;;;;N;;;;; +079C;THAANA LETTER ZAA;Lo;0;AL;;;;;N;;;;; +079D;THAANA LETTER SHEENU;Lo;0;AL;;;;;N;;;;; +079E;THAANA LETTER SAADHU;Lo;0;AL;;;;;N;;;;; +079F;THAANA LETTER DAADHU;Lo;0;AL;;;;;N;;;;; +07A0;THAANA LETTER TO;Lo;0;AL;;;;;N;;;;; +07A1;THAANA LETTER ZO;Lo;0;AL;;;;;N;;;;; +07A2;THAANA LETTER AINU;Lo;0;AL;;;;;N;;;;; +07A3;THAANA LETTER GHAINU;Lo;0;AL;;;;;N;;;;; +07A4;THAANA LETTER QAAFU;Lo;0;AL;;;;;N;;;;; +07A5;THAANA LETTER WAAVU;Lo;0;AL;;;;;N;;;;; +07A6;THAANA ABAFILI;Mn;0;NSM;;;;;N;;;;; +07A7;THAANA AABAAFILI;Mn;0;NSM;;;;;N;;;;; +07A8;THAANA IBIFILI;Mn;0;NSM;;;;;N;;;;; +07A9;THAANA EEBEEFILI;Mn;0;NSM;;;;;N;;;;; +07AA;THAANA UBUFILI;Mn;0;NSM;;;;;N;;;;; +07AB;THAANA OOBOOFILI;Mn;0;NSM;;;;;N;;;;; +07AC;THAANA EBEFILI;Mn;0;NSM;;;;;N;;;;; +07AD;THAANA EYBEYFILI;Mn;0;NSM;;;;;N;;;;; +07AE;THAANA OBOFILI;Mn;0;NSM;;;;;N;;;;; +07AF;THAANA OABOAFILI;Mn;0;NSM;;;;;N;;;;; +07B0;THAANA SUKUN;Mn;0;NSM;;;;;N;;;;; +07B1;THAANA LETTER NAA;Lo;0;AL;;;;;N;;;;; +07C0;NKO DIGIT ZERO;Nd;0;R;;0;0;0;N;;;;; +07C1;NKO DIGIT ONE;Nd;0;R;;1;1;1;N;;;;; +07C2;NKO DIGIT TWO;Nd;0;R;;2;2;2;N;;;;; +07C3;NKO DIGIT THREE;Nd;0;R;;3;3;3;N;;;;; +07C4;NKO DIGIT FOUR;Nd;0;R;;4;4;4;N;;;;; +07C5;NKO DIGIT FIVE;Nd;0;R;;5;5;5;N;;;;; +07C6;NKO DIGIT SIX;Nd;0;R;;6;6;6;N;;;;; +07C7;NKO DIGIT SEVEN;Nd;0;R;;7;7;7;N;;;;; +07C8;NKO DIGIT EIGHT;Nd;0;R;;8;8;8;N;;;;; +07C9;NKO DIGIT NINE;Nd;0;R;;9;9;9;N;;;;; +07CA;NKO LETTER A;Lo;0;R;;;;;N;;;;; +07CB;NKO LETTER EE;Lo;0;R;;;;;N;;;;; +07CC;NKO LETTER I;Lo;0;R;;;;;N;;;;; +07CD;NKO LETTER E;Lo;0;R;;;;;N;;;;; +07CE;NKO LETTER U;Lo;0;R;;;;;N;;;;; +07CF;NKO LETTER OO;Lo;0;R;;;;;N;;;;; +07D0;NKO LETTER O;Lo;0;R;;;;;N;;;;; +07D1;NKO LETTER DAGBASINNA;Lo;0;R;;;;;N;;;;; +07D2;NKO LETTER N;Lo;0;R;;;;;N;;;;; +07D3;NKO LETTER BA;Lo;0;R;;;;;N;;;;; +07D4;NKO LETTER PA;Lo;0;R;;;;;N;;;;; +07D5;NKO LETTER TA;Lo;0;R;;;;;N;;;;; +07D6;NKO LETTER JA;Lo;0;R;;;;;N;;;;; +07D7;NKO LETTER CHA;Lo;0;R;;;;;N;;;;; +07D8;NKO LETTER DA;Lo;0;R;;;;;N;;;;; +07D9;NKO LETTER RA;Lo;0;R;;;;;N;;;;; +07DA;NKO LETTER RRA;Lo;0;R;;;;;N;;;;; +07DB;NKO LETTER SA;Lo;0;R;;;;;N;;;;; +07DC;NKO LETTER GBA;Lo;0;R;;;;;N;;;;; +07DD;NKO LETTER FA;Lo;0;R;;;;;N;;;;; +07DE;NKO LETTER KA;Lo;0;R;;;;;N;;;;; +07DF;NKO LETTER LA;Lo;0;R;;;;;N;;;;; +07E0;NKO LETTER NA WOLOSO;Lo;0;R;;;;;N;;;;; +07E1;NKO LETTER MA;Lo;0;R;;;;;N;;;;; +07E2;NKO LETTER NYA;Lo;0;R;;;;;N;;;;; +07E3;NKO LETTER NA;Lo;0;R;;;;;N;;;;; +07E4;NKO LETTER HA;Lo;0;R;;;;;N;;;;; +07E5;NKO LETTER WA;Lo;0;R;;;;;N;;;;; +07E6;NKO LETTER YA;Lo;0;R;;;;;N;;;;; +07E7;NKO LETTER NYA WOLOSO;Lo;0;R;;;;;N;;;;; +07E8;NKO LETTER JONA JA;Lo;0;R;;;;;N;;;;; +07E9;NKO LETTER JONA CHA;Lo;0;R;;;;;N;;;;; +07EA;NKO LETTER JONA RA;Lo;0;R;;;;;N;;;;; +07EB;NKO COMBINING SHORT HIGH TONE;Mn;230;NSM;;;;;N;;;;; +07EC;NKO COMBINING SHORT LOW TONE;Mn;230;NSM;;;;;N;;;;; +07ED;NKO COMBINING SHORT RISING TONE;Mn;230;NSM;;;;;N;;;;; +07EE;NKO COMBINING LONG DESCENDING TONE;Mn;230;NSM;;;;;N;;;;; +07EF;NKO COMBINING LONG HIGH TONE;Mn;230;NSM;;;;;N;;;;; +07F0;NKO COMBINING LONG LOW TONE;Mn;230;NSM;;;;;N;;;;; +07F1;NKO COMBINING LONG RISING TONE;Mn;230;NSM;;;;;N;;;;; +07F2;NKO COMBINING NASALIZATION MARK;Mn;220;NSM;;;;;N;;;;; +07F3;NKO COMBINING DOUBLE DOT ABOVE;Mn;230;NSM;;;;;N;;;;; +07F4;NKO HIGH TONE APOSTROPHE;Lm;0;R;;;;;N;;;;; +07F5;NKO LOW TONE APOSTROPHE;Lm;0;R;;;;;N;;;;; +07F6;NKO SYMBOL OO DENNEN;So;0;ON;;;;;N;;;;; +07F7;NKO SYMBOL GBAKURUNEN;Po;0;ON;;;;;N;;;;; +07F8;NKO COMMA;Po;0;ON;;;;;N;;;;; +07F9;NKO EXCLAMATION MARK;Po;0;ON;;;;;N;;;;; +07FA;NKO LAJANYALAN;Lm;0;R;;;;;N;;;;; +0800;SAMARITAN LETTER ALAF;Lo;0;R;;;;;N;;;;; +0801;SAMARITAN LETTER BIT;Lo;0;R;;;;;N;;;;; +0802;SAMARITAN LETTER GAMAN;Lo;0;R;;;;;N;;;;; +0803;SAMARITAN LETTER DALAT;Lo;0;R;;;;;N;;;;; +0804;SAMARITAN LETTER IY;Lo;0;R;;;;;N;;;;; +0805;SAMARITAN LETTER BAA;Lo;0;R;;;;;N;;;;; +0806;SAMARITAN LETTER ZEN;Lo;0;R;;;;;N;;;;; +0807;SAMARITAN LETTER IT;Lo;0;R;;;;;N;;;;; +0808;SAMARITAN LETTER TIT;Lo;0;R;;;;;N;;;;; +0809;SAMARITAN LETTER YUT;Lo;0;R;;;;;N;;;;; +080A;SAMARITAN LETTER KAAF;Lo;0;R;;;;;N;;;;; +080B;SAMARITAN LETTER LABAT;Lo;0;R;;;;;N;;;;; +080C;SAMARITAN LETTER MIM;Lo;0;R;;;;;N;;;;; +080D;SAMARITAN LETTER NUN;Lo;0;R;;;;;N;;;;; +080E;SAMARITAN LETTER SINGAAT;Lo;0;R;;;;;N;;;;; +080F;SAMARITAN LETTER IN;Lo;0;R;;;;;N;;;;; +0810;SAMARITAN LETTER FI;Lo;0;R;;;;;N;;;;; +0811;SAMARITAN LETTER TSAADIY;Lo;0;R;;;;;N;;;;; +0812;SAMARITAN LETTER QUF;Lo;0;R;;;;;N;;;;; +0813;SAMARITAN LETTER RISH;Lo;0;R;;;;;N;;;;; +0814;SAMARITAN LETTER SHAN;Lo;0;R;;;;;N;;;;; +0815;SAMARITAN LETTER TAAF;Lo;0;R;;;;;N;;;;; +0816;SAMARITAN MARK IN;Mn;230;NSM;;;;;N;;;;; +0817;SAMARITAN MARK IN-ALAF;Mn;230;NSM;;;;;N;;;;; +0818;SAMARITAN MARK OCCLUSION;Mn;230;NSM;;;;;N;;;;; +0819;SAMARITAN MARK DAGESH;Mn;230;NSM;;;;;N;;;;; +081A;SAMARITAN MODIFIER LETTER EPENTHETIC YUT;Lm;0;R;;;;;N;;;;; +081B;SAMARITAN MARK EPENTHETIC YUT;Mn;230;NSM;;;;;N;;;;; +081C;SAMARITAN VOWEL SIGN LONG E;Mn;230;NSM;;;;;N;;;;; +081D;SAMARITAN VOWEL SIGN E;Mn;230;NSM;;;;;N;;;;; +081E;SAMARITAN VOWEL SIGN OVERLONG AA;Mn;230;NSM;;;;;N;;;;; +081F;SAMARITAN VOWEL SIGN LONG AA;Mn;230;NSM;;;;;N;;;;; +0820;SAMARITAN VOWEL SIGN AA;Mn;230;NSM;;;;;N;;;;; +0821;SAMARITAN VOWEL SIGN OVERLONG A;Mn;230;NSM;;;;;N;;;;; +0822;SAMARITAN VOWEL SIGN LONG A;Mn;230;NSM;;;;;N;;;;; +0823;SAMARITAN VOWEL SIGN A;Mn;230;NSM;;;;;N;;;;; +0824;SAMARITAN MODIFIER LETTER SHORT A;Lm;0;R;;;;;N;;;;; +0825;SAMARITAN VOWEL SIGN SHORT A;Mn;230;NSM;;;;;N;;;;; +0826;SAMARITAN VOWEL SIGN LONG U;Mn;230;NSM;;;;;N;;;;; +0827;SAMARITAN VOWEL SIGN U;Mn;230;NSM;;;;;N;;;;; +0828;SAMARITAN MODIFIER LETTER I;Lm;0;R;;;;;N;;;;; +0829;SAMARITAN VOWEL SIGN LONG I;Mn;230;NSM;;;;;N;;;;; +082A;SAMARITAN VOWEL SIGN I;Mn;230;NSM;;;;;N;;;;; +082B;SAMARITAN VOWEL SIGN O;Mn;230;NSM;;;;;N;;;;; +082C;SAMARITAN VOWEL SIGN SUKUN;Mn;230;NSM;;;;;N;;;;; +082D;SAMARITAN MARK NEQUDAA;Mn;230;NSM;;;;;N;;;;; +0830;SAMARITAN PUNCTUATION NEQUDAA;Po;0;R;;;;;N;;;;; +0831;SAMARITAN PUNCTUATION AFSAAQ;Po;0;R;;;;;N;;;;; +0832;SAMARITAN PUNCTUATION ANGED;Po;0;R;;;;;N;;;;; +0833;SAMARITAN PUNCTUATION BAU;Po;0;R;;;;;N;;;;; +0834;SAMARITAN PUNCTUATION ATMAAU;Po;0;R;;;;;N;;;;; +0835;SAMARITAN PUNCTUATION SHIYYAALAA;Po;0;R;;;;;N;;;;; +0836;SAMARITAN ABBREVIATION MARK;Po;0;R;;;;;N;;;;; +0837;SAMARITAN PUNCTUATION MELODIC QITSA;Po;0;R;;;;;N;;;;; +0838;SAMARITAN PUNCTUATION ZIQAA;Po;0;R;;;;;N;;;;; +0839;SAMARITAN PUNCTUATION QITSA;Po;0;R;;;;;N;;;;; +083A;SAMARITAN PUNCTUATION ZAEF;Po;0;R;;;;;N;;;;; +083B;SAMARITAN PUNCTUATION TURU;Po;0;R;;;;;N;;;;; +083C;SAMARITAN PUNCTUATION ARKAANU;Po;0;R;;;;;N;;;;; +083D;SAMARITAN PUNCTUATION SOF MASHFAAT;Po;0;R;;;;;N;;;;; +083E;SAMARITAN PUNCTUATION ANNAAU;Po;0;R;;;;;N;;;;; +0840;MANDAIC LETTER HALQA;Lo;0;R;;;;;N;;;;; +0841;MANDAIC LETTER AB;Lo;0;R;;;;;N;;;;; +0842;MANDAIC LETTER AG;Lo;0;R;;;;;N;;;;; +0843;MANDAIC LETTER AD;Lo;0;R;;;;;N;;;;; +0844;MANDAIC LETTER AH;Lo;0;R;;;;;N;;;;; +0845;MANDAIC LETTER USHENNA;Lo;0;R;;;;;N;;;;; +0846;MANDAIC LETTER AZ;Lo;0;R;;;;;N;;;;; +0847;MANDAIC LETTER IT;Lo;0;R;;;;;N;;;;; +0848;MANDAIC LETTER ATT;Lo;0;R;;;;;N;;;;; +0849;MANDAIC LETTER AKSA;Lo;0;R;;;;;N;;;;; +084A;MANDAIC LETTER AK;Lo;0;R;;;;;N;;;;; +084B;MANDAIC LETTER AL;Lo;0;R;;;;;N;;;;; +084C;MANDAIC LETTER AM;Lo;0;R;;;;;N;;;;; +084D;MANDAIC LETTER AN;Lo;0;R;;;;;N;;;;; +084E;MANDAIC LETTER AS;Lo;0;R;;;;;N;;;;; +084F;MANDAIC LETTER IN;Lo;0;R;;;;;N;;;;; +0850;MANDAIC LETTER AP;Lo;0;R;;;;;N;;;;; +0851;MANDAIC LETTER ASZ;Lo;0;R;;;;;N;;;;; +0852;MANDAIC LETTER AQ;Lo;0;R;;;;;N;;;;; +0853;MANDAIC LETTER AR;Lo;0;R;;;;;N;;;;; +0854;MANDAIC LETTER ASH;Lo;0;R;;;;;N;;;;; +0855;MANDAIC LETTER AT;Lo;0;R;;;;;N;;;;; +0856;MANDAIC LETTER DUSHENNA;Lo;0;R;;;;;N;;;;; +0857;MANDAIC LETTER KAD;Lo;0;R;;;;;N;;;;; +0858;MANDAIC LETTER AIN;Lo;0;R;;;;;N;;;;; +0859;MANDAIC AFFRICATION MARK;Mn;220;NSM;;;;;N;;;;; +085A;MANDAIC VOCALIZATION MARK;Mn;220;NSM;;;;;N;;;;; +085B;MANDAIC GEMINATION MARK;Mn;220;NSM;;;;;N;;;;; +085E;MANDAIC PUNCTUATION;Po;0;R;;;;;N;;;;; +08A0;ARABIC LETTER BEH WITH SMALL V BELOW;Lo;0;AL;;;;;N;;;;; +08A2;ARABIC LETTER JEEM WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +08A3;ARABIC LETTER TAH WITH TWO DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +08A4;ARABIC LETTER FEH WITH DOT BELOW AND THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +08A5;ARABIC LETTER QAF WITH DOT BELOW;Lo;0;AL;;;;;N;;;;; +08A6;ARABIC LETTER LAM WITH DOUBLE BAR;Lo;0;AL;;;;;N;;;;; +08A7;ARABIC LETTER MEEM WITH THREE DOTS ABOVE;Lo;0;AL;;;;;N;;;;; +08A8;ARABIC LETTER YEH WITH TWO DOTS BELOW AND HAMZA ABOVE;Lo;0;AL;;;;;N;;;;; +08A9;ARABIC LETTER YEH WITH TWO DOTS BELOW AND DOT ABOVE;Lo;0;AL;;;;;N;;;;; +08AA;ARABIC LETTER REH WITH LOOP;Lo;0;AL;;;;;N;;;;; +08AB;ARABIC LETTER WAW WITH DOT WITHIN;Lo;0;AL;;;;;N;;;;; +08AC;ARABIC LETTER ROHINGYA YEH;Lo;0;AL;;;;;N;;;;; +08E4;ARABIC CURLY FATHA;Mn;230;NSM;;;;;N;;;;; +08E5;ARABIC CURLY DAMMA;Mn;230;NSM;;;;;N;;;;; +08E6;ARABIC CURLY KASRA;Mn;220;NSM;;;;;N;;;;; +08E7;ARABIC CURLY FATHATAN;Mn;230;NSM;;;;;N;;;;; +08E8;ARABIC CURLY DAMMATAN;Mn;230;NSM;;;;;N;;;;; +08E9;ARABIC CURLY KASRATAN;Mn;220;NSM;;;;;N;;;;; +08EA;ARABIC TONE ONE DOT ABOVE;Mn;230;NSM;;;;;N;;;;; +08EB;ARABIC TONE TWO DOTS ABOVE;Mn;230;NSM;;;;;N;;;;; +08EC;ARABIC TONE LOOP ABOVE;Mn;230;NSM;;;;;N;;;;; +08ED;ARABIC TONE ONE DOT BELOW;Mn;220;NSM;;;;;N;;;;; +08EE;ARABIC TONE TWO DOTS BELOW;Mn;220;NSM;;;;;N;;;;; +08EF;ARABIC TONE LOOP BELOW;Mn;220;NSM;;;;;N;;;;; +08F0;ARABIC OPEN FATHATAN;Mn;27;NSM;;;;;N;;;;; +08F1;ARABIC OPEN DAMMATAN;Mn;28;NSM;;;;;N;;;;; +08F2;ARABIC OPEN KASRATAN;Mn;29;NSM;;;;;N;;;;; +08F3;ARABIC SMALL HIGH WAW;Mn;230;NSM;;;;;N;;;;; +08F4;ARABIC FATHA WITH RING;Mn;230;NSM;;;;;N;;;;; +08F5;ARABIC FATHA WITH DOT ABOVE;Mn;230;NSM;;;;;N;;;;; +08F6;ARABIC KASRA WITH DOT BELOW;Mn;220;NSM;;;;;N;;;;; +08F7;ARABIC LEFT ARROWHEAD ABOVE;Mn;230;NSM;;;;;N;;;;; +08F8;ARABIC RIGHT ARROWHEAD ABOVE;Mn;230;NSM;;;;;N;;;;; +08F9;ARABIC LEFT ARROWHEAD BELOW;Mn;220;NSM;;;;;N;;;;; +08FA;ARABIC RIGHT ARROWHEAD BELOW;Mn;220;NSM;;;;;N;;;;; +08FB;ARABIC DOUBLE RIGHT ARROWHEAD ABOVE;Mn;230;NSM;;;;;N;;;;; +08FC;ARABIC DOUBLE RIGHT ARROWHEAD ABOVE WITH DOT;Mn;230;NSM;;;;;N;;;;; +08FD;ARABIC RIGHT ARROWHEAD ABOVE WITH DOT;Mn;230;NSM;;;;;N;;;;; +08FE;ARABIC DAMMA WITH DOT;Mn;230;NSM;;;;;N;;;;; +0900;DEVANAGARI SIGN INVERTED CANDRABINDU;Mn;0;NSM;;;;;N;;;;; +0901;DEVANAGARI SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;; +0902;DEVANAGARI SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +0903;DEVANAGARI SIGN VISARGA;Mc;0;L;;;;;N;;;;; +0904;DEVANAGARI LETTER SHORT A;Lo;0;L;;;;;N;;;;; +0905;DEVANAGARI LETTER A;Lo;0;L;;;;;N;;;;; +0906;DEVANAGARI LETTER AA;Lo;0;L;;;;;N;;;;; +0907;DEVANAGARI LETTER I;Lo;0;L;;;;;N;;;;; +0908;DEVANAGARI LETTER II;Lo;0;L;;;;;N;;;;; +0909;DEVANAGARI LETTER U;Lo;0;L;;;;;N;;;;; +090A;DEVANAGARI LETTER UU;Lo;0;L;;;;;N;;;;; +090B;DEVANAGARI LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +090C;DEVANAGARI LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +090D;DEVANAGARI LETTER CANDRA E;Lo;0;L;;;;;N;;;;; +090E;DEVANAGARI LETTER SHORT E;Lo;0;L;;;;;N;;;;; +090F;DEVANAGARI LETTER E;Lo;0;L;;;;;N;;;;; +0910;DEVANAGARI LETTER AI;Lo;0;L;;;;;N;;;;; +0911;DEVANAGARI LETTER CANDRA O;Lo;0;L;;;;;N;;;;; +0912;DEVANAGARI LETTER SHORT O;Lo;0;L;;;;;N;;;;; +0913;DEVANAGARI LETTER O;Lo;0;L;;;;;N;;;;; +0914;DEVANAGARI LETTER AU;Lo;0;L;;;;;N;;;;; +0915;DEVANAGARI LETTER KA;Lo;0;L;;;;;N;;;;; +0916;DEVANAGARI LETTER KHA;Lo;0;L;;;;;N;;;;; +0917;DEVANAGARI LETTER GA;Lo;0;L;;;;;N;;;;; +0918;DEVANAGARI LETTER GHA;Lo;0;L;;;;;N;;;;; +0919;DEVANAGARI LETTER NGA;Lo;0;L;;;;;N;;;;; +091A;DEVANAGARI LETTER CA;Lo;0;L;;;;;N;;;;; +091B;DEVANAGARI LETTER CHA;Lo;0;L;;;;;N;;;;; +091C;DEVANAGARI LETTER JA;Lo;0;L;;;;;N;;;;; +091D;DEVANAGARI LETTER JHA;Lo;0;L;;;;;N;;;;; +091E;DEVANAGARI LETTER NYA;Lo;0;L;;;;;N;;;;; +091F;DEVANAGARI LETTER TTA;Lo;0;L;;;;;N;;;;; +0920;DEVANAGARI LETTER TTHA;Lo;0;L;;;;;N;;;;; +0921;DEVANAGARI LETTER DDA;Lo;0;L;;;;;N;;;;; +0922;DEVANAGARI LETTER DDHA;Lo;0;L;;;;;N;;;;; +0923;DEVANAGARI LETTER NNA;Lo;0;L;;;;;N;;;;; +0924;DEVANAGARI LETTER TA;Lo;0;L;;;;;N;;;;; +0925;DEVANAGARI LETTER THA;Lo;0;L;;;;;N;;;;; +0926;DEVANAGARI LETTER DA;Lo;0;L;;;;;N;;;;; +0927;DEVANAGARI LETTER DHA;Lo;0;L;;;;;N;;;;; +0928;DEVANAGARI LETTER NA;Lo;0;L;;;;;N;;;;; +0929;DEVANAGARI LETTER NNNA;Lo;0;L;0928 093C;;;;N;;;;; +092A;DEVANAGARI LETTER PA;Lo;0;L;;;;;N;;;;; +092B;DEVANAGARI LETTER PHA;Lo;0;L;;;;;N;;;;; +092C;DEVANAGARI LETTER BA;Lo;0;L;;;;;N;;;;; +092D;DEVANAGARI LETTER BHA;Lo;0;L;;;;;N;;;;; +092E;DEVANAGARI LETTER MA;Lo;0;L;;;;;N;;;;; +092F;DEVANAGARI LETTER YA;Lo;0;L;;;;;N;;;;; +0930;DEVANAGARI LETTER RA;Lo;0;L;;;;;N;;;;; +0931;DEVANAGARI LETTER RRA;Lo;0;L;0930 093C;;;;N;;;;; +0932;DEVANAGARI LETTER LA;Lo;0;L;;;;;N;;;;; +0933;DEVANAGARI LETTER LLA;Lo;0;L;;;;;N;;;;; +0934;DEVANAGARI LETTER LLLA;Lo;0;L;0933 093C;;;;N;;;;; +0935;DEVANAGARI LETTER VA;Lo;0;L;;;;;N;;;;; +0936;DEVANAGARI LETTER SHA;Lo;0;L;;;;;N;;;;; +0937;DEVANAGARI LETTER SSA;Lo;0;L;;;;;N;;;;; +0938;DEVANAGARI LETTER SA;Lo;0;L;;;;;N;;;;; +0939;DEVANAGARI LETTER HA;Lo;0;L;;;;;N;;;;; +093A;DEVANAGARI VOWEL SIGN OE;Mn;0;NSM;;;;;N;;;;; +093B;DEVANAGARI VOWEL SIGN OOE;Mc;0;L;;;;;N;;;;; +093C;DEVANAGARI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;; +093D;DEVANAGARI SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;; +093E;DEVANAGARI VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +093F;DEVANAGARI VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +0940;DEVANAGARI VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +0941;DEVANAGARI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +0942;DEVANAGARI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +0943;DEVANAGARI VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;; +0944;DEVANAGARI VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;; +0945;DEVANAGARI VOWEL SIGN CANDRA E;Mn;0;NSM;;;;;N;;;;; +0946;DEVANAGARI VOWEL SIGN SHORT E;Mn;0;NSM;;;;;N;;;;; +0947;DEVANAGARI VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +0948;DEVANAGARI VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +0949;DEVANAGARI VOWEL SIGN CANDRA O;Mc;0;L;;;;;N;;;;; +094A;DEVANAGARI VOWEL SIGN SHORT O;Mc;0;L;;;;;N;;;;; +094B;DEVANAGARI VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +094C;DEVANAGARI VOWEL SIGN AU;Mc;0;L;;;;;N;;;;; +094D;DEVANAGARI SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +094E;DEVANAGARI VOWEL SIGN PRISHTHAMATRA E;Mc;0;L;;;;;N;;;;; +094F;DEVANAGARI VOWEL SIGN AW;Mc;0;L;;;;;N;;;;; +0950;DEVANAGARI OM;Lo;0;L;;;;;N;;;;; +0951;DEVANAGARI STRESS SIGN UDATTA;Mn;230;NSM;;;;;N;;;;; +0952;DEVANAGARI STRESS SIGN ANUDATTA;Mn;220;NSM;;;;;N;;;;; +0953;DEVANAGARI GRAVE ACCENT;Mn;230;NSM;;;;;N;;;;; +0954;DEVANAGARI ACUTE ACCENT;Mn;230;NSM;;;;;N;;;;; +0955;DEVANAGARI VOWEL SIGN CANDRA LONG E;Mn;0;NSM;;;;;N;;;;; +0956;DEVANAGARI VOWEL SIGN UE;Mn;0;NSM;;;;;N;;;;; +0957;DEVANAGARI VOWEL SIGN UUE;Mn;0;NSM;;;;;N;;;;; +0958;DEVANAGARI LETTER QA;Lo;0;L;0915 093C;;;;N;;;;; +0959;DEVANAGARI LETTER KHHA;Lo;0;L;0916 093C;;;;N;;;;; +095A;DEVANAGARI LETTER GHHA;Lo;0;L;0917 093C;;;;N;;;;; +095B;DEVANAGARI LETTER ZA;Lo;0;L;091C 093C;;;;N;;;;; +095C;DEVANAGARI LETTER DDDHA;Lo;0;L;0921 093C;;;;N;;;;; +095D;DEVANAGARI LETTER RHA;Lo;0;L;0922 093C;;;;N;;;;; +095E;DEVANAGARI LETTER FA;Lo;0;L;092B 093C;;;;N;;;;; +095F;DEVANAGARI LETTER YYA;Lo;0;L;092F 093C;;;;N;;;;; +0960;DEVANAGARI LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +0961;DEVANAGARI LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +0962;DEVANAGARI VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +0963;DEVANAGARI VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +0964;DEVANAGARI DANDA;Po;0;L;;;;;N;;;;; +0965;DEVANAGARI DOUBLE DANDA;Po;0;L;;;;;N;;;;; +0966;DEVANAGARI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0967;DEVANAGARI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0968;DEVANAGARI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0969;DEVANAGARI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +096A;DEVANAGARI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +096B;DEVANAGARI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +096C;DEVANAGARI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +096D;DEVANAGARI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +096E;DEVANAGARI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +096F;DEVANAGARI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0970;DEVANAGARI ABBREVIATION SIGN;Po;0;L;;;;;N;;;;; +0971;DEVANAGARI SIGN HIGH SPACING DOT;Lm;0;L;;;;;N;;;;; +0972;DEVANAGARI LETTER CANDRA A;Lo;0;L;;;;;N;;;;; +0973;DEVANAGARI LETTER OE;Lo;0;L;;;;;N;;;;; +0974;DEVANAGARI LETTER OOE;Lo;0;L;;;;;N;;;;; +0975;DEVANAGARI LETTER AW;Lo;0;L;;;;;N;;;;; +0976;DEVANAGARI LETTER UE;Lo;0;L;;;;;N;;;;; +0977;DEVANAGARI LETTER UUE;Lo;0;L;;;;;N;;;;; +0979;DEVANAGARI LETTER ZHA;Lo;0;L;;;;;N;;;;; +097A;DEVANAGARI LETTER HEAVY YA;Lo;0;L;;;;;N;;;;; +097B;DEVANAGARI LETTER GGA;Lo;0;L;;;;;N;;;;; +097C;DEVANAGARI LETTER JJA;Lo;0;L;;;;;N;;;;; +097D;DEVANAGARI LETTER GLOTTAL STOP;Lo;0;L;;;;;N;;;;; +097E;DEVANAGARI LETTER DDDA;Lo;0;L;;;;;N;;;;; +097F;DEVANAGARI LETTER BBA;Lo;0;L;;;;;N;;;;; +0981;BENGALI SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;; +0982;BENGALI SIGN ANUSVARA;Mc;0;L;;;;;N;;;;; +0983;BENGALI SIGN VISARGA;Mc;0;L;;;;;N;;;;; +0985;BENGALI LETTER A;Lo;0;L;;;;;N;;;;; +0986;BENGALI LETTER AA;Lo;0;L;;;;;N;;;;; +0987;BENGALI LETTER I;Lo;0;L;;;;;N;;;;; +0988;BENGALI LETTER II;Lo;0;L;;;;;N;;;;; +0989;BENGALI LETTER U;Lo;0;L;;;;;N;;;;; +098A;BENGALI LETTER UU;Lo;0;L;;;;;N;;;;; +098B;BENGALI LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +098C;BENGALI LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +098F;BENGALI LETTER E;Lo;0;L;;;;;N;;;;; +0990;BENGALI LETTER AI;Lo;0;L;;;;;N;;;;; +0993;BENGALI LETTER O;Lo;0;L;;;;;N;;;;; +0994;BENGALI LETTER AU;Lo;0;L;;;;;N;;;;; +0995;BENGALI LETTER KA;Lo;0;L;;;;;N;;;;; +0996;BENGALI LETTER KHA;Lo;0;L;;;;;N;;;;; +0997;BENGALI LETTER GA;Lo;0;L;;;;;N;;;;; +0998;BENGALI LETTER GHA;Lo;0;L;;;;;N;;;;; +0999;BENGALI LETTER NGA;Lo;0;L;;;;;N;;;;; +099A;BENGALI LETTER CA;Lo;0;L;;;;;N;;;;; +099B;BENGALI LETTER CHA;Lo;0;L;;;;;N;;;;; +099C;BENGALI LETTER JA;Lo;0;L;;;;;N;;;;; +099D;BENGALI LETTER JHA;Lo;0;L;;;;;N;;;;; +099E;BENGALI LETTER NYA;Lo;0;L;;;;;N;;;;; +099F;BENGALI LETTER TTA;Lo;0;L;;;;;N;;;;; +09A0;BENGALI LETTER TTHA;Lo;0;L;;;;;N;;;;; +09A1;BENGALI LETTER DDA;Lo;0;L;;;;;N;;;;; +09A2;BENGALI LETTER DDHA;Lo;0;L;;;;;N;;;;; +09A3;BENGALI LETTER NNA;Lo;0;L;;;;;N;;;;; +09A4;BENGALI LETTER TA;Lo;0;L;;;;;N;;;;; +09A5;BENGALI LETTER THA;Lo;0;L;;;;;N;;;;; +09A6;BENGALI LETTER DA;Lo;0;L;;;;;N;;;;; +09A7;BENGALI LETTER DHA;Lo;0;L;;;;;N;;;;; +09A8;BENGALI LETTER NA;Lo;0;L;;;;;N;;;;; +09AA;BENGALI LETTER PA;Lo;0;L;;;;;N;;;;; +09AB;BENGALI LETTER PHA;Lo;0;L;;;;;N;;;;; +09AC;BENGALI LETTER BA;Lo;0;L;;;;;N;;;;; +09AD;BENGALI LETTER BHA;Lo;0;L;;;;;N;;;;; +09AE;BENGALI LETTER MA;Lo;0;L;;;;;N;;;;; +09AF;BENGALI LETTER YA;Lo;0;L;;;;;N;;;;; +09B0;BENGALI LETTER RA;Lo;0;L;;;;;N;;;;; +09B2;BENGALI LETTER LA;Lo;0;L;;;;;N;;;;; +09B6;BENGALI LETTER SHA;Lo;0;L;;;;;N;;;;; +09B7;BENGALI LETTER SSA;Lo;0;L;;;;;N;;;;; +09B8;BENGALI LETTER SA;Lo;0;L;;;;;N;;;;; +09B9;BENGALI LETTER HA;Lo;0;L;;;;;N;;;;; +09BC;BENGALI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;; +09BD;BENGALI SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;; +09BE;BENGALI VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +09BF;BENGALI VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +09C0;BENGALI VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +09C1;BENGALI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +09C2;BENGALI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +09C3;BENGALI VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;; +09C4;BENGALI VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;; +09C7;BENGALI VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +09C8;BENGALI VOWEL SIGN AI;Mc;0;L;;;;;N;;;;; +09CB;BENGALI VOWEL SIGN O;Mc;0;L;09C7 09BE;;;;N;;;;; +09CC;BENGALI VOWEL SIGN AU;Mc;0;L;09C7 09D7;;;;N;;;;; +09CD;BENGALI SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +09CE;BENGALI LETTER KHANDA TA;Lo;0;L;;;;;N;;;;; +09D7;BENGALI AU LENGTH MARK;Mc;0;L;;;;;N;;;;; +09DC;BENGALI LETTER RRA;Lo;0;L;09A1 09BC;;;;N;;;;; +09DD;BENGALI LETTER RHA;Lo;0;L;09A2 09BC;;;;N;;;;; +09DF;BENGALI LETTER YYA;Lo;0;L;09AF 09BC;;;;N;;;;; +09E0;BENGALI LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +09E1;BENGALI LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +09E2;BENGALI VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +09E3;BENGALI VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +09E6;BENGALI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +09E7;BENGALI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +09E8;BENGALI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +09E9;BENGALI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +09EA;BENGALI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +09EB;BENGALI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +09EC;BENGALI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +09ED;BENGALI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +09EE;BENGALI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +09EF;BENGALI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +09F0;BENGALI LETTER RA WITH MIDDLE DIAGONAL;Lo;0;L;;;;;N;;;;; +09F1;BENGALI LETTER RA WITH LOWER DIAGONAL;Lo;0;L;;;;;N;BENGALI LETTER VA WITH LOWER DIAGONAL;;;; +09F2;BENGALI RUPEE MARK;Sc;0;ET;;;;;N;;;;; +09F3;BENGALI RUPEE SIGN;Sc;0;ET;;;;;N;;;;; +09F4;BENGALI CURRENCY NUMERATOR ONE;No;0;L;;;;1/16;N;;;;; +09F5;BENGALI CURRENCY NUMERATOR TWO;No;0;L;;;;1/8;N;;;;; +09F6;BENGALI CURRENCY NUMERATOR THREE;No;0;L;;;;3/16;N;;;;; +09F7;BENGALI CURRENCY NUMERATOR FOUR;No;0;L;;;;1/4;N;;;;; +09F8;BENGALI CURRENCY NUMERATOR ONE LESS THAN THE DENOMINATOR;No;0;L;;;;3/4;N;;;;; +09F9;BENGALI CURRENCY DENOMINATOR SIXTEEN;No;0;L;;;;16;N;;;;; +09FA;BENGALI ISSHAR;So;0;L;;;;;N;;;;; +09FB;BENGALI GANDA MARK;Sc;0;ET;;;;;N;;;;; +0A01;GURMUKHI SIGN ADAK BINDI;Mn;0;NSM;;;;;N;;;;; +0A02;GURMUKHI SIGN BINDI;Mn;0;NSM;;;;;N;;;;; +0A03;GURMUKHI SIGN VISARGA;Mc;0;L;;;;;N;;;;; +0A05;GURMUKHI LETTER A;Lo;0;L;;;;;N;;;;; +0A06;GURMUKHI LETTER AA;Lo;0;L;;;;;N;;;;; +0A07;GURMUKHI LETTER I;Lo;0;L;;;;;N;;;;; +0A08;GURMUKHI LETTER II;Lo;0;L;;;;;N;;;;; +0A09;GURMUKHI LETTER U;Lo;0;L;;;;;N;;;;; +0A0A;GURMUKHI LETTER UU;Lo;0;L;;;;;N;;;;; +0A0F;GURMUKHI LETTER EE;Lo;0;L;;;;;N;;;;; +0A10;GURMUKHI LETTER AI;Lo;0;L;;;;;N;;;;; +0A13;GURMUKHI LETTER OO;Lo;0;L;;;;;N;;;;; +0A14;GURMUKHI LETTER AU;Lo;0;L;;;;;N;;;;; +0A15;GURMUKHI LETTER KA;Lo;0;L;;;;;N;;;;; +0A16;GURMUKHI LETTER KHA;Lo;0;L;;;;;N;;;;; +0A17;GURMUKHI LETTER GA;Lo;0;L;;;;;N;;;;; +0A18;GURMUKHI LETTER GHA;Lo;0;L;;;;;N;;;;; +0A19;GURMUKHI LETTER NGA;Lo;0;L;;;;;N;;;;; +0A1A;GURMUKHI LETTER CA;Lo;0;L;;;;;N;;;;; +0A1B;GURMUKHI LETTER CHA;Lo;0;L;;;;;N;;;;; +0A1C;GURMUKHI LETTER JA;Lo;0;L;;;;;N;;;;; +0A1D;GURMUKHI LETTER JHA;Lo;0;L;;;;;N;;;;; +0A1E;GURMUKHI LETTER NYA;Lo;0;L;;;;;N;;;;; +0A1F;GURMUKHI LETTER TTA;Lo;0;L;;;;;N;;;;; +0A20;GURMUKHI LETTER TTHA;Lo;0;L;;;;;N;;;;; +0A21;GURMUKHI LETTER DDA;Lo;0;L;;;;;N;;;;; +0A22;GURMUKHI LETTER DDHA;Lo;0;L;;;;;N;;;;; +0A23;GURMUKHI LETTER NNA;Lo;0;L;;;;;N;;;;; +0A24;GURMUKHI LETTER TA;Lo;0;L;;;;;N;;;;; +0A25;GURMUKHI LETTER THA;Lo;0;L;;;;;N;;;;; +0A26;GURMUKHI LETTER DA;Lo;0;L;;;;;N;;;;; +0A27;GURMUKHI LETTER DHA;Lo;0;L;;;;;N;;;;; +0A28;GURMUKHI LETTER NA;Lo;0;L;;;;;N;;;;; +0A2A;GURMUKHI LETTER PA;Lo;0;L;;;;;N;;;;; +0A2B;GURMUKHI LETTER PHA;Lo;0;L;;;;;N;;;;; +0A2C;GURMUKHI LETTER BA;Lo;0;L;;;;;N;;;;; +0A2D;GURMUKHI LETTER BHA;Lo;0;L;;;;;N;;;;; +0A2E;GURMUKHI LETTER MA;Lo;0;L;;;;;N;;;;; +0A2F;GURMUKHI LETTER YA;Lo;0;L;;;;;N;;;;; +0A30;GURMUKHI LETTER RA;Lo;0;L;;;;;N;;;;; +0A32;GURMUKHI LETTER LA;Lo;0;L;;;;;N;;;;; +0A33;GURMUKHI LETTER LLA;Lo;0;L;0A32 0A3C;;;;N;;;;; +0A35;GURMUKHI LETTER VA;Lo;0;L;;;;;N;;;;; +0A36;GURMUKHI LETTER SHA;Lo;0;L;0A38 0A3C;;;;N;;;;; +0A38;GURMUKHI LETTER SA;Lo;0;L;;;;;N;;;;; +0A39;GURMUKHI LETTER HA;Lo;0;L;;;;;N;;;;; +0A3C;GURMUKHI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;; +0A3E;GURMUKHI VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +0A3F;GURMUKHI VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +0A40;GURMUKHI VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +0A41;GURMUKHI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +0A42;GURMUKHI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +0A47;GURMUKHI VOWEL SIGN EE;Mn;0;NSM;;;;;N;;;;; +0A48;GURMUKHI VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +0A4B;GURMUKHI VOWEL SIGN OO;Mn;0;NSM;;;;;N;;;;; +0A4C;GURMUKHI VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;; +0A4D;GURMUKHI SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +0A51;GURMUKHI SIGN UDAAT;Mn;0;NSM;;;;;N;;;;; +0A59;GURMUKHI LETTER KHHA;Lo;0;L;0A16 0A3C;;;;N;;;;; +0A5A;GURMUKHI LETTER GHHA;Lo;0;L;0A17 0A3C;;;;N;;;;; +0A5B;GURMUKHI LETTER ZA;Lo;0;L;0A1C 0A3C;;;;N;;;;; +0A5C;GURMUKHI LETTER RRA;Lo;0;L;;;;;N;;;;; +0A5E;GURMUKHI LETTER FA;Lo;0;L;0A2B 0A3C;;;;N;;;;; +0A66;GURMUKHI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0A67;GURMUKHI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0A68;GURMUKHI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0A69;GURMUKHI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0A6A;GURMUKHI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0A6B;GURMUKHI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0A6C;GURMUKHI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0A6D;GURMUKHI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0A6E;GURMUKHI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0A6F;GURMUKHI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0A70;GURMUKHI TIPPI;Mn;0;NSM;;;;;N;;;;; +0A71;GURMUKHI ADDAK;Mn;0;NSM;;;;;N;;;;; +0A72;GURMUKHI IRI;Lo;0;L;;;;;N;;;;; +0A73;GURMUKHI URA;Lo;0;L;;;;;N;;;;; +0A74;GURMUKHI EK ONKAR;Lo;0;L;;;;;N;;;;; +0A75;GURMUKHI SIGN YAKASH;Mn;0;NSM;;;;;N;;;;; +0A81;GUJARATI SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;; +0A82;GUJARATI SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +0A83;GUJARATI SIGN VISARGA;Mc;0;L;;;;;N;;;;; +0A85;GUJARATI LETTER A;Lo;0;L;;;;;N;;;;; +0A86;GUJARATI LETTER AA;Lo;0;L;;;;;N;;;;; +0A87;GUJARATI LETTER I;Lo;0;L;;;;;N;;;;; +0A88;GUJARATI LETTER II;Lo;0;L;;;;;N;;;;; +0A89;GUJARATI LETTER U;Lo;0;L;;;;;N;;;;; +0A8A;GUJARATI LETTER UU;Lo;0;L;;;;;N;;;;; +0A8B;GUJARATI LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +0A8C;GUJARATI LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +0A8D;GUJARATI VOWEL CANDRA E;Lo;0;L;;;;;N;;;;; +0A8F;GUJARATI LETTER E;Lo;0;L;;;;;N;;;;; +0A90;GUJARATI LETTER AI;Lo;0;L;;;;;N;;;;; +0A91;GUJARATI VOWEL CANDRA O;Lo;0;L;;;;;N;;;;; +0A93;GUJARATI LETTER O;Lo;0;L;;;;;N;;;;; +0A94;GUJARATI LETTER AU;Lo;0;L;;;;;N;;;;; +0A95;GUJARATI LETTER KA;Lo;0;L;;;;;N;;;;; +0A96;GUJARATI LETTER KHA;Lo;0;L;;;;;N;;;;; +0A97;GUJARATI LETTER GA;Lo;0;L;;;;;N;;;;; +0A98;GUJARATI LETTER GHA;Lo;0;L;;;;;N;;;;; +0A99;GUJARATI LETTER NGA;Lo;0;L;;;;;N;;;;; +0A9A;GUJARATI LETTER CA;Lo;0;L;;;;;N;;;;; +0A9B;GUJARATI LETTER CHA;Lo;0;L;;;;;N;;;;; +0A9C;GUJARATI LETTER JA;Lo;0;L;;;;;N;;;;; +0A9D;GUJARATI LETTER JHA;Lo;0;L;;;;;N;;;;; +0A9E;GUJARATI LETTER NYA;Lo;0;L;;;;;N;;;;; +0A9F;GUJARATI LETTER TTA;Lo;0;L;;;;;N;;;;; +0AA0;GUJARATI LETTER TTHA;Lo;0;L;;;;;N;;;;; +0AA1;GUJARATI LETTER DDA;Lo;0;L;;;;;N;;;;; +0AA2;GUJARATI LETTER DDHA;Lo;0;L;;;;;N;;;;; +0AA3;GUJARATI LETTER NNA;Lo;0;L;;;;;N;;;;; +0AA4;GUJARATI LETTER TA;Lo;0;L;;;;;N;;;;; +0AA5;GUJARATI LETTER THA;Lo;0;L;;;;;N;;;;; +0AA6;GUJARATI LETTER DA;Lo;0;L;;;;;N;;;;; +0AA7;GUJARATI LETTER DHA;Lo;0;L;;;;;N;;;;; +0AA8;GUJARATI LETTER NA;Lo;0;L;;;;;N;;;;; +0AAA;GUJARATI LETTER PA;Lo;0;L;;;;;N;;;;; +0AAB;GUJARATI LETTER PHA;Lo;0;L;;;;;N;;;;; +0AAC;GUJARATI LETTER BA;Lo;0;L;;;;;N;;;;; +0AAD;GUJARATI LETTER BHA;Lo;0;L;;;;;N;;;;; +0AAE;GUJARATI LETTER MA;Lo;0;L;;;;;N;;;;; +0AAF;GUJARATI LETTER YA;Lo;0;L;;;;;N;;;;; +0AB0;GUJARATI LETTER RA;Lo;0;L;;;;;N;;;;; +0AB2;GUJARATI LETTER LA;Lo;0;L;;;;;N;;;;; +0AB3;GUJARATI LETTER LLA;Lo;0;L;;;;;N;;;;; +0AB5;GUJARATI LETTER VA;Lo;0;L;;;;;N;;;;; +0AB6;GUJARATI LETTER SHA;Lo;0;L;;;;;N;;;;; +0AB7;GUJARATI LETTER SSA;Lo;0;L;;;;;N;;;;; +0AB8;GUJARATI LETTER SA;Lo;0;L;;;;;N;;;;; +0AB9;GUJARATI LETTER HA;Lo;0;L;;;;;N;;;;; +0ABC;GUJARATI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;; +0ABD;GUJARATI SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;; +0ABE;GUJARATI VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +0ABF;GUJARATI VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +0AC0;GUJARATI VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +0AC1;GUJARATI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +0AC2;GUJARATI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +0AC3;GUJARATI VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;; +0AC4;GUJARATI VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;; +0AC5;GUJARATI VOWEL SIGN CANDRA E;Mn;0;NSM;;;;;N;;;;; +0AC7;GUJARATI VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +0AC8;GUJARATI VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +0AC9;GUJARATI VOWEL SIGN CANDRA O;Mc;0;L;;;;;N;;;;; +0ACB;GUJARATI VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +0ACC;GUJARATI VOWEL SIGN AU;Mc;0;L;;;;;N;;;;; +0ACD;GUJARATI SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +0AD0;GUJARATI OM;Lo;0;L;;;;;N;;;;; +0AE0;GUJARATI LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +0AE1;GUJARATI LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +0AE2;GUJARATI VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +0AE3;GUJARATI VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +0AE6;GUJARATI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0AE7;GUJARATI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0AE8;GUJARATI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0AE9;GUJARATI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0AEA;GUJARATI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0AEB;GUJARATI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0AEC;GUJARATI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0AED;GUJARATI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0AEE;GUJARATI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0AEF;GUJARATI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0AF0;GUJARATI ABBREVIATION SIGN;Po;0;L;;;;;N;;;;; +0AF1;GUJARATI RUPEE SIGN;Sc;0;ET;;;;;N;;;;; +0B01;ORIYA SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;; +0B02;ORIYA SIGN ANUSVARA;Mc;0;L;;;;;N;;;;; +0B03;ORIYA SIGN VISARGA;Mc;0;L;;;;;N;;;;; +0B05;ORIYA LETTER A;Lo;0;L;;;;;N;;;;; +0B06;ORIYA LETTER AA;Lo;0;L;;;;;N;;;;; +0B07;ORIYA LETTER I;Lo;0;L;;;;;N;;;;; +0B08;ORIYA LETTER II;Lo;0;L;;;;;N;;;;; +0B09;ORIYA LETTER U;Lo;0;L;;;;;N;;;;; +0B0A;ORIYA LETTER UU;Lo;0;L;;;;;N;;;;; +0B0B;ORIYA LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +0B0C;ORIYA LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +0B0F;ORIYA LETTER E;Lo;0;L;;;;;N;;;;; +0B10;ORIYA LETTER AI;Lo;0;L;;;;;N;;;;; +0B13;ORIYA LETTER O;Lo;0;L;;;;;N;;;;; +0B14;ORIYA LETTER AU;Lo;0;L;;;;;N;;;;; +0B15;ORIYA LETTER KA;Lo;0;L;;;;;N;;;;; +0B16;ORIYA LETTER KHA;Lo;0;L;;;;;N;;;;; +0B17;ORIYA LETTER GA;Lo;0;L;;;;;N;;;;; +0B18;ORIYA LETTER GHA;Lo;0;L;;;;;N;;;;; +0B19;ORIYA LETTER NGA;Lo;0;L;;;;;N;;;;; +0B1A;ORIYA LETTER CA;Lo;0;L;;;;;N;;;;; +0B1B;ORIYA LETTER CHA;Lo;0;L;;;;;N;;;;; +0B1C;ORIYA LETTER JA;Lo;0;L;;;;;N;;;;; +0B1D;ORIYA LETTER JHA;Lo;0;L;;;;;N;;;;; +0B1E;ORIYA LETTER NYA;Lo;0;L;;;;;N;;;;; +0B1F;ORIYA LETTER TTA;Lo;0;L;;;;;N;;;;; +0B20;ORIYA LETTER TTHA;Lo;0;L;;;;;N;;;;; +0B21;ORIYA LETTER DDA;Lo;0;L;;;;;N;;;;; +0B22;ORIYA LETTER DDHA;Lo;0;L;;;;;N;;;;; +0B23;ORIYA LETTER NNA;Lo;0;L;;;;;N;;;;; +0B24;ORIYA LETTER TA;Lo;0;L;;;;;N;;;;; +0B25;ORIYA LETTER THA;Lo;0;L;;;;;N;;;;; +0B26;ORIYA LETTER DA;Lo;0;L;;;;;N;;;;; +0B27;ORIYA LETTER DHA;Lo;0;L;;;;;N;;;;; +0B28;ORIYA LETTER NA;Lo;0;L;;;;;N;;;;; +0B2A;ORIYA LETTER PA;Lo;0;L;;;;;N;;;;; +0B2B;ORIYA LETTER PHA;Lo;0;L;;;;;N;;;;; +0B2C;ORIYA LETTER BA;Lo;0;L;;;;;N;;;;; +0B2D;ORIYA LETTER BHA;Lo;0;L;;;;;N;;;;; +0B2E;ORIYA LETTER MA;Lo;0;L;;;;;N;;;;; +0B2F;ORIYA LETTER YA;Lo;0;L;;;;;N;;;;; +0B30;ORIYA LETTER RA;Lo;0;L;;;;;N;;;;; +0B32;ORIYA LETTER LA;Lo;0;L;;;;;N;;;;; +0B33;ORIYA LETTER LLA;Lo;0;L;;;;;N;;;;; +0B35;ORIYA LETTER VA;Lo;0;L;;;;;N;;;;; +0B36;ORIYA LETTER SHA;Lo;0;L;;;;;N;;;;; +0B37;ORIYA LETTER SSA;Lo;0;L;;;;;N;;;;; +0B38;ORIYA LETTER SA;Lo;0;L;;;;;N;;;;; +0B39;ORIYA LETTER HA;Lo;0;L;;;;;N;;;;; +0B3C;ORIYA SIGN NUKTA;Mn;7;NSM;;;;;N;;;;; +0B3D;ORIYA SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;; +0B3E;ORIYA VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +0B3F;ORIYA VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +0B40;ORIYA VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +0B41;ORIYA VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +0B42;ORIYA VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +0B43;ORIYA VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;; +0B44;ORIYA VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;; +0B47;ORIYA VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +0B48;ORIYA VOWEL SIGN AI;Mc;0;L;0B47 0B56;;;;N;;;;; +0B4B;ORIYA VOWEL SIGN O;Mc;0;L;0B47 0B3E;;;;N;;;;; +0B4C;ORIYA VOWEL SIGN AU;Mc;0;L;0B47 0B57;;;;N;;;;; +0B4D;ORIYA SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +0B56;ORIYA AI LENGTH MARK;Mn;0;NSM;;;;;N;;;;; +0B57;ORIYA AU LENGTH MARK;Mc;0;L;;;;;N;;;;; +0B5C;ORIYA LETTER RRA;Lo;0;L;0B21 0B3C;;;;N;;;;; +0B5D;ORIYA LETTER RHA;Lo;0;L;0B22 0B3C;;;;N;;;;; +0B5F;ORIYA LETTER YYA;Lo;0;L;;;;;N;;;;; +0B60;ORIYA LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +0B61;ORIYA LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +0B62;ORIYA VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +0B63;ORIYA VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +0B66;ORIYA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0B67;ORIYA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0B68;ORIYA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0B69;ORIYA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0B6A;ORIYA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0B6B;ORIYA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0B6C;ORIYA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0B6D;ORIYA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0B6E;ORIYA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0B6F;ORIYA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0B70;ORIYA ISSHAR;So;0;L;;;;;N;;;;; +0B71;ORIYA LETTER WA;Lo;0;L;;;;;N;;;;; +0B72;ORIYA FRACTION ONE QUARTER;No;0;L;;;;1/4;N;;;;; +0B73;ORIYA FRACTION ONE HALF;No;0;L;;;;1/2;N;;;;; +0B74;ORIYA FRACTION THREE QUARTERS;No;0;L;;;;3/4;N;;;;; +0B75;ORIYA FRACTION ONE SIXTEENTH;No;0;L;;;;1/16;N;;;;; +0B76;ORIYA FRACTION ONE EIGHTH;No;0;L;;;;1/8;N;;;;; +0B77;ORIYA FRACTION THREE SIXTEENTHS;No;0;L;;;;3/16;N;;;;; +0B82;TAMIL SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +0B83;TAMIL SIGN VISARGA;Lo;0;L;;;;;N;;;;; +0B85;TAMIL LETTER A;Lo;0;L;;;;;N;;;;; +0B86;TAMIL LETTER AA;Lo;0;L;;;;;N;;;;; +0B87;TAMIL LETTER I;Lo;0;L;;;;;N;;;;; +0B88;TAMIL LETTER II;Lo;0;L;;;;;N;;;;; +0B89;TAMIL LETTER U;Lo;0;L;;;;;N;;;;; +0B8A;TAMIL LETTER UU;Lo;0;L;;;;;N;;;;; +0B8E;TAMIL LETTER E;Lo;0;L;;;;;N;;;;; +0B8F;TAMIL LETTER EE;Lo;0;L;;;;;N;;;;; +0B90;TAMIL LETTER AI;Lo;0;L;;;;;N;;;;; +0B92;TAMIL LETTER O;Lo;0;L;;;;;N;;;;; +0B93;TAMIL LETTER OO;Lo;0;L;;;;;N;;;;; +0B94;TAMIL LETTER AU;Lo;0;L;0B92 0BD7;;;;N;;;;; +0B95;TAMIL LETTER KA;Lo;0;L;;;;;N;;;;; +0B99;TAMIL LETTER NGA;Lo;0;L;;;;;N;;;;; +0B9A;TAMIL LETTER CA;Lo;0;L;;;;;N;;;;; +0B9C;TAMIL LETTER JA;Lo;0;L;;;;;N;;;;; +0B9E;TAMIL LETTER NYA;Lo;0;L;;;;;N;;;;; +0B9F;TAMIL LETTER TTA;Lo;0;L;;;;;N;;;;; +0BA3;TAMIL LETTER NNA;Lo;0;L;;;;;N;;;;; +0BA4;TAMIL LETTER TA;Lo;0;L;;;;;N;;;;; +0BA8;TAMIL LETTER NA;Lo;0;L;;;;;N;;;;; +0BA9;TAMIL LETTER NNNA;Lo;0;L;;;;;N;;;;; +0BAA;TAMIL LETTER PA;Lo;0;L;;;;;N;;;;; +0BAE;TAMIL LETTER MA;Lo;0;L;;;;;N;;;;; +0BAF;TAMIL LETTER YA;Lo;0;L;;;;;N;;;;; +0BB0;TAMIL LETTER RA;Lo;0;L;;;;;N;;;;; +0BB1;TAMIL LETTER RRA;Lo;0;L;;;;;N;;;;; +0BB2;TAMIL LETTER LA;Lo;0;L;;;;;N;;;;; +0BB3;TAMIL LETTER LLA;Lo;0;L;;;;;N;;;;; +0BB4;TAMIL LETTER LLLA;Lo;0;L;;;;;N;;;;; +0BB5;TAMIL LETTER VA;Lo;0;L;;;;;N;;;;; +0BB6;TAMIL LETTER SHA;Lo;0;L;;;;;N;;;;; +0BB7;TAMIL LETTER SSA;Lo;0;L;;;;;N;;;;; +0BB8;TAMIL LETTER SA;Lo;0;L;;;;;N;;;;; +0BB9;TAMIL LETTER HA;Lo;0;L;;;;;N;;;;; +0BBE;TAMIL VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +0BBF;TAMIL VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +0BC0;TAMIL VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;; +0BC1;TAMIL VOWEL SIGN U;Mc;0;L;;;;;N;;;;; +0BC2;TAMIL VOWEL SIGN UU;Mc;0;L;;;;;N;;;;; +0BC6;TAMIL VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +0BC7;TAMIL VOWEL SIGN EE;Mc;0;L;;;;;N;;;;; +0BC8;TAMIL VOWEL SIGN AI;Mc;0;L;;;;;N;;;;; +0BCA;TAMIL VOWEL SIGN O;Mc;0;L;0BC6 0BBE;;;;N;;;;; +0BCB;TAMIL VOWEL SIGN OO;Mc;0;L;0BC7 0BBE;;;;N;;;;; +0BCC;TAMIL VOWEL SIGN AU;Mc;0;L;0BC6 0BD7;;;;N;;;;; +0BCD;TAMIL SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +0BD0;TAMIL OM;Lo;0;L;;;;;N;;;;; +0BD7;TAMIL AU LENGTH MARK;Mc;0;L;;;;;N;;;;; +0BE6;TAMIL DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0BE7;TAMIL DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0BE8;TAMIL DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0BE9;TAMIL DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0BEA;TAMIL DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0BEB;TAMIL DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0BEC;TAMIL DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0BED;TAMIL DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0BEE;TAMIL DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0BEF;TAMIL DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0BF0;TAMIL NUMBER TEN;No;0;L;;;;10;N;;;;; +0BF1;TAMIL NUMBER ONE HUNDRED;No;0;L;;;;100;N;;;;; +0BF2;TAMIL NUMBER ONE THOUSAND;No;0;L;;;;1000;N;;;;; +0BF3;TAMIL DAY SIGN;So;0;ON;;;;;N;;;;; +0BF4;TAMIL MONTH SIGN;So;0;ON;;;;;N;;;;; +0BF5;TAMIL YEAR SIGN;So;0;ON;;;;;N;;;;; +0BF6;TAMIL DEBIT SIGN;So;0;ON;;;;;N;;;;; +0BF7;TAMIL CREDIT SIGN;So;0;ON;;;;;N;;;;; +0BF8;TAMIL AS ABOVE SIGN;So;0;ON;;;;;N;;;;; +0BF9;TAMIL RUPEE SIGN;Sc;0;ET;;;;;N;;;;; +0BFA;TAMIL NUMBER SIGN;So;0;ON;;;;;N;;;;; +0C01;TELUGU SIGN CANDRABINDU;Mc;0;L;;;;;N;;;;; +0C02;TELUGU SIGN ANUSVARA;Mc;0;L;;;;;N;;;;; +0C03;TELUGU SIGN VISARGA;Mc;0;L;;;;;N;;;;; +0C05;TELUGU LETTER A;Lo;0;L;;;;;N;;;;; +0C06;TELUGU LETTER AA;Lo;0;L;;;;;N;;;;; +0C07;TELUGU LETTER I;Lo;0;L;;;;;N;;;;; +0C08;TELUGU LETTER II;Lo;0;L;;;;;N;;;;; +0C09;TELUGU LETTER U;Lo;0;L;;;;;N;;;;; +0C0A;TELUGU LETTER UU;Lo;0;L;;;;;N;;;;; +0C0B;TELUGU LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +0C0C;TELUGU LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +0C0E;TELUGU LETTER E;Lo;0;L;;;;;N;;;;; +0C0F;TELUGU LETTER EE;Lo;0;L;;;;;N;;;;; +0C10;TELUGU LETTER AI;Lo;0;L;;;;;N;;;;; +0C12;TELUGU LETTER O;Lo;0;L;;;;;N;;;;; +0C13;TELUGU LETTER OO;Lo;0;L;;;;;N;;;;; +0C14;TELUGU LETTER AU;Lo;0;L;;;;;N;;;;; +0C15;TELUGU LETTER KA;Lo;0;L;;;;;N;;;;; +0C16;TELUGU LETTER KHA;Lo;0;L;;;;;N;;;;; +0C17;TELUGU LETTER GA;Lo;0;L;;;;;N;;;;; +0C18;TELUGU LETTER GHA;Lo;0;L;;;;;N;;;;; +0C19;TELUGU LETTER NGA;Lo;0;L;;;;;N;;;;; +0C1A;TELUGU LETTER CA;Lo;0;L;;;;;N;;;;; +0C1B;TELUGU LETTER CHA;Lo;0;L;;;;;N;;;;; +0C1C;TELUGU LETTER JA;Lo;0;L;;;;;N;;;;; +0C1D;TELUGU LETTER JHA;Lo;0;L;;;;;N;;;;; +0C1E;TELUGU LETTER NYA;Lo;0;L;;;;;N;;;;; +0C1F;TELUGU LETTER TTA;Lo;0;L;;;;;N;;;;; +0C20;TELUGU LETTER TTHA;Lo;0;L;;;;;N;;;;; +0C21;TELUGU LETTER DDA;Lo;0;L;;;;;N;;;;; +0C22;TELUGU LETTER DDHA;Lo;0;L;;;;;N;;;;; +0C23;TELUGU LETTER NNA;Lo;0;L;;;;;N;;;;; +0C24;TELUGU LETTER TA;Lo;0;L;;;;;N;;;;; +0C25;TELUGU LETTER THA;Lo;0;L;;;;;N;;;;; +0C26;TELUGU LETTER DA;Lo;0;L;;;;;N;;;;; +0C27;TELUGU LETTER DHA;Lo;0;L;;;;;N;;;;; +0C28;TELUGU LETTER NA;Lo;0;L;;;;;N;;;;; +0C2A;TELUGU LETTER PA;Lo;0;L;;;;;N;;;;; +0C2B;TELUGU LETTER PHA;Lo;0;L;;;;;N;;;;; +0C2C;TELUGU LETTER BA;Lo;0;L;;;;;N;;;;; +0C2D;TELUGU LETTER BHA;Lo;0;L;;;;;N;;;;; +0C2E;TELUGU LETTER MA;Lo;0;L;;;;;N;;;;; +0C2F;TELUGU LETTER YA;Lo;0;L;;;;;N;;;;; +0C30;TELUGU LETTER RA;Lo;0;L;;;;;N;;;;; +0C31;TELUGU LETTER RRA;Lo;0;L;;;;;N;;;;; +0C32;TELUGU LETTER LA;Lo;0;L;;;;;N;;;;; +0C33;TELUGU LETTER LLA;Lo;0;L;;;;;N;;;;; +0C35;TELUGU LETTER VA;Lo;0;L;;;;;N;;;;; +0C36;TELUGU LETTER SHA;Lo;0;L;;;;;N;;;;; +0C37;TELUGU LETTER SSA;Lo;0;L;;;;;N;;;;; +0C38;TELUGU LETTER SA;Lo;0;L;;;;;N;;;;; +0C39;TELUGU LETTER HA;Lo;0;L;;;;;N;;;;; +0C3D;TELUGU SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;; +0C3E;TELUGU VOWEL SIGN AA;Mn;0;NSM;;;;;N;;;;; +0C3F;TELUGU VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +0C40;TELUGU VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;; +0C41;TELUGU VOWEL SIGN U;Mc;0;L;;;;;N;;;;; +0C42;TELUGU VOWEL SIGN UU;Mc;0;L;;;;;N;;;;; +0C43;TELUGU VOWEL SIGN VOCALIC R;Mc;0;L;;;;;N;;;;; +0C44;TELUGU VOWEL SIGN VOCALIC RR;Mc;0;L;;;;;N;;;;; +0C46;TELUGU VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +0C47;TELUGU VOWEL SIGN EE;Mn;0;NSM;;;;;N;;;;; +0C48;TELUGU VOWEL SIGN AI;Mn;0;NSM;0C46 0C56;;;;N;;;;; +0C4A;TELUGU VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;; +0C4B;TELUGU VOWEL SIGN OO;Mn;0;NSM;;;;;N;;;;; +0C4C;TELUGU VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;; +0C4D;TELUGU SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +0C55;TELUGU LENGTH MARK;Mn;84;NSM;;;;;N;;;;; +0C56;TELUGU AI LENGTH MARK;Mn;91;NSM;;;;;N;;;;; +0C58;TELUGU LETTER TSA;Lo;0;L;;;;;N;;;;; +0C59;TELUGU LETTER DZA;Lo;0;L;;;;;N;;;;; +0C60;TELUGU LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +0C61;TELUGU LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +0C62;TELUGU VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +0C63;TELUGU VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +0C66;TELUGU DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0C67;TELUGU DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0C68;TELUGU DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0C69;TELUGU DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0C6A;TELUGU DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0C6B;TELUGU DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0C6C;TELUGU DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0C6D;TELUGU DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0C6E;TELUGU DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0C6F;TELUGU DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0C78;TELUGU FRACTION DIGIT ZERO FOR ODD POWERS OF FOUR;No;0;ON;;;;0;N;;;;; +0C79;TELUGU FRACTION DIGIT ONE FOR ODD POWERS OF FOUR;No;0;ON;;;;1;N;;;;; +0C7A;TELUGU FRACTION DIGIT TWO FOR ODD POWERS OF FOUR;No;0;ON;;;;2;N;;;;; +0C7B;TELUGU FRACTION DIGIT THREE FOR ODD POWERS OF FOUR;No;0;ON;;;;3;N;;;;; +0C7C;TELUGU FRACTION DIGIT ONE FOR EVEN POWERS OF FOUR;No;0;ON;;;;1;N;;;;; +0C7D;TELUGU FRACTION DIGIT TWO FOR EVEN POWERS OF FOUR;No;0;ON;;;;2;N;;;;; +0C7E;TELUGU FRACTION DIGIT THREE FOR EVEN POWERS OF FOUR;No;0;ON;;;;3;N;;;;; +0C7F;TELUGU SIGN TUUMU;So;0;L;;;;;N;;;;; +0C82;KANNADA SIGN ANUSVARA;Mc;0;L;;;;;N;;;;; +0C83;KANNADA SIGN VISARGA;Mc;0;L;;;;;N;;;;; +0C85;KANNADA LETTER A;Lo;0;L;;;;;N;;;;; +0C86;KANNADA LETTER AA;Lo;0;L;;;;;N;;;;; +0C87;KANNADA LETTER I;Lo;0;L;;;;;N;;;;; +0C88;KANNADA LETTER II;Lo;0;L;;;;;N;;;;; +0C89;KANNADA LETTER U;Lo;0;L;;;;;N;;;;; +0C8A;KANNADA LETTER UU;Lo;0;L;;;;;N;;;;; +0C8B;KANNADA LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +0C8C;KANNADA LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +0C8E;KANNADA LETTER E;Lo;0;L;;;;;N;;;;; +0C8F;KANNADA LETTER EE;Lo;0;L;;;;;N;;;;; +0C90;KANNADA LETTER AI;Lo;0;L;;;;;N;;;;; +0C92;KANNADA LETTER O;Lo;0;L;;;;;N;;;;; +0C93;KANNADA LETTER OO;Lo;0;L;;;;;N;;;;; +0C94;KANNADA LETTER AU;Lo;0;L;;;;;N;;;;; +0C95;KANNADA LETTER KA;Lo;0;L;;;;;N;;;;; +0C96;KANNADA LETTER KHA;Lo;0;L;;;;;N;;;;; +0C97;KANNADA LETTER GA;Lo;0;L;;;;;N;;;;; +0C98;KANNADA LETTER GHA;Lo;0;L;;;;;N;;;;; +0C99;KANNADA LETTER NGA;Lo;0;L;;;;;N;;;;; +0C9A;KANNADA LETTER CA;Lo;0;L;;;;;N;;;;; +0C9B;KANNADA LETTER CHA;Lo;0;L;;;;;N;;;;; +0C9C;KANNADA LETTER JA;Lo;0;L;;;;;N;;;;; +0C9D;KANNADA LETTER JHA;Lo;0;L;;;;;N;;;;; +0C9E;KANNADA LETTER NYA;Lo;0;L;;;;;N;;;;; +0C9F;KANNADA LETTER TTA;Lo;0;L;;;;;N;;;;; +0CA0;KANNADA LETTER TTHA;Lo;0;L;;;;;N;;;;; +0CA1;KANNADA LETTER DDA;Lo;0;L;;;;;N;;;;; +0CA2;KANNADA LETTER DDHA;Lo;0;L;;;;;N;;;;; +0CA3;KANNADA LETTER NNA;Lo;0;L;;;;;N;;;;; +0CA4;KANNADA LETTER TA;Lo;0;L;;;;;N;;;;; +0CA5;KANNADA LETTER THA;Lo;0;L;;;;;N;;;;; +0CA6;KANNADA LETTER DA;Lo;0;L;;;;;N;;;;; +0CA7;KANNADA LETTER DHA;Lo;0;L;;;;;N;;;;; +0CA8;KANNADA LETTER NA;Lo;0;L;;;;;N;;;;; +0CAA;KANNADA LETTER PA;Lo;0;L;;;;;N;;;;; +0CAB;KANNADA LETTER PHA;Lo;0;L;;;;;N;;;;; +0CAC;KANNADA LETTER BA;Lo;0;L;;;;;N;;;;; +0CAD;KANNADA LETTER BHA;Lo;0;L;;;;;N;;;;; +0CAE;KANNADA LETTER MA;Lo;0;L;;;;;N;;;;; +0CAF;KANNADA LETTER YA;Lo;0;L;;;;;N;;;;; +0CB0;KANNADA LETTER RA;Lo;0;L;;;;;N;;;;; +0CB1;KANNADA LETTER RRA;Lo;0;L;;;;;N;;;;; +0CB2;KANNADA LETTER LA;Lo;0;L;;;;;N;;;;; +0CB3;KANNADA LETTER LLA;Lo;0;L;;;;;N;;;;; +0CB5;KANNADA LETTER VA;Lo;0;L;;;;;N;;;;; +0CB6;KANNADA LETTER SHA;Lo;0;L;;;;;N;;;;; +0CB7;KANNADA LETTER SSA;Lo;0;L;;;;;N;;;;; +0CB8;KANNADA LETTER SA;Lo;0;L;;;;;N;;;;; +0CB9;KANNADA LETTER HA;Lo;0;L;;;;;N;;;;; +0CBC;KANNADA SIGN NUKTA;Mn;7;NSM;;;;;N;;;;; +0CBD;KANNADA SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;; +0CBE;KANNADA VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +0CBF;KANNADA VOWEL SIGN I;Mn;0;L;;;;;N;;;;; +0CC0;KANNADA VOWEL SIGN II;Mc;0;L;0CBF 0CD5;;;;N;;;;; +0CC1;KANNADA VOWEL SIGN U;Mc;0;L;;;;;N;;;;; +0CC2;KANNADA VOWEL SIGN UU;Mc;0;L;;;;;N;;;;; +0CC3;KANNADA VOWEL SIGN VOCALIC R;Mc;0;L;;;;;N;;;;; +0CC4;KANNADA VOWEL SIGN VOCALIC RR;Mc;0;L;;;;;N;;;;; +0CC6;KANNADA VOWEL SIGN E;Mn;0;L;;;;;N;;;;; +0CC7;KANNADA VOWEL SIGN EE;Mc;0;L;0CC6 0CD5;;;;N;;;;; +0CC8;KANNADA VOWEL SIGN AI;Mc;0;L;0CC6 0CD6;;;;N;;;;; +0CCA;KANNADA VOWEL SIGN O;Mc;0;L;0CC6 0CC2;;;;N;;;;; +0CCB;KANNADA VOWEL SIGN OO;Mc;0;L;0CCA 0CD5;;;;N;;;;; +0CCC;KANNADA VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;; +0CCD;KANNADA SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +0CD5;KANNADA LENGTH MARK;Mc;0;L;;;;;N;;;;; +0CD6;KANNADA AI LENGTH MARK;Mc;0;L;;;;;N;;;;; +0CDE;KANNADA LETTER FA;Lo;0;L;;;;;N;;;;; +0CE0;KANNADA LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +0CE1;KANNADA LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +0CE2;KANNADA VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +0CE3;KANNADA VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +0CE6;KANNADA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0CE7;KANNADA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0CE8;KANNADA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0CE9;KANNADA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0CEA;KANNADA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0CEB;KANNADA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0CEC;KANNADA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0CED;KANNADA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0CEE;KANNADA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0CEF;KANNADA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0CF1;KANNADA SIGN JIHVAMULIYA;Lo;0;L;;;;;N;;;;; +0CF2;KANNADA SIGN UPADHMANIYA;Lo;0;L;;;;;N;;;;; +0D02;MALAYALAM SIGN ANUSVARA;Mc;0;L;;;;;N;;;;; +0D03;MALAYALAM SIGN VISARGA;Mc;0;L;;;;;N;;;;; +0D05;MALAYALAM LETTER A;Lo;0;L;;;;;N;;;;; +0D06;MALAYALAM LETTER AA;Lo;0;L;;;;;N;;;;; +0D07;MALAYALAM LETTER I;Lo;0;L;;;;;N;;;;; +0D08;MALAYALAM LETTER II;Lo;0;L;;;;;N;;;;; +0D09;MALAYALAM LETTER U;Lo;0;L;;;;;N;;;;; +0D0A;MALAYALAM LETTER UU;Lo;0;L;;;;;N;;;;; +0D0B;MALAYALAM LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +0D0C;MALAYALAM LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +0D0E;MALAYALAM LETTER E;Lo;0;L;;;;;N;;;;; +0D0F;MALAYALAM LETTER EE;Lo;0;L;;;;;N;;;;; +0D10;MALAYALAM LETTER AI;Lo;0;L;;;;;N;;;;; +0D12;MALAYALAM LETTER O;Lo;0;L;;;;;N;;;;; +0D13;MALAYALAM LETTER OO;Lo;0;L;;;;;N;;;;; +0D14;MALAYALAM LETTER AU;Lo;0;L;;;;;N;;;;; +0D15;MALAYALAM LETTER KA;Lo;0;L;;;;;N;;;;; +0D16;MALAYALAM LETTER KHA;Lo;0;L;;;;;N;;;;; +0D17;MALAYALAM LETTER GA;Lo;0;L;;;;;N;;;;; +0D18;MALAYALAM LETTER GHA;Lo;0;L;;;;;N;;;;; +0D19;MALAYALAM LETTER NGA;Lo;0;L;;;;;N;;;;; +0D1A;MALAYALAM LETTER CA;Lo;0;L;;;;;N;;;;; +0D1B;MALAYALAM LETTER CHA;Lo;0;L;;;;;N;;;;; +0D1C;MALAYALAM LETTER JA;Lo;0;L;;;;;N;;;;; +0D1D;MALAYALAM LETTER JHA;Lo;0;L;;;;;N;;;;; +0D1E;MALAYALAM LETTER NYA;Lo;0;L;;;;;N;;;;; +0D1F;MALAYALAM LETTER TTA;Lo;0;L;;;;;N;;;;; +0D20;MALAYALAM LETTER TTHA;Lo;0;L;;;;;N;;;;; +0D21;MALAYALAM LETTER DDA;Lo;0;L;;;;;N;;;;; +0D22;MALAYALAM LETTER DDHA;Lo;0;L;;;;;N;;;;; +0D23;MALAYALAM LETTER NNA;Lo;0;L;;;;;N;;;;; +0D24;MALAYALAM LETTER TA;Lo;0;L;;;;;N;;;;; +0D25;MALAYALAM LETTER THA;Lo;0;L;;;;;N;;;;; +0D26;MALAYALAM LETTER DA;Lo;0;L;;;;;N;;;;; +0D27;MALAYALAM LETTER DHA;Lo;0;L;;;;;N;;;;; +0D28;MALAYALAM LETTER NA;Lo;0;L;;;;;N;;;;; +0D29;MALAYALAM LETTER NNNA;Lo;0;L;;;;;N;;;;; +0D2A;MALAYALAM LETTER PA;Lo;0;L;;;;;N;;;;; +0D2B;MALAYALAM LETTER PHA;Lo;0;L;;;;;N;;;;; +0D2C;MALAYALAM LETTER BA;Lo;0;L;;;;;N;;;;; +0D2D;MALAYALAM LETTER BHA;Lo;0;L;;;;;N;;;;; +0D2E;MALAYALAM LETTER MA;Lo;0;L;;;;;N;;;;; +0D2F;MALAYALAM LETTER YA;Lo;0;L;;;;;N;;;;; +0D30;MALAYALAM LETTER RA;Lo;0;L;;;;;N;;;;; +0D31;MALAYALAM LETTER RRA;Lo;0;L;;;;;N;;;;; +0D32;MALAYALAM LETTER LA;Lo;0;L;;;;;N;;;;; +0D33;MALAYALAM LETTER LLA;Lo;0;L;;;;;N;;;;; +0D34;MALAYALAM LETTER LLLA;Lo;0;L;;;;;N;;;;; +0D35;MALAYALAM LETTER VA;Lo;0;L;;;;;N;;;;; +0D36;MALAYALAM LETTER SHA;Lo;0;L;;;;;N;;;;; +0D37;MALAYALAM LETTER SSA;Lo;0;L;;;;;N;;;;; +0D38;MALAYALAM LETTER SA;Lo;0;L;;;;;N;;;;; +0D39;MALAYALAM LETTER HA;Lo;0;L;;;;;N;;;;; +0D3A;MALAYALAM LETTER TTTA;Lo;0;L;;;;;N;;;;; +0D3D;MALAYALAM SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;; +0D3E;MALAYALAM VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +0D3F;MALAYALAM VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +0D40;MALAYALAM VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +0D41;MALAYALAM VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +0D42;MALAYALAM VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +0D43;MALAYALAM VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;; +0D44;MALAYALAM VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;; +0D46;MALAYALAM VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +0D47;MALAYALAM VOWEL SIGN EE;Mc;0;L;;;;;N;;;;; +0D48;MALAYALAM VOWEL SIGN AI;Mc;0;L;;;;;N;;;;; +0D4A;MALAYALAM VOWEL SIGN O;Mc;0;L;0D46 0D3E;;;;N;;;;; +0D4B;MALAYALAM VOWEL SIGN OO;Mc;0;L;0D47 0D3E;;;;N;;;;; +0D4C;MALAYALAM VOWEL SIGN AU;Mc;0;L;0D46 0D57;;;;N;;;;; +0D4D;MALAYALAM SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +0D4E;MALAYALAM LETTER DOT REPH;Lo;0;L;;;;;N;;;;; +0D57;MALAYALAM AU LENGTH MARK;Mc;0;L;;;;;N;;;;; +0D60;MALAYALAM LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +0D61;MALAYALAM LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +0D62;MALAYALAM VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +0D63;MALAYALAM VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +0D66;MALAYALAM DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0D67;MALAYALAM DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0D68;MALAYALAM DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0D69;MALAYALAM DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0D6A;MALAYALAM DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0D6B;MALAYALAM DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0D6C;MALAYALAM DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0D6D;MALAYALAM DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0D6E;MALAYALAM DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0D6F;MALAYALAM DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0D70;MALAYALAM NUMBER TEN;No;0;L;;;;10;N;;;;; +0D71;MALAYALAM NUMBER ONE HUNDRED;No;0;L;;;;100;N;;;;; +0D72;MALAYALAM NUMBER ONE THOUSAND;No;0;L;;;;1000;N;;;;; +0D73;MALAYALAM FRACTION ONE QUARTER;No;0;L;;;;1/4;N;;;;; +0D74;MALAYALAM FRACTION ONE HALF;No;0;L;;;;1/2;N;;;;; +0D75;MALAYALAM FRACTION THREE QUARTERS;No;0;L;;;;3/4;N;;;;; +0D79;MALAYALAM DATE MARK;So;0;L;;;;;N;;;;; +0D7A;MALAYALAM LETTER CHILLU NN;Lo;0;L;;;;;N;;;;; +0D7B;MALAYALAM LETTER CHILLU N;Lo;0;L;;;;;N;;;;; +0D7C;MALAYALAM LETTER CHILLU RR;Lo;0;L;;;;;N;;;;; +0D7D;MALAYALAM LETTER CHILLU L;Lo;0;L;;;;;N;;;;; +0D7E;MALAYALAM LETTER CHILLU LL;Lo;0;L;;;;;N;;;;; +0D7F;MALAYALAM LETTER CHILLU K;Lo;0;L;;;;;N;;;;; +0D82;SINHALA SIGN ANUSVARAYA;Mc;0;L;;;;;N;;;;; +0D83;SINHALA SIGN VISARGAYA;Mc;0;L;;;;;N;;;;; +0D85;SINHALA LETTER AYANNA;Lo;0;L;;;;;N;;;;; +0D86;SINHALA LETTER AAYANNA;Lo;0;L;;;;;N;;;;; +0D87;SINHALA LETTER AEYANNA;Lo;0;L;;;;;N;;;;; +0D88;SINHALA LETTER AEEYANNA;Lo;0;L;;;;;N;;;;; +0D89;SINHALA LETTER IYANNA;Lo;0;L;;;;;N;;;;; +0D8A;SINHALA LETTER IIYANNA;Lo;0;L;;;;;N;;;;; +0D8B;SINHALA LETTER UYANNA;Lo;0;L;;;;;N;;;;; +0D8C;SINHALA LETTER UUYANNA;Lo;0;L;;;;;N;;;;; +0D8D;SINHALA LETTER IRUYANNA;Lo;0;L;;;;;N;;;;; +0D8E;SINHALA LETTER IRUUYANNA;Lo;0;L;;;;;N;;;;; +0D8F;SINHALA LETTER ILUYANNA;Lo;0;L;;;;;N;;;;; +0D90;SINHALA LETTER ILUUYANNA;Lo;0;L;;;;;N;;;;; +0D91;SINHALA LETTER EYANNA;Lo;0;L;;;;;N;;;;; +0D92;SINHALA LETTER EEYANNA;Lo;0;L;;;;;N;;;;; +0D93;SINHALA LETTER AIYANNA;Lo;0;L;;;;;N;;;;; +0D94;SINHALA LETTER OYANNA;Lo;0;L;;;;;N;;;;; +0D95;SINHALA LETTER OOYANNA;Lo;0;L;;;;;N;;;;; +0D96;SINHALA LETTER AUYANNA;Lo;0;L;;;;;N;;;;; +0D9A;SINHALA LETTER ALPAPRAANA KAYANNA;Lo;0;L;;;;;N;;;;; +0D9B;SINHALA LETTER MAHAAPRAANA KAYANNA;Lo;0;L;;;;;N;;;;; +0D9C;SINHALA LETTER ALPAPRAANA GAYANNA;Lo;0;L;;;;;N;;;;; +0D9D;SINHALA LETTER MAHAAPRAANA GAYANNA;Lo;0;L;;;;;N;;;;; +0D9E;SINHALA LETTER KANTAJA NAASIKYAYA;Lo;0;L;;;;;N;;;;; +0D9F;SINHALA LETTER SANYAKA GAYANNA;Lo;0;L;;;;;N;;;;; +0DA0;SINHALA LETTER ALPAPRAANA CAYANNA;Lo;0;L;;;;;N;;;;; +0DA1;SINHALA LETTER MAHAAPRAANA CAYANNA;Lo;0;L;;;;;N;;;;; +0DA2;SINHALA LETTER ALPAPRAANA JAYANNA;Lo;0;L;;;;;N;;;;; +0DA3;SINHALA LETTER MAHAAPRAANA JAYANNA;Lo;0;L;;;;;N;;;;; +0DA4;SINHALA LETTER TAALUJA NAASIKYAYA;Lo;0;L;;;;;N;;;;; +0DA5;SINHALA LETTER TAALUJA SANYOOGA NAAKSIKYAYA;Lo;0;L;;;;;N;;;;; +0DA6;SINHALA LETTER SANYAKA JAYANNA;Lo;0;L;;;;;N;;;;; +0DA7;SINHALA LETTER ALPAPRAANA TTAYANNA;Lo;0;L;;;;;N;;;;; +0DA8;SINHALA LETTER MAHAAPRAANA TTAYANNA;Lo;0;L;;;;;N;;;;; +0DA9;SINHALA LETTER ALPAPRAANA DDAYANNA;Lo;0;L;;;;;N;;;;; +0DAA;SINHALA LETTER MAHAAPRAANA DDAYANNA;Lo;0;L;;;;;N;;;;; +0DAB;SINHALA LETTER MUURDHAJA NAYANNA;Lo;0;L;;;;;N;;;;; +0DAC;SINHALA LETTER SANYAKA DDAYANNA;Lo;0;L;;;;;N;;;;; +0DAD;SINHALA LETTER ALPAPRAANA TAYANNA;Lo;0;L;;;;;N;;;;; +0DAE;SINHALA LETTER MAHAAPRAANA TAYANNA;Lo;0;L;;;;;N;;;;; +0DAF;SINHALA LETTER ALPAPRAANA DAYANNA;Lo;0;L;;;;;N;;;;; +0DB0;SINHALA LETTER MAHAAPRAANA DAYANNA;Lo;0;L;;;;;N;;;;; +0DB1;SINHALA LETTER DANTAJA NAYANNA;Lo;0;L;;;;;N;;;;; +0DB3;SINHALA LETTER SANYAKA DAYANNA;Lo;0;L;;;;;N;;;;; +0DB4;SINHALA LETTER ALPAPRAANA PAYANNA;Lo;0;L;;;;;N;;;;; +0DB5;SINHALA LETTER MAHAAPRAANA PAYANNA;Lo;0;L;;;;;N;;;;; +0DB6;SINHALA LETTER ALPAPRAANA BAYANNA;Lo;0;L;;;;;N;;;;; +0DB7;SINHALA LETTER MAHAAPRAANA BAYANNA;Lo;0;L;;;;;N;;;;; +0DB8;SINHALA LETTER MAYANNA;Lo;0;L;;;;;N;;;;; +0DB9;SINHALA LETTER AMBA BAYANNA;Lo;0;L;;;;;N;;;;; +0DBA;SINHALA LETTER YAYANNA;Lo;0;L;;;;;N;;;;; +0DBB;SINHALA LETTER RAYANNA;Lo;0;L;;;;;N;;;;; +0DBD;SINHALA LETTER DANTAJA LAYANNA;Lo;0;L;;;;;N;;;;; +0DC0;SINHALA LETTER VAYANNA;Lo;0;L;;;;;N;;;;; +0DC1;SINHALA LETTER TAALUJA SAYANNA;Lo;0;L;;;;;N;;;;; +0DC2;SINHALA LETTER MUURDHAJA SAYANNA;Lo;0;L;;;;;N;;;;; +0DC3;SINHALA LETTER DANTAJA SAYANNA;Lo;0;L;;;;;N;;;;; +0DC4;SINHALA LETTER HAYANNA;Lo;0;L;;;;;N;;;;; +0DC5;SINHALA LETTER MUURDHAJA LAYANNA;Lo;0;L;;;;;N;;;;; +0DC6;SINHALA LETTER FAYANNA;Lo;0;L;;;;;N;;;;; +0DCA;SINHALA SIGN AL-LAKUNA;Mn;9;NSM;;;;;N;;;;; +0DCF;SINHALA VOWEL SIGN AELA-PILLA;Mc;0;L;;;;;N;;;;; +0DD0;SINHALA VOWEL SIGN KETTI AEDA-PILLA;Mc;0;L;;;;;N;;;;; +0DD1;SINHALA VOWEL SIGN DIGA AEDA-PILLA;Mc;0;L;;;;;N;;;;; +0DD2;SINHALA VOWEL SIGN KETTI IS-PILLA;Mn;0;NSM;;;;;N;;;;; +0DD3;SINHALA VOWEL SIGN DIGA IS-PILLA;Mn;0;NSM;;;;;N;;;;; +0DD4;SINHALA VOWEL SIGN KETTI PAA-PILLA;Mn;0;NSM;;;;;N;;;;; +0DD6;SINHALA VOWEL SIGN DIGA PAA-PILLA;Mn;0;NSM;;;;;N;;;;; +0DD8;SINHALA VOWEL SIGN GAETTA-PILLA;Mc;0;L;;;;;N;;;;; +0DD9;SINHALA VOWEL SIGN KOMBUVA;Mc;0;L;;;;;N;;;;; +0DDA;SINHALA VOWEL SIGN DIGA KOMBUVA;Mc;0;L;0DD9 0DCA;;;;N;;;;; +0DDB;SINHALA VOWEL SIGN KOMBU DEKA;Mc;0;L;;;;;N;;;;; +0DDC;SINHALA VOWEL SIGN KOMBUVA HAA AELA-PILLA;Mc;0;L;0DD9 0DCF;;;;N;;;;; +0DDD;SINHALA VOWEL SIGN KOMBUVA HAA DIGA AELA-PILLA;Mc;0;L;0DDC 0DCA;;;;N;;;;; +0DDE;SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA;Mc;0;L;0DD9 0DDF;;;;N;;;;; +0DDF;SINHALA VOWEL SIGN GAYANUKITTA;Mc;0;L;;;;;N;;;;; +0DF2;SINHALA VOWEL SIGN DIGA GAETTA-PILLA;Mc;0;L;;;;;N;;;;; +0DF3;SINHALA VOWEL SIGN DIGA GAYANUKITTA;Mc;0;L;;;;;N;;;;; +0DF4;SINHALA PUNCTUATION KUNDDALIYA;Po;0;L;;;;;N;;;;; +0E01;THAI CHARACTER KO KAI;Lo;0;L;;;;;N;THAI LETTER KO KAI;;;; +0E02;THAI CHARACTER KHO KHAI;Lo;0;L;;;;;N;THAI LETTER KHO KHAI;;;; +0E03;THAI CHARACTER KHO KHUAT;Lo;0;L;;;;;N;THAI LETTER KHO KHUAT;;;; +0E04;THAI CHARACTER KHO KHWAI;Lo;0;L;;;;;N;THAI LETTER KHO KHWAI;;;; +0E05;THAI CHARACTER KHO KHON;Lo;0;L;;;;;N;THAI LETTER KHO KHON;;;; +0E06;THAI CHARACTER KHO RAKHANG;Lo;0;L;;;;;N;THAI LETTER KHO RAKHANG;;;; +0E07;THAI CHARACTER NGO NGU;Lo;0;L;;;;;N;THAI LETTER NGO NGU;;;; +0E08;THAI CHARACTER CHO CHAN;Lo;0;L;;;;;N;THAI LETTER CHO CHAN;;;; +0E09;THAI CHARACTER CHO CHING;Lo;0;L;;;;;N;THAI LETTER CHO CHING;;;; +0E0A;THAI CHARACTER CHO CHANG;Lo;0;L;;;;;N;THAI LETTER CHO CHANG;;;; +0E0B;THAI CHARACTER SO SO;Lo;0;L;;;;;N;THAI LETTER SO SO;;;; +0E0C;THAI CHARACTER CHO CHOE;Lo;0;L;;;;;N;THAI LETTER CHO CHOE;;;; +0E0D;THAI CHARACTER YO YING;Lo;0;L;;;;;N;THAI LETTER YO YING;;;; +0E0E;THAI CHARACTER DO CHADA;Lo;0;L;;;;;N;THAI LETTER DO CHADA;;;; +0E0F;THAI CHARACTER TO PATAK;Lo;0;L;;;;;N;THAI LETTER TO PATAK;;;; +0E10;THAI CHARACTER THO THAN;Lo;0;L;;;;;N;THAI LETTER THO THAN;;;; +0E11;THAI CHARACTER THO NANGMONTHO;Lo;0;L;;;;;N;THAI LETTER THO NANGMONTHO;;;; +0E12;THAI CHARACTER THO PHUTHAO;Lo;0;L;;;;;N;THAI LETTER THO PHUTHAO;;;; +0E13;THAI CHARACTER NO NEN;Lo;0;L;;;;;N;THAI LETTER NO NEN;;;; +0E14;THAI CHARACTER DO DEK;Lo;0;L;;;;;N;THAI LETTER DO DEK;;;; +0E15;THAI CHARACTER TO TAO;Lo;0;L;;;;;N;THAI LETTER TO TAO;;;; +0E16;THAI CHARACTER THO THUNG;Lo;0;L;;;;;N;THAI LETTER THO THUNG;;;; +0E17;THAI CHARACTER THO THAHAN;Lo;0;L;;;;;N;THAI LETTER THO THAHAN;;;; +0E18;THAI CHARACTER THO THONG;Lo;0;L;;;;;N;THAI LETTER THO THONG;;;; +0E19;THAI CHARACTER NO NU;Lo;0;L;;;;;N;THAI LETTER NO NU;;;; +0E1A;THAI CHARACTER BO BAIMAI;Lo;0;L;;;;;N;THAI LETTER BO BAIMAI;;;; +0E1B;THAI CHARACTER PO PLA;Lo;0;L;;;;;N;THAI LETTER PO PLA;;;; +0E1C;THAI CHARACTER PHO PHUNG;Lo;0;L;;;;;N;THAI LETTER PHO PHUNG;;;; +0E1D;THAI CHARACTER FO FA;Lo;0;L;;;;;N;THAI LETTER FO FA;;;; +0E1E;THAI CHARACTER PHO PHAN;Lo;0;L;;;;;N;THAI LETTER PHO PHAN;;;; +0E1F;THAI CHARACTER FO FAN;Lo;0;L;;;;;N;THAI LETTER FO FAN;;;; +0E20;THAI CHARACTER PHO SAMPHAO;Lo;0;L;;;;;N;THAI LETTER PHO SAMPHAO;;;; +0E21;THAI CHARACTER MO MA;Lo;0;L;;;;;N;THAI LETTER MO MA;;;; +0E22;THAI CHARACTER YO YAK;Lo;0;L;;;;;N;THAI LETTER YO YAK;;;; +0E23;THAI CHARACTER RO RUA;Lo;0;L;;;;;N;THAI LETTER RO RUA;;;; +0E24;THAI CHARACTER RU;Lo;0;L;;;;;N;THAI LETTER RU;;;; +0E25;THAI CHARACTER LO LING;Lo;0;L;;;;;N;THAI LETTER LO LING;;;; +0E26;THAI CHARACTER LU;Lo;0;L;;;;;N;THAI LETTER LU;;;; +0E27;THAI CHARACTER WO WAEN;Lo;0;L;;;;;N;THAI LETTER WO WAEN;;;; +0E28;THAI CHARACTER SO SALA;Lo;0;L;;;;;N;THAI LETTER SO SALA;;;; +0E29;THAI CHARACTER SO RUSI;Lo;0;L;;;;;N;THAI LETTER SO RUSI;;;; +0E2A;THAI CHARACTER SO SUA;Lo;0;L;;;;;N;THAI LETTER SO SUA;;;; +0E2B;THAI CHARACTER HO HIP;Lo;0;L;;;;;N;THAI LETTER HO HIP;;;; +0E2C;THAI CHARACTER LO CHULA;Lo;0;L;;;;;N;THAI LETTER LO CHULA;;;; +0E2D;THAI CHARACTER O ANG;Lo;0;L;;;;;N;THAI LETTER O ANG;;;; +0E2E;THAI CHARACTER HO NOKHUK;Lo;0;L;;;;;N;THAI LETTER HO NOK HUK;;;; +0E2F;THAI CHARACTER PAIYANNOI;Lo;0;L;;;;;N;THAI PAI YAN NOI;;;; +0E30;THAI CHARACTER SARA A;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA A;;;; +0E31;THAI CHARACTER MAI HAN-AKAT;Mn;0;NSM;;;;;N;THAI VOWEL SIGN MAI HAN-AKAT;;;; +0E32;THAI CHARACTER SARA AA;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA AA;;;; +0E33;THAI CHARACTER SARA AM;Lo;0;L; 0E4D 0E32;;;;N;THAI VOWEL SIGN SARA AM;;;; +0E34;THAI CHARACTER SARA I;Mn;0;NSM;;;;;N;THAI VOWEL SIGN SARA I;;;; +0E35;THAI CHARACTER SARA II;Mn;0;NSM;;;;;N;THAI VOWEL SIGN SARA II;;;; +0E36;THAI CHARACTER SARA UE;Mn;0;NSM;;;;;N;THAI VOWEL SIGN SARA UE;;;; +0E37;THAI CHARACTER SARA UEE;Mn;0;NSM;;;;;N;THAI VOWEL SIGN SARA UEE;;;; +0E38;THAI CHARACTER SARA U;Mn;103;NSM;;;;;N;THAI VOWEL SIGN SARA U;;;; +0E39;THAI CHARACTER SARA UU;Mn;103;NSM;;;;;N;THAI VOWEL SIGN SARA UU;;;; +0E3A;THAI CHARACTER PHINTHU;Mn;9;NSM;;;;;N;THAI VOWEL SIGN PHINTHU;;;; +0E3F;THAI CURRENCY SYMBOL BAHT;Sc;0;ET;;;;;N;THAI BAHT SIGN;;;; +0E40;THAI CHARACTER SARA E;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA E;;;; +0E41;THAI CHARACTER SARA AE;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA AE;;;; +0E42;THAI CHARACTER SARA O;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA O;;;; +0E43;THAI CHARACTER SARA AI MAIMUAN;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA MAI MUAN;;;; +0E44;THAI CHARACTER SARA AI MAIMALAI;Lo;0;L;;;;;N;THAI VOWEL SIGN SARA MAI MALAI;;;; +0E45;THAI CHARACTER LAKKHANGYAO;Lo;0;L;;;;;N;THAI LAK KHANG YAO;;;; +0E46;THAI CHARACTER MAIYAMOK;Lm;0;L;;;;;N;THAI MAI YAMOK;;;; +0E47;THAI CHARACTER MAITAIKHU;Mn;0;NSM;;;;;N;THAI VOWEL SIGN MAI TAI KHU;;;; +0E48;THAI CHARACTER MAI EK;Mn;107;NSM;;;;;N;THAI TONE MAI EK;;;; +0E49;THAI CHARACTER MAI THO;Mn;107;NSM;;;;;N;THAI TONE MAI THO;;;; +0E4A;THAI CHARACTER MAI TRI;Mn;107;NSM;;;;;N;THAI TONE MAI TRI;;;; +0E4B;THAI CHARACTER MAI CHATTAWA;Mn;107;NSM;;;;;N;THAI TONE MAI CHATTAWA;;;; +0E4C;THAI CHARACTER THANTHAKHAT;Mn;0;NSM;;;;;N;THAI THANTHAKHAT;;;; +0E4D;THAI CHARACTER NIKHAHIT;Mn;0;NSM;;;;;N;THAI NIKKHAHIT;;;; +0E4E;THAI CHARACTER YAMAKKAN;Mn;0;NSM;;;;;N;THAI YAMAKKAN;;;; +0E4F;THAI CHARACTER FONGMAN;Po;0;L;;;;;N;THAI FONGMAN;;;; +0E50;THAI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0E51;THAI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0E52;THAI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0E53;THAI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0E54;THAI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0E55;THAI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0E56;THAI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0E57;THAI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0E58;THAI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0E59;THAI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0E5A;THAI CHARACTER ANGKHANKHU;Po;0;L;;;;;N;THAI ANGKHANKHU;;;; +0E5B;THAI CHARACTER KHOMUT;Po;0;L;;;;;N;THAI KHOMUT;;;; +0E81;LAO LETTER KO;Lo;0;L;;;;;N;;;;; +0E82;LAO LETTER KHO SUNG;Lo;0;L;;;;;N;;;;; +0E84;LAO LETTER KHO TAM;Lo;0;L;;;;;N;;;;; +0E87;LAO LETTER NGO;Lo;0;L;;;;;N;;;;; +0E88;LAO LETTER CO;Lo;0;L;;;;;N;;;;; +0E8A;LAO LETTER SO TAM;Lo;0;L;;;;;N;;;;; +0E8D;LAO LETTER NYO;Lo;0;L;;;;;N;;;;; +0E94;LAO LETTER DO;Lo;0;L;;;;;N;;;;; +0E95;LAO LETTER TO;Lo;0;L;;;;;N;;;;; +0E96;LAO LETTER THO SUNG;Lo;0;L;;;;;N;;;;; +0E97;LAO LETTER THO TAM;Lo;0;L;;;;;N;;;;; +0E99;LAO LETTER NO;Lo;0;L;;;;;N;;;;; +0E9A;LAO LETTER BO;Lo;0;L;;;;;N;;;;; +0E9B;LAO LETTER PO;Lo;0;L;;;;;N;;;;; +0E9C;LAO LETTER PHO SUNG;Lo;0;L;;;;;N;;;;; +0E9D;LAO LETTER FO TAM;Lo;0;L;;;;;N;;;;; +0E9E;LAO LETTER PHO TAM;Lo;0;L;;;;;N;;;;; +0E9F;LAO LETTER FO SUNG;Lo;0;L;;;;;N;;;;; +0EA1;LAO LETTER MO;Lo;0;L;;;;;N;;;;; +0EA2;LAO LETTER YO;Lo;0;L;;;;;N;;;;; +0EA3;LAO LETTER LO LING;Lo;0;L;;;;;N;;;;; +0EA5;LAO LETTER LO LOOT;Lo;0;L;;;;;N;;;;; +0EA7;LAO LETTER WO;Lo;0;L;;;;;N;;;;; +0EAA;LAO LETTER SO SUNG;Lo;0;L;;;;;N;;;;; +0EAB;LAO LETTER HO SUNG;Lo;0;L;;;;;N;;;;; +0EAD;LAO LETTER O;Lo;0;L;;;;;N;;;;; +0EAE;LAO LETTER HO TAM;Lo;0;L;;;;;N;;;;; +0EAF;LAO ELLIPSIS;Lo;0;L;;;;;N;;;;; +0EB0;LAO VOWEL SIGN A;Lo;0;L;;;;;N;;;;; +0EB1;LAO VOWEL SIGN MAI KAN;Mn;0;NSM;;;;;N;;;;; +0EB2;LAO VOWEL SIGN AA;Lo;0;L;;;;;N;;;;; +0EB3;LAO VOWEL SIGN AM;Lo;0;L; 0ECD 0EB2;;;;N;;;;; +0EB4;LAO VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +0EB5;LAO VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;; +0EB6;LAO VOWEL SIGN Y;Mn;0;NSM;;;;;N;;;;; +0EB7;LAO VOWEL SIGN YY;Mn;0;NSM;;;;;N;;;;; +0EB8;LAO VOWEL SIGN U;Mn;118;NSM;;;;;N;;;;; +0EB9;LAO VOWEL SIGN UU;Mn;118;NSM;;;;;N;;;;; +0EBB;LAO VOWEL SIGN MAI KON;Mn;0;NSM;;;;;N;;;;; +0EBC;LAO SEMIVOWEL SIGN LO;Mn;0;NSM;;;;;N;;;;; +0EBD;LAO SEMIVOWEL SIGN NYO;Lo;0;L;;;;;N;;;;; +0EC0;LAO VOWEL SIGN E;Lo;0;L;;;;;N;;;;; +0EC1;LAO VOWEL SIGN EI;Lo;0;L;;;;;N;;;;; +0EC2;LAO VOWEL SIGN O;Lo;0;L;;;;;N;;;;; +0EC3;LAO VOWEL SIGN AY;Lo;0;L;;;;;N;;;;; +0EC4;LAO VOWEL SIGN AI;Lo;0;L;;;;;N;;;;; +0EC6;LAO KO LA;Lm;0;L;;;;;N;;;;; +0EC8;LAO TONE MAI EK;Mn;122;NSM;;;;;N;;;;; +0EC9;LAO TONE MAI THO;Mn;122;NSM;;;;;N;;;;; +0ECA;LAO TONE MAI TI;Mn;122;NSM;;;;;N;;;;; +0ECB;LAO TONE MAI CATAWA;Mn;122;NSM;;;;;N;;;;; +0ECC;LAO CANCELLATION MARK;Mn;0;NSM;;;;;N;;;;; +0ECD;LAO NIGGAHITA;Mn;0;NSM;;;;;N;;;;; +0ED0;LAO DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0ED1;LAO DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0ED2;LAO DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0ED3;LAO DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0ED4;LAO DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0ED5;LAO DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0ED6;LAO DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0ED7;LAO DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0ED8;LAO DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0ED9;LAO DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0EDC;LAO HO NO;Lo;0;L; 0EAB 0E99;;;;N;;;;; +0EDD;LAO HO MO;Lo;0;L; 0EAB 0EA1;;;;N;;;;; +0EDE;LAO LETTER KHMU GO;Lo;0;L;;;;;N;;;;; +0EDF;LAO LETTER KHMU NYO;Lo;0;L;;;;;N;;;;; +0F00;TIBETAN SYLLABLE OM;Lo;0;L;;;;;N;;;;; +0F01;TIBETAN MARK GTER YIG MGO TRUNCATED A;So;0;L;;;;;N;;;;; +0F02;TIBETAN MARK GTER YIG MGO -UM RNAM BCAD MA;So;0;L;;;;;N;;;;; +0F03;TIBETAN MARK GTER YIG MGO -UM GTER TSHEG MA;So;0;L;;;;;N;;;;; +0F04;TIBETAN MARK INITIAL YIG MGO MDUN MA;Po;0;L;;;;;N;TIBETAN SINGLE ORNAMENT;;;; +0F05;TIBETAN MARK CLOSING YIG MGO SGAB MA;Po;0;L;;;;;N;;;;; +0F06;TIBETAN MARK CARET YIG MGO PHUR SHAD MA;Po;0;L;;;;;N;;;;; +0F07;TIBETAN MARK YIG MGO TSHEG SHAD MA;Po;0;L;;;;;N;;;;; +0F08;TIBETAN MARK SBRUL SHAD;Po;0;L;;;;;N;TIBETAN RGYANSHAD;;;; +0F09;TIBETAN MARK BSKUR YIG MGO;Po;0;L;;;;;N;;;;; +0F0A;TIBETAN MARK BKA- SHOG YIG MGO;Po;0;L;;;;;N;;;;; +0F0B;TIBETAN MARK INTERSYLLABIC TSHEG;Po;0;L;;;;;N;TIBETAN TSEG;;;; +0F0C;TIBETAN MARK DELIMITER TSHEG BSTAR;Po;0;L; 0F0B;;;;N;;;;; +0F0D;TIBETAN MARK SHAD;Po;0;L;;;;;N;TIBETAN SHAD;;;; +0F0E;TIBETAN MARK NYIS SHAD;Po;0;L;;;;;N;TIBETAN DOUBLE SHAD;;;; +0F0F;TIBETAN MARK TSHEG SHAD;Po;0;L;;;;;N;;;;; +0F10;TIBETAN MARK NYIS TSHEG SHAD;Po;0;L;;;;;N;;;;; +0F11;TIBETAN MARK RIN CHEN SPUNGS SHAD;Po;0;L;;;;;N;TIBETAN RINCHANPHUNGSHAD;;;; +0F12;TIBETAN MARK RGYA GRAM SHAD;Po;0;L;;;;;N;;;;; +0F13;TIBETAN MARK CARET -DZUD RTAGS ME LONG CAN;So;0;L;;;;;N;;;;; +0F14;TIBETAN MARK GTER TSHEG;Po;0;L;;;;;N;TIBETAN COMMA;;;; +0F15;TIBETAN LOGOTYPE SIGN CHAD RTAGS;So;0;L;;;;;N;;;;; +0F16;TIBETAN LOGOTYPE SIGN LHAG RTAGS;So;0;L;;;;;N;;;;; +0F17;TIBETAN ASTROLOGICAL SIGN SGRA GCAN -CHAR RTAGS;So;0;L;;;;;N;;;;; +0F18;TIBETAN ASTROLOGICAL SIGN -KHYUD PA;Mn;220;NSM;;;;;N;;;;; +0F19;TIBETAN ASTROLOGICAL SIGN SDONG TSHUGS;Mn;220;NSM;;;;;N;;;;; +0F1A;TIBETAN SIGN RDEL DKAR GCIG;So;0;L;;;;;N;;;;; +0F1B;TIBETAN SIGN RDEL DKAR GNYIS;So;0;L;;;;;N;;;;; +0F1C;TIBETAN SIGN RDEL DKAR GSUM;So;0;L;;;;;N;;;;; +0F1D;TIBETAN SIGN RDEL NAG GCIG;So;0;L;;;;;N;;;;; +0F1E;TIBETAN SIGN RDEL NAG GNYIS;So;0;L;;;;;N;;;;; +0F1F;TIBETAN SIGN RDEL DKAR RDEL NAG;So;0;L;;;;;N;;;;; +0F20;TIBETAN DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +0F21;TIBETAN DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +0F22;TIBETAN DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +0F23;TIBETAN DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +0F24;TIBETAN DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +0F25;TIBETAN DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +0F26;TIBETAN DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +0F27;TIBETAN DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +0F28;TIBETAN DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +0F29;TIBETAN DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +0F2A;TIBETAN DIGIT HALF ONE;No;0;L;;;;1/2;N;;;;; +0F2B;TIBETAN DIGIT HALF TWO;No;0;L;;;;3/2;N;;;;; +0F2C;TIBETAN DIGIT HALF THREE;No;0;L;;;;5/2;N;;;;; +0F2D;TIBETAN DIGIT HALF FOUR;No;0;L;;;;7/2;N;;;;; +0F2E;TIBETAN DIGIT HALF FIVE;No;0;L;;;;9/2;N;;;;; +0F2F;TIBETAN DIGIT HALF SIX;No;0;L;;;;11/2;N;;;;; +0F30;TIBETAN DIGIT HALF SEVEN;No;0;L;;;;13/2;N;;;;; +0F31;TIBETAN DIGIT HALF EIGHT;No;0;L;;;;15/2;N;;;;; +0F32;TIBETAN DIGIT HALF NINE;No;0;L;;;;17/2;N;;;;; +0F33;TIBETAN DIGIT HALF ZERO;No;0;L;;;;-1/2;N;;;;; +0F34;TIBETAN MARK BSDUS RTAGS;So;0;L;;;;;N;;;;; +0F35;TIBETAN MARK NGAS BZUNG NYI ZLA;Mn;220;NSM;;;;;N;TIBETAN HONORIFIC UNDER RING;;;; +0F36;TIBETAN MARK CARET -DZUD RTAGS BZHI MIG CAN;So;0;L;;;;;N;;;;; +0F37;TIBETAN MARK NGAS BZUNG SGOR RTAGS;Mn;220;NSM;;;;;N;TIBETAN UNDER RING;;;; +0F38;TIBETAN MARK CHE MGO;So;0;L;;;;;N;;;;; +0F39;TIBETAN MARK TSA -PHRU;Mn;216;NSM;;;;;N;TIBETAN LENITION MARK;;;; +0F3A;TIBETAN MARK GUG RTAGS GYON;Ps;0;ON;;;;;Y;;;;; +0F3B;TIBETAN MARK GUG RTAGS GYAS;Pe;0;ON;;;;;Y;;;;; +0F3C;TIBETAN MARK ANG KHANG GYON;Ps;0;ON;;;;;Y;TIBETAN LEFT BRACE;;;; +0F3D;TIBETAN MARK ANG KHANG GYAS;Pe;0;ON;;;;;Y;TIBETAN RIGHT BRACE;;;; +0F3E;TIBETAN SIGN YAR TSHES;Mc;0;L;;;;;N;;;;; +0F3F;TIBETAN SIGN MAR TSHES;Mc;0;L;;;;;N;;;;; +0F40;TIBETAN LETTER KA;Lo;0;L;;;;;N;;;;; +0F41;TIBETAN LETTER KHA;Lo;0;L;;;;;N;;;;; +0F42;TIBETAN LETTER GA;Lo;0;L;;;;;N;;;;; +0F43;TIBETAN LETTER GHA;Lo;0;L;0F42 0FB7;;;;N;;;;; +0F44;TIBETAN LETTER NGA;Lo;0;L;;;;;N;;;;; +0F45;TIBETAN LETTER CA;Lo;0;L;;;;;N;;;;; +0F46;TIBETAN LETTER CHA;Lo;0;L;;;;;N;;;;; +0F47;TIBETAN LETTER JA;Lo;0;L;;;;;N;;;;; +0F49;TIBETAN LETTER NYA;Lo;0;L;;;;;N;;;;; +0F4A;TIBETAN LETTER TTA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED TA;;;; +0F4B;TIBETAN LETTER TTHA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED THA;;;; +0F4C;TIBETAN LETTER DDA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED DA;;;; +0F4D;TIBETAN LETTER DDHA;Lo;0;L;0F4C 0FB7;;;;N;;;;; +0F4E;TIBETAN LETTER NNA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED NA;;;; +0F4F;TIBETAN LETTER TA;Lo;0;L;;;;;N;;;;; +0F50;TIBETAN LETTER THA;Lo;0;L;;;;;N;;;;; +0F51;TIBETAN LETTER DA;Lo;0;L;;;;;N;;;;; +0F52;TIBETAN LETTER DHA;Lo;0;L;0F51 0FB7;;;;N;;;;; +0F53;TIBETAN LETTER NA;Lo;0;L;;;;;N;;;;; +0F54;TIBETAN LETTER PA;Lo;0;L;;;;;N;;;;; +0F55;TIBETAN LETTER PHA;Lo;0;L;;;;;N;;;;; +0F56;TIBETAN LETTER BA;Lo;0;L;;;;;N;;;;; +0F57;TIBETAN LETTER BHA;Lo;0;L;0F56 0FB7;;;;N;;;;; +0F58;TIBETAN LETTER MA;Lo;0;L;;;;;N;;;;; +0F59;TIBETAN LETTER TSA;Lo;0;L;;;;;N;;;;; +0F5A;TIBETAN LETTER TSHA;Lo;0;L;;;;;N;;;;; +0F5B;TIBETAN LETTER DZA;Lo;0;L;;;;;N;;;;; +0F5C;TIBETAN LETTER DZHA;Lo;0;L;0F5B 0FB7;;;;N;;;;; +0F5D;TIBETAN LETTER WA;Lo;0;L;;;;;N;;;;; +0F5E;TIBETAN LETTER ZHA;Lo;0;L;;;;;N;;;;; +0F5F;TIBETAN LETTER ZA;Lo;0;L;;;;;N;;;;; +0F60;TIBETAN LETTER -A;Lo;0;L;;;;;N;TIBETAN LETTER AA;;;; +0F61;TIBETAN LETTER YA;Lo;0;L;;;;;N;;;;; +0F62;TIBETAN LETTER RA;Lo;0;L;;;;;N;;;;; +0F63;TIBETAN LETTER LA;Lo;0;L;;;;;N;;;;; +0F64;TIBETAN LETTER SHA;Lo;0;L;;;;;N;;;;; +0F65;TIBETAN LETTER SSA;Lo;0;L;;;;;N;TIBETAN LETTER REVERSED SHA;;;; +0F66;TIBETAN LETTER SA;Lo;0;L;;;;;N;;;;; +0F67;TIBETAN LETTER HA;Lo;0;L;;;;;N;;;;; +0F68;TIBETAN LETTER A;Lo;0;L;;;;;N;;;;; +0F69;TIBETAN LETTER KSSA;Lo;0;L;0F40 0FB5;;;;N;;;;; +0F6A;TIBETAN LETTER FIXED-FORM RA;Lo;0;L;;;;;N;;;;; +0F6B;TIBETAN LETTER KKA;Lo;0;L;;;;;N;;;;; +0F6C;TIBETAN LETTER RRA;Lo;0;L;;;;;N;;;;; +0F71;TIBETAN VOWEL SIGN AA;Mn;129;NSM;;;;;N;;;;; +0F72;TIBETAN VOWEL SIGN I;Mn;130;NSM;;;;;N;;;;; +0F73;TIBETAN VOWEL SIGN II;Mn;0;NSM;0F71 0F72;;;;N;;;;; +0F74;TIBETAN VOWEL SIGN U;Mn;132;NSM;;;;;N;;;;; +0F75;TIBETAN VOWEL SIGN UU;Mn;0;NSM;0F71 0F74;;;;N;;;;; +0F76;TIBETAN VOWEL SIGN VOCALIC R;Mn;0;NSM;0FB2 0F80;;;;N;;;;; +0F77;TIBETAN VOWEL SIGN VOCALIC RR;Mn;0;NSM; 0FB2 0F81;;;;N;;;;; +0F78;TIBETAN VOWEL SIGN VOCALIC L;Mn;0;NSM;0FB3 0F80;;;;N;;;;; +0F79;TIBETAN VOWEL SIGN VOCALIC LL;Mn;0;NSM; 0FB3 0F81;;;;N;;;;; +0F7A;TIBETAN VOWEL SIGN E;Mn;130;NSM;;;;;N;;;;; +0F7B;TIBETAN VOWEL SIGN EE;Mn;130;NSM;;;;;N;TIBETAN VOWEL SIGN AI;;;; +0F7C;TIBETAN VOWEL SIGN O;Mn;130;NSM;;;;;N;;;;; +0F7D;TIBETAN VOWEL SIGN OO;Mn;130;NSM;;;;;N;TIBETAN VOWEL SIGN AU;;;; +0F7E;TIBETAN SIGN RJES SU NGA RO;Mn;0;NSM;;;;;N;TIBETAN ANUSVARA;;;; +0F7F;TIBETAN SIGN RNAM BCAD;Mc;0;L;;;;;N;TIBETAN VISARGA;;;; +0F80;TIBETAN VOWEL SIGN REVERSED I;Mn;130;NSM;;;;;N;TIBETAN VOWEL SIGN SHORT I;;;; +0F81;TIBETAN VOWEL SIGN REVERSED II;Mn;0;NSM;0F71 0F80;;;;N;;;;; +0F82;TIBETAN SIGN NYI ZLA NAA DA;Mn;230;NSM;;;;;N;TIBETAN CANDRABINDU WITH ORNAMENT;;;; +0F83;TIBETAN SIGN SNA LDAN;Mn;230;NSM;;;;;N;TIBETAN CANDRABINDU;;;; +0F84;TIBETAN MARK HALANTA;Mn;9;NSM;;;;;N;TIBETAN VIRAMA;;;; +0F85;TIBETAN MARK PALUTA;Po;0;L;;;;;N;TIBETAN CHUCHENYIGE;;;; +0F86;TIBETAN SIGN LCI RTAGS;Mn;230;NSM;;;;;N;;;;; +0F87;TIBETAN SIGN YANG RTAGS;Mn;230;NSM;;;;;N;;;;; +0F88;TIBETAN SIGN LCE TSA CAN;Lo;0;L;;;;;N;;;;; +0F89;TIBETAN SIGN MCHU CAN;Lo;0;L;;;;;N;;;;; +0F8A;TIBETAN SIGN GRU CAN RGYINGS;Lo;0;L;;;;;N;;;;; +0F8B;TIBETAN SIGN GRU MED RGYINGS;Lo;0;L;;;;;N;;;;; +0F8C;TIBETAN SIGN INVERTED MCHU CAN;Lo;0;L;;;;;N;;;;; +0F8D;TIBETAN SUBJOINED SIGN LCE TSA CAN;Mn;0;NSM;;;;;N;;;;; +0F8E;TIBETAN SUBJOINED SIGN MCHU CAN;Mn;0;NSM;;;;;N;;;;; +0F8F;TIBETAN SUBJOINED SIGN INVERTED MCHU CAN;Mn;0;NSM;;;;;N;;;;; +0F90;TIBETAN SUBJOINED LETTER KA;Mn;0;NSM;;;;;N;;;;; +0F91;TIBETAN SUBJOINED LETTER KHA;Mn;0;NSM;;;;;N;;;;; +0F92;TIBETAN SUBJOINED LETTER GA;Mn;0;NSM;;;;;N;;;;; +0F93;TIBETAN SUBJOINED LETTER GHA;Mn;0;NSM;0F92 0FB7;;;;N;;;;; +0F94;TIBETAN SUBJOINED LETTER NGA;Mn;0;NSM;;;;;N;;;;; +0F95;TIBETAN SUBJOINED LETTER CA;Mn;0;NSM;;;;;N;;;;; +0F96;TIBETAN SUBJOINED LETTER CHA;Mn;0;NSM;;;;;N;;;;; +0F97;TIBETAN SUBJOINED LETTER JA;Mn;0;NSM;;;;;N;;;;; +0F99;TIBETAN SUBJOINED LETTER NYA;Mn;0;NSM;;;;;N;;;;; +0F9A;TIBETAN SUBJOINED LETTER TTA;Mn;0;NSM;;;;;N;;;;; +0F9B;TIBETAN SUBJOINED LETTER TTHA;Mn;0;NSM;;;;;N;;;;; +0F9C;TIBETAN SUBJOINED LETTER DDA;Mn;0;NSM;;;;;N;;;;; +0F9D;TIBETAN SUBJOINED LETTER DDHA;Mn;0;NSM;0F9C 0FB7;;;;N;;;;; +0F9E;TIBETAN SUBJOINED LETTER NNA;Mn;0;NSM;;;;;N;;;;; +0F9F;TIBETAN SUBJOINED LETTER TA;Mn;0;NSM;;;;;N;;;;; +0FA0;TIBETAN SUBJOINED LETTER THA;Mn;0;NSM;;;;;N;;;;; +0FA1;TIBETAN SUBJOINED LETTER DA;Mn;0;NSM;;;;;N;;;;; +0FA2;TIBETAN SUBJOINED LETTER DHA;Mn;0;NSM;0FA1 0FB7;;;;N;;;;; +0FA3;TIBETAN SUBJOINED LETTER NA;Mn;0;NSM;;;;;N;;;;; +0FA4;TIBETAN SUBJOINED LETTER PA;Mn;0;NSM;;;;;N;;;;; +0FA5;TIBETAN SUBJOINED LETTER PHA;Mn;0;NSM;;;;;N;;;;; +0FA6;TIBETAN SUBJOINED LETTER BA;Mn;0;NSM;;;;;N;;;;; +0FA7;TIBETAN SUBJOINED LETTER BHA;Mn;0;NSM;0FA6 0FB7;;;;N;;;;; +0FA8;TIBETAN SUBJOINED LETTER MA;Mn;0;NSM;;;;;N;;;;; +0FA9;TIBETAN SUBJOINED LETTER TSA;Mn;0;NSM;;;;;N;;;;; +0FAA;TIBETAN SUBJOINED LETTER TSHA;Mn;0;NSM;;;;;N;;;;; +0FAB;TIBETAN SUBJOINED LETTER DZA;Mn;0;NSM;;;;;N;;;;; +0FAC;TIBETAN SUBJOINED LETTER DZHA;Mn;0;NSM;0FAB 0FB7;;;;N;;;;; +0FAD;TIBETAN SUBJOINED LETTER WA;Mn;0;NSM;;;;;N;;;;; +0FAE;TIBETAN SUBJOINED LETTER ZHA;Mn;0;NSM;;;;;N;;;;; +0FAF;TIBETAN SUBJOINED LETTER ZA;Mn;0;NSM;;;;;N;;;;; +0FB0;TIBETAN SUBJOINED LETTER -A;Mn;0;NSM;;;;;N;;;;; +0FB1;TIBETAN SUBJOINED LETTER YA;Mn;0;NSM;;;;;N;;;;; +0FB2;TIBETAN SUBJOINED LETTER RA;Mn;0;NSM;;;;;N;;;;; +0FB3;TIBETAN SUBJOINED LETTER LA;Mn;0;NSM;;;;;N;;;;; +0FB4;TIBETAN SUBJOINED LETTER SHA;Mn;0;NSM;;;;;N;;;;; +0FB5;TIBETAN SUBJOINED LETTER SSA;Mn;0;NSM;;;;;N;;;;; +0FB6;TIBETAN SUBJOINED LETTER SA;Mn;0;NSM;;;;;N;;;;; +0FB7;TIBETAN SUBJOINED LETTER HA;Mn;0;NSM;;;;;N;;;;; +0FB8;TIBETAN SUBJOINED LETTER A;Mn;0;NSM;;;;;N;;;;; +0FB9;TIBETAN SUBJOINED LETTER KSSA;Mn;0;NSM;0F90 0FB5;;;;N;;;;; +0FBA;TIBETAN SUBJOINED LETTER FIXED-FORM WA;Mn;0;NSM;;;;;N;;;;; +0FBB;TIBETAN SUBJOINED LETTER FIXED-FORM YA;Mn;0;NSM;;;;;N;;;;; +0FBC;TIBETAN SUBJOINED LETTER FIXED-FORM RA;Mn;0;NSM;;;;;N;;;;; +0FBE;TIBETAN KU RU KHA;So;0;L;;;;;N;;;;; +0FBF;TIBETAN KU RU KHA BZHI MIG CAN;So;0;L;;;;;N;;;;; +0FC0;TIBETAN CANTILLATION SIGN HEAVY BEAT;So;0;L;;;;;N;;;;; +0FC1;TIBETAN CANTILLATION SIGN LIGHT BEAT;So;0;L;;;;;N;;;;; +0FC2;TIBETAN CANTILLATION SIGN CANG TE-U;So;0;L;;;;;N;;;;; +0FC3;TIBETAN CANTILLATION SIGN SBUB -CHAL;So;0;L;;;;;N;;;;; +0FC4;TIBETAN SYMBOL DRIL BU;So;0;L;;;;;N;;;;; +0FC5;TIBETAN SYMBOL RDO RJE;So;0;L;;;;;N;;;;; +0FC6;TIBETAN SYMBOL PADMA GDAN;Mn;220;NSM;;;;;N;;;;; +0FC7;TIBETAN SYMBOL RDO RJE RGYA GRAM;So;0;L;;;;;N;;;;; +0FC8;TIBETAN SYMBOL PHUR PA;So;0;L;;;;;N;;;;; +0FC9;TIBETAN SYMBOL NOR BU;So;0;L;;;;;N;;;;; +0FCA;TIBETAN SYMBOL NOR BU NYIS -KHYIL;So;0;L;;;;;N;;;;; +0FCB;TIBETAN SYMBOL NOR BU GSUM -KHYIL;So;0;L;;;;;N;;;;; +0FCC;TIBETAN SYMBOL NOR BU BZHI -KHYIL;So;0;L;;;;;N;;;;; +0FCE;TIBETAN SIGN RDEL NAG RDEL DKAR;So;0;L;;;;;N;;;;; +0FCF;TIBETAN SIGN RDEL NAG GSUM;So;0;L;;;;;N;;;;; +0FD0;TIBETAN MARK BSKA- SHOG GI MGO RGYAN;Po;0;L;;;;;N;;;;; +0FD1;TIBETAN MARK MNYAM YIG GI MGO RGYAN;Po;0;L;;;;;N;;;;; +0FD2;TIBETAN MARK NYIS TSHEG;Po;0;L;;;;;N;;;;; +0FD3;TIBETAN MARK INITIAL BRDA RNYING YIG MGO MDUN MA;Po;0;L;;;;;N;;;;; +0FD4;TIBETAN MARK CLOSING BRDA RNYING YIG MGO SGAB MA;Po;0;L;;;;;N;;;;; +0FD5;RIGHT-FACING SVASTI SIGN;So;0;L;;;;;N;;;;; +0FD6;LEFT-FACING SVASTI SIGN;So;0;L;;;;;N;;;;; +0FD7;RIGHT-FACING SVASTI SIGN WITH DOTS;So;0;L;;;;;N;;;;; +0FD8;LEFT-FACING SVASTI SIGN WITH DOTS;So;0;L;;;;;N;;;;; +0FD9;TIBETAN MARK LEADING MCHAN RTAGS;Po;0;L;;;;;N;;;;; +0FDA;TIBETAN MARK TRAILING MCHAN RTAGS;Po;0;L;;;;;N;;;;; +1000;MYANMAR LETTER KA;Lo;0;L;;;;;N;;;;; +1001;MYANMAR LETTER KHA;Lo;0;L;;;;;N;;;;; +1002;MYANMAR LETTER GA;Lo;0;L;;;;;N;;;;; +1003;MYANMAR LETTER GHA;Lo;0;L;;;;;N;;;;; +1004;MYANMAR LETTER NGA;Lo;0;L;;;;;N;;;;; +1005;MYANMAR LETTER CA;Lo;0;L;;;;;N;;;;; +1006;MYANMAR LETTER CHA;Lo;0;L;;;;;N;;;;; +1007;MYANMAR LETTER JA;Lo;0;L;;;;;N;;;;; +1008;MYANMAR LETTER JHA;Lo;0;L;;;;;N;;;;; +1009;MYANMAR LETTER NYA;Lo;0;L;;;;;N;;;;; +100A;MYANMAR LETTER NNYA;Lo;0;L;;;;;N;;;;; +100B;MYANMAR LETTER TTA;Lo;0;L;;;;;N;;;;; +100C;MYANMAR LETTER TTHA;Lo;0;L;;;;;N;;;;; +100D;MYANMAR LETTER DDA;Lo;0;L;;;;;N;;;;; +100E;MYANMAR LETTER DDHA;Lo;0;L;;;;;N;;;;; +100F;MYANMAR LETTER NNA;Lo;0;L;;;;;N;;;;; +1010;MYANMAR LETTER TA;Lo;0;L;;;;;N;;;;; +1011;MYANMAR LETTER THA;Lo;0;L;;;;;N;;;;; +1012;MYANMAR LETTER DA;Lo;0;L;;;;;N;;;;; +1013;MYANMAR LETTER DHA;Lo;0;L;;;;;N;;;;; +1014;MYANMAR LETTER NA;Lo;0;L;;;;;N;;;;; +1015;MYANMAR LETTER PA;Lo;0;L;;;;;N;;;;; +1016;MYANMAR LETTER PHA;Lo;0;L;;;;;N;;;;; +1017;MYANMAR LETTER BA;Lo;0;L;;;;;N;;;;; +1018;MYANMAR LETTER BHA;Lo;0;L;;;;;N;;;;; +1019;MYANMAR LETTER MA;Lo;0;L;;;;;N;;;;; +101A;MYANMAR LETTER YA;Lo;0;L;;;;;N;;;;; +101B;MYANMAR LETTER RA;Lo;0;L;;;;;N;;;;; +101C;MYANMAR LETTER LA;Lo;0;L;;;;;N;;;;; +101D;MYANMAR LETTER WA;Lo;0;L;;;;;N;;;;; +101E;MYANMAR LETTER SA;Lo;0;L;;;;;N;;;;; +101F;MYANMAR LETTER HA;Lo;0;L;;;;;N;;;;; +1020;MYANMAR LETTER LLA;Lo;0;L;;;;;N;;;;; +1021;MYANMAR LETTER A;Lo;0;L;;;;;N;;;;; +1022;MYANMAR LETTER SHAN A;Lo;0;L;;;;;N;;;;; +1023;MYANMAR LETTER I;Lo;0;L;;;;;N;;;;; +1024;MYANMAR LETTER II;Lo;0;L;;;;;N;;;;; +1025;MYANMAR LETTER U;Lo;0;L;;;;;N;;;;; +1026;MYANMAR LETTER UU;Lo;0;L;1025 102E;;;;N;;;;; +1027;MYANMAR LETTER E;Lo;0;L;;;;;N;;;;; +1028;MYANMAR LETTER MON E;Lo;0;L;;;;;N;;;;; +1029;MYANMAR LETTER O;Lo;0;L;;;;;N;;;;; +102A;MYANMAR LETTER AU;Lo;0;L;;;;;N;;;;; +102B;MYANMAR VOWEL SIGN TALL AA;Mc;0;L;;;;;N;;;;; +102C;MYANMAR VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +102D;MYANMAR VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +102E;MYANMAR VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;; +102F;MYANMAR VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +1030;MYANMAR VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +1031;MYANMAR VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +1032;MYANMAR VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +1033;MYANMAR VOWEL SIGN MON II;Mn;0;NSM;;;;;N;;;;; +1034;MYANMAR VOWEL SIGN MON O;Mn;0;NSM;;;;;N;;;;; +1035;MYANMAR VOWEL SIGN E ABOVE;Mn;0;NSM;;;;;N;;;;; +1036;MYANMAR SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +1037;MYANMAR SIGN DOT BELOW;Mn;7;NSM;;;;;N;;;;; +1038;MYANMAR SIGN VISARGA;Mc;0;L;;;;;N;;;;; +1039;MYANMAR SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +103A;MYANMAR SIGN ASAT;Mn;9;NSM;;;;;N;;;;; +103B;MYANMAR CONSONANT SIGN MEDIAL YA;Mc;0;L;;;;;N;;;;; +103C;MYANMAR CONSONANT SIGN MEDIAL RA;Mc;0;L;;;;;N;;;;; +103D;MYANMAR CONSONANT SIGN MEDIAL WA;Mn;0;NSM;;;;;N;;;;; +103E;MYANMAR CONSONANT SIGN MEDIAL HA;Mn;0;NSM;;;;;N;;;;; +103F;MYANMAR LETTER GREAT SA;Lo;0;L;;;;;N;;;;; +1040;MYANMAR DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1041;MYANMAR DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1042;MYANMAR DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1043;MYANMAR DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1044;MYANMAR DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1045;MYANMAR DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1046;MYANMAR DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1047;MYANMAR DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1048;MYANMAR DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1049;MYANMAR DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +104A;MYANMAR SIGN LITTLE SECTION;Po;0;L;;;;;N;;;;; +104B;MYANMAR SIGN SECTION;Po;0;L;;;;;N;;;;; +104C;MYANMAR SYMBOL LOCATIVE;Po;0;L;;;;;N;;;;; +104D;MYANMAR SYMBOL COMPLETED;Po;0;L;;;;;N;;;;; +104E;MYANMAR SYMBOL AFOREMENTIONED;Po;0;L;;;;;N;;;;; +104F;MYANMAR SYMBOL GENITIVE;Po;0;L;;;;;N;;;;; +1050;MYANMAR LETTER SHA;Lo;0;L;;;;;N;;;;; +1051;MYANMAR LETTER SSA;Lo;0;L;;;;;N;;;;; +1052;MYANMAR LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +1053;MYANMAR LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +1054;MYANMAR LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +1055;MYANMAR LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +1056;MYANMAR VOWEL SIGN VOCALIC R;Mc;0;L;;;;;N;;;;; +1057;MYANMAR VOWEL SIGN VOCALIC RR;Mc;0;L;;;;;N;;;;; +1058;MYANMAR VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +1059;MYANMAR VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +105A;MYANMAR LETTER MON NGA;Lo;0;L;;;;;N;;;;; +105B;MYANMAR LETTER MON JHA;Lo;0;L;;;;;N;;;;; +105C;MYANMAR LETTER MON BBA;Lo;0;L;;;;;N;;;;; +105D;MYANMAR LETTER MON BBE;Lo;0;L;;;;;N;;;;; +105E;MYANMAR CONSONANT SIGN MON MEDIAL NA;Mn;0;NSM;;;;;N;;;;; +105F;MYANMAR CONSONANT SIGN MON MEDIAL MA;Mn;0;NSM;;;;;N;;;;; +1060;MYANMAR CONSONANT SIGN MON MEDIAL LA;Mn;0;NSM;;;;;N;;;;; +1061;MYANMAR LETTER SGAW KAREN SHA;Lo;0;L;;;;;N;;;;; +1062;MYANMAR VOWEL SIGN SGAW KAREN EU;Mc;0;L;;;;;N;;;;; +1063;MYANMAR TONE MARK SGAW KAREN HATHI;Mc;0;L;;;;;N;;;;; +1064;MYANMAR TONE MARK SGAW KAREN KE PHO;Mc;0;L;;;;;N;;;;; +1065;MYANMAR LETTER WESTERN PWO KAREN THA;Lo;0;L;;;;;N;;;;; +1066;MYANMAR LETTER WESTERN PWO KAREN PWA;Lo;0;L;;;;;N;;;;; +1067;MYANMAR VOWEL SIGN WESTERN PWO KAREN EU;Mc;0;L;;;;;N;;;;; +1068;MYANMAR VOWEL SIGN WESTERN PWO KAREN UE;Mc;0;L;;;;;N;;;;; +1069;MYANMAR SIGN WESTERN PWO KAREN TONE-1;Mc;0;L;;;;;N;;;;; +106A;MYANMAR SIGN WESTERN PWO KAREN TONE-2;Mc;0;L;;;;;N;;;;; +106B;MYANMAR SIGN WESTERN PWO KAREN TONE-3;Mc;0;L;;;;;N;;;;; +106C;MYANMAR SIGN WESTERN PWO KAREN TONE-4;Mc;0;L;;;;;N;;;;; +106D;MYANMAR SIGN WESTERN PWO KAREN TONE-5;Mc;0;L;;;;;N;;;;; +106E;MYANMAR LETTER EASTERN PWO KAREN NNA;Lo;0;L;;;;;N;;;;; +106F;MYANMAR LETTER EASTERN PWO KAREN YWA;Lo;0;L;;;;;N;;;;; +1070;MYANMAR LETTER EASTERN PWO KAREN GHWA;Lo;0;L;;;;;N;;;;; +1071;MYANMAR VOWEL SIGN GEBA KAREN I;Mn;0;NSM;;;;;N;;;;; +1072;MYANMAR VOWEL SIGN KAYAH OE;Mn;0;NSM;;;;;N;;;;; +1073;MYANMAR VOWEL SIGN KAYAH U;Mn;0;NSM;;;;;N;;;;; +1074;MYANMAR VOWEL SIGN KAYAH EE;Mn;0;NSM;;;;;N;;;;; +1075;MYANMAR LETTER SHAN KA;Lo;0;L;;;;;N;;;;; +1076;MYANMAR LETTER SHAN KHA;Lo;0;L;;;;;N;;;;; +1077;MYANMAR LETTER SHAN GA;Lo;0;L;;;;;N;;;;; +1078;MYANMAR LETTER SHAN CA;Lo;0;L;;;;;N;;;;; +1079;MYANMAR LETTER SHAN ZA;Lo;0;L;;;;;N;;;;; +107A;MYANMAR LETTER SHAN NYA;Lo;0;L;;;;;N;;;;; +107B;MYANMAR LETTER SHAN DA;Lo;0;L;;;;;N;;;;; +107C;MYANMAR LETTER SHAN NA;Lo;0;L;;;;;N;;;;; +107D;MYANMAR LETTER SHAN PHA;Lo;0;L;;;;;N;;;;; +107E;MYANMAR LETTER SHAN FA;Lo;0;L;;;;;N;;;;; +107F;MYANMAR LETTER SHAN BA;Lo;0;L;;;;;N;;;;; +1080;MYANMAR LETTER SHAN THA;Lo;0;L;;;;;N;;;;; +1081;MYANMAR LETTER SHAN HA;Lo;0;L;;;;;N;;;;; +1082;MYANMAR CONSONANT SIGN SHAN MEDIAL WA;Mn;0;NSM;;;;;N;;;;; +1083;MYANMAR VOWEL SIGN SHAN AA;Mc;0;L;;;;;N;;;;; +1084;MYANMAR VOWEL SIGN SHAN E;Mc;0;L;;;;;N;;;;; +1085;MYANMAR VOWEL SIGN SHAN E ABOVE;Mn;0;NSM;;;;;N;;;;; +1086;MYANMAR VOWEL SIGN SHAN FINAL Y;Mn;0;NSM;;;;;N;;;;; +1087;MYANMAR SIGN SHAN TONE-2;Mc;0;L;;;;;N;;;;; +1088;MYANMAR SIGN SHAN TONE-3;Mc;0;L;;;;;N;;;;; +1089;MYANMAR SIGN SHAN TONE-5;Mc;0;L;;;;;N;;;;; +108A;MYANMAR SIGN SHAN TONE-6;Mc;0;L;;;;;N;;;;; +108B;MYANMAR SIGN SHAN COUNCIL TONE-2;Mc;0;L;;;;;N;;;;; +108C;MYANMAR SIGN SHAN COUNCIL TONE-3;Mc;0;L;;;;;N;;;;; +108D;MYANMAR SIGN SHAN COUNCIL EMPHATIC TONE;Mn;220;NSM;;;;;N;;;;; +108E;MYANMAR LETTER RUMAI PALAUNG FA;Lo;0;L;;;;;N;;;;; +108F;MYANMAR SIGN RUMAI PALAUNG TONE-5;Mc;0;L;;;;;N;;;;; +1090;MYANMAR SHAN DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1091;MYANMAR SHAN DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1092;MYANMAR SHAN DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1093;MYANMAR SHAN DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1094;MYANMAR SHAN DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1095;MYANMAR SHAN DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1096;MYANMAR SHAN DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1097;MYANMAR SHAN DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1098;MYANMAR SHAN DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1099;MYANMAR SHAN DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +109A;MYANMAR SIGN KHAMTI TONE-1;Mc;0;L;;;;;N;;;;; +109B;MYANMAR SIGN KHAMTI TONE-3;Mc;0;L;;;;;N;;;;; +109C;MYANMAR VOWEL SIGN AITON A;Mc;0;L;;;;;N;;;;; +109D;MYANMAR VOWEL SIGN AITON AI;Mn;0;NSM;;;;;N;;;;; +109E;MYANMAR SYMBOL SHAN ONE;So;0;L;;;;;N;;;;; +109F;MYANMAR SYMBOL SHAN EXCLAMATION;So;0;L;;;;;N;;;;; +10A0;GEORGIAN CAPITAL LETTER AN;Lu;0;L;;;;;N;;;;2D00; +10A1;GEORGIAN CAPITAL LETTER BAN;Lu;0;L;;;;;N;;;;2D01; +10A2;GEORGIAN CAPITAL LETTER GAN;Lu;0;L;;;;;N;;;;2D02; +10A3;GEORGIAN CAPITAL LETTER DON;Lu;0;L;;;;;N;;;;2D03; +10A4;GEORGIAN CAPITAL LETTER EN;Lu;0;L;;;;;N;;;;2D04; +10A5;GEORGIAN CAPITAL LETTER VIN;Lu;0;L;;;;;N;;;;2D05; +10A6;GEORGIAN CAPITAL LETTER ZEN;Lu;0;L;;;;;N;;;;2D06; +10A7;GEORGIAN CAPITAL LETTER TAN;Lu;0;L;;;;;N;;;;2D07; +10A8;GEORGIAN CAPITAL LETTER IN;Lu;0;L;;;;;N;;;;2D08; +10A9;GEORGIAN CAPITAL LETTER KAN;Lu;0;L;;;;;N;;;;2D09; +10AA;GEORGIAN CAPITAL LETTER LAS;Lu;0;L;;;;;N;;;;2D0A; +10AB;GEORGIAN CAPITAL LETTER MAN;Lu;0;L;;;;;N;;;;2D0B; +10AC;GEORGIAN CAPITAL LETTER NAR;Lu;0;L;;;;;N;;;;2D0C; +10AD;GEORGIAN CAPITAL LETTER ON;Lu;0;L;;;;;N;;;;2D0D; +10AE;GEORGIAN CAPITAL LETTER PAR;Lu;0;L;;;;;N;;;;2D0E; +10AF;GEORGIAN CAPITAL LETTER ZHAR;Lu;0;L;;;;;N;;;;2D0F; +10B0;GEORGIAN CAPITAL LETTER RAE;Lu;0;L;;;;;N;;;;2D10; +10B1;GEORGIAN CAPITAL LETTER SAN;Lu;0;L;;;;;N;;;;2D11; +10B2;GEORGIAN CAPITAL LETTER TAR;Lu;0;L;;;;;N;;;;2D12; +10B3;GEORGIAN CAPITAL LETTER UN;Lu;0;L;;;;;N;;;;2D13; +10B4;GEORGIAN CAPITAL LETTER PHAR;Lu;0;L;;;;;N;;;;2D14; +10B5;GEORGIAN CAPITAL LETTER KHAR;Lu;0;L;;;;;N;;;;2D15; +10B6;GEORGIAN CAPITAL LETTER GHAN;Lu;0;L;;;;;N;;;;2D16; +10B7;GEORGIAN CAPITAL LETTER QAR;Lu;0;L;;;;;N;;;;2D17; +10B8;GEORGIAN CAPITAL LETTER SHIN;Lu;0;L;;;;;N;;;;2D18; +10B9;GEORGIAN CAPITAL LETTER CHIN;Lu;0;L;;;;;N;;;;2D19; +10BA;GEORGIAN CAPITAL LETTER CAN;Lu;0;L;;;;;N;;;;2D1A; +10BB;GEORGIAN CAPITAL LETTER JIL;Lu;0;L;;;;;N;;;;2D1B; +10BC;GEORGIAN CAPITAL LETTER CIL;Lu;0;L;;;;;N;;;;2D1C; +10BD;GEORGIAN CAPITAL LETTER CHAR;Lu;0;L;;;;;N;;;;2D1D; +10BE;GEORGIAN CAPITAL LETTER XAN;Lu;0;L;;;;;N;;;;2D1E; +10BF;GEORGIAN CAPITAL LETTER JHAN;Lu;0;L;;;;;N;;;;2D1F; +10C0;GEORGIAN CAPITAL LETTER HAE;Lu;0;L;;;;;N;;;;2D20; +10C1;GEORGIAN CAPITAL LETTER HE;Lu;0;L;;;;;N;;;;2D21; +10C2;GEORGIAN CAPITAL LETTER HIE;Lu;0;L;;;;;N;;;;2D22; +10C3;GEORGIAN CAPITAL LETTER WE;Lu;0;L;;;;;N;;;;2D23; +10C4;GEORGIAN CAPITAL LETTER HAR;Lu;0;L;;;;;N;;;;2D24; +10C5;GEORGIAN CAPITAL LETTER HOE;Lu;0;L;;;;;N;;;;2D25; +10C7;GEORGIAN CAPITAL LETTER YN;Lu;0;L;;;;;N;;;;2D27; +10CD;GEORGIAN CAPITAL LETTER AEN;Lu;0;L;;;;;N;;;;2D2D; +10D0;GEORGIAN LETTER AN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER AN;;;; +10D1;GEORGIAN LETTER BAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER BAN;;;; +10D2;GEORGIAN LETTER GAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER GAN;;;; +10D3;GEORGIAN LETTER DON;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER DON;;;; +10D4;GEORGIAN LETTER EN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER EN;;;; +10D5;GEORGIAN LETTER VIN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER VIN;;;; +10D6;GEORGIAN LETTER ZEN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER ZEN;;;; +10D7;GEORGIAN LETTER TAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER TAN;;;; +10D8;GEORGIAN LETTER IN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER IN;;;; +10D9;GEORGIAN LETTER KAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER KAN;;;; +10DA;GEORGIAN LETTER LAS;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER LAS;;;; +10DB;GEORGIAN LETTER MAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER MAN;;;; +10DC;GEORGIAN LETTER NAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER NAR;;;; +10DD;GEORGIAN LETTER ON;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER ON;;;; +10DE;GEORGIAN LETTER PAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER PAR;;;; +10DF;GEORGIAN LETTER ZHAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER ZHAR;;;; +10E0;GEORGIAN LETTER RAE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER RAE;;;; +10E1;GEORGIAN LETTER SAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER SAN;;;; +10E2;GEORGIAN LETTER TAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER TAR;;;; +10E3;GEORGIAN LETTER UN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER UN;;;; +10E4;GEORGIAN LETTER PHAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER PHAR;;;; +10E5;GEORGIAN LETTER KHAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER KHAR;;;; +10E6;GEORGIAN LETTER GHAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER GHAN;;;; +10E7;GEORGIAN LETTER QAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER QAR;;;; +10E8;GEORGIAN LETTER SHIN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER SHIN;;;; +10E9;GEORGIAN LETTER CHIN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER CHIN;;;; +10EA;GEORGIAN LETTER CAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER CAN;;;; +10EB;GEORGIAN LETTER JIL;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER JIL;;;; +10EC;GEORGIAN LETTER CIL;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER CIL;;;; +10ED;GEORGIAN LETTER CHAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER CHAR;;;; +10EE;GEORGIAN LETTER XAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER XAN;;;; +10EF;GEORGIAN LETTER JHAN;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER JHAN;;;; +10F0;GEORGIAN LETTER HAE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HAE;;;; +10F1;GEORGIAN LETTER HE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HE;;;; +10F2;GEORGIAN LETTER HIE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HIE;;;; +10F3;GEORGIAN LETTER WE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER WE;;;; +10F4;GEORGIAN LETTER HAR;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HAR;;;; +10F5;GEORGIAN LETTER HOE;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER HOE;;;; +10F6;GEORGIAN LETTER FI;Lo;0;L;;;;;N;GEORGIAN SMALL LETTER FI;;;; +10F7;GEORGIAN LETTER YN;Lo;0;L;;;;;N;;;;; +10F8;GEORGIAN LETTER ELIFI;Lo;0;L;;;;;N;;;;; +10F9;GEORGIAN LETTER TURNED GAN;Lo;0;L;;;;;N;;;;; +10FA;GEORGIAN LETTER AIN;Lo;0;L;;;;;N;;;;; +10FB;GEORGIAN PARAGRAPH SEPARATOR;Po;0;L;;;;;N;;;;; +10FC;MODIFIER LETTER GEORGIAN NAR;Lm;0;L; 10DC;;;;N;;;;; +10FD;GEORGIAN LETTER AEN;Lo;0;L;;;;;N;;;;; +10FE;GEORGIAN LETTER HARD SIGN;Lo;0;L;;;;;N;;;;; +10FF;GEORGIAN LETTER LABIAL SIGN;Lo;0;L;;;;;N;;;;; +1100;HANGUL CHOSEONG KIYEOK;Lo;0;L;;;;;N;;;;; +1101;HANGUL CHOSEONG SSANGKIYEOK;Lo;0;L;;;;;N;;;;; +1102;HANGUL CHOSEONG NIEUN;Lo;0;L;;;;;N;;;;; +1103;HANGUL CHOSEONG TIKEUT;Lo;0;L;;;;;N;;;;; +1104;HANGUL CHOSEONG SSANGTIKEUT;Lo;0;L;;;;;N;;;;; +1105;HANGUL CHOSEONG RIEUL;Lo;0;L;;;;;N;;;;; +1106;HANGUL CHOSEONG MIEUM;Lo;0;L;;;;;N;;;;; +1107;HANGUL CHOSEONG PIEUP;Lo;0;L;;;;;N;;;;; +1108;HANGUL CHOSEONG SSANGPIEUP;Lo;0;L;;;;;N;;;;; +1109;HANGUL CHOSEONG SIOS;Lo;0;L;;;;;N;;;;; +110A;HANGUL CHOSEONG SSANGSIOS;Lo;0;L;;;;;N;;;;; +110B;HANGUL CHOSEONG IEUNG;Lo;0;L;;;;;N;;;;; +110C;HANGUL CHOSEONG CIEUC;Lo;0;L;;;;;N;;;;; +110D;HANGUL CHOSEONG SSANGCIEUC;Lo;0;L;;;;;N;;;;; +110E;HANGUL CHOSEONG CHIEUCH;Lo;0;L;;;;;N;;;;; +110F;HANGUL CHOSEONG KHIEUKH;Lo;0;L;;;;;N;;;;; +1110;HANGUL CHOSEONG THIEUTH;Lo;0;L;;;;;N;;;;; +1111;HANGUL CHOSEONG PHIEUPH;Lo;0;L;;;;;N;;;;; +1112;HANGUL CHOSEONG HIEUH;Lo;0;L;;;;;N;;;;; +1113;HANGUL CHOSEONG NIEUN-KIYEOK;Lo;0;L;;;;;N;;;;; +1114;HANGUL CHOSEONG SSANGNIEUN;Lo;0;L;;;;;N;;;;; +1115;HANGUL CHOSEONG NIEUN-TIKEUT;Lo;0;L;;;;;N;;;;; +1116;HANGUL CHOSEONG NIEUN-PIEUP;Lo;0;L;;;;;N;;;;; +1117;HANGUL CHOSEONG TIKEUT-KIYEOK;Lo;0;L;;;;;N;;;;; +1118;HANGUL CHOSEONG RIEUL-NIEUN;Lo;0;L;;;;;N;;;;; +1119;HANGUL CHOSEONG SSANGRIEUL;Lo;0;L;;;;;N;;;;; +111A;HANGUL CHOSEONG RIEUL-HIEUH;Lo;0;L;;;;;N;;;;; +111B;HANGUL CHOSEONG KAPYEOUNRIEUL;Lo;0;L;;;;;N;;;;; +111C;HANGUL CHOSEONG MIEUM-PIEUP;Lo;0;L;;;;;N;;;;; +111D;HANGUL CHOSEONG KAPYEOUNMIEUM;Lo;0;L;;;;;N;;;;; +111E;HANGUL CHOSEONG PIEUP-KIYEOK;Lo;0;L;;;;;N;;;;; +111F;HANGUL CHOSEONG PIEUP-NIEUN;Lo;0;L;;;;;N;;;;; +1120;HANGUL CHOSEONG PIEUP-TIKEUT;Lo;0;L;;;;;N;;;;; +1121;HANGUL CHOSEONG PIEUP-SIOS;Lo;0;L;;;;;N;;;;; +1122;HANGUL CHOSEONG PIEUP-SIOS-KIYEOK;Lo;0;L;;;;;N;;;;; +1123;HANGUL CHOSEONG PIEUP-SIOS-TIKEUT;Lo;0;L;;;;;N;;;;; +1124;HANGUL CHOSEONG PIEUP-SIOS-PIEUP;Lo;0;L;;;;;N;;;;; +1125;HANGUL CHOSEONG PIEUP-SSANGSIOS;Lo;0;L;;;;;N;;;;; +1126;HANGUL CHOSEONG PIEUP-SIOS-CIEUC;Lo;0;L;;;;;N;;;;; +1127;HANGUL CHOSEONG PIEUP-CIEUC;Lo;0;L;;;;;N;;;;; +1128;HANGUL CHOSEONG PIEUP-CHIEUCH;Lo;0;L;;;;;N;;;;; +1129;HANGUL CHOSEONG PIEUP-THIEUTH;Lo;0;L;;;;;N;;;;; +112A;HANGUL CHOSEONG PIEUP-PHIEUPH;Lo;0;L;;;;;N;;;;; +112B;HANGUL CHOSEONG KAPYEOUNPIEUP;Lo;0;L;;;;;N;;;;; +112C;HANGUL CHOSEONG KAPYEOUNSSANGPIEUP;Lo;0;L;;;;;N;;;;; +112D;HANGUL CHOSEONG SIOS-KIYEOK;Lo;0;L;;;;;N;;;;; +112E;HANGUL CHOSEONG SIOS-NIEUN;Lo;0;L;;;;;N;;;;; +112F;HANGUL CHOSEONG SIOS-TIKEUT;Lo;0;L;;;;;N;;;;; +1130;HANGUL CHOSEONG SIOS-RIEUL;Lo;0;L;;;;;N;;;;; +1131;HANGUL CHOSEONG SIOS-MIEUM;Lo;0;L;;;;;N;;;;; +1132;HANGUL CHOSEONG SIOS-PIEUP;Lo;0;L;;;;;N;;;;; +1133;HANGUL CHOSEONG SIOS-PIEUP-KIYEOK;Lo;0;L;;;;;N;;;;; +1134;HANGUL CHOSEONG SIOS-SSANGSIOS;Lo;0;L;;;;;N;;;;; +1135;HANGUL CHOSEONG SIOS-IEUNG;Lo;0;L;;;;;N;;;;; +1136;HANGUL CHOSEONG SIOS-CIEUC;Lo;0;L;;;;;N;;;;; +1137;HANGUL CHOSEONG SIOS-CHIEUCH;Lo;0;L;;;;;N;;;;; +1138;HANGUL CHOSEONG SIOS-KHIEUKH;Lo;0;L;;;;;N;;;;; +1139;HANGUL CHOSEONG SIOS-THIEUTH;Lo;0;L;;;;;N;;;;; +113A;HANGUL CHOSEONG SIOS-PHIEUPH;Lo;0;L;;;;;N;;;;; +113B;HANGUL CHOSEONG SIOS-HIEUH;Lo;0;L;;;;;N;;;;; +113C;HANGUL CHOSEONG CHITUEUMSIOS;Lo;0;L;;;;;N;;;;; +113D;HANGUL CHOSEONG CHITUEUMSSANGSIOS;Lo;0;L;;;;;N;;;;; +113E;HANGUL CHOSEONG CEONGCHIEUMSIOS;Lo;0;L;;;;;N;;;;; +113F;HANGUL CHOSEONG CEONGCHIEUMSSANGSIOS;Lo;0;L;;;;;N;;;;; +1140;HANGUL CHOSEONG PANSIOS;Lo;0;L;;;;;N;;;;; +1141;HANGUL CHOSEONG IEUNG-KIYEOK;Lo;0;L;;;;;N;;;;; +1142;HANGUL CHOSEONG IEUNG-TIKEUT;Lo;0;L;;;;;N;;;;; +1143;HANGUL CHOSEONG IEUNG-MIEUM;Lo;0;L;;;;;N;;;;; +1144;HANGUL CHOSEONG IEUNG-PIEUP;Lo;0;L;;;;;N;;;;; +1145;HANGUL CHOSEONG IEUNG-SIOS;Lo;0;L;;;;;N;;;;; +1146;HANGUL CHOSEONG IEUNG-PANSIOS;Lo;0;L;;;;;N;;;;; +1147;HANGUL CHOSEONG SSANGIEUNG;Lo;0;L;;;;;N;;;;; +1148;HANGUL CHOSEONG IEUNG-CIEUC;Lo;0;L;;;;;N;;;;; +1149;HANGUL CHOSEONG IEUNG-CHIEUCH;Lo;0;L;;;;;N;;;;; +114A;HANGUL CHOSEONG IEUNG-THIEUTH;Lo;0;L;;;;;N;;;;; +114B;HANGUL CHOSEONG IEUNG-PHIEUPH;Lo;0;L;;;;;N;;;;; +114C;HANGUL CHOSEONG YESIEUNG;Lo;0;L;;;;;N;;;;; +114D;HANGUL CHOSEONG CIEUC-IEUNG;Lo;0;L;;;;;N;;;;; +114E;HANGUL CHOSEONG CHITUEUMCIEUC;Lo;0;L;;;;;N;;;;; +114F;HANGUL CHOSEONG CHITUEUMSSANGCIEUC;Lo;0;L;;;;;N;;;;; +1150;HANGUL CHOSEONG CEONGCHIEUMCIEUC;Lo;0;L;;;;;N;;;;; +1151;HANGUL CHOSEONG CEONGCHIEUMSSANGCIEUC;Lo;0;L;;;;;N;;;;; +1152;HANGUL CHOSEONG CHIEUCH-KHIEUKH;Lo;0;L;;;;;N;;;;; +1153;HANGUL CHOSEONG CHIEUCH-HIEUH;Lo;0;L;;;;;N;;;;; +1154;HANGUL CHOSEONG CHITUEUMCHIEUCH;Lo;0;L;;;;;N;;;;; +1155;HANGUL CHOSEONG CEONGCHIEUMCHIEUCH;Lo;0;L;;;;;N;;;;; +1156;HANGUL CHOSEONG PHIEUPH-PIEUP;Lo;0;L;;;;;N;;;;; +1157;HANGUL CHOSEONG KAPYEOUNPHIEUPH;Lo;0;L;;;;;N;;;;; +1158;HANGUL CHOSEONG SSANGHIEUH;Lo;0;L;;;;;N;;;;; +1159;HANGUL CHOSEONG YEORINHIEUH;Lo;0;L;;;;;N;;;;; +115A;HANGUL CHOSEONG KIYEOK-TIKEUT;Lo;0;L;;;;;N;;;;; +115B;HANGUL CHOSEONG NIEUN-SIOS;Lo;0;L;;;;;N;;;;; +115C;HANGUL CHOSEONG NIEUN-CIEUC;Lo;0;L;;;;;N;;;;; +115D;HANGUL CHOSEONG NIEUN-HIEUH;Lo;0;L;;;;;N;;;;; +115E;HANGUL CHOSEONG TIKEUT-RIEUL;Lo;0;L;;;;;N;;;;; +115F;HANGUL CHOSEONG FILLER;Lo;0;L;;;;;N;;;;; +1160;HANGUL JUNGSEONG FILLER;Lo;0;L;;;;;N;;;;; +1161;HANGUL JUNGSEONG A;Lo;0;L;;;;;N;;;;; +1162;HANGUL JUNGSEONG AE;Lo;0;L;;;;;N;;;;; +1163;HANGUL JUNGSEONG YA;Lo;0;L;;;;;N;;;;; +1164;HANGUL JUNGSEONG YAE;Lo;0;L;;;;;N;;;;; +1165;HANGUL JUNGSEONG EO;Lo;0;L;;;;;N;;;;; +1166;HANGUL JUNGSEONG E;Lo;0;L;;;;;N;;;;; +1167;HANGUL JUNGSEONG YEO;Lo;0;L;;;;;N;;;;; +1168;HANGUL JUNGSEONG YE;Lo;0;L;;;;;N;;;;; +1169;HANGUL JUNGSEONG O;Lo;0;L;;;;;N;;;;; +116A;HANGUL JUNGSEONG WA;Lo;0;L;;;;;N;;;;; +116B;HANGUL JUNGSEONG WAE;Lo;0;L;;;;;N;;;;; +116C;HANGUL JUNGSEONG OE;Lo;0;L;;;;;N;;;;; +116D;HANGUL JUNGSEONG YO;Lo;0;L;;;;;N;;;;; +116E;HANGUL JUNGSEONG U;Lo;0;L;;;;;N;;;;; +116F;HANGUL JUNGSEONG WEO;Lo;0;L;;;;;N;;;;; +1170;HANGUL JUNGSEONG WE;Lo;0;L;;;;;N;;;;; +1171;HANGUL JUNGSEONG WI;Lo;0;L;;;;;N;;;;; +1172;HANGUL JUNGSEONG YU;Lo;0;L;;;;;N;;;;; +1173;HANGUL JUNGSEONG EU;Lo;0;L;;;;;N;;;;; +1174;HANGUL JUNGSEONG YI;Lo;0;L;;;;;N;;;;; +1175;HANGUL JUNGSEONG I;Lo;0;L;;;;;N;;;;; +1176;HANGUL JUNGSEONG A-O;Lo;0;L;;;;;N;;;;; +1177;HANGUL JUNGSEONG A-U;Lo;0;L;;;;;N;;;;; +1178;HANGUL JUNGSEONG YA-O;Lo;0;L;;;;;N;;;;; +1179;HANGUL JUNGSEONG YA-YO;Lo;0;L;;;;;N;;;;; +117A;HANGUL JUNGSEONG EO-O;Lo;0;L;;;;;N;;;;; +117B;HANGUL JUNGSEONG EO-U;Lo;0;L;;;;;N;;;;; +117C;HANGUL JUNGSEONG EO-EU;Lo;0;L;;;;;N;;;;; +117D;HANGUL JUNGSEONG YEO-O;Lo;0;L;;;;;N;;;;; +117E;HANGUL JUNGSEONG YEO-U;Lo;0;L;;;;;N;;;;; +117F;HANGUL JUNGSEONG O-EO;Lo;0;L;;;;;N;;;;; +1180;HANGUL JUNGSEONG O-E;Lo;0;L;;;;;N;;;;; +1181;HANGUL JUNGSEONG O-YE;Lo;0;L;;;;;N;;;;; +1182;HANGUL JUNGSEONG O-O;Lo;0;L;;;;;N;;;;; +1183;HANGUL JUNGSEONG O-U;Lo;0;L;;;;;N;;;;; +1184;HANGUL JUNGSEONG YO-YA;Lo;0;L;;;;;N;;;;; +1185;HANGUL JUNGSEONG YO-YAE;Lo;0;L;;;;;N;;;;; +1186;HANGUL JUNGSEONG YO-YEO;Lo;0;L;;;;;N;;;;; +1187;HANGUL JUNGSEONG YO-O;Lo;0;L;;;;;N;;;;; +1188;HANGUL JUNGSEONG YO-I;Lo;0;L;;;;;N;;;;; +1189;HANGUL JUNGSEONG U-A;Lo;0;L;;;;;N;;;;; +118A;HANGUL JUNGSEONG U-AE;Lo;0;L;;;;;N;;;;; +118B;HANGUL JUNGSEONG U-EO-EU;Lo;0;L;;;;;N;;;;; +118C;HANGUL JUNGSEONG U-YE;Lo;0;L;;;;;N;;;;; +118D;HANGUL JUNGSEONG U-U;Lo;0;L;;;;;N;;;;; +118E;HANGUL JUNGSEONG YU-A;Lo;0;L;;;;;N;;;;; +118F;HANGUL JUNGSEONG YU-EO;Lo;0;L;;;;;N;;;;; +1190;HANGUL JUNGSEONG YU-E;Lo;0;L;;;;;N;;;;; +1191;HANGUL JUNGSEONG YU-YEO;Lo;0;L;;;;;N;;;;; +1192;HANGUL JUNGSEONG YU-YE;Lo;0;L;;;;;N;;;;; +1193;HANGUL JUNGSEONG YU-U;Lo;0;L;;;;;N;;;;; +1194;HANGUL JUNGSEONG YU-I;Lo;0;L;;;;;N;;;;; +1195;HANGUL JUNGSEONG EU-U;Lo;0;L;;;;;N;;;;; +1196;HANGUL JUNGSEONG EU-EU;Lo;0;L;;;;;N;;;;; +1197;HANGUL JUNGSEONG YI-U;Lo;0;L;;;;;N;;;;; +1198;HANGUL JUNGSEONG I-A;Lo;0;L;;;;;N;;;;; +1199;HANGUL JUNGSEONG I-YA;Lo;0;L;;;;;N;;;;; +119A;HANGUL JUNGSEONG I-O;Lo;0;L;;;;;N;;;;; +119B;HANGUL JUNGSEONG I-U;Lo;0;L;;;;;N;;;;; +119C;HANGUL JUNGSEONG I-EU;Lo;0;L;;;;;N;;;;; +119D;HANGUL JUNGSEONG I-ARAEA;Lo;0;L;;;;;N;;;;; +119E;HANGUL JUNGSEONG ARAEA;Lo;0;L;;;;;N;;;;; +119F;HANGUL JUNGSEONG ARAEA-EO;Lo;0;L;;;;;N;;;;; +11A0;HANGUL JUNGSEONG ARAEA-U;Lo;0;L;;;;;N;;;;; +11A1;HANGUL JUNGSEONG ARAEA-I;Lo;0;L;;;;;N;;;;; +11A2;HANGUL JUNGSEONG SSANGARAEA;Lo;0;L;;;;;N;;;;; +11A3;HANGUL JUNGSEONG A-EU;Lo;0;L;;;;;N;;;;; +11A4;HANGUL JUNGSEONG YA-U;Lo;0;L;;;;;N;;;;; +11A5;HANGUL JUNGSEONG YEO-YA;Lo;0;L;;;;;N;;;;; +11A6;HANGUL JUNGSEONG O-YA;Lo;0;L;;;;;N;;;;; +11A7;HANGUL JUNGSEONG O-YAE;Lo;0;L;;;;;N;;;;; +11A8;HANGUL JONGSEONG KIYEOK;Lo;0;L;;;;;N;;;;; +11A9;HANGUL JONGSEONG SSANGKIYEOK;Lo;0;L;;;;;N;;;;; +11AA;HANGUL JONGSEONG KIYEOK-SIOS;Lo;0;L;;;;;N;;;;; +11AB;HANGUL JONGSEONG NIEUN;Lo;0;L;;;;;N;;;;; +11AC;HANGUL JONGSEONG NIEUN-CIEUC;Lo;0;L;;;;;N;;;;; +11AD;HANGUL JONGSEONG NIEUN-HIEUH;Lo;0;L;;;;;N;;;;; +11AE;HANGUL JONGSEONG TIKEUT;Lo;0;L;;;;;N;;;;; +11AF;HANGUL JONGSEONG RIEUL;Lo;0;L;;;;;N;;;;; +11B0;HANGUL JONGSEONG RIEUL-KIYEOK;Lo;0;L;;;;;N;;;;; +11B1;HANGUL JONGSEONG RIEUL-MIEUM;Lo;0;L;;;;;N;;;;; +11B2;HANGUL JONGSEONG RIEUL-PIEUP;Lo;0;L;;;;;N;;;;; +11B3;HANGUL JONGSEONG RIEUL-SIOS;Lo;0;L;;;;;N;;;;; +11B4;HANGUL JONGSEONG RIEUL-THIEUTH;Lo;0;L;;;;;N;;;;; +11B5;HANGUL JONGSEONG RIEUL-PHIEUPH;Lo;0;L;;;;;N;;;;; +11B6;HANGUL JONGSEONG RIEUL-HIEUH;Lo;0;L;;;;;N;;;;; +11B7;HANGUL JONGSEONG MIEUM;Lo;0;L;;;;;N;;;;; +11B8;HANGUL JONGSEONG PIEUP;Lo;0;L;;;;;N;;;;; +11B9;HANGUL JONGSEONG PIEUP-SIOS;Lo;0;L;;;;;N;;;;; +11BA;HANGUL JONGSEONG SIOS;Lo;0;L;;;;;N;;;;; +11BB;HANGUL JONGSEONG SSANGSIOS;Lo;0;L;;;;;N;;;;; +11BC;HANGUL JONGSEONG IEUNG;Lo;0;L;;;;;N;;;;; +11BD;HANGUL JONGSEONG CIEUC;Lo;0;L;;;;;N;;;;; +11BE;HANGUL JONGSEONG CHIEUCH;Lo;0;L;;;;;N;;;;; +11BF;HANGUL JONGSEONG KHIEUKH;Lo;0;L;;;;;N;;;;; +11C0;HANGUL JONGSEONG THIEUTH;Lo;0;L;;;;;N;;;;; +11C1;HANGUL JONGSEONG PHIEUPH;Lo;0;L;;;;;N;;;;; +11C2;HANGUL JONGSEONG HIEUH;Lo;0;L;;;;;N;;;;; +11C3;HANGUL JONGSEONG KIYEOK-RIEUL;Lo;0;L;;;;;N;;;;; +11C4;HANGUL JONGSEONG KIYEOK-SIOS-KIYEOK;Lo;0;L;;;;;N;;;;; +11C5;HANGUL JONGSEONG NIEUN-KIYEOK;Lo;0;L;;;;;N;;;;; +11C6;HANGUL JONGSEONG NIEUN-TIKEUT;Lo;0;L;;;;;N;;;;; +11C7;HANGUL JONGSEONG NIEUN-SIOS;Lo;0;L;;;;;N;;;;; +11C8;HANGUL JONGSEONG NIEUN-PANSIOS;Lo;0;L;;;;;N;;;;; +11C9;HANGUL JONGSEONG NIEUN-THIEUTH;Lo;0;L;;;;;N;;;;; +11CA;HANGUL JONGSEONG TIKEUT-KIYEOK;Lo;0;L;;;;;N;;;;; +11CB;HANGUL JONGSEONG TIKEUT-RIEUL;Lo;0;L;;;;;N;;;;; +11CC;HANGUL JONGSEONG RIEUL-KIYEOK-SIOS;Lo;0;L;;;;;N;;;;; +11CD;HANGUL JONGSEONG RIEUL-NIEUN;Lo;0;L;;;;;N;;;;; +11CE;HANGUL JONGSEONG RIEUL-TIKEUT;Lo;0;L;;;;;N;;;;; +11CF;HANGUL JONGSEONG RIEUL-TIKEUT-HIEUH;Lo;0;L;;;;;N;;;;; +11D0;HANGUL JONGSEONG SSANGRIEUL;Lo;0;L;;;;;N;;;;; +11D1;HANGUL JONGSEONG RIEUL-MIEUM-KIYEOK;Lo;0;L;;;;;N;;;;; +11D2;HANGUL JONGSEONG RIEUL-MIEUM-SIOS;Lo;0;L;;;;;N;;;;; +11D3;HANGUL JONGSEONG RIEUL-PIEUP-SIOS;Lo;0;L;;;;;N;;;;; +11D4;HANGUL JONGSEONG RIEUL-PIEUP-HIEUH;Lo;0;L;;;;;N;;;;; +11D5;HANGUL JONGSEONG RIEUL-KAPYEOUNPIEUP;Lo;0;L;;;;;N;;;;; +11D6;HANGUL JONGSEONG RIEUL-SSANGSIOS;Lo;0;L;;;;;N;;;;; +11D7;HANGUL JONGSEONG RIEUL-PANSIOS;Lo;0;L;;;;;N;;;;; +11D8;HANGUL JONGSEONG RIEUL-KHIEUKH;Lo;0;L;;;;;N;;;;; +11D9;HANGUL JONGSEONG RIEUL-YEORINHIEUH;Lo;0;L;;;;;N;;;;; +11DA;HANGUL JONGSEONG MIEUM-KIYEOK;Lo;0;L;;;;;N;;;;; +11DB;HANGUL JONGSEONG MIEUM-RIEUL;Lo;0;L;;;;;N;;;;; +11DC;HANGUL JONGSEONG MIEUM-PIEUP;Lo;0;L;;;;;N;;;;; +11DD;HANGUL JONGSEONG MIEUM-SIOS;Lo;0;L;;;;;N;;;;; +11DE;HANGUL JONGSEONG MIEUM-SSANGSIOS;Lo;0;L;;;;;N;;;;; +11DF;HANGUL JONGSEONG MIEUM-PANSIOS;Lo;0;L;;;;;N;;;;; +11E0;HANGUL JONGSEONG MIEUM-CHIEUCH;Lo;0;L;;;;;N;;;;; +11E1;HANGUL JONGSEONG MIEUM-HIEUH;Lo;0;L;;;;;N;;;;; +11E2;HANGUL JONGSEONG KAPYEOUNMIEUM;Lo;0;L;;;;;N;;;;; +11E3;HANGUL JONGSEONG PIEUP-RIEUL;Lo;0;L;;;;;N;;;;; +11E4;HANGUL JONGSEONG PIEUP-PHIEUPH;Lo;0;L;;;;;N;;;;; +11E5;HANGUL JONGSEONG PIEUP-HIEUH;Lo;0;L;;;;;N;;;;; +11E6;HANGUL JONGSEONG KAPYEOUNPIEUP;Lo;0;L;;;;;N;;;;; +11E7;HANGUL JONGSEONG SIOS-KIYEOK;Lo;0;L;;;;;N;;;;; +11E8;HANGUL JONGSEONG SIOS-TIKEUT;Lo;0;L;;;;;N;;;;; +11E9;HANGUL JONGSEONG SIOS-RIEUL;Lo;0;L;;;;;N;;;;; +11EA;HANGUL JONGSEONG SIOS-PIEUP;Lo;0;L;;;;;N;;;;; +11EB;HANGUL JONGSEONG PANSIOS;Lo;0;L;;;;;N;;;;; +11EC;HANGUL JONGSEONG IEUNG-KIYEOK;Lo;0;L;;;;;N;;;;; +11ED;HANGUL JONGSEONG IEUNG-SSANGKIYEOK;Lo;0;L;;;;;N;;;;; +11EE;HANGUL JONGSEONG SSANGIEUNG;Lo;0;L;;;;;N;;;;; +11EF;HANGUL JONGSEONG IEUNG-KHIEUKH;Lo;0;L;;;;;N;;;;; +11F0;HANGUL JONGSEONG YESIEUNG;Lo;0;L;;;;;N;;;;; +11F1;HANGUL JONGSEONG YESIEUNG-SIOS;Lo;0;L;;;;;N;;;;; +11F2;HANGUL JONGSEONG YESIEUNG-PANSIOS;Lo;0;L;;;;;N;;;;; +11F3;HANGUL JONGSEONG PHIEUPH-PIEUP;Lo;0;L;;;;;N;;;;; +11F4;HANGUL JONGSEONG KAPYEOUNPHIEUPH;Lo;0;L;;;;;N;;;;; +11F5;HANGUL JONGSEONG HIEUH-NIEUN;Lo;0;L;;;;;N;;;;; +11F6;HANGUL JONGSEONG HIEUH-RIEUL;Lo;0;L;;;;;N;;;;; +11F7;HANGUL JONGSEONG HIEUH-MIEUM;Lo;0;L;;;;;N;;;;; +11F8;HANGUL JONGSEONG HIEUH-PIEUP;Lo;0;L;;;;;N;;;;; +11F9;HANGUL JONGSEONG YEORINHIEUH;Lo;0;L;;;;;N;;;;; +11FA;HANGUL JONGSEONG KIYEOK-NIEUN;Lo;0;L;;;;;N;;;;; +11FB;HANGUL JONGSEONG KIYEOK-PIEUP;Lo;0;L;;;;;N;;;;; +11FC;HANGUL JONGSEONG KIYEOK-CHIEUCH;Lo;0;L;;;;;N;;;;; +11FD;HANGUL JONGSEONG KIYEOK-KHIEUKH;Lo;0;L;;;;;N;;;;; +11FE;HANGUL JONGSEONG KIYEOK-HIEUH;Lo;0;L;;;;;N;;;;; +11FF;HANGUL JONGSEONG SSANGNIEUN;Lo;0;L;;;;;N;;;;; +1200;ETHIOPIC SYLLABLE HA;Lo;0;L;;;;;N;;;;; +1201;ETHIOPIC SYLLABLE HU;Lo;0;L;;;;;N;;;;; +1202;ETHIOPIC SYLLABLE HI;Lo;0;L;;;;;N;;;;; +1203;ETHIOPIC SYLLABLE HAA;Lo;0;L;;;;;N;;;;; +1204;ETHIOPIC SYLLABLE HEE;Lo;0;L;;;;;N;;;;; +1205;ETHIOPIC SYLLABLE HE;Lo;0;L;;;;;N;;;;; +1206;ETHIOPIC SYLLABLE HO;Lo;0;L;;;;;N;;;;; +1207;ETHIOPIC SYLLABLE HOA;Lo;0;L;;;;;N;;;;; +1208;ETHIOPIC SYLLABLE LA;Lo;0;L;;;;;N;;;;; +1209;ETHIOPIC SYLLABLE LU;Lo;0;L;;;;;N;;;;; +120A;ETHIOPIC SYLLABLE LI;Lo;0;L;;;;;N;;;;; +120B;ETHIOPIC SYLLABLE LAA;Lo;0;L;;;;;N;;;;; +120C;ETHIOPIC SYLLABLE LEE;Lo;0;L;;;;;N;;;;; +120D;ETHIOPIC SYLLABLE LE;Lo;0;L;;;;;N;;;;; +120E;ETHIOPIC SYLLABLE LO;Lo;0;L;;;;;N;;;;; +120F;ETHIOPIC SYLLABLE LWA;Lo;0;L;;;;;N;;;;; +1210;ETHIOPIC SYLLABLE HHA;Lo;0;L;;;;;N;;;;; +1211;ETHIOPIC SYLLABLE HHU;Lo;0;L;;;;;N;;;;; +1212;ETHIOPIC SYLLABLE HHI;Lo;0;L;;;;;N;;;;; +1213;ETHIOPIC SYLLABLE HHAA;Lo;0;L;;;;;N;;;;; +1214;ETHIOPIC SYLLABLE HHEE;Lo;0;L;;;;;N;;;;; +1215;ETHIOPIC SYLLABLE HHE;Lo;0;L;;;;;N;;;;; +1216;ETHIOPIC SYLLABLE HHO;Lo;0;L;;;;;N;;;;; +1217;ETHIOPIC SYLLABLE HHWA;Lo;0;L;;;;;N;;;;; +1218;ETHIOPIC SYLLABLE MA;Lo;0;L;;;;;N;;;;; +1219;ETHIOPIC SYLLABLE MU;Lo;0;L;;;;;N;;;;; +121A;ETHIOPIC SYLLABLE MI;Lo;0;L;;;;;N;;;;; +121B;ETHIOPIC SYLLABLE MAA;Lo;0;L;;;;;N;;;;; +121C;ETHIOPIC SYLLABLE MEE;Lo;0;L;;;;;N;;;;; +121D;ETHIOPIC SYLLABLE ME;Lo;0;L;;;;;N;;;;; +121E;ETHIOPIC SYLLABLE MO;Lo;0;L;;;;;N;;;;; +121F;ETHIOPIC SYLLABLE MWA;Lo;0;L;;;;;N;;;;; +1220;ETHIOPIC SYLLABLE SZA;Lo;0;L;;;;;N;;;;; +1221;ETHIOPIC SYLLABLE SZU;Lo;0;L;;;;;N;;;;; +1222;ETHIOPIC SYLLABLE SZI;Lo;0;L;;;;;N;;;;; +1223;ETHIOPIC SYLLABLE SZAA;Lo;0;L;;;;;N;;;;; +1224;ETHIOPIC SYLLABLE SZEE;Lo;0;L;;;;;N;;;;; +1225;ETHIOPIC SYLLABLE SZE;Lo;0;L;;;;;N;;;;; +1226;ETHIOPIC SYLLABLE SZO;Lo;0;L;;;;;N;;;;; +1227;ETHIOPIC SYLLABLE SZWA;Lo;0;L;;;;;N;;;;; +1228;ETHIOPIC SYLLABLE RA;Lo;0;L;;;;;N;;;;; +1229;ETHIOPIC SYLLABLE RU;Lo;0;L;;;;;N;;;;; +122A;ETHIOPIC SYLLABLE RI;Lo;0;L;;;;;N;;;;; +122B;ETHIOPIC SYLLABLE RAA;Lo;0;L;;;;;N;;;;; +122C;ETHIOPIC SYLLABLE REE;Lo;0;L;;;;;N;;;;; +122D;ETHIOPIC SYLLABLE RE;Lo;0;L;;;;;N;;;;; +122E;ETHIOPIC SYLLABLE RO;Lo;0;L;;;;;N;;;;; +122F;ETHIOPIC SYLLABLE RWA;Lo;0;L;;;;;N;;;;; +1230;ETHIOPIC SYLLABLE SA;Lo;0;L;;;;;N;;;;; +1231;ETHIOPIC SYLLABLE SU;Lo;0;L;;;;;N;;;;; +1232;ETHIOPIC SYLLABLE SI;Lo;0;L;;;;;N;;;;; +1233;ETHIOPIC SYLLABLE SAA;Lo;0;L;;;;;N;;;;; +1234;ETHIOPIC SYLLABLE SEE;Lo;0;L;;;;;N;;;;; +1235;ETHIOPIC SYLLABLE SE;Lo;0;L;;;;;N;;;;; +1236;ETHIOPIC SYLLABLE SO;Lo;0;L;;;;;N;;;;; +1237;ETHIOPIC SYLLABLE SWA;Lo;0;L;;;;;N;;;;; +1238;ETHIOPIC SYLLABLE SHA;Lo;0;L;;;;;N;;;;; +1239;ETHIOPIC SYLLABLE SHU;Lo;0;L;;;;;N;;;;; +123A;ETHIOPIC SYLLABLE SHI;Lo;0;L;;;;;N;;;;; +123B;ETHIOPIC SYLLABLE SHAA;Lo;0;L;;;;;N;;;;; +123C;ETHIOPIC SYLLABLE SHEE;Lo;0;L;;;;;N;;;;; +123D;ETHIOPIC SYLLABLE SHE;Lo;0;L;;;;;N;;;;; +123E;ETHIOPIC SYLLABLE SHO;Lo;0;L;;;;;N;;;;; +123F;ETHIOPIC SYLLABLE SHWA;Lo;0;L;;;;;N;;;;; +1240;ETHIOPIC SYLLABLE QA;Lo;0;L;;;;;N;;;;; +1241;ETHIOPIC SYLLABLE QU;Lo;0;L;;;;;N;;;;; +1242;ETHIOPIC SYLLABLE QI;Lo;0;L;;;;;N;;;;; +1243;ETHIOPIC SYLLABLE QAA;Lo;0;L;;;;;N;;;;; +1244;ETHIOPIC SYLLABLE QEE;Lo;0;L;;;;;N;;;;; +1245;ETHIOPIC SYLLABLE QE;Lo;0;L;;;;;N;;;;; +1246;ETHIOPIC SYLLABLE QO;Lo;0;L;;;;;N;;;;; +1247;ETHIOPIC SYLLABLE QOA;Lo;0;L;;;;;N;;;;; +1248;ETHIOPIC SYLLABLE QWA;Lo;0;L;;;;;N;;;;; +124A;ETHIOPIC SYLLABLE QWI;Lo;0;L;;;;;N;;;;; +124B;ETHIOPIC SYLLABLE QWAA;Lo;0;L;;;;;N;;;;; +124C;ETHIOPIC SYLLABLE QWEE;Lo;0;L;;;;;N;;;;; +124D;ETHIOPIC SYLLABLE QWE;Lo;0;L;;;;;N;;;;; +1250;ETHIOPIC SYLLABLE QHA;Lo;0;L;;;;;N;;;;; +1251;ETHIOPIC SYLLABLE QHU;Lo;0;L;;;;;N;;;;; +1252;ETHIOPIC SYLLABLE QHI;Lo;0;L;;;;;N;;;;; +1253;ETHIOPIC SYLLABLE QHAA;Lo;0;L;;;;;N;;;;; +1254;ETHIOPIC SYLLABLE QHEE;Lo;0;L;;;;;N;;;;; +1255;ETHIOPIC SYLLABLE QHE;Lo;0;L;;;;;N;;;;; +1256;ETHIOPIC SYLLABLE QHO;Lo;0;L;;;;;N;;;;; +1258;ETHIOPIC SYLLABLE QHWA;Lo;0;L;;;;;N;;;;; +125A;ETHIOPIC SYLLABLE QHWI;Lo;0;L;;;;;N;;;;; +125B;ETHIOPIC SYLLABLE QHWAA;Lo;0;L;;;;;N;;;;; +125C;ETHIOPIC SYLLABLE QHWEE;Lo;0;L;;;;;N;;;;; +125D;ETHIOPIC SYLLABLE QHWE;Lo;0;L;;;;;N;;;;; +1260;ETHIOPIC SYLLABLE BA;Lo;0;L;;;;;N;;;;; +1261;ETHIOPIC SYLLABLE BU;Lo;0;L;;;;;N;;;;; +1262;ETHIOPIC SYLLABLE BI;Lo;0;L;;;;;N;;;;; +1263;ETHIOPIC SYLLABLE BAA;Lo;0;L;;;;;N;;;;; +1264;ETHIOPIC SYLLABLE BEE;Lo;0;L;;;;;N;;;;; +1265;ETHIOPIC SYLLABLE BE;Lo;0;L;;;;;N;;;;; +1266;ETHIOPIC SYLLABLE BO;Lo;0;L;;;;;N;;;;; +1267;ETHIOPIC SYLLABLE BWA;Lo;0;L;;;;;N;;;;; +1268;ETHIOPIC SYLLABLE VA;Lo;0;L;;;;;N;;;;; +1269;ETHIOPIC SYLLABLE VU;Lo;0;L;;;;;N;;;;; +126A;ETHIOPIC SYLLABLE VI;Lo;0;L;;;;;N;;;;; +126B;ETHIOPIC SYLLABLE VAA;Lo;0;L;;;;;N;;;;; +126C;ETHIOPIC SYLLABLE VEE;Lo;0;L;;;;;N;;;;; +126D;ETHIOPIC SYLLABLE VE;Lo;0;L;;;;;N;;;;; +126E;ETHIOPIC SYLLABLE VO;Lo;0;L;;;;;N;;;;; +126F;ETHIOPIC SYLLABLE VWA;Lo;0;L;;;;;N;;;;; +1270;ETHIOPIC SYLLABLE TA;Lo;0;L;;;;;N;;;;; +1271;ETHIOPIC SYLLABLE TU;Lo;0;L;;;;;N;;;;; +1272;ETHIOPIC SYLLABLE TI;Lo;0;L;;;;;N;;;;; +1273;ETHIOPIC SYLLABLE TAA;Lo;0;L;;;;;N;;;;; +1274;ETHIOPIC SYLLABLE TEE;Lo;0;L;;;;;N;;;;; +1275;ETHIOPIC SYLLABLE TE;Lo;0;L;;;;;N;;;;; +1276;ETHIOPIC SYLLABLE TO;Lo;0;L;;;;;N;;;;; +1277;ETHIOPIC SYLLABLE TWA;Lo;0;L;;;;;N;;;;; +1278;ETHIOPIC SYLLABLE CA;Lo;0;L;;;;;N;;;;; +1279;ETHIOPIC SYLLABLE CU;Lo;0;L;;;;;N;;;;; +127A;ETHIOPIC SYLLABLE CI;Lo;0;L;;;;;N;;;;; +127B;ETHIOPIC SYLLABLE CAA;Lo;0;L;;;;;N;;;;; +127C;ETHIOPIC SYLLABLE CEE;Lo;0;L;;;;;N;;;;; +127D;ETHIOPIC SYLLABLE CE;Lo;0;L;;;;;N;;;;; +127E;ETHIOPIC SYLLABLE CO;Lo;0;L;;;;;N;;;;; +127F;ETHIOPIC SYLLABLE CWA;Lo;0;L;;;;;N;;;;; +1280;ETHIOPIC SYLLABLE XA;Lo;0;L;;;;;N;;;;; +1281;ETHIOPIC SYLLABLE XU;Lo;0;L;;;;;N;;;;; +1282;ETHIOPIC SYLLABLE XI;Lo;0;L;;;;;N;;;;; +1283;ETHIOPIC SYLLABLE XAA;Lo;0;L;;;;;N;;;;; +1284;ETHIOPIC SYLLABLE XEE;Lo;0;L;;;;;N;;;;; +1285;ETHIOPIC SYLLABLE XE;Lo;0;L;;;;;N;;;;; +1286;ETHIOPIC SYLLABLE XO;Lo;0;L;;;;;N;;;;; +1287;ETHIOPIC SYLLABLE XOA;Lo;0;L;;;;;N;;;;; +1288;ETHIOPIC SYLLABLE XWA;Lo;0;L;;;;;N;;;;; +128A;ETHIOPIC SYLLABLE XWI;Lo;0;L;;;;;N;;;;; +128B;ETHIOPIC SYLLABLE XWAA;Lo;0;L;;;;;N;;;;; +128C;ETHIOPIC SYLLABLE XWEE;Lo;0;L;;;;;N;;;;; +128D;ETHIOPIC SYLLABLE XWE;Lo;0;L;;;;;N;;;;; +1290;ETHIOPIC SYLLABLE NA;Lo;0;L;;;;;N;;;;; +1291;ETHIOPIC SYLLABLE NU;Lo;0;L;;;;;N;;;;; +1292;ETHIOPIC SYLLABLE NI;Lo;0;L;;;;;N;;;;; +1293;ETHIOPIC SYLLABLE NAA;Lo;0;L;;;;;N;;;;; +1294;ETHIOPIC SYLLABLE NEE;Lo;0;L;;;;;N;;;;; +1295;ETHIOPIC SYLLABLE NE;Lo;0;L;;;;;N;;;;; +1296;ETHIOPIC SYLLABLE NO;Lo;0;L;;;;;N;;;;; +1297;ETHIOPIC SYLLABLE NWA;Lo;0;L;;;;;N;;;;; +1298;ETHIOPIC SYLLABLE NYA;Lo;0;L;;;;;N;;;;; +1299;ETHIOPIC SYLLABLE NYU;Lo;0;L;;;;;N;;;;; +129A;ETHIOPIC SYLLABLE NYI;Lo;0;L;;;;;N;;;;; +129B;ETHIOPIC SYLLABLE NYAA;Lo;0;L;;;;;N;;;;; +129C;ETHIOPIC SYLLABLE NYEE;Lo;0;L;;;;;N;;;;; +129D;ETHIOPIC SYLLABLE NYE;Lo;0;L;;;;;N;;;;; +129E;ETHIOPIC SYLLABLE NYO;Lo;0;L;;;;;N;;;;; +129F;ETHIOPIC SYLLABLE NYWA;Lo;0;L;;;;;N;;;;; +12A0;ETHIOPIC SYLLABLE GLOTTAL A;Lo;0;L;;;;;N;;;;; +12A1;ETHIOPIC SYLLABLE GLOTTAL U;Lo;0;L;;;;;N;;;;; +12A2;ETHIOPIC SYLLABLE GLOTTAL I;Lo;0;L;;;;;N;;;;; +12A3;ETHIOPIC SYLLABLE GLOTTAL AA;Lo;0;L;;;;;N;;;;; +12A4;ETHIOPIC SYLLABLE GLOTTAL EE;Lo;0;L;;;;;N;;;;; +12A5;ETHIOPIC SYLLABLE GLOTTAL E;Lo;0;L;;;;;N;;;;; +12A6;ETHIOPIC SYLLABLE GLOTTAL O;Lo;0;L;;;;;N;;;;; +12A7;ETHIOPIC SYLLABLE GLOTTAL WA;Lo;0;L;;;;;N;;;;; +12A8;ETHIOPIC SYLLABLE KA;Lo;0;L;;;;;N;;;;; +12A9;ETHIOPIC SYLLABLE KU;Lo;0;L;;;;;N;;;;; +12AA;ETHIOPIC SYLLABLE KI;Lo;0;L;;;;;N;;;;; +12AB;ETHIOPIC SYLLABLE KAA;Lo;0;L;;;;;N;;;;; +12AC;ETHIOPIC SYLLABLE KEE;Lo;0;L;;;;;N;;;;; +12AD;ETHIOPIC SYLLABLE KE;Lo;0;L;;;;;N;;;;; +12AE;ETHIOPIC SYLLABLE KO;Lo;0;L;;;;;N;;;;; +12AF;ETHIOPIC SYLLABLE KOA;Lo;0;L;;;;;N;;;;; +12B0;ETHIOPIC SYLLABLE KWA;Lo;0;L;;;;;N;;;;; +12B2;ETHIOPIC SYLLABLE KWI;Lo;0;L;;;;;N;;;;; +12B3;ETHIOPIC SYLLABLE KWAA;Lo;0;L;;;;;N;;;;; +12B4;ETHIOPIC SYLLABLE KWEE;Lo;0;L;;;;;N;;;;; +12B5;ETHIOPIC SYLLABLE KWE;Lo;0;L;;;;;N;;;;; +12B8;ETHIOPIC SYLLABLE KXA;Lo;0;L;;;;;N;;;;; +12B9;ETHIOPIC SYLLABLE KXU;Lo;0;L;;;;;N;;;;; +12BA;ETHIOPIC SYLLABLE KXI;Lo;0;L;;;;;N;;;;; +12BB;ETHIOPIC SYLLABLE KXAA;Lo;0;L;;;;;N;;;;; +12BC;ETHIOPIC SYLLABLE KXEE;Lo;0;L;;;;;N;;;;; +12BD;ETHIOPIC SYLLABLE KXE;Lo;0;L;;;;;N;;;;; +12BE;ETHIOPIC SYLLABLE KXO;Lo;0;L;;;;;N;;;;; +12C0;ETHIOPIC SYLLABLE KXWA;Lo;0;L;;;;;N;;;;; +12C2;ETHIOPIC SYLLABLE KXWI;Lo;0;L;;;;;N;;;;; +12C3;ETHIOPIC SYLLABLE KXWAA;Lo;0;L;;;;;N;;;;; +12C4;ETHIOPIC SYLLABLE KXWEE;Lo;0;L;;;;;N;;;;; +12C5;ETHIOPIC SYLLABLE KXWE;Lo;0;L;;;;;N;;;;; +12C8;ETHIOPIC SYLLABLE WA;Lo;0;L;;;;;N;;;;; +12C9;ETHIOPIC SYLLABLE WU;Lo;0;L;;;;;N;;;;; +12CA;ETHIOPIC SYLLABLE WI;Lo;0;L;;;;;N;;;;; +12CB;ETHIOPIC SYLLABLE WAA;Lo;0;L;;;;;N;;;;; +12CC;ETHIOPIC SYLLABLE WEE;Lo;0;L;;;;;N;;;;; +12CD;ETHIOPIC SYLLABLE WE;Lo;0;L;;;;;N;;;;; +12CE;ETHIOPIC SYLLABLE WO;Lo;0;L;;;;;N;;;;; +12CF;ETHIOPIC SYLLABLE WOA;Lo;0;L;;;;;N;;;;; +12D0;ETHIOPIC SYLLABLE PHARYNGEAL A;Lo;0;L;;;;;N;;;;; +12D1;ETHIOPIC SYLLABLE PHARYNGEAL U;Lo;0;L;;;;;N;;;;; +12D2;ETHIOPIC SYLLABLE PHARYNGEAL I;Lo;0;L;;;;;N;;;;; +12D3;ETHIOPIC SYLLABLE PHARYNGEAL AA;Lo;0;L;;;;;N;;;;; +12D4;ETHIOPIC SYLLABLE PHARYNGEAL EE;Lo;0;L;;;;;N;;;;; +12D5;ETHIOPIC SYLLABLE PHARYNGEAL E;Lo;0;L;;;;;N;;;;; +12D6;ETHIOPIC SYLLABLE PHARYNGEAL O;Lo;0;L;;;;;N;;;;; +12D8;ETHIOPIC SYLLABLE ZA;Lo;0;L;;;;;N;;;;; +12D9;ETHIOPIC SYLLABLE ZU;Lo;0;L;;;;;N;;;;; +12DA;ETHIOPIC SYLLABLE ZI;Lo;0;L;;;;;N;;;;; +12DB;ETHIOPIC SYLLABLE ZAA;Lo;0;L;;;;;N;;;;; +12DC;ETHIOPIC SYLLABLE ZEE;Lo;0;L;;;;;N;;;;; +12DD;ETHIOPIC SYLLABLE ZE;Lo;0;L;;;;;N;;;;; +12DE;ETHIOPIC SYLLABLE ZO;Lo;0;L;;;;;N;;;;; +12DF;ETHIOPIC SYLLABLE ZWA;Lo;0;L;;;;;N;;;;; +12E0;ETHIOPIC SYLLABLE ZHA;Lo;0;L;;;;;N;;;;; +12E1;ETHIOPIC SYLLABLE ZHU;Lo;0;L;;;;;N;;;;; +12E2;ETHIOPIC SYLLABLE ZHI;Lo;0;L;;;;;N;;;;; +12E3;ETHIOPIC SYLLABLE ZHAA;Lo;0;L;;;;;N;;;;; +12E4;ETHIOPIC SYLLABLE ZHEE;Lo;0;L;;;;;N;;;;; +12E5;ETHIOPIC SYLLABLE ZHE;Lo;0;L;;;;;N;;;;; +12E6;ETHIOPIC SYLLABLE ZHO;Lo;0;L;;;;;N;;;;; +12E7;ETHIOPIC SYLLABLE ZHWA;Lo;0;L;;;;;N;;;;; +12E8;ETHIOPIC SYLLABLE YA;Lo;0;L;;;;;N;;;;; +12E9;ETHIOPIC SYLLABLE YU;Lo;0;L;;;;;N;;;;; +12EA;ETHIOPIC SYLLABLE YI;Lo;0;L;;;;;N;;;;; +12EB;ETHIOPIC SYLLABLE YAA;Lo;0;L;;;;;N;;;;; +12EC;ETHIOPIC SYLLABLE YEE;Lo;0;L;;;;;N;;;;; +12ED;ETHIOPIC SYLLABLE YE;Lo;0;L;;;;;N;;;;; +12EE;ETHIOPIC SYLLABLE YO;Lo;0;L;;;;;N;;;;; +12EF;ETHIOPIC SYLLABLE YOA;Lo;0;L;;;;;N;;;;; +12F0;ETHIOPIC SYLLABLE DA;Lo;0;L;;;;;N;;;;; +12F1;ETHIOPIC SYLLABLE DU;Lo;0;L;;;;;N;;;;; +12F2;ETHIOPIC SYLLABLE DI;Lo;0;L;;;;;N;;;;; +12F3;ETHIOPIC SYLLABLE DAA;Lo;0;L;;;;;N;;;;; +12F4;ETHIOPIC SYLLABLE DEE;Lo;0;L;;;;;N;;;;; +12F5;ETHIOPIC SYLLABLE DE;Lo;0;L;;;;;N;;;;; +12F6;ETHIOPIC SYLLABLE DO;Lo;0;L;;;;;N;;;;; +12F7;ETHIOPIC SYLLABLE DWA;Lo;0;L;;;;;N;;;;; +12F8;ETHIOPIC SYLLABLE DDA;Lo;0;L;;;;;N;;;;; +12F9;ETHIOPIC SYLLABLE DDU;Lo;0;L;;;;;N;;;;; +12FA;ETHIOPIC SYLLABLE DDI;Lo;0;L;;;;;N;;;;; +12FB;ETHIOPIC SYLLABLE DDAA;Lo;0;L;;;;;N;;;;; +12FC;ETHIOPIC SYLLABLE DDEE;Lo;0;L;;;;;N;;;;; +12FD;ETHIOPIC SYLLABLE DDE;Lo;0;L;;;;;N;;;;; +12FE;ETHIOPIC SYLLABLE DDO;Lo;0;L;;;;;N;;;;; +12FF;ETHIOPIC SYLLABLE DDWA;Lo;0;L;;;;;N;;;;; +1300;ETHIOPIC SYLLABLE JA;Lo;0;L;;;;;N;;;;; +1301;ETHIOPIC SYLLABLE JU;Lo;0;L;;;;;N;;;;; +1302;ETHIOPIC SYLLABLE JI;Lo;0;L;;;;;N;;;;; +1303;ETHIOPIC SYLLABLE JAA;Lo;0;L;;;;;N;;;;; +1304;ETHIOPIC SYLLABLE JEE;Lo;0;L;;;;;N;;;;; +1305;ETHIOPIC SYLLABLE JE;Lo;0;L;;;;;N;;;;; +1306;ETHIOPIC SYLLABLE JO;Lo;0;L;;;;;N;;;;; +1307;ETHIOPIC SYLLABLE JWA;Lo;0;L;;;;;N;;;;; +1308;ETHIOPIC SYLLABLE GA;Lo;0;L;;;;;N;;;;; +1309;ETHIOPIC SYLLABLE GU;Lo;0;L;;;;;N;;;;; +130A;ETHIOPIC SYLLABLE GI;Lo;0;L;;;;;N;;;;; +130B;ETHIOPIC SYLLABLE GAA;Lo;0;L;;;;;N;;;;; +130C;ETHIOPIC SYLLABLE GEE;Lo;0;L;;;;;N;;;;; +130D;ETHIOPIC SYLLABLE GE;Lo;0;L;;;;;N;;;;; +130E;ETHIOPIC SYLLABLE GO;Lo;0;L;;;;;N;;;;; +130F;ETHIOPIC SYLLABLE GOA;Lo;0;L;;;;;N;;;;; +1310;ETHIOPIC SYLLABLE GWA;Lo;0;L;;;;;N;;;;; +1312;ETHIOPIC SYLLABLE GWI;Lo;0;L;;;;;N;;;;; +1313;ETHIOPIC SYLLABLE GWAA;Lo;0;L;;;;;N;;;;; +1314;ETHIOPIC SYLLABLE GWEE;Lo;0;L;;;;;N;;;;; +1315;ETHIOPIC SYLLABLE GWE;Lo;0;L;;;;;N;;;;; +1318;ETHIOPIC SYLLABLE GGA;Lo;0;L;;;;;N;;;;; +1319;ETHIOPIC SYLLABLE GGU;Lo;0;L;;;;;N;;;;; +131A;ETHIOPIC SYLLABLE GGI;Lo;0;L;;;;;N;;;;; +131B;ETHIOPIC SYLLABLE GGAA;Lo;0;L;;;;;N;;;;; +131C;ETHIOPIC SYLLABLE GGEE;Lo;0;L;;;;;N;;;;; +131D;ETHIOPIC SYLLABLE GGE;Lo;0;L;;;;;N;;;;; +131E;ETHIOPIC SYLLABLE GGO;Lo;0;L;;;;;N;;;;; +131F;ETHIOPIC SYLLABLE GGWAA;Lo;0;L;;;;;N;;;;; +1320;ETHIOPIC SYLLABLE THA;Lo;0;L;;;;;N;;;;; +1321;ETHIOPIC SYLLABLE THU;Lo;0;L;;;;;N;;;;; +1322;ETHIOPIC SYLLABLE THI;Lo;0;L;;;;;N;;;;; +1323;ETHIOPIC SYLLABLE THAA;Lo;0;L;;;;;N;;;;; +1324;ETHIOPIC SYLLABLE THEE;Lo;0;L;;;;;N;;;;; +1325;ETHIOPIC SYLLABLE THE;Lo;0;L;;;;;N;;;;; +1326;ETHIOPIC SYLLABLE THO;Lo;0;L;;;;;N;;;;; +1327;ETHIOPIC SYLLABLE THWA;Lo;0;L;;;;;N;;;;; +1328;ETHIOPIC SYLLABLE CHA;Lo;0;L;;;;;N;;;;; +1329;ETHIOPIC SYLLABLE CHU;Lo;0;L;;;;;N;;;;; +132A;ETHIOPIC SYLLABLE CHI;Lo;0;L;;;;;N;;;;; +132B;ETHIOPIC SYLLABLE CHAA;Lo;0;L;;;;;N;;;;; +132C;ETHIOPIC SYLLABLE CHEE;Lo;0;L;;;;;N;;;;; +132D;ETHIOPIC SYLLABLE CHE;Lo;0;L;;;;;N;;;;; +132E;ETHIOPIC SYLLABLE CHO;Lo;0;L;;;;;N;;;;; +132F;ETHIOPIC SYLLABLE CHWA;Lo;0;L;;;;;N;;;;; +1330;ETHIOPIC SYLLABLE PHA;Lo;0;L;;;;;N;;;;; +1331;ETHIOPIC SYLLABLE PHU;Lo;0;L;;;;;N;;;;; +1332;ETHIOPIC SYLLABLE PHI;Lo;0;L;;;;;N;;;;; +1333;ETHIOPIC SYLLABLE PHAA;Lo;0;L;;;;;N;;;;; +1334;ETHIOPIC SYLLABLE PHEE;Lo;0;L;;;;;N;;;;; +1335;ETHIOPIC SYLLABLE PHE;Lo;0;L;;;;;N;;;;; +1336;ETHIOPIC SYLLABLE PHO;Lo;0;L;;;;;N;;;;; +1337;ETHIOPIC SYLLABLE PHWA;Lo;0;L;;;;;N;;;;; +1338;ETHIOPIC SYLLABLE TSA;Lo;0;L;;;;;N;;;;; +1339;ETHIOPIC SYLLABLE TSU;Lo;0;L;;;;;N;;;;; +133A;ETHIOPIC SYLLABLE TSI;Lo;0;L;;;;;N;;;;; +133B;ETHIOPIC SYLLABLE TSAA;Lo;0;L;;;;;N;;;;; +133C;ETHIOPIC SYLLABLE TSEE;Lo;0;L;;;;;N;;;;; +133D;ETHIOPIC SYLLABLE TSE;Lo;0;L;;;;;N;;;;; +133E;ETHIOPIC SYLLABLE TSO;Lo;0;L;;;;;N;;;;; +133F;ETHIOPIC SYLLABLE TSWA;Lo;0;L;;;;;N;;;;; +1340;ETHIOPIC SYLLABLE TZA;Lo;0;L;;;;;N;;;;; +1341;ETHIOPIC SYLLABLE TZU;Lo;0;L;;;;;N;;;;; +1342;ETHIOPIC SYLLABLE TZI;Lo;0;L;;;;;N;;;;; +1343;ETHIOPIC SYLLABLE TZAA;Lo;0;L;;;;;N;;;;; +1344;ETHIOPIC SYLLABLE TZEE;Lo;0;L;;;;;N;;;;; +1345;ETHIOPIC SYLLABLE TZE;Lo;0;L;;;;;N;;;;; +1346;ETHIOPIC SYLLABLE TZO;Lo;0;L;;;;;N;;;;; +1347;ETHIOPIC SYLLABLE TZOA;Lo;0;L;;;;;N;;;;; +1348;ETHIOPIC SYLLABLE FA;Lo;0;L;;;;;N;;;;; +1349;ETHIOPIC SYLLABLE FU;Lo;0;L;;;;;N;;;;; +134A;ETHIOPIC SYLLABLE FI;Lo;0;L;;;;;N;;;;; +134B;ETHIOPIC SYLLABLE FAA;Lo;0;L;;;;;N;;;;; +134C;ETHIOPIC SYLLABLE FEE;Lo;0;L;;;;;N;;;;; +134D;ETHIOPIC SYLLABLE FE;Lo;0;L;;;;;N;;;;; +134E;ETHIOPIC SYLLABLE FO;Lo;0;L;;;;;N;;;;; +134F;ETHIOPIC SYLLABLE FWA;Lo;0;L;;;;;N;;;;; +1350;ETHIOPIC SYLLABLE PA;Lo;0;L;;;;;N;;;;; +1351;ETHIOPIC SYLLABLE PU;Lo;0;L;;;;;N;;;;; +1352;ETHIOPIC SYLLABLE PI;Lo;0;L;;;;;N;;;;; +1353;ETHIOPIC SYLLABLE PAA;Lo;0;L;;;;;N;;;;; +1354;ETHIOPIC SYLLABLE PEE;Lo;0;L;;;;;N;;;;; +1355;ETHIOPIC SYLLABLE PE;Lo;0;L;;;;;N;;;;; +1356;ETHIOPIC SYLLABLE PO;Lo;0;L;;;;;N;;;;; +1357;ETHIOPIC SYLLABLE PWA;Lo;0;L;;;;;N;;;;; +1358;ETHIOPIC SYLLABLE RYA;Lo;0;L;;;;;N;;;;; +1359;ETHIOPIC SYLLABLE MYA;Lo;0;L;;;;;N;;;;; +135A;ETHIOPIC SYLLABLE FYA;Lo;0;L;;;;;N;;;;; +135D;ETHIOPIC COMBINING GEMINATION AND VOWEL LENGTH MARK;Mn;230;NSM;;;;;N;;;;; +135E;ETHIOPIC COMBINING VOWEL LENGTH MARK;Mn;230;NSM;;;;;N;;;;; +135F;ETHIOPIC COMBINING GEMINATION MARK;Mn;230;NSM;;;;;N;;;;; +1360;ETHIOPIC SECTION MARK;Po;0;L;;;;;N;;;;; +1361;ETHIOPIC WORDSPACE;Po;0;L;;;;;N;;;;; +1362;ETHIOPIC FULL STOP;Po;0;L;;;;;N;;;;; +1363;ETHIOPIC COMMA;Po;0;L;;;;;N;;;;; +1364;ETHIOPIC SEMICOLON;Po;0;L;;;;;N;;;;; +1365;ETHIOPIC COLON;Po;0;L;;;;;N;;;;; +1366;ETHIOPIC PREFACE COLON;Po;0;L;;;;;N;;;;; +1367;ETHIOPIC QUESTION MARK;Po;0;L;;;;;N;;;;; +1368;ETHIOPIC PARAGRAPH SEPARATOR;Po;0;L;;;;;N;;;;; +1369;ETHIOPIC DIGIT ONE;No;0;L;;;1;1;N;;;;; +136A;ETHIOPIC DIGIT TWO;No;0;L;;;2;2;N;;;;; +136B;ETHIOPIC DIGIT THREE;No;0;L;;;3;3;N;;;;; +136C;ETHIOPIC DIGIT FOUR;No;0;L;;;4;4;N;;;;; +136D;ETHIOPIC DIGIT FIVE;No;0;L;;;5;5;N;;;;; +136E;ETHIOPIC DIGIT SIX;No;0;L;;;6;6;N;;;;; +136F;ETHIOPIC DIGIT SEVEN;No;0;L;;;7;7;N;;;;; +1370;ETHIOPIC DIGIT EIGHT;No;0;L;;;8;8;N;;;;; +1371;ETHIOPIC DIGIT NINE;No;0;L;;;9;9;N;;;;; +1372;ETHIOPIC NUMBER TEN;No;0;L;;;;10;N;;;;; +1373;ETHIOPIC NUMBER TWENTY;No;0;L;;;;20;N;;;;; +1374;ETHIOPIC NUMBER THIRTY;No;0;L;;;;30;N;;;;; +1375;ETHIOPIC NUMBER FORTY;No;0;L;;;;40;N;;;;; +1376;ETHIOPIC NUMBER FIFTY;No;0;L;;;;50;N;;;;; +1377;ETHIOPIC NUMBER SIXTY;No;0;L;;;;60;N;;;;; +1378;ETHIOPIC NUMBER SEVENTY;No;0;L;;;;70;N;;;;; +1379;ETHIOPIC NUMBER EIGHTY;No;0;L;;;;80;N;;;;; +137A;ETHIOPIC NUMBER NINETY;No;0;L;;;;90;N;;;;; +137B;ETHIOPIC NUMBER HUNDRED;No;0;L;;;;100;N;;;;; +137C;ETHIOPIC NUMBER TEN THOUSAND;No;0;L;;;;10000;N;;;;; +1380;ETHIOPIC SYLLABLE SEBATBEIT MWA;Lo;0;L;;;;;N;;;;; +1381;ETHIOPIC SYLLABLE MWI;Lo;0;L;;;;;N;;;;; +1382;ETHIOPIC SYLLABLE MWEE;Lo;0;L;;;;;N;;;;; +1383;ETHIOPIC SYLLABLE MWE;Lo;0;L;;;;;N;;;;; +1384;ETHIOPIC SYLLABLE SEBATBEIT BWA;Lo;0;L;;;;;N;;;;; +1385;ETHIOPIC SYLLABLE BWI;Lo;0;L;;;;;N;;;;; +1386;ETHIOPIC SYLLABLE BWEE;Lo;0;L;;;;;N;;;;; +1387;ETHIOPIC SYLLABLE BWE;Lo;0;L;;;;;N;;;;; +1388;ETHIOPIC SYLLABLE SEBATBEIT FWA;Lo;0;L;;;;;N;;;;; +1389;ETHIOPIC SYLLABLE FWI;Lo;0;L;;;;;N;;;;; +138A;ETHIOPIC SYLLABLE FWEE;Lo;0;L;;;;;N;;;;; +138B;ETHIOPIC SYLLABLE FWE;Lo;0;L;;;;;N;;;;; +138C;ETHIOPIC SYLLABLE SEBATBEIT PWA;Lo;0;L;;;;;N;;;;; +138D;ETHIOPIC SYLLABLE PWI;Lo;0;L;;;;;N;;;;; +138E;ETHIOPIC SYLLABLE PWEE;Lo;0;L;;;;;N;;;;; +138F;ETHIOPIC SYLLABLE PWE;Lo;0;L;;;;;N;;;;; +1390;ETHIOPIC TONAL MARK YIZET;So;0;ON;;;;;N;;;;; +1391;ETHIOPIC TONAL MARK DERET;So;0;ON;;;;;N;;;;; +1392;ETHIOPIC TONAL MARK RIKRIK;So;0;ON;;;;;N;;;;; +1393;ETHIOPIC TONAL MARK SHORT RIKRIK;So;0;ON;;;;;N;;;;; +1394;ETHIOPIC TONAL MARK DIFAT;So;0;ON;;;;;N;;;;; +1395;ETHIOPIC TONAL MARK KENAT;So;0;ON;;;;;N;;;;; +1396;ETHIOPIC TONAL MARK CHIRET;So;0;ON;;;;;N;;;;; +1397;ETHIOPIC TONAL MARK HIDET;So;0;ON;;;;;N;;;;; +1398;ETHIOPIC TONAL MARK DERET-HIDET;So;0;ON;;;;;N;;;;; +1399;ETHIOPIC TONAL MARK KURT;So;0;ON;;;;;N;;;;; +13A0;CHEROKEE LETTER A;Lo;0;L;;;;;N;;;;; +13A1;CHEROKEE LETTER E;Lo;0;L;;;;;N;;;;; +13A2;CHEROKEE LETTER I;Lo;0;L;;;;;N;;;;; +13A3;CHEROKEE LETTER O;Lo;0;L;;;;;N;;;;; +13A4;CHEROKEE LETTER U;Lo;0;L;;;;;N;;;;; +13A5;CHEROKEE LETTER V;Lo;0;L;;;;;N;;;;; +13A6;CHEROKEE LETTER GA;Lo;0;L;;;;;N;;;;; +13A7;CHEROKEE LETTER KA;Lo;0;L;;;;;N;;;;; +13A8;CHEROKEE LETTER GE;Lo;0;L;;;;;N;;;;; +13A9;CHEROKEE LETTER GI;Lo;0;L;;;;;N;;;;; +13AA;CHEROKEE LETTER GO;Lo;0;L;;;;;N;;;;; +13AB;CHEROKEE LETTER GU;Lo;0;L;;;;;N;;;;; +13AC;CHEROKEE LETTER GV;Lo;0;L;;;;;N;;;;; +13AD;CHEROKEE LETTER HA;Lo;0;L;;;;;N;;;;; +13AE;CHEROKEE LETTER HE;Lo;0;L;;;;;N;;;;; +13AF;CHEROKEE LETTER HI;Lo;0;L;;;;;N;;;;; +13B0;CHEROKEE LETTER HO;Lo;0;L;;;;;N;;;;; +13B1;CHEROKEE LETTER HU;Lo;0;L;;;;;N;;;;; +13B2;CHEROKEE LETTER HV;Lo;0;L;;;;;N;;;;; +13B3;CHEROKEE LETTER LA;Lo;0;L;;;;;N;;;;; +13B4;CHEROKEE LETTER LE;Lo;0;L;;;;;N;;;;; +13B5;CHEROKEE LETTER LI;Lo;0;L;;;;;N;;;;; +13B6;CHEROKEE LETTER LO;Lo;0;L;;;;;N;;;;; +13B7;CHEROKEE LETTER LU;Lo;0;L;;;;;N;;;;; +13B8;CHEROKEE LETTER LV;Lo;0;L;;;;;N;;;;; +13B9;CHEROKEE LETTER MA;Lo;0;L;;;;;N;;;;; +13BA;CHEROKEE LETTER ME;Lo;0;L;;;;;N;;;;; +13BB;CHEROKEE LETTER MI;Lo;0;L;;;;;N;;;;; +13BC;CHEROKEE LETTER MO;Lo;0;L;;;;;N;;;;; +13BD;CHEROKEE LETTER MU;Lo;0;L;;;;;N;;;;; +13BE;CHEROKEE LETTER NA;Lo;0;L;;;;;N;;;;; +13BF;CHEROKEE LETTER HNA;Lo;0;L;;;;;N;;;;; +13C0;CHEROKEE LETTER NAH;Lo;0;L;;;;;N;;;;; +13C1;CHEROKEE LETTER NE;Lo;0;L;;;;;N;;;;; +13C2;CHEROKEE LETTER NI;Lo;0;L;;;;;N;;;;; +13C3;CHEROKEE LETTER NO;Lo;0;L;;;;;N;;;;; +13C4;CHEROKEE LETTER NU;Lo;0;L;;;;;N;;;;; +13C5;CHEROKEE LETTER NV;Lo;0;L;;;;;N;;;;; +13C6;CHEROKEE LETTER QUA;Lo;0;L;;;;;N;;;;; +13C7;CHEROKEE LETTER QUE;Lo;0;L;;;;;N;;;;; +13C8;CHEROKEE LETTER QUI;Lo;0;L;;;;;N;;;;; +13C9;CHEROKEE LETTER QUO;Lo;0;L;;;;;N;;;;; +13CA;CHEROKEE LETTER QUU;Lo;0;L;;;;;N;;;;; +13CB;CHEROKEE LETTER QUV;Lo;0;L;;;;;N;;;;; +13CC;CHEROKEE LETTER SA;Lo;0;L;;;;;N;;;;; +13CD;CHEROKEE LETTER S;Lo;0;L;;;;;N;;;;; +13CE;CHEROKEE LETTER SE;Lo;0;L;;;;;N;;;;; +13CF;CHEROKEE LETTER SI;Lo;0;L;;;;;N;;;;; +13D0;CHEROKEE LETTER SO;Lo;0;L;;;;;N;;;;; +13D1;CHEROKEE LETTER SU;Lo;0;L;;;;;N;;;;; +13D2;CHEROKEE LETTER SV;Lo;0;L;;;;;N;;;;; +13D3;CHEROKEE LETTER DA;Lo;0;L;;;;;N;;;;; +13D4;CHEROKEE LETTER TA;Lo;0;L;;;;;N;;;;; +13D5;CHEROKEE LETTER DE;Lo;0;L;;;;;N;;;;; +13D6;CHEROKEE LETTER TE;Lo;0;L;;;;;N;;;;; +13D7;CHEROKEE LETTER DI;Lo;0;L;;;;;N;;;;; +13D8;CHEROKEE LETTER TI;Lo;0;L;;;;;N;;;;; +13D9;CHEROKEE LETTER DO;Lo;0;L;;;;;N;;;;; +13DA;CHEROKEE LETTER DU;Lo;0;L;;;;;N;;;;; +13DB;CHEROKEE LETTER DV;Lo;0;L;;;;;N;;;;; +13DC;CHEROKEE LETTER DLA;Lo;0;L;;;;;N;;;;; +13DD;CHEROKEE LETTER TLA;Lo;0;L;;;;;N;;;;; +13DE;CHEROKEE LETTER TLE;Lo;0;L;;;;;N;;;;; +13DF;CHEROKEE LETTER TLI;Lo;0;L;;;;;N;;;;; +13E0;CHEROKEE LETTER TLO;Lo;0;L;;;;;N;;;;; +13E1;CHEROKEE LETTER TLU;Lo;0;L;;;;;N;;;;; +13E2;CHEROKEE LETTER TLV;Lo;0;L;;;;;N;;;;; +13E3;CHEROKEE LETTER TSA;Lo;0;L;;;;;N;;;;; +13E4;CHEROKEE LETTER TSE;Lo;0;L;;;;;N;;;;; +13E5;CHEROKEE LETTER TSI;Lo;0;L;;;;;N;;;;; +13E6;CHEROKEE LETTER TSO;Lo;0;L;;;;;N;;;;; +13E7;CHEROKEE LETTER TSU;Lo;0;L;;;;;N;;;;; +13E8;CHEROKEE LETTER TSV;Lo;0;L;;;;;N;;;;; +13E9;CHEROKEE LETTER WA;Lo;0;L;;;;;N;;;;; +13EA;CHEROKEE LETTER WE;Lo;0;L;;;;;N;;;;; +13EB;CHEROKEE LETTER WI;Lo;0;L;;;;;N;;;;; +13EC;CHEROKEE LETTER WO;Lo;0;L;;;;;N;;;;; +13ED;CHEROKEE LETTER WU;Lo;0;L;;;;;N;;;;; +13EE;CHEROKEE LETTER WV;Lo;0;L;;;;;N;;;;; +13EF;CHEROKEE LETTER YA;Lo;0;L;;;;;N;;;;; +13F0;CHEROKEE LETTER YE;Lo;0;L;;;;;N;;;;; +13F1;CHEROKEE LETTER YI;Lo;0;L;;;;;N;;;;; +13F2;CHEROKEE LETTER YO;Lo;0;L;;;;;N;;;;; +13F3;CHEROKEE LETTER YU;Lo;0;L;;;;;N;;;;; +13F4;CHEROKEE LETTER YV;Lo;0;L;;;;;N;;;;; +1400;CANADIAN SYLLABICS HYPHEN;Pd;0;ON;;;;;N;;;;; +1401;CANADIAN SYLLABICS E;Lo;0;L;;;;;N;;;;; +1402;CANADIAN SYLLABICS AAI;Lo;0;L;;;;;N;;;;; +1403;CANADIAN SYLLABICS I;Lo;0;L;;;;;N;;;;; +1404;CANADIAN SYLLABICS II;Lo;0;L;;;;;N;;;;; +1405;CANADIAN SYLLABICS O;Lo;0;L;;;;;N;;;;; +1406;CANADIAN SYLLABICS OO;Lo;0;L;;;;;N;;;;; +1407;CANADIAN SYLLABICS Y-CREE OO;Lo;0;L;;;;;N;;;;; +1408;CANADIAN SYLLABICS CARRIER EE;Lo;0;L;;;;;N;;;;; +1409;CANADIAN SYLLABICS CARRIER I;Lo;0;L;;;;;N;;;;; +140A;CANADIAN SYLLABICS A;Lo;0;L;;;;;N;;;;; +140B;CANADIAN SYLLABICS AA;Lo;0;L;;;;;N;;;;; +140C;CANADIAN SYLLABICS WE;Lo;0;L;;;;;N;;;;; +140D;CANADIAN SYLLABICS WEST-CREE WE;Lo;0;L;;;;;N;;;;; +140E;CANADIAN SYLLABICS WI;Lo;0;L;;;;;N;;;;; +140F;CANADIAN SYLLABICS WEST-CREE WI;Lo;0;L;;;;;N;;;;; +1410;CANADIAN SYLLABICS WII;Lo;0;L;;;;;N;;;;; +1411;CANADIAN SYLLABICS WEST-CREE WII;Lo;0;L;;;;;N;;;;; +1412;CANADIAN SYLLABICS WO;Lo;0;L;;;;;N;;;;; +1413;CANADIAN SYLLABICS WEST-CREE WO;Lo;0;L;;;;;N;;;;; +1414;CANADIAN SYLLABICS WOO;Lo;0;L;;;;;N;;;;; +1415;CANADIAN SYLLABICS WEST-CREE WOO;Lo;0;L;;;;;N;;;;; +1416;CANADIAN SYLLABICS NASKAPI WOO;Lo;0;L;;;;;N;;;;; +1417;CANADIAN SYLLABICS WA;Lo;0;L;;;;;N;;;;; +1418;CANADIAN SYLLABICS WEST-CREE WA;Lo;0;L;;;;;N;;;;; +1419;CANADIAN SYLLABICS WAA;Lo;0;L;;;;;N;;;;; +141A;CANADIAN SYLLABICS WEST-CREE WAA;Lo;0;L;;;;;N;;;;; +141B;CANADIAN SYLLABICS NASKAPI WAA;Lo;0;L;;;;;N;;;;; +141C;CANADIAN SYLLABICS AI;Lo;0;L;;;;;N;;;;; +141D;CANADIAN SYLLABICS Y-CREE W;Lo;0;L;;;;;N;;;;; +141E;CANADIAN SYLLABICS GLOTTAL STOP;Lo;0;L;;;;;N;;;;; +141F;CANADIAN SYLLABICS FINAL ACUTE;Lo;0;L;;;;;N;;;;; +1420;CANADIAN SYLLABICS FINAL GRAVE;Lo;0;L;;;;;N;;;;; +1421;CANADIAN SYLLABICS FINAL BOTTOM HALF RING;Lo;0;L;;;;;N;;;;; +1422;CANADIAN SYLLABICS FINAL TOP HALF RING;Lo;0;L;;;;;N;;;;; +1423;CANADIAN SYLLABICS FINAL RIGHT HALF RING;Lo;0;L;;;;;N;;;;; +1424;CANADIAN SYLLABICS FINAL RING;Lo;0;L;;;;;N;;;;; +1425;CANADIAN SYLLABICS FINAL DOUBLE ACUTE;Lo;0;L;;;;;N;;;;; +1426;CANADIAN SYLLABICS FINAL DOUBLE SHORT VERTICAL STROKES;Lo;0;L;;;;;N;;;;; +1427;CANADIAN SYLLABICS FINAL MIDDLE DOT;Lo;0;L;;;;;N;;;;; +1428;CANADIAN SYLLABICS FINAL SHORT HORIZONTAL STROKE;Lo;0;L;;;;;N;;;;; +1429;CANADIAN SYLLABICS FINAL PLUS;Lo;0;L;;;;;N;;;;; +142A;CANADIAN SYLLABICS FINAL DOWN TACK;Lo;0;L;;;;;N;;;;; +142B;CANADIAN SYLLABICS EN;Lo;0;L;;;;;N;;;;; +142C;CANADIAN SYLLABICS IN;Lo;0;L;;;;;N;;;;; +142D;CANADIAN SYLLABICS ON;Lo;0;L;;;;;N;;;;; +142E;CANADIAN SYLLABICS AN;Lo;0;L;;;;;N;;;;; +142F;CANADIAN SYLLABICS PE;Lo;0;L;;;;;N;;;;; +1430;CANADIAN SYLLABICS PAAI;Lo;0;L;;;;;N;;;;; +1431;CANADIAN SYLLABICS PI;Lo;0;L;;;;;N;;;;; +1432;CANADIAN SYLLABICS PII;Lo;0;L;;;;;N;;;;; +1433;CANADIAN SYLLABICS PO;Lo;0;L;;;;;N;;;;; +1434;CANADIAN SYLLABICS POO;Lo;0;L;;;;;N;;;;; +1435;CANADIAN SYLLABICS Y-CREE POO;Lo;0;L;;;;;N;;;;; +1436;CANADIAN SYLLABICS CARRIER HEE;Lo;0;L;;;;;N;;;;; +1437;CANADIAN SYLLABICS CARRIER HI;Lo;0;L;;;;;N;;;;; +1438;CANADIAN SYLLABICS PA;Lo;0;L;;;;;N;;;;; +1439;CANADIAN SYLLABICS PAA;Lo;0;L;;;;;N;;;;; +143A;CANADIAN SYLLABICS PWE;Lo;0;L;;;;;N;;;;; +143B;CANADIAN SYLLABICS WEST-CREE PWE;Lo;0;L;;;;;N;;;;; +143C;CANADIAN SYLLABICS PWI;Lo;0;L;;;;;N;;;;; +143D;CANADIAN SYLLABICS WEST-CREE PWI;Lo;0;L;;;;;N;;;;; +143E;CANADIAN SYLLABICS PWII;Lo;0;L;;;;;N;;;;; +143F;CANADIAN SYLLABICS WEST-CREE PWII;Lo;0;L;;;;;N;;;;; +1440;CANADIAN SYLLABICS PWO;Lo;0;L;;;;;N;;;;; +1441;CANADIAN SYLLABICS WEST-CREE PWO;Lo;0;L;;;;;N;;;;; +1442;CANADIAN SYLLABICS PWOO;Lo;0;L;;;;;N;;;;; +1443;CANADIAN SYLLABICS WEST-CREE PWOO;Lo;0;L;;;;;N;;;;; +1444;CANADIAN SYLLABICS PWA;Lo;0;L;;;;;N;;;;; +1445;CANADIAN SYLLABICS WEST-CREE PWA;Lo;0;L;;;;;N;;;;; +1446;CANADIAN SYLLABICS PWAA;Lo;0;L;;;;;N;;;;; +1447;CANADIAN SYLLABICS WEST-CREE PWAA;Lo;0;L;;;;;N;;;;; +1448;CANADIAN SYLLABICS Y-CREE PWAA;Lo;0;L;;;;;N;;;;; +1449;CANADIAN SYLLABICS P;Lo;0;L;;;;;N;;;;; +144A;CANADIAN SYLLABICS WEST-CREE P;Lo;0;L;;;;;N;;;;; +144B;CANADIAN SYLLABICS CARRIER H;Lo;0;L;;;;;N;;;;; +144C;CANADIAN SYLLABICS TE;Lo;0;L;;;;;N;;;;; +144D;CANADIAN SYLLABICS TAAI;Lo;0;L;;;;;N;;;;; +144E;CANADIAN SYLLABICS TI;Lo;0;L;;;;;N;;;;; +144F;CANADIAN SYLLABICS TII;Lo;0;L;;;;;N;;;;; +1450;CANADIAN SYLLABICS TO;Lo;0;L;;;;;N;;;;; +1451;CANADIAN SYLLABICS TOO;Lo;0;L;;;;;N;;;;; +1452;CANADIAN SYLLABICS Y-CREE TOO;Lo;0;L;;;;;N;;;;; +1453;CANADIAN SYLLABICS CARRIER DEE;Lo;0;L;;;;;N;;;;; +1454;CANADIAN SYLLABICS CARRIER DI;Lo;0;L;;;;;N;;;;; +1455;CANADIAN SYLLABICS TA;Lo;0;L;;;;;N;;;;; +1456;CANADIAN SYLLABICS TAA;Lo;0;L;;;;;N;;;;; +1457;CANADIAN SYLLABICS TWE;Lo;0;L;;;;;N;;;;; +1458;CANADIAN SYLLABICS WEST-CREE TWE;Lo;0;L;;;;;N;;;;; +1459;CANADIAN SYLLABICS TWI;Lo;0;L;;;;;N;;;;; +145A;CANADIAN SYLLABICS WEST-CREE TWI;Lo;0;L;;;;;N;;;;; +145B;CANADIAN SYLLABICS TWII;Lo;0;L;;;;;N;;;;; +145C;CANADIAN SYLLABICS WEST-CREE TWII;Lo;0;L;;;;;N;;;;; +145D;CANADIAN SYLLABICS TWO;Lo;0;L;;;;;N;;;;; +145E;CANADIAN SYLLABICS WEST-CREE TWO;Lo;0;L;;;;;N;;;;; +145F;CANADIAN SYLLABICS TWOO;Lo;0;L;;;;;N;;;;; +1460;CANADIAN SYLLABICS WEST-CREE TWOO;Lo;0;L;;;;;N;;;;; +1461;CANADIAN SYLLABICS TWA;Lo;0;L;;;;;N;;;;; +1462;CANADIAN SYLLABICS WEST-CREE TWA;Lo;0;L;;;;;N;;;;; +1463;CANADIAN SYLLABICS TWAA;Lo;0;L;;;;;N;;;;; +1464;CANADIAN SYLLABICS WEST-CREE TWAA;Lo;0;L;;;;;N;;;;; +1465;CANADIAN SYLLABICS NASKAPI TWAA;Lo;0;L;;;;;N;;;;; +1466;CANADIAN SYLLABICS T;Lo;0;L;;;;;N;;;;; +1467;CANADIAN SYLLABICS TTE;Lo;0;L;;;;;N;;;;; +1468;CANADIAN SYLLABICS TTI;Lo;0;L;;;;;N;;;;; +1469;CANADIAN SYLLABICS TTO;Lo;0;L;;;;;N;;;;; +146A;CANADIAN SYLLABICS TTA;Lo;0;L;;;;;N;;;;; +146B;CANADIAN SYLLABICS KE;Lo;0;L;;;;;N;;;;; +146C;CANADIAN SYLLABICS KAAI;Lo;0;L;;;;;N;;;;; +146D;CANADIAN SYLLABICS KI;Lo;0;L;;;;;N;;;;; +146E;CANADIAN SYLLABICS KII;Lo;0;L;;;;;N;;;;; +146F;CANADIAN SYLLABICS KO;Lo;0;L;;;;;N;;;;; +1470;CANADIAN SYLLABICS KOO;Lo;0;L;;;;;N;;;;; +1471;CANADIAN SYLLABICS Y-CREE KOO;Lo;0;L;;;;;N;;;;; +1472;CANADIAN SYLLABICS KA;Lo;0;L;;;;;N;;;;; +1473;CANADIAN SYLLABICS KAA;Lo;0;L;;;;;N;;;;; +1474;CANADIAN SYLLABICS KWE;Lo;0;L;;;;;N;;;;; +1475;CANADIAN SYLLABICS WEST-CREE KWE;Lo;0;L;;;;;N;;;;; +1476;CANADIAN SYLLABICS KWI;Lo;0;L;;;;;N;;;;; +1477;CANADIAN SYLLABICS WEST-CREE KWI;Lo;0;L;;;;;N;;;;; +1478;CANADIAN SYLLABICS KWII;Lo;0;L;;;;;N;;;;; +1479;CANADIAN SYLLABICS WEST-CREE KWII;Lo;0;L;;;;;N;;;;; +147A;CANADIAN SYLLABICS KWO;Lo;0;L;;;;;N;;;;; +147B;CANADIAN SYLLABICS WEST-CREE KWO;Lo;0;L;;;;;N;;;;; +147C;CANADIAN SYLLABICS KWOO;Lo;0;L;;;;;N;;;;; +147D;CANADIAN SYLLABICS WEST-CREE KWOO;Lo;0;L;;;;;N;;;;; +147E;CANADIAN SYLLABICS KWA;Lo;0;L;;;;;N;;;;; +147F;CANADIAN SYLLABICS WEST-CREE KWA;Lo;0;L;;;;;N;;;;; +1480;CANADIAN SYLLABICS KWAA;Lo;0;L;;;;;N;;;;; +1481;CANADIAN SYLLABICS WEST-CREE KWAA;Lo;0;L;;;;;N;;;;; +1482;CANADIAN SYLLABICS NASKAPI KWAA;Lo;0;L;;;;;N;;;;; +1483;CANADIAN SYLLABICS K;Lo;0;L;;;;;N;;;;; +1484;CANADIAN SYLLABICS KW;Lo;0;L;;;;;N;;;;; +1485;CANADIAN SYLLABICS SOUTH-SLAVEY KEH;Lo;0;L;;;;;N;;;;; +1486;CANADIAN SYLLABICS SOUTH-SLAVEY KIH;Lo;0;L;;;;;N;;;;; +1487;CANADIAN SYLLABICS SOUTH-SLAVEY KOH;Lo;0;L;;;;;N;;;;; +1488;CANADIAN SYLLABICS SOUTH-SLAVEY KAH;Lo;0;L;;;;;N;;;;; +1489;CANADIAN SYLLABICS CE;Lo;0;L;;;;;N;;;;; +148A;CANADIAN SYLLABICS CAAI;Lo;0;L;;;;;N;;;;; +148B;CANADIAN SYLLABICS CI;Lo;0;L;;;;;N;;;;; +148C;CANADIAN SYLLABICS CII;Lo;0;L;;;;;N;;;;; +148D;CANADIAN SYLLABICS CO;Lo;0;L;;;;;N;;;;; +148E;CANADIAN SYLLABICS COO;Lo;0;L;;;;;N;;;;; +148F;CANADIAN SYLLABICS Y-CREE COO;Lo;0;L;;;;;N;;;;; +1490;CANADIAN SYLLABICS CA;Lo;0;L;;;;;N;;;;; +1491;CANADIAN SYLLABICS CAA;Lo;0;L;;;;;N;;;;; +1492;CANADIAN SYLLABICS CWE;Lo;0;L;;;;;N;;;;; +1493;CANADIAN SYLLABICS WEST-CREE CWE;Lo;0;L;;;;;N;;;;; +1494;CANADIAN SYLLABICS CWI;Lo;0;L;;;;;N;;;;; +1495;CANADIAN SYLLABICS WEST-CREE CWI;Lo;0;L;;;;;N;;;;; +1496;CANADIAN SYLLABICS CWII;Lo;0;L;;;;;N;;;;; +1497;CANADIAN SYLLABICS WEST-CREE CWII;Lo;0;L;;;;;N;;;;; +1498;CANADIAN SYLLABICS CWO;Lo;0;L;;;;;N;;;;; +1499;CANADIAN SYLLABICS WEST-CREE CWO;Lo;0;L;;;;;N;;;;; +149A;CANADIAN SYLLABICS CWOO;Lo;0;L;;;;;N;;;;; +149B;CANADIAN SYLLABICS WEST-CREE CWOO;Lo;0;L;;;;;N;;;;; +149C;CANADIAN SYLLABICS CWA;Lo;0;L;;;;;N;;;;; +149D;CANADIAN SYLLABICS WEST-CREE CWA;Lo;0;L;;;;;N;;;;; +149E;CANADIAN SYLLABICS CWAA;Lo;0;L;;;;;N;;;;; +149F;CANADIAN SYLLABICS WEST-CREE CWAA;Lo;0;L;;;;;N;;;;; +14A0;CANADIAN SYLLABICS NASKAPI CWAA;Lo;0;L;;;;;N;;;;; +14A1;CANADIAN SYLLABICS C;Lo;0;L;;;;;N;;;;; +14A2;CANADIAN SYLLABICS SAYISI TH;Lo;0;L;;;;;N;;;;; +14A3;CANADIAN SYLLABICS ME;Lo;0;L;;;;;N;;;;; +14A4;CANADIAN SYLLABICS MAAI;Lo;0;L;;;;;N;;;;; +14A5;CANADIAN SYLLABICS MI;Lo;0;L;;;;;N;;;;; +14A6;CANADIAN SYLLABICS MII;Lo;0;L;;;;;N;;;;; +14A7;CANADIAN SYLLABICS MO;Lo;0;L;;;;;N;;;;; +14A8;CANADIAN SYLLABICS MOO;Lo;0;L;;;;;N;;;;; +14A9;CANADIAN SYLLABICS Y-CREE MOO;Lo;0;L;;;;;N;;;;; +14AA;CANADIAN SYLLABICS MA;Lo;0;L;;;;;N;;;;; +14AB;CANADIAN SYLLABICS MAA;Lo;0;L;;;;;N;;;;; +14AC;CANADIAN SYLLABICS MWE;Lo;0;L;;;;;N;;;;; +14AD;CANADIAN SYLLABICS WEST-CREE MWE;Lo;0;L;;;;;N;;;;; +14AE;CANADIAN SYLLABICS MWI;Lo;0;L;;;;;N;;;;; +14AF;CANADIAN SYLLABICS WEST-CREE MWI;Lo;0;L;;;;;N;;;;; +14B0;CANADIAN SYLLABICS MWII;Lo;0;L;;;;;N;;;;; +14B1;CANADIAN SYLLABICS WEST-CREE MWII;Lo;0;L;;;;;N;;;;; +14B2;CANADIAN SYLLABICS MWO;Lo;0;L;;;;;N;;;;; +14B3;CANADIAN SYLLABICS WEST-CREE MWO;Lo;0;L;;;;;N;;;;; +14B4;CANADIAN SYLLABICS MWOO;Lo;0;L;;;;;N;;;;; +14B5;CANADIAN SYLLABICS WEST-CREE MWOO;Lo;0;L;;;;;N;;;;; +14B6;CANADIAN SYLLABICS MWA;Lo;0;L;;;;;N;;;;; +14B7;CANADIAN SYLLABICS WEST-CREE MWA;Lo;0;L;;;;;N;;;;; +14B8;CANADIAN SYLLABICS MWAA;Lo;0;L;;;;;N;;;;; +14B9;CANADIAN SYLLABICS WEST-CREE MWAA;Lo;0;L;;;;;N;;;;; +14BA;CANADIAN SYLLABICS NASKAPI MWAA;Lo;0;L;;;;;N;;;;; +14BB;CANADIAN SYLLABICS M;Lo;0;L;;;;;N;;;;; +14BC;CANADIAN SYLLABICS WEST-CREE M;Lo;0;L;;;;;N;;;;; +14BD;CANADIAN SYLLABICS MH;Lo;0;L;;;;;N;;;;; +14BE;CANADIAN SYLLABICS ATHAPASCAN M;Lo;0;L;;;;;N;;;;; +14BF;CANADIAN SYLLABICS SAYISI M;Lo;0;L;;;;;N;;;;; +14C0;CANADIAN SYLLABICS NE;Lo;0;L;;;;;N;;;;; +14C1;CANADIAN SYLLABICS NAAI;Lo;0;L;;;;;N;;;;; +14C2;CANADIAN SYLLABICS NI;Lo;0;L;;;;;N;;;;; +14C3;CANADIAN SYLLABICS NII;Lo;0;L;;;;;N;;;;; +14C4;CANADIAN SYLLABICS NO;Lo;0;L;;;;;N;;;;; +14C5;CANADIAN SYLLABICS NOO;Lo;0;L;;;;;N;;;;; +14C6;CANADIAN SYLLABICS Y-CREE NOO;Lo;0;L;;;;;N;;;;; +14C7;CANADIAN SYLLABICS NA;Lo;0;L;;;;;N;;;;; +14C8;CANADIAN SYLLABICS NAA;Lo;0;L;;;;;N;;;;; +14C9;CANADIAN SYLLABICS NWE;Lo;0;L;;;;;N;;;;; +14CA;CANADIAN SYLLABICS WEST-CREE NWE;Lo;0;L;;;;;N;;;;; +14CB;CANADIAN SYLLABICS NWA;Lo;0;L;;;;;N;;;;; +14CC;CANADIAN SYLLABICS WEST-CREE NWA;Lo;0;L;;;;;N;;;;; +14CD;CANADIAN SYLLABICS NWAA;Lo;0;L;;;;;N;;;;; +14CE;CANADIAN SYLLABICS WEST-CREE NWAA;Lo;0;L;;;;;N;;;;; +14CF;CANADIAN SYLLABICS NASKAPI NWAA;Lo;0;L;;;;;N;;;;; +14D0;CANADIAN SYLLABICS N;Lo;0;L;;;;;N;;;;; +14D1;CANADIAN SYLLABICS CARRIER NG;Lo;0;L;;;;;N;;;;; +14D2;CANADIAN SYLLABICS NH;Lo;0;L;;;;;N;;;;; +14D3;CANADIAN SYLLABICS LE;Lo;0;L;;;;;N;;;;; +14D4;CANADIAN SYLLABICS LAAI;Lo;0;L;;;;;N;;;;; +14D5;CANADIAN SYLLABICS LI;Lo;0;L;;;;;N;;;;; +14D6;CANADIAN SYLLABICS LII;Lo;0;L;;;;;N;;;;; +14D7;CANADIAN SYLLABICS LO;Lo;0;L;;;;;N;;;;; +14D8;CANADIAN SYLLABICS LOO;Lo;0;L;;;;;N;;;;; +14D9;CANADIAN SYLLABICS Y-CREE LOO;Lo;0;L;;;;;N;;;;; +14DA;CANADIAN SYLLABICS LA;Lo;0;L;;;;;N;;;;; +14DB;CANADIAN SYLLABICS LAA;Lo;0;L;;;;;N;;;;; +14DC;CANADIAN SYLLABICS LWE;Lo;0;L;;;;;N;;;;; +14DD;CANADIAN SYLLABICS WEST-CREE LWE;Lo;0;L;;;;;N;;;;; +14DE;CANADIAN SYLLABICS LWI;Lo;0;L;;;;;N;;;;; +14DF;CANADIAN SYLLABICS WEST-CREE LWI;Lo;0;L;;;;;N;;;;; +14E0;CANADIAN SYLLABICS LWII;Lo;0;L;;;;;N;;;;; +14E1;CANADIAN SYLLABICS WEST-CREE LWII;Lo;0;L;;;;;N;;;;; +14E2;CANADIAN SYLLABICS LWO;Lo;0;L;;;;;N;;;;; +14E3;CANADIAN SYLLABICS WEST-CREE LWO;Lo;0;L;;;;;N;;;;; +14E4;CANADIAN SYLLABICS LWOO;Lo;0;L;;;;;N;;;;; +14E5;CANADIAN SYLLABICS WEST-CREE LWOO;Lo;0;L;;;;;N;;;;; +14E6;CANADIAN SYLLABICS LWA;Lo;0;L;;;;;N;;;;; +14E7;CANADIAN SYLLABICS WEST-CREE LWA;Lo;0;L;;;;;N;;;;; +14E8;CANADIAN SYLLABICS LWAA;Lo;0;L;;;;;N;;;;; +14E9;CANADIAN SYLLABICS WEST-CREE LWAA;Lo;0;L;;;;;N;;;;; +14EA;CANADIAN SYLLABICS L;Lo;0;L;;;;;N;;;;; +14EB;CANADIAN SYLLABICS WEST-CREE L;Lo;0;L;;;;;N;;;;; +14EC;CANADIAN SYLLABICS MEDIAL L;Lo;0;L;;;;;N;;;;; +14ED;CANADIAN SYLLABICS SE;Lo;0;L;;;;;N;;;;; +14EE;CANADIAN SYLLABICS SAAI;Lo;0;L;;;;;N;;;;; +14EF;CANADIAN SYLLABICS SI;Lo;0;L;;;;;N;;;;; +14F0;CANADIAN SYLLABICS SII;Lo;0;L;;;;;N;;;;; +14F1;CANADIAN SYLLABICS SO;Lo;0;L;;;;;N;;;;; +14F2;CANADIAN SYLLABICS SOO;Lo;0;L;;;;;N;;;;; +14F3;CANADIAN SYLLABICS Y-CREE SOO;Lo;0;L;;;;;N;;;;; +14F4;CANADIAN SYLLABICS SA;Lo;0;L;;;;;N;;;;; +14F5;CANADIAN SYLLABICS SAA;Lo;0;L;;;;;N;;;;; +14F6;CANADIAN SYLLABICS SWE;Lo;0;L;;;;;N;;;;; +14F7;CANADIAN SYLLABICS WEST-CREE SWE;Lo;0;L;;;;;N;;;;; +14F8;CANADIAN SYLLABICS SWI;Lo;0;L;;;;;N;;;;; +14F9;CANADIAN SYLLABICS WEST-CREE SWI;Lo;0;L;;;;;N;;;;; +14FA;CANADIAN SYLLABICS SWII;Lo;0;L;;;;;N;;;;; +14FB;CANADIAN SYLLABICS WEST-CREE SWII;Lo;0;L;;;;;N;;;;; +14FC;CANADIAN SYLLABICS SWO;Lo;0;L;;;;;N;;;;; +14FD;CANADIAN SYLLABICS WEST-CREE SWO;Lo;0;L;;;;;N;;;;; +14FE;CANADIAN SYLLABICS SWOO;Lo;0;L;;;;;N;;;;; +14FF;CANADIAN SYLLABICS WEST-CREE SWOO;Lo;0;L;;;;;N;;;;; +1500;CANADIAN SYLLABICS SWA;Lo;0;L;;;;;N;;;;; +1501;CANADIAN SYLLABICS WEST-CREE SWA;Lo;0;L;;;;;N;;;;; +1502;CANADIAN SYLLABICS SWAA;Lo;0;L;;;;;N;;;;; +1503;CANADIAN SYLLABICS WEST-CREE SWAA;Lo;0;L;;;;;N;;;;; +1504;CANADIAN SYLLABICS NASKAPI SWAA;Lo;0;L;;;;;N;;;;; +1505;CANADIAN SYLLABICS S;Lo;0;L;;;;;N;;;;; +1506;CANADIAN SYLLABICS ATHAPASCAN S;Lo;0;L;;;;;N;;;;; +1507;CANADIAN SYLLABICS SW;Lo;0;L;;;;;N;;;;; +1508;CANADIAN SYLLABICS BLACKFOOT S;Lo;0;L;;;;;N;;;;; +1509;CANADIAN SYLLABICS MOOSE-CREE SK;Lo;0;L;;;;;N;;;;; +150A;CANADIAN SYLLABICS NASKAPI SKW;Lo;0;L;;;;;N;;;;; +150B;CANADIAN SYLLABICS NASKAPI S-W;Lo;0;L;;;;;N;;;;; +150C;CANADIAN SYLLABICS NASKAPI SPWA;Lo;0;L;;;;;N;;;;; +150D;CANADIAN SYLLABICS NASKAPI STWA;Lo;0;L;;;;;N;;;;; +150E;CANADIAN SYLLABICS NASKAPI SKWA;Lo;0;L;;;;;N;;;;; +150F;CANADIAN SYLLABICS NASKAPI SCWA;Lo;0;L;;;;;N;;;;; +1510;CANADIAN SYLLABICS SHE;Lo;0;L;;;;;N;;;;; +1511;CANADIAN SYLLABICS SHI;Lo;0;L;;;;;N;;;;; +1512;CANADIAN SYLLABICS SHII;Lo;0;L;;;;;N;;;;; +1513;CANADIAN SYLLABICS SHO;Lo;0;L;;;;;N;;;;; +1514;CANADIAN SYLLABICS SHOO;Lo;0;L;;;;;N;;;;; +1515;CANADIAN SYLLABICS SHA;Lo;0;L;;;;;N;;;;; +1516;CANADIAN SYLLABICS SHAA;Lo;0;L;;;;;N;;;;; +1517;CANADIAN SYLLABICS SHWE;Lo;0;L;;;;;N;;;;; +1518;CANADIAN SYLLABICS WEST-CREE SHWE;Lo;0;L;;;;;N;;;;; +1519;CANADIAN SYLLABICS SHWI;Lo;0;L;;;;;N;;;;; +151A;CANADIAN SYLLABICS WEST-CREE SHWI;Lo;0;L;;;;;N;;;;; +151B;CANADIAN SYLLABICS SHWII;Lo;0;L;;;;;N;;;;; +151C;CANADIAN SYLLABICS WEST-CREE SHWII;Lo;0;L;;;;;N;;;;; +151D;CANADIAN SYLLABICS SHWO;Lo;0;L;;;;;N;;;;; +151E;CANADIAN SYLLABICS WEST-CREE SHWO;Lo;0;L;;;;;N;;;;; +151F;CANADIAN SYLLABICS SHWOO;Lo;0;L;;;;;N;;;;; +1520;CANADIAN SYLLABICS WEST-CREE SHWOO;Lo;0;L;;;;;N;;;;; +1521;CANADIAN SYLLABICS SHWA;Lo;0;L;;;;;N;;;;; +1522;CANADIAN SYLLABICS WEST-CREE SHWA;Lo;0;L;;;;;N;;;;; +1523;CANADIAN SYLLABICS SHWAA;Lo;0;L;;;;;N;;;;; +1524;CANADIAN SYLLABICS WEST-CREE SHWAA;Lo;0;L;;;;;N;;;;; +1525;CANADIAN SYLLABICS SH;Lo;0;L;;;;;N;;;;; +1526;CANADIAN SYLLABICS YE;Lo;0;L;;;;;N;;;;; +1527;CANADIAN SYLLABICS YAAI;Lo;0;L;;;;;N;;;;; +1528;CANADIAN SYLLABICS YI;Lo;0;L;;;;;N;;;;; +1529;CANADIAN SYLLABICS YII;Lo;0;L;;;;;N;;;;; +152A;CANADIAN SYLLABICS YO;Lo;0;L;;;;;N;;;;; +152B;CANADIAN SYLLABICS YOO;Lo;0;L;;;;;N;;;;; +152C;CANADIAN SYLLABICS Y-CREE YOO;Lo;0;L;;;;;N;;;;; +152D;CANADIAN SYLLABICS YA;Lo;0;L;;;;;N;;;;; +152E;CANADIAN SYLLABICS YAA;Lo;0;L;;;;;N;;;;; +152F;CANADIAN SYLLABICS YWE;Lo;0;L;;;;;N;;;;; +1530;CANADIAN SYLLABICS WEST-CREE YWE;Lo;0;L;;;;;N;;;;; +1531;CANADIAN SYLLABICS YWI;Lo;0;L;;;;;N;;;;; +1532;CANADIAN SYLLABICS WEST-CREE YWI;Lo;0;L;;;;;N;;;;; +1533;CANADIAN SYLLABICS YWII;Lo;0;L;;;;;N;;;;; +1534;CANADIAN SYLLABICS WEST-CREE YWII;Lo;0;L;;;;;N;;;;; +1535;CANADIAN SYLLABICS YWO;Lo;0;L;;;;;N;;;;; +1536;CANADIAN SYLLABICS WEST-CREE YWO;Lo;0;L;;;;;N;;;;; +1537;CANADIAN SYLLABICS YWOO;Lo;0;L;;;;;N;;;;; +1538;CANADIAN SYLLABICS WEST-CREE YWOO;Lo;0;L;;;;;N;;;;; +1539;CANADIAN SYLLABICS YWA;Lo;0;L;;;;;N;;;;; +153A;CANADIAN SYLLABICS WEST-CREE YWA;Lo;0;L;;;;;N;;;;; +153B;CANADIAN SYLLABICS YWAA;Lo;0;L;;;;;N;;;;; +153C;CANADIAN SYLLABICS WEST-CREE YWAA;Lo;0;L;;;;;N;;;;; +153D;CANADIAN SYLLABICS NASKAPI YWAA;Lo;0;L;;;;;N;;;;; +153E;CANADIAN SYLLABICS Y;Lo;0;L;;;;;N;;;;; +153F;CANADIAN SYLLABICS BIBLE-CREE Y;Lo;0;L;;;;;N;;;;; +1540;CANADIAN SYLLABICS WEST-CREE Y;Lo;0;L;;;;;N;;;;; +1541;CANADIAN SYLLABICS SAYISI YI;Lo;0;L;;;;;N;;;;; +1542;CANADIAN SYLLABICS RE;Lo;0;L;;;;;N;;;;; +1543;CANADIAN SYLLABICS R-CREE RE;Lo;0;L;;;;;N;;;;; +1544;CANADIAN SYLLABICS WEST-CREE LE;Lo;0;L;;;;;N;;;;; +1545;CANADIAN SYLLABICS RAAI;Lo;0;L;;;;;N;;;;; +1546;CANADIAN SYLLABICS RI;Lo;0;L;;;;;N;;;;; +1547;CANADIAN SYLLABICS RII;Lo;0;L;;;;;N;;;;; +1548;CANADIAN SYLLABICS RO;Lo;0;L;;;;;N;;;;; +1549;CANADIAN SYLLABICS ROO;Lo;0;L;;;;;N;;;;; +154A;CANADIAN SYLLABICS WEST-CREE LO;Lo;0;L;;;;;N;;;;; +154B;CANADIAN SYLLABICS RA;Lo;0;L;;;;;N;;;;; +154C;CANADIAN SYLLABICS RAA;Lo;0;L;;;;;N;;;;; +154D;CANADIAN SYLLABICS WEST-CREE LA;Lo;0;L;;;;;N;;;;; +154E;CANADIAN SYLLABICS RWAA;Lo;0;L;;;;;N;;;;; +154F;CANADIAN SYLLABICS WEST-CREE RWAA;Lo;0;L;;;;;N;;;;; +1550;CANADIAN SYLLABICS R;Lo;0;L;;;;;N;;;;; +1551;CANADIAN SYLLABICS WEST-CREE R;Lo;0;L;;;;;N;;;;; +1552;CANADIAN SYLLABICS MEDIAL R;Lo;0;L;;;;;N;;;;; +1553;CANADIAN SYLLABICS FE;Lo;0;L;;;;;N;;;;; +1554;CANADIAN SYLLABICS FAAI;Lo;0;L;;;;;N;;;;; +1555;CANADIAN SYLLABICS FI;Lo;0;L;;;;;N;;;;; +1556;CANADIAN SYLLABICS FII;Lo;0;L;;;;;N;;;;; +1557;CANADIAN SYLLABICS FO;Lo;0;L;;;;;N;;;;; +1558;CANADIAN SYLLABICS FOO;Lo;0;L;;;;;N;;;;; +1559;CANADIAN SYLLABICS FA;Lo;0;L;;;;;N;;;;; +155A;CANADIAN SYLLABICS FAA;Lo;0;L;;;;;N;;;;; +155B;CANADIAN SYLLABICS FWAA;Lo;0;L;;;;;N;;;;; +155C;CANADIAN SYLLABICS WEST-CREE FWAA;Lo;0;L;;;;;N;;;;; +155D;CANADIAN SYLLABICS F;Lo;0;L;;;;;N;;;;; +155E;CANADIAN SYLLABICS THE;Lo;0;L;;;;;N;;;;; +155F;CANADIAN SYLLABICS N-CREE THE;Lo;0;L;;;;;N;;;;; +1560;CANADIAN SYLLABICS THI;Lo;0;L;;;;;N;;;;; +1561;CANADIAN SYLLABICS N-CREE THI;Lo;0;L;;;;;N;;;;; +1562;CANADIAN SYLLABICS THII;Lo;0;L;;;;;N;;;;; +1563;CANADIAN SYLLABICS N-CREE THII;Lo;0;L;;;;;N;;;;; +1564;CANADIAN SYLLABICS THO;Lo;0;L;;;;;N;;;;; +1565;CANADIAN SYLLABICS THOO;Lo;0;L;;;;;N;;;;; +1566;CANADIAN SYLLABICS THA;Lo;0;L;;;;;N;;;;; +1567;CANADIAN SYLLABICS THAA;Lo;0;L;;;;;N;;;;; +1568;CANADIAN SYLLABICS THWAA;Lo;0;L;;;;;N;;;;; +1569;CANADIAN SYLLABICS WEST-CREE THWAA;Lo;0;L;;;;;N;;;;; +156A;CANADIAN SYLLABICS TH;Lo;0;L;;;;;N;;;;; +156B;CANADIAN SYLLABICS TTHE;Lo;0;L;;;;;N;;;;; +156C;CANADIAN SYLLABICS TTHI;Lo;0;L;;;;;N;;;;; +156D;CANADIAN SYLLABICS TTHO;Lo;0;L;;;;;N;;;;; +156E;CANADIAN SYLLABICS TTHA;Lo;0;L;;;;;N;;;;; +156F;CANADIAN SYLLABICS TTH;Lo;0;L;;;;;N;;;;; +1570;CANADIAN SYLLABICS TYE;Lo;0;L;;;;;N;;;;; +1571;CANADIAN SYLLABICS TYI;Lo;0;L;;;;;N;;;;; +1572;CANADIAN SYLLABICS TYO;Lo;0;L;;;;;N;;;;; +1573;CANADIAN SYLLABICS TYA;Lo;0;L;;;;;N;;;;; +1574;CANADIAN SYLLABICS NUNAVIK HE;Lo;0;L;;;;;N;;;;; +1575;CANADIAN SYLLABICS NUNAVIK HI;Lo;0;L;;;;;N;;;;; +1576;CANADIAN SYLLABICS NUNAVIK HII;Lo;0;L;;;;;N;;;;; +1577;CANADIAN SYLLABICS NUNAVIK HO;Lo;0;L;;;;;N;;;;; +1578;CANADIAN SYLLABICS NUNAVIK HOO;Lo;0;L;;;;;N;;;;; +1579;CANADIAN SYLLABICS NUNAVIK HA;Lo;0;L;;;;;N;;;;; +157A;CANADIAN SYLLABICS NUNAVIK HAA;Lo;0;L;;;;;N;;;;; +157B;CANADIAN SYLLABICS NUNAVIK H;Lo;0;L;;;;;N;;;;; +157C;CANADIAN SYLLABICS NUNAVUT H;Lo;0;L;;;;;N;;;;; +157D;CANADIAN SYLLABICS HK;Lo;0;L;;;;;N;;;;; +157E;CANADIAN SYLLABICS QAAI;Lo;0;L;;;;;N;;;;; +157F;CANADIAN SYLLABICS QI;Lo;0;L;;;;;N;;;;; +1580;CANADIAN SYLLABICS QII;Lo;0;L;;;;;N;;;;; +1581;CANADIAN SYLLABICS QO;Lo;0;L;;;;;N;;;;; +1582;CANADIAN SYLLABICS QOO;Lo;0;L;;;;;N;;;;; +1583;CANADIAN SYLLABICS QA;Lo;0;L;;;;;N;;;;; +1584;CANADIAN SYLLABICS QAA;Lo;0;L;;;;;N;;;;; +1585;CANADIAN SYLLABICS Q;Lo;0;L;;;;;N;;;;; +1586;CANADIAN SYLLABICS TLHE;Lo;0;L;;;;;N;;;;; +1587;CANADIAN SYLLABICS TLHI;Lo;0;L;;;;;N;;;;; +1588;CANADIAN SYLLABICS TLHO;Lo;0;L;;;;;N;;;;; +1589;CANADIAN SYLLABICS TLHA;Lo;0;L;;;;;N;;;;; +158A;CANADIAN SYLLABICS WEST-CREE RE;Lo;0;L;;;;;N;;;;; +158B;CANADIAN SYLLABICS WEST-CREE RI;Lo;0;L;;;;;N;;;;; +158C;CANADIAN SYLLABICS WEST-CREE RO;Lo;0;L;;;;;N;;;;; +158D;CANADIAN SYLLABICS WEST-CREE RA;Lo;0;L;;;;;N;;;;; +158E;CANADIAN SYLLABICS NGAAI;Lo;0;L;;;;;N;;;;; +158F;CANADIAN SYLLABICS NGI;Lo;0;L;;;;;N;;;;; +1590;CANADIAN SYLLABICS NGII;Lo;0;L;;;;;N;;;;; +1591;CANADIAN SYLLABICS NGO;Lo;0;L;;;;;N;;;;; +1592;CANADIAN SYLLABICS NGOO;Lo;0;L;;;;;N;;;;; +1593;CANADIAN SYLLABICS NGA;Lo;0;L;;;;;N;;;;; +1594;CANADIAN SYLLABICS NGAA;Lo;0;L;;;;;N;;;;; +1595;CANADIAN SYLLABICS NG;Lo;0;L;;;;;N;;;;; +1596;CANADIAN SYLLABICS NNG;Lo;0;L;;;;;N;;;;; +1597;CANADIAN SYLLABICS SAYISI SHE;Lo;0;L;;;;;N;;;;; +1598;CANADIAN SYLLABICS SAYISI SHI;Lo;0;L;;;;;N;;;;; +1599;CANADIAN SYLLABICS SAYISI SHO;Lo;0;L;;;;;N;;;;; +159A;CANADIAN SYLLABICS SAYISI SHA;Lo;0;L;;;;;N;;;;; +159B;CANADIAN SYLLABICS WOODS-CREE THE;Lo;0;L;;;;;N;;;;; +159C;CANADIAN SYLLABICS WOODS-CREE THI;Lo;0;L;;;;;N;;;;; +159D;CANADIAN SYLLABICS WOODS-CREE THO;Lo;0;L;;;;;N;;;;; +159E;CANADIAN SYLLABICS WOODS-CREE THA;Lo;0;L;;;;;N;;;;; +159F;CANADIAN SYLLABICS WOODS-CREE TH;Lo;0;L;;;;;N;;;;; +15A0;CANADIAN SYLLABICS LHI;Lo;0;L;;;;;N;;;;; +15A1;CANADIAN SYLLABICS LHII;Lo;0;L;;;;;N;;;;; +15A2;CANADIAN SYLLABICS LHO;Lo;0;L;;;;;N;;;;; +15A3;CANADIAN SYLLABICS LHOO;Lo;0;L;;;;;N;;;;; +15A4;CANADIAN SYLLABICS LHA;Lo;0;L;;;;;N;;;;; +15A5;CANADIAN SYLLABICS LHAA;Lo;0;L;;;;;N;;;;; +15A6;CANADIAN SYLLABICS LH;Lo;0;L;;;;;N;;;;; +15A7;CANADIAN SYLLABICS TH-CREE THE;Lo;0;L;;;;;N;;;;; +15A8;CANADIAN SYLLABICS TH-CREE THI;Lo;0;L;;;;;N;;;;; +15A9;CANADIAN SYLLABICS TH-CREE THII;Lo;0;L;;;;;N;;;;; +15AA;CANADIAN SYLLABICS TH-CREE THO;Lo;0;L;;;;;N;;;;; +15AB;CANADIAN SYLLABICS TH-CREE THOO;Lo;0;L;;;;;N;;;;; +15AC;CANADIAN SYLLABICS TH-CREE THA;Lo;0;L;;;;;N;;;;; +15AD;CANADIAN SYLLABICS TH-CREE THAA;Lo;0;L;;;;;N;;;;; +15AE;CANADIAN SYLLABICS TH-CREE TH;Lo;0;L;;;;;N;;;;; +15AF;CANADIAN SYLLABICS AIVILIK B;Lo;0;L;;;;;N;;;;; +15B0;CANADIAN SYLLABICS BLACKFOOT E;Lo;0;L;;;;;N;;;;; +15B1;CANADIAN SYLLABICS BLACKFOOT I;Lo;0;L;;;;;N;;;;; +15B2;CANADIAN SYLLABICS BLACKFOOT O;Lo;0;L;;;;;N;;;;; +15B3;CANADIAN SYLLABICS BLACKFOOT A;Lo;0;L;;;;;N;;;;; +15B4;CANADIAN SYLLABICS BLACKFOOT WE;Lo;0;L;;;;;N;;;;; +15B5;CANADIAN SYLLABICS BLACKFOOT WI;Lo;0;L;;;;;N;;;;; +15B6;CANADIAN SYLLABICS BLACKFOOT WO;Lo;0;L;;;;;N;;;;; +15B7;CANADIAN SYLLABICS BLACKFOOT WA;Lo;0;L;;;;;N;;;;; +15B8;CANADIAN SYLLABICS BLACKFOOT NE;Lo;0;L;;;;;N;;;;; +15B9;CANADIAN SYLLABICS BLACKFOOT NI;Lo;0;L;;;;;N;;;;; +15BA;CANADIAN SYLLABICS BLACKFOOT NO;Lo;0;L;;;;;N;;;;; +15BB;CANADIAN SYLLABICS BLACKFOOT NA;Lo;0;L;;;;;N;;;;; +15BC;CANADIAN SYLLABICS BLACKFOOT KE;Lo;0;L;;;;;N;;;;; +15BD;CANADIAN SYLLABICS BLACKFOOT KI;Lo;0;L;;;;;N;;;;; +15BE;CANADIAN SYLLABICS BLACKFOOT KO;Lo;0;L;;;;;N;;;;; +15BF;CANADIAN SYLLABICS BLACKFOOT KA;Lo;0;L;;;;;N;;;;; +15C0;CANADIAN SYLLABICS SAYISI HE;Lo;0;L;;;;;N;;;;; +15C1;CANADIAN SYLLABICS SAYISI HI;Lo;0;L;;;;;N;;;;; +15C2;CANADIAN SYLLABICS SAYISI HO;Lo;0;L;;;;;N;;;;; +15C3;CANADIAN SYLLABICS SAYISI HA;Lo;0;L;;;;;N;;;;; +15C4;CANADIAN SYLLABICS CARRIER GHU;Lo;0;L;;;;;N;;;;; +15C5;CANADIAN SYLLABICS CARRIER GHO;Lo;0;L;;;;;N;;;;; +15C6;CANADIAN SYLLABICS CARRIER GHE;Lo;0;L;;;;;N;;;;; +15C7;CANADIAN SYLLABICS CARRIER GHEE;Lo;0;L;;;;;N;;;;; +15C8;CANADIAN SYLLABICS CARRIER GHI;Lo;0;L;;;;;N;;;;; +15C9;CANADIAN SYLLABICS CARRIER GHA;Lo;0;L;;;;;N;;;;; +15CA;CANADIAN SYLLABICS CARRIER RU;Lo;0;L;;;;;N;;;;; +15CB;CANADIAN SYLLABICS CARRIER RO;Lo;0;L;;;;;N;;;;; +15CC;CANADIAN SYLLABICS CARRIER RE;Lo;0;L;;;;;N;;;;; +15CD;CANADIAN SYLLABICS CARRIER REE;Lo;0;L;;;;;N;;;;; +15CE;CANADIAN SYLLABICS CARRIER RI;Lo;0;L;;;;;N;;;;; +15CF;CANADIAN SYLLABICS CARRIER RA;Lo;0;L;;;;;N;;;;; +15D0;CANADIAN SYLLABICS CARRIER WU;Lo;0;L;;;;;N;;;;; +15D1;CANADIAN SYLLABICS CARRIER WO;Lo;0;L;;;;;N;;;;; +15D2;CANADIAN SYLLABICS CARRIER WE;Lo;0;L;;;;;N;;;;; +15D3;CANADIAN SYLLABICS CARRIER WEE;Lo;0;L;;;;;N;;;;; +15D4;CANADIAN SYLLABICS CARRIER WI;Lo;0;L;;;;;N;;;;; +15D5;CANADIAN SYLLABICS CARRIER WA;Lo;0;L;;;;;N;;;;; +15D6;CANADIAN SYLLABICS CARRIER HWU;Lo;0;L;;;;;N;;;;; +15D7;CANADIAN SYLLABICS CARRIER HWO;Lo;0;L;;;;;N;;;;; +15D8;CANADIAN SYLLABICS CARRIER HWE;Lo;0;L;;;;;N;;;;; +15D9;CANADIAN SYLLABICS CARRIER HWEE;Lo;0;L;;;;;N;;;;; +15DA;CANADIAN SYLLABICS CARRIER HWI;Lo;0;L;;;;;N;;;;; +15DB;CANADIAN SYLLABICS CARRIER HWA;Lo;0;L;;;;;N;;;;; +15DC;CANADIAN SYLLABICS CARRIER THU;Lo;0;L;;;;;N;;;;; +15DD;CANADIAN SYLLABICS CARRIER THO;Lo;0;L;;;;;N;;;;; +15DE;CANADIAN SYLLABICS CARRIER THE;Lo;0;L;;;;;N;;;;; +15DF;CANADIAN SYLLABICS CARRIER THEE;Lo;0;L;;;;;N;;;;; +15E0;CANADIAN SYLLABICS CARRIER THI;Lo;0;L;;;;;N;;;;; +15E1;CANADIAN SYLLABICS CARRIER THA;Lo;0;L;;;;;N;;;;; +15E2;CANADIAN SYLLABICS CARRIER TTU;Lo;0;L;;;;;N;;;;; +15E3;CANADIAN SYLLABICS CARRIER TTO;Lo;0;L;;;;;N;;;;; +15E4;CANADIAN SYLLABICS CARRIER TTE;Lo;0;L;;;;;N;;;;; +15E5;CANADIAN SYLLABICS CARRIER TTEE;Lo;0;L;;;;;N;;;;; +15E6;CANADIAN SYLLABICS CARRIER TTI;Lo;0;L;;;;;N;;;;; +15E7;CANADIAN SYLLABICS CARRIER TTA;Lo;0;L;;;;;N;;;;; +15E8;CANADIAN SYLLABICS CARRIER PU;Lo;0;L;;;;;N;;;;; +15E9;CANADIAN SYLLABICS CARRIER PO;Lo;0;L;;;;;N;;;;; +15EA;CANADIAN SYLLABICS CARRIER PE;Lo;0;L;;;;;N;;;;; +15EB;CANADIAN SYLLABICS CARRIER PEE;Lo;0;L;;;;;N;;;;; +15EC;CANADIAN SYLLABICS CARRIER PI;Lo;0;L;;;;;N;;;;; +15ED;CANADIAN SYLLABICS CARRIER PA;Lo;0;L;;;;;N;;;;; +15EE;CANADIAN SYLLABICS CARRIER P;Lo;0;L;;;;;N;;;;; +15EF;CANADIAN SYLLABICS CARRIER GU;Lo;0;L;;;;;N;;;;; +15F0;CANADIAN SYLLABICS CARRIER GO;Lo;0;L;;;;;N;;;;; +15F1;CANADIAN SYLLABICS CARRIER GE;Lo;0;L;;;;;N;;;;; +15F2;CANADIAN SYLLABICS CARRIER GEE;Lo;0;L;;;;;N;;;;; +15F3;CANADIAN SYLLABICS CARRIER GI;Lo;0;L;;;;;N;;;;; +15F4;CANADIAN SYLLABICS CARRIER GA;Lo;0;L;;;;;N;;;;; +15F5;CANADIAN SYLLABICS CARRIER KHU;Lo;0;L;;;;;N;;;;; +15F6;CANADIAN SYLLABICS CARRIER KHO;Lo;0;L;;;;;N;;;;; +15F7;CANADIAN SYLLABICS CARRIER KHE;Lo;0;L;;;;;N;;;;; +15F8;CANADIAN SYLLABICS CARRIER KHEE;Lo;0;L;;;;;N;;;;; +15F9;CANADIAN SYLLABICS CARRIER KHI;Lo;0;L;;;;;N;;;;; +15FA;CANADIAN SYLLABICS CARRIER KHA;Lo;0;L;;;;;N;;;;; +15FB;CANADIAN SYLLABICS CARRIER KKU;Lo;0;L;;;;;N;;;;; +15FC;CANADIAN SYLLABICS CARRIER KKO;Lo;0;L;;;;;N;;;;; +15FD;CANADIAN SYLLABICS CARRIER KKE;Lo;0;L;;;;;N;;;;; +15FE;CANADIAN SYLLABICS CARRIER KKEE;Lo;0;L;;;;;N;;;;; +15FF;CANADIAN SYLLABICS CARRIER KKI;Lo;0;L;;;;;N;;;;; +1600;CANADIAN SYLLABICS CARRIER KKA;Lo;0;L;;;;;N;;;;; +1601;CANADIAN SYLLABICS CARRIER KK;Lo;0;L;;;;;N;;;;; +1602;CANADIAN SYLLABICS CARRIER NU;Lo;0;L;;;;;N;;;;; +1603;CANADIAN SYLLABICS CARRIER NO;Lo;0;L;;;;;N;;;;; +1604;CANADIAN SYLLABICS CARRIER NE;Lo;0;L;;;;;N;;;;; +1605;CANADIAN SYLLABICS CARRIER NEE;Lo;0;L;;;;;N;;;;; +1606;CANADIAN SYLLABICS CARRIER NI;Lo;0;L;;;;;N;;;;; +1607;CANADIAN SYLLABICS CARRIER NA;Lo;0;L;;;;;N;;;;; +1608;CANADIAN SYLLABICS CARRIER MU;Lo;0;L;;;;;N;;;;; +1609;CANADIAN SYLLABICS CARRIER MO;Lo;0;L;;;;;N;;;;; +160A;CANADIAN SYLLABICS CARRIER ME;Lo;0;L;;;;;N;;;;; +160B;CANADIAN SYLLABICS CARRIER MEE;Lo;0;L;;;;;N;;;;; +160C;CANADIAN SYLLABICS CARRIER MI;Lo;0;L;;;;;N;;;;; +160D;CANADIAN SYLLABICS CARRIER MA;Lo;0;L;;;;;N;;;;; +160E;CANADIAN SYLLABICS CARRIER YU;Lo;0;L;;;;;N;;;;; +160F;CANADIAN SYLLABICS CARRIER YO;Lo;0;L;;;;;N;;;;; +1610;CANADIAN SYLLABICS CARRIER YE;Lo;0;L;;;;;N;;;;; +1611;CANADIAN SYLLABICS CARRIER YEE;Lo;0;L;;;;;N;;;;; +1612;CANADIAN SYLLABICS CARRIER YI;Lo;0;L;;;;;N;;;;; +1613;CANADIAN SYLLABICS CARRIER YA;Lo;0;L;;;;;N;;;;; +1614;CANADIAN SYLLABICS CARRIER JU;Lo;0;L;;;;;N;;;;; +1615;CANADIAN SYLLABICS SAYISI JU;Lo;0;L;;;;;N;;;;; +1616;CANADIAN SYLLABICS CARRIER JO;Lo;0;L;;;;;N;;;;; +1617;CANADIAN SYLLABICS CARRIER JE;Lo;0;L;;;;;N;;;;; +1618;CANADIAN SYLLABICS CARRIER JEE;Lo;0;L;;;;;N;;;;; +1619;CANADIAN SYLLABICS CARRIER JI;Lo;0;L;;;;;N;;;;; +161A;CANADIAN SYLLABICS SAYISI JI;Lo;0;L;;;;;N;;;;; +161B;CANADIAN SYLLABICS CARRIER JA;Lo;0;L;;;;;N;;;;; +161C;CANADIAN SYLLABICS CARRIER JJU;Lo;0;L;;;;;N;;;;; +161D;CANADIAN SYLLABICS CARRIER JJO;Lo;0;L;;;;;N;;;;; +161E;CANADIAN SYLLABICS CARRIER JJE;Lo;0;L;;;;;N;;;;; +161F;CANADIAN SYLLABICS CARRIER JJEE;Lo;0;L;;;;;N;;;;; +1620;CANADIAN SYLLABICS CARRIER JJI;Lo;0;L;;;;;N;;;;; +1621;CANADIAN SYLLABICS CARRIER JJA;Lo;0;L;;;;;N;;;;; +1622;CANADIAN SYLLABICS CARRIER LU;Lo;0;L;;;;;N;;;;; +1623;CANADIAN SYLLABICS CARRIER LO;Lo;0;L;;;;;N;;;;; +1624;CANADIAN SYLLABICS CARRIER LE;Lo;0;L;;;;;N;;;;; +1625;CANADIAN SYLLABICS CARRIER LEE;Lo;0;L;;;;;N;;;;; +1626;CANADIAN SYLLABICS CARRIER LI;Lo;0;L;;;;;N;;;;; +1627;CANADIAN SYLLABICS CARRIER LA;Lo;0;L;;;;;N;;;;; +1628;CANADIAN SYLLABICS CARRIER DLU;Lo;0;L;;;;;N;;;;; +1629;CANADIAN SYLLABICS CARRIER DLO;Lo;0;L;;;;;N;;;;; +162A;CANADIAN SYLLABICS CARRIER DLE;Lo;0;L;;;;;N;;;;; +162B;CANADIAN SYLLABICS CARRIER DLEE;Lo;0;L;;;;;N;;;;; +162C;CANADIAN SYLLABICS CARRIER DLI;Lo;0;L;;;;;N;;;;; +162D;CANADIAN SYLLABICS CARRIER DLA;Lo;0;L;;;;;N;;;;; +162E;CANADIAN SYLLABICS CARRIER LHU;Lo;0;L;;;;;N;;;;; +162F;CANADIAN SYLLABICS CARRIER LHO;Lo;0;L;;;;;N;;;;; +1630;CANADIAN SYLLABICS CARRIER LHE;Lo;0;L;;;;;N;;;;; +1631;CANADIAN SYLLABICS CARRIER LHEE;Lo;0;L;;;;;N;;;;; +1632;CANADIAN SYLLABICS CARRIER LHI;Lo;0;L;;;;;N;;;;; +1633;CANADIAN SYLLABICS CARRIER LHA;Lo;0;L;;;;;N;;;;; +1634;CANADIAN SYLLABICS CARRIER TLHU;Lo;0;L;;;;;N;;;;; +1635;CANADIAN SYLLABICS CARRIER TLHO;Lo;0;L;;;;;N;;;;; +1636;CANADIAN SYLLABICS CARRIER TLHE;Lo;0;L;;;;;N;;;;; +1637;CANADIAN SYLLABICS CARRIER TLHEE;Lo;0;L;;;;;N;;;;; +1638;CANADIAN SYLLABICS CARRIER TLHI;Lo;0;L;;;;;N;;;;; +1639;CANADIAN SYLLABICS CARRIER TLHA;Lo;0;L;;;;;N;;;;; +163A;CANADIAN SYLLABICS CARRIER TLU;Lo;0;L;;;;;N;;;;; +163B;CANADIAN SYLLABICS CARRIER TLO;Lo;0;L;;;;;N;;;;; +163C;CANADIAN SYLLABICS CARRIER TLE;Lo;0;L;;;;;N;;;;; +163D;CANADIAN SYLLABICS CARRIER TLEE;Lo;0;L;;;;;N;;;;; +163E;CANADIAN SYLLABICS CARRIER TLI;Lo;0;L;;;;;N;;;;; +163F;CANADIAN SYLLABICS CARRIER TLA;Lo;0;L;;;;;N;;;;; +1640;CANADIAN SYLLABICS CARRIER ZU;Lo;0;L;;;;;N;;;;; +1641;CANADIAN SYLLABICS CARRIER ZO;Lo;0;L;;;;;N;;;;; +1642;CANADIAN SYLLABICS CARRIER ZE;Lo;0;L;;;;;N;;;;; +1643;CANADIAN SYLLABICS CARRIER ZEE;Lo;0;L;;;;;N;;;;; +1644;CANADIAN SYLLABICS CARRIER ZI;Lo;0;L;;;;;N;;;;; +1645;CANADIAN SYLLABICS CARRIER ZA;Lo;0;L;;;;;N;;;;; +1646;CANADIAN SYLLABICS CARRIER Z;Lo;0;L;;;;;N;;;;; +1647;CANADIAN SYLLABICS CARRIER INITIAL Z;Lo;0;L;;;;;N;;;;; +1648;CANADIAN SYLLABICS CARRIER DZU;Lo;0;L;;;;;N;;;;; +1649;CANADIAN SYLLABICS CARRIER DZO;Lo;0;L;;;;;N;;;;; +164A;CANADIAN SYLLABICS CARRIER DZE;Lo;0;L;;;;;N;;;;; +164B;CANADIAN SYLLABICS CARRIER DZEE;Lo;0;L;;;;;N;;;;; +164C;CANADIAN SYLLABICS CARRIER DZI;Lo;0;L;;;;;N;;;;; +164D;CANADIAN SYLLABICS CARRIER DZA;Lo;0;L;;;;;N;;;;; +164E;CANADIAN SYLLABICS CARRIER SU;Lo;0;L;;;;;N;;;;; +164F;CANADIAN SYLLABICS CARRIER SO;Lo;0;L;;;;;N;;;;; +1650;CANADIAN SYLLABICS CARRIER SE;Lo;0;L;;;;;N;;;;; +1651;CANADIAN SYLLABICS CARRIER SEE;Lo;0;L;;;;;N;;;;; +1652;CANADIAN SYLLABICS CARRIER SI;Lo;0;L;;;;;N;;;;; +1653;CANADIAN SYLLABICS CARRIER SA;Lo;0;L;;;;;N;;;;; +1654;CANADIAN SYLLABICS CARRIER SHU;Lo;0;L;;;;;N;;;;; +1655;CANADIAN SYLLABICS CARRIER SHO;Lo;0;L;;;;;N;;;;; +1656;CANADIAN SYLLABICS CARRIER SHE;Lo;0;L;;;;;N;;;;; +1657;CANADIAN SYLLABICS CARRIER SHEE;Lo;0;L;;;;;N;;;;; +1658;CANADIAN SYLLABICS CARRIER SHI;Lo;0;L;;;;;N;;;;; +1659;CANADIAN SYLLABICS CARRIER SHA;Lo;0;L;;;;;N;;;;; +165A;CANADIAN SYLLABICS CARRIER SH;Lo;0;L;;;;;N;;;;; +165B;CANADIAN SYLLABICS CARRIER TSU;Lo;0;L;;;;;N;;;;; +165C;CANADIAN SYLLABICS CARRIER TSO;Lo;0;L;;;;;N;;;;; +165D;CANADIAN SYLLABICS CARRIER TSE;Lo;0;L;;;;;N;;;;; +165E;CANADIAN SYLLABICS CARRIER TSEE;Lo;0;L;;;;;N;;;;; +165F;CANADIAN SYLLABICS CARRIER TSI;Lo;0;L;;;;;N;;;;; +1660;CANADIAN SYLLABICS CARRIER TSA;Lo;0;L;;;;;N;;;;; +1661;CANADIAN SYLLABICS CARRIER CHU;Lo;0;L;;;;;N;;;;; +1662;CANADIAN SYLLABICS CARRIER CHO;Lo;0;L;;;;;N;;;;; +1663;CANADIAN SYLLABICS CARRIER CHE;Lo;0;L;;;;;N;;;;; +1664;CANADIAN SYLLABICS CARRIER CHEE;Lo;0;L;;;;;N;;;;; +1665;CANADIAN SYLLABICS CARRIER CHI;Lo;0;L;;;;;N;;;;; +1666;CANADIAN SYLLABICS CARRIER CHA;Lo;0;L;;;;;N;;;;; +1667;CANADIAN SYLLABICS CARRIER TTSU;Lo;0;L;;;;;N;;;;; +1668;CANADIAN SYLLABICS CARRIER TTSO;Lo;0;L;;;;;N;;;;; +1669;CANADIAN SYLLABICS CARRIER TTSE;Lo;0;L;;;;;N;;;;; +166A;CANADIAN SYLLABICS CARRIER TTSEE;Lo;0;L;;;;;N;;;;; +166B;CANADIAN SYLLABICS CARRIER TTSI;Lo;0;L;;;;;N;;;;; +166C;CANADIAN SYLLABICS CARRIER TTSA;Lo;0;L;;;;;N;;;;; +166D;CANADIAN SYLLABICS CHI SIGN;Po;0;L;;;;;N;;;;; +166E;CANADIAN SYLLABICS FULL STOP;Po;0;L;;;;;N;;;;; +166F;CANADIAN SYLLABICS QAI;Lo;0;L;;;;;N;;;;; +1670;CANADIAN SYLLABICS NGAI;Lo;0;L;;;;;N;;;;; +1671;CANADIAN SYLLABICS NNGI;Lo;0;L;;;;;N;;;;; +1672;CANADIAN SYLLABICS NNGII;Lo;0;L;;;;;N;;;;; +1673;CANADIAN SYLLABICS NNGO;Lo;0;L;;;;;N;;;;; +1674;CANADIAN SYLLABICS NNGOO;Lo;0;L;;;;;N;;;;; +1675;CANADIAN SYLLABICS NNGA;Lo;0;L;;;;;N;;;;; +1676;CANADIAN SYLLABICS NNGAA;Lo;0;L;;;;;N;;;;; +1677;CANADIAN SYLLABICS WOODS-CREE THWEE;Lo;0;L;;;;;N;;;;; +1678;CANADIAN SYLLABICS WOODS-CREE THWI;Lo;0;L;;;;;N;;;;; +1679;CANADIAN SYLLABICS WOODS-CREE THWII;Lo;0;L;;;;;N;;;;; +167A;CANADIAN SYLLABICS WOODS-CREE THWO;Lo;0;L;;;;;N;;;;; +167B;CANADIAN SYLLABICS WOODS-CREE THWOO;Lo;0;L;;;;;N;;;;; +167C;CANADIAN SYLLABICS WOODS-CREE THWA;Lo;0;L;;;;;N;;;;; +167D;CANADIAN SYLLABICS WOODS-CREE THWAA;Lo;0;L;;;;;N;;;;; +167E;CANADIAN SYLLABICS WOODS-CREE FINAL TH;Lo;0;L;;;;;N;;;;; +167F;CANADIAN SYLLABICS BLACKFOOT W;Lo;0;L;;;;;N;;;;; +1680;OGHAM SPACE MARK;Zs;0;WS;;;;;N;;;;; +1681;OGHAM LETTER BEITH;Lo;0;L;;;;;N;;;;; +1682;OGHAM LETTER LUIS;Lo;0;L;;;;;N;;;;; +1683;OGHAM LETTER FEARN;Lo;0;L;;;;;N;;;;; +1684;OGHAM LETTER SAIL;Lo;0;L;;;;;N;;;;; +1685;OGHAM LETTER NION;Lo;0;L;;;;;N;;;;; +1686;OGHAM LETTER UATH;Lo;0;L;;;;;N;;;;; +1687;OGHAM LETTER DAIR;Lo;0;L;;;;;N;;;;; +1688;OGHAM LETTER TINNE;Lo;0;L;;;;;N;;;;; +1689;OGHAM LETTER COLL;Lo;0;L;;;;;N;;;;; +168A;OGHAM LETTER CEIRT;Lo;0;L;;;;;N;;;;; +168B;OGHAM LETTER MUIN;Lo;0;L;;;;;N;;;;; +168C;OGHAM LETTER GORT;Lo;0;L;;;;;N;;;;; +168D;OGHAM LETTER NGEADAL;Lo;0;L;;;;;N;;;;; +168E;OGHAM LETTER STRAIF;Lo;0;L;;;;;N;;;;; +168F;OGHAM LETTER RUIS;Lo;0;L;;;;;N;;;;; +1690;OGHAM LETTER AILM;Lo;0;L;;;;;N;;;;; +1691;OGHAM LETTER ONN;Lo;0;L;;;;;N;;;;; +1692;OGHAM LETTER UR;Lo;0;L;;;;;N;;;;; +1693;OGHAM LETTER EADHADH;Lo;0;L;;;;;N;;;;; +1694;OGHAM LETTER IODHADH;Lo;0;L;;;;;N;;;;; +1695;OGHAM LETTER EABHADH;Lo;0;L;;;;;N;;;;; +1696;OGHAM LETTER OR;Lo;0;L;;;;;N;;;;; +1697;OGHAM LETTER UILLEANN;Lo;0;L;;;;;N;;;;; +1698;OGHAM LETTER IFIN;Lo;0;L;;;;;N;;;;; +1699;OGHAM LETTER EAMHANCHOLL;Lo;0;L;;;;;N;;;;; +169A;OGHAM LETTER PEITH;Lo;0;L;;;;;N;;;;; +169B;OGHAM FEATHER MARK;Ps;0;ON;;;;;Y;;;;; +169C;OGHAM REVERSED FEATHER MARK;Pe;0;ON;;;;;Y;;;;; +16A0;RUNIC LETTER FEHU FEOH FE F;Lo;0;L;;;;;N;;;;; +16A1;RUNIC LETTER V;Lo;0;L;;;;;N;;;;; +16A2;RUNIC LETTER URUZ UR U;Lo;0;L;;;;;N;;;;; +16A3;RUNIC LETTER YR;Lo;0;L;;;;;N;;;;; +16A4;RUNIC LETTER Y;Lo;0;L;;;;;N;;;;; +16A5;RUNIC LETTER W;Lo;0;L;;;;;N;;;;; +16A6;RUNIC LETTER THURISAZ THURS THORN;Lo;0;L;;;;;N;;;;; +16A7;RUNIC LETTER ETH;Lo;0;L;;;;;N;;;;; +16A8;RUNIC LETTER ANSUZ A;Lo;0;L;;;;;N;;;;; +16A9;RUNIC LETTER OS O;Lo;0;L;;;;;N;;;;; +16AA;RUNIC LETTER AC A;Lo;0;L;;;;;N;;;;; +16AB;RUNIC LETTER AESC;Lo;0;L;;;;;N;;;;; +16AC;RUNIC LETTER LONG-BRANCH-OSS O;Lo;0;L;;;;;N;;;;; +16AD;RUNIC LETTER SHORT-TWIG-OSS O;Lo;0;L;;;;;N;;;;; +16AE;RUNIC LETTER O;Lo;0;L;;;;;N;;;;; +16AF;RUNIC LETTER OE;Lo;0;L;;;;;N;;;;; +16B0;RUNIC LETTER ON;Lo;0;L;;;;;N;;;;; +16B1;RUNIC LETTER RAIDO RAD REID R;Lo;0;L;;;;;N;;;;; +16B2;RUNIC LETTER KAUNA;Lo;0;L;;;;;N;;;;; +16B3;RUNIC LETTER CEN;Lo;0;L;;;;;N;;;;; +16B4;RUNIC LETTER KAUN K;Lo;0;L;;;;;N;;;;; +16B5;RUNIC LETTER G;Lo;0;L;;;;;N;;;;; +16B6;RUNIC LETTER ENG;Lo;0;L;;;;;N;;;;; +16B7;RUNIC LETTER GEBO GYFU G;Lo;0;L;;;;;N;;;;; +16B8;RUNIC LETTER GAR;Lo;0;L;;;;;N;;;;; +16B9;RUNIC LETTER WUNJO WYNN W;Lo;0;L;;;;;N;;;;; +16BA;RUNIC LETTER HAGLAZ H;Lo;0;L;;;;;N;;;;; +16BB;RUNIC LETTER HAEGL H;Lo;0;L;;;;;N;;;;; +16BC;RUNIC LETTER LONG-BRANCH-HAGALL H;Lo;0;L;;;;;N;;;;; +16BD;RUNIC LETTER SHORT-TWIG-HAGALL H;Lo;0;L;;;;;N;;;;; +16BE;RUNIC LETTER NAUDIZ NYD NAUD N;Lo;0;L;;;;;N;;;;; +16BF;RUNIC LETTER SHORT-TWIG-NAUD N;Lo;0;L;;;;;N;;;;; +16C0;RUNIC LETTER DOTTED-N;Lo;0;L;;;;;N;;;;; +16C1;RUNIC LETTER ISAZ IS ISS I;Lo;0;L;;;;;N;;;;; +16C2;RUNIC LETTER E;Lo;0;L;;;;;N;;;;; +16C3;RUNIC LETTER JERAN J;Lo;0;L;;;;;N;;;;; +16C4;RUNIC LETTER GER;Lo;0;L;;;;;N;;;;; +16C5;RUNIC LETTER LONG-BRANCH-AR AE;Lo;0;L;;;;;N;;;;; +16C6;RUNIC LETTER SHORT-TWIG-AR A;Lo;0;L;;;;;N;;;;; +16C7;RUNIC LETTER IWAZ EOH;Lo;0;L;;;;;N;;;;; +16C8;RUNIC LETTER PERTHO PEORTH P;Lo;0;L;;;;;N;;;;; +16C9;RUNIC LETTER ALGIZ EOLHX;Lo;0;L;;;;;N;;;;; +16CA;RUNIC LETTER SOWILO S;Lo;0;L;;;;;N;;;;; +16CB;RUNIC LETTER SIGEL LONG-BRANCH-SOL S;Lo;0;L;;;;;N;;;;; +16CC;RUNIC LETTER SHORT-TWIG-SOL S;Lo;0;L;;;;;N;;;;; +16CD;RUNIC LETTER C;Lo;0;L;;;;;N;;;;; +16CE;RUNIC LETTER Z;Lo;0;L;;;;;N;;;;; +16CF;RUNIC LETTER TIWAZ TIR TYR T;Lo;0;L;;;;;N;;;;; +16D0;RUNIC LETTER SHORT-TWIG-TYR T;Lo;0;L;;;;;N;;;;; +16D1;RUNIC LETTER D;Lo;0;L;;;;;N;;;;; +16D2;RUNIC LETTER BERKANAN BEORC BJARKAN B;Lo;0;L;;;;;N;;;;; +16D3;RUNIC LETTER SHORT-TWIG-BJARKAN B;Lo;0;L;;;;;N;;;;; +16D4;RUNIC LETTER DOTTED-P;Lo;0;L;;;;;N;;;;; +16D5;RUNIC LETTER OPEN-P;Lo;0;L;;;;;N;;;;; +16D6;RUNIC LETTER EHWAZ EH E;Lo;0;L;;;;;N;;;;; +16D7;RUNIC LETTER MANNAZ MAN M;Lo;0;L;;;;;N;;;;; +16D8;RUNIC LETTER LONG-BRANCH-MADR M;Lo;0;L;;;;;N;;;;; +16D9;RUNIC LETTER SHORT-TWIG-MADR M;Lo;0;L;;;;;N;;;;; +16DA;RUNIC LETTER LAUKAZ LAGU LOGR L;Lo;0;L;;;;;N;;;;; +16DB;RUNIC LETTER DOTTED-L;Lo;0;L;;;;;N;;;;; +16DC;RUNIC LETTER INGWAZ;Lo;0;L;;;;;N;;;;; +16DD;RUNIC LETTER ING;Lo;0;L;;;;;N;;;;; +16DE;RUNIC LETTER DAGAZ DAEG D;Lo;0;L;;;;;N;;;;; +16DF;RUNIC LETTER OTHALAN ETHEL O;Lo;0;L;;;;;N;;;;; +16E0;RUNIC LETTER EAR;Lo;0;L;;;;;N;;;;; +16E1;RUNIC LETTER IOR;Lo;0;L;;;;;N;;;;; +16E2;RUNIC LETTER CWEORTH;Lo;0;L;;;;;N;;;;; +16E3;RUNIC LETTER CALC;Lo;0;L;;;;;N;;;;; +16E4;RUNIC LETTER CEALC;Lo;0;L;;;;;N;;;;; +16E5;RUNIC LETTER STAN;Lo;0;L;;;;;N;;;;; +16E6;RUNIC LETTER LONG-BRANCH-YR;Lo;0;L;;;;;N;;;;; +16E7;RUNIC LETTER SHORT-TWIG-YR;Lo;0;L;;;;;N;;;;; +16E8;RUNIC LETTER ICELANDIC-YR;Lo;0;L;;;;;N;;;;; +16E9;RUNIC LETTER Q;Lo;0;L;;;;;N;;;;; +16EA;RUNIC LETTER X;Lo;0;L;;;;;N;;;;; +16EB;RUNIC SINGLE PUNCTUATION;Po;0;L;;;;;N;;;;; +16EC;RUNIC MULTIPLE PUNCTUATION;Po;0;L;;;;;N;;;;; +16ED;RUNIC CROSS PUNCTUATION;Po;0;L;;;;;N;;;;; +16EE;RUNIC ARLAUG SYMBOL;Nl;0;L;;;;17;N;;;;; +16EF;RUNIC TVIMADUR SYMBOL;Nl;0;L;;;;18;N;;;;; +16F0;RUNIC BELGTHOR SYMBOL;Nl;0;L;;;;19;N;;;;; +1700;TAGALOG LETTER A;Lo;0;L;;;;;N;;;;; +1701;TAGALOG LETTER I;Lo;0;L;;;;;N;;;;; +1702;TAGALOG LETTER U;Lo;0;L;;;;;N;;;;; +1703;TAGALOG LETTER KA;Lo;0;L;;;;;N;;;;; +1704;TAGALOG LETTER GA;Lo;0;L;;;;;N;;;;; +1705;TAGALOG LETTER NGA;Lo;0;L;;;;;N;;;;; +1706;TAGALOG LETTER TA;Lo;0;L;;;;;N;;;;; +1707;TAGALOG LETTER DA;Lo;0;L;;;;;N;;;;; +1708;TAGALOG LETTER NA;Lo;0;L;;;;;N;;;;; +1709;TAGALOG LETTER PA;Lo;0;L;;;;;N;;;;; +170A;TAGALOG LETTER BA;Lo;0;L;;;;;N;;;;; +170B;TAGALOG LETTER MA;Lo;0;L;;;;;N;;;;; +170C;TAGALOG LETTER YA;Lo;0;L;;;;;N;;;;; +170E;TAGALOG LETTER LA;Lo;0;L;;;;;N;;;;; +170F;TAGALOG LETTER WA;Lo;0;L;;;;;N;;;;; +1710;TAGALOG LETTER SA;Lo;0;L;;;;;N;;;;; +1711;TAGALOG LETTER HA;Lo;0;L;;;;;N;;;;; +1712;TAGALOG VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +1713;TAGALOG VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +1714;TAGALOG SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +1720;HANUNOO LETTER A;Lo;0;L;;;;;N;;;;; +1721;HANUNOO LETTER I;Lo;0;L;;;;;N;;;;; +1722;HANUNOO LETTER U;Lo;0;L;;;;;N;;;;; +1723;HANUNOO LETTER KA;Lo;0;L;;;;;N;;;;; +1724;HANUNOO LETTER GA;Lo;0;L;;;;;N;;;;; +1725;HANUNOO LETTER NGA;Lo;0;L;;;;;N;;;;; +1726;HANUNOO LETTER TA;Lo;0;L;;;;;N;;;;; +1727;HANUNOO LETTER DA;Lo;0;L;;;;;N;;;;; +1728;HANUNOO LETTER NA;Lo;0;L;;;;;N;;;;; +1729;HANUNOO LETTER PA;Lo;0;L;;;;;N;;;;; +172A;HANUNOO LETTER BA;Lo;0;L;;;;;N;;;;; +172B;HANUNOO LETTER MA;Lo;0;L;;;;;N;;;;; +172C;HANUNOO LETTER YA;Lo;0;L;;;;;N;;;;; +172D;HANUNOO LETTER RA;Lo;0;L;;;;;N;;;;; +172E;HANUNOO LETTER LA;Lo;0;L;;;;;N;;;;; +172F;HANUNOO LETTER WA;Lo;0;L;;;;;N;;;;; +1730;HANUNOO LETTER SA;Lo;0;L;;;;;N;;;;; +1731;HANUNOO LETTER HA;Lo;0;L;;;;;N;;;;; +1732;HANUNOO VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +1733;HANUNOO VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +1734;HANUNOO SIGN PAMUDPOD;Mn;9;NSM;;;;;N;;;;; +1735;PHILIPPINE SINGLE PUNCTUATION;Po;0;L;;;;;N;;;;; +1736;PHILIPPINE DOUBLE PUNCTUATION;Po;0;L;;;;;N;;;;; +1740;BUHID LETTER A;Lo;0;L;;;;;N;;;;; +1741;BUHID LETTER I;Lo;0;L;;;;;N;;;;; +1742;BUHID LETTER U;Lo;0;L;;;;;N;;;;; +1743;BUHID LETTER KA;Lo;0;L;;;;;N;;;;; +1744;BUHID LETTER GA;Lo;0;L;;;;;N;;;;; +1745;BUHID LETTER NGA;Lo;0;L;;;;;N;;;;; +1746;BUHID LETTER TA;Lo;0;L;;;;;N;;;;; +1747;BUHID LETTER DA;Lo;0;L;;;;;N;;;;; +1748;BUHID LETTER NA;Lo;0;L;;;;;N;;;;; +1749;BUHID LETTER PA;Lo;0;L;;;;;N;;;;; +174A;BUHID LETTER BA;Lo;0;L;;;;;N;;;;; +174B;BUHID LETTER MA;Lo;0;L;;;;;N;;;;; +174C;BUHID LETTER YA;Lo;0;L;;;;;N;;;;; +174D;BUHID LETTER RA;Lo;0;L;;;;;N;;;;; +174E;BUHID LETTER LA;Lo;0;L;;;;;N;;;;; +174F;BUHID LETTER WA;Lo;0;L;;;;;N;;;;; +1750;BUHID LETTER SA;Lo;0;L;;;;;N;;;;; +1751;BUHID LETTER HA;Lo;0;L;;;;;N;;;;; +1752;BUHID VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +1753;BUHID VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +1760;TAGBANWA LETTER A;Lo;0;L;;;;;N;;;;; +1761;TAGBANWA LETTER I;Lo;0;L;;;;;N;;;;; +1762;TAGBANWA LETTER U;Lo;0;L;;;;;N;;;;; +1763;TAGBANWA LETTER KA;Lo;0;L;;;;;N;;;;; +1764;TAGBANWA LETTER GA;Lo;0;L;;;;;N;;;;; +1765;TAGBANWA LETTER NGA;Lo;0;L;;;;;N;;;;; +1766;TAGBANWA LETTER TA;Lo;0;L;;;;;N;;;;; +1767;TAGBANWA LETTER DA;Lo;0;L;;;;;N;;;;; +1768;TAGBANWA LETTER NA;Lo;0;L;;;;;N;;;;; +1769;TAGBANWA LETTER PA;Lo;0;L;;;;;N;;;;; +176A;TAGBANWA LETTER BA;Lo;0;L;;;;;N;;;;; +176B;TAGBANWA LETTER MA;Lo;0;L;;;;;N;;;;; +176C;TAGBANWA LETTER YA;Lo;0;L;;;;;N;;;;; +176E;TAGBANWA LETTER LA;Lo;0;L;;;;;N;;;;; +176F;TAGBANWA LETTER WA;Lo;0;L;;;;;N;;;;; +1770;TAGBANWA LETTER SA;Lo;0;L;;;;;N;;;;; +1772;TAGBANWA VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +1773;TAGBANWA VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +1780;KHMER LETTER KA;Lo;0;L;;;;;N;;;;; +1781;KHMER LETTER KHA;Lo;0;L;;;;;N;;;;; +1782;KHMER LETTER KO;Lo;0;L;;;;;N;;;;; +1783;KHMER LETTER KHO;Lo;0;L;;;;;N;;;;; +1784;KHMER LETTER NGO;Lo;0;L;;;;;N;;;;; +1785;KHMER LETTER CA;Lo;0;L;;;;;N;;;;; +1786;KHMER LETTER CHA;Lo;0;L;;;;;N;;;;; +1787;KHMER LETTER CO;Lo;0;L;;;;;N;;;;; +1788;KHMER LETTER CHO;Lo;0;L;;;;;N;;;;; +1789;KHMER LETTER NYO;Lo;0;L;;;;;N;;;;; +178A;KHMER LETTER DA;Lo;0;L;;;;;N;;;;; +178B;KHMER LETTER TTHA;Lo;0;L;;;;;N;;;;; +178C;KHMER LETTER DO;Lo;0;L;;;;;N;;;;; +178D;KHMER LETTER TTHO;Lo;0;L;;;;;N;;;;; +178E;KHMER LETTER NNO;Lo;0;L;;;;;N;;;;; +178F;KHMER LETTER TA;Lo;0;L;;;;;N;;;;; +1790;KHMER LETTER THA;Lo;0;L;;;;;N;;;;; +1791;KHMER LETTER TO;Lo;0;L;;;;;N;;;;; +1792;KHMER LETTER THO;Lo;0;L;;;;;N;;;;; +1793;KHMER LETTER NO;Lo;0;L;;;;;N;;;;; +1794;KHMER LETTER BA;Lo;0;L;;;;;N;;;;; +1795;KHMER LETTER PHA;Lo;0;L;;;;;N;;;;; +1796;KHMER LETTER PO;Lo;0;L;;;;;N;;;;; +1797;KHMER LETTER PHO;Lo;0;L;;;;;N;;;;; +1798;KHMER LETTER MO;Lo;0;L;;;;;N;;;;; +1799;KHMER LETTER YO;Lo;0;L;;;;;N;;;;; +179A;KHMER LETTER RO;Lo;0;L;;;;;N;;;;; +179B;KHMER LETTER LO;Lo;0;L;;;;;N;;;;; +179C;KHMER LETTER VO;Lo;0;L;;;;;N;;;;; +179D;KHMER LETTER SHA;Lo;0;L;;;;;N;;;;; +179E;KHMER LETTER SSO;Lo;0;L;;;;;N;;;;; +179F;KHMER LETTER SA;Lo;0;L;;;;;N;;;;; +17A0;KHMER LETTER HA;Lo;0;L;;;;;N;;;;; +17A1;KHMER LETTER LA;Lo;0;L;;;;;N;;;;; +17A2;KHMER LETTER QA;Lo;0;L;;;;;N;;;;; +17A3;KHMER INDEPENDENT VOWEL QAQ;Lo;0;L;;;;;N;;;;; +17A4;KHMER INDEPENDENT VOWEL QAA;Lo;0;L;;;;;N;;;;; +17A5;KHMER INDEPENDENT VOWEL QI;Lo;0;L;;;;;N;;;;; +17A6;KHMER INDEPENDENT VOWEL QII;Lo;0;L;;;;;N;;;;; +17A7;KHMER INDEPENDENT VOWEL QU;Lo;0;L;;;;;N;;;;; +17A8;KHMER INDEPENDENT VOWEL QUK;Lo;0;L;;;;;N;;;;; +17A9;KHMER INDEPENDENT VOWEL QUU;Lo;0;L;;;;;N;;;;; +17AA;KHMER INDEPENDENT VOWEL QUUV;Lo;0;L;;;;;N;;;;; +17AB;KHMER INDEPENDENT VOWEL RY;Lo;0;L;;;;;N;;;;; +17AC;KHMER INDEPENDENT VOWEL RYY;Lo;0;L;;;;;N;;;;; +17AD;KHMER INDEPENDENT VOWEL LY;Lo;0;L;;;;;N;;;;; +17AE;KHMER INDEPENDENT VOWEL LYY;Lo;0;L;;;;;N;;;;; +17AF;KHMER INDEPENDENT VOWEL QE;Lo;0;L;;;;;N;;;;; +17B0;KHMER INDEPENDENT VOWEL QAI;Lo;0;L;;;;;N;;;;; +17B1;KHMER INDEPENDENT VOWEL QOO TYPE ONE;Lo;0;L;;;;;N;;;;; +17B2;KHMER INDEPENDENT VOWEL QOO TYPE TWO;Lo;0;L;;;;;N;;;;; +17B3;KHMER INDEPENDENT VOWEL QAU;Lo;0;L;;;;;N;;;;; +17B4;KHMER VOWEL INHERENT AQ;Mn;0;NSM;;;;;N;;;;; +17B5;KHMER VOWEL INHERENT AA;Mn;0;NSM;;;;;N;;;;; +17B6;KHMER VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +17B7;KHMER VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +17B8;KHMER VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;; +17B9;KHMER VOWEL SIGN Y;Mn;0;NSM;;;;;N;;;;; +17BA;KHMER VOWEL SIGN YY;Mn;0;NSM;;;;;N;;;;; +17BB;KHMER VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +17BC;KHMER VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +17BD;KHMER VOWEL SIGN UA;Mn;0;NSM;;;;;N;;;;; +17BE;KHMER VOWEL SIGN OE;Mc;0;L;;;;;N;;;;; +17BF;KHMER VOWEL SIGN YA;Mc;0;L;;;;;N;;;;; +17C0;KHMER VOWEL SIGN IE;Mc;0;L;;;;;N;;;;; +17C1;KHMER VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +17C2;KHMER VOWEL SIGN AE;Mc;0;L;;;;;N;;;;; +17C3;KHMER VOWEL SIGN AI;Mc;0;L;;;;;N;;;;; +17C4;KHMER VOWEL SIGN OO;Mc;0;L;;;;;N;;;;; +17C5;KHMER VOWEL SIGN AU;Mc;0;L;;;;;N;;;;; +17C6;KHMER SIGN NIKAHIT;Mn;0;NSM;;;;;N;;;;; +17C7;KHMER SIGN REAHMUK;Mc;0;L;;;;;N;;;;; +17C8;KHMER SIGN YUUKALEAPINTU;Mc;0;L;;;;;N;;;;; +17C9;KHMER SIGN MUUSIKATOAN;Mn;0;NSM;;;;;N;;;;; +17CA;KHMER SIGN TRIISAP;Mn;0;NSM;;;;;N;;;;; +17CB;KHMER SIGN BANTOC;Mn;0;NSM;;;;;N;;;;; +17CC;KHMER SIGN ROBAT;Mn;0;NSM;;;;;N;;;;; +17CD;KHMER SIGN TOANDAKHIAT;Mn;0;NSM;;;;;N;;;;; +17CE;KHMER SIGN KAKABAT;Mn;0;NSM;;;;;N;;;;; +17CF;KHMER SIGN AHSDA;Mn;0;NSM;;;;;N;;;;; +17D0;KHMER SIGN SAMYOK SANNYA;Mn;0;NSM;;;;;N;;;;; +17D1;KHMER SIGN VIRIAM;Mn;0;NSM;;;;;N;;;;; +17D2;KHMER SIGN COENG;Mn;9;NSM;;;;;N;;;;; +17D3;KHMER SIGN BATHAMASAT;Mn;0;NSM;;;;;N;;;;; +17D4;KHMER SIGN KHAN;Po;0;L;;;;;N;;;;; +17D5;KHMER SIGN BARIYOOSAN;Po;0;L;;;;;N;;;;; +17D6;KHMER SIGN CAMNUC PII KUUH;Po;0;L;;;;;N;;;;; +17D7;KHMER SIGN LEK TOO;Lm;0;L;;;;;N;;;;; +17D8;KHMER SIGN BEYYAL;Po;0;L;;;;;N;;;;; +17D9;KHMER SIGN PHNAEK MUAN;Po;0;L;;;;;N;;;;; +17DA;KHMER SIGN KOOMUUT;Po;0;L;;;;;N;;;;; +17DB;KHMER CURRENCY SYMBOL RIEL;Sc;0;ET;;;;;N;;;;; +17DC;KHMER SIGN AVAKRAHASANYA;Lo;0;L;;;;;N;;;;; +17DD;KHMER SIGN ATTHACAN;Mn;230;NSM;;;;;N;;;;; +17E0;KHMER DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +17E1;KHMER DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +17E2;KHMER DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +17E3;KHMER DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +17E4;KHMER DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +17E5;KHMER DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +17E6;KHMER DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +17E7;KHMER DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +17E8;KHMER DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +17E9;KHMER DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +17F0;KHMER SYMBOL LEK ATTAK SON;No;0;ON;;;;0;N;;;;; +17F1;KHMER SYMBOL LEK ATTAK MUOY;No;0;ON;;;;1;N;;;;; +17F2;KHMER SYMBOL LEK ATTAK PII;No;0;ON;;;;2;N;;;;; +17F3;KHMER SYMBOL LEK ATTAK BEI;No;0;ON;;;;3;N;;;;; +17F4;KHMER SYMBOL LEK ATTAK BUON;No;0;ON;;;;4;N;;;;; +17F5;KHMER SYMBOL LEK ATTAK PRAM;No;0;ON;;;;5;N;;;;; +17F6;KHMER SYMBOL LEK ATTAK PRAM-MUOY;No;0;ON;;;;6;N;;;;; +17F7;KHMER SYMBOL LEK ATTAK PRAM-PII;No;0;ON;;;;7;N;;;;; +17F8;KHMER SYMBOL LEK ATTAK PRAM-BEI;No;0;ON;;;;8;N;;;;; +17F9;KHMER SYMBOL LEK ATTAK PRAM-BUON;No;0;ON;;;;9;N;;;;; +1800;MONGOLIAN BIRGA;Po;0;ON;;;;;N;;;;; +1801;MONGOLIAN ELLIPSIS;Po;0;ON;;;;;N;;;;; +1802;MONGOLIAN COMMA;Po;0;ON;;;;;N;;;;; +1803;MONGOLIAN FULL STOP;Po;0;ON;;;;;N;;;;; +1804;MONGOLIAN COLON;Po;0;ON;;;;;N;;;;; +1805;MONGOLIAN FOUR DOTS;Po;0;ON;;;;;N;;;;; +1806;MONGOLIAN TODO SOFT HYPHEN;Pd;0;ON;;;;;N;;;;; +1807;MONGOLIAN SIBE SYLLABLE BOUNDARY MARKER;Po;0;ON;;;;;N;;;;; +1808;MONGOLIAN MANCHU COMMA;Po;0;ON;;;;;N;;;;; +1809;MONGOLIAN MANCHU FULL STOP;Po;0;ON;;;;;N;;;;; +180A;MONGOLIAN NIRUGU;Po;0;ON;;;;;N;;;;; +180B;MONGOLIAN FREE VARIATION SELECTOR ONE;Mn;0;NSM;;;;;N;;;;; +180C;MONGOLIAN FREE VARIATION SELECTOR TWO;Mn;0;NSM;;;;;N;;;;; +180D;MONGOLIAN FREE VARIATION SELECTOR THREE;Mn;0;NSM;;;;;N;;;;; +180E;MONGOLIAN VOWEL SEPARATOR;Zs;0;WS;;;;;N;;;;; +1810;MONGOLIAN DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1811;MONGOLIAN DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1812;MONGOLIAN DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1813;MONGOLIAN DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1814;MONGOLIAN DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1815;MONGOLIAN DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1816;MONGOLIAN DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1817;MONGOLIAN DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1818;MONGOLIAN DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1819;MONGOLIAN DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +1820;MONGOLIAN LETTER A;Lo;0;L;;;;;N;;;;; +1821;MONGOLIAN LETTER E;Lo;0;L;;;;;N;;;;; +1822;MONGOLIAN LETTER I;Lo;0;L;;;;;N;;;;; +1823;MONGOLIAN LETTER O;Lo;0;L;;;;;N;;;;; +1824;MONGOLIAN LETTER U;Lo;0;L;;;;;N;;;;; +1825;MONGOLIAN LETTER OE;Lo;0;L;;;;;N;;;;; +1826;MONGOLIAN LETTER UE;Lo;0;L;;;;;N;;;;; +1827;MONGOLIAN LETTER EE;Lo;0;L;;;;;N;;;;; +1828;MONGOLIAN LETTER NA;Lo;0;L;;;;;N;;;;; +1829;MONGOLIAN LETTER ANG;Lo;0;L;;;;;N;;;;; +182A;MONGOLIAN LETTER BA;Lo;0;L;;;;;N;;;;; +182B;MONGOLIAN LETTER PA;Lo;0;L;;;;;N;;;;; +182C;MONGOLIAN LETTER QA;Lo;0;L;;;;;N;;;;; +182D;MONGOLIAN LETTER GA;Lo;0;L;;;;;N;;;;; +182E;MONGOLIAN LETTER MA;Lo;0;L;;;;;N;;;;; +182F;MONGOLIAN LETTER LA;Lo;0;L;;;;;N;;;;; +1830;MONGOLIAN LETTER SA;Lo;0;L;;;;;N;;;;; +1831;MONGOLIAN LETTER SHA;Lo;0;L;;;;;N;;;;; +1832;MONGOLIAN LETTER TA;Lo;0;L;;;;;N;;;;; +1833;MONGOLIAN LETTER DA;Lo;0;L;;;;;N;;;;; +1834;MONGOLIAN LETTER CHA;Lo;0;L;;;;;N;;;;; +1835;MONGOLIAN LETTER JA;Lo;0;L;;;;;N;;;;; +1836;MONGOLIAN LETTER YA;Lo;0;L;;;;;N;;;;; +1837;MONGOLIAN LETTER RA;Lo;0;L;;;;;N;;;;; +1838;MONGOLIAN LETTER WA;Lo;0;L;;;;;N;;;;; +1839;MONGOLIAN LETTER FA;Lo;0;L;;;;;N;;;;; +183A;MONGOLIAN LETTER KA;Lo;0;L;;;;;N;;;;; +183B;MONGOLIAN LETTER KHA;Lo;0;L;;;;;N;;;;; +183C;MONGOLIAN LETTER TSA;Lo;0;L;;;;;N;;;;; +183D;MONGOLIAN LETTER ZA;Lo;0;L;;;;;N;;;;; +183E;MONGOLIAN LETTER HAA;Lo;0;L;;;;;N;;;;; +183F;MONGOLIAN LETTER ZRA;Lo;0;L;;;;;N;;;;; +1840;MONGOLIAN LETTER LHA;Lo;0;L;;;;;N;;;;; +1841;MONGOLIAN LETTER ZHI;Lo;0;L;;;;;N;;;;; +1842;MONGOLIAN LETTER CHI;Lo;0;L;;;;;N;;;;; +1843;MONGOLIAN LETTER TODO LONG VOWEL SIGN;Lm;0;L;;;;;N;;;;; +1844;MONGOLIAN LETTER TODO E;Lo;0;L;;;;;N;;;;; +1845;MONGOLIAN LETTER TODO I;Lo;0;L;;;;;N;;;;; +1846;MONGOLIAN LETTER TODO O;Lo;0;L;;;;;N;;;;; +1847;MONGOLIAN LETTER TODO U;Lo;0;L;;;;;N;;;;; +1848;MONGOLIAN LETTER TODO OE;Lo;0;L;;;;;N;;;;; +1849;MONGOLIAN LETTER TODO UE;Lo;0;L;;;;;N;;;;; +184A;MONGOLIAN LETTER TODO ANG;Lo;0;L;;;;;N;;;;; +184B;MONGOLIAN LETTER TODO BA;Lo;0;L;;;;;N;;;;; +184C;MONGOLIAN LETTER TODO PA;Lo;0;L;;;;;N;;;;; +184D;MONGOLIAN LETTER TODO QA;Lo;0;L;;;;;N;;;;; +184E;MONGOLIAN LETTER TODO GA;Lo;0;L;;;;;N;;;;; +184F;MONGOLIAN LETTER TODO MA;Lo;0;L;;;;;N;;;;; +1850;MONGOLIAN LETTER TODO TA;Lo;0;L;;;;;N;;;;; +1851;MONGOLIAN LETTER TODO DA;Lo;0;L;;;;;N;;;;; +1852;MONGOLIAN LETTER TODO CHA;Lo;0;L;;;;;N;;;;; +1853;MONGOLIAN LETTER TODO JA;Lo;0;L;;;;;N;;;;; +1854;MONGOLIAN LETTER TODO TSA;Lo;0;L;;;;;N;;;;; +1855;MONGOLIAN LETTER TODO YA;Lo;0;L;;;;;N;;;;; +1856;MONGOLIAN LETTER TODO WA;Lo;0;L;;;;;N;;;;; +1857;MONGOLIAN LETTER TODO KA;Lo;0;L;;;;;N;;;;; +1858;MONGOLIAN LETTER TODO GAA;Lo;0;L;;;;;N;;;;; +1859;MONGOLIAN LETTER TODO HAA;Lo;0;L;;;;;N;;;;; +185A;MONGOLIAN LETTER TODO JIA;Lo;0;L;;;;;N;;;;; +185B;MONGOLIAN LETTER TODO NIA;Lo;0;L;;;;;N;;;;; +185C;MONGOLIAN LETTER TODO DZA;Lo;0;L;;;;;N;;;;; +185D;MONGOLIAN LETTER SIBE E;Lo;0;L;;;;;N;;;;; +185E;MONGOLIAN LETTER SIBE I;Lo;0;L;;;;;N;;;;; +185F;MONGOLIAN LETTER SIBE IY;Lo;0;L;;;;;N;;;;; +1860;MONGOLIAN LETTER SIBE UE;Lo;0;L;;;;;N;;;;; +1861;MONGOLIAN LETTER SIBE U;Lo;0;L;;;;;N;;;;; +1862;MONGOLIAN LETTER SIBE ANG;Lo;0;L;;;;;N;;;;; +1863;MONGOLIAN LETTER SIBE KA;Lo;0;L;;;;;N;;;;; +1864;MONGOLIAN LETTER SIBE GA;Lo;0;L;;;;;N;;;;; +1865;MONGOLIAN LETTER SIBE HA;Lo;0;L;;;;;N;;;;; +1866;MONGOLIAN LETTER SIBE PA;Lo;0;L;;;;;N;;;;; +1867;MONGOLIAN LETTER SIBE SHA;Lo;0;L;;;;;N;;;;; +1868;MONGOLIAN LETTER SIBE TA;Lo;0;L;;;;;N;;;;; +1869;MONGOLIAN LETTER SIBE DA;Lo;0;L;;;;;N;;;;; +186A;MONGOLIAN LETTER SIBE JA;Lo;0;L;;;;;N;;;;; +186B;MONGOLIAN LETTER SIBE FA;Lo;0;L;;;;;N;;;;; +186C;MONGOLIAN LETTER SIBE GAA;Lo;0;L;;;;;N;;;;; +186D;MONGOLIAN LETTER SIBE HAA;Lo;0;L;;;;;N;;;;; +186E;MONGOLIAN LETTER SIBE TSA;Lo;0;L;;;;;N;;;;; +186F;MONGOLIAN LETTER SIBE ZA;Lo;0;L;;;;;N;;;;; +1870;MONGOLIAN LETTER SIBE RAA;Lo;0;L;;;;;N;;;;; +1871;MONGOLIAN LETTER SIBE CHA;Lo;0;L;;;;;N;;;;; +1872;MONGOLIAN LETTER SIBE ZHA;Lo;0;L;;;;;N;;;;; +1873;MONGOLIAN LETTER MANCHU I;Lo;0;L;;;;;N;;;;; +1874;MONGOLIAN LETTER MANCHU KA;Lo;0;L;;;;;N;;;;; +1875;MONGOLIAN LETTER MANCHU RA;Lo;0;L;;;;;N;;;;; +1876;MONGOLIAN LETTER MANCHU FA;Lo;0;L;;;;;N;;;;; +1877;MONGOLIAN LETTER MANCHU ZHA;Lo;0;L;;;;;N;;;;; +1880;MONGOLIAN LETTER ALI GALI ANUSVARA ONE;Lo;0;L;;;;;N;;;;; +1881;MONGOLIAN LETTER ALI GALI VISARGA ONE;Lo;0;L;;;;;N;;;;; +1882;MONGOLIAN LETTER ALI GALI DAMARU;Lo;0;L;;;;;N;;;;; +1883;MONGOLIAN LETTER ALI GALI UBADAMA;Lo;0;L;;;;;N;;;;; +1884;MONGOLIAN LETTER ALI GALI INVERTED UBADAMA;Lo;0;L;;;;;N;;;;; +1885;MONGOLIAN LETTER ALI GALI BALUDA;Lo;0;L;;;;;N;;;;; +1886;MONGOLIAN LETTER ALI GALI THREE BALUDA;Lo;0;L;;;;;N;;;;; +1887;MONGOLIAN LETTER ALI GALI A;Lo;0;L;;;;;N;;;;; +1888;MONGOLIAN LETTER ALI GALI I;Lo;0;L;;;;;N;;;;; +1889;MONGOLIAN LETTER ALI GALI KA;Lo;0;L;;;;;N;;;;; +188A;MONGOLIAN LETTER ALI GALI NGA;Lo;0;L;;;;;N;;;;; +188B;MONGOLIAN LETTER ALI GALI CA;Lo;0;L;;;;;N;;;;; +188C;MONGOLIAN LETTER ALI GALI TTA;Lo;0;L;;;;;N;;;;; +188D;MONGOLIAN LETTER ALI GALI TTHA;Lo;0;L;;;;;N;;;;; +188E;MONGOLIAN LETTER ALI GALI DDA;Lo;0;L;;;;;N;;;;; +188F;MONGOLIAN LETTER ALI GALI NNA;Lo;0;L;;;;;N;;;;; +1890;MONGOLIAN LETTER ALI GALI TA;Lo;0;L;;;;;N;;;;; +1891;MONGOLIAN LETTER ALI GALI DA;Lo;0;L;;;;;N;;;;; +1892;MONGOLIAN LETTER ALI GALI PA;Lo;0;L;;;;;N;;;;; +1893;MONGOLIAN LETTER ALI GALI PHA;Lo;0;L;;;;;N;;;;; +1894;MONGOLIAN LETTER ALI GALI SSA;Lo;0;L;;;;;N;;;;; +1895;MONGOLIAN LETTER ALI GALI ZHA;Lo;0;L;;;;;N;;;;; +1896;MONGOLIAN LETTER ALI GALI ZA;Lo;0;L;;;;;N;;;;; +1897;MONGOLIAN LETTER ALI GALI AH;Lo;0;L;;;;;N;;;;; +1898;MONGOLIAN LETTER TODO ALI GALI TA;Lo;0;L;;;;;N;;;;; +1899;MONGOLIAN LETTER TODO ALI GALI ZHA;Lo;0;L;;;;;N;;;;; +189A;MONGOLIAN LETTER MANCHU ALI GALI GHA;Lo;0;L;;;;;N;;;;; +189B;MONGOLIAN LETTER MANCHU ALI GALI NGA;Lo;0;L;;;;;N;;;;; +189C;MONGOLIAN LETTER MANCHU ALI GALI CA;Lo;0;L;;;;;N;;;;; +189D;MONGOLIAN LETTER MANCHU ALI GALI JHA;Lo;0;L;;;;;N;;;;; +189E;MONGOLIAN LETTER MANCHU ALI GALI TTA;Lo;0;L;;;;;N;;;;; +189F;MONGOLIAN LETTER MANCHU ALI GALI DDHA;Lo;0;L;;;;;N;;;;; +18A0;MONGOLIAN LETTER MANCHU ALI GALI TA;Lo;0;L;;;;;N;;;;; +18A1;MONGOLIAN LETTER MANCHU ALI GALI DHA;Lo;0;L;;;;;N;;;;; +18A2;MONGOLIAN LETTER MANCHU ALI GALI SSA;Lo;0;L;;;;;N;;;;; +18A3;MONGOLIAN LETTER MANCHU ALI GALI CYA;Lo;0;L;;;;;N;;;;; +18A4;MONGOLIAN LETTER MANCHU ALI GALI ZHA;Lo;0;L;;;;;N;;;;; +18A5;MONGOLIAN LETTER MANCHU ALI GALI ZA;Lo;0;L;;;;;N;;;;; +18A6;MONGOLIAN LETTER ALI GALI HALF U;Lo;0;L;;;;;N;;;;; +18A7;MONGOLIAN LETTER ALI GALI HALF YA;Lo;0;L;;;;;N;;;;; +18A8;MONGOLIAN LETTER MANCHU ALI GALI BHA;Lo;0;L;;;;;N;;;;; +18A9;MONGOLIAN LETTER ALI GALI DAGALGA;Mn;228;NSM;;;;;N;;;;; +18AA;MONGOLIAN LETTER MANCHU ALI GALI LHA;Lo;0;L;;;;;N;;;;; +18B0;CANADIAN SYLLABICS OY;Lo;0;L;;;;;N;;;;; +18B1;CANADIAN SYLLABICS AY;Lo;0;L;;;;;N;;;;; +18B2;CANADIAN SYLLABICS AAY;Lo;0;L;;;;;N;;;;; +18B3;CANADIAN SYLLABICS WAY;Lo;0;L;;;;;N;;;;; +18B4;CANADIAN SYLLABICS POY;Lo;0;L;;;;;N;;;;; +18B5;CANADIAN SYLLABICS PAY;Lo;0;L;;;;;N;;;;; +18B6;CANADIAN SYLLABICS PWOY;Lo;0;L;;;;;N;;;;; +18B7;CANADIAN SYLLABICS TAY;Lo;0;L;;;;;N;;;;; +18B8;CANADIAN SYLLABICS KAY;Lo;0;L;;;;;N;;;;; +18B9;CANADIAN SYLLABICS KWAY;Lo;0;L;;;;;N;;;;; +18BA;CANADIAN SYLLABICS MAY;Lo;0;L;;;;;N;;;;; +18BB;CANADIAN SYLLABICS NOY;Lo;0;L;;;;;N;;;;; +18BC;CANADIAN SYLLABICS NAY;Lo;0;L;;;;;N;;;;; +18BD;CANADIAN SYLLABICS LAY;Lo;0;L;;;;;N;;;;; +18BE;CANADIAN SYLLABICS SOY;Lo;0;L;;;;;N;;;;; +18BF;CANADIAN SYLLABICS SAY;Lo;0;L;;;;;N;;;;; +18C0;CANADIAN SYLLABICS SHOY;Lo;0;L;;;;;N;;;;; +18C1;CANADIAN SYLLABICS SHAY;Lo;0;L;;;;;N;;;;; +18C2;CANADIAN SYLLABICS SHWOY;Lo;0;L;;;;;N;;;;; +18C3;CANADIAN SYLLABICS YOY;Lo;0;L;;;;;N;;;;; +18C4;CANADIAN SYLLABICS YAY;Lo;0;L;;;;;N;;;;; +18C5;CANADIAN SYLLABICS RAY;Lo;0;L;;;;;N;;;;; +18C6;CANADIAN SYLLABICS NWI;Lo;0;L;;;;;N;;;;; +18C7;CANADIAN SYLLABICS OJIBWAY NWI;Lo;0;L;;;;;N;;;;; +18C8;CANADIAN SYLLABICS NWII;Lo;0;L;;;;;N;;;;; +18C9;CANADIAN SYLLABICS OJIBWAY NWII;Lo;0;L;;;;;N;;;;; +18CA;CANADIAN SYLLABICS NWO;Lo;0;L;;;;;N;;;;; +18CB;CANADIAN SYLLABICS OJIBWAY NWO;Lo;0;L;;;;;N;;;;; +18CC;CANADIAN SYLLABICS NWOO;Lo;0;L;;;;;N;;;;; +18CD;CANADIAN SYLLABICS OJIBWAY NWOO;Lo;0;L;;;;;N;;;;; +18CE;CANADIAN SYLLABICS RWEE;Lo;0;L;;;;;N;;;;; +18CF;CANADIAN SYLLABICS RWI;Lo;0;L;;;;;N;;;;; +18D0;CANADIAN SYLLABICS RWII;Lo;0;L;;;;;N;;;;; +18D1;CANADIAN SYLLABICS RWO;Lo;0;L;;;;;N;;;;; +18D2;CANADIAN SYLLABICS RWOO;Lo;0;L;;;;;N;;;;; +18D3;CANADIAN SYLLABICS RWA;Lo;0;L;;;;;N;;;;; +18D4;CANADIAN SYLLABICS OJIBWAY P;Lo;0;L;;;;;N;;;;; +18D5;CANADIAN SYLLABICS OJIBWAY T;Lo;0;L;;;;;N;;;;; +18D6;CANADIAN SYLLABICS OJIBWAY K;Lo;0;L;;;;;N;;;;; +18D7;CANADIAN SYLLABICS OJIBWAY C;Lo;0;L;;;;;N;;;;; +18D8;CANADIAN SYLLABICS OJIBWAY M;Lo;0;L;;;;;N;;;;; +18D9;CANADIAN SYLLABICS OJIBWAY N;Lo;0;L;;;;;N;;;;; +18DA;CANADIAN SYLLABICS OJIBWAY S;Lo;0;L;;;;;N;;;;; +18DB;CANADIAN SYLLABICS OJIBWAY SH;Lo;0;L;;;;;N;;;;; +18DC;CANADIAN SYLLABICS EASTERN W;Lo;0;L;;;;;N;;;;; +18DD;CANADIAN SYLLABICS WESTERN W;Lo;0;L;;;;;N;;;;; +18DE;CANADIAN SYLLABICS FINAL SMALL RING;Lo;0;L;;;;;N;;;;; +18DF;CANADIAN SYLLABICS FINAL RAISED DOT;Lo;0;L;;;;;N;;;;; +18E0;CANADIAN SYLLABICS R-CREE RWE;Lo;0;L;;;;;N;;;;; +18E1;CANADIAN SYLLABICS WEST-CREE LOO;Lo;0;L;;;;;N;;;;; +18E2;CANADIAN SYLLABICS WEST-CREE LAA;Lo;0;L;;;;;N;;;;; +18E3;CANADIAN SYLLABICS THWE;Lo;0;L;;;;;N;;;;; +18E4;CANADIAN SYLLABICS THWA;Lo;0;L;;;;;N;;;;; +18E5;CANADIAN SYLLABICS TTHWE;Lo;0;L;;;;;N;;;;; +18E6;CANADIAN SYLLABICS TTHOO;Lo;0;L;;;;;N;;;;; +18E7;CANADIAN SYLLABICS TTHAA;Lo;0;L;;;;;N;;;;; +18E8;CANADIAN SYLLABICS TLHWE;Lo;0;L;;;;;N;;;;; +18E9;CANADIAN SYLLABICS TLHOO;Lo;0;L;;;;;N;;;;; +18EA;CANADIAN SYLLABICS SAYISI SHWE;Lo;0;L;;;;;N;;;;; +18EB;CANADIAN SYLLABICS SAYISI SHOO;Lo;0;L;;;;;N;;;;; +18EC;CANADIAN SYLLABICS SAYISI HOO;Lo;0;L;;;;;N;;;;; +18ED;CANADIAN SYLLABICS CARRIER GWU;Lo;0;L;;;;;N;;;;; +18EE;CANADIAN SYLLABICS CARRIER DENE GEE;Lo;0;L;;;;;N;;;;; +18EF;CANADIAN SYLLABICS CARRIER GAA;Lo;0;L;;;;;N;;;;; +18F0;CANADIAN SYLLABICS CARRIER GWA;Lo;0;L;;;;;N;;;;; +18F1;CANADIAN SYLLABICS SAYISI JUU;Lo;0;L;;;;;N;;;;; +18F2;CANADIAN SYLLABICS CARRIER JWA;Lo;0;L;;;;;N;;;;; +18F3;CANADIAN SYLLABICS BEAVER DENE L;Lo;0;L;;;;;N;;;;; +18F4;CANADIAN SYLLABICS BEAVER DENE R;Lo;0;L;;;;;N;;;;; +18F5;CANADIAN SYLLABICS CARRIER DENTAL S;Lo;0;L;;;;;N;;;;; +1900;LIMBU VOWEL-CARRIER LETTER;Lo;0;L;;;;;N;;;;; +1901;LIMBU LETTER KA;Lo;0;L;;;;;N;;;;; +1902;LIMBU LETTER KHA;Lo;0;L;;;;;N;;;;; +1903;LIMBU LETTER GA;Lo;0;L;;;;;N;;;;; +1904;LIMBU LETTER GHA;Lo;0;L;;;;;N;;;;; +1905;LIMBU LETTER NGA;Lo;0;L;;;;;N;;;;; +1906;LIMBU LETTER CA;Lo;0;L;;;;;N;;;;; +1907;LIMBU LETTER CHA;Lo;0;L;;;;;N;;;;; +1908;LIMBU LETTER JA;Lo;0;L;;;;;N;;;;; +1909;LIMBU LETTER JHA;Lo;0;L;;;;;N;;;;; +190A;LIMBU LETTER YAN;Lo;0;L;;;;;N;;;;; +190B;LIMBU LETTER TA;Lo;0;L;;;;;N;;;;; +190C;LIMBU LETTER THA;Lo;0;L;;;;;N;;;;; +190D;LIMBU LETTER DA;Lo;0;L;;;;;N;;;;; +190E;LIMBU LETTER DHA;Lo;0;L;;;;;N;;;;; +190F;LIMBU LETTER NA;Lo;0;L;;;;;N;;;;; +1910;LIMBU LETTER PA;Lo;0;L;;;;;N;;;;; +1911;LIMBU LETTER PHA;Lo;0;L;;;;;N;;;;; +1912;LIMBU LETTER BA;Lo;0;L;;;;;N;;;;; +1913;LIMBU LETTER BHA;Lo;0;L;;;;;N;;;;; +1914;LIMBU LETTER MA;Lo;0;L;;;;;N;;;;; +1915;LIMBU LETTER YA;Lo;0;L;;;;;N;;;;; +1916;LIMBU LETTER RA;Lo;0;L;;;;;N;;;;; +1917;LIMBU LETTER LA;Lo;0;L;;;;;N;;;;; +1918;LIMBU LETTER WA;Lo;0;L;;;;;N;;;;; +1919;LIMBU LETTER SHA;Lo;0;L;;;;;N;;;;; +191A;LIMBU LETTER SSA;Lo;0;L;;;;;N;;;;; +191B;LIMBU LETTER SA;Lo;0;L;;;;;N;;;;; +191C;LIMBU LETTER HA;Lo;0;L;;;;;N;;;;; +1920;LIMBU VOWEL SIGN A;Mn;0;NSM;;;;;N;;;;; +1921;LIMBU VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +1922;LIMBU VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +1923;LIMBU VOWEL SIGN EE;Mc;0;L;;;;;N;;;;; +1924;LIMBU VOWEL SIGN AI;Mc;0;L;;;;;N;;;;; +1925;LIMBU VOWEL SIGN OO;Mc;0;L;;;;;N;;;;; +1926;LIMBU VOWEL SIGN AU;Mc;0;L;;;;;N;;;;; +1927;LIMBU VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +1928;LIMBU VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;; +1929;LIMBU SUBJOINED LETTER YA;Mc;0;L;;;;;N;;;;; +192A;LIMBU SUBJOINED LETTER RA;Mc;0;L;;;;;N;;;;; +192B;LIMBU SUBJOINED LETTER WA;Mc;0;L;;;;;N;;;;; +1930;LIMBU SMALL LETTER KA;Mc;0;L;;;;;N;;;;; +1931;LIMBU SMALL LETTER NGA;Mc;0;L;;;;;N;;;;; +1932;LIMBU SMALL LETTER ANUSVARA;Mn;0;NSM;;;;;N;;;;; +1933;LIMBU SMALL LETTER TA;Mc;0;L;;;;;N;;;;; +1934;LIMBU SMALL LETTER NA;Mc;0;L;;;;;N;;;;; +1935;LIMBU SMALL LETTER PA;Mc;0;L;;;;;N;;;;; +1936;LIMBU SMALL LETTER MA;Mc;0;L;;;;;N;;;;; +1937;LIMBU SMALL LETTER RA;Mc;0;L;;;;;N;;;;; +1938;LIMBU SMALL LETTER LA;Mc;0;L;;;;;N;;;;; +1939;LIMBU SIGN MUKPHRENG;Mn;222;NSM;;;;;N;;;;; +193A;LIMBU SIGN KEMPHRENG;Mn;230;NSM;;;;;N;;;;; +193B;LIMBU SIGN SA-I;Mn;220;NSM;;;;;N;;;;; +1940;LIMBU SIGN LOO;So;0;ON;;;;;N;;;;; +1944;LIMBU EXCLAMATION MARK;Po;0;ON;;;;;N;;;;; +1945;LIMBU QUESTION MARK;Po;0;ON;;;;;N;;;;; +1946;LIMBU DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1947;LIMBU DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1948;LIMBU DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1949;LIMBU DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +194A;LIMBU DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +194B;LIMBU DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +194C;LIMBU DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +194D;LIMBU DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +194E;LIMBU DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +194F;LIMBU DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +1950;TAI LE LETTER KA;Lo;0;L;;;;;N;;;;; +1951;TAI LE LETTER XA;Lo;0;L;;;;;N;;;;; +1952;TAI LE LETTER NGA;Lo;0;L;;;;;N;;;;; +1953;TAI LE LETTER TSA;Lo;0;L;;;;;N;;;;; +1954;TAI LE LETTER SA;Lo;0;L;;;;;N;;;;; +1955;TAI LE LETTER YA;Lo;0;L;;;;;N;;;;; +1956;TAI LE LETTER TA;Lo;0;L;;;;;N;;;;; +1957;TAI LE LETTER THA;Lo;0;L;;;;;N;;;;; +1958;TAI LE LETTER LA;Lo;0;L;;;;;N;;;;; +1959;TAI LE LETTER PA;Lo;0;L;;;;;N;;;;; +195A;TAI LE LETTER PHA;Lo;0;L;;;;;N;;;;; +195B;TAI LE LETTER MA;Lo;0;L;;;;;N;;;;; +195C;TAI LE LETTER FA;Lo;0;L;;;;;N;;;;; +195D;TAI LE LETTER VA;Lo;0;L;;;;;N;;;;; +195E;TAI LE LETTER HA;Lo;0;L;;;;;N;;;;; +195F;TAI LE LETTER QA;Lo;0;L;;;;;N;;;;; +1960;TAI LE LETTER KHA;Lo;0;L;;;;;N;;;;; +1961;TAI LE LETTER TSHA;Lo;0;L;;;;;N;;;;; +1962;TAI LE LETTER NA;Lo;0;L;;;;;N;;;;; +1963;TAI LE LETTER A;Lo;0;L;;;;;N;;;;; +1964;TAI LE LETTER I;Lo;0;L;;;;;N;;;;; +1965;TAI LE LETTER EE;Lo;0;L;;;;;N;;;;; +1966;TAI LE LETTER EH;Lo;0;L;;;;;N;;;;; +1967;TAI LE LETTER U;Lo;0;L;;;;;N;;;;; +1968;TAI LE LETTER OO;Lo;0;L;;;;;N;;;;; +1969;TAI LE LETTER O;Lo;0;L;;;;;N;;;;; +196A;TAI LE LETTER UE;Lo;0;L;;;;;N;;;;; +196B;TAI LE LETTER E;Lo;0;L;;;;;N;;;;; +196C;TAI LE LETTER AUE;Lo;0;L;;;;;N;;;;; +196D;TAI LE LETTER AI;Lo;0;L;;;;;N;;;;; +1970;TAI LE LETTER TONE-2;Lo;0;L;;;;;N;;;;; +1971;TAI LE LETTER TONE-3;Lo;0;L;;;;;N;;;;; +1972;TAI LE LETTER TONE-4;Lo;0;L;;;;;N;;;;; +1973;TAI LE LETTER TONE-5;Lo;0;L;;;;;N;;;;; +1974;TAI LE LETTER TONE-6;Lo;0;L;;;;;N;;;;; +1980;NEW TAI LUE LETTER HIGH QA;Lo;0;L;;;;;N;;;;; +1981;NEW TAI LUE LETTER LOW QA;Lo;0;L;;;;;N;;;;; +1982;NEW TAI LUE LETTER HIGH KA;Lo;0;L;;;;;N;;;;; +1983;NEW TAI LUE LETTER HIGH XA;Lo;0;L;;;;;N;;;;; +1984;NEW TAI LUE LETTER HIGH NGA;Lo;0;L;;;;;N;;;;; +1985;NEW TAI LUE LETTER LOW KA;Lo;0;L;;;;;N;;;;; +1986;NEW TAI LUE LETTER LOW XA;Lo;0;L;;;;;N;;;;; +1987;NEW TAI LUE LETTER LOW NGA;Lo;0;L;;;;;N;;;;; +1988;NEW TAI LUE LETTER HIGH TSA;Lo;0;L;;;;;N;;;;; +1989;NEW TAI LUE LETTER HIGH SA;Lo;0;L;;;;;N;;;;; +198A;NEW TAI LUE LETTER HIGH YA;Lo;0;L;;;;;N;;;;; +198B;NEW TAI LUE LETTER LOW TSA;Lo;0;L;;;;;N;;;;; +198C;NEW TAI LUE LETTER LOW SA;Lo;0;L;;;;;N;;;;; +198D;NEW TAI LUE LETTER LOW YA;Lo;0;L;;;;;N;;;;; +198E;NEW TAI LUE LETTER HIGH TA;Lo;0;L;;;;;N;;;;; +198F;NEW TAI LUE LETTER HIGH THA;Lo;0;L;;;;;N;;;;; +1990;NEW TAI LUE LETTER HIGH NA;Lo;0;L;;;;;N;;;;; +1991;NEW TAI LUE LETTER LOW TA;Lo;0;L;;;;;N;;;;; +1992;NEW TAI LUE LETTER LOW THA;Lo;0;L;;;;;N;;;;; +1993;NEW TAI LUE LETTER LOW NA;Lo;0;L;;;;;N;;;;; +1994;NEW TAI LUE LETTER HIGH PA;Lo;0;L;;;;;N;;;;; +1995;NEW TAI LUE LETTER HIGH PHA;Lo;0;L;;;;;N;;;;; +1996;NEW TAI LUE LETTER HIGH MA;Lo;0;L;;;;;N;;;;; +1997;NEW TAI LUE LETTER LOW PA;Lo;0;L;;;;;N;;;;; +1998;NEW TAI LUE LETTER LOW PHA;Lo;0;L;;;;;N;;;;; +1999;NEW TAI LUE LETTER LOW MA;Lo;0;L;;;;;N;;;;; +199A;NEW TAI LUE LETTER HIGH FA;Lo;0;L;;;;;N;;;;; +199B;NEW TAI LUE LETTER HIGH VA;Lo;0;L;;;;;N;;;;; +199C;NEW TAI LUE LETTER HIGH LA;Lo;0;L;;;;;N;;;;; +199D;NEW TAI LUE LETTER LOW FA;Lo;0;L;;;;;N;;;;; +199E;NEW TAI LUE LETTER LOW VA;Lo;0;L;;;;;N;;;;; +199F;NEW TAI LUE LETTER LOW LA;Lo;0;L;;;;;N;;;;; +19A0;NEW TAI LUE LETTER HIGH HA;Lo;0;L;;;;;N;;;;; +19A1;NEW TAI LUE LETTER HIGH DA;Lo;0;L;;;;;N;;;;; +19A2;NEW TAI LUE LETTER HIGH BA;Lo;0;L;;;;;N;;;;; +19A3;NEW TAI LUE LETTER LOW HA;Lo;0;L;;;;;N;;;;; +19A4;NEW TAI LUE LETTER LOW DA;Lo;0;L;;;;;N;;;;; +19A5;NEW TAI LUE LETTER LOW BA;Lo;0;L;;;;;N;;;;; +19A6;NEW TAI LUE LETTER HIGH KVA;Lo;0;L;;;;;N;;;;; +19A7;NEW TAI LUE LETTER HIGH XVA;Lo;0;L;;;;;N;;;;; +19A8;NEW TAI LUE LETTER LOW KVA;Lo;0;L;;;;;N;;;;; +19A9;NEW TAI LUE LETTER LOW XVA;Lo;0;L;;;;;N;;;;; +19AA;NEW TAI LUE LETTER HIGH SUA;Lo;0;L;;;;;N;;;;; +19AB;NEW TAI LUE LETTER LOW SUA;Lo;0;L;;;;;N;;;;; +19B0;NEW TAI LUE VOWEL SIGN VOWEL SHORTENER;Mc;0;L;;;;;N;;;;; +19B1;NEW TAI LUE VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +19B2;NEW TAI LUE VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +19B3;NEW TAI LUE VOWEL SIGN U;Mc;0;L;;;;;N;;;;; +19B4;NEW TAI LUE VOWEL SIGN UU;Mc;0;L;;;;;N;;;;; +19B5;NEW TAI LUE VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +19B6;NEW TAI LUE VOWEL SIGN AE;Mc;0;L;;;;;N;;;;; +19B7;NEW TAI LUE VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +19B8;NEW TAI LUE VOWEL SIGN OA;Mc;0;L;;;;;N;;;;; +19B9;NEW TAI LUE VOWEL SIGN UE;Mc;0;L;;;;;N;;;;; +19BA;NEW TAI LUE VOWEL SIGN AY;Mc;0;L;;;;;N;;;;; +19BB;NEW TAI LUE VOWEL SIGN AAY;Mc;0;L;;;;;N;;;;; +19BC;NEW TAI LUE VOWEL SIGN UY;Mc;0;L;;;;;N;;;;; +19BD;NEW TAI LUE VOWEL SIGN OY;Mc;0;L;;;;;N;;;;; +19BE;NEW TAI LUE VOWEL SIGN OAY;Mc;0;L;;;;;N;;;;; +19BF;NEW TAI LUE VOWEL SIGN UEY;Mc;0;L;;;;;N;;;;; +19C0;NEW TAI LUE VOWEL SIGN IY;Mc;0;L;;;;;N;;;;; +19C1;NEW TAI LUE LETTER FINAL V;Lo;0;L;;;;;N;;;;; +19C2;NEW TAI LUE LETTER FINAL NG;Lo;0;L;;;;;N;;;;; +19C3;NEW TAI LUE LETTER FINAL N;Lo;0;L;;;;;N;;;;; +19C4;NEW TAI LUE LETTER FINAL M;Lo;0;L;;;;;N;;;;; +19C5;NEW TAI LUE LETTER FINAL K;Lo;0;L;;;;;N;;;;; +19C6;NEW TAI LUE LETTER FINAL D;Lo;0;L;;;;;N;;;;; +19C7;NEW TAI LUE LETTER FINAL B;Lo;0;L;;;;;N;;;;; +19C8;NEW TAI LUE TONE MARK-1;Mc;0;L;;;;;N;;;;; +19C9;NEW TAI LUE TONE MARK-2;Mc;0;L;;;;;N;;;;; +19D0;NEW TAI LUE DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +19D1;NEW TAI LUE DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +19D2;NEW TAI LUE DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +19D3;NEW TAI LUE DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +19D4;NEW TAI LUE DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +19D5;NEW TAI LUE DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +19D6;NEW TAI LUE DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +19D7;NEW TAI LUE DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +19D8;NEW TAI LUE DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +19D9;NEW TAI LUE DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +19DA;NEW TAI LUE THAM DIGIT ONE;No;0;L;;;1;1;N;;;;; +19DE;NEW TAI LUE SIGN LAE;So;0;ON;;;;;N;;;;; +19DF;NEW TAI LUE SIGN LAEV;So;0;ON;;;;;N;;;;; +19E0;KHMER SYMBOL PATHAMASAT;So;0;ON;;;;;N;;;;; +19E1;KHMER SYMBOL MUOY KOET;So;0;ON;;;;;N;;;;; +19E2;KHMER SYMBOL PII KOET;So;0;ON;;;;;N;;;;; +19E3;KHMER SYMBOL BEI KOET;So;0;ON;;;;;N;;;;; +19E4;KHMER SYMBOL BUON KOET;So;0;ON;;;;;N;;;;; +19E5;KHMER SYMBOL PRAM KOET;So;0;ON;;;;;N;;;;; +19E6;KHMER SYMBOL PRAM-MUOY KOET;So;0;ON;;;;;N;;;;; +19E7;KHMER SYMBOL PRAM-PII KOET;So;0;ON;;;;;N;;;;; +19E8;KHMER SYMBOL PRAM-BEI KOET;So;0;ON;;;;;N;;;;; +19E9;KHMER SYMBOL PRAM-BUON KOET;So;0;ON;;;;;N;;;;; +19EA;KHMER SYMBOL DAP KOET;So;0;ON;;;;;N;;;;; +19EB;KHMER SYMBOL DAP-MUOY KOET;So;0;ON;;;;;N;;;;; +19EC;KHMER SYMBOL DAP-PII KOET;So;0;ON;;;;;N;;;;; +19ED;KHMER SYMBOL DAP-BEI KOET;So;0;ON;;;;;N;;;;; +19EE;KHMER SYMBOL DAP-BUON KOET;So;0;ON;;;;;N;;;;; +19EF;KHMER SYMBOL DAP-PRAM KOET;So;0;ON;;;;;N;;;;; +19F0;KHMER SYMBOL TUTEYASAT;So;0;ON;;;;;N;;;;; +19F1;KHMER SYMBOL MUOY ROC;So;0;ON;;;;;N;;;;; +19F2;KHMER SYMBOL PII ROC;So;0;ON;;;;;N;;;;; +19F3;KHMER SYMBOL BEI ROC;So;0;ON;;;;;N;;;;; +19F4;KHMER SYMBOL BUON ROC;So;0;ON;;;;;N;;;;; +19F5;KHMER SYMBOL PRAM ROC;So;0;ON;;;;;N;;;;; +19F6;KHMER SYMBOL PRAM-MUOY ROC;So;0;ON;;;;;N;;;;; +19F7;KHMER SYMBOL PRAM-PII ROC;So;0;ON;;;;;N;;;;; +19F8;KHMER SYMBOL PRAM-BEI ROC;So;0;ON;;;;;N;;;;; +19F9;KHMER SYMBOL PRAM-BUON ROC;So;0;ON;;;;;N;;;;; +19FA;KHMER SYMBOL DAP ROC;So;0;ON;;;;;N;;;;; +19FB;KHMER SYMBOL DAP-MUOY ROC;So;0;ON;;;;;N;;;;; +19FC;KHMER SYMBOL DAP-PII ROC;So;0;ON;;;;;N;;;;; +19FD;KHMER SYMBOL DAP-BEI ROC;So;0;ON;;;;;N;;;;; +19FE;KHMER SYMBOL DAP-BUON ROC;So;0;ON;;;;;N;;;;; +19FF;KHMER SYMBOL DAP-PRAM ROC;So;0;ON;;;;;N;;;;; +1A00;BUGINESE LETTER KA;Lo;0;L;;;;;N;;;;; +1A01;BUGINESE LETTER GA;Lo;0;L;;;;;N;;;;; +1A02;BUGINESE LETTER NGA;Lo;0;L;;;;;N;;;;; +1A03;BUGINESE LETTER NGKA;Lo;0;L;;;;;N;;;;; +1A04;BUGINESE LETTER PA;Lo;0;L;;;;;N;;;;; +1A05;BUGINESE LETTER BA;Lo;0;L;;;;;N;;;;; +1A06;BUGINESE LETTER MA;Lo;0;L;;;;;N;;;;; +1A07;BUGINESE LETTER MPA;Lo;0;L;;;;;N;;;;; +1A08;BUGINESE LETTER TA;Lo;0;L;;;;;N;;;;; +1A09;BUGINESE LETTER DA;Lo;0;L;;;;;N;;;;; +1A0A;BUGINESE LETTER NA;Lo;0;L;;;;;N;;;;; +1A0B;BUGINESE LETTER NRA;Lo;0;L;;;;;N;;;;; +1A0C;BUGINESE LETTER CA;Lo;0;L;;;;;N;;;;; +1A0D;BUGINESE LETTER JA;Lo;0;L;;;;;N;;;;; +1A0E;BUGINESE LETTER NYA;Lo;0;L;;;;;N;;;;; +1A0F;BUGINESE LETTER NYCA;Lo;0;L;;;;;N;;;;; +1A10;BUGINESE LETTER YA;Lo;0;L;;;;;N;;;;; +1A11;BUGINESE LETTER RA;Lo;0;L;;;;;N;;;;; +1A12;BUGINESE LETTER LA;Lo;0;L;;;;;N;;;;; +1A13;BUGINESE LETTER VA;Lo;0;L;;;;;N;;;;; +1A14;BUGINESE LETTER SA;Lo;0;L;;;;;N;;;;; +1A15;BUGINESE LETTER A;Lo;0;L;;;;;N;;;;; +1A16;BUGINESE LETTER HA;Lo;0;L;;;;;N;;;;; +1A17;BUGINESE VOWEL SIGN I;Mn;230;NSM;;;;;N;;;;; +1A18;BUGINESE VOWEL SIGN U;Mn;220;NSM;;;;;N;;;;; +1A19;BUGINESE VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +1A1A;BUGINESE VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +1A1B;BUGINESE VOWEL SIGN AE;Mc;0;L;;;;;N;;;;; +1A1E;BUGINESE PALLAWA;Po;0;L;;;;;N;;;;; +1A1F;BUGINESE END OF SECTION;Po;0;L;;;;;N;;;;; +1A20;TAI THAM LETTER HIGH KA;Lo;0;L;;;;;N;;;;; +1A21;TAI THAM LETTER HIGH KHA;Lo;0;L;;;;;N;;;;; +1A22;TAI THAM LETTER HIGH KXA;Lo;0;L;;;;;N;;;;; +1A23;TAI THAM LETTER LOW KA;Lo;0;L;;;;;N;;;;; +1A24;TAI THAM LETTER LOW KXA;Lo;0;L;;;;;N;;;;; +1A25;TAI THAM LETTER LOW KHA;Lo;0;L;;;;;N;;;;; +1A26;TAI THAM LETTER NGA;Lo;0;L;;;;;N;;;;; +1A27;TAI THAM LETTER HIGH CA;Lo;0;L;;;;;N;;;;; +1A28;TAI THAM LETTER HIGH CHA;Lo;0;L;;;;;N;;;;; +1A29;TAI THAM LETTER LOW CA;Lo;0;L;;;;;N;;;;; +1A2A;TAI THAM LETTER LOW SA;Lo;0;L;;;;;N;;;;; +1A2B;TAI THAM LETTER LOW CHA;Lo;0;L;;;;;N;;;;; +1A2C;TAI THAM LETTER NYA;Lo;0;L;;;;;N;;;;; +1A2D;TAI THAM LETTER RATA;Lo;0;L;;;;;N;;;;; +1A2E;TAI THAM LETTER HIGH RATHA;Lo;0;L;;;;;N;;;;; +1A2F;TAI THAM LETTER DA;Lo;0;L;;;;;N;;;;; +1A30;TAI THAM LETTER LOW RATHA;Lo;0;L;;;;;N;;;;; +1A31;TAI THAM LETTER RANA;Lo;0;L;;;;;N;;;;; +1A32;TAI THAM LETTER HIGH TA;Lo;0;L;;;;;N;;;;; +1A33;TAI THAM LETTER HIGH THA;Lo;0;L;;;;;N;;;;; +1A34;TAI THAM LETTER LOW TA;Lo;0;L;;;;;N;;;;; +1A35;TAI THAM LETTER LOW THA;Lo;0;L;;;;;N;;;;; +1A36;TAI THAM LETTER NA;Lo;0;L;;;;;N;;;;; +1A37;TAI THAM LETTER BA;Lo;0;L;;;;;N;;;;; +1A38;TAI THAM LETTER HIGH PA;Lo;0;L;;;;;N;;;;; +1A39;TAI THAM LETTER HIGH PHA;Lo;0;L;;;;;N;;;;; +1A3A;TAI THAM LETTER HIGH FA;Lo;0;L;;;;;N;;;;; +1A3B;TAI THAM LETTER LOW PA;Lo;0;L;;;;;N;;;;; +1A3C;TAI THAM LETTER LOW FA;Lo;0;L;;;;;N;;;;; +1A3D;TAI THAM LETTER LOW PHA;Lo;0;L;;;;;N;;;;; +1A3E;TAI THAM LETTER MA;Lo;0;L;;;;;N;;;;; +1A3F;TAI THAM LETTER LOW YA;Lo;0;L;;;;;N;;;;; +1A40;TAI THAM LETTER HIGH YA;Lo;0;L;;;;;N;;;;; +1A41;TAI THAM LETTER RA;Lo;0;L;;;;;N;;;;; +1A42;TAI THAM LETTER RUE;Lo;0;L;;;;;N;;;;; +1A43;TAI THAM LETTER LA;Lo;0;L;;;;;N;;;;; +1A44;TAI THAM LETTER LUE;Lo;0;L;;;;;N;;;;; +1A45;TAI THAM LETTER WA;Lo;0;L;;;;;N;;;;; +1A46;TAI THAM LETTER HIGH SHA;Lo;0;L;;;;;N;;;;; +1A47;TAI THAM LETTER HIGH SSA;Lo;0;L;;;;;N;;;;; +1A48;TAI THAM LETTER HIGH SA;Lo;0;L;;;;;N;;;;; +1A49;TAI THAM LETTER HIGH HA;Lo;0;L;;;;;N;;;;; +1A4A;TAI THAM LETTER LLA;Lo;0;L;;;;;N;;;;; +1A4B;TAI THAM LETTER A;Lo;0;L;;;;;N;;;;; +1A4C;TAI THAM LETTER LOW HA;Lo;0;L;;;;;N;;;;; +1A4D;TAI THAM LETTER I;Lo;0;L;;;;;N;;;;; +1A4E;TAI THAM LETTER II;Lo;0;L;;;;;N;;;;; +1A4F;TAI THAM LETTER U;Lo;0;L;;;;;N;;;;; +1A50;TAI THAM LETTER UU;Lo;0;L;;;;;N;;;;; +1A51;TAI THAM LETTER EE;Lo;0;L;;;;;N;;;;; +1A52;TAI THAM LETTER OO;Lo;0;L;;;;;N;;;;; +1A53;TAI THAM LETTER LAE;Lo;0;L;;;;;N;;;;; +1A54;TAI THAM LETTER GREAT SA;Lo;0;L;;;;;N;;;;; +1A55;TAI THAM CONSONANT SIGN MEDIAL RA;Mc;0;L;;;;;N;;;;; +1A56;TAI THAM CONSONANT SIGN MEDIAL LA;Mn;0;NSM;;;;;N;;;;; +1A57;TAI THAM CONSONANT SIGN LA TANG LAI;Mc;0;L;;;;;N;;;;; +1A58;TAI THAM SIGN MAI KANG LAI;Mn;0;NSM;;;;;N;;;;; +1A59;TAI THAM CONSONANT SIGN FINAL NGA;Mn;0;NSM;;;;;N;;;;; +1A5A;TAI THAM CONSONANT SIGN LOW PA;Mn;0;NSM;;;;;N;;;;; +1A5B;TAI THAM CONSONANT SIGN HIGH RATHA OR LOW PA;Mn;0;NSM;;;;;N;;;;; +1A5C;TAI THAM CONSONANT SIGN MA;Mn;0;NSM;;;;;N;;;;; +1A5D;TAI THAM CONSONANT SIGN BA;Mn;0;NSM;;;;;N;;;;; +1A5E;TAI THAM CONSONANT SIGN SA;Mn;0;NSM;;;;;N;;;;; +1A60;TAI THAM SIGN SAKOT;Mn;9;NSM;;;;;N;;;;; +1A61;TAI THAM VOWEL SIGN A;Mc;0;L;;;;;N;;;;; +1A62;TAI THAM VOWEL SIGN MAI SAT;Mn;0;NSM;;;;;N;;;;; +1A63;TAI THAM VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +1A64;TAI THAM VOWEL SIGN TALL AA;Mc;0;L;;;;;N;;;;; +1A65;TAI THAM VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +1A66;TAI THAM VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;; +1A67;TAI THAM VOWEL SIGN UE;Mn;0;NSM;;;;;N;;;;; +1A68;TAI THAM VOWEL SIGN UUE;Mn;0;NSM;;;;;N;;;;; +1A69;TAI THAM VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +1A6A;TAI THAM VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +1A6B;TAI THAM VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;; +1A6C;TAI THAM VOWEL SIGN OA BELOW;Mn;0;NSM;;;;;N;;;;; +1A6D;TAI THAM VOWEL SIGN OY;Mc;0;L;;;;;N;;;;; +1A6E;TAI THAM VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +1A6F;TAI THAM VOWEL SIGN AE;Mc;0;L;;;;;N;;;;; +1A70;TAI THAM VOWEL SIGN OO;Mc;0;L;;;;;N;;;;; +1A71;TAI THAM VOWEL SIGN AI;Mc;0;L;;;;;N;;;;; +1A72;TAI THAM VOWEL SIGN THAM AI;Mc;0;L;;;;;N;;;;; +1A73;TAI THAM VOWEL SIGN OA ABOVE;Mn;0;NSM;;;;;N;;;;; +1A74;TAI THAM SIGN MAI KANG;Mn;0;NSM;;;;;N;;;;; +1A75;TAI THAM SIGN TONE-1;Mn;230;NSM;;;;;N;;;;; +1A76;TAI THAM SIGN TONE-2;Mn;230;NSM;;;;;N;;;;; +1A77;TAI THAM SIGN KHUEN TONE-3;Mn;230;NSM;;;;;N;;;;; +1A78;TAI THAM SIGN KHUEN TONE-4;Mn;230;NSM;;;;;N;;;;; +1A79;TAI THAM SIGN KHUEN TONE-5;Mn;230;NSM;;;;;N;;;;; +1A7A;TAI THAM SIGN RA HAAM;Mn;230;NSM;;;;;N;;;;; +1A7B;TAI THAM SIGN MAI SAM;Mn;230;NSM;;;;;N;;;;; +1A7C;TAI THAM SIGN KHUEN-LUE KARAN;Mn;230;NSM;;;;;N;;;;; +1A7F;TAI THAM COMBINING CRYPTOGRAMMIC DOT;Mn;220;NSM;;;;;N;;;;; +1A80;TAI THAM HORA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1A81;TAI THAM HORA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1A82;TAI THAM HORA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1A83;TAI THAM HORA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1A84;TAI THAM HORA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1A85;TAI THAM HORA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1A86;TAI THAM HORA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1A87;TAI THAM HORA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1A88;TAI THAM HORA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1A89;TAI THAM HORA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +1A90;TAI THAM THAM DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1A91;TAI THAM THAM DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1A92;TAI THAM THAM DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1A93;TAI THAM THAM DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1A94;TAI THAM THAM DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1A95;TAI THAM THAM DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1A96;TAI THAM THAM DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1A97;TAI THAM THAM DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1A98;TAI THAM THAM DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1A99;TAI THAM THAM DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +1AA0;TAI THAM SIGN WIANG;Po;0;L;;;;;N;;;;; +1AA1;TAI THAM SIGN WIANGWAAK;Po;0;L;;;;;N;;;;; +1AA2;TAI THAM SIGN SAWAN;Po;0;L;;;;;N;;;;; +1AA3;TAI THAM SIGN KEOW;Po;0;L;;;;;N;;;;; +1AA4;TAI THAM SIGN HOY;Po;0;L;;;;;N;;;;; +1AA5;TAI THAM SIGN DOKMAI;Po;0;L;;;;;N;;;;; +1AA6;TAI THAM SIGN REVERSED ROTATED RANA;Po;0;L;;;;;N;;;;; +1AA7;TAI THAM SIGN MAI YAMOK;Lm;0;L;;;;;N;;;;; +1AA8;TAI THAM SIGN KAAN;Po;0;L;;;;;N;;;;; +1AA9;TAI THAM SIGN KAANKUU;Po;0;L;;;;;N;;;;; +1AAA;TAI THAM SIGN SATKAAN;Po;0;L;;;;;N;;;;; +1AAB;TAI THAM SIGN SATKAANKUU;Po;0;L;;;;;N;;;;; +1AAC;TAI THAM SIGN HANG;Po;0;L;;;;;N;;;;; +1AAD;TAI THAM SIGN CAANG;Po;0;L;;;;;N;;;;; +1B00;BALINESE SIGN ULU RICEM;Mn;0;NSM;;;;;N;;;;; +1B01;BALINESE SIGN ULU CANDRA;Mn;0;NSM;;;;;N;;;;; +1B02;BALINESE SIGN CECEK;Mn;0;NSM;;;;;N;;;;; +1B03;BALINESE SIGN SURANG;Mn;0;NSM;;;;;N;;;;; +1B04;BALINESE SIGN BISAH;Mc;0;L;;;;;N;;;;; +1B05;BALINESE LETTER AKARA;Lo;0;L;;;;;N;;;;; +1B06;BALINESE LETTER AKARA TEDUNG;Lo;0;L;1B05 1B35;;;;N;;;;; +1B07;BALINESE LETTER IKARA;Lo;0;L;;;;;N;;;;; +1B08;BALINESE LETTER IKARA TEDUNG;Lo;0;L;1B07 1B35;;;;N;;;;; +1B09;BALINESE LETTER UKARA;Lo;0;L;;;;;N;;;;; +1B0A;BALINESE LETTER UKARA TEDUNG;Lo;0;L;1B09 1B35;;;;N;;;;; +1B0B;BALINESE LETTER RA REPA;Lo;0;L;;;;;N;;;;; +1B0C;BALINESE LETTER RA REPA TEDUNG;Lo;0;L;1B0B 1B35;;;;N;;;;; +1B0D;BALINESE LETTER LA LENGA;Lo;0;L;;;;;N;;;;; +1B0E;BALINESE LETTER LA LENGA TEDUNG;Lo;0;L;1B0D 1B35;;;;N;;;;; +1B0F;BALINESE LETTER EKARA;Lo;0;L;;;;;N;;;;; +1B10;BALINESE LETTER AIKARA;Lo;0;L;;;;;N;;;;; +1B11;BALINESE LETTER OKARA;Lo;0;L;;;;;N;;;;; +1B12;BALINESE LETTER OKARA TEDUNG;Lo;0;L;1B11 1B35;;;;N;;;;; +1B13;BALINESE LETTER KA;Lo;0;L;;;;;N;;;;; +1B14;BALINESE LETTER KA MAHAPRANA;Lo;0;L;;;;;N;;;;; +1B15;BALINESE LETTER GA;Lo;0;L;;;;;N;;;;; +1B16;BALINESE LETTER GA GORA;Lo;0;L;;;;;N;;;;; +1B17;BALINESE LETTER NGA;Lo;0;L;;;;;N;;;;; +1B18;BALINESE LETTER CA;Lo;0;L;;;;;N;;;;; +1B19;BALINESE LETTER CA LACA;Lo;0;L;;;;;N;;;;; +1B1A;BALINESE LETTER JA;Lo;0;L;;;;;N;;;;; +1B1B;BALINESE LETTER JA JERA;Lo;0;L;;;;;N;;;;; +1B1C;BALINESE LETTER NYA;Lo;0;L;;;;;N;;;;; +1B1D;BALINESE LETTER TA LATIK;Lo;0;L;;;;;N;;;;; +1B1E;BALINESE LETTER TA MURDA MAHAPRANA;Lo;0;L;;;;;N;;;;; +1B1F;BALINESE LETTER DA MURDA ALPAPRANA;Lo;0;L;;;;;N;;;;; +1B20;BALINESE LETTER DA MURDA MAHAPRANA;Lo;0;L;;;;;N;;;;; +1B21;BALINESE LETTER NA RAMBAT;Lo;0;L;;;;;N;;;;; +1B22;BALINESE LETTER TA;Lo;0;L;;;;;N;;;;; +1B23;BALINESE LETTER TA TAWA;Lo;0;L;;;;;N;;;;; +1B24;BALINESE LETTER DA;Lo;0;L;;;;;N;;;;; +1B25;BALINESE LETTER DA MADU;Lo;0;L;;;;;N;;;;; +1B26;BALINESE LETTER NA;Lo;0;L;;;;;N;;;;; +1B27;BALINESE LETTER PA;Lo;0;L;;;;;N;;;;; +1B28;BALINESE LETTER PA KAPAL;Lo;0;L;;;;;N;;;;; +1B29;BALINESE LETTER BA;Lo;0;L;;;;;N;;;;; +1B2A;BALINESE LETTER BA KEMBANG;Lo;0;L;;;;;N;;;;; +1B2B;BALINESE LETTER MA;Lo;0;L;;;;;N;;;;; +1B2C;BALINESE LETTER YA;Lo;0;L;;;;;N;;;;; +1B2D;BALINESE LETTER RA;Lo;0;L;;;;;N;;;;; +1B2E;BALINESE LETTER LA;Lo;0;L;;;;;N;;;;; +1B2F;BALINESE LETTER WA;Lo;0;L;;;;;N;;;;; +1B30;BALINESE LETTER SA SAGA;Lo;0;L;;;;;N;;;;; +1B31;BALINESE LETTER SA SAPA;Lo;0;L;;;;;N;;;;; +1B32;BALINESE LETTER SA;Lo;0;L;;;;;N;;;;; +1B33;BALINESE LETTER HA;Lo;0;L;;;;;N;;;;; +1B34;BALINESE SIGN REREKAN;Mn;7;NSM;;;;;N;;;;; +1B35;BALINESE VOWEL SIGN TEDUNG;Mc;0;L;;;;;N;;;;; +1B36;BALINESE VOWEL SIGN ULU;Mn;0;NSM;;;;;N;;;;; +1B37;BALINESE VOWEL SIGN ULU SARI;Mn;0;NSM;;;;;N;;;;; +1B38;BALINESE VOWEL SIGN SUKU;Mn;0;NSM;;;;;N;;;;; +1B39;BALINESE VOWEL SIGN SUKU ILUT;Mn;0;NSM;;;;;N;;;;; +1B3A;BALINESE VOWEL SIGN RA REPA;Mn;0;NSM;;;;;N;;;;; +1B3B;BALINESE VOWEL SIGN RA REPA TEDUNG;Mc;0;L;1B3A 1B35;;;;N;;;;; +1B3C;BALINESE VOWEL SIGN LA LENGA;Mn;0;NSM;;;;;N;;;;; +1B3D;BALINESE VOWEL SIGN LA LENGA TEDUNG;Mc;0;L;1B3C 1B35;;;;N;;;;; +1B3E;BALINESE VOWEL SIGN TALING;Mc;0;L;;;;;N;;;;; +1B3F;BALINESE VOWEL SIGN TALING REPA;Mc;0;L;;;;;N;;;;; +1B40;BALINESE VOWEL SIGN TALING TEDUNG;Mc;0;L;1B3E 1B35;;;;N;;;;; +1B41;BALINESE VOWEL SIGN TALING REPA TEDUNG;Mc;0;L;1B3F 1B35;;;;N;;;;; +1B42;BALINESE VOWEL SIGN PEPET;Mn;0;NSM;;;;;N;;;;; +1B43;BALINESE VOWEL SIGN PEPET TEDUNG;Mc;0;L;1B42 1B35;;;;N;;;;; +1B44;BALINESE ADEG ADEG;Mc;9;L;;;;;N;;;;; +1B45;BALINESE LETTER KAF SASAK;Lo;0;L;;;;;N;;;;; +1B46;BALINESE LETTER KHOT SASAK;Lo;0;L;;;;;N;;;;; +1B47;BALINESE LETTER TZIR SASAK;Lo;0;L;;;;;N;;;;; +1B48;BALINESE LETTER EF SASAK;Lo;0;L;;;;;N;;;;; +1B49;BALINESE LETTER VE SASAK;Lo;0;L;;;;;N;;;;; +1B4A;BALINESE LETTER ZAL SASAK;Lo;0;L;;;;;N;;;;; +1B4B;BALINESE LETTER ASYURA SASAK;Lo;0;L;;;;;N;;;;; +1B50;BALINESE DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1B51;BALINESE DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1B52;BALINESE DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1B53;BALINESE DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1B54;BALINESE DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1B55;BALINESE DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1B56;BALINESE DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1B57;BALINESE DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1B58;BALINESE DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1B59;BALINESE DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +1B5A;BALINESE PANTI;Po;0;L;;;;;N;;;;; +1B5B;BALINESE PAMADA;Po;0;L;;;;;N;;;;; +1B5C;BALINESE WINDU;Po;0;L;;;;;N;;;;; +1B5D;BALINESE CARIK PAMUNGKAH;Po;0;L;;;;;N;;;;; +1B5E;BALINESE CARIK SIKI;Po;0;L;;;;;N;;;;; +1B5F;BALINESE CARIK PAREREN;Po;0;L;;;;;N;;;;; +1B60;BALINESE PAMENENG;Po;0;L;;;;;N;;;;; +1B61;BALINESE MUSICAL SYMBOL DONG;So;0;L;;;;;N;;;;; +1B62;BALINESE MUSICAL SYMBOL DENG;So;0;L;;;;;N;;;;; +1B63;BALINESE MUSICAL SYMBOL DUNG;So;0;L;;;;;N;;;;; +1B64;BALINESE MUSICAL SYMBOL DANG;So;0;L;;;;;N;;;;; +1B65;BALINESE MUSICAL SYMBOL DANG SURANG;So;0;L;;;;;N;;;;; +1B66;BALINESE MUSICAL SYMBOL DING;So;0;L;;;;;N;;;;; +1B67;BALINESE MUSICAL SYMBOL DAENG;So;0;L;;;;;N;;;;; +1B68;BALINESE MUSICAL SYMBOL DEUNG;So;0;L;;;;;N;;;;; +1B69;BALINESE MUSICAL SYMBOL DAING;So;0;L;;;;;N;;;;; +1B6A;BALINESE MUSICAL SYMBOL DANG GEDE;So;0;L;;;;;N;;;;; +1B6B;BALINESE MUSICAL SYMBOL COMBINING TEGEH;Mn;230;NSM;;;;;N;;;;; +1B6C;BALINESE MUSICAL SYMBOL COMBINING ENDEP;Mn;220;NSM;;;;;N;;;;; +1B6D;BALINESE MUSICAL SYMBOL COMBINING KEMPUL;Mn;230;NSM;;;;;N;;;;; +1B6E;BALINESE MUSICAL SYMBOL COMBINING KEMPLI;Mn;230;NSM;;;;;N;;;;; +1B6F;BALINESE MUSICAL SYMBOL COMBINING JEGOGAN;Mn;230;NSM;;;;;N;;;;; +1B70;BALINESE MUSICAL SYMBOL COMBINING KEMPUL WITH JEGOGAN;Mn;230;NSM;;;;;N;;;;; +1B71;BALINESE MUSICAL SYMBOL COMBINING KEMPLI WITH JEGOGAN;Mn;230;NSM;;;;;N;;;;; +1B72;BALINESE MUSICAL SYMBOL COMBINING BENDE;Mn;230;NSM;;;;;N;;;;; +1B73;BALINESE MUSICAL SYMBOL COMBINING GONG;Mn;230;NSM;;;;;N;;;;; +1B74;BALINESE MUSICAL SYMBOL RIGHT-HAND OPEN DUG;So;0;L;;;;;N;;;;; +1B75;BALINESE MUSICAL SYMBOL RIGHT-HAND OPEN DAG;So;0;L;;;;;N;;;;; +1B76;BALINESE MUSICAL SYMBOL RIGHT-HAND CLOSED TUK;So;0;L;;;;;N;;;;; +1B77;BALINESE MUSICAL SYMBOL RIGHT-HAND CLOSED TAK;So;0;L;;;;;N;;;;; +1B78;BALINESE MUSICAL SYMBOL LEFT-HAND OPEN PANG;So;0;L;;;;;N;;;;; +1B79;BALINESE MUSICAL SYMBOL LEFT-HAND OPEN PUNG;So;0;L;;;;;N;;;;; +1B7A;BALINESE MUSICAL SYMBOL LEFT-HAND CLOSED PLAK;So;0;L;;;;;N;;;;; +1B7B;BALINESE MUSICAL SYMBOL LEFT-HAND CLOSED PLUK;So;0;L;;;;;N;;;;; +1B7C;BALINESE MUSICAL SYMBOL LEFT-HAND OPEN PING;So;0;L;;;;;N;;;;; +1B80;SUNDANESE SIGN PANYECEK;Mn;0;NSM;;;;;N;;;;; +1B81;SUNDANESE SIGN PANGLAYAR;Mn;0;NSM;;;;;N;;;;; +1B82;SUNDANESE SIGN PANGWISAD;Mc;0;L;;;;;N;;;;; +1B83;SUNDANESE LETTER A;Lo;0;L;;;;;N;;;;; +1B84;SUNDANESE LETTER I;Lo;0;L;;;;;N;;;;; +1B85;SUNDANESE LETTER U;Lo;0;L;;;;;N;;;;; +1B86;SUNDANESE LETTER AE;Lo;0;L;;;;;N;;;;; +1B87;SUNDANESE LETTER O;Lo;0;L;;;;;N;;;;; +1B88;SUNDANESE LETTER E;Lo;0;L;;;;;N;;;;; +1B89;SUNDANESE LETTER EU;Lo;0;L;;;;;N;;;;; +1B8A;SUNDANESE LETTER KA;Lo;0;L;;;;;N;;;;; +1B8B;SUNDANESE LETTER QA;Lo;0;L;;;;;N;;;;; +1B8C;SUNDANESE LETTER GA;Lo;0;L;;;;;N;;;;; +1B8D;SUNDANESE LETTER NGA;Lo;0;L;;;;;N;;;;; +1B8E;SUNDANESE LETTER CA;Lo;0;L;;;;;N;;;;; +1B8F;SUNDANESE LETTER JA;Lo;0;L;;;;;N;;;;; +1B90;SUNDANESE LETTER ZA;Lo;0;L;;;;;N;;;;; +1B91;SUNDANESE LETTER NYA;Lo;0;L;;;;;N;;;;; +1B92;SUNDANESE LETTER TA;Lo;0;L;;;;;N;;;;; +1B93;SUNDANESE LETTER DA;Lo;0;L;;;;;N;;;;; +1B94;SUNDANESE LETTER NA;Lo;0;L;;;;;N;;;;; +1B95;SUNDANESE LETTER PA;Lo;0;L;;;;;N;;;;; +1B96;SUNDANESE LETTER FA;Lo;0;L;;;;;N;;;;; +1B97;SUNDANESE LETTER VA;Lo;0;L;;;;;N;;;;; +1B98;SUNDANESE LETTER BA;Lo;0;L;;;;;N;;;;; +1B99;SUNDANESE LETTER MA;Lo;0;L;;;;;N;;;;; +1B9A;SUNDANESE LETTER YA;Lo;0;L;;;;;N;;;;; +1B9B;SUNDANESE LETTER RA;Lo;0;L;;;;;N;;;;; +1B9C;SUNDANESE LETTER LA;Lo;0;L;;;;;N;;;;; +1B9D;SUNDANESE LETTER WA;Lo;0;L;;;;;N;;;;; +1B9E;SUNDANESE LETTER SA;Lo;0;L;;;;;N;;;;; +1B9F;SUNDANESE LETTER XA;Lo;0;L;;;;;N;;;;; +1BA0;SUNDANESE LETTER HA;Lo;0;L;;;;;N;;;;; +1BA1;SUNDANESE CONSONANT SIGN PAMINGKAL;Mc;0;L;;;;;N;;;;; +1BA2;SUNDANESE CONSONANT SIGN PANYAKRA;Mn;0;NSM;;;;;N;;;;; +1BA3;SUNDANESE CONSONANT SIGN PANYIKU;Mn;0;NSM;;;;;N;;;;; +1BA4;SUNDANESE VOWEL SIGN PANGHULU;Mn;0;NSM;;;;;N;;;;; +1BA5;SUNDANESE VOWEL SIGN PANYUKU;Mn;0;NSM;;;;;N;;;;; +1BA6;SUNDANESE VOWEL SIGN PANAELAENG;Mc;0;L;;;;;N;;;;; +1BA7;SUNDANESE VOWEL SIGN PANOLONG;Mc;0;L;;;;;N;;;;; +1BA8;SUNDANESE VOWEL SIGN PAMEPET;Mn;0;NSM;;;;;N;;;;; +1BA9;SUNDANESE VOWEL SIGN PANEULEUNG;Mn;0;NSM;;;;;N;;;;; +1BAA;SUNDANESE SIGN PAMAAEH;Mc;9;L;;;;;N;;;;; +1BAB;SUNDANESE SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +1BAC;SUNDANESE CONSONANT SIGN PASANGAN MA;Mc;0;L;;;;;N;;;;; +1BAD;SUNDANESE CONSONANT SIGN PASANGAN WA;Mc;0;L;;;;;N;;;;; +1BAE;SUNDANESE LETTER KHA;Lo;0;L;;;;;N;;;;; +1BAF;SUNDANESE LETTER SYA;Lo;0;L;;;;;N;;;;; +1BB0;SUNDANESE DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1BB1;SUNDANESE DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1BB2;SUNDANESE DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1BB3;SUNDANESE DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1BB4;SUNDANESE DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1BB5;SUNDANESE DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1BB6;SUNDANESE DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1BB7;SUNDANESE DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1BB8;SUNDANESE DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1BB9;SUNDANESE DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +1BBA;SUNDANESE AVAGRAHA;Lo;0;L;;;;;N;;;;; +1BBB;SUNDANESE LETTER REU;Lo;0;L;;;;;N;;;;; +1BBC;SUNDANESE LETTER LEU;Lo;0;L;;;;;N;;;;; +1BBD;SUNDANESE LETTER BHA;Lo;0;L;;;;;N;;;;; +1BBE;SUNDANESE LETTER FINAL K;Lo;0;L;;;;;N;;;;; +1BBF;SUNDANESE LETTER FINAL M;Lo;0;L;;;;;N;;;;; +1BC0;BATAK LETTER A;Lo;0;L;;;;;N;;;;; +1BC1;BATAK LETTER SIMALUNGUN A;Lo;0;L;;;;;N;;;;; +1BC2;BATAK LETTER HA;Lo;0;L;;;;;N;;;;; +1BC3;BATAK LETTER SIMALUNGUN HA;Lo;0;L;;;;;N;;;;; +1BC4;BATAK LETTER MANDAILING HA;Lo;0;L;;;;;N;;;;; +1BC5;BATAK LETTER BA;Lo;0;L;;;;;N;;;;; +1BC6;BATAK LETTER KARO BA;Lo;0;L;;;;;N;;;;; +1BC7;BATAK LETTER PA;Lo;0;L;;;;;N;;;;; +1BC8;BATAK LETTER SIMALUNGUN PA;Lo;0;L;;;;;N;;;;; +1BC9;BATAK LETTER NA;Lo;0;L;;;;;N;;;;; +1BCA;BATAK LETTER MANDAILING NA;Lo;0;L;;;;;N;;;;; +1BCB;BATAK LETTER WA;Lo;0;L;;;;;N;;;;; +1BCC;BATAK LETTER SIMALUNGUN WA;Lo;0;L;;;;;N;;;;; +1BCD;BATAK LETTER PAKPAK WA;Lo;0;L;;;;;N;;;;; +1BCE;BATAK LETTER GA;Lo;0;L;;;;;N;;;;; +1BCF;BATAK LETTER SIMALUNGUN GA;Lo;0;L;;;;;N;;;;; +1BD0;BATAK LETTER JA;Lo;0;L;;;;;N;;;;; +1BD1;BATAK LETTER DA;Lo;0;L;;;;;N;;;;; +1BD2;BATAK LETTER RA;Lo;0;L;;;;;N;;;;; +1BD3;BATAK LETTER SIMALUNGUN RA;Lo;0;L;;;;;N;;;;; +1BD4;BATAK LETTER MA;Lo;0;L;;;;;N;;;;; +1BD5;BATAK LETTER SIMALUNGUN MA;Lo;0;L;;;;;N;;;;; +1BD6;BATAK LETTER SOUTHERN TA;Lo;0;L;;;;;N;;;;; +1BD7;BATAK LETTER NORTHERN TA;Lo;0;L;;;;;N;;;;; +1BD8;BATAK LETTER SA;Lo;0;L;;;;;N;;;;; +1BD9;BATAK LETTER SIMALUNGUN SA;Lo;0;L;;;;;N;;;;; +1BDA;BATAK LETTER MANDAILING SA;Lo;0;L;;;;;N;;;;; +1BDB;BATAK LETTER YA;Lo;0;L;;;;;N;;;;; +1BDC;BATAK LETTER SIMALUNGUN YA;Lo;0;L;;;;;N;;;;; +1BDD;BATAK LETTER NGA;Lo;0;L;;;;;N;;;;; +1BDE;BATAK LETTER LA;Lo;0;L;;;;;N;;;;; +1BDF;BATAK LETTER SIMALUNGUN LA;Lo;0;L;;;;;N;;;;; +1BE0;BATAK LETTER NYA;Lo;0;L;;;;;N;;;;; +1BE1;BATAK LETTER CA;Lo;0;L;;;;;N;;;;; +1BE2;BATAK LETTER NDA;Lo;0;L;;;;;N;;;;; +1BE3;BATAK LETTER MBA;Lo;0;L;;;;;N;;;;; +1BE4;BATAK LETTER I;Lo;0;L;;;;;N;;;;; +1BE5;BATAK LETTER U;Lo;0;L;;;;;N;;;;; +1BE6;BATAK SIGN TOMPI;Mn;7;NSM;;;;;N;;;;; +1BE7;BATAK VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +1BE8;BATAK VOWEL SIGN PAKPAK E;Mn;0;NSM;;;;;N;;;;; +1BE9;BATAK VOWEL SIGN EE;Mn;0;NSM;;;;;N;;;;; +1BEA;BATAK VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +1BEB;BATAK VOWEL SIGN KARO I;Mc;0;L;;;;;N;;;;; +1BEC;BATAK VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +1BED;BATAK VOWEL SIGN KARO O;Mn;0;NSM;;;;;N;;;;; +1BEE;BATAK VOWEL SIGN U;Mc;0;L;;;;;N;;;;; +1BEF;BATAK VOWEL SIGN U FOR SIMALUNGUN SA;Mn;0;NSM;;;;;N;;;;; +1BF0;BATAK CONSONANT SIGN NG;Mn;0;NSM;;;;;N;;;;; +1BF1;BATAK CONSONANT SIGN H;Mn;0;NSM;;;;;N;;;;; +1BF2;BATAK PANGOLAT;Mc;9;L;;;;;N;;;;; +1BF3;BATAK PANONGONAN;Mc;9;L;;;;;N;;;;; +1BFC;BATAK SYMBOL BINDU NA METEK;Po;0;L;;;;;N;;;;; +1BFD;BATAK SYMBOL BINDU PINARBORAS;Po;0;L;;;;;N;;;;; +1BFE;BATAK SYMBOL BINDU JUDUL;Po;0;L;;;;;N;;;;; +1BFF;BATAK SYMBOL BINDU PANGOLAT;Po;0;L;;;;;N;;;;; +1C00;LEPCHA LETTER KA;Lo;0;L;;;;;N;;;;; +1C01;LEPCHA LETTER KLA;Lo;0;L;;;;;N;;;;; +1C02;LEPCHA LETTER KHA;Lo;0;L;;;;;N;;;;; +1C03;LEPCHA LETTER GA;Lo;0;L;;;;;N;;;;; +1C04;LEPCHA LETTER GLA;Lo;0;L;;;;;N;;;;; +1C05;LEPCHA LETTER NGA;Lo;0;L;;;;;N;;;;; +1C06;LEPCHA LETTER CA;Lo;0;L;;;;;N;;;;; +1C07;LEPCHA LETTER CHA;Lo;0;L;;;;;N;;;;; +1C08;LEPCHA LETTER JA;Lo;0;L;;;;;N;;;;; +1C09;LEPCHA LETTER NYA;Lo;0;L;;;;;N;;;;; +1C0A;LEPCHA LETTER TA;Lo;0;L;;;;;N;;;;; +1C0B;LEPCHA LETTER THA;Lo;0;L;;;;;N;;;;; +1C0C;LEPCHA LETTER DA;Lo;0;L;;;;;N;;;;; +1C0D;LEPCHA LETTER NA;Lo;0;L;;;;;N;;;;; +1C0E;LEPCHA LETTER PA;Lo;0;L;;;;;N;;;;; +1C0F;LEPCHA LETTER PLA;Lo;0;L;;;;;N;;;;; +1C10;LEPCHA LETTER PHA;Lo;0;L;;;;;N;;;;; +1C11;LEPCHA LETTER FA;Lo;0;L;;;;;N;;;;; +1C12;LEPCHA LETTER FLA;Lo;0;L;;;;;N;;;;; +1C13;LEPCHA LETTER BA;Lo;0;L;;;;;N;;;;; +1C14;LEPCHA LETTER BLA;Lo;0;L;;;;;N;;;;; +1C15;LEPCHA LETTER MA;Lo;0;L;;;;;N;;;;; +1C16;LEPCHA LETTER MLA;Lo;0;L;;;;;N;;;;; +1C17;LEPCHA LETTER TSA;Lo;0;L;;;;;N;;;;; +1C18;LEPCHA LETTER TSHA;Lo;0;L;;;;;N;;;;; +1C19;LEPCHA LETTER DZA;Lo;0;L;;;;;N;;;;; +1C1A;LEPCHA LETTER YA;Lo;0;L;;;;;N;;;;; +1C1B;LEPCHA LETTER RA;Lo;0;L;;;;;N;;;;; +1C1C;LEPCHA LETTER LA;Lo;0;L;;;;;N;;;;; +1C1D;LEPCHA LETTER HA;Lo;0;L;;;;;N;;;;; +1C1E;LEPCHA LETTER HLA;Lo;0;L;;;;;N;;;;; +1C1F;LEPCHA LETTER VA;Lo;0;L;;;;;N;;;;; +1C20;LEPCHA LETTER SA;Lo;0;L;;;;;N;;;;; +1C21;LEPCHA LETTER SHA;Lo;0;L;;;;;N;;;;; +1C22;LEPCHA LETTER WA;Lo;0;L;;;;;N;;;;; +1C23;LEPCHA LETTER A;Lo;0;L;;;;;N;;;;; +1C24;LEPCHA SUBJOINED LETTER YA;Mc;0;L;;;;;N;;;;; +1C25;LEPCHA SUBJOINED LETTER RA;Mc;0;L;;;;;N;;;;; +1C26;LEPCHA VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +1C27;LEPCHA VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +1C28;LEPCHA VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +1C29;LEPCHA VOWEL SIGN OO;Mc;0;L;;;;;N;;;;; +1C2A;LEPCHA VOWEL SIGN U;Mc;0;L;;;;;N;;;;; +1C2B;LEPCHA VOWEL SIGN UU;Mc;0;L;;;;;N;;;;; +1C2C;LEPCHA VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +1C2D;LEPCHA CONSONANT SIGN K;Mn;0;NSM;;;;;N;;;;; +1C2E;LEPCHA CONSONANT SIGN M;Mn;0;NSM;;;;;N;;;;; +1C2F;LEPCHA CONSONANT SIGN L;Mn;0;NSM;;;;;N;;;;; +1C30;LEPCHA CONSONANT SIGN N;Mn;0;NSM;;;;;N;;;;; +1C31;LEPCHA CONSONANT SIGN P;Mn;0;NSM;;;;;N;;;;; +1C32;LEPCHA CONSONANT SIGN R;Mn;0;NSM;;;;;N;;;;; +1C33;LEPCHA CONSONANT SIGN T;Mn;0;NSM;;;;;N;;;;; +1C34;LEPCHA CONSONANT SIGN NYIN-DO;Mc;0;L;;;;;N;;;;; +1C35;LEPCHA CONSONANT SIGN KANG;Mc;0;L;;;;;N;;;;; +1C36;LEPCHA SIGN RAN;Mn;0;NSM;;;;;N;;;;; +1C37;LEPCHA SIGN NUKTA;Mn;7;NSM;;;;;N;;;;; +1C3B;LEPCHA PUNCTUATION TA-ROL;Po;0;L;;;;;N;;;;; +1C3C;LEPCHA PUNCTUATION NYET THYOOM TA-ROL;Po;0;L;;;;;N;;;;; +1C3D;LEPCHA PUNCTUATION CER-WA;Po;0;L;;;;;N;;;;; +1C3E;LEPCHA PUNCTUATION TSHOOK CER-WA;Po;0;L;;;;;N;;;;; +1C3F;LEPCHA PUNCTUATION TSHOOK;Po;0;L;;;;;N;;;;; +1C40;LEPCHA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1C41;LEPCHA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1C42;LEPCHA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1C43;LEPCHA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1C44;LEPCHA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1C45;LEPCHA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1C46;LEPCHA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1C47;LEPCHA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1C48;LEPCHA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1C49;LEPCHA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +1C4D;LEPCHA LETTER TTA;Lo;0;L;;;;;N;;;;; +1C4E;LEPCHA LETTER TTHA;Lo;0;L;;;;;N;;;;; +1C4F;LEPCHA LETTER DDA;Lo;0;L;;;;;N;;;;; +1C50;OL CHIKI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +1C51;OL CHIKI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +1C52;OL CHIKI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +1C53;OL CHIKI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1C54;OL CHIKI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1C55;OL CHIKI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1C56;OL CHIKI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1C57;OL CHIKI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1C58;OL CHIKI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1C59;OL CHIKI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +1C5A;OL CHIKI LETTER LA;Lo;0;L;;;;;N;;;;; +1C5B;OL CHIKI LETTER AT;Lo;0;L;;;;;N;;;;; +1C5C;OL CHIKI LETTER AG;Lo;0;L;;;;;N;;;;; +1C5D;OL CHIKI LETTER ANG;Lo;0;L;;;;;N;;;;; +1C5E;OL CHIKI LETTER AL;Lo;0;L;;;;;N;;;;; +1C5F;OL CHIKI LETTER LAA;Lo;0;L;;;;;N;;;;; +1C60;OL CHIKI LETTER AAK;Lo;0;L;;;;;N;;;;; +1C61;OL CHIKI LETTER AAJ;Lo;0;L;;;;;N;;;;; +1C62;OL CHIKI LETTER AAM;Lo;0;L;;;;;N;;;;; +1C63;OL CHIKI LETTER AAW;Lo;0;L;;;;;N;;;;; +1C64;OL CHIKI LETTER LI;Lo;0;L;;;;;N;;;;; +1C65;OL CHIKI LETTER IS;Lo;0;L;;;;;N;;;;; +1C66;OL CHIKI LETTER IH;Lo;0;L;;;;;N;;;;; +1C67;OL CHIKI LETTER INY;Lo;0;L;;;;;N;;;;; +1C68;OL CHIKI LETTER IR;Lo;0;L;;;;;N;;;;; +1C69;OL CHIKI LETTER LU;Lo;0;L;;;;;N;;;;; +1C6A;OL CHIKI LETTER UC;Lo;0;L;;;;;N;;;;; +1C6B;OL CHIKI LETTER UD;Lo;0;L;;;;;N;;;;; +1C6C;OL CHIKI LETTER UNN;Lo;0;L;;;;;N;;;;; +1C6D;OL CHIKI LETTER UY;Lo;0;L;;;;;N;;;;; +1C6E;OL CHIKI LETTER LE;Lo;0;L;;;;;N;;;;; +1C6F;OL CHIKI LETTER EP;Lo;0;L;;;;;N;;;;; +1C70;OL CHIKI LETTER EDD;Lo;0;L;;;;;N;;;;; +1C71;OL CHIKI LETTER EN;Lo;0;L;;;;;N;;;;; +1C72;OL CHIKI LETTER ERR;Lo;0;L;;;;;N;;;;; +1C73;OL CHIKI LETTER LO;Lo;0;L;;;;;N;;;;; +1C74;OL CHIKI LETTER OTT;Lo;0;L;;;;;N;;;;; +1C75;OL CHIKI LETTER OB;Lo;0;L;;;;;N;;;;; +1C76;OL CHIKI LETTER OV;Lo;0;L;;;;;N;;;;; +1C77;OL CHIKI LETTER OH;Lo;0;L;;;;;N;;;;; +1C78;OL CHIKI MU TTUDDAG;Lm;0;L;;;;;N;;;;; +1C79;OL CHIKI GAAHLAA TTUDDAAG;Lm;0;L;;;;;N;;;;; +1C7A;OL CHIKI MU-GAAHLAA TTUDDAAG;Lm;0;L;;;;;N;;;;; +1C7B;OL CHIKI RELAA;Lm;0;L;;;;;N;;;;; +1C7C;OL CHIKI PHAARKAA;Lm;0;L;;;;;N;;;;; +1C7D;OL CHIKI AHAD;Lm;0;L;;;;;N;;;;; +1C7E;OL CHIKI PUNCTUATION MUCAAD;Po;0;L;;;;;N;;;;; +1C7F;OL CHIKI PUNCTUATION DOUBLE MUCAAD;Po;0;L;;;;;N;;;;; +1CC0;SUNDANESE PUNCTUATION BINDU SURYA;Po;0;L;;;;;N;;;;; +1CC1;SUNDANESE PUNCTUATION BINDU PANGLONG;Po;0;L;;;;;N;;;;; +1CC2;SUNDANESE PUNCTUATION BINDU PURNAMA;Po;0;L;;;;;N;;;;; +1CC3;SUNDANESE PUNCTUATION BINDU CAKRA;Po;0;L;;;;;N;;;;; +1CC4;SUNDANESE PUNCTUATION BINDU LEU SATANGA;Po;0;L;;;;;N;;;;; +1CC5;SUNDANESE PUNCTUATION BINDU KA SATANGA;Po;0;L;;;;;N;;;;; +1CC6;SUNDANESE PUNCTUATION BINDU DA SATANGA;Po;0;L;;;;;N;;;;; +1CC7;SUNDANESE PUNCTUATION BINDU BA SATANGA;Po;0;L;;;;;N;;;;; +1CD0;VEDIC TONE KARSHANA;Mn;230;NSM;;;;;N;;;;; +1CD1;VEDIC TONE SHARA;Mn;230;NSM;;;;;N;;;;; +1CD2;VEDIC TONE PRENKHA;Mn;230;NSM;;;;;N;;;;; +1CD3;VEDIC SIGN NIHSHVASA;Po;0;L;;;;;N;;;;; +1CD4;VEDIC SIGN YAJURVEDIC MIDLINE SVARITA;Mn;1;NSM;;;;;N;;;;; +1CD5;VEDIC TONE YAJURVEDIC AGGRAVATED INDEPENDENT SVARITA;Mn;220;NSM;;;;;N;;;;; +1CD6;VEDIC TONE YAJURVEDIC INDEPENDENT SVARITA;Mn;220;NSM;;;;;N;;;;; +1CD7;VEDIC TONE YAJURVEDIC KATHAKA INDEPENDENT SVARITA;Mn;220;NSM;;;;;N;;;;; +1CD8;VEDIC TONE CANDRA BELOW;Mn;220;NSM;;;;;N;;;;; +1CD9;VEDIC TONE YAJURVEDIC KATHAKA INDEPENDENT SVARITA SCHROEDER;Mn;220;NSM;;;;;N;;;;; +1CDA;VEDIC TONE DOUBLE SVARITA;Mn;230;NSM;;;;;N;;;;; +1CDB;VEDIC TONE TRIPLE SVARITA;Mn;230;NSM;;;;;N;;;;; +1CDC;VEDIC TONE KATHAKA ANUDATTA;Mn;220;NSM;;;;;N;;;;; +1CDD;VEDIC TONE DOT BELOW;Mn;220;NSM;;;;;N;;;;; +1CDE;VEDIC TONE TWO DOTS BELOW;Mn;220;NSM;;;;;N;;;;; +1CDF;VEDIC TONE THREE DOTS BELOW;Mn;220;NSM;;;;;N;;;;; +1CE0;VEDIC TONE RIGVEDIC KASHMIRI INDEPENDENT SVARITA;Mn;230;NSM;;;;;N;;;;; +1CE1;VEDIC TONE ATHARVAVEDIC INDEPENDENT SVARITA;Mc;0;L;;;;;N;;;;; +1CE2;VEDIC SIGN VISARGA SVARITA;Mn;1;NSM;;;;;N;;;;; +1CE3;VEDIC SIGN VISARGA UDATTA;Mn;1;NSM;;;;;N;;;;; +1CE4;VEDIC SIGN REVERSED VISARGA UDATTA;Mn;1;NSM;;;;;N;;;;; +1CE5;VEDIC SIGN VISARGA ANUDATTA;Mn;1;NSM;;;;;N;;;;; +1CE6;VEDIC SIGN REVERSED VISARGA ANUDATTA;Mn;1;NSM;;;;;N;;;;; +1CE7;VEDIC SIGN VISARGA UDATTA WITH TAIL;Mn;1;NSM;;;;;N;;;;; +1CE8;VEDIC SIGN VISARGA ANUDATTA WITH TAIL;Mn;1;NSM;;;;;N;;;;; +1CE9;VEDIC SIGN ANUSVARA ANTARGOMUKHA;Lo;0;L;;;;;N;;;;; +1CEA;VEDIC SIGN ANUSVARA BAHIRGOMUKHA;Lo;0;L;;;;;N;;;;; +1CEB;VEDIC SIGN ANUSVARA VAMAGOMUKHA;Lo;0;L;;;;;N;;;;; +1CEC;VEDIC SIGN ANUSVARA VAMAGOMUKHA WITH TAIL;Lo;0;L;;;;;N;;;;; +1CED;VEDIC SIGN TIRYAK;Mn;220;NSM;;;;;N;;;;; +1CEE;VEDIC SIGN HEXIFORM LONG ANUSVARA;Lo;0;L;;;;;N;;;;; +1CEF;VEDIC SIGN LONG ANUSVARA;Lo;0;L;;;;;N;;;;; +1CF0;VEDIC SIGN RTHANG LONG ANUSVARA;Lo;0;L;;;;;N;;;;; +1CF1;VEDIC SIGN ANUSVARA UBHAYATO MUKHA;Lo;0;L;;;;;N;;;;; +1CF2;VEDIC SIGN ARDHAVISARGA;Mc;0;L;;;;;N;;;;; +1CF3;VEDIC SIGN ROTATED ARDHAVISARGA;Mc;0;L;;;;;N;;;;; +1CF4;VEDIC TONE CANDRA ABOVE;Mn;230;NSM;;;;;N;;;;; +1CF5;VEDIC SIGN JIHVAMULIYA;Lo;0;L;;;;;N;;;;; +1CF6;VEDIC SIGN UPADHMANIYA;Lo;0;L;;;;;N;;;;; +1D00;LATIN LETTER SMALL CAPITAL A;Ll;0;L;;;;;N;;;;; +1D01;LATIN LETTER SMALL CAPITAL AE;Ll;0;L;;;;;N;;;;; +1D02;LATIN SMALL LETTER TURNED AE;Ll;0;L;;;;;N;;;;; +1D03;LATIN LETTER SMALL CAPITAL BARRED B;Ll;0;L;;;;;N;;;;; +1D04;LATIN LETTER SMALL CAPITAL C;Ll;0;L;;;;;N;;;;; +1D05;LATIN LETTER SMALL CAPITAL D;Ll;0;L;;;;;N;;;;; +1D06;LATIN LETTER SMALL CAPITAL ETH;Ll;0;L;;;;;N;;;;; +1D07;LATIN LETTER SMALL CAPITAL E;Ll;0;L;;;;;N;;;;; +1D08;LATIN SMALL LETTER TURNED OPEN E;Ll;0;L;;;;;N;;;;; +1D09;LATIN SMALL LETTER TURNED I;Ll;0;L;;;;;N;;;;; +1D0A;LATIN LETTER SMALL CAPITAL J;Ll;0;L;;;;;N;;;;; +1D0B;LATIN LETTER SMALL CAPITAL K;Ll;0;L;;;;;N;;;;; +1D0C;LATIN LETTER SMALL CAPITAL L WITH STROKE;Ll;0;L;;;;;N;;;;; +1D0D;LATIN LETTER SMALL CAPITAL M;Ll;0;L;;;;;N;;;;; +1D0E;LATIN LETTER SMALL CAPITAL REVERSED N;Ll;0;L;;;;;N;;;;; +1D0F;LATIN LETTER SMALL CAPITAL O;Ll;0;L;;;;;N;;;;; +1D10;LATIN LETTER SMALL CAPITAL OPEN O;Ll;0;L;;;;;N;;;;; +1D11;LATIN SMALL LETTER SIDEWAYS O;Ll;0;L;;;;;N;;;;; +1D12;LATIN SMALL LETTER SIDEWAYS OPEN O;Ll;0;L;;;;;N;;;;; +1D13;LATIN SMALL LETTER SIDEWAYS O WITH STROKE;Ll;0;L;;;;;N;;;;; +1D14;LATIN SMALL LETTER TURNED OE;Ll;0;L;;;;;N;;;;; +1D15;LATIN LETTER SMALL CAPITAL OU;Ll;0;L;;;;;N;;;;; +1D16;LATIN SMALL LETTER TOP HALF O;Ll;0;L;;;;;N;;;;; +1D17;LATIN SMALL LETTER BOTTOM HALF O;Ll;0;L;;;;;N;;;;; +1D18;LATIN LETTER SMALL CAPITAL P;Ll;0;L;;;;;N;;;;; +1D19;LATIN LETTER SMALL CAPITAL REVERSED R;Ll;0;L;;;;;N;;;;; +1D1A;LATIN LETTER SMALL CAPITAL TURNED R;Ll;0;L;;;;;N;;;;; +1D1B;LATIN LETTER SMALL CAPITAL T;Ll;0;L;;;;;N;;;;; +1D1C;LATIN LETTER SMALL CAPITAL U;Ll;0;L;;;;;N;;;;; +1D1D;LATIN SMALL LETTER SIDEWAYS U;Ll;0;L;;;;;N;;;;; +1D1E;LATIN SMALL LETTER SIDEWAYS DIAERESIZED U;Ll;0;L;;;;;N;;;;; +1D1F;LATIN SMALL LETTER SIDEWAYS TURNED M;Ll;0;L;;;;;N;;;;; +1D20;LATIN LETTER SMALL CAPITAL V;Ll;0;L;;;;;N;;;;; +1D21;LATIN LETTER SMALL CAPITAL W;Ll;0;L;;;;;N;;;;; +1D22;LATIN LETTER SMALL CAPITAL Z;Ll;0;L;;;;;N;;;;; +1D23;LATIN LETTER SMALL CAPITAL EZH;Ll;0;L;;;;;N;;;;; +1D24;LATIN LETTER VOICED LARYNGEAL SPIRANT;Ll;0;L;;;;;N;;;;; +1D25;LATIN LETTER AIN;Ll;0;L;;;;;N;;;;; +1D26;GREEK LETTER SMALL CAPITAL GAMMA;Ll;0;L;;;;;N;;;;; +1D27;GREEK LETTER SMALL CAPITAL LAMDA;Ll;0;L;;;;;N;;;;; +1D28;GREEK LETTER SMALL CAPITAL PI;Ll;0;L;;;;;N;;;;; +1D29;GREEK LETTER SMALL CAPITAL RHO;Ll;0;L;;;;;N;;;;; +1D2A;GREEK LETTER SMALL CAPITAL PSI;Ll;0;L;;;;;N;;;;; +1D2B;CYRILLIC LETTER SMALL CAPITAL EL;Ll;0;L;;;;;N;;;;; +1D2C;MODIFIER LETTER CAPITAL A;Lm;0;L; 0041;;;;N;;;;; +1D2D;MODIFIER LETTER CAPITAL AE;Lm;0;L; 00C6;;;;N;;;;; +1D2E;MODIFIER LETTER CAPITAL B;Lm;0;L; 0042;;;;N;;;;; +1D2F;MODIFIER LETTER CAPITAL BARRED B;Lm;0;L;;;;;N;;;;; +1D30;MODIFIER LETTER CAPITAL D;Lm;0;L; 0044;;;;N;;;;; +1D31;MODIFIER LETTER CAPITAL E;Lm;0;L; 0045;;;;N;;;;; +1D32;MODIFIER LETTER CAPITAL REVERSED E;Lm;0;L; 018E;;;;N;;;;; +1D33;MODIFIER LETTER CAPITAL G;Lm;0;L; 0047;;;;N;;;;; +1D34;MODIFIER LETTER CAPITAL H;Lm;0;L; 0048;;;;N;;;;; +1D35;MODIFIER LETTER CAPITAL I;Lm;0;L; 0049;;;;N;;;;; +1D36;MODIFIER LETTER CAPITAL J;Lm;0;L; 004A;;;;N;;;;; +1D37;MODIFIER LETTER CAPITAL K;Lm;0;L; 004B;;;;N;;;;; +1D38;MODIFIER LETTER CAPITAL L;Lm;0;L; 004C;;;;N;;;;; +1D39;MODIFIER LETTER CAPITAL M;Lm;0;L; 004D;;;;N;;;;; +1D3A;MODIFIER LETTER CAPITAL N;Lm;0;L; 004E;;;;N;;;;; +1D3B;MODIFIER LETTER CAPITAL REVERSED N;Lm;0;L;;;;;N;;;;; +1D3C;MODIFIER LETTER CAPITAL O;Lm;0;L; 004F;;;;N;;;;; +1D3D;MODIFIER LETTER CAPITAL OU;Lm;0;L; 0222;;;;N;;;;; +1D3E;MODIFIER LETTER CAPITAL P;Lm;0;L; 0050;;;;N;;;;; +1D3F;MODIFIER LETTER CAPITAL R;Lm;0;L; 0052;;;;N;;;;; +1D40;MODIFIER LETTER CAPITAL T;Lm;0;L; 0054;;;;N;;;;; +1D41;MODIFIER LETTER CAPITAL U;Lm;0;L; 0055;;;;N;;;;; +1D42;MODIFIER LETTER CAPITAL W;Lm;0;L; 0057;;;;N;;;;; +1D43;MODIFIER LETTER SMALL A;Lm;0;L; 0061;;;;N;;;;; +1D44;MODIFIER LETTER SMALL TURNED A;Lm;0;L; 0250;;;;N;;;;; +1D45;MODIFIER LETTER SMALL ALPHA;Lm;0;L; 0251;;;;N;;;;; +1D46;MODIFIER LETTER SMALL TURNED AE;Lm;0;L; 1D02;;;;N;;;;; +1D47;MODIFIER LETTER SMALL B;Lm;0;L; 0062;;;;N;;;;; +1D48;MODIFIER LETTER SMALL D;Lm;0;L; 0064;;;;N;;;;; +1D49;MODIFIER LETTER SMALL E;Lm;0;L; 0065;;;;N;;;;; +1D4A;MODIFIER LETTER SMALL SCHWA;Lm;0;L; 0259;;;;N;;;;; +1D4B;MODIFIER LETTER SMALL OPEN E;Lm;0;L; 025B;;;;N;;;;; +1D4C;MODIFIER LETTER SMALL TURNED OPEN E;Lm;0;L; 025C;;;;N;;;;; +1D4D;MODIFIER LETTER SMALL G;Lm;0;L; 0067;;;;N;;;;; +1D4E;MODIFIER LETTER SMALL TURNED I;Lm;0;L;;;;;N;;;;; +1D4F;MODIFIER LETTER SMALL K;Lm;0;L; 006B;;;;N;;;;; +1D50;MODIFIER LETTER SMALL M;Lm;0;L; 006D;;;;N;;;;; +1D51;MODIFIER LETTER SMALL ENG;Lm;0;L; 014B;;;;N;;;;; +1D52;MODIFIER LETTER SMALL O;Lm;0;L; 006F;;;;N;;;;; +1D53;MODIFIER LETTER SMALL OPEN O;Lm;0;L; 0254;;;;N;;;;; +1D54;MODIFIER LETTER SMALL TOP HALF O;Lm;0;L; 1D16;;;;N;;;;; +1D55;MODIFIER LETTER SMALL BOTTOM HALF O;Lm;0;L; 1D17;;;;N;;;;; +1D56;MODIFIER LETTER SMALL P;Lm;0;L; 0070;;;;N;;;;; +1D57;MODIFIER LETTER SMALL T;Lm;0;L; 0074;;;;N;;;;; +1D58;MODIFIER LETTER SMALL U;Lm;0;L; 0075;;;;N;;;;; +1D59;MODIFIER LETTER SMALL SIDEWAYS U;Lm;0;L; 1D1D;;;;N;;;;; +1D5A;MODIFIER LETTER SMALL TURNED M;Lm;0;L; 026F;;;;N;;;;; +1D5B;MODIFIER LETTER SMALL V;Lm;0;L; 0076;;;;N;;;;; +1D5C;MODIFIER LETTER SMALL AIN;Lm;0;L; 1D25;;;;N;;;;; +1D5D;MODIFIER LETTER SMALL BETA;Lm;0;L; 03B2;;;;N;;;;; +1D5E;MODIFIER LETTER SMALL GREEK GAMMA;Lm;0;L; 03B3;;;;N;;;;; +1D5F;MODIFIER LETTER SMALL DELTA;Lm;0;L; 03B4;;;;N;;;;; +1D60;MODIFIER LETTER SMALL GREEK PHI;Lm;0;L; 03C6;;;;N;;;;; +1D61;MODIFIER LETTER SMALL CHI;Lm;0;L; 03C7;;;;N;;;;; +1D62;LATIN SUBSCRIPT SMALL LETTER I;Lm;0;L; 0069;;;;N;;;;; +1D63;LATIN SUBSCRIPT SMALL LETTER R;Lm;0;L; 0072;;;;N;;;;; +1D64;LATIN SUBSCRIPT SMALL LETTER U;Lm;0;L; 0075;;;;N;;;;; +1D65;LATIN SUBSCRIPT SMALL LETTER V;Lm;0;L; 0076;;;;N;;;;; +1D66;GREEK SUBSCRIPT SMALL LETTER BETA;Lm;0;L; 03B2;;;;N;;;;; +1D67;GREEK SUBSCRIPT SMALL LETTER GAMMA;Lm;0;L; 03B3;;;;N;;;;; +1D68;GREEK SUBSCRIPT SMALL LETTER RHO;Lm;0;L; 03C1;;;;N;;;;; +1D69;GREEK SUBSCRIPT SMALL LETTER PHI;Lm;0;L; 03C6;;;;N;;;;; +1D6A;GREEK SUBSCRIPT SMALL LETTER CHI;Lm;0;L; 03C7;;;;N;;;;; +1D6B;LATIN SMALL LETTER UE;Ll;0;L;;;;;N;;;;; +1D6C;LATIN SMALL LETTER B WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D6D;LATIN SMALL LETTER D WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D6E;LATIN SMALL LETTER F WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D6F;LATIN SMALL LETTER M WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D70;LATIN SMALL LETTER N WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D71;LATIN SMALL LETTER P WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D72;LATIN SMALL LETTER R WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D73;LATIN SMALL LETTER R WITH FISHHOOK AND MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D74;LATIN SMALL LETTER S WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D75;LATIN SMALL LETTER T WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D76;LATIN SMALL LETTER Z WITH MIDDLE TILDE;Ll;0;L;;;;;N;;;;; +1D77;LATIN SMALL LETTER TURNED G;Ll;0;L;;;;;N;;;;; +1D78;MODIFIER LETTER CYRILLIC EN;Lm;0;L; 043D;;;;N;;;;; +1D79;LATIN SMALL LETTER INSULAR G;Ll;0;L;;;;;N;;;A77D;;A77D +1D7A;LATIN SMALL LETTER TH WITH STRIKETHROUGH;Ll;0;L;;;;;N;;;;; +1D7B;LATIN SMALL CAPITAL LETTER I WITH STROKE;Ll;0;L;;;;;N;;;;; +1D7C;LATIN SMALL LETTER IOTA WITH STROKE;Ll;0;L;;;;;N;;;;; +1D7D;LATIN SMALL LETTER P WITH STROKE;Ll;0;L;;;;;N;;;2C63;;2C63 +1D7E;LATIN SMALL CAPITAL LETTER U WITH STROKE;Ll;0;L;;;;;N;;;;; +1D7F;LATIN SMALL LETTER UPSILON WITH STROKE;Ll;0;L;;;;;N;;;;; +1D80;LATIN SMALL LETTER B WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D81;LATIN SMALL LETTER D WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D82;LATIN SMALL LETTER F WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D83;LATIN SMALL LETTER G WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D84;LATIN SMALL LETTER K WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D85;LATIN SMALL LETTER L WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D86;LATIN SMALL LETTER M WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D87;LATIN SMALL LETTER N WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D88;LATIN SMALL LETTER P WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D89;LATIN SMALL LETTER R WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D8A;LATIN SMALL LETTER S WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D8B;LATIN SMALL LETTER ESH WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D8C;LATIN SMALL LETTER V WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D8D;LATIN SMALL LETTER X WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D8E;LATIN SMALL LETTER Z WITH PALATAL HOOK;Ll;0;L;;;;;N;;;;; +1D8F;LATIN SMALL LETTER A WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D90;LATIN SMALL LETTER ALPHA WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D91;LATIN SMALL LETTER D WITH HOOK AND TAIL;Ll;0;L;;;;;N;;;;; +1D92;LATIN SMALL LETTER E WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D93;LATIN SMALL LETTER OPEN E WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D94;LATIN SMALL LETTER REVERSED OPEN E WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D95;LATIN SMALL LETTER SCHWA WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D96;LATIN SMALL LETTER I WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D97;LATIN SMALL LETTER OPEN O WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D98;LATIN SMALL LETTER ESH WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D99;LATIN SMALL LETTER U WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D9A;LATIN SMALL LETTER EZH WITH RETROFLEX HOOK;Ll;0;L;;;;;N;;;;; +1D9B;MODIFIER LETTER SMALL TURNED ALPHA;Lm;0;L; 0252;;;;N;;;;; +1D9C;MODIFIER LETTER SMALL C;Lm;0;L; 0063;;;;N;;;;; +1D9D;MODIFIER LETTER SMALL C WITH CURL;Lm;0;L; 0255;;;;N;;;;; +1D9E;MODIFIER LETTER SMALL ETH;Lm;0;L; 00F0;;;;N;;;;; +1D9F;MODIFIER LETTER SMALL REVERSED OPEN E;Lm;0;L; 025C;;;;N;;;;; +1DA0;MODIFIER LETTER SMALL F;Lm;0;L; 0066;;;;N;;;;; +1DA1;MODIFIER LETTER SMALL DOTLESS J WITH STROKE;Lm;0;L; 025F;;;;N;;;;; +1DA2;MODIFIER LETTER SMALL SCRIPT G;Lm;0;L; 0261;;;;N;;;;; +1DA3;MODIFIER LETTER SMALL TURNED H;Lm;0;L; 0265;;;;N;;;;; +1DA4;MODIFIER LETTER SMALL I WITH STROKE;Lm;0;L; 0268;;;;N;;;;; +1DA5;MODIFIER LETTER SMALL IOTA;Lm;0;L; 0269;;;;N;;;;; +1DA6;MODIFIER LETTER SMALL CAPITAL I;Lm;0;L; 026A;;;;N;;;;; +1DA7;MODIFIER LETTER SMALL CAPITAL I WITH STROKE;Lm;0;L; 1D7B;;;;N;;;;; +1DA8;MODIFIER LETTER SMALL J WITH CROSSED-TAIL;Lm;0;L; 029D;;;;N;;;;; +1DA9;MODIFIER LETTER SMALL L WITH RETROFLEX HOOK;Lm;0;L; 026D;;;;N;;;;; +1DAA;MODIFIER LETTER SMALL L WITH PALATAL HOOK;Lm;0;L; 1D85;;;;N;;;;; +1DAB;MODIFIER LETTER SMALL CAPITAL L;Lm;0;L; 029F;;;;N;;;;; +1DAC;MODIFIER LETTER SMALL M WITH HOOK;Lm;0;L; 0271;;;;N;;;;; +1DAD;MODIFIER LETTER SMALL TURNED M WITH LONG LEG;Lm;0;L; 0270;;;;N;;;;; +1DAE;MODIFIER LETTER SMALL N WITH LEFT HOOK;Lm;0;L; 0272;;;;N;;;;; +1DAF;MODIFIER LETTER SMALL N WITH RETROFLEX HOOK;Lm;0;L; 0273;;;;N;;;;; +1DB0;MODIFIER LETTER SMALL CAPITAL N;Lm;0;L; 0274;;;;N;;;;; +1DB1;MODIFIER LETTER SMALL BARRED O;Lm;0;L; 0275;;;;N;;;;; +1DB2;MODIFIER LETTER SMALL PHI;Lm;0;L; 0278;;;;N;;;;; +1DB3;MODIFIER LETTER SMALL S WITH HOOK;Lm;0;L; 0282;;;;N;;;;; +1DB4;MODIFIER LETTER SMALL ESH;Lm;0;L; 0283;;;;N;;;;; +1DB5;MODIFIER LETTER SMALL T WITH PALATAL HOOK;Lm;0;L; 01AB;;;;N;;;;; +1DB6;MODIFIER LETTER SMALL U BAR;Lm;0;L; 0289;;;;N;;;;; +1DB7;MODIFIER LETTER SMALL UPSILON;Lm;0;L; 028A;;;;N;;;;; +1DB8;MODIFIER LETTER SMALL CAPITAL U;Lm;0;L; 1D1C;;;;N;;;;; +1DB9;MODIFIER LETTER SMALL V WITH HOOK;Lm;0;L; 028B;;;;N;;;;; +1DBA;MODIFIER LETTER SMALL TURNED V;Lm;0;L; 028C;;;;N;;;;; +1DBB;MODIFIER LETTER SMALL Z;Lm;0;L; 007A;;;;N;;;;; +1DBC;MODIFIER LETTER SMALL Z WITH RETROFLEX HOOK;Lm;0;L; 0290;;;;N;;;;; +1DBD;MODIFIER LETTER SMALL Z WITH CURL;Lm;0;L; 0291;;;;N;;;;; +1DBE;MODIFIER LETTER SMALL EZH;Lm;0;L; 0292;;;;N;;;;; +1DBF;MODIFIER LETTER SMALL THETA;Lm;0;L; 03B8;;;;N;;;;; +1DC0;COMBINING DOTTED GRAVE ACCENT;Mn;230;NSM;;;;;N;;;;; +1DC1;COMBINING DOTTED ACUTE ACCENT;Mn;230;NSM;;;;;N;;;;; +1DC2;COMBINING SNAKE BELOW;Mn;220;NSM;;;;;N;;;;; +1DC3;COMBINING SUSPENSION MARK;Mn;230;NSM;;;;;N;;;;; +1DC4;COMBINING MACRON-ACUTE;Mn;230;NSM;;;;;N;;;;; +1DC5;COMBINING GRAVE-MACRON;Mn;230;NSM;;;;;N;;;;; +1DC6;COMBINING MACRON-GRAVE;Mn;230;NSM;;;;;N;;;;; +1DC7;COMBINING ACUTE-MACRON;Mn;230;NSM;;;;;N;;;;; +1DC8;COMBINING GRAVE-ACUTE-GRAVE;Mn;230;NSM;;;;;N;;;;; +1DC9;COMBINING ACUTE-GRAVE-ACUTE;Mn;230;NSM;;;;;N;;;;; +1DCA;COMBINING LATIN SMALL LETTER R BELOW;Mn;220;NSM;;;;;N;;;;; +1DCB;COMBINING BREVE-MACRON;Mn;230;NSM;;;;;N;;;;; +1DCC;COMBINING MACRON-BREVE;Mn;230;NSM;;;;;N;;;;; +1DCD;COMBINING DOUBLE CIRCUMFLEX ABOVE;Mn;234;NSM;;;;;N;;;;; +1DCE;COMBINING OGONEK ABOVE;Mn;214;NSM;;;;;N;;;;; +1DCF;COMBINING ZIGZAG BELOW;Mn;220;NSM;;;;;N;;;;; +1DD0;COMBINING IS BELOW;Mn;202;NSM;;;;;N;;;;; +1DD1;COMBINING UR ABOVE;Mn;230;NSM;;;;;N;;;;; +1DD2;COMBINING US ABOVE;Mn;230;NSM;;;;;N;;;;; +1DD3;COMBINING LATIN SMALL LETTER FLATTENED OPEN A ABOVE;Mn;230;NSM;;;;;N;;;;; +1DD4;COMBINING LATIN SMALL LETTER AE;Mn;230;NSM;;;;;N;;;;; +1DD5;COMBINING LATIN SMALL LETTER AO;Mn;230;NSM;;;;;N;;;;; +1DD6;COMBINING LATIN SMALL LETTER AV;Mn;230;NSM;;;;;N;;;;; +1DD7;COMBINING LATIN SMALL LETTER C CEDILLA;Mn;230;NSM;;;;;N;;;;; +1DD8;COMBINING LATIN SMALL LETTER INSULAR D;Mn;230;NSM;;;;;N;;;;; +1DD9;COMBINING LATIN SMALL LETTER ETH;Mn;230;NSM;;;;;N;;;;; +1DDA;COMBINING LATIN SMALL LETTER G;Mn;230;NSM;;;;;N;;;;; +1DDB;COMBINING LATIN LETTER SMALL CAPITAL G;Mn;230;NSM;;;;;N;;;;; +1DDC;COMBINING LATIN SMALL LETTER K;Mn;230;NSM;;;;;N;;;;; +1DDD;COMBINING LATIN SMALL LETTER L;Mn;230;NSM;;;;;N;;;;; +1DDE;COMBINING LATIN LETTER SMALL CAPITAL L;Mn;230;NSM;;;;;N;;;;; +1DDF;COMBINING LATIN LETTER SMALL CAPITAL M;Mn;230;NSM;;;;;N;;;;; +1DE0;COMBINING LATIN SMALL LETTER N;Mn;230;NSM;;;;;N;;;;; +1DE1;COMBINING LATIN LETTER SMALL CAPITAL N;Mn;230;NSM;;;;;N;;;;; +1DE2;COMBINING LATIN LETTER SMALL CAPITAL R;Mn;230;NSM;;;;;N;;;;; +1DE3;COMBINING LATIN SMALL LETTER R ROTUNDA;Mn;230;NSM;;;;;N;;;;; +1DE4;COMBINING LATIN SMALL LETTER S;Mn;230;NSM;;;;;N;;;;; +1DE5;COMBINING LATIN SMALL LETTER LONG S;Mn;230;NSM;;;;;N;;;;; +1DE6;COMBINING LATIN SMALL LETTER Z;Mn;230;NSM;;;;;N;;;;; +1DFC;COMBINING DOUBLE INVERTED BREVE BELOW;Mn;233;NSM;;;;;N;;;;; +1DFD;COMBINING ALMOST EQUAL TO BELOW;Mn;220;NSM;;;;;N;;;;; +1DFE;COMBINING LEFT ARROWHEAD ABOVE;Mn;230;NSM;;;;;N;;;;; +1DFF;COMBINING RIGHT ARROWHEAD AND DOWN ARROWHEAD BELOW;Mn;220;NSM;;;;;N;;;;; +1E00;LATIN CAPITAL LETTER A WITH RING BELOW;Lu;0;L;0041 0325;;;;N;;;;1E01; +1E01;LATIN SMALL LETTER A WITH RING BELOW;Ll;0;L;0061 0325;;;;N;;;1E00;;1E00 +1E02;LATIN CAPITAL LETTER B WITH DOT ABOVE;Lu;0;L;0042 0307;;;;N;;;;1E03; +1E03;LATIN SMALL LETTER B WITH DOT ABOVE;Ll;0;L;0062 0307;;;;N;;;1E02;;1E02 +1E04;LATIN CAPITAL LETTER B WITH DOT BELOW;Lu;0;L;0042 0323;;;;N;;;;1E05; +1E05;LATIN SMALL LETTER B WITH DOT BELOW;Ll;0;L;0062 0323;;;;N;;;1E04;;1E04 +1E06;LATIN CAPITAL LETTER B WITH LINE BELOW;Lu;0;L;0042 0331;;;;N;;;;1E07; +1E07;LATIN SMALL LETTER B WITH LINE BELOW;Ll;0;L;0062 0331;;;;N;;;1E06;;1E06 +1E08;LATIN CAPITAL LETTER C WITH CEDILLA AND ACUTE;Lu;0;L;00C7 0301;;;;N;;;;1E09; +1E09;LATIN SMALL LETTER C WITH CEDILLA AND ACUTE;Ll;0;L;00E7 0301;;;;N;;;1E08;;1E08 +1E0A;LATIN CAPITAL LETTER D WITH DOT ABOVE;Lu;0;L;0044 0307;;;;N;;;;1E0B; +1E0B;LATIN SMALL LETTER D WITH DOT ABOVE;Ll;0;L;0064 0307;;;;N;;;1E0A;;1E0A +1E0C;LATIN CAPITAL LETTER D WITH DOT BELOW;Lu;0;L;0044 0323;;;;N;;;;1E0D; +1E0D;LATIN SMALL LETTER D WITH DOT BELOW;Ll;0;L;0064 0323;;;;N;;;1E0C;;1E0C +1E0E;LATIN CAPITAL LETTER D WITH LINE BELOW;Lu;0;L;0044 0331;;;;N;;;;1E0F; +1E0F;LATIN SMALL LETTER D WITH LINE BELOW;Ll;0;L;0064 0331;;;;N;;;1E0E;;1E0E +1E10;LATIN CAPITAL LETTER D WITH CEDILLA;Lu;0;L;0044 0327;;;;N;;;;1E11; +1E11;LATIN SMALL LETTER D WITH CEDILLA;Ll;0;L;0064 0327;;;;N;;;1E10;;1E10 +1E12;LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW;Lu;0;L;0044 032D;;;;N;;;;1E13; +1E13;LATIN SMALL LETTER D WITH CIRCUMFLEX BELOW;Ll;0;L;0064 032D;;;;N;;;1E12;;1E12 +1E14;LATIN CAPITAL LETTER E WITH MACRON AND GRAVE;Lu;0;L;0112 0300;;;;N;;;;1E15; +1E15;LATIN SMALL LETTER E WITH MACRON AND GRAVE;Ll;0;L;0113 0300;;;;N;;;1E14;;1E14 +1E16;LATIN CAPITAL LETTER E WITH MACRON AND ACUTE;Lu;0;L;0112 0301;;;;N;;;;1E17; +1E17;LATIN SMALL LETTER E WITH MACRON AND ACUTE;Ll;0;L;0113 0301;;;;N;;;1E16;;1E16 +1E18;LATIN CAPITAL LETTER E WITH CIRCUMFLEX BELOW;Lu;0;L;0045 032D;;;;N;;;;1E19; +1E19;LATIN SMALL LETTER E WITH CIRCUMFLEX BELOW;Ll;0;L;0065 032D;;;;N;;;1E18;;1E18 +1E1A;LATIN CAPITAL LETTER E WITH TILDE BELOW;Lu;0;L;0045 0330;;;;N;;;;1E1B; +1E1B;LATIN SMALL LETTER E WITH TILDE BELOW;Ll;0;L;0065 0330;;;;N;;;1E1A;;1E1A +1E1C;LATIN CAPITAL LETTER E WITH CEDILLA AND BREVE;Lu;0;L;0228 0306;;;;N;;;;1E1D; +1E1D;LATIN SMALL LETTER E WITH CEDILLA AND BREVE;Ll;0;L;0229 0306;;;;N;;;1E1C;;1E1C +1E1E;LATIN CAPITAL LETTER F WITH DOT ABOVE;Lu;0;L;0046 0307;;;;N;;;;1E1F; +1E1F;LATIN SMALL LETTER F WITH DOT ABOVE;Ll;0;L;0066 0307;;;;N;;;1E1E;;1E1E +1E20;LATIN CAPITAL LETTER G WITH MACRON;Lu;0;L;0047 0304;;;;N;;;;1E21; +1E21;LATIN SMALL LETTER G WITH MACRON;Ll;0;L;0067 0304;;;;N;;;1E20;;1E20 +1E22;LATIN CAPITAL LETTER H WITH DOT ABOVE;Lu;0;L;0048 0307;;;;N;;;;1E23; +1E23;LATIN SMALL LETTER H WITH DOT ABOVE;Ll;0;L;0068 0307;;;;N;;;1E22;;1E22 +1E24;LATIN CAPITAL LETTER H WITH DOT BELOW;Lu;0;L;0048 0323;;;;N;;;;1E25; +1E25;LATIN SMALL LETTER H WITH DOT BELOW;Ll;0;L;0068 0323;;;;N;;;1E24;;1E24 +1E26;LATIN CAPITAL LETTER H WITH DIAERESIS;Lu;0;L;0048 0308;;;;N;;;;1E27; +1E27;LATIN SMALL LETTER H WITH DIAERESIS;Ll;0;L;0068 0308;;;;N;;;1E26;;1E26 +1E28;LATIN CAPITAL LETTER H WITH CEDILLA;Lu;0;L;0048 0327;;;;N;;;;1E29; +1E29;LATIN SMALL LETTER H WITH CEDILLA;Ll;0;L;0068 0327;;;;N;;;1E28;;1E28 +1E2A;LATIN CAPITAL LETTER H WITH BREVE BELOW;Lu;0;L;0048 032E;;;;N;;;;1E2B; +1E2B;LATIN SMALL LETTER H WITH BREVE BELOW;Ll;0;L;0068 032E;;;;N;;;1E2A;;1E2A +1E2C;LATIN CAPITAL LETTER I WITH TILDE BELOW;Lu;0;L;0049 0330;;;;N;;;;1E2D; +1E2D;LATIN SMALL LETTER I WITH TILDE BELOW;Ll;0;L;0069 0330;;;;N;;;1E2C;;1E2C +1E2E;LATIN CAPITAL LETTER I WITH DIAERESIS AND ACUTE;Lu;0;L;00CF 0301;;;;N;;;;1E2F; +1E2F;LATIN SMALL LETTER I WITH DIAERESIS AND ACUTE;Ll;0;L;00EF 0301;;;;N;;;1E2E;;1E2E +1E30;LATIN CAPITAL LETTER K WITH ACUTE;Lu;0;L;004B 0301;;;;N;;;;1E31; +1E31;LATIN SMALL LETTER K WITH ACUTE;Ll;0;L;006B 0301;;;;N;;;1E30;;1E30 +1E32;LATIN CAPITAL LETTER K WITH DOT BELOW;Lu;0;L;004B 0323;;;;N;;;;1E33; +1E33;LATIN SMALL LETTER K WITH DOT BELOW;Ll;0;L;006B 0323;;;;N;;;1E32;;1E32 +1E34;LATIN CAPITAL LETTER K WITH LINE BELOW;Lu;0;L;004B 0331;;;;N;;;;1E35; +1E35;LATIN SMALL LETTER K WITH LINE BELOW;Ll;0;L;006B 0331;;;;N;;;1E34;;1E34 +1E36;LATIN CAPITAL LETTER L WITH DOT BELOW;Lu;0;L;004C 0323;;;;N;;;;1E37; +1E37;LATIN SMALL LETTER L WITH DOT BELOW;Ll;0;L;006C 0323;;;;N;;;1E36;;1E36 +1E38;LATIN CAPITAL LETTER L WITH DOT BELOW AND MACRON;Lu;0;L;1E36 0304;;;;N;;;;1E39; +1E39;LATIN SMALL LETTER L WITH DOT BELOW AND MACRON;Ll;0;L;1E37 0304;;;;N;;;1E38;;1E38 +1E3A;LATIN CAPITAL LETTER L WITH LINE BELOW;Lu;0;L;004C 0331;;;;N;;;;1E3B; +1E3B;LATIN SMALL LETTER L WITH LINE BELOW;Ll;0;L;006C 0331;;;;N;;;1E3A;;1E3A +1E3C;LATIN CAPITAL LETTER L WITH CIRCUMFLEX BELOW;Lu;0;L;004C 032D;;;;N;;;;1E3D; +1E3D;LATIN SMALL LETTER L WITH CIRCUMFLEX BELOW;Ll;0;L;006C 032D;;;;N;;;1E3C;;1E3C +1E3E;LATIN CAPITAL LETTER M WITH ACUTE;Lu;0;L;004D 0301;;;;N;;;;1E3F; +1E3F;LATIN SMALL LETTER M WITH ACUTE;Ll;0;L;006D 0301;;;;N;;;1E3E;;1E3E +1E40;LATIN CAPITAL LETTER M WITH DOT ABOVE;Lu;0;L;004D 0307;;;;N;;;;1E41; +1E41;LATIN SMALL LETTER M WITH DOT ABOVE;Ll;0;L;006D 0307;;;;N;;;1E40;;1E40 +1E42;LATIN CAPITAL LETTER M WITH DOT BELOW;Lu;0;L;004D 0323;;;;N;;;;1E43; +1E43;LATIN SMALL LETTER M WITH DOT BELOW;Ll;0;L;006D 0323;;;;N;;;1E42;;1E42 +1E44;LATIN CAPITAL LETTER N WITH DOT ABOVE;Lu;0;L;004E 0307;;;;N;;;;1E45; +1E45;LATIN SMALL LETTER N WITH DOT ABOVE;Ll;0;L;006E 0307;;;;N;;;1E44;;1E44 +1E46;LATIN CAPITAL LETTER N WITH DOT BELOW;Lu;0;L;004E 0323;;;;N;;;;1E47; +1E47;LATIN SMALL LETTER N WITH DOT BELOW;Ll;0;L;006E 0323;;;;N;;;1E46;;1E46 +1E48;LATIN CAPITAL LETTER N WITH LINE BELOW;Lu;0;L;004E 0331;;;;N;;;;1E49; +1E49;LATIN SMALL LETTER N WITH LINE BELOW;Ll;0;L;006E 0331;;;;N;;;1E48;;1E48 +1E4A;LATIN CAPITAL LETTER N WITH CIRCUMFLEX BELOW;Lu;0;L;004E 032D;;;;N;;;;1E4B; +1E4B;LATIN SMALL LETTER N WITH CIRCUMFLEX BELOW;Ll;0;L;006E 032D;;;;N;;;1E4A;;1E4A +1E4C;LATIN CAPITAL LETTER O WITH TILDE AND ACUTE;Lu;0;L;00D5 0301;;;;N;;;;1E4D; +1E4D;LATIN SMALL LETTER O WITH TILDE AND ACUTE;Ll;0;L;00F5 0301;;;;N;;;1E4C;;1E4C +1E4E;LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS;Lu;0;L;00D5 0308;;;;N;;;;1E4F; +1E4F;LATIN SMALL LETTER O WITH TILDE AND DIAERESIS;Ll;0;L;00F5 0308;;;;N;;;1E4E;;1E4E +1E50;LATIN CAPITAL LETTER O WITH MACRON AND GRAVE;Lu;0;L;014C 0300;;;;N;;;;1E51; +1E51;LATIN SMALL LETTER O WITH MACRON AND GRAVE;Ll;0;L;014D 0300;;;;N;;;1E50;;1E50 +1E52;LATIN CAPITAL LETTER O WITH MACRON AND ACUTE;Lu;0;L;014C 0301;;;;N;;;;1E53; +1E53;LATIN SMALL LETTER O WITH MACRON AND ACUTE;Ll;0;L;014D 0301;;;;N;;;1E52;;1E52 +1E54;LATIN CAPITAL LETTER P WITH ACUTE;Lu;0;L;0050 0301;;;;N;;;;1E55; +1E55;LATIN SMALL LETTER P WITH ACUTE;Ll;0;L;0070 0301;;;;N;;;1E54;;1E54 +1E56;LATIN CAPITAL LETTER P WITH DOT ABOVE;Lu;0;L;0050 0307;;;;N;;;;1E57; +1E57;LATIN SMALL LETTER P WITH DOT ABOVE;Ll;0;L;0070 0307;;;;N;;;1E56;;1E56 +1E58;LATIN CAPITAL LETTER R WITH DOT ABOVE;Lu;0;L;0052 0307;;;;N;;;;1E59; +1E59;LATIN SMALL LETTER R WITH DOT ABOVE;Ll;0;L;0072 0307;;;;N;;;1E58;;1E58 +1E5A;LATIN CAPITAL LETTER R WITH DOT BELOW;Lu;0;L;0052 0323;;;;N;;;;1E5B; +1E5B;LATIN SMALL LETTER R WITH DOT BELOW;Ll;0;L;0072 0323;;;;N;;;1E5A;;1E5A +1E5C;LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON;Lu;0;L;1E5A 0304;;;;N;;;;1E5D; +1E5D;LATIN SMALL LETTER R WITH DOT BELOW AND MACRON;Ll;0;L;1E5B 0304;;;;N;;;1E5C;;1E5C +1E5E;LATIN CAPITAL LETTER R WITH LINE BELOW;Lu;0;L;0052 0331;;;;N;;;;1E5F; +1E5F;LATIN SMALL LETTER R WITH LINE BELOW;Ll;0;L;0072 0331;;;;N;;;1E5E;;1E5E +1E60;LATIN CAPITAL LETTER S WITH DOT ABOVE;Lu;0;L;0053 0307;;;;N;;;;1E61; +1E61;LATIN SMALL LETTER S WITH DOT ABOVE;Ll;0;L;0073 0307;;;;N;;;1E60;;1E60 +1E62;LATIN CAPITAL LETTER S WITH DOT BELOW;Lu;0;L;0053 0323;;;;N;;;;1E63; +1E63;LATIN SMALL LETTER S WITH DOT BELOW;Ll;0;L;0073 0323;;;;N;;;1E62;;1E62 +1E64;LATIN CAPITAL LETTER S WITH ACUTE AND DOT ABOVE;Lu;0;L;015A 0307;;;;N;;;;1E65; +1E65;LATIN SMALL LETTER S WITH ACUTE AND DOT ABOVE;Ll;0;L;015B 0307;;;;N;;;1E64;;1E64 +1E66;LATIN CAPITAL LETTER S WITH CARON AND DOT ABOVE;Lu;0;L;0160 0307;;;;N;;;;1E67; +1E67;LATIN SMALL LETTER S WITH CARON AND DOT ABOVE;Ll;0;L;0161 0307;;;;N;;;1E66;;1E66 +1E68;LATIN CAPITAL LETTER S WITH DOT BELOW AND DOT ABOVE;Lu;0;L;1E62 0307;;;;N;;;;1E69; +1E69;LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE;Ll;0;L;1E63 0307;;;;N;;;1E68;;1E68 +1E6A;LATIN CAPITAL LETTER T WITH DOT ABOVE;Lu;0;L;0054 0307;;;;N;;;;1E6B; +1E6B;LATIN SMALL LETTER T WITH DOT ABOVE;Ll;0;L;0074 0307;;;;N;;;1E6A;;1E6A +1E6C;LATIN CAPITAL LETTER T WITH DOT BELOW;Lu;0;L;0054 0323;;;;N;;;;1E6D; +1E6D;LATIN SMALL LETTER T WITH DOT BELOW;Ll;0;L;0074 0323;;;;N;;;1E6C;;1E6C +1E6E;LATIN CAPITAL LETTER T WITH LINE BELOW;Lu;0;L;0054 0331;;;;N;;;;1E6F; +1E6F;LATIN SMALL LETTER T WITH LINE BELOW;Ll;0;L;0074 0331;;;;N;;;1E6E;;1E6E +1E70;LATIN CAPITAL LETTER T WITH CIRCUMFLEX BELOW;Lu;0;L;0054 032D;;;;N;;;;1E71; +1E71;LATIN SMALL LETTER T WITH CIRCUMFLEX BELOW;Ll;0;L;0074 032D;;;;N;;;1E70;;1E70 +1E72;LATIN CAPITAL LETTER U WITH DIAERESIS BELOW;Lu;0;L;0055 0324;;;;N;;;;1E73; +1E73;LATIN SMALL LETTER U WITH DIAERESIS BELOW;Ll;0;L;0075 0324;;;;N;;;1E72;;1E72 +1E74;LATIN CAPITAL LETTER U WITH TILDE BELOW;Lu;0;L;0055 0330;;;;N;;;;1E75; +1E75;LATIN SMALL LETTER U WITH TILDE BELOW;Ll;0;L;0075 0330;;;;N;;;1E74;;1E74 +1E76;LATIN CAPITAL LETTER U WITH CIRCUMFLEX BELOW;Lu;0;L;0055 032D;;;;N;;;;1E77; +1E77;LATIN SMALL LETTER U WITH CIRCUMFLEX BELOW;Ll;0;L;0075 032D;;;;N;;;1E76;;1E76 +1E78;LATIN CAPITAL LETTER U WITH TILDE AND ACUTE;Lu;0;L;0168 0301;;;;N;;;;1E79; +1E79;LATIN SMALL LETTER U WITH TILDE AND ACUTE;Ll;0;L;0169 0301;;;;N;;;1E78;;1E78 +1E7A;LATIN CAPITAL LETTER U WITH MACRON AND DIAERESIS;Lu;0;L;016A 0308;;;;N;;;;1E7B; +1E7B;LATIN SMALL LETTER U WITH MACRON AND DIAERESIS;Ll;0;L;016B 0308;;;;N;;;1E7A;;1E7A +1E7C;LATIN CAPITAL LETTER V WITH TILDE;Lu;0;L;0056 0303;;;;N;;;;1E7D; +1E7D;LATIN SMALL LETTER V WITH TILDE;Ll;0;L;0076 0303;;;;N;;;1E7C;;1E7C +1E7E;LATIN CAPITAL LETTER V WITH DOT BELOW;Lu;0;L;0056 0323;;;;N;;;;1E7F; +1E7F;LATIN SMALL LETTER V WITH DOT BELOW;Ll;0;L;0076 0323;;;;N;;;1E7E;;1E7E +1E80;LATIN CAPITAL LETTER W WITH GRAVE;Lu;0;L;0057 0300;;;;N;;;;1E81; +1E81;LATIN SMALL LETTER W WITH GRAVE;Ll;0;L;0077 0300;;;;N;;;1E80;;1E80 +1E82;LATIN CAPITAL LETTER W WITH ACUTE;Lu;0;L;0057 0301;;;;N;;;;1E83; +1E83;LATIN SMALL LETTER W WITH ACUTE;Ll;0;L;0077 0301;;;;N;;;1E82;;1E82 +1E84;LATIN CAPITAL LETTER W WITH DIAERESIS;Lu;0;L;0057 0308;;;;N;;;;1E85; +1E85;LATIN SMALL LETTER W WITH DIAERESIS;Ll;0;L;0077 0308;;;;N;;;1E84;;1E84 +1E86;LATIN CAPITAL LETTER W WITH DOT ABOVE;Lu;0;L;0057 0307;;;;N;;;;1E87; +1E87;LATIN SMALL LETTER W WITH DOT ABOVE;Ll;0;L;0077 0307;;;;N;;;1E86;;1E86 +1E88;LATIN CAPITAL LETTER W WITH DOT BELOW;Lu;0;L;0057 0323;;;;N;;;;1E89; +1E89;LATIN SMALL LETTER W WITH DOT BELOW;Ll;0;L;0077 0323;;;;N;;;1E88;;1E88 +1E8A;LATIN CAPITAL LETTER X WITH DOT ABOVE;Lu;0;L;0058 0307;;;;N;;;;1E8B; +1E8B;LATIN SMALL LETTER X WITH DOT ABOVE;Ll;0;L;0078 0307;;;;N;;;1E8A;;1E8A +1E8C;LATIN CAPITAL LETTER X WITH DIAERESIS;Lu;0;L;0058 0308;;;;N;;;;1E8D; +1E8D;LATIN SMALL LETTER X WITH DIAERESIS;Ll;0;L;0078 0308;;;;N;;;1E8C;;1E8C +1E8E;LATIN CAPITAL LETTER Y WITH DOT ABOVE;Lu;0;L;0059 0307;;;;N;;;;1E8F; +1E8F;LATIN SMALL LETTER Y WITH DOT ABOVE;Ll;0;L;0079 0307;;;;N;;;1E8E;;1E8E +1E90;LATIN CAPITAL LETTER Z WITH CIRCUMFLEX;Lu;0;L;005A 0302;;;;N;;;;1E91; +1E91;LATIN SMALL LETTER Z WITH CIRCUMFLEX;Ll;0;L;007A 0302;;;;N;;;1E90;;1E90 +1E92;LATIN CAPITAL LETTER Z WITH DOT BELOW;Lu;0;L;005A 0323;;;;N;;;;1E93; +1E93;LATIN SMALL LETTER Z WITH DOT BELOW;Ll;0;L;007A 0323;;;;N;;;1E92;;1E92 +1E94;LATIN CAPITAL LETTER Z WITH LINE BELOW;Lu;0;L;005A 0331;;;;N;;;;1E95; +1E95;LATIN SMALL LETTER Z WITH LINE BELOW;Ll;0;L;007A 0331;;;;N;;;1E94;;1E94 +1E96;LATIN SMALL LETTER H WITH LINE BELOW;Ll;0;L;0068 0331;;;;N;;;;; +1E97;LATIN SMALL LETTER T WITH DIAERESIS;Ll;0;L;0074 0308;;;;N;;;;; +1E98;LATIN SMALL LETTER W WITH RING ABOVE;Ll;0;L;0077 030A;;;;N;;;;; +1E99;LATIN SMALL LETTER Y WITH RING ABOVE;Ll;0;L;0079 030A;;;;N;;;;; +1E9A;LATIN SMALL LETTER A WITH RIGHT HALF RING;Ll;0;L; 0061 02BE;;;;N;;;;; +1E9B;LATIN SMALL LETTER LONG S WITH DOT ABOVE;Ll;0;L;017F 0307;;;;N;;;1E60;;1E60 +1E9C;LATIN SMALL LETTER LONG S WITH DIAGONAL STROKE;Ll;0;L;;;;;N;;;;; +1E9D;LATIN SMALL LETTER LONG S WITH HIGH STROKE;Ll;0;L;;;;;N;;;;; +1E9E;LATIN CAPITAL LETTER SHARP S;Lu;0;L;;;;;N;;;;00DF; +1E9F;LATIN SMALL LETTER DELTA;Ll;0;L;;;;;N;;;;; +1EA0;LATIN CAPITAL LETTER A WITH DOT BELOW;Lu;0;L;0041 0323;;;;N;;;;1EA1; +1EA1;LATIN SMALL LETTER A WITH DOT BELOW;Ll;0;L;0061 0323;;;;N;;;1EA0;;1EA0 +1EA2;LATIN CAPITAL LETTER A WITH HOOK ABOVE;Lu;0;L;0041 0309;;;;N;;;;1EA3; +1EA3;LATIN SMALL LETTER A WITH HOOK ABOVE;Ll;0;L;0061 0309;;;;N;;;1EA2;;1EA2 +1EA4;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE;Lu;0;L;00C2 0301;;;;N;;;;1EA5; +1EA5;LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE;Ll;0;L;00E2 0301;;;;N;;;1EA4;;1EA4 +1EA6;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE;Lu;0;L;00C2 0300;;;;N;;;;1EA7; +1EA7;LATIN SMALL LETTER A WITH CIRCUMFLEX AND GRAVE;Ll;0;L;00E2 0300;;;;N;;;1EA6;;1EA6 +1EA8;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE;Lu;0;L;00C2 0309;;;;N;;;;1EA9; +1EA9;LATIN SMALL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE;Ll;0;L;00E2 0309;;;;N;;;1EA8;;1EA8 +1EAA;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE;Lu;0;L;00C2 0303;;;;N;;;;1EAB; +1EAB;LATIN SMALL LETTER A WITH CIRCUMFLEX AND TILDE;Ll;0;L;00E2 0303;;;;N;;;1EAA;;1EAA +1EAC;LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW;Lu;0;L;1EA0 0302;;;;N;;;;1EAD; +1EAD;LATIN SMALL LETTER A WITH CIRCUMFLEX AND DOT BELOW;Ll;0;L;1EA1 0302;;;;N;;;1EAC;;1EAC +1EAE;LATIN CAPITAL LETTER A WITH BREVE AND ACUTE;Lu;0;L;0102 0301;;;;N;;;;1EAF; +1EAF;LATIN SMALL LETTER A WITH BREVE AND ACUTE;Ll;0;L;0103 0301;;;;N;;;1EAE;;1EAE +1EB0;LATIN CAPITAL LETTER A WITH BREVE AND GRAVE;Lu;0;L;0102 0300;;;;N;;;;1EB1; +1EB1;LATIN SMALL LETTER A WITH BREVE AND GRAVE;Ll;0;L;0103 0300;;;;N;;;1EB0;;1EB0 +1EB2;LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE;Lu;0;L;0102 0309;;;;N;;;;1EB3; +1EB3;LATIN SMALL LETTER A WITH BREVE AND HOOK ABOVE;Ll;0;L;0103 0309;;;;N;;;1EB2;;1EB2 +1EB4;LATIN CAPITAL LETTER A WITH BREVE AND TILDE;Lu;0;L;0102 0303;;;;N;;;;1EB5; +1EB5;LATIN SMALL LETTER A WITH BREVE AND TILDE;Ll;0;L;0103 0303;;;;N;;;1EB4;;1EB4 +1EB6;LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW;Lu;0;L;1EA0 0306;;;;N;;;;1EB7; +1EB7;LATIN SMALL LETTER A WITH BREVE AND DOT BELOW;Ll;0;L;1EA1 0306;;;;N;;;1EB6;;1EB6 +1EB8;LATIN CAPITAL LETTER E WITH DOT BELOW;Lu;0;L;0045 0323;;;;N;;;;1EB9; +1EB9;LATIN SMALL LETTER E WITH DOT BELOW;Ll;0;L;0065 0323;;;;N;;;1EB8;;1EB8 +1EBA;LATIN CAPITAL LETTER E WITH HOOK ABOVE;Lu;0;L;0045 0309;;;;N;;;;1EBB; +1EBB;LATIN SMALL LETTER E WITH HOOK ABOVE;Ll;0;L;0065 0309;;;;N;;;1EBA;;1EBA +1EBC;LATIN CAPITAL LETTER E WITH TILDE;Lu;0;L;0045 0303;;;;N;;;;1EBD; +1EBD;LATIN SMALL LETTER E WITH TILDE;Ll;0;L;0065 0303;;;;N;;;1EBC;;1EBC +1EBE;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE;Lu;0;L;00CA 0301;;;;N;;;;1EBF; +1EBF;LATIN SMALL LETTER E WITH CIRCUMFLEX AND ACUTE;Ll;0;L;00EA 0301;;;;N;;;1EBE;;1EBE +1EC0;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE;Lu;0;L;00CA 0300;;;;N;;;;1EC1; +1EC1;LATIN SMALL LETTER E WITH CIRCUMFLEX AND GRAVE;Ll;0;L;00EA 0300;;;;N;;;1EC0;;1EC0 +1EC2;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE;Lu;0;L;00CA 0309;;;;N;;;;1EC3; +1EC3;LATIN SMALL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE;Ll;0;L;00EA 0309;;;;N;;;1EC2;;1EC2 +1EC4;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE;Lu;0;L;00CA 0303;;;;N;;;;1EC5; +1EC5;LATIN SMALL LETTER E WITH CIRCUMFLEX AND TILDE;Ll;0;L;00EA 0303;;;;N;;;1EC4;;1EC4 +1EC6;LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW;Lu;0;L;1EB8 0302;;;;N;;;;1EC7; +1EC7;LATIN SMALL LETTER E WITH CIRCUMFLEX AND DOT BELOW;Ll;0;L;1EB9 0302;;;;N;;;1EC6;;1EC6 +1EC8;LATIN CAPITAL LETTER I WITH HOOK ABOVE;Lu;0;L;0049 0309;;;;N;;;;1EC9; +1EC9;LATIN SMALL LETTER I WITH HOOK ABOVE;Ll;0;L;0069 0309;;;;N;;;1EC8;;1EC8 +1ECA;LATIN CAPITAL LETTER I WITH DOT BELOW;Lu;0;L;0049 0323;;;;N;;;;1ECB; +1ECB;LATIN SMALL LETTER I WITH DOT BELOW;Ll;0;L;0069 0323;;;;N;;;1ECA;;1ECA +1ECC;LATIN CAPITAL LETTER O WITH DOT BELOW;Lu;0;L;004F 0323;;;;N;;;;1ECD; +1ECD;LATIN SMALL LETTER O WITH DOT BELOW;Ll;0;L;006F 0323;;;;N;;;1ECC;;1ECC +1ECE;LATIN CAPITAL LETTER O WITH HOOK ABOVE;Lu;0;L;004F 0309;;;;N;;;;1ECF; +1ECF;LATIN SMALL LETTER O WITH HOOK ABOVE;Ll;0;L;006F 0309;;;;N;;;1ECE;;1ECE +1ED0;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE;Lu;0;L;00D4 0301;;;;N;;;;1ED1; +1ED1;LATIN SMALL LETTER O WITH CIRCUMFLEX AND ACUTE;Ll;0;L;00F4 0301;;;;N;;;1ED0;;1ED0 +1ED2;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE;Lu;0;L;00D4 0300;;;;N;;;;1ED3; +1ED3;LATIN SMALL LETTER O WITH CIRCUMFLEX AND GRAVE;Ll;0;L;00F4 0300;;;;N;;;1ED2;;1ED2 +1ED4;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE;Lu;0;L;00D4 0309;;;;N;;;;1ED5; +1ED5;LATIN SMALL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE;Ll;0;L;00F4 0309;;;;N;;;1ED4;;1ED4 +1ED6;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE;Lu;0;L;00D4 0303;;;;N;;;;1ED7; +1ED7;LATIN SMALL LETTER O WITH CIRCUMFLEX AND TILDE;Ll;0;L;00F4 0303;;;;N;;;1ED6;;1ED6 +1ED8;LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW;Lu;0;L;1ECC 0302;;;;N;;;;1ED9; +1ED9;LATIN SMALL LETTER O WITH CIRCUMFLEX AND DOT BELOW;Ll;0;L;1ECD 0302;;;;N;;;1ED8;;1ED8 +1EDA;LATIN CAPITAL LETTER O WITH HORN AND ACUTE;Lu;0;L;01A0 0301;;;;N;;;;1EDB; +1EDB;LATIN SMALL LETTER O WITH HORN AND ACUTE;Ll;0;L;01A1 0301;;;;N;;;1EDA;;1EDA +1EDC;LATIN CAPITAL LETTER O WITH HORN AND GRAVE;Lu;0;L;01A0 0300;;;;N;;;;1EDD; +1EDD;LATIN SMALL LETTER O WITH HORN AND GRAVE;Ll;0;L;01A1 0300;;;;N;;;1EDC;;1EDC +1EDE;LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE;Lu;0;L;01A0 0309;;;;N;;;;1EDF; +1EDF;LATIN SMALL LETTER O WITH HORN AND HOOK ABOVE;Ll;0;L;01A1 0309;;;;N;;;1EDE;;1EDE +1EE0;LATIN CAPITAL LETTER O WITH HORN AND TILDE;Lu;0;L;01A0 0303;;;;N;;;;1EE1; +1EE1;LATIN SMALL LETTER O WITH HORN AND TILDE;Ll;0;L;01A1 0303;;;;N;;;1EE0;;1EE0 +1EE2;LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW;Lu;0;L;01A0 0323;;;;N;;;;1EE3; +1EE3;LATIN SMALL LETTER O WITH HORN AND DOT BELOW;Ll;0;L;01A1 0323;;;;N;;;1EE2;;1EE2 +1EE4;LATIN CAPITAL LETTER U WITH DOT BELOW;Lu;0;L;0055 0323;;;;N;;;;1EE5; +1EE5;LATIN SMALL LETTER U WITH DOT BELOW;Ll;0;L;0075 0323;;;;N;;;1EE4;;1EE4 +1EE6;LATIN CAPITAL LETTER U WITH HOOK ABOVE;Lu;0;L;0055 0309;;;;N;;;;1EE7; +1EE7;LATIN SMALL LETTER U WITH HOOK ABOVE;Ll;0;L;0075 0309;;;;N;;;1EE6;;1EE6 +1EE8;LATIN CAPITAL LETTER U WITH HORN AND ACUTE;Lu;0;L;01AF 0301;;;;N;;;;1EE9; +1EE9;LATIN SMALL LETTER U WITH HORN AND ACUTE;Ll;0;L;01B0 0301;;;;N;;;1EE8;;1EE8 +1EEA;LATIN CAPITAL LETTER U WITH HORN AND GRAVE;Lu;0;L;01AF 0300;;;;N;;;;1EEB; +1EEB;LATIN SMALL LETTER U WITH HORN AND GRAVE;Ll;0;L;01B0 0300;;;;N;;;1EEA;;1EEA +1EEC;LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE;Lu;0;L;01AF 0309;;;;N;;;;1EED; +1EED;LATIN SMALL LETTER U WITH HORN AND HOOK ABOVE;Ll;0;L;01B0 0309;;;;N;;;1EEC;;1EEC +1EEE;LATIN CAPITAL LETTER U WITH HORN AND TILDE;Lu;0;L;01AF 0303;;;;N;;;;1EEF; +1EEF;LATIN SMALL LETTER U WITH HORN AND TILDE;Ll;0;L;01B0 0303;;;;N;;;1EEE;;1EEE +1EF0;LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW;Lu;0;L;01AF 0323;;;;N;;;;1EF1; +1EF1;LATIN SMALL LETTER U WITH HORN AND DOT BELOW;Ll;0;L;01B0 0323;;;;N;;;1EF0;;1EF0 +1EF2;LATIN CAPITAL LETTER Y WITH GRAVE;Lu;0;L;0059 0300;;;;N;;;;1EF3; +1EF3;LATIN SMALL LETTER Y WITH GRAVE;Ll;0;L;0079 0300;;;;N;;;1EF2;;1EF2 +1EF4;LATIN CAPITAL LETTER Y WITH DOT BELOW;Lu;0;L;0059 0323;;;;N;;;;1EF5; +1EF5;LATIN SMALL LETTER Y WITH DOT BELOW;Ll;0;L;0079 0323;;;;N;;;1EF4;;1EF4 +1EF6;LATIN CAPITAL LETTER Y WITH HOOK ABOVE;Lu;0;L;0059 0309;;;;N;;;;1EF7; +1EF7;LATIN SMALL LETTER Y WITH HOOK ABOVE;Ll;0;L;0079 0309;;;;N;;;1EF6;;1EF6 +1EF8;LATIN CAPITAL LETTER Y WITH TILDE;Lu;0;L;0059 0303;;;;N;;;;1EF9; +1EF9;LATIN SMALL LETTER Y WITH TILDE;Ll;0;L;0079 0303;;;;N;;;1EF8;;1EF8 +1EFA;LATIN CAPITAL LETTER MIDDLE-WELSH LL;Lu;0;L;;;;;N;;;;1EFB; +1EFB;LATIN SMALL LETTER MIDDLE-WELSH LL;Ll;0;L;;;;;N;;;1EFA;;1EFA +1EFC;LATIN CAPITAL LETTER MIDDLE-WELSH V;Lu;0;L;;;;;N;;;;1EFD; +1EFD;LATIN SMALL LETTER MIDDLE-WELSH V;Ll;0;L;;;;;N;;;1EFC;;1EFC +1EFE;LATIN CAPITAL LETTER Y WITH LOOP;Lu;0;L;;;;;N;;;;1EFF; +1EFF;LATIN SMALL LETTER Y WITH LOOP;Ll;0;L;;;;;N;;;1EFE;;1EFE +1F00;GREEK SMALL LETTER ALPHA WITH PSILI;Ll;0;L;03B1 0313;;;;N;;;1F08;;1F08 +1F01;GREEK SMALL LETTER ALPHA WITH DASIA;Ll;0;L;03B1 0314;;;;N;;;1F09;;1F09 +1F02;GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA;Ll;0;L;1F00 0300;;;;N;;;1F0A;;1F0A +1F03;GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA;Ll;0;L;1F01 0300;;;;N;;;1F0B;;1F0B +1F04;GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA;Ll;0;L;1F00 0301;;;;N;;;1F0C;;1F0C +1F05;GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA;Ll;0;L;1F01 0301;;;;N;;;1F0D;;1F0D +1F06;GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI;Ll;0;L;1F00 0342;;;;N;;;1F0E;;1F0E +1F07;GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI;Ll;0;L;1F01 0342;;;;N;;;1F0F;;1F0F +1F08;GREEK CAPITAL LETTER ALPHA WITH PSILI;Lu;0;L;0391 0313;;;;N;;;;1F00; +1F09;GREEK CAPITAL LETTER ALPHA WITH DASIA;Lu;0;L;0391 0314;;;;N;;;;1F01; +1F0A;GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA;Lu;0;L;1F08 0300;;;;N;;;;1F02; +1F0B;GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA;Lu;0;L;1F09 0300;;;;N;;;;1F03; +1F0C;GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA;Lu;0;L;1F08 0301;;;;N;;;;1F04; +1F0D;GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA;Lu;0;L;1F09 0301;;;;N;;;;1F05; +1F0E;GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI;Lu;0;L;1F08 0342;;;;N;;;;1F06; +1F0F;GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI;Lu;0;L;1F09 0342;;;;N;;;;1F07; +1F10;GREEK SMALL LETTER EPSILON WITH PSILI;Ll;0;L;03B5 0313;;;;N;;;1F18;;1F18 +1F11;GREEK SMALL LETTER EPSILON WITH DASIA;Ll;0;L;03B5 0314;;;;N;;;1F19;;1F19 +1F12;GREEK SMALL LETTER EPSILON WITH PSILI AND VARIA;Ll;0;L;1F10 0300;;;;N;;;1F1A;;1F1A +1F13;GREEK SMALL LETTER EPSILON WITH DASIA AND VARIA;Ll;0;L;1F11 0300;;;;N;;;1F1B;;1F1B +1F14;GREEK SMALL LETTER EPSILON WITH PSILI AND OXIA;Ll;0;L;1F10 0301;;;;N;;;1F1C;;1F1C +1F15;GREEK SMALL LETTER EPSILON WITH DASIA AND OXIA;Ll;0;L;1F11 0301;;;;N;;;1F1D;;1F1D +1F18;GREEK CAPITAL LETTER EPSILON WITH PSILI;Lu;0;L;0395 0313;;;;N;;;;1F10; +1F19;GREEK CAPITAL LETTER EPSILON WITH DASIA;Lu;0;L;0395 0314;;;;N;;;;1F11; +1F1A;GREEK CAPITAL LETTER EPSILON WITH PSILI AND VARIA;Lu;0;L;1F18 0300;;;;N;;;;1F12; +1F1B;GREEK CAPITAL LETTER EPSILON WITH DASIA AND VARIA;Lu;0;L;1F19 0300;;;;N;;;;1F13; +1F1C;GREEK CAPITAL LETTER EPSILON WITH PSILI AND OXIA;Lu;0;L;1F18 0301;;;;N;;;;1F14; +1F1D;GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA;Lu;0;L;1F19 0301;;;;N;;;;1F15; +1F20;GREEK SMALL LETTER ETA WITH PSILI;Ll;0;L;03B7 0313;;;;N;;;1F28;;1F28 +1F21;GREEK SMALL LETTER ETA WITH DASIA;Ll;0;L;03B7 0314;;;;N;;;1F29;;1F29 +1F22;GREEK SMALL LETTER ETA WITH PSILI AND VARIA;Ll;0;L;1F20 0300;;;;N;;;1F2A;;1F2A +1F23;GREEK SMALL LETTER ETA WITH DASIA AND VARIA;Ll;0;L;1F21 0300;;;;N;;;1F2B;;1F2B +1F24;GREEK SMALL LETTER ETA WITH PSILI AND OXIA;Ll;0;L;1F20 0301;;;;N;;;1F2C;;1F2C +1F25;GREEK SMALL LETTER ETA WITH DASIA AND OXIA;Ll;0;L;1F21 0301;;;;N;;;1F2D;;1F2D +1F26;GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI;Ll;0;L;1F20 0342;;;;N;;;1F2E;;1F2E +1F27;GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI;Ll;0;L;1F21 0342;;;;N;;;1F2F;;1F2F +1F28;GREEK CAPITAL LETTER ETA WITH PSILI;Lu;0;L;0397 0313;;;;N;;;;1F20; +1F29;GREEK CAPITAL LETTER ETA WITH DASIA;Lu;0;L;0397 0314;;;;N;;;;1F21; +1F2A;GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA;Lu;0;L;1F28 0300;;;;N;;;;1F22; +1F2B;GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA;Lu;0;L;1F29 0300;;;;N;;;;1F23; +1F2C;GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA;Lu;0;L;1F28 0301;;;;N;;;;1F24; +1F2D;GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA;Lu;0;L;1F29 0301;;;;N;;;;1F25; +1F2E;GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI;Lu;0;L;1F28 0342;;;;N;;;;1F26; +1F2F;GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI;Lu;0;L;1F29 0342;;;;N;;;;1F27; +1F30;GREEK SMALL LETTER IOTA WITH PSILI;Ll;0;L;03B9 0313;;;;N;;;1F38;;1F38 +1F31;GREEK SMALL LETTER IOTA WITH DASIA;Ll;0;L;03B9 0314;;;;N;;;1F39;;1F39 +1F32;GREEK SMALL LETTER IOTA WITH PSILI AND VARIA;Ll;0;L;1F30 0300;;;;N;;;1F3A;;1F3A +1F33;GREEK SMALL LETTER IOTA WITH DASIA AND VARIA;Ll;0;L;1F31 0300;;;;N;;;1F3B;;1F3B +1F34;GREEK SMALL LETTER IOTA WITH PSILI AND OXIA;Ll;0;L;1F30 0301;;;;N;;;1F3C;;1F3C +1F35;GREEK SMALL LETTER IOTA WITH DASIA AND OXIA;Ll;0;L;1F31 0301;;;;N;;;1F3D;;1F3D +1F36;GREEK SMALL LETTER IOTA WITH PSILI AND PERISPOMENI;Ll;0;L;1F30 0342;;;;N;;;1F3E;;1F3E +1F37;GREEK SMALL LETTER IOTA WITH DASIA AND PERISPOMENI;Ll;0;L;1F31 0342;;;;N;;;1F3F;;1F3F +1F38;GREEK CAPITAL LETTER IOTA WITH PSILI;Lu;0;L;0399 0313;;;;N;;;;1F30; +1F39;GREEK CAPITAL LETTER IOTA WITH DASIA;Lu;0;L;0399 0314;;;;N;;;;1F31; +1F3A;GREEK CAPITAL LETTER IOTA WITH PSILI AND VARIA;Lu;0;L;1F38 0300;;;;N;;;;1F32; +1F3B;GREEK CAPITAL LETTER IOTA WITH DASIA AND VARIA;Lu;0;L;1F39 0300;;;;N;;;;1F33; +1F3C;GREEK CAPITAL LETTER IOTA WITH PSILI AND OXIA;Lu;0;L;1F38 0301;;;;N;;;;1F34; +1F3D;GREEK CAPITAL LETTER IOTA WITH DASIA AND OXIA;Lu;0;L;1F39 0301;;;;N;;;;1F35; +1F3E;GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI;Lu;0;L;1F38 0342;;;;N;;;;1F36; +1F3F;GREEK CAPITAL LETTER IOTA WITH DASIA AND PERISPOMENI;Lu;0;L;1F39 0342;;;;N;;;;1F37; +1F40;GREEK SMALL LETTER OMICRON WITH PSILI;Ll;0;L;03BF 0313;;;;N;;;1F48;;1F48 +1F41;GREEK SMALL LETTER OMICRON WITH DASIA;Ll;0;L;03BF 0314;;;;N;;;1F49;;1F49 +1F42;GREEK SMALL LETTER OMICRON WITH PSILI AND VARIA;Ll;0;L;1F40 0300;;;;N;;;1F4A;;1F4A +1F43;GREEK SMALL LETTER OMICRON WITH DASIA AND VARIA;Ll;0;L;1F41 0300;;;;N;;;1F4B;;1F4B +1F44;GREEK SMALL LETTER OMICRON WITH PSILI AND OXIA;Ll;0;L;1F40 0301;;;;N;;;1F4C;;1F4C +1F45;GREEK SMALL LETTER OMICRON WITH DASIA AND OXIA;Ll;0;L;1F41 0301;;;;N;;;1F4D;;1F4D +1F48;GREEK CAPITAL LETTER OMICRON WITH PSILI;Lu;0;L;039F 0313;;;;N;;;;1F40; +1F49;GREEK CAPITAL LETTER OMICRON WITH DASIA;Lu;0;L;039F 0314;;;;N;;;;1F41; +1F4A;GREEK CAPITAL LETTER OMICRON WITH PSILI AND VARIA;Lu;0;L;1F48 0300;;;;N;;;;1F42; +1F4B;GREEK CAPITAL LETTER OMICRON WITH DASIA AND VARIA;Lu;0;L;1F49 0300;;;;N;;;;1F43; +1F4C;GREEK CAPITAL LETTER OMICRON WITH PSILI AND OXIA;Lu;0;L;1F48 0301;;;;N;;;;1F44; +1F4D;GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA;Lu;0;L;1F49 0301;;;;N;;;;1F45; +1F50;GREEK SMALL LETTER UPSILON WITH PSILI;Ll;0;L;03C5 0313;;;;N;;;;; +1F51;GREEK SMALL LETTER UPSILON WITH DASIA;Ll;0;L;03C5 0314;;;;N;;;1F59;;1F59 +1F52;GREEK SMALL LETTER UPSILON WITH PSILI AND VARIA;Ll;0;L;1F50 0300;;;;N;;;;; +1F53;GREEK SMALL LETTER UPSILON WITH DASIA AND VARIA;Ll;0;L;1F51 0300;;;;N;;;1F5B;;1F5B +1F54;GREEK SMALL LETTER UPSILON WITH PSILI AND OXIA;Ll;0;L;1F50 0301;;;;N;;;;; +1F55;GREEK SMALL LETTER UPSILON WITH DASIA AND OXIA;Ll;0;L;1F51 0301;;;;N;;;1F5D;;1F5D +1F56;GREEK SMALL LETTER UPSILON WITH PSILI AND PERISPOMENI;Ll;0;L;1F50 0342;;;;N;;;;; +1F57;GREEK SMALL LETTER UPSILON WITH DASIA AND PERISPOMENI;Ll;0;L;1F51 0342;;;;N;;;1F5F;;1F5F +1F59;GREEK CAPITAL LETTER UPSILON WITH DASIA;Lu;0;L;03A5 0314;;;;N;;;;1F51; +1F5B;GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA;Lu;0;L;1F59 0300;;;;N;;;;1F53; +1F5D;GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA;Lu;0;L;1F59 0301;;;;N;;;;1F55; +1F5F;GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI;Lu;0;L;1F59 0342;;;;N;;;;1F57; +1F60;GREEK SMALL LETTER OMEGA WITH PSILI;Ll;0;L;03C9 0313;;;;N;;;1F68;;1F68 +1F61;GREEK SMALL LETTER OMEGA WITH DASIA;Ll;0;L;03C9 0314;;;;N;;;1F69;;1F69 +1F62;GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA;Ll;0;L;1F60 0300;;;;N;;;1F6A;;1F6A +1F63;GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA;Ll;0;L;1F61 0300;;;;N;;;1F6B;;1F6B +1F64;GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA;Ll;0;L;1F60 0301;;;;N;;;1F6C;;1F6C +1F65;GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA;Ll;0;L;1F61 0301;;;;N;;;1F6D;;1F6D +1F66;GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI;Ll;0;L;1F60 0342;;;;N;;;1F6E;;1F6E +1F67;GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI;Ll;0;L;1F61 0342;;;;N;;;1F6F;;1F6F +1F68;GREEK CAPITAL LETTER OMEGA WITH PSILI;Lu;0;L;03A9 0313;;;;N;;;;1F60; +1F69;GREEK CAPITAL LETTER OMEGA WITH DASIA;Lu;0;L;03A9 0314;;;;N;;;;1F61; +1F6A;GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA;Lu;0;L;1F68 0300;;;;N;;;;1F62; +1F6B;GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA;Lu;0;L;1F69 0300;;;;N;;;;1F63; +1F6C;GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA;Lu;0;L;1F68 0301;;;;N;;;;1F64; +1F6D;GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA;Lu;0;L;1F69 0301;;;;N;;;;1F65; +1F6E;GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI;Lu;0;L;1F68 0342;;;;N;;;;1F66; +1F6F;GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI;Lu;0;L;1F69 0342;;;;N;;;;1F67; +1F70;GREEK SMALL LETTER ALPHA WITH VARIA;Ll;0;L;03B1 0300;;;;N;;;1FBA;;1FBA +1F71;GREEK SMALL LETTER ALPHA WITH OXIA;Ll;0;L;03AC;;;;N;;;1FBB;;1FBB +1F72;GREEK SMALL LETTER EPSILON WITH VARIA;Ll;0;L;03B5 0300;;;;N;;;1FC8;;1FC8 +1F73;GREEK SMALL LETTER EPSILON WITH OXIA;Ll;0;L;03AD;;;;N;;;1FC9;;1FC9 +1F74;GREEK SMALL LETTER ETA WITH VARIA;Ll;0;L;03B7 0300;;;;N;;;1FCA;;1FCA +1F75;GREEK SMALL LETTER ETA WITH OXIA;Ll;0;L;03AE;;;;N;;;1FCB;;1FCB +1F76;GREEK SMALL LETTER IOTA WITH VARIA;Ll;0;L;03B9 0300;;;;N;;;1FDA;;1FDA +1F77;GREEK SMALL LETTER IOTA WITH OXIA;Ll;0;L;03AF;;;;N;;;1FDB;;1FDB +1F78;GREEK SMALL LETTER OMICRON WITH VARIA;Ll;0;L;03BF 0300;;;;N;;;1FF8;;1FF8 +1F79;GREEK SMALL LETTER OMICRON WITH OXIA;Ll;0;L;03CC;;;;N;;;1FF9;;1FF9 +1F7A;GREEK SMALL LETTER UPSILON WITH VARIA;Ll;0;L;03C5 0300;;;;N;;;1FEA;;1FEA +1F7B;GREEK SMALL LETTER UPSILON WITH OXIA;Ll;0;L;03CD;;;;N;;;1FEB;;1FEB +1F7C;GREEK SMALL LETTER OMEGA WITH VARIA;Ll;0;L;03C9 0300;;;;N;;;1FFA;;1FFA +1F7D;GREEK SMALL LETTER OMEGA WITH OXIA;Ll;0;L;03CE;;;;N;;;1FFB;;1FFB +1F80;GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI;Ll;0;L;1F00 0345;;;;N;;;1F88;;1F88 +1F81;GREEK SMALL LETTER ALPHA WITH DASIA AND YPOGEGRAMMENI;Ll;0;L;1F01 0345;;;;N;;;1F89;;1F89 +1F82;GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F02 0345;;;;N;;;1F8A;;1F8A +1F83;GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F03 0345;;;;N;;;1F8B;;1F8B +1F84;GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F04 0345;;;;N;;;1F8C;;1F8C +1F85;GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F05 0345;;;;N;;;1F8D;;1F8D +1F86;GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F06 0345;;;;N;;;1F8E;;1F8E +1F87;GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F07 0345;;;;N;;;1F8F;;1F8F +1F88;GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI;Lt;0;L;1F08 0345;;;;N;;;;1F80; +1F89;GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI;Lt;0;L;1F09 0345;;;;N;;;;1F81; +1F8A;GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F0A 0345;;;;N;;;;1F82; +1F8B;GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F0B 0345;;;;N;;;;1F83; +1F8C;GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F0C 0345;;;;N;;;;1F84; +1F8D;GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F0D 0345;;;;N;;;;1F85; +1F8E;GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F0E 0345;;;;N;;;;1F86; +1F8F;GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F0F 0345;;;;N;;;;1F87; +1F90;GREEK SMALL LETTER ETA WITH PSILI AND YPOGEGRAMMENI;Ll;0;L;1F20 0345;;;;N;;;1F98;;1F98 +1F91;GREEK SMALL LETTER ETA WITH DASIA AND YPOGEGRAMMENI;Ll;0;L;1F21 0345;;;;N;;;1F99;;1F99 +1F92;GREEK SMALL LETTER ETA WITH PSILI AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F22 0345;;;;N;;;1F9A;;1F9A +1F93;GREEK SMALL LETTER ETA WITH DASIA AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F23 0345;;;;N;;;1F9B;;1F9B +1F94;GREEK SMALL LETTER ETA WITH PSILI AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F24 0345;;;;N;;;1F9C;;1F9C +1F95;GREEK SMALL LETTER ETA WITH DASIA AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F25 0345;;;;N;;;1F9D;;1F9D +1F96;GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F26 0345;;;;N;;;1F9E;;1F9E +1F97;GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F27 0345;;;;N;;;1F9F;;1F9F +1F98;GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI;Lt;0;L;1F28 0345;;;;N;;;;1F90; +1F99;GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI;Lt;0;L;1F29 0345;;;;N;;;;1F91; +1F9A;GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F2A 0345;;;;N;;;;1F92; +1F9B;GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F2B 0345;;;;N;;;;1F93; +1F9C;GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F2C 0345;;;;N;;;;1F94; +1F9D;GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F2D 0345;;;;N;;;;1F95; +1F9E;GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F2E 0345;;;;N;;;;1F96; +1F9F;GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F2F 0345;;;;N;;;;1F97; +1FA0;GREEK SMALL LETTER OMEGA WITH PSILI AND YPOGEGRAMMENI;Ll;0;L;1F60 0345;;;;N;;;1FA8;;1FA8 +1FA1;GREEK SMALL LETTER OMEGA WITH DASIA AND YPOGEGRAMMENI;Ll;0;L;1F61 0345;;;;N;;;1FA9;;1FA9 +1FA2;GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F62 0345;;;;N;;;1FAA;;1FAA +1FA3;GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA AND YPOGEGRAMMENI;Ll;0;L;1F63 0345;;;;N;;;1FAB;;1FAB +1FA4;GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F64 0345;;;;N;;;1FAC;;1FAC +1FA5;GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA AND YPOGEGRAMMENI;Ll;0;L;1F65 0345;;;;N;;;1FAD;;1FAD +1FA6;GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F66 0345;;;;N;;;1FAE;;1FAE +1FA7;GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1F67 0345;;;;N;;;1FAF;;1FAF +1FA8;GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI;Lt;0;L;1F68 0345;;;;N;;;;1FA0; +1FA9;GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI;Lt;0;L;1F69 0345;;;;N;;;;1FA1; +1FAA;GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F6A 0345;;;;N;;;;1FA2; +1FAB;GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI;Lt;0;L;1F6B 0345;;;;N;;;;1FA3; +1FAC;GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F6C 0345;;;;N;;;;1FA4; +1FAD;GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI;Lt;0;L;1F6D 0345;;;;N;;;;1FA5; +1FAE;GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F6E 0345;;;;N;;;;1FA6; +1FAF;GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI;Lt;0;L;1F6F 0345;;;;N;;;;1FA7; +1FB0;GREEK SMALL LETTER ALPHA WITH VRACHY;Ll;0;L;03B1 0306;;;;N;;;1FB8;;1FB8 +1FB1;GREEK SMALL LETTER ALPHA WITH MACRON;Ll;0;L;03B1 0304;;;;N;;;1FB9;;1FB9 +1FB2;GREEK SMALL LETTER ALPHA WITH VARIA AND YPOGEGRAMMENI;Ll;0;L;1F70 0345;;;;N;;;;; +1FB3;GREEK SMALL LETTER ALPHA WITH YPOGEGRAMMENI;Ll;0;L;03B1 0345;;;;N;;;1FBC;;1FBC +1FB4;GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI;Ll;0;L;03AC 0345;;;;N;;;;; +1FB6;GREEK SMALL LETTER ALPHA WITH PERISPOMENI;Ll;0;L;03B1 0342;;;;N;;;;; +1FB7;GREEK SMALL LETTER ALPHA WITH PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1FB6 0345;;;;N;;;;; +1FB8;GREEK CAPITAL LETTER ALPHA WITH VRACHY;Lu;0;L;0391 0306;;;;N;;;;1FB0; +1FB9;GREEK CAPITAL LETTER ALPHA WITH MACRON;Lu;0;L;0391 0304;;;;N;;;;1FB1; +1FBA;GREEK CAPITAL LETTER ALPHA WITH VARIA;Lu;0;L;0391 0300;;;;N;;;;1F70; +1FBB;GREEK CAPITAL LETTER ALPHA WITH OXIA;Lu;0;L;0386;;;;N;;;;1F71; +1FBC;GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI;Lt;0;L;0391 0345;;;;N;;;;1FB3; +1FBD;GREEK KORONIS;Sk;0;ON; 0020 0313;;;;N;;;;; +1FBE;GREEK PROSGEGRAMMENI;Ll;0;L;03B9;;;;N;;;0399;;0399 +1FBF;GREEK PSILI;Sk;0;ON; 0020 0313;;;;N;;;;; +1FC0;GREEK PERISPOMENI;Sk;0;ON; 0020 0342;;;;N;;;;; +1FC1;GREEK DIALYTIKA AND PERISPOMENI;Sk;0;ON;00A8 0342;;;;N;;;;; +1FC2;GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI;Ll;0;L;1F74 0345;;;;N;;;;; +1FC3;GREEK SMALL LETTER ETA WITH YPOGEGRAMMENI;Ll;0;L;03B7 0345;;;;N;;;1FCC;;1FCC +1FC4;GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI;Ll;0;L;03AE 0345;;;;N;;;;; +1FC6;GREEK SMALL LETTER ETA WITH PERISPOMENI;Ll;0;L;03B7 0342;;;;N;;;;; +1FC7;GREEK SMALL LETTER ETA WITH PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1FC6 0345;;;;N;;;;; +1FC8;GREEK CAPITAL LETTER EPSILON WITH VARIA;Lu;0;L;0395 0300;;;;N;;;;1F72; +1FC9;GREEK CAPITAL LETTER EPSILON WITH OXIA;Lu;0;L;0388;;;;N;;;;1F73; +1FCA;GREEK CAPITAL LETTER ETA WITH VARIA;Lu;0;L;0397 0300;;;;N;;;;1F74; +1FCB;GREEK CAPITAL LETTER ETA WITH OXIA;Lu;0;L;0389;;;;N;;;;1F75; +1FCC;GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI;Lt;0;L;0397 0345;;;;N;;;;1FC3; +1FCD;GREEK PSILI AND VARIA;Sk;0;ON;1FBF 0300;;;;N;;;;; +1FCE;GREEK PSILI AND OXIA;Sk;0;ON;1FBF 0301;;;;N;;;;; +1FCF;GREEK PSILI AND PERISPOMENI;Sk;0;ON;1FBF 0342;;;;N;;;;; +1FD0;GREEK SMALL LETTER IOTA WITH VRACHY;Ll;0;L;03B9 0306;;;;N;;;1FD8;;1FD8 +1FD1;GREEK SMALL LETTER IOTA WITH MACRON;Ll;0;L;03B9 0304;;;;N;;;1FD9;;1FD9 +1FD2;GREEK SMALL LETTER IOTA WITH DIALYTIKA AND VARIA;Ll;0;L;03CA 0300;;;;N;;;;; +1FD3;GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA;Ll;0;L;0390;;;;N;;;;; +1FD6;GREEK SMALL LETTER IOTA WITH PERISPOMENI;Ll;0;L;03B9 0342;;;;N;;;;; +1FD7;GREEK SMALL LETTER IOTA WITH DIALYTIKA AND PERISPOMENI;Ll;0;L;03CA 0342;;;;N;;;;; +1FD8;GREEK CAPITAL LETTER IOTA WITH VRACHY;Lu;0;L;0399 0306;;;;N;;;;1FD0; +1FD9;GREEK CAPITAL LETTER IOTA WITH MACRON;Lu;0;L;0399 0304;;;;N;;;;1FD1; +1FDA;GREEK CAPITAL LETTER IOTA WITH VARIA;Lu;0;L;0399 0300;;;;N;;;;1F76; +1FDB;GREEK CAPITAL LETTER IOTA WITH OXIA;Lu;0;L;038A;;;;N;;;;1F77; +1FDD;GREEK DASIA AND VARIA;Sk;0;ON;1FFE 0300;;;;N;;;;; +1FDE;GREEK DASIA AND OXIA;Sk;0;ON;1FFE 0301;;;;N;;;;; +1FDF;GREEK DASIA AND PERISPOMENI;Sk;0;ON;1FFE 0342;;;;N;;;;; +1FE0;GREEK SMALL LETTER UPSILON WITH VRACHY;Ll;0;L;03C5 0306;;;;N;;;1FE8;;1FE8 +1FE1;GREEK SMALL LETTER UPSILON WITH MACRON;Ll;0;L;03C5 0304;;;;N;;;1FE9;;1FE9 +1FE2;GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND VARIA;Ll;0;L;03CB 0300;;;;N;;;;; +1FE3;GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA;Ll;0;L;03B0;;;;N;;;;; +1FE4;GREEK SMALL LETTER RHO WITH PSILI;Ll;0;L;03C1 0313;;;;N;;;;; +1FE5;GREEK SMALL LETTER RHO WITH DASIA;Ll;0;L;03C1 0314;;;;N;;;1FEC;;1FEC +1FE6;GREEK SMALL LETTER UPSILON WITH PERISPOMENI;Ll;0;L;03C5 0342;;;;N;;;;; +1FE7;GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND PERISPOMENI;Ll;0;L;03CB 0342;;;;N;;;;; +1FE8;GREEK CAPITAL LETTER UPSILON WITH VRACHY;Lu;0;L;03A5 0306;;;;N;;;;1FE0; +1FE9;GREEK CAPITAL LETTER UPSILON WITH MACRON;Lu;0;L;03A5 0304;;;;N;;;;1FE1; +1FEA;GREEK CAPITAL LETTER UPSILON WITH VARIA;Lu;0;L;03A5 0300;;;;N;;;;1F7A; +1FEB;GREEK CAPITAL LETTER UPSILON WITH OXIA;Lu;0;L;038E;;;;N;;;;1F7B; +1FEC;GREEK CAPITAL LETTER RHO WITH DASIA;Lu;0;L;03A1 0314;;;;N;;;;1FE5; +1FED;GREEK DIALYTIKA AND VARIA;Sk;0;ON;00A8 0300;;;;N;;;;; +1FEE;GREEK DIALYTIKA AND OXIA;Sk;0;ON;0385;;;;N;;;;; +1FEF;GREEK VARIA;Sk;0;ON;0060;;;;N;;;;; +1FF2;GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI;Ll;0;L;1F7C 0345;;;;N;;;;; +1FF3;GREEK SMALL LETTER OMEGA WITH YPOGEGRAMMENI;Ll;0;L;03C9 0345;;;;N;;;1FFC;;1FFC +1FF4;GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI;Ll;0;L;03CE 0345;;;;N;;;;; +1FF6;GREEK SMALL LETTER OMEGA WITH PERISPOMENI;Ll;0;L;03C9 0342;;;;N;;;;; +1FF7;GREEK SMALL LETTER OMEGA WITH PERISPOMENI AND YPOGEGRAMMENI;Ll;0;L;1FF6 0345;;;;N;;;;; +1FF8;GREEK CAPITAL LETTER OMICRON WITH VARIA;Lu;0;L;039F 0300;;;;N;;;;1F78; +1FF9;GREEK CAPITAL LETTER OMICRON WITH OXIA;Lu;0;L;038C;;;;N;;;;1F79; +1FFA;GREEK CAPITAL LETTER OMEGA WITH VARIA;Lu;0;L;03A9 0300;;;;N;;;;1F7C; +1FFB;GREEK CAPITAL LETTER OMEGA WITH OXIA;Lu;0;L;038F;;;;N;;;;1F7D; +1FFC;GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI;Lt;0;L;03A9 0345;;;;N;;;;1FF3; +1FFD;GREEK OXIA;Sk;0;ON;00B4;;;;N;;;;; +1FFE;GREEK DASIA;Sk;0;ON; 0020 0314;;;;N;;;;; +2000;EN QUAD;Zs;0;WS;2002;;;;N;;;;; +2001;EM QUAD;Zs;0;WS;2003;;;;N;;;;; +2002;EN SPACE;Zs;0;WS; 0020;;;;N;;;;; +2003;EM SPACE;Zs;0;WS; 0020;;;;N;;;;; +2004;THREE-PER-EM SPACE;Zs;0;WS; 0020;;;;N;;;;; +2005;FOUR-PER-EM SPACE;Zs;0;WS; 0020;;;;N;;;;; +2006;SIX-PER-EM SPACE;Zs;0;WS; 0020;;;;N;;;;; +2007;FIGURE SPACE;Zs;0;WS; 0020;;;;N;;;;; +2008;PUNCTUATION SPACE;Zs;0;WS; 0020;;;;N;;;;; +2009;THIN SPACE;Zs;0;WS; 0020;;;;N;;;;; +200A;HAIR SPACE;Zs;0;WS; 0020;;;;N;;;;; +200B;ZERO WIDTH SPACE;Cf;0;BN;;;;;N;;;;; +200C;ZERO WIDTH NON-JOINER;Cf;0;BN;;;;;N;;;;; +200D;ZERO WIDTH JOINER;Cf;0;BN;;;;;N;;;;; +200E;LEFT-TO-RIGHT MARK;Cf;0;L;;;;;N;;;;; +200F;RIGHT-TO-LEFT MARK;Cf;0;R;;;;;N;;;;; +2010;HYPHEN;Pd;0;ON;;;;;N;;;;; +2011;NON-BREAKING HYPHEN;Pd;0;ON; 2010;;;;N;;;;; +2012;FIGURE DASH;Pd;0;ON;;;;;N;;;;; +2013;EN DASH;Pd;0;ON;;;;;N;;;;; +2014;EM DASH;Pd;0;ON;;;;;N;;;;; +2015;HORIZONTAL BAR;Pd;0;ON;;;;;N;QUOTATION DASH;;;; +2016;DOUBLE VERTICAL LINE;Po;0;ON;;;;;N;DOUBLE VERTICAL BAR;;;; +2017;DOUBLE LOW LINE;Po;0;ON; 0020 0333;;;;N;SPACING DOUBLE UNDERSCORE;;;; +2018;LEFT SINGLE QUOTATION MARK;Pi;0;ON;;;;;N;SINGLE TURNED COMMA QUOTATION MARK;;;; +2019;RIGHT SINGLE QUOTATION MARK;Pf;0;ON;;;;;N;SINGLE COMMA QUOTATION MARK;;;; +201A;SINGLE LOW-9 QUOTATION MARK;Ps;0;ON;;;;;N;LOW SINGLE COMMA QUOTATION MARK;;;; +201B;SINGLE HIGH-REVERSED-9 QUOTATION MARK;Pi;0;ON;;;;;N;SINGLE REVERSED COMMA QUOTATION MARK;;;; +201C;LEFT DOUBLE QUOTATION MARK;Pi;0;ON;;;;;N;DOUBLE TURNED COMMA QUOTATION MARK;;;; +201D;RIGHT DOUBLE QUOTATION MARK;Pf;0;ON;;;;;N;DOUBLE COMMA QUOTATION MARK;;;; +201E;DOUBLE LOW-9 QUOTATION MARK;Ps;0;ON;;;;;N;LOW DOUBLE COMMA QUOTATION MARK;;;; +201F;DOUBLE HIGH-REVERSED-9 QUOTATION MARK;Pi;0;ON;;;;;N;DOUBLE REVERSED COMMA QUOTATION MARK;;;; +2020;DAGGER;Po;0;ON;;;;;N;;;;; +2021;DOUBLE DAGGER;Po;0;ON;;;;;N;;;;; +2022;BULLET;Po;0;ON;;;;;N;;;;; +2023;TRIANGULAR BULLET;Po;0;ON;;;;;N;;;;; +2024;ONE DOT LEADER;Po;0;ON; 002E;;;;N;;;;; +2025;TWO DOT LEADER;Po;0;ON; 002E 002E;;;;N;;;;; +2026;HORIZONTAL ELLIPSIS;Po;0;ON; 002E 002E 002E;;;;N;;;;; +2027;HYPHENATION POINT;Po;0;ON;;;;;N;;;;; +2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;; +2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;; +202A;LEFT-TO-RIGHT EMBEDDING;Cf;0;LRE;;;;;N;;;;; +202B;RIGHT-TO-LEFT EMBEDDING;Cf;0;RLE;;;;;N;;;;; +202C;POP DIRECTIONAL FORMATTING;Cf;0;PDF;;;;;N;;;;; +202D;LEFT-TO-RIGHT OVERRIDE;Cf;0;LRO;;;;;N;;;;; +202E;RIGHT-TO-LEFT OVERRIDE;Cf;0;RLO;;;;;N;;;;; +202F;NARROW NO-BREAK SPACE;Zs;0;CS; 0020;;;;N;;;;; +2030;PER MILLE SIGN;Po;0;ET;;;;;N;;;;; +2031;PER TEN THOUSAND SIGN;Po;0;ET;;;;;N;;;;; +2032;PRIME;Po;0;ET;;;;;N;;;;; +2033;DOUBLE PRIME;Po;0;ET; 2032 2032;;;;N;;;;; +2034;TRIPLE PRIME;Po;0;ET; 2032 2032 2032;;;;N;;;;; +2035;REVERSED PRIME;Po;0;ON;;;;;N;;;;; +2036;REVERSED DOUBLE PRIME;Po;0;ON; 2035 2035;;;;N;;;;; +2037;REVERSED TRIPLE PRIME;Po;0;ON; 2035 2035 2035;;;;N;;;;; +2038;CARET;Po;0;ON;;;;;N;;;;; +2039;SINGLE LEFT-POINTING ANGLE QUOTATION MARK;Pi;0;ON;;;;;Y;LEFT POINTING SINGLE GUILLEMET;;;; +203A;SINGLE RIGHT-POINTING ANGLE QUOTATION MARK;Pf;0;ON;;;;;Y;RIGHT POINTING SINGLE GUILLEMET;;;; +203B;REFERENCE MARK;Po;0;ON;;;;;N;;;;; +203C;DOUBLE EXCLAMATION MARK;Po;0;ON; 0021 0021;;;;N;;;;; +203D;INTERROBANG;Po;0;ON;;;;;N;;;;; +203E;OVERLINE;Po;0;ON; 0020 0305;;;;N;SPACING OVERSCORE;;;; +203F;UNDERTIE;Pc;0;ON;;;;;N;;;;; +2040;CHARACTER TIE;Pc;0;ON;;;;;N;;;;; +2041;CARET INSERTION POINT;Po;0;ON;;;;;N;;;;; +2042;ASTERISM;Po;0;ON;;;;;N;;;;; +2043;HYPHEN BULLET;Po;0;ON;;;;;N;;;;; +2044;FRACTION SLASH;Sm;0;CS;;;;;N;;;;; +2045;LEFT SQUARE BRACKET WITH QUILL;Ps;0;ON;;;;;Y;;;;; +2046;RIGHT SQUARE BRACKET WITH QUILL;Pe;0;ON;;;;;Y;;;;; +2047;DOUBLE QUESTION MARK;Po;0;ON; 003F 003F;;;;N;;;;; +2048;QUESTION EXCLAMATION MARK;Po;0;ON; 003F 0021;;;;N;;;;; +2049;EXCLAMATION QUESTION MARK;Po;0;ON; 0021 003F;;;;N;;;;; +204A;TIRONIAN SIGN ET;Po;0;ON;;;;;N;;;;; +204B;REVERSED PILCROW SIGN;Po;0;ON;;;;;N;;;;; +204C;BLACK LEFTWARDS BULLET;Po;0;ON;;;;;N;;;;; +204D;BLACK RIGHTWARDS BULLET;Po;0;ON;;;;;N;;;;; +204E;LOW ASTERISK;Po;0;ON;;;;;N;;;;; +204F;REVERSED SEMICOLON;Po;0;ON;;;;;N;;;;; +2050;CLOSE UP;Po;0;ON;;;;;N;;;;; +2051;TWO ASTERISKS ALIGNED VERTICALLY;Po;0;ON;;;;;N;;;;; +2052;COMMERCIAL MINUS SIGN;Sm;0;ON;;;;;N;;;;; +2053;SWUNG DASH;Po;0;ON;;;;;N;;;;; +2054;INVERTED UNDERTIE;Pc;0;ON;;;;;N;;;;; +2055;FLOWER PUNCTUATION MARK;Po;0;ON;;;;;N;;;;; +2056;THREE DOT PUNCTUATION;Po;0;ON;;;;;N;;;;; +2057;QUADRUPLE PRIME;Po;0;ON; 2032 2032 2032 2032;;;;N;;;;; +2058;FOUR DOT PUNCTUATION;Po;0;ON;;;;;N;;;;; +2059;FIVE DOT PUNCTUATION;Po;0;ON;;;;;N;;;;; +205A;TWO DOT PUNCTUATION;Po;0;ON;;;;;N;;;;; +205B;FOUR DOT MARK;Po;0;ON;;;;;N;;;;; +205C;DOTTED CROSS;Po;0;ON;;;;;N;;;;; +205D;TRICOLON;Po;0;ON;;;;;N;;;;; +205E;VERTICAL FOUR DOTS;Po;0;ON;;;;;N;;;;; +205F;MEDIUM MATHEMATICAL SPACE;Zs;0;WS; 0020;;;;N;;;;; +2060;WORD JOINER;Cf;0;BN;;;;;N;;;;; +2061;FUNCTION APPLICATION;Cf;0;BN;;;;;N;;;;; +2062;INVISIBLE TIMES;Cf;0;BN;;;;;N;;;;; +2063;INVISIBLE SEPARATOR;Cf;0;BN;;;;;N;;;;; +2064;INVISIBLE PLUS;Cf;0;BN;;;;;N;;;;; +206A;INHIBIT SYMMETRIC SWAPPING;Cf;0;BN;;;;;N;;;;; +206B;ACTIVATE SYMMETRIC SWAPPING;Cf;0;BN;;;;;N;;;;; +206C;INHIBIT ARABIC FORM SHAPING;Cf;0;BN;;;;;N;;;;; +206D;ACTIVATE ARABIC FORM SHAPING;Cf;0;BN;;;;;N;;;;; +206E;NATIONAL DIGIT SHAPES;Cf;0;BN;;;;;N;;;;; +206F;NOMINAL DIGIT SHAPES;Cf;0;BN;;;;;N;;;;; +2070;SUPERSCRIPT ZERO;No;0;EN; 0030;;0;0;N;SUPERSCRIPT DIGIT ZERO;;;; +2071;SUPERSCRIPT LATIN SMALL LETTER I;Lm;0;L; 0069;;;;N;;;;; +2074;SUPERSCRIPT FOUR;No;0;EN; 0034;;4;4;N;SUPERSCRIPT DIGIT FOUR;;;; +2075;SUPERSCRIPT FIVE;No;0;EN; 0035;;5;5;N;SUPERSCRIPT DIGIT FIVE;;;; +2076;SUPERSCRIPT SIX;No;0;EN; 0036;;6;6;N;SUPERSCRIPT DIGIT SIX;;;; +2077;SUPERSCRIPT SEVEN;No;0;EN; 0037;;7;7;N;SUPERSCRIPT DIGIT SEVEN;;;; +2078;SUPERSCRIPT EIGHT;No;0;EN; 0038;;8;8;N;SUPERSCRIPT DIGIT EIGHT;;;; +2079;SUPERSCRIPT NINE;No;0;EN; 0039;;9;9;N;SUPERSCRIPT DIGIT NINE;;;; +207A;SUPERSCRIPT PLUS SIGN;Sm;0;ES; 002B;;;;N;;;;; +207B;SUPERSCRIPT MINUS;Sm;0;ES; 2212;;;;N;SUPERSCRIPT HYPHEN-MINUS;;;; +207C;SUPERSCRIPT EQUALS SIGN;Sm;0;ON; 003D;;;;N;;;;; +207D;SUPERSCRIPT LEFT PARENTHESIS;Ps;0;ON; 0028;;;;Y;SUPERSCRIPT OPENING PARENTHESIS;;;; +207E;SUPERSCRIPT RIGHT PARENTHESIS;Pe;0;ON; 0029;;;;Y;SUPERSCRIPT CLOSING PARENTHESIS;;;; +207F;SUPERSCRIPT LATIN SMALL LETTER N;Lm;0;L; 006E;;;;N;;;;; +2080;SUBSCRIPT ZERO;No;0;EN; 0030;;0;0;N;SUBSCRIPT DIGIT ZERO;;;; +2081;SUBSCRIPT ONE;No;0;EN; 0031;;1;1;N;SUBSCRIPT DIGIT ONE;;;; +2082;SUBSCRIPT TWO;No;0;EN; 0032;;2;2;N;SUBSCRIPT DIGIT TWO;;;; +2083;SUBSCRIPT THREE;No;0;EN; 0033;;3;3;N;SUBSCRIPT DIGIT THREE;;;; +2084;SUBSCRIPT FOUR;No;0;EN; 0034;;4;4;N;SUBSCRIPT DIGIT FOUR;;;; +2085;SUBSCRIPT FIVE;No;0;EN; 0035;;5;5;N;SUBSCRIPT DIGIT FIVE;;;; +2086;SUBSCRIPT SIX;No;0;EN; 0036;;6;6;N;SUBSCRIPT DIGIT SIX;;;; +2087;SUBSCRIPT SEVEN;No;0;EN; 0037;;7;7;N;SUBSCRIPT DIGIT SEVEN;;;; +2088;SUBSCRIPT EIGHT;No;0;EN; 0038;;8;8;N;SUBSCRIPT DIGIT EIGHT;;;; +2089;SUBSCRIPT NINE;No;0;EN; 0039;;9;9;N;SUBSCRIPT DIGIT NINE;;;; +208A;SUBSCRIPT PLUS SIGN;Sm;0;ES; 002B;;;;N;;;;; +208B;SUBSCRIPT MINUS;Sm;0;ES; 2212;;;;N;SUBSCRIPT HYPHEN-MINUS;;;; +208C;SUBSCRIPT EQUALS SIGN;Sm;0;ON; 003D;;;;N;;;;; +208D;SUBSCRIPT LEFT PARENTHESIS;Ps;0;ON; 0028;;;;Y;SUBSCRIPT OPENING PARENTHESIS;;;; +208E;SUBSCRIPT RIGHT PARENTHESIS;Pe;0;ON; 0029;;;;Y;SUBSCRIPT CLOSING PARENTHESIS;;;; +2090;LATIN SUBSCRIPT SMALL LETTER A;Lm;0;L; 0061;;;;N;;;;; +2091;LATIN SUBSCRIPT SMALL LETTER E;Lm;0;L; 0065;;;;N;;;;; +2092;LATIN SUBSCRIPT SMALL LETTER O;Lm;0;L; 006F;;;;N;;;;; +2093;LATIN SUBSCRIPT SMALL LETTER X;Lm;0;L; 0078;;;;N;;;;; +2094;LATIN SUBSCRIPT SMALL LETTER SCHWA;Lm;0;L; 0259;;;;N;;;;; +2095;LATIN SUBSCRIPT SMALL LETTER H;Lm;0;L; 0068;;;;N;;;;; +2096;LATIN SUBSCRIPT SMALL LETTER K;Lm;0;L; 006B;;;;N;;;;; +2097;LATIN SUBSCRIPT SMALL LETTER L;Lm;0;L; 006C;;;;N;;;;; +2098;LATIN SUBSCRIPT SMALL LETTER M;Lm;0;L; 006D;;;;N;;;;; +2099;LATIN SUBSCRIPT SMALL LETTER N;Lm;0;L; 006E;;;;N;;;;; +209A;LATIN SUBSCRIPT SMALL LETTER P;Lm;0;L; 0070;;;;N;;;;; +209B;LATIN SUBSCRIPT SMALL LETTER S;Lm;0;L; 0073;;;;N;;;;; +209C;LATIN SUBSCRIPT SMALL LETTER T;Lm;0;L; 0074;;;;N;;;;; +20A0;EURO-CURRENCY SIGN;Sc;0;ET;;;;;N;;;;; +20A1;COLON SIGN;Sc;0;ET;;;;;N;;;;; +20A2;CRUZEIRO SIGN;Sc;0;ET;;;;;N;;;;; +20A3;FRENCH FRANC SIGN;Sc;0;ET;;;;;N;;;;; +20A4;LIRA SIGN;Sc;0;ET;;;;;N;;;;; +20A5;MILL SIGN;Sc;0;ET;;;;;N;;;;; +20A6;NAIRA SIGN;Sc;0;ET;;;;;N;;;;; +20A7;PESETA SIGN;Sc;0;ET;;;;;N;;;;; +20A8;RUPEE SIGN;Sc;0;ET; 0052 0073;;;;N;;;;; +20A9;WON SIGN;Sc;0;ET;;;;;N;;;;; +20AA;NEW SHEQEL SIGN;Sc;0;ET;;;;;N;;;;; +20AB;DONG SIGN;Sc;0;ET;;;;;N;;;;; +20AC;EURO SIGN;Sc;0;ET;;;;;N;;;;; +20AD;KIP SIGN;Sc;0;ET;;;;;N;;;;; +20AE;TUGRIK SIGN;Sc;0;ET;;;;;N;;;;; +20AF;DRACHMA SIGN;Sc;0;ET;;;;;N;;;;; +20B0;GERMAN PENNY SIGN;Sc;0;ET;;;;;N;;;;; +20B1;PESO SIGN;Sc;0;ET;;;;;N;;;;; +20B2;GUARANI SIGN;Sc;0;ET;;;;;N;;;;; +20B3;AUSTRAL SIGN;Sc;0;ET;;;;;N;;;;; +20B4;HRYVNIA SIGN;Sc;0;ET;;;;;N;;;;; +20B5;CEDI SIGN;Sc;0;ET;;;;;N;;;;; +20B6;LIVRE TOURNOIS SIGN;Sc;0;ET;;;;;N;;;;; +20B7;SPESMILO SIGN;Sc;0;ET;;;;;N;;;;; +20B8;TENGE SIGN;Sc;0;ET;;;;;N;;;;; +20B9;INDIAN RUPEE SIGN;Sc;0;ET;;;;;N;;;;; +20D0;COMBINING LEFT HARPOON ABOVE;Mn;230;NSM;;;;;N;NON-SPACING LEFT HARPOON ABOVE;;;; +20D1;COMBINING RIGHT HARPOON ABOVE;Mn;230;NSM;;;;;N;NON-SPACING RIGHT HARPOON ABOVE;;;; +20D2;COMBINING LONG VERTICAL LINE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING LONG VERTICAL BAR OVERLAY;;;; +20D3;COMBINING SHORT VERTICAL LINE OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING SHORT VERTICAL BAR OVERLAY;;;; +20D4;COMBINING ANTICLOCKWISE ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING ANTICLOCKWISE ARROW ABOVE;;;; +20D5;COMBINING CLOCKWISE ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING CLOCKWISE ARROW ABOVE;;;; +20D6;COMBINING LEFT ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING LEFT ARROW ABOVE;;;; +20D7;COMBINING RIGHT ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING RIGHT ARROW ABOVE;;;; +20D8;COMBINING RING OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING RING OVERLAY;;;; +20D9;COMBINING CLOCKWISE RING OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING CLOCKWISE RING OVERLAY;;;; +20DA;COMBINING ANTICLOCKWISE RING OVERLAY;Mn;1;NSM;;;;;N;NON-SPACING ANTICLOCKWISE RING OVERLAY;;;; +20DB;COMBINING THREE DOTS ABOVE;Mn;230;NSM;;;;;N;NON-SPACING THREE DOTS ABOVE;;;; +20DC;COMBINING FOUR DOTS ABOVE;Mn;230;NSM;;;;;N;NON-SPACING FOUR DOTS ABOVE;;;; +20DD;COMBINING ENCLOSING CIRCLE;Me;0;NSM;;;;;N;ENCLOSING CIRCLE;;;; +20DE;COMBINING ENCLOSING SQUARE;Me;0;NSM;;;;;N;ENCLOSING SQUARE;;;; +20DF;COMBINING ENCLOSING DIAMOND;Me;0;NSM;;;;;N;ENCLOSING DIAMOND;;;; +20E0;COMBINING ENCLOSING CIRCLE BACKSLASH;Me;0;NSM;;;;;N;ENCLOSING CIRCLE SLASH;;;; +20E1;COMBINING LEFT RIGHT ARROW ABOVE;Mn;230;NSM;;;;;N;NON-SPACING LEFT RIGHT ARROW ABOVE;;;; +20E2;COMBINING ENCLOSING SCREEN;Me;0;NSM;;;;;N;;;;; +20E3;COMBINING ENCLOSING KEYCAP;Me;0;NSM;;;;;N;;;;; +20E4;COMBINING ENCLOSING UPWARD POINTING TRIANGLE;Me;0;NSM;;;;;N;;;;; +20E5;COMBINING REVERSE SOLIDUS OVERLAY;Mn;1;NSM;;;;;N;;;;; +20E6;COMBINING DOUBLE VERTICAL STROKE OVERLAY;Mn;1;NSM;;;;;N;;;;; +20E7;COMBINING ANNUITY SYMBOL;Mn;230;NSM;;;;;N;;;;; +20E8;COMBINING TRIPLE UNDERDOT;Mn;220;NSM;;;;;N;;;;; +20E9;COMBINING WIDE BRIDGE ABOVE;Mn;230;NSM;;;;;N;;;;; +20EA;COMBINING LEFTWARDS ARROW OVERLAY;Mn;1;NSM;;;;;N;;;;; +20EB;COMBINING LONG DOUBLE SOLIDUS OVERLAY;Mn;1;NSM;;;;;N;;;;; +20EC;COMBINING RIGHTWARDS HARPOON WITH BARB DOWNWARDS;Mn;220;NSM;;;;;N;;;;; +20ED;COMBINING LEFTWARDS HARPOON WITH BARB DOWNWARDS;Mn;220;NSM;;;;;N;;;;; +20EE;COMBINING LEFT ARROW BELOW;Mn;220;NSM;;;;;N;;;;; +20EF;COMBINING RIGHT ARROW BELOW;Mn;220;NSM;;;;;N;;;;; +20F0;COMBINING ASTERISK ABOVE;Mn;230;NSM;;;;;N;;;;; +2100;ACCOUNT OF;So;0;ON; 0061 002F 0063;;;;N;;;;; +2101;ADDRESSED TO THE SUBJECT;So;0;ON; 0061 002F 0073;;;;N;;;;; +2102;DOUBLE-STRUCK CAPITAL C;Lu;0;L; 0043;;;;N;DOUBLE-STRUCK C;;;; +2103;DEGREE CELSIUS;So;0;ON; 00B0 0043;;;;N;DEGREES CENTIGRADE;;;; +2104;CENTRE LINE SYMBOL;So;0;ON;;;;;N;C L SYMBOL;;;; +2105;CARE OF;So;0;ON; 0063 002F 006F;;;;N;;;;; +2106;CADA UNA;So;0;ON; 0063 002F 0075;;;;N;;;;; +2107;EULER CONSTANT;Lu;0;L; 0190;;;;N;EULERS;;;; +2108;SCRUPLE;So;0;ON;;;;;N;;;;; +2109;DEGREE FAHRENHEIT;So;0;ON; 00B0 0046;;;;N;DEGREES FAHRENHEIT;;;; +210A;SCRIPT SMALL G;Ll;0;L; 0067;;;;N;;;;; +210B;SCRIPT CAPITAL H;Lu;0;L; 0048;;;;N;SCRIPT H;;;; +210C;BLACK-LETTER CAPITAL H;Lu;0;L; 0048;;;;N;BLACK-LETTER H;;;; +210D;DOUBLE-STRUCK CAPITAL H;Lu;0;L; 0048;;;;N;DOUBLE-STRUCK H;;;; +210E;PLANCK CONSTANT;Ll;0;L; 0068;;;;N;;;;; +210F;PLANCK CONSTANT OVER TWO PI;Ll;0;L; 0127;;;;N;PLANCK CONSTANT OVER 2 PI;;;; +2110;SCRIPT CAPITAL I;Lu;0;L; 0049;;;;N;SCRIPT I;;;; +2111;BLACK-LETTER CAPITAL I;Lu;0;L; 0049;;;;N;BLACK-LETTER I;;;; +2112;SCRIPT CAPITAL L;Lu;0;L; 004C;;;;N;SCRIPT L;;;; +2113;SCRIPT SMALL L;Ll;0;L; 006C;;;;N;;;;; +2114;L B BAR SYMBOL;So;0;ON;;;;;N;;;;; +2115;DOUBLE-STRUCK CAPITAL N;Lu;0;L; 004E;;;;N;DOUBLE-STRUCK N;;;; +2116;NUMERO SIGN;So;0;ON; 004E 006F;;;;N;NUMERO;;;; +2117;SOUND RECORDING COPYRIGHT;So;0;ON;;;;;N;;;;; +2118;SCRIPT CAPITAL P;Sm;0;ON;;;;;N;SCRIPT P;;;; +2119;DOUBLE-STRUCK CAPITAL P;Lu;0;L; 0050;;;;N;DOUBLE-STRUCK P;;;; +211A;DOUBLE-STRUCK CAPITAL Q;Lu;0;L; 0051;;;;N;DOUBLE-STRUCK Q;;;; +211B;SCRIPT CAPITAL R;Lu;0;L; 0052;;;;N;SCRIPT R;;;; +211C;BLACK-LETTER CAPITAL R;Lu;0;L; 0052;;;;N;BLACK-LETTER R;;;; +211D;DOUBLE-STRUCK CAPITAL R;Lu;0;L; 0052;;;;N;DOUBLE-STRUCK R;;;; +211E;PRESCRIPTION TAKE;So;0;ON;;;;;N;;;;; +211F;RESPONSE;So;0;ON;;;;;N;;;;; +2120;SERVICE MARK;So;0;ON; 0053 004D;;;;N;;;;; +2121;TELEPHONE SIGN;So;0;ON; 0054 0045 004C;;;;N;T E L SYMBOL;;;; +2122;TRADE MARK SIGN;So;0;ON; 0054 004D;;;;N;TRADEMARK;;;; +2123;VERSICLE;So;0;ON;;;;;N;;;;; +2124;DOUBLE-STRUCK CAPITAL Z;Lu;0;L; 005A;;;;N;DOUBLE-STRUCK Z;;;; +2125;OUNCE SIGN;So;0;ON;;;;;N;OUNCE;;;; +2126;OHM SIGN;Lu;0;L;03A9;;;;N;OHM;;;03C9; +2127;INVERTED OHM SIGN;So;0;ON;;;;;N;MHO;;;; +2128;BLACK-LETTER CAPITAL Z;Lu;0;L; 005A;;;;N;BLACK-LETTER Z;;;; +2129;TURNED GREEK SMALL LETTER IOTA;So;0;ON;;;;;N;;;;; +212A;KELVIN SIGN;Lu;0;L;004B;;;;N;DEGREES KELVIN;;;006B; +212B;ANGSTROM SIGN;Lu;0;L;00C5;;;;N;ANGSTROM UNIT;;;00E5; +212C;SCRIPT CAPITAL B;Lu;0;L; 0042;;;;N;SCRIPT B;;;; +212D;BLACK-LETTER CAPITAL C;Lu;0;L; 0043;;;;N;BLACK-LETTER C;;;; +212E;ESTIMATED SYMBOL;So;0;ET;;;;;N;;;;; +212F;SCRIPT SMALL E;Ll;0;L; 0065;;;;N;;;;; +2130;SCRIPT CAPITAL E;Lu;0;L; 0045;;;;N;SCRIPT E;;;; +2131;SCRIPT CAPITAL F;Lu;0;L; 0046;;;;N;SCRIPT F;;;; +2132;TURNED CAPITAL F;Lu;0;L;;;;;N;TURNED F;;;214E; +2133;SCRIPT CAPITAL M;Lu;0;L; 004D;;;;N;SCRIPT M;;;; +2134;SCRIPT SMALL O;Ll;0;L; 006F;;;;N;;;;; +2135;ALEF SYMBOL;Lo;0;L; 05D0;;;;N;FIRST TRANSFINITE CARDINAL;;;; +2136;BET SYMBOL;Lo;0;L; 05D1;;;;N;SECOND TRANSFINITE CARDINAL;;;; +2137;GIMEL SYMBOL;Lo;0;L; 05D2;;;;N;THIRD TRANSFINITE CARDINAL;;;; +2138;DALET SYMBOL;Lo;0;L; 05D3;;;;N;FOURTH TRANSFINITE CARDINAL;;;; +2139;INFORMATION SOURCE;Ll;0;L; 0069;;;;N;;;;; +213A;ROTATED CAPITAL Q;So;0;ON;;;;;N;;;;; +213B;FACSIMILE SIGN;So;0;ON; 0046 0041 0058;;;;N;;;;; +213C;DOUBLE-STRUCK SMALL PI;Ll;0;L; 03C0;;;;N;;;;; +213D;DOUBLE-STRUCK SMALL GAMMA;Ll;0;L; 03B3;;;;N;;;;; +213E;DOUBLE-STRUCK CAPITAL GAMMA;Lu;0;L; 0393;;;;N;;;;; +213F;DOUBLE-STRUCK CAPITAL PI;Lu;0;L; 03A0;;;;N;;;;; +2140;DOUBLE-STRUCK N-ARY SUMMATION;Sm;0;ON; 2211;;;;Y;;;;; +2141;TURNED SANS-SERIF CAPITAL G;Sm;0;ON;;;;;N;;;;; +2142;TURNED SANS-SERIF CAPITAL L;Sm;0;ON;;;;;N;;;;; +2143;REVERSED SANS-SERIF CAPITAL L;Sm;0;ON;;;;;N;;;;; +2144;TURNED SANS-SERIF CAPITAL Y;Sm;0;ON;;;;;N;;;;; +2145;DOUBLE-STRUCK ITALIC CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +2146;DOUBLE-STRUCK ITALIC SMALL D;Ll;0;L; 0064;;;;N;;;;; +2147;DOUBLE-STRUCK ITALIC SMALL E;Ll;0;L; 0065;;;;N;;;;; +2148;DOUBLE-STRUCK ITALIC SMALL I;Ll;0;L; 0069;;;;N;;;;; +2149;DOUBLE-STRUCK ITALIC SMALL J;Ll;0;L; 006A;;;;N;;;;; +214A;PROPERTY LINE;So;0;ON;;;;;N;;;;; +214B;TURNED AMPERSAND;Sm;0;ON;;;;;N;;;;; +214C;PER SIGN;So;0;ON;;;;;N;;;;; +214D;AKTIESELSKAB;So;0;ON;;;;;N;;;;; +214E;TURNED SMALL F;Ll;0;L;;;;;N;;;2132;;2132 +214F;SYMBOL FOR SAMARITAN SOURCE;So;0;L;;;;;N;;;;; +2150;VULGAR FRACTION ONE SEVENTH;No;0;ON; 0031 2044 0037;;;1/7;N;;;;; +2151;VULGAR FRACTION ONE NINTH;No;0;ON; 0031 2044 0039;;;1/9;N;;;;; +2152;VULGAR FRACTION ONE TENTH;No;0;ON; 0031 2044 0031 0030;;;1/10;N;;;;; +2153;VULGAR FRACTION ONE THIRD;No;0;ON; 0031 2044 0033;;;1/3;N;FRACTION ONE THIRD;;;; +2154;VULGAR FRACTION TWO THIRDS;No;0;ON; 0032 2044 0033;;;2/3;N;FRACTION TWO THIRDS;;;; +2155;VULGAR FRACTION ONE FIFTH;No;0;ON; 0031 2044 0035;;;1/5;N;FRACTION ONE FIFTH;;;; +2156;VULGAR FRACTION TWO FIFTHS;No;0;ON; 0032 2044 0035;;;2/5;N;FRACTION TWO FIFTHS;;;; +2157;VULGAR FRACTION THREE FIFTHS;No;0;ON; 0033 2044 0035;;;3/5;N;FRACTION THREE FIFTHS;;;; +2158;VULGAR FRACTION FOUR FIFTHS;No;0;ON; 0034 2044 0035;;;4/5;N;FRACTION FOUR FIFTHS;;;; +2159;VULGAR FRACTION ONE SIXTH;No;0;ON; 0031 2044 0036;;;1/6;N;FRACTION ONE SIXTH;;;; +215A;VULGAR FRACTION FIVE SIXTHS;No;0;ON; 0035 2044 0036;;;5/6;N;FRACTION FIVE SIXTHS;;;; +215B;VULGAR FRACTION ONE EIGHTH;No;0;ON; 0031 2044 0038;;;1/8;N;FRACTION ONE EIGHTH;;;; +215C;VULGAR FRACTION THREE EIGHTHS;No;0;ON; 0033 2044 0038;;;3/8;N;FRACTION THREE EIGHTHS;;;; +215D;VULGAR FRACTION FIVE EIGHTHS;No;0;ON; 0035 2044 0038;;;5/8;N;FRACTION FIVE EIGHTHS;;;; +215E;VULGAR FRACTION SEVEN EIGHTHS;No;0;ON; 0037 2044 0038;;;7/8;N;FRACTION SEVEN EIGHTHS;;;; +215F;FRACTION NUMERATOR ONE;No;0;ON; 0031 2044;;;1;N;;;;; +2160;ROMAN NUMERAL ONE;Nl;0;L; 0049;;;1;N;;;;2170; +2161;ROMAN NUMERAL TWO;Nl;0;L; 0049 0049;;;2;N;;;;2171; +2162;ROMAN NUMERAL THREE;Nl;0;L; 0049 0049 0049;;;3;N;;;;2172; +2163;ROMAN NUMERAL FOUR;Nl;0;L; 0049 0056;;;4;N;;;;2173; +2164;ROMAN NUMERAL FIVE;Nl;0;L; 0056;;;5;N;;;;2174; +2165;ROMAN NUMERAL SIX;Nl;0;L; 0056 0049;;;6;N;;;;2175; +2166;ROMAN NUMERAL SEVEN;Nl;0;L; 0056 0049 0049;;;7;N;;;;2176; +2167;ROMAN NUMERAL EIGHT;Nl;0;L; 0056 0049 0049 0049;;;8;N;;;;2177; +2168;ROMAN NUMERAL NINE;Nl;0;L; 0049 0058;;;9;N;;;;2178; +2169;ROMAN NUMERAL TEN;Nl;0;L; 0058;;;10;N;;;;2179; +216A;ROMAN NUMERAL ELEVEN;Nl;0;L; 0058 0049;;;11;N;;;;217A; +216B;ROMAN NUMERAL TWELVE;Nl;0;L; 0058 0049 0049;;;12;N;;;;217B; +216C;ROMAN NUMERAL FIFTY;Nl;0;L; 004C;;;50;N;;;;217C; +216D;ROMAN NUMERAL ONE HUNDRED;Nl;0;L; 0043;;;100;N;;;;217D; +216E;ROMAN NUMERAL FIVE HUNDRED;Nl;0;L; 0044;;;500;N;;;;217E; +216F;ROMAN NUMERAL ONE THOUSAND;Nl;0;L; 004D;;;1000;N;;;;217F; +2170;SMALL ROMAN NUMERAL ONE;Nl;0;L; 0069;;;1;N;;;2160;;2160 +2171;SMALL ROMAN NUMERAL TWO;Nl;0;L; 0069 0069;;;2;N;;;2161;;2161 +2172;SMALL ROMAN NUMERAL THREE;Nl;0;L; 0069 0069 0069;;;3;N;;;2162;;2162 +2173;SMALL ROMAN NUMERAL FOUR;Nl;0;L; 0069 0076;;;4;N;;;2163;;2163 +2174;SMALL ROMAN NUMERAL FIVE;Nl;0;L; 0076;;;5;N;;;2164;;2164 +2175;SMALL ROMAN NUMERAL SIX;Nl;0;L; 0076 0069;;;6;N;;;2165;;2165 +2176;SMALL ROMAN NUMERAL SEVEN;Nl;0;L; 0076 0069 0069;;;7;N;;;2166;;2166 +2177;SMALL ROMAN NUMERAL EIGHT;Nl;0;L; 0076 0069 0069 0069;;;8;N;;;2167;;2167 +2178;SMALL ROMAN NUMERAL NINE;Nl;0;L; 0069 0078;;;9;N;;;2168;;2168 +2179;SMALL ROMAN NUMERAL TEN;Nl;0;L; 0078;;;10;N;;;2169;;2169 +217A;SMALL ROMAN NUMERAL ELEVEN;Nl;0;L; 0078 0069;;;11;N;;;216A;;216A +217B;SMALL ROMAN NUMERAL TWELVE;Nl;0;L; 0078 0069 0069;;;12;N;;;216B;;216B +217C;SMALL ROMAN NUMERAL FIFTY;Nl;0;L; 006C;;;50;N;;;216C;;216C +217D;SMALL ROMAN NUMERAL ONE HUNDRED;Nl;0;L; 0063;;;100;N;;;216D;;216D +217E;SMALL ROMAN NUMERAL FIVE HUNDRED;Nl;0;L; 0064;;;500;N;;;216E;;216E +217F;SMALL ROMAN NUMERAL ONE THOUSAND;Nl;0;L; 006D;;;1000;N;;;216F;;216F +2180;ROMAN NUMERAL ONE THOUSAND C D;Nl;0;L;;;;1000;N;;;;; +2181;ROMAN NUMERAL FIVE THOUSAND;Nl;0;L;;;;5000;N;;;;; +2182;ROMAN NUMERAL TEN THOUSAND;Nl;0;L;;;;10000;N;;;;; +2183;ROMAN NUMERAL REVERSED ONE HUNDRED;Lu;0;L;;;;;N;;;;2184; +2184;LATIN SMALL LETTER REVERSED C;Ll;0;L;;;;;N;;;2183;;2183 +2185;ROMAN NUMERAL SIX LATE FORM;Nl;0;L;;;;6;N;;;;; +2186;ROMAN NUMERAL FIFTY EARLY FORM;Nl;0;L;;;;50;N;;;;; +2187;ROMAN NUMERAL FIFTY THOUSAND;Nl;0;L;;;;50000;N;;;;; +2188;ROMAN NUMERAL ONE HUNDRED THOUSAND;Nl;0;L;;;;100000;N;;;;; +2189;VULGAR FRACTION ZERO THIRDS;No;0;ON; 0030 2044 0033;;;0;N;;;;; +2190;LEFTWARDS ARROW;Sm;0;ON;;;;;N;LEFT ARROW;;;; +2191;UPWARDS ARROW;Sm;0;ON;;;;;N;UP ARROW;;;; +2192;RIGHTWARDS ARROW;Sm;0;ON;;;;;N;RIGHT ARROW;;;; +2193;DOWNWARDS ARROW;Sm;0;ON;;;;;N;DOWN ARROW;;;; +2194;LEFT RIGHT ARROW;Sm;0;ON;;;;;N;;;;; +2195;UP DOWN ARROW;So;0;ON;;;;;N;;;;; +2196;NORTH WEST ARROW;So;0;ON;;;;;N;UPPER LEFT ARROW;;;; +2197;NORTH EAST ARROW;So;0;ON;;;;;N;UPPER RIGHT ARROW;;;; +2198;SOUTH EAST ARROW;So;0;ON;;;;;N;LOWER RIGHT ARROW;;;; +2199;SOUTH WEST ARROW;So;0;ON;;;;;N;LOWER LEFT ARROW;;;; +219A;LEFTWARDS ARROW WITH STROKE;Sm;0;ON;2190 0338;;;;N;LEFT ARROW WITH STROKE;;;; +219B;RIGHTWARDS ARROW WITH STROKE;Sm;0;ON;2192 0338;;;;N;RIGHT ARROW WITH STROKE;;;; +219C;LEFTWARDS WAVE ARROW;So;0;ON;;;;;N;LEFT WAVE ARROW;;;; +219D;RIGHTWARDS WAVE ARROW;So;0;ON;;;;;N;RIGHT WAVE ARROW;;;; +219E;LEFTWARDS TWO HEADED ARROW;So;0;ON;;;;;N;LEFT TWO HEADED ARROW;;;; +219F;UPWARDS TWO HEADED ARROW;So;0;ON;;;;;N;UP TWO HEADED ARROW;;;; +21A0;RIGHTWARDS TWO HEADED ARROW;Sm;0;ON;;;;;N;RIGHT TWO HEADED ARROW;;;; +21A1;DOWNWARDS TWO HEADED ARROW;So;0;ON;;;;;N;DOWN TWO HEADED ARROW;;;; +21A2;LEFTWARDS ARROW WITH TAIL;So;0;ON;;;;;N;LEFT ARROW WITH TAIL;;;; +21A3;RIGHTWARDS ARROW WITH TAIL;Sm;0;ON;;;;;N;RIGHT ARROW WITH TAIL;;;; +21A4;LEFTWARDS ARROW FROM BAR;So;0;ON;;;;;N;LEFT ARROW FROM BAR;;;; +21A5;UPWARDS ARROW FROM BAR;So;0;ON;;;;;N;UP ARROW FROM BAR;;;; +21A6;RIGHTWARDS ARROW FROM BAR;Sm;0;ON;;;;;N;RIGHT ARROW FROM BAR;;;; +21A7;DOWNWARDS ARROW FROM BAR;So;0;ON;;;;;N;DOWN ARROW FROM BAR;;;; +21A8;UP DOWN ARROW WITH BASE;So;0;ON;;;;;N;;;;; +21A9;LEFTWARDS ARROW WITH HOOK;So;0;ON;;;;;N;LEFT ARROW WITH HOOK;;;; +21AA;RIGHTWARDS ARROW WITH HOOK;So;0;ON;;;;;N;RIGHT ARROW WITH HOOK;;;; +21AB;LEFTWARDS ARROW WITH LOOP;So;0;ON;;;;;N;LEFT ARROW WITH LOOP;;;; +21AC;RIGHTWARDS ARROW WITH LOOP;So;0;ON;;;;;N;RIGHT ARROW WITH LOOP;;;; +21AD;LEFT RIGHT WAVE ARROW;So;0;ON;;;;;N;;;;; +21AE;LEFT RIGHT ARROW WITH STROKE;Sm;0;ON;2194 0338;;;;N;;;;; +21AF;DOWNWARDS ZIGZAG ARROW;So;0;ON;;;;;N;DOWN ZIGZAG ARROW;;;; +21B0;UPWARDS ARROW WITH TIP LEFTWARDS;So;0;ON;;;;;N;UP ARROW WITH TIP LEFT;;;; +21B1;UPWARDS ARROW WITH TIP RIGHTWARDS;So;0;ON;;;;;N;UP ARROW WITH TIP RIGHT;;;; +21B2;DOWNWARDS ARROW WITH TIP LEFTWARDS;So;0;ON;;;;;N;DOWN ARROW WITH TIP LEFT;;;; +21B3;DOWNWARDS ARROW WITH TIP RIGHTWARDS;So;0;ON;;;;;N;DOWN ARROW WITH TIP RIGHT;;;; +21B4;RIGHTWARDS ARROW WITH CORNER DOWNWARDS;So;0;ON;;;;;N;RIGHT ARROW WITH CORNER DOWN;;;; +21B5;DOWNWARDS ARROW WITH CORNER LEFTWARDS;So;0;ON;;;;;N;DOWN ARROW WITH CORNER LEFT;;;; +21B6;ANTICLOCKWISE TOP SEMICIRCLE ARROW;So;0;ON;;;;;N;;;;; +21B7;CLOCKWISE TOP SEMICIRCLE ARROW;So;0;ON;;;;;N;;;;; +21B8;NORTH WEST ARROW TO LONG BAR;So;0;ON;;;;;N;UPPER LEFT ARROW TO LONG BAR;;;; +21B9;LEFTWARDS ARROW TO BAR OVER RIGHTWARDS ARROW TO BAR;So;0;ON;;;;;N;LEFT ARROW TO BAR OVER RIGHT ARROW TO BAR;;;; +21BA;ANTICLOCKWISE OPEN CIRCLE ARROW;So;0;ON;;;;;N;;;;; +21BB;CLOCKWISE OPEN CIRCLE ARROW;So;0;ON;;;;;N;;;;; +21BC;LEFTWARDS HARPOON WITH BARB UPWARDS;So;0;ON;;;;;N;LEFT HARPOON WITH BARB UP;;;; +21BD;LEFTWARDS HARPOON WITH BARB DOWNWARDS;So;0;ON;;;;;N;LEFT HARPOON WITH BARB DOWN;;;; +21BE;UPWARDS HARPOON WITH BARB RIGHTWARDS;So;0;ON;;;;;N;UP HARPOON WITH BARB RIGHT;;;; +21BF;UPWARDS HARPOON WITH BARB LEFTWARDS;So;0;ON;;;;;N;UP HARPOON WITH BARB LEFT;;;; +21C0;RIGHTWARDS HARPOON WITH BARB UPWARDS;So;0;ON;;;;;N;RIGHT HARPOON WITH BARB UP;;;; +21C1;RIGHTWARDS HARPOON WITH BARB DOWNWARDS;So;0;ON;;;;;N;RIGHT HARPOON WITH BARB DOWN;;;; +21C2;DOWNWARDS HARPOON WITH BARB RIGHTWARDS;So;0;ON;;;;;N;DOWN HARPOON WITH BARB RIGHT;;;; +21C3;DOWNWARDS HARPOON WITH BARB LEFTWARDS;So;0;ON;;;;;N;DOWN HARPOON WITH BARB LEFT;;;; +21C4;RIGHTWARDS ARROW OVER LEFTWARDS ARROW;So;0;ON;;;;;N;RIGHT ARROW OVER LEFT ARROW;;;; +21C5;UPWARDS ARROW LEFTWARDS OF DOWNWARDS ARROW;So;0;ON;;;;;N;UP ARROW LEFT OF DOWN ARROW;;;; +21C6;LEFTWARDS ARROW OVER RIGHTWARDS ARROW;So;0;ON;;;;;N;LEFT ARROW OVER RIGHT ARROW;;;; +21C7;LEFTWARDS PAIRED ARROWS;So;0;ON;;;;;N;LEFT PAIRED ARROWS;;;; +21C8;UPWARDS PAIRED ARROWS;So;0;ON;;;;;N;UP PAIRED ARROWS;;;; +21C9;RIGHTWARDS PAIRED ARROWS;So;0;ON;;;;;N;RIGHT PAIRED ARROWS;;;; +21CA;DOWNWARDS PAIRED ARROWS;So;0;ON;;;;;N;DOWN PAIRED ARROWS;;;; +21CB;LEFTWARDS HARPOON OVER RIGHTWARDS HARPOON;So;0;ON;;;;;N;LEFT HARPOON OVER RIGHT HARPOON;;;; +21CC;RIGHTWARDS HARPOON OVER LEFTWARDS HARPOON;So;0;ON;;;;;N;RIGHT HARPOON OVER LEFT HARPOON;;;; +21CD;LEFTWARDS DOUBLE ARROW WITH STROKE;So;0;ON;21D0 0338;;;;N;LEFT DOUBLE ARROW WITH STROKE;;;; +21CE;LEFT RIGHT DOUBLE ARROW WITH STROKE;Sm;0;ON;21D4 0338;;;;N;;;;; +21CF;RIGHTWARDS DOUBLE ARROW WITH STROKE;Sm;0;ON;21D2 0338;;;;N;RIGHT DOUBLE ARROW WITH STROKE;;;; +21D0;LEFTWARDS DOUBLE ARROW;So;0;ON;;;;;N;LEFT DOUBLE ARROW;;;; +21D1;UPWARDS DOUBLE ARROW;So;0;ON;;;;;N;UP DOUBLE ARROW;;;; +21D2;RIGHTWARDS DOUBLE ARROW;Sm;0;ON;;;;;N;RIGHT DOUBLE ARROW;;;; +21D3;DOWNWARDS DOUBLE ARROW;So;0;ON;;;;;N;DOWN DOUBLE ARROW;;;; +21D4;LEFT RIGHT DOUBLE ARROW;Sm;0;ON;;;;;N;;;;; +21D5;UP DOWN DOUBLE ARROW;So;0;ON;;;;;N;;;;; +21D6;NORTH WEST DOUBLE ARROW;So;0;ON;;;;;N;UPPER LEFT DOUBLE ARROW;;;; +21D7;NORTH EAST DOUBLE ARROW;So;0;ON;;;;;N;UPPER RIGHT DOUBLE ARROW;;;; +21D8;SOUTH EAST DOUBLE ARROW;So;0;ON;;;;;N;LOWER RIGHT DOUBLE ARROW;;;; +21D9;SOUTH WEST DOUBLE ARROW;So;0;ON;;;;;N;LOWER LEFT DOUBLE ARROW;;;; +21DA;LEFTWARDS TRIPLE ARROW;So;0;ON;;;;;N;LEFT TRIPLE ARROW;;;; +21DB;RIGHTWARDS TRIPLE ARROW;So;0;ON;;;;;N;RIGHT TRIPLE ARROW;;;; +21DC;LEFTWARDS SQUIGGLE ARROW;So;0;ON;;;;;N;LEFT SQUIGGLE ARROW;;;; +21DD;RIGHTWARDS SQUIGGLE ARROW;So;0;ON;;;;;N;RIGHT SQUIGGLE ARROW;;;; +21DE;UPWARDS ARROW WITH DOUBLE STROKE;So;0;ON;;;;;N;UP ARROW WITH DOUBLE STROKE;;;; +21DF;DOWNWARDS ARROW WITH DOUBLE STROKE;So;0;ON;;;;;N;DOWN ARROW WITH DOUBLE STROKE;;;; +21E0;LEFTWARDS DASHED ARROW;So;0;ON;;;;;N;LEFT DASHED ARROW;;;; +21E1;UPWARDS DASHED ARROW;So;0;ON;;;;;N;UP DASHED ARROW;;;; +21E2;RIGHTWARDS DASHED ARROW;So;0;ON;;;;;N;RIGHT DASHED ARROW;;;; +21E3;DOWNWARDS DASHED ARROW;So;0;ON;;;;;N;DOWN DASHED ARROW;;;; +21E4;LEFTWARDS ARROW TO BAR;So;0;ON;;;;;N;LEFT ARROW TO BAR;;;; +21E5;RIGHTWARDS ARROW TO BAR;So;0;ON;;;;;N;RIGHT ARROW TO BAR;;;; +21E6;LEFTWARDS WHITE ARROW;So;0;ON;;;;;N;WHITE LEFT ARROW;;;; +21E7;UPWARDS WHITE ARROW;So;0;ON;;;;;N;WHITE UP ARROW;;;; +21E8;RIGHTWARDS WHITE ARROW;So;0;ON;;;;;N;WHITE RIGHT ARROW;;;; +21E9;DOWNWARDS WHITE ARROW;So;0;ON;;;;;N;WHITE DOWN ARROW;;;; +21EA;UPWARDS WHITE ARROW FROM BAR;So;0;ON;;;;;N;WHITE UP ARROW FROM BAR;;;; +21EB;UPWARDS WHITE ARROW ON PEDESTAL;So;0;ON;;;;;N;;;;; +21EC;UPWARDS WHITE ARROW ON PEDESTAL WITH HORIZONTAL BAR;So;0;ON;;;;;N;;;;; +21ED;UPWARDS WHITE ARROW ON PEDESTAL WITH VERTICAL BAR;So;0;ON;;;;;N;;;;; +21EE;UPWARDS WHITE DOUBLE ARROW;So;0;ON;;;;;N;;;;; +21EF;UPWARDS WHITE DOUBLE ARROW ON PEDESTAL;So;0;ON;;;;;N;;;;; +21F0;RIGHTWARDS WHITE ARROW FROM WALL;So;0;ON;;;;;N;;;;; +21F1;NORTH WEST ARROW TO CORNER;So;0;ON;;;;;N;;;;; +21F2;SOUTH EAST ARROW TO CORNER;So;0;ON;;;;;N;;;;; +21F3;UP DOWN WHITE ARROW;So;0;ON;;;;;N;;;;; +21F4;RIGHT ARROW WITH SMALL CIRCLE;Sm;0;ON;;;;;N;;;;; +21F5;DOWNWARDS ARROW LEFTWARDS OF UPWARDS ARROW;Sm;0;ON;;;;;N;;;;; +21F6;THREE RIGHTWARDS ARROWS;Sm;0;ON;;;;;N;;;;; +21F7;LEFTWARDS ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +21F8;RIGHTWARDS ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +21F9;LEFT RIGHT ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +21FA;LEFTWARDS ARROW WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +21FB;RIGHTWARDS ARROW WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +21FC;LEFT RIGHT ARROW WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +21FD;LEFTWARDS OPEN-HEADED ARROW;Sm;0;ON;;;;;N;;;;; +21FE;RIGHTWARDS OPEN-HEADED ARROW;Sm;0;ON;;;;;N;;;;; +21FF;LEFT RIGHT OPEN-HEADED ARROW;Sm;0;ON;;;;;N;;;;; +2200;FOR ALL;Sm;0;ON;;;;;N;;;;; +2201;COMPLEMENT;Sm;0;ON;;;;;Y;;;;; +2202;PARTIAL DIFFERENTIAL;Sm;0;ON;;;;;Y;;;;; +2203;THERE EXISTS;Sm;0;ON;;;;;Y;;;;; +2204;THERE DOES NOT EXIST;Sm;0;ON;2203 0338;;;;Y;;;;; +2205;EMPTY SET;Sm;0;ON;;;;;N;;;;; +2206;INCREMENT;Sm;0;ON;;;;;N;;;;; +2207;NABLA;Sm;0;ON;;;;;N;;;;; +2208;ELEMENT OF;Sm;0;ON;;;;;Y;;;;; +2209;NOT AN ELEMENT OF;Sm;0;ON;2208 0338;;;;Y;;;;; +220A;SMALL ELEMENT OF;Sm;0;ON;;;;;Y;;;;; +220B;CONTAINS AS MEMBER;Sm;0;ON;;;;;Y;;;;; +220C;DOES NOT CONTAIN AS MEMBER;Sm;0;ON;220B 0338;;;;Y;;;;; +220D;SMALL CONTAINS AS MEMBER;Sm;0;ON;;;;;Y;;;;; +220E;END OF PROOF;Sm;0;ON;;;;;N;;;;; +220F;N-ARY PRODUCT;Sm;0;ON;;;;;N;;;;; +2210;N-ARY COPRODUCT;Sm;0;ON;;;;;N;;;;; +2211;N-ARY SUMMATION;Sm;0;ON;;;;;Y;;;;; +2212;MINUS SIGN;Sm;0;ES;;;;;N;;;;; +2213;MINUS-OR-PLUS SIGN;Sm;0;ET;;;;;N;;;;; +2214;DOT PLUS;Sm;0;ON;;;;;N;;;;; +2215;DIVISION SLASH;Sm;0;ON;;;;;Y;;;;; +2216;SET MINUS;Sm;0;ON;;;;;Y;;;;; +2217;ASTERISK OPERATOR;Sm;0;ON;;;;;N;;;;; +2218;RING OPERATOR;Sm;0;ON;;;;;N;;;;; +2219;BULLET OPERATOR;Sm;0;ON;;;;;N;;;;; +221A;SQUARE ROOT;Sm;0;ON;;;;;Y;;;;; +221B;CUBE ROOT;Sm;0;ON;;;;;Y;;;;; +221C;FOURTH ROOT;Sm;0;ON;;;;;Y;;;;; +221D;PROPORTIONAL TO;Sm;0;ON;;;;;Y;;;;; +221E;INFINITY;Sm;0;ON;;;;;N;;;;; +221F;RIGHT ANGLE;Sm;0;ON;;;;;Y;;;;; +2220;ANGLE;Sm;0;ON;;;;;Y;;;;; +2221;MEASURED ANGLE;Sm;0;ON;;;;;Y;;;;; +2222;SPHERICAL ANGLE;Sm;0;ON;;;;;Y;;;;; +2223;DIVIDES;Sm;0;ON;;;;;N;;;;; +2224;DOES NOT DIVIDE;Sm;0;ON;2223 0338;;;;Y;;;;; +2225;PARALLEL TO;Sm;0;ON;;;;;N;;;;; +2226;NOT PARALLEL TO;Sm;0;ON;2225 0338;;;;Y;;;;; +2227;LOGICAL AND;Sm;0;ON;;;;;N;;;;; +2228;LOGICAL OR;Sm;0;ON;;;;;N;;;;; +2229;INTERSECTION;Sm;0;ON;;;;;N;;;;; +222A;UNION;Sm;0;ON;;;;;N;;;;; +222B;INTEGRAL;Sm;0;ON;;;;;Y;;;;; +222C;DOUBLE INTEGRAL;Sm;0;ON; 222B 222B;;;;Y;;;;; +222D;TRIPLE INTEGRAL;Sm;0;ON; 222B 222B 222B;;;;Y;;;;; +222E;CONTOUR INTEGRAL;Sm;0;ON;;;;;Y;;;;; +222F;SURFACE INTEGRAL;Sm;0;ON; 222E 222E;;;;Y;;;;; +2230;VOLUME INTEGRAL;Sm;0;ON; 222E 222E 222E;;;;Y;;;;; +2231;CLOCKWISE INTEGRAL;Sm;0;ON;;;;;Y;;;;; +2232;CLOCKWISE CONTOUR INTEGRAL;Sm;0;ON;;;;;Y;;;;; +2233;ANTICLOCKWISE CONTOUR INTEGRAL;Sm;0;ON;;;;;Y;;;;; +2234;THEREFORE;Sm;0;ON;;;;;N;;;;; +2235;BECAUSE;Sm;0;ON;;;;;N;;;;; +2236;RATIO;Sm;0;ON;;;;;N;;;;; +2237;PROPORTION;Sm;0;ON;;;;;N;;;;; +2238;DOT MINUS;Sm;0;ON;;;;;N;;;;; +2239;EXCESS;Sm;0;ON;;;;;Y;;;;; +223A;GEOMETRIC PROPORTION;Sm;0;ON;;;;;N;;;;; +223B;HOMOTHETIC;Sm;0;ON;;;;;Y;;;;; +223C;TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;; +223D;REVERSED TILDE;Sm;0;ON;;;;;Y;;;;; +223E;INVERTED LAZY S;Sm;0;ON;;;;;Y;;;;; +223F;SINE WAVE;Sm;0;ON;;;;;Y;;;;; +2240;WREATH PRODUCT;Sm;0;ON;;;;;Y;;;;; +2241;NOT TILDE;Sm;0;ON;223C 0338;;;;Y;;;;; +2242;MINUS TILDE;Sm;0;ON;;;;;Y;;;;; +2243;ASYMPTOTICALLY EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2244;NOT ASYMPTOTICALLY EQUAL TO;Sm;0;ON;2243 0338;;;;Y;;;;; +2245;APPROXIMATELY EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2246;APPROXIMATELY BUT NOT ACTUALLY EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2247;NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO;Sm;0;ON;2245 0338;;;;Y;;;;; +2248;ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2249;NOT ALMOST EQUAL TO;Sm;0;ON;2248 0338;;;;Y;;;;; +224A;ALMOST EQUAL OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +224B;TRIPLE TILDE;Sm;0;ON;;;;;Y;;;;; +224C;ALL EQUAL TO;Sm;0;ON;;;;;Y;;;;; +224D;EQUIVALENT TO;Sm;0;ON;;;;;N;;;;; +224E;GEOMETRICALLY EQUIVALENT TO;Sm;0;ON;;;;;N;;;;; +224F;DIFFERENCE BETWEEN;Sm;0;ON;;;;;N;;;;; +2250;APPROACHES THE LIMIT;Sm;0;ON;;;;;N;;;;; +2251;GEOMETRICALLY EQUAL TO;Sm;0;ON;;;;;N;;;;; +2252;APPROXIMATELY EQUAL TO OR THE IMAGE OF;Sm;0;ON;;;;;Y;;;;; +2253;IMAGE OF OR APPROXIMATELY EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2254;COLON EQUALS;Sm;0;ON;;;;;Y;COLON EQUAL;;;; +2255;EQUALS COLON;Sm;0;ON;;;;;Y;EQUAL COLON;;;; +2256;RING IN EQUAL TO;Sm;0;ON;;;;;N;;;;; +2257;RING EQUAL TO;Sm;0;ON;;;;;N;;;;; +2258;CORRESPONDS TO;Sm;0;ON;;;;;N;;;;; +2259;ESTIMATES;Sm;0;ON;;;;;N;;;;; +225A;EQUIANGULAR TO;Sm;0;ON;;;;;N;;;;; +225B;STAR EQUALS;Sm;0;ON;;;;;N;;;;; +225C;DELTA EQUAL TO;Sm;0;ON;;;;;N;;;;; +225D;EQUAL TO BY DEFINITION;Sm;0;ON;;;;;N;;;;; +225E;MEASURED BY;Sm;0;ON;;;;;N;;;;; +225F;QUESTIONED EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2260;NOT EQUAL TO;Sm;0;ON;003D 0338;;;;Y;;;;; +2261;IDENTICAL TO;Sm;0;ON;;;;;N;;;;; +2262;NOT IDENTICAL TO;Sm;0;ON;2261 0338;;;;Y;;;;; +2263;STRICTLY EQUIVALENT TO;Sm;0;ON;;;;;N;;;;; +2264;LESS-THAN OR EQUAL TO;Sm;0;ON;;;;;Y;LESS THAN OR EQUAL TO;;;; +2265;GREATER-THAN OR EQUAL TO;Sm;0;ON;;;;;Y;GREATER THAN OR EQUAL TO;;;; +2266;LESS-THAN OVER EQUAL TO;Sm;0;ON;;;;;Y;LESS THAN OVER EQUAL TO;;;; +2267;GREATER-THAN OVER EQUAL TO;Sm;0;ON;;;;;Y;GREATER THAN OVER EQUAL TO;;;; +2268;LESS-THAN BUT NOT EQUAL TO;Sm;0;ON;;;;;Y;LESS THAN BUT NOT EQUAL TO;;;; +2269;GREATER-THAN BUT NOT EQUAL TO;Sm;0;ON;;;;;Y;GREATER THAN BUT NOT EQUAL TO;;;; +226A;MUCH LESS-THAN;Sm;0;ON;;;;;Y;MUCH LESS THAN;;;; +226B;MUCH GREATER-THAN;Sm;0;ON;;;;;Y;MUCH GREATER THAN;;;; +226C;BETWEEN;Sm;0;ON;;;;;N;;;;; +226D;NOT EQUIVALENT TO;Sm;0;ON;224D 0338;;;;N;;;;; +226E;NOT LESS-THAN;Sm;0;ON;003C 0338;;;;Y;NOT LESS THAN;;;; +226F;NOT GREATER-THAN;Sm;0;ON;003E 0338;;;;Y;NOT GREATER THAN;;;; +2270;NEITHER LESS-THAN NOR EQUAL TO;Sm;0;ON;2264 0338;;;;Y;NEITHER LESS THAN NOR EQUAL TO;;;; +2271;NEITHER GREATER-THAN NOR EQUAL TO;Sm;0;ON;2265 0338;;;;Y;NEITHER GREATER THAN NOR EQUAL TO;;;; +2272;LESS-THAN OR EQUIVALENT TO;Sm;0;ON;;;;;Y;LESS THAN OR EQUIVALENT TO;;;; +2273;GREATER-THAN OR EQUIVALENT TO;Sm;0;ON;;;;;Y;GREATER THAN OR EQUIVALENT TO;;;; +2274;NEITHER LESS-THAN NOR EQUIVALENT TO;Sm;0;ON;2272 0338;;;;Y;NEITHER LESS THAN NOR EQUIVALENT TO;;;; +2275;NEITHER GREATER-THAN NOR EQUIVALENT TO;Sm;0;ON;2273 0338;;;;Y;NEITHER GREATER THAN NOR EQUIVALENT TO;;;; +2276;LESS-THAN OR GREATER-THAN;Sm;0;ON;;;;;Y;LESS THAN OR GREATER THAN;;;; +2277;GREATER-THAN OR LESS-THAN;Sm;0;ON;;;;;Y;GREATER THAN OR LESS THAN;;;; +2278;NEITHER LESS-THAN NOR GREATER-THAN;Sm;0;ON;2276 0338;;;;Y;NEITHER LESS THAN NOR GREATER THAN;;;; +2279;NEITHER GREATER-THAN NOR LESS-THAN;Sm;0;ON;2277 0338;;;;Y;NEITHER GREATER THAN NOR LESS THAN;;;; +227A;PRECEDES;Sm;0;ON;;;;;Y;;;;; +227B;SUCCEEDS;Sm;0;ON;;;;;Y;;;;; +227C;PRECEDES OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +227D;SUCCEEDS OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +227E;PRECEDES OR EQUIVALENT TO;Sm;0;ON;;;;;Y;;;;; +227F;SUCCEEDS OR EQUIVALENT TO;Sm;0;ON;;;;;Y;;;;; +2280;DOES NOT PRECEDE;Sm;0;ON;227A 0338;;;;Y;;;;; +2281;DOES NOT SUCCEED;Sm;0;ON;227B 0338;;;;Y;;;;; +2282;SUBSET OF;Sm;0;ON;;;;;Y;;;;; +2283;SUPERSET OF;Sm;0;ON;;;;;Y;;;;; +2284;NOT A SUBSET OF;Sm;0;ON;2282 0338;;;;Y;;;;; +2285;NOT A SUPERSET OF;Sm;0;ON;2283 0338;;;;Y;;;;; +2286;SUBSET OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2287;SUPERSET OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2288;NEITHER A SUBSET OF NOR EQUAL TO;Sm;0;ON;2286 0338;;;;Y;;;;; +2289;NEITHER A SUPERSET OF NOR EQUAL TO;Sm;0;ON;2287 0338;;;;Y;;;;; +228A;SUBSET OF WITH NOT EQUAL TO;Sm;0;ON;;;;;Y;SUBSET OF OR NOT EQUAL TO;;;; +228B;SUPERSET OF WITH NOT EQUAL TO;Sm;0;ON;;;;;Y;SUPERSET OF OR NOT EQUAL TO;;;; +228C;MULTISET;Sm;0;ON;;;;;Y;;;;; +228D;MULTISET MULTIPLICATION;Sm;0;ON;;;;;N;;;;; +228E;MULTISET UNION;Sm;0;ON;;;;;N;;;;; +228F;SQUARE IMAGE OF;Sm;0;ON;;;;;Y;;;;; +2290;SQUARE ORIGINAL OF;Sm;0;ON;;;;;Y;;;;; +2291;SQUARE IMAGE OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2292;SQUARE ORIGINAL OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2293;SQUARE CAP;Sm;0;ON;;;;;N;;;;; +2294;SQUARE CUP;Sm;0;ON;;;;;N;;;;; +2295;CIRCLED PLUS;Sm;0;ON;;;;;N;;;;; +2296;CIRCLED MINUS;Sm;0;ON;;;;;N;;;;; +2297;CIRCLED TIMES;Sm;0;ON;;;;;N;;;;; +2298;CIRCLED DIVISION SLASH;Sm;0;ON;;;;;Y;;;;; +2299;CIRCLED DOT OPERATOR;Sm;0;ON;;;;;N;;;;; +229A;CIRCLED RING OPERATOR;Sm;0;ON;;;;;N;;;;; +229B;CIRCLED ASTERISK OPERATOR;Sm;0;ON;;;;;N;;;;; +229C;CIRCLED EQUALS;Sm;0;ON;;;;;N;;;;; +229D;CIRCLED DASH;Sm;0;ON;;;;;N;;;;; +229E;SQUARED PLUS;Sm;0;ON;;;;;N;;;;; +229F;SQUARED MINUS;Sm;0;ON;;;;;N;;;;; +22A0;SQUARED TIMES;Sm;0;ON;;;;;N;;;;; +22A1;SQUARED DOT OPERATOR;Sm;0;ON;;;;;N;;;;; +22A2;RIGHT TACK;Sm;0;ON;;;;;Y;;;;; +22A3;LEFT TACK;Sm;0;ON;;;;;Y;;;;; +22A4;DOWN TACK;Sm;0;ON;;;;;N;;;;; +22A5;UP TACK;Sm;0;ON;;;;;N;;;;; +22A6;ASSERTION;Sm;0;ON;;;;;Y;;;;; +22A7;MODELS;Sm;0;ON;;;;;Y;;;;; +22A8;TRUE;Sm;0;ON;;;;;Y;;;;; +22A9;FORCES;Sm;0;ON;;;;;Y;;;;; +22AA;TRIPLE VERTICAL BAR RIGHT TURNSTILE;Sm;0;ON;;;;;Y;;;;; +22AB;DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE;Sm;0;ON;;;;;Y;;;;; +22AC;DOES NOT PROVE;Sm;0;ON;22A2 0338;;;;Y;;;;; +22AD;NOT TRUE;Sm;0;ON;22A8 0338;;;;Y;;;;; +22AE;DOES NOT FORCE;Sm;0;ON;22A9 0338;;;;Y;;;;; +22AF;NEGATED DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE;Sm;0;ON;22AB 0338;;;;Y;;;;; +22B0;PRECEDES UNDER RELATION;Sm;0;ON;;;;;Y;;;;; +22B1;SUCCEEDS UNDER RELATION;Sm;0;ON;;;;;Y;;;;; +22B2;NORMAL SUBGROUP OF;Sm;0;ON;;;;;Y;;;;; +22B3;CONTAINS AS NORMAL SUBGROUP;Sm;0;ON;;;;;Y;;;;; +22B4;NORMAL SUBGROUP OF OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +22B5;CONTAINS AS NORMAL SUBGROUP OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +22B6;ORIGINAL OF;Sm;0;ON;;;;;Y;;;;; +22B7;IMAGE OF;Sm;0;ON;;;;;Y;;;;; +22B8;MULTIMAP;Sm;0;ON;;;;;Y;;;;; +22B9;HERMITIAN CONJUGATE MATRIX;Sm;0;ON;;;;;N;;;;; +22BA;INTERCALATE;Sm;0;ON;;;;;N;;;;; +22BB;XOR;Sm;0;ON;;;;;N;;;;; +22BC;NAND;Sm;0;ON;;;;;N;;;;; +22BD;NOR;Sm;0;ON;;;;;N;;;;; +22BE;RIGHT ANGLE WITH ARC;Sm;0;ON;;;;;Y;;;;; +22BF;RIGHT TRIANGLE;Sm;0;ON;;;;;Y;;;;; +22C0;N-ARY LOGICAL AND;Sm;0;ON;;;;;N;;;;; +22C1;N-ARY LOGICAL OR;Sm;0;ON;;;;;N;;;;; +22C2;N-ARY INTERSECTION;Sm;0;ON;;;;;N;;;;; +22C3;N-ARY UNION;Sm;0;ON;;;;;N;;;;; +22C4;DIAMOND OPERATOR;Sm;0;ON;;;;;N;;;;; +22C5;DOT OPERATOR;Sm;0;ON;;;;;N;;;;; +22C6;STAR OPERATOR;Sm;0;ON;;;;;N;;;;; +22C7;DIVISION TIMES;Sm;0;ON;;;;;N;;;;; +22C8;BOWTIE;Sm;0;ON;;;;;N;;;;; +22C9;LEFT NORMAL FACTOR SEMIDIRECT PRODUCT;Sm;0;ON;;;;;Y;;;;; +22CA;RIGHT NORMAL FACTOR SEMIDIRECT PRODUCT;Sm;0;ON;;;;;Y;;;;; +22CB;LEFT SEMIDIRECT PRODUCT;Sm;0;ON;;;;;Y;;;;; +22CC;RIGHT SEMIDIRECT PRODUCT;Sm;0;ON;;;;;Y;;;;; +22CD;REVERSED TILDE EQUALS;Sm;0;ON;;;;;Y;;;;; +22CE;CURLY LOGICAL OR;Sm;0;ON;;;;;N;;;;; +22CF;CURLY LOGICAL AND;Sm;0;ON;;;;;N;;;;; +22D0;DOUBLE SUBSET;Sm;0;ON;;;;;Y;;;;; +22D1;DOUBLE SUPERSET;Sm;0;ON;;;;;Y;;;;; +22D2;DOUBLE INTERSECTION;Sm;0;ON;;;;;N;;;;; +22D3;DOUBLE UNION;Sm;0;ON;;;;;N;;;;; +22D4;PITCHFORK;Sm;0;ON;;;;;N;;;;; +22D5;EQUAL AND PARALLEL TO;Sm;0;ON;;;;;N;;;;; +22D6;LESS-THAN WITH DOT;Sm;0;ON;;;;;Y;LESS THAN WITH DOT;;;; +22D7;GREATER-THAN WITH DOT;Sm;0;ON;;;;;Y;GREATER THAN WITH DOT;;;; +22D8;VERY MUCH LESS-THAN;Sm;0;ON;;;;;Y;VERY MUCH LESS THAN;;;; +22D9;VERY MUCH GREATER-THAN;Sm;0;ON;;;;;Y;VERY MUCH GREATER THAN;;;; +22DA;LESS-THAN EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;LESS THAN EQUAL TO OR GREATER THAN;;;; +22DB;GREATER-THAN EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;GREATER THAN EQUAL TO OR LESS THAN;;;; +22DC;EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;EQUAL TO OR LESS THAN;;;; +22DD;EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;EQUAL TO OR GREATER THAN;;;; +22DE;EQUAL TO OR PRECEDES;Sm;0;ON;;;;;Y;;;;; +22DF;EQUAL TO OR SUCCEEDS;Sm;0;ON;;;;;Y;;;;; +22E0;DOES NOT PRECEDE OR EQUAL;Sm;0;ON;227C 0338;;;;Y;;;;; +22E1;DOES NOT SUCCEED OR EQUAL;Sm;0;ON;227D 0338;;;;Y;;;;; +22E2;NOT SQUARE IMAGE OF OR EQUAL TO;Sm;0;ON;2291 0338;;;;Y;;;;; +22E3;NOT SQUARE ORIGINAL OF OR EQUAL TO;Sm;0;ON;2292 0338;;;;Y;;;;; +22E4;SQUARE IMAGE OF OR NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +22E5;SQUARE ORIGINAL OF OR NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +22E6;LESS-THAN BUT NOT EQUIVALENT TO;Sm;0;ON;;;;;Y;LESS THAN BUT NOT EQUIVALENT TO;;;; +22E7;GREATER-THAN BUT NOT EQUIVALENT TO;Sm;0;ON;;;;;Y;GREATER THAN BUT NOT EQUIVALENT TO;;;; +22E8;PRECEDES BUT NOT EQUIVALENT TO;Sm;0;ON;;;;;Y;;;;; +22E9;SUCCEEDS BUT NOT EQUIVALENT TO;Sm;0;ON;;;;;Y;;;;; +22EA;NOT NORMAL SUBGROUP OF;Sm;0;ON;22B2 0338;;;;Y;;;;; +22EB;DOES NOT CONTAIN AS NORMAL SUBGROUP;Sm;0;ON;22B3 0338;;;;Y;;;;; +22EC;NOT NORMAL SUBGROUP OF OR EQUAL TO;Sm;0;ON;22B4 0338;;;;Y;;;;; +22ED;DOES NOT CONTAIN AS NORMAL SUBGROUP OR EQUAL;Sm;0;ON;22B5 0338;;;;Y;;;;; +22EE;VERTICAL ELLIPSIS;Sm;0;ON;;;;;N;;;;; +22EF;MIDLINE HORIZONTAL ELLIPSIS;Sm;0;ON;;;;;N;;;;; +22F0;UP RIGHT DIAGONAL ELLIPSIS;Sm;0;ON;;;;;Y;;;;; +22F1;DOWN RIGHT DIAGONAL ELLIPSIS;Sm;0;ON;;;;;Y;;;;; +22F2;ELEMENT OF WITH LONG HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;; +22F3;ELEMENT OF WITH VERTICAL BAR AT END OF HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;; +22F4;SMALL ELEMENT OF WITH VERTICAL BAR AT END OF HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;; +22F5;ELEMENT OF WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;; +22F6;ELEMENT OF WITH OVERBAR;Sm;0;ON;;;;;Y;;;;; +22F7;SMALL ELEMENT OF WITH OVERBAR;Sm;0;ON;;;;;Y;;;;; +22F8;ELEMENT OF WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;; +22F9;ELEMENT OF WITH TWO HORIZONTAL STROKES;Sm;0;ON;;;;;Y;;;;; +22FA;CONTAINS WITH LONG HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;; +22FB;CONTAINS WITH VERTICAL BAR AT END OF HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;; +22FC;SMALL CONTAINS WITH VERTICAL BAR AT END OF HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;; +22FD;CONTAINS WITH OVERBAR;Sm;0;ON;;;;;Y;;;;; +22FE;SMALL CONTAINS WITH OVERBAR;Sm;0;ON;;;;;Y;;;;; +22FF;Z NOTATION BAG MEMBERSHIP;Sm;0;ON;;;;;Y;;;;; +2300;DIAMETER SIGN;So;0;ON;;;;;N;;;;; +2301;ELECTRIC ARROW;So;0;ON;;;;;N;;;;; +2302;HOUSE;So;0;ON;;;;;N;;;;; +2303;UP ARROWHEAD;So;0;ON;;;;;N;;;;; +2304;DOWN ARROWHEAD;So;0;ON;;;;;N;;;;; +2305;PROJECTIVE;So;0;ON;;;;;N;;;;; +2306;PERSPECTIVE;So;0;ON;;;;;N;;;;; +2307;WAVY LINE;So;0;ON;;;;;N;;;;; +2308;LEFT CEILING;Sm;0;ON;;;;;Y;;;;; +2309;RIGHT CEILING;Sm;0;ON;;;;;Y;;;;; +230A;LEFT FLOOR;Sm;0;ON;;;;;Y;;;;; +230B;RIGHT FLOOR;Sm;0;ON;;;;;Y;;;;; +230C;BOTTOM RIGHT CROP;So;0;ON;;;;;N;;;;; +230D;BOTTOM LEFT CROP;So;0;ON;;;;;N;;;;; +230E;TOP RIGHT CROP;So;0;ON;;;;;N;;;;; +230F;TOP LEFT CROP;So;0;ON;;;;;N;;;;; +2310;REVERSED NOT SIGN;So;0;ON;;;;;N;;;;; +2311;SQUARE LOZENGE;So;0;ON;;;;;N;;;;; +2312;ARC;So;0;ON;;;;;N;;;;; +2313;SEGMENT;So;0;ON;;;;;N;;;;; +2314;SECTOR;So;0;ON;;;;;N;;;;; +2315;TELEPHONE RECORDER;So;0;ON;;;;;N;;;;; +2316;POSITION INDICATOR;So;0;ON;;;;;N;;;;; +2317;VIEWDATA SQUARE;So;0;ON;;;;;N;;;;; +2318;PLACE OF INTEREST SIGN;So;0;ON;;;;;N;COMMAND KEY;;;; +2319;TURNED NOT SIGN;So;0;ON;;;;;N;;;;; +231A;WATCH;So;0;ON;;;;;N;;;;; +231B;HOURGLASS;So;0;ON;;;;;N;;;;; +231C;TOP LEFT CORNER;So;0;ON;;;;;N;;;;; +231D;TOP RIGHT CORNER;So;0;ON;;;;;N;;;;; +231E;BOTTOM LEFT CORNER;So;0;ON;;;;;N;;;;; +231F;BOTTOM RIGHT CORNER;So;0;ON;;;;;N;;;;; +2320;TOP HALF INTEGRAL;Sm;0;ON;;;;;Y;;;;; +2321;BOTTOM HALF INTEGRAL;Sm;0;ON;;;;;Y;;;;; +2322;FROWN;So;0;ON;;;;;N;;;;; +2323;SMILE;So;0;ON;;;;;N;;;;; +2324;UP ARROWHEAD BETWEEN TWO HORIZONTAL BARS;So;0;ON;;;;;N;ENTER KEY;;;; +2325;OPTION KEY;So;0;ON;;;;;N;;;;; +2326;ERASE TO THE RIGHT;So;0;ON;;;;;N;DELETE TO THE RIGHT KEY;;;; +2327;X IN A RECTANGLE BOX;So;0;ON;;;;;N;CLEAR KEY;;;; +2328;KEYBOARD;So;0;ON;;;;;N;;;;; +2329;LEFT-POINTING ANGLE BRACKET;Ps;0;ON;3008;;;;Y;BRA;;;; +232A;RIGHT-POINTING ANGLE BRACKET;Pe;0;ON;3009;;;;Y;KET;;;; +232B;ERASE TO THE LEFT;So;0;ON;;;;;N;DELETE TO THE LEFT KEY;;;; +232C;BENZENE RING;So;0;ON;;;;;N;;;;; +232D;CYLINDRICITY;So;0;ON;;;;;N;;;;; +232E;ALL AROUND-PROFILE;So;0;ON;;;;;N;;;;; +232F;SYMMETRY;So;0;ON;;;;;N;;;;; +2330;TOTAL RUNOUT;So;0;ON;;;;;N;;;;; +2331;DIMENSION ORIGIN;So;0;ON;;;;;N;;;;; +2332;CONICAL TAPER;So;0;ON;;;;;N;;;;; +2333;SLOPE;So;0;ON;;;;;N;;;;; +2334;COUNTERBORE;So;0;ON;;;;;N;;;;; +2335;COUNTERSINK;So;0;ON;;;;;N;;;;; +2336;APL FUNCTIONAL SYMBOL I-BEAM;So;0;L;;;;;N;;;;; +2337;APL FUNCTIONAL SYMBOL SQUISH QUAD;So;0;L;;;;;N;;;;; +2338;APL FUNCTIONAL SYMBOL QUAD EQUAL;So;0;L;;;;;N;;;;; +2339;APL FUNCTIONAL SYMBOL QUAD DIVIDE;So;0;L;;;;;N;;;;; +233A;APL FUNCTIONAL SYMBOL QUAD DIAMOND;So;0;L;;;;;N;;;;; +233B;APL FUNCTIONAL SYMBOL QUAD JOT;So;0;L;;;;;N;;;;; +233C;APL FUNCTIONAL SYMBOL QUAD CIRCLE;So;0;L;;;;;N;;;;; +233D;APL FUNCTIONAL SYMBOL CIRCLE STILE;So;0;L;;;;;N;;;;; +233E;APL FUNCTIONAL SYMBOL CIRCLE JOT;So;0;L;;;;;N;;;;; +233F;APL FUNCTIONAL SYMBOL SLASH BAR;So;0;L;;;;;N;;;;; +2340;APL FUNCTIONAL SYMBOL BACKSLASH BAR;So;0;L;;;;;N;;;;; +2341;APL FUNCTIONAL SYMBOL QUAD SLASH;So;0;L;;;;;N;;;;; +2342;APL FUNCTIONAL SYMBOL QUAD BACKSLASH;So;0;L;;;;;N;;;;; +2343;APL FUNCTIONAL SYMBOL QUAD LESS-THAN;So;0;L;;;;;N;;;;; +2344;APL FUNCTIONAL SYMBOL QUAD GREATER-THAN;So;0;L;;;;;N;;;;; +2345;APL FUNCTIONAL SYMBOL LEFTWARDS VANE;So;0;L;;;;;N;;;;; +2346;APL FUNCTIONAL SYMBOL RIGHTWARDS VANE;So;0;L;;;;;N;;;;; +2347;APL FUNCTIONAL SYMBOL QUAD LEFTWARDS ARROW;So;0;L;;;;;N;;;;; +2348;APL FUNCTIONAL SYMBOL QUAD RIGHTWARDS ARROW;So;0;L;;;;;N;;;;; +2349;APL FUNCTIONAL SYMBOL CIRCLE BACKSLASH;So;0;L;;;;;N;;;;; +234A;APL FUNCTIONAL SYMBOL DOWN TACK UNDERBAR;So;0;L;;;;;N;;;;; +234B;APL FUNCTIONAL SYMBOL DELTA STILE;So;0;L;;;;;N;;;;; +234C;APL FUNCTIONAL SYMBOL QUAD DOWN CARET;So;0;L;;;;;N;;;;; +234D;APL FUNCTIONAL SYMBOL QUAD DELTA;So;0;L;;;;;N;;;;; +234E;APL FUNCTIONAL SYMBOL DOWN TACK JOT;So;0;L;;;;;N;;;;; +234F;APL FUNCTIONAL SYMBOL UPWARDS VANE;So;0;L;;;;;N;;;;; +2350;APL FUNCTIONAL SYMBOL QUAD UPWARDS ARROW;So;0;L;;;;;N;;;;; +2351;APL FUNCTIONAL SYMBOL UP TACK OVERBAR;So;0;L;;;;;N;;;;; +2352;APL FUNCTIONAL SYMBOL DEL STILE;So;0;L;;;;;N;;;;; +2353;APL FUNCTIONAL SYMBOL QUAD UP CARET;So;0;L;;;;;N;;;;; +2354;APL FUNCTIONAL SYMBOL QUAD DEL;So;0;L;;;;;N;;;;; +2355;APL FUNCTIONAL SYMBOL UP TACK JOT;So;0;L;;;;;N;;;;; +2356;APL FUNCTIONAL SYMBOL DOWNWARDS VANE;So;0;L;;;;;N;;;;; +2357;APL FUNCTIONAL SYMBOL QUAD DOWNWARDS ARROW;So;0;L;;;;;N;;;;; +2358;APL FUNCTIONAL SYMBOL QUOTE UNDERBAR;So;0;L;;;;;N;;;;; +2359;APL FUNCTIONAL SYMBOL DELTA UNDERBAR;So;0;L;;;;;N;;;;; +235A;APL FUNCTIONAL SYMBOL DIAMOND UNDERBAR;So;0;L;;;;;N;;;;; +235B;APL FUNCTIONAL SYMBOL JOT UNDERBAR;So;0;L;;;;;N;;;;; +235C;APL FUNCTIONAL SYMBOL CIRCLE UNDERBAR;So;0;L;;;;;N;;;;; +235D;APL FUNCTIONAL SYMBOL UP SHOE JOT;So;0;L;;;;;N;;;;; +235E;APL FUNCTIONAL SYMBOL QUOTE QUAD;So;0;L;;;;;N;;;;; +235F;APL FUNCTIONAL SYMBOL CIRCLE STAR;So;0;L;;;;;N;;;;; +2360;APL FUNCTIONAL SYMBOL QUAD COLON;So;0;L;;;;;N;;;;; +2361;APL FUNCTIONAL SYMBOL UP TACK DIAERESIS;So;0;L;;;;;N;;;;; +2362;APL FUNCTIONAL SYMBOL DEL DIAERESIS;So;0;L;;;;;N;;;;; +2363;APL FUNCTIONAL SYMBOL STAR DIAERESIS;So;0;L;;;;;N;;;;; +2364;APL FUNCTIONAL SYMBOL JOT DIAERESIS;So;0;L;;;;;N;;;;; +2365;APL FUNCTIONAL SYMBOL CIRCLE DIAERESIS;So;0;L;;;;;N;;;;; +2366;APL FUNCTIONAL SYMBOL DOWN SHOE STILE;So;0;L;;;;;N;;;;; +2367;APL FUNCTIONAL SYMBOL LEFT SHOE STILE;So;0;L;;;;;N;;;;; +2368;APL FUNCTIONAL SYMBOL TILDE DIAERESIS;So;0;L;;;;;N;;;;; +2369;APL FUNCTIONAL SYMBOL GREATER-THAN DIAERESIS;So;0;L;;;;;N;;;;; +236A;APL FUNCTIONAL SYMBOL COMMA BAR;So;0;L;;;;;N;;;;; +236B;APL FUNCTIONAL SYMBOL DEL TILDE;So;0;L;;;;;N;;;;; +236C;APL FUNCTIONAL SYMBOL ZILDE;So;0;L;;;;;N;;;;; +236D;APL FUNCTIONAL SYMBOL STILE TILDE;So;0;L;;;;;N;;;;; +236E;APL FUNCTIONAL SYMBOL SEMICOLON UNDERBAR;So;0;L;;;;;N;;;;; +236F;APL FUNCTIONAL SYMBOL QUAD NOT EQUAL;So;0;L;;;;;N;;;;; +2370;APL FUNCTIONAL SYMBOL QUAD QUESTION;So;0;L;;;;;N;;;;; +2371;APL FUNCTIONAL SYMBOL DOWN CARET TILDE;So;0;L;;;;;N;;;;; +2372;APL FUNCTIONAL SYMBOL UP CARET TILDE;So;0;L;;;;;N;;;;; +2373;APL FUNCTIONAL SYMBOL IOTA;So;0;L;;;;;N;;;;; +2374;APL FUNCTIONAL SYMBOL RHO;So;0;L;;;;;N;;;;; +2375;APL FUNCTIONAL SYMBOL OMEGA;So;0;L;;;;;N;;;;; +2376;APL FUNCTIONAL SYMBOL ALPHA UNDERBAR;So;0;L;;;;;N;;;;; +2377;APL FUNCTIONAL SYMBOL EPSILON UNDERBAR;So;0;L;;;;;N;;;;; +2378;APL FUNCTIONAL SYMBOL IOTA UNDERBAR;So;0;L;;;;;N;;;;; +2379;APL FUNCTIONAL SYMBOL OMEGA UNDERBAR;So;0;L;;;;;N;;;;; +237A;APL FUNCTIONAL SYMBOL ALPHA;So;0;L;;;;;N;;;;; +237B;NOT CHECK MARK;So;0;ON;;;;;N;;;;; +237C;RIGHT ANGLE WITH DOWNWARDS ZIGZAG ARROW;Sm;0;ON;;;;;N;;;;; +237D;SHOULDERED OPEN BOX;So;0;ON;;;;;N;;;;; +237E;BELL SYMBOL;So;0;ON;;;;;N;;;;; +237F;VERTICAL LINE WITH MIDDLE DOT;So;0;ON;;;;;N;;;;; +2380;INSERTION SYMBOL;So;0;ON;;;;;N;;;;; +2381;CONTINUOUS UNDERLINE SYMBOL;So;0;ON;;;;;N;;;;; +2382;DISCONTINUOUS UNDERLINE SYMBOL;So;0;ON;;;;;N;;;;; +2383;EMPHASIS SYMBOL;So;0;ON;;;;;N;;;;; +2384;COMPOSITION SYMBOL;So;0;ON;;;;;N;;;;; +2385;WHITE SQUARE WITH CENTRE VERTICAL LINE;So;0;ON;;;;;N;;;;; +2386;ENTER SYMBOL;So;0;ON;;;;;N;;;;; +2387;ALTERNATIVE KEY SYMBOL;So;0;ON;;;;;N;;;;; +2388;HELM SYMBOL;So;0;ON;;;;;N;;;;; +2389;CIRCLED HORIZONTAL BAR WITH NOTCH;So;0;ON;;;;;N;;;;; +238A;CIRCLED TRIANGLE DOWN;So;0;ON;;;;;N;;;;; +238B;BROKEN CIRCLE WITH NORTHWEST ARROW;So;0;ON;;;;;N;;;;; +238C;UNDO SYMBOL;So;0;ON;;;;;N;;;;; +238D;MONOSTABLE SYMBOL;So;0;ON;;;;;N;;;;; +238E;HYSTERESIS SYMBOL;So;0;ON;;;;;N;;;;; +238F;OPEN-CIRCUIT-OUTPUT H-TYPE SYMBOL;So;0;ON;;;;;N;;;;; +2390;OPEN-CIRCUIT-OUTPUT L-TYPE SYMBOL;So;0;ON;;;;;N;;;;; +2391;PASSIVE-PULL-DOWN-OUTPUT SYMBOL;So;0;ON;;;;;N;;;;; +2392;PASSIVE-PULL-UP-OUTPUT SYMBOL;So;0;ON;;;;;N;;;;; +2393;DIRECT CURRENT SYMBOL FORM TWO;So;0;ON;;;;;N;;;;; +2394;SOFTWARE-FUNCTION SYMBOL;So;0;ON;;;;;N;;;;; +2395;APL FUNCTIONAL SYMBOL QUAD;So;0;L;;;;;N;;;;; +2396;DECIMAL SEPARATOR KEY SYMBOL;So;0;ON;;;;;N;;;;; +2397;PREVIOUS PAGE;So;0;ON;;;;;N;;;;; +2398;NEXT PAGE;So;0;ON;;;;;N;;;;; +2399;PRINT SCREEN SYMBOL;So;0;ON;;;;;N;;;;; +239A;CLEAR SCREEN SYMBOL;So;0;ON;;;;;N;;;;; +239B;LEFT PARENTHESIS UPPER HOOK;Sm;0;ON;;;;;N;;;;; +239C;LEFT PARENTHESIS EXTENSION;Sm;0;ON;;;;;N;;;;; +239D;LEFT PARENTHESIS LOWER HOOK;Sm;0;ON;;;;;N;;;;; +239E;RIGHT PARENTHESIS UPPER HOOK;Sm;0;ON;;;;;N;;;;; +239F;RIGHT PARENTHESIS EXTENSION;Sm;0;ON;;;;;N;;;;; +23A0;RIGHT PARENTHESIS LOWER HOOK;Sm;0;ON;;;;;N;;;;; +23A1;LEFT SQUARE BRACKET UPPER CORNER;Sm;0;ON;;;;;N;;;;; +23A2;LEFT SQUARE BRACKET EXTENSION;Sm;0;ON;;;;;N;;;;; +23A3;LEFT SQUARE BRACKET LOWER CORNER;Sm;0;ON;;;;;N;;;;; +23A4;RIGHT SQUARE BRACKET UPPER CORNER;Sm;0;ON;;;;;N;;;;; +23A5;RIGHT SQUARE BRACKET EXTENSION;Sm;0;ON;;;;;N;;;;; +23A6;RIGHT SQUARE BRACKET LOWER CORNER;Sm;0;ON;;;;;N;;;;; +23A7;LEFT CURLY BRACKET UPPER HOOK;Sm;0;ON;;;;;N;;;;; +23A8;LEFT CURLY BRACKET MIDDLE PIECE;Sm;0;ON;;;;;N;;;;; +23A9;LEFT CURLY BRACKET LOWER HOOK;Sm;0;ON;;;;;N;;;;; +23AA;CURLY BRACKET EXTENSION;Sm;0;ON;;;;;N;;;;; +23AB;RIGHT CURLY BRACKET UPPER HOOK;Sm;0;ON;;;;;N;;;;; +23AC;RIGHT CURLY BRACKET MIDDLE PIECE;Sm;0;ON;;;;;N;;;;; +23AD;RIGHT CURLY BRACKET LOWER HOOK;Sm;0;ON;;;;;N;;;;; +23AE;INTEGRAL EXTENSION;Sm;0;ON;;;;;N;;;;; +23AF;HORIZONTAL LINE EXTENSION;Sm;0;ON;;;;;N;;;;; +23B0;UPPER LEFT OR LOWER RIGHT CURLY BRACKET SECTION;Sm;0;ON;;;;;N;;;;; +23B1;UPPER RIGHT OR LOWER LEFT CURLY BRACKET SECTION;Sm;0;ON;;;;;N;;;;; +23B2;SUMMATION TOP;Sm;0;ON;;;;;N;;;;; +23B3;SUMMATION BOTTOM;Sm;0;ON;;;;;N;;;;; +23B4;TOP SQUARE BRACKET;So;0;ON;;;;;N;;;;; +23B5;BOTTOM SQUARE BRACKET;So;0;ON;;;;;N;;;;; +23B6;BOTTOM SQUARE BRACKET OVER TOP SQUARE BRACKET;So;0;ON;;;;;N;;;;; +23B7;RADICAL SYMBOL BOTTOM;So;0;ON;;;;;N;;;;; +23B8;LEFT VERTICAL BOX LINE;So;0;ON;;;;;N;;;;; +23B9;RIGHT VERTICAL BOX LINE;So;0;ON;;;;;N;;;;; +23BA;HORIZONTAL SCAN LINE-1;So;0;ON;;;;;N;;;;; +23BB;HORIZONTAL SCAN LINE-3;So;0;ON;;;;;N;;;;; +23BC;HORIZONTAL SCAN LINE-7;So;0;ON;;;;;N;;;;; +23BD;HORIZONTAL SCAN LINE-9;So;0;ON;;;;;N;;;;; +23BE;DENTISTRY SYMBOL LIGHT VERTICAL AND TOP RIGHT;So;0;ON;;;;;N;;;;; +23BF;DENTISTRY SYMBOL LIGHT VERTICAL AND BOTTOM RIGHT;So;0;ON;;;;;N;;;;; +23C0;DENTISTRY SYMBOL LIGHT VERTICAL WITH CIRCLE;So;0;ON;;;;;N;;;;; +23C1;DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL WITH CIRCLE;So;0;ON;;;;;N;;;;; +23C2;DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL WITH CIRCLE;So;0;ON;;;;;N;;;;; +23C3;DENTISTRY SYMBOL LIGHT VERTICAL WITH TRIANGLE;So;0;ON;;;;;N;;;;; +23C4;DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL WITH TRIANGLE;So;0;ON;;;;;N;;;;; +23C5;DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL WITH TRIANGLE;So;0;ON;;;;;N;;;;; +23C6;DENTISTRY SYMBOL LIGHT VERTICAL AND WAVE;So;0;ON;;;;;N;;;;; +23C7;DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL WITH WAVE;So;0;ON;;;;;N;;;;; +23C8;DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL WITH WAVE;So;0;ON;;;;;N;;;;; +23C9;DENTISTRY SYMBOL LIGHT DOWN AND HORIZONTAL;So;0;ON;;;;;N;;;;; +23CA;DENTISTRY SYMBOL LIGHT UP AND HORIZONTAL;So;0;ON;;;;;N;;;;; +23CB;DENTISTRY SYMBOL LIGHT VERTICAL AND TOP LEFT;So;0;ON;;;;;N;;;;; +23CC;DENTISTRY SYMBOL LIGHT VERTICAL AND BOTTOM LEFT;So;0;ON;;;;;N;;;;; +23CD;SQUARE FOOT;So;0;ON;;;;;N;;;;; +23CE;RETURN SYMBOL;So;0;ON;;;;;N;;;;; +23CF;EJECT SYMBOL;So;0;ON;;;;;N;;;;; +23D0;VERTICAL LINE EXTENSION;So;0;ON;;;;;N;;;;; +23D1;METRICAL BREVE;So;0;ON;;;;;N;;;;; +23D2;METRICAL LONG OVER SHORT;So;0;ON;;;;;N;;;;; +23D3;METRICAL SHORT OVER LONG;So;0;ON;;;;;N;;;;; +23D4;METRICAL LONG OVER TWO SHORTS;So;0;ON;;;;;N;;;;; +23D5;METRICAL TWO SHORTS OVER LONG;So;0;ON;;;;;N;;;;; +23D6;METRICAL TWO SHORTS JOINED;So;0;ON;;;;;N;;;;; +23D7;METRICAL TRISEME;So;0;ON;;;;;N;;;;; +23D8;METRICAL TETRASEME;So;0;ON;;;;;N;;;;; +23D9;METRICAL PENTASEME;So;0;ON;;;;;N;;;;; +23DA;EARTH GROUND;So;0;ON;;;;;N;;;;; +23DB;FUSE;So;0;ON;;;;;N;;;;; +23DC;TOP PARENTHESIS;Sm;0;ON;;;;;N;;;;; +23DD;BOTTOM PARENTHESIS;Sm;0;ON;;;;;N;;;;; +23DE;TOP CURLY BRACKET;Sm;0;ON;;;;;N;;;;; +23DF;BOTTOM CURLY BRACKET;Sm;0;ON;;;;;N;;;;; +23E0;TOP TORTOISE SHELL BRACKET;Sm;0;ON;;;;;N;;;;; +23E1;BOTTOM TORTOISE SHELL BRACKET;Sm;0;ON;;;;;N;;;;; +23E2;WHITE TRAPEZIUM;So;0;ON;;;;;N;;;;; +23E3;BENZENE RING WITH CIRCLE;So;0;ON;;;;;N;;;;; +23E4;STRAIGHTNESS;So;0;ON;;;;;N;;;;; +23E5;FLATNESS;So;0;ON;;;;;N;;;;; +23E6;AC CURRENT;So;0;ON;;;;;N;;;;; +23E7;ELECTRICAL INTERSECTION;So;0;ON;;;;;N;;;;; +23E8;DECIMAL EXPONENT SYMBOL;So;0;ON;;;;;N;;;;; +23E9;BLACK RIGHT-POINTING DOUBLE TRIANGLE;So;0;ON;;;;;N;;;;; +23EA;BLACK LEFT-POINTING DOUBLE TRIANGLE;So;0;ON;;;;;N;;;;; +23EB;BLACK UP-POINTING DOUBLE TRIANGLE;So;0;ON;;;;;N;;;;; +23EC;BLACK DOWN-POINTING DOUBLE TRIANGLE;So;0;ON;;;;;N;;;;; +23ED;BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR;So;0;ON;;;;;N;;;;; +23EE;BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR;So;0;ON;;;;;N;;;;; +23EF;BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR;So;0;ON;;;;;N;;;;; +23F0;ALARM CLOCK;So;0;ON;;;;;N;;;;; +23F1;STOPWATCH;So;0;ON;;;;;N;;;;; +23F2;TIMER CLOCK;So;0;ON;;;;;N;;;;; +23F3;HOURGLASS WITH FLOWING SAND;So;0;ON;;;;;N;;;;; +2400;SYMBOL FOR NULL;So;0;ON;;;;;N;GRAPHIC FOR NULL;;;; +2401;SYMBOL FOR START OF HEADING;So;0;ON;;;;;N;GRAPHIC FOR START OF HEADING;;;; +2402;SYMBOL FOR START OF TEXT;So;0;ON;;;;;N;GRAPHIC FOR START OF TEXT;;;; +2403;SYMBOL FOR END OF TEXT;So;0;ON;;;;;N;GRAPHIC FOR END OF TEXT;;;; +2404;SYMBOL FOR END OF TRANSMISSION;So;0;ON;;;;;N;GRAPHIC FOR END OF TRANSMISSION;;;; +2405;SYMBOL FOR ENQUIRY;So;0;ON;;;;;N;GRAPHIC FOR ENQUIRY;;;; +2406;SYMBOL FOR ACKNOWLEDGE;So;0;ON;;;;;N;GRAPHIC FOR ACKNOWLEDGE;;;; +2407;SYMBOL FOR BELL;So;0;ON;;;;;N;GRAPHIC FOR BELL;;;; +2408;SYMBOL FOR BACKSPACE;So;0;ON;;;;;N;GRAPHIC FOR BACKSPACE;;;; +2409;SYMBOL FOR HORIZONTAL TABULATION;So;0;ON;;;;;N;GRAPHIC FOR HORIZONTAL TABULATION;;;; +240A;SYMBOL FOR LINE FEED;So;0;ON;;;;;N;GRAPHIC FOR LINE FEED;;;; +240B;SYMBOL FOR VERTICAL TABULATION;So;0;ON;;;;;N;GRAPHIC FOR VERTICAL TABULATION;;;; +240C;SYMBOL FOR FORM FEED;So;0;ON;;;;;N;GRAPHIC FOR FORM FEED;;;; +240D;SYMBOL FOR CARRIAGE RETURN;So;0;ON;;;;;N;GRAPHIC FOR CARRIAGE RETURN;;;; +240E;SYMBOL FOR SHIFT OUT;So;0;ON;;;;;N;GRAPHIC FOR SHIFT OUT;;;; +240F;SYMBOL FOR SHIFT IN;So;0;ON;;;;;N;GRAPHIC FOR SHIFT IN;;;; +2410;SYMBOL FOR DATA LINK ESCAPE;So;0;ON;;;;;N;GRAPHIC FOR DATA LINK ESCAPE;;;; +2411;SYMBOL FOR DEVICE CONTROL ONE;So;0;ON;;;;;N;GRAPHIC FOR DEVICE CONTROL ONE;;;; +2412;SYMBOL FOR DEVICE CONTROL TWO;So;0;ON;;;;;N;GRAPHIC FOR DEVICE CONTROL TWO;;;; +2413;SYMBOL FOR DEVICE CONTROL THREE;So;0;ON;;;;;N;GRAPHIC FOR DEVICE CONTROL THREE;;;; +2414;SYMBOL FOR DEVICE CONTROL FOUR;So;0;ON;;;;;N;GRAPHIC FOR DEVICE CONTROL FOUR;;;; +2415;SYMBOL FOR NEGATIVE ACKNOWLEDGE;So;0;ON;;;;;N;GRAPHIC FOR NEGATIVE ACKNOWLEDGE;;;; +2416;SYMBOL FOR SYNCHRONOUS IDLE;So;0;ON;;;;;N;GRAPHIC FOR SYNCHRONOUS IDLE;;;; +2417;SYMBOL FOR END OF TRANSMISSION BLOCK;So;0;ON;;;;;N;GRAPHIC FOR END OF TRANSMISSION BLOCK;;;; +2418;SYMBOL FOR CANCEL;So;0;ON;;;;;N;GRAPHIC FOR CANCEL;;;; +2419;SYMBOL FOR END OF MEDIUM;So;0;ON;;;;;N;GRAPHIC FOR END OF MEDIUM;;;; +241A;SYMBOL FOR SUBSTITUTE;So;0;ON;;;;;N;GRAPHIC FOR SUBSTITUTE;;;; +241B;SYMBOL FOR ESCAPE;So;0;ON;;;;;N;GRAPHIC FOR ESCAPE;;;; +241C;SYMBOL FOR FILE SEPARATOR;So;0;ON;;;;;N;GRAPHIC FOR FILE SEPARATOR;;;; +241D;SYMBOL FOR GROUP SEPARATOR;So;0;ON;;;;;N;GRAPHIC FOR GROUP SEPARATOR;;;; +241E;SYMBOL FOR RECORD SEPARATOR;So;0;ON;;;;;N;GRAPHIC FOR RECORD SEPARATOR;;;; +241F;SYMBOL FOR UNIT SEPARATOR;So;0;ON;;;;;N;GRAPHIC FOR UNIT SEPARATOR;;;; +2420;SYMBOL FOR SPACE;So;0;ON;;;;;N;GRAPHIC FOR SPACE;;;; +2421;SYMBOL FOR DELETE;So;0;ON;;;;;N;GRAPHIC FOR DELETE;;;; +2422;BLANK SYMBOL;So;0;ON;;;;;N;BLANK;;;; +2423;OPEN BOX;So;0;ON;;;;;N;;;;; +2424;SYMBOL FOR NEWLINE;So;0;ON;;;;;N;GRAPHIC FOR NEWLINE;;;; +2425;SYMBOL FOR DELETE FORM TWO;So;0;ON;;;;;N;;;;; +2426;SYMBOL FOR SUBSTITUTE FORM TWO;So;0;ON;;;;;N;;;;; +2440;OCR HOOK;So;0;ON;;;;;N;;;;; +2441;OCR CHAIR;So;0;ON;;;;;N;;;;; +2442;OCR FORK;So;0;ON;;;;;N;;;;; +2443;OCR INVERTED FORK;So;0;ON;;;;;N;;;;; +2444;OCR BELT BUCKLE;So;0;ON;;;;;N;;;;; +2445;OCR BOW TIE;So;0;ON;;;;;N;;;;; +2446;OCR BRANCH BANK IDENTIFICATION;So;0;ON;;;;;N;;;;; +2447;OCR AMOUNT OF CHECK;So;0;ON;;;;;N;;;;; +2448;OCR DASH;So;0;ON;;;;;N;;;;; +2449;OCR CUSTOMER ACCOUNT NUMBER;So;0;ON;;;;;N;;;;; +244A;OCR DOUBLE BACKSLASH;So;0;ON;;;;;N;;;;; +2460;CIRCLED DIGIT ONE;No;0;ON; 0031;;1;1;N;;;;; +2461;CIRCLED DIGIT TWO;No;0;ON; 0032;;2;2;N;;;;; +2462;CIRCLED DIGIT THREE;No;0;ON; 0033;;3;3;N;;;;; +2463;CIRCLED DIGIT FOUR;No;0;ON; 0034;;4;4;N;;;;; +2464;CIRCLED DIGIT FIVE;No;0;ON; 0035;;5;5;N;;;;; +2465;CIRCLED DIGIT SIX;No;0;ON; 0036;;6;6;N;;;;; +2466;CIRCLED DIGIT SEVEN;No;0;ON; 0037;;7;7;N;;;;; +2467;CIRCLED DIGIT EIGHT;No;0;ON; 0038;;8;8;N;;;;; +2468;CIRCLED DIGIT NINE;No;0;ON; 0039;;9;9;N;;;;; +2469;CIRCLED NUMBER TEN;No;0;ON; 0031 0030;;;10;N;;;;; +246A;CIRCLED NUMBER ELEVEN;No;0;ON; 0031 0031;;;11;N;;;;; +246B;CIRCLED NUMBER TWELVE;No;0;ON; 0031 0032;;;12;N;;;;; +246C;CIRCLED NUMBER THIRTEEN;No;0;ON; 0031 0033;;;13;N;;;;; +246D;CIRCLED NUMBER FOURTEEN;No;0;ON; 0031 0034;;;14;N;;;;; +246E;CIRCLED NUMBER FIFTEEN;No;0;ON; 0031 0035;;;15;N;;;;; +246F;CIRCLED NUMBER SIXTEEN;No;0;ON; 0031 0036;;;16;N;;;;; +2470;CIRCLED NUMBER SEVENTEEN;No;0;ON; 0031 0037;;;17;N;;;;; +2471;CIRCLED NUMBER EIGHTEEN;No;0;ON; 0031 0038;;;18;N;;;;; +2472;CIRCLED NUMBER NINETEEN;No;0;ON; 0031 0039;;;19;N;;;;; +2473;CIRCLED NUMBER TWENTY;No;0;ON; 0032 0030;;;20;N;;;;; +2474;PARENTHESIZED DIGIT ONE;No;0;ON; 0028 0031 0029;;1;1;N;;;;; +2475;PARENTHESIZED DIGIT TWO;No;0;ON; 0028 0032 0029;;2;2;N;;;;; +2476;PARENTHESIZED DIGIT THREE;No;0;ON; 0028 0033 0029;;3;3;N;;;;; +2477;PARENTHESIZED DIGIT FOUR;No;0;ON; 0028 0034 0029;;4;4;N;;;;; +2478;PARENTHESIZED DIGIT FIVE;No;0;ON; 0028 0035 0029;;5;5;N;;;;; +2479;PARENTHESIZED DIGIT SIX;No;0;ON; 0028 0036 0029;;6;6;N;;;;; +247A;PARENTHESIZED DIGIT SEVEN;No;0;ON; 0028 0037 0029;;7;7;N;;;;; +247B;PARENTHESIZED DIGIT EIGHT;No;0;ON; 0028 0038 0029;;8;8;N;;;;; +247C;PARENTHESIZED DIGIT NINE;No;0;ON; 0028 0039 0029;;9;9;N;;;;; +247D;PARENTHESIZED NUMBER TEN;No;0;ON; 0028 0031 0030 0029;;;10;N;;;;; +247E;PARENTHESIZED NUMBER ELEVEN;No;0;ON; 0028 0031 0031 0029;;;11;N;;;;; +247F;PARENTHESIZED NUMBER TWELVE;No;0;ON; 0028 0031 0032 0029;;;12;N;;;;; +2480;PARENTHESIZED NUMBER THIRTEEN;No;0;ON; 0028 0031 0033 0029;;;13;N;;;;; +2481;PARENTHESIZED NUMBER FOURTEEN;No;0;ON; 0028 0031 0034 0029;;;14;N;;;;; +2482;PARENTHESIZED NUMBER FIFTEEN;No;0;ON; 0028 0031 0035 0029;;;15;N;;;;; +2483;PARENTHESIZED NUMBER SIXTEEN;No;0;ON; 0028 0031 0036 0029;;;16;N;;;;; +2484;PARENTHESIZED NUMBER SEVENTEEN;No;0;ON; 0028 0031 0037 0029;;;17;N;;;;; +2485;PARENTHESIZED NUMBER EIGHTEEN;No;0;ON; 0028 0031 0038 0029;;;18;N;;;;; +2486;PARENTHESIZED NUMBER NINETEEN;No;0;ON; 0028 0031 0039 0029;;;19;N;;;;; +2487;PARENTHESIZED NUMBER TWENTY;No;0;ON; 0028 0032 0030 0029;;;20;N;;;;; +2488;DIGIT ONE FULL STOP;No;0;EN; 0031 002E;;1;1;N;DIGIT ONE PERIOD;;;; +2489;DIGIT TWO FULL STOP;No;0;EN; 0032 002E;;2;2;N;DIGIT TWO PERIOD;;;; +248A;DIGIT THREE FULL STOP;No;0;EN; 0033 002E;;3;3;N;DIGIT THREE PERIOD;;;; +248B;DIGIT FOUR FULL STOP;No;0;EN; 0034 002E;;4;4;N;DIGIT FOUR PERIOD;;;; +248C;DIGIT FIVE FULL STOP;No;0;EN; 0035 002E;;5;5;N;DIGIT FIVE PERIOD;;;; +248D;DIGIT SIX FULL STOP;No;0;EN; 0036 002E;;6;6;N;DIGIT SIX PERIOD;;;; +248E;DIGIT SEVEN FULL STOP;No;0;EN; 0037 002E;;7;7;N;DIGIT SEVEN PERIOD;;;; +248F;DIGIT EIGHT FULL STOP;No;0;EN; 0038 002E;;8;8;N;DIGIT EIGHT PERIOD;;;; +2490;DIGIT NINE FULL STOP;No;0;EN; 0039 002E;;9;9;N;DIGIT NINE PERIOD;;;; +2491;NUMBER TEN FULL STOP;No;0;EN; 0031 0030 002E;;;10;N;NUMBER TEN PERIOD;;;; +2492;NUMBER ELEVEN FULL STOP;No;0;EN; 0031 0031 002E;;;11;N;NUMBER ELEVEN PERIOD;;;; +2493;NUMBER TWELVE FULL STOP;No;0;EN; 0031 0032 002E;;;12;N;NUMBER TWELVE PERIOD;;;; +2494;NUMBER THIRTEEN FULL STOP;No;0;EN; 0031 0033 002E;;;13;N;NUMBER THIRTEEN PERIOD;;;; +2495;NUMBER FOURTEEN FULL STOP;No;0;EN; 0031 0034 002E;;;14;N;NUMBER FOURTEEN PERIOD;;;; +2496;NUMBER FIFTEEN FULL STOP;No;0;EN; 0031 0035 002E;;;15;N;NUMBER FIFTEEN PERIOD;;;; +2497;NUMBER SIXTEEN FULL STOP;No;0;EN; 0031 0036 002E;;;16;N;NUMBER SIXTEEN PERIOD;;;; +2498;NUMBER SEVENTEEN FULL STOP;No;0;EN; 0031 0037 002E;;;17;N;NUMBER SEVENTEEN PERIOD;;;; +2499;NUMBER EIGHTEEN FULL STOP;No;0;EN; 0031 0038 002E;;;18;N;NUMBER EIGHTEEN PERIOD;;;; +249A;NUMBER NINETEEN FULL STOP;No;0;EN; 0031 0039 002E;;;19;N;NUMBER NINETEEN PERIOD;;;; +249B;NUMBER TWENTY FULL STOP;No;0;EN; 0032 0030 002E;;;20;N;NUMBER TWENTY PERIOD;;;; +249C;PARENTHESIZED LATIN SMALL LETTER A;So;0;L; 0028 0061 0029;;;;N;;;;; +249D;PARENTHESIZED LATIN SMALL LETTER B;So;0;L; 0028 0062 0029;;;;N;;;;; +249E;PARENTHESIZED LATIN SMALL LETTER C;So;0;L; 0028 0063 0029;;;;N;;;;; +249F;PARENTHESIZED LATIN SMALL LETTER D;So;0;L; 0028 0064 0029;;;;N;;;;; +24A0;PARENTHESIZED LATIN SMALL LETTER E;So;0;L; 0028 0065 0029;;;;N;;;;; +24A1;PARENTHESIZED LATIN SMALL LETTER F;So;0;L; 0028 0066 0029;;;;N;;;;; +24A2;PARENTHESIZED LATIN SMALL LETTER G;So;0;L; 0028 0067 0029;;;;N;;;;; +24A3;PARENTHESIZED LATIN SMALL LETTER H;So;0;L; 0028 0068 0029;;;;N;;;;; +24A4;PARENTHESIZED LATIN SMALL LETTER I;So;0;L; 0028 0069 0029;;;;N;;;;; +24A5;PARENTHESIZED LATIN SMALL LETTER J;So;0;L; 0028 006A 0029;;;;N;;;;; +24A6;PARENTHESIZED LATIN SMALL LETTER K;So;0;L; 0028 006B 0029;;;;N;;;;; +24A7;PARENTHESIZED LATIN SMALL LETTER L;So;0;L; 0028 006C 0029;;;;N;;;;; +24A8;PARENTHESIZED LATIN SMALL LETTER M;So;0;L; 0028 006D 0029;;;;N;;;;; +24A9;PARENTHESIZED LATIN SMALL LETTER N;So;0;L; 0028 006E 0029;;;;N;;;;; +24AA;PARENTHESIZED LATIN SMALL LETTER O;So;0;L; 0028 006F 0029;;;;N;;;;; +24AB;PARENTHESIZED LATIN SMALL LETTER P;So;0;L; 0028 0070 0029;;;;N;;;;; +24AC;PARENTHESIZED LATIN SMALL LETTER Q;So;0;L; 0028 0071 0029;;;;N;;;;; +24AD;PARENTHESIZED LATIN SMALL LETTER R;So;0;L; 0028 0072 0029;;;;N;;;;; +24AE;PARENTHESIZED LATIN SMALL LETTER S;So;0;L; 0028 0073 0029;;;;N;;;;; +24AF;PARENTHESIZED LATIN SMALL LETTER T;So;0;L; 0028 0074 0029;;;;N;;;;; +24B0;PARENTHESIZED LATIN SMALL LETTER U;So;0;L; 0028 0075 0029;;;;N;;;;; +24B1;PARENTHESIZED LATIN SMALL LETTER V;So;0;L; 0028 0076 0029;;;;N;;;;; +24B2;PARENTHESIZED LATIN SMALL LETTER W;So;0;L; 0028 0077 0029;;;;N;;;;; +24B3;PARENTHESIZED LATIN SMALL LETTER X;So;0;L; 0028 0078 0029;;;;N;;;;; +24B4;PARENTHESIZED LATIN SMALL LETTER Y;So;0;L; 0028 0079 0029;;;;N;;;;; +24B5;PARENTHESIZED LATIN SMALL LETTER Z;So;0;L; 0028 007A 0029;;;;N;;;;; +24B6;CIRCLED LATIN CAPITAL LETTER A;So;0;L; 0041;;;;N;;;;24D0; +24B7;CIRCLED LATIN CAPITAL LETTER B;So;0;L; 0042;;;;N;;;;24D1; +24B8;CIRCLED LATIN CAPITAL LETTER C;So;0;L; 0043;;;;N;;;;24D2; +24B9;CIRCLED LATIN CAPITAL LETTER D;So;0;L; 0044;;;;N;;;;24D3; +24BA;CIRCLED LATIN CAPITAL LETTER E;So;0;L; 0045;;;;N;;;;24D4; +24BB;CIRCLED LATIN CAPITAL LETTER F;So;0;L; 0046;;;;N;;;;24D5; +24BC;CIRCLED LATIN CAPITAL LETTER G;So;0;L; 0047;;;;N;;;;24D6; +24BD;CIRCLED LATIN CAPITAL LETTER H;So;0;L; 0048;;;;N;;;;24D7; +24BE;CIRCLED LATIN CAPITAL LETTER I;So;0;L; 0049;;;;N;;;;24D8; +24BF;CIRCLED LATIN CAPITAL LETTER J;So;0;L; 004A;;;;N;;;;24D9; +24C0;CIRCLED LATIN CAPITAL LETTER K;So;0;L; 004B;;;;N;;;;24DA; +24C1;CIRCLED LATIN CAPITAL LETTER L;So;0;L; 004C;;;;N;;;;24DB; +24C2;CIRCLED LATIN CAPITAL LETTER M;So;0;L; 004D;;;;N;;;;24DC; +24C3;CIRCLED LATIN CAPITAL LETTER N;So;0;L; 004E;;;;N;;;;24DD; +24C4;CIRCLED LATIN CAPITAL LETTER O;So;0;L; 004F;;;;N;;;;24DE; +24C5;CIRCLED LATIN CAPITAL LETTER P;So;0;L; 0050;;;;N;;;;24DF; +24C6;CIRCLED LATIN CAPITAL LETTER Q;So;0;L; 0051;;;;N;;;;24E0; +24C7;CIRCLED LATIN CAPITAL LETTER R;So;0;L; 0052;;;;N;;;;24E1; +24C8;CIRCLED LATIN CAPITAL LETTER S;So;0;L; 0053;;;;N;;;;24E2; +24C9;CIRCLED LATIN CAPITAL LETTER T;So;0;L; 0054;;;;N;;;;24E3; +24CA;CIRCLED LATIN CAPITAL LETTER U;So;0;L; 0055;;;;N;;;;24E4; +24CB;CIRCLED LATIN CAPITAL LETTER V;So;0;L; 0056;;;;N;;;;24E5; +24CC;CIRCLED LATIN CAPITAL LETTER W;So;0;L; 0057;;;;N;;;;24E6; +24CD;CIRCLED LATIN CAPITAL LETTER X;So;0;L; 0058;;;;N;;;;24E7; +24CE;CIRCLED LATIN CAPITAL LETTER Y;So;0;L; 0059;;;;N;;;;24E8; +24CF;CIRCLED LATIN CAPITAL LETTER Z;So;0;L; 005A;;;;N;;;;24E9; +24D0;CIRCLED LATIN SMALL LETTER A;So;0;L; 0061;;;;N;;;24B6;;24B6 +24D1;CIRCLED LATIN SMALL LETTER B;So;0;L; 0062;;;;N;;;24B7;;24B7 +24D2;CIRCLED LATIN SMALL LETTER C;So;0;L; 0063;;;;N;;;24B8;;24B8 +24D3;CIRCLED LATIN SMALL LETTER D;So;0;L; 0064;;;;N;;;24B9;;24B9 +24D4;CIRCLED LATIN SMALL LETTER E;So;0;L; 0065;;;;N;;;24BA;;24BA +24D5;CIRCLED LATIN SMALL LETTER F;So;0;L; 0066;;;;N;;;24BB;;24BB +24D6;CIRCLED LATIN SMALL LETTER G;So;0;L; 0067;;;;N;;;24BC;;24BC +24D7;CIRCLED LATIN SMALL LETTER H;So;0;L; 0068;;;;N;;;24BD;;24BD +24D8;CIRCLED LATIN SMALL LETTER I;So;0;L; 0069;;;;N;;;24BE;;24BE +24D9;CIRCLED LATIN SMALL LETTER J;So;0;L; 006A;;;;N;;;24BF;;24BF +24DA;CIRCLED LATIN SMALL LETTER K;So;0;L; 006B;;;;N;;;24C0;;24C0 +24DB;CIRCLED LATIN SMALL LETTER L;So;0;L; 006C;;;;N;;;24C1;;24C1 +24DC;CIRCLED LATIN SMALL LETTER M;So;0;L; 006D;;;;N;;;24C2;;24C2 +24DD;CIRCLED LATIN SMALL LETTER N;So;0;L; 006E;;;;N;;;24C3;;24C3 +24DE;CIRCLED LATIN SMALL LETTER O;So;0;L; 006F;;;;N;;;24C4;;24C4 +24DF;CIRCLED LATIN SMALL LETTER P;So;0;L; 0070;;;;N;;;24C5;;24C5 +24E0;CIRCLED LATIN SMALL LETTER Q;So;0;L; 0071;;;;N;;;24C6;;24C6 +24E1;CIRCLED LATIN SMALL LETTER R;So;0;L; 0072;;;;N;;;24C7;;24C7 +24E2;CIRCLED LATIN SMALL LETTER S;So;0;L; 0073;;;;N;;;24C8;;24C8 +24E3;CIRCLED LATIN SMALL LETTER T;So;0;L; 0074;;;;N;;;24C9;;24C9 +24E4;CIRCLED LATIN SMALL LETTER U;So;0;L; 0075;;;;N;;;24CA;;24CA +24E5;CIRCLED LATIN SMALL LETTER V;So;0;L; 0076;;;;N;;;24CB;;24CB +24E6;CIRCLED LATIN SMALL LETTER W;So;0;L; 0077;;;;N;;;24CC;;24CC +24E7;CIRCLED LATIN SMALL LETTER X;So;0;L; 0078;;;;N;;;24CD;;24CD +24E8;CIRCLED LATIN SMALL LETTER Y;So;0;L; 0079;;;;N;;;24CE;;24CE +24E9;CIRCLED LATIN SMALL LETTER Z;So;0;L; 007A;;;;N;;;24CF;;24CF +24EA;CIRCLED DIGIT ZERO;No;0;ON; 0030;;0;0;N;;;;; +24EB;NEGATIVE CIRCLED NUMBER ELEVEN;No;0;ON;;;;11;N;;;;; +24EC;NEGATIVE CIRCLED NUMBER TWELVE;No;0;ON;;;;12;N;;;;; +24ED;NEGATIVE CIRCLED NUMBER THIRTEEN;No;0;ON;;;;13;N;;;;; +24EE;NEGATIVE CIRCLED NUMBER FOURTEEN;No;0;ON;;;;14;N;;;;; +24EF;NEGATIVE CIRCLED NUMBER FIFTEEN;No;0;ON;;;;15;N;;;;; +24F0;NEGATIVE CIRCLED NUMBER SIXTEEN;No;0;ON;;;;16;N;;;;; +24F1;NEGATIVE CIRCLED NUMBER SEVENTEEN;No;0;ON;;;;17;N;;;;; +24F2;NEGATIVE CIRCLED NUMBER EIGHTEEN;No;0;ON;;;;18;N;;;;; +24F3;NEGATIVE CIRCLED NUMBER NINETEEN;No;0;ON;;;;19;N;;;;; +24F4;NEGATIVE CIRCLED NUMBER TWENTY;No;0;ON;;;;20;N;;;;; +24F5;DOUBLE CIRCLED DIGIT ONE;No;0;ON;;;1;1;N;;;;; +24F6;DOUBLE CIRCLED DIGIT TWO;No;0;ON;;;2;2;N;;;;; +24F7;DOUBLE CIRCLED DIGIT THREE;No;0;ON;;;3;3;N;;;;; +24F8;DOUBLE CIRCLED DIGIT FOUR;No;0;ON;;;4;4;N;;;;; +24F9;DOUBLE CIRCLED DIGIT FIVE;No;0;ON;;;5;5;N;;;;; +24FA;DOUBLE CIRCLED DIGIT SIX;No;0;ON;;;6;6;N;;;;; +24FB;DOUBLE CIRCLED DIGIT SEVEN;No;0;ON;;;7;7;N;;;;; +24FC;DOUBLE CIRCLED DIGIT EIGHT;No;0;ON;;;8;8;N;;;;; +24FD;DOUBLE CIRCLED DIGIT NINE;No;0;ON;;;9;9;N;;;;; +24FE;DOUBLE CIRCLED NUMBER TEN;No;0;ON;;;;10;N;;;;; +24FF;NEGATIVE CIRCLED DIGIT ZERO;No;0;ON;;;0;0;N;;;;; +2500;BOX DRAWINGS LIGHT HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT HORIZONTAL;;;; +2501;BOX DRAWINGS HEAVY HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY HORIZONTAL;;;; +2502;BOX DRAWINGS LIGHT VERTICAL;So;0;ON;;;;;N;FORMS LIGHT VERTICAL;;;; +2503;BOX DRAWINGS HEAVY VERTICAL;So;0;ON;;;;;N;FORMS HEAVY VERTICAL;;;; +2504;BOX DRAWINGS LIGHT TRIPLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT TRIPLE DASH HORIZONTAL;;;; +2505;BOX DRAWINGS HEAVY TRIPLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY TRIPLE DASH HORIZONTAL;;;; +2506;BOX DRAWINGS LIGHT TRIPLE DASH VERTICAL;So;0;ON;;;;;N;FORMS LIGHT TRIPLE DASH VERTICAL;;;; +2507;BOX DRAWINGS HEAVY TRIPLE DASH VERTICAL;So;0;ON;;;;;N;FORMS HEAVY TRIPLE DASH VERTICAL;;;; +2508;BOX DRAWINGS LIGHT QUADRUPLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT QUADRUPLE DASH HORIZONTAL;;;; +2509;BOX DRAWINGS HEAVY QUADRUPLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY QUADRUPLE DASH HORIZONTAL;;;; +250A;BOX DRAWINGS LIGHT QUADRUPLE DASH VERTICAL;So;0;ON;;;;;N;FORMS LIGHT QUADRUPLE DASH VERTICAL;;;; +250B;BOX DRAWINGS HEAVY QUADRUPLE DASH VERTICAL;So;0;ON;;;;;N;FORMS HEAVY QUADRUPLE DASH VERTICAL;;;; +250C;BOX DRAWINGS LIGHT DOWN AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT DOWN AND RIGHT;;;; +250D;BOX DRAWINGS DOWN LIGHT AND RIGHT HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND RIGHT HEAVY;;;; +250E;BOX DRAWINGS DOWN HEAVY AND RIGHT LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND RIGHT LIGHT;;;; +250F;BOX DRAWINGS HEAVY DOWN AND RIGHT;So;0;ON;;;;;N;FORMS HEAVY DOWN AND RIGHT;;;; +2510;BOX DRAWINGS LIGHT DOWN AND LEFT;So;0;ON;;;;;N;FORMS LIGHT DOWN AND LEFT;;;; +2511;BOX DRAWINGS DOWN LIGHT AND LEFT HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND LEFT HEAVY;;;; +2512;BOX DRAWINGS DOWN HEAVY AND LEFT LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND LEFT LIGHT;;;; +2513;BOX DRAWINGS HEAVY DOWN AND LEFT;So;0;ON;;;;;N;FORMS HEAVY DOWN AND LEFT;;;; +2514;BOX DRAWINGS LIGHT UP AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT UP AND RIGHT;;;; +2515;BOX DRAWINGS UP LIGHT AND RIGHT HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND RIGHT HEAVY;;;; +2516;BOX DRAWINGS UP HEAVY AND RIGHT LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND RIGHT LIGHT;;;; +2517;BOX DRAWINGS HEAVY UP AND RIGHT;So;0;ON;;;;;N;FORMS HEAVY UP AND RIGHT;;;; +2518;BOX DRAWINGS LIGHT UP AND LEFT;So;0;ON;;;;;N;FORMS LIGHT UP AND LEFT;;;; +2519;BOX DRAWINGS UP LIGHT AND LEFT HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND LEFT HEAVY;;;; +251A;BOX DRAWINGS UP HEAVY AND LEFT LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND LEFT LIGHT;;;; +251B;BOX DRAWINGS HEAVY UP AND LEFT;So;0;ON;;;;;N;FORMS HEAVY UP AND LEFT;;;; +251C;BOX DRAWINGS LIGHT VERTICAL AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT VERTICAL AND RIGHT;;;; +251D;BOX DRAWINGS VERTICAL LIGHT AND RIGHT HEAVY;So;0;ON;;;;;N;FORMS VERTICAL LIGHT AND RIGHT HEAVY;;;; +251E;BOX DRAWINGS UP HEAVY AND RIGHT DOWN LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND RIGHT DOWN LIGHT;;;; +251F;BOX DRAWINGS DOWN HEAVY AND RIGHT UP LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND RIGHT UP LIGHT;;;; +2520;BOX DRAWINGS VERTICAL HEAVY AND RIGHT LIGHT;So;0;ON;;;;;N;FORMS VERTICAL HEAVY AND RIGHT LIGHT;;;; +2521;BOX DRAWINGS DOWN LIGHT AND RIGHT UP HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND RIGHT UP HEAVY;;;; +2522;BOX DRAWINGS UP LIGHT AND RIGHT DOWN HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND RIGHT DOWN HEAVY;;;; +2523;BOX DRAWINGS HEAVY VERTICAL AND RIGHT;So;0;ON;;;;;N;FORMS HEAVY VERTICAL AND RIGHT;;;; +2524;BOX DRAWINGS LIGHT VERTICAL AND LEFT;So;0;ON;;;;;N;FORMS LIGHT VERTICAL AND LEFT;;;; +2525;BOX DRAWINGS VERTICAL LIGHT AND LEFT HEAVY;So;0;ON;;;;;N;FORMS VERTICAL LIGHT AND LEFT HEAVY;;;; +2526;BOX DRAWINGS UP HEAVY AND LEFT DOWN LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND LEFT DOWN LIGHT;;;; +2527;BOX DRAWINGS DOWN HEAVY AND LEFT UP LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND LEFT UP LIGHT;;;; +2528;BOX DRAWINGS VERTICAL HEAVY AND LEFT LIGHT;So;0;ON;;;;;N;FORMS VERTICAL HEAVY AND LEFT LIGHT;;;; +2529;BOX DRAWINGS DOWN LIGHT AND LEFT UP HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND LEFT UP HEAVY;;;; +252A;BOX DRAWINGS UP LIGHT AND LEFT DOWN HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND LEFT DOWN HEAVY;;;; +252B;BOX DRAWINGS HEAVY VERTICAL AND LEFT;So;0;ON;;;;;N;FORMS HEAVY VERTICAL AND LEFT;;;; +252C;BOX DRAWINGS LIGHT DOWN AND HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT DOWN AND HORIZONTAL;;;; +252D;BOX DRAWINGS LEFT HEAVY AND RIGHT DOWN LIGHT;So;0;ON;;;;;N;FORMS LEFT HEAVY AND RIGHT DOWN LIGHT;;;; +252E;BOX DRAWINGS RIGHT HEAVY AND LEFT DOWN LIGHT;So;0;ON;;;;;N;FORMS RIGHT HEAVY AND LEFT DOWN LIGHT;;;; +252F;BOX DRAWINGS DOWN LIGHT AND HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND HORIZONTAL HEAVY;;;; +2530;BOX DRAWINGS DOWN HEAVY AND HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND HORIZONTAL LIGHT;;;; +2531;BOX DRAWINGS RIGHT LIGHT AND LEFT DOWN HEAVY;So;0;ON;;;;;N;FORMS RIGHT LIGHT AND LEFT DOWN HEAVY;;;; +2532;BOX DRAWINGS LEFT LIGHT AND RIGHT DOWN HEAVY;So;0;ON;;;;;N;FORMS LEFT LIGHT AND RIGHT DOWN HEAVY;;;; +2533;BOX DRAWINGS HEAVY DOWN AND HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY DOWN AND HORIZONTAL;;;; +2534;BOX DRAWINGS LIGHT UP AND HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT UP AND HORIZONTAL;;;; +2535;BOX DRAWINGS LEFT HEAVY AND RIGHT UP LIGHT;So;0;ON;;;;;N;FORMS LEFT HEAVY AND RIGHT UP LIGHT;;;; +2536;BOX DRAWINGS RIGHT HEAVY AND LEFT UP LIGHT;So;0;ON;;;;;N;FORMS RIGHT HEAVY AND LEFT UP LIGHT;;;; +2537;BOX DRAWINGS UP LIGHT AND HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND HORIZONTAL HEAVY;;;; +2538;BOX DRAWINGS UP HEAVY AND HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND HORIZONTAL LIGHT;;;; +2539;BOX DRAWINGS RIGHT LIGHT AND LEFT UP HEAVY;So;0;ON;;;;;N;FORMS RIGHT LIGHT AND LEFT UP HEAVY;;;; +253A;BOX DRAWINGS LEFT LIGHT AND RIGHT UP HEAVY;So;0;ON;;;;;N;FORMS LEFT LIGHT AND RIGHT UP HEAVY;;;; +253B;BOX DRAWINGS HEAVY UP AND HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY UP AND HORIZONTAL;;;; +253C;BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT VERTICAL AND HORIZONTAL;;;; +253D;BOX DRAWINGS LEFT HEAVY AND RIGHT VERTICAL LIGHT;So;0;ON;;;;;N;FORMS LEFT HEAVY AND RIGHT VERTICAL LIGHT;;;; +253E;BOX DRAWINGS RIGHT HEAVY AND LEFT VERTICAL LIGHT;So;0;ON;;;;;N;FORMS RIGHT HEAVY AND LEFT VERTICAL LIGHT;;;; +253F;BOX DRAWINGS VERTICAL LIGHT AND HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS VERTICAL LIGHT AND HORIZONTAL HEAVY;;;; +2540;BOX DRAWINGS UP HEAVY AND DOWN HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS UP HEAVY AND DOWN HORIZONTAL LIGHT;;;; +2541;BOX DRAWINGS DOWN HEAVY AND UP HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS DOWN HEAVY AND UP HORIZONTAL LIGHT;;;; +2542;BOX DRAWINGS VERTICAL HEAVY AND HORIZONTAL LIGHT;So;0;ON;;;;;N;FORMS VERTICAL HEAVY AND HORIZONTAL LIGHT;;;; +2543;BOX DRAWINGS LEFT UP HEAVY AND RIGHT DOWN LIGHT;So;0;ON;;;;;N;FORMS LEFT UP HEAVY AND RIGHT DOWN LIGHT;;;; +2544;BOX DRAWINGS RIGHT UP HEAVY AND LEFT DOWN LIGHT;So;0;ON;;;;;N;FORMS RIGHT UP HEAVY AND LEFT DOWN LIGHT;;;; +2545;BOX DRAWINGS LEFT DOWN HEAVY AND RIGHT UP LIGHT;So;0;ON;;;;;N;FORMS LEFT DOWN HEAVY AND RIGHT UP LIGHT;;;; +2546;BOX DRAWINGS RIGHT DOWN HEAVY AND LEFT UP LIGHT;So;0;ON;;;;;N;FORMS RIGHT DOWN HEAVY AND LEFT UP LIGHT;;;; +2547;BOX DRAWINGS DOWN LIGHT AND UP HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS DOWN LIGHT AND UP HORIZONTAL HEAVY;;;; +2548;BOX DRAWINGS UP LIGHT AND DOWN HORIZONTAL HEAVY;So;0;ON;;;;;N;FORMS UP LIGHT AND DOWN HORIZONTAL HEAVY;;;; +2549;BOX DRAWINGS RIGHT LIGHT AND LEFT VERTICAL HEAVY;So;0;ON;;;;;N;FORMS RIGHT LIGHT AND LEFT VERTICAL HEAVY;;;; +254A;BOX DRAWINGS LEFT LIGHT AND RIGHT VERTICAL HEAVY;So;0;ON;;;;;N;FORMS LEFT LIGHT AND RIGHT VERTICAL HEAVY;;;; +254B;BOX DRAWINGS HEAVY VERTICAL AND HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY VERTICAL AND HORIZONTAL;;;; +254C;BOX DRAWINGS LIGHT DOUBLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS LIGHT DOUBLE DASH HORIZONTAL;;;; +254D;BOX DRAWINGS HEAVY DOUBLE DASH HORIZONTAL;So;0;ON;;;;;N;FORMS HEAVY DOUBLE DASH HORIZONTAL;;;; +254E;BOX DRAWINGS LIGHT DOUBLE DASH VERTICAL;So;0;ON;;;;;N;FORMS LIGHT DOUBLE DASH VERTICAL;;;; +254F;BOX DRAWINGS HEAVY DOUBLE DASH VERTICAL;So;0;ON;;;;;N;FORMS HEAVY DOUBLE DASH VERTICAL;;;; +2550;BOX DRAWINGS DOUBLE HORIZONTAL;So;0;ON;;;;;N;FORMS DOUBLE HORIZONTAL;;;; +2551;BOX DRAWINGS DOUBLE VERTICAL;So;0;ON;;;;;N;FORMS DOUBLE VERTICAL;;;; +2552;BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE;So;0;ON;;;;;N;FORMS DOWN SINGLE AND RIGHT DOUBLE;;;; +2553;BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE;So;0;ON;;;;;N;FORMS DOWN DOUBLE AND RIGHT SINGLE;;;; +2554;BOX DRAWINGS DOUBLE DOWN AND RIGHT;So;0;ON;;;;;N;FORMS DOUBLE DOWN AND RIGHT;;;; +2555;BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE;So;0;ON;;;;;N;FORMS DOWN SINGLE AND LEFT DOUBLE;;;; +2556;BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE;So;0;ON;;;;;N;FORMS DOWN DOUBLE AND LEFT SINGLE;;;; +2557;BOX DRAWINGS DOUBLE DOWN AND LEFT;So;0;ON;;;;;N;FORMS DOUBLE DOWN AND LEFT;;;; +2558;BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE;So;0;ON;;;;;N;FORMS UP SINGLE AND RIGHT DOUBLE;;;; +2559;BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE;So;0;ON;;;;;N;FORMS UP DOUBLE AND RIGHT SINGLE;;;; +255A;BOX DRAWINGS DOUBLE UP AND RIGHT;So;0;ON;;;;;N;FORMS DOUBLE UP AND RIGHT;;;; +255B;BOX DRAWINGS UP SINGLE AND LEFT DOUBLE;So;0;ON;;;;;N;FORMS UP SINGLE AND LEFT DOUBLE;;;; +255C;BOX DRAWINGS UP DOUBLE AND LEFT SINGLE;So;0;ON;;;;;N;FORMS UP DOUBLE AND LEFT SINGLE;;;; +255D;BOX DRAWINGS DOUBLE UP AND LEFT;So;0;ON;;;;;N;FORMS DOUBLE UP AND LEFT;;;; +255E;BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE;So;0;ON;;;;;N;FORMS VERTICAL SINGLE AND RIGHT DOUBLE;;;; +255F;BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE;So;0;ON;;;;;N;FORMS VERTICAL DOUBLE AND RIGHT SINGLE;;;; +2560;BOX DRAWINGS DOUBLE VERTICAL AND RIGHT;So;0;ON;;;;;N;FORMS DOUBLE VERTICAL AND RIGHT;;;; +2561;BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE;So;0;ON;;;;;N;FORMS VERTICAL SINGLE AND LEFT DOUBLE;;;; +2562;BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE;So;0;ON;;;;;N;FORMS VERTICAL DOUBLE AND LEFT SINGLE;;;; +2563;BOX DRAWINGS DOUBLE VERTICAL AND LEFT;So;0;ON;;;;;N;FORMS DOUBLE VERTICAL AND LEFT;;;; +2564;BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE;So;0;ON;;;;;N;FORMS DOWN SINGLE AND HORIZONTAL DOUBLE;;;; +2565;BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE;So;0;ON;;;;;N;FORMS DOWN DOUBLE AND HORIZONTAL SINGLE;;;; +2566;BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL;So;0;ON;;;;;N;FORMS DOUBLE DOWN AND HORIZONTAL;;;; +2567;BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE;So;0;ON;;;;;N;FORMS UP SINGLE AND HORIZONTAL DOUBLE;;;; +2568;BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE;So;0;ON;;;;;N;FORMS UP DOUBLE AND HORIZONTAL SINGLE;;;; +2569;BOX DRAWINGS DOUBLE UP AND HORIZONTAL;So;0;ON;;;;;N;FORMS DOUBLE UP AND HORIZONTAL;;;; +256A;BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE;So;0;ON;;;;;N;FORMS VERTICAL SINGLE AND HORIZONTAL DOUBLE;;;; +256B;BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE;So;0;ON;;;;;N;FORMS VERTICAL DOUBLE AND HORIZONTAL SINGLE;;;; +256C;BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL;So;0;ON;;;;;N;FORMS DOUBLE VERTICAL AND HORIZONTAL;;;; +256D;BOX DRAWINGS LIGHT ARC DOWN AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT ARC DOWN AND RIGHT;;;; +256E;BOX DRAWINGS LIGHT ARC DOWN AND LEFT;So;0;ON;;;;;N;FORMS LIGHT ARC DOWN AND LEFT;;;; +256F;BOX DRAWINGS LIGHT ARC UP AND LEFT;So;0;ON;;;;;N;FORMS LIGHT ARC UP AND LEFT;;;; +2570;BOX DRAWINGS LIGHT ARC UP AND RIGHT;So;0;ON;;;;;N;FORMS LIGHT ARC UP AND RIGHT;;;; +2571;BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT;So;0;ON;;;;;N;FORMS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT;;;; +2572;BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT;So;0;ON;;;;;N;FORMS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT;;;; +2573;BOX DRAWINGS LIGHT DIAGONAL CROSS;So;0;ON;;;;;N;FORMS LIGHT DIAGONAL CROSS;;;; +2574;BOX DRAWINGS LIGHT LEFT;So;0;ON;;;;;N;FORMS LIGHT LEFT;;;; +2575;BOX DRAWINGS LIGHT UP;So;0;ON;;;;;N;FORMS LIGHT UP;;;; +2576;BOX DRAWINGS LIGHT RIGHT;So;0;ON;;;;;N;FORMS LIGHT RIGHT;;;; +2577;BOX DRAWINGS LIGHT DOWN;So;0;ON;;;;;N;FORMS LIGHT DOWN;;;; +2578;BOX DRAWINGS HEAVY LEFT;So;0;ON;;;;;N;FORMS HEAVY LEFT;;;; +2579;BOX DRAWINGS HEAVY UP;So;0;ON;;;;;N;FORMS HEAVY UP;;;; +257A;BOX DRAWINGS HEAVY RIGHT;So;0;ON;;;;;N;FORMS HEAVY RIGHT;;;; +257B;BOX DRAWINGS HEAVY DOWN;So;0;ON;;;;;N;FORMS HEAVY DOWN;;;; +257C;BOX DRAWINGS LIGHT LEFT AND HEAVY RIGHT;So;0;ON;;;;;N;FORMS LIGHT LEFT AND HEAVY RIGHT;;;; +257D;BOX DRAWINGS LIGHT UP AND HEAVY DOWN;So;0;ON;;;;;N;FORMS LIGHT UP AND HEAVY DOWN;;;; +257E;BOX DRAWINGS HEAVY LEFT AND LIGHT RIGHT;So;0;ON;;;;;N;FORMS HEAVY LEFT AND LIGHT RIGHT;;;; +257F;BOX DRAWINGS HEAVY UP AND LIGHT DOWN;So;0;ON;;;;;N;FORMS HEAVY UP AND LIGHT DOWN;;;; +2580;UPPER HALF BLOCK;So;0;ON;;;;;N;;;;; +2581;LOWER ONE EIGHTH BLOCK;So;0;ON;;;;;N;;;;; +2582;LOWER ONE QUARTER BLOCK;So;0;ON;;;;;N;;;;; +2583;LOWER THREE EIGHTHS BLOCK;So;0;ON;;;;;N;;;;; +2584;LOWER HALF BLOCK;So;0;ON;;;;;N;;;;; +2585;LOWER FIVE EIGHTHS BLOCK;So;0;ON;;;;;N;;;;; +2586;LOWER THREE QUARTERS BLOCK;So;0;ON;;;;;N;LOWER THREE QUARTER BLOCK;;;; +2587;LOWER SEVEN EIGHTHS BLOCK;So;0;ON;;;;;N;;;;; +2588;FULL BLOCK;So;0;ON;;;;;N;;;;; +2589;LEFT SEVEN EIGHTHS BLOCK;So;0;ON;;;;;N;;;;; +258A;LEFT THREE QUARTERS BLOCK;So;0;ON;;;;;N;LEFT THREE QUARTER BLOCK;;;; +258B;LEFT FIVE EIGHTHS BLOCK;So;0;ON;;;;;N;;;;; +258C;LEFT HALF BLOCK;So;0;ON;;;;;N;;;;; +258D;LEFT THREE EIGHTHS BLOCK;So;0;ON;;;;;N;;;;; +258E;LEFT ONE QUARTER BLOCK;So;0;ON;;;;;N;;;;; +258F;LEFT ONE EIGHTH BLOCK;So;0;ON;;;;;N;;;;; +2590;RIGHT HALF BLOCK;So;0;ON;;;;;N;;;;; +2591;LIGHT SHADE;So;0;ON;;;;;N;;;;; +2592;MEDIUM SHADE;So;0;ON;;;;;N;;;;; +2593;DARK SHADE;So;0;ON;;;;;N;;;;; +2594;UPPER ONE EIGHTH BLOCK;So;0;ON;;;;;N;;;;; +2595;RIGHT ONE EIGHTH BLOCK;So;0;ON;;;;;N;;;;; +2596;QUADRANT LOWER LEFT;So;0;ON;;;;;N;;;;; +2597;QUADRANT LOWER RIGHT;So;0;ON;;;;;N;;;;; +2598;QUADRANT UPPER LEFT;So;0;ON;;;;;N;;;;; +2599;QUADRANT UPPER LEFT AND LOWER LEFT AND LOWER RIGHT;So;0;ON;;;;;N;;;;; +259A;QUADRANT UPPER LEFT AND LOWER RIGHT;So;0;ON;;;;;N;;;;; +259B;QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER LEFT;So;0;ON;;;;;N;;;;; +259C;QUADRANT UPPER LEFT AND UPPER RIGHT AND LOWER RIGHT;So;0;ON;;;;;N;;;;; +259D;QUADRANT UPPER RIGHT;So;0;ON;;;;;N;;;;; +259E;QUADRANT UPPER RIGHT AND LOWER LEFT;So;0;ON;;;;;N;;;;; +259F;QUADRANT UPPER RIGHT AND LOWER LEFT AND LOWER RIGHT;So;0;ON;;;;;N;;;;; +25A0;BLACK SQUARE;So;0;ON;;;;;N;;;;; +25A1;WHITE SQUARE;So;0;ON;;;;;N;;;;; +25A2;WHITE SQUARE WITH ROUNDED CORNERS;So;0;ON;;;;;N;;;;; +25A3;WHITE SQUARE CONTAINING BLACK SMALL SQUARE;So;0;ON;;;;;N;;;;; +25A4;SQUARE WITH HORIZONTAL FILL;So;0;ON;;;;;N;;;;; +25A5;SQUARE WITH VERTICAL FILL;So;0;ON;;;;;N;;;;; +25A6;SQUARE WITH ORTHOGONAL CROSSHATCH FILL;So;0;ON;;;;;N;;;;; +25A7;SQUARE WITH UPPER LEFT TO LOWER RIGHT FILL;So;0;ON;;;;;N;;;;; +25A8;SQUARE WITH UPPER RIGHT TO LOWER LEFT FILL;So;0;ON;;;;;N;;;;; +25A9;SQUARE WITH DIAGONAL CROSSHATCH FILL;So;0;ON;;;;;N;;;;; +25AA;BLACK SMALL SQUARE;So;0;ON;;;;;N;;;;; +25AB;WHITE SMALL SQUARE;So;0;ON;;;;;N;;;;; +25AC;BLACK RECTANGLE;So;0;ON;;;;;N;;;;; +25AD;WHITE RECTANGLE;So;0;ON;;;;;N;;;;; +25AE;BLACK VERTICAL RECTANGLE;So;0;ON;;;;;N;;;;; +25AF;WHITE VERTICAL RECTANGLE;So;0;ON;;;;;N;;;;; +25B0;BLACK PARALLELOGRAM;So;0;ON;;;;;N;;;;; +25B1;WHITE PARALLELOGRAM;So;0;ON;;;;;N;;;;; +25B2;BLACK UP-POINTING TRIANGLE;So;0;ON;;;;;N;BLACK UP POINTING TRIANGLE;;;; +25B3;WHITE UP-POINTING TRIANGLE;So;0;ON;;;;;N;WHITE UP POINTING TRIANGLE;;;; +25B4;BLACK UP-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;BLACK UP POINTING SMALL TRIANGLE;;;; +25B5;WHITE UP-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;WHITE UP POINTING SMALL TRIANGLE;;;; +25B6;BLACK RIGHT-POINTING TRIANGLE;So;0;ON;;;;;N;BLACK RIGHT POINTING TRIANGLE;;;; +25B7;WHITE RIGHT-POINTING TRIANGLE;Sm;0;ON;;;;;N;WHITE RIGHT POINTING TRIANGLE;;;; +25B8;BLACK RIGHT-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;BLACK RIGHT POINTING SMALL TRIANGLE;;;; +25B9;WHITE RIGHT-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;WHITE RIGHT POINTING SMALL TRIANGLE;;;; +25BA;BLACK RIGHT-POINTING POINTER;So;0;ON;;;;;N;BLACK RIGHT POINTING POINTER;;;; +25BB;WHITE RIGHT-POINTING POINTER;So;0;ON;;;;;N;WHITE RIGHT POINTING POINTER;;;; +25BC;BLACK DOWN-POINTING TRIANGLE;So;0;ON;;;;;N;BLACK DOWN POINTING TRIANGLE;;;; +25BD;WHITE DOWN-POINTING TRIANGLE;So;0;ON;;;;;N;WHITE DOWN POINTING TRIANGLE;;;; +25BE;BLACK DOWN-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;BLACK DOWN POINTING SMALL TRIANGLE;;;; +25BF;WHITE DOWN-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;WHITE DOWN POINTING SMALL TRIANGLE;;;; +25C0;BLACK LEFT-POINTING TRIANGLE;So;0;ON;;;;;N;BLACK LEFT POINTING TRIANGLE;;;; +25C1;WHITE LEFT-POINTING TRIANGLE;Sm;0;ON;;;;;N;WHITE LEFT POINTING TRIANGLE;;;; +25C2;BLACK LEFT-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;BLACK LEFT POINTING SMALL TRIANGLE;;;; +25C3;WHITE LEFT-POINTING SMALL TRIANGLE;So;0;ON;;;;;N;WHITE LEFT POINTING SMALL TRIANGLE;;;; +25C4;BLACK LEFT-POINTING POINTER;So;0;ON;;;;;N;BLACK LEFT POINTING POINTER;;;; +25C5;WHITE LEFT-POINTING POINTER;So;0;ON;;;;;N;WHITE LEFT POINTING POINTER;;;; +25C6;BLACK DIAMOND;So;0;ON;;;;;N;;;;; +25C7;WHITE DIAMOND;So;0;ON;;;;;N;;;;; +25C8;WHITE DIAMOND CONTAINING BLACK SMALL DIAMOND;So;0;ON;;;;;N;;;;; +25C9;FISHEYE;So;0;ON;;;;;N;;;;; +25CA;LOZENGE;So;0;ON;;;;;N;;;;; +25CB;WHITE CIRCLE;So;0;ON;;;;;N;;;;; +25CC;DOTTED CIRCLE;So;0;ON;;;;;N;;;;; +25CD;CIRCLE WITH VERTICAL FILL;So;0;ON;;;;;N;;;;; +25CE;BULLSEYE;So;0;ON;;;;;N;;;;; +25CF;BLACK CIRCLE;So;0;ON;;;;;N;;;;; +25D0;CIRCLE WITH LEFT HALF BLACK;So;0;ON;;;;;N;;;;; +25D1;CIRCLE WITH RIGHT HALF BLACK;So;0;ON;;;;;N;;;;; +25D2;CIRCLE WITH LOWER HALF BLACK;So;0;ON;;;;;N;;;;; +25D3;CIRCLE WITH UPPER HALF BLACK;So;0;ON;;;;;N;;;;; +25D4;CIRCLE WITH UPPER RIGHT QUADRANT BLACK;So;0;ON;;;;;N;;;;; +25D5;CIRCLE WITH ALL BUT UPPER LEFT QUADRANT BLACK;So;0;ON;;;;;N;;;;; +25D6;LEFT HALF BLACK CIRCLE;So;0;ON;;;;;N;;;;; +25D7;RIGHT HALF BLACK CIRCLE;So;0;ON;;;;;N;;;;; +25D8;INVERSE BULLET;So;0;ON;;;;;N;;;;; +25D9;INVERSE WHITE CIRCLE;So;0;ON;;;;;N;;;;; +25DA;UPPER HALF INVERSE WHITE CIRCLE;So;0;ON;;;;;N;;;;; +25DB;LOWER HALF INVERSE WHITE CIRCLE;So;0;ON;;;;;N;;;;; +25DC;UPPER LEFT QUADRANT CIRCULAR ARC;So;0;ON;;;;;N;;;;; +25DD;UPPER RIGHT QUADRANT CIRCULAR ARC;So;0;ON;;;;;N;;;;; +25DE;LOWER RIGHT QUADRANT CIRCULAR ARC;So;0;ON;;;;;N;;;;; +25DF;LOWER LEFT QUADRANT CIRCULAR ARC;So;0;ON;;;;;N;;;;; +25E0;UPPER HALF CIRCLE;So;0;ON;;;;;N;;;;; +25E1;LOWER HALF CIRCLE;So;0;ON;;;;;N;;;;; +25E2;BLACK LOWER RIGHT TRIANGLE;So;0;ON;;;;;N;;;;; +25E3;BLACK LOWER LEFT TRIANGLE;So;0;ON;;;;;N;;;;; +25E4;BLACK UPPER LEFT TRIANGLE;So;0;ON;;;;;N;;;;; +25E5;BLACK UPPER RIGHT TRIANGLE;So;0;ON;;;;;N;;;;; +25E6;WHITE BULLET;So;0;ON;;;;;N;;;;; +25E7;SQUARE WITH LEFT HALF BLACK;So;0;ON;;;;;N;;;;; +25E8;SQUARE WITH RIGHT HALF BLACK;So;0;ON;;;;;N;;;;; +25E9;SQUARE WITH UPPER LEFT DIAGONAL HALF BLACK;So;0;ON;;;;;N;;;;; +25EA;SQUARE WITH LOWER RIGHT DIAGONAL HALF BLACK;So;0;ON;;;;;N;;;;; +25EB;WHITE SQUARE WITH VERTICAL BISECTING LINE;So;0;ON;;;;;N;;;;; +25EC;WHITE UP-POINTING TRIANGLE WITH DOT;So;0;ON;;;;;N;WHITE UP POINTING TRIANGLE WITH DOT;;;; +25ED;UP-POINTING TRIANGLE WITH LEFT HALF BLACK;So;0;ON;;;;;N;UP POINTING TRIANGLE WITH LEFT HALF BLACK;;;; +25EE;UP-POINTING TRIANGLE WITH RIGHT HALF BLACK;So;0;ON;;;;;N;UP POINTING TRIANGLE WITH RIGHT HALF BLACK;;;; +25EF;LARGE CIRCLE;So;0;ON;;;;;N;;;;; +25F0;WHITE SQUARE WITH UPPER LEFT QUADRANT;So;0;ON;;;;;N;;;;; +25F1;WHITE SQUARE WITH LOWER LEFT QUADRANT;So;0;ON;;;;;N;;;;; +25F2;WHITE SQUARE WITH LOWER RIGHT QUADRANT;So;0;ON;;;;;N;;;;; +25F3;WHITE SQUARE WITH UPPER RIGHT QUADRANT;So;0;ON;;;;;N;;;;; +25F4;WHITE CIRCLE WITH UPPER LEFT QUADRANT;So;0;ON;;;;;N;;;;; +25F5;WHITE CIRCLE WITH LOWER LEFT QUADRANT;So;0;ON;;;;;N;;;;; +25F6;WHITE CIRCLE WITH LOWER RIGHT QUADRANT;So;0;ON;;;;;N;;;;; +25F7;WHITE CIRCLE WITH UPPER RIGHT QUADRANT;So;0;ON;;;;;N;;;;; +25F8;UPPER LEFT TRIANGLE;Sm;0;ON;;;;;N;;;;; +25F9;UPPER RIGHT TRIANGLE;Sm;0;ON;;;;;N;;;;; +25FA;LOWER LEFT TRIANGLE;Sm;0;ON;;;;;N;;;;; +25FB;WHITE MEDIUM SQUARE;Sm;0;ON;;;;;N;;;;; +25FC;BLACK MEDIUM SQUARE;Sm;0;ON;;;;;N;;;;; +25FD;WHITE MEDIUM SMALL SQUARE;Sm;0;ON;;;;;N;;;;; +25FE;BLACK MEDIUM SMALL SQUARE;Sm;0;ON;;;;;N;;;;; +25FF;LOWER RIGHT TRIANGLE;Sm;0;ON;;;;;N;;;;; +2600;BLACK SUN WITH RAYS;So;0;ON;;;;;N;;;;; +2601;CLOUD;So;0;ON;;;;;N;;;;; +2602;UMBRELLA;So;0;ON;;;;;N;;;;; +2603;SNOWMAN;So;0;ON;;;;;N;;;;; +2604;COMET;So;0;ON;;;;;N;;;;; +2605;BLACK STAR;So;0;ON;;;;;N;;;;; +2606;WHITE STAR;So;0;ON;;;;;N;;;;; +2607;LIGHTNING;So;0;ON;;;;;N;;;;; +2608;THUNDERSTORM;So;0;ON;;;;;N;;;;; +2609;SUN;So;0;ON;;;;;N;;;;; +260A;ASCENDING NODE;So;0;ON;;;;;N;;;;; +260B;DESCENDING NODE;So;0;ON;;;;;N;;;;; +260C;CONJUNCTION;So;0;ON;;;;;N;;;;; +260D;OPPOSITION;So;0;ON;;;;;N;;;;; +260E;BLACK TELEPHONE;So;0;ON;;;;;N;;;;; +260F;WHITE TELEPHONE;So;0;ON;;;;;N;;;;; +2610;BALLOT BOX;So;0;ON;;;;;N;;;;; +2611;BALLOT BOX WITH CHECK;So;0;ON;;;;;N;;;;; +2612;BALLOT BOX WITH X;So;0;ON;;;;;N;;;;; +2613;SALTIRE;So;0;ON;;;;;N;;;;; +2614;UMBRELLA WITH RAIN DROPS;So;0;ON;;;;;N;;;;; +2615;HOT BEVERAGE;So;0;ON;;;;;N;;;;; +2616;WHITE SHOGI PIECE;So;0;ON;;;;;N;;;;; +2617;BLACK SHOGI PIECE;So;0;ON;;;;;N;;;;; +2618;SHAMROCK;So;0;ON;;;;;N;;;;; +2619;REVERSED ROTATED FLORAL HEART BULLET;So;0;ON;;;;;N;;;;; +261A;BLACK LEFT POINTING INDEX;So;0;ON;;;;;N;;;;; +261B;BLACK RIGHT POINTING INDEX;So;0;ON;;;;;N;;;;; +261C;WHITE LEFT POINTING INDEX;So;0;ON;;;;;N;;;;; +261D;WHITE UP POINTING INDEX;So;0;ON;;;;;N;;;;; +261E;WHITE RIGHT POINTING INDEX;So;0;ON;;;;;N;;;;; +261F;WHITE DOWN POINTING INDEX;So;0;ON;;;;;N;;;;; +2620;SKULL AND CROSSBONES;So;0;ON;;;;;N;;;;; +2621;CAUTION SIGN;So;0;ON;;;;;N;;;;; +2622;RADIOACTIVE SIGN;So;0;ON;;;;;N;;;;; +2623;BIOHAZARD SIGN;So;0;ON;;;;;N;;;;; +2624;CADUCEUS;So;0;ON;;;;;N;;;;; +2625;ANKH;So;0;ON;;;;;N;;;;; +2626;ORTHODOX CROSS;So;0;ON;;;;;N;;;;; +2627;CHI RHO;So;0;ON;;;;;N;;;;; +2628;CROSS OF LORRAINE;So;0;ON;;;;;N;;;;; +2629;CROSS OF JERUSALEM;So;0;ON;;;;;N;;;;; +262A;STAR AND CRESCENT;So;0;ON;;;;;N;;;;; +262B;FARSI SYMBOL;So;0;ON;;;;;N;SYMBOL OF IRAN;;;; +262C;ADI SHAKTI;So;0;ON;;;;;N;;;;; +262D;HAMMER AND SICKLE;So;0;ON;;;;;N;;;;; +262E;PEACE SYMBOL;So;0;ON;;;;;N;;;;; +262F;YIN YANG;So;0;ON;;;;;N;;;;; +2630;TRIGRAM FOR HEAVEN;So;0;ON;;;;;N;;;;; +2631;TRIGRAM FOR LAKE;So;0;ON;;;;;N;;;;; +2632;TRIGRAM FOR FIRE;So;0;ON;;;;;N;;;;; +2633;TRIGRAM FOR THUNDER;So;0;ON;;;;;N;;;;; +2634;TRIGRAM FOR WIND;So;0;ON;;;;;N;;;;; +2635;TRIGRAM FOR WATER;So;0;ON;;;;;N;;;;; +2636;TRIGRAM FOR MOUNTAIN;So;0;ON;;;;;N;;;;; +2637;TRIGRAM FOR EARTH;So;0;ON;;;;;N;;;;; +2638;WHEEL OF DHARMA;So;0;ON;;;;;N;;;;; +2639;WHITE FROWNING FACE;So;0;ON;;;;;N;;;;; +263A;WHITE SMILING FACE;So;0;ON;;;;;N;;;;; +263B;BLACK SMILING FACE;So;0;ON;;;;;N;;;;; +263C;WHITE SUN WITH RAYS;So;0;ON;;;;;N;;;;; +263D;FIRST QUARTER MOON;So;0;ON;;;;;N;;;;; +263E;LAST QUARTER MOON;So;0;ON;;;;;N;;;;; +263F;MERCURY;So;0;ON;;;;;N;;;;; +2640;FEMALE SIGN;So;0;ON;;;;;N;;;;; +2641;EARTH;So;0;ON;;;;;N;;;;; +2642;MALE SIGN;So;0;ON;;;;;N;;;;; +2643;JUPITER;So;0;ON;;;;;N;;;;; +2644;SATURN;So;0;ON;;;;;N;;;;; +2645;URANUS;So;0;ON;;;;;N;;;;; +2646;NEPTUNE;So;0;ON;;;;;N;;;;; +2647;PLUTO;So;0;ON;;;;;N;;;;; +2648;ARIES;So;0;ON;;;;;N;;;;; +2649;TAURUS;So;0;ON;;;;;N;;;;; +264A;GEMINI;So;0;ON;;;;;N;;;;; +264B;CANCER;So;0;ON;;;;;N;;;;; +264C;LEO;So;0;ON;;;;;N;;;;; +264D;VIRGO;So;0;ON;;;;;N;;;;; +264E;LIBRA;So;0;ON;;;;;N;;;;; +264F;SCORPIUS;So;0;ON;;;;;N;;;;; +2650;SAGITTARIUS;So;0;ON;;;;;N;;;;; +2651;CAPRICORN;So;0;ON;;;;;N;;;;; +2652;AQUARIUS;So;0;ON;;;;;N;;;;; +2653;PISCES;So;0;ON;;;;;N;;;;; +2654;WHITE CHESS KING;So;0;ON;;;;;N;;;;; +2655;WHITE CHESS QUEEN;So;0;ON;;;;;N;;;;; +2656;WHITE CHESS ROOK;So;0;ON;;;;;N;;;;; +2657;WHITE CHESS BISHOP;So;0;ON;;;;;N;;;;; +2658;WHITE CHESS KNIGHT;So;0;ON;;;;;N;;;;; +2659;WHITE CHESS PAWN;So;0;ON;;;;;N;;;;; +265A;BLACK CHESS KING;So;0;ON;;;;;N;;;;; +265B;BLACK CHESS QUEEN;So;0;ON;;;;;N;;;;; +265C;BLACK CHESS ROOK;So;0;ON;;;;;N;;;;; +265D;BLACK CHESS BISHOP;So;0;ON;;;;;N;;;;; +265E;BLACK CHESS KNIGHT;So;0;ON;;;;;N;;;;; +265F;BLACK CHESS PAWN;So;0;ON;;;;;N;;;;; +2660;BLACK SPADE SUIT;So;0;ON;;;;;N;;;;; +2661;WHITE HEART SUIT;So;0;ON;;;;;N;;;;; +2662;WHITE DIAMOND SUIT;So;0;ON;;;;;N;;;;; +2663;BLACK CLUB SUIT;So;0;ON;;;;;N;;;;; +2664;WHITE SPADE SUIT;So;0;ON;;;;;N;;;;; +2665;BLACK HEART SUIT;So;0;ON;;;;;N;;;;; +2666;BLACK DIAMOND SUIT;So;0;ON;;;;;N;;;;; +2667;WHITE CLUB SUIT;So;0;ON;;;;;N;;;;; +2668;HOT SPRINGS;So;0;ON;;;;;N;;;;; +2669;QUARTER NOTE;So;0;ON;;;;;N;;;;; +266A;EIGHTH NOTE;So;0;ON;;;;;N;;;;; +266B;BEAMED EIGHTH NOTES;So;0;ON;;;;;N;BARRED EIGHTH NOTES;;;; +266C;BEAMED SIXTEENTH NOTES;So;0;ON;;;;;N;BARRED SIXTEENTH NOTES;;;; +266D;MUSIC FLAT SIGN;So;0;ON;;;;;N;FLAT;;;; +266E;MUSIC NATURAL SIGN;So;0;ON;;;;;N;NATURAL;;;; +266F;MUSIC SHARP SIGN;Sm;0;ON;;;;;N;SHARP;;;; +2670;WEST SYRIAC CROSS;So;0;ON;;;;;N;;;;; +2671;EAST SYRIAC CROSS;So;0;ON;;;;;N;;;;; +2672;UNIVERSAL RECYCLING SYMBOL;So;0;ON;;;;;N;;;;; +2673;RECYCLING SYMBOL FOR TYPE-1 PLASTICS;So;0;ON;;;;;N;;;;; +2674;RECYCLING SYMBOL FOR TYPE-2 PLASTICS;So;0;ON;;;;;N;;;;; +2675;RECYCLING SYMBOL FOR TYPE-3 PLASTICS;So;0;ON;;;;;N;;;;; +2676;RECYCLING SYMBOL FOR TYPE-4 PLASTICS;So;0;ON;;;;;N;;;;; +2677;RECYCLING SYMBOL FOR TYPE-5 PLASTICS;So;0;ON;;;;;N;;;;; +2678;RECYCLING SYMBOL FOR TYPE-6 PLASTICS;So;0;ON;;;;;N;;;;; +2679;RECYCLING SYMBOL FOR TYPE-7 PLASTICS;So;0;ON;;;;;N;;;;; +267A;RECYCLING SYMBOL FOR GENERIC MATERIALS;So;0;ON;;;;;N;;;;; +267B;BLACK UNIVERSAL RECYCLING SYMBOL;So;0;ON;;;;;N;;;;; +267C;RECYCLED PAPER SYMBOL;So;0;ON;;;;;N;;;;; +267D;PARTIALLY-RECYCLED PAPER SYMBOL;So;0;ON;;;;;N;;;;; +267E;PERMANENT PAPER SIGN;So;0;ON;;;;;N;;;;; +267F;WHEELCHAIR SYMBOL;So;0;ON;;;;;N;;;;; +2680;DIE FACE-1;So;0;ON;;;;;N;;;;; +2681;DIE FACE-2;So;0;ON;;;;;N;;;;; +2682;DIE FACE-3;So;0;ON;;;;;N;;;;; +2683;DIE FACE-4;So;0;ON;;;;;N;;;;; +2684;DIE FACE-5;So;0;ON;;;;;N;;;;; +2685;DIE FACE-6;So;0;ON;;;;;N;;;;; +2686;WHITE CIRCLE WITH DOT RIGHT;So;0;ON;;;;;N;;;;; +2687;WHITE CIRCLE WITH TWO DOTS;So;0;ON;;;;;N;;;;; +2688;BLACK CIRCLE WITH WHITE DOT RIGHT;So;0;ON;;;;;N;;;;; +2689;BLACK CIRCLE WITH TWO WHITE DOTS;So;0;ON;;;;;N;;;;; +268A;MONOGRAM FOR YANG;So;0;ON;;;;;N;;;;; +268B;MONOGRAM FOR YIN;So;0;ON;;;;;N;;;;; +268C;DIGRAM FOR GREATER YANG;So;0;ON;;;;;N;;;;; +268D;DIGRAM FOR LESSER YIN;So;0;ON;;;;;N;;;;; +268E;DIGRAM FOR LESSER YANG;So;0;ON;;;;;N;;;;; +268F;DIGRAM FOR GREATER YIN;So;0;ON;;;;;N;;;;; +2690;WHITE FLAG;So;0;ON;;;;;N;;;;; +2691;BLACK FLAG;So;0;ON;;;;;N;;;;; +2692;HAMMER AND PICK;So;0;ON;;;;;N;;;;; +2693;ANCHOR;So;0;ON;;;;;N;;;;; +2694;CROSSED SWORDS;So;0;ON;;;;;N;;;;; +2695;STAFF OF AESCULAPIUS;So;0;ON;;;;;N;;;;; +2696;SCALES;So;0;ON;;;;;N;;;;; +2697;ALEMBIC;So;0;ON;;;;;N;;;;; +2698;FLOWER;So;0;ON;;;;;N;;;;; +2699;GEAR;So;0;ON;;;;;N;;;;; +269A;STAFF OF HERMES;So;0;ON;;;;;N;;;;; +269B;ATOM SYMBOL;So;0;ON;;;;;N;;;;; +269C;FLEUR-DE-LIS;So;0;ON;;;;;N;;;;; +269D;OUTLINED WHITE STAR;So;0;ON;;;;;N;;;;; +269E;THREE LINES CONVERGING RIGHT;So;0;ON;;;;;N;;;;; +269F;THREE LINES CONVERGING LEFT;So;0;ON;;;;;N;;;;; +26A0;WARNING SIGN;So;0;ON;;;;;N;;;;; +26A1;HIGH VOLTAGE SIGN;So;0;ON;;;;;N;;;;; +26A2;DOUBLED FEMALE SIGN;So;0;ON;;;;;N;;;;; +26A3;DOUBLED MALE SIGN;So;0;ON;;;;;N;;;;; +26A4;INTERLOCKED FEMALE AND MALE SIGN;So;0;ON;;;;;N;;;;; +26A5;MALE AND FEMALE SIGN;So;0;ON;;;;;N;;;;; +26A6;MALE WITH STROKE SIGN;So;0;ON;;;;;N;;;;; +26A7;MALE WITH STROKE AND MALE AND FEMALE SIGN;So;0;ON;;;;;N;;;;; +26A8;VERTICAL MALE WITH STROKE SIGN;So;0;ON;;;;;N;;;;; +26A9;HORIZONTAL MALE WITH STROKE SIGN;So;0;ON;;;;;N;;;;; +26AA;MEDIUM WHITE CIRCLE;So;0;ON;;;;;N;;;;; +26AB;MEDIUM BLACK CIRCLE;So;0;ON;;;;;N;;;;; +26AC;MEDIUM SMALL WHITE CIRCLE;So;0;L;;;;;N;;;;; +26AD;MARRIAGE SYMBOL;So;0;ON;;;;;N;;;;; +26AE;DIVORCE SYMBOL;So;0;ON;;;;;N;;;;; +26AF;UNMARRIED PARTNERSHIP SYMBOL;So;0;ON;;;;;N;;;;; +26B0;COFFIN;So;0;ON;;;;;N;;;;; +26B1;FUNERAL URN;So;0;ON;;;;;N;;;;; +26B2;NEUTER;So;0;ON;;;;;N;;;;; +26B3;CERES;So;0;ON;;;;;N;;;;; +26B4;PALLAS;So;0;ON;;;;;N;;;;; +26B5;JUNO;So;0;ON;;;;;N;;;;; +26B6;VESTA;So;0;ON;;;;;N;;;;; +26B7;CHIRON;So;0;ON;;;;;N;;;;; +26B8;BLACK MOON LILITH;So;0;ON;;;;;N;;;;; +26B9;SEXTILE;So;0;ON;;;;;N;;;;; +26BA;SEMISEXTILE;So;0;ON;;;;;N;;;;; +26BB;QUINCUNX;So;0;ON;;;;;N;;;;; +26BC;SESQUIQUADRATE;So;0;ON;;;;;N;;;;; +26BD;SOCCER BALL;So;0;ON;;;;;N;;;;; +26BE;BASEBALL;So;0;ON;;;;;N;;;;; +26BF;SQUARED KEY;So;0;ON;;;;;N;;;;; +26C0;WHITE DRAUGHTS MAN;So;0;ON;;;;;N;;;;; +26C1;WHITE DRAUGHTS KING;So;0;ON;;;;;N;;;;; +26C2;BLACK DRAUGHTS MAN;So;0;ON;;;;;N;;;;; +26C3;BLACK DRAUGHTS KING;So;0;ON;;;;;N;;;;; +26C4;SNOWMAN WITHOUT SNOW;So;0;ON;;;;;N;;;;; +26C5;SUN BEHIND CLOUD;So;0;ON;;;;;N;;;;; +26C6;RAIN;So;0;ON;;;;;N;;;;; +26C7;BLACK SNOWMAN;So;0;ON;;;;;N;;;;; +26C8;THUNDER CLOUD AND RAIN;So;0;ON;;;;;N;;;;; +26C9;TURNED WHITE SHOGI PIECE;So;0;ON;;;;;N;;;;; +26CA;TURNED BLACK SHOGI PIECE;So;0;ON;;;;;N;;;;; +26CB;WHITE DIAMOND IN SQUARE;So;0;ON;;;;;N;;;;; +26CC;CROSSING LANES;So;0;ON;;;;;N;;;;; +26CD;DISABLED CAR;So;0;ON;;;;;N;;;;; +26CE;OPHIUCHUS;So;0;ON;;;;;N;;;;; +26CF;PICK;So;0;ON;;;;;N;;;;; +26D0;CAR SLIDING;So;0;ON;;;;;N;;;;; +26D1;HELMET WITH WHITE CROSS;So;0;ON;;;;;N;;;;; +26D2;CIRCLED CROSSING LANES;So;0;ON;;;;;N;;;;; +26D3;CHAINS;So;0;ON;;;;;N;;;;; +26D4;NO ENTRY;So;0;ON;;;;;N;;;;; +26D5;ALTERNATE ONE-WAY LEFT WAY TRAFFIC;So;0;ON;;;;;N;;;;; +26D6;BLACK TWO-WAY LEFT WAY TRAFFIC;So;0;ON;;;;;N;;;;; +26D7;WHITE TWO-WAY LEFT WAY TRAFFIC;So;0;ON;;;;;N;;;;; +26D8;BLACK LEFT LANE MERGE;So;0;ON;;;;;N;;;;; +26D9;WHITE LEFT LANE MERGE;So;0;ON;;;;;N;;;;; +26DA;DRIVE SLOW SIGN;So;0;ON;;;;;N;;;;; +26DB;HEAVY WHITE DOWN-POINTING TRIANGLE;So;0;ON;;;;;N;;;;; +26DC;LEFT CLOSED ENTRY;So;0;ON;;;;;N;;;;; +26DD;SQUARED SALTIRE;So;0;ON;;;;;N;;;;; +26DE;FALLING DIAGONAL IN WHITE CIRCLE IN BLACK SQUARE;So;0;ON;;;;;N;;;;; +26DF;BLACK TRUCK;So;0;ON;;;;;N;;;;; +26E0;RESTRICTED LEFT ENTRY-1;So;0;ON;;;;;N;;;;; +26E1;RESTRICTED LEFT ENTRY-2;So;0;ON;;;;;N;;;;; +26E2;ASTRONOMICAL SYMBOL FOR URANUS;So;0;ON;;;;;N;;;;; +26E3;HEAVY CIRCLE WITH STROKE AND TWO DOTS ABOVE;So;0;ON;;;;;N;;;;; +26E4;PENTAGRAM;So;0;ON;;;;;N;;;;; +26E5;RIGHT-HANDED INTERLACED PENTAGRAM;So;0;ON;;;;;N;;;;; +26E6;LEFT-HANDED INTERLACED PENTAGRAM;So;0;ON;;;;;N;;;;; +26E7;INVERTED PENTAGRAM;So;0;ON;;;;;N;;;;; +26E8;BLACK CROSS ON SHIELD;So;0;ON;;;;;N;;;;; +26E9;SHINTO SHRINE;So;0;ON;;;;;N;;;;; +26EA;CHURCH;So;0;ON;;;;;N;;;;; +26EB;CASTLE;So;0;ON;;;;;N;;;;; +26EC;HISTORIC SITE;So;0;ON;;;;;N;;;;; +26ED;GEAR WITHOUT HUB;So;0;ON;;;;;N;;;;; +26EE;GEAR WITH HANDLES;So;0;ON;;;;;N;;;;; +26EF;MAP SYMBOL FOR LIGHTHOUSE;So;0;ON;;;;;N;;;;; +26F0;MOUNTAIN;So;0;ON;;;;;N;;;;; +26F1;UMBRELLA ON GROUND;So;0;ON;;;;;N;;;;; +26F2;FOUNTAIN;So;0;ON;;;;;N;;;;; +26F3;FLAG IN HOLE;So;0;ON;;;;;N;;;;; +26F4;FERRY;So;0;ON;;;;;N;;;;; +26F5;SAILBOAT;So;0;ON;;;;;N;;;;; +26F6;SQUARE FOUR CORNERS;So;0;ON;;;;;N;;;;; +26F7;SKIER;So;0;ON;;;;;N;;;;; +26F8;ICE SKATE;So;0;ON;;;;;N;;;;; +26F9;PERSON WITH BALL;So;0;ON;;;;;N;;;;; +26FA;TENT;So;0;ON;;;;;N;;;;; +26FB;JAPANESE BANK SYMBOL;So;0;ON;;;;;N;;;;; +26FC;HEADSTONE GRAVEYARD SYMBOL;So;0;ON;;;;;N;;;;; +26FD;FUEL PUMP;So;0;ON;;;;;N;;;;; +26FE;CUP ON BLACK SQUARE;So;0;ON;;;;;N;;;;; +26FF;WHITE FLAG WITH HORIZONTAL MIDDLE BLACK STRIPE;So;0;ON;;;;;N;;;;; +2701;UPPER BLADE SCISSORS;So;0;ON;;;;;N;;;;; +2702;BLACK SCISSORS;So;0;ON;;;;;N;;;;; +2703;LOWER BLADE SCISSORS;So;0;ON;;;;;N;;;;; +2704;WHITE SCISSORS;So;0;ON;;;;;N;;;;; +2705;WHITE HEAVY CHECK MARK;So;0;ON;;;;;N;;;;; +2706;TELEPHONE LOCATION SIGN;So;0;ON;;;;;N;;;;; +2707;TAPE DRIVE;So;0;ON;;;;;N;;;;; +2708;AIRPLANE;So;0;ON;;;;;N;;;;; +2709;ENVELOPE;So;0;ON;;;;;N;;;;; +270A;RAISED FIST;So;0;ON;;;;;N;;;;; +270B;RAISED HAND;So;0;ON;;;;;N;;;;; +270C;VICTORY HAND;So;0;ON;;;;;N;;;;; +270D;WRITING HAND;So;0;ON;;;;;N;;;;; +270E;LOWER RIGHT PENCIL;So;0;ON;;;;;N;;;;; +270F;PENCIL;So;0;ON;;;;;N;;;;; +2710;UPPER RIGHT PENCIL;So;0;ON;;;;;N;;;;; +2711;WHITE NIB;So;0;ON;;;;;N;;;;; +2712;BLACK NIB;So;0;ON;;;;;N;;;;; +2713;CHECK MARK;So;0;ON;;;;;N;;;;; +2714;HEAVY CHECK MARK;So;0;ON;;;;;N;;;;; +2715;MULTIPLICATION X;So;0;ON;;;;;N;;;;; +2716;HEAVY MULTIPLICATION X;So;0;ON;;;;;N;;;;; +2717;BALLOT X;So;0;ON;;;;;N;;;;; +2718;HEAVY BALLOT X;So;0;ON;;;;;N;;;;; +2719;OUTLINED GREEK CROSS;So;0;ON;;;;;N;;;;; +271A;HEAVY GREEK CROSS;So;0;ON;;;;;N;;;;; +271B;OPEN CENTRE CROSS;So;0;ON;;;;;N;OPEN CENTER CROSS;;;; +271C;HEAVY OPEN CENTRE CROSS;So;0;ON;;;;;N;HEAVY OPEN CENTER CROSS;;;; +271D;LATIN CROSS;So;0;ON;;;;;N;;;;; +271E;SHADOWED WHITE LATIN CROSS;So;0;ON;;;;;N;;;;; +271F;OUTLINED LATIN CROSS;So;0;ON;;;;;N;;;;; +2720;MALTESE CROSS;So;0;ON;;;;;N;;;;; +2721;STAR OF DAVID;So;0;ON;;;;;N;;;;; +2722;FOUR TEARDROP-SPOKED ASTERISK;So;0;ON;;;;;N;;;;; +2723;FOUR BALLOON-SPOKED ASTERISK;So;0;ON;;;;;N;;;;; +2724;HEAVY FOUR BALLOON-SPOKED ASTERISK;So;0;ON;;;;;N;;;;; +2725;FOUR CLUB-SPOKED ASTERISK;So;0;ON;;;;;N;;;;; +2726;BLACK FOUR POINTED STAR;So;0;ON;;;;;N;;;;; +2727;WHITE FOUR POINTED STAR;So;0;ON;;;;;N;;;;; +2728;SPARKLES;So;0;ON;;;;;N;;;;; +2729;STRESS OUTLINED WHITE STAR;So;0;ON;;;;;N;;;;; +272A;CIRCLED WHITE STAR;So;0;ON;;;;;N;;;;; +272B;OPEN CENTRE BLACK STAR;So;0;ON;;;;;N;OPEN CENTER BLACK STAR;;;; +272C;BLACK CENTRE WHITE STAR;So;0;ON;;;;;N;BLACK CENTER WHITE STAR;;;; +272D;OUTLINED BLACK STAR;So;0;ON;;;;;N;;;;; +272E;HEAVY OUTLINED BLACK STAR;So;0;ON;;;;;N;;;;; +272F;PINWHEEL STAR;So;0;ON;;;;;N;;;;; +2730;SHADOWED WHITE STAR;So;0;ON;;;;;N;;;;; +2731;HEAVY ASTERISK;So;0;ON;;;;;N;;;;; +2732;OPEN CENTRE ASTERISK;So;0;ON;;;;;N;OPEN CENTER ASTERISK;;;; +2733;EIGHT SPOKED ASTERISK;So;0;ON;;;;;N;;;;; +2734;EIGHT POINTED BLACK STAR;So;0;ON;;;;;N;;;;; +2735;EIGHT POINTED PINWHEEL STAR;So;0;ON;;;;;N;;;;; +2736;SIX POINTED BLACK STAR;So;0;ON;;;;;N;;;;; +2737;EIGHT POINTED RECTILINEAR BLACK STAR;So;0;ON;;;;;N;;;;; +2738;HEAVY EIGHT POINTED RECTILINEAR BLACK STAR;So;0;ON;;;;;N;;;;; +2739;TWELVE POINTED BLACK STAR;So;0;ON;;;;;N;;;;; +273A;SIXTEEN POINTED ASTERISK;So;0;ON;;;;;N;;;;; +273B;TEARDROP-SPOKED ASTERISK;So;0;ON;;;;;N;;;;; +273C;OPEN CENTRE TEARDROP-SPOKED ASTERISK;So;0;ON;;;;;N;OPEN CENTER TEARDROP-SPOKED ASTERISK;;;; +273D;HEAVY TEARDROP-SPOKED ASTERISK;So;0;ON;;;;;N;;;;; +273E;SIX PETALLED BLACK AND WHITE FLORETTE;So;0;ON;;;;;N;;;;; +273F;BLACK FLORETTE;So;0;ON;;;;;N;;;;; +2740;WHITE FLORETTE;So;0;ON;;;;;N;;;;; +2741;EIGHT PETALLED OUTLINED BLACK FLORETTE;So;0;ON;;;;;N;;;;; +2742;CIRCLED OPEN CENTRE EIGHT POINTED STAR;So;0;ON;;;;;N;CIRCLED OPEN CENTER EIGHT POINTED STAR;;;; +2743;HEAVY TEARDROP-SPOKED PINWHEEL ASTERISK;So;0;ON;;;;;N;;;;; +2744;SNOWFLAKE;So;0;ON;;;;;N;;;;; +2745;TIGHT TRIFOLIATE SNOWFLAKE;So;0;ON;;;;;N;;;;; +2746;HEAVY CHEVRON SNOWFLAKE;So;0;ON;;;;;N;;;;; +2747;SPARKLE;So;0;ON;;;;;N;;;;; +2748;HEAVY SPARKLE;So;0;ON;;;;;N;;;;; +2749;BALLOON-SPOKED ASTERISK;So;0;ON;;;;;N;;;;; +274A;EIGHT TEARDROP-SPOKED PROPELLER ASTERISK;So;0;ON;;;;;N;;;;; +274B;HEAVY EIGHT TEARDROP-SPOKED PROPELLER ASTERISK;So;0;ON;;;;;N;;;;; +274C;CROSS MARK;So;0;ON;;;;;N;;;;; +274D;SHADOWED WHITE CIRCLE;So;0;ON;;;;;N;;;;; +274E;NEGATIVE SQUARED CROSS MARK;So;0;ON;;;;;N;;;;; +274F;LOWER RIGHT DROP-SHADOWED WHITE SQUARE;So;0;ON;;;;;N;;;;; +2750;UPPER RIGHT DROP-SHADOWED WHITE SQUARE;So;0;ON;;;;;N;;;;; +2751;LOWER RIGHT SHADOWED WHITE SQUARE;So;0;ON;;;;;N;;;;; +2752;UPPER RIGHT SHADOWED WHITE SQUARE;So;0;ON;;;;;N;;;;; +2753;BLACK QUESTION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +2754;WHITE QUESTION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +2755;WHITE EXCLAMATION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +2756;BLACK DIAMOND MINUS WHITE X;So;0;ON;;;;;N;;;;; +2757;HEAVY EXCLAMATION MARK SYMBOL;So;0;ON;;;;;N;;;;; +2758;LIGHT VERTICAL BAR;So;0;ON;;;;;N;;;;; +2759;MEDIUM VERTICAL BAR;So;0;ON;;;;;N;;;;; +275A;HEAVY VERTICAL BAR;So;0;ON;;;;;N;;;;; +275B;HEAVY SINGLE TURNED COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +275C;HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +275D;HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +275E;HEAVY DOUBLE COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +275F;HEAVY LOW SINGLE COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +2760;HEAVY LOW DOUBLE COMMA QUOTATION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +2761;CURVED STEM PARAGRAPH SIGN ORNAMENT;So;0;ON;;;;;N;;;;; +2762;HEAVY EXCLAMATION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +2763;HEAVY HEART EXCLAMATION MARK ORNAMENT;So;0;ON;;;;;N;;;;; +2764;HEAVY BLACK HEART;So;0;ON;;;;;N;;;;; +2765;ROTATED HEAVY BLACK HEART BULLET;So;0;ON;;;;;N;;;;; +2766;FLORAL HEART;So;0;ON;;;;;N;;;;; +2767;ROTATED FLORAL HEART BULLET;So;0;ON;;;;;N;;;;; +2768;MEDIUM LEFT PARENTHESIS ORNAMENT;Ps;0;ON;;;;;Y;;;;; +2769;MEDIUM RIGHT PARENTHESIS ORNAMENT;Pe;0;ON;;;;;Y;;;;; +276A;MEDIUM FLATTENED LEFT PARENTHESIS ORNAMENT;Ps;0;ON;;;;;Y;;;;; +276B;MEDIUM FLATTENED RIGHT PARENTHESIS ORNAMENT;Pe;0;ON;;;;;Y;;;;; +276C;MEDIUM LEFT-POINTING ANGLE BRACKET ORNAMENT;Ps;0;ON;;;;;Y;;;;; +276D;MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT;Pe;0;ON;;;;;Y;;;;; +276E;HEAVY LEFT-POINTING ANGLE QUOTATION MARK ORNAMENT;Ps;0;ON;;;;;Y;;;;; +276F;HEAVY RIGHT-POINTING ANGLE QUOTATION MARK ORNAMENT;Pe;0;ON;;;;;Y;;;;; +2770;HEAVY LEFT-POINTING ANGLE BRACKET ORNAMENT;Ps;0;ON;;;;;Y;;;;; +2771;HEAVY RIGHT-POINTING ANGLE BRACKET ORNAMENT;Pe;0;ON;;;;;Y;;;;; +2772;LIGHT LEFT TORTOISE SHELL BRACKET ORNAMENT;Ps;0;ON;;;;;Y;;;;; +2773;LIGHT RIGHT TORTOISE SHELL BRACKET ORNAMENT;Pe;0;ON;;;;;Y;;;;; +2774;MEDIUM LEFT CURLY BRACKET ORNAMENT;Ps;0;ON;;;;;Y;;;;; +2775;MEDIUM RIGHT CURLY BRACKET ORNAMENT;Pe;0;ON;;;;;Y;;;;; +2776;DINGBAT NEGATIVE CIRCLED DIGIT ONE;No;0;ON;;;1;1;N;INVERSE CIRCLED DIGIT ONE;;;; +2777;DINGBAT NEGATIVE CIRCLED DIGIT TWO;No;0;ON;;;2;2;N;INVERSE CIRCLED DIGIT TWO;;;; +2778;DINGBAT NEGATIVE CIRCLED DIGIT THREE;No;0;ON;;;3;3;N;INVERSE CIRCLED DIGIT THREE;;;; +2779;DINGBAT NEGATIVE CIRCLED DIGIT FOUR;No;0;ON;;;4;4;N;INVERSE CIRCLED DIGIT FOUR;;;; +277A;DINGBAT NEGATIVE CIRCLED DIGIT FIVE;No;0;ON;;;5;5;N;INVERSE CIRCLED DIGIT FIVE;;;; +277B;DINGBAT NEGATIVE CIRCLED DIGIT SIX;No;0;ON;;;6;6;N;INVERSE CIRCLED DIGIT SIX;;;; +277C;DINGBAT NEGATIVE CIRCLED DIGIT SEVEN;No;0;ON;;;7;7;N;INVERSE CIRCLED DIGIT SEVEN;;;; +277D;DINGBAT NEGATIVE CIRCLED DIGIT EIGHT;No;0;ON;;;8;8;N;INVERSE CIRCLED DIGIT EIGHT;;;; +277E;DINGBAT NEGATIVE CIRCLED DIGIT NINE;No;0;ON;;;9;9;N;INVERSE CIRCLED DIGIT NINE;;;; +277F;DINGBAT NEGATIVE CIRCLED NUMBER TEN;No;0;ON;;;;10;N;INVERSE CIRCLED NUMBER TEN;;;; +2780;DINGBAT CIRCLED SANS-SERIF DIGIT ONE;No;0;ON;;;1;1;N;CIRCLED SANS-SERIF DIGIT ONE;;;; +2781;DINGBAT CIRCLED SANS-SERIF DIGIT TWO;No;0;ON;;;2;2;N;CIRCLED SANS-SERIF DIGIT TWO;;;; +2782;DINGBAT CIRCLED SANS-SERIF DIGIT THREE;No;0;ON;;;3;3;N;CIRCLED SANS-SERIF DIGIT THREE;;;; +2783;DINGBAT CIRCLED SANS-SERIF DIGIT FOUR;No;0;ON;;;4;4;N;CIRCLED SANS-SERIF DIGIT FOUR;;;; +2784;DINGBAT CIRCLED SANS-SERIF DIGIT FIVE;No;0;ON;;;5;5;N;CIRCLED SANS-SERIF DIGIT FIVE;;;; +2785;DINGBAT CIRCLED SANS-SERIF DIGIT SIX;No;0;ON;;;6;6;N;CIRCLED SANS-SERIF DIGIT SIX;;;; +2786;DINGBAT CIRCLED SANS-SERIF DIGIT SEVEN;No;0;ON;;;7;7;N;CIRCLED SANS-SERIF DIGIT SEVEN;;;; +2787;DINGBAT CIRCLED SANS-SERIF DIGIT EIGHT;No;0;ON;;;8;8;N;CIRCLED SANS-SERIF DIGIT EIGHT;;;; +2788;DINGBAT CIRCLED SANS-SERIF DIGIT NINE;No;0;ON;;;9;9;N;CIRCLED SANS-SERIF DIGIT NINE;;;; +2789;DINGBAT CIRCLED SANS-SERIF NUMBER TEN;No;0;ON;;;;10;N;CIRCLED SANS-SERIF NUMBER TEN;;;; +278A;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT ONE;No;0;ON;;;1;1;N;INVERSE CIRCLED SANS-SERIF DIGIT ONE;;;; +278B;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT TWO;No;0;ON;;;2;2;N;INVERSE CIRCLED SANS-SERIF DIGIT TWO;;;; +278C;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT THREE;No;0;ON;;;3;3;N;INVERSE CIRCLED SANS-SERIF DIGIT THREE;;;; +278D;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FOUR;No;0;ON;;;4;4;N;INVERSE CIRCLED SANS-SERIF DIGIT FOUR;;;; +278E;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT FIVE;No;0;ON;;;5;5;N;INVERSE CIRCLED SANS-SERIF DIGIT FIVE;;;; +278F;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SIX;No;0;ON;;;6;6;N;INVERSE CIRCLED SANS-SERIF DIGIT SIX;;;; +2790;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT SEVEN;No;0;ON;;;7;7;N;INVERSE CIRCLED SANS-SERIF DIGIT SEVEN;;;; +2791;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT EIGHT;No;0;ON;;;8;8;N;INVERSE CIRCLED SANS-SERIF DIGIT EIGHT;;;; +2792;DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT NINE;No;0;ON;;;9;9;N;INVERSE CIRCLED SANS-SERIF DIGIT NINE;;;; +2793;DINGBAT NEGATIVE CIRCLED SANS-SERIF NUMBER TEN;No;0;ON;;;;10;N;INVERSE CIRCLED SANS-SERIF NUMBER TEN;;;; +2794;HEAVY WIDE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY WIDE-HEADED RIGHT ARROW;;;; +2795;HEAVY PLUS SIGN;So;0;ON;;;;;N;;;;; +2796;HEAVY MINUS SIGN;So;0;ON;;;;;N;;;;; +2797;HEAVY DIVISION SIGN;So;0;ON;;;;;N;;;;; +2798;HEAVY SOUTH EAST ARROW;So;0;ON;;;;;N;HEAVY LOWER RIGHT ARROW;;;; +2799;HEAVY RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY RIGHT ARROW;;;; +279A;HEAVY NORTH EAST ARROW;So;0;ON;;;;;N;HEAVY UPPER RIGHT ARROW;;;; +279B;DRAFTING POINT RIGHTWARDS ARROW;So;0;ON;;;;;N;DRAFTING POINT RIGHT ARROW;;;; +279C;HEAVY ROUND-TIPPED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY ROUND-TIPPED RIGHT ARROW;;;; +279D;TRIANGLE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;TRIANGLE-HEADED RIGHT ARROW;;;; +279E;HEAVY TRIANGLE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY TRIANGLE-HEADED RIGHT ARROW;;;; +279F;DASHED TRIANGLE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;DASHED TRIANGLE-HEADED RIGHT ARROW;;;; +27A0;HEAVY DASHED TRIANGLE-HEADED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY DASHED TRIANGLE-HEADED RIGHT ARROW;;;; +27A1;BLACK RIGHTWARDS ARROW;So;0;ON;;;;;N;BLACK RIGHT ARROW;;;; +27A2;THREE-D TOP-LIGHTED RIGHTWARDS ARROWHEAD;So;0;ON;;;;;N;THREE-D TOP-LIGHTED RIGHT ARROWHEAD;;;; +27A3;THREE-D BOTTOM-LIGHTED RIGHTWARDS ARROWHEAD;So;0;ON;;;;;N;THREE-D BOTTOM-LIGHTED RIGHT ARROWHEAD;;;; +27A4;BLACK RIGHTWARDS ARROWHEAD;So;0;ON;;;;;N;BLACK RIGHT ARROWHEAD;;;; +27A5;HEAVY BLACK CURVED DOWNWARDS AND RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY BLACK CURVED DOWN AND RIGHT ARROW;;;; +27A6;HEAVY BLACK CURVED UPWARDS AND RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY BLACK CURVED UP AND RIGHT ARROW;;;; +27A7;SQUAT BLACK RIGHTWARDS ARROW;So;0;ON;;;;;N;SQUAT BLACK RIGHT ARROW;;;; +27A8;HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY CONCAVE-POINTED BLACK RIGHT ARROW;;;; +27A9;RIGHT-SHADED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;RIGHT-SHADED WHITE RIGHT ARROW;;;; +27AA;LEFT-SHADED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;LEFT-SHADED WHITE RIGHT ARROW;;;; +27AB;BACK-TILTED SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;BACK-TILTED SHADOWED WHITE RIGHT ARROW;;;; +27AC;FRONT-TILTED SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;FRONT-TILTED SHADOWED WHITE RIGHT ARROW;;;; +27AD;HEAVY LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY LOWER RIGHT-SHADOWED WHITE RIGHT ARROW;;;; +27AE;HEAVY UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY UPPER RIGHT-SHADOWED WHITE RIGHT ARROW;;;; +27AF;NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHT ARROW;;;; +27B0;CURLY LOOP;So;0;ON;;;;;N;;;;; +27B1;NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHT ARROW;;;; +27B2;CIRCLED HEAVY WHITE RIGHTWARDS ARROW;So;0;ON;;;;;N;CIRCLED HEAVY WHITE RIGHT ARROW;;;; +27B3;WHITE-FEATHERED RIGHTWARDS ARROW;So;0;ON;;;;;N;WHITE-FEATHERED RIGHT ARROW;;;; +27B4;BLACK-FEATHERED SOUTH EAST ARROW;So;0;ON;;;;;N;BLACK-FEATHERED LOWER RIGHT ARROW;;;; +27B5;BLACK-FEATHERED RIGHTWARDS ARROW;So;0;ON;;;;;N;BLACK-FEATHERED RIGHT ARROW;;;; +27B6;BLACK-FEATHERED NORTH EAST ARROW;So;0;ON;;;;;N;BLACK-FEATHERED UPPER RIGHT ARROW;;;; +27B7;HEAVY BLACK-FEATHERED SOUTH EAST ARROW;So;0;ON;;;;;N;HEAVY BLACK-FEATHERED LOWER RIGHT ARROW;;;; +27B8;HEAVY BLACK-FEATHERED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY BLACK-FEATHERED RIGHT ARROW;;;; +27B9;HEAVY BLACK-FEATHERED NORTH EAST ARROW;So;0;ON;;;;;N;HEAVY BLACK-FEATHERED UPPER RIGHT ARROW;;;; +27BA;TEARDROP-BARBED RIGHTWARDS ARROW;So;0;ON;;;;;N;TEARDROP-BARBED RIGHT ARROW;;;; +27BB;HEAVY TEARDROP-SHANKED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY TEARDROP-SHANKED RIGHT ARROW;;;; +27BC;WEDGE-TAILED RIGHTWARDS ARROW;So;0;ON;;;;;N;WEDGE-TAILED RIGHT ARROW;;;; +27BD;HEAVY WEDGE-TAILED RIGHTWARDS ARROW;So;0;ON;;;;;N;HEAVY WEDGE-TAILED RIGHT ARROW;;;; +27BE;OPEN-OUTLINED RIGHTWARDS ARROW;So;0;ON;;;;;N;OPEN-OUTLINED RIGHT ARROW;;;; +27BF;DOUBLE CURLY LOOP;So;0;ON;;;;;N;;;;; +27C0;THREE DIMENSIONAL ANGLE;Sm;0;ON;;;;;Y;;;;; +27C1;WHITE TRIANGLE CONTAINING SMALL WHITE TRIANGLE;Sm;0;ON;;;;;N;;;;; +27C2;PERPENDICULAR;Sm;0;ON;;;;;N;;;;; +27C3;OPEN SUBSET;Sm;0;ON;;;;;Y;;;;; +27C4;OPEN SUPERSET;Sm;0;ON;;;;;Y;;;;; +27C5;LEFT S-SHAPED BAG DELIMITER;Ps;0;ON;;;;;Y;;;;; +27C6;RIGHT S-SHAPED BAG DELIMITER;Pe;0;ON;;;;;Y;;;;; +27C7;OR WITH DOT INSIDE;Sm;0;ON;;;;;N;;;;; +27C8;REVERSE SOLIDUS PRECEDING SUBSET;Sm;0;ON;;;;;Y;;;;; +27C9;SUPERSET PRECEDING SOLIDUS;Sm;0;ON;;;;;Y;;;;; +27CA;VERTICAL BAR WITH HORIZONTAL STROKE;Sm;0;ON;;;;;N;;;;; +27CB;MATHEMATICAL RISING DIAGONAL;Sm;0;ON;;;;;Y;;;;; +27CC;LONG DIVISION;Sm;0;ON;;;;;Y;;;;; +27CD;MATHEMATICAL FALLING DIAGONAL;Sm;0;ON;;;;;Y;;;;; +27CE;SQUARED LOGICAL AND;Sm;0;ON;;;;;N;;;;; +27CF;SQUARED LOGICAL OR;Sm;0;ON;;;;;N;;;;; +27D0;WHITE DIAMOND WITH CENTRED DOT;Sm;0;ON;;;;;N;;;;; +27D1;AND WITH DOT;Sm;0;ON;;;;;N;;;;; +27D2;ELEMENT OF OPENING UPWARDS;Sm;0;ON;;;;;N;;;;; +27D3;LOWER RIGHT CORNER WITH DOT;Sm;0;ON;;;;;Y;;;;; +27D4;UPPER LEFT CORNER WITH DOT;Sm;0;ON;;;;;Y;;;;; +27D5;LEFT OUTER JOIN;Sm;0;ON;;;;;Y;;;;; +27D6;RIGHT OUTER JOIN;Sm;0;ON;;;;;Y;;;;; +27D7;FULL OUTER JOIN;Sm;0;ON;;;;;N;;;;; +27D8;LARGE UP TACK;Sm;0;ON;;;;;N;;;;; +27D9;LARGE DOWN TACK;Sm;0;ON;;;;;N;;;;; +27DA;LEFT AND RIGHT DOUBLE TURNSTILE;Sm;0;ON;;;;;N;;;;; +27DB;LEFT AND RIGHT TACK;Sm;0;ON;;;;;N;;;;; +27DC;LEFT MULTIMAP;Sm;0;ON;;;;;Y;;;;; +27DD;LONG RIGHT TACK;Sm;0;ON;;;;;Y;;;;; +27DE;LONG LEFT TACK;Sm;0;ON;;;;;Y;;;;; +27DF;UP TACK WITH CIRCLE ABOVE;Sm;0;ON;;;;;N;;;;; +27E0;LOZENGE DIVIDED BY HORIZONTAL RULE;Sm;0;ON;;;;;N;;;;; +27E1;WHITE CONCAVE-SIDED DIAMOND;Sm;0;ON;;;;;N;;;;; +27E2;WHITE CONCAVE-SIDED DIAMOND WITH LEFTWARDS TICK;Sm;0;ON;;;;;Y;;;;; +27E3;WHITE CONCAVE-SIDED DIAMOND WITH RIGHTWARDS TICK;Sm;0;ON;;;;;Y;;;;; +27E4;WHITE SQUARE WITH LEFTWARDS TICK;Sm;0;ON;;;;;Y;;;;; +27E5;WHITE SQUARE WITH RIGHTWARDS TICK;Sm;0;ON;;;;;Y;;;;; +27E6;MATHEMATICAL LEFT WHITE SQUARE BRACKET;Ps;0;ON;;;;;Y;;;;; +27E7;MATHEMATICAL RIGHT WHITE SQUARE BRACKET;Pe;0;ON;;;;;Y;;;;; +27E8;MATHEMATICAL LEFT ANGLE BRACKET;Ps;0;ON;;;;;Y;;;;; +27E9;MATHEMATICAL RIGHT ANGLE BRACKET;Pe;0;ON;;;;;Y;;;;; +27EA;MATHEMATICAL LEFT DOUBLE ANGLE BRACKET;Ps;0;ON;;;;;Y;;;;; +27EB;MATHEMATICAL RIGHT DOUBLE ANGLE BRACKET;Pe;0;ON;;;;;Y;;;;; +27EC;MATHEMATICAL LEFT WHITE TORTOISE SHELL BRACKET;Ps;0;ON;;;;;Y;;;;; +27ED;MATHEMATICAL RIGHT WHITE TORTOISE SHELL BRACKET;Pe;0;ON;;;;;Y;;;;; +27EE;MATHEMATICAL LEFT FLATTENED PARENTHESIS;Ps;0;ON;;;;;Y;;;;; +27EF;MATHEMATICAL RIGHT FLATTENED PARENTHESIS;Pe;0;ON;;;;;Y;;;;; +27F0;UPWARDS QUADRUPLE ARROW;Sm;0;ON;;;;;N;;;;; +27F1;DOWNWARDS QUADRUPLE ARROW;Sm;0;ON;;;;;N;;;;; +27F2;ANTICLOCKWISE GAPPED CIRCLE ARROW;Sm;0;ON;;;;;N;;;;; +27F3;CLOCKWISE GAPPED CIRCLE ARROW;Sm;0;ON;;;;;N;;;;; +27F4;RIGHT ARROW WITH CIRCLED PLUS;Sm;0;ON;;;;;N;;;;; +27F5;LONG LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +27F6;LONG RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +27F7;LONG LEFT RIGHT ARROW;Sm;0;ON;;;;;N;;;;; +27F8;LONG LEFTWARDS DOUBLE ARROW;Sm;0;ON;;;;;N;;;;; +27F9;LONG RIGHTWARDS DOUBLE ARROW;Sm;0;ON;;;;;N;;;;; +27FA;LONG LEFT RIGHT DOUBLE ARROW;Sm;0;ON;;;;;N;;;;; +27FB;LONG LEFTWARDS ARROW FROM BAR;Sm;0;ON;;;;;N;;;;; +27FC;LONG RIGHTWARDS ARROW FROM BAR;Sm;0;ON;;;;;N;;;;; +27FD;LONG LEFTWARDS DOUBLE ARROW FROM BAR;Sm;0;ON;;;;;N;;;;; +27FE;LONG RIGHTWARDS DOUBLE ARROW FROM BAR;Sm;0;ON;;;;;N;;;;; +27FF;LONG RIGHTWARDS SQUIGGLE ARROW;Sm;0;ON;;;;;N;;;;; +2800;BRAILLE PATTERN BLANK;So;0;L;;;;;N;;;;; +2801;BRAILLE PATTERN DOTS-1;So;0;L;;;;;N;;;;; +2802;BRAILLE PATTERN DOTS-2;So;0;L;;;;;N;;;;; +2803;BRAILLE PATTERN DOTS-12;So;0;L;;;;;N;;;;; +2804;BRAILLE PATTERN DOTS-3;So;0;L;;;;;N;;;;; +2805;BRAILLE PATTERN DOTS-13;So;0;L;;;;;N;;;;; +2806;BRAILLE PATTERN DOTS-23;So;0;L;;;;;N;;;;; +2807;BRAILLE PATTERN DOTS-123;So;0;L;;;;;N;;;;; +2808;BRAILLE PATTERN DOTS-4;So;0;L;;;;;N;;;;; +2809;BRAILLE PATTERN DOTS-14;So;0;L;;;;;N;;;;; +280A;BRAILLE PATTERN DOTS-24;So;0;L;;;;;N;;;;; +280B;BRAILLE PATTERN DOTS-124;So;0;L;;;;;N;;;;; +280C;BRAILLE PATTERN DOTS-34;So;0;L;;;;;N;;;;; +280D;BRAILLE PATTERN DOTS-134;So;0;L;;;;;N;;;;; +280E;BRAILLE PATTERN DOTS-234;So;0;L;;;;;N;;;;; +280F;BRAILLE PATTERN DOTS-1234;So;0;L;;;;;N;;;;; +2810;BRAILLE PATTERN DOTS-5;So;0;L;;;;;N;;;;; +2811;BRAILLE PATTERN DOTS-15;So;0;L;;;;;N;;;;; +2812;BRAILLE PATTERN DOTS-25;So;0;L;;;;;N;;;;; +2813;BRAILLE PATTERN DOTS-125;So;0;L;;;;;N;;;;; +2814;BRAILLE PATTERN DOTS-35;So;0;L;;;;;N;;;;; +2815;BRAILLE PATTERN DOTS-135;So;0;L;;;;;N;;;;; +2816;BRAILLE PATTERN DOTS-235;So;0;L;;;;;N;;;;; +2817;BRAILLE PATTERN DOTS-1235;So;0;L;;;;;N;;;;; +2818;BRAILLE PATTERN DOTS-45;So;0;L;;;;;N;;;;; +2819;BRAILLE PATTERN DOTS-145;So;0;L;;;;;N;;;;; +281A;BRAILLE PATTERN DOTS-245;So;0;L;;;;;N;;;;; +281B;BRAILLE PATTERN DOTS-1245;So;0;L;;;;;N;;;;; +281C;BRAILLE PATTERN DOTS-345;So;0;L;;;;;N;;;;; +281D;BRAILLE PATTERN DOTS-1345;So;0;L;;;;;N;;;;; +281E;BRAILLE PATTERN DOTS-2345;So;0;L;;;;;N;;;;; +281F;BRAILLE PATTERN DOTS-12345;So;0;L;;;;;N;;;;; +2820;BRAILLE PATTERN DOTS-6;So;0;L;;;;;N;;;;; +2821;BRAILLE PATTERN DOTS-16;So;0;L;;;;;N;;;;; +2822;BRAILLE PATTERN DOTS-26;So;0;L;;;;;N;;;;; +2823;BRAILLE PATTERN DOTS-126;So;0;L;;;;;N;;;;; +2824;BRAILLE PATTERN DOTS-36;So;0;L;;;;;N;;;;; +2825;BRAILLE PATTERN DOTS-136;So;0;L;;;;;N;;;;; +2826;BRAILLE PATTERN DOTS-236;So;0;L;;;;;N;;;;; +2827;BRAILLE PATTERN DOTS-1236;So;0;L;;;;;N;;;;; +2828;BRAILLE PATTERN DOTS-46;So;0;L;;;;;N;;;;; +2829;BRAILLE PATTERN DOTS-146;So;0;L;;;;;N;;;;; +282A;BRAILLE PATTERN DOTS-246;So;0;L;;;;;N;;;;; +282B;BRAILLE PATTERN DOTS-1246;So;0;L;;;;;N;;;;; +282C;BRAILLE PATTERN DOTS-346;So;0;L;;;;;N;;;;; +282D;BRAILLE PATTERN DOTS-1346;So;0;L;;;;;N;;;;; +282E;BRAILLE PATTERN DOTS-2346;So;0;L;;;;;N;;;;; +282F;BRAILLE PATTERN DOTS-12346;So;0;L;;;;;N;;;;; +2830;BRAILLE PATTERN DOTS-56;So;0;L;;;;;N;;;;; +2831;BRAILLE PATTERN DOTS-156;So;0;L;;;;;N;;;;; +2832;BRAILLE PATTERN DOTS-256;So;0;L;;;;;N;;;;; +2833;BRAILLE PATTERN DOTS-1256;So;0;L;;;;;N;;;;; +2834;BRAILLE PATTERN DOTS-356;So;0;L;;;;;N;;;;; +2835;BRAILLE PATTERN DOTS-1356;So;0;L;;;;;N;;;;; +2836;BRAILLE PATTERN DOTS-2356;So;0;L;;;;;N;;;;; +2837;BRAILLE PATTERN DOTS-12356;So;0;L;;;;;N;;;;; +2838;BRAILLE PATTERN DOTS-456;So;0;L;;;;;N;;;;; +2839;BRAILLE PATTERN DOTS-1456;So;0;L;;;;;N;;;;; +283A;BRAILLE PATTERN DOTS-2456;So;0;L;;;;;N;;;;; +283B;BRAILLE PATTERN DOTS-12456;So;0;L;;;;;N;;;;; +283C;BRAILLE PATTERN DOTS-3456;So;0;L;;;;;N;;;;; +283D;BRAILLE PATTERN DOTS-13456;So;0;L;;;;;N;;;;; +283E;BRAILLE PATTERN DOTS-23456;So;0;L;;;;;N;;;;; +283F;BRAILLE PATTERN DOTS-123456;So;0;L;;;;;N;;;;; +2840;BRAILLE PATTERN DOTS-7;So;0;L;;;;;N;;;;; +2841;BRAILLE PATTERN DOTS-17;So;0;L;;;;;N;;;;; +2842;BRAILLE PATTERN DOTS-27;So;0;L;;;;;N;;;;; +2843;BRAILLE PATTERN DOTS-127;So;0;L;;;;;N;;;;; +2844;BRAILLE PATTERN DOTS-37;So;0;L;;;;;N;;;;; +2845;BRAILLE PATTERN DOTS-137;So;0;L;;;;;N;;;;; +2846;BRAILLE PATTERN DOTS-237;So;0;L;;;;;N;;;;; +2847;BRAILLE PATTERN DOTS-1237;So;0;L;;;;;N;;;;; +2848;BRAILLE PATTERN DOTS-47;So;0;L;;;;;N;;;;; +2849;BRAILLE PATTERN DOTS-147;So;0;L;;;;;N;;;;; +284A;BRAILLE PATTERN DOTS-247;So;0;L;;;;;N;;;;; +284B;BRAILLE PATTERN DOTS-1247;So;0;L;;;;;N;;;;; +284C;BRAILLE PATTERN DOTS-347;So;0;L;;;;;N;;;;; +284D;BRAILLE PATTERN DOTS-1347;So;0;L;;;;;N;;;;; +284E;BRAILLE PATTERN DOTS-2347;So;0;L;;;;;N;;;;; +284F;BRAILLE PATTERN DOTS-12347;So;0;L;;;;;N;;;;; +2850;BRAILLE PATTERN DOTS-57;So;0;L;;;;;N;;;;; +2851;BRAILLE PATTERN DOTS-157;So;0;L;;;;;N;;;;; +2852;BRAILLE PATTERN DOTS-257;So;0;L;;;;;N;;;;; +2853;BRAILLE PATTERN DOTS-1257;So;0;L;;;;;N;;;;; +2854;BRAILLE PATTERN DOTS-357;So;0;L;;;;;N;;;;; +2855;BRAILLE PATTERN DOTS-1357;So;0;L;;;;;N;;;;; +2856;BRAILLE PATTERN DOTS-2357;So;0;L;;;;;N;;;;; +2857;BRAILLE PATTERN DOTS-12357;So;0;L;;;;;N;;;;; +2858;BRAILLE PATTERN DOTS-457;So;0;L;;;;;N;;;;; +2859;BRAILLE PATTERN DOTS-1457;So;0;L;;;;;N;;;;; +285A;BRAILLE PATTERN DOTS-2457;So;0;L;;;;;N;;;;; +285B;BRAILLE PATTERN DOTS-12457;So;0;L;;;;;N;;;;; +285C;BRAILLE PATTERN DOTS-3457;So;0;L;;;;;N;;;;; +285D;BRAILLE PATTERN DOTS-13457;So;0;L;;;;;N;;;;; +285E;BRAILLE PATTERN DOTS-23457;So;0;L;;;;;N;;;;; +285F;BRAILLE PATTERN DOTS-123457;So;0;L;;;;;N;;;;; +2860;BRAILLE PATTERN DOTS-67;So;0;L;;;;;N;;;;; +2861;BRAILLE PATTERN DOTS-167;So;0;L;;;;;N;;;;; +2862;BRAILLE PATTERN DOTS-267;So;0;L;;;;;N;;;;; +2863;BRAILLE PATTERN DOTS-1267;So;0;L;;;;;N;;;;; +2864;BRAILLE PATTERN DOTS-367;So;0;L;;;;;N;;;;; +2865;BRAILLE PATTERN DOTS-1367;So;0;L;;;;;N;;;;; +2866;BRAILLE PATTERN DOTS-2367;So;0;L;;;;;N;;;;; +2867;BRAILLE PATTERN DOTS-12367;So;0;L;;;;;N;;;;; +2868;BRAILLE PATTERN DOTS-467;So;0;L;;;;;N;;;;; +2869;BRAILLE PATTERN DOTS-1467;So;0;L;;;;;N;;;;; +286A;BRAILLE PATTERN DOTS-2467;So;0;L;;;;;N;;;;; +286B;BRAILLE PATTERN DOTS-12467;So;0;L;;;;;N;;;;; +286C;BRAILLE PATTERN DOTS-3467;So;0;L;;;;;N;;;;; +286D;BRAILLE PATTERN DOTS-13467;So;0;L;;;;;N;;;;; +286E;BRAILLE PATTERN DOTS-23467;So;0;L;;;;;N;;;;; +286F;BRAILLE PATTERN DOTS-123467;So;0;L;;;;;N;;;;; +2870;BRAILLE PATTERN DOTS-567;So;0;L;;;;;N;;;;; +2871;BRAILLE PATTERN DOTS-1567;So;0;L;;;;;N;;;;; +2872;BRAILLE PATTERN DOTS-2567;So;0;L;;;;;N;;;;; +2873;BRAILLE PATTERN DOTS-12567;So;0;L;;;;;N;;;;; +2874;BRAILLE PATTERN DOTS-3567;So;0;L;;;;;N;;;;; +2875;BRAILLE PATTERN DOTS-13567;So;0;L;;;;;N;;;;; +2876;BRAILLE PATTERN DOTS-23567;So;0;L;;;;;N;;;;; +2877;BRAILLE PATTERN DOTS-123567;So;0;L;;;;;N;;;;; +2878;BRAILLE PATTERN DOTS-4567;So;0;L;;;;;N;;;;; +2879;BRAILLE PATTERN DOTS-14567;So;0;L;;;;;N;;;;; +287A;BRAILLE PATTERN DOTS-24567;So;0;L;;;;;N;;;;; +287B;BRAILLE PATTERN DOTS-124567;So;0;L;;;;;N;;;;; +287C;BRAILLE PATTERN DOTS-34567;So;0;L;;;;;N;;;;; +287D;BRAILLE PATTERN DOTS-134567;So;0;L;;;;;N;;;;; +287E;BRAILLE PATTERN DOTS-234567;So;0;L;;;;;N;;;;; +287F;BRAILLE PATTERN DOTS-1234567;So;0;L;;;;;N;;;;; +2880;BRAILLE PATTERN DOTS-8;So;0;L;;;;;N;;;;; +2881;BRAILLE PATTERN DOTS-18;So;0;L;;;;;N;;;;; +2882;BRAILLE PATTERN DOTS-28;So;0;L;;;;;N;;;;; +2883;BRAILLE PATTERN DOTS-128;So;0;L;;;;;N;;;;; +2884;BRAILLE PATTERN DOTS-38;So;0;L;;;;;N;;;;; +2885;BRAILLE PATTERN DOTS-138;So;0;L;;;;;N;;;;; +2886;BRAILLE PATTERN DOTS-238;So;0;L;;;;;N;;;;; +2887;BRAILLE PATTERN DOTS-1238;So;0;L;;;;;N;;;;; +2888;BRAILLE PATTERN DOTS-48;So;0;L;;;;;N;;;;; +2889;BRAILLE PATTERN DOTS-148;So;0;L;;;;;N;;;;; +288A;BRAILLE PATTERN DOTS-248;So;0;L;;;;;N;;;;; +288B;BRAILLE PATTERN DOTS-1248;So;0;L;;;;;N;;;;; +288C;BRAILLE PATTERN DOTS-348;So;0;L;;;;;N;;;;; +288D;BRAILLE PATTERN DOTS-1348;So;0;L;;;;;N;;;;; +288E;BRAILLE PATTERN DOTS-2348;So;0;L;;;;;N;;;;; +288F;BRAILLE PATTERN DOTS-12348;So;0;L;;;;;N;;;;; +2890;BRAILLE PATTERN DOTS-58;So;0;L;;;;;N;;;;; +2891;BRAILLE PATTERN DOTS-158;So;0;L;;;;;N;;;;; +2892;BRAILLE PATTERN DOTS-258;So;0;L;;;;;N;;;;; +2893;BRAILLE PATTERN DOTS-1258;So;0;L;;;;;N;;;;; +2894;BRAILLE PATTERN DOTS-358;So;0;L;;;;;N;;;;; +2895;BRAILLE PATTERN DOTS-1358;So;0;L;;;;;N;;;;; +2896;BRAILLE PATTERN DOTS-2358;So;0;L;;;;;N;;;;; +2897;BRAILLE PATTERN DOTS-12358;So;0;L;;;;;N;;;;; +2898;BRAILLE PATTERN DOTS-458;So;0;L;;;;;N;;;;; +2899;BRAILLE PATTERN DOTS-1458;So;0;L;;;;;N;;;;; +289A;BRAILLE PATTERN DOTS-2458;So;0;L;;;;;N;;;;; +289B;BRAILLE PATTERN DOTS-12458;So;0;L;;;;;N;;;;; +289C;BRAILLE PATTERN DOTS-3458;So;0;L;;;;;N;;;;; +289D;BRAILLE PATTERN DOTS-13458;So;0;L;;;;;N;;;;; +289E;BRAILLE PATTERN DOTS-23458;So;0;L;;;;;N;;;;; +289F;BRAILLE PATTERN DOTS-123458;So;0;L;;;;;N;;;;; +28A0;BRAILLE PATTERN DOTS-68;So;0;L;;;;;N;;;;; +28A1;BRAILLE PATTERN DOTS-168;So;0;L;;;;;N;;;;; +28A2;BRAILLE PATTERN DOTS-268;So;0;L;;;;;N;;;;; +28A3;BRAILLE PATTERN DOTS-1268;So;0;L;;;;;N;;;;; +28A4;BRAILLE PATTERN DOTS-368;So;0;L;;;;;N;;;;; +28A5;BRAILLE PATTERN DOTS-1368;So;0;L;;;;;N;;;;; +28A6;BRAILLE PATTERN DOTS-2368;So;0;L;;;;;N;;;;; +28A7;BRAILLE PATTERN DOTS-12368;So;0;L;;;;;N;;;;; +28A8;BRAILLE PATTERN DOTS-468;So;0;L;;;;;N;;;;; +28A9;BRAILLE PATTERN DOTS-1468;So;0;L;;;;;N;;;;; +28AA;BRAILLE PATTERN DOTS-2468;So;0;L;;;;;N;;;;; +28AB;BRAILLE PATTERN DOTS-12468;So;0;L;;;;;N;;;;; +28AC;BRAILLE PATTERN DOTS-3468;So;0;L;;;;;N;;;;; +28AD;BRAILLE PATTERN DOTS-13468;So;0;L;;;;;N;;;;; +28AE;BRAILLE PATTERN DOTS-23468;So;0;L;;;;;N;;;;; +28AF;BRAILLE PATTERN DOTS-123468;So;0;L;;;;;N;;;;; +28B0;BRAILLE PATTERN DOTS-568;So;0;L;;;;;N;;;;; +28B1;BRAILLE PATTERN DOTS-1568;So;0;L;;;;;N;;;;; +28B2;BRAILLE PATTERN DOTS-2568;So;0;L;;;;;N;;;;; +28B3;BRAILLE PATTERN DOTS-12568;So;0;L;;;;;N;;;;; +28B4;BRAILLE PATTERN DOTS-3568;So;0;L;;;;;N;;;;; +28B5;BRAILLE PATTERN DOTS-13568;So;0;L;;;;;N;;;;; +28B6;BRAILLE PATTERN DOTS-23568;So;0;L;;;;;N;;;;; +28B7;BRAILLE PATTERN DOTS-123568;So;0;L;;;;;N;;;;; +28B8;BRAILLE PATTERN DOTS-4568;So;0;L;;;;;N;;;;; +28B9;BRAILLE PATTERN DOTS-14568;So;0;L;;;;;N;;;;; +28BA;BRAILLE PATTERN DOTS-24568;So;0;L;;;;;N;;;;; +28BB;BRAILLE PATTERN DOTS-124568;So;0;L;;;;;N;;;;; +28BC;BRAILLE PATTERN DOTS-34568;So;0;L;;;;;N;;;;; +28BD;BRAILLE PATTERN DOTS-134568;So;0;L;;;;;N;;;;; +28BE;BRAILLE PATTERN DOTS-234568;So;0;L;;;;;N;;;;; +28BF;BRAILLE PATTERN DOTS-1234568;So;0;L;;;;;N;;;;; +28C0;BRAILLE PATTERN DOTS-78;So;0;L;;;;;N;;;;; +28C1;BRAILLE PATTERN DOTS-178;So;0;L;;;;;N;;;;; +28C2;BRAILLE PATTERN DOTS-278;So;0;L;;;;;N;;;;; +28C3;BRAILLE PATTERN DOTS-1278;So;0;L;;;;;N;;;;; +28C4;BRAILLE PATTERN DOTS-378;So;0;L;;;;;N;;;;; +28C5;BRAILLE PATTERN DOTS-1378;So;0;L;;;;;N;;;;; +28C6;BRAILLE PATTERN DOTS-2378;So;0;L;;;;;N;;;;; +28C7;BRAILLE PATTERN DOTS-12378;So;0;L;;;;;N;;;;; +28C8;BRAILLE PATTERN DOTS-478;So;0;L;;;;;N;;;;; +28C9;BRAILLE PATTERN DOTS-1478;So;0;L;;;;;N;;;;; +28CA;BRAILLE PATTERN DOTS-2478;So;0;L;;;;;N;;;;; +28CB;BRAILLE PATTERN DOTS-12478;So;0;L;;;;;N;;;;; +28CC;BRAILLE PATTERN DOTS-3478;So;0;L;;;;;N;;;;; +28CD;BRAILLE PATTERN DOTS-13478;So;0;L;;;;;N;;;;; +28CE;BRAILLE PATTERN DOTS-23478;So;0;L;;;;;N;;;;; +28CF;BRAILLE PATTERN DOTS-123478;So;0;L;;;;;N;;;;; +28D0;BRAILLE PATTERN DOTS-578;So;0;L;;;;;N;;;;; +28D1;BRAILLE PATTERN DOTS-1578;So;0;L;;;;;N;;;;; +28D2;BRAILLE PATTERN DOTS-2578;So;0;L;;;;;N;;;;; +28D3;BRAILLE PATTERN DOTS-12578;So;0;L;;;;;N;;;;; +28D4;BRAILLE PATTERN DOTS-3578;So;0;L;;;;;N;;;;; +28D5;BRAILLE PATTERN DOTS-13578;So;0;L;;;;;N;;;;; +28D6;BRAILLE PATTERN DOTS-23578;So;0;L;;;;;N;;;;; +28D7;BRAILLE PATTERN DOTS-123578;So;0;L;;;;;N;;;;; +28D8;BRAILLE PATTERN DOTS-4578;So;0;L;;;;;N;;;;; +28D9;BRAILLE PATTERN DOTS-14578;So;0;L;;;;;N;;;;; +28DA;BRAILLE PATTERN DOTS-24578;So;0;L;;;;;N;;;;; +28DB;BRAILLE PATTERN DOTS-124578;So;0;L;;;;;N;;;;; +28DC;BRAILLE PATTERN DOTS-34578;So;0;L;;;;;N;;;;; +28DD;BRAILLE PATTERN DOTS-134578;So;0;L;;;;;N;;;;; +28DE;BRAILLE PATTERN DOTS-234578;So;0;L;;;;;N;;;;; +28DF;BRAILLE PATTERN DOTS-1234578;So;0;L;;;;;N;;;;; +28E0;BRAILLE PATTERN DOTS-678;So;0;L;;;;;N;;;;; +28E1;BRAILLE PATTERN DOTS-1678;So;0;L;;;;;N;;;;; +28E2;BRAILLE PATTERN DOTS-2678;So;0;L;;;;;N;;;;; +28E3;BRAILLE PATTERN DOTS-12678;So;0;L;;;;;N;;;;; +28E4;BRAILLE PATTERN DOTS-3678;So;0;L;;;;;N;;;;; +28E5;BRAILLE PATTERN DOTS-13678;So;0;L;;;;;N;;;;; +28E6;BRAILLE PATTERN DOTS-23678;So;0;L;;;;;N;;;;; +28E7;BRAILLE PATTERN DOTS-123678;So;0;L;;;;;N;;;;; +28E8;BRAILLE PATTERN DOTS-4678;So;0;L;;;;;N;;;;; +28E9;BRAILLE PATTERN DOTS-14678;So;0;L;;;;;N;;;;; +28EA;BRAILLE PATTERN DOTS-24678;So;0;L;;;;;N;;;;; +28EB;BRAILLE PATTERN DOTS-124678;So;0;L;;;;;N;;;;; +28EC;BRAILLE PATTERN DOTS-34678;So;0;L;;;;;N;;;;; +28ED;BRAILLE PATTERN DOTS-134678;So;0;L;;;;;N;;;;; +28EE;BRAILLE PATTERN DOTS-234678;So;0;L;;;;;N;;;;; +28EF;BRAILLE PATTERN DOTS-1234678;So;0;L;;;;;N;;;;; +28F0;BRAILLE PATTERN DOTS-5678;So;0;L;;;;;N;;;;; +28F1;BRAILLE PATTERN DOTS-15678;So;0;L;;;;;N;;;;; +28F2;BRAILLE PATTERN DOTS-25678;So;0;L;;;;;N;;;;; +28F3;BRAILLE PATTERN DOTS-125678;So;0;L;;;;;N;;;;; +28F4;BRAILLE PATTERN DOTS-35678;So;0;L;;;;;N;;;;; +28F5;BRAILLE PATTERN DOTS-135678;So;0;L;;;;;N;;;;; +28F6;BRAILLE PATTERN DOTS-235678;So;0;L;;;;;N;;;;; +28F7;BRAILLE PATTERN DOTS-1235678;So;0;L;;;;;N;;;;; +28F8;BRAILLE PATTERN DOTS-45678;So;0;L;;;;;N;;;;; +28F9;BRAILLE PATTERN DOTS-145678;So;0;L;;;;;N;;;;; +28FA;BRAILLE PATTERN DOTS-245678;So;0;L;;;;;N;;;;; +28FB;BRAILLE PATTERN DOTS-1245678;So;0;L;;;;;N;;;;; +28FC;BRAILLE PATTERN DOTS-345678;So;0;L;;;;;N;;;;; +28FD;BRAILLE PATTERN DOTS-1345678;So;0;L;;;;;N;;;;; +28FE;BRAILLE PATTERN DOTS-2345678;So;0;L;;;;;N;;;;; +28FF;BRAILLE PATTERN DOTS-12345678;So;0;L;;;;;N;;;;; +2900;RIGHTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2901;RIGHTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2902;LEFTWARDS DOUBLE ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2903;RIGHTWARDS DOUBLE ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2904;LEFT RIGHT DOUBLE ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2905;RIGHTWARDS TWO-HEADED ARROW FROM BAR;Sm;0;ON;;;;;N;;;;; +2906;LEFTWARDS DOUBLE ARROW FROM BAR;Sm;0;ON;;;;;N;;;;; +2907;RIGHTWARDS DOUBLE ARROW FROM BAR;Sm;0;ON;;;;;N;;;;; +2908;DOWNWARDS ARROW WITH HORIZONTAL STROKE;Sm;0;ON;;;;;N;;;;; +2909;UPWARDS ARROW WITH HORIZONTAL STROKE;Sm;0;ON;;;;;N;;;;; +290A;UPWARDS TRIPLE ARROW;Sm;0;ON;;;;;N;;;;; +290B;DOWNWARDS TRIPLE ARROW;Sm;0;ON;;;;;N;;;;; +290C;LEFTWARDS DOUBLE DASH ARROW;Sm;0;ON;;;;;N;;;;; +290D;RIGHTWARDS DOUBLE DASH ARROW;Sm;0;ON;;;;;N;;;;; +290E;LEFTWARDS TRIPLE DASH ARROW;Sm;0;ON;;;;;N;;;;; +290F;RIGHTWARDS TRIPLE DASH ARROW;Sm;0;ON;;;;;N;;;;; +2910;RIGHTWARDS TWO-HEADED TRIPLE DASH ARROW;Sm;0;ON;;;;;N;;;;; +2911;RIGHTWARDS ARROW WITH DOTTED STEM;Sm;0;ON;;;;;N;;;;; +2912;UPWARDS ARROW TO BAR;Sm;0;ON;;;;;N;;;;; +2913;DOWNWARDS ARROW TO BAR;Sm;0;ON;;;;;N;;;;; +2914;RIGHTWARDS ARROW WITH TAIL WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2915;RIGHTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2916;RIGHTWARDS TWO-HEADED ARROW WITH TAIL;Sm;0;ON;;;;;N;;;;; +2917;RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2918;RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2919;LEFTWARDS ARROW-TAIL;Sm;0;ON;;;;;N;;;;; +291A;RIGHTWARDS ARROW-TAIL;Sm;0;ON;;;;;N;;;;; +291B;LEFTWARDS DOUBLE ARROW-TAIL;Sm;0;ON;;;;;N;;;;; +291C;RIGHTWARDS DOUBLE ARROW-TAIL;Sm;0;ON;;;;;N;;;;; +291D;LEFTWARDS ARROW TO BLACK DIAMOND;Sm;0;ON;;;;;N;;;;; +291E;RIGHTWARDS ARROW TO BLACK DIAMOND;Sm;0;ON;;;;;N;;;;; +291F;LEFTWARDS ARROW FROM BAR TO BLACK DIAMOND;Sm;0;ON;;;;;N;;;;; +2920;RIGHTWARDS ARROW FROM BAR TO BLACK DIAMOND;Sm;0;ON;;;;;N;;;;; +2921;NORTH WEST AND SOUTH EAST ARROW;Sm;0;ON;;;;;N;;;;; +2922;NORTH EAST AND SOUTH WEST ARROW;Sm;0;ON;;;;;N;;;;; +2923;NORTH WEST ARROW WITH HOOK;Sm;0;ON;;;;;N;;;;; +2924;NORTH EAST ARROW WITH HOOK;Sm;0;ON;;;;;N;;;;; +2925;SOUTH EAST ARROW WITH HOOK;Sm;0;ON;;;;;N;;;;; +2926;SOUTH WEST ARROW WITH HOOK;Sm;0;ON;;;;;N;;;;; +2927;NORTH WEST ARROW AND NORTH EAST ARROW;Sm;0;ON;;;;;N;;;;; +2928;NORTH EAST ARROW AND SOUTH EAST ARROW;Sm;0;ON;;;;;N;;;;; +2929;SOUTH EAST ARROW AND SOUTH WEST ARROW;Sm;0;ON;;;;;N;;;;; +292A;SOUTH WEST ARROW AND NORTH WEST ARROW;Sm;0;ON;;;;;N;;;;; +292B;RISING DIAGONAL CROSSING FALLING DIAGONAL;Sm;0;ON;;;;;N;;;;; +292C;FALLING DIAGONAL CROSSING RISING DIAGONAL;Sm;0;ON;;;;;N;;;;; +292D;SOUTH EAST ARROW CROSSING NORTH EAST ARROW;Sm;0;ON;;;;;N;;;;; +292E;NORTH EAST ARROW CROSSING SOUTH EAST ARROW;Sm;0;ON;;;;;N;;;;; +292F;FALLING DIAGONAL CROSSING NORTH EAST ARROW;Sm;0;ON;;;;;N;;;;; +2930;RISING DIAGONAL CROSSING SOUTH EAST ARROW;Sm;0;ON;;;;;N;;;;; +2931;NORTH EAST ARROW CROSSING NORTH WEST ARROW;Sm;0;ON;;;;;N;;;;; +2932;NORTH WEST ARROW CROSSING NORTH EAST ARROW;Sm;0;ON;;;;;N;;;;; +2933;WAVE ARROW POINTING DIRECTLY RIGHT;Sm;0;ON;;;;;N;;;;; +2934;ARROW POINTING RIGHTWARDS THEN CURVING UPWARDS;Sm;0;ON;;;;;N;;;;; +2935;ARROW POINTING RIGHTWARDS THEN CURVING DOWNWARDS;Sm;0;ON;;;;;N;;;;; +2936;ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS;Sm;0;ON;;;;;N;;;;; +2937;ARROW POINTING DOWNWARDS THEN CURVING RIGHTWARDS;Sm;0;ON;;;;;N;;;;; +2938;RIGHT-SIDE ARC CLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;; +2939;LEFT-SIDE ARC ANTICLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;; +293A;TOP ARC ANTICLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;; +293B;BOTTOM ARC ANTICLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;; +293C;TOP ARC CLOCKWISE ARROW WITH MINUS;Sm;0;ON;;;;;N;;;;; +293D;TOP ARC ANTICLOCKWISE ARROW WITH PLUS;Sm;0;ON;;;;;N;;;;; +293E;LOWER RIGHT SEMICIRCULAR CLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;; +293F;LOWER LEFT SEMICIRCULAR ANTICLOCKWISE ARROW;Sm;0;ON;;;;;N;;;;; +2940;ANTICLOCKWISE CLOSED CIRCLE ARROW;Sm;0;ON;;;;;N;;;;; +2941;CLOCKWISE CLOSED CIRCLE ARROW;Sm;0;ON;;;;;N;;;;; +2942;RIGHTWARDS ARROW ABOVE SHORT LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2943;LEFTWARDS ARROW ABOVE SHORT RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2944;SHORT RIGHTWARDS ARROW ABOVE LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2945;RIGHTWARDS ARROW WITH PLUS BELOW;Sm;0;ON;;;;;N;;;;; +2946;LEFTWARDS ARROW WITH PLUS BELOW;Sm;0;ON;;;;;N;;;;; +2947;RIGHTWARDS ARROW THROUGH X;Sm;0;ON;;;;;N;;;;; +2948;LEFT RIGHT ARROW THROUGH SMALL CIRCLE;Sm;0;ON;;;;;N;;;;; +2949;UPWARDS TWO-HEADED ARROW FROM SMALL CIRCLE;Sm;0;ON;;;;;N;;;;; +294A;LEFT BARB UP RIGHT BARB DOWN HARPOON;Sm;0;ON;;;;;N;;;;; +294B;LEFT BARB DOWN RIGHT BARB UP HARPOON;Sm;0;ON;;;;;N;;;;; +294C;UP BARB RIGHT DOWN BARB LEFT HARPOON;Sm;0;ON;;;;;N;;;;; +294D;UP BARB LEFT DOWN BARB RIGHT HARPOON;Sm;0;ON;;;;;N;;;;; +294E;LEFT BARB UP RIGHT BARB UP HARPOON;Sm;0;ON;;;;;N;;;;; +294F;UP BARB RIGHT DOWN BARB RIGHT HARPOON;Sm;0;ON;;;;;N;;;;; +2950;LEFT BARB DOWN RIGHT BARB DOWN HARPOON;Sm;0;ON;;;;;N;;;;; +2951;UP BARB LEFT DOWN BARB LEFT HARPOON;Sm;0;ON;;;;;N;;;;; +2952;LEFTWARDS HARPOON WITH BARB UP TO BAR;Sm;0;ON;;;;;N;;;;; +2953;RIGHTWARDS HARPOON WITH BARB UP TO BAR;Sm;0;ON;;;;;N;;;;; +2954;UPWARDS HARPOON WITH BARB RIGHT TO BAR;Sm;0;ON;;;;;N;;;;; +2955;DOWNWARDS HARPOON WITH BARB RIGHT TO BAR;Sm;0;ON;;;;;N;;;;; +2956;LEFTWARDS HARPOON WITH BARB DOWN TO BAR;Sm;0;ON;;;;;N;;;;; +2957;RIGHTWARDS HARPOON WITH BARB DOWN TO BAR;Sm;0;ON;;;;;N;;;;; +2958;UPWARDS HARPOON WITH BARB LEFT TO BAR;Sm;0;ON;;;;;N;;;;; +2959;DOWNWARDS HARPOON WITH BARB LEFT TO BAR;Sm;0;ON;;;;;N;;;;; +295A;LEFTWARDS HARPOON WITH BARB UP FROM BAR;Sm;0;ON;;;;;N;;;;; +295B;RIGHTWARDS HARPOON WITH BARB UP FROM BAR;Sm;0;ON;;;;;N;;;;; +295C;UPWARDS HARPOON WITH BARB RIGHT FROM BAR;Sm;0;ON;;;;;N;;;;; +295D;DOWNWARDS HARPOON WITH BARB RIGHT FROM BAR;Sm;0;ON;;;;;N;;;;; +295E;LEFTWARDS HARPOON WITH BARB DOWN FROM BAR;Sm;0;ON;;;;;N;;;;; +295F;RIGHTWARDS HARPOON WITH BARB DOWN FROM BAR;Sm;0;ON;;;;;N;;;;; +2960;UPWARDS HARPOON WITH BARB LEFT FROM BAR;Sm;0;ON;;;;;N;;;;; +2961;DOWNWARDS HARPOON WITH BARB LEFT FROM BAR;Sm;0;ON;;;;;N;;;;; +2962;LEFTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB DOWN;Sm;0;ON;;;;;N;;;;; +2963;UPWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT;Sm;0;ON;;;;;N;;;;; +2964;RIGHTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB DOWN;Sm;0;ON;;;;;N;;;;; +2965;DOWNWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT;Sm;0;ON;;;;;N;;;;; +2966;LEFTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB UP;Sm;0;ON;;;;;N;;;;; +2967;LEFTWARDS HARPOON WITH BARB DOWN ABOVE RIGHTWARDS HARPOON WITH BARB DOWN;Sm;0;ON;;;;;N;;;;; +2968;RIGHTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB UP;Sm;0;ON;;;;;N;;;;; +2969;RIGHTWARDS HARPOON WITH BARB DOWN ABOVE LEFTWARDS HARPOON WITH BARB DOWN;Sm;0;ON;;;;;N;;;;; +296A;LEFTWARDS HARPOON WITH BARB UP ABOVE LONG DASH;Sm;0;ON;;;;;N;;;;; +296B;LEFTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH;Sm;0;ON;;;;;N;;;;; +296C;RIGHTWARDS HARPOON WITH BARB UP ABOVE LONG DASH;Sm;0;ON;;;;;N;;;;; +296D;RIGHTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH;Sm;0;ON;;;;;N;;;;; +296E;UPWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT;Sm;0;ON;;;;;N;;;;; +296F;DOWNWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT;Sm;0;ON;;;;;N;;;;; +2970;RIGHT DOUBLE ARROW WITH ROUNDED HEAD;Sm;0;ON;;;;;N;;;;; +2971;EQUALS SIGN ABOVE RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2972;TILDE OPERATOR ABOVE RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2973;LEFTWARDS ARROW ABOVE TILDE OPERATOR;Sm;0;ON;;;;;N;;;;; +2974;RIGHTWARDS ARROW ABOVE TILDE OPERATOR;Sm;0;ON;;;;;N;;;;; +2975;RIGHTWARDS ARROW ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;N;;;;; +2976;LESS-THAN ABOVE LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2977;LEFTWARDS ARROW THROUGH LESS-THAN;Sm;0;ON;;;;;N;;;;; +2978;GREATER-THAN ABOVE RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2979;SUBSET ABOVE RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +297A;LEFTWARDS ARROW THROUGH SUBSET;Sm;0;ON;;;;;N;;;;; +297B;SUPERSET ABOVE LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +297C;LEFT FISH TAIL;Sm;0;ON;;;;;N;;;;; +297D;RIGHT FISH TAIL;Sm;0;ON;;;;;N;;;;; +297E;UP FISH TAIL;Sm;0;ON;;;;;N;;;;; +297F;DOWN FISH TAIL;Sm;0;ON;;;;;N;;;;; +2980;TRIPLE VERTICAL BAR DELIMITER;Sm;0;ON;;;;;N;;;;; +2981;Z NOTATION SPOT;Sm;0;ON;;;;;N;;;;; +2982;Z NOTATION TYPE COLON;Sm;0;ON;;;;;N;;;;; +2983;LEFT WHITE CURLY BRACKET;Ps;0;ON;;;;;Y;;;;; +2984;RIGHT WHITE CURLY BRACKET;Pe;0;ON;;;;;Y;;;;; +2985;LEFT WHITE PARENTHESIS;Ps;0;ON;;;;;Y;;;;; +2986;RIGHT WHITE PARENTHESIS;Pe;0;ON;;;;;Y;;;;; +2987;Z NOTATION LEFT IMAGE BRACKET;Ps;0;ON;;;;;Y;;;;; +2988;Z NOTATION RIGHT IMAGE BRACKET;Pe;0;ON;;;;;Y;;;;; +2989;Z NOTATION LEFT BINDING BRACKET;Ps;0;ON;;;;;Y;;;;; +298A;Z NOTATION RIGHT BINDING BRACKET;Pe;0;ON;;;;;Y;;;;; +298B;LEFT SQUARE BRACKET WITH UNDERBAR;Ps;0;ON;;;;;Y;;;;; +298C;RIGHT SQUARE BRACKET WITH UNDERBAR;Pe;0;ON;;;;;Y;;;;; +298D;LEFT SQUARE BRACKET WITH TICK IN TOP CORNER;Ps;0;ON;;;;;Y;;;;; +298E;RIGHT SQUARE BRACKET WITH TICK IN BOTTOM CORNER;Pe;0;ON;;;;;Y;;;;; +298F;LEFT SQUARE BRACKET WITH TICK IN BOTTOM CORNER;Ps;0;ON;;;;;Y;;;;; +2990;RIGHT SQUARE BRACKET WITH TICK IN TOP CORNER;Pe;0;ON;;;;;Y;;;;; +2991;LEFT ANGLE BRACKET WITH DOT;Ps;0;ON;;;;;Y;;;;; +2992;RIGHT ANGLE BRACKET WITH DOT;Pe;0;ON;;;;;Y;;;;; +2993;LEFT ARC LESS-THAN BRACKET;Ps;0;ON;;;;;Y;;;;; +2994;RIGHT ARC GREATER-THAN BRACKET;Pe;0;ON;;;;;Y;;;;; +2995;DOUBLE LEFT ARC GREATER-THAN BRACKET;Ps;0;ON;;;;;Y;;;;; +2996;DOUBLE RIGHT ARC LESS-THAN BRACKET;Pe;0;ON;;;;;Y;;;;; +2997;LEFT BLACK TORTOISE SHELL BRACKET;Ps;0;ON;;;;;Y;;;;; +2998;RIGHT BLACK TORTOISE SHELL BRACKET;Pe;0;ON;;;;;Y;;;;; +2999;DOTTED FENCE;Sm;0;ON;;;;;N;;;;; +299A;VERTICAL ZIGZAG LINE;Sm;0;ON;;;;;N;;;;; +299B;MEASURED ANGLE OPENING LEFT;Sm;0;ON;;;;;Y;;;;; +299C;RIGHT ANGLE VARIANT WITH SQUARE;Sm;0;ON;;;;;Y;;;;; +299D;MEASURED RIGHT ANGLE WITH DOT;Sm;0;ON;;;;;Y;;;;; +299E;ANGLE WITH S INSIDE;Sm;0;ON;;;;;Y;;;;; +299F;ACUTE ANGLE;Sm;0;ON;;;;;Y;;;;; +29A0;SPHERICAL ANGLE OPENING LEFT;Sm;0;ON;;;;;Y;;;;; +29A1;SPHERICAL ANGLE OPENING UP;Sm;0;ON;;;;;Y;;;;; +29A2;TURNED ANGLE;Sm;0;ON;;;;;Y;;;;; +29A3;REVERSED ANGLE;Sm;0;ON;;;;;Y;;;;; +29A4;ANGLE WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;; +29A5;REVERSED ANGLE WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;; +29A6;OBLIQUE ANGLE OPENING UP;Sm;0;ON;;;;;Y;;;;; +29A7;OBLIQUE ANGLE OPENING DOWN;Sm;0;ON;;;;;Y;;;;; +29A8;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND RIGHT;Sm;0;ON;;;;;Y;;;;; +29A9;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND LEFT;Sm;0;ON;;;;;Y;;;;; +29AA;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND RIGHT;Sm;0;ON;;;;;Y;;;;; +29AB;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND LEFT;Sm;0;ON;;;;;Y;;;;; +29AC;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND UP;Sm;0;ON;;;;;Y;;;;; +29AD;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND UP;Sm;0;ON;;;;;Y;;;;; +29AE;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND DOWN;Sm;0;ON;;;;;Y;;;;; +29AF;MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND DOWN;Sm;0;ON;;;;;Y;;;;; +29B0;REVERSED EMPTY SET;Sm;0;ON;;;;;N;;;;; +29B1;EMPTY SET WITH OVERBAR;Sm;0;ON;;;;;N;;;;; +29B2;EMPTY SET WITH SMALL CIRCLE ABOVE;Sm;0;ON;;;;;N;;;;; +29B3;EMPTY SET WITH RIGHT ARROW ABOVE;Sm;0;ON;;;;;N;;;;; +29B4;EMPTY SET WITH LEFT ARROW ABOVE;Sm;0;ON;;;;;N;;;;; +29B5;CIRCLE WITH HORIZONTAL BAR;Sm;0;ON;;;;;N;;;;; +29B6;CIRCLED VERTICAL BAR;Sm;0;ON;;;;;N;;;;; +29B7;CIRCLED PARALLEL;Sm;0;ON;;;;;N;;;;; +29B8;CIRCLED REVERSE SOLIDUS;Sm;0;ON;;;;;Y;;;;; +29B9;CIRCLED PERPENDICULAR;Sm;0;ON;;;;;N;;;;; +29BA;CIRCLE DIVIDED BY HORIZONTAL BAR AND TOP HALF DIVIDED BY VERTICAL BAR;Sm;0;ON;;;;;N;;;;; +29BB;CIRCLE WITH SUPERIMPOSED X;Sm;0;ON;;;;;N;;;;; +29BC;CIRCLED ANTICLOCKWISE-ROTATED DIVISION SIGN;Sm;0;ON;;;;;N;;;;; +29BD;UP ARROW THROUGH CIRCLE;Sm;0;ON;;;;;N;;;;; +29BE;CIRCLED WHITE BULLET;Sm;0;ON;;;;;N;;;;; +29BF;CIRCLED BULLET;Sm;0;ON;;;;;N;;;;; +29C0;CIRCLED LESS-THAN;Sm;0;ON;;;;;Y;;;;; +29C1;CIRCLED GREATER-THAN;Sm;0;ON;;;;;Y;;;;; +29C2;CIRCLE WITH SMALL CIRCLE TO THE RIGHT;Sm;0;ON;;;;;Y;;;;; +29C3;CIRCLE WITH TWO HORIZONTAL STROKES TO THE RIGHT;Sm;0;ON;;;;;Y;;;;; +29C4;SQUARED RISING DIAGONAL SLASH;Sm;0;ON;;;;;Y;;;;; +29C5;SQUARED FALLING DIAGONAL SLASH;Sm;0;ON;;;;;Y;;;;; +29C6;SQUARED ASTERISK;Sm;0;ON;;;;;N;;;;; +29C7;SQUARED SMALL CIRCLE;Sm;0;ON;;;;;N;;;;; +29C8;SQUARED SQUARE;Sm;0;ON;;;;;N;;;;; +29C9;TWO JOINED SQUARES;Sm;0;ON;;;;;Y;;;;; +29CA;TRIANGLE WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;; +29CB;TRIANGLE WITH UNDERBAR;Sm;0;ON;;;;;N;;;;; +29CC;S IN TRIANGLE;Sm;0;ON;;;;;N;;;;; +29CD;TRIANGLE WITH SERIFS AT BOTTOM;Sm;0;ON;;;;;N;;;;; +29CE;RIGHT TRIANGLE ABOVE LEFT TRIANGLE;Sm;0;ON;;;;;Y;;;;; +29CF;LEFT TRIANGLE BESIDE VERTICAL BAR;Sm;0;ON;;;;;Y;;;;; +29D0;VERTICAL BAR BESIDE RIGHT TRIANGLE;Sm;0;ON;;;;;Y;;;;; +29D1;BOWTIE WITH LEFT HALF BLACK;Sm;0;ON;;;;;Y;;;;; +29D2;BOWTIE WITH RIGHT HALF BLACK;Sm;0;ON;;;;;Y;;;;; +29D3;BLACK BOWTIE;Sm;0;ON;;;;;N;;;;; +29D4;TIMES WITH LEFT HALF BLACK;Sm;0;ON;;;;;Y;;;;; +29D5;TIMES WITH RIGHT HALF BLACK;Sm;0;ON;;;;;Y;;;;; +29D6;WHITE HOURGLASS;Sm;0;ON;;;;;N;;;;; +29D7;BLACK HOURGLASS;Sm;0;ON;;;;;N;;;;; +29D8;LEFT WIGGLY FENCE;Ps;0;ON;;;;;Y;;;;; +29D9;RIGHT WIGGLY FENCE;Pe;0;ON;;;;;Y;;;;; +29DA;LEFT DOUBLE WIGGLY FENCE;Ps;0;ON;;;;;Y;;;;; +29DB;RIGHT DOUBLE WIGGLY FENCE;Pe;0;ON;;;;;Y;;;;; +29DC;INCOMPLETE INFINITY;Sm;0;ON;;;;;Y;;;;; +29DD;TIE OVER INFINITY;Sm;0;ON;;;;;N;;;;; +29DE;INFINITY NEGATED WITH VERTICAL BAR;Sm;0;ON;;;;;N;;;;; +29DF;DOUBLE-ENDED MULTIMAP;Sm;0;ON;;;;;N;;;;; +29E0;SQUARE WITH CONTOURED OUTLINE;Sm;0;ON;;;;;N;;;;; +29E1;INCREASES AS;Sm;0;ON;;;;;Y;;;;; +29E2;SHUFFLE PRODUCT;Sm;0;ON;;;;;N;;;;; +29E3;EQUALS SIGN AND SLANTED PARALLEL;Sm;0;ON;;;;;Y;;;;; +29E4;EQUALS SIGN AND SLANTED PARALLEL WITH TILDE ABOVE;Sm;0;ON;;;;;Y;;;;; +29E5;IDENTICAL TO AND SLANTED PARALLEL;Sm;0;ON;;;;;Y;;;;; +29E6;GLEICH STARK;Sm;0;ON;;;;;N;;;;; +29E7;THERMODYNAMIC;Sm;0;ON;;;;;N;;;;; +29E8;DOWN-POINTING TRIANGLE WITH LEFT HALF BLACK;Sm;0;ON;;;;;Y;;;;; +29E9;DOWN-POINTING TRIANGLE WITH RIGHT HALF BLACK;Sm;0;ON;;;;;Y;;;;; +29EA;BLACK DIAMOND WITH DOWN ARROW;Sm;0;ON;;;;;N;;;;; +29EB;BLACK LOZENGE;Sm;0;ON;;;;;N;;;;; +29EC;WHITE CIRCLE WITH DOWN ARROW;Sm;0;ON;;;;;N;;;;; +29ED;BLACK CIRCLE WITH DOWN ARROW;Sm;0;ON;;;;;N;;;;; +29EE;ERROR-BARRED WHITE SQUARE;Sm;0;ON;;;;;N;;;;; +29EF;ERROR-BARRED BLACK SQUARE;Sm;0;ON;;;;;N;;;;; +29F0;ERROR-BARRED WHITE DIAMOND;Sm;0;ON;;;;;N;;;;; +29F1;ERROR-BARRED BLACK DIAMOND;Sm;0;ON;;;;;N;;;;; +29F2;ERROR-BARRED WHITE CIRCLE;Sm;0;ON;;;;;N;;;;; +29F3;ERROR-BARRED BLACK CIRCLE;Sm;0;ON;;;;;N;;;;; +29F4;RULE-DELAYED;Sm;0;ON;;;;;Y;;;;; +29F5;REVERSE SOLIDUS OPERATOR;Sm;0;ON;;;;;Y;;;;; +29F6;SOLIDUS WITH OVERBAR;Sm;0;ON;;;;;Y;;;;; +29F7;REVERSE SOLIDUS WITH HORIZONTAL STROKE;Sm;0;ON;;;;;Y;;;;; +29F8;BIG SOLIDUS;Sm;0;ON;;;;;Y;;;;; +29F9;BIG REVERSE SOLIDUS;Sm;0;ON;;;;;Y;;;;; +29FA;DOUBLE PLUS;Sm;0;ON;;;;;N;;;;; +29FB;TRIPLE PLUS;Sm;0;ON;;;;;N;;;;; +29FC;LEFT-POINTING CURVED ANGLE BRACKET;Ps;0;ON;;;;;Y;;;;; +29FD;RIGHT-POINTING CURVED ANGLE BRACKET;Pe;0;ON;;;;;Y;;;;; +29FE;TINY;Sm;0;ON;;;;;N;;;;; +29FF;MINY;Sm;0;ON;;;;;N;;;;; +2A00;N-ARY CIRCLED DOT OPERATOR;Sm;0;ON;;;;;N;;;;; +2A01;N-ARY CIRCLED PLUS OPERATOR;Sm;0;ON;;;;;N;;;;; +2A02;N-ARY CIRCLED TIMES OPERATOR;Sm;0;ON;;;;;N;;;;; +2A03;N-ARY UNION OPERATOR WITH DOT;Sm;0;ON;;;;;N;;;;; +2A04;N-ARY UNION OPERATOR WITH PLUS;Sm;0;ON;;;;;N;;;;; +2A05;N-ARY SQUARE INTERSECTION OPERATOR;Sm;0;ON;;;;;N;;;;; +2A06;N-ARY SQUARE UNION OPERATOR;Sm;0;ON;;;;;N;;;;; +2A07;TWO LOGICAL AND OPERATOR;Sm;0;ON;;;;;N;;;;; +2A08;TWO LOGICAL OR OPERATOR;Sm;0;ON;;;;;N;;;;; +2A09;N-ARY TIMES OPERATOR;Sm;0;ON;;;;;N;;;;; +2A0A;MODULO TWO SUM;Sm;0;ON;;;;;Y;;;;; +2A0B;SUMMATION WITH INTEGRAL;Sm;0;ON;;;;;Y;;;;; +2A0C;QUADRUPLE INTEGRAL OPERATOR;Sm;0;ON; 222B 222B 222B 222B;;;;Y;;;;; +2A0D;FINITE PART INTEGRAL;Sm;0;ON;;;;;Y;;;;; +2A0E;INTEGRAL WITH DOUBLE STROKE;Sm;0;ON;;;;;Y;;;;; +2A0F;INTEGRAL AVERAGE WITH SLASH;Sm;0;ON;;;;;Y;;;;; +2A10;CIRCULATION FUNCTION;Sm;0;ON;;;;;Y;;;;; +2A11;ANTICLOCKWISE INTEGRATION;Sm;0;ON;;;;;Y;;;;; +2A12;LINE INTEGRATION WITH RECTANGULAR PATH AROUND POLE;Sm;0;ON;;;;;Y;;;;; +2A13;LINE INTEGRATION WITH SEMICIRCULAR PATH AROUND POLE;Sm;0;ON;;;;;Y;;;;; +2A14;LINE INTEGRATION NOT INCLUDING THE POLE;Sm;0;ON;;;;;Y;;;;; +2A15;INTEGRAL AROUND A POINT OPERATOR;Sm;0;ON;;;;;Y;;;;; +2A16;QUATERNION INTEGRAL OPERATOR;Sm;0;ON;;;;;Y;;;;; +2A17;INTEGRAL WITH LEFTWARDS ARROW WITH HOOK;Sm;0;ON;;;;;Y;;;;; +2A18;INTEGRAL WITH TIMES SIGN;Sm;0;ON;;;;;Y;;;;; +2A19;INTEGRAL WITH INTERSECTION;Sm;0;ON;;;;;Y;;;;; +2A1A;INTEGRAL WITH UNION;Sm;0;ON;;;;;Y;;;;; +2A1B;INTEGRAL WITH OVERBAR;Sm;0;ON;;;;;Y;;;;; +2A1C;INTEGRAL WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;; +2A1D;JOIN;Sm;0;ON;;;;;N;;;;; +2A1E;LARGE LEFT TRIANGLE OPERATOR;Sm;0;ON;;;;;Y;;;;; +2A1F;Z NOTATION SCHEMA COMPOSITION;Sm;0;ON;;;;;Y;;;;; +2A20;Z NOTATION SCHEMA PIPING;Sm;0;ON;;;;;Y;;;;; +2A21;Z NOTATION SCHEMA PROJECTION;Sm;0;ON;;;;;Y;;;;; +2A22;PLUS SIGN WITH SMALL CIRCLE ABOVE;Sm;0;ON;;;;;N;;;;; +2A23;PLUS SIGN WITH CIRCUMFLEX ACCENT ABOVE;Sm;0;ON;;;;;N;;;;; +2A24;PLUS SIGN WITH TILDE ABOVE;Sm;0;ON;;;;;Y;;;;; +2A25;PLUS SIGN WITH DOT BELOW;Sm;0;ON;;;;;N;;;;; +2A26;PLUS SIGN WITH TILDE BELOW;Sm;0;ON;;;;;Y;;;;; +2A27;PLUS SIGN WITH SUBSCRIPT TWO;Sm;0;ON;;;;;N;;;;; +2A28;PLUS SIGN WITH BLACK TRIANGLE;Sm;0;ON;;;;;N;;;;; +2A29;MINUS SIGN WITH COMMA ABOVE;Sm;0;ON;;;;;Y;;;;; +2A2A;MINUS SIGN WITH DOT BELOW;Sm;0;ON;;;;;N;;;;; +2A2B;MINUS SIGN WITH FALLING DOTS;Sm;0;ON;;;;;Y;;;;; +2A2C;MINUS SIGN WITH RISING DOTS;Sm;0;ON;;;;;Y;;;;; +2A2D;PLUS SIGN IN LEFT HALF CIRCLE;Sm;0;ON;;;;;Y;;;;; +2A2E;PLUS SIGN IN RIGHT HALF CIRCLE;Sm;0;ON;;;;;Y;;;;; +2A2F;VECTOR OR CROSS PRODUCT;Sm;0;ON;;;;;N;;;;; +2A30;MULTIPLICATION SIGN WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;; +2A31;MULTIPLICATION SIGN WITH UNDERBAR;Sm;0;ON;;;;;N;;;;; +2A32;SEMIDIRECT PRODUCT WITH BOTTOM CLOSED;Sm;0;ON;;;;;N;;;;; +2A33;SMASH PRODUCT;Sm;0;ON;;;;;N;;;;; +2A34;MULTIPLICATION SIGN IN LEFT HALF CIRCLE;Sm;0;ON;;;;;Y;;;;; +2A35;MULTIPLICATION SIGN IN RIGHT HALF CIRCLE;Sm;0;ON;;;;;Y;;;;; +2A36;CIRCLED MULTIPLICATION SIGN WITH CIRCUMFLEX ACCENT;Sm;0;ON;;;;;N;;;;; +2A37;MULTIPLICATION SIGN IN DOUBLE CIRCLE;Sm;0;ON;;;;;N;;;;; +2A38;CIRCLED DIVISION SIGN;Sm;0;ON;;;;;N;;;;; +2A39;PLUS SIGN IN TRIANGLE;Sm;0;ON;;;;;N;;;;; +2A3A;MINUS SIGN IN TRIANGLE;Sm;0;ON;;;;;N;;;;; +2A3B;MULTIPLICATION SIGN IN TRIANGLE;Sm;0;ON;;;;;N;;;;; +2A3C;INTERIOR PRODUCT;Sm;0;ON;;;;;Y;;;;; +2A3D;RIGHTHAND INTERIOR PRODUCT;Sm;0;ON;;;;;Y;;;;; +2A3E;Z NOTATION RELATIONAL COMPOSITION;Sm;0;ON;;;;;Y;;;;; +2A3F;AMALGAMATION OR COPRODUCT;Sm;0;ON;;;;;N;;;;; +2A40;INTERSECTION WITH DOT;Sm;0;ON;;;;;N;;;;; +2A41;UNION WITH MINUS SIGN;Sm;0;ON;;;;;N;;;;; +2A42;UNION WITH OVERBAR;Sm;0;ON;;;;;N;;;;; +2A43;INTERSECTION WITH OVERBAR;Sm;0;ON;;;;;N;;;;; +2A44;INTERSECTION WITH LOGICAL AND;Sm;0;ON;;;;;N;;;;; +2A45;UNION WITH LOGICAL OR;Sm;0;ON;;;;;N;;;;; +2A46;UNION ABOVE INTERSECTION;Sm;0;ON;;;;;N;;;;; +2A47;INTERSECTION ABOVE UNION;Sm;0;ON;;;;;N;;;;; +2A48;UNION ABOVE BAR ABOVE INTERSECTION;Sm;0;ON;;;;;N;;;;; +2A49;INTERSECTION ABOVE BAR ABOVE UNION;Sm;0;ON;;;;;N;;;;; +2A4A;UNION BESIDE AND JOINED WITH UNION;Sm;0;ON;;;;;N;;;;; +2A4B;INTERSECTION BESIDE AND JOINED WITH INTERSECTION;Sm;0;ON;;;;;N;;;;; +2A4C;CLOSED UNION WITH SERIFS;Sm;0;ON;;;;;N;;;;; +2A4D;CLOSED INTERSECTION WITH SERIFS;Sm;0;ON;;;;;N;;;;; +2A4E;DOUBLE SQUARE INTERSECTION;Sm;0;ON;;;;;N;;;;; +2A4F;DOUBLE SQUARE UNION;Sm;0;ON;;;;;N;;;;; +2A50;CLOSED UNION WITH SERIFS AND SMASH PRODUCT;Sm;0;ON;;;;;N;;;;; +2A51;LOGICAL AND WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;; +2A52;LOGICAL OR WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;; +2A53;DOUBLE LOGICAL AND;Sm;0;ON;;;;;N;;;;; +2A54;DOUBLE LOGICAL OR;Sm;0;ON;;;;;N;;;;; +2A55;TWO INTERSECTING LOGICAL AND;Sm;0;ON;;;;;N;;;;; +2A56;TWO INTERSECTING LOGICAL OR;Sm;0;ON;;;;;N;;;;; +2A57;SLOPING LARGE OR;Sm;0;ON;;;;;Y;;;;; +2A58;SLOPING LARGE AND;Sm;0;ON;;;;;Y;;;;; +2A59;LOGICAL OR OVERLAPPING LOGICAL AND;Sm;0;ON;;;;;N;;;;; +2A5A;LOGICAL AND WITH MIDDLE STEM;Sm;0;ON;;;;;N;;;;; +2A5B;LOGICAL OR WITH MIDDLE STEM;Sm;0;ON;;;;;N;;;;; +2A5C;LOGICAL AND WITH HORIZONTAL DASH;Sm;0;ON;;;;;N;;;;; +2A5D;LOGICAL OR WITH HORIZONTAL DASH;Sm;0;ON;;;;;N;;;;; +2A5E;LOGICAL AND WITH DOUBLE OVERBAR;Sm;0;ON;;;;;N;;;;; +2A5F;LOGICAL AND WITH UNDERBAR;Sm;0;ON;;;;;N;;;;; +2A60;LOGICAL AND WITH DOUBLE UNDERBAR;Sm;0;ON;;;;;N;;;;; +2A61;SMALL VEE WITH UNDERBAR;Sm;0;ON;;;;;N;;;;; +2A62;LOGICAL OR WITH DOUBLE OVERBAR;Sm;0;ON;;;;;N;;;;; +2A63;LOGICAL OR WITH DOUBLE UNDERBAR;Sm;0;ON;;;;;N;;;;; +2A64;Z NOTATION DOMAIN ANTIRESTRICTION;Sm;0;ON;;;;;Y;;;;; +2A65;Z NOTATION RANGE ANTIRESTRICTION;Sm;0;ON;;;;;Y;;;;; +2A66;EQUALS SIGN WITH DOT BELOW;Sm;0;ON;;;;;N;;;;; +2A67;IDENTICAL WITH DOT ABOVE;Sm;0;ON;;;;;N;;;;; +2A68;TRIPLE HORIZONTAL BAR WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2A69;TRIPLE HORIZONTAL BAR WITH TRIPLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2A6A;TILDE OPERATOR WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;; +2A6B;TILDE OPERATOR WITH RISING DOTS;Sm;0;ON;;;;;Y;;;;; +2A6C;SIMILAR MINUS SIMILAR;Sm;0;ON;;;;;Y;;;;; +2A6D;CONGRUENT WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;; +2A6E;EQUALS WITH ASTERISK;Sm;0;ON;;;;;N;;;;; +2A6F;ALMOST EQUAL TO WITH CIRCUMFLEX ACCENT;Sm;0;ON;;;;;Y;;;;; +2A70;APPROXIMATELY EQUAL OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2A71;EQUALS SIGN ABOVE PLUS SIGN;Sm;0;ON;;;;;N;;;;; +2A72;PLUS SIGN ABOVE EQUALS SIGN;Sm;0;ON;;;;;N;;;;; +2A73;EQUALS SIGN ABOVE TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;; +2A74;DOUBLE COLON EQUAL;Sm;0;ON; 003A 003A 003D;;;;Y;;;;; +2A75;TWO CONSECUTIVE EQUALS SIGNS;Sm;0;ON; 003D 003D;;;;N;;;;; +2A76;THREE CONSECUTIVE EQUALS SIGNS;Sm;0;ON; 003D 003D 003D;;;;N;;;;; +2A77;EQUALS SIGN WITH TWO DOTS ABOVE AND TWO DOTS BELOW;Sm;0;ON;;;;;N;;;;; +2A78;EQUIVALENT WITH FOUR DOTS ABOVE;Sm;0;ON;;;;;N;;;;; +2A79;LESS-THAN WITH CIRCLE INSIDE;Sm;0;ON;;;;;Y;;;;; +2A7A;GREATER-THAN WITH CIRCLE INSIDE;Sm;0;ON;;;;;Y;;;;; +2A7B;LESS-THAN WITH QUESTION MARK ABOVE;Sm;0;ON;;;;;Y;;;;; +2A7C;GREATER-THAN WITH QUESTION MARK ABOVE;Sm;0;ON;;;;;Y;;;;; +2A7D;LESS-THAN OR SLANTED EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2A7E;GREATER-THAN OR SLANTED EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2A7F;LESS-THAN OR SLANTED EQUAL TO WITH DOT INSIDE;Sm;0;ON;;;;;Y;;;;; +2A80;GREATER-THAN OR SLANTED EQUAL TO WITH DOT INSIDE;Sm;0;ON;;;;;Y;;;;; +2A81;LESS-THAN OR SLANTED EQUAL TO WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;; +2A82;GREATER-THAN OR SLANTED EQUAL TO WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;; +2A83;LESS-THAN OR SLANTED EQUAL TO WITH DOT ABOVE RIGHT;Sm;0;ON;;;;;Y;;;;; +2A84;GREATER-THAN OR SLANTED EQUAL TO WITH DOT ABOVE LEFT;Sm;0;ON;;;;;Y;;;;; +2A85;LESS-THAN OR APPROXIMATE;Sm;0;ON;;;;;Y;;;;; +2A86;GREATER-THAN OR APPROXIMATE;Sm;0;ON;;;;;Y;;;;; +2A87;LESS-THAN AND SINGLE-LINE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2A88;GREATER-THAN AND SINGLE-LINE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2A89;LESS-THAN AND NOT APPROXIMATE;Sm;0;ON;;;;;Y;;;;; +2A8A;GREATER-THAN AND NOT APPROXIMATE;Sm;0;ON;;;;;Y;;;;; +2A8B;LESS-THAN ABOVE DOUBLE-LINE EQUAL ABOVE GREATER-THAN;Sm;0;ON;;;;;Y;;;;; +2A8C;GREATER-THAN ABOVE DOUBLE-LINE EQUAL ABOVE LESS-THAN;Sm;0;ON;;;;;Y;;;;; +2A8D;LESS-THAN ABOVE SIMILAR OR EQUAL;Sm;0;ON;;;;;Y;;;;; +2A8E;GREATER-THAN ABOVE SIMILAR OR EQUAL;Sm;0;ON;;;;;Y;;;;; +2A8F;LESS-THAN ABOVE SIMILAR ABOVE GREATER-THAN;Sm;0;ON;;;;;Y;;;;; +2A90;GREATER-THAN ABOVE SIMILAR ABOVE LESS-THAN;Sm;0;ON;;;;;Y;;;;; +2A91;LESS-THAN ABOVE GREATER-THAN ABOVE DOUBLE-LINE EQUAL;Sm;0;ON;;;;;Y;;;;; +2A92;GREATER-THAN ABOVE LESS-THAN ABOVE DOUBLE-LINE EQUAL;Sm;0;ON;;;;;Y;;;;; +2A93;LESS-THAN ABOVE SLANTED EQUAL ABOVE GREATER-THAN ABOVE SLANTED EQUAL;Sm;0;ON;;;;;Y;;;;; +2A94;GREATER-THAN ABOVE SLANTED EQUAL ABOVE LESS-THAN ABOVE SLANTED EQUAL;Sm;0;ON;;;;;Y;;;;; +2A95;SLANTED EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;;;;; +2A96;SLANTED EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;;;;; +2A97;SLANTED EQUAL TO OR LESS-THAN WITH DOT INSIDE;Sm;0;ON;;;;;Y;;;;; +2A98;SLANTED EQUAL TO OR GREATER-THAN WITH DOT INSIDE;Sm;0;ON;;;;;Y;;;;; +2A99;DOUBLE-LINE EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;;;;; +2A9A;DOUBLE-LINE EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;;;;; +2A9B;DOUBLE-LINE SLANTED EQUAL TO OR LESS-THAN;Sm;0;ON;;;;;Y;;;;; +2A9C;DOUBLE-LINE SLANTED EQUAL TO OR GREATER-THAN;Sm;0;ON;;;;;Y;;;;; +2A9D;SIMILAR OR LESS-THAN;Sm;0;ON;;;;;Y;;;;; +2A9E;SIMILAR OR GREATER-THAN;Sm;0;ON;;;;;Y;;;;; +2A9F;SIMILAR ABOVE LESS-THAN ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;; +2AA0;SIMILAR ABOVE GREATER-THAN ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;; +2AA1;DOUBLE NESTED LESS-THAN;Sm;0;ON;;;;;Y;;;;; +2AA2;DOUBLE NESTED GREATER-THAN;Sm;0;ON;;;;;Y;;;;; +2AA3;DOUBLE NESTED LESS-THAN WITH UNDERBAR;Sm;0;ON;;;;;Y;;;;; +2AA4;GREATER-THAN OVERLAPPING LESS-THAN;Sm;0;ON;;;;;N;;;;; +2AA5;GREATER-THAN BESIDE LESS-THAN;Sm;0;ON;;;;;N;;;;; +2AA6;LESS-THAN CLOSED BY CURVE;Sm;0;ON;;;;;Y;;;;; +2AA7;GREATER-THAN CLOSED BY CURVE;Sm;0;ON;;;;;Y;;;;; +2AA8;LESS-THAN CLOSED BY CURVE ABOVE SLANTED EQUAL;Sm;0;ON;;;;;Y;;;;; +2AA9;GREATER-THAN CLOSED BY CURVE ABOVE SLANTED EQUAL;Sm;0;ON;;;;;Y;;;;; +2AAA;SMALLER THAN;Sm;0;ON;;;;;Y;;;;; +2AAB;LARGER THAN;Sm;0;ON;;;;;Y;;;;; +2AAC;SMALLER THAN OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AAD;LARGER THAN OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AAE;EQUALS SIGN WITH BUMPY ABOVE;Sm;0;ON;;;;;N;;;;; +2AAF;PRECEDES ABOVE SINGLE-LINE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;; +2AB0;SUCCEEDS ABOVE SINGLE-LINE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;; +2AB1;PRECEDES ABOVE SINGLE-LINE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AB2;SUCCEEDS ABOVE SINGLE-LINE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AB3;PRECEDES ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;; +2AB4;SUCCEEDS ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;; +2AB5;PRECEDES ABOVE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AB6;SUCCEEDS ABOVE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AB7;PRECEDES ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AB8;SUCCEEDS ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AB9;PRECEDES ABOVE NOT ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2ABA;SUCCEEDS ABOVE NOT ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2ABB;DOUBLE PRECEDES;Sm;0;ON;;;;;Y;;;;; +2ABC;DOUBLE SUCCEEDS;Sm;0;ON;;;;;Y;;;;; +2ABD;SUBSET WITH DOT;Sm;0;ON;;;;;Y;;;;; +2ABE;SUPERSET WITH DOT;Sm;0;ON;;;;;Y;;;;; +2ABF;SUBSET WITH PLUS SIGN BELOW;Sm;0;ON;;;;;Y;;;;; +2AC0;SUPERSET WITH PLUS SIGN BELOW;Sm;0;ON;;;;;Y;;;;; +2AC1;SUBSET WITH MULTIPLICATION SIGN BELOW;Sm;0;ON;;;;;Y;;;;; +2AC2;SUPERSET WITH MULTIPLICATION SIGN BELOW;Sm;0;ON;;;;;Y;;;;; +2AC3;SUBSET OF OR EQUAL TO WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;; +2AC4;SUPERSET OF OR EQUAL TO WITH DOT ABOVE;Sm;0;ON;;;;;Y;;;;; +2AC5;SUBSET OF ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;; +2AC6;SUPERSET OF ABOVE EQUALS SIGN;Sm;0;ON;;;;;Y;;;;; +2AC7;SUBSET OF ABOVE TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;; +2AC8;SUPERSET OF ABOVE TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;; +2AC9;SUBSET OF ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2ACA;SUPERSET OF ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2ACB;SUBSET OF ABOVE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2ACC;SUPERSET OF ABOVE NOT EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2ACD;SQUARE LEFT OPEN BOX OPERATOR;Sm;0;ON;;;;;Y;;;;; +2ACE;SQUARE RIGHT OPEN BOX OPERATOR;Sm;0;ON;;;;;Y;;;;; +2ACF;CLOSED SUBSET;Sm;0;ON;;;;;Y;;;;; +2AD0;CLOSED SUPERSET;Sm;0;ON;;;;;Y;;;;; +2AD1;CLOSED SUBSET OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AD2;CLOSED SUPERSET OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AD3;SUBSET ABOVE SUPERSET;Sm;0;ON;;;;;Y;;;;; +2AD4;SUPERSET ABOVE SUBSET;Sm;0;ON;;;;;Y;;;;; +2AD5;SUBSET ABOVE SUBSET;Sm;0;ON;;;;;Y;;;;; +2AD6;SUPERSET ABOVE SUPERSET;Sm;0;ON;;;;;Y;;;;; +2AD7;SUPERSET BESIDE SUBSET;Sm;0;ON;;;;;N;;;;; +2AD8;SUPERSET BESIDE AND JOINED BY DASH WITH SUBSET;Sm;0;ON;;;;;N;;;;; +2AD9;ELEMENT OF OPENING DOWNWARDS;Sm;0;ON;;;;;N;;;;; +2ADA;PITCHFORK WITH TEE TOP;Sm;0;ON;;;;;N;;;;; +2ADB;TRANSVERSAL INTERSECTION;Sm;0;ON;;;;;N;;;;; +2ADC;FORKING;Sm;0;ON;2ADD 0338;;;;Y;;;;; +2ADD;NONFORKING;Sm;0;ON;;;;;N;;;;; +2ADE;SHORT LEFT TACK;Sm;0;ON;;;;;Y;;;;; +2ADF;SHORT DOWN TACK;Sm;0;ON;;;;;N;;;;; +2AE0;SHORT UP TACK;Sm;0;ON;;;;;N;;;;; +2AE1;PERPENDICULAR WITH S;Sm;0;ON;;;;;N;;;;; +2AE2;VERTICAL BAR TRIPLE RIGHT TURNSTILE;Sm;0;ON;;;;;Y;;;;; +2AE3;DOUBLE VERTICAL BAR LEFT TURNSTILE;Sm;0;ON;;;;;Y;;;;; +2AE4;VERTICAL BAR DOUBLE LEFT TURNSTILE;Sm;0;ON;;;;;Y;;;;; +2AE5;DOUBLE VERTICAL BAR DOUBLE LEFT TURNSTILE;Sm;0;ON;;;;;Y;;;;; +2AE6;LONG DASH FROM LEFT MEMBER OF DOUBLE VERTICAL;Sm;0;ON;;;;;Y;;;;; +2AE7;SHORT DOWN TACK WITH OVERBAR;Sm;0;ON;;;;;N;;;;; +2AE8;SHORT UP TACK WITH UNDERBAR;Sm;0;ON;;;;;N;;;;; +2AE9;SHORT UP TACK ABOVE SHORT DOWN TACK;Sm;0;ON;;;;;N;;;;; +2AEA;DOUBLE DOWN TACK;Sm;0;ON;;;;;N;;;;; +2AEB;DOUBLE UP TACK;Sm;0;ON;;;;;N;;;;; +2AEC;DOUBLE STROKE NOT SIGN;Sm;0;ON;;;;;Y;;;;; +2AED;REVERSED DOUBLE STROKE NOT SIGN;Sm;0;ON;;;;;Y;;;;; +2AEE;DOES NOT DIVIDE WITH REVERSED NEGATION SLASH;Sm;0;ON;;;;;Y;;;;; +2AEF;VERTICAL LINE WITH CIRCLE ABOVE;Sm;0;ON;;;;;N;;;;; +2AF0;VERTICAL LINE WITH CIRCLE BELOW;Sm;0;ON;;;;;N;;;;; +2AF1;DOWN TACK WITH CIRCLE BELOW;Sm;0;ON;;;;;N;;;;; +2AF2;PARALLEL WITH HORIZONTAL STROKE;Sm;0;ON;;;;;N;;;;; +2AF3;PARALLEL WITH TILDE OPERATOR;Sm;0;ON;;;;;Y;;;;; +2AF4;TRIPLE VERTICAL BAR BINARY RELATION;Sm;0;ON;;;;;N;;;;; +2AF5;TRIPLE VERTICAL BAR WITH HORIZONTAL STROKE;Sm;0;ON;;;;;N;;;;; +2AF6;TRIPLE COLON OPERATOR;Sm;0;ON;;;;;N;;;;; +2AF7;TRIPLE NESTED LESS-THAN;Sm;0;ON;;;;;Y;;;;; +2AF8;TRIPLE NESTED GREATER-THAN;Sm;0;ON;;;;;Y;;;;; +2AF9;DOUBLE-LINE SLANTED LESS-THAN OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AFA;DOUBLE-LINE SLANTED GREATER-THAN OR EQUAL TO;Sm;0;ON;;;;;Y;;;;; +2AFB;TRIPLE SOLIDUS BINARY RELATION;Sm;0;ON;;;;;Y;;;;; +2AFC;LARGE TRIPLE VERTICAL BAR OPERATOR;Sm;0;ON;;;;;N;;;;; +2AFD;DOUBLE SOLIDUS OPERATOR;Sm;0;ON;;;;;Y;;;;; +2AFE;WHITE VERTICAL BAR;Sm;0;ON;;;;;N;;;;; +2AFF;N-ARY WHITE VERTICAL BAR;Sm;0;ON;;;;;N;;;;; +2B00;NORTH EAST WHITE ARROW;So;0;ON;;;;;N;;;;; +2B01;NORTH WEST WHITE ARROW;So;0;ON;;;;;N;;;;; +2B02;SOUTH EAST WHITE ARROW;So;0;ON;;;;;N;;;;; +2B03;SOUTH WEST WHITE ARROW;So;0;ON;;;;;N;;;;; +2B04;LEFT RIGHT WHITE ARROW;So;0;ON;;;;;N;;;;; +2B05;LEFTWARDS BLACK ARROW;So;0;ON;;;;;N;;;;; +2B06;UPWARDS BLACK ARROW;So;0;ON;;;;;N;;;;; +2B07;DOWNWARDS BLACK ARROW;So;0;ON;;;;;N;;;;; +2B08;NORTH EAST BLACK ARROW;So;0;ON;;;;;N;;;;; +2B09;NORTH WEST BLACK ARROW;So;0;ON;;;;;N;;;;; +2B0A;SOUTH EAST BLACK ARROW;So;0;ON;;;;;N;;;;; +2B0B;SOUTH WEST BLACK ARROW;So;0;ON;;;;;N;;;;; +2B0C;LEFT RIGHT BLACK ARROW;So;0;ON;;;;;N;;;;; +2B0D;UP DOWN BLACK ARROW;So;0;ON;;;;;N;;;;; +2B0E;RIGHTWARDS ARROW WITH TIP DOWNWARDS;So;0;ON;;;;;N;;;;; +2B0F;RIGHTWARDS ARROW WITH TIP UPWARDS;So;0;ON;;;;;N;;;;; +2B10;LEFTWARDS ARROW WITH TIP DOWNWARDS;So;0;ON;;;;;N;;;;; +2B11;LEFTWARDS ARROW WITH TIP UPWARDS;So;0;ON;;;;;N;;;;; +2B12;SQUARE WITH TOP HALF BLACK;So;0;ON;;;;;N;;;;; +2B13;SQUARE WITH BOTTOM HALF BLACK;So;0;ON;;;;;N;;;;; +2B14;SQUARE WITH UPPER RIGHT DIAGONAL HALF BLACK;So;0;ON;;;;;N;;;;; +2B15;SQUARE WITH LOWER LEFT DIAGONAL HALF BLACK;So;0;ON;;;;;N;;;;; +2B16;DIAMOND WITH LEFT HALF BLACK;So;0;ON;;;;;N;;;;; +2B17;DIAMOND WITH RIGHT HALF BLACK;So;0;ON;;;;;N;;;;; +2B18;DIAMOND WITH TOP HALF BLACK;So;0;ON;;;;;N;;;;; +2B19;DIAMOND WITH BOTTOM HALF BLACK;So;0;ON;;;;;N;;;;; +2B1A;DOTTED SQUARE;So;0;ON;;;;;N;;;;; +2B1B;BLACK LARGE SQUARE;So;0;ON;;;;;N;;;;; +2B1C;WHITE LARGE SQUARE;So;0;ON;;;;;N;;;;; +2B1D;BLACK VERY SMALL SQUARE;So;0;ON;;;;;N;;;;; +2B1E;WHITE VERY SMALL SQUARE;So;0;ON;;;;;N;;;;; +2B1F;BLACK PENTAGON;So;0;ON;;;;;N;;;;; +2B20;WHITE PENTAGON;So;0;ON;;;;;N;;;;; +2B21;WHITE HEXAGON;So;0;ON;;;;;N;;;;; +2B22;BLACK HEXAGON;So;0;ON;;;;;N;;;;; +2B23;HORIZONTAL BLACK HEXAGON;So;0;ON;;;;;N;;;;; +2B24;BLACK LARGE CIRCLE;So;0;ON;;;;;N;;;;; +2B25;BLACK MEDIUM DIAMOND;So;0;ON;;;;;N;;;;; +2B26;WHITE MEDIUM DIAMOND;So;0;ON;;;;;N;;;;; +2B27;BLACK MEDIUM LOZENGE;So;0;ON;;;;;N;;;;; +2B28;WHITE MEDIUM LOZENGE;So;0;ON;;;;;N;;;;; +2B29;BLACK SMALL DIAMOND;So;0;ON;;;;;N;;;;; +2B2A;BLACK SMALL LOZENGE;So;0;ON;;;;;N;;;;; +2B2B;WHITE SMALL LOZENGE;So;0;ON;;;;;N;;;;; +2B2C;BLACK HORIZONTAL ELLIPSE;So;0;ON;;;;;N;;;;; +2B2D;WHITE HORIZONTAL ELLIPSE;So;0;ON;;;;;N;;;;; +2B2E;BLACK VERTICAL ELLIPSE;So;0;ON;;;;;N;;;;; +2B2F;WHITE VERTICAL ELLIPSE;So;0;ON;;;;;N;;;;; +2B30;LEFT ARROW WITH SMALL CIRCLE;Sm;0;ON;;;;;N;;;;; +2B31;THREE LEFTWARDS ARROWS;Sm;0;ON;;;;;N;;;;; +2B32;LEFT ARROW WITH CIRCLED PLUS;Sm;0;ON;;;;;N;;;;; +2B33;LONG LEFTWARDS SQUIGGLE ARROW;Sm;0;ON;;;;;N;;;;; +2B34;LEFTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2B35;LEFTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2B36;LEFTWARDS TWO-HEADED ARROW FROM BAR;Sm;0;ON;;;;;N;;;;; +2B37;LEFTWARDS TWO-HEADED TRIPLE DASH ARROW;Sm;0;ON;;;;;N;;;;; +2B38;LEFTWARDS ARROW WITH DOTTED STEM;Sm;0;ON;;;;;N;;;;; +2B39;LEFTWARDS ARROW WITH TAIL WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2B3A;LEFTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2B3B;LEFTWARDS TWO-HEADED ARROW WITH TAIL;Sm;0;ON;;;;;N;;;;; +2B3C;LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2B3D;LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE;Sm;0;ON;;;;;N;;;;; +2B3E;LEFTWARDS ARROW THROUGH X;Sm;0;ON;;;;;N;;;;; +2B3F;WAVE ARROW POINTING DIRECTLY LEFT;Sm;0;ON;;;;;N;;;;; +2B40;EQUALS SIGN ABOVE LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2B41;REVERSE TILDE OPERATOR ABOVE LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2B42;LEFTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO;Sm;0;ON;;;;;N;;;;; +2B43;RIGHTWARDS ARROW THROUGH GREATER-THAN;Sm;0;ON;;;;;N;;;;; +2B44;RIGHTWARDS ARROW THROUGH SUPERSET;Sm;0;ON;;;;;N;;;;; +2B45;LEFTWARDS QUADRUPLE ARROW;So;0;ON;;;;;N;;;;; +2B46;RIGHTWARDS QUADRUPLE ARROW;So;0;ON;;;;;N;;;;; +2B47;REVERSE TILDE OPERATOR ABOVE RIGHTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2B48;RIGHTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO;Sm;0;ON;;;;;N;;;;; +2B49;TILDE OPERATOR ABOVE LEFTWARDS ARROW;Sm;0;ON;;;;;N;;;;; +2B4A;LEFTWARDS ARROW ABOVE ALMOST EQUAL TO;Sm;0;ON;;;;;N;;;;; +2B4B;LEFTWARDS ARROW ABOVE REVERSE TILDE OPERATOR;Sm;0;ON;;;;;N;;;;; +2B4C;RIGHTWARDS ARROW ABOVE REVERSE TILDE OPERATOR;Sm;0;ON;;;;;N;;;;; +2B50;WHITE MEDIUM STAR;So;0;ON;;;;;N;;;;; +2B51;BLACK SMALL STAR;So;0;ON;;;;;N;;;;; +2B52;WHITE SMALL STAR;So;0;ON;;;;;N;;;;; +2B53;BLACK RIGHT-POINTING PENTAGON;So;0;ON;;;;;N;;;;; +2B54;WHITE RIGHT-POINTING PENTAGON;So;0;ON;;;;;N;;;;; +2B55;HEAVY LARGE CIRCLE;So;0;ON;;;;;N;;;;; +2B56;HEAVY OVAL WITH OVAL INSIDE;So;0;ON;;;;;N;;;;; +2B57;HEAVY CIRCLE WITH CIRCLE INSIDE;So;0;ON;;;;;N;;;;; +2B58;HEAVY CIRCLE;So;0;ON;;;;;N;;;;; +2B59;HEAVY CIRCLED SALTIRE;So;0;ON;;;;;N;;;;; +2C00;GLAGOLITIC CAPITAL LETTER AZU;Lu;0;L;;;;;N;;;;2C30; +2C01;GLAGOLITIC CAPITAL LETTER BUKY;Lu;0;L;;;;;N;;;;2C31; +2C02;GLAGOLITIC CAPITAL LETTER VEDE;Lu;0;L;;;;;N;;;;2C32; +2C03;GLAGOLITIC CAPITAL LETTER GLAGOLI;Lu;0;L;;;;;N;;;;2C33; +2C04;GLAGOLITIC CAPITAL LETTER DOBRO;Lu;0;L;;;;;N;;;;2C34; +2C05;GLAGOLITIC CAPITAL LETTER YESTU;Lu;0;L;;;;;N;;;;2C35; +2C06;GLAGOLITIC CAPITAL LETTER ZHIVETE;Lu;0;L;;;;;N;;;;2C36; +2C07;GLAGOLITIC CAPITAL LETTER DZELO;Lu;0;L;;;;;N;;;;2C37; +2C08;GLAGOLITIC CAPITAL LETTER ZEMLJA;Lu;0;L;;;;;N;;;;2C38; +2C09;GLAGOLITIC CAPITAL LETTER IZHE;Lu;0;L;;;;;N;;;;2C39; +2C0A;GLAGOLITIC CAPITAL LETTER INITIAL IZHE;Lu;0;L;;;;;N;;;;2C3A; +2C0B;GLAGOLITIC CAPITAL LETTER I;Lu;0;L;;;;;N;;;;2C3B; +2C0C;GLAGOLITIC CAPITAL LETTER DJERVI;Lu;0;L;;;;;N;;;;2C3C; +2C0D;GLAGOLITIC CAPITAL LETTER KAKO;Lu;0;L;;;;;N;;;;2C3D; +2C0E;GLAGOLITIC CAPITAL LETTER LJUDIJE;Lu;0;L;;;;;N;;;;2C3E; +2C0F;GLAGOLITIC CAPITAL LETTER MYSLITE;Lu;0;L;;;;;N;;;;2C3F; +2C10;GLAGOLITIC CAPITAL LETTER NASHI;Lu;0;L;;;;;N;;;;2C40; +2C11;GLAGOLITIC CAPITAL LETTER ONU;Lu;0;L;;;;;N;;;;2C41; +2C12;GLAGOLITIC CAPITAL LETTER POKOJI;Lu;0;L;;;;;N;;;;2C42; +2C13;GLAGOLITIC CAPITAL LETTER RITSI;Lu;0;L;;;;;N;;;;2C43; +2C14;GLAGOLITIC CAPITAL LETTER SLOVO;Lu;0;L;;;;;N;;;;2C44; +2C15;GLAGOLITIC CAPITAL LETTER TVRIDO;Lu;0;L;;;;;N;;;;2C45; +2C16;GLAGOLITIC CAPITAL LETTER UKU;Lu;0;L;;;;;N;;;;2C46; +2C17;GLAGOLITIC CAPITAL LETTER FRITU;Lu;0;L;;;;;N;;;;2C47; +2C18;GLAGOLITIC CAPITAL LETTER HERU;Lu;0;L;;;;;N;;;;2C48; +2C19;GLAGOLITIC CAPITAL LETTER OTU;Lu;0;L;;;;;N;;;;2C49; +2C1A;GLAGOLITIC CAPITAL LETTER PE;Lu;0;L;;;;;N;;;;2C4A; +2C1B;GLAGOLITIC CAPITAL LETTER SHTA;Lu;0;L;;;;;N;;;;2C4B; +2C1C;GLAGOLITIC CAPITAL LETTER TSI;Lu;0;L;;;;;N;;;;2C4C; +2C1D;GLAGOLITIC CAPITAL LETTER CHRIVI;Lu;0;L;;;;;N;;;;2C4D; +2C1E;GLAGOLITIC CAPITAL LETTER SHA;Lu;0;L;;;;;N;;;;2C4E; +2C1F;GLAGOLITIC CAPITAL LETTER YERU;Lu;0;L;;;;;N;;;;2C4F; +2C20;GLAGOLITIC CAPITAL LETTER YERI;Lu;0;L;;;;;N;;;;2C50; +2C21;GLAGOLITIC CAPITAL LETTER YATI;Lu;0;L;;;;;N;;;;2C51; +2C22;GLAGOLITIC CAPITAL LETTER SPIDERY HA;Lu;0;L;;;;;N;;;;2C52; +2C23;GLAGOLITIC CAPITAL LETTER YU;Lu;0;L;;;;;N;;;;2C53; +2C24;GLAGOLITIC CAPITAL LETTER SMALL YUS;Lu;0;L;;;;;N;;;;2C54; +2C25;GLAGOLITIC CAPITAL LETTER SMALL YUS WITH TAIL;Lu;0;L;;;;;N;;;;2C55; +2C26;GLAGOLITIC CAPITAL LETTER YO;Lu;0;L;;;;;N;;;;2C56; +2C27;GLAGOLITIC CAPITAL LETTER IOTATED SMALL YUS;Lu;0;L;;;;;N;;;;2C57; +2C28;GLAGOLITIC CAPITAL LETTER BIG YUS;Lu;0;L;;;;;N;;;;2C58; +2C29;GLAGOLITIC CAPITAL LETTER IOTATED BIG YUS;Lu;0;L;;;;;N;;;;2C59; +2C2A;GLAGOLITIC CAPITAL LETTER FITA;Lu;0;L;;;;;N;;;;2C5A; +2C2B;GLAGOLITIC CAPITAL LETTER IZHITSA;Lu;0;L;;;;;N;;;;2C5B; +2C2C;GLAGOLITIC CAPITAL LETTER SHTAPIC;Lu;0;L;;;;;N;;;;2C5C; +2C2D;GLAGOLITIC CAPITAL LETTER TROKUTASTI A;Lu;0;L;;;;;N;;;;2C5D; +2C2E;GLAGOLITIC CAPITAL LETTER LATINATE MYSLITE;Lu;0;L;;;;;N;;;;2C5E; +2C30;GLAGOLITIC SMALL LETTER AZU;Ll;0;L;;;;;N;;;2C00;;2C00 +2C31;GLAGOLITIC SMALL LETTER BUKY;Ll;0;L;;;;;N;;;2C01;;2C01 +2C32;GLAGOLITIC SMALL LETTER VEDE;Ll;0;L;;;;;N;;;2C02;;2C02 +2C33;GLAGOLITIC SMALL LETTER GLAGOLI;Ll;0;L;;;;;N;;;2C03;;2C03 +2C34;GLAGOLITIC SMALL LETTER DOBRO;Ll;0;L;;;;;N;;;2C04;;2C04 +2C35;GLAGOLITIC SMALL LETTER YESTU;Ll;0;L;;;;;N;;;2C05;;2C05 +2C36;GLAGOLITIC SMALL LETTER ZHIVETE;Ll;0;L;;;;;N;;;2C06;;2C06 +2C37;GLAGOLITIC SMALL LETTER DZELO;Ll;0;L;;;;;N;;;2C07;;2C07 +2C38;GLAGOLITIC SMALL LETTER ZEMLJA;Ll;0;L;;;;;N;;;2C08;;2C08 +2C39;GLAGOLITIC SMALL LETTER IZHE;Ll;0;L;;;;;N;;;2C09;;2C09 +2C3A;GLAGOLITIC SMALL LETTER INITIAL IZHE;Ll;0;L;;;;;N;;;2C0A;;2C0A +2C3B;GLAGOLITIC SMALL LETTER I;Ll;0;L;;;;;N;;;2C0B;;2C0B +2C3C;GLAGOLITIC SMALL LETTER DJERVI;Ll;0;L;;;;;N;;;2C0C;;2C0C +2C3D;GLAGOLITIC SMALL LETTER KAKO;Ll;0;L;;;;;N;;;2C0D;;2C0D +2C3E;GLAGOLITIC SMALL LETTER LJUDIJE;Ll;0;L;;;;;N;;;2C0E;;2C0E +2C3F;GLAGOLITIC SMALL LETTER MYSLITE;Ll;0;L;;;;;N;;;2C0F;;2C0F +2C40;GLAGOLITIC SMALL LETTER NASHI;Ll;0;L;;;;;N;;;2C10;;2C10 +2C41;GLAGOLITIC SMALL LETTER ONU;Ll;0;L;;;;;N;;;2C11;;2C11 +2C42;GLAGOLITIC SMALL LETTER POKOJI;Ll;0;L;;;;;N;;;2C12;;2C12 +2C43;GLAGOLITIC SMALL LETTER RITSI;Ll;0;L;;;;;N;;;2C13;;2C13 +2C44;GLAGOLITIC SMALL LETTER SLOVO;Ll;0;L;;;;;N;;;2C14;;2C14 +2C45;GLAGOLITIC SMALL LETTER TVRIDO;Ll;0;L;;;;;N;;;2C15;;2C15 +2C46;GLAGOLITIC SMALL LETTER UKU;Ll;0;L;;;;;N;;;2C16;;2C16 +2C47;GLAGOLITIC SMALL LETTER FRITU;Ll;0;L;;;;;N;;;2C17;;2C17 +2C48;GLAGOLITIC SMALL LETTER HERU;Ll;0;L;;;;;N;;;2C18;;2C18 +2C49;GLAGOLITIC SMALL LETTER OTU;Ll;0;L;;;;;N;;;2C19;;2C19 +2C4A;GLAGOLITIC SMALL LETTER PE;Ll;0;L;;;;;N;;;2C1A;;2C1A +2C4B;GLAGOLITIC SMALL LETTER SHTA;Ll;0;L;;;;;N;;;2C1B;;2C1B +2C4C;GLAGOLITIC SMALL LETTER TSI;Ll;0;L;;;;;N;;;2C1C;;2C1C +2C4D;GLAGOLITIC SMALL LETTER CHRIVI;Ll;0;L;;;;;N;;;2C1D;;2C1D +2C4E;GLAGOLITIC SMALL LETTER SHA;Ll;0;L;;;;;N;;;2C1E;;2C1E +2C4F;GLAGOLITIC SMALL LETTER YERU;Ll;0;L;;;;;N;;;2C1F;;2C1F +2C50;GLAGOLITIC SMALL LETTER YERI;Ll;0;L;;;;;N;;;2C20;;2C20 +2C51;GLAGOLITIC SMALL LETTER YATI;Ll;0;L;;;;;N;;;2C21;;2C21 +2C52;GLAGOLITIC SMALL LETTER SPIDERY HA;Ll;0;L;;;;;N;;;2C22;;2C22 +2C53;GLAGOLITIC SMALL LETTER YU;Ll;0;L;;;;;N;;;2C23;;2C23 +2C54;GLAGOLITIC SMALL LETTER SMALL YUS;Ll;0;L;;;;;N;;;2C24;;2C24 +2C55;GLAGOLITIC SMALL LETTER SMALL YUS WITH TAIL;Ll;0;L;;;;;N;;;2C25;;2C25 +2C56;GLAGOLITIC SMALL LETTER YO;Ll;0;L;;;;;N;;;2C26;;2C26 +2C57;GLAGOLITIC SMALL LETTER IOTATED SMALL YUS;Ll;0;L;;;;;N;;;2C27;;2C27 +2C58;GLAGOLITIC SMALL LETTER BIG YUS;Ll;0;L;;;;;N;;;2C28;;2C28 +2C59;GLAGOLITIC SMALL LETTER IOTATED BIG YUS;Ll;0;L;;;;;N;;;2C29;;2C29 +2C5A;GLAGOLITIC SMALL LETTER FITA;Ll;0;L;;;;;N;;;2C2A;;2C2A +2C5B;GLAGOLITIC SMALL LETTER IZHITSA;Ll;0;L;;;;;N;;;2C2B;;2C2B +2C5C;GLAGOLITIC SMALL LETTER SHTAPIC;Ll;0;L;;;;;N;;;2C2C;;2C2C +2C5D;GLAGOLITIC SMALL LETTER TROKUTASTI A;Ll;0;L;;;;;N;;;2C2D;;2C2D +2C5E;GLAGOLITIC SMALL LETTER LATINATE MYSLITE;Ll;0;L;;;;;N;;;2C2E;;2C2E +2C60;LATIN CAPITAL LETTER L WITH DOUBLE BAR;Lu;0;L;;;;;N;;;;2C61; +2C61;LATIN SMALL LETTER L WITH DOUBLE BAR;Ll;0;L;;;;;N;;;2C60;;2C60 +2C62;LATIN CAPITAL LETTER L WITH MIDDLE TILDE;Lu;0;L;;;;;N;;;;026B; +2C63;LATIN CAPITAL LETTER P WITH STROKE;Lu;0;L;;;;;N;;;;1D7D; +2C64;LATIN CAPITAL LETTER R WITH TAIL;Lu;0;L;;;;;N;;;;027D; +2C65;LATIN SMALL LETTER A WITH STROKE;Ll;0;L;;;;;N;;;023A;;023A +2C66;LATIN SMALL LETTER T WITH DIAGONAL STROKE;Ll;0;L;;;;;N;;;023E;;023E +2C67;LATIN CAPITAL LETTER H WITH DESCENDER;Lu;0;L;;;;;N;;;;2C68; +2C68;LATIN SMALL LETTER H WITH DESCENDER;Ll;0;L;;;;;N;;;2C67;;2C67 +2C69;LATIN CAPITAL LETTER K WITH DESCENDER;Lu;0;L;;;;;N;;;;2C6A; +2C6A;LATIN SMALL LETTER K WITH DESCENDER;Ll;0;L;;;;;N;;;2C69;;2C69 +2C6B;LATIN CAPITAL LETTER Z WITH DESCENDER;Lu;0;L;;;;;N;;;;2C6C; +2C6C;LATIN SMALL LETTER Z WITH DESCENDER;Ll;0;L;;;;;N;;;2C6B;;2C6B +2C6D;LATIN CAPITAL LETTER ALPHA;Lu;0;L;;;;;N;;;;0251; +2C6E;LATIN CAPITAL LETTER M WITH HOOK;Lu;0;L;;;;;N;;;;0271; +2C6F;LATIN CAPITAL LETTER TURNED A;Lu;0;L;;;;;N;;;;0250; +2C70;LATIN CAPITAL LETTER TURNED ALPHA;Lu;0;L;;;;;N;;;;0252; +2C71;LATIN SMALL LETTER V WITH RIGHT HOOK;Ll;0;L;;;;;N;;;;; +2C72;LATIN CAPITAL LETTER W WITH HOOK;Lu;0;L;;;;;N;;;;2C73; +2C73;LATIN SMALL LETTER W WITH HOOK;Ll;0;L;;;;;N;;;2C72;;2C72 +2C74;LATIN SMALL LETTER V WITH CURL;Ll;0;L;;;;;N;;;;; +2C75;LATIN CAPITAL LETTER HALF H;Lu;0;L;;;;;N;;;;2C76; +2C76;LATIN SMALL LETTER HALF H;Ll;0;L;;;;;N;;;2C75;;2C75 +2C77;LATIN SMALL LETTER TAILLESS PHI;Ll;0;L;;;;;N;;;;; +2C78;LATIN SMALL LETTER E WITH NOTCH;Ll;0;L;;;;;N;;;;; +2C79;LATIN SMALL LETTER TURNED R WITH TAIL;Ll;0;L;;;;;N;;;;; +2C7A;LATIN SMALL LETTER O WITH LOW RING INSIDE;Ll;0;L;;;;;N;;;;; +2C7B;LATIN LETTER SMALL CAPITAL TURNED E;Ll;0;L;;;;;N;;;;; +2C7C;LATIN SUBSCRIPT SMALL LETTER J;Lm;0;L; 006A;;;;N;;;;; +2C7D;MODIFIER LETTER CAPITAL V;Lm;0;L; 0056;;;;N;;;;; +2C7E;LATIN CAPITAL LETTER S WITH SWASH TAIL;Lu;0;L;;;;;N;;;;023F; +2C7F;LATIN CAPITAL LETTER Z WITH SWASH TAIL;Lu;0;L;;;;;N;;;;0240; +2C80;COPTIC CAPITAL LETTER ALFA;Lu;0;L;;;;;N;;;;2C81; +2C81;COPTIC SMALL LETTER ALFA;Ll;0;L;;;;;N;;;2C80;;2C80 +2C82;COPTIC CAPITAL LETTER VIDA;Lu;0;L;;;;;N;;;;2C83; +2C83;COPTIC SMALL LETTER VIDA;Ll;0;L;;;;;N;;;2C82;;2C82 +2C84;COPTIC CAPITAL LETTER GAMMA;Lu;0;L;;;;;N;;;;2C85; +2C85;COPTIC SMALL LETTER GAMMA;Ll;0;L;;;;;N;;;2C84;;2C84 +2C86;COPTIC CAPITAL LETTER DALDA;Lu;0;L;;;;;N;;;;2C87; +2C87;COPTIC SMALL LETTER DALDA;Ll;0;L;;;;;N;;;2C86;;2C86 +2C88;COPTIC CAPITAL LETTER EIE;Lu;0;L;;;;;N;;;;2C89; +2C89;COPTIC SMALL LETTER EIE;Ll;0;L;;;;;N;;;2C88;;2C88 +2C8A;COPTIC CAPITAL LETTER SOU;Lu;0;L;;;;;N;;;;2C8B; +2C8B;COPTIC SMALL LETTER SOU;Ll;0;L;;;;;N;;;2C8A;;2C8A +2C8C;COPTIC CAPITAL LETTER ZATA;Lu;0;L;;;;;N;;;;2C8D; +2C8D;COPTIC SMALL LETTER ZATA;Ll;0;L;;;;;N;;;2C8C;;2C8C +2C8E;COPTIC CAPITAL LETTER HATE;Lu;0;L;;;;;N;;;;2C8F; +2C8F;COPTIC SMALL LETTER HATE;Ll;0;L;;;;;N;;;2C8E;;2C8E +2C90;COPTIC CAPITAL LETTER THETHE;Lu;0;L;;;;;N;;;;2C91; +2C91;COPTIC SMALL LETTER THETHE;Ll;0;L;;;;;N;;;2C90;;2C90 +2C92;COPTIC CAPITAL LETTER IAUDA;Lu;0;L;;;;;N;;;;2C93; +2C93;COPTIC SMALL LETTER IAUDA;Ll;0;L;;;;;N;;;2C92;;2C92 +2C94;COPTIC CAPITAL LETTER KAPA;Lu;0;L;;;;;N;;;;2C95; +2C95;COPTIC SMALL LETTER KAPA;Ll;0;L;;;;;N;;;2C94;;2C94 +2C96;COPTIC CAPITAL LETTER LAULA;Lu;0;L;;;;;N;;;;2C97; +2C97;COPTIC SMALL LETTER LAULA;Ll;0;L;;;;;N;;;2C96;;2C96 +2C98;COPTIC CAPITAL LETTER MI;Lu;0;L;;;;;N;;;;2C99; +2C99;COPTIC SMALL LETTER MI;Ll;0;L;;;;;N;;;2C98;;2C98 +2C9A;COPTIC CAPITAL LETTER NI;Lu;0;L;;;;;N;;;;2C9B; +2C9B;COPTIC SMALL LETTER NI;Ll;0;L;;;;;N;;;2C9A;;2C9A +2C9C;COPTIC CAPITAL LETTER KSI;Lu;0;L;;;;;N;;;;2C9D; +2C9D;COPTIC SMALL LETTER KSI;Ll;0;L;;;;;N;;;2C9C;;2C9C +2C9E;COPTIC CAPITAL LETTER O;Lu;0;L;;;;;N;;;;2C9F; +2C9F;COPTIC SMALL LETTER O;Ll;0;L;;;;;N;;;2C9E;;2C9E +2CA0;COPTIC CAPITAL LETTER PI;Lu;0;L;;;;;N;;;;2CA1; +2CA1;COPTIC SMALL LETTER PI;Ll;0;L;;;;;N;;;2CA0;;2CA0 +2CA2;COPTIC CAPITAL LETTER RO;Lu;0;L;;;;;N;;;;2CA3; +2CA3;COPTIC SMALL LETTER RO;Ll;0;L;;;;;N;;;2CA2;;2CA2 +2CA4;COPTIC CAPITAL LETTER SIMA;Lu;0;L;;;;;N;;;;2CA5; +2CA5;COPTIC SMALL LETTER SIMA;Ll;0;L;;;;;N;;;2CA4;;2CA4 +2CA6;COPTIC CAPITAL LETTER TAU;Lu;0;L;;;;;N;;;;2CA7; +2CA7;COPTIC SMALL LETTER TAU;Ll;0;L;;;;;N;;;2CA6;;2CA6 +2CA8;COPTIC CAPITAL LETTER UA;Lu;0;L;;;;;N;;;;2CA9; +2CA9;COPTIC SMALL LETTER UA;Ll;0;L;;;;;N;;;2CA8;;2CA8 +2CAA;COPTIC CAPITAL LETTER FI;Lu;0;L;;;;;N;;;;2CAB; +2CAB;COPTIC SMALL LETTER FI;Ll;0;L;;;;;N;;;2CAA;;2CAA +2CAC;COPTIC CAPITAL LETTER KHI;Lu;0;L;;;;;N;;;;2CAD; +2CAD;COPTIC SMALL LETTER KHI;Ll;0;L;;;;;N;;;2CAC;;2CAC +2CAE;COPTIC CAPITAL LETTER PSI;Lu;0;L;;;;;N;;;;2CAF; +2CAF;COPTIC SMALL LETTER PSI;Ll;0;L;;;;;N;;;2CAE;;2CAE +2CB0;COPTIC CAPITAL LETTER OOU;Lu;0;L;;;;;N;;;;2CB1; +2CB1;COPTIC SMALL LETTER OOU;Ll;0;L;;;;;N;;;2CB0;;2CB0 +2CB2;COPTIC CAPITAL LETTER DIALECT-P ALEF;Lu;0;L;;;;;N;;;;2CB3; +2CB3;COPTIC SMALL LETTER DIALECT-P ALEF;Ll;0;L;;;;;N;;;2CB2;;2CB2 +2CB4;COPTIC CAPITAL LETTER OLD COPTIC AIN;Lu;0;L;;;;;N;;;;2CB5; +2CB5;COPTIC SMALL LETTER OLD COPTIC AIN;Ll;0;L;;;;;N;;;2CB4;;2CB4 +2CB6;COPTIC CAPITAL LETTER CRYPTOGRAMMIC EIE;Lu;0;L;;;;;N;;;;2CB7; +2CB7;COPTIC SMALL LETTER CRYPTOGRAMMIC EIE;Ll;0;L;;;;;N;;;2CB6;;2CB6 +2CB8;COPTIC CAPITAL LETTER DIALECT-P KAPA;Lu;0;L;;;;;N;;;;2CB9; +2CB9;COPTIC SMALL LETTER DIALECT-P KAPA;Ll;0;L;;;;;N;;;2CB8;;2CB8 +2CBA;COPTIC CAPITAL LETTER DIALECT-P NI;Lu;0;L;;;;;N;;;;2CBB; +2CBB;COPTIC SMALL LETTER DIALECT-P NI;Ll;0;L;;;;;N;;;2CBA;;2CBA +2CBC;COPTIC CAPITAL LETTER CRYPTOGRAMMIC NI;Lu;0;L;;;;;N;;;;2CBD; +2CBD;COPTIC SMALL LETTER CRYPTOGRAMMIC NI;Ll;0;L;;;;;N;;;2CBC;;2CBC +2CBE;COPTIC CAPITAL LETTER OLD COPTIC OOU;Lu;0;L;;;;;N;;;;2CBF; +2CBF;COPTIC SMALL LETTER OLD COPTIC OOU;Ll;0;L;;;;;N;;;2CBE;;2CBE +2CC0;COPTIC CAPITAL LETTER SAMPI;Lu;0;L;;;;;N;;;;2CC1; +2CC1;COPTIC SMALL LETTER SAMPI;Ll;0;L;;;;;N;;;2CC0;;2CC0 +2CC2;COPTIC CAPITAL LETTER CROSSED SHEI;Lu;0;L;;;;;N;;;;2CC3; +2CC3;COPTIC SMALL LETTER CROSSED SHEI;Ll;0;L;;;;;N;;;2CC2;;2CC2 +2CC4;COPTIC CAPITAL LETTER OLD COPTIC SHEI;Lu;0;L;;;;;N;;;;2CC5; +2CC5;COPTIC SMALL LETTER OLD COPTIC SHEI;Ll;0;L;;;;;N;;;2CC4;;2CC4 +2CC6;COPTIC CAPITAL LETTER OLD COPTIC ESH;Lu;0;L;;;;;N;;;;2CC7; +2CC7;COPTIC SMALL LETTER OLD COPTIC ESH;Ll;0;L;;;;;N;;;2CC6;;2CC6 +2CC8;COPTIC CAPITAL LETTER AKHMIMIC KHEI;Lu;0;L;;;;;N;;;;2CC9; +2CC9;COPTIC SMALL LETTER AKHMIMIC KHEI;Ll;0;L;;;;;N;;;2CC8;;2CC8 +2CCA;COPTIC CAPITAL LETTER DIALECT-P HORI;Lu;0;L;;;;;N;;;;2CCB; +2CCB;COPTIC SMALL LETTER DIALECT-P HORI;Ll;0;L;;;;;N;;;2CCA;;2CCA +2CCC;COPTIC CAPITAL LETTER OLD COPTIC HORI;Lu;0;L;;;;;N;;;;2CCD; +2CCD;COPTIC SMALL LETTER OLD COPTIC HORI;Ll;0;L;;;;;N;;;2CCC;;2CCC +2CCE;COPTIC CAPITAL LETTER OLD COPTIC HA;Lu;0;L;;;;;N;;;;2CCF; +2CCF;COPTIC SMALL LETTER OLD COPTIC HA;Ll;0;L;;;;;N;;;2CCE;;2CCE +2CD0;COPTIC CAPITAL LETTER L-SHAPED HA;Lu;0;L;;;;;N;;;;2CD1; +2CD1;COPTIC SMALL LETTER L-SHAPED HA;Ll;0;L;;;;;N;;;2CD0;;2CD0 +2CD2;COPTIC CAPITAL LETTER OLD COPTIC HEI;Lu;0;L;;;;;N;;;;2CD3; +2CD3;COPTIC SMALL LETTER OLD COPTIC HEI;Ll;0;L;;;;;N;;;2CD2;;2CD2 +2CD4;COPTIC CAPITAL LETTER OLD COPTIC HAT;Lu;0;L;;;;;N;;;;2CD5; +2CD5;COPTIC SMALL LETTER OLD COPTIC HAT;Ll;0;L;;;;;N;;;2CD4;;2CD4 +2CD6;COPTIC CAPITAL LETTER OLD COPTIC GANGIA;Lu;0;L;;;;;N;;;;2CD7; +2CD7;COPTIC SMALL LETTER OLD COPTIC GANGIA;Ll;0;L;;;;;N;;;2CD6;;2CD6 +2CD8;COPTIC CAPITAL LETTER OLD COPTIC DJA;Lu;0;L;;;;;N;;;;2CD9; +2CD9;COPTIC SMALL LETTER OLD COPTIC DJA;Ll;0;L;;;;;N;;;2CD8;;2CD8 +2CDA;COPTIC CAPITAL LETTER OLD COPTIC SHIMA;Lu;0;L;;;;;N;;;;2CDB; +2CDB;COPTIC SMALL LETTER OLD COPTIC SHIMA;Ll;0;L;;;;;N;;;2CDA;;2CDA +2CDC;COPTIC CAPITAL LETTER OLD NUBIAN SHIMA;Lu;0;L;;;;;N;;;;2CDD; +2CDD;COPTIC SMALL LETTER OLD NUBIAN SHIMA;Ll;0;L;;;;;N;;;2CDC;;2CDC +2CDE;COPTIC CAPITAL LETTER OLD NUBIAN NGI;Lu;0;L;;;;;N;;;;2CDF; +2CDF;COPTIC SMALL LETTER OLD NUBIAN NGI;Ll;0;L;;;;;N;;;2CDE;;2CDE +2CE0;COPTIC CAPITAL LETTER OLD NUBIAN NYI;Lu;0;L;;;;;N;;;;2CE1; +2CE1;COPTIC SMALL LETTER OLD NUBIAN NYI;Ll;0;L;;;;;N;;;2CE0;;2CE0 +2CE2;COPTIC CAPITAL LETTER OLD NUBIAN WAU;Lu;0;L;;;;;N;;;;2CE3; +2CE3;COPTIC SMALL LETTER OLD NUBIAN WAU;Ll;0;L;;;;;N;;;2CE2;;2CE2 +2CE4;COPTIC SYMBOL KAI;Ll;0;L;;;;;N;;;;; +2CE5;COPTIC SYMBOL MI RO;So;0;ON;;;;;N;;;;; +2CE6;COPTIC SYMBOL PI RO;So;0;ON;;;;;N;;;;; +2CE7;COPTIC SYMBOL STAUROS;So;0;ON;;;;;N;;;;; +2CE8;COPTIC SYMBOL TAU RO;So;0;ON;;;;;N;;;;; +2CE9;COPTIC SYMBOL KHI RO;So;0;ON;;;;;N;;;;; +2CEA;COPTIC SYMBOL SHIMA SIMA;So;0;ON;;;;;N;;;;; +2CEB;COPTIC CAPITAL LETTER CRYPTOGRAMMIC SHEI;Lu;0;L;;;;;N;;;;2CEC; +2CEC;COPTIC SMALL LETTER CRYPTOGRAMMIC SHEI;Ll;0;L;;;;;N;;;2CEB;;2CEB +2CED;COPTIC CAPITAL LETTER CRYPTOGRAMMIC GANGIA;Lu;0;L;;;;;N;;;;2CEE; +2CEE;COPTIC SMALL LETTER CRYPTOGRAMMIC GANGIA;Ll;0;L;;;;;N;;;2CED;;2CED +2CEF;COPTIC COMBINING NI ABOVE;Mn;230;NSM;;;;;N;;;;; +2CF0;COPTIC COMBINING SPIRITUS ASPER;Mn;230;NSM;;;;;N;;;;; +2CF1;COPTIC COMBINING SPIRITUS LENIS;Mn;230;NSM;;;;;N;;;;; +2CF2;COPTIC CAPITAL LETTER BOHAIRIC KHEI;Lu;0;L;;;;;N;;;;2CF3; +2CF3;COPTIC SMALL LETTER BOHAIRIC KHEI;Ll;0;L;;;;;N;;;2CF2;;2CF2 +2CF9;COPTIC OLD NUBIAN FULL STOP;Po;0;ON;;;;;N;;;;; +2CFA;COPTIC OLD NUBIAN DIRECT QUESTION MARK;Po;0;ON;;;;;N;;;;; +2CFB;COPTIC OLD NUBIAN INDIRECT QUESTION MARK;Po;0;ON;;;;;N;;;;; +2CFC;COPTIC OLD NUBIAN VERSE DIVIDER;Po;0;ON;;;;;N;;;;; +2CFD;COPTIC FRACTION ONE HALF;No;0;ON;;;;1/2;N;;;;; +2CFE;COPTIC FULL STOP;Po;0;ON;;;;;N;;;;; +2CFF;COPTIC MORPHOLOGICAL DIVIDER;Po;0;ON;;;;;N;;;;; +2D00;GEORGIAN SMALL LETTER AN;Ll;0;L;;;;;N;;;10A0;;10A0 +2D01;GEORGIAN SMALL LETTER BAN;Ll;0;L;;;;;N;;;10A1;;10A1 +2D02;GEORGIAN SMALL LETTER GAN;Ll;0;L;;;;;N;;;10A2;;10A2 +2D03;GEORGIAN SMALL LETTER DON;Ll;0;L;;;;;N;;;10A3;;10A3 +2D04;GEORGIAN SMALL LETTER EN;Ll;0;L;;;;;N;;;10A4;;10A4 +2D05;GEORGIAN SMALL LETTER VIN;Ll;0;L;;;;;N;;;10A5;;10A5 +2D06;GEORGIAN SMALL LETTER ZEN;Ll;0;L;;;;;N;;;10A6;;10A6 +2D07;GEORGIAN SMALL LETTER TAN;Ll;0;L;;;;;N;;;10A7;;10A7 +2D08;GEORGIAN SMALL LETTER IN;Ll;0;L;;;;;N;;;10A8;;10A8 +2D09;GEORGIAN SMALL LETTER KAN;Ll;0;L;;;;;N;;;10A9;;10A9 +2D0A;GEORGIAN SMALL LETTER LAS;Ll;0;L;;;;;N;;;10AA;;10AA +2D0B;GEORGIAN SMALL LETTER MAN;Ll;0;L;;;;;N;;;10AB;;10AB +2D0C;GEORGIAN SMALL LETTER NAR;Ll;0;L;;;;;N;;;10AC;;10AC +2D0D;GEORGIAN SMALL LETTER ON;Ll;0;L;;;;;N;;;10AD;;10AD +2D0E;GEORGIAN SMALL LETTER PAR;Ll;0;L;;;;;N;;;10AE;;10AE +2D0F;GEORGIAN SMALL LETTER ZHAR;Ll;0;L;;;;;N;;;10AF;;10AF +2D10;GEORGIAN SMALL LETTER RAE;Ll;0;L;;;;;N;;;10B0;;10B0 +2D11;GEORGIAN SMALL LETTER SAN;Ll;0;L;;;;;N;;;10B1;;10B1 +2D12;GEORGIAN SMALL LETTER TAR;Ll;0;L;;;;;N;;;10B2;;10B2 +2D13;GEORGIAN SMALL LETTER UN;Ll;0;L;;;;;N;;;10B3;;10B3 +2D14;GEORGIAN SMALL LETTER PHAR;Ll;0;L;;;;;N;;;10B4;;10B4 +2D15;GEORGIAN SMALL LETTER KHAR;Ll;0;L;;;;;N;;;10B5;;10B5 +2D16;GEORGIAN SMALL LETTER GHAN;Ll;0;L;;;;;N;;;10B6;;10B6 +2D17;GEORGIAN SMALL LETTER QAR;Ll;0;L;;;;;N;;;10B7;;10B7 +2D18;GEORGIAN SMALL LETTER SHIN;Ll;0;L;;;;;N;;;10B8;;10B8 +2D19;GEORGIAN SMALL LETTER CHIN;Ll;0;L;;;;;N;;;10B9;;10B9 +2D1A;GEORGIAN SMALL LETTER CAN;Ll;0;L;;;;;N;;;10BA;;10BA +2D1B;GEORGIAN SMALL LETTER JIL;Ll;0;L;;;;;N;;;10BB;;10BB +2D1C;GEORGIAN SMALL LETTER CIL;Ll;0;L;;;;;N;;;10BC;;10BC +2D1D;GEORGIAN SMALL LETTER CHAR;Ll;0;L;;;;;N;;;10BD;;10BD +2D1E;GEORGIAN SMALL LETTER XAN;Ll;0;L;;;;;N;;;10BE;;10BE +2D1F;GEORGIAN SMALL LETTER JHAN;Ll;0;L;;;;;N;;;10BF;;10BF +2D20;GEORGIAN SMALL LETTER HAE;Ll;0;L;;;;;N;;;10C0;;10C0 +2D21;GEORGIAN SMALL LETTER HE;Ll;0;L;;;;;N;;;10C1;;10C1 +2D22;GEORGIAN SMALL LETTER HIE;Ll;0;L;;;;;N;;;10C2;;10C2 +2D23;GEORGIAN SMALL LETTER WE;Ll;0;L;;;;;N;;;10C3;;10C3 +2D24;GEORGIAN SMALL LETTER HAR;Ll;0;L;;;;;N;;;10C4;;10C4 +2D25;GEORGIAN SMALL LETTER HOE;Ll;0;L;;;;;N;;;10C5;;10C5 +2D27;GEORGIAN SMALL LETTER YN;Ll;0;L;;;;;N;;;10C7;;10C7 +2D2D;GEORGIAN SMALL LETTER AEN;Ll;0;L;;;;;N;;;10CD;;10CD +2D30;TIFINAGH LETTER YA;Lo;0;L;;;;;N;;;;; +2D31;TIFINAGH LETTER YAB;Lo;0;L;;;;;N;;;;; +2D32;TIFINAGH LETTER YABH;Lo;0;L;;;;;N;;;;; +2D33;TIFINAGH LETTER YAG;Lo;0;L;;;;;N;;;;; +2D34;TIFINAGH LETTER YAGHH;Lo;0;L;;;;;N;;;;; +2D35;TIFINAGH LETTER BERBER ACADEMY YAJ;Lo;0;L;;;;;N;;;;; +2D36;TIFINAGH LETTER YAJ;Lo;0;L;;;;;N;;;;; +2D37;TIFINAGH LETTER YAD;Lo;0;L;;;;;N;;;;; +2D38;TIFINAGH LETTER YADH;Lo;0;L;;;;;N;;;;; +2D39;TIFINAGH LETTER YADD;Lo;0;L;;;;;N;;;;; +2D3A;TIFINAGH LETTER YADDH;Lo;0;L;;;;;N;;;;; +2D3B;TIFINAGH LETTER YEY;Lo;0;L;;;;;N;;;;; +2D3C;TIFINAGH LETTER YAF;Lo;0;L;;;;;N;;;;; +2D3D;TIFINAGH LETTER YAK;Lo;0;L;;;;;N;;;;; +2D3E;TIFINAGH LETTER TUAREG YAK;Lo;0;L;;;;;N;;;;; +2D3F;TIFINAGH LETTER YAKHH;Lo;0;L;;;;;N;;;;; +2D40;TIFINAGH LETTER YAH;Lo;0;L;;;;;N;;;;; +2D41;TIFINAGH LETTER BERBER ACADEMY YAH;Lo;0;L;;;;;N;;;;; +2D42;TIFINAGH LETTER TUAREG YAH;Lo;0;L;;;;;N;;;;; +2D43;TIFINAGH LETTER YAHH;Lo;0;L;;;;;N;;;;; +2D44;TIFINAGH LETTER YAA;Lo;0;L;;;;;N;;;;; +2D45;TIFINAGH LETTER YAKH;Lo;0;L;;;;;N;;;;; +2D46;TIFINAGH LETTER TUAREG YAKH;Lo;0;L;;;;;N;;;;; +2D47;TIFINAGH LETTER YAQ;Lo;0;L;;;;;N;;;;; +2D48;TIFINAGH LETTER TUAREG YAQ;Lo;0;L;;;;;N;;;;; +2D49;TIFINAGH LETTER YI;Lo;0;L;;;;;N;;;;; +2D4A;TIFINAGH LETTER YAZH;Lo;0;L;;;;;N;;;;; +2D4B;TIFINAGH LETTER AHAGGAR YAZH;Lo;0;L;;;;;N;;;;; +2D4C;TIFINAGH LETTER TUAREG YAZH;Lo;0;L;;;;;N;;;;; +2D4D;TIFINAGH LETTER YAL;Lo;0;L;;;;;N;;;;; +2D4E;TIFINAGH LETTER YAM;Lo;0;L;;;;;N;;;;; +2D4F;TIFINAGH LETTER YAN;Lo;0;L;;;;;N;;;;; +2D50;TIFINAGH LETTER TUAREG YAGN;Lo;0;L;;;;;N;;;;; +2D51;TIFINAGH LETTER TUAREG YANG;Lo;0;L;;;;;N;;;;; +2D52;TIFINAGH LETTER YAP;Lo;0;L;;;;;N;;;;; +2D53;TIFINAGH LETTER YU;Lo;0;L;;;;;N;;;;; +2D54;TIFINAGH LETTER YAR;Lo;0;L;;;;;N;;;;; +2D55;TIFINAGH LETTER YARR;Lo;0;L;;;;;N;;;;; +2D56;TIFINAGH LETTER YAGH;Lo;0;L;;;;;N;;;;; +2D57;TIFINAGH LETTER TUAREG YAGH;Lo;0;L;;;;;N;;;;; +2D58;TIFINAGH LETTER AYER YAGH;Lo;0;L;;;;;N;;;;; +2D59;TIFINAGH LETTER YAS;Lo;0;L;;;;;N;;;;; +2D5A;TIFINAGH LETTER YASS;Lo;0;L;;;;;N;;;;; +2D5B;TIFINAGH LETTER YASH;Lo;0;L;;;;;N;;;;; +2D5C;TIFINAGH LETTER YAT;Lo;0;L;;;;;N;;;;; +2D5D;TIFINAGH LETTER YATH;Lo;0;L;;;;;N;;;;; +2D5E;TIFINAGH LETTER YACH;Lo;0;L;;;;;N;;;;; +2D5F;TIFINAGH LETTER YATT;Lo;0;L;;;;;N;;;;; +2D60;TIFINAGH LETTER YAV;Lo;0;L;;;;;N;;;;; +2D61;TIFINAGH LETTER YAW;Lo;0;L;;;;;N;;;;; +2D62;TIFINAGH LETTER YAY;Lo;0;L;;;;;N;;;;; +2D63;TIFINAGH LETTER YAZ;Lo;0;L;;;;;N;;;;; +2D64;TIFINAGH LETTER TAWELLEMET YAZ;Lo;0;L;;;;;N;;;;; +2D65;TIFINAGH LETTER YAZZ;Lo;0;L;;;;;N;;;;; +2D66;TIFINAGH LETTER YE;Lo;0;L;;;;;N;;;;; +2D67;TIFINAGH LETTER YO;Lo;0;L;;;;;N;;;;; +2D6F;TIFINAGH MODIFIER LETTER LABIALIZATION MARK;Lm;0;L; 2D61;;;;N;;;;; +2D70;TIFINAGH SEPARATOR MARK;Po;0;L;;;;;N;;;;; +2D7F;TIFINAGH CONSONANT JOINER;Mn;9;NSM;;;;;N;;;;; +2D80;ETHIOPIC SYLLABLE LOA;Lo;0;L;;;;;N;;;;; +2D81;ETHIOPIC SYLLABLE MOA;Lo;0;L;;;;;N;;;;; +2D82;ETHIOPIC SYLLABLE ROA;Lo;0;L;;;;;N;;;;; +2D83;ETHIOPIC SYLLABLE SOA;Lo;0;L;;;;;N;;;;; +2D84;ETHIOPIC SYLLABLE SHOA;Lo;0;L;;;;;N;;;;; +2D85;ETHIOPIC SYLLABLE BOA;Lo;0;L;;;;;N;;;;; +2D86;ETHIOPIC SYLLABLE TOA;Lo;0;L;;;;;N;;;;; +2D87;ETHIOPIC SYLLABLE COA;Lo;0;L;;;;;N;;;;; +2D88;ETHIOPIC SYLLABLE NOA;Lo;0;L;;;;;N;;;;; +2D89;ETHIOPIC SYLLABLE NYOA;Lo;0;L;;;;;N;;;;; +2D8A;ETHIOPIC SYLLABLE GLOTTAL OA;Lo;0;L;;;;;N;;;;; +2D8B;ETHIOPIC SYLLABLE ZOA;Lo;0;L;;;;;N;;;;; +2D8C;ETHIOPIC SYLLABLE DOA;Lo;0;L;;;;;N;;;;; +2D8D;ETHIOPIC SYLLABLE DDOA;Lo;0;L;;;;;N;;;;; +2D8E;ETHIOPIC SYLLABLE JOA;Lo;0;L;;;;;N;;;;; +2D8F;ETHIOPIC SYLLABLE THOA;Lo;0;L;;;;;N;;;;; +2D90;ETHIOPIC SYLLABLE CHOA;Lo;0;L;;;;;N;;;;; +2D91;ETHIOPIC SYLLABLE PHOA;Lo;0;L;;;;;N;;;;; +2D92;ETHIOPIC SYLLABLE POA;Lo;0;L;;;;;N;;;;; +2D93;ETHIOPIC SYLLABLE GGWA;Lo;0;L;;;;;N;;;;; +2D94;ETHIOPIC SYLLABLE GGWI;Lo;0;L;;;;;N;;;;; +2D95;ETHIOPIC SYLLABLE GGWEE;Lo;0;L;;;;;N;;;;; +2D96;ETHIOPIC SYLLABLE GGWE;Lo;0;L;;;;;N;;;;; +2DA0;ETHIOPIC SYLLABLE SSA;Lo;0;L;;;;;N;;;;; +2DA1;ETHIOPIC SYLLABLE SSU;Lo;0;L;;;;;N;;;;; +2DA2;ETHIOPIC SYLLABLE SSI;Lo;0;L;;;;;N;;;;; +2DA3;ETHIOPIC SYLLABLE SSAA;Lo;0;L;;;;;N;;;;; +2DA4;ETHIOPIC SYLLABLE SSEE;Lo;0;L;;;;;N;;;;; +2DA5;ETHIOPIC SYLLABLE SSE;Lo;0;L;;;;;N;;;;; +2DA6;ETHIOPIC SYLLABLE SSO;Lo;0;L;;;;;N;;;;; +2DA8;ETHIOPIC SYLLABLE CCA;Lo;0;L;;;;;N;;;;; +2DA9;ETHIOPIC SYLLABLE CCU;Lo;0;L;;;;;N;;;;; +2DAA;ETHIOPIC SYLLABLE CCI;Lo;0;L;;;;;N;;;;; +2DAB;ETHIOPIC SYLLABLE CCAA;Lo;0;L;;;;;N;;;;; +2DAC;ETHIOPIC SYLLABLE CCEE;Lo;0;L;;;;;N;;;;; +2DAD;ETHIOPIC SYLLABLE CCE;Lo;0;L;;;;;N;;;;; +2DAE;ETHIOPIC SYLLABLE CCO;Lo;0;L;;;;;N;;;;; +2DB0;ETHIOPIC SYLLABLE ZZA;Lo;0;L;;;;;N;;;;; +2DB1;ETHIOPIC SYLLABLE ZZU;Lo;0;L;;;;;N;;;;; +2DB2;ETHIOPIC SYLLABLE ZZI;Lo;0;L;;;;;N;;;;; +2DB3;ETHIOPIC SYLLABLE ZZAA;Lo;0;L;;;;;N;;;;; +2DB4;ETHIOPIC SYLLABLE ZZEE;Lo;0;L;;;;;N;;;;; +2DB5;ETHIOPIC SYLLABLE ZZE;Lo;0;L;;;;;N;;;;; +2DB6;ETHIOPIC SYLLABLE ZZO;Lo;0;L;;;;;N;;;;; +2DB8;ETHIOPIC SYLLABLE CCHA;Lo;0;L;;;;;N;;;;; +2DB9;ETHIOPIC SYLLABLE CCHU;Lo;0;L;;;;;N;;;;; +2DBA;ETHIOPIC SYLLABLE CCHI;Lo;0;L;;;;;N;;;;; +2DBB;ETHIOPIC SYLLABLE CCHAA;Lo;0;L;;;;;N;;;;; +2DBC;ETHIOPIC SYLLABLE CCHEE;Lo;0;L;;;;;N;;;;; +2DBD;ETHIOPIC SYLLABLE CCHE;Lo;0;L;;;;;N;;;;; +2DBE;ETHIOPIC SYLLABLE CCHO;Lo;0;L;;;;;N;;;;; +2DC0;ETHIOPIC SYLLABLE QYA;Lo;0;L;;;;;N;;;;; +2DC1;ETHIOPIC SYLLABLE QYU;Lo;0;L;;;;;N;;;;; +2DC2;ETHIOPIC SYLLABLE QYI;Lo;0;L;;;;;N;;;;; +2DC3;ETHIOPIC SYLLABLE QYAA;Lo;0;L;;;;;N;;;;; +2DC4;ETHIOPIC SYLLABLE QYEE;Lo;0;L;;;;;N;;;;; +2DC5;ETHIOPIC SYLLABLE QYE;Lo;0;L;;;;;N;;;;; +2DC6;ETHIOPIC SYLLABLE QYO;Lo;0;L;;;;;N;;;;; +2DC8;ETHIOPIC SYLLABLE KYA;Lo;0;L;;;;;N;;;;; +2DC9;ETHIOPIC SYLLABLE KYU;Lo;0;L;;;;;N;;;;; +2DCA;ETHIOPIC SYLLABLE KYI;Lo;0;L;;;;;N;;;;; +2DCB;ETHIOPIC SYLLABLE KYAA;Lo;0;L;;;;;N;;;;; +2DCC;ETHIOPIC SYLLABLE KYEE;Lo;0;L;;;;;N;;;;; +2DCD;ETHIOPIC SYLLABLE KYE;Lo;0;L;;;;;N;;;;; +2DCE;ETHIOPIC SYLLABLE KYO;Lo;0;L;;;;;N;;;;; +2DD0;ETHIOPIC SYLLABLE XYA;Lo;0;L;;;;;N;;;;; +2DD1;ETHIOPIC SYLLABLE XYU;Lo;0;L;;;;;N;;;;; +2DD2;ETHIOPIC SYLLABLE XYI;Lo;0;L;;;;;N;;;;; +2DD3;ETHIOPIC SYLLABLE XYAA;Lo;0;L;;;;;N;;;;; +2DD4;ETHIOPIC SYLLABLE XYEE;Lo;0;L;;;;;N;;;;; +2DD5;ETHIOPIC SYLLABLE XYE;Lo;0;L;;;;;N;;;;; +2DD6;ETHIOPIC SYLLABLE XYO;Lo;0;L;;;;;N;;;;; +2DD8;ETHIOPIC SYLLABLE GYA;Lo;0;L;;;;;N;;;;; +2DD9;ETHIOPIC SYLLABLE GYU;Lo;0;L;;;;;N;;;;; +2DDA;ETHIOPIC SYLLABLE GYI;Lo;0;L;;;;;N;;;;; +2DDB;ETHIOPIC SYLLABLE GYAA;Lo;0;L;;;;;N;;;;; +2DDC;ETHIOPIC SYLLABLE GYEE;Lo;0;L;;;;;N;;;;; +2DDD;ETHIOPIC SYLLABLE GYE;Lo;0;L;;;;;N;;;;; +2DDE;ETHIOPIC SYLLABLE GYO;Lo;0;L;;;;;N;;;;; +2DE0;COMBINING CYRILLIC LETTER BE;Mn;230;NSM;;;;;N;;;;; +2DE1;COMBINING CYRILLIC LETTER VE;Mn;230;NSM;;;;;N;;;;; +2DE2;COMBINING CYRILLIC LETTER GHE;Mn;230;NSM;;;;;N;;;;; +2DE3;COMBINING CYRILLIC LETTER DE;Mn;230;NSM;;;;;N;;;;; +2DE4;COMBINING CYRILLIC LETTER ZHE;Mn;230;NSM;;;;;N;;;;; +2DE5;COMBINING CYRILLIC LETTER ZE;Mn;230;NSM;;;;;N;;;;; +2DE6;COMBINING CYRILLIC LETTER KA;Mn;230;NSM;;;;;N;;;;; +2DE7;COMBINING CYRILLIC LETTER EL;Mn;230;NSM;;;;;N;;;;; +2DE8;COMBINING CYRILLIC LETTER EM;Mn;230;NSM;;;;;N;;;;; +2DE9;COMBINING CYRILLIC LETTER EN;Mn;230;NSM;;;;;N;;;;; +2DEA;COMBINING CYRILLIC LETTER O;Mn;230;NSM;;;;;N;;;;; +2DEB;COMBINING CYRILLIC LETTER PE;Mn;230;NSM;;;;;N;;;;; +2DEC;COMBINING CYRILLIC LETTER ER;Mn;230;NSM;;;;;N;;;;; +2DED;COMBINING CYRILLIC LETTER ES;Mn;230;NSM;;;;;N;;;;; +2DEE;COMBINING CYRILLIC LETTER TE;Mn;230;NSM;;;;;N;;;;; +2DEF;COMBINING CYRILLIC LETTER HA;Mn;230;NSM;;;;;N;;;;; +2DF0;COMBINING CYRILLIC LETTER TSE;Mn;230;NSM;;;;;N;;;;; +2DF1;COMBINING CYRILLIC LETTER CHE;Mn;230;NSM;;;;;N;;;;; +2DF2;COMBINING CYRILLIC LETTER SHA;Mn;230;NSM;;;;;N;;;;; +2DF3;COMBINING CYRILLIC LETTER SHCHA;Mn;230;NSM;;;;;N;;;;; +2DF4;COMBINING CYRILLIC LETTER FITA;Mn;230;NSM;;;;;N;;;;; +2DF5;COMBINING CYRILLIC LETTER ES-TE;Mn;230;NSM;;;;;N;;;;; +2DF6;COMBINING CYRILLIC LETTER A;Mn;230;NSM;;;;;N;;;;; +2DF7;COMBINING CYRILLIC LETTER IE;Mn;230;NSM;;;;;N;;;;; +2DF8;COMBINING CYRILLIC LETTER DJERV;Mn;230;NSM;;;;;N;;;;; +2DF9;COMBINING CYRILLIC LETTER MONOGRAPH UK;Mn;230;NSM;;;;;N;;;;; +2DFA;COMBINING CYRILLIC LETTER YAT;Mn;230;NSM;;;;;N;;;;; +2DFB;COMBINING CYRILLIC LETTER YU;Mn;230;NSM;;;;;N;;;;; +2DFC;COMBINING CYRILLIC LETTER IOTIFIED A;Mn;230;NSM;;;;;N;;;;; +2DFD;COMBINING CYRILLIC LETTER LITTLE YUS;Mn;230;NSM;;;;;N;;;;; +2DFE;COMBINING CYRILLIC LETTER BIG YUS;Mn;230;NSM;;;;;N;;;;; +2DFF;COMBINING CYRILLIC LETTER IOTIFIED BIG YUS;Mn;230;NSM;;;;;N;;;;; +2E00;RIGHT ANGLE SUBSTITUTION MARKER;Po;0;ON;;;;;N;;;;; +2E01;RIGHT ANGLE DOTTED SUBSTITUTION MARKER;Po;0;ON;;;;;N;;;;; +2E02;LEFT SUBSTITUTION BRACKET;Pi;0;ON;;;;;Y;;;;; +2E03;RIGHT SUBSTITUTION BRACKET;Pf;0;ON;;;;;Y;;;;; +2E04;LEFT DOTTED SUBSTITUTION BRACKET;Pi;0;ON;;;;;Y;;;;; +2E05;RIGHT DOTTED SUBSTITUTION BRACKET;Pf;0;ON;;;;;Y;;;;; +2E06;RAISED INTERPOLATION MARKER;Po;0;ON;;;;;N;;;;; +2E07;RAISED DOTTED INTERPOLATION MARKER;Po;0;ON;;;;;N;;;;; +2E08;DOTTED TRANSPOSITION MARKER;Po;0;ON;;;;;N;;;;; +2E09;LEFT TRANSPOSITION BRACKET;Pi;0;ON;;;;;Y;;;;; +2E0A;RIGHT TRANSPOSITION BRACKET;Pf;0;ON;;;;;Y;;;;; +2E0B;RAISED SQUARE;Po;0;ON;;;;;N;;;;; +2E0C;LEFT RAISED OMISSION BRACKET;Pi;0;ON;;;;;Y;;;;; +2E0D;RIGHT RAISED OMISSION BRACKET;Pf;0;ON;;;;;Y;;;;; +2E0E;EDITORIAL CORONIS;Po;0;ON;;;;;N;;;;; +2E0F;PARAGRAPHOS;Po;0;ON;;;;;N;;;;; +2E10;FORKED PARAGRAPHOS;Po;0;ON;;;;;N;;;;; +2E11;REVERSED FORKED PARAGRAPHOS;Po;0;ON;;;;;N;;;;; +2E12;HYPODIASTOLE;Po;0;ON;;;;;N;;;;; +2E13;DOTTED OBELOS;Po;0;ON;;;;;N;;;;; +2E14;DOWNWARDS ANCORA;Po;0;ON;;;;;N;;;;; +2E15;UPWARDS ANCORA;Po;0;ON;;;;;N;;;;; +2E16;DOTTED RIGHT-POINTING ANGLE;Po;0;ON;;;;;N;;;;; +2E17;DOUBLE OBLIQUE HYPHEN;Pd;0;ON;;;;;N;;;;; +2E18;INVERTED INTERROBANG;Po;0;ON;;;;;N;;;;; +2E19;PALM BRANCH;Po;0;ON;;;;;N;;;;; +2E1A;HYPHEN WITH DIAERESIS;Pd;0;ON;;;;;N;;;;; +2E1B;TILDE WITH RING ABOVE;Po;0;ON;;;;;N;;;;; +2E1C;LEFT LOW PARAPHRASE BRACKET;Pi;0;ON;;;;;Y;;;;; +2E1D;RIGHT LOW PARAPHRASE BRACKET;Pf;0;ON;;;;;Y;;;;; +2E1E;TILDE WITH DOT ABOVE;Po;0;ON;;;;;N;;;;; +2E1F;TILDE WITH DOT BELOW;Po;0;ON;;;;;N;;;;; +2E20;LEFT VERTICAL BAR WITH QUILL;Pi;0;ON;;;;;Y;;;;; +2E21;RIGHT VERTICAL BAR WITH QUILL;Pf;0;ON;;;;;Y;;;;; +2E22;TOP LEFT HALF BRACKET;Ps;0;ON;;;;;Y;;;;; +2E23;TOP RIGHT HALF BRACKET;Pe;0;ON;;;;;Y;;;;; +2E24;BOTTOM LEFT HALF BRACKET;Ps;0;ON;;;;;Y;;;;; +2E25;BOTTOM RIGHT HALF BRACKET;Pe;0;ON;;;;;Y;;;;; +2E26;LEFT SIDEWAYS U BRACKET;Ps;0;ON;;;;;Y;;;;; +2E27;RIGHT SIDEWAYS U BRACKET;Pe;0;ON;;;;;Y;;;;; +2E28;LEFT DOUBLE PARENTHESIS;Ps;0;ON;;;;;Y;;;;; +2E29;RIGHT DOUBLE PARENTHESIS;Pe;0;ON;;;;;Y;;;;; +2E2A;TWO DOTS OVER ONE DOT PUNCTUATION;Po;0;ON;;;;;N;;;;; +2E2B;ONE DOT OVER TWO DOTS PUNCTUATION;Po;0;ON;;;;;N;;;;; +2E2C;SQUARED FOUR DOT PUNCTUATION;Po;0;ON;;;;;N;;;;; +2E2D;FIVE DOT MARK;Po;0;ON;;;;;N;;;;; +2E2E;REVERSED QUESTION MARK;Po;0;ON;;;;;N;;;;; +2E2F;VERTICAL TILDE;Lm;0;ON;;;;;N;;;;; +2E30;RING POINT;Po;0;ON;;;;;N;;;;; +2E31;WORD SEPARATOR MIDDLE DOT;Po;0;ON;;;;;N;;;;; +2E32;TURNED COMMA;Po;0;ON;;;;;N;;;;; +2E33;RAISED DOT;Po;0;ON;;;;;N;;;;; +2E34;RAISED COMMA;Po;0;ON;;;;;N;;;;; +2E35;TURNED SEMICOLON;Po;0;ON;;;;;N;;;;; +2E36;DAGGER WITH LEFT GUARD;Po;0;ON;;;;;N;;;;; +2E37;DAGGER WITH RIGHT GUARD;Po;0;ON;;;;;N;;;;; +2E38;TURNED DAGGER;Po;0;ON;;;;;N;;;;; +2E39;TOP HALF SECTION SIGN;Po;0;ON;;;;;N;;;;; +2E3A;TWO-EM DASH;Pd;0;ON;;;;;N;;;;; +2E3B;THREE-EM DASH;Pd;0;ON;;;;;N;;;;; +2E80;CJK RADICAL REPEAT;So;0;ON;;;;;N;;;;; +2E81;CJK RADICAL CLIFF;So;0;ON;;;;;N;;;;; +2E82;CJK RADICAL SECOND ONE;So;0;ON;;;;;N;;;;; +2E83;CJK RADICAL SECOND TWO;So;0;ON;;;;;N;;;;; +2E84;CJK RADICAL SECOND THREE;So;0;ON;;;;;N;;;;; +2E85;CJK RADICAL PERSON;So;0;ON;;;;;N;;;;; +2E86;CJK RADICAL BOX;So;0;ON;;;;;N;;;;; +2E87;CJK RADICAL TABLE;So;0;ON;;;;;N;;;;; +2E88;CJK RADICAL KNIFE ONE;So;0;ON;;;;;N;;;;; +2E89;CJK RADICAL KNIFE TWO;So;0;ON;;;;;N;;;;; +2E8A;CJK RADICAL DIVINATION;So;0;ON;;;;;N;;;;; +2E8B;CJK RADICAL SEAL;So;0;ON;;;;;N;;;;; +2E8C;CJK RADICAL SMALL ONE;So;0;ON;;;;;N;;;;; +2E8D;CJK RADICAL SMALL TWO;So;0;ON;;;;;N;;;;; +2E8E;CJK RADICAL LAME ONE;So;0;ON;;;;;N;;;;; +2E8F;CJK RADICAL LAME TWO;So;0;ON;;;;;N;;;;; +2E90;CJK RADICAL LAME THREE;So;0;ON;;;;;N;;;;; +2E91;CJK RADICAL LAME FOUR;So;0;ON;;;;;N;;;;; +2E92;CJK RADICAL SNAKE;So;0;ON;;;;;N;;;;; +2E93;CJK RADICAL THREAD;So;0;ON;;;;;N;;;;; +2E94;CJK RADICAL SNOUT ONE;So;0;ON;;;;;N;;;;; +2E95;CJK RADICAL SNOUT TWO;So;0;ON;;;;;N;;;;; +2E96;CJK RADICAL HEART ONE;So;0;ON;;;;;N;;;;; +2E97;CJK RADICAL HEART TWO;So;0;ON;;;;;N;;;;; +2E98;CJK RADICAL HAND;So;0;ON;;;;;N;;;;; +2E99;CJK RADICAL RAP;So;0;ON;;;;;N;;;;; +2E9B;CJK RADICAL CHOKE;So;0;ON;;;;;N;;;;; +2E9C;CJK RADICAL SUN;So;0;ON;;;;;N;;;;; +2E9D;CJK RADICAL MOON;So;0;ON;;;;;N;;;;; +2E9E;CJK RADICAL DEATH;So;0;ON;;;;;N;;;;; +2E9F;CJK RADICAL MOTHER;So;0;ON; 6BCD;;;;N;;;;; +2EA0;CJK RADICAL CIVILIAN;So;0;ON;;;;;N;;;;; +2EA1;CJK RADICAL WATER ONE;So;0;ON;;;;;N;;;;; +2EA2;CJK RADICAL WATER TWO;So;0;ON;;;;;N;;;;; +2EA3;CJK RADICAL FIRE;So;0;ON;;;;;N;;;;; +2EA4;CJK RADICAL PAW ONE;So;0;ON;;;;;N;;;;; +2EA5;CJK RADICAL PAW TWO;So;0;ON;;;;;N;;;;; +2EA6;CJK RADICAL SIMPLIFIED HALF TREE TRUNK;So;0;ON;;;;;N;;;;; +2EA7;CJK RADICAL COW;So;0;ON;;;;;N;;;;; +2EA8;CJK RADICAL DOG;So;0;ON;;;;;N;;;;; +2EA9;CJK RADICAL JADE;So;0;ON;;;;;N;;;;; +2EAA;CJK RADICAL BOLT OF CLOTH;So;0;ON;;;;;N;;;;; +2EAB;CJK RADICAL EYE;So;0;ON;;;;;N;;;;; +2EAC;CJK RADICAL SPIRIT ONE;So;0;ON;;;;;N;;;;; +2EAD;CJK RADICAL SPIRIT TWO;So;0;ON;;;;;N;;;;; +2EAE;CJK RADICAL BAMBOO;So;0;ON;;;;;N;;;;; +2EAF;CJK RADICAL SILK;So;0;ON;;;;;N;;;;; +2EB0;CJK RADICAL C-SIMPLIFIED SILK;So;0;ON;;;;;N;;;;; +2EB1;CJK RADICAL NET ONE;So;0;ON;;;;;N;;;;; +2EB2;CJK RADICAL NET TWO;So;0;ON;;;;;N;;;;; +2EB3;CJK RADICAL NET THREE;So;0;ON;;;;;N;;;;; +2EB4;CJK RADICAL NET FOUR;So;0;ON;;;;;N;;;;; +2EB5;CJK RADICAL MESH;So;0;ON;;;;;N;;;;; +2EB6;CJK RADICAL SHEEP;So;0;ON;;;;;N;;;;; +2EB7;CJK RADICAL RAM;So;0;ON;;;;;N;;;;; +2EB8;CJK RADICAL EWE;So;0;ON;;;;;N;;;;; +2EB9;CJK RADICAL OLD;So;0;ON;;;;;N;;;;; +2EBA;CJK RADICAL BRUSH ONE;So;0;ON;;;;;N;;;;; +2EBB;CJK RADICAL BRUSH TWO;So;0;ON;;;;;N;;;;; +2EBC;CJK RADICAL MEAT;So;0;ON;;;;;N;;;;; +2EBD;CJK RADICAL MORTAR;So;0;ON;;;;;N;;;;; +2EBE;CJK RADICAL GRASS ONE;So;0;ON;;;;;N;;;;; +2EBF;CJK RADICAL GRASS TWO;So;0;ON;;;;;N;;;;; +2EC0;CJK RADICAL GRASS THREE;So;0;ON;;;;;N;;;;; +2EC1;CJK RADICAL TIGER;So;0;ON;;;;;N;;;;; +2EC2;CJK RADICAL CLOTHES;So;0;ON;;;;;N;;;;; +2EC3;CJK RADICAL WEST ONE;So;0;ON;;;;;N;;;;; +2EC4;CJK RADICAL WEST TWO;So;0;ON;;;;;N;;;;; +2EC5;CJK RADICAL C-SIMPLIFIED SEE;So;0;ON;;;;;N;;;;; +2EC6;CJK RADICAL SIMPLIFIED HORN;So;0;ON;;;;;N;;;;; +2EC7;CJK RADICAL HORN;So;0;ON;;;;;N;;;;; +2EC8;CJK RADICAL C-SIMPLIFIED SPEECH;So;0;ON;;;;;N;;;;; +2EC9;CJK RADICAL C-SIMPLIFIED SHELL;So;0;ON;;;;;N;;;;; +2ECA;CJK RADICAL FOOT;So;0;ON;;;;;N;;;;; +2ECB;CJK RADICAL C-SIMPLIFIED CART;So;0;ON;;;;;N;;;;; +2ECC;CJK RADICAL SIMPLIFIED WALK;So;0;ON;;;;;N;;;;; +2ECD;CJK RADICAL WALK ONE;So;0;ON;;;;;N;;;;; +2ECE;CJK RADICAL WALK TWO;So;0;ON;;;;;N;;;;; +2ECF;CJK RADICAL CITY;So;0;ON;;;;;N;;;;; +2ED0;CJK RADICAL C-SIMPLIFIED GOLD;So;0;ON;;;;;N;;;;; +2ED1;CJK RADICAL LONG ONE;So;0;ON;;;;;N;;;;; +2ED2;CJK RADICAL LONG TWO;So;0;ON;;;;;N;;;;; +2ED3;CJK RADICAL C-SIMPLIFIED LONG;So;0;ON;;;;;N;;;;; +2ED4;CJK RADICAL C-SIMPLIFIED GATE;So;0;ON;;;;;N;;;;; +2ED5;CJK RADICAL MOUND ONE;So;0;ON;;;;;N;;;;; +2ED6;CJK RADICAL MOUND TWO;So;0;ON;;;;;N;;;;; +2ED7;CJK RADICAL RAIN;So;0;ON;;;;;N;;;;; +2ED8;CJK RADICAL BLUE;So;0;ON;;;;;N;;;;; +2ED9;CJK RADICAL C-SIMPLIFIED TANNED LEATHER;So;0;ON;;;;;N;;;;; +2EDA;CJK RADICAL C-SIMPLIFIED LEAF;So;0;ON;;;;;N;;;;; +2EDB;CJK RADICAL C-SIMPLIFIED WIND;So;0;ON;;;;;N;;;;; +2EDC;CJK RADICAL C-SIMPLIFIED FLY;So;0;ON;;;;;N;;;;; +2EDD;CJK RADICAL EAT ONE;So;0;ON;;;;;N;;;;; +2EDE;CJK RADICAL EAT TWO;So;0;ON;;;;;N;;;;; +2EDF;CJK RADICAL EAT THREE;So;0;ON;;;;;N;;;;; +2EE0;CJK RADICAL C-SIMPLIFIED EAT;So;0;ON;;;;;N;;;;; +2EE1;CJK RADICAL HEAD;So;0;ON;;;;;N;;;;; +2EE2;CJK RADICAL C-SIMPLIFIED HORSE;So;0;ON;;;;;N;;;;; +2EE3;CJK RADICAL BONE;So;0;ON;;;;;N;;;;; +2EE4;CJK RADICAL GHOST;So;0;ON;;;;;N;;;;; +2EE5;CJK RADICAL C-SIMPLIFIED FISH;So;0;ON;;;;;N;;;;; +2EE6;CJK RADICAL C-SIMPLIFIED BIRD;So;0;ON;;;;;N;;;;; +2EE7;CJK RADICAL C-SIMPLIFIED SALT;So;0;ON;;;;;N;;;;; +2EE8;CJK RADICAL SIMPLIFIED WHEAT;So;0;ON;;;;;N;;;;; +2EE9;CJK RADICAL SIMPLIFIED YELLOW;So;0;ON;;;;;N;;;;; +2EEA;CJK RADICAL C-SIMPLIFIED FROG;So;0;ON;;;;;N;;;;; +2EEB;CJK RADICAL J-SIMPLIFIED EVEN;So;0;ON;;;;;N;;;;; +2EEC;CJK RADICAL C-SIMPLIFIED EVEN;So;0;ON;;;;;N;;;;; +2EED;CJK RADICAL J-SIMPLIFIED TOOTH;So;0;ON;;;;;N;;;;; +2EEE;CJK RADICAL C-SIMPLIFIED TOOTH;So;0;ON;;;;;N;;;;; +2EEF;CJK RADICAL J-SIMPLIFIED DRAGON;So;0;ON;;;;;N;;;;; +2EF0;CJK RADICAL C-SIMPLIFIED DRAGON;So;0;ON;;;;;N;;;;; +2EF1;CJK RADICAL TURTLE;So;0;ON;;;;;N;;;;; +2EF2;CJK RADICAL J-SIMPLIFIED TURTLE;So;0;ON;;;;;N;;;;; +2EF3;CJK RADICAL C-SIMPLIFIED TURTLE;So;0;ON; 9F9F;;;;N;;;;; +2F00;KANGXI RADICAL ONE;So;0;ON; 4E00;;;;N;;;;; +2F01;KANGXI RADICAL LINE;So;0;ON; 4E28;;;;N;;;;; +2F02;KANGXI RADICAL DOT;So;0;ON; 4E36;;;;N;;;;; +2F03;KANGXI RADICAL SLASH;So;0;ON; 4E3F;;;;N;;;;; +2F04;KANGXI RADICAL SECOND;So;0;ON; 4E59;;;;N;;;;; +2F05;KANGXI RADICAL HOOK;So;0;ON; 4E85;;;;N;;;;; +2F06;KANGXI RADICAL TWO;So;0;ON; 4E8C;;;;N;;;;; +2F07;KANGXI RADICAL LID;So;0;ON; 4EA0;;;;N;;;;; +2F08;KANGXI RADICAL MAN;So;0;ON; 4EBA;;;;N;;;;; +2F09;KANGXI RADICAL LEGS;So;0;ON; 513F;;;;N;;;;; +2F0A;KANGXI RADICAL ENTER;So;0;ON; 5165;;;;N;;;;; +2F0B;KANGXI RADICAL EIGHT;So;0;ON; 516B;;;;N;;;;; +2F0C;KANGXI RADICAL DOWN BOX;So;0;ON; 5182;;;;N;;;;; +2F0D;KANGXI RADICAL COVER;So;0;ON; 5196;;;;N;;;;; +2F0E;KANGXI RADICAL ICE;So;0;ON; 51AB;;;;N;;;;; +2F0F;KANGXI RADICAL TABLE;So;0;ON; 51E0;;;;N;;;;; +2F10;KANGXI RADICAL OPEN BOX;So;0;ON; 51F5;;;;N;;;;; +2F11;KANGXI RADICAL KNIFE;So;0;ON; 5200;;;;N;;;;; +2F12;KANGXI RADICAL POWER;So;0;ON; 529B;;;;N;;;;; +2F13;KANGXI RADICAL WRAP;So;0;ON; 52F9;;;;N;;;;; +2F14;KANGXI RADICAL SPOON;So;0;ON; 5315;;;;N;;;;; +2F15;KANGXI RADICAL RIGHT OPEN BOX;So;0;ON; 531A;;;;N;;;;; +2F16;KANGXI RADICAL HIDING ENCLOSURE;So;0;ON; 5338;;;;N;;;;; +2F17;KANGXI RADICAL TEN;So;0;ON; 5341;;;;N;;;;; +2F18;KANGXI RADICAL DIVINATION;So;0;ON; 535C;;;;N;;;;; +2F19;KANGXI RADICAL SEAL;So;0;ON; 5369;;;;N;;;;; +2F1A;KANGXI RADICAL CLIFF;So;0;ON; 5382;;;;N;;;;; +2F1B;KANGXI RADICAL PRIVATE;So;0;ON; 53B6;;;;N;;;;; +2F1C;KANGXI RADICAL AGAIN;So;0;ON; 53C8;;;;N;;;;; +2F1D;KANGXI RADICAL MOUTH;So;0;ON; 53E3;;;;N;;;;; +2F1E;KANGXI RADICAL ENCLOSURE;So;0;ON; 56D7;;;;N;;;;; +2F1F;KANGXI RADICAL EARTH;So;0;ON; 571F;;;;N;;;;; +2F20;KANGXI RADICAL SCHOLAR;So;0;ON; 58EB;;;;N;;;;; +2F21;KANGXI RADICAL GO;So;0;ON; 5902;;;;N;;;;; +2F22;KANGXI RADICAL GO SLOWLY;So;0;ON; 590A;;;;N;;;;; +2F23;KANGXI RADICAL EVENING;So;0;ON; 5915;;;;N;;;;; +2F24;KANGXI RADICAL BIG;So;0;ON; 5927;;;;N;;;;; +2F25;KANGXI RADICAL WOMAN;So;0;ON; 5973;;;;N;;;;; +2F26;KANGXI RADICAL CHILD;So;0;ON; 5B50;;;;N;;;;; +2F27;KANGXI RADICAL ROOF;So;0;ON; 5B80;;;;N;;;;; +2F28;KANGXI RADICAL INCH;So;0;ON; 5BF8;;;;N;;;;; +2F29;KANGXI RADICAL SMALL;So;0;ON; 5C0F;;;;N;;;;; +2F2A;KANGXI RADICAL LAME;So;0;ON; 5C22;;;;N;;;;; +2F2B;KANGXI RADICAL CORPSE;So;0;ON; 5C38;;;;N;;;;; +2F2C;KANGXI RADICAL SPROUT;So;0;ON; 5C6E;;;;N;;;;; +2F2D;KANGXI RADICAL MOUNTAIN;So;0;ON; 5C71;;;;N;;;;; +2F2E;KANGXI RADICAL RIVER;So;0;ON; 5DDB;;;;N;;;;; +2F2F;KANGXI RADICAL WORK;So;0;ON; 5DE5;;;;N;;;;; +2F30;KANGXI RADICAL ONESELF;So;0;ON; 5DF1;;;;N;;;;; +2F31;KANGXI RADICAL TURBAN;So;0;ON; 5DFE;;;;N;;;;; +2F32;KANGXI RADICAL DRY;So;0;ON; 5E72;;;;N;;;;; +2F33;KANGXI RADICAL SHORT THREAD;So;0;ON; 5E7A;;;;N;;;;; +2F34;KANGXI RADICAL DOTTED CLIFF;So;0;ON; 5E7F;;;;N;;;;; +2F35;KANGXI RADICAL LONG STRIDE;So;0;ON; 5EF4;;;;N;;;;; +2F36;KANGXI RADICAL TWO HANDS;So;0;ON; 5EFE;;;;N;;;;; +2F37;KANGXI RADICAL SHOOT;So;0;ON; 5F0B;;;;N;;;;; +2F38;KANGXI RADICAL BOW;So;0;ON; 5F13;;;;N;;;;; +2F39;KANGXI RADICAL SNOUT;So;0;ON; 5F50;;;;N;;;;; +2F3A;KANGXI RADICAL BRISTLE;So;0;ON; 5F61;;;;N;;;;; +2F3B;KANGXI RADICAL STEP;So;0;ON; 5F73;;;;N;;;;; +2F3C;KANGXI RADICAL HEART;So;0;ON; 5FC3;;;;N;;;;; +2F3D;KANGXI RADICAL HALBERD;So;0;ON; 6208;;;;N;;;;; +2F3E;KANGXI RADICAL DOOR;So;0;ON; 6236;;;;N;;;;; +2F3F;KANGXI RADICAL HAND;So;0;ON; 624B;;;;N;;;;; +2F40;KANGXI RADICAL BRANCH;So;0;ON; 652F;;;;N;;;;; +2F41;KANGXI RADICAL RAP;So;0;ON; 6534;;;;N;;;;; +2F42;KANGXI RADICAL SCRIPT;So;0;ON; 6587;;;;N;;;;; +2F43;KANGXI RADICAL DIPPER;So;0;ON; 6597;;;;N;;;;; +2F44;KANGXI RADICAL AXE;So;0;ON; 65A4;;;;N;;;;; +2F45;KANGXI RADICAL SQUARE;So;0;ON; 65B9;;;;N;;;;; +2F46;KANGXI RADICAL NOT;So;0;ON; 65E0;;;;N;;;;; +2F47;KANGXI RADICAL SUN;So;0;ON; 65E5;;;;N;;;;; +2F48;KANGXI RADICAL SAY;So;0;ON; 66F0;;;;N;;;;; +2F49;KANGXI RADICAL MOON;So;0;ON; 6708;;;;N;;;;; +2F4A;KANGXI RADICAL TREE;So;0;ON; 6728;;;;N;;;;; +2F4B;KANGXI RADICAL LACK;So;0;ON; 6B20;;;;N;;;;; +2F4C;KANGXI RADICAL STOP;So;0;ON; 6B62;;;;N;;;;; +2F4D;KANGXI RADICAL DEATH;So;0;ON; 6B79;;;;N;;;;; +2F4E;KANGXI RADICAL WEAPON;So;0;ON; 6BB3;;;;N;;;;; +2F4F;KANGXI RADICAL DO NOT;So;0;ON; 6BCB;;;;N;;;;; +2F50;KANGXI RADICAL COMPARE;So;0;ON; 6BD4;;;;N;;;;; +2F51;KANGXI RADICAL FUR;So;0;ON; 6BDB;;;;N;;;;; +2F52;KANGXI RADICAL CLAN;So;0;ON; 6C0F;;;;N;;;;; +2F53;KANGXI RADICAL STEAM;So;0;ON; 6C14;;;;N;;;;; +2F54;KANGXI RADICAL WATER;So;0;ON; 6C34;;;;N;;;;; +2F55;KANGXI RADICAL FIRE;So;0;ON; 706B;;;;N;;;;; +2F56;KANGXI RADICAL CLAW;So;0;ON; 722A;;;;N;;;;; +2F57;KANGXI RADICAL FATHER;So;0;ON; 7236;;;;N;;;;; +2F58;KANGXI RADICAL DOUBLE X;So;0;ON; 723B;;;;N;;;;; +2F59;KANGXI RADICAL HALF TREE TRUNK;So;0;ON; 723F;;;;N;;;;; +2F5A;KANGXI RADICAL SLICE;So;0;ON; 7247;;;;N;;;;; +2F5B;KANGXI RADICAL FANG;So;0;ON; 7259;;;;N;;;;; +2F5C;KANGXI RADICAL COW;So;0;ON; 725B;;;;N;;;;; +2F5D;KANGXI RADICAL DOG;So;0;ON; 72AC;;;;N;;;;; +2F5E;KANGXI RADICAL PROFOUND;So;0;ON; 7384;;;;N;;;;; +2F5F;KANGXI RADICAL JADE;So;0;ON; 7389;;;;N;;;;; +2F60;KANGXI RADICAL MELON;So;0;ON; 74DC;;;;N;;;;; +2F61;KANGXI RADICAL TILE;So;0;ON; 74E6;;;;N;;;;; +2F62;KANGXI RADICAL SWEET;So;0;ON; 7518;;;;N;;;;; +2F63;KANGXI RADICAL LIFE;So;0;ON; 751F;;;;N;;;;; +2F64;KANGXI RADICAL USE;So;0;ON; 7528;;;;N;;;;; +2F65;KANGXI RADICAL FIELD;So;0;ON; 7530;;;;N;;;;; +2F66;KANGXI RADICAL BOLT OF CLOTH;So;0;ON; 758B;;;;N;;;;; +2F67;KANGXI RADICAL SICKNESS;So;0;ON; 7592;;;;N;;;;; +2F68;KANGXI RADICAL DOTTED TENT;So;0;ON; 7676;;;;N;;;;; +2F69;KANGXI RADICAL WHITE;So;0;ON; 767D;;;;N;;;;; +2F6A;KANGXI RADICAL SKIN;So;0;ON; 76AE;;;;N;;;;; +2F6B;KANGXI RADICAL DISH;So;0;ON; 76BF;;;;N;;;;; +2F6C;KANGXI RADICAL EYE;So;0;ON; 76EE;;;;N;;;;; +2F6D;KANGXI RADICAL SPEAR;So;0;ON; 77DB;;;;N;;;;; +2F6E;KANGXI RADICAL ARROW;So;0;ON; 77E2;;;;N;;;;; +2F6F;KANGXI RADICAL STONE;So;0;ON; 77F3;;;;N;;;;; +2F70;KANGXI RADICAL SPIRIT;So;0;ON; 793A;;;;N;;;;; +2F71;KANGXI RADICAL TRACK;So;0;ON; 79B8;;;;N;;;;; +2F72;KANGXI RADICAL GRAIN;So;0;ON; 79BE;;;;N;;;;; +2F73;KANGXI RADICAL CAVE;So;0;ON; 7A74;;;;N;;;;; +2F74;KANGXI RADICAL STAND;So;0;ON; 7ACB;;;;N;;;;; +2F75;KANGXI RADICAL BAMBOO;So;0;ON; 7AF9;;;;N;;;;; +2F76;KANGXI RADICAL RICE;So;0;ON; 7C73;;;;N;;;;; +2F77;KANGXI RADICAL SILK;So;0;ON; 7CF8;;;;N;;;;; +2F78;KANGXI RADICAL JAR;So;0;ON; 7F36;;;;N;;;;; +2F79;KANGXI RADICAL NET;So;0;ON; 7F51;;;;N;;;;; +2F7A;KANGXI RADICAL SHEEP;So;0;ON; 7F8A;;;;N;;;;; +2F7B;KANGXI RADICAL FEATHER;So;0;ON; 7FBD;;;;N;;;;; +2F7C;KANGXI RADICAL OLD;So;0;ON; 8001;;;;N;;;;; +2F7D;KANGXI RADICAL AND;So;0;ON; 800C;;;;N;;;;; +2F7E;KANGXI RADICAL PLOW;So;0;ON; 8012;;;;N;;;;; +2F7F;KANGXI RADICAL EAR;So;0;ON; 8033;;;;N;;;;; +2F80;KANGXI RADICAL BRUSH;So;0;ON; 807F;;;;N;;;;; +2F81;KANGXI RADICAL MEAT;So;0;ON; 8089;;;;N;;;;; +2F82;KANGXI RADICAL MINISTER;So;0;ON; 81E3;;;;N;;;;; +2F83;KANGXI RADICAL SELF;So;0;ON; 81EA;;;;N;;;;; +2F84;KANGXI RADICAL ARRIVE;So;0;ON; 81F3;;;;N;;;;; +2F85;KANGXI RADICAL MORTAR;So;0;ON; 81FC;;;;N;;;;; +2F86;KANGXI RADICAL TONGUE;So;0;ON; 820C;;;;N;;;;; +2F87;KANGXI RADICAL OPPOSE;So;0;ON; 821B;;;;N;;;;; +2F88;KANGXI RADICAL BOAT;So;0;ON; 821F;;;;N;;;;; +2F89;KANGXI RADICAL STOPPING;So;0;ON; 826E;;;;N;;;;; +2F8A;KANGXI RADICAL COLOR;So;0;ON; 8272;;;;N;;;;; +2F8B;KANGXI RADICAL GRASS;So;0;ON; 8278;;;;N;;;;; +2F8C;KANGXI RADICAL TIGER;So;0;ON; 864D;;;;N;;;;; +2F8D;KANGXI RADICAL INSECT;So;0;ON; 866B;;;;N;;;;; +2F8E;KANGXI RADICAL BLOOD;So;0;ON; 8840;;;;N;;;;; +2F8F;KANGXI RADICAL WALK ENCLOSURE;So;0;ON; 884C;;;;N;;;;; +2F90;KANGXI RADICAL CLOTHES;So;0;ON; 8863;;;;N;;;;; +2F91;KANGXI RADICAL WEST;So;0;ON; 897E;;;;N;;;;; +2F92;KANGXI RADICAL SEE;So;0;ON; 898B;;;;N;;;;; +2F93;KANGXI RADICAL HORN;So;0;ON; 89D2;;;;N;;;;; +2F94;KANGXI RADICAL SPEECH;So;0;ON; 8A00;;;;N;;;;; +2F95;KANGXI RADICAL VALLEY;So;0;ON; 8C37;;;;N;;;;; +2F96;KANGXI RADICAL BEAN;So;0;ON; 8C46;;;;N;;;;; +2F97;KANGXI RADICAL PIG;So;0;ON; 8C55;;;;N;;;;; +2F98;KANGXI RADICAL BADGER;So;0;ON; 8C78;;;;N;;;;; +2F99;KANGXI RADICAL SHELL;So;0;ON; 8C9D;;;;N;;;;; +2F9A;KANGXI RADICAL RED;So;0;ON; 8D64;;;;N;;;;; +2F9B;KANGXI RADICAL RUN;So;0;ON; 8D70;;;;N;;;;; +2F9C;KANGXI RADICAL FOOT;So;0;ON; 8DB3;;;;N;;;;; +2F9D;KANGXI RADICAL BODY;So;0;ON; 8EAB;;;;N;;;;; +2F9E;KANGXI RADICAL CART;So;0;ON; 8ECA;;;;N;;;;; +2F9F;KANGXI RADICAL BITTER;So;0;ON; 8F9B;;;;N;;;;; +2FA0;KANGXI RADICAL MORNING;So;0;ON; 8FB0;;;;N;;;;; +2FA1;KANGXI RADICAL WALK;So;0;ON; 8FB5;;;;N;;;;; +2FA2;KANGXI RADICAL CITY;So;0;ON; 9091;;;;N;;;;; +2FA3;KANGXI RADICAL WINE;So;0;ON; 9149;;;;N;;;;; +2FA4;KANGXI RADICAL DISTINGUISH;So;0;ON; 91C6;;;;N;;;;; +2FA5;KANGXI RADICAL VILLAGE;So;0;ON; 91CC;;;;N;;;;; +2FA6;KANGXI RADICAL GOLD;So;0;ON; 91D1;;;;N;;;;; +2FA7;KANGXI RADICAL LONG;So;0;ON; 9577;;;;N;;;;; +2FA8;KANGXI RADICAL GATE;So;0;ON; 9580;;;;N;;;;; +2FA9;KANGXI RADICAL MOUND;So;0;ON; 961C;;;;N;;;;; +2FAA;KANGXI RADICAL SLAVE;So;0;ON; 96B6;;;;N;;;;; +2FAB;KANGXI RADICAL SHORT TAILED BIRD;So;0;ON; 96B9;;;;N;;;;; +2FAC;KANGXI RADICAL RAIN;So;0;ON; 96E8;;;;N;;;;; +2FAD;KANGXI RADICAL BLUE;So;0;ON; 9751;;;;N;;;;; +2FAE;KANGXI RADICAL WRONG;So;0;ON; 975E;;;;N;;;;; +2FAF;KANGXI RADICAL FACE;So;0;ON; 9762;;;;N;;;;; +2FB0;KANGXI RADICAL LEATHER;So;0;ON; 9769;;;;N;;;;; +2FB1;KANGXI RADICAL TANNED LEATHER;So;0;ON; 97CB;;;;N;;;;; +2FB2;KANGXI RADICAL LEEK;So;0;ON; 97ED;;;;N;;;;; +2FB3;KANGXI RADICAL SOUND;So;0;ON; 97F3;;;;N;;;;; +2FB4;KANGXI RADICAL LEAF;So;0;ON; 9801;;;;N;;;;; +2FB5;KANGXI RADICAL WIND;So;0;ON; 98A8;;;;N;;;;; +2FB6;KANGXI RADICAL FLY;So;0;ON; 98DB;;;;N;;;;; +2FB7;KANGXI RADICAL EAT;So;0;ON; 98DF;;;;N;;;;; +2FB8;KANGXI RADICAL HEAD;So;0;ON; 9996;;;;N;;;;; +2FB9;KANGXI RADICAL FRAGRANT;So;0;ON; 9999;;;;N;;;;; +2FBA;KANGXI RADICAL HORSE;So;0;ON; 99AC;;;;N;;;;; +2FBB;KANGXI RADICAL BONE;So;0;ON; 9AA8;;;;N;;;;; +2FBC;KANGXI RADICAL TALL;So;0;ON; 9AD8;;;;N;;;;; +2FBD;KANGXI RADICAL HAIR;So;0;ON; 9ADF;;;;N;;;;; +2FBE;KANGXI RADICAL FIGHT;So;0;ON; 9B25;;;;N;;;;; +2FBF;KANGXI RADICAL SACRIFICIAL WINE;So;0;ON; 9B2F;;;;N;;;;; +2FC0;KANGXI RADICAL CAULDRON;So;0;ON; 9B32;;;;N;;;;; +2FC1;KANGXI RADICAL GHOST;So;0;ON; 9B3C;;;;N;;;;; +2FC2;KANGXI RADICAL FISH;So;0;ON; 9B5A;;;;N;;;;; +2FC3;KANGXI RADICAL BIRD;So;0;ON; 9CE5;;;;N;;;;; +2FC4;KANGXI RADICAL SALT;So;0;ON; 9E75;;;;N;;;;; +2FC5;KANGXI RADICAL DEER;So;0;ON; 9E7F;;;;N;;;;; +2FC6;KANGXI RADICAL WHEAT;So;0;ON; 9EA5;;;;N;;;;; +2FC7;KANGXI RADICAL HEMP;So;0;ON; 9EBB;;;;N;;;;; +2FC8;KANGXI RADICAL YELLOW;So;0;ON; 9EC3;;;;N;;;;; +2FC9;KANGXI RADICAL MILLET;So;0;ON; 9ECD;;;;N;;;;; +2FCA;KANGXI RADICAL BLACK;So;0;ON; 9ED1;;;;N;;;;; +2FCB;KANGXI RADICAL EMBROIDERY;So;0;ON; 9EF9;;;;N;;;;; +2FCC;KANGXI RADICAL FROG;So;0;ON; 9EFD;;;;N;;;;; +2FCD;KANGXI RADICAL TRIPOD;So;0;ON; 9F0E;;;;N;;;;; +2FCE;KANGXI RADICAL DRUM;So;0;ON; 9F13;;;;N;;;;; +2FCF;KANGXI RADICAL RAT;So;0;ON; 9F20;;;;N;;;;; +2FD0;KANGXI RADICAL NOSE;So;0;ON; 9F3B;;;;N;;;;; +2FD1;KANGXI RADICAL EVEN;So;0;ON; 9F4A;;;;N;;;;; +2FD2;KANGXI RADICAL TOOTH;So;0;ON; 9F52;;;;N;;;;; +2FD3;KANGXI RADICAL DRAGON;So;0;ON; 9F8D;;;;N;;;;; +2FD4;KANGXI RADICAL TURTLE;So;0;ON; 9F9C;;;;N;;;;; +2FD5;KANGXI RADICAL FLUTE;So;0;ON; 9FA0;;;;N;;;;; +2FF0;IDEOGRAPHIC DESCRIPTION CHARACTER LEFT TO RIGHT;So;0;ON;;;;;N;;;;; +2FF1;IDEOGRAPHIC DESCRIPTION CHARACTER ABOVE TO BELOW;So;0;ON;;;;;N;;;;; +2FF2;IDEOGRAPHIC DESCRIPTION CHARACTER LEFT TO MIDDLE AND RIGHT;So;0;ON;;;;;N;;;;; +2FF3;IDEOGRAPHIC DESCRIPTION CHARACTER ABOVE TO MIDDLE AND BELOW;So;0;ON;;;;;N;;;;; +2FF4;IDEOGRAPHIC DESCRIPTION CHARACTER FULL SURROUND;So;0;ON;;;;;N;;;;; +2FF5;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM ABOVE;So;0;ON;;;;;N;;;;; +2FF6;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM BELOW;So;0;ON;;;;;N;;;;; +2FF7;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM LEFT;So;0;ON;;;;;N;;;;; +2FF8;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM UPPER LEFT;So;0;ON;;;;;N;;;;; +2FF9;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM UPPER RIGHT;So;0;ON;;;;;N;;;;; +2FFA;IDEOGRAPHIC DESCRIPTION CHARACTER SURROUND FROM LOWER LEFT;So;0;ON;;;;;N;;;;; +2FFB;IDEOGRAPHIC DESCRIPTION CHARACTER OVERLAID;So;0;ON;;;;;N;;;;; +3000;IDEOGRAPHIC SPACE;Zs;0;WS; 0020;;;;N;;;;; +3001;IDEOGRAPHIC COMMA;Po;0;ON;;;;;N;;;;; +3002;IDEOGRAPHIC FULL STOP;Po;0;ON;;;;;N;IDEOGRAPHIC PERIOD;;;; +3003;DITTO MARK;Po;0;ON;;;;;N;;;;; +3004;JAPANESE INDUSTRIAL STANDARD SYMBOL;So;0;ON;;;;;N;;;;; +3005;IDEOGRAPHIC ITERATION MARK;Lm;0;L;;;;;N;;;;; +3006;IDEOGRAPHIC CLOSING MARK;Lo;0;L;;;;;N;;;;; +3007;IDEOGRAPHIC NUMBER ZERO;Nl;0;L;;;;0;N;;;;; +3008;LEFT ANGLE BRACKET;Ps;0;ON;;;;;Y;OPENING ANGLE BRACKET;;;; +3009;RIGHT ANGLE BRACKET;Pe;0;ON;;;;;Y;CLOSING ANGLE BRACKET;;;; +300A;LEFT DOUBLE ANGLE BRACKET;Ps;0;ON;;;;;Y;OPENING DOUBLE ANGLE BRACKET;;;; +300B;RIGHT DOUBLE ANGLE BRACKET;Pe;0;ON;;;;;Y;CLOSING DOUBLE ANGLE BRACKET;;;; +300C;LEFT CORNER BRACKET;Ps;0;ON;;;;;Y;OPENING CORNER BRACKET;;;; +300D;RIGHT CORNER BRACKET;Pe;0;ON;;;;;Y;CLOSING CORNER BRACKET;;;; +300E;LEFT WHITE CORNER BRACKET;Ps;0;ON;;;;;Y;OPENING WHITE CORNER BRACKET;;;; +300F;RIGHT WHITE CORNER BRACKET;Pe;0;ON;;;;;Y;CLOSING WHITE CORNER BRACKET;;;; +3010;LEFT BLACK LENTICULAR BRACKET;Ps;0;ON;;;;;Y;OPENING BLACK LENTICULAR BRACKET;;;; +3011;RIGHT BLACK LENTICULAR BRACKET;Pe;0;ON;;;;;Y;CLOSING BLACK LENTICULAR BRACKET;;;; +3012;POSTAL MARK;So;0;ON;;;;;N;;;;; +3013;GETA MARK;So;0;ON;;;;;N;;;;; +3014;LEFT TORTOISE SHELL BRACKET;Ps;0;ON;;;;;Y;OPENING TORTOISE SHELL BRACKET;;;; +3015;RIGHT TORTOISE SHELL BRACKET;Pe;0;ON;;;;;Y;CLOSING TORTOISE SHELL BRACKET;;;; +3016;LEFT WHITE LENTICULAR BRACKET;Ps;0;ON;;;;;Y;OPENING WHITE LENTICULAR BRACKET;;;; +3017;RIGHT WHITE LENTICULAR BRACKET;Pe;0;ON;;;;;Y;CLOSING WHITE LENTICULAR BRACKET;;;; +3018;LEFT WHITE TORTOISE SHELL BRACKET;Ps;0;ON;;;;;Y;OPENING WHITE TORTOISE SHELL BRACKET;;;; +3019;RIGHT WHITE TORTOISE SHELL BRACKET;Pe;0;ON;;;;;Y;CLOSING WHITE TORTOISE SHELL BRACKET;;;; +301A;LEFT WHITE SQUARE BRACKET;Ps;0;ON;;;;;Y;OPENING WHITE SQUARE BRACKET;;;; +301B;RIGHT WHITE SQUARE BRACKET;Pe;0;ON;;;;;Y;CLOSING WHITE SQUARE BRACKET;;;; +301C;WAVE DASH;Pd;0;ON;;;;;N;;;;; +301D;REVERSED DOUBLE PRIME QUOTATION MARK;Ps;0;ON;;;;;N;;;;; +301E;DOUBLE PRIME QUOTATION MARK;Pe;0;ON;;;;;N;;;;; +301F;LOW DOUBLE PRIME QUOTATION MARK;Pe;0;ON;;;;;N;;;;; +3020;POSTAL MARK FACE;So;0;ON;;;;;N;;;;; +3021;HANGZHOU NUMERAL ONE;Nl;0;L;;;;1;N;;;;; +3022;HANGZHOU NUMERAL TWO;Nl;0;L;;;;2;N;;;;; +3023;HANGZHOU NUMERAL THREE;Nl;0;L;;;;3;N;;;;; +3024;HANGZHOU NUMERAL FOUR;Nl;0;L;;;;4;N;;;;; +3025;HANGZHOU NUMERAL FIVE;Nl;0;L;;;;5;N;;;;; +3026;HANGZHOU NUMERAL SIX;Nl;0;L;;;;6;N;;;;; +3027;HANGZHOU NUMERAL SEVEN;Nl;0;L;;;;7;N;;;;; +3028;HANGZHOU NUMERAL EIGHT;Nl;0;L;;;;8;N;;;;; +3029;HANGZHOU NUMERAL NINE;Nl;0;L;;;;9;N;;;;; +302A;IDEOGRAPHIC LEVEL TONE MARK;Mn;218;NSM;;;;;N;;;;; +302B;IDEOGRAPHIC RISING TONE MARK;Mn;228;NSM;;;;;N;;;;; +302C;IDEOGRAPHIC DEPARTING TONE MARK;Mn;232;NSM;;;;;N;;;;; +302D;IDEOGRAPHIC ENTERING TONE MARK;Mn;222;NSM;;;;;N;;;;; +302E;HANGUL SINGLE DOT TONE MARK;Mc;224;L;;;;;N;;;;; +302F;HANGUL DOUBLE DOT TONE MARK;Mc;224;L;;;;;N;;;;; +3030;WAVY DASH;Pd;0;ON;;;;;N;;;;; +3031;VERTICAL KANA REPEAT MARK;Lm;0;L;;;;;N;;;;; +3032;VERTICAL KANA REPEAT WITH VOICED SOUND MARK;Lm;0;L;;;;;N;;;;; +3033;VERTICAL KANA REPEAT MARK UPPER HALF;Lm;0;L;;;;;N;;;;; +3034;VERTICAL KANA REPEAT WITH VOICED SOUND MARK UPPER HALF;Lm;0;L;;;;;N;;;;; +3035;VERTICAL KANA REPEAT MARK LOWER HALF;Lm;0;L;;;;;N;;;;; +3036;CIRCLED POSTAL MARK;So;0;ON; 3012;;;;N;;;;; +3037;IDEOGRAPHIC TELEGRAPH LINE FEED SEPARATOR SYMBOL;So;0;ON;;;;;N;;;;; +3038;HANGZHOU NUMERAL TEN;Nl;0;L; 5341;;;10;N;;;;; +3039;HANGZHOU NUMERAL TWENTY;Nl;0;L; 5344;;;20;N;;;;; +303A;HANGZHOU NUMERAL THIRTY;Nl;0;L; 5345;;;30;N;;;;; +303B;VERTICAL IDEOGRAPHIC ITERATION MARK;Lm;0;L;;;;;N;;;;; +303C;MASU MARK;Lo;0;L;;;;;N;;;;; +303D;PART ALTERNATION MARK;Po;0;ON;;;;;N;;;;; +303E;IDEOGRAPHIC VARIATION INDICATOR;So;0;ON;;;;;N;;;;; +303F;IDEOGRAPHIC HALF FILL SPACE;So;0;ON;;;;;N;;;;; +3041;HIRAGANA LETTER SMALL A;Lo;0;L;;;;;N;;;;; +3042;HIRAGANA LETTER A;Lo;0;L;;;;;N;;;;; +3043;HIRAGANA LETTER SMALL I;Lo;0;L;;;;;N;;;;; +3044;HIRAGANA LETTER I;Lo;0;L;;;;;N;;;;; +3045;HIRAGANA LETTER SMALL U;Lo;0;L;;;;;N;;;;; +3046;HIRAGANA LETTER U;Lo;0;L;;;;;N;;;;; +3047;HIRAGANA LETTER SMALL E;Lo;0;L;;;;;N;;;;; +3048;HIRAGANA LETTER E;Lo;0;L;;;;;N;;;;; +3049;HIRAGANA LETTER SMALL O;Lo;0;L;;;;;N;;;;; +304A;HIRAGANA LETTER O;Lo;0;L;;;;;N;;;;; +304B;HIRAGANA LETTER KA;Lo;0;L;;;;;N;;;;; +304C;HIRAGANA LETTER GA;Lo;0;L;304B 3099;;;;N;;;;; +304D;HIRAGANA LETTER KI;Lo;0;L;;;;;N;;;;; +304E;HIRAGANA LETTER GI;Lo;0;L;304D 3099;;;;N;;;;; +304F;HIRAGANA LETTER KU;Lo;0;L;;;;;N;;;;; +3050;HIRAGANA LETTER GU;Lo;0;L;304F 3099;;;;N;;;;; +3051;HIRAGANA LETTER KE;Lo;0;L;;;;;N;;;;; +3052;HIRAGANA LETTER GE;Lo;0;L;3051 3099;;;;N;;;;; +3053;HIRAGANA LETTER KO;Lo;0;L;;;;;N;;;;; +3054;HIRAGANA LETTER GO;Lo;0;L;3053 3099;;;;N;;;;; +3055;HIRAGANA LETTER SA;Lo;0;L;;;;;N;;;;; +3056;HIRAGANA LETTER ZA;Lo;0;L;3055 3099;;;;N;;;;; +3057;HIRAGANA LETTER SI;Lo;0;L;;;;;N;;;;; +3058;HIRAGANA LETTER ZI;Lo;0;L;3057 3099;;;;N;;;;; +3059;HIRAGANA LETTER SU;Lo;0;L;;;;;N;;;;; +305A;HIRAGANA LETTER ZU;Lo;0;L;3059 3099;;;;N;;;;; +305B;HIRAGANA LETTER SE;Lo;0;L;;;;;N;;;;; +305C;HIRAGANA LETTER ZE;Lo;0;L;305B 3099;;;;N;;;;; +305D;HIRAGANA LETTER SO;Lo;0;L;;;;;N;;;;; +305E;HIRAGANA LETTER ZO;Lo;0;L;305D 3099;;;;N;;;;; +305F;HIRAGANA LETTER TA;Lo;0;L;;;;;N;;;;; +3060;HIRAGANA LETTER DA;Lo;0;L;305F 3099;;;;N;;;;; +3061;HIRAGANA LETTER TI;Lo;0;L;;;;;N;;;;; +3062;HIRAGANA LETTER DI;Lo;0;L;3061 3099;;;;N;;;;; +3063;HIRAGANA LETTER SMALL TU;Lo;0;L;;;;;N;;;;; +3064;HIRAGANA LETTER TU;Lo;0;L;;;;;N;;;;; +3065;HIRAGANA LETTER DU;Lo;0;L;3064 3099;;;;N;;;;; +3066;HIRAGANA LETTER TE;Lo;0;L;;;;;N;;;;; +3067;HIRAGANA LETTER DE;Lo;0;L;3066 3099;;;;N;;;;; +3068;HIRAGANA LETTER TO;Lo;0;L;;;;;N;;;;; +3069;HIRAGANA LETTER DO;Lo;0;L;3068 3099;;;;N;;;;; +306A;HIRAGANA LETTER NA;Lo;0;L;;;;;N;;;;; +306B;HIRAGANA LETTER NI;Lo;0;L;;;;;N;;;;; +306C;HIRAGANA LETTER NU;Lo;0;L;;;;;N;;;;; +306D;HIRAGANA LETTER NE;Lo;0;L;;;;;N;;;;; +306E;HIRAGANA LETTER NO;Lo;0;L;;;;;N;;;;; +306F;HIRAGANA LETTER HA;Lo;0;L;;;;;N;;;;; +3070;HIRAGANA LETTER BA;Lo;0;L;306F 3099;;;;N;;;;; +3071;HIRAGANA LETTER PA;Lo;0;L;306F 309A;;;;N;;;;; +3072;HIRAGANA LETTER HI;Lo;0;L;;;;;N;;;;; +3073;HIRAGANA LETTER BI;Lo;0;L;3072 3099;;;;N;;;;; +3074;HIRAGANA LETTER PI;Lo;0;L;3072 309A;;;;N;;;;; +3075;HIRAGANA LETTER HU;Lo;0;L;;;;;N;;;;; +3076;HIRAGANA LETTER BU;Lo;0;L;3075 3099;;;;N;;;;; +3077;HIRAGANA LETTER PU;Lo;0;L;3075 309A;;;;N;;;;; +3078;HIRAGANA LETTER HE;Lo;0;L;;;;;N;;;;; +3079;HIRAGANA LETTER BE;Lo;0;L;3078 3099;;;;N;;;;; +307A;HIRAGANA LETTER PE;Lo;0;L;3078 309A;;;;N;;;;; +307B;HIRAGANA LETTER HO;Lo;0;L;;;;;N;;;;; +307C;HIRAGANA LETTER BO;Lo;0;L;307B 3099;;;;N;;;;; +307D;HIRAGANA LETTER PO;Lo;0;L;307B 309A;;;;N;;;;; +307E;HIRAGANA LETTER MA;Lo;0;L;;;;;N;;;;; +307F;HIRAGANA LETTER MI;Lo;0;L;;;;;N;;;;; +3080;HIRAGANA LETTER MU;Lo;0;L;;;;;N;;;;; +3081;HIRAGANA LETTER ME;Lo;0;L;;;;;N;;;;; +3082;HIRAGANA LETTER MO;Lo;0;L;;;;;N;;;;; +3083;HIRAGANA LETTER SMALL YA;Lo;0;L;;;;;N;;;;; +3084;HIRAGANA LETTER YA;Lo;0;L;;;;;N;;;;; +3085;HIRAGANA LETTER SMALL YU;Lo;0;L;;;;;N;;;;; +3086;HIRAGANA LETTER YU;Lo;0;L;;;;;N;;;;; +3087;HIRAGANA LETTER SMALL YO;Lo;0;L;;;;;N;;;;; +3088;HIRAGANA LETTER YO;Lo;0;L;;;;;N;;;;; +3089;HIRAGANA LETTER RA;Lo;0;L;;;;;N;;;;; +308A;HIRAGANA LETTER RI;Lo;0;L;;;;;N;;;;; +308B;HIRAGANA LETTER RU;Lo;0;L;;;;;N;;;;; +308C;HIRAGANA LETTER RE;Lo;0;L;;;;;N;;;;; +308D;HIRAGANA LETTER RO;Lo;0;L;;;;;N;;;;; +308E;HIRAGANA LETTER SMALL WA;Lo;0;L;;;;;N;;;;; +308F;HIRAGANA LETTER WA;Lo;0;L;;;;;N;;;;; +3090;HIRAGANA LETTER WI;Lo;0;L;;;;;N;;;;; +3091;HIRAGANA LETTER WE;Lo;0;L;;;;;N;;;;; +3092;HIRAGANA LETTER WO;Lo;0;L;;;;;N;;;;; +3093;HIRAGANA LETTER N;Lo;0;L;;;;;N;;;;; +3094;HIRAGANA LETTER VU;Lo;0;L;3046 3099;;;;N;;;;; +3095;HIRAGANA LETTER SMALL KA;Lo;0;L;;;;;N;;;;; +3096;HIRAGANA LETTER SMALL KE;Lo;0;L;;;;;N;;;;; +3099;COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK;Mn;8;NSM;;;;;N;NON-SPACING KATAKANA-HIRAGANA VOICED SOUND MARK;;;; +309A;COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK;Mn;8;NSM;;;;;N;NON-SPACING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK;;;; +309B;KATAKANA-HIRAGANA VOICED SOUND MARK;Sk;0;ON; 0020 3099;;;;N;;;;; +309C;KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK;Sk;0;ON; 0020 309A;;;;N;;;;; +309D;HIRAGANA ITERATION MARK;Lm;0;L;;;;;N;;;;; +309E;HIRAGANA VOICED ITERATION MARK;Lm;0;L;309D 3099;;;;N;;;;; +309F;HIRAGANA DIGRAPH YORI;Lo;0;L; 3088 308A;;;;N;;;;; +30A0;KATAKANA-HIRAGANA DOUBLE HYPHEN;Pd;0;ON;;;;;N;;;;; +30A1;KATAKANA LETTER SMALL A;Lo;0;L;;;;;N;;;;; +30A2;KATAKANA LETTER A;Lo;0;L;;;;;N;;;;; +30A3;KATAKANA LETTER SMALL I;Lo;0;L;;;;;N;;;;; +30A4;KATAKANA LETTER I;Lo;0;L;;;;;N;;;;; +30A5;KATAKANA LETTER SMALL U;Lo;0;L;;;;;N;;;;; +30A6;KATAKANA LETTER U;Lo;0;L;;;;;N;;;;; +30A7;KATAKANA LETTER SMALL E;Lo;0;L;;;;;N;;;;; +30A8;KATAKANA LETTER E;Lo;0;L;;;;;N;;;;; +30A9;KATAKANA LETTER SMALL O;Lo;0;L;;;;;N;;;;; +30AA;KATAKANA LETTER O;Lo;0;L;;;;;N;;;;; +30AB;KATAKANA LETTER KA;Lo;0;L;;;;;N;;;;; +30AC;KATAKANA LETTER GA;Lo;0;L;30AB 3099;;;;N;;;;; +30AD;KATAKANA LETTER KI;Lo;0;L;;;;;N;;;;; +30AE;KATAKANA LETTER GI;Lo;0;L;30AD 3099;;;;N;;;;; +30AF;KATAKANA LETTER KU;Lo;0;L;;;;;N;;;;; +30B0;KATAKANA LETTER GU;Lo;0;L;30AF 3099;;;;N;;;;; +30B1;KATAKANA LETTER KE;Lo;0;L;;;;;N;;;;; +30B2;KATAKANA LETTER GE;Lo;0;L;30B1 3099;;;;N;;;;; +30B3;KATAKANA LETTER KO;Lo;0;L;;;;;N;;;;; +30B4;KATAKANA LETTER GO;Lo;0;L;30B3 3099;;;;N;;;;; +30B5;KATAKANA LETTER SA;Lo;0;L;;;;;N;;;;; +30B6;KATAKANA LETTER ZA;Lo;0;L;30B5 3099;;;;N;;;;; +30B7;KATAKANA LETTER SI;Lo;0;L;;;;;N;;;;; +30B8;KATAKANA LETTER ZI;Lo;0;L;30B7 3099;;;;N;;;;; +30B9;KATAKANA LETTER SU;Lo;0;L;;;;;N;;;;; +30BA;KATAKANA LETTER ZU;Lo;0;L;30B9 3099;;;;N;;;;; +30BB;KATAKANA LETTER SE;Lo;0;L;;;;;N;;;;; +30BC;KATAKANA LETTER ZE;Lo;0;L;30BB 3099;;;;N;;;;; +30BD;KATAKANA LETTER SO;Lo;0;L;;;;;N;;;;; +30BE;KATAKANA LETTER ZO;Lo;0;L;30BD 3099;;;;N;;;;; +30BF;KATAKANA LETTER TA;Lo;0;L;;;;;N;;;;; +30C0;KATAKANA LETTER DA;Lo;0;L;30BF 3099;;;;N;;;;; +30C1;KATAKANA LETTER TI;Lo;0;L;;;;;N;;;;; +30C2;KATAKANA LETTER DI;Lo;0;L;30C1 3099;;;;N;;;;; +30C3;KATAKANA LETTER SMALL TU;Lo;0;L;;;;;N;;;;; +30C4;KATAKANA LETTER TU;Lo;0;L;;;;;N;;;;; +30C5;KATAKANA LETTER DU;Lo;0;L;30C4 3099;;;;N;;;;; +30C6;KATAKANA LETTER TE;Lo;0;L;;;;;N;;;;; +30C7;KATAKANA LETTER DE;Lo;0;L;30C6 3099;;;;N;;;;; +30C8;KATAKANA LETTER TO;Lo;0;L;;;;;N;;;;; +30C9;KATAKANA LETTER DO;Lo;0;L;30C8 3099;;;;N;;;;; +30CA;KATAKANA LETTER NA;Lo;0;L;;;;;N;;;;; +30CB;KATAKANA LETTER NI;Lo;0;L;;;;;N;;;;; +30CC;KATAKANA LETTER NU;Lo;0;L;;;;;N;;;;; +30CD;KATAKANA LETTER NE;Lo;0;L;;;;;N;;;;; +30CE;KATAKANA LETTER NO;Lo;0;L;;;;;N;;;;; +30CF;KATAKANA LETTER HA;Lo;0;L;;;;;N;;;;; +30D0;KATAKANA LETTER BA;Lo;0;L;30CF 3099;;;;N;;;;; +30D1;KATAKANA LETTER PA;Lo;0;L;30CF 309A;;;;N;;;;; +30D2;KATAKANA LETTER HI;Lo;0;L;;;;;N;;;;; +30D3;KATAKANA LETTER BI;Lo;0;L;30D2 3099;;;;N;;;;; +30D4;KATAKANA LETTER PI;Lo;0;L;30D2 309A;;;;N;;;;; +30D5;KATAKANA LETTER HU;Lo;0;L;;;;;N;;;;; +30D6;KATAKANA LETTER BU;Lo;0;L;30D5 3099;;;;N;;;;; +30D7;KATAKANA LETTER PU;Lo;0;L;30D5 309A;;;;N;;;;; +30D8;KATAKANA LETTER HE;Lo;0;L;;;;;N;;;;; +30D9;KATAKANA LETTER BE;Lo;0;L;30D8 3099;;;;N;;;;; +30DA;KATAKANA LETTER PE;Lo;0;L;30D8 309A;;;;N;;;;; +30DB;KATAKANA LETTER HO;Lo;0;L;;;;;N;;;;; +30DC;KATAKANA LETTER BO;Lo;0;L;30DB 3099;;;;N;;;;; +30DD;KATAKANA LETTER PO;Lo;0;L;30DB 309A;;;;N;;;;; +30DE;KATAKANA LETTER MA;Lo;0;L;;;;;N;;;;; +30DF;KATAKANA LETTER MI;Lo;0;L;;;;;N;;;;; +30E0;KATAKANA LETTER MU;Lo;0;L;;;;;N;;;;; +30E1;KATAKANA LETTER ME;Lo;0;L;;;;;N;;;;; +30E2;KATAKANA LETTER MO;Lo;0;L;;;;;N;;;;; +30E3;KATAKANA LETTER SMALL YA;Lo;0;L;;;;;N;;;;; +30E4;KATAKANA LETTER YA;Lo;0;L;;;;;N;;;;; +30E5;KATAKANA LETTER SMALL YU;Lo;0;L;;;;;N;;;;; +30E6;KATAKANA LETTER YU;Lo;0;L;;;;;N;;;;; +30E7;KATAKANA LETTER SMALL YO;Lo;0;L;;;;;N;;;;; +30E8;KATAKANA LETTER YO;Lo;0;L;;;;;N;;;;; +30E9;KATAKANA LETTER RA;Lo;0;L;;;;;N;;;;; +30EA;KATAKANA LETTER RI;Lo;0;L;;;;;N;;;;; +30EB;KATAKANA LETTER RU;Lo;0;L;;;;;N;;;;; +30EC;KATAKANA LETTER RE;Lo;0;L;;;;;N;;;;; +30ED;KATAKANA LETTER RO;Lo;0;L;;;;;N;;;;; +30EE;KATAKANA LETTER SMALL WA;Lo;0;L;;;;;N;;;;; +30EF;KATAKANA LETTER WA;Lo;0;L;;;;;N;;;;; +30F0;KATAKANA LETTER WI;Lo;0;L;;;;;N;;;;; +30F1;KATAKANA LETTER WE;Lo;0;L;;;;;N;;;;; +30F2;KATAKANA LETTER WO;Lo;0;L;;;;;N;;;;; +30F3;KATAKANA LETTER N;Lo;0;L;;;;;N;;;;; +30F4;KATAKANA LETTER VU;Lo;0;L;30A6 3099;;;;N;;;;; +30F5;KATAKANA LETTER SMALL KA;Lo;0;L;;;;;N;;;;; +30F6;KATAKANA LETTER SMALL KE;Lo;0;L;;;;;N;;;;; +30F7;KATAKANA LETTER VA;Lo;0;L;30EF 3099;;;;N;;;;; +30F8;KATAKANA LETTER VI;Lo;0;L;30F0 3099;;;;N;;;;; +30F9;KATAKANA LETTER VE;Lo;0;L;30F1 3099;;;;N;;;;; +30FA;KATAKANA LETTER VO;Lo;0;L;30F2 3099;;;;N;;;;; +30FB;KATAKANA MIDDLE DOT;Po;0;ON;;;;;N;;;;; +30FC;KATAKANA-HIRAGANA PROLONGED SOUND MARK;Lm;0;L;;;;;N;;;;; +30FD;KATAKANA ITERATION MARK;Lm;0;L;;;;;N;;;;; +30FE;KATAKANA VOICED ITERATION MARK;Lm;0;L;30FD 3099;;;;N;;;;; +30FF;KATAKANA DIGRAPH KOTO;Lo;0;L; 30B3 30C8;;;;N;;;;; +3105;BOPOMOFO LETTER B;Lo;0;L;;;;;N;;;;; +3106;BOPOMOFO LETTER P;Lo;0;L;;;;;N;;;;; +3107;BOPOMOFO LETTER M;Lo;0;L;;;;;N;;;;; +3108;BOPOMOFO LETTER F;Lo;0;L;;;;;N;;;;; +3109;BOPOMOFO LETTER D;Lo;0;L;;;;;N;;;;; +310A;BOPOMOFO LETTER T;Lo;0;L;;;;;N;;;;; +310B;BOPOMOFO LETTER N;Lo;0;L;;;;;N;;;;; +310C;BOPOMOFO LETTER L;Lo;0;L;;;;;N;;;;; +310D;BOPOMOFO LETTER G;Lo;0;L;;;;;N;;;;; +310E;BOPOMOFO LETTER K;Lo;0;L;;;;;N;;;;; +310F;BOPOMOFO LETTER H;Lo;0;L;;;;;N;;;;; +3110;BOPOMOFO LETTER J;Lo;0;L;;;;;N;;;;; +3111;BOPOMOFO LETTER Q;Lo;0;L;;;;;N;;;;; +3112;BOPOMOFO LETTER X;Lo;0;L;;;;;N;;;;; +3113;BOPOMOFO LETTER ZH;Lo;0;L;;;;;N;;;;; +3114;BOPOMOFO LETTER CH;Lo;0;L;;;;;N;;;;; +3115;BOPOMOFO LETTER SH;Lo;0;L;;;;;N;;;;; +3116;BOPOMOFO LETTER R;Lo;0;L;;;;;N;;;;; +3117;BOPOMOFO LETTER Z;Lo;0;L;;;;;N;;;;; +3118;BOPOMOFO LETTER C;Lo;0;L;;;;;N;;;;; +3119;BOPOMOFO LETTER S;Lo;0;L;;;;;N;;;;; +311A;BOPOMOFO LETTER A;Lo;0;L;;;;;N;;;;; +311B;BOPOMOFO LETTER O;Lo;0;L;;;;;N;;;;; +311C;BOPOMOFO LETTER E;Lo;0;L;;;;;N;;;;; +311D;BOPOMOFO LETTER EH;Lo;0;L;;;;;N;;;;; +311E;BOPOMOFO LETTER AI;Lo;0;L;;;;;N;;;;; +311F;BOPOMOFO LETTER EI;Lo;0;L;;;;;N;;;;; +3120;BOPOMOFO LETTER AU;Lo;0;L;;;;;N;;;;; +3121;BOPOMOFO LETTER OU;Lo;0;L;;;;;N;;;;; +3122;BOPOMOFO LETTER AN;Lo;0;L;;;;;N;;;;; +3123;BOPOMOFO LETTER EN;Lo;0;L;;;;;N;;;;; +3124;BOPOMOFO LETTER ANG;Lo;0;L;;;;;N;;;;; +3125;BOPOMOFO LETTER ENG;Lo;0;L;;;;;N;;;;; +3126;BOPOMOFO LETTER ER;Lo;0;L;;;;;N;;;;; +3127;BOPOMOFO LETTER I;Lo;0;L;;;;;N;;;;; +3128;BOPOMOFO LETTER U;Lo;0;L;;;;;N;;;;; +3129;BOPOMOFO LETTER IU;Lo;0;L;;;;;N;;;;; +312A;BOPOMOFO LETTER V;Lo;0;L;;;;;N;;;;; +312B;BOPOMOFO LETTER NG;Lo;0;L;;;;;N;;;;; +312C;BOPOMOFO LETTER GN;Lo;0;L;;;;;N;;;;; +312D;BOPOMOFO LETTER IH;Lo;0;L;;;;;N;;;;; +3131;HANGUL LETTER KIYEOK;Lo;0;L; 1100;;;;N;HANGUL LETTER GIYEOG;;;; +3132;HANGUL LETTER SSANGKIYEOK;Lo;0;L; 1101;;;;N;HANGUL LETTER SSANG GIYEOG;;;; +3133;HANGUL LETTER KIYEOK-SIOS;Lo;0;L; 11AA;;;;N;HANGUL LETTER GIYEOG SIOS;;;; +3134;HANGUL LETTER NIEUN;Lo;0;L; 1102;;;;N;;;;; +3135;HANGUL LETTER NIEUN-CIEUC;Lo;0;L; 11AC;;;;N;HANGUL LETTER NIEUN JIEUJ;;;; +3136;HANGUL LETTER NIEUN-HIEUH;Lo;0;L; 11AD;;;;N;HANGUL LETTER NIEUN HIEUH;;;; +3137;HANGUL LETTER TIKEUT;Lo;0;L; 1103;;;;N;HANGUL LETTER DIGEUD;;;; +3138;HANGUL LETTER SSANGTIKEUT;Lo;0;L; 1104;;;;N;HANGUL LETTER SSANG DIGEUD;;;; +3139;HANGUL LETTER RIEUL;Lo;0;L; 1105;;;;N;HANGUL LETTER LIEUL;;;; +313A;HANGUL LETTER RIEUL-KIYEOK;Lo;0;L; 11B0;;;;N;HANGUL LETTER LIEUL GIYEOG;;;; +313B;HANGUL LETTER RIEUL-MIEUM;Lo;0;L; 11B1;;;;N;HANGUL LETTER LIEUL MIEUM;;;; +313C;HANGUL LETTER RIEUL-PIEUP;Lo;0;L; 11B2;;;;N;HANGUL LETTER LIEUL BIEUB;;;; +313D;HANGUL LETTER RIEUL-SIOS;Lo;0;L; 11B3;;;;N;HANGUL LETTER LIEUL SIOS;;;; +313E;HANGUL LETTER RIEUL-THIEUTH;Lo;0;L; 11B4;;;;N;HANGUL LETTER LIEUL TIEUT;;;; +313F;HANGUL LETTER RIEUL-PHIEUPH;Lo;0;L; 11B5;;;;N;HANGUL LETTER LIEUL PIEUP;;;; +3140;HANGUL LETTER RIEUL-HIEUH;Lo;0;L; 111A;;;;N;HANGUL LETTER LIEUL HIEUH;;;; +3141;HANGUL LETTER MIEUM;Lo;0;L; 1106;;;;N;;;;; +3142;HANGUL LETTER PIEUP;Lo;0;L; 1107;;;;N;HANGUL LETTER BIEUB;;;; +3143;HANGUL LETTER SSANGPIEUP;Lo;0;L; 1108;;;;N;HANGUL LETTER SSANG BIEUB;;;; +3144;HANGUL LETTER PIEUP-SIOS;Lo;0;L; 1121;;;;N;HANGUL LETTER BIEUB SIOS;;;; +3145;HANGUL LETTER SIOS;Lo;0;L; 1109;;;;N;;;;; +3146;HANGUL LETTER SSANGSIOS;Lo;0;L; 110A;;;;N;HANGUL LETTER SSANG SIOS;;;; +3147;HANGUL LETTER IEUNG;Lo;0;L; 110B;;;;N;;;;; +3148;HANGUL LETTER CIEUC;Lo;0;L; 110C;;;;N;HANGUL LETTER JIEUJ;;;; +3149;HANGUL LETTER SSANGCIEUC;Lo;0;L; 110D;;;;N;HANGUL LETTER SSANG JIEUJ;;;; +314A;HANGUL LETTER CHIEUCH;Lo;0;L; 110E;;;;N;HANGUL LETTER CIEUC;;;; +314B;HANGUL LETTER KHIEUKH;Lo;0;L; 110F;;;;N;HANGUL LETTER KIYEOK;;;; +314C;HANGUL LETTER THIEUTH;Lo;0;L; 1110;;;;N;HANGUL LETTER TIEUT;;;; +314D;HANGUL LETTER PHIEUPH;Lo;0;L; 1111;;;;N;HANGUL LETTER PIEUP;;;; +314E;HANGUL LETTER HIEUH;Lo;0;L; 1112;;;;N;;;;; +314F;HANGUL LETTER A;Lo;0;L; 1161;;;;N;;;;; +3150;HANGUL LETTER AE;Lo;0;L; 1162;;;;N;;;;; +3151;HANGUL LETTER YA;Lo;0;L; 1163;;;;N;;;;; +3152;HANGUL LETTER YAE;Lo;0;L; 1164;;;;N;;;;; +3153;HANGUL LETTER EO;Lo;0;L; 1165;;;;N;;;;; +3154;HANGUL LETTER E;Lo;0;L; 1166;;;;N;;;;; +3155;HANGUL LETTER YEO;Lo;0;L; 1167;;;;N;;;;; +3156;HANGUL LETTER YE;Lo;0;L; 1168;;;;N;;;;; +3157;HANGUL LETTER O;Lo;0;L; 1169;;;;N;;;;; +3158;HANGUL LETTER WA;Lo;0;L; 116A;;;;N;;;;; +3159;HANGUL LETTER WAE;Lo;0;L; 116B;;;;N;;;;; +315A;HANGUL LETTER OE;Lo;0;L; 116C;;;;N;;;;; +315B;HANGUL LETTER YO;Lo;0;L; 116D;;;;N;;;;; +315C;HANGUL LETTER U;Lo;0;L; 116E;;;;N;;;;; +315D;HANGUL LETTER WEO;Lo;0;L; 116F;;;;N;;;;; +315E;HANGUL LETTER WE;Lo;0;L; 1170;;;;N;;;;; +315F;HANGUL LETTER WI;Lo;0;L; 1171;;;;N;;;;; +3160;HANGUL LETTER YU;Lo;0;L; 1172;;;;N;;;;; +3161;HANGUL LETTER EU;Lo;0;L; 1173;;;;N;;;;; +3162;HANGUL LETTER YI;Lo;0;L; 1174;;;;N;;;;; +3163;HANGUL LETTER I;Lo;0;L; 1175;;;;N;;;;; +3164;HANGUL FILLER;Lo;0;L; 1160;;;;N;HANGUL CAE OM;;;; +3165;HANGUL LETTER SSANGNIEUN;Lo;0;L; 1114;;;;N;HANGUL LETTER SSANG NIEUN;;;; +3166;HANGUL LETTER NIEUN-TIKEUT;Lo;0;L; 1115;;;;N;HANGUL LETTER NIEUN DIGEUD;;;; +3167;HANGUL LETTER NIEUN-SIOS;Lo;0;L; 11C7;;;;N;HANGUL LETTER NIEUN SIOS;;;; +3168;HANGUL LETTER NIEUN-PANSIOS;Lo;0;L; 11C8;;;;N;HANGUL LETTER NIEUN BAN CHI EUM;;;; +3169;HANGUL LETTER RIEUL-KIYEOK-SIOS;Lo;0;L; 11CC;;;;N;HANGUL LETTER LIEUL GIYEOG SIOS;;;; +316A;HANGUL LETTER RIEUL-TIKEUT;Lo;0;L; 11CE;;;;N;HANGUL LETTER LIEUL DIGEUD;;;; +316B;HANGUL LETTER RIEUL-PIEUP-SIOS;Lo;0;L; 11D3;;;;N;HANGUL LETTER LIEUL BIEUB SIOS;;;; +316C;HANGUL LETTER RIEUL-PANSIOS;Lo;0;L; 11D7;;;;N;HANGUL LETTER LIEUL BAN CHI EUM;;;; +316D;HANGUL LETTER RIEUL-YEORINHIEUH;Lo;0;L; 11D9;;;;N;HANGUL LETTER LIEUL YEOLIN HIEUH;;;; +316E;HANGUL LETTER MIEUM-PIEUP;Lo;0;L; 111C;;;;N;HANGUL LETTER MIEUM BIEUB;;;; +316F;HANGUL LETTER MIEUM-SIOS;Lo;0;L; 11DD;;;;N;HANGUL LETTER MIEUM SIOS;;;; +3170;HANGUL LETTER MIEUM-PANSIOS;Lo;0;L; 11DF;;;;N;HANGUL LETTER BIEUB BAN CHI EUM;;;; +3171;HANGUL LETTER KAPYEOUNMIEUM;Lo;0;L; 111D;;;;N;HANGUL LETTER MIEUM SUN GYEONG EUM;;;; +3172;HANGUL LETTER PIEUP-KIYEOK;Lo;0;L; 111E;;;;N;HANGUL LETTER BIEUB GIYEOG;;;; +3173;HANGUL LETTER PIEUP-TIKEUT;Lo;0;L; 1120;;;;N;HANGUL LETTER BIEUB DIGEUD;;;; +3174;HANGUL LETTER PIEUP-SIOS-KIYEOK;Lo;0;L; 1122;;;;N;HANGUL LETTER BIEUB SIOS GIYEOG;;;; +3175;HANGUL LETTER PIEUP-SIOS-TIKEUT;Lo;0;L; 1123;;;;N;HANGUL LETTER BIEUB SIOS DIGEUD;;;; +3176;HANGUL LETTER PIEUP-CIEUC;Lo;0;L; 1127;;;;N;HANGUL LETTER BIEUB JIEUJ;;;; +3177;HANGUL LETTER PIEUP-THIEUTH;Lo;0;L; 1129;;;;N;HANGUL LETTER BIEUB TIEUT;;;; +3178;HANGUL LETTER KAPYEOUNPIEUP;Lo;0;L; 112B;;;;N;HANGUL LETTER BIEUB SUN GYEONG EUM;;;; +3179;HANGUL LETTER KAPYEOUNSSANGPIEUP;Lo;0;L; 112C;;;;N;HANGUL LETTER SSANG BIEUB SUN GYEONG EUM;;;; +317A;HANGUL LETTER SIOS-KIYEOK;Lo;0;L; 112D;;;;N;HANGUL LETTER SIOS GIYEOG;;;; +317B;HANGUL LETTER SIOS-NIEUN;Lo;0;L; 112E;;;;N;HANGUL LETTER SIOS NIEUN;;;; +317C;HANGUL LETTER SIOS-TIKEUT;Lo;0;L; 112F;;;;N;HANGUL LETTER SIOS DIGEUD;;;; +317D;HANGUL LETTER SIOS-PIEUP;Lo;0;L; 1132;;;;N;HANGUL LETTER SIOS BIEUB;;;; +317E;HANGUL LETTER SIOS-CIEUC;Lo;0;L; 1136;;;;N;HANGUL LETTER SIOS JIEUJ;;;; +317F;HANGUL LETTER PANSIOS;Lo;0;L; 1140;;;;N;HANGUL LETTER BAN CHI EUM;;;; +3180;HANGUL LETTER SSANGIEUNG;Lo;0;L; 1147;;;;N;HANGUL LETTER SSANG IEUNG;;;; +3181;HANGUL LETTER YESIEUNG;Lo;0;L; 114C;;;;N;HANGUL LETTER NGIEUNG;;;; +3182;HANGUL LETTER YESIEUNG-SIOS;Lo;0;L; 11F1;;;;N;HANGUL LETTER NGIEUNG SIOS;;;; +3183;HANGUL LETTER YESIEUNG-PANSIOS;Lo;0;L; 11F2;;;;N;HANGUL LETTER NGIEUNG BAN CHI EUM;;;; +3184;HANGUL LETTER KAPYEOUNPHIEUPH;Lo;0;L; 1157;;;;N;HANGUL LETTER PIEUP SUN GYEONG EUM;;;; +3185;HANGUL LETTER SSANGHIEUH;Lo;0;L; 1158;;;;N;HANGUL LETTER SSANG HIEUH;;;; +3186;HANGUL LETTER YEORINHIEUH;Lo;0;L; 1159;;;;N;HANGUL LETTER YEOLIN HIEUH;;;; +3187;HANGUL LETTER YO-YA;Lo;0;L; 1184;;;;N;HANGUL LETTER YOYA;;;; +3188;HANGUL LETTER YO-YAE;Lo;0;L; 1185;;;;N;HANGUL LETTER YOYAE;;;; +3189;HANGUL LETTER YO-I;Lo;0;L; 1188;;;;N;HANGUL LETTER YOI;;;; +318A;HANGUL LETTER YU-YEO;Lo;0;L; 1191;;;;N;HANGUL LETTER YUYEO;;;; +318B;HANGUL LETTER YU-YE;Lo;0;L; 1192;;;;N;HANGUL LETTER YUYE;;;; +318C;HANGUL LETTER YU-I;Lo;0;L; 1194;;;;N;HANGUL LETTER YUI;;;; +318D;HANGUL LETTER ARAEA;Lo;0;L; 119E;;;;N;HANGUL LETTER ALAE A;;;; +318E;HANGUL LETTER ARAEAE;Lo;0;L; 11A1;;;;N;HANGUL LETTER ALAE AE;;;; +3190;IDEOGRAPHIC ANNOTATION LINKING MARK;So;0;L;;;;;N;KANBUN TATETEN;;;; +3191;IDEOGRAPHIC ANNOTATION REVERSE MARK;So;0;L;;;;;N;KAERITEN RE;;;; +3192;IDEOGRAPHIC ANNOTATION ONE MARK;No;0;L; 4E00;;;1;N;KAERITEN ITI;;;; +3193;IDEOGRAPHIC ANNOTATION TWO MARK;No;0;L; 4E8C;;;2;N;KAERITEN NI;;;; +3194;IDEOGRAPHIC ANNOTATION THREE MARK;No;0;L; 4E09;;;3;N;KAERITEN SAN;;;; +3195;IDEOGRAPHIC ANNOTATION FOUR MARK;No;0;L; 56DB;;;4;N;KAERITEN SI;;;; +3196;IDEOGRAPHIC ANNOTATION TOP MARK;So;0;L; 4E0A;;;;N;KAERITEN ZYOU;;;; +3197;IDEOGRAPHIC ANNOTATION MIDDLE MARK;So;0;L; 4E2D;;;;N;KAERITEN TYUU;;;; +3198;IDEOGRAPHIC ANNOTATION BOTTOM MARK;So;0;L; 4E0B;;;;N;KAERITEN GE;;;; +3199;IDEOGRAPHIC ANNOTATION FIRST MARK;So;0;L; 7532;;;;N;KAERITEN KOU;;;; +319A;IDEOGRAPHIC ANNOTATION SECOND MARK;So;0;L; 4E59;;;;N;KAERITEN OTU;;;; +319B;IDEOGRAPHIC ANNOTATION THIRD MARK;So;0;L; 4E19;;;;N;KAERITEN HEI;;;; +319C;IDEOGRAPHIC ANNOTATION FOURTH MARK;So;0;L; 4E01;;;;N;KAERITEN TEI;;;; +319D;IDEOGRAPHIC ANNOTATION HEAVEN MARK;So;0;L; 5929;;;;N;KAERITEN TEN;;;; +319E;IDEOGRAPHIC ANNOTATION EARTH MARK;So;0;L; 5730;;;;N;KAERITEN TI;;;; +319F;IDEOGRAPHIC ANNOTATION MAN MARK;So;0;L; 4EBA;;;;N;KAERITEN ZIN;;;; +31A0;BOPOMOFO LETTER BU;Lo;0;L;;;;;N;;;;; +31A1;BOPOMOFO LETTER ZI;Lo;0;L;;;;;N;;;;; +31A2;BOPOMOFO LETTER JI;Lo;0;L;;;;;N;;;;; +31A3;BOPOMOFO LETTER GU;Lo;0;L;;;;;N;;;;; +31A4;BOPOMOFO LETTER EE;Lo;0;L;;;;;N;;;;; +31A5;BOPOMOFO LETTER ENN;Lo;0;L;;;;;N;;;;; +31A6;BOPOMOFO LETTER OO;Lo;0;L;;;;;N;;;;; +31A7;BOPOMOFO LETTER ONN;Lo;0;L;;;;;N;;;;; +31A8;BOPOMOFO LETTER IR;Lo;0;L;;;;;N;;;;; +31A9;BOPOMOFO LETTER ANN;Lo;0;L;;;;;N;;;;; +31AA;BOPOMOFO LETTER INN;Lo;0;L;;;;;N;;;;; +31AB;BOPOMOFO LETTER UNN;Lo;0;L;;;;;N;;;;; +31AC;BOPOMOFO LETTER IM;Lo;0;L;;;;;N;;;;; +31AD;BOPOMOFO LETTER NGG;Lo;0;L;;;;;N;;;;; +31AE;BOPOMOFO LETTER AINN;Lo;0;L;;;;;N;;;;; +31AF;BOPOMOFO LETTER AUNN;Lo;0;L;;;;;N;;;;; +31B0;BOPOMOFO LETTER AM;Lo;0;L;;;;;N;;;;; +31B1;BOPOMOFO LETTER OM;Lo;0;L;;;;;N;;;;; +31B2;BOPOMOFO LETTER ONG;Lo;0;L;;;;;N;;;;; +31B3;BOPOMOFO LETTER INNN;Lo;0;L;;;;;N;;;;; +31B4;BOPOMOFO FINAL LETTER P;Lo;0;L;;;;;N;;;;; +31B5;BOPOMOFO FINAL LETTER T;Lo;0;L;;;;;N;;;;; +31B6;BOPOMOFO FINAL LETTER K;Lo;0;L;;;;;N;;;;; +31B7;BOPOMOFO FINAL LETTER H;Lo;0;L;;;;;N;;;;; +31B8;BOPOMOFO LETTER GH;Lo;0;L;;;;;N;;;;; +31B9;BOPOMOFO LETTER LH;Lo;0;L;;;;;N;;;;; +31BA;BOPOMOFO LETTER ZY;Lo;0;L;;;;;N;;;;; +31C0;CJK STROKE T;So;0;ON;;;;;N;;;;; +31C1;CJK STROKE WG;So;0;ON;;;;;N;;;;; +31C2;CJK STROKE XG;So;0;ON;;;;;N;;;;; +31C3;CJK STROKE BXG;So;0;ON;;;;;N;;;;; +31C4;CJK STROKE SW;So;0;ON;;;;;N;;;;; +31C5;CJK STROKE HZZ;So;0;ON;;;;;N;;;;; +31C6;CJK STROKE HZG;So;0;ON;;;;;N;;;;; +31C7;CJK STROKE HP;So;0;ON;;;;;N;;;;; +31C8;CJK STROKE HZWG;So;0;ON;;;;;N;;;;; +31C9;CJK STROKE SZWG;So;0;ON;;;;;N;;;;; +31CA;CJK STROKE HZT;So;0;ON;;;;;N;;;;; +31CB;CJK STROKE HZZP;So;0;ON;;;;;N;;;;; +31CC;CJK STROKE HPWG;So;0;ON;;;;;N;;;;; +31CD;CJK STROKE HZW;So;0;ON;;;;;N;;;;; +31CE;CJK STROKE HZZZ;So;0;ON;;;;;N;;;;; +31CF;CJK STROKE N;So;0;ON;;;;;N;;;;; +31D0;CJK STROKE H;So;0;ON;;;;;N;;;;; +31D1;CJK STROKE S;So;0;ON;;;;;N;;;;; +31D2;CJK STROKE P;So;0;ON;;;;;N;;;;; +31D3;CJK STROKE SP;So;0;ON;;;;;N;;;;; +31D4;CJK STROKE D;So;0;ON;;;;;N;;;;; +31D5;CJK STROKE HZ;So;0;ON;;;;;N;;;;; +31D6;CJK STROKE HG;So;0;ON;;;;;N;;;;; +31D7;CJK STROKE SZ;So;0;ON;;;;;N;;;;; +31D8;CJK STROKE SWZ;So;0;ON;;;;;N;;;;; +31D9;CJK STROKE ST;So;0;ON;;;;;N;;;;; +31DA;CJK STROKE SG;So;0;ON;;;;;N;;;;; +31DB;CJK STROKE PD;So;0;ON;;;;;N;;;;; +31DC;CJK STROKE PZ;So;0;ON;;;;;N;;;;; +31DD;CJK STROKE TN;So;0;ON;;;;;N;;;;; +31DE;CJK STROKE SZZ;So;0;ON;;;;;N;;;;; +31DF;CJK STROKE SWG;So;0;ON;;;;;N;;;;; +31E0;CJK STROKE HXWG;So;0;ON;;;;;N;;;;; +31E1;CJK STROKE HZZZG;So;0;ON;;;;;N;;;;; +31E2;CJK STROKE PG;So;0;ON;;;;;N;;;;; +31E3;CJK STROKE Q;So;0;ON;;;;;N;;;;; +31F0;KATAKANA LETTER SMALL KU;Lo;0;L;;;;;N;;;;; +31F1;KATAKANA LETTER SMALL SI;Lo;0;L;;;;;N;;;;; +31F2;KATAKANA LETTER SMALL SU;Lo;0;L;;;;;N;;;;; +31F3;KATAKANA LETTER SMALL TO;Lo;0;L;;;;;N;;;;; +31F4;KATAKANA LETTER SMALL NU;Lo;0;L;;;;;N;;;;; +31F5;KATAKANA LETTER SMALL HA;Lo;0;L;;;;;N;;;;; +31F6;KATAKANA LETTER SMALL HI;Lo;0;L;;;;;N;;;;; +31F7;KATAKANA LETTER SMALL HU;Lo;0;L;;;;;N;;;;; +31F8;KATAKANA LETTER SMALL HE;Lo;0;L;;;;;N;;;;; +31F9;KATAKANA LETTER SMALL HO;Lo;0;L;;;;;N;;;;; +31FA;KATAKANA LETTER SMALL MU;Lo;0;L;;;;;N;;;;; +31FB;KATAKANA LETTER SMALL RA;Lo;0;L;;;;;N;;;;; +31FC;KATAKANA LETTER SMALL RI;Lo;0;L;;;;;N;;;;; +31FD;KATAKANA LETTER SMALL RU;Lo;0;L;;;;;N;;;;; +31FE;KATAKANA LETTER SMALL RE;Lo;0;L;;;;;N;;;;; +31FF;KATAKANA LETTER SMALL RO;Lo;0;L;;;;;N;;;;; +3200;PARENTHESIZED HANGUL KIYEOK;So;0;L; 0028 1100 0029;;;;N;PARENTHESIZED HANGUL GIYEOG;;;; +3201;PARENTHESIZED HANGUL NIEUN;So;0;L; 0028 1102 0029;;;;N;;;;; +3202;PARENTHESIZED HANGUL TIKEUT;So;0;L; 0028 1103 0029;;;;N;PARENTHESIZED HANGUL DIGEUD;;;; +3203;PARENTHESIZED HANGUL RIEUL;So;0;L; 0028 1105 0029;;;;N;PARENTHESIZED HANGUL LIEUL;;;; +3204;PARENTHESIZED HANGUL MIEUM;So;0;L; 0028 1106 0029;;;;N;;;;; +3205;PARENTHESIZED HANGUL PIEUP;So;0;L; 0028 1107 0029;;;;N;PARENTHESIZED HANGUL BIEUB;;;; +3206;PARENTHESIZED HANGUL SIOS;So;0;L; 0028 1109 0029;;;;N;;;;; +3207;PARENTHESIZED HANGUL IEUNG;So;0;L; 0028 110B 0029;;;;N;;;;; +3208;PARENTHESIZED HANGUL CIEUC;So;0;L; 0028 110C 0029;;;;N;PARENTHESIZED HANGUL JIEUJ;;;; +3209;PARENTHESIZED HANGUL CHIEUCH;So;0;L; 0028 110E 0029;;;;N;PARENTHESIZED HANGUL CIEUC;;;; +320A;PARENTHESIZED HANGUL KHIEUKH;So;0;L; 0028 110F 0029;;;;N;PARENTHESIZED HANGUL KIYEOK;;;; +320B;PARENTHESIZED HANGUL THIEUTH;So;0;L; 0028 1110 0029;;;;N;PARENTHESIZED HANGUL TIEUT;;;; +320C;PARENTHESIZED HANGUL PHIEUPH;So;0;L; 0028 1111 0029;;;;N;PARENTHESIZED HANGUL PIEUP;;;; +320D;PARENTHESIZED HANGUL HIEUH;So;0;L; 0028 1112 0029;;;;N;;;;; +320E;PARENTHESIZED HANGUL KIYEOK A;So;0;L; 0028 1100 1161 0029;;;;N;PARENTHESIZED HANGUL GA;;;; +320F;PARENTHESIZED HANGUL NIEUN A;So;0;L; 0028 1102 1161 0029;;;;N;PARENTHESIZED HANGUL NA;;;; +3210;PARENTHESIZED HANGUL TIKEUT A;So;0;L; 0028 1103 1161 0029;;;;N;PARENTHESIZED HANGUL DA;;;; +3211;PARENTHESIZED HANGUL RIEUL A;So;0;L; 0028 1105 1161 0029;;;;N;PARENTHESIZED HANGUL LA;;;; +3212;PARENTHESIZED HANGUL MIEUM A;So;0;L; 0028 1106 1161 0029;;;;N;PARENTHESIZED HANGUL MA;;;; +3213;PARENTHESIZED HANGUL PIEUP A;So;0;L; 0028 1107 1161 0029;;;;N;PARENTHESIZED HANGUL BA;;;; +3214;PARENTHESIZED HANGUL SIOS A;So;0;L; 0028 1109 1161 0029;;;;N;PARENTHESIZED HANGUL SA;;;; +3215;PARENTHESIZED HANGUL IEUNG A;So;0;L; 0028 110B 1161 0029;;;;N;PARENTHESIZED HANGUL A;;;; +3216;PARENTHESIZED HANGUL CIEUC A;So;0;L; 0028 110C 1161 0029;;;;N;PARENTHESIZED HANGUL JA;;;; +3217;PARENTHESIZED HANGUL CHIEUCH A;So;0;L; 0028 110E 1161 0029;;;;N;PARENTHESIZED HANGUL CA;;;; +3218;PARENTHESIZED HANGUL KHIEUKH A;So;0;L; 0028 110F 1161 0029;;;;N;PARENTHESIZED HANGUL KA;;;; +3219;PARENTHESIZED HANGUL THIEUTH A;So;0;L; 0028 1110 1161 0029;;;;N;PARENTHESIZED HANGUL TA;;;; +321A;PARENTHESIZED HANGUL PHIEUPH A;So;0;L; 0028 1111 1161 0029;;;;N;PARENTHESIZED HANGUL PA;;;; +321B;PARENTHESIZED HANGUL HIEUH A;So;0;L; 0028 1112 1161 0029;;;;N;PARENTHESIZED HANGUL HA;;;; +321C;PARENTHESIZED HANGUL CIEUC U;So;0;L; 0028 110C 116E 0029;;;;N;PARENTHESIZED HANGUL JU;;;; +321D;PARENTHESIZED KOREAN CHARACTER OJEON;So;0;ON; 0028 110B 1169 110C 1165 11AB 0029;;;;N;;;;; +321E;PARENTHESIZED KOREAN CHARACTER O HU;So;0;ON; 0028 110B 1169 1112 116E 0029;;;;N;;;;; +3220;PARENTHESIZED IDEOGRAPH ONE;No;0;L; 0028 4E00 0029;;;1;N;;;;; +3221;PARENTHESIZED IDEOGRAPH TWO;No;0;L; 0028 4E8C 0029;;;2;N;;;;; +3222;PARENTHESIZED IDEOGRAPH THREE;No;0;L; 0028 4E09 0029;;;3;N;;;;; +3223;PARENTHESIZED IDEOGRAPH FOUR;No;0;L; 0028 56DB 0029;;;4;N;;;;; +3224;PARENTHESIZED IDEOGRAPH FIVE;No;0;L; 0028 4E94 0029;;;5;N;;;;; +3225;PARENTHESIZED IDEOGRAPH SIX;No;0;L; 0028 516D 0029;;;6;N;;;;; +3226;PARENTHESIZED IDEOGRAPH SEVEN;No;0;L; 0028 4E03 0029;;;7;N;;;;; +3227;PARENTHESIZED IDEOGRAPH EIGHT;No;0;L; 0028 516B 0029;;;8;N;;;;; +3228;PARENTHESIZED IDEOGRAPH NINE;No;0;L; 0028 4E5D 0029;;;9;N;;;;; +3229;PARENTHESIZED IDEOGRAPH TEN;No;0;L; 0028 5341 0029;;;10;N;;;;; +322A;PARENTHESIZED IDEOGRAPH MOON;So;0;L; 0028 6708 0029;;;;N;;;;; +322B;PARENTHESIZED IDEOGRAPH FIRE;So;0;L; 0028 706B 0029;;;;N;;;;; +322C;PARENTHESIZED IDEOGRAPH WATER;So;0;L; 0028 6C34 0029;;;;N;;;;; +322D;PARENTHESIZED IDEOGRAPH WOOD;So;0;L; 0028 6728 0029;;;;N;;;;; +322E;PARENTHESIZED IDEOGRAPH METAL;So;0;L; 0028 91D1 0029;;;;N;;;;; +322F;PARENTHESIZED IDEOGRAPH EARTH;So;0;L; 0028 571F 0029;;;;N;;;;; +3230;PARENTHESIZED IDEOGRAPH SUN;So;0;L; 0028 65E5 0029;;;;N;;;;; +3231;PARENTHESIZED IDEOGRAPH STOCK;So;0;L; 0028 682A 0029;;;;N;;;;; +3232;PARENTHESIZED IDEOGRAPH HAVE;So;0;L; 0028 6709 0029;;;;N;;;;; +3233;PARENTHESIZED IDEOGRAPH SOCIETY;So;0;L; 0028 793E 0029;;;;N;;;;; +3234;PARENTHESIZED IDEOGRAPH NAME;So;0;L; 0028 540D 0029;;;;N;;;;; +3235;PARENTHESIZED IDEOGRAPH SPECIAL;So;0;L; 0028 7279 0029;;;;N;;;;; +3236;PARENTHESIZED IDEOGRAPH FINANCIAL;So;0;L; 0028 8CA1 0029;;;;N;;;;; +3237;PARENTHESIZED IDEOGRAPH CONGRATULATION;So;0;L; 0028 795D 0029;;;;N;;;;; +3238;PARENTHESIZED IDEOGRAPH LABOR;So;0;L; 0028 52B4 0029;;;;N;;;;; +3239;PARENTHESIZED IDEOGRAPH REPRESENT;So;0;L; 0028 4EE3 0029;;;;N;;;;; +323A;PARENTHESIZED IDEOGRAPH CALL;So;0;L; 0028 547C 0029;;;;N;;;;; +323B;PARENTHESIZED IDEOGRAPH STUDY;So;0;L; 0028 5B66 0029;;;;N;;;;; +323C;PARENTHESIZED IDEOGRAPH SUPERVISE;So;0;L; 0028 76E3 0029;;;;N;;;;; +323D;PARENTHESIZED IDEOGRAPH ENTERPRISE;So;0;L; 0028 4F01 0029;;;;N;;;;; +323E;PARENTHESIZED IDEOGRAPH RESOURCE;So;0;L; 0028 8CC7 0029;;;;N;;;;; +323F;PARENTHESIZED IDEOGRAPH ALLIANCE;So;0;L; 0028 5354 0029;;;;N;;;;; +3240;PARENTHESIZED IDEOGRAPH FESTIVAL;So;0;L; 0028 796D 0029;;;;N;;;;; +3241;PARENTHESIZED IDEOGRAPH REST;So;0;L; 0028 4F11 0029;;;;N;;;;; +3242;PARENTHESIZED IDEOGRAPH SELF;So;0;L; 0028 81EA 0029;;;;N;;;;; +3243;PARENTHESIZED IDEOGRAPH REACH;So;0;L; 0028 81F3 0029;;;;N;;;;; +3244;CIRCLED IDEOGRAPH QUESTION;So;0;L; 554F;;;;N;;;;; +3245;CIRCLED IDEOGRAPH KINDERGARTEN;So;0;L; 5E7C;;;;N;;;;; +3246;CIRCLED IDEOGRAPH SCHOOL;So;0;L; 6587;;;;N;;;;; +3247;CIRCLED IDEOGRAPH KOTO;So;0;L; 7B8F;;;;N;;;;; +3248;CIRCLED NUMBER TEN ON BLACK SQUARE;No;0;L;;;;10;N;;;;; +3249;CIRCLED NUMBER TWENTY ON BLACK SQUARE;No;0;L;;;;20;N;;;;; +324A;CIRCLED NUMBER THIRTY ON BLACK SQUARE;No;0;L;;;;30;N;;;;; +324B;CIRCLED NUMBER FORTY ON BLACK SQUARE;No;0;L;;;;40;N;;;;; +324C;CIRCLED NUMBER FIFTY ON BLACK SQUARE;No;0;L;;;;50;N;;;;; +324D;CIRCLED NUMBER SIXTY ON BLACK SQUARE;No;0;L;;;;60;N;;;;; +324E;CIRCLED NUMBER SEVENTY ON BLACK SQUARE;No;0;L;;;;70;N;;;;; +324F;CIRCLED NUMBER EIGHTY ON BLACK SQUARE;No;0;L;;;;80;N;;;;; +3250;PARTNERSHIP SIGN;So;0;ON; 0050 0054 0045;;;;N;;;;; +3251;CIRCLED NUMBER TWENTY ONE;No;0;ON; 0032 0031;;;21;N;;;;; +3252;CIRCLED NUMBER TWENTY TWO;No;0;ON; 0032 0032;;;22;N;;;;; +3253;CIRCLED NUMBER TWENTY THREE;No;0;ON; 0032 0033;;;23;N;;;;; +3254;CIRCLED NUMBER TWENTY FOUR;No;0;ON; 0032 0034;;;24;N;;;;; +3255;CIRCLED NUMBER TWENTY FIVE;No;0;ON; 0032 0035;;;25;N;;;;; +3256;CIRCLED NUMBER TWENTY SIX;No;0;ON; 0032 0036;;;26;N;;;;; +3257;CIRCLED NUMBER TWENTY SEVEN;No;0;ON; 0032 0037;;;27;N;;;;; +3258;CIRCLED NUMBER TWENTY EIGHT;No;0;ON; 0032 0038;;;28;N;;;;; +3259;CIRCLED NUMBER TWENTY NINE;No;0;ON; 0032 0039;;;29;N;;;;; +325A;CIRCLED NUMBER THIRTY;No;0;ON; 0033 0030;;;30;N;;;;; +325B;CIRCLED NUMBER THIRTY ONE;No;0;ON; 0033 0031;;;31;N;;;;; +325C;CIRCLED NUMBER THIRTY TWO;No;0;ON; 0033 0032;;;32;N;;;;; +325D;CIRCLED NUMBER THIRTY THREE;No;0;ON; 0033 0033;;;33;N;;;;; +325E;CIRCLED NUMBER THIRTY FOUR;No;0;ON; 0033 0034;;;34;N;;;;; +325F;CIRCLED NUMBER THIRTY FIVE;No;0;ON; 0033 0035;;;35;N;;;;; +3260;CIRCLED HANGUL KIYEOK;So;0;L; 1100;;;;N;CIRCLED HANGUL GIYEOG;;;; +3261;CIRCLED HANGUL NIEUN;So;0;L; 1102;;;;N;;;;; +3262;CIRCLED HANGUL TIKEUT;So;0;L; 1103;;;;N;CIRCLED HANGUL DIGEUD;;;; +3263;CIRCLED HANGUL RIEUL;So;0;L; 1105;;;;N;CIRCLED HANGUL LIEUL;;;; +3264;CIRCLED HANGUL MIEUM;So;0;L; 1106;;;;N;;;;; +3265;CIRCLED HANGUL PIEUP;So;0;L; 1107;;;;N;CIRCLED HANGUL BIEUB;;;; +3266;CIRCLED HANGUL SIOS;So;0;L; 1109;;;;N;;;;; +3267;CIRCLED HANGUL IEUNG;So;0;L; 110B;;;;N;;;;; +3268;CIRCLED HANGUL CIEUC;So;0;L; 110C;;;;N;CIRCLED HANGUL JIEUJ;;;; +3269;CIRCLED HANGUL CHIEUCH;So;0;L; 110E;;;;N;CIRCLED HANGUL CIEUC;;;; +326A;CIRCLED HANGUL KHIEUKH;So;0;L; 110F;;;;N;CIRCLED HANGUL KIYEOK;;;; +326B;CIRCLED HANGUL THIEUTH;So;0;L; 1110;;;;N;CIRCLED HANGUL TIEUT;;;; +326C;CIRCLED HANGUL PHIEUPH;So;0;L; 1111;;;;N;CIRCLED HANGUL PIEUP;;;; +326D;CIRCLED HANGUL HIEUH;So;0;L; 1112;;;;N;;;;; +326E;CIRCLED HANGUL KIYEOK A;So;0;L; 1100 1161;;;;N;CIRCLED HANGUL GA;;;; +326F;CIRCLED HANGUL NIEUN A;So;0;L; 1102 1161;;;;N;CIRCLED HANGUL NA;;;; +3270;CIRCLED HANGUL TIKEUT A;So;0;L; 1103 1161;;;;N;CIRCLED HANGUL DA;;;; +3271;CIRCLED HANGUL RIEUL A;So;0;L; 1105 1161;;;;N;CIRCLED HANGUL LA;;;; +3272;CIRCLED HANGUL MIEUM A;So;0;L; 1106 1161;;;;N;CIRCLED HANGUL MA;;;; +3273;CIRCLED HANGUL PIEUP A;So;0;L; 1107 1161;;;;N;CIRCLED HANGUL BA;;;; +3274;CIRCLED HANGUL SIOS A;So;0;L; 1109 1161;;;;N;CIRCLED HANGUL SA;;;; +3275;CIRCLED HANGUL IEUNG A;So;0;L; 110B 1161;;;;N;CIRCLED HANGUL A;;;; +3276;CIRCLED HANGUL CIEUC A;So;0;L; 110C 1161;;;;N;CIRCLED HANGUL JA;;;; +3277;CIRCLED HANGUL CHIEUCH A;So;0;L; 110E 1161;;;;N;CIRCLED HANGUL CA;;;; +3278;CIRCLED HANGUL KHIEUKH A;So;0;L; 110F 1161;;;;N;CIRCLED HANGUL KA;;;; +3279;CIRCLED HANGUL THIEUTH A;So;0;L; 1110 1161;;;;N;CIRCLED HANGUL TA;;;; +327A;CIRCLED HANGUL PHIEUPH A;So;0;L; 1111 1161;;;;N;CIRCLED HANGUL PA;;;; +327B;CIRCLED HANGUL HIEUH A;So;0;L; 1112 1161;;;;N;CIRCLED HANGUL HA;;;; +327C;CIRCLED KOREAN CHARACTER CHAMKO;So;0;ON; 110E 1161 11B7 1100 1169;;;;N;;;;; +327D;CIRCLED KOREAN CHARACTER JUEUI;So;0;ON; 110C 116E 110B 1174;;;;N;;;;; +327E;CIRCLED HANGUL IEUNG U;So;0;ON; 110B 116E;;;;N;;;;; +327F;KOREAN STANDARD SYMBOL;So;0;L;;;;;N;;;;; +3280;CIRCLED IDEOGRAPH ONE;No;0;L; 4E00;;;1;N;;;;; +3281;CIRCLED IDEOGRAPH TWO;No;0;L; 4E8C;;;2;N;;;;; +3282;CIRCLED IDEOGRAPH THREE;No;0;L; 4E09;;;3;N;;;;; +3283;CIRCLED IDEOGRAPH FOUR;No;0;L; 56DB;;;4;N;;;;; +3284;CIRCLED IDEOGRAPH FIVE;No;0;L; 4E94;;;5;N;;;;; +3285;CIRCLED IDEOGRAPH SIX;No;0;L; 516D;;;6;N;;;;; +3286;CIRCLED IDEOGRAPH SEVEN;No;0;L; 4E03;;;7;N;;;;; +3287;CIRCLED IDEOGRAPH EIGHT;No;0;L; 516B;;;8;N;;;;; +3288;CIRCLED IDEOGRAPH NINE;No;0;L; 4E5D;;;9;N;;;;; +3289;CIRCLED IDEOGRAPH TEN;No;0;L; 5341;;;10;N;;;;; +328A;CIRCLED IDEOGRAPH MOON;So;0;L; 6708;;;;N;;;;; +328B;CIRCLED IDEOGRAPH FIRE;So;0;L; 706B;;;;N;;;;; +328C;CIRCLED IDEOGRAPH WATER;So;0;L; 6C34;;;;N;;;;; +328D;CIRCLED IDEOGRAPH WOOD;So;0;L; 6728;;;;N;;;;; +328E;CIRCLED IDEOGRAPH METAL;So;0;L; 91D1;;;;N;;;;; +328F;CIRCLED IDEOGRAPH EARTH;So;0;L; 571F;;;;N;;;;; +3290;CIRCLED IDEOGRAPH SUN;So;0;L; 65E5;;;;N;;;;; +3291;CIRCLED IDEOGRAPH STOCK;So;0;L; 682A;;;;N;;;;; +3292;CIRCLED IDEOGRAPH HAVE;So;0;L; 6709;;;;N;;;;; +3293;CIRCLED IDEOGRAPH SOCIETY;So;0;L; 793E;;;;N;;;;; +3294;CIRCLED IDEOGRAPH NAME;So;0;L; 540D;;;;N;;;;; +3295;CIRCLED IDEOGRAPH SPECIAL;So;0;L; 7279;;;;N;;;;; +3296;CIRCLED IDEOGRAPH FINANCIAL;So;0;L; 8CA1;;;;N;;;;; +3297;CIRCLED IDEOGRAPH CONGRATULATION;So;0;L; 795D;;;;N;;;;; +3298;CIRCLED IDEOGRAPH LABOR;So;0;L; 52B4;;;;N;;;;; +3299;CIRCLED IDEOGRAPH SECRET;So;0;L; 79D8;;;;N;;;;; +329A;CIRCLED IDEOGRAPH MALE;So;0;L; 7537;;;;N;;;;; +329B;CIRCLED IDEOGRAPH FEMALE;So;0;L; 5973;;;;N;;;;; +329C;CIRCLED IDEOGRAPH SUITABLE;So;0;L; 9069;;;;N;;;;; +329D;CIRCLED IDEOGRAPH EXCELLENT;So;0;L; 512A;;;;N;;;;; +329E;CIRCLED IDEOGRAPH PRINT;So;0;L; 5370;;;;N;;;;; +329F;CIRCLED IDEOGRAPH ATTENTION;So;0;L; 6CE8;;;;N;;;;; +32A0;CIRCLED IDEOGRAPH ITEM;So;0;L; 9805;;;;N;;;;; +32A1;CIRCLED IDEOGRAPH REST;So;0;L; 4F11;;;;N;;;;; +32A2;CIRCLED IDEOGRAPH COPY;So;0;L; 5199;;;;N;;;;; +32A3;CIRCLED IDEOGRAPH CORRECT;So;0;L; 6B63;;;;N;;;;; +32A4;CIRCLED IDEOGRAPH HIGH;So;0;L; 4E0A;;;;N;;;;; +32A5;CIRCLED IDEOGRAPH CENTRE;So;0;L; 4E2D;;;;N;CIRCLED IDEOGRAPH CENTER;;;; +32A6;CIRCLED IDEOGRAPH LOW;So;0;L; 4E0B;;;;N;;;;; +32A7;CIRCLED IDEOGRAPH LEFT;So;0;L; 5DE6;;;;N;;;;; +32A8;CIRCLED IDEOGRAPH RIGHT;So;0;L; 53F3;;;;N;;;;; +32A9;CIRCLED IDEOGRAPH MEDICINE;So;0;L; 533B;;;;N;;;;; +32AA;CIRCLED IDEOGRAPH RELIGION;So;0;L; 5B97;;;;N;;;;; +32AB;CIRCLED IDEOGRAPH STUDY;So;0;L; 5B66;;;;N;;;;; +32AC;CIRCLED IDEOGRAPH SUPERVISE;So;0;L; 76E3;;;;N;;;;; +32AD;CIRCLED IDEOGRAPH ENTERPRISE;So;0;L; 4F01;;;;N;;;;; +32AE;CIRCLED IDEOGRAPH RESOURCE;So;0;L; 8CC7;;;;N;;;;; +32AF;CIRCLED IDEOGRAPH ALLIANCE;So;0;L; 5354;;;;N;;;;; +32B0;CIRCLED IDEOGRAPH NIGHT;So;0;L; 591C;;;;N;;;;; +32B1;CIRCLED NUMBER THIRTY SIX;No;0;ON; 0033 0036;;;36;N;;;;; +32B2;CIRCLED NUMBER THIRTY SEVEN;No;0;ON; 0033 0037;;;37;N;;;;; +32B3;CIRCLED NUMBER THIRTY EIGHT;No;0;ON; 0033 0038;;;38;N;;;;; +32B4;CIRCLED NUMBER THIRTY NINE;No;0;ON; 0033 0039;;;39;N;;;;; +32B5;CIRCLED NUMBER FORTY;No;0;ON; 0034 0030;;;40;N;;;;; +32B6;CIRCLED NUMBER FORTY ONE;No;0;ON; 0034 0031;;;41;N;;;;; +32B7;CIRCLED NUMBER FORTY TWO;No;0;ON; 0034 0032;;;42;N;;;;; +32B8;CIRCLED NUMBER FORTY THREE;No;0;ON; 0034 0033;;;43;N;;;;; +32B9;CIRCLED NUMBER FORTY FOUR;No;0;ON; 0034 0034;;;44;N;;;;; +32BA;CIRCLED NUMBER FORTY FIVE;No;0;ON; 0034 0035;;;45;N;;;;; +32BB;CIRCLED NUMBER FORTY SIX;No;0;ON; 0034 0036;;;46;N;;;;; +32BC;CIRCLED NUMBER FORTY SEVEN;No;0;ON; 0034 0037;;;47;N;;;;; +32BD;CIRCLED NUMBER FORTY EIGHT;No;0;ON; 0034 0038;;;48;N;;;;; +32BE;CIRCLED NUMBER FORTY NINE;No;0;ON; 0034 0039;;;49;N;;;;; +32BF;CIRCLED NUMBER FIFTY;No;0;ON; 0035 0030;;;50;N;;;;; +32C0;IDEOGRAPHIC TELEGRAPH SYMBOL FOR JANUARY;So;0;L; 0031 6708;;;;N;;;;; +32C1;IDEOGRAPHIC TELEGRAPH SYMBOL FOR FEBRUARY;So;0;L; 0032 6708;;;;N;;;;; +32C2;IDEOGRAPHIC TELEGRAPH SYMBOL FOR MARCH;So;0;L; 0033 6708;;;;N;;;;; +32C3;IDEOGRAPHIC TELEGRAPH SYMBOL FOR APRIL;So;0;L; 0034 6708;;;;N;;;;; +32C4;IDEOGRAPHIC TELEGRAPH SYMBOL FOR MAY;So;0;L; 0035 6708;;;;N;;;;; +32C5;IDEOGRAPHIC TELEGRAPH SYMBOL FOR JUNE;So;0;L; 0036 6708;;;;N;;;;; +32C6;IDEOGRAPHIC TELEGRAPH SYMBOL FOR JULY;So;0;L; 0037 6708;;;;N;;;;; +32C7;IDEOGRAPHIC TELEGRAPH SYMBOL FOR AUGUST;So;0;L; 0038 6708;;;;N;;;;; +32C8;IDEOGRAPHIC TELEGRAPH SYMBOL FOR SEPTEMBER;So;0;L; 0039 6708;;;;N;;;;; +32C9;IDEOGRAPHIC TELEGRAPH SYMBOL FOR OCTOBER;So;0;L; 0031 0030 6708;;;;N;;;;; +32CA;IDEOGRAPHIC TELEGRAPH SYMBOL FOR NOVEMBER;So;0;L; 0031 0031 6708;;;;N;;;;; +32CB;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DECEMBER;So;0;L; 0031 0032 6708;;;;N;;;;; +32CC;SQUARE HG;So;0;ON; 0048 0067;;;;N;;;;; +32CD;SQUARE ERG;So;0;ON; 0065 0072 0067;;;;N;;;;; +32CE;SQUARE EV;So;0;ON; 0065 0056;;;;N;;;;; +32CF;LIMITED LIABILITY SIGN;So;0;ON; 004C 0054 0044;;;;N;;;;; +32D0;CIRCLED KATAKANA A;So;0;L; 30A2;;;;N;;;;; +32D1;CIRCLED KATAKANA I;So;0;L; 30A4;;;;N;;;;; +32D2;CIRCLED KATAKANA U;So;0;L; 30A6;;;;N;;;;; +32D3;CIRCLED KATAKANA E;So;0;L; 30A8;;;;N;;;;; +32D4;CIRCLED KATAKANA O;So;0;L; 30AA;;;;N;;;;; +32D5;CIRCLED KATAKANA KA;So;0;L; 30AB;;;;N;;;;; +32D6;CIRCLED KATAKANA KI;So;0;L; 30AD;;;;N;;;;; +32D7;CIRCLED KATAKANA KU;So;0;L; 30AF;;;;N;;;;; +32D8;CIRCLED KATAKANA KE;So;0;L; 30B1;;;;N;;;;; +32D9;CIRCLED KATAKANA KO;So;0;L; 30B3;;;;N;;;;; +32DA;CIRCLED KATAKANA SA;So;0;L; 30B5;;;;N;;;;; +32DB;CIRCLED KATAKANA SI;So;0;L; 30B7;;;;N;;;;; +32DC;CIRCLED KATAKANA SU;So;0;L; 30B9;;;;N;;;;; +32DD;CIRCLED KATAKANA SE;So;0;L; 30BB;;;;N;;;;; +32DE;CIRCLED KATAKANA SO;So;0;L; 30BD;;;;N;;;;; +32DF;CIRCLED KATAKANA TA;So;0;L; 30BF;;;;N;;;;; +32E0;CIRCLED KATAKANA TI;So;0;L; 30C1;;;;N;;;;; +32E1;CIRCLED KATAKANA TU;So;0;L; 30C4;;;;N;;;;; +32E2;CIRCLED KATAKANA TE;So;0;L; 30C6;;;;N;;;;; +32E3;CIRCLED KATAKANA TO;So;0;L; 30C8;;;;N;;;;; +32E4;CIRCLED KATAKANA NA;So;0;L; 30CA;;;;N;;;;; +32E5;CIRCLED KATAKANA NI;So;0;L; 30CB;;;;N;;;;; +32E6;CIRCLED KATAKANA NU;So;0;L; 30CC;;;;N;;;;; +32E7;CIRCLED KATAKANA NE;So;0;L; 30CD;;;;N;;;;; +32E8;CIRCLED KATAKANA NO;So;0;L; 30CE;;;;N;;;;; +32E9;CIRCLED KATAKANA HA;So;0;L; 30CF;;;;N;;;;; +32EA;CIRCLED KATAKANA HI;So;0;L; 30D2;;;;N;;;;; +32EB;CIRCLED KATAKANA HU;So;0;L; 30D5;;;;N;;;;; +32EC;CIRCLED KATAKANA HE;So;0;L; 30D8;;;;N;;;;; +32ED;CIRCLED KATAKANA HO;So;0;L; 30DB;;;;N;;;;; +32EE;CIRCLED KATAKANA MA;So;0;L; 30DE;;;;N;;;;; +32EF;CIRCLED KATAKANA MI;So;0;L; 30DF;;;;N;;;;; +32F0;CIRCLED KATAKANA MU;So;0;L; 30E0;;;;N;;;;; +32F1;CIRCLED KATAKANA ME;So;0;L; 30E1;;;;N;;;;; +32F2;CIRCLED KATAKANA MO;So;0;L; 30E2;;;;N;;;;; +32F3;CIRCLED KATAKANA YA;So;0;L; 30E4;;;;N;;;;; +32F4;CIRCLED KATAKANA YU;So;0;L; 30E6;;;;N;;;;; +32F5;CIRCLED KATAKANA YO;So;0;L; 30E8;;;;N;;;;; +32F6;CIRCLED KATAKANA RA;So;0;L; 30E9;;;;N;;;;; +32F7;CIRCLED KATAKANA RI;So;0;L; 30EA;;;;N;;;;; +32F8;CIRCLED KATAKANA RU;So;0;L; 30EB;;;;N;;;;; +32F9;CIRCLED KATAKANA RE;So;0;L; 30EC;;;;N;;;;; +32FA;CIRCLED KATAKANA RO;So;0;L; 30ED;;;;N;;;;; +32FB;CIRCLED KATAKANA WA;So;0;L; 30EF;;;;N;;;;; +32FC;CIRCLED KATAKANA WI;So;0;L; 30F0;;;;N;;;;; +32FD;CIRCLED KATAKANA WE;So;0;L; 30F1;;;;N;;;;; +32FE;CIRCLED KATAKANA WO;So;0;L; 30F2;;;;N;;;;; +3300;SQUARE APAATO;So;0;L; 30A2 30D1 30FC 30C8;;;;N;SQUARED APAATO;;;; +3301;SQUARE ARUHUA;So;0;L; 30A2 30EB 30D5 30A1;;;;N;SQUARED ARUHUA;;;; +3302;SQUARE ANPEA;So;0;L; 30A2 30F3 30DA 30A2;;;;N;SQUARED ANPEA;;;; +3303;SQUARE AARU;So;0;L; 30A2 30FC 30EB;;;;N;SQUARED AARU;;;; +3304;SQUARE ININGU;So;0;L; 30A4 30CB 30F3 30B0;;;;N;SQUARED ININGU;;;; +3305;SQUARE INTI;So;0;L; 30A4 30F3 30C1;;;;N;SQUARED INTI;;;; +3306;SQUARE UON;So;0;L; 30A6 30A9 30F3;;;;N;SQUARED UON;;;; +3307;SQUARE ESUKUUDO;So;0;L; 30A8 30B9 30AF 30FC 30C9;;;;N;SQUARED ESUKUUDO;;;; +3308;SQUARE EEKAA;So;0;L; 30A8 30FC 30AB 30FC;;;;N;SQUARED EEKAA;;;; +3309;SQUARE ONSU;So;0;L; 30AA 30F3 30B9;;;;N;SQUARED ONSU;;;; +330A;SQUARE OOMU;So;0;L; 30AA 30FC 30E0;;;;N;SQUARED OOMU;;;; +330B;SQUARE KAIRI;So;0;L; 30AB 30A4 30EA;;;;N;SQUARED KAIRI;;;; +330C;SQUARE KARATTO;So;0;L; 30AB 30E9 30C3 30C8;;;;N;SQUARED KARATTO;;;; +330D;SQUARE KARORII;So;0;L; 30AB 30ED 30EA 30FC;;;;N;SQUARED KARORII;;;; +330E;SQUARE GARON;So;0;L; 30AC 30ED 30F3;;;;N;SQUARED GARON;;;; +330F;SQUARE GANMA;So;0;L; 30AC 30F3 30DE;;;;N;SQUARED GANMA;;;; +3310;SQUARE GIGA;So;0;L; 30AE 30AC;;;;N;SQUARED GIGA;;;; +3311;SQUARE GINII;So;0;L; 30AE 30CB 30FC;;;;N;SQUARED GINII;;;; +3312;SQUARE KYURII;So;0;L; 30AD 30E5 30EA 30FC;;;;N;SQUARED KYURII;;;; +3313;SQUARE GIRUDAA;So;0;L; 30AE 30EB 30C0 30FC;;;;N;SQUARED GIRUDAA;;;; +3314;SQUARE KIRO;So;0;L; 30AD 30ED;;;;N;SQUARED KIRO;;;; +3315;SQUARE KIROGURAMU;So;0;L; 30AD 30ED 30B0 30E9 30E0;;;;N;SQUARED KIROGURAMU;;;; +3316;SQUARE KIROMEETORU;So;0;L; 30AD 30ED 30E1 30FC 30C8 30EB;;;;N;SQUARED KIROMEETORU;;;; +3317;SQUARE KIROWATTO;So;0;L; 30AD 30ED 30EF 30C3 30C8;;;;N;SQUARED KIROWATTO;;;; +3318;SQUARE GURAMU;So;0;L; 30B0 30E9 30E0;;;;N;SQUARED GURAMU;;;; +3319;SQUARE GURAMUTON;So;0;L; 30B0 30E9 30E0 30C8 30F3;;;;N;SQUARED GURAMUTON;;;; +331A;SQUARE KURUZEIRO;So;0;L; 30AF 30EB 30BC 30A4 30ED;;;;N;SQUARED KURUZEIRO;;;; +331B;SQUARE KUROONE;So;0;L; 30AF 30ED 30FC 30CD;;;;N;SQUARED KUROONE;;;; +331C;SQUARE KEESU;So;0;L; 30B1 30FC 30B9;;;;N;SQUARED KEESU;;;; +331D;SQUARE KORUNA;So;0;L; 30B3 30EB 30CA;;;;N;SQUARED KORUNA;;;; +331E;SQUARE KOOPO;So;0;L; 30B3 30FC 30DD;;;;N;SQUARED KOOPO;;;; +331F;SQUARE SAIKURU;So;0;L; 30B5 30A4 30AF 30EB;;;;N;SQUARED SAIKURU;;;; +3320;SQUARE SANTIIMU;So;0;L; 30B5 30F3 30C1 30FC 30E0;;;;N;SQUARED SANTIIMU;;;; +3321;SQUARE SIRINGU;So;0;L; 30B7 30EA 30F3 30B0;;;;N;SQUARED SIRINGU;;;; +3322;SQUARE SENTI;So;0;L; 30BB 30F3 30C1;;;;N;SQUARED SENTI;;;; +3323;SQUARE SENTO;So;0;L; 30BB 30F3 30C8;;;;N;SQUARED SENTO;;;; +3324;SQUARE DAASU;So;0;L; 30C0 30FC 30B9;;;;N;SQUARED DAASU;;;; +3325;SQUARE DESI;So;0;L; 30C7 30B7;;;;N;SQUARED DESI;;;; +3326;SQUARE DORU;So;0;L; 30C9 30EB;;;;N;SQUARED DORU;;;; +3327;SQUARE TON;So;0;L; 30C8 30F3;;;;N;SQUARED TON;;;; +3328;SQUARE NANO;So;0;L; 30CA 30CE;;;;N;SQUARED NANO;;;; +3329;SQUARE NOTTO;So;0;L; 30CE 30C3 30C8;;;;N;SQUARED NOTTO;;;; +332A;SQUARE HAITU;So;0;L; 30CF 30A4 30C4;;;;N;SQUARED HAITU;;;; +332B;SQUARE PAASENTO;So;0;L; 30D1 30FC 30BB 30F3 30C8;;;;N;SQUARED PAASENTO;;;; +332C;SQUARE PAATU;So;0;L; 30D1 30FC 30C4;;;;N;SQUARED PAATU;;;; +332D;SQUARE BAARERU;So;0;L; 30D0 30FC 30EC 30EB;;;;N;SQUARED BAARERU;;;; +332E;SQUARE PIASUTORU;So;0;L; 30D4 30A2 30B9 30C8 30EB;;;;N;SQUARED PIASUTORU;;;; +332F;SQUARE PIKURU;So;0;L; 30D4 30AF 30EB;;;;N;SQUARED PIKURU;;;; +3330;SQUARE PIKO;So;0;L; 30D4 30B3;;;;N;SQUARED PIKO;;;; +3331;SQUARE BIRU;So;0;L; 30D3 30EB;;;;N;SQUARED BIRU;;;; +3332;SQUARE HUARADDO;So;0;L; 30D5 30A1 30E9 30C3 30C9;;;;N;SQUARED HUARADDO;;;; +3333;SQUARE HUIITO;So;0;L; 30D5 30A3 30FC 30C8;;;;N;SQUARED HUIITO;;;; +3334;SQUARE BUSSYERU;So;0;L; 30D6 30C3 30B7 30A7 30EB;;;;N;SQUARED BUSSYERU;;;; +3335;SQUARE HURAN;So;0;L; 30D5 30E9 30F3;;;;N;SQUARED HURAN;;;; +3336;SQUARE HEKUTAARU;So;0;L; 30D8 30AF 30BF 30FC 30EB;;;;N;SQUARED HEKUTAARU;;;; +3337;SQUARE PESO;So;0;L; 30DA 30BD;;;;N;SQUARED PESO;;;; +3338;SQUARE PENIHI;So;0;L; 30DA 30CB 30D2;;;;N;SQUARED PENIHI;;;; +3339;SQUARE HERUTU;So;0;L; 30D8 30EB 30C4;;;;N;SQUARED HERUTU;;;; +333A;SQUARE PENSU;So;0;L; 30DA 30F3 30B9;;;;N;SQUARED PENSU;;;; +333B;SQUARE PEEZI;So;0;L; 30DA 30FC 30B8;;;;N;SQUARED PEEZI;;;; +333C;SQUARE BEETA;So;0;L; 30D9 30FC 30BF;;;;N;SQUARED BEETA;;;; +333D;SQUARE POINTO;So;0;L; 30DD 30A4 30F3 30C8;;;;N;SQUARED POINTO;;;; +333E;SQUARE BORUTO;So;0;L; 30DC 30EB 30C8;;;;N;SQUARED BORUTO;;;; +333F;SQUARE HON;So;0;L; 30DB 30F3;;;;N;SQUARED HON;;;; +3340;SQUARE PONDO;So;0;L; 30DD 30F3 30C9;;;;N;SQUARED PONDO;;;; +3341;SQUARE HOORU;So;0;L; 30DB 30FC 30EB;;;;N;SQUARED HOORU;;;; +3342;SQUARE HOON;So;0;L; 30DB 30FC 30F3;;;;N;SQUARED HOON;;;; +3343;SQUARE MAIKURO;So;0;L; 30DE 30A4 30AF 30ED;;;;N;SQUARED MAIKURO;;;; +3344;SQUARE MAIRU;So;0;L; 30DE 30A4 30EB;;;;N;SQUARED MAIRU;;;; +3345;SQUARE MAHHA;So;0;L; 30DE 30C3 30CF;;;;N;SQUARED MAHHA;;;; +3346;SQUARE MARUKU;So;0;L; 30DE 30EB 30AF;;;;N;SQUARED MARUKU;;;; +3347;SQUARE MANSYON;So;0;L; 30DE 30F3 30B7 30E7 30F3;;;;N;SQUARED MANSYON;;;; +3348;SQUARE MIKURON;So;0;L; 30DF 30AF 30ED 30F3;;;;N;SQUARED MIKURON;;;; +3349;SQUARE MIRI;So;0;L; 30DF 30EA;;;;N;SQUARED MIRI;;;; +334A;SQUARE MIRIBAARU;So;0;L; 30DF 30EA 30D0 30FC 30EB;;;;N;SQUARED MIRIBAARU;;;; +334B;SQUARE MEGA;So;0;L; 30E1 30AC;;;;N;SQUARED MEGA;;;; +334C;SQUARE MEGATON;So;0;L; 30E1 30AC 30C8 30F3;;;;N;SQUARED MEGATON;;;; +334D;SQUARE MEETORU;So;0;L; 30E1 30FC 30C8 30EB;;;;N;SQUARED MEETORU;;;; +334E;SQUARE YAADO;So;0;L; 30E4 30FC 30C9;;;;N;SQUARED YAADO;;;; +334F;SQUARE YAARU;So;0;L; 30E4 30FC 30EB;;;;N;SQUARED YAARU;;;; +3350;SQUARE YUAN;So;0;L; 30E6 30A2 30F3;;;;N;SQUARED YUAN;;;; +3351;SQUARE RITTORU;So;0;L; 30EA 30C3 30C8 30EB;;;;N;SQUARED RITTORU;;;; +3352;SQUARE RIRA;So;0;L; 30EA 30E9;;;;N;SQUARED RIRA;;;; +3353;SQUARE RUPII;So;0;L; 30EB 30D4 30FC;;;;N;SQUARED RUPII;;;; +3354;SQUARE RUUBURU;So;0;L; 30EB 30FC 30D6 30EB;;;;N;SQUARED RUUBURU;;;; +3355;SQUARE REMU;So;0;L; 30EC 30E0;;;;N;SQUARED REMU;;;; +3356;SQUARE RENTOGEN;So;0;L; 30EC 30F3 30C8 30B2 30F3;;;;N;SQUARED RENTOGEN;;;; +3357;SQUARE WATTO;So;0;L; 30EF 30C3 30C8;;;;N;SQUARED WATTO;;;; +3358;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ZERO;So;0;L; 0030 70B9;;;;N;;;;; +3359;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ONE;So;0;L; 0031 70B9;;;;N;;;;; +335A;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWO;So;0;L; 0032 70B9;;;;N;;;;; +335B;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR THREE;So;0;L; 0033 70B9;;;;N;;;;; +335C;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FOUR;So;0;L; 0034 70B9;;;;N;;;;; +335D;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FIVE;So;0;L; 0035 70B9;;;;N;;;;; +335E;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SIX;So;0;L; 0036 70B9;;;;N;;;;; +335F;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SEVEN;So;0;L; 0037 70B9;;;;N;;;;; +3360;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR EIGHT;So;0;L; 0038 70B9;;;;N;;;;; +3361;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR NINE;So;0;L; 0039 70B9;;;;N;;;;; +3362;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TEN;So;0;L; 0031 0030 70B9;;;;N;;;;; +3363;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ELEVEN;So;0;L; 0031 0031 70B9;;;;N;;;;; +3364;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWELVE;So;0;L; 0031 0032 70B9;;;;N;;;;; +3365;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR THIRTEEN;So;0;L; 0031 0033 70B9;;;;N;;;;; +3366;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FOURTEEN;So;0;L; 0031 0034 70B9;;;;N;;;;; +3367;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FIFTEEN;So;0;L; 0031 0035 70B9;;;;N;;;;; +3368;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SIXTEEN;So;0;L; 0031 0036 70B9;;;;N;;;;; +3369;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SEVENTEEN;So;0;L; 0031 0037 70B9;;;;N;;;;; +336A;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR EIGHTEEN;So;0;L; 0031 0038 70B9;;;;N;;;;; +336B;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR NINETEEN;So;0;L; 0031 0039 70B9;;;;N;;;;; +336C;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY;So;0;L; 0032 0030 70B9;;;;N;;;;; +336D;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-ONE;So;0;L; 0032 0031 70B9;;;;N;;;;; +336E;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-TWO;So;0;L; 0032 0032 70B9;;;;N;;;;; +336F;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-THREE;So;0;L; 0032 0033 70B9;;;;N;;;;; +3370;IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-FOUR;So;0;L; 0032 0034 70B9;;;;N;;;;; +3371;SQUARE HPA;So;0;L; 0068 0050 0061;;;;N;;;;; +3372;SQUARE DA;So;0;L; 0064 0061;;;;N;;;;; +3373;SQUARE AU;So;0;L; 0041 0055;;;;N;;;;; +3374;SQUARE BAR;So;0;L; 0062 0061 0072;;;;N;;;;; +3375;SQUARE OV;So;0;L; 006F 0056;;;;N;;;;; +3376;SQUARE PC;So;0;L; 0070 0063;;;;N;;;;; +3377;SQUARE DM;So;0;ON; 0064 006D;;;;N;;;;; +3378;SQUARE DM SQUARED;So;0;ON; 0064 006D 00B2;;;;N;;;;; +3379;SQUARE DM CUBED;So;0;ON; 0064 006D 00B3;;;;N;;;;; +337A;SQUARE IU;So;0;ON; 0049 0055;;;;N;;;;; +337B;SQUARE ERA NAME HEISEI;So;0;L; 5E73 6210;;;;N;SQUARED TWO IDEOGRAPHS ERA NAME HEISEI;;;; +337C;SQUARE ERA NAME SYOUWA;So;0;L; 662D 548C;;;;N;SQUARED TWO IDEOGRAPHS ERA NAME SYOUWA;;;; +337D;SQUARE ERA NAME TAISYOU;So;0;L; 5927 6B63;;;;N;SQUARED TWO IDEOGRAPHS ERA NAME TAISYOU;;;; +337E;SQUARE ERA NAME MEIZI;So;0;L; 660E 6CBB;;;;N;SQUARED TWO IDEOGRAPHS ERA NAME MEIZI;;;; +337F;SQUARE CORPORATION;So;0;L; 682A 5F0F 4F1A 793E;;;;N;SQUARED FOUR IDEOGRAPHS CORPORATION;;;; +3380;SQUARE PA AMPS;So;0;L; 0070 0041;;;;N;SQUARED PA AMPS;;;; +3381;SQUARE NA;So;0;L; 006E 0041;;;;N;SQUARED NA;;;; +3382;SQUARE MU A;So;0;L; 03BC 0041;;;;N;SQUARED MU A;;;; +3383;SQUARE MA;So;0;L; 006D 0041;;;;N;SQUARED MA;;;; +3384;SQUARE KA;So;0;L; 006B 0041;;;;N;SQUARED KA;;;; +3385;SQUARE KB;So;0;L; 004B 0042;;;;N;SQUARED KB;;;; +3386;SQUARE MB;So;0;L; 004D 0042;;;;N;SQUARED MB;;;; +3387;SQUARE GB;So;0;L; 0047 0042;;;;N;SQUARED GB;;;; +3388;SQUARE CAL;So;0;L; 0063 0061 006C;;;;N;SQUARED CAL;;;; +3389;SQUARE KCAL;So;0;L; 006B 0063 0061 006C;;;;N;SQUARED KCAL;;;; +338A;SQUARE PF;So;0;L; 0070 0046;;;;N;SQUARED PF;;;; +338B;SQUARE NF;So;0;L; 006E 0046;;;;N;SQUARED NF;;;; +338C;SQUARE MU F;So;0;L; 03BC 0046;;;;N;SQUARED MU F;;;; +338D;SQUARE MU G;So;0;L; 03BC 0067;;;;N;SQUARED MU G;;;; +338E;SQUARE MG;So;0;L; 006D 0067;;;;N;SQUARED MG;;;; +338F;SQUARE KG;So;0;L; 006B 0067;;;;N;SQUARED KG;;;; +3390;SQUARE HZ;So;0;L; 0048 007A;;;;N;SQUARED HZ;;;; +3391;SQUARE KHZ;So;0;L; 006B 0048 007A;;;;N;SQUARED KHZ;;;; +3392;SQUARE MHZ;So;0;L; 004D 0048 007A;;;;N;SQUARED MHZ;;;; +3393;SQUARE GHZ;So;0;L; 0047 0048 007A;;;;N;SQUARED GHZ;;;; +3394;SQUARE THZ;So;0;L; 0054 0048 007A;;;;N;SQUARED THZ;;;; +3395;SQUARE MU L;So;0;L; 03BC 2113;;;;N;SQUARED MU L;;;; +3396;SQUARE ML;So;0;L; 006D 2113;;;;N;SQUARED ML;;;; +3397;SQUARE DL;So;0;L; 0064 2113;;;;N;SQUARED DL;;;; +3398;SQUARE KL;So;0;L; 006B 2113;;;;N;SQUARED KL;;;; +3399;SQUARE FM;So;0;L; 0066 006D;;;;N;SQUARED FM;;;; +339A;SQUARE NM;So;0;L; 006E 006D;;;;N;SQUARED NM;;;; +339B;SQUARE MU M;So;0;L; 03BC 006D;;;;N;SQUARED MU M;;;; +339C;SQUARE MM;So;0;L; 006D 006D;;;;N;SQUARED MM;;;; +339D;SQUARE CM;So;0;L; 0063 006D;;;;N;SQUARED CM;;;; +339E;SQUARE KM;So;0;L; 006B 006D;;;;N;SQUARED KM;;;; +339F;SQUARE MM SQUARED;So;0;L; 006D 006D 00B2;;;;N;SQUARED MM SQUARED;;;; +33A0;SQUARE CM SQUARED;So;0;L; 0063 006D 00B2;;;;N;SQUARED CM SQUARED;;;; +33A1;SQUARE M SQUARED;So;0;L; 006D 00B2;;;;N;SQUARED M SQUARED;;;; +33A2;SQUARE KM SQUARED;So;0;L; 006B 006D 00B2;;;;N;SQUARED KM SQUARED;;;; +33A3;SQUARE MM CUBED;So;0;L; 006D 006D 00B3;;;;N;SQUARED MM CUBED;;;; +33A4;SQUARE CM CUBED;So;0;L; 0063 006D 00B3;;;;N;SQUARED CM CUBED;;;; +33A5;SQUARE M CUBED;So;0;L; 006D 00B3;;;;N;SQUARED M CUBED;;;; +33A6;SQUARE KM CUBED;So;0;L; 006B 006D 00B3;;;;N;SQUARED KM CUBED;;;; +33A7;SQUARE M OVER S;So;0;L; 006D 2215 0073;;;;N;SQUARED M OVER S;;;; +33A8;SQUARE M OVER S SQUARED;So;0;L; 006D 2215 0073 00B2;;;;N;SQUARED M OVER S SQUARED;;;; +33A9;SQUARE PA;So;0;L; 0050 0061;;;;N;SQUARED PA;;;; +33AA;SQUARE KPA;So;0;L; 006B 0050 0061;;;;N;SQUARED KPA;;;; +33AB;SQUARE MPA;So;0;L; 004D 0050 0061;;;;N;SQUARED MPA;;;; +33AC;SQUARE GPA;So;0;L; 0047 0050 0061;;;;N;SQUARED GPA;;;; +33AD;SQUARE RAD;So;0;L; 0072 0061 0064;;;;N;SQUARED RAD;;;; +33AE;SQUARE RAD OVER S;So;0;L; 0072 0061 0064 2215 0073;;;;N;SQUARED RAD OVER S;;;; +33AF;SQUARE RAD OVER S SQUARED;So;0;L; 0072 0061 0064 2215 0073 00B2;;;;N;SQUARED RAD OVER S SQUARED;;;; +33B0;SQUARE PS;So;0;L; 0070 0073;;;;N;SQUARED PS;;;; +33B1;SQUARE NS;So;0;L; 006E 0073;;;;N;SQUARED NS;;;; +33B2;SQUARE MU S;So;0;L; 03BC 0073;;;;N;SQUARED MU S;;;; +33B3;SQUARE MS;So;0;L; 006D 0073;;;;N;SQUARED MS;;;; +33B4;SQUARE PV;So;0;L; 0070 0056;;;;N;SQUARED PV;;;; +33B5;SQUARE NV;So;0;L; 006E 0056;;;;N;SQUARED NV;;;; +33B6;SQUARE MU V;So;0;L; 03BC 0056;;;;N;SQUARED MU V;;;; +33B7;SQUARE MV;So;0;L; 006D 0056;;;;N;SQUARED MV;;;; +33B8;SQUARE KV;So;0;L; 006B 0056;;;;N;SQUARED KV;;;; +33B9;SQUARE MV MEGA;So;0;L; 004D 0056;;;;N;SQUARED MV MEGA;;;; +33BA;SQUARE PW;So;0;L; 0070 0057;;;;N;SQUARED PW;;;; +33BB;SQUARE NW;So;0;L; 006E 0057;;;;N;SQUARED NW;;;; +33BC;SQUARE MU W;So;0;L; 03BC 0057;;;;N;SQUARED MU W;;;; +33BD;SQUARE MW;So;0;L; 006D 0057;;;;N;SQUARED MW;;;; +33BE;SQUARE KW;So;0;L; 006B 0057;;;;N;SQUARED KW;;;; +33BF;SQUARE MW MEGA;So;0;L; 004D 0057;;;;N;SQUARED MW MEGA;;;; +33C0;SQUARE K OHM;So;0;L; 006B 03A9;;;;N;SQUARED K OHM;;;; +33C1;SQUARE M OHM;So;0;L; 004D 03A9;;;;N;SQUARED M OHM;;;; +33C2;SQUARE AM;So;0;L; 0061 002E 006D 002E;;;;N;SQUARED AM;;;; +33C3;SQUARE BQ;So;0;L; 0042 0071;;;;N;SQUARED BQ;;;; +33C4;SQUARE CC;So;0;L; 0063 0063;;;;N;SQUARED CC;;;; +33C5;SQUARE CD;So;0;L; 0063 0064;;;;N;SQUARED CD;;;; +33C6;SQUARE C OVER KG;So;0;L; 0043 2215 006B 0067;;;;N;SQUARED C OVER KG;;;; +33C7;SQUARE CO;So;0;L; 0043 006F 002E;;;;N;SQUARED CO;;;; +33C8;SQUARE DB;So;0;L; 0064 0042;;;;N;SQUARED DB;;;; +33C9;SQUARE GY;So;0;L; 0047 0079;;;;N;SQUARED GY;;;; +33CA;SQUARE HA;So;0;L; 0068 0061;;;;N;SQUARED HA;;;; +33CB;SQUARE HP;So;0;L; 0048 0050;;;;N;SQUARED HP;;;; +33CC;SQUARE IN;So;0;L; 0069 006E;;;;N;SQUARED IN;;;; +33CD;SQUARE KK;So;0;L; 004B 004B;;;;N;SQUARED KK;;;; +33CE;SQUARE KM CAPITAL;So;0;L; 004B 004D;;;;N;SQUARED KM CAPITAL;;;; +33CF;SQUARE KT;So;0;L; 006B 0074;;;;N;SQUARED KT;;;; +33D0;SQUARE LM;So;0;L; 006C 006D;;;;N;SQUARED LM;;;; +33D1;SQUARE LN;So;0;L; 006C 006E;;;;N;SQUARED LN;;;; +33D2;SQUARE LOG;So;0;L; 006C 006F 0067;;;;N;SQUARED LOG;;;; +33D3;SQUARE LX;So;0;L; 006C 0078;;;;N;SQUARED LX;;;; +33D4;SQUARE MB SMALL;So;0;L; 006D 0062;;;;N;SQUARED MB SMALL;;;; +33D5;SQUARE MIL;So;0;L; 006D 0069 006C;;;;N;SQUARED MIL;;;; +33D6;SQUARE MOL;So;0;L; 006D 006F 006C;;;;N;SQUARED MOL;;;; +33D7;SQUARE PH;So;0;L; 0050 0048;;;;N;SQUARED PH;;;; +33D8;SQUARE PM;So;0;L; 0070 002E 006D 002E;;;;N;SQUARED PM;;;; +33D9;SQUARE PPM;So;0;L; 0050 0050 004D;;;;N;SQUARED PPM;;;; +33DA;SQUARE PR;So;0;L; 0050 0052;;;;N;SQUARED PR;;;; +33DB;SQUARE SR;So;0;L; 0073 0072;;;;N;SQUARED SR;;;; +33DC;SQUARE SV;So;0;L; 0053 0076;;;;N;SQUARED SV;;;; +33DD;SQUARE WB;So;0;L; 0057 0062;;;;N;SQUARED WB;;;; +33DE;SQUARE V OVER M;So;0;ON; 0056 2215 006D;;;;N;;;;; +33DF;SQUARE A OVER M;So;0;ON; 0041 2215 006D;;;;N;;;;; +33E0;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY ONE;So;0;L; 0031 65E5;;;;N;;;;; +33E1;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWO;So;0;L; 0032 65E5;;;;N;;;;; +33E2;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THREE;So;0;L; 0033 65E5;;;;N;;;;; +33E3;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FOUR;So;0;L; 0034 65E5;;;;N;;;;; +33E4;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FIVE;So;0;L; 0035 65E5;;;;N;;;;; +33E5;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SIX;So;0;L; 0036 65E5;;;;N;;;;; +33E6;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SEVEN;So;0;L; 0037 65E5;;;;N;;;;; +33E7;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY EIGHT;So;0;L; 0038 65E5;;;;N;;;;; +33E8;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY NINE;So;0;L; 0039 65E5;;;;N;;;;; +33E9;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TEN;So;0;L; 0031 0030 65E5;;;;N;;;;; +33EA;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY ELEVEN;So;0;L; 0031 0031 65E5;;;;N;;;;; +33EB;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWELVE;So;0;L; 0031 0032 65E5;;;;N;;;;; +33EC;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTEEN;So;0;L; 0031 0033 65E5;;;;N;;;;; +33ED;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FOURTEEN;So;0;L; 0031 0034 65E5;;;;N;;;;; +33EE;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FIFTEEN;So;0;L; 0031 0035 65E5;;;;N;;;;; +33EF;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SIXTEEN;So;0;L; 0031 0036 65E5;;;;N;;;;; +33F0;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SEVENTEEN;So;0;L; 0031 0037 65E5;;;;N;;;;; +33F1;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY EIGHTEEN;So;0;L; 0031 0038 65E5;;;;N;;;;; +33F2;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY NINETEEN;So;0;L; 0031 0039 65E5;;;;N;;;;; +33F3;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY;So;0;L; 0032 0030 65E5;;;;N;;;;; +33F4;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-ONE;So;0;L; 0032 0031 65E5;;;;N;;;;; +33F5;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-TWO;So;0;L; 0032 0032 65E5;;;;N;;;;; +33F6;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-THREE;So;0;L; 0032 0033 65E5;;;;N;;;;; +33F7;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-FOUR;So;0;L; 0032 0034 65E5;;;;N;;;;; +33F8;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-FIVE;So;0;L; 0032 0035 65E5;;;;N;;;;; +33F9;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-SIX;So;0;L; 0032 0036 65E5;;;;N;;;;; +33FA;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-SEVEN;So;0;L; 0032 0037 65E5;;;;N;;;;; +33FB;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-EIGHT;So;0;L; 0032 0038 65E5;;;;N;;;;; +33FC;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-NINE;So;0;L; 0032 0039 65E5;;;;N;;;;; +33FD;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTY;So;0;L; 0033 0030 65E5;;;;N;;;;; +33FE;IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTY-ONE;So;0;L; 0033 0031 65E5;;;;N;;;;; +33FF;SQUARE GAL;So;0;ON; 0067 0061 006C;;;;N;;;;; +3400;;Lo;0;L;;;;;N;;;;; +4DB5;;Lo;0;L;;;;;N;;;;; +4DC0;HEXAGRAM FOR THE CREATIVE HEAVEN;So;0;ON;;;;;N;;;;; +4DC1;HEXAGRAM FOR THE RECEPTIVE EARTH;So;0;ON;;;;;N;;;;; +4DC2;HEXAGRAM FOR DIFFICULTY AT THE BEGINNING;So;0;ON;;;;;N;;;;; +4DC3;HEXAGRAM FOR YOUTHFUL FOLLY;So;0;ON;;;;;N;;;;; +4DC4;HEXAGRAM FOR WAITING;So;0;ON;;;;;N;;;;; +4DC5;HEXAGRAM FOR CONFLICT;So;0;ON;;;;;N;;;;; +4DC6;HEXAGRAM FOR THE ARMY;So;0;ON;;;;;N;;;;; +4DC7;HEXAGRAM FOR HOLDING TOGETHER;So;0;ON;;;;;N;;;;; +4DC8;HEXAGRAM FOR SMALL TAMING;So;0;ON;;;;;N;;;;; +4DC9;HEXAGRAM FOR TREADING;So;0;ON;;;;;N;;;;; +4DCA;HEXAGRAM FOR PEACE;So;0;ON;;;;;N;;;;; +4DCB;HEXAGRAM FOR STANDSTILL;So;0;ON;;;;;N;;;;; +4DCC;HEXAGRAM FOR FELLOWSHIP;So;0;ON;;;;;N;;;;; +4DCD;HEXAGRAM FOR GREAT POSSESSION;So;0;ON;;;;;N;;;;; +4DCE;HEXAGRAM FOR MODESTY;So;0;ON;;;;;N;;;;; +4DCF;HEXAGRAM FOR ENTHUSIASM;So;0;ON;;;;;N;;;;; +4DD0;HEXAGRAM FOR FOLLOWING;So;0;ON;;;;;N;;;;; +4DD1;HEXAGRAM FOR WORK ON THE DECAYED;So;0;ON;;;;;N;;;;; +4DD2;HEXAGRAM FOR APPROACH;So;0;ON;;;;;N;;;;; +4DD3;HEXAGRAM FOR CONTEMPLATION;So;0;ON;;;;;N;;;;; +4DD4;HEXAGRAM FOR BITING THROUGH;So;0;ON;;;;;N;;;;; +4DD5;HEXAGRAM FOR GRACE;So;0;ON;;;;;N;;;;; +4DD6;HEXAGRAM FOR SPLITTING APART;So;0;ON;;;;;N;;;;; +4DD7;HEXAGRAM FOR RETURN;So;0;ON;;;;;N;;;;; +4DD8;HEXAGRAM FOR INNOCENCE;So;0;ON;;;;;N;;;;; +4DD9;HEXAGRAM FOR GREAT TAMING;So;0;ON;;;;;N;;;;; +4DDA;HEXAGRAM FOR MOUTH CORNERS;So;0;ON;;;;;N;;;;; +4DDB;HEXAGRAM FOR GREAT PREPONDERANCE;So;0;ON;;;;;N;;;;; +4DDC;HEXAGRAM FOR THE ABYSMAL WATER;So;0;ON;;;;;N;;;;; +4DDD;HEXAGRAM FOR THE CLINGING FIRE;So;0;ON;;;;;N;;;;; +4DDE;HEXAGRAM FOR INFLUENCE;So;0;ON;;;;;N;;;;; +4DDF;HEXAGRAM FOR DURATION;So;0;ON;;;;;N;;;;; +4DE0;HEXAGRAM FOR RETREAT;So;0;ON;;;;;N;;;;; +4DE1;HEXAGRAM FOR GREAT POWER;So;0;ON;;;;;N;;;;; +4DE2;HEXAGRAM FOR PROGRESS;So;0;ON;;;;;N;;;;; +4DE3;HEXAGRAM FOR DARKENING OF THE LIGHT;So;0;ON;;;;;N;;;;; +4DE4;HEXAGRAM FOR THE FAMILY;So;0;ON;;;;;N;;;;; +4DE5;HEXAGRAM FOR OPPOSITION;So;0;ON;;;;;N;;;;; +4DE6;HEXAGRAM FOR OBSTRUCTION;So;0;ON;;;;;N;;;;; +4DE7;HEXAGRAM FOR DELIVERANCE;So;0;ON;;;;;N;;;;; +4DE8;HEXAGRAM FOR DECREASE;So;0;ON;;;;;N;;;;; +4DE9;HEXAGRAM FOR INCREASE;So;0;ON;;;;;N;;;;; +4DEA;HEXAGRAM FOR BREAKTHROUGH;So;0;ON;;;;;N;;;;; +4DEB;HEXAGRAM FOR COMING TO MEET;So;0;ON;;;;;N;;;;; +4DEC;HEXAGRAM FOR GATHERING TOGETHER;So;0;ON;;;;;N;;;;; +4DED;HEXAGRAM FOR PUSHING UPWARD;So;0;ON;;;;;N;;;;; +4DEE;HEXAGRAM FOR OPPRESSION;So;0;ON;;;;;N;;;;; +4DEF;HEXAGRAM FOR THE WELL;So;0;ON;;;;;N;;;;; +4DF0;HEXAGRAM FOR REVOLUTION;So;0;ON;;;;;N;;;;; +4DF1;HEXAGRAM FOR THE CAULDRON;So;0;ON;;;;;N;;;;; +4DF2;HEXAGRAM FOR THE AROUSING THUNDER;So;0;ON;;;;;N;;;;; +4DF3;HEXAGRAM FOR THE KEEPING STILL MOUNTAIN;So;0;ON;;;;;N;;;;; +4DF4;HEXAGRAM FOR DEVELOPMENT;So;0;ON;;;;;N;;;;; +4DF5;HEXAGRAM FOR THE MARRYING MAIDEN;So;0;ON;;;;;N;;;;; +4DF6;HEXAGRAM FOR ABUNDANCE;So;0;ON;;;;;N;;;;; +4DF7;HEXAGRAM FOR THE WANDERER;So;0;ON;;;;;N;;;;; +4DF8;HEXAGRAM FOR THE GENTLE WIND;So;0;ON;;;;;N;;;;; +4DF9;HEXAGRAM FOR THE JOYOUS LAKE;So;0;ON;;;;;N;;;;; +4DFA;HEXAGRAM FOR DISPERSION;So;0;ON;;;;;N;;;;; +4DFB;HEXAGRAM FOR LIMITATION;So;0;ON;;;;;N;;;;; +4DFC;HEXAGRAM FOR INNER TRUTH;So;0;ON;;;;;N;;;;; +4DFD;HEXAGRAM FOR SMALL PREPONDERANCE;So;0;ON;;;;;N;;;;; +4DFE;HEXAGRAM FOR AFTER COMPLETION;So;0;ON;;;;;N;;;;; +4DFF;HEXAGRAM FOR BEFORE COMPLETION;So;0;ON;;;;;N;;;;; +4E00;;Lo;0;L;;;;;N;;;;; +9FCC;;Lo;0;L;;;;;N;;;;; +A000;YI SYLLABLE IT;Lo;0;L;;;;;N;;;;; +A001;YI SYLLABLE IX;Lo;0;L;;;;;N;;;;; +A002;YI SYLLABLE I;Lo;0;L;;;;;N;;;;; +A003;YI SYLLABLE IP;Lo;0;L;;;;;N;;;;; +A004;YI SYLLABLE IET;Lo;0;L;;;;;N;;;;; +A005;YI SYLLABLE IEX;Lo;0;L;;;;;N;;;;; +A006;YI SYLLABLE IE;Lo;0;L;;;;;N;;;;; +A007;YI SYLLABLE IEP;Lo;0;L;;;;;N;;;;; +A008;YI SYLLABLE AT;Lo;0;L;;;;;N;;;;; +A009;YI SYLLABLE AX;Lo;0;L;;;;;N;;;;; +A00A;YI SYLLABLE A;Lo;0;L;;;;;N;;;;; +A00B;YI SYLLABLE AP;Lo;0;L;;;;;N;;;;; +A00C;YI SYLLABLE UOX;Lo;0;L;;;;;N;;;;; +A00D;YI SYLLABLE UO;Lo;0;L;;;;;N;;;;; +A00E;YI SYLLABLE UOP;Lo;0;L;;;;;N;;;;; +A00F;YI SYLLABLE OT;Lo;0;L;;;;;N;;;;; +A010;YI SYLLABLE OX;Lo;0;L;;;;;N;;;;; +A011;YI SYLLABLE O;Lo;0;L;;;;;N;;;;; +A012;YI SYLLABLE OP;Lo;0;L;;;;;N;;;;; +A013;YI SYLLABLE EX;Lo;0;L;;;;;N;;;;; +A014;YI SYLLABLE E;Lo;0;L;;;;;N;;;;; +A015;YI SYLLABLE WU;Lm;0;L;;;;;N;;;;; +A016;YI SYLLABLE BIT;Lo;0;L;;;;;N;;;;; +A017;YI SYLLABLE BIX;Lo;0;L;;;;;N;;;;; +A018;YI SYLLABLE BI;Lo;0;L;;;;;N;;;;; +A019;YI SYLLABLE BIP;Lo;0;L;;;;;N;;;;; +A01A;YI SYLLABLE BIET;Lo;0;L;;;;;N;;;;; +A01B;YI SYLLABLE BIEX;Lo;0;L;;;;;N;;;;; +A01C;YI SYLLABLE BIE;Lo;0;L;;;;;N;;;;; +A01D;YI SYLLABLE BIEP;Lo;0;L;;;;;N;;;;; +A01E;YI SYLLABLE BAT;Lo;0;L;;;;;N;;;;; +A01F;YI SYLLABLE BAX;Lo;0;L;;;;;N;;;;; +A020;YI SYLLABLE BA;Lo;0;L;;;;;N;;;;; +A021;YI SYLLABLE BAP;Lo;0;L;;;;;N;;;;; +A022;YI SYLLABLE BUOX;Lo;0;L;;;;;N;;;;; +A023;YI SYLLABLE BUO;Lo;0;L;;;;;N;;;;; +A024;YI SYLLABLE BUOP;Lo;0;L;;;;;N;;;;; +A025;YI SYLLABLE BOT;Lo;0;L;;;;;N;;;;; +A026;YI SYLLABLE BOX;Lo;0;L;;;;;N;;;;; +A027;YI SYLLABLE BO;Lo;0;L;;;;;N;;;;; +A028;YI SYLLABLE BOP;Lo;0;L;;;;;N;;;;; +A029;YI SYLLABLE BEX;Lo;0;L;;;;;N;;;;; +A02A;YI SYLLABLE BE;Lo;0;L;;;;;N;;;;; +A02B;YI SYLLABLE BEP;Lo;0;L;;;;;N;;;;; +A02C;YI SYLLABLE BUT;Lo;0;L;;;;;N;;;;; +A02D;YI SYLLABLE BUX;Lo;0;L;;;;;N;;;;; +A02E;YI SYLLABLE BU;Lo;0;L;;;;;N;;;;; +A02F;YI SYLLABLE BUP;Lo;0;L;;;;;N;;;;; +A030;YI SYLLABLE BURX;Lo;0;L;;;;;N;;;;; +A031;YI SYLLABLE BUR;Lo;0;L;;;;;N;;;;; +A032;YI SYLLABLE BYT;Lo;0;L;;;;;N;;;;; +A033;YI SYLLABLE BYX;Lo;0;L;;;;;N;;;;; +A034;YI SYLLABLE BY;Lo;0;L;;;;;N;;;;; +A035;YI SYLLABLE BYP;Lo;0;L;;;;;N;;;;; +A036;YI SYLLABLE BYRX;Lo;0;L;;;;;N;;;;; +A037;YI SYLLABLE BYR;Lo;0;L;;;;;N;;;;; +A038;YI SYLLABLE PIT;Lo;0;L;;;;;N;;;;; +A039;YI SYLLABLE PIX;Lo;0;L;;;;;N;;;;; +A03A;YI SYLLABLE PI;Lo;0;L;;;;;N;;;;; +A03B;YI SYLLABLE PIP;Lo;0;L;;;;;N;;;;; +A03C;YI SYLLABLE PIEX;Lo;0;L;;;;;N;;;;; +A03D;YI SYLLABLE PIE;Lo;0;L;;;;;N;;;;; +A03E;YI SYLLABLE PIEP;Lo;0;L;;;;;N;;;;; +A03F;YI SYLLABLE PAT;Lo;0;L;;;;;N;;;;; +A040;YI SYLLABLE PAX;Lo;0;L;;;;;N;;;;; +A041;YI SYLLABLE PA;Lo;0;L;;;;;N;;;;; +A042;YI SYLLABLE PAP;Lo;0;L;;;;;N;;;;; +A043;YI SYLLABLE PUOX;Lo;0;L;;;;;N;;;;; +A044;YI SYLLABLE PUO;Lo;0;L;;;;;N;;;;; +A045;YI SYLLABLE PUOP;Lo;0;L;;;;;N;;;;; +A046;YI SYLLABLE POT;Lo;0;L;;;;;N;;;;; +A047;YI SYLLABLE POX;Lo;0;L;;;;;N;;;;; +A048;YI SYLLABLE PO;Lo;0;L;;;;;N;;;;; +A049;YI SYLLABLE POP;Lo;0;L;;;;;N;;;;; +A04A;YI SYLLABLE PUT;Lo;0;L;;;;;N;;;;; +A04B;YI SYLLABLE PUX;Lo;0;L;;;;;N;;;;; +A04C;YI SYLLABLE PU;Lo;0;L;;;;;N;;;;; +A04D;YI SYLLABLE PUP;Lo;0;L;;;;;N;;;;; +A04E;YI SYLLABLE PURX;Lo;0;L;;;;;N;;;;; +A04F;YI SYLLABLE PUR;Lo;0;L;;;;;N;;;;; +A050;YI SYLLABLE PYT;Lo;0;L;;;;;N;;;;; +A051;YI SYLLABLE PYX;Lo;0;L;;;;;N;;;;; +A052;YI SYLLABLE PY;Lo;0;L;;;;;N;;;;; +A053;YI SYLLABLE PYP;Lo;0;L;;;;;N;;;;; +A054;YI SYLLABLE PYRX;Lo;0;L;;;;;N;;;;; +A055;YI SYLLABLE PYR;Lo;0;L;;;;;N;;;;; +A056;YI SYLLABLE BBIT;Lo;0;L;;;;;N;;;;; +A057;YI SYLLABLE BBIX;Lo;0;L;;;;;N;;;;; +A058;YI SYLLABLE BBI;Lo;0;L;;;;;N;;;;; +A059;YI SYLLABLE BBIP;Lo;0;L;;;;;N;;;;; +A05A;YI SYLLABLE BBIET;Lo;0;L;;;;;N;;;;; +A05B;YI SYLLABLE BBIEX;Lo;0;L;;;;;N;;;;; +A05C;YI SYLLABLE BBIE;Lo;0;L;;;;;N;;;;; +A05D;YI SYLLABLE BBIEP;Lo;0;L;;;;;N;;;;; +A05E;YI SYLLABLE BBAT;Lo;0;L;;;;;N;;;;; +A05F;YI SYLLABLE BBAX;Lo;0;L;;;;;N;;;;; +A060;YI SYLLABLE BBA;Lo;0;L;;;;;N;;;;; +A061;YI SYLLABLE BBAP;Lo;0;L;;;;;N;;;;; +A062;YI SYLLABLE BBUOX;Lo;0;L;;;;;N;;;;; +A063;YI SYLLABLE BBUO;Lo;0;L;;;;;N;;;;; +A064;YI SYLLABLE BBUOP;Lo;0;L;;;;;N;;;;; +A065;YI SYLLABLE BBOT;Lo;0;L;;;;;N;;;;; +A066;YI SYLLABLE BBOX;Lo;0;L;;;;;N;;;;; +A067;YI SYLLABLE BBO;Lo;0;L;;;;;N;;;;; +A068;YI SYLLABLE BBOP;Lo;0;L;;;;;N;;;;; +A069;YI SYLLABLE BBEX;Lo;0;L;;;;;N;;;;; +A06A;YI SYLLABLE BBE;Lo;0;L;;;;;N;;;;; +A06B;YI SYLLABLE BBEP;Lo;0;L;;;;;N;;;;; +A06C;YI SYLLABLE BBUT;Lo;0;L;;;;;N;;;;; +A06D;YI SYLLABLE BBUX;Lo;0;L;;;;;N;;;;; +A06E;YI SYLLABLE BBU;Lo;0;L;;;;;N;;;;; +A06F;YI SYLLABLE BBUP;Lo;0;L;;;;;N;;;;; +A070;YI SYLLABLE BBURX;Lo;0;L;;;;;N;;;;; +A071;YI SYLLABLE BBUR;Lo;0;L;;;;;N;;;;; +A072;YI SYLLABLE BBYT;Lo;0;L;;;;;N;;;;; +A073;YI SYLLABLE BBYX;Lo;0;L;;;;;N;;;;; +A074;YI SYLLABLE BBY;Lo;0;L;;;;;N;;;;; +A075;YI SYLLABLE BBYP;Lo;0;L;;;;;N;;;;; +A076;YI SYLLABLE NBIT;Lo;0;L;;;;;N;;;;; +A077;YI SYLLABLE NBIX;Lo;0;L;;;;;N;;;;; +A078;YI SYLLABLE NBI;Lo;0;L;;;;;N;;;;; +A079;YI SYLLABLE NBIP;Lo;0;L;;;;;N;;;;; +A07A;YI SYLLABLE NBIEX;Lo;0;L;;;;;N;;;;; +A07B;YI SYLLABLE NBIE;Lo;0;L;;;;;N;;;;; +A07C;YI SYLLABLE NBIEP;Lo;0;L;;;;;N;;;;; +A07D;YI SYLLABLE NBAT;Lo;0;L;;;;;N;;;;; +A07E;YI SYLLABLE NBAX;Lo;0;L;;;;;N;;;;; +A07F;YI SYLLABLE NBA;Lo;0;L;;;;;N;;;;; +A080;YI SYLLABLE NBAP;Lo;0;L;;;;;N;;;;; +A081;YI SYLLABLE NBOT;Lo;0;L;;;;;N;;;;; +A082;YI SYLLABLE NBOX;Lo;0;L;;;;;N;;;;; +A083;YI SYLLABLE NBO;Lo;0;L;;;;;N;;;;; +A084;YI SYLLABLE NBOP;Lo;0;L;;;;;N;;;;; +A085;YI SYLLABLE NBUT;Lo;0;L;;;;;N;;;;; +A086;YI SYLLABLE NBUX;Lo;0;L;;;;;N;;;;; +A087;YI SYLLABLE NBU;Lo;0;L;;;;;N;;;;; +A088;YI SYLLABLE NBUP;Lo;0;L;;;;;N;;;;; +A089;YI SYLLABLE NBURX;Lo;0;L;;;;;N;;;;; +A08A;YI SYLLABLE NBUR;Lo;0;L;;;;;N;;;;; +A08B;YI SYLLABLE NBYT;Lo;0;L;;;;;N;;;;; +A08C;YI SYLLABLE NBYX;Lo;0;L;;;;;N;;;;; +A08D;YI SYLLABLE NBY;Lo;0;L;;;;;N;;;;; +A08E;YI SYLLABLE NBYP;Lo;0;L;;;;;N;;;;; +A08F;YI SYLLABLE NBYRX;Lo;0;L;;;;;N;;;;; +A090;YI SYLLABLE NBYR;Lo;0;L;;;;;N;;;;; +A091;YI SYLLABLE HMIT;Lo;0;L;;;;;N;;;;; +A092;YI SYLLABLE HMIX;Lo;0;L;;;;;N;;;;; +A093;YI SYLLABLE HMI;Lo;0;L;;;;;N;;;;; +A094;YI SYLLABLE HMIP;Lo;0;L;;;;;N;;;;; +A095;YI SYLLABLE HMIEX;Lo;0;L;;;;;N;;;;; +A096;YI SYLLABLE HMIE;Lo;0;L;;;;;N;;;;; +A097;YI SYLLABLE HMIEP;Lo;0;L;;;;;N;;;;; +A098;YI SYLLABLE HMAT;Lo;0;L;;;;;N;;;;; +A099;YI SYLLABLE HMAX;Lo;0;L;;;;;N;;;;; +A09A;YI SYLLABLE HMA;Lo;0;L;;;;;N;;;;; +A09B;YI SYLLABLE HMAP;Lo;0;L;;;;;N;;;;; +A09C;YI SYLLABLE HMUOX;Lo;0;L;;;;;N;;;;; +A09D;YI SYLLABLE HMUO;Lo;0;L;;;;;N;;;;; +A09E;YI SYLLABLE HMUOP;Lo;0;L;;;;;N;;;;; +A09F;YI SYLLABLE HMOT;Lo;0;L;;;;;N;;;;; +A0A0;YI SYLLABLE HMOX;Lo;0;L;;;;;N;;;;; +A0A1;YI SYLLABLE HMO;Lo;0;L;;;;;N;;;;; +A0A2;YI SYLLABLE HMOP;Lo;0;L;;;;;N;;;;; +A0A3;YI SYLLABLE HMUT;Lo;0;L;;;;;N;;;;; +A0A4;YI SYLLABLE HMUX;Lo;0;L;;;;;N;;;;; +A0A5;YI SYLLABLE HMU;Lo;0;L;;;;;N;;;;; +A0A6;YI SYLLABLE HMUP;Lo;0;L;;;;;N;;;;; +A0A7;YI SYLLABLE HMURX;Lo;0;L;;;;;N;;;;; +A0A8;YI SYLLABLE HMUR;Lo;0;L;;;;;N;;;;; +A0A9;YI SYLLABLE HMYX;Lo;0;L;;;;;N;;;;; +A0AA;YI SYLLABLE HMY;Lo;0;L;;;;;N;;;;; +A0AB;YI SYLLABLE HMYP;Lo;0;L;;;;;N;;;;; +A0AC;YI SYLLABLE HMYRX;Lo;0;L;;;;;N;;;;; +A0AD;YI SYLLABLE HMYR;Lo;0;L;;;;;N;;;;; +A0AE;YI SYLLABLE MIT;Lo;0;L;;;;;N;;;;; +A0AF;YI SYLLABLE MIX;Lo;0;L;;;;;N;;;;; +A0B0;YI SYLLABLE MI;Lo;0;L;;;;;N;;;;; +A0B1;YI SYLLABLE MIP;Lo;0;L;;;;;N;;;;; +A0B2;YI SYLLABLE MIEX;Lo;0;L;;;;;N;;;;; +A0B3;YI SYLLABLE MIE;Lo;0;L;;;;;N;;;;; +A0B4;YI SYLLABLE MIEP;Lo;0;L;;;;;N;;;;; +A0B5;YI SYLLABLE MAT;Lo;0;L;;;;;N;;;;; +A0B6;YI SYLLABLE MAX;Lo;0;L;;;;;N;;;;; +A0B7;YI SYLLABLE MA;Lo;0;L;;;;;N;;;;; +A0B8;YI SYLLABLE MAP;Lo;0;L;;;;;N;;;;; +A0B9;YI SYLLABLE MUOT;Lo;0;L;;;;;N;;;;; +A0BA;YI SYLLABLE MUOX;Lo;0;L;;;;;N;;;;; +A0BB;YI SYLLABLE MUO;Lo;0;L;;;;;N;;;;; +A0BC;YI SYLLABLE MUOP;Lo;0;L;;;;;N;;;;; +A0BD;YI SYLLABLE MOT;Lo;0;L;;;;;N;;;;; +A0BE;YI SYLLABLE MOX;Lo;0;L;;;;;N;;;;; +A0BF;YI SYLLABLE MO;Lo;0;L;;;;;N;;;;; +A0C0;YI SYLLABLE MOP;Lo;0;L;;;;;N;;;;; +A0C1;YI SYLLABLE MEX;Lo;0;L;;;;;N;;;;; +A0C2;YI SYLLABLE ME;Lo;0;L;;;;;N;;;;; +A0C3;YI SYLLABLE MUT;Lo;0;L;;;;;N;;;;; +A0C4;YI SYLLABLE MUX;Lo;0;L;;;;;N;;;;; +A0C5;YI SYLLABLE MU;Lo;0;L;;;;;N;;;;; +A0C6;YI SYLLABLE MUP;Lo;0;L;;;;;N;;;;; +A0C7;YI SYLLABLE MURX;Lo;0;L;;;;;N;;;;; +A0C8;YI SYLLABLE MUR;Lo;0;L;;;;;N;;;;; +A0C9;YI SYLLABLE MYT;Lo;0;L;;;;;N;;;;; +A0CA;YI SYLLABLE MYX;Lo;0;L;;;;;N;;;;; +A0CB;YI SYLLABLE MY;Lo;0;L;;;;;N;;;;; +A0CC;YI SYLLABLE MYP;Lo;0;L;;;;;N;;;;; +A0CD;YI SYLLABLE FIT;Lo;0;L;;;;;N;;;;; +A0CE;YI SYLLABLE FIX;Lo;0;L;;;;;N;;;;; +A0CF;YI SYLLABLE FI;Lo;0;L;;;;;N;;;;; +A0D0;YI SYLLABLE FIP;Lo;0;L;;;;;N;;;;; +A0D1;YI SYLLABLE FAT;Lo;0;L;;;;;N;;;;; +A0D2;YI SYLLABLE FAX;Lo;0;L;;;;;N;;;;; +A0D3;YI SYLLABLE FA;Lo;0;L;;;;;N;;;;; +A0D4;YI SYLLABLE FAP;Lo;0;L;;;;;N;;;;; +A0D5;YI SYLLABLE FOX;Lo;0;L;;;;;N;;;;; +A0D6;YI SYLLABLE FO;Lo;0;L;;;;;N;;;;; +A0D7;YI SYLLABLE FOP;Lo;0;L;;;;;N;;;;; +A0D8;YI SYLLABLE FUT;Lo;0;L;;;;;N;;;;; +A0D9;YI SYLLABLE FUX;Lo;0;L;;;;;N;;;;; +A0DA;YI SYLLABLE FU;Lo;0;L;;;;;N;;;;; +A0DB;YI SYLLABLE FUP;Lo;0;L;;;;;N;;;;; +A0DC;YI SYLLABLE FURX;Lo;0;L;;;;;N;;;;; +A0DD;YI SYLLABLE FUR;Lo;0;L;;;;;N;;;;; +A0DE;YI SYLLABLE FYT;Lo;0;L;;;;;N;;;;; +A0DF;YI SYLLABLE FYX;Lo;0;L;;;;;N;;;;; +A0E0;YI SYLLABLE FY;Lo;0;L;;;;;N;;;;; +A0E1;YI SYLLABLE FYP;Lo;0;L;;;;;N;;;;; +A0E2;YI SYLLABLE VIT;Lo;0;L;;;;;N;;;;; +A0E3;YI SYLLABLE VIX;Lo;0;L;;;;;N;;;;; +A0E4;YI SYLLABLE VI;Lo;0;L;;;;;N;;;;; +A0E5;YI SYLLABLE VIP;Lo;0;L;;;;;N;;;;; +A0E6;YI SYLLABLE VIET;Lo;0;L;;;;;N;;;;; +A0E7;YI SYLLABLE VIEX;Lo;0;L;;;;;N;;;;; +A0E8;YI SYLLABLE VIE;Lo;0;L;;;;;N;;;;; +A0E9;YI SYLLABLE VIEP;Lo;0;L;;;;;N;;;;; +A0EA;YI SYLLABLE VAT;Lo;0;L;;;;;N;;;;; +A0EB;YI SYLLABLE VAX;Lo;0;L;;;;;N;;;;; +A0EC;YI SYLLABLE VA;Lo;0;L;;;;;N;;;;; +A0ED;YI SYLLABLE VAP;Lo;0;L;;;;;N;;;;; +A0EE;YI SYLLABLE VOT;Lo;0;L;;;;;N;;;;; +A0EF;YI SYLLABLE VOX;Lo;0;L;;;;;N;;;;; +A0F0;YI SYLLABLE VO;Lo;0;L;;;;;N;;;;; +A0F1;YI SYLLABLE VOP;Lo;0;L;;;;;N;;;;; +A0F2;YI SYLLABLE VEX;Lo;0;L;;;;;N;;;;; +A0F3;YI SYLLABLE VEP;Lo;0;L;;;;;N;;;;; +A0F4;YI SYLLABLE VUT;Lo;0;L;;;;;N;;;;; +A0F5;YI SYLLABLE VUX;Lo;0;L;;;;;N;;;;; +A0F6;YI SYLLABLE VU;Lo;0;L;;;;;N;;;;; +A0F7;YI SYLLABLE VUP;Lo;0;L;;;;;N;;;;; +A0F8;YI SYLLABLE VURX;Lo;0;L;;;;;N;;;;; +A0F9;YI SYLLABLE VUR;Lo;0;L;;;;;N;;;;; +A0FA;YI SYLLABLE VYT;Lo;0;L;;;;;N;;;;; +A0FB;YI SYLLABLE VYX;Lo;0;L;;;;;N;;;;; +A0FC;YI SYLLABLE VY;Lo;0;L;;;;;N;;;;; +A0FD;YI SYLLABLE VYP;Lo;0;L;;;;;N;;;;; +A0FE;YI SYLLABLE VYRX;Lo;0;L;;;;;N;;;;; +A0FF;YI SYLLABLE VYR;Lo;0;L;;;;;N;;;;; +A100;YI SYLLABLE DIT;Lo;0;L;;;;;N;;;;; +A101;YI SYLLABLE DIX;Lo;0;L;;;;;N;;;;; +A102;YI SYLLABLE DI;Lo;0;L;;;;;N;;;;; +A103;YI SYLLABLE DIP;Lo;0;L;;;;;N;;;;; +A104;YI SYLLABLE DIEX;Lo;0;L;;;;;N;;;;; +A105;YI SYLLABLE DIE;Lo;0;L;;;;;N;;;;; +A106;YI SYLLABLE DIEP;Lo;0;L;;;;;N;;;;; +A107;YI SYLLABLE DAT;Lo;0;L;;;;;N;;;;; +A108;YI SYLLABLE DAX;Lo;0;L;;;;;N;;;;; +A109;YI SYLLABLE DA;Lo;0;L;;;;;N;;;;; +A10A;YI SYLLABLE DAP;Lo;0;L;;;;;N;;;;; +A10B;YI SYLLABLE DUOX;Lo;0;L;;;;;N;;;;; +A10C;YI SYLLABLE DUO;Lo;0;L;;;;;N;;;;; +A10D;YI SYLLABLE DOT;Lo;0;L;;;;;N;;;;; +A10E;YI SYLLABLE DOX;Lo;0;L;;;;;N;;;;; +A10F;YI SYLLABLE DO;Lo;0;L;;;;;N;;;;; +A110;YI SYLLABLE DOP;Lo;0;L;;;;;N;;;;; +A111;YI SYLLABLE DEX;Lo;0;L;;;;;N;;;;; +A112;YI SYLLABLE DE;Lo;0;L;;;;;N;;;;; +A113;YI SYLLABLE DEP;Lo;0;L;;;;;N;;;;; +A114;YI SYLLABLE DUT;Lo;0;L;;;;;N;;;;; +A115;YI SYLLABLE DUX;Lo;0;L;;;;;N;;;;; +A116;YI SYLLABLE DU;Lo;0;L;;;;;N;;;;; +A117;YI SYLLABLE DUP;Lo;0;L;;;;;N;;;;; +A118;YI SYLLABLE DURX;Lo;0;L;;;;;N;;;;; +A119;YI SYLLABLE DUR;Lo;0;L;;;;;N;;;;; +A11A;YI SYLLABLE TIT;Lo;0;L;;;;;N;;;;; +A11B;YI SYLLABLE TIX;Lo;0;L;;;;;N;;;;; +A11C;YI SYLLABLE TI;Lo;0;L;;;;;N;;;;; +A11D;YI SYLLABLE TIP;Lo;0;L;;;;;N;;;;; +A11E;YI SYLLABLE TIEX;Lo;0;L;;;;;N;;;;; +A11F;YI SYLLABLE TIE;Lo;0;L;;;;;N;;;;; +A120;YI SYLLABLE TIEP;Lo;0;L;;;;;N;;;;; +A121;YI SYLLABLE TAT;Lo;0;L;;;;;N;;;;; +A122;YI SYLLABLE TAX;Lo;0;L;;;;;N;;;;; +A123;YI SYLLABLE TA;Lo;0;L;;;;;N;;;;; +A124;YI SYLLABLE TAP;Lo;0;L;;;;;N;;;;; +A125;YI SYLLABLE TUOT;Lo;0;L;;;;;N;;;;; +A126;YI SYLLABLE TUOX;Lo;0;L;;;;;N;;;;; +A127;YI SYLLABLE TUO;Lo;0;L;;;;;N;;;;; +A128;YI SYLLABLE TUOP;Lo;0;L;;;;;N;;;;; +A129;YI SYLLABLE TOT;Lo;0;L;;;;;N;;;;; +A12A;YI SYLLABLE TOX;Lo;0;L;;;;;N;;;;; +A12B;YI SYLLABLE TO;Lo;0;L;;;;;N;;;;; +A12C;YI SYLLABLE TOP;Lo;0;L;;;;;N;;;;; +A12D;YI SYLLABLE TEX;Lo;0;L;;;;;N;;;;; +A12E;YI SYLLABLE TE;Lo;0;L;;;;;N;;;;; +A12F;YI SYLLABLE TEP;Lo;0;L;;;;;N;;;;; +A130;YI SYLLABLE TUT;Lo;0;L;;;;;N;;;;; +A131;YI SYLLABLE TUX;Lo;0;L;;;;;N;;;;; +A132;YI SYLLABLE TU;Lo;0;L;;;;;N;;;;; +A133;YI SYLLABLE TUP;Lo;0;L;;;;;N;;;;; +A134;YI SYLLABLE TURX;Lo;0;L;;;;;N;;;;; +A135;YI SYLLABLE TUR;Lo;0;L;;;;;N;;;;; +A136;YI SYLLABLE DDIT;Lo;0;L;;;;;N;;;;; +A137;YI SYLLABLE DDIX;Lo;0;L;;;;;N;;;;; +A138;YI SYLLABLE DDI;Lo;0;L;;;;;N;;;;; +A139;YI SYLLABLE DDIP;Lo;0;L;;;;;N;;;;; +A13A;YI SYLLABLE DDIEX;Lo;0;L;;;;;N;;;;; +A13B;YI SYLLABLE DDIE;Lo;0;L;;;;;N;;;;; +A13C;YI SYLLABLE DDIEP;Lo;0;L;;;;;N;;;;; +A13D;YI SYLLABLE DDAT;Lo;0;L;;;;;N;;;;; +A13E;YI SYLLABLE DDAX;Lo;0;L;;;;;N;;;;; +A13F;YI SYLLABLE DDA;Lo;0;L;;;;;N;;;;; +A140;YI SYLLABLE DDAP;Lo;0;L;;;;;N;;;;; +A141;YI SYLLABLE DDUOX;Lo;0;L;;;;;N;;;;; +A142;YI SYLLABLE DDUO;Lo;0;L;;;;;N;;;;; +A143;YI SYLLABLE DDUOP;Lo;0;L;;;;;N;;;;; +A144;YI SYLLABLE DDOT;Lo;0;L;;;;;N;;;;; +A145;YI SYLLABLE DDOX;Lo;0;L;;;;;N;;;;; +A146;YI SYLLABLE DDO;Lo;0;L;;;;;N;;;;; +A147;YI SYLLABLE DDOP;Lo;0;L;;;;;N;;;;; +A148;YI SYLLABLE DDEX;Lo;0;L;;;;;N;;;;; +A149;YI SYLLABLE DDE;Lo;0;L;;;;;N;;;;; +A14A;YI SYLLABLE DDEP;Lo;0;L;;;;;N;;;;; +A14B;YI SYLLABLE DDUT;Lo;0;L;;;;;N;;;;; +A14C;YI SYLLABLE DDUX;Lo;0;L;;;;;N;;;;; +A14D;YI SYLLABLE DDU;Lo;0;L;;;;;N;;;;; +A14E;YI SYLLABLE DDUP;Lo;0;L;;;;;N;;;;; +A14F;YI SYLLABLE DDURX;Lo;0;L;;;;;N;;;;; +A150;YI SYLLABLE DDUR;Lo;0;L;;;;;N;;;;; +A151;YI SYLLABLE NDIT;Lo;0;L;;;;;N;;;;; +A152;YI SYLLABLE NDIX;Lo;0;L;;;;;N;;;;; +A153;YI SYLLABLE NDI;Lo;0;L;;;;;N;;;;; +A154;YI SYLLABLE NDIP;Lo;0;L;;;;;N;;;;; +A155;YI SYLLABLE NDIEX;Lo;0;L;;;;;N;;;;; +A156;YI SYLLABLE NDIE;Lo;0;L;;;;;N;;;;; +A157;YI SYLLABLE NDAT;Lo;0;L;;;;;N;;;;; +A158;YI SYLLABLE NDAX;Lo;0;L;;;;;N;;;;; +A159;YI SYLLABLE NDA;Lo;0;L;;;;;N;;;;; +A15A;YI SYLLABLE NDAP;Lo;0;L;;;;;N;;;;; +A15B;YI SYLLABLE NDOT;Lo;0;L;;;;;N;;;;; +A15C;YI SYLLABLE NDOX;Lo;0;L;;;;;N;;;;; +A15D;YI SYLLABLE NDO;Lo;0;L;;;;;N;;;;; +A15E;YI SYLLABLE NDOP;Lo;0;L;;;;;N;;;;; +A15F;YI SYLLABLE NDEX;Lo;0;L;;;;;N;;;;; +A160;YI SYLLABLE NDE;Lo;0;L;;;;;N;;;;; +A161;YI SYLLABLE NDEP;Lo;0;L;;;;;N;;;;; +A162;YI SYLLABLE NDUT;Lo;0;L;;;;;N;;;;; +A163;YI SYLLABLE NDUX;Lo;0;L;;;;;N;;;;; +A164;YI SYLLABLE NDU;Lo;0;L;;;;;N;;;;; +A165;YI SYLLABLE NDUP;Lo;0;L;;;;;N;;;;; +A166;YI SYLLABLE NDURX;Lo;0;L;;;;;N;;;;; +A167;YI SYLLABLE NDUR;Lo;0;L;;;;;N;;;;; +A168;YI SYLLABLE HNIT;Lo;0;L;;;;;N;;;;; +A169;YI SYLLABLE HNIX;Lo;0;L;;;;;N;;;;; +A16A;YI SYLLABLE HNI;Lo;0;L;;;;;N;;;;; +A16B;YI SYLLABLE HNIP;Lo;0;L;;;;;N;;;;; +A16C;YI SYLLABLE HNIET;Lo;0;L;;;;;N;;;;; +A16D;YI SYLLABLE HNIEX;Lo;0;L;;;;;N;;;;; +A16E;YI SYLLABLE HNIE;Lo;0;L;;;;;N;;;;; +A16F;YI SYLLABLE HNIEP;Lo;0;L;;;;;N;;;;; +A170;YI SYLLABLE HNAT;Lo;0;L;;;;;N;;;;; +A171;YI SYLLABLE HNAX;Lo;0;L;;;;;N;;;;; +A172;YI SYLLABLE HNA;Lo;0;L;;;;;N;;;;; +A173;YI SYLLABLE HNAP;Lo;0;L;;;;;N;;;;; +A174;YI SYLLABLE HNUOX;Lo;0;L;;;;;N;;;;; +A175;YI SYLLABLE HNUO;Lo;0;L;;;;;N;;;;; +A176;YI SYLLABLE HNOT;Lo;0;L;;;;;N;;;;; +A177;YI SYLLABLE HNOX;Lo;0;L;;;;;N;;;;; +A178;YI SYLLABLE HNOP;Lo;0;L;;;;;N;;;;; +A179;YI SYLLABLE HNEX;Lo;0;L;;;;;N;;;;; +A17A;YI SYLLABLE HNE;Lo;0;L;;;;;N;;;;; +A17B;YI SYLLABLE HNEP;Lo;0;L;;;;;N;;;;; +A17C;YI SYLLABLE HNUT;Lo;0;L;;;;;N;;;;; +A17D;YI SYLLABLE NIT;Lo;0;L;;;;;N;;;;; +A17E;YI SYLLABLE NIX;Lo;0;L;;;;;N;;;;; +A17F;YI SYLLABLE NI;Lo;0;L;;;;;N;;;;; +A180;YI SYLLABLE NIP;Lo;0;L;;;;;N;;;;; +A181;YI SYLLABLE NIEX;Lo;0;L;;;;;N;;;;; +A182;YI SYLLABLE NIE;Lo;0;L;;;;;N;;;;; +A183;YI SYLLABLE NIEP;Lo;0;L;;;;;N;;;;; +A184;YI SYLLABLE NAX;Lo;0;L;;;;;N;;;;; +A185;YI SYLLABLE NA;Lo;0;L;;;;;N;;;;; +A186;YI SYLLABLE NAP;Lo;0;L;;;;;N;;;;; +A187;YI SYLLABLE NUOX;Lo;0;L;;;;;N;;;;; +A188;YI SYLLABLE NUO;Lo;0;L;;;;;N;;;;; +A189;YI SYLLABLE NUOP;Lo;0;L;;;;;N;;;;; +A18A;YI SYLLABLE NOT;Lo;0;L;;;;;N;;;;; +A18B;YI SYLLABLE NOX;Lo;0;L;;;;;N;;;;; +A18C;YI SYLLABLE NO;Lo;0;L;;;;;N;;;;; +A18D;YI SYLLABLE NOP;Lo;0;L;;;;;N;;;;; +A18E;YI SYLLABLE NEX;Lo;0;L;;;;;N;;;;; +A18F;YI SYLLABLE NE;Lo;0;L;;;;;N;;;;; +A190;YI SYLLABLE NEP;Lo;0;L;;;;;N;;;;; +A191;YI SYLLABLE NUT;Lo;0;L;;;;;N;;;;; +A192;YI SYLLABLE NUX;Lo;0;L;;;;;N;;;;; +A193;YI SYLLABLE NU;Lo;0;L;;;;;N;;;;; +A194;YI SYLLABLE NUP;Lo;0;L;;;;;N;;;;; +A195;YI SYLLABLE NURX;Lo;0;L;;;;;N;;;;; +A196;YI SYLLABLE NUR;Lo;0;L;;;;;N;;;;; +A197;YI SYLLABLE HLIT;Lo;0;L;;;;;N;;;;; +A198;YI SYLLABLE HLIX;Lo;0;L;;;;;N;;;;; +A199;YI SYLLABLE HLI;Lo;0;L;;;;;N;;;;; +A19A;YI SYLLABLE HLIP;Lo;0;L;;;;;N;;;;; +A19B;YI SYLLABLE HLIEX;Lo;0;L;;;;;N;;;;; +A19C;YI SYLLABLE HLIE;Lo;0;L;;;;;N;;;;; +A19D;YI SYLLABLE HLIEP;Lo;0;L;;;;;N;;;;; +A19E;YI SYLLABLE HLAT;Lo;0;L;;;;;N;;;;; +A19F;YI SYLLABLE HLAX;Lo;0;L;;;;;N;;;;; +A1A0;YI SYLLABLE HLA;Lo;0;L;;;;;N;;;;; +A1A1;YI SYLLABLE HLAP;Lo;0;L;;;;;N;;;;; +A1A2;YI SYLLABLE HLUOX;Lo;0;L;;;;;N;;;;; +A1A3;YI SYLLABLE HLUO;Lo;0;L;;;;;N;;;;; +A1A4;YI SYLLABLE HLUOP;Lo;0;L;;;;;N;;;;; +A1A5;YI SYLLABLE HLOX;Lo;0;L;;;;;N;;;;; +A1A6;YI SYLLABLE HLO;Lo;0;L;;;;;N;;;;; +A1A7;YI SYLLABLE HLOP;Lo;0;L;;;;;N;;;;; +A1A8;YI SYLLABLE HLEX;Lo;0;L;;;;;N;;;;; +A1A9;YI SYLLABLE HLE;Lo;0;L;;;;;N;;;;; +A1AA;YI SYLLABLE HLEP;Lo;0;L;;;;;N;;;;; +A1AB;YI SYLLABLE HLUT;Lo;0;L;;;;;N;;;;; +A1AC;YI SYLLABLE HLUX;Lo;0;L;;;;;N;;;;; +A1AD;YI SYLLABLE HLU;Lo;0;L;;;;;N;;;;; +A1AE;YI SYLLABLE HLUP;Lo;0;L;;;;;N;;;;; +A1AF;YI SYLLABLE HLURX;Lo;0;L;;;;;N;;;;; +A1B0;YI SYLLABLE HLUR;Lo;0;L;;;;;N;;;;; +A1B1;YI SYLLABLE HLYT;Lo;0;L;;;;;N;;;;; +A1B2;YI SYLLABLE HLYX;Lo;0;L;;;;;N;;;;; +A1B3;YI SYLLABLE HLY;Lo;0;L;;;;;N;;;;; +A1B4;YI SYLLABLE HLYP;Lo;0;L;;;;;N;;;;; +A1B5;YI SYLLABLE HLYRX;Lo;0;L;;;;;N;;;;; +A1B6;YI SYLLABLE HLYR;Lo;0;L;;;;;N;;;;; +A1B7;YI SYLLABLE LIT;Lo;0;L;;;;;N;;;;; +A1B8;YI SYLLABLE LIX;Lo;0;L;;;;;N;;;;; +A1B9;YI SYLLABLE LI;Lo;0;L;;;;;N;;;;; +A1BA;YI SYLLABLE LIP;Lo;0;L;;;;;N;;;;; +A1BB;YI SYLLABLE LIET;Lo;0;L;;;;;N;;;;; +A1BC;YI SYLLABLE LIEX;Lo;0;L;;;;;N;;;;; +A1BD;YI SYLLABLE LIE;Lo;0;L;;;;;N;;;;; +A1BE;YI SYLLABLE LIEP;Lo;0;L;;;;;N;;;;; +A1BF;YI SYLLABLE LAT;Lo;0;L;;;;;N;;;;; +A1C0;YI SYLLABLE LAX;Lo;0;L;;;;;N;;;;; +A1C1;YI SYLLABLE LA;Lo;0;L;;;;;N;;;;; +A1C2;YI SYLLABLE LAP;Lo;0;L;;;;;N;;;;; +A1C3;YI SYLLABLE LUOT;Lo;0;L;;;;;N;;;;; +A1C4;YI SYLLABLE LUOX;Lo;0;L;;;;;N;;;;; +A1C5;YI SYLLABLE LUO;Lo;0;L;;;;;N;;;;; +A1C6;YI SYLLABLE LUOP;Lo;0;L;;;;;N;;;;; +A1C7;YI SYLLABLE LOT;Lo;0;L;;;;;N;;;;; +A1C8;YI SYLLABLE LOX;Lo;0;L;;;;;N;;;;; +A1C9;YI SYLLABLE LO;Lo;0;L;;;;;N;;;;; +A1CA;YI SYLLABLE LOP;Lo;0;L;;;;;N;;;;; +A1CB;YI SYLLABLE LEX;Lo;0;L;;;;;N;;;;; +A1CC;YI SYLLABLE LE;Lo;0;L;;;;;N;;;;; +A1CD;YI SYLLABLE LEP;Lo;0;L;;;;;N;;;;; +A1CE;YI SYLLABLE LUT;Lo;0;L;;;;;N;;;;; +A1CF;YI SYLLABLE LUX;Lo;0;L;;;;;N;;;;; +A1D0;YI SYLLABLE LU;Lo;0;L;;;;;N;;;;; +A1D1;YI SYLLABLE LUP;Lo;0;L;;;;;N;;;;; +A1D2;YI SYLLABLE LURX;Lo;0;L;;;;;N;;;;; +A1D3;YI SYLLABLE LUR;Lo;0;L;;;;;N;;;;; +A1D4;YI SYLLABLE LYT;Lo;0;L;;;;;N;;;;; +A1D5;YI SYLLABLE LYX;Lo;0;L;;;;;N;;;;; +A1D6;YI SYLLABLE LY;Lo;0;L;;;;;N;;;;; +A1D7;YI SYLLABLE LYP;Lo;0;L;;;;;N;;;;; +A1D8;YI SYLLABLE LYRX;Lo;0;L;;;;;N;;;;; +A1D9;YI SYLLABLE LYR;Lo;0;L;;;;;N;;;;; +A1DA;YI SYLLABLE GIT;Lo;0;L;;;;;N;;;;; +A1DB;YI SYLLABLE GIX;Lo;0;L;;;;;N;;;;; +A1DC;YI SYLLABLE GI;Lo;0;L;;;;;N;;;;; +A1DD;YI SYLLABLE GIP;Lo;0;L;;;;;N;;;;; +A1DE;YI SYLLABLE GIET;Lo;0;L;;;;;N;;;;; +A1DF;YI SYLLABLE GIEX;Lo;0;L;;;;;N;;;;; +A1E0;YI SYLLABLE GIE;Lo;0;L;;;;;N;;;;; +A1E1;YI SYLLABLE GIEP;Lo;0;L;;;;;N;;;;; +A1E2;YI SYLLABLE GAT;Lo;0;L;;;;;N;;;;; +A1E3;YI SYLLABLE GAX;Lo;0;L;;;;;N;;;;; +A1E4;YI SYLLABLE GA;Lo;0;L;;;;;N;;;;; +A1E5;YI SYLLABLE GAP;Lo;0;L;;;;;N;;;;; +A1E6;YI SYLLABLE GUOT;Lo;0;L;;;;;N;;;;; +A1E7;YI SYLLABLE GUOX;Lo;0;L;;;;;N;;;;; +A1E8;YI SYLLABLE GUO;Lo;0;L;;;;;N;;;;; +A1E9;YI SYLLABLE GUOP;Lo;0;L;;;;;N;;;;; +A1EA;YI SYLLABLE GOT;Lo;0;L;;;;;N;;;;; +A1EB;YI SYLLABLE GOX;Lo;0;L;;;;;N;;;;; +A1EC;YI SYLLABLE GO;Lo;0;L;;;;;N;;;;; +A1ED;YI SYLLABLE GOP;Lo;0;L;;;;;N;;;;; +A1EE;YI SYLLABLE GET;Lo;0;L;;;;;N;;;;; +A1EF;YI SYLLABLE GEX;Lo;0;L;;;;;N;;;;; +A1F0;YI SYLLABLE GE;Lo;0;L;;;;;N;;;;; +A1F1;YI SYLLABLE GEP;Lo;0;L;;;;;N;;;;; +A1F2;YI SYLLABLE GUT;Lo;0;L;;;;;N;;;;; +A1F3;YI SYLLABLE GUX;Lo;0;L;;;;;N;;;;; +A1F4;YI SYLLABLE GU;Lo;0;L;;;;;N;;;;; +A1F5;YI SYLLABLE GUP;Lo;0;L;;;;;N;;;;; +A1F6;YI SYLLABLE GURX;Lo;0;L;;;;;N;;;;; +A1F7;YI SYLLABLE GUR;Lo;0;L;;;;;N;;;;; +A1F8;YI SYLLABLE KIT;Lo;0;L;;;;;N;;;;; +A1F9;YI SYLLABLE KIX;Lo;0;L;;;;;N;;;;; +A1FA;YI SYLLABLE KI;Lo;0;L;;;;;N;;;;; +A1FB;YI SYLLABLE KIP;Lo;0;L;;;;;N;;;;; +A1FC;YI SYLLABLE KIEX;Lo;0;L;;;;;N;;;;; +A1FD;YI SYLLABLE KIE;Lo;0;L;;;;;N;;;;; +A1FE;YI SYLLABLE KIEP;Lo;0;L;;;;;N;;;;; +A1FF;YI SYLLABLE KAT;Lo;0;L;;;;;N;;;;; +A200;YI SYLLABLE KAX;Lo;0;L;;;;;N;;;;; +A201;YI SYLLABLE KA;Lo;0;L;;;;;N;;;;; +A202;YI SYLLABLE KAP;Lo;0;L;;;;;N;;;;; +A203;YI SYLLABLE KUOX;Lo;0;L;;;;;N;;;;; +A204;YI SYLLABLE KUO;Lo;0;L;;;;;N;;;;; +A205;YI SYLLABLE KUOP;Lo;0;L;;;;;N;;;;; +A206;YI SYLLABLE KOT;Lo;0;L;;;;;N;;;;; +A207;YI SYLLABLE KOX;Lo;0;L;;;;;N;;;;; +A208;YI SYLLABLE KO;Lo;0;L;;;;;N;;;;; +A209;YI SYLLABLE KOP;Lo;0;L;;;;;N;;;;; +A20A;YI SYLLABLE KET;Lo;0;L;;;;;N;;;;; +A20B;YI SYLLABLE KEX;Lo;0;L;;;;;N;;;;; +A20C;YI SYLLABLE KE;Lo;0;L;;;;;N;;;;; +A20D;YI SYLLABLE KEP;Lo;0;L;;;;;N;;;;; +A20E;YI SYLLABLE KUT;Lo;0;L;;;;;N;;;;; +A20F;YI SYLLABLE KUX;Lo;0;L;;;;;N;;;;; +A210;YI SYLLABLE KU;Lo;0;L;;;;;N;;;;; +A211;YI SYLLABLE KUP;Lo;0;L;;;;;N;;;;; +A212;YI SYLLABLE KURX;Lo;0;L;;;;;N;;;;; +A213;YI SYLLABLE KUR;Lo;0;L;;;;;N;;;;; +A214;YI SYLLABLE GGIT;Lo;0;L;;;;;N;;;;; +A215;YI SYLLABLE GGIX;Lo;0;L;;;;;N;;;;; +A216;YI SYLLABLE GGI;Lo;0;L;;;;;N;;;;; +A217;YI SYLLABLE GGIEX;Lo;0;L;;;;;N;;;;; +A218;YI SYLLABLE GGIE;Lo;0;L;;;;;N;;;;; +A219;YI SYLLABLE GGIEP;Lo;0;L;;;;;N;;;;; +A21A;YI SYLLABLE GGAT;Lo;0;L;;;;;N;;;;; +A21B;YI SYLLABLE GGAX;Lo;0;L;;;;;N;;;;; +A21C;YI SYLLABLE GGA;Lo;0;L;;;;;N;;;;; +A21D;YI SYLLABLE GGAP;Lo;0;L;;;;;N;;;;; +A21E;YI SYLLABLE GGUOT;Lo;0;L;;;;;N;;;;; +A21F;YI SYLLABLE GGUOX;Lo;0;L;;;;;N;;;;; +A220;YI SYLLABLE GGUO;Lo;0;L;;;;;N;;;;; +A221;YI SYLLABLE GGUOP;Lo;0;L;;;;;N;;;;; +A222;YI SYLLABLE GGOT;Lo;0;L;;;;;N;;;;; +A223;YI SYLLABLE GGOX;Lo;0;L;;;;;N;;;;; +A224;YI SYLLABLE GGO;Lo;0;L;;;;;N;;;;; +A225;YI SYLLABLE GGOP;Lo;0;L;;;;;N;;;;; +A226;YI SYLLABLE GGET;Lo;0;L;;;;;N;;;;; +A227;YI SYLLABLE GGEX;Lo;0;L;;;;;N;;;;; +A228;YI SYLLABLE GGE;Lo;0;L;;;;;N;;;;; +A229;YI SYLLABLE GGEP;Lo;0;L;;;;;N;;;;; +A22A;YI SYLLABLE GGUT;Lo;0;L;;;;;N;;;;; +A22B;YI SYLLABLE GGUX;Lo;0;L;;;;;N;;;;; +A22C;YI SYLLABLE GGU;Lo;0;L;;;;;N;;;;; +A22D;YI SYLLABLE GGUP;Lo;0;L;;;;;N;;;;; +A22E;YI SYLLABLE GGURX;Lo;0;L;;;;;N;;;;; +A22F;YI SYLLABLE GGUR;Lo;0;L;;;;;N;;;;; +A230;YI SYLLABLE MGIEX;Lo;0;L;;;;;N;;;;; +A231;YI SYLLABLE MGIE;Lo;0;L;;;;;N;;;;; +A232;YI SYLLABLE MGAT;Lo;0;L;;;;;N;;;;; +A233;YI SYLLABLE MGAX;Lo;0;L;;;;;N;;;;; +A234;YI SYLLABLE MGA;Lo;0;L;;;;;N;;;;; +A235;YI SYLLABLE MGAP;Lo;0;L;;;;;N;;;;; +A236;YI SYLLABLE MGUOX;Lo;0;L;;;;;N;;;;; +A237;YI SYLLABLE MGUO;Lo;0;L;;;;;N;;;;; +A238;YI SYLLABLE MGUOP;Lo;0;L;;;;;N;;;;; +A239;YI SYLLABLE MGOT;Lo;0;L;;;;;N;;;;; +A23A;YI SYLLABLE MGOX;Lo;0;L;;;;;N;;;;; +A23B;YI SYLLABLE MGO;Lo;0;L;;;;;N;;;;; +A23C;YI SYLLABLE MGOP;Lo;0;L;;;;;N;;;;; +A23D;YI SYLLABLE MGEX;Lo;0;L;;;;;N;;;;; +A23E;YI SYLLABLE MGE;Lo;0;L;;;;;N;;;;; +A23F;YI SYLLABLE MGEP;Lo;0;L;;;;;N;;;;; +A240;YI SYLLABLE MGUT;Lo;0;L;;;;;N;;;;; +A241;YI SYLLABLE MGUX;Lo;0;L;;;;;N;;;;; +A242;YI SYLLABLE MGU;Lo;0;L;;;;;N;;;;; +A243;YI SYLLABLE MGUP;Lo;0;L;;;;;N;;;;; +A244;YI SYLLABLE MGURX;Lo;0;L;;;;;N;;;;; +A245;YI SYLLABLE MGUR;Lo;0;L;;;;;N;;;;; +A246;YI SYLLABLE HXIT;Lo;0;L;;;;;N;;;;; +A247;YI SYLLABLE HXIX;Lo;0;L;;;;;N;;;;; +A248;YI SYLLABLE HXI;Lo;0;L;;;;;N;;;;; +A249;YI SYLLABLE HXIP;Lo;0;L;;;;;N;;;;; +A24A;YI SYLLABLE HXIET;Lo;0;L;;;;;N;;;;; +A24B;YI SYLLABLE HXIEX;Lo;0;L;;;;;N;;;;; +A24C;YI SYLLABLE HXIE;Lo;0;L;;;;;N;;;;; +A24D;YI SYLLABLE HXIEP;Lo;0;L;;;;;N;;;;; +A24E;YI SYLLABLE HXAT;Lo;0;L;;;;;N;;;;; +A24F;YI SYLLABLE HXAX;Lo;0;L;;;;;N;;;;; +A250;YI SYLLABLE HXA;Lo;0;L;;;;;N;;;;; +A251;YI SYLLABLE HXAP;Lo;0;L;;;;;N;;;;; +A252;YI SYLLABLE HXUOT;Lo;0;L;;;;;N;;;;; +A253;YI SYLLABLE HXUOX;Lo;0;L;;;;;N;;;;; +A254;YI SYLLABLE HXUO;Lo;0;L;;;;;N;;;;; +A255;YI SYLLABLE HXUOP;Lo;0;L;;;;;N;;;;; +A256;YI SYLLABLE HXOT;Lo;0;L;;;;;N;;;;; +A257;YI SYLLABLE HXOX;Lo;0;L;;;;;N;;;;; +A258;YI SYLLABLE HXO;Lo;0;L;;;;;N;;;;; +A259;YI SYLLABLE HXOP;Lo;0;L;;;;;N;;;;; +A25A;YI SYLLABLE HXEX;Lo;0;L;;;;;N;;;;; +A25B;YI SYLLABLE HXE;Lo;0;L;;;;;N;;;;; +A25C;YI SYLLABLE HXEP;Lo;0;L;;;;;N;;;;; +A25D;YI SYLLABLE NGIEX;Lo;0;L;;;;;N;;;;; +A25E;YI SYLLABLE NGIE;Lo;0;L;;;;;N;;;;; +A25F;YI SYLLABLE NGIEP;Lo;0;L;;;;;N;;;;; +A260;YI SYLLABLE NGAT;Lo;0;L;;;;;N;;;;; +A261;YI SYLLABLE NGAX;Lo;0;L;;;;;N;;;;; +A262;YI SYLLABLE NGA;Lo;0;L;;;;;N;;;;; +A263;YI SYLLABLE NGAP;Lo;0;L;;;;;N;;;;; +A264;YI SYLLABLE NGUOT;Lo;0;L;;;;;N;;;;; +A265;YI SYLLABLE NGUOX;Lo;0;L;;;;;N;;;;; +A266;YI SYLLABLE NGUO;Lo;0;L;;;;;N;;;;; +A267;YI SYLLABLE NGOT;Lo;0;L;;;;;N;;;;; +A268;YI SYLLABLE NGOX;Lo;0;L;;;;;N;;;;; +A269;YI SYLLABLE NGO;Lo;0;L;;;;;N;;;;; +A26A;YI SYLLABLE NGOP;Lo;0;L;;;;;N;;;;; +A26B;YI SYLLABLE NGEX;Lo;0;L;;;;;N;;;;; +A26C;YI SYLLABLE NGE;Lo;0;L;;;;;N;;;;; +A26D;YI SYLLABLE NGEP;Lo;0;L;;;;;N;;;;; +A26E;YI SYLLABLE HIT;Lo;0;L;;;;;N;;;;; +A26F;YI SYLLABLE HIEX;Lo;0;L;;;;;N;;;;; +A270;YI SYLLABLE HIE;Lo;0;L;;;;;N;;;;; +A271;YI SYLLABLE HAT;Lo;0;L;;;;;N;;;;; +A272;YI SYLLABLE HAX;Lo;0;L;;;;;N;;;;; +A273;YI SYLLABLE HA;Lo;0;L;;;;;N;;;;; +A274;YI SYLLABLE HAP;Lo;0;L;;;;;N;;;;; +A275;YI SYLLABLE HUOT;Lo;0;L;;;;;N;;;;; +A276;YI SYLLABLE HUOX;Lo;0;L;;;;;N;;;;; +A277;YI SYLLABLE HUO;Lo;0;L;;;;;N;;;;; +A278;YI SYLLABLE HUOP;Lo;0;L;;;;;N;;;;; +A279;YI SYLLABLE HOT;Lo;0;L;;;;;N;;;;; +A27A;YI SYLLABLE HOX;Lo;0;L;;;;;N;;;;; +A27B;YI SYLLABLE HO;Lo;0;L;;;;;N;;;;; +A27C;YI SYLLABLE HOP;Lo;0;L;;;;;N;;;;; +A27D;YI SYLLABLE HEX;Lo;0;L;;;;;N;;;;; +A27E;YI SYLLABLE HE;Lo;0;L;;;;;N;;;;; +A27F;YI SYLLABLE HEP;Lo;0;L;;;;;N;;;;; +A280;YI SYLLABLE WAT;Lo;0;L;;;;;N;;;;; +A281;YI SYLLABLE WAX;Lo;0;L;;;;;N;;;;; +A282;YI SYLLABLE WA;Lo;0;L;;;;;N;;;;; +A283;YI SYLLABLE WAP;Lo;0;L;;;;;N;;;;; +A284;YI SYLLABLE WUOX;Lo;0;L;;;;;N;;;;; +A285;YI SYLLABLE WUO;Lo;0;L;;;;;N;;;;; +A286;YI SYLLABLE WUOP;Lo;0;L;;;;;N;;;;; +A287;YI SYLLABLE WOX;Lo;0;L;;;;;N;;;;; +A288;YI SYLLABLE WO;Lo;0;L;;;;;N;;;;; +A289;YI SYLLABLE WOP;Lo;0;L;;;;;N;;;;; +A28A;YI SYLLABLE WEX;Lo;0;L;;;;;N;;;;; +A28B;YI SYLLABLE WE;Lo;0;L;;;;;N;;;;; +A28C;YI SYLLABLE WEP;Lo;0;L;;;;;N;;;;; +A28D;YI SYLLABLE ZIT;Lo;0;L;;;;;N;;;;; +A28E;YI SYLLABLE ZIX;Lo;0;L;;;;;N;;;;; +A28F;YI SYLLABLE ZI;Lo;0;L;;;;;N;;;;; +A290;YI SYLLABLE ZIP;Lo;0;L;;;;;N;;;;; +A291;YI SYLLABLE ZIEX;Lo;0;L;;;;;N;;;;; +A292;YI SYLLABLE ZIE;Lo;0;L;;;;;N;;;;; +A293;YI SYLLABLE ZIEP;Lo;0;L;;;;;N;;;;; +A294;YI SYLLABLE ZAT;Lo;0;L;;;;;N;;;;; +A295;YI SYLLABLE ZAX;Lo;0;L;;;;;N;;;;; +A296;YI SYLLABLE ZA;Lo;0;L;;;;;N;;;;; +A297;YI SYLLABLE ZAP;Lo;0;L;;;;;N;;;;; +A298;YI SYLLABLE ZUOX;Lo;0;L;;;;;N;;;;; +A299;YI SYLLABLE ZUO;Lo;0;L;;;;;N;;;;; +A29A;YI SYLLABLE ZUOP;Lo;0;L;;;;;N;;;;; +A29B;YI SYLLABLE ZOT;Lo;0;L;;;;;N;;;;; +A29C;YI SYLLABLE ZOX;Lo;0;L;;;;;N;;;;; +A29D;YI SYLLABLE ZO;Lo;0;L;;;;;N;;;;; +A29E;YI SYLLABLE ZOP;Lo;0;L;;;;;N;;;;; +A29F;YI SYLLABLE ZEX;Lo;0;L;;;;;N;;;;; +A2A0;YI SYLLABLE ZE;Lo;0;L;;;;;N;;;;; +A2A1;YI SYLLABLE ZEP;Lo;0;L;;;;;N;;;;; +A2A2;YI SYLLABLE ZUT;Lo;0;L;;;;;N;;;;; +A2A3;YI SYLLABLE ZUX;Lo;0;L;;;;;N;;;;; +A2A4;YI SYLLABLE ZU;Lo;0;L;;;;;N;;;;; +A2A5;YI SYLLABLE ZUP;Lo;0;L;;;;;N;;;;; +A2A6;YI SYLLABLE ZURX;Lo;0;L;;;;;N;;;;; +A2A7;YI SYLLABLE ZUR;Lo;0;L;;;;;N;;;;; +A2A8;YI SYLLABLE ZYT;Lo;0;L;;;;;N;;;;; +A2A9;YI SYLLABLE ZYX;Lo;0;L;;;;;N;;;;; +A2AA;YI SYLLABLE ZY;Lo;0;L;;;;;N;;;;; +A2AB;YI SYLLABLE ZYP;Lo;0;L;;;;;N;;;;; +A2AC;YI SYLLABLE ZYRX;Lo;0;L;;;;;N;;;;; +A2AD;YI SYLLABLE ZYR;Lo;0;L;;;;;N;;;;; +A2AE;YI SYLLABLE CIT;Lo;0;L;;;;;N;;;;; +A2AF;YI SYLLABLE CIX;Lo;0;L;;;;;N;;;;; +A2B0;YI SYLLABLE CI;Lo;0;L;;;;;N;;;;; +A2B1;YI SYLLABLE CIP;Lo;0;L;;;;;N;;;;; +A2B2;YI SYLLABLE CIET;Lo;0;L;;;;;N;;;;; +A2B3;YI SYLLABLE CIEX;Lo;0;L;;;;;N;;;;; +A2B4;YI SYLLABLE CIE;Lo;0;L;;;;;N;;;;; +A2B5;YI SYLLABLE CIEP;Lo;0;L;;;;;N;;;;; +A2B6;YI SYLLABLE CAT;Lo;0;L;;;;;N;;;;; +A2B7;YI SYLLABLE CAX;Lo;0;L;;;;;N;;;;; +A2B8;YI SYLLABLE CA;Lo;0;L;;;;;N;;;;; +A2B9;YI SYLLABLE CAP;Lo;0;L;;;;;N;;;;; +A2BA;YI SYLLABLE CUOX;Lo;0;L;;;;;N;;;;; +A2BB;YI SYLLABLE CUO;Lo;0;L;;;;;N;;;;; +A2BC;YI SYLLABLE CUOP;Lo;0;L;;;;;N;;;;; +A2BD;YI SYLLABLE COT;Lo;0;L;;;;;N;;;;; +A2BE;YI SYLLABLE COX;Lo;0;L;;;;;N;;;;; +A2BF;YI SYLLABLE CO;Lo;0;L;;;;;N;;;;; +A2C0;YI SYLLABLE COP;Lo;0;L;;;;;N;;;;; +A2C1;YI SYLLABLE CEX;Lo;0;L;;;;;N;;;;; +A2C2;YI SYLLABLE CE;Lo;0;L;;;;;N;;;;; +A2C3;YI SYLLABLE CEP;Lo;0;L;;;;;N;;;;; +A2C4;YI SYLLABLE CUT;Lo;0;L;;;;;N;;;;; +A2C5;YI SYLLABLE CUX;Lo;0;L;;;;;N;;;;; +A2C6;YI SYLLABLE CU;Lo;0;L;;;;;N;;;;; +A2C7;YI SYLLABLE CUP;Lo;0;L;;;;;N;;;;; +A2C8;YI SYLLABLE CURX;Lo;0;L;;;;;N;;;;; +A2C9;YI SYLLABLE CUR;Lo;0;L;;;;;N;;;;; +A2CA;YI SYLLABLE CYT;Lo;0;L;;;;;N;;;;; +A2CB;YI SYLLABLE CYX;Lo;0;L;;;;;N;;;;; +A2CC;YI SYLLABLE CY;Lo;0;L;;;;;N;;;;; +A2CD;YI SYLLABLE CYP;Lo;0;L;;;;;N;;;;; +A2CE;YI SYLLABLE CYRX;Lo;0;L;;;;;N;;;;; +A2CF;YI SYLLABLE CYR;Lo;0;L;;;;;N;;;;; +A2D0;YI SYLLABLE ZZIT;Lo;0;L;;;;;N;;;;; +A2D1;YI SYLLABLE ZZIX;Lo;0;L;;;;;N;;;;; +A2D2;YI SYLLABLE ZZI;Lo;0;L;;;;;N;;;;; +A2D3;YI SYLLABLE ZZIP;Lo;0;L;;;;;N;;;;; +A2D4;YI SYLLABLE ZZIET;Lo;0;L;;;;;N;;;;; +A2D5;YI SYLLABLE ZZIEX;Lo;0;L;;;;;N;;;;; +A2D6;YI SYLLABLE ZZIE;Lo;0;L;;;;;N;;;;; +A2D7;YI SYLLABLE ZZIEP;Lo;0;L;;;;;N;;;;; +A2D8;YI SYLLABLE ZZAT;Lo;0;L;;;;;N;;;;; +A2D9;YI SYLLABLE ZZAX;Lo;0;L;;;;;N;;;;; +A2DA;YI SYLLABLE ZZA;Lo;0;L;;;;;N;;;;; +A2DB;YI SYLLABLE ZZAP;Lo;0;L;;;;;N;;;;; +A2DC;YI SYLLABLE ZZOX;Lo;0;L;;;;;N;;;;; +A2DD;YI SYLLABLE ZZO;Lo;0;L;;;;;N;;;;; +A2DE;YI SYLLABLE ZZOP;Lo;0;L;;;;;N;;;;; +A2DF;YI SYLLABLE ZZEX;Lo;0;L;;;;;N;;;;; +A2E0;YI SYLLABLE ZZE;Lo;0;L;;;;;N;;;;; +A2E1;YI SYLLABLE ZZEP;Lo;0;L;;;;;N;;;;; +A2E2;YI SYLLABLE ZZUX;Lo;0;L;;;;;N;;;;; +A2E3;YI SYLLABLE ZZU;Lo;0;L;;;;;N;;;;; +A2E4;YI SYLLABLE ZZUP;Lo;0;L;;;;;N;;;;; +A2E5;YI SYLLABLE ZZURX;Lo;0;L;;;;;N;;;;; +A2E6;YI SYLLABLE ZZUR;Lo;0;L;;;;;N;;;;; +A2E7;YI SYLLABLE ZZYT;Lo;0;L;;;;;N;;;;; +A2E8;YI SYLLABLE ZZYX;Lo;0;L;;;;;N;;;;; +A2E9;YI SYLLABLE ZZY;Lo;0;L;;;;;N;;;;; +A2EA;YI SYLLABLE ZZYP;Lo;0;L;;;;;N;;;;; +A2EB;YI SYLLABLE ZZYRX;Lo;0;L;;;;;N;;;;; +A2EC;YI SYLLABLE ZZYR;Lo;0;L;;;;;N;;;;; +A2ED;YI SYLLABLE NZIT;Lo;0;L;;;;;N;;;;; +A2EE;YI SYLLABLE NZIX;Lo;0;L;;;;;N;;;;; +A2EF;YI SYLLABLE NZI;Lo;0;L;;;;;N;;;;; +A2F0;YI SYLLABLE NZIP;Lo;0;L;;;;;N;;;;; +A2F1;YI SYLLABLE NZIEX;Lo;0;L;;;;;N;;;;; +A2F2;YI SYLLABLE NZIE;Lo;0;L;;;;;N;;;;; +A2F3;YI SYLLABLE NZIEP;Lo;0;L;;;;;N;;;;; +A2F4;YI SYLLABLE NZAT;Lo;0;L;;;;;N;;;;; +A2F5;YI SYLLABLE NZAX;Lo;0;L;;;;;N;;;;; +A2F6;YI SYLLABLE NZA;Lo;0;L;;;;;N;;;;; +A2F7;YI SYLLABLE NZAP;Lo;0;L;;;;;N;;;;; +A2F8;YI SYLLABLE NZUOX;Lo;0;L;;;;;N;;;;; +A2F9;YI SYLLABLE NZUO;Lo;0;L;;;;;N;;;;; +A2FA;YI SYLLABLE NZOX;Lo;0;L;;;;;N;;;;; +A2FB;YI SYLLABLE NZOP;Lo;0;L;;;;;N;;;;; +A2FC;YI SYLLABLE NZEX;Lo;0;L;;;;;N;;;;; +A2FD;YI SYLLABLE NZE;Lo;0;L;;;;;N;;;;; +A2FE;YI SYLLABLE NZUX;Lo;0;L;;;;;N;;;;; +A2FF;YI SYLLABLE NZU;Lo;0;L;;;;;N;;;;; +A300;YI SYLLABLE NZUP;Lo;0;L;;;;;N;;;;; +A301;YI SYLLABLE NZURX;Lo;0;L;;;;;N;;;;; +A302;YI SYLLABLE NZUR;Lo;0;L;;;;;N;;;;; +A303;YI SYLLABLE NZYT;Lo;0;L;;;;;N;;;;; +A304;YI SYLLABLE NZYX;Lo;0;L;;;;;N;;;;; +A305;YI SYLLABLE NZY;Lo;0;L;;;;;N;;;;; +A306;YI SYLLABLE NZYP;Lo;0;L;;;;;N;;;;; +A307;YI SYLLABLE NZYRX;Lo;0;L;;;;;N;;;;; +A308;YI SYLLABLE NZYR;Lo;0;L;;;;;N;;;;; +A309;YI SYLLABLE SIT;Lo;0;L;;;;;N;;;;; +A30A;YI SYLLABLE SIX;Lo;0;L;;;;;N;;;;; +A30B;YI SYLLABLE SI;Lo;0;L;;;;;N;;;;; +A30C;YI SYLLABLE SIP;Lo;0;L;;;;;N;;;;; +A30D;YI SYLLABLE SIEX;Lo;0;L;;;;;N;;;;; +A30E;YI SYLLABLE SIE;Lo;0;L;;;;;N;;;;; +A30F;YI SYLLABLE SIEP;Lo;0;L;;;;;N;;;;; +A310;YI SYLLABLE SAT;Lo;0;L;;;;;N;;;;; +A311;YI SYLLABLE SAX;Lo;0;L;;;;;N;;;;; +A312;YI SYLLABLE SA;Lo;0;L;;;;;N;;;;; +A313;YI SYLLABLE SAP;Lo;0;L;;;;;N;;;;; +A314;YI SYLLABLE SUOX;Lo;0;L;;;;;N;;;;; +A315;YI SYLLABLE SUO;Lo;0;L;;;;;N;;;;; +A316;YI SYLLABLE SUOP;Lo;0;L;;;;;N;;;;; +A317;YI SYLLABLE SOT;Lo;0;L;;;;;N;;;;; +A318;YI SYLLABLE SOX;Lo;0;L;;;;;N;;;;; +A319;YI SYLLABLE SO;Lo;0;L;;;;;N;;;;; +A31A;YI SYLLABLE SOP;Lo;0;L;;;;;N;;;;; +A31B;YI SYLLABLE SEX;Lo;0;L;;;;;N;;;;; +A31C;YI SYLLABLE SE;Lo;0;L;;;;;N;;;;; +A31D;YI SYLLABLE SEP;Lo;0;L;;;;;N;;;;; +A31E;YI SYLLABLE SUT;Lo;0;L;;;;;N;;;;; +A31F;YI SYLLABLE SUX;Lo;0;L;;;;;N;;;;; +A320;YI SYLLABLE SU;Lo;0;L;;;;;N;;;;; +A321;YI SYLLABLE SUP;Lo;0;L;;;;;N;;;;; +A322;YI SYLLABLE SURX;Lo;0;L;;;;;N;;;;; +A323;YI SYLLABLE SUR;Lo;0;L;;;;;N;;;;; +A324;YI SYLLABLE SYT;Lo;0;L;;;;;N;;;;; +A325;YI SYLLABLE SYX;Lo;0;L;;;;;N;;;;; +A326;YI SYLLABLE SY;Lo;0;L;;;;;N;;;;; +A327;YI SYLLABLE SYP;Lo;0;L;;;;;N;;;;; +A328;YI SYLLABLE SYRX;Lo;0;L;;;;;N;;;;; +A329;YI SYLLABLE SYR;Lo;0;L;;;;;N;;;;; +A32A;YI SYLLABLE SSIT;Lo;0;L;;;;;N;;;;; +A32B;YI SYLLABLE SSIX;Lo;0;L;;;;;N;;;;; +A32C;YI SYLLABLE SSI;Lo;0;L;;;;;N;;;;; +A32D;YI SYLLABLE SSIP;Lo;0;L;;;;;N;;;;; +A32E;YI SYLLABLE SSIEX;Lo;0;L;;;;;N;;;;; +A32F;YI SYLLABLE SSIE;Lo;0;L;;;;;N;;;;; +A330;YI SYLLABLE SSIEP;Lo;0;L;;;;;N;;;;; +A331;YI SYLLABLE SSAT;Lo;0;L;;;;;N;;;;; +A332;YI SYLLABLE SSAX;Lo;0;L;;;;;N;;;;; +A333;YI SYLLABLE SSA;Lo;0;L;;;;;N;;;;; +A334;YI SYLLABLE SSAP;Lo;0;L;;;;;N;;;;; +A335;YI SYLLABLE SSOT;Lo;0;L;;;;;N;;;;; +A336;YI SYLLABLE SSOX;Lo;0;L;;;;;N;;;;; +A337;YI SYLLABLE SSO;Lo;0;L;;;;;N;;;;; +A338;YI SYLLABLE SSOP;Lo;0;L;;;;;N;;;;; +A339;YI SYLLABLE SSEX;Lo;0;L;;;;;N;;;;; +A33A;YI SYLLABLE SSE;Lo;0;L;;;;;N;;;;; +A33B;YI SYLLABLE SSEP;Lo;0;L;;;;;N;;;;; +A33C;YI SYLLABLE SSUT;Lo;0;L;;;;;N;;;;; +A33D;YI SYLLABLE SSUX;Lo;0;L;;;;;N;;;;; +A33E;YI SYLLABLE SSU;Lo;0;L;;;;;N;;;;; +A33F;YI SYLLABLE SSUP;Lo;0;L;;;;;N;;;;; +A340;YI SYLLABLE SSYT;Lo;0;L;;;;;N;;;;; +A341;YI SYLLABLE SSYX;Lo;0;L;;;;;N;;;;; +A342;YI SYLLABLE SSY;Lo;0;L;;;;;N;;;;; +A343;YI SYLLABLE SSYP;Lo;0;L;;;;;N;;;;; +A344;YI SYLLABLE SSYRX;Lo;0;L;;;;;N;;;;; +A345;YI SYLLABLE SSYR;Lo;0;L;;;;;N;;;;; +A346;YI SYLLABLE ZHAT;Lo;0;L;;;;;N;;;;; +A347;YI SYLLABLE ZHAX;Lo;0;L;;;;;N;;;;; +A348;YI SYLLABLE ZHA;Lo;0;L;;;;;N;;;;; +A349;YI SYLLABLE ZHAP;Lo;0;L;;;;;N;;;;; +A34A;YI SYLLABLE ZHUOX;Lo;0;L;;;;;N;;;;; +A34B;YI SYLLABLE ZHUO;Lo;0;L;;;;;N;;;;; +A34C;YI SYLLABLE ZHUOP;Lo;0;L;;;;;N;;;;; +A34D;YI SYLLABLE ZHOT;Lo;0;L;;;;;N;;;;; +A34E;YI SYLLABLE ZHOX;Lo;0;L;;;;;N;;;;; +A34F;YI SYLLABLE ZHO;Lo;0;L;;;;;N;;;;; +A350;YI SYLLABLE ZHOP;Lo;0;L;;;;;N;;;;; +A351;YI SYLLABLE ZHET;Lo;0;L;;;;;N;;;;; +A352;YI SYLLABLE ZHEX;Lo;0;L;;;;;N;;;;; +A353;YI SYLLABLE ZHE;Lo;0;L;;;;;N;;;;; +A354;YI SYLLABLE ZHEP;Lo;0;L;;;;;N;;;;; +A355;YI SYLLABLE ZHUT;Lo;0;L;;;;;N;;;;; +A356;YI SYLLABLE ZHUX;Lo;0;L;;;;;N;;;;; +A357;YI SYLLABLE ZHU;Lo;0;L;;;;;N;;;;; +A358;YI SYLLABLE ZHUP;Lo;0;L;;;;;N;;;;; +A359;YI SYLLABLE ZHURX;Lo;0;L;;;;;N;;;;; +A35A;YI SYLLABLE ZHUR;Lo;0;L;;;;;N;;;;; +A35B;YI SYLLABLE ZHYT;Lo;0;L;;;;;N;;;;; +A35C;YI SYLLABLE ZHYX;Lo;0;L;;;;;N;;;;; +A35D;YI SYLLABLE ZHY;Lo;0;L;;;;;N;;;;; +A35E;YI SYLLABLE ZHYP;Lo;0;L;;;;;N;;;;; +A35F;YI SYLLABLE ZHYRX;Lo;0;L;;;;;N;;;;; +A360;YI SYLLABLE ZHYR;Lo;0;L;;;;;N;;;;; +A361;YI SYLLABLE CHAT;Lo;0;L;;;;;N;;;;; +A362;YI SYLLABLE CHAX;Lo;0;L;;;;;N;;;;; +A363;YI SYLLABLE CHA;Lo;0;L;;;;;N;;;;; +A364;YI SYLLABLE CHAP;Lo;0;L;;;;;N;;;;; +A365;YI SYLLABLE CHUOT;Lo;0;L;;;;;N;;;;; +A366;YI SYLLABLE CHUOX;Lo;0;L;;;;;N;;;;; +A367;YI SYLLABLE CHUO;Lo;0;L;;;;;N;;;;; +A368;YI SYLLABLE CHUOP;Lo;0;L;;;;;N;;;;; +A369;YI SYLLABLE CHOT;Lo;0;L;;;;;N;;;;; +A36A;YI SYLLABLE CHOX;Lo;0;L;;;;;N;;;;; +A36B;YI SYLLABLE CHO;Lo;0;L;;;;;N;;;;; +A36C;YI SYLLABLE CHOP;Lo;0;L;;;;;N;;;;; +A36D;YI SYLLABLE CHET;Lo;0;L;;;;;N;;;;; +A36E;YI SYLLABLE CHEX;Lo;0;L;;;;;N;;;;; +A36F;YI SYLLABLE CHE;Lo;0;L;;;;;N;;;;; +A370;YI SYLLABLE CHEP;Lo;0;L;;;;;N;;;;; +A371;YI SYLLABLE CHUX;Lo;0;L;;;;;N;;;;; +A372;YI SYLLABLE CHU;Lo;0;L;;;;;N;;;;; +A373;YI SYLLABLE CHUP;Lo;0;L;;;;;N;;;;; +A374;YI SYLLABLE CHURX;Lo;0;L;;;;;N;;;;; +A375;YI SYLLABLE CHUR;Lo;0;L;;;;;N;;;;; +A376;YI SYLLABLE CHYT;Lo;0;L;;;;;N;;;;; +A377;YI SYLLABLE CHYX;Lo;0;L;;;;;N;;;;; +A378;YI SYLLABLE CHY;Lo;0;L;;;;;N;;;;; +A379;YI SYLLABLE CHYP;Lo;0;L;;;;;N;;;;; +A37A;YI SYLLABLE CHYRX;Lo;0;L;;;;;N;;;;; +A37B;YI SYLLABLE CHYR;Lo;0;L;;;;;N;;;;; +A37C;YI SYLLABLE RRAX;Lo;0;L;;;;;N;;;;; +A37D;YI SYLLABLE RRA;Lo;0;L;;;;;N;;;;; +A37E;YI SYLLABLE RRUOX;Lo;0;L;;;;;N;;;;; +A37F;YI SYLLABLE RRUO;Lo;0;L;;;;;N;;;;; +A380;YI SYLLABLE RROT;Lo;0;L;;;;;N;;;;; +A381;YI SYLLABLE RROX;Lo;0;L;;;;;N;;;;; +A382;YI SYLLABLE RRO;Lo;0;L;;;;;N;;;;; +A383;YI SYLLABLE RROP;Lo;0;L;;;;;N;;;;; +A384;YI SYLLABLE RRET;Lo;0;L;;;;;N;;;;; +A385;YI SYLLABLE RREX;Lo;0;L;;;;;N;;;;; +A386;YI SYLLABLE RRE;Lo;0;L;;;;;N;;;;; +A387;YI SYLLABLE RREP;Lo;0;L;;;;;N;;;;; +A388;YI SYLLABLE RRUT;Lo;0;L;;;;;N;;;;; +A389;YI SYLLABLE RRUX;Lo;0;L;;;;;N;;;;; +A38A;YI SYLLABLE RRU;Lo;0;L;;;;;N;;;;; +A38B;YI SYLLABLE RRUP;Lo;0;L;;;;;N;;;;; +A38C;YI SYLLABLE RRURX;Lo;0;L;;;;;N;;;;; +A38D;YI SYLLABLE RRUR;Lo;0;L;;;;;N;;;;; +A38E;YI SYLLABLE RRYT;Lo;0;L;;;;;N;;;;; +A38F;YI SYLLABLE RRYX;Lo;0;L;;;;;N;;;;; +A390;YI SYLLABLE RRY;Lo;0;L;;;;;N;;;;; +A391;YI SYLLABLE RRYP;Lo;0;L;;;;;N;;;;; +A392;YI SYLLABLE RRYRX;Lo;0;L;;;;;N;;;;; +A393;YI SYLLABLE RRYR;Lo;0;L;;;;;N;;;;; +A394;YI SYLLABLE NRAT;Lo;0;L;;;;;N;;;;; +A395;YI SYLLABLE NRAX;Lo;0;L;;;;;N;;;;; +A396;YI SYLLABLE NRA;Lo;0;L;;;;;N;;;;; +A397;YI SYLLABLE NRAP;Lo;0;L;;;;;N;;;;; +A398;YI SYLLABLE NROX;Lo;0;L;;;;;N;;;;; +A399;YI SYLLABLE NRO;Lo;0;L;;;;;N;;;;; +A39A;YI SYLLABLE NROP;Lo;0;L;;;;;N;;;;; +A39B;YI SYLLABLE NRET;Lo;0;L;;;;;N;;;;; +A39C;YI SYLLABLE NREX;Lo;0;L;;;;;N;;;;; +A39D;YI SYLLABLE NRE;Lo;0;L;;;;;N;;;;; +A39E;YI SYLLABLE NREP;Lo;0;L;;;;;N;;;;; +A39F;YI SYLLABLE NRUT;Lo;0;L;;;;;N;;;;; +A3A0;YI SYLLABLE NRUX;Lo;0;L;;;;;N;;;;; +A3A1;YI SYLLABLE NRU;Lo;0;L;;;;;N;;;;; +A3A2;YI SYLLABLE NRUP;Lo;0;L;;;;;N;;;;; +A3A3;YI SYLLABLE NRURX;Lo;0;L;;;;;N;;;;; +A3A4;YI SYLLABLE NRUR;Lo;0;L;;;;;N;;;;; +A3A5;YI SYLLABLE NRYT;Lo;0;L;;;;;N;;;;; +A3A6;YI SYLLABLE NRYX;Lo;0;L;;;;;N;;;;; +A3A7;YI SYLLABLE NRY;Lo;0;L;;;;;N;;;;; +A3A8;YI SYLLABLE NRYP;Lo;0;L;;;;;N;;;;; +A3A9;YI SYLLABLE NRYRX;Lo;0;L;;;;;N;;;;; +A3AA;YI SYLLABLE NRYR;Lo;0;L;;;;;N;;;;; +A3AB;YI SYLLABLE SHAT;Lo;0;L;;;;;N;;;;; +A3AC;YI SYLLABLE SHAX;Lo;0;L;;;;;N;;;;; +A3AD;YI SYLLABLE SHA;Lo;0;L;;;;;N;;;;; +A3AE;YI SYLLABLE SHAP;Lo;0;L;;;;;N;;;;; +A3AF;YI SYLLABLE SHUOX;Lo;0;L;;;;;N;;;;; +A3B0;YI SYLLABLE SHUO;Lo;0;L;;;;;N;;;;; +A3B1;YI SYLLABLE SHUOP;Lo;0;L;;;;;N;;;;; +A3B2;YI SYLLABLE SHOT;Lo;0;L;;;;;N;;;;; +A3B3;YI SYLLABLE SHOX;Lo;0;L;;;;;N;;;;; +A3B4;YI SYLLABLE SHO;Lo;0;L;;;;;N;;;;; +A3B5;YI SYLLABLE SHOP;Lo;0;L;;;;;N;;;;; +A3B6;YI SYLLABLE SHET;Lo;0;L;;;;;N;;;;; +A3B7;YI SYLLABLE SHEX;Lo;0;L;;;;;N;;;;; +A3B8;YI SYLLABLE SHE;Lo;0;L;;;;;N;;;;; +A3B9;YI SYLLABLE SHEP;Lo;0;L;;;;;N;;;;; +A3BA;YI SYLLABLE SHUT;Lo;0;L;;;;;N;;;;; +A3BB;YI SYLLABLE SHUX;Lo;0;L;;;;;N;;;;; +A3BC;YI SYLLABLE SHU;Lo;0;L;;;;;N;;;;; +A3BD;YI SYLLABLE SHUP;Lo;0;L;;;;;N;;;;; +A3BE;YI SYLLABLE SHURX;Lo;0;L;;;;;N;;;;; +A3BF;YI SYLLABLE SHUR;Lo;0;L;;;;;N;;;;; +A3C0;YI SYLLABLE SHYT;Lo;0;L;;;;;N;;;;; +A3C1;YI SYLLABLE SHYX;Lo;0;L;;;;;N;;;;; +A3C2;YI SYLLABLE SHY;Lo;0;L;;;;;N;;;;; +A3C3;YI SYLLABLE SHYP;Lo;0;L;;;;;N;;;;; +A3C4;YI SYLLABLE SHYRX;Lo;0;L;;;;;N;;;;; +A3C5;YI SYLLABLE SHYR;Lo;0;L;;;;;N;;;;; +A3C6;YI SYLLABLE RAT;Lo;0;L;;;;;N;;;;; +A3C7;YI SYLLABLE RAX;Lo;0;L;;;;;N;;;;; +A3C8;YI SYLLABLE RA;Lo;0;L;;;;;N;;;;; +A3C9;YI SYLLABLE RAP;Lo;0;L;;;;;N;;;;; +A3CA;YI SYLLABLE RUOX;Lo;0;L;;;;;N;;;;; +A3CB;YI SYLLABLE RUO;Lo;0;L;;;;;N;;;;; +A3CC;YI SYLLABLE RUOP;Lo;0;L;;;;;N;;;;; +A3CD;YI SYLLABLE ROT;Lo;0;L;;;;;N;;;;; +A3CE;YI SYLLABLE ROX;Lo;0;L;;;;;N;;;;; +A3CF;YI SYLLABLE RO;Lo;0;L;;;;;N;;;;; +A3D0;YI SYLLABLE ROP;Lo;0;L;;;;;N;;;;; +A3D1;YI SYLLABLE REX;Lo;0;L;;;;;N;;;;; +A3D2;YI SYLLABLE RE;Lo;0;L;;;;;N;;;;; +A3D3;YI SYLLABLE REP;Lo;0;L;;;;;N;;;;; +A3D4;YI SYLLABLE RUT;Lo;0;L;;;;;N;;;;; +A3D5;YI SYLLABLE RUX;Lo;0;L;;;;;N;;;;; +A3D6;YI SYLLABLE RU;Lo;0;L;;;;;N;;;;; +A3D7;YI SYLLABLE RUP;Lo;0;L;;;;;N;;;;; +A3D8;YI SYLLABLE RURX;Lo;0;L;;;;;N;;;;; +A3D9;YI SYLLABLE RUR;Lo;0;L;;;;;N;;;;; +A3DA;YI SYLLABLE RYT;Lo;0;L;;;;;N;;;;; +A3DB;YI SYLLABLE RYX;Lo;0;L;;;;;N;;;;; +A3DC;YI SYLLABLE RY;Lo;0;L;;;;;N;;;;; +A3DD;YI SYLLABLE RYP;Lo;0;L;;;;;N;;;;; +A3DE;YI SYLLABLE RYRX;Lo;0;L;;;;;N;;;;; +A3DF;YI SYLLABLE RYR;Lo;0;L;;;;;N;;;;; +A3E0;YI SYLLABLE JIT;Lo;0;L;;;;;N;;;;; +A3E1;YI SYLLABLE JIX;Lo;0;L;;;;;N;;;;; +A3E2;YI SYLLABLE JI;Lo;0;L;;;;;N;;;;; +A3E3;YI SYLLABLE JIP;Lo;0;L;;;;;N;;;;; +A3E4;YI SYLLABLE JIET;Lo;0;L;;;;;N;;;;; +A3E5;YI SYLLABLE JIEX;Lo;0;L;;;;;N;;;;; +A3E6;YI SYLLABLE JIE;Lo;0;L;;;;;N;;;;; +A3E7;YI SYLLABLE JIEP;Lo;0;L;;;;;N;;;;; +A3E8;YI SYLLABLE JUOT;Lo;0;L;;;;;N;;;;; +A3E9;YI SYLLABLE JUOX;Lo;0;L;;;;;N;;;;; +A3EA;YI SYLLABLE JUO;Lo;0;L;;;;;N;;;;; +A3EB;YI SYLLABLE JUOP;Lo;0;L;;;;;N;;;;; +A3EC;YI SYLLABLE JOT;Lo;0;L;;;;;N;;;;; +A3ED;YI SYLLABLE JOX;Lo;0;L;;;;;N;;;;; +A3EE;YI SYLLABLE JO;Lo;0;L;;;;;N;;;;; +A3EF;YI SYLLABLE JOP;Lo;0;L;;;;;N;;;;; +A3F0;YI SYLLABLE JUT;Lo;0;L;;;;;N;;;;; +A3F1;YI SYLLABLE JUX;Lo;0;L;;;;;N;;;;; +A3F2;YI SYLLABLE JU;Lo;0;L;;;;;N;;;;; +A3F3;YI SYLLABLE JUP;Lo;0;L;;;;;N;;;;; +A3F4;YI SYLLABLE JURX;Lo;0;L;;;;;N;;;;; +A3F5;YI SYLLABLE JUR;Lo;0;L;;;;;N;;;;; +A3F6;YI SYLLABLE JYT;Lo;0;L;;;;;N;;;;; +A3F7;YI SYLLABLE JYX;Lo;0;L;;;;;N;;;;; +A3F8;YI SYLLABLE JY;Lo;0;L;;;;;N;;;;; +A3F9;YI SYLLABLE JYP;Lo;0;L;;;;;N;;;;; +A3FA;YI SYLLABLE JYRX;Lo;0;L;;;;;N;;;;; +A3FB;YI SYLLABLE JYR;Lo;0;L;;;;;N;;;;; +A3FC;YI SYLLABLE QIT;Lo;0;L;;;;;N;;;;; +A3FD;YI SYLLABLE QIX;Lo;0;L;;;;;N;;;;; +A3FE;YI SYLLABLE QI;Lo;0;L;;;;;N;;;;; +A3FF;YI SYLLABLE QIP;Lo;0;L;;;;;N;;;;; +A400;YI SYLLABLE QIET;Lo;0;L;;;;;N;;;;; +A401;YI SYLLABLE QIEX;Lo;0;L;;;;;N;;;;; +A402;YI SYLLABLE QIE;Lo;0;L;;;;;N;;;;; +A403;YI SYLLABLE QIEP;Lo;0;L;;;;;N;;;;; +A404;YI SYLLABLE QUOT;Lo;0;L;;;;;N;;;;; +A405;YI SYLLABLE QUOX;Lo;0;L;;;;;N;;;;; +A406;YI SYLLABLE QUO;Lo;0;L;;;;;N;;;;; +A407;YI SYLLABLE QUOP;Lo;0;L;;;;;N;;;;; +A408;YI SYLLABLE QOT;Lo;0;L;;;;;N;;;;; +A409;YI SYLLABLE QOX;Lo;0;L;;;;;N;;;;; +A40A;YI SYLLABLE QO;Lo;0;L;;;;;N;;;;; +A40B;YI SYLLABLE QOP;Lo;0;L;;;;;N;;;;; +A40C;YI SYLLABLE QUT;Lo;0;L;;;;;N;;;;; +A40D;YI SYLLABLE QUX;Lo;0;L;;;;;N;;;;; +A40E;YI SYLLABLE QU;Lo;0;L;;;;;N;;;;; +A40F;YI SYLLABLE QUP;Lo;0;L;;;;;N;;;;; +A410;YI SYLLABLE QURX;Lo;0;L;;;;;N;;;;; +A411;YI SYLLABLE QUR;Lo;0;L;;;;;N;;;;; +A412;YI SYLLABLE QYT;Lo;0;L;;;;;N;;;;; +A413;YI SYLLABLE QYX;Lo;0;L;;;;;N;;;;; +A414;YI SYLLABLE QY;Lo;0;L;;;;;N;;;;; +A415;YI SYLLABLE QYP;Lo;0;L;;;;;N;;;;; +A416;YI SYLLABLE QYRX;Lo;0;L;;;;;N;;;;; +A417;YI SYLLABLE QYR;Lo;0;L;;;;;N;;;;; +A418;YI SYLLABLE JJIT;Lo;0;L;;;;;N;;;;; +A419;YI SYLLABLE JJIX;Lo;0;L;;;;;N;;;;; +A41A;YI SYLLABLE JJI;Lo;0;L;;;;;N;;;;; +A41B;YI SYLLABLE JJIP;Lo;0;L;;;;;N;;;;; +A41C;YI SYLLABLE JJIET;Lo;0;L;;;;;N;;;;; +A41D;YI SYLLABLE JJIEX;Lo;0;L;;;;;N;;;;; +A41E;YI SYLLABLE JJIE;Lo;0;L;;;;;N;;;;; +A41F;YI SYLLABLE JJIEP;Lo;0;L;;;;;N;;;;; +A420;YI SYLLABLE JJUOX;Lo;0;L;;;;;N;;;;; +A421;YI SYLLABLE JJUO;Lo;0;L;;;;;N;;;;; +A422;YI SYLLABLE JJUOP;Lo;0;L;;;;;N;;;;; +A423;YI SYLLABLE JJOT;Lo;0;L;;;;;N;;;;; +A424;YI SYLLABLE JJOX;Lo;0;L;;;;;N;;;;; +A425;YI SYLLABLE JJO;Lo;0;L;;;;;N;;;;; +A426;YI SYLLABLE JJOP;Lo;0;L;;;;;N;;;;; +A427;YI SYLLABLE JJUT;Lo;0;L;;;;;N;;;;; +A428;YI SYLLABLE JJUX;Lo;0;L;;;;;N;;;;; +A429;YI SYLLABLE JJU;Lo;0;L;;;;;N;;;;; +A42A;YI SYLLABLE JJUP;Lo;0;L;;;;;N;;;;; +A42B;YI SYLLABLE JJURX;Lo;0;L;;;;;N;;;;; +A42C;YI SYLLABLE JJUR;Lo;0;L;;;;;N;;;;; +A42D;YI SYLLABLE JJYT;Lo;0;L;;;;;N;;;;; +A42E;YI SYLLABLE JJYX;Lo;0;L;;;;;N;;;;; +A42F;YI SYLLABLE JJY;Lo;0;L;;;;;N;;;;; +A430;YI SYLLABLE JJYP;Lo;0;L;;;;;N;;;;; +A431;YI SYLLABLE NJIT;Lo;0;L;;;;;N;;;;; +A432;YI SYLLABLE NJIX;Lo;0;L;;;;;N;;;;; +A433;YI SYLLABLE NJI;Lo;0;L;;;;;N;;;;; +A434;YI SYLLABLE NJIP;Lo;0;L;;;;;N;;;;; +A435;YI SYLLABLE NJIET;Lo;0;L;;;;;N;;;;; +A436;YI SYLLABLE NJIEX;Lo;0;L;;;;;N;;;;; +A437;YI SYLLABLE NJIE;Lo;0;L;;;;;N;;;;; +A438;YI SYLLABLE NJIEP;Lo;0;L;;;;;N;;;;; +A439;YI SYLLABLE NJUOX;Lo;0;L;;;;;N;;;;; +A43A;YI SYLLABLE NJUO;Lo;0;L;;;;;N;;;;; +A43B;YI SYLLABLE NJOT;Lo;0;L;;;;;N;;;;; +A43C;YI SYLLABLE NJOX;Lo;0;L;;;;;N;;;;; +A43D;YI SYLLABLE NJO;Lo;0;L;;;;;N;;;;; +A43E;YI SYLLABLE NJOP;Lo;0;L;;;;;N;;;;; +A43F;YI SYLLABLE NJUX;Lo;0;L;;;;;N;;;;; +A440;YI SYLLABLE NJU;Lo;0;L;;;;;N;;;;; +A441;YI SYLLABLE NJUP;Lo;0;L;;;;;N;;;;; +A442;YI SYLLABLE NJURX;Lo;0;L;;;;;N;;;;; +A443;YI SYLLABLE NJUR;Lo;0;L;;;;;N;;;;; +A444;YI SYLLABLE NJYT;Lo;0;L;;;;;N;;;;; +A445;YI SYLLABLE NJYX;Lo;0;L;;;;;N;;;;; +A446;YI SYLLABLE NJY;Lo;0;L;;;;;N;;;;; +A447;YI SYLLABLE NJYP;Lo;0;L;;;;;N;;;;; +A448;YI SYLLABLE NJYRX;Lo;0;L;;;;;N;;;;; +A449;YI SYLLABLE NJYR;Lo;0;L;;;;;N;;;;; +A44A;YI SYLLABLE NYIT;Lo;0;L;;;;;N;;;;; +A44B;YI SYLLABLE NYIX;Lo;0;L;;;;;N;;;;; +A44C;YI SYLLABLE NYI;Lo;0;L;;;;;N;;;;; +A44D;YI SYLLABLE NYIP;Lo;0;L;;;;;N;;;;; +A44E;YI SYLLABLE NYIET;Lo;0;L;;;;;N;;;;; +A44F;YI SYLLABLE NYIEX;Lo;0;L;;;;;N;;;;; +A450;YI SYLLABLE NYIE;Lo;0;L;;;;;N;;;;; +A451;YI SYLLABLE NYIEP;Lo;0;L;;;;;N;;;;; +A452;YI SYLLABLE NYUOX;Lo;0;L;;;;;N;;;;; +A453;YI SYLLABLE NYUO;Lo;0;L;;;;;N;;;;; +A454;YI SYLLABLE NYUOP;Lo;0;L;;;;;N;;;;; +A455;YI SYLLABLE NYOT;Lo;0;L;;;;;N;;;;; +A456;YI SYLLABLE NYOX;Lo;0;L;;;;;N;;;;; +A457;YI SYLLABLE NYO;Lo;0;L;;;;;N;;;;; +A458;YI SYLLABLE NYOP;Lo;0;L;;;;;N;;;;; +A459;YI SYLLABLE NYUT;Lo;0;L;;;;;N;;;;; +A45A;YI SYLLABLE NYUX;Lo;0;L;;;;;N;;;;; +A45B;YI SYLLABLE NYU;Lo;0;L;;;;;N;;;;; +A45C;YI SYLLABLE NYUP;Lo;0;L;;;;;N;;;;; +A45D;YI SYLLABLE XIT;Lo;0;L;;;;;N;;;;; +A45E;YI SYLLABLE XIX;Lo;0;L;;;;;N;;;;; +A45F;YI SYLLABLE XI;Lo;0;L;;;;;N;;;;; +A460;YI SYLLABLE XIP;Lo;0;L;;;;;N;;;;; +A461;YI SYLLABLE XIET;Lo;0;L;;;;;N;;;;; +A462;YI SYLLABLE XIEX;Lo;0;L;;;;;N;;;;; +A463;YI SYLLABLE XIE;Lo;0;L;;;;;N;;;;; +A464;YI SYLLABLE XIEP;Lo;0;L;;;;;N;;;;; +A465;YI SYLLABLE XUOX;Lo;0;L;;;;;N;;;;; +A466;YI SYLLABLE XUO;Lo;0;L;;;;;N;;;;; +A467;YI SYLLABLE XOT;Lo;0;L;;;;;N;;;;; +A468;YI SYLLABLE XOX;Lo;0;L;;;;;N;;;;; +A469;YI SYLLABLE XO;Lo;0;L;;;;;N;;;;; +A46A;YI SYLLABLE XOP;Lo;0;L;;;;;N;;;;; +A46B;YI SYLLABLE XYT;Lo;0;L;;;;;N;;;;; +A46C;YI SYLLABLE XYX;Lo;0;L;;;;;N;;;;; +A46D;YI SYLLABLE XY;Lo;0;L;;;;;N;;;;; +A46E;YI SYLLABLE XYP;Lo;0;L;;;;;N;;;;; +A46F;YI SYLLABLE XYRX;Lo;0;L;;;;;N;;;;; +A470;YI SYLLABLE XYR;Lo;0;L;;;;;N;;;;; +A471;YI SYLLABLE YIT;Lo;0;L;;;;;N;;;;; +A472;YI SYLLABLE YIX;Lo;0;L;;;;;N;;;;; +A473;YI SYLLABLE YI;Lo;0;L;;;;;N;;;;; +A474;YI SYLLABLE YIP;Lo;0;L;;;;;N;;;;; +A475;YI SYLLABLE YIET;Lo;0;L;;;;;N;;;;; +A476;YI SYLLABLE YIEX;Lo;0;L;;;;;N;;;;; +A477;YI SYLLABLE YIE;Lo;0;L;;;;;N;;;;; +A478;YI SYLLABLE YIEP;Lo;0;L;;;;;N;;;;; +A479;YI SYLLABLE YUOT;Lo;0;L;;;;;N;;;;; +A47A;YI SYLLABLE YUOX;Lo;0;L;;;;;N;;;;; +A47B;YI SYLLABLE YUO;Lo;0;L;;;;;N;;;;; +A47C;YI SYLLABLE YUOP;Lo;0;L;;;;;N;;;;; +A47D;YI SYLLABLE YOT;Lo;0;L;;;;;N;;;;; +A47E;YI SYLLABLE YOX;Lo;0;L;;;;;N;;;;; +A47F;YI SYLLABLE YO;Lo;0;L;;;;;N;;;;; +A480;YI SYLLABLE YOP;Lo;0;L;;;;;N;;;;; +A481;YI SYLLABLE YUT;Lo;0;L;;;;;N;;;;; +A482;YI SYLLABLE YUX;Lo;0;L;;;;;N;;;;; +A483;YI SYLLABLE YU;Lo;0;L;;;;;N;;;;; +A484;YI SYLLABLE YUP;Lo;0;L;;;;;N;;;;; +A485;YI SYLLABLE YURX;Lo;0;L;;;;;N;;;;; +A486;YI SYLLABLE YUR;Lo;0;L;;;;;N;;;;; +A487;YI SYLLABLE YYT;Lo;0;L;;;;;N;;;;; +A488;YI SYLLABLE YYX;Lo;0;L;;;;;N;;;;; +A489;YI SYLLABLE YY;Lo;0;L;;;;;N;;;;; +A48A;YI SYLLABLE YYP;Lo;0;L;;;;;N;;;;; +A48B;YI SYLLABLE YYRX;Lo;0;L;;;;;N;;;;; +A48C;YI SYLLABLE YYR;Lo;0;L;;;;;N;;;;; +A490;YI RADICAL QOT;So;0;ON;;;;;N;;;;; +A491;YI RADICAL LI;So;0;ON;;;;;N;;;;; +A492;YI RADICAL KIT;So;0;ON;;;;;N;;;;; +A493;YI RADICAL NYIP;So;0;ON;;;;;N;;;;; +A494;YI RADICAL CYP;So;0;ON;;;;;N;;;;; +A495;YI RADICAL SSI;So;0;ON;;;;;N;;;;; +A496;YI RADICAL GGOP;So;0;ON;;;;;N;;;;; +A497;YI RADICAL GEP;So;0;ON;;;;;N;;;;; +A498;YI RADICAL MI;So;0;ON;;;;;N;;;;; +A499;YI RADICAL HXIT;So;0;ON;;;;;N;;;;; +A49A;YI RADICAL LYR;So;0;ON;;;;;N;;;;; +A49B;YI RADICAL BBUT;So;0;ON;;;;;N;;;;; +A49C;YI RADICAL MOP;So;0;ON;;;;;N;;;;; +A49D;YI RADICAL YO;So;0;ON;;;;;N;;;;; +A49E;YI RADICAL PUT;So;0;ON;;;;;N;;;;; +A49F;YI RADICAL HXUO;So;0;ON;;;;;N;;;;; +A4A0;YI RADICAL TAT;So;0;ON;;;;;N;;;;; +A4A1;YI RADICAL GA;So;0;ON;;;;;N;;;;; +A4A2;YI RADICAL ZUP;So;0;ON;;;;;N;;;;; +A4A3;YI RADICAL CYT;So;0;ON;;;;;N;;;;; +A4A4;YI RADICAL DDUR;So;0;ON;;;;;N;;;;; +A4A5;YI RADICAL BUR;So;0;ON;;;;;N;;;;; +A4A6;YI RADICAL GGUO;So;0;ON;;;;;N;;;;; +A4A7;YI RADICAL NYOP;So;0;ON;;;;;N;;;;; +A4A8;YI RADICAL TU;So;0;ON;;;;;N;;;;; +A4A9;YI RADICAL OP;So;0;ON;;;;;N;;;;; +A4AA;YI RADICAL JJUT;So;0;ON;;;;;N;;;;; +A4AB;YI RADICAL ZOT;So;0;ON;;;;;N;;;;; +A4AC;YI RADICAL PYT;So;0;ON;;;;;N;;;;; +A4AD;YI RADICAL HMO;So;0;ON;;;;;N;;;;; +A4AE;YI RADICAL YIT;So;0;ON;;;;;N;;;;; +A4AF;YI RADICAL VUR;So;0;ON;;;;;N;;;;; +A4B0;YI RADICAL SHY;So;0;ON;;;;;N;;;;; +A4B1;YI RADICAL VEP;So;0;ON;;;;;N;;;;; +A4B2;YI RADICAL ZA;So;0;ON;;;;;N;;;;; +A4B3;YI RADICAL JO;So;0;ON;;;;;N;;;;; +A4B4;YI RADICAL NZUP;So;0;ON;;;;;N;;;;; +A4B5;YI RADICAL JJY;So;0;ON;;;;;N;;;;; +A4B6;YI RADICAL GOT;So;0;ON;;;;;N;;;;; +A4B7;YI RADICAL JJIE;So;0;ON;;;;;N;;;;; +A4B8;YI RADICAL WO;So;0;ON;;;;;N;;;;; +A4B9;YI RADICAL DU;So;0;ON;;;;;N;;;;; +A4BA;YI RADICAL SHUR;So;0;ON;;;;;N;;;;; +A4BB;YI RADICAL LIE;So;0;ON;;;;;N;;;;; +A4BC;YI RADICAL CY;So;0;ON;;;;;N;;;;; +A4BD;YI RADICAL CUOP;So;0;ON;;;;;N;;;;; +A4BE;YI RADICAL CIP;So;0;ON;;;;;N;;;;; +A4BF;YI RADICAL HXOP;So;0;ON;;;;;N;;;;; +A4C0;YI RADICAL SHAT;So;0;ON;;;;;N;;;;; +A4C1;YI RADICAL ZUR;So;0;ON;;;;;N;;;;; +A4C2;YI RADICAL SHOP;So;0;ON;;;;;N;;;;; +A4C3;YI RADICAL CHE;So;0;ON;;;;;N;;;;; +A4C4;YI RADICAL ZZIET;So;0;ON;;;;;N;;;;; +A4C5;YI RADICAL NBIE;So;0;ON;;;;;N;;;;; +A4C6;YI RADICAL KE;So;0;ON;;;;;N;;;;; +A4D0;LISU LETTER BA;Lo;0;L;;;;;N;;;;; +A4D1;LISU LETTER PA;Lo;0;L;;;;;N;;;;; +A4D2;LISU LETTER PHA;Lo;0;L;;;;;N;;;;; +A4D3;LISU LETTER DA;Lo;0;L;;;;;N;;;;; +A4D4;LISU LETTER TA;Lo;0;L;;;;;N;;;;; +A4D5;LISU LETTER THA;Lo;0;L;;;;;N;;;;; +A4D6;LISU LETTER GA;Lo;0;L;;;;;N;;;;; +A4D7;LISU LETTER KA;Lo;0;L;;;;;N;;;;; +A4D8;LISU LETTER KHA;Lo;0;L;;;;;N;;;;; +A4D9;LISU LETTER JA;Lo;0;L;;;;;N;;;;; +A4DA;LISU LETTER CA;Lo;0;L;;;;;N;;;;; +A4DB;LISU LETTER CHA;Lo;0;L;;;;;N;;;;; +A4DC;LISU LETTER DZA;Lo;0;L;;;;;N;;;;; +A4DD;LISU LETTER TSA;Lo;0;L;;;;;N;;;;; +A4DE;LISU LETTER TSHA;Lo;0;L;;;;;N;;;;; +A4DF;LISU LETTER MA;Lo;0;L;;;;;N;;;;; +A4E0;LISU LETTER NA;Lo;0;L;;;;;N;;;;; +A4E1;LISU LETTER LA;Lo;0;L;;;;;N;;;;; +A4E2;LISU LETTER SA;Lo;0;L;;;;;N;;;;; +A4E3;LISU LETTER ZHA;Lo;0;L;;;;;N;;;;; +A4E4;LISU LETTER ZA;Lo;0;L;;;;;N;;;;; +A4E5;LISU LETTER NGA;Lo;0;L;;;;;N;;;;; +A4E6;LISU LETTER HA;Lo;0;L;;;;;N;;;;; +A4E7;LISU LETTER XA;Lo;0;L;;;;;N;;;;; +A4E8;LISU LETTER HHA;Lo;0;L;;;;;N;;;;; +A4E9;LISU LETTER FA;Lo;0;L;;;;;N;;;;; +A4EA;LISU LETTER WA;Lo;0;L;;;;;N;;;;; +A4EB;LISU LETTER SHA;Lo;0;L;;;;;N;;;;; +A4EC;LISU LETTER YA;Lo;0;L;;;;;N;;;;; +A4ED;LISU LETTER GHA;Lo;0;L;;;;;N;;;;; +A4EE;LISU LETTER A;Lo;0;L;;;;;N;;;;; +A4EF;LISU LETTER AE;Lo;0;L;;;;;N;;;;; +A4F0;LISU LETTER E;Lo;0;L;;;;;N;;;;; +A4F1;LISU LETTER EU;Lo;0;L;;;;;N;;;;; +A4F2;LISU LETTER I;Lo;0;L;;;;;N;;;;; +A4F3;LISU LETTER O;Lo;0;L;;;;;N;;;;; +A4F4;LISU LETTER U;Lo;0;L;;;;;N;;;;; +A4F5;LISU LETTER UE;Lo;0;L;;;;;N;;;;; +A4F6;LISU LETTER UH;Lo;0;L;;;;;N;;;;; +A4F7;LISU LETTER OE;Lo;0;L;;;;;N;;;;; +A4F8;LISU LETTER TONE MYA TI;Lm;0;L;;;;;N;;;;; +A4F9;LISU LETTER TONE NA PO;Lm;0;L;;;;;N;;;;; +A4FA;LISU LETTER TONE MYA CYA;Lm;0;L;;;;;N;;;;; +A4FB;LISU LETTER TONE MYA BO;Lm;0;L;;;;;N;;;;; +A4FC;LISU LETTER TONE MYA NA;Lm;0;L;;;;;N;;;;; +A4FD;LISU LETTER TONE MYA JEU;Lm;0;L;;;;;N;;;;; +A4FE;LISU PUNCTUATION COMMA;Po;0;L;;;;;N;;;;; +A4FF;LISU PUNCTUATION FULL STOP;Po;0;L;;;;;N;;;;; +A500;VAI SYLLABLE EE;Lo;0;L;;;;;N;;;;; +A501;VAI SYLLABLE EEN;Lo;0;L;;;;;N;;;;; +A502;VAI SYLLABLE HEE;Lo;0;L;;;;;N;;;;; +A503;VAI SYLLABLE WEE;Lo;0;L;;;;;N;;;;; +A504;VAI SYLLABLE WEEN;Lo;0;L;;;;;N;;;;; +A505;VAI SYLLABLE PEE;Lo;0;L;;;;;N;;;;; +A506;VAI SYLLABLE BHEE;Lo;0;L;;;;;N;;;;; +A507;VAI SYLLABLE BEE;Lo;0;L;;;;;N;;;;; +A508;VAI SYLLABLE MBEE;Lo;0;L;;;;;N;;;;; +A509;VAI SYLLABLE KPEE;Lo;0;L;;;;;N;;;;; +A50A;VAI SYLLABLE MGBEE;Lo;0;L;;;;;N;;;;; +A50B;VAI SYLLABLE GBEE;Lo;0;L;;;;;N;;;;; +A50C;VAI SYLLABLE FEE;Lo;0;L;;;;;N;;;;; +A50D;VAI SYLLABLE VEE;Lo;0;L;;;;;N;;;;; +A50E;VAI SYLLABLE TEE;Lo;0;L;;;;;N;;;;; +A50F;VAI SYLLABLE THEE;Lo;0;L;;;;;N;;;;; +A510;VAI SYLLABLE DHEE;Lo;0;L;;;;;N;;;;; +A511;VAI SYLLABLE DHHEE;Lo;0;L;;;;;N;;;;; +A512;VAI SYLLABLE LEE;Lo;0;L;;;;;N;;;;; +A513;VAI SYLLABLE REE;Lo;0;L;;;;;N;;;;; +A514;VAI SYLLABLE DEE;Lo;0;L;;;;;N;;;;; +A515;VAI SYLLABLE NDEE;Lo;0;L;;;;;N;;;;; +A516;VAI SYLLABLE SEE;Lo;0;L;;;;;N;;;;; +A517;VAI SYLLABLE SHEE;Lo;0;L;;;;;N;;;;; +A518;VAI SYLLABLE ZEE;Lo;0;L;;;;;N;;;;; +A519;VAI SYLLABLE ZHEE;Lo;0;L;;;;;N;;;;; +A51A;VAI SYLLABLE CEE;Lo;0;L;;;;;N;;;;; +A51B;VAI SYLLABLE JEE;Lo;0;L;;;;;N;;;;; +A51C;VAI SYLLABLE NJEE;Lo;0;L;;;;;N;;;;; +A51D;VAI SYLLABLE YEE;Lo;0;L;;;;;N;;;;; +A51E;VAI SYLLABLE KEE;Lo;0;L;;;;;N;;;;; +A51F;VAI SYLLABLE NGGEE;Lo;0;L;;;;;N;;;;; +A520;VAI SYLLABLE GEE;Lo;0;L;;;;;N;;;;; +A521;VAI SYLLABLE MEE;Lo;0;L;;;;;N;;;;; +A522;VAI SYLLABLE NEE;Lo;0;L;;;;;N;;;;; +A523;VAI SYLLABLE NYEE;Lo;0;L;;;;;N;;;;; +A524;VAI SYLLABLE I;Lo;0;L;;;;;N;;;;; +A525;VAI SYLLABLE IN;Lo;0;L;;;;;N;;;;; +A526;VAI SYLLABLE HI;Lo;0;L;;;;;N;;;;; +A527;VAI SYLLABLE HIN;Lo;0;L;;;;;N;;;;; +A528;VAI SYLLABLE WI;Lo;0;L;;;;;N;;;;; +A529;VAI SYLLABLE WIN;Lo;0;L;;;;;N;;;;; +A52A;VAI SYLLABLE PI;Lo;0;L;;;;;N;;;;; +A52B;VAI SYLLABLE BHI;Lo;0;L;;;;;N;;;;; +A52C;VAI SYLLABLE BI;Lo;0;L;;;;;N;;;;; +A52D;VAI SYLLABLE MBI;Lo;0;L;;;;;N;;;;; +A52E;VAI SYLLABLE KPI;Lo;0;L;;;;;N;;;;; +A52F;VAI SYLLABLE MGBI;Lo;0;L;;;;;N;;;;; +A530;VAI SYLLABLE GBI;Lo;0;L;;;;;N;;;;; +A531;VAI SYLLABLE FI;Lo;0;L;;;;;N;;;;; +A532;VAI SYLLABLE VI;Lo;0;L;;;;;N;;;;; +A533;VAI SYLLABLE TI;Lo;0;L;;;;;N;;;;; +A534;VAI SYLLABLE THI;Lo;0;L;;;;;N;;;;; +A535;VAI SYLLABLE DHI;Lo;0;L;;;;;N;;;;; +A536;VAI SYLLABLE DHHI;Lo;0;L;;;;;N;;;;; +A537;VAI SYLLABLE LI;Lo;0;L;;;;;N;;;;; +A538;VAI SYLLABLE RI;Lo;0;L;;;;;N;;;;; +A539;VAI SYLLABLE DI;Lo;0;L;;;;;N;;;;; +A53A;VAI SYLLABLE NDI;Lo;0;L;;;;;N;;;;; +A53B;VAI SYLLABLE SI;Lo;0;L;;;;;N;;;;; +A53C;VAI SYLLABLE SHI;Lo;0;L;;;;;N;;;;; +A53D;VAI SYLLABLE ZI;Lo;0;L;;;;;N;;;;; +A53E;VAI SYLLABLE ZHI;Lo;0;L;;;;;N;;;;; +A53F;VAI SYLLABLE CI;Lo;0;L;;;;;N;;;;; +A540;VAI SYLLABLE JI;Lo;0;L;;;;;N;;;;; +A541;VAI SYLLABLE NJI;Lo;0;L;;;;;N;;;;; +A542;VAI SYLLABLE YI;Lo;0;L;;;;;N;;;;; +A543;VAI SYLLABLE KI;Lo;0;L;;;;;N;;;;; +A544;VAI SYLLABLE NGGI;Lo;0;L;;;;;N;;;;; +A545;VAI SYLLABLE GI;Lo;0;L;;;;;N;;;;; +A546;VAI SYLLABLE MI;Lo;0;L;;;;;N;;;;; +A547;VAI SYLLABLE NI;Lo;0;L;;;;;N;;;;; +A548;VAI SYLLABLE NYI;Lo;0;L;;;;;N;;;;; +A549;VAI SYLLABLE A;Lo;0;L;;;;;N;;;;; +A54A;VAI SYLLABLE AN;Lo;0;L;;;;;N;;;;; +A54B;VAI SYLLABLE NGAN;Lo;0;L;;;;;N;;;;; +A54C;VAI SYLLABLE HA;Lo;0;L;;;;;N;;;;; +A54D;VAI SYLLABLE HAN;Lo;0;L;;;;;N;;;;; +A54E;VAI SYLLABLE WA;Lo;0;L;;;;;N;;;;; +A54F;VAI SYLLABLE WAN;Lo;0;L;;;;;N;;;;; +A550;VAI SYLLABLE PA;Lo;0;L;;;;;N;;;;; +A551;VAI SYLLABLE BHA;Lo;0;L;;;;;N;;;;; +A552;VAI SYLLABLE BA;Lo;0;L;;;;;N;;;;; +A553;VAI SYLLABLE MBA;Lo;0;L;;;;;N;;;;; +A554;VAI SYLLABLE KPA;Lo;0;L;;;;;N;;;;; +A555;VAI SYLLABLE KPAN;Lo;0;L;;;;;N;;;;; +A556;VAI SYLLABLE MGBA;Lo;0;L;;;;;N;;;;; +A557;VAI SYLLABLE GBA;Lo;0;L;;;;;N;;;;; +A558;VAI SYLLABLE FA;Lo;0;L;;;;;N;;;;; +A559;VAI SYLLABLE VA;Lo;0;L;;;;;N;;;;; +A55A;VAI SYLLABLE TA;Lo;0;L;;;;;N;;;;; +A55B;VAI SYLLABLE THA;Lo;0;L;;;;;N;;;;; +A55C;VAI SYLLABLE DHA;Lo;0;L;;;;;N;;;;; +A55D;VAI SYLLABLE DHHA;Lo;0;L;;;;;N;;;;; +A55E;VAI SYLLABLE LA;Lo;0;L;;;;;N;;;;; +A55F;VAI SYLLABLE RA;Lo;0;L;;;;;N;;;;; +A560;VAI SYLLABLE DA;Lo;0;L;;;;;N;;;;; +A561;VAI SYLLABLE NDA;Lo;0;L;;;;;N;;;;; +A562;VAI SYLLABLE SA;Lo;0;L;;;;;N;;;;; +A563;VAI SYLLABLE SHA;Lo;0;L;;;;;N;;;;; +A564;VAI SYLLABLE ZA;Lo;0;L;;;;;N;;;;; +A565;VAI SYLLABLE ZHA;Lo;0;L;;;;;N;;;;; +A566;VAI SYLLABLE CA;Lo;0;L;;;;;N;;;;; +A567;VAI SYLLABLE JA;Lo;0;L;;;;;N;;;;; +A568;VAI SYLLABLE NJA;Lo;0;L;;;;;N;;;;; +A569;VAI SYLLABLE YA;Lo;0;L;;;;;N;;;;; +A56A;VAI SYLLABLE KA;Lo;0;L;;;;;N;;;;; +A56B;VAI SYLLABLE KAN;Lo;0;L;;;;;N;;;;; +A56C;VAI SYLLABLE NGGA;Lo;0;L;;;;;N;;;;; +A56D;VAI SYLLABLE GA;Lo;0;L;;;;;N;;;;; +A56E;VAI SYLLABLE MA;Lo;0;L;;;;;N;;;;; +A56F;VAI SYLLABLE NA;Lo;0;L;;;;;N;;;;; +A570;VAI SYLLABLE NYA;Lo;0;L;;;;;N;;;;; +A571;VAI SYLLABLE OO;Lo;0;L;;;;;N;;;;; +A572;VAI SYLLABLE OON;Lo;0;L;;;;;N;;;;; +A573;VAI SYLLABLE HOO;Lo;0;L;;;;;N;;;;; +A574;VAI SYLLABLE WOO;Lo;0;L;;;;;N;;;;; +A575;VAI SYLLABLE WOON;Lo;0;L;;;;;N;;;;; +A576;VAI SYLLABLE POO;Lo;0;L;;;;;N;;;;; +A577;VAI SYLLABLE BHOO;Lo;0;L;;;;;N;;;;; +A578;VAI SYLLABLE BOO;Lo;0;L;;;;;N;;;;; +A579;VAI SYLLABLE MBOO;Lo;0;L;;;;;N;;;;; +A57A;VAI SYLLABLE KPOO;Lo;0;L;;;;;N;;;;; +A57B;VAI SYLLABLE MGBOO;Lo;0;L;;;;;N;;;;; +A57C;VAI SYLLABLE GBOO;Lo;0;L;;;;;N;;;;; +A57D;VAI SYLLABLE FOO;Lo;0;L;;;;;N;;;;; +A57E;VAI SYLLABLE VOO;Lo;0;L;;;;;N;;;;; +A57F;VAI SYLLABLE TOO;Lo;0;L;;;;;N;;;;; +A580;VAI SYLLABLE THOO;Lo;0;L;;;;;N;;;;; +A581;VAI SYLLABLE DHOO;Lo;0;L;;;;;N;;;;; +A582;VAI SYLLABLE DHHOO;Lo;0;L;;;;;N;;;;; +A583;VAI SYLLABLE LOO;Lo;0;L;;;;;N;;;;; +A584;VAI SYLLABLE ROO;Lo;0;L;;;;;N;;;;; +A585;VAI SYLLABLE DOO;Lo;0;L;;;;;N;;;;; +A586;VAI SYLLABLE NDOO;Lo;0;L;;;;;N;;;;; +A587;VAI SYLLABLE SOO;Lo;0;L;;;;;N;;;;; +A588;VAI SYLLABLE SHOO;Lo;0;L;;;;;N;;;;; +A589;VAI SYLLABLE ZOO;Lo;0;L;;;;;N;;;;; +A58A;VAI SYLLABLE ZHOO;Lo;0;L;;;;;N;;;;; +A58B;VAI SYLLABLE COO;Lo;0;L;;;;;N;;;;; +A58C;VAI SYLLABLE JOO;Lo;0;L;;;;;N;;;;; +A58D;VAI SYLLABLE NJOO;Lo;0;L;;;;;N;;;;; +A58E;VAI SYLLABLE YOO;Lo;0;L;;;;;N;;;;; +A58F;VAI SYLLABLE KOO;Lo;0;L;;;;;N;;;;; +A590;VAI SYLLABLE NGGOO;Lo;0;L;;;;;N;;;;; +A591;VAI SYLLABLE GOO;Lo;0;L;;;;;N;;;;; +A592;VAI SYLLABLE MOO;Lo;0;L;;;;;N;;;;; +A593;VAI SYLLABLE NOO;Lo;0;L;;;;;N;;;;; +A594;VAI SYLLABLE NYOO;Lo;0;L;;;;;N;;;;; +A595;VAI SYLLABLE U;Lo;0;L;;;;;N;;;;; +A596;VAI SYLLABLE UN;Lo;0;L;;;;;N;;;;; +A597;VAI SYLLABLE HU;Lo;0;L;;;;;N;;;;; +A598;VAI SYLLABLE HUN;Lo;0;L;;;;;N;;;;; +A599;VAI SYLLABLE WU;Lo;0;L;;;;;N;;;;; +A59A;VAI SYLLABLE WUN;Lo;0;L;;;;;N;;;;; +A59B;VAI SYLLABLE PU;Lo;0;L;;;;;N;;;;; +A59C;VAI SYLLABLE BHU;Lo;0;L;;;;;N;;;;; +A59D;VAI SYLLABLE BU;Lo;0;L;;;;;N;;;;; +A59E;VAI SYLLABLE MBU;Lo;0;L;;;;;N;;;;; +A59F;VAI SYLLABLE KPU;Lo;0;L;;;;;N;;;;; +A5A0;VAI SYLLABLE MGBU;Lo;0;L;;;;;N;;;;; +A5A1;VAI SYLLABLE GBU;Lo;0;L;;;;;N;;;;; +A5A2;VAI SYLLABLE FU;Lo;0;L;;;;;N;;;;; +A5A3;VAI SYLLABLE VU;Lo;0;L;;;;;N;;;;; +A5A4;VAI SYLLABLE TU;Lo;0;L;;;;;N;;;;; +A5A5;VAI SYLLABLE THU;Lo;0;L;;;;;N;;;;; +A5A6;VAI SYLLABLE DHU;Lo;0;L;;;;;N;;;;; +A5A7;VAI SYLLABLE DHHU;Lo;0;L;;;;;N;;;;; +A5A8;VAI SYLLABLE LU;Lo;0;L;;;;;N;;;;; +A5A9;VAI SYLLABLE RU;Lo;0;L;;;;;N;;;;; +A5AA;VAI SYLLABLE DU;Lo;0;L;;;;;N;;;;; +A5AB;VAI SYLLABLE NDU;Lo;0;L;;;;;N;;;;; +A5AC;VAI SYLLABLE SU;Lo;0;L;;;;;N;;;;; +A5AD;VAI SYLLABLE SHU;Lo;0;L;;;;;N;;;;; +A5AE;VAI SYLLABLE ZU;Lo;0;L;;;;;N;;;;; +A5AF;VAI SYLLABLE ZHU;Lo;0;L;;;;;N;;;;; +A5B0;VAI SYLLABLE CU;Lo;0;L;;;;;N;;;;; +A5B1;VAI SYLLABLE JU;Lo;0;L;;;;;N;;;;; +A5B2;VAI SYLLABLE NJU;Lo;0;L;;;;;N;;;;; +A5B3;VAI SYLLABLE YU;Lo;0;L;;;;;N;;;;; +A5B4;VAI SYLLABLE KU;Lo;0;L;;;;;N;;;;; +A5B5;VAI SYLLABLE NGGU;Lo;0;L;;;;;N;;;;; +A5B6;VAI SYLLABLE GU;Lo;0;L;;;;;N;;;;; +A5B7;VAI SYLLABLE MU;Lo;0;L;;;;;N;;;;; +A5B8;VAI SYLLABLE NU;Lo;0;L;;;;;N;;;;; +A5B9;VAI SYLLABLE NYU;Lo;0;L;;;;;N;;;;; +A5BA;VAI SYLLABLE O;Lo;0;L;;;;;N;;;;; +A5BB;VAI SYLLABLE ON;Lo;0;L;;;;;N;;;;; +A5BC;VAI SYLLABLE NGON;Lo;0;L;;;;;N;;;;; +A5BD;VAI SYLLABLE HO;Lo;0;L;;;;;N;;;;; +A5BE;VAI SYLLABLE HON;Lo;0;L;;;;;N;;;;; +A5BF;VAI SYLLABLE WO;Lo;0;L;;;;;N;;;;; +A5C0;VAI SYLLABLE WON;Lo;0;L;;;;;N;;;;; +A5C1;VAI SYLLABLE PO;Lo;0;L;;;;;N;;;;; +A5C2;VAI SYLLABLE BHO;Lo;0;L;;;;;N;;;;; +A5C3;VAI SYLLABLE BO;Lo;0;L;;;;;N;;;;; +A5C4;VAI SYLLABLE MBO;Lo;0;L;;;;;N;;;;; +A5C5;VAI SYLLABLE KPO;Lo;0;L;;;;;N;;;;; +A5C6;VAI SYLLABLE MGBO;Lo;0;L;;;;;N;;;;; +A5C7;VAI SYLLABLE GBO;Lo;0;L;;;;;N;;;;; +A5C8;VAI SYLLABLE GBON;Lo;0;L;;;;;N;;;;; +A5C9;VAI SYLLABLE FO;Lo;0;L;;;;;N;;;;; +A5CA;VAI SYLLABLE VO;Lo;0;L;;;;;N;;;;; +A5CB;VAI SYLLABLE TO;Lo;0;L;;;;;N;;;;; +A5CC;VAI SYLLABLE THO;Lo;0;L;;;;;N;;;;; +A5CD;VAI SYLLABLE DHO;Lo;0;L;;;;;N;;;;; +A5CE;VAI SYLLABLE DHHO;Lo;0;L;;;;;N;;;;; +A5CF;VAI SYLLABLE LO;Lo;0;L;;;;;N;;;;; +A5D0;VAI SYLLABLE RO;Lo;0;L;;;;;N;;;;; +A5D1;VAI SYLLABLE DO;Lo;0;L;;;;;N;;;;; +A5D2;VAI SYLLABLE NDO;Lo;0;L;;;;;N;;;;; +A5D3;VAI SYLLABLE SO;Lo;0;L;;;;;N;;;;; +A5D4;VAI SYLLABLE SHO;Lo;0;L;;;;;N;;;;; +A5D5;VAI SYLLABLE ZO;Lo;0;L;;;;;N;;;;; +A5D6;VAI SYLLABLE ZHO;Lo;0;L;;;;;N;;;;; +A5D7;VAI SYLLABLE CO;Lo;0;L;;;;;N;;;;; +A5D8;VAI SYLLABLE JO;Lo;0;L;;;;;N;;;;; +A5D9;VAI SYLLABLE NJO;Lo;0;L;;;;;N;;;;; +A5DA;VAI SYLLABLE YO;Lo;0;L;;;;;N;;;;; +A5DB;VAI SYLLABLE KO;Lo;0;L;;;;;N;;;;; +A5DC;VAI SYLLABLE NGGO;Lo;0;L;;;;;N;;;;; +A5DD;VAI SYLLABLE GO;Lo;0;L;;;;;N;;;;; +A5DE;VAI SYLLABLE MO;Lo;0;L;;;;;N;;;;; +A5DF;VAI SYLLABLE NO;Lo;0;L;;;;;N;;;;; +A5E0;VAI SYLLABLE NYO;Lo;0;L;;;;;N;;;;; +A5E1;VAI SYLLABLE E;Lo;0;L;;;;;N;;;;; +A5E2;VAI SYLLABLE EN;Lo;0;L;;;;;N;;;;; +A5E3;VAI SYLLABLE NGEN;Lo;0;L;;;;;N;;;;; +A5E4;VAI SYLLABLE HE;Lo;0;L;;;;;N;;;;; +A5E5;VAI SYLLABLE HEN;Lo;0;L;;;;;N;;;;; +A5E6;VAI SYLLABLE WE;Lo;0;L;;;;;N;;;;; +A5E7;VAI SYLLABLE WEN;Lo;0;L;;;;;N;;;;; +A5E8;VAI SYLLABLE PE;Lo;0;L;;;;;N;;;;; +A5E9;VAI SYLLABLE BHE;Lo;0;L;;;;;N;;;;; +A5EA;VAI SYLLABLE BE;Lo;0;L;;;;;N;;;;; +A5EB;VAI SYLLABLE MBE;Lo;0;L;;;;;N;;;;; +A5EC;VAI SYLLABLE KPE;Lo;0;L;;;;;N;;;;; +A5ED;VAI SYLLABLE KPEN;Lo;0;L;;;;;N;;;;; +A5EE;VAI SYLLABLE MGBE;Lo;0;L;;;;;N;;;;; +A5EF;VAI SYLLABLE GBE;Lo;0;L;;;;;N;;;;; +A5F0;VAI SYLLABLE GBEN;Lo;0;L;;;;;N;;;;; +A5F1;VAI SYLLABLE FE;Lo;0;L;;;;;N;;;;; +A5F2;VAI SYLLABLE VE;Lo;0;L;;;;;N;;;;; +A5F3;VAI SYLLABLE TE;Lo;0;L;;;;;N;;;;; +A5F4;VAI SYLLABLE THE;Lo;0;L;;;;;N;;;;; +A5F5;VAI SYLLABLE DHE;Lo;0;L;;;;;N;;;;; +A5F6;VAI SYLLABLE DHHE;Lo;0;L;;;;;N;;;;; +A5F7;VAI SYLLABLE LE;Lo;0;L;;;;;N;;;;; +A5F8;VAI SYLLABLE RE;Lo;0;L;;;;;N;;;;; +A5F9;VAI SYLLABLE DE;Lo;0;L;;;;;N;;;;; +A5FA;VAI SYLLABLE NDE;Lo;0;L;;;;;N;;;;; +A5FB;VAI SYLLABLE SE;Lo;0;L;;;;;N;;;;; +A5FC;VAI SYLLABLE SHE;Lo;0;L;;;;;N;;;;; +A5FD;VAI SYLLABLE ZE;Lo;0;L;;;;;N;;;;; +A5FE;VAI SYLLABLE ZHE;Lo;0;L;;;;;N;;;;; +A5FF;VAI SYLLABLE CE;Lo;0;L;;;;;N;;;;; +A600;VAI SYLLABLE JE;Lo;0;L;;;;;N;;;;; +A601;VAI SYLLABLE NJE;Lo;0;L;;;;;N;;;;; +A602;VAI SYLLABLE YE;Lo;0;L;;;;;N;;;;; +A603;VAI SYLLABLE KE;Lo;0;L;;;;;N;;;;; +A604;VAI SYLLABLE NGGE;Lo;0;L;;;;;N;;;;; +A605;VAI SYLLABLE NGGEN;Lo;0;L;;;;;N;;;;; +A606;VAI SYLLABLE GE;Lo;0;L;;;;;N;;;;; +A607;VAI SYLLABLE GEN;Lo;0;L;;;;;N;;;;; +A608;VAI SYLLABLE ME;Lo;0;L;;;;;N;;;;; +A609;VAI SYLLABLE NE;Lo;0;L;;;;;N;;;;; +A60A;VAI SYLLABLE NYE;Lo;0;L;;;;;N;;;;; +A60B;VAI SYLLABLE NG;Lo;0;L;;;;;N;;;;; +A60C;VAI SYLLABLE LENGTHENER;Lm;0;L;;;;;N;;;;; +A60D;VAI COMMA;Po;0;ON;;;;;N;;;;; +A60E;VAI FULL STOP;Po;0;ON;;;;;N;;;;; +A60F;VAI QUESTION MARK;Po;0;ON;;;;;N;;;;; +A610;VAI SYLLABLE NDOLE FA;Lo;0;L;;;;;N;;;;; +A611;VAI SYLLABLE NDOLE KA;Lo;0;L;;;;;N;;;;; +A612;VAI SYLLABLE NDOLE SOO;Lo;0;L;;;;;N;;;;; +A613;VAI SYMBOL FEENG;Lo;0;L;;;;;N;;;;; +A614;VAI SYMBOL KEENG;Lo;0;L;;;;;N;;;;; +A615;VAI SYMBOL TING;Lo;0;L;;;;;N;;;;; +A616;VAI SYMBOL NII;Lo;0;L;;;;;N;;;;; +A617;VAI SYMBOL BANG;Lo;0;L;;;;;N;;;;; +A618;VAI SYMBOL FAA;Lo;0;L;;;;;N;;;;; +A619;VAI SYMBOL TAA;Lo;0;L;;;;;N;;;;; +A61A;VAI SYMBOL DANG;Lo;0;L;;;;;N;;;;; +A61B;VAI SYMBOL DOONG;Lo;0;L;;;;;N;;;;; +A61C;VAI SYMBOL KUNG;Lo;0;L;;;;;N;;;;; +A61D;VAI SYMBOL TONG;Lo;0;L;;;;;N;;;;; +A61E;VAI SYMBOL DO-O;Lo;0;L;;;;;N;;;;; +A61F;VAI SYMBOL JONG;Lo;0;L;;;;;N;;;;; +A620;VAI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +A621;VAI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +A622;VAI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +A623;VAI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +A624;VAI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +A625;VAI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +A626;VAI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +A627;VAI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +A628;VAI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +A629;VAI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +A62A;VAI SYLLABLE NDOLE MA;Lo;0;L;;;;;N;;;;; +A62B;VAI SYLLABLE NDOLE DO;Lo;0;L;;;;;N;;;;; +A640;CYRILLIC CAPITAL LETTER ZEMLYA;Lu;0;L;;;;;N;;;;A641; +A641;CYRILLIC SMALL LETTER ZEMLYA;Ll;0;L;;;;;N;;;A640;;A640 +A642;CYRILLIC CAPITAL LETTER DZELO;Lu;0;L;;;;;N;;;;A643; +A643;CYRILLIC SMALL LETTER DZELO;Ll;0;L;;;;;N;;;A642;;A642 +A644;CYRILLIC CAPITAL LETTER REVERSED DZE;Lu;0;L;;;;;N;;;;A645; +A645;CYRILLIC SMALL LETTER REVERSED DZE;Ll;0;L;;;;;N;;;A644;;A644 +A646;CYRILLIC CAPITAL LETTER IOTA;Lu;0;L;;;;;N;;;;A647; +A647;CYRILLIC SMALL LETTER IOTA;Ll;0;L;;;;;N;;;A646;;A646 +A648;CYRILLIC CAPITAL LETTER DJERV;Lu;0;L;;;;;N;;;;A649; +A649;CYRILLIC SMALL LETTER DJERV;Ll;0;L;;;;;N;;;A648;;A648 +A64A;CYRILLIC CAPITAL LETTER MONOGRAPH UK;Lu;0;L;;;;;N;;;;A64B; +A64B;CYRILLIC SMALL LETTER MONOGRAPH UK;Ll;0;L;;;;;N;;;A64A;;A64A +A64C;CYRILLIC CAPITAL LETTER BROAD OMEGA;Lu;0;L;;;;;N;;;;A64D; +A64D;CYRILLIC SMALL LETTER BROAD OMEGA;Ll;0;L;;;;;N;;;A64C;;A64C +A64E;CYRILLIC CAPITAL LETTER NEUTRAL YER;Lu;0;L;;;;;N;;;;A64F; +A64F;CYRILLIC SMALL LETTER NEUTRAL YER;Ll;0;L;;;;;N;;;A64E;;A64E +A650;CYRILLIC CAPITAL LETTER YERU WITH BACK YER;Lu;0;L;;;;;N;;;;A651; +A651;CYRILLIC SMALL LETTER YERU WITH BACK YER;Ll;0;L;;;;;N;;;A650;;A650 +A652;CYRILLIC CAPITAL LETTER IOTIFIED YAT;Lu;0;L;;;;;N;;;;A653; +A653;CYRILLIC SMALL LETTER IOTIFIED YAT;Ll;0;L;;;;;N;;;A652;;A652 +A654;CYRILLIC CAPITAL LETTER REVERSED YU;Lu;0;L;;;;;N;;;;A655; +A655;CYRILLIC SMALL LETTER REVERSED YU;Ll;0;L;;;;;N;;;A654;;A654 +A656;CYRILLIC CAPITAL LETTER IOTIFIED A;Lu;0;L;;;;;N;;;;A657; +A657;CYRILLIC SMALL LETTER IOTIFIED A;Ll;0;L;;;;;N;;;A656;;A656 +A658;CYRILLIC CAPITAL LETTER CLOSED LITTLE YUS;Lu;0;L;;;;;N;;;;A659; +A659;CYRILLIC SMALL LETTER CLOSED LITTLE YUS;Ll;0;L;;;;;N;;;A658;;A658 +A65A;CYRILLIC CAPITAL LETTER BLENDED YUS;Lu;0;L;;;;;N;;;;A65B; +A65B;CYRILLIC SMALL LETTER BLENDED YUS;Ll;0;L;;;;;N;;;A65A;;A65A +A65C;CYRILLIC CAPITAL LETTER IOTIFIED CLOSED LITTLE YUS;Lu;0;L;;;;;N;;;;A65D; +A65D;CYRILLIC SMALL LETTER IOTIFIED CLOSED LITTLE YUS;Ll;0;L;;;;;N;;;A65C;;A65C +A65E;CYRILLIC CAPITAL LETTER YN;Lu;0;L;;;;;N;;;;A65F; +A65F;CYRILLIC SMALL LETTER YN;Ll;0;L;;;;;N;;;A65E;;A65E +A660;CYRILLIC CAPITAL LETTER REVERSED TSE;Lu;0;L;;;;;N;;;;A661; +A661;CYRILLIC SMALL LETTER REVERSED TSE;Ll;0;L;;;;;N;;;A660;;A660 +A662;CYRILLIC CAPITAL LETTER SOFT DE;Lu;0;L;;;;;N;;;;A663; +A663;CYRILLIC SMALL LETTER SOFT DE;Ll;0;L;;;;;N;;;A662;;A662 +A664;CYRILLIC CAPITAL LETTER SOFT EL;Lu;0;L;;;;;N;;;;A665; +A665;CYRILLIC SMALL LETTER SOFT EL;Ll;0;L;;;;;N;;;A664;;A664 +A666;CYRILLIC CAPITAL LETTER SOFT EM;Lu;0;L;;;;;N;;;;A667; +A667;CYRILLIC SMALL LETTER SOFT EM;Ll;0;L;;;;;N;;;A666;;A666 +A668;CYRILLIC CAPITAL LETTER MONOCULAR O;Lu;0;L;;;;;N;;;;A669; +A669;CYRILLIC SMALL LETTER MONOCULAR O;Ll;0;L;;;;;N;;;A668;;A668 +A66A;CYRILLIC CAPITAL LETTER BINOCULAR O;Lu;0;L;;;;;N;;;;A66B; +A66B;CYRILLIC SMALL LETTER BINOCULAR O;Ll;0;L;;;;;N;;;A66A;;A66A +A66C;CYRILLIC CAPITAL LETTER DOUBLE MONOCULAR O;Lu;0;L;;;;;N;;;;A66D; +A66D;CYRILLIC SMALL LETTER DOUBLE MONOCULAR O;Ll;0;L;;;;;N;;;A66C;;A66C +A66E;CYRILLIC LETTER MULTIOCULAR O;Lo;0;L;;;;;N;;;;; +A66F;COMBINING CYRILLIC VZMET;Mn;230;NSM;;;;;N;;;;; +A670;COMBINING CYRILLIC TEN MILLIONS SIGN;Me;0;NSM;;;;;N;;;;; +A671;COMBINING CYRILLIC HUNDRED MILLIONS SIGN;Me;0;NSM;;;;;N;;;;; +A672;COMBINING CYRILLIC THOUSAND MILLIONS SIGN;Me;0;NSM;;;;;N;;;;; +A673;SLAVONIC ASTERISK;Po;0;ON;;;;;N;;;;; +A674;COMBINING CYRILLIC LETTER UKRAINIAN IE;Mn;230;NSM;;;;;N;;;;; +A675;COMBINING CYRILLIC LETTER I;Mn;230;NSM;;;;;N;;;;; +A676;COMBINING CYRILLIC LETTER YI;Mn;230;NSM;;;;;N;;;;; +A677;COMBINING CYRILLIC LETTER U;Mn;230;NSM;;;;;N;;;;; +A678;COMBINING CYRILLIC LETTER HARD SIGN;Mn;230;NSM;;;;;N;;;;; +A679;COMBINING CYRILLIC LETTER YERU;Mn;230;NSM;;;;;N;;;;; +A67A;COMBINING CYRILLIC LETTER SOFT SIGN;Mn;230;NSM;;;;;N;;;;; +A67B;COMBINING CYRILLIC LETTER OMEGA;Mn;230;NSM;;;;;N;;;;; +A67C;COMBINING CYRILLIC KAVYKA;Mn;230;NSM;;;;;N;;;;; +A67D;COMBINING CYRILLIC PAYEROK;Mn;230;NSM;;;;;N;;;;; +A67E;CYRILLIC KAVYKA;Po;0;ON;;;;;N;;;;; +A67F;CYRILLIC PAYEROK;Lm;0;ON;;;;;N;;;;; +A680;CYRILLIC CAPITAL LETTER DWE;Lu;0;L;;;;;N;;;;A681; +A681;CYRILLIC SMALL LETTER DWE;Ll;0;L;;;;;N;;;A680;;A680 +A682;CYRILLIC CAPITAL LETTER DZWE;Lu;0;L;;;;;N;;;;A683; +A683;CYRILLIC SMALL LETTER DZWE;Ll;0;L;;;;;N;;;A682;;A682 +A684;CYRILLIC CAPITAL LETTER ZHWE;Lu;0;L;;;;;N;;;;A685; +A685;CYRILLIC SMALL LETTER ZHWE;Ll;0;L;;;;;N;;;A684;;A684 +A686;CYRILLIC CAPITAL LETTER CCHE;Lu;0;L;;;;;N;;;;A687; +A687;CYRILLIC SMALL LETTER CCHE;Ll;0;L;;;;;N;;;A686;;A686 +A688;CYRILLIC CAPITAL LETTER DZZE;Lu;0;L;;;;;N;;;;A689; +A689;CYRILLIC SMALL LETTER DZZE;Ll;0;L;;;;;N;;;A688;;A688 +A68A;CYRILLIC CAPITAL LETTER TE WITH MIDDLE HOOK;Lu;0;L;;;;;N;;;;A68B; +A68B;CYRILLIC SMALL LETTER TE WITH MIDDLE HOOK;Ll;0;L;;;;;N;;;A68A;;A68A +A68C;CYRILLIC CAPITAL LETTER TWE;Lu;0;L;;;;;N;;;;A68D; +A68D;CYRILLIC SMALL LETTER TWE;Ll;0;L;;;;;N;;;A68C;;A68C +A68E;CYRILLIC CAPITAL LETTER TSWE;Lu;0;L;;;;;N;;;;A68F; +A68F;CYRILLIC SMALL LETTER TSWE;Ll;0;L;;;;;N;;;A68E;;A68E +A690;CYRILLIC CAPITAL LETTER TSSE;Lu;0;L;;;;;N;;;;A691; +A691;CYRILLIC SMALL LETTER TSSE;Ll;0;L;;;;;N;;;A690;;A690 +A692;CYRILLIC CAPITAL LETTER TCHE;Lu;0;L;;;;;N;;;;A693; +A693;CYRILLIC SMALL LETTER TCHE;Ll;0;L;;;;;N;;;A692;;A692 +A694;CYRILLIC CAPITAL LETTER HWE;Lu;0;L;;;;;N;;;;A695; +A695;CYRILLIC SMALL LETTER HWE;Ll;0;L;;;;;N;;;A694;;A694 +A696;CYRILLIC CAPITAL LETTER SHWE;Lu;0;L;;;;;N;;;;A697; +A697;CYRILLIC SMALL LETTER SHWE;Ll;0;L;;;;;N;;;A696;;A696 +A69F;COMBINING CYRILLIC LETTER IOTIFIED E;Mn;230;NSM;;;;;N;;;;; +A6A0;BAMUM LETTER A;Lo;0;L;;;;;N;;;;; +A6A1;BAMUM LETTER KA;Lo;0;L;;;;;N;;;;; +A6A2;BAMUM LETTER U;Lo;0;L;;;;;N;;;;; +A6A3;BAMUM LETTER KU;Lo;0;L;;;;;N;;;;; +A6A4;BAMUM LETTER EE;Lo;0;L;;;;;N;;;;; +A6A5;BAMUM LETTER REE;Lo;0;L;;;;;N;;;;; +A6A6;BAMUM LETTER TAE;Lo;0;L;;;;;N;;;;; +A6A7;BAMUM LETTER O;Lo;0;L;;;;;N;;;;; +A6A8;BAMUM LETTER NYI;Lo;0;L;;;;;N;;;;; +A6A9;BAMUM LETTER I;Lo;0;L;;;;;N;;;;; +A6AA;BAMUM LETTER LA;Lo;0;L;;;;;N;;;;; +A6AB;BAMUM LETTER PA;Lo;0;L;;;;;N;;;;; +A6AC;BAMUM LETTER RII;Lo;0;L;;;;;N;;;;; +A6AD;BAMUM LETTER RIEE;Lo;0;L;;;;;N;;;;; +A6AE;BAMUM LETTER LEEEE;Lo;0;L;;;;;N;;;;; +A6AF;BAMUM LETTER MEEEE;Lo;0;L;;;;;N;;;;; +A6B0;BAMUM LETTER TAA;Lo;0;L;;;;;N;;;;; +A6B1;BAMUM LETTER NDAA;Lo;0;L;;;;;N;;;;; +A6B2;BAMUM LETTER NJAEM;Lo;0;L;;;;;N;;;;; +A6B3;BAMUM LETTER M;Lo;0;L;;;;;N;;;;; +A6B4;BAMUM LETTER SUU;Lo;0;L;;;;;N;;;;; +A6B5;BAMUM LETTER MU;Lo;0;L;;;;;N;;;;; +A6B6;BAMUM LETTER SHII;Lo;0;L;;;;;N;;;;; +A6B7;BAMUM LETTER SI;Lo;0;L;;;;;N;;;;; +A6B8;BAMUM LETTER SHEUX;Lo;0;L;;;;;N;;;;; +A6B9;BAMUM LETTER SEUX;Lo;0;L;;;;;N;;;;; +A6BA;BAMUM LETTER KYEE;Lo;0;L;;;;;N;;;;; +A6BB;BAMUM LETTER KET;Lo;0;L;;;;;N;;;;; +A6BC;BAMUM LETTER NUAE;Lo;0;L;;;;;N;;;;; +A6BD;BAMUM LETTER NU;Lo;0;L;;;;;N;;;;; +A6BE;BAMUM LETTER NJUAE;Lo;0;L;;;;;N;;;;; +A6BF;BAMUM LETTER YOQ;Lo;0;L;;;;;N;;;;; +A6C0;BAMUM LETTER SHU;Lo;0;L;;;;;N;;;;; +A6C1;BAMUM LETTER YUQ;Lo;0;L;;;;;N;;;;; +A6C2;BAMUM LETTER YA;Lo;0;L;;;;;N;;;;; +A6C3;BAMUM LETTER NSHA;Lo;0;L;;;;;N;;;;; +A6C4;BAMUM LETTER KEUX;Lo;0;L;;;;;N;;;;; +A6C5;BAMUM LETTER PEUX;Lo;0;L;;;;;N;;;;; +A6C6;BAMUM LETTER NJEE;Lo;0;L;;;;;N;;;;; +A6C7;BAMUM LETTER NTEE;Lo;0;L;;;;;N;;;;; +A6C8;BAMUM LETTER PUE;Lo;0;L;;;;;N;;;;; +A6C9;BAMUM LETTER WUE;Lo;0;L;;;;;N;;;;; +A6CA;BAMUM LETTER PEE;Lo;0;L;;;;;N;;;;; +A6CB;BAMUM LETTER FEE;Lo;0;L;;;;;N;;;;; +A6CC;BAMUM LETTER RU;Lo;0;L;;;;;N;;;;; +A6CD;BAMUM LETTER LU;Lo;0;L;;;;;N;;;;; +A6CE;BAMUM LETTER MI;Lo;0;L;;;;;N;;;;; +A6CF;BAMUM LETTER NI;Lo;0;L;;;;;N;;;;; +A6D0;BAMUM LETTER REUX;Lo;0;L;;;;;N;;;;; +A6D1;BAMUM LETTER RAE;Lo;0;L;;;;;N;;;;; +A6D2;BAMUM LETTER KEN;Lo;0;L;;;;;N;;;;; +A6D3;BAMUM LETTER NGKWAEN;Lo;0;L;;;;;N;;;;; +A6D4;BAMUM LETTER NGGA;Lo;0;L;;;;;N;;;;; +A6D5;BAMUM LETTER NGA;Lo;0;L;;;;;N;;;;; +A6D6;BAMUM LETTER SHO;Lo;0;L;;;;;N;;;;; +A6D7;BAMUM LETTER PUAE;Lo;0;L;;;;;N;;;;; +A6D8;BAMUM LETTER FU;Lo;0;L;;;;;N;;;;; +A6D9;BAMUM LETTER FOM;Lo;0;L;;;;;N;;;;; +A6DA;BAMUM LETTER WA;Lo;0;L;;;;;N;;;;; +A6DB;BAMUM LETTER NA;Lo;0;L;;;;;N;;;;; +A6DC;BAMUM LETTER LI;Lo;0;L;;;;;N;;;;; +A6DD;BAMUM LETTER PI;Lo;0;L;;;;;N;;;;; +A6DE;BAMUM LETTER LOQ;Lo;0;L;;;;;N;;;;; +A6DF;BAMUM LETTER KO;Lo;0;L;;;;;N;;;;; +A6E0;BAMUM LETTER MBEN;Lo;0;L;;;;;N;;;;; +A6E1;BAMUM LETTER REN;Lo;0;L;;;;;N;;;;; +A6E2;BAMUM LETTER MEN;Lo;0;L;;;;;N;;;;; +A6E3;BAMUM LETTER MA;Lo;0;L;;;;;N;;;;; +A6E4;BAMUM LETTER TI;Lo;0;L;;;;;N;;;;; +A6E5;BAMUM LETTER KI;Lo;0;L;;;;;N;;;;; +A6E6;BAMUM LETTER MO;Nl;0;L;;;;1;N;;;;; +A6E7;BAMUM LETTER MBAA;Nl;0;L;;;;2;N;;;;; +A6E8;BAMUM LETTER TET;Nl;0;L;;;;3;N;;;;; +A6E9;BAMUM LETTER KPA;Nl;0;L;;;;4;N;;;;; +A6EA;BAMUM LETTER TEN;Nl;0;L;;;;5;N;;;;; +A6EB;BAMUM LETTER NTUU;Nl;0;L;;;;6;N;;;;; +A6EC;BAMUM LETTER SAMBA;Nl;0;L;;;;7;N;;;;; +A6ED;BAMUM LETTER FAAMAE;Nl;0;L;;;;8;N;;;;; +A6EE;BAMUM LETTER KOVUU;Nl;0;L;;;;9;N;;;;; +A6EF;BAMUM LETTER KOGHOM;Nl;0;L;;;;0;N;;;;; +A6F0;BAMUM COMBINING MARK KOQNDON;Mn;230;NSM;;;;;N;;;;; +A6F1;BAMUM COMBINING MARK TUKWENTIS;Mn;230;NSM;;;;;N;;;;; +A6F2;BAMUM NJAEMLI;Po;0;L;;;;;N;;;;; +A6F3;BAMUM FULL STOP;Po;0;L;;;;;N;;;;; +A6F4;BAMUM COLON;Po;0;L;;;;;N;;;;; +A6F5;BAMUM COMMA;Po;0;L;;;;;N;;;;; +A6F6;BAMUM SEMICOLON;Po;0;L;;;;;N;;;;; +A6F7;BAMUM QUESTION MARK;Po;0;L;;;;;N;;;;; +A700;MODIFIER LETTER CHINESE TONE YIN PING;Sk;0;ON;;;;;N;;;;; +A701;MODIFIER LETTER CHINESE TONE YANG PING;Sk;0;ON;;;;;N;;;;; +A702;MODIFIER LETTER CHINESE TONE YIN SHANG;Sk;0;ON;;;;;N;;;;; +A703;MODIFIER LETTER CHINESE TONE YANG SHANG;Sk;0;ON;;;;;N;;;;; +A704;MODIFIER LETTER CHINESE TONE YIN QU;Sk;0;ON;;;;;N;;;;; +A705;MODIFIER LETTER CHINESE TONE YANG QU;Sk;0;ON;;;;;N;;;;; +A706;MODIFIER LETTER CHINESE TONE YIN RU;Sk;0;ON;;;;;N;;;;; +A707;MODIFIER LETTER CHINESE TONE YANG RU;Sk;0;ON;;;;;N;;;;; +A708;MODIFIER LETTER EXTRA-HIGH DOTTED TONE BAR;Sk;0;ON;;;;;N;;;;; +A709;MODIFIER LETTER HIGH DOTTED TONE BAR;Sk;0;ON;;;;;N;;;;; +A70A;MODIFIER LETTER MID DOTTED TONE BAR;Sk;0;ON;;;;;N;;;;; +A70B;MODIFIER LETTER LOW DOTTED TONE BAR;Sk;0;ON;;;;;N;;;;; +A70C;MODIFIER LETTER EXTRA-LOW DOTTED TONE BAR;Sk;0;ON;;;;;N;;;;; +A70D;MODIFIER LETTER EXTRA-HIGH DOTTED LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A70E;MODIFIER LETTER HIGH DOTTED LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A70F;MODIFIER LETTER MID DOTTED LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A710;MODIFIER LETTER LOW DOTTED LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A711;MODIFIER LETTER EXTRA-LOW DOTTED LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A712;MODIFIER LETTER EXTRA-HIGH LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A713;MODIFIER LETTER HIGH LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A714;MODIFIER LETTER MID LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A715;MODIFIER LETTER LOW LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A716;MODIFIER LETTER EXTRA-LOW LEFT-STEM TONE BAR;Sk;0;ON;;;;;N;;;;; +A717;MODIFIER LETTER DOT VERTICAL BAR;Lm;0;ON;;;;;N;;;;; +A718;MODIFIER LETTER DOT SLASH;Lm;0;ON;;;;;N;;;;; +A719;MODIFIER LETTER DOT HORIZONTAL BAR;Lm;0;ON;;;;;N;;;;; +A71A;MODIFIER LETTER LOWER RIGHT CORNER ANGLE;Lm;0;ON;;;;;N;;;;; +A71B;MODIFIER LETTER RAISED UP ARROW;Lm;0;ON;;;;;N;;;;; +A71C;MODIFIER LETTER RAISED DOWN ARROW;Lm;0;ON;;;;;N;;;;; +A71D;MODIFIER LETTER RAISED EXCLAMATION MARK;Lm;0;ON;;;;;N;;;;; +A71E;MODIFIER LETTER RAISED INVERTED EXCLAMATION MARK;Lm;0;ON;;;;;N;;;;; +A71F;MODIFIER LETTER LOW INVERTED EXCLAMATION MARK;Lm;0;ON;;;;;N;;;;; +A720;MODIFIER LETTER STRESS AND HIGH TONE;Sk;0;ON;;;;;N;;;;; +A721;MODIFIER LETTER STRESS AND LOW TONE;Sk;0;ON;;;;;N;;;;; +A722;LATIN CAPITAL LETTER EGYPTOLOGICAL ALEF;Lu;0;L;;;;;N;;;;A723; +A723;LATIN SMALL LETTER EGYPTOLOGICAL ALEF;Ll;0;L;;;;;N;;;A722;;A722 +A724;LATIN CAPITAL LETTER EGYPTOLOGICAL AIN;Lu;0;L;;;;;N;;;;A725; +A725;LATIN SMALL LETTER EGYPTOLOGICAL AIN;Ll;0;L;;;;;N;;;A724;;A724 +A726;LATIN CAPITAL LETTER HENG;Lu;0;L;;;;;N;;;;A727; +A727;LATIN SMALL LETTER HENG;Ll;0;L;;;;;N;;;A726;;A726 +A728;LATIN CAPITAL LETTER TZ;Lu;0;L;;;;;N;;;;A729; +A729;LATIN SMALL LETTER TZ;Ll;0;L;;;;;N;;;A728;;A728 +A72A;LATIN CAPITAL LETTER TRESILLO;Lu;0;L;;;;;N;;;;A72B; +A72B;LATIN SMALL LETTER TRESILLO;Ll;0;L;;;;;N;;;A72A;;A72A +A72C;LATIN CAPITAL LETTER CUATRILLO;Lu;0;L;;;;;N;;;;A72D; +A72D;LATIN SMALL LETTER CUATRILLO;Ll;0;L;;;;;N;;;A72C;;A72C +A72E;LATIN CAPITAL LETTER CUATRILLO WITH COMMA;Lu;0;L;;;;;N;;;;A72F; +A72F;LATIN SMALL LETTER CUATRILLO WITH COMMA;Ll;0;L;;;;;N;;;A72E;;A72E +A730;LATIN LETTER SMALL CAPITAL F;Ll;0;L;;;;;N;;;;; +A731;LATIN LETTER SMALL CAPITAL S;Ll;0;L;;;;;N;;;;; +A732;LATIN CAPITAL LETTER AA;Lu;0;L;;;;;N;;;;A733; +A733;LATIN SMALL LETTER AA;Ll;0;L;;;;;N;;;A732;;A732 +A734;LATIN CAPITAL LETTER AO;Lu;0;L;;;;;N;;;;A735; +A735;LATIN SMALL LETTER AO;Ll;0;L;;;;;N;;;A734;;A734 +A736;LATIN CAPITAL LETTER AU;Lu;0;L;;;;;N;;;;A737; +A737;LATIN SMALL LETTER AU;Ll;0;L;;;;;N;;;A736;;A736 +A738;LATIN CAPITAL LETTER AV;Lu;0;L;;;;;N;;;;A739; +A739;LATIN SMALL LETTER AV;Ll;0;L;;;;;N;;;A738;;A738 +A73A;LATIN CAPITAL LETTER AV WITH HORIZONTAL BAR;Lu;0;L;;;;;N;;;;A73B; +A73B;LATIN SMALL LETTER AV WITH HORIZONTAL BAR;Ll;0;L;;;;;N;;;A73A;;A73A +A73C;LATIN CAPITAL LETTER AY;Lu;0;L;;;;;N;;;;A73D; +A73D;LATIN SMALL LETTER AY;Ll;0;L;;;;;N;;;A73C;;A73C +A73E;LATIN CAPITAL LETTER REVERSED C WITH DOT;Lu;0;L;;;;;N;;;;A73F; +A73F;LATIN SMALL LETTER REVERSED C WITH DOT;Ll;0;L;;;;;N;;;A73E;;A73E +A740;LATIN CAPITAL LETTER K WITH STROKE;Lu;0;L;;;;;N;;;;A741; +A741;LATIN SMALL LETTER K WITH STROKE;Ll;0;L;;;;;N;;;A740;;A740 +A742;LATIN CAPITAL LETTER K WITH DIAGONAL STROKE;Lu;0;L;;;;;N;;;;A743; +A743;LATIN SMALL LETTER K WITH DIAGONAL STROKE;Ll;0;L;;;;;N;;;A742;;A742 +A744;LATIN CAPITAL LETTER K WITH STROKE AND DIAGONAL STROKE;Lu;0;L;;;;;N;;;;A745; +A745;LATIN SMALL LETTER K WITH STROKE AND DIAGONAL STROKE;Ll;0;L;;;;;N;;;A744;;A744 +A746;LATIN CAPITAL LETTER BROKEN L;Lu;0;L;;;;;N;;;;A747; +A747;LATIN SMALL LETTER BROKEN L;Ll;0;L;;;;;N;;;A746;;A746 +A748;LATIN CAPITAL LETTER L WITH HIGH STROKE;Lu;0;L;;;;;N;;;;A749; +A749;LATIN SMALL LETTER L WITH HIGH STROKE;Ll;0;L;;;;;N;;;A748;;A748 +A74A;LATIN CAPITAL LETTER O WITH LONG STROKE OVERLAY;Lu;0;L;;;;;N;;;;A74B; +A74B;LATIN SMALL LETTER O WITH LONG STROKE OVERLAY;Ll;0;L;;;;;N;;;A74A;;A74A +A74C;LATIN CAPITAL LETTER O WITH LOOP;Lu;0;L;;;;;N;;;;A74D; +A74D;LATIN SMALL LETTER O WITH LOOP;Ll;0;L;;;;;N;;;A74C;;A74C +A74E;LATIN CAPITAL LETTER OO;Lu;0;L;;;;;N;;;;A74F; +A74F;LATIN SMALL LETTER OO;Ll;0;L;;;;;N;;;A74E;;A74E +A750;LATIN CAPITAL LETTER P WITH STROKE THROUGH DESCENDER;Lu;0;L;;;;;N;;;;A751; +A751;LATIN SMALL LETTER P WITH STROKE THROUGH DESCENDER;Ll;0;L;;;;;N;;;A750;;A750 +A752;LATIN CAPITAL LETTER P WITH FLOURISH;Lu;0;L;;;;;N;;;;A753; +A753;LATIN SMALL LETTER P WITH FLOURISH;Ll;0;L;;;;;N;;;A752;;A752 +A754;LATIN CAPITAL LETTER P WITH SQUIRREL TAIL;Lu;0;L;;;;;N;;;;A755; +A755;LATIN SMALL LETTER P WITH SQUIRREL TAIL;Ll;0;L;;;;;N;;;A754;;A754 +A756;LATIN CAPITAL LETTER Q WITH STROKE THROUGH DESCENDER;Lu;0;L;;;;;N;;;;A757; +A757;LATIN SMALL LETTER Q WITH STROKE THROUGH DESCENDER;Ll;0;L;;;;;N;;;A756;;A756 +A758;LATIN CAPITAL LETTER Q WITH DIAGONAL STROKE;Lu;0;L;;;;;N;;;;A759; +A759;LATIN SMALL LETTER Q WITH DIAGONAL STROKE;Ll;0;L;;;;;N;;;A758;;A758 +A75A;LATIN CAPITAL LETTER R ROTUNDA;Lu;0;L;;;;;N;;;;A75B; +A75B;LATIN SMALL LETTER R ROTUNDA;Ll;0;L;;;;;N;;;A75A;;A75A +A75C;LATIN CAPITAL LETTER RUM ROTUNDA;Lu;0;L;;;;;N;;;;A75D; +A75D;LATIN SMALL LETTER RUM ROTUNDA;Ll;0;L;;;;;N;;;A75C;;A75C +A75E;LATIN CAPITAL LETTER V WITH DIAGONAL STROKE;Lu;0;L;;;;;N;;;;A75F; +A75F;LATIN SMALL LETTER V WITH DIAGONAL STROKE;Ll;0;L;;;;;N;;;A75E;;A75E +A760;LATIN CAPITAL LETTER VY;Lu;0;L;;;;;N;;;;A761; +A761;LATIN SMALL LETTER VY;Ll;0;L;;;;;N;;;A760;;A760 +A762;LATIN CAPITAL LETTER VISIGOTHIC Z;Lu;0;L;;;;;N;;;;A763; +A763;LATIN SMALL LETTER VISIGOTHIC Z;Ll;0;L;;;;;N;;;A762;;A762 +A764;LATIN CAPITAL LETTER THORN WITH STROKE;Lu;0;L;;;;;N;;;;A765; +A765;LATIN SMALL LETTER THORN WITH STROKE;Ll;0;L;;;;;N;;;A764;;A764 +A766;LATIN CAPITAL LETTER THORN WITH STROKE THROUGH DESCENDER;Lu;0;L;;;;;N;;;;A767; +A767;LATIN SMALL LETTER THORN WITH STROKE THROUGH DESCENDER;Ll;0;L;;;;;N;;;A766;;A766 +A768;LATIN CAPITAL LETTER VEND;Lu;0;L;;;;;N;;;;A769; +A769;LATIN SMALL LETTER VEND;Ll;0;L;;;;;N;;;A768;;A768 +A76A;LATIN CAPITAL LETTER ET;Lu;0;L;;;;;N;;;;A76B; +A76B;LATIN SMALL LETTER ET;Ll;0;L;;;;;N;;;A76A;;A76A +A76C;LATIN CAPITAL LETTER IS;Lu;0;L;;;;;N;;;;A76D; +A76D;LATIN SMALL LETTER IS;Ll;0;L;;;;;N;;;A76C;;A76C +A76E;LATIN CAPITAL LETTER CON;Lu;0;L;;;;;N;;;;A76F; +A76F;LATIN SMALL LETTER CON;Ll;0;L;;;;;N;;;A76E;;A76E +A770;MODIFIER LETTER US;Lm;0;L; A76F;;;;N;;;;; +A771;LATIN SMALL LETTER DUM;Ll;0;L;;;;;N;;;;; +A772;LATIN SMALL LETTER LUM;Ll;0;L;;;;;N;;;;; +A773;LATIN SMALL LETTER MUM;Ll;0;L;;;;;N;;;;; +A774;LATIN SMALL LETTER NUM;Ll;0;L;;;;;N;;;;; +A775;LATIN SMALL LETTER RUM;Ll;0;L;;;;;N;;;;; +A776;LATIN LETTER SMALL CAPITAL RUM;Ll;0;L;;;;;N;;;;; +A777;LATIN SMALL LETTER TUM;Ll;0;L;;;;;N;;;;; +A778;LATIN SMALL LETTER UM;Ll;0;L;;;;;N;;;;; +A779;LATIN CAPITAL LETTER INSULAR D;Lu;0;L;;;;;N;;;;A77A; +A77A;LATIN SMALL LETTER INSULAR D;Ll;0;L;;;;;N;;;A779;;A779 +A77B;LATIN CAPITAL LETTER INSULAR F;Lu;0;L;;;;;N;;;;A77C; +A77C;LATIN SMALL LETTER INSULAR F;Ll;0;L;;;;;N;;;A77B;;A77B +A77D;LATIN CAPITAL LETTER INSULAR G;Lu;0;L;;;;;N;;;;1D79; +A77E;LATIN CAPITAL LETTER TURNED INSULAR G;Lu;0;L;;;;;N;;;;A77F; +A77F;LATIN SMALL LETTER TURNED INSULAR G;Ll;0;L;;;;;N;;;A77E;;A77E +A780;LATIN CAPITAL LETTER TURNED L;Lu;0;L;;;;;N;;;;A781; +A781;LATIN SMALL LETTER TURNED L;Ll;0;L;;;;;N;;;A780;;A780 +A782;LATIN CAPITAL LETTER INSULAR R;Lu;0;L;;;;;N;;;;A783; +A783;LATIN SMALL LETTER INSULAR R;Ll;0;L;;;;;N;;;A782;;A782 +A784;LATIN CAPITAL LETTER INSULAR S;Lu;0;L;;;;;N;;;;A785; +A785;LATIN SMALL LETTER INSULAR S;Ll;0;L;;;;;N;;;A784;;A784 +A786;LATIN CAPITAL LETTER INSULAR T;Lu;0;L;;;;;N;;;;A787; +A787;LATIN SMALL LETTER INSULAR T;Ll;0;L;;;;;N;;;A786;;A786 +A788;MODIFIER LETTER LOW CIRCUMFLEX ACCENT;Lm;0;ON;;;;;N;;;;; +A789;MODIFIER LETTER COLON;Sk;0;L;;;;;N;;;;; +A78A;MODIFIER LETTER SHORT EQUALS SIGN;Sk;0;L;;;;;N;;;;; +A78B;LATIN CAPITAL LETTER SALTILLO;Lu;0;L;;;;;N;;;;A78C; +A78C;LATIN SMALL LETTER SALTILLO;Ll;0;L;;;;;N;;;A78B;;A78B +A78D;LATIN CAPITAL LETTER TURNED H;Lu;0;L;;;;;N;;;;0265; +A78E;LATIN SMALL LETTER L WITH RETROFLEX HOOK AND BELT;Ll;0;L;;;;;N;;;;; +A790;LATIN CAPITAL LETTER N WITH DESCENDER;Lu;0;L;;;;;N;;;;A791; +A791;LATIN SMALL LETTER N WITH DESCENDER;Ll;0;L;;;;;N;;;A790;;A790 +A792;LATIN CAPITAL LETTER C WITH BAR;Lu;0;L;;;;;N;;;;A793; +A793;LATIN SMALL LETTER C WITH BAR;Ll;0;L;;;;;N;;;A792;;A792 +A7A0;LATIN CAPITAL LETTER G WITH OBLIQUE STROKE;Lu;0;L;;;;;N;;;;A7A1; +A7A1;LATIN SMALL LETTER G WITH OBLIQUE STROKE;Ll;0;L;;;;;N;;;A7A0;;A7A0 +A7A2;LATIN CAPITAL LETTER K WITH OBLIQUE STROKE;Lu;0;L;;;;;N;;;;A7A3; +A7A3;LATIN SMALL LETTER K WITH OBLIQUE STROKE;Ll;0;L;;;;;N;;;A7A2;;A7A2 +A7A4;LATIN CAPITAL LETTER N WITH OBLIQUE STROKE;Lu;0;L;;;;;N;;;;A7A5; +A7A5;LATIN SMALL LETTER N WITH OBLIQUE STROKE;Ll;0;L;;;;;N;;;A7A4;;A7A4 +A7A6;LATIN CAPITAL LETTER R WITH OBLIQUE STROKE;Lu;0;L;;;;;N;;;;A7A7; +A7A7;LATIN SMALL LETTER R WITH OBLIQUE STROKE;Ll;0;L;;;;;N;;;A7A6;;A7A6 +A7A8;LATIN CAPITAL LETTER S WITH OBLIQUE STROKE;Lu;0;L;;;;;N;;;;A7A9; +A7A9;LATIN SMALL LETTER S WITH OBLIQUE STROKE;Ll;0;L;;;;;N;;;A7A8;;A7A8 +A7AA;LATIN CAPITAL LETTER H WITH HOOK;Lu;0;L;;;;;N;;;;0266; +A7F8;MODIFIER LETTER CAPITAL H WITH STROKE;Lm;0;L; 0126;;;;N;;;;; +A7F9;MODIFIER LETTER SMALL LIGATURE OE;Lm;0;L; 0153;;;;N;;;;; +A7FA;LATIN LETTER SMALL CAPITAL TURNED M;Ll;0;L;;;;;N;;;;; +A7FB;LATIN EPIGRAPHIC LETTER REVERSED F;Lo;0;L;;;;;N;;;;; +A7FC;LATIN EPIGRAPHIC LETTER REVERSED P;Lo;0;L;;;;;N;;;;; +A7FD;LATIN EPIGRAPHIC LETTER INVERTED M;Lo;0;L;;;;;N;;;;; +A7FE;LATIN EPIGRAPHIC LETTER I LONGA;Lo;0;L;;;;;N;;;;; +A7FF;LATIN EPIGRAPHIC LETTER ARCHAIC M;Lo;0;L;;;;;N;;;;; +A800;SYLOTI NAGRI LETTER A;Lo;0;L;;;;;N;;;;; +A801;SYLOTI NAGRI LETTER I;Lo;0;L;;;;;N;;;;; +A802;SYLOTI NAGRI SIGN DVISVARA;Mn;0;NSM;;;;;N;;;;; +A803;SYLOTI NAGRI LETTER U;Lo;0;L;;;;;N;;;;; +A804;SYLOTI NAGRI LETTER E;Lo;0;L;;;;;N;;;;; +A805;SYLOTI NAGRI LETTER O;Lo;0;L;;;;;N;;;;; +A806;SYLOTI NAGRI SIGN HASANTA;Mn;9;NSM;;;;;N;;;;; +A807;SYLOTI NAGRI LETTER KO;Lo;0;L;;;;;N;;;;; +A808;SYLOTI NAGRI LETTER KHO;Lo;0;L;;;;;N;;;;; +A809;SYLOTI NAGRI LETTER GO;Lo;0;L;;;;;N;;;;; +A80A;SYLOTI NAGRI LETTER GHO;Lo;0;L;;;;;N;;;;; +A80B;SYLOTI NAGRI SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +A80C;SYLOTI NAGRI LETTER CO;Lo;0;L;;;;;N;;;;; +A80D;SYLOTI NAGRI LETTER CHO;Lo;0;L;;;;;N;;;;; +A80E;SYLOTI NAGRI LETTER JO;Lo;0;L;;;;;N;;;;; +A80F;SYLOTI NAGRI LETTER JHO;Lo;0;L;;;;;N;;;;; +A810;SYLOTI NAGRI LETTER TTO;Lo;0;L;;;;;N;;;;; +A811;SYLOTI NAGRI LETTER TTHO;Lo;0;L;;;;;N;;;;; +A812;SYLOTI NAGRI LETTER DDO;Lo;0;L;;;;;N;;;;; +A813;SYLOTI NAGRI LETTER DDHO;Lo;0;L;;;;;N;;;;; +A814;SYLOTI NAGRI LETTER TO;Lo;0;L;;;;;N;;;;; +A815;SYLOTI NAGRI LETTER THO;Lo;0;L;;;;;N;;;;; +A816;SYLOTI NAGRI LETTER DO;Lo;0;L;;;;;N;;;;; +A817;SYLOTI NAGRI LETTER DHO;Lo;0;L;;;;;N;;;;; +A818;SYLOTI NAGRI LETTER NO;Lo;0;L;;;;;N;;;;; +A819;SYLOTI NAGRI LETTER PO;Lo;0;L;;;;;N;;;;; +A81A;SYLOTI NAGRI LETTER PHO;Lo;0;L;;;;;N;;;;; +A81B;SYLOTI NAGRI LETTER BO;Lo;0;L;;;;;N;;;;; +A81C;SYLOTI NAGRI LETTER BHO;Lo;0;L;;;;;N;;;;; +A81D;SYLOTI NAGRI LETTER MO;Lo;0;L;;;;;N;;;;; +A81E;SYLOTI NAGRI LETTER RO;Lo;0;L;;;;;N;;;;; +A81F;SYLOTI NAGRI LETTER LO;Lo;0;L;;;;;N;;;;; +A820;SYLOTI NAGRI LETTER RRO;Lo;0;L;;;;;N;;;;; +A821;SYLOTI NAGRI LETTER SO;Lo;0;L;;;;;N;;;;; +A822;SYLOTI NAGRI LETTER HO;Lo;0;L;;;;;N;;;;; +A823;SYLOTI NAGRI VOWEL SIGN A;Mc;0;L;;;;;N;;;;; +A824;SYLOTI NAGRI VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +A825;SYLOTI NAGRI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +A826;SYLOTI NAGRI VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +A827;SYLOTI NAGRI VOWEL SIGN OO;Mc;0;L;;;;;N;;;;; +A828;SYLOTI NAGRI POETRY MARK-1;So;0;ON;;;;;N;;;;; +A829;SYLOTI NAGRI POETRY MARK-2;So;0;ON;;;;;N;;;;; +A82A;SYLOTI NAGRI POETRY MARK-3;So;0;ON;;;;;N;;;;; +A82B;SYLOTI NAGRI POETRY MARK-4;So;0;ON;;;;;N;;;;; +A830;NORTH INDIC FRACTION ONE QUARTER;No;0;L;;;;1/4;N;;;;; +A831;NORTH INDIC FRACTION ONE HALF;No;0;L;;;;1/2;N;;;;; +A832;NORTH INDIC FRACTION THREE QUARTERS;No;0;L;;;;3/4;N;;;;; +A833;NORTH INDIC FRACTION ONE SIXTEENTH;No;0;L;;;;1/16;N;;;;; +A834;NORTH INDIC FRACTION ONE EIGHTH;No;0;L;;;;1/8;N;;;;; +A835;NORTH INDIC FRACTION THREE SIXTEENTHS;No;0;L;;;;3/16;N;;;;; +A836;NORTH INDIC QUARTER MARK;So;0;L;;;;;N;;;;; +A837;NORTH INDIC PLACEHOLDER MARK;So;0;L;;;;;N;;;;; +A838;NORTH INDIC RUPEE MARK;Sc;0;ET;;;;;N;;;;; +A839;NORTH INDIC QUANTITY MARK;So;0;ET;;;;;N;;;;; +A840;PHAGS-PA LETTER KA;Lo;0;L;;;;;N;;;;; +A841;PHAGS-PA LETTER KHA;Lo;0;L;;;;;N;;;;; +A842;PHAGS-PA LETTER GA;Lo;0;L;;;;;N;;;;; +A843;PHAGS-PA LETTER NGA;Lo;0;L;;;;;N;;;;; +A844;PHAGS-PA LETTER CA;Lo;0;L;;;;;N;;;;; +A845;PHAGS-PA LETTER CHA;Lo;0;L;;;;;N;;;;; +A846;PHAGS-PA LETTER JA;Lo;0;L;;;;;N;;;;; +A847;PHAGS-PA LETTER NYA;Lo;0;L;;;;;N;;;;; +A848;PHAGS-PA LETTER TA;Lo;0;L;;;;;N;;;;; +A849;PHAGS-PA LETTER THA;Lo;0;L;;;;;N;;;;; +A84A;PHAGS-PA LETTER DA;Lo;0;L;;;;;N;;;;; +A84B;PHAGS-PA LETTER NA;Lo;0;L;;;;;N;;;;; +A84C;PHAGS-PA LETTER PA;Lo;0;L;;;;;N;;;;; +A84D;PHAGS-PA LETTER PHA;Lo;0;L;;;;;N;;;;; +A84E;PHAGS-PA LETTER BA;Lo;0;L;;;;;N;;;;; +A84F;PHAGS-PA LETTER MA;Lo;0;L;;;;;N;;;;; +A850;PHAGS-PA LETTER TSA;Lo;0;L;;;;;N;;;;; +A851;PHAGS-PA LETTER TSHA;Lo;0;L;;;;;N;;;;; +A852;PHAGS-PA LETTER DZA;Lo;0;L;;;;;N;;;;; +A853;PHAGS-PA LETTER WA;Lo;0;L;;;;;N;;;;; +A854;PHAGS-PA LETTER ZHA;Lo;0;L;;;;;N;;;;; +A855;PHAGS-PA LETTER ZA;Lo;0;L;;;;;N;;;;; +A856;PHAGS-PA LETTER SMALL A;Lo;0;L;;;;;N;;;;; +A857;PHAGS-PA LETTER YA;Lo;0;L;;;;;N;;;;; +A858;PHAGS-PA LETTER RA;Lo;0;L;;;;;N;;;;; +A859;PHAGS-PA LETTER LA;Lo;0;L;;;;;N;;;;; +A85A;PHAGS-PA LETTER SHA;Lo;0;L;;;;;N;;;;; +A85B;PHAGS-PA LETTER SA;Lo;0;L;;;;;N;;;;; +A85C;PHAGS-PA LETTER HA;Lo;0;L;;;;;N;;;;; +A85D;PHAGS-PA LETTER A;Lo;0;L;;;;;N;;;;; +A85E;PHAGS-PA LETTER I;Lo;0;L;;;;;N;;;;; +A85F;PHAGS-PA LETTER U;Lo;0;L;;;;;N;;;;; +A860;PHAGS-PA LETTER E;Lo;0;L;;;;;N;;;;; +A861;PHAGS-PA LETTER O;Lo;0;L;;;;;N;;;;; +A862;PHAGS-PA LETTER QA;Lo;0;L;;;;;N;;;;; +A863;PHAGS-PA LETTER XA;Lo;0;L;;;;;N;;;;; +A864;PHAGS-PA LETTER FA;Lo;0;L;;;;;N;;;;; +A865;PHAGS-PA LETTER GGA;Lo;0;L;;;;;N;;;;; +A866;PHAGS-PA LETTER EE;Lo;0;L;;;;;N;;;;; +A867;PHAGS-PA SUBJOINED LETTER WA;Lo;0;L;;;;;N;;;;; +A868;PHAGS-PA SUBJOINED LETTER YA;Lo;0;L;;;;;N;;;;; +A869;PHAGS-PA LETTER TTA;Lo;0;L;;;;;N;;;;; +A86A;PHAGS-PA LETTER TTHA;Lo;0;L;;;;;N;;;;; +A86B;PHAGS-PA LETTER DDA;Lo;0;L;;;;;N;;;;; +A86C;PHAGS-PA LETTER NNA;Lo;0;L;;;;;N;;;;; +A86D;PHAGS-PA LETTER ALTERNATE YA;Lo;0;L;;;;;N;;;;; +A86E;PHAGS-PA LETTER VOICELESS SHA;Lo;0;L;;;;;N;;;;; +A86F;PHAGS-PA LETTER VOICED HA;Lo;0;L;;;;;N;;;;; +A870;PHAGS-PA LETTER ASPIRATED FA;Lo;0;L;;;;;N;;;;; +A871;PHAGS-PA SUBJOINED LETTER RA;Lo;0;L;;;;;N;;;;; +A872;PHAGS-PA SUPERFIXED LETTER RA;Lo;0;L;;;;;N;;;;; +A873;PHAGS-PA LETTER CANDRABINDU;Lo;0;L;;;;;N;;;;; +A874;PHAGS-PA SINGLE HEAD MARK;Po;0;ON;;;;;N;;;;; +A875;PHAGS-PA DOUBLE HEAD MARK;Po;0;ON;;;;;N;;;;; +A876;PHAGS-PA MARK SHAD;Po;0;ON;;;;;N;;;;; +A877;PHAGS-PA MARK DOUBLE SHAD;Po;0;ON;;;;;N;;;;; +A880;SAURASHTRA SIGN ANUSVARA;Mc;0;L;;;;;N;;;;; +A881;SAURASHTRA SIGN VISARGA;Mc;0;L;;;;;N;;;;; +A882;SAURASHTRA LETTER A;Lo;0;L;;;;;N;;;;; +A883;SAURASHTRA LETTER AA;Lo;0;L;;;;;N;;;;; +A884;SAURASHTRA LETTER I;Lo;0;L;;;;;N;;;;; +A885;SAURASHTRA LETTER II;Lo;0;L;;;;;N;;;;; +A886;SAURASHTRA LETTER U;Lo;0;L;;;;;N;;;;; +A887;SAURASHTRA LETTER UU;Lo;0;L;;;;;N;;;;; +A888;SAURASHTRA LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +A889;SAURASHTRA LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +A88A;SAURASHTRA LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +A88B;SAURASHTRA LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +A88C;SAURASHTRA LETTER E;Lo;0;L;;;;;N;;;;; +A88D;SAURASHTRA LETTER EE;Lo;0;L;;;;;N;;;;; +A88E;SAURASHTRA LETTER AI;Lo;0;L;;;;;N;;;;; +A88F;SAURASHTRA LETTER O;Lo;0;L;;;;;N;;;;; +A890;SAURASHTRA LETTER OO;Lo;0;L;;;;;N;;;;; +A891;SAURASHTRA LETTER AU;Lo;0;L;;;;;N;;;;; +A892;SAURASHTRA LETTER KA;Lo;0;L;;;;;N;;;;; +A893;SAURASHTRA LETTER KHA;Lo;0;L;;;;;N;;;;; +A894;SAURASHTRA LETTER GA;Lo;0;L;;;;;N;;;;; +A895;SAURASHTRA LETTER GHA;Lo;0;L;;;;;N;;;;; +A896;SAURASHTRA LETTER NGA;Lo;0;L;;;;;N;;;;; +A897;SAURASHTRA LETTER CA;Lo;0;L;;;;;N;;;;; +A898;SAURASHTRA LETTER CHA;Lo;0;L;;;;;N;;;;; +A899;SAURASHTRA LETTER JA;Lo;0;L;;;;;N;;;;; +A89A;SAURASHTRA LETTER JHA;Lo;0;L;;;;;N;;;;; +A89B;SAURASHTRA LETTER NYA;Lo;0;L;;;;;N;;;;; +A89C;SAURASHTRA LETTER TTA;Lo;0;L;;;;;N;;;;; +A89D;SAURASHTRA LETTER TTHA;Lo;0;L;;;;;N;;;;; +A89E;SAURASHTRA LETTER DDA;Lo;0;L;;;;;N;;;;; +A89F;SAURASHTRA LETTER DDHA;Lo;0;L;;;;;N;;;;; +A8A0;SAURASHTRA LETTER NNA;Lo;0;L;;;;;N;;;;; +A8A1;SAURASHTRA LETTER TA;Lo;0;L;;;;;N;;;;; +A8A2;SAURASHTRA LETTER THA;Lo;0;L;;;;;N;;;;; +A8A3;SAURASHTRA LETTER DA;Lo;0;L;;;;;N;;;;; +A8A4;SAURASHTRA LETTER DHA;Lo;0;L;;;;;N;;;;; +A8A5;SAURASHTRA LETTER NA;Lo;0;L;;;;;N;;;;; +A8A6;SAURASHTRA LETTER PA;Lo;0;L;;;;;N;;;;; +A8A7;SAURASHTRA LETTER PHA;Lo;0;L;;;;;N;;;;; +A8A8;SAURASHTRA LETTER BA;Lo;0;L;;;;;N;;;;; +A8A9;SAURASHTRA LETTER BHA;Lo;0;L;;;;;N;;;;; +A8AA;SAURASHTRA LETTER MA;Lo;0;L;;;;;N;;;;; +A8AB;SAURASHTRA LETTER YA;Lo;0;L;;;;;N;;;;; +A8AC;SAURASHTRA LETTER RA;Lo;0;L;;;;;N;;;;; +A8AD;SAURASHTRA LETTER LA;Lo;0;L;;;;;N;;;;; +A8AE;SAURASHTRA LETTER VA;Lo;0;L;;;;;N;;;;; +A8AF;SAURASHTRA LETTER SHA;Lo;0;L;;;;;N;;;;; +A8B0;SAURASHTRA LETTER SSA;Lo;0;L;;;;;N;;;;; +A8B1;SAURASHTRA LETTER SA;Lo;0;L;;;;;N;;;;; +A8B2;SAURASHTRA LETTER HA;Lo;0;L;;;;;N;;;;; +A8B3;SAURASHTRA LETTER LLA;Lo;0;L;;;;;N;;;;; +A8B4;SAURASHTRA CONSONANT SIGN HAARU;Mc;0;L;;;;;N;;;;; +A8B5;SAURASHTRA VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +A8B6;SAURASHTRA VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +A8B7;SAURASHTRA VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +A8B8;SAURASHTRA VOWEL SIGN U;Mc;0;L;;;;;N;;;;; +A8B9;SAURASHTRA VOWEL SIGN UU;Mc;0;L;;;;;N;;;;; +A8BA;SAURASHTRA VOWEL SIGN VOCALIC R;Mc;0;L;;;;;N;;;;; +A8BB;SAURASHTRA VOWEL SIGN VOCALIC RR;Mc;0;L;;;;;N;;;;; +A8BC;SAURASHTRA VOWEL SIGN VOCALIC L;Mc;0;L;;;;;N;;;;; +A8BD;SAURASHTRA VOWEL SIGN VOCALIC LL;Mc;0;L;;;;;N;;;;; +A8BE;SAURASHTRA VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +A8BF;SAURASHTRA VOWEL SIGN EE;Mc;0;L;;;;;N;;;;; +A8C0;SAURASHTRA VOWEL SIGN AI;Mc;0;L;;;;;N;;;;; +A8C1;SAURASHTRA VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +A8C2;SAURASHTRA VOWEL SIGN OO;Mc;0;L;;;;;N;;;;; +A8C3;SAURASHTRA VOWEL SIGN AU;Mc;0;L;;;;;N;;;;; +A8C4;SAURASHTRA SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +A8CE;SAURASHTRA DANDA;Po;0;L;;;;;N;;;;; +A8CF;SAURASHTRA DOUBLE DANDA;Po;0;L;;;;;N;;;;; +A8D0;SAURASHTRA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +A8D1;SAURASHTRA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +A8D2;SAURASHTRA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +A8D3;SAURASHTRA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +A8D4;SAURASHTRA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +A8D5;SAURASHTRA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +A8D6;SAURASHTRA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +A8D7;SAURASHTRA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +A8D8;SAURASHTRA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +A8D9;SAURASHTRA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +A8E0;COMBINING DEVANAGARI DIGIT ZERO;Mn;230;NSM;;;;;N;;;;; +A8E1;COMBINING DEVANAGARI DIGIT ONE;Mn;230;NSM;;;;;N;;;;; +A8E2;COMBINING DEVANAGARI DIGIT TWO;Mn;230;NSM;;;;;N;;;;; +A8E3;COMBINING DEVANAGARI DIGIT THREE;Mn;230;NSM;;;;;N;;;;; +A8E4;COMBINING DEVANAGARI DIGIT FOUR;Mn;230;NSM;;;;;N;;;;; +A8E5;COMBINING DEVANAGARI DIGIT FIVE;Mn;230;NSM;;;;;N;;;;; +A8E6;COMBINING DEVANAGARI DIGIT SIX;Mn;230;NSM;;;;;N;;;;; +A8E7;COMBINING DEVANAGARI DIGIT SEVEN;Mn;230;NSM;;;;;N;;;;; +A8E8;COMBINING DEVANAGARI DIGIT EIGHT;Mn;230;NSM;;;;;N;;;;; +A8E9;COMBINING DEVANAGARI DIGIT NINE;Mn;230;NSM;;;;;N;;;;; +A8EA;COMBINING DEVANAGARI LETTER A;Mn;230;NSM;;;;;N;;;;; +A8EB;COMBINING DEVANAGARI LETTER U;Mn;230;NSM;;;;;N;;;;; +A8EC;COMBINING DEVANAGARI LETTER KA;Mn;230;NSM;;;;;N;;;;; +A8ED;COMBINING DEVANAGARI LETTER NA;Mn;230;NSM;;;;;N;;;;; +A8EE;COMBINING DEVANAGARI LETTER PA;Mn;230;NSM;;;;;N;;;;; +A8EF;COMBINING DEVANAGARI LETTER RA;Mn;230;NSM;;;;;N;;;;; +A8F0;COMBINING DEVANAGARI LETTER VI;Mn;230;NSM;;;;;N;;;;; +A8F1;COMBINING DEVANAGARI SIGN AVAGRAHA;Mn;230;NSM;;;;;N;;;;; +A8F2;DEVANAGARI SIGN SPACING CANDRABINDU;Lo;0;L;;;;;N;;;;; +A8F3;DEVANAGARI SIGN CANDRABINDU VIRAMA;Lo;0;L;;;;;N;;;;; +A8F4;DEVANAGARI SIGN DOUBLE CANDRABINDU VIRAMA;Lo;0;L;;;;;N;;;;; +A8F5;DEVANAGARI SIGN CANDRABINDU TWO;Lo;0;L;;;;;N;;;;; +A8F6;DEVANAGARI SIGN CANDRABINDU THREE;Lo;0;L;;;;;N;;;;; +A8F7;DEVANAGARI SIGN CANDRABINDU AVAGRAHA;Lo;0;L;;;;;N;;;;; +A8F8;DEVANAGARI SIGN PUSHPIKA;Po;0;L;;;;;N;;;;; +A8F9;DEVANAGARI GAP FILLER;Po;0;L;;;;;N;;;;; +A8FA;DEVANAGARI CARET;Po;0;L;;;;;N;;;;; +A8FB;DEVANAGARI HEADSTROKE;Lo;0;L;;;;;N;;;;; +A900;KAYAH LI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +A901;KAYAH LI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +A902;KAYAH LI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +A903;KAYAH LI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +A904;KAYAH LI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +A905;KAYAH LI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +A906;KAYAH LI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +A907;KAYAH LI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +A908;KAYAH LI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +A909;KAYAH LI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +A90A;KAYAH LI LETTER KA;Lo;0;L;;;;;N;;;;; +A90B;KAYAH LI LETTER KHA;Lo;0;L;;;;;N;;;;; +A90C;KAYAH LI LETTER GA;Lo;0;L;;;;;N;;;;; +A90D;KAYAH LI LETTER NGA;Lo;0;L;;;;;N;;;;; +A90E;KAYAH LI LETTER SA;Lo;0;L;;;;;N;;;;; +A90F;KAYAH LI LETTER SHA;Lo;0;L;;;;;N;;;;; +A910;KAYAH LI LETTER ZA;Lo;0;L;;;;;N;;;;; +A911;KAYAH LI LETTER NYA;Lo;0;L;;;;;N;;;;; +A912;KAYAH LI LETTER TA;Lo;0;L;;;;;N;;;;; +A913;KAYAH LI LETTER HTA;Lo;0;L;;;;;N;;;;; +A914;KAYAH LI LETTER NA;Lo;0;L;;;;;N;;;;; +A915;KAYAH LI LETTER PA;Lo;0;L;;;;;N;;;;; +A916;KAYAH LI LETTER PHA;Lo;0;L;;;;;N;;;;; +A917;KAYAH LI LETTER MA;Lo;0;L;;;;;N;;;;; +A918;KAYAH LI LETTER DA;Lo;0;L;;;;;N;;;;; +A919;KAYAH LI LETTER BA;Lo;0;L;;;;;N;;;;; +A91A;KAYAH LI LETTER RA;Lo;0;L;;;;;N;;;;; +A91B;KAYAH LI LETTER YA;Lo;0;L;;;;;N;;;;; +A91C;KAYAH LI LETTER LA;Lo;0;L;;;;;N;;;;; +A91D;KAYAH LI LETTER WA;Lo;0;L;;;;;N;;;;; +A91E;KAYAH LI LETTER THA;Lo;0;L;;;;;N;;;;; +A91F;KAYAH LI LETTER HA;Lo;0;L;;;;;N;;;;; +A920;KAYAH LI LETTER VA;Lo;0;L;;;;;N;;;;; +A921;KAYAH LI LETTER CA;Lo;0;L;;;;;N;;;;; +A922;KAYAH LI LETTER A;Lo;0;L;;;;;N;;;;; +A923;KAYAH LI LETTER OE;Lo;0;L;;;;;N;;;;; +A924;KAYAH LI LETTER I;Lo;0;L;;;;;N;;;;; +A925;KAYAH LI LETTER OO;Lo;0;L;;;;;N;;;;; +A926;KAYAH LI VOWEL UE;Mn;0;NSM;;;;;N;;;;; +A927;KAYAH LI VOWEL E;Mn;0;NSM;;;;;N;;;;; +A928;KAYAH LI VOWEL U;Mn;0;NSM;;;;;N;;;;; +A929;KAYAH LI VOWEL EE;Mn;0;NSM;;;;;N;;;;; +A92A;KAYAH LI VOWEL O;Mn;0;NSM;;;;;N;;;;; +A92B;KAYAH LI TONE PLOPHU;Mn;220;NSM;;;;;N;;;;; +A92C;KAYAH LI TONE CALYA;Mn;220;NSM;;;;;N;;;;; +A92D;KAYAH LI TONE CALYA PLOPHU;Mn;220;NSM;;;;;N;;;;; +A92E;KAYAH LI SIGN CWI;Po;0;L;;;;;N;;;;; +A92F;KAYAH LI SIGN SHYA;Po;0;L;;;;;N;;;;; +A930;REJANG LETTER KA;Lo;0;L;;;;;N;;;;; +A931;REJANG LETTER GA;Lo;0;L;;;;;N;;;;; +A932;REJANG LETTER NGA;Lo;0;L;;;;;N;;;;; +A933;REJANG LETTER TA;Lo;0;L;;;;;N;;;;; +A934;REJANG LETTER DA;Lo;0;L;;;;;N;;;;; +A935;REJANG LETTER NA;Lo;0;L;;;;;N;;;;; +A936;REJANG LETTER PA;Lo;0;L;;;;;N;;;;; +A937;REJANG LETTER BA;Lo;0;L;;;;;N;;;;; +A938;REJANG LETTER MA;Lo;0;L;;;;;N;;;;; +A939;REJANG LETTER CA;Lo;0;L;;;;;N;;;;; +A93A;REJANG LETTER JA;Lo;0;L;;;;;N;;;;; +A93B;REJANG LETTER NYA;Lo;0;L;;;;;N;;;;; +A93C;REJANG LETTER SA;Lo;0;L;;;;;N;;;;; +A93D;REJANG LETTER RA;Lo;0;L;;;;;N;;;;; +A93E;REJANG LETTER LA;Lo;0;L;;;;;N;;;;; +A93F;REJANG LETTER YA;Lo;0;L;;;;;N;;;;; +A940;REJANG LETTER WA;Lo;0;L;;;;;N;;;;; +A941;REJANG LETTER HA;Lo;0;L;;;;;N;;;;; +A942;REJANG LETTER MBA;Lo;0;L;;;;;N;;;;; +A943;REJANG LETTER NGGA;Lo;0;L;;;;;N;;;;; +A944;REJANG LETTER NDA;Lo;0;L;;;;;N;;;;; +A945;REJANG LETTER NYJA;Lo;0;L;;;;;N;;;;; +A946;REJANG LETTER A;Lo;0;L;;;;;N;;;;; +A947;REJANG VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +A948;REJANG VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +A949;REJANG VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +A94A;REJANG VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +A94B;REJANG VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;; +A94C;REJANG VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;; +A94D;REJANG VOWEL SIGN EU;Mn;0;NSM;;;;;N;;;;; +A94E;REJANG VOWEL SIGN EA;Mn;0;NSM;;;;;N;;;;; +A94F;REJANG CONSONANT SIGN NG;Mn;0;NSM;;;;;N;;;;; +A950;REJANG CONSONANT SIGN N;Mn;0;NSM;;;;;N;;;;; +A951;REJANG CONSONANT SIGN R;Mn;0;NSM;;;;;N;;;;; +A952;REJANG CONSONANT SIGN H;Mc;0;L;;;;;N;;;;; +A953;REJANG VIRAMA;Mc;9;L;;;;;N;;;;; +A95F;REJANG SECTION MARK;Po;0;L;;;;;N;;;;; +A960;HANGUL CHOSEONG TIKEUT-MIEUM;Lo;0;L;;;;;N;;;;; +A961;HANGUL CHOSEONG TIKEUT-PIEUP;Lo;0;L;;;;;N;;;;; +A962;HANGUL CHOSEONG TIKEUT-SIOS;Lo;0;L;;;;;N;;;;; +A963;HANGUL CHOSEONG TIKEUT-CIEUC;Lo;0;L;;;;;N;;;;; +A964;HANGUL CHOSEONG RIEUL-KIYEOK;Lo;0;L;;;;;N;;;;; +A965;HANGUL CHOSEONG RIEUL-SSANGKIYEOK;Lo;0;L;;;;;N;;;;; +A966;HANGUL CHOSEONG RIEUL-TIKEUT;Lo;0;L;;;;;N;;;;; +A967;HANGUL CHOSEONG RIEUL-SSANGTIKEUT;Lo;0;L;;;;;N;;;;; +A968;HANGUL CHOSEONG RIEUL-MIEUM;Lo;0;L;;;;;N;;;;; +A969;HANGUL CHOSEONG RIEUL-PIEUP;Lo;0;L;;;;;N;;;;; +A96A;HANGUL CHOSEONG RIEUL-SSANGPIEUP;Lo;0;L;;;;;N;;;;; +A96B;HANGUL CHOSEONG RIEUL-KAPYEOUNPIEUP;Lo;0;L;;;;;N;;;;; +A96C;HANGUL CHOSEONG RIEUL-SIOS;Lo;0;L;;;;;N;;;;; +A96D;HANGUL CHOSEONG RIEUL-CIEUC;Lo;0;L;;;;;N;;;;; +A96E;HANGUL CHOSEONG RIEUL-KHIEUKH;Lo;0;L;;;;;N;;;;; +A96F;HANGUL CHOSEONG MIEUM-KIYEOK;Lo;0;L;;;;;N;;;;; +A970;HANGUL CHOSEONG MIEUM-TIKEUT;Lo;0;L;;;;;N;;;;; +A971;HANGUL CHOSEONG MIEUM-SIOS;Lo;0;L;;;;;N;;;;; +A972;HANGUL CHOSEONG PIEUP-SIOS-THIEUTH;Lo;0;L;;;;;N;;;;; +A973;HANGUL CHOSEONG PIEUP-KHIEUKH;Lo;0;L;;;;;N;;;;; +A974;HANGUL CHOSEONG PIEUP-HIEUH;Lo;0;L;;;;;N;;;;; +A975;HANGUL CHOSEONG SSANGSIOS-PIEUP;Lo;0;L;;;;;N;;;;; +A976;HANGUL CHOSEONG IEUNG-RIEUL;Lo;0;L;;;;;N;;;;; +A977;HANGUL CHOSEONG IEUNG-HIEUH;Lo;0;L;;;;;N;;;;; +A978;HANGUL CHOSEONG SSANGCIEUC-HIEUH;Lo;0;L;;;;;N;;;;; +A979;HANGUL CHOSEONG SSANGTHIEUTH;Lo;0;L;;;;;N;;;;; +A97A;HANGUL CHOSEONG PHIEUPH-HIEUH;Lo;0;L;;;;;N;;;;; +A97B;HANGUL CHOSEONG HIEUH-SIOS;Lo;0;L;;;;;N;;;;; +A97C;HANGUL CHOSEONG SSANGYEORINHIEUH;Lo;0;L;;;;;N;;;;; +A980;JAVANESE SIGN PANYANGGA;Mn;0;NSM;;;;;N;;;;; +A981;JAVANESE SIGN CECAK;Mn;0;NSM;;;;;N;;;;; +A982;JAVANESE SIGN LAYAR;Mn;0;NSM;;;;;N;;;;; +A983;JAVANESE SIGN WIGNYAN;Mc;0;L;;;;;N;;;;; +A984;JAVANESE LETTER A;Lo;0;L;;;;;N;;;;; +A985;JAVANESE LETTER I KAWI;Lo;0;L;;;;;N;;;;; +A986;JAVANESE LETTER I;Lo;0;L;;;;;N;;;;; +A987;JAVANESE LETTER II;Lo;0;L;;;;;N;;;;; +A988;JAVANESE LETTER U;Lo;0;L;;;;;N;;;;; +A989;JAVANESE LETTER PA CEREK;Lo;0;L;;;;;N;;;;; +A98A;JAVANESE LETTER NGA LELET;Lo;0;L;;;;;N;;;;; +A98B;JAVANESE LETTER NGA LELET RASWADI;Lo;0;L;;;;;N;;;;; +A98C;JAVANESE LETTER E;Lo;0;L;;;;;N;;;;; +A98D;JAVANESE LETTER AI;Lo;0;L;;;;;N;;;;; +A98E;JAVANESE LETTER O;Lo;0;L;;;;;N;;;;; +A98F;JAVANESE LETTER KA;Lo;0;L;;;;;N;;;;; +A990;JAVANESE LETTER KA SASAK;Lo;0;L;;;;;N;;;;; +A991;JAVANESE LETTER KA MURDA;Lo;0;L;;;;;N;;;;; +A992;JAVANESE LETTER GA;Lo;0;L;;;;;N;;;;; +A993;JAVANESE LETTER GA MURDA;Lo;0;L;;;;;N;;;;; +A994;JAVANESE LETTER NGA;Lo;0;L;;;;;N;;;;; +A995;JAVANESE LETTER CA;Lo;0;L;;;;;N;;;;; +A996;JAVANESE LETTER CA MURDA;Lo;0;L;;;;;N;;;;; +A997;JAVANESE LETTER JA;Lo;0;L;;;;;N;;;;; +A998;JAVANESE LETTER NYA MURDA;Lo;0;L;;;;;N;;;;; +A999;JAVANESE LETTER JA MAHAPRANA;Lo;0;L;;;;;N;;;;; +A99A;JAVANESE LETTER NYA;Lo;0;L;;;;;N;;;;; +A99B;JAVANESE LETTER TTA;Lo;0;L;;;;;N;;;;; +A99C;JAVANESE LETTER TTA MAHAPRANA;Lo;0;L;;;;;N;;;;; +A99D;JAVANESE LETTER DDA;Lo;0;L;;;;;N;;;;; +A99E;JAVANESE LETTER DDA MAHAPRANA;Lo;0;L;;;;;N;;;;; +A99F;JAVANESE LETTER NA MURDA;Lo;0;L;;;;;N;;;;; +A9A0;JAVANESE LETTER TA;Lo;0;L;;;;;N;;;;; +A9A1;JAVANESE LETTER TA MURDA;Lo;0;L;;;;;N;;;;; +A9A2;JAVANESE LETTER DA;Lo;0;L;;;;;N;;;;; +A9A3;JAVANESE LETTER DA MAHAPRANA;Lo;0;L;;;;;N;;;;; +A9A4;JAVANESE LETTER NA;Lo;0;L;;;;;N;;;;; +A9A5;JAVANESE LETTER PA;Lo;0;L;;;;;N;;;;; +A9A6;JAVANESE LETTER PA MURDA;Lo;0;L;;;;;N;;;;; +A9A7;JAVANESE LETTER BA;Lo;0;L;;;;;N;;;;; +A9A8;JAVANESE LETTER BA MURDA;Lo;0;L;;;;;N;;;;; +A9A9;JAVANESE LETTER MA;Lo;0;L;;;;;N;;;;; +A9AA;JAVANESE LETTER YA;Lo;0;L;;;;;N;;;;; +A9AB;JAVANESE LETTER RA;Lo;0;L;;;;;N;;;;; +A9AC;JAVANESE LETTER RA AGUNG;Lo;0;L;;;;;N;;;;; +A9AD;JAVANESE LETTER LA;Lo;0;L;;;;;N;;;;; +A9AE;JAVANESE LETTER WA;Lo;0;L;;;;;N;;;;; +A9AF;JAVANESE LETTER SA MURDA;Lo;0;L;;;;;N;;;;; +A9B0;JAVANESE LETTER SA MAHAPRANA;Lo;0;L;;;;;N;;;;; +A9B1;JAVANESE LETTER SA;Lo;0;L;;;;;N;;;;; +A9B2;JAVANESE LETTER HA;Lo;0;L;;;;;N;;;;; +A9B3;JAVANESE SIGN CECAK TELU;Mn;7;NSM;;;;;N;;;;; +A9B4;JAVANESE VOWEL SIGN TARUNG;Mc;0;L;;;;;N;;;;; +A9B5;JAVANESE VOWEL SIGN TOLONG;Mc;0;L;;;;;N;;;;; +A9B6;JAVANESE VOWEL SIGN WULU;Mn;0;NSM;;;;;N;;;;; +A9B7;JAVANESE VOWEL SIGN WULU MELIK;Mn;0;NSM;;;;;N;;;;; +A9B8;JAVANESE VOWEL SIGN SUKU;Mn;0;NSM;;;;;N;;;;; +A9B9;JAVANESE VOWEL SIGN SUKU MENDUT;Mn;0;NSM;;;;;N;;;;; +A9BA;JAVANESE VOWEL SIGN TALING;Mc;0;L;;;;;N;;;;; +A9BB;JAVANESE VOWEL SIGN DIRGA MURE;Mc;0;L;;;;;N;;;;; +A9BC;JAVANESE VOWEL SIGN PEPET;Mn;0;NSM;;;;;N;;;;; +A9BD;JAVANESE CONSONANT SIGN KERET;Mc;0;L;;;;;N;;;;; +A9BE;JAVANESE CONSONANT SIGN PENGKAL;Mc;0;L;;;;;N;;;;; +A9BF;JAVANESE CONSONANT SIGN CAKRA;Mc;0;L;;;;;N;;;;; +A9C0;JAVANESE PANGKON;Mc;9;L;;;;;N;;;;; +A9C1;JAVANESE LEFT RERENGGAN;Po;0;L;;;;;N;;;;; +A9C2;JAVANESE RIGHT RERENGGAN;Po;0;L;;;;;N;;;;; +A9C3;JAVANESE PADA ANDAP;Po;0;L;;;;;N;;;;; +A9C4;JAVANESE PADA MADYA;Po;0;L;;;;;N;;;;; +A9C5;JAVANESE PADA LUHUR;Po;0;L;;;;;N;;;;; +A9C6;JAVANESE PADA WINDU;Po;0;L;;;;;N;;;;; +A9C7;JAVANESE PADA PANGKAT;Po;0;L;;;;;N;;;;; +A9C8;JAVANESE PADA LINGSA;Po;0;L;;;;;N;;;;; +A9C9;JAVANESE PADA LUNGSI;Po;0;L;;;;;N;;;;; +A9CA;JAVANESE PADA ADEG;Po;0;L;;;;;N;;;;; +A9CB;JAVANESE PADA ADEG ADEG;Po;0;L;;;;;N;;;;; +A9CC;JAVANESE PADA PISELEH;Po;0;L;;;;;N;;;;; +A9CD;JAVANESE TURNED PADA PISELEH;Po;0;L;;;;;N;;;;; +A9CF;JAVANESE PANGRANGKEP;Lm;0;L;;;;;N;;;;; +A9D0;JAVANESE DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +A9D1;JAVANESE DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +A9D2;JAVANESE DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +A9D3;JAVANESE DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +A9D4;JAVANESE DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +A9D5;JAVANESE DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +A9D6;JAVANESE DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +A9D7;JAVANESE DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +A9D8;JAVANESE DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +A9D9;JAVANESE DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +A9DE;JAVANESE PADA TIRTA TUMETES;Po;0;L;;;;;N;;;;; +A9DF;JAVANESE PADA ISEN-ISEN;Po;0;L;;;;;N;;;;; +AA00;CHAM LETTER A;Lo;0;L;;;;;N;;;;; +AA01;CHAM LETTER I;Lo;0;L;;;;;N;;;;; +AA02;CHAM LETTER U;Lo;0;L;;;;;N;;;;; +AA03;CHAM LETTER E;Lo;0;L;;;;;N;;;;; +AA04;CHAM LETTER AI;Lo;0;L;;;;;N;;;;; +AA05;CHAM LETTER O;Lo;0;L;;;;;N;;;;; +AA06;CHAM LETTER KA;Lo;0;L;;;;;N;;;;; +AA07;CHAM LETTER KHA;Lo;0;L;;;;;N;;;;; +AA08;CHAM LETTER GA;Lo;0;L;;;;;N;;;;; +AA09;CHAM LETTER GHA;Lo;0;L;;;;;N;;;;; +AA0A;CHAM LETTER NGUE;Lo;0;L;;;;;N;;;;; +AA0B;CHAM LETTER NGA;Lo;0;L;;;;;N;;;;; +AA0C;CHAM LETTER CHA;Lo;0;L;;;;;N;;;;; +AA0D;CHAM LETTER CHHA;Lo;0;L;;;;;N;;;;; +AA0E;CHAM LETTER JA;Lo;0;L;;;;;N;;;;; +AA0F;CHAM LETTER JHA;Lo;0;L;;;;;N;;;;; +AA10;CHAM LETTER NHUE;Lo;0;L;;;;;N;;;;; +AA11;CHAM LETTER NHA;Lo;0;L;;;;;N;;;;; +AA12;CHAM LETTER NHJA;Lo;0;L;;;;;N;;;;; +AA13;CHAM LETTER TA;Lo;0;L;;;;;N;;;;; +AA14;CHAM LETTER THA;Lo;0;L;;;;;N;;;;; +AA15;CHAM LETTER DA;Lo;0;L;;;;;N;;;;; +AA16;CHAM LETTER DHA;Lo;0;L;;;;;N;;;;; +AA17;CHAM LETTER NUE;Lo;0;L;;;;;N;;;;; +AA18;CHAM LETTER NA;Lo;0;L;;;;;N;;;;; +AA19;CHAM LETTER DDA;Lo;0;L;;;;;N;;;;; +AA1A;CHAM LETTER PA;Lo;0;L;;;;;N;;;;; +AA1B;CHAM LETTER PPA;Lo;0;L;;;;;N;;;;; +AA1C;CHAM LETTER PHA;Lo;0;L;;;;;N;;;;; +AA1D;CHAM LETTER BA;Lo;0;L;;;;;N;;;;; +AA1E;CHAM LETTER BHA;Lo;0;L;;;;;N;;;;; +AA1F;CHAM LETTER MUE;Lo;0;L;;;;;N;;;;; +AA20;CHAM LETTER MA;Lo;0;L;;;;;N;;;;; +AA21;CHAM LETTER BBA;Lo;0;L;;;;;N;;;;; +AA22;CHAM LETTER YA;Lo;0;L;;;;;N;;;;; +AA23;CHAM LETTER RA;Lo;0;L;;;;;N;;;;; +AA24;CHAM LETTER LA;Lo;0;L;;;;;N;;;;; +AA25;CHAM LETTER VA;Lo;0;L;;;;;N;;;;; +AA26;CHAM LETTER SSA;Lo;0;L;;;;;N;;;;; +AA27;CHAM LETTER SA;Lo;0;L;;;;;N;;;;; +AA28;CHAM LETTER HA;Lo;0;L;;;;;N;;;;; +AA29;CHAM VOWEL SIGN AA;Mn;0;NSM;;;;;N;;;;; +AA2A;CHAM VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +AA2B;CHAM VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;; +AA2C;CHAM VOWEL SIGN EI;Mn;0;NSM;;;;;N;;;;; +AA2D;CHAM VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +AA2E;CHAM VOWEL SIGN OE;Mn;0;NSM;;;;;N;;;;; +AA2F;CHAM VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +AA30;CHAM VOWEL SIGN AI;Mc;0;L;;;;;N;;;;; +AA31;CHAM VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;; +AA32;CHAM VOWEL SIGN UE;Mn;0;NSM;;;;;N;;;;; +AA33;CHAM CONSONANT SIGN YA;Mc;0;L;;;;;N;;;;; +AA34;CHAM CONSONANT SIGN RA;Mc;0;L;;;;;N;;;;; +AA35;CHAM CONSONANT SIGN LA;Mn;0;NSM;;;;;N;;;;; +AA36;CHAM CONSONANT SIGN WA;Mn;0;NSM;;;;;N;;;;; +AA40;CHAM LETTER FINAL K;Lo;0;L;;;;;N;;;;; +AA41;CHAM LETTER FINAL G;Lo;0;L;;;;;N;;;;; +AA42;CHAM LETTER FINAL NG;Lo;0;L;;;;;N;;;;; +AA43;CHAM CONSONANT SIGN FINAL NG;Mn;0;NSM;;;;;N;;;;; +AA44;CHAM LETTER FINAL CH;Lo;0;L;;;;;N;;;;; +AA45;CHAM LETTER FINAL T;Lo;0;L;;;;;N;;;;; +AA46;CHAM LETTER FINAL N;Lo;0;L;;;;;N;;;;; +AA47;CHAM LETTER FINAL P;Lo;0;L;;;;;N;;;;; +AA48;CHAM LETTER FINAL Y;Lo;0;L;;;;;N;;;;; +AA49;CHAM LETTER FINAL R;Lo;0;L;;;;;N;;;;; +AA4A;CHAM LETTER FINAL L;Lo;0;L;;;;;N;;;;; +AA4B;CHAM LETTER FINAL SS;Lo;0;L;;;;;N;;;;; +AA4C;CHAM CONSONANT SIGN FINAL M;Mn;0;NSM;;;;;N;;;;; +AA4D;CHAM CONSONANT SIGN FINAL H;Mc;0;L;;;;;N;;;;; +AA50;CHAM DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +AA51;CHAM DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +AA52;CHAM DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +AA53;CHAM DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +AA54;CHAM DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +AA55;CHAM DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +AA56;CHAM DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +AA57;CHAM DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +AA58;CHAM DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +AA59;CHAM DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +AA5C;CHAM PUNCTUATION SPIRAL;Po;0;L;;;;;N;;;;; +AA5D;CHAM PUNCTUATION DANDA;Po;0;L;;;;;N;;;;; +AA5E;CHAM PUNCTUATION DOUBLE DANDA;Po;0;L;;;;;N;;;;; +AA5F;CHAM PUNCTUATION TRIPLE DANDA;Po;0;L;;;;;N;;;;; +AA60;MYANMAR LETTER KHAMTI GA;Lo;0;L;;;;;N;;;;; +AA61;MYANMAR LETTER KHAMTI CA;Lo;0;L;;;;;N;;;;; +AA62;MYANMAR LETTER KHAMTI CHA;Lo;0;L;;;;;N;;;;; +AA63;MYANMAR LETTER KHAMTI JA;Lo;0;L;;;;;N;;;;; +AA64;MYANMAR LETTER KHAMTI JHA;Lo;0;L;;;;;N;;;;; +AA65;MYANMAR LETTER KHAMTI NYA;Lo;0;L;;;;;N;;;;; +AA66;MYANMAR LETTER KHAMTI TTA;Lo;0;L;;;;;N;;;;; +AA67;MYANMAR LETTER KHAMTI TTHA;Lo;0;L;;;;;N;;;;; +AA68;MYANMAR LETTER KHAMTI DDA;Lo;0;L;;;;;N;;;;; +AA69;MYANMAR LETTER KHAMTI DDHA;Lo;0;L;;;;;N;;;;; +AA6A;MYANMAR LETTER KHAMTI DHA;Lo;0;L;;;;;N;;;;; +AA6B;MYANMAR LETTER KHAMTI NA;Lo;0;L;;;;;N;;;;; +AA6C;MYANMAR LETTER KHAMTI SA;Lo;0;L;;;;;N;;;;; +AA6D;MYANMAR LETTER KHAMTI HA;Lo;0;L;;;;;N;;;;; +AA6E;MYANMAR LETTER KHAMTI HHA;Lo;0;L;;;;;N;;;;; +AA6F;MYANMAR LETTER KHAMTI FA;Lo;0;L;;;;;N;;;;; +AA70;MYANMAR MODIFIER LETTER KHAMTI REDUPLICATION;Lm;0;L;;;;;N;;;;; +AA71;MYANMAR LETTER KHAMTI XA;Lo;0;L;;;;;N;;;;; +AA72;MYANMAR LETTER KHAMTI ZA;Lo;0;L;;;;;N;;;;; +AA73;MYANMAR LETTER KHAMTI RA;Lo;0;L;;;;;N;;;;; +AA74;MYANMAR LOGOGRAM KHAMTI OAY;Lo;0;L;;;;;N;;;;; +AA75;MYANMAR LOGOGRAM KHAMTI QN;Lo;0;L;;;;;N;;;;; +AA76;MYANMAR LOGOGRAM KHAMTI HM;Lo;0;L;;;;;N;;;;; +AA77;MYANMAR SYMBOL AITON EXCLAMATION;So;0;L;;;;;N;;;;; +AA78;MYANMAR SYMBOL AITON ONE;So;0;L;;;;;N;;;;; +AA79;MYANMAR SYMBOL AITON TWO;So;0;L;;;;;N;;;;; +AA7A;MYANMAR LETTER AITON RA;Lo;0;L;;;;;N;;;;; +AA7B;MYANMAR SIGN PAO KAREN TONE;Mc;0;L;;;;;N;;;;; +AA80;TAI VIET LETTER LOW KO;Lo;0;L;;;;;N;;;;; +AA81;TAI VIET LETTER HIGH KO;Lo;0;L;;;;;N;;;;; +AA82;TAI VIET LETTER LOW KHO;Lo;0;L;;;;;N;;;;; +AA83;TAI VIET LETTER HIGH KHO;Lo;0;L;;;;;N;;;;; +AA84;TAI VIET LETTER LOW KHHO;Lo;0;L;;;;;N;;;;; +AA85;TAI VIET LETTER HIGH KHHO;Lo;0;L;;;;;N;;;;; +AA86;TAI VIET LETTER LOW GO;Lo;0;L;;;;;N;;;;; +AA87;TAI VIET LETTER HIGH GO;Lo;0;L;;;;;N;;;;; +AA88;TAI VIET LETTER LOW NGO;Lo;0;L;;;;;N;;;;; +AA89;TAI VIET LETTER HIGH NGO;Lo;0;L;;;;;N;;;;; +AA8A;TAI VIET LETTER LOW CO;Lo;0;L;;;;;N;;;;; +AA8B;TAI VIET LETTER HIGH CO;Lo;0;L;;;;;N;;;;; +AA8C;TAI VIET LETTER LOW CHO;Lo;0;L;;;;;N;;;;; +AA8D;TAI VIET LETTER HIGH CHO;Lo;0;L;;;;;N;;;;; +AA8E;TAI VIET LETTER LOW SO;Lo;0;L;;;;;N;;;;; +AA8F;TAI VIET LETTER HIGH SO;Lo;0;L;;;;;N;;;;; +AA90;TAI VIET LETTER LOW NYO;Lo;0;L;;;;;N;;;;; +AA91;TAI VIET LETTER HIGH NYO;Lo;0;L;;;;;N;;;;; +AA92;TAI VIET LETTER LOW DO;Lo;0;L;;;;;N;;;;; +AA93;TAI VIET LETTER HIGH DO;Lo;0;L;;;;;N;;;;; +AA94;TAI VIET LETTER LOW TO;Lo;0;L;;;;;N;;;;; +AA95;TAI VIET LETTER HIGH TO;Lo;0;L;;;;;N;;;;; +AA96;TAI VIET LETTER LOW THO;Lo;0;L;;;;;N;;;;; +AA97;TAI VIET LETTER HIGH THO;Lo;0;L;;;;;N;;;;; +AA98;TAI VIET LETTER LOW NO;Lo;0;L;;;;;N;;;;; +AA99;TAI VIET LETTER HIGH NO;Lo;0;L;;;;;N;;;;; +AA9A;TAI VIET LETTER LOW BO;Lo;0;L;;;;;N;;;;; +AA9B;TAI VIET LETTER HIGH BO;Lo;0;L;;;;;N;;;;; +AA9C;TAI VIET LETTER LOW PO;Lo;0;L;;;;;N;;;;; +AA9D;TAI VIET LETTER HIGH PO;Lo;0;L;;;;;N;;;;; +AA9E;TAI VIET LETTER LOW PHO;Lo;0;L;;;;;N;;;;; +AA9F;TAI VIET LETTER HIGH PHO;Lo;0;L;;;;;N;;;;; +AAA0;TAI VIET LETTER LOW FO;Lo;0;L;;;;;N;;;;; +AAA1;TAI VIET LETTER HIGH FO;Lo;0;L;;;;;N;;;;; +AAA2;TAI VIET LETTER LOW MO;Lo;0;L;;;;;N;;;;; +AAA3;TAI VIET LETTER HIGH MO;Lo;0;L;;;;;N;;;;; +AAA4;TAI VIET LETTER LOW YO;Lo;0;L;;;;;N;;;;; +AAA5;TAI VIET LETTER HIGH YO;Lo;0;L;;;;;N;;;;; +AAA6;TAI VIET LETTER LOW RO;Lo;0;L;;;;;N;;;;; +AAA7;TAI VIET LETTER HIGH RO;Lo;0;L;;;;;N;;;;; +AAA8;TAI VIET LETTER LOW LO;Lo;0;L;;;;;N;;;;; +AAA9;TAI VIET LETTER HIGH LO;Lo;0;L;;;;;N;;;;; +AAAA;TAI VIET LETTER LOW VO;Lo;0;L;;;;;N;;;;; +AAAB;TAI VIET LETTER HIGH VO;Lo;0;L;;;;;N;;;;; +AAAC;TAI VIET LETTER LOW HO;Lo;0;L;;;;;N;;;;; +AAAD;TAI VIET LETTER HIGH HO;Lo;0;L;;;;;N;;;;; +AAAE;TAI VIET LETTER LOW O;Lo;0;L;;;;;N;;;;; +AAAF;TAI VIET LETTER HIGH O;Lo;0;L;;;;;N;;;;; +AAB0;TAI VIET MAI KANG;Mn;230;NSM;;;;;N;;;;; +AAB1;TAI VIET VOWEL AA;Lo;0;L;;;;;N;;;;; +AAB2;TAI VIET VOWEL I;Mn;230;NSM;;;;;N;;;;; +AAB3;TAI VIET VOWEL UE;Mn;230;NSM;;;;;N;;;;; +AAB4;TAI VIET VOWEL U;Mn;220;NSM;;;;;N;;;;; +AAB5;TAI VIET VOWEL E;Lo;0;L;;;;;N;;;;; +AAB6;TAI VIET VOWEL O;Lo;0;L;;;;;N;;;;; +AAB7;TAI VIET MAI KHIT;Mn;230;NSM;;;;;N;;;;; +AAB8;TAI VIET VOWEL IA;Mn;230;NSM;;;;;N;;;;; +AAB9;TAI VIET VOWEL UEA;Lo;0;L;;;;;N;;;;; +AABA;TAI VIET VOWEL UA;Lo;0;L;;;;;N;;;;; +AABB;TAI VIET VOWEL AUE;Lo;0;L;;;;;N;;;;; +AABC;TAI VIET VOWEL AY;Lo;0;L;;;;;N;;;;; +AABD;TAI VIET VOWEL AN;Lo;0;L;;;;;N;;;;; +AABE;TAI VIET VOWEL AM;Mn;230;NSM;;;;;N;;;;; +AABF;TAI VIET TONE MAI EK;Mn;230;NSM;;;;;N;;;;; +AAC0;TAI VIET TONE MAI NUENG;Lo;0;L;;;;;N;;;;; +AAC1;TAI VIET TONE MAI THO;Mn;230;NSM;;;;;N;;;;; +AAC2;TAI VIET TONE MAI SONG;Lo;0;L;;;;;N;;;;; +AADB;TAI VIET SYMBOL KON;Lo;0;L;;;;;N;;;;; +AADC;TAI VIET SYMBOL NUENG;Lo;0;L;;;;;N;;;;; +AADD;TAI VIET SYMBOL SAM;Lm;0;L;;;;;N;;;;; +AADE;TAI VIET SYMBOL HO HOI;Po;0;L;;;;;N;;;;; +AADF;TAI VIET SYMBOL KOI KOI;Po;0;L;;;;;N;;;;; +AAE0;MEETEI MAYEK LETTER E;Lo;0;L;;;;;N;;;;; +AAE1;MEETEI MAYEK LETTER O;Lo;0;L;;;;;N;;;;; +AAE2;MEETEI MAYEK LETTER CHA;Lo;0;L;;;;;N;;;;; +AAE3;MEETEI MAYEK LETTER NYA;Lo;0;L;;;;;N;;;;; +AAE4;MEETEI MAYEK LETTER TTA;Lo;0;L;;;;;N;;;;; +AAE5;MEETEI MAYEK LETTER TTHA;Lo;0;L;;;;;N;;;;; +AAE6;MEETEI MAYEK LETTER DDA;Lo;0;L;;;;;N;;;;; +AAE7;MEETEI MAYEK LETTER DDHA;Lo;0;L;;;;;N;;;;; +AAE8;MEETEI MAYEK LETTER NNA;Lo;0;L;;;;;N;;;;; +AAE9;MEETEI MAYEK LETTER SHA;Lo;0;L;;;;;N;;;;; +AAEA;MEETEI MAYEK LETTER SSA;Lo;0;L;;;;;N;;;;; +AAEB;MEETEI MAYEK VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +AAEC;MEETEI MAYEK VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +AAED;MEETEI MAYEK VOWEL SIGN AAI;Mn;0;NSM;;;;;N;;;;; +AAEE;MEETEI MAYEK VOWEL SIGN AU;Mc;0;L;;;;;N;;;;; +AAEF;MEETEI MAYEK VOWEL SIGN AAU;Mc;0;L;;;;;N;;;;; +AAF0;MEETEI MAYEK CHEIKHAN;Po;0;L;;;;;N;;;;; +AAF1;MEETEI MAYEK AHANG KHUDAM;Po;0;L;;;;;N;;;;; +AAF2;MEETEI MAYEK ANJI;Lo;0;L;;;;;N;;;;; +AAF3;MEETEI MAYEK SYLLABLE REPETITION MARK;Lm;0;L;;;;;N;;;;; +AAF4;MEETEI MAYEK WORD REPETITION MARK;Lm;0;L;;;;;N;;;;; +AAF5;MEETEI MAYEK VOWEL SIGN VISARGA;Mc;0;L;;;;;N;;;;; +AAF6;MEETEI MAYEK VIRAMA;Mn;9;NSM;;;;;N;;;;; +AB01;ETHIOPIC SYLLABLE TTHU;Lo;0;L;;;;;N;;;;; +AB02;ETHIOPIC SYLLABLE TTHI;Lo;0;L;;;;;N;;;;; +AB03;ETHIOPIC SYLLABLE TTHAA;Lo;0;L;;;;;N;;;;; +AB04;ETHIOPIC SYLLABLE TTHEE;Lo;0;L;;;;;N;;;;; +AB05;ETHIOPIC SYLLABLE TTHE;Lo;0;L;;;;;N;;;;; +AB06;ETHIOPIC SYLLABLE TTHO;Lo;0;L;;;;;N;;;;; +AB09;ETHIOPIC SYLLABLE DDHU;Lo;0;L;;;;;N;;;;; +AB0A;ETHIOPIC SYLLABLE DDHI;Lo;0;L;;;;;N;;;;; +AB0B;ETHIOPIC SYLLABLE DDHAA;Lo;0;L;;;;;N;;;;; +AB0C;ETHIOPIC SYLLABLE DDHEE;Lo;0;L;;;;;N;;;;; +AB0D;ETHIOPIC SYLLABLE DDHE;Lo;0;L;;;;;N;;;;; +AB0E;ETHIOPIC SYLLABLE DDHO;Lo;0;L;;;;;N;;;;; +AB11;ETHIOPIC SYLLABLE DZU;Lo;0;L;;;;;N;;;;; +AB12;ETHIOPIC SYLLABLE DZI;Lo;0;L;;;;;N;;;;; +AB13;ETHIOPIC SYLLABLE DZAA;Lo;0;L;;;;;N;;;;; +AB14;ETHIOPIC SYLLABLE DZEE;Lo;0;L;;;;;N;;;;; +AB15;ETHIOPIC SYLLABLE DZE;Lo;0;L;;;;;N;;;;; +AB16;ETHIOPIC SYLLABLE DZO;Lo;0;L;;;;;N;;;;; +AB20;ETHIOPIC SYLLABLE CCHHA;Lo;0;L;;;;;N;;;;; +AB21;ETHIOPIC SYLLABLE CCHHU;Lo;0;L;;;;;N;;;;; +AB22;ETHIOPIC SYLLABLE CCHHI;Lo;0;L;;;;;N;;;;; +AB23;ETHIOPIC SYLLABLE CCHHAA;Lo;0;L;;;;;N;;;;; +AB24;ETHIOPIC SYLLABLE CCHHEE;Lo;0;L;;;;;N;;;;; +AB25;ETHIOPIC SYLLABLE CCHHE;Lo;0;L;;;;;N;;;;; +AB26;ETHIOPIC SYLLABLE CCHHO;Lo;0;L;;;;;N;;;;; +AB28;ETHIOPIC SYLLABLE BBA;Lo;0;L;;;;;N;;;;; +AB29;ETHIOPIC SYLLABLE BBU;Lo;0;L;;;;;N;;;;; +AB2A;ETHIOPIC SYLLABLE BBI;Lo;0;L;;;;;N;;;;; +AB2B;ETHIOPIC SYLLABLE BBAA;Lo;0;L;;;;;N;;;;; +AB2C;ETHIOPIC SYLLABLE BBEE;Lo;0;L;;;;;N;;;;; +AB2D;ETHIOPIC SYLLABLE BBE;Lo;0;L;;;;;N;;;;; +AB2E;ETHIOPIC SYLLABLE BBO;Lo;0;L;;;;;N;;;;; +ABC0;MEETEI MAYEK LETTER KOK;Lo;0;L;;;;;N;;;;; +ABC1;MEETEI MAYEK LETTER SAM;Lo;0;L;;;;;N;;;;; +ABC2;MEETEI MAYEK LETTER LAI;Lo;0;L;;;;;N;;;;; +ABC3;MEETEI MAYEK LETTER MIT;Lo;0;L;;;;;N;;;;; +ABC4;MEETEI MAYEK LETTER PA;Lo;0;L;;;;;N;;;;; +ABC5;MEETEI MAYEK LETTER NA;Lo;0;L;;;;;N;;;;; +ABC6;MEETEI MAYEK LETTER CHIL;Lo;0;L;;;;;N;;;;; +ABC7;MEETEI MAYEK LETTER TIL;Lo;0;L;;;;;N;;;;; +ABC8;MEETEI MAYEK LETTER KHOU;Lo;0;L;;;;;N;;;;; +ABC9;MEETEI MAYEK LETTER NGOU;Lo;0;L;;;;;N;;;;; +ABCA;MEETEI MAYEK LETTER THOU;Lo;0;L;;;;;N;;;;; +ABCB;MEETEI MAYEK LETTER WAI;Lo;0;L;;;;;N;;;;; +ABCC;MEETEI MAYEK LETTER YANG;Lo;0;L;;;;;N;;;;; +ABCD;MEETEI MAYEK LETTER HUK;Lo;0;L;;;;;N;;;;; +ABCE;MEETEI MAYEK LETTER UN;Lo;0;L;;;;;N;;;;; +ABCF;MEETEI MAYEK LETTER I;Lo;0;L;;;;;N;;;;; +ABD0;MEETEI MAYEK LETTER PHAM;Lo;0;L;;;;;N;;;;; +ABD1;MEETEI MAYEK LETTER ATIYA;Lo;0;L;;;;;N;;;;; +ABD2;MEETEI MAYEK LETTER GOK;Lo;0;L;;;;;N;;;;; +ABD3;MEETEI MAYEK LETTER JHAM;Lo;0;L;;;;;N;;;;; +ABD4;MEETEI MAYEK LETTER RAI;Lo;0;L;;;;;N;;;;; +ABD5;MEETEI MAYEK LETTER BA;Lo;0;L;;;;;N;;;;; +ABD6;MEETEI MAYEK LETTER JIL;Lo;0;L;;;;;N;;;;; +ABD7;MEETEI MAYEK LETTER DIL;Lo;0;L;;;;;N;;;;; +ABD8;MEETEI MAYEK LETTER GHOU;Lo;0;L;;;;;N;;;;; +ABD9;MEETEI MAYEK LETTER DHOU;Lo;0;L;;;;;N;;;;; +ABDA;MEETEI MAYEK LETTER BHAM;Lo;0;L;;;;;N;;;;; +ABDB;MEETEI MAYEK LETTER KOK LONSUM;Lo;0;L;;;;;N;;;;; +ABDC;MEETEI MAYEK LETTER LAI LONSUM;Lo;0;L;;;;;N;;;;; +ABDD;MEETEI MAYEK LETTER MIT LONSUM;Lo;0;L;;;;;N;;;;; +ABDE;MEETEI MAYEK LETTER PA LONSUM;Lo;0;L;;;;;N;;;;; +ABDF;MEETEI MAYEK LETTER NA LONSUM;Lo;0;L;;;;;N;;;;; +ABE0;MEETEI MAYEK LETTER TIL LONSUM;Lo;0;L;;;;;N;;;;; +ABE1;MEETEI MAYEK LETTER NGOU LONSUM;Lo;0;L;;;;;N;;;;; +ABE2;MEETEI MAYEK LETTER I LONSUM;Lo;0;L;;;;;N;;;;; +ABE3;MEETEI MAYEK VOWEL SIGN ONAP;Mc;0;L;;;;;N;;;;; +ABE4;MEETEI MAYEK VOWEL SIGN INAP;Mc;0;L;;;;;N;;;;; +ABE5;MEETEI MAYEK VOWEL SIGN ANAP;Mn;0;NSM;;;;;N;;;;; +ABE6;MEETEI MAYEK VOWEL SIGN YENAP;Mc;0;L;;;;;N;;;;; +ABE7;MEETEI MAYEK VOWEL SIGN SOUNAP;Mc;0;L;;;;;N;;;;; +ABE8;MEETEI MAYEK VOWEL SIGN UNAP;Mn;0;NSM;;;;;N;;;;; +ABE9;MEETEI MAYEK VOWEL SIGN CHEINAP;Mc;0;L;;;;;N;;;;; +ABEA;MEETEI MAYEK VOWEL SIGN NUNG;Mc;0;L;;;;;N;;;;; +ABEB;MEETEI MAYEK CHEIKHEI;Po;0;L;;;;;N;;;;; +ABEC;MEETEI MAYEK LUM IYEK;Mc;0;L;;;;;N;;;;; +ABED;MEETEI MAYEK APUN IYEK;Mn;9;NSM;;;;;N;;;;; +ABF0;MEETEI MAYEK DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +ABF1;MEETEI MAYEK DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +ABF2;MEETEI MAYEK DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +ABF3;MEETEI MAYEK DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +ABF4;MEETEI MAYEK DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +ABF5;MEETEI MAYEK DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +ABF6;MEETEI MAYEK DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +ABF7;MEETEI MAYEK DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +ABF8;MEETEI MAYEK DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +ABF9;MEETEI MAYEK DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +AC00;;Lo;0;L;;;;;N;;;;; +D7A3;;Lo;0;L;;;;;N;;;;; +D7B0;HANGUL JUNGSEONG O-YEO;Lo;0;L;;;;;N;;;;; +D7B1;HANGUL JUNGSEONG O-O-I;Lo;0;L;;;;;N;;;;; +D7B2;HANGUL JUNGSEONG YO-A;Lo;0;L;;;;;N;;;;; +D7B3;HANGUL JUNGSEONG YO-AE;Lo;0;L;;;;;N;;;;; +D7B4;HANGUL JUNGSEONG YO-EO;Lo;0;L;;;;;N;;;;; +D7B5;HANGUL JUNGSEONG U-YEO;Lo;0;L;;;;;N;;;;; +D7B6;HANGUL JUNGSEONG U-I-I;Lo;0;L;;;;;N;;;;; +D7B7;HANGUL JUNGSEONG YU-AE;Lo;0;L;;;;;N;;;;; +D7B8;HANGUL JUNGSEONG YU-O;Lo;0;L;;;;;N;;;;; +D7B9;HANGUL JUNGSEONG EU-A;Lo;0;L;;;;;N;;;;; +D7BA;HANGUL JUNGSEONG EU-EO;Lo;0;L;;;;;N;;;;; +D7BB;HANGUL JUNGSEONG EU-E;Lo;0;L;;;;;N;;;;; +D7BC;HANGUL JUNGSEONG EU-O;Lo;0;L;;;;;N;;;;; +D7BD;HANGUL JUNGSEONG I-YA-O;Lo;0;L;;;;;N;;;;; +D7BE;HANGUL JUNGSEONG I-YAE;Lo;0;L;;;;;N;;;;; +D7BF;HANGUL JUNGSEONG I-YEO;Lo;0;L;;;;;N;;;;; +D7C0;HANGUL JUNGSEONG I-YE;Lo;0;L;;;;;N;;;;; +D7C1;HANGUL JUNGSEONG I-O-I;Lo;0;L;;;;;N;;;;; +D7C2;HANGUL JUNGSEONG I-YO;Lo;0;L;;;;;N;;;;; +D7C3;HANGUL JUNGSEONG I-YU;Lo;0;L;;;;;N;;;;; +D7C4;HANGUL JUNGSEONG I-I;Lo;0;L;;;;;N;;;;; +D7C5;HANGUL JUNGSEONG ARAEA-A;Lo;0;L;;;;;N;;;;; +D7C6;HANGUL JUNGSEONG ARAEA-E;Lo;0;L;;;;;N;;;;; +D7CB;HANGUL JONGSEONG NIEUN-RIEUL;Lo;0;L;;;;;N;;;;; +D7CC;HANGUL JONGSEONG NIEUN-CHIEUCH;Lo;0;L;;;;;N;;;;; +D7CD;HANGUL JONGSEONG SSANGTIKEUT;Lo;0;L;;;;;N;;;;; +D7CE;HANGUL JONGSEONG SSANGTIKEUT-PIEUP;Lo;0;L;;;;;N;;;;; +D7CF;HANGUL JONGSEONG TIKEUT-PIEUP;Lo;0;L;;;;;N;;;;; +D7D0;HANGUL JONGSEONG TIKEUT-SIOS;Lo;0;L;;;;;N;;;;; +D7D1;HANGUL JONGSEONG TIKEUT-SIOS-KIYEOK;Lo;0;L;;;;;N;;;;; +D7D2;HANGUL JONGSEONG TIKEUT-CIEUC;Lo;0;L;;;;;N;;;;; +D7D3;HANGUL JONGSEONG TIKEUT-CHIEUCH;Lo;0;L;;;;;N;;;;; +D7D4;HANGUL JONGSEONG TIKEUT-THIEUTH;Lo;0;L;;;;;N;;;;; +D7D5;HANGUL JONGSEONG RIEUL-SSANGKIYEOK;Lo;0;L;;;;;N;;;;; +D7D6;HANGUL JONGSEONG RIEUL-KIYEOK-HIEUH;Lo;0;L;;;;;N;;;;; +D7D7;HANGUL JONGSEONG SSANGRIEUL-KHIEUKH;Lo;0;L;;;;;N;;;;; +D7D8;HANGUL JONGSEONG RIEUL-MIEUM-HIEUH;Lo;0;L;;;;;N;;;;; +D7D9;HANGUL JONGSEONG RIEUL-PIEUP-TIKEUT;Lo;0;L;;;;;N;;;;; +D7DA;HANGUL JONGSEONG RIEUL-PIEUP-PHIEUPH;Lo;0;L;;;;;N;;;;; +D7DB;HANGUL JONGSEONG RIEUL-YESIEUNG;Lo;0;L;;;;;N;;;;; +D7DC;HANGUL JONGSEONG RIEUL-YEORINHIEUH-HIEUH;Lo;0;L;;;;;N;;;;; +D7DD;HANGUL JONGSEONG KAPYEOUNRIEUL;Lo;0;L;;;;;N;;;;; +D7DE;HANGUL JONGSEONG MIEUM-NIEUN;Lo;0;L;;;;;N;;;;; +D7DF;HANGUL JONGSEONG MIEUM-SSANGNIEUN;Lo;0;L;;;;;N;;;;; +D7E0;HANGUL JONGSEONG SSANGMIEUM;Lo;0;L;;;;;N;;;;; +D7E1;HANGUL JONGSEONG MIEUM-PIEUP-SIOS;Lo;0;L;;;;;N;;;;; +D7E2;HANGUL JONGSEONG MIEUM-CIEUC;Lo;0;L;;;;;N;;;;; +D7E3;HANGUL JONGSEONG PIEUP-TIKEUT;Lo;0;L;;;;;N;;;;; +D7E4;HANGUL JONGSEONG PIEUP-RIEUL-PHIEUPH;Lo;0;L;;;;;N;;;;; +D7E5;HANGUL JONGSEONG PIEUP-MIEUM;Lo;0;L;;;;;N;;;;; +D7E6;HANGUL JONGSEONG SSANGPIEUP;Lo;0;L;;;;;N;;;;; +D7E7;HANGUL JONGSEONG PIEUP-SIOS-TIKEUT;Lo;0;L;;;;;N;;;;; +D7E8;HANGUL JONGSEONG PIEUP-CIEUC;Lo;0;L;;;;;N;;;;; +D7E9;HANGUL JONGSEONG PIEUP-CHIEUCH;Lo;0;L;;;;;N;;;;; +D7EA;HANGUL JONGSEONG SIOS-MIEUM;Lo;0;L;;;;;N;;;;; +D7EB;HANGUL JONGSEONG SIOS-KAPYEOUNPIEUP;Lo;0;L;;;;;N;;;;; +D7EC;HANGUL JONGSEONG SSANGSIOS-KIYEOK;Lo;0;L;;;;;N;;;;; +D7ED;HANGUL JONGSEONG SSANGSIOS-TIKEUT;Lo;0;L;;;;;N;;;;; +D7EE;HANGUL JONGSEONG SIOS-PANSIOS;Lo;0;L;;;;;N;;;;; +D7EF;HANGUL JONGSEONG SIOS-CIEUC;Lo;0;L;;;;;N;;;;; +D7F0;HANGUL JONGSEONG SIOS-CHIEUCH;Lo;0;L;;;;;N;;;;; +D7F1;HANGUL JONGSEONG SIOS-THIEUTH;Lo;0;L;;;;;N;;;;; +D7F2;HANGUL JONGSEONG SIOS-HIEUH;Lo;0;L;;;;;N;;;;; +D7F3;HANGUL JONGSEONG PANSIOS-PIEUP;Lo;0;L;;;;;N;;;;; +D7F4;HANGUL JONGSEONG PANSIOS-KAPYEOUNPIEUP;Lo;0;L;;;;;N;;;;; +D7F5;HANGUL JONGSEONG YESIEUNG-MIEUM;Lo;0;L;;;;;N;;;;; +D7F6;HANGUL JONGSEONG YESIEUNG-HIEUH;Lo;0;L;;;;;N;;;;; +D7F7;HANGUL JONGSEONG CIEUC-PIEUP;Lo;0;L;;;;;N;;;;; +D7F8;HANGUL JONGSEONG CIEUC-SSANGPIEUP;Lo;0;L;;;;;N;;;;; +D7F9;HANGUL JONGSEONG SSANGCIEUC;Lo;0;L;;;;;N;;;;; +D7FA;HANGUL JONGSEONG PHIEUPH-SIOS;Lo;0;L;;;;;N;;;;; +D7FB;HANGUL JONGSEONG PHIEUPH-THIEUTH;Lo;0;L;;;;;N;;;;; +D800;;Cs;0;L;;;;;N;;;;; +DB7F;;Cs;0;L;;;;;N;;;;; +DB80;;Cs;0;L;;;;;N;;;;; +DBFF;;Cs;0;L;;;;;N;;;;; +DC00;;Cs;0;L;;;;;N;;;;; +DFFF;;Cs;0;L;;;;;N;;;;; +E000;;Co;0;L;;;;;N;;;;; +F8FF;;Co;0;L;;;;;N;;;;; +F900;CJK COMPATIBILITY IDEOGRAPH-F900;Lo;0;L;8C48;;;;N;;;;; +F901;CJK COMPATIBILITY IDEOGRAPH-F901;Lo;0;L;66F4;;;;N;;;;; +F902;CJK COMPATIBILITY IDEOGRAPH-F902;Lo;0;L;8ECA;;;;N;;;;; +F903;CJK COMPATIBILITY IDEOGRAPH-F903;Lo;0;L;8CC8;;;;N;;;;; +F904;CJK COMPATIBILITY IDEOGRAPH-F904;Lo;0;L;6ED1;;;;N;;;;; +F905;CJK COMPATIBILITY IDEOGRAPH-F905;Lo;0;L;4E32;;;;N;;;;; +F906;CJK COMPATIBILITY IDEOGRAPH-F906;Lo;0;L;53E5;;;;N;;;;; +F907;CJK COMPATIBILITY IDEOGRAPH-F907;Lo;0;L;9F9C;;;;N;;;;; +F908;CJK COMPATIBILITY IDEOGRAPH-F908;Lo;0;L;9F9C;;;;N;;;;; +F909;CJK COMPATIBILITY IDEOGRAPH-F909;Lo;0;L;5951;;;;N;;;;; +F90A;CJK COMPATIBILITY IDEOGRAPH-F90A;Lo;0;L;91D1;;;;N;;;;; +F90B;CJK COMPATIBILITY IDEOGRAPH-F90B;Lo;0;L;5587;;;;N;;;;; +F90C;CJK COMPATIBILITY IDEOGRAPH-F90C;Lo;0;L;5948;;;;N;;;;; +F90D;CJK COMPATIBILITY IDEOGRAPH-F90D;Lo;0;L;61F6;;;;N;;;;; +F90E;CJK COMPATIBILITY IDEOGRAPH-F90E;Lo;0;L;7669;;;;N;;;;; +F90F;CJK COMPATIBILITY IDEOGRAPH-F90F;Lo;0;L;7F85;;;;N;;;;; +F910;CJK COMPATIBILITY IDEOGRAPH-F910;Lo;0;L;863F;;;;N;;;;; +F911;CJK COMPATIBILITY IDEOGRAPH-F911;Lo;0;L;87BA;;;;N;;;;; +F912;CJK COMPATIBILITY IDEOGRAPH-F912;Lo;0;L;88F8;;;;N;;;;; +F913;CJK COMPATIBILITY IDEOGRAPH-F913;Lo;0;L;908F;;;;N;;;;; +F914;CJK COMPATIBILITY IDEOGRAPH-F914;Lo;0;L;6A02;;;;N;;;;; +F915;CJK COMPATIBILITY IDEOGRAPH-F915;Lo;0;L;6D1B;;;;N;;;;; +F916;CJK COMPATIBILITY IDEOGRAPH-F916;Lo;0;L;70D9;;;;N;;;;; +F917;CJK COMPATIBILITY IDEOGRAPH-F917;Lo;0;L;73DE;;;;N;;;;; +F918;CJK COMPATIBILITY IDEOGRAPH-F918;Lo;0;L;843D;;;;N;;;;; +F919;CJK COMPATIBILITY IDEOGRAPH-F919;Lo;0;L;916A;;;;N;;;;; +F91A;CJK COMPATIBILITY IDEOGRAPH-F91A;Lo;0;L;99F1;;;;N;;;;; +F91B;CJK COMPATIBILITY IDEOGRAPH-F91B;Lo;0;L;4E82;;;;N;;;;; +F91C;CJK COMPATIBILITY IDEOGRAPH-F91C;Lo;0;L;5375;;;;N;;;;; +F91D;CJK COMPATIBILITY IDEOGRAPH-F91D;Lo;0;L;6B04;;;;N;;;;; +F91E;CJK COMPATIBILITY IDEOGRAPH-F91E;Lo;0;L;721B;;;;N;;;;; +F91F;CJK COMPATIBILITY IDEOGRAPH-F91F;Lo;0;L;862D;;;;N;;;;; +F920;CJK COMPATIBILITY IDEOGRAPH-F920;Lo;0;L;9E1E;;;;N;;;;; +F921;CJK COMPATIBILITY IDEOGRAPH-F921;Lo;0;L;5D50;;;;N;;;;; +F922;CJK COMPATIBILITY IDEOGRAPH-F922;Lo;0;L;6FEB;;;;N;;;;; +F923;CJK COMPATIBILITY IDEOGRAPH-F923;Lo;0;L;85CD;;;;N;;;;; +F924;CJK COMPATIBILITY IDEOGRAPH-F924;Lo;0;L;8964;;;;N;;;;; +F925;CJK COMPATIBILITY IDEOGRAPH-F925;Lo;0;L;62C9;;;;N;;;;; +F926;CJK COMPATIBILITY IDEOGRAPH-F926;Lo;0;L;81D8;;;;N;;;;; +F927;CJK COMPATIBILITY IDEOGRAPH-F927;Lo;0;L;881F;;;;N;;;;; +F928;CJK COMPATIBILITY IDEOGRAPH-F928;Lo;0;L;5ECA;;;;N;;;;; +F929;CJK COMPATIBILITY IDEOGRAPH-F929;Lo;0;L;6717;;;;N;;;;; +F92A;CJK COMPATIBILITY IDEOGRAPH-F92A;Lo;0;L;6D6A;;;;N;;;;; +F92B;CJK COMPATIBILITY IDEOGRAPH-F92B;Lo;0;L;72FC;;;;N;;;;; +F92C;CJK COMPATIBILITY IDEOGRAPH-F92C;Lo;0;L;90CE;;;;N;;;;; +F92D;CJK COMPATIBILITY IDEOGRAPH-F92D;Lo;0;L;4F86;;;;N;;;;; +F92E;CJK COMPATIBILITY IDEOGRAPH-F92E;Lo;0;L;51B7;;;;N;;;;; +F92F;CJK COMPATIBILITY IDEOGRAPH-F92F;Lo;0;L;52DE;;;;N;;;;; +F930;CJK COMPATIBILITY IDEOGRAPH-F930;Lo;0;L;64C4;;;;N;;;;; +F931;CJK COMPATIBILITY IDEOGRAPH-F931;Lo;0;L;6AD3;;;;N;;;;; +F932;CJK COMPATIBILITY IDEOGRAPH-F932;Lo;0;L;7210;;;;N;;;;; +F933;CJK COMPATIBILITY IDEOGRAPH-F933;Lo;0;L;76E7;;;;N;;;;; +F934;CJK COMPATIBILITY IDEOGRAPH-F934;Lo;0;L;8001;;;;N;;;;; +F935;CJK COMPATIBILITY IDEOGRAPH-F935;Lo;0;L;8606;;;;N;;;;; +F936;CJK COMPATIBILITY IDEOGRAPH-F936;Lo;0;L;865C;;;;N;;;;; +F937;CJK COMPATIBILITY IDEOGRAPH-F937;Lo;0;L;8DEF;;;;N;;;;; +F938;CJK COMPATIBILITY IDEOGRAPH-F938;Lo;0;L;9732;;;;N;;;;; +F939;CJK COMPATIBILITY IDEOGRAPH-F939;Lo;0;L;9B6F;;;;N;;;;; +F93A;CJK COMPATIBILITY IDEOGRAPH-F93A;Lo;0;L;9DFA;;;;N;;;;; +F93B;CJK COMPATIBILITY IDEOGRAPH-F93B;Lo;0;L;788C;;;;N;;;;; +F93C;CJK COMPATIBILITY IDEOGRAPH-F93C;Lo;0;L;797F;;;;N;;;;; +F93D;CJK COMPATIBILITY IDEOGRAPH-F93D;Lo;0;L;7DA0;;;;N;;;;; +F93E;CJK COMPATIBILITY IDEOGRAPH-F93E;Lo;0;L;83C9;;;;N;;;;; +F93F;CJK COMPATIBILITY IDEOGRAPH-F93F;Lo;0;L;9304;;;;N;;;;; +F940;CJK COMPATIBILITY IDEOGRAPH-F940;Lo;0;L;9E7F;;;;N;;;;; +F941;CJK COMPATIBILITY IDEOGRAPH-F941;Lo;0;L;8AD6;;;;N;;;;; +F942;CJK COMPATIBILITY IDEOGRAPH-F942;Lo;0;L;58DF;;;;N;;;;; +F943;CJK COMPATIBILITY IDEOGRAPH-F943;Lo;0;L;5F04;;;;N;;;;; +F944;CJK COMPATIBILITY IDEOGRAPH-F944;Lo;0;L;7C60;;;;N;;;;; +F945;CJK COMPATIBILITY IDEOGRAPH-F945;Lo;0;L;807E;;;;N;;;;; +F946;CJK COMPATIBILITY IDEOGRAPH-F946;Lo;0;L;7262;;;;N;;;;; +F947;CJK COMPATIBILITY IDEOGRAPH-F947;Lo;0;L;78CA;;;;N;;;;; +F948;CJK COMPATIBILITY IDEOGRAPH-F948;Lo;0;L;8CC2;;;;N;;;;; +F949;CJK COMPATIBILITY IDEOGRAPH-F949;Lo;0;L;96F7;;;;N;;;;; +F94A;CJK COMPATIBILITY IDEOGRAPH-F94A;Lo;0;L;58D8;;;;N;;;;; +F94B;CJK COMPATIBILITY IDEOGRAPH-F94B;Lo;0;L;5C62;;;;N;;;;; +F94C;CJK COMPATIBILITY IDEOGRAPH-F94C;Lo;0;L;6A13;;;;N;;;;; +F94D;CJK COMPATIBILITY IDEOGRAPH-F94D;Lo;0;L;6DDA;;;;N;;;;; +F94E;CJK COMPATIBILITY IDEOGRAPH-F94E;Lo;0;L;6F0F;;;;N;;;;; +F94F;CJK COMPATIBILITY IDEOGRAPH-F94F;Lo;0;L;7D2F;;;;N;;;;; +F950;CJK COMPATIBILITY IDEOGRAPH-F950;Lo;0;L;7E37;;;;N;;;;; +F951;CJK COMPATIBILITY IDEOGRAPH-F951;Lo;0;L;964B;;;;N;;;;; +F952;CJK COMPATIBILITY IDEOGRAPH-F952;Lo;0;L;52D2;;;;N;;;;; +F953;CJK COMPATIBILITY IDEOGRAPH-F953;Lo;0;L;808B;;;;N;;;;; +F954;CJK COMPATIBILITY IDEOGRAPH-F954;Lo;0;L;51DC;;;;N;;;;; +F955;CJK COMPATIBILITY IDEOGRAPH-F955;Lo;0;L;51CC;;;;N;;;;; +F956;CJK COMPATIBILITY IDEOGRAPH-F956;Lo;0;L;7A1C;;;;N;;;;; +F957;CJK COMPATIBILITY IDEOGRAPH-F957;Lo;0;L;7DBE;;;;N;;;;; +F958;CJK COMPATIBILITY IDEOGRAPH-F958;Lo;0;L;83F1;;;;N;;;;; +F959;CJK COMPATIBILITY IDEOGRAPH-F959;Lo;0;L;9675;;;;N;;;;; +F95A;CJK COMPATIBILITY IDEOGRAPH-F95A;Lo;0;L;8B80;;;;N;;;;; +F95B;CJK COMPATIBILITY IDEOGRAPH-F95B;Lo;0;L;62CF;;;;N;;;;; +F95C;CJK COMPATIBILITY IDEOGRAPH-F95C;Lo;0;L;6A02;;;;N;;;;; +F95D;CJK COMPATIBILITY IDEOGRAPH-F95D;Lo;0;L;8AFE;;;;N;;;;; +F95E;CJK COMPATIBILITY IDEOGRAPH-F95E;Lo;0;L;4E39;;;;N;;;;; +F95F;CJK COMPATIBILITY IDEOGRAPH-F95F;Lo;0;L;5BE7;;;;N;;;;; +F960;CJK COMPATIBILITY IDEOGRAPH-F960;Lo;0;L;6012;;;;N;;;;; +F961;CJK COMPATIBILITY IDEOGRAPH-F961;Lo;0;L;7387;;;;N;;;;; +F962;CJK COMPATIBILITY IDEOGRAPH-F962;Lo;0;L;7570;;;;N;;;;; +F963;CJK COMPATIBILITY IDEOGRAPH-F963;Lo;0;L;5317;;;;N;;;;; +F964;CJK COMPATIBILITY IDEOGRAPH-F964;Lo;0;L;78FB;;;;N;;;;; +F965;CJK COMPATIBILITY IDEOGRAPH-F965;Lo;0;L;4FBF;;;;N;;;;; +F966;CJK COMPATIBILITY IDEOGRAPH-F966;Lo;0;L;5FA9;;;;N;;;;; +F967;CJK COMPATIBILITY IDEOGRAPH-F967;Lo;0;L;4E0D;;;;N;;;;; +F968;CJK COMPATIBILITY IDEOGRAPH-F968;Lo;0;L;6CCC;;;;N;;;;; +F969;CJK COMPATIBILITY IDEOGRAPH-F969;Lo;0;L;6578;;;;N;;;;; +F96A;CJK COMPATIBILITY IDEOGRAPH-F96A;Lo;0;L;7D22;;;;N;;;;; +F96B;CJK COMPATIBILITY IDEOGRAPH-F96B;Lo;0;L;53C3;;;3;N;;;;; +F96C;CJK COMPATIBILITY IDEOGRAPH-F96C;Lo;0;L;585E;;;;N;;;;; +F96D;CJK COMPATIBILITY IDEOGRAPH-F96D;Lo;0;L;7701;;;;N;;;;; +F96E;CJK COMPATIBILITY IDEOGRAPH-F96E;Lo;0;L;8449;;;;N;;;;; +F96F;CJK COMPATIBILITY IDEOGRAPH-F96F;Lo;0;L;8AAA;;;;N;;;;; +F970;CJK COMPATIBILITY IDEOGRAPH-F970;Lo;0;L;6BBA;;;;N;;;;; +F971;CJK COMPATIBILITY IDEOGRAPH-F971;Lo;0;L;8FB0;;;;N;;;;; +F972;CJK COMPATIBILITY IDEOGRAPH-F972;Lo;0;L;6C88;;;;N;;;;; +F973;CJK COMPATIBILITY IDEOGRAPH-F973;Lo;0;L;62FE;;;10;N;;;;; +F974;CJK COMPATIBILITY IDEOGRAPH-F974;Lo;0;L;82E5;;;;N;;;;; +F975;CJK COMPATIBILITY IDEOGRAPH-F975;Lo;0;L;63A0;;;;N;;;;; +F976;CJK COMPATIBILITY IDEOGRAPH-F976;Lo;0;L;7565;;;;N;;;;; +F977;CJK COMPATIBILITY IDEOGRAPH-F977;Lo;0;L;4EAE;;;;N;;;;; +F978;CJK COMPATIBILITY IDEOGRAPH-F978;Lo;0;L;5169;;;2;N;;;;; +F979;CJK COMPATIBILITY IDEOGRAPH-F979;Lo;0;L;51C9;;;;N;;;;; +F97A;CJK COMPATIBILITY IDEOGRAPH-F97A;Lo;0;L;6881;;;;N;;;;; +F97B;CJK COMPATIBILITY IDEOGRAPH-F97B;Lo;0;L;7CE7;;;;N;;;;; +F97C;CJK COMPATIBILITY IDEOGRAPH-F97C;Lo;0;L;826F;;;;N;;;;; +F97D;CJK COMPATIBILITY IDEOGRAPH-F97D;Lo;0;L;8AD2;;;;N;;;;; +F97E;CJK COMPATIBILITY IDEOGRAPH-F97E;Lo;0;L;91CF;;;;N;;;;; +F97F;CJK COMPATIBILITY IDEOGRAPH-F97F;Lo;0;L;52F5;;;;N;;;;; +F980;CJK COMPATIBILITY IDEOGRAPH-F980;Lo;0;L;5442;;;;N;;;;; +F981;CJK COMPATIBILITY IDEOGRAPH-F981;Lo;0;L;5973;;;;N;;;;; +F982;CJK COMPATIBILITY IDEOGRAPH-F982;Lo;0;L;5EEC;;;;N;;;;; +F983;CJK COMPATIBILITY IDEOGRAPH-F983;Lo;0;L;65C5;;;;N;;;;; +F984;CJK COMPATIBILITY IDEOGRAPH-F984;Lo;0;L;6FFE;;;;N;;;;; +F985;CJK COMPATIBILITY IDEOGRAPH-F985;Lo;0;L;792A;;;;N;;;;; +F986;CJK COMPATIBILITY IDEOGRAPH-F986;Lo;0;L;95AD;;;;N;;;;; +F987;CJK COMPATIBILITY IDEOGRAPH-F987;Lo;0;L;9A6A;;;;N;;;;; +F988;CJK COMPATIBILITY IDEOGRAPH-F988;Lo;0;L;9E97;;;;N;;;;; +F989;CJK COMPATIBILITY IDEOGRAPH-F989;Lo;0;L;9ECE;;;;N;;;;; +F98A;CJK COMPATIBILITY IDEOGRAPH-F98A;Lo;0;L;529B;;;;N;;;;; +F98B;CJK COMPATIBILITY IDEOGRAPH-F98B;Lo;0;L;66C6;;;;N;;;;; +F98C;CJK COMPATIBILITY IDEOGRAPH-F98C;Lo;0;L;6B77;;;;N;;;;; +F98D;CJK COMPATIBILITY IDEOGRAPH-F98D;Lo;0;L;8F62;;;;N;;;;; +F98E;CJK COMPATIBILITY IDEOGRAPH-F98E;Lo;0;L;5E74;;;;N;;;;; +F98F;CJK COMPATIBILITY IDEOGRAPH-F98F;Lo;0;L;6190;;;;N;;;;; +F990;CJK COMPATIBILITY IDEOGRAPH-F990;Lo;0;L;6200;;;;N;;;;; +F991;CJK COMPATIBILITY IDEOGRAPH-F991;Lo;0;L;649A;;;;N;;;;; +F992;CJK COMPATIBILITY IDEOGRAPH-F992;Lo;0;L;6F23;;;;N;;;;; +F993;CJK COMPATIBILITY IDEOGRAPH-F993;Lo;0;L;7149;;;;N;;;;; +F994;CJK COMPATIBILITY IDEOGRAPH-F994;Lo;0;L;7489;;;;N;;;;; +F995;CJK COMPATIBILITY IDEOGRAPH-F995;Lo;0;L;79CA;;;;N;;;;; +F996;CJK COMPATIBILITY IDEOGRAPH-F996;Lo;0;L;7DF4;;;;N;;;;; +F997;CJK COMPATIBILITY IDEOGRAPH-F997;Lo;0;L;806F;;;;N;;;;; +F998;CJK COMPATIBILITY IDEOGRAPH-F998;Lo;0;L;8F26;;;;N;;;;; +F999;CJK COMPATIBILITY IDEOGRAPH-F999;Lo;0;L;84EE;;;;N;;;;; +F99A;CJK COMPATIBILITY IDEOGRAPH-F99A;Lo;0;L;9023;;;;N;;;;; +F99B;CJK COMPATIBILITY IDEOGRAPH-F99B;Lo;0;L;934A;;;;N;;;;; +F99C;CJK COMPATIBILITY IDEOGRAPH-F99C;Lo;0;L;5217;;;;N;;;;; +F99D;CJK COMPATIBILITY IDEOGRAPH-F99D;Lo;0;L;52A3;;;;N;;;;; +F99E;CJK COMPATIBILITY IDEOGRAPH-F99E;Lo;0;L;54BD;;;;N;;;;; +F99F;CJK COMPATIBILITY IDEOGRAPH-F99F;Lo;0;L;70C8;;;;N;;;;; +F9A0;CJK COMPATIBILITY IDEOGRAPH-F9A0;Lo;0;L;88C2;;;;N;;;;; +F9A1;CJK COMPATIBILITY IDEOGRAPH-F9A1;Lo;0;L;8AAA;;;;N;;;;; +F9A2;CJK COMPATIBILITY IDEOGRAPH-F9A2;Lo;0;L;5EC9;;;;N;;;;; +F9A3;CJK COMPATIBILITY IDEOGRAPH-F9A3;Lo;0;L;5FF5;;;;N;;;;; +F9A4;CJK COMPATIBILITY IDEOGRAPH-F9A4;Lo;0;L;637B;;;;N;;;;; +F9A5;CJK COMPATIBILITY IDEOGRAPH-F9A5;Lo;0;L;6BAE;;;;N;;;;; +F9A6;CJK COMPATIBILITY IDEOGRAPH-F9A6;Lo;0;L;7C3E;;;;N;;;;; +F9A7;CJK COMPATIBILITY IDEOGRAPH-F9A7;Lo;0;L;7375;;;;N;;;;; +F9A8;CJK COMPATIBILITY IDEOGRAPH-F9A8;Lo;0;L;4EE4;;;;N;;;;; +F9A9;CJK COMPATIBILITY IDEOGRAPH-F9A9;Lo;0;L;56F9;;;;N;;;;; +F9AA;CJK COMPATIBILITY IDEOGRAPH-F9AA;Lo;0;L;5BE7;;;;N;;;;; +F9AB;CJK COMPATIBILITY IDEOGRAPH-F9AB;Lo;0;L;5DBA;;;;N;;;;; +F9AC;CJK COMPATIBILITY IDEOGRAPH-F9AC;Lo;0;L;601C;;;;N;;;;; +F9AD;CJK COMPATIBILITY IDEOGRAPH-F9AD;Lo;0;L;73B2;;;;N;;;;; +F9AE;CJK COMPATIBILITY IDEOGRAPH-F9AE;Lo;0;L;7469;;;;N;;;;; +F9AF;CJK COMPATIBILITY IDEOGRAPH-F9AF;Lo;0;L;7F9A;;;;N;;;;; +F9B0;CJK COMPATIBILITY IDEOGRAPH-F9B0;Lo;0;L;8046;;;;N;;;;; +F9B1;CJK COMPATIBILITY IDEOGRAPH-F9B1;Lo;0;L;9234;;;;N;;;;; +F9B2;CJK COMPATIBILITY IDEOGRAPH-F9B2;Lo;0;L;96F6;;;0;N;;;;; +F9B3;CJK COMPATIBILITY IDEOGRAPH-F9B3;Lo;0;L;9748;;;;N;;;;; +F9B4;CJK COMPATIBILITY IDEOGRAPH-F9B4;Lo;0;L;9818;;;;N;;;;; +F9B5;CJK COMPATIBILITY IDEOGRAPH-F9B5;Lo;0;L;4F8B;;;;N;;;;; +F9B6;CJK COMPATIBILITY IDEOGRAPH-F9B6;Lo;0;L;79AE;;;;N;;;;; +F9B7;CJK COMPATIBILITY IDEOGRAPH-F9B7;Lo;0;L;91B4;;;;N;;;;; +F9B8;CJK COMPATIBILITY IDEOGRAPH-F9B8;Lo;0;L;96B8;;;;N;;;;; +F9B9;CJK COMPATIBILITY IDEOGRAPH-F9B9;Lo;0;L;60E1;;;;N;;;;; +F9BA;CJK COMPATIBILITY IDEOGRAPH-F9BA;Lo;0;L;4E86;;;;N;;;;; +F9BB;CJK COMPATIBILITY IDEOGRAPH-F9BB;Lo;0;L;50DA;;;;N;;;;; +F9BC;CJK COMPATIBILITY IDEOGRAPH-F9BC;Lo;0;L;5BEE;;;;N;;;;; +F9BD;CJK COMPATIBILITY IDEOGRAPH-F9BD;Lo;0;L;5C3F;;;;N;;;;; +F9BE;CJK COMPATIBILITY IDEOGRAPH-F9BE;Lo;0;L;6599;;;;N;;;;; +F9BF;CJK COMPATIBILITY IDEOGRAPH-F9BF;Lo;0;L;6A02;;;;N;;;;; +F9C0;CJK COMPATIBILITY IDEOGRAPH-F9C0;Lo;0;L;71CE;;;;N;;;;; +F9C1;CJK COMPATIBILITY IDEOGRAPH-F9C1;Lo;0;L;7642;;;;N;;;;; +F9C2;CJK COMPATIBILITY IDEOGRAPH-F9C2;Lo;0;L;84FC;;;;N;;;;; +F9C3;CJK COMPATIBILITY IDEOGRAPH-F9C3;Lo;0;L;907C;;;;N;;;;; +F9C4;CJK COMPATIBILITY IDEOGRAPH-F9C4;Lo;0;L;9F8D;;;;N;;;;; +F9C5;CJK COMPATIBILITY IDEOGRAPH-F9C5;Lo;0;L;6688;;;;N;;;;; +F9C6;CJK COMPATIBILITY IDEOGRAPH-F9C6;Lo;0;L;962E;;;;N;;;;; +F9C7;CJK COMPATIBILITY IDEOGRAPH-F9C7;Lo;0;L;5289;;;;N;;;;; +F9C8;CJK COMPATIBILITY IDEOGRAPH-F9C8;Lo;0;L;677B;;;;N;;;;; +F9C9;CJK COMPATIBILITY IDEOGRAPH-F9C9;Lo;0;L;67F3;;;;N;;;;; +F9CA;CJK COMPATIBILITY IDEOGRAPH-F9CA;Lo;0;L;6D41;;;;N;;;;; +F9CB;CJK COMPATIBILITY IDEOGRAPH-F9CB;Lo;0;L;6E9C;;;;N;;;;; +F9CC;CJK COMPATIBILITY IDEOGRAPH-F9CC;Lo;0;L;7409;;;;N;;;;; +F9CD;CJK COMPATIBILITY IDEOGRAPH-F9CD;Lo;0;L;7559;;;;N;;;;; +F9CE;CJK COMPATIBILITY IDEOGRAPH-F9CE;Lo;0;L;786B;;;;N;;;;; +F9CF;CJK COMPATIBILITY IDEOGRAPH-F9CF;Lo;0;L;7D10;;;;N;;;;; +F9D0;CJK COMPATIBILITY IDEOGRAPH-F9D0;Lo;0;L;985E;;;;N;;;;; +F9D1;CJK COMPATIBILITY IDEOGRAPH-F9D1;Lo;0;L;516D;;;6;N;;;;; +F9D2;CJK COMPATIBILITY IDEOGRAPH-F9D2;Lo;0;L;622E;;;;N;;;;; +F9D3;CJK COMPATIBILITY IDEOGRAPH-F9D3;Lo;0;L;9678;;;6;N;;;;; +F9D4;CJK COMPATIBILITY IDEOGRAPH-F9D4;Lo;0;L;502B;;;;N;;;;; +F9D5;CJK COMPATIBILITY IDEOGRAPH-F9D5;Lo;0;L;5D19;;;;N;;;;; +F9D6;CJK COMPATIBILITY IDEOGRAPH-F9D6;Lo;0;L;6DEA;;;;N;;;;; +F9D7;CJK COMPATIBILITY IDEOGRAPH-F9D7;Lo;0;L;8F2A;;;;N;;;;; +F9D8;CJK COMPATIBILITY IDEOGRAPH-F9D8;Lo;0;L;5F8B;;;;N;;;;; +F9D9;CJK COMPATIBILITY IDEOGRAPH-F9D9;Lo;0;L;6144;;;;N;;;;; +F9DA;CJK COMPATIBILITY IDEOGRAPH-F9DA;Lo;0;L;6817;;;;N;;;;; +F9DB;CJK COMPATIBILITY IDEOGRAPH-F9DB;Lo;0;L;7387;;;;N;;;;; +F9DC;CJK COMPATIBILITY IDEOGRAPH-F9DC;Lo;0;L;9686;;;;N;;;;; +F9DD;CJK COMPATIBILITY IDEOGRAPH-F9DD;Lo;0;L;5229;;;;N;;;;; +F9DE;CJK COMPATIBILITY IDEOGRAPH-F9DE;Lo;0;L;540F;;;;N;;;;; +F9DF;CJK COMPATIBILITY IDEOGRAPH-F9DF;Lo;0;L;5C65;;;;N;;;;; +F9E0;CJK COMPATIBILITY IDEOGRAPH-F9E0;Lo;0;L;6613;;;;N;;;;; +F9E1;CJK COMPATIBILITY IDEOGRAPH-F9E1;Lo;0;L;674E;;;;N;;;;; +F9E2;CJK COMPATIBILITY IDEOGRAPH-F9E2;Lo;0;L;68A8;;;;N;;;;; +F9E3;CJK COMPATIBILITY IDEOGRAPH-F9E3;Lo;0;L;6CE5;;;;N;;;;; +F9E4;CJK COMPATIBILITY IDEOGRAPH-F9E4;Lo;0;L;7406;;;;N;;;;; +F9E5;CJK COMPATIBILITY IDEOGRAPH-F9E5;Lo;0;L;75E2;;;;N;;;;; +F9E6;CJK COMPATIBILITY IDEOGRAPH-F9E6;Lo;0;L;7F79;;;;N;;;;; +F9E7;CJK COMPATIBILITY IDEOGRAPH-F9E7;Lo;0;L;88CF;;;;N;;;;; +F9E8;CJK COMPATIBILITY IDEOGRAPH-F9E8;Lo;0;L;88E1;;;;N;;;;; +F9E9;CJK COMPATIBILITY IDEOGRAPH-F9E9;Lo;0;L;91CC;;;;N;;;;; +F9EA;CJK COMPATIBILITY IDEOGRAPH-F9EA;Lo;0;L;96E2;;;;N;;;;; +F9EB;CJK COMPATIBILITY IDEOGRAPH-F9EB;Lo;0;L;533F;;;;N;;;;; +F9EC;CJK COMPATIBILITY IDEOGRAPH-F9EC;Lo;0;L;6EBA;;;;N;;;;; +F9ED;CJK COMPATIBILITY IDEOGRAPH-F9ED;Lo;0;L;541D;;;;N;;;;; +F9EE;CJK COMPATIBILITY IDEOGRAPH-F9EE;Lo;0;L;71D0;;;;N;;;;; +F9EF;CJK COMPATIBILITY IDEOGRAPH-F9EF;Lo;0;L;7498;;;;N;;;;; +F9F0;CJK COMPATIBILITY IDEOGRAPH-F9F0;Lo;0;L;85FA;;;;N;;;;; +F9F1;CJK COMPATIBILITY IDEOGRAPH-F9F1;Lo;0;L;96A3;;;;N;;;;; +F9F2;CJK COMPATIBILITY IDEOGRAPH-F9F2;Lo;0;L;9C57;;;;N;;;;; +F9F3;CJK COMPATIBILITY IDEOGRAPH-F9F3;Lo;0;L;9E9F;;;;N;;;;; +F9F4;CJK COMPATIBILITY IDEOGRAPH-F9F4;Lo;0;L;6797;;;;N;;;;; +F9F5;CJK COMPATIBILITY IDEOGRAPH-F9F5;Lo;0;L;6DCB;;;;N;;;;; +F9F6;CJK COMPATIBILITY IDEOGRAPH-F9F6;Lo;0;L;81E8;;;;N;;;;; +F9F7;CJK COMPATIBILITY IDEOGRAPH-F9F7;Lo;0;L;7ACB;;;;N;;;;; +F9F8;CJK COMPATIBILITY IDEOGRAPH-F9F8;Lo;0;L;7B20;;;;N;;;;; +F9F9;CJK COMPATIBILITY IDEOGRAPH-F9F9;Lo;0;L;7C92;;;;N;;;;; +F9FA;CJK COMPATIBILITY IDEOGRAPH-F9FA;Lo;0;L;72C0;;;;N;;;;; +F9FB;CJK COMPATIBILITY IDEOGRAPH-F9FB;Lo;0;L;7099;;;;N;;;;; +F9FC;CJK COMPATIBILITY IDEOGRAPH-F9FC;Lo;0;L;8B58;;;;N;;;;; +F9FD;CJK COMPATIBILITY IDEOGRAPH-F9FD;Lo;0;L;4EC0;;;10;N;;;;; +F9FE;CJK COMPATIBILITY IDEOGRAPH-F9FE;Lo;0;L;8336;;;;N;;;;; +F9FF;CJK COMPATIBILITY IDEOGRAPH-F9FF;Lo;0;L;523A;;;;N;;;;; +FA00;CJK COMPATIBILITY IDEOGRAPH-FA00;Lo;0;L;5207;;;;N;;;;; +FA01;CJK COMPATIBILITY IDEOGRAPH-FA01;Lo;0;L;5EA6;;;;N;;;;; +FA02;CJK COMPATIBILITY IDEOGRAPH-FA02;Lo;0;L;62D3;;;;N;;;;; +FA03;CJK COMPATIBILITY IDEOGRAPH-FA03;Lo;0;L;7CD6;;;;N;;;;; +FA04;CJK COMPATIBILITY IDEOGRAPH-FA04;Lo;0;L;5B85;;;;N;;;;; +FA05;CJK COMPATIBILITY IDEOGRAPH-FA05;Lo;0;L;6D1E;;;;N;;;;; +FA06;CJK COMPATIBILITY IDEOGRAPH-FA06;Lo;0;L;66B4;;;;N;;;;; +FA07;CJK COMPATIBILITY IDEOGRAPH-FA07;Lo;0;L;8F3B;;;;N;;;;; +FA08;CJK COMPATIBILITY IDEOGRAPH-FA08;Lo;0;L;884C;;;;N;;;;; +FA09;CJK COMPATIBILITY IDEOGRAPH-FA09;Lo;0;L;964D;;;;N;;;;; +FA0A;CJK COMPATIBILITY IDEOGRAPH-FA0A;Lo;0;L;898B;;;;N;;;;; +FA0B;CJK COMPATIBILITY IDEOGRAPH-FA0B;Lo;0;L;5ED3;;;;N;;;;; +FA0C;CJK COMPATIBILITY IDEOGRAPH-FA0C;Lo;0;L;5140;;;;N;;;;; +FA0D;CJK COMPATIBILITY IDEOGRAPH-FA0D;Lo;0;L;55C0;;;;N;;;;; +FA0E;CJK COMPATIBILITY IDEOGRAPH-FA0E;Lo;0;L;;;;;N;;;;; +FA0F;CJK COMPATIBILITY IDEOGRAPH-FA0F;Lo;0;L;;;;;N;;;;; +FA10;CJK COMPATIBILITY IDEOGRAPH-FA10;Lo;0;L;585A;;;;N;;;;; +FA11;CJK COMPATIBILITY IDEOGRAPH-FA11;Lo;0;L;;;;;N;;;;; +FA12;CJK COMPATIBILITY IDEOGRAPH-FA12;Lo;0;L;6674;;;;N;;;;; +FA13;CJK COMPATIBILITY IDEOGRAPH-FA13;Lo;0;L;;;;;N;;;;; +FA14;CJK COMPATIBILITY IDEOGRAPH-FA14;Lo;0;L;;;;;N;;;;; +FA15;CJK COMPATIBILITY IDEOGRAPH-FA15;Lo;0;L;51DE;;;;N;;;;; +FA16;CJK COMPATIBILITY IDEOGRAPH-FA16;Lo;0;L;732A;;;;N;;;;; +FA17;CJK COMPATIBILITY IDEOGRAPH-FA17;Lo;0;L;76CA;;;;N;;;;; +FA18;CJK COMPATIBILITY IDEOGRAPH-FA18;Lo;0;L;793C;;;;N;;;;; +FA19;CJK COMPATIBILITY IDEOGRAPH-FA19;Lo;0;L;795E;;;;N;;;;; +FA1A;CJK COMPATIBILITY IDEOGRAPH-FA1A;Lo;0;L;7965;;;;N;;;;; +FA1B;CJK COMPATIBILITY IDEOGRAPH-FA1B;Lo;0;L;798F;;;;N;;;;; +FA1C;CJK COMPATIBILITY IDEOGRAPH-FA1C;Lo;0;L;9756;;;;N;;;;; +FA1D;CJK COMPATIBILITY IDEOGRAPH-FA1D;Lo;0;L;7CBE;;;;N;;;;; +FA1E;CJK COMPATIBILITY IDEOGRAPH-FA1E;Lo;0;L;7FBD;;;;N;;;;; +FA1F;CJK COMPATIBILITY IDEOGRAPH-FA1F;Lo;0;L;;;;;N;;;;; +FA20;CJK COMPATIBILITY IDEOGRAPH-FA20;Lo;0;L;8612;;;;N;;;;; +FA21;CJK COMPATIBILITY IDEOGRAPH-FA21;Lo;0;L;;;;;N;;;;; +FA22;CJK COMPATIBILITY IDEOGRAPH-FA22;Lo;0;L;8AF8;;;;N;;;;; +FA23;CJK COMPATIBILITY IDEOGRAPH-FA23;Lo;0;L;;;;;N;;;;; +FA24;CJK COMPATIBILITY IDEOGRAPH-FA24;Lo;0;L;;;;;N;;;;; +FA25;CJK COMPATIBILITY IDEOGRAPH-FA25;Lo;0;L;9038;;;;N;;;;; +FA26;CJK COMPATIBILITY IDEOGRAPH-FA26;Lo;0;L;90FD;;;;N;;;;; +FA27;CJK COMPATIBILITY IDEOGRAPH-FA27;Lo;0;L;;;;;N;;;;; +FA28;CJK COMPATIBILITY IDEOGRAPH-FA28;Lo;0;L;;;;;N;;;;; +FA29;CJK COMPATIBILITY IDEOGRAPH-FA29;Lo;0;L;;;;;N;;;;; +FA2A;CJK COMPATIBILITY IDEOGRAPH-FA2A;Lo;0;L;98EF;;;;N;;;;; +FA2B;CJK COMPATIBILITY IDEOGRAPH-FA2B;Lo;0;L;98FC;;;;N;;;;; +FA2C;CJK COMPATIBILITY IDEOGRAPH-FA2C;Lo;0;L;9928;;;;N;;;;; +FA2D;CJK COMPATIBILITY IDEOGRAPH-FA2D;Lo;0;L;9DB4;;;;N;;;;; +FA2E;CJK COMPATIBILITY IDEOGRAPH-FA2E;Lo;0;L;90DE;;;;N;;;;; +FA2F;CJK COMPATIBILITY IDEOGRAPH-FA2F;Lo;0;L;96B7;;;;N;;;;; +FA30;CJK COMPATIBILITY IDEOGRAPH-FA30;Lo;0;L;4FAE;;;;N;;;;; +FA31;CJK COMPATIBILITY IDEOGRAPH-FA31;Lo;0;L;50E7;;;;N;;;;; +FA32;CJK COMPATIBILITY IDEOGRAPH-FA32;Lo;0;L;514D;;;;N;;;;; +FA33;CJK COMPATIBILITY IDEOGRAPH-FA33;Lo;0;L;52C9;;;;N;;;;; +FA34;CJK COMPATIBILITY IDEOGRAPH-FA34;Lo;0;L;52E4;;;;N;;;;; +FA35;CJK COMPATIBILITY IDEOGRAPH-FA35;Lo;0;L;5351;;;;N;;;;; +FA36;CJK COMPATIBILITY IDEOGRAPH-FA36;Lo;0;L;559D;;;;N;;;;; +FA37;CJK COMPATIBILITY IDEOGRAPH-FA37;Lo;0;L;5606;;;;N;;;;; +FA38;CJK COMPATIBILITY IDEOGRAPH-FA38;Lo;0;L;5668;;;;N;;;;; +FA39;CJK COMPATIBILITY IDEOGRAPH-FA39;Lo;0;L;5840;;;;N;;;;; +FA3A;CJK COMPATIBILITY IDEOGRAPH-FA3A;Lo;0;L;58A8;;;;N;;;;; +FA3B;CJK COMPATIBILITY IDEOGRAPH-FA3B;Lo;0;L;5C64;;;;N;;;;; +FA3C;CJK COMPATIBILITY IDEOGRAPH-FA3C;Lo;0;L;5C6E;;;;N;;;;; +FA3D;CJK COMPATIBILITY IDEOGRAPH-FA3D;Lo;0;L;6094;;;;N;;;;; +FA3E;CJK COMPATIBILITY IDEOGRAPH-FA3E;Lo;0;L;6168;;;;N;;;;; +FA3F;CJK COMPATIBILITY IDEOGRAPH-FA3F;Lo;0;L;618E;;;;N;;;;; +FA40;CJK COMPATIBILITY IDEOGRAPH-FA40;Lo;0;L;61F2;;;;N;;;;; +FA41;CJK COMPATIBILITY IDEOGRAPH-FA41;Lo;0;L;654F;;;;N;;;;; +FA42;CJK COMPATIBILITY IDEOGRAPH-FA42;Lo;0;L;65E2;;;;N;;;;; +FA43;CJK COMPATIBILITY IDEOGRAPH-FA43;Lo;0;L;6691;;;;N;;;;; +FA44;CJK COMPATIBILITY IDEOGRAPH-FA44;Lo;0;L;6885;;;;N;;;;; +FA45;CJK COMPATIBILITY IDEOGRAPH-FA45;Lo;0;L;6D77;;;;N;;;;; +FA46;CJK COMPATIBILITY IDEOGRAPH-FA46;Lo;0;L;6E1A;;;;N;;;;; +FA47;CJK COMPATIBILITY IDEOGRAPH-FA47;Lo;0;L;6F22;;;;N;;;;; +FA48;CJK COMPATIBILITY IDEOGRAPH-FA48;Lo;0;L;716E;;;;N;;;;; +FA49;CJK COMPATIBILITY IDEOGRAPH-FA49;Lo;0;L;722B;;;;N;;;;; +FA4A;CJK COMPATIBILITY IDEOGRAPH-FA4A;Lo;0;L;7422;;;;N;;;;; +FA4B;CJK COMPATIBILITY IDEOGRAPH-FA4B;Lo;0;L;7891;;;;N;;;;; +FA4C;CJK COMPATIBILITY IDEOGRAPH-FA4C;Lo;0;L;793E;;;;N;;;;; +FA4D;CJK COMPATIBILITY IDEOGRAPH-FA4D;Lo;0;L;7949;;;;N;;;;; +FA4E;CJK COMPATIBILITY IDEOGRAPH-FA4E;Lo;0;L;7948;;;;N;;;;; +FA4F;CJK COMPATIBILITY IDEOGRAPH-FA4F;Lo;0;L;7950;;;;N;;;;; +FA50;CJK COMPATIBILITY IDEOGRAPH-FA50;Lo;0;L;7956;;;;N;;;;; +FA51;CJK COMPATIBILITY IDEOGRAPH-FA51;Lo;0;L;795D;;;;N;;;;; +FA52;CJK COMPATIBILITY IDEOGRAPH-FA52;Lo;0;L;798D;;;;N;;;;; +FA53;CJK COMPATIBILITY IDEOGRAPH-FA53;Lo;0;L;798E;;;;N;;;;; +FA54;CJK COMPATIBILITY IDEOGRAPH-FA54;Lo;0;L;7A40;;;;N;;;;; +FA55;CJK COMPATIBILITY IDEOGRAPH-FA55;Lo;0;L;7A81;;;;N;;;;; +FA56;CJK COMPATIBILITY IDEOGRAPH-FA56;Lo;0;L;7BC0;;;;N;;;;; +FA57;CJK COMPATIBILITY IDEOGRAPH-FA57;Lo;0;L;7DF4;;;;N;;;;; +FA58;CJK COMPATIBILITY IDEOGRAPH-FA58;Lo;0;L;7E09;;;;N;;;;; +FA59;CJK COMPATIBILITY IDEOGRAPH-FA59;Lo;0;L;7E41;;;;N;;;;; +FA5A;CJK COMPATIBILITY IDEOGRAPH-FA5A;Lo;0;L;7F72;;;;N;;;;; +FA5B;CJK COMPATIBILITY IDEOGRAPH-FA5B;Lo;0;L;8005;;;;N;;;;; +FA5C;CJK COMPATIBILITY IDEOGRAPH-FA5C;Lo;0;L;81ED;;;;N;;;;; +FA5D;CJK COMPATIBILITY IDEOGRAPH-FA5D;Lo;0;L;8279;;;;N;;;;; +FA5E;CJK COMPATIBILITY IDEOGRAPH-FA5E;Lo;0;L;8279;;;;N;;;;; +FA5F;CJK COMPATIBILITY IDEOGRAPH-FA5F;Lo;0;L;8457;;;;N;;;;; +FA60;CJK COMPATIBILITY IDEOGRAPH-FA60;Lo;0;L;8910;;;;N;;;;; +FA61;CJK COMPATIBILITY IDEOGRAPH-FA61;Lo;0;L;8996;;;;N;;;;; +FA62;CJK COMPATIBILITY IDEOGRAPH-FA62;Lo;0;L;8B01;;;;N;;;;; +FA63;CJK COMPATIBILITY IDEOGRAPH-FA63;Lo;0;L;8B39;;;;N;;;;; +FA64;CJK COMPATIBILITY IDEOGRAPH-FA64;Lo;0;L;8CD3;;;;N;;;;; +FA65;CJK COMPATIBILITY IDEOGRAPH-FA65;Lo;0;L;8D08;;;;N;;;;; +FA66;CJK COMPATIBILITY IDEOGRAPH-FA66;Lo;0;L;8FB6;;;;N;;;;; +FA67;CJK COMPATIBILITY IDEOGRAPH-FA67;Lo;0;L;9038;;;;N;;;;; +FA68;CJK COMPATIBILITY IDEOGRAPH-FA68;Lo;0;L;96E3;;;;N;;;;; +FA69;CJK COMPATIBILITY IDEOGRAPH-FA69;Lo;0;L;97FF;;;;N;;;;; +FA6A;CJK COMPATIBILITY IDEOGRAPH-FA6A;Lo;0;L;983B;;;;N;;;;; +FA6B;CJK COMPATIBILITY IDEOGRAPH-FA6B;Lo;0;L;6075;;;;N;;;;; +FA6C;CJK COMPATIBILITY IDEOGRAPH-FA6C;Lo;0;L;242EE;;;;N;;;;; +FA6D;CJK COMPATIBILITY IDEOGRAPH-FA6D;Lo;0;L;8218;;;;N;;;;; +FA70;CJK COMPATIBILITY IDEOGRAPH-FA70;Lo;0;L;4E26;;;;N;;;;; +FA71;CJK COMPATIBILITY IDEOGRAPH-FA71;Lo;0;L;51B5;;;;N;;;;; +FA72;CJK COMPATIBILITY IDEOGRAPH-FA72;Lo;0;L;5168;;;;N;;;;; +FA73;CJK COMPATIBILITY IDEOGRAPH-FA73;Lo;0;L;4F80;;;;N;;;;; +FA74;CJK COMPATIBILITY IDEOGRAPH-FA74;Lo;0;L;5145;;;;N;;;;; +FA75;CJK COMPATIBILITY IDEOGRAPH-FA75;Lo;0;L;5180;;;;N;;;;; +FA76;CJK COMPATIBILITY IDEOGRAPH-FA76;Lo;0;L;52C7;;;;N;;;;; +FA77;CJK COMPATIBILITY IDEOGRAPH-FA77;Lo;0;L;52FA;;;;N;;;;; +FA78;CJK COMPATIBILITY IDEOGRAPH-FA78;Lo;0;L;559D;;;;N;;;;; +FA79;CJK COMPATIBILITY IDEOGRAPH-FA79;Lo;0;L;5555;;;;N;;;;; +FA7A;CJK COMPATIBILITY IDEOGRAPH-FA7A;Lo;0;L;5599;;;;N;;;;; +FA7B;CJK COMPATIBILITY IDEOGRAPH-FA7B;Lo;0;L;55E2;;;;N;;;;; +FA7C;CJK COMPATIBILITY IDEOGRAPH-FA7C;Lo;0;L;585A;;;;N;;;;; +FA7D;CJK COMPATIBILITY IDEOGRAPH-FA7D;Lo;0;L;58B3;;;;N;;;;; +FA7E;CJK COMPATIBILITY IDEOGRAPH-FA7E;Lo;0;L;5944;;;;N;;;;; +FA7F;CJK COMPATIBILITY IDEOGRAPH-FA7F;Lo;0;L;5954;;;;N;;;;; +FA80;CJK COMPATIBILITY IDEOGRAPH-FA80;Lo;0;L;5A62;;;;N;;;;; +FA81;CJK COMPATIBILITY IDEOGRAPH-FA81;Lo;0;L;5B28;;;;N;;;;; +FA82;CJK COMPATIBILITY IDEOGRAPH-FA82;Lo;0;L;5ED2;;;;N;;;;; +FA83;CJK COMPATIBILITY IDEOGRAPH-FA83;Lo;0;L;5ED9;;;;N;;;;; +FA84;CJK COMPATIBILITY IDEOGRAPH-FA84;Lo;0;L;5F69;;;;N;;;;; +FA85;CJK COMPATIBILITY IDEOGRAPH-FA85;Lo;0;L;5FAD;;;;N;;;;; +FA86;CJK COMPATIBILITY IDEOGRAPH-FA86;Lo;0;L;60D8;;;;N;;;;; +FA87;CJK COMPATIBILITY IDEOGRAPH-FA87;Lo;0;L;614E;;;;N;;;;; +FA88;CJK COMPATIBILITY IDEOGRAPH-FA88;Lo;0;L;6108;;;;N;;;;; +FA89;CJK COMPATIBILITY IDEOGRAPH-FA89;Lo;0;L;618E;;;;N;;;;; +FA8A;CJK COMPATIBILITY IDEOGRAPH-FA8A;Lo;0;L;6160;;;;N;;;;; +FA8B;CJK COMPATIBILITY IDEOGRAPH-FA8B;Lo;0;L;61F2;;;;N;;;;; +FA8C;CJK COMPATIBILITY IDEOGRAPH-FA8C;Lo;0;L;6234;;;;N;;;;; +FA8D;CJK COMPATIBILITY IDEOGRAPH-FA8D;Lo;0;L;63C4;;;;N;;;;; +FA8E;CJK COMPATIBILITY IDEOGRAPH-FA8E;Lo;0;L;641C;;;;N;;;;; +FA8F;CJK COMPATIBILITY IDEOGRAPH-FA8F;Lo;0;L;6452;;;;N;;;;; +FA90;CJK COMPATIBILITY IDEOGRAPH-FA90;Lo;0;L;6556;;;;N;;;;; +FA91;CJK COMPATIBILITY IDEOGRAPH-FA91;Lo;0;L;6674;;;;N;;;;; +FA92;CJK COMPATIBILITY IDEOGRAPH-FA92;Lo;0;L;6717;;;;N;;;;; +FA93;CJK COMPATIBILITY IDEOGRAPH-FA93;Lo;0;L;671B;;;;N;;;;; +FA94;CJK COMPATIBILITY IDEOGRAPH-FA94;Lo;0;L;6756;;;;N;;;;; +FA95;CJK COMPATIBILITY IDEOGRAPH-FA95;Lo;0;L;6B79;;;;N;;;;; +FA96;CJK COMPATIBILITY IDEOGRAPH-FA96;Lo;0;L;6BBA;;;;N;;;;; +FA97;CJK COMPATIBILITY IDEOGRAPH-FA97;Lo;0;L;6D41;;;;N;;;;; +FA98;CJK COMPATIBILITY IDEOGRAPH-FA98;Lo;0;L;6EDB;;;;N;;;;; +FA99;CJK COMPATIBILITY IDEOGRAPH-FA99;Lo;0;L;6ECB;;;;N;;;;; +FA9A;CJK COMPATIBILITY IDEOGRAPH-FA9A;Lo;0;L;6F22;;;;N;;;;; +FA9B;CJK COMPATIBILITY IDEOGRAPH-FA9B;Lo;0;L;701E;;;;N;;;;; +FA9C;CJK COMPATIBILITY IDEOGRAPH-FA9C;Lo;0;L;716E;;;;N;;;;; +FA9D;CJK COMPATIBILITY IDEOGRAPH-FA9D;Lo;0;L;77A7;;;;N;;;;; +FA9E;CJK COMPATIBILITY IDEOGRAPH-FA9E;Lo;0;L;7235;;;;N;;;;; +FA9F;CJK COMPATIBILITY IDEOGRAPH-FA9F;Lo;0;L;72AF;;;;N;;;;; +FAA0;CJK COMPATIBILITY IDEOGRAPH-FAA0;Lo;0;L;732A;;;;N;;;;; +FAA1;CJK COMPATIBILITY IDEOGRAPH-FAA1;Lo;0;L;7471;;;;N;;;;; +FAA2;CJK COMPATIBILITY IDEOGRAPH-FAA2;Lo;0;L;7506;;;;N;;;;; +FAA3;CJK COMPATIBILITY IDEOGRAPH-FAA3;Lo;0;L;753B;;;;N;;;;; +FAA4;CJK COMPATIBILITY IDEOGRAPH-FAA4;Lo;0;L;761D;;;;N;;;;; +FAA5;CJK COMPATIBILITY IDEOGRAPH-FAA5;Lo;0;L;761F;;;;N;;;;; +FAA6;CJK COMPATIBILITY IDEOGRAPH-FAA6;Lo;0;L;76CA;;;;N;;;;; +FAA7;CJK COMPATIBILITY IDEOGRAPH-FAA7;Lo;0;L;76DB;;;;N;;;;; +FAA8;CJK COMPATIBILITY IDEOGRAPH-FAA8;Lo;0;L;76F4;;;;N;;;;; +FAA9;CJK COMPATIBILITY IDEOGRAPH-FAA9;Lo;0;L;774A;;;;N;;;;; +FAAA;CJK COMPATIBILITY IDEOGRAPH-FAAA;Lo;0;L;7740;;;;N;;;;; +FAAB;CJK COMPATIBILITY IDEOGRAPH-FAAB;Lo;0;L;78CC;;;;N;;;;; +FAAC;CJK COMPATIBILITY IDEOGRAPH-FAAC;Lo;0;L;7AB1;;;;N;;;;; +FAAD;CJK COMPATIBILITY IDEOGRAPH-FAAD;Lo;0;L;7BC0;;;;N;;;;; +FAAE;CJK COMPATIBILITY IDEOGRAPH-FAAE;Lo;0;L;7C7B;;;;N;;;;; +FAAF;CJK COMPATIBILITY IDEOGRAPH-FAAF;Lo;0;L;7D5B;;;;N;;;;; +FAB0;CJK COMPATIBILITY IDEOGRAPH-FAB0;Lo;0;L;7DF4;;;;N;;;;; +FAB1;CJK COMPATIBILITY IDEOGRAPH-FAB1;Lo;0;L;7F3E;;;;N;;;;; +FAB2;CJK COMPATIBILITY IDEOGRAPH-FAB2;Lo;0;L;8005;;;;N;;;;; +FAB3;CJK COMPATIBILITY IDEOGRAPH-FAB3;Lo;0;L;8352;;;;N;;;;; +FAB4;CJK COMPATIBILITY IDEOGRAPH-FAB4;Lo;0;L;83EF;;;;N;;;;; +FAB5;CJK COMPATIBILITY IDEOGRAPH-FAB5;Lo;0;L;8779;;;;N;;;;; +FAB6;CJK COMPATIBILITY IDEOGRAPH-FAB6;Lo;0;L;8941;;;;N;;;;; +FAB7;CJK COMPATIBILITY IDEOGRAPH-FAB7;Lo;0;L;8986;;;;N;;;;; +FAB8;CJK COMPATIBILITY IDEOGRAPH-FAB8;Lo;0;L;8996;;;;N;;;;; +FAB9;CJK COMPATIBILITY IDEOGRAPH-FAB9;Lo;0;L;8ABF;;;;N;;;;; +FABA;CJK COMPATIBILITY IDEOGRAPH-FABA;Lo;0;L;8AF8;;;;N;;;;; +FABB;CJK COMPATIBILITY IDEOGRAPH-FABB;Lo;0;L;8ACB;;;;N;;;;; +FABC;CJK COMPATIBILITY IDEOGRAPH-FABC;Lo;0;L;8B01;;;;N;;;;; +FABD;CJK COMPATIBILITY IDEOGRAPH-FABD;Lo;0;L;8AFE;;;;N;;;;; +FABE;CJK COMPATIBILITY IDEOGRAPH-FABE;Lo;0;L;8AED;;;;N;;;;; +FABF;CJK COMPATIBILITY IDEOGRAPH-FABF;Lo;0;L;8B39;;;;N;;;;; +FAC0;CJK COMPATIBILITY IDEOGRAPH-FAC0;Lo;0;L;8B8A;;;;N;;;;; +FAC1;CJK COMPATIBILITY IDEOGRAPH-FAC1;Lo;0;L;8D08;;;;N;;;;; +FAC2;CJK COMPATIBILITY IDEOGRAPH-FAC2;Lo;0;L;8F38;;;;N;;;;; +FAC3;CJK COMPATIBILITY IDEOGRAPH-FAC3;Lo;0;L;9072;;;;N;;;;; +FAC4;CJK COMPATIBILITY IDEOGRAPH-FAC4;Lo;0;L;9199;;;;N;;;;; +FAC5;CJK COMPATIBILITY IDEOGRAPH-FAC5;Lo;0;L;9276;;;;N;;;;; +FAC6;CJK COMPATIBILITY IDEOGRAPH-FAC6;Lo;0;L;967C;;;;N;;;;; +FAC7;CJK COMPATIBILITY IDEOGRAPH-FAC7;Lo;0;L;96E3;;;;N;;;;; +FAC8;CJK COMPATIBILITY IDEOGRAPH-FAC8;Lo;0;L;9756;;;;N;;;;; +FAC9;CJK COMPATIBILITY IDEOGRAPH-FAC9;Lo;0;L;97DB;;;;N;;;;; +FACA;CJK COMPATIBILITY IDEOGRAPH-FACA;Lo;0;L;97FF;;;;N;;;;; +FACB;CJK COMPATIBILITY IDEOGRAPH-FACB;Lo;0;L;980B;;;;N;;;;; +FACC;CJK COMPATIBILITY IDEOGRAPH-FACC;Lo;0;L;983B;;;;N;;;;; +FACD;CJK COMPATIBILITY IDEOGRAPH-FACD;Lo;0;L;9B12;;;;N;;;;; +FACE;CJK COMPATIBILITY IDEOGRAPH-FACE;Lo;0;L;9F9C;;;;N;;;;; +FACF;CJK COMPATIBILITY IDEOGRAPH-FACF;Lo;0;L;2284A;;;;N;;;;; +FAD0;CJK COMPATIBILITY IDEOGRAPH-FAD0;Lo;0;L;22844;;;;N;;;;; +FAD1;CJK COMPATIBILITY IDEOGRAPH-FAD1;Lo;0;L;233D5;;;;N;;;;; +FAD2;CJK COMPATIBILITY IDEOGRAPH-FAD2;Lo;0;L;3B9D;;;;N;;;;; +FAD3;CJK COMPATIBILITY IDEOGRAPH-FAD3;Lo;0;L;4018;;;;N;;;;; +FAD4;CJK COMPATIBILITY IDEOGRAPH-FAD4;Lo;0;L;4039;;;;N;;;;; +FAD5;CJK COMPATIBILITY IDEOGRAPH-FAD5;Lo;0;L;25249;;;;N;;;;; +FAD6;CJK COMPATIBILITY IDEOGRAPH-FAD6;Lo;0;L;25CD0;;;;N;;;;; +FAD7;CJK COMPATIBILITY IDEOGRAPH-FAD7;Lo;0;L;27ED3;;;;N;;;;; +FAD8;CJK COMPATIBILITY IDEOGRAPH-FAD8;Lo;0;L;9F43;;;;N;;;;; +FAD9;CJK COMPATIBILITY IDEOGRAPH-FAD9;Lo;0;L;9F8E;;;;N;;;;; +FB00;LATIN SMALL LIGATURE FF;Ll;0;L; 0066 0066;;;;N;;;;; +FB01;LATIN SMALL LIGATURE FI;Ll;0;L; 0066 0069;;;;N;;;;; +FB02;LATIN SMALL LIGATURE FL;Ll;0;L; 0066 006C;;;;N;;;;; +FB03;LATIN SMALL LIGATURE FFI;Ll;0;L; 0066 0066 0069;;;;N;;;;; +FB04;LATIN SMALL LIGATURE FFL;Ll;0;L; 0066 0066 006C;;;;N;;;;; +FB05;LATIN SMALL LIGATURE LONG S T;Ll;0;L; 017F 0074;;;;N;;;;; +FB06;LATIN SMALL LIGATURE ST;Ll;0;L; 0073 0074;;;;N;;;;; +FB13;ARMENIAN SMALL LIGATURE MEN NOW;Ll;0;L; 0574 0576;;;;N;;;;; +FB14;ARMENIAN SMALL LIGATURE MEN ECH;Ll;0;L; 0574 0565;;;;N;;;;; +FB15;ARMENIAN SMALL LIGATURE MEN INI;Ll;0;L; 0574 056B;;;;N;;;;; +FB16;ARMENIAN SMALL LIGATURE VEW NOW;Ll;0;L; 057E 0576;;;;N;;;;; +FB17;ARMENIAN SMALL LIGATURE MEN XEH;Ll;0;L; 0574 056D;;;;N;;;;; +FB1D;HEBREW LETTER YOD WITH HIRIQ;Lo;0;R;05D9 05B4;;;;N;;;;; +FB1E;HEBREW POINT JUDEO-SPANISH VARIKA;Mn;26;NSM;;;;;N;HEBREW POINT VARIKA;;;; +FB1F;HEBREW LIGATURE YIDDISH YOD YOD PATAH;Lo;0;R;05F2 05B7;;;;N;;;;; +FB20;HEBREW LETTER ALTERNATIVE AYIN;Lo;0;R; 05E2;;;;N;;;;; +FB21;HEBREW LETTER WIDE ALEF;Lo;0;R; 05D0;;;;N;;;;; +FB22;HEBREW LETTER WIDE DALET;Lo;0;R; 05D3;;;;N;;;;; +FB23;HEBREW LETTER WIDE HE;Lo;0;R; 05D4;;;;N;;;;; +FB24;HEBREW LETTER WIDE KAF;Lo;0;R; 05DB;;;;N;;;;; +FB25;HEBREW LETTER WIDE LAMED;Lo;0;R; 05DC;;;;N;;;;; +FB26;HEBREW LETTER WIDE FINAL MEM;Lo;0;R; 05DD;;;;N;;;;; +FB27;HEBREW LETTER WIDE RESH;Lo;0;R; 05E8;;;;N;;;;; +FB28;HEBREW LETTER WIDE TAV;Lo;0;R; 05EA;;;;N;;;;; +FB29;HEBREW LETTER ALTERNATIVE PLUS SIGN;Sm;0;ES; 002B;;;;N;;;;; +FB2A;HEBREW LETTER SHIN WITH SHIN DOT;Lo;0;R;05E9 05C1;;;;N;;;;; +FB2B;HEBREW LETTER SHIN WITH SIN DOT;Lo;0;R;05E9 05C2;;;;N;;;;; +FB2C;HEBREW LETTER SHIN WITH DAGESH AND SHIN DOT;Lo;0;R;FB49 05C1;;;;N;;;;; +FB2D;HEBREW LETTER SHIN WITH DAGESH AND SIN DOT;Lo;0;R;FB49 05C2;;;;N;;;;; +FB2E;HEBREW LETTER ALEF WITH PATAH;Lo;0;R;05D0 05B7;;;;N;;;;; +FB2F;HEBREW LETTER ALEF WITH QAMATS;Lo;0;R;05D0 05B8;;;;N;;;;; +FB30;HEBREW LETTER ALEF WITH MAPIQ;Lo;0;R;05D0 05BC;;;;N;;;;; +FB31;HEBREW LETTER BET WITH DAGESH;Lo;0;R;05D1 05BC;;;;N;;;;; +FB32;HEBREW LETTER GIMEL WITH DAGESH;Lo;0;R;05D2 05BC;;;;N;;;;; +FB33;HEBREW LETTER DALET WITH DAGESH;Lo;0;R;05D3 05BC;;;;N;;;;; +FB34;HEBREW LETTER HE WITH MAPIQ;Lo;0;R;05D4 05BC;;;;N;;;;; +FB35;HEBREW LETTER VAV WITH DAGESH;Lo;0;R;05D5 05BC;;;;N;;;;; +FB36;HEBREW LETTER ZAYIN WITH DAGESH;Lo;0;R;05D6 05BC;;;;N;;;;; +FB38;HEBREW LETTER TET WITH DAGESH;Lo;0;R;05D8 05BC;;;;N;;;;; +FB39;HEBREW LETTER YOD WITH DAGESH;Lo;0;R;05D9 05BC;;;;N;;;;; +FB3A;HEBREW LETTER FINAL KAF WITH DAGESH;Lo;0;R;05DA 05BC;;;;N;;;;; +FB3B;HEBREW LETTER KAF WITH DAGESH;Lo;0;R;05DB 05BC;;;;N;;;;; +FB3C;HEBREW LETTER LAMED WITH DAGESH;Lo;0;R;05DC 05BC;;;;N;;;;; +FB3E;HEBREW LETTER MEM WITH DAGESH;Lo;0;R;05DE 05BC;;;;N;;;;; +FB40;HEBREW LETTER NUN WITH DAGESH;Lo;0;R;05E0 05BC;;;;N;;;;; +FB41;HEBREW LETTER SAMEKH WITH DAGESH;Lo;0;R;05E1 05BC;;;;N;;;;; +FB43;HEBREW LETTER FINAL PE WITH DAGESH;Lo;0;R;05E3 05BC;;;;N;;;;; +FB44;HEBREW LETTER PE WITH DAGESH;Lo;0;R;05E4 05BC;;;;N;;;;; +FB46;HEBREW LETTER TSADI WITH DAGESH;Lo;0;R;05E6 05BC;;;;N;;;;; +FB47;HEBREW LETTER QOF WITH DAGESH;Lo;0;R;05E7 05BC;;;;N;;;;; +FB48;HEBREW LETTER RESH WITH DAGESH;Lo;0;R;05E8 05BC;;;;N;;;;; +FB49;HEBREW LETTER SHIN WITH DAGESH;Lo;0;R;05E9 05BC;;;;N;;;;; +FB4A;HEBREW LETTER TAV WITH DAGESH;Lo;0;R;05EA 05BC;;;;N;;;;; +FB4B;HEBREW LETTER VAV WITH HOLAM;Lo;0;R;05D5 05B9;;;;N;;;;; +FB4C;HEBREW LETTER BET WITH RAFE;Lo;0;R;05D1 05BF;;;;N;;;;; +FB4D;HEBREW LETTER KAF WITH RAFE;Lo;0;R;05DB 05BF;;;;N;;;;; +FB4E;HEBREW LETTER PE WITH RAFE;Lo;0;R;05E4 05BF;;;;N;;;;; +FB4F;HEBREW LIGATURE ALEF LAMED;Lo;0;R; 05D0 05DC;;;;N;;;;; +FB50;ARABIC LETTER ALEF WASLA ISOLATED FORM;Lo;0;AL; 0671;;;;N;;;;; +FB51;ARABIC LETTER ALEF WASLA FINAL FORM;Lo;0;AL; 0671;;;;N;;;;; +FB52;ARABIC LETTER BEEH ISOLATED FORM;Lo;0;AL; 067B;;;;N;;;;; +FB53;ARABIC LETTER BEEH FINAL FORM;Lo;0;AL; 067B;;;;N;;;;; +FB54;ARABIC LETTER BEEH INITIAL FORM;Lo;0;AL; 067B;;;;N;;;;; +FB55;ARABIC LETTER BEEH MEDIAL FORM;Lo;0;AL; 067B;;;;N;;;;; +FB56;ARABIC LETTER PEH ISOLATED FORM;Lo;0;AL; 067E;;;;N;;;;; +FB57;ARABIC LETTER PEH FINAL FORM;Lo;0;AL; 067E;;;;N;;;;; +FB58;ARABIC LETTER PEH INITIAL FORM;Lo;0;AL; 067E;;;;N;;;;; +FB59;ARABIC LETTER PEH MEDIAL FORM;Lo;0;AL; 067E;;;;N;;;;; +FB5A;ARABIC LETTER BEHEH ISOLATED FORM;Lo;0;AL; 0680;;;;N;;;;; +FB5B;ARABIC LETTER BEHEH FINAL FORM;Lo;0;AL; 0680;;;;N;;;;; +FB5C;ARABIC LETTER BEHEH INITIAL FORM;Lo;0;AL; 0680;;;;N;;;;; +FB5D;ARABIC LETTER BEHEH MEDIAL FORM;Lo;0;AL; 0680;;;;N;;;;; +FB5E;ARABIC LETTER TTEHEH ISOLATED FORM;Lo;0;AL; 067A;;;;N;;;;; +FB5F;ARABIC LETTER TTEHEH FINAL FORM;Lo;0;AL; 067A;;;;N;;;;; +FB60;ARABIC LETTER TTEHEH INITIAL FORM;Lo;0;AL; 067A;;;;N;;;;; +FB61;ARABIC LETTER TTEHEH MEDIAL FORM;Lo;0;AL; 067A;;;;N;;;;; +FB62;ARABIC LETTER TEHEH ISOLATED FORM;Lo;0;AL; 067F;;;;N;;;;; +FB63;ARABIC LETTER TEHEH FINAL FORM;Lo;0;AL; 067F;;;;N;;;;; +FB64;ARABIC LETTER TEHEH INITIAL FORM;Lo;0;AL; 067F;;;;N;;;;; +FB65;ARABIC LETTER TEHEH MEDIAL FORM;Lo;0;AL; 067F;;;;N;;;;; +FB66;ARABIC LETTER TTEH ISOLATED FORM;Lo;0;AL; 0679;;;;N;;;;; +FB67;ARABIC LETTER TTEH FINAL FORM;Lo;0;AL; 0679;;;;N;;;;; +FB68;ARABIC LETTER TTEH INITIAL FORM;Lo;0;AL; 0679;;;;N;;;;; +FB69;ARABIC LETTER TTEH MEDIAL FORM;Lo;0;AL; 0679;;;;N;;;;; +FB6A;ARABIC LETTER VEH ISOLATED FORM;Lo;0;AL; 06A4;;;;N;;;;; +FB6B;ARABIC LETTER VEH FINAL FORM;Lo;0;AL; 06A4;;;;N;;;;; +FB6C;ARABIC LETTER VEH INITIAL FORM;Lo;0;AL; 06A4;;;;N;;;;; +FB6D;ARABIC LETTER VEH MEDIAL FORM;Lo;0;AL; 06A4;;;;N;;;;; +FB6E;ARABIC LETTER PEHEH ISOLATED FORM;Lo;0;AL; 06A6;;;;N;;;;; +FB6F;ARABIC LETTER PEHEH FINAL FORM;Lo;0;AL; 06A6;;;;N;;;;; +FB70;ARABIC LETTER PEHEH INITIAL FORM;Lo;0;AL; 06A6;;;;N;;;;; +FB71;ARABIC LETTER PEHEH MEDIAL FORM;Lo;0;AL; 06A6;;;;N;;;;; +FB72;ARABIC LETTER DYEH ISOLATED FORM;Lo;0;AL; 0684;;;;N;;;;; +FB73;ARABIC LETTER DYEH FINAL FORM;Lo;0;AL; 0684;;;;N;;;;; +FB74;ARABIC LETTER DYEH INITIAL FORM;Lo;0;AL; 0684;;;;N;;;;; +FB75;ARABIC LETTER DYEH MEDIAL FORM;Lo;0;AL; 0684;;;;N;;;;; +FB76;ARABIC LETTER NYEH ISOLATED FORM;Lo;0;AL; 0683;;;;N;;;;; +FB77;ARABIC LETTER NYEH FINAL FORM;Lo;0;AL; 0683;;;;N;;;;; +FB78;ARABIC LETTER NYEH INITIAL FORM;Lo;0;AL; 0683;;;;N;;;;; +FB79;ARABIC LETTER NYEH MEDIAL FORM;Lo;0;AL; 0683;;;;N;;;;; +FB7A;ARABIC LETTER TCHEH ISOLATED FORM;Lo;0;AL; 0686;;;;N;;;;; +FB7B;ARABIC LETTER TCHEH FINAL FORM;Lo;0;AL; 0686;;;;N;;;;; +FB7C;ARABIC LETTER TCHEH INITIAL FORM;Lo;0;AL; 0686;;;;N;;;;; +FB7D;ARABIC LETTER TCHEH MEDIAL FORM;Lo;0;AL; 0686;;;;N;;;;; +FB7E;ARABIC LETTER TCHEHEH ISOLATED FORM;Lo;0;AL; 0687;;;;N;;;;; +FB7F;ARABIC LETTER TCHEHEH FINAL FORM;Lo;0;AL; 0687;;;;N;;;;; +FB80;ARABIC LETTER TCHEHEH INITIAL FORM;Lo;0;AL; 0687;;;;N;;;;; +FB81;ARABIC LETTER TCHEHEH MEDIAL FORM;Lo;0;AL; 0687;;;;N;;;;; +FB82;ARABIC LETTER DDAHAL ISOLATED FORM;Lo;0;AL; 068D;;;;N;;;;; +FB83;ARABIC LETTER DDAHAL FINAL FORM;Lo;0;AL; 068D;;;;N;;;;; +FB84;ARABIC LETTER DAHAL ISOLATED FORM;Lo;0;AL; 068C;;;;N;;;;; +FB85;ARABIC LETTER DAHAL FINAL FORM;Lo;0;AL; 068C;;;;N;;;;; +FB86;ARABIC LETTER DUL ISOLATED FORM;Lo;0;AL; 068E;;;;N;;;;; +FB87;ARABIC LETTER DUL FINAL FORM;Lo;0;AL; 068E;;;;N;;;;; +FB88;ARABIC LETTER DDAL ISOLATED FORM;Lo;0;AL; 0688;;;;N;;;;; +FB89;ARABIC LETTER DDAL FINAL FORM;Lo;0;AL; 0688;;;;N;;;;; +FB8A;ARABIC LETTER JEH ISOLATED FORM;Lo;0;AL; 0698;;;;N;;;;; +FB8B;ARABIC LETTER JEH FINAL FORM;Lo;0;AL; 0698;;;;N;;;;; +FB8C;ARABIC LETTER RREH ISOLATED FORM;Lo;0;AL; 0691;;;;N;;;;; +FB8D;ARABIC LETTER RREH FINAL FORM;Lo;0;AL; 0691;;;;N;;;;; +FB8E;ARABIC LETTER KEHEH ISOLATED FORM;Lo;0;AL; 06A9;;;;N;;;;; +FB8F;ARABIC LETTER KEHEH FINAL FORM;Lo;0;AL; 06A9;;;;N;;;;; +FB90;ARABIC LETTER KEHEH INITIAL FORM;Lo;0;AL; 06A9;;;;N;;;;; +FB91;ARABIC LETTER KEHEH MEDIAL FORM;Lo;0;AL; 06A9;;;;N;;;;; +FB92;ARABIC LETTER GAF ISOLATED FORM;Lo;0;AL; 06AF;;;;N;;;;; +FB93;ARABIC LETTER GAF FINAL FORM;Lo;0;AL; 06AF;;;;N;;;;; +FB94;ARABIC LETTER GAF INITIAL FORM;Lo;0;AL; 06AF;;;;N;;;;; +FB95;ARABIC LETTER GAF MEDIAL FORM;Lo;0;AL; 06AF;;;;N;;;;; +FB96;ARABIC LETTER GUEH ISOLATED FORM;Lo;0;AL; 06B3;;;;N;;;;; +FB97;ARABIC LETTER GUEH FINAL FORM;Lo;0;AL; 06B3;;;;N;;;;; +FB98;ARABIC LETTER GUEH INITIAL FORM;Lo;0;AL; 06B3;;;;N;;;;; +FB99;ARABIC LETTER GUEH MEDIAL FORM;Lo;0;AL; 06B3;;;;N;;;;; +FB9A;ARABIC LETTER NGOEH ISOLATED FORM;Lo;0;AL; 06B1;;;;N;;;;; +FB9B;ARABIC LETTER NGOEH FINAL FORM;Lo;0;AL; 06B1;;;;N;;;;; +FB9C;ARABIC LETTER NGOEH INITIAL FORM;Lo;0;AL; 06B1;;;;N;;;;; +FB9D;ARABIC LETTER NGOEH MEDIAL FORM;Lo;0;AL; 06B1;;;;N;;;;; +FB9E;ARABIC LETTER NOON GHUNNA ISOLATED FORM;Lo;0;AL; 06BA;;;;N;;;;; +FB9F;ARABIC LETTER NOON GHUNNA FINAL FORM;Lo;0;AL; 06BA;;;;N;;;;; +FBA0;ARABIC LETTER RNOON ISOLATED FORM;Lo;0;AL; 06BB;;;;N;;;;; +FBA1;ARABIC LETTER RNOON FINAL FORM;Lo;0;AL; 06BB;;;;N;;;;; +FBA2;ARABIC LETTER RNOON INITIAL FORM;Lo;0;AL; 06BB;;;;N;;;;; +FBA3;ARABIC LETTER RNOON MEDIAL FORM;Lo;0;AL; 06BB;;;;N;;;;; +FBA4;ARABIC LETTER HEH WITH YEH ABOVE ISOLATED FORM;Lo;0;AL; 06C0;;;;N;;;;; +FBA5;ARABIC LETTER HEH WITH YEH ABOVE FINAL FORM;Lo;0;AL; 06C0;;;;N;;;;; +FBA6;ARABIC LETTER HEH GOAL ISOLATED FORM;Lo;0;AL; 06C1;;;;N;;;;; +FBA7;ARABIC LETTER HEH GOAL FINAL FORM;Lo;0;AL; 06C1;;;;N;;;;; +FBA8;ARABIC LETTER HEH GOAL INITIAL FORM;Lo;0;AL; 06C1;;;;N;;;;; +FBA9;ARABIC LETTER HEH GOAL MEDIAL FORM;Lo;0;AL; 06C1;;;;N;;;;; +FBAA;ARABIC LETTER HEH DOACHASHMEE ISOLATED FORM;Lo;0;AL; 06BE;;;;N;;;;; +FBAB;ARABIC LETTER HEH DOACHASHMEE FINAL FORM;Lo;0;AL; 06BE;;;;N;;;;; +FBAC;ARABIC LETTER HEH DOACHASHMEE INITIAL FORM;Lo;0;AL; 06BE;;;;N;;;;; +FBAD;ARABIC LETTER HEH DOACHASHMEE MEDIAL FORM;Lo;0;AL; 06BE;;;;N;;;;; +FBAE;ARABIC LETTER YEH BARREE ISOLATED FORM;Lo;0;AL; 06D2;;;;N;;;;; +FBAF;ARABIC LETTER YEH BARREE FINAL FORM;Lo;0;AL; 06D2;;;;N;;;;; +FBB0;ARABIC LETTER YEH BARREE WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL; 06D3;;;;N;;;;; +FBB1;ARABIC LETTER YEH BARREE WITH HAMZA ABOVE FINAL FORM;Lo;0;AL; 06D3;;;;N;;;;; +FBB2;ARABIC SYMBOL DOT ABOVE;Sk;0;AL;;;;;N;;;;; +FBB3;ARABIC SYMBOL DOT BELOW;Sk;0;AL;;;;;N;;;;; +FBB4;ARABIC SYMBOL TWO DOTS ABOVE;Sk;0;AL;;;;;N;;;;; +FBB5;ARABIC SYMBOL TWO DOTS BELOW;Sk;0;AL;;;;;N;;;;; +FBB6;ARABIC SYMBOL THREE DOTS ABOVE;Sk;0;AL;;;;;N;;;;; +FBB7;ARABIC SYMBOL THREE DOTS BELOW;Sk;0;AL;;;;;N;;;;; +FBB8;ARABIC SYMBOL THREE DOTS POINTING DOWNWARDS ABOVE;Sk;0;AL;;;;;N;;;;; +FBB9;ARABIC SYMBOL THREE DOTS POINTING DOWNWARDS BELOW;Sk;0;AL;;;;;N;;;;; +FBBA;ARABIC SYMBOL FOUR DOTS ABOVE;Sk;0;AL;;;;;N;;;;; +FBBB;ARABIC SYMBOL FOUR DOTS BELOW;Sk;0;AL;;;;;N;;;;; +FBBC;ARABIC SYMBOL DOUBLE VERTICAL BAR BELOW;Sk;0;AL;;;;;N;;;;; +FBBD;ARABIC SYMBOL TWO DOTS VERTICALLY ABOVE;Sk;0;AL;;;;;N;;;;; +FBBE;ARABIC SYMBOL TWO DOTS VERTICALLY BELOW;Sk;0;AL;;;;;N;;;;; +FBBF;ARABIC SYMBOL RING;Sk;0;AL;;;;;N;;;;; +FBC0;ARABIC SYMBOL SMALL TAH ABOVE;Sk;0;AL;;;;;N;;;;; +FBC1;ARABIC SYMBOL SMALL TAH BELOW;Sk;0;AL;;;;;N;;;;; +FBD3;ARABIC LETTER NG ISOLATED FORM;Lo;0;AL; 06AD;;;;N;;;;; +FBD4;ARABIC LETTER NG FINAL FORM;Lo;0;AL; 06AD;;;;N;;;;; +FBD5;ARABIC LETTER NG INITIAL FORM;Lo;0;AL; 06AD;;;;N;;;;; +FBD6;ARABIC LETTER NG MEDIAL FORM;Lo;0;AL; 06AD;;;;N;;;;; +FBD7;ARABIC LETTER U ISOLATED FORM;Lo;0;AL; 06C7;;;;N;;;;; +FBD8;ARABIC LETTER U FINAL FORM;Lo;0;AL; 06C7;;;;N;;;;; +FBD9;ARABIC LETTER OE ISOLATED FORM;Lo;0;AL; 06C6;;;;N;;;;; +FBDA;ARABIC LETTER OE FINAL FORM;Lo;0;AL; 06C6;;;;N;;;;; +FBDB;ARABIC LETTER YU ISOLATED FORM;Lo;0;AL; 06C8;;;;N;;;;; +FBDC;ARABIC LETTER YU FINAL FORM;Lo;0;AL; 06C8;;;;N;;;;; +FBDD;ARABIC LETTER U WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL; 0677;;;;N;;;;; +FBDE;ARABIC LETTER VE ISOLATED FORM;Lo;0;AL; 06CB;;;;N;;;;; +FBDF;ARABIC LETTER VE FINAL FORM;Lo;0;AL; 06CB;;;;N;;;;; +FBE0;ARABIC LETTER KIRGHIZ OE ISOLATED FORM;Lo;0;AL; 06C5;;;;N;;;;; +FBE1;ARABIC LETTER KIRGHIZ OE FINAL FORM;Lo;0;AL; 06C5;;;;N;;;;; +FBE2;ARABIC LETTER KIRGHIZ YU ISOLATED FORM;Lo;0;AL; 06C9;;;;N;;;;; +FBE3;ARABIC LETTER KIRGHIZ YU FINAL FORM;Lo;0;AL; 06C9;;;;N;;;;; +FBE4;ARABIC LETTER E ISOLATED FORM;Lo;0;AL; 06D0;;;;N;;;;; +FBE5;ARABIC LETTER E FINAL FORM;Lo;0;AL; 06D0;;;;N;;;;; +FBE6;ARABIC LETTER E INITIAL FORM;Lo;0;AL; 06D0;;;;N;;;;; +FBE7;ARABIC LETTER E MEDIAL FORM;Lo;0;AL; 06D0;;;;N;;;;; +FBE8;ARABIC LETTER UIGHUR KAZAKH KIRGHIZ ALEF MAKSURA INITIAL FORM;Lo;0;AL; 0649;;;;N;;;;; +FBE9;ARABIC LETTER UIGHUR KAZAKH KIRGHIZ ALEF MAKSURA MEDIAL FORM;Lo;0;AL; 0649;;;;N;;;;; +FBEA;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF ISOLATED FORM;Lo;0;AL; 0626 0627;;;;N;;;;; +FBEB;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF FINAL FORM;Lo;0;AL; 0626 0627;;;;N;;;;; +FBEC;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH AE ISOLATED FORM;Lo;0;AL; 0626 06D5;;;;N;;;;; +FBED;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH AE FINAL FORM;Lo;0;AL; 0626 06D5;;;;N;;;;; +FBEE;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH WAW ISOLATED FORM;Lo;0;AL; 0626 0648;;;;N;;;;; +FBEF;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH WAW FINAL FORM;Lo;0;AL; 0626 0648;;;;N;;;;; +FBF0;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH U ISOLATED FORM;Lo;0;AL; 0626 06C7;;;;N;;;;; +FBF1;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH U FINAL FORM;Lo;0;AL; 0626 06C7;;;;N;;;;; +FBF2;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH OE ISOLATED FORM;Lo;0;AL; 0626 06C6;;;;N;;;;; +FBF3;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH OE FINAL FORM;Lo;0;AL; 0626 06C6;;;;N;;;;; +FBF4;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YU ISOLATED FORM;Lo;0;AL; 0626 06C8;;;;N;;;;; +FBF5;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YU FINAL FORM;Lo;0;AL; 0626 06C8;;;;N;;;;; +FBF6;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH E ISOLATED FORM;Lo;0;AL; 0626 06D0;;;;N;;;;; +FBF7;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH E FINAL FORM;Lo;0;AL; 0626 06D0;;;;N;;;;; +FBF8;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH E INITIAL FORM;Lo;0;AL; 0626 06D0;;;;N;;;;; +FBF9;ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0626 0649;;;;N;;;;; +FBFA;ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0626 0649;;;;N;;;;; +FBFB;ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA INITIAL FORM;Lo;0;AL; 0626 0649;;;;N;;;;; +FBFC;ARABIC LETTER FARSI YEH ISOLATED FORM;Lo;0;AL; 06CC;;;;N;;;;; +FBFD;ARABIC LETTER FARSI YEH FINAL FORM;Lo;0;AL; 06CC;;;;N;;;;; +FBFE;ARABIC LETTER FARSI YEH INITIAL FORM;Lo;0;AL; 06CC;;;;N;;;;; +FBFF;ARABIC LETTER FARSI YEH MEDIAL FORM;Lo;0;AL; 06CC;;;;N;;;;; +FC00;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH JEEM ISOLATED FORM;Lo;0;AL; 0626 062C;;;;N;;;;; +FC01;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HAH ISOLATED FORM;Lo;0;AL; 0626 062D;;;;N;;;;; +FC02;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM ISOLATED FORM;Lo;0;AL; 0626 0645;;;;N;;;;; +FC03;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0626 0649;;;;N;;;;; +FC04;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YEH ISOLATED FORM;Lo;0;AL; 0626 064A;;;;N;;;;; +FC05;ARABIC LIGATURE BEH WITH JEEM ISOLATED FORM;Lo;0;AL; 0628 062C;;;;N;;;;; +FC06;ARABIC LIGATURE BEH WITH HAH ISOLATED FORM;Lo;0;AL; 0628 062D;;;;N;;;;; +FC07;ARABIC LIGATURE BEH WITH KHAH ISOLATED FORM;Lo;0;AL; 0628 062E;;;;N;;;;; +FC08;ARABIC LIGATURE BEH WITH MEEM ISOLATED FORM;Lo;0;AL; 0628 0645;;;;N;;;;; +FC09;ARABIC LIGATURE BEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0628 0649;;;;N;;;;; +FC0A;ARABIC LIGATURE BEH WITH YEH ISOLATED FORM;Lo;0;AL; 0628 064A;;;;N;;;;; +FC0B;ARABIC LIGATURE TEH WITH JEEM ISOLATED FORM;Lo;0;AL; 062A 062C;;;;N;;;;; +FC0C;ARABIC LIGATURE TEH WITH HAH ISOLATED FORM;Lo;0;AL; 062A 062D;;;;N;;;;; +FC0D;ARABIC LIGATURE TEH WITH KHAH ISOLATED FORM;Lo;0;AL; 062A 062E;;;;N;;;;; +FC0E;ARABIC LIGATURE TEH WITH MEEM ISOLATED FORM;Lo;0;AL; 062A 0645;;;;N;;;;; +FC0F;ARABIC LIGATURE TEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 062A 0649;;;;N;;;;; +FC10;ARABIC LIGATURE TEH WITH YEH ISOLATED FORM;Lo;0;AL; 062A 064A;;;;N;;;;; +FC11;ARABIC LIGATURE THEH WITH JEEM ISOLATED FORM;Lo;0;AL; 062B 062C;;;;N;;;;; +FC12;ARABIC LIGATURE THEH WITH MEEM ISOLATED FORM;Lo;0;AL; 062B 0645;;;;N;;;;; +FC13;ARABIC LIGATURE THEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 062B 0649;;;;N;;;;; +FC14;ARABIC LIGATURE THEH WITH YEH ISOLATED FORM;Lo;0;AL; 062B 064A;;;;N;;;;; +FC15;ARABIC LIGATURE JEEM WITH HAH ISOLATED FORM;Lo;0;AL; 062C 062D;;;;N;;;;; +FC16;ARABIC LIGATURE JEEM WITH MEEM ISOLATED FORM;Lo;0;AL; 062C 0645;;;;N;;;;; +FC17;ARABIC LIGATURE HAH WITH JEEM ISOLATED FORM;Lo;0;AL; 062D 062C;;;;N;;;;; +FC18;ARABIC LIGATURE HAH WITH MEEM ISOLATED FORM;Lo;0;AL; 062D 0645;;;;N;;;;; +FC19;ARABIC LIGATURE KHAH WITH JEEM ISOLATED FORM;Lo;0;AL; 062E 062C;;;;N;;;;; +FC1A;ARABIC LIGATURE KHAH WITH HAH ISOLATED FORM;Lo;0;AL; 062E 062D;;;;N;;;;; +FC1B;ARABIC LIGATURE KHAH WITH MEEM ISOLATED FORM;Lo;0;AL; 062E 0645;;;;N;;;;; +FC1C;ARABIC LIGATURE SEEN WITH JEEM ISOLATED FORM;Lo;0;AL; 0633 062C;;;;N;;;;; +FC1D;ARABIC LIGATURE SEEN WITH HAH ISOLATED FORM;Lo;0;AL; 0633 062D;;;;N;;;;; +FC1E;ARABIC LIGATURE SEEN WITH KHAH ISOLATED FORM;Lo;0;AL; 0633 062E;;;;N;;;;; +FC1F;ARABIC LIGATURE SEEN WITH MEEM ISOLATED FORM;Lo;0;AL; 0633 0645;;;;N;;;;; +FC20;ARABIC LIGATURE SAD WITH HAH ISOLATED FORM;Lo;0;AL; 0635 062D;;;;N;;;;; +FC21;ARABIC LIGATURE SAD WITH MEEM ISOLATED FORM;Lo;0;AL; 0635 0645;;;;N;;;;; +FC22;ARABIC LIGATURE DAD WITH JEEM ISOLATED FORM;Lo;0;AL; 0636 062C;;;;N;;;;; +FC23;ARABIC LIGATURE DAD WITH HAH ISOLATED FORM;Lo;0;AL; 0636 062D;;;;N;;;;; +FC24;ARABIC LIGATURE DAD WITH KHAH ISOLATED FORM;Lo;0;AL; 0636 062E;;;;N;;;;; +FC25;ARABIC LIGATURE DAD WITH MEEM ISOLATED FORM;Lo;0;AL; 0636 0645;;;;N;;;;; +FC26;ARABIC LIGATURE TAH WITH HAH ISOLATED FORM;Lo;0;AL; 0637 062D;;;;N;;;;; +FC27;ARABIC LIGATURE TAH WITH MEEM ISOLATED FORM;Lo;0;AL; 0637 0645;;;;N;;;;; +FC28;ARABIC LIGATURE ZAH WITH MEEM ISOLATED FORM;Lo;0;AL; 0638 0645;;;;N;;;;; +FC29;ARABIC LIGATURE AIN WITH JEEM ISOLATED FORM;Lo;0;AL; 0639 062C;;;;N;;;;; +FC2A;ARABIC LIGATURE AIN WITH MEEM ISOLATED FORM;Lo;0;AL; 0639 0645;;;;N;;;;; +FC2B;ARABIC LIGATURE GHAIN WITH JEEM ISOLATED FORM;Lo;0;AL; 063A 062C;;;;N;;;;; +FC2C;ARABIC LIGATURE GHAIN WITH MEEM ISOLATED FORM;Lo;0;AL; 063A 0645;;;;N;;;;; +FC2D;ARABIC LIGATURE FEH WITH JEEM ISOLATED FORM;Lo;0;AL; 0641 062C;;;;N;;;;; +FC2E;ARABIC LIGATURE FEH WITH HAH ISOLATED FORM;Lo;0;AL; 0641 062D;;;;N;;;;; +FC2F;ARABIC LIGATURE FEH WITH KHAH ISOLATED FORM;Lo;0;AL; 0641 062E;;;;N;;;;; +FC30;ARABIC LIGATURE FEH WITH MEEM ISOLATED FORM;Lo;0;AL; 0641 0645;;;;N;;;;; +FC31;ARABIC LIGATURE FEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0641 0649;;;;N;;;;; +FC32;ARABIC LIGATURE FEH WITH YEH ISOLATED FORM;Lo;0;AL; 0641 064A;;;;N;;;;; +FC33;ARABIC LIGATURE QAF WITH HAH ISOLATED FORM;Lo;0;AL; 0642 062D;;;;N;;;;; +FC34;ARABIC LIGATURE QAF WITH MEEM ISOLATED FORM;Lo;0;AL; 0642 0645;;;;N;;;;; +FC35;ARABIC LIGATURE QAF WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0642 0649;;;;N;;;;; +FC36;ARABIC LIGATURE QAF WITH YEH ISOLATED FORM;Lo;0;AL; 0642 064A;;;;N;;;;; +FC37;ARABIC LIGATURE KAF WITH ALEF ISOLATED FORM;Lo;0;AL; 0643 0627;;;;N;;;;; +FC38;ARABIC LIGATURE KAF WITH JEEM ISOLATED FORM;Lo;0;AL; 0643 062C;;;;N;;;;; +FC39;ARABIC LIGATURE KAF WITH HAH ISOLATED FORM;Lo;0;AL; 0643 062D;;;;N;;;;; +FC3A;ARABIC LIGATURE KAF WITH KHAH ISOLATED FORM;Lo;0;AL; 0643 062E;;;;N;;;;; +FC3B;ARABIC LIGATURE KAF WITH LAM ISOLATED FORM;Lo;0;AL; 0643 0644;;;;N;;;;; +FC3C;ARABIC LIGATURE KAF WITH MEEM ISOLATED FORM;Lo;0;AL; 0643 0645;;;;N;;;;; +FC3D;ARABIC LIGATURE KAF WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0643 0649;;;;N;;;;; +FC3E;ARABIC LIGATURE KAF WITH YEH ISOLATED FORM;Lo;0;AL; 0643 064A;;;;N;;;;; +FC3F;ARABIC LIGATURE LAM WITH JEEM ISOLATED FORM;Lo;0;AL; 0644 062C;;;;N;;;;; +FC40;ARABIC LIGATURE LAM WITH HAH ISOLATED FORM;Lo;0;AL; 0644 062D;;;;N;;;;; +FC41;ARABIC LIGATURE LAM WITH KHAH ISOLATED FORM;Lo;0;AL; 0644 062E;;;;N;;;;; +FC42;ARABIC LIGATURE LAM WITH MEEM ISOLATED FORM;Lo;0;AL; 0644 0645;;;;N;;;;; +FC43;ARABIC LIGATURE LAM WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0644 0649;;;;N;;;;; +FC44;ARABIC LIGATURE LAM WITH YEH ISOLATED FORM;Lo;0;AL; 0644 064A;;;;N;;;;; +FC45;ARABIC LIGATURE MEEM WITH JEEM ISOLATED FORM;Lo;0;AL; 0645 062C;;;;N;;;;; +FC46;ARABIC LIGATURE MEEM WITH HAH ISOLATED FORM;Lo;0;AL; 0645 062D;;;;N;;;;; +FC47;ARABIC LIGATURE MEEM WITH KHAH ISOLATED FORM;Lo;0;AL; 0645 062E;;;;N;;;;; +FC48;ARABIC LIGATURE MEEM WITH MEEM ISOLATED FORM;Lo;0;AL; 0645 0645;;;;N;;;;; +FC49;ARABIC LIGATURE MEEM WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0645 0649;;;;N;;;;; +FC4A;ARABIC LIGATURE MEEM WITH YEH ISOLATED FORM;Lo;0;AL; 0645 064A;;;;N;;;;; +FC4B;ARABIC LIGATURE NOON WITH JEEM ISOLATED FORM;Lo;0;AL; 0646 062C;;;;N;;;;; +FC4C;ARABIC LIGATURE NOON WITH HAH ISOLATED FORM;Lo;0;AL; 0646 062D;;;;N;;;;; +FC4D;ARABIC LIGATURE NOON WITH KHAH ISOLATED FORM;Lo;0;AL; 0646 062E;;;;N;;;;; +FC4E;ARABIC LIGATURE NOON WITH MEEM ISOLATED FORM;Lo;0;AL; 0646 0645;;;;N;;;;; +FC4F;ARABIC LIGATURE NOON WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0646 0649;;;;N;;;;; +FC50;ARABIC LIGATURE NOON WITH YEH ISOLATED FORM;Lo;0;AL; 0646 064A;;;;N;;;;; +FC51;ARABIC LIGATURE HEH WITH JEEM ISOLATED FORM;Lo;0;AL; 0647 062C;;;;N;;;;; +FC52;ARABIC LIGATURE HEH WITH MEEM ISOLATED FORM;Lo;0;AL; 0647 0645;;;;N;;;;; +FC53;ARABIC LIGATURE HEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0647 0649;;;;N;;;;; +FC54;ARABIC LIGATURE HEH WITH YEH ISOLATED FORM;Lo;0;AL; 0647 064A;;;;N;;;;; +FC55;ARABIC LIGATURE YEH WITH JEEM ISOLATED FORM;Lo;0;AL; 064A 062C;;;;N;;;;; +FC56;ARABIC LIGATURE YEH WITH HAH ISOLATED FORM;Lo;0;AL; 064A 062D;;;;N;;;;; +FC57;ARABIC LIGATURE YEH WITH KHAH ISOLATED FORM;Lo;0;AL; 064A 062E;;;;N;;;;; +FC58;ARABIC LIGATURE YEH WITH MEEM ISOLATED FORM;Lo;0;AL; 064A 0645;;;;N;;;;; +FC59;ARABIC LIGATURE YEH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 064A 0649;;;;N;;;;; +FC5A;ARABIC LIGATURE YEH WITH YEH ISOLATED FORM;Lo;0;AL; 064A 064A;;;;N;;;;; +FC5B;ARABIC LIGATURE THAL WITH SUPERSCRIPT ALEF ISOLATED FORM;Lo;0;AL; 0630 0670;;;;N;;;;; +FC5C;ARABIC LIGATURE REH WITH SUPERSCRIPT ALEF ISOLATED FORM;Lo;0;AL; 0631 0670;;;;N;;;;; +FC5D;ARABIC LIGATURE ALEF MAKSURA WITH SUPERSCRIPT ALEF ISOLATED FORM;Lo;0;AL; 0649 0670;;;;N;;;;; +FC5E;ARABIC LIGATURE SHADDA WITH DAMMATAN ISOLATED FORM;Lo;0;AL; 0020 064C 0651;;;;N;;;;; +FC5F;ARABIC LIGATURE SHADDA WITH KASRATAN ISOLATED FORM;Lo;0;AL; 0020 064D 0651;;;;N;;;;; +FC60;ARABIC LIGATURE SHADDA WITH FATHA ISOLATED FORM;Lo;0;AL; 0020 064E 0651;;;;N;;;;; +FC61;ARABIC LIGATURE SHADDA WITH DAMMA ISOLATED FORM;Lo;0;AL; 0020 064F 0651;;;;N;;;;; +FC62;ARABIC LIGATURE SHADDA WITH KASRA ISOLATED FORM;Lo;0;AL; 0020 0650 0651;;;;N;;;;; +FC63;ARABIC LIGATURE SHADDA WITH SUPERSCRIPT ALEF ISOLATED FORM;Lo;0;AL; 0020 0651 0670;;;;N;;;;; +FC64;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH REH FINAL FORM;Lo;0;AL; 0626 0631;;;;N;;;;; +FC65;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ZAIN FINAL FORM;Lo;0;AL; 0626 0632;;;;N;;;;; +FC66;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM FINAL FORM;Lo;0;AL; 0626 0645;;;;N;;;;; +FC67;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH NOON FINAL FORM;Lo;0;AL; 0626 0646;;;;N;;;;; +FC68;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0626 0649;;;;N;;;;; +FC69;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH YEH FINAL FORM;Lo;0;AL; 0626 064A;;;;N;;;;; +FC6A;ARABIC LIGATURE BEH WITH REH FINAL FORM;Lo;0;AL; 0628 0631;;;;N;;;;; +FC6B;ARABIC LIGATURE BEH WITH ZAIN FINAL FORM;Lo;0;AL; 0628 0632;;;;N;;;;; +FC6C;ARABIC LIGATURE BEH WITH MEEM FINAL FORM;Lo;0;AL; 0628 0645;;;;N;;;;; +FC6D;ARABIC LIGATURE BEH WITH NOON FINAL FORM;Lo;0;AL; 0628 0646;;;;N;;;;; +FC6E;ARABIC LIGATURE BEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0628 0649;;;;N;;;;; +FC6F;ARABIC LIGATURE BEH WITH YEH FINAL FORM;Lo;0;AL; 0628 064A;;;;N;;;;; +FC70;ARABIC LIGATURE TEH WITH REH FINAL FORM;Lo;0;AL; 062A 0631;;;;N;;;;; +FC71;ARABIC LIGATURE TEH WITH ZAIN FINAL FORM;Lo;0;AL; 062A 0632;;;;N;;;;; +FC72;ARABIC LIGATURE TEH WITH MEEM FINAL FORM;Lo;0;AL; 062A 0645;;;;N;;;;; +FC73;ARABIC LIGATURE TEH WITH NOON FINAL FORM;Lo;0;AL; 062A 0646;;;;N;;;;; +FC74;ARABIC LIGATURE TEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062A 0649;;;;N;;;;; +FC75;ARABIC LIGATURE TEH WITH YEH FINAL FORM;Lo;0;AL; 062A 064A;;;;N;;;;; +FC76;ARABIC LIGATURE THEH WITH REH FINAL FORM;Lo;0;AL; 062B 0631;;;;N;;;;; +FC77;ARABIC LIGATURE THEH WITH ZAIN FINAL FORM;Lo;0;AL; 062B 0632;;;;N;;;;; +FC78;ARABIC LIGATURE THEH WITH MEEM FINAL FORM;Lo;0;AL; 062B 0645;;;;N;;;;; +FC79;ARABIC LIGATURE THEH WITH NOON FINAL FORM;Lo;0;AL; 062B 0646;;;;N;;;;; +FC7A;ARABIC LIGATURE THEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062B 0649;;;;N;;;;; +FC7B;ARABIC LIGATURE THEH WITH YEH FINAL FORM;Lo;0;AL; 062B 064A;;;;N;;;;; +FC7C;ARABIC LIGATURE FEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0641 0649;;;;N;;;;; +FC7D;ARABIC LIGATURE FEH WITH YEH FINAL FORM;Lo;0;AL; 0641 064A;;;;N;;;;; +FC7E;ARABIC LIGATURE QAF WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0642 0649;;;;N;;;;; +FC7F;ARABIC LIGATURE QAF WITH YEH FINAL FORM;Lo;0;AL; 0642 064A;;;;N;;;;; +FC80;ARABIC LIGATURE KAF WITH ALEF FINAL FORM;Lo;0;AL; 0643 0627;;;;N;;;;; +FC81;ARABIC LIGATURE KAF WITH LAM FINAL FORM;Lo;0;AL; 0643 0644;;;;N;;;;; +FC82;ARABIC LIGATURE KAF WITH MEEM FINAL FORM;Lo;0;AL; 0643 0645;;;;N;;;;; +FC83;ARABIC LIGATURE KAF WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0643 0649;;;;N;;;;; +FC84;ARABIC LIGATURE KAF WITH YEH FINAL FORM;Lo;0;AL; 0643 064A;;;;N;;;;; +FC85;ARABIC LIGATURE LAM WITH MEEM FINAL FORM;Lo;0;AL; 0644 0645;;;;N;;;;; +FC86;ARABIC LIGATURE LAM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0644 0649;;;;N;;;;; +FC87;ARABIC LIGATURE LAM WITH YEH FINAL FORM;Lo;0;AL; 0644 064A;;;;N;;;;; +FC88;ARABIC LIGATURE MEEM WITH ALEF FINAL FORM;Lo;0;AL; 0645 0627;;;;N;;;;; +FC89;ARABIC LIGATURE MEEM WITH MEEM FINAL FORM;Lo;0;AL; 0645 0645;;;;N;;;;; +FC8A;ARABIC LIGATURE NOON WITH REH FINAL FORM;Lo;0;AL; 0646 0631;;;;N;;;;; +FC8B;ARABIC LIGATURE NOON WITH ZAIN FINAL FORM;Lo;0;AL; 0646 0632;;;;N;;;;; +FC8C;ARABIC LIGATURE NOON WITH MEEM FINAL FORM;Lo;0;AL; 0646 0645;;;;N;;;;; +FC8D;ARABIC LIGATURE NOON WITH NOON FINAL FORM;Lo;0;AL; 0646 0646;;;;N;;;;; +FC8E;ARABIC LIGATURE NOON WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0646 0649;;;;N;;;;; +FC8F;ARABIC LIGATURE NOON WITH YEH FINAL FORM;Lo;0;AL; 0646 064A;;;;N;;;;; +FC90;ARABIC LIGATURE ALEF MAKSURA WITH SUPERSCRIPT ALEF FINAL FORM;Lo;0;AL; 0649 0670;;;;N;;;;; +FC91;ARABIC LIGATURE YEH WITH REH FINAL FORM;Lo;0;AL; 064A 0631;;;;N;;;;; +FC92;ARABIC LIGATURE YEH WITH ZAIN FINAL FORM;Lo;0;AL; 064A 0632;;;;N;;;;; +FC93;ARABIC LIGATURE YEH WITH MEEM FINAL FORM;Lo;0;AL; 064A 0645;;;;N;;;;; +FC94;ARABIC LIGATURE YEH WITH NOON FINAL FORM;Lo;0;AL; 064A 0646;;;;N;;;;; +FC95;ARABIC LIGATURE YEH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 064A 0649;;;;N;;;;; +FC96;ARABIC LIGATURE YEH WITH YEH FINAL FORM;Lo;0;AL; 064A 064A;;;;N;;;;; +FC97;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH JEEM INITIAL FORM;Lo;0;AL; 0626 062C;;;;N;;;;; +FC98;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HAH INITIAL FORM;Lo;0;AL; 0626 062D;;;;N;;;;; +FC99;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH KHAH INITIAL FORM;Lo;0;AL; 0626 062E;;;;N;;;;; +FC9A;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM INITIAL FORM;Lo;0;AL; 0626 0645;;;;N;;;;; +FC9B;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HEH INITIAL FORM;Lo;0;AL; 0626 0647;;;;N;;;;; +FC9C;ARABIC LIGATURE BEH WITH JEEM INITIAL FORM;Lo;0;AL; 0628 062C;;;;N;;;;; +FC9D;ARABIC LIGATURE BEH WITH HAH INITIAL FORM;Lo;0;AL; 0628 062D;;;;N;;;;; +FC9E;ARABIC LIGATURE BEH WITH KHAH INITIAL FORM;Lo;0;AL; 0628 062E;;;;N;;;;; +FC9F;ARABIC LIGATURE BEH WITH MEEM INITIAL FORM;Lo;0;AL; 0628 0645;;;;N;;;;; +FCA0;ARABIC LIGATURE BEH WITH HEH INITIAL FORM;Lo;0;AL; 0628 0647;;;;N;;;;; +FCA1;ARABIC LIGATURE TEH WITH JEEM INITIAL FORM;Lo;0;AL; 062A 062C;;;;N;;;;; +FCA2;ARABIC LIGATURE TEH WITH HAH INITIAL FORM;Lo;0;AL; 062A 062D;;;;N;;;;; +FCA3;ARABIC LIGATURE TEH WITH KHAH INITIAL FORM;Lo;0;AL; 062A 062E;;;;N;;;;; +FCA4;ARABIC LIGATURE TEH WITH MEEM INITIAL FORM;Lo;0;AL; 062A 0645;;;;N;;;;; +FCA5;ARABIC LIGATURE TEH WITH HEH INITIAL FORM;Lo;0;AL; 062A 0647;;;;N;;;;; +FCA6;ARABIC LIGATURE THEH WITH MEEM INITIAL FORM;Lo;0;AL; 062B 0645;;;;N;;;;; +FCA7;ARABIC LIGATURE JEEM WITH HAH INITIAL FORM;Lo;0;AL; 062C 062D;;;;N;;;;; +FCA8;ARABIC LIGATURE JEEM WITH MEEM INITIAL FORM;Lo;0;AL; 062C 0645;;;;N;;;;; +FCA9;ARABIC LIGATURE HAH WITH JEEM INITIAL FORM;Lo;0;AL; 062D 062C;;;;N;;;;; +FCAA;ARABIC LIGATURE HAH WITH MEEM INITIAL FORM;Lo;0;AL; 062D 0645;;;;N;;;;; +FCAB;ARABIC LIGATURE KHAH WITH JEEM INITIAL FORM;Lo;0;AL; 062E 062C;;;;N;;;;; +FCAC;ARABIC LIGATURE KHAH WITH MEEM INITIAL FORM;Lo;0;AL; 062E 0645;;;;N;;;;; +FCAD;ARABIC LIGATURE SEEN WITH JEEM INITIAL FORM;Lo;0;AL; 0633 062C;;;;N;;;;; +FCAE;ARABIC LIGATURE SEEN WITH HAH INITIAL FORM;Lo;0;AL; 0633 062D;;;;N;;;;; +FCAF;ARABIC LIGATURE SEEN WITH KHAH INITIAL FORM;Lo;0;AL; 0633 062E;;;;N;;;;; +FCB0;ARABIC LIGATURE SEEN WITH MEEM INITIAL FORM;Lo;0;AL; 0633 0645;;;;N;;;;; +FCB1;ARABIC LIGATURE SAD WITH HAH INITIAL FORM;Lo;0;AL; 0635 062D;;;;N;;;;; +FCB2;ARABIC LIGATURE SAD WITH KHAH INITIAL FORM;Lo;0;AL; 0635 062E;;;;N;;;;; +FCB3;ARABIC LIGATURE SAD WITH MEEM INITIAL FORM;Lo;0;AL; 0635 0645;;;;N;;;;; +FCB4;ARABIC LIGATURE DAD WITH JEEM INITIAL FORM;Lo;0;AL; 0636 062C;;;;N;;;;; +FCB5;ARABIC LIGATURE DAD WITH HAH INITIAL FORM;Lo;0;AL; 0636 062D;;;;N;;;;; +FCB6;ARABIC LIGATURE DAD WITH KHAH INITIAL FORM;Lo;0;AL; 0636 062E;;;;N;;;;; +FCB7;ARABIC LIGATURE DAD WITH MEEM INITIAL FORM;Lo;0;AL; 0636 0645;;;;N;;;;; +FCB8;ARABIC LIGATURE TAH WITH HAH INITIAL FORM;Lo;0;AL; 0637 062D;;;;N;;;;; +FCB9;ARABIC LIGATURE ZAH WITH MEEM INITIAL FORM;Lo;0;AL; 0638 0645;;;;N;;;;; +FCBA;ARABIC LIGATURE AIN WITH JEEM INITIAL FORM;Lo;0;AL; 0639 062C;;;;N;;;;; +FCBB;ARABIC LIGATURE AIN WITH MEEM INITIAL FORM;Lo;0;AL; 0639 0645;;;;N;;;;; +FCBC;ARABIC LIGATURE GHAIN WITH JEEM INITIAL FORM;Lo;0;AL; 063A 062C;;;;N;;;;; +FCBD;ARABIC LIGATURE GHAIN WITH MEEM INITIAL FORM;Lo;0;AL; 063A 0645;;;;N;;;;; +FCBE;ARABIC LIGATURE FEH WITH JEEM INITIAL FORM;Lo;0;AL; 0641 062C;;;;N;;;;; +FCBF;ARABIC LIGATURE FEH WITH HAH INITIAL FORM;Lo;0;AL; 0641 062D;;;;N;;;;; +FCC0;ARABIC LIGATURE FEH WITH KHAH INITIAL FORM;Lo;0;AL; 0641 062E;;;;N;;;;; +FCC1;ARABIC LIGATURE FEH WITH MEEM INITIAL FORM;Lo;0;AL; 0641 0645;;;;N;;;;; +FCC2;ARABIC LIGATURE QAF WITH HAH INITIAL FORM;Lo;0;AL; 0642 062D;;;;N;;;;; +FCC3;ARABIC LIGATURE QAF WITH MEEM INITIAL FORM;Lo;0;AL; 0642 0645;;;;N;;;;; +FCC4;ARABIC LIGATURE KAF WITH JEEM INITIAL FORM;Lo;0;AL; 0643 062C;;;;N;;;;; +FCC5;ARABIC LIGATURE KAF WITH HAH INITIAL FORM;Lo;0;AL; 0643 062D;;;;N;;;;; +FCC6;ARABIC LIGATURE KAF WITH KHAH INITIAL FORM;Lo;0;AL; 0643 062E;;;;N;;;;; +FCC7;ARABIC LIGATURE KAF WITH LAM INITIAL FORM;Lo;0;AL; 0643 0644;;;;N;;;;; +FCC8;ARABIC LIGATURE KAF WITH MEEM INITIAL FORM;Lo;0;AL; 0643 0645;;;;N;;;;; +FCC9;ARABIC LIGATURE LAM WITH JEEM INITIAL FORM;Lo;0;AL; 0644 062C;;;;N;;;;; +FCCA;ARABIC LIGATURE LAM WITH HAH INITIAL FORM;Lo;0;AL; 0644 062D;;;;N;;;;; +FCCB;ARABIC LIGATURE LAM WITH KHAH INITIAL FORM;Lo;0;AL; 0644 062E;;;;N;;;;; +FCCC;ARABIC LIGATURE LAM WITH MEEM INITIAL FORM;Lo;0;AL; 0644 0645;;;;N;;;;; +FCCD;ARABIC LIGATURE LAM WITH HEH INITIAL FORM;Lo;0;AL; 0644 0647;;;;N;;;;; +FCCE;ARABIC LIGATURE MEEM WITH JEEM INITIAL FORM;Lo;0;AL; 0645 062C;;;;N;;;;; +FCCF;ARABIC LIGATURE MEEM WITH HAH INITIAL FORM;Lo;0;AL; 0645 062D;;;;N;;;;; +FCD0;ARABIC LIGATURE MEEM WITH KHAH INITIAL FORM;Lo;0;AL; 0645 062E;;;;N;;;;; +FCD1;ARABIC LIGATURE MEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0645 0645;;;;N;;;;; +FCD2;ARABIC LIGATURE NOON WITH JEEM INITIAL FORM;Lo;0;AL; 0646 062C;;;;N;;;;; +FCD3;ARABIC LIGATURE NOON WITH HAH INITIAL FORM;Lo;0;AL; 0646 062D;;;;N;;;;; +FCD4;ARABIC LIGATURE NOON WITH KHAH INITIAL FORM;Lo;0;AL; 0646 062E;;;;N;;;;; +FCD5;ARABIC LIGATURE NOON WITH MEEM INITIAL FORM;Lo;0;AL; 0646 0645;;;;N;;;;; +FCD6;ARABIC LIGATURE NOON WITH HEH INITIAL FORM;Lo;0;AL; 0646 0647;;;;N;;;;; +FCD7;ARABIC LIGATURE HEH WITH JEEM INITIAL FORM;Lo;0;AL; 0647 062C;;;;N;;;;; +FCD8;ARABIC LIGATURE HEH WITH MEEM INITIAL FORM;Lo;0;AL; 0647 0645;;;;N;;;;; +FCD9;ARABIC LIGATURE HEH WITH SUPERSCRIPT ALEF INITIAL FORM;Lo;0;AL; 0647 0670;;;;N;;;;; +FCDA;ARABIC LIGATURE YEH WITH JEEM INITIAL FORM;Lo;0;AL; 064A 062C;;;;N;;;;; +FCDB;ARABIC LIGATURE YEH WITH HAH INITIAL FORM;Lo;0;AL; 064A 062D;;;;N;;;;; +FCDC;ARABIC LIGATURE YEH WITH KHAH INITIAL FORM;Lo;0;AL; 064A 062E;;;;N;;;;; +FCDD;ARABIC LIGATURE YEH WITH MEEM INITIAL FORM;Lo;0;AL; 064A 0645;;;;N;;;;; +FCDE;ARABIC LIGATURE YEH WITH HEH INITIAL FORM;Lo;0;AL; 064A 0647;;;;N;;;;; +FCDF;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH MEEM MEDIAL FORM;Lo;0;AL; 0626 0645;;;;N;;;;; +FCE0;ARABIC LIGATURE YEH WITH HAMZA ABOVE WITH HEH MEDIAL FORM;Lo;0;AL; 0626 0647;;;;N;;;;; +FCE1;ARABIC LIGATURE BEH WITH MEEM MEDIAL FORM;Lo;0;AL; 0628 0645;;;;N;;;;; +FCE2;ARABIC LIGATURE BEH WITH HEH MEDIAL FORM;Lo;0;AL; 0628 0647;;;;N;;;;; +FCE3;ARABIC LIGATURE TEH WITH MEEM MEDIAL FORM;Lo;0;AL; 062A 0645;;;;N;;;;; +FCE4;ARABIC LIGATURE TEH WITH HEH MEDIAL FORM;Lo;0;AL; 062A 0647;;;;N;;;;; +FCE5;ARABIC LIGATURE THEH WITH MEEM MEDIAL FORM;Lo;0;AL; 062B 0645;;;;N;;;;; +FCE6;ARABIC LIGATURE THEH WITH HEH MEDIAL FORM;Lo;0;AL; 062B 0647;;;;N;;;;; +FCE7;ARABIC LIGATURE SEEN WITH MEEM MEDIAL FORM;Lo;0;AL; 0633 0645;;;;N;;;;; +FCE8;ARABIC LIGATURE SEEN WITH HEH MEDIAL FORM;Lo;0;AL; 0633 0647;;;;N;;;;; +FCE9;ARABIC LIGATURE SHEEN WITH MEEM MEDIAL FORM;Lo;0;AL; 0634 0645;;;;N;;;;; +FCEA;ARABIC LIGATURE SHEEN WITH HEH MEDIAL FORM;Lo;0;AL; 0634 0647;;;;N;;;;; +FCEB;ARABIC LIGATURE KAF WITH LAM MEDIAL FORM;Lo;0;AL; 0643 0644;;;;N;;;;; +FCEC;ARABIC LIGATURE KAF WITH MEEM MEDIAL FORM;Lo;0;AL; 0643 0645;;;;N;;;;; +FCED;ARABIC LIGATURE LAM WITH MEEM MEDIAL FORM;Lo;0;AL; 0644 0645;;;;N;;;;; +FCEE;ARABIC LIGATURE NOON WITH MEEM MEDIAL FORM;Lo;0;AL; 0646 0645;;;;N;;;;; +FCEF;ARABIC LIGATURE NOON WITH HEH MEDIAL FORM;Lo;0;AL; 0646 0647;;;;N;;;;; +FCF0;ARABIC LIGATURE YEH WITH MEEM MEDIAL FORM;Lo;0;AL; 064A 0645;;;;N;;;;; +FCF1;ARABIC LIGATURE YEH WITH HEH MEDIAL FORM;Lo;0;AL; 064A 0647;;;;N;;;;; +FCF2;ARABIC LIGATURE SHADDA WITH FATHA MEDIAL FORM;Lo;0;AL; 0640 064E 0651;;;;N;;;;; +FCF3;ARABIC LIGATURE SHADDA WITH DAMMA MEDIAL FORM;Lo;0;AL; 0640 064F 0651;;;;N;;;;; +FCF4;ARABIC LIGATURE SHADDA WITH KASRA MEDIAL FORM;Lo;0;AL; 0640 0650 0651;;;;N;;;;; +FCF5;ARABIC LIGATURE TAH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0637 0649;;;;N;;;;; +FCF6;ARABIC LIGATURE TAH WITH YEH ISOLATED FORM;Lo;0;AL; 0637 064A;;;;N;;;;; +FCF7;ARABIC LIGATURE AIN WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0639 0649;;;;N;;;;; +FCF8;ARABIC LIGATURE AIN WITH YEH ISOLATED FORM;Lo;0;AL; 0639 064A;;;;N;;;;; +FCF9;ARABIC LIGATURE GHAIN WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 063A 0649;;;;N;;;;; +FCFA;ARABIC LIGATURE GHAIN WITH YEH ISOLATED FORM;Lo;0;AL; 063A 064A;;;;N;;;;; +FCFB;ARABIC LIGATURE SEEN WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0633 0649;;;;N;;;;; +FCFC;ARABIC LIGATURE SEEN WITH YEH ISOLATED FORM;Lo;0;AL; 0633 064A;;;;N;;;;; +FCFD;ARABIC LIGATURE SHEEN WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0634 0649;;;;N;;;;; +FCFE;ARABIC LIGATURE SHEEN WITH YEH ISOLATED FORM;Lo;0;AL; 0634 064A;;;;N;;;;; +FCFF;ARABIC LIGATURE HAH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 062D 0649;;;;N;;;;; +FD00;ARABIC LIGATURE HAH WITH YEH ISOLATED FORM;Lo;0;AL; 062D 064A;;;;N;;;;; +FD01;ARABIC LIGATURE JEEM WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 062C 0649;;;;N;;;;; +FD02;ARABIC LIGATURE JEEM WITH YEH ISOLATED FORM;Lo;0;AL; 062C 064A;;;;N;;;;; +FD03;ARABIC LIGATURE KHAH WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 062E 0649;;;;N;;;;; +FD04;ARABIC LIGATURE KHAH WITH YEH ISOLATED FORM;Lo;0;AL; 062E 064A;;;;N;;;;; +FD05;ARABIC LIGATURE SAD WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0635 0649;;;;N;;;;; +FD06;ARABIC LIGATURE SAD WITH YEH ISOLATED FORM;Lo;0;AL; 0635 064A;;;;N;;;;; +FD07;ARABIC LIGATURE DAD WITH ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0636 0649;;;;N;;;;; +FD08;ARABIC LIGATURE DAD WITH YEH ISOLATED FORM;Lo;0;AL; 0636 064A;;;;N;;;;; +FD09;ARABIC LIGATURE SHEEN WITH JEEM ISOLATED FORM;Lo;0;AL; 0634 062C;;;;N;;;;; +FD0A;ARABIC LIGATURE SHEEN WITH HAH ISOLATED FORM;Lo;0;AL; 0634 062D;;;;N;;;;; +FD0B;ARABIC LIGATURE SHEEN WITH KHAH ISOLATED FORM;Lo;0;AL; 0634 062E;;;;N;;;;; +FD0C;ARABIC LIGATURE SHEEN WITH MEEM ISOLATED FORM;Lo;0;AL; 0634 0645;;;;N;;;;; +FD0D;ARABIC LIGATURE SHEEN WITH REH ISOLATED FORM;Lo;0;AL; 0634 0631;;;;N;;;;; +FD0E;ARABIC LIGATURE SEEN WITH REH ISOLATED FORM;Lo;0;AL; 0633 0631;;;;N;;;;; +FD0F;ARABIC LIGATURE SAD WITH REH ISOLATED FORM;Lo;0;AL; 0635 0631;;;;N;;;;; +FD10;ARABIC LIGATURE DAD WITH REH ISOLATED FORM;Lo;0;AL; 0636 0631;;;;N;;;;; +FD11;ARABIC LIGATURE TAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0637 0649;;;;N;;;;; +FD12;ARABIC LIGATURE TAH WITH YEH FINAL FORM;Lo;0;AL; 0637 064A;;;;N;;;;; +FD13;ARABIC LIGATURE AIN WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0639 0649;;;;N;;;;; +FD14;ARABIC LIGATURE AIN WITH YEH FINAL FORM;Lo;0;AL; 0639 064A;;;;N;;;;; +FD15;ARABIC LIGATURE GHAIN WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 063A 0649;;;;N;;;;; +FD16;ARABIC LIGATURE GHAIN WITH YEH FINAL FORM;Lo;0;AL; 063A 064A;;;;N;;;;; +FD17;ARABIC LIGATURE SEEN WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0633 0649;;;;N;;;;; +FD18;ARABIC LIGATURE SEEN WITH YEH FINAL FORM;Lo;0;AL; 0633 064A;;;;N;;;;; +FD19;ARABIC LIGATURE SHEEN WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0634 0649;;;;N;;;;; +FD1A;ARABIC LIGATURE SHEEN WITH YEH FINAL FORM;Lo;0;AL; 0634 064A;;;;N;;;;; +FD1B;ARABIC LIGATURE HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062D 0649;;;;N;;;;; +FD1C;ARABIC LIGATURE HAH WITH YEH FINAL FORM;Lo;0;AL; 062D 064A;;;;N;;;;; +FD1D;ARABIC LIGATURE JEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062C 0649;;;;N;;;;; +FD1E;ARABIC LIGATURE JEEM WITH YEH FINAL FORM;Lo;0;AL; 062C 064A;;;;N;;;;; +FD1F;ARABIC LIGATURE KHAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062E 0649;;;;N;;;;; +FD20;ARABIC LIGATURE KHAH WITH YEH FINAL FORM;Lo;0;AL; 062E 064A;;;;N;;;;; +FD21;ARABIC LIGATURE SAD WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0635 0649;;;;N;;;;; +FD22;ARABIC LIGATURE SAD WITH YEH FINAL FORM;Lo;0;AL; 0635 064A;;;;N;;;;; +FD23;ARABIC LIGATURE DAD WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0636 0649;;;;N;;;;; +FD24;ARABIC LIGATURE DAD WITH YEH FINAL FORM;Lo;0;AL; 0636 064A;;;;N;;;;; +FD25;ARABIC LIGATURE SHEEN WITH JEEM FINAL FORM;Lo;0;AL; 0634 062C;;;;N;;;;; +FD26;ARABIC LIGATURE SHEEN WITH HAH FINAL FORM;Lo;0;AL; 0634 062D;;;;N;;;;; +FD27;ARABIC LIGATURE SHEEN WITH KHAH FINAL FORM;Lo;0;AL; 0634 062E;;;;N;;;;; +FD28;ARABIC LIGATURE SHEEN WITH MEEM FINAL FORM;Lo;0;AL; 0634 0645;;;;N;;;;; +FD29;ARABIC LIGATURE SHEEN WITH REH FINAL FORM;Lo;0;AL; 0634 0631;;;;N;;;;; +FD2A;ARABIC LIGATURE SEEN WITH REH FINAL FORM;Lo;0;AL; 0633 0631;;;;N;;;;; +FD2B;ARABIC LIGATURE SAD WITH REH FINAL FORM;Lo;0;AL; 0635 0631;;;;N;;;;; +FD2C;ARABIC LIGATURE DAD WITH REH FINAL FORM;Lo;0;AL; 0636 0631;;;;N;;;;; +FD2D;ARABIC LIGATURE SHEEN WITH JEEM INITIAL FORM;Lo;0;AL; 0634 062C;;;;N;;;;; +FD2E;ARABIC LIGATURE SHEEN WITH HAH INITIAL FORM;Lo;0;AL; 0634 062D;;;;N;;;;; +FD2F;ARABIC LIGATURE SHEEN WITH KHAH INITIAL FORM;Lo;0;AL; 0634 062E;;;;N;;;;; +FD30;ARABIC LIGATURE SHEEN WITH MEEM INITIAL FORM;Lo;0;AL; 0634 0645;;;;N;;;;; +FD31;ARABIC LIGATURE SEEN WITH HEH INITIAL FORM;Lo;0;AL; 0633 0647;;;;N;;;;; +FD32;ARABIC LIGATURE SHEEN WITH HEH INITIAL FORM;Lo;0;AL; 0634 0647;;;;N;;;;; +FD33;ARABIC LIGATURE TAH WITH MEEM INITIAL FORM;Lo;0;AL; 0637 0645;;;;N;;;;; +FD34;ARABIC LIGATURE SEEN WITH JEEM MEDIAL FORM;Lo;0;AL; 0633 062C;;;;N;;;;; +FD35;ARABIC LIGATURE SEEN WITH HAH MEDIAL FORM;Lo;0;AL; 0633 062D;;;;N;;;;; +FD36;ARABIC LIGATURE SEEN WITH KHAH MEDIAL FORM;Lo;0;AL; 0633 062E;;;;N;;;;; +FD37;ARABIC LIGATURE SHEEN WITH JEEM MEDIAL FORM;Lo;0;AL; 0634 062C;;;;N;;;;; +FD38;ARABIC LIGATURE SHEEN WITH HAH MEDIAL FORM;Lo;0;AL; 0634 062D;;;;N;;;;; +FD39;ARABIC LIGATURE SHEEN WITH KHAH MEDIAL FORM;Lo;0;AL; 0634 062E;;;;N;;;;; +FD3A;ARABIC LIGATURE TAH WITH MEEM MEDIAL FORM;Lo;0;AL; 0637 0645;;;;N;;;;; +FD3B;ARABIC LIGATURE ZAH WITH MEEM MEDIAL FORM;Lo;0;AL; 0638 0645;;;;N;;;;; +FD3C;ARABIC LIGATURE ALEF WITH FATHATAN FINAL FORM;Lo;0;AL; 0627 064B;;;;N;;;;; +FD3D;ARABIC LIGATURE ALEF WITH FATHATAN ISOLATED FORM;Lo;0;AL; 0627 064B;;;;N;;;;; +FD3E;ORNATE LEFT PARENTHESIS;Ps;0;ON;;;;;N;;;;; +FD3F;ORNATE RIGHT PARENTHESIS;Pe;0;ON;;;;;N;;;;; +FD50;ARABIC LIGATURE TEH WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL; 062A 062C 0645;;;;N;;;;; +FD51;ARABIC LIGATURE TEH WITH HAH WITH JEEM FINAL FORM;Lo;0;AL; 062A 062D 062C;;;;N;;;;; +FD52;ARABIC LIGATURE TEH WITH HAH WITH JEEM INITIAL FORM;Lo;0;AL; 062A 062D 062C;;;;N;;;;; +FD53;ARABIC LIGATURE TEH WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL; 062A 062D 0645;;;;N;;;;; +FD54;ARABIC LIGATURE TEH WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL; 062A 062E 0645;;;;N;;;;; +FD55;ARABIC LIGATURE TEH WITH MEEM WITH JEEM INITIAL FORM;Lo;0;AL; 062A 0645 062C;;;;N;;;;; +FD56;ARABIC LIGATURE TEH WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL; 062A 0645 062D;;;;N;;;;; +FD57;ARABIC LIGATURE TEH WITH MEEM WITH KHAH INITIAL FORM;Lo;0;AL; 062A 0645 062E;;;;N;;;;; +FD58;ARABIC LIGATURE JEEM WITH MEEM WITH HAH FINAL FORM;Lo;0;AL; 062C 0645 062D;;;;N;;;;; +FD59;ARABIC LIGATURE JEEM WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL; 062C 0645 062D;;;;N;;;;; +FD5A;ARABIC LIGATURE HAH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 062D 0645 064A;;;;N;;;;; +FD5B;ARABIC LIGATURE HAH WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062D 0645 0649;;;;N;;;;; +FD5C;ARABIC LIGATURE SEEN WITH HAH WITH JEEM INITIAL FORM;Lo;0;AL; 0633 062D 062C;;;;N;;;;; +FD5D;ARABIC LIGATURE SEEN WITH JEEM WITH HAH INITIAL FORM;Lo;0;AL; 0633 062C 062D;;;;N;;;;; +FD5E;ARABIC LIGATURE SEEN WITH JEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0633 062C 0649;;;;N;;;;; +FD5F;ARABIC LIGATURE SEEN WITH MEEM WITH HAH FINAL FORM;Lo;0;AL; 0633 0645 062D;;;;N;;;;; +FD60;ARABIC LIGATURE SEEN WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL; 0633 0645 062D;;;;N;;;;; +FD61;ARABIC LIGATURE SEEN WITH MEEM WITH JEEM INITIAL FORM;Lo;0;AL; 0633 0645 062C;;;;N;;;;; +FD62;ARABIC LIGATURE SEEN WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL; 0633 0645 0645;;;;N;;;;; +FD63;ARABIC LIGATURE SEEN WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0633 0645 0645;;;;N;;;;; +FD64;ARABIC LIGATURE SAD WITH HAH WITH HAH FINAL FORM;Lo;0;AL; 0635 062D 062D;;;;N;;;;; +FD65;ARABIC LIGATURE SAD WITH HAH WITH HAH INITIAL FORM;Lo;0;AL; 0635 062D 062D;;;;N;;;;; +FD66;ARABIC LIGATURE SAD WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL; 0635 0645 0645;;;;N;;;;; +FD67;ARABIC LIGATURE SHEEN WITH HAH WITH MEEM FINAL FORM;Lo;0;AL; 0634 062D 0645;;;;N;;;;; +FD68;ARABIC LIGATURE SHEEN WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL; 0634 062D 0645;;;;N;;;;; +FD69;ARABIC LIGATURE SHEEN WITH JEEM WITH YEH FINAL FORM;Lo;0;AL; 0634 062C 064A;;;;N;;;;; +FD6A;ARABIC LIGATURE SHEEN WITH MEEM WITH KHAH FINAL FORM;Lo;0;AL; 0634 0645 062E;;;;N;;;;; +FD6B;ARABIC LIGATURE SHEEN WITH MEEM WITH KHAH INITIAL FORM;Lo;0;AL; 0634 0645 062E;;;;N;;;;; +FD6C;ARABIC LIGATURE SHEEN WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL; 0634 0645 0645;;;;N;;;;; +FD6D;ARABIC LIGATURE SHEEN WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0634 0645 0645;;;;N;;;;; +FD6E;ARABIC LIGATURE DAD WITH HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0636 062D 0649;;;;N;;;;; +FD6F;ARABIC LIGATURE DAD WITH KHAH WITH MEEM FINAL FORM;Lo;0;AL; 0636 062E 0645;;;;N;;;;; +FD70;ARABIC LIGATURE DAD WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL; 0636 062E 0645;;;;N;;;;; +FD71;ARABIC LIGATURE TAH WITH MEEM WITH HAH FINAL FORM;Lo;0;AL; 0637 0645 062D;;;;N;;;;; +FD72;ARABIC LIGATURE TAH WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL; 0637 0645 062D;;;;N;;;;; +FD73;ARABIC LIGATURE TAH WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0637 0645 0645;;;;N;;;;; +FD74;ARABIC LIGATURE TAH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 0637 0645 064A;;;;N;;;;; +FD75;ARABIC LIGATURE AIN WITH JEEM WITH MEEM FINAL FORM;Lo;0;AL; 0639 062C 0645;;;;N;;;;; +FD76;ARABIC LIGATURE AIN WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL; 0639 0645 0645;;;;N;;;;; +FD77;ARABIC LIGATURE AIN WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0639 0645 0645;;;;N;;;;; +FD78;ARABIC LIGATURE AIN WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0639 0645 0649;;;;N;;;;; +FD79;ARABIC LIGATURE GHAIN WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL; 063A 0645 0645;;;;N;;;;; +FD7A;ARABIC LIGATURE GHAIN WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 063A 0645 064A;;;;N;;;;; +FD7B;ARABIC LIGATURE GHAIN WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 063A 0645 0649;;;;N;;;;; +FD7C;ARABIC LIGATURE FEH WITH KHAH WITH MEEM FINAL FORM;Lo;0;AL; 0641 062E 0645;;;;N;;;;; +FD7D;ARABIC LIGATURE FEH WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL; 0641 062E 0645;;;;N;;;;; +FD7E;ARABIC LIGATURE QAF WITH MEEM WITH HAH FINAL FORM;Lo;0;AL; 0642 0645 062D;;;;N;;;;; +FD7F;ARABIC LIGATURE QAF WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL; 0642 0645 0645;;;;N;;;;; +FD80;ARABIC LIGATURE LAM WITH HAH WITH MEEM FINAL FORM;Lo;0;AL; 0644 062D 0645;;;;N;;;;; +FD81;ARABIC LIGATURE LAM WITH HAH WITH YEH FINAL FORM;Lo;0;AL; 0644 062D 064A;;;;N;;;;; +FD82;ARABIC LIGATURE LAM WITH HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0644 062D 0649;;;;N;;;;; +FD83;ARABIC LIGATURE LAM WITH JEEM WITH JEEM INITIAL FORM;Lo;0;AL; 0644 062C 062C;;;;N;;;;; +FD84;ARABIC LIGATURE LAM WITH JEEM WITH JEEM FINAL FORM;Lo;0;AL; 0644 062C 062C;;;;N;;;;; +FD85;ARABIC LIGATURE LAM WITH KHAH WITH MEEM FINAL FORM;Lo;0;AL; 0644 062E 0645;;;;N;;;;; +FD86;ARABIC LIGATURE LAM WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL; 0644 062E 0645;;;;N;;;;; +FD87;ARABIC LIGATURE LAM WITH MEEM WITH HAH FINAL FORM;Lo;0;AL; 0644 0645 062D;;;;N;;;;; +FD88;ARABIC LIGATURE LAM WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL; 0644 0645 062D;;;;N;;;;; +FD89;ARABIC LIGATURE MEEM WITH HAH WITH JEEM INITIAL FORM;Lo;0;AL; 0645 062D 062C;;;;N;;;;; +FD8A;ARABIC LIGATURE MEEM WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL; 0645 062D 0645;;;;N;;;;; +FD8B;ARABIC LIGATURE MEEM WITH HAH WITH YEH FINAL FORM;Lo;0;AL; 0645 062D 064A;;;;N;;;;; +FD8C;ARABIC LIGATURE MEEM WITH JEEM WITH HAH INITIAL FORM;Lo;0;AL; 0645 062C 062D;;;;N;;;;; +FD8D;ARABIC LIGATURE MEEM WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0645 062C 0645;;;;N;;;;; +FD8E;ARABIC LIGATURE MEEM WITH KHAH WITH JEEM INITIAL FORM;Lo;0;AL; 0645 062E 062C;;;;N;;;;; +FD8F;ARABIC LIGATURE MEEM WITH KHAH WITH MEEM INITIAL FORM;Lo;0;AL; 0645 062E 0645;;;;N;;;;; +FD92;ARABIC LIGATURE MEEM WITH JEEM WITH KHAH INITIAL FORM;Lo;0;AL; 0645 062C 062E;;;;N;;;;; +FD93;ARABIC LIGATURE HEH WITH MEEM WITH JEEM INITIAL FORM;Lo;0;AL; 0647 0645 062C;;;;N;;;;; +FD94;ARABIC LIGATURE HEH WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0647 0645 0645;;;;N;;;;; +FD95;ARABIC LIGATURE NOON WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL; 0646 062D 0645;;;;N;;;;; +FD96;ARABIC LIGATURE NOON WITH HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0646 062D 0649;;;;N;;;;; +FD97;ARABIC LIGATURE NOON WITH JEEM WITH MEEM FINAL FORM;Lo;0;AL; 0646 062C 0645;;;;N;;;;; +FD98;ARABIC LIGATURE NOON WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0646 062C 0645;;;;N;;;;; +FD99;ARABIC LIGATURE NOON WITH JEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0646 062C 0649;;;;N;;;;; +FD9A;ARABIC LIGATURE NOON WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 0646 0645 064A;;;;N;;;;; +FD9B;ARABIC LIGATURE NOON WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0646 0645 0649;;;;N;;;;; +FD9C;ARABIC LIGATURE YEH WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL; 064A 0645 0645;;;;N;;;;; +FD9D;ARABIC LIGATURE YEH WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL; 064A 0645 0645;;;;N;;;;; +FD9E;ARABIC LIGATURE BEH WITH KHAH WITH YEH FINAL FORM;Lo;0;AL; 0628 062E 064A;;;;N;;;;; +FD9F;ARABIC LIGATURE TEH WITH JEEM WITH YEH FINAL FORM;Lo;0;AL; 062A 062C 064A;;;;N;;;;; +FDA0;ARABIC LIGATURE TEH WITH JEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062A 062C 0649;;;;N;;;;; +FDA1;ARABIC LIGATURE TEH WITH KHAH WITH YEH FINAL FORM;Lo;0;AL; 062A 062E 064A;;;;N;;;;; +FDA2;ARABIC LIGATURE TEH WITH KHAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062A 062E 0649;;;;N;;;;; +FDA3;ARABIC LIGATURE TEH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 062A 0645 064A;;;;N;;;;; +FDA4;ARABIC LIGATURE TEH WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062A 0645 0649;;;;N;;;;; +FDA5;ARABIC LIGATURE JEEM WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 062C 0645 064A;;;;N;;;;; +FDA6;ARABIC LIGATURE JEEM WITH HAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062C 062D 0649;;;;N;;;;; +FDA7;ARABIC LIGATURE JEEM WITH MEEM WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 062C 0645 0649;;;;N;;;;; +FDA8;ARABIC LIGATURE SEEN WITH KHAH WITH ALEF MAKSURA FINAL FORM;Lo;0;AL; 0633 062E 0649;;;;N;;;;; +FDA9;ARABIC LIGATURE SAD WITH HAH WITH YEH FINAL FORM;Lo;0;AL; 0635 062D 064A;;;;N;;;;; +FDAA;ARABIC LIGATURE SHEEN WITH HAH WITH YEH FINAL FORM;Lo;0;AL; 0634 062D 064A;;;;N;;;;; +FDAB;ARABIC LIGATURE DAD WITH HAH WITH YEH FINAL FORM;Lo;0;AL; 0636 062D 064A;;;;N;;;;; +FDAC;ARABIC LIGATURE LAM WITH JEEM WITH YEH FINAL FORM;Lo;0;AL; 0644 062C 064A;;;;N;;;;; +FDAD;ARABIC LIGATURE LAM WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 0644 0645 064A;;;;N;;;;; +FDAE;ARABIC LIGATURE YEH WITH HAH WITH YEH FINAL FORM;Lo;0;AL; 064A 062D 064A;;;;N;;;;; +FDAF;ARABIC LIGATURE YEH WITH JEEM WITH YEH FINAL FORM;Lo;0;AL; 064A 062C 064A;;;;N;;;;; +FDB0;ARABIC LIGATURE YEH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 064A 0645 064A;;;;N;;;;; +FDB1;ARABIC LIGATURE MEEM WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 0645 0645 064A;;;;N;;;;; +FDB2;ARABIC LIGATURE QAF WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 0642 0645 064A;;;;N;;;;; +FDB3;ARABIC LIGATURE NOON WITH HAH WITH YEH FINAL FORM;Lo;0;AL; 0646 062D 064A;;;;N;;;;; +FDB4;ARABIC LIGATURE QAF WITH MEEM WITH HAH INITIAL FORM;Lo;0;AL; 0642 0645 062D;;;;N;;;;; +FDB5;ARABIC LIGATURE LAM WITH HAH WITH MEEM INITIAL FORM;Lo;0;AL; 0644 062D 0645;;;;N;;;;; +FDB6;ARABIC LIGATURE AIN WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 0639 0645 064A;;;;N;;;;; +FDB7;ARABIC LIGATURE KAF WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 0643 0645 064A;;;;N;;;;; +FDB8;ARABIC LIGATURE NOON WITH JEEM WITH HAH INITIAL FORM;Lo;0;AL; 0646 062C 062D;;;;N;;;;; +FDB9;ARABIC LIGATURE MEEM WITH KHAH WITH YEH FINAL FORM;Lo;0;AL; 0645 062E 064A;;;;N;;;;; +FDBA;ARABIC LIGATURE LAM WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0644 062C 0645;;;;N;;;;; +FDBB;ARABIC LIGATURE KAF WITH MEEM WITH MEEM FINAL FORM;Lo;0;AL; 0643 0645 0645;;;;N;;;;; +FDBC;ARABIC LIGATURE LAM WITH JEEM WITH MEEM FINAL FORM;Lo;0;AL; 0644 062C 0645;;;;N;;;;; +FDBD;ARABIC LIGATURE NOON WITH JEEM WITH HAH FINAL FORM;Lo;0;AL; 0646 062C 062D;;;;N;;;;; +FDBE;ARABIC LIGATURE JEEM WITH HAH WITH YEH FINAL FORM;Lo;0;AL; 062C 062D 064A;;;;N;;;;; +FDBF;ARABIC LIGATURE HAH WITH JEEM WITH YEH FINAL FORM;Lo;0;AL; 062D 062C 064A;;;;N;;;;; +FDC0;ARABIC LIGATURE MEEM WITH JEEM WITH YEH FINAL FORM;Lo;0;AL; 0645 062C 064A;;;;N;;;;; +FDC1;ARABIC LIGATURE FEH WITH MEEM WITH YEH FINAL FORM;Lo;0;AL; 0641 0645 064A;;;;N;;;;; +FDC2;ARABIC LIGATURE BEH WITH HAH WITH YEH FINAL FORM;Lo;0;AL; 0628 062D 064A;;;;N;;;;; +FDC3;ARABIC LIGATURE KAF WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0643 0645 0645;;;;N;;;;; +FDC4;ARABIC LIGATURE AIN WITH JEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0639 062C 0645;;;;N;;;;; +FDC5;ARABIC LIGATURE SAD WITH MEEM WITH MEEM INITIAL FORM;Lo;0;AL; 0635 0645 0645;;;;N;;;;; +FDC6;ARABIC LIGATURE SEEN WITH KHAH WITH YEH FINAL FORM;Lo;0;AL; 0633 062E 064A;;;;N;;;;; +FDC7;ARABIC LIGATURE NOON WITH JEEM WITH YEH FINAL FORM;Lo;0;AL; 0646 062C 064A;;;;N;;;;; +FDF0;ARABIC LIGATURE SALLA USED AS KORANIC STOP SIGN ISOLATED FORM;Lo;0;AL; 0635 0644 06D2;;;;N;;;;; +FDF1;ARABIC LIGATURE QALA USED AS KORANIC STOP SIGN ISOLATED FORM;Lo;0;AL; 0642 0644 06D2;;;;N;;;;; +FDF2;ARABIC LIGATURE ALLAH ISOLATED FORM;Lo;0;AL; 0627 0644 0644 0647;;;;N;;;;; +FDF3;ARABIC LIGATURE AKBAR ISOLATED FORM;Lo;0;AL; 0627 0643 0628 0631;;;;N;;;;; +FDF4;ARABIC LIGATURE MOHAMMAD ISOLATED FORM;Lo;0;AL; 0645 062D 0645 062F;;;;N;;;;; +FDF5;ARABIC LIGATURE SALAM ISOLATED FORM;Lo;0;AL; 0635 0644 0639 0645;;;;N;;;;; +FDF6;ARABIC LIGATURE RASOUL ISOLATED FORM;Lo;0;AL; 0631 0633 0648 0644;;;;N;;;;; +FDF7;ARABIC LIGATURE ALAYHE ISOLATED FORM;Lo;0;AL; 0639 0644 064A 0647;;;;N;;;;; +FDF8;ARABIC LIGATURE WASALLAM ISOLATED FORM;Lo;0;AL; 0648 0633 0644 0645;;;;N;;;;; +FDF9;ARABIC LIGATURE SALLA ISOLATED FORM;Lo;0;AL; 0635 0644 0649;;;;N;;;;; +FDFA;ARABIC LIGATURE SALLALLAHOU ALAYHE WASALLAM;Lo;0;AL; 0635 0644 0649 0020 0627 0644 0644 0647 0020 0639 0644 064A 0647 0020 0648 0633 0644 0645;;;;N;ARABIC LETTER SALLALLAHOU ALAYHE WASALLAM;;;; +FDFB;ARABIC LIGATURE JALLAJALALOUHOU;Lo;0;AL; 062C 0644 0020 062C 0644 0627 0644 0647;;;;N;ARABIC LETTER JALLAJALALOUHOU;;;; +FDFC;RIAL SIGN;Sc;0;AL; 0631 06CC 0627 0644;;;;N;;;;; +FDFD;ARABIC LIGATURE BISMILLAH AR-RAHMAN AR-RAHEEM;So;0;ON;;;;;N;;;;; +FE00;VARIATION SELECTOR-1;Mn;0;NSM;;;;;N;;;;; +FE01;VARIATION SELECTOR-2;Mn;0;NSM;;;;;N;;;;; +FE02;VARIATION SELECTOR-3;Mn;0;NSM;;;;;N;;;;; +FE03;VARIATION SELECTOR-4;Mn;0;NSM;;;;;N;;;;; +FE04;VARIATION SELECTOR-5;Mn;0;NSM;;;;;N;;;;; +FE05;VARIATION SELECTOR-6;Mn;0;NSM;;;;;N;;;;; +FE06;VARIATION SELECTOR-7;Mn;0;NSM;;;;;N;;;;; +FE07;VARIATION SELECTOR-8;Mn;0;NSM;;;;;N;;;;; +FE08;VARIATION SELECTOR-9;Mn;0;NSM;;;;;N;;;;; +FE09;VARIATION SELECTOR-10;Mn;0;NSM;;;;;N;;;;; +FE0A;VARIATION SELECTOR-11;Mn;0;NSM;;;;;N;;;;; +FE0B;VARIATION SELECTOR-12;Mn;0;NSM;;;;;N;;;;; +FE0C;VARIATION SELECTOR-13;Mn;0;NSM;;;;;N;;;;; +FE0D;VARIATION SELECTOR-14;Mn;0;NSM;;;;;N;;;;; +FE0E;VARIATION SELECTOR-15;Mn;0;NSM;;;;;N;;;;; +FE0F;VARIATION SELECTOR-16;Mn;0;NSM;;;;;N;;;;; +FE10;PRESENTATION FORM FOR VERTICAL COMMA;Po;0;ON; 002C;;;;N;;;;; +FE11;PRESENTATION FORM FOR VERTICAL IDEOGRAPHIC COMMA;Po;0;ON; 3001;;;;N;;;;; +FE12;PRESENTATION FORM FOR VERTICAL IDEOGRAPHIC FULL STOP;Po;0;ON; 3002;;;;N;;;;; +FE13;PRESENTATION FORM FOR VERTICAL COLON;Po;0;ON; 003A;;;;N;;;;; +FE14;PRESENTATION FORM FOR VERTICAL SEMICOLON;Po;0;ON; 003B;;;;N;;;;; +FE15;PRESENTATION FORM FOR VERTICAL EXCLAMATION MARK;Po;0;ON; 0021;;;;N;;;;; +FE16;PRESENTATION FORM FOR VERTICAL QUESTION MARK;Po;0;ON; 003F;;;;N;;;;; +FE17;PRESENTATION FORM FOR VERTICAL LEFT WHITE LENTICULAR BRACKET;Ps;0;ON; 3016;;;;N;;;;; +FE18;PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRAKCET;Pe;0;ON; 3017;;;;N;;;;; +FE19;PRESENTATION FORM FOR VERTICAL HORIZONTAL ELLIPSIS;Po;0;ON; 2026;;;;N;;;;; +FE20;COMBINING LIGATURE LEFT HALF;Mn;230;NSM;;;;;N;;;;; +FE21;COMBINING LIGATURE RIGHT HALF;Mn;230;NSM;;;;;N;;;;; +FE22;COMBINING DOUBLE TILDE LEFT HALF;Mn;230;NSM;;;;;N;;;;; +FE23;COMBINING DOUBLE TILDE RIGHT HALF;Mn;230;NSM;;;;;N;;;;; +FE24;COMBINING MACRON LEFT HALF;Mn;230;NSM;;;;;N;;;;; +FE25;COMBINING MACRON RIGHT HALF;Mn;230;NSM;;;;;N;;;;; +FE26;COMBINING CONJOINING MACRON;Mn;230;NSM;;;;;N;;;;; +FE30;PRESENTATION FORM FOR VERTICAL TWO DOT LEADER;Po;0;ON; 2025;;;;N;GLYPH FOR VERTICAL TWO DOT LEADER;;;; +FE31;PRESENTATION FORM FOR VERTICAL EM DASH;Pd;0;ON; 2014;;;;N;GLYPH FOR VERTICAL EM DASH;;;; +FE32;PRESENTATION FORM FOR VERTICAL EN DASH;Pd;0;ON; 2013;;;;N;GLYPH FOR VERTICAL EN DASH;;;; +FE33;PRESENTATION FORM FOR VERTICAL LOW LINE;Pc;0;ON; 005F;;;;N;GLYPH FOR VERTICAL SPACING UNDERSCORE;;;; +FE34;PRESENTATION FORM FOR VERTICAL WAVY LOW LINE;Pc;0;ON; 005F;;;;N;GLYPH FOR VERTICAL SPACING WAVY UNDERSCORE;;;; +FE35;PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS;Ps;0;ON; 0028;;;;N;GLYPH FOR VERTICAL OPENING PARENTHESIS;;;; +FE36;PRESENTATION FORM FOR VERTICAL RIGHT PARENTHESIS;Pe;0;ON; 0029;;;;N;GLYPH FOR VERTICAL CLOSING PARENTHESIS;;;; +FE37;PRESENTATION FORM FOR VERTICAL LEFT CURLY BRACKET;Ps;0;ON; 007B;;;;N;GLYPH FOR VERTICAL OPENING CURLY BRACKET;;;; +FE38;PRESENTATION FORM FOR VERTICAL RIGHT CURLY BRACKET;Pe;0;ON; 007D;;;;N;GLYPH FOR VERTICAL CLOSING CURLY BRACKET;;;; +FE39;PRESENTATION FORM FOR VERTICAL LEFT TORTOISE SHELL BRACKET;Ps;0;ON; 3014;;;;N;GLYPH FOR VERTICAL OPENING TORTOISE SHELL BRACKET;;;; +FE3A;PRESENTATION FORM FOR VERTICAL RIGHT TORTOISE SHELL BRACKET;Pe;0;ON; 3015;;;;N;GLYPH FOR VERTICAL CLOSING TORTOISE SHELL BRACKET;;;; +FE3B;PRESENTATION FORM FOR VERTICAL LEFT BLACK LENTICULAR BRACKET;Ps;0;ON; 3010;;;;N;GLYPH FOR VERTICAL OPENING BLACK LENTICULAR BRACKET;;;; +FE3C;PRESENTATION FORM FOR VERTICAL RIGHT BLACK LENTICULAR BRACKET;Pe;0;ON; 3011;;;;N;GLYPH FOR VERTICAL CLOSING BLACK LENTICULAR BRACKET;;;; +FE3D;PRESENTATION FORM FOR VERTICAL LEFT DOUBLE ANGLE BRACKET;Ps;0;ON; 300A;;;;N;GLYPH FOR VERTICAL OPENING DOUBLE ANGLE BRACKET;;;; +FE3E;PRESENTATION FORM FOR VERTICAL RIGHT DOUBLE ANGLE BRACKET;Pe;0;ON; 300B;;;;N;GLYPH FOR VERTICAL CLOSING DOUBLE ANGLE BRACKET;;;; +FE3F;PRESENTATION FORM FOR VERTICAL LEFT ANGLE BRACKET;Ps;0;ON; 3008;;;;N;GLYPH FOR VERTICAL OPENING ANGLE BRACKET;;;; +FE40;PRESENTATION FORM FOR VERTICAL RIGHT ANGLE BRACKET;Pe;0;ON; 3009;;;;N;GLYPH FOR VERTICAL CLOSING ANGLE BRACKET;;;; +FE41;PRESENTATION FORM FOR VERTICAL LEFT CORNER BRACKET;Ps;0;ON; 300C;;;;N;GLYPH FOR VERTICAL OPENING CORNER BRACKET;;;; +FE42;PRESENTATION FORM FOR VERTICAL RIGHT CORNER BRACKET;Pe;0;ON; 300D;;;;N;GLYPH FOR VERTICAL CLOSING CORNER BRACKET;;;; +FE43;PRESENTATION FORM FOR VERTICAL LEFT WHITE CORNER BRACKET;Ps;0;ON; 300E;;;;N;GLYPH FOR VERTICAL OPENING WHITE CORNER BRACKET;;;; +FE44;PRESENTATION FORM FOR VERTICAL RIGHT WHITE CORNER BRACKET;Pe;0;ON; 300F;;;;N;GLYPH FOR VERTICAL CLOSING WHITE CORNER BRACKET;;;; +FE45;SESAME DOT;Po;0;ON;;;;;N;;;;; +FE46;WHITE SESAME DOT;Po;0;ON;;;;;N;;;;; +FE47;PRESENTATION FORM FOR VERTICAL LEFT SQUARE BRACKET;Ps;0;ON; 005B;;;;N;;;;; +FE48;PRESENTATION FORM FOR VERTICAL RIGHT SQUARE BRACKET;Pe;0;ON; 005D;;;;N;;;;; +FE49;DASHED OVERLINE;Po;0;ON; 203E;;;;N;SPACING DASHED OVERSCORE;;;; +FE4A;CENTRELINE OVERLINE;Po;0;ON; 203E;;;;N;SPACING CENTERLINE OVERSCORE;;;; +FE4B;WAVY OVERLINE;Po;0;ON; 203E;;;;N;SPACING WAVY OVERSCORE;;;; +FE4C;DOUBLE WAVY OVERLINE;Po;0;ON; 203E;;;;N;SPACING DOUBLE WAVY OVERSCORE;;;; +FE4D;DASHED LOW LINE;Pc;0;ON; 005F;;;;N;SPACING DASHED UNDERSCORE;;;; +FE4E;CENTRELINE LOW LINE;Pc;0;ON; 005F;;;;N;SPACING CENTERLINE UNDERSCORE;;;; +FE4F;WAVY LOW LINE;Pc;0;ON; 005F;;;;N;SPACING WAVY UNDERSCORE;;;; +FE50;SMALL COMMA;Po;0;CS; 002C;;;;N;;;;; +FE51;SMALL IDEOGRAPHIC COMMA;Po;0;ON; 3001;;;;N;;;;; +FE52;SMALL FULL STOP;Po;0;CS; 002E;;;;N;SMALL PERIOD;;;; +FE54;SMALL SEMICOLON;Po;0;ON; 003B;;;;N;;;;; +FE55;SMALL COLON;Po;0;CS; 003A;;;;N;;;;; +FE56;SMALL QUESTION MARK;Po;0;ON; 003F;;;;N;;;;; +FE57;SMALL EXCLAMATION MARK;Po;0;ON; 0021;;;;N;;;;; +FE58;SMALL EM DASH;Pd;0;ON; 2014;;;;N;;;;; +FE59;SMALL LEFT PARENTHESIS;Ps;0;ON; 0028;;;;Y;SMALL OPENING PARENTHESIS;;;; +FE5A;SMALL RIGHT PARENTHESIS;Pe;0;ON; 0029;;;;Y;SMALL CLOSING PARENTHESIS;;;; +FE5B;SMALL LEFT CURLY BRACKET;Ps;0;ON; 007B;;;;Y;SMALL OPENING CURLY BRACKET;;;; +FE5C;SMALL RIGHT CURLY BRACKET;Pe;0;ON; 007D;;;;Y;SMALL CLOSING CURLY BRACKET;;;; +FE5D;SMALL LEFT TORTOISE SHELL BRACKET;Ps;0;ON; 3014;;;;Y;SMALL OPENING TORTOISE SHELL BRACKET;;;; +FE5E;SMALL RIGHT TORTOISE SHELL BRACKET;Pe;0;ON; 3015;;;;Y;SMALL CLOSING TORTOISE SHELL BRACKET;;;; +FE5F;SMALL NUMBER SIGN;Po;0;ET; 0023;;;;N;;;;; +FE60;SMALL AMPERSAND;Po;0;ON; 0026;;;;N;;;;; +FE61;SMALL ASTERISK;Po;0;ON; 002A;;;;N;;;;; +FE62;SMALL PLUS SIGN;Sm;0;ES; 002B;;;;N;;;;; +FE63;SMALL HYPHEN-MINUS;Pd;0;ES; 002D;;;;N;;;;; +FE64;SMALL LESS-THAN SIGN;Sm;0;ON; 003C;;;;Y;;;;; +FE65;SMALL GREATER-THAN SIGN;Sm;0;ON; 003E;;;;Y;;;;; +FE66;SMALL EQUALS SIGN;Sm;0;ON; 003D;;;;N;;;;; +FE68;SMALL REVERSE SOLIDUS;Po;0;ON; 005C;;;;N;SMALL BACKSLASH;;;; +FE69;SMALL DOLLAR SIGN;Sc;0;ET; 0024;;;;N;;;;; +FE6A;SMALL PERCENT SIGN;Po;0;ET; 0025;;;;N;;;;; +FE6B;SMALL COMMERCIAL AT;Po;0;ON; 0040;;;;N;;;;; +FE70;ARABIC FATHATAN ISOLATED FORM;Lo;0;AL; 0020 064B;;;;N;ARABIC SPACING FATHATAN;;;; +FE71;ARABIC TATWEEL WITH FATHATAN ABOVE;Lo;0;AL; 0640 064B;;;;N;ARABIC FATHATAN ON TATWEEL;;;; +FE72;ARABIC DAMMATAN ISOLATED FORM;Lo;0;AL; 0020 064C;;;;N;ARABIC SPACING DAMMATAN;;;; +FE73;ARABIC TAIL FRAGMENT;Lo;0;AL;;;;;N;;;;; +FE74;ARABIC KASRATAN ISOLATED FORM;Lo;0;AL; 0020 064D;;;;N;ARABIC SPACING KASRATAN;;;; +FE76;ARABIC FATHA ISOLATED FORM;Lo;0;AL; 0020 064E;;;;N;ARABIC SPACING FATHAH;;;; +FE77;ARABIC FATHA MEDIAL FORM;Lo;0;AL; 0640 064E;;;;N;ARABIC FATHAH ON TATWEEL;;;; +FE78;ARABIC DAMMA ISOLATED FORM;Lo;0;AL; 0020 064F;;;;N;ARABIC SPACING DAMMAH;;;; +FE79;ARABIC DAMMA MEDIAL FORM;Lo;0;AL; 0640 064F;;;;N;ARABIC DAMMAH ON TATWEEL;;;; +FE7A;ARABIC KASRA ISOLATED FORM;Lo;0;AL; 0020 0650;;;;N;ARABIC SPACING KASRAH;;;; +FE7B;ARABIC KASRA MEDIAL FORM;Lo;0;AL; 0640 0650;;;;N;ARABIC KASRAH ON TATWEEL;;;; +FE7C;ARABIC SHADDA ISOLATED FORM;Lo;0;AL; 0020 0651;;;;N;ARABIC SPACING SHADDAH;;;; +FE7D;ARABIC SHADDA MEDIAL FORM;Lo;0;AL; 0640 0651;;;;N;ARABIC SHADDAH ON TATWEEL;;;; +FE7E;ARABIC SUKUN ISOLATED FORM;Lo;0;AL; 0020 0652;;;;N;ARABIC SPACING SUKUN;;;; +FE7F;ARABIC SUKUN MEDIAL FORM;Lo;0;AL; 0640 0652;;;;N;ARABIC SUKUN ON TATWEEL;;;; +FE80;ARABIC LETTER HAMZA ISOLATED FORM;Lo;0;AL; 0621;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH;;;; +FE81;ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM;Lo;0;AL; 0622;;;;N;GLYPH FOR ISOLATE ARABIC MADDAH ON ALEF;;;; +FE82;ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM;Lo;0;AL; 0622;;;;N;GLYPH FOR FINAL ARABIC MADDAH ON ALEF;;;; +FE83;ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL; 0623;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH ON ALEF;;;; +FE84;ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM;Lo;0;AL; 0623;;;;N;GLYPH FOR FINAL ARABIC HAMZAH ON ALEF;;;; +FE85;ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL; 0624;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH ON WAW;;;; +FE86;ARABIC LETTER WAW WITH HAMZA ABOVE FINAL FORM;Lo;0;AL; 0624;;;;N;GLYPH FOR FINAL ARABIC HAMZAH ON WAW;;;; +FE87;ARABIC LETTER ALEF WITH HAMZA BELOW ISOLATED FORM;Lo;0;AL; 0625;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH UNDER ALEF;;;; +FE88;ARABIC LETTER ALEF WITH HAMZA BELOW FINAL FORM;Lo;0;AL; 0625;;;;N;GLYPH FOR FINAL ARABIC HAMZAH UNDER ALEF;;;; +FE89;ARABIC LETTER YEH WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL; 0626;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH ON YA;;;; +FE8A;ARABIC LETTER YEH WITH HAMZA ABOVE FINAL FORM;Lo;0;AL; 0626;;;;N;GLYPH FOR FINAL ARABIC HAMZAH ON YA;;;; +FE8B;ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM;Lo;0;AL; 0626;;;;N;GLYPH FOR INITIAL ARABIC HAMZAH ON YA;;;; +FE8C;ARABIC LETTER YEH WITH HAMZA ABOVE MEDIAL FORM;Lo;0;AL; 0626;;;;N;GLYPH FOR MEDIAL ARABIC HAMZAH ON YA;;;; +FE8D;ARABIC LETTER ALEF ISOLATED FORM;Lo;0;AL; 0627;;;;N;GLYPH FOR ISOLATE ARABIC ALEF;;;; +FE8E;ARABIC LETTER ALEF FINAL FORM;Lo;0;AL; 0627;;;;N;GLYPH FOR FINAL ARABIC ALEF;;;; +FE8F;ARABIC LETTER BEH ISOLATED FORM;Lo;0;AL; 0628;;;;N;GLYPH FOR ISOLATE ARABIC BAA;;;; +FE90;ARABIC LETTER BEH FINAL FORM;Lo;0;AL; 0628;;;;N;GLYPH FOR FINAL ARABIC BAA;;;; +FE91;ARABIC LETTER BEH INITIAL FORM;Lo;0;AL; 0628;;;;N;GLYPH FOR INITIAL ARABIC BAA;;;; +FE92;ARABIC LETTER BEH MEDIAL FORM;Lo;0;AL; 0628;;;;N;GLYPH FOR MEDIAL ARABIC BAA;;;; +FE93;ARABIC LETTER TEH MARBUTA ISOLATED FORM;Lo;0;AL; 0629;;;;N;GLYPH FOR ISOLATE ARABIC TAA MARBUTAH;;;; +FE94;ARABIC LETTER TEH MARBUTA FINAL FORM;Lo;0;AL; 0629;;;;N;GLYPH FOR FINAL ARABIC TAA MARBUTAH;;;; +FE95;ARABIC LETTER TEH ISOLATED FORM;Lo;0;AL; 062A;;;;N;GLYPH FOR ISOLATE ARABIC TAA;;;; +FE96;ARABIC LETTER TEH FINAL FORM;Lo;0;AL; 062A;;;;N;GLYPH FOR FINAL ARABIC TAA;;;; +FE97;ARABIC LETTER TEH INITIAL FORM;Lo;0;AL; 062A;;;;N;GLYPH FOR INITIAL ARABIC TAA;;;; +FE98;ARABIC LETTER TEH MEDIAL FORM;Lo;0;AL; 062A;;;;N;GLYPH FOR MEDIAL ARABIC TAA;;;; +FE99;ARABIC LETTER THEH ISOLATED FORM;Lo;0;AL; 062B;;;;N;GLYPH FOR ISOLATE ARABIC THAA;;;; +FE9A;ARABIC LETTER THEH FINAL FORM;Lo;0;AL; 062B;;;;N;GLYPH FOR FINAL ARABIC THAA;;;; +FE9B;ARABIC LETTER THEH INITIAL FORM;Lo;0;AL; 062B;;;;N;GLYPH FOR INITIAL ARABIC THAA;;;; +FE9C;ARABIC LETTER THEH MEDIAL FORM;Lo;0;AL; 062B;;;;N;GLYPH FOR MEDIAL ARABIC THAA;;;; +FE9D;ARABIC LETTER JEEM ISOLATED FORM;Lo;0;AL; 062C;;;;N;GLYPH FOR ISOLATE ARABIC JEEM;;;; +FE9E;ARABIC LETTER JEEM FINAL FORM;Lo;0;AL; 062C;;;;N;GLYPH FOR FINAL ARABIC JEEM;;;; +FE9F;ARABIC LETTER JEEM INITIAL FORM;Lo;0;AL; 062C;;;;N;GLYPH FOR INITIAL ARABIC JEEM;;;; +FEA0;ARABIC LETTER JEEM MEDIAL FORM;Lo;0;AL; 062C;;;;N;GLYPH FOR MEDIAL ARABIC JEEM;;;; +FEA1;ARABIC LETTER HAH ISOLATED FORM;Lo;0;AL; 062D;;;;N;GLYPH FOR ISOLATE ARABIC HAA;;;; +FEA2;ARABIC LETTER HAH FINAL FORM;Lo;0;AL; 062D;;;;N;GLYPH FOR FINAL ARABIC HAA;;;; +FEA3;ARABIC LETTER HAH INITIAL FORM;Lo;0;AL; 062D;;;;N;GLYPH FOR INITIAL ARABIC HAA;;;; +FEA4;ARABIC LETTER HAH MEDIAL FORM;Lo;0;AL; 062D;;;;N;GLYPH FOR MEDIAL ARABIC HAA;;;; +FEA5;ARABIC LETTER KHAH ISOLATED FORM;Lo;0;AL; 062E;;;;N;GLYPH FOR ISOLATE ARABIC KHAA;;;; +FEA6;ARABIC LETTER KHAH FINAL FORM;Lo;0;AL; 062E;;;;N;GLYPH FOR FINAL ARABIC KHAA;;;; +FEA7;ARABIC LETTER KHAH INITIAL FORM;Lo;0;AL; 062E;;;;N;GLYPH FOR INITIAL ARABIC KHAA;;;; +FEA8;ARABIC LETTER KHAH MEDIAL FORM;Lo;0;AL; 062E;;;;N;GLYPH FOR MEDIAL ARABIC KHAA;;;; +FEA9;ARABIC LETTER DAL ISOLATED FORM;Lo;0;AL; 062F;;;;N;GLYPH FOR ISOLATE ARABIC DAL;;;; +FEAA;ARABIC LETTER DAL FINAL FORM;Lo;0;AL; 062F;;;;N;GLYPH FOR FINAL ARABIC DAL;;;; +FEAB;ARABIC LETTER THAL ISOLATED FORM;Lo;0;AL; 0630;;;;N;GLYPH FOR ISOLATE ARABIC THAL;;;; +FEAC;ARABIC LETTER THAL FINAL FORM;Lo;0;AL; 0630;;;;N;GLYPH FOR FINAL ARABIC THAL;;;; +FEAD;ARABIC LETTER REH ISOLATED FORM;Lo;0;AL; 0631;;;;N;GLYPH FOR ISOLATE ARABIC RA;;;; +FEAE;ARABIC LETTER REH FINAL FORM;Lo;0;AL; 0631;;;;N;GLYPH FOR FINAL ARABIC RA;;;; +FEAF;ARABIC LETTER ZAIN ISOLATED FORM;Lo;0;AL; 0632;;;;N;GLYPH FOR ISOLATE ARABIC ZAIN;;;; +FEB0;ARABIC LETTER ZAIN FINAL FORM;Lo;0;AL; 0632;;;;N;GLYPH FOR FINAL ARABIC ZAIN;;;; +FEB1;ARABIC LETTER SEEN ISOLATED FORM;Lo;0;AL; 0633;;;;N;GLYPH FOR ISOLATE ARABIC SEEN;;;; +FEB2;ARABIC LETTER SEEN FINAL FORM;Lo;0;AL; 0633;;;;N;GLYPH FOR FINAL ARABIC SEEN;;;; +FEB3;ARABIC LETTER SEEN INITIAL FORM;Lo;0;AL; 0633;;;;N;GLYPH FOR INITIAL ARABIC SEEN;;;; +FEB4;ARABIC LETTER SEEN MEDIAL FORM;Lo;0;AL; 0633;;;;N;GLYPH FOR MEDIAL ARABIC SEEN;;;; +FEB5;ARABIC LETTER SHEEN ISOLATED FORM;Lo;0;AL; 0634;;;;N;GLYPH FOR ISOLATE ARABIC SHEEN;;;; +FEB6;ARABIC LETTER SHEEN FINAL FORM;Lo;0;AL; 0634;;;;N;GLYPH FOR FINAL ARABIC SHEEN;;;; +FEB7;ARABIC LETTER SHEEN INITIAL FORM;Lo;0;AL; 0634;;;;N;GLYPH FOR INITIAL ARABIC SHEEN;;;; +FEB8;ARABIC LETTER SHEEN MEDIAL FORM;Lo;0;AL; 0634;;;;N;GLYPH FOR MEDIAL ARABIC SHEEN;;;; +FEB9;ARABIC LETTER SAD ISOLATED FORM;Lo;0;AL; 0635;;;;N;GLYPH FOR ISOLATE ARABIC SAD;;;; +FEBA;ARABIC LETTER SAD FINAL FORM;Lo;0;AL; 0635;;;;N;GLYPH FOR FINAL ARABIC SAD;;;; +FEBB;ARABIC LETTER SAD INITIAL FORM;Lo;0;AL; 0635;;;;N;GLYPH FOR INITIAL ARABIC SAD;;;; +FEBC;ARABIC LETTER SAD MEDIAL FORM;Lo;0;AL; 0635;;;;N;GLYPH FOR MEDIAL ARABIC SAD;;;; +FEBD;ARABIC LETTER DAD ISOLATED FORM;Lo;0;AL; 0636;;;;N;GLYPH FOR ISOLATE ARABIC DAD;;;; +FEBE;ARABIC LETTER DAD FINAL FORM;Lo;0;AL; 0636;;;;N;GLYPH FOR FINAL ARABIC DAD;;;; +FEBF;ARABIC LETTER DAD INITIAL FORM;Lo;0;AL; 0636;;;;N;GLYPH FOR INITIAL ARABIC DAD;;;; +FEC0;ARABIC LETTER DAD MEDIAL FORM;Lo;0;AL; 0636;;;;N;GLYPH FOR MEDIAL ARABIC DAD;;;; +FEC1;ARABIC LETTER TAH ISOLATED FORM;Lo;0;AL; 0637;;;;N;GLYPH FOR ISOLATE ARABIC TAH;;;; +FEC2;ARABIC LETTER TAH FINAL FORM;Lo;0;AL; 0637;;;;N;GLYPH FOR FINAL ARABIC TAH;;;; +FEC3;ARABIC LETTER TAH INITIAL FORM;Lo;0;AL; 0637;;;;N;GLYPH FOR INITIAL ARABIC TAH;;;; +FEC4;ARABIC LETTER TAH MEDIAL FORM;Lo;0;AL; 0637;;;;N;GLYPH FOR MEDIAL ARABIC TAH;;;; +FEC5;ARABIC LETTER ZAH ISOLATED FORM;Lo;0;AL; 0638;;;;N;GLYPH FOR ISOLATE ARABIC DHAH;;;; +FEC6;ARABIC LETTER ZAH FINAL FORM;Lo;0;AL; 0638;;;;N;GLYPH FOR FINAL ARABIC DHAH;;;; +FEC7;ARABIC LETTER ZAH INITIAL FORM;Lo;0;AL; 0638;;;;N;GLYPH FOR INITIAL ARABIC DHAH;;;; +FEC8;ARABIC LETTER ZAH MEDIAL FORM;Lo;0;AL; 0638;;;;N;GLYPH FOR MEDIAL ARABIC DHAH;;;; +FEC9;ARABIC LETTER AIN ISOLATED FORM;Lo;0;AL; 0639;;;;N;GLYPH FOR ISOLATE ARABIC AIN;;;; +FECA;ARABIC LETTER AIN FINAL FORM;Lo;0;AL; 0639;;;;N;GLYPH FOR FINAL ARABIC AIN;;;; +FECB;ARABIC LETTER AIN INITIAL FORM;Lo;0;AL; 0639;;;;N;GLYPH FOR INITIAL ARABIC AIN;;;; +FECC;ARABIC LETTER AIN MEDIAL FORM;Lo;0;AL; 0639;;;;N;GLYPH FOR MEDIAL ARABIC AIN;;;; +FECD;ARABIC LETTER GHAIN ISOLATED FORM;Lo;0;AL; 063A;;;;N;GLYPH FOR ISOLATE ARABIC GHAIN;;;; +FECE;ARABIC LETTER GHAIN FINAL FORM;Lo;0;AL; 063A;;;;N;GLYPH FOR FINAL ARABIC GHAIN;;;; +FECF;ARABIC LETTER GHAIN INITIAL FORM;Lo;0;AL; 063A;;;;N;GLYPH FOR INITIAL ARABIC GHAIN;;;; +FED0;ARABIC LETTER GHAIN MEDIAL FORM;Lo;0;AL; 063A;;;;N;GLYPH FOR MEDIAL ARABIC GHAIN;;;; +FED1;ARABIC LETTER FEH ISOLATED FORM;Lo;0;AL; 0641;;;;N;GLYPH FOR ISOLATE ARABIC FA;;;; +FED2;ARABIC LETTER FEH FINAL FORM;Lo;0;AL; 0641;;;;N;GLYPH FOR FINAL ARABIC FA;;;; +FED3;ARABIC LETTER FEH INITIAL FORM;Lo;0;AL; 0641;;;;N;GLYPH FOR INITIAL ARABIC FA;;;; +FED4;ARABIC LETTER FEH MEDIAL FORM;Lo;0;AL; 0641;;;;N;GLYPH FOR MEDIAL ARABIC FA;;;; +FED5;ARABIC LETTER QAF ISOLATED FORM;Lo;0;AL; 0642;;;;N;GLYPH FOR ISOLATE ARABIC QAF;;;; +FED6;ARABIC LETTER QAF FINAL FORM;Lo;0;AL; 0642;;;;N;GLYPH FOR FINAL ARABIC QAF;;;; +FED7;ARABIC LETTER QAF INITIAL FORM;Lo;0;AL; 0642;;;;N;GLYPH FOR INITIAL ARABIC QAF;;;; +FED8;ARABIC LETTER QAF MEDIAL FORM;Lo;0;AL; 0642;;;;N;GLYPH FOR MEDIAL ARABIC QAF;;;; +FED9;ARABIC LETTER KAF ISOLATED FORM;Lo;0;AL; 0643;;;;N;GLYPH FOR ISOLATE ARABIC CAF;;;; +FEDA;ARABIC LETTER KAF FINAL FORM;Lo;0;AL; 0643;;;;N;GLYPH FOR FINAL ARABIC CAF;;;; +FEDB;ARABIC LETTER KAF INITIAL FORM;Lo;0;AL; 0643;;;;N;GLYPH FOR INITIAL ARABIC CAF;;;; +FEDC;ARABIC LETTER KAF MEDIAL FORM;Lo;0;AL; 0643;;;;N;GLYPH FOR MEDIAL ARABIC CAF;;;; +FEDD;ARABIC LETTER LAM ISOLATED FORM;Lo;0;AL; 0644;;;;N;GLYPH FOR ISOLATE ARABIC LAM;;;; +FEDE;ARABIC LETTER LAM FINAL FORM;Lo;0;AL; 0644;;;;N;GLYPH FOR FINAL ARABIC LAM;;;; +FEDF;ARABIC LETTER LAM INITIAL FORM;Lo;0;AL; 0644;;;;N;GLYPH FOR INITIAL ARABIC LAM;;;; +FEE0;ARABIC LETTER LAM MEDIAL FORM;Lo;0;AL; 0644;;;;N;GLYPH FOR MEDIAL ARABIC LAM;;;; +FEE1;ARABIC LETTER MEEM ISOLATED FORM;Lo;0;AL; 0645;;;;N;GLYPH FOR ISOLATE ARABIC MEEM;;;; +FEE2;ARABIC LETTER MEEM FINAL FORM;Lo;0;AL; 0645;;;;N;GLYPH FOR FINAL ARABIC MEEM;;;; +FEE3;ARABIC LETTER MEEM INITIAL FORM;Lo;0;AL; 0645;;;;N;GLYPH FOR INITIAL ARABIC MEEM;;;; +FEE4;ARABIC LETTER MEEM MEDIAL FORM;Lo;0;AL; 0645;;;;N;GLYPH FOR MEDIAL ARABIC MEEM;;;; +FEE5;ARABIC LETTER NOON ISOLATED FORM;Lo;0;AL; 0646;;;;N;GLYPH FOR ISOLATE ARABIC NOON;;;; +FEE6;ARABIC LETTER NOON FINAL FORM;Lo;0;AL; 0646;;;;N;GLYPH FOR FINAL ARABIC NOON;;;; +FEE7;ARABIC LETTER NOON INITIAL FORM;Lo;0;AL; 0646;;;;N;GLYPH FOR INITIAL ARABIC NOON;;;; +FEE8;ARABIC LETTER NOON MEDIAL FORM;Lo;0;AL; 0646;;;;N;GLYPH FOR MEDIAL ARABIC NOON;;;; +FEE9;ARABIC LETTER HEH ISOLATED FORM;Lo;0;AL; 0647;;;;N;GLYPH FOR ISOLATE ARABIC HA;;;; +FEEA;ARABIC LETTER HEH FINAL FORM;Lo;0;AL; 0647;;;;N;GLYPH FOR FINAL ARABIC HA;;;; +FEEB;ARABIC LETTER HEH INITIAL FORM;Lo;0;AL; 0647;;;;N;GLYPH FOR INITIAL ARABIC HA;;;; +FEEC;ARABIC LETTER HEH MEDIAL FORM;Lo;0;AL; 0647;;;;N;GLYPH FOR MEDIAL ARABIC HA;;;; +FEED;ARABIC LETTER WAW ISOLATED FORM;Lo;0;AL; 0648;;;;N;GLYPH FOR ISOLATE ARABIC WAW;;;; +FEEE;ARABIC LETTER WAW FINAL FORM;Lo;0;AL; 0648;;;;N;GLYPH FOR FINAL ARABIC WAW;;;; +FEEF;ARABIC LETTER ALEF MAKSURA ISOLATED FORM;Lo;0;AL; 0649;;;;N;GLYPH FOR ISOLATE ARABIC ALEF MAQSURAH;;;; +FEF0;ARABIC LETTER ALEF MAKSURA FINAL FORM;Lo;0;AL; 0649;;;;N;GLYPH FOR FINAL ARABIC ALEF MAQSURAH;;;; +FEF1;ARABIC LETTER YEH ISOLATED FORM;Lo;0;AL; 064A;;;;N;GLYPH FOR ISOLATE ARABIC YA;;;; +FEF2;ARABIC LETTER YEH FINAL FORM;Lo;0;AL; 064A;;;;N;GLYPH FOR FINAL ARABIC YA;;;; +FEF3;ARABIC LETTER YEH INITIAL FORM;Lo;0;AL; 064A;;;;N;GLYPH FOR INITIAL ARABIC YA;;;; +FEF4;ARABIC LETTER YEH MEDIAL FORM;Lo;0;AL; 064A;;;;N;GLYPH FOR MEDIAL ARABIC YA;;;; +FEF5;ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM;Lo;0;AL; 0644 0622;;;;N;GLYPH FOR ISOLATE ARABIC MADDAH ON LIGATURE LAM ALEF;;;; +FEF6;ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM;Lo;0;AL; 0644 0622;;;;N;GLYPH FOR FINAL ARABIC MADDAH ON LIGATURE LAM ALEF;;;; +FEF7;ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM;Lo;0;AL; 0644 0623;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH ON LIGATURE LAM ALEF;;;; +FEF8;ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM;Lo;0;AL; 0644 0623;;;;N;GLYPH FOR FINAL ARABIC HAMZAH ON LIGATURE LAM ALEF;;;; +FEF9;ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW ISOLATED FORM;Lo;0;AL; 0644 0625;;;;N;GLYPH FOR ISOLATE ARABIC HAMZAH UNDER LIGATURE LAM ALEF;;;; +FEFA;ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW FINAL FORM;Lo;0;AL; 0644 0625;;;;N;GLYPH FOR FINAL ARABIC HAMZAH UNDER LIGATURE LAM ALEF;;;; +FEFB;ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM;Lo;0;AL; 0644 0627;;;;N;GLYPH FOR ISOLATE ARABIC LIGATURE LAM ALEF;;;; +FEFC;ARABIC LIGATURE LAM WITH ALEF FINAL FORM;Lo;0;AL; 0644 0627;;;;N;GLYPH FOR FINAL ARABIC LIGATURE LAM ALEF;;;; +FEFF;ZERO WIDTH NO-BREAK SPACE;Cf;0;BN;;;;;N;BYTE ORDER MARK;;;; +FF01;FULLWIDTH EXCLAMATION MARK;Po;0;ON; 0021;;;;N;;;;; +FF02;FULLWIDTH QUOTATION MARK;Po;0;ON; 0022;;;;N;;;;; +FF03;FULLWIDTH NUMBER SIGN;Po;0;ET; 0023;;;;N;;;;; +FF04;FULLWIDTH DOLLAR SIGN;Sc;0;ET; 0024;;;;N;;;;; +FF05;FULLWIDTH PERCENT SIGN;Po;0;ET; 0025;;;;N;;;;; +FF06;FULLWIDTH AMPERSAND;Po;0;ON; 0026;;;;N;;;;; +FF07;FULLWIDTH APOSTROPHE;Po;0;ON; 0027;;;;N;;;;; +FF08;FULLWIDTH LEFT PARENTHESIS;Ps;0;ON; 0028;;;;Y;FULLWIDTH OPENING PARENTHESIS;;;; +FF09;FULLWIDTH RIGHT PARENTHESIS;Pe;0;ON; 0029;;;;Y;FULLWIDTH CLOSING PARENTHESIS;;;; +FF0A;FULLWIDTH ASTERISK;Po;0;ON; 002A;;;;N;;;;; +FF0B;FULLWIDTH PLUS SIGN;Sm;0;ES; 002B;;;;N;;;;; +FF0C;FULLWIDTH COMMA;Po;0;CS; 002C;;;;N;;;;; +FF0D;FULLWIDTH HYPHEN-MINUS;Pd;0;ES; 002D;;;;N;;;;; +FF0E;FULLWIDTH FULL STOP;Po;0;CS; 002E;;;;N;FULLWIDTH PERIOD;;;; +FF0F;FULLWIDTH SOLIDUS;Po;0;CS; 002F;;;;N;FULLWIDTH SLASH;;;; +FF10;FULLWIDTH DIGIT ZERO;Nd;0;EN; 0030;0;0;0;N;;;;; +FF11;FULLWIDTH DIGIT ONE;Nd;0;EN; 0031;1;1;1;N;;;;; +FF12;FULLWIDTH DIGIT TWO;Nd;0;EN; 0032;2;2;2;N;;;;; +FF13;FULLWIDTH DIGIT THREE;Nd;0;EN; 0033;3;3;3;N;;;;; +FF14;FULLWIDTH DIGIT FOUR;Nd;0;EN; 0034;4;4;4;N;;;;; +FF15;FULLWIDTH DIGIT FIVE;Nd;0;EN; 0035;5;5;5;N;;;;; +FF16;FULLWIDTH DIGIT SIX;Nd;0;EN; 0036;6;6;6;N;;;;; +FF17;FULLWIDTH DIGIT SEVEN;Nd;0;EN; 0037;7;7;7;N;;;;; +FF18;FULLWIDTH DIGIT EIGHT;Nd;0;EN; 0038;8;8;8;N;;;;; +FF19;FULLWIDTH DIGIT NINE;Nd;0;EN; 0039;9;9;9;N;;;;; +FF1A;FULLWIDTH COLON;Po;0;CS; 003A;;;;N;;;;; +FF1B;FULLWIDTH SEMICOLON;Po;0;ON; 003B;;;;N;;;;; +FF1C;FULLWIDTH LESS-THAN SIGN;Sm;0;ON; 003C;;;;Y;;;;; +FF1D;FULLWIDTH EQUALS SIGN;Sm;0;ON; 003D;;;;N;;;;; +FF1E;FULLWIDTH GREATER-THAN SIGN;Sm;0;ON; 003E;;;;Y;;;;; +FF1F;FULLWIDTH QUESTION MARK;Po;0;ON; 003F;;;;N;;;;; +FF20;FULLWIDTH COMMERCIAL AT;Po;0;ON; 0040;;;;N;;;;; +FF21;FULLWIDTH LATIN CAPITAL LETTER A;Lu;0;L; 0041;;;;N;;;;FF41; +FF22;FULLWIDTH LATIN CAPITAL LETTER B;Lu;0;L; 0042;;;;N;;;;FF42; +FF23;FULLWIDTH LATIN CAPITAL LETTER C;Lu;0;L; 0043;;;;N;;;;FF43; +FF24;FULLWIDTH LATIN CAPITAL LETTER D;Lu;0;L; 0044;;;;N;;;;FF44; +FF25;FULLWIDTH LATIN CAPITAL LETTER E;Lu;0;L; 0045;;;;N;;;;FF45; +FF26;FULLWIDTH LATIN CAPITAL LETTER F;Lu;0;L; 0046;;;;N;;;;FF46; +FF27;FULLWIDTH LATIN CAPITAL LETTER G;Lu;0;L; 0047;;;;N;;;;FF47; +FF28;FULLWIDTH LATIN CAPITAL LETTER H;Lu;0;L; 0048;;;;N;;;;FF48; +FF29;FULLWIDTH LATIN CAPITAL LETTER I;Lu;0;L; 0049;;;;N;;;;FF49; +FF2A;FULLWIDTH LATIN CAPITAL LETTER J;Lu;0;L; 004A;;;;N;;;;FF4A; +FF2B;FULLWIDTH LATIN CAPITAL LETTER K;Lu;0;L; 004B;;;;N;;;;FF4B; +FF2C;FULLWIDTH LATIN CAPITAL LETTER L;Lu;0;L; 004C;;;;N;;;;FF4C; +FF2D;FULLWIDTH LATIN CAPITAL LETTER M;Lu;0;L; 004D;;;;N;;;;FF4D; +FF2E;FULLWIDTH LATIN CAPITAL LETTER N;Lu;0;L; 004E;;;;N;;;;FF4E; +FF2F;FULLWIDTH LATIN CAPITAL LETTER O;Lu;0;L; 004F;;;;N;;;;FF4F; +FF30;FULLWIDTH LATIN CAPITAL LETTER P;Lu;0;L; 0050;;;;N;;;;FF50; +FF31;FULLWIDTH LATIN CAPITAL LETTER Q;Lu;0;L; 0051;;;;N;;;;FF51; +FF32;FULLWIDTH LATIN CAPITAL LETTER R;Lu;0;L; 0052;;;;N;;;;FF52; +FF33;FULLWIDTH LATIN CAPITAL LETTER S;Lu;0;L; 0053;;;;N;;;;FF53; +FF34;FULLWIDTH LATIN CAPITAL LETTER T;Lu;0;L; 0054;;;;N;;;;FF54; +FF35;FULLWIDTH LATIN CAPITAL LETTER U;Lu;0;L; 0055;;;;N;;;;FF55; +FF36;FULLWIDTH LATIN CAPITAL LETTER V;Lu;0;L; 0056;;;;N;;;;FF56; +FF37;FULLWIDTH LATIN CAPITAL LETTER W;Lu;0;L; 0057;;;;N;;;;FF57; +FF38;FULLWIDTH LATIN CAPITAL LETTER X;Lu;0;L; 0058;;;;N;;;;FF58; +FF39;FULLWIDTH LATIN CAPITAL LETTER Y;Lu;0;L; 0059;;;;N;;;;FF59; +FF3A;FULLWIDTH LATIN CAPITAL LETTER Z;Lu;0;L; 005A;;;;N;;;;FF5A; +FF3B;FULLWIDTH LEFT SQUARE BRACKET;Ps;0;ON; 005B;;;;Y;FULLWIDTH OPENING SQUARE BRACKET;;;; +FF3C;FULLWIDTH REVERSE SOLIDUS;Po;0;ON; 005C;;;;N;FULLWIDTH BACKSLASH;;;; +FF3D;FULLWIDTH RIGHT SQUARE BRACKET;Pe;0;ON; 005D;;;;Y;FULLWIDTH CLOSING SQUARE BRACKET;;;; +FF3E;FULLWIDTH CIRCUMFLEX ACCENT;Sk;0;ON; 005E;;;;N;FULLWIDTH SPACING CIRCUMFLEX;;;; +FF3F;FULLWIDTH LOW LINE;Pc;0;ON; 005F;;;;N;FULLWIDTH SPACING UNDERSCORE;;;; +FF40;FULLWIDTH GRAVE ACCENT;Sk;0;ON; 0060;;;;N;FULLWIDTH SPACING GRAVE;;;; +FF41;FULLWIDTH LATIN SMALL LETTER A;Ll;0;L; 0061;;;;N;;;FF21;;FF21 +FF42;FULLWIDTH LATIN SMALL LETTER B;Ll;0;L; 0062;;;;N;;;FF22;;FF22 +FF43;FULLWIDTH LATIN SMALL LETTER C;Ll;0;L; 0063;;;;N;;;FF23;;FF23 +FF44;FULLWIDTH LATIN SMALL LETTER D;Ll;0;L; 0064;;;;N;;;FF24;;FF24 +FF45;FULLWIDTH LATIN SMALL LETTER E;Ll;0;L; 0065;;;;N;;;FF25;;FF25 +FF46;FULLWIDTH LATIN SMALL LETTER F;Ll;0;L; 0066;;;;N;;;FF26;;FF26 +FF47;FULLWIDTH LATIN SMALL LETTER G;Ll;0;L; 0067;;;;N;;;FF27;;FF27 +FF48;FULLWIDTH LATIN SMALL LETTER H;Ll;0;L; 0068;;;;N;;;FF28;;FF28 +FF49;FULLWIDTH LATIN SMALL LETTER I;Ll;0;L; 0069;;;;N;;;FF29;;FF29 +FF4A;FULLWIDTH LATIN SMALL LETTER J;Ll;0;L; 006A;;;;N;;;FF2A;;FF2A +FF4B;FULLWIDTH LATIN SMALL LETTER K;Ll;0;L; 006B;;;;N;;;FF2B;;FF2B +FF4C;FULLWIDTH LATIN SMALL LETTER L;Ll;0;L; 006C;;;;N;;;FF2C;;FF2C +FF4D;FULLWIDTH LATIN SMALL LETTER M;Ll;0;L; 006D;;;;N;;;FF2D;;FF2D +FF4E;FULLWIDTH LATIN SMALL LETTER N;Ll;0;L; 006E;;;;N;;;FF2E;;FF2E +FF4F;FULLWIDTH LATIN SMALL LETTER O;Ll;0;L; 006F;;;;N;;;FF2F;;FF2F +FF50;FULLWIDTH LATIN SMALL LETTER P;Ll;0;L; 0070;;;;N;;;FF30;;FF30 +FF51;FULLWIDTH LATIN SMALL LETTER Q;Ll;0;L; 0071;;;;N;;;FF31;;FF31 +FF52;FULLWIDTH LATIN SMALL LETTER R;Ll;0;L; 0072;;;;N;;;FF32;;FF32 +FF53;FULLWIDTH LATIN SMALL LETTER S;Ll;0;L; 0073;;;;N;;;FF33;;FF33 +FF54;FULLWIDTH LATIN SMALL LETTER T;Ll;0;L; 0074;;;;N;;;FF34;;FF34 +FF55;FULLWIDTH LATIN SMALL LETTER U;Ll;0;L; 0075;;;;N;;;FF35;;FF35 +FF56;FULLWIDTH LATIN SMALL LETTER V;Ll;0;L; 0076;;;;N;;;FF36;;FF36 +FF57;FULLWIDTH LATIN SMALL LETTER W;Ll;0;L; 0077;;;;N;;;FF37;;FF37 +FF58;FULLWIDTH LATIN SMALL LETTER X;Ll;0;L; 0078;;;;N;;;FF38;;FF38 +FF59;FULLWIDTH LATIN SMALL LETTER Y;Ll;0;L; 0079;;;;N;;;FF39;;FF39 +FF5A;FULLWIDTH LATIN SMALL LETTER Z;Ll;0;L; 007A;;;;N;;;FF3A;;FF3A +FF5B;FULLWIDTH LEFT CURLY BRACKET;Ps;0;ON; 007B;;;;Y;FULLWIDTH OPENING CURLY BRACKET;;;; +FF5C;FULLWIDTH VERTICAL LINE;Sm;0;ON; 007C;;;;N;FULLWIDTH VERTICAL BAR;;;; +FF5D;FULLWIDTH RIGHT CURLY BRACKET;Pe;0;ON; 007D;;;;Y;FULLWIDTH CLOSING CURLY BRACKET;;;; +FF5E;FULLWIDTH TILDE;Sm;0;ON; 007E;;;;N;FULLWIDTH SPACING TILDE;;;; +FF5F;FULLWIDTH LEFT WHITE PARENTHESIS;Ps;0;ON; 2985;;;;Y;;;;; +FF60;FULLWIDTH RIGHT WHITE PARENTHESIS;Pe;0;ON; 2986;;;;Y;;;;; +FF61;HALFWIDTH IDEOGRAPHIC FULL STOP;Po;0;ON; 3002;;;;N;HALFWIDTH IDEOGRAPHIC PERIOD;;;; +FF62;HALFWIDTH LEFT CORNER BRACKET;Ps;0;ON; 300C;;;;Y;HALFWIDTH OPENING CORNER BRACKET;;;; +FF63;HALFWIDTH RIGHT CORNER BRACKET;Pe;0;ON; 300D;;;;Y;HALFWIDTH CLOSING CORNER BRACKET;;;; +FF64;HALFWIDTH IDEOGRAPHIC COMMA;Po;0;ON; 3001;;;;N;;;;; +FF65;HALFWIDTH KATAKANA MIDDLE DOT;Po;0;ON; 30FB;;;;N;;;;; +FF66;HALFWIDTH KATAKANA LETTER WO;Lo;0;L; 30F2;;;;N;;;;; +FF67;HALFWIDTH KATAKANA LETTER SMALL A;Lo;0;L; 30A1;;;;N;;;;; +FF68;HALFWIDTH KATAKANA LETTER SMALL I;Lo;0;L; 30A3;;;;N;;;;; +FF69;HALFWIDTH KATAKANA LETTER SMALL U;Lo;0;L; 30A5;;;;N;;;;; +FF6A;HALFWIDTH KATAKANA LETTER SMALL E;Lo;0;L; 30A7;;;;N;;;;; +FF6B;HALFWIDTH KATAKANA LETTER SMALL O;Lo;0;L; 30A9;;;;N;;;;; +FF6C;HALFWIDTH KATAKANA LETTER SMALL YA;Lo;0;L; 30E3;;;;N;;;;; +FF6D;HALFWIDTH KATAKANA LETTER SMALL YU;Lo;0;L; 30E5;;;;N;;;;; +FF6E;HALFWIDTH KATAKANA LETTER SMALL YO;Lo;0;L; 30E7;;;;N;;;;; +FF6F;HALFWIDTH KATAKANA LETTER SMALL TU;Lo;0;L; 30C3;;;;N;;;;; +FF70;HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK;Lm;0;L; 30FC;;;;N;;;;; +FF71;HALFWIDTH KATAKANA LETTER A;Lo;0;L; 30A2;;;;N;;;;; +FF72;HALFWIDTH KATAKANA LETTER I;Lo;0;L; 30A4;;;;N;;;;; +FF73;HALFWIDTH KATAKANA LETTER U;Lo;0;L; 30A6;;;;N;;;;; +FF74;HALFWIDTH KATAKANA LETTER E;Lo;0;L; 30A8;;;;N;;;;; +FF75;HALFWIDTH KATAKANA LETTER O;Lo;0;L; 30AA;;;;N;;;;; +FF76;HALFWIDTH KATAKANA LETTER KA;Lo;0;L; 30AB;;;;N;;;;; +FF77;HALFWIDTH KATAKANA LETTER KI;Lo;0;L; 30AD;;;;N;;;;; +FF78;HALFWIDTH KATAKANA LETTER KU;Lo;0;L; 30AF;;;;N;;;;; +FF79;HALFWIDTH KATAKANA LETTER KE;Lo;0;L; 30B1;;;;N;;;;; +FF7A;HALFWIDTH KATAKANA LETTER KO;Lo;0;L; 30B3;;;;N;;;;; +FF7B;HALFWIDTH KATAKANA LETTER SA;Lo;0;L; 30B5;;;;N;;;;; +FF7C;HALFWIDTH KATAKANA LETTER SI;Lo;0;L; 30B7;;;;N;;;;; +FF7D;HALFWIDTH KATAKANA LETTER SU;Lo;0;L; 30B9;;;;N;;;;; +FF7E;HALFWIDTH KATAKANA LETTER SE;Lo;0;L; 30BB;;;;N;;;;; +FF7F;HALFWIDTH KATAKANA LETTER SO;Lo;0;L; 30BD;;;;N;;;;; +FF80;HALFWIDTH KATAKANA LETTER TA;Lo;0;L; 30BF;;;;N;;;;; +FF81;HALFWIDTH KATAKANA LETTER TI;Lo;0;L; 30C1;;;;N;;;;; +FF82;HALFWIDTH KATAKANA LETTER TU;Lo;0;L; 30C4;;;;N;;;;; +FF83;HALFWIDTH KATAKANA LETTER TE;Lo;0;L; 30C6;;;;N;;;;; +FF84;HALFWIDTH KATAKANA LETTER TO;Lo;0;L; 30C8;;;;N;;;;; +FF85;HALFWIDTH KATAKANA LETTER NA;Lo;0;L; 30CA;;;;N;;;;; +FF86;HALFWIDTH KATAKANA LETTER NI;Lo;0;L; 30CB;;;;N;;;;; +FF87;HALFWIDTH KATAKANA LETTER NU;Lo;0;L; 30CC;;;;N;;;;; +FF88;HALFWIDTH KATAKANA LETTER NE;Lo;0;L; 30CD;;;;N;;;;; +FF89;HALFWIDTH KATAKANA LETTER NO;Lo;0;L; 30CE;;;;N;;;;; +FF8A;HALFWIDTH KATAKANA LETTER HA;Lo;0;L; 30CF;;;;N;;;;; +FF8B;HALFWIDTH KATAKANA LETTER HI;Lo;0;L; 30D2;;;;N;;;;; +FF8C;HALFWIDTH KATAKANA LETTER HU;Lo;0;L; 30D5;;;;N;;;;; +FF8D;HALFWIDTH KATAKANA LETTER HE;Lo;0;L; 30D8;;;;N;;;;; +FF8E;HALFWIDTH KATAKANA LETTER HO;Lo;0;L; 30DB;;;;N;;;;; +FF8F;HALFWIDTH KATAKANA LETTER MA;Lo;0;L; 30DE;;;;N;;;;; +FF90;HALFWIDTH KATAKANA LETTER MI;Lo;0;L; 30DF;;;;N;;;;; +FF91;HALFWIDTH KATAKANA LETTER MU;Lo;0;L; 30E0;;;;N;;;;; +FF92;HALFWIDTH KATAKANA LETTER ME;Lo;0;L; 30E1;;;;N;;;;; +FF93;HALFWIDTH KATAKANA LETTER MO;Lo;0;L; 30E2;;;;N;;;;; +FF94;HALFWIDTH KATAKANA LETTER YA;Lo;0;L; 30E4;;;;N;;;;; +FF95;HALFWIDTH KATAKANA LETTER YU;Lo;0;L; 30E6;;;;N;;;;; +FF96;HALFWIDTH KATAKANA LETTER YO;Lo;0;L; 30E8;;;;N;;;;; +FF97;HALFWIDTH KATAKANA LETTER RA;Lo;0;L; 30E9;;;;N;;;;; +FF98;HALFWIDTH KATAKANA LETTER RI;Lo;0;L; 30EA;;;;N;;;;; +FF99;HALFWIDTH KATAKANA LETTER RU;Lo;0;L; 30EB;;;;N;;;;; +FF9A;HALFWIDTH KATAKANA LETTER RE;Lo;0;L; 30EC;;;;N;;;;; +FF9B;HALFWIDTH KATAKANA LETTER RO;Lo;0;L; 30ED;;;;N;;;;; +FF9C;HALFWIDTH KATAKANA LETTER WA;Lo;0;L; 30EF;;;;N;;;;; +FF9D;HALFWIDTH KATAKANA LETTER N;Lo;0;L; 30F3;;;;N;;;;; +FF9E;HALFWIDTH KATAKANA VOICED SOUND MARK;Lm;0;L; 3099;;;;N;;;;; +FF9F;HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK;Lm;0;L; 309A;;;;N;;;;; +FFA0;HALFWIDTH HANGUL FILLER;Lo;0;L; 3164;;;;N;HALFWIDTH HANGUL CAE OM;;;; +FFA1;HALFWIDTH HANGUL LETTER KIYEOK;Lo;0;L; 3131;;;;N;HALFWIDTH HANGUL LETTER GIYEOG;;;; +FFA2;HALFWIDTH HANGUL LETTER SSANGKIYEOK;Lo;0;L; 3132;;;;N;HALFWIDTH HANGUL LETTER SSANG GIYEOG;;;; +FFA3;HALFWIDTH HANGUL LETTER KIYEOK-SIOS;Lo;0;L; 3133;;;;N;HALFWIDTH HANGUL LETTER GIYEOG SIOS;;;; +FFA4;HALFWIDTH HANGUL LETTER NIEUN;Lo;0;L; 3134;;;;N;;;;; +FFA5;HALFWIDTH HANGUL LETTER NIEUN-CIEUC;Lo;0;L; 3135;;;;N;HALFWIDTH HANGUL LETTER NIEUN JIEUJ;;;; +FFA6;HALFWIDTH HANGUL LETTER NIEUN-HIEUH;Lo;0;L; 3136;;;;N;HALFWIDTH HANGUL LETTER NIEUN HIEUH;;;; +FFA7;HALFWIDTH HANGUL LETTER TIKEUT;Lo;0;L; 3137;;;;N;HALFWIDTH HANGUL LETTER DIGEUD;;;; +FFA8;HALFWIDTH HANGUL LETTER SSANGTIKEUT;Lo;0;L; 3138;;;;N;HALFWIDTH HANGUL LETTER SSANG DIGEUD;;;; +FFA9;HALFWIDTH HANGUL LETTER RIEUL;Lo;0;L; 3139;;;;N;HALFWIDTH HANGUL LETTER LIEUL;;;; +FFAA;HALFWIDTH HANGUL LETTER RIEUL-KIYEOK;Lo;0;L; 313A;;;;N;HALFWIDTH HANGUL LETTER LIEUL GIYEOG;;;; +FFAB;HALFWIDTH HANGUL LETTER RIEUL-MIEUM;Lo;0;L; 313B;;;;N;HALFWIDTH HANGUL LETTER LIEUL MIEUM;;;; +FFAC;HALFWIDTH HANGUL LETTER RIEUL-PIEUP;Lo;0;L; 313C;;;;N;HALFWIDTH HANGUL LETTER LIEUL BIEUB;;;; +FFAD;HALFWIDTH HANGUL LETTER RIEUL-SIOS;Lo;0;L; 313D;;;;N;HALFWIDTH HANGUL LETTER LIEUL SIOS;;;; +FFAE;HALFWIDTH HANGUL LETTER RIEUL-THIEUTH;Lo;0;L; 313E;;;;N;HALFWIDTH HANGUL LETTER LIEUL TIEUT;;;; +FFAF;HALFWIDTH HANGUL LETTER RIEUL-PHIEUPH;Lo;0;L; 313F;;;;N;HALFWIDTH HANGUL LETTER LIEUL PIEUP;;;; +FFB0;HALFWIDTH HANGUL LETTER RIEUL-HIEUH;Lo;0;L; 3140;;;;N;HALFWIDTH HANGUL LETTER LIEUL HIEUH;;;; +FFB1;HALFWIDTH HANGUL LETTER MIEUM;Lo;0;L; 3141;;;;N;;;;; +FFB2;HALFWIDTH HANGUL LETTER PIEUP;Lo;0;L; 3142;;;;N;HALFWIDTH HANGUL LETTER BIEUB;;;; +FFB3;HALFWIDTH HANGUL LETTER SSANGPIEUP;Lo;0;L; 3143;;;;N;HALFWIDTH HANGUL LETTER SSANG BIEUB;;;; +FFB4;HALFWIDTH HANGUL LETTER PIEUP-SIOS;Lo;0;L; 3144;;;;N;HALFWIDTH HANGUL LETTER BIEUB SIOS;;;; +FFB5;HALFWIDTH HANGUL LETTER SIOS;Lo;0;L; 3145;;;;N;;;;; +FFB6;HALFWIDTH HANGUL LETTER SSANGSIOS;Lo;0;L; 3146;;;;N;HALFWIDTH HANGUL LETTER SSANG SIOS;;;; +FFB7;HALFWIDTH HANGUL LETTER IEUNG;Lo;0;L; 3147;;;;N;;;;; +FFB8;HALFWIDTH HANGUL LETTER CIEUC;Lo;0;L; 3148;;;;N;HALFWIDTH HANGUL LETTER JIEUJ;;;; +FFB9;HALFWIDTH HANGUL LETTER SSANGCIEUC;Lo;0;L; 3149;;;;N;HALFWIDTH HANGUL LETTER SSANG JIEUJ;;;; +FFBA;HALFWIDTH HANGUL LETTER CHIEUCH;Lo;0;L; 314A;;;;N;HALFWIDTH HANGUL LETTER CIEUC;;;; +FFBB;HALFWIDTH HANGUL LETTER KHIEUKH;Lo;0;L; 314B;;;;N;HALFWIDTH HANGUL LETTER KIYEOK;;;; +FFBC;HALFWIDTH HANGUL LETTER THIEUTH;Lo;0;L; 314C;;;;N;HALFWIDTH HANGUL LETTER TIEUT;;;; +FFBD;HALFWIDTH HANGUL LETTER PHIEUPH;Lo;0;L; 314D;;;;N;HALFWIDTH HANGUL LETTER PIEUP;;;; +FFBE;HALFWIDTH HANGUL LETTER HIEUH;Lo;0;L; 314E;;;;N;;;;; +FFC2;HALFWIDTH HANGUL LETTER A;Lo;0;L; 314F;;;;N;;;;; +FFC3;HALFWIDTH HANGUL LETTER AE;Lo;0;L; 3150;;;;N;;;;; +FFC4;HALFWIDTH HANGUL LETTER YA;Lo;0;L; 3151;;;;N;;;;; +FFC5;HALFWIDTH HANGUL LETTER YAE;Lo;0;L; 3152;;;;N;;;;; +FFC6;HALFWIDTH HANGUL LETTER EO;Lo;0;L; 3153;;;;N;;;;; +FFC7;HALFWIDTH HANGUL LETTER E;Lo;0;L; 3154;;;;N;;;;; +FFCA;HALFWIDTH HANGUL LETTER YEO;Lo;0;L; 3155;;;;N;;;;; +FFCB;HALFWIDTH HANGUL LETTER YE;Lo;0;L; 3156;;;;N;;;;; +FFCC;HALFWIDTH HANGUL LETTER O;Lo;0;L; 3157;;;;N;;;;; +FFCD;HALFWIDTH HANGUL LETTER WA;Lo;0;L; 3158;;;;N;;;;; +FFCE;HALFWIDTH HANGUL LETTER WAE;Lo;0;L; 3159;;;;N;;;;; +FFCF;HALFWIDTH HANGUL LETTER OE;Lo;0;L; 315A;;;;N;;;;; +FFD2;HALFWIDTH HANGUL LETTER YO;Lo;0;L; 315B;;;;N;;;;; +FFD3;HALFWIDTH HANGUL LETTER U;Lo;0;L; 315C;;;;N;;;;; +FFD4;HALFWIDTH HANGUL LETTER WEO;Lo;0;L; 315D;;;;N;;;;; +FFD5;HALFWIDTH HANGUL LETTER WE;Lo;0;L; 315E;;;;N;;;;; +FFD6;HALFWIDTH HANGUL LETTER WI;Lo;0;L; 315F;;;;N;;;;; +FFD7;HALFWIDTH HANGUL LETTER YU;Lo;0;L; 3160;;;;N;;;;; +FFDA;HALFWIDTH HANGUL LETTER EU;Lo;0;L; 3161;;;;N;;;;; +FFDB;HALFWIDTH HANGUL LETTER YI;Lo;0;L; 3162;;;;N;;;;; +FFDC;HALFWIDTH HANGUL LETTER I;Lo;0;L; 3163;;;;N;;;;; +FFE0;FULLWIDTH CENT SIGN;Sc;0;ET; 00A2;;;;N;;;;; +FFE1;FULLWIDTH POUND SIGN;Sc;0;ET; 00A3;;;;N;;;;; +FFE2;FULLWIDTH NOT SIGN;Sm;0;ON; 00AC;;;;N;;;;; +FFE3;FULLWIDTH MACRON;Sk;0;ON; 00AF;;;;N;FULLWIDTH SPACING MACRON;;;; +FFE4;FULLWIDTH BROKEN BAR;So;0;ON; 00A6;;;;N;FULLWIDTH BROKEN VERTICAL BAR;;;; +FFE5;FULLWIDTH YEN SIGN;Sc;0;ET; 00A5;;;;N;;;;; +FFE6;FULLWIDTH WON SIGN;Sc;0;ET; 20A9;;;;N;;;;; +FFE8;HALFWIDTH FORMS LIGHT VERTICAL;So;0;ON; 2502;;;;N;;;;; +FFE9;HALFWIDTH LEFTWARDS ARROW;Sm;0;ON; 2190;;;;N;;;;; +FFEA;HALFWIDTH UPWARDS ARROW;Sm;0;ON; 2191;;;;N;;;;; +FFEB;HALFWIDTH RIGHTWARDS ARROW;Sm;0;ON; 2192;;;;N;;;;; +FFEC;HALFWIDTH DOWNWARDS ARROW;Sm;0;ON; 2193;;;;N;;;;; +FFED;HALFWIDTH BLACK SQUARE;So;0;ON; 25A0;;;;N;;;;; +FFEE;HALFWIDTH WHITE CIRCLE;So;0;ON; 25CB;;;;N;;;;; +FFF9;INTERLINEAR ANNOTATION ANCHOR;Cf;0;ON;;;;;N;;;;; +FFFA;INTERLINEAR ANNOTATION SEPARATOR;Cf;0;ON;;;;;N;;;;; +FFFB;INTERLINEAR ANNOTATION TERMINATOR;Cf;0;ON;;;;;N;;;;; +FFFC;OBJECT REPLACEMENT CHARACTER;So;0;ON;;;;;N;;;;; +FFFD;REPLACEMENT CHARACTER;So;0;ON;;;;;N;;;;; +10000;LINEAR B SYLLABLE B008 A;Lo;0;L;;;;;N;;;;; +10001;LINEAR B SYLLABLE B038 E;Lo;0;L;;;;;N;;;;; +10002;LINEAR B SYLLABLE B028 I;Lo;0;L;;;;;N;;;;; +10003;LINEAR B SYLLABLE B061 O;Lo;0;L;;;;;N;;;;; +10004;LINEAR B SYLLABLE B010 U;Lo;0;L;;;;;N;;;;; +10005;LINEAR B SYLLABLE B001 DA;Lo;0;L;;;;;N;;;;; +10006;LINEAR B SYLLABLE B045 DE;Lo;0;L;;;;;N;;;;; +10007;LINEAR B SYLLABLE B007 DI;Lo;0;L;;;;;N;;;;; +10008;LINEAR B SYLLABLE B014 DO;Lo;0;L;;;;;N;;;;; +10009;LINEAR B SYLLABLE B051 DU;Lo;0;L;;;;;N;;;;; +1000A;LINEAR B SYLLABLE B057 JA;Lo;0;L;;;;;N;;;;; +1000B;LINEAR B SYLLABLE B046 JE;Lo;0;L;;;;;N;;;;; +1000D;LINEAR B SYLLABLE B036 JO;Lo;0;L;;;;;N;;;;; +1000E;LINEAR B SYLLABLE B065 JU;Lo;0;L;;;;;N;;;;; +1000F;LINEAR B SYLLABLE B077 KA;Lo;0;L;;;;;N;;;;; +10010;LINEAR B SYLLABLE B044 KE;Lo;0;L;;;;;N;;;;; +10011;LINEAR B SYLLABLE B067 KI;Lo;0;L;;;;;N;;;;; +10012;LINEAR B SYLLABLE B070 KO;Lo;0;L;;;;;N;;;;; +10013;LINEAR B SYLLABLE B081 KU;Lo;0;L;;;;;N;;;;; +10014;LINEAR B SYLLABLE B080 MA;Lo;0;L;;;;;N;;;;; +10015;LINEAR B SYLLABLE B013 ME;Lo;0;L;;;;;N;;;;; +10016;LINEAR B SYLLABLE B073 MI;Lo;0;L;;;;;N;;;;; +10017;LINEAR B SYLLABLE B015 MO;Lo;0;L;;;;;N;;;;; +10018;LINEAR B SYLLABLE B023 MU;Lo;0;L;;;;;N;;;;; +10019;LINEAR B SYLLABLE B006 NA;Lo;0;L;;;;;N;;;;; +1001A;LINEAR B SYLLABLE B024 NE;Lo;0;L;;;;;N;;;;; +1001B;LINEAR B SYLLABLE B030 NI;Lo;0;L;;;;;N;;;;; +1001C;LINEAR B SYLLABLE B052 NO;Lo;0;L;;;;;N;;;;; +1001D;LINEAR B SYLLABLE B055 NU;Lo;0;L;;;;;N;;;;; +1001E;LINEAR B SYLLABLE B003 PA;Lo;0;L;;;;;N;;;;; +1001F;LINEAR B SYLLABLE B072 PE;Lo;0;L;;;;;N;;;;; +10020;LINEAR B SYLLABLE B039 PI;Lo;0;L;;;;;N;;;;; +10021;LINEAR B SYLLABLE B011 PO;Lo;0;L;;;;;N;;;;; +10022;LINEAR B SYLLABLE B050 PU;Lo;0;L;;;;;N;;;;; +10023;LINEAR B SYLLABLE B016 QA;Lo;0;L;;;;;N;;;;; +10024;LINEAR B SYLLABLE B078 QE;Lo;0;L;;;;;N;;;;; +10025;LINEAR B SYLLABLE B021 QI;Lo;0;L;;;;;N;;;;; +10026;LINEAR B SYLLABLE B032 QO;Lo;0;L;;;;;N;;;;; +10028;LINEAR B SYLLABLE B060 RA;Lo;0;L;;;;;N;;;;; +10029;LINEAR B SYLLABLE B027 RE;Lo;0;L;;;;;N;;;;; +1002A;LINEAR B SYLLABLE B053 RI;Lo;0;L;;;;;N;;;;; +1002B;LINEAR B SYLLABLE B002 RO;Lo;0;L;;;;;N;;;;; +1002C;LINEAR B SYLLABLE B026 RU;Lo;0;L;;;;;N;;;;; +1002D;LINEAR B SYLLABLE B031 SA;Lo;0;L;;;;;N;;;;; +1002E;LINEAR B SYLLABLE B009 SE;Lo;0;L;;;;;N;;;;; +1002F;LINEAR B SYLLABLE B041 SI;Lo;0;L;;;;;N;;;;; +10030;LINEAR B SYLLABLE B012 SO;Lo;0;L;;;;;N;;;;; +10031;LINEAR B SYLLABLE B058 SU;Lo;0;L;;;;;N;;;;; +10032;LINEAR B SYLLABLE B059 TA;Lo;0;L;;;;;N;;;;; +10033;LINEAR B SYLLABLE B004 TE;Lo;0;L;;;;;N;;;;; +10034;LINEAR B SYLLABLE B037 TI;Lo;0;L;;;;;N;;;;; +10035;LINEAR B SYLLABLE B005 TO;Lo;0;L;;;;;N;;;;; +10036;LINEAR B SYLLABLE B069 TU;Lo;0;L;;;;;N;;;;; +10037;LINEAR B SYLLABLE B054 WA;Lo;0;L;;;;;N;;;;; +10038;LINEAR B SYLLABLE B075 WE;Lo;0;L;;;;;N;;;;; +10039;LINEAR B SYLLABLE B040 WI;Lo;0;L;;;;;N;;;;; +1003A;LINEAR B SYLLABLE B042 WO;Lo;0;L;;;;;N;;;;; +1003C;LINEAR B SYLLABLE B017 ZA;Lo;0;L;;;;;N;;;;; +1003D;LINEAR B SYLLABLE B074 ZE;Lo;0;L;;;;;N;;;;; +1003F;LINEAR B SYLLABLE B020 ZO;Lo;0;L;;;;;N;;;;; +10040;LINEAR B SYLLABLE B025 A2;Lo;0;L;;;;;N;;;;; +10041;LINEAR B SYLLABLE B043 A3;Lo;0;L;;;;;N;;;;; +10042;LINEAR B SYLLABLE B085 AU;Lo;0;L;;;;;N;;;;; +10043;LINEAR B SYLLABLE B071 DWE;Lo;0;L;;;;;N;;;;; +10044;LINEAR B SYLLABLE B090 DWO;Lo;0;L;;;;;N;;;;; +10045;LINEAR B SYLLABLE B048 NWA;Lo;0;L;;;;;N;;;;; +10046;LINEAR B SYLLABLE B029 PU2;Lo;0;L;;;;;N;;;;; +10047;LINEAR B SYLLABLE B062 PTE;Lo;0;L;;;;;N;;;;; +10048;LINEAR B SYLLABLE B076 RA2;Lo;0;L;;;;;N;;;;; +10049;LINEAR B SYLLABLE B033 RA3;Lo;0;L;;;;;N;;;;; +1004A;LINEAR B SYLLABLE B068 RO2;Lo;0;L;;;;;N;;;;; +1004B;LINEAR B SYLLABLE B066 TA2;Lo;0;L;;;;;N;;;;; +1004C;LINEAR B SYLLABLE B087 TWE;Lo;0;L;;;;;N;;;;; +1004D;LINEAR B SYLLABLE B091 TWO;Lo;0;L;;;;;N;;;;; +10050;LINEAR B SYMBOL B018;Lo;0;L;;;;;N;;;;; +10051;LINEAR B SYMBOL B019;Lo;0;L;;;;;N;;;;; +10052;LINEAR B SYMBOL B022;Lo;0;L;;;;;N;;;;; +10053;LINEAR B SYMBOL B034;Lo;0;L;;;;;N;;;;; +10054;LINEAR B SYMBOL B047;Lo;0;L;;;;;N;;;;; +10055;LINEAR B SYMBOL B049;Lo;0;L;;;;;N;;;;; +10056;LINEAR B SYMBOL B056;Lo;0;L;;;;;N;;;;; +10057;LINEAR B SYMBOL B063;Lo;0;L;;;;;N;;;;; +10058;LINEAR B SYMBOL B064;Lo;0;L;;;;;N;;;;; +10059;LINEAR B SYMBOL B079;Lo;0;L;;;;;N;;;;; +1005A;LINEAR B SYMBOL B082;Lo;0;L;;;;;N;;;;; +1005B;LINEAR B SYMBOL B083;Lo;0;L;;;;;N;;;;; +1005C;LINEAR B SYMBOL B086;Lo;0;L;;;;;N;;;;; +1005D;LINEAR B SYMBOL B089;Lo;0;L;;;;;N;;;;; +10080;LINEAR B IDEOGRAM B100 MAN;Lo;0;L;;;;;N;;;;; +10081;LINEAR B IDEOGRAM B102 WOMAN;Lo;0;L;;;;;N;;;;; +10082;LINEAR B IDEOGRAM B104 DEER;Lo;0;L;;;;;N;;;;; +10083;LINEAR B IDEOGRAM B105 EQUID;Lo;0;L;;;;;N;;;;; +10084;LINEAR B IDEOGRAM B105F MARE;Lo;0;L;;;;;N;;;;; +10085;LINEAR B IDEOGRAM B105M STALLION;Lo;0;L;;;;;N;;;;; +10086;LINEAR B IDEOGRAM B106F EWE;Lo;0;L;;;;;N;;;;; +10087;LINEAR B IDEOGRAM B106M RAM;Lo;0;L;;;;;N;;;;; +10088;LINEAR B IDEOGRAM B107F SHE-GOAT;Lo;0;L;;;;;N;;;;; +10089;LINEAR B IDEOGRAM B107M HE-GOAT;Lo;0;L;;;;;N;;;;; +1008A;LINEAR B IDEOGRAM B108F SOW;Lo;0;L;;;;;N;;;;; +1008B;LINEAR B IDEOGRAM B108M BOAR;Lo;0;L;;;;;N;;;;; +1008C;LINEAR B IDEOGRAM B109F COW;Lo;0;L;;;;;N;;;;; +1008D;LINEAR B IDEOGRAM B109M BULL;Lo;0;L;;;;;N;;;;; +1008E;LINEAR B IDEOGRAM B120 WHEAT;Lo;0;L;;;;;N;;;;; +1008F;LINEAR B IDEOGRAM B121 BARLEY;Lo;0;L;;;;;N;;;;; +10090;LINEAR B IDEOGRAM B122 OLIVE;Lo;0;L;;;;;N;;;;; +10091;LINEAR B IDEOGRAM B123 SPICE;Lo;0;L;;;;;N;;;;; +10092;LINEAR B IDEOGRAM B125 CYPERUS;Lo;0;L;;;;;N;;;;; +10093;LINEAR B MONOGRAM B127 KAPO;Lo;0;L;;;;;N;;;;; +10094;LINEAR B MONOGRAM B128 KANAKO;Lo;0;L;;;;;N;;;;; +10095;LINEAR B IDEOGRAM B130 OIL;Lo;0;L;;;;;N;;;;; +10096;LINEAR B IDEOGRAM B131 WINE;Lo;0;L;;;;;N;;;;; +10097;LINEAR B IDEOGRAM B132;Lo;0;L;;;;;N;;;;; +10098;LINEAR B MONOGRAM B133 AREPA;Lo;0;L;;;;;N;;;;; +10099;LINEAR B MONOGRAM B135 MERI;Lo;0;L;;;;;N;;;;; +1009A;LINEAR B IDEOGRAM B140 BRONZE;Lo;0;L;;;;;N;;;;; +1009B;LINEAR B IDEOGRAM B141 GOLD;Lo;0;L;;;;;N;;;;; +1009C;LINEAR B IDEOGRAM B142;Lo;0;L;;;;;N;;;;; +1009D;LINEAR B IDEOGRAM B145 WOOL;Lo;0;L;;;;;N;;;;; +1009E;LINEAR B IDEOGRAM B146;Lo;0;L;;;;;N;;;;; +1009F;LINEAR B IDEOGRAM B150;Lo;0;L;;;;;N;;;;; +100A0;LINEAR B IDEOGRAM B151 HORN;Lo;0;L;;;;;N;;;;; +100A1;LINEAR B IDEOGRAM B152;Lo;0;L;;;;;N;;;;; +100A2;LINEAR B IDEOGRAM B153;Lo;0;L;;;;;N;;;;; +100A3;LINEAR B IDEOGRAM B154;Lo;0;L;;;;;N;;;;; +100A4;LINEAR B MONOGRAM B156 TURO2;Lo;0;L;;;;;N;;;;; +100A5;LINEAR B IDEOGRAM B157;Lo;0;L;;;;;N;;;;; +100A6;LINEAR B IDEOGRAM B158;Lo;0;L;;;;;N;;;;; +100A7;LINEAR B IDEOGRAM B159 CLOTH;Lo;0;L;;;;;N;;;;; +100A8;LINEAR B IDEOGRAM B160;Lo;0;L;;;;;N;;;;; +100A9;LINEAR B IDEOGRAM B161;Lo;0;L;;;;;N;;;;; +100AA;LINEAR B IDEOGRAM B162 GARMENT;Lo;0;L;;;;;N;;;;; +100AB;LINEAR B IDEOGRAM B163 ARMOUR;Lo;0;L;;;;;N;;;;; +100AC;LINEAR B IDEOGRAM B164;Lo;0;L;;;;;N;;;;; +100AD;LINEAR B IDEOGRAM B165;Lo;0;L;;;;;N;;;;; +100AE;LINEAR B IDEOGRAM B166;Lo;0;L;;;;;N;;;;; +100AF;LINEAR B IDEOGRAM B167;Lo;0;L;;;;;N;;;;; +100B0;LINEAR B IDEOGRAM B168;Lo;0;L;;;;;N;;;;; +100B1;LINEAR B IDEOGRAM B169;Lo;0;L;;;;;N;;;;; +100B2;LINEAR B IDEOGRAM B170;Lo;0;L;;;;;N;;;;; +100B3;LINEAR B IDEOGRAM B171;Lo;0;L;;;;;N;;;;; +100B4;LINEAR B IDEOGRAM B172;Lo;0;L;;;;;N;;;;; +100B5;LINEAR B IDEOGRAM B173 MONTH;Lo;0;L;;;;;N;;;;; +100B6;LINEAR B IDEOGRAM B174;Lo;0;L;;;;;N;;;;; +100B7;LINEAR B IDEOGRAM B176 TREE;Lo;0;L;;;;;N;;;;; +100B8;LINEAR B IDEOGRAM B177;Lo;0;L;;;;;N;;;;; +100B9;LINEAR B IDEOGRAM B178;Lo;0;L;;;;;N;;;;; +100BA;LINEAR B IDEOGRAM B179;Lo;0;L;;;;;N;;;;; +100BB;LINEAR B IDEOGRAM B180;Lo;0;L;;;;;N;;;;; +100BC;LINEAR B IDEOGRAM B181;Lo;0;L;;;;;N;;;;; +100BD;LINEAR B IDEOGRAM B182;Lo;0;L;;;;;N;;;;; +100BE;LINEAR B IDEOGRAM B183;Lo;0;L;;;;;N;;;;; +100BF;LINEAR B IDEOGRAM B184;Lo;0;L;;;;;N;;;;; +100C0;LINEAR B IDEOGRAM B185;Lo;0;L;;;;;N;;;;; +100C1;LINEAR B IDEOGRAM B189;Lo;0;L;;;;;N;;;;; +100C2;LINEAR B IDEOGRAM B190;Lo;0;L;;;;;N;;;;; +100C3;LINEAR B IDEOGRAM B191 HELMET;Lo;0;L;;;;;N;;;;; +100C4;LINEAR B IDEOGRAM B220 FOOTSTOOL;Lo;0;L;;;;;N;;;;; +100C5;LINEAR B IDEOGRAM B225 BATHTUB;Lo;0;L;;;;;N;;;;; +100C6;LINEAR B IDEOGRAM B230 SPEAR;Lo;0;L;;;;;N;;;;; +100C7;LINEAR B IDEOGRAM B231 ARROW;Lo;0;L;;;;;N;;;;; +100C8;LINEAR B IDEOGRAM B232;Lo;0;L;;;;;N;;;;; +100C9;LINEAR B IDEOGRAM B233 SWORD;Lo;0;L;;;;;N;;;;; +100CA;LINEAR B IDEOGRAM B234;Lo;0;L;;;;;N;;;;; +100CB;LINEAR B IDEOGRAM B236;Lo;0;L;;;;;N;;;;; +100CC;LINEAR B IDEOGRAM B240 WHEELED CHARIOT;Lo;0;L;;;;;N;;;;; +100CD;LINEAR B IDEOGRAM B241 CHARIOT;Lo;0;L;;;;;N;;;;; +100CE;LINEAR B IDEOGRAM B242 CHARIOT FRAME;Lo;0;L;;;;;N;;;;; +100CF;LINEAR B IDEOGRAM B243 WHEEL;Lo;0;L;;;;;N;;;;; +100D0;LINEAR B IDEOGRAM B245;Lo;0;L;;;;;N;;;;; +100D1;LINEAR B IDEOGRAM B246;Lo;0;L;;;;;N;;;;; +100D2;LINEAR B MONOGRAM B247 DIPTE;Lo;0;L;;;;;N;;;;; +100D3;LINEAR B IDEOGRAM B248;Lo;0;L;;;;;N;;;;; +100D4;LINEAR B IDEOGRAM B249;Lo;0;L;;;;;N;;;;; +100D5;LINEAR B IDEOGRAM B251;Lo;0;L;;;;;N;;;;; +100D6;LINEAR B IDEOGRAM B252;Lo;0;L;;;;;N;;;;; +100D7;LINEAR B IDEOGRAM B253;Lo;0;L;;;;;N;;;;; +100D8;LINEAR B IDEOGRAM B254 DART;Lo;0;L;;;;;N;;;;; +100D9;LINEAR B IDEOGRAM B255;Lo;0;L;;;;;N;;;;; +100DA;LINEAR B IDEOGRAM B256;Lo;0;L;;;;;N;;;;; +100DB;LINEAR B IDEOGRAM B257;Lo;0;L;;;;;N;;;;; +100DC;LINEAR B IDEOGRAM B258;Lo;0;L;;;;;N;;;;; +100DD;LINEAR B IDEOGRAM B259;Lo;0;L;;;;;N;;;;; +100DE;LINEAR B IDEOGRAM VESSEL B155;Lo;0;L;;;;;N;;;;; +100DF;LINEAR B IDEOGRAM VESSEL B200;Lo;0;L;;;;;N;;;;; +100E0;LINEAR B IDEOGRAM VESSEL B201;Lo;0;L;;;;;N;;;;; +100E1;LINEAR B IDEOGRAM VESSEL B202;Lo;0;L;;;;;N;;;;; +100E2;LINEAR B IDEOGRAM VESSEL B203;Lo;0;L;;;;;N;;;;; +100E3;LINEAR B IDEOGRAM VESSEL B204;Lo;0;L;;;;;N;;;;; +100E4;LINEAR B IDEOGRAM VESSEL B205;Lo;0;L;;;;;N;;;;; +100E5;LINEAR B IDEOGRAM VESSEL B206;Lo;0;L;;;;;N;;;;; +100E6;LINEAR B IDEOGRAM VESSEL B207;Lo;0;L;;;;;N;;;;; +100E7;LINEAR B IDEOGRAM VESSEL B208;Lo;0;L;;;;;N;;;;; +100E8;LINEAR B IDEOGRAM VESSEL B209;Lo;0;L;;;;;N;;;;; +100E9;LINEAR B IDEOGRAM VESSEL B210;Lo;0;L;;;;;N;;;;; +100EA;LINEAR B IDEOGRAM VESSEL B211;Lo;0;L;;;;;N;;;;; +100EB;LINEAR B IDEOGRAM VESSEL B212;Lo;0;L;;;;;N;;;;; +100EC;LINEAR B IDEOGRAM VESSEL B213;Lo;0;L;;;;;N;;;;; +100ED;LINEAR B IDEOGRAM VESSEL B214;Lo;0;L;;;;;N;;;;; +100EE;LINEAR B IDEOGRAM VESSEL B215;Lo;0;L;;;;;N;;;;; +100EF;LINEAR B IDEOGRAM VESSEL B216;Lo;0;L;;;;;N;;;;; +100F0;LINEAR B IDEOGRAM VESSEL B217;Lo;0;L;;;;;N;;;;; +100F1;LINEAR B IDEOGRAM VESSEL B218;Lo;0;L;;;;;N;;;;; +100F2;LINEAR B IDEOGRAM VESSEL B219;Lo;0;L;;;;;N;;;;; +100F3;LINEAR B IDEOGRAM VESSEL B221;Lo;0;L;;;;;N;;;;; +100F4;LINEAR B IDEOGRAM VESSEL B222;Lo;0;L;;;;;N;;;;; +100F5;LINEAR B IDEOGRAM VESSEL B226;Lo;0;L;;;;;N;;;;; +100F6;LINEAR B IDEOGRAM VESSEL B227;Lo;0;L;;;;;N;;;;; +100F7;LINEAR B IDEOGRAM VESSEL B228;Lo;0;L;;;;;N;;;;; +100F8;LINEAR B IDEOGRAM VESSEL B229;Lo;0;L;;;;;N;;;;; +100F9;LINEAR B IDEOGRAM VESSEL B250;Lo;0;L;;;;;N;;;;; +100FA;LINEAR B IDEOGRAM VESSEL B305;Lo;0;L;;;;;N;;;;; +10100;AEGEAN WORD SEPARATOR LINE;Po;0;L;;;;;N;;;;; +10101;AEGEAN WORD SEPARATOR DOT;Po;0;ON;;;;;N;;;;; +10102;AEGEAN CHECK MARK;Po;0;L;;;;;N;;;;; +10107;AEGEAN NUMBER ONE;No;0;L;;;;1;N;;;;; +10108;AEGEAN NUMBER TWO;No;0;L;;;;2;N;;;;; +10109;AEGEAN NUMBER THREE;No;0;L;;;;3;N;;;;; +1010A;AEGEAN NUMBER FOUR;No;0;L;;;;4;N;;;;; +1010B;AEGEAN NUMBER FIVE;No;0;L;;;;5;N;;;;; +1010C;AEGEAN NUMBER SIX;No;0;L;;;;6;N;;;;; +1010D;AEGEAN NUMBER SEVEN;No;0;L;;;;7;N;;;;; +1010E;AEGEAN NUMBER EIGHT;No;0;L;;;;8;N;;;;; +1010F;AEGEAN NUMBER NINE;No;0;L;;;;9;N;;;;; +10110;AEGEAN NUMBER TEN;No;0;L;;;;10;N;;;;; +10111;AEGEAN NUMBER TWENTY;No;0;L;;;;20;N;;;;; +10112;AEGEAN NUMBER THIRTY;No;0;L;;;;30;N;;;;; +10113;AEGEAN NUMBER FORTY;No;0;L;;;;40;N;;;;; +10114;AEGEAN NUMBER FIFTY;No;0;L;;;;50;N;;;;; +10115;AEGEAN NUMBER SIXTY;No;0;L;;;;60;N;;;;; +10116;AEGEAN NUMBER SEVENTY;No;0;L;;;;70;N;;;;; +10117;AEGEAN NUMBER EIGHTY;No;0;L;;;;80;N;;;;; +10118;AEGEAN NUMBER NINETY;No;0;L;;;;90;N;;;;; +10119;AEGEAN NUMBER ONE HUNDRED;No;0;L;;;;100;N;;;;; +1011A;AEGEAN NUMBER TWO HUNDRED;No;0;L;;;;200;N;;;;; +1011B;AEGEAN NUMBER THREE HUNDRED;No;0;L;;;;300;N;;;;; +1011C;AEGEAN NUMBER FOUR HUNDRED;No;0;L;;;;400;N;;;;; +1011D;AEGEAN NUMBER FIVE HUNDRED;No;0;L;;;;500;N;;;;; +1011E;AEGEAN NUMBER SIX HUNDRED;No;0;L;;;;600;N;;;;; +1011F;AEGEAN NUMBER SEVEN HUNDRED;No;0;L;;;;700;N;;;;; +10120;AEGEAN NUMBER EIGHT HUNDRED;No;0;L;;;;800;N;;;;; +10121;AEGEAN NUMBER NINE HUNDRED;No;0;L;;;;900;N;;;;; +10122;AEGEAN NUMBER ONE THOUSAND;No;0;L;;;;1000;N;;;;; +10123;AEGEAN NUMBER TWO THOUSAND;No;0;L;;;;2000;N;;;;; +10124;AEGEAN NUMBER THREE THOUSAND;No;0;L;;;;3000;N;;;;; +10125;AEGEAN NUMBER FOUR THOUSAND;No;0;L;;;;4000;N;;;;; +10126;AEGEAN NUMBER FIVE THOUSAND;No;0;L;;;;5000;N;;;;; +10127;AEGEAN NUMBER SIX THOUSAND;No;0;L;;;;6000;N;;;;; +10128;AEGEAN NUMBER SEVEN THOUSAND;No;0;L;;;;7000;N;;;;; +10129;AEGEAN NUMBER EIGHT THOUSAND;No;0;L;;;;8000;N;;;;; +1012A;AEGEAN NUMBER NINE THOUSAND;No;0;L;;;;9000;N;;;;; +1012B;AEGEAN NUMBER TEN THOUSAND;No;0;L;;;;10000;N;;;;; +1012C;AEGEAN NUMBER TWENTY THOUSAND;No;0;L;;;;20000;N;;;;; +1012D;AEGEAN NUMBER THIRTY THOUSAND;No;0;L;;;;30000;N;;;;; +1012E;AEGEAN NUMBER FORTY THOUSAND;No;0;L;;;;40000;N;;;;; +1012F;AEGEAN NUMBER FIFTY THOUSAND;No;0;L;;;;50000;N;;;;; +10130;AEGEAN NUMBER SIXTY THOUSAND;No;0;L;;;;60000;N;;;;; +10131;AEGEAN NUMBER SEVENTY THOUSAND;No;0;L;;;;70000;N;;;;; +10132;AEGEAN NUMBER EIGHTY THOUSAND;No;0;L;;;;80000;N;;;;; +10133;AEGEAN NUMBER NINETY THOUSAND;No;0;L;;;;90000;N;;;;; +10137;AEGEAN WEIGHT BASE UNIT;So;0;L;;;;;N;;;;; +10138;AEGEAN WEIGHT FIRST SUBUNIT;So;0;L;;;;;N;;;;; +10139;AEGEAN WEIGHT SECOND SUBUNIT;So;0;L;;;;;N;;;;; +1013A;AEGEAN WEIGHT THIRD SUBUNIT;So;0;L;;;;;N;;;;; +1013B;AEGEAN WEIGHT FOURTH SUBUNIT;So;0;L;;;;;N;;;;; +1013C;AEGEAN DRY MEASURE FIRST SUBUNIT;So;0;L;;;;;N;;;;; +1013D;AEGEAN LIQUID MEASURE FIRST SUBUNIT;So;0;L;;;;;N;;;;; +1013E;AEGEAN MEASURE SECOND SUBUNIT;So;0;L;;;;;N;;;;; +1013F;AEGEAN MEASURE THIRD SUBUNIT;So;0;L;;;;;N;;;;; +10140;GREEK ACROPHONIC ATTIC ONE QUARTER;Nl;0;ON;;;;1/4;N;;;;; +10141;GREEK ACROPHONIC ATTIC ONE HALF;Nl;0;ON;;;;1/2;N;;;;; +10142;GREEK ACROPHONIC ATTIC ONE DRACHMA;Nl;0;ON;;;;1;N;;;;; +10143;GREEK ACROPHONIC ATTIC FIVE;Nl;0;ON;;;;5;N;;;;; +10144;GREEK ACROPHONIC ATTIC FIFTY;Nl;0;ON;;;;50;N;;;;; +10145;GREEK ACROPHONIC ATTIC FIVE HUNDRED;Nl;0;ON;;;;500;N;;;;; +10146;GREEK ACROPHONIC ATTIC FIVE THOUSAND;Nl;0;ON;;;;5000;N;;;;; +10147;GREEK ACROPHONIC ATTIC FIFTY THOUSAND;Nl;0;ON;;;;50000;N;;;;; +10148;GREEK ACROPHONIC ATTIC FIVE TALENTS;Nl;0;ON;;;;5;N;;;;; +10149;GREEK ACROPHONIC ATTIC TEN TALENTS;Nl;0;ON;;;;10;N;;;;; +1014A;GREEK ACROPHONIC ATTIC FIFTY TALENTS;Nl;0;ON;;;;50;N;;;;; +1014B;GREEK ACROPHONIC ATTIC ONE HUNDRED TALENTS;Nl;0;ON;;;;100;N;;;;; +1014C;GREEK ACROPHONIC ATTIC FIVE HUNDRED TALENTS;Nl;0;ON;;;;500;N;;;;; +1014D;GREEK ACROPHONIC ATTIC ONE THOUSAND TALENTS;Nl;0;ON;;;;1000;N;;;;; +1014E;GREEK ACROPHONIC ATTIC FIVE THOUSAND TALENTS;Nl;0;ON;;;;5000;N;;;;; +1014F;GREEK ACROPHONIC ATTIC FIVE STATERS;Nl;0;ON;;;;5;N;;;;; +10150;GREEK ACROPHONIC ATTIC TEN STATERS;Nl;0;ON;;;;10;N;;;;; +10151;GREEK ACROPHONIC ATTIC FIFTY STATERS;Nl;0;ON;;;;50;N;;;;; +10152;GREEK ACROPHONIC ATTIC ONE HUNDRED STATERS;Nl;0;ON;;;;100;N;;;;; +10153;GREEK ACROPHONIC ATTIC FIVE HUNDRED STATERS;Nl;0;ON;;;;500;N;;;;; +10154;GREEK ACROPHONIC ATTIC ONE THOUSAND STATERS;Nl;0;ON;;;;1000;N;;;;; +10155;GREEK ACROPHONIC ATTIC TEN THOUSAND STATERS;Nl;0;ON;;;;10000;N;;;;; +10156;GREEK ACROPHONIC ATTIC FIFTY THOUSAND STATERS;Nl;0;ON;;;;50000;N;;;;; +10157;GREEK ACROPHONIC ATTIC TEN MNAS;Nl;0;ON;;;;10;N;;;;; +10158;GREEK ACROPHONIC HERAEUM ONE PLETHRON;Nl;0;ON;;;;1;N;;;;; +10159;GREEK ACROPHONIC THESPIAN ONE;Nl;0;ON;;;;1;N;;;;; +1015A;GREEK ACROPHONIC HERMIONIAN ONE;Nl;0;ON;;;;1;N;;;;; +1015B;GREEK ACROPHONIC EPIDAUREAN TWO;Nl;0;ON;;;;2;N;;;;; +1015C;GREEK ACROPHONIC THESPIAN TWO;Nl;0;ON;;;;2;N;;;;; +1015D;GREEK ACROPHONIC CYRENAIC TWO DRACHMAS;Nl;0;ON;;;;2;N;;;;; +1015E;GREEK ACROPHONIC EPIDAUREAN TWO DRACHMAS;Nl;0;ON;;;;2;N;;;;; +1015F;GREEK ACROPHONIC TROEZENIAN FIVE;Nl;0;ON;;;;5;N;;;;; +10160;GREEK ACROPHONIC TROEZENIAN TEN;Nl;0;ON;;;;10;N;;;;; +10161;GREEK ACROPHONIC TROEZENIAN TEN ALTERNATE FORM;Nl;0;ON;;;;10;N;;;;; +10162;GREEK ACROPHONIC HERMIONIAN TEN;Nl;0;ON;;;;10;N;;;;; +10163;GREEK ACROPHONIC MESSENIAN TEN;Nl;0;ON;;;;10;N;;;;; +10164;GREEK ACROPHONIC THESPIAN TEN;Nl;0;ON;;;;10;N;;;;; +10165;GREEK ACROPHONIC THESPIAN THIRTY;Nl;0;ON;;;;30;N;;;;; +10166;GREEK ACROPHONIC TROEZENIAN FIFTY;Nl;0;ON;;;;50;N;;;;; +10167;GREEK ACROPHONIC TROEZENIAN FIFTY ALTERNATE FORM;Nl;0;ON;;;;50;N;;;;; +10168;GREEK ACROPHONIC HERMIONIAN FIFTY;Nl;0;ON;;;;50;N;;;;; +10169;GREEK ACROPHONIC THESPIAN FIFTY;Nl;0;ON;;;;50;N;;;;; +1016A;GREEK ACROPHONIC THESPIAN ONE HUNDRED;Nl;0;ON;;;;100;N;;;;; +1016B;GREEK ACROPHONIC THESPIAN THREE HUNDRED;Nl;0;ON;;;;300;N;;;;; +1016C;GREEK ACROPHONIC EPIDAUREAN FIVE HUNDRED;Nl;0;ON;;;;500;N;;;;; +1016D;GREEK ACROPHONIC TROEZENIAN FIVE HUNDRED;Nl;0;ON;;;;500;N;;;;; +1016E;GREEK ACROPHONIC THESPIAN FIVE HUNDRED;Nl;0;ON;;;;500;N;;;;; +1016F;GREEK ACROPHONIC CARYSTIAN FIVE HUNDRED;Nl;0;ON;;;;500;N;;;;; +10170;GREEK ACROPHONIC NAXIAN FIVE HUNDRED;Nl;0;ON;;;;500;N;;;;; +10171;GREEK ACROPHONIC THESPIAN ONE THOUSAND;Nl;0;ON;;;;1000;N;;;;; +10172;GREEK ACROPHONIC THESPIAN FIVE THOUSAND;Nl;0;ON;;;;5000;N;;;;; +10173;GREEK ACROPHONIC DELPHIC FIVE MNAS;Nl;0;ON;;;;5;N;;;;; +10174;GREEK ACROPHONIC STRATIAN FIFTY MNAS;Nl;0;ON;;;;50;N;;;;; +10175;GREEK ONE HALF SIGN;No;0;ON;;;;1/2;N;;;;; +10176;GREEK ONE HALF SIGN ALTERNATE FORM;No;0;ON;;;;1/2;N;;;;; +10177;GREEK TWO THIRDS SIGN;No;0;ON;;;;2/3;N;;;;; +10178;GREEK THREE QUARTERS SIGN;No;0;ON;;;;3/4;N;;;;; +10179;GREEK YEAR SIGN;So;0;ON;;;;;N;;;;; +1017A;GREEK TALENT SIGN;So;0;ON;;;;;N;;;;; +1017B;GREEK DRACHMA SIGN;So;0;ON;;;;;N;;;;; +1017C;GREEK OBOL SIGN;So;0;ON;;;;;N;;;;; +1017D;GREEK TWO OBOLS SIGN;So;0;ON;;;;;N;;;;; +1017E;GREEK THREE OBOLS SIGN;So;0;ON;;;;;N;;;;; +1017F;GREEK FOUR OBOLS SIGN;So;0;ON;;;;;N;;;;; +10180;GREEK FIVE OBOLS SIGN;So;0;ON;;;;;N;;;;; +10181;GREEK METRETES SIGN;So;0;ON;;;;;N;;;;; +10182;GREEK KYATHOS BASE SIGN;So;0;ON;;;;;N;;;;; +10183;GREEK LITRA SIGN;So;0;ON;;;;;N;;;;; +10184;GREEK OUNKIA SIGN;So;0;ON;;;;;N;;;;; +10185;GREEK XESTES SIGN;So;0;ON;;;;;N;;;;; +10186;GREEK ARTABE SIGN;So;0;ON;;;;;N;;;;; +10187;GREEK AROURA SIGN;So;0;ON;;;;;N;;;;; +10188;GREEK GRAMMA SIGN;So;0;ON;;;;;N;;;;; +10189;GREEK TRYBLION BASE SIGN;So;0;ON;;;;;N;;;;; +1018A;GREEK ZERO SIGN;No;0;ON;;;;0;N;;;;; +10190;ROMAN SEXTANS SIGN;So;0;ON;;;;;N;;;;; +10191;ROMAN UNCIA SIGN;So;0;ON;;;;;N;;;;; +10192;ROMAN SEMUNCIA SIGN;So;0;ON;;;;;N;;;;; +10193;ROMAN SEXTULA SIGN;So;0;ON;;;;;N;;;;; +10194;ROMAN DIMIDIA SEXTULA SIGN;So;0;ON;;;;;N;;;;; +10195;ROMAN SILIQUA SIGN;So;0;ON;;;;;N;;;;; +10196;ROMAN DENARIUS SIGN;So;0;ON;;;;;N;;;;; +10197;ROMAN QUINARIUS SIGN;So;0;ON;;;;;N;;;;; +10198;ROMAN SESTERTIUS SIGN;So;0;ON;;;;;N;;;;; +10199;ROMAN DUPONDIUS SIGN;So;0;ON;;;;;N;;;;; +1019A;ROMAN AS SIGN;So;0;ON;;;;;N;;;;; +1019B;ROMAN CENTURIAL SIGN;So;0;ON;;;;;N;;;;; +101D0;PHAISTOS DISC SIGN PEDESTRIAN;So;0;L;;;;;N;;;;; +101D1;PHAISTOS DISC SIGN PLUMED HEAD;So;0;L;;;;;N;;;;; +101D2;PHAISTOS DISC SIGN TATTOOED HEAD;So;0;L;;;;;N;;;;; +101D3;PHAISTOS DISC SIGN CAPTIVE;So;0;L;;;;;N;;;;; +101D4;PHAISTOS DISC SIGN CHILD;So;0;L;;;;;N;;;;; +101D5;PHAISTOS DISC SIGN WOMAN;So;0;L;;;;;N;;;;; +101D6;PHAISTOS DISC SIGN HELMET;So;0;L;;;;;N;;;;; +101D7;PHAISTOS DISC SIGN GAUNTLET;So;0;L;;;;;N;;;;; +101D8;PHAISTOS DISC SIGN TIARA;So;0;L;;;;;N;;;;; +101D9;PHAISTOS DISC SIGN ARROW;So;0;L;;;;;N;;;;; +101DA;PHAISTOS DISC SIGN BOW;So;0;L;;;;;N;;;;; +101DB;PHAISTOS DISC SIGN SHIELD;So;0;L;;;;;N;;;;; +101DC;PHAISTOS DISC SIGN CLUB;So;0;L;;;;;N;;;;; +101DD;PHAISTOS DISC SIGN MANACLES;So;0;L;;;;;N;;;;; +101DE;PHAISTOS DISC SIGN MATTOCK;So;0;L;;;;;N;;;;; +101DF;PHAISTOS DISC SIGN SAW;So;0;L;;;;;N;;;;; +101E0;PHAISTOS DISC SIGN LID;So;0;L;;;;;N;;;;; +101E1;PHAISTOS DISC SIGN BOOMERANG;So;0;L;;;;;N;;;;; +101E2;PHAISTOS DISC SIGN CARPENTRY PLANE;So;0;L;;;;;N;;;;; +101E3;PHAISTOS DISC SIGN DOLIUM;So;0;L;;;;;N;;;;; +101E4;PHAISTOS DISC SIGN COMB;So;0;L;;;;;N;;;;; +101E5;PHAISTOS DISC SIGN SLING;So;0;L;;;;;N;;;;; +101E6;PHAISTOS DISC SIGN COLUMN;So;0;L;;;;;N;;;;; +101E7;PHAISTOS DISC SIGN BEEHIVE;So;0;L;;;;;N;;;;; +101E8;PHAISTOS DISC SIGN SHIP;So;0;L;;;;;N;;;;; +101E9;PHAISTOS DISC SIGN HORN;So;0;L;;;;;N;;;;; +101EA;PHAISTOS DISC SIGN HIDE;So;0;L;;;;;N;;;;; +101EB;PHAISTOS DISC SIGN BULLS LEG;So;0;L;;;;;N;;;;; +101EC;PHAISTOS DISC SIGN CAT;So;0;L;;;;;N;;;;; +101ED;PHAISTOS DISC SIGN RAM;So;0;L;;;;;N;;;;; +101EE;PHAISTOS DISC SIGN EAGLE;So;0;L;;;;;N;;;;; +101EF;PHAISTOS DISC SIGN DOVE;So;0;L;;;;;N;;;;; +101F0;PHAISTOS DISC SIGN TUNNY;So;0;L;;;;;N;;;;; +101F1;PHAISTOS DISC SIGN BEE;So;0;L;;;;;N;;;;; +101F2;PHAISTOS DISC SIGN PLANE TREE;So;0;L;;;;;N;;;;; +101F3;PHAISTOS DISC SIGN VINE;So;0;L;;;;;N;;;;; +101F4;PHAISTOS DISC SIGN PAPYRUS;So;0;L;;;;;N;;;;; +101F5;PHAISTOS DISC SIGN ROSETTE;So;0;L;;;;;N;;;;; +101F6;PHAISTOS DISC SIGN LILY;So;0;L;;;;;N;;;;; +101F7;PHAISTOS DISC SIGN OX BACK;So;0;L;;;;;N;;;;; +101F8;PHAISTOS DISC SIGN FLUTE;So;0;L;;;;;N;;;;; +101F9;PHAISTOS DISC SIGN GRATER;So;0;L;;;;;N;;;;; +101FA;PHAISTOS DISC SIGN STRAINER;So;0;L;;;;;N;;;;; +101FB;PHAISTOS DISC SIGN SMALL AXE;So;0;L;;;;;N;;;;; +101FC;PHAISTOS DISC SIGN WAVY BAND;So;0;L;;;;;N;;;;; +101FD;PHAISTOS DISC SIGN COMBINING OBLIQUE STROKE;Mn;220;NSM;;;;;N;;;;; +10280;LYCIAN LETTER A;Lo;0;L;;;;;N;;;;; +10281;LYCIAN LETTER E;Lo;0;L;;;;;N;;;;; +10282;LYCIAN LETTER B;Lo;0;L;;;;;N;;;;; +10283;LYCIAN LETTER BH;Lo;0;L;;;;;N;;;;; +10284;LYCIAN LETTER G;Lo;0;L;;;;;N;;;;; +10285;LYCIAN LETTER D;Lo;0;L;;;;;N;;;;; +10286;LYCIAN LETTER I;Lo;0;L;;;;;N;;;;; +10287;LYCIAN LETTER W;Lo;0;L;;;;;N;;;;; +10288;LYCIAN LETTER Z;Lo;0;L;;;;;N;;;;; +10289;LYCIAN LETTER TH;Lo;0;L;;;;;N;;;;; +1028A;LYCIAN LETTER J;Lo;0;L;;;;;N;;;;; +1028B;LYCIAN LETTER K;Lo;0;L;;;;;N;;;;; +1028C;LYCIAN LETTER Q;Lo;0;L;;;;;N;;;;; +1028D;LYCIAN LETTER L;Lo;0;L;;;;;N;;;;; +1028E;LYCIAN LETTER M;Lo;0;L;;;;;N;;;;; +1028F;LYCIAN LETTER N;Lo;0;L;;;;;N;;;;; +10290;LYCIAN LETTER MM;Lo;0;L;;;;;N;;;;; +10291;LYCIAN LETTER NN;Lo;0;L;;;;;N;;;;; +10292;LYCIAN LETTER U;Lo;0;L;;;;;N;;;;; +10293;LYCIAN LETTER P;Lo;0;L;;;;;N;;;;; +10294;LYCIAN LETTER KK;Lo;0;L;;;;;N;;;;; +10295;LYCIAN LETTER R;Lo;0;L;;;;;N;;;;; +10296;LYCIAN LETTER S;Lo;0;L;;;;;N;;;;; +10297;LYCIAN LETTER T;Lo;0;L;;;;;N;;;;; +10298;LYCIAN LETTER TT;Lo;0;L;;;;;N;;;;; +10299;LYCIAN LETTER AN;Lo;0;L;;;;;N;;;;; +1029A;LYCIAN LETTER EN;Lo;0;L;;;;;N;;;;; +1029B;LYCIAN LETTER H;Lo;0;L;;;;;N;;;;; +1029C;LYCIAN LETTER X;Lo;0;L;;;;;N;;;;; +102A0;CARIAN LETTER A;Lo;0;L;;;;;N;;;;; +102A1;CARIAN LETTER P2;Lo;0;L;;;;;N;;;;; +102A2;CARIAN LETTER D;Lo;0;L;;;;;N;;;;; +102A3;CARIAN LETTER L;Lo;0;L;;;;;N;;;;; +102A4;CARIAN LETTER UUU;Lo;0;L;;;;;N;;;;; +102A5;CARIAN LETTER R;Lo;0;L;;;;;N;;;;; +102A6;CARIAN LETTER LD;Lo;0;L;;;;;N;;;;; +102A7;CARIAN LETTER A2;Lo;0;L;;;;;N;;;;; +102A8;CARIAN LETTER Q;Lo;0;L;;;;;N;;;;; +102A9;CARIAN LETTER B;Lo;0;L;;;;;N;;;;; +102AA;CARIAN LETTER M;Lo;0;L;;;;;N;;;;; +102AB;CARIAN LETTER O;Lo;0;L;;;;;N;;;;; +102AC;CARIAN LETTER D2;Lo;0;L;;;;;N;;;;; +102AD;CARIAN LETTER T;Lo;0;L;;;;;N;;;;; +102AE;CARIAN LETTER SH;Lo;0;L;;;;;N;;;;; +102AF;CARIAN LETTER SH2;Lo;0;L;;;;;N;;;;; +102B0;CARIAN LETTER S;Lo;0;L;;;;;N;;;;; +102B1;CARIAN LETTER C-18;Lo;0;L;;;;;N;;;;; +102B2;CARIAN LETTER U;Lo;0;L;;;;;N;;;;; +102B3;CARIAN LETTER NN;Lo;0;L;;;;;N;;;;; +102B4;CARIAN LETTER X;Lo;0;L;;;;;N;;;;; +102B5;CARIAN LETTER N;Lo;0;L;;;;;N;;;;; +102B6;CARIAN LETTER TT2;Lo;0;L;;;;;N;;;;; +102B7;CARIAN LETTER P;Lo;0;L;;;;;N;;;;; +102B8;CARIAN LETTER SS;Lo;0;L;;;;;N;;;;; +102B9;CARIAN LETTER I;Lo;0;L;;;;;N;;;;; +102BA;CARIAN LETTER E;Lo;0;L;;;;;N;;;;; +102BB;CARIAN LETTER UUUU;Lo;0;L;;;;;N;;;;; +102BC;CARIAN LETTER K;Lo;0;L;;;;;N;;;;; +102BD;CARIAN LETTER K2;Lo;0;L;;;;;N;;;;; +102BE;CARIAN LETTER ND;Lo;0;L;;;;;N;;;;; +102BF;CARIAN LETTER UU;Lo;0;L;;;;;N;;;;; +102C0;CARIAN LETTER G;Lo;0;L;;;;;N;;;;; +102C1;CARIAN LETTER G2;Lo;0;L;;;;;N;;;;; +102C2;CARIAN LETTER ST;Lo;0;L;;;;;N;;;;; +102C3;CARIAN LETTER ST2;Lo;0;L;;;;;N;;;;; +102C4;CARIAN LETTER NG;Lo;0;L;;;;;N;;;;; +102C5;CARIAN LETTER II;Lo;0;L;;;;;N;;;;; +102C6;CARIAN LETTER C-39;Lo;0;L;;;;;N;;;;; +102C7;CARIAN LETTER TT;Lo;0;L;;;;;N;;;;; +102C8;CARIAN LETTER UUU2;Lo;0;L;;;;;N;;;;; +102C9;CARIAN LETTER RR;Lo;0;L;;;;;N;;;;; +102CA;CARIAN LETTER MB;Lo;0;L;;;;;N;;;;; +102CB;CARIAN LETTER MB2;Lo;0;L;;;;;N;;;;; +102CC;CARIAN LETTER MB3;Lo;0;L;;;;;N;;;;; +102CD;CARIAN LETTER MB4;Lo;0;L;;;;;N;;;;; +102CE;CARIAN LETTER LD2;Lo;0;L;;;;;N;;;;; +102CF;CARIAN LETTER E2;Lo;0;L;;;;;N;;;;; +102D0;CARIAN LETTER UUU3;Lo;0;L;;;;;N;;;;; +10300;OLD ITALIC LETTER A;Lo;0;L;;;;;N;;;;; +10301;OLD ITALIC LETTER BE;Lo;0;L;;;;;N;;;;; +10302;OLD ITALIC LETTER KE;Lo;0;L;;;;;N;;;;; +10303;OLD ITALIC LETTER DE;Lo;0;L;;;;;N;;;;; +10304;OLD ITALIC LETTER E;Lo;0;L;;;;;N;;;;; +10305;OLD ITALIC LETTER VE;Lo;0;L;;;;;N;;;;; +10306;OLD ITALIC LETTER ZE;Lo;0;L;;;;;N;;;;; +10307;OLD ITALIC LETTER HE;Lo;0;L;;;;;N;;;;; +10308;OLD ITALIC LETTER THE;Lo;0;L;;;;;N;;;;; +10309;OLD ITALIC LETTER I;Lo;0;L;;;;;N;;;;; +1030A;OLD ITALIC LETTER KA;Lo;0;L;;;;;N;;;;; +1030B;OLD ITALIC LETTER EL;Lo;0;L;;;;;N;;;;; +1030C;OLD ITALIC LETTER EM;Lo;0;L;;;;;N;;;;; +1030D;OLD ITALIC LETTER EN;Lo;0;L;;;;;N;;;;; +1030E;OLD ITALIC LETTER ESH;Lo;0;L;;;;;N;;;;; +1030F;OLD ITALIC LETTER O;Lo;0;L;;;;;N;;;;; +10310;OLD ITALIC LETTER PE;Lo;0;L;;;;;N;;;;; +10311;OLD ITALIC LETTER SHE;Lo;0;L;;;;;N;;;;; +10312;OLD ITALIC LETTER KU;Lo;0;L;;;;;N;;;;; +10313;OLD ITALIC LETTER ER;Lo;0;L;;;;;N;;;;; +10314;OLD ITALIC LETTER ES;Lo;0;L;;;;;N;;;;; +10315;OLD ITALIC LETTER TE;Lo;0;L;;;;;N;;;;; +10316;OLD ITALIC LETTER U;Lo;0;L;;;;;N;;;;; +10317;OLD ITALIC LETTER EKS;Lo;0;L;;;;;N;;;;; +10318;OLD ITALIC LETTER PHE;Lo;0;L;;;;;N;;;;; +10319;OLD ITALIC LETTER KHE;Lo;0;L;;;;;N;;;;; +1031A;OLD ITALIC LETTER EF;Lo;0;L;;;;;N;;;;; +1031B;OLD ITALIC LETTER ERS;Lo;0;L;;;;;N;;;;; +1031C;OLD ITALIC LETTER CHE;Lo;0;L;;;;;N;;;;; +1031D;OLD ITALIC LETTER II;Lo;0;L;;;;;N;;;;; +1031E;OLD ITALIC LETTER UU;Lo;0;L;;;;;N;;;;; +10320;OLD ITALIC NUMERAL ONE;No;0;L;;;;1;N;;;;; +10321;OLD ITALIC NUMERAL FIVE;No;0;L;;;;5;N;;;;; +10322;OLD ITALIC NUMERAL TEN;No;0;L;;;;10;N;;;;; +10323;OLD ITALIC NUMERAL FIFTY;No;0;L;;;;50;N;;;;; +10330;GOTHIC LETTER AHSA;Lo;0;L;;;;;N;;;;; +10331;GOTHIC LETTER BAIRKAN;Lo;0;L;;;;;N;;;;; +10332;GOTHIC LETTER GIBA;Lo;0;L;;;;;N;;;;; +10333;GOTHIC LETTER DAGS;Lo;0;L;;;;;N;;;;; +10334;GOTHIC LETTER AIHVUS;Lo;0;L;;;;;N;;;;; +10335;GOTHIC LETTER QAIRTHRA;Lo;0;L;;;;;N;;;;; +10336;GOTHIC LETTER IUJA;Lo;0;L;;;;;N;;;;; +10337;GOTHIC LETTER HAGL;Lo;0;L;;;;;N;;;;; +10338;GOTHIC LETTER THIUTH;Lo;0;L;;;;;N;;;;; +10339;GOTHIC LETTER EIS;Lo;0;L;;;;;N;;;;; +1033A;GOTHIC LETTER KUSMA;Lo;0;L;;;;;N;;;;; +1033B;GOTHIC LETTER LAGUS;Lo;0;L;;;;;N;;;;; +1033C;GOTHIC LETTER MANNA;Lo;0;L;;;;;N;;;;; +1033D;GOTHIC LETTER NAUTHS;Lo;0;L;;;;;N;;;;; +1033E;GOTHIC LETTER JER;Lo;0;L;;;;;N;;;;; +1033F;GOTHIC LETTER URUS;Lo;0;L;;;;;N;;;;; +10340;GOTHIC LETTER PAIRTHRA;Lo;0;L;;;;;N;;;;; +10341;GOTHIC LETTER NINETY;Nl;0;L;;;;90;N;;;;; +10342;GOTHIC LETTER RAIDA;Lo;0;L;;;;;N;;;;; +10343;GOTHIC LETTER SAUIL;Lo;0;L;;;;;N;;;;; +10344;GOTHIC LETTER TEIWS;Lo;0;L;;;;;N;;;;; +10345;GOTHIC LETTER WINJA;Lo;0;L;;;;;N;;;;; +10346;GOTHIC LETTER FAIHU;Lo;0;L;;;;;N;;;;; +10347;GOTHIC LETTER IGGWS;Lo;0;L;;;;;N;;;;; +10348;GOTHIC LETTER HWAIR;Lo;0;L;;;;;N;;;;; +10349;GOTHIC LETTER OTHAL;Lo;0;L;;;;;N;;;;; +1034A;GOTHIC LETTER NINE HUNDRED;Nl;0;L;;;;900;N;;;;; +10380;UGARITIC LETTER ALPA;Lo;0;L;;;;;N;;;;; +10381;UGARITIC LETTER BETA;Lo;0;L;;;;;N;;;;; +10382;UGARITIC LETTER GAMLA;Lo;0;L;;;;;N;;;;; +10383;UGARITIC LETTER KHA;Lo;0;L;;;;;N;;;;; +10384;UGARITIC LETTER DELTA;Lo;0;L;;;;;N;;;;; +10385;UGARITIC LETTER HO;Lo;0;L;;;;;N;;;;; +10386;UGARITIC LETTER WO;Lo;0;L;;;;;N;;;;; +10387;UGARITIC LETTER ZETA;Lo;0;L;;;;;N;;;;; +10388;UGARITIC LETTER HOTA;Lo;0;L;;;;;N;;;;; +10389;UGARITIC LETTER TET;Lo;0;L;;;;;N;;;;; +1038A;UGARITIC LETTER YOD;Lo;0;L;;;;;N;;;;; +1038B;UGARITIC LETTER KAF;Lo;0;L;;;;;N;;;;; +1038C;UGARITIC LETTER SHIN;Lo;0;L;;;;;N;;;;; +1038D;UGARITIC LETTER LAMDA;Lo;0;L;;;;;N;;;;; +1038E;UGARITIC LETTER MEM;Lo;0;L;;;;;N;;;;; +1038F;UGARITIC LETTER DHAL;Lo;0;L;;;;;N;;;;; +10390;UGARITIC LETTER NUN;Lo;0;L;;;;;N;;;;; +10391;UGARITIC LETTER ZU;Lo;0;L;;;;;N;;;;; +10392;UGARITIC LETTER SAMKA;Lo;0;L;;;;;N;;;;; +10393;UGARITIC LETTER AIN;Lo;0;L;;;;;N;;;;; +10394;UGARITIC LETTER PU;Lo;0;L;;;;;N;;;;; +10395;UGARITIC LETTER SADE;Lo;0;L;;;;;N;;;;; +10396;UGARITIC LETTER QOPA;Lo;0;L;;;;;N;;;;; +10397;UGARITIC LETTER RASHA;Lo;0;L;;;;;N;;;;; +10398;UGARITIC LETTER THANNA;Lo;0;L;;;;;N;;;;; +10399;UGARITIC LETTER GHAIN;Lo;0;L;;;;;N;;;;; +1039A;UGARITIC LETTER TO;Lo;0;L;;;;;N;;;;; +1039B;UGARITIC LETTER I;Lo;0;L;;;;;N;;;;; +1039C;UGARITIC LETTER U;Lo;0;L;;;;;N;;;;; +1039D;UGARITIC LETTER SSU;Lo;0;L;;;;;N;;;;; +1039F;UGARITIC WORD DIVIDER;Po;0;L;;;;;N;;;;; +103A0;OLD PERSIAN SIGN A;Lo;0;L;;;;;N;;;;; +103A1;OLD PERSIAN SIGN I;Lo;0;L;;;;;N;;;;; +103A2;OLD PERSIAN SIGN U;Lo;0;L;;;;;N;;;;; +103A3;OLD PERSIAN SIGN KA;Lo;0;L;;;;;N;;;;; +103A4;OLD PERSIAN SIGN KU;Lo;0;L;;;;;N;;;;; +103A5;OLD PERSIAN SIGN GA;Lo;0;L;;;;;N;;;;; +103A6;OLD PERSIAN SIGN GU;Lo;0;L;;;;;N;;;;; +103A7;OLD PERSIAN SIGN XA;Lo;0;L;;;;;N;;;;; +103A8;OLD PERSIAN SIGN CA;Lo;0;L;;;;;N;;;;; +103A9;OLD PERSIAN SIGN JA;Lo;0;L;;;;;N;;;;; +103AA;OLD PERSIAN SIGN JI;Lo;0;L;;;;;N;;;;; +103AB;OLD PERSIAN SIGN TA;Lo;0;L;;;;;N;;;;; +103AC;OLD PERSIAN SIGN TU;Lo;0;L;;;;;N;;;;; +103AD;OLD PERSIAN SIGN DA;Lo;0;L;;;;;N;;;;; +103AE;OLD PERSIAN SIGN DI;Lo;0;L;;;;;N;;;;; +103AF;OLD PERSIAN SIGN DU;Lo;0;L;;;;;N;;;;; +103B0;OLD PERSIAN SIGN THA;Lo;0;L;;;;;N;;;;; +103B1;OLD PERSIAN SIGN PA;Lo;0;L;;;;;N;;;;; +103B2;OLD PERSIAN SIGN BA;Lo;0;L;;;;;N;;;;; +103B3;OLD PERSIAN SIGN FA;Lo;0;L;;;;;N;;;;; +103B4;OLD PERSIAN SIGN NA;Lo;0;L;;;;;N;;;;; +103B5;OLD PERSIAN SIGN NU;Lo;0;L;;;;;N;;;;; +103B6;OLD PERSIAN SIGN MA;Lo;0;L;;;;;N;;;;; +103B7;OLD PERSIAN SIGN MI;Lo;0;L;;;;;N;;;;; +103B8;OLD PERSIAN SIGN MU;Lo;0;L;;;;;N;;;;; +103B9;OLD PERSIAN SIGN YA;Lo;0;L;;;;;N;;;;; +103BA;OLD PERSIAN SIGN VA;Lo;0;L;;;;;N;;;;; +103BB;OLD PERSIAN SIGN VI;Lo;0;L;;;;;N;;;;; +103BC;OLD PERSIAN SIGN RA;Lo;0;L;;;;;N;;;;; +103BD;OLD PERSIAN SIGN RU;Lo;0;L;;;;;N;;;;; +103BE;OLD PERSIAN SIGN LA;Lo;0;L;;;;;N;;;;; +103BF;OLD PERSIAN SIGN SA;Lo;0;L;;;;;N;;;;; +103C0;OLD PERSIAN SIGN ZA;Lo;0;L;;;;;N;;;;; +103C1;OLD PERSIAN SIGN SHA;Lo;0;L;;;;;N;;;;; +103C2;OLD PERSIAN SIGN SSA;Lo;0;L;;;;;N;;;;; +103C3;OLD PERSIAN SIGN HA;Lo;0;L;;;;;N;;;;; +103C8;OLD PERSIAN SIGN AURAMAZDAA;Lo;0;L;;;;;N;;;;; +103C9;OLD PERSIAN SIGN AURAMAZDAA-2;Lo;0;L;;;;;N;;;;; +103CA;OLD PERSIAN SIGN AURAMAZDAAHA;Lo;0;L;;;;;N;;;;; +103CB;OLD PERSIAN SIGN XSHAAYATHIYA;Lo;0;L;;;;;N;;;;; +103CC;OLD PERSIAN SIGN DAHYAAUSH;Lo;0;L;;;;;N;;;;; +103CD;OLD PERSIAN SIGN DAHYAAUSH-2;Lo;0;L;;;;;N;;;;; +103CE;OLD PERSIAN SIGN BAGA;Lo;0;L;;;;;N;;;;; +103CF;OLD PERSIAN SIGN BUUMISH;Lo;0;L;;;;;N;;;;; +103D0;OLD PERSIAN WORD DIVIDER;Po;0;L;;;;;N;;;;; +103D1;OLD PERSIAN NUMBER ONE;Nl;0;L;;;;1;N;;;;; +103D2;OLD PERSIAN NUMBER TWO;Nl;0;L;;;;2;N;;;;; +103D3;OLD PERSIAN NUMBER TEN;Nl;0;L;;;;10;N;;;;; +103D4;OLD PERSIAN NUMBER TWENTY;Nl;0;L;;;;20;N;;;;; +103D5;OLD PERSIAN NUMBER HUNDRED;Nl;0;L;;;;100;N;;;;; +10400;DESERET CAPITAL LETTER LONG I;Lu;0;L;;;;;N;;;;10428; +10401;DESERET CAPITAL LETTER LONG E;Lu;0;L;;;;;N;;;;10429; +10402;DESERET CAPITAL LETTER LONG A;Lu;0;L;;;;;N;;;;1042A; +10403;DESERET CAPITAL LETTER LONG AH;Lu;0;L;;;;;N;;;;1042B; +10404;DESERET CAPITAL LETTER LONG O;Lu;0;L;;;;;N;;;;1042C; +10405;DESERET CAPITAL LETTER LONG OO;Lu;0;L;;;;;N;;;;1042D; +10406;DESERET CAPITAL LETTER SHORT I;Lu;0;L;;;;;N;;;;1042E; +10407;DESERET CAPITAL LETTER SHORT E;Lu;0;L;;;;;N;;;;1042F; +10408;DESERET CAPITAL LETTER SHORT A;Lu;0;L;;;;;N;;;;10430; +10409;DESERET CAPITAL LETTER SHORT AH;Lu;0;L;;;;;N;;;;10431; +1040A;DESERET CAPITAL LETTER SHORT O;Lu;0;L;;;;;N;;;;10432; +1040B;DESERET CAPITAL LETTER SHORT OO;Lu;0;L;;;;;N;;;;10433; +1040C;DESERET CAPITAL LETTER AY;Lu;0;L;;;;;N;;;;10434; +1040D;DESERET CAPITAL LETTER OW;Lu;0;L;;;;;N;;;;10435; +1040E;DESERET CAPITAL LETTER WU;Lu;0;L;;;;;N;;;;10436; +1040F;DESERET CAPITAL LETTER YEE;Lu;0;L;;;;;N;;;;10437; +10410;DESERET CAPITAL LETTER H;Lu;0;L;;;;;N;;;;10438; +10411;DESERET CAPITAL LETTER PEE;Lu;0;L;;;;;N;;;;10439; +10412;DESERET CAPITAL LETTER BEE;Lu;0;L;;;;;N;;;;1043A; +10413;DESERET CAPITAL LETTER TEE;Lu;0;L;;;;;N;;;;1043B; +10414;DESERET CAPITAL LETTER DEE;Lu;0;L;;;;;N;;;;1043C; +10415;DESERET CAPITAL LETTER CHEE;Lu;0;L;;;;;N;;;;1043D; +10416;DESERET CAPITAL LETTER JEE;Lu;0;L;;;;;N;;;;1043E; +10417;DESERET CAPITAL LETTER KAY;Lu;0;L;;;;;N;;;;1043F; +10418;DESERET CAPITAL LETTER GAY;Lu;0;L;;;;;N;;;;10440; +10419;DESERET CAPITAL LETTER EF;Lu;0;L;;;;;N;;;;10441; +1041A;DESERET CAPITAL LETTER VEE;Lu;0;L;;;;;N;;;;10442; +1041B;DESERET CAPITAL LETTER ETH;Lu;0;L;;;;;N;;;;10443; +1041C;DESERET CAPITAL LETTER THEE;Lu;0;L;;;;;N;;;;10444; +1041D;DESERET CAPITAL LETTER ES;Lu;0;L;;;;;N;;;;10445; +1041E;DESERET CAPITAL LETTER ZEE;Lu;0;L;;;;;N;;;;10446; +1041F;DESERET CAPITAL LETTER ESH;Lu;0;L;;;;;N;;;;10447; +10420;DESERET CAPITAL LETTER ZHEE;Lu;0;L;;;;;N;;;;10448; +10421;DESERET CAPITAL LETTER ER;Lu;0;L;;;;;N;;;;10449; +10422;DESERET CAPITAL LETTER EL;Lu;0;L;;;;;N;;;;1044A; +10423;DESERET CAPITAL LETTER EM;Lu;0;L;;;;;N;;;;1044B; +10424;DESERET CAPITAL LETTER EN;Lu;0;L;;;;;N;;;;1044C; +10425;DESERET CAPITAL LETTER ENG;Lu;0;L;;;;;N;;;;1044D; +10426;DESERET CAPITAL LETTER OI;Lu;0;L;;;;;N;;;;1044E; +10427;DESERET CAPITAL LETTER EW;Lu;0;L;;;;;N;;;;1044F; +10428;DESERET SMALL LETTER LONG I;Ll;0;L;;;;;N;;;10400;;10400 +10429;DESERET SMALL LETTER LONG E;Ll;0;L;;;;;N;;;10401;;10401 +1042A;DESERET SMALL LETTER LONG A;Ll;0;L;;;;;N;;;10402;;10402 +1042B;DESERET SMALL LETTER LONG AH;Ll;0;L;;;;;N;;;10403;;10403 +1042C;DESERET SMALL LETTER LONG O;Ll;0;L;;;;;N;;;10404;;10404 +1042D;DESERET SMALL LETTER LONG OO;Ll;0;L;;;;;N;;;10405;;10405 +1042E;DESERET SMALL LETTER SHORT I;Ll;0;L;;;;;N;;;10406;;10406 +1042F;DESERET SMALL LETTER SHORT E;Ll;0;L;;;;;N;;;10407;;10407 +10430;DESERET SMALL LETTER SHORT A;Ll;0;L;;;;;N;;;10408;;10408 +10431;DESERET SMALL LETTER SHORT AH;Ll;0;L;;;;;N;;;10409;;10409 +10432;DESERET SMALL LETTER SHORT O;Ll;0;L;;;;;N;;;1040A;;1040A +10433;DESERET SMALL LETTER SHORT OO;Ll;0;L;;;;;N;;;1040B;;1040B +10434;DESERET SMALL LETTER AY;Ll;0;L;;;;;N;;;1040C;;1040C +10435;DESERET SMALL LETTER OW;Ll;0;L;;;;;N;;;1040D;;1040D +10436;DESERET SMALL LETTER WU;Ll;0;L;;;;;N;;;1040E;;1040E +10437;DESERET SMALL LETTER YEE;Ll;0;L;;;;;N;;;1040F;;1040F +10438;DESERET SMALL LETTER H;Ll;0;L;;;;;N;;;10410;;10410 +10439;DESERET SMALL LETTER PEE;Ll;0;L;;;;;N;;;10411;;10411 +1043A;DESERET SMALL LETTER BEE;Ll;0;L;;;;;N;;;10412;;10412 +1043B;DESERET SMALL LETTER TEE;Ll;0;L;;;;;N;;;10413;;10413 +1043C;DESERET SMALL LETTER DEE;Ll;0;L;;;;;N;;;10414;;10414 +1043D;DESERET SMALL LETTER CHEE;Ll;0;L;;;;;N;;;10415;;10415 +1043E;DESERET SMALL LETTER JEE;Ll;0;L;;;;;N;;;10416;;10416 +1043F;DESERET SMALL LETTER KAY;Ll;0;L;;;;;N;;;10417;;10417 +10440;DESERET SMALL LETTER GAY;Ll;0;L;;;;;N;;;10418;;10418 +10441;DESERET SMALL LETTER EF;Ll;0;L;;;;;N;;;10419;;10419 +10442;DESERET SMALL LETTER VEE;Ll;0;L;;;;;N;;;1041A;;1041A +10443;DESERET SMALL LETTER ETH;Ll;0;L;;;;;N;;;1041B;;1041B +10444;DESERET SMALL LETTER THEE;Ll;0;L;;;;;N;;;1041C;;1041C +10445;DESERET SMALL LETTER ES;Ll;0;L;;;;;N;;;1041D;;1041D +10446;DESERET SMALL LETTER ZEE;Ll;0;L;;;;;N;;;1041E;;1041E +10447;DESERET SMALL LETTER ESH;Ll;0;L;;;;;N;;;1041F;;1041F +10448;DESERET SMALL LETTER ZHEE;Ll;0;L;;;;;N;;;10420;;10420 +10449;DESERET SMALL LETTER ER;Ll;0;L;;;;;N;;;10421;;10421 +1044A;DESERET SMALL LETTER EL;Ll;0;L;;;;;N;;;10422;;10422 +1044B;DESERET SMALL LETTER EM;Ll;0;L;;;;;N;;;10423;;10423 +1044C;DESERET SMALL LETTER EN;Ll;0;L;;;;;N;;;10424;;10424 +1044D;DESERET SMALL LETTER ENG;Ll;0;L;;;;;N;;;10425;;10425 +1044E;DESERET SMALL LETTER OI;Ll;0;L;;;;;N;;;10426;;10426 +1044F;DESERET SMALL LETTER EW;Ll;0;L;;;;;N;;;10427;;10427 +10450;SHAVIAN LETTER PEEP;Lo;0;L;;;;;N;;;;; +10451;SHAVIAN LETTER TOT;Lo;0;L;;;;;N;;;;; +10452;SHAVIAN LETTER KICK;Lo;0;L;;;;;N;;;;; +10453;SHAVIAN LETTER FEE;Lo;0;L;;;;;N;;;;; +10454;SHAVIAN LETTER THIGH;Lo;0;L;;;;;N;;;;; +10455;SHAVIAN LETTER SO;Lo;0;L;;;;;N;;;;; +10456;SHAVIAN LETTER SURE;Lo;0;L;;;;;N;;;;; +10457;SHAVIAN LETTER CHURCH;Lo;0;L;;;;;N;;;;; +10458;SHAVIAN LETTER YEA;Lo;0;L;;;;;N;;;;; +10459;SHAVIAN LETTER HUNG;Lo;0;L;;;;;N;;;;; +1045A;SHAVIAN LETTER BIB;Lo;0;L;;;;;N;;;;; +1045B;SHAVIAN LETTER DEAD;Lo;0;L;;;;;N;;;;; +1045C;SHAVIAN LETTER GAG;Lo;0;L;;;;;N;;;;; +1045D;SHAVIAN LETTER VOW;Lo;0;L;;;;;N;;;;; +1045E;SHAVIAN LETTER THEY;Lo;0;L;;;;;N;;;;; +1045F;SHAVIAN LETTER ZOO;Lo;0;L;;;;;N;;;;; +10460;SHAVIAN LETTER MEASURE;Lo;0;L;;;;;N;;;;; +10461;SHAVIAN LETTER JUDGE;Lo;0;L;;;;;N;;;;; +10462;SHAVIAN LETTER WOE;Lo;0;L;;;;;N;;;;; +10463;SHAVIAN LETTER HA-HA;Lo;0;L;;;;;N;;;;; +10464;SHAVIAN LETTER LOLL;Lo;0;L;;;;;N;;;;; +10465;SHAVIAN LETTER MIME;Lo;0;L;;;;;N;;;;; +10466;SHAVIAN LETTER IF;Lo;0;L;;;;;N;;;;; +10467;SHAVIAN LETTER EGG;Lo;0;L;;;;;N;;;;; +10468;SHAVIAN LETTER ASH;Lo;0;L;;;;;N;;;;; +10469;SHAVIAN LETTER ADO;Lo;0;L;;;;;N;;;;; +1046A;SHAVIAN LETTER ON;Lo;0;L;;;;;N;;;;; +1046B;SHAVIAN LETTER WOOL;Lo;0;L;;;;;N;;;;; +1046C;SHAVIAN LETTER OUT;Lo;0;L;;;;;N;;;;; +1046D;SHAVIAN LETTER AH;Lo;0;L;;;;;N;;;;; +1046E;SHAVIAN LETTER ROAR;Lo;0;L;;;;;N;;;;; +1046F;SHAVIAN LETTER NUN;Lo;0;L;;;;;N;;;;; +10470;SHAVIAN LETTER EAT;Lo;0;L;;;;;N;;;;; +10471;SHAVIAN LETTER AGE;Lo;0;L;;;;;N;;;;; +10472;SHAVIAN LETTER ICE;Lo;0;L;;;;;N;;;;; +10473;SHAVIAN LETTER UP;Lo;0;L;;;;;N;;;;; +10474;SHAVIAN LETTER OAK;Lo;0;L;;;;;N;;;;; +10475;SHAVIAN LETTER OOZE;Lo;0;L;;;;;N;;;;; +10476;SHAVIAN LETTER OIL;Lo;0;L;;;;;N;;;;; +10477;SHAVIAN LETTER AWE;Lo;0;L;;;;;N;;;;; +10478;SHAVIAN LETTER ARE;Lo;0;L;;;;;N;;;;; +10479;SHAVIAN LETTER OR;Lo;0;L;;;;;N;;;;; +1047A;SHAVIAN LETTER AIR;Lo;0;L;;;;;N;;;;; +1047B;SHAVIAN LETTER ERR;Lo;0;L;;;;;N;;;;; +1047C;SHAVIAN LETTER ARRAY;Lo;0;L;;;;;N;;;;; +1047D;SHAVIAN LETTER EAR;Lo;0;L;;;;;N;;;;; +1047E;SHAVIAN LETTER IAN;Lo;0;L;;;;;N;;;;; +1047F;SHAVIAN LETTER YEW;Lo;0;L;;;;;N;;;;; +10480;OSMANYA LETTER ALEF;Lo;0;L;;;;;N;;;;; +10481;OSMANYA LETTER BA;Lo;0;L;;;;;N;;;;; +10482;OSMANYA LETTER TA;Lo;0;L;;;;;N;;;;; +10483;OSMANYA LETTER JA;Lo;0;L;;;;;N;;;;; +10484;OSMANYA LETTER XA;Lo;0;L;;;;;N;;;;; +10485;OSMANYA LETTER KHA;Lo;0;L;;;;;N;;;;; +10486;OSMANYA LETTER DEEL;Lo;0;L;;;;;N;;;;; +10487;OSMANYA LETTER RA;Lo;0;L;;;;;N;;;;; +10488;OSMANYA LETTER SA;Lo;0;L;;;;;N;;;;; +10489;OSMANYA LETTER SHIIN;Lo;0;L;;;;;N;;;;; +1048A;OSMANYA LETTER DHA;Lo;0;L;;;;;N;;;;; +1048B;OSMANYA LETTER CAYN;Lo;0;L;;;;;N;;;;; +1048C;OSMANYA LETTER GA;Lo;0;L;;;;;N;;;;; +1048D;OSMANYA LETTER FA;Lo;0;L;;;;;N;;;;; +1048E;OSMANYA LETTER QAAF;Lo;0;L;;;;;N;;;;; +1048F;OSMANYA LETTER KAAF;Lo;0;L;;;;;N;;;;; +10490;OSMANYA LETTER LAAN;Lo;0;L;;;;;N;;;;; +10491;OSMANYA LETTER MIIN;Lo;0;L;;;;;N;;;;; +10492;OSMANYA LETTER NUUN;Lo;0;L;;;;;N;;;;; +10493;OSMANYA LETTER WAW;Lo;0;L;;;;;N;;;;; +10494;OSMANYA LETTER HA;Lo;0;L;;;;;N;;;;; +10495;OSMANYA LETTER YA;Lo;0;L;;;;;N;;;;; +10496;OSMANYA LETTER A;Lo;0;L;;;;;N;;;;; +10497;OSMANYA LETTER E;Lo;0;L;;;;;N;;;;; +10498;OSMANYA LETTER I;Lo;0;L;;;;;N;;;;; +10499;OSMANYA LETTER O;Lo;0;L;;;;;N;;;;; +1049A;OSMANYA LETTER U;Lo;0;L;;;;;N;;;;; +1049B;OSMANYA LETTER AA;Lo;0;L;;;;;N;;;;; +1049C;OSMANYA LETTER EE;Lo;0;L;;;;;N;;;;; +1049D;OSMANYA LETTER OO;Lo;0;L;;;;;N;;;;; +104A0;OSMANYA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +104A1;OSMANYA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +104A2;OSMANYA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +104A3;OSMANYA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +104A4;OSMANYA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +104A5;OSMANYA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +104A6;OSMANYA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +104A7;OSMANYA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +104A8;OSMANYA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +104A9;OSMANYA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +10800;CYPRIOT SYLLABLE A;Lo;0;R;;;;;N;;;;; +10801;CYPRIOT SYLLABLE E;Lo;0;R;;;;;N;;;;; +10802;CYPRIOT SYLLABLE I;Lo;0;R;;;;;N;;;;; +10803;CYPRIOT SYLLABLE O;Lo;0;R;;;;;N;;;;; +10804;CYPRIOT SYLLABLE U;Lo;0;R;;;;;N;;;;; +10805;CYPRIOT SYLLABLE JA;Lo;0;R;;;;;N;;;;; +10808;CYPRIOT SYLLABLE JO;Lo;0;R;;;;;N;;;;; +1080A;CYPRIOT SYLLABLE KA;Lo;0;R;;;;;N;;;;; +1080B;CYPRIOT SYLLABLE KE;Lo;0;R;;;;;N;;;;; +1080C;CYPRIOT SYLLABLE KI;Lo;0;R;;;;;N;;;;; +1080D;CYPRIOT SYLLABLE KO;Lo;0;R;;;;;N;;;;; +1080E;CYPRIOT SYLLABLE KU;Lo;0;R;;;;;N;;;;; +1080F;CYPRIOT SYLLABLE LA;Lo;0;R;;;;;N;;;;; +10810;CYPRIOT SYLLABLE LE;Lo;0;R;;;;;N;;;;; +10811;CYPRIOT SYLLABLE LI;Lo;0;R;;;;;N;;;;; +10812;CYPRIOT SYLLABLE LO;Lo;0;R;;;;;N;;;;; +10813;CYPRIOT SYLLABLE LU;Lo;0;R;;;;;N;;;;; +10814;CYPRIOT SYLLABLE MA;Lo;0;R;;;;;N;;;;; +10815;CYPRIOT SYLLABLE ME;Lo;0;R;;;;;N;;;;; +10816;CYPRIOT SYLLABLE MI;Lo;0;R;;;;;N;;;;; +10817;CYPRIOT SYLLABLE MO;Lo;0;R;;;;;N;;;;; +10818;CYPRIOT SYLLABLE MU;Lo;0;R;;;;;N;;;;; +10819;CYPRIOT SYLLABLE NA;Lo;0;R;;;;;N;;;;; +1081A;CYPRIOT SYLLABLE NE;Lo;0;R;;;;;N;;;;; +1081B;CYPRIOT SYLLABLE NI;Lo;0;R;;;;;N;;;;; +1081C;CYPRIOT SYLLABLE NO;Lo;0;R;;;;;N;;;;; +1081D;CYPRIOT SYLLABLE NU;Lo;0;R;;;;;N;;;;; +1081E;CYPRIOT SYLLABLE PA;Lo;0;R;;;;;N;;;;; +1081F;CYPRIOT SYLLABLE PE;Lo;0;R;;;;;N;;;;; +10820;CYPRIOT SYLLABLE PI;Lo;0;R;;;;;N;;;;; +10821;CYPRIOT SYLLABLE PO;Lo;0;R;;;;;N;;;;; +10822;CYPRIOT SYLLABLE PU;Lo;0;R;;;;;N;;;;; +10823;CYPRIOT SYLLABLE RA;Lo;0;R;;;;;N;;;;; +10824;CYPRIOT SYLLABLE RE;Lo;0;R;;;;;N;;;;; +10825;CYPRIOT SYLLABLE RI;Lo;0;R;;;;;N;;;;; +10826;CYPRIOT SYLLABLE RO;Lo;0;R;;;;;N;;;;; +10827;CYPRIOT SYLLABLE RU;Lo;0;R;;;;;N;;;;; +10828;CYPRIOT SYLLABLE SA;Lo;0;R;;;;;N;;;;; +10829;CYPRIOT SYLLABLE SE;Lo;0;R;;;;;N;;;;; +1082A;CYPRIOT SYLLABLE SI;Lo;0;R;;;;;N;;;;; +1082B;CYPRIOT SYLLABLE SO;Lo;0;R;;;;;N;;;;; +1082C;CYPRIOT SYLLABLE SU;Lo;0;R;;;;;N;;;;; +1082D;CYPRIOT SYLLABLE TA;Lo;0;R;;;;;N;;;;; +1082E;CYPRIOT SYLLABLE TE;Lo;0;R;;;;;N;;;;; +1082F;CYPRIOT SYLLABLE TI;Lo;0;R;;;;;N;;;;; +10830;CYPRIOT SYLLABLE TO;Lo;0;R;;;;;N;;;;; +10831;CYPRIOT SYLLABLE TU;Lo;0;R;;;;;N;;;;; +10832;CYPRIOT SYLLABLE WA;Lo;0;R;;;;;N;;;;; +10833;CYPRIOT SYLLABLE WE;Lo;0;R;;;;;N;;;;; +10834;CYPRIOT SYLLABLE WI;Lo;0;R;;;;;N;;;;; +10835;CYPRIOT SYLLABLE WO;Lo;0;R;;;;;N;;;;; +10837;CYPRIOT SYLLABLE XA;Lo;0;R;;;;;N;;;;; +10838;CYPRIOT SYLLABLE XE;Lo;0;R;;;;;N;;;;; +1083C;CYPRIOT SYLLABLE ZA;Lo;0;R;;;;;N;;;;; +1083F;CYPRIOT SYLLABLE ZO;Lo;0;R;;;;;N;;;;; +10840;IMPERIAL ARAMAIC LETTER ALEPH;Lo;0;R;;;;;N;;;;; +10841;IMPERIAL ARAMAIC LETTER BETH;Lo;0;R;;;;;N;;;;; +10842;IMPERIAL ARAMAIC LETTER GIMEL;Lo;0;R;;;;;N;;;;; +10843;IMPERIAL ARAMAIC LETTER DALETH;Lo;0;R;;;;;N;;;;; +10844;IMPERIAL ARAMAIC LETTER HE;Lo;0;R;;;;;N;;;;; +10845;IMPERIAL ARAMAIC LETTER WAW;Lo;0;R;;;;;N;;;;; +10846;IMPERIAL ARAMAIC LETTER ZAYIN;Lo;0;R;;;;;N;;;;; +10847;IMPERIAL ARAMAIC LETTER HETH;Lo;0;R;;;;;N;;;;; +10848;IMPERIAL ARAMAIC LETTER TETH;Lo;0;R;;;;;N;;;;; +10849;IMPERIAL ARAMAIC LETTER YODH;Lo;0;R;;;;;N;;;;; +1084A;IMPERIAL ARAMAIC LETTER KAPH;Lo;0;R;;;;;N;;;;; +1084B;IMPERIAL ARAMAIC LETTER LAMEDH;Lo;0;R;;;;;N;;;;; +1084C;IMPERIAL ARAMAIC LETTER MEM;Lo;0;R;;;;;N;;;;; +1084D;IMPERIAL ARAMAIC LETTER NUN;Lo;0;R;;;;;N;;;;; +1084E;IMPERIAL ARAMAIC LETTER SAMEKH;Lo;0;R;;;;;N;;;;; +1084F;IMPERIAL ARAMAIC LETTER AYIN;Lo;0;R;;;;;N;;;;; +10850;IMPERIAL ARAMAIC LETTER PE;Lo;0;R;;;;;N;;;;; +10851;IMPERIAL ARAMAIC LETTER SADHE;Lo;0;R;;;;;N;;;;; +10852;IMPERIAL ARAMAIC LETTER QOPH;Lo;0;R;;;;;N;;;;; +10853;IMPERIAL ARAMAIC LETTER RESH;Lo;0;R;;;;;N;;;;; +10854;IMPERIAL ARAMAIC LETTER SHIN;Lo;0;R;;;;;N;;;;; +10855;IMPERIAL ARAMAIC LETTER TAW;Lo;0;R;;;;;N;;;;; +10857;IMPERIAL ARAMAIC SECTION SIGN;Po;0;R;;;;;N;;;;; +10858;IMPERIAL ARAMAIC NUMBER ONE;No;0;R;;;;1;N;;;;; +10859;IMPERIAL ARAMAIC NUMBER TWO;No;0;R;;;;2;N;;;;; +1085A;IMPERIAL ARAMAIC NUMBER THREE;No;0;R;;;;3;N;;;;; +1085B;IMPERIAL ARAMAIC NUMBER TEN;No;0;R;;;;10;N;;;;; +1085C;IMPERIAL ARAMAIC NUMBER TWENTY;No;0;R;;;;20;N;;;;; +1085D;IMPERIAL ARAMAIC NUMBER ONE HUNDRED;No;0;R;;;;100;N;;;;; +1085E;IMPERIAL ARAMAIC NUMBER ONE THOUSAND;No;0;R;;;;1000;N;;;;; +1085F;IMPERIAL ARAMAIC NUMBER TEN THOUSAND;No;0;R;;;;10000;N;;;;; +10900;PHOENICIAN LETTER ALF;Lo;0;R;;;;;N;;;;; +10901;PHOENICIAN LETTER BET;Lo;0;R;;;;;N;;;;; +10902;PHOENICIAN LETTER GAML;Lo;0;R;;;;;N;;;;; +10903;PHOENICIAN LETTER DELT;Lo;0;R;;;;;N;;;;; +10904;PHOENICIAN LETTER HE;Lo;0;R;;;;;N;;;;; +10905;PHOENICIAN LETTER WAU;Lo;0;R;;;;;N;;;;; +10906;PHOENICIAN LETTER ZAI;Lo;0;R;;;;;N;;;;; +10907;PHOENICIAN LETTER HET;Lo;0;R;;;;;N;;;;; +10908;PHOENICIAN LETTER TET;Lo;0;R;;;;;N;;;;; +10909;PHOENICIAN LETTER YOD;Lo;0;R;;;;;N;;;;; +1090A;PHOENICIAN LETTER KAF;Lo;0;R;;;;;N;;;;; +1090B;PHOENICIAN LETTER LAMD;Lo;0;R;;;;;N;;;;; +1090C;PHOENICIAN LETTER MEM;Lo;0;R;;;;;N;;;;; +1090D;PHOENICIAN LETTER NUN;Lo;0;R;;;;;N;;;;; +1090E;PHOENICIAN LETTER SEMK;Lo;0;R;;;;;N;;;;; +1090F;PHOENICIAN LETTER AIN;Lo;0;R;;;;;N;;;;; +10910;PHOENICIAN LETTER PE;Lo;0;R;;;;;N;;;;; +10911;PHOENICIAN LETTER SADE;Lo;0;R;;;;;N;;;;; +10912;PHOENICIAN LETTER QOF;Lo;0;R;;;;;N;;;;; +10913;PHOENICIAN LETTER ROSH;Lo;0;R;;;;;N;;;;; +10914;PHOENICIAN LETTER SHIN;Lo;0;R;;;;;N;;;;; +10915;PHOENICIAN LETTER TAU;Lo;0;R;;;;;N;;;;; +10916;PHOENICIAN NUMBER ONE;No;0;R;;;;1;N;;;;; +10917;PHOENICIAN NUMBER TEN;No;0;R;;;;10;N;;;;; +10918;PHOENICIAN NUMBER TWENTY;No;0;R;;;;20;N;;;;; +10919;PHOENICIAN NUMBER ONE HUNDRED;No;0;R;;;;100;N;;;;; +1091A;PHOENICIAN NUMBER TWO;No;0;R;;;;2;N;;;;; +1091B;PHOENICIAN NUMBER THREE;No;0;R;;;;3;N;;;;; +1091F;PHOENICIAN WORD SEPARATOR;Po;0;ON;;;;;N;;;;; +10920;LYDIAN LETTER A;Lo;0;R;;;;;N;;;;; +10921;LYDIAN LETTER B;Lo;0;R;;;;;N;;;;; +10922;LYDIAN LETTER G;Lo;0;R;;;;;N;;;;; +10923;LYDIAN LETTER D;Lo;0;R;;;;;N;;;;; +10924;LYDIAN LETTER E;Lo;0;R;;;;;N;;;;; +10925;LYDIAN LETTER V;Lo;0;R;;;;;N;;;;; +10926;LYDIAN LETTER I;Lo;0;R;;;;;N;;;;; +10927;LYDIAN LETTER Y;Lo;0;R;;;;;N;;;;; +10928;LYDIAN LETTER K;Lo;0;R;;;;;N;;;;; +10929;LYDIAN LETTER L;Lo;0;R;;;;;N;;;;; +1092A;LYDIAN LETTER M;Lo;0;R;;;;;N;;;;; +1092B;LYDIAN LETTER N;Lo;0;R;;;;;N;;;;; +1092C;LYDIAN LETTER O;Lo;0;R;;;;;N;;;;; +1092D;LYDIAN LETTER R;Lo;0;R;;;;;N;;;;; +1092E;LYDIAN LETTER SS;Lo;0;R;;;;;N;;;;; +1092F;LYDIAN LETTER T;Lo;0;R;;;;;N;;;;; +10930;LYDIAN LETTER U;Lo;0;R;;;;;N;;;;; +10931;LYDIAN LETTER F;Lo;0;R;;;;;N;;;;; +10932;LYDIAN LETTER Q;Lo;0;R;;;;;N;;;;; +10933;LYDIAN LETTER S;Lo;0;R;;;;;N;;;;; +10934;LYDIAN LETTER TT;Lo;0;R;;;;;N;;;;; +10935;LYDIAN LETTER AN;Lo;0;R;;;;;N;;;;; +10936;LYDIAN LETTER EN;Lo;0;R;;;;;N;;;;; +10937;LYDIAN LETTER LY;Lo;0;R;;;;;N;;;;; +10938;LYDIAN LETTER NN;Lo;0;R;;;;;N;;;;; +10939;LYDIAN LETTER C;Lo;0;R;;;;;N;;;;; +1093F;LYDIAN TRIANGULAR MARK;Po;0;R;;;;;N;;;;; +10980;MEROITIC HIEROGLYPHIC LETTER A;Lo;0;R;;;;;N;;;;; +10981;MEROITIC HIEROGLYPHIC LETTER E;Lo;0;R;;;;;N;;;;; +10982;MEROITIC HIEROGLYPHIC LETTER I;Lo;0;R;;;;;N;;;;; +10983;MEROITIC HIEROGLYPHIC LETTER O;Lo;0;R;;;;;N;;;;; +10984;MEROITIC HIEROGLYPHIC LETTER YA;Lo;0;R;;;;;N;;;;; +10985;MEROITIC HIEROGLYPHIC LETTER WA;Lo;0;R;;;;;N;;;;; +10986;MEROITIC HIEROGLYPHIC LETTER BA;Lo;0;R;;;;;N;;;;; +10987;MEROITIC HIEROGLYPHIC LETTER BA-2;Lo;0;R;;;;;N;;;;; +10988;MEROITIC HIEROGLYPHIC LETTER PA;Lo;0;R;;;;;N;;;;; +10989;MEROITIC HIEROGLYPHIC LETTER MA;Lo;0;R;;;;;N;;;;; +1098A;MEROITIC HIEROGLYPHIC LETTER NA;Lo;0;R;;;;;N;;;;; +1098B;MEROITIC HIEROGLYPHIC LETTER NA-2;Lo;0;R;;;;;N;;;;; +1098C;MEROITIC HIEROGLYPHIC LETTER NE;Lo;0;R;;;;;N;;;;; +1098D;MEROITIC HIEROGLYPHIC LETTER NE-2;Lo;0;R;;;;;N;;;;; +1098E;MEROITIC HIEROGLYPHIC LETTER RA;Lo;0;R;;;;;N;;;;; +1098F;MEROITIC HIEROGLYPHIC LETTER RA-2;Lo;0;R;;;;;N;;;;; +10990;MEROITIC HIEROGLYPHIC LETTER LA;Lo;0;R;;;;;N;;;;; +10991;MEROITIC HIEROGLYPHIC LETTER KHA;Lo;0;R;;;;;N;;;;; +10992;MEROITIC HIEROGLYPHIC LETTER HHA;Lo;0;R;;;;;N;;;;; +10993;MEROITIC HIEROGLYPHIC LETTER SA;Lo;0;R;;;;;N;;;;; +10994;MEROITIC HIEROGLYPHIC LETTER SA-2;Lo;0;R;;;;;N;;;;; +10995;MEROITIC HIEROGLYPHIC LETTER SE;Lo;0;R;;;;;N;;;;; +10996;MEROITIC HIEROGLYPHIC LETTER KA;Lo;0;R;;;;;N;;;;; +10997;MEROITIC HIEROGLYPHIC LETTER QA;Lo;0;R;;;;;N;;;;; +10998;MEROITIC HIEROGLYPHIC LETTER TA;Lo;0;R;;;;;N;;;;; +10999;MEROITIC HIEROGLYPHIC LETTER TA-2;Lo;0;R;;;;;N;;;;; +1099A;MEROITIC HIEROGLYPHIC LETTER TE;Lo;0;R;;;;;N;;;;; +1099B;MEROITIC HIEROGLYPHIC LETTER TE-2;Lo;0;R;;;;;N;;;;; +1099C;MEROITIC HIEROGLYPHIC LETTER TO;Lo;0;R;;;;;N;;;;; +1099D;MEROITIC HIEROGLYPHIC LETTER DA;Lo;0;R;;;;;N;;;;; +1099E;MEROITIC HIEROGLYPHIC SYMBOL VIDJ;Lo;0;R;;;;;N;;;;; +1099F;MEROITIC HIEROGLYPHIC SYMBOL VIDJ-2;Lo;0;R;;;;;N;;;;; +109A0;MEROITIC CURSIVE LETTER A;Lo;0;R;;;;;N;;;;; +109A1;MEROITIC CURSIVE LETTER E;Lo;0;R;;;;;N;;;;; +109A2;MEROITIC CURSIVE LETTER I;Lo;0;R;;;;;N;;;;; +109A3;MEROITIC CURSIVE LETTER O;Lo;0;R;;;;;N;;;;; +109A4;MEROITIC CURSIVE LETTER YA;Lo;0;R;;;;;N;;;;; +109A5;MEROITIC CURSIVE LETTER WA;Lo;0;R;;;;;N;;;;; +109A6;MEROITIC CURSIVE LETTER BA;Lo;0;R;;;;;N;;;;; +109A7;MEROITIC CURSIVE LETTER PA;Lo;0;R;;;;;N;;;;; +109A8;MEROITIC CURSIVE LETTER MA;Lo;0;R;;;;;N;;;;; +109A9;MEROITIC CURSIVE LETTER NA;Lo;0;R;;;;;N;;;;; +109AA;MEROITIC CURSIVE LETTER NE;Lo;0;R;;;;;N;;;;; +109AB;MEROITIC CURSIVE LETTER RA;Lo;0;R;;;;;N;;;;; +109AC;MEROITIC CURSIVE LETTER LA;Lo;0;R;;;;;N;;;;; +109AD;MEROITIC CURSIVE LETTER KHA;Lo;0;R;;;;;N;;;;; +109AE;MEROITIC CURSIVE LETTER HHA;Lo;0;R;;;;;N;;;;; +109AF;MEROITIC CURSIVE LETTER SA;Lo;0;R;;;;;N;;;;; +109B0;MEROITIC CURSIVE LETTER ARCHAIC SA;Lo;0;R;;;;;N;;;;; +109B1;MEROITIC CURSIVE LETTER SE;Lo;0;R;;;;;N;;;;; +109B2;MEROITIC CURSIVE LETTER KA;Lo;0;R;;;;;N;;;;; +109B3;MEROITIC CURSIVE LETTER QA;Lo;0;R;;;;;N;;;;; +109B4;MEROITIC CURSIVE LETTER TA;Lo;0;R;;;;;N;;;;; +109B5;MEROITIC CURSIVE LETTER TE;Lo;0;R;;;;;N;;;;; +109B6;MEROITIC CURSIVE LETTER TO;Lo;0;R;;;;;N;;;;; +109B7;MEROITIC CURSIVE LETTER DA;Lo;0;R;;;;;N;;;;; +109BE;MEROITIC CURSIVE LOGOGRAM RMT;Lo;0;R;;;;;N;;;;; +109BF;MEROITIC CURSIVE LOGOGRAM IMN;Lo;0;R;;;;;N;;;;; +10A00;KHAROSHTHI LETTER A;Lo;0;R;;;;;N;;;;; +10A01;KHAROSHTHI VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +10A02;KHAROSHTHI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +10A03;KHAROSHTHI VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;; +10A05;KHAROSHTHI VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +10A06;KHAROSHTHI VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;; +10A0C;KHAROSHTHI VOWEL LENGTH MARK;Mn;0;NSM;;;;;N;;;;; +10A0D;KHAROSHTHI SIGN DOUBLE RING BELOW;Mn;220;NSM;;;;;N;;;;; +10A0E;KHAROSHTHI SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +10A0F;KHAROSHTHI SIGN VISARGA;Mn;230;NSM;;;;;N;;;;; +10A10;KHAROSHTHI LETTER KA;Lo;0;R;;;;;N;;;;; +10A11;KHAROSHTHI LETTER KHA;Lo;0;R;;;;;N;;;;; +10A12;KHAROSHTHI LETTER GA;Lo;0;R;;;;;N;;;;; +10A13;KHAROSHTHI LETTER GHA;Lo;0;R;;;;;N;;;;; +10A15;KHAROSHTHI LETTER CA;Lo;0;R;;;;;N;;;;; +10A16;KHAROSHTHI LETTER CHA;Lo;0;R;;;;;N;;;;; +10A17;KHAROSHTHI LETTER JA;Lo;0;R;;;;;N;;;;; +10A19;KHAROSHTHI LETTER NYA;Lo;0;R;;;;;N;;;;; +10A1A;KHAROSHTHI LETTER TTA;Lo;0;R;;;;;N;;;;; +10A1B;KHAROSHTHI LETTER TTHA;Lo;0;R;;;;;N;;;;; +10A1C;KHAROSHTHI LETTER DDA;Lo;0;R;;;;;N;;;;; +10A1D;KHAROSHTHI LETTER DDHA;Lo;0;R;;;;;N;;;;; +10A1E;KHAROSHTHI LETTER NNA;Lo;0;R;;;;;N;;;;; +10A1F;KHAROSHTHI LETTER TA;Lo;0;R;;;;;N;;;;; +10A20;KHAROSHTHI LETTER THA;Lo;0;R;;;;;N;;;;; +10A21;KHAROSHTHI LETTER DA;Lo;0;R;;;;;N;;;;; +10A22;KHAROSHTHI LETTER DHA;Lo;0;R;;;;;N;;;;; +10A23;KHAROSHTHI LETTER NA;Lo;0;R;;;;;N;;;;; +10A24;KHAROSHTHI LETTER PA;Lo;0;R;;;;;N;;;;; +10A25;KHAROSHTHI LETTER PHA;Lo;0;R;;;;;N;;;;; +10A26;KHAROSHTHI LETTER BA;Lo;0;R;;;;;N;;;;; +10A27;KHAROSHTHI LETTER BHA;Lo;0;R;;;;;N;;;;; +10A28;KHAROSHTHI LETTER MA;Lo;0;R;;;;;N;;;;; +10A29;KHAROSHTHI LETTER YA;Lo;0;R;;;;;N;;;;; +10A2A;KHAROSHTHI LETTER RA;Lo;0;R;;;;;N;;;;; +10A2B;KHAROSHTHI LETTER LA;Lo;0;R;;;;;N;;;;; +10A2C;KHAROSHTHI LETTER VA;Lo;0;R;;;;;N;;;;; +10A2D;KHAROSHTHI LETTER SHA;Lo;0;R;;;;;N;;;;; +10A2E;KHAROSHTHI LETTER SSA;Lo;0;R;;;;;N;;;;; +10A2F;KHAROSHTHI LETTER SA;Lo;0;R;;;;;N;;;;; +10A30;KHAROSHTHI LETTER ZA;Lo;0;R;;;;;N;;;;; +10A31;KHAROSHTHI LETTER HA;Lo;0;R;;;;;N;;;;; +10A32;KHAROSHTHI LETTER KKA;Lo;0;R;;;;;N;;;;; +10A33;KHAROSHTHI LETTER TTTHA;Lo;0;R;;;;;N;;;;; +10A38;KHAROSHTHI SIGN BAR ABOVE;Mn;230;NSM;;;;;N;;;;; +10A39;KHAROSHTHI SIGN CAUDA;Mn;1;NSM;;;;;N;;;;; +10A3A;KHAROSHTHI SIGN DOT BELOW;Mn;220;NSM;;;;;N;;;;; +10A3F;KHAROSHTHI VIRAMA;Mn;9;NSM;;;;;N;;;;; +10A40;KHAROSHTHI DIGIT ONE;No;0;R;;;1;1;N;;;;; +10A41;KHAROSHTHI DIGIT TWO;No;0;R;;;2;2;N;;;;; +10A42;KHAROSHTHI DIGIT THREE;No;0;R;;;3;3;N;;;;; +10A43;KHAROSHTHI DIGIT FOUR;No;0;R;;;4;4;N;;;;; +10A44;KHAROSHTHI NUMBER TEN;No;0;R;;;;10;N;;;;; +10A45;KHAROSHTHI NUMBER TWENTY;No;0;R;;;;20;N;;;;; +10A46;KHAROSHTHI NUMBER ONE HUNDRED;No;0;R;;;;100;N;;;;; +10A47;KHAROSHTHI NUMBER ONE THOUSAND;No;0;R;;;;1000;N;;;;; +10A50;KHAROSHTHI PUNCTUATION DOT;Po;0;R;;;;;N;;;;; +10A51;KHAROSHTHI PUNCTUATION SMALL CIRCLE;Po;0;R;;;;;N;;;;; +10A52;KHAROSHTHI PUNCTUATION CIRCLE;Po;0;R;;;;;N;;;;; +10A53;KHAROSHTHI PUNCTUATION CRESCENT BAR;Po;0;R;;;;;N;;;;; +10A54;KHAROSHTHI PUNCTUATION MANGALAM;Po;0;R;;;;;N;;;;; +10A55;KHAROSHTHI PUNCTUATION LOTUS;Po;0;R;;;;;N;;;;; +10A56;KHAROSHTHI PUNCTUATION DANDA;Po;0;R;;;;;N;;;;; +10A57;KHAROSHTHI PUNCTUATION DOUBLE DANDA;Po;0;R;;;;;N;;;;; +10A58;KHAROSHTHI PUNCTUATION LINES;Po;0;R;;;;;N;;;;; +10A60;OLD SOUTH ARABIAN LETTER HE;Lo;0;R;;;;;N;;;;; +10A61;OLD SOUTH ARABIAN LETTER LAMEDH;Lo;0;R;;;;;N;;;;; +10A62;OLD SOUTH ARABIAN LETTER HETH;Lo;0;R;;;;;N;;;;; +10A63;OLD SOUTH ARABIAN LETTER MEM;Lo;0;R;;;;;N;;;;; +10A64;OLD SOUTH ARABIAN LETTER QOPH;Lo;0;R;;;;;N;;;;; +10A65;OLD SOUTH ARABIAN LETTER WAW;Lo;0;R;;;;;N;;;;; +10A66;OLD SOUTH ARABIAN LETTER SHIN;Lo;0;R;;;;;N;;;;; +10A67;OLD SOUTH ARABIAN LETTER RESH;Lo;0;R;;;;;N;;;;; +10A68;OLD SOUTH ARABIAN LETTER BETH;Lo;0;R;;;;;N;;;;; +10A69;OLD SOUTH ARABIAN LETTER TAW;Lo;0;R;;;;;N;;;;; +10A6A;OLD SOUTH ARABIAN LETTER SAT;Lo;0;R;;;;;N;;;;; +10A6B;OLD SOUTH ARABIAN LETTER KAPH;Lo;0;R;;;;;N;;;;; +10A6C;OLD SOUTH ARABIAN LETTER NUN;Lo;0;R;;;;;N;;;;; +10A6D;OLD SOUTH ARABIAN LETTER KHETH;Lo;0;R;;;;;N;;;;; +10A6E;OLD SOUTH ARABIAN LETTER SADHE;Lo;0;R;;;;;N;;;;; +10A6F;OLD SOUTH ARABIAN LETTER SAMEKH;Lo;0;R;;;;;N;;;;; +10A70;OLD SOUTH ARABIAN LETTER FE;Lo;0;R;;;;;N;;;;; +10A71;OLD SOUTH ARABIAN LETTER ALEF;Lo;0;R;;;;;N;;;;; +10A72;OLD SOUTH ARABIAN LETTER AYN;Lo;0;R;;;;;N;;;;; +10A73;OLD SOUTH ARABIAN LETTER DHADHE;Lo;0;R;;;;;N;;;;; +10A74;OLD SOUTH ARABIAN LETTER GIMEL;Lo;0;R;;;;;N;;;;; +10A75;OLD SOUTH ARABIAN LETTER DALETH;Lo;0;R;;;;;N;;;;; +10A76;OLD SOUTH ARABIAN LETTER GHAYN;Lo;0;R;;;;;N;;;;; +10A77;OLD SOUTH ARABIAN LETTER TETH;Lo;0;R;;;;;N;;;;; +10A78;OLD SOUTH ARABIAN LETTER ZAYN;Lo;0;R;;;;;N;;;;; +10A79;OLD SOUTH ARABIAN LETTER DHALETH;Lo;0;R;;;;;N;;;;; +10A7A;OLD SOUTH ARABIAN LETTER YODH;Lo;0;R;;;;;N;;;;; +10A7B;OLD SOUTH ARABIAN LETTER THAW;Lo;0;R;;;;;N;;;;; +10A7C;OLD SOUTH ARABIAN LETTER THETH;Lo;0;R;;;;;N;;;;; +10A7D;OLD SOUTH ARABIAN NUMBER ONE;No;0;R;;;;1;N;;;;; +10A7E;OLD SOUTH ARABIAN NUMBER FIFTY;No;0;R;;;;50;N;;;;; +10A7F;OLD SOUTH ARABIAN NUMERIC INDICATOR;Po;0;R;;;;;N;;;;; +10B00;AVESTAN LETTER A;Lo;0;R;;;;;N;;;;; +10B01;AVESTAN LETTER AA;Lo;0;R;;;;;N;;;;; +10B02;AVESTAN LETTER AO;Lo;0;R;;;;;N;;;;; +10B03;AVESTAN LETTER AAO;Lo;0;R;;;;;N;;;;; +10B04;AVESTAN LETTER AN;Lo;0;R;;;;;N;;;;; +10B05;AVESTAN LETTER AAN;Lo;0;R;;;;;N;;;;; +10B06;AVESTAN LETTER AE;Lo;0;R;;;;;N;;;;; +10B07;AVESTAN LETTER AEE;Lo;0;R;;;;;N;;;;; +10B08;AVESTAN LETTER E;Lo;0;R;;;;;N;;;;; +10B09;AVESTAN LETTER EE;Lo;0;R;;;;;N;;;;; +10B0A;AVESTAN LETTER O;Lo;0;R;;;;;N;;;;; +10B0B;AVESTAN LETTER OO;Lo;0;R;;;;;N;;;;; +10B0C;AVESTAN LETTER I;Lo;0;R;;;;;N;;;;; +10B0D;AVESTAN LETTER II;Lo;0;R;;;;;N;;;;; +10B0E;AVESTAN LETTER U;Lo;0;R;;;;;N;;;;; +10B0F;AVESTAN LETTER UU;Lo;0;R;;;;;N;;;;; +10B10;AVESTAN LETTER KE;Lo;0;R;;;;;N;;;;; +10B11;AVESTAN LETTER XE;Lo;0;R;;;;;N;;;;; +10B12;AVESTAN LETTER XYE;Lo;0;R;;;;;N;;;;; +10B13;AVESTAN LETTER XVE;Lo;0;R;;;;;N;;;;; +10B14;AVESTAN LETTER GE;Lo;0;R;;;;;N;;;;; +10B15;AVESTAN LETTER GGE;Lo;0;R;;;;;N;;;;; +10B16;AVESTAN LETTER GHE;Lo;0;R;;;;;N;;;;; +10B17;AVESTAN LETTER CE;Lo;0;R;;;;;N;;;;; +10B18;AVESTAN LETTER JE;Lo;0;R;;;;;N;;;;; +10B19;AVESTAN LETTER TE;Lo;0;R;;;;;N;;;;; +10B1A;AVESTAN LETTER THE;Lo;0;R;;;;;N;;;;; +10B1B;AVESTAN LETTER DE;Lo;0;R;;;;;N;;;;; +10B1C;AVESTAN LETTER DHE;Lo;0;R;;;;;N;;;;; +10B1D;AVESTAN LETTER TTE;Lo;0;R;;;;;N;;;;; +10B1E;AVESTAN LETTER PE;Lo;0;R;;;;;N;;;;; +10B1F;AVESTAN LETTER FE;Lo;0;R;;;;;N;;;;; +10B20;AVESTAN LETTER BE;Lo;0;R;;;;;N;;;;; +10B21;AVESTAN LETTER BHE;Lo;0;R;;;;;N;;;;; +10B22;AVESTAN LETTER NGE;Lo;0;R;;;;;N;;;;; +10B23;AVESTAN LETTER NGYE;Lo;0;R;;;;;N;;;;; +10B24;AVESTAN LETTER NGVE;Lo;0;R;;;;;N;;;;; +10B25;AVESTAN LETTER NE;Lo;0;R;;;;;N;;;;; +10B26;AVESTAN LETTER NYE;Lo;0;R;;;;;N;;;;; +10B27;AVESTAN LETTER NNE;Lo;0;R;;;;;N;;;;; +10B28;AVESTAN LETTER ME;Lo;0;R;;;;;N;;;;; +10B29;AVESTAN LETTER HME;Lo;0;R;;;;;N;;;;; +10B2A;AVESTAN LETTER YYE;Lo;0;R;;;;;N;;;;; +10B2B;AVESTAN LETTER YE;Lo;0;R;;;;;N;;;;; +10B2C;AVESTAN LETTER VE;Lo;0;R;;;;;N;;;;; +10B2D;AVESTAN LETTER RE;Lo;0;R;;;;;N;;;;; +10B2E;AVESTAN LETTER LE;Lo;0;R;;;;;N;;;;; +10B2F;AVESTAN LETTER SE;Lo;0;R;;;;;N;;;;; +10B30;AVESTAN LETTER ZE;Lo;0;R;;;;;N;;;;; +10B31;AVESTAN LETTER SHE;Lo;0;R;;;;;N;;;;; +10B32;AVESTAN LETTER ZHE;Lo;0;R;;;;;N;;;;; +10B33;AVESTAN LETTER SHYE;Lo;0;R;;;;;N;;;;; +10B34;AVESTAN LETTER SSHE;Lo;0;R;;;;;N;;;;; +10B35;AVESTAN LETTER HE;Lo;0;R;;;;;N;;;;; +10B39;AVESTAN ABBREVIATION MARK;Po;0;ON;;;;;N;;;;; +10B3A;TINY TWO DOTS OVER ONE DOT PUNCTUATION;Po;0;ON;;;;;N;;;;; +10B3B;SMALL TWO DOTS OVER ONE DOT PUNCTUATION;Po;0;ON;;;;;N;;;;; +10B3C;LARGE TWO DOTS OVER ONE DOT PUNCTUATION;Po;0;ON;;;;;N;;;;; +10B3D;LARGE ONE DOT OVER TWO DOTS PUNCTUATION;Po;0;ON;;;;;N;;;;; +10B3E;LARGE TWO RINGS OVER ONE RING PUNCTUATION;Po;0;ON;;;;;N;;;;; +10B3F;LARGE ONE RING OVER TWO RINGS PUNCTUATION;Po;0;ON;;;;;N;;;;; +10B40;INSCRIPTIONAL PARTHIAN LETTER ALEPH;Lo;0;R;;;;;N;;;;; +10B41;INSCRIPTIONAL PARTHIAN LETTER BETH;Lo;0;R;;;;;N;;;;; +10B42;INSCRIPTIONAL PARTHIAN LETTER GIMEL;Lo;0;R;;;;;N;;;;; +10B43;INSCRIPTIONAL PARTHIAN LETTER DALETH;Lo;0;R;;;;;N;;;;; +10B44;INSCRIPTIONAL PARTHIAN LETTER HE;Lo;0;R;;;;;N;;;;; +10B45;INSCRIPTIONAL PARTHIAN LETTER WAW;Lo;0;R;;;;;N;;;;; +10B46;INSCRIPTIONAL PARTHIAN LETTER ZAYIN;Lo;0;R;;;;;N;;;;; +10B47;INSCRIPTIONAL PARTHIAN LETTER HETH;Lo;0;R;;;;;N;;;;; +10B48;INSCRIPTIONAL PARTHIAN LETTER TETH;Lo;0;R;;;;;N;;;;; +10B49;INSCRIPTIONAL PARTHIAN LETTER YODH;Lo;0;R;;;;;N;;;;; +10B4A;INSCRIPTIONAL PARTHIAN LETTER KAPH;Lo;0;R;;;;;N;;;;; +10B4B;INSCRIPTIONAL PARTHIAN LETTER LAMEDH;Lo;0;R;;;;;N;;;;; +10B4C;INSCRIPTIONAL PARTHIAN LETTER MEM;Lo;0;R;;;;;N;;;;; +10B4D;INSCRIPTIONAL PARTHIAN LETTER NUN;Lo;0;R;;;;;N;;;;; +10B4E;INSCRIPTIONAL PARTHIAN LETTER SAMEKH;Lo;0;R;;;;;N;;;;; +10B4F;INSCRIPTIONAL PARTHIAN LETTER AYIN;Lo;0;R;;;;;N;;;;; +10B50;INSCRIPTIONAL PARTHIAN LETTER PE;Lo;0;R;;;;;N;;;;; +10B51;INSCRIPTIONAL PARTHIAN LETTER SADHE;Lo;0;R;;;;;N;;;;; +10B52;INSCRIPTIONAL PARTHIAN LETTER QOPH;Lo;0;R;;;;;N;;;;; +10B53;INSCRIPTIONAL PARTHIAN LETTER RESH;Lo;0;R;;;;;N;;;;; +10B54;INSCRIPTIONAL PARTHIAN LETTER SHIN;Lo;0;R;;;;;N;;;;; +10B55;INSCRIPTIONAL PARTHIAN LETTER TAW;Lo;0;R;;;;;N;;;;; +10B58;INSCRIPTIONAL PARTHIAN NUMBER ONE;No;0;R;;;;1;N;;;;; +10B59;INSCRIPTIONAL PARTHIAN NUMBER TWO;No;0;R;;;;2;N;;;;; +10B5A;INSCRIPTIONAL PARTHIAN NUMBER THREE;No;0;R;;;;3;N;;;;; +10B5B;INSCRIPTIONAL PARTHIAN NUMBER FOUR;No;0;R;;;;4;N;;;;; +10B5C;INSCRIPTIONAL PARTHIAN NUMBER TEN;No;0;R;;;;10;N;;;;; +10B5D;INSCRIPTIONAL PARTHIAN NUMBER TWENTY;No;0;R;;;;20;N;;;;; +10B5E;INSCRIPTIONAL PARTHIAN NUMBER ONE HUNDRED;No;0;R;;;;100;N;;;;; +10B5F;INSCRIPTIONAL PARTHIAN NUMBER ONE THOUSAND;No;0;R;;;;1000;N;;;;; +10B60;INSCRIPTIONAL PAHLAVI LETTER ALEPH;Lo;0;R;;;;;N;;;;; +10B61;INSCRIPTIONAL PAHLAVI LETTER BETH;Lo;0;R;;;;;N;;;;; +10B62;INSCRIPTIONAL PAHLAVI LETTER GIMEL;Lo;0;R;;;;;N;;;;; +10B63;INSCRIPTIONAL PAHLAVI LETTER DALETH;Lo;0;R;;;;;N;;;;; +10B64;INSCRIPTIONAL PAHLAVI LETTER HE;Lo;0;R;;;;;N;;;;; +10B65;INSCRIPTIONAL PAHLAVI LETTER WAW-AYIN-RESH;Lo;0;R;;;;;N;;;;; +10B66;INSCRIPTIONAL PAHLAVI LETTER ZAYIN;Lo;0;R;;;;;N;;;;; +10B67;INSCRIPTIONAL PAHLAVI LETTER HETH;Lo;0;R;;;;;N;;;;; +10B68;INSCRIPTIONAL PAHLAVI LETTER TETH;Lo;0;R;;;;;N;;;;; +10B69;INSCRIPTIONAL PAHLAVI LETTER YODH;Lo;0;R;;;;;N;;;;; +10B6A;INSCRIPTIONAL PAHLAVI LETTER KAPH;Lo;0;R;;;;;N;;;;; +10B6B;INSCRIPTIONAL PAHLAVI LETTER LAMEDH;Lo;0;R;;;;;N;;;;; +10B6C;INSCRIPTIONAL PAHLAVI LETTER MEM-QOPH;Lo;0;R;;;;;N;;;;; +10B6D;INSCRIPTIONAL PAHLAVI LETTER NUN;Lo;0;R;;;;;N;;;;; +10B6E;INSCRIPTIONAL PAHLAVI LETTER SAMEKH;Lo;0;R;;;;;N;;;;; +10B6F;INSCRIPTIONAL PAHLAVI LETTER PE;Lo;0;R;;;;;N;;;;; +10B70;INSCRIPTIONAL PAHLAVI LETTER SADHE;Lo;0;R;;;;;N;;;;; +10B71;INSCRIPTIONAL PAHLAVI LETTER SHIN;Lo;0;R;;;;;N;;;;; +10B72;INSCRIPTIONAL PAHLAVI LETTER TAW;Lo;0;R;;;;;N;;;;; +10B78;INSCRIPTIONAL PAHLAVI NUMBER ONE;No;0;R;;;;1;N;;;;; +10B79;INSCRIPTIONAL PAHLAVI NUMBER TWO;No;0;R;;;;2;N;;;;; +10B7A;INSCRIPTIONAL PAHLAVI NUMBER THREE;No;0;R;;;;3;N;;;;; +10B7B;INSCRIPTIONAL PAHLAVI NUMBER FOUR;No;0;R;;;;4;N;;;;; +10B7C;INSCRIPTIONAL PAHLAVI NUMBER TEN;No;0;R;;;;10;N;;;;; +10B7D;INSCRIPTIONAL PAHLAVI NUMBER TWENTY;No;0;R;;;;20;N;;;;; +10B7E;INSCRIPTIONAL PAHLAVI NUMBER ONE HUNDRED;No;0;R;;;;100;N;;;;; +10B7F;INSCRIPTIONAL PAHLAVI NUMBER ONE THOUSAND;No;0;R;;;;1000;N;;;;; +10C00;OLD TURKIC LETTER ORKHON A;Lo;0;R;;;;;N;;;;; +10C01;OLD TURKIC LETTER YENISEI A;Lo;0;R;;;;;N;;;;; +10C02;OLD TURKIC LETTER YENISEI AE;Lo;0;R;;;;;N;;;;; +10C03;OLD TURKIC LETTER ORKHON I;Lo;0;R;;;;;N;;;;; +10C04;OLD TURKIC LETTER YENISEI I;Lo;0;R;;;;;N;;;;; +10C05;OLD TURKIC LETTER YENISEI E;Lo;0;R;;;;;N;;;;; +10C06;OLD TURKIC LETTER ORKHON O;Lo;0;R;;;;;N;;;;; +10C07;OLD TURKIC LETTER ORKHON OE;Lo;0;R;;;;;N;;;;; +10C08;OLD TURKIC LETTER YENISEI OE;Lo;0;R;;;;;N;;;;; +10C09;OLD TURKIC LETTER ORKHON AB;Lo;0;R;;;;;N;;;;; +10C0A;OLD TURKIC LETTER YENISEI AB;Lo;0;R;;;;;N;;;;; +10C0B;OLD TURKIC LETTER ORKHON AEB;Lo;0;R;;;;;N;;;;; +10C0C;OLD TURKIC LETTER YENISEI AEB;Lo;0;R;;;;;N;;;;; +10C0D;OLD TURKIC LETTER ORKHON AG;Lo;0;R;;;;;N;;;;; +10C0E;OLD TURKIC LETTER YENISEI AG;Lo;0;R;;;;;N;;;;; +10C0F;OLD TURKIC LETTER ORKHON AEG;Lo;0;R;;;;;N;;;;; +10C10;OLD TURKIC LETTER YENISEI AEG;Lo;0;R;;;;;N;;;;; +10C11;OLD TURKIC LETTER ORKHON AD;Lo;0;R;;;;;N;;;;; +10C12;OLD TURKIC LETTER YENISEI AD;Lo;0;R;;;;;N;;;;; +10C13;OLD TURKIC LETTER ORKHON AED;Lo;0;R;;;;;N;;;;; +10C14;OLD TURKIC LETTER ORKHON EZ;Lo;0;R;;;;;N;;;;; +10C15;OLD TURKIC LETTER YENISEI EZ;Lo;0;R;;;;;N;;;;; +10C16;OLD TURKIC LETTER ORKHON AY;Lo;0;R;;;;;N;;;;; +10C17;OLD TURKIC LETTER YENISEI AY;Lo;0;R;;;;;N;;;;; +10C18;OLD TURKIC LETTER ORKHON AEY;Lo;0;R;;;;;N;;;;; +10C19;OLD TURKIC LETTER YENISEI AEY;Lo;0;R;;;;;N;;;;; +10C1A;OLD TURKIC LETTER ORKHON AEK;Lo;0;R;;;;;N;;;;; +10C1B;OLD TURKIC LETTER YENISEI AEK;Lo;0;R;;;;;N;;;;; +10C1C;OLD TURKIC LETTER ORKHON OEK;Lo;0;R;;;;;N;;;;; +10C1D;OLD TURKIC LETTER YENISEI OEK;Lo;0;R;;;;;N;;;;; +10C1E;OLD TURKIC LETTER ORKHON AL;Lo;0;R;;;;;N;;;;; +10C1F;OLD TURKIC LETTER YENISEI AL;Lo;0;R;;;;;N;;;;; +10C20;OLD TURKIC LETTER ORKHON AEL;Lo;0;R;;;;;N;;;;; +10C21;OLD TURKIC LETTER ORKHON ELT;Lo;0;R;;;;;N;;;;; +10C22;OLD TURKIC LETTER ORKHON EM;Lo;0;R;;;;;N;;;;; +10C23;OLD TURKIC LETTER ORKHON AN;Lo;0;R;;;;;N;;;;; +10C24;OLD TURKIC LETTER ORKHON AEN;Lo;0;R;;;;;N;;;;; +10C25;OLD TURKIC LETTER YENISEI AEN;Lo;0;R;;;;;N;;;;; +10C26;OLD TURKIC LETTER ORKHON ENT;Lo;0;R;;;;;N;;;;; +10C27;OLD TURKIC LETTER YENISEI ENT;Lo;0;R;;;;;N;;;;; +10C28;OLD TURKIC LETTER ORKHON ENC;Lo;0;R;;;;;N;;;;; +10C29;OLD TURKIC LETTER YENISEI ENC;Lo;0;R;;;;;N;;;;; +10C2A;OLD TURKIC LETTER ORKHON ENY;Lo;0;R;;;;;N;;;;; +10C2B;OLD TURKIC LETTER YENISEI ENY;Lo;0;R;;;;;N;;;;; +10C2C;OLD TURKIC LETTER YENISEI ANG;Lo;0;R;;;;;N;;;;; +10C2D;OLD TURKIC LETTER ORKHON ENG;Lo;0;R;;;;;N;;;;; +10C2E;OLD TURKIC LETTER YENISEI AENG;Lo;0;R;;;;;N;;;;; +10C2F;OLD TURKIC LETTER ORKHON EP;Lo;0;R;;;;;N;;;;; +10C30;OLD TURKIC LETTER ORKHON OP;Lo;0;R;;;;;N;;;;; +10C31;OLD TURKIC LETTER ORKHON IC;Lo;0;R;;;;;N;;;;; +10C32;OLD TURKIC LETTER ORKHON EC;Lo;0;R;;;;;N;;;;; +10C33;OLD TURKIC LETTER YENISEI EC;Lo;0;R;;;;;N;;;;; +10C34;OLD TURKIC LETTER ORKHON AQ;Lo;0;R;;;;;N;;;;; +10C35;OLD TURKIC LETTER YENISEI AQ;Lo;0;R;;;;;N;;;;; +10C36;OLD TURKIC LETTER ORKHON IQ;Lo;0;R;;;;;N;;;;; +10C37;OLD TURKIC LETTER YENISEI IQ;Lo;0;R;;;;;N;;;;; +10C38;OLD TURKIC LETTER ORKHON OQ;Lo;0;R;;;;;N;;;;; +10C39;OLD TURKIC LETTER YENISEI OQ;Lo;0;R;;;;;N;;;;; +10C3A;OLD TURKIC LETTER ORKHON AR;Lo;0;R;;;;;N;;;;; +10C3B;OLD TURKIC LETTER YENISEI AR;Lo;0;R;;;;;N;;;;; +10C3C;OLD TURKIC LETTER ORKHON AER;Lo;0;R;;;;;N;;;;; +10C3D;OLD TURKIC LETTER ORKHON AS;Lo;0;R;;;;;N;;;;; +10C3E;OLD TURKIC LETTER ORKHON AES;Lo;0;R;;;;;N;;;;; +10C3F;OLD TURKIC LETTER ORKHON ASH;Lo;0;R;;;;;N;;;;; +10C40;OLD TURKIC LETTER YENISEI ASH;Lo;0;R;;;;;N;;;;; +10C41;OLD TURKIC LETTER ORKHON ESH;Lo;0;R;;;;;N;;;;; +10C42;OLD TURKIC LETTER YENISEI ESH;Lo;0;R;;;;;N;;;;; +10C43;OLD TURKIC LETTER ORKHON AT;Lo;0;R;;;;;N;;;;; +10C44;OLD TURKIC LETTER YENISEI AT;Lo;0;R;;;;;N;;;;; +10C45;OLD TURKIC LETTER ORKHON AET;Lo;0;R;;;;;N;;;;; +10C46;OLD TURKIC LETTER YENISEI AET;Lo;0;R;;;;;N;;;;; +10C47;OLD TURKIC LETTER ORKHON OT;Lo;0;R;;;;;N;;;;; +10C48;OLD TURKIC LETTER ORKHON BASH;Lo;0;R;;;;;N;;;;; +10E60;RUMI DIGIT ONE;No;0;AN;;;1;1;N;;;;; +10E61;RUMI DIGIT TWO;No;0;AN;;;2;2;N;;;;; +10E62;RUMI DIGIT THREE;No;0;AN;;;3;3;N;;;;; +10E63;RUMI DIGIT FOUR;No;0;AN;;;4;4;N;;;;; +10E64;RUMI DIGIT FIVE;No;0;AN;;;5;5;N;;;;; +10E65;RUMI DIGIT SIX;No;0;AN;;;6;6;N;;;;; +10E66;RUMI DIGIT SEVEN;No;0;AN;;;7;7;N;;;;; +10E67;RUMI DIGIT EIGHT;No;0;AN;;;8;8;N;;;;; +10E68;RUMI DIGIT NINE;No;0;AN;;;9;9;N;;;;; +10E69;RUMI NUMBER TEN;No;0;AN;;;;10;N;;;;; +10E6A;RUMI NUMBER TWENTY;No;0;AN;;;;20;N;;;;; +10E6B;RUMI NUMBER THIRTY;No;0;AN;;;;30;N;;;;; +10E6C;RUMI NUMBER FORTY;No;0;AN;;;;40;N;;;;; +10E6D;RUMI NUMBER FIFTY;No;0;AN;;;;50;N;;;;; +10E6E;RUMI NUMBER SIXTY;No;0;AN;;;;60;N;;;;; +10E6F;RUMI NUMBER SEVENTY;No;0;AN;;;;70;N;;;;; +10E70;RUMI NUMBER EIGHTY;No;0;AN;;;;80;N;;;;; +10E71;RUMI NUMBER NINETY;No;0;AN;;;;90;N;;;;; +10E72;RUMI NUMBER ONE HUNDRED;No;0;AN;;;;100;N;;;;; +10E73;RUMI NUMBER TWO HUNDRED;No;0;AN;;;;200;N;;;;; +10E74;RUMI NUMBER THREE HUNDRED;No;0;AN;;;;300;N;;;;; +10E75;RUMI NUMBER FOUR HUNDRED;No;0;AN;;;;400;N;;;;; +10E76;RUMI NUMBER FIVE HUNDRED;No;0;AN;;;;500;N;;;;; +10E77;RUMI NUMBER SIX HUNDRED;No;0;AN;;;;600;N;;;;; +10E78;RUMI NUMBER SEVEN HUNDRED;No;0;AN;;;;700;N;;;;; +10E79;RUMI NUMBER EIGHT HUNDRED;No;0;AN;;;;800;N;;;;; +10E7A;RUMI NUMBER NINE HUNDRED;No;0;AN;;;;900;N;;;;; +10E7B;RUMI FRACTION ONE HALF;No;0;AN;;;;1/2;N;;;;; +10E7C;RUMI FRACTION ONE QUARTER;No;0;AN;;;;1/4;N;;;;; +10E7D;RUMI FRACTION ONE THIRD;No;0;AN;;;;1/3;N;;;;; +10E7E;RUMI FRACTION TWO THIRDS;No;0;AN;;;;2/3;N;;;;; +11000;BRAHMI SIGN CANDRABINDU;Mc;0;L;;;;;N;;;;; +11001;BRAHMI SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +11002;BRAHMI SIGN VISARGA;Mc;0;L;;;;;N;;;;; +11003;BRAHMI SIGN JIHVAMULIYA;Lo;0;L;;;;;N;;;;; +11004;BRAHMI SIGN UPADHMANIYA;Lo;0;L;;;;;N;;;;; +11005;BRAHMI LETTER A;Lo;0;L;;;;;N;;;;; +11006;BRAHMI LETTER AA;Lo;0;L;;;;;N;;;;; +11007;BRAHMI LETTER I;Lo;0;L;;;;;N;;;;; +11008;BRAHMI LETTER II;Lo;0;L;;;;;N;;;;; +11009;BRAHMI LETTER U;Lo;0;L;;;;;N;;;;; +1100A;BRAHMI LETTER UU;Lo;0;L;;;;;N;;;;; +1100B;BRAHMI LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +1100C;BRAHMI LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +1100D;BRAHMI LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +1100E;BRAHMI LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +1100F;BRAHMI LETTER E;Lo;0;L;;;;;N;;;;; +11010;BRAHMI LETTER AI;Lo;0;L;;;;;N;;;;; +11011;BRAHMI LETTER O;Lo;0;L;;;;;N;;;;; +11012;BRAHMI LETTER AU;Lo;0;L;;;;;N;;;;; +11013;BRAHMI LETTER KA;Lo;0;L;;;;;N;;;;; +11014;BRAHMI LETTER KHA;Lo;0;L;;;;;N;;;;; +11015;BRAHMI LETTER GA;Lo;0;L;;;;;N;;;;; +11016;BRAHMI LETTER GHA;Lo;0;L;;;;;N;;;;; +11017;BRAHMI LETTER NGA;Lo;0;L;;;;;N;;;;; +11018;BRAHMI LETTER CA;Lo;0;L;;;;;N;;;;; +11019;BRAHMI LETTER CHA;Lo;0;L;;;;;N;;;;; +1101A;BRAHMI LETTER JA;Lo;0;L;;;;;N;;;;; +1101B;BRAHMI LETTER JHA;Lo;0;L;;;;;N;;;;; +1101C;BRAHMI LETTER NYA;Lo;0;L;;;;;N;;;;; +1101D;BRAHMI LETTER TTA;Lo;0;L;;;;;N;;;;; +1101E;BRAHMI LETTER TTHA;Lo;0;L;;;;;N;;;;; +1101F;BRAHMI LETTER DDA;Lo;0;L;;;;;N;;;;; +11020;BRAHMI LETTER DDHA;Lo;0;L;;;;;N;;;;; +11021;BRAHMI LETTER NNA;Lo;0;L;;;;;N;;;;; +11022;BRAHMI LETTER TA;Lo;0;L;;;;;N;;;;; +11023;BRAHMI LETTER THA;Lo;0;L;;;;;N;;;;; +11024;BRAHMI LETTER DA;Lo;0;L;;;;;N;;;;; +11025;BRAHMI LETTER DHA;Lo;0;L;;;;;N;;;;; +11026;BRAHMI LETTER NA;Lo;0;L;;;;;N;;;;; +11027;BRAHMI LETTER PA;Lo;0;L;;;;;N;;;;; +11028;BRAHMI LETTER PHA;Lo;0;L;;;;;N;;;;; +11029;BRAHMI LETTER BA;Lo;0;L;;;;;N;;;;; +1102A;BRAHMI LETTER BHA;Lo;0;L;;;;;N;;;;; +1102B;BRAHMI LETTER MA;Lo;0;L;;;;;N;;;;; +1102C;BRAHMI LETTER YA;Lo;0;L;;;;;N;;;;; +1102D;BRAHMI LETTER RA;Lo;0;L;;;;;N;;;;; +1102E;BRAHMI LETTER LA;Lo;0;L;;;;;N;;;;; +1102F;BRAHMI LETTER VA;Lo;0;L;;;;;N;;;;; +11030;BRAHMI LETTER SHA;Lo;0;L;;;;;N;;;;; +11031;BRAHMI LETTER SSA;Lo;0;L;;;;;N;;;;; +11032;BRAHMI LETTER SA;Lo;0;L;;;;;N;;;;; +11033;BRAHMI LETTER HA;Lo;0;L;;;;;N;;;;; +11034;BRAHMI LETTER LLA;Lo;0;L;;;;;N;;;;; +11035;BRAHMI LETTER OLD TAMIL LLLA;Lo;0;L;;;;;N;;;;; +11036;BRAHMI LETTER OLD TAMIL RRA;Lo;0;L;;;;;N;;;;; +11037;BRAHMI LETTER OLD TAMIL NNNA;Lo;0;L;;;;;N;;;;; +11038;BRAHMI VOWEL SIGN AA;Mn;0;NSM;;;;;N;;;;; +11039;BRAHMI VOWEL SIGN BHATTIPROLU AA;Mn;0;NSM;;;;;N;;;;; +1103A;BRAHMI VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +1103B;BRAHMI VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;; +1103C;BRAHMI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +1103D;BRAHMI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +1103E;BRAHMI VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;; +1103F;BRAHMI VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;; +11040;BRAHMI VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +11041;BRAHMI VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +11042;BRAHMI VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +11043;BRAHMI VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +11044;BRAHMI VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;; +11045;BRAHMI VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;; +11046;BRAHMI VIRAMA;Mn;9;NSM;;;;;N;;;;; +11047;BRAHMI DANDA;Po;0;L;;;;;N;;;;; +11048;BRAHMI DOUBLE DANDA;Po;0;L;;;;;N;;;;; +11049;BRAHMI PUNCTUATION DOT;Po;0;L;;;;;N;;;;; +1104A;BRAHMI PUNCTUATION DOUBLE DOT;Po;0;L;;;;;N;;;;; +1104B;BRAHMI PUNCTUATION LINE;Po;0;L;;;;;N;;;;; +1104C;BRAHMI PUNCTUATION CRESCENT BAR;Po;0;L;;;;;N;;;;; +1104D;BRAHMI PUNCTUATION LOTUS;Po;0;L;;;;;N;;;;; +11052;BRAHMI NUMBER ONE;No;0;ON;;;1;1;N;;;;; +11053;BRAHMI NUMBER TWO;No;0;ON;;;2;2;N;;;;; +11054;BRAHMI NUMBER THREE;No;0;ON;;;3;3;N;;;;; +11055;BRAHMI NUMBER FOUR;No;0;ON;;;4;4;N;;;;; +11056;BRAHMI NUMBER FIVE;No;0;ON;;;5;5;N;;;;; +11057;BRAHMI NUMBER SIX;No;0;ON;;;6;6;N;;;;; +11058;BRAHMI NUMBER SEVEN;No;0;ON;;;7;7;N;;;;; +11059;BRAHMI NUMBER EIGHT;No;0;ON;;;8;8;N;;;;; +1105A;BRAHMI NUMBER NINE;No;0;ON;;;9;9;N;;;;; +1105B;BRAHMI NUMBER TEN;No;0;ON;;;;10;N;;;;; +1105C;BRAHMI NUMBER TWENTY;No;0;ON;;;;20;N;;;;; +1105D;BRAHMI NUMBER THIRTY;No;0;ON;;;;30;N;;;;; +1105E;BRAHMI NUMBER FORTY;No;0;ON;;;;40;N;;;;; +1105F;BRAHMI NUMBER FIFTY;No;0;ON;;;;50;N;;;;; +11060;BRAHMI NUMBER SIXTY;No;0;ON;;;;60;N;;;;; +11061;BRAHMI NUMBER SEVENTY;No;0;ON;;;;70;N;;;;; +11062;BRAHMI NUMBER EIGHTY;No;0;ON;;;;80;N;;;;; +11063;BRAHMI NUMBER NINETY;No;0;ON;;;;90;N;;;;; +11064;BRAHMI NUMBER ONE HUNDRED;No;0;ON;;;;100;N;;;;; +11065;BRAHMI NUMBER ONE THOUSAND;No;0;ON;;;;1000;N;;;;; +11066;BRAHMI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +11067;BRAHMI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +11068;BRAHMI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +11069;BRAHMI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1106A;BRAHMI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1106B;BRAHMI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1106C;BRAHMI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1106D;BRAHMI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1106E;BRAHMI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1106F;BRAHMI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +11080;KAITHI SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;; +11081;KAITHI SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +11082;KAITHI SIGN VISARGA;Mc;0;L;;;;;N;;;;; +11083;KAITHI LETTER A;Lo;0;L;;;;;N;;;;; +11084;KAITHI LETTER AA;Lo;0;L;;;;;N;;;;; +11085;KAITHI LETTER I;Lo;0;L;;;;;N;;;;; +11086;KAITHI LETTER II;Lo;0;L;;;;;N;;;;; +11087;KAITHI LETTER U;Lo;0;L;;;;;N;;;;; +11088;KAITHI LETTER UU;Lo;0;L;;;;;N;;;;; +11089;KAITHI LETTER E;Lo;0;L;;;;;N;;;;; +1108A;KAITHI LETTER AI;Lo;0;L;;;;;N;;;;; +1108B;KAITHI LETTER O;Lo;0;L;;;;;N;;;;; +1108C;KAITHI LETTER AU;Lo;0;L;;;;;N;;;;; +1108D;KAITHI LETTER KA;Lo;0;L;;;;;N;;;;; +1108E;KAITHI LETTER KHA;Lo;0;L;;;;;N;;;;; +1108F;KAITHI LETTER GA;Lo;0;L;;;;;N;;;;; +11090;KAITHI LETTER GHA;Lo;0;L;;;;;N;;;;; +11091;KAITHI LETTER NGA;Lo;0;L;;;;;N;;;;; +11092;KAITHI LETTER CA;Lo;0;L;;;;;N;;;;; +11093;KAITHI LETTER CHA;Lo;0;L;;;;;N;;;;; +11094;KAITHI LETTER JA;Lo;0;L;;;;;N;;;;; +11095;KAITHI LETTER JHA;Lo;0;L;;;;;N;;;;; +11096;KAITHI LETTER NYA;Lo;0;L;;;;;N;;;;; +11097;KAITHI LETTER TTA;Lo;0;L;;;;;N;;;;; +11098;KAITHI LETTER TTHA;Lo;0;L;;;;;N;;;;; +11099;KAITHI LETTER DDA;Lo;0;L;;;;;N;;;;; +1109A;KAITHI LETTER DDDHA;Lo;0;L;11099 110BA;;;;N;;;;; +1109B;KAITHI LETTER DDHA;Lo;0;L;;;;;N;;;;; +1109C;KAITHI LETTER RHA;Lo;0;L;1109B 110BA;;;;N;;;;; +1109D;KAITHI LETTER NNA;Lo;0;L;;;;;N;;;;; +1109E;KAITHI LETTER TA;Lo;0;L;;;;;N;;;;; +1109F;KAITHI LETTER THA;Lo;0;L;;;;;N;;;;; +110A0;KAITHI LETTER DA;Lo;0;L;;;;;N;;;;; +110A1;KAITHI LETTER DHA;Lo;0;L;;;;;N;;;;; +110A2;KAITHI LETTER NA;Lo;0;L;;;;;N;;;;; +110A3;KAITHI LETTER PA;Lo;0;L;;;;;N;;;;; +110A4;KAITHI LETTER PHA;Lo;0;L;;;;;N;;;;; +110A5;KAITHI LETTER BA;Lo;0;L;;;;;N;;;;; +110A6;KAITHI LETTER BHA;Lo;0;L;;;;;N;;;;; +110A7;KAITHI LETTER MA;Lo;0;L;;;;;N;;;;; +110A8;KAITHI LETTER YA;Lo;0;L;;;;;N;;;;; +110A9;KAITHI LETTER RA;Lo;0;L;;;;;N;;;;; +110AA;KAITHI LETTER LA;Lo;0;L;;;;;N;;;;; +110AB;KAITHI LETTER VA;Lo;0;L;110A5 110BA;;;;N;;;;; +110AC;KAITHI LETTER SHA;Lo;0;L;;;;;N;;;;; +110AD;KAITHI LETTER SSA;Lo;0;L;;;;;N;;;;; +110AE;KAITHI LETTER SA;Lo;0;L;;;;;N;;;;; +110AF;KAITHI LETTER HA;Lo;0;L;;;;;N;;;;; +110B0;KAITHI VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +110B1;KAITHI VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +110B2;KAITHI VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +110B3;KAITHI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +110B4;KAITHI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +110B5;KAITHI VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +110B6;KAITHI VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +110B7;KAITHI VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +110B8;KAITHI VOWEL SIGN AU;Mc;0;L;;;;;N;;;;; +110B9;KAITHI SIGN VIRAMA;Mn;9;NSM;;;;;N;;;;; +110BA;KAITHI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;; +110BB;KAITHI ABBREVIATION SIGN;Po;0;L;;;;;N;;;;; +110BC;KAITHI ENUMERATION SIGN;Po;0;L;;;;;N;;;;; +110BD;KAITHI NUMBER SIGN;Cf;0;L;;;;;N;;;;; +110BE;KAITHI SECTION MARK;Po;0;L;;;;;N;;;;; +110BF;KAITHI DOUBLE SECTION MARK;Po;0;L;;;;;N;;;;; +110C0;KAITHI DANDA;Po;0;L;;;;;N;;;;; +110C1;KAITHI DOUBLE DANDA;Po;0;L;;;;;N;;;;; +110D0;SORA SOMPENG LETTER SAH;Lo;0;L;;;;;N;;;;; +110D1;SORA SOMPENG LETTER TAH;Lo;0;L;;;;;N;;;;; +110D2;SORA SOMPENG LETTER BAH;Lo;0;L;;;;;N;;;;; +110D3;SORA SOMPENG LETTER CAH;Lo;0;L;;;;;N;;;;; +110D4;SORA SOMPENG LETTER DAH;Lo;0;L;;;;;N;;;;; +110D5;SORA SOMPENG LETTER GAH;Lo;0;L;;;;;N;;;;; +110D6;SORA SOMPENG LETTER MAH;Lo;0;L;;;;;N;;;;; +110D7;SORA SOMPENG LETTER NGAH;Lo;0;L;;;;;N;;;;; +110D8;SORA SOMPENG LETTER LAH;Lo;0;L;;;;;N;;;;; +110D9;SORA SOMPENG LETTER NAH;Lo;0;L;;;;;N;;;;; +110DA;SORA SOMPENG LETTER VAH;Lo;0;L;;;;;N;;;;; +110DB;SORA SOMPENG LETTER PAH;Lo;0;L;;;;;N;;;;; +110DC;SORA SOMPENG LETTER YAH;Lo;0;L;;;;;N;;;;; +110DD;SORA SOMPENG LETTER RAH;Lo;0;L;;;;;N;;;;; +110DE;SORA SOMPENG LETTER HAH;Lo;0;L;;;;;N;;;;; +110DF;SORA SOMPENG LETTER KAH;Lo;0;L;;;;;N;;;;; +110E0;SORA SOMPENG LETTER JAH;Lo;0;L;;;;;N;;;;; +110E1;SORA SOMPENG LETTER NYAH;Lo;0;L;;;;;N;;;;; +110E2;SORA SOMPENG LETTER AH;Lo;0;L;;;;;N;;;;; +110E3;SORA SOMPENG LETTER EEH;Lo;0;L;;;;;N;;;;; +110E4;SORA SOMPENG LETTER IH;Lo;0;L;;;;;N;;;;; +110E5;SORA SOMPENG LETTER UH;Lo;0;L;;;;;N;;;;; +110E6;SORA SOMPENG LETTER OH;Lo;0;L;;;;;N;;;;; +110E7;SORA SOMPENG LETTER EH;Lo;0;L;;;;;N;;;;; +110E8;SORA SOMPENG LETTER MAE;Lo;0;L;;;;;N;;;;; +110F0;SORA SOMPENG DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +110F1;SORA SOMPENG DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +110F2;SORA SOMPENG DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +110F3;SORA SOMPENG DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +110F4;SORA SOMPENG DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +110F5;SORA SOMPENG DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +110F6;SORA SOMPENG DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +110F7;SORA SOMPENG DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +110F8;SORA SOMPENG DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +110F9;SORA SOMPENG DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +11100;CHAKMA SIGN CANDRABINDU;Mn;230;NSM;;;;;N;;;;; +11101;CHAKMA SIGN ANUSVARA;Mn;230;NSM;;;;;N;;;;; +11102;CHAKMA SIGN VISARGA;Mn;230;NSM;;;;;N;;;;; +11103;CHAKMA LETTER AA;Lo;0;L;;;;;N;;;;; +11104;CHAKMA LETTER I;Lo;0;L;;;;;N;;;;; +11105;CHAKMA LETTER U;Lo;0;L;;;;;N;;;;; +11106;CHAKMA LETTER E;Lo;0;L;;;;;N;;;;; +11107;CHAKMA LETTER KAA;Lo;0;L;;;;;N;;;;; +11108;CHAKMA LETTER KHAA;Lo;0;L;;;;;N;;;;; +11109;CHAKMA LETTER GAA;Lo;0;L;;;;;N;;;;; +1110A;CHAKMA LETTER GHAA;Lo;0;L;;;;;N;;;;; +1110B;CHAKMA LETTER NGAA;Lo;0;L;;;;;N;;;;; +1110C;CHAKMA LETTER CAA;Lo;0;L;;;;;N;;;;; +1110D;CHAKMA LETTER CHAA;Lo;0;L;;;;;N;;;;; +1110E;CHAKMA LETTER JAA;Lo;0;L;;;;;N;;;;; +1110F;CHAKMA LETTER JHAA;Lo;0;L;;;;;N;;;;; +11110;CHAKMA LETTER NYAA;Lo;0;L;;;;;N;;;;; +11111;CHAKMA LETTER TTAA;Lo;0;L;;;;;N;;;;; +11112;CHAKMA LETTER TTHAA;Lo;0;L;;;;;N;;;;; +11113;CHAKMA LETTER DDAA;Lo;0;L;;;;;N;;;;; +11114;CHAKMA LETTER DDHAA;Lo;0;L;;;;;N;;;;; +11115;CHAKMA LETTER NNAA;Lo;0;L;;;;;N;;;;; +11116;CHAKMA LETTER TAA;Lo;0;L;;;;;N;;;;; +11117;CHAKMA LETTER THAA;Lo;0;L;;;;;N;;;;; +11118;CHAKMA LETTER DAA;Lo;0;L;;;;;N;;;;; +11119;CHAKMA LETTER DHAA;Lo;0;L;;;;;N;;;;; +1111A;CHAKMA LETTER NAA;Lo;0;L;;;;;N;;;;; +1111B;CHAKMA LETTER PAA;Lo;0;L;;;;;N;;;;; +1111C;CHAKMA LETTER PHAA;Lo;0;L;;;;;N;;;;; +1111D;CHAKMA LETTER BAA;Lo;0;L;;;;;N;;;;; +1111E;CHAKMA LETTER BHAA;Lo;0;L;;;;;N;;;;; +1111F;CHAKMA LETTER MAA;Lo;0;L;;;;;N;;;;; +11120;CHAKMA LETTER YYAA;Lo;0;L;;;;;N;;;;; +11121;CHAKMA LETTER YAA;Lo;0;L;;;;;N;;;;; +11122;CHAKMA LETTER RAA;Lo;0;L;;;;;N;;;;; +11123;CHAKMA LETTER LAA;Lo;0;L;;;;;N;;;;; +11124;CHAKMA LETTER WAA;Lo;0;L;;;;;N;;;;; +11125;CHAKMA LETTER SAA;Lo;0;L;;;;;N;;;;; +11126;CHAKMA LETTER HAA;Lo;0;L;;;;;N;;;;; +11127;CHAKMA VOWEL SIGN A;Mn;0;NSM;;;;;N;;;;; +11128;CHAKMA VOWEL SIGN I;Mn;0;NSM;;;;;N;;;;; +11129;CHAKMA VOWEL SIGN II;Mn;0;NSM;;;;;N;;;;; +1112A;CHAKMA VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +1112B;CHAKMA VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +1112C;CHAKMA VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +1112D;CHAKMA VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +1112E;CHAKMA VOWEL SIGN O;Mn;0;NSM;11131 11127;;;;N;;;;; +1112F;CHAKMA VOWEL SIGN AU;Mn;0;NSM;11132 11127;;;;N;;;;; +11130;CHAKMA VOWEL SIGN OI;Mn;0;NSM;;;;;N;;;;; +11131;CHAKMA O MARK;Mn;0;NSM;;;;;N;;;;; +11132;CHAKMA AU MARK;Mn;0;NSM;;;;;N;;;;; +11133;CHAKMA VIRAMA;Mn;9;NSM;;;;;N;;;;; +11134;CHAKMA MAAYYAA;Mn;9;NSM;;;;;N;;;;; +11136;CHAKMA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +11137;CHAKMA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +11138;CHAKMA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +11139;CHAKMA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +1113A;CHAKMA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +1113B;CHAKMA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +1113C;CHAKMA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +1113D;CHAKMA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +1113E;CHAKMA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +1113F;CHAKMA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +11140;CHAKMA SECTION MARK;Po;0;L;;;;;N;;;;; +11141;CHAKMA DANDA;Po;0;L;;;;;N;;;;; +11142;CHAKMA DOUBLE DANDA;Po;0;L;;;;;N;;;;; +11143;CHAKMA QUESTION MARK;Po;0;L;;;;;N;;;;; +11180;SHARADA SIGN CANDRABINDU;Mn;0;NSM;;;;;N;;;;; +11181;SHARADA SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +11182;SHARADA SIGN VISARGA;Mc;0;L;;;;;N;;;;; +11183;SHARADA LETTER A;Lo;0;L;;;;;N;;;;; +11184;SHARADA LETTER AA;Lo;0;L;;;;;N;;;;; +11185;SHARADA LETTER I;Lo;0;L;;;;;N;;;;; +11186;SHARADA LETTER II;Lo;0;L;;;;;N;;;;; +11187;SHARADA LETTER U;Lo;0;L;;;;;N;;;;; +11188;SHARADA LETTER UU;Lo;0;L;;;;;N;;;;; +11189;SHARADA LETTER VOCALIC R;Lo;0;L;;;;;N;;;;; +1118A;SHARADA LETTER VOCALIC RR;Lo;0;L;;;;;N;;;;; +1118B;SHARADA LETTER VOCALIC L;Lo;0;L;;;;;N;;;;; +1118C;SHARADA LETTER VOCALIC LL;Lo;0;L;;;;;N;;;;; +1118D;SHARADA LETTER E;Lo;0;L;;;;;N;;;;; +1118E;SHARADA LETTER AI;Lo;0;L;;;;;N;;;;; +1118F;SHARADA LETTER O;Lo;0;L;;;;;N;;;;; +11190;SHARADA LETTER AU;Lo;0;L;;;;;N;;;;; +11191;SHARADA LETTER KA;Lo;0;L;;;;;N;;;;; +11192;SHARADA LETTER KHA;Lo;0;L;;;;;N;;;;; +11193;SHARADA LETTER GA;Lo;0;L;;;;;N;;;;; +11194;SHARADA LETTER GHA;Lo;0;L;;;;;N;;;;; +11195;SHARADA LETTER NGA;Lo;0;L;;;;;N;;;;; +11196;SHARADA LETTER CA;Lo;0;L;;;;;N;;;;; +11197;SHARADA LETTER CHA;Lo;0;L;;;;;N;;;;; +11198;SHARADA LETTER JA;Lo;0;L;;;;;N;;;;; +11199;SHARADA LETTER JHA;Lo;0;L;;;;;N;;;;; +1119A;SHARADA LETTER NYA;Lo;0;L;;;;;N;;;;; +1119B;SHARADA LETTER TTA;Lo;0;L;;;;;N;;;;; +1119C;SHARADA LETTER TTHA;Lo;0;L;;;;;N;;;;; +1119D;SHARADA LETTER DDA;Lo;0;L;;;;;N;;;;; +1119E;SHARADA LETTER DDHA;Lo;0;L;;;;;N;;;;; +1119F;SHARADA LETTER NNA;Lo;0;L;;;;;N;;;;; +111A0;SHARADA LETTER TA;Lo;0;L;;;;;N;;;;; +111A1;SHARADA LETTER THA;Lo;0;L;;;;;N;;;;; +111A2;SHARADA LETTER DA;Lo;0;L;;;;;N;;;;; +111A3;SHARADA LETTER DHA;Lo;0;L;;;;;N;;;;; +111A4;SHARADA LETTER NA;Lo;0;L;;;;;N;;;;; +111A5;SHARADA LETTER PA;Lo;0;L;;;;;N;;;;; +111A6;SHARADA LETTER PHA;Lo;0;L;;;;;N;;;;; +111A7;SHARADA LETTER BA;Lo;0;L;;;;;N;;;;; +111A8;SHARADA LETTER BHA;Lo;0;L;;;;;N;;;;; +111A9;SHARADA LETTER MA;Lo;0;L;;;;;N;;;;; +111AA;SHARADA LETTER YA;Lo;0;L;;;;;N;;;;; +111AB;SHARADA LETTER RA;Lo;0;L;;;;;N;;;;; +111AC;SHARADA LETTER LA;Lo;0;L;;;;;N;;;;; +111AD;SHARADA LETTER LLA;Lo;0;L;;;;;N;;;;; +111AE;SHARADA LETTER VA;Lo;0;L;;;;;N;;;;; +111AF;SHARADA LETTER SHA;Lo;0;L;;;;;N;;;;; +111B0;SHARADA LETTER SSA;Lo;0;L;;;;;N;;;;; +111B1;SHARADA LETTER SA;Lo;0;L;;;;;N;;;;; +111B2;SHARADA LETTER HA;Lo;0;L;;;;;N;;;;; +111B3;SHARADA VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +111B4;SHARADA VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +111B5;SHARADA VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +111B6;SHARADA VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +111B7;SHARADA VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +111B8;SHARADA VOWEL SIGN VOCALIC R;Mn;0;NSM;;;;;N;;;;; +111B9;SHARADA VOWEL SIGN VOCALIC RR;Mn;0;NSM;;;;;N;;;;; +111BA;SHARADA VOWEL SIGN VOCALIC L;Mn;0;NSM;;;;;N;;;;; +111BB;SHARADA VOWEL SIGN VOCALIC LL;Mn;0;NSM;;;;;N;;;;; +111BC;SHARADA VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +111BD;SHARADA VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +111BE;SHARADA VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;; +111BF;SHARADA VOWEL SIGN AU;Mc;0;L;;;;;N;;;;; +111C0;SHARADA SIGN VIRAMA;Mc;9;L;;;;;N;;;;; +111C1;SHARADA SIGN AVAGRAHA;Lo;0;L;;;;;N;;;;; +111C2;SHARADA SIGN JIHVAMULIYA;Lo;0;L;;;;;N;;;;; +111C3;SHARADA SIGN UPADHMANIYA;Lo;0;L;;;;;N;;;;; +111C4;SHARADA OM;Lo;0;L;;;;;N;;;;; +111C5;SHARADA DANDA;Po;0;L;;;;;N;;;;; +111C6;SHARADA DOUBLE DANDA;Po;0;L;;;;;N;;;;; +111C7;SHARADA ABBREVIATION SIGN;Po;0;L;;;;;N;;;;; +111C8;SHARADA SEPARATOR;Po;0;L;;;;;N;;;;; +111D0;SHARADA DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +111D1;SHARADA DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +111D2;SHARADA DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +111D3;SHARADA DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +111D4;SHARADA DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +111D5;SHARADA DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +111D6;SHARADA DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +111D7;SHARADA DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +111D8;SHARADA DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +111D9;SHARADA DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +11680;TAKRI LETTER A;Lo;0;L;;;;;N;;;;; +11681;TAKRI LETTER AA;Lo;0;L;;;;;N;;;;; +11682;TAKRI LETTER I;Lo;0;L;;;;;N;;;;; +11683;TAKRI LETTER II;Lo;0;L;;;;;N;;;;; +11684;TAKRI LETTER U;Lo;0;L;;;;;N;;;;; +11685;TAKRI LETTER UU;Lo;0;L;;;;;N;;;;; +11686;TAKRI LETTER E;Lo;0;L;;;;;N;;;;; +11687;TAKRI LETTER AI;Lo;0;L;;;;;N;;;;; +11688;TAKRI LETTER O;Lo;0;L;;;;;N;;;;; +11689;TAKRI LETTER AU;Lo;0;L;;;;;N;;;;; +1168A;TAKRI LETTER KA;Lo;0;L;;;;;N;;;;; +1168B;TAKRI LETTER KHA;Lo;0;L;;;;;N;;;;; +1168C;TAKRI LETTER GA;Lo;0;L;;;;;N;;;;; +1168D;TAKRI LETTER GHA;Lo;0;L;;;;;N;;;;; +1168E;TAKRI LETTER NGA;Lo;0;L;;;;;N;;;;; +1168F;TAKRI LETTER CA;Lo;0;L;;;;;N;;;;; +11690;TAKRI LETTER CHA;Lo;0;L;;;;;N;;;;; +11691;TAKRI LETTER JA;Lo;0;L;;;;;N;;;;; +11692;TAKRI LETTER JHA;Lo;0;L;;;;;N;;;;; +11693;TAKRI LETTER NYA;Lo;0;L;;;;;N;;;;; +11694;TAKRI LETTER TTA;Lo;0;L;;;;;N;;;;; +11695;TAKRI LETTER TTHA;Lo;0;L;;;;;N;;;;; +11696;TAKRI LETTER DDA;Lo;0;L;;;;;N;;;;; +11697;TAKRI LETTER DDHA;Lo;0;L;;;;;N;;;;; +11698;TAKRI LETTER NNA;Lo;0;L;;;;;N;;;;; +11699;TAKRI LETTER TA;Lo;0;L;;;;;N;;;;; +1169A;TAKRI LETTER THA;Lo;0;L;;;;;N;;;;; +1169B;TAKRI LETTER DA;Lo;0;L;;;;;N;;;;; +1169C;TAKRI LETTER DHA;Lo;0;L;;;;;N;;;;; +1169D;TAKRI LETTER NA;Lo;0;L;;;;;N;;;;; +1169E;TAKRI LETTER PA;Lo;0;L;;;;;N;;;;; +1169F;TAKRI LETTER PHA;Lo;0;L;;;;;N;;;;; +116A0;TAKRI LETTER BA;Lo;0;L;;;;;N;;;;; +116A1;TAKRI LETTER BHA;Lo;0;L;;;;;N;;;;; +116A2;TAKRI LETTER MA;Lo;0;L;;;;;N;;;;; +116A3;TAKRI LETTER YA;Lo;0;L;;;;;N;;;;; +116A4;TAKRI LETTER RA;Lo;0;L;;;;;N;;;;; +116A5;TAKRI LETTER LA;Lo;0;L;;;;;N;;;;; +116A6;TAKRI LETTER VA;Lo;0;L;;;;;N;;;;; +116A7;TAKRI LETTER SHA;Lo;0;L;;;;;N;;;;; +116A8;TAKRI LETTER SA;Lo;0;L;;;;;N;;;;; +116A9;TAKRI LETTER HA;Lo;0;L;;;;;N;;;;; +116AA;TAKRI LETTER RRA;Lo;0;L;;;;;N;;;;; +116AB;TAKRI SIGN ANUSVARA;Mn;0;NSM;;;;;N;;;;; +116AC;TAKRI SIGN VISARGA;Mc;0;L;;;;;N;;;;; +116AD;TAKRI VOWEL SIGN AA;Mn;0;NSM;;;;;N;;;;; +116AE;TAKRI VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +116AF;TAKRI VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +116B0;TAKRI VOWEL SIGN U;Mn;0;NSM;;;;;N;;;;; +116B1;TAKRI VOWEL SIGN UU;Mn;0;NSM;;;;;N;;;;; +116B2;TAKRI VOWEL SIGN E;Mn;0;NSM;;;;;N;;;;; +116B3;TAKRI VOWEL SIGN AI;Mn;0;NSM;;;;;N;;;;; +116B4;TAKRI VOWEL SIGN O;Mn;0;NSM;;;;;N;;;;; +116B5;TAKRI VOWEL SIGN AU;Mn;0;NSM;;;;;N;;;;; +116B6;TAKRI SIGN VIRAMA;Mc;9;L;;;;;N;;;;; +116B7;TAKRI SIGN NUKTA;Mn;7;NSM;;;;;N;;;;; +116C0;TAKRI DIGIT ZERO;Nd;0;L;;0;0;0;N;;;;; +116C1;TAKRI DIGIT ONE;Nd;0;L;;1;1;1;N;;;;; +116C2;TAKRI DIGIT TWO;Nd;0;L;;2;2;2;N;;;;; +116C3;TAKRI DIGIT THREE;Nd;0;L;;3;3;3;N;;;;; +116C4;TAKRI DIGIT FOUR;Nd;0;L;;4;4;4;N;;;;; +116C5;TAKRI DIGIT FIVE;Nd;0;L;;5;5;5;N;;;;; +116C6;TAKRI DIGIT SIX;Nd;0;L;;6;6;6;N;;;;; +116C7;TAKRI DIGIT SEVEN;Nd;0;L;;7;7;7;N;;;;; +116C8;TAKRI DIGIT EIGHT;Nd;0;L;;8;8;8;N;;;;; +116C9;TAKRI DIGIT NINE;Nd;0;L;;9;9;9;N;;;;; +12000;CUNEIFORM SIGN A;Lo;0;L;;;;;N;;;;; +12001;CUNEIFORM SIGN A TIMES A;Lo;0;L;;;;;N;;;;; +12002;CUNEIFORM SIGN A TIMES BAD;Lo;0;L;;;;;N;;;;; +12003;CUNEIFORM SIGN A TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +12004;CUNEIFORM SIGN A TIMES HA;Lo;0;L;;;;;N;;;;; +12005;CUNEIFORM SIGN A TIMES IGI;Lo;0;L;;;;;N;;;;; +12006;CUNEIFORM SIGN A TIMES LAGAR GUNU;Lo;0;L;;;;;N;;;;; +12007;CUNEIFORM SIGN A TIMES MUSH;Lo;0;L;;;;;N;;;;; +12008;CUNEIFORM SIGN A TIMES SAG;Lo;0;L;;;;;N;;;;; +12009;CUNEIFORM SIGN A2;Lo;0;L;;;;;N;;;;; +1200A;CUNEIFORM SIGN AB;Lo;0;L;;;;;N;;;;; +1200B;CUNEIFORM SIGN AB TIMES ASH2;Lo;0;L;;;;;N;;;;; +1200C;CUNEIFORM SIGN AB TIMES DUN3 GUNU;Lo;0;L;;;;;N;;;;; +1200D;CUNEIFORM SIGN AB TIMES GAL;Lo;0;L;;;;;N;;;;; +1200E;CUNEIFORM SIGN AB TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +1200F;CUNEIFORM SIGN AB TIMES HA;Lo;0;L;;;;;N;;;;; +12010;CUNEIFORM SIGN AB TIMES IGI GUNU;Lo;0;L;;;;;N;;;;; +12011;CUNEIFORM SIGN AB TIMES IMIN;Lo;0;L;;;;;N;;;;; +12012;CUNEIFORM SIGN AB TIMES LAGAB;Lo;0;L;;;;;N;;;;; +12013;CUNEIFORM SIGN AB TIMES SHESH;Lo;0;L;;;;;N;;;;; +12014;CUNEIFORM SIGN AB TIMES U PLUS U PLUS U;Lo;0;L;;;;;N;;;;; +12015;CUNEIFORM SIGN AB GUNU;Lo;0;L;;;;;N;;;;; +12016;CUNEIFORM SIGN AB2;Lo;0;L;;;;;N;;;;; +12017;CUNEIFORM SIGN AB2 TIMES BALAG;Lo;0;L;;;;;N;;;;; +12018;CUNEIFORM SIGN AB2 TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +12019;CUNEIFORM SIGN AB2 TIMES ME PLUS EN;Lo;0;L;;;;;N;;;;; +1201A;CUNEIFORM SIGN AB2 TIMES SHA3;Lo;0;L;;;;;N;;;;; +1201B;CUNEIFORM SIGN AB2 TIMES TAK4;Lo;0;L;;;;;N;;;;; +1201C;CUNEIFORM SIGN AD;Lo;0;L;;;;;N;;;;; +1201D;CUNEIFORM SIGN AK;Lo;0;L;;;;;N;;;;; +1201E;CUNEIFORM SIGN AK TIMES ERIN2;Lo;0;L;;;;;N;;;;; +1201F;CUNEIFORM SIGN AK TIMES SHITA PLUS GISH;Lo;0;L;;;;;N;;;;; +12020;CUNEIFORM SIGN AL;Lo;0;L;;;;;N;;;;; +12021;CUNEIFORM SIGN AL TIMES AL;Lo;0;L;;;;;N;;;;; +12022;CUNEIFORM SIGN AL TIMES DIM2;Lo;0;L;;;;;N;;;;; +12023;CUNEIFORM SIGN AL TIMES GISH;Lo;0;L;;;;;N;;;;; +12024;CUNEIFORM SIGN AL TIMES HA;Lo;0;L;;;;;N;;;;; +12025;CUNEIFORM SIGN AL TIMES KAD3;Lo;0;L;;;;;N;;;;; +12026;CUNEIFORM SIGN AL TIMES KI;Lo;0;L;;;;;N;;;;; +12027;CUNEIFORM SIGN AL TIMES SHE;Lo;0;L;;;;;N;;;;; +12028;CUNEIFORM SIGN AL TIMES USH;Lo;0;L;;;;;N;;;;; +12029;CUNEIFORM SIGN ALAN;Lo;0;L;;;;;N;;;;; +1202A;CUNEIFORM SIGN ALEPH;Lo;0;L;;;;;N;;;;; +1202B;CUNEIFORM SIGN AMAR;Lo;0;L;;;;;N;;;;; +1202C;CUNEIFORM SIGN AMAR TIMES SHE;Lo;0;L;;;;;N;;;;; +1202D;CUNEIFORM SIGN AN;Lo;0;L;;;;;N;;;;; +1202E;CUNEIFORM SIGN AN OVER AN;Lo;0;L;;;;;N;;;;; +1202F;CUNEIFORM SIGN AN THREE TIMES;Lo;0;L;;;;;N;;;;; +12030;CUNEIFORM SIGN AN PLUS NAGA OPPOSING AN PLUS NAGA;Lo;0;L;;;;;N;;;;; +12031;CUNEIFORM SIGN AN PLUS NAGA SQUARED;Lo;0;L;;;;;N;;;;; +12032;CUNEIFORM SIGN ANSHE;Lo;0;L;;;;;N;;;;; +12033;CUNEIFORM SIGN APIN;Lo;0;L;;;;;N;;;;; +12034;CUNEIFORM SIGN ARAD;Lo;0;L;;;;;N;;;;; +12035;CUNEIFORM SIGN ARAD TIMES KUR;Lo;0;L;;;;;N;;;;; +12036;CUNEIFORM SIGN ARKAB;Lo;0;L;;;;;N;;;;; +12037;CUNEIFORM SIGN ASAL2;Lo;0;L;;;;;N;;;;; +12038;CUNEIFORM SIGN ASH;Lo;0;L;;;;;N;;;;; +12039;CUNEIFORM SIGN ASH ZIDA TENU;Lo;0;L;;;;;N;;;;; +1203A;CUNEIFORM SIGN ASH KABA TENU;Lo;0;L;;;;;N;;;;; +1203B;CUNEIFORM SIGN ASH OVER ASH TUG2 OVER TUG2 TUG2 OVER TUG2 PAP;Lo;0;L;;;;;N;;;;; +1203C;CUNEIFORM SIGN ASH OVER ASH OVER ASH;Lo;0;L;;;;;N;;;;; +1203D;CUNEIFORM SIGN ASH OVER ASH OVER ASH CROSSING ASH OVER ASH OVER ASH;Lo;0;L;;;;;N;;;;; +1203E;CUNEIFORM SIGN ASH2;Lo;0;L;;;;;N;;;;; +1203F;CUNEIFORM SIGN ASHGAB;Lo;0;L;;;;;N;;;;; +12040;CUNEIFORM SIGN BA;Lo;0;L;;;;;N;;;;; +12041;CUNEIFORM SIGN BAD;Lo;0;L;;;;;N;;;;; +12042;CUNEIFORM SIGN BAG3;Lo;0;L;;;;;N;;;;; +12043;CUNEIFORM SIGN BAHAR2;Lo;0;L;;;;;N;;;;; +12044;CUNEIFORM SIGN BAL;Lo;0;L;;;;;N;;;;; +12045;CUNEIFORM SIGN BAL OVER BAL;Lo;0;L;;;;;N;;;;; +12046;CUNEIFORM SIGN BALAG;Lo;0;L;;;;;N;;;;; +12047;CUNEIFORM SIGN BAR;Lo;0;L;;;;;N;;;;; +12048;CUNEIFORM SIGN BARA2;Lo;0;L;;;;;N;;;;; +12049;CUNEIFORM SIGN BI;Lo;0;L;;;;;N;;;;; +1204A;CUNEIFORM SIGN BI TIMES A;Lo;0;L;;;;;N;;;;; +1204B;CUNEIFORM SIGN BI TIMES GAR;Lo;0;L;;;;;N;;;;; +1204C;CUNEIFORM SIGN BI TIMES IGI GUNU;Lo;0;L;;;;;N;;;;; +1204D;CUNEIFORM SIGN BU;Lo;0;L;;;;;N;;;;; +1204E;CUNEIFORM SIGN BU OVER BU AB;Lo;0;L;;;;;N;;;;; +1204F;CUNEIFORM SIGN BU OVER BU UN;Lo;0;L;;;;;N;;;;; +12050;CUNEIFORM SIGN BU CROSSING BU;Lo;0;L;;;;;N;;;;; +12051;CUNEIFORM SIGN BULUG;Lo;0;L;;;;;N;;;;; +12052;CUNEIFORM SIGN BULUG OVER BULUG;Lo;0;L;;;;;N;;;;; +12053;CUNEIFORM SIGN BUR;Lo;0;L;;;;;N;;;;; +12054;CUNEIFORM SIGN BUR2;Lo;0;L;;;;;N;;;;; +12055;CUNEIFORM SIGN DA;Lo;0;L;;;;;N;;;;; +12056;CUNEIFORM SIGN DAG;Lo;0;L;;;;;N;;;;; +12057;CUNEIFORM SIGN DAG KISIM5 TIMES A PLUS MASH;Lo;0;L;;;;;N;;;;; +12058;CUNEIFORM SIGN DAG KISIM5 TIMES AMAR;Lo;0;L;;;;;N;;;;; +12059;CUNEIFORM SIGN DAG KISIM5 TIMES BALAG;Lo;0;L;;;;;N;;;;; +1205A;CUNEIFORM SIGN DAG KISIM5 TIMES BI;Lo;0;L;;;;;N;;;;; +1205B;CUNEIFORM SIGN DAG KISIM5 TIMES GA;Lo;0;L;;;;;N;;;;; +1205C;CUNEIFORM SIGN DAG KISIM5 TIMES GA PLUS MASH;Lo;0;L;;;;;N;;;;; +1205D;CUNEIFORM SIGN DAG KISIM5 TIMES GI;Lo;0;L;;;;;N;;;;; +1205E;CUNEIFORM SIGN DAG KISIM5 TIMES GIR2;Lo;0;L;;;;;N;;;;; +1205F;CUNEIFORM SIGN DAG KISIM5 TIMES GUD;Lo;0;L;;;;;N;;;;; +12060;CUNEIFORM SIGN DAG KISIM5 TIMES HA;Lo;0;L;;;;;N;;;;; +12061;CUNEIFORM SIGN DAG KISIM5 TIMES IR;Lo;0;L;;;;;N;;;;; +12062;CUNEIFORM SIGN DAG KISIM5 TIMES IR PLUS LU;Lo;0;L;;;;;N;;;;; +12063;CUNEIFORM SIGN DAG KISIM5 TIMES KAK;Lo;0;L;;;;;N;;;;; +12064;CUNEIFORM SIGN DAG KISIM5 TIMES LA;Lo;0;L;;;;;N;;;;; +12065;CUNEIFORM SIGN DAG KISIM5 TIMES LU;Lo;0;L;;;;;N;;;;; +12066;CUNEIFORM SIGN DAG KISIM5 TIMES LU PLUS MASH2;Lo;0;L;;;;;N;;;;; +12067;CUNEIFORM SIGN DAG KISIM5 TIMES LUM;Lo;0;L;;;;;N;;;;; +12068;CUNEIFORM SIGN DAG KISIM5 TIMES NE;Lo;0;L;;;;;N;;;;; +12069;CUNEIFORM SIGN DAG KISIM5 TIMES PAP PLUS PAP;Lo;0;L;;;;;N;;;;; +1206A;CUNEIFORM SIGN DAG KISIM5 TIMES SI;Lo;0;L;;;;;N;;;;; +1206B;CUNEIFORM SIGN DAG KISIM5 TIMES TAK4;Lo;0;L;;;;;N;;;;; +1206C;CUNEIFORM SIGN DAG KISIM5 TIMES U2 PLUS GIR2;Lo;0;L;;;;;N;;;;; +1206D;CUNEIFORM SIGN DAG KISIM5 TIMES USH;Lo;0;L;;;;;N;;;;; +1206E;CUNEIFORM SIGN DAM;Lo;0;L;;;;;N;;;;; +1206F;CUNEIFORM SIGN DAR;Lo;0;L;;;;;N;;;;; +12070;CUNEIFORM SIGN DARA3;Lo;0;L;;;;;N;;;;; +12071;CUNEIFORM SIGN DARA4;Lo;0;L;;;;;N;;;;; +12072;CUNEIFORM SIGN DI;Lo;0;L;;;;;N;;;;; +12073;CUNEIFORM SIGN DIB;Lo;0;L;;;;;N;;;;; +12074;CUNEIFORM SIGN DIM;Lo;0;L;;;;;N;;;;; +12075;CUNEIFORM SIGN DIM TIMES SHE;Lo;0;L;;;;;N;;;;; +12076;CUNEIFORM SIGN DIM2;Lo;0;L;;;;;N;;;;; +12077;CUNEIFORM SIGN DIN;Lo;0;L;;;;;N;;;;; +12078;CUNEIFORM SIGN DIN KASKAL U GUNU DISH;Lo;0;L;;;;;N;;;;; +12079;CUNEIFORM SIGN DISH;Lo;0;L;;;;;N;;;;; +1207A;CUNEIFORM SIGN DU;Lo;0;L;;;;;N;;;;; +1207B;CUNEIFORM SIGN DU OVER DU;Lo;0;L;;;;;N;;;;; +1207C;CUNEIFORM SIGN DU GUNU;Lo;0;L;;;;;N;;;;; +1207D;CUNEIFORM SIGN DU SHESHIG;Lo;0;L;;;;;N;;;;; +1207E;CUNEIFORM SIGN DUB;Lo;0;L;;;;;N;;;;; +1207F;CUNEIFORM SIGN DUB TIMES ESH2;Lo;0;L;;;;;N;;;;; +12080;CUNEIFORM SIGN DUB2;Lo;0;L;;;;;N;;;;; +12081;CUNEIFORM SIGN DUG;Lo;0;L;;;;;N;;;;; +12082;CUNEIFORM SIGN DUGUD;Lo;0;L;;;;;N;;;;; +12083;CUNEIFORM SIGN DUH;Lo;0;L;;;;;N;;;;; +12084;CUNEIFORM SIGN DUN;Lo;0;L;;;;;N;;;;; +12085;CUNEIFORM SIGN DUN3;Lo;0;L;;;;;N;;;;; +12086;CUNEIFORM SIGN DUN3 GUNU;Lo;0;L;;;;;N;;;;; +12087;CUNEIFORM SIGN DUN3 GUNU GUNU;Lo;0;L;;;;;N;;;;; +12088;CUNEIFORM SIGN DUN4;Lo;0;L;;;;;N;;;;; +12089;CUNEIFORM SIGN DUR2;Lo;0;L;;;;;N;;;;; +1208A;CUNEIFORM SIGN E;Lo;0;L;;;;;N;;;;; +1208B;CUNEIFORM SIGN E TIMES PAP;Lo;0;L;;;;;N;;;;; +1208C;CUNEIFORM SIGN E OVER E NUN OVER NUN;Lo;0;L;;;;;N;;;;; +1208D;CUNEIFORM SIGN E2;Lo;0;L;;;;;N;;;;; +1208E;CUNEIFORM SIGN E2 TIMES A PLUS HA PLUS DA;Lo;0;L;;;;;N;;;;; +1208F;CUNEIFORM SIGN E2 TIMES GAR;Lo;0;L;;;;;N;;;;; +12090;CUNEIFORM SIGN E2 TIMES MI;Lo;0;L;;;;;N;;;;; +12091;CUNEIFORM SIGN E2 TIMES SAL;Lo;0;L;;;;;N;;;;; +12092;CUNEIFORM SIGN E2 TIMES SHE;Lo;0;L;;;;;N;;;;; +12093;CUNEIFORM SIGN E2 TIMES U;Lo;0;L;;;;;N;;;;; +12094;CUNEIFORM SIGN EDIN;Lo;0;L;;;;;N;;;;; +12095;CUNEIFORM SIGN EGIR;Lo;0;L;;;;;N;;;;; +12096;CUNEIFORM SIGN EL;Lo;0;L;;;;;N;;;;; +12097;CUNEIFORM SIGN EN;Lo;0;L;;;;;N;;;;; +12098;CUNEIFORM SIGN EN TIMES GAN2;Lo;0;L;;;;;N;;;;; +12099;CUNEIFORM SIGN EN TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +1209A;CUNEIFORM SIGN EN TIMES ME;Lo;0;L;;;;;N;;;;; +1209B;CUNEIFORM SIGN EN CROSSING EN;Lo;0;L;;;;;N;;;;; +1209C;CUNEIFORM SIGN EN OPPOSING EN;Lo;0;L;;;;;N;;;;; +1209D;CUNEIFORM SIGN EN SQUARED;Lo;0;L;;;;;N;;;;; +1209E;CUNEIFORM SIGN EREN;Lo;0;L;;;;;N;;;;; +1209F;CUNEIFORM SIGN ERIN2;Lo;0;L;;;;;N;;;;; +120A0;CUNEIFORM SIGN ESH2;Lo;0;L;;;;;N;;;;; +120A1;CUNEIFORM SIGN EZEN;Lo;0;L;;;;;N;;;;; +120A2;CUNEIFORM SIGN EZEN TIMES A;Lo;0;L;;;;;N;;;;; +120A3;CUNEIFORM SIGN EZEN TIMES A PLUS LAL;Lo;0;L;;;;;N;;;;; +120A4;CUNEIFORM SIGN EZEN TIMES A PLUS LAL TIMES LAL;Lo;0;L;;;;;N;;;;; +120A5;CUNEIFORM SIGN EZEN TIMES AN;Lo;0;L;;;;;N;;;;; +120A6;CUNEIFORM SIGN EZEN TIMES BAD;Lo;0;L;;;;;N;;;;; +120A7;CUNEIFORM SIGN EZEN TIMES DUN3 GUNU;Lo;0;L;;;;;N;;;;; +120A8;CUNEIFORM SIGN EZEN TIMES DUN3 GUNU GUNU;Lo;0;L;;;;;N;;;;; +120A9;CUNEIFORM SIGN EZEN TIMES HA;Lo;0;L;;;;;N;;;;; +120AA;CUNEIFORM SIGN EZEN TIMES HA GUNU;Lo;0;L;;;;;N;;;;; +120AB;CUNEIFORM SIGN EZEN TIMES IGI GUNU;Lo;0;L;;;;;N;;;;; +120AC;CUNEIFORM SIGN EZEN TIMES KASKAL;Lo;0;L;;;;;N;;;;; +120AD;CUNEIFORM SIGN EZEN TIMES KASKAL SQUARED;Lo;0;L;;;;;N;;;;; +120AE;CUNEIFORM SIGN EZEN TIMES KU3;Lo;0;L;;;;;N;;;;; +120AF;CUNEIFORM SIGN EZEN TIMES LA;Lo;0;L;;;;;N;;;;; +120B0;CUNEIFORM SIGN EZEN TIMES LAL TIMES LAL;Lo;0;L;;;;;N;;;;; +120B1;CUNEIFORM SIGN EZEN TIMES LI;Lo;0;L;;;;;N;;;;; +120B2;CUNEIFORM SIGN EZEN TIMES LU;Lo;0;L;;;;;N;;;;; +120B3;CUNEIFORM SIGN EZEN TIMES U2;Lo;0;L;;;;;N;;;;; +120B4;CUNEIFORM SIGN EZEN TIMES UD;Lo;0;L;;;;;N;;;;; +120B5;CUNEIFORM SIGN GA;Lo;0;L;;;;;N;;;;; +120B6;CUNEIFORM SIGN GA GUNU;Lo;0;L;;;;;N;;;;; +120B7;CUNEIFORM SIGN GA2;Lo;0;L;;;;;N;;;;; +120B8;CUNEIFORM SIGN GA2 TIMES A PLUS DA PLUS HA;Lo;0;L;;;;;N;;;;; +120B9;CUNEIFORM SIGN GA2 TIMES A PLUS HA;Lo;0;L;;;;;N;;;;; +120BA;CUNEIFORM SIGN GA2 TIMES A PLUS IGI;Lo;0;L;;;;;N;;;;; +120BB;CUNEIFORM SIGN GA2 TIMES AB2 TENU PLUS TAB;Lo;0;L;;;;;N;;;;; +120BC;CUNEIFORM SIGN GA2 TIMES AN;Lo;0;L;;;;;N;;;;; +120BD;CUNEIFORM SIGN GA2 TIMES ASH;Lo;0;L;;;;;N;;;;; +120BE;CUNEIFORM SIGN GA2 TIMES ASH2 PLUS GAL;Lo;0;L;;;;;N;;;;; +120BF;CUNEIFORM SIGN GA2 TIMES BAD;Lo;0;L;;;;;N;;;;; +120C0;CUNEIFORM SIGN GA2 TIMES BAR PLUS RA;Lo;0;L;;;;;N;;;;; +120C1;CUNEIFORM SIGN GA2 TIMES BUR;Lo;0;L;;;;;N;;;;; +120C2;CUNEIFORM SIGN GA2 TIMES BUR PLUS RA;Lo;0;L;;;;;N;;;;; +120C3;CUNEIFORM SIGN GA2 TIMES DA;Lo;0;L;;;;;N;;;;; +120C4;CUNEIFORM SIGN GA2 TIMES DI;Lo;0;L;;;;;N;;;;; +120C5;CUNEIFORM SIGN GA2 TIMES DIM TIMES SHE;Lo;0;L;;;;;N;;;;; +120C6;CUNEIFORM SIGN GA2 TIMES DUB;Lo;0;L;;;;;N;;;;; +120C7;CUNEIFORM SIGN GA2 TIMES EL;Lo;0;L;;;;;N;;;;; +120C8;CUNEIFORM SIGN GA2 TIMES EL PLUS LA;Lo;0;L;;;;;N;;;;; +120C9;CUNEIFORM SIGN GA2 TIMES EN;Lo;0;L;;;;;N;;;;; +120CA;CUNEIFORM SIGN GA2 TIMES EN TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +120CB;CUNEIFORM SIGN GA2 TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +120CC;CUNEIFORM SIGN GA2 TIMES GAR;Lo;0;L;;;;;N;;;;; +120CD;CUNEIFORM SIGN GA2 TIMES GI;Lo;0;L;;;;;N;;;;; +120CE;CUNEIFORM SIGN GA2 TIMES GI4;Lo;0;L;;;;;N;;;;; +120CF;CUNEIFORM SIGN GA2 TIMES GI4 PLUS A;Lo;0;L;;;;;N;;;;; +120D0;CUNEIFORM SIGN GA2 TIMES GIR2 PLUS SU;Lo;0;L;;;;;N;;;;; +120D1;CUNEIFORM SIGN GA2 TIMES HA PLUS LU PLUS ESH2;Lo;0;L;;;;;N;;;;; +120D2;CUNEIFORM SIGN GA2 TIMES HAL;Lo;0;L;;;;;N;;;;; +120D3;CUNEIFORM SIGN GA2 TIMES HAL PLUS LA;Lo;0;L;;;;;N;;;;; +120D4;CUNEIFORM SIGN GA2 TIMES HI PLUS LI;Lo;0;L;;;;;N;;;;; +120D5;CUNEIFORM SIGN GA2 TIMES HUB2;Lo;0;L;;;;;N;;;;; +120D6;CUNEIFORM SIGN GA2 TIMES IGI GUNU;Lo;0;L;;;;;N;;;;; +120D7;CUNEIFORM SIGN GA2 TIMES ISH PLUS HU PLUS ASH;Lo;0;L;;;;;N;;;;; +120D8;CUNEIFORM SIGN GA2 TIMES KAK;Lo;0;L;;;;;N;;;;; +120D9;CUNEIFORM SIGN GA2 TIMES KASKAL;Lo;0;L;;;;;N;;;;; +120DA;CUNEIFORM SIGN GA2 TIMES KID;Lo;0;L;;;;;N;;;;; +120DB;CUNEIFORM SIGN GA2 TIMES KID PLUS LAL;Lo;0;L;;;;;N;;;;; +120DC;CUNEIFORM SIGN GA2 TIMES KU3 PLUS AN;Lo;0;L;;;;;N;;;;; +120DD;CUNEIFORM SIGN GA2 TIMES LA;Lo;0;L;;;;;N;;;;; +120DE;CUNEIFORM SIGN GA2 TIMES ME PLUS EN;Lo;0;L;;;;;N;;;;; +120DF;CUNEIFORM SIGN GA2 TIMES MI;Lo;0;L;;;;;N;;;;; +120E0;CUNEIFORM SIGN GA2 TIMES NUN;Lo;0;L;;;;;N;;;;; +120E1;CUNEIFORM SIGN GA2 TIMES NUN OVER NUN;Lo;0;L;;;;;N;;;;; +120E2;CUNEIFORM SIGN GA2 TIMES PA;Lo;0;L;;;;;N;;;;; +120E3;CUNEIFORM SIGN GA2 TIMES SAL;Lo;0;L;;;;;N;;;;; +120E4;CUNEIFORM SIGN GA2 TIMES SAR;Lo;0;L;;;;;N;;;;; +120E5;CUNEIFORM SIGN GA2 TIMES SHE;Lo;0;L;;;;;N;;;;; +120E6;CUNEIFORM SIGN GA2 TIMES SHE PLUS TUR;Lo;0;L;;;;;N;;;;; +120E7;CUNEIFORM SIGN GA2 TIMES SHID;Lo;0;L;;;;;N;;;;; +120E8;CUNEIFORM SIGN GA2 TIMES SUM;Lo;0;L;;;;;N;;;;; +120E9;CUNEIFORM SIGN GA2 TIMES TAK4;Lo;0;L;;;;;N;;;;; +120EA;CUNEIFORM SIGN GA2 TIMES U;Lo;0;L;;;;;N;;;;; +120EB;CUNEIFORM SIGN GA2 TIMES UD;Lo;0;L;;;;;N;;;;; +120EC;CUNEIFORM SIGN GA2 TIMES UD PLUS DU;Lo;0;L;;;;;N;;;;; +120ED;CUNEIFORM SIGN GA2 OVER GA2;Lo;0;L;;;;;N;;;;; +120EE;CUNEIFORM SIGN GABA;Lo;0;L;;;;;N;;;;; +120EF;CUNEIFORM SIGN GABA CROSSING GABA;Lo;0;L;;;;;N;;;;; +120F0;CUNEIFORM SIGN GAD;Lo;0;L;;;;;N;;;;; +120F1;CUNEIFORM SIGN GAD OVER GAD GAR OVER GAR;Lo;0;L;;;;;N;;;;; +120F2;CUNEIFORM SIGN GAL;Lo;0;L;;;;;N;;;;; +120F3;CUNEIFORM SIGN GAL GAD OVER GAD GAR OVER GAR;Lo;0;L;;;;;N;;;;; +120F4;CUNEIFORM SIGN GALAM;Lo;0;L;;;;;N;;;;; +120F5;CUNEIFORM SIGN GAM;Lo;0;L;;;;;N;;;;; +120F6;CUNEIFORM SIGN GAN;Lo;0;L;;;;;N;;;;; +120F7;CUNEIFORM SIGN GAN2;Lo;0;L;;;;;N;;;;; +120F8;CUNEIFORM SIGN GAN2 TENU;Lo;0;L;;;;;N;;;;; +120F9;CUNEIFORM SIGN GAN2 OVER GAN2;Lo;0;L;;;;;N;;;;; +120FA;CUNEIFORM SIGN GAN2 CROSSING GAN2;Lo;0;L;;;;;N;;;;; +120FB;CUNEIFORM SIGN GAR;Lo;0;L;;;;;N;;;;; +120FC;CUNEIFORM SIGN GAR3;Lo;0;L;;;;;N;;;;; +120FD;CUNEIFORM SIGN GASHAN;Lo;0;L;;;;;N;;;;; +120FE;CUNEIFORM SIGN GESHTIN;Lo;0;L;;;;;N;;;;; +120FF;CUNEIFORM SIGN GESHTIN TIMES KUR;Lo;0;L;;;;;N;;;;; +12100;CUNEIFORM SIGN GI;Lo;0;L;;;;;N;;;;; +12101;CUNEIFORM SIGN GI TIMES E;Lo;0;L;;;;;N;;;;; +12102;CUNEIFORM SIGN GI TIMES U;Lo;0;L;;;;;N;;;;; +12103;CUNEIFORM SIGN GI CROSSING GI;Lo;0;L;;;;;N;;;;; +12104;CUNEIFORM SIGN GI4;Lo;0;L;;;;;N;;;;; +12105;CUNEIFORM SIGN GI4 OVER GI4;Lo;0;L;;;;;N;;;;; +12106;CUNEIFORM SIGN GI4 CROSSING GI4;Lo;0;L;;;;;N;;;;; +12107;CUNEIFORM SIGN GIDIM;Lo;0;L;;;;;N;;;;; +12108;CUNEIFORM SIGN GIR2;Lo;0;L;;;;;N;;;;; +12109;CUNEIFORM SIGN GIR2 GUNU;Lo;0;L;;;;;N;;;;; +1210A;CUNEIFORM SIGN GIR3;Lo;0;L;;;;;N;;;;; +1210B;CUNEIFORM SIGN GIR3 TIMES A PLUS IGI;Lo;0;L;;;;;N;;;;; +1210C;CUNEIFORM SIGN GIR3 TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +1210D;CUNEIFORM SIGN GIR3 TIMES IGI;Lo;0;L;;;;;N;;;;; +1210E;CUNEIFORM SIGN GIR3 TIMES LU PLUS IGI;Lo;0;L;;;;;N;;;;; +1210F;CUNEIFORM SIGN GIR3 TIMES PA;Lo;0;L;;;;;N;;;;; +12110;CUNEIFORM SIGN GISAL;Lo;0;L;;;;;N;;;;; +12111;CUNEIFORM SIGN GISH;Lo;0;L;;;;;N;;;;; +12112;CUNEIFORM SIGN GISH CROSSING GISH;Lo;0;L;;;;;N;;;;; +12113;CUNEIFORM SIGN GISH TIMES BAD;Lo;0;L;;;;;N;;;;; +12114;CUNEIFORM SIGN GISH TIMES TAK4;Lo;0;L;;;;;N;;;;; +12115;CUNEIFORM SIGN GISH TENU;Lo;0;L;;;;;N;;;;; +12116;CUNEIFORM SIGN GU;Lo;0;L;;;;;N;;;;; +12117;CUNEIFORM SIGN GU CROSSING GU;Lo;0;L;;;;;N;;;;; +12118;CUNEIFORM SIGN GU2;Lo;0;L;;;;;N;;;;; +12119;CUNEIFORM SIGN GU2 TIMES KAK;Lo;0;L;;;;;N;;;;; +1211A;CUNEIFORM SIGN GU2 TIMES KAK TIMES IGI GUNU;Lo;0;L;;;;;N;;;;; +1211B;CUNEIFORM SIGN GU2 TIMES NUN;Lo;0;L;;;;;N;;;;; +1211C;CUNEIFORM SIGN GU2 TIMES SAL PLUS TUG2;Lo;0;L;;;;;N;;;;; +1211D;CUNEIFORM SIGN GU2 GUNU;Lo;0;L;;;;;N;;;;; +1211E;CUNEIFORM SIGN GUD;Lo;0;L;;;;;N;;;;; +1211F;CUNEIFORM SIGN GUD TIMES A PLUS KUR;Lo;0;L;;;;;N;;;;; +12120;CUNEIFORM SIGN GUD TIMES KUR;Lo;0;L;;;;;N;;;;; +12121;CUNEIFORM SIGN GUD OVER GUD LUGAL;Lo;0;L;;;;;N;;;;; +12122;CUNEIFORM SIGN GUL;Lo;0;L;;;;;N;;;;; +12123;CUNEIFORM SIGN GUM;Lo;0;L;;;;;N;;;;; +12124;CUNEIFORM SIGN GUM TIMES SHE;Lo;0;L;;;;;N;;;;; +12125;CUNEIFORM SIGN GUR;Lo;0;L;;;;;N;;;;; +12126;CUNEIFORM SIGN GUR7;Lo;0;L;;;;;N;;;;; +12127;CUNEIFORM SIGN GURUN;Lo;0;L;;;;;N;;;;; +12128;CUNEIFORM SIGN GURUSH;Lo;0;L;;;;;N;;;;; +12129;CUNEIFORM SIGN HA;Lo;0;L;;;;;N;;;;; +1212A;CUNEIFORM SIGN HA TENU;Lo;0;L;;;;;N;;;;; +1212B;CUNEIFORM SIGN HA GUNU;Lo;0;L;;;;;N;;;;; +1212C;CUNEIFORM SIGN HAL;Lo;0;L;;;;;N;;;;; +1212D;CUNEIFORM SIGN HI;Lo;0;L;;;;;N;;;;; +1212E;CUNEIFORM SIGN HI TIMES ASH;Lo;0;L;;;;;N;;;;; +1212F;CUNEIFORM SIGN HI TIMES ASH2;Lo;0;L;;;;;N;;;;; +12130;CUNEIFORM SIGN HI TIMES BAD;Lo;0;L;;;;;N;;;;; +12131;CUNEIFORM SIGN HI TIMES DISH;Lo;0;L;;;;;N;;;;; +12132;CUNEIFORM SIGN HI TIMES GAD;Lo;0;L;;;;;N;;;;; +12133;CUNEIFORM SIGN HI TIMES KIN;Lo;0;L;;;;;N;;;;; +12134;CUNEIFORM SIGN HI TIMES NUN;Lo;0;L;;;;;N;;;;; +12135;CUNEIFORM SIGN HI TIMES SHE;Lo;0;L;;;;;N;;;;; +12136;CUNEIFORM SIGN HI TIMES U;Lo;0;L;;;;;N;;;;; +12137;CUNEIFORM SIGN HU;Lo;0;L;;;;;N;;;;; +12138;CUNEIFORM SIGN HUB2;Lo;0;L;;;;;N;;;;; +12139;CUNEIFORM SIGN HUB2 TIMES AN;Lo;0;L;;;;;N;;;;; +1213A;CUNEIFORM SIGN HUB2 TIMES HAL;Lo;0;L;;;;;N;;;;; +1213B;CUNEIFORM SIGN HUB2 TIMES KASKAL;Lo;0;L;;;;;N;;;;; +1213C;CUNEIFORM SIGN HUB2 TIMES LISH;Lo;0;L;;;;;N;;;;; +1213D;CUNEIFORM SIGN HUB2 TIMES UD;Lo;0;L;;;;;N;;;;; +1213E;CUNEIFORM SIGN HUL2;Lo;0;L;;;;;N;;;;; +1213F;CUNEIFORM SIGN I;Lo;0;L;;;;;N;;;;; +12140;CUNEIFORM SIGN I A;Lo;0;L;;;;;N;;;;; +12141;CUNEIFORM SIGN IB;Lo;0;L;;;;;N;;;;; +12142;CUNEIFORM SIGN IDIM;Lo;0;L;;;;;N;;;;; +12143;CUNEIFORM SIGN IDIM OVER IDIM BUR;Lo;0;L;;;;;N;;;;; +12144;CUNEIFORM SIGN IDIM OVER IDIM SQUARED;Lo;0;L;;;;;N;;;;; +12145;CUNEIFORM SIGN IG;Lo;0;L;;;;;N;;;;; +12146;CUNEIFORM SIGN IGI;Lo;0;L;;;;;N;;;;; +12147;CUNEIFORM SIGN IGI DIB;Lo;0;L;;;;;N;;;;; +12148;CUNEIFORM SIGN IGI RI;Lo;0;L;;;;;N;;;;; +12149;CUNEIFORM SIGN IGI OVER IGI SHIR OVER SHIR UD OVER UD;Lo;0;L;;;;;N;;;;; +1214A;CUNEIFORM SIGN IGI GUNU;Lo;0;L;;;;;N;;;;; +1214B;CUNEIFORM SIGN IL;Lo;0;L;;;;;N;;;;; +1214C;CUNEIFORM SIGN IL TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +1214D;CUNEIFORM SIGN IL2;Lo;0;L;;;;;N;;;;; +1214E;CUNEIFORM SIGN IM;Lo;0;L;;;;;N;;;;; +1214F;CUNEIFORM SIGN IM TIMES TAK4;Lo;0;L;;;;;N;;;;; +12150;CUNEIFORM SIGN IM CROSSING IM;Lo;0;L;;;;;N;;;;; +12151;CUNEIFORM SIGN IM OPPOSING IM;Lo;0;L;;;;;N;;;;; +12152;CUNEIFORM SIGN IM SQUARED;Lo;0;L;;;;;N;;;;; +12153;CUNEIFORM SIGN IMIN;Lo;0;L;;;;;N;;;;; +12154;CUNEIFORM SIGN IN;Lo;0;L;;;;;N;;;;; +12155;CUNEIFORM SIGN IR;Lo;0;L;;;;;N;;;;; +12156;CUNEIFORM SIGN ISH;Lo;0;L;;;;;N;;;;; +12157;CUNEIFORM SIGN KA;Lo;0;L;;;;;N;;;;; +12158;CUNEIFORM SIGN KA TIMES A;Lo;0;L;;;;;N;;;;; +12159;CUNEIFORM SIGN KA TIMES AD;Lo;0;L;;;;;N;;;;; +1215A;CUNEIFORM SIGN KA TIMES AD PLUS KU3;Lo;0;L;;;;;N;;;;; +1215B;CUNEIFORM SIGN KA TIMES ASH2;Lo;0;L;;;;;N;;;;; +1215C;CUNEIFORM SIGN KA TIMES BAD;Lo;0;L;;;;;N;;;;; +1215D;CUNEIFORM SIGN KA TIMES BALAG;Lo;0;L;;;;;N;;;;; +1215E;CUNEIFORM SIGN KA TIMES BAR;Lo;0;L;;;;;N;;;;; +1215F;CUNEIFORM SIGN KA TIMES BI;Lo;0;L;;;;;N;;;;; +12160;CUNEIFORM SIGN KA TIMES ERIN2;Lo;0;L;;;;;N;;;;; +12161;CUNEIFORM SIGN KA TIMES ESH2;Lo;0;L;;;;;N;;;;; +12162;CUNEIFORM SIGN KA TIMES GA;Lo;0;L;;;;;N;;;;; +12163;CUNEIFORM SIGN KA TIMES GAL;Lo;0;L;;;;;N;;;;; +12164;CUNEIFORM SIGN KA TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +12165;CUNEIFORM SIGN KA TIMES GAR;Lo;0;L;;;;;N;;;;; +12166;CUNEIFORM SIGN KA TIMES GAR PLUS SHA3 PLUS A;Lo;0;L;;;;;N;;;;; +12167;CUNEIFORM SIGN KA TIMES GI;Lo;0;L;;;;;N;;;;; +12168;CUNEIFORM SIGN KA TIMES GIR2;Lo;0;L;;;;;N;;;;; +12169;CUNEIFORM SIGN KA TIMES GISH PLUS SAR;Lo;0;L;;;;;N;;;;; +1216A;CUNEIFORM SIGN KA TIMES GISH CROSSING GISH;Lo;0;L;;;;;N;;;;; +1216B;CUNEIFORM SIGN KA TIMES GU;Lo;0;L;;;;;N;;;;; +1216C;CUNEIFORM SIGN KA TIMES GUR7;Lo;0;L;;;;;N;;;;; +1216D;CUNEIFORM SIGN KA TIMES IGI;Lo;0;L;;;;;N;;;;; +1216E;CUNEIFORM SIGN KA TIMES IM;Lo;0;L;;;;;N;;;;; +1216F;CUNEIFORM SIGN KA TIMES KAK;Lo;0;L;;;;;N;;;;; +12170;CUNEIFORM SIGN KA TIMES KI;Lo;0;L;;;;;N;;;;; +12171;CUNEIFORM SIGN KA TIMES KID;Lo;0;L;;;;;N;;;;; +12172;CUNEIFORM SIGN KA TIMES LI;Lo;0;L;;;;;N;;;;; +12173;CUNEIFORM SIGN KA TIMES LU;Lo;0;L;;;;;N;;;;; +12174;CUNEIFORM SIGN KA TIMES ME;Lo;0;L;;;;;N;;;;; +12175;CUNEIFORM SIGN KA TIMES ME PLUS DU;Lo;0;L;;;;;N;;;;; +12176;CUNEIFORM SIGN KA TIMES ME PLUS GI;Lo;0;L;;;;;N;;;;; +12177;CUNEIFORM SIGN KA TIMES ME PLUS TE;Lo;0;L;;;;;N;;;;; +12178;CUNEIFORM SIGN KA TIMES MI;Lo;0;L;;;;;N;;;;; +12179;CUNEIFORM SIGN KA TIMES MI PLUS NUNUZ;Lo;0;L;;;;;N;;;;; +1217A;CUNEIFORM SIGN KA TIMES NE;Lo;0;L;;;;;N;;;;; +1217B;CUNEIFORM SIGN KA TIMES NUN;Lo;0;L;;;;;N;;;;; +1217C;CUNEIFORM SIGN KA TIMES PI;Lo;0;L;;;;;N;;;;; +1217D;CUNEIFORM SIGN KA TIMES RU;Lo;0;L;;;;;N;;;;; +1217E;CUNEIFORM SIGN KA TIMES SA;Lo;0;L;;;;;N;;;;; +1217F;CUNEIFORM SIGN KA TIMES SAR;Lo;0;L;;;;;N;;;;; +12180;CUNEIFORM SIGN KA TIMES SHA;Lo;0;L;;;;;N;;;;; +12181;CUNEIFORM SIGN KA TIMES SHE;Lo;0;L;;;;;N;;;;; +12182;CUNEIFORM SIGN KA TIMES SHID;Lo;0;L;;;;;N;;;;; +12183;CUNEIFORM SIGN KA TIMES SHU;Lo;0;L;;;;;N;;;;; +12184;CUNEIFORM SIGN KA TIMES SIG;Lo;0;L;;;;;N;;;;; +12185;CUNEIFORM SIGN KA TIMES SUHUR;Lo;0;L;;;;;N;;;;; +12186;CUNEIFORM SIGN KA TIMES TAR;Lo;0;L;;;;;N;;;;; +12187;CUNEIFORM SIGN KA TIMES U;Lo;0;L;;;;;N;;;;; +12188;CUNEIFORM SIGN KA TIMES U2;Lo;0;L;;;;;N;;;;; +12189;CUNEIFORM SIGN KA TIMES UD;Lo;0;L;;;;;N;;;;; +1218A;CUNEIFORM SIGN KA TIMES UMUM TIMES PA;Lo;0;L;;;;;N;;;;; +1218B;CUNEIFORM SIGN KA TIMES USH;Lo;0;L;;;;;N;;;;; +1218C;CUNEIFORM SIGN KA TIMES ZI;Lo;0;L;;;;;N;;;;; +1218D;CUNEIFORM SIGN KA2;Lo;0;L;;;;;N;;;;; +1218E;CUNEIFORM SIGN KA2 CROSSING KA2;Lo;0;L;;;;;N;;;;; +1218F;CUNEIFORM SIGN KAB;Lo;0;L;;;;;N;;;;; +12190;CUNEIFORM SIGN KAD2;Lo;0;L;;;;;N;;;;; +12191;CUNEIFORM SIGN KAD3;Lo;0;L;;;;;N;;;;; +12192;CUNEIFORM SIGN KAD4;Lo;0;L;;;;;N;;;;; +12193;CUNEIFORM SIGN KAD5;Lo;0;L;;;;;N;;;;; +12194;CUNEIFORM SIGN KAD5 OVER KAD5;Lo;0;L;;;;;N;;;;; +12195;CUNEIFORM SIGN KAK;Lo;0;L;;;;;N;;;;; +12196;CUNEIFORM SIGN KAK TIMES IGI GUNU;Lo;0;L;;;;;N;;;;; +12197;CUNEIFORM SIGN KAL;Lo;0;L;;;;;N;;;;; +12198;CUNEIFORM SIGN KAL TIMES BAD;Lo;0;L;;;;;N;;;;; +12199;CUNEIFORM SIGN KAL CROSSING KAL;Lo;0;L;;;;;N;;;;; +1219A;CUNEIFORM SIGN KAM2;Lo;0;L;;;;;N;;;;; +1219B;CUNEIFORM SIGN KAM4;Lo;0;L;;;;;N;;;;; +1219C;CUNEIFORM SIGN KASKAL;Lo;0;L;;;;;N;;;;; +1219D;CUNEIFORM SIGN KASKAL LAGAB TIMES U OVER LAGAB TIMES U;Lo;0;L;;;;;N;;;;; +1219E;CUNEIFORM SIGN KASKAL OVER KASKAL LAGAB TIMES U OVER LAGAB TIMES U;Lo;0;L;;;;;N;;;;; +1219F;CUNEIFORM SIGN KESH2;Lo;0;L;;;;;N;;;;; +121A0;CUNEIFORM SIGN KI;Lo;0;L;;;;;N;;;;; +121A1;CUNEIFORM SIGN KI TIMES BAD;Lo;0;L;;;;;N;;;;; +121A2;CUNEIFORM SIGN KI TIMES U;Lo;0;L;;;;;N;;;;; +121A3;CUNEIFORM SIGN KI TIMES UD;Lo;0;L;;;;;N;;;;; +121A4;CUNEIFORM SIGN KID;Lo;0;L;;;;;N;;;;; +121A5;CUNEIFORM SIGN KIN;Lo;0;L;;;;;N;;;;; +121A6;CUNEIFORM SIGN KISAL;Lo;0;L;;;;;N;;;;; +121A7;CUNEIFORM SIGN KISH;Lo;0;L;;;;;N;;;;; +121A8;CUNEIFORM SIGN KISIM5;Lo;0;L;;;;;N;;;;; +121A9;CUNEIFORM SIGN KISIM5 OVER KISIM5;Lo;0;L;;;;;N;;;;; +121AA;CUNEIFORM SIGN KU;Lo;0;L;;;;;N;;;;; +121AB;CUNEIFORM SIGN KU OVER HI TIMES ASH2 KU OVER HI TIMES ASH2;Lo;0;L;;;;;N;;;;; +121AC;CUNEIFORM SIGN KU3;Lo;0;L;;;;;N;;;;; +121AD;CUNEIFORM SIGN KU4;Lo;0;L;;;;;N;;;;; +121AE;CUNEIFORM SIGN KU4 VARIANT FORM;Lo;0;L;;;;;N;;;;; +121AF;CUNEIFORM SIGN KU7;Lo;0;L;;;;;N;;;;; +121B0;CUNEIFORM SIGN KUL;Lo;0;L;;;;;N;;;;; +121B1;CUNEIFORM SIGN KUL GUNU;Lo;0;L;;;;;N;;;;; +121B2;CUNEIFORM SIGN KUN;Lo;0;L;;;;;N;;;;; +121B3;CUNEIFORM SIGN KUR;Lo;0;L;;;;;N;;;;; +121B4;CUNEIFORM SIGN KUR OPPOSING KUR;Lo;0;L;;;;;N;;;;; +121B5;CUNEIFORM SIGN KUSHU2;Lo;0;L;;;;;N;;;;; +121B6;CUNEIFORM SIGN KWU318;Lo;0;L;;;;;N;;;;; +121B7;CUNEIFORM SIGN LA;Lo;0;L;;;;;N;;;;; +121B8;CUNEIFORM SIGN LAGAB;Lo;0;L;;;;;N;;;;; +121B9;CUNEIFORM SIGN LAGAB TIMES A;Lo;0;L;;;;;N;;;;; +121BA;CUNEIFORM SIGN LAGAB TIMES A PLUS DA PLUS HA;Lo;0;L;;;;;N;;;;; +121BB;CUNEIFORM SIGN LAGAB TIMES A PLUS GAR;Lo;0;L;;;;;N;;;;; +121BC;CUNEIFORM SIGN LAGAB TIMES A PLUS LAL;Lo;0;L;;;;;N;;;;; +121BD;CUNEIFORM SIGN LAGAB TIMES AL;Lo;0;L;;;;;N;;;;; +121BE;CUNEIFORM SIGN LAGAB TIMES AN;Lo;0;L;;;;;N;;;;; +121BF;CUNEIFORM SIGN LAGAB TIMES ASH ZIDA TENU;Lo;0;L;;;;;N;;;;; +121C0;CUNEIFORM SIGN LAGAB TIMES BAD;Lo;0;L;;;;;N;;;;; +121C1;CUNEIFORM SIGN LAGAB TIMES BI;Lo;0;L;;;;;N;;;;; +121C2;CUNEIFORM SIGN LAGAB TIMES DAR;Lo;0;L;;;;;N;;;;; +121C3;CUNEIFORM SIGN LAGAB TIMES EN;Lo;0;L;;;;;N;;;;; +121C4;CUNEIFORM SIGN LAGAB TIMES GA;Lo;0;L;;;;;N;;;;; +121C5;CUNEIFORM SIGN LAGAB TIMES GAR;Lo;0;L;;;;;N;;;;; +121C6;CUNEIFORM SIGN LAGAB TIMES GUD;Lo;0;L;;;;;N;;;;; +121C7;CUNEIFORM SIGN LAGAB TIMES GUD PLUS GUD;Lo;0;L;;;;;N;;;;; +121C8;CUNEIFORM SIGN LAGAB TIMES HA;Lo;0;L;;;;;N;;;;; +121C9;CUNEIFORM SIGN LAGAB TIMES HAL;Lo;0;L;;;;;N;;;;; +121CA;CUNEIFORM SIGN LAGAB TIMES HI TIMES NUN;Lo;0;L;;;;;N;;;;; +121CB;CUNEIFORM SIGN LAGAB TIMES IGI GUNU;Lo;0;L;;;;;N;;;;; +121CC;CUNEIFORM SIGN LAGAB TIMES IM;Lo;0;L;;;;;N;;;;; +121CD;CUNEIFORM SIGN LAGAB TIMES IM PLUS HA;Lo;0;L;;;;;N;;;;; +121CE;CUNEIFORM SIGN LAGAB TIMES IM PLUS LU;Lo;0;L;;;;;N;;;;; +121CF;CUNEIFORM SIGN LAGAB TIMES KI;Lo;0;L;;;;;N;;;;; +121D0;CUNEIFORM SIGN LAGAB TIMES KIN;Lo;0;L;;;;;N;;;;; +121D1;CUNEIFORM SIGN LAGAB TIMES KU3;Lo;0;L;;;;;N;;;;; +121D2;CUNEIFORM SIGN LAGAB TIMES KUL;Lo;0;L;;;;;N;;;;; +121D3;CUNEIFORM SIGN LAGAB TIMES KUL PLUS HI PLUS A;Lo;0;L;;;;;N;;;;; +121D4;CUNEIFORM SIGN LAGAB TIMES LAGAB;Lo;0;L;;;;;N;;;;; +121D5;CUNEIFORM SIGN LAGAB TIMES LISH;Lo;0;L;;;;;N;;;;; +121D6;CUNEIFORM SIGN LAGAB TIMES LU;Lo;0;L;;;;;N;;;;; +121D7;CUNEIFORM SIGN LAGAB TIMES LUL;Lo;0;L;;;;;N;;;;; +121D8;CUNEIFORM SIGN LAGAB TIMES ME;Lo;0;L;;;;;N;;;;; +121D9;CUNEIFORM SIGN LAGAB TIMES ME PLUS EN;Lo;0;L;;;;;N;;;;; +121DA;CUNEIFORM SIGN LAGAB TIMES MUSH;Lo;0;L;;;;;N;;;;; +121DB;CUNEIFORM SIGN LAGAB TIMES NE;Lo;0;L;;;;;N;;;;; +121DC;CUNEIFORM SIGN LAGAB TIMES SHE PLUS SUM;Lo;0;L;;;;;N;;;;; +121DD;CUNEIFORM SIGN LAGAB TIMES SHITA PLUS GISH PLUS ERIN2;Lo;0;L;;;;;N;;;;; +121DE;CUNEIFORM SIGN LAGAB TIMES SHITA PLUS GISH TENU;Lo;0;L;;;;;N;;;;; +121DF;CUNEIFORM SIGN LAGAB TIMES SHU2;Lo;0;L;;;;;N;;;;; +121E0;CUNEIFORM SIGN LAGAB TIMES SHU2 PLUS SHU2;Lo;0;L;;;;;N;;;;; +121E1;CUNEIFORM SIGN LAGAB TIMES SUM;Lo;0;L;;;;;N;;;;; +121E2;CUNEIFORM SIGN LAGAB TIMES TAG;Lo;0;L;;;;;N;;;;; +121E3;CUNEIFORM SIGN LAGAB TIMES TAK4;Lo;0;L;;;;;N;;;;; +121E4;CUNEIFORM SIGN LAGAB TIMES TE PLUS A PLUS SU PLUS NA;Lo;0;L;;;;;N;;;;; +121E5;CUNEIFORM SIGN LAGAB TIMES U;Lo;0;L;;;;;N;;;;; +121E6;CUNEIFORM SIGN LAGAB TIMES U PLUS A;Lo;0;L;;;;;N;;;;; +121E7;CUNEIFORM SIGN LAGAB TIMES U PLUS U PLUS U;Lo;0;L;;;;;N;;;;; +121E8;CUNEIFORM SIGN LAGAB TIMES U2 PLUS ASH;Lo;0;L;;;;;N;;;;; +121E9;CUNEIFORM SIGN LAGAB TIMES UD;Lo;0;L;;;;;N;;;;; +121EA;CUNEIFORM SIGN LAGAB TIMES USH;Lo;0;L;;;;;N;;;;; +121EB;CUNEIFORM SIGN LAGAB SQUARED;Lo;0;L;;;;;N;;;;; +121EC;CUNEIFORM SIGN LAGAR;Lo;0;L;;;;;N;;;;; +121ED;CUNEIFORM SIGN LAGAR TIMES SHE;Lo;0;L;;;;;N;;;;; +121EE;CUNEIFORM SIGN LAGAR TIMES SHE PLUS SUM;Lo;0;L;;;;;N;;;;; +121EF;CUNEIFORM SIGN LAGAR GUNU;Lo;0;L;;;;;N;;;;; +121F0;CUNEIFORM SIGN LAGAR GUNU OVER LAGAR GUNU SHE;Lo;0;L;;;;;N;;;;; +121F1;CUNEIFORM SIGN LAHSHU;Lo;0;L;;;;;N;;;;; +121F2;CUNEIFORM SIGN LAL;Lo;0;L;;;;;N;;;;; +121F3;CUNEIFORM SIGN LAL TIMES LAL;Lo;0;L;;;;;N;;;;; +121F4;CUNEIFORM SIGN LAM;Lo;0;L;;;;;N;;;;; +121F5;CUNEIFORM SIGN LAM TIMES KUR;Lo;0;L;;;;;N;;;;; +121F6;CUNEIFORM SIGN LAM TIMES KUR PLUS RU;Lo;0;L;;;;;N;;;;; +121F7;CUNEIFORM SIGN LI;Lo;0;L;;;;;N;;;;; +121F8;CUNEIFORM SIGN LIL;Lo;0;L;;;;;N;;;;; +121F9;CUNEIFORM SIGN LIMMU2;Lo;0;L;;;;;N;;;;; +121FA;CUNEIFORM SIGN LISH;Lo;0;L;;;;;N;;;;; +121FB;CUNEIFORM SIGN LU;Lo;0;L;;;;;N;;;;; +121FC;CUNEIFORM SIGN LU TIMES BAD;Lo;0;L;;;;;N;;;;; +121FD;CUNEIFORM SIGN LU2;Lo;0;L;;;;;N;;;;; +121FE;CUNEIFORM SIGN LU2 TIMES AL;Lo;0;L;;;;;N;;;;; +121FF;CUNEIFORM SIGN LU2 TIMES BAD;Lo;0;L;;;;;N;;;;; +12200;CUNEIFORM SIGN LU2 TIMES ESH2;Lo;0;L;;;;;N;;;;; +12201;CUNEIFORM SIGN LU2 TIMES ESH2 TENU;Lo;0;L;;;;;N;;;;; +12202;CUNEIFORM SIGN LU2 TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +12203;CUNEIFORM SIGN LU2 TIMES HI TIMES BAD;Lo;0;L;;;;;N;;;;; +12204;CUNEIFORM SIGN LU2 TIMES IM;Lo;0;L;;;;;N;;;;; +12205;CUNEIFORM SIGN LU2 TIMES KAD2;Lo;0;L;;;;;N;;;;; +12206;CUNEIFORM SIGN LU2 TIMES KAD3;Lo;0;L;;;;;N;;;;; +12207;CUNEIFORM SIGN LU2 TIMES KAD3 PLUS ASH;Lo;0;L;;;;;N;;;;; +12208;CUNEIFORM SIGN LU2 TIMES KI;Lo;0;L;;;;;N;;;;; +12209;CUNEIFORM SIGN LU2 TIMES LA PLUS ASH;Lo;0;L;;;;;N;;;;; +1220A;CUNEIFORM SIGN LU2 TIMES LAGAB;Lo;0;L;;;;;N;;;;; +1220B;CUNEIFORM SIGN LU2 TIMES ME PLUS EN;Lo;0;L;;;;;N;;;;; +1220C;CUNEIFORM SIGN LU2 TIMES NE;Lo;0;L;;;;;N;;;;; +1220D;CUNEIFORM SIGN LU2 TIMES NU;Lo;0;L;;;;;N;;;;; +1220E;CUNEIFORM SIGN LU2 TIMES SI PLUS ASH;Lo;0;L;;;;;N;;;;; +1220F;CUNEIFORM SIGN LU2 TIMES SIK2 PLUS BU;Lo;0;L;;;;;N;;;;; +12210;CUNEIFORM SIGN LU2 TIMES TUG2;Lo;0;L;;;;;N;;;;; +12211;CUNEIFORM SIGN LU2 TENU;Lo;0;L;;;;;N;;;;; +12212;CUNEIFORM SIGN LU2 CROSSING LU2;Lo;0;L;;;;;N;;;;; +12213;CUNEIFORM SIGN LU2 OPPOSING LU2;Lo;0;L;;;;;N;;;;; +12214;CUNEIFORM SIGN LU2 SQUARED;Lo;0;L;;;;;N;;;;; +12215;CUNEIFORM SIGN LU2 SHESHIG;Lo;0;L;;;;;N;;;;; +12216;CUNEIFORM SIGN LU3;Lo;0;L;;;;;N;;;;; +12217;CUNEIFORM SIGN LUGAL;Lo;0;L;;;;;N;;;;; +12218;CUNEIFORM SIGN LUGAL OVER LUGAL;Lo;0;L;;;;;N;;;;; +12219;CUNEIFORM SIGN LUGAL OPPOSING LUGAL;Lo;0;L;;;;;N;;;;; +1221A;CUNEIFORM SIGN LUGAL SHESHIG;Lo;0;L;;;;;N;;;;; +1221B;CUNEIFORM SIGN LUH;Lo;0;L;;;;;N;;;;; +1221C;CUNEIFORM SIGN LUL;Lo;0;L;;;;;N;;;;; +1221D;CUNEIFORM SIGN LUM;Lo;0;L;;;;;N;;;;; +1221E;CUNEIFORM SIGN LUM OVER LUM;Lo;0;L;;;;;N;;;;; +1221F;CUNEIFORM SIGN LUM OVER LUM GAR OVER GAR;Lo;0;L;;;;;N;;;;; +12220;CUNEIFORM SIGN MA;Lo;0;L;;;;;N;;;;; +12221;CUNEIFORM SIGN MA TIMES TAK4;Lo;0;L;;;;;N;;;;; +12222;CUNEIFORM SIGN MA GUNU;Lo;0;L;;;;;N;;;;; +12223;CUNEIFORM SIGN MA2;Lo;0;L;;;;;N;;;;; +12224;CUNEIFORM SIGN MAH;Lo;0;L;;;;;N;;;;; +12225;CUNEIFORM SIGN MAR;Lo;0;L;;;;;N;;;;; +12226;CUNEIFORM SIGN MASH;Lo;0;L;;;;;N;;;;; +12227;CUNEIFORM SIGN MASH2;Lo;0;L;;;;;N;;;;; +12228;CUNEIFORM SIGN ME;Lo;0;L;;;;;N;;;;; +12229;CUNEIFORM SIGN MES;Lo;0;L;;;;;N;;;;; +1222A;CUNEIFORM SIGN MI;Lo;0;L;;;;;N;;;;; +1222B;CUNEIFORM SIGN MIN;Lo;0;L;;;;;N;;;;; +1222C;CUNEIFORM SIGN MU;Lo;0;L;;;;;N;;;;; +1222D;CUNEIFORM SIGN MU OVER MU;Lo;0;L;;;;;N;;;;; +1222E;CUNEIFORM SIGN MUG;Lo;0;L;;;;;N;;;;; +1222F;CUNEIFORM SIGN MUG GUNU;Lo;0;L;;;;;N;;;;; +12230;CUNEIFORM SIGN MUNSUB;Lo;0;L;;;;;N;;;;; +12231;CUNEIFORM SIGN MURGU2;Lo;0;L;;;;;N;;;;; +12232;CUNEIFORM SIGN MUSH;Lo;0;L;;;;;N;;;;; +12233;CUNEIFORM SIGN MUSH TIMES A;Lo;0;L;;;;;N;;;;; +12234;CUNEIFORM SIGN MUSH TIMES KUR;Lo;0;L;;;;;N;;;;; +12235;CUNEIFORM SIGN MUSH TIMES ZA;Lo;0;L;;;;;N;;;;; +12236;CUNEIFORM SIGN MUSH OVER MUSH;Lo;0;L;;;;;N;;;;; +12237;CUNEIFORM SIGN MUSH OVER MUSH TIMES A PLUS NA;Lo;0;L;;;;;N;;;;; +12238;CUNEIFORM SIGN MUSH CROSSING MUSH;Lo;0;L;;;;;N;;;;; +12239;CUNEIFORM SIGN MUSH3;Lo;0;L;;;;;N;;;;; +1223A;CUNEIFORM SIGN MUSH3 TIMES A;Lo;0;L;;;;;N;;;;; +1223B;CUNEIFORM SIGN MUSH3 TIMES A PLUS DI;Lo;0;L;;;;;N;;;;; +1223C;CUNEIFORM SIGN MUSH3 TIMES DI;Lo;0;L;;;;;N;;;;; +1223D;CUNEIFORM SIGN MUSH3 GUNU;Lo;0;L;;;;;N;;;;; +1223E;CUNEIFORM SIGN NA;Lo;0;L;;;;;N;;;;; +1223F;CUNEIFORM SIGN NA2;Lo;0;L;;;;;N;;;;; +12240;CUNEIFORM SIGN NAGA;Lo;0;L;;;;;N;;;;; +12241;CUNEIFORM SIGN NAGA INVERTED;Lo;0;L;;;;;N;;;;; +12242;CUNEIFORM SIGN NAGA TIMES SHU TENU;Lo;0;L;;;;;N;;;;; +12243;CUNEIFORM SIGN NAGA OPPOSING NAGA;Lo;0;L;;;;;N;;;;; +12244;CUNEIFORM SIGN NAGAR;Lo;0;L;;;;;N;;;;; +12245;CUNEIFORM SIGN NAM NUTILLU;Lo;0;L;;;;;N;;;;; +12246;CUNEIFORM SIGN NAM;Lo;0;L;;;;;N;;;;; +12247;CUNEIFORM SIGN NAM2;Lo;0;L;;;;;N;;;;; +12248;CUNEIFORM SIGN NE;Lo;0;L;;;;;N;;;;; +12249;CUNEIFORM SIGN NE TIMES A;Lo;0;L;;;;;N;;;;; +1224A;CUNEIFORM SIGN NE TIMES UD;Lo;0;L;;;;;N;;;;; +1224B;CUNEIFORM SIGN NE SHESHIG;Lo;0;L;;;;;N;;;;; +1224C;CUNEIFORM SIGN NI;Lo;0;L;;;;;N;;;;; +1224D;CUNEIFORM SIGN NI TIMES E;Lo;0;L;;;;;N;;;;; +1224E;CUNEIFORM SIGN NI2;Lo;0;L;;;;;N;;;;; +1224F;CUNEIFORM SIGN NIM;Lo;0;L;;;;;N;;;;; +12250;CUNEIFORM SIGN NIM TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +12251;CUNEIFORM SIGN NIM TIMES GAR PLUS GAN2 TENU;Lo;0;L;;;;;N;;;;; +12252;CUNEIFORM SIGN NINDA2;Lo;0;L;;;;;N;;;;; +12253;CUNEIFORM SIGN NINDA2 TIMES AN;Lo;0;L;;;;;N;;;;; +12254;CUNEIFORM SIGN NINDA2 TIMES ASH;Lo;0;L;;;;;N;;;;; +12255;CUNEIFORM SIGN NINDA2 TIMES ASH PLUS ASH;Lo;0;L;;;;;N;;;;; +12256;CUNEIFORM SIGN NINDA2 TIMES GUD;Lo;0;L;;;;;N;;;;; +12257;CUNEIFORM SIGN NINDA2 TIMES ME PLUS GAN2 TENU;Lo;0;L;;;;;N;;;;; +12258;CUNEIFORM SIGN NINDA2 TIMES NE;Lo;0;L;;;;;N;;;;; +12259;CUNEIFORM SIGN NINDA2 TIMES NUN;Lo;0;L;;;;;N;;;;; +1225A;CUNEIFORM SIGN NINDA2 TIMES SHE;Lo;0;L;;;;;N;;;;; +1225B;CUNEIFORM SIGN NINDA2 TIMES SHE PLUS A AN;Lo;0;L;;;;;N;;;;; +1225C;CUNEIFORM SIGN NINDA2 TIMES SHE PLUS ASH;Lo;0;L;;;;;N;;;;; +1225D;CUNEIFORM SIGN NINDA2 TIMES SHE PLUS ASH PLUS ASH;Lo;0;L;;;;;N;;;;; +1225E;CUNEIFORM SIGN NINDA2 TIMES U2 PLUS ASH;Lo;0;L;;;;;N;;;;; +1225F;CUNEIFORM SIGN NINDA2 TIMES USH;Lo;0;L;;;;;N;;;;; +12260;CUNEIFORM SIGN NISAG;Lo;0;L;;;;;N;;;;; +12261;CUNEIFORM SIGN NU;Lo;0;L;;;;;N;;;;; +12262;CUNEIFORM SIGN NU11;Lo;0;L;;;;;N;;;;; +12263;CUNEIFORM SIGN NUN;Lo;0;L;;;;;N;;;;; +12264;CUNEIFORM SIGN NUN LAGAR TIMES GAR;Lo;0;L;;;;;N;;;;; +12265;CUNEIFORM SIGN NUN LAGAR TIMES MASH;Lo;0;L;;;;;N;;;;; +12266;CUNEIFORM SIGN NUN LAGAR TIMES SAL;Lo;0;L;;;;;N;;;;; +12267;CUNEIFORM SIGN NUN LAGAR TIMES SAL OVER NUN LAGAR TIMES SAL;Lo;0;L;;;;;N;;;;; +12268;CUNEIFORM SIGN NUN LAGAR TIMES USH;Lo;0;L;;;;;N;;;;; +12269;CUNEIFORM SIGN NUN TENU;Lo;0;L;;;;;N;;;;; +1226A;CUNEIFORM SIGN NUN OVER NUN;Lo;0;L;;;;;N;;;;; +1226B;CUNEIFORM SIGN NUN CROSSING NUN;Lo;0;L;;;;;N;;;;; +1226C;CUNEIFORM SIGN NUN CROSSING NUN LAGAR OVER LAGAR;Lo;0;L;;;;;N;;;;; +1226D;CUNEIFORM SIGN NUNUZ;Lo;0;L;;;;;N;;;;; +1226E;CUNEIFORM SIGN NUNUZ AB2 TIMES ASHGAB;Lo;0;L;;;;;N;;;;; +1226F;CUNEIFORM SIGN NUNUZ AB2 TIMES BI;Lo;0;L;;;;;N;;;;; +12270;CUNEIFORM SIGN NUNUZ AB2 TIMES DUG;Lo;0;L;;;;;N;;;;; +12271;CUNEIFORM SIGN NUNUZ AB2 TIMES GUD;Lo;0;L;;;;;N;;;;; +12272;CUNEIFORM SIGN NUNUZ AB2 TIMES IGI GUNU;Lo;0;L;;;;;N;;;;; +12273;CUNEIFORM SIGN NUNUZ AB2 TIMES KAD3;Lo;0;L;;;;;N;;;;; +12274;CUNEIFORM SIGN NUNUZ AB2 TIMES LA;Lo;0;L;;;;;N;;;;; +12275;CUNEIFORM SIGN NUNUZ AB2 TIMES NE;Lo;0;L;;;;;N;;;;; +12276;CUNEIFORM SIGN NUNUZ AB2 TIMES SILA3;Lo;0;L;;;;;N;;;;; +12277;CUNEIFORM SIGN NUNUZ AB2 TIMES U2;Lo;0;L;;;;;N;;;;; +12278;CUNEIFORM SIGN NUNUZ KISIM5 TIMES BI;Lo;0;L;;;;;N;;;;; +12279;CUNEIFORM SIGN NUNUZ KISIM5 TIMES BI U;Lo;0;L;;;;;N;;;;; +1227A;CUNEIFORM SIGN PA;Lo;0;L;;;;;N;;;;; +1227B;CUNEIFORM SIGN PAD;Lo;0;L;;;;;N;;;;; +1227C;CUNEIFORM SIGN PAN;Lo;0;L;;;;;N;;;;; +1227D;CUNEIFORM SIGN PAP;Lo;0;L;;;;;N;;;;; +1227E;CUNEIFORM SIGN PESH2;Lo;0;L;;;;;N;;;;; +1227F;CUNEIFORM SIGN PI;Lo;0;L;;;;;N;;;;; +12280;CUNEIFORM SIGN PI TIMES A;Lo;0;L;;;;;N;;;;; +12281;CUNEIFORM SIGN PI TIMES AB;Lo;0;L;;;;;N;;;;; +12282;CUNEIFORM SIGN PI TIMES BI;Lo;0;L;;;;;N;;;;; +12283;CUNEIFORM SIGN PI TIMES BU;Lo;0;L;;;;;N;;;;; +12284;CUNEIFORM SIGN PI TIMES E;Lo;0;L;;;;;N;;;;; +12285;CUNEIFORM SIGN PI TIMES I;Lo;0;L;;;;;N;;;;; +12286;CUNEIFORM SIGN PI TIMES IB;Lo;0;L;;;;;N;;;;; +12287;CUNEIFORM SIGN PI TIMES U;Lo;0;L;;;;;N;;;;; +12288;CUNEIFORM SIGN PI TIMES U2;Lo;0;L;;;;;N;;;;; +12289;CUNEIFORM SIGN PI CROSSING PI;Lo;0;L;;;;;N;;;;; +1228A;CUNEIFORM SIGN PIRIG;Lo;0;L;;;;;N;;;;; +1228B;CUNEIFORM SIGN PIRIG TIMES KAL;Lo;0;L;;;;;N;;;;; +1228C;CUNEIFORM SIGN PIRIG TIMES UD;Lo;0;L;;;;;N;;;;; +1228D;CUNEIFORM SIGN PIRIG TIMES ZA;Lo;0;L;;;;;N;;;;; +1228E;CUNEIFORM SIGN PIRIG OPPOSING PIRIG;Lo;0;L;;;;;N;;;;; +1228F;CUNEIFORM SIGN RA;Lo;0;L;;;;;N;;;;; +12290;CUNEIFORM SIGN RAB;Lo;0;L;;;;;N;;;;; +12291;CUNEIFORM SIGN RI;Lo;0;L;;;;;N;;;;; +12292;CUNEIFORM SIGN RU;Lo;0;L;;;;;N;;;;; +12293;CUNEIFORM SIGN SA;Lo;0;L;;;;;N;;;;; +12294;CUNEIFORM SIGN SAG NUTILLU;Lo;0;L;;;;;N;;;;; +12295;CUNEIFORM SIGN SAG;Lo;0;L;;;;;N;;;;; +12296;CUNEIFORM SIGN SAG TIMES A;Lo;0;L;;;;;N;;;;; +12297;CUNEIFORM SIGN SAG TIMES DU;Lo;0;L;;;;;N;;;;; +12298;CUNEIFORM SIGN SAG TIMES DUB;Lo;0;L;;;;;N;;;;; +12299;CUNEIFORM SIGN SAG TIMES HA;Lo;0;L;;;;;N;;;;; +1229A;CUNEIFORM SIGN SAG TIMES KAK;Lo;0;L;;;;;N;;;;; +1229B;CUNEIFORM SIGN SAG TIMES KUR;Lo;0;L;;;;;N;;;;; +1229C;CUNEIFORM SIGN SAG TIMES LUM;Lo;0;L;;;;;N;;;;; +1229D;CUNEIFORM SIGN SAG TIMES MI;Lo;0;L;;;;;N;;;;; +1229E;CUNEIFORM SIGN SAG TIMES NUN;Lo;0;L;;;;;N;;;;; +1229F;CUNEIFORM SIGN SAG TIMES SAL;Lo;0;L;;;;;N;;;;; +122A0;CUNEIFORM SIGN SAG TIMES SHID;Lo;0;L;;;;;N;;;;; +122A1;CUNEIFORM SIGN SAG TIMES TAB;Lo;0;L;;;;;N;;;;; +122A2;CUNEIFORM SIGN SAG TIMES U2;Lo;0;L;;;;;N;;;;; +122A3;CUNEIFORM SIGN SAG TIMES UB;Lo;0;L;;;;;N;;;;; +122A4;CUNEIFORM SIGN SAG TIMES UM;Lo;0;L;;;;;N;;;;; +122A5;CUNEIFORM SIGN SAG TIMES UR;Lo;0;L;;;;;N;;;;; +122A6;CUNEIFORM SIGN SAG TIMES USH;Lo;0;L;;;;;N;;;;; +122A7;CUNEIFORM SIGN SAG OVER SAG;Lo;0;L;;;;;N;;;;; +122A8;CUNEIFORM SIGN SAG GUNU;Lo;0;L;;;;;N;;;;; +122A9;CUNEIFORM SIGN SAL;Lo;0;L;;;;;N;;;;; +122AA;CUNEIFORM SIGN SAL LAGAB TIMES ASH2;Lo;0;L;;;;;N;;;;; +122AB;CUNEIFORM SIGN SANGA2;Lo;0;L;;;;;N;;;;; +122AC;CUNEIFORM SIGN SAR;Lo;0;L;;;;;N;;;;; +122AD;CUNEIFORM SIGN SHA;Lo;0;L;;;;;N;;;;; +122AE;CUNEIFORM SIGN SHA3;Lo;0;L;;;;;N;;;;; +122AF;CUNEIFORM SIGN SHA3 TIMES A;Lo;0;L;;;;;N;;;;; +122B0;CUNEIFORM SIGN SHA3 TIMES BAD;Lo;0;L;;;;;N;;;;; +122B1;CUNEIFORM SIGN SHA3 TIMES GISH;Lo;0;L;;;;;N;;;;; +122B2;CUNEIFORM SIGN SHA3 TIMES NE;Lo;0;L;;;;;N;;;;; +122B3;CUNEIFORM SIGN SHA3 TIMES SHU2;Lo;0;L;;;;;N;;;;; +122B4;CUNEIFORM SIGN SHA3 TIMES TUR;Lo;0;L;;;;;N;;;;; +122B5;CUNEIFORM SIGN SHA3 TIMES U;Lo;0;L;;;;;N;;;;; +122B6;CUNEIFORM SIGN SHA3 TIMES U PLUS A;Lo;0;L;;;;;N;;;;; +122B7;CUNEIFORM SIGN SHA6;Lo;0;L;;;;;N;;;;; +122B8;CUNEIFORM SIGN SHAB6;Lo;0;L;;;;;N;;;;; +122B9;CUNEIFORM SIGN SHAR2;Lo;0;L;;;;;N;;;;; +122BA;CUNEIFORM SIGN SHE;Lo;0;L;;;;;N;;;;; +122BB;CUNEIFORM SIGN SHE HU;Lo;0;L;;;;;N;;;;; +122BC;CUNEIFORM SIGN SHE OVER SHE GAD OVER GAD GAR OVER GAR;Lo;0;L;;;;;N;;;;; +122BD;CUNEIFORM SIGN SHE OVER SHE TAB OVER TAB GAR OVER GAR;Lo;0;L;;;;;N;;;;; +122BE;CUNEIFORM SIGN SHEG9;Lo;0;L;;;;;N;;;;; +122BF;CUNEIFORM SIGN SHEN;Lo;0;L;;;;;N;;;;; +122C0;CUNEIFORM SIGN SHESH;Lo;0;L;;;;;N;;;;; +122C1;CUNEIFORM SIGN SHESH2;Lo;0;L;;;;;N;;;;; +122C2;CUNEIFORM SIGN SHESHLAM;Lo;0;L;;;;;N;;;;; +122C3;CUNEIFORM SIGN SHID;Lo;0;L;;;;;N;;;;; +122C4;CUNEIFORM SIGN SHID TIMES A;Lo;0;L;;;;;N;;;;; +122C5;CUNEIFORM SIGN SHID TIMES IM;Lo;0;L;;;;;N;;;;; +122C6;CUNEIFORM SIGN SHIM;Lo;0;L;;;;;N;;;;; +122C7;CUNEIFORM SIGN SHIM TIMES A;Lo;0;L;;;;;N;;;;; +122C8;CUNEIFORM SIGN SHIM TIMES BAL;Lo;0;L;;;;;N;;;;; +122C9;CUNEIFORM SIGN SHIM TIMES BULUG;Lo;0;L;;;;;N;;;;; +122CA;CUNEIFORM SIGN SHIM TIMES DIN;Lo;0;L;;;;;N;;;;; +122CB;CUNEIFORM SIGN SHIM TIMES GAR;Lo;0;L;;;;;N;;;;; +122CC;CUNEIFORM SIGN SHIM TIMES IGI;Lo;0;L;;;;;N;;;;; +122CD;CUNEIFORM SIGN SHIM TIMES IGI GUNU;Lo;0;L;;;;;N;;;;; +122CE;CUNEIFORM SIGN SHIM TIMES KUSHU2;Lo;0;L;;;;;N;;;;; +122CF;CUNEIFORM SIGN SHIM TIMES LUL;Lo;0;L;;;;;N;;;;; +122D0;CUNEIFORM SIGN SHIM TIMES MUG;Lo;0;L;;;;;N;;;;; +122D1;CUNEIFORM SIGN SHIM TIMES SAL;Lo;0;L;;;;;N;;;;; +122D2;CUNEIFORM SIGN SHINIG;Lo;0;L;;;;;N;;;;; +122D3;CUNEIFORM SIGN SHIR;Lo;0;L;;;;;N;;;;; +122D4;CUNEIFORM SIGN SHIR TENU;Lo;0;L;;;;;N;;;;; +122D5;CUNEIFORM SIGN SHIR OVER SHIR BUR OVER BUR;Lo;0;L;;;;;N;;;;; +122D6;CUNEIFORM SIGN SHITA;Lo;0;L;;;;;N;;;;; +122D7;CUNEIFORM SIGN SHU;Lo;0;L;;;;;N;;;;; +122D8;CUNEIFORM SIGN SHU OVER INVERTED SHU;Lo;0;L;;;;;N;;;;; +122D9;CUNEIFORM SIGN SHU2;Lo;0;L;;;;;N;;;;; +122DA;CUNEIFORM SIGN SHUBUR;Lo;0;L;;;;;N;;;;; +122DB;CUNEIFORM SIGN SI;Lo;0;L;;;;;N;;;;; +122DC;CUNEIFORM SIGN SI GUNU;Lo;0;L;;;;;N;;;;; +122DD;CUNEIFORM SIGN SIG;Lo;0;L;;;;;N;;;;; +122DE;CUNEIFORM SIGN SIG4;Lo;0;L;;;;;N;;;;; +122DF;CUNEIFORM SIGN SIG4 OVER SIG4 SHU2;Lo;0;L;;;;;N;;;;; +122E0;CUNEIFORM SIGN SIK2;Lo;0;L;;;;;N;;;;; +122E1;CUNEIFORM SIGN SILA3;Lo;0;L;;;;;N;;;;; +122E2;CUNEIFORM SIGN SU;Lo;0;L;;;;;N;;;;; +122E3;CUNEIFORM SIGN SU OVER SU;Lo;0;L;;;;;N;;;;; +122E4;CUNEIFORM SIGN SUD;Lo;0;L;;;;;N;;;;; +122E5;CUNEIFORM SIGN SUD2;Lo;0;L;;;;;N;;;;; +122E6;CUNEIFORM SIGN SUHUR;Lo;0;L;;;;;N;;;;; +122E7;CUNEIFORM SIGN SUM;Lo;0;L;;;;;N;;;;; +122E8;CUNEIFORM SIGN SUMASH;Lo;0;L;;;;;N;;;;; +122E9;CUNEIFORM SIGN SUR;Lo;0;L;;;;;N;;;;; +122EA;CUNEIFORM SIGN SUR9;Lo;0;L;;;;;N;;;;; +122EB;CUNEIFORM SIGN TA;Lo;0;L;;;;;N;;;;; +122EC;CUNEIFORM SIGN TA ASTERISK;Lo;0;L;;;;;N;;;;; +122ED;CUNEIFORM SIGN TA TIMES HI;Lo;0;L;;;;;N;;;;; +122EE;CUNEIFORM SIGN TA TIMES MI;Lo;0;L;;;;;N;;;;; +122EF;CUNEIFORM SIGN TA GUNU;Lo;0;L;;;;;N;;;;; +122F0;CUNEIFORM SIGN TAB;Lo;0;L;;;;;N;;;;; +122F1;CUNEIFORM SIGN TAB OVER TAB NI OVER NI DISH OVER DISH;Lo;0;L;;;;;N;;;;; +122F2;CUNEIFORM SIGN TAB SQUARED;Lo;0;L;;;;;N;;;;; +122F3;CUNEIFORM SIGN TAG;Lo;0;L;;;;;N;;;;; +122F4;CUNEIFORM SIGN TAG TIMES BI;Lo;0;L;;;;;N;;;;; +122F5;CUNEIFORM SIGN TAG TIMES GUD;Lo;0;L;;;;;N;;;;; +122F6;CUNEIFORM SIGN TAG TIMES SHE;Lo;0;L;;;;;N;;;;; +122F7;CUNEIFORM SIGN TAG TIMES SHU;Lo;0;L;;;;;N;;;;; +122F8;CUNEIFORM SIGN TAG TIMES TUG2;Lo;0;L;;;;;N;;;;; +122F9;CUNEIFORM SIGN TAG TIMES UD;Lo;0;L;;;;;N;;;;; +122FA;CUNEIFORM SIGN TAK4;Lo;0;L;;;;;N;;;;; +122FB;CUNEIFORM SIGN TAR;Lo;0;L;;;;;N;;;;; +122FC;CUNEIFORM SIGN TE;Lo;0;L;;;;;N;;;;; +122FD;CUNEIFORM SIGN TE GUNU;Lo;0;L;;;;;N;;;;; +122FE;CUNEIFORM SIGN TI;Lo;0;L;;;;;N;;;;; +122FF;CUNEIFORM SIGN TI TENU;Lo;0;L;;;;;N;;;;; +12300;CUNEIFORM SIGN TIL;Lo;0;L;;;;;N;;;;; +12301;CUNEIFORM SIGN TIR;Lo;0;L;;;;;N;;;;; +12302;CUNEIFORM SIGN TIR TIMES TAK4;Lo;0;L;;;;;N;;;;; +12303;CUNEIFORM SIGN TIR OVER TIR;Lo;0;L;;;;;N;;;;; +12304;CUNEIFORM SIGN TIR OVER TIR GAD OVER GAD GAR OVER GAR;Lo;0;L;;;;;N;;;;; +12305;CUNEIFORM SIGN TU;Lo;0;L;;;;;N;;;;; +12306;CUNEIFORM SIGN TUG2;Lo;0;L;;;;;N;;;;; +12307;CUNEIFORM SIGN TUK;Lo;0;L;;;;;N;;;;; +12308;CUNEIFORM SIGN TUM;Lo;0;L;;;;;N;;;;; +12309;CUNEIFORM SIGN TUR;Lo;0;L;;;;;N;;;;; +1230A;CUNEIFORM SIGN TUR OVER TUR ZA OVER ZA;Lo;0;L;;;;;N;;;;; +1230B;CUNEIFORM SIGN U;Lo;0;L;;;;;N;;;;; +1230C;CUNEIFORM SIGN U GUD;Lo;0;L;;;;;N;;;;; +1230D;CUNEIFORM SIGN U U U;Lo;0;L;;;;;N;;;;; +1230E;CUNEIFORM SIGN U OVER U PA OVER PA GAR OVER GAR;Lo;0;L;;;;;N;;;;; +1230F;CUNEIFORM SIGN U OVER U SUR OVER SUR;Lo;0;L;;;;;N;;;;; +12310;CUNEIFORM SIGN U OVER U U REVERSED OVER U REVERSED;Lo;0;L;;;;;N;;;;; +12311;CUNEIFORM SIGN U2;Lo;0;L;;;;;N;;;;; +12312;CUNEIFORM SIGN UB;Lo;0;L;;;;;N;;;;; +12313;CUNEIFORM SIGN UD;Lo;0;L;;;;;N;;;;; +12314;CUNEIFORM SIGN UD KUSHU2;Lo;0;L;;;;;N;;;;; +12315;CUNEIFORM SIGN UD TIMES BAD;Lo;0;L;;;;;N;;;;; +12316;CUNEIFORM SIGN UD TIMES MI;Lo;0;L;;;;;N;;;;; +12317;CUNEIFORM SIGN UD TIMES U PLUS U PLUS U;Lo;0;L;;;;;N;;;;; +12318;CUNEIFORM SIGN UD TIMES U PLUS U PLUS U GUNU;Lo;0;L;;;;;N;;;;; +12319;CUNEIFORM SIGN UD GUNU;Lo;0;L;;;;;N;;;;; +1231A;CUNEIFORM SIGN UD SHESHIG;Lo;0;L;;;;;N;;;;; +1231B;CUNEIFORM SIGN UD SHESHIG TIMES BAD;Lo;0;L;;;;;N;;;;; +1231C;CUNEIFORM SIGN UDUG;Lo;0;L;;;;;N;;;;; +1231D;CUNEIFORM SIGN UM;Lo;0;L;;;;;N;;;;; +1231E;CUNEIFORM SIGN UM TIMES LAGAB;Lo;0;L;;;;;N;;;;; +1231F;CUNEIFORM SIGN UM TIMES ME PLUS DA;Lo;0;L;;;;;N;;;;; +12320;CUNEIFORM SIGN UM TIMES SHA3;Lo;0;L;;;;;N;;;;; +12321;CUNEIFORM SIGN UM TIMES U;Lo;0;L;;;;;N;;;;; +12322;CUNEIFORM SIGN UMBIN;Lo;0;L;;;;;N;;;;; +12323;CUNEIFORM SIGN UMUM;Lo;0;L;;;;;N;;;;; +12324;CUNEIFORM SIGN UMUM TIMES KASKAL;Lo;0;L;;;;;N;;;;; +12325;CUNEIFORM SIGN UMUM TIMES PA;Lo;0;L;;;;;N;;;;; +12326;CUNEIFORM SIGN UN;Lo;0;L;;;;;N;;;;; +12327;CUNEIFORM SIGN UN GUNU;Lo;0;L;;;;;N;;;;; +12328;CUNEIFORM SIGN UR;Lo;0;L;;;;;N;;;;; +12329;CUNEIFORM SIGN UR CROSSING UR;Lo;0;L;;;;;N;;;;; +1232A;CUNEIFORM SIGN UR SHESHIG;Lo;0;L;;;;;N;;;;; +1232B;CUNEIFORM SIGN UR2;Lo;0;L;;;;;N;;;;; +1232C;CUNEIFORM SIGN UR2 TIMES A PLUS HA;Lo;0;L;;;;;N;;;;; +1232D;CUNEIFORM SIGN UR2 TIMES A PLUS NA;Lo;0;L;;;;;N;;;;; +1232E;CUNEIFORM SIGN UR2 TIMES AL;Lo;0;L;;;;;N;;;;; +1232F;CUNEIFORM SIGN UR2 TIMES HA;Lo;0;L;;;;;N;;;;; +12330;CUNEIFORM SIGN UR2 TIMES NUN;Lo;0;L;;;;;N;;;;; +12331;CUNEIFORM SIGN UR2 TIMES U2;Lo;0;L;;;;;N;;;;; +12332;CUNEIFORM SIGN UR2 TIMES U2 PLUS ASH;Lo;0;L;;;;;N;;;;; +12333;CUNEIFORM SIGN UR2 TIMES U2 PLUS BI;Lo;0;L;;;;;N;;;;; +12334;CUNEIFORM SIGN UR4;Lo;0;L;;;;;N;;;;; +12335;CUNEIFORM SIGN URI;Lo;0;L;;;;;N;;;;; +12336;CUNEIFORM SIGN URI3;Lo;0;L;;;;;N;;;;; +12337;CUNEIFORM SIGN URU;Lo;0;L;;;;;N;;;;; +12338;CUNEIFORM SIGN URU TIMES A;Lo;0;L;;;;;N;;;;; +12339;CUNEIFORM SIGN URU TIMES ASHGAB;Lo;0;L;;;;;N;;;;; +1233A;CUNEIFORM SIGN URU TIMES BAR;Lo;0;L;;;;;N;;;;; +1233B;CUNEIFORM SIGN URU TIMES DUN;Lo;0;L;;;;;N;;;;; +1233C;CUNEIFORM SIGN URU TIMES GA;Lo;0;L;;;;;N;;;;; +1233D;CUNEIFORM SIGN URU TIMES GAL;Lo;0;L;;;;;N;;;;; +1233E;CUNEIFORM SIGN URU TIMES GAN2 TENU;Lo;0;L;;;;;N;;;;; +1233F;CUNEIFORM SIGN URU TIMES GAR;Lo;0;L;;;;;N;;;;; +12340;CUNEIFORM SIGN URU TIMES GU;Lo;0;L;;;;;N;;;;; +12341;CUNEIFORM SIGN URU TIMES HA;Lo;0;L;;;;;N;;;;; +12342;CUNEIFORM SIGN URU TIMES IGI;Lo;0;L;;;;;N;;;;; +12343;CUNEIFORM SIGN URU TIMES IM;Lo;0;L;;;;;N;;;;; +12344;CUNEIFORM SIGN URU TIMES ISH;Lo;0;L;;;;;N;;;;; +12345;CUNEIFORM SIGN URU TIMES KI;Lo;0;L;;;;;N;;;;; +12346;CUNEIFORM SIGN URU TIMES LUM;Lo;0;L;;;;;N;;;;; +12347;CUNEIFORM SIGN URU TIMES MIN;Lo;0;L;;;;;N;;;;; +12348;CUNEIFORM SIGN URU TIMES PA;Lo;0;L;;;;;N;;;;; +12349;CUNEIFORM SIGN URU TIMES SHE;Lo;0;L;;;;;N;;;;; +1234A;CUNEIFORM SIGN URU TIMES SIG4;Lo;0;L;;;;;N;;;;; +1234B;CUNEIFORM SIGN URU TIMES TU;Lo;0;L;;;;;N;;;;; +1234C;CUNEIFORM SIGN URU TIMES U PLUS GUD;Lo;0;L;;;;;N;;;;; +1234D;CUNEIFORM SIGN URU TIMES UD;Lo;0;L;;;;;N;;;;; +1234E;CUNEIFORM SIGN URU TIMES URUDA;Lo;0;L;;;;;N;;;;; +1234F;CUNEIFORM SIGN URUDA;Lo;0;L;;;;;N;;;;; +12350;CUNEIFORM SIGN URUDA TIMES U;Lo;0;L;;;;;N;;;;; +12351;CUNEIFORM SIGN USH;Lo;0;L;;;;;N;;;;; +12352;CUNEIFORM SIGN USH TIMES A;Lo;0;L;;;;;N;;;;; +12353;CUNEIFORM SIGN USH TIMES KU;Lo;0;L;;;;;N;;;;; +12354;CUNEIFORM SIGN USH TIMES KUR;Lo;0;L;;;;;N;;;;; +12355;CUNEIFORM SIGN USH TIMES TAK4;Lo;0;L;;;;;N;;;;; +12356;CUNEIFORM SIGN USHX;Lo;0;L;;;;;N;;;;; +12357;CUNEIFORM SIGN USH2;Lo;0;L;;;;;N;;;;; +12358;CUNEIFORM SIGN USHUMX;Lo;0;L;;;;;N;;;;; +12359;CUNEIFORM SIGN UTUKI;Lo;0;L;;;;;N;;;;; +1235A;CUNEIFORM SIGN UZ3;Lo;0;L;;;;;N;;;;; +1235B;CUNEIFORM SIGN UZ3 TIMES KASKAL;Lo;0;L;;;;;N;;;;; +1235C;CUNEIFORM SIGN UZU;Lo;0;L;;;;;N;;;;; +1235D;CUNEIFORM SIGN ZA;Lo;0;L;;;;;N;;;;; +1235E;CUNEIFORM SIGN ZA TENU;Lo;0;L;;;;;N;;;;; +1235F;CUNEIFORM SIGN ZA SQUARED TIMES KUR;Lo;0;L;;;;;N;;;;; +12360;CUNEIFORM SIGN ZAG;Lo;0;L;;;;;N;;;;; +12361;CUNEIFORM SIGN ZAMX;Lo;0;L;;;;;N;;;;; +12362;CUNEIFORM SIGN ZE2;Lo;0;L;;;;;N;;;;; +12363;CUNEIFORM SIGN ZI;Lo;0;L;;;;;N;;;;; +12364;CUNEIFORM SIGN ZI OVER ZI;Lo;0;L;;;;;N;;;;; +12365;CUNEIFORM SIGN ZI3;Lo;0;L;;;;;N;;;;; +12366;CUNEIFORM SIGN ZIB;Lo;0;L;;;;;N;;;;; +12367;CUNEIFORM SIGN ZIB KABA TENU;Lo;0;L;;;;;N;;;;; +12368;CUNEIFORM SIGN ZIG;Lo;0;L;;;;;N;;;;; +12369;CUNEIFORM SIGN ZIZ2;Lo;0;L;;;;;N;;;;; +1236A;CUNEIFORM SIGN ZU;Lo;0;L;;;;;N;;;;; +1236B;CUNEIFORM SIGN ZU5;Lo;0;L;;;;;N;;;;; +1236C;CUNEIFORM SIGN ZU5 TIMES A;Lo;0;L;;;;;N;;;;; +1236D;CUNEIFORM SIGN ZUBUR;Lo;0;L;;;;;N;;;;; +1236E;CUNEIFORM SIGN ZUM;Lo;0;L;;;;;N;;;;; +12400;CUNEIFORM NUMERIC SIGN TWO ASH;Nl;0;L;;;;2;N;;;;; +12401;CUNEIFORM NUMERIC SIGN THREE ASH;Nl;0;L;;;;3;N;;;;; +12402;CUNEIFORM NUMERIC SIGN FOUR ASH;Nl;0;L;;;;4;N;;;;; +12403;CUNEIFORM NUMERIC SIGN FIVE ASH;Nl;0;L;;;;5;N;;;;; +12404;CUNEIFORM NUMERIC SIGN SIX ASH;Nl;0;L;;;;6;N;;;;; +12405;CUNEIFORM NUMERIC SIGN SEVEN ASH;Nl;0;L;;;;7;N;;;;; +12406;CUNEIFORM NUMERIC SIGN EIGHT ASH;Nl;0;L;;;;8;N;;;;; +12407;CUNEIFORM NUMERIC SIGN NINE ASH;Nl;0;L;;;;9;N;;;;; +12408;CUNEIFORM NUMERIC SIGN THREE DISH;Nl;0;L;;;;3;N;;;;; +12409;CUNEIFORM NUMERIC SIGN FOUR DISH;Nl;0;L;;;;4;N;;;;; +1240A;CUNEIFORM NUMERIC SIGN FIVE DISH;Nl;0;L;;;;5;N;;;;; +1240B;CUNEIFORM NUMERIC SIGN SIX DISH;Nl;0;L;;;;6;N;;;;; +1240C;CUNEIFORM NUMERIC SIGN SEVEN DISH;Nl;0;L;;;;7;N;;;;; +1240D;CUNEIFORM NUMERIC SIGN EIGHT DISH;Nl;0;L;;;;8;N;;;;; +1240E;CUNEIFORM NUMERIC SIGN NINE DISH;Nl;0;L;;;;9;N;;;;; +1240F;CUNEIFORM NUMERIC SIGN FOUR U;Nl;0;L;;;;4;N;;;;; +12410;CUNEIFORM NUMERIC SIGN FIVE U;Nl;0;L;;;;5;N;;;;; +12411;CUNEIFORM NUMERIC SIGN SIX U;Nl;0;L;;;;6;N;;;;; +12412;CUNEIFORM NUMERIC SIGN SEVEN U;Nl;0;L;;;;7;N;;;;; +12413;CUNEIFORM NUMERIC SIGN EIGHT U;Nl;0;L;;;;8;N;;;;; +12414;CUNEIFORM NUMERIC SIGN NINE U;Nl;0;L;;;;9;N;;;;; +12415;CUNEIFORM NUMERIC SIGN ONE GESH2;Nl;0;L;;;;1;N;;;;; +12416;CUNEIFORM NUMERIC SIGN TWO GESH2;Nl;0;L;;;;2;N;;;;; +12417;CUNEIFORM NUMERIC SIGN THREE GESH2;Nl;0;L;;;;3;N;;;;; +12418;CUNEIFORM NUMERIC SIGN FOUR GESH2;Nl;0;L;;;;4;N;;;;; +12419;CUNEIFORM NUMERIC SIGN FIVE GESH2;Nl;0;L;;;;5;N;;;;; +1241A;CUNEIFORM NUMERIC SIGN SIX GESH2;Nl;0;L;;;;6;N;;;;; +1241B;CUNEIFORM NUMERIC SIGN SEVEN GESH2;Nl;0;L;;;;7;N;;;;; +1241C;CUNEIFORM NUMERIC SIGN EIGHT GESH2;Nl;0;L;;;;8;N;;;;; +1241D;CUNEIFORM NUMERIC SIGN NINE GESH2;Nl;0;L;;;;9;N;;;;; +1241E;CUNEIFORM NUMERIC SIGN ONE GESHU;Nl;0;L;;;;1;N;;;;; +1241F;CUNEIFORM NUMERIC SIGN TWO GESHU;Nl;0;L;;;;2;N;;;;; +12420;CUNEIFORM NUMERIC SIGN THREE GESHU;Nl;0;L;;;;3;N;;;;; +12421;CUNEIFORM NUMERIC SIGN FOUR GESHU;Nl;0;L;;;;4;N;;;;; +12422;CUNEIFORM NUMERIC SIGN FIVE GESHU;Nl;0;L;;;;5;N;;;;; +12423;CUNEIFORM NUMERIC SIGN TWO SHAR2;Nl;0;L;;;;2;N;;;;; +12424;CUNEIFORM NUMERIC SIGN THREE SHAR2;Nl;0;L;;;;3;N;;;;; +12425;CUNEIFORM NUMERIC SIGN THREE SHAR2 VARIANT FORM;Nl;0;L;;;;3;N;;;;; +12426;CUNEIFORM NUMERIC SIGN FOUR SHAR2;Nl;0;L;;;;4;N;;;;; +12427;CUNEIFORM NUMERIC SIGN FIVE SHAR2;Nl;0;L;;;;5;N;;;;; +12428;CUNEIFORM NUMERIC SIGN SIX SHAR2;Nl;0;L;;;;6;N;;;;; +12429;CUNEIFORM NUMERIC SIGN SEVEN SHAR2;Nl;0;L;;;;7;N;;;;; +1242A;CUNEIFORM NUMERIC SIGN EIGHT SHAR2;Nl;0;L;;;;8;N;;;;; +1242B;CUNEIFORM NUMERIC SIGN NINE SHAR2;Nl;0;L;;;;9;N;;;;; +1242C;CUNEIFORM NUMERIC SIGN ONE SHARU;Nl;0;L;;;;1;N;;;;; +1242D;CUNEIFORM NUMERIC SIGN TWO SHARU;Nl;0;L;;;;2;N;;;;; +1242E;CUNEIFORM NUMERIC SIGN THREE SHARU;Nl;0;L;;;;3;N;;;;; +1242F;CUNEIFORM NUMERIC SIGN THREE SHARU VARIANT FORM;Nl;0;L;;;;3;N;;;;; +12430;CUNEIFORM NUMERIC SIGN FOUR SHARU;Nl;0;L;;;;4;N;;;;; +12431;CUNEIFORM NUMERIC SIGN FIVE SHARU;Nl;0;L;;;;5;N;;;;; +12432;CUNEIFORM NUMERIC SIGN SHAR2 TIMES GAL PLUS DISH;Nl;0;L;;;;;N;;;;; +12433;CUNEIFORM NUMERIC SIGN SHAR2 TIMES GAL PLUS MIN;Nl;0;L;;;;;N;;;;; +12434;CUNEIFORM NUMERIC SIGN ONE BURU;Nl;0;L;;;;1;N;;;;; +12435;CUNEIFORM NUMERIC SIGN TWO BURU;Nl;0;L;;;;2;N;;;;; +12436;CUNEIFORM NUMERIC SIGN THREE BURU;Nl;0;L;;;;3;N;;;;; +12437;CUNEIFORM NUMERIC SIGN THREE BURU VARIANT FORM;Nl;0;L;;;;3;N;;;;; +12438;CUNEIFORM NUMERIC SIGN FOUR BURU;Nl;0;L;;;;4;N;;;;; +12439;CUNEIFORM NUMERIC SIGN FIVE BURU;Nl;0;L;;;;5;N;;;;; +1243A;CUNEIFORM NUMERIC SIGN THREE VARIANT FORM ESH16;Nl;0;L;;;;3;N;;;;; +1243B;CUNEIFORM NUMERIC SIGN THREE VARIANT FORM ESH21;Nl;0;L;;;;3;N;;;;; +1243C;CUNEIFORM NUMERIC SIGN FOUR VARIANT FORM LIMMU;Nl;0;L;;;;4;N;;;;; +1243D;CUNEIFORM NUMERIC SIGN FOUR VARIANT FORM LIMMU4;Nl;0;L;;;;4;N;;;;; +1243E;CUNEIFORM NUMERIC SIGN FOUR VARIANT FORM LIMMU A;Nl;0;L;;;;4;N;;;;; +1243F;CUNEIFORM NUMERIC SIGN FOUR VARIANT FORM LIMMU B;Nl;0;L;;;;4;N;;;;; +12440;CUNEIFORM NUMERIC SIGN SIX VARIANT FORM ASH9;Nl;0;L;;;;6;N;;;;; +12441;CUNEIFORM NUMERIC SIGN SEVEN VARIANT FORM IMIN3;Nl;0;L;;;;7;N;;;;; +12442;CUNEIFORM NUMERIC SIGN SEVEN VARIANT FORM IMIN A;Nl;0;L;;;;7;N;;;;; +12443;CUNEIFORM NUMERIC SIGN SEVEN VARIANT FORM IMIN B;Nl;0;L;;;;7;N;;;;; +12444;CUNEIFORM NUMERIC SIGN EIGHT VARIANT FORM USSU;Nl;0;L;;;;8;N;;;;; +12445;CUNEIFORM NUMERIC SIGN EIGHT VARIANT FORM USSU3;Nl;0;L;;;;8;N;;;;; +12446;CUNEIFORM NUMERIC SIGN NINE VARIANT FORM ILIMMU;Nl;0;L;;;;9;N;;;;; +12447;CUNEIFORM NUMERIC SIGN NINE VARIANT FORM ILIMMU3;Nl;0;L;;;;9;N;;;;; +12448;CUNEIFORM NUMERIC SIGN NINE VARIANT FORM ILIMMU4;Nl;0;L;;;;9;N;;;;; +12449;CUNEIFORM NUMERIC SIGN NINE VARIANT FORM ILIMMU A;Nl;0;L;;;;9;N;;;;; +1244A;CUNEIFORM NUMERIC SIGN TWO ASH TENU;Nl;0;L;;;;2;N;;;;; +1244B;CUNEIFORM NUMERIC SIGN THREE ASH TENU;Nl;0;L;;;;3;N;;;;; +1244C;CUNEIFORM NUMERIC SIGN FOUR ASH TENU;Nl;0;L;;;;4;N;;;;; +1244D;CUNEIFORM NUMERIC SIGN FIVE ASH TENU;Nl;0;L;;;;5;N;;;;; +1244E;CUNEIFORM NUMERIC SIGN SIX ASH TENU;Nl;0;L;;;;6;N;;;;; +1244F;CUNEIFORM NUMERIC SIGN ONE BAN2;Nl;0;L;;;;1;N;;;;; +12450;CUNEIFORM NUMERIC SIGN TWO BAN2;Nl;0;L;;;;2;N;;;;; +12451;CUNEIFORM NUMERIC SIGN THREE BAN2;Nl;0;L;;;;3;N;;;;; +12452;CUNEIFORM NUMERIC SIGN FOUR BAN2;Nl;0;L;;;;4;N;;;;; +12453;CUNEIFORM NUMERIC SIGN FOUR BAN2 VARIANT FORM;Nl;0;L;;;;4;N;;;;; +12454;CUNEIFORM NUMERIC SIGN FIVE BAN2;Nl;0;L;;;;5;N;;;;; +12455;CUNEIFORM NUMERIC SIGN FIVE BAN2 VARIANT FORM;Nl;0;L;;;;5;N;;;;; +12456;CUNEIFORM NUMERIC SIGN NIGIDAMIN;Nl;0;L;;;;;N;;;;; +12457;CUNEIFORM NUMERIC SIGN NIGIDAESH;Nl;0;L;;;;;N;;;;; +12458;CUNEIFORM NUMERIC SIGN ONE ESHE3;Nl;0;L;;;;1;N;;;;; +12459;CUNEIFORM NUMERIC SIGN TWO ESHE3;Nl;0;L;;;;2;N;;;;; +1245A;CUNEIFORM NUMERIC SIGN ONE THIRD DISH;Nl;0;L;;;;1/3;N;;;;; +1245B;CUNEIFORM NUMERIC SIGN TWO THIRDS DISH;Nl;0;L;;;;2/3;N;;;;; +1245C;CUNEIFORM NUMERIC SIGN FIVE SIXTHS DISH;Nl;0;L;;;;5/6;N;;;;; +1245D;CUNEIFORM NUMERIC SIGN ONE THIRD VARIANT FORM A;Nl;0;L;;;;1/3;N;;;;; +1245E;CUNEIFORM NUMERIC SIGN TWO THIRDS VARIANT FORM A;Nl;0;L;;;;2/3;N;;;;; +1245F;CUNEIFORM NUMERIC SIGN ONE EIGHTH ASH;Nl;0;L;;;;1/8;N;;;;; +12460;CUNEIFORM NUMERIC SIGN ONE QUARTER ASH;Nl;0;L;;;;1/4;N;;;;; +12461;CUNEIFORM NUMERIC SIGN OLD ASSYRIAN ONE SIXTH;Nl;0;L;;;;1/6;N;;;;; +12462;CUNEIFORM NUMERIC SIGN OLD ASSYRIAN ONE QUARTER;Nl;0;L;;;;1/4;N;;;;; +12470;CUNEIFORM PUNCTUATION SIGN OLD ASSYRIAN WORD DIVIDER;Po;0;L;;;;;N;;;;; +12471;CUNEIFORM PUNCTUATION SIGN VERTICAL COLON;Po;0;L;;;;;N;;;;; +12472;CUNEIFORM PUNCTUATION SIGN DIAGONAL COLON;Po;0;L;;;;;N;;;;; +12473;CUNEIFORM PUNCTUATION SIGN DIAGONAL TRICOLON;Po;0;L;;;;;N;;;;; +13000;EGYPTIAN HIEROGLYPH A001;Lo;0;L;;;;;N;;;;; +13001;EGYPTIAN HIEROGLYPH A002;Lo;0;L;;;;;N;;;;; +13002;EGYPTIAN HIEROGLYPH A003;Lo;0;L;;;;;N;;;;; +13003;EGYPTIAN HIEROGLYPH A004;Lo;0;L;;;;;N;;;;; +13004;EGYPTIAN HIEROGLYPH A005;Lo;0;L;;;;;N;;;;; +13005;EGYPTIAN HIEROGLYPH A005A;Lo;0;L;;;;;N;;;;; +13006;EGYPTIAN HIEROGLYPH A006;Lo;0;L;;;;;N;;;;; +13007;EGYPTIAN HIEROGLYPH A006A;Lo;0;L;;;;;N;;;;; +13008;EGYPTIAN HIEROGLYPH A006B;Lo;0;L;;;;;N;;;;; +13009;EGYPTIAN HIEROGLYPH A007;Lo;0;L;;;;;N;;;;; +1300A;EGYPTIAN HIEROGLYPH A008;Lo;0;L;;;;;N;;;;; +1300B;EGYPTIAN HIEROGLYPH A009;Lo;0;L;;;;;N;;;;; +1300C;EGYPTIAN HIEROGLYPH A010;Lo;0;L;;;;;N;;;;; +1300D;EGYPTIAN HIEROGLYPH A011;Lo;0;L;;;;;N;;;;; +1300E;EGYPTIAN HIEROGLYPH A012;Lo;0;L;;;;;N;;;;; +1300F;EGYPTIAN HIEROGLYPH A013;Lo;0;L;;;;;N;;;;; +13010;EGYPTIAN HIEROGLYPH A014;Lo;0;L;;;;;N;;;;; +13011;EGYPTIAN HIEROGLYPH A014A;Lo;0;L;;;;;N;;;;; +13012;EGYPTIAN HIEROGLYPH A015;Lo;0;L;;;;;N;;;;; +13013;EGYPTIAN HIEROGLYPH A016;Lo;0;L;;;;;N;;;;; +13014;EGYPTIAN HIEROGLYPH A017;Lo;0;L;;;;;N;;;;; +13015;EGYPTIAN HIEROGLYPH A017A;Lo;0;L;;;;;N;;;;; +13016;EGYPTIAN HIEROGLYPH A018;Lo;0;L;;;;;N;;;;; +13017;EGYPTIAN HIEROGLYPH A019;Lo;0;L;;;;;N;;;;; +13018;EGYPTIAN HIEROGLYPH A020;Lo;0;L;;;;;N;;;;; +13019;EGYPTIAN HIEROGLYPH A021;Lo;0;L;;;;;N;;;;; +1301A;EGYPTIAN HIEROGLYPH A022;Lo;0;L;;;;;N;;;;; +1301B;EGYPTIAN HIEROGLYPH A023;Lo;0;L;;;;;N;;;;; +1301C;EGYPTIAN HIEROGLYPH A024;Lo;0;L;;;;;N;;;;; +1301D;EGYPTIAN HIEROGLYPH A025;Lo;0;L;;;;;N;;;;; +1301E;EGYPTIAN HIEROGLYPH A026;Lo;0;L;;;;;N;;;;; +1301F;EGYPTIAN HIEROGLYPH A027;Lo;0;L;;;;;N;;;;; +13020;EGYPTIAN HIEROGLYPH A028;Lo;0;L;;;;;N;;;;; +13021;EGYPTIAN HIEROGLYPH A029;Lo;0;L;;;;;N;;;;; +13022;EGYPTIAN HIEROGLYPH A030;Lo;0;L;;;;;N;;;;; +13023;EGYPTIAN HIEROGLYPH A031;Lo;0;L;;;;;N;;;;; +13024;EGYPTIAN HIEROGLYPH A032;Lo;0;L;;;;;N;;;;; +13025;EGYPTIAN HIEROGLYPH A032A;Lo;0;L;;;;;N;;;;; +13026;EGYPTIAN HIEROGLYPH A033;Lo;0;L;;;;;N;;;;; +13027;EGYPTIAN HIEROGLYPH A034;Lo;0;L;;;;;N;;;;; +13028;EGYPTIAN HIEROGLYPH A035;Lo;0;L;;;;;N;;;;; +13029;EGYPTIAN HIEROGLYPH A036;Lo;0;L;;;;;N;;;;; +1302A;EGYPTIAN HIEROGLYPH A037;Lo;0;L;;;;;N;;;;; +1302B;EGYPTIAN HIEROGLYPH A038;Lo;0;L;;;;;N;;;;; +1302C;EGYPTIAN HIEROGLYPH A039;Lo;0;L;;;;;N;;;;; +1302D;EGYPTIAN HIEROGLYPH A040;Lo;0;L;;;;;N;;;;; +1302E;EGYPTIAN HIEROGLYPH A040A;Lo;0;L;;;;;N;;;;; +1302F;EGYPTIAN HIEROGLYPH A041;Lo;0;L;;;;;N;;;;; +13030;EGYPTIAN HIEROGLYPH A042;Lo;0;L;;;;;N;;;;; +13031;EGYPTIAN HIEROGLYPH A042A;Lo;0;L;;;;;N;;;;; +13032;EGYPTIAN HIEROGLYPH A043;Lo;0;L;;;;;N;;;;; +13033;EGYPTIAN HIEROGLYPH A043A;Lo;0;L;;;;;N;;;;; +13034;EGYPTIAN HIEROGLYPH A044;Lo;0;L;;;;;N;;;;; +13035;EGYPTIAN HIEROGLYPH A045;Lo;0;L;;;;;N;;;;; +13036;EGYPTIAN HIEROGLYPH A045A;Lo;0;L;;;;;N;;;;; +13037;EGYPTIAN HIEROGLYPH A046;Lo;0;L;;;;;N;;;;; +13038;EGYPTIAN HIEROGLYPH A047;Lo;0;L;;;;;N;;;;; +13039;EGYPTIAN HIEROGLYPH A048;Lo;0;L;;;;;N;;;;; +1303A;EGYPTIAN HIEROGLYPH A049;Lo;0;L;;;;;N;;;;; +1303B;EGYPTIAN HIEROGLYPH A050;Lo;0;L;;;;;N;;;;; +1303C;EGYPTIAN HIEROGLYPH A051;Lo;0;L;;;;;N;;;;; +1303D;EGYPTIAN HIEROGLYPH A052;Lo;0;L;;;;;N;;;;; +1303E;EGYPTIAN HIEROGLYPH A053;Lo;0;L;;;;;N;;;;; +1303F;EGYPTIAN HIEROGLYPH A054;Lo;0;L;;;;;N;;;;; +13040;EGYPTIAN HIEROGLYPH A055;Lo;0;L;;;;;N;;;;; +13041;EGYPTIAN HIEROGLYPH A056;Lo;0;L;;;;;N;;;;; +13042;EGYPTIAN HIEROGLYPH A057;Lo;0;L;;;;;N;;;;; +13043;EGYPTIAN HIEROGLYPH A058;Lo;0;L;;;;;N;;;;; +13044;EGYPTIAN HIEROGLYPH A059;Lo;0;L;;;;;N;;;;; +13045;EGYPTIAN HIEROGLYPH A060;Lo;0;L;;;;;N;;;;; +13046;EGYPTIAN HIEROGLYPH A061;Lo;0;L;;;;;N;;;;; +13047;EGYPTIAN HIEROGLYPH A062;Lo;0;L;;;;;N;;;;; +13048;EGYPTIAN HIEROGLYPH A063;Lo;0;L;;;;;N;;;;; +13049;EGYPTIAN HIEROGLYPH A064;Lo;0;L;;;;;N;;;;; +1304A;EGYPTIAN HIEROGLYPH A065;Lo;0;L;;;;;N;;;;; +1304B;EGYPTIAN HIEROGLYPH A066;Lo;0;L;;;;;N;;;;; +1304C;EGYPTIAN HIEROGLYPH A067;Lo;0;L;;;;;N;;;;; +1304D;EGYPTIAN HIEROGLYPH A068;Lo;0;L;;;;;N;;;;; +1304E;EGYPTIAN HIEROGLYPH A069;Lo;0;L;;;;;N;;;;; +1304F;EGYPTIAN HIEROGLYPH A070;Lo;0;L;;;;;N;;;;; +13050;EGYPTIAN HIEROGLYPH B001;Lo;0;L;;;;;N;;;;; +13051;EGYPTIAN HIEROGLYPH B002;Lo;0;L;;;;;N;;;;; +13052;EGYPTIAN HIEROGLYPH B003;Lo;0;L;;;;;N;;;;; +13053;EGYPTIAN HIEROGLYPH B004;Lo;0;L;;;;;N;;;;; +13054;EGYPTIAN HIEROGLYPH B005;Lo;0;L;;;;;N;;;;; +13055;EGYPTIAN HIEROGLYPH B005A;Lo;0;L;;;;;N;;;;; +13056;EGYPTIAN HIEROGLYPH B006;Lo;0;L;;;;;N;;;;; +13057;EGYPTIAN HIEROGLYPH B007;Lo;0;L;;;;;N;;;;; +13058;EGYPTIAN HIEROGLYPH B008;Lo;0;L;;;;;N;;;;; +13059;EGYPTIAN HIEROGLYPH B009;Lo;0;L;;;;;N;;;;; +1305A;EGYPTIAN HIEROGLYPH C001;Lo;0;L;;;;;N;;;;; +1305B;EGYPTIAN HIEROGLYPH C002;Lo;0;L;;;;;N;;;;; +1305C;EGYPTIAN HIEROGLYPH C002A;Lo;0;L;;;;;N;;;;; +1305D;EGYPTIAN HIEROGLYPH C002B;Lo;0;L;;;;;N;;;;; +1305E;EGYPTIAN HIEROGLYPH C002C;Lo;0;L;;;;;N;;;;; +1305F;EGYPTIAN HIEROGLYPH C003;Lo;0;L;;;;;N;;;;; +13060;EGYPTIAN HIEROGLYPH C004;Lo;0;L;;;;;N;;;;; +13061;EGYPTIAN HIEROGLYPH C005;Lo;0;L;;;;;N;;;;; +13062;EGYPTIAN HIEROGLYPH C006;Lo;0;L;;;;;N;;;;; +13063;EGYPTIAN HIEROGLYPH C007;Lo;0;L;;;;;N;;;;; +13064;EGYPTIAN HIEROGLYPH C008;Lo;0;L;;;;;N;;;;; +13065;EGYPTIAN HIEROGLYPH C009;Lo;0;L;;;;;N;;;;; +13066;EGYPTIAN HIEROGLYPH C010;Lo;0;L;;;;;N;;;;; +13067;EGYPTIAN HIEROGLYPH C010A;Lo;0;L;;;;;N;;;;; +13068;EGYPTIAN HIEROGLYPH C011;Lo;0;L;;;;;N;;;;; +13069;EGYPTIAN HIEROGLYPH C012;Lo;0;L;;;;;N;;;;; +1306A;EGYPTIAN HIEROGLYPH C013;Lo;0;L;;;;;N;;;;; +1306B;EGYPTIAN HIEROGLYPH C014;Lo;0;L;;;;;N;;;;; +1306C;EGYPTIAN HIEROGLYPH C015;Lo;0;L;;;;;N;;;;; +1306D;EGYPTIAN HIEROGLYPH C016;Lo;0;L;;;;;N;;;;; +1306E;EGYPTIAN HIEROGLYPH C017;Lo;0;L;;;;;N;;;;; +1306F;EGYPTIAN HIEROGLYPH C018;Lo;0;L;;;;;N;;;;; +13070;EGYPTIAN HIEROGLYPH C019;Lo;0;L;;;;;N;;;;; +13071;EGYPTIAN HIEROGLYPH C020;Lo;0;L;;;;;N;;;;; +13072;EGYPTIAN HIEROGLYPH C021;Lo;0;L;;;;;N;;;;; +13073;EGYPTIAN HIEROGLYPH C022;Lo;0;L;;;;;N;;;;; +13074;EGYPTIAN HIEROGLYPH C023;Lo;0;L;;;;;N;;;;; +13075;EGYPTIAN HIEROGLYPH C024;Lo;0;L;;;;;N;;;;; +13076;EGYPTIAN HIEROGLYPH D001;Lo;0;L;;;;;N;;;;; +13077;EGYPTIAN HIEROGLYPH D002;Lo;0;L;;;;;N;;;;; +13078;EGYPTIAN HIEROGLYPH D003;Lo;0;L;;;;;N;;;;; +13079;EGYPTIAN HIEROGLYPH D004;Lo;0;L;;;;;N;;;;; +1307A;EGYPTIAN HIEROGLYPH D005;Lo;0;L;;;;;N;;;;; +1307B;EGYPTIAN HIEROGLYPH D006;Lo;0;L;;;;;N;;;;; +1307C;EGYPTIAN HIEROGLYPH D007;Lo;0;L;;;;;N;;;;; +1307D;EGYPTIAN HIEROGLYPH D008;Lo;0;L;;;;;N;;;;; +1307E;EGYPTIAN HIEROGLYPH D008A;Lo;0;L;;;;;N;;;;; +1307F;EGYPTIAN HIEROGLYPH D009;Lo;0;L;;;;;N;;;;; +13080;EGYPTIAN HIEROGLYPH D010;Lo;0;L;;;;;N;;;;; +13081;EGYPTIAN HIEROGLYPH D011;Lo;0;L;;;;;N;;;;; +13082;EGYPTIAN HIEROGLYPH D012;Lo;0;L;;;;;N;;;;; +13083;EGYPTIAN HIEROGLYPH D013;Lo;0;L;;;;;N;;;;; +13084;EGYPTIAN HIEROGLYPH D014;Lo;0;L;;;;;N;;;;; +13085;EGYPTIAN HIEROGLYPH D015;Lo;0;L;;;;;N;;;;; +13086;EGYPTIAN HIEROGLYPH D016;Lo;0;L;;;;;N;;;;; +13087;EGYPTIAN HIEROGLYPH D017;Lo;0;L;;;;;N;;;;; +13088;EGYPTIAN HIEROGLYPH D018;Lo;0;L;;;;;N;;;;; +13089;EGYPTIAN HIEROGLYPH D019;Lo;0;L;;;;;N;;;;; +1308A;EGYPTIAN HIEROGLYPH D020;Lo;0;L;;;;;N;;;;; +1308B;EGYPTIAN HIEROGLYPH D021;Lo;0;L;;;;;N;;;;; +1308C;EGYPTIAN HIEROGLYPH D022;Lo;0;L;;;;;N;;;;; +1308D;EGYPTIAN HIEROGLYPH D023;Lo;0;L;;;;;N;;;;; +1308E;EGYPTIAN HIEROGLYPH D024;Lo;0;L;;;;;N;;;;; +1308F;EGYPTIAN HIEROGLYPH D025;Lo;0;L;;;;;N;;;;; +13090;EGYPTIAN HIEROGLYPH D026;Lo;0;L;;;;;N;;;;; +13091;EGYPTIAN HIEROGLYPH D027;Lo;0;L;;;;;N;;;;; +13092;EGYPTIAN HIEROGLYPH D027A;Lo;0;L;;;;;N;;;;; +13093;EGYPTIAN HIEROGLYPH D028;Lo;0;L;;;;;N;;;;; +13094;EGYPTIAN HIEROGLYPH D029;Lo;0;L;;;;;N;;;;; +13095;EGYPTIAN HIEROGLYPH D030;Lo;0;L;;;;;N;;;;; +13096;EGYPTIAN HIEROGLYPH D031;Lo;0;L;;;;;N;;;;; +13097;EGYPTIAN HIEROGLYPH D031A;Lo;0;L;;;;;N;;;;; +13098;EGYPTIAN HIEROGLYPH D032;Lo;0;L;;;;;N;;;;; +13099;EGYPTIAN HIEROGLYPH D033;Lo;0;L;;;;;N;;;;; +1309A;EGYPTIAN HIEROGLYPH D034;Lo;0;L;;;;;N;;;;; +1309B;EGYPTIAN HIEROGLYPH D034A;Lo;0;L;;;;;N;;;;; +1309C;EGYPTIAN HIEROGLYPH D035;Lo;0;L;;;;;N;;;;; +1309D;EGYPTIAN HIEROGLYPH D036;Lo;0;L;;;;;N;;;;; +1309E;EGYPTIAN HIEROGLYPH D037;Lo;0;L;;;;;N;;;;; +1309F;EGYPTIAN HIEROGLYPH D038;Lo;0;L;;;;;N;;;;; +130A0;EGYPTIAN HIEROGLYPH D039;Lo;0;L;;;;;N;;;;; +130A1;EGYPTIAN HIEROGLYPH D040;Lo;0;L;;;;;N;;;;; +130A2;EGYPTIAN HIEROGLYPH D041;Lo;0;L;;;;;N;;;;; +130A3;EGYPTIAN HIEROGLYPH D042;Lo;0;L;;;;;N;;;;; +130A4;EGYPTIAN HIEROGLYPH D043;Lo;0;L;;;;;N;;;;; +130A5;EGYPTIAN HIEROGLYPH D044;Lo;0;L;;;;;N;;;;; +130A6;EGYPTIAN HIEROGLYPH D045;Lo;0;L;;;;;N;;;;; +130A7;EGYPTIAN HIEROGLYPH D046;Lo;0;L;;;;;N;;;;; +130A8;EGYPTIAN HIEROGLYPH D046A;Lo;0;L;;;;;N;;;;; +130A9;EGYPTIAN HIEROGLYPH D047;Lo;0;L;;;;;N;;;;; +130AA;EGYPTIAN HIEROGLYPH D048;Lo;0;L;;;;;N;;;;; +130AB;EGYPTIAN HIEROGLYPH D048A;Lo;0;L;;;;;N;;;;; +130AC;EGYPTIAN HIEROGLYPH D049;Lo;0;L;;;;;N;;;;; +130AD;EGYPTIAN HIEROGLYPH D050;Lo;0;L;;;;;N;;;;; +130AE;EGYPTIAN HIEROGLYPH D050A;Lo;0;L;;;;;N;;;;; +130AF;EGYPTIAN HIEROGLYPH D050B;Lo;0;L;;;;;N;;;;; +130B0;EGYPTIAN HIEROGLYPH D050C;Lo;0;L;;;;;N;;;;; +130B1;EGYPTIAN HIEROGLYPH D050D;Lo;0;L;;;;;N;;;;; +130B2;EGYPTIAN HIEROGLYPH D050E;Lo;0;L;;;;;N;;;;; +130B3;EGYPTIAN HIEROGLYPH D050F;Lo;0;L;;;;;N;;;;; +130B4;EGYPTIAN HIEROGLYPH D050G;Lo;0;L;;;;;N;;;;; +130B5;EGYPTIAN HIEROGLYPH D050H;Lo;0;L;;;;;N;;;;; +130B6;EGYPTIAN HIEROGLYPH D050I;Lo;0;L;;;;;N;;;;; +130B7;EGYPTIAN HIEROGLYPH D051;Lo;0;L;;;;;N;;;;; +130B8;EGYPTIAN HIEROGLYPH D052;Lo;0;L;;;;;N;;;;; +130B9;EGYPTIAN HIEROGLYPH D052A;Lo;0;L;;;;;N;;;;; +130BA;EGYPTIAN HIEROGLYPH D053;Lo;0;L;;;;;N;;;;; +130BB;EGYPTIAN HIEROGLYPH D054;Lo;0;L;;;;;N;;;;; +130BC;EGYPTIAN HIEROGLYPH D054A;Lo;0;L;;;;;N;;;;; +130BD;EGYPTIAN HIEROGLYPH D055;Lo;0;L;;;;;N;;;;; +130BE;EGYPTIAN HIEROGLYPH D056;Lo;0;L;;;;;N;;;;; +130BF;EGYPTIAN HIEROGLYPH D057;Lo;0;L;;;;;N;;;;; +130C0;EGYPTIAN HIEROGLYPH D058;Lo;0;L;;;;;N;;;;; +130C1;EGYPTIAN HIEROGLYPH D059;Lo;0;L;;;;;N;;;;; +130C2;EGYPTIAN HIEROGLYPH D060;Lo;0;L;;;;;N;;;;; +130C3;EGYPTIAN HIEROGLYPH D061;Lo;0;L;;;;;N;;;;; +130C4;EGYPTIAN HIEROGLYPH D062;Lo;0;L;;;;;N;;;;; +130C5;EGYPTIAN HIEROGLYPH D063;Lo;0;L;;;;;N;;;;; +130C6;EGYPTIAN HIEROGLYPH D064;Lo;0;L;;;;;N;;;;; +130C7;EGYPTIAN HIEROGLYPH D065;Lo;0;L;;;;;N;;;;; +130C8;EGYPTIAN HIEROGLYPH D066;Lo;0;L;;;;;N;;;;; +130C9;EGYPTIAN HIEROGLYPH D067;Lo;0;L;;;;;N;;;;; +130CA;EGYPTIAN HIEROGLYPH D067A;Lo;0;L;;;;;N;;;;; +130CB;EGYPTIAN HIEROGLYPH D067B;Lo;0;L;;;;;N;;;;; +130CC;EGYPTIAN HIEROGLYPH D067C;Lo;0;L;;;;;N;;;;; +130CD;EGYPTIAN HIEROGLYPH D067D;Lo;0;L;;;;;N;;;;; +130CE;EGYPTIAN HIEROGLYPH D067E;Lo;0;L;;;;;N;;;;; +130CF;EGYPTIAN HIEROGLYPH D067F;Lo;0;L;;;;;N;;;;; +130D0;EGYPTIAN HIEROGLYPH D067G;Lo;0;L;;;;;N;;;;; +130D1;EGYPTIAN HIEROGLYPH D067H;Lo;0;L;;;;;N;;;;; +130D2;EGYPTIAN HIEROGLYPH E001;Lo;0;L;;;;;N;;;;; +130D3;EGYPTIAN HIEROGLYPH E002;Lo;0;L;;;;;N;;;;; +130D4;EGYPTIAN HIEROGLYPH E003;Lo;0;L;;;;;N;;;;; +130D5;EGYPTIAN HIEROGLYPH E004;Lo;0;L;;;;;N;;;;; +130D6;EGYPTIAN HIEROGLYPH E005;Lo;0;L;;;;;N;;;;; +130D7;EGYPTIAN HIEROGLYPH E006;Lo;0;L;;;;;N;;;;; +130D8;EGYPTIAN HIEROGLYPH E007;Lo;0;L;;;;;N;;;;; +130D9;EGYPTIAN HIEROGLYPH E008;Lo;0;L;;;;;N;;;;; +130DA;EGYPTIAN HIEROGLYPH E008A;Lo;0;L;;;;;N;;;;; +130DB;EGYPTIAN HIEROGLYPH E009;Lo;0;L;;;;;N;;;;; +130DC;EGYPTIAN HIEROGLYPH E009A;Lo;0;L;;;;;N;;;;; +130DD;EGYPTIAN HIEROGLYPH E010;Lo;0;L;;;;;N;;;;; +130DE;EGYPTIAN HIEROGLYPH E011;Lo;0;L;;;;;N;;;;; +130DF;EGYPTIAN HIEROGLYPH E012;Lo;0;L;;;;;N;;;;; +130E0;EGYPTIAN HIEROGLYPH E013;Lo;0;L;;;;;N;;;;; +130E1;EGYPTIAN HIEROGLYPH E014;Lo;0;L;;;;;N;;;;; +130E2;EGYPTIAN HIEROGLYPH E015;Lo;0;L;;;;;N;;;;; +130E3;EGYPTIAN HIEROGLYPH E016;Lo;0;L;;;;;N;;;;; +130E4;EGYPTIAN HIEROGLYPH E016A;Lo;0;L;;;;;N;;;;; +130E5;EGYPTIAN HIEROGLYPH E017;Lo;0;L;;;;;N;;;;; +130E6;EGYPTIAN HIEROGLYPH E017A;Lo;0;L;;;;;N;;;;; +130E7;EGYPTIAN HIEROGLYPH E018;Lo;0;L;;;;;N;;;;; +130E8;EGYPTIAN HIEROGLYPH E019;Lo;0;L;;;;;N;;;;; +130E9;EGYPTIAN HIEROGLYPH E020;Lo;0;L;;;;;N;;;;; +130EA;EGYPTIAN HIEROGLYPH E020A;Lo;0;L;;;;;N;;;;; +130EB;EGYPTIAN HIEROGLYPH E021;Lo;0;L;;;;;N;;;;; +130EC;EGYPTIAN HIEROGLYPH E022;Lo;0;L;;;;;N;;;;; +130ED;EGYPTIAN HIEROGLYPH E023;Lo;0;L;;;;;N;;;;; +130EE;EGYPTIAN HIEROGLYPH E024;Lo;0;L;;;;;N;;;;; +130EF;EGYPTIAN HIEROGLYPH E025;Lo;0;L;;;;;N;;;;; +130F0;EGYPTIAN HIEROGLYPH E026;Lo;0;L;;;;;N;;;;; +130F1;EGYPTIAN HIEROGLYPH E027;Lo;0;L;;;;;N;;;;; +130F2;EGYPTIAN HIEROGLYPH E028;Lo;0;L;;;;;N;;;;; +130F3;EGYPTIAN HIEROGLYPH E028A;Lo;0;L;;;;;N;;;;; +130F4;EGYPTIAN HIEROGLYPH E029;Lo;0;L;;;;;N;;;;; +130F5;EGYPTIAN HIEROGLYPH E030;Lo;0;L;;;;;N;;;;; +130F6;EGYPTIAN HIEROGLYPH E031;Lo;0;L;;;;;N;;;;; +130F7;EGYPTIAN HIEROGLYPH E032;Lo;0;L;;;;;N;;;;; +130F8;EGYPTIAN HIEROGLYPH E033;Lo;0;L;;;;;N;;;;; +130F9;EGYPTIAN HIEROGLYPH E034;Lo;0;L;;;;;N;;;;; +130FA;EGYPTIAN HIEROGLYPH E034A;Lo;0;L;;;;;N;;;;; +130FB;EGYPTIAN HIEROGLYPH E036;Lo;0;L;;;;;N;;;;; +130FC;EGYPTIAN HIEROGLYPH E037;Lo;0;L;;;;;N;;;;; +130FD;EGYPTIAN HIEROGLYPH E038;Lo;0;L;;;;;N;;;;; +130FE;EGYPTIAN HIEROGLYPH F001;Lo;0;L;;;;;N;;;;; +130FF;EGYPTIAN HIEROGLYPH F001A;Lo;0;L;;;;;N;;;;; +13100;EGYPTIAN HIEROGLYPH F002;Lo;0;L;;;;;N;;;;; +13101;EGYPTIAN HIEROGLYPH F003;Lo;0;L;;;;;N;;;;; +13102;EGYPTIAN HIEROGLYPH F004;Lo;0;L;;;;;N;;;;; +13103;EGYPTIAN HIEROGLYPH F005;Lo;0;L;;;;;N;;;;; +13104;EGYPTIAN HIEROGLYPH F006;Lo;0;L;;;;;N;;;;; +13105;EGYPTIAN HIEROGLYPH F007;Lo;0;L;;;;;N;;;;; +13106;EGYPTIAN HIEROGLYPH F008;Lo;0;L;;;;;N;;;;; +13107;EGYPTIAN HIEROGLYPH F009;Lo;0;L;;;;;N;;;;; +13108;EGYPTIAN HIEROGLYPH F010;Lo;0;L;;;;;N;;;;; +13109;EGYPTIAN HIEROGLYPH F011;Lo;0;L;;;;;N;;;;; +1310A;EGYPTIAN HIEROGLYPH F012;Lo;0;L;;;;;N;;;;; +1310B;EGYPTIAN HIEROGLYPH F013;Lo;0;L;;;;;N;;;;; +1310C;EGYPTIAN HIEROGLYPH F013A;Lo;0;L;;;;;N;;;;; +1310D;EGYPTIAN HIEROGLYPH F014;Lo;0;L;;;;;N;;;;; +1310E;EGYPTIAN HIEROGLYPH F015;Lo;0;L;;;;;N;;;;; +1310F;EGYPTIAN HIEROGLYPH F016;Lo;0;L;;;;;N;;;;; +13110;EGYPTIAN HIEROGLYPH F017;Lo;0;L;;;;;N;;;;; +13111;EGYPTIAN HIEROGLYPH F018;Lo;0;L;;;;;N;;;;; +13112;EGYPTIAN HIEROGLYPH F019;Lo;0;L;;;;;N;;;;; +13113;EGYPTIAN HIEROGLYPH F020;Lo;0;L;;;;;N;;;;; +13114;EGYPTIAN HIEROGLYPH F021;Lo;0;L;;;;;N;;;;; +13115;EGYPTIAN HIEROGLYPH F021A;Lo;0;L;;;;;N;;;;; +13116;EGYPTIAN HIEROGLYPH F022;Lo;0;L;;;;;N;;;;; +13117;EGYPTIAN HIEROGLYPH F023;Lo;0;L;;;;;N;;;;; +13118;EGYPTIAN HIEROGLYPH F024;Lo;0;L;;;;;N;;;;; +13119;EGYPTIAN HIEROGLYPH F025;Lo;0;L;;;;;N;;;;; +1311A;EGYPTIAN HIEROGLYPH F026;Lo;0;L;;;;;N;;;;; +1311B;EGYPTIAN HIEROGLYPH F027;Lo;0;L;;;;;N;;;;; +1311C;EGYPTIAN HIEROGLYPH F028;Lo;0;L;;;;;N;;;;; +1311D;EGYPTIAN HIEROGLYPH F029;Lo;0;L;;;;;N;;;;; +1311E;EGYPTIAN HIEROGLYPH F030;Lo;0;L;;;;;N;;;;; +1311F;EGYPTIAN HIEROGLYPH F031;Lo;0;L;;;;;N;;;;; +13120;EGYPTIAN HIEROGLYPH F031A;Lo;0;L;;;;;N;;;;; +13121;EGYPTIAN HIEROGLYPH F032;Lo;0;L;;;;;N;;;;; +13122;EGYPTIAN HIEROGLYPH F033;Lo;0;L;;;;;N;;;;; +13123;EGYPTIAN HIEROGLYPH F034;Lo;0;L;;;;;N;;;;; +13124;EGYPTIAN HIEROGLYPH F035;Lo;0;L;;;;;N;;;;; +13125;EGYPTIAN HIEROGLYPH F036;Lo;0;L;;;;;N;;;;; +13126;EGYPTIAN HIEROGLYPH F037;Lo;0;L;;;;;N;;;;; +13127;EGYPTIAN HIEROGLYPH F037A;Lo;0;L;;;;;N;;;;; +13128;EGYPTIAN HIEROGLYPH F038;Lo;0;L;;;;;N;;;;; +13129;EGYPTIAN HIEROGLYPH F038A;Lo;0;L;;;;;N;;;;; +1312A;EGYPTIAN HIEROGLYPH F039;Lo;0;L;;;;;N;;;;; +1312B;EGYPTIAN HIEROGLYPH F040;Lo;0;L;;;;;N;;;;; +1312C;EGYPTIAN HIEROGLYPH F041;Lo;0;L;;;;;N;;;;; +1312D;EGYPTIAN HIEROGLYPH F042;Lo;0;L;;;;;N;;;;; +1312E;EGYPTIAN HIEROGLYPH F043;Lo;0;L;;;;;N;;;;; +1312F;EGYPTIAN HIEROGLYPH F044;Lo;0;L;;;;;N;;;;; +13130;EGYPTIAN HIEROGLYPH F045;Lo;0;L;;;;;N;;;;; +13131;EGYPTIAN HIEROGLYPH F045A;Lo;0;L;;;;;N;;;;; +13132;EGYPTIAN HIEROGLYPH F046;Lo;0;L;;;;;N;;;;; +13133;EGYPTIAN HIEROGLYPH F046A;Lo;0;L;;;;;N;;;;; +13134;EGYPTIAN HIEROGLYPH F047;Lo;0;L;;;;;N;;;;; +13135;EGYPTIAN HIEROGLYPH F047A;Lo;0;L;;;;;N;;;;; +13136;EGYPTIAN HIEROGLYPH F048;Lo;0;L;;;;;N;;;;; +13137;EGYPTIAN HIEROGLYPH F049;Lo;0;L;;;;;N;;;;; +13138;EGYPTIAN HIEROGLYPH F050;Lo;0;L;;;;;N;;;;; +13139;EGYPTIAN HIEROGLYPH F051;Lo;0;L;;;;;N;;;;; +1313A;EGYPTIAN HIEROGLYPH F051A;Lo;0;L;;;;;N;;;;; +1313B;EGYPTIAN HIEROGLYPH F051B;Lo;0;L;;;;;N;;;;; +1313C;EGYPTIAN HIEROGLYPH F051C;Lo;0;L;;;;;N;;;;; +1313D;EGYPTIAN HIEROGLYPH F052;Lo;0;L;;;;;N;;;;; +1313E;EGYPTIAN HIEROGLYPH F053;Lo;0;L;;;;;N;;;;; +1313F;EGYPTIAN HIEROGLYPH G001;Lo;0;L;;;;;N;;;;; +13140;EGYPTIAN HIEROGLYPH G002;Lo;0;L;;;;;N;;;;; +13141;EGYPTIAN HIEROGLYPH G003;Lo;0;L;;;;;N;;;;; +13142;EGYPTIAN HIEROGLYPH G004;Lo;0;L;;;;;N;;;;; +13143;EGYPTIAN HIEROGLYPH G005;Lo;0;L;;;;;N;;;;; +13144;EGYPTIAN HIEROGLYPH G006;Lo;0;L;;;;;N;;;;; +13145;EGYPTIAN HIEROGLYPH G006A;Lo;0;L;;;;;N;;;;; +13146;EGYPTIAN HIEROGLYPH G007;Lo;0;L;;;;;N;;;;; +13147;EGYPTIAN HIEROGLYPH G007A;Lo;0;L;;;;;N;;;;; +13148;EGYPTIAN HIEROGLYPH G007B;Lo;0;L;;;;;N;;;;; +13149;EGYPTIAN HIEROGLYPH G008;Lo;0;L;;;;;N;;;;; +1314A;EGYPTIAN HIEROGLYPH G009;Lo;0;L;;;;;N;;;;; +1314B;EGYPTIAN HIEROGLYPH G010;Lo;0;L;;;;;N;;;;; +1314C;EGYPTIAN HIEROGLYPH G011;Lo;0;L;;;;;N;;;;; +1314D;EGYPTIAN HIEROGLYPH G011A;Lo;0;L;;;;;N;;;;; +1314E;EGYPTIAN HIEROGLYPH G012;Lo;0;L;;;;;N;;;;; +1314F;EGYPTIAN HIEROGLYPH G013;Lo;0;L;;;;;N;;;;; +13150;EGYPTIAN HIEROGLYPH G014;Lo;0;L;;;;;N;;;;; +13151;EGYPTIAN HIEROGLYPH G015;Lo;0;L;;;;;N;;;;; +13152;EGYPTIAN HIEROGLYPH G016;Lo;0;L;;;;;N;;;;; +13153;EGYPTIAN HIEROGLYPH G017;Lo;0;L;;;;;N;;;;; +13154;EGYPTIAN HIEROGLYPH G018;Lo;0;L;;;;;N;;;;; +13155;EGYPTIAN HIEROGLYPH G019;Lo;0;L;;;;;N;;;;; +13156;EGYPTIAN HIEROGLYPH G020;Lo;0;L;;;;;N;;;;; +13157;EGYPTIAN HIEROGLYPH G020A;Lo;0;L;;;;;N;;;;; +13158;EGYPTIAN HIEROGLYPH G021;Lo;0;L;;;;;N;;;;; +13159;EGYPTIAN HIEROGLYPH G022;Lo;0;L;;;;;N;;;;; +1315A;EGYPTIAN HIEROGLYPH G023;Lo;0;L;;;;;N;;;;; +1315B;EGYPTIAN HIEROGLYPH G024;Lo;0;L;;;;;N;;;;; +1315C;EGYPTIAN HIEROGLYPH G025;Lo;0;L;;;;;N;;;;; +1315D;EGYPTIAN HIEROGLYPH G026;Lo;0;L;;;;;N;;;;; +1315E;EGYPTIAN HIEROGLYPH G026A;Lo;0;L;;;;;N;;;;; +1315F;EGYPTIAN HIEROGLYPH G027;Lo;0;L;;;;;N;;;;; +13160;EGYPTIAN HIEROGLYPH G028;Lo;0;L;;;;;N;;;;; +13161;EGYPTIAN HIEROGLYPH G029;Lo;0;L;;;;;N;;;;; +13162;EGYPTIAN HIEROGLYPH G030;Lo;0;L;;;;;N;;;;; +13163;EGYPTIAN HIEROGLYPH G031;Lo;0;L;;;;;N;;;;; +13164;EGYPTIAN HIEROGLYPH G032;Lo;0;L;;;;;N;;;;; +13165;EGYPTIAN HIEROGLYPH G033;Lo;0;L;;;;;N;;;;; +13166;EGYPTIAN HIEROGLYPH G034;Lo;0;L;;;;;N;;;;; +13167;EGYPTIAN HIEROGLYPH G035;Lo;0;L;;;;;N;;;;; +13168;EGYPTIAN HIEROGLYPH G036;Lo;0;L;;;;;N;;;;; +13169;EGYPTIAN HIEROGLYPH G036A;Lo;0;L;;;;;N;;;;; +1316A;EGYPTIAN HIEROGLYPH G037;Lo;0;L;;;;;N;;;;; +1316B;EGYPTIAN HIEROGLYPH G037A;Lo;0;L;;;;;N;;;;; +1316C;EGYPTIAN HIEROGLYPH G038;Lo;0;L;;;;;N;;;;; +1316D;EGYPTIAN HIEROGLYPH G039;Lo;0;L;;;;;N;;;;; +1316E;EGYPTIAN HIEROGLYPH G040;Lo;0;L;;;;;N;;;;; +1316F;EGYPTIAN HIEROGLYPH G041;Lo;0;L;;;;;N;;;;; +13170;EGYPTIAN HIEROGLYPH G042;Lo;0;L;;;;;N;;;;; +13171;EGYPTIAN HIEROGLYPH G043;Lo;0;L;;;;;N;;;;; +13172;EGYPTIAN HIEROGLYPH G043A;Lo;0;L;;;;;N;;;;; +13173;EGYPTIAN HIEROGLYPH G044;Lo;0;L;;;;;N;;;;; +13174;EGYPTIAN HIEROGLYPH G045;Lo;0;L;;;;;N;;;;; +13175;EGYPTIAN HIEROGLYPH G045A;Lo;0;L;;;;;N;;;;; +13176;EGYPTIAN HIEROGLYPH G046;Lo;0;L;;;;;N;;;;; +13177;EGYPTIAN HIEROGLYPH G047;Lo;0;L;;;;;N;;;;; +13178;EGYPTIAN HIEROGLYPH G048;Lo;0;L;;;;;N;;;;; +13179;EGYPTIAN HIEROGLYPH G049;Lo;0;L;;;;;N;;;;; +1317A;EGYPTIAN HIEROGLYPH G050;Lo;0;L;;;;;N;;;;; +1317B;EGYPTIAN HIEROGLYPH G051;Lo;0;L;;;;;N;;;;; +1317C;EGYPTIAN HIEROGLYPH G052;Lo;0;L;;;;;N;;;;; +1317D;EGYPTIAN HIEROGLYPH G053;Lo;0;L;;;;;N;;;;; +1317E;EGYPTIAN HIEROGLYPH G054;Lo;0;L;;;;;N;;;;; +1317F;EGYPTIAN HIEROGLYPH H001;Lo;0;L;;;;;N;;;;; +13180;EGYPTIAN HIEROGLYPH H002;Lo;0;L;;;;;N;;;;; +13181;EGYPTIAN HIEROGLYPH H003;Lo;0;L;;;;;N;;;;; +13182;EGYPTIAN HIEROGLYPH H004;Lo;0;L;;;;;N;;;;; +13183;EGYPTIAN HIEROGLYPH H005;Lo;0;L;;;;;N;;;;; +13184;EGYPTIAN HIEROGLYPH H006;Lo;0;L;;;;;N;;;;; +13185;EGYPTIAN HIEROGLYPH H006A;Lo;0;L;;;;;N;;;;; +13186;EGYPTIAN HIEROGLYPH H007;Lo;0;L;;;;;N;;;;; +13187;EGYPTIAN HIEROGLYPH H008;Lo;0;L;;;;;N;;;;; +13188;EGYPTIAN HIEROGLYPH I001;Lo;0;L;;;;;N;;;;; +13189;EGYPTIAN HIEROGLYPH I002;Lo;0;L;;;;;N;;;;; +1318A;EGYPTIAN HIEROGLYPH I003;Lo;0;L;;;;;N;;;;; +1318B;EGYPTIAN HIEROGLYPH I004;Lo;0;L;;;;;N;;;;; +1318C;EGYPTIAN HIEROGLYPH I005;Lo;0;L;;;;;N;;;;; +1318D;EGYPTIAN HIEROGLYPH I005A;Lo;0;L;;;;;N;;;;; +1318E;EGYPTIAN HIEROGLYPH I006;Lo;0;L;;;;;N;;;;; +1318F;EGYPTIAN HIEROGLYPH I007;Lo;0;L;;;;;N;;;;; +13190;EGYPTIAN HIEROGLYPH I008;Lo;0;L;;;;;N;;;;; +13191;EGYPTIAN HIEROGLYPH I009;Lo;0;L;;;;;N;;;;; +13192;EGYPTIAN HIEROGLYPH I009A;Lo;0;L;;;;;N;;;;; +13193;EGYPTIAN HIEROGLYPH I010;Lo;0;L;;;;;N;;;;; +13194;EGYPTIAN HIEROGLYPH I010A;Lo;0;L;;;;;N;;;;; +13195;EGYPTIAN HIEROGLYPH I011;Lo;0;L;;;;;N;;;;; +13196;EGYPTIAN HIEROGLYPH I011A;Lo;0;L;;;;;N;;;;; +13197;EGYPTIAN HIEROGLYPH I012;Lo;0;L;;;;;N;;;;; +13198;EGYPTIAN HIEROGLYPH I013;Lo;0;L;;;;;N;;;;; +13199;EGYPTIAN HIEROGLYPH I014;Lo;0;L;;;;;N;;;;; +1319A;EGYPTIAN HIEROGLYPH I015;Lo;0;L;;;;;N;;;;; +1319B;EGYPTIAN HIEROGLYPH K001;Lo;0;L;;;;;N;;;;; +1319C;EGYPTIAN HIEROGLYPH K002;Lo;0;L;;;;;N;;;;; +1319D;EGYPTIAN HIEROGLYPH K003;Lo;0;L;;;;;N;;;;; +1319E;EGYPTIAN HIEROGLYPH K004;Lo;0;L;;;;;N;;;;; +1319F;EGYPTIAN HIEROGLYPH K005;Lo;0;L;;;;;N;;;;; +131A0;EGYPTIAN HIEROGLYPH K006;Lo;0;L;;;;;N;;;;; +131A1;EGYPTIAN HIEROGLYPH K007;Lo;0;L;;;;;N;;;;; +131A2;EGYPTIAN HIEROGLYPH K008;Lo;0;L;;;;;N;;;;; +131A3;EGYPTIAN HIEROGLYPH L001;Lo;0;L;;;;;N;;;;; +131A4;EGYPTIAN HIEROGLYPH L002;Lo;0;L;;;;;N;;;;; +131A5;EGYPTIAN HIEROGLYPH L002A;Lo;0;L;;;;;N;;;;; +131A6;EGYPTIAN HIEROGLYPH L003;Lo;0;L;;;;;N;;;;; +131A7;EGYPTIAN HIEROGLYPH L004;Lo;0;L;;;;;N;;;;; +131A8;EGYPTIAN HIEROGLYPH L005;Lo;0;L;;;;;N;;;;; +131A9;EGYPTIAN HIEROGLYPH L006;Lo;0;L;;;;;N;;;;; +131AA;EGYPTIAN HIEROGLYPH L006A;Lo;0;L;;;;;N;;;;; +131AB;EGYPTIAN HIEROGLYPH L007;Lo;0;L;;;;;N;;;;; +131AC;EGYPTIAN HIEROGLYPH L008;Lo;0;L;;;;;N;;;;; +131AD;EGYPTIAN HIEROGLYPH M001;Lo;0;L;;;;;N;;;;; +131AE;EGYPTIAN HIEROGLYPH M001A;Lo;0;L;;;;;N;;;;; +131AF;EGYPTIAN HIEROGLYPH M001B;Lo;0;L;;;;;N;;;;; +131B0;EGYPTIAN HIEROGLYPH M002;Lo;0;L;;;;;N;;;;; +131B1;EGYPTIAN HIEROGLYPH M003;Lo;0;L;;;;;N;;;;; +131B2;EGYPTIAN HIEROGLYPH M003A;Lo;0;L;;;;;N;;;;; +131B3;EGYPTIAN HIEROGLYPH M004;Lo;0;L;;;;;N;;;;; +131B4;EGYPTIAN HIEROGLYPH M005;Lo;0;L;;;;;N;;;;; +131B5;EGYPTIAN HIEROGLYPH M006;Lo;0;L;;;;;N;;;;; +131B6;EGYPTIAN HIEROGLYPH M007;Lo;0;L;;;;;N;;;;; +131B7;EGYPTIAN HIEROGLYPH M008;Lo;0;L;;;;;N;;;;; +131B8;EGYPTIAN HIEROGLYPH M009;Lo;0;L;;;;;N;;;;; +131B9;EGYPTIAN HIEROGLYPH M010;Lo;0;L;;;;;N;;;;; +131BA;EGYPTIAN HIEROGLYPH M010A;Lo;0;L;;;;;N;;;;; +131BB;EGYPTIAN HIEROGLYPH M011;Lo;0;L;;;;;N;;;;; +131BC;EGYPTIAN HIEROGLYPH M012;Lo;0;L;;;;;N;;;;; +131BD;EGYPTIAN HIEROGLYPH M012A;Lo;0;L;;;;;N;;;;; +131BE;EGYPTIAN HIEROGLYPH M012B;Lo;0;L;;;;;N;;;;; +131BF;EGYPTIAN HIEROGLYPH M012C;Lo;0;L;;;;;N;;;;; +131C0;EGYPTIAN HIEROGLYPH M012D;Lo;0;L;;;;;N;;;;; +131C1;EGYPTIAN HIEROGLYPH M012E;Lo;0;L;;;;;N;;;;; +131C2;EGYPTIAN HIEROGLYPH M012F;Lo;0;L;;;;;N;;;;; +131C3;EGYPTIAN HIEROGLYPH M012G;Lo;0;L;;;;;N;;;;; +131C4;EGYPTIAN HIEROGLYPH M012H;Lo;0;L;;;;;N;;;;; +131C5;EGYPTIAN HIEROGLYPH M013;Lo;0;L;;;;;N;;;;; +131C6;EGYPTIAN HIEROGLYPH M014;Lo;0;L;;;;;N;;;;; +131C7;EGYPTIAN HIEROGLYPH M015;Lo;0;L;;;;;N;;;;; +131C8;EGYPTIAN HIEROGLYPH M015A;Lo;0;L;;;;;N;;;;; +131C9;EGYPTIAN HIEROGLYPH M016;Lo;0;L;;;;;N;;;;; +131CA;EGYPTIAN HIEROGLYPH M016A;Lo;0;L;;;;;N;;;;; +131CB;EGYPTIAN HIEROGLYPH M017;Lo;0;L;;;;;N;;;;; +131CC;EGYPTIAN HIEROGLYPH M017A;Lo;0;L;;;;;N;;;;; +131CD;EGYPTIAN HIEROGLYPH M018;Lo;0;L;;;;;N;;;;; +131CE;EGYPTIAN HIEROGLYPH M019;Lo;0;L;;;;;N;;;;; +131CF;EGYPTIAN HIEROGLYPH M020;Lo;0;L;;;;;N;;;;; +131D0;EGYPTIAN HIEROGLYPH M021;Lo;0;L;;;;;N;;;;; +131D1;EGYPTIAN HIEROGLYPH M022;Lo;0;L;;;;;N;;;;; +131D2;EGYPTIAN HIEROGLYPH M022A;Lo;0;L;;;;;N;;;;; +131D3;EGYPTIAN HIEROGLYPH M023;Lo;0;L;;;;;N;;;;; +131D4;EGYPTIAN HIEROGLYPH M024;Lo;0;L;;;;;N;;;;; +131D5;EGYPTIAN HIEROGLYPH M024A;Lo;0;L;;;;;N;;;;; +131D6;EGYPTIAN HIEROGLYPH M025;Lo;0;L;;;;;N;;;;; +131D7;EGYPTIAN HIEROGLYPH M026;Lo;0;L;;;;;N;;;;; +131D8;EGYPTIAN HIEROGLYPH M027;Lo;0;L;;;;;N;;;;; +131D9;EGYPTIAN HIEROGLYPH M028;Lo;0;L;;;;;N;;;;; +131DA;EGYPTIAN HIEROGLYPH M028A;Lo;0;L;;;;;N;;;;; +131DB;EGYPTIAN HIEROGLYPH M029;Lo;0;L;;;;;N;;;;; +131DC;EGYPTIAN HIEROGLYPH M030;Lo;0;L;;;;;N;;;;; +131DD;EGYPTIAN HIEROGLYPH M031;Lo;0;L;;;;;N;;;;; +131DE;EGYPTIAN HIEROGLYPH M031A;Lo;0;L;;;;;N;;;;; +131DF;EGYPTIAN HIEROGLYPH M032;Lo;0;L;;;;;N;;;;; +131E0;EGYPTIAN HIEROGLYPH M033;Lo;0;L;;;;;N;;;;; +131E1;EGYPTIAN HIEROGLYPH M033A;Lo;0;L;;;;;N;;;;; +131E2;EGYPTIAN HIEROGLYPH M033B;Lo;0;L;;;;;N;;;;; +131E3;EGYPTIAN HIEROGLYPH M034;Lo;0;L;;;;;N;;;;; +131E4;EGYPTIAN HIEROGLYPH M035;Lo;0;L;;;;;N;;;;; +131E5;EGYPTIAN HIEROGLYPH M036;Lo;0;L;;;;;N;;;;; +131E6;EGYPTIAN HIEROGLYPH M037;Lo;0;L;;;;;N;;;;; +131E7;EGYPTIAN HIEROGLYPH M038;Lo;0;L;;;;;N;;;;; +131E8;EGYPTIAN HIEROGLYPH M039;Lo;0;L;;;;;N;;;;; +131E9;EGYPTIAN HIEROGLYPH M040;Lo;0;L;;;;;N;;;;; +131EA;EGYPTIAN HIEROGLYPH M040A;Lo;0;L;;;;;N;;;;; +131EB;EGYPTIAN HIEROGLYPH M041;Lo;0;L;;;;;N;;;;; +131EC;EGYPTIAN HIEROGLYPH M042;Lo;0;L;;;;;N;;;;; +131ED;EGYPTIAN HIEROGLYPH M043;Lo;0;L;;;;;N;;;;; +131EE;EGYPTIAN HIEROGLYPH M044;Lo;0;L;;;;;N;;;;; +131EF;EGYPTIAN HIEROGLYPH N001;Lo;0;L;;;;;N;;;;; +131F0;EGYPTIAN HIEROGLYPH N002;Lo;0;L;;;;;N;;;;; +131F1;EGYPTIAN HIEROGLYPH N003;Lo;0;L;;;;;N;;;;; +131F2;EGYPTIAN HIEROGLYPH N004;Lo;0;L;;;;;N;;;;; +131F3;EGYPTIAN HIEROGLYPH N005;Lo;0;L;;;;;N;;;;; +131F4;EGYPTIAN HIEROGLYPH N006;Lo;0;L;;;;;N;;;;; +131F5;EGYPTIAN HIEROGLYPH N007;Lo;0;L;;;;;N;;;;; +131F6;EGYPTIAN HIEROGLYPH N008;Lo;0;L;;;;;N;;;;; +131F7;EGYPTIAN HIEROGLYPH N009;Lo;0;L;;;;;N;;;;; +131F8;EGYPTIAN HIEROGLYPH N010;Lo;0;L;;;;;N;;;;; +131F9;EGYPTIAN HIEROGLYPH N011;Lo;0;L;;;;;N;;;;; +131FA;EGYPTIAN HIEROGLYPH N012;Lo;0;L;;;;;N;;;;; +131FB;EGYPTIAN HIEROGLYPH N013;Lo;0;L;;;;;N;;;;; +131FC;EGYPTIAN HIEROGLYPH N014;Lo;0;L;;;;;N;;;;; +131FD;EGYPTIAN HIEROGLYPH N015;Lo;0;L;;;;;N;;;;; +131FE;EGYPTIAN HIEROGLYPH N016;Lo;0;L;;;;;N;;;;; +131FF;EGYPTIAN HIEROGLYPH N017;Lo;0;L;;;;;N;;;;; +13200;EGYPTIAN HIEROGLYPH N018;Lo;0;L;;;;;N;;;;; +13201;EGYPTIAN HIEROGLYPH N018A;Lo;0;L;;;;;N;;;;; +13202;EGYPTIAN HIEROGLYPH N018B;Lo;0;L;;;;;N;;;;; +13203;EGYPTIAN HIEROGLYPH N019;Lo;0;L;;;;;N;;;;; +13204;EGYPTIAN HIEROGLYPH N020;Lo;0;L;;;;;N;;;;; +13205;EGYPTIAN HIEROGLYPH N021;Lo;0;L;;;;;N;;;;; +13206;EGYPTIAN HIEROGLYPH N022;Lo;0;L;;;;;N;;;;; +13207;EGYPTIAN HIEROGLYPH N023;Lo;0;L;;;;;N;;;;; +13208;EGYPTIAN HIEROGLYPH N024;Lo;0;L;;;;;N;;;;; +13209;EGYPTIAN HIEROGLYPH N025;Lo;0;L;;;;;N;;;;; +1320A;EGYPTIAN HIEROGLYPH N025A;Lo;0;L;;;;;N;;;;; +1320B;EGYPTIAN HIEROGLYPH N026;Lo;0;L;;;;;N;;;;; +1320C;EGYPTIAN HIEROGLYPH N027;Lo;0;L;;;;;N;;;;; +1320D;EGYPTIAN HIEROGLYPH N028;Lo;0;L;;;;;N;;;;; +1320E;EGYPTIAN HIEROGLYPH N029;Lo;0;L;;;;;N;;;;; +1320F;EGYPTIAN HIEROGLYPH N030;Lo;0;L;;;;;N;;;;; +13210;EGYPTIAN HIEROGLYPH N031;Lo;0;L;;;;;N;;;;; +13211;EGYPTIAN HIEROGLYPH N032;Lo;0;L;;;;;N;;;;; +13212;EGYPTIAN HIEROGLYPH N033;Lo;0;L;;;;;N;;;;; +13213;EGYPTIAN HIEROGLYPH N033A;Lo;0;L;;;;;N;;;;; +13214;EGYPTIAN HIEROGLYPH N034;Lo;0;L;;;;;N;;;;; +13215;EGYPTIAN HIEROGLYPH N034A;Lo;0;L;;;;;N;;;;; +13216;EGYPTIAN HIEROGLYPH N035;Lo;0;L;;;;;N;;;;; +13217;EGYPTIAN HIEROGLYPH N035A;Lo;0;L;;;;;N;;;;; +13218;EGYPTIAN HIEROGLYPH N036;Lo;0;L;;;;;N;;;;; +13219;EGYPTIAN HIEROGLYPH N037;Lo;0;L;;;;;N;;;;; +1321A;EGYPTIAN HIEROGLYPH N037A;Lo;0;L;;;;;N;;;;; +1321B;EGYPTIAN HIEROGLYPH N038;Lo;0;L;;;;;N;;;;; +1321C;EGYPTIAN HIEROGLYPH N039;Lo;0;L;;;;;N;;;;; +1321D;EGYPTIAN HIEROGLYPH N040;Lo;0;L;;;;;N;;;;; +1321E;EGYPTIAN HIEROGLYPH N041;Lo;0;L;;;;;N;;;;; +1321F;EGYPTIAN HIEROGLYPH N042;Lo;0;L;;;;;N;;;;; +13220;EGYPTIAN HIEROGLYPH NL001;Lo;0;L;;;;;N;;;;; +13221;EGYPTIAN HIEROGLYPH NL002;Lo;0;L;;;;;N;;;;; +13222;EGYPTIAN HIEROGLYPH NL003;Lo;0;L;;;;;N;;;;; +13223;EGYPTIAN HIEROGLYPH NL004;Lo;0;L;;;;;N;;;;; +13224;EGYPTIAN HIEROGLYPH NL005;Lo;0;L;;;;;N;;;;; +13225;EGYPTIAN HIEROGLYPH NL005A;Lo;0;L;;;;;N;;;;; +13226;EGYPTIAN HIEROGLYPH NL006;Lo;0;L;;;;;N;;;;; +13227;EGYPTIAN HIEROGLYPH NL007;Lo;0;L;;;;;N;;;;; +13228;EGYPTIAN HIEROGLYPH NL008;Lo;0;L;;;;;N;;;;; +13229;EGYPTIAN HIEROGLYPH NL009;Lo;0;L;;;;;N;;;;; +1322A;EGYPTIAN HIEROGLYPH NL010;Lo;0;L;;;;;N;;;;; +1322B;EGYPTIAN HIEROGLYPH NL011;Lo;0;L;;;;;N;;;;; +1322C;EGYPTIAN HIEROGLYPH NL012;Lo;0;L;;;;;N;;;;; +1322D;EGYPTIAN HIEROGLYPH NL013;Lo;0;L;;;;;N;;;;; +1322E;EGYPTIAN HIEROGLYPH NL014;Lo;0;L;;;;;N;;;;; +1322F;EGYPTIAN HIEROGLYPH NL015;Lo;0;L;;;;;N;;;;; +13230;EGYPTIAN HIEROGLYPH NL016;Lo;0;L;;;;;N;;;;; +13231;EGYPTIAN HIEROGLYPH NL017;Lo;0;L;;;;;N;;;;; +13232;EGYPTIAN HIEROGLYPH NL017A;Lo;0;L;;;;;N;;;;; +13233;EGYPTIAN HIEROGLYPH NL018;Lo;0;L;;;;;N;;;;; +13234;EGYPTIAN HIEROGLYPH NL019;Lo;0;L;;;;;N;;;;; +13235;EGYPTIAN HIEROGLYPH NL020;Lo;0;L;;;;;N;;;;; +13236;EGYPTIAN HIEROGLYPH NU001;Lo;0;L;;;;;N;;;;; +13237;EGYPTIAN HIEROGLYPH NU002;Lo;0;L;;;;;N;;;;; +13238;EGYPTIAN HIEROGLYPH NU003;Lo;0;L;;;;;N;;;;; +13239;EGYPTIAN HIEROGLYPH NU004;Lo;0;L;;;;;N;;;;; +1323A;EGYPTIAN HIEROGLYPH NU005;Lo;0;L;;;;;N;;;;; +1323B;EGYPTIAN HIEROGLYPH NU006;Lo;0;L;;;;;N;;;;; +1323C;EGYPTIAN HIEROGLYPH NU007;Lo;0;L;;;;;N;;;;; +1323D;EGYPTIAN HIEROGLYPH NU008;Lo;0;L;;;;;N;;;;; +1323E;EGYPTIAN HIEROGLYPH NU009;Lo;0;L;;;;;N;;;;; +1323F;EGYPTIAN HIEROGLYPH NU010;Lo;0;L;;;;;N;;;;; +13240;EGYPTIAN HIEROGLYPH NU010A;Lo;0;L;;;;;N;;;;; +13241;EGYPTIAN HIEROGLYPH NU011;Lo;0;L;;;;;N;;;;; +13242;EGYPTIAN HIEROGLYPH NU011A;Lo;0;L;;;;;N;;;;; +13243;EGYPTIAN HIEROGLYPH NU012;Lo;0;L;;;;;N;;;;; +13244;EGYPTIAN HIEROGLYPH NU013;Lo;0;L;;;;;N;;;;; +13245;EGYPTIAN HIEROGLYPH NU014;Lo;0;L;;;;;N;;;;; +13246;EGYPTIAN HIEROGLYPH NU015;Lo;0;L;;;;;N;;;;; +13247;EGYPTIAN HIEROGLYPH NU016;Lo;0;L;;;;;N;;;;; +13248;EGYPTIAN HIEROGLYPH NU017;Lo;0;L;;;;;N;;;;; +13249;EGYPTIAN HIEROGLYPH NU018;Lo;0;L;;;;;N;;;;; +1324A;EGYPTIAN HIEROGLYPH NU018A;Lo;0;L;;;;;N;;;;; +1324B;EGYPTIAN HIEROGLYPH NU019;Lo;0;L;;;;;N;;;;; +1324C;EGYPTIAN HIEROGLYPH NU020;Lo;0;L;;;;;N;;;;; +1324D;EGYPTIAN HIEROGLYPH NU021;Lo;0;L;;;;;N;;;;; +1324E;EGYPTIAN HIEROGLYPH NU022;Lo;0;L;;;;;N;;;;; +1324F;EGYPTIAN HIEROGLYPH NU022A;Lo;0;L;;;;;N;;;;; +13250;EGYPTIAN HIEROGLYPH O001;Lo;0;L;;;;;N;;;;; +13251;EGYPTIAN HIEROGLYPH O001A;Lo;0;L;;;;;N;;;;; +13252;EGYPTIAN HIEROGLYPH O002;Lo;0;L;;;;;N;;;;; +13253;EGYPTIAN HIEROGLYPH O003;Lo;0;L;;;;;N;;;;; +13254;EGYPTIAN HIEROGLYPH O004;Lo;0;L;;;;;N;;;;; +13255;EGYPTIAN HIEROGLYPH O005;Lo;0;L;;;;;N;;;;; +13256;EGYPTIAN HIEROGLYPH O005A;Lo;0;L;;;;;N;;;;; +13257;EGYPTIAN HIEROGLYPH O006;Lo;0;L;;;;;N;;;;; +13258;EGYPTIAN HIEROGLYPH O006A;Lo;0;L;;;;;N;;;;; +13259;EGYPTIAN HIEROGLYPH O006B;Lo;0;L;;;;;N;;;;; +1325A;EGYPTIAN HIEROGLYPH O006C;Lo;0;L;;;;;N;;;;; +1325B;EGYPTIAN HIEROGLYPH O006D;Lo;0;L;;;;;N;;;;; +1325C;EGYPTIAN HIEROGLYPH O006E;Lo;0;L;;;;;N;;;;; +1325D;EGYPTIAN HIEROGLYPH O006F;Lo;0;L;;;;;N;;;;; +1325E;EGYPTIAN HIEROGLYPH O007;Lo;0;L;;;;;N;;;;; +1325F;EGYPTIAN HIEROGLYPH O008;Lo;0;L;;;;;N;;;;; +13260;EGYPTIAN HIEROGLYPH O009;Lo;0;L;;;;;N;;;;; +13261;EGYPTIAN HIEROGLYPH O010;Lo;0;L;;;;;N;;;;; +13262;EGYPTIAN HIEROGLYPH O010A;Lo;0;L;;;;;N;;;;; +13263;EGYPTIAN HIEROGLYPH O010B;Lo;0;L;;;;;N;;;;; +13264;EGYPTIAN HIEROGLYPH O010C;Lo;0;L;;;;;N;;;;; +13265;EGYPTIAN HIEROGLYPH O011;Lo;0;L;;;;;N;;;;; +13266;EGYPTIAN HIEROGLYPH O012;Lo;0;L;;;;;N;;;;; +13267;EGYPTIAN HIEROGLYPH O013;Lo;0;L;;;;;N;;;;; +13268;EGYPTIAN HIEROGLYPH O014;Lo;0;L;;;;;N;;;;; +13269;EGYPTIAN HIEROGLYPH O015;Lo;0;L;;;;;N;;;;; +1326A;EGYPTIAN HIEROGLYPH O016;Lo;0;L;;;;;N;;;;; +1326B;EGYPTIAN HIEROGLYPH O017;Lo;0;L;;;;;N;;;;; +1326C;EGYPTIAN HIEROGLYPH O018;Lo;0;L;;;;;N;;;;; +1326D;EGYPTIAN HIEROGLYPH O019;Lo;0;L;;;;;N;;;;; +1326E;EGYPTIAN HIEROGLYPH O019A;Lo;0;L;;;;;N;;;;; +1326F;EGYPTIAN HIEROGLYPH O020;Lo;0;L;;;;;N;;;;; +13270;EGYPTIAN HIEROGLYPH O020A;Lo;0;L;;;;;N;;;;; +13271;EGYPTIAN HIEROGLYPH O021;Lo;0;L;;;;;N;;;;; +13272;EGYPTIAN HIEROGLYPH O022;Lo;0;L;;;;;N;;;;; +13273;EGYPTIAN HIEROGLYPH O023;Lo;0;L;;;;;N;;;;; +13274;EGYPTIAN HIEROGLYPH O024;Lo;0;L;;;;;N;;;;; +13275;EGYPTIAN HIEROGLYPH O024A;Lo;0;L;;;;;N;;;;; +13276;EGYPTIAN HIEROGLYPH O025;Lo;0;L;;;;;N;;;;; +13277;EGYPTIAN HIEROGLYPH O025A;Lo;0;L;;;;;N;;;;; +13278;EGYPTIAN HIEROGLYPH O026;Lo;0;L;;;;;N;;;;; +13279;EGYPTIAN HIEROGLYPH O027;Lo;0;L;;;;;N;;;;; +1327A;EGYPTIAN HIEROGLYPH O028;Lo;0;L;;;;;N;;;;; +1327B;EGYPTIAN HIEROGLYPH O029;Lo;0;L;;;;;N;;;;; +1327C;EGYPTIAN HIEROGLYPH O029A;Lo;0;L;;;;;N;;;;; +1327D;EGYPTIAN HIEROGLYPH O030;Lo;0;L;;;;;N;;;;; +1327E;EGYPTIAN HIEROGLYPH O030A;Lo;0;L;;;;;N;;;;; +1327F;EGYPTIAN HIEROGLYPH O031;Lo;0;L;;;;;N;;;;; +13280;EGYPTIAN HIEROGLYPH O032;Lo;0;L;;;;;N;;;;; +13281;EGYPTIAN HIEROGLYPH O033;Lo;0;L;;;;;N;;;;; +13282;EGYPTIAN HIEROGLYPH O033A;Lo;0;L;;;;;N;;;;; +13283;EGYPTIAN HIEROGLYPH O034;Lo;0;L;;;;;N;;;;; +13284;EGYPTIAN HIEROGLYPH O035;Lo;0;L;;;;;N;;;;; +13285;EGYPTIAN HIEROGLYPH O036;Lo;0;L;;;;;N;;;;; +13286;EGYPTIAN HIEROGLYPH O036A;Lo;0;L;;;;;N;;;;; +13287;EGYPTIAN HIEROGLYPH O036B;Lo;0;L;;;;;N;;;;; +13288;EGYPTIAN HIEROGLYPH O036C;Lo;0;L;;;;;N;;;;; +13289;EGYPTIAN HIEROGLYPH O036D;Lo;0;L;;;;;N;;;;; +1328A;EGYPTIAN HIEROGLYPH O037;Lo;0;L;;;;;N;;;;; +1328B;EGYPTIAN HIEROGLYPH O038;Lo;0;L;;;;;N;;;;; +1328C;EGYPTIAN HIEROGLYPH O039;Lo;0;L;;;;;N;;;;; +1328D;EGYPTIAN HIEROGLYPH O040;Lo;0;L;;;;;N;;;;; +1328E;EGYPTIAN HIEROGLYPH O041;Lo;0;L;;;;;N;;;;; +1328F;EGYPTIAN HIEROGLYPH O042;Lo;0;L;;;;;N;;;;; +13290;EGYPTIAN HIEROGLYPH O043;Lo;0;L;;;;;N;;;;; +13291;EGYPTIAN HIEROGLYPH O044;Lo;0;L;;;;;N;;;;; +13292;EGYPTIAN HIEROGLYPH O045;Lo;0;L;;;;;N;;;;; +13293;EGYPTIAN HIEROGLYPH O046;Lo;0;L;;;;;N;;;;; +13294;EGYPTIAN HIEROGLYPH O047;Lo;0;L;;;;;N;;;;; +13295;EGYPTIAN HIEROGLYPH O048;Lo;0;L;;;;;N;;;;; +13296;EGYPTIAN HIEROGLYPH O049;Lo;0;L;;;;;N;;;;; +13297;EGYPTIAN HIEROGLYPH O050;Lo;0;L;;;;;N;;;;; +13298;EGYPTIAN HIEROGLYPH O050A;Lo;0;L;;;;;N;;;;; +13299;EGYPTIAN HIEROGLYPH O050B;Lo;0;L;;;;;N;;;;; +1329A;EGYPTIAN HIEROGLYPH O051;Lo;0;L;;;;;N;;;;; +1329B;EGYPTIAN HIEROGLYPH P001;Lo;0;L;;;;;N;;;;; +1329C;EGYPTIAN HIEROGLYPH P001A;Lo;0;L;;;;;N;;;;; +1329D;EGYPTIAN HIEROGLYPH P002;Lo;0;L;;;;;N;;;;; +1329E;EGYPTIAN HIEROGLYPH P003;Lo;0;L;;;;;N;;;;; +1329F;EGYPTIAN HIEROGLYPH P003A;Lo;0;L;;;;;N;;;;; +132A0;EGYPTIAN HIEROGLYPH P004;Lo;0;L;;;;;N;;;;; +132A1;EGYPTIAN HIEROGLYPH P005;Lo;0;L;;;;;N;;;;; +132A2;EGYPTIAN HIEROGLYPH P006;Lo;0;L;;;;;N;;;;; +132A3;EGYPTIAN HIEROGLYPH P007;Lo;0;L;;;;;N;;;;; +132A4;EGYPTIAN HIEROGLYPH P008;Lo;0;L;;;;;N;;;;; +132A5;EGYPTIAN HIEROGLYPH P009;Lo;0;L;;;;;N;;;;; +132A6;EGYPTIAN HIEROGLYPH P010;Lo;0;L;;;;;N;;;;; +132A7;EGYPTIAN HIEROGLYPH P011;Lo;0;L;;;;;N;;;;; +132A8;EGYPTIAN HIEROGLYPH Q001;Lo;0;L;;;;;N;;;;; +132A9;EGYPTIAN HIEROGLYPH Q002;Lo;0;L;;;;;N;;;;; +132AA;EGYPTIAN HIEROGLYPH Q003;Lo;0;L;;;;;N;;;;; +132AB;EGYPTIAN HIEROGLYPH Q004;Lo;0;L;;;;;N;;;;; +132AC;EGYPTIAN HIEROGLYPH Q005;Lo;0;L;;;;;N;;;;; +132AD;EGYPTIAN HIEROGLYPH Q006;Lo;0;L;;;;;N;;;;; +132AE;EGYPTIAN HIEROGLYPH Q007;Lo;0;L;;;;;N;;;;; +132AF;EGYPTIAN HIEROGLYPH R001;Lo;0;L;;;;;N;;;;; +132B0;EGYPTIAN HIEROGLYPH R002;Lo;0;L;;;;;N;;;;; +132B1;EGYPTIAN HIEROGLYPH R002A;Lo;0;L;;;;;N;;;;; +132B2;EGYPTIAN HIEROGLYPH R003;Lo;0;L;;;;;N;;;;; +132B3;EGYPTIAN HIEROGLYPH R003A;Lo;0;L;;;;;N;;;;; +132B4;EGYPTIAN HIEROGLYPH R003B;Lo;0;L;;;;;N;;;;; +132B5;EGYPTIAN HIEROGLYPH R004;Lo;0;L;;;;;N;;;;; +132B6;EGYPTIAN HIEROGLYPH R005;Lo;0;L;;;;;N;;;;; +132B7;EGYPTIAN HIEROGLYPH R006;Lo;0;L;;;;;N;;;;; +132B8;EGYPTIAN HIEROGLYPH R007;Lo;0;L;;;;;N;;;;; +132B9;EGYPTIAN HIEROGLYPH R008;Lo;0;L;;;;;N;;;;; +132BA;EGYPTIAN HIEROGLYPH R009;Lo;0;L;;;;;N;;;;; +132BB;EGYPTIAN HIEROGLYPH R010;Lo;0;L;;;;;N;;;;; +132BC;EGYPTIAN HIEROGLYPH R010A;Lo;0;L;;;;;N;;;;; +132BD;EGYPTIAN HIEROGLYPH R011;Lo;0;L;;;;;N;;;;; +132BE;EGYPTIAN HIEROGLYPH R012;Lo;0;L;;;;;N;;;;; +132BF;EGYPTIAN HIEROGLYPH R013;Lo;0;L;;;;;N;;;;; +132C0;EGYPTIAN HIEROGLYPH R014;Lo;0;L;;;;;N;;;;; +132C1;EGYPTIAN HIEROGLYPH R015;Lo;0;L;;;;;N;;;;; +132C2;EGYPTIAN HIEROGLYPH R016;Lo;0;L;;;;;N;;;;; +132C3;EGYPTIAN HIEROGLYPH R016A;Lo;0;L;;;;;N;;;;; +132C4;EGYPTIAN HIEROGLYPH R017;Lo;0;L;;;;;N;;;;; +132C5;EGYPTIAN HIEROGLYPH R018;Lo;0;L;;;;;N;;;;; +132C6;EGYPTIAN HIEROGLYPH R019;Lo;0;L;;;;;N;;;;; +132C7;EGYPTIAN HIEROGLYPH R020;Lo;0;L;;;;;N;;;;; +132C8;EGYPTIAN HIEROGLYPH R021;Lo;0;L;;;;;N;;;;; +132C9;EGYPTIAN HIEROGLYPH R022;Lo;0;L;;;;;N;;;;; +132CA;EGYPTIAN HIEROGLYPH R023;Lo;0;L;;;;;N;;;;; +132CB;EGYPTIAN HIEROGLYPH R024;Lo;0;L;;;;;N;;;;; +132CC;EGYPTIAN HIEROGLYPH R025;Lo;0;L;;;;;N;;;;; +132CD;EGYPTIAN HIEROGLYPH R026;Lo;0;L;;;;;N;;;;; +132CE;EGYPTIAN HIEROGLYPH R027;Lo;0;L;;;;;N;;;;; +132CF;EGYPTIAN HIEROGLYPH R028;Lo;0;L;;;;;N;;;;; +132D0;EGYPTIAN HIEROGLYPH R029;Lo;0;L;;;;;N;;;;; +132D1;EGYPTIAN HIEROGLYPH S001;Lo;0;L;;;;;N;;;;; +132D2;EGYPTIAN HIEROGLYPH S002;Lo;0;L;;;;;N;;;;; +132D3;EGYPTIAN HIEROGLYPH S002A;Lo;0;L;;;;;N;;;;; +132D4;EGYPTIAN HIEROGLYPH S003;Lo;0;L;;;;;N;;;;; +132D5;EGYPTIAN HIEROGLYPH S004;Lo;0;L;;;;;N;;;;; +132D6;EGYPTIAN HIEROGLYPH S005;Lo;0;L;;;;;N;;;;; +132D7;EGYPTIAN HIEROGLYPH S006;Lo;0;L;;;;;N;;;;; +132D8;EGYPTIAN HIEROGLYPH S006A;Lo;0;L;;;;;N;;;;; +132D9;EGYPTIAN HIEROGLYPH S007;Lo;0;L;;;;;N;;;;; +132DA;EGYPTIAN HIEROGLYPH S008;Lo;0;L;;;;;N;;;;; +132DB;EGYPTIAN HIEROGLYPH S009;Lo;0;L;;;;;N;;;;; +132DC;EGYPTIAN HIEROGLYPH S010;Lo;0;L;;;;;N;;;;; +132DD;EGYPTIAN HIEROGLYPH S011;Lo;0;L;;;;;N;;;;; +132DE;EGYPTIAN HIEROGLYPH S012;Lo;0;L;;;;;N;;;;; +132DF;EGYPTIAN HIEROGLYPH S013;Lo;0;L;;;;;N;;;;; +132E0;EGYPTIAN HIEROGLYPH S014;Lo;0;L;;;;;N;;;;; +132E1;EGYPTIAN HIEROGLYPH S014A;Lo;0;L;;;;;N;;;;; +132E2;EGYPTIAN HIEROGLYPH S014B;Lo;0;L;;;;;N;;;;; +132E3;EGYPTIAN HIEROGLYPH S015;Lo;0;L;;;;;N;;;;; +132E4;EGYPTIAN HIEROGLYPH S016;Lo;0;L;;;;;N;;;;; +132E5;EGYPTIAN HIEROGLYPH S017;Lo;0;L;;;;;N;;;;; +132E6;EGYPTIAN HIEROGLYPH S017A;Lo;0;L;;;;;N;;;;; +132E7;EGYPTIAN HIEROGLYPH S018;Lo;0;L;;;;;N;;;;; +132E8;EGYPTIAN HIEROGLYPH S019;Lo;0;L;;;;;N;;;;; +132E9;EGYPTIAN HIEROGLYPH S020;Lo;0;L;;;;;N;;;;; +132EA;EGYPTIAN HIEROGLYPH S021;Lo;0;L;;;;;N;;;;; +132EB;EGYPTIAN HIEROGLYPH S022;Lo;0;L;;;;;N;;;;; +132EC;EGYPTIAN HIEROGLYPH S023;Lo;0;L;;;;;N;;;;; +132ED;EGYPTIAN HIEROGLYPH S024;Lo;0;L;;;;;N;;;;; +132EE;EGYPTIAN HIEROGLYPH S025;Lo;0;L;;;;;N;;;;; +132EF;EGYPTIAN HIEROGLYPH S026;Lo;0;L;;;;;N;;;;; +132F0;EGYPTIAN HIEROGLYPH S026A;Lo;0;L;;;;;N;;;;; +132F1;EGYPTIAN HIEROGLYPH S026B;Lo;0;L;;;;;N;;;;; +132F2;EGYPTIAN HIEROGLYPH S027;Lo;0;L;;;;;N;;;;; +132F3;EGYPTIAN HIEROGLYPH S028;Lo;0;L;;;;;N;;;;; +132F4;EGYPTIAN HIEROGLYPH S029;Lo;0;L;;;;;N;;;;; +132F5;EGYPTIAN HIEROGLYPH S030;Lo;0;L;;;;;N;;;;; +132F6;EGYPTIAN HIEROGLYPH S031;Lo;0;L;;;;;N;;;;; +132F7;EGYPTIAN HIEROGLYPH S032;Lo;0;L;;;;;N;;;;; +132F8;EGYPTIAN HIEROGLYPH S033;Lo;0;L;;;;;N;;;;; +132F9;EGYPTIAN HIEROGLYPH S034;Lo;0;L;;;;;N;;;;; +132FA;EGYPTIAN HIEROGLYPH S035;Lo;0;L;;;;;N;;;;; +132FB;EGYPTIAN HIEROGLYPH S035A;Lo;0;L;;;;;N;;;;; +132FC;EGYPTIAN HIEROGLYPH S036;Lo;0;L;;;;;N;;;;; +132FD;EGYPTIAN HIEROGLYPH S037;Lo;0;L;;;;;N;;;;; +132FE;EGYPTIAN HIEROGLYPH S038;Lo;0;L;;;;;N;;;;; +132FF;EGYPTIAN HIEROGLYPH S039;Lo;0;L;;;;;N;;;;; +13300;EGYPTIAN HIEROGLYPH S040;Lo;0;L;;;;;N;;;;; +13301;EGYPTIAN HIEROGLYPH S041;Lo;0;L;;;;;N;;;;; +13302;EGYPTIAN HIEROGLYPH S042;Lo;0;L;;;;;N;;;;; +13303;EGYPTIAN HIEROGLYPH S043;Lo;0;L;;;;;N;;;;; +13304;EGYPTIAN HIEROGLYPH S044;Lo;0;L;;;;;N;;;;; +13305;EGYPTIAN HIEROGLYPH S045;Lo;0;L;;;;;N;;;;; +13306;EGYPTIAN HIEROGLYPH S046;Lo;0;L;;;;;N;;;;; +13307;EGYPTIAN HIEROGLYPH T001;Lo;0;L;;;;;N;;;;; +13308;EGYPTIAN HIEROGLYPH T002;Lo;0;L;;;;;N;;;;; +13309;EGYPTIAN HIEROGLYPH T003;Lo;0;L;;;;;N;;;;; +1330A;EGYPTIAN HIEROGLYPH T003A;Lo;0;L;;;;;N;;;;; +1330B;EGYPTIAN HIEROGLYPH T004;Lo;0;L;;;;;N;;;;; +1330C;EGYPTIAN HIEROGLYPH T005;Lo;0;L;;;;;N;;;;; +1330D;EGYPTIAN HIEROGLYPH T006;Lo;0;L;;;;;N;;;;; +1330E;EGYPTIAN HIEROGLYPH T007;Lo;0;L;;;;;N;;;;; +1330F;EGYPTIAN HIEROGLYPH T007A;Lo;0;L;;;;;N;;;;; +13310;EGYPTIAN HIEROGLYPH T008;Lo;0;L;;;;;N;;;;; +13311;EGYPTIAN HIEROGLYPH T008A;Lo;0;L;;;;;N;;;;; +13312;EGYPTIAN HIEROGLYPH T009;Lo;0;L;;;;;N;;;;; +13313;EGYPTIAN HIEROGLYPH T009A;Lo;0;L;;;;;N;;;;; +13314;EGYPTIAN HIEROGLYPH T010;Lo;0;L;;;;;N;;;;; +13315;EGYPTIAN HIEROGLYPH T011;Lo;0;L;;;;;N;;;;; +13316;EGYPTIAN HIEROGLYPH T011A;Lo;0;L;;;;;N;;;;; +13317;EGYPTIAN HIEROGLYPH T012;Lo;0;L;;;;;N;;;;; +13318;EGYPTIAN HIEROGLYPH T013;Lo;0;L;;;;;N;;;;; +13319;EGYPTIAN HIEROGLYPH T014;Lo;0;L;;;;;N;;;;; +1331A;EGYPTIAN HIEROGLYPH T015;Lo;0;L;;;;;N;;;;; +1331B;EGYPTIAN HIEROGLYPH T016;Lo;0;L;;;;;N;;;;; +1331C;EGYPTIAN HIEROGLYPH T016A;Lo;0;L;;;;;N;;;;; +1331D;EGYPTIAN HIEROGLYPH T017;Lo;0;L;;;;;N;;;;; +1331E;EGYPTIAN HIEROGLYPH T018;Lo;0;L;;;;;N;;;;; +1331F;EGYPTIAN HIEROGLYPH T019;Lo;0;L;;;;;N;;;;; +13320;EGYPTIAN HIEROGLYPH T020;Lo;0;L;;;;;N;;;;; +13321;EGYPTIAN HIEROGLYPH T021;Lo;0;L;;;;;N;;;;; +13322;EGYPTIAN HIEROGLYPH T022;Lo;0;L;;;;;N;;;;; +13323;EGYPTIAN HIEROGLYPH T023;Lo;0;L;;;;;N;;;;; +13324;EGYPTIAN HIEROGLYPH T024;Lo;0;L;;;;;N;;;;; +13325;EGYPTIAN HIEROGLYPH T025;Lo;0;L;;;;;N;;;;; +13326;EGYPTIAN HIEROGLYPH T026;Lo;0;L;;;;;N;;;;; +13327;EGYPTIAN HIEROGLYPH T027;Lo;0;L;;;;;N;;;;; +13328;EGYPTIAN HIEROGLYPH T028;Lo;0;L;;;;;N;;;;; +13329;EGYPTIAN HIEROGLYPH T029;Lo;0;L;;;;;N;;;;; +1332A;EGYPTIAN HIEROGLYPH T030;Lo;0;L;;;;;N;;;;; +1332B;EGYPTIAN HIEROGLYPH T031;Lo;0;L;;;;;N;;;;; +1332C;EGYPTIAN HIEROGLYPH T032;Lo;0;L;;;;;N;;;;; +1332D;EGYPTIAN HIEROGLYPH T032A;Lo;0;L;;;;;N;;;;; +1332E;EGYPTIAN HIEROGLYPH T033;Lo;0;L;;;;;N;;;;; +1332F;EGYPTIAN HIEROGLYPH T033A;Lo;0;L;;;;;N;;;;; +13330;EGYPTIAN HIEROGLYPH T034;Lo;0;L;;;;;N;;;;; +13331;EGYPTIAN HIEROGLYPH T035;Lo;0;L;;;;;N;;;;; +13332;EGYPTIAN HIEROGLYPH T036;Lo;0;L;;;;;N;;;;; +13333;EGYPTIAN HIEROGLYPH U001;Lo;0;L;;;;;N;;;;; +13334;EGYPTIAN HIEROGLYPH U002;Lo;0;L;;;;;N;;;;; +13335;EGYPTIAN HIEROGLYPH U003;Lo;0;L;;;;;N;;;;; +13336;EGYPTIAN HIEROGLYPH U004;Lo;0;L;;;;;N;;;;; +13337;EGYPTIAN HIEROGLYPH U005;Lo;0;L;;;;;N;;;;; +13338;EGYPTIAN HIEROGLYPH U006;Lo;0;L;;;;;N;;;;; +13339;EGYPTIAN HIEROGLYPH U006A;Lo;0;L;;;;;N;;;;; +1333A;EGYPTIAN HIEROGLYPH U006B;Lo;0;L;;;;;N;;;;; +1333B;EGYPTIAN HIEROGLYPH U007;Lo;0;L;;;;;N;;;;; +1333C;EGYPTIAN HIEROGLYPH U008;Lo;0;L;;;;;N;;;;; +1333D;EGYPTIAN HIEROGLYPH U009;Lo;0;L;;;;;N;;;;; +1333E;EGYPTIAN HIEROGLYPH U010;Lo;0;L;;;;;N;;;;; +1333F;EGYPTIAN HIEROGLYPH U011;Lo;0;L;;;;;N;;;;; +13340;EGYPTIAN HIEROGLYPH U012;Lo;0;L;;;;;N;;;;; +13341;EGYPTIAN HIEROGLYPH U013;Lo;0;L;;;;;N;;;;; +13342;EGYPTIAN HIEROGLYPH U014;Lo;0;L;;;;;N;;;;; +13343;EGYPTIAN HIEROGLYPH U015;Lo;0;L;;;;;N;;;;; +13344;EGYPTIAN HIEROGLYPH U016;Lo;0;L;;;;;N;;;;; +13345;EGYPTIAN HIEROGLYPH U017;Lo;0;L;;;;;N;;;;; +13346;EGYPTIAN HIEROGLYPH U018;Lo;0;L;;;;;N;;;;; +13347;EGYPTIAN HIEROGLYPH U019;Lo;0;L;;;;;N;;;;; +13348;EGYPTIAN HIEROGLYPH U020;Lo;0;L;;;;;N;;;;; +13349;EGYPTIAN HIEROGLYPH U021;Lo;0;L;;;;;N;;;;; +1334A;EGYPTIAN HIEROGLYPH U022;Lo;0;L;;;;;N;;;;; +1334B;EGYPTIAN HIEROGLYPH U023;Lo;0;L;;;;;N;;;;; +1334C;EGYPTIAN HIEROGLYPH U023A;Lo;0;L;;;;;N;;;;; +1334D;EGYPTIAN HIEROGLYPH U024;Lo;0;L;;;;;N;;;;; +1334E;EGYPTIAN HIEROGLYPH U025;Lo;0;L;;;;;N;;;;; +1334F;EGYPTIAN HIEROGLYPH U026;Lo;0;L;;;;;N;;;;; +13350;EGYPTIAN HIEROGLYPH U027;Lo;0;L;;;;;N;;;;; +13351;EGYPTIAN HIEROGLYPH U028;Lo;0;L;;;;;N;;;;; +13352;EGYPTIAN HIEROGLYPH U029;Lo;0;L;;;;;N;;;;; +13353;EGYPTIAN HIEROGLYPH U029A;Lo;0;L;;;;;N;;;;; +13354;EGYPTIAN HIEROGLYPH U030;Lo;0;L;;;;;N;;;;; +13355;EGYPTIAN HIEROGLYPH U031;Lo;0;L;;;;;N;;;;; +13356;EGYPTIAN HIEROGLYPH U032;Lo;0;L;;;;;N;;;;; +13357;EGYPTIAN HIEROGLYPH U032A;Lo;0;L;;;;;N;;;;; +13358;EGYPTIAN HIEROGLYPH U033;Lo;0;L;;;;;N;;;;; +13359;EGYPTIAN HIEROGLYPH U034;Lo;0;L;;;;;N;;;;; +1335A;EGYPTIAN HIEROGLYPH U035;Lo;0;L;;;;;N;;;;; +1335B;EGYPTIAN HIEROGLYPH U036;Lo;0;L;;;;;N;;;;; +1335C;EGYPTIAN HIEROGLYPH U037;Lo;0;L;;;;;N;;;;; +1335D;EGYPTIAN HIEROGLYPH U038;Lo;0;L;;;;;N;;;;; +1335E;EGYPTIAN HIEROGLYPH U039;Lo;0;L;;;;;N;;;;; +1335F;EGYPTIAN HIEROGLYPH U040;Lo;0;L;;;;;N;;;;; +13360;EGYPTIAN HIEROGLYPH U041;Lo;0;L;;;;;N;;;;; +13361;EGYPTIAN HIEROGLYPH U042;Lo;0;L;;;;;N;;;;; +13362;EGYPTIAN HIEROGLYPH V001;Lo;0;L;;;;;N;;;;; +13363;EGYPTIAN HIEROGLYPH V001A;Lo;0;L;;;;;N;;;;; +13364;EGYPTIAN HIEROGLYPH V001B;Lo;0;L;;;;;N;;;;; +13365;EGYPTIAN HIEROGLYPH V001C;Lo;0;L;;;;;N;;;;; +13366;EGYPTIAN HIEROGLYPH V001D;Lo;0;L;;;;;N;;;;; +13367;EGYPTIAN HIEROGLYPH V001E;Lo;0;L;;;;;N;;;;; +13368;EGYPTIAN HIEROGLYPH V001F;Lo;0;L;;;;;N;;;;; +13369;EGYPTIAN HIEROGLYPH V001G;Lo;0;L;;;;;N;;;;; +1336A;EGYPTIAN HIEROGLYPH V001H;Lo;0;L;;;;;N;;;;; +1336B;EGYPTIAN HIEROGLYPH V001I;Lo;0;L;;;;;N;;;;; +1336C;EGYPTIAN HIEROGLYPH V002;Lo;0;L;;;;;N;;;;; +1336D;EGYPTIAN HIEROGLYPH V002A;Lo;0;L;;;;;N;;;;; +1336E;EGYPTIAN HIEROGLYPH V003;Lo;0;L;;;;;N;;;;; +1336F;EGYPTIAN HIEROGLYPH V004;Lo;0;L;;;;;N;;;;; +13370;EGYPTIAN HIEROGLYPH V005;Lo;0;L;;;;;N;;;;; +13371;EGYPTIAN HIEROGLYPH V006;Lo;0;L;;;;;N;;;;; +13372;EGYPTIAN HIEROGLYPH V007;Lo;0;L;;;;;N;;;;; +13373;EGYPTIAN HIEROGLYPH V007A;Lo;0;L;;;;;N;;;;; +13374;EGYPTIAN HIEROGLYPH V007B;Lo;0;L;;;;;N;;;;; +13375;EGYPTIAN HIEROGLYPH V008;Lo;0;L;;;;;N;;;;; +13376;EGYPTIAN HIEROGLYPH V009;Lo;0;L;;;;;N;;;;; +13377;EGYPTIAN HIEROGLYPH V010;Lo;0;L;;;;;N;;;;; +13378;EGYPTIAN HIEROGLYPH V011;Lo;0;L;;;;;N;;;;; +13379;EGYPTIAN HIEROGLYPH V011A;Lo;0;L;;;;;N;;;;; +1337A;EGYPTIAN HIEROGLYPH V011B;Lo;0;L;;;;;N;;;;; +1337B;EGYPTIAN HIEROGLYPH V011C;Lo;0;L;;;;;N;;;;; +1337C;EGYPTIAN HIEROGLYPH V012;Lo;0;L;;;;;N;;;;; +1337D;EGYPTIAN HIEROGLYPH V012A;Lo;0;L;;;;;N;;;;; +1337E;EGYPTIAN HIEROGLYPH V012B;Lo;0;L;;;;;N;;;;; +1337F;EGYPTIAN HIEROGLYPH V013;Lo;0;L;;;;;N;;;;; +13380;EGYPTIAN HIEROGLYPH V014;Lo;0;L;;;;;N;;;;; +13381;EGYPTIAN HIEROGLYPH V015;Lo;0;L;;;;;N;;;;; +13382;EGYPTIAN HIEROGLYPH V016;Lo;0;L;;;;;N;;;;; +13383;EGYPTIAN HIEROGLYPH V017;Lo;0;L;;;;;N;;;;; +13384;EGYPTIAN HIEROGLYPH V018;Lo;0;L;;;;;N;;;;; +13385;EGYPTIAN HIEROGLYPH V019;Lo;0;L;;;;;N;;;;; +13386;EGYPTIAN HIEROGLYPH V020;Lo;0;L;;;;;N;;;;; +13387;EGYPTIAN HIEROGLYPH V020A;Lo;0;L;;;;;N;;;;; +13388;EGYPTIAN HIEROGLYPH V020B;Lo;0;L;;;;;N;;;;; +13389;EGYPTIAN HIEROGLYPH V020C;Lo;0;L;;;;;N;;;;; +1338A;EGYPTIAN HIEROGLYPH V020D;Lo;0;L;;;;;N;;;;; +1338B;EGYPTIAN HIEROGLYPH V020E;Lo;0;L;;;;;N;;;;; +1338C;EGYPTIAN HIEROGLYPH V020F;Lo;0;L;;;;;N;;;;; +1338D;EGYPTIAN HIEROGLYPH V020G;Lo;0;L;;;;;N;;;;; +1338E;EGYPTIAN HIEROGLYPH V020H;Lo;0;L;;;;;N;;;;; +1338F;EGYPTIAN HIEROGLYPH V020I;Lo;0;L;;;;;N;;;;; +13390;EGYPTIAN HIEROGLYPH V020J;Lo;0;L;;;;;N;;;;; +13391;EGYPTIAN HIEROGLYPH V020K;Lo;0;L;;;;;N;;;;; +13392;EGYPTIAN HIEROGLYPH V020L;Lo;0;L;;;;;N;;;;; +13393;EGYPTIAN HIEROGLYPH V021;Lo;0;L;;;;;N;;;;; +13394;EGYPTIAN HIEROGLYPH V022;Lo;0;L;;;;;N;;;;; +13395;EGYPTIAN HIEROGLYPH V023;Lo;0;L;;;;;N;;;;; +13396;EGYPTIAN HIEROGLYPH V023A;Lo;0;L;;;;;N;;;;; +13397;EGYPTIAN HIEROGLYPH V024;Lo;0;L;;;;;N;;;;; +13398;EGYPTIAN HIEROGLYPH V025;Lo;0;L;;;;;N;;;;; +13399;EGYPTIAN HIEROGLYPH V026;Lo;0;L;;;;;N;;;;; +1339A;EGYPTIAN HIEROGLYPH V027;Lo;0;L;;;;;N;;;;; +1339B;EGYPTIAN HIEROGLYPH V028;Lo;0;L;;;;;N;;;;; +1339C;EGYPTIAN HIEROGLYPH V028A;Lo;0;L;;;;;N;;;;; +1339D;EGYPTIAN HIEROGLYPH V029;Lo;0;L;;;;;N;;;;; +1339E;EGYPTIAN HIEROGLYPH V029A;Lo;0;L;;;;;N;;;;; +1339F;EGYPTIAN HIEROGLYPH V030;Lo;0;L;;;;;N;;;;; +133A0;EGYPTIAN HIEROGLYPH V030A;Lo;0;L;;;;;N;;;;; +133A1;EGYPTIAN HIEROGLYPH V031;Lo;0;L;;;;;N;;;;; +133A2;EGYPTIAN HIEROGLYPH V031A;Lo;0;L;;;;;N;;;;; +133A3;EGYPTIAN HIEROGLYPH V032;Lo;0;L;;;;;N;;;;; +133A4;EGYPTIAN HIEROGLYPH V033;Lo;0;L;;;;;N;;;;; +133A5;EGYPTIAN HIEROGLYPH V033A;Lo;0;L;;;;;N;;;;; +133A6;EGYPTIAN HIEROGLYPH V034;Lo;0;L;;;;;N;;;;; +133A7;EGYPTIAN HIEROGLYPH V035;Lo;0;L;;;;;N;;;;; +133A8;EGYPTIAN HIEROGLYPH V036;Lo;0;L;;;;;N;;;;; +133A9;EGYPTIAN HIEROGLYPH V037;Lo;0;L;;;;;N;;;;; +133AA;EGYPTIAN HIEROGLYPH V037A;Lo;0;L;;;;;N;;;;; +133AB;EGYPTIAN HIEROGLYPH V038;Lo;0;L;;;;;N;;;;; +133AC;EGYPTIAN HIEROGLYPH V039;Lo;0;L;;;;;N;;;;; +133AD;EGYPTIAN HIEROGLYPH V040;Lo;0;L;;;;;N;;;;; +133AE;EGYPTIAN HIEROGLYPH V040A;Lo;0;L;;;;;N;;;;; +133AF;EGYPTIAN HIEROGLYPH W001;Lo;0;L;;;;;N;;;;; +133B0;EGYPTIAN HIEROGLYPH W002;Lo;0;L;;;;;N;;;;; +133B1;EGYPTIAN HIEROGLYPH W003;Lo;0;L;;;;;N;;;;; +133B2;EGYPTIAN HIEROGLYPH W003A;Lo;0;L;;;;;N;;;;; +133B3;EGYPTIAN HIEROGLYPH W004;Lo;0;L;;;;;N;;;;; +133B4;EGYPTIAN HIEROGLYPH W005;Lo;0;L;;;;;N;;;;; +133B5;EGYPTIAN HIEROGLYPH W006;Lo;0;L;;;;;N;;;;; +133B6;EGYPTIAN HIEROGLYPH W007;Lo;0;L;;;;;N;;;;; +133B7;EGYPTIAN HIEROGLYPH W008;Lo;0;L;;;;;N;;;;; +133B8;EGYPTIAN HIEROGLYPH W009;Lo;0;L;;;;;N;;;;; +133B9;EGYPTIAN HIEROGLYPH W009A;Lo;0;L;;;;;N;;;;; +133BA;EGYPTIAN HIEROGLYPH W010;Lo;0;L;;;;;N;;;;; +133BB;EGYPTIAN HIEROGLYPH W010A;Lo;0;L;;;;;N;;;;; +133BC;EGYPTIAN HIEROGLYPH W011;Lo;0;L;;;;;N;;;;; +133BD;EGYPTIAN HIEROGLYPH W012;Lo;0;L;;;;;N;;;;; +133BE;EGYPTIAN HIEROGLYPH W013;Lo;0;L;;;;;N;;;;; +133BF;EGYPTIAN HIEROGLYPH W014;Lo;0;L;;;;;N;;;;; +133C0;EGYPTIAN HIEROGLYPH W014A;Lo;0;L;;;;;N;;;;; +133C1;EGYPTIAN HIEROGLYPH W015;Lo;0;L;;;;;N;;;;; +133C2;EGYPTIAN HIEROGLYPH W016;Lo;0;L;;;;;N;;;;; +133C3;EGYPTIAN HIEROGLYPH W017;Lo;0;L;;;;;N;;;;; +133C4;EGYPTIAN HIEROGLYPH W017A;Lo;0;L;;;;;N;;;;; +133C5;EGYPTIAN HIEROGLYPH W018;Lo;0;L;;;;;N;;;;; +133C6;EGYPTIAN HIEROGLYPH W018A;Lo;0;L;;;;;N;;;;; +133C7;EGYPTIAN HIEROGLYPH W019;Lo;0;L;;;;;N;;;;; +133C8;EGYPTIAN HIEROGLYPH W020;Lo;0;L;;;;;N;;;;; +133C9;EGYPTIAN HIEROGLYPH W021;Lo;0;L;;;;;N;;;;; +133CA;EGYPTIAN HIEROGLYPH W022;Lo;0;L;;;;;N;;;;; +133CB;EGYPTIAN HIEROGLYPH W023;Lo;0;L;;;;;N;;;;; +133CC;EGYPTIAN HIEROGLYPH W024;Lo;0;L;;;;;N;;;;; +133CD;EGYPTIAN HIEROGLYPH W024A;Lo;0;L;;;;;N;;;;; +133CE;EGYPTIAN HIEROGLYPH W025;Lo;0;L;;;;;N;;;;; +133CF;EGYPTIAN HIEROGLYPH X001;Lo;0;L;;;;;N;;;;; +133D0;EGYPTIAN HIEROGLYPH X002;Lo;0;L;;;;;N;;;;; +133D1;EGYPTIAN HIEROGLYPH X003;Lo;0;L;;;;;N;;;;; +133D2;EGYPTIAN HIEROGLYPH X004;Lo;0;L;;;;;N;;;;; +133D3;EGYPTIAN HIEROGLYPH X004A;Lo;0;L;;;;;N;;;;; +133D4;EGYPTIAN HIEROGLYPH X004B;Lo;0;L;;;;;N;;;;; +133D5;EGYPTIAN HIEROGLYPH X005;Lo;0;L;;;;;N;;;;; +133D6;EGYPTIAN HIEROGLYPH X006;Lo;0;L;;;;;N;;;;; +133D7;EGYPTIAN HIEROGLYPH X006A;Lo;0;L;;;;;N;;;;; +133D8;EGYPTIAN HIEROGLYPH X007;Lo;0;L;;;;;N;;;;; +133D9;EGYPTIAN HIEROGLYPH X008;Lo;0;L;;;;;N;;;;; +133DA;EGYPTIAN HIEROGLYPH X008A;Lo;0;L;;;;;N;;;;; +133DB;EGYPTIAN HIEROGLYPH Y001;Lo;0;L;;;;;N;;;;; +133DC;EGYPTIAN HIEROGLYPH Y001A;Lo;0;L;;;;;N;;;;; +133DD;EGYPTIAN HIEROGLYPH Y002;Lo;0;L;;;;;N;;;;; +133DE;EGYPTIAN HIEROGLYPH Y003;Lo;0;L;;;;;N;;;;; +133DF;EGYPTIAN HIEROGLYPH Y004;Lo;0;L;;;;;N;;;;; +133E0;EGYPTIAN HIEROGLYPH Y005;Lo;0;L;;;;;N;;;;; +133E1;EGYPTIAN HIEROGLYPH Y006;Lo;0;L;;;;;N;;;;; +133E2;EGYPTIAN HIEROGLYPH Y007;Lo;0;L;;;;;N;;;;; +133E3;EGYPTIAN HIEROGLYPH Y008;Lo;0;L;;;;;N;;;;; +133E4;EGYPTIAN HIEROGLYPH Z001;Lo;0;L;;;;;N;;;;; +133E5;EGYPTIAN HIEROGLYPH Z002;Lo;0;L;;;;;N;;;;; +133E6;EGYPTIAN HIEROGLYPH Z002A;Lo;0;L;;;;;N;;;;; +133E7;EGYPTIAN HIEROGLYPH Z002B;Lo;0;L;;;;;N;;;;; +133E8;EGYPTIAN HIEROGLYPH Z002C;Lo;0;L;;;;;N;;;;; +133E9;EGYPTIAN HIEROGLYPH Z002D;Lo;0;L;;;;;N;;;;; +133EA;EGYPTIAN HIEROGLYPH Z003;Lo;0;L;;;;;N;;;;; +133EB;EGYPTIAN HIEROGLYPH Z003A;Lo;0;L;;;;;N;;;;; +133EC;EGYPTIAN HIEROGLYPH Z003B;Lo;0;L;;;;;N;;;;; +133ED;EGYPTIAN HIEROGLYPH Z004;Lo;0;L;;;;;N;;;;; +133EE;EGYPTIAN HIEROGLYPH Z004A;Lo;0;L;;;;;N;;;;; +133EF;EGYPTIAN HIEROGLYPH Z005;Lo;0;L;;;;;N;;;;; +133F0;EGYPTIAN HIEROGLYPH Z005A;Lo;0;L;;;;;N;;;;; +133F1;EGYPTIAN HIEROGLYPH Z006;Lo;0;L;;;;;N;;;;; +133F2;EGYPTIAN HIEROGLYPH Z007;Lo;0;L;;;;;N;;;;; +133F3;EGYPTIAN HIEROGLYPH Z008;Lo;0;L;;;;;N;;;;; +133F4;EGYPTIAN HIEROGLYPH Z009;Lo;0;L;;;;;N;;;;; +133F5;EGYPTIAN HIEROGLYPH Z010;Lo;0;L;;;;;N;;;;; +133F6;EGYPTIAN HIEROGLYPH Z011;Lo;0;L;;;;;N;;;;; +133F7;EGYPTIAN HIEROGLYPH Z012;Lo;0;L;;;;;N;;;;; +133F8;EGYPTIAN HIEROGLYPH Z013;Lo;0;L;;;;;N;;;;; +133F9;EGYPTIAN HIEROGLYPH Z014;Lo;0;L;;;;;N;;;;; +133FA;EGYPTIAN HIEROGLYPH Z015;Lo;0;L;;;;;N;;;;; +133FB;EGYPTIAN HIEROGLYPH Z015A;Lo;0;L;;;;;N;;;;; +133FC;EGYPTIAN HIEROGLYPH Z015B;Lo;0;L;;;;;N;;;;; +133FD;EGYPTIAN HIEROGLYPH Z015C;Lo;0;L;;;;;N;;;;; +133FE;EGYPTIAN HIEROGLYPH Z015D;Lo;0;L;;;;;N;;;;; +133FF;EGYPTIAN HIEROGLYPH Z015E;Lo;0;L;;;;;N;;;;; +13400;EGYPTIAN HIEROGLYPH Z015F;Lo;0;L;;;;;N;;;;; +13401;EGYPTIAN HIEROGLYPH Z015G;Lo;0;L;;;;;N;;;;; +13402;EGYPTIAN HIEROGLYPH Z015H;Lo;0;L;;;;;N;;;;; +13403;EGYPTIAN HIEROGLYPH Z015I;Lo;0;L;;;;;N;;;;; +13404;EGYPTIAN HIEROGLYPH Z016;Lo;0;L;;;;;N;;;;; +13405;EGYPTIAN HIEROGLYPH Z016A;Lo;0;L;;;;;N;;;;; +13406;EGYPTIAN HIEROGLYPH Z016B;Lo;0;L;;;;;N;;;;; +13407;EGYPTIAN HIEROGLYPH Z016C;Lo;0;L;;;;;N;;;;; +13408;EGYPTIAN HIEROGLYPH Z016D;Lo;0;L;;;;;N;;;;; +13409;EGYPTIAN HIEROGLYPH Z016E;Lo;0;L;;;;;N;;;;; +1340A;EGYPTIAN HIEROGLYPH Z016F;Lo;0;L;;;;;N;;;;; +1340B;EGYPTIAN HIEROGLYPH Z016G;Lo;0;L;;;;;N;;;;; +1340C;EGYPTIAN HIEROGLYPH Z016H;Lo;0;L;;;;;N;;;;; +1340D;EGYPTIAN HIEROGLYPH AA001;Lo;0;L;;;;;N;;;;; +1340E;EGYPTIAN HIEROGLYPH AA002;Lo;0;L;;;;;N;;;;; +1340F;EGYPTIAN HIEROGLYPH AA003;Lo;0;L;;;;;N;;;;; +13410;EGYPTIAN HIEROGLYPH AA004;Lo;0;L;;;;;N;;;;; +13411;EGYPTIAN HIEROGLYPH AA005;Lo;0;L;;;;;N;;;;; +13412;EGYPTIAN HIEROGLYPH AA006;Lo;0;L;;;;;N;;;;; +13413;EGYPTIAN HIEROGLYPH AA007;Lo;0;L;;;;;N;;;;; +13414;EGYPTIAN HIEROGLYPH AA007A;Lo;0;L;;;;;N;;;;; +13415;EGYPTIAN HIEROGLYPH AA007B;Lo;0;L;;;;;N;;;;; +13416;EGYPTIAN HIEROGLYPH AA008;Lo;0;L;;;;;N;;;;; +13417;EGYPTIAN HIEROGLYPH AA009;Lo;0;L;;;;;N;;;;; +13418;EGYPTIAN HIEROGLYPH AA010;Lo;0;L;;;;;N;;;;; +13419;EGYPTIAN HIEROGLYPH AA011;Lo;0;L;;;;;N;;;;; +1341A;EGYPTIAN HIEROGLYPH AA012;Lo;0;L;;;;;N;;;;; +1341B;EGYPTIAN HIEROGLYPH AA013;Lo;0;L;;;;;N;;;;; +1341C;EGYPTIAN HIEROGLYPH AA014;Lo;0;L;;;;;N;;;;; +1341D;EGYPTIAN HIEROGLYPH AA015;Lo;0;L;;;;;N;;;;; +1341E;EGYPTIAN HIEROGLYPH AA016;Lo;0;L;;;;;N;;;;; +1341F;EGYPTIAN HIEROGLYPH AA017;Lo;0;L;;;;;N;;;;; +13420;EGYPTIAN HIEROGLYPH AA018;Lo;0;L;;;;;N;;;;; +13421;EGYPTIAN HIEROGLYPH AA019;Lo;0;L;;;;;N;;;;; +13422;EGYPTIAN HIEROGLYPH AA020;Lo;0;L;;;;;N;;;;; +13423;EGYPTIAN HIEROGLYPH AA021;Lo;0;L;;;;;N;;;;; +13424;EGYPTIAN HIEROGLYPH AA022;Lo;0;L;;;;;N;;;;; +13425;EGYPTIAN HIEROGLYPH AA023;Lo;0;L;;;;;N;;;;; +13426;EGYPTIAN HIEROGLYPH AA024;Lo;0;L;;;;;N;;;;; +13427;EGYPTIAN HIEROGLYPH AA025;Lo;0;L;;;;;N;;;;; +13428;EGYPTIAN HIEROGLYPH AA026;Lo;0;L;;;;;N;;;;; +13429;EGYPTIAN HIEROGLYPH AA027;Lo;0;L;;;;;N;;;;; +1342A;EGYPTIAN HIEROGLYPH AA028;Lo;0;L;;;;;N;;;;; +1342B;EGYPTIAN HIEROGLYPH AA029;Lo;0;L;;;;;N;;;;; +1342C;EGYPTIAN HIEROGLYPH AA030;Lo;0;L;;;;;N;;;;; +1342D;EGYPTIAN HIEROGLYPH AA031;Lo;0;L;;;;;N;;;;; +1342E;EGYPTIAN HIEROGLYPH AA032;Lo;0;L;;;;;N;;;;; +16800;BAMUM LETTER PHASE-A NGKUE MFON;Lo;0;L;;;;;N;;;;; +16801;BAMUM LETTER PHASE-A GBIEE FON;Lo;0;L;;;;;N;;;;; +16802;BAMUM LETTER PHASE-A PON MFON PIPAEMGBIEE;Lo;0;L;;;;;N;;;;; +16803;BAMUM LETTER PHASE-A PON MFON PIPAEMBA;Lo;0;L;;;;;N;;;;; +16804;BAMUM LETTER PHASE-A NAA MFON;Lo;0;L;;;;;N;;;;; +16805;BAMUM LETTER PHASE-A SHUENSHUET;Lo;0;L;;;;;N;;;;; +16806;BAMUM LETTER PHASE-A TITA MFON;Lo;0;L;;;;;N;;;;; +16807;BAMUM LETTER PHASE-A NZA MFON;Lo;0;L;;;;;N;;;;; +16808;BAMUM LETTER PHASE-A SHINDA PA NJI;Lo;0;L;;;;;N;;;;; +16809;BAMUM LETTER PHASE-A PON PA NJI PIPAEMGBIEE;Lo;0;L;;;;;N;;;;; +1680A;BAMUM LETTER PHASE-A PON PA NJI PIPAEMBA;Lo;0;L;;;;;N;;;;; +1680B;BAMUM LETTER PHASE-A MAEMBGBIEE;Lo;0;L;;;;;N;;;;; +1680C;BAMUM LETTER PHASE-A TU MAEMBA;Lo;0;L;;;;;N;;;;; +1680D;BAMUM LETTER PHASE-A NGANGU;Lo;0;L;;;;;N;;;;; +1680E;BAMUM LETTER PHASE-A MAEMVEUX;Lo;0;L;;;;;N;;;;; +1680F;BAMUM LETTER PHASE-A MANSUAE;Lo;0;L;;;;;N;;;;; +16810;BAMUM LETTER PHASE-A MVEUAENGAM;Lo;0;L;;;;;N;;;;; +16811;BAMUM LETTER PHASE-A SEUNYAM;Lo;0;L;;;;;N;;;;; +16812;BAMUM LETTER PHASE-A NTOQPEN;Lo;0;L;;;;;N;;;;; +16813;BAMUM LETTER PHASE-A KEUKEUTNDA;Lo;0;L;;;;;N;;;;; +16814;BAMUM LETTER PHASE-A NKINDI;Lo;0;L;;;;;N;;;;; +16815;BAMUM LETTER PHASE-A SUU;Lo;0;L;;;;;N;;;;; +16816;BAMUM LETTER PHASE-A NGKUENZEUM;Lo;0;L;;;;;N;;;;; +16817;BAMUM LETTER PHASE-A LAPAQ;Lo;0;L;;;;;N;;;;; +16818;BAMUM LETTER PHASE-A LET KUT;Lo;0;L;;;;;N;;;;; +16819;BAMUM LETTER PHASE-A NTAP MFAA;Lo;0;L;;;;;N;;;;; +1681A;BAMUM LETTER PHASE-A MAEKEUP;Lo;0;L;;;;;N;;;;; +1681B;BAMUM LETTER PHASE-A PASHAE;Lo;0;L;;;;;N;;;;; +1681C;BAMUM LETTER PHASE-A GHEUAERAE;Lo;0;L;;;;;N;;;;; +1681D;BAMUM LETTER PHASE-A PAMSHAE;Lo;0;L;;;;;N;;;;; +1681E;BAMUM LETTER PHASE-A MON NGGEUAET;Lo;0;L;;;;;N;;;;; +1681F;BAMUM LETTER PHASE-A NZUN MEUT;Lo;0;L;;;;;N;;;;; +16820;BAMUM LETTER PHASE-A U YUQ NAE;Lo;0;L;;;;;N;;;;; +16821;BAMUM LETTER PHASE-A GHEUAEGHEUAE;Lo;0;L;;;;;N;;;;; +16822;BAMUM LETTER PHASE-A NTAP NTAA;Lo;0;L;;;;;N;;;;; +16823;BAMUM LETTER PHASE-A SISA;Lo;0;L;;;;;N;;;;; +16824;BAMUM LETTER PHASE-A MGBASA;Lo;0;L;;;;;N;;;;; +16825;BAMUM LETTER PHASE-A MEUNJOMNDEUQ;Lo;0;L;;;;;N;;;;; +16826;BAMUM LETTER PHASE-A MOOMPUQ;Lo;0;L;;;;;N;;;;; +16827;BAMUM LETTER PHASE-A KAFA;Lo;0;L;;;;;N;;;;; +16828;BAMUM LETTER PHASE-A PA LEERAEWA;Lo;0;L;;;;;N;;;;; +16829;BAMUM LETTER PHASE-A NDA LEERAEWA;Lo;0;L;;;;;N;;;;; +1682A;BAMUM LETTER PHASE-A PET;Lo;0;L;;;;;N;;;;; +1682B;BAMUM LETTER PHASE-A MAEMKPEN;Lo;0;L;;;;;N;;;;; +1682C;BAMUM LETTER PHASE-A NIKA;Lo;0;L;;;;;N;;;;; +1682D;BAMUM LETTER PHASE-A PUP;Lo;0;L;;;;;N;;;;; +1682E;BAMUM LETTER PHASE-A TUAEP;Lo;0;L;;;;;N;;;;; +1682F;BAMUM LETTER PHASE-A LUAEP;Lo;0;L;;;;;N;;;;; +16830;BAMUM LETTER PHASE-A SONJAM;Lo;0;L;;;;;N;;;;; +16831;BAMUM LETTER PHASE-A TEUTEUWEN;Lo;0;L;;;;;N;;;;; +16832;BAMUM LETTER PHASE-A MAENYI;Lo;0;L;;;;;N;;;;; +16833;BAMUM LETTER PHASE-A KET;Lo;0;L;;;;;N;;;;; +16834;BAMUM LETTER PHASE-A NDAANGGEUAET;Lo;0;L;;;;;N;;;;; +16835;BAMUM LETTER PHASE-A KUOQ;Lo;0;L;;;;;N;;;;; +16836;BAMUM LETTER PHASE-A MOOMEUT;Lo;0;L;;;;;N;;;;; +16837;BAMUM LETTER PHASE-A SHUM;Lo;0;L;;;;;N;;;;; +16838;BAMUM LETTER PHASE-A LOMMAE;Lo;0;L;;;;;N;;;;; +16839;BAMUM LETTER PHASE-A FIRI;Lo;0;L;;;;;N;;;;; +1683A;BAMUM LETTER PHASE-A ROM;Lo;0;L;;;;;N;;;;; +1683B;BAMUM LETTER PHASE-A KPOQ;Lo;0;L;;;;;N;;;;; +1683C;BAMUM LETTER PHASE-A SOQ;Lo;0;L;;;;;N;;;;; +1683D;BAMUM LETTER PHASE-A MAP PIEET;Lo;0;L;;;;;N;;;;; +1683E;BAMUM LETTER PHASE-A SHIRAE;Lo;0;L;;;;;N;;;;; +1683F;BAMUM LETTER PHASE-A NTAP;Lo;0;L;;;;;N;;;;; +16840;BAMUM LETTER PHASE-A SHOQ NSHUT YUM;Lo;0;L;;;;;N;;;;; +16841;BAMUM LETTER PHASE-A NYIT MONGKEUAEQ;Lo;0;L;;;;;N;;;;; +16842;BAMUM LETTER PHASE-A PAARAE;Lo;0;L;;;;;N;;;;; +16843;BAMUM LETTER PHASE-A NKAARAE;Lo;0;L;;;;;N;;;;; +16844;BAMUM LETTER PHASE-A UNKNOWN;Lo;0;L;;;;;N;;;;; +16845;BAMUM LETTER PHASE-A NGGEN;Lo;0;L;;;;;N;;;;; +16846;BAMUM LETTER PHASE-A MAESI;Lo;0;L;;;;;N;;;;; +16847;BAMUM LETTER PHASE-A NJAM;Lo;0;L;;;;;N;;;;; +16848;BAMUM LETTER PHASE-A MBANYI;Lo;0;L;;;;;N;;;;; +16849;BAMUM LETTER PHASE-A NYET;Lo;0;L;;;;;N;;;;; +1684A;BAMUM LETTER PHASE-A TEUAEN;Lo;0;L;;;;;N;;;;; +1684B;BAMUM LETTER PHASE-A SOT;Lo;0;L;;;;;N;;;;; +1684C;BAMUM LETTER PHASE-A PAAM;Lo;0;L;;;;;N;;;;; +1684D;BAMUM LETTER PHASE-A NSHIEE;Lo;0;L;;;;;N;;;;; +1684E;BAMUM LETTER PHASE-A MAEM;Lo;0;L;;;;;N;;;;; +1684F;BAMUM LETTER PHASE-A NYI;Lo;0;L;;;;;N;;;;; +16850;BAMUM LETTER PHASE-A KAQ;Lo;0;L;;;;;N;;;;; +16851;BAMUM LETTER PHASE-A NSHA;Lo;0;L;;;;;N;;;;; +16852;BAMUM LETTER PHASE-A VEE;Lo;0;L;;;;;N;;;;; +16853;BAMUM LETTER PHASE-A LU;Lo;0;L;;;;;N;;;;; +16854;BAMUM LETTER PHASE-A NEN;Lo;0;L;;;;;N;;;;; +16855;BAMUM LETTER PHASE-A NAQ;Lo;0;L;;;;;N;;;;; +16856;BAMUM LETTER PHASE-A MBAQ;Lo;0;L;;;;;N;;;;; +16857;BAMUM LETTER PHASE-B NSHUET;Lo;0;L;;;;;N;;;;; +16858;BAMUM LETTER PHASE-B TU MAEMGBIEE;Lo;0;L;;;;;N;;;;; +16859;BAMUM LETTER PHASE-B SIEE;Lo;0;L;;;;;N;;;;; +1685A;BAMUM LETTER PHASE-B SET TU;Lo;0;L;;;;;N;;;;; +1685B;BAMUM LETTER PHASE-B LOM NTEUM;Lo;0;L;;;;;N;;;;; +1685C;BAMUM LETTER PHASE-B MBA MAELEE;Lo;0;L;;;;;N;;;;; +1685D;BAMUM LETTER PHASE-B KIEEM;Lo;0;L;;;;;N;;;;; +1685E;BAMUM LETTER PHASE-B YEURAE;Lo;0;L;;;;;N;;;;; +1685F;BAMUM LETTER PHASE-B MBAARAE;Lo;0;L;;;;;N;;;;; +16860;BAMUM LETTER PHASE-B KAM;Lo;0;L;;;;;N;;;;; +16861;BAMUM LETTER PHASE-B PEESHI;Lo;0;L;;;;;N;;;;; +16862;BAMUM LETTER PHASE-B YAFU LEERAEWA;Lo;0;L;;;;;N;;;;; +16863;BAMUM LETTER PHASE-B LAM NSHUT NYAM;Lo;0;L;;;;;N;;;;; +16864;BAMUM LETTER PHASE-B NTIEE SHEUOQ;Lo;0;L;;;;;N;;;;; +16865;BAMUM LETTER PHASE-B NDU NJAA;Lo;0;L;;;;;N;;;;; +16866;BAMUM LETTER PHASE-B GHEUGHEUAEM;Lo;0;L;;;;;N;;;;; +16867;BAMUM LETTER PHASE-B PIT;Lo;0;L;;;;;N;;;;; +16868;BAMUM LETTER PHASE-B TU NSIEE;Lo;0;L;;;;;N;;;;; +16869;BAMUM LETTER PHASE-B SHET NJAQ;Lo;0;L;;;;;N;;;;; +1686A;BAMUM LETTER PHASE-B SHEUAEQTU;Lo;0;L;;;;;N;;;;; +1686B;BAMUM LETTER PHASE-B MFON TEUAEQ;Lo;0;L;;;;;N;;;;; +1686C;BAMUM LETTER PHASE-B MBIT MBAAKET;Lo;0;L;;;;;N;;;;; +1686D;BAMUM LETTER PHASE-B NYI NTEUM;Lo;0;L;;;;;N;;;;; +1686E;BAMUM LETTER PHASE-B KEUPUQ;Lo;0;L;;;;;N;;;;; +1686F;BAMUM LETTER PHASE-B GHEUGHEN;Lo;0;L;;;;;N;;;;; +16870;BAMUM LETTER PHASE-B KEUYEUX;Lo;0;L;;;;;N;;;;; +16871;BAMUM LETTER PHASE-B LAANAE;Lo;0;L;;;;;N;;;;; +16872;BAMUM LETTER PHASE-B PARUM;Lo;0;L;;;;;N;;;;; +16873;BAMUM LETTER PHASE-B VEUM;Lo;0;L;;;;;N;;;;; +16874;BAMUM LETTER PHASE-B NGKINDI MVOP;Lo;0;L;;;;;N;;;;; +16875;BAMUM LETTER PHASE-B NGGEU MBU;Lo;0;L;;;;;N;;;;; +16876;BAMUM LETTER PHASE-B WUAET;Lo;0;L;;;;;N;;;;; +16877;BAMUM LETTER PHASE-B SAKEUAE;Lo;0;L;;;;;N;;;;; +16878;BAMUM LETTER PHASE-B TAAM;Lo;0;L;;;;;N;;;;; +16879;BAMUM LETTER PHASE-B MEUQ;Lo;0;L;;;;;N;;;;; +1687A;BAMUM LETTER PHASE-B NGGUOQ;Lo;0;L;;;;;N;;;;; +1687B;BAMUM LETTER PHASE-B NGGUOQ LARGE;Lo;0;L;;;;;N;;;;; +1687C;BAMUM LETTER PHASE-B MFIYAQ;Lo;0;L;;;;;N;;;;; +1687D;BAMUM LETTER PHASE-B SUE;Lo;0;L;;;;;N;;;;; +1687E;BAMUM LETTER PHASE-B MBEURI;Lo;0;L;;;;;N;;;;; +1687F;BAMUM LETTER PHASE-B MONTIEEN;Lo;0;L;;;;;N;;;;; +16880;BAMUM LETTER PHASE-B NYAEMAE;Lo;0;L;;;;;N;;;;; +16881;BAMUM LETTER PHASE-B PUNGAAM;Lo;0;L;;;;;N;;;;; +16882;BAMUM LETTER PHASE-B MEUT NGGEET;Lo;0;L;;;;;N;;;;; +16883;BAMUM LETTER PHASE-B FEUX;Lo;0;L;;;;;N;;;;; +16884;BAMUM LETTER PHASE-B MBUOQ;Lo;0;L;;;;;N;;;;; +16885;BAMUM LETTER PHASE-B FEE;Lo;0;L;;;;;N;;;;; +16886;BAMUM LETTER PHASE-B KEUAEM;Lo;0;L;;;;;N;;;;; +16887;BAMUM LETTER PHASE-B MA NJEUAENA;Lo;0;L;;;;;N;;;;; +16888;BAMUM LETTER PHASE-B MA NJUQA;Lo;0;L;;;;;N;;;;; +16889;BAMUM LETTER PHASE-B LET;Lo;0;L;;;;;N;;;;; +1688A;BAMUM LETTER PHASE-B NGGAAM;Lo;0;L;;;;;N;;;;; +1688B;BAMUM LETTER PHASE-B NSEN;Lo;0;L;;;;;N;;;;; +1688C;BAMUM LETTER PHASE-B MA;Lo;0;L;;;;;N;;;;; +1688D;BAMUM LETTER PHASE-B KIQ;Lo;0;L;;;;;N;;;;; +1688E;BAMUM LETTER PHASE-B NGOM;Lo;0;L;;;;;N;;;;; +1688F;BAMUM LETTER PHASE-C NGKUE MAEMBA;Lo;0;L;;;;;N;;;;; +16890;BAMUM LETTER PHASE-C NZA;Lo;0;L;;;;;N;;;;; +16891;BAMUM LETTER PHASE-C YUM;Lo;0;L;;;;;N;;;;; +16892;BAMUM LETTER PHASE-C WANGKUOQ;Lo;0;L;;;;;N;;;;; +16893;BAMUM LETTER PHASE-C NGGEN;Lo;0;L;;;;;N;;;;; +16894;BAMUM LETTER PHASE-C NDEUAEREE;Lo;0;L;;;;;N;;;;; +16895;BAMUM LETTER PHASE-C NGKAQ;Lo;0;L;;;;;N;;;;; +16896;BAMUM LETTER PHASE-C GHARAE;Lo;0;L;;;;;N;;;;; +16897;BAMUM LETTER PHASE-C MBEEKEET;Lo;0;L;;;;;N;;;;; +16898;BAMUM LETTER PHASE-C GBAYI;Lo;0;L;;;;;N;;;;; +16899;BAMUM LETTER PHASE-C NYIR MKPARAQ MEUN;Lo;0;L;;;;;N;;;;; +1689A;BAMUM LETTER PHASE-C NTU MBIT;Lo;0;L;;;;;N;;;;; +1689B;BAMUM LETTER PHASE-C MBEUM;Lo;0;L;;;;;N;;;;; +1689C;BAMUM LETTER PHASE-C PIRIEEN;Lo;0;L;;;;;N;;;;; +1689D;BAMUM LETTER PHASE-C NDOMBU;Lo;0;L;;;;;N;;;;; +1689E;BAMUM LETTER PHASE-C MBAA CABBAGE-TREE;Lo;0;L;;;;;N;;;;; +1689F;BAMUM LETTER PHASE-C KEUSHEUAEP;Lo;0;L;;;;;N;;;;; +168A0;BAMUM LETTER PHASE-C GHAP;Lo;0;L;;;;;N;;;;; +168A1;BAMUM LETTER PHASE-C KEUKAQ;Lo;0;L;;;;;N;;;;; +168A2;BAMUM LETTER PHASE-C YU MUOMAE;Lo;0;L;;;;;N;;;;; +168A3;BAMUM LETTER PHASE-C NZEUM;Lo;0;L;;;;;N;;;;; +168A4;BAMUM LETTER PHASE-C MBUE;Lo;0;L;;;;;N;;;;; +168A5;BAMUM LETTER PHASE-C NSEUAEN;Lo;0;L;;;;;N;;;;; +168A6;BAMUM LETTER PHASE-C MBIT;Lo;0;L;;;;;N;;;;; +168A7;BAMUM LETTER PHASE-C YEUQ;Lo;0;L;;;;;N;;;;; +168A8;BAMUM LETTER PHASE-C KPARAQ;Lo;0;L;;;;;N;;;;; +168A9;BAMUM LETTER PHASE-C KAA;Lo;0;L;;;;;N;;;;; +168AA;BAMUM LETTER PHASE-C SEUX;Lo;0;L;;;;;N;;;;; +168AB;BAMUM LETTER PHASE-C NDIDA;Lo;0;L;;;;;N;;;;; +168AC;BAMUM LETTER PHASE-C TAASHAE;Lo;0;L;;;;;N;;;;; +168AD;BAMUM LETTER PHASE-C NJUEQ;Lo;0;L;;;;;N;;;;; +168AE;BAMUM LETTER PHASE-C TITA YUE;Lo;0;L;;;;;N;;;;; +168AF;BAMUM LETTER PHASE-C SUAET;Lo;0;L;;;;;N;;;;; +168B0;BAMUM LETTER PHASE-C NGGUAEN NYAM;Lo;0;L;;;;;N;;;;; +168B1;BAMUM LETTER PHASE-C VEUX;Lo;0;L;;;;;N;;;;; +168B2;BAMUM LETTER PHASE-C NANSANAQ;Lo;0;L;;;;;N;;;;; +168B3;BAMUM LETTER PHASE-C MA KEUAERI;Lo;0;L;;;;;N;;;;; +168B4;BAMUM LETTER PHASE-C NTAA;Lo;0;L;;;;;N;;;;; +168B5;BAMUM LETTER PHASE-C NGGUON;Lo;0;L;;;;;N;;;;; +168B6;BAMUM LETTER PHASE-C LAP;Lo;0;L;;;;;N;;;;; +168B7;BAMUM LETTER PHASE-C MBIRIEEN;Lo;0;L;;;;;N;;;;; +168B8;BAMUM LETTER PHASE-C MGBASAQ;Lo;0;L;;;;;N;;;;; +168B9;BAMUM LETTER PHASE-C NTEUNGBA;Lo;0;L;;;;;N;;;;; +168BA;BAMUM LETTER PHASE-C TEUTEUX;Lo;0;L;;;;;N;;;;; +168BB;BAMUM LETTER PHASE-C NGGUM;Lo;0;L;;;;;N;;;;; +168BC;BAMUM LETTER PHASE-C FUE;Lo;0;L;;;;;N;;;;; +168BD;BAMUM LETTER PHASE-C NDEUT;Lo;0;L;;;;;N;;;;; +168BE;BAMUM LETTER PHASE-C NSA;Lo;0;L;;;;;N;;;;; +168BF;BAMUM LETTER PHASE-C NSHAQ;Lo;0;L;;;;;N;;;;; +168C0;BAMUM LETTER PHASE-C BUNG;Lo;0;L;;;;;N;;;;; +168C1;BAMUM LETTER PHASE-C VEUAEPEN;Lo;0;L;;;;;N;;;;; +168C2;BAMUM LETTER PHASE-C MBERAE;Lo;0;L;;;;;N;;;;; +168C3;BAMUM LETTER PHASE-C RU;Lo;0;L;;;;;N;;;;; +168C4;BAMUM LETTER PHASE-C NJAEM;Lo;0;L;;;;;N;;;;; +168C5;BAMUM LETTER PHASE-C LAM;Lo;0;L;;;;;N;;;;; +168C6;BAMUM LETTER PHASE-C TITUAEP;Lo;0;L;;;;;N;;;;; +168C7;BAMUM LETTER PHASE-C NSUOT NGOM;Lo;0;L;;;;;N;;;;; +168C8;BAMUM LETTER PHASE-C NJEEEE;Lo;0;L;;;;;N;;;;; +168C9;BAMUM LETTER PHASE-C KET;Lo;0;L;;;;;N;;;;; +168CA;BAMUM LETTER PHASE-C NGGU;Lo;0;L;;;;;N;;;;; +168CB;BAMUM LETTER PHASE-C MAESI;Lo;0;L;;;;;N;;;;; +168CC;BAMUM LETTER PHASE-C MBUAEM;Lo;0;L;;;;;N;;;;; +168CD;BAMUM LETTER PHASE-C LU;Lo;0;L;;;;;N;;;;; +168CE;BAMUM LETTER PHASE-C KUT;Lo;0;L;;;;;N;;;;; +168CF;BAMUM LETTER PHASE-C NJAM;Lo;0;L;;;;;N;;;;; +168D0;BAMUM LETTER PHASE-C NGOM;Lo;0;L;;;;;N;;;;; +168D1;BAMUM LETTER PHASE-C WUP;Lo;0;L;;;;;N;;;;; +168D2;BAMUM LETTER PHASE-C NGGUEET;Lo;0;L;;;;;N;;;;; +168D3;BAMUM LETTER PHASE-C NSOM;Lo;0;L;;;;;N;;;;; +168D4;BAMUM LETTER PHASE-C NTEN;Lo;0;L;;;;;N;;;;; +168D5;BAMUM LETTER PHASE-C KUOP NKAARAE;Lo;0;L;;;;;N;;;;; +168D6;BAMUM LETTER PHASE-C NSUN;Lo;0;L;;;;;N;;;;; +168D7;BAMUM LETTER PHASE-C NDAM;Lo;0;L;;;;;N;;;;; +168D8;BAMUM LETTER PHASE-C MA NSIEE;Lo;0;L;;;;;N;;;;; +168D9;BAMUM LETTER PHASE-C YAA;Lo;0;L;;;;;N;;;;; +168DA;BAMUM LETTER PHASE-C NDAP;Lo;0;L;;;;;N;;;;; +168DB;BAMUM LETTER PHASE-C SHUEQ;Lo;0;L;;;;;N;;;;; +168DC;BAMUM LETTER PHASE-C SETFON;Lo;0;L;;;;;N;;;;; +168DD;BAMUM LETTER PHASE-C MBI;Lo;0;L;;;;;N;;;;; +168DE;BAMUM LETTER PHASE-C MAEMBA;Lo;0;L;;;;;N;;;;; +168DF;BAMUM LETTER PHASE-C MBANYI;Lo;0;L;;;;;N;;;;; +168E0;BAMUM LETTER PHASE-C KEUSEUX;Lo;0;L;;;;;N;;;;; +168E1;BAMUM LETTER PHASE-C MBEUX;Lo;0;L;;;;;N;;;;; +168E2;BAMUM LETTER PHASE-C KEUM;Lo;0;L;;;;;N;;;;; +168E3;BAMUM LETTER PHASE-C MBAA PICKET;Lo;0;L;;;;;N;;;;; +168E4;BAMUM LETTER PHASE-C YUWOQ;Lo;0;L;;;;;N;;;;; +168E5;BAMUM LETTER PHASE-C NJEUX;Lo;0;L;;;;;N;;;;; +168E6;BAMUM LETTER PHASE-C MIEE;Lo;0;L;;;;;N;;;;; +168E7;BAMUM LETTER PHASE-C MUAE;Lo;0;L;;;;;N;;;;; +168E8;BAMUM LETTER PHASE-C SHIQ;Lo;0;L;;;;;N;;;;; +168E9;BAMUM LETTER PHASE-C KEN LAW;Lo;0;L;;;;;N;;;;; +168EA;BAMUM LETTER PHASE-C KEN FATIGUE;Lo;0;L;;;;;N;;;;; +168EB;BAMUM LETTER PHASE-C NGAQ;Lo;0;L;;;;;N;;;;; +168EC;BAMUM LETTER PHASE-C NAQ;Lo;0;L;;;;;N;;;;; +168ED;BAMUM LETTER PHASE-C LIQ;Lo;0;L;;;;;N;;;;; +168EE;BAMUM LETTER PHASE-C PIN;Lo;0;L;;;;;N;;;;; +168EF;BAMUM LETTER PHASE-C PEN;Lo;0;L;;;;;N;;;;; +168F0;BAMUM LETTER PHASE-C TET;Lo;0;L;;;;;N;;;;; +168F1;BAMUM LETTER PHASE-D MBUO;Lo;0;L;;;;;N;;;;; +168F2;BAMUM LETTER PHASE-D WAP;Lo;0;L;;;;;N;;;;; +168F3;BAMUM LETTER PHASE-D NJI;Lo;0;L;;;;;N;;;;; +168F4;BAMUM LETTER PHASE-D MFON;Lo;0;L;;;;;N;;;;; +168F5;BAMUM LETTER PHASE-D NJIEE;Lo;0;L;;;;;N;;;;; +168F6;BAMUM LETTER PHASE-D LIEE;Lo;0;L;;;;;N;;;;; +168F7;BAMUM LETTER PHASE-D NJEUT;Lo;0;L;;;;;N;;;;; +168F8;BAMUM LETTER PHASE-D NSHEE;Lo;0;L;;;;;N;;;;; +168F9;BAMUM LETTER PHASE-D NGGAAMAE;Lo;0;L;;;;;N;;;;; +168FA;BAMUM LETTER PHASE-D NYAM;Lo;0;L;;;;;N;;;;; +168FB;BAMUM LETTER PHASE-D WUAEN;Lo;0;L;;;;;N;;;;; +168FC;BAMUM LETTER PHASE-D NGKUN;Lo;0;L;;;;;N;;;;; +168FD;BAMUM LETTER PHASE-D SHEE;Lo;0;L;;;;;N;;;;; +168FE;BAMUM LETTER PHASE-D NGKAP;Lo;0;L;;;;;N;;;;; +168FF;BAMUM LETTER PHASE-D KEUAETMEUN;Lo;0;L;;;;;N;;;;; +16900;BAMUM LETTER PHASE-D TEUT;Lo;0;L;;;;;N;;;;; +16901;BAMUM LETTER PHASE-D SHEUAE;Lo;0;L;;;;;N;;;;; +16902;BAMUM LETTER PHASE-D NJAP;Lo;0;L;;;;;N;;;;; +16903;BAMUM LETTER PHASE-D SUE;Lo;0;L;;;;;N;;;;; +16904;BAMUM LETTER PHASE-D KET;Lo;0;L;;;;;N;;;;; +16905;BAMUM LETTER PHASE-D YAEMMAE;Lo;0;L;;;;;N;;;;; +16906;BAMUM LETTER PHASE-D KUOM;Lo;0;L;;;;;N;;;;; +16907;BAMUM LETTER PHASE-D SAP;Lo;0;L;;;;;N;;;;; +16908;BAMUM LETTER PHASE-D MFEUT;Lo;0;L;;;;;N;;;;; +16909;BAMUM LETTER PHASE-D NDEUX;Lo;0;L;;;;;N;;;;; +1690A;BAMUM LETTER PHASE-D MALEERI;Lo;0;L;;;;;N;;;;; +1690B;BAMUM LETTER PHASE-D MEUT;Lo;0;L;;;;;N;;;;; +1690C;BAMUM LETTER PHASE-D SEUAEQ;Lo;0;L;;;;;N;;;;; +1690D;BAMUM LETTER PHASE-D YEN;Lo;0;L;;;;;N;;;;; +1690E;BAMUM LETTER PHASE-D NJEUAEM;Lo;0;L;;;;;N;;;;; +1690F;BAMUM LETTER PHASE-D KEUOT MBUAE;Lo;0;L;;;;;N;;;;; +16910;BAMUM LETTER PHASE-D NGKEURI;Lo;0;L;;;;;N;;;;; +16911;BAMUM LETTER PHASE-D TU;Lo;0;L;;;;;N;;;;; +16912;BAMUM LETTER PHASE-D GHAA;Lo;0;L;;;;;N;;;;; +16913;BAMUM LETTER PHASE-D NGKYEE;Lo;0;L;;;;;N;;;;; +16914;BAMUM LETTER PHASE-D FEUFEUAET;Lo;0;L;;;;;N;;;;; +16915;BAMUM LETTER PHASE-D NDEE;Lo;0;L;;;;;N;;;;; +16916;BAMUM LETTER PHASE-D MGBOFUM;Lo;0;L;;;;;N;;;;; +16917;BAMUM LETTER PHASE-D LEUAEP;Lo;0;L;;;;;N;;;;; +16918;BAMUM LETTER PHASE-D NDON;Lo;0;L;;;;;N;;;;; +16919;BAMUM LETTER PHASE-D MONI;Lo;0;L;;;;;N;;;;; +1691A;BAMUM LETTER PHASE-D MGBEUN;Lo;0;L;;;;;N;;;;; +1691B;BAMUM LETTER PHASE-D PUUT;Lo;0;L;;;;;N;;;;; +1691C;BAMUM LETTER PHASE-D MGBIEE;Lo;0;L;;;;;N;;;;; +1691D;BAMUM LETTER PHASE-D MFO;Lo;0;L;;;;;N;;;;; +1691E;BAMUM LETTER PHASE-D LUM;Lo;0;L;;;;;N;;;;; +1691F;BAMUM LETTER PHASE-D NSIEEP;Lo;0;L;;;;;N;;;;; +16920;BAMUM LETTER PHASE-D MBAA;Lo;0;L;;;;;N;;;;; +16921;BAMUM LETTER PHASE-D KWAET;Lo;0;L;;;;;N;;;;; +16922;BAMUM LETTER PHASE-D NYET;Lo;0;L;;;;;N;;;;; +16923;BAMUM LETTER PHASE-D TEUAEN;Lo;0;L;;;;;N;;;;; +16924;BAMUM LETTER PHASE-D SOT;Lo;0;L;;;;;N;;;;; +16925;BAMUM LETTER PHASE-D YUWOQ;Lo;0;L;;;;;N;;;;; +16926;BAMUM LETTER PHASE-D KEUM;Lo;0;L;;;;;N;;;;; +16927;BAMUM LETTER PHASE-D RAEM;Lo;0;L;;;;;N;;;;; +16928;BAMUM LETTER PHASE-D TEEEE;Lo;0;L;;;;;N;;;;; +16929;BAMUM LETTER PHASE-D NGKEUAEQ;Lo;0;L;;;;;N;;;;; +1692A;BAMUM LETTER PHASE-D MFEUAE;Lo;0;L;;;;;N;;;;; +1692B;BAMUM LETTER PHASE-D NSIEET;Lo;0;L;;;;;N;;;;; +1692C;BAMUM LETTER PHASE-D KEUP;Lo;0;L;;;;;N;;;;; +1692D;BAMUM LETTER PHASE-D PIP;Lo;0;L;;;;;N;;;;; +1692E;BAMUM LETTER PHASE-D PEUTAE;Lo;0;L;;;;;N;;;;; +1692F;BAMUM LETTER PHASE-D NYUE;Lo;0;L;;;;;N;;;;; +16930;BAMUM LETTER PHASE-D LET;Lo;0;L;;;;;N;;;;; +16931;BAMUM LETTER PHASE-D NGGAAM;Lo;0;L;;;;;N;;;;; +16932;BAMUM LETTER PHASE-D MFIEE;Lo;0;L;;;;;N;;;;; +16933;BAMUM LETTER PHASE-D NGGWAEN;Lo;0;L;;;;;N;;;;; +16934;BAMUM LETTER PHASE-D YUOM;Lo;0;L;;;;;N;;;;; +16935;BAMUM LETTER PHASE-D PAP;Lo;0;L;;;;;N;;;;; +16936;BAMUM LETTER PHASE-D YUOP;Lo;0;L;;;;;N;;;;; +16937;BAMUM LETTER PHASE-D NDAM;Lo;0;L;;;;;N;;;;; +16938;BAMUM LETTER PHASE-D NTEUM;Lo;0;L;;;;;N;;;;; +16939;BAMUM LETTER PHASE-D SUAE;Lo;0;L;;;;;N;;;;; +1693A;BAMUM LETTER PHASE-D KUN;Lo;0;L;;;;;N;;;;; +1693B;BAMUM LETTER PHASE-D NGGEUX;Lo;0;L;;;;;N;;;;; +1693C;BAMUM LETTER PHASE-D NGKIEE;Lo;0;L;;;;;N;;;;; +1693D;BAMUM LETTER PHASE-D TUOT;Lo;0;L;;;;;N;;;;; +1693E;BAMUM LETTER PHASE-D MEUN;Lo;0;L;;;;;N;;;;; +1693F;BAMUM LETTER PHASE-D KUQ;Lo;0;L;;;;;N;;;;; +16940;BAMUM LETTER PHASE-D NSUM;Lo;0;L;;;;;N;;;;; +16941;BAMUM LETTER PHASE-D TEUN;Lo;0;L;;;;;N;;;;; +16942;BAMUM LETTER PHASE-D MAENJET;Lo;0;L;;;;;N;;;;; +16943;BAMUM LETTER PHASE-D NGGAP;Lo;0;L;;;;;N;;;;; +16944;BAMUM LETTER PHASE-D LEUM;Lo;0;L;;;;;N;;;;; +16945;BAMUM LETTER PHASE-D NGGUOM;Lo;0;L;;;;;N;;;;; +16946;BAMUM LETTER PHASE-D NSHUT;Lo;0;L;;;;;N;;;;; +16947;BAMUM LETTER PHASE-D NJUEQ;Lo;0;L;;;;;N;;;;; +16948;BAMUM LETTER PHASE-D GHEUAE;Lo;0;L;;;;;N;;;;; +16949;BAMUM LETTER PHASE-D KU;Lo;0;L;;;;;N;;;;; +1694A;BAMUM LETTER PHASE-D REN OLD;Lo;0;L;;;;;N;;;;; +1694B;BAMUM LETTER PHASE-D TAE;Lo;0;L;;;;;N;;;;; +1694C;BAMUM LETTER PHASE-D TOQ;Lo;0;L;;;;;N;;;;; +1694D;BAMUM LETTER PHASE-D NYI;Lo;0;L;;;;;N;;;;; +1694E;BAMUM LETTER PHASE-D RII;Lo;0;L;;;;;N;;;;; +1694F;BAMUM LETTER PHASE-D LEEEE;Lo;0;L;;;;;N;;;;; +16950;BAMUM LETTER PHASE-D MEEEE;Lo;0;L;;;;;N;;;;; +16951;BAMUM LETTER PHASE-D M;Lo;0;L;;;;;N;;;;; +16952;BAMUM LETTER PHASE-D SUU;Lo;0;L;;;;;N;;;;; +16953;BAMUM LETTER PHASE-D MU;Lo;0;L;;;;;N;;;;; +16954;BAMUM LETTER PHASE-D SHII;Lo;0;L;;;;;N;;;;; +16955;BAMUM LETTER PHASE-D SHEUX;Lo;0;L;;;;;N;;;;; +16956;BAMUM LETTER PHASE-D KYEE;Lo;0;L;;;;;N;;;;; +16957;BAMUM LETTER PHASE-D NU;Lo;0;L;;;;;N;;;;; +16958;BAMUM LETTER PHASE-D SHU;Lo;0;L;;;;;N;;;;; +16959;BAMUM LETTER PHASE-D NTEE;Lo;0;L;;;;;N;;;;; +1695A;BAMUM LETTER PHASE-D PEE;Lo;0;L;;;;;N;;;;; +1695B;BAMUM LETTER PHASE-D NI;Lo;0;L;;;;;N;;;;; +1695C;BAMUM LETTER PHASE-D SHOQ;Lo;0;L;;;;;N;;;;; +1695D;BAMUM LETTER PHASE-D PUQ;Lo;0;L;;;;;N;;;;; +1695E;BAMUM LETTER PHASE-D MVOP;Lo;0;L;;;;;N;;;;; +1695F;BAMUM LETTER PHASE-D LOQ;Lo;0;L;;;;;N;;;;; +16960;BAMUM LETTER PHASE-D REN MUCH;Lo;0;L;;;;;N;;;;; +16961;BAMUM LETTER PHASE-D TI;Lo;0;L;;;;;N;;;;; +16962;BAMUM LETTER PHASE-D NTUU;Lo;0;L;;;;;N;;;;; +16963;BAMUM LETTER PHASE-D MBAA SEVEN;Lo;0;L;;;;;N;;;;; +16964;BAMUM LETTER PHASE-D SAQ;Lo;0;L;;;;;N;;;;; +16965;BAMUM LETTER PHASE-D FAA;Lo;0;L;;;;;N;;;;; +16966;BAMUM LETTER PHASE-E NDAP;Lo;0;L;;;;;N;;;;; +16967;BAMUM LETTER PHASE-E TOON;Lo;0;L;;;;;N;;;;; +16968;BAMUM LETTER PHASE-E MBEUM;Lo;0;L;;;;;N;;;;; +16969;BAMUM LETTER PHASE-E LAP;Lo;0;L;;;;;N;;;;; +1696A;BAMUM LETTER PHASE-E VOM;Lo;0;L;;;;;N;;;;; +1696B;BAMUM LETTER PHASE-E LOON;Lo;0;L;;;;;N;;;;; +1696C;BAMUM LETTER PHASE-E PAA;Lo;0;L;;;;;N;;;;; +1696D;BAMUM LETTER PHASE-E SOM;Lo;0;L;;;;;N;;;;; +1696E;BAMUM LETTER PHASE-E RAQ;Lo;0;L;;;;;N;;;;; +1696F;BAMUM LETTER PHASE-E NSHUOP;Lo;0;L;;;;;N;;;;; +16970;BAMUM LETTER PHASE-E NDUN;Lo;0;L;;;;;N;;;;; +16971;BAMUM LETTER PHASE-E PUAE;Lo;0;L;;;;;N;;;;; +16972;BAMUM LETTER PHASE-E TAM;Lo;0;L;;;;;N;;;;; +16973;BAMUM LETTER PHASE-E NGKA;Lo;0;L;;;;;N;;;;; +16974;BAMUM LETTER PHASE-E KPEUX;Lo;0;L;;;;;N;;;;; +16975;BAMUM LETTER PHASE-E WUO;Lo;0;L;;;;;N;;;;; +16976;BAMUM LETTER PHASE-E SEE;Lo;0;L;;;;;N;;;;; +16977;BAMUM LETTER PHASE-E NGGEUAET;Lo;0;L;;;;;N;;;;; +16978;BAMUM LETTER PHASE-E PAAM;Lo;0;L;;;;;N;;;;; +16979;BAMUM LETTER PHASE-E TOO;Lo;0;L;;;;;N;;;;; +1697A;BAMUM LETTER PHASE-E KUOP;Lo;0;L;;;;;N;;;;; +1697B;BAMUM LETTER PHASE-E LOM;Lo;0;L;;;;;N;;;;; +1697C;BAMUM LETTER PHASE-E NSHIEE;Lo;0;L;;;;;N;;;;; +1697D;BAMUM LETTER PHASE-E NGOP;Lo;0;L;;;;;N;;;;; +1697E;BAMUM LETTER PHASE-E MAEM;Lo;0;L;;;;;N;;;;; +1697F;BAMUM LETTER PHASE-E NGKEUX;Lo;0;L;;;;;N;;;;; +16980;BAMUM LETTER PHASE-E NGOQ;Lo;0;L;;;;;N;;;;; +16981;BAMUM LETTER PHASE-E NSHUE;Lo;0;L;;;;;N;;;;; +16982;BAMUM LETTER PHASE-E RIMGBA;Lo;0;L;;;;;N;;;;; +16983;BAMUM LETTER PHASE-E NJEUX;Lo;0;L;;;;;N;;;;; +16984;BAMUM LETTER PHASE-E PEEM;Lo;0;L;;;;;N;;;;; +16985;BAMUM LETTER PHASE-E SAA;Lo;0;L;;;;;N;;;;; +16986;BAMUM LETTER PHASE-E NGGURAE;Lo;0;L;;;;;N;;;;; +16987;BAMUM LETTER PHASE-E MGBA;Lo;0;L;;;;;N;;;;; +16988;BAMUM LETTER PHASE-E GHEUX;Lo;0;L;;;;;N;;;;; +16989;BAMUM LETTER PHASE-E NGKEUAEM;Lo;0;L;;;;;N;;;;; +1698A;BAMUM LETTER PHASE-E NJAEMLI;Lo;0;L;;;;;N;;;;; +1698B;BAMUM LETTER PHASE-E MAP;Lo;0;L;;;;;N;;;;; +1698C;BAMUM LETTER PHASE-E LOOT;Lo;0;L;;;;;N;;;;; +1698D;BAMUM LETTER PHASE-E NGGEEEE;Lo;0;L;;;;;N;;;;; +1698E;BAMUM LETTER PHASE-E NDIQ;Lo;0;L;;;;;N;;;;; +1698F;BAMUM LETTER PHASE-E TAEN NTEUM;Lo;0;L;;;;;N;;;;; +16990;BAMUM LETTER PHASE-E SET;Lo;0;L;;;;;N;;;;; +16991;BAMUM LETTER PHASE-E PUM;Lo;0;L;;;;;N;;;;; +16992;BAMUM LETTER PHASE-E NDAA SOFTNESS;Lo;0;L;;;;;N;;;;; +16993;BAMUM LETTER PHASE-E NGGUAESHAE NYAM;Lo;0;L;;;;;N;;;;; +16994;BAMUM LETTER PHASE-E YIEE;Lo;0;L;;;;;N;;;;; +16995;BAMUM LETTER PHASE-E GHEUN;Lo;0;L;;;;;N;;;;; +16996;BAMUM LETTER PHASE-E TUAE;Lo;0;L;;;;;N;;;;; +16997;BAMUM LETTER PHASE-E YEUAE;Lo;0;L;;;;;N;;;;; +16998;BAMUM LETTER PHASE-E PO;Lo;0;L;;;;;N;;;;; +16999;BAMUM LETTER PHASE-E TUMAE;Lo;0;L;;;;;N;;;;; +1699A;BAMUM LETTER PHASE-E KEUAE;Lo;0;L;;;;;N;;;;; +1699B;BAMUM LETTER PHASE-E SUAEN;Lo;0;L;;;;;N;;;;; +1699C;BAMUM LETTER PHASE-E TEUAEQ;Lo;0;L;;;;;N;;;;; +1699D;BAMUM LETTER PHASE-E VEUAE;Lo;0;L;;;;;N;;;;; +1699E;BAMUM LETTER PHASE-E WEUX;Lo;0;L;;;;;N;;;;; +1699F;BAMUM LETTER PHASE-E LAAM;Lo;0;L;;;;;N;;;;; +169A0;BAMUM LETTER PHASE-E PU;Lo;0;L;;;;;N;;;;; +169A1;BAMUM LETTER PHASE-E TAAQ;Lo;0;L;;;;;N;;;;; +169A2;BAMUM LETTER PHASE-E GHAAMAE;Lo;0;L;;;;;N;;;;; +169A3;BAMUM LETTER PHASE-E NGEUREUT;Lo;0;L;;;;;N;;;;; +169A4;BAMUM LETTER PHASE-E SHEUAEQ;Lo;0;L;;;;;N;;;;; +169A5;BAMUM LETTER PHASE-E MGBEN;Lo;0;L;;;;;N;;;;; +169A6;BAMUM LETTER PHASE-E MBEE;Lo;0;L;;;;;N;;;;; +169A7;BAMUM LETTER PHASE-E NZAQ;Lo;0;L;;;;;N;;;;; +169A8;BAMUM LETTER PHASE-E NKOM;Lo;0;L;;;;;N;;;;; +169A9;BAMUM LETTER PHASE-E GBET;Lo;0;L;;;;;N;;;;; +169AA;BAMUM LETTER PHASE-E TUM;Lo;0;L;;;;;N;;;;; +169AB;BAMUM LETTER PHASE-E KUET;Lo;0;L;;;;;N;;;;; +169AC;BAMUM LETTER PHASE-E YAP;Lo;0;L;;;;;N;;;;; +169AD;BAMUM LETTER PHASE-E NYI CLEAVER;Lo;0;L;;;;;N;;;;; +169AE;BAMUM LETTER PHASE-E YIT;Lo;0;L;;;;;N;;;;; +169AF;BAMUM LETTER PHASE-E MFEUQ;Lo;0;L;;;;;N;;;;; +169B0;BAMUM LETTER PHASE-E NDIAQ;Lo;0;L;;;;;N;;;;; +169B1;BAMUM LETTER PHASE-E PIEEQ;Lo;0;L;;;;;N;;;;; +169B2;BAMUM LETTER PHASE-E YUEQ;Lo;0;L;;;;;N;;;;; +169B3;BAMUM LETTER PHASE-E LEUAEM;Lo;0;L;;;;;N;;;;; +169B4;BAMUM LETTER PHASE-E FUE;Lo;0;L;;;;;N;;;;; +169B5;BAMUM LETTER PHASE-E GBEUX;Lo;0;L;;;;;N;;;;; +169B6;BAMUM LETTER PHASE-E NGKUP;Lo;0;L;;;;;N;;;;; +169B7;BAMUM LETTER PHASE-E KET;Lo;0;L;;;;;N;;;;; +169B8;BAMUM LETTER PHASE-E MAE;Lo;0;L;;;;;N;;;;; +169B9;BAMUM LETTER PHASE-E NGKAAMI;Lo;0;L;;;;;N;;;;; +169BA;BAMUM LETTER PHASE-E GHET;Lo;0;L;;;;;N;;;;; +169BB;BAMUM LETTER PHASE-E FA;Lo;0;L;;;;;N;;;;; +169BC;BAMUM LETTER PHASE-E NTUM;Lo;0;L;;;;;N;;;;; +169BD;BAMUM LETTER PHASE-E PEUT;Lo;0;L;;;;;N;;;;; +169BE;BAMUM LETTER PHASE-E YEUM;Lo;0;L;;;;;N;;;;; +169BF;BAMUM LETTER PHASE-E NGGEUAE;Lo;0;L;;;;;N;;;;; +169C0;BAMUM LETTER PHASE-E NYI BETWEEN;Lo;0;L;;;;;N;;;;; +169C1;BAMUM LETTER PHASE-E NZUQ;Lo;0;L;;;;;N;;;;; +169C2;BAMUM LETTER PHASE-E POON;Lo;0;L;;;;;N;;;;; +169C3;BAMUM LETTER PHASE-E MIEE;Lo;0;L;;;;;N;;;;; +169C4;BAMUM LETTER PHASE-E FUET;Lo;0;L;;;;;N;;;;; +169C5;BAMUM LETTER PHASE-E NAE;Lo;0;L;;;;;N;;;;; +169C6;BAMUM LETTER PHASE-E MUAE;Lo;0;L;;;;;N;;;;; +169C7;BAMUM LETTER PHASE-E GHEUAE;Lo;0;L;;;;;N;;;;; +169C8;BAMUM LETTER PHASE-E FU I;Lo;0;L;;;;;N;;;;; +169C9;BAMUM LETTER PHASE-E MVI;Lo;0;L;;;;;N;;;;; +169CA;BAMUM LETTER PHASE-E PUAQ;Lo;0;L;;;;;N;;;;; +169CB;BAMUM LETTER PHASE-E NGKUM;Lo;0;L;;;;;N;;;;; +169CC;BAMUM LETTER PHASE-E KUT;Lo;0;L;;;;;N;;;;; +169CD;BAMUM LETTER PHASE-E PIET;Lo;0;L;;;;;N;;;;; +169CE;BAMUM LETTER PHASE-E NTAP;Lo;0;L;;;;;N;;;;; +169CF;BAMUM LETTER PHASE-E YEUAET;Lo;0;L;;;;;N;;;;; +169D0;BAMUM LETTER PHASE-E NGGUP;Lo;0;L;;;;;N;;;;; +169D1;BAMUM LETTER PHASE-E PA PEOPLE;Lo;0;L;;;;;N;;;;; +169D2;BAMUM LETTER PHASE-E FU CALL;Lo;0;L;;;;;N;;;;; +169D3;BAMUM LETTER PHASE-E FOM;Lo;0;L;;;;;N;;;;; +169D4;BAMUM LETTER PHASE-E NJEE;Lo;0;L;;;;;N;;;;; +169D5;BAMUM LETTER PHASE-E A;Lo;0;L;;;;;N;;;;; +169D6;BAMUM LETTER PHASE-E TOQ;Lo;0;L;;;;;N;;;;; +169D7;BAMUM LETTER PHASE-E O;Lo;0;L;;;;;N;;;;; +169D8;BAMUM LETTER PHASE-E I;Lo;0;L;;;;;N;;;;; +169D9;BAMUM LETTER PHASE-E LAQ;Lo;0;L;;;;;N;;;;; +169DA;BAMUM LETTER PHASE-E PA PLURAL;Lo;0;L;;;;;N;;;;; +169DB;BAMUM LETTER PHASE-E TAA;Lo;0;L;;;;;N;;;;; +169DC;BAMUM LETTER PHASE-E TAQ;Lo;0;L;;;;;N;;;;; +169DD;BAMUM LETTER PHASE-E NDAA MY HOUSE;Lo;0;L;;;;;N;;;;; +169DE;BAMUM LETTER PHASE-E SHIQ;Lo;0;L;;;;;N;;;;; +169DF;BAMUM LETTER PHASE-E YEUX;Lo;0;L;;;;;N;;;;; +169E0;BAMUM LETTER PHASE-E NGUAE;Lo;0;L;;;;;N;;;;; +169E1;BAMUM LETTER PHASE-E YUAEN;Lo;0;L;;;;;N;;;;; +169E2;BAMUM LETTER PHASE-E YOQ SWIMMING;Lo;0;L;;;;;N;;;;; +169E3;BAMUM LETTER PHASE-E YOQ COVER;Lo;0;L;;;;;N;;;;; +169E4;BAMUM LETTER PHASE-E YUQ;Lo;0;L;;;;;N;;;;; +169E5;BAMUM LETTER PHASE-E YUN;Lo;0;L;;;;;N;;;;; +169E6;BAMUM LETTER PHASE-E KEUX;Lo;0;L;;;;;N;;;;; +169E7;BAMUM LETTER PHASE-E PEUX;Lo;0;L;;;;;N;;;;; +169E8;BAMUM LETTER PHASE-E NJEE EPOCH;Lo;0;L;;;;;N;;;;; +169E9;BAMUM LETTER PHASE-E PUE;Lo;0;L;;;;;N;;;;; +169EA;BAMUM LETTER PHASE-E WUE;Lo;0;L;;;;;N;;;;; +169EB;BAMUM LETTER PHASE-E FEE;Lo;0;L;;;;;N;;;;; +169EC;BAMUM LETTER PHASE-E VEE;Lo;0;L;;;;;N;;;;; +169ED;BAMUM LETTER PHASE-E LU;Lo;0;L;;;;;N;;;;; +169EE;BAMUM LETTER PHASE-E MI;Lo;0;L;;;;;N;;;;; +169EF;BAMUM LETTER PHASE-E REUX;Lo;0;L;;;;;N;;;;; +169F0;BAMUM LETTER PHASE-E RAE;Lo;0;L;;;;;N;;;;; +169F1;BAMUM LETTER PHASE-E NGUAET;Lo;0;L;;;;;N;;;;; +169F2;BAMUM LETTER PHASE-E NGA;Lo;0;L;;;;;N;;;;; +169F3;BAMUM LETTER PHASE-E SHO;Lo;0;L;;;;;N;;;;; +169F4;BAMUM LETTER PHASE-E SHOQ;Lo;0;L;;;;;N;;;;; +169F5;BAMUM LETTER PHASE-E FU REMEDY;Lo;0;L;;;;;N;;;;; +169F6;BAMUM LETTER PHASE-E NA;Lo;0;L;;;;;N;;;;; +169F7;BAMUM LETTER PHASE-E PI;Lo;0;L;;;;;N;;;;; +169F8;BAMUM LETTER PHASE-E LOQ;Lo;0;L;;;;;N;;;;; +169F9;BAMUM LETTER PHASE-E KO;Lo;0;L;;;;;N;;;;; +169FA;BAMUM LETTER PHASE-E MEN;Lo;0;L;;;;;N;;;;; +169FB;BAMUM LETTER PHASE-E MA;Lo;0;L;;;;;N;;;;; +169FC;BAMUM LETTER PHASE-E MAQ;Lo;0;L;;;;;N;;;;; +169FD;BAMUM LETTER PHASE-E TEU;Lo;0;L;;;;;N;;;;; +169FE;BAMUM LETTER PHASE-E KI;Lo;0;L;;;;;N;;;;; +169FF;BAMUM LETTER PHASE-E MON;Lo;0;L;;;;;N;;;;; +16A00;BAMUM LETTER PHASE-E TEN;Lo;0;L;;;;;N;;;;; +16A01;BAMUM LETTER PHASE-E FAQ;Lo;0;L;;;;;N;;;;; +16A02;BAMUM LETTER PHASE-E GHOM;Lo;0;L;;;;;N;;;;; +16A03;BAMUM LETTER PHASE-F KA;Lo;0;L;;;;;N;;;;; +16A04;BAMUM LETTER PHASE-F U;Lo;0;L;;;;;N;;;;; +16A05;BAMUM LETTER PHASE-F KU;Lo;0;L;;;;;N;;;;; +16A06;BAMUM LETTER PHASE-F EE;Lo;0;L;;;;;N;;;;; +16A07;BAMUM LETTER PHASE-F REE;Lo;0;L;;;;;N;;;;; +16A08;BAMUM LETTER PHASE-F TAE;Lo;0;L;;;;;N;;;;; +16A09;BAMUM LETTER PHASE-F NYI;Lo;0;L;;;;;N;;;;; +16A0A;BAMUM LETTER PHASE-F LA;Lo;0;L;;;;;N;;;;; +16A0B;BAMUM LETTER PHASE-F RII;Lo;0;L;;;;;N;;;;; +16A0C;BAMUM LETTER PHASE-F RIEE;Lo;0;L;;;;;N;;;;; +16A0D;BAMUM LETTER PHASE-F MEEEE;Lo;0;L;;;;;N;;;;; +16A0E;BAMUM LETTER PHASE-F TAA;Lo;0;L;;;;;N;;;;; +16A0F;BAMUM LETTER PHASE-F NDAA;Lo;0;L;;;;;N;;;;; +16A10;BAMUM LETTER PHASE-F NJAEM;Lo;0;L;;;;;N;;;;; +16A11;BAMUM LETTER PHASE-F M;Lo;0;L;;;;;N;;;;; +16A12;BAMUM LETTER PHASE-F SUU;Lo;0;L;;;;;N;;;;; +16A13;BAMUM LETTER PHASE-F SHII;Lo;0;L;;;;;N;;;;; +16A14;BAMUM LETTER PHASE-F SI;Lo;0;L;;;;;N;;;;; +16A15;BAMUM LETTER PHASE-F SEUX;Lo;0;L;;;;;N;;;;; +16A16;BAMUM LETTER PHASE-F KYEE;Lo;0;L;;;;;N;;;;; +16A17;BAMUM LETTER PHASE-F KET;Lo;0;L;;;;;N;;;;; +16A18;BAMUM LETTER PHASE-F NUAE;Lo;0;L;;;;;N;;;;; +16A19;BAMUM LETTER PHASE-F NU;Lo;0;L;;;;;N;;;;; +16A1A;BAMUM LETTER PHASE-F NJUAE;Lo;0;L;;;;;N;;;;; +16A1B;BAMUM LETTER PHASE-F YOQ;Lo;0;L;;;;;N;;;;; +16A1C;BAMUM LETTER PHASE-F SHU;Lo;0;L;;;;;N;;;;; +16A1D;BAMUM LETTER PHASE-F YA;Lo;0;L;;;;;N;;;;; +16A1E;BAMUM LETTER PHASE-F NSHA;Lo;0;L;;;;;N;;;;; +16A1F;BAMUM LETTER PHASE-F PEUX;Lo;0;L;;;;;N;;;;; +16A20;BAMUM LETTER PHASE-F NTEE;Lo;0;L;;;;;N;;;;; +16A21;BAMUM LETTER PHASE-F WUE;Lo;0;L;;;;;N;;;;; +16A22;BAMUM LETTER PHASE-F PEE;Lo;0;L;;;;;N;;;;; +16A23;BAMUM LETTER PHASE-F RU;Lo;0;L;;;;;N;;;;; +16A24;BAMUM LETTER PHASE-F NI;Lo;0;L;;;;;N;;;;; +16A25;BAMUM LETTER PHASE-F REUX;Lo;0;L;;;;;N;;;;; +16A26;BAMUM LETTER PHASE-F KEN;Lo;0;L;;;;;N;;;;; +16A27;BAMUM LETTER PHASE-F NGKWAEN;Lo;0;L;;;;;N;;;;; +16A28;BAMUM LETTER PHASE-F NGGA;Lo;0;L;;;;;N;;;;; +16A29;BAMUM LETTER PHASE-F SHO;Lo;0;L;;;;;N;;;;; +16A2A;BAMUM LETTER PHASE-F PUAE;Lo;0;L;;;;;N;;;;; +16A2B;BAMUM LETTER PHASE-F FOM;Lo;0;L;;;;;N;;;;; +16A2C;BAMUM LETTER PHASE-F WA;Lo;0;L;;;;;N;;;;; +16A2D;BAMUM LETTER PHASE-F LI;Lo;0;L;;;;;N;;;;; +16A2E;BAMUM LETTER PHASE-F LOQ;Lo;0;L;;;;;N;;;;; +16A2F;BAMUM LETTER PHASE-F KO;Lo;0;L;;;;;N;;;;; +16A30;BAMUM LETTER PHASE-F MBEN;Lo;0;L;;;;;N;;;;; +16A31;BAMUM LETTER PHASE-F REN;Lo;0;L;;;;;N;;;;; +16A32;BAMUM LETTER PHASE-F MA;Lo;0;L;;;;;N;;;;; +16A33;BAMUM LETTER PHASE-F MO;Lo;0;L;;;;;N;;;;; +16A34;BAMUM LETTER PHASE-F MBAA;Lo;0;L;;;;;N;;;;; +16A35;BAMUM LETTER PHASE-F TET;Lo;0;L;;;;;N;;;;; +16A36;BAMUM LETTER PHASE-F KPA;Lo;0;L;;;;;N;;;;; +16A37;BAMUM LETTER PHASE-F SAMBA;Lo;0;L;;;;;N;;;;; +16A38;BAMUM LETTER PHASE-F VUEQ;Lo;0;L;;;;;N;;;;; +16F00;MIAO LETTER PA;Lo;0;L;;;;;N;;;;; +16F01;MIAO LETTER BA;Lo;0;L;;;;;N;;;;; +16F02;MIAO LETTER YI PA;Lo;0;L;;;;;N;;;;; +16F03;MIAO LETTER PLA;Lo;0;L;;;;;N;;;;; +16F04;MIAO LETTER MA;Lo;0;L;;;;;N;;;;; +16F05;MIAO LETTER MHA;Lo;0;L;;;;;N;;;;; +16F06;MIAO LETTER ARCHAIC MA;Lo;0;L;;;;;N;;;;; +16F07;MIAO LETTER FA;Lo;0;L;;;;;N;;;;; +16F08;MIAO LETTER VA;Lo;0;L;;;;;N;;;;; +16F09;MIAO LETTER VFA;Lo;0;L;;;;;N;;;;; +16F0A;MIAO LETTER TA;Lo;0;L;;;;;N;;;;; +16F0B;MIAO LETTER DA;Lo;0;L;;;;;N;;;;; +16F0C;MIAO LETTER YI TTA;Lo;0;L;;;;;N;;;;; +16F0D;MIAO LETTER YI TA;Lo;0;L;;;;;N;;;;; +16F0E;MIAO LETTER TTA;Lo;0;L;;;;;N;;;;; +16F0F;MIAO LETTER DDA;Lo;0;L;;;;;N;;;;; +16F10;MIAO LETTER NA;Lo;0;L;;;;;N;;;;; +16F11;MIAO LETTER NHA;Lo;0;L;;;;;N;;;;; +16F12;MIAO LETTER YI NNA;Lo;0;L;;;;;N;;;;; +16F13;MIAO LETTER ARCHAIC NA;Lo;0;L;;;;;N;;;;; +16F14;MIAO LETTER NNA;Lo;0;L;;;;;N;;;;; +16F15;MIAO LETTER NNHA;Lo;0;L;;;;;N;;;;; +16F16;MIAO LETTER LA;Lo;0;L;;;;;N;;;;; +16F17;MIAO LETTER LYA;Lo;0;L;;;;;N;;;;; +16F18;MIAO LETTER LHA;Lo;0;L;;;;;N;;;;; +16F19;MIAO LETTER LHYA;Lo;0;L;;;;;N;;;;; +16F1A;MIAO LETTER TLHA;Lo;0;L;;;;;N;;;;; +16F1B;MIAO LETTER DLHA;Lo;0;L;;;;;N;;;;; +16F1C;MIAO LETTER TLHYA;Lo;0;L;;;;;N;;;;; +16F1D;MIAO LETTER DLHYA;Lo;0;L;;;;;N;;;;; +16F1E;MIAO LETTER KA;Lo;0;L;;;;;N;;;;; +16F1F;MIAO LETTER GA;Lo;0;L;;;;;N;;;;; +16F20;MIAO LETTER YI KA;Lo;0;L;;;;;N;;;;; +16F21;MIAO LETTER QA;Lo;0;L;;;;;N;;;;; +16F22;MIAO LETTER QGA;Lo;0;L;;;;;N;;;;; +16F23;MIAO LETTER NGA;Lo;0;L;;;;;N;;;;; +16F24;MIAO LETTER NGHA;Lo;0;L;;;;;N;;;;; +16F25;MIAO LETTER ARCHAIC NGA;Lo;0;L;;;;;N;;;;; +16F26;MIAO LETTER HA;Lo;0;L;;;;;N;;;;; +16F27;MIAO LETTER XA;Lo;0;L;;;;;N;;;;; +16F28;MIAO LETTER GHA;Lo;0;L;;;;;N;;;;; +16F29;MIAO LETTER GHHA;Lo;0;L;;;;;N;;;;; +16F2A;MIAO LETTER TSSA;Lo;0;L;;;;;N;;;;; +16F2B;MIAO LETTER DZZA;Lo;0;L;;;;;N;;;;; +16F2C;MIAO LETTER NYA;Lo;0;L;;;;;N;;;;; +16F2D;MIAO LETTER NYHA;Lo;0;L;;;;;N;;;;; +16F2E;MIAO LETTER TSHA;Lo;0;L;;;;;N;;;;; +16F2F;MIAO LETTER DZHA;Lo;0;L;;;;;N;;;;; +16F30;MIAO LETTER YI TSHA;Lo;0;L;;;;;N;;;;; +16F31;MIAO LETTER YI DZHA;Lo;0;L;;;;;N;;;;; +16F32;MIAO LETTER REFORMED TSHA;Lo;0;L;;;;;N;;;;; +16F33;MIAO LETTER SHA;Lo;0;L;;;;;N;;;;; +16F34;MIAO LETTER SSA;Lo;0;L;;;;;N;;;;; +16F35;MIAO LETTER ZHA;Lo;0;L;;;;;N;;;;; +16F36;MIAO LETTER ZSHA;Lo;0;L;;;;;N;;;;; +16F37;MIAO LETTER TSA;Lo;0;L;;;;;N;;;;; +16F38;MIAO LETTER DZA;Lo;0;L;;;;;N;;;;; +16F39;MIAO LETTER YI TSA;Lo;0;L;;;;;N;;;;; +16F3A;MIAO LETTER SA;Lo;0;L;;;;;N;;;;; +16F3B;MIAO LETTER ZA;Lo;0;L;;;;;N;;;;; +16F3C;MIAO LETTER ZSA;Lo;0;L;;;;;N;;;;; +16F3D;MIAO LETTER ZZA;Lo;0;L;;;;;N;;;;; +16F3E;MIAO LETTER ZZSA;Lo;0;L;;;;;N;;;;; +16F3F;MIAO LETTER ARCHAIC ZZA;Lo;0;L;;;;;N;;;;; +16F40;MIAO LETTER ZZYA;Lo;0;L;;;;;N;;;;; +16F41;MIAO LETTER ZZSYA;Lo;0;L;;;;;N;;;;; +16F42;MIAO LETTER WA;Lo;0;L;;;;;N;;;;; +16F43;MIAO LETTER AH;Lo;0;L;;;;;N;;;;; +16F44;MIAO LETTER HHA;Lo;0;L;;;;;N;;;;; +16F50;MIAO LETTER NASALIZATION;Lo;0;L;;;;;N;;;;; +16F51;MIAO SIGN ASPIRATION;Mc;0;L;;;;;N;;;;; +16F52;MIAO SIGN REFORMED VOICING;Mc;0;L;;;;;N;;;;; +16F53;MIAO SIGN REFORMED ASPIRATION;Mc;0;L;;;;;N;;;;; +16F54;MIAO VOWEL SIGN A;Mc;0;L;;;;;N;;;;; +16F55;MIAO VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; +16F56;MIAO VOWEL SIGN AHH;Mc;0;L;;;;;N;;;;; +16F57;MIAO VOWEL SIGN AN;Mc;0;L;;;;;N;;;;; +16F58;MIAO VOWEL SIGN ANG;Mc;0;L;;;;;N;;;;; +16F59;MIAO VOWEL SIGN O;Mc;0;L;;;;;N;;;;; +16F5A;MIAO VOWEL SIGN OO;Mc;0;L;;;;;N;;;;; +16F5B;MIAO VOWEL SIGN WO;Mc;0;L;;;;;N;;;;; +16F5C;MIAO VOWEL SIGN W;Mc;0;L;;;;;N;;;;; +16F5D;MIAO VOWEL SIGN E;Mc;0;L;;;;;N;;;;; +16F5E;MIAO VOWEL SIGN EN;Mc;0;L;;;;;N;;;;; +16F5F;MIAO VOWEL SIGN ENG;Mc;0;L;;;;;N;;;;; +16F60;MIAO VOWEL SIGN OEY;Mc;0;L;;;;;N;;;;; +16F61;MIAO VOWEL SIGN I;Mc;0;L;;;;;N;;;;; +16F62;MIAO VOWEL SIGN IA;Mc;0;L;;;;;N;;;;; +16F63;MIAO VOWEL SIGN IAN;Mc;0;L;;;;;N;;;;; +16F64;MIAO VOWEL SIGN IANG;Mc;0;L;;;;;N;;;;; +16F65;MIAO VOWEL SIGN IO;Mc;0;L;;;;;N;;;;; +16F66;MIAO VOWEL SIGN IE;Mc;0;L;;;;;N;;;;; +16F67;MIAO VOWEL SIGN II;Mc;0;L;;;;;N;;;;; +16F68;MIAO VOWEL SIGN IU;Mc;0;L;;;;;N;;;;; +16F69;MIAO VOWEL SIGN ING;Mc;0;L;;;;;N;;;;; +16F6A;MIAO VOWEL SIGN U;Mc;0;L;;;;;N;;;;; +16F6B;MIAO VOWEL SIGN UA;Mc;0;L;;;;;N;;;;; +16F6C;MIAO VOWEL SIGN UAN;Mc;0;L;;;;;N;;;;; +16F6D;MIAO VOWEL SIGN UANG;Mc;0;L;;;;;N;;;;; +16F6E;MIAO VOWEL SIGN UU;Mc;0;L;;;;;N;;;;; +16F6F;MIAO VOWEL SIGN UEI;Mc;0;L;;;;;N;;;;; +16F70;MIAO VOWEL SIGN UNG;Mc;0;L;;;;;N;;;;; +16F71;MIAO VOWEL SIGN Y;Mc;0;L;;;;;N;;;;; +16F72;MIAO VOWEL SIGN YI;Mc;0;L;;;;;N;;;;; +16F73;MIAO VOWEL SIGN AE;Mc;0;L;;;;;N;;;;; +16F74;MIAO VOWEL SIGN AEE;Mc;0;L;;;;;N;;;;; +16F75;MIAO VOWEL SIGN ERR;Mc;0;L;;;;;N;;;;; +16F76;MIAO VOWEL SIGN ROUNDED ERR;Mc;0;L;;;;;N;;;;; +16F77;MIAO VOWEL SIGN ER;Mc;0;L;;;;;N;;;;; +16F78;MIAO VOWEL SIGN ROUNDED ER;Mc;0;L;;;;;N;;;;; +16F79;MIAO VOWEL SIGN AI;Mc;0;L;;;;;N;;;;; +16F7A;MIAO VOWEL SIGN EI;Mc;0;L;;;;;N;;;;; +16F7B;MIAO VOWEL SIGN AU;Mc;0;L;;;;;N;;;;; +16F7C;MIAO VOWEL SIGN OU;Mc;0;L;;;;;N;;;;; +16F7D;MIAO VOWEL SIGN N;Mc;0;L;;;;;N;;;;; +16F7E;MIAO VOWEL SIGN NG;Mc;0;L;;;;;N;;;;; +16F8F;MIAO TONE RIGHT;Mn;0;NSM;;;;;N;;;;; +16F90;MIAO TONE TOP RIGHT;Mn;0;NSM;;;;;N;;;;; +16F91;MIAO TONE ABOVE;Mn;0;NSM;;;;;N;;;;; +16F92;MIAO TONE BELOW;Mn;0;NSM;;;;;N;;;;; +16F93;MIAO LETTER TONE-2;Lm;0;L;;;;;N;;;;; +16F94;MIAO LETTER TONE-3;Lm;0;L;;;;;N;;;;; +16F95;MIAO LETTER TONE-4;Lm;0;L;;;;;N;;;;; +16F96;MIAO LETTER TONE-5;Lm;0;L;;;;;N;;;;; +16F97;MIAO LETTER TONE-6;Lm;0;L;;;;;N;;;;; +16F98;MIAO LETTER TONE-7;Lm;0;L;;;;;N;;;;; +16F99;MIAO LETTER TONE-8;Lm;0;L;;;;;N;;;;; +16F9A;MIAO LETTER REFORMED TONE-1;Lm;0;L;;;;;N;;;;; +16F9B;MIAO LETTER REFORMED TONE-2;Lm;0;L;;;;;N;;;;; +16F9C;MIAO LETTER REFORMED TONE-4;Lm;0;L;;;;;N;;;;; +16F9D;MIAO LETTER REFORMED TONE-5;Lm;0;L;;;;;N;;;;; +16F9E;MIAO LETTER REFORMED TONE-6;Lm;0;L;;;;;N;;;;; +16F9F;MIAO LETTER REFORMED TONE-8;Lm;0;L;;;;;N;;;;; +1B000;KATAKANA LETTER ARCHAIC E;Lo;0;L;;;;;N;;;;; +1B001;HIRAGANA LETTER ARCHAIC YE;Lo;0;L;;;;;N;;;;; +1D000;BYZANTINE MUSICAL SYMBOL PSILI;So;0;L;;;;;N;;;;; +1D001;BYZANTINE MUSICAL SYMBOL DASEIA;So;0;L;;;;;N;;;;; +1D002;BYZANTINE MUSICAL SYMBOL PERISPOMENI;So;0;L;;;;;N;;;;; +1D003;BYZANTINE MUSICAL SYMBOL OXEIA EKFONITIKON;So;0;L;;;;;N;;;;; +1D004;BYZANTINE MUSICAL SYMBOL OXEIA DIPLI;So;0;L;;;;;N;;;;; +1D005;BYZANTINE MUSICAL SYMBOL VAREIA EKFONITIKON;So;0;L;;;;;N;;;;; +1D006;BYZANTINE MUSICAL SYMBOL VAREIA DIPLI;So;0;L;;;;;N;;;;; +1D007;BYZANTINE MUSICAL SYMBOL KATHISTI;So;0;L;;;;;N;;;;; +1D008;BYZANTINE MUSICAL SYMBOL SYRMATIKI;So;0;L;;;;;N;;;;; +1D009;BYZANTINE MUSICAL SYMBOL PARAKLITIKI;So;0;L;;;;;N;;;;; +1D00A;BYZANTINE MUSICAL SYMBOL YPOKRISIS;So;0;L;;;;;N;;;;; +1D00B;BYZANTINE MUSICAL SYMBOL YPOKRISIS DIPLI;So;0;L;;;;;N;;;;; +1D00C;BYZANTINE MUSICAL SYMBOL KREMASTI;So;0;L;;;;;N;;;;; +1D00D;BYZANTINE MUSICAL SYMBOL APESO EKFONITIKON;So;0;L;;;;;N;;;;; +1D00E;BYZANTINE MUSICAL SYMBOL EXO EKFONITIKON;So;0;L;;;;;N;;;;; +1D00F;BYZANTINE MUSICAL SYMBOL TELEIA;So;0;L;;;;;N;;;;; +1D010;BYZANTINE MUSICAL SYMBOL KENTIMATA;So;0;L;;;;;N;;;;; +1D011;BYZANTINE MUSICAL SYMBOL APOSTROFOS;So;0;L;;;;;N;;;;; +1D012;BYZANTINE MUSICAL SYMBOL APOSTROFOS DIPLI;So;0;L;;;;;N;;;;; +1D013;BYZANTINE MUSICAL SYMBOL SYNEVMA;So;0;L;;;;;N;;;;; +1D014;BYZANTINE MUSICAL SYMBOL THITA;So;0;L;;;;;N;;;;; +1D015;BYZANTINE MUSICAL SYMBOL OLIGON ARCHAION;So;0;L;;;;;N;;;;; +1D016;BYZANTINE MUSICAL SYMBOL GORGON ARCHAION;So;0;L;;;;;N;;;;; +1D017;BYZANTINE MUSICAL SYMBOL PSILON;So;0;L;;;;;N;;;;; +1D018;BYZANTINE MUSICAL SYMBOL CHAMILON;So;0;L;;;;;N;;;;; +1D019;BYZANTINE MUSICAL SYMBOL VATHY;So;0;L;;;;;N;;;;; +1D01A;BYZANTINE MUSICAL SYMBOL ISON ARCHAION;So;0;L;;;;;N;;;;; +1D01B;BYZANTINE MUSICAL SYMBOL KENTIMA ARCHAION;So;0;L;;;;;N;;;;; +1D01C;BYZANTINE MUSICAL SYMBOL KENTIMATA ARCHAION;So;0;L;;;;;N;;;;; +1D01D;BYZANTINE MUSICAL SYMBOL SAXIMATA;So;0;L;;;;;N;;;;; +1D01E;BYZANTINE MUSICAL SYMBOL PARICHON;So;0;L;;;;;N;;;;; +1D01F;BYZANTINE MUSICAL SYMBOL STAVROS APODEXIA;So;0;L;;;;;N;;;;; +1D020;BYZANTINE MUSICAL SYMBOL OXEIAI ARCHAION;So;0;L;;;;;N;;;;; +1D021;BYZANTINE MUSICAL SYMBOL VAREIAI ARCHAION;So;0;L;;;;;N;;;;; +1D022;BYZANTINE MUSICAL SYMBOL APODERMA ARCHAION;So;0;L;;;;;N;;;;; +1D023;BYZANTINE MUSICAL SYMBOL APOTHEMA;So;0;L;;;;;N;;;;; +1D024;BYZANTINE MUSICAL SYMBOL KLASMA;So;0;L;;;;;N;;;;; +1D025;BYZANTINE MUSICAL SYMBOL REVMA;So;0;L;;;;;N;;;;; +1D026;BYZANTINE MUSICAL SYMBOL PIASMA ARCHAION;So;0;L;;;;;N;;;;; +1D027;BYZANTINE MUSICAL SYMBOL TINAGMA;So;0;L;;;;;N;;;;; +1D028;BYZANTINE MUSICAL SYMBOL ANATRICHISMA;So;0;L;;;;;N;;;;; +1D029;BYZANTINE MUSICAL SYMBOL SEISMA;So;0;L;;;;;N;;;;; +1D02A;BYZANTINE MUSICAL SYMBOL SYNAGMA ARCHAION;So;0;L;;;;;N;;;;; +1D02B;BYZANTINE MUSICAL SYMBOL SYNAGMA META STAVROU;So;0;L;;;;;N;;;;; +1D02C;BYZANTINE MUSICAL SYMBOL OYRANISMA ARCHAION;So;0;L;;;;;N;;;;; +1D02D;BYZANTINE MUSICAL SYMBOL THEMA;So;0;L;;;;;N;;;;; +1D02E;BYZANTINE MUSICAL SYMBOL LEMOI;So;0;L;;;;;N;;;;; +1D02F;BYZANTINE MUSICAL SYMBOL DYO;So;0;L;;;;;N;;;;; +1D030;BYZANTINE MUSICAL SYMBOL TRIA;So;0;L;;;;;N;;;;; +1D031;BYZANTINE MUSICAL SYMBOL TESSERA;So;0;L;;;;;N;;;;; +1D032;BYZANTINE MUSICAL SYMBOL KRATIMATA;So;0;L;;;;;N;;;;; +1D033;BYZANTINE MUSICAL SYMBOL APESO EXO NEO;So;0;L;;;;;N;;;;; +1D034;BYZANTINE MUSICAL SYMBOL FTHORA ARCHAION;So;0;L;;;;;N;;;;; +1D035;BYZANTINE MUSICAL SYMBOL IMIFTHORA;So;0;L;;;;;N;;;;; +1D036;BYZANTINE MUSICAL SYMBOL TROMIKON ARCHAION;So;0;L;;;;;N;;;;; +1D037;BYZANTINE MUSICAL SYMBOL KATAVA TROMIKON;So;0;L;;;;;N;;;;; +1D038;BYZANTINE MUSICAL SYMBOL PELASTON;So;0;L;;;;;N;;;;; +1D039;BYZANTINE MUSICAL SYMBOL PSIFISTON;So;0;L;;;;;N;;;;; +1D03A;BYZANTINE MUSICAL SYMBOL KONTEVMA;So;0;L;;;;;N;;;;; +1D03B;BYZANTINE MUSICAL SYMBOL CHOREVMA ARCHAION;So;0;L;;;;;N;;;;; +1D03C;BYZANTINE MUSICAL SYMBOL RAPISMA;So;0;L;;;;;N;;;;; +1D03D;BYZANTINE MUSICAL SYMBOL PARAKALESMA ARCHAION;So;0;L;;;;;N;;;;; +1D03E;BYZANTINE MUSICAL SYMBOL PARAKLITIKI ARCHAION;So;0;L;;;;;N;;;;; +1D03F;BYZANTINE MUSICAL SYMBOL ICHADIN;So;0;L;;;;;N;;;;; +1D040;BYZANTINE MUSICAL SYMBOL NANA;So;0;L;;;;;N;;;;; +1D041;BYZANTINE MUSICAL SYMBOL PETASMA;So;0;L;;;;;N;;;;; +1D042;BYZANTINE MUSICAL SYMBOL KONTEVMA ALLO;So;0;L;;;;;N;;;;; +1D043;BYZANTINE MUSICAL SYMBOL TROMIKON ALLO;So;0;L;;;;;N;;;;; +1D044;BYZANTINE MUSICAL SYMBOL STRAGGISMATA;So;0;L;;;;;N;;;;; +1D045;BYZANTINE MUSICAL SYMBOL GRONTHISMATA;So;0;L;;;;;N;;;;; +1D046;BYZANTINE MUSICAL SYMBOL ISON NEO;So;0;L;;;;;N;;;;; +1D047;BYZANTINE MUSICAL SYMBOL OLIGON NEO;So;0;L;;;;;N;;;;; +1D048;BYZANTINE MUSICAL SYMBOL OXEIA NEO;So;0;L;;;;;N;;;;; +1D049;BYZANTINE MUSICAL SYMBOL PETASTI;So;0;L;;;;;N;;;;; +1D04A;BYZANTINE MUSICAL SYMBOL KOUFISMA;So;0;L;;;;;N;;;;; +1D04B;BYZANTINE MUSICAL SYMBOL PETASTOKOUFISMA;So;0;L;;;;;N;;;;; +1D04C;BYZANTINE MUSICAL SYMBOL KRATIMOKOUFISMA;So;0;L;;;;;N;;;;; +1D04D;BYZANTINE MUSICAL SYMBOL PELASTON NEO;So;0;L;;;;;N;;;;; +1D04E;BYZANTINE MUSICAL SYMBOL KENTIMATA NEO ANO;So;0;L;;;;;N;;;;; +1D04F;BYZANTINE MUSICAL SYMBOL KENTIMA NEO ANO;So;0;L;;;;;N;;;;; +1D050;BYZANTINE MUSICAL SYMBOL YPSILI;So;0;L;;;;;N;;;;; +1D051;BYZANTINE MUSICAL SYMBOL APOSTROFOS NEO;So;0;L;;;;;N;;;;; +1D052;BYZANTINE MUSICAL SYMBOL APOSTROFOI SYNDESMOS NEO;So;0;L;;;;;N;;;;; +1D053;BYZANTINE MUSICAL SYMBOL YPORROI;So;0;L;;;;;N;;;;; +1D054;BYZANTINE MUSICAL SYMBOL KRATIMOYPORROON;So;0;L;;;;;N;;;;; +1D055;BYZANTINE MUSICAL SYMBOL ELAFRON;So;0;L;;;;;N;;;;; +1D056;BYZANTINE MUSICAL SYMBOL CHAMILI;So;0;L;;;;;N;;;;; +1D057;BYZANTINE MUSICAL SYMBOL MIKRON ISON;So;0;L;;;;;N;;;;; +1D058;BYZANTINE MUSICAL SYMBOL VAREIA NEO;So;0;L;;;;;N;;;;; +1D059;BYZANTINE MUSICAL SYMBOL PIASMA NEO;So;0;L;;;;;N;;;;; +1D05A;BYZANTINE MUSICAL SYMBOL PSIFISTON NEO;So;0;L;;;;;N;;;;; +1D05B;BYZANTINE MUSICAL SYMBOL OMALON;So;0;L;;;;;N;;;;; +1D05C;BYZANTINE MUSICAL SYMBOL ANTIKENOMA;So;0;L;;;;;N;;;;; +1D05D;BYZANTINE MUSICAL SYMBOL LYGISMA;So;0;L;;;;;N;;;;; +1D05E;BYZANTINE MUSICAL SYMBOL PARAKLITIKI NEO;So;0;L;;;;;N;;;;; +1D05F;BYZANTINE MUSICAL SYMBOL PARAKALESMA NEO;So;0;L;;;;;N;;;;; +1D060;BYZANTINE MUSICAL SYMBOL ETERON PARAKALESMA;So;0;L;;;;;N;;;;; +1D061;BYZANTINE MUSICAL SYMBOL KYLISMA;So;0;L;;;;;N;;;;; +1D062;BYZANTINE MUSICAL SYMBOL ANTIKENOKYLISMA;So;0;L;;;;;N;;;;; +1D063;BYZANTINE MUSICAL SYMBOL TROMIKON NEO;So;0;L;;;;;N;;;;; +1D064;BYZANTINE MUSICAL SYMBOL EKSTREPTON;So;0;L;;;;;N;;;;; +1D065;BYZANTINE MUSICAL SYMBOL SYNAGMA NEO;So;0;L;;;;;N;;;;; +1D066;BYZANTINE MUSICAL SYMBOL SYRMA;So;0;L;;;;;N;;;;; +1D067;BYZANTINE MUSICAL SYMBOL CHOREVMA NEO;So;0;L;;;;;N;;;;; +1D068;BYZANTINE MUSICAL SYMBOL EPEGERMA;So;0;L;;;;;N;;;;; +1D069;BYZANTINE MUSICAL SYMBOL SEISMA NEO;So;0;L;;;;;N;;;;; +1D06A;BYZANTINE MUSICAL SYMBOL XIRON KLASMA;So;0;L;;;;;N;;;;; +1D06B;BYZANTINE MUSICAL SYMBOL TROMIKOPSIFISTON;So;0;L;;;;;N;;;;; +1D06C;BYZANTINE MUSICAL SYMBOL PSIFISTOLYGISMA;So;0;L;;;;;N;;;;; +1D06D;BYZANTINE MUSICAL SYMBOL TROMIKOLYGISMA;So;0;L;;;;;N;;;;; +1D06E;BYZANTINE MUSICAL SYMBOL TROMIKOPARAKALESMA;So;0;L;;;;;N;;;;; +1D06F;BYZANTINE MUSICAL SYMBOL PSIFISTOPARAKALESMA;So;0;L;;;;;N;;;;; +1D070;BYZANTINE MUSICAL SYMBOL TROMIKOSYNAGMA;So;0;L;;;;;N;;;;; +1D071;BYZANTINE MUSICAL SYMBOL PSIFISTOSYNAGMA;So;0;L;;;;;N;;;;; +1D072;BYZANTINE MUSICAL SYMBOL GORGOSYNTHETON;So;0;L;;;;;N;;;;; +1D073;BYZANTINE MUSICAL SYMBOL ARGOSYNTHETON;So;0;L;;;;;N;;;;; +1D074;BYZANTINE MUSICAL SYMBOL ETERON ARGOSYNTHETON;So;0;L;;;;;N;;;;; +1D075;BYZANTINE MUSICAL SYMBOL OYRANISMA NEO;So;0;L;;;;;N;;;;; +1D076;BYZANTINE MUSICAL SYMBOL THEMATISMOS ESO;So;0;L;;;;;N;;;;; +1D077;BYZANTINE MUSICAL SYMBOL THEMATISMOS EXO;So;0;L;;;;;N;;;;; +1D078;BYZANTINE MUSICAL SYMBOL THEMA APLOUN;So;0;L;;;;;N;;;;; +1D079;BYZANTINE MUSICAL SYMBOL THES KAI APOTHES;So;0;L;;;;;N;;;;; +1D07A;BYZANTINE MUSICAL SYMBOL KATAVASMA;So;0;L;;;;;N;;;;; +1D07B;BYZANTINE MUSICAL SYMBOL ENDOFONON;So;0;L;;;;;N;;;;; +1D07C;BYZANTINE MUSICAL SYMBOL YFEN KATO;So;0;L;;;;;N;;;;; +1D07D;BYZANTINE MUSICAL SYMBOL YFEN ANO;So;0;L;;;;;N;;;;; +1D07E;BYZANTINE MUSICAL SYMBOL STAVROS;So;0;L;;;;;N;;;;; +1D07F;BYZANTINE MUSICAL SYMBOL KLASMA ANO;So;0;L;;;;;N;;;;; +1D080;BYZANTINE MUSICAL SYMBOL DIPLI ARCHAION;So;0;L;;;;;N;;;;; +1D081;BYZANTINE MUSICAL SYMBOL KRATIMA ARCHAION;So;0;L;;;;;N;;;;; +1D082;BYZANTINE MUSICAL SYMBOL KRATIMA ALLO;So;0;L;;;;;N;;;;; +1D083;BYZANTINE MUSICAL SYMBOL KRATIMA NEO;So;0;L;;;;;N;;;;; +1D084;BYZANTINE MUSICAL SYMBOL APODERMA NEO;So;0;L;;;;;N;;;;; +1D085;BYZANTINE MUSICAL SYMBOL APLI;So;0;L;;;;;N;;;;; +1D086;BYZANTINE MUSICAL SYMBOL DIPLI;So;0;L;;;;;N;;;;; +1D087;BYZANTINE MUSICAL SYMBOL TRIPLI;So;0;L;;;;;N;;;;; +1D088;BYZANTINE MUSICAL SYMBOL TETRAPLI;So;0;L;;;;;N;;;;; +1D089;BYZANTINE MUSICAL SYMBOL KORONIS;So;0;L;;;;;N;;;;; +1D08A;BYZANTINE MUSICAL SYMBOL LEIMMA ENOS CHRONOU;So;0;L;;;;;N;;;;; +1D08B;BYZANTINE MUSICAL SYMBOL LEIMMA DYO CHRONON;So;0;L;;;;;N;;;;; +1D08C;BYZANTINE MUSICAL SYMBOL LEIMMA TRION CHRONON;So;0;L;;;;;N;;;;; +1D08D;BYZANTINE MUSICAL SYMBOL LEIMMA TESSARON CHRONON;So;0;L;;;;;N;;;;; +1D08E;BYZANTINE MUSICAL SYMBOL LEIMMA IMISEOS CHRONOU;So;0;L;;;;;N;;;;; +1D08F;BYZANTINE MUSICAL SYMBOL GORGON NEO ANO;So;0;L;;;;;N;;;;; +1D090;BYZANTINE MUSICAL SYMBOL GORGON PARESTIGMENON ARISTERA;So;0;L;;;;;N;;;;; +1D091;BYZANTINE MUSICAL SYMBOL GORGON PARESTIGMENON DEXIA;So;0;L;;;;;N;;;;; +1D092;BYZANTINE MUSICAL SYMBOL DIGORGON;So;0;L;;;;;N;;;;; +1D093;BYZANTINE MUSICAL SYMBOL DIGORGON PARESTIGMENON ARISTERA KATO;So;0;L;;;;;N;;;;; +1D094;BYZANTINE MUSICAL SYMBOL DIGORGON PARESTIGMENON ARISTERA ANO;So;0;L;;;;;N;;;;; +1D095;BYZANTINE MUSICAL SYMBOL DIGORGON PARESTIGMENON DEXIA;So;0;L;;;;;N;;;;; +1D096;BYZANTINE MUSICAL SYMBOL TRIGORGON;So;0;L;;;;;N;;;;; +1D097;BYZANTINE MUSICAL SYMBOL ARGON;So;0;L;;;;;N;;;;; +1D098;BYZANTINE MUSICAL SYMBOL IMIDIARGON;So;0;L;;;;;N;;;;; +1D099;BYZANTINE MUSICAL SYMBOL DIARGON;So;0;L;;;;;N;;;;; +1D09A;BYZANTINE MUSICAL SYMBOL AGOGI POLI ARGI;So;0;L;;;;;N;;;;; +1D09B;BYZANTINE MUSICAL SYMBOL AGOGI ARGOTERI;So;0;L;;;;;N;;;;; +1D09C;BYZANTINE MUSICAL SYMBOL AGOGI ARGI;So;0;L;;;;;N;;;;; +1D09D;BYZANTINE MUSICAL SYMBOL AGOGI METRIA;So;0;L;;;;;N;;;;; +1D09E;BYZANTINE MUSICAL SYMBOL AGOGI MESI;So;0;L;;;;;N;;;;; +1D09F;BYZANTINE MUSICAL SYMBOL AGOGI GORGI;So;0;L;;;;;N;;;;; +1D0A0;BYZANTINE MUSICAL SYMBOL AGOGI GORGOTERI;So;0;L;;;;;N;;;;; +1D0A1;BYZANTINE MUSICAL SYMBOL AGOGI POLI GORGI;So;0;L;;;;;N;;;;; +1D0A2;BYZANTINE MUSICAL SYMBOL MARTYRIA PROTOS ICHOS;So;0;L;;;;;N;;;;; +1D0A3;BYZANTINE MUSICAL SYMBOL MARTYRIA ALLI PROTOS ICHOS;So;0;L;;;;;N;;;;; +1D0A4;BYZANTINE MUSICAL SYMBOL MARTYRIA DEYTEROS ICHOS;So;0;L;;;;;N;;;;; +1D0A5;BYZANTINE MUSICAL SYMBOL MARTYRIA ALLI DEYTEROS ICHOS;So;0;L;;;;;N;;;;; +1D0A6;BYZANTINE MUSICAL SYMBOL MARTYRIA TRITOS ICHOS;So;0;L;;;;;N;;;;; +1D0A7;BYZANTINE MUSICAL SYMBOL MARTYRIA TRIFONIAS;So;0;L;;;;;N;;;;; +1D0A8;BYZANTINE MUSICAL SYMBOL MARTYRIA TETARTOS ICHOS;So;0;L;;;;;N;;;;; +1D0A9;BYZANTINE MUSICAL SYMBOL MARTYRIA TETARTOS LEGETOS ICHOS;So;0;L;;;;;N;;;;; +1D0AA;BYZANTINE MUSICAL SYMBOL MARTYRIA LEGETOS ICHOS;So;0;L;;;;;N;;;;; +1D0AB;BYZANTINE MUSICAL SYMBOL MARTYRIA PLAGIOS ICHOS;So;0;L;;;;;N;;;;; +1D0AC;BYZANTINE MUSICAL SYMBOL ISAKIA TELOUS ICHIMATOS;So;0;L;;;;;N;;;;; +1D0AD;BYZANTINE MUSICAL SYMBOL APOSTROFOI TELOUS ICHIMATOS;So;0;L;;;;;N;;;;; +1D0AE;BYZANTINE MUSICAL SYMBOL FANEROSIS TETRAFONIAS;So;0;L;;;;;N;;;;; +1D0AF;BYZANTINE MUSICAL SYMBOL FANEROSIS MONOFONIAS;So;0;L;;;;;N;;;;; +1D0B0;BYZANTINE MUSICAL SYMBOL FANEROSIS DIFONIAS;So;0;L;;;;;N;;;;; +1D0B1;BYZANTINE MUSICAL SYMBOL MARTYRIA VARYS ICHOS;So;0;L;;;;;N;;;;; +1D0B2;BYZANTINE MUSICAL SYMBOL MARTYRIA PROTOVARYS ICHOS;So;0;L;;;;;N;;;;; +1D0B3;BYZANTINE MUSICAL SYMBOL MARTYRIA PLAGIOS TETARTOS ICHOS;So;0;L;;;;;N;;;;; +1D0B4;BYZANTINE MUSICAL SYMBOL GORTHMIKON N APLOUN;So;0;L;;;;;N;;;;; +1D0B5;BYZANTINE MUSICAL SYMBOL GORTHMIKON N DIPLOUN;So;0;L;;;;;N;;;;; +1D0B6;BYZANTINE MUSICAL SYMBOL ENARXIS KAI FTHORA VOU;So;0;L;;;;;N;;;;; +1D0B7;BYZANTINE MUSICAL SYMBOL IMIFONON;So;0;L;;;;;N;;;;; +1D0B8;BYZANTINE MUSICAL SYMBOL IMIFTHORON;So;0;L;;;;;N;;;;; +1D0B9;BYZANTINE MUSICAL SYMBOL FTHORA ARCHAION DEYTEROU ICHOU;So;0;L;;;;;N;;;;; +1D0BA;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI PA;So;0;L;;;;;N;;;;; +1D0BB;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI NANA;So;0;L;;;;;N;;;;; +1D0BC;BYZANTINE MUSICAL SYMBOL FTHORA NAOS ICHOS;So;0;L;;;;;N;;;;; +1D0BD;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI DI;So;0;L;;;;;N;;;;; +1D0BE;BYZANTINE MUSICAL SYMBOL FTHORA SKLIRON DIATONON DI;So;0;L;;;;;N;;;;; +1D0BF;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI KE;So;0;L;;;;;N;;;;; +1D0C0;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI ZO;So;0;L;;;;;N;;;;; +1D0C1;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI NI KATO;So;0;L;;;;;N;;;;; +1D0C2;BYZANTINE MUSICAL SYMBOL FTHORA DIATONIKI NI ANO;So;0;L;;;;;N;;;;; +1D0C3;BYZANTINE MUSICAL SYMBOL FTHORA MALAKON CHROMA DIFONIAS;So;0;L;;;;;N;;;;; +1D0C4;BYZANTINE MUSICAL SYMBOL FTHORA MALAKON CHROMA MONOFONIAS;So;0;L;;;;;N;;;;; +1D0C5;BYZANTINE MUSICAL SYMBOL FHTORA SKLIRON CHROMA VASIS;So;0;L;;;;;N;;;;; +1D0C6;BYZANTINE MUSICAL SYMBOL FTHORA SKLIRON CHROMA SYNAFI;So;0;L;;;;;N;;;;; +1D0C7;BYZANTINE MUSICAL SYMBOL FTHORA NENANO;So;0;L;;;;;N;;;;; +1D0C8;BYZANTINE MUSICAL SYMBOL CHROA ZYGOS;So;0;L;;;;;N;;;;; +1D0C9;BYZANTINE MUSICAL SYMBOL CHROA KLITON;So;0;L;;;;;N;;;;; +1D0CA;BYZANTINE MUSICAL SYMBOL CHROA SPATHI;So;0;L;;;;;N;;;;; +1D0CB;BYZANTINE MUSICAL SYMBOL FTHORA I YFESIS TETARTIMORION;So;0;L;;;;;N;;;;; +1D0CC;BYZANTINE MUSICAL SYMBOL FTHORA ENARMONIOS ANTIFONIA;So;0;L;;;;;N;;;;; +1D0CD;BYZANTINE MUSICAL SYMBOL YFESIS TRITIMORION;So;0;L;;;;;N;;;;; +1D0CE;BYZANTINE MUSICAL SYMBOL DIESIS TRITIMORION;So;0;L;;;;;N;;;;; +1D0CF;BYZANTINE MUSICAL SYMBOL DIESIS TETARTIMORION;So;0;L;;;;;N;;;;; +1D0D0;BYZANTINE MUSICAL SYMBOL DIESIS APLI DYO DODEKATA;So;0;L;;;;;N;;;;; +1D0D1;BYZANTINE MUSICAL SYMBOL DIESIS MONOGRAMMOS TESSERA DODEKATA;So;0;L;;;;;N;;;;; +1D0D2;BYZANTINE MUSICAL SYMBOL DIESIS DIGRAMMOS EX DODEKATA;So;0;L;;;;;N;;;;; +1D0D3;BYZANTINE MUSICAL SYMBOL DIESIS TRIGRAMMOS OKTO DODEKATA;So;0;L;;;;;N;;;;; +1D0D4;BYZANTINE MUSICAL SYMBOL YFESIS APLI DYO DODEKATA;So;0;L;;;;;N;;;;; +1D0D5;BYZANTINE MUSICAL SYMBOL YFESIS MONOGRAMMOS TESSERA DODEKATA;So;0;L;;;;;N;;;;; +1D0D6;BYZANTINE MUSICAL SYMBOL YFESIS DIGRAMMOS EX DODEKATA;So;0;L;;;;;N;;;;; +1D0D7;BYZANTINE MUSICAL SYMBOL YFESIS TRIGRAMMOS OKTO DODEKATA;So;0;L;;;;;N;;;;; +1D0D8;BYZANTINE MUSICAL SYMBOL GENIKI DIESIS;So;0;L;;;;;N;;;;; +1D0D9;BYZANTINE MUSICAL SYMBOL GENIKI YFESIS;So;0;L;;;;;N;;;;; +1D0DA;BYZANTINE MUSICAL SYMBOL DIASTOLI APLI MIKRI;So;0;L;;;;;N;;;;; +1D0DB;BYZANTINE MUSICAL SYMBOL DIASTOLI APLI MEGALI;So;0;L;;;;;N;;;;; +1D0DC;BYZANTINE MUSICAL SYMBOL DIASTOLI DIPLI;So;0;L;;;;;N;;;;; +1D0DD;BYZANTINE MUSICAL SYMBOL DIASTOLI THESEOS;So;0;L;;;;;N;;;;; +1D0DE;BYZANTINE MUSICAL SYMBOL SIMANSIS THESEOS;So;0;L;;;;;N;;;;; +1D0DF;BYZANTINE MUSICAL SYMBOL SIMANSIS THESEOS DISIMOU;So;0;L;;;;;N;;;;; +1D0E0;BYZANTINE MUSICAL SYMBOL SIMANSIS THESEOS TRISIMOU;So;0;L;;;;;N;;;;; +1D0E1;BYZANTINE MUSICAL SYMBOL SIMANSIS THESEOS TETRASIMOU;So;0;L;;;;;N;;;;; +1D0E2;BYZANTINE MUSICAL SYMBOL SIMANSIS ARSEOS;So;0;L;;;;;N;;;;; +1D0E3;BYZANTINE MUSICAL SYMBOL SIMANSIS ARSEOS DISIMOU;So;0;L;;;;;N;;;;; +1D0E4;BYZANTINE MUSICAL SYMBOL SIMANSIS ARSEOS TRISIMOU;So;0;L;;;;;N;;;;; +1D0E5;BYZANTINE MUSICAL SYMBOL SIMANSIS ARSEOS TETRASIMOU;So;0;L;;;;;N;;;;; +1D0E6;BYZANTINE MUSICAL SYMBOL DIGRAMMA GG;So;0;L;;;;;N;;;;; +1D0E7;BYZANTINE MUSICAL SYMBOL DIFTOGGOS OU;So;0;L;;;;;N;;;;; +1D0E8;BYZANTINE MUSICAL SYMBOL STIGMA;So;0;L;;;;;N;;;;; +1D0E9;BYZANTINE MUSICAL SYMBOL ARKTIKO PA;So;0;L;;;;;N;;;;; +1D0EA;BYZANTINE MUSICAL SYMBOL ARKTIKO VOU;So;0;L;;;;;N;;;;; +1D0EB;BYZANTINE MUSICAL SYMBOL ARKTIKO GA;So;0;L;;;;;N;;;;; +1D0EC;BYZANTINE MUSICAL SYMBOL ARKTIKO DI;So;0;L;;;;;N;;;;; +1D0ED;BYZANTINE MUSICAL SYMBOL ARKTIKO KE;So;0;L;;;;;N;;;;; +1D0EE;BYZANTINE MUSICAL SYMBOL ARKTIKO ZO;So;0;L;;;;;N;;;;; +1D0EF;BYZANTINE MUSICAL SYMBOL ARKTIKO NI;So;0;L;;;;;N;;;;; +1D0F0;BYZANTINE MUSICAL SYMBOL KENTIMATA NEO MESO;So;0;L;;;;;N;;;;; +1D0F1;BYZANTINE MUSICAL SYMBOL KENTIMA NEO MESO;So;0;L;;;;;N;;;;; +1D0F2;BYZANTINE MUSICAL SYMBOL KENTIMATA NEO KATO;So;0;L;;;;;N;;;;; +1D0F3;BYZANTINE MUSICAL SYMBOL KENTIMA NEO KATO;So;0;L;;;;;N;;;;; +1D0F4;BYZANTINE MUSICAL SYMBOL KLASMA KATO;So;0;L;;;;;N;;;;; +1D0F5;BYZANTINE MUSICAL SYMBOL GORGON NEO KATO;So;0;L;;;;;N;;;;; +1D100;MUSICAL SYMBOL SINGLE BARLINE;So;0;L;;;;;N;;;;; +1D101;MUSICAL SYMBOL DOUBLE BARLINE;So;0;L;;;;;N;;;;; +1D102;MUSICAL SYMBOL FINAL BARLINE;So;0;L;;;;;N;;;;; +1D103;MUSICAL SYMBOL REVERSE FINAL BARLINE;So;0;L;;;;;N;;;;; +1D104;MUSICAL SYMBOL DASHED BARLINE;So;0;L;;;;;N;;;;; +1D105;MUSICAL SYMBOL SHORT BARLINE;So;0;L;;;;;N;;;;; +1D106;MUSICAL SYMBOL LEFT REPEAT SIGN;So;0;L;;;;;N;;;;; +1D107;MUSICAL SYMBOL RIGHT REPEAT SIGN;So;0;L;;;;;N;;;;; +1D108;MUSICAL SYMBOL REPEAT DOTS;So;0;L;;;;;N;;;;; +1D109;MUSICAL SYMBOL DAL SEGNO;So;0;L;;;;;N;;;;; +1D10A;MUSICAL SYMBOL DA CAPO;So;0;L;;;;;N;;;;; +1D10B;MUSICAL SYMBOL SEGNO;So;0;L;;;;;N;;;;; +1D10C;MUSICAL SYMBOL CODA;So;0;L;;;;;N;;;;; +1D10D;MUSICAL SYMBOL REPEATED FIGURE-1;So;0;L;;;;;N;;;;; +1D10E;MUSICAL SYMBOL REPEATED FIGURE-2;So;0;L;;;;;N;;;;; +1D10F;MUSICAL SYMBOL REPEATED FIGURE-3;So;0;L;;;;;N;;;;; +1D110;MUSICAL SYMBOL FERMATA;So;0;L;;;;;N;;;;; +1D111;MUSICAL SYMBOL FERMATA BELOW;So;0;L;;;;;N;;;;; +1D112;MUSICAL SYMBOL BREATH MARK;So;0;L;;;;;N;;;;; +1D113;MUSICAL SYMBOL CAESURA;So;0;L;;;;;N;;;;; +1D114;MUSICAL SYMBOL BRACE;So;0;L;;;;;N;;;;; +1D115;MUSICAL SYMBOL BRACKET;So;0;L;;;;;N;;;;; +1D116;MUSICAL SYMBOL ONE-LINE STAFF;So;0;L;;;;;N;;;;; +1D117;MUSICAL SYMBOL TWO-LINE STAFF;So;0;L;;;;;N;;;;; +1D118;MUSICAL SYMBOL THREE-LINE STAFF;So;0;L;;;;;N;;;;; +1D119;MUSICAL SYMBOL FOUR-LINE STAFF;So;0;L;;;;;N;;;;; +1D11A;MUSICAL SYMBOL FIVE-LINE STAFF;So;0;L;;;;;N;;;;; +1D11B;MUSICAL SYMBOL SIX-LINE STAFF;So;0;L;;;;;N;;;;; +1D11C;MUSICAL SYMBOL SIX-STRING FRETBOARD;So;0;L;;;;;N;;;;; +1D11D;MUSICAL SYMBOL FOUR-STRING FRETBOARD;So;0;L;;;;;N;;;;; +1D11E;MUSICAL SYMBOL G CLEF;So;0;L;;;;;N;;;;; +1D11F;MUSICAL SYMBOL G CLEF OTTAVA ALTA;So;0;L;;;;;N;;;;; +1D120;MUSICAL SYMBOL G CLEF OTTAVA BASSA;So;0;L;;;;;N;;;;; +1D121;MUSICAL SYMBOL C CLEF;So;0;L;;;;;N;;;;; +1D122;MUSICAL SYMBOL F CLEF;So;0;L;;;;;N;;;;; +1D123;MUSICAL SYMBOL F CLEF OTTAVA ALTA;So;0;L;;;;;N;;;;; +1D124;MUSICAL SYMBOL F CLEF OTTAVA BASSA;So;0;L;;;;;N;;;;; +1D125;MUSICAL SYMBOL DRUM CLEF-1;So;0;L;;;;;N;;;;; +1D126;MUSICAL SYMBOL DRUM CLEF-2;So;0;L;;;;;N;;;;; +1D129;MUSICAL SYMBOL MULTIPLE MEASURE REST;So;0;L;;;;;N;;;;; +1D12A;MUSICAL SYMBOL DOUBLE SHARP;So;0;L;;;;;N;;;;; +1D12B;MUSICAL SYMBOL DOUBLE FLAT;So;0;L;;;;;N;;;;; +1D12C;MUSICAL SYMBOL FLAT UP;So;0;L;;;;;N;;;;; +1D12D;MUSICAL SYMBOL FLAT DOWN;So;0;L;;;;;N;;;;; +1D12E;MUSICAL SYMBOL NATURAL UP;So;0;L;;;;;N;;;;; +1D12F;MUSICAL SYMBOL NATURAL DOWN;So;0;L;;;;;N;;;;; +1D130;MUSICAL SYMBOL SHARP UP;So;0;L;;;;;N;;;;; +1D131;MUSICAL SYMBOL SHARP DOWN;So;0;L;;;;;N;;;;; +1D132;MUSICAL SYMBOL QUARTER TONE SHARP;So;0;L;;;;;N;;;;; +1D133;MUSICAL SYMBOL QUARTER TONE FLAT;So;0;L;;;;;N;;;;; +1D134;MUSICAL SYMBOL COMMON TIME;So;0;L;;;;;N;;;;; +1D135;MUSICAL SYMBOL CUT TIME;So;0;L;;;;;N;;;;; +1D136;MUSICAL SYMBOL OTTAVA ALTA;So;0;L;;;;;N;;;;; +1D137;MUSICAL SYMBOL OTTAVA BASSA;So;0;L;;;;;N;;;;; +1D138;MUSICAL SYMBOL QUINDICESIMA ALTA;So;0;L;;;;;N;;;;; +1D139;MUSICAL SYMBOL QUINDICESIMA BASSA;So;0;L;;;;;N;;;;; +1D13A;MUSICAL SYMBOL MULTI REST;So;0;L;;;;;N;;;;; +1D13B;MUSICAL SYMBOL WHOLE REST;So;0;L;;;;;N;;;;; +1D13C;MUSICAL SYMBOL HALF REST;So;0;L;;;;;N;;;;; +1D13D;MUSICAL SYMBOL QUARTER REST;So;0;L;;;;;N;;;;; +1D13E;MUSICAL SYMBOL EIGHTH REST;So;0;L;;;;;N;;;;; +1D13F;MUSICAL SYMBOL SIXTEENTH REST;So;0;L;;;;;N;;;;; +1D140;MUSICAL SYMBOL THIRTY-SECOND REST;So;0;L;;;;;N;;;;; +1D141;MUSICAL SYMBOL SIXTY-FOURTH REST;So;0;L;;;;;N;;;;; +1D142;MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH REST;So;0;L;;;;;N;;;;; +1D143;MUSICAL SYMBOL X NOTEHEAD;So;0;L;;;;;N;;;;; +1D144;MUSICAL SYMBOL PLUS NOTEHEAD;So;0;L;;;;;N;;;;; +1D145;MUSICAL SYMBOL CIRCLE X NOTEHEAD;So;0;L;;;;;N;;;;; +1D146;MUSICAL SYMBOL SQUARE NOTEHEAD WHITE;So;0;L;;;;;N;;;;; +1D147;MUSICAL SYMBOL SQUARE NOTEHEAD BLACK;So;0;L;;;;;N;;;;; +1D148;MUSICAL SYMBOL TRIANGLE NOTEHEAD UP WHITE;So;0;L;;;;;N;;;;; +1D149;MUSICAL SYMBOL TRIANGLE NOTEHEAD UP BLACK;So;0;L;;;;;N;;;;; +1D14A;MUSICAL SYMBOL TRIANGLE NOTEHEAD LEFT WHITE;So;0;L;;;;;N;;;;; +1D14B;MUSICAL SYMBOL TRIANGLE NOTEHEAD LEFT BLACK;So;0;L;;;;;N;;;;; +1D14C;MUSICAL SYMBOL TRIANGLE NOTEHEAD RIGHT WHITE;So;0;L;;;;;N;;;;; +1D14D;MUSICAL SYMBOL TRIANGLE NOTEHEAD RIGHT BLACK;So;0;L;;;;;N;;;;; +1D14E;MUSICAL SYMBOL TRIANGLE NOTEHEAD DOWN WHITE;So;0;L;;;;;N;;;;; +1D14F;MUSICAL SYMBOL TRIANGLE NOTEHEAD DOWN BLACK;So;0;L;;;;;N;;;;; +1D150;MUSICAL SYMBOL TRIANGLE NOTEHEAD UP RIGHT WHITE;So;0;L;;;;;N;;;;; +1D151;MUSICAL SYMBOL TRIANGLE NOTEHEAD UP RIGHT BLACK;So;0;L;;;;;N;;;;; +1D152;MUSICAL SYMBOL MOON NOTEHEAD WHITE;So;0;L;;;;;N;;;;; +1D153;MUSICAL SYMBOL MOON NOTEHEAD BLACK;So;0;L;;;;;N;;;;; +1D154;MUSICAL SYMBOL TRIANGLE-ROUND NOTEHEAD DOWN WHITE;So;0;L;;;;;N;;;;; +1D155;MUSICAL SYMBOL TRIANGLE-ROUND NOTEHEAD DOWN BLACK;So;0;L;;;;;N;;;;; +1D156;MUSICAL SYMBOL PARENTHESIS NOTEHEAD;So;0;L;;;;;N;;;;; +1D157;MUSICAL SYMBOL VOID NOTEHEAD;So;0;L;;;;;N;;;;; +1D158;MUSICAL SYMBOL NOTEHEAD BLACK;So;0;L;;;;;N;;;;; +1D159;MUSICAL SYMBOL NULL NOTEHEAD;So;0;L;;;;;N;;;;; +1D15A;MUSICAL SYMBOL CLUSTER NOTEHEAD WHITE;So;0;L;;;;;N;;;;; +1D15B;MUSICAL SYMBOL CLUSTER NOTEHEAD BLACK;So;0;L;;;;;N;;;;; +1D15C;MUSICAL SYMBOL BREVE;So;0;L;;;;;N;;;;; +1D15D;MUSICAL SYMBOL WHOLE NOTE;So;0;L;;;;;N;;;;; +1D15E;MUSICAL SYMBOL HALF NOTE;So;0;L;1D157 1D165;;;;N;;;;; +1D15F;MUSICAL SYMBOL QUARTER NOTE;So;0;L;1D158 1D165;;;;N;;;;; +1D160;MUSICAL SYMBOL EIGHTH NOTE;So;0;L;1D15F 1D16E;;;;N;;;;; +1D161;MUSICAL SYMBOL SIXTEENTH NOTE;So;0;L;1D15F 1D16F;;;;N;;;;; +1D162;MUSICAL SYMBOL THIRTY-SECOND NOTE;So;0;L;1D15F 1D170;;;;N;;;;; +1D163;MUSICAL SYMBOL SIXTY-FOURTH NOTE;So;0;L;1D15F 1D171;;;;N;;;;; +1D164;MUSICAL SYMBOL ONE HUNDRED TWENTY-EIGHTH NOTE;So;0;L;1D15F 1D172;;;;N;;;;; +1D165;MUSICAL SYMBOL COMBINING STEM;Mc;216;L;;;;;N;;;;; +1D166;MUSICAL SYMBOL COMBINING SPRECHGESANG STEM;Mc;216;L;;;;;N;;;;; +1D167;MUSICAL SYMBOL COMBINING TREMOLO-1;Mn;1;NSM;;;;;N;;;;; +1D168;MUSICAL SYMBOL COMBINING TREMOLO-2;Mn;1;NSM;;;;;N;;;;; +1D169;MUSICAL SYMBOL COMBINING TREMOLO-3;Mn;1;NSM;;;;;N;;;;; +1D16A;MUSICAL SYMBOL FINGERED TREMOLO-1;So;0;L;;;;;N;;;;; +1D16B;MUSICAL SYMBOL FINGERED TREMOLO-2;So;0;L;;;;;N;;;;; +1D16C;MUSICAL SYMBOL FINGERED TREMOLO-3;So;0;L;;;;;N;;;;; +1D16D;MUSICAL SYMBOL COMBINING AUGMENTATION DOT;Mc;226;L;;;;;N;;;;; +1D16E;MUSICAL SYMBOL COMBINING FLAG-1;Mc;216;L;;;;;N;;;;; +1D16F;MUSICAL SYMBOL COMBINING FLAG-2;Mc;216;L;;;;;N;;;;; +1D170;MUSICAL SYMBOL COMBINING FLAG-3;Mc;216;L;;;;;N;;;;; +1D171;MUSICAL SYMBOL COMBINING FLAG-4;Mc;216;L;;;;;N;;;;; +1D172;MUSICAL SYMBOL COMBINING FLAG-5;Mc;216;L;;;;;N;;;;; +1D173;MUSICAL SYMBOL BEGIN BEAM;Cf;0;BN;;;;;N;;;;; +1D174;MUSICAL SYMBOL END BEAM;Cf;0;BN;;;;;N;;;;; +1D175;MUSICAL SYMBOL BEGIN TIE;Cf;0;BN;;;;;N;;;;; +1D176;MUSICAL SYMBOL END TIE;Cf;0;BN;;;;;N;;;;; +1D177;MUSICAL SYMBOL BEGIN SLUR;Cf;0;BN;;;;;N;;;;; +1D178;MUSICAL SYMBOL END SLUR;Cf;0;BN;;;;;N;;;;; +1D179;MUSICAL SYMBOL BEGIN PHRASE;Cf;0;BN;;;;;N;;;;; +1D17A;MUSICAL SYMBOL END PHRASE;Cf;0;BN;;;;;N;;;;; +1D17B;MUSICAL SYMBOL COMBINING ACCENT;Mn;220;NSM;;;;;N;;;;; +1D17C;MUSICAL SYMBOL COMBINING STACCATO;Mn;220;NSM;;;;;N;;;;; +1D17D;MUSICAL SYMBOL COMBINING TENUTO;Mn;220;NSM;;;;;N;;;;; +1D17E;MUSICAL SYMBOL COMBINING STACCATISSIMO;Mn;220;NSM;;;;;N;;;;; +1D17F;MUSICAL SYMBOL COMBINING MARCATO;Mn;220;NSM;;;;;N;;;;; +1D180;MUSICAL SYMBOL COMBINING MARCATO-STACCATO;Mn;220;NSM;;;;;N;;;;; +1D181;MUSICAL SYMBOL COMBINING ACCENT-STACCATO;Mn;220;NSM;;;;;N;;;;; +1D182;MUSICAL SYMBOL COMBINING LOURE;Mn;220;NSM;;;;;N;;;;; +1D183;MUSICAL SYMBOL ARPEGGIATO UP;So;0;L;;;;;N;;;;; +1D184;MUSICAL SYMBOL ARPEGGIATO DOWN;So;0;L;;;;;N;;;;; +1D185;MUSICAL SYMBOL COMBINING DOIT;Mn;230;NSM;;;;;N;;;;; +1D186;MUSICAL SYMBOL COMBINING RIP;Mn;230;NSM;;;;;N;;;;; +1D187;MUSICAL SYMBOL COMBINING FLIP;Mn;230;NSM;;;;;N;;;;; +1D188;MUSICAL SYMBOL COMBINING SMEAR;Mn;230;NSM;;;;;N;;;;; +1D189;MUSICAL SYMBOL COMBINING BEND;Mn;230;NSM;;;;;N;;;;; +1D18A;MUSICAL SYMBOL COMBINING DOUBLE TONGUE;Mn;220;NSM;;;;;N;;;;; +1D18B;MUSICAL SYMBOL COMBINING TRIPLE TONGUE;Mn;220;NSM;;;;;N;;;;; +1D18C;MUSICAL SYMBOL RINFORZANDO;So;0;L;;;;;N;;;;; +1D18D;MUSICAL SYMBOL SUBITO;So;0;L;;;;;N;;;;; +1D18E;MUSICAL SYMBOL Z;So;0;L;;;;;N;;;;; +1D18F;MUSICAL SYMBOL PIANO;So;0;L;;;;;N;;;;; +1D190;MUSICAL SYMBOL MEZZO;So;0;L;;;;;N;;;;; +1D191;MUSICAL SYMBOL FORTE;So;0;L;;;;;N;;;;; +1D192;MUSICAL SYMBOL CRESCENDO;So;0;L;;;;;N;;;;; +1D193;MUSICAL SYMBOL DECRESCENDO;So;0;L;;;;;N;;;;; +1D194;MUSICAL SYMBOL GRACE NOTE SLASH;So;0;L;;;;;N;;;;; +1D195;MUSICAL SYMBOL GRACE NOTE NO SLASH;So;0;L;;;;;N;;;;; +1D196;MUSICAL SYMBOL TR;So;0;L;;;;;N;;;;; +1D197;MUSICAL SYMBOL TURN;So;0;L;;;;;N;;;;; +1D198;MUSICAL SYMBOL INVERTED TURN;So;0;L;;;;;N;;;;; +1D199;MUSICAL SYMBOL TURN SLASH;So;0;L;;;;;N;;;;; +1D19A;MUSICAL SYMBOL TURN UP;So;0;L;;;;;N;;;;; +1D19B;MUSICAL SYMBOL ORNAMENT STROKE-1;So;0;L;;;;;N;;;;; +1D19C;MUSICAL SYMBOL ORNAMENT STROKE-2;So;0;L;;;;;N;;;;; +1D19D;MUSICAL SYMBOL ORNAMENT STROKE-3;So;0;L;;;;;N;;;;; +1D19E;MUSICAL SYMBOL ORNAMENT STROKE-4;So;0;L;;;;;N;;;;; +1D19F;MUSICAL SYMBOL ORNAMENT STROKE-5;So;0;L;;;;;N;;;;; +1D1A0;MUSICAL SYMBOL ORNAMENT STROKE-6;So;0;L;;;;;N;;;;; +1D1A1;MUSICAL SYMBOL ORNAMENT STROKE-7;So;0;L;;;;;N;;;;; +1D1A2;MUSICAL SYMBOL ORNAMENT STROKE-8;So;0;L;;;;;N;;;;; +1D1A3;MUSICAL SYMBOL ORNAMENT STROKE-9;So;0;L;;;;;N;;;;; +1D1A4;MUSICAL SYMBOL ORNAMENT STROKE-10;So;0;L;;;;;N;;;;; +1D1A5;MUSICAL SYMBOL ORNAMENT STROKE-11;So;0;L;;;;;N;;;;; +1D1A6;MUSICAL SYMBOL HAUPTSTIMME;So;0;L;;;;;N;;;;; +1D1A7;MUSICAL SYMBOL NEBENSTIMME;So;0;L;;;;;N;;;;; +1D1A8;MUSICAL SYMBOL END OF STIMME;So;0;L;;;;;N;;;;; +1D1A9;MUSICAL SYMBOL DEGREE SLASH;So;0;L;;;;;N;;;;; +1D1AA;MUSICAL SYMBOL COMBINING DOWN BOW;Mn;230;NSM;;;;;N;;;;; +1D1AB;MUSICAL SYMBOL COMBINING UP BOW;Mn;230;NSM;;;;;N;;;;; +1D1AC;MUSICAL SYMBOL COMBINING HARMONIC;Mn;230;NSM;;;;;N;;;;; +1D1AD;MUSICAL SYMBOL COMBINING SNAP PIZZICATO;Mn;230;NSM;;;;;N;;;;; +1D1AE;MUSICAL SYMBOL PEDAL MARK;So;0;L;;;;;N;;;;; +1D1AF;MUSICAL SYMBOL PEDAL UP MARK;So;0;L;;;;;N;;;;; +1D1B0;MUSICAL SYMBOL HALF PEDAL MARK;So;0;L;;;;;N;;;;; +1D1B1;MUSICAL SYMBOL GLISSANDO UP;So;0;L;;;;;N;;;;; +1D1B2;MUSICAL SYMBOL GLISSANDO DOWN;So;0;L;;;;;N;;;;; +1D1B3;MUSICAL SYMBOL WITH FINGERNAILS;So;0;L;;;;;N;;;;; +1D1B4;MUSICAL SYMBOL DAMP;So;0;L;;;;;N;;;;; +1D1B5;MUSICAL SYMBOL DAMP ALL;So;0;L;;;;;N;;;;; +1D1B6;MUSICAL SYMBOL MAXIMA;So;0;L;;;;;N;;;;; +1D1B7;MUSICAL SYMBOL LONGA;So;0;L;;;;;N;;;;; +1D1B8;MUSICAL SYMBOL BREVIS;So;0;L;;;;;N;;;;; +1D1B9;MUSICAL SYMBOL SEMIBREVIS WHITE;So;0;L;;;;;N;;;;; +1D1BA;MUSICAL SYMBOL SEMIBREVIS BLACK;So;0;L;;;;;N;;;;; +1D1BB;MUSICAL SYMBOL MINIMA;So;0;L;1D1B9 1D165;;;;N;;;;; +1D1BC;MUSICAL SYMBOL MINIMA BLACK;So;0;L;1D1BA 1D165;;;;N;;;;; +1D1BD;MUSICAL SYMBOL SEMIMINIMA WHITE;So;0;L;1D1BB 1D16E;;;;N;;;;; +1D1BE;MUSICAL SYMBOL SEMIMINIMA BLACK;So;0;L;1D1BC 1D16E;;;;N;;;;; +1D1BF;MUSICAL SYMBOL FUSA WHITE;So;0;L;1D1BB 1D16F;;;;N;;;;; +1D1C0;MUSICAL SYMBOL FUSA BLACK;So;0;L;1D1BC 1D16F;;;;N;;;;; +1D1C1;MUSICAL SYMBOL LONGA PERFECTA REST;So;0;L;;;;;N;;;;; +1D1C2;MUSICAL SYMBOL LONGA IMPERFECTA REST;So;0;L;;;;;N;;;;; +1D1C3;MUSICAL SYMBOL BREVIS REST;So;0;L;;;;;N;;;;; +1D1C4;MUSICAL SYMBOL SEMIBREVIS REST;So;0;L;;;;;N;;;;; +1D1C5;MUSICAL SYMBOL MINIMA REST;So;0;L;;;;;N;;;;; +1D1C6;MUSICAL SYMBOL SEMIMINIMA REST;So;0;L;;;;;N;;;;; +1D1C7;MUSICAL SYMBOL TEMPUS PERFECTUM CUM PROLATIONE PERFECTA;So;0;L;;;;;N;;;;; +1D1C8;MUSICAL SYMBOL TEMPUS PERFECTUM CUM PROLATIONE IMPERFECTA;So;0;L;;;;;N;;;;; +1D1C9;MUSICAL SYMBOL TEMPUS PERFECTUM CUM PROLATIONE PERFECTA DIMINUTION-1;So;0;L;;;;;N;;;;; +1D1CA;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE PERFECTA;So;0;L;;;;;N;;;;; +1D1CB;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE IMPERFECTA;So;0;L;;;;;N;;;;; +1D1CC;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE IMPERFECTA DIMINUTION-1;So;0;L;;;;;N;;;;; +1D1CD;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE IMPERFECTA DIMINUTION-2;So;0;L;;;;;N;;;;; +1D1CE;MUSICAL SYMBOL TEMPUS IMPERFECTUM CUM PROLATIONE IMPERFECTA DIMINUTION-3;So;0;L;;;;;N;;;;; +1D1CF;MUSICAL SYMBOL CROIX;So;0;L;;;;;N;;;;; +1D1D0;MUSICAL SYMBOL GREGORIAN C CLEF;So;0;L;;;;;N;;;;; +1D1D1;MUSICAL SYMBOL GREGORIAN F CLEF;So;0;L;;;;;N;;;;; +1D1D2;MUSICAL SYMBOL SQUARE B;So;0;L;;;;;N;;;;; +1D1D3;MUSICAL SYMBOL VIRGA;So;0;L;;;;;N;;;;; +1D1D4;MUSICAL SYMBOL PODATUS;So;0;L;;;;;N;;;;; +1D1D5;MUSICAL SYMBOL CLIVIS;So;0;L;;;;;N;;;;; +1D1D6;MUSICAL SYMBOL SCANDICUS;So;0;L;;;;;N;;;;; +1D1D7;MUSICAL SYMBOL CLIMACUS;So;0;L;;;;;N;;;;; +1D1D8;MUSICAL SYMBOL TORCULUS;So;0;L;;;;;N;;;;; +1D1D9;MUSICAL SYMBOL PORRECTUS;So;0;L;;;;;N;;;;; +1D1DA;MUSICAL SYMBOL PORRECTUS FLEXUS;So;0;L;;;;;N;;;;; +1D1DB;MUSICAL SYMBOL SCANDICUS FLEXUS;So;0;L;;;;;N;;;;; +1D1DC;MUSICAL SYMBOL TORCULUS RESUPINUS;So;0;L;;;;;N;;;;; +1D1DD;MUSICAL SYMBOL PES SUBPUNCTIS;So;0;L;;;;;N;;;;; +1D200;GREEK VOCAL NOTATION SYMBOL-1;So;0;ON;;;;;N;;;;; +1D201;GREEK VOCAL NOTATION SYMBOL-2;So;0;ON;;;;;N;;;;; +1D202;GREEK VOCAL NOTATION SYMBOL-3;So;0;ON;;;;;N;;;;; +1D203;GREEK VOCAL NOTATION SYMBOL-4;So;0;ON;;;;;N;;;;; +1D204;GREEK VOCAL NOTATION SYMBOL-5;So;0;ON;;;;;N;;;;; +1D205;GREEK VOCAL NOTATION SYMBOL-6;So;0;ON;;;;;N;;;;; +1D206;GREEK VOCAL NOTATION SYMBOL-7;So;0;ON;;;;;N;;;;; +1D207;GREEK VOCAL NOTATION SYMBOL-8;So;0;ON;;;;;N;;;;; +1D208;GREEK VOCAL NOTATION SYMBOL-9;So;0;ON;;;;;N;;;;; +1D209;GREEK VOCAL NOTATION SYMBOL-10;So;0;ON;;;;;N;;;;; +1D20A;GREEK VOCAL NOTATION SYMBOL-11;So;0;ON;;;;;N;;;;; +1D20B;GREEK VOCAL NOTATION SYMBOL-12;So;0;ON;;;;;N;;;;; +1D20C;GREEK VOCAL NOTATION SYMBOL-13;So;0;ON;;;;;N;;;;; +1D20D;GREEK VOCAL NOTATION SYMBOL-14;So;0;ON;;;;;N;;;;; +1D20E;GREEK VOCAL NOTATION SYMBOL-15;So;0;ON;;;;;N;;;;; +1D20F;GREEK VOCAL NOTATION SYMBOL-16;So;0;ON;;;;;N;;;;; +1D210;GREEK VOCAL NOTATION SYMBOL-17;So;0;ON;;;;;N;;;;; +1D211;GREEK VOCAL NOTATION SYMBOL-18;So;0;ON;;;;;N;;;;; +1D212;GREEK VOCAL NOTATION SYMBOL-19;So;0;ON;;;;;N;;;;; +1D213;GREEK VOCAL NOTATION SYMBOL-20;So;0;ON;;;;;N;;;;; +1D214;GREEK VOCAL NOTATION SYMBOL-21;So;0;ON;;;;;N;;;;; +1D215;GREEK VOCAL NOTATION SYMBOL-22;So;0;ON;;;;;N;;;;; +1D216;GREEK VOCAL NOTATION SYMBOL-23;So;0;ON;;;;;N;;;;; +1D217;GREEK VOCAL NOTATION SYMBOL-24;So;0;ON;;;;;N;;;;; +1D218;GREEK VOCAL NOTATION SYMBOL-50;So;0;ON;;;;;N;;;;; +1D219;GREEK VOCAL NOTATION SYMBOL-51;So;0;ON;;;;;N;;;;; +1D21A;GREEK VOCAL NOTATION SYMBOL-52;So;0;ON;;;;;N;;;;; +1D21B;GREEK VOCAL NOTATION SYMBOL-53;So;0;ON;;;;;N;;;;; +1D21C;GREEK VOCAL NOTATION SYMBOL-54;So;0;ON;;;;;N;;;;; +1D21D;GREEK INSTRUMENTAL NOTATION SYMBOL-1;So;0;ON;;;;;N;;;;; +1D21E;GREEK INSTRUMENTAL NOTATION SYMBOL-2;So;0;ON;;;;;N;;;;; +1D21F;GREEK INSTRUMENTAL NOTATION SYMBOL-4;So;0;ON;;;;;N;;;;; +1D220;GREEK INSTRUMENTAL NOTATION SYMBOL-5;So;0;ON;;;;;N;;;;; +1D221;GREEK INSTRUMENTAL NOTATION SYMBOL-7;So;0;ON;;;;;N;;;;; +1D222;GREEK INSTRUMENTAL NOTATION SYMBOL-8;So;0;ON;;;;;N;;;;; +1D223;GREEK INSTRUMENTAL NOTATION SYMBOL-11;So;0;ON;;;;;N;;;;; +1D224;GREEK INSTRUMENTAL NOTATION SYMBOL-12;So;0;ON;;;;;N;;;;; +1D225;GREEK INSTRUMENTAL NOTATION SYMBOL-13;So;0;ON;;;;;N;;;;; +1D226;GREEK INSTRUMENTAL NOTATION SYMBOL-14;So;0;ON;;;;;N;;;;; +1D227;GREEK INSTRUMENTAL NOTATION SYMBOL-17;So;0;ON;;;;;N;;;;; +1D228;GREEK INSTRUMENTAL NOTATION SYMBOL-18;So;0;ON;;;;;N;;;;; +1D229;GREEK INSTRUMENTAL NOTATION SYMBOL-19;So;0;ON;;;;;N;;;;; +1D22A;GREEK INSTRUMENTAL NOTATION SYMBOL-23;So;0;ON;;;;;N;;;;; +1D22B;GREEK INSTRUMENTAL NOTATION SYMBOL-24;So;0;ON;;;;;N;;;;; +1D22C;GREEK INSTRUMENTAL NOTATION SYMBOL-25;So;0;ON;;;;;N;;;;; +1D22D;GREEK INSTRUMENTAL NOTATION SYMBOL-26;So;0;ON;;;;;N;;;;; +1D22E;GREEK INSTRUMENTAL NOTATION SYMBOL-27;So;0;ON;;;;;N;;;;; +1D22F;GREEK INSTRUMENTAL NOTATION SYMBOL-29;So;0;ON;;;;;N;;;;; +1D230;GREEK INSTRUMENTAL NOTATION SYMBOL-30;So;0;ON;;;;;N;;;;; +1D231;GREEK INSTRUMENTAL NOTATION SYMBOL-32;So;0;ON;;;;;N;;;;; +1D232;GREEK INSTRUMENTAL NOTATION SYMBOL-36;So;0;ON;;;;;N;;;;; +1D233;GREEK INSTRUMENTAL NOTATION SYMBOL-37;So;0;ON;;;;;N;;;;; +1D234;GREEK INSTRUMENTAL NOTATION SYMBOL-38;So;0;ON;;;;;N;;;;; +1D235;GREEK INSTRUMENTAL NOTATION SYMBOL-39;So;0;ON;;;;;N;;;;; +1D236;GREEK INSTRUMENTAL NOTATION SYMBOL-40;So;0;ON;;;;;N;;;;; +1D237;GREEK INSTRUMENTAL NOTATION SYMBOL-42;So;0;ON;;;;;N;;;;; +1D238;GREEK INSTRUMENTAL NOTATION SYMBOL-43;So;0;ON;;;;;N;;;;; +1D239;GREEK INSTRUMENTAL NOTATION SYMBOL-45;So;0;ON;;;;;N;;;;; +1D23A;GREEK INSTRUMENTAL NOTATION SYMBOL-47;So;0;ON;;;;;N;;;;; +1D23B;GREEK INSTRUMENTAL NOTATION SYMBOL-48;So;0;ON;;;;;N;;;;; +1D23C;GREEK INSTRUMENTAL NOTATION SYMBOL-49;So;0;ON;;;;;N;;;;; +1D23D;GREEK INSTRUMENTAL NOTATION SYMBOL-50;So;0;ON;;;;;N;;;;; +1D23E;GREEK INSTRUMENTAL NOTATION SYMBOL-51;So;0;ON;;;;;N;;;;; +1D23F;GREEK INSTRUMENTAL NOTATION SYMBOL-52;So;0;ON;;;;;N;;;;; +1D240;GREEK INSTRUMENTAL NOTATION SYMBOL-53;So;0;ON;;;;;N;;;;; +1D241;GREEK INSTRUMENTAL NOTATION SYMBOL-54;So;0;ON;;;;;N;;;;; +1D242;COMBINING GREEK MUSICAL TRISEME;Mn;230;NSM;;;;;N;;;;; +1D243;COMBINING GREEK MUSICAL TETRASEME;Mn;230;NSM;;;;;N;;;;; +1D244;COMBINING GREEK MUSICAL PENTASEME;Mn;230;NSM;;;;;N;;;;; +1D245;GREEK MUSICAL LEIMMA;So;0;ON;;;;;N;;;;; +1D300;MONOGRAM FOR EARTH;So;0;ON;;;;;N;;;;; +1D301;DIGRAM FOR HEAVENLY EARTH;So;0;ON;;;;;N;;;;; +1D302;DIGRAM FOR HUMAN EARTH;So;0;ON;;;;;N;;;;; +1D303;DIGRAM FOR EARTHLY HEAVEN;So;0;ON;;;;;N;;;;; +1D304;DIGRAM FOR EARTHLY HUMAN;So;0;ON;;;;;N;;;;; +1D305;DIGRAM FOR EARTH;So;0;ON;;;;;N;;;;; +1D306;TETRAGRAM FOR CENTRE;So;0;ON;;;;;N;;;;; +1D307;TETRAGRAM FOR FULL CIRCLE;So;0;ON;;;;;N;;;;; +1D308;TETRAGRAM FOR MIRED;So;0;ON;;;;;N;;;;; +1D309;TETRAGRAM FOR BARRIER;So;0;ON;;;;;N;;;;; +1D30A;TETRAGRAM FOR KEEPING SMALL;So;0;ON;;;;;N;;;;; +1D30B;TETRAGRAM FOR CONTRARIETY;So;0;ON;;;;;N;;;;; +1D30C;TETRAGRAM FOR ASCENT;So;0;ON;;;;;N;;;;; +1D30D;TETRAGRAM FOR OPPOSITION;So;0;ON;;;;;N;;;;; +1D30E;TETRAGRAM FOR BRANCHING OUT;So;0;ON;;;;;N;;;;; +1D30F;TETRAGRAM FOR DEFECTIVENESS OR DISTORTION;So;0;ON;;;;;N;;;;; +1D310;TETRAGRAM FOR DIVERGENCE;So;0;ON;;;;;N;;;;; +1D311;TETRAGRAM FOR YOUTHFULNESS;So;0;ON;;;;;N;;;;; +1D312;TETRAGRAM FOR INCREASE;So;0;ON;;;;;N;;;;; +1D313;TETRAGRAM FOR PENETRATION;So;0;ON;;;;;N;;;;; +1D314;TETRAGRAM FOR REACH;So;0;ON;;;;;N;;;;; +1D315;TETRAGRAM FOR CONTACT;So;0;ON;;;;;N;;;;; +1D316;TETRAGRAM FOR HOLDING BACK;So;0;ON;;;;;N;;;;; +1D317;TETRAGRAM FOR WAITING;So;0;ON;;;;;N;;;;; +1D318;TETRAGRAM FOR FOLLOWING;So;0;ON;;;;;N;;;;; +1D319;TETRAGRAM FOR ADVANCE;So;0;ON;;;;;N;;;;; +1D31A;TETRAGRAM FOR RELEASE;So;0;ON;;;;;N;;;;; +1D31B;TETRAGRAM FOR RESISTANCE;So;0;ON;;;;;N;;;;; +1D31C;TETRAGRAM FOR EASE;So;0;ON;;;;;N;;;;; +1D31D;TETRAGRAM FOR JOY;So;0;ON;;;;;N;;;;; +1D31E;TETRAGRAM FOR CONTENTION;So;0;ON;;;;;N;;;;; +1D31F;TETRAGRAM FOR ENDEAVOUR;So;0;ON;;;;;N;;;;; +1D320;TETRAGRAM FOR DUTIES;So;0;ON;;;;;N;;;;; +1D321;TETRAGRAM FOR CHANGE;So;0;ON;;;;;N;;;;; +1D322;TETRAGRAM FOR DECISIVENESS;So;0;ON;;;;;N;;;;; +1D323;TETRAGRAM FOR BOLD RESOLUTION;So;0;ON;;;;;N;;;;; +1D324;TETRAGRAM FOR PACKING;So;0;ON;;;;;N;;;;; +1D325;TETRAGRAM FOR LEGION;So;0;ON;;;;;N;;;;; +1D326;TETRAGRAM FOR CLOSENESS;So;0;ON;;;;;N;;;;; +1D327;TETRAGRAM FOR KINSHIP;So;0;ON;;;;;N;;;;; +1D328;TETRAGRAM FOR GATHERING;So;0;ON;;;;;N;;;;; +1D329;TETRAGRAM FOR STRENGTH;So;0;ON;;;;;N;;;;; +1D32A;TETRAGRAM FOR PURITY;So;0;ON;;;;;N;;;;; +1D32B;TETRAGRAM FOR FULLNESS;So;0;ON;;;;;N;;;;; +1D32C;TETRAGRAM FOR RESIDENCE;So;0;ON;;;;;N;;;;; +1D32D;TETRAGRAM FOR LAW OR MODEL;So;0;ON;;;;;N;;;;; +1D32E;TETRAGRAM FOR RESPONSE;So;0;ON;;;;;N;;;;; +1D32F;TETRAGRAM FOR GOING TO MEET;So;0;ON;;;;;N;;;;; +1D330;TETRAGRAM FOR ENCOUNTERS;So;0;ON;;;;;N;;;;; +1D331;TETRAGRAM FOR STOVE;So;0;ON;;;;;N;;;;; +1D332;TETRAGRAM FOR GREATNESS;So;0;ON;;;;;N;;;;; +1D333;TETRAGRAM FOR ENLARGEMENT;So;0;ON;;;;;N;;;;; +1D334;TETRAGRAM FOR PATTERN;So;0;ON;;;;;N;;;;; +1D335;TETRAGRAM FOR RITUAL;So;0;ON;;;;;N;;;;; +1D336;TETRAGRAM FOR FLIGHT;So;0;ON;;;;;N;;;;; +1D337;TETRAGRAM FOR VASTNESS OR WASTING;So;0;ON;;;;;N;;;;; +1D338;TETRAGRAM FOR CONSTANCY;So;0;ON;;;;;N;;;;; +1D339;TETRAGRAM FOR MEASURE;So;0;ON;;;;;N;;;;; +1D33A;TETRAGRAM FOR ETERNITY;So;0;ON;;;;;N;;;;; +1D33B;TETRAGRAM FOR UNITY;So;0;ON;;;;;N;;;;; +1D33C;TETRAGRAM FOR DIMINISHMENT;So;0;ON;;;;;N;;;;; +1D33D;TETRAGRAM FOR CLOSED MOUTH;So;0;ON;;;;;N;;;;; +1D33E;TETRAGRAM FOR GUARDEDNESS;So;0;ON;;;;;N;;;;; +1D33F;TETRAGRAM FOR GATHERING IN;So;0;ON;;;;;N;;;;; +1D340;TETRAGRAM FOR MASSING;So;0;ON;;;;;N;;;;; +1D341;TETRAGRAM FOR ACCUMULATION;So;0;ON;;;;;N;;;;; +1D342;TETRAGRAM FOR EMBELLISHMENT;So;0;ON;;;;;N;;;;; +1D343;TETRAGRAM FOR DOUBT;So;0;ON;;;;;N;;;;; +1D344;TETRAGRAM FOR WATCH;So;0;ON;;;;;N;;;;; +1D345;TETRAGRAM FOR SINKING;So;0;ON;;;;;N;;;;; +1D346;TETRAGRAM FOR INNER;So;0;ON;;;;;N;;;;; +1D347;TETRAGRAM FOR DEPARTURE;So;0;ON;;;;;N;;;;; +1D348;TETRAGRAM FOR DARKENING;So;0;ON;;;;;N;;;;; +1D349;TETRAGRAM FOR DIMMING;So;0;ON;;;;;N;;;;; +1D34A;TETRAGRAM FOR EXHAUSTION;So;0;ON;;;;;N;;;;; +1D34B;TETRAGRAM FOR SEVERANCE;So;0;ON;;;;;N;;;;; +1D34C;TETRAGRAM FOR STOPPAGE;So;0;ON;;;;;N;;;;; +1D34D;TETRAGRAM FOR HARDNESS;So;0;ON;;;;;N;;;;; +1D34E;TETRAGRAM FOR COMPLETION;So;0;ON;;;;;N;;;;; +1D34F;TETRAGRAM FOR CLOSURE;So;0;ON;;;;;N;;;;; +1D350;TETRAGRAM FOR FAILURE;So;0;ON;;;;;N;;;;; +1D351;TETRAGRAM FOR AGGRAVATION;So;0;ON;;;;;N;;;;; +1D352;TETRAGRAM FOR COMPLIANCE;So;0;ON;;;;;N;;;;; +1D353;TETRAGRAM FOR ON THE VERGE;So;0;ON;;;;;N;;;;; +1D354;TETRAGRAM FOR DIFFICULTIES;So;0;ON;;;;;N;;;;; +1D355;TETRAGRAM FOR LABOURING;So;0;ON;;;;;N;;;;; +1D356;TETRAGRAM FOR FOSTERING;So;0;ON;;;;;N;;;;; +1D360;COUNTING ROD UNIT DIGIT ONE;No;0;L;;;;1;N;;;;; +1D361;COUNTING ROD UNIT DIGIT TWO;No;0;L;;;;2;N;;;;; +1D362;COUNTING ROD UNIT DIGIT THREE;No;0;L;;;;3;N;;;;; +1D363;COUNTING ROD UNIT DIGIT FOUR;No;0;L;;;;4;N;;;;; +1D364;COUNTING ROD UNIT DIGIT FIVE;No;0;L;;;;5;N;;;;; +1D365;COUNTING ROD UNIT DIGIT SIX;No;0;L;;;;6;N;;;;; +1D366;COUNTING ROD UNIT DIGIT SEVEN;No;0;L;;;;7;N;;;;; +1D367;COUNTING ROD UNIT DIGIT EIGHT;No;0;L;;;;8;N;;;;; +1D368;COUNTING ROD UNIT DIGIT NINE;No;0;L;;;;9;N;;;;; +1D369;COUNTING ROD TENS DIGIT ONE;No;0;L;;;;10;N;;;;; +1D36A;COUNTING ROD TENS DIGIT TWO;No;0;L;;;;20;N;;;;; +1D36B;COUNTING ROD TENS DIGIT THREE;No;0;L;;;;30;N;;;;; +1D36C;COUNTING ROD TENS DIGIT FOUR;No;0;L;;;;40;N;;;;; +1D36D;COUNTING ROD TENS DIGIT FIVE;No;0;L;;;;50;N;;;;; +1D36E;COUNTING ROD TENS DIGIT SIX;No;0;L;;;;60;N;;;;; +1D36F;COUNTING ROD TENS DIGIT SEVEN;No;0;L;;;;70;N;;;;; +1D370;COUNTING ROD TENS DIGIT EIGHT;No;0;L;;;;80;N;;;;; +1D371;COUNTING ROD TENS DIGIT NINE;No;0;L;;;;90;N;;;;; +1D400;MATHEMATICAL BOLD CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D401;MATHEMATICAL BOLD CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D402;MATHEMATICAL BOLD CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D403;MATHEMATICAL BOLD CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D404;MATHEMATICAL BOLD CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D405;MATHEMATICAL BOLD CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D406;MATHEMATICAL BOLD CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D407;MATHEMATICAL BOLD CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D408;MATHEMATICAL BOLD CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D409;MATHEMATICAL BOLD CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D40A;MATHEMATICAL BOLD CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D40B;MATHEMATICAL BOLD CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D40C;MATHEMATICAL BOLD CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D40D;MATHEMATICAL BOLD CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D40E;MATHEMATICAL BOLD CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D40F;MATHEMATICAL BOLD CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D410;MATHEMATICAL BOLD CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D411;MATHEMATICAL BOLD CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D412;MATHEMATICAL BOLD CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D413;MATHEMATICAL BOLD CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D414;MATHEMATICAL BOLD CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D415;MATHEMATICAL BOLD CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D416;MATHEMATICAL BOLD CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D417;MATHEMATICAL BOLD CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D418;MATHEMATICAL BOLD CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D419;MATHEMATICAL BOLD CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D41A;MATHEMATICAL BOLD SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D41B;MATHEMATICAL BOLD SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D41C;MATHEMATICAL BOLD SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D41D;MATHEMATICAL BOLD SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D41E;MATHEMATICAL BOLD SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D41F;MATHEMATICAL BOLD SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D420;MATHEMATICAL BOLD SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D421;MATHEMATICAL BOLD SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D422;MATHEMATICAL BOLD SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D423;MATHEMATICAL BOLD SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D424;MATHEMATICAL BOLD SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D425;MATHEMATICAL BOLD SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D426;MATHEMATICAL BOLD SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D427;MATHEMATICAL BOLD SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D428;MATHEMATICAL BOLD SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D429;MATHEMATICAL BOLD SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D42A;MATHEMATICAL BOLD SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D42B;MATHEMATICAL BOLD SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D42C;MATHEMATICAL BOLD SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D42D;MATHEMATICAL BOLD SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D42E;MATHEMATICAL BOLD SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D42F;MATHEMATICAL BOLD SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D430;MATHEMATICAL BOLD SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D431;MATHEMATICAL BOLD SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D432;MATHEMATICAL BOLD SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D433;MATHEMATICAL BOLD SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D434;MATHEMATICAL ITALIC CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D435;MATHEMATICAL ITALIC CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D436;MATHEMATICAL ITALIC CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D437;MATHEMATICAL ITALIC CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D438;MATHEMATICAL ITALIC CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D439;MATHEMATICAL ITALIC CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D43A;MATHEMATICAL ITALIC CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D43B;MATHEMATICAL ITALIC CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D43C;MATHEMATICAL ITALIC CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D43D;MATHEMATICAL ITALIC CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D43E;MATHEMATICAL ITALIC CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D43F;MATHEMATICAL ITALIC CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D440;MATHEMATICAL ITALIC CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D441;MATHEMATICAL ITALIC CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D442;MATHEMATICAL ITALIC CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D443;MATHEMATICAL ITALIC CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D444;MATHEMATICAL ITALIC CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D445;MATHEMATICAL ITALIC CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D446;MATHEMATICAL ITALIC CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D447;MATHEMATICAL ITALIC CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D448;MATHEMATICAL ITALIC CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D449;MATHEMATICAL ITALIC CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D44A;MATHEMATICAL ITALIC CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D44B;MATHEMATICAL ITALIC CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D44C;MATHEMATICAL ITALIC CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D44D;MATHEMATICAL ITALIC CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D44E;MATHEMATICAL ITALIC SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D44F;MATHEMATICAL ITALIC SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D450;MATHEMATICAL ITALIC SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D451;MATHEMATICAL ITALIC SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D452;MATHEMATICAL ITALIC SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D453;MATHEMATICAL ITALIC SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D454;MATHEMATICAL ITALIC SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D456;MATHEMATICAL ITALIC SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D457;MATHEMATICAL ITALIC SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D458;MATHEMATICAL ITALIC SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D459;MATHEMATICAL ITALIC SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D45A;MATHEMATICAL ITALIC SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D45B;MATHEMATICAL ITALIC SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D45C;MATHEMATICAL ITALIC SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D45D;MATHEMATICAL ITALIC SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D45E;MATHEMATICAL ITALIC SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D45F;MATHEMATICAL ITALIC SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D460;MATHEMATICAL ITALIC SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D461;MATHEMATICAL ITALIC SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D462;MATHEMATICAL ITALIC SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D463;MATHEMATICAL ITALIC SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D464;MATHEMATICAL ITALIC SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D465;MATHEMATICAL ITALIC SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D466;MATHEMATICAL ITALIC SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D467;MATHEMATICAL ITALIC SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D468;MATHEMATICAL BOLD ITALIC CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D469;MATHEMATICAL BOLD ITALIC CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D46A;MATHEMATICAL BOLD ITALIC CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D46B;MATHEMATICAL BOLD ITALIC CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D46C;MATHEMATICAL BOLD ITALIC CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D46D;MATHEMATICAL BOLD ITALIC CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D46E;MATHEMATICAL BOLD ITALIC CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D46F;MATHEMATICAL BOLD ITALIC CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D470;MATHEMATICAL BOLD ITALIC CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D471;MATHEMATICAL BOLD ITALIC CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D472;MATHEMATICAL BOLD ITALIC CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D473;MATHEMATICAL BOLD ITALIC CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D474;MATHEMATICAL BOLD ITALIC CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D475;MATHEMATICAL BOLD ITALIC CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D476;MATHEMATICAL BOLD ITALIC CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D477;MATHEMATICAL BOLD ITALIC CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D478;MATHEMATICAL BOLD ITALIC CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D479;MATHEMATICAL BOLD ITALIC CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D47A;MATHEMATICAL BOLD ITALIC CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D47B;MATHEMATICAL BOLD ITALIC CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D47C;MATHEMATICAL BOLD ITALIC CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D47D;MATHEMATICAL BOLD ITALIC CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D47E;MATHEMATICAL BOLD ITALIC CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D47F;MATHEMATICAL BOLD ITALIC CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D480;MATHEMATICAL BOLD ITALIC CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D481;MATHEMATICAL BOLD ITALIC CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D482;MATHEMATICAL BOLD ITALIC SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D483;MATHEMATICAL BOLD ITALIC SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D484;MATHEMATICAL BOLD ITALIC SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D485;MATHEMATICAL BOLD ITALIC SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D486;MATHEMATICAL BOLD ITALIC SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D487;MATHEMATICAL BOLD ITALIC SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D488;MATHEMATICAL BOLD ITALIC SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D489;MATHEMATICAL BOLD ITALIC SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D48A;MATHEMATICAL BOLD ITALIC SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D48B;MATHEMATICAL BOLD ITALIC SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D48C;MATHEMATICAL BOLD ITALIC SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D48D;MATHEMATICAL BOLD ITALIC SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D48E;MATHEMATICAL BOLD ITALIC SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D48F;MATHEMATICAL BOLD ITALIC SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D490;MATHEMATICAL BOLD ITALIC SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D491;MATHEMATICAL BOLD ITALIC SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D492;MATHEMATICAL BOLD ITALIC SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D493;MATHEMATICAL BOLD ITALIC SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D494;MATHEMATICAL BOLD ITALIC SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D495;MATHEMATICAL BOLD ITALIC SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D496;MATHEMATICAL BOLD ITALIC SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D497;MATHEMATICAL BOLD ITALIC SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D498;MATHEMATICAL BOLD ITALIC SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D499;MATHEMATICAL BOLD ITALIC SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D49A;MATHEMATICAL BOLD ITALIC SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D49B;MATHEMATICAL BOLD ITALIC SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D49C;MATHEMATICAL SCRIPT CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D49E;MATHEMATICAL SCRIPT CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D49F;MATHEMATICAL SCRIPT CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D4A2;MATHEMATICAL SCRIPT CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D4A5;MATHEMATICAL SCRIPT CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D4A6;MATHEMATICAL SCRIPT CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D4A9;MATHEMATICAL SCRIPT CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D4AA;MATHEMATICAL SCRIPT CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D4AB;MATHEMATICAL SCRIPT CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D4AC;MATHEMATICAL SCRIPT CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D4AE;MATHEMATICAL SCRIPT CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D4AF;MATHEMATICAL SCRIPT CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D4B0;MATHEMATICAL SCRIPT CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D4B1;MATHEMATICAL SCRIPT CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D4B2;MATHEMATICAL SCRIPT CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D4B3;MATHEMATICAL SCRIPT CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D4B4;MATHEMATICAL SCRIPT CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D4B5;MATHEMATICAL SCRIPT CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D4B6;MATHEMATICAL SCRIPT SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D4B7;MATHEMATICAL SCRIPT SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D4B8;MATHEMATICAL SCRIPT SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D4B9;MATHEMATICAL SCRIPT SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D4BB;MATHEMATICAL SCRIPT SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D4BD;MATHEMATICAL SCRIPT SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D4BE;MATHEMATICAL SCRIPT SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D4BF;MATHEMATICAL SCRIPT SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D4C0;MATHEMATICAL SCRIPT SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D4C1;MATHEMATICAL SCRIPT SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D4C2;MATHEMATICAL SCRIPT SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D4C3;MATHEMATICAL SCRIPT SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D4C5;MATHEMATICAL SCRIPT SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D4C6;MATHEMATICAL SCRIPT SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D4C7;MATHEMATICAL SCRIPT SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D4C8;MATHEMATICAL SCRIPT SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D4C9;MATHEMATICAL SCRIPT SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D4CA;MATHEMATICAL SCRIPT SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D4CB;MATHEMATICAL SCRIPT SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D4CC;MATHEMATICAL SCRIPT SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D4CD;MATHEMATICAL SCRIPT SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D4CE;MATHEMATICAL SCRIPT SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D4CF;MATHEMATICAL SCRIPT SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D4D0;MATHEMATICAL BOLD SCRIPT CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D4D1;MATHEMATICAL BOLD SCRIPT CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D4D2;MATHEMATICAL BOLD SCRIPT CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D4D3;MATHEMATICAL BOLD SCRIPT CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D4D4;MATHEMATICAL BOLD SCRIPT CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D4D5;MATHEMATICAL BOLD SCRIPT CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D4D6;MATHEMATICAL BOLD SCRIPT CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D4D7;MATHEMATICAL BOLD SCRIPT CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D4D8;MATHEMATICAL BOLD SCRIPT CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D4D9;MATHEMATICAL BOLD SCRIPT CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D4DA;MATHEMATICAL BOLD SCRIPT CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D4DB;MATHEMATICAL BOLD SCRIPT CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D4DC;MATHEMATICAL BOLD SCRIPT CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D4DD;MATHEMATICAL BOLD SCRIPT CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D4DE;MATHEMATICAL BOLD SCRIPT CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D4DF;MATHEMATICAL BOLD SCRIPT CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D4E0;MATHEMATICAL BOLD SCRIPT CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D4E1;MATHEMATICAL BOLD SCRIPT CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D4E2;MATHEMATICAL BOLD SCRIPT CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D4E3;MATHEMATICAL BOLD SCRIPT CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D4E4;MATHEMATICAL BOLD SCRIPT CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D4E5;MATHEMATICAL BOLD SCRIPT CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D4E6;MATHEMATICAL BOLD SCRIPT CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D4E7;MATHEMATICAL BOLD SCRIPT CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D4E8;MATHEMATICAL BOLD SCRIPT CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D4E9;MATHEMATICAL BOLD SCRIPT CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D4EA;MATHEMATICAL BOLD SCRIPT SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D4EB;MATHEMATICAL BOLD SCRIPT SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D4EC;MATHEMATICAL BOLD SCRIPT SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D4ED;MATHEMATICAL BOLD SCRIPT SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D4EE;MATHEMATICAL BOLD SCRIPT SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D4EF;MATHEMATICAL BOLD SCRIPT SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D4F0;MATHEMATICAL BOLD SCRIPT SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D4F1;MATHEMATICAL BOLD SCRIPT SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D4F2;MATHEMATICAL BOLD SCRIPT SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D4F3;MATHEMATICAL BOLD SCRIPT SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D4F4;MATHEMATICAL BOLD SCRIPT SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D4F5;MATHEMATICAL BOLD SCRIPT SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D4F6;MATHEMATICAL BOLD SCRIPT SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D4F7;MATHEMATICAL BOLD SCRIPT SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D4F8;MATHEMATICAL BOLD SCRIPT SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D4F9;MATHEMATICAL BOLD SCRIPT SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D4FA;MATHEMATICAL BOLD SCRIPT SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D4FB;MATHEMATICAL BOLD SCRIPT SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D4FC;MATHEMATICAL BOLD SCRIPT SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D4FD;MATHEMATICAL BOLD SCRIPT SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D4FE;MATHEMATICAL BOLD SCRIPT SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D4FF;MATHEMATICAL BOLD SCRIPT SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D500;MATHEMATICAL BOLD SCRIPT SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D501;MATHEMATICAL BOLD SCRIPT SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D502;MATHEMATICAL BOLD SCRIPT SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D503;MATHEMATICAL BOLD SCRIPT SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D504;MATHEMATICAL FRAKTUR CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D505;MATHEMATICAL FRAKTUR CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D507;MATHEMATICAL FRAKTUR CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D508;MATHEMATICAL FRAKTUR CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D509;MATHEMATICAL FRAKTUR CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D50A;MATHEMATICAL FRAKTUR CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D50D;MATHEMATICAL FRAKTUR CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D50E;MATHEMATICAL FRAKTUR CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D50F;MATHEMATICAL FRAKTUR CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D510;MATHEMATICAL FRAKTUR CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D511;MATHEMATICAL FRAKTUR CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D512;MATHEMATICAL FRAKTUR CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D513;MATHEMATICAL FRAKTUR CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D514;MATHEMATICAL FRAKTUR CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D516;MATHEMATICAL FRAKTUR CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D517;MATHEMATICAL FRAKTUR CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D518;MATHEMATICAL FRAKTUR CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D519;MATHEMATICAL FRAKTUR CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D51A;MATHEMATICAL FRAKTUR CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D51B;MATHEMATICAL FRAKTUR CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D51C;MATHEMATICAL FRAKTUR CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D51E;MATHEMATICAL FRAKTUR SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D51F;MATHEMATICAL FRAKTUR SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D520;MATHEMATICAL FRAKTUR SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D521;MATHEMATICAL FRAKTUR SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D522;MATHEMATICAL FRAKTUR SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D523;MATHEMATICAL FRAKTUR SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D524;MATHEMATICAL FRAKTUR SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D525;MATHEMATICAL FRAKTUR SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D526;MATHEMATICAL FRAKTUR SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D527;MATHEMATICAL FRAKTUR SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D528;MATHEMATICAL FRAKTUR SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D529;MATHEMATICAL FRAKTUR SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D52A;MATHEMATICAL FRAKTUR SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D52B;MATHEMATICAL FRAKTUR SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D52C;MATHEMATICAL FRAKTUR SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D52D;MATHEMATICAL FRAKTUR SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D52E;MATHEMATICAL FRAKTUR SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D52F;MATHEMATICAL FRAKTUR SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D530;MATHEMATICAL FRAKTUR SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D531;MATHEMATICAL FRAKTUR SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D532;MATHEMATICAL FRAKTUR SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D533;MATHEMATICAL FRAKTUR SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D534;MATHEMATICAL FRAKTUR SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D535;MATHEMATICAL FRAKTUR SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D536;MATHEMATICAL FRAKTUR SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D537;MATHEMATICAL FRAKTUR SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D538;MATHEMATICAL DOUBLE-STRUCK CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D539;MATHEMATICAL DOUBLE-STRUCK CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D53B;MATHEMATICAL DOUBLE-STRUCK CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D53C;MATHEMATICAL DOUBLE-STRUCK CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D53D;MATHEMATICAL DOUBLE-STRUCK CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D53E;MATHEMATICAL DOUBLE-STRUCK CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D540;MATHEMATICAL DOUBLE-STRUCK CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D541;MATHEMATICAL DOUBLE-STRUCK CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D542;MATHEMATICAL DOUBLE-STRUCK CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D543;MATHEMATICAL DOUBLE-STRUCK CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D544;MATHEMATICAL DOUBLE-STRUCK CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D546;MATHEMATICAL DOUBLE-STRUCK CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D54A;MATHEMATICAL DOUBLE-STRUCK CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D54B;MATHEMATICAL DOUBLE-STRUCK CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D54C;MATHEMATICAL DOUBLE-STRUCK CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D54D;MATHEMATICAL DOUBLE-STRUCK CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D54E;MATHEMATICAL DOUBLE-STRUCK CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D54F;MATHEMATICAL DOUBLE-STRUCK CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D550;MATHEMATICAL DOUBLE-STRUCK CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D552;MATHEMATICAL DOUBLE-STRUCK SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D553;MATHEMATICAL DOUBLE-STRUCK SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D554;MATHEMATICAL DOUBLE-STRUCK SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D555;MATHEMATICAL DOUBLE-STRUCK SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D556;MATHEMATICAL DOUBLE-STRUCK SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D557;MATHEMATICAL DOUBLE-STRUCK SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D558;MATHEMATICAL DOUBLE-STRUCK SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D559;MATHEMATICAL DOUBLE-STRUCK SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D55A;MATHEMATICAL DOUBLE-STRUCK SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D55B;MATHEMATICAL DOUBLE-STRUCK SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D55C;MATHEMATICAL DOUBLE-STRUCK SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D55D;MATHEMATICAL DOUBLE-STRUCK SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D55E;MATHEMATICAL DOUBLE-STRUCK SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D55F;MATHEMATICAL DOUBLE-STRUCK SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D560;MATHEMATICAL DOUBLE-STRUCK SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D561;MATHEMATICAL DOUBLE-STRUCK SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D562;MATHEMATICAL DOUBLE-STRUCK SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D563;MATHEMATICAL DOUBLE-STRUCK SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D564;MATHEMATICAL DOUBLE-STRUCK SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D565;MATHEMATICAL DOUBLE-STRUCK SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D566;MATHEMATICAL DOUBLE-STRUCK SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D567;MATHEMATICAL DOUBLE-STRUCK SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D568;MATHEMATICAL DOUBLE-STRUCK SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D569;MATHEMATICAL DOUBLE-STRUCK SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D56A;MATHEMATICAL DOUBLE-STRUCK SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D56B;MATHEMATICAL DOUBLE-STRUCK SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D56C;MATHEMATICAL BOLD FRAKTUR CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D56D;MATHEMATICAL BOLD FRAKTUR CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D56E;MATHEMATICAL BOLD FRAKTUR CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D56F;MATHEMATICAL BOLD FRAKTUR CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D570;MATHEMATICAL BOLD FRAKTUR CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D571;MATHEMATICAL BOLD FRAKTUR CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D572;MATHEMATICAL BOLD FRAKTUR CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D573;MATHEMATICAL BOLD FRAKTUR CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D574;MATHEMATICAL BOLD FRAKTUR CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D575;MATHEMATICAL BOLD FRAKTUR CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D576;MATHEMATICAL BOLD FRAKTUR CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D577;MATHEMATICAL BOLD FRAKTUR CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D578;MATHEMATICAL BOLD FRAKTUR CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D579;MATHEMATICAL BOLD FRAKTUR CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D57A;MATHEMATICAL BOLD FRAKTUR CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D57B;MATHEMATICAL BOLD FRAKTUR CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D57C;MATHEMATICAL BOLD FRAKTUR CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D57D;MATHEMATICAL BOLD FRAKTUR CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D57E;MATHEMATICAL BOLD FRAKTUR CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D57F;MATHEMATICAL BOLD FRAKTUR CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D580;MATHEMATICAL BOLD FRAKTUR CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D581;MATHEMATICAL BOLD FRAKTUR CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D582;MATHEMATICAL BOLD FRAKTUR CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D583;MATHEMATICAL BOLD FRAKTUR CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D584;MATHEMATICAL BOLD FRAKTUR CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D585;MATHEMATICAL BOLD FRAKTUR CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D586;MATHEMATICAL BOLD FRAKTUR SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D587;MATHEMATICAL BOLD FRAKTUR SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D588;MATHEMATICAL BOLD FRAKTUR SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D589;MATHEMATICAL BOLD FRAKTUR SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D58A;MATHEMATICAL BOLD FRAKTUR SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D58B;MATHEMATICAL BOLD FRAKTUR SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D58C;MATHEMATICAL BOLD FRAKTUR SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D58D;MATHEMATICAL BOLD FRAKTUR SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D58E;MATHEMATICAL BOLD FRAKTUR SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D58F;MATHEMATICAL BOLD FRAKTUR SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D590;MATHEMATICAL BOLD FRAKTUR SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D591;MATHEMATICAL BOLD FRAKTUR SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D592;MATHEMATICAL BOLD FRAKTUR SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D593;MATHEMATICAL BOLD FRAKTUR SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D594;MATHEMATICAL BOLD FRAKTUR SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D595;MATHEMATICAL BOLD FRAKTUR SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D596;MATHEMATICAL BOLD FRAKTUR SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D597;MATHEMATICAL BOLD FRAKTUR SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D598;MATHEMATICAL BOLD FRAKTUR SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D599;MATHEMATICAL BOLD FRAKTUR SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D59A;MATHEMATICAL BOLD FRAKTUR SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D59B;MATHEMATICAL BOLD FRAKTUR SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D59C;MATHEMATICAL BOLD FRAKTUR SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D59D;MATHEMATICAL BOLD FRAKTUR SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D59E;MATHEMATICAL BOLD FRAKTUR SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D59F;MATHEMATICAL BOLD FRAKTUR SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D5A0;MATHEMATICAL SANS-SERIF CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D5A1;MATHEMATICAL SANS-SERIF CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D5A2;MATHEMATICAL SANS-SERIF CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D5A3;MATHEMATICAL SANS-SERIF CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D5A4;MATHEMATICAL SANS-SERIF CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D5A5;MATHEMATICAL SANS-SERIF CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D5A6;MATHEMATICAL SANS-SERIF CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D5A7;MATHEMATICAL SANS-SERIF CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D5A8;MATHEMATICAL SANS-SERIF CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D5A9;MATHEMATICAL SANS-SERIF CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D5AA;MATHEMATICAL SANS-SERIF CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D5AB;MATHEMATICAL SANS-SERIF CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D5AC;MATHEMATICAL SANS-SERIF CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D5AD;MATHEMATICAL SANS-SERIF CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D5AE;MATHEMATICAL SANS-SERIF CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D5AF;MATHEMATICAL SANS-SERIF CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D5B0;MATHEMATICAL SANS-SERIF CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D5B1;MATHEMATICAL SANS-SERIF CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D5B2;MATHEMATICAL SANS-SERIF CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D5B3;MATHEMATICAL SANS-SERIF CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D5B4;MATHEMATICAL SANS-SERIF CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D5B5;MATHEMATICAL SANS-SERIF CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D5B6;MATHEMATICAL SANS-SERIF CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D5B7;MATHEMATICAL SANS-SERIF CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D5B8;MATHEMATICAL SANS-SERIF CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D5B9;MATHEMATICAL SANS-SERIF CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D5BA;MATHEMATICAL SANS-SERIF SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D5BB;MATHEMATICAL SANS-SERIF SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D5BC;MATHEMATICAL SANS-SERIF SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D5BD;MATHEMATICAL SANS-SERIF SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D5BE;MATHEMATICAL SANS-SERIF SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D5BF;MATHEMATICAL SANS-SERIF SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D5C0;MATHEMATICAL SANS-SERIF SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D5C1;MATHEMATICAL SANS-SERIF SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D5C2;MATHEMATICAL SANS-SERIF SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D5C3;MATHEMATICAL SANS-SERIF SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D5C4;MATHEMATICAL SANS-SERIF SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D5C5;MATHEMATICAL SANS-SERIF SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D5C6;MATHEMATICAL SANS-SERIF SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D5C7;MATHEMATICAL SANS-SERIF SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D5C8;MATHEMATICAL SANS-SERIF SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D5C9;MATHEMATICAL SANS-SERIF SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D5CA;MATHEMATICAL SANS-SERIF SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D5CB;MATHEMATICAL SANS-SERIF SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D5CC;MATHEMATICAL SANS-SERIF SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D5CD;MATHEMATICAL SANS-SERIF SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D5CE;MATHEMATICAL SANS-SERIF SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D5CF;MATHEMATICAL SANS-SERIF SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D5D0;MATHEMATICAL SANS-SERIF SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D5D1;MATHEMATICAL SANS-SERIF SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D5D2;MATHEMATICAL SANS-SERIF SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D5D3;MATHEMATICAL SANS-SERIF SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D5D4;MATHEMATICAL SANS-SERIF BOLD CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D5D5;MATHEMATICAL SANS-SERIF BOLD CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D5D6;MATHEMATICAL SANS-SERIF BOLD CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D5D7;MATHEMATICAL SANS-SERIF BOLD CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D5D8;MATHEMATICAL SANS-SERIF BOLD CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D5D9;MATHEMATICAL SANS-SERIF BOLD CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D5DA;MATHEMATICAL SANS-SERIF BOLD CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D5DB;MATHEMATICAL SANS-SERIF BOLD CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D5DC;MATHEMATICAL SANS-SERIF BOLD CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D5DD;MATHEMATICAL SANS-SERIF BOLD CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D5DE;MATHEMATICAL SANS-SERIF BOLD CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D5DF;MATHEMATICAL SANS-SERIF BOLD CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D5E0;MATHEMATICAL SANS-SERIF BOLD CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D5E1;MATHEMATICAL SANS-SERIF BOLD CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D5E2;MATHEMATICAL SANS-SERIF BOLD CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D5E3;MATHEMATICAL SANS-SERIF BOLD CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D5E4;MATHEMATICAL SANS-SERIF BOLD CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D5E5;MATHEMATICAL SANS-SERIF BOLD CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D5E6;MATHEMATICAL SANS-SERIF BOLD CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D5E7;MATHEMATICAL SANS-SERIF BOLD CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D5E8;MATHEMATICAL SANS-SERIF BOLD CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D5E9;MATHEMATICAL SANS-SERIF BOLD CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D5EA;MATHEMATICAL SANS-SERIF BOLD CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D5EB;MATHEMATICAL SANS-SERIF BOLD CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D5EC;MATHEMATICAL SANS-SERIF BOLD CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D5ED;MATHEMATICAL SANS-SERIF BOLD CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D5EE;MATHEMATICAL SANS-SERIF BOLD SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D5EF;MATHEMATICAL SANS-SERIF BOLD SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D5F0;MATHEMATICAL SANS-SERIF BOLD SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D5F1;MATHEMATICAL SANS-SERIF BOLD SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D5F2;MATHEMATICAL SANS-SERIF BOLD SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D5F3;MATHEMATICAL SANS-SERIF BOLD SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D5F4;MATHEMATICAL SANS-SERIF BOLD SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D5F5;MATHEMATICAL SANS-SERIF BOLD SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D5F6;MATHEMATICAL SANS-SERIF BOLD SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D5F7;MATHEMATICAL SANS-SERIF BOLD SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D5F8;MATHEMATICAL SANS-SERIF BOLD SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D5F9;MATHEMATICAL SANS-SERIF BOLD SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D5FA;MATHEMATICAL SANS-SERIF BOLD SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D5FB;MATHEMATICAL SANS-SERIF BOLD SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D5FC;MATHEMATICAL SANS-SERIF BOLD SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D5FD;MATHEMATICAL SANS-SERIF BOLD SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D5FE;MATHEMATICAL SANS-SERIF BOLD SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D5FF;MATHEMATICAL SANS-SERIF BOLD SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D600;MATHEMATICAL SANS-SERIF BOLD SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D601;MATHEMATICAL SANS-SERIF BOLD SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D602;MATHEMATICAL SANS-SERIF BOLD SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D603;MATHEMATICAL SANS-SERIF BOLD SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D604;MATHEMATICAL SANS-SERIF BOLD SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D605;MATHEMATICAL SANS-SERIF BOLD SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D606;MATHEMATICAL SANS-SERIF BOLD SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D607;MATHEMATICAL SANS-SERIF BOLD SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D608;MATHEMATICAL SANS-SERIF ITALIC CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D609;MATHEMATICAL SANS-SERIF ITALIC CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D60A;MATHEMATICAL SANS-SERIF ITALIC CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D60B;MATHEMATICAL SANS-SERIF ITALIC CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D60C;MATHEMATICAL SANS-SERIF ITALIC CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D60D;MATHEMATICAL SANS-SERIF ITALIC CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D60E;MATHEMATICAL SANS-SERIF ITALIC CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D60F;MATHEMATICAL SANS-SERIF ITALIC CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D610;MATHEMATICAL SANS-SERIF ITALIC CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D611;MATHEMATICAL SANS-SERIF ITALIC CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D612;MATHEMATICAL SANS-SERIF ITALIC CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D613;MATHEMATICAL SANS-SERIF ITALIC CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D614;MATHEMATICAL SANS-SERIF ITALIC CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D615;MATHEMATICAL SANS-SERIF ITALIC CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D616;MATHEMATICAL SANS-SERIF ITALIC CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D617;MATHEMATICAL SANS-SERIF ITALIC CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D618;MATHEMATICAL SANS-SERIF ITALIC CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D619;MATHEMATICAL SANS-SERIF ITALIC CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D61A;MATHEMATICAL SANS-SERIF ITALIC CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D61B;MATHEMATICAL SANS-SERIF ITALIC CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D61C;MATHEMATICAL SANS-SERIF ITALIC CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D61D;MATHEMATICAL SANS-SERIF ITALIC CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D61E;MATHEMATICAL SANS-SERIF ITALIC CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D61F;MATHEMATICAL SANS-SERIF ITALIC CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D620;MATHEMATICAL SANS-SERIF ITALIC CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D621;MATHEMATICAL SANS-SERIF ITALIC CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D622;MATHEMATICAL SANS-SERIF ITALIC SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D623;MATHEMATICAL SANS-SERIF ITALIC SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D624;MATHEMATICAL SANS-SERIF ITALIC SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D625;MATHEMATICAL SANS-SERIF ITALIC SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D626;MATHEMATICAL SANS-SERIF ITALIC SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D627;MATHEMATICAL SANS-SERIF ITALIC SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D628;MATHEMATICAL SANS-SERIF ITALIC SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D629;MATHEMATICAL SANS-SERIF ITALIC SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D62A;MATHEMATICAL SANS-SERIF ITALIC SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D62B;MATHEMATICAL SANS-SERIF ITALIC SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D62C;MATHEMATICAL SANS-SERIF ITALIC SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D62D;MATHEMATICAL SANS-SERIF ITALIC SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D62E;MATHEMATICAL SANS-SERIF ITALIC SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D62F;MATHEMATICAL SANS-SERIF ITALIC SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D630;MATHEMATICAL SANS-SERIF ITALIC SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D631;MATHEMATICAL SANS-SERIF ITALIC SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D632;MATHEMATICAL SANS-SERIF ITALIC SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D633;MATHEMATICAL SANS-SERIF ITALIC SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D634;MATHEMATICAL SANS-SERIF ITALIC SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D635;MATHEMATICAL SANS-SERIF ITALIC SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D636;MATHEMATICAL SANS-SERIF ITALIC SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D637;MATHEMATICAL SANS-SERIF ITALIC SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D638;MATHEMATICAL SANS-SERIF ITALIC SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D639;MATHEMATICAL SANS-SERIF ITALIC SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D63A;MATHEMATICAL SANS-SERIF ITALIC SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D63B;MATHEMATICAL SANS-SERIF ITALIC SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D63C;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D63D;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D63E;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D63F;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D640;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D641;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D642;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D643;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D644;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D645;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D646;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D647;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D648;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D649;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D64A;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D64B;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D64C;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D64D;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D64E;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D64F;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D650;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D651;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D652;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D653;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D654;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D655;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D656;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D657;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D658;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D659;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D65A;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D65B;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D65C;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D65D;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D65E;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D65F;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D660;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D661;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D662;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D663;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D664;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D665;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D666;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D667;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D668;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D669;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D66A;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D66B;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D66C;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D66D;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D66E;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D66F;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D670;MATHEMATICAL MONOSPACE CAPITAL A;Lu;0;L; 0041;;;;N;;;;; +1D671;MATHEMATICAL MONOSPACE CAPITAL B;Lu;0;L; 0042;;;;N;;;;; +1D672;MATHEMATICAL MONOSPACE CAPITAL C;Lu;0;L; 0043;;;;N;;;;; +1D673;MATHEMATICAL MONOSPACE CAPITAL D;Lu;0;L; 0044;;;;N;;;;; +1D674;MATHEMATICAL MONOSPACE CAPITAL E;Lu;0;L; 0045;;;;N;;;;; +1D675;MATHEMATICAL MONOSPACE CAPITAL F;Lu;0;L; 0046;;;;N;;;;; +1D676;MATHEMATICAL MONOSPACE CAPITAL G;Lu;0;L; 0047;;;;N;;;;; +1D677;MATHEMATICAL MONOSPACE CAPITAL H;Lu;0;L; 0048;;;;N;;;;; +1D678;MATHEMATICAL MONOSPACE CAPITAL I;Lu;0;L; 0049;;;;N;;;;; +1D679;MATHEMATICAL MONOSPACE CAPITAL J;Lu;0;L; 004A;;;;N;;;;; +1D67A;MATHEMATICAL MONOSPACE CAPITAL K;Lu;0;L; 004B;;;;N;;;;; +1D67B;MATHEMATICAL MONOSPACE CAPITAL L;Lu;0;L; 004C;;;;N;;;;; +1D67C;MATHEMATICAL MONOSPACE CAPITAL M;Lu;0;L; 004D;;;;N;;;;; +1D67D;MATHEMATICAL MONOSPACE CAPITAL N;Lu;0;L; 004E;;;;N;;;;; +1D67E;MATHEMATICAL MONOSPACE CAPITAL O;Lu;0;L; 004F;;;;N;;;;; +1D67F;MATHEMATICAL MONOSPACE CAPITAL P;Lu;0;L; 0050;;;;N;;;;; +1D680;MATHEMATICAL MONOSPACE CAPITAL Q;Lu;0;L; 0051;;;;N;;;;; +1D681;MATHEMATICAL MONOSPACE CAPITAL R;Lu;0;L; 0052;;;;N;;;;; +1D682;MATHEMATICAL MONOSPACE CAPITAL S;Lu;0;L; 0053;;;;N;;;;; +1D683;MATHEMATICAL MONOSPACE CAPITAL T;Lu;0;L; 0054;;;;N;;;;; +1D684;MATHEMATICAL MONOSPACE CAPITAL U;Lu;0;L; 0055;;;;N;;;;; +1D685;MATHEMATICAL MONOSPACE CAPITAL V;Lu;0;L; 0056;;;;N;;;;; +1D686;MATHEMATICAL MONOSPACE CAPITAL W;Lu;0;L; 0057;;;;N;;;;; +1D687;MATHEMATICAL MONOSPACE CAPITAL X;Lu;0;L; 0058;;;;N;;;;; +1D688;MATHEMATICAL MONOSPACE CAPITAL Y;Lu;0;L; 0059;;;;N;;;;; +1D689;MATHEMATICAL MONOSPACE CAPITAL Z;Lu;0;L; 005A;;;;N;;;;; +1D68A;MATHEMATICAL MONOSPACE SMALL A;Ll;0;L; 0061;;;;N;;;;; +1D68B;MATHEMATICAL MONOSPACE SMALL B;Ll;0;L; 0062;;;;N;;;;; +1D68C;MATHEMATICAL MONOSPACE SMALL C;Ll;0;L; 0063;;;;N;;;;; +1D68D;MATHEMATICAL MONOSPACE SMALL D;Ll;0;L; 0064;;;;N;;;;; +1D68E;MATHEMATICAL MONOSPACE SMALL E;Ll;0;L; 0065;;;;N;;;;; +1D68F;MATHEMATICAL MONOSPACE SMALL F;Ll;0;L; 0066;;;;N;;;;; +1D690;MATHEMATICAL MONOSPACE SMALL G;Ll;0;L; 0067;;;;N;;;;; +1D691;MATHEMATICAL MONOSPACE SMALL H;Ll;0;L; 0068;;;;N;;;;; +1D692;MATHEMATICAL MONOSPACE SMALL I;Ll;0;L; 0069;;;;N;;;;; +1D693;MATHEMATICAL MONOSPACE SMALL J;Ll;0;L; 006A;;;;N;;;;; +1D694;MATHEMATICAL MONOSPACE SMALL K;Ll;0;L; 006B;;;;N;;;;; +1D695;MATHEMATICAL MONOSPACE SMALL L;Ll;0;L; 006C;;;;N;;;;; +1D696;MATHEMATICAL MONOSPACE SMALL M;Ll;0;L; 006D;;;;N;;;;; +1D697;MATHEMATICAL MONOSPACE SMALL N;Ll;0;L; 006E;;;;N;;;;; +1D698;MATHEMATICAL MONOSPACE SMALL O;Ll;0;L; 006F;;;;N;;;;; +1D699;MATHEMATICAL MONOSPACE SMALL P;Ll;0;L; 0070;;;;N;;;;; +1D69A;MATHEMATICAL MONOSPACE SMALL Q;Ll;0;L; 0071;;;;N;;;;; +1D69B;MATHEMATICAL MONOSPACE SMALL R;Ll;0;L; 0072;;;;N;;;;; +1D69C;MATHEMATICAL MONOSPACE SMALL S;Ll;0;L; 0073;;;;N;;;;; +1D69D;MATHEMATICAL MONOSPACE SMALL T;Ll;0;L; 0074;;;;N;;;;; +1D69E;MATHEMATICAL MONOSPACE SMALL U;Ll;0;L; 0075;;;;N;;;;; +1D69F;MATHEMATICAL MONOSPACE SMALL V;Ll;0;L; 0076;;;;N;;;;; +1D6A0;MATHEMATICAL MONOSPACE SMALL W;Ll;0;L; 0077;;;;N;;;;; +1D6A1;MATHEMATICAL MONOSPACE SMALL X;Ll;0;L; 0078;;;;N;;;;; +1D6A2;MATHEMATICAL MONOSPACE SMALL Y;Ll;0;L; 0079;;;;N;;;;; +1D6A3;MATHEMATICAL MONOSPACE SMALL Z;Ll;0;L; 007A;;;;N;;;;; +1D6A4;MATHEMATICAL ITALIC SMALL DOTLESS I;Ll;0;L; 0131;;;;N;;;;; +1D6A5;MATHEMATICAL ITALIC SMALL DOTLESS J;Ll;0;L; 0237;;;;N;;;;; +1D6A8;MATHEMATICAL BOLD CAPITAL ALPHA;Lu;0;L; 0391;;;;N;;;;; +1D6A9;MATHEMATICAL BOLD CAPITAL BETA;Lu;0;L; 0392;;;;N;;;;; +1D6AA;MATHEMATICAL BOLD CAPITAL GAMMA;Lu;0;L; 0393;;;;N;;;;; +1D6AB;MATHEMATICAL BOLD CAPITAL DELTA;Lu;0;L; 0394;;;;N;;;;; +1D6AC;MATHEMATICAL BOLD CAPITAL EPSILON;Lu;0;L; 0395;;;;N;;;;; +1D6AD;MATHEMATICAL BOLD CAPITAL ZETA;Lu;0;L; 0396;;;;N;;;;; +1D6AE;MATHEMATICAL BOLD CAPITAL ETA;Lu;0;L; 0397;;;;N;;;;; +1D6AF;MATHEMATICAL BOLD CAPITAL THETA;Lu;0;L; 0398;;;;N;;;;; +1D6B0;MATHEMATICAL BOLD CAPITAL IOTA;Lu;0;L; 0399;;;;N;;;;; +1D6B1;MATHEMATICAL BOLD CAPITAL KAPPA;Lu;0;L; 039A;;;;N;;;;; +1D6B2;MATHEMATICAL BOLD CAPITAL LAMDA;Lu;0;L; 039B;;;;N;;;;; +1D6B3;MATHEMATICAL BOLD CAPITAL MU;Lu;0;L; 039C;;;;N;;;;; +1D6B4;MATHEMATICAL BOLD CAPITAL NU;Lu;0;L; 039D;;;;N;;;;; +1D6B5;MATHEMATICAL BOLD CAPITAL XI;Lu;0;L; 039E;;;;N;;;;; +1D6B6;MATHEMATICAL BOLD CAPITAL OMICRON;Lu;0;L; 039F;;;;N;;;;; +1D6B7;MATHEMATICAL BOLD CAPITAL PI;Lu;0;L; 03A0;;;;N;;;;; +1D6B8;MATHEMATICAL BOLD CAPITAL RHO;Lu;0;L; 03A1;;;;N;;;;; +1D6B9;MATHEMATICAL BOLD CAPITAL THETA SYMBOL;Lu;0;L; 03F4;;;;N;;;;; +1D6BA;MATHEMATICAL BOLD CAPITAL SIGMA;Lu;0;L; 03A3;;;;N;;;;; +1D6BB;MATHEMATICAL BOLD CAPITAL TAU;Lu;0;L; 03A4;;;;N;;;;; +1D6BC;MATHEMATICAL BOLD CAPITAL UPSILON;Lu;0;L; 03A5;;;;N;;;;; +1D6BD;MATHEMATICAL BOLD CAPITAL PHI;Lu;0;L; 03A6;;;;N;;;;; +1D6BE;MATHEMATICAL BOLD CAPITAL CHI;Lu;0;L; 03A7;;;;N;;;;; +1D6BF;MATHEMATICAL BOLD CAPITAL PSI;Lu;0;L; 03A8;;;;N;;;;; +1D6C0;MATHEMATICAL BOLD CAPITAL OMEGA;Lu;0;L; 03A9;;;;N;;;;; +1D6C1;MATHEMATICAL BOLD NABLA;Sm;0;L; 2207;;;;N;;;;; +1D6C2;MATHEMATICAL BOLD SMALL ALPHA;Ll;0;L; 03B1;;;;N;;;;; +1D6C3;MATHEMATICAL BOLD SMALL BETA;Ll;0;L; 03B2;;;;N;;;;; +1D6C4;MATHEMATICAL BOLD SMALL GAMMA;Ll;0;L; 03B3;;;;N;;;;; +1D6C5;MATHEMATICAL BOLD SMALL DELTA;Ll;0;L; 03B4;;;;N;;;;; +1D6C6;MATHEMATICAL BOLD SMALL EPSILON;Ll;0;L; 03B5;;;;N;;;;; +1D6C7;MATHEMATICAL BOLD SMALL ZETA;Ll;0;L; 03B6;;;;N;;;;; +1D6C8;MATHEMATICAL BOLD SMALL ETA;Ll;0;L; 03B7;;;;N;;;;; +1D6C9;MATHEMATICAL BOLD SMALL THETA;Ll;0;L; 03B8;;;;N;;;;; +1D6CA;MATHEMATICAL BOLD SMALL IOTA;Ll;0;L; 03B9;;;;N;;;;; +1D6CB;MATHEMATICAL BOLD SMALL KAPPA;Ll;0;L; 03BA;;;;N;;;;; +1D6CC;MATHEMATICAL BOLD SMALL LAMDA;Ll;0;L; 03BB;;;;N;;;;; +1D6CD;MATHEMATICAL BOLD SMALL MU;Ll;0;L; 03BC;;;;N;;;;; +1D6CE;MATHEMATICAL BOLD SMALL NU;Ll;0;L; 03BD;;;;N;;;;; +1D6CF;MATHEMATICAL BOLD SMALL XI;Ll;0;L; 03BE;;;;N;;;;; +1D6D0;MATHEMATICAL BOLD SMALL OMICRON;Ll;0;L; 03BF;;;;N;;;;; +1D6D1;MATHEMATICAL BOLD SMALL PI;Ll;0;L; 03C0;;;;N;;;;; +1D6D2;MATHEMATICAL BOLD SMALL RHO;Ll;0;L; 03C1;;;;N;;;;; +1D6D3;MATHEMATICAL BOLD SMALL FINAL SIGMA;Ll;0;L; 03C2;;;;N;;;;; +1D6D4;MATHEMATICAL BOLD SMALL SIGMA;Ll;0;L; 03C3;;;;N;;;;; +1D6D5;MATHEMATICAL BOLD SMALL TAU;Ll;0;L; 03C4;;;;N;;;;; +1D6D6;MATHEMATICAL BOLD SMALL UPSILON;Ll;0;L; 03C5;;;;N;;;;; +1D6D7;MATHEMATICAL BOLD SMALL PHI;Ll;0;L; 03C6;;;;N;;;;; +1D6D8;MATHEMATICAL BOLD SMALL CHI;Ll;0;L; 03C7;;;;N;;;;; +1D6D9;MATHEMATICAL BOLD SMALL PSI;Ll;0;L; 03C8;;;;N;;;;; +1D6DA;MATHEMATICAL BOLD SMALL OMEGA;Ll;0;L; 03C9;;;;N;;;;; +1D6DB;MATHEMATICAL BOLD PARTIAL DIFFERENTIAL;Sm;0;ON; 2202;;;;Y;;;;; +1D6DC;MATHEMATICAL BOLD EPSILON SYMBOL;Ll;0;L; 03F5;;;;N;;;;; +1D6DD;MATHEMATICAL BOLD THETA SYMBOL;Ll;0;L; 03D1;;;;N;;;;; +1D6DE;MATHEMATICAL BOLD KAPPA SYMBOL;Ll;0;L; 03F0;;;;N;;;;; +1D6DF;MATHEMATICAL BOLD PHI SYMBOL;Ll;0;L; 03D5;;;;N;;;;; +1D6E0;MATHEMATICAL BOLD RHO SYMBOL;Ll;0;L; 03F1;;;;N;;;;; +1D6E1;MATHEMATICAL BOLD PI SYMBOL;Ll;0;L; 03D6;;;;N;;;;; +1D6E2;MATHEMATICAL ITALIC CAPITAL ALPHA;Lu;0;L; 0391;;;;N;;;;; +1D6E3;MATHEMATICAL ITALIC CAPITAL BETA;Lu;0;L; 0392;;;;N;;;;; +1D6E4;MATHEMATICAL ITALIC CAPITAL GAMMA;Lu;0;L; 0393;;;;N;;;;; +1D6E5;MATHEMATICAL ITALIC CAPITAL DELTA;Lu;0;L; 0394;;;;N;;;;; +1D6E6;MATHEMATICAL ITALIC CAPITAL EPSILON;Lu;0;L; 0395;;;;N;;;;; +1D6E7;MATHEMATICAL ITALIC CAPITAL ZETA;Lu;0;L; 0396;;;;N;;;;; +1D6E8;MATHEMATICAL ITALIC CAPITAL ETA;Lu;0;L; 0397;;;;N;;;;; +1D6E9;MATHEMATICAL ITALIC CAPITAL THETA;Lu;0;L; 0398;;;;N;;;;; +1D6EA;MATHEMATICAL ITALIC CAPITAL IOTA;Lu;0;L; 0399;;;;N;;;;; +1D6EB;MATHEMATICAL ITALIC CAPITAL KAPPA;Lu;0;L; 039A;;;;N;;;;; +1D6EC;MATHEMATICAL ITALIC CAPITAL LAMDA;Lu;0;L; 039B;;;;N;;;;; +1D6ED;MATHEMATICAL ITALIC CAPITAL MU;Lu;0;L; 039C;;;;N;;;;; +1D6EE;MATHEMATICAL ITALIC CAPITAL NU;Lu;0;L; 039D;;;;N;;;;; +1D6EF;MATHEMATICAL ITALIC CAPITAL XI;Lu;0;L; 039E;;;;N;;;;; +1D6F0;MATHEMATICAL ITALIC CAPITAL OMICRON;Lu;0;L; 039F;;;;N;;;;; +1D6F1;MATHEMATICAL ITALIC CAPITAL PI;Lu;0;L; 03A0;;;;N;;;;; +1D6F2;MATHEMATICAL ITALIC CAPITAL RHO;Lu;0;L; 03A1;;;;N;;;;; +1D6F3;MATHEMATICAL ITALIC CAPITAL THETA SYMBOL;Lu;0;L; 03F4;;;;N;;;;; +1D6F4;MATHEMATICAL ITALIC CAPITAL SIGMA;Lu;0;L; 03A3;;;;N;;;;; +1D6F5;MATHEMATICAL ITALIC CAPITAL TAU;Lu;0;L; 03A4;;;;N;;;;; +1D6F6;MATHEMATICAL ITALIC CAPITAL UPSILON;Lu;0;L; 03A5;;;;N;;;;; +1D6F7;MATHEMATICAL ITALIC CAPITAL PHI;Lu;0;L; 03A6;;;;N;;;;; +1D6F8;MATHEMATICAL ITALIC CAPITAL CHI;Lu;0;L; 03A7;;;;N;;;;; +1D6F9;MATHEMATICAL ITALIC CAPITAL PSI;Lu;0;L; 03A8;;;;N;;;;; +1D6FA;MATHEMATICAL ITALIC CAPITAL OMEGA;Lu;0;L; 03A9;;;;N;;;;; +1D6FB;MATHEMATICAL ITALIC NABLA;Sm;0;L; 2207;;;;N;;;;; +1D6FC;MATHEMATICAL ITALIC SMALL ALPHA;Ll;0;L; 03B1;;;;N;;;;; +1D6FD;MATHEMATICAL ITALIC SMALL BETA;Ll;0;L; 03B2;;;;N;;;;; +1D6FE;MATHEMATICAL ITALIC SMALL GAMMA;Ll;0;L; 03B3;;;;N;;;;; +1D6FF;MATHEMATICAL ITALIC SMALL DELTA;Ll;0;L; 03B4;;;;N;;;;; +1D700;MATHEMATICAL ITALIC SMALL EPSILON;Ll;0;L; 03B5;;;;N;;;;; +1D701;MATHEMATICAL ITALIC SMALL ZETA;Ll;0;L; 03B6;;;;N;;;;; +1D702;MATHEMATICAL ITALIC SMALL ETA;Ll;0;L; 03B7;;;;N;;;;; +1D703;MATHEMATICAL ITALIC SMALL THETA;Ll;0;L; 03B8;;;;N;;;;; +1D704;MATHEMATICAL ITALIC SMALL IOTA;Ll;0;L; 03B9;;;;N;;;;; +1D705;MATHEMATICAL ITALIC SMALL KAPPA;Ll;0;L; 03BA;;;;N;;;;; +1D706;MATHEMATICAL ITALIC SMALL LAMDA;Ll;0;L; 03BB;;;;N;;;;; +1D707;MATHEMATICAL ITALIC SMALL MU;Ll;0;L; 03BC;;;;N;;;;; +1D708;MATHEMATICAL ITALIC SMALL NU;Ll;0;L; 03BD;;;;N;;;;; +1D709;MATHEMATICAL ITALIC SMALL XI;Ll;0;L; 03BE;;;;N;;;;; +1D70A;MATHEMATICAL ITALIC SMALL OMICRON;Ll;0;L; 03BF;;;;N;;;;; +1D70B;MATHEMATICAL ITALIC SMALL PI;Ll;0;L; 03C0;;;;N;;;;; +1D70C;MATHEMATICAL ITALIC SMALL RHO;Ll;0;L; 03C1;;;;N;;;;; +1D70D;MATHEMATICAL ITALIC SMALL FINAL SIGMA;Ll;0;L; 03C2;;;;N;;;;; +1D70E;MATHEMATICAL ITALIC SMALL SIGMA;Ll;0;L; 03C3;;;;N;;;;; +1D70F;MATHEMATICAL ITALIC SMALL TAU;Ll;0;L; 03C4;;;;N;;;;; +1D710;MATHEMATICAL ITALIC SMALL UPSILON;Ll;0;L; 03C5;;;;N;;;;; +1D711;MATHEMATICAL ITALIC SMALL PHI;Ll;0;L; 03C6;;;;N;;;;; +1D712;MATHEMATICAL ITALIC SMALL CHI;Ll;0;L; 03C7;;;;N;;;;; +1D713;MATHEMATICAL ITALIC SMALL PSI;Ll;0;L; 03C8;;;;N;;;;; +1D714;MATHEMATICAL ITALIC SMALL OMEGA;Ll;0;L; 03C9;;;;N;;;;; +1D715;MATHEMATICAL ITALIC PARTIAL DIFFERENTIAL;Sm;0;ON; 2202;;;;Y;;;;; +1D716;MATHEMATICAL ITALIC EPSILON SYMBOL;Ll;0;L; 03F5;;;;N;;;;; +1D717;MATHEMATICAL ITALIC THETA SYMBOL;Ll;0;L; 03D1;;;;N;;;;; +1D718;MATHEMATICAL ITALIC KAPPA SYMBOL;Ll;0;L; 03F0;;;;N;;;;; +1D719;MATHEMATICAL ITALIC PHI SYMBOL;Ll;0;L; 03D5;;;;N;;;;; +1D71A;MATHEMATICAL ITALIC RHO SYMBOL;Ll;0;L; 03F1;;;;N;;;;; +1D71B;MATHEMATICAL ITALIC PI SYMBOL;Ll;0;L; 03D6;;;;N;;;;; +1D71C;MATHEMATICAL BOLD ITALIC CAPITAL ALPHA;Lu;0;L; 0391;;;;N;;;;; +1D71D;MATHEMATICAL BOLD ITALIC CAPITAL BETA;Lu;0;L; 0392;;;;N;;;;; +1D71E;MATHEMATICAL BOLD ITALIC CAPITAL GAMMA;Lu;0;L; 0393;;;;N;;;;; +1D71F;MATHEMATICAL BOLD ITALIC CAPITAL DELTA;Lu;0;L; 0394;;;;N;;;;; +1D720;MATHEMATICAL BOLD ITALIC CAPITAL EPSILON;Lu;0;L; 0395;;;;N;;;;; +1D721;MATHEMATICAL BOLD ITALIC CAPITAL ZETA;Lu;0;L; 0396;;;;N;;;;; +1D722;MATHEMATICAL BOLD ITALIC CAPITAL ETA;Lu;0;L; 0397;;;;N;;;;; +1D723;MATHEMATICAL BOLD ITALIC CAPITAL THETA;Lu;0;L; 0398;;;;N;;;;; +1D724;MATHEMATICAL BOLD ITALIC CAPITAL IOTA;Lu;0;L; 0399;;;;N;;;;; +1D725;MATHEMATICAL BOLD ITALIC CAPITAL KAPPA;Lu;0;L; 039A;;;;N;;;;; +1D726;MATHEMATICAL BOLD ITALIC CAPITAL LAMDA;Lu;0;L; 039B;;;;N;;;;; +1D727;MATHEMATICAL BOLD ITALIC CAPITAL MU;Lu;0;L; 039C;;;;N;;;;; +1D728;MATHEMATICAL BOLD ITALIC CAPITAL NU;Lu;0;L; 039D;;;;N;;;;; +1D729;MATHEMATICAL BOLD ITALIC CAPITAL XI;Lu;0;L; 039E;;;;N;;;;; +1D72A;MATHEMATICAL BOLD ITALIC CAPITAL OMICRON;Lu;0;L; 039F;;;;N;;;;; +1D72B;MATHEMATICAL BOLD ITALIC CAPITAL PI;Lu;0;L; 03A0;;;;N;;;;; +1D72C;MATHEMATICAL BOLD ITALIC CAPITAL RHO;Lu;0;L; 03A1;;;;N;;;;; +1D72D;MATHEMATICAL BOLD ITALIC CAPITAL THETA SYMBOL;Lu;0;L; 03F4;;;;N;;;;; +1D72E;MATHEMATICAL BOLD ITALIC CAPITAL SIGMA;Lu;0;L; 03A3;;;;N;;;;; +1D72F;MATHEMATICAL BOLD ITALIC CAPITAL TAU;Lu;0;L; 03A4;;;;N;;;;; +1D730;MATHEMATICAL BOLD ITALIC CAPITAL UPSILON;Lu;0;L; 03A5;;;;N;;;;; +1D731;MATHEMATICAL BOLD ITALIC CAPITAL PHI;Lu;0;L; 03A6;;;;N;;;;; +1D732;MATHEMATICAL BOLD ITALIC CAPITAL CHI;Lu;0;L; 03A7;;;;N;;;;; +1D733;MATHEMATICAL BOLD ITALIC CAPITAL PSI;Lu;0;L; 03A8;;;;N;;;;; +1D734;MATHEMATICAL BOLD ITALIC CAPITAL OMEGA;Lu;0;L; 03A9;;;;N;;;;; +1D735;MATHEMATICAL BOLD ITALIC NABLA;Sm;0;L; 2207;;;;N;;;;; +1D736;MATHEMATICAL BOLD ITALIC SMALL ALPHA;Ll;0;L; 03B1;;;;N;;;;; +1D737;MATHEMATICAL BOLD ITALIC SMALL BETA;Ll;0;L; 03B2;;;;N;;;;; +1D738;MATHEMATICAL BOLD ITALIC SMALL GAMMA;Ll;0;L; 03B3;;;;N;;;;; +1D739;MATHEMATICAL BOLD ITALIC SMALL DELTA;Ll;0;L; 03B4;;;;N;;;;; +1D73A;MATHEMATICAL BOLD ITALIC SMALL EPSILON;Ll;0;L; 03B5;;;;N;;;;; +1D73B;MATHEMATICAL BOLD ITALIC SMALL ZETA;Ll;0;L; 03B6;;;;N;;;;; +1D73C;MATHEMATICAL BOLD ITALIC SMALL ETA;Ll;0;L; 03B7;;;;N;;;;; +1D73D;MATHEMATICAL BOLD ITALIC SMALL THETA;Ll;0;L; 03B8;;;;N;;;;; +1D73E;MATHEMATICAL BOLD ITALIC SMALL IOTA;Ll;0;L; 03B9;;;;N;;;;; +1D73F;MATHEMATICAL BOLD ITALIC SMALL KAPPA;Ll;0;L; 03BA;;;;N;;;;; +1D740;MATHEMATICAL BOLD ITALIC SMALL LAMDA;Ll;0;L; 03BB;;;;N;;;;; +1D741;MATHEMATICAL BOLD ITALIC SMALL MU;Ll;0;L; 03BC;;;;N;;;;; +1D742;MATHEMATICAL BOLD ITALIC SMALL NU;Ll;0;L; 03BD;;;;N;;;;; +1D743;MATHEMATICAL BOLD ITALIC SMALL XI;Ll;0;L; 03BE;;;;N;;;;; +1D744;MATHEMATICAL BOLD ITALIC SMALL OMICRON;Ll;0;L; 03BF;;;;N;;;;; +1D745;MATHEMATICAL BOLD ITALIC SMALL PI;Ll;0;L; 03C0;;;;N;;;;; +1D746;MATHEMATICAL BOLD ITALIC SMALL RHO;Ll;0;L; 03C1;;;;N;;;;; +1D747;MATHEMATICAL BOLD ITALIC SMALL FINAL SIGMA;Ll;0;L; 03C2;;;;N;;;;; +1D748;MATHEMATICAL BOLD ITALIC SMALL SIGMA;Ll;0;L; 03C3;;;;N;;;;; +1D749;MATHEMATICAL BOLD ITALIC SMALL TAU;Ll;0;L; 03C4;;;;N;;;;; +1D74A;MATHEMATICAL BOLD ITALIC SMALL UPSILON;Ll;0;L; 03C5;;;;N;;;;; +1D74B;MATHEMATICAL BOLD ITALIC SMALL PHI;Ll;0;L; 03C6;;;;N;;;;; +1D74C;MATHEMATICAL BOLD ITALIC SMALL CHI;Ll;0;L; 03C7;;;;N;;;;; +1D74D;MATHEMATICAL BOLD ITALIC SMALL PSI;Ll;0;L; 03C8;;;;N;;;;; +1D74E;MATHEMATICAL BOLD ITALIC SMALL OMEGA;Ll;0;L; 03C9;;;;N;;;;; +1D74F;MATHEMATICAL BOLD ITALIC PARTIAL DIFFERENTIAL;Sm;0;ON; 2202;;;;Y;;;;; +1D750;MATHEMATICAL BOLD ITALIC EPSILON SYMBOL;Ll;0;L; 03F5;;;;N;;;;; +1D751;MATHEMATICAL BOLD ITALIC THETA SYMBOL;Ll;0;L; 03D1;;;;N;;;;; +1D752;MATHEMATICAL BOLD ITALIC KAPPA SYMBOL;Ll;0;L; 03F0;;;;N;;;;; +1D753;MATHEMATICAL BOLD ITALIC PHI SYMBOL;Ll;0;L; 03D5;;;;N;;;;; +1D754;MATHEMATICAL BOLD ITALIC RHO SYMBOL;Ll;0;L; 03F1;;;;N;;;;; +1D755;MATHEMATICAL BOLD ITALIC PI SYMBOL;Ll;0;L; 03D6;;;;N;;;;; +1D756;MATHEMATICAL SANS-SERIF BOLD CAPITAL ALPHA;Lu;0;L; 0391;;;;N;;;;; +1D757;MATHEMATICAL SANS-SERIF BOLD CAPITAL BETA;Lu;0;L; 0392;;;;N;;;;; +1D758;MATHEMATICAL SANS-SERIF BOLD CAPITAL GAMMA;Lu;0;L; 0393;;;;N;;;;; +1D759;MATHEMATICAL SANS-SERIF BOLD CAPITAL DELTA;Lu;0;L; 0394;;;;N;;;;; +1D75A;MATHEMATICAL SANS-SERIF BOLD CAPITAL EPSILON;Lu;0;L; 0395;;;;N;;;;; +1D75B;MATHEMATICAL SANS-SERIF BOLD CAPITAL ZETA;Lu;0;L; 0396;;;;N;;;;; +1D75C;MATHEMATICAL SANS-SERIF BOLD CAPITAL ETA;Lu;0;L; 0397;;;;N;;;;; +1D75D;MATHEMATICAL SANS-SERIF BOLD CAPITAL THETA;Lu;0;L; 0398;;;;N;;;;; +1D75E;MATHEMATICAL SANS-SERIF BOLD CAPITAL IOTA;Lu;0;L; 0399;;;;N;;;;; +1D75F;MATHEMATICAL SANS-SERIF BOLD CAPITAL KAPPA;Lu;0;L; 039A;;;;N;;;;; +1D760;MATHEMATICAL SANS-SERIF BOLD CAPITAL LAMDA;Lu;0;L; 039B;;;;N;;;;; +1D761;MATHEMATICAL SANS-SERIF BOLD CAPITAL MU;Lu;0;L; 039C;;;;N;;;;; +1D762;MATHEMATICAL SANS-SERIF BOLD CAPITAL NU;Lu;0;L; 039D;;;;N;;;;; +1D763;MATHEMATICAL SANS-SERIF BOLD CAPITAL XI;Lu;0;L; 039E;;;;N;;;;; +1D764;MATHEMATICAL SANS-SERIF BOLD CAPITAL OMICRON;Lu;0;L; 039F;;;;N;;;;; +1D765;MATHEMATICAL SANS-SERIF BOLD CAPITAL PI;Lu;0;L; 03A0;;;;N;;;;; +1D766;MATHEMATICAL SANS-SERIF BOLD CAPITAL RHO;Lu;0;L; 03A1;;;;N;;;;; +1D767;MATHEMATICAL SANS-SERIF BOLD CAPITAL THETA SYMBOL;Lu;0;L; 03F4;;;;N;;;;; +1D768;MATHEMATICAL SANS-SERIF BOLD CAPITAL SIGMA;Lu;0;L; 03A3;;;;N;;;;; +1D769;MATHEMATICAL SANS-SERIF BOLD CAPITAL TAU;Lu;0;L; 03A4;;;;N;;;;; +1D76A;MATHEMATICAL SANS-SERIF BOLD CAPITAL UPSILON;Lu;0;L; 03A5;;;;N;;;;; +1D76B;MATHEMATICAL SANS-SERIF BOLD CAPITAL PHI;Lu;0;L; 03A6;;;;N;;;;; +1D76C;MATHEMATICAL SANS-SERIF BOLD CAPITAL CHI;Lu;0;L; 03A7;;;;N;;;;; +1D76D;MATHEMATICAL SANS-SERIF BOLD CAPITAL PSI;Lu;0;L; 03A8;;;;N;;;;; +1D76E;MATHEMATICAL SANS-SERIF BOLD CAPITAL OMEGA;Lu;0;L; 03A9;;;;N;;;;; +1D76F;MATHEMATICAL SANS-SERIF BOLD NABLA;Sm;0;L; 2207;;;;N;;;;; +1D770;MATHEMATICAL SANS-SERIF BOLD SMALL ALPHA;Ll;0;L; 03B1;;;;N;;;;; +1D771;MATHEMATICAL SANS-SERIF BOLD SMALL BETA;Ll;0;L; 03B2;;;;N;;;;; +1D772;MATHEMATICAL SANS-SERIF BOLD SMALL GAMMA;Ll;0;L; 03B3;;;;N;;;;; +1D773;MATHEMATICAL SANS-SERIF BOLD SMALL DELTA;Ll;0;L; 03B4;;;;N;;;;; +1D774;MATHEMATICAL SANS-SERIF BOLD SMALL EPSILON;Ll;0;L; 03B5;;;;N;;;;; +1D775;MATHEMATICAL SANS-SERIF BOLD SMALL ZETA;Ll;0;L; 03B6;;;;N;;;;; +1D776;MATHEMATICAL SANS-SERIF BOLD SMALL ETA;Ll;0;L; 03B7;;;;N;;;;; +1D777;MATHEMATICAL SANS-SERIF BOLD SMALL THETA;Ll;0;L; 03B8;;;;N;;;;; +1D778;MATHEMATICAL SANS-SERIF BOLD SMALL IOTA;Ll;0;L; 03B9;;;;N;;;;; +1D779;MATHEMATICAL SANS-SERIF BOLD SMALL KAPPA;Ll;0;L; 03BA;;;;N;;;;; +1D77A;MATHEMATICAL SANS-SERIF BOLD SMALL LAMDA;Ll;0;L; 03BB;;;;N;;;;; +1D77B;MATHEMATICAL SANS-SERIF BOLD SMALL MU;Ll;0;L; 03BC;;;;N;;;;; +1D77C;MATHEMATICAL SANS-SERIF BOLD SMALL NU;Ll;0;L; 03BD;;;;N;;;;; +1D77D;MATHEMATICAL SANS-SERIF BOLD SMALL XI;Ll;0;L; 03BE;;;;N;;;;; +1D77E;MATHEMATICAL SANS-SERIF BOLD SMALL OMICRON;Ll;0;L; 03BF;;;;N;;;;; +1D77F;MATHEMATICAL SANS-SERIF BOLD SMALL PI;Ll;0;L; 03C0;;;;N;;;;; +1D780;MATHEMATICAL SANS-SERIF BOLD SMALL RHO;Ll;0;L; 03C1;;;;N;;;;; +1D781;MATHEMATICAL SANS-SERIF BOLD SMALL FINAL SIGMA;Ll;0;L; 03C2;;;;N;;;;; +1D782;MATHEMATICAL SANS-SERIF BOLD SMALL SIGMA;Ll;0;L; 03C3;;;;N;;;;; +1D783;MATHEMATICAL SANS-SERIF BOLD SMALL TAU;Ll;0;L; 03C4;;;;N;;;;; +1D784;MATHEMATICAL SANS-SERIF BOLD SMALL UPSILON;Ll;0;L; 03C5;;;;N;;;;; +1D785;MATHEMATICAL SANS-SERIF BOLD SMALL PHI;Ll;0;L; 03C6;;;;N;;;;; +1D786;MATHEMATICAL SANS-SERIF BOLD SMALL CHI;Ll;0;L; 03C7;;;;N;;;;; +1D787;MATHEMATICAL SANS-SERIF BOLD SMALL PSI;Ll;0;L; 03C8;;;;N;;;;; +1D788;MATHEMATICAL SANS-SERIF BOLD SMALL OMEGA;Ll;0;L; 03C9;;;;N;;;;; +1D789;MATHEMATICAL SANS-SERIF BOLD PARTIAL DIFFERENTIAL;Sm;0;ON; 2202;;;;Y;;;;; +1D78A;MATHEMATICAL SANS-SERIF BOLD EPSILON SYMBOL;Ll;0;L; 03F5;;;;N;;;;; +1D78B;MATHEMATICAL SANS-SERIF BOLD THETA SYMBOL;Ll;0;L; 03D1;;;;N;;;;; +1D78C;MATHEMATICAL SANS-SERIF BOLD KAPPA SYMBOL;Ll;0;L; 03F0;;;;N;;;;; +1D78D;MATHEMATICAL SANS-SERIF BOLD PHI SYMBOL;Ll;0;L; 03D5;;;;N;;;;; +1D78E;MATHEMATICAL SANS-SERIF BOLD RHO SYMBOL;Ll;0;L; 03F1;;;;N;;;;; +1D78F;MATHEMATICAL SANS-SERIF BOLD PI SYMBOL;Ll;0;L; 03D6;;;;N;;;;; +1D790;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ALPHA;Lu;0;L; 0391;;;;N;;;;; +1D791;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL BETA;Lu;0;L; 0392;;;;N;;;;; +1D792;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL GAMMA;Lu;0;L; 0393;;;;N;;;;; +1D793;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL DELTA;Lu;0;L; 0394;;;;N;;;;; +1D794;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL EPSILON;Lu;0;L; 0395;;;;N;;;;; +1D795;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ZETA;Lu;0;L; 0396;;;;N;;;;; +1D796;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ETA;Lu;0;L; 0397;;;;N;;;;; +1D797;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA;Lu;0;L; 0398;;;;N;;;;; +1D798;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL IOTA;Lu;0;L; 0399;;;;N;;;;; +1D799;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL KAPPA;Lu;0;L; 039A;;;;N;;;;; +1D79A;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL LAMDA;Lu;0;L; 039B;;;;N;;;;; +1D79B;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL MU;Lu;0;L; 039C;;;;N;;;;; +1D79C;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL NU;Lu;0;L; 039D;;;;N;;;;; +1D79D;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL XI;Lu;0;L; 039E;;;;N;;;;; +1D79E;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMICRON;Lu;0;L; 039F;;;;N;;;;; +1D79F;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PI;Lu;0;L; 03A0;;;;N;;;;; +1D7A0;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL RHO;Lu;0;L; 03A1;;;;N;;;;; +1D7A1;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA SYMBOL;Lu;0;L; 03F4;;;;N;;;;; +1D7A2;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL SIGMA;Lu;0;L; 03A3;;;;N;;;;; +1D7A3;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL TAU;Lu;0;L; 03A4;;;;N;;;;; +1D7A4;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL UPSILON;Lu;0;L; 03A5;;;;N;;;;; +1D7A5;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PHI;Lu;0;L; 03A6;;;;N;;;;; +1D7A6;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL CHI;Lu;0;L; 03A7;;;;N;;;;; +1D7A7;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PSI;Lu;0;L; 03A8;;;;N;;;;; +1D7A8;MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMEGA;Lu;0;L; 03A9;;;;N;;;;; +1D7A9;MATHEMATICAL SANS-SERIF BOLD ITALIC NABLA;Sm;0;L; 2207;;;;N;;;;; +1D7AA;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ALPHA;Ll;0;L; 03B1;;;;N;;;;; +1D7AB;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL BETA;Ll;0;L; 03B2;;;;N;;;;; +1D7AC;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL GAMMA;Ll;0;L; 03B3;;;;N;;;;; +1D7AD;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL DELTA;Ll;0;L; 03B4;;;;N;;;;; +1D7AE;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL EPSILON;Ll;0;L; 03B5;;;;N;;;;; +1D7AF;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ZETA;Ll;0;L; 03B6;;;;N;;;;; +1D7B0;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ETA;Ll;0;L; 03B7;;;;N;;;;; +1D7B1;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL THETA;Ll;0;L; 03B8;;;;N;;;;; +1D7B2;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL IOTA;Ll;0;L; 03B9;;;;N;;;;; +1D7B3;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL KAPPA;Ll;0;L; 03BA;;;;N;;;;; +1D7B4;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL LAMDA;Ll;0;L; 03BB;;;;N;;;;; +1D7B5;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL MU;Ll;0;L; 03BC;;;;N;;;;; +1D7B6;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL NU;Ll;0;L; 03BD;;;;N;;;;; +1D7B7;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL XI;Ll;0;L; 03BE;;;;N;;;;; +1D7B8;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMICRON;Ll;0;L; 03BF;;;;N;;;;; +1D7B9;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PI;Ll;0;L; 03C0;;;;N;;;;; +1D7BA;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL RHO;Ll;0;L; 03C1;;;;N;;;;; +1D7BB;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL FINAL SIGMA;Ll;0;L; 03C2;;;;N;;;;; +1D7BC;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL SIGMA;Ll;0;L; 03C3;;;;N;;;;; +1D7BD;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL TAU;Ll;0;L; 03C4;;;;N;;;;; +1D7BE;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL UPSILON;Ll;0;L; 03C5;;;;N;;;;; +1D7BF;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PHI;Ll;0;L; 03C6;;;;N;;;;; +1D7C0;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL CHI;Ll;0;L; 03C7;;;;N;;;;; +1D7C1;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PSI;Ll;0;L; 03C8;;;;N;;;;; +1D7C2;MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMEGA;Ll;0;L; 03C9;;;;N;;;;; +1D7C3;MATHEMATICAL SANS-SERIF BOLD ITALIC PARTIAL DIFFERENTIAL;Sm;0;ON; 2202;;;;Y;;;;; +1D7C4;MATHEMATICAL SANS-SERIF BOLD ITALIC EPSILON SYMBOL;Ll;0;L; 03F5;;;;N;;;;; +1D7C5;MATHEMATICAL SANS-SERIF BOLD ITALIC THETA SYMBOL;Ll;0;L; 03D1;;;;N;;;;; +1D7C6;MATHEMATICAL SANS-SERIF BOLD ITALIC KAPPA SYMBOL;Ll;0;L; 03F0;;;;N;;;;; +1D7C7;MATHEMATICAL SANS-SERIF BOLD ITALIC PHI SYMBOL;Ll;0;L; 03D5;;;;N;;;;; +1D7C8;MATHEMATICAL SANS-SERIF BOLD ITALIC RHO SYMBOL;Ll;0;L; 03F1;;;;N;;;;; +1D7C9;MATHEMATICAL SANS-SERIF BOLD ITALIC PI SYMBOL;Ll;0;L; 03D6;;;;N;;;;; +1D7CA;MATHEMATICAL BOLD CAPITAL DIGAMMA;Lu;0;L; 03DC;;;;N;;;;; +1D7CB;MATHEMATICAL BOLD SMALL DIGAMMA;Ll;0;L; 03DD;;;;N;;;;; +1D7CE;MATHEMATICAL BOLD DIGIT ZERO;Nd;0;EN; 0030;0;0;0;N;;;;; +1D7CF;MATHEMATICAL BOLD DIGIT ONE;Nd;0;EN; 0031;1;1;1;N;;;;; +1D7D0;MATHEMATICAL BOLD DIGIT TWO;Nd;0;EN; 0032;2;2;2;N;;;;; +1D7D1;MATHEMATICAL BOLD DIGIT THREE;Nd;0;EN; 0033;3;3;3;N;;;;; +1D7D2;MATHEMATICAL BOLD DIGIT FOUR;Nd;0;EN; 0034;4;4;4;N;;;;; +1D7D3;MATHEMATICAL BOLD DIGIT FIVE;Nd;0;EN; 0035;5;5;5;N;;;;; +1D7D4;MATHEMATICAL BOLD DIGIT SIX;Nd;0;EN; 0036;6;6;6;N;;;;; +1D7D5;MATHEMATICAL BOLD DIGIT SEVEN;Nd;0;EN; 0037;7;7;7;N;;;;; +1D7D6;MATHEMATICAL BOLD DIGIT EIGHT;Nd;0;EN; 0038;8;8;8;N;;;;; +1D7D7;MATHEMATICAL BOLD DIGIT NINE;Nd;0;EN; 0039;9;9;9;N;;;;; +1D7D8;MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO;Nd;0;EN; 0030;0;0;0;N;;;;; +1D7D9;MATHEMATICAL DOUBLE-STRUCK DIGIT ONE;Nd;0;EN; 0031;1;1;1;N;;;;; +1D7DA;MATHEMATICAL DOUBLE-STRUCK DIGIT TWO;Nd;0;EN; 0032;2;2;2;N;;;;; +1D7DB;MATHEMATICAL DOUBLE-STRUCK DIGIT THREE;Nd;0;EN; 0033;3;3;3;N;;;;; +1D7DC;MATHEMATICAL DOUBLE-STRUCK DIGIT FOUR;Nd;0;EN; 0034;4;4;4;N;;;;; +1D7DD;MATHEMATICAL DOUBLE-STRUCK DIGIT FIVE;Nd;0;EN; 0035;5;5;5;N;;;;; +1D7DE;MATHEMATICAL DOUBLE-STRUCK DIGIT SIX;Nd;0;EN; 0036;6;6;6;N;;;;; +1D7DF;MATHEMATICAL DOUBLE-STRUCK DIGIT SEVEN;Nd;0;EN; 0037;7;7;7;N;;;;; +1D7E0;MATHEMATICAL DOUBLE-STRUCK DIGIT EIGHT;Nd;0;EN; 0038;8;8;8;N;;;;; +1D7E1;MATHEMATICAL DOUBLE-STRUCK DIGIT NINE;Nd;0;EN; 0039;9;9;9;N;;;;; +1D7E2;MATHEMATICAL SANS-SERIF DIGIT ZERO;Nd;0;EN; 0030;0;0;0;N;;;;; +1D7E3;MATHEMATICAL SANS-SERIF DIGIT ONE;Nd;0;EN; 0031;1;1;1;N;;;;; +1D7E4;MATHEMATICAL SANS-SERIF DIGIT TWO;Nd;0;EN; 0032;2;2;2;N;;;;; +1D7E5;MATHEMATICAL SANS-SERIF DIGIT THREE;Nd;0;EN; 0033;3;3;3;N;;;;; +1D7E6;MATHEMATICAL SANS-SERIF DIGIT FOUR;Nd;0;EN; 0034;4;4;4;N;;;;; +1D7E7;MATHEMATICAL SANS-SERIF DIGIT FIVE;Nd;0;EN; 0035;5;5;5;N;;;;; +1D7E8;MATHEMATICAL SANS-SERIF DIGIT SIX;Nd;0;EN; 0036;6;6;6;N;;;;; +1D7E9;MATHEMATICAL SANS-SERIF DIGIT SEVEN;Nd;0;EN; 0037;7;7;7;N;;;;; +1D7EA;MATHEMATICAL SANS-SERIF DIGIT EIGHT;Nd;0;EN; 0038;8;8;8;N;;;;; +1D7EB;MATHEMATICAL SANS-SERIF DIGIT NINE;Nd;0;EN; 0039;9;9;9;N;;;;; +1D7EC;MATHEMATICAL SANS-SERIF BOLD DIGIT ZERO;Nd;0;EN; 0030;0;0;0;N;;;;; +1D7ED;MATHEMATICAL SANS-SERIF BOLD DIGIT ONE;Nd;0;EN; 0031;1;1;1;N;;;;; +1D7EE;MATHEMATICAL SANS-SERIF BOLD DIGIT TWO;Nd;0;EN; 0032;2;2;2;N;;;;; +1D7EF;MATHEMATICAL SANS-SERIF BOLD DIGIT THREE;Nd;0;EN; 0033;3;3;3;N;;;;; +1D7F0;MATHEMATICAL SANS-SERIF BOLD DIGIT FOUR;Nd;0;EN; 0034;4;4;4;N;;;;; +1D7F1;MATHEMATICAL SANS-SERIF BOLD DIGIT FIVE;Nd;0;EN; 0035;5;5;5;N;;;;; +1D7F2;MATHEMATICAL SANS-SERIF BOLD DIGIT SIX;Nd;0;EN; 0036;6;6;6;N;;;;; +1D7F3;MATHEMATICAL SANS-SERIF BOLD DIGIT SEVEN;Nd;0;EN; 0037;7;7;7;N;;;;; +1D7F4;MATHEMATICAL SANS-SERIF BOLD DIGIT EIGHT;Nd;0;EN; 0038;8;8;8;N;;;;; +1D7F5;MATHEMATICAL SANS-SERIF BOLD DIGIT NINE;Nd;0;EN; 0039;9;9;9;N;;;;; +1D7F6;MATHEMATICAL MONOSPACE DIGIT ZERO;Nd;0;EN; 0030;0;0;0;N;;;;; +1D7F7;MATHEMATICAL MONOSPACE DIGIT ONE;Nd;0;EN; 0031;1;1;1;N;;;;; +1D7F8;MATHEMATICAL MONOSPACE DIGIT TWO;Nd;0;EN; 0032;2;2;2;N;;;;; +1D7F9;MATHEMATICAL MONOSPACE DIGIT THREE;Nd;0;EN; 0033;3;3;3;N;;;;; +1D7FA;MATHEMATICAL MONOSPACE DIGIT FOUR;Nd;0;EN; 0034;4;4;4;N;;;;; +1D7FB;MATHEMATICAL MONOSPACE DIGIT FIVE;Nd;0;EN; 0035;5;5;5;N;;;;; +1D7FC;MATHEMATICAL MONOSPACE DIGIT SIX;Nd;0;EN; 0036;6;6;6;N;;;;; +1D7FD;MATHEMATICAL MONOSPACE DIGIT SEVEN;Nd;0;EN; 0037;7;7;7;N;;;;; +1D7FE;MATHEMATICAL MONOSPACE DIGIT EIGHT;Nd;0;EN; 0038;8;8;8;N;;;;; +1D7FF;MATHEMATICAL MONOSPACE DIGIT NINE;Nd;0;EN; 0039;9;9;9;N;;;;; +1EE00;ARABIC MATHEMATICAL ALEF;Lo;0;AL; 0627;;;;N;;;;; +1EE01;ARABIC MATHEMATICAL BEH;Lo;0;AL; 0628;;;;N;;;;; +1EE02;ARABIC MATHEMATICAL JEEM;Lo;0;AL; 062C;;;;N;;;;; +1EE03;ARABIC MATHEMATICAL DAL;Lo;0;AL; 062F;;;;N;;;;; +1EE05;ARABIC MATHEMATICAL WAW;Lo;0;AL; 0648;;;;N;;;;; +1EE06;ARABIC MATHEMATICAL ZAIN;Lo;0;AL; 0632;;;;N;;;;; +1EE07;ARABIC MATHEMATICAL HAH;Lo;0;AL; 062D;;;;N;;;;; +1EE08;ARABIC MATHEMATICAL TAH;Lo;0;AL; 0637;;;;N;;;;; +1EE09;ARABIC MATHEMATICAL YEH;Lo;0;AL; 064A;;;;N;;;;; +1EE0A;ARABIC MATHEMATICAL KAF;Lo;0;AL; 0643;;;;N;;;;; +1EE0B;ARABIC MATHEMATICAL LAM;Lo;0;AL; 0644;;;;N;;;;; +1EE0C;ARABIC MATHEMATICAL MEEM;Lo;0;AL; 0645;;;;N;;;;; +1EE0D;ARABIC MATHEMATICAL NOON;Lo;0;AL; 0646;;;;N;;;;; +1EE0E;ARABIC MATHEMATICAL SEEN;Lo;0;AL; 0633;;;;N;;;;; +1EE0F;ARABIC MATHEMATICAL AIN;Lo;0;AL; 0639;;;;N;;;;; +1EE10;ARABIC MATHEMATICAL FEH;Lo;0;AL; 0641;;;;N;;;;; +1EE11;ARABIC MATHEMATICAL SAD;Lo;0;AL; 0635;;;;N;;;;; +1EE12;ARABIC MATHEMATICAL QAF;Lo;0;AL; 0642;;;;N;;;;; +1EE13;ARABIC MATHEMATICAL REH;Lo;0;AL; 0631;;;;N;;;;; +1EE14;ARABIC MATHEMATICAL SHEEN;Lo;0;AL; 0634;;;;N;;;;; +1EE15;ARABIC MATHEMATICAL TEH;Lo;0;AL; 062A;;;;N;;;;; +1EE16;ARABIC MATHEMATICAL THEH;Lo;0;AL; 062B;;;;N;;;;; +1EE17;ARABIC MATHEMATICAL KHAH;Lo;0;AL; 062E;;;;N;;;;; +1EE18;ARABIC MATHEMATICAL THAL;Lo;0;AL; 0630;;;;N;;;;; +1EE19;ARABIC MATHEMATICAL DAD;Lo;0;AL; 0636;;;;N;;;;; +1EE1A;ARABIC MATHEMATICAL ZAH;Lo;0;AL; 0638;;;;N;;;;; +1EE1B;ARABIC MATHEMATICAL GHAIN;Lo;0;AL; 063A;;;;N;;;;; +1EE1C;ARABIC MATHEMATICAL DOTLESS BEH;Lo;0;AL; 066E;;;;N;;;;; +1EE1D;ARABIC MATHEMATICAL DOTLESS NOON;Lo;0;AL; 06BA;;;;N;;;;; +1EE1E;ARABIC MATHEMATICAL DOTLESS FEH;Lo;0;AL; 06A1;;;;N;;;;; +1EE1F;ARABIC MATHEMATICAL DOTLESS QAF;Lo;0;AL; 066F;;;;N;;;;; +1EE21;ARABIC MATHEMATICAL INITIAL BEH;Lo;0;AL; 0628;;;;N;;;;; +1EE22;ARABIC MATHEMATICAL INITIAL JEEM;Lo;0;AL; 062C;;;;N;;;;; +1EE24;ARABIC MATHEMATICAL INITIAL HEH;Lo;0;AL; 0647;;;;N;;;;; +1EE27;ARABIC MATHEMATICAL INITIAL HAH;Lo;0;AL; 062D;;;;N;;;;; +1EE29;ARABIC MATHEMATICAL INITIAL YEH;Lo;0;AL; 064A;;;;N;;;;; +1EE2A;ARABIC MATHEMATICAL INITIAL KAF;Lo;0;AL; 0643;;;;N;;;;; +1EE2B;ARABIC MATHEMATICAL INITIAL LAM;Lo;0;AL; 0644;;;;N;;;;; +1EE2C;ARABIC MATHEMATICAL INITIAL MEEM;Lo;0;AL; 0645;;;;N;;;;; +1EE2D;ARABIC MATHEMATICAL INITIAL NOON;Lo;0;AL; 0646;;;;N;;;;; +1EE2E;ARABIC MATHEMATICAL INITIAL SEEN;Lo;0;AL; 0633;;;;N;;;;; +1EE2F;ARABIC MATHEMATICAL INITIAL AIN;Lo;0;AL; 0639;;;;N;;;;; +1EE30;ARABIC MATHEMATICAL INITIAL FEH;Lo;0;AL; 0641;;;;N;;;;; +1EE31;ARABIC MATHEMATICAL INITIAL SAD;Lo;0;AL; 0635;;;;N;;;;; +1EE32;ARABIC MATHEMATICAL INITIAL QAF;Lo;0;AL; 0642;;;;N;;;;; +1EE34;ARABIC MATHEMATICAL INITIAL SHEEN;Lo;0;AL; 0634;;;;N;;;;; +1EE35;ARABIC MATHEMATICAL INITIAL TEH;Lo;0;AL; 062A;;;;N;;;;; +1EE36;ARABIC MATHEMATICAL INITIAL THEH;Lo;0;AL; 062B;;;;N;;;;; +1EE37;ARABIC MATHEMATICAL INITIAL KHAH;Lo;0;AL; 062E;;;;N;;;;; +1EE39;ARABIC MATHEMATICAL INITIAL DAD;Lo;0;AL; 0636;;;;N;;;;; +1EE3B;ARABIC MATHEMATICAL INITIAL GHAIN;Lo;0;AL; 063A;;;;N;;;;; +1EE42;ARABIC MATHEMATICAL TAILED JEEM;Lo;0;AL; 062C;;;;N;;;;; +1EE47;ARABIC MATHEMATICAL TAILED HAH;Lo;0;AL; 062D;;;;N;;;;; +1EE49;ARABIC MATHEMATICAL TAILED YEH;Lo;0;AL; 064A;;;;N;;;;; +1EE4B;ARABIC MATHEMATICAL TAILED LAM;Lo;0;AL; 0644;;;;N;;;;; +1EE4D;ARABIC MATHEMATICAL TAILED NOON;Lo;0;AL; 0646;;;;N;;;;; +1EE4E;ARABIC MATHEMATICAL TAILED SEEN;Lo;0;AL; 0633;;;;N;;;;; +1EE4F;ARABIC MATHEMATICAL TAILED AIN;Lo;0;AL; 0639;;;;N;;;;; +1EE51;ARABIC MATHEMATICAL TAILED SAD;Lo;0;AL; 0635;;;;N;;;;; +1EE52;ARABIC MATHEMATICAL TAILED QAF;Lo;0;AL; 0642;;;;N;;;;; +1EE54;ARABIC MATHEMATICAL TAILED SHEEN;Lo;0;AL; 0634;;;;N;;;;; +1EE57;ARABIC MATHEMATICAL TAILED KHAH;Lo;0;AL; 062E;;;;N;;;;; +1EE59;ARABIC MATHEMATICAL TAILED DAD;Lo;0;AL; 0636;;;;N;;;;; +1EE5B;ARABIC MATHEMATICAL TAILED GHAIN;Lo;0;AL; 063A;;;;N;;;;; +1EE5D;ARABIC MATHEMATICAL TAILED DOTLESS NOON;Lo;0;AL; 06BA;;;;N;;;;; +1EE5F;ARABIC MATHEMATICAL TAILED DOTLESS QAF;Lo;0;AL; 066F;;;;N;;;;; +1EE61;ARABIC MATHEMATICAL STRETCHED BEH;Lo;0;AL; 0628;;;;N;;;;; +1EE62;ARABIC MATHEMATICAL STRETCHED JEEM;Lo;0;AL; 062C;;;;N;;;;; +1EE64;ARABIC MATHEMATICAL STRETCHED HEH;Lo;0;AL; 0647;;;;N;;;;; +1EE67;ARABIC MATHEMATICAL STRETCHED HAH;Lo;0;AL; 062D;;;;N;;;;; +1EE68;ARABIC MATHEMATICAL STRETCHED TAH;Lo;0;AL; 0637;;;;N;;;;; +1EE69;ARABIC MATHEMATICAL STRETCHED YEH;Lo;0;AL; 064A;;;;N;;;;; +1EE6A;ARABIC MATHEMATICAL STRETCHED KAF;Lo;0;AL; 0643;;;;N;;;;; +1EE6C;ARABIC MATHEMATICAL STRETCHED MEEM;Lo;0;AL; 0645;;;;N;;;;; +1EE6D;ARABIC MATHEMATICAL STRETCHED NOON;Lo;0;AL; 0646;;;;N;;;;; +1EE6E;ARABIC MATHEMATICAL STRETCHED SEEN;Lo;0;AL; 0633;;;;N;;;;; +1EE6F;ARABIC MATHEMATICAL STRETCHED AIN;Lo;0;AL; 0639;;;;N;;;;; +1EE70;ARABIC MATHEMATICAL STRETCHED FEH;Lo;0;AL; 0641;;;;N;;;;; +1EE71;ARABIC MATHEMATICAL STRETCHED SAD;Lo;0;AL; 0635;;;;N;;;;; +1EE72;ARABIC MATHEMATICAL STRETCHED QAF;Lo;0;AL; 0642;;;;N;;;;; +1EE74;ARABIC MATHEMATICAL STRETCHED SHEEN;Lo;0;AL; 0634;;;;N;;;;; +1EE75;ARABIC MATHEMATICAL STRETCHED TEH;Lo;0;AL; 062A;;;;N;;;;; +1EE76;ARABIC MATHEMATICAL STRETCHED THEH;Lo;0;AL; 062B;;;;N;;;;; +1EE77;ARABIC MATHEMATICAL STRETCHED KHAH;Lo;0;AL; 062E;;;;N;;;;; +1EE79;ARABIC MATHEMATICAL STRETCHED DAD;Lo;0;AL; 0636;;;;N;;;;; +1EE7A;ARABIC MATHEMATICAL STRETCHED ZAH;Lo;0;AL; 0638;;;;N;;;;; +1EE7B;ARABIC MATHEMATICAL STRETCHED GHAIN;Lo;0;AL; 063A;;;;N;;;;; +1EE7C;ARABIC MATHEMATICAL STRETCHED DOTLESS BEH;Lo;0;AL; 066E;;;;N;;;;; +1EE7E;ARABIC MATHEMATICAL STRETCHED DOTLESS FEH;Lo;0;AL; 06A1;;;;N;;;;; +1EE80;ARABIC MATHEMATICAL LOOPED ALEF;Lo;0;AL; 0627;;;;N;;;;; +1EE81;ARABIC MATHEMATICAL LOOPED BEH;Lo;0;AL; 0628;;;;N;;;;; +1EE82;ARABIC MATHEMATICAL LOOPED JEEM;Lo;0;AL; 062C;;;;N;;;;; +1EE83;ARABIC MATHEMATICAL LOOPED DAL;Lo;0;AL; 062F;;;;N;;;;; +1EE84;ARABIC MATHEMATICAL LOOPED HEH;Lo;0;AL; 0647;;;;N;;;;; +1EE85;ARABIC MATHEMATICAL LOOPED WAW;Lo;0;AL; 0648;;;;N;;;;; +1EE86;ARABIC MATHEMATICAL LOOPED ZAIN;Lo;0;AL; 0632;;;;N;;;;; +1EE87;ARABIC MATHEMATICAL LOOPED HAH;Lo;0;AL; 062D;;;;N;;;;; +1EE88;ARABIC MATHEMATICAL LOOPED TAH;Lo;0;AL; 0637;;;;N;;;;; +1EE89;ARABIC MATHEMATICAL LOOPED YEH;Lo;0;AL; 064A;;;;N;;;;; +1EE8B;ARABIC MATHEMATICAL LOOPED LAM;Lo;0;AL; 0644;;;;N;;;;; +1EE8C;ARABIC MATHEMATICAL LOOPED MEEM;Lo;0;AL; 0645;;;;N;;;;; +1EE8D;ARABIC MATHEMATICAL LOOPED NOON;Lo;0;AL; 0646;;;;N;;;;; +1EE8E;ARABIC MATHEMATICAL LOOPED SEEN;Lo;0;AL; 0633;;;;N;;;;; +1EE8F;ARABIC MATHEMATICAL LOOPED AIN;Lo;0;AL; 0639;;;;N;;;;; +1EE90;ARABIC MATHEMATICAL LOOPED FEH;Lo;0;AL; 0641;;;;N;;;;; +1EE91;ARABIC MATHEMATICAL LOOPED SAD;Lo;0;AL; 0635;;;;N;;;;; +1EE92;ARABIC MATHEMATICAL LOOPED QAF;Lo;0;AL; 0642;;;;N;;;;; +1EE93;ARABIC MATHEMATICAL LOOPED REH;Lo;0;AL; 0631;;;;N;;;;; +1EE94;ARABIC MATHEMATICAL LOOPED SHEEN;Lo;0;AL; 0634;;;;N;;;;; +1EE95;ARABIC MATHEMATICAL LOOPED TEH;Lo;0;AL; 062A;;;;N;;;;; +1EE96;ARABIC MATHEMATICAL LOOPED THEH;Lo;0;AL; 062B;;;;N;;;;; +1EE97;ARABIC MATHEMATICAL LOOPED KHAH;Lo;0;AL; 062E;;;;N;;;;; +1EE98;ARABIC MATHEMATICAL LOOPED THAL;Lo;0;AL; 0630;;;;N;;;;; +1EE99;ARABIC MATHEMATICAL LOOPED DAD;Lo;0;AL; 0636;;;;N;;;;; +1EE9A;ARABIC MATHEMATICAL LOOPED ZAH;Lo;0;AL; 0638;;;;N;;;;; +1EE9B;ARABIC MATHEMATICAL LOOPED GHAIN;Lo;0;AL; 063A;;;;N;;;;; +1EEA1;ARABIC MATHEMATICAL DOUBLE-STRUCK BEH;Lo;0;AL; 0628;;;;N;;;;; +1EEA2;ARABIC MATHEMATICAL DOUBLE-STRUCK JEEM;Lo;0;AL; 062C;;;;N;;;;; +1EEA3;ARABIC MATHEMATICAL DOUBLE-STRUCK DAL;Lo;0;AL; 062F;;;;N;;;;; +1EEA5;ARABIC MATHEMATICAL DOUBLE-STRUCK WAW;Lo;0;AL; 0648;;;;N;;;;; +1EEA6;ARABIC MATHEMATICAL DOUBLE-STRUCK ZAIN;Lo;0;AL; 0632;;;;N;;;;; +1EEA7;ARABIC MATHEMATICAL DOUBLE-STRUCK HAH;Lo;0;AL; 062D;;;;N;;;;; +1EEA8;ARABIC MATHEMATICAL DOUBLE-STRUCK TAH;Lo;0;AL; 0637;;;;N;;;;; +1EEA9;ARABIC MATHEMATICAL DOUBLE-STRUCK YEH;Lo;0;AL; 064A;;;;N;;;;; +1EEAB;ARABIC MATHEMATICAL DOUBLE-STRUCK LAM;Lo;0;AL; 0644;;;;N;;;;; +1EEAC;ARABIC MATHEMATICAL DOUBLE-STRUCK MEEM;Lo;0;AL; 0645;;;;N;;;;; +1EEAD;ARABIC MATHEMATICAL DOUBLE-STRUCK NOON;Lo;0;AL; 0646;;;;N;;;;; +1EEAE;ARABIC MATHEMATICAL DOUBLE-STRUCK SEEN;Lo;0;AL; 0633;;;;N;;;;; +1EEAF;ARABIC MATHEMATICAL DOUBLE-STRUCK AIN;Lo;0;AL; 0639;;;;N;;;;; +1EEB0;ARABIC MATHEMATICAL DOUBLE-STRUCK FEH;Lo;0;AL; 0641;;;;N;;;;; +1EEB1;ARABIC MATHEMATICAL DOUBLE-STRUCK SAD;Lo;0;AL; 0635;;;;N;;;;; +1EEB2;ARABIC MATHEMATICAL DOUBLE-STRUCK QAF;Lo;0;AL; 0642;;;;N;;;;; +1EEB3;ARABIC MATHEMATICAL DOUBLE-STRUCK REH;Lo;0;AL; 0631;;;;N;;;;; +1EEB4;ARABIC MATHEMATICAL DOUBLE-STRUCK SHEEN;Lo;0;AL; 0634;;;;N;;;;; +1EEB5;ARABIC MATHEMATICAL DOUBLE-STRUCK TEH;Lo;0;AL; 062A;;;;N;;;;; +1EEB6;ARABIC MATHEMATICAL DOUBLE-STRUCK THEH;Lo;0;AL; 062B;;;;N;;;;; +1EEB7;ARABIC MATHEMATICAL DOUBLE-STRUCK KHAH;Lo;0;AL; 062E;;;;N;;;;; +1EEB8;ARABIC MATHEMATICAL DOUBLE-STRUCK THAL;Lo;0;AL; 0630;;;;N;;;;; +1EEB9;ARABIC MATHEMATICAL DOUBLE-STRUCK DAD;Lo;0;AL; 0636;;;;N;;;;; +1EEBA;ARABIC MATHEMATICAL DOUBLE-STRUCK ZAH;Lo;0;AL; 0638;;;;N;;;;; +1EEBB;ARABIC MATHEMATICAL DOUBLE-STRUCK GHAIN;Lo;0;AL; 063A;;;;N;;;;; +1EEF0;ARABIC MATHEMATICAL OPERATOR MEEM WITH HAH WITH TATWEEL;Sm;0;ON;;;;;N;;;;; +1EEF1;ARABIC MATHEMATICAL OPERATOR HAH WITH DAL;Sm;0;ON;;;;;N;;;;; +1F000;MAHJONG TILE EAST WIND;So;0;ON;;;;;N;;;;; +1F001;MAHJONG TILE SOUTH WIND;So;0;ON;;;;;N;;;;; +1F002;MAHJONG TILE WEST WIND;So;0;ON;;;;;N;;;;; +1F003;MAHJONG TILE NORTH WIND;So;0;ON;;;;;N;;;;; +1F004;MAHJONG TILE RED DRAGON;So;0;ON;;;;;N;;;;; +1F005;MAHJONG TILE GREEN DRAGON;So;0;ON;;;;;N;;;;; +1F006;MAHJONG TILE WHITE DRAGON;So;0;ON;;;;;N;;;;; +1F007;MAHJONG TILE ONE OF CHARACTERS;So;0;ON;;;;;N;;;;; +1F008;MAHJONG TILE TWO OF CHARACTERS;So;0;ON;;;;;N;;;;; +1F009;MAHJONG TILE THREE OF CHARACTERS;So;0;ON;;;;;N;;;;; +1F00A;MAHJONG TILE FOUR OF CHARACTERS;So;0;ON;;;;;N;;;;; +1F00B;MAHJONG TILE FIVE OF CHARACTERS;So;0;ON;;;;;N;;;;; +1F00C;MAHJONG TILE SIX OF CHARACTERS;So;0;ON;;;;;N;;;;; +1F00D;MAHJONG TILE SEVEN OF CHARACTERS;So;0;ON;;;;;N;;;;; +1F00E;MAHJONG TILE EIGHT OF CHARACTERS;So;0;ON;;;;;N;;;;; +1F00F;MAHJONG TILE NINE OF CHARACTERS;So;0;ON;;;;;N;;;;; +1F010;MAHJONG TILE ONE OF BAMBOOS;So;0;ON;;;;;N;;;;; +1F011;MAHJONG TILE TWO OF BAMBOOS;So;0;ON;;;;;N;;;;; +1F012;MAHJONG TILE THREE OF BAMBOOS;So;0;ON;;;;;N;;;;; +1F013;MAHJONG TILE FOUR OF BAMBOOS;So;0;ON;;;;;N;;;;; +1F014;MAHJONG TILE FIVE OF BAMBOOS;So;0;ON;;;;;N;;;;; +1F015;MAHJONG TILE SIX OF BAMBOOS;So;0;ON;;;;;N;;;;; +1F016;MAHJONG TILE SEVEN OF BAMBOOS;So;0;ON;;;;;N;;;;; +1F017;MAHJONG TILE EIGHT OF BAMBOOS;So;0;ON;;;;;N;;;;; +1F018;MAHJONG TILE NINE OF BAMBOOS;So;0;ON;;;;;N;;;;; +1F019;MAHJONG TILE ONE OF CIRCLES;So;0;ON;;;;;N;;;;; +1F01A;MAHJONG TILE TWO OF CIRCLES;So;0;ON;;;;;N;;;;; +1F01B;MAHJONG TILE THREE OF CIRCLES;So;0;ON;;;;;N;;;;; +1F01C;MAHJONG TILE FOUR OF CIRCLES;So;0;ON;;;;;N;;;;; +1F01D;MAHJONG TILE FIVE OF CIRCLES;So;0;ON;;;;;N;;;;; +1F01E;MAHJONG TILE SIX OF CIRCLES;So;0;ON;;;;;N;;;;; +1F01F;MAHJONG TILE SEVEN OF CIRCLES;So;0;ON;;;;;N;;;;; +1F020;MAHJONG TILE EIGHT OF CIRCLES;So;0;ON;;;;;N;;;;; +1F021;MAHJONG TILE NINE OF CIRCLES;So;0;ON;;;;;N;;;;; +1F022;MAHJONG TILE PLUM;So;0;ON;;;;;N;;;;; +1F023;MAHJONG TILE ORCHID;So;0;ON;;;;;N;;;;; +1F024;MAHJONG TILE BAMBOO;So;0;ON;;;;;N;;;;; +1F025;MAHJONG TILE CHRYSANTHEMUM;So;0;ON;;;;;N;;;;; +1F026;MAHJONG TILE SPRING;So;0;ON;;;;;N;;;;; +1F027;MAHJONG TILE SUMMER;So;0;ON;;;;;N;;;;; +1F028;MAHJONG TILE AUTUMN;So;0;ON;;;;;N;;;;; +1F029;MAHJONG TILE WINTER;So;0;ON;;;;;N;;;;; +1F02A;MAHJONG TILE JOKER;So;0;ON;;;;;N;;;;; +1F02B;MAHJONG TILE BACK;So;0;ON;;;;;N;;;;; +1F030;DOMINO TILE HORIZONTAL BACK;So;0;ON;;;;;N;;;;; +1F031;DOMINO TILE HORIZONTAL-00-00;So;0;ON;;;;;N;;;;; +1F032;DOMINO TILE HORIZONTAL-00-01;So;0;ON;;;;;N;;;;; +1F033;DOMINO TILE HORIZONTAL-00-02;So;0;ON;;;;;N;;;;; +1F034;DOMINO TILE HORIZONTAL-00-03;So;0;ON;;;;;N;;;;; +1F035;DOMINO TILE HORIZONTAL-00-04;So;0;ON;;;;;N;;;;; +1F036;DOMINO TILE HORIZONTAL-00-05;So;0;ON;;;;;N;;;;; +1F037;DOMINO TILE HORIZONTAL-00-06;So;0;ON;;;;;N;;;;; +1F038;DOMINO TILE HORIZONTAL-01-00;So;0;ON;;;;;N;;;;; +1F039;DOMINO TILE HORIZONTAL-01-01;So;0;ON;;;;;N;;;;; +1F03A;DOMINO TILE HORIZONTAL-01-02;So;0;ON;;;;;N;;;;; +1F03B;DOMINO TILE HORIZONTAL-01-03;So;0;ON;;;;;N;;;;; +1F03C;DOMINO TILE HORIZONTAL-01-04;So;0;ON;;;;;N;;;;; +1F03D;DOMINO TILE HORIZONTAL-01-05;So;0;ON;;;;;N;;;;; +1F03E;DOMINO TILE HORIZONTAL-01-06;So;0;ON;;;;;N;;;;; +1F03F;DOMINO TILE HORIZONTAL-02-00;So;0;ON;;;;;N;;;;; +1F040;DOMINO TILE HORIZONTAL-02-01;So;0;ON;;;;;N;;;;; +1F041;DOMINO TILE HORIZONTAL-02-02;So;0;ON;;;;;N;;;;; +1F042;DOMINO TILE HORIZONTAL-02-03;So;0;ON;;;;;N;;;;; +1F043;DOMINO TILE HORIZONTAL-02-04;So;0;ON;;;;;N;;;;; +1F044;DOMINO TILE HORIZONTAL-02-05;So;0;ON;;;;;N;;;;; +1F045;DOMINO TILE HORIZONTAL-02-06;So;0;ON;;;;;N;;;;; +1F046;DOMINO TILE HORIZONTAL-03-00;So;0;ON;;;;;N;;;;; +1F047;DOMINO TILE HORIZONTAL-03-01;So;0;ON;;;;;N;;;;; +1F048;DOMINO TILE HORIZONTAL-03-02;So;0;ON;;;;;N;;;;; +1F049;DOMINO TILE HORIZONTAL-03-03;So;0;ON;;;;;N;;;;; +1F04A;DOMINO TILE HORIZONTAL-03-04;So;0;ON;;;;;N;;;;; +1F04B;DOMINO TILE HORIZONTAL-03-05;So;0;ON;;;;;N;;;;; +1F04C;DOMINO TILE HORIZONTAL-03-06;So;0;ON;;;;;N;;;;; +1F04D;DOMINO TILE HORIZONTAL-04-00;So;0;ON;;;;;N;;;;; +1F04E;DOMINO TILE HORIZONTAL-04-01;So;0;ON;;;;;N;;;;; +1F04F;DOMINO TILE HORIZONTAL-04-02;So;0;ON;;;;;N;;;;; +1F050;DOMINO TILE HORIZONTAL-04-03;So;0;ON;;;;;N;;;;; +1F051;DOMINO TILE HORIZONTAL-04-04;So;0;ON;;;;;N;;;;; +1F052;DOMINO TILE HORIZONTAL-04-05;So;0;ON;;;;;N;;;;; +1F053;DOMINO TILE HORIZONTAL-04-06;So;0;ON;;;;;N;;;;; +1F054;DOMINO TILE HORIZONTAL-05-00;So;0;ON;;;;;N;;;;; +1F055;DOMINO TILE HORIZONTAL-05-01;So;0;ON;;;;;N;;;;; +1F056;DOMINO TILE HORIZONTAL-05-02;So;0;ON;;;;;N;;;;; +1F057;DOMINO TILE HORIZONTAL-05-03;So;0;ON;;;;;N;;;;; +1F058;DOMINO TILE HORIZONTAL-05-04;So;0;ON;;;;;N;;;;; +1F059;DOMINO TILE HORIZONTAL-05-05;So;0;ON;;;;;N;;;;; +1F05A;DOMINO TILE HORIZONTAL-05-06;So;0;ON;;;;;N;;;;; +1F05B;DOMINO TILE HORIZONTAL-06-00;So;0;ON;;;;;N;;;;; +1F05C;DOMINO TILE HORIZONTAL-06-01;So;0;ON;;;;;N;;;;; +1F05D;DOMINO TILE HORIZONTAL-06-02;So;0;ON;;;;;N;;;;; +1F05E;DOMINO TILE HORIZONTAL-06-03;So;0;ON;;;;;N;;;;; +1F05F;DOMINO TILE HORIZONTAL-06-04;So;0;ON;;;;;N;;;;; +1F060;DOMINO TILE HORIZONTAL-06-05;So;0;ON;;;;;N;;;;; +1F061;DOMINO TILE HORIZONTAL-06-06;So;0;ON;;;;;N;;;;; +1F062;DOMINO TILE VERTICAL BACK;So;0;ON;;;;;N;;;;; +1F063;DOMINO TILE VERTICAL-00-00;So;0;ON;;;;;N;;;;; +1F064;DOMINO TILE VERTICAL-00-01;So;0;ON;;;;;N;;;;; +1F065;DOMINO TILE VERTICAL-00-02;So;0;ON;;;;;N;;;;; +1F066;DOMINO TILE VERTICAL-00-03;So;0;ON;;;;;N;;;;; +1F067;DOMINO TILE VERTICAL-00-04;So;0;ON;;;;;N;;;;; +1F068;DOMINO TILE VERTICAL-00-05;So;0;ON;;;;;N;;;;; +1F069;DOMINO TILE VERTICAL-00-06;So;0;ON;;;;;N;;;;; +1F06A;DOMINO TILE VERTICAL-01-00;So;0;ON;;;;;N;;;;; +1F06B;DOMINO TILE VERTICAL-01-01;So;0;ON;;;;;N;;;;; +1F06C;DOMINO TILE VERTICAL-01-02;So;0;ON;;;;;N;;;;; +1F06D;DOMINO TILE VERTICAL-01-03;So;0;ON;;;;;N;;;;; +1F06E;DOMINO TILE VERTICAL-01-04;So;0;ON;;;;;N;;;;; +1F06F;DOMINO TILE VERTICAL-01-05;So;0;ON;;;;;N;;;;; +1F070;DOMINO TILE VERTICAL-01-06;So;0;ON;;;;;N;;;;; +1F071;DOMINO TILE VERTICAL-02-00;So;0;ON;;;;;N;;;;; +1F072;DOMINO TILE VERTICAL-02-01;So;0;ON;;;;;N;;;;; +1F073;DOMINO TILE VERTICAL-02-02;So;0;ON;;;;;N;;;;; +1F074;DOMINO TILE VERTICAL-02-03;So;0;ON;;;;;N;;;;; +1F075;DOMINO TILE VERTICAL-02-04;So;0;ON;;;;;N;;;;; +1F076;DOMINO TILE VERTICAL-02-05;So;0;ON;;;;;N;;;;; +1F077;DOMINO TILE VERTICAL-02-06;So;0;ON;;;;;N;;;;; +1F078;DOMINO TILE VERTICAL-03-00;So;0;ON;;;;;N;;;;; +1F079;DOMINO TILE VERTICAL-03-01;So;0;ON;;;;;N;;;;; +1F07A;DOMINO TILE VERTICAL-03-02;So;0;ON;;;;;N;;;;; +1F07B;DOMINO TILE VERTICAL-03-03;So;0;ON;;;;;N;;;;; +1F07C;DOMINO TILE VERTICAL-03-04;So;0;ON;;;;;N;;;;; +1F07D;DOMINO TILE VERTICAL-03-05;So;0;ON;;;;;N;;;;; +1F07E;DOMINO TILE VERTICAL-03-06;So;0;ON;;;;;N;;;;; +1F07F;DOMINO TILE VERTICAL-04-00;So;0;ON;;;;;N;;;;; +1F080;DOMINO TILE VERTICAL-04-01;So;0;ON;;;;;N;;;;; +1F081;DOMINO TILE VERTICAL-04-02;So;0;ON;;;;;N;;;;; +1F082;DOMINO TILE VERTICAL-04-03;So;0;ON;;;;;N;;;;; +1F083;DOMINO TILE VERTICAL-04-04;So;0;ON;;;;;N;;;;; +1F084;DOMINO TILE VERTICAL-04-05;So;0;ON;;;;;N;;;;; +1F085;DOMINO TILE VERTICAL-04-06;So;0;ON;;;;;N;;;;; +1F086;DOMINO TILE VERTICAL-05-00;So;0;ON;;;;;N;;;;; +1F087;DOMINO TILE VERTICAL-05-01;So;0;ON;;;;;N;;;;; +1F088;DOMINO TILE VERTICAL-05-02;So;0;ON;;;;;N;;;;; +1F089;DOMINO TILE VERTICAL-05-03;So;0;ON;;;;;N;;;;; +1F08A;DOMINO TILE VERTICAL-05-04;So;0;ON;;;;;N;;;;; +1F08B;DOMINO TILE VERTICAL-05-05;So;0;ON;;;;;N;;;;; +1F08C;DOMINO TILE VERTICAL-05-06;So;0;ON;;;;;N;;;;; +1F08D;DOMINO TILE VERTICAL-06-00;So;0;ON;;;;;N;;;;; +1F08E;DOMINO TILE VERTICAL-06-01;So;0;ON;;;;;N;;;;; +1F08F;DOMINO TILE VERTICAL-06-02;So;0;ON;;;;;N;;;;; +1F090;DOMINO TILE VERTICAL-06-03;So;0;ON;;;;;N;;;;; +1F091;DOMINO TILE VERTICAL-06-04;So;0;ON;;;;;N;;;;; +1F092;DOMINO TILE VERTICAL-06-05;So;0;ON;;;;;N;;;;; +1F093;DOMINO TILE VERTICAL-06-06;So;0;ON;;;;;N;;;;; +1F0A0;PLAYING CARD BACK;So;0;ON;;;;;N;;;;; +1F0A1;PLAYING CARD ACE OF SPADES;So;0;ON;;;;;N;;;;; +1F0A2;PLAYING CARD TWO OF SPADES;So;0;ON;;;;;N;;;;; +1F0A3;PLAYING CARD THREE OF SPADES;So;0;ON;;;;;N;;;;; +1F0A4;PLAYING CARD FOUR OF SPADES;So;0;ON;;;;;N;;;;; +1F0A5;PLAYING CARD FIVE OF SPADES;So;0;ON;;;;;N;;;;; +1F0A6;PLAYING CARD SIX OF SPADES;So;0;ON;;;;;N;;;;; +1F0A7;PLAYING CARD SEVEN OF SPADES;So;0;ON;;;;;N;;;;; +1F0A8;PLAYING CARD EIGHT OF SPADES;So;0;ON;;;;;N;;;;; +1F0A9;PLAYING CARD NINE OF SPADES;So;0;ON;;;;;N;;;;; +1F0AA;PLAYING CARD TEN OF SPADES;So;0;ON;;;;;N;;;;; +1F0AB;PLAYING CARD JACK OF SPADES;So;0;ON;;;;;N;;;;; +1F0AC;PLAYING CARD KNIGHT OF SPADES;So;0;ON;;;;;N;;;;; +1F0AD;PLAYING CARD QUEEN OF SPADES;So;0;ON;;;;;N;;;;; +1F0AE;PLAYING CARD KING OF SPADES;So;0;ON;;;;;N;;;;; +1F0B1;PLAYING CARD ACE OF HEARTS;So;0;ON;;;;;N;;;;; +1F0B2;PLAYING CARD TWO OF HEARTS;So;0;ON;;;;;N;;;;; +1F0B3;PLAYING CARD THREE OF HEARTS;So;0;ON;;;;;N;;;;; +1F0B4;PLAYING CARD FOUR OF HEARTS;So;0;ON;;;;;N;;;;; +1F0B5;PLAYING CARD FIVE OF HEARTS;So;0;ON;;;;;N;;;;; +1F0B6;PLAYING CARD SIX OF HEARTS;So;0;ON;;;;;N;;;;; +1F0B7;PLAYING CARD SEVEN OF HEARTS;So;0;ON;;;;;N;;;;; +1F0B8;PLAYING CARD EIGHT OF HEARTS;So;0;ON;;;;;N;;;;; +1F0B9;PLAYING CARD NINE OF HEARTS;So;0;ON;;;;;N;;;;; +1F0BA;PLAYING CARD TEN OF HEARTS;So;0;ON;;;;;N;;;;; +1F0BB;PLAYING CARD JACK OF HEARTS;So;0;ON;;;;;N;;;;; +1F0BC;PLAYING CARD KNIGHT OF HEARTS;So;0;ON;;;;;N;;;;; +1F0BD;PLAYING CARD QUEEN OF HEARTS;So;0;ON;;;;;N;;;;; +1F0BE;PLAYING CARD KING OF HEARTS;So;0;ON;;;;;N;;;;; +1F0C1;PLAYING CARD ACE OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0C2;PLAYING CARD TWO OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0C3;PLAYING CARD THREE OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0C4;PLAYING CARD FOUR OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0C5;PLAYING CARD FIVE OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0C6;PLAYING CARD SIX OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0C7;PLAYING CARD SEVEN OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0C8;PLAYING CARD EIGHT OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0C9;PLAYING CARD NINE OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0CA;PLAYING CARD TEN OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0CB;PLAYING CARD JACK OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0CC;PLAYING CARD KNIGHT OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0CD;PLAYING CARD QUEEN OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0CE;PLAYING CARD KING OF DIAMONDS;So;0;ON;;;;;N;;;;; +1F0CF;PLAYING CARD BLACK JOKER;So;0;ON;;;;;N;;;;; +1F0D1;PLAYING CARD ACE OF CLUBS;So;0;ON;;;;;N;;;;; +1F0D2;PLAYING CARD TWO OF CLUBS;So;0;ON;;;;;N;;;;; +1F0D3;PLAYING CARD THREE OF CLUBS;So;0;ON;;;;;N;;;;; +1F0D4;PLAYING CARD FOUR OF CLUBS;So;0;ON;;;;;N;;;;; +1F0D5;PLAYING CARD FIVE OF CLUBS;So;0;ON;;;;;N;;;;; +1F0D6;PLAYING CARD SIX OF CLUBS;So;0;ON;;;;;N;;;;; +1F0D7;PLAYING CARD SEVEN OF CLUBS;So;0;ON;;;;;N;;;;; +1F0D8;PLAYING CARD EIGHT OF CLUBS;So;0;ON;;;;;N;;;;; +1F0D9;PLAYING CARD NINE OF CLUBS;So;0;ON;;;;;N;;;;; +1F0DA;PLAYING CARD TEN OF CLUBS;So;0;ON;;;;;N;;;;; +1F0DB;PLAYING CARD JACK OF CLUBS;So;0;ON;;;;;N;;;;; +1F0DC;PLAYING CARD KNIGHT OF CLUBS;So;0;ON;;;;;N;;;;; +1F0DD;PLAYING CARD QUEEN OF CLUBS;So;0;ON;;;;;N;;;;; +1F0DE;PLAYING CARD KING OF CLUBS;So;0;ON;;;;;N;;;;; +1F0DF;PLAYING CARD WHITE JOKER;So;0;ON;;;;;N;;;;; +1F100;DIGIT ZERO FULL STOP;No;0;EN; 0030 002E;;0;0;N;;;;; +1F101;DIGIT ZERO COMMA;No;0;EN; 0030 002C;;0;0;N;;;;; +1F102;DIGIT ONE COMMA;No;0;EN; 0031 002C;;1;1;N;;;;; +1F103;DIGIT TWO COMMA;No;0;EN; 0032 002C;;2;2;N;;;;; +1F104;DIGIT THREE COMMA;No;0;EN; 0033 002C;;3;3;N;;;;; +1F105;DIGIT FOUR COMMA;No;0;EN; 0034 002C;;4;4;N;;;;; +1F106;DIGIT FIVE COMMA;No;0;EN; 0035 002C;;5;5;N;;;;; +1F107;DIGIT SIX COMMA;No;0;EN; 0036 002C;;6;6;N;;;;; +1F108;DIGIT SEVEN COMMA;No;0;EN; 0037 002C;;7;7;N;;;;; +1F109;DIGIT EIGHT COMMA;No;0;EN; 0038 002C;;8;8;N;;;;; +1F10A;DIGIT NINE COMMA;No;0;EN; 0039 002C;;9;9;N;;;;; +1F110;PARENTHESIZED LATIN CAPITAL LETTER A;So;0;L; 0028 0041 0029;;;;N;;;;; +1F111;PARENTHESIZED LATIN CAPITAL LETTER B;So;0;L; 0028 0042 0029;;;;N;;;;; +1F112;PARENTHESIZED LATIN CAPITAL LETTER C;So;0;L; 0028 0043 0029;;;;N;;;;; +1F113;PARENTHESIZED LATIN CAPITAL LETTER D;So;0;L; 0028 0044 0029;;;;N;;;;; +1F114;PARENTHESIZED LATIN CAPITAL LETTER E;So;0;L; 0028 0045 0029;;;;N;;;;; +1F115;PARENTHESIZED LATIN CAPITAL LETTER F;So;0;L; 0028 0046 0029;;;;N;;;;; +1F116;PARENTHESIZED LATIN CAPITAL LETTER G;So;0;L; 0028 0047 0029;;;;N;;;;; +1F117;PARENTHESIZED LATIN CAPITAL LETTER H;So;0;L; 0028 0048 0029;;;;N;;;;; +1F118;PARENTHESIZED LATIN CAPITAL LETTER I;So;0;L; 0028 0049 0029;;;;N;;;;; +1F119;PARENTHESIZED LATIN CAPITAL LETTER J;So;0;L; 0028 004A 0029;;;;N;;;;; +1F11A;PARENTHESIZED LATIN CAPITAL LETTER K;So;0;L; 0028 004B 0029;;;;N;;;;; +1F11B;PARENTHESIZED LATIN CAPITAL LETTER L;So;0;L; 0028 004C 0029;;;;N;;;;; +1F11C;PARENTHESIZED LATIN CAPITAL LETTER M;So;0;L; 0028 004D 0029;;;;N;;;;; +1F11D;PARENTHESIZED LATIN CAPITAL LETTER N;So;0;L; 0028 004E 0029;;;;N;;;;; +1F11E;PARENTHESIZED LATIN CAPITAL LETTER O;So;0;L; 0028 004F 0029;;;;N;;;;; +1F11F;PARENTHESIZED LATIN CAPITAL LETTER P;So;0;L; 0028 0050 0029;;;;N;;;;; +1F120;PARENTHESIZED LATIN CAPITAL LETTER Q;So;0;L; 0028 0051 0029;;;;N;;;;; +1F121;PARENTHESIZED LATIN CAPITAL LETTER R;So;0;L; 0028 0052 0029;;;;N;;;;; +1F122;PARENTHESIZED LATIN CAPITAL LETTER S;So;0;L; 0028 0053 0029;;;;N;;;;; +1F123;PARENTHESIZED LATIN CAPITAL LETTER T;So;0;L; 0028 0054 0029;;;;N;;;;; +1F124;PARENTHESIZED LATIN CAPITAL LETTER U;So;0;L; 0028 0055 0029;;;;N;;;;; +1F125;PARENTHESIZED LATIN CAPITAL LETTER V;So;0;L; 0028 0056 0029;;;;N;;;;; +1F126;PARENTHESIZED LATIN CAPITAL LETTER W;So;0;L; 0028 0057 0029;;;;N;;;;; +1F127;PARENTHESIZED LATIN CAPITAL LETTER X;So;0;L; 0028 0058 0029;;;;N;;;;; +1F128;PARENTHESIZED LATIN CAPITAL LETTER Y;So;0;L; 0028 0059 0029;;;;N;;;;; +1F129;PARENTHESIZED LATIN CAPITAL LETTER Z;So;0;L; 0028 005A 0029;;;;N;;;;; +1F12A;TORTOISE SHELL BRACKETED LATIN CAPITAL LETTER S;So;0;L; 3014 0053 3015;;;;N;;;;; +1F12B;CIRCLED ITALIC LATIN CAPITAL LETTER C;So;0;L; 0043;;;;N;;;;; +1F12C;CIRCLED ITALIC LATIN CAPITAL LETTER R;So;0;L; 0052;;;;N;;;;; +1F12D;CIRCLED CD;So;0;L; 0043 0044;;;;N;;;;; +1F12E;CIRCLED WZ;So;0;L; 0057 005A;;;;N;;;;; +1F130;SQUARED LATIN CAPITAL LETTER A;So;0;L; 0041;;;;N;;;;; +1F131;SQUARED LATIN CAPITAL LETTER B;So;0;L; 0042;;;;N;;;;; +1F132;SQUARED LATIN CAPITAL LETTER C;So;0;L; 0043;;;;N;;;;; +1F133;SQUARED LATIN CAPITAL LETTER D;So;0;L; 0044;;;;N;;;;; +1F134;SQUARED LATIN CAPITAL LETTER E;So;0;L; 0045;;;;N;;;;; +1F135;SQUARED LATIN CAPITAL LETTER F;So;0;L; 0046;;;;N;;;;; +1F136;SQUARED LATIN CAPITAL LETTER G;So;0;L; 0047;;;;N;;;;; +1F137;SQUARED LATIN CAPITAL LETTER H;So;0;L; 0048;;;;N;;;;; +1F138;SQUARED LATIN CAPITAL LETTER I;So;0;L; 0049;;;;N;;;;; +1F139;SQUARED LATIN CAPITAL LETTER J;So;0;L; 004A;;;;N;;;;; +1F13A;SQUARED LATIN CAPITAL LETTER K;So;0;L; 004B;;;;N;;;;; +1F13B;SQUARED LATIN CAPITAL LETTER L;So;0;L; 004C;;;;N;;;;; +1F13C;SQUARED LATIN CAPITAL LETTER M;So;0;L; 004D;;;;N;;;;; +1F13D;SQUARED LATIN CAPITAL LETTER N;So;0;L; 004E;;;;N;;;;; +1F13E;SQUARED LATIN CAPITAL LETTER O;So;0;L; 004F;;;;N;;;;; +1F13F;SQUARED LATIN CAPITAL LETTER P;So;0;L; 0050;;;;N;;;;; +1F140;SQUARED LATIN CAPITAL LETTER Q;So;0;L; 0051;;;;N;;;;; +1F141;SQUARED LATIN CAPITAL LETTER R;So;0;L; 0052;;;;N;;;;; +1F142;SQUARED LATIN CAPITAL LETTER S;So;0;L; 0053;;;;N;;;;; +1F143;SQUARED LATIN CAPITAL LETTER T;So;0;L; 0054;;;;N;;;;; +1F144;SQUARED LATIN CAPITAL LETTER U;So;0;L; 0055;;;;N;;;;; +1F145;SQUARED LATIN CAPITAL LETTER V;So;0;L; 0056;;;;N;;;;; +1F146;SQUARED LATIN CAPITAL LETTER W;So;0;L; 0057;;;;N;;;;; +1F147;SQUARED LATIN CAPITAL LETTER X;So;0;L; 0058;;;;N;;;;; +1F148;SQUARED LATIN CAPITAL LETTER Y;So;0;L; 0059;;;;N;;;;; +1F149;SQUARED LATIN CAPITAL LETTER Z;So;0;L; 005A;;;;N;;;;; +1F14A;SQUARED HV;So;0;L; 0048 0056;;;;N;;;;; +1F14B;SQUARED MV;So;0;L; 004D 0056;;;;N;;;;; +1F14C;SQUARED SD;So;0;L; 0053 0044;;;;N;;;;; +1F14D;SQUARED SS;So;0;L; 0053 0053;;;;N;;;;; +1F14E;SQUARED PPV;So;0;L; 0050 0050 0056;;;;N;;;;; +1F14F;SQUARED WC;So;0;L; 0057 0043;;;;N;;;;; +1F150;NEGATIVE CIRCLED LATIN CAPITAL LETTER A;So;0;L;;;;;N;;;;; +1F151;NEGATIVE CIRCLED LATIN CAPITAL LETTER B;So;0;L;;;;;N;;;;; +1F152;NEGATIVE CIRCLED LATIN CAPITAL LETTER C;So;0;L;;;;;N;;;;; +1F153;NEGATIVE CIRCLED LATIN CAPITAL LETTER D;So;0;L;;;;;N;;;;; +1F154;NEGATIVE CIRCLED LATIN CAPITAL LETTER E;So;0;L;;;;;N;;;;; +1F155;NEGATIVE CIRCLED LATIN CAPITAL LETTER F;So;0;L;;;;;N;;;;; +1F156;NEGATIVE CIRCLED LATIN CAPITAL LETTER G;So;0;L;;;;;N;;;;; +1F157;NEGATIVE CIRCLED LATIN CAPITAL LETTER H;So;0;L;;;;;N;;;;; +1F158;NEGATIVE CIRCLED LATIN CAPITAL LETTER I;So;0;L;;;;;N;;;;; +1F159;NEGATIVE CIRCLED LATIN CAPITAL LETTER J;So;0;L;;;;;N;;;;; +1F15A;NEGATIVE CIRCLED LATIN CAPITAL LETTER K;So;0;L;;;;;N;;;;; +1F15B;NEGATIVE CIRCLED LATIN CAPITAL LETTER L;So;0;L;;;;;N;;;;; +1F15C;NEGATIVE CIRCLED LATIN CAPITAL LETTER M;So;0;L;;;;;N;;;;; +1F15D;NEGATIVE CIRCLED LATIN CAPITAL LETTER N;So;0;L;;;;;N;;;;; +1F15E;NEGATIVE CIRCLED LATIN CAPITAL LETTER O;So;0;L;;;;;N;;;;; +1F15F;NEGATIVE CIRCLED LATIN CAPITAL LETTER P;So;0;L;;;;;N;;;;; +1F160;NEGATIVE CIRCLED LATIN CAPITAL LETTER Q;So;0;L;;;;;N;;;;; +1F161;NEGATIVE CIRCLED LATIN CAPITAL LETTER R;So;0;L;;;;;N;;;;; +1F162;NEGATIVE CIRCLED LATIN CAPITAL LETTER S;So;0;L;;;;;N;;;;; +1F163;NEGATIVE CIRCLED LATIN CAPITAL LETTER T;So;0;L;;;;;N;;;;; +1F164;NEGATIVE CIRCLED LATIN CAPITAL LETTER U;So;0;L;;;;;N;;;;; +1F165;NEGATIVE CIRCLED LATIN CAPITAL LETTER V;So;0;L;;;;;N;;;;; +1F166;NEGATIVE CIRCLED LATIN CAPITAL LETTER W;So;0;L;;;;;N;;;;; +1F167;NEGATIVE CIRCLED LATIN CAPITAL LETTER X;So;0;L;;;;;N;;;;; +1F168;NEGATIVE CIRCLED LATIN CAPITAL LETTER Y;So;0;L;;;;;N;;;;; +1F169;NEGATIVE CIRCLED LATIN CAPITAL LETTER Z;So;0;L;;;;;N;;;;; +1F16A;RAISED MC SIGN;So;0;ON; 004D 0043;;;;N;;;;; +1F16B;RAISED MD SIGN;So;0;ON; 004D 0044;;;;N;;;;; +1F170;NEGATIVE SQUARED LATIN CAPITAL LETTER A;So;0;L;;;;;N;;;;; +1F171;NEGATIVE SQUARED LATIN CAPITAL LETTER B;So;0;L;;;;;N;;;;; +1F172;NEGATIVE SQUARED LATIN CAPITAL LETTER C;So;0;L;;;;;N;;;;; +1F173;NEGATIVE SQUARED LATIN CAPITAL LETTER D;So;0;L;;;;;N;;;;; +1F174;NEGATIVE SQUARED LATIN CAPITAL LETTER E;So;0;L;;;;;N;;;;; +1F175;NEGATIVE SQUARED LATIN CAPITAL LETTER F;So;0;L;;;;;N;;;;; +1F176;NEGATIVE SQUARED LATIN CAPITAL LETTER G;So;0;L;;;;;N;;;;; +1F177;NEGATIVE SQUARED LATIN CAPITAL LETTER H;So;0;L;;;;;N;;;;; +1F178;NEGATIVE SQUARED LATIN CAPITAL LETTER I;So;0;L;;;;;N;;;;; +1F179;NEGATIVE SQUARED LATIN CAPITAL LETTER J;So;0;L;;;;;N;;;;; +1F17A;NEGATIVE SQUARED LATIN CAPITAL LETTER K;So;0;L;;;;;N;;;;; +1F17B;NEGATIVE SQUARED LATIN CAPITAL LETTER L;So;0;L;;;;;N;;;;; +1F17C;NEGATIVE SQUARED LATIN CAPITAL LETTER M;So;0;L;;;;;N;;;;; +1F17D;NEGATIVE SQUARED LATIN CAPITAL LETTER N;So;0;L;;;;;N;;;;; +1F17E;NEGATIVE SQUARED LATIN CAPITAL LETTER O;So;0;L;;;;;N;;;;; +1F17F;NEGATIVE SQUARED LATIN CAPITAL LETTER P;So;0;L;;;;;N;;;;; +1F180;NEGATIVE SQUARED LATIN CAPITAL LETTER Q;So;0;L;;;;;N;;;;; +1F181;NEGATIVE SQUARED LATIN CAPITAL LETTER R;So;0;L;;;;;N;;;;; +1F182;NEGATIVE SQUARED LATIN CAPITAL LETTER S;So;0;L;;;;;N;;;;; +1F183;NEGATIVE SQUARED LATIN CAPITAL LETTER T;So;0;L;;;;;N;;;;; +1F184;NEGATIVE SQUARED LATIN CAPITAL LETTER U;So;0;L;;;;;N;;;;; +1F185;NEGATIVE SQUARED LATIN CAPITAL LETTER V;So;0;L;;;;;N;;;;; +1F186;NEGATIVE SQUARED LATIN CAPITAL LETTER W;So;0;L;;;;;N;;;;; +1F187;NEGATIVE SQUARED LATIN CAPITAL LETTER X;So;0;L;;;;;N;;;;; +1F188;NEGATIVE SQUARED LATIN CAPITAL LETTER Y;So;0;L;;;;;N;;;;; +1F189;NEGATIVE SQUARED LATIN CAPITAL LETTER Z;So;0;L;;;;;N;;;;; +1F18A;CROSSED NEGATIVE SQUARED LATIN CAPITAL LETTER P;So;0;L;;;;;N;;;;; +1F18B;NEGATIVE SQUARED IC;So;0;L;;;;;N;;;;; +1F18C;NEGATIVE SQUARED PA;So;0;L;;;;;N;;;;; +1F18D;NEGATIVE SQUARED SA;So;0;L;;;;;N;;;;; +1F18E;NEGATIVE SQUARED AB;So;0;L;;;;;N;;;;; +1F18F;NEGATIVE SQUARED WC;So;0;L;;;;;N;;;;; +1F190;SQUARE DJ;So;0;L; 0044 004A;;;;N;;;;; +1F191;SQUARED CL;So;0;L;;;;;N;;;;; +1F192;SQUARED COOL;So;0;L;;;;;N;;;;; +1F193;SQUARED FREE;So;0;L;;;;;N;;;;; +1F194;SQUARED ID;So;0;L;;;;;N;;;;; +1F195;SQUARED NEW;So;0;L;;;;;N;;;;; +1F196;SQUARED NG;So;0;L;;;;;N;;;;; +1F197;SQUARED OK;So;0;L;;;;;N;;;;; +1F198;SQUARED SOS;So;0;L;;;;;N;;;;; +1F199;SQUARED UP WITH EXCLAMATION MARK;So;0;L;;;;;N;;;;; +1F19A;SQUARED VS;So;0;L;;;;;N;;;;; +1F1E6;REGIONAL INDICATOR SYMBOL LETTER A;So;0;L;;;;;N;;;;; +1F1E7;REGIONAL INDICATOR SYMBOL LETTER B;So;0;L;;;;;N;;;;; +1F1E8;REGIONAL INDICATOR SYMBOL LETTER C;So;0;L;;;;;N;;;;; +1F1E9;REGIONAL INDICATOR SYMBOL LETTER D;So;0;L;;;;;N;;;;; +1F1EA;REGIONAL INDICATOR SYMBOL LETTER E;So;0;L;;;;;N;;;;; +1F1EB;REGIONAL INDICATOR SYMBOL LETTER F;So;0;L;;;;;N;;;;; +1F1EC;REGIONAL INDICATOR SYMBOL LETTER G;So;0;L;;;;;N;;;;; +1F1ED;REGIONAL INDICATOR SYMBOL LETTER H;So;0;L;;;;;N;;;;; +1F1EE;REGIONAL INDICATOR SYMBOL LETTER I;So;0;L;;;;;N;;;;; +1F1EF;REGIONAL INDICATOR SYMBOL LETTER J;So;0;L;;;;;N;;;;; +1F1F0;REGIONAL INDICATOR SYMBOL LETTER K;So;0;L;;;;;N;;;;; +1F1F1;REGIONAL INDICATOR SYMBOL LETTER L;So;0;L;;;;;N;;;;; +1F1F2;REGIONAL INDICATOR SYMBOL LETTER M;So;0;L;;;;;N;;;;; +1F1F3;REGIONAL INDICATOR SYMBOL LETTER N;So;0;L;;;;;N;;;;; +1F1F4;REGIONAL INDICATOR SYMBOL LETTER O;So;0;L;;;;;N;;;;; +1F1F5;REGIONAL INDICATOR SYMBOL LETTER P;So;0;L;;;;;N;;;;; +1F1F6;REGIONAL INDICATOR SYMBOL LETTER Q;So;0;L;;;;;N;;;;; +1F1F7;REGIONAL INDICATOR SYMBOL LETTER R;So;0;L;;;;;N;;;;; +1F1F8;REGIONAL INDICATOR SYMBOL LETTER S;So;0;L;;;;;N;;;;; +1F1F9;REGIONAL INDICATOR SYMBOL LETTER T;So;0;L;;;;;N;;;;; +1F1FA;REGIONAL INDICATOR SYMBOL LETTER U;So;0;L;;;;;N;;;;; +1F1FB;REGIONAL INDICATOR SYMBOL LETTER V;So;0;L;;;;;N;;;;; +1F1FC;REGIONAL INDICATOR SYMBOL LETTER W;So;0;L;;;;;N;;;;; +1F1FD;REGIONAL INDICATOR SYMBOL LETTER X;So;0;L;;;;;N;;;;; +1F1FE;REGIONAL INDICATOR SYMBOL LETTER Y;So;0;L;;;;;N;;;;; +1F1FF;REGIONAL INDICATOR SYMBOL LETTER Z;So;0;L;;;;;N;;;;; +1F200;SQUARE HIRAGANA HOKA;So;0;L; 307B 304B;;;;N;;;;; +1F201;SQUARED KATAKANA KOKO;So;0;L; 30B3 30B3;;;;N;;;;; +1F202;SQUARED KATAKANA SA;So;0;L; 30B5;;;;N;;;;; +1F210;SQUARED CJK UNIFIED IDEOGRAPH-624B;So;0;L; 624B;;;;N;;;;; +1F211;SQUARED CJK UNIFIED IDEOGRAPH-5B57;So;0;L; 5B57;;;;N;;;;; +1F212;SQUARED CJK UNIFIED IDEOGRAPH-53CC;So;0;L; 53CC;;;;N;;;;; +1F213;SQUARED KATAKANA DE;So;0;L; 30C7;;;;N;;;;; +1F214;SQUARED CJK UNIFIED IDEOGRAPH-4E8C;So;0;L; 4E8C;;;;N;;;;; +1F215;SQUARED CJK UNIFIED IDEOGRAPH-591A;So;0;L; 591A;;;;N;;;;; +1F216;SQUARED CJK UNIFIED IDEOGRAPH-89E3;So;0;L; 89E3;;;;N;;;;; +1F217;SQUARED CJK UNIFIED IDEOGRAPH-5929;So;0;L; 5929;;;;N;;;;; +1F218;SQUARED CJK UNIFIED IDEOGRAPH-4EA4;So;0;L; 4EA4;;;;N;;;;; +1F219;SQUARED CJK UNIFIED IDEOGRAPH-6620;So;0;L; 6620;;;;N;;;;; +1F21A;SQUARED CJK UNIFIED IDEOGRAPH-7121;So;0;L; 7121;;;;N;;;;; +1F21B;SQUARED CJK UNIFIED IDEOGRAPH-6599;So;0;L; 6599;;;;N;;;;; +1F21C;SQUARED CJK UNIFIED IDEOGRAPH-524D;So;0;L; 524D;;;;N;;;;; +1F21D;SQUARED CJK UNIFIED IDEOGRAPH-5F8C;So;0;L; 5F8C;;;;N;;;;; +1F21E;SQUARED CJK UNIFIED IDEOGRAPH-518D;So;0;L; 518D;;;;N;;;;; +1F21F;SQUARED CJK UNIFIED IDEOGRAPH-65B0;So;0;L; 65B0;;;;N;;;;; +1F220;SQUARED CJK UNIFIED IDEOGRAPH-521D;So;0;L; 521D;;;;N;;;;; +1F221;SQUARED CJK UNIFIED IDEOGRAPH-7D42;So;0;L; 7D42;;;;N;;;;; +1F222;SQUARED CJK UNIFIED IDEOGRAPH-751F;So;0;L; 751F;;;;N;;;;; +1F223;SQUARED CJK UNIFIED IDEOGRAPH-8CA9;So;0;L; 8CA9;;;;N;;;;; +1F224;SQUARED CJK UNIFIED IDEOGRAPH-58F0;So;0;L; 58F0;;;;N;;;;; +1F225;SQUARED CJK UNIFIED IDEOGRAPH-5439;So;0;L; 5439;;;;N;;;;; +1F226;SQUARED CJK UNIFIED IDEOGRAPH-6F14;So;0;L; 6F14;;;;N;;;;; +1F227;SQUARED CJK UNIFIED IDEOGRAPH-6295;So;0;L; 6295;;;;N;;;;; +1F228;SQUARED CJK UNIFIED IDEOGRAPH-6355;So;0;L; 6355;;;;N;;;;; +1F229;SQUARED CJK UNIFIED IDEOGRAPH-4E00;So;0;L; 4E00;;;;N;;;;; +1F22A;SQUARED CJK UNIFIED IDEOGRAPH-4E09;So;0;L; 4E09;;;;N;;;;; +1F22B;SQUARED CJK UNIFIED IDEOGRAPH-904A;So;0;L; 904A;;;;N;;;;; +1F22C;SQUARED CJK UNIFIED IDEOGRAPH-5DE6;So;0;L; 5DE6;;;;N;;;;; +1F22D;SQUARED CJK UNIFIED IDEOGRAPH-4E2D;So;0;L; 4E2D;;;;N;;;;; +1F22E;SQUARED CJK UNIFIED IDEOGRAPH-53F3;So;0;L; 53F3;;;;N;;;;; +1F22F;SQUARED CJK UNIFIED IDEOGRAPH-6307;So;0;L; 6307;;;;N;;;;; +1F230;SQUARED CJK UNIFIED IDEOGRAPH-8D70;So;0;L; 8D70;;;;N;;;;; +1F231;SQUARED CJK UNIFIED IDEOGRAPH-6253;So;0;L; 6253;;;;N;;;;; +1F232;SQUARED CJK UNIFIED IDEOGRAPH-7981;So;0;L; 7981;;;;N;;;;; +1F233;SQUARED CJK UNIFIED IDEOGRAPH-7A7A;So;0;L; 7A7A;;;;N;;;;; +1F234;SQUARED CJK UNIFIED IDEOGRAPH-5408;So;0;L; 5408;;;;N;;;;; +1F235;SQUARED CJK UNIFIED IDEOGRAPH-6E80;So;0;L; 6E80;;;;N;;;;; +1F236;SQUARED CJK UNIFIED IDEOGRAPH-6709;So;0;L; 6709;;;;N;;;;; +1F237;SQUARED CJK UNIFIED IDEOGRAPH-6708;So;0;L; 6708;;;;N;;;;; +1F238;SQUARED CJK UNIFIED IDEOGRAPH-7533;So;0;L; 7533;;;;N;;;;; +1F239;SQUARED CJK UNIFIED IDEOGRAPH-5272;So;0;L; 5272;;;;N;;;;; +1F23A;SQUARED CJK UNIFIED IDEOGRAPH-55B6;So;0;L; 55B6;;;;N;;;;; +1F240;TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH-672C;So;0;L; 3014 672C 3015;;;;N;;;;; +1F241;TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH-4E09;So;0;L; 3014 4E09 3015;;;;N;;;;; +1F242;TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH-4E8C;So;0;L; 3014 4E8C 3015;;;;N;;;;; +1F243;TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH-5B89;So;0;L; 3014 5B89 3015;;;;N;;;;; +1F244;TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH-70B9;So;0;L; 3014 70B9 3015;;;;N;;;;; +1F245;TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH-6253;So;0;L; 3014 6253 3015;;;;N;;;;; +1F246;TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH-76D7;So;0;L; 3014 76D7 3015;;;;N;;;;; +1F247;TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH-52DD;So;0;L; 3014 52DD 3015;;;;N;;;;; +1F248;TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH-6557;So;0;L; 3014 6557 3015;;;;N;;;;; +1F250;CIRCLED IDEOGRAPH ADVANTAGE;So;0;L; 5F97;;;;N;;;;; +1F251;CIRCLED IDEOGRAPH ACCEPT;So;0;L; 53EF;;;;N;;;;; +1F300;CYCLONE;So;0;ON;;;;;N;;;;; +1F301;FOGGY;So;0;ON;;;;;N;;;;; +1F302;CLOSED UMBRELLA;So;0;ON;;;;;N;;;;; +1F303;NIGHT WITH STARS;So;0;ON;;;;;N;;;;; +1F304;SUNRISE OVER MOUNTAINS;So;0;ON;;;;;N;;;;; +1F305;SUNRISE;So;0;ON;;;;;N;;;;; +1F306;CITYSCAPE AT DUSK;So;0;ON;;;;;N;;;;; +1F307;SUNSET OVER BUILDINGS;So;0;ON;;;;;N;;;;; +1F308;RAINBOW;So;0;ON;;;;;N;;;;; +1F309;BRIDGE AT NIGHT;So;0;ON;;;;;N;;;;; +1F30A;WATER WAVE;So;0;ON;;;;;N;;;;; +1F30B;VOLCANO;So;0;ON;;;;;N;;;;; +1F30C;MILKY WAY;So;0;ON;;;;;N;;;;; +1F30D;EARTH GLOBE EUROPE-AFRICA;So;0;ON;;;;;N;;;;; +1F30E;EARTH GLOBE AMERICAS;So;0;ON;;;;;N;;;;; +1F30F;EARTH GLOBE ASIA-AUSTRALIA;So;0;ON;;;;;N;;;;; +1F310;GLOBE WITH MERIDIANS;So;0;ON;;;;;N;;;;; +1F311;NEW MOON SYMBOL;So;0;ON;;;;;N;;;;; +1F312;WAXING CRESCENT MOON SYMBOL;So;0;ON;;;;;N;;;;; +1F313;FIRST QUARTER MOON SYMBOL;So;0;ON;;;;;N;;;;; +1F314;WAXING GIBBOUS MOON SYMBOL;So;0;ON;;;;;N;;;;; +1F315;FULL MOON SYMBOL;So;0;ON;;;;;N;;;;; +1F316;WANING GIBBOUS MOON SYMBOL;So;0;ON;;;;;N;;;;; +1F317;LAST QUARTER MOON SYMBOL;So;0;ON;;;;;N;;;;; +1F318;WANING CRESCENT MOON SYMBOL;So;0;ON;;;;;N;;;;; +1F319;CRESCENT MOON;So;0;ON;;;;;N;;;;; +1F31A;NEW MOON WITH FACE;So;0;ON;;;;;N;;;;; +1F31B;FIRST QUARTER MOON WITH FACE;So;0;ON;;;;;N;;;;; +1F31C;LAST QUARTER MOON WITH FACE;So;0;ON;;;;;N;;;;; +1F31D;FULL MOON WITH FACE;So;0;ON;;;;;N;;;;; +1F31E;SUN WITH FACE;So;0;ON;;;;;N;;;;; +1F31F;GLOWING STAR;So;0;ON;;;;;N;;;;; +1F320;SHOOTING STAR;So;0;ON;;;;;N;;;;; +1F330;CHESTNUT;So;0;ON;;;;;N;;;;; +1F331;SEEDLING;So;0;ON;;;;;N;;;;; +1F332;EVERGREEN TREE;So;0;ON;;;;;N;;;;; +1F333;DECIDUOUS TREE;So;0;ON;;;;;N;;;;; +1F334;PALM TREE;So;0;ON;;;;;N;;;;; +1F335;CACTUS;So;0;ON;;;;;N;;;;; +1F337;TULIP;So;0;ON;;;;;N;;;;; +1F338;CHERRY BLOSSOM;So;0;ON;;;;;N;;;;; +1F339;ROSE;So;0;ON;;;;;N;;;;; +1F33A;HIBISCUS;So;0;ON;;;;;N;;;;; +1F33B;SUNFLOWER;So;0;ON;;;;;N;;;;; +1F33C;BLOSSOM;So;0;ON;;;;;N;;;;; +1F33D;EAR OF MAIZE;So;0;ON;;;;;N;;;;; +1F33E;EAR OF RICE;So;0;ON;;;;;N;;;;; +1F33F;HERB;So;0;ON;;;;;N;;;;; +1F340;FOUR LEAF CLOVER;So;0;ON;;;;;N;;;;; +1F341;MAPLE LEAF;So;0;ON;;;;;N;;;;; +1F342;FALLEN LEAF;So;0;ON;;;;;N;;;;; +1F343;LEAF FLUTTERING IN WIND;So;0;ON;;;;;N;;;;; +1F344;MUSHROOM;So;0;ON;;;;;N;;;;; +1F345;TOMATO;So;0;ON;;;;;N;;;;; +1F346;AUBERGINE;So;0;ON;;;;;N;;;;; +1F347;GRAPES;So;0;ON;;;;;N;;;;; +1F348;MELON;So;0;ON;;;;;N;;;;; +1F349;WATERMELON;So;0;ON;;;;;N;;;;; +1F34A;TANGERINE;So;0;ON;;;;;N;;;;; +1F34B;LEMON;So;0;ON;;;;;N;;;;; +1F34C;BANANA;So;0;ON;;;;;N;;;;; +1F34D;PINEAPPLE;So;0;ON;;;;;N;;;;; +1F34E;RED APPLE;So;0;ON;;;;;N;;;;; +1F34F;GREEN APPLE;So;0;ON;;;;;N;;;;; +1F350;PEAR;So;0;ON;;;;;N;;;;; +1F351;PEACH;So;0;ON;;;;;N;;;;; +1F352;CHERRIES;So;0;ON;;;;;N;;;;; +1F353;STRAWBERRY;So;0;ON;;;;;N;;;;; +1F354;HAMBURGER;So;0;ON;;;;;N;;;;; +1F355;SLICE OF PIZZA;So;0;ON;;;;;N;;;;; +1F356;MEAT ON BONE;So;0;ON;;;;;N;;;;; +1F357;POULTRY LEG;So;0;ON;;;;;N;;;;; +1F358;RICE CRACKER;So;0;ON;;;;;N;;;;; +1F359;RICE BALL;So;0;ON;;;;;N;;;;; +1F35A;COOKED RICE;So;0;ON;;;;;N;;;;; +1F35B;CURRY AND RICE;So;0;ON;;;;;N;;;;; +1F35C;STEAMING BOWL;So;0;ON;;;;;N;;;;; +1F35D;SPAGHETTI;So;0;ON;;;;;N;;;;; +1F35E;BREAD;So;0;ON;;;;;N;;;;; +1F35F;FRENCH FRIES;So;0;ON;;;;;N;;;;; +1F360;ROASTED SWEET POTATO;So;0;ON;;;;;N;;;;; +1F361;DANGO;So;0;ON;;;;;N;;;;; +1F362;ODEN;So;0;ON;;;;;N;;;;; +1F363;SUSHI;So;0;ON;;;;;N;;;;; +1F364;FRIED SHRIMP;So;0;ON;;;;;N;;;;; +1F365;FISH CAKE WITH SWIRL DESIGN;So;0;ON;;;;;N;;;;; +1F366;SOFT ICE CREAM;So;0;ON;;;;;N;;;;; +1F367;SHAVED ICE;So;0;ON;;;;;N;;;;; +1F368;ICE CREAM;So;0;ON;;;;;N;;;;; +1F369;DOUGHNUT;So;0;ON;;;;;N;;;;; +1F36A;COOKIE;So;0;ON;;;;;N;;;;; +1F36B;CHOCOLATE BAR;So;0;ON;;;;;N;;;;; +1F36C;CANDY;So;0;ON;;;;;N;;;;; +1F36D;LOLLIPOP;So;0;ON;;;;;N;;;;; +1F36E;CUSTARD;So;0;ON;;;;;N;;;;; +1F36F;HONEY POT;So;0;ON;;;;;N;;;;; +1F370;SHORTCAKE;So;0;ON;;;;;N;;;;; +1F371;BENTO BOX;So;0;ON;;;;;N;;;;; +1F372;POT OF FOOD;So;0;ON;;;;;N;;;;; +1F373;COOKING;So;0;ON;;;;;N;;;;; +1F374;FORK AND KNIFE;So;0;ON;;;;;N;;;;; +1F375;TEACUP WITHOUT HANDLE;So;0;ON;;;;;N;;;;; +1F376;SAKE BOTTLE AND CUP;So;0;ON;;;;;N;;;;; +1F377;WINE GLASS;So;0;ON;;;;;N;;;;; +1F378;COCKTAIL GLASS;So;0;ON;;;;;N;;;;; +1F379;TROPICAL DRINK;So;0;ON;;;;;N;;;;; +1F37A;BEER MUG;So;0;ON;;;;;N;;;;; +1F37B;CLINKING BEER MUGS;So;0;ON;;;;;N;;;;; +1F37C;BABY BOTTLE;So;0;ON;;;;;N;;;;; +1F380;RIBBON;So;0;ON;;;;;N;;;;; +1F381;WRAPPED PRESENT;So;0;ON;;;;;N;;;;; +1F382;BIRTHDAY CAKE;So;0;ON;;;;;N;;;;; +1F383;JACK-O-LANTERN;So;0;ON;;;;;N;;;;; +1F384;CHRISTMAS TREE;So;0;ON;;;;;N;;;;; +1F385;FATHER CHRISTMAS;So;0;ON;;;;;N;;;;; +1F386;FIREWORKS;So;0;ON;;;;;N;;;;; +1F387;FIREWORK SPARKLER;So;0;ON;;;;;N;;;;; +1F388;BALLOON;So;0;ON;;;;;N;;;;; +1F389;PARTY POPPER;So;0;ON;;;;;N;;;;; +1F38A;CONFETTI BALL;So;0;ON;;;;;N;;;;; +1F38B;TANABATA TREE;So;0;ON;;;;;N;;;;; +1F38C;CROSSED FLAGS;So;0;ON;;;;;N;;;;; +1F38D;PINE DECORATION;So;0;ON;;;;;N;;;;; +1F38E;JAPANESE DOLLS;So;0;ON;;;;;N;;;;; +1F38F;CARP STREAMER;So;0;ON;;;;;N;;;;; +1F390;WIND CHIME;So;0;ON;;;;;N;;;;; +1F391;MOON VIEWING CEREMONY;So;0;ON;;;;;N;;;;; +1F392;SCHOOL SATCHEL;So;0;ON;;;;;N;;;;; +1F393;GRADUATION CAP;So;0;ON;;;;;N;;;;; +1F3A0;CAROUSEL HORSE;So;0;ON;;;;;N;;;;; +1F3A1;FERRIS WHEEL;So;0;ON;;;;;N;;;;; +1F3A2;ROLLER COASTER;So;0;ON;;;;;N;;;;; +1F3A3;FISHING POLE AND FISH;So;0;ON;;;;;N;;;;; +1F3A4;MICROPHONE;So;0;ON;;;;;N;;;;; +1F3A5;MOVIE CAMERA;So;0;ON;;;;;N;;;;; +1F3A6;CINEMA;So;0;ON;;;;;N;;;;; +1F3A7;HEADPHONE;So;0;ON;;;;;N;;;;; +1F3A8;ARTIST PALETTE;So;0;ON;;;;;N;;;;; +1F3A9;TOP HAT;So;0;ON;;;;;N;;;;; +1F3AA;CIRCUS TENT;So;0;ON;;;;;N;;;;; +1F3AB;TICKET;So;0;ON;;;;;N;;;;; +1F3AC;CLAPPER BOARD;So;0;ON;;;;;N;;;;; +1F3AD;PERFORMING ARTS;So;0;ON;;;;;N;;;;; +1F3AE;VIDEO GAME;So;0;ON;;;;;N;;;;; +1F3AF;DIRECT HIT;So;0;ON;;;;;N;;;;; +1F3B0;SLOT MACHINE;So;0;ON;;;;;N;;;;; +1F3B1;BILLIARDS;So;0;ON;;;;;N;;;;; +1F3B2;GAME DIE;So;0;ON;;;;;N;;;;; +1F3B3;BOWLING;So;0;ON;;;;;N;;;;; +1F3B4;FLOWER PLAYING CARDS;So;0;ON;;;;;N;;;;; +1F3B5;MUSICAL NOTE;So;0;ON;;;;;N;;;;; +1F3B6;MULTIPLE MUSICAL NOTES;So;0;ON;;;;;N;;;;; +1F3B7;SAXOPHONE;So;0;ON;;;;;N;;;;; +1F3B8;GUITAR;So;0;ON;;;;;N;;;;; +1F3B9;MUSICAL KEYBOARD;So;0;ON;;;;;N;;;;; +1F3BA;TRUMPET;So;0;ON;;;;;N;;;;; +1F3BB;VIOLIN;So;0;ON;;;;;N;;;;; +1F3BC;MUSICAL SCORE;So;0;ON;;;;;N;;;;; +1F3BD;RUNNING SHIRT WITH SASH;So;0;ON;;;;;N;;;;; +1F3BE;TENNIS RACQUET AND BALL;So;0;ON;;;;;N;;;;; +1F3BF;SKI AND SKI BOOT;So;0;ON;;;;;N;;;;; +1F3C0;BASKETBALL AND HOOP;So;0;ON;;;;;N;;;;; +1F3C1;CHEQUERED FLAG;So;0;ON;;;;;N;;;;; +1F3C2;SNOWBOARDER;So;0;ON;;;;;N;;;;; +1F3C3;RUNNER;So;0;ON;;;;;N;;;;; +1F3C4;SURFER;So;0;ON;;;;;N;;;;; +1F3C6;TROPHY;So;0;ON;;;;;N;;;;; +1F3C7;HORSE RACING;So;0;ON;;;;;N;;;;; +1F3C8;AMERICAN FOOTBALL;So;0;ON;;;;;N;;;;; +1F3C9;RUGBY FOOTBALL;So;0;ON;;;;;N;;;;; +1F3CA;SWIMMER;So;0;ON;;;;;N;;;;; +1F3E0;HOUSE BUILDING;So;0;ON;;;;;N;;;;; +1F3E1;HOUSE WITH GARDEN;So;0;ON;;;;;N;;;;; +1F3E2;OFFICE BUILDING;So;0;ON;;;;;N;;;;; +1F3E3;JAPANESE POST OFFICE;So;0;ON;;;;;N;;;;; +1F3E4;EUROPEAN POST OFFICE;So;0;ON;;;;;N;;;;; +1F3E5;HOSPITAL;So;0;ON;;;;;N;;;;; +1F3E6;BANK;So;0;ON;;;;;N;;;;; +1F3E7;AUTOMATED TELLER MACHINE;So;0;ON;;;;;N;;;;; +1F3E8;HOTEL;So;0;ON;;;;;N;;;;; +1F3E9;LOVE HOTEL;So;0;ON;;;;;N;;;;; +1F3EA;CONVENIENCE STORE;So;0;ON;;;;;N;;;;; +1F3EB;SCHOOL;So;0;ON;;;;;N;;;;; +1F3EC;DEPARTMENT STORE;So;0;ON;;;;;N;;;;; +1F3ED;FACTORY;So;0;ON;;;;;N;;;;; +1F3EE;IZAKAYA LANTERN;So;0;ON;;;;;N;;;;; +1F3EF;JAPANESE CASTLE;So;0;ON;;;;;N;;;;; +1F3F0;EUROPEAN CASTLE;So;0;ON;;;;;N;;;;; +1F400;RAT;So;0;ON;;;;;N;;;;; +1F401;MOUSE;So;0;ON;;;;;N;;;;; +1F402;OX;So;0;ON;;;;;N;;;;; +1F403;WATER BUFFALO;So;0;ON;;;;;N;;;;; +1F404;COW;So;0;ON;;;;;N;;;;; +1F405;TIGER;So;0;ON;;;;;N;;;;; +1F406;LEOPARD;So;0;ON;;;;;N;;;;; +1F407;RABBIT;So;0;ON;;;;;N;;;;; +1F408;CAT;So;0;ON;;;;;N;;;;; +1F409;DRAGON;So;0;ON;;;;;N;;;;; +1F40A;CROCODILE;So;0;ON;;;;;N;;;;; +1F40B;WHALE;So;0;ON;;;;;N;;;;; +1F40C;SNAIL;So;0;ON;;;;;N;;;;; +1F40D;SNAKE;So;0;ON;;;;;N;;;;; +1F40E;HORSE;So;0;ON;;;;;N;;;;; +1F40F;RAM;So;0;ON;;;;;N;;;;; +1F410;GOAT;So;0;ON;;;;;N;;;;; +1F411;SHEEP;So;0;ON;;;;;N;;;;; +1F412;MONKEY;So;0;ON;;;;;N;;;;; +1F413;ROOSTER;So;0;ON;;;;;N;;;;; +1F414;CHICKEN;So;0;ON;;;;;N;;;;; +1F415;DOG;So;0;ON;;;;;N;;;;; +1F416;PIG;So;0;ON;;;;;N;;;;; +1F417;BOAR;So;0;ON;;;;;N;;;;; +1F418;ELEPHANT;So;0;ON;;;;;N;;;;; +1F419;OCTOPUS;So;0;ON;;;;;N;;;;; +1F41A;SPIRAL SHELL;So;0;ON;;;;;N;;;;; +1F41B;BUG;So;0;ON;;;;;N;;;;; +1F41C;ANT;So;0;ON;;;;;N;;;;; +1F41D;HONEYBEE;So;0;ON;;;;;N;;;;; +1F41E;LADY BEETLE;So;0;ON;;;;;N;;;;; +1F41F;FISH;So;0;ON;;;;;N;;;;; +1F420;TROPICAL FISH;So;0;ON;;;;;N;;;;; +1F421;BLOWFISH;So;0;ON;;;;;N;;;;; +1F422;TURTLE;So;0;ON;;;;;N;;;;; +1F423;HATCHING CHICK;So;0;ON;;;;;N;;;;; +1F424;BABY CHICK;So;0;ON;;;;;N;;;;; +1F425;FRONT-FACING BABY CHICK;So;0;ON;;;;;N;;;;; +1F426;BIRD;So;0;ON;;;;;N;;;;; +1F427;PENGUIN;So;0;ON;;;;;N;;;;; +1F428;KOALA;So;0;ON;;;;;N;;;;; +1F429;POODLE;So;0;ON;;;;;N;;;;; +1F42A;DROMEDARY CAMEL;So;0;ON;;;;;N;;;;; +1F42B;BACTRIAN CAMEL;So;0;ON;;;;;N;;;;; +1F42C;DOLPHIN;So;0;ON;;;;;N;;;;; +1F42D;MOUSE FACE;So;0;ON;;;;;N;;;;; +1F42E;COW FACE;So;0;ON;;;;;N;;;;; +1F42F;TIGER FACE;So;0;ON;;;;;N;;;;; +1F430;RABBIT FACE;So;0;ON;;;;;N;;;;; +1F431;CAT FACE;So;0;ON;;;;;N;;;;; +1F432;DRAGON FACE;So;0;ON;;;;;N;;;;; +1F433;SPOUTING WHALE;So;0;ON;;;;;N;;;;; +1F434;HORSE FACE;So;0;ON;;;;;N;;;;; +1F435;MONKEY FACE;So;0;ON;;;;;N;;;;; +1F436;DOG FACE;So;0;ON;;;;;N;;;;; +1F437;PIG FACE;So;0;ON;;;;;N;;;;; +1F438;FROG FACE;So;0;ON;;;;;N;;;;; +1F439;HAMSTER FACE;So;0;ON;;;;;N;;;;; +1F43A;WOLF FACE;So;0;ON;;;;;N;;;;; +1F43B;BEAR FACE;So;0;ON;;;;;N;;;;; +1F43C;PANDA FACE;So;0;ON;;;;;N;;;;; +1F43D;PIG NOSE;So;0;ON;;;;;N;;;;; +1F43E;PAW PRINTS;So;0;ON;;;;;N;;;;; +1F440;EYES;So;0;ON;;;;;N;;;;; +1F442;EAR;So;0;ON;;;;;N;;;;; +1F443;NOSE;So;0;ON;;;;;N;;;;; +1F444;MOUTH;So;0;ON;;;;;N;;;;; +1F445;TONGUE;So;0;ON;;;;;N;;;;; +1F446;WHITE UP POINTING BACKHAND INDEX;So;0;ON;;;;;N;;;;; +1F447;WHITE DOWN POINTING BACKHAND INDEX;So;0;ON;;;;;N;;;;; +1F448;WHITE LEFT POINTING BACKHAND INDEX;So;0;ON;;;;;N;;;;; +1F449;WHITE RIGHT POINTING BACKHAND INDEX;So;0;ON;;;;;N;;;;; +1F44A;FISTED HAND SIGN;So;0;ON;;;;;N;;;;; +1F44B;WAVING HAND SIGN;So;0;ON;;;;;N;;;;; +1F44C;OK HAND SIGN;So;0;ON;;;;;N;;;;; +1F44D;THUMBS UP SIGN;So;0;ON;;;;;N;;;;; +1F44E;THUMBS DOWN SIGN;So;0;ON;;;;;N;;;;; +1F44F;CLAPPING HANDS SIGN;So;0;ON;;;;;N;;;;; +1F450;OPEN HANDS SIGN;So;0;ON;;;;;N;;;;; +1F451;CROWN;So;0;ON;;;;;N;;;;; +1F452;WOMANS HAT;So;0;ON;;;;;N;;;;; +1F453;EYEGLASSES;So;0;ON;;;;;N;;;;; +1F454;NECKTIE;So;0;ON;;;;;N;;;;; +1F455;T-SHIRT;So;0;ON;;;;;N;;;;; +1F456;JEANS;So;0;ON;;;;;N;;;;; +1F457;DRESS;So;0;ON;;;;;N;;;;; +1F458;KIMONO;So;0;ON;;;;;N;;;;; +1F459;BIKINI;So;0;ON;;;;;N;;;;; +1F45A;WOMANS CLOTHES;So;0;ON;;;;;N;;;;; +1F45B;PURSE;So;0;ON;;;;;N;;;;; +1F45C;HANDBAG;So;0;ON;;;;;N;;;;; +1F45D;POUCH;So;0;ON;;;;;N;;;;; +1F45E;MANS SHOE;So;0;ON;;;;;N;;;;; +1F45F;ATHLETIC SHOE;So;0;ON;;;;;N;;;;; +1F460;HIGH-HEELED SHOE;So;0;ON;;;;;N;;;;; +1F461;WOMANS SANDAL;So;0;ON;;;;;N;;;;; +1F462;WOMANS BOOTS;So;0;ON;;;;;N;;;;; +1F463;FOOTPRINTS;So;0;ON;;;;;N;;;;; +1F464;BUST IN SILHOUETTE;So;0;ON;;;;;N;;;;; +1F465;BUSTS IN SILHOUETTE;So;0;ON;;;;;N;;;;; +1F466;BOY;So;0;ON;;;;;N;;;;; +1F467;GIRL;So;0;ON;;;;;N;;;;; +1F468;MAN;So;0;ON;;;;;N;;;;; +1F469;WOMAN;So;0;ON;;;;;N;;;;; +1F46A;FAMILY;So;0;ON;;;;;N;;;;; +1F46B;MAN AND WOMAN HOLDING HANDS;So;0;ON;;;;;N;;;;; +1F46C;TWO MEN HOLDING HANDS;So;0;ON;;;;;N;;;;; +1F46D;TWO WOMEN HOLDING HANDS;So;0;ON;;;;;N;;;;; +1F46E;POLICE OFFICER;So;0;ON;;;;;N;;;;; +1F46F;WOMAN WITH BUNNY EARS;So;0;ON;;;;;N;;;;; +1F470;BRIDE WITH VEIL;So;0;ON;;;;;N;;;;; +1F471;PERSON WITH BLOND HAIR;So;0;ON;;;;;N;;;;; +1F472;MAN WITH GUA PI MAO;So;0;ON;;;;;N;;;;; +1F473;MAN WITH TURBAN;So;0;ON;;;;;N;;;;; +1F474;OLDER MAN;So;0;ON;;;;;N;;;;; +1F475;OLDER WOMAN;So;0;ON;;;;;N;;;;; +1F476;BABY;So;0;ON;;;;;N;;;;; +1F477;CONSTRUCTION WORKER;So;0;ON;;;;;N;;;;; +1F478;PRINCESS;So;0;ON;;;;;N;;;;; +1F479;JAPANESE OGRE;So;0;ON;;;;;N;;;;; +1F47A;JAPANESE GOBLIN;So;0;ON;;;;;N;;;;; +1F47B;GHOST;So;0;ON;;;;;N;;;;; +1F47C;BABY ANGEL;So;0;ON;;;;;N;;;;; +1F47D;EXTRATERRESTRIAL ALIEN;So;0;ON;;;;;N;;;;; +1F47E;ALIEN MONSTER;So;0;ON;;;;;N;;;;; +1F47F;IMP;So;0;ON;;;;;N;;;;; +1F480;SKULL;So;0;ON;;;;;N;;;;; +1F481;INFORMATION DESK PERSON;So;0;ON;;;;;N;;;;; +1F482;GUARDSMAN;So;0;ON;;;;;N;;;;; +1F483;DANCER;So;0;ON;;;;;N;;;;; +1F484;LIPSTICK;So;0;ON;;;;;N;;;;; +1F485;NAIL POLISH;So;0;ON;;;;;N;;;;; +1F486;FACE MASSAGE;So;0;ON;;;;;N;;;;; +1F487;HAIRCUT;So;0;ON;;;;;N;;;;; +1F488;BARBER POLE;So;0;ON;;;;;N;;;;; +1F489;SYRINGE;So;0;ON;;;;;N;;;;; +1F48A;PILL;So;0;ON;;;;;N;;;;; +1F48B;KISS MARK;So;0;ON;;;;;N;;;;; +1F48C;LOVE LETTER;So;0;ON;;;;;N;;;;; +1F48D;RING;So;0;ON;;;;;N;;;;; +1F48E;GEM STONE;So;0;ON;;;;;N;;;;; +1F48F;KISS;So;0;ON;;;;;N;;;;; +1F490;BOUQUET;So;0;ON;;;;;N;;;;; +1F491;COUPLE WITH HEART;So;0;ON;;;;;N;;;;; +1F492;WEDDING;So;0;ON;;;;;N;;;;; +1F493;BEATING HEART;So;0;ON;;;;;N;;;;; +1F494;BROKEN HEART;So;0;ON;;;;;N;;;;; +1F495;TWO HEARTS;So;0;ON;;;;;N;;;;; +1F496;SPARKLING HEART;So;0;ON;;;;;N;;;;; +1F497;GROWING HEART;So;0;ON;;;;;N;;;;; +1F498;HEART WITH ARROW;So;0;ON;;;;;N;;;;; +1F499;BLUE HEART;So;0;ON;;;;;N;;;;; +1F49A;GREEN HEART;So;0;ON;;;;;N;;;;; +1F49B;YELLOW HEART;So;0;ON;;;;;N;;;;; +1F49C;PURPLE HEART;So;0;ON;;;;;N;;;;; +1F49D;HEART WITH RIBBON;So;0;ON;;;;;N;;;;; +1F49E;REVOLVING HEARTS;So;0;ON;;;;;N;;;;; +1F49F;HEART DECORATION;So;0;ON;;;;;N;;;;; +1F4A0;DIAMOND SHAPE WITH A DOT INSIDE;So;0;ON;;;;;N;;;;; +1F4A1;ELECTRIC LIGHT BULB;So;0;ON;;;;;N;;;;; +1F4A2;ANGER SYMBOL;So;0;ON;;;;;N;;;;; +1F4A3;BOMB;So;0;ON;;;;;N;;;;; +1F4A4;SLEEPING SYMBOL;So;0;ON;;;;;N;;;;; +1F4A5;COLLISION SYMBOL;So;0;ON;;;;;N;;;;; +1F4A6;SPLASHING SWEAT SYMBOL;So;0;ON;;;;;N;;;;; +1F4A7;DROPLET;So;0;ON;;;;;N;;;;; +1F4A8;DASH SYMBOL;So;0;ON;;;;;N;;;;; +1F4A9;PILE OF POO;So;0;ON;;;;;N;;;;; +1F4AA;FLEXED BICEPS;So;0;ON;;;;;N;;;;; +1F4AB;DIZZY SYMBOL;So;0;ON;;;;;N;;;;; +1F4AC;SPEECH BALLOON;So;0;ON;;;;;N;;;;; +1F4AD;THOUGHT BALLOON;So;0;ON;;;;;N;;;;; +1F4AE;WHITE FLOWER;So;0;ON;;;;;N;;;;; +1F4AF;HUNDRED POINTS SYMBOL;So;0;ON;;;;;N;;;;; +1F4B0;MONEY BAG;So;0;ON;;;;;N;;;;; +1F4B1;CURRENCY EXCHANGE;So;0;ON;;;;;N;;;;; +1F4B2;HEAVY DOLLAR SIGN;So;0;ON;;;;;N;;;;; +1F4B3;CREDIT CARD;So;0;ON;;;;;N;;;;; +1F4B4;BANKNOTE WITH YEN SIGN;So;0;ON;;;;;N;;;;; +1F4B5;BANKNOTE WITH DOLLAR SIGN;So;0;ON;;;;;N;;;;; +1F4B6;BANKNOTE WITH EURO SIGN;So;0;ON;;;;;N;;;;; +1F4B7;BANKNOTE WITH POUND SIGN;So;0;ON;;;;;N;;;;; +1F4B8;MONEY WITH WINGS;So;0;ON;;;;;N;;;;; +1F4B9;CHART WITH UPWARDS TREND AND YEN SIGN;So;0;ON;;;;;N;;;;; +1F4BA;SEAT;So;0;ON;;;;;N;;;;; +1F4BB;PERSONAL COMPUTER;So;0;ON;;;;;N;;;;; +1F4BC;BRIEFCASE;So;0;ON;;;;;N;;;;; +1F4BD;MINIDISC;So;0;ON;;;;;N;;;;; +1F4BE;FLOPPY DISK;So;0;ON;;;;;N;;;;; +1F4BF;OPTICAL DISC;So;0;ON;;;;;N;;;;; +1F4C0;DVD;So;0;ON;;;;;N;;;;; +1F4C1;FILE FOLDER;So;0;ON;;;;;N;;;;; +1F4C2;OPEN FILE FOLDER;So;0;ON;;;;;N;;;;; +1F4C3;PAGE WITH CURL;So;0;ON;;;;;N;;;;; +1F4C4;PAGE FACING UP;So;0;ON;;;;;N;;;;; +1F4C5;CALENDAR;So;0;ON;;;;;N;;;;; +1F4C6;TEAR-OFF CALENDAR;So;0;ON;;;;;N;;;;; +1F4C7;CARD INDEX;So;0;ON;;;;;N;;;;; +1F4C8;CHART WITH UPWARDS TREND;So;0;ON;;;;;N;;;;; +1F4C9;CHART WITH DOWNWARDS TREND;So;0;ON;;;;;N;;;;; +1F4CA;BAR CHART;So;0;ON;;;;;N;;;;; +1F4CB;CLIPBOARD;So;0;ON;;;;;N;;;;; +1F4CC;PUSHPIN;So;0;ON;;;;;N;;;;; +1F4CD;ROUND PUSHPIN;So;0;ON;;;;;N;;;;; +1F4CE;PAPERCLIP;So;0;ON;;;;;N;;;;; +1F4CF;STRAIGHT RULER;So;0;ON;;;;;N;;;;; +1F4D0;TRIANGULAR RULER;So;0;ON;;;;;N;;;;; +1F4D1;BOOKMARK TABS;So;0;ON;;;;;N;;;;; +1F4D2;LEDGER;So;0;ON;;;;;N;;;;; +1F4D3;NOTEBOOK;So;0;ON;;;;;N;;;;; +1F4D4;NOTEBOOK WITH DECORATIVE COVER;So;0;ON;;;;;N;;;;; +1F4D5;CLOSED BOOK;So;0;ON;;;;;N;;;;; +1F4D6;OPEN BOOK;So;0;ON;;;;;N;;;;; +1F4D7;GREEN BOOK;So;0;ON;;;;;N;;;;; +1F4D8;BLUE BOOK;So;0;ON;;;;;N;;;;; +1F4D9;ORANGE BOOK;So;0;ON;;;;;N;;;;; +1F4DA;BOOKS;So;0;ON;;;;;N;;;;; +1F4DB;NAME BADGE;So;0;ON;;;;;N;;;;; +1F4DC;SCROLL;So;0;ON;;;;;N;;;;; +1F4DD;MEMO;So;0;ON;;;;;N;;;;; +1F4DE;TELEPHONE RECEIVER;So;0;ON;;;;;N;;;;; +1F4DF;PAGER;So;0;ON;;;;;N;;;;; +1F4E0;FAX MACHINE;So;0;ON;;;;;N;;;;; +1F4E1;SATELLITE ANTENNA;So;0;ON;;;;;N;;;;; +1F4E2;PUBLIC ADDRESS LOUDSPEAKER;So;0;ON;;;;;N;;;;; +1F4E3;CHEERING MEGAPHONE;So;0;ON;;;;;N;;;;; +1F4E4;OUTBOX TRAY;So;0;ON;;;;;N;;;;; +1F4E5;INBOX TRAY;So;0;ON;;;;;N;;;;; +1F4E6;PACKAGE;So;0;ON;;;;;N;;;;; +1F4E7;E-MAIL SYMBOL;So;0;ON;;;;;N;;;;; +1F4E8;INCOMING ENVELOPE;So;0;ON;;;;;N;;;;; +1F4E9;ENVELOPE WITH DOWNWARDS ARROW ABOVE;So;0;ON;;;;;N;;;;; +1F4EA;CLOSED MAILBOX WITH LOWERED FLAG;So;0;ON;;;;;N;;;;; +1F4EB;CLOSED MAILBOX WITH RAISED FLAG;So;0;ON;;;;;N;;;;; +1F4EC;OPEN MAILBOX WITH RAISED FLAG;So;0;ON;;;;;N;;;;; +1F4ED;OPEN MAILBOX WITH LOWERED FLAG;So;0;ON;;;;;N;;;;; +1F4EE;POSTBOX;So;0;ON;;;;;N;;;;; +1F4EF;POSTAL HORN;So;0;ON;;;;;N;;;;; +1F4F0;NEWSPAPER;So;0;ON;;;;;N;;;;; +1F4F1;MOBILE PHONE;So;0;ON;;;;;N;;;;; +1F4F2;MOBILE PHONE WITH RIGHTWARDS ARROW AT LEFT;So;0;ON;;;;;N;;;;; +1F4F3;VIBRATION MODE;So;0;ON;;;;;N;;;;; +1F4F4;MOBILE PHONE OFF;So;0;ON;;;;;N;;;;; +1F4F5;NO MOBILE PHONES;So;0;ON;;;;;N;;;;; +1F4F6;ANTENNA WITH BARS;So;0;ON;;;;;N;;;;; +1F4F7;CAMERA;So;0;ON;;;;;N;;;;; +1F4F9;VIDEO CAMERA;So;0;ON;;;;;N;;;;; +1F4FA;TELEVISION;So;0;ON;;;;;N;;;;; +1F4FB;RADIO;So;0;ON;;;;;N;;;;; +1F4FC;VIDEOCASSETTE;So;0;ON;;;;;N;;;;; +1F500;TWISTED RIGHTWARDS ARROWS;So;0;ON;;;;;N;;;;; +1F501;CLOCKWISE RIGHTWARDS AND LEFTWARDS OPEN CIRCLE ARROWS;So;0;ON;;;;;N;;;;; +1F502;CLOCKWISE RIGHTWARDS AND LEFTWARDS OPEN CIRCLE ARROWS WITH CIRCLED ONE OVERLAY;So;0;ON;;;;;N;;;;; +1F503;CLOCKWISE DOWNWARDS AND UPWARDS OPEN CIRCLE ARROWS;So;0;ON;;;;;N;;;;; +1F504;ANTICLOCKWISE DOWNWARDS AND UPWARDS OPEN CIRCLE ARROWS;So;0;ON;;;;;N;;;;; +1F505;LOW BRIGHTNESS SYMBOL;So;0;ON;;;;;N;;;;; +1F506;HIGH BRIGHTNESS SYMBOL;So;0;ON;;;;;N;;;;; +1F507;SPEAKER WITH CANCELLATION STROKE;So;0;ON;;;;;N;;;;; +1F508;SPEAKER;So;0;ON;;;;;N;;;;; +1F509;SPEAKER WITH ONE SOUND WAVE;So;0;ON;;;;;N;;;;; +1F50A;SPEAKER WITH THREE SOUND WAVES;So;0;ON;;;;;N;;;;; +1F50B;BATTERY;So;0;ON;;;;;N;;;;; +1F50C;ELECTRIC PLUG;So;0;ON;;;;;N;;;;; +1F50D;LEFT-POINTING MAGNIFYING GLASS;So;0;ON;;;;;N;;;;; +1F50E;RIGHT-POINTING MAGNIFYING GLASS;So;0;ON;;;;;N;;;;; +1F50F;LOCK WITH INK PEN;So;0;ON;;;;;N;;;;; +1F510;CLOSED LOCK WITH KEY;So;0;ON;;;;;N;;;;; +1F511;KEY;So;0;ON;;;;;N;;;;; +1F512;LOCK;So;0;ON;;;;;N;;;;; +1F513;OPEN LOCK;So;0;ON;;;;;N;;;;; +1F514;BELL;So;0;ON;;;;;N;;;;; +1F515;BELL WITH CANCELLATION STROKE;So;0;ON;;;;;N;;;;; +1F516;BOOKMARK;So;0;ON;;;;;N;;;;; +1F517;LINK SYMBOL;So;0;ON;;;;;N;;;;; +1F518;RADIO BUTTON;So;0;ON;;;;;N;;;;; +1F519;BACK WITH LEFTWARDS ARROW ABOVE;So;0;ON;;;;;N;;;;; +1F51A;END WITH LEFTWARDS ARROW ABOVE;So;0;ON;;;;;N;;;;; +1F51B;ON WITH EXCLAMATION MARK WITH LEFT RIGHT ARROW ABOVE;So;0;ON;;;;;N;;;;; +1F51C;SOON WITH RIGHTWARDS ARROW ABOVE;So;0;ON;;;;;N;;;;; +1F51D;TOP WITH UPWARDS ARROW ABOVE;So;0;ON;;;;;N;;;;; +1F51E;NO ONE UNDER EIGHTEEN SYMBOL;So;0;ON;;;;;N;;;;; +1F51F;KEYCAP TEN;So;0;ON;;;;;N;;;;; +1F520;INPUT SYMBOL FOR LATIN CAPITAL LETTERS;So;0;ON;;;;;N;;;;; +1F521;INPUT SYMBOL FOR LATIN SMALL LETTERS;So;0;ON;;;;;N;;;;; +1F522;INPUT SYMBOL FOR NUMBERS;So;0;ON;;;;;N;;;;; +1F523;INPUT SYMBOL FOR SYMBOLS;So;0;ON;;;;;N;;;;; +1F524;INPUT SYMBOL FOR LATIN LETTERS;So;0;ON;;;;;N;;;;; +1F525;FIRE;So;0;ON;;;;;N;;;;; +1F526;ELECTRIC TORCH;So;0;ON;;;;;N;;;;; +1F527;WRENCH;So;0;ON;;;;;N;;;;; +1F528;HAMMER;So;0;ON;;;;;N;;;;; +1F529;NUT AND BOLT;So;0;ON;;;;;N;;;;; +1F52A;HOCHO;So;0;ON;;;;;N;;;;; +1F52B;PISTOL;So;0;ON;;;;;N;;;;; +1F52C;MICROSCOPE;So;0;ON;;;;;N;;;;; +1F52D;TELESCOPE;So;0;ON;;;;;N;;;;; +1F52E;CRYSTAL BALL;So;0;ON;;;;;N;;;;; +1F52F;SIX POINTED STAR WITH MIDDLE DOT;So;0;ON;;;;;N;;;;; +1F530;JAPANESE SYMBOL FOR BEGINNER;So;0;ON;;;;;N;;;;; +1F531;TRIDENT EMBLEM;So;0;ON;;;;;N;;;;; +1F532;BLACK SQUARE BUTTON;So;0;ON;;;;;N;;;;; +1F533;WHITE SQUARE BUTTON;So;0;ON;;;;;N;;;;; +1F534;LARGE RED CIRCLE;So;0;ON;;;;;N;;;;; +1F535;LARGE BLUE CIRCLE;So;0;ON;;;;;N;;;;; +1F536;LARGE ORANGE DIAMOND;So;0;ON;;;;;N;;;;; +1F537;LARGE BLUE DIAMOND;So;0;ON;;;;;N;;;;; +1F538;SMALL ORANGE DIAMOND;So;0;ON;;;;;N;;;;; +1F539;SMALL BLUE DIAMOND;So;0;ON;;;;;N;;;;; +1F53A;UP-POINTING RED TRIANGLE;So;0;ON;;;;;N;;;;; +1F53B;DOWN-POINTING RED TRIANGLE;So;0;ON;;;;;N;;;;; +1F53C;UP-POINTING SMALL RED TRIANGLE;So;0;ON;;;;;N;;;;; +1F53D;DOWN-POINTING SMALL RED TRIANGLE;So;0;ON;;;;;N;;;;; +1F540;CIRCLED CROSS POMMEE;So;0;ON;;;;;N;;;;; +1F541;CROSS POMMEE WITH HALF-CIRCLE BELOW;So;0;ON;;;;;N;;;;; +1F542;CROSS POMMEE;So;0;ON;;;;;N;;;;; +1F543;NOTCHED LEFT SEMICIRCLE WITH THREE DOTS;So;0;ON;;;;;N;;;;; +1F550;CLOCK FACE ONE OCLOCK;So;0;ON;;;;;N;;;;; +1F551;CLOCK FACE TWO OCLOCK;So;0;ON;;;;;N;;;;; +1F552;CLOCK FACE THREE OCLOCK;So;0;ON;;;;;N;;;;; +1F553;CLOCK FACE FOUR OCLOCK;So;0;ON;;;;;N;;;;; +1F554;CLOCK FACE FIVE OCLOCK;So;0;ON;;;;;N;;;;; +1F555;CLOCK FACE SIX OCLOCK;So;0;ON;;;;;N;;;;; +1F556;CLOCK FACE SEVEN OCLOCK;So;0;ON;;;;;N;;;;; +1F557;CLOCK FACE EIGHT OCLOCK;So;0;ON;;;;;N;;;;; +1F558;CLOCK FACE NINE OCLOCK;So;0;ON;;;;;N;;;;; +1F559;CLOCK FACE TEN OCLOCK;So;0;ON;;;;;N;;;;; +1F55A;CLOCK FACE ELEVEN OCLOCK;So;0;ON;;;;;N;;;;; +1F55B;CLOCK FACE TWELVE OCLOCK;So;0;ON;;;;;N;;;;; +1F55C;CLOCK FACE ONE-THIRTY;So;0;ON;;;;;N;;;;; +1F55D;CLOCK FACE TWO-THIRTY;So;0;ON;;;;;N;;;;; +1F55E;CLOCK FACE THREE-THIRTY;So;0;ON;;;;;N;;;;; +1F55F;CLOCK FACE FOUR-THIRTY;So;0;ON;;;;;N;;;;; +1F560;CLOCK FACE FIVE-THIRTY;So;0;ON;;;;;N;;;;; +1F561;CLOCK FACE SIX-THIRTY;So;0;ON;;;;;N;;;;; +1F562;CLOCK FACE SEVEN-THIRTY;So;0;ON;;;;;N;;;;; +1F563;CLOCK FACE EIGHT-THIRTY;So;0;ON;;;;;N;;;;; +1F564;CLOCK FACE NINE-THIRTY;So;0;ON;;;;;N;;;;; +1F565;CLOCK FACE TEN-THIRTY;So;0;ON;;;;;N;;;;; +1F566;CLOCK FACE ELEVEN-THIRTY;So;0;ON;;;;;N;;;;; +1F567;CLOCK FACE TWELVE-THIRTY;So;0;ON;;;;;N;;;;; +1F5FB;MOUNT FUJI;So;0;ON;;;;;N;;;;; +1F5FC;TOKYO TOWER;So;0;ON;;;;;N;;;;; +1F5FD;STATUE OF LIBERTY;So;0;ON;;;;;N;;;;; +1F5FE;SILHOUETTE OF JAPAN;So;0;ON;;;;;N;;;;; +1F5FF;MOYAI;So;0;ON;;;;;N;;;;; +1F600;GRINNING FACE;So;0;ON;;;;;N;;;;; +1F601;GRINNING FACE WITH SMILING EYES;So;0;ON;;;;;N;;;;; +1F602;FACE WITH TEARS OF JOY;So;0;ON;;;;;N;;;;; +1F603;SMILING FACE WITH OPEN MOUTH;So;0;ON;;;;;N;;;;; +1F604;SMILING FACE WITH OPEN MOUTH AND SMILING EYES;So;0;ON;;;;;N;;;;; +1F605;SMILING FACE WITH OPEN MOUTH AND COLD SWEAT;So;0;ON;;;;;N;;;;; +1F606;SMILING FACE WITH OPEN MOUTH AND TIGHTLY-CLOSED EYES;So;0;ON;;;;;N;;;;; +1F607;SMILING FACE WITH HALO;So;0;ON;;;;;N;;;;; +1F608;SMILING FACE WITH HORNS;So;0;ON;;;;;N;;;;; +1F609;WINKING FACE;So;0;ON;;;;;N;;;;; +1F60A;SMILING FACE WITH SMILING EYES;So;0;ON;;;;;N;;;;; +1F60B;FACE SAVOURING DELICIOUS FOOD;So;0;ON;;;;;N;;;;; +1F60C;RELIEVED FACE;So;0;ON;;;;;N;;;;; +1F60D;SMILING FACE WITH HEART-SHAPED EYES;So;0;ON;;;;;N;;;;; +1F60E;SMILING FACE WITH SUNGLASSES;So;0;ON;;;;;N;;;;; +1F60F;SMIRKING FACE;So;0;ON;;;;;N;;;;; +1F610;NEUTRAL FACE;So;0;ON;;;;;N;;;;; +1F611;EXPRESSIONLESS FACE;So;0;ON;;;;;N;;;;; +1F612;UNAMUSED FACE;So;0;ON;;;;;N;;;;; +1F613;FACE WITH COLD SWEAT;So;0;ON;;;;;N;;;;; +1F614;PENSIVE FACE;So;0;ON;;;;;N;;;;; +1F615;CONFUSED FACE;So;0;ON;;;;;N;;;;; +1F616;CONFOUNDED FACE;So;0;ON;;;;;N;;;;; +1F617;KISSING FACE;So;0;ON;;;;;N;;;;; +1F618;FACE THROWING A KISS;So;0;ON;;;;;N;;;;; +1F619;KISSING FACE WITH SMILING EYES;So;0;ON;;;;;N;;;;; +1F61A;KISSING FACE WITH CLOSED EYES;So;0;ON;;;;;N;;;;; +1F61B;FACE WITH STUCK-OUT TONGUE;So;0;ON;;;;;N;;;;; +1F61C;FACE WITH STUCK-OUT TONGUE AND WINKING EYE;So;0;ON;;;;;N;;;;; +1F61D;FACE WITH STUCK-OUT TONGUE AND TIGHTLY-CLOSED EYES;So;0;ON;;;;;N;;;;; +1F61E;DISAPPOINTED FACE;So;0;ON;;;;;N;;;;; +1F61F;WORRIED FACE;So;0;ON;;;;;N;;;;; +1F620;ANGRY FACE;So;0;ON;;;;;N;;;;; +1F621;POUTING FACE;So;0;ON;;;;;N;;;;; +1F622;CRYING FACE;So;0;ON;;;;;N;;;;; +1F623;PERSEVERING FACE;So;0;ON;;;;;N;;;;; +1F624;FACE WITH LOOK OF TRIUMPH;So;0;ON;;;;;N;;;;; +1F625;DISAPPOINTED BUT RELIEVED FACE;So;0;ON;;;;;N;;;;; +1F626;FROWNING FACE WITH OPEN MOUTH;So;0;ON;;;;;N;;;;; +1F627;ANGUISHED FACE;So;0;ON;;;;;N;;;;; +1F628;FEARFUL FACE;So;0;ON;;;;;N;;;;; +1F629;WEARY FACE;So;0;ON;;;;;N;;;;; +1F62A;SLEEPY FACE;So;0;ON;;;;;N;;;;; +1F62B;TIRED FACE;So;0;ON;;;;;N;;;;; +1F62C;GRIMACING FACE;So;0;ON;;;;;N;;;;; +1F62D;LOUDLY CRYING FACE;So;0;ON;;;;;N;;;;; +1F62E;FACE WITH OPEN MOUTH;So;0;ON;;;;;N;;;;; +1F62F;HUSHED FACE;So;0;ON;;;;;N;;;;; +1F630;FACE WITH OPEN MOUTH AND COLD SWEAT;So;0;ON;;;;;N;;;;; +1F631;FACE SCREAMING IN FEAR;So;0;ON;;;;;N;;;;; +1F632;ASTONISHED FACE;So;0;ON;;;;;N;;;;; +1F633;FLUSHED FACE;So;0;ON;;;;;N;;;;; +1F634;SLEEPING FACE;So;0;ON;;;;;N;;;;; +1F635;DIZZY FACE;So;0;ON;;;;;N;;;;; +1F636;FACE WITHOUT MOUTH;So;0;ON;;;;;N;;;;; +1F637;FACE WITH MEDICAL MASK;So;0;ON;;;;;N;;;;; +1F638;GRINNING CAT FACE WITH SMILING EYES;So;0;ON;;;;;N;;;;; +1F639;CAT FACE WITH TEARS OF JOY;So;0;ON;;;;;N;;;;; +1F63A;SMILING CAT FACE WITH OPEN MOUTH;So;0;ON;;;;;N;;;;; +1F63B;SMILING CAT FACE WITH HEART-SHAPED EYES;So;0;ON;;;;;N;;;;; +1F63C;CAT FACE WITH WRY SMILE;So;0;ON;;;;;N;;;;; +1F63D;KISSING CAT FACE WITH CLOSED EYES;So;0;ON;;;;;N;;;;; +1F63E;POUTING CAT FACE;So;0;ON;;;;;N;;;;; +1F63F;CRYING CAT FACE;So;0;ON;;;;;N;;;;; +1F640;WEARY CAT FACE;So;0;ON;;;;;N;;;;; +1F645;FACE WITH NO GOOD GESTURE;So;0;ON;;;;;N;;;;; +1F646;FACE WITH OK GESTURE;So;0;ON;;;;;N;;;;; +1F647;PERSON BOWING DEEPLY;So;0;ON;;;;;N;;;;; +1F648;SEE-NO-EVIL MONKEY;So;0;ON;;;;;N;;;;; +1F649;HEAR-NO-EVIL MONKEY;So;0;ON;;;;;N;;;;; +1F64A;SPEAK-NO-EVIL MONKEY;So;0;ON;;;;;N;;;;; +1F64B;HAPPY PERSON RAISING ONE HAND;So;0;ON;;;;;N;;;;; +1F64C;PERSON RAISING BOTH HANDS IN CELEBRATION;So;0;ON;;;;;N;;;;; +1F64D;PERSON FROWNING;So;0;ON;;;;;N;;;;; +1F64E;PERSON WITH POUTING FACE;So;0;ON;;;;;N;;;;; +1F64F;PERSON WITH FOLDED HANDS;So;0;ON;;;;;N;;;;; +1F680;ROCKET;So;0;ON;;;;;N;;;;; +1F681;HELICOPTER;So;0;ON;;;;;N;;;;; +1F682;STEAM LOCOMOTIVE;So;0;ON;;;;;N;;;;; +1F683;RAILWAY CAR;So;0;ON;;;;;N;;;;; +1F684;HIGH-SPEED TRAIN;So;0;ON;;;;;N;;;;; +1F685;HIGH-SPEED TRAIN WITH BULLET NOSE;So;0;ON;;;;;N;;;;; +1F686;TRAIN;So;0;ON;;;;;N;;;;; +1F687;METRO;So;0;ON;;;;;N;;;;; +1F688;LIGHT RAIL;So;0;ON;;;;;N;;;;; +1F689;STATION;So;0;ON;;;;;N;;;;; +1F68A;TRAM;So;0;ON;;;;;N;;;;; +1F68B;TRAM CAR;So;0;ON;;;;;N;;;;; +1F68C;BUS;So;0;ON;;;;;N;;;;; +1F68D;ONCOMING BUS;So;0;ON;;;;;N;;;;; +1F68E;TROLLEYBUS;So;0;ON;;;;;N;;;;; +1F68F;BUS STOP;So;0;ON;;;;;N;;;;; +1F690;MINIBUS;So;0;ON;;;;;N;;;;; +1F691;AMBULANCE;So;0;ON;;;;;N;;;;; +1F692;FIRE ENGINE;So;0;ON;;;;;N;;;;; +1F693;POLICE CAR;So;0;ON;;;;;N;;;;; +1F694;ONCOMING POLICE CAR;So;0;ON;;;;;N;;;;; +1F695;TAXI;So;0;ON;;;;;N;;;;; +1F696;ONCOMING TAXI;So;0;ON;;;;;N;;;;; +1F697;AUTOMOBILE;So;0;ON;;;;;N;;;;; +1F698;ONCOMING AUTOMOBILE;So;0;ON;;;;;N;;;;; +1F699;RECREATIONAL VEHICLE;So;0;ON;;;;;N;;;;; +1F69A;DELIVERY TRUCK;So;0;ON;;;;;N;;;;; +1F69B;ARTICULATED LORRY;So;0;ON;;;;;N;;;;; +1F69C;TRACTOR;So;0;ON;;;;;N;;;;; +1F69D;MONORAIL;So;0;ON;;;;;N;;;;; +1F69E;MOUNTAIN RAILWAY;So;0;ON;;;;;N;;;;; +1F69F;SUSPENSION RAILWAY;So;0;ON;;;;;N;;;;; +1F6A0;MOUNTAIN CABLEWAY;So;0;ON;;;;;N;;;;; +1F6A1;AERIAL TRAMWAY;So;0;ON;;;;;N;;;;; +1F6A2;SHIP;So;0;ON;;;;;N;;;;; +1F6A3;ROWBOAT;So;0;ON;;;;;N;;;;; +1F6A4;SPEEDBOAT;So;0;ON;;;;;N;;;;; +1F6A5;HORIZONTAL TRAFFIC LIGHT;So;0;ON;;;;;N;;;;; +1F6A6;VERTICAL TRAFFIC LIGHT;So;0;ON;;;;;N;;;;; +1F6A7;CONSTRUCTION SIGN;So;0;ON;;;;;N;;;;; +1F6A8;POLICE CARS REVOLVING LIGHT;So;0;ON;;;;;N;;;;; +1F6A9;TRIANGULAR FLAG ON POST;So;0;ON;;;;;N;;;;; +1F6AA;DOOR;So;0;ON;;;;;N;;;;; +1F6AB;NO ENTRY SIGN;So;0;ON;;;;;N;;;;; +1F6AC;SMOKING SYMBOL;So;0;ON;;;;;N;;;;; +1F6AD;NO SMOKING SYMBOL;So;0;ON;;;;;N;;;;; +1F6AE;PUT LITTER IN ITS PLACE SYMBOL;So;0;ON;;;;;N;;;;; +1F6AF;DO NOT LITTER SYMBOL;So;0;ON;;;;;N;;;;; +1F6B0;POTABLE WATER SYMBOL;So;0;ON;;;;;N;;;;; +1F6B1;NON-POTABLE WATER SYMBOL;So;0;ON;;;;;N;;;;; +1F6B2;BICYCLE;So;0;ON;;;;;N;;;;; +1F6B3;NO BICYCLES;So;0;ON;;;;;N;;;;; +1F6B4;BICYCLIST;So;0;ON;;;;;N;;;;; +1F6B5;MOUNTAIN BICYCLIST;So;0;ON;;;;;N;;;;; +1F6B6;PEDESTRIAN;So;0;ON;;;;;N;;;;; +1F6B7;NO PEDESTRIANS;So;0;ON;;;;;N;;;;; +1F6B8;CHILDREN CROSSING;So;0;ON;;;;;N;;;;; +1F6B9;MENS SYMBOL;So;0;ON;;;;;N;;;;; +1F6BA;WOMENS SYMBOL;So;0;ON;;;;;N;;;;; +1F6BB;RESTROOM;So;0;ON;;;;;N;;;;; +1F6BC;BABY SYMBOL;So;0;ON;;;;;N;;;;; +1F6BD;TOILET;So;0;ON;;;;;N;;;;; +1F6BE;WATER CLOSET;So;0;ON;;;;;N;;;;; +1F6BF;SHOWER;So;0;ON;;;;;N;;;;; +1F6C0;BATH;So;0;ON;;;;;N;;;;; +1F6C1;BATHTUB;So;0;ON;;;;;N;;;;; +1F6C2;PASSPORT CONTROL;So;0;ON;;;;;N;;;;; +1F6C3;CUSTOMS;So;0;ON;;;;;N;;;;; +1F6C4;BAGGAGE CLAIM;So;0;ON;;;;;N;;;;; +1F6C5;LEFT LUGGAGE;So;0;ON;;;;;N;;;;; +1F700;ALCHEMICAL SYMBOL FOR QUINTESSENCE;So;0;ON;;;;;N;;;;; +1F701;ALCHEMICAL SYMBOL FOR AIR;So;0;ON;;;;;N;;;;; +1F702;ALCHEMICAL SYMBOL FOR FIRE;So;0;ON;;;;;N;;;;; +1F703;ALCHEMICAL SYMBOL FOR EARTH;So;0;ON;;;;;N;;;;; +1F704;ALCHEMICAL SYMBOL FOR WATER;So;0;ON;;;;;N;;;;; +1F705;ALCHEMICAL SYMBOL FOR AQUAFORTIS;So;0;ON;;;;;N;;;;; +1F706;ALCHEMICAL SYMBOL FOR AQUA REGIA;So;0;ON;;;;;N;;;;; +1F707;ALCHEMICAL SYMBOL FOR AQUA REGIA-2;So;0;ON;;;;;N;;;;; +1F708;ALCHEMICAL SYMBOL FOR AQUA VITAE;So;0;ON;;;;;N;;;;; +1F709;ALCHEMICAL SYMBOL FOR AQUA VITAE-2;So;0;ON;;;;;N;;;;; +1F70A;ALCHEMICAL SYMBOL FOR VINEGAR;So;0;ON;;;;;N;;;;; +1F70B;ALCHEMICAL SYMBOL FOR VINEGAR-2;So;0;ON;;;;;N;;;;; +1F70C;ALCHEMICAL SYMBOL FOR VINEGAR-3;So;0;ON;;;;;N;;;;; +1F70D;ALCHEMICAL SYMBOL FOR SULFUR;So;0;ON;;;;;N;;;;; +1F70E;ALCHEMICAL SYMBOL FOR PHILOSOPHERS SULFUR;So;0;ON;;;;;N;;;;; +1F70F;ALCHEMICAL SYMBOL FOR BLACK SULFUR;So;0;ON;;;;;N;;;;; +1F710;ALCHEMICAL SYMBOL FOR MERCURY SUBLIMATE;So;0;ON;;;;;N;;;;; +1F711;ALCHEMICAL SYMBOL FOR MERCURY SUBLIMATE-2;So;0;ON;;;;;N;;;;; +1F712;ALCHEMICAL SYMBOL FOR MERCURY SUBLIMATE-3;So;0;ON;;;;;N;;;;; +1F713;ALCHEMICAL SYMBOL FOR CINNABAR;So;0;ON;;;;;N;;;;; +1F714;ALCHEMICAL SYMBOL FOR SALT;So;0;ON;;;;;N;;;;; +1F715;ALCHEMICAL SYMBOL FOR NITRE;So;0;ON;;;;;N;;;;; +1F716;ALCHEMICAL SYMBOL FOR VITRIOL;So;0;ON;;;;;N;;;;; +1F717;ALCHEMICAL SYMBOL FOR VITRIOL-2;So;0;ON;;;;;N;;;;; +1F718;ALCHEMICAL SYMBOL FOR ROCK SALT;So;0;ON;;;;;N;;;;; +1F719;ALCHEMICAL SYMBOL FOR ROCK SALT-2;So;0;ON;;;;;N;;;;; +1F71A;ALCHEMICAL SYMBOL FOR GOLD;So;0;ON;;;;;N;;;;; +1F71B;ALCHEMICAL SYMBOL FOR SILVER;So;0;ON;;;;;N;;;;; +1F71C;ALCHEMICAL SYMBOL FOR IRON ORE;So;0;ON;;;;;N;;;;; +1F71D;ALCHEMICAL SYMBOL FOR IRON ORE-2;So;0;ON;;;;;N;;;;; +1F71E;ALCHEMICAL SYMBOL FOR CROCUS OF IRON;So;0;ON;;;;;N;;;;; +1F71F;ALCHEMICAL SYMBOL FOR REGULUS OF IRON;So;0;ON;;;;;N;;;;; +1F720;ALCHEMICAL SYMBOL FOR COPPER ORE;So;0;ON;;;;;N;;;;; +1F721;ALCHEMICAL SYMBOL FOR IRON-COPPER ORE;So;0;ON;;;;;N;;;;; +1F722;ALCHEMICAL SYMBOL FOR SUBLIMATE OF COPPER;So;0;ON;;;;;N;;;;; +1F723;ALCHEMICAL SYMBOL FOR CROCUS OF COPPER;So;0;ON;;;;;N;;;;; +1F724;ALCHEMICAL SYMBOL FOR CROCUS OF COPPER-2;So;0;ON;;;;;N;;;;; +1F725;ALCHEMICAL SYMBOL FOR COPPER ANTIMONIATE;So;0;ON;;;;;N;;;;; +1F726;ALCHEMICAL SYMBOL FOR SALT OF COPPER ANTIMONIATE;So;0;ON;;;;;N;;;;; +1F727;ALCHEMICAL SYMBOL FOR SUBLIMATE OF SALT OF COPPER;So;0;ON;;;;;N;;;;; +1F728;ALCHEMICAL SYMBOL FOR VERDIGRIS;So;0;ON;;;;;N;;;;; +1F729;ALCHEMICAL SYMBOL FOR TIN ORE;So;0;ON;;;;;N;;;;; +1F72A;ALCHEMICAL SYMBOL FOR LEAD ORE;So;0;ON;;;;;N;;;;; +1F72B;ALCHEMICAL SYMBOL FOR ANTIMONY ORE;So;0;ON;;;;;N;;;;; +1F72C;ALCHEMICAL SYMBOL FOR SUBLIMATE OF ANTIMONY;So;0;ON;;;;;N;;;;; +1F72D;ALCHEMICAL SYMBOL FOR SALT OF ANTIMONY;So;0;ON;;;;;N;;;;; +1F72E;ALCHEMICAL SYMBOL FOR SUBLIMATE OF SALT OF ANTIMONY;So;0;ON;;;;;N;;;;; +1F72F;ALCHEMICAL SYMBOL FOR VINEGAR OF ANTIMONY;So;0;ON;;;;;N;;;;; +1F730;ALCHEMICAL SYMBOL FOR REGULUS OF ANTIMONY;So;0;ON;;;;;N;;;;; +1F731;ALCHEMICAL SYMBOL FOR REGULUS OF ANTIMONY-2;So;0;ON;;;;;N;;;;; +1F732;ALCHEMICAL SYMBOL FOR REGULUS;So;0;ON;;;;;N;;;;; +1F733;ALCHEMICAL SYMBOL FOR REGULUS-2;So;0;ON;;;;;N;;;;; +1F734;ALCHEMICAL SYMBOL FOR REGULUS-3;So;0;ON;;;;;N;;;;; +1F735;ALCHEMICAL SYMBOL FOR REGULUS-4;So;0;ON;;;;;N;;;;; +1F736;ALCHEMICAL SYMBOL FOR ALKALI;So;0;ON;;;;;N;;;;; +1F737;ALCHEMICAL SYMBOL FOR ALKALI-2;So;0;ON;;;;;N;;;;; +1F738;ALCHEMICAL SYMBOL FOR MARCASITE;So;0;ON;;;;;N;;;;; +1F739;ALCHEMICAL SYMBOL FOR SAL-AMMONIAC;So;0;ON;;;;;N;;;;; +1F73A;ALCHEMICAL SYMBOL FOR ARSENIC;So;0;ON;;;;;N;;;;; +1F73B;ALCHEMICAL SYMBOL FOR REALGAR;So;0;ON;;;;;N;;;;; +1F73C;ALCHEMICAL SYMBOL FOR REALGAR-2;So;0;ON;;;;;N;;;;; +1F73D;ALCHEMICAL SYMBOL FOR AURIPIGMENT;So;0;ON;;;;;N;;;;; +1F73E;ALCHEMICAL SYMBOL FOR BISMUTH ORE;So;0;ON;;;;;N;;;;; +1F73F;ALCHEMICAL SYMBOL FOR TARTAR;So;0;ON;;;;;N;;;;; +1F740;ALCHEMICAL SYMBOL FOR TARTAR-2;So;0;ON;;;;;N;;;;; +1F741;ALCHEMICAL SYMBOL FOR QUICK LIME;So;0;ON;;;;;N;;;;; +1F742;ALCHEMICAL SYMBOL FOR BORAX;So;0;ON;;;;;N;;;;; +1F743;ALCHEMICAL SYMBOL FOR BORAX-2;So;0;ON;;;;;N;;;;; +1F744;ALCHEMICAL SYMBOL FOR BORAX-3;So;0;ON;;;;;N;;;;; +1F745;ALCHEMICAL SYMBOL FOR ALUM;So;0;ON;;;;;N;;;;; +1F746;ALCHEMICAL SYMBOL FOR OIL;So;0;ON;;;;;N;;;;; +1F747;ALCHEMICAL SYMBOL FOR SPIRIT;So;0;ON;;;;;N;;;;; +1F748;ALCHEMICAL SYMBOL FOR TINCTURE;So;0;ON;;;;;N;;;;; +1F749;ALCHEMICAL SYMBOL FOR GUM;So;0;ON;;;;;N;;;;; +1F74A;ALCHEMICAL SYMBOL FOR WAX;So;0;ON;;;;;N;;;;; +1F74B;ALCHEMICAL SYMBOL FOR POWDER;So;0;ON;;;;;N;;;;; +1F74C;ALCHEMICAL SYMBOL FOR CALX;So;0;ON;;;;;N;;;;; +1F74D;ALCHEMICAL SYMBOL FOR TUTTY;So;0;ON;;;;;N;;;;; +1F74E;ALCHEMICAL SYMBOL FOR CAPUT MORTUUM;So;0;ON;;;;;N;;;;; +1F74F;ALCHEMICAL SYMBOL FOR SCEPTER OF JOVE;So;0;ON;;;;;N;;;;; +1F750;ALCHEMICAL SYMBOL FOR CADUCEUS;So;0;ON;;;;;N;;;;; +1F751;ALCHEMICAL SYMBOL FOR TRIDENT;So;0;ON;;;;;N;;;;; +1F752;ALCHEMICAL SYMBOL FOR STARRED TRIDENT;So;0;ON;;;;;N;;;;; +1F753;ALCHEMICAL SYMBOL FOR LODESTONE;So;0;ON;;;;;N;;;;; +1F754;ALCHEMICAL SYMBOL FOR SOAP;So;0;ON;;;;;N;;;;; +1F755;ALCHEMICAL SYMBOL FOR URINE;So;0;ON;;;;;N;;;;; +1F756;ALCHEMICAL SYMBOL FOR HORSE DUNG;So;0;ON;;;;;N;;;;; +1F757;ALCHEMICAL SYMBOL FOR ASHES;So;0;ON;;;;;N;;;;; +1F758;ALCHEMICAL SYMBOL FOR POT ASHES;So;0;ON;;;;;N;;;;; +1F759;ALCHEMICAL SYMBOL FOR BRICK;So;0;ON;;;;;N;;;;; +1F75A;ALCHEMICAL SYMBOL FOR POWDERED BRICK;So;0;ON;;;;;N;;;;; +1F75B;ALCHEMICAL SYMBOL FOR AMALGAM;So;0;ON;;;;;N;;;;; +1F75C;ALCHEMICAL SYMBOL FOR STRATUM SUPER STRATUM;So;0;ON;;;;;N;;;;; +1F75D;ALCHEMICAL SYMBOL FOR STRATUM SUPER STRATUM-2;So;0;ON;;;;;N;;;;; +1F75E;ALCHEMICAL SYMBOL FOR SUBLIMATION;So;0;ON;;;;;N;;;;; +1F75F;ALCHEMICAL SYMBOL FOR PRECIPITATE;So;0;ON;;;;;N;;;;; +1F760;ALCHEMICAL SYMBOL FOR DISTILL;So;0;ON;;;;;N;;;;; +1F761;ALCHEMICAL SYMBOL FOR DISSOLVE;So;0;ON;;;;;N;;;;; +1F762;ALCHEMICAL SYMBOL FOR DISSOLVE-2;So;0;ON;;;;;N;;;;; +1F763;ALCHEMICAL SYMBOL FOR PURIFY;So;0;ON;;;;;N;;;;; +1F764;ALCHEMICAL SYMBOL FOR PUTREFACTION;So;0;ON;;;;;N;;;;; +1F765;ALCHEMICAL SYMBOL FOR CRUCIBLE;So;0;ON;;;;;N;;;;; +1F766;ALCHEMICAL SYMBOL FOR CRUCIBLE-2;So;0;ON;;;;;N;;;;; +1F767;ALCHEMICAL SYMBOL FOR CRUCIBLE-3;So;0;ON;;;;;N;;;;; +1F768;ALCHEMICAL SYMBOL FOR CRUCIBLE-4;So;0;ON;;;;;N;;;;; +1F769;ALCHEMICAL SYMBOL FOR CRUCIBLE-5;So;0;ON;;;;;N;;;;; +1F76A;ALCHEMICAL SYMBOL FOR ALEMBIC;So;0;ON;;;;;N;;;;; +1F76B;ALCHEMICAL SYMBOL FOR BATH OF MARY;So;0;ON;;;;;N;;;;; +1F76C;ALCHEMICAL SYMBOL FOR BATH OF VAPOURS;So;0;ON;;;;;N;;;;; +1F76D;ALCHEMICAL SYMBOL FOR RETORT;So;0;ON;;;;;N;;;;; +1F76E;ALCHEMICAL SYMBOL FOR HOUR;So;0;ON;;;;;N;;;;; +1F76F;ALCHEMICAL SYMBOL FOR NIGHT;So;0;ON;;;;;N;;;;; +1F770;ALCHEMICAL SYMBOL FOR DAY-NIGHT;So;0;ON;;;;;N;;;;; +1F771;ALCHEMICAL SYMBOL FOR MONTH;So;0;ON;;;;;N;;;;; +1F772;ALCHEMICAL SYMBOL FOR HALF DRAM;So;0;ON;;;;;N;;;;; +1F773;ALCHEMICAL SYMBOL FOR HALF OUNCE;So;0;ON;;;;;N;;;;; +20000;;Lo;0;L;;;;;N;;;;; +2A6D6;;Lo;0;L;;;;;N;;;;; +2A700;;Lo;0;L;;;;;N;;;;; +2B734;;Lo;0;L;;;;;N;;;;; +2B740;;Lo;0;L;;;;;N;;;;; +2B81D;;Lo;0;L;;;;;N;;;;; +2F800;CJK COMPATIBILITY IDEOGRAPH-2F800;Lo;0;L;4E3D;;;;N;;;;; +2F801;CJK COMPATIBILITY IDEOGRAPH-2F801;Lo;0;L;4E38;;;;N;;;;; +2F802;CJK COMPATIBILITY IDEOGRAPH-2F802;Lo;0;L;4E41;;;;N;;;;; +2F803;CJK COMPATIBILITY IDEOGRAPH-2F803;Lo;0;L;20122;;;;N;;;;; +2F804;CJK COMPATIBILITY IDEOGRAPH-2F804;Lo;0;L;4F60;;;;N;;;;; +2F805;CJK COMPATIBILITY IDEOGRAPH-2F805;Lo;0;L;4FAE;;;;N;;;;; +2F806;CJK COMPATIBILITY IDEOGRAPH-2F806;Lo;0;L;4FBB;;;;N;;;;; +2F807;CJK COMPATIBILITY IDEOGRAPH-2F807;Lo;0;L;5002;;;;N;;;;; +2F808;CJK COMPATIBILITY IDEOGRAPH-2F808;Lo;0;L;507A;;;;N;;;;; +2F809;CJK COMPATIBILITY IDEOGRAPH-2F809;Lo;0;L;5099;;;;N;;;;; +2F80A;CJK COMPATIBILITY IDEOGRAPH-2F80A;Lo;0;L;50E7;;;;N;;;;; +2F80B;CJK COMPATIBILITY IDEOGRAPH-2F80B;Lo;0;L;50CF;;;;N;;;;; +2F80C;CJK COMPATIBILITY IDEOGRAPH-2F80C;Lo;0;L;349E;;;;N;;;;; +2F80D;CJK COMPATIBILITY IDEOGRAPH-2F80D;Lo;0;L;2063A;;;;N;;;;; +2F80E;CJK COMPATIBILITY IDEOGRAPH-2F80E;Lo;0;L;514D;;;;N;;;;; +2F80F;CJK COMPATIBILITY IDEOGRAPH-2F80F;Lo;0;L;5154;;;;N;;;;; +2F810;CJK COMPATIBILITY IDEOGRAPH-2F810;Lo;0;L;5164;;;;N;;;;; +2F811;CJK COMPATIBILITY IDEOGRAPH-2F811;Lo;0;L;5177;;;;N;;;;; +2F812;CJK COMPATIBILITY IDEOGRAPH-2F812;Lo;0;L;2051C;;;;N;;;;; +2F813;CJK COMPATIBILITY IDEOGRAPH-2F813;Lo;0;L;34B9;;;;N;;;;; +2F814;CJK COMPATIBILITY IDEOGRAPH-2F814;Lo;0;L;5167;;;;N;;;;; +2F815;CJK COMPATIBILITY IDEOGRAPH-2F815;Lo;0;L;518D;;;;N;;;;; +2F816;CJK COMPATIBILITY IDEOGRAPH-2F816;Lo;0;L;2054B;;;;N;;;;; +2F817;CJK COMPATIBILITY IDEOGRAPH-2F817;Lo;0;L;5197;;;;N;;;;; +2F818;CJK COMPATIBILITY IDEOGRAPH-2F818;Lo;0;L;51A4;;;;N;;;;; +2F819;CJK COMPATIBILITY IDEOGRAPH-2F819;Lo;0;L;4ECC;;;;N;;;;; +2F81A;CJK COMPATIBILITY IDEOGRAPH-2F81A;Lo;0;L;51AC;;;;N;;;;; +2F81B;CJK COMPATIBILITY IDEOGRAPH-2F81B;Lo;0;L;51B5;;;;N;;;;; +2F81C;CJK COMPATIBILITY IDEOGRAPH-2F81C;Lo;0;L;291DF;;;;N;;;;; +2F81D;CJK COMPATIBILITY IDEOGRAPH-2F81D;Lo;0;L;51F5;;;;N;;;;; +2F81E;CJK COMPATIBILITY IDEOGRAPH-2F81E;Lo;0;L;5203;;;;N;;;;; +2F81F;CJK COMPATIBILITY IDEOGRAPH-2F81F;Lo;0;L;34DF;;;;N;;;;; +2F820;CJK COMPATIBILITY IDEOGRAPH-2F820;Lo;0;L;523B;;;;N;;;;; +2F821;CJK COMPATIBILITY IDEOGRAPH-2F821;Lo;0;L;5246;;;;N;;;;; +2F822;CJK COMPATIBILITY IDEOGRAPH-2F822;Lo;0;L;5272;;;;N;;;;; +2F823;CJK COMPATIBILITY IDEOGRAPH-2F823;Lo;0;L;5277;;;;N;;;;; +2F824;CJK COMPATIBILITY IDEOGRAPH-2F824;Lo;0;L;3515;;;;N;;;;; +2F825;CJK COMPATIBILITY IDEOGRAPH-2F825;Lo;0;L;52C7;;;;N;;;;; +2F826;CJK COMPATIBILITY IDEOGRAPH-2F826;Lo;0;L;52C9;;;;N;;;;; +2F827;CJK COMPATIBILITY IDEOGRAPH-2F827;Lo;0;L;52E4;;;;N;;;;; +2F828;CJK COMPATIBILITY IDEOGRAPH-2F828;Lo;0;L;52FA;;;;N;;;;; +2F829;CJK COMPATIBILITY IDEOGRAPH-2F829;Lo;0;L;5305;;;;N;;;;; +2F82A;CJK COMPATIBILITY IDEOGRAPH-2F82A;Lo;0;L;5306;;;;N;;;;; +2F82B;CJK COMPATIBILITY IDEOGRAPH-2F82B;Lo;0;L;5317;;;;N;;;;; +2F82C;CJK COMPATIBILITY IDEOGRAPH-2F82C;Lo;0;L;5349;;;;N;;;;; +2F82D;CJK COMPATIBILITY IDEOGRAPH-2F82D;Lo;0;L;5351;;;;N;;;;; +2F82E;CJK COMPATIBILITY IDEOGRAPH-2F82E;Lo;0;L;535A;;;;N;;;;; +2F82F;CJK COMPATIBILITY IDEOGRAPH-2F82F;Lo;0;L;5373;;;;N;;;;; +2F830;CJK COMPATIBILITY IDEOGRAPH-2F830;Lo;0;L;537D;;;;N;;;;; +2F831;CJK COMPATIBILITY IDEOGRAPH-2F831;Lo;0;L;537F;;;;N;;;;; +2F832;CJK COMPATIBILITY IDEOGRAPH-2F832;Lo;0;L;537F;;;;N;;;;; +2F833;CJK COMPATIBILITY IDEOGRAPH-2F833;Lo;0;L;537F;;;;N;;;;; +2F834;CJK COMPATIBILITY IDEOGRAPH-2F834;Lo;0;L;20A2C;;;;N;;;;; +2F835;CJK COMPATIBILITY IDEOGRAPH-2F835;Lo;0;L;7070;;;;N;;;;; +2F836;CJK COMPATIBILITY IDEOGRAPH-2F836;Lo;0;L;53CA;;;;N;;;;; +2F837;CJK COMPATIBILITY IDEOGRAPH-2F837;Lo;0;L;53DF;;;;N;;;;; +2F838;CJK COMPATIBILITY IDEOGRAPH-2F838;Lo;0;L;20B63;;;;N;;;;; +2F839;CJK COMPATIBILITY IDEOGRAPH-2F839;Lo;0;L;53EB;;;;N;;;;; +2F83A;CJK COMPATIBILITY IDEOGRAPH-2F83A;Lo;0;L;53F1;;;;N;;;;; +2F83B;CJK COMPATIBILITY IDEOGRAPH-2F83B;Lo;0;L;5406;;;;N;;;;; +2F83C;CJK COMPATIBILITY IDEOGRAPH-2F83C;Lo;0;L;549E;;;;N;;;;; +2F83D;CJK COMPATIBILITY IDEOGRAPH-2F83D;Lo;0;L;5438;;;;N;;;;; +2F83E;CJK COMPATIBILITY IDEOGRAPH-2F83E;Lo;0;L;5448;;;;N;;;;; +2F83F;CJK COMPATIBILITY IDEOGRAPH-2F83F;Lo;0;L;5468;;;;N;;;;; +2F840;CJK COMPATIBILITY IDEOGRAPH-2F840;Lo;0;L;54A2;;;;N;;;;; +2F841;CJK COMPATIBILITY IDEOGRAPH-2F841;Lo;0;L;54F6;;;;N;;;;; +2F842;CJK COMPATIBILITY IDEOGRAPH-2F842;Lo;0;L;5510;;;;N;;;;; +2F843;CJK COMPATIBILITY IDEOGRAPH-2F843;Lo;0;L;5553;;;;N;;;;; +2F844;CJK COMPATIBILITY IDEOGRAPH-2F844;Lo;0;L;5563;;;;N;;;;; +2F845;CJK COMPATIBILITY IDEOGRAPH-2F845;Lo;0;L;5584;;;;N;;;;; +2F846;CJK COMPATIBILITY IDEOGRAPH-2F846;Lo;0;L;5584;;;;N;;;;; +2F847;CJK COMPATIBILITY IDEOGRAPH-2F847;Lo;0;L;5599;;;;N;;;;; +2F848;CJK COMPATIBILITY IDEOGRAPH-2F848;Lo;0;L;55AB;;;;N;;;;; +2F849;CJK COMPATIBILITY IDEOGRAPH-2F849;Lo;0;L;55B3;;;;N;;;;; +2F84A;CJK COMPATIBILITY IDEOGRAPH-2F84A;Lo;0;L;55C2;;;;N;;;;; +2F84B;CJK COMPATIBILITY IDEOGRAPH-2F84B;Lo;0;L;5716;;;;N;;;;; +2F84C;CJK COMPATIBILITY IDEOGRAPH-2F84C;Lo;0;L;5606;;;;N;;;;; +2F84D;CJK COMPATIBILITY IDEOGRAPH-2F84D;Lo;0;L;5717;;;;N;;;;; +2F84E;CJK COMPATIBILITY IDEOGRAPH-2F84E;Lo;0;L;5651;;;;N;;;;; +2F84F;CJK COMPATIBILITY IDEOGRAPH-2F84F;Lo;0;L;5674;;;;N;;;;; +2F850;CJK COMPATIBILITY IDEOGRAPH-2F850;Lo;0;L;5207;;;;N;;;;; +2F851;CJK COMPATIBILITY IDEOGRAPH-2F851;Lo;0;L;58EE;;;;N;;;;; +2F852;CJK COMPATIBILITY IDEOGRAPH-2F852;Lo;0;L;57CE;;;;N;;;;; +2F853;CJK COMPATIBILITY IDEOGRAPH-2F853;Lo;0;L;57F4;;;;N;;;;; +2F854;CJK COMPATIBILITY IDEOGRAPH-2F854;Lo;0;L;580D;;;;N;;;;; +2F855;CJK COMPATIBILITY IDEOGRAPH-2F855;Lo;0;L;578B;;;;N;;;;; +2F856;CJK COMPATIBILITY IDEOGRAPH-2F856;Lo;0;L;5832;;;;N;;;;; +2F857;CJK COMPATIBILITY IDEOGRAPH-2F857;Lo;0;L;5831;;;;N;;;;; +2F858;CJK COMPATIBILITY IDEOGRAPH-2F858;Lo;0;L;58AC;;;;N;;;;; +2F859;CJK COMPATIBILITY IDEOGRAPH-2F859;Lo;0;L;214E4;;;;N;;;;; +2F85A;CJK COMPATIBILITY IDEOGRAPH-2F85A;Lo;0;L;58F2;;;;N;;;;; +2F85B;CJK COMPATIBILITY IDEOGRAPH-2F85B;Lo;0;L;58F7;;;;N;;;;; +2F85C;CJK COMPATIBILITY IDEOGRAPH-2F85C;Lo;0;L;5906;;;;N;;;;; +2F85D;CJK COMPATIBILITY IDEOGRAPH-2F85D;Lo;0;L;591A;;;;N;;;;; +2F85E;CJK COMPATIBILITY IDEOGRAPH-2F85E;Lo;0;L;5922;;;;N;;;;; +2F85F;CJK COMPATIBILITY IDEOGRAPH-2F85F;Lo;0;L;5962;;;;N;;;;; +2F860;CJK COMPATIBILITY IDEOGRAPH-2F860;Lo;0;L;216A8;;;;N;;;;; +2F861;CJK COMPATIBILITY IDEOGRAPH-2F861;Lo;0;L;216EA;;;;N;;;;; +2F862;CJK COMPATIBILITY IDEOGRAPH-2F862;Lo;0;L;59EC;;;;N;;;;; +2F863;CJK COMPATIBILITY IDEOGRAPH-2F863;Lo;0;L;5A1B;;;;N;;;;; +2F864;CJK COMPATIBILITY IDEOGRAPH-2F864;Lo;0;L;5A27;;;;N;;;;; +2F865;CJK COMPATIBILITY IDEOGRAPH-2F865;Lo;0;L;59D8;;;;N;;;;; +2F866;CJK COMPATIBILITY IDEOGRAPH-2F866;Lo;0;L;5A66;;;;N;;;;; +2F867;CJK COMPATIBILITY IDEOGRAPH-2F867;Lo;0;L;36EE;;;;N;;;;; +2F868;CJK COMPATIBILITY IDEOGRAPH-2F868;Lo;0;L;36FC;;;;N;;;;; +2F869;CJK COMPATIBILITY IDEOGRAPH-2F869;Lo;0;L;5B08;;;;N;;;;; +2F86A;CJK COMPATIBILITY IDEOGRAPH-2F86A;Lo;0;L;5B3E;;;;N;;;;; +2F86B;CJK COMPATIBILITY IDEOGRAPH-2F86B;Lo;0;L;5B3E;;;;N;;;;; +2F86C;CJK COMPATIBILITY IDEOGRAPH-2F86C;Lo;0;L;219C8;;;;N;;;;; +2F86D;CJK COMPATIBILITY IDEOGRAPH-2F86D;Lo;0;L;5BC3;;;;N;;;;; +2F86E;CJK COMPATIBILITY IDEOGRAPH-2F86E;Lo;0;L;5BD8;;;;N;;;;; +2F86F;CJK COMPATIBILITY IDEOGRAPH-2F86F;Lo;0;L;5BE7;;;;N;;;;; +2F870;CJK COMPATIBILITY IDEOGRAPH-2F870;Lo;0;L;5BF3;;;;N;;;;; +2F871;CJK COMPATIBILITY IDEOGRAPH-2F871;Lo;0;L;21B18;;;;N;;;;; +2F872;CJK COMPATIBILITY IDEOGRAPH-2F872;Lo;0;L;5BFF;;;;N;;;;; +2F873;CJK COMPATIBILITY IDEOGRAPH-2F873;Lo;0;L;5C06;;;;N;;;;; +2F874;CJK COMPATIBILITY IDEOGRAPH-2F874;Lo;0;L;5F53;;;;N;;;;; +2F875;CJK COMPATIBILITY IDEOGRAPH-2F875;Lo;0;L;5C22;;;;N;;;;; +2F876;CJK COMPATIBILITY IDEOGRAPH-2F876;Lo;0;L;3781;;;;N;;;;; +2F877;CJK COMPATIBILITY IDEOGRAPH-2F877;Lo;0;L;5C60;;;;N;;;;; +2F878;CJK COMPATIBILITY IDEOGRAPH-2F878;Lo;0;L;5C6E;;;;N;;;;; +2F879;CJK COMPATIBILITY IDEOGRAPH-2F879;Lo;0;L;5CC0;;;;N;;;;; +2F87A;CJK COMPATIBILITY IDEOGRAPH-2F87A;Lo;0;L;5C8D;;;;N;;;;; +2F87B;CJK COMPATIBILITY IDEOGRAPH-2F87B;Lo;0;L;21DE4;;;;N;;;;; +2F87C;CJK COMPATIBILITY IDEOGRAPH-2F87C;Lo;0;L;5D43;;;;N;;;;; +2F87D;CJK COMPATIBILITY IDEOGRAPH-2F87D;Lo;0;L;21DE6;;;;N;;;;; +2F87E;CJK COMPATIBILITY IDEOGRAPH-2F87E;Lo;0;L;5D6E;;;;N;;;;; +2F87F;CJK COMPATIBILITY IDEOGRAPH-2F87F;Lo;0;L;5D6B;;;;N;;;;; +2F880;CJK COMPATIBILITY IDEOGRAPH-2F880;Lo;0;L;5D7C;;;;N;;;;; +2F881;CJK COMPATIBILITY IDEOGRAPH-2F881;Lo;0;L;5DE1;;;;N;;;;; +2F882;CJK COMPATIBILITY IDEOGRAPH-2F882;Lo;0;L;5DE2;;;;N;;;;; +2F883;CJK COMPATIBILITY IDEOGRAPH-2F883;Lo;0;L;382F;;;;N;;;;; +2F884;CJK COMPATIBILITY IDEOGRAPH-2F884;Lo;0;L;5DFD;;;;N;;;;; +2F885;CJK COMPATIBILITY IDEOGRAPH-2F885;Lo;0;L;5E28;;;;N;;;;; +2F886;CJK COMPATIBILITY IDEOGRAPH-2F886;Lo;0;L;5E3D;;;;N;;;;; +2F887;CJK COMPATIBILITY IDEOGRAPH-2F887;Lo;0;L;5E69;;;;N;;;;; +2F888;CJK COMPATIBILITY IDEOGRAPH-2F888;Lo;0;L;3862;;;;N;;;;; +2F889;CJK COMPATIBILITY IDEOGRAPH-2F889;Lo;0;L;22183;;;;N;;;;; +2F88A;CJK COMPATIBILITY IDEOGRAPH-2F88A;Lo;0;L;387C;;;;N;;;;; +2F88B;CJK COMPATIBILITY IDEOGRAPH-2F88B;Lo;0;L;5EB0;;;;N;;;;; +2F88C;CJK COMPATIBILITY IDEOGRAPH-2F88C;Lo;0;L;5EB3;;;;N;;;;; +2F88D;CJK COMPATIBILITY IDEOGRAPH-2F88D;Lo;0;L;5EB6;;;;N;;;;; +2F88E;CJK COMPATIBILITY IDEOGRAPH-2F88E;Lo;0;L;5ECA;;;;N;;;;; +2F88F;CJK COMPATIBILITY IDEOGRAPH-2F88F;Lo;0;L;2A392;;;;N;;;;; +2F890;CJK COMPATIBILITY IDEOGRAPH-2F890;Lo;0;L;5EFE;;;9;N;;;;; +2F891;CJK COMPATIBILITY IDEOGRAPH-2F891;Lo;0;L;22331;;;;N;;;;; +2F892;CJK COMPATIBILITY IDEOGRAPH-2F892;Lo;0;L;22331;;;;N;;;;; +2F893;CJK COMPATIBILITY IDEOGRAPH-2F893;Lo;0;L;8201;;;;N;;;;; +2F894;CJK COMPATIBILITY IDEOGRAPH-2F894;Lo;0;L;5F22;;;;N;;;;; +2F895;CJK COMPATIBILITY IDEOGRAPH-2F895;Lo;0;L;5F22;;;;N;;;;; +2F896;CJK COMPATIBILITY IDEOGRAPH-2F896;Lo;0;L;38C7;;;;N;;;;; +2F897;CJK COMPATIBILITY IDEOGRAPH-2F897;Lo;0;L;232B8;;;;N;;;;; +2F898;CJK COMPATIBILITY IDEOGRAPH-2F898;Lo;0;L;261DA;;;;N;;;;; +2F899;CJK COMPATIBILITY IDEOGRAPH-2F899;Lo;0;L;5F62;;;;N;;;;; +2F89A;CJK COMPATIBILITY IDEOGRAPH-2F89A;Lo;0;L;5F6B;;;;N;;;;; +2F89B;CJK COMPATIBILITY IDEOGRAPH-2F89B;Lo;0;L;38E3;;;;N;;;;; +2F89C;CJK COMPATIBILITY IDEOGRAPH-2F89C;Lo;0;L;5F9A;;;;N;;;;; +2F89D;CJK COMPATIBILITY IDEOGRAPH-2F89D;Lo;0;L;5FCD;;;;N;;;;; +2F89E;CJK COMPATIBILITY IDEOGRAPH-2F89E;Lo;0;L;5FD7;;;;N;;;;; +2F89F;CJK COMPATIBILITY IDEOGRAPH-2F89F;Lo;0;L;5FF9;;;;N;;;;; +2F8A0;CJK COMPATIBILITY IDEOGRAPH-2F8A0;Lo;0;L;6081;;;;N;;;;; +2F8A1;CJK COMPATIBILITY IDEOGRAPH-2F8A1;Lo;0;L;393A;;;;N;;;;; +2F8A2;CJK COMPATIBILITY IDEOGRAPH-2F8A2;Lo;0;L;391C;;;;N;;;;; +2F8A3;CJK COMPATIBILITY IDEOGRAPH-2F8A3;Lo;0;L;6094;;;;N;;;;; +2F8A4;CJK COMPATIBILITY IDEOGRAPH-2F8A4;Lo;0;L;226D4;;;;N;;;;; +2F8A5;CJK COMPATIBILITY IDEOGRAPH-2F8A5;Lo;0;L;60C7;;;;N;;;;; +2F8A6;CJK COMPATIBILITY IDEOGRAPH-2F8A6;Lo;0;L;6148;;;;N;;;;; +2F8A7;CJK COMPATIBILITY IDEOGRAPH-2F8A7;Lo;0;L;614C;;;;N;;;;; +2F8A8;CJK COMPATIBILITY IDEOGRAPH-2F8A8;Lo;0;L;614E;;;;N;;;;; +2F8A9;CJK COMPATIBILITY IDEOGRAPH-2F8A9;Lo;0;L;614C;;;;N;;;;; +2F8AA;CJK COMPATIBILITY IDEOGRAPH-2F8AA;Lo;0;L;617A;;;;N;;;;; +2F8AB;CJK COMPATIBILITY IDEOGRAPH-2F8AB;Lo;0;L;618E;;;;N;;;;; +2F8AC;CJK COMPATIBILITY IDEOGRAPH-2F8AC;Lo;0;L;61B2;;;;N;;;;; +2F8AD;CJK COMPATIBILITY IDEOGRAPH-2F8AD;Lo;0;L;61A4;;;;N;;;;; +2F8AE;CJK COMPATIBILITY IDEOGRAPH-2F8AE;Lo;0;L;61AF;;;;N;;;;; +2F8AF;CJK COMPATIBILITY IDEOGRAPH-2F8AF;Lo;0;L;61DE;;;;N;;;;; +2F8B0;CJK COMPATIBILITY IDEOGRAPH-2F8B0;Lo;0;L;61F2;;;;N;;;;; +2F8B1;CJK COMPATIBILITY IDEOGRAPH-2F8B1;Lo;0;L;61F6;;;;N;;;;; +2F8B2;CJK COMPATIBILITY IDEOGRAPH-2F8B2;Lo;0;L;6210;;;;N;;;;; +2F8B3;CJK COMPATIBILITY IDEOGRAPH-2F8B3;Lo;0;L;621B;;;;N;;;;; +2F8B4;CJK COMPATIBILITY IDEOGRAPH-2F8B4;Lo;0;L;625D;;;;N;;;;; +2F8B5;CJK COMPATIBILITY IDEOGRAPH-2F8B5;Lo;0;L;62B1;;;;N;;;;; +2F8B6;CJK COMPATIBILITY IDEOGRAPH-2F8B6;Lo;0;L;62D4;;;;N;;;;; +2F8B7;CJK COMPATIBILITY IDEOGRAPH-2F8B7;Lo;0;L;6350;;;;N;;;;; +2F8B8;CJK COMPATIBILITY IDEOGRAPH-2F8B8;Lo;0;L;22B0C;;;;N;;;;; +2F8B9;CJK COMPATIBILITY IDEOGRAPH-2F8B9;Lo;0;L;633D;;;;N;;;;; +2F8BA;CJK COMPATIBILITY IDEOGRAPH-2F8BA;Lo;0;L;62FC;;;;N;;;;; +2F8BB;CJK COMPATIBILITY IDEOGRAPH-2F8BB;Lo;0;L;6368;;;;N;;;;; +2F8BC;CJK COMPATIBILITY IDEOGRAPH-2F8BC;Lo;0;L;6383;;;;N;;;;; +2F8BD;CJK COMPATIBILITY IDEOGRAPH-2F8BD;Lo;0;L;63E4;;;;N;;;;; +2F8BE;CJK COMPATIBILITY IDEOGRAPH-2F8BE;Lo;0;L;22BF1;;;;N;;;;; +2F8BF;CJK COMPATIBILITY IDEOGRAPH-2F8BF;Lo;0;L;6422;;;;N;;;;; +2F8C0;CJK COMPATIBILITY IDEOGRAPH-2F8C0;Lo;0;L;63C5;;;;N;;;;; +2F8C1;CJK COMPATIBILITY IDEOGRAPH-2F8C1;Lo;0;L;63A9;;;;N;;;;; +2F8C2;CJK COMPATIBILITY IDEOGRAPH-2F8C2;Lo;0;L;3A2E;;;;N;;;;; +2F8C3;CJK COMPATIBILITY IDEOGRAPH-2F8C3;Lo;0;L;6469;;;;N;;;;; +2F8C4;CJK COMPATIBILITY IDEOGRAPH-2F8C4;Lo;0;L;647E;;;;N;;;;; +2F8C5;CJK COMPATIBILITY IDEOGRAPH-2F8C5;Lo;0;L;649D;;;;N;;;;; +2F8C6;CJK COMPATIBILITY IDEOGRAPH-2F8C6;Lo;0;L;6477;;;;N;;;;; +2F8C7;CJK COMPATIBILITY IDEOGRAPH-2F8C7;Lo;0;L;3A6C;;;;N;;;;; +2F8C8;CJK COMPATIBILITY IDEOGRAPH-2F8C8;Lo;0;L;654F;;;;N;;;;; +2F8C9;CJK COMPATIBILITY IDEOGRAPH-2F8C9;Lo;0;L;656C;;;;N;;;;; +2F8CA;CJK COMPATIBILITY IDEOGRAPH-2F8CA;Lo;0;L;2300A;;;;N;;;;; +2F8CB;CJK COMPATIBILITY IDEOGRAPH-2F8CB;Lo;0;L;65E3;;;;N;;;;; +2F8CC;CJK COMPATIBILITY IDEOGRAPH-2F8CC;Lo;0;L;66F8;;;;N;;;;; +2F8CD;CJK COMPATIBILITY IDEOGRAPH-2F8CD;Lo;0;L;6649;;;;N;;;;; +2F8CE;CJK COMPATIBILITY IDEOGRAPH-2F8CE;Lo;0;L;3B19;;;;N;;;;; +2F8CF;CJK COMPATIBILITY IDEOGRAPH-2F8CF;Lo;0;L;6691;;;;N;;;;; +2F8D0;CJK COMPATIBILITY IDEOGRAPH-2F8D0;Lo;0;L;3B08;;;;N;;;;; +2F8D1;CJK COMPATIBILITY IDEOGRAPH-2F8D1;Lo;0;L;3AE4;;;;N;;;;; +2F8D2;CJK COMPATIBILITY IDEOGRAPH-2F8D2;Lo;0;L;5192;;;;N;;;;; +2F8D3;CJK COMPATIBILITY IDEOGRAPH-2F8D3;Lo;0;L;5195;;;;N;;;;; +2F8D4;CJK COMPATIBILITY IDEOGRAPH-2F8D4;Lo;0;L;6700;;;;N;;;;; +2F8D5;CJK COMPATIBILITY IDEOGRAPH-2F8D5;Lo;0;L;669C;;;;N;;;;; +2F8D6;CJK COMPATIBILITY IDEOGRAPH-2F8D6;Lo;0;L;80AD;;;;N;;;;; +2F8D7;CJK COMPATIBILITY IDEOGRAPH-2F8D7;Lo;0;L;43D9;;;;N;;;;; +2F8D8;CJK COMPATIBILITY IDEOGRAPH-2F8D8;Lo;0;L;6717;;;;N;;;;; +2F8D9;CJK COMPATIBILITY IDEOGRAPH-2F8D9;Lo;0;L;671B;;;;N;;;;; +2F8DA;CJK COMPATIBILITY IDEOGRAPH-2F8DA;Lo;0;L;6721;;;;N;;;;; +2F8DB;CJK COMPATIBILITY IDEOGRAPH-2F8DB;Lo;0;L;675E;;;;N;;;;; +2F8DC;CJK COMPATIBILITY IDEOGRAPH-2F8DC;Lo;0;L;6753;;;;N;;;;; +2F8DD;CJK COMPATIBILITY IDEOGRAPH-2F8DD;Lo;0;L;233C3;;;;N;;;;; +2F8DE;CJK COMPATIBILITY IDEOGRAPH-2F8DE;Lo;0;L;3B49;;;;N;;;;; +2F8DF;CJK COMPATIBILITY IDEOGRAPH-2F8DF;Lo;0;L;67FA;;;;N;;;;; +2F8E0;CJK COMPATIBILITY IDEOGRAPH-2F8E0;Lo;0;L;6785;;;;N;;;;; +2F8E1;CJK COMPATIBILITY IDEOGRAPH-2F8E1;Lo;0;L;6852;;;;N;;;;; +2F8E2;CJK COMPATIBILITY IDEOGRAPH-2F8E2;Lo;0;L;6885;;;;N;;;;; +2F8E3;CJK COMPATIBILITY IDEOGRAPH-2F8E3;Lo;0;L;2346D;;;;N;;;;; +2F8E4;CJK COMPATIBILITY IDEOGRAPH-2F8E4;Lo;0;L;688E;;;;N;;;;; +2F8E5;CJK COMPATIBILITY IDEOGRAPH-2F8E5;Lo;0;L;681F;;;;N;;;;; +2F8E6;CJK COMPATIBILITY IDEOGRAPH-2F8E6;Lo;0;L;6914;;;;N;;;;; +2F8E7;CJK COMPATIBILITY IDEOGRAPH-2F8E7;Lo;0;L;3B9D;;;;N;;;;; +2F8E8;CJK COMPATIBILITY IDEOGRAPH-2F8E8;Lo;0;L;6942;;;;N;;;;; +2F8E9;CJK COMPATIBILITY IDEOGRAPH-2F8E9;Lo;0;L;69A3;;;;N;;;;; +2F8EA;CJK COMPATIBILITY IDEOGRAPH-2F8EA;Lo;0;L;69EA;;;;N;;;;; +2F8EB;CJK COMPATIBILITY IDEOGRAPH-2F8EB;Lo;0;L;6AA8;;;;N;;;;; +2F8EC;CJK COMPATIBILITY IDEOGRAPH-2F8EC;Lo;0;L;236A3;;;;N;;;;; +2F8ED;CJK COMPATIBILITY IDEOGRAPH-2F8ED;Lo;0;L;6ADB;;;;N;;;;; +2F8EE;CJK COMPATIBILITY IDEOGRAPH-2F8EE;Lo;0;L;3C18;;;;N;;;;; +2F8EF;CJK COMPATIBILITY IDEOGRAPH-2F8EF;Lo;0;L;6B21;;;;N;;;;; +2F8F0;CJK COMPATIBILITY IDEOGRAPH-2F8F0;Lo;0;L;238A7;;;;N;;;;; +2F8F1;CJK COMPATIBILITY IDEOGRAPH-2F8F1;Lo;0;L;6B54;;;;N;;;;; +2F8F2;CJK COMPATIBILITY IDEOGRAPH-2F8F2;Lo;0;L;3C4E;;;;N;;;;; +2F8F3;CJK COMPATIBILITY IDEOGRAPH-2F8F3;Lo;0;L;6B72;;;;N;;;;; +2F8F4;CJK COMPATIBILITY IDEOGRAPH-2F8F4;Lo;0;L;6B9F;;;;N;;;;; +2F8F5;CJK COMPATIBILITY IDEOGRAPH-2F8F5;Lo;0;L;6BBA;;;;N;;;;; +2F8F6;CJK COMPATIBILITY IDEOGRAPH-2F8F6;Lo;0;L;6BBB;;;;N;;;;; +2F8F7;CJK COMPATIBILITY IDEOGRAPH-2F8F7;Lo;0;L;23A8D;;;;N;;;;; +2F8F8;CJK COMPATIBILITY IDEOGRAPH-2F8F8;Lo;0;L;21D0B;;;;N;;;;; +2F8F9;CJK COMPATIBILITY IDEOGRAPH-2F8F9;Lo;0;L;23AFA;;;;N;;;;; +2F8FA;CJK COMPATIBILITY IDEOGRAPH-2F8FA;Lo;0;L;6C4E;;;;N;;;;; +2F8FB;CJK COMPATIBILITY IDEOGRAPH-2F8FB;Lo;0;L;23CBC;;;;N;;;;; +2F8FC;CJK COMPATIBILITY IDEOGRAPH-2F8FC;Lo;0;L;6CBF;;;;N;;;;; +2F8FD;CJK COMPATIBILITY IDEOGRAPH-2F8FD;Lo;0;L;6CCD;;;;N;;;;; +2F8FE;CJK COMPATIBILITY IDEOGRAPH-2F8FE;Lo;0;L;6C67;;;;N;;;;; +2F8FF;CJK COMPATIBILITY IDEOGRAPH-2F8FF;Lo;0;L;6D16;;;;N;;;;; +2F900;CJK COMPATIBILITY IDEOGRAPH-2F900;Lo;0;L;6D3E;;;;N;;;;; +2F901;CJK COMPATIBILITY IDEOGRAPH-2F901;Lo;0;L;6D77;;;;N;;;;; +2F902;CJK COMPATIBILITY IDEOGRAPH-2F902;Lo;0;L;6D41;;;;N;;;;; +2F903;CJK COMPATIBILITY IDEOGRAPH-2F903;Lo;0;L;6D69;;;;N;;;;; +2F904;CJK COMPATIBILITY IDEOGRAPH-2F904;Lo;0;L;6D78;;;;N;;;;; +2F905;CJK COMPATIBILITY IDEOGRAPH-2F905;Lo;0;L;6D85;;;;N;;;;; +2F906;CJK COMPATIBILITY IDEOGRAPH-2F906;Lo;0;L;23D1E;;;;N;;;;; +2F907;CJK COMPATIBILITY IDEOGRAPH-2F907;Lo;0;L;6D34;;;;N;;;;; +2F908;CJK COMPATIBILITY IDEOGRAPH-2F908;Lo;0;L;6E2F;;;;N;;;;; +2F909;CJK COMPATIBILITY IDEOGRAPH-2F909;Lo;0;L;6E6E;;;;N;;;;; +2F90A;CJK COMPATIBILITY IDEOGRAPH-2F90A;Lo;0;L;3D33;;;;N;;;;; +2F90B;CJK COMPATIBILITY IDEOGRAPH-2F90B;Lo;0;L;6ECB;;;;N;;;;; +2F90C;CJK COMPATIBILITY IDEOGRAPH-2F90C;Lo;0;L;6EC7;;;;N;;;;; +2F90D;CJK COMPATIBILITY IDEOGRAPH-2F90D;Lo;0;L;23ED1;;;;N;;;;; +2F90E;CJK COMPATIBILITY IDEOGRAPH-2F90E;Lo;0;L;6DF9;;;;N;;;;; +2F90F;CJK COMPATIBILITY IDEOGRAPH-2F90F;Lo;0;L;6F6E;;;;N;;;;; +2F910;CJK COMPATIBILITY IDEOGRAPH-2F910;Lo;0;L;23F5E;;;;N;;;;; +2F911;CJK COMPATIBILITY IDEOGRAPH-2F911;Lo;0;L;23F8E;;;;N;;;;; +2F912;CJK COMPATIBILITY IDEOGRAPH-2F912;Lo;0;L;6FC6;;;;N;;;;; +2F913;CJK COMPATIBILITY IDEOGRAPH-2F913;Lo;0;L;7039;;;;N;;;;; +2F914;CJK COMPATIBILITY IDEOGRAPH-2F914;Lo;0;L;701E;;;;N;;;;; +2F915;CJK COMPATIBILITY IDEOGRAPH-2F915;Lo;0;L;701B;;;;N;;;;; +2F916;CJK COMPATIBILITY IDEOGRAPH-2F916;Lo;0;L;3D96;;;;N;;;;; +2F917;CJK COMPATIBILITY IDEOGRAPH-2F917;Lo;0;L;704A;;;;N;;;;; +2F918;CJK COMPATIBILITY IDEOGRAPH-2F918;Lo;0;L;707D;;;;N;;;;; +2F919;CJK COMPATIBILITY IDEOGRAPH-2F919;Lo;0;L;7077;;;;N;;;;; +2F91A;CJK COMPATIBILITY IDEOGRAPH-2F91A;Lo;0;L;70AD;;;;N;;;;; +2F91B;CJK COMPATIBILITY IDEOGRAPH-2F91B;Lo;0;L;20525;;;;N;;;;; +2F91C;CJK COMPATIBILITY IDEOGRAPH-2F91C;Lo;0;L;7145;;;;N;;;;; +2F91D;CJK COMPATIBILITY IDEOGRAPH-2F91D;Lo;0;L;24263;;;;N;;;;; +2F91E;CJK COMPATIBILITY IDEOGRAPH-2F91E;Lo;0;L;719C;;;;N;;;;; +2F91F;CJK COMPATIBILITY IDEOGRAPH-2F91F;Lo;0;L;243AB;;;;N;;;;; +2F920;CJK COMPATIBILITY IDEOGRAPH-2F920;Lo;0;L;7228;;;;N;;;;; +2F921;CJK COMPATIBILITY IDEOGRAPH-2F921;Lo;0;L;7235;;;;N;;;;; +2F922;CJK COMPATIBILITY IDEOGRAPH-2F922;Lo;0;L;7250;;;;N;;;;; +2F923;CJK COMPATIBILITY IDEOGRAPH-2F923;Lo;0;L;24608;;;;N;;;;; +2F924;CJK COMPATIBILITY IDEOGRAPH-2F924;Lo;0;L;7280;;;;N;;;;; +2F925;CJK COMPATIBILITY IDEOGRAPH-2F925;Lo;0;L;7295;;;;N;;;;; +2F926;CJK COMPATIBILITY IDEOGRAPH-2F926;Lo;0;L;24735;;;;N;;;;; +2F927;CJK COMPATIBILITY IDEOGRAPH-2F927;Lo;0;L;24814;;;;N;;;;; +2F928;CJK COMPATIBILITY IDEOGRAPH-2F928;Lo;0;L;737A;;;;N;;;;; +2F929;CJK COMPATIBILITY IDEOGRAPH-2F929;Lo;0;L;738B;;;;N;;;;; +2F92A;CJK COMPATIBILITY IDEOGRAPH-2F92A;Lo;0;L;3EAC;;;;N;;;;; +2F92B;CJK COMPATIBILITY IDEOGRAPH-2F92B;Lo;0;L;73A5;;;;N;;;;; +2F92C;CJK COMPATIBILITY IDEOGRAPH-2F92C;Lo;0;L;3EB8;;;;N;;;;; +2F92D;CJK COMPATIBILITY IDEOGRAPH-2F92D;Lo;0;L;3EB8;;;;N;;;;; +2F92E;CJK COMPATIBILITY IDEOGRAPH-2F92E;Lo;0;L;7447;;;;N;;;;; +2F92F;CJK COMPATIBILITY IDEOGRAPH-2F92F;Lo;0;L;745C;;;;N;;;;; +2F930;CJK COMPATIBILITY IDEOGRAPH-2F930;Lo;0;L;7471;;;;N;;;;; +2F931;CJK COMPATIBILITY IDEOGRAPH-2F931;Lo;0;L;7485;;;;N;;;;; +2F932;CJK COMPATIBILITY IDEOGRAPH-2F932;Lo;0;L;74CA;;;;N;;;;; +2F933;CJK COMPATIBILITY IDEOGRAPH-2F933;Lo;0;L;3F1B;;;;N;;;;; +2F934;CJK COMPATIBILITY IDEOGRAPH-2F934;Lo;0;L;7524;;;;N;;;;; +2F935;CJK COMPATIBILITY IDEOGRAPH-2F935;Lo;0;L;24C36;;;;N;;;;; +2F936;CJK COMPATIBILITY IDEOGRAPH-2F936;Lo;0;L;753E;;;;N;;;;; +2F937;CJK COMPATIBILITY IDEOGRAPH-2F937;Lo;0;L;24C92;;;;N;;;;; +2F938;CJK COMPATIBILITY IDEOGRAPH-2F938;Lo;0;L;7570;;;;N;;;;; +2F939;CJK COMPATIBILITY IDEOGRAPH-2F939;Lo;0;L;2219F;;;;N;;;;; +2F93A;CJK COMPATIBILITY IDEOGRAPH-2F93A;Lo;0;L;7610;;;;N;;;;; +2F93B;CJK COMPATIBILITY IDEOGRAPH-2F93B;Lo;0;L;24FA1;;;;N;;;;; +2F93C;CJK COMPATIBILITY IDEOGRAPH-2F93C;Lo;0;L;24FB8;;;;N;;;;; +2F93D;CJK COMPATIBILITY IDEOGRAPH-2F93D;Lo;0;L;25044;;;;N;;;;; +2F93E;CJK COMPATIBILITY IDEOGRAPH-2F93E;Lo;0;L;3FFC;;;;N;;;;; +2F93F;CJK COMPATIBILITY IDEOGRAPH-2F93F;Lo;0;L;4008;;;;N;;;;; +2F940;CJK COMPATIBILITY IDEOGRAPH-2F940;Lo;0;L;76F4;;;;N;;;;; +2F941;CJK COMPATIBILITY IDEOGRAPH-2F941;Lo;0;L;250F3;;;;N;;;;; +2F942;CJK COMPATIBILITY IDEOGRAPH-2F942;Lo;0;L;250F2;;;;N;;;;; +2F943;CJK COMPATIBILITY IDEOGRAPH-2F943;Lo;0;L;25119;;;;N;;;;; +2F944;CJK COMPATIBILITY IDEOGRAPH-2F944;Lo;0;L;25133;;;;N;;;;; +2F945;CJK COMPATIBILITY IDEOGRAPH-2F945;Lo;0;L;771E;;;;N;;;;; +2F946;CJK COMPATIBILITY IDEOGRAPH-2F946;Lo;0;L;771F;;;;N;;;;; +2F947;CJK COMPATIBILITY IDEOGRAPH-2F947;Lo;0;L;771F;;;;N;;;;; +2F948;CJK COMPATIBILITY IDEOGRAPH-2F948;Lo;0;L;774A;;;;N;;;;; +2F949;CJK COMPATIBILITY IDEOGRAPH-2F949;Lo;0;L;4039;;;;N;;;;; +2F94A;CJK COMPATIBILITY IDEOGRAPH-2F94A;Lo;0;L;778B;;;;N;;;;; +2F94B;CJK COMPATIBILITY IDEOGRAPH-2F94B;Lo;0;L;4046;;;;N;;;;; +2F94C;CJK COMPATIBILITY IDEOGRAPH-2F94C;Lo;0;L;4096;;;;N;;;;; +2F94D;CJK COMPATIBILITY IDEOGRAPH-2F94D;Lo;0;L;2541D;;;;N;;;;; +2F94E;CJK COMPATIBILITY IDEOGRAPH-2F94E;Lo;0;L;784E;;;;N;;;;; +2F94F;CJK COMPATIBILITY IDEOGRAPH-2F94F;Lo;0;L;788C;;;;N;;;;; +2F950;CJK COMPATIBILITY IDEOGRAPH-2F950;Lo;0;L;78CC;;;;N;;;;; +2F951;CJK COMPATIBILITY IDEOGRAPH-2F951;Lo;0;L;40E3;;;;N;;;;; +2F952;CJK COMPATIBILITY IDEOGRAPH-2F952;Lo;0;L;25626;;;;N;;;;; +2F953;CJK COMPATIBILITY IDEOGRAPH-2F953;Lo;0;L;7956;;;;N;;;;; +2F954;CJK COMPATIBILITY IDEOGRAPH-2F954;Lo;0;L;2569A;;;;N;;;;; +2F955;CJK COMPATIBILITY IDEOGRAPH-2F955;Lo;0;L;256C5;;;;N;;;;; +2F956;CJK COMPATIBILITY IDEOGRAPH-2F956;Lo;0;L;798F;;;;N;;;;; +2F957;CJK COMPATIBILITY IDEOGRAPH-2F957;Lo;0;L;79EB;;;;N;;;;; +2F958;CJK COMPATIBILITY IDEOGRAPH-2F958;Lo;0;L;412F;;;;N;;;;; +2F959;CJK COMPATIBILITY IDEOGRAPH-2F959;Lo;0;L;7A40;;;;N;;;;; +2F95A;CJK COMPATIBILITY IDEOGRAPH-2F95A;Lo;0;L;7A4A;;;;N;;;;; +2F95B;CJK COMPATIBILITY IDEOGRAPH-2F95B;Lo;0;L;7A4F;;;;N;;;;; +2F95C;CJK COMPATIBILITY IDEOGRAPH-2F95C;Lo;0;L;2597C;;;;N;;;;; +2F95D;CJK COMPATIBILITY IDEOGRAPH-2F95D;Lo;0;L;25AA7;;;;N;;;;; +2F95E;CJK COMPATIBILITY IDEOGRAPH-2F95E;Lo;0;L;25AA7;;;;N;;;;; +2F95F;CJK COMPATIBILITY IDEOGRAPH-2F95F;Lo;0;L;7AEE;;;;N;;;;; +2F960;CJK COMPATIBILITY IDEOGRAPH-2F960;Lo;0;L;4202;;;;N;;;;; +2F961;CJK COMPATIBILITY IDEOGRAPH-2F961;Lo;0;L;25BAB;;;;N;;;;; +2F962;CJK COMPATIBILITY IDEOGRAPH-2F962;Lo;0;L;7BC6;;;;N;;;;; +2F963;CJK COMPATIBILITY IDEOGRAPH-2F963;Lo;0;L;7BC9;;;;N;;;;; +2F964;CJK COMPATIBILITY IDEOGRAPH-2F964;Lo;0;L;4227;;;;N;;;;; +2F965;CJK COMPATIBILITY IDEOGRAPH-2F965;Lo;0;L;25C80;;;;N;;;;; +2F966;CJK COMPATIBILITY IDEOGRAPH-2F966;Lo;0;L;7CD2;;;;N;;;;; +2F967;CJK COMPATIBILITY IDEOGRAPH-2F967;Lo;0;L;42A0;;;;N;;;;; +2F968;CJK COMPATIBILITY IDEOGRAPH-2F968;Lo;0;L;7CE8;;;;N;;;;; +2F969;CJK COMPATIBILITY IDEOGRAPH-2F969;Lo;0;L;7CE3;;;;N;;;;; +2F96A;CJK COMPATIBILITY IDEOGRAPH-2F96A;Lo;0;L;7D00;;;;N;;;;; +2F96B;CJK COMPATIBILITY IDEOGRAPH-2F96B;Lo;0;L;25F86;;;;N;;;;; +2F96C;CJK COMPATIBILITY IDEOGRAPH-2F96C;Lo;0;L;7D63;;;;N;;;;; +2F96D;CJK COMPATIBILITY IDEOGRAPH-2F96D;Lo;0;L;4301;;;;N;;;;; +2F96E;CJK COMPATIBILITY IDEOGRAPH-2F96E;Lo;0;L;7DC7;;;;N;;;;; +2F96F;CJK COMPATIBILITY IDEOGRAPH-2F96F;Lo;0;L;7E02;;;;N;;;;; +2F970;CJK COMPATIBILITY IDEOGRAPH-2F970;Lo;0;L;7E45;;;;N;;;;; +2F971;CJK COMPATIBILITY IDEOGRAPH-2F971;Lo;0;L;4334;;;;N;;;;; +2F972;CJK COMPATIBILITY IDEOGRAPH-2F972;Lo;0;L;26228;;;;N;;;;; +2F973;CJK COMPATIBILITY IDEOGRAPH-2F973;Lo;0;L;26247;;;;N;;;;; +2F974;CJK COMPATIBILITY IDEOGRAPH-2F974;Lo;0;L;4359;;;;N;;;;; +2F975;CJK COMPATIBILITY IDEOGRAPH-2F975;Lo;0;L;262D9;;;;N;;;;; +2F976;CJK COMPATIBILITY IDEOGRAPH-2F976;Lo;0;L;7F7A;;;;N;;;;; +2F977;CJK COMPATIBILITY IDEOGRAPH-2F977;Lo;0;L;2633E;;;;N;;;;; +2F978;CJK COMPATIBILITY IDEOGRAPH-2F978;Lo;0;L;7F95;;;;N;;;;; +2F979;CJK COMPATIBILITY IDEOGRAPH-2F979;Lo;0;L;7FFA;;;;N;;;;; +2F97A;CJK COMPATIBILITY IDEOGRAPH-2F97A;Lo;0;L;8005;;;;N;;;;; +2F97B;CJK COMPATIBILITY IDEOGRAPH-2F97B;Lo;0;L;264DA;;;;N;;;;; +2F97C;CJK COMPATIBILITY IDEOGRAPH-2F97C;Lo;0;L;26523;;;;N;;;;; +2F97D;CJK COMPATIBILITY IDEOGRAPH-2F97D;Lo;0;L;8060;;;;N;;;;; +2F97E;CJK COMPATIBILITY IDEOGRAPH-2F97E;Lo;0;L;265A8;;;;N;;;;; +2F97F;CJK COMPATIBILITY IDEOGRAPH-2F97F;Lo;0;L;8070;;;;N;;;;; +2F980;CJK COMPATIBILITY IDEOGRAPH-2F980;Lo;0;L;2335F;;;;N;;;;; +2F981;CJK COMPATIBILITY IDEOGRAPH-2F981;Lo;0;L;43D5;;;;N;;;;; +2F982;CJK COMPATIBILITY IDEOGRAPH-2F982;Lo;0;L;80B2;;;;N;;;;; +2F983;CJK COMPATIBILITY IDEOGRAPH-2F983;Lo;0;L;8103;;;;N;;;;; +2F984;CJK COMPATIBILITY IDEOGRAPH-2F984;Lo;0;L;440B;;;;N;;;;; +2F985;CJK COMPATIBILITY IDEOGRAPH-2F985;Lo;0;L;813E;;;;N;;;;; +2F986;CJK COMPATIBILITY IDEOGRAPH-2F986;Lo;0;L;5AB5;;;;N;;;;; +2F987;CJK COMPATIBILITY IDEOGRAPH-2F987;Lo;0;L;267A7;;;;N;;;;; +2F988;CJK COMPATIBILITY IDEOGRAPH-2F988;Lo;0;L;267B5;;;;N;;;;; +2F989;CJK COMPATIBILITY IDEOGRAPH-2F989;Lo;0;L;23393;;;;N;;;;; +2F98A;CJK COMPATIBILITY IDEOGRAPH-2F98A;Lo;0;L;2339C;;;;N;;;;; +2F98B;CJK COMPATIBILITY IDEOGRAPH-2F98B;Lo;0;L;8201;;;;N;;;;; +2F98C;CJK COMPATIBILITY IDEOGRAPH-2F98C;Lo;0;L;8204;;;;N;;;;; +2F98D;CJK COMPATIBILITY IDEOGRAPH-2F98D;Lo;0;L;8F9E;;;;N;;;;; +2F98E;CJK COMPATIBILITY IDEOGRAPH-2F98E;Lo;0;L;446B;;;;N;;;;; +2F98F;CJK COMPATIBILITY IDEOGRAPH-2F98F;Lo;0;L;8291;;;;N;;;;; +2F990;CJK COMPATIBILITY IDEOGRAPH-2F990;Lo;0;L;828B;;;;N;;;;; +2F991;CJK COMPATIBILITY IDEOGRAPH-2F991;Lo;0;L;829D;;;;N;;;;; +2F992;CJK COMPATIBILITY IDEOGRAPH-2F992;Lo;0;L;52B3;;;;N;;;;; +2F993;CJK COMPATIBILITY IDEOGRAPH-2F993;Lo;0;L;82B1;;;;N;;;;; +2F994;CJK COMPATIBILITY IDEOGRAPH-2F994;Lo;0;L;82B3;;;;N;;;;; +2F995;CJK COMPATIBILITY IDEOGRAPH-2F995;Lo;0;L;82BD;;;;N;;;;; +2F996;CJK COMPATIBILITY IDEOGRAPH-2F996;Lo;0;L;82E6;;;;N;;;;; +2F997;CJK COMPATIBILITY IDEOGRAPH-2F997;Lo;0;L;26B3C;;;;N;;;;; +2F998;CJK COMPATIBILITY IDEOGRAPH-2F998;Lo;0;L;82E5;;;;N;;;;; +2F999;CJK COMPATIBILITY IDEOGRAPH-2F999;Lo;0;L;831D;;;;N;;;;; +2F99A;CJK COMPATIBILITY IDEOGRAPH-2F99A;Lo;0;L;8363;;;;N;;;;; +2F99B;CJK COMPATIBILITY IDEOGRAPH-2F99B;Lo;0;L;83AD;;;;N;;;;; +2F99C;CJK COMPATIBILITY IDEOGRAPH-2F99C;Lo;0;L;8323;;;;N;;;;; +2F99D;CJK COMPATIBILITY IDEOGRAPH-2F99D;Lo;0;L;83BD;;;;N;;;;; +2F99E;CJK COMPATIBILITY IDEOGRAPH-2F99E;Lo;0;L;83E7;;;;N;;;;; +2F99F;CJK COMPATIBILITY IDEOGRAPH-2F99F;Lo;0;L;8457;;;;N;;;;; +2F9A0;CJK COMPATIBILITY IDEOGRAPH-2F9A0;Lo;0;L;8353;;;;N;;;;; +2F9A1;CJK COMPATIBILITY IDEOGRAPH-2F9A1;Lo;0;L;83CA;;;;N;;;;; +2F9A2;CJK COMPATIBILITY IDEOGRAPH-2F9A2;Lo;0;L;83CC;;;;N;;;;; +2F9A3;CJK COMPATIBILITY IDEOGRAPH-2F9A3;Lo;0;L;83DC;;;;N;;;;; +2F9A4;CJK COMPATIBILITY IDEOGRAPH-2F9A4;Lo;0;L;26C36;;;;N;;;;; +2F9A5;CJK COMPATIBILITY IDEOGRAPH-2F9A5;Lo;0;L;26D6B;;;;N;;;;; +2F9A6;CJK COMPATIBILITY IDEOGRAPH-2F9A6;Lo;0;L;26CD5;;;;N;;;;; +2F9A7;CJK COMPATIBILITY IDEOGRAPH-2F9A7;Lo;0;L;452B;;;;N;;;;; +2F9A8;CJK COMPATIBILITY IDEOGRAPH-2F9A8;Lo;0;L;84F1;;;;N;;;;; +2F9A9;CJK COMPATIBILITY IDEOGRAPH-2F9A9;Lo;0;L;84F3;;;;N;;;;; +2F9AA;CJK COMPATIBILITY IDEOGRAPH-2F9AA;Lo;0;L;8516;;;;N;;;;; +2F9AB;CJK COMPATIBILITY IDEOGRAPH-2F9AB;Lo;0;L;273CA;;;;N;;;;; +2F9AC;CJK COMPATIBILITY IDEOGRAPH-2F9AC;Lo;0;L;8564;;;;N;;;;; +2F9AD;CJK COMPATIBILITY IDEOGRAPH-2F9AD;Lo;0;L;26F2C;;;;N;;;;; +2F9AE;CJK COMPATIBILITY IDEOGRAPH-2F9AE;Lo;0;L;455D;;;;N;;;;; +2F9AF;CJK COMPATIBILITY IDEOGRAPH-2F9AF;Lo;0;L;4561;;;;N;;;;; +2F9B0;CJK COMPATIBILITY IDEOGRAPH-2F9B0;Lo;0;L;26FB1;;;;N;;;;; +2F9B1;CJK COMPATIBILITY IDEOGRAPH-2F9B1;Lo;0;L;270D2;;;;N;;;;; +2F9B2;CJK COMPATIBILITY IDEOGRAPH-2F9B2;Lo;0;L;456B;;;;N;;;;; +2F9B3;CJK COMPATIBILITY IDEOGRAPH-2F9B3;Lo;0;L;8650;;;;N;;;;; +2F9B4;CJK COMPATIBILITY IDEOGRAPH-2F9B4;Lo;0;L;865C;;;;N;;;;; +2F9B5;CJK COMPATIBILITY IDEOGRAPH-2F9B5;Lo;0;L;8667;;;;N;;;;; +2F9B6;CJK COMPATIBILITY IDEOGRAPH-2F9B6;Lo;0;L;8669;;;;N;;;;; +2F9B7;CJK COMPATIBILITY IDEOGRAPH-2F9B7;Lo;0;L;86A9;;;;N;;;;; +2F9B8;CJK COMPATIBILITY IDEOGRAPH-2F9B8;Lo;0;L;8688;;;;N;;;;; +2F9B9;CJK COMPATIBILITY IDEOGRAPH-2F9B9;Lo;0;L;870E;;;;N;;;;; +2F9BA;CJK COMPATIBILITY IDEOGRAPH-2F9BA;Lo;0;L;86E2;;;;N;;;;; +2F9BB;CJK COMPATIBILITY IDEOGRAPH-2F9BB;Lo;0;L;8779;;;;N;;;;; +2F9BC;CJK COMPATIBILITY IDEOGRAPH-2F9BC;Lo;0;L;8728;;;;N;;;;; +2F9BD;CJK COMPATIBILITY IDEOGRAPH-2F9BD;Lo;0;L;876B;;;;N;;;;; +2F9BE;CJK COMPATIBILITY IDEOGRAPH-2F9BE;Lo;0;L;8786;;;;N;;;;; +2F9BF;CJK COMPATIBILITY IDEOGRAPH-2F9BF;Lo;0;L;45D7;;;;N;;;;; +2F9C0;CJK COMPATIBILITY IDEOGRAPH-2F9C0;Lo;0;L;87E1;;;;N;;;;; +2F9C1;CJK COMPATIBILITY IDEOGRAPH-2F9C1;Lo;0;L;8801;;;;N;;;;; +2F9C2;CJK COMPATIBILITY IDEOGRAPH-2F9C2;Lo;0;L;45F9;;;;N;;;;; +2F9C3;CJK COMPATIBILITY IDEOGRAPH-2F9C3;Lo;0;L;8860;;;;N;;;;; +2F9C4;CJK COMPATIBILITY IDEOGRAPH-2F9C4;Lo;0;L;8863;;;;N;;;;; +2F9C5;CJK COMPATIBILITY IDEOGRAPH-2F9C5;Lo;0;L;27667;;;;N;;;;; +2F9C6;CJK COMPATIBILITY IDEOGRAPH-2F9C6;Lo;0;L;88D7;;;;N;;;;; +2F9C7;CJK COMPATIBILITY IDEOGRAPH-2F9C7;Lo;0;L;88DE;;;;N;;;;; +2F9C8;CJK COMPATIBILITY IDEOGRAPH-2F9C8;Lo;0;L;4635;;;;N;;;;; +2F9C9;CJK COMPATIBILITY IDEOGRAPH-2F9C9;Lo;0;L;88FA;;;;N;;;;; +2F9CA;CJK COMPATIBILITY IDEOGRAPH-2F9CA;Lo;0;L;34BB;;;;N;;;;; +2F9CB;CJK COMPATIBILITY IDEOGRAPH-2F9CB;Lo;0;L;278AE;;;;N;;;;; +2F9CC;CJK COMPATIBILITY IDEOGRAPH-2F9CC;Lo;0;L;27966;;;;N;;;;; +2F9CD;CJK COMPATIBILITY IDEOGRAPH-2F9CD;Lo;0;L;46BE;;;;N;;;;; +2F9CE;CJK COMPATIBILITY IDEOGRAPH-2F9CE;Lo;0;L;46C7;;;;N;;;;; +2F9CF;CJK COMPATIBILITY IDEOGRAPH-2F9CF;Lo;0;L;8AA0;;;;N;;;;; +2F9D0;CJK COMPATIBILITY IDEOGRAPH-2F9D0;Lo;0;L;8AED;;;;N;;;;; +2F9D1;CJK COMPATIBILITY IDEOGRAPH-2F9D1;Lo;0;L;8B8A;;;;N;;;;; +2F9D2;CJK COMPATIBILITY IDEOGRAPH-2F9D2;Lo;0;L;8C55;;;;N;;;;; +2F9D3;CJK COMPATIBILITY IDEOGRAPH-2F9D3;Lo;0;L;27CA8;;;;N;;;;; +2F9D4;CJK COMPATIBILITY IDEOGRAPH-2F9D4;Lo;0;L;8CAB;;;;N;;;;; +2F9D5;CJK COMPATIBILITY IDEOGRAPH-2F9D5;Lo;0;L;8CC1;;;;N;;;;; +2F9D6;CJK COMPATIBILITY IDEOGRAPH-2F9D6;Lo;0;L;8D1B;;;;N;;;;; +2F9D7;CJK COMPATIBILITY IDEOGRAPH-2F9D7;Lo;0;L;8D77;;;;N;;;;; +2F9D8;CJK COMPATIBILITY IDEOGRAPH-2F9D8;Lo;0;L;27F2F;;;;N;;;;; +2F9D9;CJK COMPATIBILITY IDEOGRAPH-2F9D9;Lo;0;L;20804;;;;N;;;;; +2F9DA;CJK COMPATIBILITY IDEOGRAPH-2F9DA;Lo;0;L;8DCB;;;;N;;;;; +2F9DB;CJK COMPATIBILITY IDEOGRAPH-2F9DB;Lo;0;L;8DBC;;;;N;;;;; +2F9DC;CJK COMPATIBILITY IDEOGRAPH-2F9DC;Lo;0;L;8DF0;;;;N;;;;; +2F9DD;CJK COMPATIBILITY IDEOGRAPH-2F9DD;Lo;0;L;208DE;;;;N;;;;; +2F9DE;CJK COMPATIBILITY IDEOGRAPH-2F9DE;Lo;0;L;8ED4;;;;N;;;;; +2F9DF;CJK COMPATIBILITY IDEOGRAPH-2F9DF;Lo;0;L;8F38;;;;N;;;;; +2F9E0;CJK COMPATIBILITY IDEOGRAPH-2F9E0;Lo;0;L;285D2;;;;N;;;;; +2F9E1;CJK COMPATIBILITY IDEOGRAPH-2F9E1;Lo;0;L;285ED;;;;N;;;;; +2F9E2;CJK COMPATIBILITY IDEOGRAPH-2F9E2;Lo;0;L;9094;;;;N;;;;; +2F9E3;CJK COMPATIBILITY IDEOGRAPH-2F9E3;Lo;0;L;90F1;;;;N;;;;; +2F9E4;CJK COMPATIBILITY IDEOGRAPH-2F9E4;Lo;0;L;9111;;;;N;;;;; +2F9E5;CJK COMPATIBILITY IDEOGRAPH-2F9E5;Lo;0;L;2872E;;;;N;;;;; +2F9E6;CJK COMPATIBILITY IDEOGRAPH-2F9E6;Lo;0;L;911B;;;;N;;;;; +2F9E7;CJK COMPATIBILITY IDEOGRAPH-2F9E7;Lo;0;L;9238;;;;N;;;;; +2F9E8;CJK COMPATIBILITY IDEOGRAPH-2F9E8;Lo;0;L;92D7;;;;N;;;;; +2F9E9;CJK COMPATIBILITY IDEOGRAPH-2F9E9;Lo;0;L;92D8;;;;N;;;;; +2F9EA;CJK COMPATIBILITY IDEOGRAPH-2F9EA;Lo;0;L;927C;;;;N;;;;; +2F9EB;CJK COMPATIBILITY IDEOGRAPH-2F9EB;Lo;0;L;93F9;;;;N;;;;; +2F9EC;CJK COMPATIBILITY IDEOGRAPH-2F9EC;Lo;0;L;9415;;;;N;;;;; +2F9ED;CJK COMPATIBILITY IDEOGRAPH-2F9ED;Lo;0;L;28BFA;;;;N;;;;; +2F9EE;CJK COMPATIBILITY IDEOGRAPH-2F9EE;Lo;0;L;958B;;;;N;;;;; +2F9EF;CJK COMPATIBILITY IDEOGRAPH-2F9EF;Lo;0;L;4995;;;;N;;;;; +2F9F0;CJK COMPATIBILITY IDEOGRAPH-2F9F0;Lo;0;L;95B7;;;;N;;;;; +2F9F1;CJK COMPATIBILITY IDEOGRAPH-2F9F1;Lo;0;L;28D77;;;;N;;;;; +2F9F2;CJK COMPATIBILITY IDEOGRAPH-2F9F2;Lo;0;L;49E6;;;;N;;;;; +2F9F3;CJK COMPATIBILITY IDEOGRAPH-2F9F3;Lo;0;L;96C3;;;;N;;;;; +2F9F4;CJK COMPATIBILITY IDEOGRAPH-2F9F4;Lo;0;L;5DB2;;;;N;;;;; +2F9F5;CJK COMPATIBILITY IDEOGRAPH-2F9F5;Lo;0;L;9723;;;;N;;;;; +2F9F6;CJK COMPATIBILITY IDEOGRAPH-2F9F6;Lo;0;L;29145;;;;N;;;;; +2F9F7;CJK COMPATIBILITY IDEOGRAPH-2F9F7;Lo;0;L;2921A;;;;N;;;;; +2F9F8;CJK COMPATIBILITY IDEOGRAPH-2F9F8;Lo;0;L;4A6E;;;;N;;;;; +2F9F9;CJK COMPATIBILITY IDEOGRAPH-2F9F9;Lo;0;L;4A76;;;;N;;;;; +2F9FA;CJK COMPATIBILITY IDEOGRAPH-2F9FA;Lo;0;L;97E0;;;;N;;;;; +2F9FB;CJK COMPATIBILITY IDEOGRAPH-2F9FB;Lo;0;L;2940A;;;;N;;;;; +2F9FC;CJK COMPATIBILITY IDEOGRAPH-2F9FC;Lo;0;L;4AB2;;;;N;;;;; +2F9FD;CJK COMPATIBILITY IDEOGRAPH-2F9FD;Lo;0;L;29496;;;;N;;;;; +2F9FE;CJK COMPATIBILITY IDEOGRAPH-2F9FE;Lo;0;L;980B;;;;N;;;;; +2F9FF;CJK COMPATIBILITY IDEOGRAPH-2F9FF;Lo;0;L;980B;;;;N;;;;; +2FA00;CJK COMPATIBILITY IDEOGRAPH-2FA00;Lo;0;L;9829;;;;N;;;;; +2FA01;CJK COMPATIBILITY IDEOGRAPH-2FA01;Lo;0;L;295B6;;;;N;;;;; +2FA02;CJK COMPATIBILITY IDEOGRAPH-2FA02;Lo;0;L;98E2;;;;N;;;;; +2FA03;CJK COMPATIBILITY IDEOGRAPH-2FA03;Lo;0;L;4B33;;;;N;;;;; +2FA04;CJK COMPATIBILITY IDEOGRAPH-2FA04;Lo;0;L;9929;;;;N;;;;; +2FA05;CJK COMPATIBILITY IDEOGRAPH-2FA05;Lo;0;L;99A7;;;;N;;;;; +2FA06;CJK COMPATIBILITY IDEOGRAPH-2FA06;Lo;0;L;99C2;;;;N;;;;; +2FA07;CJK COMPATIBILITY IDEOGRAPH-2FA07;Lo;0;L;99FE;;;;N;;;;; +2FA08;CJK COMPATIBILITY IDEOGRAPH-2FA08;Lo;0;L;4BCE;;;;N;;;;; +2FA09;CJK COMPATIBILITY IDEOGRAPH-2FA09;Lo;0;L;29B30;;;;N;;;;; +2FA0A;CJK COMPATIBILITY IDEOGRAPH-2FA0A;Lo;0;L;9B12;;;;N;;;;; +2FA0B;CJK COMPATIBILITY IDEOGRAPH-2FA0B;Lo;0;L;9C40;;;;N;;;;; +2FA0C;CJK COMPATIBILITY IDEOGRAPH-2FA0C;Lo;0;L;9CFD;;;;N;;;;; +2FA0D;CJK COMPATIBILITY IDEOGRAPH-2FA0D;Lo;0;L;4CCE;;;;N;;;;; +2FA0E;CJK COMPATIBILITY IDEOGRAPH-2FA0E;Lo;0;L;4CED;;;;N;;;;; +2FA0F;CJK COMPATIBILITY IDEOGRAPH-2FA0F;Lo;0;L;9D67;;;;N;;;;; +2FA10;CJK COMPATIBILITY IDEOGRAPH-2FA10;Lo;0;L;2A0CE;;;;N;;;;; +2FA11;CJK COMPATIBILITY IDEOGRAPH-2FA11;Lo;0;L;4CF8;;;;N;;;;; +2FA12;CJK COMPATIBILITY IDEOGRAPH-2FA12;Lo;0;L;2A105;;;;N;;;;; +2FA13;CJK COMPATIBILITY IDEOGRAPH-2FA13;Lo;0;L;2A20E;;;;N;;;;; +2FA14;CJK COMPATIBILITY IDEOGRAPH-2FA14;Lo;0;L;2A291;;;;N;;;;; +2FA15;CJK COMPATIBILITY IDEOGRAPH-2FA15;Lo;0;L;9EBB;;;;N;;;;; +2FA16;CJK COMPATIBILITY IDEOGRAPH-2FA16;Lo;0;L;4D56;;;;N;;;;; +2FA17;CJK COMPATIBILITY IDEOGRAPH-2FA17;Lo;0;L;9EF9;;;;N;;;;; +2FA18;CJK COMPATIBILITY IDEOGRAPH-2FA18;Lo;0;L;9EFE;;;;N;;;;; +2FA19;CJK COMPATIBILITY IDEOGRAPH-2FA19;Lo;0;L;9F05;;;;N;;;;; +2FA1A;CJK COMPATIBILITY IDEOGRAPH-2FA1A;Lo;0;L;9F0F;;;;N;;;;; +2FA1B;CJK COMPATIBILITY IDEOGRAPH-2FA1B;Lo;0;L;9F16;;;;N;;;;; +2FA1C;CJK COMPATIBILITY IDEOGRAPH-2FA1C;Lo;0;L;9F3B;;;;N;;;;; +2FA1D;CJK COMPATIBILITY IDEOGRAPH-2FA1D;Lo;0;L;2A600;;;;N;;;;; +E0001;LANGUAGE TAG;Cf;0;BN;;;;;N;;;;; +E0020;TAG SPACE;Cf;0;BN;;;;;N;;;;; +E0021;TAG EXCLAMATION MARK;Cf;0;BN;;;;;N;;;;; +E0022;TAG QUOTATION MARK;Cf;0;BN;;;;;N;;;;; +E0023;TAG NUMBER SIGN;Cf;0;BN;;;;;N;;;;; +E0024;TAG DOLLAR SIGN;Cf;0;BN;;;;;N;;;;; +E0025;TAG PERCENT SIGN;Cf;0;BN;;;;;N;;;;; +E0026;TAG AMPERSAND;Cf;0;BN;;;;;N;;;;; +E0027;TAG APOSTROPHE;Cf;0;BN;;;;;N;;;;; +E0028;TAG LEFT PARENTHESIS;Cf;0;BN;;;;;N;;;;; +E0029;TAG RIGHT PARENTHESIS;Cf;0;BN;;;;;N;;;;; +E002A;TAG ASTERISK;Cf;0;BN;;;;;N;;;;; +E002B;TAG PLUS SIGN;Cf;0;BN;;;;;N;;;;; +E002C;TAG COMMA;Cf;0;BN;;;;;N;;;;; +E002D;TAG HYPHEN-MINUS;Cf;0;BN;;;;;N;;;;; +E002E;TAG FULL STOP;Cf;0;BN;;;;;N;;;;; +E002F;TAG SOLIDUS;Cf;0;BN;;;;;N;;;;; +E0030;TAG DIGIT ZERO;Cf;0;BN;;;;;N;;;;; +E0031;TAG DIGIT ONE;Cf;0;BN;;;;;N;;;;; +E0032;TAG DIGIT TWO;Cf;0;BN;;;;;N;;;;; +E0033;TAG DIGIT THREE;Cf;0;BN;;;;;N;;;;; +E0034;TAG DIGIT FOUR;Cf;0;BN;;;;;N;;;;; +E0035;TAG DIGIT FIVE;Cf;0;BN;;;;;N;;;;; +E0036;TAG DIGIT SIX;Cf;0;BN;;;;;N;;;;; +E0037;TAG DIGIT SEVEN;Cf;0;BN;;;;;N;;;;; +E0038;TAG DIGIT EIGHT;Cf;0;BN;;;;;N;;;;; +E0039;TAG DIGIT NINE;Cf;0;BN;;;;;N;;;;; +E003A;TAG COLON;Cf;0;BN;;;;;N;;;;; +E003B;TAG SEMICOLON;Cf;0;BN;;;;;N;;;;; +E003C;TAG LESS-THAN SIGN;Cf;0;BN;;;;;N;;;;; +E003D;TAG EQUALS SIGN;Cf;0;BN;;;;;N;;;;; +E003E;TAG GREATER-THAN SIGN;Cf;0;BN;;;;;N;;;;; +E003F;TAG QUESTION MARK;Cf;0;BN;;;;;N;;;;; +E0040;TAG COMMERCIAL AT;Cf;0;BN;;;;;N;;;;; +E0041;TAG LATIN CAPITAL LETTER A;Cf;0;BN;;;;;N;;;;; +E0042;TAG LATIN CAPITAL LETTER B;Cf;0;BN;;;;;N;;;;; +E0043;TAG LATIN CAPITAL LETTER C;Cf;0;BN;;;;;N;;;;; +E0044;TAG LATIN CAPITAL LETTER D;Cf;0;BN;;;;;N;;;;; +E0045;TAG LATIN CAPITAL LETTER E;Cf;0;BN;;;;;N;;;;; +E0046;TAG LATIN CAPITAL LETTER F;Cf;0;BN;;;;;N;;;;; +E0047;TAG LATIN CAPITAL LETTER G;Cf;0;BN;;;;;N;;;;; +E0048;TAG LATIN CAPITAL LETTER H;Cf;0;BN;;;;;N;;;;; +E0049;TAG LATIN CAPITAL LETTER I;Cf;0;BN;;;;;N;;;;; +E004A;TAG LATIN CAPITAL LETTER J;Cf;0;BN;;;;;N;;;;; +E004B;TAG LATIN CAPITAL LETTER K;Cf;0;BN;;;;;N;;;;; +E004C;TAG LATIN CAPITAL LETTER L;Cf;0;BN;;;;;N;;;;; +E004D;TAG LATIN CAPITAL LETTER M;Cf;0;BN;;;;;N;;;;; +E004E;TAG LATIN CAPITAL LETTER N;Cf;0;BN;;;;;N;;;;; +E004F;TAG LATIN CAPITAL LETTER O;Cf;0;BN;;;;;N;;;;; +E0050;TAG LATIN CAPITAL LETTER P;Cf;0;BN;;;;;N;;;;; +E0051;TAG LATIN CAPITAL LETTER Q;Cf;0;BN;;;;;N;;;;; +E0052;TAG LATIN CAPITAL LETTER R;Cf;0;BN;;;;;N;;;;; +E0053;TAG LATIN CAPITAL LETTER S;Cf;0;BN;;;;;N;;;;; +E0054;TAG LATIN CAPITAL LETTER T;Cf;0;BN;;;;;N;;;;; +E0055;TAG LATIN CAPITAL LETTER U;Cf;0;BN;;;;;N;;;;; +E0056;TAG LATIN CAPITAL LETTER V;Cf;0;BN;;;;;N;;;;; +E0057;TAG LATIN CAPITAL LETTER W;Cf;0;BN;;;;;N;;;;; +E0058;TAG LATIN CAPITAL LETTER X;Cf;0;BN;;;;;N;;;;; +E0059;TAG LATIN CAPITAL LETTER Y;Cf;0;BN;;;;;N;;;;; +E005A;TAG LATIN CAPITAL LETTER Z;Cf;0;BN;;;;;N;;;;; +E005B;TAG LEFT SQUARE BRACKET;Cf;0;BN;;;;;N;;;;; +E005C;TAG REVERSE SOLIDUS;Cf;0;BN;;;;;N;;;;; +E005D;TAG RIGHT SQUARE BRACKET;Cf;0;BN;;;;;N;;;;; +E005E;TAG CIRCUMFLEX ACCENT;Cf;0;BN;;;;;N;;;;; +E005F;TAG LOW LINE;Cf;0;BN;;;;;N;;;;; +E0060;TAG GRAVE ACCENT;Cf;0;BN;;;;;N;;;;; +E0061;TAG LATIN SMALL LETTER A;Cf;0;BN;;;;;N;;;;; +E0062;TAG LATIN SMALL LETTER B;Cf;0;BN;;;;;N;;;;; +E0063;TAG LATIN SMALL LETTER C;Cf;0;BN;;;;;N;;;;; +E0064;TAG LATIN SMALL LETTER D;Cf;0;BN;;;;;N;;;;; +E0065;TAG LATIN SMALL LETTER E;Cf;0;BN;;;;;N;;;;; +E0066;TAG LATIN SMALL LETTER F;Cf;0;BN;;;;;N;;;;; +E0067;TAG LATIN SMALL LETTER G;Cf;0;BN;;;;;N;;;;; +E0068;TAG LATIN SMALL LETTER H;Cf;0;BN;;;;;N;;;;; +E0069;TAG LATIN SMALL LETTER I;Cf;0;BN;;;;;N;;;;; +E006A;TAG LATIN SMALL LETTER J;Cf;0;BN;;;;;N;;;;; +E006B;TAG LATIN SMALL LETTER K;Cf;0;BN;;;;;N;;;;; +E006C;TAG LATIN SMALL LETTER L;Cf;0;BN;;;;;N;;;;; +E006D;TAG LATIN SMALL LETTER M;Cf;0;BN;;;;;N;;;;; +E006E;TAG LATIN SMALL LETTER N;Cf;0;BN;;;;;N;;;;; +E006F;TAG LATIN SMALL LETTER O;Cf;0;BN;;;;;N;;;;; +E0070;TAG LATIN SMALL LETTER P;Cf;0;BN;;;;;N;;;;; +E0071;TAG LATIN SMALL LETTER Q;Cf;0;BN;;;;;N;;;;; +E0072;TAG LATIN SMALL LETTER R;Cf;0;BN;;;;;N;;;;; +E0073;TAG LATIN SMALL LETTER S;Cf;0;BN;;;;;N;;;;; +E0074;TAG LATIN SMALL LETTER T;Cf;0;BN;;;;;N;;;;; +E0075;TAG LATIN SMALL LETTER U;Cf;0;BN;;;;;N;;;;; +E0076;TAG LATIN SMALL LETTER V;Cf;0;BN;;;;;N;;;;; +E0077;TAG LATIN SMALL LETTER W;Cf;0;BN;;;;;N;;;;; +E0078;TAG LATIN SMALL LETTER X;Cf;0;BN;;;;;N;;;;; +E0079;TAG LATIN SMALL LETTER Y;Cf;0;BN;;;;;N;;;;; +E007A;TAG LATIN SMALL LETTER Z;Cf;0;BN;;;;;N;;;;; +E007B;TAG LEFT CURLY BRACKET;Cf;0;BN;;;;;N;;;;; +E007C;TAG VERTICAL LINE;Cf;0;BN;;;;;N;;;;; +E007D;TAG RIGHT CURLY BRACKET;Cf;0;BN;;;;;N;;;;; +E007E;TAG TILDE;Cf;0;BN;;;;;N;;;;; +E007F;CANCEL TAG;Cf;0;BN;;;;;N;;;;; +E0100;VARIATION SELECTOR-17;Mn;0;NSM;;;;;N;;;;; +E0101;VARIATION SELECTOR-18;Mn;0;NSM;;;;;N;;;;; +E0102;VARIATION SELECTOR-19;Mn;0;NSM;;;;;N;;;;; +E0103;VARIATION SELECTOR-20;Mn;0;NSM;;;;;N;;;;; +E0104;VARIATION SELECTOR-21;Mn;0;NSM;;;;;N;;;;; +E0105;VARIATION SELECTOR-22;Mn;0;NSM;;;;;N;;;;; +E0106;VARIATION SELECTOR-23;Mn;0;NSM;;;;;N;;;;; +E0107;VARIATION SELECTOR-24;Mn;0;NSM;;;;;N;;;;; +E0108;VARIATION SELECTOR-25;Mn;0;NSM;;;;;N;;;;; +E0109;VARIATION SELECTOR-26;Mn;0;NSM;;;;;N;;;;; +E010A;VARIATION SELECTOR-27;Mn;0;NSM;;;;;N;;;;; +E010B;VARIATION SELECTOR-28;Mn;0;NSM;;;;;N;;;;; +E010C;VARIATION SELECTOR-29;Mn;0;NSM;;;;;N;;;;; +E010D;VARIATION SELECTOR-30;Mn;0;NSM;;;;;N;;;;; +E010E;VARIATION SELECTOR-31;Mn;0;NSM;;;;;N;;;;; +E010F;VARIATION SELECTOR-32;Mn;0;NSM;;;;;N;;;;; +E0110;VARIATION SELECTOR-33;Mn;0;NSM;;;;;N;;;;; +E0111;VARIATION SELECTOR-34;Mn;0;NSM;;;;;N;;;;; +E0112;VARIATION SELECTOR-35;Mn;0;NSM;;;;;N;;;;; +E0113;VARIATION SELECTOR-36;Mn;0;NSM;;;;;N;;;;; +E0114;VARIATION SELECTOR-37;Mn;0;NSM;;;;;N;;;;; +E0115;VARIATION SELECTOR-38;Mn;0;NSM;;;;;N;;;;; +E0116;VARIATION SELECTOR-39;Mn;0;NSM;;;;;N;;;;; +E0117;VARIATION SELECTOR-40;Mn;0;NSM;;;;;N;;;;; +E0118;VARIATION SELECTOR-41;Mn;0;NSM;;;;;N;;;;; +E0119;VARIATION SELECTOR-42;Mn;0;NSM;;;;;N;;;;; +E011A;VARIATION SELECTOR-43;Mn;0;NSM;;;;;N;;;;; +E011B;VARIATION SELECTOR-44;Mn;0;NSM;;;;;N;;;;; +E011C;VARIATION SELECTOR-45;Mn;0;NSM;;;;;N;;;;; +E011D;VARIATION SELECTOR-46;Mn;0;NSM;;;;;N;;;;; +E011E;VARIATION SELECTOR-47;Mn;0;NSM;;;;;N;;;;; +E011F;VARIATION SELECTOR-48;Mn;0;NSM;;;;;N;;;;; +E0120;VARIATION SELECTOR-49;Mn;0;NSM;;;;;N;;;;; +E0121;VARIATION SELECTOR-50;Mn;0;NSM;;;;;N;;;;; +E0122;VARIATION SELECTOR-51;Mn;0;NSM;;;;;N;;;;; +E0123;VARIATION SELECTOR-52;Mn;0;NSM;;;;;N;;;;; +E0124;VARIATION SELECTOR-53;Mn;0;NSM;;;;;N;;;;; +E0125;VARIATION SELECTOR-54;Mn;0;NSM;;;;;N;;;;; +E0126;VARIATION SELECTOR-55;Mn;0;NSM;;;;;N;;;;; +E0127;VARIATION SELECTOR-56;Mn;0;NSM;;;;;N;;;;; +E0128;VARIATION SELECTOR-57;Mn;0;NSM;;;;;N;;;;; +E0129;VARIATION SELECTOR-58;Mn;0;NSM;;;;;N;;;;; +E012A;VARIATION SELECTOR-59;Mn;0;NSM;;;;;N;;;;; +E012B;VARIATION SELECTOR-60;Mn;0;NSM;;;;;N;;;;; +E012C;VARIATION SELECTOR-61;Mn;0;NSM;;;;;N;;;;; +E012D;VARIATION SELECTOR-62;Mn;0;NSM;;;;;N;;;;; +E012E;VARIATION SELECTOR-63;Mn;0;NSM;;;;;N;;;;; +E012F;VARIATION SELECTOR-64;Mn;0;NSM;;;;;N;;;;; +E0130;VARIATION SELECTOR-65;Mn;0;NSM;;;;;N;;;;; +E0131;VARIATION SELECTOR-66;Mn;0;NSM;;;;;N;;;;; +E0132;VARIATION SELECTOR-67;Mn;0;NSM;;;;;N;;;;; +E0133;VARIATION SELECTOR-68;Mn;0;NSM;;;;;N;;;;; +E0134;VARIATION SELECTOR-69;Mn;0;NSM;;;;;N;;;;; +E0135;VARIATION SELECTOR-70;Mn;0;NSM;;;;;N;;;;; +E0136;VARIATION SELECTOR-71;Mn;0;NSM;;;;;N;;;;; +E0137;VARIATION SELECTOR-72;Mn;0;NSM;;;;;N;;;;; +E0138;VARIATION SELECTOR-73;Mn;0;NSM;;;;;N;;;;; +E0139;VARIATION SELECTOR-74;Mn;0;NSM;;;;;N;;;;; +E013A;VARIATION SELECTOR-75;Mn;0;NSM;;;;;N;;;;; +E013B;VARIATION SELECTOR-76;Mn;0;NSM;;;;;N;;;;; +E013C;VARIATION SELECTOR-77;Mn;0;NSM;;;;;N;;;;; +E013D;VARIATION SELECTOR-78;Mn;0;NSM;;;;;N;;;;; +E013E;VARIATION SELECTOR-79;Mn;0;NSM;;;;;N;;;;; +E013F;VARIATION SELECTOR-80;Mn;0;NSM;;;;;N;;;;; +E0140;VARIATION SELECTOR-81;Mn;0;NSM;;;;;N;;;;; +E0141;VARIATION SELECTOR-82;Mn;0;NSM;;;;;N;;;;; +E0142;VARIATION SELECTOR-83;Mn;0;NSM;;;;;N;;;;; +E0143;VARIATION SELECTOR-84;Mn;0;NSM;;;;;N;;;;; +E0144;VARIATION SELECTOR-85;Mn;0;NSM;;;;;N;;;;; +E0145;VARIATION SELECTOR-86;Mn;0;NSM;;;;;N;;;;; +E0146;VARIATION SELECTOR-87;Mn;0;NSM;;;;;N;;;;; +E0147;VARIATION SELECTOR-88;Mn;0;NSM;;;;;N;;;;; +E0148;VARIATION SELECTOR-89;Mn;0;NSM;;;;;N;;;;; +E0149;VARIATION SELECTOR-90;Mn;0;NSM;;;;;N;;;;; +E014A;VARIATION SELECTOR-91;Mn;0;NSM;;;;;N;;;;; +E014B;VARIATION SELECTOR-92;Mn;0;NSM;;;;;N;;;;; +E014C;VARIATION SELECTOR-93;Mn;0;NSM;;;;;N;;;;; +E014D;VARIATION SELECTOR-94;Mn;0;NSM;;;;;N;;;;; +E014E;VARIATION SELECTOR-95;Mn;0;NSM;;;;;N;;;;; +E014F;VARIATION SELECTOR-96;Mn;0;NSM;;;;;N;;;;; +E0150;VARIATION SELECTOR-97;Mn;0;NSM;;;;;N;;;;; +E0151;VARIATION SELECTOR-98;Mn;0;NSM;;;;;N;;;;; +E0152;VARIATION SELECTOR-99;Mn;0;NSM;;;;;N;;;;; +E0153;VARIATION SELECTOR-100;Mn;0;NSM;;;;;N;;;;; +E0154;VARIATION SELECTOR-101;Mn;0;NSM;;;;;N;;;;; +E0155;VARIATION SELECTOR-102;Mn;0;NSM;;;;;N;;;;; +E0156;VARIATION SELECTOR-103;Mn;0;NSM;;;;;N;;;;; +E0157;VARIATION SELECTOR-104;Mn;0;NSM;;;;;N;;;;; +E0158;VARIATION SELECTOR-105;Mn;0;NSM;;;;;N;;;;; +E0159;VARIATION SELECTOR-106;Mn;0;NSM;;;;;N;;;;; +E015A;VARIATION SELECTOR-107;Mn;0;NSM;;;;;N;;;;; +E015B;VARIATION SELECTOR-108;Mn;0;NSM;;;;;N;;;;; +E015C;VARIATION SELECTOR-109;Mn;0;NSM;;;;;N;;;;; +E015D;VARIATION SELECTOR-110;Mn;0;NSM;;;;;N;;;;; +E015E;VARIATION SELECTOR-111;Mn;0;NSM;;;;;N;;;;; +E015F;VARIATION SELECTOR-112;Mn;0;NSM;;;;;N;;;;; +E0160;VARIATION SELECTOR-113;Mn;0;NSM;;;;;N;;;;; +E0161;VARIATION SELECTOR-114;Mn;0;NSM;;;;;N;;;;; +E0162;VARIATION SELECTOR-115;Mn;0;NSM;;;;;N;;;;; +E0163;VARIATION SELECTOR-116;Mn;0;NSM;;;;;N;;;;; +E0164;VARIATION SELECTOR-117;Mn;0;NSM;;;;;N;;;;; +E0165;VARIATION SELECTOR-118;Mn;0;NSM;;;;;N;;;;; +E0166;VARIATION SELECTOR-119;Mn;0;NSM;;;;;N;;;;; +E0167;VARIATION SELECTOR-120;Mn;0;NSM;;;;;N;;;;; +E0168;VARIATION SELECTOR-121;Mn;0;NSM;;;;;N;;;;; +E0169;VARIATION SELECTOR-122;Mn;0;NSM;;;;;N;;;;; +E016A;VARIATION SELECTOR-123;Mn;0;NSM;;;;;N;;;;; +E016B;VARIATION SELECTOR-124;Mn;0;NSM;;;;;N;;;;; +E016C;VARIATION SELECTOR-125;Mn;0;NSM;;;;;N;;;;; +E016D;VARIATION SELECTOR-126;Mn;0;NSM;;;;;N;;;;; +E016E;VARIATION SELECTOR-127;Mn;0;NSM;;;;;N;;;;; +E016F;VARIATION SELECTOR-128;Mn;0;NSM;;;;;N;;;;; +E0170;VARIATION SELECTOR-129;Mn;0;NSM;;;;;N;;;;; +E0171;VARIATION SELECTOR-130;Mn;0;NSM;;;;;N;;;;; +E0172;VARIATION SELECTOR-131;Mn;0;NSM;;;;;N;;;;; +E0173;VARIATION SELECTOR-132;Mn;0;NSM;;;;;N;;;;; +E0174;VARIATION SELECTOR-133;Mn;0;NSM;;;;;N;;;;; +E0175;VARIATION SELECTOR-134;Mn;0;NSM;;;;;N;;;;; +E0176;VARIATION SELECTOR-135;Mn;0;NSM;;;;;N;;;;; +E0177;VARIATION SELECTOR-136;Mn;0;NSM;;;;;N;;;;; +E0178;VARIATION SELECTOR-137;Mn;0;NSM;;;;;N;;;;; +E0179;VARIATION SELECTOR-138;Mn;0;NSM;;;;;N;;;;; +E017A;VARIATION SELECTOR-139;Mn;0;NSM;;;;;N;;;;; +E017B;VARIATION SELECTOR-140;Mn;0;NSM;;;;;N;;;;; +E017C;VARIATION SELECTOR-141;Mn;0;NSM;;;;;N;;;;; +E017D;VARIATION SELECTOR-142;Mn;0;NSM;;;;;N;;;;; +E017E;VARIATION SELECTOR-143;Mn;0;NSM;;;;;N;;;;; +E017F;VARIATION SELECTOR-144;Mn;0;NSM;;;;;N;;;;; +E0180;VARIATION SELECTOR-145;Mn;0;NSM;;;;;N;;;;; +E0181;VARIATION SELECTOR-146;Mn;0;NSM;;;;;N;;;;; +E0182;VARIATION SELECTOR-147;Mn;0;NSM;;;;;N;;;;; +E0183;VARIATION SELECTOR-148;Mn;0;NSM;;;;;N;;;;; +E0184;VARIATION SELECTOR-149;Mn;0;NSM;;;;;N;;;;; +E0185;VARIATION SELECTOR-150;Mn;0;NSM;;;;;N;;;;; +E0186;VARIATION SELECTOR-151;Mn;0;NSM;;;;;N;;;;; +E0187;VARIATION SELECTOR-152;Mn;0;NSM;;;;;N;;;;; +E0188;VARIATION SELECTOR-153;Mn;0;NSM;;;;;N;;;;; +E0189;VARIATION SELECTOR-154;Mn;0;NSM;;;;;N;;;;; +E018A;VARIATION SELECTOR-155;Mn;0;NSM;;;;;N;;;;; +E018B;VARIATION SELECTOR-156;Mn;0;NSM;;;;;N;;;;; +E018C;VARIATION SELECTOR-157;Mn;0;NSM;;;;;N;;;;; +E018D;VARIATION SELECTOR-158;Mn;0;NSM;;;;;N;;;;; +E018E;VARIATION SELECTOR-159;Mn;0;NSM;;;;;N;;;;; +E018F;VARIATION SELECTOR-160;Mn;0;NSM;;;;;N;;;;; +E0190;VARIATION SELECTOR-161;Mn;0;NSM;;;;;N;;;;; +E0191;VARIATION SELECTOR-162;Mn;0;NSM;;;;;N;;;;; +E0192;VARIATION SELECTOR-163;Mn;0;NSM;;;;;N;;;;; +E0193;VARIATION SELECTOR-164;Mn;0;NSM;;;;;N;;;;; +E0194;VARIATION SELECTOR-165;Mn;0;NSM;;;;;N;;;;; +E0195;VARIATION SELECTOR-166;Mn;0;NSM;;;;;N;;;;; +E0196;VARIATION SELECTOR-167;Mn;0;NSM;;;;;N;;;;; +E0197;VARIATION SELECTOR-168;Mn;0;NSM;;;;;N;;;;; +E0198;VARIATION SELECTOR-169;Mn;0;NSM;;;;;N;;;;; +E0199;VARIATION SELECTOR-170;Mn;0;NSM;;;;;N;;;;; +E019A;VARIATION SELECTOR-171;Mn;0;NSM;;;;;N;;;;; +E019B;VARIATION SELECTOR-172;Mn;0;NSM;;;;;N;;;;; +E019C;VARIATION SELECTOR-173;Mn;0;NSM;;;;;N;;;;; +E019D;VARIATION SELECTOR-174;Mn;0;NSM;;;;;N;;;;; +E019E;VARIATION SELECTOR-175;Mn;0;NSM;;;;;N;;;;; +E019F;VARIATION SELECTOR-176;Mn;0;NSM;;;;;N;;;;; +E01A0;VARIATION SELECTOR-177;Mn;0;NSM;;;;;N;;;;; +E01A1;VARIATION SELECTOR-178;Mn;0;NSM;;;;;N;;;;; +E01A2;VARIATION SELECTOR-179;Mn;0;NSM;;;;;N;;;;; +E01A3;VARIATION SELECTOR-180;Mn;0;NSM;;;;;N;;;;; +E01A4;VARIATION SELECTOR-181;Mn;0;NSM;;;;;N;;;;; +E01A5;VARIATION SELECTOR-182;Mn;0;NSM;;;;;N;;;;; +E01A6;VARIATION SELECTOR-183;Mn;0;NSM;;;;;N;;;;; +E01A7;VARIATION SELECTOR-184;Mn;0;NSM;;;;;N;;;;; +E01A8;VARIATION SELECTOR-185;Mn;0;NSM;;;;;N;;;;; +E01A9;VARIATION SELECTOR-186;Mn;0;NSM;;;;;N;;;;; +E01AA;VARIATION SELECTOR-187;Mn;0;NSM;;;;;N;;;;; +E01AB;VARIATION SELECTOR-188;Mn;0;NSM;;;;;N;;;;; +E01AC;VARIATION SELECTOR-189;Mn;0;NSM;;;;;N;;;;; +E01AD;VARIATION SELECTOR-190;Mn;0;NSM;;;;;N;;;;; +E01AE;VARIATION SELECTOR-191;Mn;0;NSM;;;;;N;;;;; +E01AF;VARIATION SELECTOR-192;Mn;0;NSM;;;;;N;;;;; +E01B0;VARIATION SELECTOR-193;Mn;0;NSM;;;;;N;;;;; +E01B1;VARIATION SELECTOR-194;Mn;0;NSM;;;;;N;;;;; +E01B2;VARIATION SELECTOR-195;Mn;0;NSM;;;;;N;;;;; +E01B3;VARIATION SELECTOR-196;Mn;0;NSM;;;;;N;;;;; +E01B4;VARIATION SELECTOR-197;Mn;0;NSM;;;;;N;;;;; +E01B5;VARIATION SELECTOR-198;Mn;0;NSM;;;;;N;;;;; +E01B6;VARIATION SELECTOR-199;Mn;0;NSM;;;;;N;;;;; +E01B7;VARIATION SELECTOR-200;Mn;0;NSM;;;;;N;;;;; +E01B8;VARIATION SELECTOR-201;Mn;0;NSM;;;;;N;;;;; +E01B9;VARIATION SELECTOR-202;Mn;0;NSM;;;;;N;;;;; +E01BA;VARIATION SELECTOR-203;Mn;0;NSM;;;;;N;;;;; +E01BB;VARIATION SELECTOR-204;Mn;0;NSM;;;;;N;;;;; +E01BC;VARIATION SELECTOR-205;Mn;0;NSM;;;;;N;;;;; +E01BD;VARIATION SELECTOR-206;Mn;0;NSM;;;;;N;;;;; +E01BE;VARIATION SELECTOR-207;Mn;0;NSM;;;;;N;;;;; +E01BF;VARIATION SELECTOR-208;Mn;0;NSM;;;;;N;;;;; +E01C0;VARIATION SELECTOR-209;Mn;0;NSM;;;;;N;;;;; +E01C1;VARIATION SELECTOR-210;Mn;0;NSM;;;;;N;;;;; +E01C2;VARIATION SELECTOR-211;Mn;0;NSM;;;;;N;;;;; +E01C3;VARIATION SELECTOR-212;Mn;0;NSM;;;;;N;;;;; +E01C4;VARIATION SELECTOR-213;Mn;0;NSM;;;;;N;;;;; +E01C5;VARIATION SELECTOR-214;Mn;0;NSM;;;;;N;;;;; +E01C6;VARIATION SELECTOR-215;Mn;0;NSM;;;;;N;;;;; +E01C7;VARIATION SELECTOR-216;Mn;0;NSM;;;;;N;;;;; +E01C8;VARIATION SELECTOR-217;Mn;0;NSM;;;;;N;;;;; +E01C9;VARIATION SELECTOR-218;Mn;0;NSM;;;;;N;;;;; +E01CA;VARIATION SELECTOR-219;Mn;0;NSM;;;;;N;;;;; +E01CB;VARIATION SELECTOR-220;Mn;0;NSM;;;;;N;;;;; +E01CC;VARIATION SELECTOR-221;Mn;0;NSM;;;;;N;;;;; +E01CD;VARIATION SELECTOR-222;Mn;0;NSM;;;;;N;;;;; +E01CE;VARIATION SELECTOR-223;Mn;0;NSM;;;;;N;;;;; +E01CF;VARIATION SELECTOR-224;Mn;0;NSM;;;;;N;;;;; +E01D0;VARIATION SELECTOR-225;Mn;0;NSM;;;;;N;;;;; +E01D1;VARIATION SELECTOR-226;Mn;0;NSM;;;;;N;;;;; +E01D2;VARIATION SELECTOR-227;Mn;0;NSM;;;;;N;;;;; +E01D3;VARIATION SELECTOR-228;Mn;0;NSM;;;;;N;;;;; +E01D4;VARIATION SELECTOR-229;Mn;0;NSM;;;;;N;;;;; +E01D5;VARIATION SELECTOR-230;Mn;0;NSM;;;;;N;;;;; +E01D6;VARIATION SELECTOR-231;Mn;0;NSM;;;;;N;;;;; +E01D7;VARIATION SELECTOR-232;Mn;0;NSM;;;;;N;;;;; +E01D8;VARIATION SELECTOR-233;Mn;0;NSM;;;;;N;;;;; +E01D9;VARIATION SELECTOR-234;Mn;0;NSM;;;;;N;;;;; +E01DA;VARIATION SELECTOR-235;Mn;0;NSM;;;;;N;;;;; +E01DB;VARIATION SELECTOR-236;Mn;0;NSM;;;;;N;;;;; +E01DC;VARIATION SELECTOR-237;Mn;0;NSM;;;;;N;;;;; +E01DD;VARIATION SELECTOR-238;Mn;0;NSM;;;;;N;;;;; +E01DE;VARIATION SELECTOR-239;Mn;0;NSM;;;;;N;;;;; +E01DF;VARIATION SELECTOR-240;Mn;0;NSM;;;;;N;;;;; +E01E0;VARIATION SELECTOR-241;Mn;0;NSM;;;;;N;;;;; +E01E1;VARIATION SELECTOR-242;Mn;0;NSM;;;;;N;;;;; +E01E2;VARIATION SELECTOR-243;Mn;0;NSM;;;;;N;;;;; +E01E3;VARIATION SELECTOR-244;Mn;0;NSM;;;;;N;;;;; +E01E4;VARIATION SELECTOR-245;Mn;0;NSM;;;;;N;;;;; +E01E5;VARIATION SELECTOR-246;Mn;0;NSM;;;;;N;;;;; +E01E6;VARIATION SELECTOR-247;Mn;0;NSM;;;;;N;;;;; +E01E7;VARIATION SELECTOR-248;Mn;0;NSM;;;;;N;;;;; +E01E8;VARIATION SELECTOR-249;Mn;0;NSM;;;;;N;;;;; +E01E9;VARIATION SELECTOR-250;Mn;0;NSM;;;;;N;;;;; +E01EA;VARIATION SELECTOR-251;Mn;0;NSM;;;;;N;;;;; +E01EB;VARIATION SELECTOR-252;Mn;0;NSM;;;;;N;;;;; +E01EC;VARIATION SELECTOR-253;Mn;0;NSM;;;;;N;;;;; +E01ED;VARIATION SELECTOR-254;Mn;0;NSM;;;;;N;;;;; +E01EE;VARIATION SELECTOR-255;Mn;0;NSM;;;;;N;;;;; +E01EF;VARIATION SELECTOR-256;Mn;0;NSM;;;;;N;;;;; +F0000;;Co;0;L;;;;;N;;;;; +FFFFD;;Co;0;L;;;;;N;;;;; +100000;;Co;0;L;;;;;N;;;;; +10FFFD;;Co;0;L;;;;;N;;;;; diff --git a/components/external/SQLite-3.8.1/ext/fts3/unicode/mkunicode.tcl b/components/external/SQLite-3.8.1/ext/fts3/unicode/mkunicode.tcl new file mode 100644 index 0000000000000000000000000000000000000000..2da17c51a53ba79b923650d44b02a4a6c4f4cbeb --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/fts3/unicode/mkunicode.tcl @@ -0,0 +1,811 @@ + +# +# Parameter $zName must be a path to the file UnicodeData.txt. This command +# reads the file and returns a list of mappings required to remove all +# diacritical marks from a unicode string. Each mapping is itself a list +# consisting of two elements - the unicode codepoint and the single ASCII +# character that it should be replaced with, or an empty string if the +# codepoint should simply be removed from the input. Examples: +# +# { 224 a } (replace codepoint 224 to "a") +# { 769 "" } (remove codepoint 769 from input) +# +# Mappings are only returned for non-upper case codepoints. It is assumed +# that the input has already been folded to lower case. +# +proc rd_load_unicodedata_text {zName} { + global tl_lookup_table + + set fd [open $zName] + set lField { + code + character_name + general_category + canonical_combining_classes + bidirectional_category + character_decomposition_mapping + decimal_digit_value + digit_value + numeric_value + mirrored + unicode_1_name + iso10646_comment_field + uppercase_mapping + lowercase_mapping + titlecase_mapping + } + set lRet [list] + + while { ![eof $fd] } { + set line [gets $fd] + if {$line == ""} continue + + set fields [split $line ";"] + if {[llength $fields] != [llength $lField]} { error "parse error: $line" } + foreach $lField $fields {} + if { [llength $character_decomposition_mapping]!=2 + || [string is xdigit [lindex $character_decomposition_mapping 0]]==0 + } { + continue + } + + set iCode [expr "0x$code"] + set iAscii [expr "0x[lindex $character_decomposition_mapping 0]"] + set iDia [expr "0x[lindex $character_decomposition_mapping 1]"] + + if {[info exists tl_lookup_table($iCode)]} continue + + if { ($iAscii >= 97 && $iAscii <= 122) + || ($iAscii >= 65 && $iAscii <= 90) + } { + lappend lRet [list $iCode [string tolower [format %c $iAscii]]] + set dia($iDia) 1 + } + } + + foreach d [array names dia] { + lappend lRet [list $d ""] + } + set lRet [lsort -integer -index 0 $lRet] + + close $fd + set lRet +} + + +proc print_rd {map} { + global tl_lookup_table + set aChar [list] + set lRange [list] + + set nRange 1 + set iFirst [lindex $map 0 0] + set cPrev [lindex $map 0 1] + + foreach m [lrange $map 1 end] { + foreach {i c} $m {} + + if {$cPrev == $c} { + for {set j [expr $iFirst+$nRange]} {$j<$i} {incr j} { + if {[info exists tl_lookup_table($j)]==0} break + } + + if {$j==$i} { + set nNew [expr {(1 + $i - $iFirst)}] + if {$nNew<=8} { + set nRange $nNew + continue + } + } + } + + lappend lRange [list $iFirst $nRange] + lappend aChar $cPrev + + set iFirst $i + set cPrev $c + set nRange 1 + } + lappend lRange [list $iFirst $nRange] + lappend aChar $cPrev + + puts "/*" + puts "** If the argument is a codepoint corresponding to a lowercase letter" + puts "** in the ASCII range with a diacritic added, return the codepoint" + puts "** of the ASCII letter only. For example, if passed 235 - \"LATIN" + puts "** SMALL LETTER E WITH DIAERESIS\" - return 65 (\"LATIN SMALL LETTER" + puts "** E\"). The resuls of passing a codepoint that corresponds to an" + puts "** uppercase letter are undefined." + puts "*/" + puts "static int remove_diacritic(int c)\{" + puts " unsigned short aDia\[\] = \{" + puts -nonewline " 0, " + set i 1 + foreach r $lRange { + foreach {iCode nRange} $r {} + if {($i % 8)==0} {puts "" ; puts -nonewline " " } + incr i + + puts -nonewline [format "%5d" [expr ($iCode<<3) + $nRange-1]] + puts -nonewline ", " + } + puts "" + puts " \};" + puts " char aChar\[\] = \{" + puts -nonewline " '\\0', " + set i 1 + foreach c $aChar { + set str "'$c', " + if {$c == ""} { set str "'\\0', " } + + if {($i % 12)==0} {puts "" ; puts -nonewline " " } + incr i + puts -nonewline "$str" + } + puts "" + puts " \};" + puts { + unsigned int key = (((unsigned int)c)<<3) | 0x00000007; + int iRes = 0; + int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1; + int iLo = 0; + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + if( key >= aDia[iTest] ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + assert( key>=aDia[iRes] ); + return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);} + puts "\};" +} + +proc print_isdiacritic {zFunc map} { + + set lCode [list] + foreach m $map { + foreach {code char} $m {} + if {$code && $char == ""} { lappend lCode $code } + } + set lCode [lsort -integer $lCode] + set iFirst [lindex $lCode 0] + set iLast [lindex $lCode end] + + set i1 0 + set i2 0 + + foreach c $lCode { + set i [expr $c - $iFirst] + if {$i < 32} { + set i1 [expr {$i1 | (1<<$i)}] + } else { + set i2 [expr {$i2 | (1<<($i-32))}] + } + } + + puts "/*" + puts "** Return true if the argument interpreted as a unicode codepoint" + puts "** is a diacritical modifier character." + puts "*/" + puts "int ${zFunc}\(int c)\{" + puts " unsigned int mask0 = [format "0x%08X" $i1];" + puts " unsigned int mask1 = [format "0x%08X" $i2];" + + puts " if( c<$iFirst || c>$iLast ) return 0;" + puts " return (c < $iFirst+32) ?" + puts " (mask0 & (1 << (c-$iFirst))) :" + puts " (mask1 & (1 << (c-$iFirst-32)));" + puts "\}" +} + + +#------------------------------------------------------------------------- + +# Parameter $zName must be a path to the file UnicodeData.txt. This command +# reads the file and returns a list of codepoints (integers). The list +# contains all codepoints in the UnicodeData.txt assigned to any "General +# Category" that is not a "Letter" or "Number". +# +proc an_load_unicodedata_text {zName} { + set fd [open $zName] + set lField { + code + character_name + general_category + canonical_combining_classes + bidirectional_category + character_decomposition_mapping + decimal_digit_value + digit_value + numeric_value + mirrored + unicode_1_name + iso10646_comment_field + uppercase_mapping + lowercase_mapping + titlecase_mapping + } + set lRet [list] + + while { ![eof $fd] } { + set line [gets $fd] + if {$line == ""} continue + + set fields [split $line ";"] + if {[llength $fields] != [llength $lField]} { error "parse error: $line" } + foreach $lField $fields {} + + set iCode [expr "0x$code"] + set bAlnum [expr { + [lsearch {L N} [string range $general_category 0 0]] >= 0 + || $general_category=="Co" + }] + + if { !$bAlnum } { lappend lRet $iCode } + } + + close $fd + set lRet +} + +proc an_load_separator_ranges {} { + global unicodedata.txt + set lSep [an_load_unicodedata_text ${unicodedata.txt}] + unset -nocomplain iFirst + unset -nocomplain nRange + set lRange [list] + foreach sep $lSep { + if {0==[info exists iFirst]} { + set iFirst $sep + set nRange 1 + } elseif { $sep == ($iFirst+$nRange) } { + incr nRange + } else { + lappend lRange [list $iFirst $nRange] + set iFirst $sep + set nRange 1 + } + } + lappend lRange [list $iFirst $nRange] + set lRange +} + +proc an_print_range_array {lRange} { + set iFirstMax 0 + set nRangeMax 0 + foreach range $lRange { + foreach {iFirst nRange} $range {} + if {$iFirst > $iFirstMax} {set iFirstMax $iFirst} + if {$nRange > $nRangeMax} {set nRangeMax $nRange} + } + if {$iFirstMax >= (1<<22)} {error "first-max is too large for format"} + if {$nRangeMax >= (1<<10)} {error "range-max is too large for format"} + + puts -nonewline " " + puts [string trim { + /* Each unsigned integer in the following array corresponds to a contiguous + ** range of unicode codepoints that are not either letters or numbers (i.e. + ** codepoints for which this function should return 0). + ** + ** The most significant 22 bits in each 32-bit value contain the first + ** codepoint in the range. The least significant 10 bits are used to store + ** the size of the range (always at least 1). In other words, the value + ** ((C<<22) + N) represents a range of N codepoints starting with codepoint + ** C. It is not possible to represent a range larger than 1023 codepoints + ** using this format. + */ + }] + puts -nonewline " const static unsigned int aEntry\[\] = \{" + set i 0 + foreach range $lRange { + foreach {iFirst nRange} $range {} + set u32 [format "0x%08X" [expr ($iFirst<<10) + $nRange]] + + if {($i % 5)==0} {puts "" ; puts -nonewline " "} + puts -nonewline " $u32," + incr i + } + puts "" + puts " \};" +} + +proc an_print_ascii_bitmap {lRange} { + foreach range $lRange { + foreach {iFirst nRange} $range {} + for {set i $iFirst} {$i < ($iFirst+$nRange)} {incr i} { + if {$i<=127} { set a($i) 1 } + } + } + + set aAscii [list 0 0 0 0] + foreach key [array names a] { + set idx [expr $key >> 5] + lset aAscii $idx [expr [lindex $aAscii $idx] | (1 << ($key&0x001F))] + } + + puts " static const unsigned int aAscii\[4\] = \{" + puts -nonewline " " + foreach v $aAscii { puts -nonewline [format " 0x%08X," $v] } + puts "" + puts " \};" +} + +proc print_isalnum {zFunc lRange} { + puts "/*" + puts "** Return true if the argument corresponds to a unicode codepoint" + puts "** classified as either a letter or a number. Otherwise false." + puts "**" + puts "** The results are undefined if the value passed to this function" + puts "** is less than zero." + puts "*/" + puts "int ${zFunc}\(int c)\{" + an_print_range_array $lRange + an_print_ascii_bitmap $lRange + puts { + if( c<128 ){ + return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 ); + }else if( c<(1<<22) ){ + unsigned int key = (((unsigned int)c)<<10) | 0x000003FF; + int iRes; + int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; + int iLo = 0; + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + if( key >= aEntry[iTest] ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + assert( aEntry[0]=aEntry[iRes] ); + return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF))); + } + return 1;} + puts "\}" +} + +proc print_test_isalnum {zFunc lRange} { + foreach range $lRange { + foreach {iFirst nRange} $range {} + for {set i $iFirst} {$i < ($iFirst+$nRange)} {incr i} { set a($i) 1 } + } + + puts "static int isalnum_test(int *piCode)\{" + puts -nonewline " unsigned char aAlnum\[\] = \{" + for {set i 0} {$i < 70000} {incr i} { + if {($i % 32)==0} { puts "" ; puts -nonewline " " } + set bFlag [expr ![info exists a($i)]] + puts -nonewline "${bFlag}," + } + puts "" + puts " \};" + + puts -nonewline " int aLargeSep\[\] = \{" + set i 0 + foreach iSep [lsort -integer [array names a]] { + if {$iSep<70000} continue + if {($i % 8)==0} { puts "" ; puts -nonewline " " } + puts -nonewline " $iSep," + incr i + } + puts "" + puts " \};" + puts -nonewline " int aLargeOther\[\] = \{" + set i 0 + foreach iSep [lsort -integer [array names a]] { + if {$iSep<70000} continue + if {[info exists a([expr $iSep-1])]==0} { + if {($i % 8)==0} { puts "" ; puts -nonewline " " } + puts -nonewline " [expr $iSep-1]," + incr i + } + if {[info exists a([expr $iSep+1])]==0} { + if {($i % 8)==0} { puts "" ; puts -nonewline " " } + puts -nonewline " [expr $iSep+1]," + incr i + } + } + puts "" + puts " \};" + + puts [subst -nocommands { + int i; + for(i=0; i>1]) & 0xFFFF). + ** + ** The contents of this array are generated by parsing the CaseFolding.txt + ** file distributed as part of the "Unicode Character Database". See + ** http://www.unicode.org for details. + */ + }] + puts " static const struct TableEntry \{" + puts " unsigned short iCode;" + puts " unsigned char flags;" + puts " unsigned char nRange;" + puts " \} aEntry\[\] = \{" +} + +proc tl_print_table_entry {togglevar entry liOff} { + upvar $togglevar t + foreach {iFirst nIncr nRange nOff} $entry {} + + if {$iFirst > (1<<16)} { return 1 } + + if {[info exists t]==0} {set t 0} + if {$t==0} { puts -nonewline " " } + + set flags 0 + if {$nIncr==2} { set flags 1 ; set nRange [expr $nRange * 2]} + if {$nOff<0} { incr nOff [expr (1<<16)] } + + set idx [lsearch $liOff $nOff] + if {$idx<0} {error "malfunction generating aiOff"} + set flags [expr $flags + $idx*2] + + set txt "{$iFirst, $flags, $nRange}," + if {$t==2} { + puts $txt + } else { + puts -nonewline [format "% -23s" $txt] + } + set t [expr ($t+1)%3] + + return 0 +} + +proc tl_print_table_footer {togglevar} { + upvar $togglevar t + if {$t!=0} {puts ""} + puts " \};" +} + +proc tl_print_if_entry {entry} { + foreach {iFirst nIncr nRange nOff} $entry {} + if {$nIncr==2} {error "tl_print_if_entry needs improvement!"} + + puts " else if( c>=$iFirst && c<[expr $iFirst+$nRange] )\{" + puts " ret = c + $nOff;" + puts " \}" +} + +proc tl_generate_ioff_table {lRecord} { + foreach entry $lRecord { + foreach {iFirst nIncr nRange iOff} $entry {} + if {$iOff<0} { incr iOff [expr (1<<16)] } + if {[info exists a($iOff)]} continue + set a($iOff) 1 + } + + set liOff [lsort -integer [array names a]] + if {[llength $liOff]>128} { error "Too many distinct ioffs" } + return $liOff +} + +proc tl_print_ioff_table {liOff} { + puts -nonewline " static const unsigned short aiOff\[\] = \{" + set i 0 + foreach off $liOff { + if {($i % 8)==0} {puts "" ; puts -nonewline " "} + puts -nonewline [format "% -7s" "$off,"] + incr i + } + puts "" + puts " \};" + +} + +proc print_fold {zFunc} { + + set lRecord [tl_create_records] + + set lHigh [list] + puts "/*" + puts "** Interpret the argument as a unicode codepoint. If the codepoint" + puts "** is an upper case character that has a lower case equivalent," + puts "** return the codepoint corresponding to the lower case version." + puts "** Otherwise, return a copy of the argument." + puts "**" + puts "** The results are undefined if the value passed to this function" + puts "** is less than zero." + puts "*/" + puts "int ${zFunc}\(int c, int bRemoveDiacritic)\{" + + set liOff [tl_generate_ioff_table $lRecord] + tl_print_table_header + foreach entry $lRecord { + if {[tl_print_table_entry toggle $entry $liOff]} { + lappend lHigh $entry + } + } + tl_print_table_footer toggle + tl_print_ioff_table $liOff + + puts { + int ret = c; + + assert( c>=0 ); + assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 ); + + if( c<128 ){ + if( c>='A' && c<='Z' ) ret = c + ('a' - 'A'); + }else if( c<65536 ){ + int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; + int iLo = 0; + int iRes = -1; + + while( iHi>=iLo ){ + int iTest = (iHi + iLo) / 2; + int cmp = (c - aEntry[iTest].iCode); + if( cmp>=0 ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest-1; + } + } + assert( iRes<0 || c>=aEntry[iRes].iCode ); + + if( iRes>=0 ){ + const struct TableEntry *p = &aEntry[iRes]; + if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){ + ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF; + assert( ret>0 ); + } + } + + if( bRemoveDiacritic ) ret = remove_diacritic(ret); + } + } + + foreach entry $lHigh { + tl_print_if_entry $entry + } + + puts "" + puts " return ret;" + puts "\}" +} + +proc print_fold_test {zFunc mappings} { + global tl_lookup_table + + foreach m $mappings { + set c [lindex $m 1] + if {$c == ""} { + set extra([lindex $m 0]) 0 + } else { + scan $c %c i + set extra([lindex $m 0]) $i + } + } + + puts "static int fold_test(int *piCode)\{" + puts -nonewline " static int aLookup\[\] = \{" + for {set i 0} {$i < 70000} {incr i} { + + set expected $i + catch { set expected $tl_lookup_table($i) } + set expected2 $expected + catch { set expected2 $extra($expected2) } + + if {($i % 4)==0} { puts "" ; puts -nonewline " " } + puts -nonewline "$expected, $expected2, " + } + puts " \};" + puts " int i;" + puts " for(i=0; i" + puts "" +} + +proc print_test_main {} { + puts "" + puts "#include " + puts "" + puts "int main(int argc, char **argv)\{" + puts " int r1, r2;" + puts " int code;" + puts " r1 = isalnum_test(&code);" + puts " if( r1 ) printf(\"isalnum(): Problem with code %d\\n\",code);" + puts " else printf(\"isalnum(): test passed\\n\");" + puts " r2 = fold_test(&code);" + puts " if( r2 ) printf(\"fold(): Problem with code %d\\n\",code);" + puts " else printf(\"fold(): test passed\\n\");" + puts " return (r1 || r2);" + puts "\}" +} + +# Proces the command line arguments. Exit early if they are not to +# our liking. +# +proc usage {} { + puts -nonewline stderr "Usage: $::argv0 ?-test? " + puts stderr " " + exit 1 +} +if {[llength $argv]!=2 && [llength $argv]!=3} usage +if {[llength $argv]==3 && [lindex $argv 0]!="-test"} usage +set unicodedata.txt [lindex $argv end] +set casefolding.txt [lindex $argv end-1] +set generate_test_code [expr {[llength $argv]==3}] + +print_fileheader + +# Print the isalnum() function to stdout. +# +set lRange [an_load_separator_ranges] +print_isalnum sqlite3FtsUnicodeIsalnum $lRange + +# Leave a gap between the two generated C functions. +# +puts "" +puts "" + +# Load the fold data. This is used by the [rd_XXX] commands +# as well as [print_fold]. +tl_load_casefolding_txt ${casefolding.txt} + +set mappings [rd_load_unicodedata_text ${unicodedata.txt}] +print_rd $mappings +puts "" +puts "" +print_isdiacritic sqlite3FtsUnicodeIsdiacritic $mappings +puts "" +puts "" + +# Print the fold() function to stdout. +# +print_fold sqlite3FtsUnicodeFold + +# Print the test routines and main() function to stdout, if -test +# was specified. +# +if {$::generate_test_code} { + print_test_isalnum sqlite3FtsUnicodeIsalnum $lRange + print_fold_test sqlite3FtsUnicodeFold $mappings + print_test_main +} + +puts "#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */" +puts "#endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */" diff --git a/components/external/SQLite-3.8.1/ext/icu/README.txt b/components/external/SQLite-3.8.1/ext/icu/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..d744f74981d7f75d65beb15d876fdd66bd9bbdd8 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/icu/README.txt @@ -0,0 +1,169 @@ + +This directory contains source code for the SQLite "ICU" extension, an +integration of the "International Components for Unicode" library with +SQLite. Documentation follows. + + 1. Features + + 1.1 SQL Scalars upper() and lower() + 1.2 Unicode Aware LIKE Operator + 1.3 ICU Collation Sequences + 1.4 SQL REGEXP Operator + + 2. Compilation and Usage + + 3. Bugs, Problems and Security Issues + + 3.1 The "case_sensitive_like" Pragma + 3.2 The SQLITE_MAX_LIKE_PATTERN_LENGTH Macro + 3.3 Collation Sequence Security Issue + + +1. FEATURES + + 1.1 SQL Scalars upper() and lower() + + SQLite's built-in implementations of these two functions only + provide case mapping for the 26 letters used in the English + language. The ICU based functions provided by this extension + provide case mapping, where defined, for the full range of + unicode characters. + + ICU provides two types of case mapping, "general" case mapping and + "language specific". Refer to ICU documentation for the differences + between the two. Specifically: + + http://www.icu-project.org/userguide/caseMappings.html + http://www.icu-project.org/userguide/posix.html#case_mappings + + To utilise "general" case mapping, the upper() or lower() scalar + functions are invoked with one argument: + + upper('ABC') -> 'abc' + lower('abc') -> 'ABC' + + To access ICU "language specific" case mapping, upper() or lower() + should be invoked with two arguments. The second argument is the name + of the locale to use. Passing an empty string ("") or SQL NULL value + as the second argument is the same as invoking the 1 argument version + of upper() or lower(): + + lower('I', 'en_us') -> 'i' + lower('I', 'tr_tr') -> 'ı' (small dotless i) + + 1.2 Unicode Aware LIKE Operator + + Similarly to the upper() and lower() functions, the built-in SQLite LIKE + operator understands case equivalence for the 26 letters of the English + language alphabet. The implementation of LIKE included in this + extension uses the ICU function u_foldCase() to provide case + independent comparisons for the full range of unicode characters. + + The U_FOLD_CASE_DEFAULT flag is passed to u_foldCase(), meaning the + dotless 'I' character used in the Turkish language is considered + to be in the same equivalence class as the dotted 'I' character + used by many languages (including English). + + 1.3 ICU Collation Sequences + + A special SQL scalar function, icu_load_collation() is provided that + may be used to register ICU collation sequences with SQLite. It + is always called with exactly two arguments, the ICU locale + identifying the collation sequence to ICU, and the name of the + SQLite collation sequence to create. For example, to create an + SQLite collation sequence named "turkish" using Turkish language + sorting rules, the SQL statement: + + SELECT icu_load_collation('tr_TR', 'turkish'); + + Or, for Australian English: + + SELECT icu_load_collation('en_AU', 'australian'); + + The identifiers "turkish" and "australian" may then be used + as collation sequence identifiers in SQL statements: + + CREATE TABLE aust_turkish_penpals( + australian_penpal_name TEXT COLLATE australian, + turkish_penpal_name TEXT COLLATE turkish + ); + + 1.4 SQL REGEXP Operator + + This extension provides an implementation of the SQL binary + comparision operator "REGEXP", based on the regular expression functions + provided by the ICU library. The syntax of the operator is as described + in SQLite documentation: + + REGEXP + + This extension uses the ICU defaults for regular expression matching + behavior. Specifically, this means that: + + * Matching is case-sensitive, + * Regular expression comments are not allowed within patterns, and + * The '^' and '$' characters match the beginning and end of the + argument, not the beginning and end of lines within + the argument. + + Even more specifically, the value passed to the "flags" parameter + of ICU C function uregex_open() is 0. + + +2 COMPILATION AND USAGE + + The easiest way to compile and use the ICU extension is to build + and use it as a dynamically loadable SQLite extension. To do this + using gcc on *nix: + + gcc -shared icu.c `icu-config --ldflags` -o libSqliteIcu.so + + You may need to add "-I" flags so that gcc can find sqlite3ext.h + and sqlite3.h. The resulting shared lib, libSqliteIcu.so, may be + loaded into sqlite in the same way as any other dynamically loadable + extension. + + +3 BUGS, PROBLEMS AND SECURITY ISSUES + + 3.1 The "case_sensitive_like" Pragma + + This extension does not work well with the "case_sensitive_like" + pragma. If this pragma is used before the ICU extension is loaded, + then the pragma has no effect. If the pragma is used after the ICU + extension is loaded, then SQLite ignores the ICU implementation and + always uses the built-in LIKE operator. + + The ICU extension LIKE operator is always case insensitive. + + 3.2 The SQLITE_MAX_LIKE_PATTERN_LENGTH Macro + + Passing very long patterns to the built-in SQLite LIKE operator can + cause excessive CPU usage. To curb this problem, SQLite defines the + SQLITE_MAX_LIKE_PATTERN_LENGTH macro as the maximum length of a + pattern in bytes (irrespective of encoding). The default value is + defined in internal header file "limits.h". + + The ICU extension LIKE implementation suffers from the same + problem and uses the same solution. However, since the ICU extension + code does not include the SQLite file "limits.h", modifying + the default value therein does not affect the ICU extension. + The default value of SQLITE_MAX_LIKE_PATTERN_LENGTH used by + the ICU extension LIKE operator is 50000, defined in source + file "icu.c". + + 3.3 Collation Sequence Security Issue + + Internally, SQLite assumes that indices stored in database files + are sorted according to the collation sequence indicated by the + SQL schema. Changing the definition of a collation sequence after + an index has been built is therefore equivalent to database + corruption. The SQLite library is not very well tested under + these conditions, and may contain potential buffer overruns + or other programming errors that could be exploited by a malicious + programmer. + + If the ICU extension is used in an environment where potentially + malicious users may execute arbitrary SQL (i.e. gears), they + should be prevented from invoking the icu_load_collation() function, + possibly using the authorisation callback. diff --git a/components/external/SQLite-3.8.1/ext/icu/icu.c b/components/external/SQLite-3.8.1/ext/icu/icu.c new file mode 100644 index 0000000000000000000000000000000000000000..1ce1e0c806a0976fdd44c4c9e39110e496a41a6e --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/icu/icu.c @@ -0,0 +1,504 @@ +/* +** 2007 May 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $ +** +** This file implements an integration between the ICU library +** ("International Components for Unicode", an open-source library +** for handling unicode data) and SQLite. The integration uses +** ICU to provide the following to SQLite: +** +** * An implementation of the SQL regexp() function (and hence REGEXP +** operator) using the ICU uregex_XX() APIs. +** +** * Implementations of the SQL scalar upper() and lower() functions +** for case mapping. +** +** * Integration of ICU and SQLite collation sequences. +** +** * An implementation of the LIKE operator that uses ICU to +** provide case-independent matching. +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) + +/* Include ICU headers */ +#include +#include +#include +#include + +#include + +#ifndef SQLITE_CORE + #include "sqlite3ext.h" + SQLITE_EXTENSION_INIT1 +#else + #include "sqlite3.h" +#endif + +/* +** Maximum length (in bytes) of the pattern in a LIKE or GLOB +** operator. +*/ +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 +#endif + +/* +** Version of sqlite3_free() that is always a function, never a macro. +*/ +static void xFree(void *p){ + sqlite3_free(p); +} + +/* +** Compare two UTF-8 strings for equality where the first string is +** a "LIKE" expression. Return true (1) if they are the same and +** false (0) if they are different. +*/ +static int icuLikeCompare( + const uint8_t *zPattern, /* LIKE pattern */ + const uint8_t *zString, /* The UTF-8 string to compare against */ + const UChar32 uEsc /* The escape character */ +){ + static const int MATCH_ONE = (UChar32)'_'; + static const int MATCH_ALL = (UChar32)'%'; + + int iPattern = 0; /* Current byte index in zPattern */ + int iString = 0; /* Current byte index in zString */ + + int prevEscape = 0; /* True if the previous character was uEsc */ + + while( zPattern[iPattern]!=0 ){ + + /* Read (and consume) the next character from the input pattern. */ + UChar32 uPattern; + U8_NEXT_UNSAFE(zPattern, iPattern, uPattern); + assert(uPattern!=0); + + /* There are now 4 possibilities: + ** + ** 1. uPattern is an unescaped match-all character "%", + ** 2. uPattern is an unescaped match-one character "_", + ** 3. uPattern is an unescaped escape character, or + ** 4. uPattern is to be handled as an ordinary character + */ + if( !prevEscape && uPattern==MATCH_ALL ){ + /* Case 1. */ + uint8_t c; + + /* Skip any MATCH_ALL or MATCH_ONE characters that follow a + ** MATCH_ALL. For each MATCH_ONE, skip one character in the + ** test string. + */ + while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){ + if( c==MATCH_ONE ){ + if( zString[iString]==0 ) return 0; + U8_FWD_1_UNSAFE(zString, iString); + } + iPattern++; + } + + if( zPattern[iPattern]==0 ) return 1; + + while( zString[iString] ){ + if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){ + return 1; + } + U8_FWD_1_UNSAFE(zString, iString); + } + return 0; + + }else if( !prevEscape && uPattern==MATCH_ONE ){ + /* Case 2. */ + if( zString[iString]==0 ) return 0; + U8_FWD_1_UNSAFE(zString, iString); + + }else if( !prevEscape && uPattern==uEsc){ + /* Case 3. */ + prevEscape = 1; + + }else{ + /* Case 4. */ + UChar32 uString; + U8_NEXT_UNSAFE(zString, iString, uString); + uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT); + uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT); + if( uString!=uPattern ){ + return 0; + } + prevEscape = 0; + } + } + + return zString[iString]==0; +} + +/* +** Implementation of the like() SQL function. This function implements +** the build-in LIKE operator. The first argument to the function is the +** pattern and the second argument is the string. So, the SQL statements: +** +** A LIKE B +** +** is implemented as like(B, A). If there is an escape character E, +** +** A LIKE B ESCAPE E +** +** is mapped to like(B, A, E). +*/ +static void icuLikeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zA = sqlite3_value_text(argv[0]); + const unsigned char *zB = sqlite3_value_text(argv[1]); + UChar32 uEsc = 0; + + /* Limit the length of the LIKE or GLOB pattern to avoid problems + ** of deep recursion and N*N behavior in patternCompare(). + */ + if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){ + sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); + return; + } + + + if( argc==3 ){ + /* The escape character string must consist of a single UTF-8 character. + ** Otherwise, return an error. + */ + int nE= sqlite3_value_bytes(argv[2]); + const unsigned char *zE = sqlite3_value_text(argv[2]); + int i = 0; + if( zE==0 ) return; + U8_NEXT(zE, i, nE, uEsc); + if( i!=nE){ + sqlite3_result_error(context, + "ESCAPE expression must be a single character", -1); + return; + } + } + + if( zA && zB ){ + sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc)); + } +} + +/* +** This function is called when an ICU function called from within +** the implementation of an SQL scalar function returns an error. +** +** The scalar function context passed as the first argument is +** loaded with an error message based on the following two args. +*/ +static void icuFunctionError( + sqlite3_context *pCtx, /* SQLite scalar function context */ + const char *zName, /* Name of ICU function that failed */ + UErrorCode e /* Error code returned by ICU function */ +){ + char zBuf[128]; + sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e)); + zBuf[127] = '\0'; + sqlite3_result_error(pCtx, zBuf, -1); +} + +/* +** Function to delete compiled regexp objects. Registered as +** a destructor function with sqlite3_set_auxdata(). +*/ +static void icuRegexpDelete(void *p){ + URegularExpression *pExpr = (URegularExpression *)p; + uregex_close(pExpr); +} + +/* +** Implementation of SQLite REGEXP operator. This scalar function takes +** two arguments. The first is a regular expression pattern to compile +** the second is a string to match against that pattern. If either +** argument is an SQL NULL, then NULL Is returned. Otherwise, the result +** is 1 if the string matches the pattern, or 0 otherwise. +** +** SQLite maps the regexp() function to the regexp() operator such +** that the following two are equivalent: +** +** zString REGEXP zPattern +** regexp(zPattern, zString) +** +** Uses the following ICU regexp APIs: +** +** uregex_open() +** uregex_matches() +** uregex_close() +*/ +static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ + UErrorCode status = U_ZERO_ERROR; + URegularExpression *pExpr; + UBool res; + const UChar *zString = sqlite3_value_text16(apArg[1]); + + (void)nArg; /* Unused parameter */ + + /* If the left hand side of the regexp operator is NULL, + ** then the result is also NULL. + */ + if( !zString ){ + return; + } + + pExpr = sqlite3_get_auxdata(p, 0); + if( !pExpr ){ + const UChar *zPattern = sqlite3_value_text16(apArg[0]); + if( !zPattern ){ + return; + } + pExpr = uregex_open(zPattern, -1, 0, 0, &status); + + if( U_SUCCESS(status) ){ + sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete); + }else{ + assert(!pExpr); + icuFunctionError(p, "uregex_open", status); + return; + } + } + + /* Configure the text that the regular expression operates on. */ + uregex_setText(pExpr, zString, -1, &status); + if( !U_SUCCESS(status) ){ + icuFunctionError(p, "uregex_setText", status); + return; + } + + /* Attempt the match */ + res = uregex_matches(pExpr, 0, &status); + if( !U_SUCCESS(status) ){ + icuFunctionError(p, "uregex_matches", status); + return; + } + + /* Set the text that the regular expression operates on to a NULL + ** pointer. This is not really necessary, but it is tidier than + ** leaving the regular expression object configured with an invalid + ** pointer after this function returns. + */ + uregex_setText(pExpr, 0, 0, &status); + + /* Return 1 or 0. */ + sqlite3_result_int(p, res ? 1 : 0); +} + +/* +** Implementations of scalar functions for case mapping - upper() and +** lower(). Function upper() converts its input to upper-case (ABC). +** Function lower() converts to lower-case (abc). +** +** ICU provides two types of case mapping, "general" case mapping and +** "language specific". Refer to ICU documentation for the differences +** between the two. +** +** To utilise "general" case mapping, the upper() or lower() scalar +** functions are invoked with one argument: +** +** upper('ABC') -> 'abc' +** lower('abc') -> 'ABC' +** +** To access ICU "language specific" case mapping, upper() or lower() +** should be invoked with two arguments. The second argument is the name +** of the locale to use. Passing an empty string ("") or SQL NULL value +** as the second argument is the same as invoking the 1 argument version +** of upper() or lower(). +** +** lower('I', 'en_us') -> 'i' +** lower('I', 'tr_tr') -> 'ı' (small dotless i) +** +** http://www.icu-project.org/userguide/posix.html#case_mappings +*/ +static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ + const UChar *zInput; + UChar *zOutput; + int nInput; + int nOutput; + + UErrorCode status = U_ZERO_ERROR; + const char *zLocale = 0; + + assert(nArg==1 || nArg==2); + if( nArg==2 ){ + zLocale = (const char *)sqlite3_value_text(apArg[1]); + } + + zInput = sqlite3_value_text16(apArg[0]); + if( !zInput ){ + return; + } + nInput = sqlite3_value_bytes16(apArg[0]); + + nOutput = nInput * 2 + 2; + zOutput = sqlite3_malloc(nOutput); + if( !zOutput ){ + return; + } + + if( sqlite3_user_data(p) ){ + u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status); + }else{ + u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status); + } + + if( !U_SUCCESS(status) ){ + icuFunctionError(p, "u_strToLower()/u_strToUpper", status); + return; + } + + sqlite3_result_text16(p, zOutput, -1, xFree); +} + +/* +** Collation sequence destructor function. The pCtx argument points to +** a UCollator structure previously allocated using ucol_open(). +*/ +static void icuCollationDel(void *pCtx){ + UCollator *p = (UCollator *)pCtx; + ucol_close(p); +} + +/* +** Collation sequence comparison function. The pCtx argument points to +** a UCollator structure previously allocated using ucol_open(). +*/ +static int icuCollationColl( + void *pCtx, + int nLeft, + const void *zLeft, + int nRight, + const void *zRight +){ + UCollationResult res; + UCollator *p = (UCollator *)pCtx; + res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2); + switch( res ){ + case UCOL_LESS: return -1; + case UCOL_GREATER: return +1; + case UCOL_EQUAL: return 0; + } + assert(!"Unexpected return value from ucol_strcoll()"); + return 0; +} + +/* +** Implementation of the scalar function icu_load_collation(). +** +** This scalar function is used to add ICU collation based collation +** types to an SQLite database connection. It is intended to be called +** as follows: +** +** SELECT icu_load_collation(, ); +** +** Where is a string containing an ICU locale identifier (i.e. +** "en_AU", "tr_TR" etc.) and is the name of the +** collation sequence to create. +*/ +static void icuLoadCollation( + sqlite3_context *p, + int nArg, + sqlite3_value **apArg +){ + sqlite3 *db = (sqlite3 *)sqlite3_user_data(p); + UErrorCode status = U_ZERO_ERROR; + const char *zLocale; /* Locale identifier - (eg. "jp_JP") */ + const char *zName; /* SQL Collation sequence name (eg. "japanese") */ + UCollator *pUCollator; /* ICU library collation object */ + int rc; /* Return code from sqlite3_create_collation_x() */ + + assert(nArg==2); + zLocale = (const char *)sqlite3_value_text(apArg[0]); + zName = (const char *)sqlite3_value_text(apArg[1]); + + if( !zLocale || !zName ){ + return; + } + + pUCollator = ucol_open(zLocale, &status); + if( !U_SUCCESS(status) ){ + icuFunctionError(p, "ucol_open", status); + return; + } + assert(p); + + rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, + icuCollationColl, icuCollationDel + ); + if( rc!=SQLITE_OK ){ + ucol_close(pUCollator); + sqlite3_result_error(p, "Error registering collation function", -1); + } +} + +/* +** Register the ICU extension functions with database db. +*/ +int sqlite3IcuInit(sqlite3 *db){ + struct IcuScalar { + const char *zName; /* Function name */ + int nArg; /* Number of arguments */ + int enc; /* Optimal text encoding */ + void *pContext; /* sqlite3_user_data() context */ + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); + } scalars[] = { + {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc}, + + {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16}, + {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16}, + {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16}, + {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16}, + + {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16}, + {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16}, + {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16}, + {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16}, + + {"like", 2, SQLITE_UTF8, 0, icuLikeFunc}, + {"like", 3, SQLITE_UTF8, 0, icuLikeFunc}, + + {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation}, + }; + + int rc = SQLITE_OK; + int i; + + for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){ + struct IcuScalar *p = &scalars[i]; + rc = sqlite3_create_function( + db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0 + ); + } + + return rc; +} + +#if !SQLITE_CORE +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_icu_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi) + return sqlite3IcuInit(db); +} +#endif + +#endif diff --git a/components/external/SQLite-3.8.1/ext/icu/sqliteicu.h b/components/external/SQLite-3.8.1/ext/icu/sqliteicu.h new file mode 100644 index 0000000000000000000000000000000000000000..69b42f982102954b11c1652525a93586b201c7e8 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/icu/sqliteicu.h @@ -0,0 +1,27 @@ +/* +** 2008 May 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file is used by programs that want to link against the +** ICU extension. All it does is declare the sqlite3IcuInit() interface. +*/ +#include "sqlite3.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +int sqlite3IcuInit(sqlite3 *db); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ + diff --git a/components/external/SQLite-3.8.1/ext/misc/amatch.c b/components/external/SQLite-3.8.1/ext/misc/amatch.c new file mode 100644 index 0000000000000000000000000000000000000000..d869dbd8d1394af672f96a5508d9e5ab91a2934f --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/misc/amatch.c @@ -0,0 +1,1487 @@ +/* +** 2013-03-14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code for a demonstration virtual table that finds +** "approximate matches" - strings from a finite set that are nearly the +** same as a single input string. The virtual table is called "amatch". +** +** A amatch virtual table is created like this: +** +** CREATE VIRTUAL TABLE f USING approximate_match( +** vocabulary_table=, -- V +** vocabulary_word=, -- W +** vocabulary_language=, -- L +** edit_distances= +** ); +** +** When it is created, the new amatch table must be supplied with the +** the name of a table V and columns V.W and V.L such that +** +** SELECT W FROM V WHERE L=$language +** +** returns the allowed vocabulary for the match. If the "vocabulary_language" +** or L columnname is left unspecified or is an empty string, then no +** filtering of the vocabulary by language is performed. +** +** For efficiency, it is essential that the vocabulary table be indexed: +** +** CREATE vocab_index ON V(W) +** +** A separate edit-cost-table provides scoring information that defines +** what it means for one string to be "close" to another. +** +** The edit-cost-table must contain exactly four columns (more precisely, +** the statement "SELECT * FROM " must return records +** that consist of four columns). It does not matter what the columns are +** named. +** +** Each row in the edit-cost-table represents a single character +** transformation going from user input to the vocabulary. The leftmost +** column of the row (column 0) contains an integer identifier of the +** language to which the transformation rule belongs (see "MULTIPLE LANGUAGES" +** below). The second column of the row (column 1) contains the input +** character or characters - the characters of user input. The third +** column contains characters as they appear in the vocabulary table. +** And the fourth column contains the integer cost of making the +** transformation. For example: +** +** CREATE TABLE f_data(iLang, cFrom, cTo, Cost); +** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, '', 'a', 100); +** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, 'b', '', 87); +** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, 'o', 'oe', 38); +** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, 'oe', 'o', 40); +** +** The first row inserted into the edit-cost-table by the SQL script +** above indicates that the cost of having an extra 'a' in the vocabulary +** table that is missing in the user input 100. (All costs are integers. +** Overall cost must not exceed 16777216.) The second INSERT statement +** creates a rule saying that the cost of having a single letter 'b' in +** user input which is missing in the vocabulary table is 87. The third +** INSERT statement mean that the cost of matching an 'o' in user input +** against an 'oe' in the vocabulary table is 38. And so forth. +** +** The following rules are special: +** +** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, '?', '', 97); +** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, '', '?', 98); +** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, '?', '?', 99); +** +** The '?' to '' rule is the cost of having any single character in the input +** that is not found in the vocabular. The '' to '?' rule is the cost of +** having a character in the vocabulary table that is missing from input. +** And the '?' to '?' rule is the cost of doing an arbitrary character +** substitution. These three generic rules apply across all languages. +** In other words, the iLang field is ignored for the generic substitution +** rules. If more than one cost is given for a generic substitution rule, +** then the lowest cost is used. +** +** Once it has been created, the amatch virtual table can be queried +** as follows: +** +** SELECT word, distance FROM f +** WHERE word MATCH 'abcdefg' +** AND distance<200; +** +** This query outputs the strings contained in the T(F) field that +** are close to "abcdefg" and in order of increasing distance. No string +** is output more than once. If there are multiple ways to transform the +** target string ("abcdefg") into a string in the vocabulary table then +** the lowest cost transform is the one that is returned. In this example, +** the search is limited to strings with a total distance of less than 200. +** +** For efficiency, it is important to put tight bounds on the distance. +** The time and memory space needed to perform this query is exponential +** in the maximum distance. A good rule of thumb is to limit the distance +** to no more than 1.5 or 2 times the maximum cost of any rule in the +** edit-cost-table. +** +** The amatch is a read-only table. Any attempt to DELETE, INSERT, or +** UPDATE on a amatch table will throw an error. +** +** It is important to put some kind of a limit on the amatch output. This +** can be either in the form of a LIMIT clause at the end of the query, +** or better, a "distance +#include +#include +#include +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Forward declaration of objects used by this implementation +*/ +typedef struct amatch_vtab amatch_vtab; +typedef struct amatch_cursor amatch_cursor; +typedef struct amatch_rule amatch_rule; +typedef struct amatch_word amatch_word; +typedef struct amatch_avl amatch_avl; + + +/***************************************************************************** +** AVL Tree implementation +*/ +/* +** Objects that want to be members of the AVL tree should embedded an +** instance of this structure. +*/ +struct amatch_avl { + amatch_word *pWord; /* Points to the object being stored in the tree */ + char *zKey; /* Key. zero-terminated string. Must be unique */ + amatch_avl *pBefore; /* Other elements less than zKey */ + amatch_avl *pAfter; /* Other elements greater than zKey */ + amatch_avl *pUp; /* Parent element */ + short int height; /* Height of this node. Leaf==1 */ + short int imbalance; /* Height difference between pBefore and pAfter */ +}; + +/* Recompute the amatch_avl.height and amatch_avl.imbalance fields for p. +** Assume that the children of p have correct heights. +*/ +static void amatchAvlRecomputeHeight(amatch_avl *p){ + short int hBefore = p->pBefore ? p->pBefore->height : 0; + short int hAfter = p->pAfter ? p->pAfter->height : 0; + p->imbalance = hBefore - hAfter; /* -: pAfter higher. +: pBefore higher */ + p->height = (hBefore>hAfter ? hBefore : hAfter)+1; +} + +/* +** P B +** / \ / \ +** B Z ==> X P +** / \ / \ +** X Y Y Z +** +*/ +static amatch_avl *amatchAvlRotateBefore(amatch_avl *pP){ + amatch_avl *pB = pP->pBefore; + amatch_avl *pY = pB->pAfter; + pB->pUp = pP->pUp; + pB->pAfter = pP; + pP->pUp = pB; + pP->pBefore = pY; + if( pY ) pY->pUp = pP; + amatchAvlRecomputeHeight(pP); + amatchAvlRecomputeHeight(pB); + return pB; +} + +/* +** P A +** / \ / \ +** X A ==> P Z +** / \ / \ +** Y Z X Y +** +*/ +static amatch_avl *amatchAvlRotateAfter(amatch_avl *pP){ + amatch_avl *pA = pP->pAfter; + amatch_avl *pY = pA->pBefore; + pA->pUp = pP->pUp; + pA->pBefore = pP; + pP->pUp = pA; + pP->pAfter = pY; + if( pY ) pY->pUp = pP; + amatchAvlRecomputeHeight(pP); + amatchAvlRecomputeHeight(pA); + return pA; +} + +/* +** Return a pointer to the pBefore or pAfter pointer in the parent +** of p that points to p. Or if p is the root node, return pp. +*/ +static amatch_avl **amatchAvlFromPtr(amatch_avl *p, amatch_avl **pp){ + amatch_avl *pUp = p->pUp; + if( pUp==0 ) return pp; + if( pUp->pAfter==p ) return &pUp->pAfter; + return &pUp->pBefore; +} + +/* +** Rebalance all nodes starting with p and working up to the root. +** Return the new root. +*/ +static amatch_avl *amatchAvlBalance(amatch_avl *p){ + amatch_avl *pTop = p; + amatch_avl **pp; + while( p ){ + amatchAvlRecomputeHeight(p); + if( p->imbalance>=2 ){ + amatch_avl *pB = p->pBefore; + if( pB->imbalance<0 ) p->pBefore = amatchAvlRotateAfter(pB); + pp = amatchAvlFromPtr(p,&p); + p = *pp = amatchAvlRotateBefore(p); + }else if( p->imbalance<=(-2) ){ + amatch_avl *pA = p->pAfter; + if( pA->imbalance>0 ) p->pAfter = amatchAvlRotateBefore(pA); + pp = amatchAvlFromPtr(p,&p); + p = *pp = amatchAvlRotateAfter(p); + } + pTop = p; + p = p->pUp; + } + return pTop; +} + +/* Search the tree rooted at p for an entry with zKey. Return a pointer +** to the entry or return NULL. +*/ +static amatch_avl *amatchAvlSearch(amatch_avl *p, const char *zKey){ + int c; + while( p && (c = strcmp(zKey, p->zKey))!=0 ){ + p = (c<0) ? p->pBefore : p->pAfter; + } + return p; +} + +/* Find the first node (the one with the smallest key). +*/ +static amatch_avl *amatchAvlFirst(amatch_avl *p){ + if( p ) while( p->pBefore ) p = p->pBefore; + return p; +} + +#if 0 /* NOT USED */ +/* Return the node with the next larger key after p. +*/ +static amatch_avl *amatchAvlNext(amatch_avl *p){ + amatch_avl *pPrev = 0; + while( p && p->pAfter==pPrev ){ + pPrev = p; + p = p->pUp; + } + if( p && pPrev==0 ){ + p = amatchAvlFirst(p->pAfter); + } + return p; +} +#endif + +#if 0 /* NOT USED */ +/* Verify AVL tree integrity +*/ +static int amatchAvlIntegrity(amatch_avl *pHead){ + amatch_avl *p; + if( pHead==0 ) return 1; + if( (p = pHead->pBefore)!=0 ){ + assert( p->pUp==pHead ); + assert( amatchAvlIntegrity(p) ); + assert( strcmp(p->zKey, pHead->zKey)<0 ); + while( p->pAfter ) p = p->pAfter; + assert( strcmp(p->zKey, pHead->zKey)<0 ); + } + if( (p = pHead->pAfter)!=0 ){ + assert( p->pUp==pHead ); + assert( amatchAvlIntegrity(p) ); + assert( strcmp(p->zKey, pHead->zKey)>0 ); + p = amatchAvlFirst(p); + assert( strcmp(p->zKey, pHead->zKey)>0 ); + } + return 1; +} +static int amatchAvlIntegrity2(amatch_avl *pHead){ + amatch_avl *p, *pNext; + for(p=amatchAvlFirst(pHead); p; p=pNext){ + pNext = amatchAvlNext(p); + if( pNext==0 ) break; + assert( strcmp(p->zKey, pNext->zKey)<0 ); + } + return 1; +} +#endif + +/* Insert a new node pNew. Return NULL on success. If the key is not +** unique, then do not perform the insert but instead leave pNew unchanged +** and return a pointer to an existing node with the same key. +*/ +static amatch_avl *amatchAvlInsert(amatch_avl **ppHead, amatch_avl *pNew){ + int c; + amatch_avl *p = *ppHead; + if( p==0 ){ + p = pNew; + pNew->pUp = 0; + }else{ + while( p ){ + c = strcmp(pNew->zKey, p->zKey); + if( c<0 ){ + if( p->pBefore ){ + p = p->pBefore; + }else{ + p->pBefore = pNew; + pNew->pUp = p; + break; + } + }else if( c>0 ){ + if( p->pAfter ){ + p = p->pAfter; + }else{ + p->pAfter = pNew; + pNew->pUp = p; + break; + } + }else{ + return p; + } + } + } + pNew->pBefore = 0; + pNew->pAfter = 0; + pNew->height = 1; + pNew->imbalance = 0; + *ppHead = amatchAvlBalance(p); + /* assert( amatchAvlIntegrity(*ppHead) ); */ + /* assert( amatchAvlIntegrity2(*ppHead) ); */ + return 0; +} + +/* Remove node pOld from the tree. pOld must be an element of the tree or +** the AVL tree will become corrupt. +*/ +static void amatchAvlRemove(amatch_avl **ppHead, amatch_avl *pOld){ + amatch_avl **ppParent; + amatch_avl *pBalance; + /* assert( amatchAvlSearch(*ppHead, pOld->zKey)==pOld ); */ + ppParent = amatchAvlFromPtr(pOld, ppHead); + if( pOld->pBefore==0 && pOld->pAfter==0 ){ + *ppParent = 0; + pBalance = pOld->pUp; + }else if( pOld->pBefore && pOld->pAfter ){ + amatch_avl *pX, *pY; + pX = amatchAvlFirst(pOld->pAfter); + *amatchAvlFromPtr(pX, 0) = pX->pAfter; + if( pX->pAfter ) pX->pAfter->pUp = pX->pUp; + pBalance = pX->pUp; + pX->pAfter = pOld->pAfter; + if( pX->pAfter ){ + pX->pAfter->pUp = pX; + }else{ + assert( pBalance==pOld ); + pBalance = pX; + } + pX->pBefore = pY = pOld->pBefore; + if( pY ) pY->pUp = pX; + pX->pUp = pOld->pUp; + *ppParent = pX; + }else if( pOld->pBefore==0 ){ + *ppParent = pBalance = pOld->pAfter; + pBalance->pUp = pOld->pUp; + }else if( pOld->pAfter==0 ){ + *ppParent = pBalance = pOld->pBefore; + pBalance->pUp = pOld->pUp; + } + *ppHead = amatchAvlBalance(pBalance); + pOld->pUp = 0; + pOld->pBefore = 0; + pOld->pAfter = 0; + /* assert( amatchAvlIntegrity(*ppHead) ); */ + /* assert( amatchAvlIntegrity2(*ppHead) ); */ +} +/* +** End of the AVL Tree implementation +******************************************************************************/ + + +/* +** Various types. +** +** amatch_cost is the "cost" of an edit operation. +** +** amatch_len is the length of a matching string. +** +** amatch_langid is an ruleset identifier. +*/ +typedef int amatch_cost; +typedef signed char amatch_len; +typedef int amatch_langid; + +/* +** Limits +*/ +#define AMATCH_MX_LENGTH 50 /* Maximum length of a rule string */ +#define AMATCH_MX_LANGID 2147483647 /* Maximum rule ID */ +#define AMATCH_MX_COST 1000 /* Maximum single-rule cost */ + +/* +** A match or partial match +*/ +struct amatch_word { + amatch_word *pNext; /* Next on a list of all amatch_words */ + amatch_avl sCost; /* Linkage of this node into the cost tree */ + amatch_avl sWord; /* Linkage of this node into the word tree */ + amatch_cost rCost; /* Cost of the match so far */ + int iSeq; /* Sequence number */ + char zCost[10]; /* Cost key (text rendering of rCost) */ + short int nMatch; /* Input characters matched */ + char zWord[4]; /* Text of the word. Extra space appended as needed */ +}; + +/* +** Each transformation rule is stored as an instance of this object. +** All rules are kept on a linked list sorted by rCost. +*/ +struct amatch_rule { + amatch_rule *pNext; /* Next rule in order of increasing rCost */ + char *zFrom; /* Transform from (a string from user input) */ + amatch_cost rCost; /* Cost of this transformation */ + amatch_langid iLang; /* The langauge to which this rule belongs */ + amatch_len nFrom, nTo; /* Length of the zFrom and zTo strings */ + char zTo[4]; /* Tranform to V.W value (extra space appended) */ +}; + +/* +** A amatch virtual-table object +*/ +struct amatch_vtab { + sqlite3_vtab base; /* Base class - must be first */ + char *zClassName; /* Name of this class. Default: "amatch" */ + char *zDb; /* Name of database. (ex: "main") */ + char *zSelf; /* Name of this virtual table */ + char *zCostTab; /* Name of edit-cost-table */ + char *zVocabTab; /* Name of vocabulary table */ + char *zVocabWord; /* Name of vocabulary table word column */ + char *zVocabLang; /* Name of vocabulary table language column */ + amatch_rule *pRule; /* All active rules in this amatch */ + amatch_cost rIns; /* Generic insertion cost '' -> ? */ + amatch_cost rDel; /* Generic deletion cost ? -> '' */ + amatch_cost rSub; /* Generic substitution cost ? -> ? */ + sqlite3 *db; /* The database connection */ + sqlite3_stmt *pVCheck; /* Query to check zVocabTab */ + int nCursor; /* Number of active cursors */ +}; + +/* A amatch cursor object */ +struct amatch_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + sqlite3_int64 iRowid; /* The rowid of the current word */ + amatch_langid iLang; /* Use this language ID */ + amatch_cost rLimit; /* Maximum cost of any term */ + int nBuf; /* Space allocated for zBuf */ + int oomErr; /* True following an OOM error */ + int nWord; /* Number of amatch_word objects */ + char *zBuf; /* Temp-use buffer space */ + char *zInput; /* Input word to match against */ + amatch_vtab *pVtab; /* The virtual table this cursor belongs to */ + amatch_word *pAllWords; /* List of all amatch_word objects */ + amatch_word *pCurrent; /* Most recent solution */ + amatch_avl *pCost; /* amatch_word objects keyed by iCost */ + amatch_avl *pWord; /* amatch_word objects keyed by zWord */ +}; + +/* +** The two input rule lists are both sorted in order of increasing +** cost. Merge them together into a single list, sorted by cost, and +** return a pointer to the head of that list. +*/ +static amatch_rule *amatchMergeRules(amatch_rule *pA, amatch_rule *pB){ + amatch_rule head; + amatch_rule *pTail; + + pTail = &head; + while( pA && pB ){ + if( pA->rCost<=pB->rCost ){ + pTail->pNext = pA; + pTail = pA; + pA = pA->pNext; + }else{ + pTail->pNext = pB; + pTail = pB; + pB = pB->pNext; + } + } + if( pA==0 ){ + pTail->pNext = pB; + }else{ + pTail->pNext = pA; + } + return head.pNext; +} + +/* +** Statement pStmt currently points to a row in the amatch data table. This +** function allocates and populates a amatch_rule structure according to +** the content of the row. +** +** If successful, *ppRule is set to point to the new object and SQLITE_OK +** is returned. Otherwise, *ppRule is zeroed, *pzErr may be set to point +** to an error message and an SQLite error code returned. +*/ +static int amatchLoadOneRule( + amatch_vtab *p, /* Fuzzer virtual table handle */ + sqlite3_stmt *pStmt, /* Base rule on statements current row */ + amatch_rule **ppRule, /* OUT: New rule object */ + char **pzErr /* OUT: Error message */ +){ + sqlite3_int64 iLang = sqlite3_column_int64(pStmt, 0); + const char *zFrom = (const char *)sqlite3_column_text(pStmt, 1); + const char *zTo = (const char *)sqlite3_column_text(pStmt, 2); + amatch_cost rCost = sqlite3_column_int(pStmt, 3); + + int rc = SQLITE_OK; /* Return code */ + int nFrom; /* Size of string zFrom, in bytes */ + int nTo; /* Size of string zTo, in bytes */ + amatch_rule *pRule = 0; /* New rule object to return */ + + if( zFrom==0 ) zFrom = ""; + if( zTo==0 ) zTo = ""; + nFrom = (int)strlen(zFrom); + nTo = (int)strlen(zTo); + + /* Silently ignore null transformations */ + if( strcmp(zFrom, zTo)==0 ){ + if( zFrom[0]=='?' && zFrom[1]==0 ){ + if( p->rSub==0 || p->rSub>rCost ) p->rSub = rCost; + } + *ppRule = 0; + return SQLITE_OK; + } + + if( rCost<=0 || rCost>AMATCH_MX_COST ){ + *pzErr = sqlite3_mprintf("%s: cost must be between 1 and %d", + p->zClassName, AMATCH_MX_COST + ); + rc = SQLITE_ERROR; + }else + if( nFrom>AMATCH_MX_LENGTH || nTo>AMATCH_MX_LENGTH ){ + *pzErr = sqlite3_mprintf("%s: maximum string length is %d", + p->zClassName, AMATCH_MX_LENGTH + ); + rc = SQLITE_ERROR; + }else + if( iLang<0 || iLang>AMATCH_MX_LANGID ){ + *pzErr = sqlite3_mprintf("%s: iLang must be between 0 and %d", + p->zClassName, AMATCH_MX_LANGID + ); + rc = SQLITE_ERROR; + }else + if( strcmp(zFrom,"")==0 && strcmp(zTo,"?")==0 ){ + if( p->rIns==0 || p->rIns>rCost ) p->rIns = rCost; + }else + if( strcmp(zFrom,"?")==0 && strcmp(zTo,"")==0 ){ + if( p->rDel==0 || p->rDel>rCost ) p->rDel = rCost; + }else + { + pRule = sqlite3_malloc( sizeof(*pRule) + nFrom + nTo ); + if( pRule==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pRule, 0, sizeof(*pRule)); + pRule->zFrom = &pRule->zTo[nTo+1]; + pRule->nFrom = nFrom; + memcpy(pRule->zFrom, zFrom, nFrom+1); + memcpy(pRule->zTo, zTo, nTo+1); + pRule->nTo = nTo; + pRule->rCost = rCost; + pRule->iLang = (int)iLang; + } + } + + *ppRule = pRule; + return rc; +} + +/* +** Free all the content in the edit-cost-table +*/ +static void amatchFreeRules(amatch_vtab *p){ + while( p->pRule ){ + amatch_rule *pRule = p->pRule; + p->pRule = pRule->pNext; + sqlite3_free(pRule); + } + p->pRule = 0; +} + +/* +** Load the content of the amatch data table into memory. +*/ +static int amatchLoadRules( + sqlite3 *db, /* Database handle */ + amatch_vtab *p, /* Virtual amatch table to configure */ + char **pzErr /* OUT: Error message */ +){ + int rc = SQLITE_OK; /* Return code */ + char *zSql; /* SELECT used to read from rules table */ + amatch_rule *pHead = 0; + + zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", p->zDb, p->zCostTab); + if( zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + int rc2; /* finalize() return code */ + sqlite3_stmt *pStmt = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + *pzErr = sqlite3_mprintf("%s: %s", p->zClassName, sqlite3_errmsg(db)); + }else if( sqlite3_column_count(pStmt)!=4 ){ + *pzErr = sqlite3_mprintf("%s: %s has %d columns, expected 4", + p->zClassName, p->zCostTab, sqlite3_column_count(pStmt) + ); + rc = SQLITE_ERROR; + }else{ + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ + amatch_rule *pRule = 0; + rc = amatchLoadOneRule(p, pStmt, &pRule, pzErr); + if( pRule ){ + pRule->pNext = pHead; + pHead = pRule; + } + } + } + rc2 = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ) rc = rc2; + } + sqlite3_free(zSql); + + /* All rules are now in a singly linked list starting at pHead. This + ** block sorts them by cost and then sets amatch_vtab.pRule to point to + ** point to the head of the sorted list. + */ + if( rc==SQLITE_OK ){ + unsigned int i; + amatch_rule *pX; + amatch_rule *a[15]; + for(i=0; ipNext; + pX->pNext = 0; + for(i=0; a[i] && ipRule = amatchMergeRules(p->pRule, pX); + }else{ + /* An error has occurred. Setting p->pRule to point to the head of the + ** allocated list ensures that the list will be cleaned up in this case. + */ + assert( p->pRule==0 ); + p->pRule = pHead; + } + + return rc; +} + +/* +** This function converts an SQL quoted string into an unquoted string +** and returns a pointer to a buffer allocated using sqlite3_malloc() +** containing the result. The caller should eventually free this buffer +** using sqlite3_free. +** +** Examples: +** +** "abc" becomes abc +** 'xyz' becomes xyz +** [pqr] becomes pqr +** `mno` becomes mno +*/ +static char *amatchDequote(const char *zIn){ + int nIn; /* Size of input string, in bytes */ + char *zOut; /* Output (dequoted) string */ + + nIn = (int)strlen(zIn); + zOut = sqlite3_malloc(nIn+1); + if( zOut ){ + char q = zIn[0]; /* Quote character (if any ) */ + + if( q!='[' && q!= '\'' && q!='"' && q!='`' ){ + memcpy(zOut, zIn, nIn+1); + }else{ + int iOut = 0; /* Index of next byte to write to output */ + int iIn; /* Index of next byte to read from input */ + + if( q=='[' ) q = ']'; + for(iIn=1; iInpVCheck ){ + sqlite3_finalize(p->pVCheck); + p->pVCheck = 0; + } +} + +/* +** Deallocate an amatch_vtab object +*/ +static void amatchFree(amatch_vtab *p){ + if( p ){ + amatchFreeRules(p); + amatchVCheckClear(p); + sqlite3_free(p->zClassName); + sqlite3_free(p->zDb); + sqlite3_free(p->zCostTab); + sqlite3_free(p->zVocabTab); + sqlite3_free(p->zVocabWord); + sqlite3_free(p->zVocabLang); + sqlite3_free(p->zSelf); + memset(p, 0, sizeof(*p)); + sqlite3_free(p); + } +} + +/* +** xDisconnect/xDestroy method for the amatch module. +*/ +static int amatchDisconnect(sqlite3_vtab *pVtab){ + amatch_vtab *p = (amatch_vtab*)pVtab; + assert( p->nCursor==0 ); + amatchFree(p); + return SQLITE_OK; +} + +/* +** Check to see if the argument is of the form: +** +** KEY = VALUE +** +** If it is, return a pointer to the first character of VALUE. +** If not, return NULL. Spaces around the = are ignored. +*/ +static const char *amatchValueOfKey(const char *zKey, const char *zStr){ + int nKey = (int)strlen(zKey); + int nStr = (int)strlen(zStr); + int i; + if( nStr module name ("approximate_match") +** argv[1] -> database name +** argv[2] -> table name +** argv[3...] -> arguments +*/ +static int amatchConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int rc = SQLITE_OK; /* Return code */ + amatch_vtab *pNew = 0; /* New virtual table */ + const char *zModule = argv[0]; + const char *zDb = argv[1]; + const char *zVal; + int i; + + (void)pAux; + *ppVtab = 0; + pNew = sqlite3_malloc( sizeof(*pNew) ); + if( pNew==0 ) return SQLITE_NOMEM; + rc = SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + pNew->db = db; + pNew->zClassName = sqlite3_mprintf("%s", zModule); + if( pNew->zClassName==0 ) goto amatchConnectError; + pNew->zDb = sqlite3_mprintf("%s", zDb); + if( pNew->zDb==0 ) goto amatchConnectError; + pNew->zSelf = sqlite3_mprintf("%s", argv[2]); + if( pNew->zSelf==0 ) goto amatchConnectError; + for(i=3; izVocabTab); + pNew->zVocabTab = amatchDequote(zVal); + if( pNew->zVocabTab==0 ) goto amatchConnectError; + continue; + } + zVal = amatchValueOfKey("vocabulary_word", argv[i]); + if( zVal ){ + sqlite3_free(pNew->zVocabWord); + pNew->zVocabWord = amatchDequote(zVal); + if( pNew->zVocabWord==0 ) goto amatchConnectError; + continue; + } + zVal = amatchValueOfKey("vocabulary_language", argv[i]); + if( zVal ){ + sqlite3_free(pNew->zVocabLang); + pNew->zVocabLang = amatchDequote(zVal); + if( pNew->zVocabLang==0 ) goto amatchConnectError; + continue; + } + zVal = amatchValueOfKey("edit_distances", argv[i]); + if( zVal ){ + sqlite3_free(pNew->zCostTab); + pNew->zCostTab = amatchDequote(zVal); + if( pNew->zCostTab==0 ) goto amatchConnectError; + continue; + } + *pzErr = sqlite3_mprintf("unrecognized argument: [%s]\n", argv[i]); + amatchFree(pNew); + *ppVtab = 0; + return SQLITE_ERROR; + } + rc = SQLITE_OK; + if( pNew->zCostTab==0 ){ + *pzErr = sqlite3_mprintf("no edit_distances table specified"); + rc = SQLITE_ERROR; + }else{ + rc = amatchLoadRules(db, pNew, pzErr); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_declare_vtab(db, + "CREATE TABLE x(word,distance,language," + "command HIDDEN,nword HIDDEN)" + ); +#define AMATCH_COL_WORD 0 +#define AMATCH_COL_DISTANCE 1 +#define AMATCH_COL_LANGUAGE 2 +#define AMATCH_COL_COMMAND 3 +#define AMATCH_COL_NWORD 4 + } + if( rc!=SQLITE_OK ){ + amatchFree(pNew); + } + *ppVtab = &pNew->base; + return rc; + +amatchConnectError: + amatchFree(pNew); + return rc; +} + +/* +** Open a new amatch cursor. +*/ +static int amatchOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + amatch_vtab *p = (amatch_vtab*)pVTab; + amatch_cursor *pCur; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + pCur->pVtab = p; + *ppCursor = &pCur->base; + p->nCursor++; + return SQLITE_OK; +} + +/* +** Free up all the memory allocated by a cursor. Set it rLimit to 0 +** to indicate that it is at EOF. +*/ +static void amatchClearCursor(amatch_cursor *pCur){ + amatch_word *pWord, *pNextWord; + for(pWord=pCur->pAllWords; pWord; pWord=pNextWord){ + pNextWord = pWord->pNext; + sqlite3_free(pWord); + } + pCur->pAllWords = 0; + sqlite3_free(pCur->zInput); + pCur->zInput = 0; + sqlite3_free(pCur->zBuf); + pCur->zBuf = 0; + pCur->nBuf = 0; + pCur->pCost = 0; + pCur->pWord = 0; + pCur->pCurrent = 0; + pCur->rLimit = 1000000; + pCur->iLang = 0; + pCur->nWord = 0; +} + +/* +** Close a amatch cursor. +*/ +static int amatchClose(sqlite3_vtab_cursor *cur){ + amatch_cursor *pCur = (amatch_cursor *)cur; + amatchClearCursor(pCur); + pCur->pVtab->nCursor--; + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Render a 24-bit unsigned integer as a 4-byte base-64 number. +*/ +static void amatchEncodeInt(int x, char *z){ + static const char a[] = + "0123456789" + "ABCDEFGHIJ" + "KLMNOPQRST" + "UVWXYZ^abc" + "defghijklm" + "nopqrstuvw" + "xyz~"; + z[0] = a[(x>>18)&0x3f]; + z[1] = a[(x>>12)&0x3f]; + z[2] = a[(x>>6)&0x3f]; + z[3] = a[x&0x3f]; +} + +/* +** Write the zCost[] field for a amatch_word object +*/ +static void amatchWriteCost(amatch_word *pWord){ + amatchEncodeInt(pWord->rCost, pWord->zCost); + amatchEncodeInt(pWord->iSeq, pWord->zCost+4); + pWord->zCost[8] = 0; +} + +/* +** Add a new amatch_word object to the queue. +** +** If a prior amatch_word object with the same zWord, and nMatch +** already exists, update its rCost (if the new rCost is less) but +** otherwise leave it unchanged. Do not add a duplicate. +** +** Do nothing if the cost exceeds threshold. +*/ +static void amatchAddWord( + amatch_cursor *pCur, + amatch_cost rCost, + int nMatch, + const char *zWordBase, + const char *zWordTail +){ + amatch_word *pWord; + amatch_avl *pNode; + amatch_avl *pOther; + int nBase, nTail; + char zBuf[4]; + + if( rCost>pCur->rLimit ){ + return; + } + nBase = (int)strlen(zWordBase); + nTail = (int)strlen(zWordTail); + if( nBase+nTail+3>pCur->nBuf ){ + pCur->nBuf = nBase+nTail+100; + pCur->zBuf = sqlite3_realloc(pCur->zBuf, pCur->nBuf); + if( pCur->zBuf==0 ){ + pCur->nBuf = 0; + return; + } + } + amatchEncodeInt(nMatch, zBuf); + memcpy(pCur->zBuf, zBuf+2, 2); + memcpy(pCur->zBuf+2, zWordBase, nBase); + memcpy(pCur->zBuf+2+nBase, zWordTail, nTail+1); + pNode = amatchAvlSearch(pCur->pWord, pCur->zBuf); + if( pNode ){ + pWord = pNode->pWord; + if( pWord->rCost>rCost ){ +#ifdef AMATCH_TRACE_1 + printf("UPDATE [%s][%.*s^%s] %d (\"%s\" \"%s\")\n", + pWord->zWord+2, pWord->nMatch, pCur->zInput, pCur->zInput, + pWord->rCost, pWord->zWord, pWord->zCost); +#endif + amatchAvlRemove(&pCur->pCost, &pWord->sCost); + pWord->rCost = rCost; + amatchWriteCost(pWord); +#ifdef AMATCH_TRACE_1 + printf(" ---> %d (\"%s\" \"%s\")\n", + pWord->rCost, pWord->zWord, pWord->zCost); +#endif + pOther = amatchAvlInsert(&pCur->pCost, &pWord->sCost); + assert( pOther==0 ); (void)pOther; + } + return; + } + pWord = sqlite3_malloc( sizeof(*pWord) + nBase + nTail - 1 ); + if( pWord==0 ) return; + memset(pWord, 0, sizeof(*pWord)); + pWord->rCost = rCost; + pWord->iSeq = pCur->nWord++; + amatchWriteCost(pWord); + pWord->nMatch = nMatch; + pWord->pNext = pCur->pAllWords; + pCur->pAllWords = pWord; + pWord->sCost.zKey = pWord->zCost; + pWord->sCost.pWord = pWord; + pOther = amatchAvlInsert(&pCur->pCost, &pWord->sCost); + assert( pOther==0 ); (void)pOther; + pWord->sWord.zKey = pWord->zWord; + pWord->sWord.pWord = pWord; + strcpy(pWord->zWord, pCur->zBuf); + pOther = amatchAvlInsert(&pCur->pWord, &pWord->sWord); + assert( pOther==0 ); (void)pOther; +#ifdef AMATCH_TRACE_1 + printf("INSERT [%s][%.*s^%s] %d (\"%s\" \"%s\")\n", pWord->zWord+2, + pWord->nMatch, pCur->zInput, pCur->zInput+pWord->nMatch, rCost, + pWord->zWord, pWord->zCost); +#endif +} + +/* +** Advance a cursor to its next row of output +*/ +static int amatchNext(sqlite3_vtab_cursor *cur){ + amatch_cursor *pCur = (amatch_cursor*)cur; + amatch_word *pWord = 0; + amatch_avl *pNode; + int isMatch = 0; + amatch_vtab *p = pCur->pVtab; + int nWord; + int rc; + int i; + const char *zW; + amatch_rule *pRule; + char *zBuf = 0; + char nBuf = 0; + char zNext[8]; + char zNextIn[8]; + int nNextIn; + + if( p->pVCheck==0 ){ + char *zSql; + if( p->zVocabLang && p->zVocabLang[0] ){ + zSql = sqlite3_mprintf( + "SELECT \"%w\" FROM \"%w\"", + " WHERE \"%w\">=?1 AND \"%w\"=?2" + " ORDER BY 1", + p->zVocabWord, p->zVocabTab, + p->zVocabWord, p->zVocabLang + ); + }else{ + zSql = sqlite3_mprintf( + "SELECT \"%w\" FROM \"%w\"" + " WHERE \"%w\">=?1" + " ORDER BY 1", + p->zVocabWord, p->zVocabTab, + p->zVocabWord + ); + } + rc = sqlite3_prepare_v2(p->db, zSql, -1, &p->pVCheck, 0); + sqlite3_free(zSql); + if( rc ) return rc; + } + sqlite3_bind_int(p->pVCheck, 2, pCur->iLang); + + do{ + pNode = amatchAvlFirst(pCur->pCost); + if( pNode==0 ){ + pWord = 0; + break; + } + pWord = pNode->pWord; + amatchAvlRemove(&pCur->pCost, &pWord->sCost); + +#ifdef AMATCH_TRACE_1 + printf("PROCESS [%s][%.*s^%s] %d (\"%s\" \"%s\")\n", + pWord->zWord+2, pWord->nMatch, pCur->zInput, pCur->zInput+pWord->nMatch, + pWord->rCost, pWord->zWord, pWord->zCost); +#endif + nWord = (int)strlen(pWord->zWord+2); + if( nWord+20>nBuf ){ + nBuf = nWord+100; + zBuf = sqlite3_realloc(zBuf, nBuf); + if( zBuf==0 ) return SQLITE_NOMEM; + } + strcpy(zBuf, pWord->zWord+2); + zNext[0] = 0; + zNextIn[0] = pCur->zInput[pWord->nMatch]; + if( zNextIn[0] ){ + for(i=1; i<=4 && (pCur->zInput[pWord->nMatch+i]&0xc0)==0x80; i++){ + zNextIn[i] = pCur->zInput[pWord->nMatch+i]; + } + zNextIn[i] = 0; + nNextIn = i; + }else{ + nNextIn = 0; + } + + if( zNextIn[0] && zNextIn[0]!='*' ){ + sqlite3_reset(p->pVCheck); + strcat(zBuf, zNextIn); + sqlite3_bind_text(p->pVCheck, 1, zBuf, nWord+nNextIn, SQLITE_STATIC); + rc = sqlite3_step(p->pVCheck); + if( rc==SQLITE_ROW ){ + zW = (const char*)sqlite3_column_text(p->pVCheck, 0); + if( strncmp(zBuf, zW, nWord+nNextIn)==0 ){ + amatchAddWord(pCur, pWord->rCost, pWord->nMatch+nNextIn, zBuf, ""); + } + } + zBuf[nWord] = 0; + } + + while( 1 ){ + strcpy(zBuf+nWord, zNext); + sqlite3_reset(p->pVCheck); + sqlite3_bind_text(p->pVCheck, 1, zBuf, -1, SQLITE_TRANSIENT); + rc = sqlite3_step(p->pVCheck); + if( rc!=SQLITE_ROW ) break; + zW = (const char*)sqlite3_column_text(p->pVCheck, 0); + strcpy(zBuf+nWord, zNext); + if( strncmp(zW, zBuf, nWord)!=0 ) break; + if( (zNextIn[0]=='*' && zNextIn[1]==0) + || (zNextIn[0]==0 && zW[nWord]==0) + ){ + isMatch = 1; + zNextIn[0] = 0; + nNextIn = 0; + break; + } + zNext[0] = zW[nWord]; + for(i=1; i<=4 && (zW[nWord+i]&0xc0)==0x80; i++){ + zNext[i] = zW[nWord+i]; + } + zNext[i] = 0; + zBuf[nWord] = 0; + if( p->rIns>0 ){ + amatchAddWord(pCur, pWord->rCost+p->rIns, pWord->nMatch, + zBuf, zNext); + } + if( p->rSub>0 ){ + amatchAddWord(pCur, pWord->rCost+p->rSub, pWord->nMatch+nNextIn, + zBuf, zNext); + } + if( p->rIns<0 && p->rSub<0 ) break; + zNext[i-1]++; /* FIX ME */ + } + sqlite3_reset(p->pVCheck); + + if( p->rDel>0 ){ + zBuf[nWord] = 0; + amatchAddWord(pCur, pWord->rCost+p->rDel, pWord->nMatch+nNextIn, + zBuf, ""); + } + + for(pRule=p->pRule; pRule; pRule=pRule->pNext){ + if( pRule->iLang!=pCur->iLang ) continue; + if( strncmp(pRule->zFrom, pCur->zInput+pWord->nMatch, pRule->nFrom)==0 ){ + amatchAddWord(pCur, pWord->rCost+pRule->rCost, + pWord->nMatch+pRule->nFrom, pWord->zWord+2, pRule->zTo); + } + } + }while( !isMatch ); + pCur->pCurrent = pWord; + sqlite3_free(zBuf); + return SQLITE_OK; +} + +/* +** Called to "rewind" a cursor back to the beginning so that +** it starts its output over again. Always called at least once +** prior to any amatchColumn, amatchRowid, or amatchEof call. +*/ +static int amatchFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + amatch_cursor *pCur = (amatch_cursor *)pVtabCursor; + const char *zWord = "*"; + int idx; + + amatchClearCursor(pCur); + idx = 0; + if( idxNum & 1 ){ + zWord = (const char*)sqlite3_value_text(argv[0]); + idx++; + } + if( idxNum & 2 ){ + pCur->rLimit = (amatch_cost)sqlite3_value_int(argv[idx]); + idx++; + } + if( idxNum & 4 ){ + pCur->iLang = (amatch_cost)sqlite3_value_int(argv[idx]); + idx++; + } + pCur->zInput = sqlite3_mprintf("%s", zWord); + if( pCur->zInput==0 ) return SQLITE_NOMEM; + amatchAddWord(pCur, 0, 0, "", ""); + amatchNext(pVtabCursor); + + return SQLITE_OK; +} + +/* +** Only the word and distance columns have values. All other columns +** return NULL +*/ +static int amatchColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + amatch_cursor *pCur = (amatch_cursor*)cur; + switch( i ){ + case AMATCH_COL_WORD: { + sqlite3_result_text(ctx, pCur->pCurrent->zWord+2, -1, SQLITE_STATIC); + break; + } + case AMATCH_COL_DISTANCE: { + sqlite3_result_int(ctx, pCur->pCurrent->rCost); + break; + } + case AMATCH_COL_LANGUAGE: { + sqlite3_result_int(ctx, pCur->iLang); + break; + } + case AMATCH_COL_NWORD: { + sqlite3_result_int(ctx, pCur->nWord); + break; + } + default: { + sqlite3_result_null(ctx); + break; + } + } + return SQLITE_OK; +} + +/* +** The rowid. +*/ +static int amatchRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + amatch_cursor *pCur = (amatch_cursor*)cur; + *pRowid = pCur->iRowid; + return SQLITE_OK; +} + +/* +** EOF indicator +*/ +static int amatchEof(sqlite3_vtab_cursor *cur){ + amatch_cursor *pCur = (amatch_cursor*)cur; + return pCur->pCurrent==0; +} + +/* +** Search for terms of these forms: +** +** (A) word MATCH $str +** (B1) distance < $value +** (B2) distance <= $value +** (C) language == $language +** +** The distance< and distance<= are both treated as distance<=. +** The query plan number is a bit vector: +** +** bit 1: Term of the form (A) found +** bit 2: Term like (B1) or (B2) found +** bit 3: Term like (C) found +** +** If bit-1 is set, $str is always in filter.argv[0]. If bit-2 is set +** then $value is in filter.argv[0] if bit-1 is clear and is in +** filter.argv[1] if bit-1 is set. If bit-3 is set, then $ruleid is +** in filter.argv[0] if bit-1 and bit-2 are both zero, is in +** filter.argv[1] if exactly one of bit-1 and bit-2 are set, and is in +** filter.argv[2] if both bit-1 and bit-2 are set. +*/ +static int amatchBestIndex( + sqlite3_vtab *tab, + sqlite3_index_info *pIdxInfo +){ + int iPlan = 0; + int iDistTerm = -1; + int iLangTerm = -1; + int i; + const struct sqlite3_index_constraint *pConstraint; + + (void)tab; + pConstraint = pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pConstraint++){ + if( pConstraint->usable==0 ) continue; + if( (iPlan & 1)==0 + && pConstraint->iColumn==0 + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH + ){ + iPlan |= 1; + pIdxInfo->aConstraintUsage[i].argvIndex = 1; + pIdxInfo->aConstraintUsage[i].omit = 1; + } + if( (iPlan & 2)==0 + && pConstraint->iColumn==1 + && (pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT + || pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE) + ){ + iPlan |= 2; + iDistTerm = i; + } + if( (iPlan & 4)==0 + && pConstraint->iColumn==2 + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + iPlan |= 4; + pIdxInfo->aConstraintUsage[i].omit = 1; + iLangTerm = i; + } + } + if( iPlan & 2 ){ + pIdxInfo->aConstraintUsage[iDistTerm].argvIndex = 1+((iPlan&1)!=0); + } + if( iPlan & 4 ){ + int idx = 1; + if( iPlan & 1 ) idx++; + if( iPlan & 2 ) idx++; + pIdxInfo->aConstraintUsage[iLangTerm].argvIndex = idx; + } + pIdxInfo->idxNum = iPlan; + if( pIdxInfo->nOrderBy==1 + && pIdxInfo->aOrderBy[0].iColumn==1 + && pIdxInfo->aOrderBy[0].desc==0 + ){ + pIdxInfo->orderByConsumed = 1; + } + pIdxInfo->estimatedCost = (double)10000; + + return SQLITE_OK; +} + +/* +** The xUpdate() method. +** +** This implementation disallows DELETE and UPDATE. The only thing +** allowed is INSERT into the "command" column. +*/ +static int amatchUpdate( + sqlite3_vtab *pVTab, + int argc, + sqlite3_value **argv, + sqlite_int64 *pRowid +){ + amatch_vtab *p = (amatch_vtab*)pVTab; + const unsigned char *zCmd; + (void)pRowid; + if( argc==1 ){ + pVTab->zErrMsg = sqlite3_mprintf("DELETE from %s is not allowed", + p->zSelf); + return SQLITE_ERROR; + } + if( sqlite3_value_type(argv[0])!=SQLITE_NULL ){ + pVTab->zErrMsg = sqlite3_mprintf("UPDATE of %s is not allowed", + p->zSelf); + return SQLITE_ERROR; + } + if( sqlite3_value_type(argv[2+AMATCH_COL_WORD])!=SQLITE_NULL + || sqlite3_value_type(argv[2+AMATCH_COL_DISTANCE])!=SQLITE_NULL + || sqlite3_value_type(argv[2+AMATCH_COL_LANGUAGE])!=SQLITE_NULL + ){ + pVTab->zErrMsg = sqlite3_mprintf( + "INSERT INTO %s allowed for column [command] only", p->zSelf); + return SQLITE_ERROR; + } + zCmd = sqlite3_value_text(argv[2+AMATCH_COL_COMMAND]); + if( zCmd==0 ) return SQLITE_OK; + + return SQLITE_OK; +} + +/* +** A virtual table module that implements the "approximate_match". +*/ +static sqlite3_module amatchModule = { + 0, /* iVersion */ + amatchConnect, /* xCreate */ + amatchConnect, /* xConnect */ + amatchBestIndex, /* xBestIndex */ + amatchDisconnect, /* xDisconnect */ + amatchDisconnect, /* xDestroy */ + amatchOpen, /* xOpen - open a cursor */ + amatchClose, /* xClose - close a cursor */ + amatchFilter, /* xFilter - configure scan constraints */ + amatchNext, /* xNext - advance a cursor */ + amatchEof, /* xEof - check for end of scan */ + amatchColumn, /* xColumn - read data */ + amatchRowid, /* xRowid - read data */ + amatchUpdate, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0 /* xRollbackTo */ +}; + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** Register the amatch virtual table +*/ +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_amatch_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; /* Not used */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = sqlite3_create_module(db, "approximate_match", &amatchModule, 0); +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + return rc; +} diff --git a/components/external/SQLite-3.8.1/ext/misc/closure.c b/components/external/SQLite-3.8.1/ext/misc/closure.c new file mode 100644 index 0000000000000000000000000000000000000000..30c812d2201cd2d08a5d1a5c3464dbdfbed52fb1 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/misc/closure.c @@ -0,0 +1,958 @@ +/* +** 2013-04-16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code for a virtual table that finds the transitive +** closure of a parent/child relationship in a real table. The virtual +** table is called "transitive_closure". +** +** A transitive_closure virtual table is created like this: +** +** CREATE VIRTUAL TABLE x USING transitive_closure( +** tablename=, -- T +** idcolumn=, -- X +** parentcolumn= -- P +** ); +** +** When it is created, the new transitive_closure table may be supplied +** with default values for the name of a table T and columns T.X and T.P. +** The T.X and T.P columns must contain integers. The ideal case is for +** T.X to be the INTEGER PRIMARY KEY. The T.P column should reference +** the T.X column. The row referenced by T.P is the parent of the current row. +** +** The tablename, idcolumn, and parentcolumn supplied by the CREATE VIRTUAL +** TABLE statement may be overridden in individual queries by including +** terms like tablename='newtable', idcolumn='id2', or +** parentcolumn='parent3' in the WHERE clause of the query. +** +** For efficiency, it is essential that there be an index on the P column: +** +** CREATE Tidx1 ON T(P) +** +** Suppose a specific instance of the closure table is as follows: +** +** CREATE VIRTUAL TABLE ct1 USING transitive_closure( +** tablename='group', +** idcolumn='groupId', +** parentcolumn='parentId' +** ); +** +** Such an instance of the transitive_closure virtual table would be +** appropriate for walking a tree defined using a table like this, for example: +** +** CREATE TABLE group( +** groupId INTEGER PRIMARY KEY, +** parentId INTEGER REFERENCES group +** ); +** CREATE INDEX group_idx1 ON group(parentId); +** +** The group table above would presumably have other application-specific +** fields. The key point here is that rows of the group table form a +** tree. The purpose of the ct1 virtual table is to easily extract +** branches of that tree. +** +** Once it has been created, the ct1 virtual table can be queried +** as follows: +** +** SELECT * FROM element +** WHERE element.groupId IN (SELECT id FROM ct1 WHERE root=?1); +** +** The above query will return all elements that are part of group ?1 +** or children of group ?1 or grand-children of ?1 and so forth for all +** descendents of group ?1. The same query can be formulated as a join: +** +** SELECT element.* FROM element, ct1 +** WHERE element.groupid=ct1.id +** AND ct1.root=?1; +** +** The depth of the transitive_closure (the number of generations of +** parent/child relations to follow) can be limited by setting "depth" +** column in the WHERE clause. So, for example, the following query +** finds only children and grandchildren but no further descendents: +** +** SELECT element.* FROM element, ct1 +** WHERE element.groupid=ct1.id +** AND ct1.root=?1 +** AND ct1.depth<=2; +** +** The "ct1.depth<=2" term could be a strict equality "ct1.depth=2" in +** order to find only the grandchildren of ?1, not ?1 itself or the +** children of ?1. +** +** The root=?1 term must be supplied in WHERE clause or else the query +** of the ct1 virtual table will return an empty set. The tablename, +** idcolumn, and parentcolumn attributes can be overridden in the WHERE +** clause if desired. So, for example, the ct1 table could be repurposed +** to find ancestors rather than descendents by inverting the roles of +** the idcolumn and parentcolumn: +** +** SELECT element.* FROM element, ct1 +** WHERE element.groupid=ct1.id +** AND ct1.root=?1 +** AND ct1.idcolumn='parentId' +** AND ct1.parentcolumn='groupId'; +** +** Multiple calls to ct1 could be combined. For example, the following +** query finds all elements that "cousins" of groupId ?1. That is to say +** elements where the groupId is a grandchild of the grandparent of ?1. +** (This definition of "cousins" also includes siblings and self.) +** +** SELECT element.* FROM element, ct1 +** WHERE element.groupId=ct1.id +** AND ct1.depth=2 +** AND ct1.root IN (SELECT id FROM ct1 +** WHERE root=?1 +** AND depth=2 +** AND idcolumn='parentId' +** AND parentcolumn='groupId'); +** +** In our example, the group.groupId column is unique and thus the +** subquery will return exactly one row. For that reason, the IN +** operator could be replaced by "=" to get the same result. But +** in the general case where the idcolumn is not unique, an IN operator +** would be required for this kind of query. +** +** Note that because the tablename, idcolumn, and parentcolumn can +** all be specified in the query, it is possible for an application +** to define a single transitive_closure virtual table for use on lots +** of different hierarchy tables. One might say: +** +** CREATE VIRTUAL TABLE temp.closure USING transitive_closure; +** +** As each database connection is being opened. Then the application +** would always have a "closure" virtual table handy to use for querying. +** +** SELECT element.* FROM element, closure +** WHERE element.groupid=ct1.id +** AND closure.root=?1 +** AND closure.tablename='group' +** AND closure.idname='groupId' +** AND closure.parentname='parentId'; +** +** See the documentation at http://www.sqlite.org/loadext.html for information +** on how to compile and use loadable extensions such as this one. +*/ +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 +#include +#include +#include +#include +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Forward declaration of objects used by this implementation +*/ +typedef struct closure_vtab closure_vtab; +typedef struct closure_cursor closure_cursor; +typedef struct closure_queue closure_queue; +typedef struct closure_avl closure_avl; + +/***************************************************************************** +** AVL Tree implementation +*/ +/* +** Objects that want to be members of the AVL tree should embedded an +** instance of this structure. +*/ +struct closure_avl { + sqlite3_int64 id; /* Id of this entry in the table */ + int iGeneration; /* Which generation is this entry part of */ + closure_avl *pList; /* A linked list of nodes */ + closure_avl *pBefore; /* Other elements less than id */ + closure_avl *pAfter; /* Other elements greater than id */ + closure_avl *pUp; /* Parent element */ + short int height; /* Height of this node. Leaf==1 */ + short int imbalance; /* Height difference between pBefore and pAfter */ +}; + +/* Recompute the closure_avl.height and closure_avl.imbalance fields for p. +** Assume that the children of p have correct heights. +*/ +static void closureAvlRecomputeHeight(closure_avl *p){ + short int hBefore = p->pBefore ? p->pBefore->height : 0; + short int hAfter = p->pAfter ? p->pAfter->height : 0; + p->imbalance = hBefore - hAfter; /* -: pAfter higher. +: pBefore higher */ + p->height = (hBefore>hAfter ? hBefore : hAfter)+1; +} + +/* +** P B +** / \ / \ +** B Z ==> X P +** / \ / \ +** X Y Y Z +** +*/ +static closure_avl *closureAvlRotateBefore(closure_avl *pP){ + closure_avl *pB = pP->pBefore; + closure_avl *pY = pB->pAfter; + pB->pUp = pP->pUp; + pB->pAfter = pP; + pP->pUp = pB; + pP->pBefore = pY; + if( pY ) pY->pUp = pP; + closureAvlRecomputeHeight(pP); + closureAvlRecomputeHeight(pB); + return pB; +} + +/* +** P A +** / \ / \ +** X A ==> P Z +** / \ / \ +** Y Z X Y +** +*/ +static closure_avl *closureAvlRotateAfter(closure_avl *pP){ + closure_avl *pA = pP->pAfter; + closure_avl *pY = pA->pBefore; + pA->pUp = pP->pUp; + pA->pBefore = pP; + pP->pUp = pA; + pP->pAfter = pY; + if( pY ) pY->pUp = pP; + closureAvlRecomputeHeight(pP); + closureAvlRecomputeHeight(pA); + return pA; +} + +/* +** Return a pointer to the pBefore or pAfter pointer in the parent +** of p that points to p. Or if p is the root node, return pp. +*/ +static closure_avl **closureAvlFromPtr(closure_avl *p, closure_avl **pp){ + closure_avl *pUp = p->pUp; + if( pUp==0 ) return pp; + if( pUp->pAfter==p ) return &pUp->pAfter; + return &pUp->pBefore; +} + +/* +** Rebalance all nodes starting with p and working up to the root. +** Return the new root. +*/ +static closure_avl *closureAvlBalance(closure_avl *p){ + closure_avl *pTop = p; + closure_avl **pp; + while( p ){ + closureAvlRecomputeHeight(p); + if( p->imbalance>=2 ){ + closure_avl *pB = p->pBefore; + if( pB->imbalance<0 ) p->pBefore = closureAvlRotateAfter(pB); + pp = closureAvlFromPtr(p,&p); + p = *pp = closureAvlRotateBefore(p); + }else if( p->imbalance<=(-2) ){ + closure_avl *pA = p->pAfter; + if( pA->imbalance>0 ) p->pAfter = closureAvlRotateBefore(pA); + pp = closureAvlFromPtr(p,&p); + p = *pp = closureAvlRotateAfter(p); + } + pTop = p; + p = p->pUp; + } + return pTop; +} + +/* Search the tree rooted at p for an entry with id. Return a pointer +** to the entry or return NULL. +*/ +static closure_avl *closureAvlSearch(closure_avl *p, sqlite3_int64 id){ + while( p && id!=p->id ){ + p = (idid) ? p->pBefore : p->pAfter; + } + return p; +} + +/* Find the first node (the one with the smallest key). +*/ +static closure_avl *closureAvlFirst(closure_avl *p){ + if( p ) while( p->pBefore ) p = p->pBefore; + return p; +} + +/* Return the node with the next larger key after p. +*/ +closure_avl *closureAvlNext(closure_avl *p){ + closure_avl *pPrev = 0; + while( p && p->pAfter==pPrev ){ + pPrev = p; + p = p->pUp; + } + if( p && pPrev==0 ){ + p = closureAvlFirst(p->pAfter); + } + return p; +} + +/* Insert a new node pNew. Return NULL on success. If the key is not +** unique, then do not perform the insert but instead leave pNew unchanged +** and return a pointer to an existing node with the same key. +*/ +static closure_avl *closureAvlInsert( + closure_avl **ppHead, /* Head of the tree */ + closure_avl *pNew /* New node to be inserted */ +){ + closure_avl *p = *ppHead; + if( p==0 ){ + p = pNew; + pNew->pUp = 0; + }else{ + while( p ){ + if( pNew->idid ){ + if( p->pBefore ){ + p = p->pBefore; + }else{ + p->pBefore = pNew; + pNew->pUp = p; + break; + } + }else if( pNew->id>p->id ){ + if( p->pAfter ){ + p = p->pAfter; + }else{ + p->pAfter = pNew; + pNew->pUp = p; + break; + } + }else{ + return p; + } + } + } + pNew->pBefore = 0; + pNew->pAfter = 0; + pNew->height = 1; + pNew->imbalance = 0; + *ppHead = closureAvlBalance(p); + return 0; +} + +/* Walk the tree can call xDestroy on each node +*/ +static void closureAvlDestroy(closure_avl *p, void (*xDestroy)(closure_avl*)){ + if( p ){ + closureAvlDestroy(p->pBefore, xDestroy); + closureAvlDestroy(p->pAfter, xDestroy); + xDestroy(p); + } +} +/* +** End of the AVL Tree implementation +******************************************************************************/ + +/* +** A closure virtual-table object +*/ +struct closure_vtab { + sqlite3_vtab base; /* Base class - must be first */ + char *zDb; /* Name of database. (ex: "main") */ + char *zSelf; /* Name of this virtual table */ + char *zTableName; /* Name of table holding parent/child relation */ + char *zIdColumn; /* Name of ID column of zTableName */ + char *zParentColumn; /* Name of PARENT column in zTableName */ + sqlite3 *db; /* The database connection */ + int nCursor; /* Number of pending cursors */ +}; + +/* A closure cursor object */ +struct closure_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + closure_vtab *pVtab; /* The virtual table this cursor belongs to */ + char *zTableName; /* Name of table holding parent/child relation */ + char *zIdColumn; /* Name of ID column of zTableName */ + char *zParentColumn; /* Name of PARENT column in zTableName */ + closure_avl *pCurrent; /* Current element of output */ + closure_avl *pClosure; /* The complete closure tree */ +}; + +/* A queue of AVL nodes */ +struct closure_queue { + closure_avl *pFirst; /* Oldest node on the queue */ + closure_avl *pLast; /* Youngest node on the queue */ +}; + +/* +** Add a node to the end of the queue +*/ +static void queuePush(closure_queue *pQueue, closure_avl *pNode){ + pNode->pList = 0; + if( pQueue->pLast ){ + pQueue->pLast->pList = pNode; + }else{ + pQueue->pFirst = pNode; + } + pQueue->pLast = pNode; +} + +/* +** Extract the oldest element (the front element) from the queue. +*/ +static closure_avl *queuePull(closure_queue *pQueue){ + closure_avl *p = pQueue->pFirst; + if( p ){ + pQueue->pFirst = p->pList; + if( pQueue->pFirst==0 ) pQueue->pLast = 0; + } + return p; +} + +/* +** This function converts an SQL quoted string into an unquoted string +** and returns a pointer to a buffer allocated using sqlite3_malloc() +** containing the result. The caller should eventually free this buffer +** using sqlite3_free. +** +** Examples: +** +** "abc" becomes abc +** 'xyz' becomes xyz +** [pqr] becomes pqr +** `mno` becomes mno +*/ +static char *closureDequote(const char *zIn){ + int nIn; /* Size of input string, in bytes */ + char *zOut; /* Output (dequoted) string */ + + nIn = (int)strlen(zIn); + zOut = sqlite3_malloc(nIn+1); + if( zOut ){ + char q = zIn[0]; /* Quote character (if any ) */ + + if( q!='[' && q!= '\'' && q!='"' && q!='`' ){ + memcpy(zOut, zIn, nIn+1); + }else{ + int iOut = 0; /* Index of next byte to write to output */ + int iIn; /* Index of next byte to read from input */ + + if( q=='[' ) q = ']'; + for(iIn=1; iInzDb); + sqlite3_free(p->zSelf); + sqlite3_free(p->zTableName); + sqlite3_free(p->zIdColumn); + sqlite3_free(p->zParentColumn); + memset(p, 0, sizeof(*p)); + sqlite3_free(p); + } +} + +/* +** xDisconnect/xDestroy method for the closure module. +*/ +static int closureDisconnect(sqlite3_vtab *pVtab){ + closure_vtab *p = (closure_vtab*)pVtab; + assert( p->nCursor==0 ); + closureFree(p); + return SQLITE_OK; +} + +/* +** Check to see if the argument is of the form: +** +** KEY = VALUE +** +** If it is, return a pointer to the first character of VALUE. +** If not, return NULL. Spaces around the = are ignored. +*/ +static const char *closureValueOfKey(const char *zKey, const char *zStr){ + int nKey = (int)strlen(zKey); + int nStr = (int)strlen(zStr); + int i; + if( nStr module name ("transitive_closure") +** argv[1] -> database name +** argv[2] -> table name +** argv[3...] -> arguments +*/ +static int closureConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int rc = SQLITE_OK; /* Return code */ + closure_vtab *pNew = 0; /* New virtual table */ + const char *zDb = argv[1]; + const char *zVal; + int i; + + (void)pAux; + *ppVtab = 0; + pNew = sqlite3_malloc( sizeof(*pNew) ); + if( pNew==0 ) return SQLITE_NOMEM; + rc = SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + pNew->db = db; + pNew->zDb = sqlite3_mprintf("%s", zDb); + if( pNew->zDb==0 ) goto closureConnectError; + pNew->zSelf = sqlite3_mprintf("%s", argv[2]); + if( pNew->zSelf==0 ) goto closureConnectError; + for(i=3; izTableName); + pNew->zTableName = closureDequote(zVal); + if( pNew->zTableName==0 ) goto closureConnectError; + continue; + } + zVal = closureValueOfKey("idcolumn", argv[i]); + if( zVal ){ + sqlite3_free(pNew->zIdColumn); + pNew->zIdColumn = closureDequote(zVal); + if( pNew->zIdColumn==0 ) goto closureConnectError; + continue; + } + zVal = closureValueOfKey("parentcolumn", argv[i]); + if( zVal ){ + sqlite3_free(pNew->zParentColumn); + pNew->zParentColumn = closureDequote(zVal); + if( pNew->zParentColumn==0 ) goto closureConnectError; + continue; + } + *pzErr = sqlite3_mprintf("unrecognized argument: [%s]\n", argv[i]); + closureFree(pNew); + *ppVtab = 0; + return SQLITE_ERROR; + } + rc = sqlite3_declare_vtab(db, + "CREATE TABLE x(id,depth,root HIDDEN,tablename HIDDEN," + "idcolumn HIDDEN,parentcolumn HIDDEN)" + ); +#define CLOSURE_COL_ID 0 +#define CLOSURE_COL_DEPTH 1 +#define CLOSURE_COL_ROOT 2 +#define CLOSURE_COL_TABLENAME 3 +#define CLOSURE_COL_IDCOLUMN 4 +#define CLOSURE_COL_PARENTCOLUMN 5 + if( rc!=SQLITE_OK ){ + closureFree(pNew); + } + *ppVtab = &pNew->base; + return rc; + +closureConnectError: + closureFree(pNew); + return rc; +} + +/* +** Open a new closure cursor. +*/ +static int closureOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + closure_vtab *p = (closure_vtab*)pVTab; + closure_cursor *pCur; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + pCur->pVtab = p; + *ppCursor = &pCur->base; + p->nCursor++; + return SQLITE_OK; +} + +/* +** Free up all the memory allocated by a cursor. Set it rLimit to 0 +** to indicate that it is at EOF. +*/ +static void closureClearCursor(closure_cursor *pCur){ + closureAvlDestroy(pCur->pClosure, (void(*)(closure_avl*))sqlite3_free); + sqlite3_free(pCur->zTableName); + sqlite3_free(pCur->zIdColumn); + sqlite3_free(pCur->zParentColumn); + pCur->zTableName = 0; + pCur->zIdColumn = 0; + pCur->zParentColumn = 0; + pCur->pCurrent = 0; + pCur->pClosure = 0; +} + +/* +** Close a closure cursor. +*/ +static int closureClose(sqlite3_vtab_cursor *cur){ + closure_cursor *pCur = (closure_cursor *)cur; + closureClearCursor(pCur); + pCur->pVtab->nCursor--; + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Advance a cursor to its next row of output +*/ +static int closureNext(sqlite3_vtab_cursor *cur){ + closure_cursor *pCur = (closure_cursor*)cur; + pCur->pCurrent = closureAvlNext(pCur->pCurrent); + return SQLITE_OK; +} + +/* +** Allocate and insert a node +*/ +static int closureInsertNode( + closure_queue *pQueue, /* Add new node to this queue */ + closure_cursor *pCur, /* The cursor into which to add the node */ + sqlite3_int64 id, /* The node ID */ + int iGeneration /* The generation number for this node */ +){ + closure_avl *pNew = sqlite3_malloc( sizeof(*pNew) ); + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + pNew->id = id; + pNew->iGeneration = iGeneration; + closureAvlInsert(&pCur->pClosure, pNew); + queuePush(pQueue, pNew); + return SQLITE_OK; +} + +/* +** Called to "rewind" a cursor back to the beginning so that +** it starts its output over again. Always called at least once +** prior to any closureColumn, closureRowid, or closureEof call. +** +** This routine actually computes the closure. +** +** See the comment at the beginning of closureBestIndex() for a +** description of the meaning of idxNum. The idxStr parameter is +** not used. +*/ +static int closureFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + closure_cursor *pCur = (closure_cursor *)pVtabCursor; + closure_vtab *pVtab = pCur->pVtab; + sqlite3_int64 iRoot; + int mxGen = 999999999; + char *zSql; + sqlite3_stmt *pStmt; + closure_avl *pAvl; + int rc = SQLITE_OK; + const char *zTableName = pVtab->zTableName; + const char *zIdColumn = pVtab->zIdColumn; + const char *zParentColumn = pVtab->zParentColumn; + closure_queue sQueue; + + (void)idxStr; /* Unused parameter */ + (void)argc; /* Unused parameter */ + closureClearCursor(pCur); + memset(&sQueue, 0, sizeof(sQueue)); + if( (idxNum & 1)==0 ){ + /* No root=$root in the WHERE clause. Return an empty set */ + return SQLITE_OK; + } + iRoot = sqlite3_value_int64(argv[0]); + if( (idxNum & 0x000f0)!=0 ){ + mxGen = sqlite3_value_int(argv[(idxNum>>4)&0x0f]); + if( (idxNum & 0x00002)!=0 ) mxGen--; + } + if( (idxNum & 0x00f00)!=0 ){ + zTableName = (const char*)sqlite3_value_text(argv[(idxNum>>8)&0x0f]); + pCur->zTableName = sqlite3_mprintf("%s", zTableName); + } + if( (idxNum & 0x0f000)!=0 ){ + zIdColumn = (const char*)sqlite3_value_text(argv[(idxNum>>12)&0x0f]); + pCur->zIdColumn = sqlite3_mprintf("%s", zIdColumn); + } + if( (idxNum & 0x0f0000)!=0 ){ + zParentColumn = (const char*)sqlite3_value_text(argv[(idxNum>>16)&0x0f]); + pCur->zParentColumn = sqlite3_mprintf("%s", zParentColumn); + } + + zSql = sqlite3_mprintf( + "SELECT \"%w\".\"%w\" FROM \"%w\" WHERE \"%w\".\"%w\"=?1", + zTableName, zIdColumn, zTableName, zTableName, zParentColumn); + if( zSql==0 ){ + return SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare_v2(pVtab->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + if( rc ){ + sqlite3_free(pVtab->base.zErrMsg); + pVtab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pVtab->db)); + return rc; + } + } + if( rc==SQLITE_OK ){ + rc = closureInsertNode(&sQueue, pCur, iRoot, 0); + } + while( (pAvl = queuePull(&sQueue))!=0 ){ + if( pAvl->iGeneration>=mxGen ) continue; + sqlite3_bind_int64(pStmt, 1, pAvl->id); + while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ + if( sqlite3_column_type(pStmt,0)==SQLITE_INTEGER ){ + sqlite3_int64 iNew = sqlite3_column_int64(pStmt, 0); + if( closureAvlSearch(pCur->pClosure, iNew)==0 ){ + rc = closureInsertNode(&sQueue, pCur, iNew, pAvl->iGeneration+1); + } + } + } + sqlite3_reset(pStmt); + } + sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ){ + pCur->pCurrent = closureAvlFirst(pCur->pClosure); + } + + return rc; +} + +/* +** Only the word and distance columns have values. All other columns +** return NULL +*/ +static int closureColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + closure_cursor *pCur = (closure_cursor*)cur; + switch( i ){ + case CLOSURE_COL_ID: { + sqlite3_result_int64(ctx, pCur->pCurrent->id); + break; + } + case CLOSURE_COL_DEPTH: { + sqlite3_result_int(ctx, pCur->pCurrent->iGeneration); + break; + } + case CLOSURE_COL_ROOT: { + sqlite3_result_null(ctx); + break; + } + case CLOSURE_COL_TABLENAME: { + sqlite3_result_text(ctx, + pCur->zTableName ? pCur->zTableName : pCur->pVtab->zTableName, + -1, SQLITE_TRANSIENT); + break; + } + case CLOSURE_COL_IDCOLUMN: { + sqlite3_result_text(ctx, + pCur->zIdColumn ? pCur->zIdColumn : pCur->pVtab->zIdColumn, + -1, SQLITE_TRANSIENT); + break; + } + case CLOSURE_COL_PARENTCOLUMN: { + sqlite3_result_text(ctx, + pCur->zParentColumn ? pCur->zParentColumn : pCur->pVtab->zParentColumn, + -1, SQLITE_TRANSIENT); + break; + } + } + return SQLITE_OK; +} + +/* +** The rowid. For the closure table, this is the same as the "id" column. +*/ +static int closureRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + closure_cursor *pCur = (closure_cursor*)cur; + *pRowid = pCur->pCurrent->id; + return SQLITE_OK; +} + +/* +** EOF indicator +*/ +static int closureEof(sqlite3_vtab_cursor *cur){ + closure_cursor *pCur = (closure_cursor*)cur; + return pCur->pCurrent==0; +} + +/* +** Search for terms of these forms: +** +** (A) root = $root +** (B1) depth < $depth +** (B2) depth <= $depth +** (B3) depth = $depth +** (C) tablename = $tablename +** (D) idcolumn = $idcolumn +** (E) parentcolumn = $parentcolumn +** +** +** +** idxNum meaning +** ---------- ------------------------------------------------------ +** 0x00000001 Term of the form (A) found +** 0x00000002 The term of bit-2 is like (B1) +** 0x000000f0 Index in filter.argv[] of $depth. 0 if not used. +** 0x00000f00 Index in filter.argv[] of $tablename. 0 if not used. +** 0x0000f000 Index in filter.argv[] of $idcolumn. 0 if not used +** 0x000f0000 Index in filter.argv[] of $parentcolumn. 0 if not used. +** +** There must be a term of type (A). If there is not, then the index type +** is 0 and the query will return an empty set. +*/ +static int closureBestIndex( + sqlite3_vtab *pTab, /* The virtual table */ + sqlite3_index_info *pIdxInfo /* Information about the query */ +){ + int iPlan = 0; + int i; + int idx = 1; + int seenMatch = 0; + const struct sqlite3_index_constraint *pConstraint; + closure_vtab *pVtab = (closure_vtab*)pTab; + double rCost = 10000000.0; + + pConstraint = pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pConstraint++){ + if( pConstraint->iColumn==CLOSURE_COL_ROOT + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + seenMatch = 1; + } + if( pConstraint->usable==0 ) continue; + if( (iPlan & 1)==0 + && pConstraint->iColumn==CLOSURE_COL_ROOT + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + iPlan |= 1; + pIdxInfo->aConstraintUsage[i].argvIndex = 1; + pIdxInfo->aConstraintUsage[i].omit = 1; + rCost /= 100.0; + } + if( (iPlan & 0x0000f0)==0 + && pConstraint->iColumn==CLOSURE_COL_DEPTH + && (pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT + || pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE + || pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ) + ){ + iPlan |= idx<<4; + pIdxInfo->aConstraintUsage[i].argvIndex = ++idx; + if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT ) iPlan |= 0x000002; + rCost /= 5.0; + } + if( (iPlan & 0x000f00)==0 + && pConstraint->iColumn==CLOSURE_COL_TABLENAME + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + iPlan |= idx<<8; + pIdxInfo->aConstraintUsage[i].argvIndex = ++idx; + pIdxInfo->aConstraintUsage[i].omit = 1; + rCost /= 5.0; + } + if( (iPlan & 0x00f000)==0 + && pConstraint->iColumn==CLOSURE_COL_IDCOLUMN + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + iPlan |= idx<<12; + pIdxInfo->aConstraintUsage[i].argvIndex = ++idx; + pIdxInfo->aConstraintUsage[i].omit = 1; + } + if( (iPlan & 0x0f0000)==0 + && pConstraint->iColumn==CLOSURE_COL_PARENTCOLUMN + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + iPlan |= idx<<16; + pIdxInfo->aConstraintUsage[i].argvIndex = ++idx; + pIdxInfo->aConstraintUsage[i].omit = 1; + } + } + if( (pVtab->zTableName==0 && (iPlan & 0x000f00)==0) + || (pVtab->zIdColumn==0 && (iPlan & 0x00f000)==0) + || (pVtab->zParentColumn==0 && (iPlan & 0x0f0000)==0) + ){ + /* All of tablename, idcolumn, and parentcolumn must be specified + ** in either the CREATE VIRTUAL TABLE or in the WHERE clause constraints + ** or else the result is an empty set. */ + iPlan = 0; + } + pIdxInfo->idxNum = iPlan; + if( pIdxInfo->nOrderBy==1 + && pIdxInfo->aOrderBy[0].iColumn==CLOSURE_COL_ID + && pIdxInfo->aOrderBy[0].desc==0 + ){ + pIdxInfo->orderByConsumed = 1; + } + if( seenMatch && (iPlan&1)==0 ) rCost *= 1e30; + pIdxInfo->estimatedCost = rCost; + + return SQLITE_OK; +} + +/* +** A virtual table module that implements the "transitive_closure". +*/ +static sqlite3_module closureModule = { + 0, /* iVersion */ + closureConnect, /* xCreate */ + closureConnect, /* xConnect */ + closureBestIndex, /* xBestIndex */ + closureDisconnect, /* xDisconnect */ + closureDisconnect, /* xDestroy */ + closureOpen, /* xOpen - open a cursor */ + closureClose, /* xClose - close a cursor */ + closureFilter, /* xFilter - configure scan constraints */ + closureNext, /* xNext - advance a cursor */ + closureEof, /* xEof - check for end of scan */ + closureColumn, /* xColumn - read data */ + closureRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0 /* xRollbackTo */ +}; + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** Register the closure virtual table +*/ +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_closure_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = sqlite3_create_module(db, "transitive_closure", &closureModule, 0); +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + return rc; +} diff --git a/components/external/SQLite-3.8.1/ext/misc/fuzzer.c b/components/external/SQLite-3.8.1/ext/misc/fuzzer.c new file mode 100644 index 0000000000000000000000000000000000000000..fe41cda8c24ae3dfcd58b01f46fe075fbbcd00f9 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/misc/fuzzer.c @@ -0,0 +1,1184 @@ +/* +** 2011 March 24 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** Code for a demonstration virtual table that generates variations +** on an input word at increasing edit distances from the original. +** +** A fuzzer virtual table is created like this: +** +** CREATE VIRTUAL TABLE f USING fuzzer(); +** +** When it is created, the new fuzzer table must be supplied with the +** name of a "fuzzer data table", which must reside in the same database +** file as the new fuzzer table. The fuzzer data table contains the various +** transformations and their costs that the fuzzer logic uses to generate +** variations. +** +** The fuzzer data table must contain exactly four columns (more precisely, +** the statement "SELECT * FROM " must return records +** that consist of four columns). It does not matter what the columns are +** named. +** +** Each row in the fuzzer data table represents a single character +** transformation. The left most column of the row (column 0) contains an +** integer value - the identifier of the ruleset to which the transformation +** rule belongs (see "MULTIPLE RULE SETS" below). The second column of the +** row (column 0) contains the input character or characters. The third +** column contains the output character or characters. And the fourth column +** contains the integer cost of making the transformation. For example: +** +** CREATE TABLE f_data(ruleset, cFrom, cTo, Cost); +** INSERT INTO f_data(ruleset, cFrom, cTo, Cost) VALUES(0, '', 'a', 100); +** INSERT INTO f_data(ruleset, cFrom, cTo, Cost) VALUES(0, 'b', '', 87); +** INSERT INTO f_data(ruleset, cFrom, cTo, Cost) VALUES(0, 'o', 'oe', 38); +** INSERT INTO f_data(ruleset, cFrom, cTo, Cost) VALUES(0, 'oe', 'o', 40); +** +** The first row inserted into the fuzzer data table by the SQL script +** above indicates that the cost of inserting a letter 'a' is 100. (All +** costs are integers. We recommend that costs be scaled so that the +** average cost is around 100.) The second INSERT statement creates a rule +** saying that the cost of deleting a single letter 'b' is 87. The third +** and fourth INSERT statements mean that the cost of transforming a +** single letter "o" into the two-letter sequence "oe" is 38 and that the +** cost of transforming "oe" back into "o" is 40. +** +** The contents of the fuzzer data table are loaded into main memory when +** a fuzzer table is first created, and may be internally reloaded by the +** system at any subsequent time. Therefore, the fuzzer data table should be +** populated before the fuzzer table is created and not modified thereafter. +** If you do need to modify the contents of the fuzzer data table, it is +** recommended that the associated fuzzer table be dropped, the fuzzer data +** table edited, and the fuzzer table recreated within a single transaction. +** Alternatively, the fuzzer data table can be edited then the database +** connection can be closed and reopened. +** +** Once it has been created, the fuzzer table can be queried as follows: +** +** SELECT word, distance FROM f +** WHERE word MATCH 'abcdefg' +** AND distance<200; +** +** This first query outputs the string "abcdefg" and all strings that +** can be derived from that string by appling the specified transformations. +** The strings are output together with their total transformation cost +** (called "distance") and appear in order of increasing cost. No string +** is output more than once. If there are multiple ways to transform the +** target string into the output string then the lowest cost transform is +** the one that is returned. In the example, the search is limited to +** strings with a total distance of less than 200. +** +** The fuzzer is a read-only table. Any attempt to DELETE, INSERT, or +** UPDATE on a fuzzer table will throw an error. +** +** It is important to put some kind of a limit on the fuzzer output. This +** can be either in the form of a LIMIT clause at the end of the query, +** or better, a "distance +#include +#include +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Forward declaration of objects used by this implementation +*/ +typedef struct fuzzer_vtab fuzzer_vtab; +typedef struct fuzzer_cursor fuzzer_cursor; +typedef struct fuzzer_rule fuzzer_rule; +typedef struct fuzzer_seen fuzzer_seen; +typedef struct fuzzer_stem fuzzer_stem; + +/* +** Various types. +** +** fuzzer_cost is the "cost" of an edit operation. +** +** fuzzer_len is the length of a matching string. +** +** fuzzer_ruleid is an ruleset identifier. +*/ +typedef int fuzzer_cost; +typedef signed char fuzzer_len; +typedef int fuzzer_ruleid; + +/* +** Limits +*/ +#define FUZZER_MX_LENGTH 50 /* Maximum length of a rule string */ +#define FUZZER_MX_RULEID 2147483647 /* Maximum rule ID */ +#define FUZZER_MX_COST 1000 /* Maximum single-rule cost */ +#define FUZZER_MX_OUTPUT_LENGTH 100 /* Maximum length of an output string */ + + +/* +** Each transformation rule is stored as an instance of this object. +** All rules are kept on a linked list sorted by rCost. +*/ +struct fuzzer_rule { + fuzzer_rule *pNext; /* Next rule in order of increasing rCost */ + char *zFrom; /* Transform from */ + fuzzer_cost rCost; /* Cost of this transformation */ + fuzzer_len nFrom, nTo; /* Length of the zFrom and zTo strings */ + fuzzer_ruleid iRuleset; /* The rule set to which this rule belongs */ + char zTo[4]; /* Transform to (extra space appended) */ +}; + +/* +** A stem object is used to generate variants. It is also used to record +** previously generated outputs. +** +** Every stem is added to a hash table as it is output. Generation of +** duplicate stems is suppressed. +** +** Active stems (those that might generate new outputs) are kepts on a linked +** list sorted by increasing cost. The cost is the sum of rBaseCost and +** pRule->rCost. +*/ +struct fuzzer_stem { + char *zBasis; /* Word being fuzzed */ + const fuzzer_rule *pRule; /* Current rule to apply */ + fuzzer_stem *pNext; /* Next stem in rCost order */ + fuzzer_stem *pHash; /* Next stem with same hash on zBasis */ + fuzzer_cost rBaseCost; /* Base cost of getting to zBasis */ + fuzzer_cost rCostX; /* Precomputed rBaseCost + pRule->rCost */ + fuzzer_len nBasis; /* Length of the zBasis string */ + fuzzer_len n; /* Apply pRule at this character offset */ +}; + +/* +** A fuzzer virtual-table object +*/ +struct fuzzer_vtab { + sqlite3_vtab base; /* Base class - must be first */ + char *zClassName; /* Name of this class. Default: "fuzzer" */ + fuzzer_rule *pRule; /* All active rules in this fuzzer */ + int nCursor; /* Number of active cursors */ +}; + +#define FUZZER_HASH 4001 /* Hash table size */ +#define FUZZER_NQUEUE 20 /* Number of slots on the stem queue */ + +/* A fuzzer cursor object */ +struct fuzzer_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + sqlite3_int64 iRowid; /* The rowid of the current word */ + fuzzer_vtab *pVtab; /* The virtual table this cursor belongs to */ + fuzzer_cost rLimit; /* Maximum cost of any term */ + fuzzer_stem *pStem; /* Stem with smallest rCostX */ + fuzzer_stem *pDone; /* Stems already processed to completion */ + fuzzer_stem *aQueue[FUZZER_NQUEUE]; /* Queue of stems with higher rCostX */ + int mxQueue; /* Largest used index in aQueue[] */ + char *zBuf; /* Temporary use buffer */ + int nBuf; /* Bytes allocated for zBuf */ + int nStem; /* Number of stems allocated */ + int iRuleset; /* Only process rules from this ruleset */ + fuzzer_rule nullRule; /* Null rule used first */ + fuzzer_stem *apHash[FUZZER_HASH]; /* Hash of previously generated terms */ +}; + +/* +** The two input rule lists are both sorted in order of increasing +** cost. Merge them together into a single list, sorted by cost, and +** return a pointer to the head of that list. +*/ +static fuzzer_rule *fuzzerMergeRules(fuzzer_rule *pA, fuzzer_rule *pB){ + fuzzer_rule head; + fuzzer_rule *pTail; + + pTail = &head; + while( pA && pB ){ + if( pA->rCost<=pB->rCost ){ + pTail->pNext = pA; + pTail = pA; + pA = pA->pNext; + }else{ + pTail->pNext = pB; + pTail = pB; + pB = pB->pNext; + } + } + if( pA==0 ){ + pTail->pNext = pB; + }else{ + pTail->pNext = pA; + } + return head.pNext; +} + +/* +** Statement pStmt currently points to a row in the fuzzer data table. This +** function allocates and populates a fuzzer_rule structure according to +** the content of the row. +** +** If successful, *ppRule is set to point to the new object and SQLITE_OK +** is returned. Otherwise, *ppRule is zeroed, *pzErr may be set to point +** to an error message and an SQLite error code returned. +*/ +static int fuzzerLoadOneRule( + fuzzer_vtab *p, /* Fuzzer virtual table handle */ + sqlite3_stmt *pStmt, /* Base rule on statements current row */ + fuzzer_rule **ppRule, /* OUT: New rule object */ + char **pzErr /* OUT: Error message */ +){ + sqlite3_int64 iRuleset = sqlite3_column_int64(pStmt, 0); + const char *zFrom = (const char *)sqlite3_column_text(pStmt, 1); + const char *zTo = (const char *)sqlite3_column_text(pStmt, 2); + int nCost = sqlite3_column_int(pStmt, 3); + + int rc = SQLITE_OK; /* Return code */ + int nFrom; /* Size of string zFrom, in bytes */ + int nTo; /* Size of string zTo, in bytes */ + fuzzer_rule *pRule = 0; /* New rule object to return */ + + if( zFrom==0 ) zFrom = ""; + if( zTo==0 ) zTo = ""; + nFrom = (int)strlen(zFrom); + nTo = (int)strlen(zTo); + + /* Silently ignore null transformations */ + if( strcmp(zFrom, zTo)==0 ){ + *ppRule = 0; + return SQLITE_OK; + } + + if( nCost<=0 || nCost>FUZZER_MX_COST ){ + *pzErr = sqlite3_mprintf("%s: cost must be between 1 and %d", + p->zClassName, FUZZER_MX_COST + ); + rc = SQLITE_ERROR; + }else + if( nFrom>FUZZER_MX_LENGTH || nTo>FUZZER_MX_LENGTH ){ + *pzErr = sqlite3_mprintf("%s: maximum string length is %d", + p->zClassName, FUZZER_MX_LENGTH + ); + rc = SQLITE_ERROR; + }else + if( iRuleset<0 || iRuleset>FUZZER_MX_RULEID ){ + *pzErr = sqlite3_mprintf("%s: ruleset must be between 0 and %d", + p->zClassName, FUZZER_MX_RULEID + ); + rc = SQLITE_ERROR; + }else{ + + pRule = sqlite3_malloc( sizeof(*pRule) + nFrom + nTo ); + if( pRule==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pRule, 0, sizeof(*pRule)); + pRule->zFrom = &pRule->zTo[nTo+1]; + pRule->nFrom = nFrom; + memcpy(pRule->zFrom, zFrom, nFrom+1); + memcpy(pRule->zTo, zTo, nTo+1); + pRule->nTo = nTo; + pRule->rCost = nCost; + pRule->iRuleset = (int)iRuleset; + } + } + + *ppRule = pRule; + return rc; +} + +/* +** Load the content of the fuzzer data table into memory. +*/ +static int fuzzerLoadRules( + sqlite3 *db, /* Database handle */ + fuzzer_vtab *p, /* Virtual fuzzer table to configure */ + const char *zDb, /* Database containing rules data */ + const char *zData, /* Table containing rules data */ + char **pzErr /* OUT: Error message */ +){ + int rc = SQLITE_OK; /* Return code */ + char *zSql; /* SELECT used to read from rules table */ + fuzzer_rule *pHead = 0; + + zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zData); + if( zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + int rc2; /* finalize() return code */ + sqlite3_stmt *pStmt = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + *pzErr = sqlite3_mprintf("%s: %s", p->zClassName, sqlite3_errmsg(db)); + }else if( sqlite3_column_count(pStmt)!=4 ){ + *pzErr = sqlite3_mprintf("%s: %s has %d columns, expected 4", + p->zClassName, zData, sqlite3_column_count(pStmt) + ); + rc = SQLITE_ERROR; + }else{ + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ + fuzzer_rule *pRule = 0; + rc = fuzzerLoadOneRule(p, pStmt, &pRule, pzErr); + if( pRule ){ + pRule->pNext = pHead; + pHead = pRule; + } + } + } + rc2 = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ) rc = rc2; + } + sqlite3_free(zSql); + + /* All rules are now in a singly linked list starting at pHead. This + ** block sorts them by cost and then sets fuzzer_vtab.pRule to point to + ** point to the head of the sorted list. + */ + if( rc==SQLITE_OK ){ + unsigned int i; + fuzzer_rule *pX; + fuzzer_rule *a[15]; + for(i=0; ipNext; + pX->pNext = 0; + for(i=0; a[i] && ipRule = fuzzerMergeRules(p->pRule, pX); + }else{ + /* An error has occurred. Setting p->pRule to point to the head of the + ** allocated list ensures that the list will be cleaned up in this case. + */ + assert( p->pRule==0 ); + p->pRule = pHead; + } + + return rc; +} + +/* +** This function converts an SQL quoted string into an unquoted string +** and returns a pointer to a buffer allocated using sqlite3_malloc() +** containing the result. The caller should eventually free this buffer +** using sqlite3_free. +** +** Examples: +** +** "abc" becomes abc +** 'xyz' becomes xyz +** [pqr] becomes pqr +** `mno` becomes mno +*/ +static char *fuzzerDequote(const char *zIn){ + int nIn; /* Size of input string, in bytes */ + char *zOut; /* Output (dequoted) string */ + + nIn = (int)strlen(zIn); + zOut = sqlite3_malloc(nIn+1); + if( zOut ){ + char q = zIn[0]; /* Quote character (if any ) */ + + if( q!='[' && q!= '\'' && q!='"' && q!='`' ){ + memcpy(zOut, zIn, nIn+1); + }else{ + int iOut = 0; /* Index of next byte to write to output */ + int iIn; /* Index of next byte to read from input */ + + if( q=='[' ) q = ']'; + for(iIn=1; iInnCursor==0 ); + while( p->pRule ){ + fuzzer_rule *pRule = p->pRule; + p->pRule = pRule->pNext; + sqlite3_free(pRule); + } + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** xConnect/xCreate method for the fuzzer module. Arguments are: +** +** argv[0] -> module name ("fuzzer") +** argv[1] -> database name +** argv[2] -> table name +** argv[3] -> fuzzer rule table name +*/ +static int fuzzerConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int rc = SQLITE_OK; /* Return code */ + fuzzer_vtab *pNew = 0; /* New virtual table */ + const char *zModule = argv[0]; + const char *zDb = argv[1]; + + if( argc!=4 ){ + *pzErr = sqlite3_mprintf( + "%s: wrong number of CREATE VIRTUAL TABLE arguments", zModule + ); + rc = SQLITE_ERROR; + }else{ + int nModule; /* Length of zModule, in bytes */ + + nModule = (int)strlen(zModule); + pNew = sqlite3_malloc( sizeof(*pNew) + nModule + 1); + if( pNew==0 ){ + rc = SQLITE_NOMEM; + }else{ + char *zTab; /* Dequoted name of fuzzer data table */ + + memset(pNew, 0, sizeof(*pNew)); + pNew->zClassName = (char*)&pNew[1]; + memcpy(pNew->zClassName, zModule, nModule+1); + + zTab = fuzzerDequote(argv[3]); + if( zTab==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = fuzzerLoadRules(db, pNew, zDb, zTab, pzErr); + sqlite3_free(zTab); + } + + if( rc==SQLITE_OK ){ + rc = sqlite3_declare_vtab(db, "CREATE TABLE x(word,distance,ruleset)"); + } + if( rc!=SQLITE_OK ){ + fuzzerDisconnect((sqlite3_vtab *)pNew); + pNew = 0; + } + } + } + + *ppVtab = (sqlite3_vtab *)pNew; + return rc; +} + +/* +** Open a new fuzzer cursor. +*/ +static int fuzzerOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + fuzzer_vtab *p = (fuzzer_vtab*)pVTab; + fuzzer_cursor *pCur; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + pCur->pVtab = p; + *ppCursor = &pCur->base; + p->nCursor++; + return SQLITE_OK; +} + +/* +** Free all stems in a list. +*/ +static void fuzzerClearStemList(fuzzer_stem *pStem){ + while( pStem ){ + fuzzer_stem *pNext = pStem->pNext; + sqlite3_free(pStem); + pStem = pNext; + } +} + +/* +** Free up all the memory allocated by a cursor. Set it rLimit to 0 +** to indicate that it is at EOF. +*/ +static void fuzzerClearCursor(fuzzer_cursor *pCur, int clearHash){ + int i; + fuzzerClearStemList(pCur->pStem); + fuzzerClearStemList(pCur->pDone); + for(i=0; iaQueue[i]); + pCur->rLimit = (fuzzer_cost)0; + if( clearHash && pCur->nStem ){ + pCur->mxQueue = 0; + pCur->pStem = 0; + pCur->pDone = 0; + memset(pCur->aQueue, 0, sizeof(pCur->aQueue)); + memset(pCur->apHash, 0, sizeof(pCur->apHash)); + } + pCur->nStem = 0; +} + +/* +** Close a fuzzer cursor. +*/ +static int fuzzerClose(sqlite3_vtab_cursor *cur){ + fuzzer_cursor *pCur = (fuzzer_cursor *)cur; + fuzzerClearCursor(pCur, 0); + sqlite3_free(pCur->zBuf); + pCur->pVtab->nCursor--; + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Compute the current output term for a fuzzer_stem. +*/ +static int fuzzerRender( + fuzzer_stem *pStem, /* The stem to be rendered */ + char **pzBuf, /* Write results into this buffer. realloc if needed */ + int *pnBuf /* Size of the buffer */ +){ + const fuzzer_rule *pRule = pStem->pRule; + int n; /* Size of output term without nul-term */ + char *z; /* Buffer to assemble output term in */ + + n = pStem->nBasis + pRule->nTo - pRule->nFrom; + if( (*pnBuf)n; + z = *pzBuf; + if( n<0 ){ + memcpy(z, pStem->zBasis, pStem->nBasis+1); + }else{ + memcpy(z, pStem->zBasis, n); + memcpy(&z[n], pRule->zTo, pRule->nTo); + memcpy(&z[n+pRule->nTo], &pStem->zBasis[n+pRule->nFrom], + pStem->nBasis-n-pRule->nFrom+1); + } + + assert( z[pStem->nBasis + pRule->nTo - pRule->nFrom]==0 ); + return SQLITE_OK; +} + +/* +** Compute a hash on zBasis. +*/ +static unsigned int fuzzerHash(const char *z){ + unsigned int h = 0; + while( *z ){ h = (h<<3) ^ (h>>29) ^ *(z++); } + return h % FUZZER_HASH; +} + +/* +** Current cost of a stem +*/ +static fuzzer_cost fuzzerCost(fuzzer_stem *pStem){ + return pStem->rCostX = pStem->rBaseCost + pStem->pRule->rCost; +} + +#if 0 +/* +** Print a description of a fuzzer_stem on stderr. +*/ +static void fuzzerStemPrint( + const char *zPrefix, + fuzzer_stem *pStem, + const char *zSuffix +){ + if( pStem->n<0 ){ + fprintf(stderr, "%s[%s](%d)-->self%s", + zPrefix, + pStem->zBasis, pStem->rBaseCost, + zSuffix + ); + }else{ + char *zBuf = 0; + int nBuf = 0; + if( fuzzerRender(pStem, &zBuf, &nBuf)!=SQLITE_OK ) return; + fprintf(stderr, "%s[%s](%d)-->{%s}(%d)%s", + zPrefix, + pStem->zBasis, pStem->rBaseCost, zBuf, pStem->, + zSuffix + ); + sqlite3_free(zBuf); + } +} +#endif + +/* +** Return 1 if the string to which the cursor is point has already +** been emitted. Return 0 if not. Return -1 on a memory allocation +** failures. +*/ +static int fuzzerSeen(fuzzer_cursor *pCur, fuzzer_stem *pStem){ + unsigned int h; + fuzzer_stem *pLookup; + + if( fuzzerRender(pStem, &pCur->zBuf, &pCur->nBuf)==SQLITE_NOMEM ){ + return -1; + } + h = fuzzerHash(pCur->zBuf); + pLookup = pCur->apHash[h]; + while( pLookup && strcmp(pLookup->zBasis, pCur->zBuf)!=0 ){ + pLookup = pLookup->pHash; + } + return pLookup!=0; +} + +/* +** If argument pRule is NULL, this function returns false. +** +** Otherwise, it returns true if rule pRule should be skipped. A rule +** should be skipped if it does not belong to rule-set iRuleset, or if +** applying it to stem pStem would create a string longer than +** FUZZER_MX_OUTPUT_LENGTH bytes. +*/ +static int fuzzerSkipRule( + const fuzzer_rule *pRule, /* Determine whether or not to skip this */ + fuzzer_stem *pStem, /* Stem rule may be applied to */ + int iRuleset /* Rule-set used by the current query */ +){ + return pRule && ( + (pRule->iRuleset!=iRuleset) + || (pStem->nBasis + pRule->nTo - pRule->nFrom)>FUZZER_MX_OUTPUT_LENGTH + ); +} + +/* +** Advance a fuzzer_stem to its next value. Return 0 if there are +** no more values that can be generated by this fuzzer_stem. Return +** -1 on a memory allocation failure. +*/ +static int fuzzerAdvance(fuzzer_cursor *pCur, fuzzer_stem *pStem){ + const fuzzer_rule *pRule; + while( (pRule = pStem->pRule)!=0 ){ + assert( pRule==&pCur->nullRule || pRule->iRuleset==pCur->iRuleset ); + while( pStem->n < pStem->nBasis - pRule->nFrom ){ + pStem->n++; + if( pRule->nFrom==0 + || memcmp(&pStem->zBasis[pStem->n], pRule->zFrom, pRule->nFrom)==0 + ){ + /* Found a rewrite case. Make sure it is not a duplicate */ + int rc = fuzzerSeen(pCur, pStem); + if( rc<0 ) return -1; + if( rc==0 ){ + fuzzerCost(pStem); + return 1; + } + } + } + pStem->n = -1; + do{ + pRule = pRule->pNext; + }while( fuzzerSkipRule(pRule, pStem, pCur->iRuleset) ); + pStem->pRule = pRule; + if( pRule && fuzzerCost(pStem)>pCur->rLimit ) pStem->pRule = 0; + } + return 0; +} + +/* +** The two input stem lists are both sorted in order of increasing +** rCostX. Merge them together into a single list, sorted by rCostX, and +** return a pointer to the head of that new list. +*/ +static fuzzer_stem *fuzzerMergeStems(fuzzer_stem *pA, fuzzer_stem *pB){ + fuzzer_stem head; + fuzzer_stem *pTail; + + pTail = &head; + while( pA && pB ){ + if( pA->rCostX<=pB->rCostX ){ + pTail->pNext = pA; + pTail = pA; + pA = pA->pNext; + }else{ + pTail->pNext = pB; + pTail = pB; + pB = pB->pNext; + } + } + if( pA==0 ){ + pTail->pNext = pB; + }else{ + pTail->pNext = pA; + } + return head.pNext; +} + +/* +** Load pCur->pStem with the lowest-cost stem. Return a pointer +** to the lowest-cost stem. +*/ +static fuzzer_stem *fuzzerLowestCostStem(fuzzer_cursor *pCur){ + fuzzer_stem *pBest, *pX; + int iBest; + int i; + + if( pCur->pStem==0 ){ + iBest = -1; + pBest = 0; + for(i=0; i<=pCur->mxQueue; i++){ + pX = pCur->aQueue[i]; + if( pX==0 ) continue; + if( pBest==0 || pBest->rCostX>pX->rCostX ){ + pBest = pX; + iBest = i; + } + } + if( pBest ){ + pCur->aQueue[iBest] = pBest->pNext; + pBest->pNext = 0; + pCur->pStem = pBest; + } + } + return pCur->pStem; +} + +/* +** Insert pNew into queue of pending stems. Then find the stem +** with the lowest rCostX and move it into pCur->pStem. +** list. The insert is done such the pNew is in the correct order +** according to fuzzer_stem.zBaseCost+fuzzer_stem.pRule->rCost. +*/ +static fuzzer_stem *fuzzerInsert(fuzzer_cursor *pCur, fuzzer_stem *pNew){ + fuzzer_stem *pX; + int i; + + /* If pCur->pStem exists and is greater than pNew, then make pNew + ** the new pCur->pStem and insert the old pCur->pStem instead. + */ + if( (pX = pCur->pStem)!=0 && pX->rCostX>pNew->rCostX ){ + pNew->pNext = 0; + pCur->pStem = pNew; + pNew = pX; + } + + /* Insert the new value */ + pNew->pNext = 0; + pX = pNew; + for(i=0; i<=pCur->mxQueue; i++){ + if( pCur->aQueue[i] ){ + pX = fuzzerMergeStems(pX, pCur->aQueue[i]); + pCur->aQueue[i] = 0; + }else{ + pCur->aQueue[i] = pX; + break; + } + } + if( i>pCur->mxQueue ){ + if( imxQueue = i; + pCur->aQueue[i] = pX; + }else{ + assert( pCur->mxQueue==FUZZER_NQUEUE-1 ); + pX = fuzzerMergeStems(pX, pCur->aQueue[FUZZER_NQUEUE-1]); + pCur->aQueue[FUZZER_NQUEUE-1] = pX; + } + } + + return fuzzerLowestCostStem(pCur); +} + +/* +** Allocate a new fuzzer_stem. Add it to the hash table but do not +** link it into either the pCur->pStem or pCur->pDone lists. +*/ +static fuzzer_stem *fuzzerNewStem( + fuzzer_cursor *pCur, + const char *zWord, + fuzzer_cost rBaseCost +){ + fuzzer_stem *pNew; + fuzzer_rule *pRule; + unsigned int h; + + pNew = sqlite3_malloc( sizeof(*pNew) + (int)strlen(zWord) + 1 ); + if( pNew==0 ) return 0; + memset(pNew, 0, sizeof(*pNew)); + pNew->zBasis = (char*)&pNew[1]; + pNew->nBasis = (int)strlen(zWord); + memcpy(pNew->zBasis, zWord, pNew->nBasis+1); + pRule = pCur->pVtab->pRule; + while( fuzzerSkipRule(pRule, pNew, pCur->iRuleset) ){ + pRule = pRule->pNext; + } + pNew->pRule = pRule; + pNew->n = -1; + pNew->rBaseCost = pNew->rCostX = rBaseCost; + h = fuzzerHash(pNew->zBasis); + pNew->pHash = pCur->apHash[h]; + pCur->apHash[h] = pNew; + pCur->nStem++; + return pNew; +} + + +/* +** Advance a cursor to its next row of output +*/ +static int fuzzerNext(sqlite3_vtab_cursor *cur){ + fuzzer_cursor *pCur = (fuzzer_cursor*)cur; + int rc; + fuzzer_stem *pStem, *pNew; + + pCur->iRowid++; + + /* Use the element the cursor is currently point to to create + ** a new stem and insert the new stem into the priority queue. + */ + pStem = pCur->pStem; + if( pStem->rCostX>0 ){ + rc = fuzzerRender(pStem, &pCur->zBuf, &pCur->nBuf); + if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM; + pNew = fuzzerNewStem(pCur, pCur->zBuf, pStem->rCostX); + if( pNew ){ + if( fuzzerAdvance(pCur, pNew)==0 ){ + pNew->pNext = pCur->pDone; + pCur->pDone = pNew; + }else{ + if( fuzzerInsert(pCur, pNew)==pNew ){ + return SQLITE_OK; + } + } + }else{ + return SQLITE_NOMEM; + } + } + + /* Adjust the priority queue so that the first element of the + ** stem list is the next lowest cost word. + */ + while( (pStem = pCur->pStem)!=0 ){ + int res = fuzzerAdvance(pCur, pStem); + if( res<0 ){ + return SQLITE_NOMEM; + }else if( res>0 ){ + pCur->pStem = 0; + pStem = fuzzerInsert(pCur, pStem); + if( (rc = fuzzerSeen(pCur, pStem))!=0 ){ + if( rc<0 ) return SQLITE_NOMEM; + continue; + } + return SQLITE_OK; /* New word found */ + } + pCur->pStem = 0; + pStem->pNext = pCur->pDone; + pCur->pDone = pStem; + if( fuzzerLowestCostStem(pCur) ){ + rc = fuzzerSeen(pCur, pCur->pStem); + if( rc<0 ) return SQLITE_NOMEM; + if( rc==0 ){ + return SQLITE_OK; + } + } + } + + /* Reach this point only if queue has been exhausted and there is + ** nothing left to be output. */ + pCur->rLimit = (fuzzer_cost)0; + return SQLITE_OK; +} + +/* +** Called to "rewind" a cursor back to the beginning so that +** it starts its output over again. Always called at least once +** prior to any fuzzerColumn, fuzzerRowid, or fuzzerEof call. +*/ +static int fuzzerFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + fuzzer_cursor *pCur = (fuzzer_cursor *)pVtabCursor; + const char *zWord = ""; + fuzzer_stem *pStem; + int idx; + + fuzzerClearCursor(pCur, 1); + pCur->rLimit = 2147483647; + idx = 0; + if( idxNum & 1 ){ + zWord = (const char*)sqlite3_value_text(argv[0]); + idx++; + } + if( idxNum & 2 ){ + pCur->rLimit = (fuzzer_cost)sqlite3_value_int(argv[idx]); + idx++; + } + if( idxNum & 4 ){ + pCur->iRuleset = (fuzzer_cost)sqlite3_value_int(argv[idx]); + idx++; + } + pCur->nullRule.pNext = pCur->pVtab->pRule; + pCur->nullRule.rCost = 0; + pCur->nullRule.nFrom = 0; + pCur->nullRule.nTo = 0; + pCur->nullRule.zFrom = ""; + pCur->iRowid = 1; + assert( pCur->pStem==0 ); + + /* If the query term is longer than FUZZER_MX_OUTPUT_LENGTH bytes, this + ** query will return zero rows. */ + if( (int)strlen(zWord)pStem = pStem = fuzzerNewStem(pCur, zWord, (fuzzer_cost)0); + if( pStem==0 ) return SQLITE_NOMEM; + pStem->pRule = &pCur->nullRule; + pStem->n = pStem->nBasis; + }else{ + pCur->rLimit = 0; + } + + return SQLITE_OK; +} + +/* +** Only the word and distance columns have values. All other columns +** return NULL +*/ +static int fuzzerColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + fuzzer_cursor *pCur = (fuzzer_cursor*)cur; + if( i==0 ){ + /* the "word" column */ + if( fuzzerRender(pCur->pStem, &pCur->zBuf, &pCur->nBuf)==SQLITE_NOMEM ){ + return SQLITE_NOMEM; + } + sqlite3_result_text(ctx, pCur->zBuf, -1, SQLITE_TRANSIENT); + }else if( i==1 ){ + /* the "distance" column */ + sqlite3_result_int(ctx, pCur->pStem->rCostX); + }else{ + /* All other columns are NULL */ + sqlite3_result_null(ctx); + } + return SQLITE_OK; +} + +/* +** The rowid. +*/ +static int fuzzerRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + fuzzer_cursor *pCur = (fuzzer_cursor*)cur; + *pRowid = pCur->iRowid; + return SQLITE_OK; +} + +/* +** When the fuzzer_cursor.rLimit value is 0 or less, that is a signal +** that the cursor has nothing more to output. +*/ +static int fuzzerEof(sqlite3_vtab_cursor *cur){ + fuzzer_cursor *pCur = (fuzzer_cursor*)cur; + return pCur->rLimit<=(fuzzer_cost)0; +} + +/* +** Search for terms of these forms: +** +** (A) word MATCH $str +** (B1) distance < $value +** (B2) distance <= $value +** (C) ruleid == $ruleid +** +** The distance< and distance<= are both treated as distance<=. +** The query plan number is a bit vector: +** +** bit 1: Term of the form (A) found +** bit 2: Term like (B1) or (B2) found +** bit 3: Term like (C) found +** +** If bit-1 is set, $str is always in filter.argv[0]. If bit-2 is set +** then $value is in filter.argv[0] if bit-1 is clear and is in +** filter.argv[1] if bit-1 is set. If bit-3 is set, then $ruleid is +** in filter.argv[0] if bit-1 and bit-2 are both zero, is in +** filter.argv[1] if exactly one of bit-1 and bit-2 are set, and is in +** filter.argv[2] if both bit-1 and bit-2 are set. +*/ +static int fuzzerBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int iPlan = 0; + int iDistTerm = -1; + int iRulesetTerm = -1; + int i; + int seenMatch = 0; + const struct sqlite3_index_constraint *pConstraint; + double rCost = 1e12; + + pConstraint = pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pConstraint++){ + if( pConstraint->iColumn==0 + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ + seenMatch = 1; + } + if( pConstraint->usable==0 ) continue; + if( (iPlan & 1)==0 + && pConstraint->iColumn==0 + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH + ){ + iPlan |= 1; + pIdxInfo->aConstraintUsage[i].argvIndex = 1; + pIdxInfo->aConstraintUsage[i].omit = 1; + rCost /= 1e6; + } + if( (iPlan & 2)==0 + && pConstraint->iColumn==1 + && (pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT + || pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE) + ){ + iPlan |= 2; + iDistTerm = i; + rCost /= 10.0; + } + if( (iPlan & 4)==0 + && pConstraint->iColumn==2 + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + iPlan |= 4; + pIdxInfo->aConstraintUsage[i].omit = 1; + iRulesetTerm = i; + rCost /= 10.0; + } + } + if( iPlan & 2 ){ + pIdxInfo->aConstraintUsage[iDistTerm].argvIndex = 1+((iPlan&1)!=0); + } + if( iPlan & 4 ){ + int idx = 1; + if( iPlan & 1 ) idx++; + if( iPlan & 2 ) idx++; + pIdxInfo->aConstraintUsage[iRulesetTerm].argvIndex = idx; + } + pIdxInfo->idxNum = iPlan; + if( pIdxInfo->nOrderBy==1 + && pIdxInfo->aOrderBy[0].iColumn==1 + && pIdxInfo->aOrderBy[0].desc==0 + ){ + pIdxInfo->orderByConsumed = 1; + } + if( seenMatch && (iPlan&1)==0 ) rCost = 1e99; + pIdxInfo->estimatedCost = rCost; + + return SQLITE_OK; +} + +/* +** A virtual table module that implements the "fuzzer". +*/ +static sqlite3_module fuzzerModule = { + 0, /* iVersion */ + fuzzerConnect, + fuzzerConnect, + fuzzerBestIndex, + fuzzerDisconnect, + fuzzerDisconnect, + fuzzerOpen, /* xOpen - open a cursor */ + fuzzerClose, /* xClose - close a cursor */ + fuzzerFilter, /* xFilter - configure scan constraints */ + fuzzerNext, /* xNext - advance a cursor */ + fuzzerEof, /* xEof - check for end of scan */ + fuzzerColumn, /* xColumn - read data */ + fuzzerRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + + +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_fuzzer_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = sqlite3_create_module(db, "fuzzer", &fuzzerModule, 0); +#endif + return rc; +} diff --git a/components/external/SQLite-3.8.1/ext/misc/ieee754.c b/components/external/SQLite-3.8.1/ext/misc/ieee754.c new file mode 100644 index 0000000000000000000000000000000000000000..f1438938857723b53d32b2ce14ce31c62310efd9 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/misc/ieee754.c @@ -0,0 +1,131 @@ +/* +** 2013-04-17 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This SQLite extension implements functions for the exact display +** and input of IEEE754 Binary64 floating-point numbers. +** +** ieee754(X) +** ieee754(Y,Z) +** +** In the first form, the value X should be a floating-point number. +** The function will return a string of the form 'ieee754(Y,Z)' where +** Y and Z are integers such that X==Y*pow(2,Z). +** +** In the second form, Y and Z are integers which are the mantissa and +** base-2 exponent of a new floating point number. The function returns +** a floating-point value equal to Y*pow(2,Z). +** +** Examples: +** +** ieee754(2.0) -> 'ieee754(2,0)' +** ieee754(45.25) -> 'ieee754(181,-2)' +** ieee754(2, 0) -> 2.0 +** ieee754(181, -2) -> 45.25 +*/ +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 +#include +#include + +/* +** Implementation of the ieee754() function +*/ +static void ieee754func( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + if( argc==1 ){ + sqlite3_int64 m, a; + double r; + int e; + int isNeg; + char zResult[100]; + assert( sizeof(m)==sizeof(r) ); + if( sqlite3_value_type(argv[0])!=SQLITE_FLOAT ) return; + r = sqlite3_value_double(argv[0]); + if( r<0.0 ){ + isNeg = 1; + r = -r; + }else{ + isNeg = 0; + } + memcpy(&a,&r,sizeof(a)); + if( a==0 ){ + e = 0; + m = 0; + }else{ + e = a>>52; + m = a & ((((sqlite3_int64)1)<<52)-1); + m |= ((sqlite3_int64)1)<<52; + while( e<1075 && m>0 && (m&1)==0 ){ + m >>= 1; + e++; + } + if( isNeg ) m = -m; + } + sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)", + m, e-1075); + sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT); + }else if( argc==2 ){ + sqlite3_int64 m, e, a; + double r; + int isNeg = 0; + m = sqlite3_value_int64(argv[0]); + e = sqlite3_value_int64(argv[1]); + if( m<0 ){ + isNeg = 1; + m = -m; + if( m<0 ) return; + }else if( m==0 && e>1000 && e<1000 ){ + sqlite3_result_double(context, 0.0); + return; + } + while( (m>>32)&0xffe00000 ){ + m >>= 1; + e++; + } + while( ((m>>32)&0xfff00000)==0 ){ + m <<= 1; + e--; + } + e += 1075; + if( e<0 ) e = m = 0; + if( e>0x7ff ) m = 0; + a = m & ((((sqlite3_int64)1)<<52)-1); + a |= e<<52; + if( isNeg ) a |= ((sqlite3_int64)1)<<63; + memcpy(&r, &a, sizeof(r)); + sqlite3_result_double(context, r); + } +} + + +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_ieee_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; /* Unused parameter */ + rc = sqlite3_create_function(db, "ieee754", 1, SQLITE_UTF8, 0, + ieee754func, 0, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "ieee754", 2, SQLITE_UTF8, 0, + ieee754func, 0, 0); + } + return rc; +} diff --git a/components/external/SQLite-3.8.1/ext/misc/nextchar.c b/components/external/SQLite-3.8.1/ext/misc/nextchar.c new file mode 100644 index 0000000000000000000000000000000000000000..49dfd24f1f1faa2859d1355a5090cf5e676675e9 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/misc/nextchar.c @@ -0,0 +1,311 @@ +/* +** 2013-02-28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code to implement the next_char(A,T,F,W,C) SQL function. +** +** The next_char(A,T,F,W,C) function finds all valid "next" characters for +** string A given the vocabulary in T.F. If the W value exists and is a +** non-empty string, then it is an SQL expression that limits the entries +** in T.F that will be considered. If C exists and is a non-empty string, +** then it is the name of the collating sequence to use for comparison. If +** +** Only the first three arguments are required. If the C parameter is +** omitted or is NULL or is an empty string, then the default collating +** sequence of T.F is used for comparision. If the W parameter is omitted +** or is NULL or is an empty string, then no filtering of the output is +** done. +** +** The T.F column should be indexed using collation C or else this routine +** will be quite slow. +** +** For example, suppose an application has a dictionary like this: +** +** CREATE TABLE dictionary(word TEXT UNIQUE); +** +** Further suppose that for user keypad entry, it is desired to disable +** (gray out) keys that are not valid as the next character. If the +** the user has previously entered (say) 'cha' then to find all allowed +** next characters (and thereby determine when keys should not be grayed +** out) run the following query: +** +** SELECT next_char('cha','dictionary','word'); +** +** IMPLEMENTATION NOTES: +** +** The next_char function is implemented using recursive SQL that makes +** use of the table name and column name as part of a query. If either +** the table name or column name are keywords or contain special characters, +** then they should be escaped. For example: +** +** SELECT next_char('cha','[dictionary]','[word]'); +** +** This also means that the table name can be a subquery: +** +** SELECT next_char('cha','(SELECT word AS w FROM dictionary)','w'); +*/ +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 +#include + +/* +** A structure to hold context of the next_char() computation across +** nested function calls. +*/ +typedef struct nextCharContext nextCharContext; +struct nextCharContext { + sqlite3 *db; /* Database connection */ + sqlite3_stmt *pStmt; /* Prepared statement used to query */ + const unsigned char *zPrefix; /* Prefix to scan */ + int nPrefix; /* Size of zPrefix in bytes */ + int nAlloc; /* Space allocated to aResult */ + int nUsed; /* Space used in aResult */ + unsigned int *aResult; /* Array of next characters */ + int mallocFailed; /* True if malloc fails */ + int otherError; /* True for any other failure */ +}; + +/* +** Append a result character if the character is not already in the +** result. +*/ +static void nextCharAppend(nextCharContext *p, unsigned c){ + int i; + for(i=0; inUsed; i++){ + if( p->aResult[i]==c ) return; + } + if( p->nUsed+1 > p->nAlloc ){ + unsigned int *aNew; + int n = p->nAlloc*2 + 30; + aNew = sqlite3_realloc(p->aResult, n*sizeof(unsigned int)); + if( aNew==0 ){ + p->mallocFailed = 1; + return; + }else{ + p->aResult = aNew; + p->nAlloc = n; + } + } + p->aResult[p->nUsed++] = c; +} + +/* +** Write a character into z[] as UTF8. Return the number of bytes needed +** to hold the character +*/ +static int writeUtf8(unsigned char *z, unsigned c){ + if( c<0x00080 ){ + z[0] = (unsigned char)(c&0xff); + return 1; + } + if( c<0x00800 ){ + z[0] = 0xC0 + (unsigned char)((c>>6)&0x1F); + z[1] = 0x80 + (unsigned char)(c & 0x3F); + return 2; + } + if( c<0x10000 ){ + z[0] = 0xE0 + (unsigned char)((c>>12)&0x0F); + z[1] = 0x80 + (unsigned char)((c>>6) & 0x3F); + z[2] = 0x80 + (unsigned char)(c & 0x3F); + return 3; + } + z[0] = 0xF0 + (unsigned char)((c>>18) & 0x07); + z[1] = 0x80 + (unsigned char)((c>>12) & 0x3F); + z[2] = 0x80 + (unsigned char)((c>>6) & 0x3F); + z[3] = 0x80 + (unsigned char)(c & 0x3F); + return 4; +} + +/* +** Read a UTF8 character out of z[] and write it into *pOut. Return +** the number of bytes in z[] that were used to construct the character. +*/ +static int readUtf8(const unsigned char *z, unsigned *pOut){ + static const unsigned char validBits[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, + }; + unsigned c = z[0]; + if( c<0xc0 ){ + *pOut = c; + return 1; + }else{ + int n = 1; + c = validBits[c-0xc0]; + while( (z[n] & 0xc0)==0x80 ){ + c = (c<<6) + (0x3f & z[n++]); + } + if( c<0x80 || (c&0xFFFFF800)==0xD800 || (c&0xFFFFFFFE)==0xFFFE ){ + c = 0xFFFD; + } + *pOut = c; + return n; + } +} + +/* +** The nextCharContext structure has been set up. Add all "next" characters +** to the result set. +*/ +static void findNextChars(nextCharContext *p){ + unsigned cPrev = 0; + unsigned char zPrev[8]; + int n, rc; + + for(;;){ + sqlite3_bind_text(p->pStmt, 1, (char*)p->zPrefix, p->nPrefix, + SQLITE_STATIC); + n = writeUtf8(zPrev, cPrev+1); + sqlite3_bind_text(p->pStmt, 2, (char*)zPrev, n, SQLITE_STATIC); + rc = sqlite3_step(p->pStmt); + if( rc==SQLITE_DONE ){ + sqlite3_reset(p->pStmt); + return; + }else if( rc!=SQLITE_ROW ){ + p->otherError = rc; + return; + }else{ + const unsigned char *zOut = sqlite3_column_text(p->pStmt, 0); + unsigned cNext; + n = readUtf8(zOut+p->nPrefix, &cNext); + sqlite3_reset(p->pStmt); + nextCharAppend(p, cNext); + cPrev = cNext; + if( p->mallocFailed ) return; + } + } +} + + +/* +** next_character(A,T,F,W) +** +** Return a string composted of all next possible characters after +** A for elements of T.F. If W is supplied, then it is an SQL expression +** that limits the elements in T.F that are considered. +*/ +static void nextCharFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + nextCharContext c; + const unsigned char *zTable = sqlite3_value_text(argv[1]); + const unsigned char *zField = sqlite3_value_text(argv[2]); + const unsigned char *zWhere; + const unsigned char *zCollName; + char *zWhereClause = 0; + char *zColl = 0; + char *zSql; + int rc; + + memset(&c, 0, sizeof(c)); + c.db = sqlite3_context_db_handle(context); + c.zPrefix = sqlite3_value_text(argv[0]); + c.nPrefix = sqlite3_value_bytes(argv[0]); + if( zTable==0 || zField==0 || c.zPrefix==0 ) return; + if( argc>=4 + && (zWhere = sqlite3_value_text(argv[3]))!=0 + && zWhere[0]!=0 + ){ + zWhereClause = sqlite3_mprintf("AND (%s)", zWhere); + if( zWhereClause==0 ){ + sqlite3_result_error_nomem(context); + return; + } + }else{ + zWhereClause = ""; + } + if( argc>=5 + && (zCollName = sqlite3_value_text(argv[4]))!=0 + && zCollName[0]!=0 + ){ + zColl = sqlite3_mprintf("collate \"%w\"", zCollName); + if( zColl==0 ){ + sqlite3_result_error_nomem(context); + if( zWhereClause[0] ) sqlite3_free(zWhereClause); + return; + } + }else{ + zColl = ""; + } + zSql = sqlite3_mprintf( + "SELECT %s FROM %s" + " WHERE %s>=(?1 || ?2) %s" + " AND %s<=(?1 || char(1114111)) %s" /* 1114111 == 0x10ffff */ + " %s" + " ORDER BY 1 %s ASC LIMIT 1", + zField, zTable, zField, zColl, zField, zColl, zWhereClause, zColl + ); + if( zWhereClause[0] ) sqlite3_free(zWhereClause); + if( zColl[0] ) sqlite3_free(zColl); + if( zSql==0 ){ + sqlite3_result_error_nomem(context); + return; + } + + rc = sqlite3_prepare_v2(c.db, zSql, -1, &c.pStmt, 0); + sqlite3_free(zSql); + if( rc ){ + sqlite3_result_error(context, sqlite3_errmsg(c.db), -1); + return; + } + findNextChars(&c); + if( c.mallocFailed ){ + sqlite3_result_error_nomem(context); + }else{ + unsigned char *pRes; + pRes = sqlite3_malloc( c.nUsed*4 + 1 ); + if( pRes==0 ){ + sqlite3_result_error_nomem(context); + }else{ + int i; + int n = 0; + for(i=0; i +#include +#include + +/* The following object is the session context for a single percentile() +** function. We have to remember all input Y values until the very end. +** Those values are accumulated in the Percentile.a[] array. +*/ +typedef struct Percentile Percentile; +struct Percentile { + unsigned nAlloc; /* Number of slots allocated for a[] */ + unsigned nUsed; /* Number of slots actually used in a[] */ + double rPct; /* 1.0 more than the value for P */ + double *a; /* Array of Y values */ +}; + +/* +** Return TRUE if the input floating-point number is an infinity. +*/ +static int isInfinity(double r){ + sqlite3_uint64 u; + assert( sizeof(u)==sizeof(r) ); + memcpy(&u, &r, sizeof(u)); + return ((u>>52)&0x7ff)==0x7ff; +} + +/* +** Return TRUE if two doubles differ by 0.001 or less +*/ +static int sameValue(double a, double b){ + a -= b; + return a>=-0.001 && a<=0.001; +} + +/* +** The "step" function for percentile(Y,P) is called once for each +** input row. +*/ +static void percentStep(sqlite3_context *pCtx, int argc, sqlite3_value **argv){ + Percentile *p; + double rPct; + int eType; + double y; + assert( argc==2 ); + + /* Requirement 3: P must be a number between 0 and 100 */ + eType = sqlite3_value_numeric_type(argv[1]); + rPct = sqlite3_value_double(argv[1]); + if( (eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT) || + ((rPct = sqlite3_value_double(argv[1]))<0.0 || rPct>100.0) ){ + sqlite3_result_error(pCtx, "2nd argument to percentile() is not " + "a number between 0.0 and 100.0", -1); + return; + } + + /* Allocate the session context. */ + p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p==0 ) return; + + /* Remember the P value. Throw an error if the P value is different + ** from any prior row, per Requirement (2). */ + if( p->rPct==0.0 ){ + p->rPct = rPct+1.0; + }else if( !sameValue(p->rPct,rPct+1.0) ){ + sqlite3_result_error(pCtx, "2nd argument to percentile() is not the " + "same for all input rows", -1); + return; + } + + /* Ignore rows for which Y is NULL */ + eType = sqlite3_value_type(argv[0]); + if( eType==SQLITE_NULL ) return; + + /* If not NULL, then Y must be numeric. Otherwise throw an error. + ** Requirement 4 */ + if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){ + sqlite3_result_error(pCtx, "1st argument to percentile() is not " + "numeric", -1); + return; + } + + /* Throw an error if the Y value is infinity or NaN */ + y = sqlite3_value_double(argv[0]); + if( isInfinity(y) ){ + sqlite3_result_error(pCtx, "Inf input to percentile()", -1); + return; + } + + /* Allocate and store the Y */ + if( p->nUsed>=p->nAlloc ){ + unsigned n = p->nAlloc*2 + 250; + double *a = sqlite3_realloc(p->a, sizeof(double)*n); + if( a==0 ){ + sqlite3_free(p->a); + memset(p, 0, sizeof(*p)); + sqlite3_result_error_nomem(pCtx); + return; + } + p->nAlloc = n; + p->a = a; + } + p->a[p->nUsed++] = y; +} + +/* +** Compare to doubles for sorting using qsort() +*/ +static int doubleCmp(const void *pA, const void *pB){ + double a = *(double*)pA; + double b = *(double*)pB; + if( a==b ) return 0; + if( aa==0 ) return; + if( p->nUsed ){ + qsort(p->a, p->nUsed, sizeof(double), doubleCmp); + ix = (p->rPct-1.0)*(p->nUsed-1)*0.01; + i1 = (unsigned)ix; + i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1; + v1 = p->a[i1]; + v2 = p->a[i2]; + vx = v1 + (v2-v1)*(ix-i1); + sqlite3_result_double(pCtx, vx); + } + sqlite3_free(p->a); + memset(p, 0, sizeof(*p)); +} + + +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_percentile_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; /* Unused parameter */ + rc = sqlite3_create_function(db, "percentile", 2, SQLITE_UTF8, 0, + 0, percentStep, percentFinal); + return rc; +} diff --git a/components/external/SQLite-3.8.1/ext/misc/regexp.c b/components/external/SQLite-3.8.1/ext/misc/regexp.c new file mode 100644 index 0000000000000000000000000000000000000000..7244d5299815b3607fb8098172eabcfc1a5fe7a6 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/misc/regexp.c @@ -0,0 +1,760 @@ +/* +** 2012-11-13 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** The code in this file implements a compact but reasonably +** efficient regular-expression matcher for posix extended regular +** expressions against UTF8 text. +** +** This file is an SQLite extension. It registers a single function +** named "regexp(A,B)" where A is the regular expression and B is the +** string to be matched. By registering this function, SQLite will also +** then implement the "B regexp A" operator. Note that with the function +** the regular expression comes first, but with the operator it comes +** second. +** +** The following regular expression syntax is supported: +** +** X* zero or more occurrences of X +** X+ one or more occurrences of X +** X? zero or one occurrences of X +** X{p,q} between p and q occurrences of X +** (X) match X +** X|Y X or Y +** ^X X occurring at the beginning of the string +** X$ X occurring at the end of the string +** . Match any single character +** \c Character c where c is one of \{}()[]|*+?. +** \c C-language escapes for c in afnrtv. ex: \t or \n +** \uXXXX Where XXXX is exactly 4 hex digits, unicode value XXXX +** \xXX Where XX is exactly 2 hex digits, unicode value XX +** [abc] Any single character from the set abc +** [^abc] Any single character not in the set abc +** [a-z] Any single character in the range a-z +** [^a-z] Any single character not in the range a-z +** \b Word boundary +** \w Word character. [A-Za-z0-9_] +** \W Non-word character +** \d Digit +** \D Non-digit +** \s Whitespace character +** \S Non-whitespace character +** +** A nondeterministic finite automaton (NFA) is used for matching, so the +** performance is bounded by O(N*M) where N is the size of the regular +** expression and M is the size of the input string. The matcher never +** exhibits exponential behavior. Note that the X{p,q} operator expands +** to p copies of X following by q-p copies of X? and that the size of the +** regular expression in the O(N*M) performance bound is computed after +** this expansion. +*/ +#include +#include +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 + +/* +** The following #defines change the names of some functions implemented in +** this file to prevent name collisions with C-library functions of the +** same name. +*/ +#define re_match sqlite3re_match +#define re_compile sqlite3re_compile +#define re_free sqlite3re_free + +/* The end-of-input character */ +#define RE_EOF 0 /* End of input */ + +/* The NFA is implemented as sequence of opcodes taken from the following +** set. Each opcode has a single integer argument. +*/ +#define RE_OP_MATCH 1 /* Match the one character in the argument */ +#define RE_OP_ANY 2 /* Match any one character. (Implements ".") */ +#define RE_OP_ANYSTAR 3 /* Special optimized version of .* */ +#define RE_OP_FORK 4 /* Continue to both next and opcode at iArg */ +#define RE_OP_GOTO 5 /* Jump to opcode at iArg */ +#define RE_OP_ACCEPT 6 /* Halt and indicate a successful match */ +#define RE_OP_CC_INC 7 /* Beginning of a [...] character class */ +#define RE_OP_CC_EXC 8 /* Beginning of a [^...] character class */ +#define RE_OP_CC_VALUE 9 /* Single value in a character class */ +#define RE_OP_CC_RANGE 10 /* Range of values in a character class */ +#define RE_OP_WORD 11 /* Perl word character [A-Za-z0-9_] */ +#define RE_OP_NOTWORD 12 /* Not a perl word character */ +#define RE_OP_DIGIT 13 /* digit: [0-9] */ +#define RE_OP_NOTDIGIT 14 /* Not a digit */ +#define RE_OP_SPACE 15 /* space: [ \t\n\r\v\f] */ +#define RE_OP_NOTSPACE 16 /* Not a digit */ +#define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */ + +/* Each opcode is a "state" in the NFA */ +typedef unsigned short ReStateNumber; + +/* Because this is an NFA and not a DFA, multiple states can be active at +** once. An instance of the following object records all active states in +** the NFA. The implementation is optimized for the common case where the +** number of actives states is small. +*/ +typedef struct ReStateSet { + unsigned nState; /* Number of current states */ + ReStateNumber *aState; /* Current states */ +} ReStateSet; + +/* An input string read one character at a time. +*/ +typedef struct ReInput ReInput; +struct ReInput { + const unsigned char *z; /* All text */ + int i; /* Next byte to read */ + int mx; /* EOF when i>=mx */ +}; + +/* A compiled NFA (or an NFA that is in the process of being compiled) is +** an instance of the following object. +*/ +typedef struct ReCompiled ReCompiled; +struct ReCompiled { + ReInput sIn; /* Regular expression text */ + const char *zErr; /* Error message to return */ + char *aOp; /* Operators for the virtual machine */ + int *aArg; /* Arguments to each operator */ + unsigned (*xNextChar)(ReInput*); /* Next character function */ + unsigned char zInit[12]; /* Initial text to match */ + int nInit; /* Number of characters in zInit */ + unsigned nState; /* Number of entries in aOp[] and aArg[] */ + unsigned nAlloc; /* Slots allocated for aOp[] and aArg[] */ +}; + +/* Add a state to the given state set if it is not already there */ +static void re_add_state(ReStateSet *pSet, int newState){ + unsigned i; + for(i=0; inState; i++) if( pSet->aState[i]==newState ) return; + pSet->aState[pSet->nState++] = newState; +} + +/* Extract the next unicode character from *pzIn and return it. Advance +** *pzIn to the first byte past the end of the character returned. To +** be clear: this routine converts utf8 to unicode. This routine is +** optimized for the common case where the next character is a single byte. +*/ +static unsigned re_next_char(ReInput *p){ + unsigned c; + if( p->i>=p->mx ) return 0; + c = p->z[p->i++]; + if( c>=0x80 ){ + if( (c&0xe0)==0xc0 && p->imx && (p->z[p->i]&0xc0)==0x80 ){ + c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f); + if( c<0x80 ) c = 0xfffd; + }else if( (c&0xf0)==0xe0 && p->i+1mx && (p->z[p->i]&0xc0)==0x80 + && (p->z[p->i+1]&0xc0)==0x80 ){ + c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f); + p->i += 2; + if( c<=0x3ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd; + }else if( (c&0xf8)==0xf0 && p->i+3mx && (p->z[p->i]&0xc0)==0x80 + && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){ + c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6) + | (p->z[p->i+2]&0x3f); + p->i += 3; + if( c<=0xffff || c>0x10ffff ) c = 0xfffd; + }else{ + c = 0xfffd; + } + } + return c; +} +static unsigned re_next_char_nocase(ReInput *p){ + unsigned c = re_next_char(p); + if( c>='A' && c<='Z' ) c += 'a' - 'A'; + return c; +} + +/* Return true if c is a perl "word" character: [A-Za-z0-9_] */ +static int re_word_char(int c){ + return (c>='0' && c<='9') || (c>='a' && c<='z') + || (c>='A' && c<='Z') || c=='_'; +} + +/* Return true if c is a "digit" character: [0-9] */ +static int re_digit_char(int c){ + return (c>='0' && c<='9'); +} + +/* Return true if c is a perl "space" character: [ \t\r\n\v\f] */ +static int re_space_char(int c){ + return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; +} + +/* Run a compiled regular expression on the zero-terminated input +** string zIn[]. Return true on a match and false if there is no match. +*/ +static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){ + ReStateSet aStateSet[2], *pThis, *pNext; + ReStateNumber aSpace[100]; + ReStateNumber *pToFree; + unsigned int i = 0; + unsigned int iSwap = 0; + int c = RE_EOF+1; + int cPrev = 0; + int rc = 0; + ReInput in; + + in.z = zIn; + in.i = 0; + in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn); + + /* Look for the initial prefix match, if there is one. */ + if( pRe->nInit ){ + unsigned char x = pRe->zInit[0]; + while( in.i+pRe->nInit<=in.mx + && (zIn[in.i]!=x || + strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0) + ){ + in.i++; + } + if( in.i+pRe->nInit>in.mx ) return 0; + } + + if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){ + pToFree = 0; + aStateSet[0].aState = aSpace; + }else{ + pToFree = sqlite3_malloc( sizeof(ReStateNumber)*2*pRe->nState ); + if( pToFree==0 ) return -1; + aStateSet[0].aState = pToFree; + } + aStateSet[1].aState = &aStateSet[0].aState[pRe->nState]; + pNext = &aStateSet[1]; + pNext->nState = 0; + re_add_state(pNext, 0); + while( c!=RE_EOF && pNext->nState>0 ){ + cPrev = c; + c = pRe->xNextChar(&in); + pThis = pNext; + pNext = &aStateSet[iSwap]; + iSwap = 1 - iSwap; + pNext->nState = 0; + for(i=0; inState; i++){ + int x = pThis->aState[i]; + switch( pRe->aOp[x] ){ + case RE_OP_MATCH: { + if( pRe->aArg[x]==c ) re_add_state(pNext, x+1); + break; + } + case RE_OP_ANY: { + re_add_state(pNext, x+1); + break; + } + case RE_OP_WORD: { + if( re_word_char(c) ) re_add_state(pNext, x+1); + break; + } + case RE_OP_NOTWORD: { + if( !re_word_char(c) ) re_add_state(pNext, x+1); + break; + } + case RE_OP_DIGIT: { + if( re_digit_char(c) ) re_add_state(pNext, x+1); + break; + } + case RE_OP_NOTDIGIT: { + if( !re_digit_char(c) ) re_add_state(pNext, x+1); + break; + } + case RE_OP_SPACE: { + if( re_space_char(c) ) re_add_state(pNext, x+1); + break; + } + case RE_OP_NOTSPACE: { + if( !re_space_char(c) ) re_add_state(pNext, x+1); + break; + } + case RE_OP_BOUNDARY: { + if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1); + break; + } + case RE_OP_ANYSTAR: { + re_add_state(pNext, x); + re_add_state(pThis, x+1); + break; + } + case RE_OP_FORK: { + re_add_state(pThis, x+pRe->aArg[x]); + re_add_state(pThis, x+1); + break; + } + case RE_OP_GOTO: { + re_add_state(pThis, x+pRe->aArg[x]); + break; + } + case RE_OP_ACCEPT: { + rc = 1; + goto re_match_end; + } + case RE_OP_CC_INC: + case RE_OP_CC_EXC: { + int j = 1; + int n = pRe->aArg[x]; + int hit = 0; + for(j=1; j>0 && jaOp[x+j]==RE_OP_CC_VALUE ){ + if( pRe->aArg[x+j]==c ){ + hit = 1; + j = -1; + } + }else{ + if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){ + hit = 1; + j = -1; + }else{ + j++; + } + } + } + if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit; + if( hit ) re_add_state(pNext, x+n); + break; + } + } + } + } + for(i=0; inState; i++){ + if( pRe->aOp[pNext->aState[i]]==RE_OP_ACCEPT ){ rc = 1; break; } + } +re_match_end: + sqlite3_free(pToFree); + return rc; +} + +/* Resize the opcode and argument arrays for an RE under construction. +*/ +static int re_resize(ReCompiled *p, int N){ + char *aOp; + int *aArg; + aOp = sqlite3_realloc(p->aOp, N*sizeof(p->aOp[0])); + if( aOp==0 ) return 1; + p->aOp = aOp; + aArg = sqlite3_realloc(p->aArg, N*sizeof(p->aArg[0])); + if( aArg==0 ) return 1; + p->aArg = aArg; + p->nAlloc = N; + return 0; +} + +/* Insert a new opcode and argument into an RE under construction. The +** insertion point is just prior to existing opcode iBefore. +*/ +static int re_insert(ReCompiled *p, int iBefore, int op, int arg){ + int i; + if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0; + for(i=p->nState; i>iBefore; i--){ + p->aOp[i] = p->aOp[i-1]; + p->aArg[i] = p->aArg[i-1]; + } + p->nState++; + p->aOp[iBefore] = op; + p->aArg[iBefore] = arg; + return iBefore; +} + +/* Append a new opcode and argument to the end of the RE under construction. +*/ +static int re_append(ReCompiled *p, int op, int arg){ + return re_insert(p, p->nState, op, arg); +} + +/* Make a copy of N opcodes starting at iStart onto the end of the RE +** under construction. +*/ +static void re_copy(ReCompiled *p, int iStart, int N){ + if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return; + memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0])); + memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0])); + p->nState += N; +} + +/* Return true if c is a hexadecimal digit character: [0-9a-fA-F] +** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c). If +** c is not a hex digit *pV is unchanged. +*/ +static int re_hex(int c, int *pV){ + if( c>='0' && c<='9' ){ + c -= '0'; + }else if( c>='a' && c<='f' ){ + c -= 'a' - 10; + }else if( c>='A' && c<='F' ){ + c -= 'A' - 10; + }else{ + return 0; + } + *pV = (*pV)*16 + (c & 0xff); + return 1; +} + +/* A backslash character has been seen, read the next character and +** return its interpretation. +*/ +static unsigned re_esc_char(ReCompiled *p){ + static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]"; + static const char zTrans[] = "\a\f\n\r\t\v"; + int i, v = 0; + char c; + if( p->sIn.i>=p->sIn.mx ) return 0; + c = p->sIn.z[p->sIn.i]; + if( c=='u' && p->sIn.i+4sIn.mx ){ + const unsigned char *zIn = p->sIn.z + p->sIn.i; + if( re_hex(zIn[1],&v) + && re_hex(zIn[2],&v) + && re_hex(zIn[3],&v) + && re_hex(zIn[4],&v) + ){ + p->sIn.i += 5; + return v; + } + } + if( c=='x' && p->sIn.i+2sIn.mx ){ + const unsigned char *zIn = p->sIn.z + p->sIn.i; + if( re_hex(zIn[1],&v) + && re_hex(zIn[2],&v) + ){ + p->sIn.i += 3; + return v; + } + } + for(i=0; zEsc[i] && zEsc[i]!=c; i++){} + if( zEsc[i] ){ + if( i<6 ) c = zTrans[i]; + p->sIn.i++; + }else{ + p->zErr = "unknown \\ escape"; + } + return c; +} + +/* Forward declaration */ +static const char *re_subcompile_string(ReCompiled*); + +/* Peek at the next byte of input */ +static unsigned char rePeek(ReCompiled *p){ + return p->sIn.isIn.mx ? p->sIn.z[p->sIn.i] : 0; +} + +/* Compile RE text into a sequence of opcodes. Continue up to the +** first unmatched ")" character, then return. If an error is found, +** return a pointer to the error message string. +*/ +static const char *re_subcompile_re(ReCompiled *p){ + const char *zErr; + int iStart, iEnd, iGoto; + iStart = p->nState; + zErr = re_subcompile_string(p); + if( zErr ) return zErr; + while( rePeek(p)=='|' ){ + iEnd = p->nState; + re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart); + iGoto = re_append(p, RE_OP_GOTO, 0); + p->sIn.i++; + zErr = re_subcompile_string(p); + if( zErr ) return zErr; + p->aArg[iGoto] = p->nState - iGoto; + } + return 0; +} + +/* Compile an element of regular expression text (anything that can be +** an operand to the "|" operator). Return NULL on success or a pointer +** to the error message if there is a problem. +*/ +static const char *re_subcompile_string(ReCompiled *p){ + int iPrev = -1; + int iStart; + unsigned c; + const char *zErr; + while( (c = p->xNextChar(&p->sIn))!=0 ){ + iStart = p->nState; + switch( c ){ + case '|': + case '$': + case ')': { + p->sIn.i--; + return 0; + } + case '(': { + zErr = re_subcompile_re(p); + if( zErr ) return zErr; + if( rePeek(p)!=')' ) return "unmatched '('"; + p->sIn.i++; + break; + } + case '.': { + if( rePeek(p)=='*' ){ + re_append(p, RE_OP_ANYSTAR, 0); + p->sIn.i++; + }else{ + re_append(p, RE_OP_ANY, 0); + } + break; + } + case '*': { + if( iPrev<0 ) return "'*' without operand"; + re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1); + re_append(p, RE_OP_FORK, iPrev - p->nState + 1); + break; + } + case '+': { + if( iPrev<0 ) return "'+' without operand"; + re_append(p, RE_OP_FORK, iPrev - p->nState); + break; + } + case '?': { + if( iPrev<0 ) return "'?' without operand"; + re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1); + break; + } + case '{': { + int m = 0, n = 0; + int sz, j; + if( iPrev<0 ) return "'{m,n}' without operand"; + while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; } + n = m; + if( c==',' ){ + p->sIn.i++; + n = 0; + while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; } + } + if( c!='}' ) return "unmatched '{'"; + if( n>0 && nsIn.i++; + sz = p->nState - iPrev; + if( m==0 ){ + if( n==0 ) return "both m and n are zero in '{m,n}'"; + re_insert(p, iPrev, RE_OP_FORK, sz+1); + n--; + }else{ + for(j=1; j0 ){ + re_append(p, RE_OP_FORK, -sz); + } + break; + } + case '[': { + int iFirst = p->nState; + if( rePeek(p)=='^' ){ + re_append(p, RE_OP_CC_EXC, 0); + p->sIn.i++; + }else{ + re_append(p, RE_OP_CC_INC, 0); + } + while( (c = p->xNextChar(&p->sIn))!=0 ){ + if( c=='[' && rePeek(p)==':' ){ + return "POSIX character classes not supported"; + } + if( c=='\\' ) c = re_esc_char(p); + if( rePeek(p)=='-' ){ + re_append(p, RE_OP_CC_RANGE, c); + p->sIn.i++; + c = p->xNextChar(&p->sIn); + if( c=='\\' ) c = re_esc_char(p); + re_append(p, RE_OP_CC_RANGE, c); + }else{ + re_append(p, RE_OP_CC_VALUE, c); + } + if( rePeek(p)==']' ){ p->sIn.i++; break; } + } + if( c==0 ) return "unclosed '['"; + p->aArg[iFirst] = p->nState - iFirst; + break; + } + case '\\': { + int specialOp = 0; + switch( rePeek(p) ){ + case 'b': specialOp = RE_OP_BOUNDARY; break; + case 'd': specialOp = RE_OP_DIGIT; break; + case 'D': specialOp = RE_OP_NOTDIGIT; break; + case 's': specialOp = RE_OP_SPACE; break; + case 'S': specialOp = RE_OP_NOTSPACE; break; + case 'w': specialOp = RE_OP_WORD; break; + case 'W': specialOp = RE_OP_NOTWORD; break; + } + if( specialOp ){ + p->sIn.i++; + re_append(p, specialOp, 0); + }else{ + c = re_esc_char(p); + re_append(p, RE_OP_MATCH, c); + } + break; + } + default: { + re_append(p, RE_OP_MATCH, c); + break; + } + } + iPrev = iStart; + } + return 0; +} + +/* Free and reclaim all the memory used by a previously compiled +** regular expression. Applications should invoke this routine once +** for every call to re_compile() to avoid memory leaks. +*/ +void re_free(ReCompiled *pRe){ + if( pRe ){ + sqlite3_free(pRe->aOp); + sqlite3_free(pRe->aArg); + sqlite3_free(pRe); + } +} + +/* +** Compile a textual regular expression in zIn[] into a compiled regular +** expression suitable for us by re_match() and return a pointer to the +** compiled regular expression in *ppRe. Return NULL on success or an +** error message if something goes wrong. +*/ +const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){ + ReCompiled *pRe; + const char *zErr; + int i, j; + + *ppRe = 0; + pRe = sqlite3_malloc( sizeof(*pRe) ); + if( pRe==0 ){ + return "out of memory"; + } + memset(pRe, 0, sizeof(*pRe)); + pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char; + if( re_resize(pRe, 30) ){ + re_free(pRe); + return "out of memory"; + } + if( zIn[0]=='^' ){ + zIn++; + }else{ + re_append(pRe, RE_OP_ANYSTAR, 0); + } + pRe->sIn.z = (unsigned char*)zIn; + pRe->sIn.i = 0; + pRe->sIn.mx = (int)strlen(zIn); + zErr = re_subcompile_re(pRe); + if( zErr ){ + re_free(pRe); + return zErr; + } + if( rePeek(pRe)=='$' && pRe->sIn.i+1>=pRe->sIn.mx ){ + re_append(pRe, RE_OP_MATCH, RE_EOF); + re_append(pRe, RE_OP_ACCEPT, 0); + *ppRe = pRe; + }else if( pRe->sIn.i>=pRe->sIn.mx ){ + re_append(pRe, RE_OP_ACCEPT, 0); + *ppRe = pRe; + }else{ + re_free(pRe); + return "unrecognized character"; + } + + /* The following is a performance optimization. If the regex begins with + ** ".*" (if the input regex lacks an initial "^") and afterwards there are + ** one or more matching characters, enter those matching characters into + ** zInit[]. The re_match() routine can then search ahead in the input + ** string looking for the initial match without having to run the whole + ** regex engine over the string. Do not worry able trying to match + ** unicode characters beyond plane 0 - those are very rare and this is + ** just an optimization. */ + if( pRe->aOp[0]==RE_OP_ANYSTAR ){ + for(j=0, i=1; jzInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){ + unsigned x = pRe->aArg[i]; + if( x<=127 ){ + pRe->zInit[j++] = x; + }else if( x<=0xfff ){ + pRe->zInit[j++] = 0xc0 | (x>>6); + pRe->zInit[j++] = 0x80 | (x&0x3f); + }else if( x<=0xffff ){ + pRe->zInit[j++] = 0xd0 | (x>>12); + pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f); + pRe->zInit[j++] = 0x80 | (x&0x3f); + }else{ + break; + } + } + if( j>0 && pRe->zInit[j-1]==0 ) j--; + pRe->nInit = j; + } + return pRe->zErr; +} + +/* +** Implementation of the regexp() SQL function. This function implements +** the build-in REGEXP operator. The first argument to the function is the +** pattern and the second argument is the string. So, the SQL statements: +** +** A REGEXP B +** +** is implemented as regexp(B,A). +*/ +static void re_sql_func( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + ReCompiled *pRe; /* Compiled regular expression */ + const char *zPattern; /* The regular expression */ + const unsigned char *zStr;/* String being searched */ + const char *zErr; /* Compile error message */ + int setAux = 0; /* True to invoke sqlite3_set_auxdata() */ + + pRe = sqlite3_get_auxdata(context, 0); + if( pRe==0 ){ + zPattern = (const char*)sqlite3_value_text(argv[0]); + if( zPattern==0 ) return; + zErr = re_compile(&pRe, zPattern, 0); + if( zErr ){ + re_free(pRe); + sqlite3_result_error(context, zErr, -1); + return; + } + if( pRe==0 ){ + sqlite3_result_error_nomem(context); + return; + } + setAux = 1; + } + zStr = (const unsigned char*)sqlite3_value_text(argv[1]); + if( zStr!=0 ){ + sqlite3_result_int(context, re_match(pRe, zStr, -1)); + } + if( setAux ){ + sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free); + } +} + +/* +** Invoke this routine to register the regexp() function with the +** SQLite database connection. +*/ +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_regexp_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + rc = sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, 0, + re_sql_func, 0, 0); + return rc; +} diff --git a/components/external/SQLite-3.8.1/ext/misc/rot13.c b/components/external/SQLite-3.8.1/ext/misc/rot13.c new file mode 100644 index 0000000000000000000000000000000000000000..68fdf60b0f0a28b7ff0e12a432ceed134c9e8566 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/misc/rot13.c @@ -0,0 +1,114 @@ +/* +** 2013-05-15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This SQLite extension implements a rot13() function and a rot13 +** collating sequence. +*/ +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 +#include +#include + +/* +** Perform rot13 encoding on a single ASCII character. +*/ +static unsigned char rot13(unsigned char c){ + if( c>='a' && c<='z' ){ + c += 13; + if( c>'z' ) c -= 26; + }else if( c>='A' && c<='Z' ){ + c += 13; + if( c>'Z' ) c -= 26; + } + return c; +} + +/* +** Implementation of the rot13() function. +** +** Rotate ASCII alphabetic characters by 13 character positions. +** Non-ASCII characters are unchanged. rot13(rot13(X)) should always +** equal X. +*/ +static void rot13func( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zIn; + int nIn; + unsigned char *zOut; + char *zToFree = 0; + int i; + char zTemp[100]; + assert( argc==1 ); + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; + zIn = (const unsigned char*)sqlite3_value_text(argv[0]); + nIn = sqlite3_value_bytes(argv[0]); + if( nIn +# include +# include +# include +# define ALWAYS(X) 1 +# define NEVER(X) 0 + typedef unsigned char u8; + typedef unsigned short u16; +# include +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Character classes for ASCII characters: +** +** 0 '' Silent letters: H W +** 1 'A' Any vowel: A E I O U (Y) +** 2 'B' A bilabeal stop or fricative: B F P V W +** 3 'C' Other fricatives or back stops: C G J K Q S X Z +** 4 'D' Alveolar stops: D T +** 5 'H' Letter H at the beginning of a word +** 6 'L' Glide: L +** 7 'R' Semivowel: R +** 8 'M' Nasals: M N +** 9 'Y' Letter Y at the beginning of a word. +** 10 '9' Digits: 0 1 2 3 4 5 6 7 8 9 +** 11 ' ' White space +** 12 '?' Other. +*/ +#define CCLASS_SILENT 0 +#define CCLASS_VOWEL 1 +#define CCLASS_B 2 +#define CCLASS_C 3 +#define CCLASS_D 4 +#define CCLASS_H 5 +#define CCLASS_L 6 +#define CCLASS_R 7 +#define CCLASS_M 8 +#define CCLASS_Y 9 +#define CCLASS_DIGIT 10 +#define CCLASS_SPACE 11 +#define CCLASS_OTHER 12 + +/* +** The following table gives the character class for non-initial ASCII +** characters. +*/ +static const unsigned char midClass[] = { + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_SPACE, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_SPACE, /* */ CCLASS_SPACE, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_SPACE, + /* ! */ CCLASS_OTHER, /* " */ CCLASS_OTHER, /* # */ CCLASS_OTHER, + /* $ */ CCLASS_OTHER, /* % */ CCLASS_OTHER, /* & */ CCLASS_OTHER, + /* ' */ CCLASS_SILENT, /* ( */ CCLASS_OTHER, /* ) */ CCLASS_OTHER, + /* * */ CCLASS_OTHER, /* + */ CCLASS_OTHER, /* , */ CCLASS_OTHER, + /* - */ CCLASS_OTHER, /* . */ CCLASS_OTHER, /* / */ CCLASS_OTHER, + /* 0 */ CCLASS_DIGIT, /* 1 */ CCLASS_DIGIT, /* 2 */ CCLASS_DIGIT, + /* 3 */ CCLASS_DIGIT, /* 4 */ CCLASS_DIGIT, /* 5 */ CCLASS_DIGIT, + /* 6 */ CCLASS_DIGIT, /* 7 */ CCLASS_DIGIT, /* 8 */ CCLASS_DIGIT, + /* 9 */ CCLASS_DIGIT, /* : */ CCLASS_OTHER, /* ; */ CCLASS_OTHER, + /* < */ CCLASS_OTHER, /* = */ CCLASS_OTHER, /* > */ CCLASS_OTHER, + /* ? */ CCLASS_OTHER, /* @ */ CCLASS_OTHER, /* A */ CCLASS_VOWEL, + /* B */ CCLASS_B, /* C */ CCLASS_C, /* D */ CCLASS_D, + /* E */ CCLASS_VOWEL, /* F */ CCLASS_B, /* G */ CCLASS_C, + /* H */ CCLASS_SILENT, /* I */ CCLASS_VOWEL, /* J */ CCLASS_C, + /* K */ CCLASS_C, /* L */ CCLASS_L, /* M */ CCLASS_M, + /* N */ CCLASS_M, /* O */ CCLASS_VOWEL, /* P */ CCLASS_B, + /* Q */ CCLASS_C, /* R */ CCLASS_R, /* S */ CCLASS_C, + /* T */ CCLASS_D, /* U */ CCLASS_VOWEL, /* V */ CCLASS_B, + /* W */ CCLASS_B, /* X */ CCLASS_C, /* Y */ CCLASS_VOWEL, + /* Z */ CCLASS_C, /* [ */ CCLASS_OTHER, /* \ */ CCLASS_OTHER, + /* ] */ CCLASS_OTHER, /* ^ */ CCLASS_OTHER, /* _ */ CCLASS_OTHER, + /* ` */ CCLASS_OTHER, /* a */ CCLASS_VOWEL, /* b */ CCLASS_B, + /* c */ CCLASS_C, /* d */ CCLASS_D, /* e */ CCLASS_VOWEL, + /* f */ CCLASS_B, /* g */ CCLASS_C, /* h */ CCLASS_SILENT, + /* i */ CCLASS_VOWEL, /* j */ CCLASS_C, /* k */ CCLASS_C, + /* l */ CCLASS_L, /* m */ CCLASS_M, /* n */ CCLASS_M, + /* o */ CCLASS_VOWEL, /* p */ CCLASS_B, /* q */ CCLASS_C, + /* r */ CCLASS_R, /* s */ CCLASS_C, /* t */ CCLASS_D, + /* u */ CCLASS_VOWEL, /* v */ CCLASS_B, /* w */ CCLASS_B, + /* x */ CCLASS_C, /* y */ CCLASS_VOWEL, /* z */ CCLASS_C, + /* { */ CCLASS_OTHER, /* | */ CCLASS_OTHER, /* } */ CCLASS_OTHER, + /* ~ */ CCLASS_OTHER, /* */ CCLASS_OTHER, +}; +/* +** This tables gives the character class for ASCII characters that form the +** initial character of a word. The only difference from midClass is with +** the letters H, W, and Y. +*/ +static const unsigned char initClass[] = { + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_SPACE, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_SPACE, /* */ CCLASS_SPACE, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, + /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_SPACE, + /* ! */ CCLASS_OTHER, /* " */ CCLASS_OTHER, /* # */ CCLASS_OTHER, + /* $ */ CCLASS_OTHER, /* % */ CCLASS_OTHER, /* & */ CCLASS_OTHER, + /* ' */ CCLASS_OTHER, /* ( */ CCLASS_OTHER, /* ) */ CCLASS_OTHER, + /* * */ CCLASS_OTHER, /* + */ CCLASS_OTHER, /* , */ CCLASS_OTHER, + /* - */ CCLASS_OTHER, /* . */ CCLASS_OTHER, /* / */ CCLASS_OTHER, + /* 0 */ CCLASS_DIGIT, /* 1 */ CCLASS_DIGIT, /* 2 */ CCLASS_DIGIT, + /* 3 */ CCLASS_DIGIT, /* 4 */ CCLASS_DIGIT, /* 5 */ CCLASS_DIGIT, + /* 6 */ CCLASS_DIGIT, /* 7 */ CCLASS_DIGIT, /* 8 */ CCLASS_DIGIT, + /* 9 */ CCLASS_DIGIT, /* : */ CCLASS_OTHER, /* ; */ CCLASS_OTHER, + /* < */ CCLASS_OTHER, /* = */ CCLASS_OTHER, /* > */ CCLASS_OTHER, + /* ? */ CCLASS_OTHER, /* @ */ CCLASS_OTHER, /* A */ CCLASS_VOWEL, + /* B */ CCLASS_B, /* C */ CCLASS_C, /* D */ CCLASS_D, + /* E */ CCLASS_VOWEL, /* F */ CCLASS_B, /* G */ CCLASS_C, + /* H */ CCLASS_SILENT, /* I */ CCLASS_VOWEL, /* J */ CCLASS_C, + /* K */ CCLASS_C, /* L */ CCLASS_L, /* M */ CCLASS_M, + /* N */ CCLASS_M, /* O */ CCLASS_VOWEL, /* P */ CCLASS_B, + /* Q */ CCLASS_C, /* R */ CCLASS_R, /* S */ CCLASS_C, + /* T */ CCLASS_D, /* U */ CCLASS_VOWEL, /* V */ CCLASS_B, + /* W */ CCLASS_B, /* X */ CCLASS_C, /* Y */ CCLASS_Y, + /* Z */ CCLASS_C, /* [ */ CCLASS_OTHER, /* \ */ CCLASS_OTHER, + /* ] */ CCLASS_OTHER, /* ^ */ CCLASS_OTHER, /* _ */ CCLASS_OTHER, + /* ` */ CCLASS_OTHER, /* a */ CCLASS_VOWEL, /* b */ CCLASS_B, + /* c */ CCLASS_C, /* d */ CCLASS_D, /* e */ CCLASS_VOWEL, + /* f */ CCLASS_B, /* g */ CCLASS_C, /* h */ CCLASS_SILENT, + /* i */ CCLASS_VOWEL, /* j */ CCLASS_C, /* k */ CCLASS_C, + /* l */ CCLASS_L, /* m */ CCLASS_M, /* n */ CCLASS_M, + /* o */ CCLASS_VOWEL, /* p */ CCLASS_B, /* q */ CCLASS_C, + /* r */ CCLASS_R, /* s */ CCLASS_C, /* t */ CCLASS_D, + /* u */ CCLASS_VOWEL, /* v */ CCLASS_B, /* w */ CCLASS_B, + /* x */ CCLASS_C, /* y */ CCLASS_Y, /* z */ CCLASS_C, + /* { */ CCLASS_OTHER, /* | */ CCLASS_OTHER, /* } */ CCLASS_OTHER, + /* ~ */ CCLASS_OTHER, /* */ CCLASS_OTHER, +}; + +/* +** Mapping from the character class number (0-13) to a symbol for each +** character class. Note that initClass[] can be used to map the class +** symbol back into the class number. +*/ +static const unsigned char className[] = ".ABCDHLRMY9 ?"; + +/* +** Generate a "phonetic hash" from a string of ASCII characters +** in zIn[0..nIn-1]. +** +** * Map characters by character class as defined above. +** * Omit double-letters +** * Omit vowels beside R and L +** * Omit T when followed by CH +** * Omit W when followed by R +** * Omit D when followed by J or G +** * Omit K in KN or G in GN at the beginning of a word +** +** Space to hold the result is obtained from sqlite3_malloc() +** +** Return NULL if memory allocation fails. +*/ +static unsigned char *phoneticHash(const unsigned char *zIn, int nIn){ + unsigned char *zOut = sqlite3_malloc( nIn + 1 ); + int i; + int nOut = 0; + char cPrev = 0x77; + char cPrevX = 0x77; + const unsigned char *aClass = initClass; + + if( zOut==0 ) return 0; + if( nIn>2 ){ + switch( zIn[0] ){ + case 'g': + case 'k': { + if( zIn[1]=='n' ){ zIn++; nIn--; } + break; + } + } + } + for(i=0; i=0 ); + if( nOut==0 || c!=zOut[nOut-1] ) zOut[nOut++] = c; + } + zOut[nOut] = 0; + return zOut; +} + +/* +** This is an SQL function wrapper around phoneticHash(). See +** the description of phoneticHash() for additional information. +*/ +static void phoneticHashSqlFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zIn; + unsigned char *zOut; + + zIn = sqlite3_value_text(argv[0]); + if( zIn==0 ) return; + zOut = phoneticHash(zIn, sqlite3_value_bytes(argv[0])); + if( zOut==0 ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_result_text(context, (char*)zOut, -1, sqlite3_free); + } +} + +/* +** Return the character class number for a character given its +** context. +*/ +static char characterClass(char cPrev, char c){ + return cPrev==0 ? initClass[c&0x7f] : midClass[c&0x7f]; +} + +/* +** Return the cost of inserting or deleting character c immediately +** following character cPrev. If cPrev==0, that means c is the first +** character of the word. +*/ +static int insertOrDeleteCost(char cPrev, char c, char cNext){ + char classC = characterClass(cPrev, c); + char classCprev; + + if( classC==CCLASS_SILENT ){ + /* Insert or delete "silent" characters such as H or W */ + return 1; + } + if( cPrev==c ){ + /* Repeated characters, or miss a repeat */ + return 10; + } + if( classC==CCLASS_VOWEL && (cPrev=='r' || cNext=='r') ){ + return 20; /* Insert a vowel before or after 'r' */ + } + classCprev = characterClass(cPrev, cPrev); + if( classC==classCprev ){ + if( classC==CCLASS_VOWEL ){ + /* Remove or add a new vowel to a vowel cluster */ + return 15; + }else{ + /* Remove or add a consonant not in the same class */ + return 50; + } + } + + /* any other character insertion or deletion */ + return 100; +} + +/* +** Divide the insertion cost by this factor when appending to the +** end of the word. +*/ +#define FINAL_INS_COST_DIV 4 + +/* +** Return the cost of substituting cTo in place of cFrom assuming +** the previous character is cPrev. If cPrev==0 then cTo is the first +** character of the word. +*/ +static int substituteCost(char cPrev, char cFrom, char cTo){ + char classFrom, classTo; + if( cFrom==cTo ){ + /* Exact match */ + return 0; + } + if( cFrom==(cTo^0x20) && ((cTo>='A' && cTo<='Z') || (cTo>='a' && cTo<='z')) ){ + /* differ only in case */ + return 0; + } + classFrom = characterClass(cPrev, cFrom); + classTo = characterClass(cPrev, cTo); + if( classFrom==classTo ){ + /* Same character class */ + return 40; + } + if( classFrom>=CCLASS_B && classFrom<=CCLASS_Y + && classTo>=CCLASS_B && classTo<=CCLASS_Y ){ + /* Convert from one consonant to another, but in a different class */ + return 75; + } + /* Any other subsitution */ + return 100; +} + +/* +** Given two strings zA and zB which are pure ASCII, return the cost +** of transforming zA into zB. If zA ends with '*' assume that it is +** a prefix of zB and give only minimal penalty for extra characters +** on the end of zB. +** +** Smaller numbers mean a closer match. +** +** Negative values indicate an error: +** -1 One of the inputs is NULL +** -2 Non-ASCII characters on input +** -3 Unable to allocate memory +** +** If pnMatch is not NULL, then *pnMatch is set to the number of bytes +** of zB that matched the pattern in zA. If zA does not end with a '*', +** then this value is always the number of bytes in zB (i.e. strlen(zB)). +** If zA does end in a '*', then it is the number of bytes in the prefix +** of zB that was deemed to match zA. +*/ +static int editdist1(const char *zA, const char *zB, int *pnMatch){ + int nA, nB; /* Number of characters in zA[] and zB[] */ + int xA, xB; /* Loop counters for zA[] and zB[] */ + char cA, cB; /* Current character of zA and zB */ + char cAprev, cBprev; /* Previous character of zA and zB */ + char cAnext, cBnext; /* Next character in zA and zB */ + int d; /* North-west cost value */ + int dc = 0; /* North-west character value */ + int res; /* Final result */ + int *m; /* The cost matrix */ + char *cx; /* Corresponding character values */ + int *toFree = 0; /* Malloced space */ + int mStack[60+15]; /* Stack space to use if not too much is needed */ + int nMatch = 0; + + /* Early out if either input is NULL */ + if( zA==0 || zB==0 ) return -1; + + /* Skip any common prefix */ + while( zA[0] && zA[0]==zB[0] ){ dc = zA[0]; zA++; zB++; nMatch++; } + if( pnMatch ) *pnMatch = nMatch; + if( zA[0]==0 && zB[0]==0 ) return 0; + +#if 0 + printf("A=\"%s\" B=\"%s\" dc=%c\n", zA, zB, dc?dc:' '); +#endif + + /* Verify input strings and measure their lengths */ + for(nA=0; zA[nA]; nA++){ + if( zA[nA]&0x80 ) return -2; + } + for(nB=0; zB[nB]; nB++){ + if( zB[nB]&0x80 ) return -2; + } + + /* Special processing if either string is empty */ + if( nA==0 ){ + cBprev = dc; + for(xB=res=0; (cB = zB[xB])!=0; xB++){ + res += insertOrDeleteCost(cBprev, cB, zB[xB+1])/FINAL_INS_COST_DIV; + cBprev = cB; + } + return res; + } + if( nB==0 ){ + cAprev = dc; + for(xA=res=0; (cA = zA[xA])!=0; xA++){ + res += insertOrDeleteCost(cAprev, cA, zA[xA+1]); + cAprev = cA; + } + return res; + } + + /* A is a prefix of B */ + if( zA[0]=='*' && zA[1]==0 ) return 0; + + /* Allocate and initialize the Wagner matrix */ + if( nB<(sizeof(mStack)*4)/(sizeof(mStack[0])*5) ){ + m = mStack; + }else{ + m = toFree = sqlite3_malloc( (nB+1)*5*sizeof(m[0])/4 ); + if( m==0 ) return -3; + } + cx = (char*)&m[nB+1]; + + /* Compute the Wagner edit distance */ + m[0] = 0; + cx[0] = dc; + cBprev = dc; + for(xB=1; xB<=nB; xB++){ + cBnext = zB[xB]; + cB = zB[xB-1]; + cx[xB] = cB; + m[xB] = m[xB-1] + insertOrDeleteCost(cBprev, cB, cBnext); + cBprev = cB; + } + cAprev = dc; + for(xA=1; xA<=nA; xA++){ + int lastA = (xA==nA); + cA = zA[xA-1]; + cAnext = zA[xA]; + if( cA=='*' && lastA ) break; + d = m[0]; + dc = cx[0]; + m[0] = d + insertOrDeleteCost(cAprev, cA, cAnext); + cBprev = 0; + for(xB=1; xB<=nB; xB++){ + int totalCost, insCost, delCost, subCost, ncx; + cB = zB[xB-1]; + cBnext = zB[xB]; + + /* Cost to insert cB */ + insCost = insertOrDeleteCost(cx[xB-1], cB, cBnext); + if( lastA ) insCost /= FINAL_INS_COST_DIV; + + /* Cost to delete cA */ + delCost = insertOrDeleteCost(cx[xB], cA, cBnext); + + /* Cost to substitute cA->cB */ + subCost = substituteCost(cx[xB-1], cA, cB); + + /* Best cost */ + totalCost = insCost + m[xB-1]; + ncx = cB; + if( (delCost + m[xB])nLang; i++){ + EditDist3Cost *pCost, *pNext; + pCost = p->a[i].pCost; + while( pCost ){ + pNext = pCost->pNext; + sqlite3_free(pCost); + pCost = pNext; + } + } + sqlite3_free(p->a); + memset(p, 0, sizeof(*p)); +} +static void editDist3ConfigDelete(void *pIn){ + EditDist3Config *p = (EditDist3Config*)pIn; + editDist3ConfigClear(p); + sqlite3_free(p); +} + +/* +** Load all edit-distance weights from a table. +*/ +static int editDist3ConfigLoad( + EditDist3Config *p, /* The edit distance configuration to load */ + sqlite3 *db, /* Load from this database */ + const char *zTable /* Name of the table from which to load */ +){ + sqlite3_stmt *pStmt; + int rc, rc2; + char *zSql; + int iLangPrev = -9999; + EditDist3Lang *pLang = 0; + + zSql = sqlite3_mprintf("SELECT iLang, cFrom, cTo, iCost" + " FROM \"%w\" WHERE iLang>=0 ORDER BY iLang", zTable); + if( zSql==0 ) return SQLITE_NOMEM; + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + if( rc ) return rc; + editDist3ConfigClear(p); + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + int iLang = sqlite3_column_int(pStmt, 0); + const char *zFrom = (const char*)sqlite3_column_text(pStmt, 1); + int nFrom = zFrom ? sqlite3_column_bytes(pStmt, 1) : 0; + const char *zTo = (const char*)sqlite3_column_text(pStmt, 2); + int nTo = zTo ? sqlite3_column_bytes(pStmt, 2) : 0; + int iCost = sqlite3_column_int(pStmt, 3); + + assert( zFrom!=0 || nFrom==0 ); + assert( zTo!=0 || nTo==0 ); + if( nFrom>100 || nTo>100 ) continue; + if( iCost<0 ) continue; + if( pLang==0 || iLang!=iLangPrev ){ + EditDist3Lang *pNew; + pNew = sqlite3_realloc(p->a, (p->nLang+1)*sizeof(p->a[0])); + if( pNew==0 ){ rc = SQLITE_NOMEM; break; } + p->a = pNew; + pLang = &p->a[p->nLang]; + p->nLang++; + pLang->iLang = iLang; + pLang->iInsCost = 100; + pLang->iDelCost = 100; + pLang->iSubCost = 150; + pLang->pCost = 0; + iLangPrev = iLang; + } + if( nFrom==1 && zFrom[0]=='?' && nTo==0 ){ + pLang->iDelCost = iCost; + }else if( nFrom==0 && nTo==1 && zTo[0]=='?' ){ + pLang->iInsCost = iCost; + }else if( nFrom==1 && nTo==1 && zFrom[0]=='?' && zTo[0]=='?' ){ + pLang->iSubCost = iCost; + }else{ + EditDist3Cost *pCost; + int nExtra = nFrom + nTo - 4; + if( nExtra<0 ) nExtra = 0; + pCost = sqlite3_malloc( sizeof(*pCost) + nExtra ); + if( pCost==0 ){ rc = SQLITE_NOMEM; break; } + pCost->nFrom = nFrom; + pCost->nTo = nTo; + pCost->iCost = iCost; + memcpy(pCost->a, zFrom, nFrom); + memcpy(pCost->a + nFrom, zTo, nTo); + pCost->pNext = pLang->pCost; + pLang->pCost = pCost; + } + } + rc2 = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ) rc = rc2; + return rc; +} + +/* +** Return the length (in bytes) of a utf-8 character. Or return a maximum +** of N. +*/ +static int utf8Len(unsigned char c, int N){ + int len = 1; + if( c>0x7f ){ + if( (c&0xe0)==0xc0 ){ + len = 2; + }else if( (c&0xf0)==0xe0 ){ + len = 3; + }else{ + len = 4; + } + } + if( len>N ) len = N; + return len; +} + +/* +** Return TRUE (non-zero) if the To side of the given cost matches +** the given string. +*/ +static int matchTo(EditDist3Cost *p, const char *z, int n){ + if( p->nTo>n ) return 0; + if( strncmp(p->a+p->nFrom, z, p->nTo)!=0 ) return 0; + return 1; +} + +/* +** Return TRUE (non-zero) if the From side of the given cost matches +** the given string. +*/ +static int matchFrom(EditDist3Cost *p, const char *z, int n){ + assert( p->nFrom<=n ); + if( strncmp(p->a, z, p->nFrom)!=0 ) return 0; + return 1; +} + +/* +** Return TRUE (non-zero) of the next FROM character and the next TO +** character are the same. +*/ +static int matchFromTo( + EditDist3FromString *pStr, /* Left hand string */ + int n1, /* Index of comparison character on the left */ + const char *z2, /* Right-handl comparison character */ + int n2 /* Bytes remaining in z2[] */ +){ + int b1 = pStr->a[n1].nByte; + if( b1>n2 ) return 0; + if( memcmp(pStr->z+n1, z2, b1)!=0 ) return 0; + return 1; +} + +/* +** Delete an EditDist3FromString objecct +*/ +static void editDist3FromStringDelete(EditDist3FromString *p){ + int i; + if( p ){ + for(i=0; in; i++){ + sqlite3_free(p->a[i].apDel); + sqlite3_free(p->a[i].apSubst); + } + sqlite3_free(p); + } +} + +/* +** Create a EditDist3FromString object. +*/ +static EditDist3FromString *editDist3FromStringNew( + const EditDist3Lang *pLang, + const char *z, + int n +){ + EditDist3FromString *pStr; + EditDist3Cost *p; + int i; + + if( z==0 ) return 0; + if( n<0 ) n = (int)strlen(z); + pStr = sqlite3_malloc( sizeof(*pStr) + sizeof(pStr->a[0])*n + n + 1 ); + if( pStr==0 ) return 0; + pStr->a = (EditDist3From*)&pStr[1]; + memset(pStr->a, 0, sizeof(pStr->a[0])*n); + pStr->n = n; + pStr->z = (char*)&pStr->a[n]; + memcpy(pStr->z, z, n+1); + if( n && z[n-1]=='*' ){ + pStr->isPrefix = 1; + n--; + pStr->n--; + pStr->z[n] = 0; + }else{ + pStr->isPrefix = 0; + } + + for(i=0; ia[i]; + memset(pFrom, 0, sizeof(*pFrom)); + pFrom->nByte = utf8Len((unsigned char)z[i], n-i); + for(p=pLang->pCost; p; p=p->pNext){ + EditDist3Cost **apNew; + if( i+p->nFrom>n ) continue; + if( matchFrom(p, z+i, n-i)==0 ) continue; + if( p->nTo==0 ){ + apNew = sqlite3_realloc(pFrom->apDel, + sizeof(*apNew)*(pFrom->nDel+1)); + if( apNew==0 ) break; + pFrom->apDel = apNew; + apNew[pFrom->nDel++] = p; + }else{ + apNew = sqlite3_realloc(pFrom->apSubst, + sizeof(*apNew)*(pFrom->nSubst+1)); + if( apNew==0 ) break; + pFrom->apSubst = apNew; + apNew[pFrom->nSubst++] = p; + } + } + if( p ){ + editDist3FromStringDelete(pStr); + pStr = 0; + break; + } + } + return pStr; +} + +/* +** Update entry m[i] such that it is the minimum of its current value +** and m[j]+iCost. +** +** If the iCost is 1,000,000 or greater, then consider the cost to be +** infinite and skip the update. +*/ +static void updateCost( + unsigned int *m, + int i, + int j, + int iCost +){ + assert( iCost>=0 ); + if( iCost<10000 ){ + unsigned int b = m[j] + iCost; + if( bpCost; p; p=p->pNext){ + EditDist3Cost **apNew; + if( p->nFrom>0 ) continue; + if( i2+p->nTo>n2 ) continue; + if( matchTo(p, z2+i2, n2-i2)==0 ) continue; + a2[i2].nIns++; + apNew = sqlite3_realloc(a2[i2].apIns, sizeof(*apNew)*a2[i2].nIns); + if( apNew==0 ){ + res = -1; /* Out of memory */ + goto editDist3Abort; + } + a2[i2].apIns = apNew; + a2[i2].apIns[a2[i2].nIns-1] = p; + } + } + + /* Prepare to compute the minimum edit distance */ + szRow = f.n+1; + memset(m, 0x01, (n2+1)*szRow*sizeof(m[0])); + m[0] = 0; + + /* First fill in the top-row of the matrix with FROM deletion costs */ + for(i1=0; i1iDelCost); + for(k=0; knFrom, i1, p->iCost); + } + } + + /* Fill in all subsequent rows, top-to-bottom, left-to-right */ + for(i2=0; i2iInsCost); + for(k=0; knTo), rxp, p->iCost); + } + for(i1=0; i1iDelCost); + for(k=0; knFrom, cxp, p->iCost); + } + updateCost(m, cx, cxu, pLang->iInsCost); + if( matchFromTo(&f, i1, z2+i2, n2-i2) ){ + updateCost(m, cx, cxd, 0); + } + updateCost(m, cx, cxd, pLang->iSubCost); + for(k=0; knFrom+szRow*p->nTo, cxd, p->iCost); + } + } + } + } + +#if 0 /* Enable for debugging */ + printf(" ^"); + for(i1=0; i19999 ) printf(" ****"); + else printf(" %4d", v); + } + printf("\n"); + for(i2=0; i29999 ) printf(" ****"); + else printf(" %4d", v); + } + printf("\n"); + } +#endif + + /* Free memory allocations and return the result */ + res = (int)m[szRow*(n2+1)-1]; + n = n2; + if( f.isPrefix ){ + for(i2=1; i2<=n2; i2++){ + int b = m[szRow*i2-1]; + if( b<=res ){ + res = b; + n = i2 - 1; + } + } + } + if( pnMatch ){ + int nExtra = 0; + for(k=0; knLang; i++){ + if( pConfig->a[i].iLang==iLang ) return &pConfig->a[i]; + } + return &editDist3Lang; +} + +/* +** Function: editdist3(A,B,iLang) +** editdist3(tablename) +** +** Return the cost of transforming string A into string B using edit +** weights for iLang. +** +** The second form loads edit weights into memory from a table. +*/ +static void editDist3SqlFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + EditDist3Config *pConfig = (EditDist3Config*)sqlite3_user_data(context); + sqlite3 *db = sqlite3_context_db_handle(context); + int rc; + if( argc==1 ){ + const char *zTable = (const char*)sqlite3_value_text(argv[0]); + rc = editDist3ConfigLoad(pConfig, db, zTable); + if( rc ) sqlite3_result_error_code(context, rc); + }else{ + const char *zA = (const char*)sqlite3_value_text(argv[0]); + const char *zB = (const char*)sqlite3_value_text(argv[1]); + int nA = sqlite3_value_bytes(argv[0]); + int nB = sqlite3_value_bytes(argv[1]); + int iLang = argc==3 ? sqlite3_value_int(argv[2]) : 0; + const EditDist3Lang *pLang = editDist3FindLang(pConfig, iLang); + EditDist3FromString *pFrom; + int dist; + + pFrom = editDist3FromStringNew(pLang, zA, nA); + if( pFrom==0 ){ + sqlite3_result_error_nomem(context); + return; + } + dist = editDist3Core(pFrom, zB, nB, pLang, 0); + editDist3FromStringDelete(pFrom); + if( dist==(-1) ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_result_int(context, dist); + } + } +} + +/* +** Register the editDist3 function with SQLite +*/ +static int editDist3Install(sqlite3 *db){ + int rc; + EditDist3Config *pConfig = sqlite3_malloc( sizeof(*pConfig) ); + if( pConfig==0 ) return SQLITE_NOMEM; + memset(pConfig, 0, sizeof(*pConfig)); + rc = sqlite3_create_function_v2(db, "editdist3", + 2, SQLITE_UTF8, pConfig, editDist3SqlFunc, 0, 0, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function_v2(db, "editdist3", + 3, SQLITE_UTF8, pConfig, editDist3SqlFunc, 0, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function_v2(db, "editdist3", + 1, SQLITE_UTF8, pConfig, editDist3SqlFunc, 0, 0, + editDist3ConfigDelete); + }else{ + sqlite3_free(pConfig); + } + return rc; +} +/* End configurable cost unicode edit distance routines +****************************************************************************** +****************************************************************************** +** Begin transliterate unicode-to-ascii implementation +*/ + +#if !SQLITE_AMALGAMATION +/* +** This lookup table is used to help decode the first byte of +** a multi-byte UTF8 character. +*/ +static const unsigned char sqlite3Utf8Trans1[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, +}; +#endif + +/* +** Return the value of the first UTF-8 character in the string. +*/ +static int utf8Read(const unsigned char *z, int n, int *pSize){ + int c, i; + + /* All callers to this routine (in the current implementation) + ** always have n>0. */ + if( NEVER(n==0) ){ + c = i = 0; + }else{ + c = z[0]; + i = 1; + if( c>=0xc0 ){ + c = sqlite3Utf8Trans1[c-0xc0]; + while( i0 ){ + c = utf8Read(zIn, nIn, &sz); + zIn += sz; + nIn -= sz; + if( c<=127 ){ + zOut[nOut++] = c; + }else{ + int xTop, xBtm, x; + xTop = sizeof(translit)/sizeof(translit[0]) - 1; + xBtm = 0; + while( xTop>=xBtm ){ + x = (xTop + xBtm)/2; + if( translit[x].cFrom==c ){ + zOut[nOut++] = translit[x].cTo0; + if( translit[x].cTo1 ){ + zOut[nOut++] = translit[x].cTo1; + /* Add an extra "ch" after the "sh" for Щ and щ */ + if( c==0x0429 || c== 0x0449 ){ + zOut[nOut++] = 'c'; + zOut[nOut++] = 'h'; + } + } + c = 0; + break; + }else if( translit[x].cFrom>c ){ + xTop = x-1; + }else{ + xBtm = x+1; + } + } + if( c ) zOut[nOut++] = '?'; + } + } + zOut[nOut] = 0; + return zOut; +} + +/* +** Return the number of characters in the shortest prefix of the input +** string that transliterates to an ASCII string nTrans bytes or longer. +** Or, if the transliteration of the input string is less than nTrans +** bytes in size, return the number of characters in the input string. +*/ +static int translen_to_charlen(const char *zIn, int nIn, int nTrans){ + int i, c, sz, nOut; + int nChar; + + i = nOut = 0; + for(nChar=0; i=128 ){ + int xTop, xBtm, x; + xTop = sizeof(translit)/sizeof(translit[0]) - 1; + xBtm = 0; + while( xTop>=xBtm ){ + x = (xTop + xBtm)/2; + if( translit[x].cFrom==c ){ + if( translit[x].cTo1 ) nOut++; + if( c==0x0429 || c== 0x0449 ) nOut += 2; + break; + }else if( translit[x].cFrom>c ){ + xTop = x-1; + }else{ + xBtm = x+1; + } + } + } + } + + return nChar; +} + + +/* +** spellfix1_translit(X) +** +** Convert a string that contains non-ASCII Roman characters into +** pure ASCII. +*/ +static void transliterateSqlFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zIn = sqlite3_value_text(argv[0]); + int nIn = sqlite3_value_bytes(argv[0]); + unsigned char *zOut = transliterate(zIn, nIn); + if( zOut==0 ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_result_text(context, (char*)zOut, -1, sqlite3_free); + } +} + +/* +** spellfix1_scriptcode(X) +** +** Try to determine the dominant script used by the word X and return +** its ISO 15924 numeric code. +** +** The current implementation only understands the following scripts: +** +** 215 (Latin) +** 220 (Cyrillic) +** 200 (Greek) +** +** This routine will return 998 if the input X contains characters from +** two or more of the above scripts or 999 if X contains no characters +** from any of the above scripts. +*/ +static void scriptCodeSqlFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zIn = sqlite3_value_text(argv[0]); + int nIn = sqlite3_value_bytes(argv[0]); + int c, sz; + int scriptMask = 0; + int res; +# define SCRIPT_LATIN 0x0001 +# define SCRIPT_CYRILLIC 0x0002 +# define SCRIPT_GREEK 0x0004 + + while( nIn>0 ){ + c = utf8Read(zIn, nIn, &sz); + zIn += sz; + nIn -= sz; + if( c<0x02af ){ + scriptMask |= SCRIPT_LATIN; + }else if( c>=0x0400 && c<=0x04ff ){ + scriptMask |= SCRIPT_CYRILLIC; + }else if( c>=0x0386 && c<=0x03ce ){ + scriptMask |= SCRIPT_GREEK; + } + } + switch( scriptMask ){ + case 0: res = 999; break; + case SCRIPT_LATIN: res = 215; break; + case SCRIPT_CYRILLIC: res = 220; break; + case SCRIPT_GREEK: res = 200; break; + default: res = 998; break; + } + sqlite3_result_int(context, res); +} + +/* End transliterate +****************************************************************************** +****************************************************************************** +** Begin spellfix1 virtual table. +*/ + +/* Maximum length of a phonehash used for querying the shadow table */ +#define SPELLFIX_MX_HASH 8 + +/* Maximum number of hash strings to examine per query */ +#define SPELLFIX_MX_RUN 1 + +typedef struct spellfix1_vtab spellfix1_vtab; +typedef struct spellfix1_cursor spellfix1_cursor; + +/* Fuzzy-search virtual table object */ +struct spellfix1_vtab { + sqlite3_vtab base; /* Base class - must be first */ + sqlite3 *db; /* Database connection */ + char *zDbName; /* Name of database holding this table */ + char *zTableName; /* Name of the virtual table */ + char *zCostTable; /* Table holding edit-distance cost numbers */ + EditDist3Config *pConfig3; /* Parsed edit distance costs */ +}; + +/* Fuzzy-search cursor object */ +struct spellfix1_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + spellfix1_vtab *pVTab; /* The table to which this cursor belongs */ + char *zPattern; /* rhs of MATCH clause */ + int nRow; /* Number of rows of content */ + int nAlloc; /* Number of allocated rows */ + int iRow; /* Current row of content */ + int iLang; /* Value of the langid= constraint */ + int iTop; /* Value of the top= constraint */ + int iScope; /* Value of the scope= constraint */ + int nSearch; /* Number of vocabulary items checked */ + sqlite3_stmt *pFullScan; /* Shadow query for a full table scan */ + struct spellfix1_row { /* For each row of content */ + sqlite3_int64 iRowid; /* Rowid for this row */ + char *zWord; /* Text for this row */ + int iRank; /* Rank for this row */ + int iDistance; /* Distance from pattern for this row */ + int iScore; /* Score for sorting */ + int iMatchlen; /* Value of matchlen column (or -1) */ + char zHash[SPELLFIX_MX_HASH]; /* the phonehash used for this match */ + } *a; +}; + +/* +** Construct one or more SQL statements from the format string given +** and then evaluate those statements. The success code is written +** into *pRc. +** +** If *pRc is initially non-zero then this routine is a no-op. +*/ +static void spellfix1DbExec( + int *pRc, /* Success code */ + sqlite3 *db, /* Database in which to run SQL */ + const char *zFormat, /* Format string for SQL */ + ... /* Arguments to the format string */ +){ + va_list ap; + char *zSql; + if( *pRc ) return; + va_start(ap, zFormat); + zSql = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + if( zSql==0 ){ + *pRc = SQLITE_NOMEM; + }else{ + *pRc = sqlite3_exec(db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } +} + +/* +** xDisconnect/xDestroy method for the fuzzy-search module. +*/ +static int spellfix1Uninit(int isDestroy, sqlite3_vtab *pVTab){ + spellfix1_vtab *p = (spellfix1_vtab*)pVTab; + int rc = SQLITE_OK; + if( isDestroy ){ + sqlite3 *db = p->db; + spellfix1DbExec(&rc, db, "DROP TABLE IF EXISTS \"%w\".\"%w_vocab\"", + p->zDbName, p->zTableName); + } + if( rc==SQLITE_OK ){ + sqlite3_free(p->zTableName); + editDist3ConfigDelete(p->pConfig3); + sqlite3_free(p->zCostTable); + sqlite3_free(p); + } + return rc; +} +static int spellfix1Disconnect(sqlite3_vtab *pVTab){ + return spellfix1Uninit(0, pVTab); +} +static int spellfix1Destroy(sqlite3_vtab *pVTab){ + return spellfix1Uninit(1, pVTab); +} + +/* +** Make a copy of a string. Remove leading and trailing whitespace +** and dequote it. +*/ +static char *spellfix1Dequote(const char *zIn){ + char *zOut; + int i, j; + char c; + while( isspace(zIn[0]) ) zIn++; + zOut = sqlite3_mprintf("%s", zIn); + if( zOut==0 ) return 0; + i = (int)strlen(zOut); +#if 0 /* The parser will never leave spaces at the end */ + while( i>0 && isspace(zOut[i-1]) ){ i--; } +#endif + zOut[i] = 0; + c = zOut[0]; + if( c=='\'' || c=='"' ){ + for(i=1, j=0; ALWAYS(zOut[i]); i++){ + zOut[j++] = zOut[i]; + if( zOut[i]==c ){ + if( zOut[i+1]==c ){ + i++; + }else{ + zOut[j-1] = 0; + break; + } + } + } + } + return zOut; +} + + +/* +** xConnect/xCreate method for the spellfix1 module. Arguments are: +** +** argv[0] -> module name ("spellfix1") +** argv[1] -> database name +** argv[2] -> table name +** argv[3].. -> optional arguments (i.e. "edit_cost_table" parameter) +*/ +static int spellfix1Init( + int isCreate, + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, + char **pzErr +){ + spellfix1_vtab *pNew = 0; + const char *zModule = argv[0]; + const char *zDbName = argv[1]; + const char *zTableName = argv[2]; + int nDbName; + int rc = SQLITE_OK; + int i; + + nDbName = (int)strlen(zDbName); + pNew = sqlite3_malloc( sizeof(*pNew) + nDbName + 1); + if( pNew==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pNew, 0, sizeof(*pNew)); + pNew->zDbName = (char*)&pNew[1]; + memcpy(pNew->zDbName, zDbName, nDbName+1); + pNew->zTableName = sqlite3_mprintf("%s", zTableName); + pNew->db = db; + if( pNew->zTableName==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_declare_vtab(db, + "CREATE TABLE x(word,rank,distance,langid, " + "score, matchlen, phonehash HIDDEN, " + "top HIDDEN, scope HIDDEN, srchcnt HIDDEN, " + "soundslike HIDDEN, command HIDDEN)" + ); +#define SPELLFIX_COL_WORD 0 +#define SPELLFIX_COL_RANK 1 +#define SPELLFIX_COL_DISTANCE 2 +#define SPELLFIX_COL_LANGID 3 +#define SPELLFIX_COL_SCORE 4 +#define SPELLFIX_COL_MATCHLEN 5 +#define SPELLFIX_COL_PHONEHASH 6 +#define SPELLFIX_COL_TOP 7 +#define SPELLFIX_COL_SCOPE 8 +#define SPELLFIX_COL_SRCHCNT 9 +#define SPELLFIX_COL_SOUNDSLIKE 10 +#define SPELLFIX_COL_COMMAND 11 + } + if( rc==SQLITE_OK && isCreate ){ + sqlite3_uint64 r; + spellfix1DbExec(&rc, db, + "CREATE TABLE IF NOT EXISTS \"%w\".\"%w_vocab\"(\n" + " id INTEGER PRIMARY KEY,\n" + " rank INT,\n" + " langid INT,\n" + " word TEXT,\n" + " k1 TEXT,\n" + " k2 TEXT\n" + ");\n", + zDbName, zTableName + ); + sqlite3_randomness(sizeof(r), &r); + spellfix1DbExec(&rc, db, + "CREATE INDEX IF NOT EXISTS \"%w\".\"%w_index_%llx\" " + "ON \"%w_vocab\"(langid,k2);", + zDbName, zModule, r, zTableName + ); + } + for(i=3; rc==SQLITE_OK && ibase); + }else{ + *ppVTab = (sqlite3_vtab *)pNew; + } + return rc; +} + +/* +** The xConnect and xCreate methods +*/ +static int spellfix1Connect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, + char **pzErr +){ + return spellfix1Init(0, db, pAux, argc, argv, ppVTab, pzErr); +} +static int spellfix1Create( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, + char **pzErr +){ + return spellfix1Init(1, db, pAux, argc, argv, ppVTab, pzErr); +} + +/* +** Clear all of the content from a cursor. +*/ +static void spellfix1ResetCursor(spellfix1_cursor *pCur){ + int i; + for(i=0; inRow; i++){ + sqlite3_free(pCur->a[i].zWord); + } + pCur->nRow = 0; + pCur->iRow = 0; + pCur->nSearch = 0; + if( pCur->pFullScan ){ + sqlite3_finalize(pCur->pFullScan); + pCur->pFullScan = 0; + } +} + +/* +** Resize the cursor to hold up to N rows of content +*/ +static void spellfix1ResizeCursor(spellfix1_cursor *pCur, int N){ + struct spellfix1_row *aNew; + assert( N>=pCur->nRow ); + aNew = sqlite3_realloc(pCur->a, sizeof(pCur->a[0])*N); + if( aNew==0 && N>0 ){ + spellfix1ResetCursor(pCur); + sqlite3_free(pCur->a); + pCur->nAlloc = 0; + pCur->a = 0; + }else{ + pCur->nAlloc = N; + pCur->a = aNew; + } +} + + +/* +** Close a fuzzy-search cursor. +*/ +static int spellfix1Close(sqlite3_vtab_cursor *cur){ + spellfix1_cursor *pCur = (spellfix1_cursor *)cur; + spellfix1ResetCursor(pCur); + spellfix1ResizeCursor(pCur, 0); + sqlite3_free(pCur->zPattern); + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Search for terms of these forms: +** +** (A) word MATCH $str +** (B) langid == $langid +** (C) top = $top +** (D) scope = $scope +** (E) distance < $distance +** (F) distance <= $distance +** +** The plan number is a bit mask formed with these bits: +** +** 0x01 (A) is found +** 0x02 (B) is found +** 0x04 (C) is found +** 0x08 (D) is found +** 0x10 (E) is found +** 0x20 (F) is found +** +** filter.argv[*] values contains $str, $langid, $top, and $scope, +** if specified and in that order. +*/ +static int spellfix1BestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int iPlan = 0; + int iLangTerm = -1; + int iTopTerm = -1; + int iScopeTerm = -1; + int iDistTerm = -1; + int i; + const struct sqlite3_index_constraint *pConstraint; + pConstraint = pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pConstraint++){ + if( pConstraint->usable==0 ) continue; + + /* Terms of the form: word MATCH $str */ + if( (iPlan & 1)==0 + && pConstraint->iColumn==SPELLFIX_COL_WORD + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH + ){ + iPlan |= 1; + pIdxInfo->aConstraintUsage[i].argvIndex = 1; + pIdxInfo->aConstraintUsage[i].omit = 1; + } + + /* Terms of the form: langid = $langid */ + if( (iPlan & 2)==0 + && pConstraint->iColumn==SPELLFIX_COL_LANGID + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + iPlan |= 2; + iLangTerm = i; + } + + /* Terms of the form: top = $top */ + if( (iPlan & 4)==0 + && pConstraint->iColumn==SPELLFIX_COL_TOP + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + iPlan |= 4; + iTopTerm = i; + } + + /* Terms of the form: scope = $scope */ + if( (iPlan & 8)==0 + && pConstraint->iColumn==SPELLFIX_COL_SCOPE + && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ + ){ + iPlan |= 8; + iScopeTerm = i; + } + + /* Terms of the form: distance < $dist or distance <= $dist */ + if( (iPlan & (16|32))==0 + && pConstraint->iColumn==SPELLFIX_COL_DISTANCE + && (pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT + || pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE) + ){ + iPlan |= pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT ? 16 : 32; + iDistTerm = i; + } + } + if( iPlan&1 ){ + int idx = 2; + pIdxInfo->idxNum = iPlan; + if( pIdxInfo->nOrderBy==1 + && pIdxInfo->aOrderBy[0].iColumn==SPELLFIX_COL_SCORE + && pIdxInfo->aOrderBy[0].desc==0 + ){ + pIdxInfo->orderByConsumed = 1; /* Default order by iScore */ + } + if( iPlan&2 ){ + pIdxInfo->aConstraintUsage[iLangTerm].argvIndex = idx++; + pIdxInfo->aConstraintUsage[iLangTerm].omit = 1; + } + if( iPlan&4 ){ + pIdxInfo->aConstraintUsage[iTopTerm].argvIndex = idx++; + pIdxInfo->aConstraintUsage[iTopTerm].omit = 1; + } + if( iPlan&8 ){ + pIdxInfo->aConstraintUsage[iScopeTerm].argvIndex = idx++; + pIdxInfo->aConstraintUsage[iScopeTerm].omit = 1; + } + if( iPlan&(16|32) ){ + pIdxInfo->aConstraintUsage[iDistTerm].argvIndex = idx++; + pIdxInfo->aConstraintUsage[iDistTerm].omit = 1; + } + pIdxInfo->estimatedCost = 1e5; + }else{ + pIdxInfo->idxNum = 0; + pIdxInfo->estimatedCost = 1e50; + } + return SQLITE_OK; +} + +/* +** Open a new fuzzy-search cursor. +*/ +static int spellfix1Open(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + spellfix1_vtab *p = (spellfix1_vtab*)pVTab; + spellfix1_cursor *pCur; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + pCur->pVTab = p; + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Adjust a distance measurement by the words rank in order to show +** preference to common words. +*/ +static int spellfix1Score(int iDistance, int iRank){ + int iLog2; + for(iLog2=0; iRank>0; iLog2++, iRank>>=1){} + return iDistance + 32 - iLog2; +} + +/* +** Compare two spellfix1_row objects for sorting purposes in qsort() such +** that they sort in order of increasing distance. +*/ +static int spellfix1RowCompare(const void *A, const void *B){ + const struct spellfix1_row *a = (const struct spellfix1_row*)A; + const struct spellfix1_row *b = (const struct spellfix1_row*)B; + return a->iScore - b->iScore; +} + +/* +** A structure used to pass information from spellfix1FilterForMatch() +** into spellfix1RunQuery(). +*/ +typedef struct MatchQuery { + spellfix1_cursor *pCur; /* The cursor being queried */ + sqlite3_stmt *pStmt; /* shadow table query statment */ + char zHash[SPELLFIX_MX_HASH]; /* The current phonehash for zPattern */ + const char *zPattern; /* Transliterated input string */ + int nPattern; /* Length of zPattern */ + EditDist3FromString *pMatchStr3; /* Original unicode string */ + EditDist3Config *pConfig3; /* Edit-distance cost coefficients */ + const EditDist3Lang *pLang; /* The selected language coefficients */ + int iLang; /* The language id */ + int iScope; /* Default scope */ + int iMaxDist; /* Maximum allowed edit distance, or -1 */ + int rc; /* Error code */ + int nRun; /* Number of prior runs for the same zPattern */ + char azPrior[SPELLFIX_MX_RUN][SPELLFIX_MX_HASH]; /* Prior hashes */ +} MatchQuery; + +/* +** Run a query looking for the best matches against zPattern using +** zHash as the character class seed hash. +*/ +static void spellfix1RunQuery(MatchQuery *p, const char *zQuery, int nQuery){ + const char *zK1; + const char *zWord; + int iDist; + int iRank; + int iScore; + int iWorst = 0; + int idx; + int idxWorst = -1; + int i; + int iScope = p->iScope; + spellfix1_cursor *pCur = p->pCur; + sqlite3_stmt *pStmt = p->pStmt; + char zHash1[SPELLFIX_MX_HASH]; + char zHash2[SPELLFIX_MX_HASH]; + char *zClass; + int nClass; + int rc; + + if( pCur->a==0 || p->rc ) return; /* Prior memory allocation failure */ + zClass = (char*)phoneticHash((unsigned char*)zQuery, nQuery); + if( zClass==0 ){ + p->rc = SQLITE_NOMEM; + return; + } + nClass = (int)strlen(zClass); + if( nClass>SPELLFIX_MX_HASH-2 ){ + nClass = SPELLFIX_MX_HASH-2; + zClass[nClass] = 0; + } + if( nClass<=iScope ){ + if( nClass>2 ){ + iScope = nClass-1; + }else{ + iScope = nClass; + } + } + memcpy(zHash1, zClass, iScope); + sqlite3_free(zClass); + zHash1[iScope] = 0; + memcpy(zHash2, zHash1, iScope); + zHash2[iScope] = 'Z'; + zHash2[iScope+1] = 0; +#if SPELLFIX_MX_RUN>1 + for(i=0; inRun; i++){ + if( strcmp(p->azPrior[i], zHash1)==0 ) return; + } +#endif + assert( p->nRunazPrior[p->nRun++], zHash1, iScope+1); + if( sqlite3_bind_text(pStmt, 1, zHash1, -1, SQLITE_STATIC)==SQLITE_NOMEM + || sqlite3_bind_text(pStmt, 2, zHash2, -1, SQLITE_STATIC)==SQLITE_NOMEM + ){ + p->rc = SQLITE_NOMEM; + return; + } +#if SPELLFIX_MX_RUN>1 + for(i=0; inRow; i++){ + if( pCur->a[i].iScore>iWorst ){ + iWorst = pCur->a[i].iScore; + idxWorst = i; + } + } +#endif + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + int iMatchlen = -1; + iRank = sqlite3_column_int(pStmt, 2); + if( p->pMatchStr3 ){ + int nWord = sqlite3_column_bytes(pStmt, 1); + zWord = (const char*)sqlite3_column_text(pStmt, 1); + iDist = editDist3Core(p->pMatchStr3, zWord, nWord, p->pLang, &iMatchlen); + }else{ + zK1 = (const char*)sqlite3_column_text(pStmt, 3); + if( zK1==0 ) continue; + iDist = editdist1(p->zPattern, zK1, 0); + } + if( iDist<0 ){ + p->rc = SQLITE_NOMEM; + break; + } + pCur->nSearch++; + iScore = spellfix1Score(iDist,iRank); + if( p->iMaxDist>=0 ){ + if( iDist>p->iMaxDist ) continue; + if( pCur->nRow>=pCur->nAlloc-1 ){ + spellfix1ResizeCursor(pCur, pCur->nAlloc*2 + 10); + if( pCur->a==0 ) break; + } + idx = pCur->nRow; + }else if( pCur->nRownAlloc ){ + idx = pCur->nRow; + }else if( iScorea[idx].zWord); + }else{ + continue; + } + pCur->a[idx].zWord = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); + if( pCur->a[idx].zWord==0 ){ + p->rc = SQLITE_NOMEM; + break; + } + pCur->a[idx].iRowid = sqlite3_column_int64(pStmt, 0); + pCur->a[idx].iRank = iRank; + pCur->a[idx].iDistance = iDist; + pCur->a[idx].iScore = iScore; + pCur->a[idx].iMatchlen = iMatchlen; + memcpy(pCur->a[idx].zHash, zHash1, iScope+1); + if( pCur->nRownAlloc ) pCur->nRow++; + if( pCur->nRow==pCur->nAlloc ){ + iWorst = pCur->a[0].iScore; + idxWorst = 0; + for(i=1; inRow; i++){ + iScore = pCur->a[i].iScore; + if( iWorstrc = rc; +} + +/* +** This version of the xFilter method work if the MATCH term is present +** and we are doing a scan. +*/ +static int spellfix1FilterForMatch( + spellfix1_cursor *pCur, + int idxNum, + int argc, + sqlite3_value **argv +){ + const unsigned char *zMatchThis; /* RHS of the MATCH operator */ + EditDist3FromString *pMatchStr3 = 0; /* zMatchThis as an editdist string */ + char *zPattern; /* Transliteration of zMatchThis */ + int nPattern; /* Length of zPattern */ + int iLimit = 20; /* Max number of rows of output */ + int iScope = 3; /* Use this many characters of zClass */ + int iLang = 0; /* Language code */ + char *zSql; /* SQL of shadow table query */ + sqlite3_stmt *pStmt = 0; /* Shadow table query */ + int rc; /* Result code */ + int idx = 1; /* Next available filter parameter */ + spellfix1_vtab *p = pCur->pVTab; /* The virtual table that owns pCur */ + MatchQuery x; /* For passing info to RunQuery() */ + + /* Load the cost table if we have not already done so */ + if( p->zCostTable!=0 && p->pConfig3==0 ){ + p->pConfig3 = sqlite3_malloc( sizeof(p->pConfig3[0]) ); + if( p->pConfig3==0 ) return SQLITE_NOMEM; + memset(p->pConfig3, 0, sizeof(p->pConfig3[0])); + rc = editDist3ConfigLoad(p->pConfig3, p->db, p->zCostTable); + if( rc ) return rc; + } + memset(&x, 0, sizeof(x)); + x.iScope = 3; /* Default scope if none specified by "WHERE scope=N" */ + x.iMaxDist = -1; /* Maximum allowed edit distance */ + + if( idxNum&2 ){ + iLang = sqlite3_value_int(argv[idx++]); + } + if( idxNum&4 ){ + iLimit = sqlite3_value_int(argv[idx++]); + if( iLimit<1 ) iLimit = 1; + } + if( idxNum&8 ){ + x.iScope = sqlite3_value_int(argv[idx++]); + if( x.iScope<1 ) x.iScope = 1; + if( x.iScope>SPELLFIX_MX_HASH-2 ) x.iScope = SPELLFIX_MX_HASH-2; + } + if( idxNum&(16|32) ){ + x.iMaxDist = sqlite3_value_int(argv[idx++]); + if( idxNum&16 ) x.iMaxDist--; + if( x.iMaxDist<0 ) x.iMaxDist = 0; + } + spellfix1ResetCursor(pCur); + spellfix1ResizeCursor(pCur, iLimit); + zMatchThis = sqlite3_value_text(argv[0]); + if( zMatchThis==0 ) return SQLITE_OK; + if( p->pConfig3 ){ + x.pLang = editDist3FindLang(p->pConfig3, iLang); + pMatchStr3 = editDist3FromStringNew(x.pLang, (const char*)zMatchThis, -1); + if( pMatchStr3==0 ){ + x.rc = SQLITE_NOMEM; + goto filter_exit; + } + }else{ + x.pLang = 0; + } + zPattern = (char*)transliterate(zMatchThis, sqlite3_value_bytes(argv[0])); + sqlite3_free(pCur->zPattern); + pCur->zPattern = zPattern; + if( zPattern==0 ){ + x.rc = SQLITE_NOMEM; + goto filter_exit; + } + nPattern = (int)strlen(zPattern); + if( zPattern[nPattern-1]=='*' ) nPattern--; + zSql = sqlite3_mprintf( + "SELECT id, word, rank, k1" + " FROM \"%w\".\"%w_vocab\"" + " WHERE langid=%d AND k2>=?1 AND k2zDbName, p->zTableName, iLang + ); + if( zSql==0 ){ + x.rc = SQLITE_NOMEM; + pStmt = 0; + goto filter_exit; + } + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + pCur->iLang = iLang; + x.pCur = pCur; + x.pStmt = pStmt; + x.zPattern = zPattern; + x.nPattern = nPattern; + x.pMatchStr3 = pMatchStr3; + x.iLang = iLang; + x.rc = rc; + x.pConfig3 = p->pConfig3; + if( x.rc==SQLITE_OK ){ + spellfix1RunQuery(&x, zPattern, nPattern); + } + + if( pCur->a ){ + qsort(pCur->a, pCur->nRow, sizeof(pCur->a[0]), spellfix1RowCompare); + pCur->iTop = iLimit; + pCur->iScope = iScope; + }else{ + x.rc = SQLITE_NOMEM; + } + +filter_exit: + sqlite3_finalize(pStmt); + editDist3FromStringDelete(pMatchStr3); + return x.rc; +} + +/* +** This version of xFilter handles a full-table scan case +*/ +static int spellfix1FilterForFullScan( + spellfix1_cursor *pCur, + int idxNum, + int argc, + sqlite3_value **argv +){ + int rc; + char *zSql; + spellfix1_vtab *pVTab = pCur->pVTab; + spellfix1ResetCursor(pCur); + zSql = sqlite3_mprintf( + "SELECT word, rank, NULL, langid, id FROM \"%w\".\"%w_vocab\"", + pVTab->zDbName, pVTab->zTableName); + if( zSql==0 ) return SQLITE_NOMEM; + rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pFullScan, 0); + sqlite3_free(zSql); + pCur->nRow = pCur->iRow = 0; + if( rc==SQLITE_OK ){ + rc = sqlite3_step(pCur->pFullScan); + if( rc==SQLITE_ROW ){ pCur->iRow = -1; rc = SQLITE_OK; } + if( rc==SQLITE_DONE ){ rc = SQLITE_OK; } + }else{ + pCur->iRow = 0; + } + return rc; +} + + +/* +** Called to "rewind" a cursor back to the beginning so that +** it starts its output over again. Always called at least once +** prior to any spellfix1Column, spellfix1Rowid, or spellfix1Eof call. +*/ +static int spellfix1Filter( + sqlite3_vtab_cursor *cur, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + spellfix1_cursor *pCur = (spellfix1_cursor *)cur; + int rc; + if( idxNum & 1 ){ + rc = spellfix1FilterForMatch(pCur, idxNum, argc, argv); + }else{ + rc = spellfix1FilterForFullScan(pCur, idxNum, argc, argv); + } + return rc; +} + + +/* +** Advance a cursor to its next row of output +*/ +static int spellfix1Next(sqlite3_vtab_cursor *cur){ + spellfix1_cursor *pCur = (spellfix1_cursor *)cur; + int rc = SQLITE_OK; + if( pCur->iRow < pCur->nRow ){ + if( pCur->pFullScan ){ + rc = sqlite3_step(pCur->pFullScan); + if( rc!=SQLITE_ROW ) pCur->iRow = pCur->nRow; + if( rc==SQLITE_ROW || rc==SQLITE_DONE ) rc = SQLITE_OK; + }else{ + pCur->iRow++; + } + } + return rc; +} + +/* +** Return TRUE if we are at the end-of-file +*/ +static int spellfix1Eof(sqlite3_vtab_cursor *cur){ + spellfix1_cursor *pCur = (spellfix1_cursor *)cur; + return pCur->iRow>=pCur->nRow; +} + +/* +** Return columns from the current row. +*/ +static int spellfix1Column( + sqlite3_vtab_cursor *cur, + sqlite3_context *ctx, + int i +){ + spellfix1_cursor *pCur = (spellfix1_cursor*)cur; + if( pCur->pFullScan ){ + if( i<=SPELLFIX_COL_LANGID ){ + sqlite3_result_value(ctx, sqlite3_column_value(pCur->pFullScan, i)); + }else{ + sqlite3_result_null(ctx); + } + return SQLITE_OK; + } + switch( i ){ + case SPELLFIX_COL_WORD: { + sqlite3_result_text(ctx, pCur->a[pCur->iRow].zWord, -1, SQLITE_STATIC); + break; + } + case SPELLFIX_COL_RANK: { + sqlite3_result_int(ctx, pCur->a[pCur->iRow].iRank); + break; + } + case SPELLFIX_COL_DISTANCE: { + sqlite3_result_int(ctx, pCur->a[pCur->iRow].iDistance); + break; + } + case SPELLFIX_COL_LANGID: { + sqlite3_result_int(ctx, pCur->iLang); + break; + } + case SPELLFIX_COL_SCORE: { + sqlite3_result_int(ctx, pCur->a[pCur->iRow].iScore); + break; + } + case SPELLFIX_COL_MATCHLEN: { + int iMatchlen = pCur->a[pCur->iRow].iMatchlen; + if( iMatchlen<0 ){ + int nPattern = (int)strlen(pCur->zPattern); + char *zWord = pCur->a[pCur->iRow].zWord; + int nWord = (int)strlen(zWord); + + if( nPattern>0 && pCur->zPattern[nPattern-1]=='*' ){ + char *zTranslit; + int res; + zTranslit = (char *)transliterate((unsigned char *)zWord, nWord); + if( !zTranslit ) return SQLITE_NOMEM; + res = editdist1(pCur->zPattern, zTranslit, &iMatchlen); + sqlite3_free(zTranslit); + if( res<0 ) return SQLITE_NOMEM; + iMatchlen = translen_to_charlen(zWord, nWord, iMatchlen); + }else{ + iMatchlen = utf8Charlen(zWord, nWord); + } + } + + sqlite3_result_int(ctx, iMatchlen); + break; + } + case SPELLFIX_COL_PHONEHASH: { + sqlite3_result_text(ctx, pCur->a[pCur->iRow].zHash, -1, SQLITE_STATIC); + break; + } + case SPELLFIX_COL_TOP: { + sqlite3_result_int(ctx, pCur->iTop); + break; + } + case SPELLFIX_COL_SCOPE: { + sqlite3_result_int(ctx, pCur->iScope); + break; + } + case SPELLFIX_COL_SRCHCNT: { + sqlite3_result_int(ctx, pCur->nSearch); + break; + } + default: { + sqlite3_result_null(ctx); + break; + } + } + return SQLITE_OK; +} + +/* +** The rowid. +*/ +static int spellfix1Rowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + spellfix1_cursor *pCur = (spellfix1_cursor*)cur; + if( pCur->pFullScan ){ + *pRowid = sqlite3_column_int64(pCur->pFullScan, 4); + }else{ + *pRowid = pCur->a[pCur->iRow].iRowid; + } + return SQLITE_OK; +} + +/* +** The xUpdate() method. +*/ +static int spellfix1Update( + sqlite3_vtab *pVTab, + int argc, + sqlite3_value **argv, + sqlite_int64 *pRowid +){ + int rc = SQLITE_OK; + sqlite3_int64 rowid, newRowid; + spellfix1_vtab *p = (spellfix1_vtab*)pVTab; + sqlite3 *db = p->db; + + if( argc==1 ){ + /* A delete operation on the rowid given by argv[0] */ + rowid = *pRowid = sqlite3_value_int64(argv[0]); + spellfix1DbExec(&rc, db, "DELETE FROM \"%w\".\"%w_vocab\" " + " WHERE id=%lld", + p->zDbName, p->zTableName, rowid); + }else{ + const unsigned char *zWord = sqlite3_value_text(argv[SPELLFIX_COL_WORD+2]); + int nWord = sqlite3_value_bytes(argv[SPELLFIX_COL_WORD+2]); + int iLang = sqlite3_value_int(argv[SPELLFIX_COL_LANGID+2]); + int iRank = sqlite3_value_int(argv[SPELLFIX_COL_RANK+2]); + const unsigned char *zSoundslike = + sqlite3_value_text(argv[SPELLFIX_COL_SOUNDSLIKE+2]); + int nSoundslike = sqlite3_value_bytes(argv[SPELLFIX_COL_SOUNDSLIKE+2]); + char *zK1, *zK2; + int i; + char c; + + if( zWord==0 ){ + /* Inserts of the form: INSERT INTO table(command) VALUES('xyzzy'); + ** cause zWord to be NULL, so we look at the "command" column to see + ** what special actions to take */ + const char *zCmd = + (const char*)sqlite3_value_text(argv[SPELLFIX_COL_COMMAND+2]); + if( zCmd==0 ){ + pVTab->zErrMsg = sqlite3_mprintf("%s.word may not be NULL", + p->zTableName); + return SQLITE_CONSTRAINT_NOTNULL; + } + if( strcmp(zCmd,"reset")==0 ){ + /* Reset the edit cost table (if there is one). */ + editDist3ConfigDelete(p->pConfig3); + p->pConfig3 = 0; + return SQLITE_OK; + } + if( strncmp(zCmd,"edit_cost_table=",16)==0 ){ + editDist3ConfigDelete(p->pConfig3); + p->pConfig3 = 0; + sqlite3_free(p->zCostTable); + p->zCostTable = spellfix1Dequote(zCmd+16); + if( p->zCostTable==0 ) return SQLITE_NOMEM; + if( p->zCostTable[0]==0 || sqlite3_stricmp(p->zCostTable,"null")==0 ){ + sqlite3_free(p->zCostTable); + p->zCostTable = 0; + } + return SQLITE_OK; + } + pVTab->zErrMsg = sqlite3_mprintf("unknown value for %s.command: \"%w\"", + p->zTableName, zCmd); + return SQLITE_ERROR; + } + if( iRank<1 ) iRank = 1; + if( zSoundslike ){ + zK1 = (char*)transliterate(zSoundslike, nSoundslike); + }else{ + zK1 = (char*)transliterate(zWord, nWord); + } + if( zK1==0 ) return SQLITE_NOMEM; + for(i=0; (c = zK1[i])!=0; i++){ + if( c>='A' && c<='Z' ) zK1[i] += 'a' - 'A'; + } + zK2 = (char*)phoneticHash((const unsigned char*)zK1, i); + if( zK2==0 ){ + sqlite3_free(zK1); + return SQLITE_NOMEM; + } + if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ + spellfix1DbExec(&rc, db, + "INSERT INTO \"%w\".\"%w_vocab\"(rank,langid,word,k1,k2) " + "VALUES(%d,%d,%Q,%Q,%Q)", + p->zDbName, p->zTableName, + iRank, iLang, zWord, zK1, zK2 + ); + *pRowid = sqlite3_last_insert_rowid(db); + }else{ + rowid = sqlite3_value_int64(argv[0]); + newRowid = *pRowid = sqlite3_value_int64(argv[1]); + spellfix1DbExec(&rc, db, + "UPDATE \"%w\".\"%w_vocab\" SET id=%lld, rank=%d, langid=%d," + " word=%Q, k1=%Q, k2=%Q WHERE id=%lld", + p->zDbName, p->zTableName, newRowid, iRank, iLang, + zWord, zK1, zK2, rowid + ); + } + sqlite3_free(zK1); + sqlite3_free(zK2); + } + return rc; +} + +/* +** Rename the spellfix1 table. +*/ +static int spellfix1Rename(sqlite3_vtab *pVTab, const char *zNew){ + spellfix1_vtab *p = (spellfix1_vtab*)pVTab; + sqlite3 *db = p->db; + int rc = SQLITE_OK; + char *zNewName = sqlite3_mprintf("%s", zNew); + if( zNewName==0 ){ + return SQLITE_NOMEM; + } + spellfix1DbExec(&rc, db, + "ALTER TABLE \"%w\".\"%w_vocab\" RENAME TO \"%w_vocab\"", + p->zDbName, p->zTableName, zNewName + ); + if( rc==SQLITE_OK ){ + sqlite3_free(p->zTableName); + p->zTableName = zNewName; + }else{ + sqlite3_free(zNewName); + } + return rc; +} + + +/* +** A virtual table module that provides fuzzy search. +*/ +static sqlite3_module spellfix1Module = { + 0, /* iVersion */ + spellfix1Create, /* xCreate - handle CREATE VIRTUAL TABLE */ + spellfix1Connect, /* xConnect - reconnected to an existing table */ + spellfix1BestIndex, /* xBestIndex - figure out how to do a query */ + spellfix1Disconnect, /* xDisconnect - close a connection */ + spellfix1Destroy, /* xDestroy - handle DROP TABLE */ + spellfix1Open, /* xOpen - open a cursor */ + spellfix1Close, /* xClose - close a cursor */ + spellfix1Filter, /* xFilter - configure scan constraints */ + spellfix1Next, /* xNext - advance a cursor */ + spellfix1Eof, /* xEof - check for end of scan */ + spellfix1Column, /* xColumn - read data */ + spellfix1Rowid, /* xRowid - read data */ + spellfix1Update, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + spellfix1Rename, /* xRename */ +}; + +/* +** Register the various functions and the virtual table. +*/ +static int spellfix1Register(sqlite3 *db){ + int rc = SQLITE_OK; + int i; + rc = sqlite3_create_function(db, "spellfix1_translit", 1, SQLITE_UTF8, 0, + transliterateSqlFunc, 0, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "spellfix1_editdist", 2, SQLITE_UTF8, 0, + editdistSqlFunc, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "spellfix1_phonehash", 1, SQLITE_UTF8, 0, + phoneticHashSqlFunc, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "spellfix1_scriptcode", 1, SQLITE_UTF8, 0, + scriptCodeSqlFunc, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_module(db, "spellfix1", &spellfix1Module, 0); + } + if( rc==SQLITE_OK ){ + rc = editDist3Install(db); + } + + /* Verify sanity of the translit[] table */ + for(i=0; i +#include + +/* +** Determine if this is running on a big-endian or little-endian +** processor +*/ +#if defined(i386) || defined(__i386__) || defined(_M_IX86)\ + || defined(__x86_64) || defined(__x86_64__) +# define TOTYPE_BIGENDIAN 0 +# define TOTYPE_LITTLEENDIAN 1 +#else + const int totype_one = 1; +# define TOTYPE_BIGENDIAN (*(char *)(&totype_one)==0) +# define TOTYPE_LITTLEENDIAN (*(char *)(&totype_one)==1) +#endif + +/* +** Constants for the largest and smallest possible 64-bit signed integers. +** These macros are designed to work correctly on both 32-bit and 64-bit +** compilers. +*/ +#ifndef LARGEST_INT64 +# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) +#endif + +#ifndef SMALLEST_INT64 +# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) +#endif + +/* +** Return TRUE if character c is a whitespace character +*/ +static int totypeIsspace(unsigned char c){ + return c==' ' || c=='\t' || c=='\n' || c=='\v' || c=='\f' || c=='\r'; +} + +/* +** Return TRUE if character c is a digit +*/ +static int totypeIsdigit(unsigned char c){ + return c>='0' && c<='9'; +} + +/* +** Compare the 19-character string zNum against the text representation +** value 2^63: 9223372036854775808. Return negative, zero, or positive +** if zNum is less than, equal to, or greater than the string. +** Note that zNum must contain exactly 19 characters. +** +** Unlike memcmp() this routine is guaranteed to return the difference +** in the values of the last digit if the only difference is in the +** last digit. So, for example, +** +** totypeCompare2pow63("9223372036854775800") +** +** will return -8. +*/ +static int totypeCompare2pow63(const char *zNum){ + int c = 0; + int i; + /* 012345678901234567 */ + const char *pow63 = "922337203685477580"; + for(i=0; c==0 && i<18; i++){ + c = (zNum[i]-pow63[i])*10; + } + if( c==0 ){ + c = zNum[18] - '8'; + } + return c; +} + +/* +** Convert zNum to a 64-bit signed integer. +** +** If the zNum value is representable as a 64-bit twos-complement +** integer, then write that value into *pNum and return 0. +** +** If zNum is exactly 9223372036854665808, return 2. This special +** case is broken out because while 9223372036854665808 cannot be a +** signed 64-bit integer, its negative -9223372036854665808 can be. +** +** If zNum is too big for a 64-bit integer and is not +** 9223372036854665808 or if zNum contains any non-numeric text, +** then return 1. +** +** The string is not necessarily zero-terminated. +*/ +static int totypeAtoi64(const char *zNum, sqlite3_int64 *pNum, int length){ + sqlite3_uint64 u = 0; + int neg = 0; /* assume positive */ + int i; + int c = 0; + int nonNum = 0; + const char *zStart; + const char *zEnd = zNum + length; + + while( zNum='0' && c<='9'; i++){ + u = u*10 + c - '0'; + } + if( u>LARGEST_INT64 ){ + *pNum = SMALLEST_INT64; + }else if( neg ){ + *pNum = -(sqlite3_int64)u; + }else{ + *pNum = (sqlite3_int64)u; + } + if( (c!=0 && &zNum[i]19 || nonNum ){ + /* zNum is empty or contains non-numeric text or is longer + ** than 19 digits (thus guaranteeing that it is too large) */ + return 1; + }else if( i<19 ){ + /* Less than 19 digits, so we know that it fits in 64 bits */ + assert( u<=LARGEST_INT64 ); + return 0; + }else{ + /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ + c = totypeCompare2pow63(zNum); + if( c<0 ){ + /* zNum is less than 9223372036854775808 so it fits */ + assert( u<=LARGEST_INT64 ); + return 0; + }else if( c>0 ){ + /* zNum is greater than 9223372036854775808 so it overflows */ + return 1; + }else{ + /* zNum is exactly 9223372036854775808. Fits if negative. The + ** special case 2 overflow if positive */ + assert( u-1==LARGEST_INT64 ); + assert( (*pNum)==SMALLEST_INT64 ); + return neg ? 0 : 2; + } + } +} + +/* +** The string z[] is an text representation of a real number. +** Convert this string to a double and write it into *pResult. +** +** The string is not necessarily zero-terminated. +** +** Return TRUE if the result is a valid real number (or integer) and FALSE +** if the string is empty or contains extraneous text. Valid numbers +** are in one of these formats: +** +** [+-]digits[E[+-]digits] +** [+-]digits.[digits][E[+-]digits] +** [+-].digits[E[+-]digits] +** +** Leading and trailing whitespace is ignored for the purpose of determining +** validity. +** +** If some prefix of the input string is a valid number, this routine +** returns FALSE but it still converts the prefix and writes the result +** into *pResult. +*/ +static int totypeAtoF(const char *z, double *pResult, int length){ + const char *zEnd = z + length; + /* sign * significand * (10 ^ (esign * exponent)) */ + int sign = 1; /* sign of significand */ + sqlite3_int64 s = 0; /* significand */ + int d = 0; /* adjust exponent for shifting decimal point */ + int esign = 1; /* sign of exponent */ + int e = 0; /* exponent */ + int eValid = 1; /* True exponent is either not used or is well-formed */ + double result; + int nDigits = 0; + int nonNum = 0; + + *pResult = 0.0; /* Default return value, in case of an error */ + + /* skip leading spaces */ + while( z=zEnd ) return 0; + + /* get sign of significand */ + if( *z=='-' ){ + sign = -1; + z++; + }else if( *z=='+' ){ + z++; + } + + /* skip leading zeroes */ + while( z=zEnd ) goto totype_atof_calc; + + /* if decimal point is present */ + if( *z=='.' ){ + z++; + /* copy digits from after decimal to significand + ** (decrease exponent by d to shift decimal right) */ + while( z=zEnd ) goto totype_atof_calc; + + /* if exponent is present */ + if( *z=='e' || *z=='E' ){ + z++; + eValid = 0; + if( z>=zEnd ) goto totype_atof_calc; + /* get sign of exponent */ + if( *z=='-' ){ + esign = -1; + z++; + }else if( *z=='+' ){ + z++; + } + /* copy digits to exponent */ + while( z0 ){ + while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10; + }else{ + while( !(s%10) && e>0 ) e--,s/=10; + } + + /* adjust the sign of significand */ + s = sign<0 ? -s : s; + + /* if exponent, scale significand as appropriate + ** and store in result. */ + if( e ){ + double scale = 1.0; + /* attempt to handle extremely small/large numbers better */ + if( e>307 && e<342 ){ + while( e%308 ) { scale *= 1.0e+1; e -= 1; } + if( esign<0 ){ + result = s / scale; + result /= 1.0e+308; + }else{ + result = s * scale; + result *= 1.0e+308; + } + }else if( e>=342 ){ + if( esign<0 ){ + result = 0.0*s; + }else{ + result = 1e308*1e308*s; /* Infinity */ + } + }else{ + /* 1.0e+22 is the largest power of 10 than can be + ** represented exactly. */ + while( e%22 ) { scale *= 1.0e+1; e -= 1; } + while( e>0 ) { scale *= 1.0e+22; e -= 22; } + if( esign<0 ){ + result = s / scale; + }else{ + result = s * scale; + } + } + } else { + result = (double)s; + } + } + + /* store the result */ + *pResult = result; + + /* return true if number and no extra non-whitespace chracters after */ + return z>=zEnd && nDigits>0 && eValid && nonNum==0; +} + +/* +** tointeger(X): If X is any value (integer, double, blob, or string) that +** can be losslessly converted into an integer, then make the conversion and +** return the result. Otherwise, return NULL. +*/ +static void tointegerFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + assert( argc==1 ); + (void)argc; + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_FLOAT: { + double rVal = sqlite3_value_double(argv[0]); + sqlite3_int64 iVal = (sqlite3_int64)rVal; + if( rVal==(double)iVal ){ + sqlite3_result_int64(context, iVal); + } + break; + } + case SQLITE_INTEGER: { + sqlite3_result_int64(context, sqlite3_value_int64(argv[0])); + break; + } + case SQLITE_BLOB: { + const unsigned char *zBlob = sqlite3_value_blob(argv[0]); + if( zBlob ){ + int nBlob = sqlite3_value_bytes(argv[0]); + if( nBlob==sizeof(sqlite3_int64) ){ + sqlite3_int64 iVal; + if( TOTYPE_BIGENDIAN ){ + int i; + unsigned char zBlobRev[sizeof(sqlite3_int64)]; + for(i=0; i +#include +#include +#if SQLITE_OS_UNIX +# include +#endif + +/* +** Forward declaration of objects used by this utility +*/ +typedef struct VLogLog VLogLog; +typedef struct VLogVfs VLogVfs; +typedef struct VLogFile VLogFile; + +/* There is a pair (an array of size 2) of the following objects for +** each database file being logged. The first contains the filename +** and is used to log I/O with the main database. The second has +** a NULL filename and is used to log I/O for the journal. Both +** out pointers are the same. +*/ +struct VLogLog { + VLogLog *pNext; /* Next in a list of all active logs */ + VLogLog **ppPrev; /* Pointer to this in the list */ + int nRef; /* Number of references to this object */ + int nFilename; /* Length of zFilename in bytes */ + char *zFilename; /* Name of database file. NULL for journal */ + FILE *out; /* Write information here */ +}; + +struct VLogVfs { + sqlite3_vfs base; /* VFS methods */ + sqlite3_vfs *pVfs; /* Parent VFS */ +}; + +struct VLogFile { + sqlite3_file base; /* IO methods */ + sqlite3_file *pReal; /* Underlying file handle */ + VLogLog *pLog; /* The log file for this file */ +}; + +#define REALVFS(p) (((VLogVfs*)(p))->pVfs) + +/* +** Methods for VLogFile +*/ +static int vlogClose(sqlite3_file*); +static int vlogRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int vlogWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); +static int vlogTruncate(sqlite3_file*, sqlite3_int64 size); +static int vlogSync(sqlite3_file*, int flags); +static int vlogFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int vlogLock(sqlite3_file*, int); +static int vlogUnlock(sqlite3_file*, int); +static int vlogCheckReservedLock(sqlite3_file*, int *pResOut); +static int vlogFileControl(sqlite3_file*, int op, void *pArg); +static int vlogSectorSize(sqlite3_file*); +static int vlogDeviceCharacteristics(sqlite3_file*); + +/* +** Methods for VLogVfs +*/ +static int vlogOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int vlogDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int vlogAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int vlogFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); +static void *vlogDlOpen(sqlite3_vfs*, const char *zFilename); +static void vlogDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*vlogDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void); +static void vlogDlClose(sqlite3_vfs*, void*); +static int vlogRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int vlogSleep(sqlite3_vfs*, int microseconds); +static int vlogCurrentTime(sqlite3_vfs*, double*); +static int vlogGetLastError(sqlite3_vfs*, int, char *); +static int vlogCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); + +static VLogVfs vlog_vfs = { + { + 1, /* iVersion */ + 0, /* szOsFile (set by register_vlog()) */ + 1024, /* mxPathname */ + 0, /* pNext */ + "vfslog", /* zName */ + 0, /* pAppData */ + vlogOpen, /* xOpen */ + vlogDelete, /* xDelete */ + vlogAccess, /* xAccess */ + vlogFullPathname, /* xFullPathname */ + vlogDlOpen, /* xDlOpen */ + vlogDlError, /* xDlError */ + vlogDlSym, /* xDlSym */ + vlogDlClose, /* xDlClose */ + vlogRandomness, /* xRandomness */ + vlogSleep, /* xSleep */ + vlogCurrentTime, /* xCurrentTime */ + vlogGetLastError, /* xGetLastError */ + vlogCurrentTimeInt64 /* xCurrentTimeInt64 */ + }, + 0 +}; + +static sqlite3_io_methods vlog_io_methods = { + 1, /* iVersion */ + vlogClose, /* xClose */ + vlogRead, /* xRead */ + vlogWrite, /* xWrite */ + vlogTruncate, /* xTruncate */ + vlogSync, /* xSync */ + vlogFileSize, /* xFileSize */ + vlogLock, /* xLock */ + vlogUnlock, /* xUnlock */ + vlogCheckReservedLock, /* xCheckReservedLock */ + vlogFileControl, /* xFileControl */ + vlogSectorSize, /* xSectorSize */ + vlogDeviceCharacteristics, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0 /* xShmUnmap */ +}; + +#if SQLITE_OS_UNIX && !defined(NO_GETTOD) +#include +static sqlite3_uint64 vlog_time(){ + struct timeval sTime; + gettimeofday(&sTime, 0); + return sTime.tv_usec + (sqlite3_uint64)sTime.tv_sec * 1000000; +} +#elif SQLITE_OS_WIN +#include +#include +static sqlite3_uint64 vlog_time(){ + FILETIME ft; + sqlite3_uint64 u64time = 0; + + GetSystemTimeAsFileTime(&ft); + + u64time |= ft.dwHighDateTime; + u64time <<= 32; + u64time |= ft.dwLowDateTime; + + /* ft is 100-nanosecond intervals, we want microseconds */ + return u64time /(sqlite3_uint64)10; +} +#else +static sqlite3_uint64 vlog_time(){ + return 0; +} +#endif + + +/* +** Write a message to the log file +*/ +static void vlogLogPrint( + VLogLog *pLog, /* The log file to write into */ + sqlite3_int64 tStart, /* Start time of system call */ + sqlite3_int64 tElapse, /* Elapse time of system call */ + const char *zOp, /* Type of system call */ + sqlite3_int64 iArg1, /* First argument */ + sqlite3_int64 iArg2, /* Second argument */ + const char *zArg3, /* Third argument */ + int iRes /* Result */ +){ + char z1[40], z2[40], z3[70]; + if( pLog==0 ) return; + if( iArg1>=0 ){ + sqlite3_snprintf(sizeof(z1), z1, "%lld", iArg1); + }else{ + z1[0] = 0; + } + if( iArg2>=0 ){ + sqlite3_snprintf(sizeof(z2), z2, "%lld", iArg2); + }else{ + z2[0] = 0; + } + if( zArg3 ){ + sqlite3_snprintf(sizeof(z3), z3, "\"%s\"", zArg3); + }else{ + z3[0] = 0; + } + fprintf(pLog->out,"%lld,%lld,%s,%d,%s,%s,%s,%d\n", + tStart, tElapse, zOp, pLog->zFilename==0, z1, z2, z3, iRes); +} + +/* +** List of all active log connections. Protected by the master mutex. +*/ +static VLogLog *allLogs = 0; + +/* +** Close a VLogLog object +*/ +static void vlogLogClose(VLogLog *p){ + if( p ){ + sqlite3_mutex *pMutex; + p->nRef--; + if( p->nRef>0 || p->zFilename==0 ) return; + pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); + sqlite3_mutex_enter(pMutex); + *p->ppPrev = p->pNext; + if( p->pNext ) p->pNext->ppPrev = p->ppPrev; + sqlite3_mutex_leave(pMutex); + fclose(p->out); + sqlite3_free(p); + } +} + +/* +** Open a VLogLog object on the given file +*/ +static VLogLog *vlogLogOpen(const char *zFilename){ + int nName = (int)strlen(zFilename); + int isJournal = 0; + sqlite3_mutex *pMutex; + VLogLog *pLog, *pTemp; + sqlite3_int64 tNow = 0; + if( nName>4 && strcmp(zFilename+nName-4,"-wal")==0 ){ + return 0; /* Do not log wal files */ + }else + if( nName>8 && strcmp(zFilename+nName-8,"-journal")==0 ){ + nName -= 8; + isJournal = 1; + }else if( nName>12 + && sqlite3_strglob("-mj??????9??", zFilename+nName-12)==0 ){ + return 0; /* Do not log master journal files */ + } + pTemp = sqlite3_malloc( sizeof(*pLog)*2 + nName + 60 ); + if( pTemp==0 ) return 0; + pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); + sqlite3_mutex_enter(pMutex); + for(pLog=allLogs; pLog; pLog=pLog->pNext){ + if( pLog->nFilename==nName && !memcmp(pLog->zFilename, zFilename, nName) ){ + break; + } + } + if( pLog==0 ){ + pLog = pTemp; + pTemp = 0; + memset(pLog, 0, sizeof(*pLog)*2); + pLog->zFilename = (char*)&pLog[2]; + tNow = vlog_time(); + sqlite3_snprintf(nName+60, pLog->zFilename, "%.*s-debuglog-%lld", + nName, zFilename, tNow); + pLog->out = fopen(pLog->zFilename, "a"); + if( pLog->out==0 ){ + sqlite3_mutex_leave(pMutex); + sqlite3_free(pLog); + return 0; + } + pLog->nFilename = nName; + pLog[1].out = pLog[0].out; + pLog->ppPrev = &allLogs; + if( allLogs ) allLogs->ppPrev = &pLog->pNext; + pLog->pNext = allLogs; + allLogs = pLog; + } + sqlite3_mutex_leave(pMutex); + if( pTemp ){ + sqlite3_free(pTemp); + }else{ +#if SQLITE_OS_UNIX + char zHost[200]; + zHost[0] = 0; + gethostname(zHost, sizeof(zHost)-1); + zHost[sizeof(zHost)-1] = 0; + vlogLogPrint(pLog, tNow, 0, "IDENT", getpid(), -1, zHost, 0); +#endif + } + if( pLog && isJournal ) pLog++; + pLog->nRef++; + return pLog; +} + + +/* +** Close an vlog-file. +*/ +static int vlogClose(sqlite3_file *pFile){ + sqlite3_uint64 tStart, tElapse; + int rc = SQLITE_OK; + VLogFile *p = (VLogFile *)pFile; + + tStart = vlog_time(); + if( p->pReal->pMethods ){ + rc = p->pReal->pMethods->xClose(p->pReal); + } + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "CLOSE", -1, -1, 0, rc); + vlogLogClose(p->pLog); + return rc; +} + +/* +** Compute signature for a block of content. +** +** For blocks of 16 or fewer bytes, the signature is just a hex dump of +** the entire block. +** +** For blocks of more than 16 bytes, the signature is a hex dump of the +** first 8 bytes followed by a 64-bit has of the entire block. +*/ +static void vlogSignature(unsigned char *p, int n, char *zCksum){ + unsigned int s0 = 0, s1 = 0; + unsigned int *pI; + int i; + if( n<=16 ){ + for(i=0; ipReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst); + tElapse = vlog_time() - tStart; + if( rc==SQLITE_OK ){ + vlogSignature(zBuf, iAmt, zSig); + }else{ + zSig[0] = 0; + } + vlogLogPrint(p->pLog, tStart, tElapse, "READ", iAmt, iOfst, zSig, rc); + if( rc==SQLITE_OK + && p->pLog + && p->pLog->zFilename + && iOfst<=24 + && iOfst+iAmt>=28 + ){ + unsigned char *x = ((unsigned char*)zBuf)+(24-iOfst); + unsigned iCtr; + iCtr = (x[0]<<24) + (x[1]<<16) + (x[2]<<8) + x[3]; + vlogLogPrint(p->pLog, tStart, 0, "CHNGCTR-READ", iCtr, -1, 0, 0); + } + return rc; +} + +/* +** Write data to an vlog-file. +*/ +static int vlogWrite( + sqlite3_file *pFile, + const void *z, + int iAmt, + sqlite_int64 iOfst +){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogFile *p = (VLogFile *)pFile; + char zSig[40]; + + tStart = vlog_time(); + vlogSignature((unsigned char*)z, iAmt, zSig); + rc = p->pReal->pMethods->xWrite(p->pReal, z, iAmt, iOfst); + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "WRITE", iAmt, iOfst, zSig, rc); + if( rc==SQLITE_OK + && p->pLog + && p->pLog->zFilename + && iOfst<=24 + && iOfst+iAmt>=28 + ){ + unsigned char *x = ((unsigned char*)z)+(24-iOfst); + unsigned iCtr; + iCtr = (x[0]<<24) + (x[1]<<16) + (x[2]<<8) + x[3]; + vlogLogPrint(p->pLog, tStart, 0, "CHNGCTR-WRITE", iCtr, -1, 0, 0); + } + return rc; +} + +/* +** Truncate an vlog-file. +*/ +static int vlogTruncate(sqlite3_file *pFile, sqlite_int64 size){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogFile *p = (VLogFile *)pFile; + tStart = vlog_time(); + rc = p->pReal->pMethods->xTruncate(p->pReal, size); + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "TRUNCATE", size, -1, 0, rc); + return rc; +} + +/* +** Sync an vlog-file. +*/ +static int vlogSync(sqlite3_file *pFile, int flags){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogFile *p = (VLogFile *)pFile; + tStart = vlog_time(); + rc = p->pReal->pMethods->xSync(p->pReal, flags); + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "SYNC", flags, -1, 0, rc); + return rc; +} + +/* +** Return the current file-size of an vlog-file. +*/ +static int vlogFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogFile *p = (VLogFile *)pFile; + tStart = vlog_time(); + rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "FILESIZE", *pSize, -1, 0, rc); + return rc; +} + +/* +** Lock an vlog-file. +*/ +static int vlogLock(sqlite3_file *pFile, int eLock){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogFile *p = (VLogFile *)pFile; + tStart = vlog_time(); + rc = p->pReal->pMethods->xLock(p->pReal, eLock); + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "LOCK", eLock, -1, 0, rc); + return rc; +} + +/* +** Unlock an vlog-file. +*/ +static int vlogUnlock(sqlite3_file *pFile, int eLock){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogFile *p = (VLogFile *)pFile; + tStart = vlog_time(); + rc = p->pReal->pMethods->xUnlock(p->pReal, eLock); + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "UNLOCK", eLock, -1, 0, rc); + return rc; +} + +/* +** Check if another file-handle holds a RESERVED lock on an vlog-file. +*/ +static int vlogCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogFile *p = (VLogFile *)pFile; + tStart = vlog_time(); + rc = p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "CHECKRESERVEDLOCK", + *pResOut, -1, "", rc); + return rc; +} + +/* +** File control method. For custom operations on an vlog-file. +*/ +static int vlogFileControl(sqlite3_file *pFile, int op, void *pArg){ + VLogFile *p = (VLogFile *)pFile; + sqlite3_uint64 tStart, tElapse; + int rc; + tStart = vlog_time(); + rc = p->pReal->pMethods->xFileControl(p->pReal, op, pArg); + if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){ + *(char**)pArg = sqlite3_mprintf("vlog/%z", *(char**)pArg); + } + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "FILECONTROL", op, -1, 0, rc); + return rc; +} + +/* +** Return the sector-size in bytes for an vlog-file. +*/ +static int vlogSectorSize(sqlite3_file *pFile){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogFile *p = (VLogFile *)pFile; + tStart = vlog_time(); + rc = p->pReal->pMethods->xSectorSize(p->pReal); + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "SECTORSIZE", -1, -1, 0, rc); + return rc; +} + +/* +** Return the device characteristic flags supported by an vlog-file. +*/ +static int vlogDeviceCharacteristics(sqlite3_file *pFile){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogFile *p = (VLogFile *)pFile; + tStart = vlog_time(); + rc = p->pReal->pMethods->xDeviceCharacteristics(p->pReal); + tElapse = vlog_time() - tStart; + vlogLogPrint(p->pLog, tStart, tElapse, "DEVCHAR", -1, -1, 0, rc); + return rc; +} + + +/* +** Open an vlog file handle. +*/ +static int vlogOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + sqlite3_uint64 tStart, tElapse; + sqlite3_int64 iArg2; + VLogFile *p = (VLogFile*)pFile; + + p->pReal = (sqlite3_file*)&p[1]; + if( (flags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){ + p->pLog = vlogLogOpen(zName); + }else{ + p->pLog = 0; + } + tStart = vlog_time(); + rc = REALVFS(pVfs)->xOpen(REALVFS(pVfs), zName, p->pReal, flags, pOutFlags); + tElapse = vlog_time() - tStart; + iArg2 = pOutFlags ? *pOutFlags : -1; + vlogLogPrint(p->pLog, tStart, tElapse, "OPEN", flags, iArg2, 0, rc); + if( rc==SQLITE_OK ){ + pFile->pMethods = &vlog_io_methods; + }else{ + if( p->pLog ) vlogLogClose(p->pLog); + p->pLog = 0; + } + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int vlogDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogLog *pLog; + tStart = vlog_time(); + rc = REALVFS(pVfs)->xDelete(REALVFS(pVfs), zPath, dirSync); + tElapse = vlog_time() - tStart; + pLog = vlogLogOpen(zPath); + vlogLogPrint(pLog, tStart, tElapse, "DELETE", dirSync, -1, 0, rc); + vlogLogClose(pLog); + return rc; +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int vlogAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + int rc; + sqlite3_uint64 tStart, tElapse; + VLogLog *pLog; + tStart = vlog_time(); + rc = REALVFS(pVfs)->xAccess(REALVFS(pVfs), zPath, flags, pResOut); + tElapse = vlog_time() - tStart; + pLog = vlogLogOpen(zPath); + vlogLogPrint(pLog, tStart, tElapse, "ACCESS", flags, *pResOut, 0, rc); + vlogLogClose(pLog); + return rc; +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (INST_MAX_PATHNAME+1) bytes. +*/ +static int vlogFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + return REALVFS(pVfs)->xFullPathname(REALVFS(pVfs), zPath, nOut, zOut); +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *vlogDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return REALVFS(pVfs)->xDlOpen(REALVFS(pVfs), zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void vlogDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + REALVFS(pVfs)->xDlError(REALVFS(pVfs), nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*vlogDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return REALVFS(pVfs)->xDlSym(REALVFS(pVfs), p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void vlogDlClose(sqlite3_vfs *pVfs, void *pHandle){ + REALVFS(pVfs)->xDlClose(REALVFS(pVfs), pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int vlogRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return REALVFS(pVfs)->xRandomness(REALVFS(pVfs), nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int vlogSleep(sqlite3_vfs *pVfs, int nMicro){ + return REALVFS(pVfs)->xSleep(REALVFS(pVfs), nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int vlogCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + return REALVFS(pVfs)->xCurrentTime(REALVFS(pVfs), pTimeOut); +} + +static int vlogGetLastError(sqlite3_vfs *pVfs, int a, char *b){ + return REALVFS(pVfs)->xGetLastError(REALVFS(pVfs), a, b); +} +static int vlogCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){ + return REALVFS(pVfs)->xCurrentTimeInt64(REALVFS(pVfs), p); +} + +/* +** Register debugvfs as the default VFS for this process. +*/ +int sqlite3_register_vfslog(const char *zArg){ + vlog_vfs.pVfs = sqlite3_vfs_find(0); + vlog_vfs.base.szOsFile = sizeof(VLogFile) + vlog_vfs.pVfs->szOsFile; + return sqlite3_vfs_register(&vlog_vfs.base, 1); +} diff --git a/components/external/SQLite-3.8.1/ext/misc/vtshim.c b/components/external/SQLite-3.8.1/ext/misc/vtshim.c new file mode 100644 index 0000000000000000000000000000000000000000..01348e8d3eebbfe3161c0b55dd6cbc3d448ea161 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/misc/vtshim.c @@ -0,0 +1,551 @@ +/* +** 2013-06-12 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** A shim that sits between the SQLite virtual table interface and +** runtimes with garbage collector based memory management. +*/ +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 +#include +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* Forward references */ +typedef struct vtshim_aux vtshim_aux; +typedef struct vtshim_vtab vtshim_vtab; +typedef struct vtshim_cursor vtshim_cursor; + + +/* The vtshim_aux argument is the auxiliary parameter that is passed +** into sqlite3_create_module_v2(). +*/ +struct vtshim_aux { + void *pChildAux; /* pAux for child virtual tables */ + void (*xChildDestroy)(void*); /* Destructor for pChildAux */ + sqlite3_module *pMod; /* Methods for child virtual tables */ + sqlite3 *db; /* The database to which we are attached */ + char *zName; /* Name of the module */ + int bDisposed; /* True if disposed */ + vtshim_vtab *pAllVtab; /* List of all vtshim_vtab objects */ + sqlite3_module sSelf; /* Methods used by this shim */ +}; + +/* A vtshim virtual table object */ +struct vtshim_vtab { + sqlite3_vtab base; /* Base class - must be first */ + sqlite3_vtab *pChild; /* Child virtual table */ + vtshim_aux *pAux; /* Pointer to vtshim_aux object */ + vtshim_cursor *pAllCur; /* List of all cursors */ + vtshim_vtab **ppPrev; /* Previous on list */ + vtshim_vtab *pNext; /* Next on list */ +}; + +/* A vtshim cursor object */ +struct vtshim_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + sqlite3_vtab_cursor *pChild; /* Cursor generated by the managed subclass */ + vtshim_cursor **ppPrev; /* Previous on list of all cursors */ + vtshim_cursor *pNext; /* Next on list of all cursors */ +}; + +/* Macro used to copy the child vtable error message to outer vtable */ +#define VTSHIM_COPY_ERRMSG() \ + do { \ + sqlite3_free(pVtab->base.zErrMsg); \ + pVtab->base.zErrMsg = sqlite3_mprintf("%s", pVtab->pChild->zErrMsg); \ + } while (0) + +/* Methods for the vtshim module */ +static int vtshimCreate( + sqlite3 *db, + void *ppAux, + int argc, + const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + vtshim_aux *pAux = (vtshim_aux*)ppAux; + vtshim_vtab *pNew; + int rc; + + assert( db==pAux->db ); + if( pAux->bDisposed ){ + if( pzErr ){ + *pzErr = sqlite3_mprintf("virtual table was disposed: \"%s\"", + pAux->zName); + } + return SQLITE_ERROR; + } + pNew = sqlite3_malloc( sizeof(*pNew) ); + *ppVtab = (sqlite3_vtab*)pNew; + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + rc = pAux->pMod->xCreate(db, pAux->pChildAux, argc, argv, + &pNew->pChild, pzErr); + if( rc ){ + sqlite3_free(pNew); + *ppVtab = 0; + } + pNew->pAux = pAux; + pNew->ppPrev = &pAux->pAllVtab; + pNew->pNext = pAux->pAllVtab; + if( pAux->pAllVtab ) pAux->pAllVtab->ppPrev = &pNew->pNext; + pAux->pAllVtab = pNew; + return rc; +} + +static int vtshimConnect( + sqlite3 *db, + void *ppAux, + int argc, + const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + vtshim_aux *pAux = (vtshim_aux*)ppAux; + vtshim_vtab *pNew; + int rc; + + assert( db==pAux->db ); + if( pAux->bDisposed ){ + if( pzErr ){ + *pzErr = sqlite3_mprintf("virtual table was disposed: \"%s\"", + pAux->zName); + } + return SQLITE_ERROR; + } + pNew = sqlite3_malloc( sizeof(*pNew) ); + *ppVtab = (sqlite3_vtab*)pNew; + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + rc = pAux->pMod->xConnect(db, pAux->pChildAux, argc, argv, + &pNew->pChild, pzErr); + if( rc ){ + sqlite3_free(pNew); + *ppVtab = 0; + } + pNew->pAux = pAux; + pNew->ppPrev = &pAux->pAllVtab; + pNew->pNext = pAux->pAllVtab; + if( pAux->pAllVtab ) pAux->pAllVtab->ppPrev = &pNew->pNext; + pAux->pAllVtab = pNew; + return rc; +} + +static int vtshimBestIndex( + sqlite3_vtab *pBase, + sqlite3_index_info *pIdxInfo +){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xBestIndex(pVtab->pChild, pIdxInfo); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimDisconnect(sqlite3_vtab *pBase){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc = SQLITE_OK; + if( !pAux->bDisposed ){ + rc = pAux->pMod->xDisconnect(pVtab->pChild); + } + if( pVtab->pNext ) pVtab->pNext->ppPrev = pVtab->ppPrev; + *pVtab->ppPrev = pVtab->pNext; + sqlite3_free(pVtab); + return rc; +} + +static int vtshimDestroy(sqlite3_vtab *pBase){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc = SQLITE_OK; + if( !pAux->bDisposed ){ + rc = pAux->pMod->xDestroy(pVtab->pChild); + } + if( pVtab->pNext ) pVtab->pNext->ppPrev = pVtab->ppPrev; + *pVtab->ppPrev = pVtab->pNext; + sqlite3_free(pVtab); + return rc; +} + +static int vtshimOpen(sqlite3_vtab *pBase, sqlite3_vtab_cursor **ppCursor){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + vtshim_cursor *pCur; + int rc; + *ppCursor = 0; + if( pAux->bDisposed ) return SQLITE_ERROR; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + rc = pAux->pMod->xOpen(pVtab->pChild, &pCur->pChild); + if( rc ){ + sqlite3_free(pCur); + VTSHIM_COPY_ERRMSG(); + return rc; + } + pCur->pChild->pVtab = pVtab->pChild; + *ppCursor = &pCur->base; + pCur->ppPrev = &pVtab->pAllCur; + if( pVtab->pAllCur ) pVtab->pAllCur->ppPrev = &pCur->pNext; + pCur->pNext = pVtab->pAllCur; + pVtab->pAllCur = pCur; + return SQLITE_OK; +} + +static int vtshimClose(sqlite3_vtab_cursor *pX){ + vtshim_cursor *pCur = (vtshim_cursor*)pX; + vtshim_vtab *pVtab = (vtshim_vtab*)pCur->base.pVtab; + vtshim_aux *pAux = pVtab->pAux; + int rc = SQLITE_OK; + if( !pAux->bDisposed ){ + rc = pAux->pMod->xClose(pCur->pChild); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + } + if( pCur->pNext ) pCur->pNext->ppPrev = pCur->ppPrev; + *pCur->ppPrev = pCur->pNext; + sqlite3_free(pCur); + return rc; +} + +static int vtshimFilter( + sqlite3_vtab_cursor *pX, + int idxNum, + const char *idxStr, + int argc, + sqlite3_value **argv +){ + vtshim_cursor *pCur = (vtshim_cursor*)pX; + vtshim_vtab *pVtab = (vtshim_vtab*)pCur->base.pVtab; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xFilter(pCur->pChild, idxNum, idxStr, argc, argv); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimNext(sqlite3_vtab_cursor *pX){ + vtshim_cursor *pCur = (vtshim_cursor*)pX; + vtshim_vtab *pVtab = (vtshim_vtab*)pCur->base.pVtab; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xNext(pCur->pChild); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimEof(sqlite3_vtab_cursor *pX){ + vtshim_cursor *pCur = (vtshim_cursor*)pX; + vtshim_vtab *pVtab = (vtshim_vtab*)pCur->base.pVtab; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return 1; + rc = pAux->pMod->xEof(pCur->pChild); + VTSHIM_COPY_ERRMSG(); + return rc; +} + +static int vtshimColumn(sqlite3_vtab_cursor *pX, sqlite3_context *ctx, int i){ + vtshim_cursor *pCur = (vtshim_cursor*)pX; + vtshim_vtab *pVtab = (vtshim_vtab*)pCur->base.pVtab; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xColumn(pCur->pChild, ctx, i); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimRowid(sqlite3_vtab_cursor *pX, sqlite3_int64 *pRowid){ + vtshim_cursor *pCur = (vtshim_cursor*)pX; + vtshim_vtab *pVtab = (vtshim_vtab*)pCur->base.pVtab; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xRowid(pCur->pChild, pRowid); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimUpdate( + sqlite3_vtab *pBase, + int argc, + sqlite3_value **argv, + sqlite3_int64 *pRowid +){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xUpdate(pVtab->pChild, argc, argv, pRowid); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimBegin(sqlite3_vtab *pBase){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xBegin(pVtab->pChild); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimSync(sqlite3_vtab *pBase){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xSync(pVtab->pChild); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimCommit(sqlite3_vtab *pBase){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xCommit(pVtab->pChild); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimRollback(sqlite3_vtab *pBase){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xRollback(pVtab->pChild); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimFindFunction( + sqlite3_vtab *pBase, + int nArg, + const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg +){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return 0; + rc = pAux->pMod->xFindFunction(pVtab->pChild, nArg, zName, pxFunc, ppArg); + VTSHIM_COPY_ERRMSG(); + return rc; +} + +static int vtshimRename(sqlite3_vtab *pBase, const char *zNewName){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xRename(pVtab->pChild, zNewName); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimSavepoint(sqlite3_vtab *pBase, int n){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xSavepoint(pVtab->pChild, n); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimRelease(sqlite3_vtab *pBase, int n){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xRelease(pVtab->pChild, n); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +static int vtshimRollbackTo(sqlite3_vtab *pBase, int n){ + vtshim_vtab *pVtab = (vtshim_vtab*)pBase; + vtshim_aux *pAux = pVtab->pAux; + int rc; + if( pAux->bDisposed ) return SQLITE_ERROR; + rc = pAux->pMod->xRollbackTo(pVtab->pChild, n); + if( rc!=SQLITE_OK ){ + VTSHIM_COPY_ERRMSG(); + } + return rc; +} + +/* The destructor function for a disposible module */ +static void vtshimAuxDestructor(void *pXAux){ + vtshim_aux *pAux = (vtshim_aux*)pXAux; + assert( pAux->pAllVtab==0 ); + if( !pAux->bDisposed && pAux->xChildDestroy ){ + pAux->xChildDestroy(pAux->pChildAux); + pAux->xChildDestroy = 0; + } + sqlite3_free(pAux->zName); + sqlite3_free(pAux->pMod); + sqlite3_free(pAux); +} + +static int vtshimCopyModule( + const sqlite3_module *pMod, /* Source module to be copied */ + sqlite3_module **ppMod /* Destination for copied module */ +){ + sqlite3_module *p; + if( !pMod || !ppMod ) return SQLITE_ERROR; + p = sqlite3_malloc( sizeof(*p) ); + if( p==0 ) return SQLITE_NOMEM; + memcpy(p, pMod, sizeof(*p)); + *ppMod = p; + return SQLITE_OK; +} + +#ifdef _WIN32 +__declspec(dllexport) +#endif +void *sqlite3_create_disposable_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +){ + vtshim_aux *pAux; + sqlite3_module *pMod; + int rc; + pAux = sqlite3_malloc( sizeof(*pAux) ); + if( pAux==0 ){ + if( xDestroy ) xDestroy(pClientData); + return 0; + } + rc = vtshimCopyModule(p, &pMod); + if( rc!=SQLITE_OK ){ + sqlite3_free(pAux); + return 0; + } + pAux->pChildAux = pClientData; + pAux->xChildDestroy = xDestroy; + pAux->pMod = pMod; + pAux->db = db; + pAux->zName = sqlite3_mprintf("%s", zName); + pAux->bDisposed = 0; + pAux->pAllVtab = 0; + pAux->sSelf.iVersion = p->iVersion<=2 ? p->iVersion : 2; + pAux->sSelf.xCreate = p->xCreate ? vtshimCreate : 0; + pAux->sSelf.xConnect = p->xConnect ? vtshimConnect : 0; + pAux->sSelf.xBestIndex = p->xBestIndex ? vtshimBestIndex : 0; + pAux->sSelf.xDisconnect = p->xDisconnect ? vtshimDisconnect : 0; + pAux->sSelf.xDestroy = p->xDestroy ? vtshimDestroy : 0; + pAux->sSelf.xOpen = p->xOpen ? vtshimOpen : 0; + pAux->sSelf.xClose = p->xClose ? vtshimClose : 0; + pAux->sSelf.xFilter = p->xFilter ? vtshimFilter : 0; + pAux->sSelf.xNext = p->xNext ? vtshimNext : 0; + pAux->sSelf.xEof = p->xEof ? vtshimEof : 0; + pAux->sSelf.xColumn = p->xColumn ? vtshimColumn : 0; + pAux->sSelf.xRowid = p->xRowid ? vtshimRowid : 0; + pAux->sSelf.xUpdate = p->xUpdate ? vtshimUpdate : 0; + pAux->sSelf.xBegin = p->xBegin ? vtshimBegin : 0; + pAux->sSelf.xSync = p->xSync ? vtshimSync : 0; + pAux->sSelf.xCommit = p->xCommit ? vtshimCommit : 0; + pAux->sSelf.xRollback = p->xRollback ? vtshimRollback : 0; + pAux->sSelf.xFindFunction = p->xFindFunction ? vtshimFindFunction : 0; + pAux->sSelf.xRename = p->xRename ? vtshimRename : 0; + if( p->iVersion>=2 ){ + pAux->sSelf.xSavepoint = p->xSavepoint ? vtshimSavepoint : 0; + pAux->sSelf.xRelease = p->xRelease ? vtshimRelease : 0; + pAux->sSelf.xRollbackTo = p->xRollbackTo ? vtshimRollbackTo : 0; + }else{ + pAux->sSelf.xSavepoint = 0; + pAux->sSelf.xRelease = 0; + pAux->sSelf.xRollbackTo = 0; + } + rc = sqlite3_create_module_v2(db, zName, &pAux->sSelf, + pAux, vtshimAuxDestructor); + return rc==SQLITE_OK ? (void*)pAux : 0; +} + +#ifdef _WIN32 +__declspec(dllexport) +#endif +void sqlite3_dispose_module(void *pX){ + vtshim_aux *pAux = (vtshim_aux*)pX; + if( !pAux->bDisposed ){ + vtshim_vtab *pVtab; + vtshim_cursor *pCur; + for(pVtab=pAux->pAllVtab; pVtab; pVtab=pVtab->pNext){ + for(pCur=pVtab->pAllCur; pCur; pCur=pCur->pNext){ + pAux->pMod->xClose(pCur->pChild); + } + pAux->pMod->xDisconnect(pVtab->pChild); + } + pAux->bDisposed = 1; + if( pAux->xChildDestroy ){ + pAux->xChildDestroy(pAux->pChildAux); + pAux->xChildDestroy = 0; + } + } +} + + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_vtshim_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi); + return SQLITE_OK; +} diff --git a/components/external/SQLite-3.8.1/ext/misc/wholenumber.c b/components/external/SQLite-3.8.1/ext/misc/wholenumber.c new file mode 100644 index 0000000000000000000000000000000000000000..63369c6ac474e1cae1b4309f78536166ebc716a5 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/misc/wholenumber.c @@ -0,0 +1,274 @@ +/* +** 2011 April 02 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements a virtual table that returns the whole numbers +** between 1 and 4294967295, inclusive. +** +** Example: +** +** CREATE VIRTUAL TABLE nums USING wholenumber; +** SELECT value FROM nums WHERE value<10; +** +** Results in: +** +** 1 2 3 4 5 6 7 8 9 +*/ +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 +#include +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + + +/* A wholenumber cursor object */ +typedef struct wholenumber_cursor wholenumber_cursor; +struct wholenumber_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + sqlite3_int64 iValue; /* Current value */ + sqlite3_int64 mxValue; /* Maximum value */ +}; + +/* Methods for the wholenumber module */ +static int wholenumberConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + sqlite3_vtab *pNew; + pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) ); + if( pNew==0 ) return SQLITE_NOMEM; + sqlite3_declare_vtab(db, "CREATE TABLE x(value)"); + memset(pNew, 0, sizeof(*pNew)); + return SQLITE_OK; +} +/* Note that for this virtual table, the xCreate and xConnect +** methods are identical. */ + +static int wholenumberDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} +/* The xDisconnect and xDestroy methods are also the same */ + + +/* +** Open a new wholenumber cursor. +*/ +static int wholenumberOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ + wholenumber_cursor *pCur; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Close a wholenumber cursor. +*/ +static int wholenumberClose(sqlite3_vtab_cursor *cur){ + sqlite3_free(cur); + return SQLITE_OK; +} + + +/* +** Advance a cursor to its next row of output +*/ +static int wholenumberNext(sqlite3_vtab_cursor *cur){ + wholenumber_cursor *pCur = (wholenumber_cursor*)cur; + pCur->iValue++; + return SQLITE_OK; +} + +/* +** Return the value associated with a wholenumber. +*/ +static int wholenumberColumn( + sqlite3_vtab_cursor *cur, + sqlite3_context *ctx, + int i +){ + wholenumber_cursor *pCur = (wholenumber_cursor*)cur; + sqlite3_result_int64(ctx, pCur->iValue); + return SQLITE_OK; +} + +/* +** The rowid. +*/ +static int wholenumberRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + wholenumber_cursor *pCur = (wholenumber_cursor*)cur; + *pRowid = pCur->iValue; + return SQLITE_OK; +} + +/* +** When the wholenumber_cursor.rLimit value is 0 or less, that is a signal +** that the cursor has nothing more to output. +*/ +static int wholenumberEof(sqlite3_vtab_cursor *cur){ + wholenumber_cursor *pCur = (wholenumber_cursor*)cur; + return pCur->iValue>pCur->mxValue || pCur->iValue==0; +} + +/* +** Called to "rewind" a cursor back to the beginning so that +** it starts its output over again. Always called at least once +** prior to any wholenumberColumn, wholenumberRowid, or wholenumberEof call. +** +** idxNum Constraints +** ------ --------------------- +** 0 (none) +** 1 value > $argv0 +** 2 value >= $argv0 +** 4 value < $argv0 +** 8 value <= $argv0 +** +** 5 value > $argv0 AND value < $argv1 +** 6 value >= $argv0 AND value < $argv1 +** 9 value > $argv0 AND value <= $argv1 +** 10 value >= $argv0 AND value <= $argv1 +*/ +static int wholenumberFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + wholenumber_cursor *pCur = (wholenumber_cursor *)pVtabCursor; + sqlite3_int64 v; + int i = 0; + pCur->iValue = 1; + pCur->mxValue = 0xffffffff; /* 4294967295 */ + if( idxNum & 3 ){ + v = sqlite3_value_int64(argv[0]) + (idxNum&1); + if( v>pCur->iValue && v<=pCur->mxValue ) pCur->iValue = v; + i++; + } + if( idxNum & 12 ){ + v = sqlite3_value_int64(argv[i]) - ((idxNum>>2)&1); + if( v>=pCur->iValue && vmxValue ) pCur->mxValue = v; + } + return SQLITE_OK; +} + +/* +** Search for terms of these forms: +** +** (1) value > $value +** (2) value >= $value +** (4) value < $value +** (8) value <= $value +** +** idxNum is an ORed combination of 1 or 2 with 4 or 8. +*/ +static int wholenumberBestIndex( + sqlite3_vtab *tab, + sqlite3_index_info *pIdxInfo +){ + int i; + int idxNum = 0; + int argvIdx = 1; + int ltIdx = -1; + int gtIdx = -1; + const struct sqlite3_index_constraint *pConstraint; + pConstraint = pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pConstraint++){ + if( pConstraint->usable==0 ) continue; + if( (idxNum & 3)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_GT ){ + idxNum |= 1; + ltIdx = i; + } + if( (idxNum & 3)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_GE ){ + idxNum |= 2; + ltIdx = i; + } + if( (idxNum & 12)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT ){ + idxNum |= 4; + gtIdx = i; + } + if( (idxNum & 12)==0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE ){ + idxNum |= 8; + gtIdx = i; + } + } + pIdxInfo->idxNum = idxNum; + if( ltIdx>=0 ){ + pIdxInfo->aConstraintUsage[ltIdx].argvIndex = argvIdx++; + pIdxInfo->aConstraintUsage[ltIdx].omit = 1; + } + if( gtIdx>=0 ){ + pIdxInfo->aConstraintUsage[gtIdx].argvIndex = argvIdx; + pIdxInfo->aConstraintUsage[gtIdx].omit = 1; + } + if( pIdxInfo->nOrderBy==1 + && pIdxInfo->aOrderBy[0].desc==0 + ){ + pIdxInfo->orderByConsumed = 1; + } + if( (idxNum & 12)==0 ){ + pIdxInfo->estimatedCost = (double)100000000; + }else if( (idxNum & 3)==0 ){ + pIdxInfo->estimatedCost = (double)5; + }else{ + pIdxInfo->estimatedCost = (double)1; + } + return SQLITE_OK; +} + +/* +** A virtual table module that provides read-only access to a +** Tcl global variable namespace. +*/ +static sqlite3_module wholenumberModule = { + 0, /* iVersion */ + wholenumberConnect, + wholenumberConnect, + wholenumberBestIndex, + wholenumberDisconnect, + wholenumberDisconnect, + wholenumberOpen, /* xOpen - open a cursor */ + wholenumberClose, /* xClose - close a cursor */ + wholenumberFilter, /* xFilter - configure scan constraints */ + wholenumberNext, /* xNext - advance a cursor */ + wholenumberEof, /* xEof - check for end of scan */ + wholenumberColumn, /* xColumn - read data */ + wholenumberRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_wholenumber_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = sqlite3_create_module(db, "wholenumber", &wholenumberModule, 0); +#endif + return rc; +} diff --git a/components/external/SQLite-3.8.1/ext/rtree/README b/components/external/SQLite-3.8.1/ext/rtree/README new file mode 100644 index 0000000000000000000000000000000000000000..3736f45c5fd968542a4d201a2274dd09b66b7865 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/README @@ -0,0 +1,120 @@ + +This directory contains an SQLite extension that implements a virtual +table type that allows users to create, query and manipulate r-tree[1] +data structures inside of SQLite databases. Users create, populate +and query r-tree structures using ordinary SQL statements. + + 1. SQL Interface + + 1.1 Table Creation + 1.2 Data Manipulation + 1.3 Data Querying + 1.4 Introspection and Analysis + + 2. Compilation and Deployment + + 3. References + + +1. SQL INTERFACE + + 1.1 Table Creation. + + All r-tree virtual tables have an odd number of columns between + 3 and 11. Unlike regular SQLite tables, r-tree tables are strongly + typed. + + The leftmost column is always the pimary key and contains 64-bit + integer values. Each subsequent column contains a 32-bit real + value. For each pair of real values, the first (leftmost) must be + less than or equal to the second. R-tree tables may be + constructed using the following syntax: + + CREATE VIRTUAL TABLE USING rtree() + + For example: + + CREATE VIRTUAL TABLE boxes USING rtree(boxno, xmin, xmax, ymin, ymax); + INSERT INTO boxes VALUES(1, 1.0, 3.0, 2.0, 4.0); + + Constructing a virtual r-tree table creates the following three + real tables in the database to store the data structure: + + _node + _rowid + _parent + + Dropping or modifying the contents of these tables directly will + corrupt the r-tree structure. To delete an r-tree from a database, + use a regular DROP TABLE statement: + + DROP TABLE ; + + Dropping the main r-tree table automatically drops the automatically + created tables. + + 1.2 Data Manipulation (INSERT, UPDATE, DELETE). + + The usual INSERT, UPDATE or DELETE syntax is used to manipulate data + stored in an r-tree table. Please note the following: + + * Inserting a NULL value into the primary key column has the + same effect as inserting a NULL into an INTEGER PRIMARY KEY + column of a regular table. The system automatically assigns + an unused integer key value to the new record. Usually, this + is one greater than the largest primary key value currently + present in the table. + + * Attempting to insert a duplicate primary key value fails with + an SQLITE_CONSTRAINT error. + + * Attempting to insert or modify a record such that the value + stored in the (N*2)th column is greater than that stored in + the (N*2+1)th column fails with an SQLITE_CONSTRAINT error. + + * When a record is inserted, values are always converted to + the required type (64-bit integer or 32-bit real) as if they + were part of an SQL CAST expression. Non-numeric strings are + converted to zero. + + 1.3 Queries. + + R-tree tables may be queried using all of the same SQL syntax supported + by regular tables. However, some query patterns are more efficient + than others. + + R-trees support fast lookup by primary key value (O(logN), like + regular tables). + + Any combination of equality and range (<, <=, >, >=) constraints + on spatial data columns may be used to optimize other queries. This + is the key advantage to using r-tree tables instead of creating + indices on regular tables. + + 1.4 Introspection and Analysis. + + TODO: Describe rtreenode() and rtreedepth() functions. + + +2. COMPILATION AND USAGE + + The easiest way to compile and use the RTREE extension is to build + and use it as a dynamically loadable SQLite extension. To do this + using gcc on *nix: + + gcc -shared rtree.c -o libSqliteRtree.so + + You may need to add "-I" flags so that gcc can find sqlite3ext.h + and sqlite3.h. The resulting shared lib, libSqliteRtree.so, may be + loaded into sqlite in the same way as any other dynamicly loadable + extension. + + +3. REFERENCES + + [1] Atonin Guttman, "R-trees - A Dynamic Index Structure For Spatial + Searching", University of California Berkeley, 1984. + + [2] Norbert Beckmann, Hans-Peter Kriegel, Ralf Schneider, Bernhard Seeger, + "The R*-tree: An Efficient and Robust Access Method for Points and + Rectangles", Universitaet Bremen, 1990. diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree.c b/components/external/SQLite-3.8.1/ext/rtree/rtree.c new file mode 100644 index 0000000000000000000000000000000000000000..815a8993e4f7836e7bdb4a3c30d6d0d9bb899e2b --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree.c @@ -0,0 +1,3366 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code for implementations of the r-tree and r*-tree +** algorithms packaged as an SQLite virtual table module. +*/ + +/* +** Database Format of R-Tree Tables +** -------------------------------- +** +** The data structure for a single virtual r-tree table is stored in three +** native SQLite tables declared as follows. In each case, the '%' character +** in the table name is replaced with the user-supplied name of the r-tree +** table. +** +** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB) +** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER) +** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER) +** +** The data for each node of the r-tree structure is stored in the %_node +** table. For each node that is not the root node of the r-tree, there is +** an entry in the %_parent table associating the node with its parent. +** And for each row of data in the table, there is an entry in the %_rowid +** table that maps from the entries rowid to the id of the node that it +** is stored on. +** +** The root node of an r-tree always exists, even if the r-tree table is +** empty. The nodeno of the root node is always 1. All other nodes in the +** table must be the same size as the root node. The content of each node +** is formatted as follows: +** +** 1. If the node is the root node (node 1), then the first 2 bytes +** of the node contain the tree depth as a big-endian integer. +** For non-root nodes, the first 2 bytes are left unused. +** +** 2. The next 2 bytes contain the number of entries currently +** stored in the node. +** +** 3. The remainder of the node contains the node entries. Each entry +** consists of a single 8-byte integer followed by an even number +** of 4-byte coordinates. For leaf nodes the integer is the rowid +** of a record. For internal nodes it is the node number of a +** child page. +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE) + +/* +** This file contains an implementation of a couple of different variants +** of the r-tree algorithm. See the README file for further details. The +** same data-structure is used for all, but the algorithms for insert and +** delete operations vary. The variants used are selected at compile time +** by defining the following symbols: +*/ + +/* Either, both or none of the following may be set to activate +** r*tree variant algorithms. +*/ +#define VARIANT_RSTARTREE_CHOOSESUBTREE 0 +#define VARIANT_RSTARTREE_REINSERT 1 + +/* +** Exactly one of the following must be set to 1. +*/ +#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0 +#define VARIANT_GUTTMAN_LINEAR_SPLIT 0 +#define VARIANT_RSTARTREE_SPLIT 1 + +#define VARIANT_GUTTMAN_SPLIT \ + (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT) + +#if VARIANT_GUTTMAN_QUADRATIC_SPLIT + #define PickNext QuadraticPickNext + #define PickSeeds QuadraticPickSeeds + #define AssignCells splitNodeGuttman +#endif +#if VARIANT_GUTTMAN_LINEAR_SPLIT + #define PickNext LinearPickNext + #define PickSeeds LinearPickSeeds + #define AssignCells splitNodeGuttman +#endif +#if VARIANT_RSTARTREE_SPLIT + #define AssignCells splitNodeStartree +#endif + +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif + +#ifndef SQLITE_CORE + #include "sqlite3ext.h" + SQLITE_EXTENSION_INIT1 +#else + #include "sqlite3.h" +#endif + +#include +#include + +#ifndef SQLITE_AMALGAMATION +#include "sqlite3rtree.h" +typedef sqlite3_int64 i64; +typedef unsigned char u8; +typedef unsigned int u32; +#endif + +/* The following macro is used to suppress compiler warnings. +*/ +#ifndef UNUSED_PARAMETER +# define UNUSED_PARAMETER(x) (void)(x) +#endif + +typedef struct Rtree Rtree; +typedef struct RtreeCursor RtreeCursor; +typedef struct RtreeNode RtreeNode; +typedef struct RtreeCell RtreeCell; +typedef struct RtreeConstraint RtreeConstraint; +typedef struct RtreeMatchArg RtreeMatchArg; +typedef struct RtreeGeomCallback RtreeGeomCallback; +typedef union RtreeCoord RtreeCoord; + +/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */ +#define RTREE_MAX_DIMENSIONS 5 + +/* Size of hash table Rtree.aHash. This hash table is not expected to +** ever contain very many entries, so a fixed number of buckets is +** used. +*/ +#define HASHSIZE 128 + +/* +** An rtree virtual-table object. +*/ +struct Rtree { + sqlite3_vtab base; + sqlite3 *db; /* Host database connection */ + int iNodeSize; /* Size in bytes of each node in the node table */ + int nDim; /* Number of dimensions */ + int nBytesPerCell; /* Bytes consumed per cell */ + int iDepth; /* Current depth of the r-tree structure */ + char *zDb; /* Name of database containing r-tree table */ + char *zName; /* Name of r-tree table */ + RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ + int nBusy; /* Current number of users of this structure */ + + /* List of nodes removed during a CondenseTree operation. List is + ** linked together via the pointer normally used for hash chains - + ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree + ** headed by the node (leaf nodes have RtreeNode.iNode==0). + */ + RtreeNode *pDeleted; + int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */ + + /* Statements to read/write/delete a record from xxx_node */ + sqlite3_stmt *pReadNode; + sqlite3_stmt *pWriteNode; + sqlite3_stmt *pDeleteNode; + + /* Statements to read/write/delete a record from xxx_rowid */ + sqlite3_stmt *pReadRowid; + sqlite3_stmt *pWriteRowid; + sqlite3_stmt *pDeleteRowid; + + /* Statements to read/write/delete a record from xxx_parent */ + sqlite3_stmt *pReadParent; + sqlite3_stmt *pWriteParent; + sqlite3_stmt *pDeleteParent; + + int eCoordType; +}; + +/* Possible values for eCoordType: */ +#define RTREE_COORD_REAL32 0 +#define RTREE_COORD_INT32 1 + +/* +** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will +** only deal with integer coordinates. No floating point operations +** will be done. +*/ +#ifdef SQLITE_RTREE_INT_ONLY + typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */ + typedef int RtreeValue; /* Low accuracy coordinate */ +#else + typedef double RtreeDValue; /* High accuracy coordinate */ + typedef float RtreeValue; /* Low accuracy coordinate */ +#endif + +/* +** The minimum number of cells allowed for a node is a third of the +** maximum. In Gutman's notation: +** +** m = M/3 +** +** If an R*-tree "Reinsert" operation is required, the same number of +** cells are removed from the overfull node and reinserted into the tree. +*/ +#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3) +#define RTREE_REINSERT(p) RTREE_MINCELLS(p) +#define RTREE_MAXCELLS 51 + +/* +** The smallest possible node-size is (512-64)==448 bytes. And the largest +** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates). +** Therefore all non-root nodes must contain at least 3 entries. Since +** 2^40 is greater than 2^64, an r-tree structure always has a depth of +** 40 or less. +*/ +#define RTREE_MAX_DEPTH 40 + +/* +** An rtree cursor object. +*/ +struct RtreeCursor { + sqlite3_vtab_cursor base; + RtreeNode *pNode; /* Node cursor is currently pointing at */ + int iCell; /* Index of current cell in pNode */ + int iStrategy; /* Copy of idxNum search parameter */ + int nConstraint; /* Number of entries in aConstraint */ + RtreeConstraint *aConstraint; /* Search constraints. */ +}; + +union RtreeCoord { + RtreeValue f; + int i; +}; + +/* +** The argument is an RtreeCoord. Return the value stored within the RtreeCoord +** formatted as a RtreeDValue (double or int64). This macro assumes that local +** variable pRtree points to the Rtree structure associated with the +** RtreeCoord. +*/ +#ifdef SQLITE_RTREE_INT_ONLY +# define DCOORD(coord) ((RtreeDValue)coord.i) +#else +# define DCOORD(coord) ( \ + (pRtree->eCoordType==RTREE_COORD_REAL32) ? \ + ((double)coord.f) : \ + ((double)coord.i) \ + ) +#endif + +/* +** A search constraint. +*/ +struct RtreeConstraint { + int iCoord; /* Index of constrained coordinate */ + int op; /* Constraining operation */ + RtreeDValue rValue; /* Constraint value. */ + int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*); + sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */ +}; + +/* Possible values for RtreeConstraint.op */ +#define RTREE_EQ 0x41 +#define RTREE_LE 0x42 +#define RTREE_LT 0x43 +#define RTREE_GE 0x44 +#define RTREE_GT 0x45 +#define RTREE_MATCH 0x46 + +/* +** An rtree structure node. +*/ +struct RtreeNode { + RtreeNode *pParent; /* Parent node */ + i64 iNode; + int nRef; + int isDirty; + u8 *zData; + RtreeNode *pNext; /* Next node in this hash chain */ +}; +#define NCELL(pNode) readInt16(&(pNode)->zData[2]) + +/* +** Structure to store a deserialized rtree record. +*/ +struct RtreeCell { + i64 iRowid; + RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; +}; + + +/* +** Value for the first field of every RtreeMatchArg object. The MATCH +** operator tests that the first field of a blob operand matches this +** value to avoid operating on invalid blobs (which could cause a segfault). +*/ +#define RTREE_GEOMETRY_MAGIC 0x891245AB + +/* +** An instance of this structure must be supplied as a blob argument to +** the right-hand-side of an SQL MATCH operator used to constrain an +** r-tree query. +*/ +struct RtreeMatchArg { + u32 magic; /* Always RTREE_GEOMETRY_MAGIC */ + int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *); + void *pContext; + int nParam; + RtreeDValue aParam[1]; +}; + +/* +** When a geometry callback is created (see sqlite3_rtree_geometry_callback), +** a single instance of the following structure is allocated. It is used +** as the context for the user-function created by by s_r_g_c(). The object +** is eventually deleted by the destructor mechanism provided by +** sqlite3_create_function_v2() (which is called by s_r_g_c() to create +** the geometry callback function). +*/ +struct RtreeGeomCallback { + int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*); + void *pContext; +}; + +#ifndef MAX +# define MAX(x,y) ((x) < (y) ? (y) : (x)) +#endif +#ifndef MIN +# define MIN(x,y) ((x) > (y) ? (y) : (x)) +#endif + +/* +** Functions to deserialize a 16 bit integer, 32 bit real number and +** 64 bit integer. The deserialized value is returned. +*/ +static int readInt16(u8 *p){ + return (p[0]<<8) + p[1]; +} +static void readCoord(u8 *p, RtreeCoord *pCoord){ + u32 i = ( + (((u32)p[0]) << 24) + + (((u32)p[1]) << 16) + + (((u32)p[2]) << 8) + + (((u32)p[3]) << 0) + ); + *(u32 *)pCoord = i; +} +static i64 readInt64(u8 *p){ + return ( + (((i64)p[0]) << 56) + + (((i64)p[1]) << 48) + + (((i64)p[2]) << 40) + + (((i64)p[3]) << 32) + + (((i64)p[4]) << 24) + + (((i64)p[5]) << 16) + + (((i64)p[6]) << 8) + + (((i64)p[7]) << 0) + ); +} + +/* +** Functions to serialize a 16 bit integer, 32 bit real number and +** 64 bit integer. The value returned is the number of bytes written +** to the argument buffer (always 2, 4 and 8 respectively). +*/ +static int writeInt16(u8 *p, int i){ + p[0] = (i>> 8)&0xFF; + p[1] = (i>> 0)&0xFF; + return 2; +} +static int writeCoord(u8 *p, RtreeCoord *pCoord){ + u32 i; + assert( sizeof(RtreeCoord)==4 ); + assert( sizeof(u32)==4 ); + i = *(u32 *)pCoord; + p[0] = (i>>24)&0xFF; + p[1] = (i>>16)&0xFF; + p[2] = (i>> 8)&0xFF; + p[3] = (i>> 0)&0xFF; + return 4; +} +static int writeInt64(u8 *p, i64 i){ + p[0] = (i>>56)&0xFF; + p[1] = (i>>48)&0xFF; + p[2] = (i>>40)&0xFF; + p[3] = (i>>32)&0xFF; + p[4] = (i>>24)&0xFF; + p[5] = (i>>16)&0xFF; + p[6] = (i>> 8)&0xFF; + p[7] = (i>> 0)&0xFF; + return 8; +} + +/* +** Increment the reference count of node p. +*/ +static void nodeReference(RtreeNode *p){ + if( p ){ + p->nRef++; + } +} + +/* +** Clear the content of node p (set all bytes to 0x00). +*/ +static void nodeZero(Rtree *pRtree, RtreeNode *p){ + memset(&p->zData[2], 0, pRtree->iNodeSize-2); + p->isDirty = 1; +} + +/* +** Given a node number iNode, return the corresponding key to use +** in the Rtree.aHash table. +*/ +static int nodeHash(i64 iNode){ + return ( + (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ + (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0) + ) % HASHSIZE; +} + +/* +** Search the node hash table for node iNode. If found, return a pointer +** to it. Otherwise, return 0. +*/ +static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){ + RtreeNode *p; + for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext); + return p; +} + +/* +** Add node pNode to the node hash table. +*/ +static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){ + int iHash; + assert( pNode->pNext==0 ); + iHash = nodeHash(pNode->iNode); + pNode->pNext = pRtree->aHash[iHash]; + pRtree->aHash[iHash] = pNode; +} + +/* +** Remove node pNode from the node hash table. +*/ +static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){ + RtreeNode **pp; + if( pNode->iNode!=0 ){ + pp = &pRtree->aHash[nodeHash(pNode->iNode)]; + for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); } + *pp = pNode->pNext; + pNode->pNext = 0; + } +} + +/* +** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0), +** indicating that node has not yet been assigned a node number. It is +** assigned a node number when nodeWrite() is called to write the +** node contents out to the database. +*/ +static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){ + RtreeNode *pNode; + pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); + if( pNode ){ + memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize); + pNode->zData = (u8 *)&pNode[1]; + pNode->nRef = 1; + pNode->pParent = pParent; + pNode->isDirty = 1; + nodeReference(pParent); + } + return pNode; +} + +/* +** Obtain a reference to an r-tree node. +*/ +static int +nodeAcquire( + Rtree *pRtree, /* R-tree structure */ + i64 iNode, /* Node number to load */ + RtreeNode *pParent, /* Either the parent node or NULL */ + RtreeNode **ppNode /* OUT: Acquired node */ +){ + int rc; + int rc2 = SQLITE_OK; + RtreeNode *pNode; + + /* Check if the requested node is already in the hash table. If so, + ** increase its reference count and return it. + */ + if( (pNode = nodeHashLookup(pRtree, iNode)) ){ + assert( !pParent || !pNode->pParent || pNode->pParent==pParent ); + if( pParent && !pNode->pParent ){ + nodeReference(pParent); + pNode->pParent = pParent; + } + pNode->nRef++; + *ppNode = pNode; + return SQLITE_OK; + } + + sqlite3_bind_int64(pRtree->pReadNode, 1, iNode); + rc = sqlite3_step(pRtree->pReadNode); + if( rc==SQLITE_ROW ){ + const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0); + if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){ + pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize); + if( !pNode ){ + rc2 = SQLITE_NOMEM; + }else{ + pNode->pParent = pParent; + pNode->zData = (u8 *)&pNode[1]; + pNode->nRef = 1; + pNode->iNode = iNode; + pNode->isDirty = 0; + pNode->pNext = 0; + memcpy(pNode->zData, zBlob, pRtree->iNodeSize); + nodeReference(pParent); + } + } + } + rc = sqlite3_reset(pRtree->pReadNode); + if( rc==SQLITE_OK ) rc = rc2; + + /* If the root node was just loaded, set pRtree->iDepth to the height + ** of the r-tree structure. A height of zero means all data is stored on + ** the root node. A height of one means the children of the root node + ** are the leaves, and so on. If the depth as specified on the root node + ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt. + */ + if( pNode && iNode==1 ){ + pRtree->iDepth = readInt16(pNode->zData); + if( pRtree->iDepth>RTREE_MAX_DEPTH ){ + rc = SQLITE_CORRUPT_VTAB; + } + } + + /* If no error has occurred so far, check if the "number of entries" + ** field on the node is too large. If so, set the return code to + ** SQLITE_CORRUPT_VTAB. + */ + if( pNode && rc==SQLITE_OK ){ + if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){ + rc = SQLITE_CORRUPT_VTAB; + } + } + + if( rc==SQLITE_OK ){ + if( pNode!=0 ){ + nodeHashInsert(pRtree, pNode); + }else{ + rc = SQLITE_CORRUPT_VTAB; + } + *ppNode = pNode; + }else{ + sqlite3_free(pNode); + *ppNode = 0; + } + + return rc; +} + +/* +** Overwrite cell iCell of node pNode with the contents of pCell. +*/ +static void nodeOverwriteCell( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell, + int iCell +){ + int ii; + u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; + p += writeInt64(p, pCell->iRowid); + for(ii=0; ii<(pRtree->nDim*2); ii++){ + p += writeCoord(p, &pCell->aCoord[ii]); + } + pNode->isDirty = 1; +} + +/* +** Remove cell the cell with index iCell from node pNode. +*/ +static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){ + u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; + u8 *pSrc = &pDst[pRtree->nBytesPerCell]; + int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell; + memmove(pDst, pSrc, nByte); + writeInt16(&pNode->zData[2], NCELL(pNode)-1); + pNode->isDirty = 1; +} + +/* +** Insert the contents of cell pCell into node pNode. If the insert +** is successful, return SQLITE_OK. +** +** If there is not enough free space in pNode, return SQLITE_FULL. +*/ +static int +nodeInsertCell( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell +){ + int nCell; /* Current number of cells in pNode */ + int nMaxCell; /* Maximum number of cells for pNode */ + + nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell; + nCell = NCELL(pNode); + + assert( nCell<=nMaxCell ); + if( nCellzData[2], nCell+1); + pNode->isDirty = 1; + } + + return (nCell==nMaxCell); +} + +/* +** If the node is dirty, write it out to the database. +*/ +static int +nodeWrite(Rtree *pRtree, RtreeNode *pNode){ + int rc = SQLITE_OK; + if( pNode->isDirty ){ + sqlite3_stmt *p = pRtree->pWriteNode; + if( pNode->iNode ){ + sqlite3_bind_int64(p, 1, pNode->iNode); + }else{ + sqlite3_bind_null(p, 1); + } + sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); + sqlite3_step(p); + pNode->isDirty = 0; + rc = sqlite3_reset(p); + if( pNode->iNode==0 && rc==SQLITE_OK ){ + pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); + nodeHashInsert(pRtree, pNode); + } + } + return rc; +} + +/* +** Release a reference to a node. If the node is dirty and the reference +** count drops to zero, the node data is written to the database. +*/ +static int +nodeRelease(Rtree *pRtree, RtreeNode *pNode){ + int rc = SQLITE_OK; + if( pNode ){ + assert( pNode->nRef>0 ); + pNode->nRef--; + if( pNode->nRef==0 ){ + if( pNode->iNode==1 ){ + pRtree->iDepth = -1; + } + if( pNode->pParent ){ + rc = nodeRelease(pRtree, pNode->pParent); + } + if( rc==SQLITE_OK ){ + rc = nodeWrite(pRtree, pNode); + } + nodeHashDelete(pRtree, pNode); + sqlite3_free(pNode); + } + } + return rc; +} + +/* +** Return the 64-bit integer value associated with cell iCell of +** node pNode. If pNode is a leaf node, this is a rowid. If it is +** an internal node, then the 64-bit integer is a child page number. +*/ +static i64 nodeGetRowid( + Rtree *pRtree, + RtreeNode *pNode, + int iCell +){ + assert( iCellzData[4 + pRtree->nBytesPerCell*iCell]); +} + +/* +** Return coordinate iCoord from cell iCell in node pNode. +*/ +static void nodeGetCoord( + Rtree *pRtree, + RtreeNode *pNode, + int iCell, + int iCoord, + RtreeCoord *pCoord /* Space to write result to */ +){ + readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord); +} + +/* +** Deserialize cell iCell of node pNode. Populate the structure pointed +** to by pCell with the results. +*/ +static void nodeGetCell( + Rtree *pRtree, + RtreeNode *pNode, + int iCell, + RtreeCell *pCell +){ + int ii; + pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell); + for(ii=0; iinDim*2; ii++){ + nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]); + } +} + + +/* Forward declaration for the function that does the work of +** the virtual table module xCreate() and xConnect() methods. +*/ +static int rtreeInit( + sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int +); + +/* +** Rtree virtual table module xCreate method. +*/ +static int rtreeCreate( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1); +} + +/* +** Rtree virtual table module xConnect method. +*/ +static int rtreeConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0); +} + +/* +** Increment the r-tree reference count. +*/ +static void rtreeReference(Rtree *pRtree){ + pRtree->nBusy++; +} + +/* +** Decrement the r-tree reference count. When the reference count reaches +** zero the structure is deleted. +*/ +static void rtreeRelease(Rtree *pRtree){ + pRtree->nBusy--; + if( pRtree->nBusy==0 ){ + sqlite3_finalize(pRtree->pReadNode); + sqlite3_finalize(pRtree->pWriteNode); + sqlite3_finalize(pRtree->pDeleteNode); + sqlite3_finalize(pRtree->pReadRowid); + sqlite3_finalize(pRtree->pWriteRowid); + sqlite3_finalize(pRtree->pDeleteRowid); + sqlite3_finalize(pRtree->pReadParent); + sqlite3_finalize(pRtree->pWriteParent); + sqlite3_finalize(pRtree->pDeleteParent); + sqlite3_free(pRtree); + } +} + +/* +** Rtree virtual table module xDisconnect method. +*/ +static int rtreeDisconnect(sqlite3_vtab *pVtab){ + rtreeRelease((Rtree *)pVtab); + return SQLITE_OK; +} + +/* +** Rtree virtual table module xDestroy method. +*/ +static int rtreeDestroy(sqlite3_vtab *pVtab){ + Rtree *pRtree = (Rtree *)pVtab; + int rc; + char *zCreate = sqlite3_mprintf( + "DROP TABLE '%q'.'%q_node';" + "DROP TABLE '%q'.'%q_rowid';" + "DROP TABLE '%q'.'%q_parent';", + pRtree->zDb, pRtree->zName, + pRtree->zDb, pRtree->zName, + pRtree->zDb, pRtree->zName + ); + if( !zCreate ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0); + sqlite3_free(zCreate); + } + if( rc==SQLITE_OK ){ + rtreeRelease(pRtree); + } + + return rc; +} + +/* +** Rtree virtual table module xOpen method. +*/ +static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + int rc = SQLITE_NOMEM; + RtreeCursor *pCsr; + + pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor)); + if( pCsr ){ + memset(pCsr, 0, sizeof(RtreeCursor)); + pCsr->base.pVtab = pVTab; + rc = SQLITE_OK; + } + *ppCursor = (sqlite3_vtab_cursor *)pCsr; + + return rc; +} + + +/* +** Free the RtreeCursor.aConstraint[] array and its contents. +*/ +static void freeCursorConstraints(RtreeCursor *pCsr){ + if( pCsr->aConstraint ){ + int i; /* Used to iterate through constraint array */ + for(i=0; inConstraint; i++){ + sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom; + if( pGeom ){ + if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser); + sqlite3_free(pGeom); + } + } + sqlite3_free(pCsr->aConstraint); + pCsr->aConstraint = 0; + } +} + +/* +** Rtree virtual table module xClose method. +*/ +static int rtreeClose(sqlite3_vtab_cursor *cur){ + Rtree *pRtree = (Rtree *)(cur->pVtab); + int rc; + RtreeCursor *pCsr = (RtreeCursor *)cur; + freeCursorConstraints(pCsr); + rc = nodeRelease(pRtree, pCsr->pNode); + sqlite3_free(pCsr); + return rc; +} + +/* +** Rtree virtual table module xEof method. +** +** Return non-zero if the cursor does not currently point to a valid +** record (i.e if the scan has finished), or zero otherwise. +*/ +static int rtreeEof(sqlite3_vtab_cursor *cur){ + RtreeCursor *pCsr = (RtreeCursor *)cur; + return (pCsr->pNode==0); +} + +/* +** The r-tree constraint passed as the second argument to this function is +** guaranteed to be a MATCH constraint. +*/ +static int testRtreeGeom( + Rtree *pRtree, /* R-Tree object */ + RtreeConstraint *pConstraint, /* MATCH constraint to test */ + RtreeCell *pCell, /* Cell to test */ + int *pbRes /* OUT: Test result */ +){ + int i; + RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2]; + int nCoord = pRtree->nDim*2; + + assert( pConstraint->op==RTREE_MATCH ); + assert( pConstraint->pGeom ); + + for(i=0; iaCoord[i]); + } + return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes); +} + +/* +** Cursor pCursor currently points to a cell in a non-leaf page. +** Set *pbEof to true if the sub-tree headed by the cell is filtered +** (excluded) by the constraints in the pCursor->aConstraint[] +** array, or false otherwise. +** +** Return SQLITE_OK if successful or an SQLite error code if an error +** occurs within a geometry callback. +*/ +static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){ + RtreeCell cell; + int ii; + int bRes = 0; + int rc = SQLITE_OK; + + nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell); + for(ii=0; bRes==0 && iinConstraint; ii++){ + RtreeConstraint *p = &pCursor->aConstraint[ii]; + RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]); + RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]); + + assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE + || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH + ); + + switch( p->op ){ + case RTREE_LE: case RTREE_LT: + bRes = p->rValuerValue>cell_max; + break; + + case RTREE_EQ: + bRes = (p->rValue>cell_max || p->rValueop==RTREE_MATCH ); + rc = testRtreeGeom(pRtree, p, &cell, &bRes); + bRes = !bRes; + break; + } + } + } + + *pbEof = bRes; + return rc; +} + +/* +** Test if the cell that cursor pCursor currently points to +** would be filtered (excluded) by the constraints in the +** pCursor->aConstraint[] array. If so, set *pbEof to true before +** returning. If the cell is not filtered (excluded) by the constraints, +** set pbEof to zero. +** +** Return SQLITE_OK if successful or an SQLite error code if an error +** occurs within a geometry callback. +** +** This function assumes that the cell is part of a leaf node. +*/ +static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){ + RtreeCell cell; + int ii; + *pbEof = 0; + + nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell); + for(ii=0; iinConstraint; ii++){ + RtreeConstraint *p = &pCursor->aConstraint[ii]; + RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]); + int res; + assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE + || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH + ); + switch( p->op ){ + case RTREE_LE: res = (coord<=p->rValue); break; + case RTREE_LT: res = (coordrValue); break; + case RTREE_GE: res = (coord>=p->rValue); break; + case RTREE_GT: res = (coord>p->rValue); break; + case RTREE_EQ: res = (coord==p->rValue); break; + default: { + int rc; + assert( p->op==RTREE_MATCH ); + rc = testRtreeGeom(pRtree, p, &cell, &res); + if( rc!=SQLITE_OK ){ + return rc; + } + break; + } + } + + if( !res ){ + *pbEof = 1; + return SQLITE_OK; + } + } + + return SQLITE_OK; +} + +/* +** Cursor pCursor currently points at a node that heads a sub-tree of +** height iHeight (if iHeight==0, then the node is a leaf). Descend +** to point to the left-most cell of the sub-tree that matches the +** configured constraints. +*/ +static int descendToCell( + Rtree *pRtree, + RtreeCursor *pCursor, + int iHeight, + int *pEof /* OUT: Set to true if cannot descend */ +){ + int isEof; + int rc; + int ii; + RtreeNode *pChild; + sqlite3_int64 iRowid; + + RtreeNode *pSavedNode = pCursor->pNode; + int iSavedCell = pCursor->iCell; + + assert( iHeight>=0 ); + + if( iHeight==0 ){ + rc = testRtreeEntry(pRtree, pCursor, &isEof); + }else{ + rc = testRtreeCell(pRtree, pCursor, &isEof); + } + if( rc!=SQLITE_OK || isEof || iHeight==0 ){ + goto descend_to_cell_out; + } + + iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell); + rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild); + if( rc!=SQLITE_OK ){ + goto descend_to_cell_out; + } + + nodeRelease(pRtree, pCursor->pNode); + pCursor->pNode = pChild; + isEof = 1; + for(ii=0; isEof && iiiCell = ii; + rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof); + if( rc!=SQLITE_OK ){ + goto descend_to_cell_out; + } + } + + if( isEof ){ + assert( pCursor->pNode==pChild ); + nodeReference(pSavedNode); + nodeRelease(pRtree, pChild); + pCursor->pNode = pSavedNode; + pCursor->iCell = iSavedCell; + } + +descend_to_cell_out: + *pEof = isEof; + return rc; +} + +/* +** One of the cells in node pNode is guaranteed to have a 64-bit +** integer value equal to iRowid. Return the index of this cell. +*/ +static int nodeRowidIndex( + Rtree *pRtree, + RtreeNode *pNode, + i64 iRowid, + int *piIndex +){ + int ii; + int nCell = NCELL(pNode); + for(ii=0; iipParent; + if( pParent ){ + return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex); + } + *piIndex = -1; + return SQLITE_OK; +} + +/* +** Rtree virtual table module xNext method. +*/ +static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ + Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab); + RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; + int rc = SQLITE_OK; + + /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is + ** already at EOF. It is against the rules to call the xNext() method of + ** a cursor that has already reached EOF. + */ + assert( pCsr->pNode ); + + if( pCsr->iStrategy==1 ){ + /* This "scan" is a direct lookup by rowid. There is no next entry. */ + nodeRelease(pRtree, pCsr->pNode); + pCsr->pNode = 0; + }else{ + /* Move to the next entry that matches the configured constraints. */ + int iHeight = 0; + while( pCsr->pNode ){ + RtreeNode *pNode = pCsr->pNode; + int nCell = NCELL(pNode); + for(pCsr->iCell++; pCsr->iCelliCell++){ + int isEof; + rc = descendToCell(pRtree, pCsr, iHeight, &isEof); + if( rc!=SQLITE_OK || !isEof ){ + return rc; + } + } + pCsr->pNode = pNode->pParent; + rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell); + if( rc!=SQLITE_OK ){ + return rc; + } + nodeReference(pCsr->pNode); + nodeRelease(pRtree, pNode); + iHeight++; + } + } + + return rc; +} + +/* +** Rtree virtual table module xRowid method. +*/ +static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ + Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; + RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; + + assert(pCsr->pNode); + *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell); + + return SQLITE_OK; +} + +/* +** Rtree virtual table module xColumn method. +*/ +static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + Rtree *pRtree = (Rtree *)cur->pVtab; + RtreeCursor *pCsr = (RtreeCursor *)cur; + + if( i==0 ){ + i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell); + sqlite3_result_int64(ctx, iRowid); + }else{ + RtreeCoord c; + nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c); +#ifndef SQLITE_RTREE_INT_ONLY + if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ + sqlite3_result_double(ctx, c.f); + }else +#endif + { + assert( pRtree->eCoordType==RTREE_COORD_INT32 ); + sqlite3_result_int(ctx, c.i); + } + } + + return SQLITE_OK; +} + +/* +** Use nodeAcquire() to obtain the leaf node containing the record with +** rowid iRowid. If successful, set *ppLeaf to point to the node and +** return SQLITE_OK. If there is no such record in the table, set +** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf +** to zero and return an SQLite error code. +*/ +static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){ + int rc; + *ppLeaf = 0; + sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); + if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ + i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0); + rc = nodeAcquire(pRtree, iNode, 0, ppLeaf); + sqlite3_reset(pRtree->pReadRowid); + }else{ + rc = sqlite3_reset(pRtree->pReadRowid); + } + return rc; +} + +/* +** This function is called to configure the RtreeConstraint object passed +** as the second argument for a MATCH constraint. The value passed as the +** first argument to this function is the right-hand operand to the MATCH +** operator. +*/ +static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){ + RtreeMatchArg *p; + sqlite3_rtree_geometry *pGeom; + int nBlob; + + /* Check that value is actually a blob. */ + if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR; + + /* Check that the blob is roughly the right size. */ + nBlob = sqlite3_value_bytes(pValue); + if( nBlob<(int)sizeof(RtreeMatchArg) + || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0 + ){ + return SQLITE_ERROR; + } + + pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc( + sizeof(sqlite3_rtree_geometry) + nBlob + ); + if( !pGeom ) return SQLITE_NOMEM; + memset(pGeom, 0, sizeof(sqlite3_rtree_geometry)); + p = (RtreeMatchArg *)&pGeom[1]; + + memcpy(p, sqlite3_value_blob(pValue), nBlob); + if( p->magic!=RTREE_GEOMETRY_MAGIC + || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue)) + ){ + sqlite3_free(pGeom); + return SQLITE_ERROR; + } + + pGeom->pContext = p->pContext; + pGeom->nParam = p->nParam; + pGeom->aParam = p->aParam; + + pCons->xGeom = p->xGeom; + pCons->pGeom = pGeom; + return SQLITE_OK; +} + +/* +** Rtree virtual table module xFilter method. +*/ +static int rtreeFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; + RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; + + RtreeNode *pRoot = 0; + int ii; + int rc = SQLITE_OK; + + rtreeReference(pRtree); + + freeCursorConstraints(pCsr); + pCsr->iStrategy = idxNum; + + if( idxNum==1 ){ + /* Special case - lookup by rowid. */ + RtreeNode *pLeaf; /* Leaf on which the required cell resides */ + i64 iRowid = sqlite3_value_int64(argv[0]); + rc = findLeafNode(pRtree, iRowid, &pLeaf); + pCsr->pNode = pLeaf; + if( pLeaf ){ + assert( rc==SQLITE_OK ); + rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell); + } + }else{ + /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array + ** with the configured constraints. + */ + if( argc>0 ){ + pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc); + pCsr->nConstraint = argc; + if( !pCsr->aConstraint ){ + rc = SQLITE_NOMEM; + }else{ + memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc); + assert( (idxStr==0 && argc==0) + || (idxStr && (int)strlen(idxStr)==argc*2) ); + for(ii=0; iiaConstraint[ii]; + p->op = idxStr[ii*2]; + p->iCoord = idxStr[ii*2+1]-'a'; + if( p->op==RTREE_MATCH ){ + /* A MATCH operator. The right-hand-side must be a blob that + ** can be cast into an RtreeMatchArg object. One created using + ** an sqlite3_rtree_geometry_callback() SQL user function. + */ + rc = deserializeGeometry(argv[ii], p); + if( rc!=SQLITE_OK ){ + break; + } + }else{ +#ifdef SQLITE_RTREE_INT_ONLY + p->rValue = sqlite3_value_int64(argv[ii]); +#else + p->rValue = sqlite3_value_double(argv[ii]); +#endif + } + } + } + } + + if( rc==SQLITE_OK ){ + pCsr->pNode = 0; + rc = nodeAcquire(pRtree, 1, 0, &pRoot); + } + if( rc==SQLITE_OK ){ + int isEof = 1; + int nCell = NCELL(pRoot); + pCsr->pNode = pRoot; + for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCelliCell++){ + assert( pCsr->pNode==pRoot ); + rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof); + if( !isEof ){ + break; + } + } + if( rc==SQLITE_OK && isEof ){ + assert( pCsr->pNode==pRoot ); + nodeRelease(pRtree, pRoot); + pCsr->pNode = 0; + } + assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCellpNode) ); + } + } + + rtreeRelease(pRtree); + return rc; +} + +/* +** Rtree virtual table module xBestIndex method. There are three +** table scan strategies to choose from (in order from most to +** least desirable): +** +** idxNum idxStr Strategy +** ------------------------------------------------ +** 1 Unused Direct lookup by rowid. +** 2 See below R-tree query or full-table scan. +** ------------------------------------------------ +** +** If strategy 1 is used, then idxStr is not meaningful. If strategy +** 2 is used, idxStr is formatted to contain 2 bytes for each +** constraint used. The first two bytes of idxStr correspond to +** the constraint in sqlite3_index_info.aConstraintUsage[] with +** (argvIndex==1) etc. +** +** The first of each pair of bytes in idxStr identifies the constraint +** operator as follows: +** +** Operator Byte Value +** ---------------------- +** = 0x41 ('A') +** <= 0x42 ('B') +** < 0x43 ('C') +** >= 0x44 ('D') +** > 0x45 ('E') +** MATCH 0x46 ('F') +** ---------------------- +** +** The second of each pair of bytes identifies the coordinate column +** to which the constraint applies. The leftmost coordinate column +** is 'a', the second from the left 'b' etc. +*/ +static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int rc = SQLITE_OK; + int ii; + + int iIdx = 0; + char zIdxStr[RTREE_MAX_DIMENSIONS*8+1]; + memset(zIdxStr, 0, sizeof(zIdxStr)); + UNUSED_PARAMETER(tab); + + assert( pIdxInfo->idxStr==0 ); + for(ii=0; iinConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){ + struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; + + if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + /* We have an equality constraint on the rowid. Use strategy 1. */ + int jj; + for(jj=0; jjaConstraintUsage[jj].argvIndex = 0; + pIdxInfo->aConstraintUsage[jj].omit = 0; + } + pIdxInfo->idxNum = 1; + pIdxInfo->aConstraintUsage[ii].argvIndex = 1; + pIdxInfo->aConstraintUsage[jj].omit = 1; + + /* This strategy involves a two rowid lookups on an B-Tree structures + ** and then a linear search of an R-Tree node. This should be + ** considered almost as quick as a direct rowid lookup (for which + ** sqlite uses an internal cost of 0.0). + */ + pIdxInfo->estimatedCost = 10.0; + return SQLITE_OK; + } + + if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){ + u8 op; + switch( p->op ){ + case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; + case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; + case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; + case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; + case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; + default: + assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH ); + op = RTREE_MATCH; + break; + } + zIdxStr[iIdx++] = op; + zIdxStr[iIdx++] = p->iColumn - 1 + 'a'; + pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2); + pIdxInfo->aConstraintUsage[ii].omit = 1; + } + } + + pIdxInfo->idxNum = 2; + pIdxInfo->needToFreeIdxStr = 1; + if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ + return SQLITE_NOMEM; + } + assert( iIdx>=0 ); + pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1)); + return rc; +} + +/* +** Return the N-dimensional volumn of the cell stored in *p. +*/ +static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){ + RtreeDValue area = (RtreeDValue)1; + int ii; + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]))); + } + return area; +} + +/* +** Return the margin length of cell p. The margin length is the sum +** of the objects size in each dimension. +*/ +static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){ + RtreeDValue margin = (RtreeDValue)0; + int ii; + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); + } + return margin; +} + +/* +** Store the union of cells p1 and p2 in p1. +*/ +static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ + int ii; + if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f); + p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f); + } + }else{ + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i); + p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i); + } + } +} + +/* +** Return true if the area covered by p2 is a subset of the area covered +** by p1. False otherwise. +*/ +static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ + int ii; + int isInt = (pRtree->eCoordType==RTREE_COORD_INT32); + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + RtreeCoord *a1 = &p1->aCoord[ii]; + RtreeCoord *a2 = &p2->aCoord[ii]; + if( (!isInt && (a2[0].fa1[1].f)) + || ( isInt && (a2[0].ia1[1].i)) + ){ + return 0; + } + } + return 1; +} + +/* +** Return the amount cell p would grow by if it were unioned with pCell. +*/ +static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){ + RtreeDValue area; + RtreeCell cell; + memcpy(&cell, p, sizeof(RtreeCell)); + area = cellArea(pRtree, &cell); + cellUnion(pRtree, &cell, pCell); + return (cellArea(pRtree, &cell)-area); +} + +#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT +static RtreeDValue cellOverlap( + Rtree *pRtree, + RtreeCell *p, + RtreeCell *aCell, + int nCell, + int iExclude +){ + int ii; + RtreeDValue overlap = 0.0; + for(ii=0; iinDim*2); jj+=2){ + RtreeDValue x1, x2; + + x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj])); + x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1])); + + if( x2iDepth-iHeight); ii++){ + int iCell; + sqlite3_int64 iBest = 0; + + RtreeDValue fMinGrowth = 0.0; + RtreeDValue fMinArea = 0.0; +#if VARIANT_RSTARTREE_CHOOSESUBTREE + RtreeDValue fMinOverlap = 0.0; + RtreeDValue overlap; +#endif + + int nCell = NCELL(pNode); + RtreeCell cell; + RtreeNode *pChild; + + RtreeCell *aCell = 0; + +#if VARIANT_RSTARTREE_CHOOSESUBTREE + if( ii==(pRtree->iDepth-1) ){ + int jj; + aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell); + if( !aCell ){ + rc = SQLITE_NOMEM; + nodeRelease(pRtree, pNode); + pNode = 0; + continue; + } + for(jj=0; jjiDepth-1) ){ + overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell); + }else{ + overlap = 0.0; + } + if( (iCell==0) + || (overlappParent ){ + RtreeNode *pParent = p->pParent; + RtreeCell cell; + int iCell; + + if( nodeParentIndex(pRtree, p, &iCell) ){ + return SQLITE_CORRUPT_VTAB; + } + + nodeGetCell(pRtree, pParent, iCell, &cell); + if( !cellContains(pRtree, &cell, pCell) ){ + cellUnion(pRtree, &cell, pCell); + nodeOverwriteCell(pRtree, pParent, &cell, iCell); + } + + p = pParent; + } + return SQLITE_OK; +} + +/* +** Write mapping (iRowid->iNode) to the _rowid table. +*/ +static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){ + sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); + sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); + sqlite3_step(pRtree->pWriteRowid); + return sqlite3_reset(pRtree->pWriteRowid); +} + +/* +** Write mapping (iNode->iPar) to the _parent table. +*/ +static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){ + sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); + sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); + sqlite3_step(pRtree->pWriteParent); + return sqlite3_reset(pRtree->pWriteParent); +} + +static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int); + +#if VARIANT_GUTTMAN_LINEAR_SPLIT +/* +** Implementation of the linear variant of the PickNext() function from +** Guttman[84]. +*/ +static RtreeCell *LinearPickNext( + Rtree *pRtree, + RtreeCell *aCell, + int nCell, + RtreeCell *pLeftBox, + RtreeCell *pRightBox, + int *aiUsed +){ + int ii; + for(ii=0; aiUsed[ii]; ii++); + aiUsed[ii] = 1; + return &aCell[ii]; +} + +/* +** Implementation of the linear variant of the PickSeeds() function from +** Guttman[84]. +*/ +static void LinearPickSeeds( + Rtree *pRtree, + RtreeCell *aCell, + int nCell, + int *piLeftSeed, + int *piRightSeed +){ + int i; + int iLeftSeed = 0; + int iRightSeed = 1; + RtreeDValue maxNormalInnerWidth = (RtreeDValue)0; + + /* Pick two "seed" cells from the array of cells. The algorithm used + ** here is the LinearPickSeeds algorithm from Gutman[1984]. The + ** indices of the two seed cells in the array are stored in local + ** variables iLeftSeek and iRightSeed. + */ + for(i=0; inDim; i++){ + RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]); + RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]); + RtreeDValue x3 = x1; + RtreeDValue x4 = x2; + int jj; + + int iCellLeft = 0; + int iCellRight = 0; + + for(jj=1; jjx4 ) x4 = right; + if( left>x3 ){ + x3 = left; + iCellRight = jj; + } + if( rightmaxNormalInnerWidth ){ + iLeftSeed = iCellLeft; + iRightSeed = iCellRight; + } + } + } + + *piLeftSeed = iLeftSeed; + *piRightSeed = iRightSeed; +} +#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */ + +#if VARIANT_GUTTMAN_QUADRATIC_SPLIT +/* +** Implementation of the quadratic variant of the PickNext() function from +** Guttman[84]. +*/ +static RtreeCell *QuadraticPickNext( + Rtree *pRtree, + RtreeCell *aCell, + int nCell, + RtreeCell *pLeftBox, + RtreeCell *pRightBox, + int *aiUsed +){ + #define FABS(a) ((a)<0.0?-1.0*(a):(a)) + + int iSelect = -1; + RtreeDValue fDiff; + int ii; + for(ii=0; iifDiff ){ + fDiff = diff; + iSelect = ii; + } + } + } + aiUsed[iSelect] = 1; + return &aCell[iSelect]; +} + +/* +** Implementation of the quadratic variant of the PickSeeds() function from +** Guttman[84]. +*/ +static void QuadraticPickSeeds( + Rtree *pRtree, + RtreeCell *aCell, + int nCell, + int *piLeftSeed, + int *piRightSeed +){ + int ii; + int jj; + + int iLeftSeed = 0; + int iRightSeed = 1; + RtreeDValue fWaste = 0.0; + + for(ii=0; iifWaste ){ + iLeftSeed = ii; + iRightSeed = jj; + fWaste = waste; + } + } + } + + *piLeftSeed = iLeftSeed; + *piRightSeed = iRightSeed; +} +#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */ + +/* +** Arguments aIdx, aDistance and aSpare all point to arrays of size +** nIdx. The aIdx array contains the set of integers from 0 to +** (nIdx-1) in no particular order. This function sorts the values +** in aIdx according to the indexed values in aDistance. For +** example, assuming the inputs: +** +** aIdx = { 0, 1, 2, 3 } +** aDistance = { 5.0, 2.0, 7.0, 6.0 } +** +** this function sets the aIdx array to contain: +** +** aIdx = { 0, 1, 2, 3 } +** +** The aSpare array is used as temporary working space by the +** sorting algorithm. +*/ +static void SortByDistance( + int *aIdx, + int nIdx, + RtreeDValue *aDistance, + int *aSpare +){ + if( nIdx>1 ){ + int iLeft = 0; + int iRight = 0; + + int nLeft = nIdx/2; + int nRight = nIdx-nLeft; + int *aLeft = aIdx; + int *aRight = &aIdx[nLeft]; + + SortByDistance(aLeft, nLeft, aDistance, aSpare); + SortByDistance(aRight, nRight, aDistance, aSpare); + + memcpy(aSpare, aLeft, sizeof(int)*nLeft); + aLeft = aSpare; + + while( iLeft1 ){ + + int iLeft = 0; + int iRight = 0; + + int nLeft = nIdx/2; + int nRight = nIdx-nLeft; + int *aLeft = aIdx; + int *aRight = &aIdx[nLeft]; + + SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare); + SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare); + + memcpy(aSpare, aLeft, sizeof(int)*nLeft); + aLeft = aSpare; + while( iLeftnDim+1)*(sizeof(int*)+nCell*sizeof(int)); + + aaSorted = (int **)sqlite3_malloc(nByte); + if( !aaSorted ){ + return SQLITE_NOMEM; + } + + aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell]; + memset(aaSorted, 0, nByte); + for(ii=0; iinDim; ii++){ + int jj; + aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell]; + for(jj=0; jjnDim; ii++){ + RtreeDValue margin = 0.0; + RtreeDValue fBestOverlap = 0.0; + RtreeDValue fBestArea = 0.0; + int iBestLeft = 0; + int nLeft; + + for( + nLeft=RTREE_MINCELLS(pRtree); + nLeft<=(nCell-RTREE_MINCELLS(pRtree)); + nLeft++ + ){ + RtreeCell left; + RtreeCell right; + int kk; + RtreeDValue overlap; + RtreeDValue area; + + memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell)); + memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell)); + for(kk=1; kk<(nCell-1); kk++){ + if( kk0; i--){ + RtreeCell *pNext; + pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed); + RtreeDValue diff = + cellGrowth(pRtree, pBboxLeft, pNext) - + cellGrowth(pRtree, pBboxRight, pNext) + ; + if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i) + || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i)) + ){ + nodeInsertCell(pRtree, pRight, pNext); + cellUnion(pRtree, pBboxRight, pNext); + }else{ + nodeInsertCell(pRtree, pLeft, pNext); + cellUnion(pRtree, pBboxLeft, pNext); + } + } + + sqlite3_free(aiUsed); + return SQLITE_OK; +} +#endif + +static int updateMapping( + Rtree *pRtree, + i64 iRowid, + RtreeNode *pNode, + int iHeight +){ + int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64); + xSetMapping = ((iHeight==0)?rowidWrite:parentWrite); + if( iHeight>0 ){ + RtreeNode *pChild = nodeHashLookup(pRtree, iRowid); + if( pChild ){ + nodeRelease(pRtree, pChild->pParent); + nodeReference(pNode); + pChild->pParent = pNode; + } + } + return xSetMapping(pRtree, iRowid, pNode->iNode); +} + +static int SplitNode( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell, + int iHeight +){ + int i; + int newCellIsRight = 0; + + int rc = SQLITE_OK; + int nCell = NCELL(pNode); + RtreeCell *aCell; + int *aiUsed; + + RtreeNode *pLeft = 0; + RtreeNode *pRight = 0; + + RtreeCell leftbbox; + RtreeCell rightbbox; + + /* Allocate an array and populate it with a copy of pCell and + ** all cells from node pLeft. Then zero the original node. + */ + aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); + if( !aCell ){ + rc = SQLITE_NOMEM; + goto splitnode_out; + } + aiUsed = (int *)&aCell[nCell+1]; + memset(aiUsed, 0, sizeof(int)*(nCell+1)); + for(i=0; iiNode==1 ){ + pRight = nodeNew(pRtree, pNode); + pLeft = nodeNew(pRtree, pNode); + pRtree->iDepth++; + pNode->isDirty = 1; + writeInt16(pNode->zData, pRtree->iDepth); + }else{ + pLeft = pNode; + pRight = nodeNew(pRtree, pLeft->pParent); + nodeReference(pLeft); + } + + if( !pLeft || !pRight ){ + rc = SQLITE_NOMEM; + goto splitnode_out; + } + + memset(pLeft->zData, 0, pRtree->iNodeSize); + memset(pRight->zData, 0, pRtree->iNodeSize); + + rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox); + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + + /* Ensure both child nodes have node numbers assigned to them by calling + ** nodeWrite(). Node pRight always needs a node number, as it was created + ** by nodeNew() above. But node pLeft sometimes already has a node number. + ** In this case avoid the all to nodeWrite(). + */ + if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)) + || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) + ){ + goto splitnode_out; + } + + rightbbox.iRowid = pRight->iNode; + leftbbox.iRowid = pLeft->iNode; + + if( pNode->iNode==1 ){ + rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + }else{ + RtreeNode *pParent = pLeft->pParent; + int iCell; + rc = nodeParentIndex(pRtree, pLeft, &iCell); + if( rc==SQLITE_OK ){ + nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); + rc = AdjustTree(pRtree, pParent, &leftbbox); + } + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + } + if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ + goto splitnode_out; + } + + for(i=0; iiRowid ){ + newCellIsRight = 1; + } + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + } + if( pNode->iNode==1 ){ + for(i=0; iiRowid, pLeft, iHeight); + } + + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pRight); + pRight = 0; + } + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pLeft); + pLeft = 0; + } + +splitnode_out: + nodeRelease(pRtree, pRight); + nodeRelease(pRtree, pLeft); + sqlite3_free(aCell); + return rc; +} + +/* +** If node pLeaf is not the root of the r-tree and its pParent pointer is +** still NULL, load all ancestor nodes of pLeaf into memory and populate +** the pLeaf->pParent chain all the way up to the root node. +** +** This operation is required when a row is deleted (or updated - an update +** is implemented as a delete followed by an insert). SQLite provides the +** rowid of the row to delete, which can be used to find the leaf on which +** the entry resides (argument pLeaf). Once the leaf is located, this +** function is called to determine its ancestry. +*/ +static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ + int rc = SQLITE_OK; + RtreeNode *pChild = pLeaf; + while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){ + int rc2 = SQLITE_OK; /* sqlite3_reset() return code */ + sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode); + rc = sqlite3_step(pRtree->pReadParent); + if( rc==SQLITE_ROW ){ + RtreeNode *pTest; /* Used to test for reference loops */ + i64 iNode; /* Node number of parent node */ + + /* Before setting pChild->pParent, test that we are not creating a + ** loop of references (as we would if, say, pChild==pParent). We don't + ** want to do this as it leads to a memory leak when trying to delete + ** the referenced counted node structures. + */ + iNode = sqlite3_column_int64(pRtree->pReadParent, 0); + for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent); + if( !pTest ){ + rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent); + } + } + rc = sqlite3_reset(pRtree->pReadParent); + if( rc==SQLITE_OK ) rc = rc2; + if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB; + pChild = pChild->pParent; + } + return rc; +} + +static int deleteCell(Rtree *, RtreeNode *, int, int); + +static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){ + int rc; + int rc2; + RtreeNode *pParent = 0; + int iCell; + + assert( pNode->nRef==1 ); + + /* Remove the entry in the parent cell. */ + rc = nodeParentIndex(pRtree, pNode, &iCell); + if( rc==SQLITE_OK ){ + pParent = pNode->pParent; + pNode->pParent = 0; + rc = deleteCell(pRtree, pParent, iCell, iHeight+1); + } + rc2 = nodeRelease(pRtree, pParent); + if( rc==SQLITE_OK ){ + rc = rc2; + } + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Remove the xxx_node entry. */ + sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); + sqlite3_step(pRtree->pDeleteNode); + if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){ + return rc; + } + + /* Remove the xxx_parent entry. */ + sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); + sqlite3_step(pRtree->pDeleteParent); + if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){ + return rc; + } + + /* Remove the node from the in-memory hash table and link it into + ** the Rtree.pDeleted list. Its contents will be re-inserted later on. + */ + nodeHashDelete(pRtree, pNode); + pNode->iNode = iHeight; + pNode->pNext = pRtree->pDeleted; + pNode->nRef++; + pRtree->pDeleted = pNode; + + return SQLITE_OK; +} + +static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){ + RtreeNode *pParent = pNode->pParent; + int rc = SQLITE_OK; + if( pParent ){ + int ii; + int nCell = NCELL(pNode); + RtreeCell box; /* Bounding box for pNode */ + nodeGetCell(pRtree, pNode, 0, &box); + for(ii=1; iiiNode; + rc = nodeParentIndex(pRtree, pNode, &ii); + if( rc==SQLITE_OK ){ + nodeOverwriteCell(pRtree, pParent, &box, ii); + rc = fixBoundingBox(pRtree, pParent); + } + } + return rc; +} + +/* +** Delete the cell at index iCell of node pNode. After removing the +** cell, adjust the r-tree data structure if required. +*/ +static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){ + RtreeNode *pParent; + int rc; + + if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){ + return rc; + } + + /* Remove the cell from the node. This call just moves bytes around + ** the in-memory node image, so it cannot fail. + */ + nodeDeleteCell(pRtree, pNode, iCell); + + /* If the node is not the tree root and now has less than the minimum + ** number of cells, remove it from the tree. Otherwise, update the + ** cell in the parent node so that it tightly contains the updated + ** node. + */ + pParent = pNode->pParent; + assert( pParent || pNode->iNode==1 ); + if( pParent ){ + if( NCELL(pNode)nDim; iDim++){ + aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]); + aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]); + } + } + for(iDim=0; iDimnDim; iDim++){ + aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2)); + } + + for(ii=0; iinDim; iDim++){ + RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - + DCOORD(aCell[ii].aCoord[iDim*2])); + aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]); + } + } + + SortByDistance(aOrder, nCell, aDistance, aSpare); + nodeZero(pRtree, pNode); + + for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){ + RtreeCell *p = &aCell[aOrder[ii]]; + nodeInsertCell(pRtree, pNode, p); + if( p->iRowid==pCell->iRowid ){ + if( iHeight==0 ){ + rc = rowidWrite(pRtree, p->iRowid, pNode->iNode); + }else{ + rc = parentWrite(pRtree, p->iRowid, pNode->iNode); + } + } + } + if( rc==SQLITE_OK ){ + rc = fixBoundingBox(pRtree, pNode); + } + for(; rc==SQLITE_OK && iiiNode currently contains + ** the height of the sub-tree headed by the cell. + */ + RtreeNode *pInsert; + RtreeCell *p = &aCell[aOrder[ii]]; + rc = ChooseLeaf(pRtree, p, iHeight, &pInsert); + if( rc==SQLITE_OK ){ + int rc2; + rc = rtreeInsertCell(pRtree, pInsert, p, iHeight); + rc2 = nodeRelease(pRtree, pInsert); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + + sqlite3_free(aCell); + return rc; +} + +/* +** Insert cell pCell into node pNode. Node pNode is the head of a +** subtree iHeight high (leaf nodes have iHeight==0). +*/ +static int rtreeInsertCell( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell, + int iHeight +){ + int rc = SQLITE_OK; + if( iHeight>0 ){ + RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid); + if( pChild ){ + nodeRelease(pRtree, pChild->pParent); + nodeReference(pNode); + pChild->pParent = pNode; + } + } + if( nodeInsertCell(pRtree, pNode, pCell) ){ +#if VARIANT_RSTARTREE_REINSERT + if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){ + rc = SplitNode(pRtree, pNode, pCell, iHeight); + }else{ + pRtree->iReinsertHeight = iHeight; + rc = Reinsert(pRtree, pNode, pCell, iHeight); + } +#else + rc = SplitNode(pRtree, pNode, pCell, iHeight); +#endif + }else{ + rc = AdjustTree(pRtree, pNode, pCell); + if( rc==SQLITE_OK ){ + if( iHeight==0 ){ + rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode); + }else{ + rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode); + } + } + } + return rc; +} + +static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){ + int ii; + int rc = SQLITE_OK; + int nCell = NCELL(pNode); + + for(ii=0; rc==SQLITE_OK && iiiNode currently contains + ** the height of the sub-tree headed by the cell. + */ + rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert); + if( rc==SQLITE_OK ){ + int rc2; + rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode); + rc2 = nodeRelease(pRtree, pInsert); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + return rc; +} + +/* +** Select a currently unused rowid for a new r-tree record. +*/ +static int newRowid(Rtree *pRtree, i64 *piRowid){ + int rc; + sqlite3_bind_null(pRtree->pWriteRowid, 1); + sqlite3_bind_null(pRtree->pWriteRowid, 2); + sqlite3_step(pRtree->pWriteRowid); + rc = sqlite3_reset(pRtree->pWriteRowid); + *piRowid = sqlite3_last_insert_rowid(pRtree->db); + return rc; +} + +/* +** Remove the entry with rowid=iDelete from the r-tree structure. +*/ +static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ + int rc; /* Return code */ + RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */ + int iCell; /* Index of iDelete cell in pLeaf */ + RtreeNode *pRoot; /* Root node of rtree structure */ + + + /* Obtain a reference to the root node to initialize Rtree.iDepth */ + rc = nodeAcquire(pRtree, 1, 0, &pRoot); + + /* Obtain a reference to the leaf node that contains the entry + ** about to be deleted. + */ + if( rc==SQLITE_OK ){ + rc = findLeafNode(pRtree, iDelete, &pLeaf); + } + + /* Delete the cell in question from the leaf node. */ + if( rc==SQLITE_OK ){ + int rc2; + rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell); + if( rc==SQLITE_OK ){ + rc = deleteCell(pRtree, pLeaf, iCell, 0); + } + rc2 = nodeRelease(pRtree, pLeaf); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + + /* Delete the corresponding entry in the _rowid table. */ + if( rc==SQLITE_OK ){ + sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); + sqlite3_step(pRtree->pDeleteRowid); + rc = sqlite3_reset(pRtree->pDeleteRowid); + } + + /* Check if the root node now has exactly one child. If so, remove + ** it, schedule the contents of the child for reinsertion and + ** reduce the tree height by one. + ** + ** This is equivalent to copying the contents of the child into + ** the root node (the operation that Gutman's paper says to perform + ** in this scenario). + */ + if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){ + int rc2; + RtreeNode *pChild; + i64 iChild = nodeGetRowid(pRtree, pRoot, 0); + rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); + if( rc==SQLITE_OK ){ + rc = removeNode(pRtree, pChild, pRtree->iDepth-1); + } + rc2 = nodeRelease(pRtree, pChild); + if( rc==SQLITE_OK ) rc = rc2; + if( rc==SQLITE_OK ){ + pRtree->iDepth--; + writeInt16(pRoot->zData, pRtree->iDepth); + pRoot->isDirty = 1; + } + } + + /* Re-insert the contents of any underfull nodes removed from the tree. */ + for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){ + if( rc==SQLITE_OK ){ + rc = reinsertNodeContent(pRtree, pLeaf); + } + pRtree->pDeleted = pLeaf->pNext; + sqlite3_free(pLeaf); + } + + /* Release the reference to the root node. */ + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pRoot); + }else{ + nodeRelease(pRtree, pRoot); + } + + return rc; +} + +/* +** Rounding constants for float->double conversion. +*/ +#define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */ +#define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */ + +#if !defined(SQLITE_RTREE_INT_ONLY) +/* +** Convert an sqlite3_value into an RtreeValue (presumably a float) +** while taking care to round toward negative or positive, respectively. +*/ +static RtreeValue rtreeValueDown(sqlite3_value *v){ + double d = sqlite3_value_double(v); + float f = (float)d; + if( f>d ){ + f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS)); + } + return f; +} +static RtreeValue rtreeValueUp(sqlite3_value *v){ + double d = sqlite3_value_double(v); + float f = (float)d; + if( f1 */ + int bHaveRowid = 0; /* Set to 1 after new rowid is determined */ + + rtreeReference(pRtree); + assert(nData>=1); + + /* Constraint handling. A write operation on an r-tree table may return + ** SQLITE_CONSTRAINT for two reasons: + ** + ** 1. A duplicate rowid value, or + ** 2. The supplied data violates the "x2>=x1" constraint. + ** + ** In the first case, if the conflict-handling mode is REPLACE, then + ** the conflicting row can be removed before proceeding. In the second + ** case, SQLITE_CONSTRAINT must be returned regardless of the + ** conflict-handling mode specified by the user. + */ + if( nData>1 ){ + int ii; + + /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */ + assert( nData==(pRtree->nDim*2 + 3) ); +#ifndef SQLITE_RTREE_INT_ONLY + if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]); + cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]); + if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){ + rc = SQLITE_CONSTRAINT; + goto constraint; + } + } + }else +#endif + { + for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]); + cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]); + if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){ + rc = SQLITE_CONSTRAINT; + goto constraint; + } + } + } + + /* If a rowid value was supplied, check if it is already present in + ** the table. If so, the constraint has failed. */ + if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){ + cell.iRowid = sqlite3_value_int64(azData[2]); + if( sqlite3_value_type(azData[0])==SQLITE_NULL + || sqlite3_value_int64(azData[0])!=cell.iRowid + ){ + int steprc; + sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); + steprc = sqlite3_step(pRtree->pReadRowid); + rc = sqlite3_reset(pRtree->pReadRowid); + if( SQLITE_ROW==steprc ){ + if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ + rc = rtreeDeleteRowid(pRtree, cell.iRowid); + }else{ + rc = SQLITE_CONSTRAINT; + goto constraint; + } + } + } + bHaveRowid = 1; + } + } + + /* If azData[0] is not an SQL NULL value, it is the rowid of a + ** record to delete from the r-tree table. The following block does + ** just that. + */ + if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){ + rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0])); + } + + /* If the azData[] array contains more than one element, elements + ** (azData[2]..azData[argc-1]) contain a new record to insert into + ** the r-tree structure. + */ + if( rc==SQLITE_OK && nData>1 ){ + /* Insert the new record into the r-tree */ + RtreeNode *pLeaf = 0; + + /* Figure out the rowid of the new row. */ + if( bHaveRowid==0 ){ + rc = newRowid(pRtree, &cell.iRowid); + } + *pRowid = cell.iRowid; + + if( rc==SQLITE_OK ){ + rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); + } + if( rc==SQLITE_OK ){ + int rc2; + pRtree->iReinsertHeight = -1; + rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); + rc2 = nodeRelease(pRtree, pLeaf); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + +constraint: + rtreeRelease(pRtree); + return rc; +} + +/* +** The xRename method for rtree module virtual tables. +*/ +static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ + Rtree *pRtree = (Rtree *)pVtab; + int rc = SQLITE_NOMEM; + char *zSql = sqlite3_mprintf( + "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";" + "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";" + "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";" + , pRtree->zDb, pRtree->zName, zNewName + , pRtree->zDb, pRtree->zName, zNewName + , pRtree->zDb, pRtree->zName, zNewName + ); + if( zSql ){ + rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } + return rc; +} + +static sqlite3_module rtreeModule = { + 0, /* iVersion */ + rtreeCreate, /* xCreate - create a table */ + rtreeConnect, /* xConnect - connect to an existing table */ + rtreeBestIndex, /* xBestIndex - Determine search strategy */ + rtreeDisconnect, /* xDisconnect - Disconnect from a table */ + rtreeDestroy, /* xDestroy - Drop a table */ + rtreeOpen, /* xOpen - open a cursor */ + rtreeClose, /* xClose - close a cursor */ + rtreeFilter, /* xFilter - configure scan constraints */ + rtreeNext, /* xNext - advance a cursor */ + rtreeEof, /* xEof */ + rtreeColumn, /* xColumn - read data */ + rtreeRowid, /* xRowid - read data */ + rtreeUpdate, /* xUpdate - write data */ + 0, /* xBegin - begin transaction */ + 0, /* xSync - sync transaction */ + 0, /* xCommit - commit transaction */ + 0, /* xRollback - rollback transaction */ + 0, /* xFindFunction - function overloading */ + rtreeRename, /* xRename - rename the table */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0 /* xRollbackTo */ +}; + +static int rtreeSqlInit( + Rtree *pRtree, + sqlite3 *db, + const char *zDb, + const char *zPrefix, + int isCreate +){ + int rc = SQLITE_OK; + + #define N_STATEMENT 9 + static const char *azSql[N_STATEMENT] = { + /* Read and write the xxx_node table */ + "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1", + "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)", + "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1", + + /* Read and write the xxx_rowid table */ + "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1", + "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)", + "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1", + + /* Read and write the xxx_parent table */ + "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1", + "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)", + "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1" + }; + sqlite3_stmt **appStmt[N_STATEMENT]; + int i; + + pRtree->db = db; + + if( isCreate ){ + char *zCreate = sqlite3_mprintf( +"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);" +"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);" +"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);" +"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))", + zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize + ); + if( !zCreate ){ + return SQLITE_NOMEM; + } + rc = sqlite3_exec(db, zCreate, 0, 0, 0); + sqlite3_free(zCreate); + if( rc!=SQLITE_OK ){ + return rc; + } + } + + appStmt[0] = &pRtree->pReadNode; + appStmt[1] = &pRtree->pWriteNode; + appStmt[2] = &pRtree->pDeleteNode; + appStmt[3] = &pRtree->pReadRowid; + appStmt[4] = &pRtree->pWriteRowid; + appStmt[5] = &pRtree->pDeleteRowid; + appStmt[6] = &pRtree->pReadParent; + appStmt[7] = &pRtree->pWriteParent; + appStmt[8] = &pRtree->pDeleteParent; + + for(i=0; iiNodeSize is populated and SQLITE_OK returned. +** Otherwise, an SQLite error code is returned. +** +** If this function is being called as part of an xConnect(), then the rtree +** table already exists. In this case the node-size is determined by inspecting +** the root node of the tree. +** +** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. +** This ensures that each node is stored on a single database page. If the +** database page-size is so large that more than RTREE_MAXCELLS entries +** would fit in a single node, use a smaller node-size. +*/ +static int getNodeSize( + sqlite3 *db, /* Database handle */ + Rtree *pRtree, /* Rtree handle */ + int isCreate, /* True for xCreate, false for xConnect */ + char **pzErr /* OUT: Error message, if any */ +){ + int rc; + char *zSql; + if( isCreate ){ + int iPageSize = 0; + zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb); + rc = getIntFromStmt(db, zSql, &iPageSize); + if( rc==SQLITE_OK ){ + pRtree->iNodeSize = iPageSize-64; + if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)iNodeSize ){ + pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS; + } + }else{ + *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + } + }else{ + zSql = sqlite3_mprintf( + "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1", + pRtree->zDb, pRtree->zName + ); + rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize); + if( rc!=SQLITE_OK ){ + *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + } + } + + sqlite3_free(zSql); + return rc; +} + +/* +** This function is the implementation of both the xConnect and xCreate +** methods of the r-tree virtual table. +** +** argv[0] -> module name +** argv[1] -> database name +** argv[2] -> table name +** argv[...] -> column names... +*/ +static int rtreeInit( + sqlite3 *db, /* Database connection */ + void *pAux, /* One of the RTREE_COORD_* constants */ + int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ + sqlite3_vtab **ppVtab, /* OUT: New virtual table */ + char **pzErr, /* OUT: Error message, if any */ + int isCreate /* True for xCreate, false for xConnect */ +){ + int rc = SQLITE_OK; + Rtree *pRtree; + int nDb; /* Length of string argv[1] */ + int nName; /* Length of string argv[2] */ + int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32); + + const char *aErrMsg[] = { + 0, /* 0 */ + "Wrong number of columns for an rtree table", /* 1 */ + "Too few columns for an rtree table", /* 2 */ + "Too many columns for an rtree table" /* 3 */ + }; + + int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2; + if( aErrMsg[iErr] ){ + *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); + return SQLITE_ERROR; + } + + sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); + + /* Allocate the sqlite3_vtab structure */ + nDb = (int)strlen(argv[1]); + nName = (int)strlen(argv[2]); + pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2); + if( !pRtree ){ + return SQLITE_NOMEM; + } + memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); + pRtree->nBusy = 1; + pRtree->base.pModule = &rtreeModule; + pRtree->zDb = (char *)&pRtree[1]; + pRtree->zName = &pRtree->zDb[nDb+1]; + pRtree->nDim = (argc-4)/2; + pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2; + pRtree->eCoordType = eCoordType; + memcpy(pRtree->zDb, argv[1], nDb); + memcpy(pRtree->zName, argv[2], nName); + + /* Figure out the node size to use. */ + rc = getNodeSize(db, pRtree, isCreate, pzErr); + + /* Create/Connect to the underlying relational database schema. If + ** that is successful, call sqlite3_declare_vtab() to configure + ** the r-tree table schema. + */ + if( rc==SQLITE_OK ){ + if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){ + *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + }else{ + char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]); + char *zTmp; + int ii; + for(ii=4; zSql && ii*2 coordinates. +*/ +static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ + char *zText = 0; + RtreeNode node; + Rtree tree; + int ii; + + UNUSED_PARAMETER(nArg); + memset(&node, 0, sizeof(RtreeNode)); + memset(&tree, 0, sizeof(Rtree)); + tree.nDim = sqlite3_value_int(apArg[0]); + tree.nBytesPerCell = 8 + 8 * tree.nDim; + node.zData = (u8 *)sqlite3_value_blob(apArg[1]); + + for(ii=0; iimagic = RTREE_GEOMETRY_MAGIC; + pBlob->xGeom = pGeomCtx->xGeom; + pBlob->pContext = pGeomCtx->pContext; + pBlob->nParam = nArg; + for(i=0; iaParam[i] = sqlite3_value_int64(aArg[i]); +#else + pBlob->aParam[i] = sqlite3_value_double(aArg[i]); +#endif + } + sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free); + } +} + +/* +** Register a new geometry function for use with the r-tree MATCH operator. +*/ +int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, + int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *), + void *pContext +){ + RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ + + /* Allocate and populate the context object. */ + pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); + if( !pGeomCtx ) return SQLITE_NOMEM; + pGeomCtx->xGeom = xGeom; + pGeomCtx->pContext = pContext; + + /* Create the new user-function. Register a destructor function to delete + ** the context object when it is no longer required. */ + return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, + (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free + ); +} + +#if !SQLITE_CORE +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_rtree_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi) + return sqlite3RtreeInit(db); +} +#endif + +#endif diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree.h b/components/external/SQLite-3.8.1/ext/rtree/rtree.h new file mode 100644 index 0000000000000000000000000000000000000000..1fdbcccc5ef6ee8f27352f7d8b7f0d72cbf1f40f --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree.h @@ -0,0 +1,26 @@ +/* +** 2008 May 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file is used by programs that want to link against the +** RTREE library. All it does is declare the sqlite3RtreeInit() interface. +*/ +#include "sqlite3.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +int sqlite3RtreeInit(sqlite3 *db); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree1.test b/components/external/SQLite-3.8.1/ext/rtree/rtree1.test new file mode 100644 index 0000000000000000000000000000000000000000..275b13264f71c56da63d0a3c7ac842eb09266a94 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree1.test @@ -0,0 +1,513 @@ +# 2008 Feb 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing the r-tree extension. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source [file join [file dirname [info script]] rtree_util.tcl] +source $testdir/tester.tcl +set testprefix rtree1 + +# Test plan: +# +# rtree-1.*: Creating/destroying r-tree tables. +# rtree-2.*: Test the implicit constraints - unique rowid and +# (coord[N]<=coord[N+1]) for even values of N. Also +# automatic assigning of rowid values. +# rtree-3.*: Linear scans of r-tree data. +# rtree-4.*: Test INSERT +# rtree-5.*: Test DELETE +# rtree-6.*: Test UPDATE +# rtree-7.*: Test renaming an r-tree table. +# rtree-8.*: Test constrained scans of r-tree data. +# +# rtree-12.*: Test that on-conflict clauses are supported. +# + +ifcapable !rtree { + finish_test + return +} + +#---------------------------------------------------------------------------- +# Test cases rtree-1.* test CREATE and DROP table statements. +# + +# Test creating and dropping an rtree table. +# +do_test rtree-1.1.1 { + execsql { CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2) } +} {} +do_test rtree-1.1.2 { + execsql { SELECT name FROM sqlite_master ORDER BY name } +} {t1 t1_node t1_parent t1_rowid} +do_test rtree-1.1.3 { + execsql { + DROP TABLE t1; + SELECT name FROM sqlite_master ORDER BY name; + } +} {} + +# Test creating and dropping an rtree table with an odd name in +# an attached database. +# +do_test rtree-1.2.1 { + file delete -force test2.db + execsql { + ATTACH 'test2.db' AS aux; + CREATE VIRTUAL TABLE aux.'a" "b' USING rtree(ii, x1, x2, y1, y2); + } +} {} +do_test rtree-1.2.2 { + execsql { SELECT name FROM sqlite_master ORDER BY name } +} {} +do_test rtree-1.2.3 { + execsql { SELECT name FROM aux.sqlite_master ORDER BY name } +} {{a" "b} {a" "b_node} {a" "b_parent} {a" "b_rowid}} +do_test rtree-1.2.4 { + execsql { + DROP TABLE aux.'a" "b'; + SELECT name FROM aux.sqlite_master ORDER BY name; + } +} {} + +# Test that the logic for checking the number of columns specified +# for an rtree table. Acceptable values are odd numbers between 3 and +# 11, inclusive. +# +set cols [list i1 i2 i3 i4 i5 i6 i7 i8 i9 iA iB iC iD iE iF iG iH iI iJ iK] +for {set nCol 1} {$nCol<[llength $cols]} {incr nCol} { + + set columns [join [lrange $cols 0 [expr {$nCol-1}]] ,] + + set X {0 {}} + if {$nCol%2 == 0} { set X {1 {Wrong number of columns for an rtree table}} } + if {$nCol < 3} { set X {1 {Too few columns for an rtree table}} } + if {$nCol > 11} { set X {1 {Too many columns for an rtree table}} } + + do_test rtree-1.3.$nCol { + catchsql " + CREATE VIRTUAL TABLE t1 USING rtree($columns); + " + } $X + + catchsql { DROP TABLE t1 } +} + +# Like execsql except display output as integer where that can be +# done without loss of information. +# +proc execsql_intout {sql} { + set out {} + foreach term [execsql $sql] { + regsub {\.0$} $term {} term + lappend out $term + } + return $out +} + +# Test that it is possible to open an existing database that contains +# r-tree tables. +# +do_test rtree-1.4.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2); + INSERT INTO t1 VALUES(1, 5.0, 10.0); + INSERT INTO t1 VALUES(2, 15.0, 20.0); + } +} {} +do_test rtree-1.4.2 { + db close + sqlite3 db test.db + execsql_intout { SELECT * FROM t1 ORDER BY ii } +} {1 5 10 2 15 20} +do_test rtree-1.4.3 { + execsql { DROP TABLE t1 } +} {} + +# Test that it is possible to create an r-tree table with ridiculous +# column names. +# +do_test rtree-1.5.1 { + execsql_intout { + CREATE VIRTUAL TABLE t1 USING rtree("the key", "x dim.", "x2'dim"); + INSERT INTO t1 VALUES(1, 2, 3); + SELECT "the key", "x dim.", "x2'dim" FROM t1; + } +} {1 2 3} +do_test rtree-1.5.1 { + execsql { DROP TABLE t1 } +} {} + +# Force the r-tree constructor to fail. +# +do_test rtree-1.6.1 { + execsql { CREATE TABLE t1_rowid(a); } + catchsql { + CREATE VIRTUAL TABLE t1 USING rtree("the key", "x dim.", "x2'dim"); + } +} {1 {table "t1_rowid" already exists}} +do_test rtree-1.6.1 { + execsql { DROP TABLE t1_rowid } +} {} + +#---------------------------------------------------------------------------- +# Test cases rtree-2.* +# +do_test rtree-2.1.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2); + SELECT * FROM t1; + } +} {} + +do_test rtree-2.1.2 { + execsql { INSERT INTO t1 VALUES(NULL, 1, 3, 2, 4) } + execsql_intout { SELECT * FROM t1 } +} {1 1 3 2 4} +do_test rtree-2.1.3 { + execsql { INSERT INTO t1 VALUES(NULL, 1, 3, 2, 4) } + execsql { SELECT rowid FROM t1 ORDER BY rowid } +} {1 2} +do_test rtree-2.1.3 { + execsql { INSERT INTO t1 VALUES(NULL, 1, 3, 2, 4) } + execsql { SELECT ii FROM t1 ORDER BY ii } +} {1 2 3} + +do_test rtree-2.2.1 { + catchsql { INSERT INTO t1 VALUES(2, 1, 3, 2, 4) } +} {1 {constraint failed}} +do_test rtree-2.2.2 { + catchsql { INSERT INTO t1 VALUES(4, 1, 3, 4, 2) } +} {1 {constraint failed}} +do_test rtree-2.2.3 { + catchsql { INSERT INTO t1 VALUES(4, 3, 1, 2, 4) } +} {1 {constraint failed}} +do_test rtree-2.2.4 { + execsql { SELECT ii FROM t1 ORDER BY ii } +} {1 2 3} + +do_test rtree-2.X { + execsql { DROP TABLE t1 } +} {} + +#---------------------------------------------------------------------------- +# Test cases rtree-3.* test linear scans of r-tree table data. To test +# this we have to insert some data into an r-tree, but that is not the +# focus of these tests. +# +do_test rtree-3.1.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2); + SELECT * FROM t1; + } +} {} +do_test rtree-3.1.2 { + execsql_intout { + INSERT INTO t1 VALUES(5, 1, 3, 2, 4); + SELECT * FROM t1; + } +} {5 1 3 2 4} +do_test rtree-3.1.3 { + execsql_intout { + INSERT INTO t1 VALUES(6, 2, 6, 4, 8); + SELECT * FROM t1; + } +} {5 1 3 2 4 6 2 6 4 8} + +# Test the constraint on the coordinates (c[i]<=c[i+1] where (i%2==0)): +do_test rtree-3.2.1 { + catchsql { INSERT INTO t1 VALUES(7, 2, 6, 4, 3) } +} {1 {constraint failed}} +do_test rtree-3.2.2 { + catchsql { INSERT INTO t1 VALUES(8, 2, 6, 3, 3) } +} {0 {}} + +#---------------------------------------------------------------------------- +# Test cases rtree-5.* test DELETE operations. +# +do_test rtree-5.1.1 { + execsql { CREATE VIRTUAL TABLE t2 USING rtree(ii, x1, x2) } +} {} +do_test rtree-5.1.2 { + execsql_intout { + INSERT INTO t2 VALUES(1, 10, 20); + INSERT INTO t2 VALUES(2, 30, 40); + INSERT INTO t2 VALUES(3, 50, 60); + SELECT * FROM t2 ORDER BY ii; + } +} {1 10 20 2 30 40 3 50 60} +do_test rtree-5.1.3 { + execsql_intout { + DELETE FROM t2 WHERE ii=2; + SELECT * FROM t2 ORDER BY ii; + } +} {1 10 20 3 50 60} +do_test rtree-5.1.4 { + execsql_intout { + DELETE FROM t2 WHERE ii=1; + SELECT * FROM t2 ORDER BY ii; + } +} {3 50 60} +do_test rtree-5.1.5 { + execsql { + DELETE FROM t2 WHERE ii=3; + SELECT * FROM t2 ORDER BY ii; + } +} {} +do_test rtree-5.1.6 { + execsql { SELECT * FROM t2_rowid } +} {} + +#---------------------------------------------------------------------------- +# Test cases rtree-5.* test UPDATE operations. +# +do_test rtree-6.1.1 { + execsql { CREATE VIRTUAL TABLE t3 USING rtree(ii, x1, x2, y1, y2) } +} {} +do_test rtree-6.1.2 { + execsql_intout { + INSERT INTO t3 VALUES(1, 2, 3, 4, 5); + UPDATE t3 SET x2=5; + SELECT * FROM t3; + } +} {1 2 5 4 5} +do_test rtree-6.1.3 { + execsql { UPDATE t3 SET ii = 2 } + execsql_intout { SELECT * FROM t3 } +} {2 2 5 4 5} + +#---------------------------------------------------------------------------- +# Test cases rtree-7.* test rename operations. +# +do_test rtree-7.1.1 { + execsql { + CREATE VIRTUAL TABLE t4 USING rtree(ii, x1, x2, y1, y2, z1, z2); + INSERT INTO t4 VALUES(1, 2, 3, 4, 5, 6, 7); + } +} {} +do_test rtree-7.1.2 { + execsql { ALTER TABLE t4 RENAME TO t5 } + execsql_intout { SELECT * FROM t5 } +} {1 2 3 4 5 6 7} +do_test rtree-7.1.3 { + db close + sqlite3 db test.db + execsql_intout { SELECT * FROM t5 } +} {1 2 3 4 5 6 7} +do_test rtree-7.1.4 { + execsql { ALTER TABLE t5 RENAME TO 'raisara "one"'''} + execsql_intout { SELECT * FROM "raisara ""one""'" } +} {1 2 3 4 5 6 7} +do_test rtree-7.1.5 { + execsql_intout { SELECT * FROM 'raisara "one"''' } +} {1 2 3 4 5 6 7} +do_test rtree-7.1.6 { + execsql { ALTER TABLE "raisara ""one""'" RENAME TO "abc 123" } + execsql_intout { SELECT * FROM "abc 123" } +} {1 2 3 4 5 6 7} +do_test rtree-7.1.7 { + db close + sqlite3 db test.db + execsql_intout { SELECT * FROM "abc 123" } +} {1 2 3 4 5 6 7} + +# An error midway through a rename operation. +do_test rtree-7.2.1 { + execsql { + CREATE TABLE t4_node(a); + } + catchsql { ALTER TABLE "abc 123" RENAME TO t4 } +} {1 {SQL logic error or missing database}} +do_test rtree-7.2.2 { + execsql_intout { SELECT * FROM "abc 123" } +} {1 2 3 4 5 6 7} +do_test rtree-7.2.3 { + execsql { + DROP TABLE t4_node; + CREATE TABLE t4_rowid(a); + } + catchsql { ALTER TABLE "abc 123" RENAME TO t4 } +} {1 {SQL logic error or missing database}} +do_test rtree-7.2.4 { + db close + sqlite3 db test.db + execsql_intout { SELECT * FROM "abc 123" } +} {1 2 3 4 5 6 7} +do_test rtree-7.2.5 { + execsql { DROP TABLE t4_rowid } + execsql { ALTER TABLE "abc 123" RENAME TO t4 } + execsql_intout { SELECT * FROM t4 } +} {1 2 3 4 5 6 7} + + +#---------------------------------------------------------------------------- +# Test cases rtree-8.* +# + +# Test that the function to determine if a leaf cell is part of the +# result set works. +do_test rtree-8.1.1 { + execsql { + CREATE VIRTUAL TABLE t6 USING rtree(ii, x1, x2); + INSERT INTO t6 VALUES(1, 3, 7); + INSERT INTO t6 VALUES(2, 4, 6); + } +} {} +do_test rtree-8.1.2 { execsql { SELECT ii FROM t6 WHERE x1>2 } } {1 2} +do_test rtree-8.1.3 { execsql { SELECT ii FROM t6 WHERE x1>3 } } {2} +do_test rtree-8.1.4 { execsql { SELECT ii FROM t6 WHERE x1>4 } } {} +do_test rtree-8.1.5 { execsql { SELECT ii FROM t6 WHERE x1>5 } } {} +do_test rtree-8.1.6 { execsql { SELECT ii FROM t6 WHERE x1<3 } } {} +do_test rtree-8.1.7 { execsql { SELECT ii FROM t6 WHERE x1<4 } } {1} +do_test rtree-8.1.8 { execsql { SELECT ii FROM t6 WHERE x1<5 } } {1 2} + +#---------------------------------------------------------------------------- +# Test cases rtree-9.* +# +# Test that ticket #3549 is fixed. +do_test rtree-9.1 { + execsql { + CREATE TABLE foo (id INTEGER PRIMARY KEY); + CREATE VIRTUAL TABLE bar USING rtree (id, minX, maxX, minY, maxY); + INSERT INTO foo VALUES (null); + INSERT INTO foo SELECT null FROM foo; + INSERT INTO foo SELECT null FROM foo; + INSERT INTO foo SELECT null FROM foo; + INSERT INTO foo SELECT null FROM foo; + INSERT INTO foo SELECT null FROM foo; + INSERT INTO foo SELECT null FROM foo; + DELETE FROM foo WHERE id > 40; + INSERT INTO bar SELECT NULL, 0, 0, 0, 0 FROM foo; + } +} {} + +# This used to crash. +do_test rtree-9.2 { + execsql { + SELECT count(*) FROM bar b1, bar b2, foo s1 WHERE s1.id = b1.id; + } +} {1600} +do_test rtree-9.3 { + execsql { + SELECT count(*) FROM bar b1, bar b2, foo s1 + WHERE b1.minX <= b2.maxX AND s1.id = b1.id; + } +} {1600} + +#------------------------------------------------------------------------- +# Ticket #3970: Check that the error message is meaningful when a +# keyword is used as a column name. +# +do_test rtree-10.1 { + catchsql { CREATE VIRTUAL TABLE t7 USING rtree(index, x1, y1, x2, y2) } +} {1 {near "index": syntax error}} + +#------------------------------------------------------------------------- +# Test last_insert_rowid(). +# +do_test rtree-11.1 { + execsql { + CREATE VIRTUAL TABLE t8 USING rtree(idx, x1, x2, y1, y2); + INSERT INTO t8 VALUES(1, 1.0, 1.0, 2.0, 2.0); + SELECT last_insert_rowid(); + } +} {1} +do_test rtree-11.2 { + execsql { + INSERT INTO t8 VALUES(NULL, 1.0, 1.0, 2.0, 2.0); + SELECT last_insert_rowid(); + } +} {2} + +#------------------------------------------------------------------------- +# Test on-conflict clause handling. +# +db_delete_and_reopen +do_execsql_test 12.0 { + CREATE VIRTUAL TABLE t1 USING rtree_i32(idx, x1, x2, y1, y2); + INSERT INTO t1 VALUES(1, 1, 2, 3, 4); + INSERT INTO t1 VALUES(2, 2, 3, 4, 5); + INSERT INTO t1 VALUES(3, 3, 4, 5, 6); + + CREATE TABLE source(idx, x1, x2, y1, y2); + INSERT INTO source VALUES(5, 8, 8, 8, 8); + INSERT INTO source VALUES(2, 7, 7, 7, 7); + +} +db_save_and_close +foreach {tn sql_template testdata} { + 1 "INSERT %CONF% INTO t1 VALUES(2, 7, 7, 7, 7)" { + ROLLBACK 0 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6} + ABORT 0 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + IGNORE 0 0 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + FAIL 0 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + REPLACE 0 0 {1 1 2 3 4 2 7 7 7 7 3 3 4 5 6 4 4 5 6 7} + } + + 2 "INSERT %CONF% INTO t1 SELECT * FROM source" { + ROLLBACK 1 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6} + ABORT 1 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + IGNORE 1 0 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7 5 8 8 8 8} + FAIL 1 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7 5 8 8 8 8} + REPLACE 1 0 {1 1 2 3 4 2 7 7 7 7 3 3 4 5 6 4 4 5 6 7 5 8 8 8 8} + } + + 3 "UPDATE %CONF% t1 SET idx = 2 WHERE idx = 4" { + ROLLBACK 1 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6} + ABORT 1 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + IGNORE 1 0 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + FAIL 1 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + REPLACE 1 0 {1 1 2 3 4 2 4 5 6 7 3 3 4 5 6} + } + + 3 "UPDATE %CONF% t1 SET idx = ((idx+1)%5)+1 WHERE idx > 2" { + ROLLBACK 1 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6} + ABORT 1 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + IGNORE 1 0 {1 1 2 3 4 2 2 3 4 5 4 4 5 6 7 5 3 4 5 6} + FAIL 1 1 {1 1 2 3 4 2 2 3 4 5 4 4 5 6 7 5 3 4 5 6} + REPLACE 1 0 {1 4 5 6 7 2 2 3 4 5 5 3 4 5 6} + } + + 4 "INSERT %CONF% INTO t1 VALUES(2, 7, 6, 7, 7)" { + ROLLBACK 0 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6} + ABORT 0 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + IGNORE 0 0 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + FAIL 0 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + REPLACE 0 1 {1 1 2 3 4 2 2 3 4 5 3 3 4 5 6 4 4 5 6 7} + } + +} { + foreach {mode uses error data} $testdata { + db_restore_and_reopen + + set sql [string map [list %CONF% "OR $mode"] $sql_template] + set testname "12.$tn.[string tolower $mode]" + + execsql { + BEGIN; + INSERT INTO t1 VALUES(4, 4, 5, 6, 7); + } + + set res(0) {0 {}} + set res(1) {1 {constraint failed}} + do_catchsql_test $testname.1 $sql $res($error) + do_test $testname.2 [list sql_uses_stmt db $sql] $uses + do_execsql_test $testname.3 { SELECT * FROM t1 ORDER BY idx } $data + + do_test $testname.4 { rtree_check db t1 } 0 + db close + } +} +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree2.test b/components/external/SQLite-3.8.1/ext/rtree/rtree2.test new file mode 100644 index 0000000000000000000000000000000000000000..f5d15cc6b935d1120df9e7c8e58a4a24acca5a65 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree2.test @@ -0,0 +1,150 @@ +# 2008 Feb 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing the r-tree extension. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source [file join [file dirname [info script]] rtree_util.tcl] +source $testdir/tester.tcl + +ifcapable !rtree { + finish_test + return +} + +set ::NROW 1000 +set ::NDEL 10 +set ::NSELECT 100 + +if {[info exists G(isquick)] && $G(isquick)} { + set ::NROW 100 + set ::NSELECT 10 +} + +foreach module {rtree_i32 rtree} { + for {set nDim 1} {$nDim <= 5} {incr nDim} { + + do_test rtree2-$module.$nDim.1 { + set cols [list] + foreach c [list c0 c1 c2 c3 c4 c5 c6 c7 c8 c9] { + lappend cols "$c REAL" + } + set cols [join [lrange $cols 0 [expr {$nDim*2-1}]] ", "] + execsql " + CREATE VIRTUAL TABLE t1 USING ${module}(ii, $cols); + CREATE TABLE t2 (ii, $cols); + " + } {} + + do_test rtree2-$module.$nDim.2 { + db transaction { + for {set ii 0} {$ii < $::NROW} {incr ii} { + #puts "Row $ii" + set values [list] + for {set jj 0} {$jj<$nDim*2} {incr jj} { + lappend values [expr int(rand()*1000)] + } + set values [join $values ,] + #puts [rtree_treedump db t1] + #puts "INSERT INTO t2 VALUES($ii, $values)" + set rc [catch {db eval "INSERT INTO t1 VALUES($ii, $values)"}] + if {$rc} { + incr ii -1 + } else { + db eval "INSERT INTO t2 VALUES($ii, $values)" + } + #if {[rtree_check db t1]} { + #puts [rtree_treedump db t1] + #exit + #} + } + } + + set t1 [execsql {SELECT * FROM t1 ORDER BY ii}] + set t2 [execsql {SELECT * FROM t2 ORDER BY ii}] + set rc [expr {$t1 eq $t2}] + if {$rc != 1} { + puts $t1 + puts $t2 + } + set rc + } {1} + + do_test rtree2-$module.$nDim.3 { + rtree_check db t1 + } 0 + + set OPS [list < > <= >= =] + for {set ii 0} {$ii < $::NSELECT} {incr ii} { + do_test rtree2-$module.$nDim.4.$ii.1 { + set where [list] + foreach look_three_dots! {. . .} { + set colidx [expr int(rand()*($nDim*2+1))-1] + if {$colidx<0} { + set col ii + } else { + set col "c$colidx" + } + set op [lindex $OPS [expr int(rand()*[llength $OPS])]] + set val [expr int(rand()*1000)] + lappend where "$col $op $val" + } + set where [join $where " AND "] + + set t1 [execsql "SELECT * FROM t1 WHERE $where ORDER BY ii"] + set t2 [execsql "SELECT * FROM t2 WHERE $where ORDER BY ii"] + set rc [expr {$t1 eq $t2}] + if {$rc != 1} { + #puts $where + puts $t1 + puts $t2 + #puts [rtree_treedump db t1] + #breakpoint + #set t1 [execsql "SELECT * FROM t1 WHERE $where ORDER BY ii"] + #exit + } + set rc + } {1} + } + + for {set ii 0} {$ii < $::NROW} {incr ii $::NDEL} { + #puts [rtree_treedump db t1] + do_test rtree2-$module.$nDim.5.$ii.1 { + execsql "DELETE FROM t2 WHERE ii <= $::ii" + execsql "DELETE FROM t1 WHERE ii <= $::ii" + + set t1 [execsql {SELECT * FROM t1 ORDER BY ii}] + set t2 [execsql {SELECT * FROM t2 ORDER BY ii}] + set rc [expr {$t1 eq $t2}] + if {$rc != 1} { + puts $t1 + puts $t2 + } + set rc + } {1} + do_test rtree2-$module.$nDim.5.$ii.2 { + rtree_check db t1 + } {0} + } + + do_test rtree2-$module.$nDim.6 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + } + } {} + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree3.test b/components/external/SQLite-3.8.1/ext/rtree/rtree3.test new file mode 100644 index 0000000000000000000000000000000000000000..fea5513069bb1fddcd10021e44da80d7be52e6c4 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree3.test @@ -0,0 +1,237 @@ +# 2008 Feb 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing that the r-tree correctly handles +# out-of-memory conditions. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +ifcapable !rtree { + finish_test + return +} + +# Test summary: +# +# rtree3-1: Test OOM in simple CREATE TABLE, INSERT, DELETE and SELECT +# commands on an almost empty table. +# +# rtree3-2: Test OOM in a DROP TABLE command. +# +# rtree3-3a: Test OOM during a transaction to insert 100 pseudo-random rows. +# +# rtree3-3b: Test OOM during a transaction deleting all entries in the +# database constructed in [rtree3-3a] in pseudo-random order. +# +# rtree3-4a: OOM during "SELECT count(*) FROM ..." on a big table. +# +# rtree3-4b: OOM while deleting rows from a big table. +# +# rtree3-5: Test OOM while inserting rows into a big table. +# +# rtree3-6: Test OOM while deleting all rows of a table, one at a time. +# +# rtree3-7: OOM during an ALTER TABLE RENAME TABLE command. +# +# rtree3-8: Test OOM while registering the r-tree module with sqlite. +# + +do_faultsim_test rtree3-1 -faults oom* -prep { + faultsim_delete_and_reopen +} -body { + execsql { + BEGIN TRANSACTION; + CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2); + INSERT INTO rt VALUES(NULL, 3, 5, 7, 9); + INSERT INTO rt VALUES(NULL, 13, 15, 17, 19); + DELETE FROM rt WHERE ii = 1; + SELECT * FROM rt; + SELECT ii FROM rt WHERE ii = 2; + COMMIT; + } +} + +do_test rtree3-2.prep { + faultsim_delete_and_reopen + execsql { + CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2); + INSERT INTO rt VALUES(NULL, 3, 5, 7, 9); + } + faultsim_save_and_close +} {} +do_faultsim_test rtree3-2 -faults oom* -prep { + faultsim_restore_and_reopen +} -body { + execsql { DROP TABLE rt } +} + +do_malloc_test rtree3-3.prep { + faultsim_delete_and_reopen + execsql { + CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2); + INSERT INTO rt VALUES(NULL, 3, 5, 7, 9); + } + faultsim_save_and_close +} {} + +do_faultsim_test rtree3-3a -faults oom* -prep { + faultsim_restore_and_reopen +} -body { + db eval BEGIN + for {set ii 0} {$ii < 100} {incr ii} { + set f [expr rand()] + db eval {INSERT INTO rt VALUES(NULL, $f*10.0, $f*10.0, $f*15.0, $f*15.0)} + } + db eval COMMIT +} +faultsim_save_and_close + +do_faultsim_test rtree3-3b -faults oom* -prep { + faultsim_restore_and_reopen +} -body { + db eval BEGIN + for {set ii 0} {$ii < 100} {incr ii} { + set f [expr rand()] + db eval { DELETE FROM rt WHERE x1<($f*10.0) AND x1>($f*10.5) } + } + db eval COMMIT +} + +do_test rtree3-4.prep { + faultsim_delete_and_reopen + execsql { + BEGIN; + PRAGMA page_size = 512; + CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2); + } + for {set i 0} {$i < 1500} {incr i} { + execsql { INSERT INTO rt VALUES($i, $i, $i+1, $i, $i+1) } + } + execsql { COMMIT } + faultsim_save_and_close +} {} + +do_faultsim_test rtree3-4a -faults oom-* -prep { + faultsim_restore_and_reopen +} -body { + db eval { SELECT count(*) FROM rt } +} -test { + faultsim_test_result {0 1500} +} + +do_faultsim_test rtree3-4b -faults oom-transient -prep { + faultsim_restore_and_reopen +} -body { + db eval { DELETE FROM rt WHERE ii BETWEEN 1 AND 100 } +} -test { + faultsim_test_result {0 {}} +} + +do_test rtree3-5.prep { + faultsim_delete_and_reopen + execsql { + BEGIN; + PRAGMA page_size = 512; + CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2); + } + for {set i 0} {$i < 100} {incr i} { + execsql { INSERT INTO rt VALUES($i, $i, $i+1, $i, $i+1) } + } + execsql { COMMIT } + faultsim_save_and_close +} {} +do_faultsim_test rtree3-5 -faults oom-* -prep { + faultsim_restore_and_reopen +} -body { + for {set i 100} {$i < 110} {incr i} { + execsql { INSERT INTO rt VALUES($i, $i, $i+1, $i, $i+1) } + } +} -test { + faultsim_test_result {0 {}} +} + +do_test rtree3-6.prep { + faultsim_delete_and_reopen + execsql { + BEGIN; + PRAGMA page_size = 512; + CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2); + } + for {set i 0} {$i < 50} {incr i} { + execsql { INSERT INTO rt VALUES($i, $i, $i+1, $i, $i+1) } + } + execsql { COMMIT } + faultsim_save_and_close +} {} +do_faultsim_test rtree3-6 -faults oom-* -prep { + faultsim_restore_and_reopen +} -body { + execsql BEGIN + for {set i 0} {$i < 50} {incr i} { + execsql { DELETE FROM rt WHERE ii=$i } + } + execsql COMMIT +} -test { + faultsim_test_result {0 {}} +} + +do_test rtree3-7.prep { + faultsim_delete_and_reopen + execsql { CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2) } + faultsim_save_and_close +} {} +do_faultsim_test rtree3-7 -faults oom-* -prep { + faultsim_restore_and_reopen +} -body { + execsql { ALTER TABLE rt RENAME TO rt2 } +} -test { + faultsim_test_result {0 {}} +} + +do_faultsim_test rtree3-8 -faults oom-* -prep { + catch { db close } +} -body { + sqlite3 db test.db +} + +do_faultsim_test rtree3-9 -faults oom-* -prep { + sqlite3 db :memory: +} -body { + set rc [register_cube_geom db] + if {$rc != "SQLITE_OK"} { error $rc } +} -test { + faultsim_test_result {0 {}} {1 SQLITE_NOMEM} +} + +do_test rtree3-10.prep { + faultsim_delete_and_reopen + execsql { + CREATE VIRTUAL TABLE rt USING rtree(ii, x1, x2, y1, y2, z1, z2); + INSERT INTO rt VALUES(1, 10, 10, 10, 11, 11, 11); + INSERT INTO rt VALUES(2, 5, 6, 6, 7, 7, 8); + } + faultsim_save_and_close +} {} +do_faultsim_test rtree3-10 -faults oom-* -prep { + faultsim_restore_and_reopen + register_cube_geom db + execsql { SELECT * FROM rt } +} -body { + execsql { SELECT ii FROM rt WHERE ii MATCH cube(4.5, 5.5, 6.5, 1, 1, 1) } +} -test { + faultsim_test_result {0 2} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree4.test b/components/external/SQLite-3.8.1/ext/rtree/rtree4.test new file mode 100644 index 0000000000000000000000000000000000000000..a3872b073569426bf368bc9fd2ee70dddc8945cc --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree4.test @@ -0,0 +1,251 @@ +# 2008 May 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Randomized test cases for the rtree extension. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl + +ifcapable !rtree { + finish_test + return +} + +set ::NROW 2500 +if {[info exists G(isquick)] && $G(isquick)} { + set ::NROW 250 +} + +ifcapable !rtree_int_only { + # Return a floating point number between -X and X. + # + proc rand {X} { + return [expr {int((rand()-0.5)*1024.0*$X)/512.0}] + } + + # Return a positive floating point number less than or equal to X + # + proc randincr {X} { + while 1 { + set r [expr {int(rand()*$X*32.0)/32.0}] + if {$r>0.0} {return $r} + } + } +} else { + # For rtree_int_only, return an number between -X and X. + # + proc rand {X} { + return [expr {int((rand()-0.5)*2*$X)}] + } + + # Return a positive integer less than or equal to X + # + proc randincr {X} { + while 1 { + set r [expr {int(rand()*$X)+1}] + if {$r>0} {return $r} + } + } +} + +# Scramble the $inlist into a random order. +# +proc scramble {inlist} { + set y {} + foreach x $inlist { + lappend y [list [expr {rand()}] $x] + } + set y [lsort $y] + set outlist {} + foreach x $y { + lappend outlist [lindex $x 1] + } + return $outlist +} + +# Always use the same random seed so that the sequence of tests +# is repeatable. +# +expr {srand(1234)} + +# Run these tests for all number of dimensions between 1 and 5. +# +for {set nDim 1} {$nDim<=5} {incr nDim} { + + # Construct an rtree virtual table and an ordinary btree table + # to mirror it. The ordinary table should be much slower (since + # it has to do a full table scan) but should give the exact same + # answers. + # + do_test rtree4-$nDim.1 { + set clist {} + set cklist {} + for {set i 0} {$i<$nDim} {incr i} { + lappend clist mn$i mx$i + lappend cklist "mn$i=$mn mx$j<=$mx + } + set where "WHERE [join $where { AND }]" + do_test rtree4-$nDim.2.$i.2 { + list $where [db eval "SELECT id FROM rx $where ORDER BY id"] + } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]] + + # Do an overlaps query on all dimensions + # + set where {} + for {set j 0} {$j<$nDim} {incr j} { + set mn [rand 10000] + set mx [expr {$mn+[randincr 500]}] + lappend where mx$j>=$mn mn$j<=$mx + } + set where "WHERE [join $where { AND }]" + do_test rtree4-$nDim.2.$i.3 { + list $where [db eval "SELECT id FROM rx $where ORDER BY id"] + } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]] + + # Do a contained-in query with surplus contraints at the beginning. + # This should force a full-table scan on the rtree. + # + set where {} + for {set j 0} {$j<$nDim} {incr j} { + lappend where mn$j>-10000 mx$j<10000 + } + for {set j 0} {$j<$nDim} {incr j} { + set mn [rand 10000] + set mx [expr {$mn+[randincr 500]}] + lappend where mn$j>=$mn mx$j<=$mx + } + set where "WHERE [join $where { AND }]" + do_test rtree4-$nDim.2.$i.3 { + list $where [db eval "SELECT id FROM rx $where ORDER BY id"] + } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]] + + # Do an overlaps query with surplus contraints at the beginning. + # This should force a full-table scan on the rtree. + # + set where {} + for {set j 0} {$j<$nDim} {incr j} { + lappend where mn$j>=-10000 mx$j<=10000 + } + for {set j 0} {$j<$nDim} {incr j} { + set mn [rand 10000] + set mx [expr {$mn+[randincr 500]}] + lappend where mx$j>$mn mn$j<$mx + } + set where "WHERE [join $where { AND }]" + do_test rtree4-$nDim.2.$i.4 { + list $where [db eval "SELECT id FROM rx $where ORDER BY id"] + } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]] + + # Do a contained-in query with surplus contraints at the end + # + set where {} + for {set j 0} {$j<$nDim} {incr j} { + set mn [rand 10000] + set mx [expr {$mn+[randincr 500]}] + lappend where mn$j>=$mn mx$j<$mx + } + for {set j [expr {$nDim-1}]} {$j>=0} {incr j -1} { + lappend where mn$j>=-10000 mx$j<10000 + } + set where "WHERE [join $where { AND }]" + do_test rtree4-$nDim.2.$i.5 { + list $where [db eval "SELECT id FROM rx $where ORDER BY id"] + } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]] + + # Do an overlaps query with surplus contraints at the end + # + set where {} + for {set j [expr {$nDim-1}]} {$j>=0} {incr j -1} { + set mn [rand 10000] + set mx [expr {$mn+[randincr 500]}] + lappend where mx$j>$mn mn$j<=$mx + } + for {set j 0} {$j<$nDim} {incr j} { + lappend where mx$j>-10000 mn$j<=10000 + } + set where "WHERE [join $where { AND }]" + do_test rtree4-$nDim.2.$i.6 { + list $where [db eval "SELECT id FROM rx $where ORDER BY id"] + } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]] + + # Do a contained-in query with surplus contraints where the + # constraints appear in a random order. + # + set where {} + for {set j 0} {$j<$nDim} {incr j} { + set mn1 [rand 10000] + set mn2 [expr {$mn1+[randincr 100]}] + set mx1 [expr {$mn2+[randincr 400]}] + set mx2 [expr {$mx1+[randincr 100]}] + lappend where mn$j>=$mn1 mn$j>$mn2 mx$j<$mx1 mx$j<=$mx2 + } + set where "WHERE [join [scramble $where] { AND }]" + do_test rtree4-$nDim.2.$i.7 { + list $where [db eval "SELECT id FROM rx $where ORDER BY id"] + } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]] + + # Do an overlaps query with surplus contraints where the + # constraints appear in a random order. + # + set where {} + for {set j 0} {$j<$nDim} {incr j} { + set mn1 [rand 10000] + set mn2 [expr {$mn1+[randincr 100]}] + set mx1 [expr {$mn2+[randincr 400]}] + set mx2 [expr {$mx1+[randincr 100]}] + lappend where mx$j>=$mn1 mx$j>$mn2 mn$j<$mx1 mn$j<=$mx2 + } + set where "WHERE [join [scramble $where] { AND }]" + do_test rtree4-$nDim.2.$i.8 { + list $where [db eval "SELECT id FROM rx $where ORDER BY id"] + } [list $where [db eval "SELECT id FROM bx $where ORDER BY id"]] + } + +} + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree5.test b/components/external/SQLite-3.8.1/ext/rtree/rtree5.test new file mode 100644 index 0000000000000000000000000000000000000000..8ff90b0cb7071b89716d30611be4893af3b28410 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree5.test @@ -0,0 +1,80 @@ +# 2008 Jul 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing the r-tree extension when it is +# configured to store values as 32 bit integers. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl + +ifcapable !rtree { + finish_test + return +} + +do_test rtree5-1.0 { + execsql { CREATE VIRTUAL TABLE t1 USING rtree_i32(id, x1, x2, y1, y2) } +} {} +do_test rtree5-1.1 { + execsql { INSERT INTO t1 VALUES(1, 5, 10, 4, 11.2) } +} {} +do_test rtree5-1.2 { + execsql { SELECT * FROM t1 } +} {1 5 10 4 11} +do_test rtree5-1.3 { + execsql { SELECT typeof(x1) FROM t1 } +} {integer} + +do_test rtree5-1.4 { + execsql { SELECT x1==5 FROM t1 } +} {1} +do_test rtree5-1.5 { + execsql { SELECT x1==5.2 FROM t1 } +} {0} +do_test rtree5-1.6 { + execsql { SELECT x1==5.0 FROM t1 } +} {1} + +do_test rtree5-1.7 { + execsql { SELECT count(*) FROM t1 WHERE x1==5 } +} {1} +ifcapable !rtree_int_only { + do_test rtree5-1.8 { + execsql { SELECT count(*) FROM t1 WHERE x1==5.2 } + } {0} +} +do_test rtree5-1.9 { + execsql { SELECT count(*) FROM t1 WHERE x1==5.0 } +} {1} + +do_test rtree5-1.10 { + execsql { SELECT (1<<31)-5, (1<<31)-1, -1*(1<<31), -1*(1<<31)+5 } +} {2147483643 2147483647 -2147483648 -2147483643} +do_test rtree5-1.11 { + execsql { + INSERT INTO t1 VALUES(2, (1<<31)-5, (1<<31)-1, -1*(1<<31), -1*(1<<31)+5) + } +} {} +do_test rtree5-1.12 { + execsql { SELECT * FROM t1 WHERE id=2 } +} {2 2147483643 2147483647 -2147483648 -2147483643} +do_test rtree5-1.13 { + execsql { + SELECT * FROM t1 WHERE + x1=2147483643 AND x2=2147483647 AND + y1=-2147483648 AND y2=-2147483643 + } +} {2 2147483643 2147483647 -2147483648 -2147483643} + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree6.test b/components/external/SQLite-3.8.1/ext/rtree/rtree6.test new file mode 100644 index 0000000000000000000000000000000000000000..17985ee5256c41c6b9251412b384fb5ca54949e4 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree6.test @@ -0,0 +1,156 @@ +# 2008 Sep 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl + +ifcapable {!rtree || rtree_int_only} { + finish_test + return +} + +# Operator Byte Value +# ---------------------- +# = 0x41 ('A') +# <= 0x42 ('B') +# < 0x43 ('C') +# >= 0x44 ('D') +# > 0x45 ('E') +# ---------------------- + +proc rtree_strategy {sql} { + set ret [list] + db eval "explain $sql" a { + if {$a(opcode) eq "VFilter"} { + lappend ret $a(p4) + } + } + set ret +} + +proc query_plan {sql} { + set ret [list] + db eval "explain query plan $sql" a { + lappend ret $a(detail) + } + set ret +} + +do_test rtree6-1.1 { + execsql { + CREATE TABLE t2(k INTEGER PRIMARY KEY, v); + CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2); + } +} {} + +do_test rtree6-1.2 { + rtree_strategy {SELECT * FROM t1 WHERE x1>10} +} {Ea} + +do_test rtree6-1.3 { + rtree_strategy {SELECT * FROM t1 WHERE x1<10} +} {Ca} + +do_test rtree6-1.4 { + rtree_strategy {SELECT * FROM t1,t2 WHERE k=ii AND x1<10} +} {Ca} + +do_test rtree6-1.5 { + rtree_strategy {SELECT * FROM t1,t2 WHERE k=+ii AND x1<10} +} {Ca} + +do_eqp_test rtree6.2.1 { + SELECT * FROM t1,t2 WHERE k=+ii AND x1<10 +} { + 0 0 0 {SCAN TABLE t1 VIRTUAL TABLE INDEX 2:Ca} + 0 1 1 {SEARCH TABLE t2 USING INTEGER PRIMARY KEY (rowid=?)} +} + +do_eqp_test rtree6.2.2 { + SELECT * FROM t1,t2 WHERE k=ii AND x1<10 +} { + 0 0 0 {SCAN TABLE t1 VIRTUAL TABLE INDEX 2:Ca} + 0 1 1 {SEARCH TABLE t2 USING INTEGER PRIMARY KEY (rowid=?)} +} + +do_eqp_test rtree6.2.3 { + SELECT * FROM t1,t2 WHERE k=ii +} { + 0 0 0 {SCAN TABLE t1 VIRTUAL TABLE INDEX 2:} + 0 1 1 {SEARCH TABLE t2 USING INTEGER PRIMARY KEY (rowid=?)} +} + +do_eqp_test rtree6.2.4 { + SELECT * FROM t1,t2 WHERE v=10 and x1<10 and x2>10 +} { + 0 0 0 {SCAN TABLE t1 VIRTUAL TABLE INDEX 2:CaEb} + 0 1 1 {SCAN TABLE t2} +} + +do_eqp_test rtree6.2.5 { + SELECT * FROM t1,t2 WHERE k=ii AND x10.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5; +} {1 1.0 1.0 2.0 2.0} + +do_test rtree6.3.2 { + rtree_strategy { + SELECT * FROM t3 WHERE + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 + } +} {EaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEa} +do_test rtree6.3.3 { + rtree_strategy { + SELECT * FROM t3 WHERE + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 + } +} {EaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEaEa} + +do_execsql_test rtree6-3.4 { + SELECT * FROM t3 WHERE x1>0.5 AND x1>0.8 AND x1>1.1 +} {} +do_execsql_test rtree6-3.5 { + SELECT * FROM t3 WHERE + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND + x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>0.5 AND x1>1.1 +} {} + + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree7.test b/components/external/SQLite-3.8.1/ext/rtree/rtree7.test new file mode 100644 index 0000000000000000000000000000000000000000..4eee4c219a61ce1ffde288fbb2a3f188411f128b --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree7.test @@ -0,0 +1,70 @@ +# 2010 February 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test that nothing goes wrong if an rtree table is created, then the +# database page-size is modified. At one point (3.6.22), this was causing +# malfunctions. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl + +ifcapable !rtree||!vacuum { + finish_test + return +} + +# Like execsql except display output as integer where that can be +# done without loss of information. +# +proc execsql_intout {sql} { + set out {} + foreach term [execsql $sql] { + regsub {\.0$} $term {} term + lappend out $term + } + return $out +} + +do_test rtree7-1.1 { + execsql { + PRAGMA page_size = 1024; + CREATE VIRTUAL TABLE rt USING rtree(id, x1, x2, y1, y2); + INSERT INTO rt VALUES(1, 1, 2, 3, 4); + } +} {} +do_test rtree7-1.2 { + execsql_intout { SELECT * FROM rt } +} {1 1 2 3 4} +do_test rtree7-1.3 { + execsql_intout { + PRAGMA page_size = 2048; + VACUUM; + SELECT * FROM rt; + } +} {1 1 2 3 4} +do_test rtree7-1.4 { + for {set i 2} {$i <= 51} {incr i} { + execsql { INSERT INTO rt VALUES($i, 1, 2, 3, 4) } + } + execsql_intout { SELECT sum(x1), sum(x2), sum(y1), sum(y2) FROM rt } +} {51 102 153 204} +do_test rtree7-1.5 { + execsql_intout { + PRAGMA page_size = 512; + VACUUM; + SELECT sum(x1), sum(x2), sum(y1), sum(y2) FROM rt + } +} {51 102 153 204} + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree8.test b/components/external/SQLite-3.8.1/ext/rtree/rtree8.test new file mode 100644 index 0000000000000000000000000000000000000000..578a1468b8bdac48e1c60e58c872a7388c41ed28 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree8.test @@ -0,0 +1,170 @@ +# 2010 February 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl +ifcapable !rtree { finish_test ; return } + +#------------------------------------------------------------------------- +# The following block of tests - rtree8-1.* - feature reading and writing +# an r-tree table while there exist open cursors on it. +# +proc populate_t1 {n} { + execsql { DELETE FROM t1 } + for {set i 1} {$i <= $n} {incr i} { + execsql { INSERT INTO t1 VALUES($i, $i, $i+2) } + } +} + +# A DELETE while a cursor is reading the table. +# +do_test rtree8-1.1.1 { + execsql { PRAGMA page_size = 512 } + execsql { CREATE VIRTUAL TABLE t1 USING rtree_i32(id, x1, x2) } + populate_t1 5 +} {} +do_test rtree8-1.1.2 { + set res [list] + db eval { SELECT * FROM t1 } { + lappend res $x1 $x2 + if {$id==3} { db eval { DELETE FROM t1 WHERE id>3 } } + } + set res +} {1 3 2 4 3 5} +do_test rtree8-1.1.3 { + execsql { SELECT * FROM t1 } +} {1 1 3 2 2 4 3 3 5} + +# Many SELECTs on the same small table. +# +proc nested_select {n} { + set ::max $n + db eval { SELECT * FROM t1 } { + if {$id == $n} { nested_select [expr $n+1] } + } + return $::max +} +do_test rtree8-1.2.1 { populate_t1 50 } {} +do_test rtree8-1.2.2 { nested_select 1 } {51} + +# This test runs many SELECT queries simultaneously against a large +# table, causing a collision in the hash-table used to store r-tree +# nodes internally. +# +populate_t1 1500 +do_execsql_test rtree8-1.3.1 { SELECT max(nodeno) FROM t1_node } {164} +do_test rtree8-1.3.2 { + set rowids [execsql {SELECT min(rowid) FROM t1_rowid GROUP BY nodeno}] + set stmt_list [list] + foreach row $rowids { + set stmt [sqlite3_prepare db "SELECT * FROM t1 WHERE id = $row" -1 tail] + sqlite3_step $stmt + lappend res_list [sqlite3_column_int $stmt 0] + lappend stmt_list $stmt + } +} {} +do_test rtree8-1.3.3 { set res_list } $rowids +do_execsql_test rtree8-1.3.4 { SELECT count(*) FROM t1 } {1500} +do_test rtree8-1.3.5 { + foreach stmt $stmt_list { sqlite3_finalize $stmt } +} {} + + +#------------------------------------------------------------------------- +# The following block of tests - rtree8-2.* - test a couple of database +# corruption cases. In this case things are not corrupted at the b-tree +# level, but the contents of the various tables used internally by an +# r-tree table are inconsistent. +# +populate_t1 50 +do_execsql_test rtree8-2.1.1 { SELECT max(nodeno) FROM t1_node } {5} +do_execsql_test rtree8-2.1.2 { DELETE FROM t1_node } {} +for {set i 1} {$i <= 50} {incr i} { + do_catchsql_test rtree8-2.1.3.$i { + SELECT * FROM t1 WHERE id = $i + } {1 {database disk image is malformed}} +} +do_catchsql_test rtree8-2.1.4 { + SELECT * FROM t1 +} {1 {database disk image is malformed}} +do_catchsql_test rtree8-2.1.5 { + DELETE FROM t1 +} {1 {database disk image is malformed}} + +do_execsql_test rtree8-2.1.6 { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING rtree_i32(id, x1, x2); +} {} + + +populate_t1 50 +do_execsql_test rtree8-2.2.1 { + DELETE FROM t1_parent +} {} +do_catchsql_test rtree8-2.2.2 { + DELETE FROM t1 WHERE id=25 +} {1 {database disk image is malformed}} +do_execsql_test rtree8-2.2.3 { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING rtree_i32(id, x1, x2); +} {} + + +#------------------------------------------------------------------------- +# Test that trying to use the MATCH operator with the r-tree module does +# not confuse it. +# +populate_t1 10 +do_catchsql_test rtree8-3.1 { + SELECT * FROM t1 WHERE x1 MATCH '1234' +} {1 {SQL logic error or missing database}} + +#------------------------------------------------------------------------- +# Test a couple of invalid arguments to rtreedepth(). +# +do_catchsql_test rtree8-4.1 { + SELECT rtreedepth('hello world') +} {1 {Invalid argument to rtreedepth()}} +do_catchsql_test rtree8-4.2 { + SELECT rtreedepth(X'00') +} {1 {Invalid argument to rtreedepth()}} + + +#------------------------------------------------------------------------- +# Delete half of a lopsided tree. +# +do_execsql_test rtree8-5.1 { + CREATE VIRTUAL TABLE t2 USING rtree_i32(id, x1, x2) +} {} +do_test rtree8-5.2 { + execsql BEGIN + for {set i 0} {$i < 100} {incr i} { + execsql { INSERT INTO t2 VALUES($i, 100, 101) } + } + for {set i 100} {$i < 200} {incr i} { + execsql { INSERT INTO t2 VALUES($i, 1000, 1001) } + } + execsql COMMIT +} {} +do_test rtree8-5.3 { + execsql BEGIN + for {set i 0} {$i < 200} {incr i} { + execsql { DELETE FROM t2 WHERE id = $i } + } + execsql COMMIT +} {} + + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree9.test b/components/external/SQLite-3.8.1/ext/rtree/rtree9.test new file mode 100644 index 0000000000000000000000000000000000000000..6479516bed6d04d3b62ca219ec4cde23753b3164 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree9.test @@ -0,0 +1,126 @@ +# 2010 August 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file contains tests for the r-tree module. Specifically, it tests +# that custom r-tree queries (geometry callbacks) work. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl +ifcapable !rtree { finish_test ; return } +ifcapable rtree_int_only { finish_test; return } + +register_cube_geom db + +do_execsql_test rtree9-1.1 { + CREATE VIRTUAL TABLE rt USING rtree(id, x1, x2, y1, y2, z1, z2); + INSERT INTO rt VALUES(1, 1, 2, 1, 2, 1, 2); +} {} +do_execsql_test rtree9-1.2 { + SELECT * FROM rt WHERE id MATCH cube(0, 0, 0, 2, 2, 2); +} {1 1.0 2.0 1.0 2.0 1.0 2.0} +do_execsql_test rtree9-1.3 { + SELECT * FROM rt WHERE id MATCH cube(3, 3, 3, 2, 2, 2); +} {} +do_execsql_test rtree9-1.4 { + DELETE FROM rt; +} {} + + +for {set i 0} {$i < 1000} {incr i} { + set x [expr $i%10] + set y [expr ($i/10)%10] + set z [expr ($i/100)%10] + execsql { INSERT INTO rt VALUES($i, $x, $x+1, $y, $y+1, $z, $z+1) } +} +do_execsql_test rtree9-2.1 { + SELECT id FROM rt WHERE id MATCH cube(2.5, 2.5, 2.5, 1, 1, 1) ORDER BY id; +} {222 223 232 233 322 323 332 333} +do_execsql_test rtree9-2.2 { + SELECT id FROM rt WHERE id MATCH cube(5.5, 5.5, 5.5, 1, 1, 1) ORDER BY id; +} {555 556 565 566 655 656 665 666} + + +do_execsql_test rtree9-3.1 { + CREATE VIRTUAL TABLE rt32 USING rtree_i32(id, x1, x2, y1, y2, z1, z2); +} {} +for {set i 0} {$i < 1000} {incr i} { + set x [expr $i%10] + set y [expr ($i/10)%10] + set z [expr ($i/100)%10] + execsql { INSERT INTO rt32 VALUES($i, $x, $x+1, $y, $y+1, $z, $z+1) } +} +do_execsql_test rtree9-3.2 { + SELECT id FROM rt32 WHERE id MATCH cube(3, 3, 3, 1, 1, 1) ORDER BY id; +} {222 223 224 232 233 234 242 243 244 322 323 324 332 333 334 342 343 344 422 423 424 432 433 434 442 443 444} +do_execsql_test rtree9-3.3 { + SELECT id FROM rt32 WHERE id MATCH cube(5.5, 5.5, 5.5, 1, 1, 1) ORDER BY id; +} {555 556 565 566 655 656 665 666} + + +do_catchsql_test rtree9-4.1 { + SELECT id FROM rt32 WHERE id MATCH cube(5.5, 5.5, 1, 1, 1) ORDER BY id; +} {1 {SQL logic error or missing database}} +for {set x 2} {$x<200} {incr x 2} { + do_catchsql_test rtree9-4.2.[expr $x/2] { + SELECT id FROM rt WHERE id MATCH randomblob($x) + } {1 {SQL logic error or missing database}} +} +do_catchsql_test rtree9-4.3 { + SELECT id FROM rt WHERE id MATCH CAST( + (cube(5.5, 5.5, 5.5, 1, 1, 1) || X'1234567812345678') AS blob + ) +} {1 {SQL logic error or missing database}} + + +#------------------------------------------------------------------------- +# Test the example 2d "circle" geometry callback. +# +register_circle_geom db + +breakpoint +do_execsql_test rtree9-5.1 { + CREATE VIRTUAL TABLE rt2 USING rtree(id, xmin, xmax, ymin, ymax); + + INSERT INTO rt2 VALUES(1, 1, 2, 1, 2); + INSERT INTO rt2 VALUES(2, 1, 2, -2, -1); + INSERT INTO rt2 VALUES(3, -2, -1, -2, -1); + INSERT INTO rt2 VALUES(4, -2, -1, 1, 2); + + INSERT INTO rt2 VALUES(5, 2, 3, 2, 3); + INSERT INTO rt2 VALUES(6, 2, 3, -3, -2); + INSERT INTO rt2 VALUES(7, -3, -2, -3, -2); + INSERT INTO rt2 VALUES(8, -3, -2, 2, 3); + + INSERT INTO rt2 VALUES(9, 1.8, 3, 1.8, 3); + INSERT INTO rt2 VALUES(10, 1.8, 3, -3, -1.8); + INSERT INTO rt2 VALUES(11, -3, -1.8, -3, -1.8); + INSERT INTO rt2 VALUES(12, -3, -1.8, 1.8, 3); + + INSERT INTO rt2 VALUES(13, -15, 15, 1.8, 2.2); + INSERT INTO rt2 VALUES(14, -15, 15, -2.2, -1.8); + INSERT INTO rt2 VALUES(15, 1.8, 2.2, -15, 15); + INSERT INTO rt2 VALUES(16, -2.2, -1.8, -15, 15); + + INSERT INTO rt2 VALUES(17, -100, 100, -100, 100); +} {} + +do_execsql_test rtree9-5.2 { + SELECT id FROM rt2 WHERE id MATCH circle(0.0, 0.0, 2.0); +} {1 2 3 4 13 14 15 16 17} + +do_execsql_test rtree9-5.3 { + UPDATE rt2 SET xmin=xmin+5, ymin=ymin+5, xmax=xmax+5, ymax=ymax+5; + SELECT id FROM rt2 WHERE id MATCH circle(5.0, 5.0, 2.0); +} {1 2 3 4 13 14 15 16 17} + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtreeA.test b/components/external/SQLite-3.8.1/ext/rtree/rtreeA.test new file mode 100644 index 0000000000000000000000000000000000000000..e377b013c133358925023b62dbb23934324ffda3 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtreeA.test @@ -0,0 +1,220 @@ +# 2010 September 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file contains tests for the r-tree module. Specifically, it tests +# that corrupt or inconsistent databases do not cause crashes in the r-tree +# module. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl +ifcapable !rtree { finish_test ; return } + +proc create_t1 {} { + db close + forcedelete test.db + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + CREATE VIRTUAL TABLE t1 USING rtree(id, x1, x2, y1, y2); + } +} +proc populate_t1 {} { + execsql BEGIN + for {set i 0} {$i < 500} {incr i} { + set x2 [expr $i+5] + set y2 [expr $i+5] + execsql { INSERT INTO t1 VALUES($i, $i, $x2, $i, $y2) } + } + execsql COMMIT +} + +proc truncate_node {nodeno nTrunc} { + set blob [db one {SELECT data FROM t1_node WHERE nodeno=$nodeno}] + if {$nTrunc<0} {set nTrunc "end-$nTrunc"} + set blob [string range $blob 0 $nTrunc] + db eval { UPDATE t1_node SET data = $blob WHERE nodeno=$nodeno } +} + +proc set_tree_depth {tbl {newvalue ""}} { + set blob [db one "SELECT data FROM ${tbl}_node WHERE nodeno=1"] + + if {$newvalue == ""} { + binary scan $blob Su oldvalue + return $oldvalue + } + + set blob [binary format Sua* $newvalue [string range $blob 2 end]] + db eval "UPDATE ${tbl}_node SET data = \$blob WHERE nodeno=1" + return [set_tree_depth $tbl] +} + +proc set_entry_count {tbl nodeno {newvalue ""}} { + set blob [db one "SELECT data FROM ${tbl}_node WHERE nodeno=$nodeno"] + + if {$newvalue == ""} { + binary scan [string range $blob 2 end] Su oldvalue + return $oldvalue + } + + set blob [binary format a*Sua* \ + [string range $blob 0 1] $newvalue [string range $blob 4 end] + ] + db eval "UPDATE ${tbl}_node SET data = \$blob WHERE nodeno=$nodeno" + return [set_entry_count $tbl $nodeno] +} + + +proc do_corruption_tests {prefix args} { + set testarray [lindex $args end] + set errormsg {database disk image is malformed} + + foreach {z value} [lrange $args 0 end-1] { + set n [string length $z] + if {$n>=2 && [string equal -length $n $z "-error"]} { + set errormsg $value + } + } + + foreach {tn sql} $testarray { + do_catchsql_test $prefix.$tn $sql [list 1 $errormsg] + } +} + +#------------------------------------------------------------------------- +# Test the libraries response if the %_node table is completely empty +# (i.e. the root node is missing), or has been removed from the database +# entirely. +# +create_t1 +populate_t1 +do_execsql_test rtreeA-1.0 { + DELETE FROM t1_node; +} {} + +do_corruption_tests rtreeA-1.1 { + 1 "SELECT * FROM t1" + 2 "SELECT * FROM t1 WHERE rowid=5" + 3 "INSERT INTO t1 VALUES(1000, 1, 2, 3, 4)" + 4 "SELECT * FROM t1 WHERE x1<10 AND x2>12" +} + +do_execsql_test rtreeA-1.2.0 { DROP TABLE t1_node } {} +do_corruption_tests rtreeA-1.2 -error "SQL logic error or missing database" { + 1 "SELECT * FROM t1" + 2 "SELECT * FROM t1 WHERE rowid=5" + 3 "INSERT INTO t1 VALUES(1000, 1, 2, 3, 4)" + 4 "SELECT * FROM t1 WHERE x1<10 AND x2>12" +} + +#------------------------------------------------------------------------- +# Test the libraries response if some of the entries in the %_node table +# are the wrong size. +# +create_t1 +populate_t1 +do_test rtreeA-2.1.0 { + set nodes [db eval {select nodeno FROM t1_node}] + foreach {a b c} $nodes { truncate_node $c 200 } +} {} +do_corruption_tests rtreeA-2.1 { + 1 "SELECT * FROM t1" + 2 "SELECT * FROM t1 WHERE rowid=5" + 3 "INSERT INTO t1 VALUES(1000, 1, 2, 3, 4)" + 4 "SELECT * FROM t1 WHERE x1<10 AND x2>12" +} + +create_t1 +populate_t1 +do_test rtreeA-2.2.0 { truncate_node 1 200 } {} +do_corruption_tests rtreeA-2.2 { + 1 "SELECT * FROM t1" + 2 "SELECT * FROM t1 WHERE rowid=5" + 3 "INSERT INTO t1 VALUES(1000, 1, 2, 3, 4)" + 4 "SELECT * FROM t1 WHERE x1<10 AND x2>12" +} + +#------------------------------------------------------------------------- +# Set the "depth" of the tree stored on the root node incorrectly. Test +# that this does not cause any problems. +# +create_t1 +populate_t1 +do_test rtreeA-3.1.0.1 { set_tree_depth t1 } {1} +do_test rtreeA-3.1.0.2 { set_tree_depth t1 3 } {3} +do_corruption_tests rtreeA-3.1 { + 1 "SELECT * FROM t1" + 2 "SELECT * FROM t1 WHERE rowid=5" + 3 "INSERT INTO t1 VALUES(1000, 1, 2, 3, 4)" +} + +do_test rtreeA-3.2.0 { set_tree_depth t1 1000 } {1000} +do_corruption_tests rtreeA-3.2 { + 1 "SELECT * FROM t1" + 2 "SELECT * FROM t1 WHERE rowid=5" + 3 "INSERT INTO t1 VALUES(1000, 1, 2, 3, 4)" +} + +create_t1 +populate_t1 +do_test rtreeA-3.3.0 { + execsql { DELETE FROM t1 WHERE rowid = 0 } + set_tree_depth t1 65535 +} {65535} +do_corruption_tests rtreeA-3.3 { + 1 "SELECT * FROM t1" + 2 "SELECT * FROM t1 WHERE rowid=5" + 3 "INSERT INTO t1 VALUES(1000, 1, 2, 3, 4)" +} + +#------------------------------------------------------------------------- +# Set the "number of entries" field on some nodes incorrectly. +# +create_t1 +populate_t1 +do_test rtreeA-4.1.0 { + set_entry_count t1 1 4000 +} {4000} +do_corruption_tests rtreeA-4.1 { + 1 "SELECT * FROM t1" + 2 "SELECT * FROM t1 WHERE rowid=5" + 3 "INSERT INTO t1 VALUES(1000, 1, 2, 3, 4)" + 4 "SELECT * FROM t1 WHERE x1<10 AND x2>12" +} + +#------------------------------------------------------------------------- +# Remove entries from the %_parent table and check that this does not +# cause a crash. +# +create_t1 +populate_t1 +do_execsql_test rtreeA-5.1.0 { DELETE FROM t1_parent } {} +do_corruption_tests rtreeA-5.1 { + 1 "DELETE FROM t1 WHERE rowid = 5" + 2 "DELETE FROM t1" +} + +#------------------------------------------------------------------------- +# Add some bad entries to the %_parent table. +# +create_t1 +populate_t1 +do_execsql_test rtreeA-6.1.0 { + UPDATE t1_parent set parentnode = parentnode+1 +} {} +do_corruption_tests rtreeA-6.1 { + 1 "DELETE FROM t1 WHERE rowid = 5" + 2 "UPDATE t1 SET x1=x1+1, x2=x2+1" +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtreeB.test b/components/external/SQLite-3.8.1/ext/rtree/rtreeB.test new file mode 100644 index 0000000000000000000000000000000000000000..7cb445cc4fa97a0368ecde17badca67416eb1c49 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtreeB.test @@ -0,0 +1,47 @@ +# 2011 March 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# Make sure the rtreenode() testing function can handle entries with +# 64-bit rowids. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source $testdir/tester.tcl +ifcapable !rtree { finish_test ; return } + +ifcapable rtree_int_only { + do_test rtreeB-1.1-intonly { + db eval { + CREATE VIRTUAL TABLE t1 USING rtree(ii, x0, y0, x1, y1); + INSERT INTO t1 VALUES(1073741824, 0.0, 0.0, 100.0, 100.0); + INSERT INTO t1 VALUES(2147483646, 0.0, 0.0, 200.0, 200.0); + INSERT INTO t1 VALUES(4294967296, 0.0, 0.0, 300.0, 300.0); + INSERT INTO t1 VALUES(8589934592, 20.0, 20.0, 150.0, 150.0); + INSERT INTO t1 VALUES(9223372036854775807, 150, 150, 400, 400); + SELECT rtreenode(2, data) FROM t1_node; + } + } {{{1073741824 0 0 100 100} {2147483646 0 0 200 200} {4294967296 0 0 300 300} {8589934592 20 20 150 150} {9223372036854775807 150 150 400 400}}} +} else { + do_test rtreeB-1.1 { + db eval { + CREATE VIRTUAL TABLE t1 USING rtree(ii, x0, y0, x1, y1); + INSERT INTO t1 VALUES(1073741824, 0.0, 0.0, 100.0, 100.0); + INSERT INTO t1 VALUES(2147483646, 0.0, 0.0, 200.0, 200.0); + INSERT INTO t1 VALUES(4294967296, 0.0, 0.0, 300.0, 300.0); + INSERT INTO t1 VALUES(8589934592, 20.0, 20.0, 150.0, 150.0); + INSERT INTO t1 VALUES(9223372036854775807, 150, 150, 400, 400); + SELECT rtreenode(2, data) FROM t1_node; + } + } {{{1073741824 0.000000 0.000000 100.000000 100.000000} {2147483646 0.000000 0.000000 200.000000 200.000000} {4294967296 0.000000 0.000000 300.000000 300.000000} {8589934592 20.000000 20.000000 150.000000 150.000000} {9223372036854775807 150.000000 150.000000 400.000000 400.000000}}} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree_perf.tcl b/components/external/SQLite-3.8.1/ext/rtree/rtree_perf.tcl new file mode 100644 index 0000000000000000000000000000000000000000..e42e68550611cce669945a51d1befe9efde7b8a2 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree_perf.tcl @@ -0,0 +1,74 @@ + +set testdir [file join [file dirname $argv0] .. .. test] +source $testdir/tester.tcl + +ifcapable !rtree { + finish_test + return +} + +set NROW 10000 +set NQUERY 500 + +puts "Generating $NROW rows of data..." +set data [list] +for {set ii 0} {$ii < $NROW} {incr ii} { + set x1 [expr {rand()*1000}] + set x2 [expr {$x1+rand()*50}] + set y1 [expr {rand()*1000}] + set y2 [expr {$y1+rand()*50}] + lappend data $x1 $x2 $y1 $y2 +} +puts "Finished generating data" + + +set sql1 {CREATE TABLE btree(ii INTEGER PRIMARY KEY, x1, x2, y1, y2)} +set sql2 {CREATE VIRTUAL TABLE rtree USING rtree(ii, x1, x2, y1, y2)} +puts "Creating tables:" +puts " $sql1" +puts " $sql2" +db eval $sql1 +db eval $sql2 + +db eval "pragma cache_size=100" + +puts -nonewline "Inserting into btree... " +flush stdout +set btree_time [time {db transaction { + set ii 1 + foreach {x1 x2 y1 y2} $data { + db eval {INSERT INTO btree VALUES($ii, $x1, $x2, $y1, $y2)} + incr ii + } +}}] +puts "$btree_time" + +puts -nonewline "Inserting into rtree... " +flush stdout +set rtree_time [time {db transaction { + set ii 1 + foreach {x1 x2 y1 y2} $data { + incr ii + db eval {INSERT INTO rtree VALUES($ii, $x1, $x2, $y1, $y2)} + } +}}] +puts "$rtree_time" + + +puts -nonewline "Selecting from btree... " +flush stdout +set btree_select_time [time { + foreach {x1 x2 y1 y2} [lrange $data 0 [expr $NQUERY*4-1]] { + db eval {SELECT * FROM btree WHERE x1<$x1 AND x2>$x2 AND y1<$y1 AND y2>$y2} + } +}] +puts "$btree_select_time" + +puts -nonewline "Selecting from rtree... " +flush stdout +set rtree_select_time [time { + foreach {x1 x2 y1 y2} [lrange $data 0 [expr $NQUERY*4-1]] { + db eval {SELECT * FROM rtree WHERE x1<$x1 AND x2>$x2 AND y1<$y1 AND y2>$y2} + } +}] +puts "$rtree_select_time" diff --git a/components/external/SQLite-3.8.1/ext/rtree/rtree_util.tcl b/components/external/SQLite-3.8.1/ext/rtree/rtree_util.tcl new file mode 100644 index 0000000000000000000000000000000000000000..50a1b58065111013a8f2d066f0f9178936f47089 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/rtree_util.tcl @@ -0,0 +1,192 @@ +# 2008 Feb 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains Tcl code that may be useful for testing or +# analyzing r-tree structures created with this module. It is +# used by both test procedures and the r-tree viewer application. +# + + +#-------------------------------------------------------------------------- +# PUBLIC API: +# +# rtree_depth +# rtree_ndim +# rtree_node +# rtree_mincells +# rtree_check +# rtree_dump +# rtree_treedump +# + +proc rtree_depth {db zTab} { + $db one "SELECT rtreedepth(data) FROM ${zTab}_node WHERE nodeno=1" +} + +proc rtree_nodedepth {db zTab iNode} { + set iDepth [rtree_depth $db $zTab] + + set ii $iNode + while {$ii != 1} { + set sql "SELECT parentnode FROM ${zTab}_parent WHERE nodeno = $ii" + set ii [db one $sql] + incr iDepth -1 + } + + return $iDepth +} + +# Return the number of dimensions of the rtree. +# +proc rtree_ndim {db zTab} { + set nDim [expr {(([llength [$db eval "pragma table_info($zTab)"]]/6)-1)/2}] +} + +# Return the contents of rtree node $iNode. +# +proc rtree_node {db zTab iNode {iPrec 6}} { + set nDim [rtree_ndim $db $zTab] + set sql " + SELECT rtreenode($nDim, data) FROM ${zTab}_node WHERE nodeno = $iNode + " + set node [db one $sql] + + set nCell [llength $node] + set nCoord [expr $nDim*2] + for {set ii 0} {$ii < $nCell} {incr ii} { + for {set jj 1} {$jj <= $nCoord} {incr jj} { + set newval [format "%.${iPrec}f" [lindex $node $ii $jj]] + lset node $ii $jj $newval + } + } + set node +} + +proc rtree_mincells {db zTab} { + set n [$db one "select length(data) FROM ${zTab}_node LIMIT 1"] + set nMax [expr {int(($n-4)/(8+[rtree_ndim $db $zTab]*2*4))}] + return [expr {int($nMax/3)}] +} + +# An integrity check for the rtree $zTab accessible via database +# connection $db. +# +proc rtree_check {db zTab} { + array unset ::checked + + # Check each r-tree node. + set rc [catch { + rtree_node_check $db $zTab 1 [rtree_depth $db $zTab] + } msg] + if {$rc && $msg ne ""} { error $msg } + + # Check that the _rowid and _parent tables have the right + # number of entries. + set nNode [$db one "SELECT count(*) FROM ${zTab}_node"] + set nRow [$db one "SELECT count(*) FROM ${zTab}"] + set nRowid [$db one "SELECT count(*) FROM ${zTab}_rowid"] + set nParent [$db one "SELECT count(*) FROM ${zTab}_parent"] + + if {$nNode != ($nParent+1)} { + error "Wrong number of entries in ${zTab}_parent" + } + if {$nRow != $nRowid} { + error "Wrong number of entries in ${zTab}_rowid" + } + + return $rc +} + +proc rtree_node_check {db zTab iNode iDepth} { + if {[info exists ::checked($iNode)]} { error "Second ref to $iNode" } + set ::checked($iNode) 1 + + set node [rtree_node $db $zTab $iNode] + if {$iNode!=1 && [llength $node]==0} { error "No such node: $iNode" } + + if {$iNode != 1 && [llength $node]<[rtree_mincells $db $zTab]} { + puts "Node $iNode: Has only [llength $node] cells" + error "" + } + if {$iNode == 1 && [llength $node]==1 && [rtree_depth $db $zTab]>0} { + set depth [rtree_depth $db $zTab] + puts "Node $iNode: Has only 1 child (tree depth is $depth)" + error "" + } + + set nDim [expr {([llength [lindex $node 0]]-1)/2}] + + if {$iDepth > 0} { + set d [expr $iDepth-1] + foreach cell $node { + set shouldbe [rtree_node_check $db $zTab [lindex $cell 0] $d] + if {$cell ne $shouldbe} { + puts "Node $iNode: Cell is: {$cell}, should be {$shouldbe}" + error "" + } + } + } + + set mapping_table "${zTab}_parent" + set mapping_sql "SELECT parentnode FROM $mapping_table WHERE rowid = \$rowid" + if {$iDepth==0} { + set mapping_table "${zTab}_rowid" + set mapping_sql "SELECT nodeno FROM $mapping_table WHERE rowid = \$rowid" + } + foreach cell $node { + set rowid [lindex $cell 0] + set mapping [db one $mapping_sql] + if {$mapping != $iNode} { + puts "Node $iNode: $mapping_table entry for cell $rowid is $mapping" + error "" + } + } + + set ret [list $iNode] + for {set ii 1} {$ii <= $nDim*2} {incr ii} { + set f [lindex $node 0 $ii] + foreach cell $node { + set f2 [lindex $cell $ii] + if {($ii%2)==1 && $f2<$f} {set f $f2} + if {($ii%2)==0 && $f2>$f} {set f $f2} + } + lappend ret $f + } + return $ret +} + +proc rtree_dump {db zTab} { + set zRet "" + set nDim [expr {(([llength [$db eval "pragma table_info($zTab)"]]/6)-1)/2}] + set sql "SELECT nodeno, rtreenode($nDim, data) AS node FROM ${zTab}_node" + $db eval $sql { + append zRet [format "% -10s %s\n" $nodeno $node] + } + set zRet +} + +proc rtree_nodetreedump {db zTab zIndent iDepth iNode} { + set ret "" + set node [rtree_node $db $zTab $iNode 1] + append ret [format "%-3d %s%s\n" $iNode $zIndent $node] + if {$iDepth>0} { + foreach cell $node { + set i [lindex $cell 0] + append ret [rtree_nodetreedump $db $zTab "$zIndent " [expr $iDepth-1] $i] + } + } + set ret +} + +proc rtree_treedump {db zTab} { + set d [rtree_depth $db $zTab] + rtree_nodetreedump $db $zTab "" $d 1 +} diff --git a/components/external/SQLite-3.8.1/ext/rtree/sqlite3rtree.h b/components/external/SQLite-3.8.1/ext/rtree/sqlite3rtree.h new file mode 100644 index 0000000000000000000000000000000000000000..c849091f29a895fb0a462dd4521f93f6b8417b81 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/sqlite3rtree.h @@ -0,0 +1,60 @@ +/* +** 2010 August 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ + +#ifndef _SQLITE3RTREE_H_ +#define _SQLITE3RTREE_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; + +/* +** Register a geometry callback named zGeom that can be used as part of an +** R-Tree geometry query as follows: +** +** SELECT ... FROM WHERE MATCH $zGeom(... params ...) +*/ +int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, +#ifdef SQLITE_RTREE_INT_ONLY + int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes), +#else + int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes), +#endif + void *pContext +); + + +/* +** A pointer to a structure of the following type is passed as the first +** argument to callbacks registered using rtree_geometry_callback(). +*/ +struct sqlite3_rtree_geometry { + void *pContext; /* Copy of pContext passed to s_r_g_c() */ + int nParam; /* Size of array aParam[] */ + double *aParam; /* Parameters passed to SQL geom function */ + void *pUser; /* Callback implementation user data */ + void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ +}; + + +#ifdef __cplusplus +} /* end of the 'extern "C"' block */ +#endif + +#endif /* ifndef _SQLITE3RTREE_H_ */ diff --git a/components/external/SQLite-3.8.1/ext/rtree/tkt3363.test b/components/external/SQLite-3.8.1/ext/rtree/tkt3363.test new file mode 100644 index 0000000000000000000000000000000000000000..db05ed527a125cbda255261cc79f1be8acb1c779 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/tkt3363.test @@ -0,0 +1,50 @@ +# 2008 Sep 08 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing that ticket #3363 is fixed. +# + +if {![info exists testdir]} { + set testdir [file join [file dirname [info script]] .. .. test] +} +source [file join [file dirname [info script]] rtree_util.tcl] +source $testdir/tester.tcl + +ifcapable !rtree { + finish_test + return +} + +do_test tkt3363.1.1 { + execsql { CREATE VIRTUAL TABLE t1 USING rtree(ii, x1, x2, y1, y2) } +} {} + +do_test tkt3363.1.2 { + for {set ii 1} {$ii < 50} {incr ii} { + set x 1000000 + set y [expr 4000000 + $ii*10] + execsql { INSERT INTO t1 VALUES($ii, $x, $x, $y, $y) } + } +} {} + +do_test tkt3363.1.3 { + execsql { + SELECT count(*) FROM t1 WHERE +y2>4000425.0; + } +} {7} + +do_test tkt3363.1.4 { + execsql { + SELECT count(*) FROM t1 WHERE y2>4000425.0; + } +} {7} + +finish_test diff --git a/components/external/SQLite-3.8.1/ext/rtree/viewrtree.tcl b/components/external/SQLite-3.8.1/ext/rtree/viewrtree.tcl new file mode 100644 index 0000000000000000000000000000000000000000..794677f5a371c772fdbc00c0134c4e931a6ae488 --- /dev/null +++ b/components/external/SQLite-3.8.1/ext/rtree/viewrtree.tcl @@ -0,0 +1,188 @@ + +load ./libsqlite3.dylib +#package require sqlite3 +source [file join [file dirname $argv0] rtree_util.tcl] + +wm title . "SQLite r-tree viewer" + +if {[llength $argv]!=1} { + puts stderr "Usage: $argv0 " + puts stderr "" + exit +} +sqlite3 db [lindex $argv 0] + +canvas .c -background white -width 400 -height 300 -highlightthickness 0 + +button .b -text "Parent Node" -command { + set sql "SELECT parentnode FROM $::O(zTab)_parent WHERE nodeno = $::O(iNode)" + set ::O(iNode) [db one $sql] + if {$::O(iNode) eq ""} {set ::O(iNode) 1} + view_node +} + +set O(iNode) 1 +set O(zTab) "" +set O(listbox_captions) [list] +set O(listbox_itemmap) [list] +set O(listbox_highlight) -1 + +listbox .l -listvariable ::O(listbox_captions) -yscrollcommand {.ls set} +scrollbar .ls -command {.l yview} +label .status -font courier -anchor w +label .title -anchor w -text "Node 1:" -background white -borderwidth 0 + + +set rtree_tables [list] +db eval { + SELECT name + FROM sqlite_master + WHERE type='table' AND sql LIKE '%virtual%table%using%rtree%' +} { + set nCol [expr [llength [db eval "pragma table_info($name)"]]/6] + if {$nCol != 5} { + puts stderr "Not viewing $name - is not 2-dimensional" + } else { + lappend rtree_tables [list Table $name] + } +} +if {$rtree_tables eq ""} { + puts stderr "Cannot find an r-tree table in database [lindex $argv 0]" + puts stderr "" + exit +} +eval tk_optionMenu .select option_var $rtree_tables +trace add variable option_var write set_option_var +proc set_option_var {args} { + set ::O(zTab) [lindex $::option_var 1] + set ::O(iNode) 1 + view_node +} +set ::O(zTab) [lindex $::rtree_tables 0 1] + +bind .l <1> {listbox_click [.l nearest %y]} +bind .l {listbox_mouseover [.l nearest %y]} +bind .l {listbox_mouseover -1} + +proc listbox_click {sel} { + if {$sel ne ""} { + set ::O(iNode) [lindex $::O(listbox_captions) $sel 1] + view_node + } +} +proc listbox_mouseover {i} { + set oldid [lindex $::O(listbox_itemmap) $::O(listbox_highlight)] + .c itemconfigure $oldid -fill "" + + .l selection clear 0 end + .status configure -text "" + if {$i>=0} { + set id [lindex $::O(listbox_itemmap) $i] + .c itemconfigure $id -fill grey + .c lower $id + set ::O(listbox_highlight) $i + .l selection set $i + .status configure -text [cell_report db $::O(zTab) $::O(iNode) $i] + } +} + +grid configure .select -row 0 -column 0 -columnspan 2 -sticky nsew +grid configure .b -row 1 -column 0 -columnspan 2 -sticky nsew +grid configure .l -row 2 -column 0 -sticky nsew +grid configure .status -row 3 -column 0 -columnspan 3 -sticky nsew + +grid configure .title -row 0 -column 2 -sticky nsew +grid configure .c -row 1 -column 2 -rowspan 2 -sticky nsew +grid configure .ls -row 2 -column 1 -sticky nsew + +grid columnconfigure . 2 -weight 1 +grid rowconfigure . 2 -weight 1 + +proc node_bbox {data} { + set xmin 0 + set xmax 0 + set ymin 0 + set ymax 0 + foreach {rowid xmin xmax ymin ymax} [lindex $data 0] break + foreach cell [lrange $data 1 end] { + foreach {rowid x1 x2 y1 y2} $cell break + if {$x1 < $xmin} {set xmin $x1} + if {$x2 > $xmax} {set xmax $x2} + if {$y1 < $ymin} {set ymin $y1} + if {$y2 > $ymax} {set ymax $y2} + } + list $xmin $xmax $ymin $ymax +} + +proc view_node {} { + set iNode $::O(iNode) + set zTab $::O(zTab) + + set data [rtree_node db $zTab $iNode 12] + set depth [rtree_nodedepth db $zTab $iNode] + + .c delete all + set ::O(listbox_captions) [list] + set ::O(listbox_itemmap) [list] + set $::O(listbox_highlight) -1 + + .b configure -state normal + if {$iNode == 1} {.b configure -state disabled} + .title configure -text "Node $iNode: [cell_report db $zTab $iNode -1]" + + foreach {xmin xmax ymin ymax} [node_bbox $data] break + set total_area 0.0 + + set xscale [expr {double([winfo width .c]-20)/($xmax-$xmin)}] + set yscale [expr {double([winfo height .c]-20)/($ymax-$ymin)}] + + set xoff [expr {10.0 - $xmin*$xscale}] + set yoff [expr {10.0 - $ymin*$yscale}] + + foreach cell $data { + foreach {rowid x1 x2 y1 y2} $cell break + set total_area [expr {$total_area + ($x2-$x1)*($y2-$y1)}] + set x1 [expr {$x1*$xscale + $xoff}] + set x2 [expr {$x2*$xscale + $xoff}] + set y1 [expr {$y1*$yscale + $yoff}] + set y2 [expr {$y2*$yscale + $yoff}] + + set id [.c create rectangle $x1 $y1 $x2 $y2] + if {$depth>0} { + lappend ::O(listbox_captions) "Node $rowid" + lappend ::O(listbox_itemmap) $id + } + } +} + +proc cell_report {db zTab iParent iCell} { + set data [rtree_node db $zTab $iParent 12] + set cell [lindex $data $iCell] + + foreach {xmin xmax ymin ymax} [node_bbox $data] break + set total_area [expr ($xmax-$xmin)*($ymax-$ymin)] + + if {$cell eq ""} { + set cell_area 0.0 + foreach cell $data { + foreach {rowid x1 x2 y1 y2} $cell break + set cell_area [expr $cell_area+($x2-$x1)*($y2-$y1)] + } + set cell_area [expr $cell_area/[llength $data]] + set zReport [format "Size = %.1f x %.1f Average child area = %.1f%%" \ + [expr $xmax-$xmin] [expr $ymax-$ymin] [expr 100.0*$cell_area/$total_area]\ + ] + append zReport " Sub-tree height: [rtree_nodedepth db $zTab $iParent]" + } else { + foreach {rowid x1 x2 y1 y2} $cell break + set cell_area [expr ($x2-$x1)*($y2-$y1)] + set zReport [format "Size = %.1f x %.1f Area = %.1f%%" \ + [expr $x2-$x1] [expr $y2-$y1] [expr 100.0*$cell_area/$total_area] + ] + } + + return $zReport +} + +view_node +bind .c view_node diff --git a/components/external/SQLite-3.8.1/install-sh b/components/external/SQLite-3.8.1/install-sh new file mode 100644 index 0000000000000000000000000000000000000000..e9de23842dcd44d2953129c866b1ad25f7e1f1d9 --- /dev/null +++ b/components/external/SQLite-3.8.1/install-sh @@ -0,0 +1,251 @@ +#!/bin/sh +# +# install - install a program, script, or datafile +# This comes from X11R5 (mit/util/scripts/install.sh). +# +# Copyright 1991 by the Massachusetts Institute of Technology +# +# Permission to use, copy, modify, distribute, and sell this software and its +# documentation for any purpose is hereby granted without fee, provided that +# the above copyright notice appear in all copies and that both that +# copyright notice and this permission notice appear in supporting +# documentation, and that the name of M.I.T. not be used in advertising or +# publicity pertaining to distribution of the software without specific, +# written prior permission. M.I.T. makes no representations about the +# suitability of this software for any purpose. It is provided "as is" +# without express or implied warranty. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# `make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. It can only install one file at a time, a restriction +# shared with many OS's install programs. + + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" + + +# put in absolute paths if you don't have them in your path; or use env. vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" +mkdirprog="${MKDIRPROG-mkdir}" + +transformbasename="" +transform_arg="" +instcmd="$mvprog" +chmodcmd="$chmodprog 0755" +chowncmd="" +chgrpcmd="" +stripcmd="" +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src="" +dst="" +dir_arg="" + +while [ x"$1" != x ]; do + case $1 in + -c) instcmd="$cpprog" + shift + continue;; + + -d) dir_arg=true + shift + continue;; + + -m) chmodcmd="$chmodprog $2" + shift + shift + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + -s) stripcmd="$stripprog" + shift + continue;; + + -t=*) transformarg=`echo $1 | sed 's/-t=//'` + shift + continue;; + + -b=*) transformbasename=`echo $1 | sed 's/-b=//'` + shift + continue;; + + *) if [ x"$src" = x ] + then + src=$1 + else + # this colon is to work around a 386BSD /bin/sh bug + : + dst=$1 + fi + shift + continue;; + esac +done + +if [ x"$src" = x ] +then + echo "install: no input file specified" + exit 1 +else + true +fi + +if [ x"$dir_arg" != x ]; then + dst=$src + src="" + + if [ -d $dst ]; then + instcmd=: + chmodcmd="" + else + instcmd=mkdir + fi +else + +# Waiting for this to be detected by the "$instcmd $src $dsttmp" command +# might cause directories to be created, which would be especially bad +# if $src (and thus $dsttmp) contains '*'. + + if [ -f $src -o -d $src ] + then + true + else + echo "install: $src does not exist" + exit 1 + fi + + if [ x"$dst" = x ] + then + echo "install: no destination specified" + exit 1 + else + true + fi + +# If destination is a directory, append the input filename; if your system +# does not like double slashes in filenames, you may need to add some logic + + if [ -d $dst ] + then + dst="$dst"/`basename $src` + else + true + fi +fi + +## this sed command emulates the dirname command +dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` + +# Make sure that the destination directory exists. +# this part is taken from Noah Friedman's mkinstalldirs script + +# Skip lots of stat calls in the usual case. +if [ ! -d "$dstdir" ]; then +defaultIFS=' +' +IFS="${IFS-${defaultIFS}}" + +oIFS="${IFS}" +# Some sh's can't handle IFS=/ for some reason. +IFS='%' +set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'` +IFS="${oIFS}" + +pathcomp='' + +while [ $# -ne 0 ] ; do + pathcomp="${pathcomp}${1}" + shift + + if [ ! -d "${pathcomp}" ] ; + then + $mkdirprog "${pathcomp}" + else + true + fi + + pathcomp="${pathcomp}/" +done +fi + +if [ x"$dir_arg" != x ] +then + $doit $instcmd $dst && + + if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi && + if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi && + if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi && + if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi +else + +# If we're going to rename the final executable, determine the name now. + + if [ x"$transformarg" = x ] + then + dstfile=`basename $dst` + else + dstfile=`basename $dst $transformbasename | + sed $transformarg`$transformbasename + fi + +# don't allow the sed command to completely eliminate the filename + + if [ x"$dstfile" = x ] + then + dstfile=`basename $dst` + else + true + fi + +# Make a temp file name in the proper directory. + + dsttmp=$dstdir/#inst.$$# + +# Move or copy the file name to the temp name + + $doit $instcmd $src $dsttmp && + + trap "rm -f ${dsttmp}" 0 && + +# and set any options; do chmod last to preserve setuid bits + +# If any of these fail, we abort the whole thing. If we want to +# ignore errors from any of these, just make sure not to ignore +# errors from the above "$doit $instcmd $src $dsttmp" command. + + if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi && + if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi && + if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi && + if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi && + +# Now rename the file to the real destination. + + $doit $rmcmd -f $dstdir/$dstfile && + $doit $mvcmd $dsttmp $dstdir/$dstfile + +fi && + + +exit 0 diff --git a/components/external/SQLite-3.8.1/ltmain.sh b/components/external/SQLite-3.8.1/ltmain.sh new file mode 100644 index 0000000000000000000000000000000000000000..0634c4bccce12e53a48e3ba015df80305b579618 --- /dev/null +++ b/components/external/SQLite-3.8.1/ltmain.sh @@ -0,0 +1,8461 @@ +# Generated from ltmain.m4sh. + +# ltmain.sh (GNU libtool) 2.2.6 +# Written by Gordon Matzigkeit , 1996 + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc. +# This is free software; see the source for copying conditions. There is NO +# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +# GNU Libtool is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Libtool; see the file COPYING. If not, a copy +# can be downloaded from http://www.gnu.org/licenses/gpl.html, +# or obtained by writing to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +# Usage: $progname [OPTION]... [MODE-ARG]... +# +# Provide generalized library-building support services. +# +# --config show all configuration variables +# --debug enable verbose shell tracing +# -n, --dry-run display commands without modifying any files +# --features display basic configuration information and exit +# --mode=MODE use operation mode MODE +# --preserve-dup-deps don't remove duplicate dependency libraries +# --quiet, --silent don't print informational messages +# --tag=TAG use configuration variables from tag TAG +# -v, --verbose print informational messages (default) +# --version print version information +# -h, --help print short or long help message +# +# MODE must be one of the following: +# +# clean remove files from the build directory +# compile compile a source file into a libtool object +# execute automatically set library path, then run a program +# finish complete the installation of libtool libraries +# install install libraries or executables +# link create a library or an executable +# uninstall remove libraries from an installed directory +# +# MODE-ARGS vary depending on the MODE. +# Try `$progname --help --mode=MODE' for a more detailed description of MODE. +# +# When reporting a bug, please describe a test case to reproduce it and +# include the following information: +# +# host-triplet: $host +# shell: $SHELL +# compiler: $LTCC +# compiler flags: $LTCFLAGS +# linker: $LD (gnu? $with_gnu_ld) +# $progname: (GNU libtool) 2.2.6 +# automake: $automake_version +# autoconf: $autoconf_version +# +# Report bugs to . + +PROGRAM=ltmain.sh +PACKAGE=libtool +VERSION=2.2.6 +TIMESTAMP="" +package_revision=1.3012 + +# Be Bourne compatible +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac +fi +BIN_SH=xpg4; export BIN_SH # for Tru64 +DUALCASE=1; export DUALCASE # for MKS sh + +# NLS nuisances: We save the old values to restore during execute mode. +# Only set LANG and LC_ALL to C if already set. +# These must not be set unconditionally because not all systems understand +# e.g. LANG=C (notably SCO). +lt_user_locale= +lt_safe_locale= +for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES +do + eval "if test \"\${$lt_var+set}\" = set; then + save_$lt_var=\$$lt_var + $lt_var=C + export $lt_var + lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" + lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" + fi" +done + +$lt_unset CDPATH + + + + + +: ${CP="cp -f"} +: ${ECHO="echo"} +: ${EGREP="/usr/bin/grep -E"} +: ${FGREP="/usr/bin/grep -F"} +: ${GREP="/usr/bin/grep"} +: ${LN_S="ln -s"} +: ${MAKE="make"} +: ${MKDIR="mkdir"} +: ${MV="mv -f"} +: ${RM="rm -f"} +: ${SED="/opt/local/bin/gsed"} +: ${SHELL="${CONFIG_SHELL-/bin/sh}"} +: ${Xsed="$SED -e 1s/^X//"} + +# Global variables: +EXIT_SUCCESS=0 +EXIT_FAILURE=1 +EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. +EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. + +exit_status=$EXIT_SUCCESS + +# Make sure IFS has a sensible default +lt_nl=' +' +IFS=" $lt_nl" + +dirname="s,/[^/]*$,," +basename="s,^.*/,," + +# func_dirname_and_basename file append nondir_replacement +# perform func_basename and func_dirname in a single function +# call: +# dirname: Compute the dirname of FILE. If nonempty, +# add APPEND to the result, otherwise set result +# to NONDIR_REPLACEMENT. +# value returned in "$func_dirname_result" +# basename: Compute filename of FILE. +# value retuned in "$func_basename_result" +# Implementation must be kept synchronized with func_dirname +# and func_basename. For efficiency, we do not delegate to +# those functions but instead duplicate the functionality here. +func_dirname_and_basename () +{ + # Extract subdirectory from the argument. + func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` + if test "X$func_dirname_result" = "X${1}"; then + func_dirname_result="${3}" + else + func_dirname_result="$func_dirname_result${2}" + fi + func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` +} + +# Generated shell functions inserted here. + +# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh +# is ksh but when the shell is invoked as "sh" and the current value of +# the _XPG environment variable is not equal to 1 (one), the special +# positional parameter $0, within a function call, is the name of the +# function. +progpath="$0" + +# The name of this program: +# In the unlikely event $progname began with a '-', it would play havoc with +# func_echo (imagine progname=-n), so we prepend ./ in that case: +func_dirname_and_basename "$progpath" +progname=$func_basename_result +case $progname in + -*) progname=./$progname ;; +esac + +# Make sure we have an absolute path for reexecution: +case $progpath in + [\\/]*|[A-Za-z]:\\*) ;; + *[\\/]*) + progdir=$func_dirname_result + progdir=`cd "$progdir" && pwd` + progpath="$progdir/$progname" + ;; + *) + save_IFS="$IFS" + IFS=: + for progdir in $PATH; do + IFS="$save_IFS" + test -x "$progdir/$progname" && break + done + IFS="$save_IFS" + test -n "$progdir" || progdir=`pwd` + progpath="$progdir/$progname" + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed="${SED}"' -e 1s/^X//' +sed_quote_subst='s/\([`"$\\]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\(["`\\]\)/\\\1/g' + +# Re-`\' parameter expansions in output of double_quote_subst that were +# `\'-ed in input to the same. If an odd number of `\' preceded a '$' +# in input to double_quote_subst, that '$' was protected from expansion. +# Since each input `\' is now two `\'s, look for any number of runs of +# four `\'s followed by two `\'s and then a '$'. `\' that '$'. +bs='\\' +bs2='\\\\' +bs4='\\\\\\\\' +dollar='\$' +sed_double_backslash="\ + s/$bs4/&\\ +/g + s/^$bs2$dollar/$bs&/ + s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g + s/\n//g" + +# Standard options: +opt_dry_run=false +opt_help=false +opt_quiet=false +opt_verbose=false +opt_warning=: + +# func_echo arg... +# Echo program name prefixed message, along with the current mode +# name if it has been set yet. +func_echo () +{ + $ECHO "$progname${mode+: }$mode: $*" +} + +# func_verbose arg... +# Echo program name prefixed message in verbose mode only. +func_verbose () +{ + $opt_verbose && func_echo ${1+"$@"} + + # A bug in bash halts the script if the last line of a function + # fails when set -e is in force, so we need another command to + # work around that: + : +} + +# func_error arg... +# Echo program name prefixed message to standard error. +func_error () +{ + $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2 +} + +# func_warning arg... +# Echo program name prefixed warning message to standard error. +func_warning () +{ + $opt_warning && $ECHO "$progname${mode+: }$mode: warning: "${1+"$@"} 1>&2 + + # bash bug again: + : +} + +# func_fatal_error arg... +# Echo program name prefixed message to standard error, and exit. +func_fatal_error () +{ + func_error ${1+"$@"} + exit $EXIT_FAILURE +} + +# func_fatal_help arg... +# Echo program name prefixed message to standard error, followed by +# a help hint, and exit. +func_fatal_help () +{ + func_error ${1+"$@"} + func_fatal_error "$help" +} +help="Try \`$progname --help' for more information." ## default + + +# func_grep expression filename +# Check whether EXPRESSION matches any line of FILENAME, without output. +func_grep () +{ + $GREP "$1" "$2" >/dev/null 2>&1 +} + + +# func_mkdir_p directory-path +# Make sure the entire path to DIRECTORY-PATH is available. +func_mkdir_p () +{ + my_directory_path="$1" + my_dir_list= + + if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then + + # Protect directory names starting with `-' + case $my_directory_path in + -*) my_directory_path="./$my_directory_path" ;; + esac + + # While some portion of DIR does not yet exist... + while test ! -d "$my_directory_path"; do + # ...make a list in topmost first order. Use a colon delimited + # list incase some portion of path contains whitespace. + my_dir_list="$my_directory_path:$my_dir_list" + + # If the last portion added has no slash in it, the list is done + case $my_directory_path in */*) ;; *) break ;; esac + + # ...otherwise throw away the child directory and loop + my_directory_path=`$ECHO "X$my_directory_path" | $Xsed -e "$dirname"` + done + my_dir_list=`$ECHO "X$my_dir_list" | $Xsed -e 's,:*$,,'` + + save_mkdir_p_IFS="$IFS"; IFS=':' + for my_dir in $my_dir_list; do + IFS="$save_mkdir_p_IFS" + # mkdir can fail with a `File exist' error if two processes + # try to create one of the directories concurrently. Don't + # stop in that case! + $MKDIR "$my_dir" 2>/dev/null || : + done + IFS="$save_mkdir_p_IFS" + + # Bail out if we (or some other process) failed to create a directory. + test -d "$my_directory_path" || \ + func_fatal_error "Failed to create \`$1'" + fi +} + + +# func_mktempdir [string] +# Make a temporary directory that won't clash with other running +# libtool processes, and avoids race conditions if possible. If +# given, STRING is the basename for that directory. +func_mktempdir () +{ + my_template="${TMPDIR-/tmp}/${1-$progname}" + + if test "$opt_dry_run" = ":"; then + # Return a directory name, but don't create it in dry-run mode + my_tmpdir="${my_template}-$$" + else + + # If mktemp works, use that first and foremost + my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` + + if test ! -d "$my_tmpdir"; then + # Failing that, at least try and use $RANDOM to avoid a race + my_tmpdir="${my_template}-${RANDOM-0}$$" + + save_mktempdir_umask=`umask` + umask 0077 + $MKDIR "$my_tmpdir" + umask $save_mktempdir_umask + fi + + # If we're not in dry-run mode, bomb out on failure + test -d "$my_tmpdir" || \ + func_fatal_error "cannot create temporary directory \`$my_tmpdir'" + fi + + $ECHO "X$my_tmpdir" | $Xsed +} + + +# func_quote_for_eval arg +# Aesthetically quote ARG to be evaled later. +# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT +# is double-quoted, suitable for a subsequent eval, whereas +# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters +# which are still active within double quotes backslashified. +func_quote_for_eval () +{ + case $1 in + *[\\\`\"\$]*) + func_quote_for_eval_unquoted_result=`$ECHO "X$1" | $Xsed -e "$sed_quote_subst"` ;; + *) + func_quote_for_eval_unquoted_result="$1" ;; + esac + + case $func_quote_for_eval_unquoted_result in + # Double-quote args containing shell metacharacters to delay + # word splitting, command substitution and and variable + # expansion for a subsequent eval. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" + ;; + *) + func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" + esac +} + + +# func_quote_for_expand arg +# Aesthetically quote ARG to be evaled later; same as above, +# but do not quote variable references. +func_quote_for_expand () +{ + case $1 in + *[\\\`\"]*) + my_arg=`$ECHO "X$1" | $Xsed \ + -e "$double_quote_subst" -e "$sed_double_backslash"` ;; + *) + my_arg="$1" ;; + esac + + case $my_arg in + # Double-quote args containing shell metacharacters to delay + # word splitting and command substitution for a subsequent eval. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + my_arg="\"$my_arg\"" + ;; + esac + + func_quote_for_expand_result="$my_arg" +} + + +# func_show_eval cmd [fail_exp] +# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. +func_show_eval () +{ + my_cmd="$1" + my_fail_exp="${2-:}" + + ${opt_silent-false} || { + func_quote_for_expand "$my_cmd" + eval "func_echo $func_quote_for_expand_result" + } + + if ${opt_dry_run-false}; then :; else + eval "$my_cmd" + my_status=$? + if test "$my_status" -eq 0; then :; else + eval "(exit $my_status); $my_fail_exp" + fi + fi +} + + +# func_show_eval_locale cmd [fail_exp] +# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. Use the saved locale for evaluation. +func_show_eval_locale () +{ + my_cmd="$1" + my_fail_exp="${2-:}" + + ${opt_silent-false} || { + func_quote_for_expand "$my_cmd" + eval "func_echo $func_quote_for_expand_result" + } + + if ${opt_dry_run-false}; then :; else + eval "$lt_user_locale + $my_cmd" + my_status=$? + eval "$lt_safe_locale" + if test "$my_status" -eq 0; then :; else + eval "(exit $my_status); $my_fail_exp" + fi + fi +} + + + + + +# func_version +# Echo version message to standard output and exit. +func_version () +{ + $SED -n '/^# '$PROGRAM' (GNU /,/# warranty; / { + s/^# // + s/^# *$// + s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ + p + }' < "$progpath" + exit $? +} + +# func_usage +# Echo short help message to standard output and exit. +func_usage () +{ + $SED -n '/^# Usage:/,/# -h/ { + s/^# // + s/^# *$// + s/\$progname/'$progname'/ + p + }' < "$progpath" + $ECHO + $ECHO "run \`$progname --help | more' for full usage" + exit $? +} + +# func_help +# Echo long help message to standard output and exit. +func_help () +{ + $SED -n '/^# Usage:/,/# Report bugs to/ { + s/^# // + s/^# *$// + s*\$progname*'$progname'* + s*\$host*'"$host"'* + s*\$SHELL*'"$SHELL"'* + s*\$LTCC*'"$LTCC"'* + s*\$LTCFLAGS*'"$LTCFLAGS"'* + s*\$LD*'"$LD"'* + s/\$with_gnu_ld/'"$with_gnu_ld"'/ + s/\$automake_version/'"`(automake --version) 2>/dev/null |$SED 1q`"'/ + s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/ + p + }' < "$progpath" + exit $? +} + +# func_missing_arg argname +# Echo program name prefixed message to standard error and set global +# exit_cmd. +func_missing_arg () +{ + func_error "missing argument for $1" + exit_cmd=exit +} + +exit_cmd=: + + + + + +# Check that we have a working $ECHO. +if test "X$1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X$1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t'; then + # Yippee, $ECHO works! + : +else + # Restart under the correct shell, and then maybe $ECHO will work. + exec $SHELL "$progpath" --no-reexec ${1+"$@"} +fi +# Same for EGREP, and just to be sure, do LTCC as well +if test "x$EGREP" = x ; then + EGREP=egrep +fi +if test "x$LTCC" = x ; then + LTCC=${CC-gcc} +fi + +if test "X$1" = X--fallback-echo; then + # used as fallback echo + shift + cat </dev/null 2>&1; then + taglist="$taglist $tagname" + + # Evaluate the configuration. Be careful to quote the path + # and the sed script, to avoid splitting on whitespace, but + # also don't use non-portable quotes within backquotes within + # quotes we have to do it in 2 steps: + extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` + eval "$extractedcf" + else + func_error "ignoring unknown tag $tagname" + fi + ;; + esac +} + +# Parse options once, thoroughly. This comes as soon as possible in +# the script to make things like `libtool --version' happen quickly. +{ + + # Shorthand for --mode=foo, only valid as the first argument + case $1 in + clean|clea|cle|cl) + shift; set dummy --mode clean ${1+"$@"}; shift + ;; + compile|compil|compi|comp|com|co|c) + shift; set dummy --mode compile ${1+"$@"}; shift + ;; + execute|execut|execu|exec|exe|ex|e) + shift; set dummy --mode execute ${1+"$@"}; shift + ;; + finish|finis|fini|fin|fi|f) + shift; set dummy --mode finish ${1+"$@"}; shift + ;; + install|instal|insta|inst|ins|in|i) + shift; set dummy --mode install ${1+"$@"}; shift + ;; + link|lin|li|l) + shift; set dummy --mode link ${1+"$@"}; shift + ;; + uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) + shift; set dummy --mode uninstall ${1+"$@"}; shift + ;; + esac + + # Parse non-mode specific arguments: + while test "$#" -gt 0; do + opt="$1" + shift + + case $opt in + --config) func_config ;; + + --debug) preserve_args="$preserve_args $opt" + func_echo "enabling shell trace mode" + opt_debug='set -x' + $opt_debug + ;; + + -dlopen) test "$#" -eq 0 && func_missing_arg "$opt" && break + execute_dlfiles="$execute_dlfiles $1" + shift + ;; + + --dry-run | -n) opt_dry_run=: ;; + --features) func_features ;; + --finish) mode="finish" ;; + + --mode) test "$#" -eq 0 && func_missing_arg "$opt" && break + case $1 in + # Valid mode arguments: + clean) ;; + compile) ;; + execute) ;; + finish) ;; + install) ;; + link) ;; + relink) ;; + uninstall) ;; + + # Catch anything else as an error + *) func_error "invalid argument for $opt" + exit_cmd=exit + break + ;; + esac + + mode="$1" + shift + ;; + + --preserve-dup-deps) + opt_duplicate_deps=: ;; + + --quiet|--silent) preserve_args="$preserve_args $opt" + opt_silent=: + ;; + + --verbose| -v) preserve_args="$preserve_args $opt" + opt_silent=false + ;; + + --tag) test "$#" -eq 0 && func_missing_arg "$opt" && break + preserve_args="$preserve_args $opt $1" + func_enable_tag "$1" # tagname is set here + shift + ;; + + # Separate optargs to long options: + -dlopen=*|--mode=*|--tag=*) + func_opt_split "$opt" + set dummy "$func_opt_split_opt" "$func_opt_split_arg" ${1+"$@"} + shift + ;; + + -\?|-h) func_usage ;; + --help) opt_help=: ;; + --version) func_version ;; + + -*) func_fatal_help "unrecognized option \`$opt'" ;; + + *) nonopt="$opt" + break + ;; + esac + done + + + case $host in + *cygwin* | *mingw* | *pw32* | *cegcc*) + # don't eliminate duplications in $postdeps and $predeps + opt_duplicate_compiler_generated_deps=: + ;; + *) + opt_duplicate_compiler_generated_deps=$opt_duplicate_deps + ;; + esac + + # Having warned about all mis-specified options, bail out if + # anything was wrong. + $exit_cmd $EXIT_FAILURE +} + +# func_check_version_match +# Ensure that we are using m4 macros, and libtool script from the same +# release of libtool. +func_check_version_match () +{ + if test "$package_revision" != "$macro_revision"; then + if test "$VERSION" != "$macro_version"; then + if test -z "$macro_version"; then + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from an older release. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from $PACKAGE $macro_version. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + fi + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, +$progname: but the definition of this LT_INIT comes from revision $macro_revision. +$progname: You should recreate aclocal.m4 with macros from revision $package_revision +$progname: of $PACKAGE $VERSION and run autoconf again. +_LT_EOF + fi + + exit $EXIT_MISMATCH + fi +} + + +## ----------- ## +## Main. ## +## ----------- ## + +$opt_help || { + # Sanity checks first: + func_check_version_match + + if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then + func_fatal_configuration "not configured to build any kind of library" + fi + + test -z "$mode" && func_fatal_error "error: you must specify a MODE." + + + # Darwin sucks + eval std_shrext=\"$shrext_cmds\" + + + # Only execute mode is allowed to have -dlopen flags. + if test -n "$execute_dlfiles" && test "$mode" != execute; then + func_error "unrecognized option \`-dlopen'" + $ECHO "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Change the help message to a mode-specific one. + generic_help="$help" + help="Try \`$progname --help --mode=$mode' for more information." +} + + +# func_lalib_p file +# True iff FILE is a libtool `.la' library or `.lo' object file. +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_lalib_p () +{ + test -f "$1" && + $SED -e 4q "$1" 2>/dev/null \ + | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 +} + +# func_lalib_unsafe_p file +# True iff FILE is a libtool `.la' library or `.lo' object file. +# This function implements the same check as func_lalib_p without +# resorting to external programs. To this end, it redirects stdin and +# closes it afterwards, without saving the original file descriptor. +# As a safety measure, use it only where a negative result would be +# fatal anyway. Works if `file' does not exist. +func_lalib_unsafe_p () +{ + lalib_p=no + if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then + for lalib_p_l in 1 2 3 4 + do + read lalib_p_line + case "$lalib_p_line" in + \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; + esac + done + exec 0<&5 5<&- + fi + test "$lalib_p" = yes +} + +# func_ltwrapper_script_p file +# True iff FILE is a libtool wrapper script +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_script_p () +{ + func_lalib_p "$1" +} + +# func_ltwrapper_executable_p file +# True iff FILE is a libtool wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_executable_p () +{ + func_ltwrapper_exec_suffix= + case $1 in + *.exe) ;; + *) func_ltwrapper_exec_suffix=.exe ;; + esac + $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 +} + +# func_ltwrapper_scriptname file +# Assumes file is an ltwrapper_executable +# uses $file to determine the appropriate filename for a +# temporary ltwrapper_script. +func_ltwrapper_scriptname () +{ + func_ltwrapper_scriptname_result="" + if func_ltwrapper_executable_p "$1"; then + func_dirname_and_basename "$1" "" "." + func_stripname '' '.exe' "$func_basename_result" + func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" + fi +} + +# func_ltwrapper_p file +# True iff FILE is a libtool wrapper script or wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_p () +{ + func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" +} + + +# func_execute_cmds commands fail_cmd +# Execute tilde-delimited COMMANDS. +# If FAIL_CMD is given, eval that upon failure. +# FAIL_CMD may read-access the current command in variable CMD! +func_execute_cmds () +{ + $opt_debug + save_ifs=$IFS; IFS='~' + for cmd in $1; do + IFS=$save_ifs + eval cmd=\"$cmd\" + func_show_eval "$cmd" "${2-:}" + done + IFS=$save_ifs +} + + +# func_source file +# Source FILE, adding directory component if necessary. +# Note that it is not necessary on cygwin/mingw to append a dot to +# FILE even if both FILE and FILE.exe exist: automatic-append-.exe +# behavior happens only for exec(3), not for open(2)! Also, sourcing +# `FILE.' does not work on cygwin managed mounts. +func_source () +{ + $opt_debug + case $1 in + */* | *\\*) . "$1" ;; + *) . "./$1" ;; + esac +} + + +# func_infer_tag arg +# Infer tagged configuration to use if any are available and +# if one wasn't chosen via the "--tag" command line option. +# Only attempt this if the compiler in the base compile +# command doesn't match the default compiler. +# arg is usually of the form 'gcc ...' +func_infer_tag () +{ + $opt_debug + if test -n "$available_tags" && test -z "$tagname"; then + CC_quoted= + for arg in $CC; do + func_quote_for_eval "$arg" + CC_quoted="$CC_quoted $func_quote_for_eval_result" + done + case $@ in + # Blanks in the command may have been stripped by the calling shell, + # but not from the CC environment variable when configure was run. + " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) ;; + # Blanks at the start of $base_compile will cause this to fail + # if we don't check for them as well. + *) + for z in $available_tags; do + if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then + # Evaluate the configuration. + eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" + CC_quoted= + for arg in $CC; do + # Double-quote args containing other shell metacharacters. + func_quote_for_eval "$arg" + CC_quoted="$CC_quoted $func_quote_for_eval_result" + done + case "$@ " in + " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) + # The compiler in the base compile command matches + # the one in the tagged configuration. + # Assume this is the tagged configuration we want. + tagname=$z + break + ;; + esac + fi + done + # If $tagname still isn't set, then no tagged configuration + # was found and let the user know that the "--tag" command + # line option must be used. + if test -z "$tagname"; then + func_echo "unable to infer tagged configuration" + func_fatal_error "specify a tag with \`--tag'" +# else +# func_verbose "using $tagname tagged configuration" + fi + ;; + esac + fi +} + + + +# func_write_libtool_object output_name pic_name nonpic_name +# Create a libtool object file (analogous to a ".la" file), +# but don't create it if we're doing a dry run. +func_write_libtool_object () +{ + write_libobj=${1} + if test "$build_libtool_libs" = yes; then + write_lobj=\'${2}\' + else + write_lobj=none + fi + + if test "$build_old_libs" = yes; then + write_oldobj=\'${3}\' + else + write_oldobj=none + fi + + $opt_dry_run || { + cat >${write_libobj}T <?"'"'"' &()|`$[]' \ + && func_warning "libobj name \`$libobj' may not contain shell special characters." + func_dirname_and_basename "$obj" "/" "" + objname="$func_basename_result" + xdir="$func_dirname_result" + lobj=${xdir}$objdir/$objname + + test -z "$base_compile" && \ + func_fatal_help "you must specify a compilation command" + + # Delete any leftover library objects. + if test "$build_old_libs" = yes; then + removelist="$obj $lobj $libobj ${libobj}T" + else + removelist="$lobj $libobj ${libobj}T" + fi + + # On Cygwin there's no "real" PIC flag so we must build both object types + case $host_os in + cygwin* | mingw* | pw32* | os2* | cegcc*) + pic_mode=default + ;; + esac + if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then + # non-PIC code in shared libraries is not supported + pic_mode=default + fi + + # Calculate the filename of the output object if compiler does + # not support -o with -c + if test "$compiler_c_o" = no; then + output_obj=`$ECHO "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} + lockfile="$output_obj.lock" + else + output_obj= + need_locks=no + lockfile= + fi + + # Lock this critical section if it is needed + # We use this script file to make the link, it avoids creating a new file + if test "$need_locks" = yes; then + until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do + func_echo "Waiting for $lockfile to be removed" + sleep 2 + done + elif test "$need_locks" = warn; then + if test -f "$lockfile"; then + $ECHO "\ +*** ERROR, $lockfile exists and contains: +`cat $lockfile 2>/dev/null` + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + removelist="$removelist $output_obj" + $ECHO "$srcfile" > "$lockfile" + fi + + $opt_dry_run || $RM $removelist + removelist="$removelist $lockfile" + trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 + + if test -n "$fix_srcfile_path"; then + eval srcfile=\"$fix_srcfile_path\" + fi + func_quote_for_eval "$srcfile" + qsrcfile=$func_quote_for_eval_result + + # Only build a PIC object if we are building libtool libraries. + if test "$build_libtool_libs" = yes; then + # Without this assignment, base_compile gets emptied. + fbsd_hideous_sh_bug=$base_compile + + if test "$pic_mode" != no; then + command="$base_compile $qsrcfile $pic_flag" + else + # Don't build PIC code + command="$base_compile $qsrcfile" + fi + + func_mkdir_p "$xdir$objdir" + + if test -z "$output_obj"; then + # Place PIC objects in $objdir + command="$command -o $lobj" + fi + + func_show_eval_locale "$command" \ + 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' + + if test "$need_locks" = warn && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed, then go on to compile the next one + if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then + func_show_eval '$MV "$output_obj" "$lobj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + + # Allow error messages only from the first compilation. + if test "$suppress_opt" = yes; then + suppress_output=' >/dev/null 2>&1' + fi + fi + + # Only build a position-dependent object if we build old libraries. + if test "$build_old_libs" = yes; then + if test "$pic_mode" != yes; then + # Don't build PIC code + command="$base_compile $qsrcfile$pie_flag" + else + command="$base_compile $qsrcfile $pic_flag" + fi + if test "$compiler_c_o" = yes; then + command="$command -o $obj" + fi + + # Suppress compiler output if we already did a PIC compilation. + command="$command$suppress_output" + func_show_eval_locale "$command" \ + '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' + + if test "$need_locks" = warn && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed + if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then + func_show_eval '$MV "$output_obj" "$obj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + fi + + $opt_dry_run || { + func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" + + # Unlock the critical section if it was locked + if test "$need_locks" != no; then + removelist=$lockfile + $RM "$lockfile" + fi + } + + exit $EXIT_SUCCESS +} + +$opt_help || { +test "$mode" = compile && func_mode_compile ${1+"$@"} +} + +func_mode_help () +{ + # We need to display help for each of the modes. + case $mode in + "") + # Generic help is extracted from the usage comments + # at the start of this file. + func_help + ;; + + clean) + $ECHO \ +"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... + +Remove files from the build directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, object or program, all the files associated +with it are deleted. Otherwise, only FILE itself is deleted using RM." + ;; + + compile) + $ECHO \ +"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE + +Compile a source file into a libtool library object. + +This mode accepts the following additional options: + + -o OUTPUT-FILE set the output file name to OUTPUT-FILE + -no-suppress do not suppress compiler output for multiple passes + -prefer-pic try to building PIC objects only + -prefer-non-pic try to building non-PIC objects only + -shared do not build a \`.o' file suitable for static linking + -static only build a \`.o' file suitable for static linking + +COMPILE-COMMAND is a command to be used in creating a \`standard' object file +from the given SOURCEFILE. + +The output file name is determined by removing the directory component from +SOURCEFILE, then substituting the C source code suffix \`.c' with the +library object suffix, \`.lo'." + ;; + + execute) + $ECHO \ +"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... + +Automatically set library path, then run a program. + +This mode accepts the following additional options: + + -dlopen FILE add the directory containing FILE to the library path + +This mode sets the library path environment variable according to \`-dlopen' +flags. + +If any of the ARGS are libtool executable wrappers, then they are translated +into their corresponding uninstalled binary, and any of their required library +directories are added to the library path. + +Then, COMMAND is executed, with ARGS as arguments." + ;; + + finish) + $ECHO \ +"Usage: $progname [OPTION]... --mode=finish [LIBDIR]... + +Complete the installation of libtool libraries. + +Each LIBDIR is a directory that contains libtool libraries. + +The commands that this mode executes may require superuser privileges. Use +the \`--dry-run' option if you just want to see what would be executed." + ;; + + install) + $ECHO \ +"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... + +Install executables or libraries. + +INSTALL-COMMAND is the installation command. The first component should be +either the \`install' or \`cp' program. + +The following components of INSTALL-COMMAND are treated specially: + + -inst-prefix PREFIX-DIR Use PREFIX-DIR as a staging area for installation + +The rest of the components are interpreted as arguments to that command (only +BSD-compatible install options are recognized)." + ;; + + link) + $ECHO \ +"Usage: $progname [OPTION]... --mode=link LINK-COMMAND... + +Link object files or libraries together to form another library, or to +create an executable program. + +LINK-COMMAND is a command using the C compiler that you would use to create +a program from several object files. + +The following components of LINK-COMMAND are treated specially: + + -all-static do not do any dynamic linking at all + -avoid-version do not add a version suffix if possible + -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime + -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols + -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) + -export-symbols SYMFILE + try to export only the symbols listed in SYMFILE + -export-symbols-regex REGEX + try to export only the symbols matching REGEX + -LLIBDIR search LIBDIR for required installed libraries + -lNAME OUTPUT-FILE requires the installed library libNAME + -module build a library that can dlopened + -no-fast-install disable the fast-install mode + -no-install link a not-installable executable + -no-undefined declare that a library does not refer to external symbols + -o OUTPUT-FILE create OUTPUT-FILE from the specified objects + -objectlist FILE Use a list of object files found in FILE to specify objects + -precious-files-regex REGEX + don't remove output files matching REGEX + -release RELEASE specify package release information + -rpath LIBDIR the created library will eventually be installed in LIBDIR + -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries + -shared only do dynamic linking of libtool libraries + -shrext SUFFIX override the standard shared library file extension + -static do not do any dynamic linking of uninstalled libtool libraries + -static-libtool-libs + do not do any dynamic linking of libtool libraries + -version-info CURRENT[:REVISION[:AGE]] + specify library version info [each variable defaults to 0] + -weak LIBNAME declare that the target provides the LIBNAME interface + +All other options (arguments beginning with \`-') are ignored. + +Every other argument is treated as a filename. Files ending in \`.la' are +treated as uninstalled libtool libraries, other files are standard or library +object files. + +If the OUTPUT-FILE ends in \`.la', then a libtool library is created, +only library objects (\`.lo' files) may be specified, and \`-rpath' is +required, except when creating a convenience library. + +If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created +using \`ar' and \`ranlib', or on Windows using \`lib'. + +If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file +is created, otherwise an executable program is created." + ;; + + uninstall) + $ECHO \ +"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... + +Remove libraries from an installation directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, all the files associated with it are deleted. +Otherwise, only FILE itself is deleted using RM." + ;; + + *) + func_fatal_help "invalid operation mode \`$mode'" + ;; + esac + + $ECHO + $ECHO "Try \`$progname --help' for more information about other modes." + + exit $? +} + + # Now that we've collected a possible --mode arg, show help if necessary + $opt_help && func_mode_help + + +# func_mode_execute arg... +func_mode_execute () +{ + $opt_debug + # The first argument is the command name. + cmd="$nonopt" + test -z "$cmd" && \ + func_fatal_help "you must specify a COMMAND" + + # Handle -dlopen flags immediately. + for file in $execute_dlfiles; do + test -f "$file" \ + || func_fatal_help "\`$file' is not a file" + + dir= + case $file in + *.la) + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "\`$lib' is not a valid libtool archive" + + # Read the libtool library. + dlname= + library_names= + func_source "$file" + + # Skip this library if it cannot be dlopened. + if test -z "$dlname"; then + # Warn if it was a shared library. + test -n "$library_names" && \ + func_warning "\`$file' was not linked with \`-export-dynamic'" + continue + fi + + func_dirname "$file" "" "." + dir="$func_dirname_result" + + if test -f "$dir/$objdir/$dlname"; then + dir="$dir/$objdir" + else + if test ! -f "$dir/$dlname"; then + func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" + fi + fi + ;; + + *.lo) + # Just add the directory containing the .lo file. + func_dirname "$file" "" "." + dir="$func_dirname_result" + ;; + + *) + func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" + continue + ;; + esac + + # Get the absolute pathname. + absdir=`cd "$dir" && pwd` + test -n "$absdir" && dir="$absdir" + + # Now add the directory to shlibpath_var. + if eval "test -z \"\$$shlibpath_var\""; then + eval "$shlibpath_var=\"\$dir\"" + else + eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" + fi + done + + # This variable tells wrapper scripts just to set shlibpath_var + # rather than running their programs. + libtool_execute_magic="$magic" + + # Check if any of the arguments is a wrapper script. + args= + for file + do + case $file in + -*) ;; + *) + # Do a test to see if this is really a libtool program. + if func_ltwrapper_script_p "$file"; then + func_source "$file" + # Transform arg to wrapped name. + file="$progdir/$program" + elif func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + func_source "$func_ltwrapper_scriptname_result" + # Transform arg to wrapped name. + file="$progdir/$program" + fi + ;; + esac + # Quote arguments (to preserve shell metacharacters). + func_quote_for_eval "$file" + args="$args $func_quote_for_eval_result" + done + + if test "X$opt_dry_run" = Xfalse; then + if test -n "$shlibpath_var"; then + # Export the shlibpath_var. + eval "export $shlibpath_var" + fi + + # Restore saved environment variables + for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES + do + eval "if test \"\${save_$lt_var+set}\" = set; then + $lt_var=\$save_$lt_var; export $lt_var + else + $lt_unset $lt_var + fi" + done + + # Now prepare to actually exec the command. + exec_cmd="\$cmd$args" + else + # Display what would be done. + if test -n "$shlibpath_var"; then + eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" + $ECHO "export $shlibpath_var" + fi + $ECHO "$cmd$args" + exit $EXIT_SUCCESS + fi +} + +test "$mode" = execute && func_mode_execute ${1+"$@"} + + +# func_mode_finish arg... +func_mode_finish () +{ + $opt_debug + libdirs="$nonopt" + admincmds= + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + for dir + do + libdirs="$libdirs $dir" + done + + for libdir in $libdirs; do + if test -n "$finish_cmds"; then + # Do each command in the finish commands. + func_execute_cmds "$finish_cmds" 'admincmds="$admincmds +'"$cmd"'"' + fi + if test -n "$finish_eval"; then + # Do the single finish_eval. + eval cmds=\"$finish_eval\" + $opt_dry_run || eval "$cmds" || admincmds="$admincmds + $cmds" + fi + done + fi + + # Exit here if they wanted silent mode. + $opt_silent && exit $EXIT_SUCCESS + + $ECHO "X----------------------------------------------------------------------" | $Xsed + $ECHO "Libraries have been installed in:" + for libdir in $libdirs; do + $ECHO " $libdir" + done + $ECHO + $ECHO "If you ever happen to want to link against installed libraries" + $ECHO "in a given directory, LIBDIR, you must either use libtool, and" + $ECHO "specify the full pathname of the library, or use the \`-LLIBDIR'" + $ECHO "flag during linking and do at least one of the following:" + if test -n "$shlibpath_var"; then + $ECHO " - add LIBDIR to the \`$shlibpath_var' environment variable" + $ECHO " during execution" + fi + if test -n "$runpath_var"; then + $ECHO " - add LIBDIR to the \`$runpath_var' environment variable" + $ECHO " during linking" + fi + if test -n "$hardcode_libdir_flag_spec"; then + libdir=LIBDIR + eval flag=\"$hardcode_libdir_flag_spec\" + + $ECHO " - use the \`$flag' linker flag" + fi + if test -n "$admincmds"; then + $ECHO " - have your system administrator run these commands:$admincmds" + fi + if test -f /etc/ld.so.conf; then + $ECHO " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" + fi + $ECHO + + $ECHO "See any operating system documentation about shared libraries for" + case $host in + solaris2.[6789]|solaris2.1[0-9]) + $ECHO "more information, such as the ld(1), crle(1) and ld.so(8) manual" + $ECHO "pages." + ;; + *) + $ECHO "more information, such as the ld(1) and ld.so(8) manual pages." + ;; + esac + $ECHO "X----------------------------------------------------------------------" | $Xsed + exit $EXIT_SUCCESS +} + +test "$mode" = finish && func_mode_finish ${1+"$@"} + + +# func_mode_install arg... +func_mode_install () +{ + $opt_debug + # There may be an optional sh(1) argument at the beginning of + # install_prog (especially on Windows NT). + if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || + # Allow the use of GNU shtool's install command. + $ECHO "X$nonopt" | $GREP shtool >/dev/null; then + # Aesthetically quote it. + func_quote_for_eval "$nonopt" + install_prog="$func_quote_for_eval_result " + arg=$1 + shift + else + install_prog= + arg=$nonopt + fi + + # The real first argument should be the name of the installation program. + # Aesthetically quote it. + func_quote_for_eval "$arg" + install_prog="$install_prog$func_quote_for_eval_result" + + # We need to accept at least all the BSD install flags. + dest= + files= + opts= + prev= + install_type= + isdir=no + stripme= + for arg + do + if test -n "$dest"; then + files="$files $dest" + dest=$arg + continue + fi + + case $arg in + -d) isdir=yes ;; + -f) + case " $install_prog " in + *[\\\ /]cp\ *) ;; + *) prev=$arg ;; + esac + ;; + -g | -m | -o) + prev=$arg + ;; + -s) + stripme=" -s" + continue + ;; + -*) + ;; + *) + # If the previous option needed an argument, then skip it. + if test -n "$prev"; then + prev= + else + dest=$arg + continue + fi + ;; + esac + + # Aesthetically quote the argument. + func_quote_for_eval "$arg" + install_prog="$install_prog $func_quote_for_eval_result" + done + + test -z "$install_prog" && \ + func_fatal_help "you must specify an install program" + + test -n "$prev" && \ + func_fatal_help "the \`$prev' option requires an argument" + + if test -z "$files"; then + if test -z "$dest"; then + func_fatal_help "no file or destination specified" + else + func_fatal_help "you must specify a destination" + fi + fi + + # Strip any trailing slash from the destination. + func_stripname '' '/' "$dest" + dest=$func_stripname_result + + # Check to see that the destination is a directory. + test -d "$dest" && isdir=yes + if test "$isdir" = yes; then + destdir="$dest" + destname= + else + func_dirname_and_basename "$dest" "" "." + destdir="$func_dirname_result" + destname="$func_basename_result" + + # Not a directory, so check to see that there is only one file specified. + set dummy $files; shift + test "$#" -gt 1 && \ + func_fatal_help "\`$dest' is not a directory" + fi + case $destdir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + for file in $files; do + case $file in + *.lo) ;; + *) + func_fatal_help "\`$destdir' must be an absolute directory name" + ;; + esac + done + ;; + esac + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + staticlibs= + future_libdirs= + current_libdirs= + for file in $files; do + + # Do each installation. + case $file in + *.$libext) + # Do the static libraries later. + staticlibs="$staticlibs $file" + ;; + + *.la) + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "\`$file' is not a valid libtool archive" + + library_names= + old_library= + relink_command= + func_source "$file" + + # Add the libdir to current_libdirs if it is the destination. + if test "X$destdir" = "X$libdir"; then + case "$current_libdirs " in + *" $libdir "*) ;; + *) current_libdirs="$current_libdirs $libdir" ;; + esac + else + # Note the libdir as a future libdir. + case "$future_libdirs " in + *" $libdir "*) ;; + *) future_libdirs="$future_libdirs $libdir" ;; + esac + fi + + func_dirname "$file" "/" "" + dir="$func_dirname_result" + dir="$dir$objdir" + + if test -n "$relink_command"; then + # Determine the prefix the user has applied to our future dir. + inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"` + + # Don't allow the user to place us outside of our expected + # location b/c this prevents finding dependent libraries that + # are installed to the same prefix. + # At present, this check doesn't affect windows .dll's that + # are installed into $libdir/../bin (currently, that works fine) + # but it's something to keep an eye on. + test "$inst_prefix_dir" = "$destdir" && \ + func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" + + if test -n "$inst_prefix_dir"; then + # Stick the inst_prefix_dir data into the link command. + relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` + else + relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%%"` + fi + + func_warning "relinking \`$file'" + func_show_eval "$relink_command" \ + 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' + fi + + # See the names of the shared library. + set dummy $library_names; shift + if test -n "$1"; then + realname="$1" + shift + + srcname="$realname" + test -n "$relink_command" && srcname="$realname"T + + # Install the shared library and build the symlinks. + func_show_eval "$install_prog $dir/$srcname $destdir/$realname" \ + 'exit $?' + tstripme="$stripme" + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + case $realname in + *.dll.a) + tstripme="" + ;; + esac + ;; + esac + if test -n "$tstripme" && test -n "$striplib"; then + func_show_eval "$striplib $destdir/$realname" 'exit $?' + fi + + if test "$#" -gt 0; then + # Delete the old symlinks, and create new ones. + # Try `ln -sf' first, because the `ln' binary might depend on + # the symlink we replace! Solaris /bin/ln does not understand -f, + # so we also need to try rm && ln -s. + for linkname + do + test "$linkname" != "$realname" \ + && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" + done + fi + + # Do each command in the postinstall commands. + lib="$destdir/$realname" + func_execute_cmds "$postinstall_cmds" 'exit $?' + fi + + # Install the pseudo-library for information purposes. + func_basename "$file" + name="$func_basename_result" + instname="$dir/$name"i + func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' + + # Maybe install the static library, too. + test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library" + ;; + + *.lo) + # Install (i.e. copy) a libtool object. + + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + func_basename "$file" + destfile="$func_basename_result" + destfile="$destdir/$destfile" + fi + + # Deduce the name of the destination old-style object file. + case $destfile in + *.lo) + func_lo2o "$destfile" + staticdest=$func_lo2o_result + ;; + *.$objext) + staticdest="$destfile" + destfile= + ;; + *) + func_fatal_help "cannot copy a libtool object to \`$destfile'" + ;; + esac + + # Install the libtool object if requested. + test -n "$destfile" && \ + func_show_eval "$install_prog $file $destfile" 'exit $?' + + # Install the old object if enabled. + if test "$build_old_libs" = yes; then + # Deduce the name of the old-style object file. + func_lo2o "$file" + staticobj=$func_lo2o_result + func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' + fi + exit $EXIT_SUCCESS + ;; + + *) + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + func_basename "$file" + destfile="$func_basename_result" + destfile="$destdir/$destfile" + fi + + # If the file is missing, and there is a .exe on the end, strip it + # because it is most likely a libtool script we actually want to + # install + stripped_ext="" + case $file in + *.exe) + if test ! -f "$file"; then + func_stripname '' '.exe' "$file" + file=$func_stripname_result + stripped_ext=".exe" + fi + ;; + esac + + # Do a test to see if this is really a libtool program. + case $host in + *cygwin* | *mingw*) + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + wrapper=$func_ltwrapper_scriptname_result + else + func_stripname '' '.exe' "$file" + wrapper=$func_stripname_result + fi + ;; + *) + wrapper=$file + ;; + esac + if func_ltwrapper_script_p "$wrapper"; then + notinst_deplibs= + relink_command= + + func_source "$wrapper" + + # Check the variables that should have been set. + test -z "$generated_by_libtool_version" && \ + func_fatal_error "invalid libtool wrapper script \`$wrapper'" + + finalize=yes + for lib in $notinst_deplibs; do + # Check to see that each library is installed. + libdir= + if test -f "$lib"; then + func_source "$lib" + fi + libfile="$libdir/"`$ECHO "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test + if test -n "$libdir" && test ! -f "$libfile"; then + func_warning "\`$lib' has not been installed in \`$libdir'" + finalize=no + fi + done + + relink_command= + func_source "$wrapper" + + outputname= + if test "$fast_install" = no && test -n "$relink_command"; then + $opt_dry_run || { + if test "$finalize" = yes; then + tmpdir=`func_mktempdir` + func_basename "$file$stripped_ext" + file="$func_basename_result" + outputname="$tmpdir/$file" + # Replace the output file specification. + relink_command=`$ECHO "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` + + $opt_silent || { + func_quote_for_expand "$relink_command" + eval "func_echo $func_quote_for_expand_result" + } + if eval "$relink_command"; then : + else + func_error "error: relink \`$file' with the above command before installing it" + $opt_dry_run || ${RM}r "$tmpdir" + continue + fi + file="$outputname" + else + func_warning "cannot relink \`$file'" + fi + } + else + # Install the binary that we compiled earlier. + file=`$ECHO "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"` + fi + fi + + # remove .exe since cygwin /usr/bin/install will append another + # one anyway + case $install_prog,$host in + */usr/bin/install*,*cygwin*) + case $file:$destfile in + *.exe:*.exe) + # this is ok + ;; + *.exe:*) + destfile=$destfile.exe + ;; + *:*.exe) + func_stripname '' '.exe' "$destfile" + destfile=$func_stripname_result + ;; + esac + ;; + esac + func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' + $opt_dry_run || if test -n "$outputname"; then + ${RM}r "$tmpdir" + fi + ;; + esac + done + + for file in $staticlibs; do + func_basename "$file" + name="$func_basename_result" + + # Set up the ranlib parameters. + oldlib="$destdir/$name" + + func_show_eval "$install_prog \$file \$oldlib" 'exit $?' + + if test -n "$stripme" && test -n "$old_striplib"; then + func_show_eval "$old_striplib $oldlib" 'exit $?' + fi + + # Do each command in the postinstall commands. + func_execute_cmds "$old_postinstall_cmds" 'exit $?' + done + + test -n "$future_libdirs" && \ + func_warning "remember to run \`$progname --finish$future_libdirs'" + + if test -n "$current_libdirs"; then + # Maybe just do a dry run. + $opt_dry_run && current_libdirs=" -n$current_libdirs" + exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' + else + exit $EXIT_SUCCESS + fi +} + +test "$mode" = install && func_mode_install ${1+"$@"} + + +# func_generate_dlsyms outputname originator pic_p +# Extract symbols from dlprefiles and create ${outputname}S.o with +# a dlpreopen symbol table. +func_generate_dlsyms () +{ + $opt_debug + my_outputname="$1" + my_originator="$2" + my_pic_p="${3-no}" + my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` + my_dlsyms= + + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + if test -n "$NM" && test -n "$global_symbol_pipe"; then + my_dlsyms="${my_outputname}S.c" + else + func_error "not configured to extract global symbols from dlpreopened files" + fi + fi + + if test -n "$my_dlsyms"; then + case $my_dlsyms in + "") ;; + *.c) + # Discover the nlist of each of the dlfiles. + nlist="$output_objdir/${my_outputname}.nm" + + func_show_eval "$RM $nlist ${nlist}S ${nlist}T" + + # Parse the name list into a source file. + func_verbose "creating $output_objdir/$my_dlsyms" + + $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ +/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ +/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ + +#ifdef __cplusplus +extern \"C\" { +#endif + +/* External symbol declarations for the compiler. */\ +" + + if test "$dlself" = yes; then + func_verbose "generating symbol list for \`$output'" + + $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" + + # Add our own program objects to the symbol list. + progfiles=`$ECHO "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + for progfile in $progfiles; do + func_verbose "extracting global C symbols from \`$progfile'" + $opt_dry_run || eval "$NM $progfile | $global_symbol_pipe >> '$nlist'" + done + + if test -n "$exclude_expsyms"; then + $opt_dry_run || { + eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + if test -n "$export_symbols_regex"; then + $opt_dry_run || { + eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + export_symbols="$output_objdir/$outputname.exp" + $opt_dry_run || { + $RM $export_symbols + eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' + case $host in + *cygwin* | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' + ;; + esac + } + else + $opt_dry_run || { + eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' + eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + case $host in + *cygwin | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' + ;; + esac + } + fi + fi + + for dlprefile in $dlprefiles; do + func_verbose "extracting global C symbols from \`$dlprefile'" + func_basename "$dlprefile" + name="$func_basename_result" + $opt_dry_run || { + eval '$ECHO ": $name " >> "$nlist"' + eval "$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'" + } + done + + $opt_dry_run || { + # Make sure we have at least an empty file. + test -f "$nlist" || : > "$nlist" + + if test -n "$exclude_expsyms"; then + $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T + $MV "$nlist"T "$nlist" + fi + + # Try sorting and uniquifying the output. + if $GREP -v "^: " < "$nlist" | + if sort -k 3 /dev/null 2>&1; then + sort -k 3 + else + sort +2 + fi | + uniq > "$nlist"S; then + : + else + $GREP -v "^: " < "$nlist" > "$nlist"S + fi + + if test -f "$nlist"S; then + eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' + else + $ECHO '/* NONE */' >> "$output_objdir/$my_dlsyms" + fi + + $ECHO >> "$output_objdir/$my_dlsyms" "\ + +/* The mapping between symbol names and symbols. */ +typedef struct { + const char *name; + void *address; +} lt_dlsymlist; +" + case $host in + *cygwin* | *mingw* | *cegcc* ) + $ECHO >> "$output_objdir/$my_dlsyms" "\ +/* DATA imports from DLLs on WIN32 con't be const, because + runtime relocations are performed -- see ld's documentation + on pseudo-relocs. */" + lt_dlsym_const= ;; + *osf5*) + echo >> "$output_objdir/$my_dlsyms" "\ +/* This system does not cope well with relocations in const data */" + lt_dlsym_const= ;; + *) + lt_dlsym_const=const ;; + esac + + $ECHO >> "$output_objdir/$my_dlsyms" "\ +extern $lt_dlsym_const lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[]; +$lt_dlsym_const lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[] = +{\ + { \"$my_originator\", (void *) 0 }," + + case $need_lib_prefix in + no) + eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + *) + eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + esac + $ECHO >> "$output_objdir/$my_dlsyms" "\ + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt_${my_prefix}_LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif\ +" + } # !$opt_dry_run + + pic_flag_for_symtable= + case "$compile_command " in + *" -static "*) ;; + *) + case $host in + # compiling the symbol table file with pic_flag works around + # a FreeBSD bug that causes programs to crash when -lm is + # linked before any other PIC object. But we must not use + # pic_flag when linking with -static. The problem exists in + # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. + *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) + pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; + *-*-hpux*) + pic_flag_for_symtable=" $pic_flag" ;; + *) + if test "X$my_pic_p" != Xno; then + pic_flag_for_symtable=" $pic_flag" + fi + ;; + esac + ;; + esac + symtab_cflags= + for arg in $LTCFLAGS; do + case $arg in + -pie | -fpie | -fPIE) ;; + *) symtab_cflags="$symtab_cflags $arg" ;; + esac + done + + # Now compile the dynamic symbol file. + func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' + + # Clean up the generated files. + func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' + + # Transform the symbol file into the correct name. + symfileobj="$output_objdir/${my_outputname}S.$objext" + case $host in + *cygwin* | *mingw* | *cegcc* ) + if test -f "$output_objdir/$my_outputname.def"; then + compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + else + compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` + fi + ;; + *) + compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` + ;; + esac + ;; + *) + func_fatal_error "unknown suffix for \`$my_dlsyms'" + ;; + esac + else + # We keep going just in case the user didn't refer to + # lt_preloaded_symbols. The linker will fail if global_symbol_pipe + # really was required. + + # Nullify the symbol file. + compile_command=`$ECHO "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` + finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` + fi +} + +# func_win32_libid arg +# return the library type of file 'arg' +# +# Need a lot of goo to handle *both* DLLs and import libs +# Has to be a shell function in order to 'eat' the argument +# that is supplied when $file_magic_command is called. +func_win32_libid () +{ + $opt_debug + win32_libid_type="unknown" + win32_fileres=`file -L $1 2>/dev/null` + case $win32_fileres in + *ar\ archive\ import\ library*) # definitely import + win32_libid_type="x86 archive import" + ;; + *ar\ archive*) # could be an import, or static + if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | + $EGREP 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then + win32_nmres=`eval $NM -f posix -A $1 | + $SED -n -e ' + 1,100{ + / I /{ + s,.*,import, + p + q + } + }'` + case $win32_nmres in + import*) win32_libid_type="x86 archive import";; + *) win32_libid_type="x86 archive static";; + esac + fi + ;; + *DLL*) + win32_libid_type="x86 DLL" + ;; + *executable*) # but shell scripts are "executable" too... + case $win32_fileres in + *MS\ Windows\ PE\ Intel*) + win32_libid_type="x86 DLL" + ;; + esac + ;; + esac + $ECHO "$win32_libid_type" +} + + + +# func_extract_an_archive dir oldlib +func_extract_an_archive () +{ + $opt_debug + f_ex_an_ar_dir="$1"; shift + f_ex_an_ar_oldlib="$1" + func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" 'exit $?' + if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then + : + else + func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" + fi +} + + +# func_extract_archives gentop oldlib ... +func_extract_archives () +{ + $opt_debug + my_gentop="$1"; shift + my_oldlibs=${1+"$@"} + my_oldobjs="" + my_xlib="" + my_xabs="" + my_xdir="" + + for my_xlib in $my_oldlibs; do + # Extract the objects. + case $my_xlib in + [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; + *) my_xabs=`pwd`"/$my_xlib" ;; + esac + func_basename "$my_xlib" + my_xlib="$func_basename_result" + my_xlib_u=$my_xlib + while :; do + case " $extracted_archives " in + *" $my_xlib_u "*) + func_arith $extracted_serial + 1 + extracted_serial=$func_arith_result + my_xlib_u=lt$extracted_serial-$my_xlib ;; + *) break ;; + esac + done + extracted_archives="$extracted_archives $my_xlib_u" + my_xdir="$my_gentop/$my_xlib_u" + + func_mkdir_p "$my_xdir" + + case $host in + *-darwin*) + func_verbose "Extracting $my_xabs" + # Do not bother doing anything if just a dry run + $opt_dry_run || { + darwin_orig_dir=`pwd` + cd $my_xdir || exit $? + darwin_archive=$my_xabs + darwin_curdir=`pwd` + darwin_base_archive=`basename "$darwin_archive"` + darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` + if test -n "$darwin_arches"; then + darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` + darwin_arch= + func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" + for darwin_arch in $darwin_arches ; do + func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" + $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" + cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" + func_extract_an_archive "`pwd`" "${darwin_base_archive}" + cd "$darwin_curdir" + $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" + done # $darwin_arches + ## Okay now we've a bunch of thin objects, gotta fatten them up :) + darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` + darwin_file= + darwin_files= + for darwin_file in $darwin_filelist; do + darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP` + $LIPO -create -output "$darwin_file" $darwin_files + done # $darwin_filelist + $RM -rf unfat-$$ + cd "$darwin_orig_dir" + else + cd $darwin_orig_dir + func_extract_an_archive "$my_xdir" "$my_xabs" + fi # $darwin_arches + } # !$opt_dry_run + ;; + *) + func_extract_an_archive "$my_xdir" "$my_xabs" + ;; + esac + my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` + done + + func_extract_archives_result="$my_oldobjs" +} + + + +# func_emit_wrapper_part1 [arg=no] +# +# Emit the first part of a libtool wrapper script on stdout. +# For more information, see the description associated with +# func_emit_wrapper(), below. +func_emit_wrapper_part1 () +{ + func_emit_wrapper_part1_arg1=no + if test -n "$1" ; then + func_emit_wrapper_part1_arg1=$1 + fi + + $ECHO "\ +#! $SHELL + +# $output - temporary wrapper script for $objdir/$outputname +# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION +# +# The $output program cannot be directly executed until all the libtool +# libraries that it depends on are installed. +# +# This wrapper script should never be moved out of the build directory. +# If it is, it will not operate correctly. + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed='${SED} -e 1s/^X//' +sed_quote_subst='$sed_quote_subst' + +# Be Bourne compatible +if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac +fi +BIN_SH=xpg4; export BIN_SH # for Tru64 +DUALCASE=1; export DUALCASE # for MKS sh + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +relink_command=\"$relink_command\" + +# This environment variable determines our operation mode. +if test \"\$libtool_install_magic\" = \"$magic\"; then + # install mode needs the following variables: + generated_by_libtool_version='$macro_version' + notinst_deplibs='$notinst_deplibs' +else + # When we are sourced in execute mode, \$file and \$ECHO are already set. + if test \"\$libtool_execute_magic\" != \"$magic\"; then + ECHO=\"$qecho\" + file=\"\$0\" + # Make sure echo works. + if test \"X\$1\" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift + elif test \"X\`{ \$ECHO '\t'; } 2>/dev/null\`\" = 'X\t'; then + # Yippee, \$ECHO works! + : + else + # Restart under the correct shell, and then maybe \$ECHO will work. + exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"} + fi + fi\ +" + $ECHO "\ + + # Find the directory that this script lives in. + thisdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\` + test \"x\$thisdir\" = \"x\$file\" && thisdir=. + + # Follow symbolic links until we get to the real thisdir. + file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\` + while test -n \"\$file\"; do + destdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\` + + # If there was a directory component, then change thisdir. + if test \"x\$destdir\" != \"x\$file\"; then + case \"\$destdir\" in + [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; + *) thisdir=\"\$thisdir/\$destdir\" ;; + esac + fi + + file=\`\$ECHO \"X\$file\" | \$Xsed -e 's%^.*/%%'\` + file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\` + done +" +} +# end: func_emit_wrapper_part1 + +# func_emit_wrapper_part2 [arg=no] +# +# Emit the second part of a libtool wrapper script on stdout. +# For more information, see the description associated with +# func_emit_wrapper(), below. +func_emit_wrapper_part2 () +{ + func_emit_wrapper_part2_arg1=no + if test -n "$1" ; then + func_emit_wrapper_part2_arg1=$1 + fi + + $ECHO "\ + + # Usually 'no', except on cygwin/mingw when embedded into + # the cwrapper. + WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_part2_arg1 + if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then + # special case for '.' + if test \"\$thisdir\" = \".\"; then + thisdir=\`pwd\` + fi + # remove .libs from thisdir + case \"\$thisdir\" in + *[\\\\/]$objdir ) thisdir=\`\$ECHO \"X\$thisdir\" | \$Xsed -e 's%[\\\\/][^\\\\/]*$%%'\` ;; + $objdir ) thisdir=. ;; + esac + fi + + # Try to get the absolute directory name. + absdir=\`cd \"\$thisdir\" && pwd\` + test -n \"\$absdir\" && thisdir=\"\$absdir\" +" + + if test "$fast_install" = yes; then + $ECHO "\ + program=lt-'$outputname'$exeext + progdir=\"\$thisdir/$objdir\" + + if test ! -f \"\$progdir/\$program\" || + { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ + test \"X\$file\" != \"X\$progdir/\$program\"; }; then + + file=\"\$\$-\$program\" + + if test ! -d \"\$progdir\"; then + $MKDIR \"\$progdir\" + else + $RM \"\$progdir/\$file\" + fi" + + $ECHO "\ + + # relink executable if necessary + if test -n \"\$relink_command\"; then + if relink_command_output=\`eval \$relink_command 2>&1\`; then : + else + $ECHO \"\$relink_command_output\" >&2 + $RM \"\$progdir/\$file\" + exit 1 + fi + fi + + $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || + { $RM \"\$progdir/\$program\"; + $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } + $RM \"\$progdir/\$file\" + fi" + else + $ECHO "\ + program='$outputname' + progdir=\"\$thisdir/$objdir\" +" + fi + + $ECHO "\ + + if test -f \"\$progdir/\$program\"; then" + + # Export our shlibpath_var if we have one. + if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then + $ECHO "\ + # Add our own library path to $shlibpath_var + $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" + + # Some systems cannot cope with colon-terminated $shlibpath_var + # The second colon is a workaround for a bug in BeOS R4 sed + $shlibpath_var=\`\$ECHO \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\` + + export $shlibpath_var +" + fi + + # fixup the dll searchpath if we need to. + if test -n "$dllsearchpath"; then + $ECHO "\ + # Add the dll search path components to the executable PATH + PATH=$dllsearchpath:\$PATH +" + fi + + $ECHO "\ + if test \"\$libtool_execute_magic\" != \"$magic\"; then + # Run the actual program with our arguments. +" + case $host in + # Backslashes separate directories on plain windows + *-*-mingw | *-*-os2* | *-cegcc*) + $ECHO "\ + exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} +" + ;; + + *) + $ECHO "\ + exec \"\$progdir/\$program\" \${1+\"\$@\"} +" + ;; + esac + $ECHO "\ + \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 + exit 1 + fi + else + # The program doesn't exist. + \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 + \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 + $ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 + exit 1 + fi +fi\ +" +} +# end: func_emit_wrapper_part2 + + +# func_emit_wrapper [arg=no] +# +# Emit a libtool wrapper script on stdout. +# Don't directly open a file because we may want to +# incorporate the script contents within a cygwin/mingw +# wrapper executable. Must ONLY be called from within +# func_mode_link because it depends on a number of variables +# set therein. +# +# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR +# variable will take. If 'yes', then the emitted script +# will assume that the directory in which it is stored is +# the $objdir directory. This is a cygwin/mingw-specific +# behavior. +func_emit_wrapper () +{ + func_emit_wrapper_arg1=no + if test -n "$1" ; then + func_emit_wrapper_arg1=$1 + fi + + # split this up so that func_emit_cwrapperexe_src + # can call each part independently. + func_emit_wrapper_part1 "${func_emit_wrapper_arg1}" + func_emit_wrapper_part2 "${func_emit_wrapper_arg1}" +} + + +# func_to_host_path arg +# +# Convert paths to host format when used with build tools. +# Intended for use with "native" mingw (where libtool itself +# is running under the msys shell), or in the following cross- +# build environments: +# $build $host +# mingw (msys) mingw [e.g. native] +# cygwin mingw +# *nix + wine mingw +# where wine is equipped with the `winepath' executable. +# In the native mingw case, the (msys) shell automatically +# converts paths for any non-msys applications it launches, +# but that facility isn't available from inside the cwrapper. +# Similar accommodations are necessary for $host mingw and +# $build cygwin. Calling this function does no harm for other +# $host/$build combinations not listed above. +# +# ARG is the path (on $build) that should be converted to +# the proper representation for $host. The result is stored +# in $func_to_host_path_result. +func_to_host_path () +{ + func_to_host_path_result="$1" + if test -n "$1" ; then + case $host in + *mingw* ) + lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' + case $build in + *mingw* ) # actually, msys + # awkward: cmd appends spaces to result + lt_sed_strip_trailing_spaces="s/[ ]*\$//" + func_to_host_path_tmp1=`( cmd //c echo "$1" |\ + $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""` + func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ + $SED -e "$lt_sed_naive_backslashify"` + ;; + *cygwin* ) + func_to_host_path_tmp1=`cygpath -w "$1"` + func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ + $SED -e "$lt_sed_naive_backslashify"` + ;; + * ) + # Unfortunately, winepath does not exit with a non-zero + # error code, so we are forced to check the contents of + # stdout. On the other hand, if the command is not + # found, the shell will set an exit code of 127 and print + # *an error message* to stdout. So we must check for both + # error code of zero AND non-empty stdout, which explains + # the odd construction: + func_to_host_path_tmp1=`winepath -w "$1" 2>/dev/null` + if test "$?" -eq 0 && test -n "${func_to_host_path_tmp1}"; then + func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ + $SED -e "$lt_sed_naive_backslashify"` + else + # Allow warning below. + func_to_host_path_result="" + fi + ;; + esac + if test -z "$func_to_host_path_result" ; then + func_error "Could not determine host path corresponding to" + func_error " '$1'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback: + func_to_host_path_result="$1" + fi + ;; + esac + fi +} +# end: func_to_host_path + +# func_to_host_pathlist arg +# +# Convert pathlists to host format when used with build tools. +# See func_to_host_path(), above. This function supports the +# following $build/$host combinations (but does no harm for +# combinations not listed here): +# $build $host +# mingw (msys) mingw [e.g. native] +# cygwin mingw +# *nix + wine mingw +# +# Path separators are also converted from $build format to +# $host format. If ARG begins or ends with a path separator +# character, it is preserved (but converted to $host format) +# on output. +# +# ARG is a pathlist (on $build) that should be converted to +# the proper representation on $host. The result is stored +# in $func_to_host_pathlist_result. +func_to_host_pathlist () +{ + func_to_host_pathlist_result="$1" + if test -n "$1" ; then + case $host in + *mingw* ) + lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' + # Remove leading and trailing path separator characters from + # ARG. msys behavior is inconsistent here, cygpath turns them + # into '.;' and ';.', and winepath ignores them completely. + func_to_host_pathlist_tmp2="$1" + # Once set for this call, this variable should not be + # reassigned. It is used in tha fallback case. + func_to_host_pathlist_tmp1=`echo "$func_to_host_pathlist_tmp2" |\ + $SED -e 's|^:*||' -e 's|:*$||'` + case $build in + *mingw* ) # Actually, msys. + # Awkward: cmd appends spaces to result. + lt_sed_strip_trailing_spaces="s/[ ]*\$//" + func_to_host_pathlist_tmp2=`( cmd //c echo "$func_to_host_pathlist_tmp1" |\ + $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""` + func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\ + $SED -e "$lt_sed_naive_backslashify"` + ;; + *cygwin* ) + func_to_host_pathlist_tmp2=`cygpath -w -p "$func_to_host_pathlist_tmp1"` + func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\ + $SED -e "$lt_sed_naive_backslashify"` + ;; + * ) + # unfortunately, winepath doesn't convert pathlists + func_to_host_pathlist_result="" + func_to_host_pathlist_oldIFS=$IFS + IFS=: + for func_to_host_pathlist_f in $func_to_host_pathlist_tmp1 ; do + IFS=$func_to_host_pathlist_oldIFS + if test -n "$func_to_host_pathlist_f" ; then + func_to_host_path "$func_to_host_pathlist_f" + if test -n "$func_to_host_path_result" ; then + if test -z "$func_to_host_pathlist_result" ; then + func_to_host_pathlist_result="$func_to_host_path_result" + else + func_to_host_pathlist_result="$func_to_host_pathlist_result;$func_to_host_path_result" + fi + fi + fi + IFS=: + done + IFS=$func_to_host_pathlist_oldIFS + ;; + esac + if test -z "$func_to_host_pathlist_result" ; then + func_error "Could not determine the host path(s) corresponding to" + func_error " '$1'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback. This may break if $1 contains DOS-style drive + # specifications. The fix is not to complicate the expression + # below, but for the user to provide a working wine installation + # with winepath so that path translation in the cross-to-mingw + # case works properly. + lt_replace_pathsep_nix_to_dos="s|:|;|g" + func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp1" |\ + $SED -e "$lt_replace_pathsep_nix_to_dos"` + fi + # Now, add the leading and trailing path separators back + case "$1" in + :* ) func_to_host_pathlist_result=";$func_to_host_pathlist_result" + ;; + esac + case "$1" in + *: ) func_to_host_pathlist_result="$func_to_host_pathlist_result;" + ;; + esac + ;; + esac + fi +} +# end: func_to_host_pathlist + +# func_emit_cwrapperexe_src +# emit the source code for a wrapper executable on stdout +# Must ONLY be called from within func_mode_link because +# it depends on a number of variable set therein. +func_emit_cwrapperexe_src () +{ + cat < +#include +#ifdef _MSC_VER +# include +# include +# include +# define setmode _setmode +#else +# include +# include +# ifdef __CYGWIN__ +# include +# define HAVE_SETENV +# ifdef __STRICT_ANSI__ +char *realpath (const char *, char *); +int putenv (char *); +int setenv (const char *, const char *, int); +# endif +# endif +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(PATH_MAX) +# define LT_PATHMAX PATH_MAX +#elif defined(MAXPATHLEN) +# define LT_PATHMAX MAXPATHLEN +#else +# define LT_PATHMAX 1024 +#endif + +#ifndef S_IXOTH +# define S_IXOTH 0 +#endif +#ifndef S_IXGRP +# define S_IXGRP 0 +#endif + +#ifdef _MSC_VER +# define S_IXUSR _S_IEXEC +# define stat _stat +# ifndef _INTPTR_T_DEFINED +# define intptr_t int +# endif +#endif + +#ifndef DIR_SEPARATOR +# define DIR_SEPARATOR '/' +# define PATH_SEPARATOR ':' +#endif + +#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ + defined (__OS2__) +# define HAVE_DOS_BASED_FILE_SYSTEM +# define FOPEN_WB "wb" +# ifndef DIR_SEPARATOR_2 +# define DIR_SEPARATOR_2 '\\' +# endif +# ifndef PATH_SEPARATOR_2 +# define PATH_SEPARATOR_2 ';' +# endif +#endif + +#ifndef DIR_SEPARATOR_2 +# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) +#else /* DIR_SEPARATOR_2 */ +# define IS_DIR_SEPARATOR(ch) \ + (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) +#endif /* DIR_SEPARATOR_2 */ + +#ifndef PATH_SEPARATOR_2 +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) +#else /* PATH_SEPARATOR_2 */ +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) +#endif /* PATH_SEPARATOR_2 */ + +#ifdef __CYGWIN__ +# define FOPEN_WB "wb" +#endif + +#ifndef FOPEN_WB +# define FOPEN_WB "w" +#endif +#ifndef _O_BINARY +# define _O_BINARY 0 +#endif + +#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) +#define XFREE(stale) do { \ + if (stale) { free ((void *) stale); stale = 0; } \ +} while (0) + +#undef LTWRAPPER_DEBUGPRINTF +#if defined DEBUGWRAPPER +# define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args +static void +ltwrapper_debugprintf (const char *fmt, ...) +{ + va_list args; + va_start (args, fmt); + (void) vfprintf (stderr, fmt, args); + va_end (args); +} +#else +# define LTWRAPPER_DEBUGPRINTF(args) +#endif + +const char *program_name = NULL; + +void *xmalloc (size_t num); +char *xstrdup (const char *string); +const char *base_name (const char *name); +char *find_executable (const char *wrapper); +char *chase_symlinks (const char *pathspec); +int make_executable (const char *path); +int check_executable (const char *path); +char *strendzap (char *str, const char *pat); +void lt_fatal (const char *message, ...); +void lt_setenv (const char *name, const char *value); +char *lt_extend_str (const char *orig_value, const char *add, int to_end); +void lt_opt_process_env_set (const char *arg); +void lt_opt_process_env_prepend (const char *arg); +void lt_opt_process_env_append (const char *arg); +int lt_split_name_value (const char *arg, char** name, char** value); +void lt_update_exe_path (const char *name, const char *value); +void lt_update_lib_path (const char *name, const char *value); + +static const char *script_text_part1 = +EOF + + func_emit_wrapper_part1 yes | + $SED -e 's/\([\\"]\)/\\\1/g' \ + -e 's/^/ "/' -e 's/$/\\n"/' + echo ";" + cat <"))); + for (i = 0; i < newargc; i++) + { + LTWRAPPER_DEBUGPRINTF (("(main) newargz[%d] : %s\n", i, (newargz[i] ? newargz[i] : ""))); + } + +EOF + + case $host_os in + mingw*) + cat <<"EOF" + /* execv doesn't actually work on mingw as expected on unix */ + rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz); + if (rval == -1) + { + /* failed to start process */ + LTWRAPPER_DEBUGPRINTF (("(main) failed to launch target \"%s\": errno = %d\n", lt_argv_zero, errno)); + return 127; + } + return rval; +EOF + ;; + *) + cat <<"EOF" + execv (lt_argv_zero, newargz); + return rval; /* =127, but avoids unused variable warning */ +EOF + ;; + esac + + cat <<"EOF" +} + +void * +xmalloc (size_t num) +{ + void *p = (void *) malloc (num); + if (!p) + lt_fatal ("Memory exhausted"); + + return p; +} + +char * +xstrdup (const char *string) +{ + return string ? strcpy ((char *) xmalloc (strlen (string) + 1), + string) : NULL; +} + +const char * +base_name (const char *name) +{ + const char *base; + +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + /* Skip over the disk name in MSDOS pathnames. */ + if (isalpha ((unsigned char) name[0]) && name[1] == ':') + name += 2; +#endif + + for (base = name; *name; name++) + if (IS_DIR_SEPARATOR (*name)) + base = name + 1; + return base; +} + +int +check_executable (const char *path) +{ + struct stat st; + + LTWRAPPER_DEBUGPRINTF (("(check_executable) : %s\n", + path ? (*path ? path : "EMPTY!") : "NULL!")); + if ((!path) || (!*path)) + return 0; + + if ((stat (path, &st) >= 0) + && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) + return 1; + else + return 0; +} + +int +make_executable (const char *path) +{ + int rval = 0; + struct stat st; + + LTWRAPPER_DEBUGPRINTF (("(make_executable) : %s\n", + path ? (*path ? path : "EMPTY!") : "NULL!")); + if ((!path) || (!*path)) + return 0; + + if (stat (path, &st) >= 0) + { + rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); + } + return rval; +} + +/* Searches for the full path of the wrapper. Returns + newly allocated full path name if found, NULL otherwise + Does not chase symlinks, even on platforms that support them. +*/ +char * +find_executable (const char *wrapper) +{ + int has_slash = 0; + const char *p; + const char *p_next; + /* static buffer for getcwd */ + char tmp[LT_PATHMAX + 1]; + int tmp_len; + char *concat_name; + + LTWRAPPER_DEBUGPRINTF (("(find_executable) : %s\n", + wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!")); + + if ((wrapper == NULL) || (*wrapper == '\0')) + return NULL; + + /* Absolute path? */ +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + else + { +#endif + if (IS_DIR_SEPARATOR (wrapper[0])) + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + } +#endif + + for (p = wrapper; *p; p++) + if (*p == '/') + { + has_slash = 1; + break; + } + if (!has_slash) + { + /* no slashes; search PATH */ + const char *path = getenv ("PATH"); + if (path != NULL) + { + for (p = path; *p; p = p_next) + { + const char *q; + size_t p_len; + for (q = p; *q; q++) + if (IS_PATH_SEPARATOR (*q)) + break; + p_len = q - p; + p_next = (*q == '\0' ? q : q + 1); + if (p_len == 0) + { + /* empty path: current directory */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal ("getcwd failed"); + tmp_len = strlen (tmp); + concat_name = + XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + } + else + { + concat_name = + XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, p, p_len); + concat_name[p_len] = '/'; + strcpy (concat_name + p_len + 1, wrapper); + } + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + } + /* not found in PATH; assume curdir */ + } + /* Relative path | not found in path: prepend cwd */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal ("getcwd failed"); + tmp_len = strlen (tmp); + concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + return NULL; +} + +char * +chase_symlinks (const char *pathspec) +{ +#ifndef S_ISLNK + return xstrdup (pathspec); +#else + char buf[LT_PATHMAX]; + struct stat s; + char *tmp_pathspec = xstrdup (pathspec); + char *p; + int has_symlinks = 0; + while (strlen (tmp_pathspec) && !has_symlinks) + { + LTWRAPPER_DEBUGPRINTF (("checking path component for symlinks: %s\n", + tmp_pathspec)); + if (lstat (tmp_pathspec, &s) == 0) + { + if (S_ISLNK (s.st_mode) != 0) + { + has_symlinks = 1; + break; + } + + /* search backwards for last DIR_SEPARATOR */ + p = tmp_pathspec + strlen (tmp_pathspec) - 1; + while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + p--; + if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + { + /* no more DIR_SEPARATORS left */ + break; + } + *p = '\0'; + } + else + { + char *errstr = strerror (errno); + lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr); + } + } + XFREE (tmp_pathspec); + + if (!has_symlinks) + { + return xstrdup (pathspec); + } + + tmp_pathspec = realpath (pathspec, buf); + if (tmp_pathspec == 0) + { + lt_fatal ("Could not follow symlinks for %s", pathspec); + } + return xstrdup (tmp_pathspec); +#endif +} + +char * +strendzap (char *str, const char *pat) +{ + size_t len, patlen; + + assert (str != NULL); + assert (pat != NULL); + + len = strlen (str); + patlen = strlen (pat); + + if (patlen <= len) + { + str += len - patlen; + if (strcmp (str, pat) == 0) + *str = '\0'; + } + return str; +} + +static void +lt_error_core (int exit_status, const char *mode, + const char *message, va_list ap) +{ + fprintf (stderr, "%s: %s: ", program_name, mode); + vfprintf (stderr, message, ap); + fprintf (stderr, ".\n"); + + if (exit_status >= 0) + exit (exit_status); +} + +void +lt_fatal (const char *message, ...) +{ + va_list ap; + va_start (ap, message); + lt_error_core (EXIT_FAILURE, "FATAL", message, ap); + va_end (ap); +} + +void +lt_setenv (const char *name, const char *value) +{ + LTWRAPPER_DEBUGPRINTF (("(lt_setenv) setting '%s' to '%s'\n", + (name ? name : ""), + (value ? value : ""))); + { +#ifdef HAVE_SETENV + /* always make a copy, for consistency with !HAVE_SETENV */ + char *str = xstrdup (value); + setenv (name, str, 1); +#else + int len = strlen (name) + 1 + strlen (value) + 1; + char *str = XMALLOC (char, len); + sprintf (str, "%s=%s", name, value); + if (putenv (str) != EXIT_SUCCESS) + { + XFREE (str); + } +#endif + } +} + +char * +lt_extend_str (const char *orig_value, const char *add, int to_end) +{ + char *new_value; + if (orig_value && *orig_value) + { + int orig_value_len = strlen (orig_value); + int add_len = strlen (add); + new_value = XMALLOC (char, add_len + orig_value_len + 1); + if (to_end) + { + strcpy (new_value, orig_value); + strcpy (new_value + orig_value_len, add); + } + else + { + strcpy (new_value, add); + strcpy (new_value + add_len, orig_value); + } + } + else + { + new_value = xstrdup (add); + } + return new_value; +} + +int +lt_split_name_value (const char *arg, char** name, char** value) +{ + const char *p; + int len; + if (!arg || !*arg) + return 1; + + p = strchr (arg, (int)'='); + + if (!p) + return 1; + + *value = xstrdup (++p); + + len = strlen (arg) - strlen (*value); + *name = XMALLOC (char, len); + strncpy (*name, arg, len-1); + (*name)[len - 1] = '\0'; + + return 0; +} + +void +lt_opt_process_env_set (const char *arg) +{ + char *name = NULL; + char *value = NULL; + + if (lt_split_name_value (arg, &name, &value) != 0) + { + XFREE (name); + XFREE (value); + lt_fatal ("bad argument for %s: '%s'", env_set_opt, arg); + } + + lt_setenv (name, value); + XFREE (name); + XFREE (value); +} + +void +lt_opt_process_env_prepend (const char *arg) +{ + char *name = NULL; + char *value = NULL; + char *new_value = NULL; + + if (lt_split_name_value (arg, &name, &value) != 0) + { + XFREE (name); + XFREE (value); + lt_fatal ("bad argument for %s: '%s'", env_prepend_opt, arg); + } + + new_value = lt_extend_str (getenv (name), value, 0); + lt_setenv (name, new_value); + XFREE (new_value); + XFREE (name); + XFREE (value); +} + +void +lt_opt_process_env_append (const char *arg) +{ + char *name = NULL; + char *value = NULL; + char *new_value = NULL; + + if (lt_split_name_value (arg, &name, &value) != 0) + { + XFREE (name); + XFREE (value); + lt_fatal ("bad argument for %s: '%s'", env_append_opt, arg); + } + + new_value = lt_extend_str (getenv (name), value, 1); + lt_setenv (name, new_value); + XFREE (new_value); + XFREE (name); + XFREE (value); +} + +void +lt_update_exe_path (const char *name, const char *value) +{ + LTWRAPPER_DEBUGPRINTF (("(lt_update_exe_path) modifying '%s' by prepending '%s'\n", + (name ? name : ""), + (value ? value : ""))); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + /* some systems can't cope with a ':'-terminated path #' */ + int len = strlen (new_value); + while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) + { + new_value[len-1] = '\0'; + } + lt_setenv (name, new_value); + XFREE (new_value); + } +} + +void +lt_update_lib_path (const char *name, const char *value) +{ + LTWRAPPER_DEBUGPRINTF (("(lt_update_lib_path) modifying '%s' by prepending '%s'\n", + (name ? name : ""), + (value ? value : ""))); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + lt_setenv (name, new_value); + XFREE (new_value); + } +} + + +EOF +} +# end: func_emit_cwrapperexe_src + +# func_mode_link arg... +func_mode_link () +{ + $opt_debug + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + # It is impossible to link a dll without this setting, and + # we shouldn't force the makefile maintainer to figure out + # which system we are compiling for in order to pass an extra + # flag for every libtool invocation. + # allow_undefined=no + + # FIXME: Unfortunately, there are problems with the above when trying + # to make a dll which has undefined symbols, in which case not + # even a static library is built. For now, we need to specify + # -no-undefined on the libtool link line when we can be certain + # that all symbols are satisfied, otherwise we get a static library. + allow_undefined=yes + ;; + *) + allow_undefined=yes + ;; + esac + libtool_args=$nonopt + base_compile="$nonopt $@" + compile_command=$nonopt + finalize_command=$nonopt + + compile_rpath= + finalize_rpath= + compile_shlibpath= + finalize_shlibpath= + convenience= + old_convenience= + deplibs= + old_deplibs= + compiler_flags= + linker_flags= + dllsearchpath= + lib_search_path=`pwd` + inst_prefix_dir= + new_inherited_linker_flags= + + avoid_version=no + dlfiles= + dlprefiles= + dlself=no + export_dynamic=no + export_symbols= + export_symbols_regex= + generated= + libobjs= + ltlibs= + module=no + no_install=no + objs= + non_pic_objects= + precious_files_regex= + prefer_static_libs=no + preload=no + prev= + prevarg= + release= + rpath= + xrpath= + perm_rpath= + temp_rpath= + thread_safe=no + vinfo= + vinfo_number=no + weak_libs= + single_module="${wl}-single_module" + func_infer_tag $base_compile + + # We need to know -static, to get the right output filenames. + for arg + do + case $arg in + -shared) + test "$build_libtool_libs" != yes && \ + func_fatal_configuration "can not build a shared library" + build_old_libs=no + break + ;; + -all-static | -static | -static-libtool-libs) + case $arg in + -all-static) + if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then + func_warning "complete static linking is impossible in this configuration" + fi + if test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + -static) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=built + ;; + -static-libtool-libs) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + esac + build_libtool_libs=no + build_old_libs=yes + break + ;; + esac + done + + # See if our shared archives depend on static archives. + test -n "$old_archive_from_new_cmds" && build_old_libs=yes + + # Go through the arguments, transforming them on the way. + while test "$#" -gt 0; do + arg="$1" + shift + func_quote_for_eval "$arg" + qarg=$func_quote_for_eval_unquoted_result + func_append libtool_args " $func_quote_for_eval_result" + + # If the previous option needs an argument, assign it. + if test -n "$prev"; then + case $prev in + output) + func_append compile_command " @OUTPUT@" + func_append finalize_command " @OUTPUT@" + ;; + esac + + case $prev in + dlfiles|dlprefiles) + if test "$preload" = no; then + # Add the symbol object into the linking commands. + func_append compile_command " @SYMFILE@" + func_append finalize_command " @SYMFILE@" + preload=yes + fi + case $arg in + *.la | *.lo) ;; # We handle these cases below. + force) + if test "$dlself" = no; then + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + self) + if test "$prev" = dlprefiles; then + dlself=yes + elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then + dlself=yes + else + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + *) + if test "$prev" = dlfiles; then + dlfiles="$dlfiles $arg" + else + dlprefiles="$dlprefiles $arg" + fi + prev= + continue + ;; + esac + ;; + expsyms) + export_symbols="$arg" + test -f "$arg" \ + || func_fatal_error "symbol file \`$arg' does not exist" + prev= + continue + ;; + expsyms_regex) + export_symbols_regex="$arg" + prev= + continue + ;; + framework) + case $host in + *-*-darwin*) + case "$deplibs " in + *" $qarg.ltframework "*) ;; + *) deplibs="$deplibs $qarg.ltframework" # this is fixed later + ;; + esac + ;; + esac + prev= + continue + ;; + inst_prefix) + inst_prefix_dir="$arg" + prev= + continue + ;; + objectlist) + if test -f "$arg"; then + save_arg=$arg + moreargs= + for fil in `cat "$save_arg"` + do +# moreargs="$moreargs $fil" + arg=$fil + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test "$pic_object" = none && + test "$non_pic_object" = none; then + func_fatal_error "cannot find name of object for \`$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + dlfiles="$dlfiles $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + dlprefiles="$dlprefiles $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object="$pic_object" + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "\`$arg' is not a valid libtool object" + fi + fi + done + else + func_fatal_error "link input file \`$arg' does not exist" + fi + arg=$save_arg + prev= + continue + ;; + precious_regex) + precious_files_regex="$arg" + prev= + continue + ;; + release) + release="-$arg" + prev= + continue + ;; + rpath | xrpath) + # We need an absolute path. + case $arg in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + if test "$prev" = rpath; then + case "$rpath " in + *" $arg "*) ;; + *) rpath="$rpath $arg" ;; + esac + else + case "$xrpath " in + *" $arg "*) ;; + *) xrpath="$xrpath $arg" ;; + esac + fi + prev= + continue + ;; + shrext) + shrext_cmds="$arg" + prev= + continue + ;; + weak) + weak_libs="$weak_libs $arg" + prev= + continue + ;; + xcclinker) + linker_flags="$linker_flags $qarg" + compiler_flags="$compiler_flags $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xcompiler) + compiler_flags="$compiler_flags $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xlinker) + linker_flags="$linker_flags $qarg" + compiler_flags="$compiler_flags $wl$qarg" + prev= + func_append compile_command " $wl$qarg" + func_append finalize_command " $wl$qarg" + continue + ;; + *) + eval "$prev=\"\$arg\"" + prev= + continue + ;; + esac + fi # test -n "$prev" + + prevarg="$arg" + + case $arg in + -all-static) + if test -n "$link_static_flag"; then + # See comment for -static flag below, for more details. + func_append compile_command " $link_static_flag" + func_append finalize_command " $link_static_flag" + fi + continue + ;; + + -allow-undefined) + # FIXME: remove this flag sometime in the future. + func_fatal_error "\`-allow-undefined' must not be used because it is the default" + ;; + + -avoid-version) + avoid_version=yes + continue + ;; + + -dlopen) + prev=dlfiles + continue + ;; + + -dlpreopen) + prev=dlprefiles + continue + ;; + + -export-dynamic) + export_dynamic=yes + continue + ;; + + -export-symbols | -export-symbols-regex) + if test -n "$export_symbols" || test -n "$export_symbols_regex"; then + func_fatal_error "more than one -exported-symbols argument is not allowed" + fi + if test "X$arg" = "X-export-symbols"; then + prev=expsyms + else + prev=expsyms_regex + fi + continue + ;; + + -framework) + prev=framework + continue + ;; + + -inst-prefix-dir) + prev=inst_prefix + continue + ;; + + # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* + # so, if we see these flags be careful not to treat them like -L + -L[A-Z][A-Z]*:*) + case $with_gcc/$host in + no/*-*-irix* | /*-*-irix*) + func_append compile_command " $arg" + func_append finalize_command " $arg" + ;; + esac + continue + ;; + + -L*) + func_stripname '-L' '' "$arg" + dir=$func_stripname_result + if test -z "$dir"; then + if test "$#" -gt 0; then + func_fatal_error "require no space between \`-L' and \`$1'" + else + func_fatal_error "need path for \`-L' option" + fi + fi + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + absdir=`cd "$dir" && pwd` + test -z "$absdir" && \ + func_fatal_error "cannot determine absolute directory name of \`$dir'" + dir="$absdir" + ;; + esac + case "$deplibs " in + *" -L$dir "*) ;; + *) + deplibs="$deplibs -L$dir" + lib_search_path="$lib_search_path $dir" + ;; + esac + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`$ECHO "X$dir" | $Xsed -e 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$dir:"*) ;; + ::) dllsearchpath=$dir;; + *) dllsearchpath="$dllsearchpath:$dir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) dllsearchpath="$dllsearchpath:$testbindir";; + esac + ;; + esac + continue + ;; + + -l*) + if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc*) + # These systems don't actually have a C or math library (as such) + continue + ;; + *-*-os2*) + # These systems don't actually have a C library (as such) + test "X$arg" = "X-lc" && continue + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc due to us having libc/libc_r. + test "X$arg" = "X-lc" && continue + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C and math libraries are in the System framework + deplibs="$deplibs System.ltframework" + continue + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + test "X$arg" = "X-lc" && continue + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + test "X$arg" = "X-lc" && continue + ;; + esac + elif test "X$arg" = "X-lc_r"; then + case $host in + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc_r directly, use -pthread flag. + continue + ;; + esac + fi + deplibs="$deplibs $arg" + continue + ;; + + -module) + module=yes + continue + ;; + + # Tru64 UNIX uses -model [arg] to determine the layout of C++ + # classes, name mangling, and exception handling. + # Darwin uses the -arch flag to determine output architecture. + -model|-arch|-isysroot) + compiler_flags="$compiler_flags $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + prev=xcompiler + continue + ;; + + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) + compiler_flags="$compiler_flags $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + case "$new_inherited_linker_flags " in + *" $arg "*) ;; + * ) new_inherited_linker_flags="$new_inherited_linker_flags $arg" ;; + esac + continue + ;; + + -multi_module) + single_module="${wl}-multi_module" + continue + ;; + + -no-fast-install) + fast_install=no + continue + ;; + + -no-install) + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) + # The PATH hackery in wrapper scripts is required on Windows + # and Darwin in order for the loader to find any dlls it needs. + func_warning "\`-no-install' is ignored for $host" + func_warning "assuming \`-no-fast-install' instead" + fast_install=no + ;; + *) no_install=yes ;; + esac + continue + ;; + + -no-undefined) + allow_undefined=no + continue + ;; + + -objectlist) + prev=objectlist + continue + ;; + + -o) prev=output ;; + + -precious-files-regex) + prev=precious_regex + continue + ;; + + -release) + prev=release + continue + ;; + + -rpath) + prev=rpath + continue + ;; + + -R) + prev=xrpath + continue + ;; + + -R*) + func_stripname '-R' '' "$arg" + dir=$func_stripname_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + case "$xrpath " in + *" $dir "*) ;; + *) xrpath="$xrpath $dir" ;; + esac + continue + ;; + + -shared) + # The effects of -shared are defined in a previous loop. + continue + ;; + + -shrext) + prev=shrext + continue + ;; + + -static | -static-libtool-libs) + # The effects of -static are defined in a previous loop. + # We used to do the same as -all-static on platforms that + # didn't have a PIC flag, but the assumption that the effects + # would be equivalent was wrong. It would break on at least + # Digital Unix and AIX. + continue + ;; + + -thread-safe) + thread_safe=yes + continue + ;; + + -version-info) + prev=vinfo + continue + ;; + + -version-number) + prev=vinfo + vinfo_number=yes + continue + ;; + + -weak) + prev=weak + continue + ;; + + -Wc,*) + func_stripname '-Wc,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + func_quote_for_eval "$flag" + arg="$arg $wl$func_quote_for_eval_result" + compiler_flags="$compiler_flags $func_quote_for_eval_result" + done + IFS="$save_ifs" + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Wl,*) + func_stripname '-Wl,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + func_quote_for_eval "$flag" + arg="$arg $wl$func_quote_for_eval_result" + compiler_flags="$compiler_flags $wl$func_quote_for_eval_result" + linker_flags="$linker_flags $func_quote_for_eval_result" + done + IFS="$save_ifs" + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Xcompiler) + prev=xcompiler + continue + ;; + + -Xlinker) + prev=xlinker + continue + ;; + + -XCClinker) + prev=xcclinker + continue + ;; + + # -msg_* for osf cc + -msg_*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + + # -64, -mips[0-9] enable 64-bit mode on the SGI compiler + # -r[0-9][0-9]* specifies the processor on the SGI compiler + # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler + # +DA*, +DD* enable 64-bit mode on the HP compiler + # -q* pass through compiler args for the IBM compiler + # -m*, -t[45]*, -txscale* pass through architecture-specific + # compiler args for GCC + # -F/path gives path to uninstalled frameworks, gcc on darwin + # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC + # @file GCC response files + -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ + -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + func_append compile_command " $arg" + func_append finalize_command " $arg" + compiler_flags="$compiler_flags $arg" + continue + ;; + + # Some other compiler flag. + -* | +*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + + *.$objext) + # A standard object. + objs="$objs $arg" + ;; + + *.lo) + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test "$pic_object" = none && + test "$non_pic_object" = none; then + func_fatal_error "cannot find name of object for \`$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + dlfiles="$dlfiles $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + dlprefiles="$dlprefiles $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object="$pic_object" + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "\`$arg' is not a valid libtool object" + fi + fi + ;; + + *.$libext) + # An archive. + deplibs="$deplibs $arg" + old_deplibs="$old_deplibs $arg" + continue + ;; + + *.la) + # A libtool-controlled library. + + if test "$prev" = dlfiles; then + # This library was specified with -dlopen. + dlfiles="$dlfiles $arg" + prev= + elif test "$prev" = dlprefiles; then + # The library was specified with -dlpreopen. + dlprefiles="$dlprefiles $arg" + prev= + else + deplibs="$deplibs $arg" + fi + continue + ;; + + # Some other compiler argument. + *) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + esac # arg + + # Now actually substitute the argument into the commands. + if test -n "$arg"; then + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + done # argument parsing loop + + test -n "$prev" && \ + func_fatal_help "the \`$prevarg' option requires an argument" + + if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then + eval arg=\"$export_dynamic_flag_spec\" + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + + oldlibs= + # calculate the name of the file, without its directory + func_basename "$output" + outputname="$func_basename_result" + libobjs_save="$libobjs" + + if test -n "$shlibpath_var"; then + # get the directories listed in $shlibpath_var + eval shlib_search_path=\`\$ECHO \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` + else + shlib_search_path= + fi + eval sys_lib_search_path=\"$sys_lib_search_path_spec\" + eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" + + func_dirname "$output" "/" "" + output_objdir="$func_dirname_result$objdir" + # Create the object directory. + func_mkdir_p "$output_objdir" + + # Determine the type of output + case $output in + "") + func_fatal_help "you must specify an output file" + ;; + *.$libext) linkmode=oldlib ;; + *.lo | *.$objext) linkmode=obj ;; + *.la) linkmode=lib ;; + *) linkmode=prog ;; # Anything else should be a program. + esac + + specialdeplibs= + + libs= + # Find all interdependent deplibs by searching for libraries + # that are linked more than once (e.g. -la -lb -la) + for deplib in $deplibs; do + if $opt_duplicate_deps ; then + case "$libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + libs="$libs $deplib" + done + + if test "$linkmode" = lib; then + libs="$predeps $libs $compiler_lib_search_path $postdeps" + + # Compute libraries that are listed more than once in $predeps + # $postdeps and mark them as special (i.e., whose duplicates are + # not to be eliminated). + pre_post_deps= + if $opt_duplicate_compiler_generated_deps; then + for pre_post_dep in $predeps $postdeps; do + case "$pre_post_deps " in + *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; + esac + pre_post_deps="$pre_post_deps $pre_post_dep" + done + fi + pre_post_deps= + fi + + deplibs= + newdependency_libs= + newlib_search_path= + need_relink=no # whether we're linking any uninstalled libtool libraries + notinst_deplibs= # not-installed libtool libraries + notinst_path= # paths that contain not-installed libtool libraries + + case $linkmode in + lib) + passes="conv dlpreopen link" + for file in $dlfiles $dlprefiles; do + case $file in + *.la) ;; + *) + func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" + ;; + esac + done + ;; + prog) + compile_deplibs= + finalize_deplibs= + alldeplibs=no + newdlfiles= + newdlprefiles= + passes="conv scan dlopen dlpreopen link" + ;; + *) passes="conv" + ;; + esac + + for pass in $passes; do + # The preopen pass in lib mode reverses $deplibs; put it back here + # so that -L comes before libs that need it for instance... + if test "$linkmode,$pass" = "lib,link"; then + ## FIXME: Find the place where the list is rebuilt in the wrong + ## order, and fix it there properly + tmp_deplibs= + for deplib in $deplibs; do + tmp_deplibs="$deplib $tmp_deplibs" + done + deplibs="$tmp_deplibs" + fi + + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan"; then + libs="$deplibs" + deplibs= + fi + if test "$linkmode" = prog; then + case $pass in + dlopen) libs="$dlfiles" ;; + dlpreopen) libs="$dlprefiles" ;; + link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; + esac + fi + if test "$linkmode,$pass" = "lib,dlpreopen"; then + # Collect and forward deplibs of preopened libtool libs + for lib in $dlprefiles; do + # Ignore non-libtool-libs + dependency_libs= + case $lib in + *.la) func_source "$lib" ;; + esac + + # Collect preopened libtool deplibs, except any this library + # has declared as weak libs + for deplib in $dependency_libs; do + deplib_base=`$ECHO "X$deplib" | $Xsed -e "$basename"` + case " $weak_libs " in + *" $deplib_base "*) ;; + *) deplibs="$deplibs $deplib" ;; + esac + done + done + libs="$dlprefiles" + fi + if test "$pass" = dlopen; then + # Collect dlpreopened libraries + save_deplibs="$deplibs" + deplibs= + fi + + for deplib in $libs; do + lib= + found=no + case $deplib in + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + compiler_flags="$compiler_flags $deplib" + if test "$linkmode" = lib ; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; + esac + fi + fi + continue + ;; + -l*) + if test "$linkmode" != lib && test "$linkmode" != prog; then + func_warning "\`-l' is ignored for archives/objects" + continue + fi + func_stripname '-l' '' "$deplib" + name=$func_stripname_result + if test "$linkmode" = lib; then + searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" + else + searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" + fi + for searchdir in $searchdirs; do + for search_ext in .la $std_shrext .so .a; do + # Search the libtool library + lib="$searchdir/lib${name}${search_ext}" + if test -f "$lib"; then + if test "$search_ext" = ".la"; then + found=yes + else + found=no + fi + break 2 + fi + done + done + if test "$found" != yes; then + # deplib doesn't seem to be a libtool library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + else # deplib is a libtool library + # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, + # We need to do some special things here, and not later. + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $deplib "*) + if func_lalib_p "$lib"; then + library_names= + old_library= + func_source "$lib" + for l in $old_library $library_names; do + ll="$l" + done + if test "X$ll" = "X$old_library" ; then # only static version available + found=no + func_dirname "$lib" "" "." + ladir="$func_dirname_result" + lib=$ladir/$old_library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + fi + fi + ;; + *) ;; + esac + fi + fi + ;; # -l + *.ltframework) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + if test "$linkmode" = lib ; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; + esac + fi + fi + continue + ;; + -L*) + case $linkmode in + lib) + deplibs="$deplib $deplibs" + test "$pass" = conv && continue + newdependency_libs="$deplib $newdependency_libs" + func_stripname '-L' '' "$deplib" + newlib_search_path="$newlib_search_path $func_stripname_result" + ;; + prog) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + if test "$pass" = scan; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + func_stripname '-L' '' "$deplib" + newlib_search_path="$newlib_search_path $func_stripname_result" + ;; + *) + func_warning "\`-L' is ignored for archives/objects" + ;; + esac # linkmode + continue + ;; # -L + -R*) + if test "$pass" = link; then + func_stripname '-R' '' "$deplib" + dir=$func_stripname_result + # Make sure the xrpath contains only unique directories. + case "$xrpath " in + *" $dir "*) ;; + *) xrpath="$xrpath $dir" ;; + esac + fi + deplibs="$deplib $deplibs" + continue + ;; + *.la) lib="$deplib" ;; + *.$libext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + case $linkmode in + lib) + # Linking convenience modules into shared libraries is allowed, + # but linking other static libraries is non-portable. + case " $dlpreconveniencelibs " in + *" $deplib "*) ;; + *) + valid_a_lib=no + case $deplibs_check_method in + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + if eval "\$ECHO \"X$deplib\"" 2>/dev/null | $Xsed -e 10q \ + | $EGREP "$match_pattern_regex" > /dev/null; then + valid_a_lib=yes + fi + ;; + pass_all) + valid_a_lib=yes + ;; + esac + if test "$valid_a_lib" != yes; then + $ECHO + $ECHO "*** Warning: Trying to link with static lib archive $deplib." + $ECHO "*** I have the capability to make that library automatically link in when" + $ECHO "*** you link to this library. But I can only do this if you have a" + $ECHO "*** shared version of the library, which you do not appear to have" + $ECHO "*** because the file extensions .$libext of this argument makes me believe" + $ECHO "*** that it is just a static archive that I should not use here." + else + $ECHO + $ECHO "*** Warning: Linking the shared library $output against the" + $ECHO "*** static library $deplib is not portable!" + deplibs="$deplib $deplibs" + fi + ;; + esac + continue + ;; + prog) + if test "$pass" != link; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + continue + ;; + esac # linkmode + ;; # *.$libext + *.lo | *.$objext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + elif test "$linkmode" = prog; then + if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then + # If there is no dlopen support or we're linking statically, + # we need to preload. + newdlprefiles="$newdlprefiles $deplib" + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + newdlfiles="$newdlfiles $deplib" + fi + fi + continue + ;; + %DEPLIBS%) + alldeplibs=yes + continue + ;; + esac # case $deplib + + if test "$found" = yes || test -f "$lib"; then : + else + func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" + fi + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$lib" \ + || func_fatal_error "\`$lib' is not a valid libtool archive" + + func_dirname "$lib" "" "." + ladir="$func_dirname_result" + + dlname= + dlopen= + dlpreopen= + libdir= + library_names= + old_library= + inherited_linker_flags= + # If the library was installed with an old release of libtool, + # it will not redefine variables installed, or shouldnotlink + installed=yes + shouldnotlink=no + avoidtemprpath= + + + # Read the .la file + func_source "$lib" + + # Convert "-framework foo" to "foo.ltframework" + if test -n "$inherited_linker_flags"; then + tmp_inherited_linker_flags=`$ECHO "X$inherited_linker_flags" | $Xsed -e 's/-framework \([^ $]*\)/\1.ltframework/g'` + for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do + case " $new_inherited_linker_flags " in + *" $tmp_inherited_linker_flag "*) ;; + *) new_inherited_linker_flags="$new_inherited_linker_flags $tmp_inherited_linker_flag";; + esac + done + fi + dependency_libs=`$ECHO "X $dependency_libs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan" || + { test "$linkmode" != prog && test "$linkmode" != lib; }; then + test -n "$dlopen" && dlfiles="$dlfiles $dlopen" + test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" + fi + + if test "$pass" = conv; then + # Only check for convenience libraries + deplibs="$lib $deplibs" + if test -z "$libdir"; then + if test -z "$old_library"; then + func_fatal_error "cannot find name of link library for \`$lib'" + fi + # It is a libtool convenience library, so add in its objects. + convenience="$convenience $ladir/$objdir/$old_library" + old_convenience="$old_convenience $ladir/$objdir/$old_library" + elif test "$linkmode" != prog && test "$linkmode" != lib; then + func_fatal_error "\`$lib' is not a convenience library" + fi + tmp_libs= + for deplib in $dependency_libs; do + deplibs="$deplib $deplibs" + if $opt_duplicate_deps ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done + continue + fi # $pass = conv + + + # Get the name of the library we link against. + linklib= + for l in $old_library $library_names; do + linklib="$l" + done + if test -z "$linklib"; then + func_fatal_error "cannot find name of link library for \`$lib'" + fi + + # This library was specified with -dlopen. + if test "$pass" = dlopen; then + if test -z "$libdir"; then + func_fatal_error "cannot -dlopen a convenience library: \`$lib'" + fi + if test -z "$dlname" || + test "$dlopen_support" != yes || + test "$build_libtool_libs" = no; then + # If there is no dlname, no dlopen support or we're linking + # statically, we need to preload. We also need to preload any + # dependent libraries so libltdl's deplib preloader doesn't + # bomb out in the load deplibs phase. + dlprefiles="$dlprefiles $lib $dependency_libs" + else + newdlfiles="$newdlfiles $lib" + fi + continue + fi # $pass = dlopen + + # We need an absolute path. + case $ladir in + [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; + *) + abs_ladir=`cd "$ladir" && pwd` + if test -z "$abs_ladir"; then + func_warning "cannot determine absolute directory name of \`$ladir'" + func_warning "passing it literally to the linker, although it might fail" + abs_ladir="$ladir" + fi + ;; + esac + func_basename "$lib" + laname="$func_basename_result" + + # Find the relevant object directory and library name. + if test "X$installed" = Xyes; then + if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then + func_warning "library \`$lib' was moved." + dir="$ladir" + absdir="$abs_ladir" + libdir="$abs_ladir" + else + dir="$libdir" + absdir="$libdir" + fi + test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes + else + if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then + dir="$ladir" + absdir="$abs_ladir" + # Remove this search path later + notinst_path="$notinst_path $abs_ladir" + else + dir="$ladir/$objdir" + absdir="$abs_ladir/$objdir" + # Remove this search path later + notinst_path="$notinst_path $abs_ladir" + fi + fi # $installed = yes + func_stripname 'lib' '.la' "$laname" + name=$func_stripname_result + + # This library was specified with -dlpreopen. + if test "$pass" = dlpreopen; then + if test -z "$libdir" && test "$linkmode" = prog; then + func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" + fi + # Prefer using a static library (so that no silly _DYNAMIC symbols + # are required to link). + if test -n "$old_library"; then + newdlprefiles="$newdlprefiles $dir/$old_library" + # Keep a list of preopened convenience libraries to check + # that they are being used correctly in the link pass. + test -z "$libdir" && \ + dlpreconveniencelibs="$dlpreconveniencelibs $dir/$old_library" + # Otherwise, use the dlname, so that lt_dlopen finds it. + elif test -n "$dlname"; then + newdlprefiles="$newdlprefiles $dir/$dlname" + else + newdlprefiles="$newdlprefiles $dir/$linklib" + fi + fi # $pass = dlpreopen + + if test -z "$libdir"; then + # Link the convenience library + if test "$linkmode" = lib; then + deplibs="$dir/$old_library $deplibs" + elif test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$dir/$old_library $compile_deplibs" + finalize_deplibs="$dir/$old_library $finalize_deplibs" + else + deplibs="$lib $deplibs" # used for prog,scan pass + fi + continue + fi + + + if test "$linkmode" = prog && test "$pass" != link; then + newlib_search_path="$newlib_search_path $ladir" + deplibs="$lib $deplibs" + + linkalldeplibs=no + if test "$link_all_deplibs" != no || test -z "$library_names" || + test "$build_libtool_libs" = no; then + linkalldeplibs=yes + fi + + tmp_libs= + for deplib in $dependency_libs; do + case $deplib in + -L*) func_stripname '-L' '' "$deplib" + newlib_search_path="$newlib_search_path $func_stripname_result" + ;; + esac + # Need to link against all dependency_libs? + if test "$linkalldeplibs" = yes; then + deplibs="$deplib $deplibs" + else + # Need to hardcode shared library paths + # or/and link against static libraries + newdependency_libs="$deplib $newdependency_libs" + fi + if $opt_duplicate_deps ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done # for deplib + continue + fi # $linkmode = prog... + + if test "$linkmode,$pass" = "prog,link"; then + if test -n "$library_names" && + { { test "$prefer_static_libs" = no || + test "$prefer_static_libs,$installed" = "built,yes"; } || + test -z "$old_library"; }; then + # We need to hardcode the library path + if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then + # Make sure the rpath contains only unique directories. + case "$temp_rpath:" in + *"$absdir:"*) ;; + *) temp_rpath="$temp_rpath$absdir:" ;; + esac + fi + + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) compile_rpath="$compile_rpath $absdir" + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" + esac + ;; + esac + fi # $linkmode,$pass = prog,link... + + if test "$alldeplibs" = yes && + { test "$deplibs_check_method" = pass_all || + { test "$build_libtool_libs" = yes && + test -n "$library_names"; }; }; then + # We only need to search for static libraries + continue + fi + fi + + link_static=no # Whether the deplib will be linked statically + use_static_libs=$prefer_static_libs + if test "$use_static_libs" = built && test "$installed" = yes; then + use_static_libs=no + fi + if test -n "$library_names" && + { test "$use_static_libs" = no || test -z "$old_library"; }; then + case $host in + *cygwin* | *mingw* | *cegcc*) + # No point in relinking DLLs because paths are not encoded + notinst_deplibs="$notinst_deplibs $lib" + need_relink=no + ;; + *) + if test "$installed" = no; then + notinst_deplibs="$notinst_deplibs $lib" + need_relink=yes + fi + ;; + esac + # This is a shared library + + # Warn about portability, can't link against -module's on some + # systems (darwin). Don't bleat about dlopened modules though! + dlopenmodule="" + for dlpremoduletest in $dlprefiles; do + if test "X$dlpremoduletest" = "X$lib"; then + dlopenmodule="$dlpremoduletest" + break + fi + done + if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then + $ECHO + if test "$linkmode" = prog; then + $ECHO "*** Warning: Linking the executable $output against the loadable module" + else + $ECHO "*** Warning: Linking the shared library $output against the loadable module" + fi + $ECHO "*** $linklib is not portable!" + fi + if test "$linkmode" = lib && + test "$hardcode_into_libs" = yes; then + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) compile_rpath="$compile_rpath $absdir" + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" + esac + ;; + esac + fi + + if test -n "$old_archive_from_expsyms_cmds"; then + # figure out the soname + set dummy $library_names + shift + realname="$1" + shift + libname=`eval "\\$ECHO \"$libname_spec\""` + # use dlname if we got it. it's perfectly good, no? + if test -n "$dlname"; then + soname="$dlname" + elif test -n "$soname_spec"; then + # bleh windows + case $host in + *cygwin* | mingw* | *cegcc*) + func_arith $current - $age + major=$func_arith_result + versuffix="-$major" + ;; + esac + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + + # Make a new name for the extract_expsyms_cmds to use + soroot="$soname" + func_basename "$soroot" + soname="$func_basename_result" + func_stripname 'lib' '.dll' "$soname" + newlib=libimp-$func_stripname_result.a + + # If the library has no export list, then create one now + if test -f "$output_objdir/$soname-def"; then : + else + func_verbose "extracting exported symbol list from \`$soname'" + func_execute_cmds "$extract_expsyms_cmds" 'exit $?' + fi + + # Create $newlib + if test -f "$output_objdir/$newlib"; then :; else + func_verbose "generating import library for \`$soname'" + func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' + fi + # make sure the library variables are pointing to the new library + dir=$output_objdir + linklib=$newlib + fi # test -n "$old_archive_from_expsyms_cmds" + + if test "$linkmode" = prog || test "$mode" != relink; then + add_shlibpath= + add_dir= + add= + lib_linked=yes + case $hardcode_action in + immediate | unsupported) + if test "$hardcode_direct" = no; then + add="$dir/$linklib" + case $host in + *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; + *-*-sysv4*uw2*) add_dir="-L$dir" ;; + *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ + *-*-unixware7*) add_dir="-L$dir" ;; + *-*-darwin* ) + # if the lib is a (non-dlopened) module then we can not + # link against it, someone is ignoring the earlier warnings + if /usr/bin/file -L $add 2> /dev/null | + $GREP ": [^:]* bundle" >/dev/null ; then + if test "X$dlopenmodule" != "X$lib"; then + $ECHO "*** Warning: lib $linklib is a module, not a shared library" + if test -z "$old_library" ; then + $ECHO + $ECHO "*** And there doesn't seem to be a static archive available" + $ECHO "*** The link will probably fail, sorry" + else + add="$dir/$old_library" + fi + elif test -n "$old_library"; then + add="$dir/$old_library" + fi + fi + esac + elif test "$hardcode_minus_L" = no; then + case $host in + *-*-sunos*) add_shlibpath="$dir" ;; + esac + add_dir="-L$dir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = no; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + relink) + if test "$hardcode_direct" = yes && + test "$hardcode_direct_absolute" = no; then + add="$dir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$dir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + add_dir="$add_dir -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + *) lib_linked=no ;; + esac + + if test "$lib_linked" != yes; then + func_fatal_configuration "unsupported hardcode properties" + fi + + if test -n "$add_shlibpath"; then + case :$compile_shlibpath: in + *":$add_shlibpath:"*) ;; + *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; + esac + fi + if test "$linkmode" = prog; then + test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" + test -n "$add" && compile_deplibs="$add $compile_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + if test "$hardcode_direct" != yes && + test "$hardcode_minus_L" != yes && + test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; + esac + fi + fi + fi + + if test "$linkmode" = prog || test "$mode" = relink; then + add_shlibpath= + add_dir= + add= + # Finalize command for both is simple: just hardcode it. + if test "$hardcode_direct" = yes && + test "$hardcode_direct_absolute" = no; then + add="$libdir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$libdir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; + esac + add="-l$name" + elif test "$hardcode_automatic" = yes; then + if test -n "$inst_prefix_dir" && + test -f "$inst_prefix_dir$libdir/$linklib" ; then + add="$inst_prefix_dir$libdir/$linklib" + else + add="$libdir/$linklib" + fi + else + # We cannot seem to hardcode it, guess we'll fake it. + add_dir="-L$libdir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + add_dir="$add_dir -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + fi + + if test "$linkmode" = prog; then + test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" + test -n "$add" && finalize_deplibs="$add $finalize_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + fi + fi + elif test "$linkmode" = prog; then + # Here we assume that one of hardcode_direct or hardcode_minus_L + # is not unsupported. This is valid on all known static and + # shared platforms. + if test "$hardcode_direct" != unsupported; then + test -n "$old_library" && linklib="$old_library" + compile_deplibs="$dir/$linklib $compile_deplibs" + finalize_deplibs="$dir/$linklib $finalize_deplibs" + else + compile_deplibs="-l$name -L$dir $compile_deplibs" + finalize_deplibs="-l$name -L$dir $finalize_deplibs" + fi + elif test "$build_libtool_libs" = yes; then + # Not a shared library + if test "$deplibs_check_method" != pass_all; then + # We're trying link a shared library against a static one + # but the system doesn't support it. + + # Just print a warning and add the library to dependency_libs so + # that the program can be linked against the static library. + $ECHO + $ECHO "*** Warning: This system can not link to static lib archive $lib." + $ECHO "*** I have the capability to make that library automatically link in when" + $ECHO "*** you link to this library. But I can only do this if you have a" + $ECHO "*** shared version of the library, which you do not appear to have." + if test "$module" = yes; then + $ECHO "*** But as you try to build a module library, libtool will still create " + $ECHO "*** a static module, that should work as long as the dlopening application" + $ECHO "*** is linked with the -dlopen flag to resolve symbols at runtime." + if test -z "$global_symbol_pipe"; then + $ECHO + $ECHO "*** However, this would only work if libtool was able to extract symbol" + $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" + $ECHO "*** not find such a program. So, this module is probably useless." + $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + else + deplibs="$dir/$old_library $deplibs" + link_static=yes + fi + fi # link shared/static library? + + if test "$linkmode" = lib; then + if test -n "$dependency_libs" && + { test "$hardcode_into_libs" != yes || + test "$build_old_libs" = yes || + test "$link_static" = yes; }; then + # Extract -R from dependency_libs + temp_deplibs= + for libdir in $dependency_libs; do + case $libdir in + -R*) func_stripname '-R' '' "$libdir" + temp_xrpath=$func_stripname_result + case " $xrpath " in + *" $temp_xrpath "*) ;; + *) xrpath="$xrpath $temp_xrpath";; + esac;; + *) temp_deplibs="$temp_deplibs $libdir";; + esac + done + dependency_libs="$temp_deplibs" + fi + + newlib_search_path="$newlib_search_path $absdir" + # Link against this library + test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" + # ... and its dependency_libs + tmp_libs= + for deplib in $dependency_libs; do + newdependency_libs="$deplib $newdependency_libs" + if $opt_duplicate_deps ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done + + if test "$link_all_deplibs" != no; then + # Add the search paths of all dependency libraries + for deplib in $dependency_libs; do + case $deplib in + -L*) path="$deplib" ;; + *.la) + func_dirname "$deplib" "" "." + dir="$func_dirname_result" + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; + *) + absdir=`cd "$dir" && pwd` + if test -z "$absdir"; then + func_warning "cannot determine absolute directory name of \`$dir'" + absdir="$dir" + fi + ;; + esac + if $GREP "^installed=no" $deplib > /dev/null; then + case $host in + *-*-darwin*) + depdepl= + eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` + if test -n "$deplibrary_names" ; then + for tmp in $deplibrary_names ; do + depdepl=$tmp + done + if test -f "$absdir/$objdir/$depdepl" ; then + depdepl="$absdir/$objdir/$depdepl" + darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + if test -z "$darwin_install_name"; then + darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + fi + compiler_flags="$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" + linker_flags="$linker_flags -dylib_file ${darwin_install_name}:${depdepl}" + path= + fi + fi + ;; + *) + path="-L$absdir/$objdir" + ;; + esac + else + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + test -z "$libdir" && \ + func_fatal_error "\`$deplib' is not a valid libtool archive" + test "$absdir" != "$libdir" && \ + func_warning "\`$deplib' seems to be moved" + + path="-L$absdir" + fi + ;; + esac + case " $deplibs " in + *" $path "*) ;; + *) deplibs="$path $deplibs" ;; + esac + done + fi # link_all_deplibs != no + fi # linkmode = lib + done # for deplib in $libs + if test "$pass" = link; then + if test "$linkmode" = "prog"; then + compile_deplibs="$new_inherited_linker_flags $compile_deplibs" + finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" + else + compiler_flags="$compiler_flags "`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + fi + fi + dependency_libs="$newdependency_libs" + if test "$pass" = dlpreopen; then + # Link the dlpreopened libraries before other libraries + for deplib in $save_deplibs; do + deplibs="$deplib $deplibs" + done + fi + if test "$pass" != dlopen; then + if test "$pass" != conv; then + # Make sure lib_search_path contains only unique directories. + lib_search_path= + for dir in $newlib_search_path; do + case "$lib_search_path " in + *" $dir "*) ;; + *) lib_search_path="$lib_search_path $dir" ;; + esac + done + newlib_search_path= + fi + + if test "$linkmode,$pass" != "prog,link"; then + vars="deplibs" + else + vars="compile_deplibs finalize_deplibs" + fi + for var in $vars dependency_libs; do + # Add libraries to $var in reverse order + eval tmp_libs=\"\$$var\" + new_libs= + for deplib in $tmp_libs; do + # FIXME: Pedantically, this is the right thing to do, so + # that some nasty dependency loop isn't accidentally + # broken: + #new_libs="$deplib $new_libs" + # Pragmatically, this seems to cause very few problems in + # practice: + case $deplib in + -L*) new_libs="$deplib $new_libs" ;; + -R*) ;; + *) + # And here is the reason: when a library appears more + # than once as an explicit dependence of a library, or + # is implicitly linked in more than once by the + # compiler, it is considered special, and multiple + # occurrences thereof are not removed. Compare this + # with having the same library being listed as a + # dependency of multiple other libraries: in this case, + # we know (pedantically, we assume) the library does not + # need to be listed more than once, so we keep only the + # last copy. This is not always right, but it is rare + # enough that we require users that really mean to play + # such unportable linking tricks to link the library + # using -Wl,-lname, so that libtool does not consider it + # for duplicate removal. + case " $specialdeplibs " in + *" $deplib "*) new_libs="$deplib $new_libs" ;; + *) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$deplib $new_libs" ;; + esac + ;; + esac + ;; + esac + done + tmp_libs= + for deplib in $new_libs; do + case $deplib in + -L*) + case " $tmp_libs " in + *" $deplib "*) ;; + *) tmp_libs="$tmp_libs $deplib" ;; + esac + ;; + *) tmp_libs="$tmp_libs $deplib" ;; + esac + done + eval $var=\"$tmp_libs\" + done # for var + fi + # Last step: remove runtime libs from dependency_libs + # (they stay in deplibs) + tmp_libs= + for i in $dependency_libs ; do + case " $predeps $postdeps $compiler_lib_search_path " in + *" $i "*) + i="" + ;; + esac + if test -n "$i" ; then + tmp_libs="$tmp_libs $i" + fi + done + dependency_libs=$tmp_libs + done # for pass + if test "$linkmode" = prog; then + dlfiles="$newdlfiles" + fi + if test "$linkmode" = prog || test "$linkmode" = lib; then + dlprefiles="$newdlprefiles" + fi + + case $linkmode in + oldlib) + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + func_warning "\`-dlopen' is ignored for archives" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "\`-l' and \`-L' are ignored for archives" ;; + esac + + test -n "$rpath" && \ + func_warning "\`-rpath' is ignored for archives" + + test -n "$xrpath" && \ + func_warning "\`-R' is ignored for archives" + + test -n "$vinfo" && \ + func_warning "\`-version-info/-version-number' is ignored for archives" + + test -n "$release" && \ + func_warning "\`-release' is ignored for archives" + + test -n "$export_symbols$export_symbols_regex" && \ + func_warning "\`-export-symbols' is ignored for archives" + + # Now set the variables for building old libraries. + build_libtool_libs=no + oldlibs="$output" + objs="$objs$old_deplibs" + ;; + + lib) + # Make sure we only generate libraries of the form `libNAME.la'. + case $outputname in + lib*) + func_stripname 'lib' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + ;; + *) + test "$module" = no && \ + func_fatal_help "libtool library \`$output' must begin with \`lib'" + + if test "$need_lib_prefix" != no; then + # Add the "lib" prefix for modules if required + func_stripname '' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + else + func_stripname '' '.la' "$outputname" + libname=$func_stripname_result + fi + ;; + esac + + if test -n "$objs"; then + if test "$deplibs_check_method" != pass_all; then + func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" + else + $ECHO + $ECHO "*** Warning: Linking the shared library $output against the non-libtool" + $ECHO "*** objects $objs is not portable!" + libobjs="$libobjs $objs" + fi + fi + + test "$dlself" != no && \ + func_warning "\`-dlopen self' is ignored for libtool libraries" + + set dummy $rpath + shift + test "$#" -gt 1 && \ + func_warning "ignoring multiple \`-rpath's for a libtool library" + + install_libdir="$1" + + oldlibs= + if test -z "$rpath"; then + if test "$build_libtool_libs" = yes; then + # Building a libtool convenience library. + # Some compilers have problems with a `.al' extension so + # convenience libraries should have the same extension an + # archive normally would. + oldlibs="$output_objdir/$libname.$libext $oldlibs" + build_libtool_libs=convenience + build_old_libs=yes + fi + + test -n "$vinfo" && \ + func_warning "\`-version-info/-version-number' is ignored for convenience libraries" + + test -n "$release" && \ + func_warning "\`-release' is ignored for convenience libraries" + else + + # Parse the version information argument. + save_ifs="$IFS"; IFS=':' + set dummy $vinfo 0 0 0 + shift + IFS="$save_ifs" + + test -n "$7" && \ + func_fatal_help "too many parameters to \`-version-info'" + + # convert absolute version numbers to libtool ages + # this retains compatibility with .la files and attempts + # to make the code below a bit more comprehensible + + case $vinfo_number in + yes) + number_major="$1" + number_minor="$2" + number_revision="$3" + # + # There are really only two kinds -- those that + # use the current revision as the major version + # and those that subtract age and use age as + # a minor version. But, then there is irix + # which has an extra 1 added just for fun + # + case $version_type in + darwin|linux|osf|windows|none) + func_arith $number_major + $number_minor + current=$func_arith_result + age="$number_minor" + revision="$number_revision" + ;; + freebsd-aout|freebsd-elf|sunos) + current="$number_major" + revision="$number_minor" + age="0" + ;; + irix|nonstopux) + func_arith $number_major + $number_minor + current=$func_arith_result + age="$number_minor" + revision="$number_minor" + lt_irix_increment=no + ;; + esac + ;; + no) + current="$1" + revision="$2" + age="$3" + ;; + esac + + # Check that each of the things are valid numbers. + case $current in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "CURRENT \`$current' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + case $revision in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "REVISION \`$revision' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + case $age in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "AGE \`$age' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + if test "$age" -gt "$current"; then + func_error "AGE \`$age' is greater than the current interface number \`$current'" + func_fatal_error "\`$vinfo' is not valid version information" + fi + + # Calculate the version variables. + major= + versuffix= + verstring= + case $version_type in + none) ;; + + darwin) + # Like Linux, but with the current version available in + # verstring for coding it into the library header + func_arith $current - $age + major=.$func_arith_result + versuffix="$major.$age.$revision" + # Darwin ld doesn't like 0 for these options... + func_arith $current + 1 + minor_current=$func_arith_result + xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" + verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" + ;; + + freebsd-aout) + major=".$current" + versuffix=".$current.$revision"; + ;; + + freebsd-elf) + major=".$current" + versuffix=".$current" + ;; + + irix | nonstopux) + if test "X$lt_irix_increment" = "Xno"; then + func_arith $current - $age + else + func_arith $current - $age + 1 + fi + major=$func_arith_result + + case $version_type in + nonstopux) verstring_prefix=nonstopux ;; + *) verstring_prefix=sgi ;; + esac + verstring="$verstring_prefix$major.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$revision + while test "$loop" -ne 0; do + func_arith $revision - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring="$verstring_prefix$major.$iface:$verstring" + done + + # Before this point, $major must not contain `.'. + major=.$major + versuffix="$major.$revision" + ;; + + linux) + func_arith $current - $age + major=.$func_arith_result + versuffix="$major.$age.$revision" + ;; + + osf) + func_arith $current - $age + major=.$func_arith_result + versuffix=".$current.$age.$revision" + verstring="$current.$age.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$age + while test "$loop" -ne 0; do + func_arith $current - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring="$verstring:${iface}.0" + done + + # Make executables depend on our current version. + verstring="$verstring:${current}.0" + ;; + + qnx) + major=".$current" + versuffix=".$current" + ;; + + sunos) + major=".$current" + versuffix=".$current.$revision" + ;; + + windows) + # Use '-' rather than '.', since we only want one + # extension on DOS 8.3 filesystems. + func_arith $current - $age + major=$func_arith_result + versuffix="-$major" + ;; + + *) + func_fatal_configuration "unknown library version type \`$version_type'" + ;; + esac + + # Clear the version info if we defaulted, and they specified a release. + if test -z "$vinfo" && test -n "$release"; then + major= + case $version_type in + darwin) + # we can't check for "0.0" in archive_cmds due to quoting + # problems, so we reset it completely + verstring= + ;; + *) + verstring="0.0" + ;; + esac + if test "$need_version" = no; then + versuffix= + else + versuffix=".0.0" + fi + fi + + # Remove version info from name if versioning should be avoided + if test "$avoid_version" = yes && test "$need_version" = no; then + major= + versuffix= + verstring="" + fi + + # Check to see if the archive will have undefined symbols. + if test "$allow_undefined" = yes; then + if test "$allow_undefined_flag" = unsupported; then + func_warning "undefined symbols not allowed in $host shared libraries" + build_libtool_libs=no + build_old_libs=yes + fi + else + # Don't allow undefined symbols. + allow_undefined_flag="$no_undefined_flag" + fi + + fi + + func_generate_dlsyms "$libname" "$libname" "yes" + libobjs="$libobjs $symfileobj" + test "X$libobjs" = "X " && libobjs= + + if test "$mode" != relink; then + # Remove our outputs, but don't remove object files since they + # may have been created when compiling PIC objects. + removelist= + tempremovelist=`$ECHO "$output_objdir/*"` + for p in $tempremovelist; do + case $p in + *.$objext | *.gcno) + ;; + $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) + if test "X$precious_files_regex" != "X"; then + if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 + then + continue + fi + fi + removelist="$removelist $p" + ;; + *) ;; + esac + done + test -n "$removelist" && \ + func_show_eval "${RM}r \$removelist" + fi + + # Now set the variables for building old libraries. + if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then + oldlibs="$oldlibs $output_objdir/$libname.$libext" + + # Transform .lo files to .o files. + oldobjs="$objs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP` + fi + + # Eliminate all temporary directories. + #for path in $notinst_path; do + # lib_search_path=`$ECHO "X$lib_search_path " | $Xsed -e "s% $path % %g"` + # deplibs=`$ECHO "X$deplibs " | $Xsed -e "s% -L$path % %g"` + # dependency_libs=`$ECHO "X$dependency_libs " | $Xsed -e "s% -L$path % %g"` + #done + + if test -n "$xrpath"; then + # If the user specified any rpath flags, then add them. + temp_xrpath= + for libdir in $xrpath; do + temp_xrpath="$temp_xrpath -R$libdir" + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" ;; + esac + done + if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then + dependency_libs="$temp_xrpath $dependency_libs" + fi + fi + + # Make sure dlfiles contains only unique files that won't be dlpreopened + old_dlfiles="$dlfiles" + dlfiles= + for lib in $old_dlfiles; do + case " $dlprefiles $dlfiles " in + *" $lib "*) ;; + *) dlfiles="$dlfiles $lib" ;; + esac + done + + # Make sure dlprefiles contains only unique files + old_dlprefiles="$dlprefiles" + dlprefiles= + for lib in $old_dlprefiles; do + case "$dlprefiles " in + *" $lib "*) ;; + *) dlprefiles="$dlprefiles $lib" ;; + esac + done + + if test "$build_libtool_libs" = yes; then + if test -n "$rpath"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc*) + # these systems don't actually have a c library (as such)! + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C library is in the System framework + deplibs="$deplibs System.ltframework" + ;; + *-*-netbsd*) + # Don't link with libc until the a.out ld.so is fixed. + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc due to us having libc/libc_r. + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + ;; + *) + # Add libc to deplibs on all other systems if necessary. + if test "$build_libtool_need_lc" = "yes"; then + deplibs="$deplibs -lc" + fi + ;; + esac + fi + + # Transform deplibs into only deplibs that can be linked in shared. + name_save=$name + libname_save=$libname + release_save=$release + versuffix_save=$versuffix + major_save=$major + # I'm not sure if I'm treating the release correctly. I think + # release should show up in the -l (ie -lgmp5) so we don't want to + # add it in twice. Is that correct? + release="" + versuffix="" + major="" + newdeplibs= + droppeddeps=no + case $deplibs_check_method in + pass_all) + # Don't check for shared/static. Everything works. + # This might be a little naive. We might want to check + # whether the library exists or not. But this is on + # osf3 & osf4 and I'm not really sure... Just + # implementing what was already the behavior. + newdeplibs=$deplibs + ;; + test_compile) + # This code stresses the "libraries are programs" paradigm to its + # limits. Maybe even breaks it. We compile a program, linking it + # against the deplibs as a proxy for the library. Then we can check + # whether they linked in statically or dynamically with ldd. + $opt_dry_run || $RM conftest.c + cat > conftest.c </dev/null` + for potent_lib in $potential_libs; do + # Follow soft links. + if ls -lLd "$potent_lib" 2>/dev/null | + $GREP " -> " >/dev/null; then + continue + fi + # The statement above tries to avoid entering an + # endless loop below, in case of cyclic links. + # We might still enter an endless loop, since a link + # loop can be closed while we follow links, + # but so what? + potlib="$potent_lib" + while test -h "$potlib" 2>/dev/null; do + potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` + case $potliblink in + [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; + *) potlib=`$ECHO "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";; + esac + done + if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | + $SED -e 10q | + $EGREP "$file_magic_regex" > /dev/null; then + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + $ECHO + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + $ECHO "*** I have the capability to make that library automatically link in when" + $ECHO "*** you link to this library. But I can only do this if you have a" + $ECHO "*** shared version of the library, which you do not appear to have" + $ECHO "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $ECHO "*** with $libname but no candidates were found. (...for file magic test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a file magic. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + newdeplibs="$newdeplibs $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + for a_deplib in $deplibs; do + case $a_deplib in + -l*) + func_stripname -l '' "$a_deplib" + name=$func_stripname_result + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $a_deplib "*) + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + ;; + esac + fi + if test -n "$a_deplib" ; then + libname=`eval "\\$ECHO \"$libname_spec\""` + for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do + potential_libs=`ls $i/$libname[.-]* 2>/dev/null` + for potent_lib in $potential_libs; do + potlib="$potent_lib" # see symlink-check above in file_magic test + if eval "\$ECHO \"X$potent_lib\"" 2>/dev/null | $Xsed -e 10q | \ + $EGREP "$match_pattern_regex" > /dev/null; then + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + $ECHO + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + $ECHO "*** I have the capability to make that library automatically link in when" + $ECHO "*** you link to this library. But I can only do this if you have a" + $ECHO "*** shared version of the library, which you do not appear to have" + $ECHO "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a regex pattern. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + newdeplibs="$newdeplibs $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + none | unknown | *) + newdeplibs="" + tmp_deplibs=`$ECHO "X $deplibs" | $Xsed \ + -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'` + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + for i in $predeps $postdeps ; do + # can't use Xsed below, because $i might contain '/' + tmp_deplibs=`$ECHO "X $tmp_deplibs" | $Xsed -e "s,$i,,"` + done + fi + if $ECHO "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' | + $GREP . >/dev/null; then + $ECHO + if test "X$deplibs_check_method" = "Xnone"; then + $ECHO "*** Warning: inter-library dependencies are not supported in this platform." + else + $ECHO "*** Warning: inter-library dependencies are not known to be supported." + fi + $ECHO "*** All declared inter-library dependencies are being dropped." + droppeddeps=yes + fi + ;; + esac + versuffix=$versuffix_save + major=$major_save + release=$release_save + libname=$libname_save + name=$name_save + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library with the System framework + newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's/ -lc / System.ltframework /'` + ;; + esac + + if test "$droppeddeps" = yes; then + if test "$module" = yes; then + $ECHO + $ECHO "*** Warning: libtool could not satisfy all declared inter-library" + $ECHO "*** dependencies of module $libname. Therefore, libtool will create" + $ECHO "*** a static module, that should work as long as the dlopening" + $ECHO "*** application is linked with the -dlopen flag." + if test -z "$global_symbol_pipe"; then + $ECHO + $ECHO "*** However, this would only work if libtool was able to extract symbol" + $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" + $ECHO "*** not find such a program. So, this module is probably useless." + $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + else + $ECHO "*** The inter-library dependencies that have been dropped here will be" + $ECHO "*** automatically added whenever a program is linked with this library" + $ECHO "*** or is declared to -dlopen it." + + if test "$allow_undefined" = no; then + $ECHO + $ECHO "*** Since this library must not contain undefined symbols," + $ECHO "*** because either the platform does not support them or" + $ECHO "*** it was explicitly requested with -no-undefined," + $ECHO "*** libtool will only create a static version of it." + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + fi + fi + # Done checking deplibs! + deplibs=$newdeplibs + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + case $host in + *-*-darwin*) + newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + new_inherited_linker_flags=`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + deplibs=`$ECHO "X $deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $deplibs " in + *" -L$path/$objdir "*) + new_libs="$new_libs -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$new_libs $deplib" ;; + esac + ;; + *) new_libs="$new_libs $deplib" ;; + esac + done + deplibs="$new_libs" + + # All the library-specific variables (install_libdir is set above). + library_names= + old_library= + dlname= + + # Test again, we may have decided not to build it any more + if test "$build_libtool_libs" = yes; then + if test "$hardcode_into_libs" = yes; then + # Hardcode the library paths + hardcode_libdirs= + dep_rpath= + rpath="$finalize_rpath" + test "$mode" != relink && rpath="$compile_rpath$rpath" + for libdir in $rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + dep_rpath="$dep_rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) perm_rpath="$perm_rpath $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + if test -n "$hardcode_libdir_flag_spec_ld"; then + eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\" + else + eval dep_rpath=\"$hardcode_libdir_flag_spec\" + fi + fi + if test -n "$runpath_var" && test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + rpath="$rpath$dir:" + done + eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" + fi + test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" + fi + + shlibpath="$finalize_shlibpath" + test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath" + if test -n "$shlibpath"; then + eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" + fi + + # Get the real and link names of the library. + eval shared_ext=\"$shrext_cmds\" + eval library_names=\"$library_names_spec\" + set dummy $library_names + shift + realname="$1" + shift + + if test -n "$soname_spec"; then + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + if test -z "$dlname"; then + dlname=$soname + fi + + lib="$output_objdir/$realname" + linknames= + for link + do + linknames="$linknames $link" + done + + # Use standard objects if they are pic + test -z "$pic_flag" && libobjs=`$ECHO "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + test "X$libobjs" = "X " && libobjs= + + delfiles= + if test -n "$export_symbols" && test -n "$include_expsyms"; then + $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" + export_symbols="$output_objdir/$libname.uexp" + delfiles="$delfiles $export_symbols" + fi + + orig_export_symbols= + case $host_os in + cygwin* | mingw* | cegcc*) + if test -n "$export_symbols" && test -z "$export_symbols_regex"; then + # exporting using user supplied symfile + if test "x`$SED 1q $export_symbols`" != xEXPORTS; then + # and it's NOT already a .def file. Must figure out + # which of the given symbols are data symbols and tag + # them as such. So, trigger use of export_symbols_cmds. + # export_symbols gets reassigned inside the "prepare + # the list of exported symbols" if statement, so the + # include_expsyms logic still works. + orig_export_symbols="$export_symbols" + export_symbols= + always_export_symbols=yes + fi + fi + ;; + esac + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then + func_verbose "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $opt_dry_run || $RM $export_symbols + cmds=$export_symbols_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + func_len " $cmd" + len=$func_len_result + if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + func_show_eval "$cmd" 'exit $?' + skipped_export=false + else + # The command line is too long to execute in one step. + func_verbose "using reloadable object file for export list..." + skipped_export=: + # Break out early, otherwise skipped_export may be + # set to false by a later but shorter cmd. + break + fi + done + IFS="$save_ifs" + if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + fi + + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols="$export_symbols" + test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" + $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' + fi + + if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + + tmp_deplibs= + for test_deplib in $deplibs; do + case " $convenience " in + *" $test_deplib "*) ;; + *) + tmp_deplibs="$tmp_deplibs $test_deplib" + ;; + esac + done + deplibs="$tmp_deplibs" + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec" && + test "$compiler_needs_object" = yes && + test -z "$libobjs"; then + # extract the archives, so we have objects to list. + # TODO: could optimize this to just extract one archive. + whole_archive_flag_spec= + fi + if test -n "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + else + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + + func_extract_archives $gentop $convenience + libobjs="$libobjs $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + fi + + if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then + eval flag=\"$thread_safe_flag_spec\" + linker_flags="$linker_flags $flag" + fi + + # Make a backup of the uninstalled library when relinking + if test "$mode" = relink; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? + fi + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + eval test_cmds=\"$module_expsym_cmds\" + cmds=$module_expsym_cmds + else + eval test_cmds=\"$module_cmds\" + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + eval test_cmds=\"$archive_expsym_cmds\" + cmds=$archive_expsym_cmds + else + eval test_cmds=\"$archive_cmds\" + cmds=$archive_cmds + fi + fi + + if test "X$skipped_export" != "X:" && + func_len " $test_cmds" && + len=$func_len_result && + test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + : + else + # The command line is too long to link in one step, link piecewise + # or, if using GNU ld and skipped_export is not :, use a linker + # script. + + # Save the value of $output and $libobjs because we want to + # use them later. If we have whole_archive_flag_spec, we + # want to use save_libobjs as it was before + # whole_archive_flag_spec was expanded, because we can't + # assume the linker understands whole_archive_flag_spec. + # This may have to be revisited, in case too many + # convenience libraries get linked in and end up exceeding + # the spec. + if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + fi + save_output=$output + output_la=`$ECHO "X$output" | $Xsed -e "$basename"` + + # Clear the reloadable object creation command queue and + # initialize k to one. + test_cmds= + concat_cmds= + objlist= + last_robj= + k=1 + + if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then + output=${output_objdir}/${output_la}.lnkscript + func_verbose "creating GNU ld script: $output" + $ECHO 'INPUT (' > $output + for obj in $save_libobjs + do + $ECHO "$obj" >> $output + done + $ECHO ')' >> $output + delfiles="$delfiles $output" + elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then + output=${output_objdir}/${output_la}.lnk + func_verbose "creating linker input file list: $output" + : > $output + set x $save_libobjs + shift + firstobj= + if test "$compiler_needs_object" = yes; then + firstobj="$1 " + shift + fi + for obj + do + $ECHO "$obj" >> $output + done + delfiles="$delfiles $output" + output=$firstobj\"$file_list_spec$output\" + else + if test -n "$save_libobjs"; then + func_verbose "creating reloadable object files..." + output=$output_objdir/$output_la-${k}.$objext + eval test_cmds=\"$reload_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + + # Loop over the list of objects to be linked. + for obj in $save_libobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + if test "X$objlist" = X || + test "$len" -lt "$max_cmd_len"; then + func_append objlist " $obj" + else + # The command $test_cmds is almost too long, add a + # command to the queue. + if test "$k" -eq 1 ; then + # The first file doesn't have a previous command to add. + eval concat_cmds=\"$reload_cmds $objlist $last_robj\" + else + # All subsequent reloadable object files will link in + # the last one created. + eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj~\$RM $last_robj\" + fi + last_robj=$output_objdir/$output_la-${k}.$objext + func_arith $k + 1 + k=$func_arith_result + output=$output_objdir/$output_la-${k}.$objext + objlist=$obj + func_len " $last_robj" + func_arith $len0 + $func_len_result + len=$func_arith_result + fi + done + # Handle the remaining objects by creating one last + # reloadable object file. All subsequent reloadable object + # files will link in the last one created. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\" + if test -n "$last_robj"; then + eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" + fi + delfiles="$delfiles $output" + + else + output= + fi + + if ${skipped_export-false}; then + func_verbose "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $opt_dry_run || $RM $export_symbols + libobjs=$output + # Append the command to create the export file. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" + if test -n "$last_robj"; then + eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" + fi + fi + + test -n "$save_libobjs" && + func_verbose "creating a temporary reloadable object file: $output" + + # Loop through the commands generated above and execute them. + save_ifs="$IFS"; IFS='~' + for cmd in $concat_cmds; do + IFS="$save_ifs" + $opt_silent || { + func_quote_for_expand "$cmd" + eval "func_echo $func_quote_for_expand_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test "$mode" = relink; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS="$save_ifs" + + if test -n "$export_symbols_regex" && ${skipped_export-false}; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + + if ${skipped_export-false}; then + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols="$export_symbols" + test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" + $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' + fi + + if test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + fi + + libobjs=$output + # Restore the value of output. + output=$save_output + + if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + fi + # Expand the library linking commands again to reset the + # value of $libobjs for piecewise linking. + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + cmds=$module_expsym_cmds + else + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + cmds=$archive_expsym_cmds + else + cmds=$archive_cmds + fi + fi + fi + + if test -n "$delfiles"; then + # Append the command to remove temporary files to $cmds. + eval cmds=\"\$cmds~\$RM $delfiles\" + fi + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + + func_extract_archives $gentop $dlprefiles + libobjs="$libobjs $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $opt_silent || { + func_quote_for_expand "$cmd" + eval "func_echo $func_quote_for_expand_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test "$mode" = relink; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS="$save_ifs" + + # Restore the uninstalled library and exit + if test "$mode" = relink; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? + + if test -n "$convenience"; then + if test -z "$whole_archive_flag_spec"; then + func_show_eval '${RM}r "$gentop"' + fi + fi + + exit $EXIT_SUCCESS + fi + + # Create links to the real library. + for linkname in $linknames; do + if test "$realname" != "$linkname"; then + func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' + fi + done + + # If -module or -export-dynamic was specified, set the dlname. + if test "$module" = yes || test "$export_dynamic" = yes; then + # On all known operating systems, these are identical. + dlname="$soname" + fi + fi + ;; + + obj) + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + func_warning "\`-dlopen' is ignored for objects" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "\`-l' and \`-L' are ignored for objects" ;; + esac + + test -n "$rpath" && \ + func_warning "\`-rpath' is ignored for objects" + + test -n "$xrpath" && \ + func_warning "\`-R' is ignored for objects" + + test -n "$vinfo" && \ + func_warning "\`-version-info' is ignored for objects" + + test -n "$release" && \ + func_warning "\`-release' is ignored for objects" + + case $output in + *.lo) + test -n "$objs$old_deplibs" && \ + func_fatal_error "cannot build library object \`$output' from non-libtool objects" + + libobj=$output + func_lo2o "$libobj" + obj=$func_lo2o_result + ;; + *) + libobj= + obj="$output" + ;; + esac + + # Delete the old objects. + $opt_dry_run || $RM $obj $libobj + + # Objects from convenience libraries. This assumes + # single-version convenience libraries. Whenever we create + # different ones for PIC/non-PIC, this we'll have to duplicate + # the extraction. + reload_conv_objs= + gentop= + # reload_cmds runs $LD directly, so let us get rid of + # -Wl from whole_archive_flag_spec and hope we can get by with + # turning comma into space.. + wl= + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec"; then + eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" + reload_conv_objs=$reload_objs\ `$ECHO "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'` + else + gentop="$output_objdir/${obj}x" + generated="$generated $gentop" + + func_extract_archives $gentop $convenience + reload_conv_objs="$reload_objs $func_extract_archives_result" + fi + fi + + # Create the old-style object. + reload_objs="$objs$old_deplibs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test + + output="$obj" + func_execute_cmds "$reload_cmds" 'exit $?' + + # Exit if we aren't doing a library object file. + if test -z "$libobj"; then + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + fi + + if test "$build_libtool_libs" != yes; then + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + # Create an invalid libtool object if no PIC, so that we don't + # accidentally link it into a program. + # $show "echo timestamp > $libobj" + # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? + exit $EXIT_SUCCESS + fi + + if test -n "$pic_flag" || test "$pic_mode" != default; then + # Only do commands if we really have different PIC objects. + reload_objs="$libobjs $reload_conv_objs" + output="$libobj" + func_execute_cmds "$reload_cmds" 'exit $?' + fi + + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + ;; + + prog) + case $host in + *cygwin*) func_stripname '' '.exe' "$output" + output=$func_stripname_result.exe;; + esac + test -n "$vinfo" && \ + func_warning "\`-version-info' is ignored for programs" + + test -n "$release" && \ + func_warning "\`-release' is ignored for programs" + + test "$preload" = yes \ + && test "$dlopen_support" = unknown \ + && test "$dlopen_self" = unknown \ + && test "$dlopen_self_static" = unknown && \ + func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library is the System framework + compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` + finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` + ;; + esac + + case $host in + *-*-darwin*) + # Don't allow lazy linking, it breaks C++ global constructors + # But is supposedly fixed on 10.4 or later (yay!). + if test "$tagname" = CXX ; then + case ${MACOSX_DEPLOYMENT_TARGET-10.0} in + 10.[0123]) + compile_command="$compile_command ${wl}-bind_at_load" + finalize_command="$finalize_command ${wl}-bind_at_load" + ;; + esac + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $compile_deplibs " in + *" -L$path/$objdir "*) + new_libs="$new_libs -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $compile_deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$new_libs $deplib" ;; + esac + ;; + *) new_libs="$new_libs $deplib" ;; + esac + done + compile_deplibs="$new_libs" + + + compile_command="$compile_command $compile_deplibs" + finalize_command="$finalize_command $finalize_deplibs" + + if test -n "$rpath$xrpath"; then + # If the user specified any rpath flags, then add them. + for libdir in $rpath $xrpath; do + # This is the magic to use -rpath. + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" ;; + esac + done + fi + + # Now hardcode the library paths + rpath= + hardcode_libdirs= + for libdir in $compile_rpath $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + rpath="$rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) perm_rpath="$perm_rpath $libdir" ;; + esac + fi + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$libdir:"*) ;; + ::) dllsearchpath=$libdir;; + *) dllsearchpath="$dllsearchpath:$libdir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) dllsearchpath="$dllsearchpath:$testbindir";; + esac + ;; + esac + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + compile_rpath="$rpath" + + rpath= + hardcode_libdirs= + for libdir in $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + rpath="$rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$finalize_perm_rpath " in + *" $libdir "*) ;; + *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + finalize_rpath="$rpath" + + if test -n "$libobjs" && test "$build_old_libs" = yes; then + # Transform all the library objects into standard objects. + compile_command=`$ECHO "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + finalize_command=`$ECHO "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + fi + + func_generate_dlsyms "$outputname" "@PROGRAM@" "no" + + # template prelinking step + if test -n "$prelink_cmds"; then + func_execute_cmds "$prelink_cmds" 'exit $?' + fi + + wrappers_required=yes + case $host in + *cygwin* | *mingw* ) + if test "$build_libtool_libs" != yes; then + wrappers_required=no + fi + ;; + *cegcc) + # Disable wrappers for cegcc, we are cross compiling anyway. + wrappers_required=no + ;; + *) + if test "$need_relink" = no || test "$build_libtool_libs" != yes; then + wrappers_required=no + fi + ;; + esac + if test "$wrappers_required" = no; then + # Replace the output file specification. + compile_command=`$ECHO "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` + link_command="$compile_command$compile_rpath" + + # We have no uninstalled library dependencies, so finalize right now. + exit_status=0 + func_show_eval "$link_command" 'exit_status=$?' + + # Delete the generated files. + if test -f "$output_objdir/${outputname}S.${objext}"; then + func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' + fi + + exit $exit_status + fi + + if test -n "$compile_shlibpath$finalize_shlibpath"; then + compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" + fi + if test -n "$finalize_shlibpath"; then + finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" + fi + + compile_var= + finalize_var= + if test -n "$runpath_var"; then + if test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + rpath="$rpath$dir:" + done + compile_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + if test -n "$finalize_perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $finalize_perm_rpath; do + rpath="$rpath$dir:" + done + finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + fi + + if test "$no_install" = yes; then + # We don't need to create a wrapper script. + link_command="$compile_var$compile_command$compile_rpath" + # Replace the output file specification. + link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` + # Delete the old output file. + $opt_dry_run || $RM $output + # Link the executable and exit + func_show_eval "$link_command" 'exit $?' + exit $EXIT_SUCCESS + fi + + if test "$hardcode_action" = relink; then + # Fast installation is not supported + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + + func_warning "this platform does not like uninstalled shared libraries" + func_warning "\`$output' will be relinked during installation" + else + if test "$fast_install" != no; then + link_command="$finalize_var$compile_command$finalize_rpath" + if test "$fast_install" = yes; then + relink_command=`$ECHO "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` + else + # fast_install is set to needless + relink_command= + fi + else + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + fi + fi + + # Replace the output file specification. + link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` + + # Delete the old output files. + $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname + + func_show_eval "$link_command" 'exit $?' + + # Now create the wrapper script. + func_verbose "creating $output" + + # Quote the relink command for shipping. + if test -n "$relink_command"; then + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_for_eval "$var_value" + relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" + fi + done + relink_command="(cd `pwd`; $relink_command)" + relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` + fi + + # Quote $ECHO for shipping. + if test "X$ECHO" = "X$SHELL $progpath --fallback-echo"; then + case $progpath in + [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";; + *) qecho="$SHELL `pwd`/$progpath --fallback-echo";; + esac + qecho=`$ECHO "X$qecho" | $Xsed -e "$sed_quote_subst"` + else + qecho=`$ECHO "X$ECHO" | $Xsed -e "$sed_quote_subst"` + fi + + # Only actually do things if not in dry run mode. + $opt_dry_run || { + # win32 will think the script is a binary if it has + # a .exe suffix, so we strip it off here. + case $output in + *.exe) func_stripname '' '.exe' "$output" + output=$func_stripname_result ;; + esac + # test for cygwin because mv fails w/o .exe extensions + case $host in + *cygwin*) + exeext=.exe + func_stripname '' '.exe' "$outputname" + outputname=$func_stripname_result ;; + *) exeext= ;; + esac + case $host in + *cygwin* | *mingw* ) + func_dirname_and_basename "$output" "" "." + output_name=$func_basename_result + output_path=$func_dirname_result + cwrappersource="$output_path/$objdir/lt-$output_name.c" + cwrapper="$output_path/$output_name.exe" + $RM $cwrappersource $cwrapper + trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 + + func_emit_cwrapperexe_src > $cwrappersource + + # The wrapper executable is built using the $host compiler, + # because it contains $host paths and files. If cross- + # compiling, it, like the target executable, must be + # executed on the $host or under an emulation environment. + $opt_dry_run || { + $LTCC $LTCFLAGS -o $cwrapper $cwrappersource + $STRIP $cwrapper + } + + # Now, create the wrapper script for func_source use: + func_ltwrapper_scriptname $cwrapper + $RM $func_ltwrapper_scriptname_result + trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 + $opt_dry_run || { + # note: this script will not be executed, so do not chmod. + if test "x$build" = "x$host" ; then + $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result + else + func_emit_wrapper no > $func_ltwrapper_scriptname_result + fi + } + ;; + * ) + $RM $output + trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 + + func_emit_wrapper no > $output + chmod +x $output + ;; + esac + } + exit $EXIT_SUCCESS + ;; + esac + + # See if we need to build an old-fashioned archive. + for oldlib in $oldlibs; do + + if test "$build_libtool_libs" = convenience; then + oldobjs="$libobjs_save $symfileobj" + addlibs="$convenience" + build_libtool_libs=no + else + if test "$build_libtool_libs" = module; then + oldobjs="$libobjs_save" + build_libtool_libs=no + else + oldobjs="$old_deplibs $non_pic_objects" + if test "$preload" = yes && test -f "$symfileobj"; then + oldobjs="$oldobjs $symfileobj" + fi + fi + addlibs="$old_convenience" + fi + + if test -n "$addlibs"; then + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + + func_extract_archives $gentop $addlibs + oldobjs="$oldobjs $func_extract_archives_result" + fi + + # Do each command in the archive commands. + if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then + cmds=$old_archive_from_new_cmds + else + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + + func_extract_archives $gentop $dlprefiles + oldobjs="$oldobjs $func_extract_archives_result" + fi + + # POSIX demands no paths to be encoded in archives. We have + # to avoid creating archives with duplicate basenames if we + # might have to extract them afterwards, e.g., when creating a + # static archive out of a convenience library, or when linking + # the entirety of a libtool archive into another (currently + # not supported by libtool). + if (for obj in $oldobjs + do + func_basename "$obj" + $ECHO "$func_basename_result" + done | sort | sort -uc >/dev/null 2>&1); then + : + else + $ECHO "copying selected object files to avoid basename conflicts..." + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + func_mkdir_p "$gentop" + save_oldobjs=$oldobjs + oldobjs= + counter=1 + for obj in $save_oldobjs + do + func_basename "$obj" + objbase="$func_basename_result" + case " $oldobjs " in + " ") oldobjs=$obj ;; + *[\ /]"$objbase "*) + while :; do + # Make sure we don't pick an alternate name that also + # overlaps. + newobj=lt$counter-$objbase + func_arith $counter + 1 + counter=$func_arith_result + case " $oldobjs " in + *[\ /]"$newobj "*) ;; + *) if test ! -f "$gentop/$newobj"; then break; fi ;; + esac + done + func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" + oldobjs="$oldobjs $gentop/$newobj" + ;; + *) oldobjs="$oldobjs $obj" ;; + esac + done + fi + eval cmds=\"$old_archive_cmds\" + + func_len " $cmds" + len=$func_len_result + if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + cmds=$old_archive_cmds + else + # the command line is too long to link in one step, link in parts + func_verbose "using piecewise archive linking..." + save_RANLIB=$RANLIB + RANLIB=: + objlist= + concat_cmds= + save_oldobjs=$oldobjs + oldobjs= + # Is there a better way of finding the last object in the list? + for obj in $save_oldobjs + do + last_oldobj=$obj + done + eval test_cmds=\"$old_archive_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + for obj in $save_oldobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + func_append objlist " $obj" + if test "$len" -lt "$max_cmd_len"; then + : + else + # the above command should be used before it gets too long + oldobjs=$objlist + if test "$obj" = "$last_oldobj" ; then + RANLIB=$save_RANLIB + fi + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" + objlist= + len=$len0 + fi + done + RANLIB=$save_RANLIB + oldobjs=$objlist + if test "X$oldobjs" = "X" ; then + eval cmds=\"\$concat_cmds\" + else + eval cmds=\"\$concat_cmds~\$old_archive_cmds\" + fi + fi + fi + func_execute_cmds "$cmds" 'exit $?' + done + + test -n "$generated" && \ + func_show_eval "${RM}r$generated" + + # Now create the libtool archive. + case $output in + *.la) + old_library= + test "$build_old_libs" = yes && old_library="$libname.$libext" + func_verbose "creating $output" + + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_for_eval "$var_value" + relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" + fi + done + # Quote the link command for shipping. + relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" + relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` + if test "$hardcode_automatic" = yes ; then + relink_command= + fi + + # Only create the output if not a dry run. + $opt_dry_run || { + for installed in no yes; do + if test "$installed" = yes; then + if test -z "$install_libdir"; then + break + fi + output="$output_objdir/$outputname"i + # Replace all uninstalled libtool libraries with the installed ones + newdependency_libs= + for deplib in $dependency_libs; do + case $deplib in + *.la) + func_basename "$deplib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + test -z "$libdir" && \ + func_fatal_error "\`$deplib' is not a valid libtool archive" + if test "x$EGREP" = x ; then + EGREP=egrep + fi + # We do not want portage's install root ($D) present. Check only for + # this if the .la is being installed. + if test "$installed" = yes && test "$D"; then + eval mynewdependency_lib=`echo "$libdir/$name" |sed -e "s:$D:/:g" -e 's:/\+:/:g'` + else + mynewdependency_lib="$libdir/$name" + fi + # Do not add duplicates + if test "$mynewdependency_lib"; then + my_little_ninja_foo_1=`echo $newdependency_libs |$EGREP -e "$mynewdependency_lib"` + if test -z "$my_little_ninja_foo_1"; then + newdependency_libs="$newdependency_libs $mynewdependency_lib" + fi + fi + ;; + *) + if test "$installed" = yes; then + # Rather use S=WORKDIR if our version of portage supports it. + # This is because some ebuild (gcc) do not use $S as buildroot. + if test "$PWORKDIR"; then + S="$PWORKDIR" + fi + # We do not want portage's build root ($S) present. + my_little_ninja_foo_2=`echo $deplib |$EGREP -e "$S"` + # We do not want portage's install root ($D) present. + my_little_ninja_foo_3=`echo $deplib |$EGREP -e "$D"` + if test -n "$my_little_ninja_foo_2" && test "$S"; then + mynewdependency_lib="" + elif test -n "$my_little_ninja_foo_3" && test "$D"; then + eval mynewdependency_lib=`echo "$deplib" |sed -e "s:$D:/:g" -e 's:/\+:/:g'` + else + mynewdependency_lib="$deplib" + fi + else + mynewdependency_lib="$deplib" + fi + # Do not add duplicates + if test "$mynewdependency_lib"; then + my_little_ninja_foo_4=`echo $newdependency_libs |$EGREP -e "$mynewdependency_lib"` + if test -z "$my_little_ninja_foo_4"; then + newdependency_libs="$newdependency_libs $mynewdependency_lib" + fi + fi + ;; + esac + done + dependency_libs="$newdependency_libs" + newdlfiles= + + for lib in $dlfiles; do + case $lib in + *.la) + func_basename "$lib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "\`$lib' is not a valid libtool archive" + newdlfiles="$newdlfiles $libdir/$name" + ;; + *) newdlfiles="$newdlfiles $lib" ;; + esac + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + *.la) + # Only pass preopened files to the pseudo-archive (for + # eventual linking with the app. that links it) if we + # didn't already link the preopened objects directly into + # the library: + func_basename "$lib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "\`$lib' is not a valid libtool archive" + newdlprefiles="$newdlprefiles $libdir/$name" + ;; + esac + done + dlprefiles="$newdlprefiles" + else + newdlfiles= + for lib in $dlfiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + newdlfiles="$newdlfiles $abs" + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + newdlprefiles="$newdlprefiles $abs" + done + dlprefiles="$newdlprefiles" + fi + $RM $output + # place dlname in correct position for cygwin + tdlname=$dlname + case $host,$output,$installed,$module,$dlname in + *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;; + esac + # Do not add duplicates + if test "$installed" = yes && test "$D"; then + install_libdir=`echo "$install_libdir" |sed -e "s:$D:/:g" -e 's:/\+:/:g'` + fi + $ECHO > $output "\ +# $outputname - a libtool library file +# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION +# +# Please DO NOT delete this file! +# It is necessary for linking the library. + +# The name that we can dlopen(3). +dlname='$tdlname' + +# Names of this library. +library_names='$library_names' + +# The name of the static archive. +old_library='$old_library' + +# Linker flags that can not go in dependency_libs. +inherited_linker_flags='$new_inherited_linker_flags' + +# Libraries that this one depends upon. +dependency_libs='$dependency_libs' + +# Names of additional weak libraries provided by this library +weak_library_names='$weak_libs' + +# Version information for $libname. +current=$current +age=$age +revision=$revision + +# Is this an already installed library? +installed=$installed + +# Should we warn about portability when linking against -modules? +shouldnotlink=$module + +# Files to dlopen/dlpreopen +dlopen='$dlfiles' +dlpreopen='$dlprefiles' + +# Directory that this library needs to be installed in: +libdir='$install_libdir'" + if test "$installed" = no && test "$need_relink" = yes; then + $ECHO >> $output "\ +relink_command=\"$relink_command\"" + fi + done + } + + # Do a symbolic link so that the libtool archive can be found in + # LD_LIBRARY_PATH before the program is installed. + func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' + ;; + esac + exit $EXIT_SUCCESS +} + +{ test "$mode" = link || test "$mode" = relink; } && + func_mode_link ${1+"$@"} + + +# func_mode_uninstall arg... +func_mode_uninstall () +{ + $opt_debug + RM="$nonopt" + files= + rmforce= + exit_status=0 + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + for arg + do + case $arg in + -f) RM="$RM $arg"; rmforce=yes ;; + -*) RM="$RM $arg" ;; + *) files="$files $arg" ;; + esac + done + + test -z "$RM" && \ + func_fatal_help "you must specify an RM program" + + rmdirs= + + origobjdir="$objdir" + for file in $files; do + func_dirname "$file" "" "." + dir="$func_dirname_result" + if test "X$dir" = X.; then + objdir="$origobjdir" + else + objdir="$dir/$origobjdir" + fi + func_basename "$file" + name="$func_basename_result" + test "$mode" = uninstall && objdir="$dir" + + # Remember objdir for removal later, being careful to avoid duplicates + if test "$mode" = clean; then + case " $rmdirs " in + *" $objdir "*) ;; + *) rmdirs="$rmdirs $objdir" ;; + esac + fi + + # Don't error if the file doesn't exist and rm -f was used. + if { test -L "$file"; } >/dev/null 2>&1 || + { test -h "$file"; } >/dev/null 2>&1 || + test -f "$file"; then + : + elif test -d "$file"; then + exit_status=1 + continue + elif test "$rmforce" = yes; then + continue + fi + + rmfiles="$file" + + case $name in + *.la) + # Possibly a libtool archive, so verify it. + if func_lalib_p "$file"; then + func_source $dir/$name + + # Delete the libtool libraries and symlinks. + for n in $library_names; do + rmfiles="$rmfiles $objdir/$n" + done + test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library" + + case "$mode" in + clean) + case " $library_names " in + # " " in the beginning catches empty $dlname + *" $dlname "*) ;; + *) rmfiles="$rmfiles $objdir/$dlname" ;; + esac + test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i" + ;; + uninstall) + if test -n "$library_names"; then + # Do each command in the postuninstall commands. + func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' + fi + + if test -n "$old_library"; then + # Do each command in the old_postuninstall commands. + func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' + fi + # FIXME: should reinstall the best remaining shared library. + ;; + esac + fi + ;; + + *.lo) + # Possibly a libtool object, so verify it. + if func_lalib_p "$file"; then + + # Read the .lo file + func_source $dir/$name + + # Add PIC object to the list of files to remove. + if test -n "$pic_object" && + test "$pic_object" != none; then + rmfiles="$rmfiles $dir/$pic_object" + fi + + # Add non-PIC object to the list of files to remove. + if test -n "$non_pic_object" && + test "$non_pic_object" != none; then + rmfiles="$rmfiles $dir/$non_pic_object" + fi + fi + ;; + + *) + if test "$mode" = clean ; then + noexename=$name + case $file in + *.exe) + func_stripname '' '.exe' "$file" + file=$func_stripname_result + func_stripname '' '.exe' "$name" + noexename=$func_stripname_result + # $file with .exe has already been added to rmfiles, + # add $file without .exe + rmfiles="$rmfiles $file" + ;; + esac + # Do a test to see if this is a libtool program. + if func_ltwrapper_p "$file"; then + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + relink_command= + func_source $func_ltwrapper_scriptname_result + rmfiles="$rmfiles $func_ltwrapper_scriptname_result" + else + relink_command= + func_source $dir/$noexename + fi + + # note $name still contains .exe if it was in $file originally + # as does the version of $file that was added into $rmfiles + rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}" + if test "$fast_install" = yes && test -n "$relink_command"; then + rmfiles="$rmfiles $objdir/lt-$name" + fi + if test "X$noexename" != "X$name" ; then + rmfiles="$rmfiles $objdir/lt-${noexename}.c" + fi + fi + fi + ;; + esac + func_show_eval "$RM $rmfiles" 'exit_status=1' + done + objdir="$origobjdir" + + # Try to remove the ${objdir}s in the directories where we deleted files + for dir in $rmdirs; do + if test -d "$dir"; then + func_show_eval "rmdir $dir >/dev/null 2>&1" + fi + done + + exit $exit_status +} + +{ test "$mode" = uninstall || test "$mode" = clean; } && + func_mode_uninstall ${1+"$@"} + +test -z "$mode" && { + help="$generic_help" + func_fatal_help "you must specify a MODE" +} + +test -z "$exec_cmd" && \ + func_fatal_help "invalid operation mode \`$mode'" + +if test -n "$exec_cmd"; then + eval exec "$exec_cmd" + exit $EXIT_FAILURE +fi + +exit $exit_status + + +# The TAGs below are defined such that we never get into a situation +# in which we disable both kinds of libraries. Given conflicting +# choices, we go for a static library, that is the most portable, +# since we can't tell whether shared libraries were disabled because +# the user asked for that or because the platform doesn't support +# them. This is particularly important on AIX, because we don't +# support having both static and shared libraries enabled at the same +# time on that platform, so we default to a shared-only configuration. +# If a disable-shared tag is given, we'll fallback to a static-only +# configuration. But we'll never go from static-only to shared-only. + +# ### BEGIN LIBTOOL TAG CONFIG: disable-shared +build_libtool_libs=no +build_old_libs=yes +# ### END LIBTOOL TAG CONFIG: disable-shared + +# ### BEGIN LIBTOOL TAG CONFIG: disable-static +build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` +# ### END LIBTOOL TAG CONFIG: disable-static + +# Local Variables: +# mode:shell-script +# sh-indentation:2 +# End: +# vi:sw=2 + diff --git a/components/external/SQLite-3.8.1/magic.txt b/components/external/SQLite-3.8.1/magic.txt new file mode 100644 index 0000000000000000000000000000000000000000..c6340d9b18ce17fc79d4c7f15cef4c37a05dd3c3 --- /dev/null +++ b/components/external/SQLite-3.8.1/magic.txt @@ -0,0 +1,30 @@ +# This file contains suggested magic(5) text for the unix file(1) +# utility for recognizing SQLite3 databases. +# +# When SQLite is used as an application file format, it is desirable to +# have file(1) recognize the database file as being with the specific +# application. You can set the application_id for a database file +# using: +# +# PRAGMA application_id = INTEGER; +# +# INTEGER can be any signed 32-bit integer. That integer is written as +# a 4-byte big-endian integer into offset 68 of the database header. +# +# The Monotone application used "PRAGMA user_version=1598903374;" to set +# its identifier long before "PRAGMA application_id" became available. +# The user_version is very similar to application_id except that it is +# stored at offset 68 instead of offset 60. The application_id pragma +# is preferred. The rule using offset 60 for Monotone is for historical +# compatibility only. +# +0 string =SQLite\ format\ 3 +>68 belong =0x0f055112 Fossil checkout - +>68 belong =0x0f055113 Fossil global configuration - +>68 belong =0x0f055111 Fossil repository - +>68 belong =0x42654462 Bentley Systems BeSQLite Database - +>68 belong =0x42654c6e Bentley Systems Localization File - +>60 belong =0x5f4d544e Monotone source repository - +>68 belong =0x47504b47 OGC GeoPackage file - +>68 belong =0x47503130 OGC GeoPackage version 1.0 file - +>0 string =SQLite SQLite3 database diff --git a/components/external/SQLite-3.8.1/main.mk b/components/external/SQLite-3.8.1/main.mk new file mode 100644 index 0000000000000000000000000000000000000000..9eb384d9054398778d68bbe40ac279b7879ce065 --- /dev/null +++ b/components/external/SQLite-3.8.1/main.mk @@ -0,0 +1,666 @@ +############################################################################### +# The following macros should be defined before this script is +# invoked: +# +# TOP The toplevel directory of the source tree. This is the +# directory that contains this "Makefile.in" and the +# "configure.in" script. +# +# BCC C Compiler and options for use in building executables that +# will run on the platform that is doing the build. +# +# THREADLIB Specify any extra linker options needed to make the library +# thread safe +# +# OPTS Extra compiler command-line options. +# +# EXE The suffix to add to executable files. ".exe" for windows +# and "" for Unix. +# +# TCC C Compiler and options for use in building executables that +# will run on the target platform. This is usually the same +# as BCC, unless you are cross-compiling. +# +# AR Tools used to build a static library. +# RANLIB +# +# TCL_FLAGS Extra compiler options needed for programs that use the +# TCL library. +# +# LIBTCL Linker options needed to link against the TCL library. +# +# READLINE_FLAGS Compiler options needed for programs that use the +# readline() library. +# +# LIBREADLINE Linker options needed by programs using readline() must +# link against. +# +# NAWK Nawk compatible awk program. Older (obsolete?) solaris +# systems need this to avoid using the original AT&T AWK. +# +# Once the macros above are defined, the rest of this make script will +# build the SQLite library and testing tools. +################################################################################ + +# This is how we compile +# +TCCX = $(TCC) $(OPTS) -I. -I$(TOP)/src -I$(TOP) +TCCX += -I$(TOP)/ext/rtree -I$(TOP)/ext/icu -I$(TOP)/ext/fts3 +TCCX += -I$(TOP)/ext/async + +# Object files for the SQLite library. +# +LIBOBJ+= vdbe.o parse.o \ + alter.o analyze.o attach.o auth.o \ + backup.o bitvec.o btmutex.o btree.o build.o \ + callback.o complete.o ctime.o date.o delete.o expr.o fault.o fkey.o \ + fts3.o fts3_aux.o fts3_expr.o fts3_hash.o fts3_icu.o fts3_porter.o \ + fts3_snippet.o fts3_tokenizer.o fts3_tokenizer1.o \ + fts3_tokenize_vtab.o \ + fts3_unicode.o fts3_unicode2.o \ + fts3_write.o func.o global.o hash.o \ + icu.o insert.o journal.o legacy.o loadext.o \ + main.o malloc.o mem0.o mem1.o mem2.o mem3.o mem5.o \ + memjournal.o \ + mutex.o mutex_noop.o mutex_unix.o mutex_w32.o \ + notify.o opcodes.o os.o os_unix.o os_win.o \ + pager.o pcache.o pcache1.o pragma.o prepare.o printf.o \ + random.o resolve.o rowset.o rtree.o select.o status.o \ + table.o tokenize.o trigger.o \ + update.o util.o vacuum.o \ + vdbeapi.o vdbeaux.o vdbeblob.o vdbemem.o vdbesort.o \ + vdbetrace.o wal.o walker.o where.o utf.o vtab.o + + + +# All of the source code files. +# +SRC = \ + $(TOP)/src/alter.c \ + $(TOP)/src/analyze.c \ + $(TOP)/src/attach.c \ + $(TOP)/src/auth.c \ + $(TOP)/src/backup.c \ + $(TOP)/src/bitvec.c \ + $(TOP)/src/btmutex.c \ + $(TOP)/src/btree.c \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/build.c \ + $(TOP)/src/callback.c \ + $(TOP)/src/complete.c \ + $(TOP)/src/ctime.c \ + $(TOP)/src/date.c \ + $(TOP)/src/delete.c \ + $(TOP)/src/expr.c \ + $(TOP)/src/fault.c \ + $(TOP)/src/fkey.c \ + $(TOP)/src/func.c \ + $(TOP)/src/global.c \ + $(TOP)/src/hash.c \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + $(TOP)/src/insert.c \ + $(TOP)/src/journal.c \ + $(TOP)/src/legacy.c \ + $(TOP)/src/loadext.c \ + $(TOP)/src/main.c \ + $(TOP)/src/malloc.c \ + $(TOP)/src/mem0.c \ + $(TOP)/src/mem1.c \ + $(TOP)/src/mem2.c \ + $(TOP)/src/mem3.c \ + $(TOP)/src/mem5.c \ + $(TOP)/src/memjournal.c \ + $(TOP)/src/mutex.c \ + $(TOP)/src/mutex.h \ + $(TOP)/src/mutex_noop.c \ + $(TOP)/src/mutex_unix.c \ + $(TOP)/src/mutex_w32.c \ + $(TOP)/src/notify.c \ + $(TOP)/src/os.c \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/os_unix.c \ + $(TOP)/src/os_win.c \ + $(TOP)/src/pager.c \ + $(TOP)/src/pager.h \ + $(TOP)/src/parse.y \ + $(TOP)/src/pcache.c \ + $(TOP)/src/pcache.h \ + $(TOP)/src/pcache1.c \ + $(TOP)/src/pragma.c \ + $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c \ + $(TOP)/src/random.c \ + $(TOP)/src/resolve.c \ + $(TOP)/src/rowset.c \ + $(TOP)/src/select.c \ + $(TOP)/src/status.c \ + $(TOP)/src/shell.c \ + $(TOP)/src/sqlite.h.in \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/table.c \ + $(TOP)/src/tclsqlite.c \ + $(TOP)/src/tokenize.c \ + $(TOP)/src/trigger.c \ + $(TOP)/src/utf.c \ + $(TOP)/src/update.c \ + $(TOP)/src/util.c \ + $(TOP)/src/vacuum.c \ + $(TOP)/src/vdbe.c \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeapi.c \ + $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbeblob.c \ + $(TOP)/src/vdbemem.c \ + $(TOP)/src/vdbesort.c \ + $(TOP)/src/vdbetrace.c \ + $(TOP)/src/vdbeInt.h \ + $(TOP)/src/vtab.c \ + $(TOP)/src/wal.c \ + $(TOP)/src/wal.h \ + $(TOP)/src/walker.c \ + $(TOP)/src/where.c + +# Source code for extensions +# +SRC += \ + $(TOP)/ext/fts1/fts1.c \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.c \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_porter.c \ + $(TOP)/ext/fts1/fts1_tokenizer.h \ + $(TOP)/ext/fts1/fts1_tokenizer1.c +SRC += \ + $(TOP)/ext/fts2/fts2.c \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.c \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_icu.c \ + $(TOP)/ext/fts2/fts2_porter.c \ + $(TOP)/ext/fts2/fts2_tokenizer.h \ + $(TOP)/ext/fts2/fts2_tokenizer.c \ + $(TOP)/ext/fts2/fts2_tokenizer1.c +SRC += \ + $(TOP)/ext/fts3/fts3.c \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3Int.h \ + $(TOP)/ext/fts3/fts3_aux.c \ + $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_hash.c \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_icu.c \ + $(TOP)/ext/fts3/fts3_porter.c \ + $(TOP)/ext/fts3/fts3_snippet.c \ + $(TOP)/ext/fts3/fts3_tokenizer.h \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/fts3/fts3_tokenizer1.c \ + $(TOP)/ext/fts3/fts3_tokenize_vtab.c \ + $(TOP)/ext/fts3/fts3_unicode.c \ + $(TOP)/ext/fts3/fts3_unicode2.c \ + $(TOP)/ext/fts3/fts3_write.c +SRC += \ + $(TOP)/ext/icu/sqliteicu.h \ + $(TOP)/ext/icu/icu.c +SRC += \ + $(TOP)/ext/rtree/rtree.h \ + $(TOP)/ext/rtree/rtree.c + + +# Generated source code files +# +SRC += \ + keywordhash.h \ + opcodes.c \ + opcodes.h \ + parse.c \ + parse.h \ + sqlite3.h + + +# Source code to the test files. +# +TESTSRC = \ + $(TOP)/ext/fts3/fts3_term.c \ + $(TOP)/ext/fts3/fts3_test.c \ + $(TOP)/src/test1.c \ + $(TOP)/src/test2.c \ + $(TOP)/src/test3.c \ + $(TOP)/src/test4.c \ + $(TOP)/src/test5.c \ + $(TOP)/src/test6.c \ + $(TOP)/src/test7.c \ + $(TOP)/src/test8.c \ + $(TOP)/src/test9.c \ + $(TOP)/src/test_autoext.c \ + $(TOP)/src/test_async.c \ + $(TOP)/src/test_backup.c \ + $(TOP)/src/test_btree.c \ + $(TOP)/src/test_config.c \ + $(TOP)/src/test_demovfs.c \ + $(TOP)/src/test_devsym.c \ + $(TOP)/src/test_fs.c \ + $(TOP)/src/test_func.c \ + $(TOP)/src/test_hexio.c \ + $(TOP)/src/test_init.c \ + $(TOP)/src/test_intarray.c \ + $(TOP)/src/test_journal.c \ + $(TOP)/src/test_malloc.c \ + $(TOP)/src/test_multiplex.c \ + $(TOP)/src/test_mutex.c \ + $(TOP)/src/test_onefile.c \ + $(TOP)/src/test_osinst.c \ + $(TOP)/src/test_pcache.c \ + $(TOP)/src/test_quota.c \ + $(TOP)/src/test_rtree.c \ + $(TOP)/src/test_schema.c \ + $(TOP)/src/test_server.c \ + $(TOP)/src/test_stat.c \ + $(TOP)/src/test_sqllog.c \ + $(TOP)/src/test_superlock.c \ + $(TOP)/src/test_syscall.c \ + $(TOP)/src/test_tclvar.c \ + $(TOP)/src/test_thread.c \ + $(TOP)/src/test_vfs.c \ + $(TOP)/src/test_wsd.c + +# Extensions to be statically loaded. +# +TESTSRC += \ + $(TOP)/ext/misc/amatch.c \ + $(TOP)/ext/misc/closure.c \ + $(TOP)/ext/misc/fuzzer.c \ + $(TOP)/ext/misc/ieee754.c \ + $(TOP)/ext/misc/nextchar.c \ + $(TOP)/ext/misc/percentile.c \ + $(TOP)/ext/misc/regexp.c \ + $(TOP)/ext/misc/spellfix.c \ + $(TOP)/ext/misc/totype.c \ + $(TOP)/ext/misc/wholenumber.c \ + $(TOP)/ext/misc/vfslog.c + + +#TESTSRC += $(TOP)/ext/fts2/fts2_tokenizer.c +#TESTSRC += $(TOP)/ext/fts3/fts3_tokenizer.c + +TESTSRC2 = \ + $(TOP)/src/attach.c \ + $(TOP)/src/backup.c \ + $(TOP)/src/btree.c \ + $(TOP)/src/build.c \ + $(TOP)/src/date.c \ + $(TOP)/src/expr.c \ + $(TOP)/src/func.c \ + $(TOP)/src/insert.c \ + $(TOP)/src/wal.c \ + $(TOP)/src/main.c \ + $(TOP)/src/mem5.c \ + $(TOP)/src/os.c \ + $(TOP)/src/os_unix.c \ + $(TOP)/src/os_win.c \ + $(TOP)/src/pager.c \ + $(TOP)/src/pragma.c \ + $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c \ + $(TOP)/src/random.c \ + $(TOP)/src/pcache.c \ + $(TOP)/src/pcache1.c \ + $(TOP)/src/select.c \ + $(TOP)/src/tokenize.c \ + $(TOP)/src/utf.c \ + $(TOP)/src/util.c \ + $(TOP)/src/vdbeapi.c \ + $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbe.c \ + $(TOP)/src/vdbemem.c \ + $(TOP)/src/where.c \ + parse.c \ + $(TOP)/ext/fts3/fts3.c \ + $(TOP)/ext/fts3/fts3_aux.c \ + $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/fts3/fts3_write.c \ + $(TOP)/ext/async/sqlite3async.c + +# Header files used by all library source files. +# +HDR = \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + keywordhash.h \ + $(TOP)/src/mutex.h \ + opcodes.h \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/pager.h \ + $(TOP)/src/pcache.h \ + parse.h \ + sqlite3.h \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeInt.h + +# Header files used by extensions +# +EXTHDR += \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3Int.h \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_tokenizer.h +EXTHDR += \ + $(TOP)/ext/rtree/rtree.h +EXTHDR += \ + $(TOP)/ext/icu/sqliteicu.h + +# This is the default Makefile target. The objects listed here +# are what get build when you type just "make" with no arguments. +# +all: sqlite3.h libsqlite3.a sqlite3$(EXE) + +libsqlite3.a: $(LIBOBJ) + $(AR) libsqlite3.a $(LIBOBJ) + $(RANLIB) libsqlite3.a + +sqlite3$(EXE): $(TOP)/src/shell.c libsqlite3.a sqlite3.h + $(TCCX) $(READLINE_FLAGS) -o sqlite3$(EXE) \ + $(TOP)/src/shell.c \ + libsqlite3.a $(LIBREADLINE) $(TLIBS) $(THREADLIB) + +mptester$(EXE): sqlite3.c $(TOP)/mptest/mptest.c + $(TCCX) -o $@ -I. $(TOP)/mptest/mptest.c sqlite3.c \ + $(TLIBS) $(THREADLIB) + +sqlite3.o: sqlite3.c + $(TCCX) -c sqlite3.c + +# This target creates a directory named "tsrc" and fills it with +# copies of all of the C source code and header files needed to +# build on the target system. Some of the C source code and header +# files are automatically generated. This target takes care of +# all that automatic generation. +# +target_source: $(SRC) $(TOP)/tool/vdbe-compress.tcl + rm -rf tsrc + mkdir tsrc + cp -f $(SRC) tsrc + rm tsrc/sqlite.h.in tsrc/parse.y + tclsh $(TOP)/tool/vdbe-compress.tcl vdbe.new + mv vdbe.new tsrc/vdbe.c + touch target_source + +sqlite3.c: target_source $(TOP)/tool/mksqlite3c.tcl + tclsh $(TOP)/tool/mksqlite3c.tcl + cp tsrc/shell.c tsrc/sqlite3ext.h . + echo '#ifndef USE_SYSTEM_SQLITE' >tclsqlite3.c + cat sqlite3.c >>tclsqlite3.c + echo '#endif /* USE_SYSTEM_SQLITE */' >>tclsqlite3.c + cat $(TOP)/src/tclsqlite.c >>tclsqlite3.c + +sqlite3.c-debug: target_source $(TOP)/tool/mksqlite3c.tcl + tclsh $(TOP)/tool/mksqlite3c.tcl --linemacros + echo '#ifndef USE_SYSTEM_SQLITE' >tclsqlite3.c + cat sqlite3.c >>tclsqlite3.c + echo '#endif /* USE_SYSTEM_SQLITE */' >>tclsqlite3.c + echo '#line 1 "tclsqlite.c"' >>tclsqlite3.c + cat $(TOP)/src/tclsqlite.c >>tclsqlite3.c + +sqlite3-all.c: sqlite3.c $(TOP)/tool/split-sqlite3c.tcl + tclsh $(TOP)/tool/split-sqlite3c.tcl + +fts2amal.c: target_source $(TOP)/ext/fts2/mkfts2amal.tcl + tclsh $(TOP)/ext/fts2/mkfts2amal.tcl + +fts3amal.c: target_source $(TOP)/ext/fts3/mkfts3amal.tcl + tclsh $(TOP)/ext/fts3/mkfts3amal.tcl + +# Rules to build the LEMON compiler generator +# +lemon: $(TOP)/tool/lemon.c $(TOP)/src/lempar.c + $(BCC) -o lemon $(TOP)/tool/lemon.c + cp $(TOP)/src/lempar.c . + +# Rules to build individual *.o files from generated *.c files. This +# applies to: +# +# parse.o +# opcodes.o +# +%.o: %.c $(HDR) + $(TCCX) -c $< + +# Rules to build individual *.o files from files in the src directory. +# +%.o: $(TOP)/src/%.c $(HDR) + $(TCCX) -c $< + +tclsqlite.o: $(TOP)/src/tclsqlite.c $(HDR) + $(TCCX) $(TCL_FLAGS) -c $(TOP)/src/tclsqlite.c + + + +# Rules to build opcodes.c and opcodes.h +# +opcodes.c: opcodes.h $(TOP)/mkopcodec.awk + $(NAWK) -f $(TOP)/mkopcodec.awk opcodes.h >opcodes.c + +opcodes.h: parse.h $(TOP)/src/vdbe.c $(TOP)/mkopcodeh.awk + cat parse.h $(TOP)/src/vdbe.c | \ + $(NAWK) -f $(TOP)/mkopcodeh.awk >opcodes.h + +# Rules to build parse.c and parse.h - the outputs of lemon. +# +parse.h: parse.c + +parse.c: $(TOP)/src/parse.y lemon $(TOP)/addopcodes.awk + cp $(TOP)/src/parse.y . + rm -f parse.h + ./lemon $(OPTS) parse.y + mv parse.h parse.h.temp + $(NAWK) -f $(TOP)/addopcodes.awk parse.h.temp >parse.h + +sqlite3.h: $(TOP)/src/sqlite.h.in $(TOP)/manifest.uuid $(TOP)/VERSION + tclsh $(TOP)/tool/mksqlite3h.tcl $(TOP) >sqlite3.h + +keywordhash.h: $(TOP)/tool/mkkeywordhash.c + $(BCC) -o mkkeywordhash $(OPTS) $(TOP)/tool/mkkeywordhash.c + ./mkkeywordhash >keywordhash.h + + + +# Rules to build the extension objects. +# +icu.o: $(TOP)/ext/icu/icu.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/icu/icu.c + +fts2.o: $(TOP)/ext/fts2/fts2.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2.c + +fts2_hash.o: $(TOP)/ext/fts2/fts2_hash.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_hash.c + +fts2_icu.o: $(TOP)/ext/fts2/fts2_icu.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_icu.c + +fts2_porter.o: $(TOP)/ext/fts2/fts2_porter.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_porter.c + +fts2_tokenizer.o: $(TOP)/ext/fts2/fts2_tokenizer.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer.c + +fts2_tokenizer1.o: $(TOP)/ext/fts2/fts2_tokenizer1.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer1.c + +fts3.o: $(TOP)/ext/fts3/fts3.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3.c + +fts3_aux.o: $(TOP)/ext/fts3/fts3_aux.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_aux.c + +fts3_expr.o: $(TOP)/ext/fts3/fts3_expr.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_expr.c + +fts3_hash.o: $(TOP)/ext/fts3/fts3_hash.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_hash.c + +fts3_icu.o: $(TOP)/ext/fts3/fts3_icu.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_icu.c + +fts3_snippet.o: $(TOP)/ext/fts3/fts3_snippet.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_snippet.c + +fts3_porter.o: $(TOP)/ext/fts3/fts3_porter.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_porter.c + +fts3_tokenizer.o: $(TOP)/ext/fts3/fts3_tokenizer.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer.c + +fts3_tokenizer1.o: $(TOP)/ext/fts3/fts3_tokenizer1.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer1.c + +fts3_tokenize_vtab.o: $(TOP)/ext/fts3/fts3_tokenize_vtab.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenize_vtab.c + +fts3_unicode.o: $(TOP)/ext/fts3/fts3_unicode.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_unicode.c + +fts3_unicode2.o: $(TOP)/ext/fts3/fts3_unicode2.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_unicode2.c + +fts3_write.o: $(TOP)/ext/fts3/fts3_write.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_write.c + +rtree.o: $(TOP)/ext/rtree/rtree.c $(HDR) $(EXTHDR) + $(TCCX) -DSQLITE_CORE -c $(TOP)/ext/rtree/rtree.c + + +# Rules for building test programs and for running tests +# +tclsqlite3: $(TOP)/src/tclsqlite.c libsqlite3.a + $(TCCX) $(TCL_FLAGS) -DTCLSH=1 -o tclsqlite3 \ + $(TOP)/src/tclsqlite.c libsqlite3.a $(LIBTCL) $(THREADLIB) + +sqlite3_analyzer.c: sqlite3.c $(TOP)/src/test_stat.c $(TOP)/src/tclsqlite.c $(TOP)/tool/spaceanal.tcl + echo "#define TCLSH 2" > $@ + cat sqlite3.c $(TOP)/src/test_stat.c $(TOP)/src/tclsqlite.c >> $@ + echo "static const char *tclsh_main_loop(void){" >> $@ + echo "static const char *zMainloop = " >> $@ + $(NAWK) -f $(TOP)/tool/tostr.awk $(TOP)/tool/spaceanal.tcl >> $@ + echo "; return zMainloop; }" >> $@ + +sqlite3_analyzer$(EXE): sqlite3_analyzer.c + $(TCCX) $(TCL_FLAGS) sqlite3_analyzer.c -o $@ $(LIBTCL) $(THREADLIB) + +# Rules to build the 'testfixture' application. +# +TESTFIXTURE_FLAGS = -DSQLITE_TEST=1 -DSQLITE_CRASH_TEST=1 +TESTFIXTURE_FLAGS += -DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE + +testfixture$(EXE): $(TESTSRC2) libsqlite3.a $(TESTSRC) $(TOP)/src/tclsqlite.c + $(TCCX) $(TCL_FLAGS) -DTCLSH=1 $(TESTFIXTURE_FLAGS) \ + $(TESTSRC) $(TESTSRC2) $(TOP)/src/tclsqlite.c \ + -o testfixture$(EXE) $(LIBTCL) libsqlite3.a $(THREADLIB) + +amalgamation-testfixture$(EXE): sqlite3.c $(TESTSRC) $(TOP)/src/tclsqlite.c + $(TCCX) $(TCL_FLAGS) -DTCLSH=1 $(TESTFIXTURE_FLAGS) \ + $(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c \ + -o testfixture$(EXE) $(LIBTCL) $(THREADLIB) + +fts3-testfixture$(EXE): sqlite3.c fts3amal.c $(TESTSRC) $(TOP)/src/tclsqlite.c + $(TCCX) $(TCL_FLAGS) -DTCLSH=1 $(TESTFIXTURE_FLAGS) \ + -DSQLITE_ENABLE_FTS3=1 \ + $(TESTSRC) $(TOP)/src/tclsqlite.c sqlite3.c fts3amal.c \ + -o testfixture$(EXE) $(LIBTCL) $(THREADLIB) + +fulltest: testfixture$(EXE) sqlite3$(EXE) + ./testfixture$(EXE) $(TOP)/test/all.test + +soaktest: testfixture$(EXE) sqlite3$(EXE) + ./testfixture$(EXE) $(TOP)/test/all.test -soak=1 + +fulltestonly: testfixture$(EXE) sqlite3$(EXE) + ./testfixture$(EXE) $(TOP)/test/full.test + +queryplantest: testfixture$(EXE) sqlite3$(EXE) + ./testfixture$(EXE) $(TOP)/test/permutations.test queryplanner + +test: testfixture$(EXE) sqlite3$(EXE) + ./testfixture$(EXE) $(TOP)/test/veryquick.test + +# The next two rules are used to support the "threadtest" target. Building +# threadtest runs a few thread-safety tests that are implemented in C. This +# target is invoked by the releasetest.tcl script. +# +threadtest3$(EXE): sqlite3.o $(TOP)/test/threadtest3.c $(TOP)/test/tt3_checkpoint.c + $(TCCX) -O2 sqlite3.o $(TOP)/test/threadtest3.c \ + -o threadtest3$(EXE) $(THREADLIB) + +threadtest: threadtest3$(EXE) + ./threadtest3$(EXE) + +TEST_EXTENSION = $(SHPREFIX)testloadext.$(SO) +$(TEST_EXTENSION): $(TOP)/src/test_loadext.c + $(MKSHLIB) $(TOP)/src/test_loadext.c -o $(TEST_EXTENSION) + +extensiontest: testfixture$(EXE) $(TEST_EXTENSION) + ./testfixture$(EXE) $(TOP)/test/loadext.test + +showdb: $(TOP)/tool/showdb.c sqlite3.c + $(TCC) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -o showdb \ + $(TOP)/tool/showdb.c sqlite3.c + +# This target will fail if the SQLite amalgamation contains any exported +# symbols that do not begin with "sqlite3_". It is run as part of the +# releasetest.tcl script. +# +checksymbols: sqlite3.o + nm -g --defined-only sqlite3.o | grep -v " sqlite3_" ; test $$? -ne 0 + +# Build the amalgamation-autoconf package. +# +dist: sqlite3.c + TOP=$(TOP) sh $(TOP)/tool/mkautoconfamal.sh + + +# Standard install and cleanup targets +# +install: sqlite3 libsqlite3.a sqlite3.h + mv sqlite3 /usr/bin + mv libsqlite3.a /usr/lib + mv sqlite3.h /usr/include + +clean: + rm -f *.o sqlite3 sqlite3.exe libsqlite3.a sqlite3.h opcodes.* + rm -f lemon lemon.exe lempar.c parse.* sqlite*.tar.gz + rm -f mkkeywordhash mkkeywordhash.exe keywordhash.h + rm -f $(PUBLISH) + rm -f *.da *.bb *.bbg gmon.out + rm -rf quota2a quota2b quota2c + rm -rf tsrc target_source + rm -f testloadext.dll libtestloadext.so + rm -f amalgamation-testfixture amalgamation-testfixture.exe + rm -f fts3-testfixture fts3-testfixture.exe + rm -f testfixture testfixture.exe + rm -f threadtest3 threadtest3.exe + rm -f sqlite3.c sqlite3-*.c fts?amal.c tclsqlite3.c + rm -f sqlite3rc.h + rm -f shell.c sqlite3ext.h + rm -f sqlite3_analyzer sqlite3_analyzer.exe sqlite3_analyzer.c + rm -f sqlite-*-output.vsix + rm -f mptester mptester.exe + rm -f showdb diff --git a/components/external/SQLite-3.8.1/make/Makefile b/components/external/SQLite-3.8.1/make/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..f8d829eee3195efa1f78186de4b598b61cb89a4e --- /dev/null +++ b/components/external/SQLite-3.8.1/make/Makefile @@ -0,0 +1,979 @@ +#!/usr/make +# +# Makefile for SQLITE +# +# This makefile is suppose to be configured automatically using the +# autoconf. But if that does not work for you, you can configure +# the makefile manually. Just set the parameters below to values that +# work well for your system. +# +# If the configure script does not work out-of-the-box, you might +# be able to get it to work by giving it some hints. See the comment +# at the beginning of configure.in for additional information. +# + +# The toplevel directory of the source tree. This is the directory +# that contains this "Makefile.in" and the "configure.in" script. +# +TOP = .. + +# C Compiler and options for use in building executables that +# will run on the platform that is doing the build. +# +BCC = gcc -g + +# C Compile and options for use in building executables that +# will run on the target platform. (BCC and TCC are usually the +# same unless your are cross-compiling.) +# +TCC = arm-none-eabi-gcc -g -O2 \ + -DSQLITE_OS_OTHER=1 -DSQLITE_OS_RTTHREAD=1 \ + -I. -I${TOP}/src -I${TOP}/ext/rtree \ + -I../../../../include \ + -I../../../../components/dfs/include \ + -I../../../../components/libc/newlib \ + -I../../../../components/libc/newlib/sys \ + -I../../../../bsp/mini2440 + +# Define this for the autoconf-based build, so that the code knows it can +# include the generated config.h +# +TCC += -D_HAVE_SQLITE_CONFIG_H -DBUILD_sqlite + +# Define -DNDEBUG to compile without debugging (i.e., for production usage) +# Omitting the define will cause extra debugging code to be inserted and +# includes extra comments when "EXPLAIN stmt" is used. +# +TCC += -DNDEBUG + +# Compiler options needed for programs that use the TCL library. +# +TCC += -I/usr/include + +# The library that programs using TCL must link against. +# +LIBTCL = -L/usr/lib -ltcl8.5 + +# Compiler options needed for programs that use the readline() library. +# +READLINE_FLAGS = -DHAVE_READLINE=0 + +# The library that programs using readline() must link against. +# +LIBREADLINE = + +# Should the database engine be compiled threadsafe +# +TCC += -DSQLITE_THREADSAFE=1 + +# Any target libraries which libsqlite must be linked against +# +TLIBS = + +# Flags controlling use of the in memory btree implementation +# +# SQLITE_TEMP_STORE is 0 to force temporary tables to be in a file, 1 to +# default to file, 2 to default to memory, and 3 to force temporary +# tables to always be in memory. +# +TEMP_STORE = -DSQLITE_TEMP_STORE=1 + +# Enable/disable loadable extensions, and other optional features +# based on configuration. (-DSQLITE_OMIT*, -DSQLITE_ENABLE*). +# The same set of OMIT and ENABLE flags should be passed to the +# LEMON parser generator and the mkkeywordhash tool as well. +OPT_FEATURE_FLAGS = -DSQLITE_OMIT_LOAD_EXTENSION=1 -DSQLITE_RTTHREAD_NO_WIDE=1 \ + -DSQLITE_OMIT_WAL -DSQLITE_ENABLE_LOCKING_STYLE=0 \ + -DSQLITE_DISABLE_LOCKING_STYLE=1 + +TCC += $(OPT_FEATURE_FLAGS) + +# Add in any optional parameters specified on the make commane line +# ie. make "OPTS=-DSQLITE_ENABLE_FOO=1 -DSQLITE_OMIT_FOO=1". +TCC += $(OPTS) + +# Version numbers and release number for the SQLite being compiled. +# +VERSION = 3.8 +VERSION_NUMBER = 3008001 +RELEASE = 3.8.1 + +# Filename extensions +# +BEXE = +TEXE = + +# The following variable is "1" if the configure script was able to locate +# the tclConfig.sh file. It is an empty string otherwise. When this +# variable is "1", the TCL extension library (libtclsqlite3.so) is built +# and installed. +# +HAVE_TCL = 1 + +# This is the command to use for tclsh - normally just "tclsh", but we may +# know the specific version we want to use +# +TCLSH_CMD = tclsh8.5 + +# Where do we want to install the tcl plugin +# +TCLLIBDIR = /usr/lib/tcl8.5/sqlite3 + +# The suffix used on shared libraries. Ex: ".dll", ".so", ".dylib" +# +SHLIB_SUFFIX = @TCL_SHLIB_SUFFIX@ + +# If gcov support was enabled by the configure script, add the appropriate +# flags here. It's not always as easy as just having the user add the right +# CFLAGS / LDFLAGS, because libtool wants to use CFLAGS when linking, which +# causes build errors with -fprofile-arcs -ftest-coverage with some GCCs. +# Supposedly GCC does the right thing if you use --coverage, but in +# practice it still fails. See: +# +# http://www.mail-archive.com/debian-gcc@lists.debian.org/msg26197.html +# +# for more info. +# +GCOV_CFLAGS1 = -DSQLITE_COVERAGE_TEST=1 -fprofile-arcs -ftest-coverage +GCOV_LDFLAGS1 = -lgcov +USE_GCOV = 0 +LTCOMPILE_EXTRAS += $(GCOV_CFLAGS$(USE_GCOV)) +LTLINK_EXTRAS += $(GCOV_LDFLAGS$(USE_GCOV)) + + +# The directory into which to store package information for + +# Some standard variables and programs +# +prefix = /usr/local +exec_prefix = ${prefix} +libdir = ${exec_prefix}/lib +pkgconfigdir = $(libdir)/pkgconfig +bindir = ${exec_prefix}/bin +includedir = ${prefix}/include +INSTALL = /usr/bin/install -c +LIBTOOL = ./libtool +ALLOWRELEASE = + +# libtool compile/link/install +LTCOMPILE = $(LIBTOOL) --mode=compile --tag=CC $(TCC) $(LTCOMPILE_EXTRAS) +LTLINK = $(LIBTOOL) --mode=link $(TCC) $(LTCOMPILE_EXTRAS) $(LTLINK_EXTRAS) +LTINSTALL = $(LIBTOOL) --mode=install $(INSTALL) + +# nawk compatible awk. +NAWK = gawk + +# You should not have to change anything below this line +############################################################################### + +USE_AMALGAMATION = 1 + +# Object files for the SQLite library (non-amalgamation). +# +LIBOBJS0 = alter.lo analyze.lo attach.lo auth.lo \ + backup.lo bitvec.lo btmutex.lo btree.lo build.lo \ + callback.lo complete.lo ctime.lo date.lo delete.lo \ + expr.lo fault.lo fkey.lo \ + fts3.lo fts3_aux.lo fts3_expr.lo fts3_hash.lo fts3_icu.lo \ + fts3_porter.lo fts3_snippet.lo fts3_tokenizer.lo fts3_tokenizer1.lo \ + fts3_tokenize_vtab.lo \ + fts3_unicode.lo fts3_unicode2.lo fts3_write.lo \ + func.lo global.lo hash.lo \ + icu.lo insert.lo journal.lo legacy.lo loadext.lo \ + main.lo malloc.lo mem0.lo mem1.lo mem2.lo mem3.lo mem5.lo \ + memjournal.lo \ + mutex.lo mutex_noop.lo mutex_rtthread.lo \ + notify.lo opcodes.lo os.lo os_rtthread.lo \ + pager.lo parse.lo pcache.lo pcache1.lo pragma.lo prepare.lo printf.lo \ + random.lo resolve.lo rowset.lo rtree.lo select.lo status.lo \ + table.lo tokenize.lo trigger.lo \ + update.lo util.lo vacuum.lo \ + vdbe.lo vdbeapi.lo vdbeaux.lo vdbeblob.lo vdbemem.lo vdbesort.lo \ + vdbetrace.lo wal.lo walker.lo where.lo utf.lo vtab.lo + +# Object files for the amalgamation. +# +LIBOBJS1 = sqlite3.lo + +# Determine the real value of LIBOBJ based on the 'configure' script +# +LIBOBJ = $(LIBOBJS$(USE_AMALGAMATION)) + + +# All of the source code files. +# +SRC = \ + $(TOP)/src/alter.c \ + $(TOP)/src/analyze.c \ + $(TOP)/src/attach.c \ + $(TOP)/src/auth.c \ + $(TOP)/src/backup.c \ + $(TOP)/src/bitvec.c \ + $(TOP)/src/btmutex.c \ + $(TOP)/src/btree.c \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/build.c \ + $(TOP)/src/callback.c \ + $(TOP)/src/complete.c \ + $(TOP)/src/ctime.c \ + $(TOP)/src/date.c \ + $(TOP)/src/delete.c \ + $(TOP)/src/expr.c \ + $(TOP)/src/fault.c \ + $(TOP)/src/fkey.c \ + $(TOP)/src/func.c \ + $(TOP)/src/global.c \ + $(TOP)/src/hash.c \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + $(TOP)/src/insert.c \ + $(TOP)/src/journal.c \ + $(TOP)/src/legacy.c \ + $(TOP)/src/loadext.c \ + $(TOP)/src/main.c \ + $(TOP)/src/malloc.c \ + $(TOP)/src/mem0.c \ + $(TOP)/src/mem1.c \ + $(TOP)/src/mem2.c \ + $(TOP)/src/mem3.c \ + $(TOP)/src/mem5.c \ + $(TOP)/src/memjournal.c \ + $(TOP)/src/mutex.c \ + $(TOP)/src/mutex.h \ + $(TOP)/src/mutex_noop.c \ + $(TOP)/src/mutex_rtthread.c \ + $(TOP)/src/notify.c \ + $(TOP)/src/os.c \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/os_rtthread.c \ + $(TOP)/src/pager.c \ + $(TOP)/src/pager.h \ + $(TOP)/src/parse.y \ + $(TOP)/src/pcache.c \ + $(TOP)/src/pcache.h \ + $(TOP)/src/pcache1.c \ + $(TOP)/src/pragma.c \ + $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c \ + $(TOP)/src/random.c \ + $(TOP)/src/resolve.c \ + $(TOP)/src/rowset.c \ + $(TOP)/src/select.c \ + $(TOP)/src/status.c \ + $(TOP)/src/shell.c \ + $(TOP)/src/sqlite.h.in \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/table.c \ + $(TOP)/src/tclsqlite.c \ + $(TOP)/src/tokenize.c \ + $(TOP)/src/trigger.c \ + $(TOP)/src/utf.c \ + $(TOP)/src/update.c \ + $(TOP)/src/util.c \ + $(TOP)/src/vacuum.c \ + $(TOP)/src/vdbe.c \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeapi.c \ + $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbeblob.c \ + $(TOP)/src/vdbemem.c \ + $(TOP)/src/vdbesort.c \ + $(TOP)/src/vdbetrace.c \ + $(TOP)/src/vdbeInt.h \ + $(TOP)/src/vtab.c \ + $(TOP)/src/wal.c \ + $(TOP)/src/wal.h \ + $(TOP)/src/walker.c \ + $(TOP)/src/where.c + +# Source code for extensions +# +SRC += \ + $(TOP)/ext/fts1/fts1.c \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.c \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_porter.c \ + $(TOP)/ext/fts1/fts1_tokenizer.h \ + $(TOP)/ext/fts1/fts1_tokenizer1.c +SRC += \ + $(TOP)/ext/fts2/fts2.c \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.c \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_icu.c \ + $(TOP)/ext/fts2/fts2_porter.c \ + $(TOP)/ext/fts2/fts2_tokenizer.h \ + $(TOP)/ext/fts2/fts2_tokenizer.c \ + $(TOP)/ext/fts2/fts2_tokenizer1.c +SRC += \ + $(TOP)/ext/fts3/fts3.c \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3Int.h \ + $(TOP)/ext/fts3/fts3_aux.c \ + $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_hash.c \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_icu.c \ + $(TOP)/ext/fts3/fts3_porter.c \ + $(TOP)/ext/fts3/fts3_snippet.c \ + $(TOP)/ext/fts3/fts3_tokenizer.h \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/fts3/fts3_tokenizer1.c \ + $(TOP)/ext/fts3/fts3_tokenize_vtab.c \ + $(TOP)/ext/fts3/fts3_unicode.c \ + $(TOP)/ext/fts3/fts3_unicode2.c \ + $(TOP)/ext/fts3/fts3_write.c +SRC += \ + $(TOP)/ext/icu/sqliteicu.h \ + $(TOP)/ext/icu/icu.c +SRC += \ + $(TOP)/ext/rtree/rtree.h \ + $(TOP)/ext/rtree/rtree.c + + +# Generated source code files +# +SRC += \ + keywordhash.h \ + opcodes.c \ + opcodes.h \ + parse.c \ + parse.h \ + config.h \ + sqlite3.h + +# Source code to the test files. +# +TESTSRC = \ + $(TOP)/src/test1.c \ + $(TOP)/src/test2.c \ + $(TOP)/src/test3.c \ + $(TOP)/src/test4.c \ + $(TOP)/src/test5.c \ + $(TOP)/src/test6.c \ + $(TOP)/src/test7.c \ + $(TOP)/src/test8.c \ + $(TOP)/src/test9.c \ + $(TOP)/src/test_autoext.c \ + $(TOP)/src/test_async.c \ + $(TOP)/src/test_backup.c \ + $(TOP)/src/test_btree.c \ + $(TOP)/src/test_config.c \ + $(TOP)/src/test_demovfs.c \ + $(TOP)/src/test_devsym.c \ + $(TOP)/src/test_fs.c \ + $(TOP)/src/test_func.c \ + $(TOP)/src/test_hexio.c \ + $(TOP)/src/test_init.c \ + $(TOP)/src/test_intarray.c \ + $(TOP)/src/test_journal.c \ + $(TOP)/src/test_malloc.c \ + $(TOP)/src/test_multiplex.c \ + $(TOP)/src/test_mutex.c \ + $(TOP)/src/test_onefile.c \ + $(TOP)/src/test_osinst.c \ + $(TOP)/src/test_pcache.c \ + $(TOP)/src/test_quota.c \ + $(TOP)/src/test_rtree.c \ + $(TOP)/src/test_schema.c \ + $(TOP)/src/test_server.c \ + $(TOP)/src/test_superlock.c \ + $(TOP)/src/test_syscall.c \ + $(TOP)/src/test_stat.c \ + $(TOP)/src/test_tclvar.c \ + $(TOP)/src/test_thread.c \ + $(TOP)/src/test_vfs.c \ + $(TOP)/src/test_wsd.c \ + $(TOP)/ext/fts3/fts3_term.c \ + $(TOP)/ext/fts3/fts3_test.c + +# Statically linked extensions +# +TESTSRC += \ + $(TOP)/ext/misc/amatch.c \ + $(TOP)/ext/misc/closure.c \ + $(TOP)/ext/misc/fuzzer.c \ + $(TOP)/ext/misc/ieee754.c \ + $(TOP)/ext/misc/nextchar.c \ + $(TOP)/ext/misc/percentile.c \ + $(TOP)/ext/misc/regexp.c \ + $(TOP)/ext/misc/spellfix.c \ + $(TOP)/ext/misc/totype.c \ + $(TOP)/ext/misc/wholenumber.c + +# Source code to the library files needed by the test fixture +# +TESTSRC2 = \ + $(TOP)/src/attach.c \ + $(TOP)/src/backup.c \ + $(TOP)/src/bitvec.c \ + $(TOP)/src/btree.c \ + $(TOP)/src/build.c \ + $(TOP)/src/ctime.c \ + $(TOP)/src/date.c \ + $(TOP)/src/expr.c \ + $(TOP)/src/func.c \ + $(TOP)/src/insert.c \ + $(TOP)/src/wal.c \ + $(TOP)/src/main.c \ + $(TOP)/src/mem5.c \ + $(TOP)/src/os.c \ + $(TOP)/src/os_unix.c \ + $(TOP)/src/os_win.c \ + $(TOP)/src/pager.c \ + $(TOP)/src/pragma.c \ + $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c \ + $(TOP)/src/random.c \ + $(TOP)/src/pcache.c \ + $(TOP)/src/pcache1.c \ + $(TOP)/src/select.c \ + $(TOP)/src/tokenize.c \ + $(TOP)/src/utf.c \ + $(TOP)/src/util.c \ + $(TOP)/src/vdbeapi.c \ + $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbe.c \ + $(TOP)/src/vdbemem.c \ + $(TOP)/src/vdbetrace.c \ + $(TOP)/src/where.c \ + parse.c \ + $(TOP)/ext/fts3/fts3.c \ + $(TOP)/ext/fts3/fts3_aux.c \ + $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_term.c \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/fts3/fts3_write.c \ + $(TOP)/ext/async/sqlite3async.c + +# Header files used by all library source files. +# +HDR = \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + keywordhash.h \ + $(TOP)/src/mutex.h \ + opcodes.h \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/pager.h \ + $(TOP)/src/pcache.h \ + parse.h \ + sqlite3.h \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeInt.h \ + config.h + +# Header files used by extensions +# +EXTHDR += \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3Int.h \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_tokenizer.h +EXTHDR += \ + $(TOP)/ext/rtree/rtree.h +EXTHDR += \ + $(TOP)/ext/icu/sqliteicu.h +EXTHDR += \ + $(TOP)/ext/rtree/sqlite3rtree.h + +# This is the default Makefile target. The objects listed here +# are what get build when you type just "make" with no arguments. +# +all: sqlite3.h libsqlite3.la sqlite3$(TEXE) $(HAVE_TCL:1=libtclsqlite3.la) + +Makefile: $(TOP)/Makefile.in + ./config.status + +sqlite3.pc: $(TOP)/sqlite3.pc.in + ./config.status + +libsqlite3.la: $(LIBOBJ) + $(LTLINK) -no-undefined -o $@ $(LIBOBJ) $(TLIBS) \ + ${ALLOWRELEASE} -rpath "$(libdir)" -version-info "8:6:8" + +libtclsqlite3.la: tclsqlite.lo libsqlite3.la + $(LTLINK) -no-undefined -o $@ tclsqlite.lo \ + libsqlite3.la -Wl,-ltclstub8.5 $(TLIBS) \ + -rpath "$(TCLLIBDIR)" \ + -version-info "8:6:8" \ + -avoid-version + +sqlite3$(TEXE): $(TOP)/src/shell.c libsqlite3.la sqlite3.h + $(LTLINK) $(READLINE_FLAGS) \ + -o $@ $(TOP)/src/shell.c libsqlite3.la \ + $(LIBREADLINE) $(TLIBS) -rpath "$(libdir)" + +mptester$(EXE): sqlite3.c $(TOP)/mptest/mptest.c + $(LTLINK) -o $@ -I. $(TOP)/mptest/mptest.c sqlite3.c \ + $(TLIBS) -rpath "$(libdir)" + + +# This target creates a directory named "tsrc" and fills it with +# copies of all of the C source code and header files needed to +# build on the target system. Some of the C source code and header +# files are automatically generated. This target takes care of +# all that automatic generation. +# +.target_source: $(SRC) $(TOP)/tool/vdbe-compress.tcl + rm -rf tsrc + mkdir tsrc + cp -f $(SRC) tsrc + rm tsrc/sqlite.h.in tsrc/parse.y + $(TCLSH_CMD) $(TOP)/tool/vdbe-compress.tcl vdbe.new + mv vdbe.new tsrc/vdbe.c + touch .target_source + +sqlite3.c: .target_source $(TOP)/tool/mksqlite3c.tcl + $(TCLSH_CMD) $(TOP)/tool/mksqlite3c.tcl + cp tsrc/shell.c tsrc/sqlite3ext.h . + +tclsqlite3.c: sqlite3.c + echo '#ifndef USE_SYSTEM_SQLITE' >tclsqlite3.c + cat sqlite3.c >>tclsqlite3.c + echo '#endif /* USE_SYSTEM_SQLITE */' >>tclsqlite3.c + cat $(TOP)/src/tclsqlite.c >>tclsqlite3.c + +sqlite3-all.c: sqlite3.c $(TOP)/tool/split-sqlite3c.tcl + $(TCLSH_CMD) $(TOP)/tool/split-sqlite3c.tcl + +# Rule to build the amalgamation +# +sqlite3.lo: sqlite3.c + $(LTCOMPILE) $(TEMP_STORE) -c sqlite3.c + +# Rules to build the LEMON compiler generator +# +lemon$(BEXE): $(TOP)/tool/lemon.c $(TOP)/src/lempar.c + $(BCC) -o $@ $(TOP)/tool/lemon.c + cp $(TOP)/src/lempar.c . + +# Rules to build individual *.o files from generated *.c files. This +# applies to: +# +# parse.o +# opcodes.o +# +parse.lo: parse.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c parse.c + +opcodes.lo: opcodes.c + $(LTCOMPILE) $(TEMP_STORE) -c opcodes.c + +# Rules to build individual *.o files from files in the src directory. +# +alter.lo: $(TOP)/src/alter.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/alter.c + +analyze.lo: $(TOP)/src/analyze.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/analyze.c + +attach.lo: $(TOP)/src/attach.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/attach.c + +auth.lo: $(TOP)/src/auth.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/auth.c + +backup.lo: $(TOP)/src/backup.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/backup.c + +bitvec.lo: $(TOP)/src/bitvec.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/bitvec.c + +btmutex.lo: $(TOP)/src/btmutex.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/btmutex.c + +btree.lo: $(TOP)/src/btree.c $(HDR) $(TOP)/src/pager.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/btree.c + +build.lo: $(TOP)/src/build.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/build.c + +callback.lo: $(TOP)/src/callback.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/callback.c + +complete.lo: $(TOP)/src/complete.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/complete.c + +ctime.lo: $(TOP)/src/ctime.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/ctime.c + +date.lo: $(TOP)/src/date.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/date.c + +delete.lo: $(TOP)/src/delete.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/delete.c + +expr.lo: $(TOP)/src/expr.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/expr.c + +fault.lo: $(TOP)/src/fault.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/fault.c + +fkey.lo: $(TOP)/src/fkey.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/fkey.c + +func.lo: $(TOP)/src/func.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/func.c + +global.lo: $(TOP)/src/global.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/global.c + +hash.lo: $(TOP)/src/hash.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/hash.c + +insert.lo: $(TOP)/src/insert.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/insert.c + +journal.lo: $(TOP)/src/journal.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/journal.c + +legacy.lo: $(TOP)/src/legacy.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/legacy.c + +loadext.lo: $(TOP)/src/loadext.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/loadext.c + +main.lo: $(TOP)/src/main.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/main.c + +malloc.lo: $(TOP)/src/malloc.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/malloc.c + +mem0.lo: $(TOP)/src/mem0.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem0.c + +mem1.lo: $(TOP)/src/mem1.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem1.c + +mem2.lo: $(TOP)/src/mem2.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem2.c + +mem3.lo: $(TOP)/src/mem3.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem3.c + +mem5.lo: $(TOP)/src/mem5.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem5.c + +memjournal.lo: $(TOP)/src/memjournal.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/memjournal.c + +mutex.lo: $(TOP)/src/mutex.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex.c + +mutex_noop.lo: $(TOP)/src/mutex_noop.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_noop.c + +mutex_rtthread.lo: $(TOP)/src/mutex_rtthread.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_rtthread.c + +notify.lo: $(TOP)/src/notify.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/notify.c + +pager.lo: $(TOP)/src/pager.c $(HDR) $(TOP)/src/pager.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pager.c + +pcache.lo: $(TOP)/src/pcache.c $(HDR) $(TOP)/src/pcache.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pcache.c + +pcache1.lo: $(TOP)/src/pcache1.c $(HDR) $(TOP)/src/pcache.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pcache1.c + +os.lo: $(TOP)/src/os.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os.c + +os_rtthread.lo:$(TOP)/src/os_rtthread.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_rtthread.c + +pragma.lo: $(TOP)/src/pragma.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pragma.c + +prepare.lo: $(TOP)/src/prepare.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/prepare.c + +printf.lo: $(TOP)/src/printf.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/printf.c + +random.lo: $(TOP)/src/random.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/random.c + +resolve.lo: $(TOP)/src/resolve.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/resolve.c + +rowset.lo: $(TOP)/src/rowset.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/rowset.c + +select.lo: $(TOP)/src/select.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/select.c + +status.lo: $(TOP)/src/status.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/status.c + +table.lo: $(TOP)/src/table.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/table.c + +tokenize.lo: $(TOP)/src/tokenize.c keywordhash.h $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/tokenize.c + +trigger.lo: $(TOP)/src/trigger.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/trigger.c + +update.lo: $(TOP)/src/update.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/update.c + +utf.lo: $(TOP)/src/utf.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/utf.c + +util.lo: $(TOP)/src/util.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/util.c + +vacuum.lo: $(TOP)/src/vacuum.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vacuum.c + +vdbe.lo: $(TOP)/src/vdbe.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbe.c + +vdbeapi.lo: $(TOP)/src/vdbeapi.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeapi.c + +vdbeaux.lo: $(TOP)/src/vdbeaux.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeaux.c + +vdbeblob.lo: $(TOP)/src/vdbeblob.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeblob.c + +vdbemem.lo: $(TOP)/src/vdbemem.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbemem.c + +vdbesort.lo: $(TOP)/src/vdbesort.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbesort.c + +vdbetrace.lo: $(TOP)/src/vdbetrace.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbetrace.c + +vtab.lo: $(TOP)/src/vtab.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vtab.c + +wal.lo: $(TOP)/src/wal.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/wal.c + +walker.lo: $(TOP)/src/walker.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/walker.c + +where.lo: $(TOP)/src/where.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/where.c + +tclsqlite.lo: $(TOP)/src/tclsqlite.c $(HDR) + $(LTCOMPILE) -DUSE_TCL_STUBS=1 -c $(TOP)/src/tclsqlite.c + +tclsqlite-shell.lo: $(TOP)/src/tclsqlite.c $(HDR) + $(LTCOMPILE) -DTCLSH=1 -o $@ -c $(TOP)/src/tclsqlite.c + +tclsqlite-stubs.lo: $(TOP)/src/tclsqlite.c $(HDR) + $(LTCOMPILE) -DUSE_TCL_STUBS=1 -o $@ -c $(TOP)/src/tclsqlite.c + +tclsqlite3$(TEXE): tclsqlite-shell.lo libsqlite3.la + $(LTLINK) -o $@ tclsqlite-shell.lo \ + libsqlite3.la $(LIBTCL) + +# Rules to build opcodes.c and opcodes.h +# +opcodes.c: opcodes.h $(TOP)/mkopcodec.awk + $(NAWK) -f $(TOP)/mkopcodec.awk opcodes.h >opcodes.c + +opcodes.h: parse.h $(TOP)/src/vdbe.c $(TOP)/mkopcodeh.awk + cat parse.h $(TOP)/src/vdbe.c | $(NAWK) -f $(TOP)/mkopcodeh.awk >opcodes.h + +# Rules to build parse.c and parse.h - the outputs of lemon. +# +parse.h: parse.c + +parse.c: $(TOP)/src/parse.y lemon$(BEXE) $(TOP)/addopcodes.awk + cp $(TOP)/src/parse.y . + rm -f parse.h + ./lemon$(BEXE) $(OPT_FEATURE_FLAGS) $(OPTS) parse.y + mv parse.h parse.h.temp + $(NAWK) -f $(TOP)/addopcodes.awk parse.h.temp >parse.h + +sqlite3.h: $(TOP)/src/sqlite.h.in $(TOP)/manifest.uuid $(TOP)/VERSION + $(TCLSH_CMD) $(TOP)/tool/mksqlite3h.tcl $(TOP) >sqlite3.h + +keywordhash.h: $(TOP)/tool/mkkeywordhash.c + $(BCC) -o mkkeywordhash$(BEXE) $(OPT_FEATURE_FLAGS) $(OPTS) $(TOP)/tool/mkkeywordhash.c + ./mkkeywordhash$(BEXE) >keywordhash.h + + + +# Rules to build the extension objects. +# +icu.lo: $(TOP)/ext/icu/icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/icu/icu.c + +fts2.lo: $(TOP)/ext/fts2/fts2.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2.c + +fts2_hash.lo: $(TOP)/ext/fts2/fts2_hash.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_hash.c + +fts2_icu.lo: $(TOP)/ext/fts2/fts2_icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_icu.c + +fts2_porter.lo: $(TOP)/ext/fts2/fts2_porter.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_porter.c + +fts2_tokenizer.lo: $(TOP)/ext/fts2/fts2_tokenizer.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer.c + +fts2_tokenizer1.lo: $(TOP)/ext/fts2/fts2_tokenizer1.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer1.c + +fts3.lo: $(TOP)/ext/fts3/fts3.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3.c + +fts3_aux.lo: $(TOP)/ext/fts3/fts3_aux.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_aux.c + +fts3_expr.lo: $(TOP)/ext/fts3/fts3_expr.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_expr.c + +fts3_hash.lo: $(TOP)/ext/fts3/fts3_hash.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_hash.c + +fts3_icu.lo: $(TOP)/ext/fts3/fts3_icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_icu.c + +fts3_porter.lo: $(TOP)/ext/fts3/fts3_porter.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_porter.c + +fts3_snippet.lo: $(TOP)/ext/fts3/fts3_snippet.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_snippet.c + +fts3_tokenizer.lo: $(TOP)/ext/fts3/fts3_tokenizer.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer.c + +fts3_tokenizer1.lo: $(TOP)/ext/fts3/fts3_tokenizer1.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer1.c + +fts3_tokenize_vtab.lo: $(TOP)/ext/fts3/fts3_tokenize_vtab.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenize_vtab.c + +fts3_unicode.lo: $(TOP)/ext/fts3/fts3_unicode.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_unicode.c + +fts3_unicode2.lo: $(TOP)/ext/fts3/fts3_unicode2.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_unicode2.c + +fts3_write.lo: $(TOP)/ext/fts3/fts3_write.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_write.c + +rtree.lo: $(TOP)/ext/rtree/rtree.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/rtree/rtree.c + + +# Rules to build the 'testfixture' application. +# +# If using the amalgamation, use sqlite3.c directly to build the test +# fixture. Otherwise link against libsqlite3.la. (This distinction is +# necessary because the test fixture requires non-API symbols which are +# hidden when the library is built via the amalgamation). +# +TESTFIXTURE_FLAGS = -DTCLSH=1 -DSQLITE_TEST=1 -DSQLITE_CRASH_TEST=1 +TESTFIXTURE_FLAGS += -DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE +TESTFIXTURE_FLAGS += -DBUILD_sqlite + +TESTFIXTURE_SRC0 = $(TESTSRC2) libsqlite3.la +TESTFIXTURE_SRC1 = sqlite3.c +TESTFIXTURE_SRC = $(TESTSRC) $(TOP)/src/tclsqlite.c +TESTFIXTURE_SRC += $(TESTFIXTURE_SRC$(USE_AMALGAMATION)) + +testfixture$(TEXE): $(TESTFIXTURE_SRC) + $(LTLINK) -DSQLITE_NO_SYNC=1 $(TEMP_STORE) $(TESTFIXTURE_FLAGS) \ + -o $@ $(TESTFIXTURE_SRC) $(LIBTCL) $(TLIBS) + + +fulltest: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/all.test + +soaktest: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/all.test -soak=1 + +fulltestonly: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/full.test + +test: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/veryquick.test + +sqlite3_analyzer.c: sqlite3.c $(TOP)/src/test_stat.c $(TOP)/src/tclsqlite.c $(TOP)/tool/spaceanal.tcl + echo "#define TCLSH 2" > $@ + cat sqlite3.c $(TOP)/src/test_stat.c $(TOP)/src/tclsqlite.c >> $@ + echo "static const char *tclsh_main_loop(void){" >> $@ + echo "static const char *zMainloop = " >> $@ + $(NAWK) -f $(TOP)/tool/tostr.awk $(TOP)/tool/spaceanal.tcl >> $@ + echo "; return zMainloop; }" >> $@ + +sqlite3_analyzer$(TEXE): sqlite3_analyzer.c + $(LTLINK) sqlite3_analyzer.c -o $@ $(LIBTCL) $(TLIBS) + +# Standard install and cleanup targets +# +lib_install: libsqlite3.la + $(INSTALL) -d $(DESTDIR)$(libdir) + $(LTINSTALL) libsqlite3.la $(DESTDIR)$(libdir) + +install: sqlite3$(BEXE) lib_install sqlite3.h sqlite3.pc ${HAVE_TCL:1=tcl_install} + $(INSTALL) -d $(DESTDIR)$(bindir) + $(LTINSTALL) sqlite3$(BEXE) $(DESTDIR)$(bindir) + $(INSTALL) -d $(DESTDIR)$(includedir) + $(INSTALL) -m 0644 sqlite3.h $(DESTDIR)$(includedir) + $(INSTALL) -m 0644 $(TOP)/src/sqlite3ext.h $(DESTDIR)$(includedir) + $(INSTALL) -d $(DESTDIR)$(pkgconfigdir) + $(INSTALL) -m 0644 sqlite3.pc $(DESTDIR)$(pkgconfigdir) + +pkgIndex.tcl: + echo 'package ifneeded sqlite3 $(RELEASE) [list load $(TCLLIBDIR)/libtclsqlite3.so sqlite3]' > $@ +tcl_install: lib_install libtclsqlite3.la pkgIndex.tcl + $(INSTALL) -d $(DESTDIR)$(TCLLIBDIR) + $(LTINSTALL) libtclsqlite3.la $(DESTDIR)$(TCLLIBDIR) + rm -f $(DESTDIR)$(TCLLIBDIR)/libtclsqlite3.la $(DESTDIR)$(TCLLIBDIR)/libtclsqlite3.a + $(INSTALL) -m 0644 pkgIndex.tcl $(DESTDIR)$(TCLLIBDIR) + +clean: + rm -f *.lo *.la *.o sqlite3$(TEXE) libsqlite3.la + rm -f sqlite3.h opcodes.* + rm -rf .libs .deps + rm -f lemon$(BEXE) lempar.c parse.* sqlite*.tar.gz + rm -f mkkeywordhash$(BEXE) keywordhash.h + rm -f *.da *.bb *.bbg gmon.out + rm -rf quota2a quota2b quota2c + rm -rf tsrc .target_source + rm -f tclsqlite3$(TEXE) + rm -f testfixture$(TEXE) test.db + rm -f sqlite3.dll sqlite3.lib sqlite3.exp sqlite3.def + rm -f sqlite3.c + rm -f sqlite3rc.h + rm -f shell.c sqlite3ext.h + rm -f sqlite3_analyzer$(TEXE) sqlite3_analyzer.c + rm -f sqlite-*-output.vsix + rm -f mptester mptester.exe + +distclean: clean + rm -f config.log config.status libtool Makefile sqlite3.pc diff --git a/components/external/SQLite-3.8.1/make/Makefile.bak b/components/external/SQLite-3.8.1/make/Makefile.bak new file mode 100644 index 0000000000000000000000000000000000000000..69f45828a5d02412be919bc7678761ea808ed6c1 --- /dev/null +++ b/components/external/SQLite-3.8.1/make/Makefile.bak @@ -0,0 +1,1011 @@ +#!/usr/make +# +# Makefile for SQLITE +# +# This makefile is suppose to be configured automatically using the +# autoconf. But if that does not work for you, you can configure +# the makefile manually. Just set the parameters below to values that +# work well for your system. +# +# If the configure script does not work out-of-the-box, you might +# be able to get it to work by giving it some hints. See the comment +# at the beginning of configure.in for additional information. +# + +# The toplevel directory of the source tree. This is the directory +# that contains this "Makefile.in" and the "configure.in" script. +# +TOP = .. + +# C Compiler and options for use in building executables that +# will run on the platform that is doing the build. +# +BCC = gcc -g + +# C Compile and options for use in building executables that +# will run on the target platform. (BCC and TCC are usually the +# same unless your are cross-compiling.) +# +TCC = arm-none-eabi-gcc -g -O2 \ + -DSQLITE_OS_OTHER=1 -DSQLITE_OS_RTT=1 \ + -I. -I${TOP}/src -I${TOP}/ext/rtree \ + -I../../../../include \ + -I../../../../components/dfs/include \ + -I../../../../components/libc/newlib \ + -I../../../../components/libc/newlib/sys \ + -I../../../../bsp/mini2440 + +# Define this for the autoconf-based build, so that the code knows it can +# include the generated config.h +# +TCC += -D_HAVE_SQLITE_CONFIG_H -DBUILD_sqlite + +# Define -DNDEBUG to compile without debugging (i.e., for production usage) +# Omitting the define will cause extra debugging code to be inserted and +# includes extra comments when "EXPLAIN stmt" is used. +# +TCC += -DNDEBUG + +# Compiler options needed for programs that use the TCL library. +# +TCC += -I/usr/include + +# The library that programs using TCL must link against. +# +LIBTCL = -L/usr/lib -ltcl8.5 + +# Compiler options needed for programs that use the readline() library. +# +READLINE_FLAGS = -DHAVE_READLINE=0 + +# The library that programs using readline() must link against. +# +LIBREADLINE = + +# Should the database engine be compiled threadsafe +# +TCC += -DSQLITE_THREADSAFE=1 + +# Any target libraries which libsqlite must be linked against +# +TLIBS = + +# Flags controlling use of the in memory btree implementation +# +# SQLITE_TEMP_STORE is 0 to force temporary tables to be in a file, 1 to +# default to file, 2 to default to memory, and 3 to force temporary +# tables to always be in memory. +# +TEMP_STORE = -DSQLITE_TEMP_STORE=1 + +# Enable/disable loadable extensions, and other optional features +# based on configuration. (-DSQLITE_OMIT*, -DSQLITE_ENABLE*). +# The same set of OMIT and ENABLE flags should be passed to the +# LEMON parser generator and the mkkeywordhash tool as well. +OPT_FEATURE_FLAGS = -DSQLITE_OMIT_LOAD_EXTENSION=1 -DSQLITE_RTT_NO_WIDE=1 \ + -DSQLITE_OMIT_WAL -DSQLITE_ENABLE_LOCKING_STYLE=0 \ + -DSQLITE_DISABLE_LOCKING_STYLE=1 + +TCC += $(OPT_FEATURE_FLAGS) + +# Add in any optional parameters specified on the make commane line +# ie. make "OPTS=-DSQLITE_ENABLE_FOO=1 -DSQLITE_OMIT_FOO=1". +TCC += $(OPTS) + +# Version numbers and release number for the SQLite being compiled. +# +VERSION = 3.8 +VERSION_NUMBER = 3008001 +RELEASE = 3.8.1 + +# Filename extensions +# +BEXE = +TEXE = + +# The following variable is "1" if the configure script was able to locate +# the tclConfig.sh file. It is an empty string otherwise. When this +# variable is "1", the TCL extension library (libtclsqlite3.so) is built +# and installed. +# +HAVE_TCL = 1 + +# This is the command to use for tclsh - normally just "tclsh", but we may +# know the specific version we want to use +# +TCLSH_CMD = tclsh8.5 + +# Where do we want to install the tcl plugin +# +TCLLIBDIR = /usr/lib/tcl8.5/sqlite3 + +# The suffix used on shared libraries. Ex: ".dll", ".so", ".dylib" +# +SHLIB_SUFFIX = @TCL_SHLIB_SUFFIX@ + +# If gcov support was enabled by the configure script, add the appropriate +# flags here. It's not always as easy as just having the user add the right +# CFLAGS / LDFLAGS, because libtool wants to use CFLAGS when linking, which +# causes build errors with -fprofile-arcs -ftest-coverage with some GCCs. +# Supposedly GCC does the right thing if you use --coverage, but in +# practice it still fails. See: +# +# http://www.mail-archive.com/debian-gcc@lists.debian.org/msg26197.html +# +# for more info. +# +GCOV_CFLAGS1 = -DSQLITE_COVERAGE_TEST=1 -fprofile-arcs -ftest-coverage +GCOV_LDFLAGS1 = -lgcov +USE_GCOV = 0 +LTCOMPILE_EXTRAS += $(GCOV_CFLAGS$(USE_GCOV)) +LTLINK_EXTRAS += $(GCOV_LDFLAGS$(USE_GCOV)) + + +# The directory into which to store package information for + +# Some standard variables and programs +# +prefix = /usr/local +exec_prefix = ${prefix} +libdir = ${exec_prefix}/lib +pkgconfigdir = $(libdir)/pkgconfig +bindir = ${exec_prefix}/bin +includedir = ${prefix}/include +INSTALL = /usr/bin/install -c +LIBTOOL = ./libtool +ALLOWRELEASE = + +# libtool compile/link/install +LTCOMPILE = $(LIBTOOL) --mode=compile --tag=CC $(TCC) $(LTCOMPILE_EXTRAS) +LTLINK = $(LIBTOOL) --mode=link $(TCC) $(LTCOMPILE_EXTRAS) $(LTLINK_EXTRAS) +LTINSTALL = $(LIBTOOL) --mode=install $(INSTALL) + +# nawk compatible awk. +NAWK = gawk + +# You should not have to change anything below this line +############################################################################### + +USE_AMALGAMATION = 1 + +# Object files for the SQLite library (non-amalgamation). +# +LIBOBJS0 = alter.lo analyze.lo attach.lo auth.lo \ + backup.lo bitvec.lo btmutex.lo btree.lo build.lo \ + callback.lo complete.lo ctime.lo date.lo delete.lo \ + expr.lo fault.lo fkey.lo \ + fts3.lo fts3_aux.lo fts3_expr.lo fts3_hash.lo fts3_icu.lo \ + fts3_porter.lo fts3_snippet.lo fts3_tokenizer.lo fts3_tokenizer1.lo \ + fts3_tokenize_vtab.lo \ + fts3_unicode.lo fts3_unicode2.lo fts3_write.lo \ + func.lo global.lo hash.lo \ + icu.lo insert.lo journal.lo legacy.lo loadext.lo \ + main.lo malloc.lo mem0.lo mem1.lo mem2.lo mem3.lo mem5.lo \ + memjournal.lo \ + mutex.lo mutex_noop.lo mutex_unix.lo mutex_w32.lo mutex_rtt.lo \ + notify.lo opcodes.lo os.lo os_unix.lo os_win.lo os_rtt.lo \ + pager.lo parse.lo pcache.lo pcache1.lo pragma.lo prepare.lo printf.lo \ + random.lo resolve.lo rowset.lo rtree.lo select.lo status.lo \ + table.lo tokenize.lo trigger.lo \ + update.lo util.lo vacuum.lo \ + vdbe.lo vdbeapi.lo vdbeaux.lo vdbeblob.lo vdbemem.lo vdbesort.lo \ + vdbetrace.lo wal.lo walker.lo where.lo utf.lo vtab.lo + +# Object files for the amalgamation. +# +LIBOBJS1 = sqlite3.lo + +# Determine the real value of LIBOBJ based on the 'configure' script +# +LIBOBJ = $(LIBOBJS$(USE_AMALGAMATION)) + + +# All of the source code files. +# +SRC = \ + $(TOP)/src/alter.c \ + $(TOP)/src/analyze.c \ + $(TOP)/src/attach.c \ + $(TOP)/src/auth.c \ + $(TOP)/src/backup.c \ + $(TOP)/src/bitvec.c \ + $(TOP)/src/btmutex.c \ + $(TOP)/src/btree.c \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/build.c \ + $(TOP)/src/callback.c \ + $(TOP)/src/complete.c \ + $(TOP)/src/ctime.c \ + $(TOP)/src/date.c \ + $(TOP)/src/delete.c \ + $(TOP)/src/expr.c \ + $(TOP)/src/fault.c \ + $(TOP)/src/fkey.c \ + $(TOP)/src/func.c \ + $(TOP)/src/global.c \ + $(TOP)/src/hash.c \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + $(TOP)/src/insert.c \ + $(TOP)/src/journal.c \ + $(TOP)/src/legacy.c \ + $(TOP)/src/loadext.c \ + $(TOP)/src/main.c \ + $(TOP)/src/malloc.c \ + $(TOP)/src/mem0.c \ + $(TOP)/src/mem1.c \ + $(TOP)/src/mem2.c \ + $(TOP)/src/mem3.c \ + $(TOP)/src/mem5.c \ + $(TOP)/src/memjournal.c \ + $(TOP)/src/mutex.c \ + $(TOP)/src/mutex.h \ + $(TOP)/src/mutex_noop.c \ + $(TOP)/src/mutex_unix.c \ + $(TOP)/src/mutex_w32.c \ + $(TOP)/src/mutex_rtt.c \ + $(TOP)/src/notify.c \ + $(TOP)/src/os.c \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/os_unix.c \ + $(TOP)/src/os_win.c \ + $(TOP)/src/os_rtt.c \ + $(TOP)/src/pager.c \ + $(TOP)/src/pager.h \ + $(TOP)/src/parse.y \ + $(TOP)/src/pcache.c \ + $(TOP)/src/pcache.h \ + $(TOP)/src/pcache1.c \ + $(TOP)/src/pragma.c \ + $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c \ + $(TOP)/src/random.c \ + $(TOP)/src/resolve.c \ + $(TOP)/src/rowset.c \ + $(TOP)/src/select.c \ + $(TOP)/src/status.c \ + $(TOP)/src/shell.c \ + $(TOP)/src/sqlite.h.in \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/table.c \ + $(TOP)/src/tclsqlite.c \ + $(TOP)/src/tokenize.c \ + $(TOP)/src/trigger.c \ + $(TOP)/src/utf.c \ + $(TOP)/src/update.c \ + $(TOP)/src/util.c \ + $(TOP)/src/vacuum.c \ + $(TOP)/src/vdbe.c \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeapi.c \ + $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbeblob.c \ + $(TOP)/src/vdbemem.c \ + $(TOP)/src/vdbesort.c \ + $(TOP)/src/vdbetrace.c \ + $(TOP)/src/vdbeInt.h \ + $(TOP)/src/vtab.c \ + $(TOP)/src/wal.c \ + $(TOP)/src/wal.h \ + $(TOP)/src/walker.c \ + $(TOP)/src/where.c + +# Source code for extensions +# +SRC += \ + $(TOP)/ext/fts1/fts1.c \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.c \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_porter.c \ + $(TOP)/ext/fts1/fts1_tokenizer.h \ + $(TOP)/ext/fts1/fts1_tokenizer1.c +SRC += \ + $(TOP)/ext/fts2/fts2.c \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.c \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_icu.c \ + $(TOP)/ext/fts2/fts2_porter.c \ + $(TOP)/ext/fts2/fts2_tokenizer.h \ + $(TOP)/ext/fts2/fts2_tokenizer.c \ + $(TOP)/ext/fts2/fts2_tokenizer1.c +SRC += \ + $(TOP)/ext/fts3/fts3.c \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3Int.h \ + $(TOP)/ext/fts3/fts3_aux.c \ + $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_hash.c \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_icu.c \ + $(TOP)/ext/fts3/fts3_porter.c \ + $(TOP)/ext/fts3/fts3_snippet.c \ + $(TOP)/ext/fts3/fts3_tokenizer.h \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/fts3/fts3_tokenizer1.c \ + $(TOP)/ext/fts3/fts3_tokenize_vtab.c \ + $(TOP)/ext/fts3/fts3_unicode.c \ + $(TOP)/ext/fts3/fts3_unicode2.c \ + $(TOP)/ext/fts3/fts3_write.c +SRC += \ + $(TOP)/ext/icu/sqliteicu.h \ + $(TOP)/ext/icu/icu.c +SRC += \ + $(TOP)/ext/rtree/rtree.h \ + $(TOP)/ext/rtree/rtree.c + + +# Generated source code files +# +SRC += \ + keywordhash.h \ + opcodes.c \ + opcodes.h \ + parse.c \ + parse.h \ + config.h \ + sqlite3.h + +# Source code to the test files. +# +TESTSRC = \ + $(TOP)/src/test1.c \ + $(TOP)/src/test2.c \ + $(TOP)/src/test3.c \ + $(TOP)/src/test4.c \ + $(TOP)/src/test5.c \ + $(TOP)/src/test6.c \ + $(TOP)/src/test7.c \ + $(TOP)/src/test8.c \ + $(TOP)/src/test9.c \ + $(TOP)/src/test_autoext.c \ + $(TOP)/src/test_async.c \ + $(TOP)/src/test_backup.c \ + $(TOP)/src/test_btree.c \ + $(TOP)/src/test_config.c \ + $(TOP)/src/test_demovfs.c \ + $(TOP)/src/test_devsym.c \ + $(TOP)/src/test_fs.c \ + $(TOP)/src/test_func.c \ + $(TOP)/src/test_hexio.c \ + $(TOP)/src/test_init.c \ + $(TOP)/src/test_intarray.c \ + $(TOP)/src/test_journal.c \ + $(TOP)/src/test_malloc.c \ + $(TOP)/src/test_multiplex.c \ + $(TOP)/src/test_mutex.c \ + $(TOP)/src/test_onefile.c \ + $(TOP)/src/test_osinst.c \ + $(TOP)/src/test_pcache.c \ + $(TOP)/src/test_quota.c \ + $(TOP)/src/test_rtree.c \ + $(TOP)/src/test_schema.c \ + $(TOP)/src/test_server.c \ + $(TOP)/src/test_superlock.c \ + $(TOP)/src/test_syscall.c \ + $(TOP)/src/test_stat.c \ + $(TOP)/src/test_tclvar.c \ + $(TOP)/src/test_thread.c \ + $(TOP)/src/test_vfs.c \ + $(TOP)/src/test_wsd.c \ + $(TOP)/ext/fts3/fts3_term.c \ + $(TOP)/ext/fts3/fts3_test.c + +# Statically linked extensions +# +TESTSRC += \ + $(TOP)/ext/misc/amatch.c \ + $(TOP)/ext/misc/closure.c \ + $(TOP)/ext/misc/fuzzer.c \ + $(TOP)/ext/misc/ieee754.c \ + $(TOP)/ext/misc/nextchar.c \ + $(TOP)/ext/misc/percentile.c \ + $(TOP)/ext/misc/regexp.c \ + $(TOP)/ext/misc/spellfix.c \ + $(TOP)/ext/misc/totype.c \ + $(TOP)/ext/misc/wholenumber.c + +# Source code to the library files needed by the test fixture +# +TESTSRC2 = \ + $(TOP)/src/attach.c \ + $(TOP)/src/backup.c \ + $(TOP)/src/bitvec.c \ + $(TOP)/src/btree.c \ + $(TOP)/src/build.c \ + $(TOP)/src/ctime.c \ + $(TOP)/src/date.c \ + $(TOP)/src/expr.c \ + $(TOP)/src/func.c \ + $(TOP)/src/insert.c \ + $(TOP)/src/wal.c \ + $(TOP)/src/main.c \ + $(TOP)/src/mem5.c \ + $(TOP)/src/os.c \ + $(TOP)/src/os_unix.c \ + $(TOP)/src/os_win.c \ + $(TOP)/src/pager.c \ + $(TOP)/src/pragma.c \ + $(TOP)/src/prepare.c \ + $(TOP)/src/printf.c \ + $(TOP)/src/random.c \ + $(TOP)/src/pcache.c \ + $(TOP)/src/pcache1.c \ + $(TOP)/src/select.c \ + $(TOP)/src/tokenize.c \ + $(TOP)/src/utf.c \ + $(TOP)/src/util.c \ + $(TOP)/src/vdbeapi.c \ + $(TOP)/src/vdbeaux.c \ + $(TOP)/src/vdbe.c \ + $(TOP)/src/vdbemem.c \ + $(TOP)/src/vdbetrace.c \ + $(TOP)/src/where.c \ + parse.c \ + $(TOP)/ext/fts3/fts3.c \ + $(TOP)/ext/fts3/fts3_aux.c \ + $(TOP)/ext/fts3/fts3_expr.c \ + $(TOP)/ext/fts3/fts3_term.c \ + $(TOP)/ext/fts3/fts3_tokenizer.c \ + $(TOP)/ext/fts3/fts3_write.c \ + $(TOP)/ext/async/sqlite3async.c + +# Header files used by all library source files. +# +HDR = \ + $(TOP)/src/btree.h \ + $(TOP)/src/btreeInt.h \ + $(TOP)/src/hash.h \ + $(TOP)/src/hwtime.h \ + keywordhash.h \ + $(TOP)/src/mutex.h \ + opcodes.h \ + $(TOP)/src/os.h \ + $(TOP)/src/os_common.h \ + $(TOP)/src/pager.h \ + $(TOP)/src/pcache.h \ + parse.h \ + sqlite3.h \ + $(TOP)/src/sqlite3ext.h \ + $(TOP)/src/sqliteInt.h \ + $(TOP)/src/sqliteLimit.h \ + $(TOP)/src/vdbe.h \ + $(TOP)/src/vdbeInt.h \ + config.h + +# Header files used by extensions +# +EXTHDR += \ + $(TOP)/ext/fts1/fts1.h \ + $(TOP)/ext/fts1/fts1_hash.h \ + $(TOP)/ext/fts1/fts1_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts2/fts2.h \ + $(TOP)/ext/fts2/fts2_hash.h \ + $(TOP)/ext/fts2/fts2_tokenizer.h +EXTHDR += \ + $(TOP)/ext/fts3/fts3.h \ + $(TOP)/ext/fts3/fts3Int.h \ + $(TOP)/ext/fts3/fts3_hash.h \ + $(TOP)/ext/fts3/fts3_tokenizer.h +EXTHDR += \ + $(TOP)/ext/rtree/rtree.h +EXTHDR += \ + $(TOP)/ext/icu/sqliteicu.h +EXTHDR += \ + $(TOP)/ext/rtree/sqlite3rtree.h + +# This is the default Makefile target. The objects listed here +# are what get build when you type just "make" with no arguments. +# +all: sqlite3.h libsqlite3.la sqlite3$(TEXE) $(HAVE_TCL:1=libtclsqlite3.la) + +Makefile: $(TOP)/Makefile.in + ./config.status + +sqlite3.pc: $(TOP)/sqlite3.pc.in + ./config.status + +libsqlite3.la: $(LIBOBJ) + $(LTLINK) -no-undefined -o $@ $(LIBOBJ) $(TLIBS) \ + ${ALLOWRELEASE} -rpath "$(libdir)" -version-info "8:6:8" + +libtclsqlite3.la: tclsqlite.lo libsqlite3.la + $(LTLINK) -no-undefined -o $@ tclsqlite.lo \ + libsqlite3.la -Wl,-ltclstub8.5 $(TLIBS) \ + -rpath "$(TCLLIBDIR)" \ + -version-info "8:6:8" \ + -avoid-version + +sqlite3$(TEXE): $(TOP)/src/shell.c libsqlite3.la sqlite3.h + $(LTLINK) $(READLINE_FLAGS) \ + -o $@ $(TOP)/src/shell.c libsqlite3.la \ + $(LIBREADLINE) $(TLIBS) -rpath "$(libdir)" + +mptester$(EXE): sqlite3.c $(TOP)/mptest/mptest.c + $(LTLINK) -o $@ -I. $(TOP)/mptest/mptest.c sqlite3.c \ + $(TLIBS) -rpath "$(libdir)" + + +# This target creates a directory named "tsrc" and fills it with +# copies of all of the C source code and header files needed to +# build on the target system. Some of the C source code and header +# files are automatically generated. This target takes care of +# all that automatic generation. +# +.target_source: $(SRC) $(TOP)/tool/vdbe-compress.tcl + rm -rf tsrc + mkdir tsrc + cp -f $(SRC) tsrc + rm tsrc/sqlite.h.in tsrc/parse.y + $(TCLSH_CMD) $(TOP)/tool/vdbe-compress.tcl vdbe.new + mv vdbe.new tsrc/vdbe.c + touch .target_source + +sqlite3.c: .target_source $(TOP)/tool/mksqlite3c.tcl + $(TCLSH_CMD) $(TOP)/tool/mksqlite3c.tcl + cp tsrc/shell.c tsrc/sqlite3ext.h . + +tclsqlite3.c: sqlite3.c + echo '#ifndef USE_SYSTEM_SQLITE' >tclsqlite3.c + cat sqlite3.c >>tclsqlite3.c + echo '#endif /* USE_SYSTEM_SQLITE */' >>tclsqlite3.c + cat $(TOP)/src/tclsqlite.c >>tclsqlite3.c + +sqlite3-all.c: sqlite3.c $(TOP)/tool/split-sqlite3c.tcl + $(TCLSH_CMD) $(TOP)/tool/split-sqlite3c.tcl + +# Rule to build the amalgamation +# +sqlite3.lo: sqlite3.c + $(LTCOMPILE) $(TEMP_STORE) -c sqlite3.c + +# Rules to build the LEMON compiler generator +# +lemon$(BEXE): $(TOP)/tool/lemon.c $(TOP)/src/lempar.c + $(BCC) -o $@ $(TOP)/tool/lemon.c + cp $(TOP)/src/lempar.c . + +# Rules to build individual *.o files from generated *.c files. This +# applies to: +# +# parse.o +# opcodes.o +# +parse.lo: parse.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c parse.c + +opcodes.lo: opcodes.c + $(LTCOMPILE) $(TEMP_STORE) -c opcodes.c + +# Rules to build individual *.o files from files in the src directory. +# +alter.lo: $(TOP)/src/alter.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/alter.c + +analyze.lo: $(TOP)/src/analyze.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/analyze.c + +attach.lo: $(TOP)/src/attach.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/attach.c + +auth.lo: $(TOP)/src/auth.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/auth.c + +backup.lo: $(TOP)/src/backup.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/backup.c + +bitvec.lo: $(TOP)/src/bitvec.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/bitvec.c + +btmutex.lo: $(TOP)/src/btmutex.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/btmutex.c + +btree.lo: $(TOP)/src/btree.c $(HDR) $(TOP)/src/pager.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/btree.c + +build.lo: $(TOP)/src/build.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/build.c + +callback.lo: $(TOP)/src/callback.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/callback.c + +complete.lo: $(TOP)/src/complete.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/complete.c + +ctime.lo: $(TOP)/src/ctime.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/ctime.c + +date.lo: $(TOP)/src/date.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/date.c + +delete.lo: $(TOP)/src/delete.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/delete.c + +expr.lo: $(TOP)/src/expr.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/expr.c + +fault.lo: $(TOP)/src/fault.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/fault.c + +fkey.lo: $(TOP)/src/fkey.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/fkey.c + +func.lo: $(TOP)/src/func.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/func.c + +global.lo: $(TOP)/src/global.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/global.c + +hash.lo: $(TOP)/src/hash.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/hash.c + +insert.lo: $(TOP)/src/insert.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/insert.c + +journal.lo: $(TOP)/src/journal.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/journal.c + +legacy.lo: $(TOP)/src/legacy.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/legacy.c + +loadext.lo: $(TOP)/src/loadext.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/loadext.c + +main.lo: $(TOP)/src/main.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/main.c + +malloc.lo: $(TOP)/src/malloc.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/malloc.c + +mem0.lo: $(TOP)/src/mem0.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem0.c + +mem1.lo: $(TOP)/src/mem1.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem1.c + +mem2.lo: $(TOP)/src/mem2.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem2.c + +mem3.lo: $(TOP)/src/mem3.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem3.c + +mem5.lo: $(TOP)/src/mem5.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mem5.c + +memjournal.lo: $(TOP)/src/memjournal.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/memjournal.c + +mutex.lo: $(TOP)/src/mutex.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex.c + +mutex_noop.lo: $(TOP)/src/mutex_noop.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_noop.c + +mutex_unix.lo: $(TOP)/src/mutex_unix.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_unix.c + +mutex_w32.lo: $(TOP)/src/mutex_w32.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_w32.c + +mutex_rtt.lo: $(TOP)/src/mutex_rtt.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/mutex_rtt.c +notify.lo: $(TOP)/src/notify.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/notify.c + +pager.lo: $(TOP)/src/pager.c $(HDR) $(TOP)/src/pager.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pager.c + +pcache.lo: $(TOP)/src/pcache.c $(HDR) $(TOP)/src/pcache.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pcache.c + +pcache1.lo: $(TOP)/src/pcache1.c $(HDR) $(TOP)/src/pcache.h + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pcache1.c + +os.lo: $(TOP)/src/os.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os.c + +os_unix.lo: $(TOP)/src/os_unix.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_unix.c + +os_win.lo: $(TOP)/src/os_win.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_win.c +os_rtt.lo:$(TOP)/src/os_rtt.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/os_rtt.c + +pragma.lo: $(TOP)/src/pragma.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/pragma.c + +prepare.lo: $(TOP)/src/prepare.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/prepare.c + +printf.lo: $(TOP)/src/printf.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/printf.c + +random.lo: $(TOP)/src/random.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/random.c + +resolve.lo: $(TOP)/src/resolve.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/resolve.c + +rowset.lo: $(TOP)/src/rowset.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/rowset.c + +select.lo: $(TOP)/src/select.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/select.c + +status.lo: $(TOP)/src/status.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/status.c + +table.lo: $(TOP)/src/table.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/table.c + +tokenize.lo: $(TOP)/src/tokenize.c keywordhash.h $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/tokenize.c + +trigger.lo: $(TOP)/src/trigger.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/trigger.c + +update.lo: $(TOP)/src/update.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/update.c + +utf.lo: $(TOP)/src/utf.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/utf.c + +util.lo: $(TOP)/src/util.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/util.c + +vacuum.lo: $(TOP)/src/vacuum.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vacuum.c + +vdbe.lo: $(TOP)/src/vdbe.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbe.c + +vdbeapi.lo: $(TOP)/src/vdbeapi.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeapi.c + +vdbeaux.lo: $(TOP)/src/vdbeaux.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeaux.c + +vdbeblob.lo: $(TOP)/src/vdbeblob.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbeblob.c + +vdbemem.lo: $(TOP)/src/vdbemem.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbemem.c + +vdbesort.lo: $(TOP)/src/vdbesort.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbesort.c + +vdbetrace.lo: $(TOP)/src/vdbetrace.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vdbetrace.c + +vtab.lo: $(TOP)/src/vtab.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/vtab.c + +wal.lo: $(TOP)/src/wal.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/wal.c + +walker.lo: $(TOP)/src/walker.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/walker.c + +where.lo: $(TOP)/src/where.c $(HDR) + $(LTCOMPILE) $(TEMP_STORE) -c $(TOP)/src/where.c + +tclsqlite.lo: $(TOP)/src/tclsqlite.c $(HDR) + $(LTCOMPILE) -DUSE_TCL_STUBS=1 -c $(TOP)/src/tclsqlite.c + +tclsqlite-shell.lo: $(TOP)/src/tclsqlite.c $(HDR) + $(LTCOMPILE) -DTCLSH=1 -o $@ -c $(TOP)/src/tclsqlite.c + +tclsqlite-stubs.lo: $(TOP)/src/tclsqlite.c $(HDR) + $(LTCOMPILE) -DUSE_TCL_STUBS=1 -o $@ -c $(TOP)/src/tclsqlite.c + +tclsqlite3$(TEXE): tclsqlite-shell.lo libsqlite3.la + $(LTLINK) -o $@ tclsqlite-shell.lo \ + libsqlite3.la $(LIBTCL) + +# Rules to build opcodes.c and opcodes.h +# +opcodes.c: opcodes.h $(TOP)/mkopcodec.awk + $(NAWK) -f $(TOP)/mkopcodec.awk opcodes.h >opcodes.c + +opcodes.h: parse.h $(TOP)/src/vdbe.c $(TOP)/mkopcodeh.awk + cat parse.h $(TOP)/src/vdbe.c | $(NAWK) -f $(TOP)/mkopcodeh.awk >opcodes.h + +# Rules to build parse.c and parse.h - the outputs of lemon. +# +parse.h: parse.c + +parse.c: $(TOP)/src/parse.y lemon$(BEXE) $(TOP)/addopcodes.awk + cp $(TOP)/src/parse.y . + rm -f parse.h + ./lemon$(BEXE) $(OPT_FEATURE_FLAGS) $(OPTS) parse.y + mv parse.h parse.h.temp + $(NAWK) -f $(TOP)/addopcodes.awk parse.h.temp >parse.h + +sqlite3.h: $(TOP)/src/sqlite.h.in $(TOP)/manifest.uuid $(TOP)/VERSION + $(TCLSH_CMD) $(TOP)/tool/mksqlite3h.tcl $(TOP) >sqlite3.h + +keywordhash.h: $(TOP)/tool/mkkeywordhash.c + $(BCC) -o mkkeywordhash$(BEXE) $(OPT_FEATURE_FLAGS) $(OPTS) $(TOP)/tool/mkkeywordhash.c + ./mkkeywordhash$(BEXE) >keywordhash.h + + + +# Rules to build the extension objects. +# +icu.lo: $(TOP)/ext/icu/icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/icu/icu.c + +fts2.lo: $(TOP)/ext/fts2/fts2.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2.c + +fts2_hash.lo: $(TOP)/ext/fts2/fts2_hash.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_hash.c + +fts2_icu.lo: $(TOP)/ext/fts2/fts2_icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_icu.c + +fts2_porter.lo: $(TOP)/ext/fts2/fts2_porter.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_porter.c + +fts2_tokenizer.lo: $(TOP)/ext/fts2/fts2_tokenizer.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer.c + +fts2_tokenizer1.lo: $(TOP)/ext/fts2/fts2_tokenizer1.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts2/fts2_tokenizer1.c + +fts3.lo: $(TOP)/ext/fts3/fts3.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3.c + +fts3_aux.lo: $(TOP)/ext/fts3/fts3_aux.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_aux.c + +fts3_expr.lo: $(TOP)/ext/fts3/fts3_expr.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_expr.c + +fts3_hash.lo: $(TOP)/ext/fts3/fts3_hash.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_hash.c + +fts3_icu.lo: $(TOP)/ext/fts3/fts3_icu.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_icu.c + +fts3_porter.lo: $(TOP)/ext/fts3/fts3_porter.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_porter.c + +fts3_snippet.lo: $(TOP)/ext/fts3/fts3_snippet.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_snippet.c + +fts3_tokenizer.lo: $(TOP)/ext/fts3/fts3_tokenizer.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer.c + +fts3_tokenizer1.lo: $(TOP)/ext/fts3/fts3_tokenizer1.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenizer1.c + +fts3_tokenize_vtab.lo: $(TOP)/ext/fts3/fts3_tokenize_vtab.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_tokenize_vtab.c + +fts3_unicode.lo: $(TOP)/ext/fts3/fts3_unicode.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_unicode.c + +fts3_unicode2.lo: $(TOP)/ext/fts3/fts3_unicode2.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_unicode2.c + +fts3_write.lo: $(TOP)/ext/fts3/fts3_write.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/fts3/fts3_write.c + +rtree.lo: $(TOP)/ext/rtree/rtree.c $(HDR) $(EXTHDR) + $(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/rtree/rtree.c + + +# Rules to build the 'testfixture' application. +# +# If using the amalgamation, use sqlite3.c directly to build the test +# fixture. Otherwise link against libsqlite3.la. (This distinction is +# necessary because the test fixture requires non-API symbols which are +# hidden when the library is built via the amalgamation). +# +TESTFIXTURE_FLAGS = -DTCLSH=1 -DSQLITE_TEST=1 -DSQLITE_CRASH_TEST=1 +TESTFIXTURE_FLAGS += -DSQLITE_SERVER=1 -DSQLITE_PRIVATE="" -DSQLITE_CORE +TESTFIXTURE_FLAGS += -DBUILD_sqlite + +TESTFIXTURE_SRC0 = $(TESTSRC2) libsqlite3.la +TESTFIXTURE_SRC1 = sqlite3.c +TESTFIXTURE_SRC = $(TESTSRC) $(TOP)/src/tclsqlite.c +TESTFIXTURE_SRC += $(TESTFIXTURE_SRC$(USE_AMALGAMATION)) + +testfixture$(TEXE): $(TESTFIXTURE_SRC) + $(LTLINK) -DSQLITE_NO_SYNC=1 $(TEMP_STORE) $(TESTFIXTURE_FLAGS) \ + -o $@ $(TESTFIXTURE_SRC) $(LIBTCL) $(TLIBS) + + +fulltest: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/all.test + +soaktest: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/all.test -soak=1 + +fulltestonly: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/full.test + +test: testfixture$(TEXE) sqlite3$(TEXE) + ./testfixture$(TEXE) $(TOP)/test/veryquick.test + +sqlite3_analyzer.c: sqlite3.c $(TOP)/src/test_stat.c $(TOP)/src/tclsqlite.c $(TOP)/tool/spaceanal.tcl + echo "#define TCLSH 2" > $@ + cat sqlite3.c $(TOP)/src/test_stat.c $(TOP)/src/tclsqlite.c >> $@ + echo "static const char *tclsh_main_loop(void){" >> $@ + echo "static const char *zMainloop = " >> $@ + $(NAWK) -f $(TOP)/tool/tostr.awk $(TOP)/tool/spaceanal.tcl >> $@ + echo "; return zMainloop; }" >> $@ + +sqlite3_analyzer$(TEXE): sqlite3_analyzer.c + $(LTLINK) sqlite3_analyzer.c -o $@ $(LIBTCL) $(TLIBS) + +# Standard install and cleanup targets +# +lib_install: libsqlite3.la + $(INSTALL) -d $(DESTDIR)$(libdir) + $(LTINSTALL) libsqlite3.la $(DESTDIR)$(libdir) + +install: sqlite3$(BEXE) lib_install sqlite3.h sqlite3.pc ${HAVE_TCL:1=tcl_install} + $(INSTALL) -d $(DESTDIR)$(bindir) + $(LTINSTALL) sqlite3$(BEXE) $(DESTDIR)$(bindir) + $(INSTALL) -d $(DESTDIR)$(includedir) + $(INSTALL) -m 0644 sqlite3.h $(DESTDIR)$(includedir) + $(INSTALL) -m 0644 $(TOP)/src/sqlite3ext.h $(DESTDIR)$(includedir) + $(INSTALL) -d $(DESTDIR)$(pkgconfigdir) + $(INSTALL) -m 0644 sqlite3.pc $(DESTDIR)$(pkgconfigdir) + +pkgIndex.tcl: + echo 'package ifneeded sqlite3 $(RELEASE) [list load $(TCLLIBDIR)/libtclsqlite3.so sqlite3]' > $@ +tcl_install: lib_install libtclsqlite3.la pkgIndex.tcl + $(INSTALL) -d $(DESTDIR)$(TCLLIBDIR) + $(LTINSTALL) libtclsqlite3.la $(DESTDIR)$(TCLLIBDIR) + rm -f $(DESTDIR)$(TCLLIBDIR)/libtclsqlite3.la $(DESTDIR)$(TCLLIBDIR)/libtclsqlite3.a + $(INSTALL) -m 0644 pkgIndex.tcl $(DESTDIR)$(TCLLIBDIR) + +clean: + rm -f *.lo *.la *.o sqlite3$(TEXE) libsqlite3.la + rm -f sqlite3.h opcodes.* + rm -rf .libs .deps + rm -f lemon$(BEXE) lempar.c parse.* sqlite*.tar.gz + rm -f mkkeywordhash$(BEXE) keywordhash.h + rm -f *.da *.bb *.bbg gmon.out + rm -rf quota2a quota2b quota2c + rm -rf tsrc .target_source + rm -f tclsqlite3$(TEXE) + rm -f testfixture$(TEXE) test.db + rm -f sqlite3.dll sqlite3.lib sqlite3.exp sqlite3.def + rm -f sqlite3.c + rm -f sqlite3rc.h + rm -f shell.c sqlite3ext.h + rm -f sqlite3_analyzer$(TEXE) sqlite3_analyzer.c + rm -f sqlite-*-output.vsix + rm -f mptester mptester.exe + +distclean: clean + rm -f config.log config.status libtool Makefile sqlite3.pc + +# +# Windows section +# +dll: sqlite3.dll + +REAL_LIBOBJ = $(LIBOBJ:%.lo=.libs/%.o) + +$(REAL_LIBOBJ): $(LIBOBJ) + +sqlite3.def: $(REAL_LIBOBJ) + echo 'EXPORTS' >sqlite3.def + nm $(REAL_LIBOBJ) | grep ' T ' | grep ' _sqlite3_' \ + | sed 's/^.* _//' >>sqlite3.def + +sqlite3.dll: $(REAL_LIBOBJ) sqlite3.def + $(TCC) -shared -o $@ sqlite3.def \ + -Wl,"--strip-all" $(REAL_LIBOBJ) diff --git a/components/external/SQLite-3.8.1/make/README b/components/external/SQLite-3.8.1/make/README new file mode 100644 index 0000000000000000000000000000000000000000..dc915b1978aa79ac3d6740387c5d5adec0a77e1c --- /dev/null +++ b/components/external/SQLite-3.8.1/make/README @@ -0,0 +1,13 @@ +Õâ¸öĿ¼ÓÃÀ´Éú³Ésqlite3.c/.hºÍconfig.h +Èç¹ûÄãÒªÖØÐÂÉú³É£¬ÔòÏÈ°²×°TclÓïÑÔ¡£ +È»ºó±¸·Ýconfig.h +Éú³ÉÖ®ºó£¬²ÎÕÕÏÖÔÚµÄconfig.hÀ´ÅäÖÃÐÂÉú³ÉµÄconfig.hÎļþ¡£ +Ö´ÐÐmake¾Í»áÖØÐÂÉú³É¡£ +Ö®ºó¿ÉÒԵõ½sqlite3.c/.h + +ÄãÒ²¿ÉÒÔ×Ô¼ºÉú³ÉMakefile£¬×¢ÒâÏȱ¸·ÝMakefile +Ö´ÐÐ../configure¾Í¿ÉÒÔÉú³ÉMakefile¡£ +--host²ÎÊýÓÃÀ´Ö¸¶¨±àÒëÆ÷£¬¸üÏêϸµÄ²ÎÊýÎÒûÓÐÑо¿¡£ÒªÊÇÄãÖªµÀ +¸üÏêϸµÄ²Ù×÷°ì·¨£¬¿ÉÒÔÍêÉÆÕâ¸öÎļþ¡£ +ÀýÈ磺../configure --host=arm-none-eabi +Ö®ºóÉú³ÉµÄMakefile¿ÉÒÔ²ÎÕÕÀÏ°æ±¾µÄMakefileÀ´Ð޸ġ£ \ No newline at end of file diff --git a/components/external/SQLite-3.8.1/make/config.h b/components/external/SQLite-3.8.1/make/config.h new file mode 100644 index 0000000000000000000000000000000000000000..8b711f73a5c575e1e59df2a3ff7752295e30e7c7 --- /dev/null +++ b/components/external/SQLite-3.8.1/make/config.h @@ -0,0 +1,114 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_DLFCN_H */ + +/* Define to 1 if you have the `fdatasync' function. */ +/* #undef HAVE_FDATASYNC */ + +/* Define to 1 if you have the `gmtime_r' function. */ +#define HAVE_GMTIME_R 1 + +/* Define to 1 if the system has the type `int16_t'. */ +#define HAVE_INT16_T 1 + +/* Define to 1 if the system has the type `int32_t'. */ +#define HAVE_INT32_T 1 + +/* Define to 1 if the system has the type `int64_t'. */ +#define HAVE_INT64_T 1 + +/* Define to 1 if the system has the type `int8_t'. */ +#define HAVE_INT8_T 1 + +/* Define to 1 if the system has the type `intptr_t'. */ +#define HAVE_INTPTR_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `localtime_r' function. */ +#define HAVE_LOCALTIME_R 1 + +/* Define to 1 if you have the `localtime_s' function. */ +/* #undef HAVE_LOCALTIME_S */ + +/* Define to 1 if you have the header file. */ +/* #define HAVE_MALLOC_H 0 */ + +/* Define to 1 if you have the `malloc_usable_size' function. */ +/* #define HAVE_MALLOC_USABLE_SIZE 0 */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_MEMORY_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_STRINGS_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if the system has the type `uint16_t'. */ +#define HAVE_UINT16_T 1 + +/* Define to 1 if the system has the type `uint32_t'. */ +#define HAVE_UINT32_T 1 + +/* Define to 1 if the system has the type `uint64_t'. */ +#define HAVE_UINT64_T 1 + +/* Define to 1 if the system has the type `uint8_t'. */ +#define HAVE_UINT8_T 1 + +/* Define to 1 if the system has the type `uintptr_t'. */ +#define HAVE_UINTPTR_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the `usleep' function. */ +/* #undef HAVE_USLEEP */ + +/* Define to 1 if you have the utime() library function. */ +/* #undef HAVE_UTIME */ + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#define LT_OBJDIR ".libs/" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "sqlite" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "sqlite 3.8.1" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "sqlite" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "3.8.1" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Number of bits in a file offset, on hosts where this is settable. */ +/* #undef _FILE_OFFSET_BITS */ + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ diff --git a/components/external/SQLite-3.8.1/make/config.h.bak b/components/external/SQLite-3.8.1/make/config.h.bak new file mode 100644 index 0000000000000000000000000000000000000000..e64095bf96b35974f008c77c13f8ad4914d7cf3d --- /dev/null +++ b/components/external/SQLite-3.8.1/make/config.h.bak @@ -0,0 +1,114 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_DLFCN_H */ + +/* Define to 1 if you have the `fdatasync' function. */ +/* #undef HAVE_FDATASYNC */ + +/* Define to 1 if you have the `gmtime_r' function. */ +#define HAVE_GMTIME_R 1 + +/* Define to 1 if the system has the type `int16_t'. */ +#define HAVE_INT16_T 1 + +/* Define to 1 if the system has the type `int32_t'. */ +#define HAVE_INT32_T 1 + +/* Define to 1 if the system has the type `int64_t'. */ +#define HAVE_INT64_T 1 + +/* Define to 1 if the system has the type `int8_t'. */ +#define HAVE_INT8_T 1 + +/* Define to 1 if the system has the type `intptr_t'. */ +#define HAVE_INTPTR_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `localtime_r' function. */ +#define HAVE_LOCALTIME_R 1 + +/* Define to 1 if you have the `localtime_s' function. */ +/* #undef HAVE_LOCALTIME_S */ + +/* Define to 1 if you have the header file. */ +/* #define HAVE_MALLOC_H 0 */ + +/* Define to 1 if you have the `malloc_usable_size' function. */ +//#define HAVE_MALLOC_USABLE_SIZE 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_MEMORY_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_STRINGS_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if the system has the type `uint16_t'. */ +#define HAVE_UINT16_T 1 + +/* Define to 1 if the system has the type `uint32_t'. */ +#define HAVE_UINT32_T 1 + +/* Define to 1 if the system has the type `uint64_t'. */ +#define HAVE_UINT64_T 1 + +/* Define to 1 if the system has the type `uint8_t'. */ +#define HAVE_UINT8_T 1 + +/* Define to 1 if the system has the type `uintptr_t'. */ +#define HAVE_UINTPTR_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the `usleep' function. */ +/* #undef HAVE_USLEEP */ + +/* Define to 1 if you have the utime() library function. */ +/* #undef HAVE_UTIME */ + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#define LT_OBJDIR ".libs/" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "sqlite" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "sqlite 3.8.1" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "sqlite" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "3.8.1" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Number of bits in a file offset, on hosts where this is settable. */ +/* #undef _FILE_OFFSET_BITS */ + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ diff --git a/components/external/SQLite-3.8.1/make/config.log b/components/external/SQLite-3.8.1/make/config.log new file mode 100644 index 0000000000000000000000000000000000000000..b16dfa8b8649ccae1b07a1c5b4e01078c98f8b54 --- /dev/null +++ b/components/external/SQLite-3.8.1/make/config.log @@ -0,0 +1,2646 @@ +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by sqlite configure 3.8.1, which was +generated by GNU Autoconf 2.62. Invocation command line was + + $ ../configure --host=arm-none-eabi + +## --------- ## +## Platform. ## +## --------- ## + +hostname = geniuscode +uname -m = i686 +uname -r = 1.7.25(0.270/5/3) +uname -s = CYGWIN_NT-6.1 +uname -v = 2013-08-31 20:39 + +/usr/bin/uname -p = unknown +/bin/uname -X = unknown + +/bin/arch = i686 +/usr/bin/arch -k = unknown +/usr/convex/getsysinfo = unknown +/usr/bin/hostinfo = unknown +/bin/machine = unknown +/usr/bin/oslevel = unknown +/bin/universe = unknown + +PATH: /usr/local/bin +PATH: /usr/bin +PATH: /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin +PATH: /cygdrive/c/Windows/system32 +PATH: /cygdrive/c/Windows +PATH: /cygdrive/c/Windows/System32/Wbem +PATH: /cygdrive/c/Windows/System32/WindowsPowerShell/v1.0 +PATH: /cygdrive/c/Program Files/CodeBlocks/MinGW/bin +PATH: . +PATH: /cygdrive/c/Program Files/Git/cmd +PATH: /cygdrive/c/Program Files/Git/bin +PATH: /cygdrive/c/Python27 +PATH: /cygdrive/c/Python27/Lib +PATH: /cygdrive/c/Python27/Scripts +PATH: /cygdrive/c/Program Files/TortoiseGit/bin +PATH: . + + +## ----------- ## +## Core tests. ## +## ----------- ## + +configure:2129: checking build system type +configure:2147: result: i686-pc-cygwin +configure:2169: checking host system type +configure:2184: result: arm-none-eabi +configure:2214: checking for arm-none-eabi-gcc +configure:2230: found /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-gcc +configure:2241: result: arm-none-eabi-gcc +configure:2519: checking for C compiler version +configure:2527: arm-none-eabi-gcc --version >&5 +arm-none-eabi-gcc.exe (Sourcery CodeBench Lite 2012.03-56) 4.6.3 +Copyright (C) 2011 Free Software Foundation, Inc. +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +configure:2531: $? = 0 +configure:2538: arm-none-eabi-gcc -v >&5 +Using built-in specs. +COLLECT_GCC=C:\Program Files\CodeSourcery\Sourcery_CodeBench_Lite_for_ARM_EABI\bin\arm-none-eabi-gcc.exe +COLLECT_LTO_WRAPPER=c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../libexec/gcc/arm-none-eabi/4.6.3/lto-wrapper.exe +Target: arm-none-eabi +Configured with: /scratch/nsidwell/arm/eabi/src/gcc-4.6-2012.03/configure --build=i686-pc-linux-gnu --host=i686-mingw32 --target=arm-none-eabi --enable-threads --disable-libmudflap --disable-libssp --disable-libstdcxx-pch --enable-extra-sgxxlite-multilibs --with-gnu-as --with-gnu-ld --with-specs='%{save-temps: -fverbose-asm} -D__CS_SOURCERYGXX_MAJ__=2012 -D__CS_SOURCERYGXX_MIN__=3 -D__CS_SOURCERYGXX_REV__=56 %{O2:%{!fno-remove-local-statics: -fremove-local-statics}} %{O*:%{O|O0|O1|O2|Os:;:%{!fno-remove-local-statics: -fremove-local-statics}}}' --enable-languages=c,c++ --disable-shared --enable-lto --with-newlib --with-pkgversion='Sourcery CodeBench Lite 2012.03-56' --with-bugurl=https://support.codesourcery.com/GNUToolchain/ --disable-nls --prefix=/opt/codesourcery --with-headers=yes --with-sysroot=/opt/codesourcery/arm-none-eabi --with-build-sysroot=/scratch/nsidwell/arm/eabi/install/host-i686-mingw32/arm-none-eabi --with-libiconv-prefix=/scratch/nsidwell/arm/eabi/obj/host-libs-2012.03-56-arm-none-eabi-i686-mingw32/usr --with-gmp=/scratch/nsidwell/arm/eabi/obj/host-libs-2012.03-56-arm-none-eabi-i686-mingw32/usr --with-mpfr=/scratch/nsidwell/arm/eabi/obj/host-libs-2012.03-56-arm-none-eabi-i686-mingw32/usr --with-mpc=/scratch/nsidwell/arm/eabi/obj/host-libs-2012.03-56-arm-none-eabi-i686-mingw32/usr --with-ppl=/scratch/nsidwell/arm/eabi/obj/host-libs-2012.03-56-arm-none-eabi-i686-mingw32/usr --with-host-libstdcxx='-static-libgcc -Wl,-Bstatic,-lstdc++,-Bdynamic -lm' --with-cloog=/scratch/nsidwell/arm/eabi/obj/host-libs-2012.03-56-arm-none-eabi-i686-mingw32/usr --with-libelf=/scratch/nsidwell/arm/eabi/obj/host-libs-2012.03-56-arm-none-eabi-i686-mingw32/usr --disable-libgomp --enable-poison-system-directories --with-build-time-tools=/scratch/nsidwell/arm/eabi/obj/tools-i686-pc-linux-gnu-2012.03-56-arm-none-eabi-i686-mingw32/arm-none-eabi/bin --with-build-time-tools=/scratch/nsidwell/arm/eabi/obj/tools-i686-pc-linux-gnu-2012.03-56-arm-none-eabi-i686-mingw32/arm-none-eabi/bin +Thread model: single +gcc version 4.6.3 (Sourcery CodeBench Lite 2012.03-56) +configure:2542: $? = 0 +configure:2549: arm-none-eabi-gcc -V >&5 +arm-none-eabi-gcc.exe: error: unrecognized option '-V' +arm-none-eabi-gcc.exe: fatal error: no input files +compilation terminated. +configure:2553: $? = 1 +configure:2576: checking for C compiler default output file name +configure:2598: arm-none-eabi-gcc conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +configure:2602: $? = 0 +configure:2640: result: a.out +configure:2657: checking whether the C compiler works +configure:2667: ./a.out +../configure: line 2669: ./a.out: cannot execute binary file +configure:2671: $? = 126 +configure:2688: result: yes +configure:2695: checking whether we are cross compiling +configure:2697: result: yes +configure:2700: checking for suffix of executables +configure:2707: arm-none-eabi-gcc -o conftest conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +configure:2711: $? = 0 +configure:2735: result: +configure:2741: checking for suffix of object files +configure:2767: arm-none-eabi-gcc -c conftest.c >&5 +configure:2771: $? = 0 +configure:2794: result: o +configure:2798: checking whether we are using the GNU C compiler +configure:2827: arm-none-eabi-gcc -c conftest.c >&5 +configure:2834: $? = 0 +configure:2851: result: yes +configure:2860: checking whether arm-none-eabi-gcc accepts -g +configure:2890: arm-none-eabi-gcc -c -g conftest.c >&5 +configure:2897: $? = 0 +configure:2998: result: yes +configure:3015: checking for arm-none-eabi-gcc option to accept ISO C89 +configure:3089: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:3096: $? = 0 +configure:3119: result: none needed +configure:3137: checking for a sed that does not truncate output +configure:3203: result: /usr/bin/sed +configure:3221: checking for grep that handles long lines and -e +configure:3281: result: /usr/bin/grep +configure:3286: checking for egrep +configure:3350: result: /usr/bin/grep -E +configure:3355: checking for fgrep +configure:3419: result: /usr/bin/grep -F +configure:3454: checking for ld used by arm-none-eabi-gcc +configure:3521: result: c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/arm-none-eabi/bin/ld.exe +configure:3530: checking if the linker (c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/arm-none-eabi/bin/ld.exe) is GNU ld +configure:3545: result: no +configure:3557: checking for BSD- or MS-compatible name lister (nm) +configure:3606: result: /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B +configure:3728: checking the name lister (/cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B) interface +configure:3735: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:3738: /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B "conftest.o" +../configure: line 3739: /cygdrive/c/Program: No such file or directory +configure:3741: output +configure:3748: result: BSD nm +configure:3751: checking whether ln -s works +configure:3755: result: yes +configure:3763: checking the maximum length of command line arguments +configure:3883: result: 8192 +configure:3900: checking whether the shell understands some XSI constructs +configure:3910: result: yes +configure:3914: checking whether the shell understands "+=" +configure:3920: result: yes +configure:3955: checking for c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/arm-none-eabi/bin/ld.exe option to reload object files +configure:3962: result: -r +configure:3991: checking for arm-none-eabi-objdump +configure:4007: found /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-objdump +configure:4018: result: arm-none-eabi-objdump +configure:4094: checking how to recognize dependent libraries +configure:4290: result: unknown +configure:4310: checking for arm-none-eabi-ar +configure:4326: found /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-ar +configure:4337: result: arm-none-eabi-ar +configure:4419: checking for arm-none-eabi-strip +configure:4435: found /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-strip +configure:4446: result: arm-none-eabi-strip +configure:4522: checking for arm-none-eabi-ranlib +configure:4538: found /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-ranlib +configure:4549: result: arm-none-eabi-ranlib +configure:4683: checking command to parse /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B output from arm-none-eabi-gcc object +configure:4801: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:4804: $? = 0 +configure:4808: /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B conftest.o \| sed -n -e 's/^.*[ ]\([BCDEGRST][BCDEGRST]*\)[ ][ ]*\([_A-Za-z][_A-Za-z0-9]*\)$/\1 \2 \2/p' \> conftest.nm +../configure: line 4809: /cygdrive/c/Program: No such file or directory +configure:4811: $? = 0 +cannot run sed -n -e 's/^.*[ ]\([BCDEGRST][BCDEGRST]*\)[ ][ ]*\([_A-Za-z][_A-Za-z0-9]*\)$/\1 \2 \2/p' +configure:4801: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:4804: $? = 0 +configure:4808: /cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B conftest.o \| sed -n -e 's/^.*[ ]\([BCDEGRST][BCDEGRST]*\)[ ][ ]*_\([_A-Za-z][_A-Za-z0-9]*\)$/\1 _\2 \2/p' \> conftest.nm +../configure: line 4809: /cygdrive/c/Program: No such file or directory +configure:4811: $? = 0 +cannot run sed -n -e 's/^.*[ ]\([BCDEGRST][BCDEGRST]*\)[ ][ ]*_\([_A-Za-z][_A-Za-z0-9]*\)$/\1 _\2 \2/p' +configure:4903: result: failed +configure:5793: checking how to run the C preprocessor +configure:5833: arm-none-eabi-gcc -E conftest.c +configure:5840: $? = 0 +configure:5871: arm-none-eabi-gcc -E conftest.c +conftest.c:8:28: fatal error: ac_nonexistent.h: No such file or directory +compilation terminated. +configure:5878: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| /* end confdefs.h. */ +| #include +configure:5911: result: arm-none-eabi-gcc -E +configure:5940: arm-none-eabi-gcc -E conftest.c +configure:5947: $? = 0 +configure:5978: arm-none-eabi-gcc -E conftest.c +conftest.c:8:28: fatal error: ac_nonexistent.h: No such file or directory +compilation terminated. +configure:5985: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| /* end confdefs.h. */ +| #include +configure:6023: checking for ANSI C header files +configure:6053: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:6060: $? = 0 +configure:6191: result: yes +configure:6215: checking for sys/types.h +configure:6236: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:6243: $? = 0 +configure:6260: result: yes +configure:6215: checking for sys/stat.h +configure:6236: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:6243: $? = 0 +configure:6260: result: yes +configure:6215: checking for stdlib.h +configure:6236: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:6243: $? = 0 +configure:6260: result: yes +configure:6215: checking for string.h +configure:6236: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:6243: $? = 0 +configure:6260: result: yes +configure:6215: checking for memory.h +configure:6236: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c:47:20: fatal error: memory.h: No such file or directory +compilation terminated. +configure:6243: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| +| #include +configure:6260: result: no +configure:6215: checking for strings.h +configure:6236: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c:47:21: fatal error: strings.h: No such file or directory +compilation terminated. +configure:6243: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| +| #include +configure:6260: result: no +configure:6215: checking for inttypes.h +configure:6236: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:6243: $? = 0 +configure:6260: result: yes +configure:6215: checking for stdint.h +configure:6236: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:6243: $? = 0 +configure:6260: result: yes +configure:6215: checking for unistd.h +configure:6236: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:6243: $? = 0 +configure:6260: result: yes +configure:6277: checking for dlfcn.h +configure:6298: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c:50:19: fatal error: dlfcn.h: No such file or directory +compilation terminated. +configure:6305: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| +| #include +configure:6322: result: no +configure:6507: checking for objdir +configure:6522: result: .libs +configure:6814: checking if arm-none-eabi-gcc supports -fno-rtti -fno-exceptions +configure:6832: arm-none-eabi-gcc -c -g -O2 -fno-rtti -fno-exceptions conftest.c >&5 +cc1.exe: warning: command line option '-fno-rtti' is valid for C++/ObjC++ but not for C [enabled by default] +configure:6836: $? = 0 +configure:6849: result: no +configure:6869: checking for arm-none-eabi-gcc option to produce PIC +configure:7141: result: -fPIC -DPIC +configure:7153: checking if arm-none-eabi-gcc PIC flag -fPIC -DPIC works +configure:7171: arm-none-eabi-gcc -c -g -O2 -fPIC -DPIC -DPIC conftest.c >&5 +configure:7175: $? = 0 +configure:7188: result: yes +configure:7212: checking if arm-none-eabi-gcc static flag -static works +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +configure:7240: result: yes +configure:7255: checking if arm-none-eabi-gcc supports -c -o file.o +configure:7276: arm-none-eabi-gcc -c -g -O2 -o out/conftest2.o conftest.c >&5 +configure:7280: $? = 0 +configure:7302: result: yes +configure:7310: checking if arm-none-eabi-gcc supports -c -o file.o +configure:7357: result: yes +configure:7390: checking whether the arm-none-eabi-gcc linker (c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/arm-none-eabi/bin/ld.exe) supports shared libraries +configure:8464: result: no +configure:8703: checking dynamic linker characteristics +configure:9399: result: no +configure:9501: checking how to hardcode library paths into programs +configure:9526: result: unsupported +configure:10359: checking whether stripping libraries is possible +configure:10364: result: yes +configure:10399: checking if libtool supports shared libraries +configure:10401: result: no +configure:10404: checking whether to build shared libraries +configure:10425: result: no +configure:10428: checking whether to build static libraries +configure:10432: result: yes +configure:10481: checking for a BSD-compatible install +configure:10549: result: /usr/bin/install -c +configure:10564: checking for gawk +configure:10580: found /usr/bin/gawk +configure:10591: result: gawk +configure:10613: checking for special C compiler options needed for large files +configure:10708: result: no +configure:10714: checking for _FILE_OFFSET_BITS value needed for large files +configure:10749: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c:23:3: warning: left shift count >= width of type [enabled by default] +conftest.c:23:3: warning: left shift count >= width of type [enabled by default] +conftest.c:24:10: warning: left shift count >= width of type [enabled by default] +conftest.c:24:10: warning: left shift count >= width of type [enabled by default] +conftest.c:23:7: error: size of array 'off_t_is_large' is negative +conftest.c:25:9: warning: variably modified 'off_t_is_large' at file scope [enabled by default] +configure:10756: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| /* end confdefs.h. */ +| #include +| /* Check that off_t can represent 2**63 - 1 correctly. +| We can't simply define LARGE_OFF_T to be 9223372036854775807, +| since some C++ compilers masquerading as C compilers +| incorrectly reject 9223372036854775807. */ +| #define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) +| int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 +| && LARGE_OFF_T % 2147483647 == 1) +| ? 1 : -1]; +| int +| main () +| { +| +| ; +| return 0; +| } +configure:10800: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c:24:3: warning: left shift count >= width of type [enabled by default] +conftest.c:24:3: warning: left shift count >= width of type [enabled by default] +conftest.c:25:10: warning: left shift count >= width of type [enabled by default] +conftest.c:25:10: warning: left shift count >= width of type [enabled by default] +conftest.c:24:7: error: size of array 'off_t_is_large' is negative +conftest.c:26:9: warning: variably modified 'off_t_is_large' at file scope [enabled by default] +configure:10807: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| /* end confdefs.h. */ +| #define _FILE_OFFSET_BITS 64 +| #include +| /* Check that off_t can represent 2**63 - 1 correctly. +| We can't simply define LARGE_OFF_T to be 9223372036854775807, +| since some C++ compilers masquerading as C compilers +| incorrectly reject 9223372036854775807. */ +| #define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) +| int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 +| && LARGE_OFF_T % 2147483647 == 1) +| ? 1 : -1]; +| int +| main () +| { +| +| ; +| return 0; +| } +configure:10825: result: unknown +configure:10837: checking for _LARGE_FILES value needed for large files +configure:10872: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c:23:3: warning: left shift count >= width of type [enabled by default] +conftest.c:23:3: warning: left shift count >= width of type [enabled by default] +conftest.c:24:10: warning: left shift count >= width of type [enabled by default] +conftest.c:24:10: warning: left shift count >= width of type [enabled by default] +conftest.c:23:7: error: size of array 'off_t_is_large' is negative +conftest.c:25:9: warning: variably modified 'off_t_is_large' at file scope [enabled by default] +configure:10879: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| /* end confdefs.h. */ +| #include +| /* Check that off_t can represent 2**63 - 1 correctly. +| We can't simply define LARGE_OFF_T to be 9223372036854775807, +| since some C++ compilers masquerading as C compilers +| incorrectly reject 9223372036854775807. */ +| #define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) +| int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 +| && LARGE_OFF_T % 2147483647 == 1) +| ? 1 : -1]; +| int +| main () +| { +| +| ; +| return 0; +| } +configure:10923: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c:24:3: warning: left shift count >= width of type [enabled by default] +conftest.c:24:3: warning: left shift count >= width of type [enabled by default] +conftest.c:25:10: warning: left shift count >= width of type [enabled by default] +conftest.c:25:10: warning: left shift count >= width of type [enabled by default] +conftest.c:24:7: error: size of array 'off_t_is_large' is negative +conftest.c:26:9: warning: variably modified 'off_t_is_large' at file scope [enabled by default] +configure:10930: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| /* end confdefs.h. */ +| #define _LARGE_FILES 1 +| #include +| /* Check that off_t can represent 2**63 - 1 correctly. +| We can't simply define LARGE_OFF_T to be 9223372036854775807, +| since some C++ compilers masquerading as C compilers +| incorrectly reject 9223372036854775807. */ +| #define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) +| int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 +| && LARGE_OFF_T % 2147483647 == 1) +| ? 1 : -1]; +| int +| main () +| { +| +| ; +| return 0; +| } +configure:10948: result: unknown +configure:10965: checking for int8_t +configure:10993: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11000: $? = 0 +configure:11027: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:53:21: error: expected expression before ')' token +configure:11034: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((int8_t))) +| return 0; +| ; +| return 0; +| } +configure:11057: result: yes +configure:11067: checking for int16_t +configure:11095: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11102: $? = 0 +configure:11129: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:54:22: error: expected expression before ')' token +configure:11136: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((int16_t))) +| return 0; +| ; +| return 0; +| } +configure:11159: result: yes +configure:11169: checking for int32_t +configure:11197: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11204: $? = 0 +configure:11231: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:55:22: error: expected expression before ')' token +configure:11238: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((int32_t))) +| return 0; +| ; +| return 0; +| } +configure:11261: result: yes +configure:11271: checking for int64_t +configure:11299: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11306: $? = 0 +configure:11333: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:56:22: error: expected expression before ')' token +configure:11340: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((int64_t))) +| return 0; +| ; +| return 0; +| } +configure:11363: result: yes +configure:11373: checking for intptr_t +configure:11401: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11408: $? = 0 +configure:11435: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:57:23: error: expected expression before ')' token +configure:11442: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((intptr_t))) +| return 0; +| ; +| return 0; +| } +configure:11465: result: yes +configure:11475: checking for uint8_t +configure:11503: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11510: $? = 0 +configure:11537: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:58:22: error: expected expression before ')' token +configure:11544: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((uint8_t))) +| return 0; +| ; +| return 0; +| } +configure:11567: result: yes +configure:11577: checking for uint16_t +configure:11605: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11612: $? = 0 +configure:11639: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:59:23: error: expected expression before ')' token +configure:11646: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((uint16_t))) +| return 0; +| ; +| return 0; +| } +configure:11669: result: yes +configure:11679: checking for uint32_t +configure:11707: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11714: $? = 0 +configure:11741: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:60:23: error: expected expression before ')' token +configure:11748: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((uint32_t))) +| return 0; +| ; +| return 0; +| } +configure:11771: result: yes +configure:11781: checking for uint64_t +configure:11809: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11816: $? = 0 +configure:11843: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:61:23: error: expected expression before ')' token +configure:11850: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((uint64_t))) +| return 0; +| ; +| return 0; +| } +configure:11873: result: yes +configure:11883: checking for uintptr_t +configure:11911: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:11918: $? = 0 +configure:11945: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +conftest.c: In function 'main': +conftest.c:62:24: error: expected expression before ')' token +configure:11952: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| int +| main () +| { +| if (sizeof ((uintptr_t))) +| return 0; +| ; +| return 0; +| } +configure:11975: result: yes +configure:11998: checking for sys/types.h +configure:12005: result: yes +configure:11998: checking for stdlib.h +configure:12005: result: yes +configure:11998: checking for stdint.h +configure:12005: result: yes +configure:11998: checking for inttypes.h +configure:12005: result: yes +configure:12009: checking malloc.h usability +configure:12026: arm-none-eabi-gcc -c -g -O2 conftest.c >&5 +configure:12033: $? = 0 +configure:12047: result: yes +configure:12051: checking malloc.h presence +configure:12066: arm-none-eabi-gcc -E conftest.c +configure:12073: $? = 0 +configure:12087: result: yes +configure:12115: checking for malloc.h +configure:12124: result: yes +configure:12152: checking for usleep +configure:12208: arm-none-eabi-gcc -o conftest -g -O2 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +C:\cygwin\tmp\ccmfmFhK.o: In function `main': +E:\rt-thread\components\external\SQLite-3.8.1\make/conftest.c:66: undefined reference to `usleep' +collect2: ld returned 1 exit status +configure:12215: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| /* end confdefs.h. */ +| /* Define usleep to an innocuous variant, in case declares usleep. +| For example, HP-UX 11i declares gettimeofday. */ +| #define usleep innocuous_usleep +| +| /* System header to define __stub macros and hopefully few prototypes, +| which can conflict with char usleep (); below. +| Prefer to if __STDC__ is defined, since +| exists even on freestanding compilers. */ +| +| #ifdef __STDC__ +| # include +| #else +| # include +| #endif +| +| #undef usleep +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char usleep (); +| /* The GNU C library defines this for functions which it implements +| to always fail with ENOSYS. Some functions are actually named +| something starting with __ and the normal name is an alias. */ +| #if defined __stub_usleep || defined __stub___usleep +| choke me +| #endif +| +| int +| main () +| { +| return usleep (); +| ; +| return 0; +| } +configure:12237: result: no +configure:12152: checking for fdatasync +configure:12208: arm-none-eabi-gcc -o conftest -g -O2 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +C:\cygwin\tmp\ccIA003u.o: In function `main': +E:\rt-thread\components\external\SQLite-3.8.1\make/conftest.c:66: undefined reference to `fdatasync' +collect2: ld returned 1 exit status +configure:12215: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| /* end confdefs.h. */ +| /* Define fdatasync to an innocuous variant, in case declares fdatasync. +| For example, HP-UX 11i declares gettimeofday. */ +| #define fdatasync innocuous_fdatasync +| +| /* System header to define __stub macros and hopefully few prototypes, +| which can conflict with char fdatasync (); below. +| Prefer to if __STDC__ is defined, since +| exists even on freestanding compilers. */ +| +| #ifdef __STDC__ +| # include +| #else +| # include +| #endif +| +| #undef fdatasync +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char fdatasync (); +| /* The GNU C library defines this for functions which it implements +| to always fail with ENOSYS. Some functions are actually named +| something starting with __ and the normal name is an alias. */ +| #if defined __stub_fdatasync || defined __stub___fdatasync +| choke me +| #endif +| +| int +| main () +| { +| return fdatasync (); +| ; +| return 0; +| } +configure:12237: result: no +configure:12152: checking for localtime_r +configure:12208: arm-none-eabi-gcc -o conftest -g -O2 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +configure:12215: $? = 0 +configure:12237: result: yes +configure:12152: checking for gmtime_r +configure:12208: arm-none-eabi-gcc -o conftest -g -O2 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +configure:12215: $? = 0 +configure:12237: result: yes +configure:12152: checking for localtime_s +configure:12208: arm-none-eabi-gcc -o conftest -g -O2 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +C:\cygwin\tmp\ccQgpJ1T.o: In function `main': +E:\rt-thread\components\external\SQLite-3.8.1\make/conftest.c:68: undefined reference to `localtime_s' +collect2: ld returned 1 exit status +configure:12215: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| /* end confdefs.h. */ +| /* Define localtime_s to an innocuous variant, in case declares localtime_s. +| For example, HP-UX 11i declares gettimeofday. */ +| #define localtime_s innocuous_localtime_s +| +| /* System header to define __stub macros and hopefully few prototypes, +| which can conflict with char localtime_s (); below. +| Prefer to if __STDC__ is defined, since +| exists even on freestanding compilers. */ +| +| #ifdef __STDC__ +| # include +| #else +| # include +| #endif +| +| #undef localtime_s +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char localtime_s (); +| /* The GNU C library defines this for functions which it implements +| to always fail with ENOSYS. Some functions are actually named +| something starting with __ and the normal name is an alias. */ +| #if defined __stub_localtime_s || defined __stub___localtime_s +| choke me +| #endif +| +| int +| main () +| { +| return localtime_s (); +| ; +| return 0; +| } +configure:12237: result: no +configure:12152: checking for utime +configure:12208: arm-none-eabi-gcc -o conftest -g -O2 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +C:\cygwin\tmp\cc43rkMv.o: In function `main': +E:\rt-thread\components\external\SQLite-3.8.1\make/conftest.c:68: undefined reference to `utime' +collect2: ld returned 1 exit status +configure:12215: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| /* end confdefs.h. */ +| /* Define utime to an innocuous variant, in case declares utime. +| For example, HP-UX 11i declares gettimeofday. */ +| #define utime innocuous_utime +| +| /* System header to define __stub macros and hopefully few prototypes, +| which can conflict with char utime (); below. +| Prefer to if __STDC__ is defined, since +| exists even on freestanding compilers. */ +| +| #ifdef __STDC__ +| # include +| #else +| # include +| #endif +| +| #undef utime +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char utime (); +| /* The GNU C library defines this for functions which it implements +| to always fail with ENOSYS. Some functions are actually named +| something starting with __ and the normal name is an alias. */ +| #if defined __stub_utime || defined __stub___utime +| choke me +| #endif +| +| int +| main () +| { +| return utime (); +| ; +| return 0; +| } +configure:12237: result: no +configure:12152: checking for malloc_usable_size +configure:12208: arm-none-eabi-gcc -o conftest -g -O2 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +configure:12215: $? = 0 +configure:12237: result: yes +configure:12263: checking for tclsh8.6 +configure:12293: result: no +configure:12263: checking for tclsh8.5 +configure:12279: found /usr/bin/tclsh8.5 +configure:12290: result: tclsh8.5 +configure:12331: Version set to 3.8 +configure:12335: Release set to 3.8.1 +configure:12341: Version number set to 3008001 +configure:12397: checking for gcc +configure:12413: found /usr/bin/gcc +configure:12424: result: gcc +configure:12452: checking whether to support threadsafe operation +configure:12460: result: yes +configure:12466: checking for library containing pthread_create +configure:12507: arm-none-eabi-gcc -o conftest -g -O2 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +C:\cygwin\tmp\ccucoypj.o: In function `main': +E:\rt-thread\components\external\SQLite-3.8.1\make/conftest.c:46: undefined reference to `pthread_create' +collect2: ld returned 1 exit status +configure:12514: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char pthread_create (); +| int +| main () +| { +| return pthread_create (); +| ; +| return 0; +| } +configure:12507: arm-none-eabi-gcc -o conftest -g -O2 conftest.c -lpthread >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: cannot find -lpthread +collect2: ld returned 1 exit status +configure:12514: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char pthread_create (); +| int +| main () +| { +| return pthread_create (); +| ; +| return 0; +| } +configure:12545: result: no +configure:12567: checking whether to allow connections to be shared across threads +configure:12571: result: no +configure:12590: checking whether to support shared library linked as release mode or not +configure:12594: result: no +configure:12613: checking whether to use an in-ram database for temporary tables +configure:12623: result: no +configure:12650: checking if executables have the .exe suffix +configure:12657: result: unknown +configure:12661: checking host system type +configure:12676: result: arm-none-eabi +configure:12751: checking for Tcl configuration +configure:12847: result: found /usr/lib/tclConfig.sh +configure:12850: checking for existence of /usr/lib/tclConfig.sh +configure:12853: result: loading +configure:12938: checking for library containing tgetent +configure:12979: arm-none-eabi-gcc -o conftest -g -O2 -DSQLITE_OS_UNIX=1 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +C:\cygwin\tmp\cc8HgZuF.o: In function `main': +E:\rt-thread\components\external\SQLite-3.8.1\make/conftest.c:46: undefined reference to `tgetent' +collect2: ld returned 1 exit status +configure:12986: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char tgetent (); +| int +| main () +| { +| return tgetent (); +| ; +| return 0; +| } +configure:12979: arm-none-eabi-gcc -o conftest -g -O2 -DSQLITE_OS_UNIX=1 conftest.c -lreadline >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: cannot find -lreadline +collect2: ld returned 1 exit status +configure:12986: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char tgetent (); +| int +| main () +| { +| return tgetent (); +| ; +| return 0; +| } +configure:12979: arm-none-eabi-gcc -o conftest -g -O2 -DSQLITE_OS_UNIX=1 conftest.c -lncurses >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: cannot find -lncurses +collect2: ld returned 1 exit status +configure:12986: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char tgetent (); +| int +| main () +| { +| return tgetent (); +| ; +| return 0; +| } +configure:12979: arm-none-eabi-gcc -o conftest -g -O2 -DSQLITE_OS_UNIX=1 conftest.c -lcurses >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: cannot find -lcurses +collect2: ld returned 1 exit status +configure:12986: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char tgetent (); +| int +| main () +| { +| return tgetent (); +| ; +| return 0; +| } +configure:12979: arm-none-eabi-gcc -o conftest -g -O2 -DSQLITE_OS_UNIX=1 conftest.c -ltermcap >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: cannot find -ltermcap +collect2: ld returned 1 exit status +configure:12986: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char tgetent (); +| int +| main () +| { +| return tgetent (); +| ; +| return 0; +| } +configure:13017: result: no +configure:13027: checking for readline in -lreadline +configure:13062: arm-none-eabi-gcc -o conftest -g -O2 -DSQLITE_OS_UNIX=1 conftest.c -lreadline >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: cannot find -lreadline +collect2: ld returned 1 exit status +configure:13069: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char readline (); +| int +| main () +| { +| return readline (); +| ; +| return 0; +| } +configure:13090: result: no +configure:13123: checking readline.h usability +configure:13140: arm-none-eabi-gcc -c -g -O2 -DSQLITE_OS_UNIX=1 conftest.c >&5 +conftest.c:68:22: fatal error: readline.h: No such file or directory +compilation terminated. +configure:13147: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| #include +| #ifdef HAVE_SYS_TYPES_H +| # include +| #endif +| #ifdef HAVE_SYS_STAT_H +| # include +| #endif +| #ifdef STDC_HEADERS +| # include +| # include +| #else +| # ifdef HAVE_STDLIB_H +| # include +| # endif +| #endif +| #ifdef HAVE_STRING_H +| # if !defined STDC_HEADERS && defined HAVE_MEMORY_H +| # include +| # endif +| # include +| #endif +| #ifdef HAVE_STRINGS_H +| # include +| #endif +| #ifdef HAVE_INTTYPES_H +| # include +| #endif +| #ifdef HAVE_STDINT_H +| # include +| #endif +| #ifdef HAVE_UNISTD_H +| # include +| #endif +| #include +configure:13161: result: no +configure:13165: checking readline.h presence +configure:13180: arm-none-eabi-gcc -E conftest.c +conftest.c:35:22: fatal error: readline.h: No such file or directory +compilation terminated. +configure:13187: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| #include +configure:13201: result: no +configure:13229: checking for readline.h +configure:13236: result: no +configure:13306: checking for library containing fdatasync +configure:13347: arm-none-eabi-gcc -o conftest -g -O2 -DSQLITE_OS_UNIX=1 conftest.c >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: warning: cannot find entry symbol _start; defaulting to 00008018 +C:\cygwin\tmp\ccu5x1pj.o: In function `main': +E:\rt-thread\components\external\SQLite-3.8.1\make/conftest.c:46: undefined reference to `fdatasync' +collect2: ld returned 1 exit status +configure:13354: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char fdatasync (); +| int +| main () +| { +| return fdatasync (); +| ; +| return 0; +| } +configure:13347: arm-none-eabi-gcc -o conftest -g -O2 -DSQLITE_OS_UNIX=1 conftest.c -lrt >&5 +c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/bin/../lib/gcc/arm-none-eabi/4.6.3/../../../../arm-none-eabi/bin/ld.exe: cannot find -lrt +collect2: ld returned 1 exit status +configure:13354: $? = 1 +configure: failed program was: +| /* confdefs.h. */ +| #define PACKAGE_NAME "sqlite" +| #define PACKAGE_TARNAME "sqlite" +| #define PACKAGE_VERSION "3.8.1" +| #define PACKAGE_STRING "sqlite 3.8.1" +| #define PACKAGE_BUGREPORT "" +| #define STDC_HEADERS 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_SYS_STAT_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STRING_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_UNISTD_H 1 +| #define LT_OBJDIR ".libs/" +| #define HAVE_INT8_T 1 +| #define HAVE_INT16_T 1 +| #define HAVE_INT32_T 1 +| #define HAVE_INT64_T 1 +| #define HAVE_INTPTR_T 1 +| #define HAVE_UINT8_T 1 +| #define HAVE_UINT16_T 1 +| #define HAVE_UINT32_T 1 +| #define HAVE_UINT64_T 1 +| #define HAVE_UINTPTR_T 1 +| #define HAVE_SYS_TYPES_H 1 +| #define HAVE_STDLIB_H 1 +| #define HAVE_STDINT_H 1 +| #define HAVE_INTTYPES_H 1 +| #define HAVE_MALLOC_H 1 +| #define HAVE_LOCALTIME_R 1 +| #define HAVE_GMTIME_R 1 +| #define HAVE_MALLOC_USABLE_SIZE 1 +| /* end confdefs.h. */ +| +| /* Override any GCC internal prototype to avoid an error. +| Use char because int might match the return type of a GCC +| builtin and then its argument prototype would still apply. */ +| #ifdef __cplusplus +| extern "C" +| #endif +| char fdatasync (); +| int +| main () +| { +| return fdatasync (); +| ; +| return 0; +| } +configure:13385: result: no +configure:13707: creating ./config.status + +## ---------------------- ## +## Running config.status. ## +## ---------------------- ## + +This file was extended by sqlite config.status 3.8.1, which was +generated by GNU Autoconf 2.62. Invocation command line was + + CONFIG_FILES = + CONFIG_HEADERS = + CONFIG_LINKS = + CONFIG_COMMANDS = + $ ./config.status + +on geniuscode + +config.status:995: creating Makefile +config.status:995: creating sqlite3.pc +config.status:995: creating config.h +config.status:1222: executing libtool commands + +## ---------------- ## +## Cache variables. ## +## ---------------- ## + +ac_cv_build=i686-pc-cygwin +ac_cv_c_compiler_gnu=yes +ac_cv_c_tclconfig=/usr/lib +ac_cv_env_CC_set= +ac_cv_env_CC_value= +ac_cv_env_CFLAGS_set= +ac_cv_env_CFLAGS_value= +ac_cv_env_CPPFLAGS_set= +ac_cv_env_CPPFLAGS_value= +ac_cv_env_CPP_set= +ac_cv_env_CPP_value= +ac_cv_env_LDFLAGS_set= +ac_cv_env_LDFLAGS_value= +ac_cv_env_LIBS_set= +ac_cv_env_LIBS_value= +ac_cv_env_TCLLIBDIR_set= +ac_cv_env_TCLLIBDIR_value= +ac_cv_env_build_alias_set= +ac_cv_env_build_alias_value= +ac_cv_env_host_alias_set=set +ac_cv_env_host_alias_value=arm-none-eabi +ac_cv_env_target_alias_set= +ac_cv_env_target_alias_value= +ac_cv_func_fdatasync=no +ac_cv_func_gmtime_r=yes +ac_cv_func_localtime_r=yes +ac_cv_func_localtime_s=no +ac_cv_func_malloc_usable_size=yes +ac_cv_func_usleep=no +ac_cv_func_utime=no +ac_cv_header_dlfcn_h=no +ac_cv_header_inttypes_h=yes +ac_cv_header_malloc_h=yes +ac_cv_header_memory_h=no +ac_cv_header_readline_h=no +ac_cv_header_stdc=yes +ac_cv_header_stdint_h=yes +ac_cv_header_stdlib_h=yes +ac_cv_header_string_h=yes +ac_cv_header_strings_h=no +ac_cv_header_sys_stat_h=yes +ac_cv_header_sys_types_h=yes +ac_cv_header_unistd_h=yes +ac_cv_host=arm-none-eabi +ac_cv_lib_readline_readline=no +ac_cv_objext=o +ac_cv_path_EGREP='/usr/bin/grep -E' +ac_cv_path_FGREP='/usr/bin/grep -F' +ac_cv_path_GREP=/usr/bin/grep +ac_cv_path_SED=/usr/bin/sed +ac_cv_path_install='/usr/bin/install -c' +ac_cv_prog_AR=arm-none-eabi-ar +ac_cv_prog_AWK=gawk +ac_cv_prog_BUILD_CC=gcc +ac_cv_prog_CC=arm-none-eabi-gcc +ac_cv_prog_CPP='arm-none-eabi-gcc -E' +ac_cv_prog_OBJDUMP=arm-none-eabi-objdump +ac_cv_prog_RANLIB=arm-none-eabi-ranlib +ac_cv_prog_STRIP=arm-none-eabi-strip +ac_cv_prog_TCLSH_CMD=tclsh8.5 +ac_cv_prog_cc_c89= +ac_cv_prog_cc_g=yes +ac_cv_search_fdatasync=no +ac_cv_search_pthread_create=no +ac_cv_search_tgetent=no +ac_cv_sys_file_offset_bits=unknown +ac_cv_sys_large_files=unknown +ac_cv_sys_largefile_CC=no +ac_cv_type_int16_t=yes +ac_cv_type_int32_t=yes +ac_cv_type_int64_t=yes +ac_cv_type_int8_t=yes +ac_cv_type_intptr_t=yes +ac_cv_type_uint16_t=yes +ac_cv_type_uint32_t=yes +ac_cv_type_uint64_t=yes +ac_cv_type_uint8_t=yes +ac_cv_type_uintptr_t=yes +lt_cv_deplibs_check_method=unknown +lt_cv_file_magic_cmd='$MAGIC_CMD' +lt_cv_file_magic_test_file= +lt_cv_ld_reload_flag=-r +lt_cv_nm_interface='BSD nm' +lt_cv_objdir=.libs +lt_cv_path_LD='c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/arm-none-eabi/bin/ld.exe' +lt_cv_path_NM='/cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B' +lt_cv_prog_compiler_c_o=yes +lt_cv_prog_compiler_pic_works=yes +lt_cv_prog_compiler_rtti_exceptions=no +lt_cv_prog_compiler_static_works=yes +lt_cv_prog_gnu_ld=no +lt_cv_sys_global_symbol_pipe= +lt_cv_sys_global_symbol_to_c_name_address='sed -n -e '\''s/^: \([^ ]*\) $/ {\"\1\", (void *) 0},/p'\'' -e '\''s/^[BCDEGRST]* \([^ ]*\) \([^ ]*\)$/ {"\2", (void *) \&\2},/p'\''' +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='sed -n -e '\''s/^: \([^ ]*\) $/ {\"\1\", (void *) 0},/p'\'' -e '\''s/^[BCDEGRST]* \([^ ]*\) \(lib[^ ]*\)$/ {"\2", (void *) \&\2},/p'\'' -e '\''s/^[BCDEGRST]* \([^ ]*\) \([^ ]*\)$/ {"lib\2", (void *) \&\2},/p'\''' +lt_cv_sys_global_symbol_to_cdecl= +lt_cv_sys_max_cmd_len=8192 + +## ----------------- ## +## Output variables. ## +## ----------------- ## + +ALLOWRELEASE='' +AR='arm-none-eabi-ar' +AWK='gawk' +BUILD_CC='gcc' +BUILD_CFLAGS=' -g' +BUILD_EXEEXT='' +CC='arm-none-eabi-gcc' +CFLAGS=' -g -O2 -DSQLITE_OS_UNIX=1' +CPP='arm-none-eabi-gcc -E' +CPPFLAGS='' +DEFS='-DHAVE_CONFIG_H' +DSYMUTIL='' +DUMPBIN='' +ECHO_C='' +ECHO_N='-n' +ECHO_T='' +EGREP='/usr/bin/grep -E' +EXEEXT='' +FGREP='/usr/bin/grep -F' +GREP='/usr/bin/grep' +HAVE_TCL='1' +INSTALL_DATA='${INSTALL} -m 644' +INSTALL_PROGRAM='${INSTALL}' +INSTALL_SCRIPT='${INSTALL}' +LD='c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/arm-none-eabi/bin/ld.exe' +LDFLAGS='' +LIBOBJS='' +LIBS='' +LIBTOOL='$(SHELL) $(top_builddir)/libtool' +LIPO='' +LN_S='ln -s' +LTLIBOBJS='' +NM='/cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B' +NMEDIT='' +OBJDUMP='arm-none-eabi-objdump' +OBJEXT='o' +OPT_FEATURE_FLAGS='-DSQLITE_OMIT_LOAD_EXTENSION=1' +OTOOL64='' +OTOOL='' +PACKAGE_BUGREPORT='' +PACKAGE_NAME='sqlite' +PACKAGE_STRING='sqlite 3.8.1' +PACKAGE_TARNAME='sqlite' +PACKAGE_VERSION='3.8.1' +PATH_SEPARATOR=':' +RANLIB='arm-none-eabi-ranlib' +RELEASE='3.8.1' +SED='/usr/bin/sed' +SHELL='/bin/sh' +SQLITE_OS_UNIX='1' +SQLITE_OS_WIN='0' +SQLITE_THREADSAFE='1' +STRIP='arm-none-eabi-strip' +TARGET_DEBUG='-DNDEBUG' +TARGET_EXEEXT='' +TARGET_HAVE_READLINE='0' +TARGET_READLINE_INC='' +TARGET_READLINE_LIBS='' +TCLLIBDIR='/usr/lib/tcl8.5/sqlite3' +TCLSH_CMD='tclsh8.5' +TCL_BIN_DIR='/usr/lib' +TCL_INCLUDE_SPEC='-I/usr/include' +TCL_LIB_FILE='libtcl8.5.dll' +TCL_LIB_FLAG='-ltcl8.5' +TCL_LIB_SPEC='-L/usr/lib -ltcl8.5' +TCL_SRC_DIR='/usr/include/tcl8.5' +TCL_STUB_LIB_FILE='libtclstub8.5.a' +TCL_STUB_LIB_FLAG='-ltclstub8.5' +TCL_STUB_LIB_SPEC='-Wl,-ltclstub8.5' +TCL_VERSION='8.5' +TEMP_STORE='1' +USE_AMALGAMATION='1' +USE_GCOV='0' +VERSION='3.8' +VERSION_NUMBER='3008001' +XTHREADCONNECT='' +ac_ct_CC='' +ac_ct_DUMPBIN='' +bindir='${exec_prefix}/bin' +build='i686-pc-cygwin' +build_alias='' +build_cpu='i686' +build_os='cygwin' +build_vendor='pc' +datadir='${datarootdir}' +datarootdir='${prefix}/share' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +dvidir='${docdir}' +exec_prefix='${prefix}' +host='arm-none-eabi' +host_alias='arm-none-eabi' +host_cpu='arm' +host_os='eabi' +host_vendor='none' +htmldir='${docdir}' +includedir='${prefix}/include' +infodir='${datarootdir}/info' +libdir='${exec_prefix}/lib' +libexecdir='${exec_prefix}/libexec' +localedir='${datarootdir}/locale' +localstatedir='${prefix}/var' +lt_ECHO='echo' +mandir='${datarootdir}/man' +oldincludedir='/usr/include' +pdfdir='${docdir}' +prefix='/usr/local' +program_prefix='' +program_transform_name='s,x,x,' +psdir='${docdir}' +sbindir='${exec_prefix}/sbin' +sharedstatedir='${prefix}/com' +sysconfdir='${prefix}/etc' +target_alias='' + +## ----------- ## +## confdefs.h. ## +## ----------- ## + +#define PACKAGE_NAME "sqlite" +#define PACKAGE_TARNAME "sqlite" +#define PACKAGE_VERSION "3.8.1" +#define PACKAGE_STRING "sqlite 3.8.1" +#define PACKAGE_BUGREPORT "" +#define STDC_HEADERS 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRING_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_UNISTD_H 1 +#define LT_OBJDIR ".libs/" +#define HAVE_INT8_T 1 +#define HAVE_INT16_T 1 +#define HAVE_INT32_T 1 +#define HAVE_INT64_T 1 +#define HAVE_INTPTR_T 1 +#define HAVE_UINT8_T 1 +#define HAVE_UINT16_T 1 +#define HAVE_UINT32_T 1 +#define HAVE_UINT64_T 1 +#define HAVE_UINTPTR_T 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_LOCALTIME_R 1 +#define HAVE_GMTIME_R 1 +#define HAVE_MALLOC_USABLE_SIZE 1 + +configure: exit 0 diff --git a/components/external/SQLite-3.8.1/make/config.status b/components/external/SQLite-3.8.1/make/config.status new file mode 100644 index 0000000000000000000000000000000000000000..b208fd861b49925d2a526833b8892ba0e306dffd --- /dev/null +++ b/components/external/SQLite-3.8.1/make/config.status @@ -0,0 +1,1869 @@ +#! /bin/sh +# Generated by configure. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false +SHELL=${CONFIG_SHELL-/bin/sh} +## --------------------- ## +## M4sh Initialization. ## +## --------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + + + +# PATH needs CR +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + +# Support unset when possible. +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + as_unset=unset +else + as_unset=false +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + { (exit 1); exit 1; } +fi + +# Work around bugs in pre-3.0 UWIN ksh. +for as_var in ENV MAIL MAILPATH +do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# Required to use basename. +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + + +# Name of the executable. +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# CDPATH. +$as_unset CDPATH + + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { + + # Create $as_me.lineno as a copy of $as_myself, but with $LINENO + # uniformly replaced by the line number. The first 'sed' inserts a + # line-number line after each line using $LINENO; the second 'sed' + # does the real work. The second script uses 'N' to pair each + # line-number line with the line containing $LINENO, and appends + # trailing '-' during substitution so that $LINENO is not a special + # case at line end. + # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the + # scripts with optimization help from Paolo Bonzini. Blame Lee + # E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { (exit 1); exit 1; }; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in +-n*) + case `echo 'x\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + *) ECHO_C='\c';; + esac;; +*) + ECHO_N='-n';; +esac +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -p' + fi +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p=: +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 + +# Save the log message, to keep $[0] and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by sqlite $as_me 3.8.1, which was +generated by GNU Autoconf 2.62. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +# Files that config.status was made for. +config_files=" Makefile sqlite3.pc" +config_headers=" config.h" +config_commands=" libtool" + +ac_cs_usage="\ +\`$as_me' instantiates files from templates according to the +current configuration. + +Usage: $0 [OPTIONS] [FILE]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + -q, --quiet do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Configuration commands: +$config_commands + +Report bugs to ." + +ac_cs_version="\ +sqlite config.status 3.8.1 +configured by ../configure, generated by GNU Autoconf 2.62, + with options \"'--host=arm-none-eabi' 'host_alias=arm-none-eabi'\" + +Copyright (C) 2008 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='/cygdrive/e/rt-thread/components/external/SQLite-3.8.1/make' +srcdir='..' +INSTALL='/usr/bin/install -c' +AWK='gawk' +test -n "$AWK" || AWK=awk +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + CONFIG_FILES="$CONFIG_FILES '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + CONFIG_HEADERS="$CONFIG_HEADERS '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + { $as_echo "$as_me: error: ambiguous option: $1 +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; };; + --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) { $as_echo "$as_me: error: unrecognized option: $1 +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; } ;; + + *) ac_config_targets="$ac_config_targets $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +if $ac_cs_recheck; then + set X '/bin/sh' '../configure' '--host=arm-none-eabi' 'host_alias=arm-none-eabi' $ac_configure_extra_args --no-create --no-recursion + shift + $as_echo "running CONFIG_SHELL=/bin/sh $*" >&6 + CONFIG_SHELL='/bin/sh' + export CONFIG_SHELL + exec "$@" +fi + +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +# +# INIT-COMMANDS +# + + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +sed_quote_subst='s/\(["`$\\]\)/\\\1/g' +double_quote_subst='s/\(["`\\]\)/\\\1/g' +delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' +macro_version='2.2.6' +macro_revision='1.3012' +enable_shared='no' +enable_static='yes' +pic_mode='default' +enable_fast_install='yes' +host_alias='arm-none-eabi' +host='arm-none-eabi' +host_os='eabi' +build_alias='' +build='i686-pc-cygwin' +build_os='cygwin' +SED='/usr/bin/sed' +Xsed='/usr/bin/sed -e 1s/^X//' +GREP='/usr/bin/grep' +EGREP='/usr/bin/grep -E' +FGREP='/usr/bin/grep -F' +LD='c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/arm-none-eabi/bin/ld.exe' +NM='/cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B' +LN_S='ln -s' +max_cmd_len='8192' +ac_objext='o' +exeext='' +lt_unset='unset' +lt_SP2NL='tr \040 \012' +lt_NL2SP='tr \015\012 \040\040' +reload_flag=' -r' +reload_cmds='$LD$reload_flag -o $output$reload_objs' +OBJDUMP='arm-none-eabi-objdump' +deplibs_check_method='unknown' +file_magic_cmd='$MAGIC_CMD' +AR='arm-none-eabi-ar' +AR_FLAGS='cru' +STRIP='arm-none-eabi-strip' +RANLIB='arm-none-eabi-ranlib' +old_postinstall_cmds='chmod 644 $oldlib~$RANLIB $oldlib' +old_postuninstall_cmds='' +old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs~$RANLIB $oldlib' +CC='arm-none-eabi-gcc' +CFLAGS=' -g -O2 -DSQLITE_OS_UNIX=1' +compiler='arm-none-eabi-gcc' +GCC='yes' +lt_cv_sys_global_symbol_pipe='' +lt_cv_sys_global_symbol_to_cdecl='' +lt_cv_sys_global_symbol_to_c_name_address='sed -n -e '\''s/^: \([^ ]*\) $/ {\"\1\", (void *) 0},/p'\'' -e '\''s/^[BCDEGRST]* \([^ ]*\) \([^ ]*\)$/ {"\2", (void *) \&\2},/p'\''' +lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='sed -n -e '\''s/^: \([^ ]*\) $/ {\"\1\", (void *) 0},/p'\'' -e '\''s/^[BCDEGRST]* \([^ ]*\) \(lib[^ ]*\)$/ {"\2", (void *) \&\2},/p'\'' -e '\''s/^[BCDEGRST]* \([^ ]*\) \([^ ]*\)$/ {"lib\2", (void *) \&\2},/p'\''' +objdir='.libs' +SHELL='/bin/sh' +ECHO='echo' +MAGIC_CMD='file' +lt_prog_compiler_no_builtin_flag=' -fno-builtin' +lt_prog_compiler_wl='-Wl,' +lt_prog_compiler_pic=' -fPIC -DPIC' +lt_prog_compiler_static='-static' +lt_cv_prog_compiler_c_o='yes' +need_locks='no' +DSYMUTIL='' +NMEDIT='' +LIPO='' +OTOOL='' +OTOOL64='' +libext='a' +shrext_cmds='.so' +extract_expsyms_cmds='' +archive_cmds_need_lc='yes' +enable_shared_with_static_runtimes='no' +export_dynamic_flag_spec='' +whole_archive_flag_spec='' +compiler_needs_object='no' +old_archive_from_new_cmds='' +old_archive_from_expsyms_cmds='' +archive_cmds='' +archive_expsym_cmds='' +module_cmds='' +module_expsym_cmds='' +with_gnu_ld='no' +allow_undefined_flag='' +no_undefined_flag='' +hardcode_libdir_flag_spec='' +hardcode_libdir_flag_spec_ld='' +hardcode_libdir_separator='' +hardcode_direct='no' +hardcode_direct_absolute='no' +hardcode_minus_L='no' +hardcode_shlibpath_var='unsupported' +hardcode_automatic='no' +inherit_rpath='no' +link_all_deplibs='unknown' +fix_srcfile_path='' +always_export_symbols='no' +export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' +exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' +include_expsyms='' +prelink_cmds='' +file_list_spec='' +variables_saved_for_relink='PATH GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH' +need_lib_prefix='unknown' +need_version='unknown' +version_type='none' +runpath_var='' +shlibpath_var='' +shlibpath_overrides_runpath='unknown' +libname_spec='lib$name' +library_names_spec='' +soname_spec='' +postinstall_cmds='' +postuninstall_cmds='' +finish_cmds='' +finish_eval='' +hardcode_into_libs='no' +sys_lib_search_path_spec='' +sys_lib_dlsearch_path_spec='/lib /usr/lib' +hardcode_action='unsupported' +enable_dlopen='unknown' +enable_dlopen_self='unknown' +enable_dlopen_self_static='unknown' +old_striplib='arm-none-eabi-strip --strip-debug' +striplib='arm-none-eabi-strip --strip-unneeded' + +LTCC='arm-none-eabi-gcc' +LTCFLAGS='-g -O2' +compiler='arm-none-eabi-gcc' + +# Quote evaled strings. +for var in SED GREP EGREP FGREP LD NM LN_S lt_SP2NL lt_NL2SP reload_flag OBJDUMP deplibs_check_method file_magic_cmd AR AR_FLAGS STRIP RANLIB CC CFLAGS compiler lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl lt_cv_sys_global_symbol_to_c_name_address lt_cv_sys_global_symbol_to_c_name_address_lib_prefix SHELL ECHO lt_prog_compiler_no_builtin_flag lt_prog_compiler_wl lt_prog_compiler_pic lt_prog_compiler_static lt_cv_prog_compiler_c_o need_locks DSYMUTIL NMEDIT LIPO OTOOL OTOOL64 shrext_cmds export_dynamic_flag_spec whole_archive_flag_spec compiler_needs_object with_gnu_ld allow_undefined_flag no_undefined_flag hardcode_libdir_flag_spec hardcode_libdir_flag_spec_ld hardcode_libdir_separator fix_srcfile_path exclude_expsyms include_expsyms file_list_spec variables_saved_for_relink libname_spec library_names_spec soname_spec finish_eval old_striplib striplib; do + case `eval \\$ECHO "X\\$$var"` in + *[\\\`\"\$]*) + eval "lt_$var=\\\"\`\$ECHO \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\$$var\\\"" + ;; + esac +done + +# Double-quote double-evaled strings. +for var in reload_cmds old_postinstall_cmds old_postuninstall_cmds old_archive_cmds extract_expsyms_cmds old_archive_from_new_cmds old_archive_from_expsyms_cmds archive_cmds archive_expsym_cmds module_cmds module_expsym_cmds export_symbols_cmds prelink_cmds postinstall_cmds postuninstall_cmds finish_cmds sys_lib_search_path_spec sys_lib_dlsearch_path_spec; do + case `eval \\$ECHO "X\\$$var"` in + *[\\\`\"\$]*) + eval "lt_$var=\\\"\`\$ECHO \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\"" + ;; + *) + eval "lt_$var=\\\"\$$var\\\"" + ;; + esac +done + +# Fix-up fallback echo if it was mangled by the above quoting rules. +case $lt_ECHO in +*'\$0 --fallback-echo"') lt_ECHO=`$ECHO "X$lt_ECHO" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'` + ;; +esac + +ac_aux_dir='..' +xsi_shell='yes' +lt_shell_append='yes' + +# See if we are running on zsh, and set the options which allow our +# commands through without removal of \ escapes INIT. +if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST +fi + + + PACKAGE='' + VERSION='3.8' + TIMESTAMP='' + RM='rm -f' + ofile='libtool' + + + + + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; + "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "sqlite3.pc") CONFIG_FILES="$CONFIG_FILES sqlite3.pc" ;; + + *) { { $as_echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 +$as_echo "$as_me: error: invalid argument: $ac_config_target" >&2;} + { (exit 1); exit 1; }; };; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers + test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= + trap 'exit_status=$? + { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status +' 0 + trap '{ (exit 1); exit 1; }' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -n "$tmp" && test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || +{ + $as_echo "$as_me: cannot create a temporary directory in ." >&2 + { (exit 1); exit 1; } +} + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=' ' +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$tmp/subs1.awk" && +cat >>"$tmp/subs1.awk" <<\_ACAWK && +S["SHELL"]="/bin/sh" +S["PATH_SEPARATOR"]=":" +S["PACKAGE_NAME"]="sqlite" +S["PACKAGE_TARNAME"]="sqlite" +S["PACKAGE_VERSION"]="3.8.1" +S["PACKAGE_STRING"]="sqlite 3.8.1" +S["PACKAGE_BUGREPORT"]="" +S["exec_prefix"]="${prefix}" +S["prefix"]="/usr/local" +S["program_transform_name"]="s,x,x," +S["bindir"]="${exec_prefix}/bin" +S["sbindir"]="${exec_prefix}/sbin" +S["libexecdir"]="${exec_prefix}/libexec" +S["datarootdir"]="${prefix}/share" +S["datadir"]="${datarootdir}" +S["sysconfdir"]="${prefix}/etc" +S["sharedstatedir"]="${prefix}/com" +S["localstatedir"]="${prefix}/var" +S["includedir"]="${prefix}/include" +S["oldincludedir"]="/usr/include" +S["docdir"]="${datarootdir}/doc/${PACKAGE_TARNAME}" +S["infodir"]="${datarootdir}/info" +S["htmldir"]="${docdir}" +S["dvidir"]="${docdir}" +S["pdfdir"]="${docdir}" +S["psdir"]="${docdir}" +S["libdir"]="${exec_prefix}/lib" +S["localedir"]="${datarootdir}/locale" +S["mandir"]="${datarootdir}/man" +S["DEFS"]="-DHAVE_CONFIG_H" +S["ECHO_C"]="" +S["ECHO_N"]="-n" +S["ECHO_T"]="" +S["LIBS"]="" +S["build_alias"]="" +S["host_alias"]="arm-none-eabi" +S["target_alias"]="" +S["LIBTOOL"]="$(SHELL) $(top_builddir)/libtool" +S["build"]="i686-pc-cygwin" +S["build_cpu"]="i686" +S["build_vendor"]="pc" +S["build_os"]="cygwin" +S["host"]="arm-none-eabi" +S["host_cpu"]="arm" +S["host_vendor"]="none" +S["host_os"]="eabi" +S["CC"]="arm-none-eabi-gcc" +S["CFLAGS"]=" -g -O2 -DSQLITE_OS_UNIX=1" +S["LDFLAGS"]="" +S["CPPFLAGS"]="" +S["ac_ct_CC"]="" +S["EXEEXT"]="" +S["OBJEXT"]="o" +S["SED"]="/usr/bin/sed" +S["GREP"]="/usr/bin/grep" +S["EGREP"]="/usr/bin/grep -E" +S["FGREP"]="/usr/bin/grep -F" +S["LD"]="c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/arm-none-eabi/bin/ld.exe" +S["DUMPBIN"]="" +S["ac_ct_DUMPBIN"]="" +S["NM"]="/cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B" +S["LN_S"]="ln -s" +S["OBJDUMP"]="arm-none-eabi-objdump" +S["AR"]="arm-none-eabi-ar" +S["STRIP"]="arm-none-eabi-strip" +S["RANLIB"]="arm-none-eabi-ranlib" +S["lt_ECHO"]="echo" +S["DSYMUTIL"]="" +S["NMEDIT"]="" +S["LIPO"]="" +S["OTOOL"]="" +S["OTOOL64"]="" +S["CPP"]="arm-none-eabi-gcc -E" +S["INSTALL_PROGRAM"]="${INSTALL}" +S["INSTALL_SCRIPT"]="${INSTALL}" +S["INSTALL_DATA"]="${INSTALL} -m 644" +S["AWK"]="gawk" +S["TCLSH_CMD"]="tclsh8.5" +S["TCLLIBDIR"]="/usr/lib/tcl8.5/sqlite3" +S["program_prefix"]="" +S["VERSION"]="3.8" +S["RELEASE"]="3.8.1" +S["VERSION_NUMBER"]="3008001" +S["BUILD_CC"]="gcc" +S["SQLITE_THREADSAFE"]="1" +S["XTHREADCONNECT"]="" +S["ALLOWRELEASE"]="" +S["TEMP_STORE"]="1" +S["BUILD_EXEEXT"]="" +S["SQLITE_OS_UNIX"]="1" +S["SQLITE_OS_WIN"]="0" +S["TARGET_EXEEXT"]="" +S["TCL_VERSION"]="8.5" +S["TCL_BIN_DIR"]="/usr/lib" +S["TCL_SRC_DIR"]="/usr/include/tcl8.5" +S["TCL_INCLUDE_SPEC"]="-I/usr/include" +S["TCL_LIB_FILE"]="libtcl8.5.dll" +S["TCL_LIB_FLAG"]="-ltcl8.5" +S["TCL_LIB_SPEC"]="-L/usr/lib -ltcl8.5" +S["TCL_STUB_LIB_FILE"]="libtclstub8.5.a" +S["TCL_STUB_LIB_FLAG"]="-ltclstub8.5" +S["TCL_STUB_LIB_SPEC"]="-Wl,-ltclstub8.5" +S["HAVE_TCL"]="1" +S["TARGET_READLINE_LIBS"]="" +S["TARGET_READLINE_INC"]="" +S["TARGET_HAVE_READLINE"]="0" +S["TARGET_DEBUG"]="-DNDEBUG" +S["USE_AMALGAMATION"]="1" +S["OPT_FEATURE_FLAGS"]="-DSQLITE_OMIT_LOAD_EXTENSION=1" +S["USE_GCOV"]="0" +S["BUILD_CFLAGS"]=" -g" +S["LIBOBJS"]="" +S["LTLIBOBJS"]="" +_ACAWK +cat >>"$tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ + || { { $as_echo "$as_me:$LINENO: error: could not setup config files machinery" >&5 +$as_echo "$as_me: error: could not setup config files machinery" >&2;} + { (exit 1); exit 1; }; } +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$tmp/defines.awk" <<\_ACAWK || +BEGIN { +D["PACKAGE_NAME"]=" \"sqlite\"" +D["PACKAGE_TARNAME"]=" \"sqlite\"" +D["PACKAGE_VERSION"]=" \"3.8.1\"" +D["PACKAGE_STRING"]=" \"sqlite 3.8.1\"" +D["PACKAGE_BUGREPORT"]=" \"\"" +D["STDC_HEADERS"]=" 1" +D["HAVE_SYS_TYPES_H"]=" 1" +D["HAVE_SYS_STAT_H"]=" 1" +D["HAVE_STDLIB_H"]=" 1" +D["HAVE_STRING_H"]=" 1" +D["HAVE_INTTYPES_H"]=" 1" +D["HAVE_STDINT_H"]=" 1" +D["HAVE_UNISTD_H"]=" 1" +D["LT_OBJDIR"]=" \".libs/\"" +D["HAVE_INT8_T"]=" 1" +D["HAVE_INT16_T"]=" 1" +D["HAVE_INT32_T"]=" 1" +D["HAVE_INT64_T"]=" 1" +D["HAVE_INTPTR_T"]=" 1" +D["HAVE_UINT8_T"]=" 1" +D["HAVE_UINT16_T"]=" 1" +D["HAVE_UINT32_T"]=" 1" +D["HAVE_UINT64_T"]=" 1" +D["HAVE_UINTPTR_T"]=" 1" +D["HAVE_SYS_TYPES_H"]=" 1" +D["HAVE_STDLIB_H"]=" 1" +D["HAVE_STDINT_H"]=" 1" +D["HAVE_INTTYPES_H"]=" 1" +D["HAVE_MALLOC_H"]=" 1" +D["HAVE_LOCALTIME_R"]=" 1" +D["HAVE_GMTIME_R"]=" 1" +D["HAVE_MALLOC_USABLE_SIZE"]=" 1" + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+[_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*([\t (]|$)/ { + line = $ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + prefix = substr(line, 1, index(line, defundef) - 1) + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", line, "*/" + next + } + } +} +{ print } +_ACAWK + { { $as_echo "$as_me:$LINENO: error: could not setup config headers machinery" >&5 +$as_echo "$as_me: error: could not setup config headers machinery" >&2;} + { (exit 1); exit 1; }; } +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) { { $as_echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5 +$as_echo "$as_me: error: Invalid tag $ac_tag." >&2;} + { (exit 1); exit 1; }; };; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + { { $as_echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 +$as_echo "$as_me: error: cannot find input file: $ac_f" >&2;} + { (exit 1); exit 1; }; };; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + ac_file_inputs="$ac_file_inputs '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:$LINENO: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$tmp/stdin" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + { as_dir="$ac_dir" + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || { { $as_echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 +$as_echo "$as_me: error: cannot create directory $as_dir" >&2;} + { (exit 1); exit 1; }; }; } + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + + case $INSTALL in + [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; + *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; + esac +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= + +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p +' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} + ac_datarootdir_hack=' + s&@datadir@&${datarootdir}&g + s&@docdir@&${datarootdir}/doc/${PACKAGE_TARNAME}&g + s&@infodir@&${datarootdir}/info&g + s&@localedir@&${datarootdir}/locale&g + s&@mandir@&${datarootdir}/man&g + s&\${datarootdir}&${prefix}/share&g' ;; +esac +ac_sed_extra=" + +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +s&@INSTALL@&$ac_INSTALL&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&2;} + + rm -f "$tmp/stdin" + case $ac_file in + -) cat "$tmp/out" && rm -f "$tmp/out";; + *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; + esac \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" + } >"$tmp/config.h" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:$LINENO: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$tmp/config.h" "$ac_file" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + fi + else + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ + || { { $as_echo "$as_me:$LINENO: error: could not create -" >&5 +$as_echo "$as_me: error: could not create -" >&2;} + { (exit 1); exit 1; }; } + fi + ;; + + :C) { $as_echo "$as_me:$LINENO: executing $ac_file commands" >&5 +$as_echo "$as_me: executing $ac_file commands" >&6;} + ;; + esac + + + case $ac_file$ac_mode in + "libtool":C) + + # See if we are running on zsh, and set the options which allow our + # commands through without removal of \ escapes. + if test -n "${ZSH_VERSION+set}" ; then + setopt NO_GLOB_SUBST + fi + + cfgfile="${ofile}T" + trap "$RM \"$cfgfile\"; exit 1" 1 2 15 + $RM "$cfgfile" + + cat <<_LT_EOF >> "$cfgfile" +#! $SHELL + +# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. +# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION +# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: +# NOTE: Changes made to this file will be lost: look at ltmain.sh. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, +# 2006, 2007, 2008 Free Software Foundation, Inc. +# Written by Gordon Matzigkeit, 1996 +# +# This file is part of GNU Libtool. +# +# GNU Libtool is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of +# the License, or (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Libtool; see the file COPYING. If not, a copy +# can be downloaded from http://www.gnu.org/licenses/gpl.html, or +# obtained by writing to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + +# The names of the tagged configurations supported by this script. +available_tags="" + +# ### BEGIN LIBTOOL CONFIG + +# Which release of libtool.m4 was used? +macro_version=$macro_version +macro_revision=$macro_revision + +# Whether or not to build shared libraries. +build_libtool_libs=$enable_shared + +# Whether or not to build static libraries. +build_old_libs=$enable_static + +# What type of objects to build. +pic_mode=$pic_mode + +# Whether or not to optimize for fast installation. +fast_install=$enable_fast_install + +# The host system. +host_alias=$host_alias +host=$host +host_os=$host_os + +# The build system. +build_alias=$build_alias +build=$build +build_os=$build_os + +# A sed program that does not truncate output. +SED=$lt_SED + +# Sed that helps us avoid accidentally triggering echo(1) options like -n. +Xsed="\$SED -e 1s/^X//" + +# A grep program that handles long lines. +GREP=$lt_GREP + +# An ERE matcher. +EGREP=$lt_EGREP + +# A literal string matcher. +FGREP=$lt_FGREP + +# A BSD- or MS-compatible name lister. +NM=$lt_NM + +# Whether we need soft or hard links. +LN_S=$lt_LN_S + +# What is the maximum length of a command? +max_cmd_len=$max_cmd_len + +# Object file suffix (normally "o"). +objext=$ac_objext + +# Executable file suffix (normally ""). +exeext=$exeext + +# whether the shell understands "unset". +lt_unset=$lt_unset + +# turn spaces into newlines. +SP2NL=$lt_lt_SP2NL + +# turn newlines into spaces. +NL2SP=$lt_lt_NL2SP + +# How to create reloadable object files. +reload_flag=$lt_reload_flag +reload_cmds=$lt_reload_cmds + +# An object symbol dumper. +OBJDUMP=$lt_OBJDUMP + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method=$lt_deplibs_check_method + +# Command to use when deplibs_check_method == "file_magic". +file_magic_cmd=$lt_file_magic_cmd + +# The archiver. +AR=$lt_AR +AR_FLAGS=$lt_AR_FLAGS + +# A symbol stripping program. +STRIP=$lt_STRIP + +# Commands used to install an old-style archive. +RANLIB=$lt_RANLIB +old_postinstall_cmds=$lt_old_postinstall_cmds +old_postuninstall_cmds=$lt_old_postuninstall_cmds + +# A C compiler. +LTCC=$lt_CC + +# LTCC compiler flags. +LTCFLAGS=$lt_CFLAGS + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe + +# Transform the output of nm in a proper C declaration. +global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl + +# Transform the output of nm in a C name address pair. +global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address + +# Transform the output of nm in a C name address pair when lib prefix is needed. +global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix + +# The name of the directory that contains temporary libtool files. +objdir=$objdir + +# Shell to use when invoking shell scripts. +SHELL=$lt_SHELL + +# An echo program that does not interpret backslashes. +ECHO=$lt_ECHO + +# Used to examine libraries when file_magic_cmd begins with "file". +MAGIC_CMD=$MAGIC_CMD + +# Must we lock files when doing compilation? +need_locks=$lt_need_locks + +# Tool to manipulate archived DWARF debug symbol files on Mac OS X. +DSYMUTIL=$lt_DSYMUTIL + +# Tool to change global to local symbols on Mac OS X. +NMEDIT=$lt_NMEDIT + +# Tool to manipulate fat objects and archives on Mac OS X. +LIPO=$lt_LIPO + +# ldd/readelf like tool for Mach-O binaries on Mac OS X. +OTOOL=$lt_OTOOL + +# ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. +OTOOL64=$lt_OTOOL64 + +# Old archive suffix (normally "a"). +libext=$libext + +# Shared library suffix (normally ".so"). +shrext_cmds=$lt_shrext_cmds + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds=$lt_extract_expsyms_cmds + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at link time. +variables_saved_for_relink=$lt_variables_saved_for_relink + +# Do we need the "lib" prefix for modules? +need_lib_prefix=$need_lib_prefix + +# Do we need a version for libraries? +need_version=$need_version + +# Library versioning type. +version_type=$version_type + +# Shared library runtime path variable. +runpath_var=$runpath_var + +# Shared library path variable. +shlibpath_var=$shlibpath_var + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=$shlibpath_overrides_runpath + +# Format of library name prefix. +libname_spec=$lt_libname_spec + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME +library_names_spec=$lt_library_names_spec + +# The coded name of the library, if different from the real name. +soname_spec=$lt_soname_spec + +# Command to use after installation of a shared archive. +postinstall_cmds=$lt_postinstall_cmds + +# Command to use after uninstallation of a shared archive. +postuninstall_cmds=$lt_postuninstall_cmds + +# Commands used to finish a libtool library installation in a directory. +finish_cmds=$lt_finish_cmds + +# As "finish_cmds", except a single script fragment to be evaled but +# not shown. +finish_eval=$lt_finish_eval + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=$hardcode_into_libs + +# Compile-time system search path for libraries. +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec + +# Run-time system search path for libraries. +sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec + +# Whether dlopen is supported. +dlopen_support=$enable_dlopen + +# Whether dlopen of programs is supported. +dlopen_self=$enable_dlopen_self + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=$enable_dlopen_self_static + +# Commands to strip libraries. +old_striplib=$lt_old_striplib +striplib=$lt_striplib + + +# The linker used to build libraries. +LD=$lt_LD + +# Commands used to build an old-style archive. +old_archive_cmds=$lt_old_archive_cmds + +# A language specific compiler. +CC=$lt_compiler + +# Is the compiler the GNU compiler? +with_gcc=$GCC + +# Compiler flag to turn off builtin functions. +no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag + +# How to pass a linker flag through the compiler. +wl=$lt_lt_prog_compiler_wl + +# Additional compiler flags for building library objects. +pic_flag=$lt_lt_prog_compiler_pic + +# Compiler flag to prevent dynamic linking. +link_static_flag=$lt_lt_prog_compiler_static + +# Does compiler simultaneously support -c and -o options? +compiler_c_o=$lt_lt_cv_prog_compiler_c_o + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=$archive_cmds_need_lc + +# Whether or not to disallow shared libs when runtime libs are static. +allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec=$lt_export_dynamic_flag_spec + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec=$lt_whole_archive_flag_spec + +# Whether the compiler copes with passing no objects directly. +compiler_needs_object=$lt_compiler_needs_object + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds=$lt_old_archive_from_new_cmds + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds + +# Commands used to build a shared archive. +archive_cmds=$lt_archive_cmds +archive_expsym_cmds=$lt_archive_expsym_cmds + +# Commands used to build a loadable module if different from building +# a shared archive. +module_cmds=$lt_module_cmds +module_expsym_cmds=$lt_module_expsym_cmds + +# Whether we are building with GNU ld or not. +with_gnu_ld=$lt_with_gnu_ld + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag=$lt_allow_undefined_flag + +# Flag that enforces no undefined symbols. +no_undefined_flag=$lt_no_undefined_flag + +# Flag to hardcode \$libdir into a binary during linking. +# This must work even if \$libdir does not exist +hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec + +# If ld is used when linking, flag to hardcode \$libdir into a binary +# during linking. This must work even if \$libdir does not exist. +hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld + +# Whether we need a single "-rpath" flag with a separated argument. +hardcode_libdir_separator=$lt_hardcode_libdir_separator + +# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes +# DIR into the resulting binary. +hardcode_direct=$hardcode_direct + +# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes +# DIR into the resulting binary and the resulting library dependency is +# "absolute",i.e impossible to change by setting \${shlibpath_var} if the +# library is relocated. +hardcode_direct_absolute=$hardcode_direct_absolute + +# Set to "yes" if using the -LDIR flag during linking hardcodes DIR +# into the resulting binary. +hardcode_minus_L=$hardcode_minus_L + +# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR +# into the resulting binary. +hardcode_shlibpath_var=$hardcode_shlibpath_var + +# Set to "yes" if building a shared library automatically hardcodes DIR +# into the library and all subsequent libraries and executables linked +# against it. +hardcode_automatic=$hardcode_automatic + +# Set to yes if linker adds runtime paths of dependent libraries +# to runtime path list. +inherit_rpath=$inherit_rpath + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=$link_all_deplibs + +# Fix the shell variable \$srcfile for the compiler. +fix_srcfile_path=$lt_fix_srcfile_path + +# Set to "yes" if exported symbols are required. +always_export_symbols=$always_export_symbols + +# The commands to list exported symbols. +export_symbols_cmds=$lt_export_symbols_cmds + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms=$lt_exclude_expsyms + +# Symbols that must always be exported. +include_expsyms=$lt_include_expsyms + +# Commands necessary for linking programs (against libraries) with templates. +prelink_cmds=$lt_prelink_cmds + +# Specify filename containing input files. +file_list_spec=$lt_file_list_spec + +# How to hardcode a shared library path into an executable. +hardcode_action=$hardcode_action + +# ### END LIBTOOL CONFIG + +_LT_EOF + + case $host_os in + aix3*) + cat <<\_LT_EOF >> "$cfgfile" +# AIX sometimes has problems with the GCC collect2 program. For some +# reason, if we set the COLLECT_NAMES environment variable, the problems +# vanish in a puff of smoke. +if test "X${COLLECT_NAMES+set}" != Xset; then + COLLECT_NAMES= + export COLLECT_NAMES +fi +_LT_EOF + ;; + esac + + +ltmain="$ac_aux_dir/ltmain.sh" + + + # We use sed instead of cat because bash on DJGPP gets confused if + # if finds mixed CR/LF and LF-only lines. Since sed operates in + # text mode, it properly converts lines to CR/LF. This bash problem + # is reportedly fixed, but why not run on old versions too? + sed '/^# Generated shell functions inserted here/q' "$ltmain" >> "$cfgfile" \ + || (rm -f "$cfgfile"; exit 1) + + case $xsi_shell in + yes) + cat << \_LT_EOF >> "$cfgfile" + +# func_dirname file append nondir_replacement +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +func_dirname () +{ + case ${1} in + */*) func_dirname_result="${1%/*}${2}" ;; + * ) func_dirname_result="${3}" ;; + esac +} + +# func_basename file +func_basename () +{ + func_basename_result="${1##*/}" +} + +# func_dirname_and_basename file append nondir_replacement +# perform func_basename and func_dirname in a single function +# call: +# dirname: Compute the dirname of FILE. If nonempty, +# add APPEND to the result, otherwise set result +# to NONDIR_REPLACEMENT. +# value returned in "$func_dirname_result" +# basename: Compute filename of FILE. +# value retuned in "$func_basename_result" +# Implementation must be kept synchronized with func_dirname +# and func_basename. For efficiency, we do not delegate to +# those functions but instead duplicate the functionality here. +func_dirname_and_basename () +{ + case ${1} in + */*) func_dirname_result="${1%/*}${2}" ;; + * ) func_dirname_result="${3}" ;; + esac + func_basename_result="${1##*/}" +} + +# func_stripname prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +func_stripname () +{ + # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are + # positional parameters, so assign one to ordinary parameter first. + func_stripname_result=${3} + func_stripname_result=${func_stripname_result#"${1}"} + func_stripname_result=${func_stripname_result%"${2}"} +} + +# func_opt_split +func_opt_split () +{ + func_opt_split_opt=${1%%=*} + func_opt_split_arg=${1#*=} +} + +# func_lo2o object +func_lo2o () +{ + case ${1} in + *.lo) func_lo2o_result=${1%.lo}.${objext} ;; + *) func_lo2o_result=${1} ;; + esac +} + +# func_xform libobj-or-source +func_xform () +{ + func_xform_result=${1%.*}.lo +} + +# func_arith arithmetic-term... +func_arith () +{ + func_arith_result=$(( $* )) +} + +# func_len string +# STRING may not start with a hyphen. +func_len () +{ + func_len_result=${#1} +} + +_LT_EOF + ;; + *) # Bourne compatible functions. + cat << \_LT_EOF >> "$cfgfile" + +# func_dirname file append nondir_replacement +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +func_dirname () +{ + # Extract subdirectory from the argument. + func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` + if test "X$func_dirname_result" = "X${1}"; then + func_dirname_result="${3}" + else + func_dirname_result="$func_dirname_result${2}" + fi +} + +# func_basename file +func_basename () +{ + func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` +} + + +# func_stripname prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +# func_strip_suffix prefix name +func_stripname () +{ + case ${2} in + .*) func_stripname_result=`$ECHO "X${3}" \ + | $Xsed -e "s%^${1}%%" -e "s%\\\\${2}\$%%"`;; + *) func_stripname_result=`$ECHO "X${3}" \ + | $Xsed -e "s%^${1}%%" -e "s%${2}\$%%"`;; + esac +} + +# sed scripts: +my_sed_long_opt='1s/^\(-[^=]*\)=.*/\1/;q' +my_sed_long_arg='1s/^-[^=]*=//' + +# func_opt_split +func_opt_split () +{ + func_opt_split_opt=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_opt"` + func_opt_split_arg=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_arg"` +} + +# func_lo2o object +func_lo2o () +{ + func_lo2o_result=`$ECHO "X${1}" | $Xsed -e "$lo2o"` +} + +# func_xform libobj-or-source +func_xform () +{ + func_xform_result=`$ECHO "X${1}" | $Xsed -e 's/\.[^.]*$/.lo/'` +} + +# func_arith arithmetic-term... +func_arith () +{ + func_arith_result=`expr "$@"` +} + +# func_len string +# STRING may not start with a hyphen. +func_len () +{ + func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len` +} + +_LT_EOF +esac + +case $lt_shell_append in + yes) + cat << \_LT_EOF >> "$cfgfile" + +# func_append var value +# Append VALUE to the end of shell variable VAR. +func_append () +{ + eval "$1+=\$2" +} +_LT_EOF + ;; + *) + cat << \_LT_EOF >> "$cfgfile" + +# func_append var value +# Append VALUE to the end of shell variable VAR. +func_append () +{ + eval "$1=\$$1\$2" +} + +_LT_EOF + ;; + esac + + + sed -n '/^# Generated shell functions inserted here/,$p' "$ltmain" >> "$cfgfile" \ + || (rm -f "$cfgfile"; exit 1) + + mv -f "$cfgfile" "$ofile" || + (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") + chmod +x "$ofile" + + ;; + + esac +done # for ac_tag + + +{ (exit 0); exit 0; } diff --git a/components/external/SQLite-3.8.1/make/libtool b/components/external/SQLite-3.8.1/make/libtool new file mode 100644 index 0000000000000000000000000000000000000000..4e58260c5e753ce8637e82b0e93d0c935aa49a19 --- /dev/null +++ b/components/external/SQLite-3.8.1/make/libtool @@ -0,0 +1,8945 @@ +#! /bin/sh + +# libtool - Provide generalized library-building support services. +# Generated automatically by config.status () 3.8 +# Libtool was configured on host geniuscode: +# NOTE: Changes made to this file will be lost: look at ltmain.sh. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, +# 2006, 2007, 2008 Free Software Foundation, Inc. +# Written by Gordon Matzigkeit, 1996 +# +# This file is part of GNU Libtool. +# +# GNU Libtool is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of +# the License, or (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Libtool; see the file COPYING. If not, a copy +# can be downloaded from http://www.gnu.org/licenses/gpl.html, or +# obtained by writing to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + +# The names of the tagged configurations supported by this script. +available_tags="" + +# ### BEGIN LIBTOOL CONFIG + +# Which release of libtool.m4 was used? +macro_version=2.2.6 +macro_revision=1.3012 + +# Whether or not to build shared libraries. +build_libtool_libs=no + +# Whether or not to build static libraries. +build_old_libs=yes + +# What type of objects to build. +pic_mode=default + +# Whether or not to optimize for fast installation. +fast_install=yes + +# The host system. +host_alias=arm-none-eabi +host=arm-none-eabi +host_os=eabi + +# The build system. +build_alias= +build=i686-pc-cygwin +build_os=cygwin + +# A sed program that does not truncate output. +SED="/usr/bin/sed" + +# Sed that helps us avoid accidentally triggering echo(1) options like -n. +Xsed="$SED -e 1s/^X//" + +# A grep program that handles long lines. +GREP="/usr/bin/grep" + +# An ERE matcher. +EGREP="/usr/bin/grep -E" + +# A literal string matcher. +FGREP="/usr/bin/grep -F" + +# A BSD- or MS-compatible name lister. +NM="/cygdrive/c/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/arm-none-eabi-nm -B" + +# Whether we need soft or hard links. +LN_S="ln -s" + +# What is the maximum length of a command? +max_cmd_len=8192 + +# Object file suffix (normally "o"). +objext=o + +# Executable file suffix (normally ""). +exeext= + +# whether the shell understands "unset". +lt_unset=unset + +# turn spaces into newlines. +SP2NL="tr \\040 \\012" + +# turn newlines into spaces. +NL2SP="tr \\015\\012 \\040\\040" + +# How to create reloadable object files. +reload_flag=" -r" +reload_cmds="\$LD\$reload_flag -o \$output\$reload_objs" + +# An object symbol dumper. +OBJDUMP="arm-none-eabi-objdump" + +# Method to check whether dependent libraries are shared objects. +deplibs_check_method="unknown" + +# Command to use when deplibs_check_method == "file_magic". +file_magic_cmd="\$MAGIC_CMD" + +# The archiver. +AR="arm-none-eabi-ar" +AR_FLAGS="cru" + +# A symbol stripping program. +STRIP="arm-none-eabi-strip" + +# Commands used to install an old-style archive. +RANLIB="arm-none-eabi-ranlib" +old_postinstall_cmds="chmod 644 \$oldlib~\$RANLIB \$oldlib" +old_postuninstall_cmds="" + +# A C compiler. +LTCC="arm-none-eabi-gcc" + +# LTCC compiler flags. +LTCFLAGS=" -g -O2 -DSQLITE_OS_UNIX=1" + +# Take the output of nm and produce a listing of raw symbols and C names. +global_symbol_pipe="" + +# Transform the output of nm in a proper C declaration. +global_symbol_to_cdecl="" + +# Transform the output of nm in a C name address pair. +global_symbol_to_c_name_address="sed -n -e 's/^: \\([^ ]*\\) \$/ {\\\"\\1\\\", (void *) 0},/p' -e 's/^[BCDEGRST]* \\([^ ]*\\) \\([^ ]*\\)\$/ {\"\\2\", (void *) \\&\\2},/p'" + +# Transform the output of nm in a C name address pair when lib prefix is needed. +global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \\([^ ]*\\) \$/ {\\\"\\1\\\", (void *) 0},/p' -e 's/^[BCDEGRST]* \\([^ ]*\\) \\(lib[^ ]*\\)\$/ {\"\\2\", (void *) \\&\\2},/p' -e 's/^[BCDEGRST]* \\([^ ]*\\) \\([^ ]*\\)\$/ {\"lib\\2\", (void *) \\&\\2},/p'" + +# The name of the directory that contains temporary libtool files. +objdir=.libs + +# Shell to use when invoking shell scripts. +SHELL="/bin/sh" + +# An echo program that does not interpret backslashes. +ECHO="echo" + +# Used to examine libraries when file_magic_cmd begins with "file". +MAGIC_CMD=file + +# Must we lock files when doing compilation? +need_locks="no" + +# Tool to manipulate archived DWARF debug symbol files on Mac OS X. +DSYMUTIL="" + +# Tool to change global to local symbols on Mac OS X. +NMEDIT="" + +# Tool to manipulate fat objects and archives on Mac OS X. +LIPO="" + +# ldd/readelf like tool for Mach-O binaries on Mac OS X. +OTOOL="" + +# ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. +OTOOL64="" + +# Old archive suffix (normally "a"). +libext=a + +# Shared library suffix (normally ".so"). +shrext_cmds=".so" + +# The commands to extract the exported symbol list from a shared archive. +extract_expsyms_cmds="" + +# Variables whose values should be saved in libtool wrapper scripts and +# restored at link time. +variables_saved_for_relink="PATH GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" + +# Do we need the "lib" prefix for modules? +need_lib_prefix=unknown + +# Do we need a version for libraries? +need_version=unknown + +# Library versioning type. +version_type=none + +# Shared library runtime path variable. +runpath_var= + +# Shared library path variable. +shlibpath_var= + +# Is shlibpath searched before the hard-coded library search path? +shlibpath_overrides_runpath=unknown + +# Format of library name prefix. +libname_spec="lib\$name" + +# List of archive names. First name is the real one, the rest are links. +# The last name is the one that the linker finds with -lNAME +library_names_spec="" + +# The coded name of the library, if different from the real name. +soname_spec="" + +# Command to use after installation of a shared archive. +postinstall_cmds="" + +# Command to use after uninstallation of a shared archive. +postuninstall_cmds="" + +# Commands used to finish a libtool library installation in a directory. +finish_cmds="" + +# As "finish_cmds", except a single script fragment to be evaled but +# not shown. +finish_eval="" + +# Whether we should hardcode library paths into libraries. +hardcode_into_libs=no + +# Compile-time system search path for libraries. +sys_lib_search_path_spec="" + +# Run-time system search path for libraries. +sys_lib_dlsearch_path_spec="/lib /usr/lib" + +# Whether dlopen is supported. +dlopen_support=unknown + +# Whether dlopen of programs is supported. +dlopen_self=unknown + +# Whether dlopen of statically linked programs is supported. +dlopen_self_static=unknown + +# Commands to strip libraries. +old_striplib="arm-none-eabi-strip --strip-debug" +striplib="arm-none-eabi-strip --strip-unneeded" + + +# The linker used to build libraries. +LD="c:/program files/codesourcery/sourcery_codebench_lite_for_arm_eabi/arm-none-eabi/bin/ld.exe" + +# Commands used to build an old-style archive. +old_archive_cmds="\$AR \$AR_FLAGS \$oldlib\$oldobjs~\$RANLIB \$oldlib" + +# A language specific compiler. +CC="arm-none-eabi-gcc" + +# Is the compiler the GNU compiler? +with_gcc=yes + +# Compiler flag to turn off builtin functions. +no_builtin_flag=" -fno-builtin" + +# How to pass a linker flag through the compiler. +wl="-Wl," + +# Additional compiler flags for building library objects. +pic_flag=" -fPIC -DPIC" + +# Compiler flag to prevent dynamic linking. +link_static_flag="-static" + +# Does compiler simultaneously support -c and -o options? +compiler_c_o="yes" + +# Whether or not to add -lc for building shared libraries. +build_libtool_need_lc=yes + +# Whether or not to disallow shared libs when runtime libs are static. +allow_libtool_libs_with_static_runtimes=no + +# Compiler flag to allow reflexive dlopens. +export_dynamic_flag_spec="" + +# Compiler flag to generate shared objects directly from archives. +whole_archive_flag_spec="" + +# Whether the compiler copes with passing no objects directly. +compiler_needs_object="no" + +# Create an old-style archive from a shared archive. +old_archive_from_new_cmds="" + +# Create a temporary old-style archive to link instead of a shared archive. +old_archive_from_expsyms_cmds="" + +# Commands used to build a shared archive. +archive_cmds="" +archive_expsym_cmds="" + +# Commands used to build a loadable module if different from building +# a shared archive. +module_cmds="" +module_expsym_cmds="" + +# Whether we are building with GNU ld or not. +with_gnu_ld="no" + +# Flag that allows shared libraries with undefined symbols to be built. +allow_undefined_flag="" + +# Flag that enforces no undefined symbols. +no_undefined_flag="" + +# Flag to hardcode $libdir into a binary during linking. +# This must work even if $libdir does not exist +hardcode_libdir_flag_spec="" + +# If ld is used when linking, flag to hardcode $libdir into a binary +# during linking. This must work even if $libdir does not exist. +hardcode_libdir_flag_spec_ld="" + +# Whether we need a single "-rpath" flag with a separated argument. +hardcode_libdir_separator="" + +# Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes +# DIR into the resulting binary. +hardcode_direct=no + +# Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes +# DIR into the resulting binary and the resulting library dependency is +# "absolute",i.e impossible to change by setting ${shlibpath_var} if the +# library is relocated. +hardcode_direct_absolute=no + +# Set to "yes" if using the -LDIR flag during linking hardcodes DIR +# into the resulting binary. +hardcode_minus_L=no + +# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR +# into the resulting binary. +hardcode_shlibpath_var=unsupported + +# Set to "yes" if building a shared library automatically hardcodes DIR +# into the library and all subsequent libraries and executables linked +# against it. +hardcode_automatic=no + +# Set to yes if linker adds runtime paths of dependent libraries +# to runtime path list. +inherit_rpath=no + +# Whether libtool must link a program against all its dependency libraries. +link_all_deplibs=unknown + +# Fix the shell variable $srcfile for the compiler. +fix_srcfile_path="" + +# Set to "yes" if exported symbols are required. +always_export_symbols=no + +# The commands to list exported symbols. +export_symbols_cmds="\$NM \$libobjs \$convenience | \$global_symbol_pipe | \$SED 's/.* //' | sort | uniq > \$export_symbols" + +# Symbols that should not be listed in the preloaded symbols. +exclude_expsyms="_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*" + +# Symbols that must always be exported. +include_expsyms="" + +# Commands necessary for linking programs (against libraries) with templates. +prelink_cmds="" + +# Specify filename containing input files. +file_list_spec="" + +# How to hardcode a shared library path into an executable. +hardcode_action=unsupported + +# ### END LIBTOOL CONFIG + +# Generated from ltmain.m4sh. + +# ltmain.sh (GNU libtool) 2.2.6 +# Written by Gordon Matzigkeit , 1996 + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc. +# This is free software; see the source for copying conditions. There is NO +# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +# GNU Libtool is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Libtool; see the file COPYING. If not, a copy +# can be downloaded from http://www.gnu.org/licenses/gpl.html, +# or obtained by writing to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +# Usage: $progname [OPTION]... [MODE-ARG]... +# +# Provide generalized library-building support services. +# +# --config show all configuration variables +# --debug enable verbose shell tracing +# -n, --dry-run display commands without modifying any files +# --features display basic configuration information and exit +# --mode=MODE use operation mode MODE +# --preserve-dup-deps don't remove duplicate dependency libraries +# --quiet, --silent don't print informational messages +# --tag=TAG use configuration variables from tag TAG +# -v, --verbose print informational messages (default) +# --version print version information +# -h, --help print short or long help message +# +# MODE must be one of the following: +# +# clean remove files from the build directory +# compile compile a source file into a libtool object +# execute automatically set library path, then run a program +# finish complete the installation of libtool libraries +# install install libraries or executables +# link create a library or an executable +# uninstall remove libraries from an installed directory +# +# MODE-ARGS vary depending on the MODE. +# Try `$progname --help --mode=MODE' for a more detailed description of MODE. +# +# When reporting a bug, please describe a test case to reproduce it and +# include the following information: +# +# host-triplet: $host +# shell: $SHELL +# compiler: $LTCC +# compiler flags: $LTCFLAGS +# linker: $LD (gnu? $with_gnu_ld) +# $progname: (GNU libtool) 2.2.6 +# automake: $automake_version +# autoconf: $autoconf_version +# +# Report bugs to . + +PROGRAM=ltmain.sh +PACKAGE=libtool +VERSION=2.2.6 +TIMESTAMP="" +package_revision=1.3012 + +# Be Bourne compatible +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac +fi +BIN_SH=xpg4; export BIN_SH # for Tru64 +DUALCASE=1; export DUALCASE # for MKS sh + +# NLS nuisances: We save the old values to restore during execute mode. +# Only set LANG and LC_ALL to C if already set. +# These must not be set unconditionally because not all systems understand +# e.g. LANG=C (notably SCO). +lt_user_locale= +lt_safe_locale= +for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES +do + eval "if test \"\${$lt_var+set}\" = set; then + save_$lt_var=\$$lt_var + $lt_var=C + export $lt_var + lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" + lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" + fi" +done + +$lt_unset CDPATH + + + + + +: ${CP="cp -f"} +: ${ECHO="echo"} +: ${EGREP="/usr/bin/grep -E"} +: ${FGREP="/usr/bin/grep -F"} +: ${GREP="/usr/bin/grep"} +: ${LN_S="ln -s"} +: ${MAKE="make"} +: ${MKDIR="mkdir"} +: ${MV="mv -f"} +: ${RM="rm -f"} +: ${SED="/opt/local/bin/gsed"} +: ${SHELL="${CONFIG_SHELL-/bin/sh}"} +: ${Xsed="$SED -e 1s/^X//"} + +# Global variables: +EXIT_SUCCESS=0 +EXIT_FAILURE=1 +EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. +EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. + +exit_status=$EXIT_SUCCESS + +# Make sure IFS has a sensible default +lt_nl=' +' +IFS=" $lt_nl" + +dirname="s,/[^/]*$,," +basename="s,^.*/,," + +# func_dirname_and_basename file append nondir_replacement +# perform func_basename and func_dirname in a single function +# call: +# dirname: Compute the dirname of FILE. If nonempty, +# add APPEND to the result, otherwise set result +# to NONDIR_REPLACEMENT. +# value returned in "$func_dirname_result" +# basename: Compute filename of FILE. +# value retuned in "$func_basename_result" +# Implementation must be kept synchronized with func_dirname +# and func_basename. For efficiency, we do not delegate to +# those functions but instead duplicate the functionality here. +func_dirname_and_basename () +{ + # Extract subdirectory from the argument. + func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` + if test "X$func_dirname_result" = "X${1}"; then + func_dirname_result="${3}" + else + func_dirname_result="$func_dirname_result${2}" + fi + func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` +} + +# Generated shell functions inserted here. + +# func_dirname file append nondir_replacement +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +func_dirname () +{ + case ${1} in + */*) func_dirname_result="${1%/*}${2}" ;; + * ) func_dirname_result="${3}" ;; + esac +} + +# func_basename file +func_basename () +{ + func_basename_result="${1##*/}" +} + +# func_dirname_and_basename file append nondir_replacement +# perform func_basename and func_dirname in a single function +# call: +# dirname: Compute the dirname of FILE. If nonempty, +# add APPEND to the result, otherwise set result +# to NONDIR_REPLACEMENT. +# value returned in "$func_dirname_result" +# basename: Compute filename of FILE. +# value retuned in "$func_basename_result" +# Implementation must be kept synchronized with func_dirname +# and func_basename. For efficiency, we do not delegate to +# those functions but instead duplicate the functionality here. +func_dirname_and_basename () +{ + case ${1} in + */*) func_dirname_result="${1%/*}${2}" ;; + * ) func_dirname_result="${3}" ;; + esac + func_basename_result="${1##*/}" +} + +# func_stripname prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +func_stripname () +{ + # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are + # positional parameters, so assign one to ordinary parameter first. + func_stripname_result=${3} + func_stripname_result=${func_stripname_result#"${1}"} + func_stripname_result=${func_stripname_result%"${2}"} +} + +# func_opt_split +func_opt_split () +{ + func_opt_split_opt=${1%%=*} + func_opt_split_arg=${1#*=} +} + +# func_lo2o object +func_lo2o () +{ + case ${1} in + *.lo) func_lo2o_result=${1%.lo}.${objext} ;; + *) func_lo2o_result=${1} ;; + esac +} + +# func_xform libobj-or-source +func_xform () +{ + func_xform_result=${1%.*}.lo +} + +# func_arith arithmetic-term... +func_arith () +{ + func_arith_result=$(( $* )) +} + +# func_len string +# STRING may not start with a hyphen. +func_len () +{ + func_len_result=${#1} +} + + +# func_append var value +# Append VALUE to the end of shell variable VAR. +func_append () +{ + eval "$1+=\$2" +} +# Generated shell functions inserted here. + +# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh +# is ksh but when the shell is invoked as "sh" and the current value of +# the _XPG environment variable is not equal to 1 (one), the special +# positional parameter $0, within a function call, is the name of the +# function. +progpath="$0" + +# The name of this program: +# In the unlikely event $progname began with a '-', it would play havoc with +# func_echo (imagine progname=-n), so we prepend ./ in that case: +func_dirname_and_basename "$progpath" +progname=$func_basename_result +case $progname in + -*) progname=./$progname ;; +esac + +# Make sure we have an absolute path for reexecution: +case $progpath in + [\\/]*|[A-Za-z]:\\*) ;; + *[\\/]*) + progdir=$func_dirname_result + progdir=`cd "$progdir" && pwd` + progpath="$progdir/$progname" + ;; + *) + save_IFS="$IFS" + IFS=: + for progdir in $PATH; do + IFS="$save_IFS" + test -x "$progdir/$progname" && break + done + IFS="$save_IFS" + test -n "$progdir" || progdir=`pwd` + progpath="$progdir/$progname" + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed="${SED}"' -e 1s/^X//' +sed_quote_subst='s/\([`"$\\]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\(["`\\]\)/\\\1/g' + +# Re-`\' parameter expansions in output of double_quote_subst that were +# `\'-ed in input to the same. If an odd number of `\' preceded a '$' +# in input to double_quote_subst, that '$' was protected from expansion. +# Since each input `\' is now two `\'s, look for any number of runs of +# four `\'s followed by two `\'s and then a '$'. `\' that '$'. +bs='\\' +bs2='\\\\' +bs4='\\\\\\\\' +dollar='\$' +sed_double_backslash="\ + s/$bs4/&\\ +/g + s/^$bs2$dollar/$bs&/ + s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g + s/\n//g" + +# Standard options: +opt_dry_run=false +opt_help=false +opt_quiet=false +opt_verbose=false +opt_warning=: + +# func_echo arg... +# Echo program name prefixed message, along with the current mode +# name if it has been set yet. +func_echo () +{ + $ECHO "$progname${mode+: }$mode: $*" +} + +# func_verbose arg... +# Echo program name prefixed message in verbose mode only. +func_verbose () +{ + $opt_verbose && func_echo ${1+"$@"} + + # A bug in bash halts the script if the last line of a function + # fails when set -e is in force, so we need another command to + # work around that: + : +} + +# func_error arg... +# Echo program name prefixed message to standard error. +func_error () +{ + $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2 +} + +# func_warning arg... +# Echo program name prefixed warning message to standard error. +func_warning () +{ + $opt_warning && $ECHO "$progname${mode+: }$mode: warning: "${1+"$@"} 1>&2 + + # bash bug again: + : +} + +# func_fatal_error arg... +# Echo program name prefixed message to standard error, and exit. +func_fatal_error () +{ + func_error ${1+"$@"} + exit $EXIT_FAILURE +} + +# func_fatal_help arg... +# Echo program name prefixed message to standard error, followed by +# a help hint, and exit. +func_fatal_help () +{ + func_error ${1+"$@"} + func_fatal_error "$help" +} +help="Try \`$progname --help' for more information." ## default + + +# func_grep expression filename +# Check whether EXPRESSION matches any line of FILENAME, without output. +func_grep () +{ + $GREP "$1" "$2" >/dev/null 2>&1 +} + + +# func_mkdir_p directory-path +# Make sure the entire path to DIRECTORY-PATH is available. +func_mkdir_p () +{ + my_directory_path="$1" + my_dir_list= + + if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then + + # Protect directory names starting with `-' + case $my_directory_path in + -*) my_directory_path="./$my_directory_path" ;; + esac + + # While some portion of DIR does not yet exist... + while test ! -d "$my_directory_path"; do + # ...make a list in topmost first order. Use a colon delimited + # list incase some portion of path contains whitespace. + my_dir_list="$my_directory_path:$my_dir_list" + + # If the last portion added has no slash in it, the list is done + case $my_directory_path in */*) ;; *) break ;; esac + + # ...otherwise throw away the child directory and loop + my_directory_path=`$ECHO "X$my_directory_path" | $Xsed -e "$dirname"` + done + my_dir_list=`$ECHO "X$my_dir_list" | $Xsed -e 's,:*$,,'` + + save_mkdir_p_IFS="$IFS"; IFS=':' + for my_dir in $my_dir_list; do + IFS="$save_mkdir_p_IFS" + # mkdir can fail with a `File exist' error if two processes + # try to create one of the directories concurrently. Don't + # stop in that case! + $MKDIR "$my_dir" 2>/dev/null || : + done + IFS="$save_mkdir_p_IFS" + + # Bail out if we (or some other process) failed to create a directory. + test -d "$my_directory_path" || \ + func_fatal_error "Failed to create \`$1'" + fi +} + + +# func_mktempdir [string] +# Make a temporary directory that won't clash with other running +# libtool processes, and avoids race conditions if possible. If +# given, STRING is the basename for that directory. +func_mktempdir () +{ + my_template="${TMPDIR-/tmp}/${1-$progname}" + + if test "$opt_dry_run" = ":"; then + # Return a directory name, but don't create it in dry-run mode + my_tmpdir="${my_template}-$$" + else + + # If mktemp works, use that first and foremost + my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` + + if test ! -d "$my_tmpdir"; then + # Failing that, at least try and use $RANDOM to avoid a race + my_tmpdir="${my_template}-${RANDOM-0}$$" + + save_mktempdir_umask=`umask` + umask 0077 + $MKDIR "$my_tmpdir" + umask $save_mktempdir_umask + fi + + # If we're not in dry-run mode, bomb out on failure + test -d "$my_tmpdir" || \ + func_fatal_error "cannot create temporary directory \`$my_tmpdir'" + fi + + $ECHO "X$my_tmpdir" | $Xsed +} + + +# func_quote_for_eval arg +# Aesthetically quote ARG to be evaled later. +# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT +# is double-quoted, suitable for a subsequent eval, whereas +# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters +# which are still active within double quotes backslashified. +func_quote_for_eval () +{ + case $1 in + *[\\\`\"\$]*) + func_quote_for_eval_unquoted_result=`$ECHO "X$1" | $Xsed -e "$sed_quote_subst"` ;; + *) + func_quote_for_eval_unquoted_result="$1" ;; + esac + + case $func_quote_for_eval_unquoted_result in + # Double-quote args containing shell metacharacters to delay + # word splitting, command substitution and and variable + # expansion for a subsequent eval. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" + ;; + *) + func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" + esac +} + + +# func_quote_for_expand arg +# Aesthetically quote ARG to be evaled later; same as above, +# but do not quote variable references. +func_quote_for_expand () +{ + case $1 in + *[\\\`\"]*) + my_arg=`$ECHO "X$1" | $Xsed \ + -e "$double_quote_subst" -e "$sed_double_backslash"` ;; + *) + my_arg="$1" ;; + esac + + case $my_arg in + # Double-quote args containing shell metacharacters to delay + # word splitting and command substitution for a subsequent eval. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + my_arg="\"$my_arg\"" + ;; + esac + + func_quote_for_expand_result="$my_arg" +} + + +# func_show_eval cmd [fail_exp] +# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. +func_show_eval () +{ + my_cmd="$1" + my_fail_exp="${2-:}" + + ${opt_silent-false} || { + func_quote_for_expand "$my_cmd" + eval "func_echo $func_quote_for_expand_result" + } + + if ${opt_dry_run-false}; then :; else + eval "$my_cmd" + my_status=$? + if test "$my_status" -eq 0; then :; else + eval "(exit $my_status); $my_fail_exp" + fi + fi +} + + +# func_show_eval_locale cmd [fail_exp] +# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. Use the saved locale for evaluation. +func_show_eval_locale () +{ + my_cmd="$1" + my_fail_exp="${2-:}" + + ${opt_silent-false} || { + func_quote_for_expand "$my_cmd" + eval "func_echo $func_quote_for_expand_result" + } + + if ${opt_dry_run-false}; then :; else + eval "$lt_user_locale + $my_cmd" + my_status=$? + eval "$lt_safe_locale" + if test "$my_status" -eq 0; then :; else + eval "(exit $my_status); $my_fail_exp" + fi + fi +} + + + + + +# func_version +# Echo version message to standard output and exit. +func_version () +{ + $SED -n '/^# '$PROGRAM' (GNU /,/# warranty; / { + s/^# // + s/^# *$// + s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ + p + }' < "$progpath" + exit $? +} + +# func_usage +# Echo short help message to standard output and exit. +func_usage () +{ + $SED -n '/^# Usage:/,/# -h/ { + s/^# // + s/^# *$// + s/\$progname/'$progname'/ + p + }' < "$progpath" + $ECHO + $ECHO "run \`$progname --help | more' for full usage" + exit $? +} + +# func_help +# Echo long help message to standard output and exit. +func_help () +{ + $SED -n '/^# Usage:/,/# Report bugs to/ { + s/^# // + s/^# *$// + s*\$progname*'$progname'* + s*\$host*'"$host"'* + s*\$SHELL*'"$SHELL"'* + s*\$LTCC*'"$LTCC"'* + s*\$LTCFLAGS*'"$LTCFLAGS"'* + s*\$LD*'"$LD"'* + s/\$with_gnu_ld/'"$with_gnu_ld"'/ + s/\$automake_version/'"`(automake --version) 2>/dev/null |$SED 1q`"'/ + s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/ + p + }' < "$progpath" + exit $? +} + +# func_missing_arg argname +# Echo program name prefixed message to standard error and set global +# exit_cmd. +func_missing_arg () +{ + func_error "missing argument for $1" + exit_cmd=exit +} + +exit_cmd=: + + + + + +# Check that we have a working $ECHO. +if test "X$1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X$1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t'; then + # Yippee, $ECHO works! + : +else + # Restart under the correct shell, and then maybe $ECHO will work. + exec $SHELL "$progpath" --no-reexec ${1+"$@"} +fi +# Same for EGREP, and just to be sure, do LTCC as well +if test "x$EGREP" = x ; then + EGREP=egrep +fi +if test "x$LTCC" = x ; then + LTCC=${CC-gcc} +fi + +if test "X$1" = X--fallback-echo; then + # used as fallback echo + shift + cat </dev/null 2>&1; then + taglist="$taglist $tagname" + + # Evaluate the configuration. Be careful to quote the path + # and the sed script, to avoid splitting on whitespace, but + # also don't use non-portable quotes within backquotes within + # quotes we have to do it in 2 steps: + extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` + eval "$extractedcf" + else + func_error "ignoring unknown tag $tagname" + fi + ;; + esac +} + +# Parse options once, thoroughly. This comes as soon as possible in +# the script to make things like `libtool --version' happen quickly. +{ + + # Shorthand for --mode=foo, only valid as the first argument + case $1 in + clean|clea|cle|cl) + shift; set dummy --mode clean ${1+"$@"}; shift + ;; + compile|compil|compi|comp|com|co|c) + shift; set dummy --mode compile ${1+"$@"}; shift + ;; + execute|execut|execu|exec|exe|ex|e) + shift; set dummy --mode execute ${1+"$@"}; shift + ;; + finish|finis|fini|fin|fi|f) + shift; set dummy --mode finish ${1+"$@"}; shift + ;; + install|instal|insta|inst|ins|in|i) + shift; set dummy --mode install ${1+"$@"}; shift + ;; + link|lin|li|l) + shift; set dummy --mode link ${1+"$@"}; shift + ;; + uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) + shift; set dummy --mode uninstall ${1+"$@"}; shift + ;; + esac + + # Parse non-mode specific arguments: + while test "$#" -gt 0; do + opt="$1" + shift + + case $opt in + --config) func_config ;; + + --debug) preserve_args="$preserve_args $opt" + func_echo "enabling shell trace mode" + opt_debug='set -x' + $opt_debug + ;; + + -dlopen) test "$#" -eq 0 && func_missing_arg "$opt" && break + execute_dlfiles="$execute_dlfiles $1" + shift + ;; + + --dry-run | -n) opt_dry_run=: ;; + --features) func_features ;; + --finish) mode="finish" ;; + + --mode) test "$#" -eq 0 && func_missing_arg "$opt" && break + case $1 in + # Valid mode arguments: + clean) ;; + compile) ;; + execute) ;; + finish) ;; + install) ;; + link) ;; + relink) ;; + uninstall) ;; + + # Catch anything else as an error + *) func_error "invalid argument for $opt" + exit_cmd=exit + break + ;; + esac + + mode="$1" + shift + ;; + + --preserve-dup-deps) + opt_duplicate_deps=: ;; + + --quiet|--silent) preserve_args="$preserve_args $opt" + opt_silent=: + ;; + + --verbose| -v) preserve_args="$preserve_args $opt" + opt_silent=false + ;; + + --tag) test "$#" -eq 0 && func_missing_arg "$opt" && break + preserve_args="$preserve_args $opt $1" + func_enable_tag "$1" # tagname is set here + shift + ;; + + # Separate optargs to long options: + -dlopen=*|--mode=*|--tag=*) + func_opt_split "$opt" + set dummy "$func_opt_split_opt" "$func_opt_split_arg" ${1+"$@"} + shift + ;; + + -\?|-h) func_usage ;; + --help) opt_help=: ;; + --version) func_version ;; + + -*) func_fatal_help "unrecognized option \`$opt'" ;; + + *) nonopt="$opt" + break + ;; + esac + done + + + case $host in + *cygwin* | *mingw* | *pw32* | *cegcc*) + # don't eliminate duplications in $postdeps and $predeps + opt_duplicate_compiler_generated_deps=: + ;; + *) + opt_duplicate_compiler_generated_deps=$opt_duplicate_deps + ;; + esac + + # Having warned about all mis-specified options, bail out if + # anything was wrong. + $exit_cmd $EXIT_FAILURE +} + +# func_check_version_match +# Ensure that we are using m4 macros, and libtool script from the same +# release of libtool. +func_check_version_match () +{ + if test "$package_revision" != "$macro_revision"; then + if test "$VERSION" != "$macro_version"; then + if test -z "$macro_version"; then + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from an older release. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from $PACKAGE $macro_version. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + fi + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, +$progname: but the definition of this LT_INIT comes from revision $macro_revision. +$progname: You should recreate aclocal.m4 with macros from revision $package_revision +$progname: of $PACKAGE $VERSION and run autoconf again. +_LT_EOF + fi + + exit $EXIT_MISMATCH + fi +} + + +## ----------- ## +## Main. ## +## ----------- ## + +$opt_help || { + # Sanity checks first: + func_check_version_match + + if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then + func_fatal_configuration "not configured to build any kind of library" + fi + + test -z "$mode" && func_fatal_error "error: you must specify a MODE." + + + # Darwin sucks + eval std_shrext=\"$shrext_cmds\" + + + # Only execute mode is allowed to have -dlopen flags. + if test -n "$execute_dlfiles" && test "$mode" != execute; then + func_error "unrecognized option \`-dlopen'" + $ECHO "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Change the help message to a mode-specific one. + generic_help="$help" + help="Try \`$progname --help --mode=$mode' for more information." +} + + +# func_lalib_p file +# True iff FILE is a libtool `.la' library or `.lo' object file. +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_lalib_p () +{ + test -f "$1" && + $SED -e 4q "$1" 2>/dev/null \ + | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 +} + +# func_lalib_unsafe_p file +# True iff FILE is a libtool `.la' library or `.lo' object file. +# This function implements the same check as func_lalib_p without +# resorting to external programs. To this end, it redirects stdin and +# closes it afterwards, without saving the original file descriptor. +# As a safety measure, use it only where a negative result would be +# fatal anyway. Works if `file' does not exist. +func_lalib_unsafe_p () +{ + lalib_p=no + if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then + for lalib_p_l in 1 2 3 4 + do + read lalib_p_line + case "$lalib_p_line" in + \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; + esac + done + exec 0<&5 5<&- + fi + test "$lalib_p" = yes +} + +# func_ltwrapper_script_p file +# True iff FILE is a libtool wrapper script +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_script_p () +{ + func_lalib_p "$1" +} + +# func_ltwrapper_executable_p file +# True iff FILE is a libtool wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_executable_p () +{ + func_ltwrapper_exec_suffix= + case $1 in + *.exe) ;; + *) func_ltwrapper_exec_suffix=.exe ;; + esac + $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 +} + +# func_ltwrapper_scriptname file +# Assumes file is an ltwrapper_executable +# uses $file to determine the appropriate filename for a +# temporary ltwrapper_script. +func_ltwrapper_scriptname () +{ + func_ltwrapper_scriptname_result="" + if func_ltwrapper_executable_p "$1"; then + func_dirname_and_basename "$1" "" "." + func_stripname '' '.exe' "$func_basename_result" + func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" + fi +} + +# func_ltwrapper_p file +# True iff FILE is a libtool wrapper script or wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_p () +{ + func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" +} + + +# func_execute_cmds commands fail_cmd +# Execute tilde-delimited COMMANDS. +# If FAIL_CMD is given, eval that upon failure. +# FAIL_CMD may read-access the current command in variable CMD! +func_execute_cmds () +{ + $opt_debug + save_ifs=$IFS; IFS='~' + for cmd in $1; do + IFS=$save_ifs + eval cmd=\"$cmd\" + func_show_eval "$cmd" "${2-:}" + done + IFS=$save_ifs +} + + +# func_source file +# Source FILE, adding directory component if necessary. +# Note that it is not necessary on cygwin/mingw to append a dot to +# FILE even if both FILE and FILE.exe exist: automatic-append-.exe +# behavior happens only for exec(3), not for open(2)! Also, sourcing +# `FILE.' does not work on cygwin managed mounts. +func_source () +{ + $opt_debug + case $1 in + */* | *\\*) . "$1" ;; + *) . "./$1" ;; + esac +} + + +# func_infer_tag arg +# Infer tagged configuration to use if any are available and +# if one wasn't chosen via the "--tag" command line option. +# Only attempt this if the compiler in the base compile +# command doesn't match the default compiler. +# arg is usually of the form 'gcc ...' +func_infer_tag () +{ + $opt_debug + if test -n "$available_tags" && test -z "$tagname"; then + CC_quoted= + for arg in $CC; do + func_quote_for_eval "$arg" + CC_quoted="$CC_quoted $func_quote_for_eval_result" + done + case $@ in + # Blanks in the command may have been stripped by the calling shell, + # but not from the CC environment variable when configure was run. + " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) ;; + # Blanks at the start of $base_compile will cause this to fail + # if we don't check for them as well. + *) + for z in $available_tags; do + if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then + # Evaluate the configuration. + eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" + CC_quoted= + for arg in $CC; do + # Double-quote args containing other shell metacharacters. + func_quote_for_eval "$arg" + CC_quoted="$CC_quoted $func_quote_for_eval_result" + done + case "$@ " in + " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) + # The compiler in the base compile command matches + # the one in the tagged configuration. + # Assume this is the tagged configuration we want. + tagname=$z + break + ;; + esac + fi + done + # If $tagname still isn't set, then no tagged configuration + # was found and let the user know that the "--tag" command + # line option must be used. + if test -z "$tagname"; then + func_echo "unable to infer tagged configuration" + func_fatal_error "specify a tag with \`--tag'" +# else +# func_verbose "using $tagname tagged configuration" + fi + ;; + esac + fi +} + + + +# func_write_libtool_object output_name pic_name nonpic_name +# Create a libtool object file (analogous to a ".la" file), +# but don't create it if we're doing a dry run. +func_write_libtool_object () +{ + write_libobj=${1} + if test "$build_libtool_libs" = yes; then + write_lobj=\'${2}\' + else + write_lobj=none + fi + + if test "$build_old_libs" = yes; then + write_oldobj=\'${3}\' + else + write_oldobj=none + fi + + $opt_dry_run || { + cat >${write_libobj}T <?"'"'"' &()|`$[]' \ + && func_warning "libobj name \`$libobj' may not contain shell special characters." + func_dirname_and_basename "$obj" "/" "" + objname="$func_basename_result" + xdir="$func_dirname_result" + lobj=${xdir}$objdir/$objname + + test -z "$base_compile" && \ + func_fatal_help "you must specify a compilation command" + + # Delete any leftover library objects. + if test "$build_old_libs" = yes; then + removelist="$obj $lobj $libobj ${libobj}T" + else + removelist="$lobj $libobj ${libobj}T" + fi + + # On Cygwin there's no "real" PIC flag so we must build both object types + case $host_os in + cygwin* | mingw* | pw32* | os2* | cegcc*) + pic_mode=default + ;; + esac + if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then + # non-PIC code in shared libraries is not supported + pic_mode=default + fi + + # Calculate the filename of the output object if compiler does + # not support -o with -c + if test "$compiler_c_o" = no; then + output_obj=`$ECHO "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} + lockfile="$output_obj.lock" + else + output_obj= + need_locks=no + lockfile= + fi + + # Lock this critical section if it is needed + # We use this script file to make the link, it avoids creating a new file + if test "$need_locks" = yes; then + until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do + func_echo "Waiting for $lockfile to be removed" + sleep 2 + done + elif test "$need_locks" = warn; then + if test -f "$lockfile"; then + $ECHO "\ +*** ERROR, $lockfile exists and contains: +`cat $lockfile 2>/dev/null` + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + removelist="$removelist $output_obj" + $ECHO "$srcfile" > "$lockfile" + fi + + $opt_dry_run || $RM $removelist + removelist="$removelist $lockfile" + trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 + + if test -n "$fix_srcfile_path"; then + eval srcfile=\"$fix_srcfile_path\" + fi + func_quote_for_eval "$srcfile" + qsrcfile=$func_quote_for_eval_result + + # Only build a PIC object if we are building libtool libraries. + if test "$build_libtool_libs" = yes; then + # Without this assignment, base_compile gets emptied. + fbsd_hideous_sh_bug=$base_compile + + if test "$pic_mode" != no; then + command="$base_compile $qsrcfile $pic_flag" + else + # Don't build PIC code + command="$base_compile $qsrcfile" + fi + + func_mkdir_p "$xdir$objdir" + + if test -z "$output_obj"; then + # Place PIC objects in $objdir + command="$command -o $lobj" + fi + + func_show_eval_locale "$command" \ + 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' + + if test "$need_locks" = warn && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed, then go on to compile the next one + if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then + func_show_eval '$MV "$output_obj" "$lobj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + + # Allow error messages only from the first compilation. + if test "$suppress_opt" = yes; then + suppress_output=' >/dev/null 2>&1' + fi + fi + + # Only build a position-dependent object if we build old libraries. + if test "$build_old_libs" = yes; then + if test "$pic_mode" != yes; then + # Don't build PIC code + command="$base_compile $qsrcfile$pie_flag" + else + command="$base_compile $qsrcfile $pic_flag" + fi + if test "$compiler_c_o" = yes; then + command="$command -o $obj" + fi + + # Suppress compiler output if we already did a PIC compilation. + command="$command$suppress_output" + func_show_eval_locale "$command" \ + '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' + + if test "$need_locks" = warn && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed + if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then + func_show_eval '$MV "$output_obj" "$obj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + fi + + $opt_dry_run || { + func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" + + # Unlock the critical section if it was locked + if test "$need_locks" != no; then + removelist=$lockfile + $RM "$lockfile" + fi + } + + exit $EXIT_SUCCESS +} + +$opt_help || { +test "$mode" = compile && func_mode_compile ${1+"$@"} +} + +func_mode_help () +{ + # We need to display help for each of the modes. + case $mode in + "") + # Generic help is extracted from the usage comments + # at the start of this file. + func_help + ;; + + clean) + $ECHO \ +"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... + +Remove files from the build directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, object or program, all the files associated +with it are deleted. Otherwise, only FILE itself is deleted using RM." + ;; + + compile) + $ECHO \ +"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE + +Compile a source file into a libtool library object. + +This mode accepts the following additional options: + + -o OUTPUT-FILE set the output file name to OUTPUT-FILE + -no-suppress do not suppress compiler output for multiple passes + -prefer-pic try to building PIC objects only + -prefer-non-pic try to building non-PIC objects only + -shared do not build a \`.o' file suitable for static linking + -static only build a \`.o' file suitable for static linking + +COMPILE-COMMAND is a command to be used in creating a \`standard' object file +from the given SOURCEFILE. + +The output file name is determined by removing the directory component from +SOURCEFILE, then substituting the C source code suffix \`.c' with the +library object suffix, \`.lo'." + ;; + + execute) + $ECHO \ +"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... + +Automatically set library path, then run a program. + +This mode accepts the following additional options: + + -dlopen FILE add the directory containing FILE to the library path + +This mode sets the library path environment variable according to \`-dlopen' +flags. + +If any of the ARGS are libtool executable wrappers, then they are translated +into their corresponding uninstalled binary, and any of their required library +directories are added to the library path. + +Then, COMMAND is executed, with ARGS as arguments." + ;; + + finish) + $ECHO \ +"Usage: $progname [OPTION]... --mode=finish [LIBDIR]... + +Complete the installation of libtool libraries. + +Each LIBDIR is a directory that contains libtool libraries. + +The commands that this mode executes may require superuser privileges. Use +the \`--dry-run' option if you just want to see what would be executed." + ;; + + install) + $ECHO \ +"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... + +Install executables or libraries. + +INSTALL-COMMAND is the installation command. The first component should be +either the \`install' or \`cp' program. + +The following components of INSTALL-COMMAND are treated specially: + + -inst-prefix PREFIX-DIR Use PREFIX-DIR as a staging area for installation + +The rest of the components are interpreted as arguments to that command (only +BSD-compatible install options are recognized)." + ;; + + link) + $ECHO \ +"Usage: $progname [OPTION]... --mode=link LINK-COMMAND... + +Link object files or libraries together to form another library, or to +create an executable program. + +LINK-COMMAND is a command using the C compiler that you would use to create +a program from several object files. + +The following components of LINK-COMMAND are treated specially: + + -all-static do not do any dynamic linking at all + -avoid-version do not add a version suffix if possible + -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime + -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols + -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) + -export-symbols SYMFILE + try to export only the symbols listed in SYMFILE + -export-symbols-regex REGEX + try to export only the symbols matching REGEX + -LLIBDIR search LIBDIR for required installed libraries + -lNAME OUTPUT-FILE requires the installed library libNAME + -module build a library that can dlopened + -no-fast-install disable the fast-install mode + -no-install link a not-installable executable + -no-undefined declare that a library does not refer to external symbols + -o OUTPUT-FILE create OUTPUT-FILE from the specified objects + -objectlist FILE Use a list of object files found in FILE to specify objects + -precious-files-regex REGEX + don't remove output files matching REGEX + -release RELEASE specify package release information + -rpath LIBDIR the created library will eventually be installed in LIBDIR + -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries + -shared only do dynamic linking of libtool libraries + -shrext SUFFIX override the standard shared library file extension + -static do not do any dynamic linking of uninstalled libtool libraries + -static-libtool-libs + do not do any dynamic linking of libtool libraries + -version-info CURRENT[:REVISION[:AGE]] + specify library version info [each variable defaults to 0] + -weak LIBNAME declare that the target provides the LIBNAME interface + +All other options (arguments beginning with \`-') are ignored. + +Every other argument is treated as a filename. Files ending in \`.la' are +treated as uninstalled libtool libraries, other files are standard or library +object files. + +If the OUTPUT-FILE ends in \`.la', then a libtool library is created, +only library objects (\`.lo' files) may be specified, and \`-rpath' is +required, except when creating a convenience library. + +If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created +using \`ar' and \`ranlib', or on Windows using \`lib'. + +If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file +is created, otherwise an executable program is created." + ;; + + uninstall) + $ECHO \ +"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... + +Remove libraries from an installation directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, all the files associated with it are deleted. +Otherwise, only FILE itself is deleted using RM." + ;; + + *) + func_fatal_help "invalid operation mode \`$mode'" + ;; + esac + + $ECHO + $ECHO "Try \`$progname --help' for more information about other modes." + + exit $? +} + + # Now that we've collected a possible --mode arg, show help if necessary + $opt_help && func_mode_help + + +# func_mode_execute arg... +func_mode_execute () +{ + $opt_debug + # The first argument is the command name. + cmd="$nonopt" + test -z "$cmd" && \ + func_fatal_help "you must specify a COMMAND" + + # Handle -dlopen flags immediately. + for file in $execute_dlfiles; do + test -f "$file" \ + || func_fatal_help "\`$file' is not a file" + + dir= + case $file in + *.la) + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "\`$lib' is not a valid libtool archive" + + # Read the libtool library. + dlname= + library_names= + func_source "$file" + + # Skip this library if it cannot be dlopened. + if test -z "$dlname"; then + # Warn if it was a shared library. + test -n "$library_names" && \ + func_warning "\`$file' was not linked with \`-export-dynamic'" + continue + fi + + func_dirname "$file" "" "." + dir="$func_dirname_result" + + if test -f "$dir/$objdir/$dlname"; then + dir="$dir/$objdir" + else + if test ! -f "$dir/$dlname"; then + func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" + fi + fi + ;; + + *.lo) + # Just add the directory containing the .lo file. + func_dirname "$file" "" "." + dir="$func_dirname_result" + ;; + + *) + func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" + continue + ;; + esac + + # Get the absolute pathname. + absdir=`cd "$dir" && pwd` + test -n "$absdir" && dir="$absdir" + + # Now add the directory to shlibpath_var. + if eval "test -z \"\$$shlibpath_var\""; then + eval "$shlibpath_var=\"\$dir\"" + else + eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" + fi + done + + # This variable tells wrapper scripts just to set shlibpath_var + # rather than running their programs. + libtool_execute_magic="$magic" + + # Check if any of the arguments is a wrapper script. + args= + for file + do + case $file in + -*) ;; + *) + # Do a test to see if this is really a libtool program. + if func_ltwrapper_script_p "$file"; then + func_source "$file" + # Transform arg to wrapped name. + file="$progdir/$program" + elif func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + func_source "$func_ltwrapper_scriptname_result" + # Transform arg to wrapped name. + file="$progdir/$program" + fi + ;; + esac + # Quote arguments (to preserve shell metacharacters). + func_quote_for_eval "$file" + args="$args $func_quote_for_eval_result" + done + + if test "X$opt_dry_run" = Xfalse; then + if test -n "$shlibpath_var"; then + # Export the shlibpath_var. + eval "export $shlibpath_var" + fi + + # Restore saved environment variables + for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES + do + eval "if test \"\${save_$lt_var+set}\" = set; then + $lt_var=\$save_$lt_var; export $lt_var + else + $lt_unset $lt_var + fi" + done + + # Now prepare to actually exec the command. + exec_cmd="\$cmd$args" + else + # Display what would be done. + if test -n "$shlibpath_var"; then + eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" + $ECHO "export $shlibpath_var" + fi + $ECHO "$cmd$args" + exit $EXIT_SUCCESS + fi +} + +test "$mode" = execute && func_mode_execute ${1+"$@"} + + +# func_mode_finish arg... +func_mode_finish () +{ + $opt_debug + libdirs="$nonopt" + admincmds= + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + for dir + do + libdirs="$libdirs $dir" + done + + for libdir in $libdirs; do + if test -n "$finish_cmds"; then + # Do each command in the finish commands. + func_execute_cmds "$finish_cmds" 'admincmds="$admincmds +'"$cmd"'"' + fi + if test -n "$finish_eval"; then + # Do the single finish_eval. + eval cmds=\"$finish_eval\" + $opt_dry_run || eval "$cmds" || admincmds="$admincmds + $cmds" + fi + done + fi + + # Exit here if they wanted silent mode. + $opt_silent && exit $EXIT_SUCCESS + + $ECHO "X----------------------------------------------------------------------" | $Xsed + $ECHO "Libraries have been installed in:" + for libdir in $libdirs; do + $ECHO " $libdir" + done + $ECHO + $ECHO "If you ever happen to want to link against installed libraries" + $ECHO "in a given directory, LIBDIR, you must either use libtool, and" + $ECHO "specify the full pathname of the library, or use the \`-LLIBDIR'" + $ECHO "flag during linking and do at least one of the following:" + if test -n "$shlibpath_var"; then + $ECHO " - add LIBDIR to the \`$shlibpath_var' environment variable" + $ECHO " during execution" + fi + if test -n "$runpath_var"; then + $ECHO " - add LIBDIR to the \`$runpath_var' environment variable" + $ECHO " during linking" + fi + if test -n "$hardcode_libdir_flag_spec"; then + libdir=LIBDIR + eval flag=\"$hardcode_libdir_flag_spec\" + + $ECHO " - use the \`$flag' linker flag" + fi + if test -n "$admincmds"; then + $ECHO " - have your system administrator run these commands:$admincmds" + fi + if test -f /etc/ld.so.conf; then + $ECHO " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" + fi + $ECHO + + $ECHO "See any operating system documentation about shared libraries for" + case $host in + solaris2.[6789]|solaris2.1[0-9]) + $ECHO "more information, such as the ld(1), crle(1) and ld.so(8) manual" + $ECHO "pages." + ;; + *) + $ECHO "more information, such as the ld(1) and ld.so(8) manual pages." + ;; + esac + $ECHO "X----------------------------------------------------------------------" | $Xsed + exit $EXIT_SUCCESS +} + +test "$mode" = finish && func_mode_finish ${1+"$@"} + + +# func_mode_install arg... +func_mode_install () +{ + $opt_debug + # There may be an optional sh(1) argument at the beginning of + # install_prog (especially on Windows NT). + if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || + # Allow the use of GNU shtool's install command. + $ECHO "X$nonopt" | $GREP shtool >/dev/null; then + # Aesthetically quote it. + func_quote_for_eval "$nonopt" + install_prog="$func_quote_for_eval_result " + arg=$1 + shift + else + install_prog= + arg=$nonopt + fi + + # The real first argument should be the name of the installation program. + # Aesthetically quote it. + func_quote_for_eval "$arg" + install_prog="$install_prog$func_quote_for_eval_result" + + # We need to accept at least all the BSD install flags. + dest= + files= + opts= + prev= + install_type= + isdir=no + stripme= + for arg + do + if test -n "$dest"; then + files="$files $dest" + dest=$arg + continue + fi + + case $arg in + -d) isdir=yes ;; + -f) + case " $install_prog " in + *[\\\ /]cp\ *) ;; + *) prev=$arg ;; + esac + ;; + -g | -m | -o) + prev=$arg + ;; + -s) + stripme=" -s" + continue + ;; + -*) + ;; + *) + # If the previous option needed an argument, then skip it. + if test -n "$prev"; then + prev= + else + dest=$arg + continue + fi + ;; + esac + + # Aesthetically quote the argument. + func_quote_for_eval "$arg" + install_prog="$install_prog $func_quote_for_eval_result" + done + + test -z "$install_prog" && \ + func_fatal_help "you must specify an install program" + + test -n "$prev" && \ + func_fatal_help "the \`$prev' option requires an argument" + + if test -z "$files"; then + if test -z "$dest"; then + func_fatal_help "no file or destination specified" + else + func_fatal_help "you must specify a destination" + fi + fi + + # Strip any trailing slash from the destination. + func_stripname '' '/' "$dest" + dest=$func_stripname_result + + # Check to see that the destination is a directory. + test -d "$dest" && isdir=yes + if test "$isdir" = yes; then + destdir="$dest" + destname= + else + func_dirname_and_basename "$dest" "" "." + destdir="$func_dirname_result" + destname="$func_basename_result" + + # Not a directory, so check to see that there is only one file specified. + set dummy $files; shift + test "$#" -gt 1 && \ + func_fatal_help "\`$dest' is not a directory" + fi + case $destdir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + for file in $files; do + case $file in + *.lo) ;; + *) + func_fatal_help "\`$destdir' must be an absolute directory name" + ;; + esac + done + ;; + esac + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + staticlibs= + future_libdirs= + current_libdirs= + for file in $files; do + + # Do each installation. + case $file in + *.$libext) + # Do the static libraries later. + staticlibs="$staticlibs $file" + ;; + + *.la) + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "\`$file' is not a valid libtool archive" + + library_names= + old_library= + relink_command= + func_source "$file" + + # Add the libdir to current_libdirs if it is the destination. + if test "X$destdir" = "X$libdir"; then + case "$current_libdirs " in + *" $libdir "*) ;; + *) current_libdirs="$current_libdirs $libdir" ;; + esac + else + # Note the libdir as a future libdir. + case "$future_libdirs " in + *" $libdir "*) ;; + *) future_libdirs="$future_libdirs $libdir" ;; + esac + fi + + func_dirname "$file" "/" "" + dir="$func_dirname_result" + dir="$dir$objdir" + + if test -n "$relink_command"; then + # Determine the prefix the user has applied to our future dir. + inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"` + + # Don't allow the user to place us outside of our expected + # location b/c this prevents finding dependent libraries that + # are installed to the same prefix. + # At present, this check doesn't affect windows .dll's that + # are installed into $libdir/../bin (currently, that works fine) + # but it's something to keep an eye on. + test "$inst_prefix_dir" = "$destdir" && \ + func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" + + if test -n "$inst_prefix_dir"; then + # Stick the inst_prefix_dir data into the link command. + relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` + else + relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%%"` + fi + + func_warning "relinking \`$file'" + func_show_eval "$relink_command" \ + 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' + fi + + # See the names of the shared library. + set dummy $library_names; shift + if test -n "$1"; then + realname="$1" + shift + + srcname="$realname" + test -n "$relink_command" && srcname="$realname"T + + # Install the shared library and build the symlinks. + func_show_eval "$install_prog $dir/$srcname $destdir/$realname" \ + 'exit $?' + tstripme="$stripme" + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + case $realname in + *.dll.a) + tstripme="" + ;; + esac + ;; + esac + if test -n "$tstripme" && test -n "$striplib"; then + func_show_eval "$striplib $destdir/$realname" 'exit $?' + fi + + if test "$#" -gt 0; then + # Delete the old symlinks, and create new ones. + # Try `ln -sf' first, because the `ln' binary might depend on + # the symlink we replace! Solaris /bin/ln does not understand -f, + # so we also need to try rm && ln -s. + for linkname + do + test "$linkname" != "$realname" \ + && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" + done + fi + + # Do each command in the postinstall commands. + lib="$destdir/$realname" + func_execute_cmds "$postinstall_cmds" 'exit $?' + fi + + # Install the pseudo-library for information purposes. + func_basename "$file" + name="$func_basename_result" + instname="$dir/$name"i + func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' + + # Maybe install the static library, too. + test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library" + ;; + + *.lo) + # Install (i.e. copy) a libtool object. + + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + func_basename "$file" + destfile="$func_basename_result" + destfile="$destdir/$destfile" + fi + + # Deduce the name of the destination old-style object file. + case $destfile in + *.lo) + func_lo2o "$destfile" + staticdest=$func_lo2o_result + ;; + *.$objext) + staticdest="$destfile" + destfile= + ;; + *) + func_fatal_help "cannot copy a libtool object to \`$destfile'" + ;; + esac + + # Install the libtool object if requested. + test -n "$destfile" && \ + func_show_eval "$install_prog $file $destfile" 'exit $?' + + # Install the old object if enabled. + if test "$build_old_libs" = yes; then + # Deduce the name of the old-style object file. + func_lo2o "$file" + staticobj=$func_lo2o_result + func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' + fi + exit $EXIT_SUCCESS + ;; + + *) + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + func_basename "$file" + destfile="$func_basename_result" + destfile="$destdir/$destfile" + fi + + # If the file is missing, and there is a .exe on the end, strip it + # because it is most likely a libtool script we actually want to + # install + stripped_ext="" + case $file in + *.exe) + if test ! -f "$file"; then + func_stripname '' '.exe' "$file" + file=$func_stripname_result + stripped_ext=".exe" + fi + ;; + esac + + # Do a test to see if this is really a libtool program. + case $host in + *cygwin* | *mingw*) + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + wrapper=$func_ltwrapper_scriptname_result + else + func_stripname '' '.exe' "$file" + wrapper=$func_stripname_result + fi + ;; + *) + wrapper=$file + ;; + esac + if func_ltwrapper_script_p "$wrapper"; then + notinst_deplibs= + relink_command= + + func_source "$wrapper" + + # Check the variables that should have been set. + test -z "$generated_by_libtool_version" && \ + func_fatal_error "invalid libtool wrapper script \`$wrapper'" + + finalize=yes + for lib in $notinst_deplibs; do + # Check to see that each library is installed. + libdir= + if test -f "$lib"; then + func_source "$lib" + fi + libfile="$libdir/"`$ECHO "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test + if test -n "$libdir" && test ! -f "$libfile"; then + func_warning "\`$lib' has not been installed in \`$libdir'" + finalize=no + fi + done + + relink_command= + func_source "$wrapper" + + outputname= + if test "$fast_install" = no && test -n "$relink_command"; then + $opt_dry_run || { + if test "$finalize" = yes; then + tmpdir=`func_mktempdir` + func_basename "$file$stripped_ext" + file="$func_basename_result" + outputname="$tmpdir/$file" + # Replace the output file specification. + relink_command=`$ECHO "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` + + $opt_silent || { + func_quote_for_expand "$relink_command" + eval "func_echo $func_quote_for_expand_result" + } + if eval "$relink_command"; then : + else + func_error "error: relink \`$file' with the above command before installing it" + $opt_dry_run || ${RM}r "$tmpdir" + continue + fi + file="$outputname" + else + func_warning "cannot relink \`$file'" + fi + } + else + # Install the binary that we compiled earlier. + file=`$ECHO "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"` + fi + fi + + # remove .exe since cygwin /usr/bin/install will append another + # one anyway + case $install_prog,$host in + */usr/bin/install*,*cygwin*) + case $file:$destfile in + *.exe:*.exe) + # this is ok + ;; + *.exe:*) + destfile=$destfile.exe + ;; + *:*.exe) + func_stripname '' '.exe' "$destfile" + destfile=$func_stripname_result + ;; + esac + ;; + esac + func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' + $opt_dry_run || if test -n "$outputname"; then + ${RM}r "$tmpdir" + fi + ;; + esac + done + + for file in $staticlibs; do + func_basename "$file" + name="$func_basename_result" + + # Set up the ranlib parameters. + oldlib="$destdir/$name" + + func_show_eval "$install_prog \$file \$oldlib" 'exit $?' + + if test -n "$stripme" && test -n "$old_striplib"; then + func_show_eval "$old_striplib $oldlib" 'exit $?' + fi + + # Do each command in the postinstall commands. + func_execute_cmds "$old_postinstall_cmds" 'exit $?' + done + + test -n "$future_libdirs" && \ + func_warning "remember to run \`$progname --finish$future_libdirs'" + + if test -n "$current_libdirs"; then + # Maybe just do a dry run. + $opt_dry_run && current_libdirs=" -n$current_libdirs" + exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' + else + exit $EXIT_SUCCESS + fi +} + +test "$mode" = install && func_mode_install ${1+"$@"} + + +# func_generate_dlsyms outputname originator pic_p +# Extract symbols from dlprefiles and create ${outputname}S.o with +# a dlpreopen symbol table. +func_generate_dlsyms () +{ + $opt_debug + my_outputname="$1" + my_originator="$2" + my_pic_p="${3-no}" + my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` + my_dlsyms= + + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + if test -n "$NM" && test -n "$global_symbol_pipe"; then + my_dlsyms="${my_outputname}S.c" + else + func_error "not configured to extract global symbols from dlpreopened files" + fi + fi + + if test -n "$my_dlsyms"; then + case $my_dlsyms in + "") ;; + *.c) + # Discover the nlist of each of the dlfiles. + nlist="$output_objdir/${my_outputname}.nm" + + func_show_eval "$RM $nlist ${nlist}S ${nlist}T" + + # Parse the name list into a source file. + func_verbose "creating $output_objdir/$my_dlsyms" + + $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ +/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ +/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ + +#ifdef __cplusplus +extern \"C\" { +#endif + +/* External symbol declarations for the compiler. */\ +" + + if test "$dlself" = yes; then + func_verbose "generating symbol list for \`$output'" + + $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" + + # Add our own program objects to the symbol list. + progfiles=`$ECHO "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + for progfile in $progfiles; do + func_verbose "extracting global C symbols from \`$progfile'" + $opt_dry_run || eval "$NM $progfile | $global_symbol_pipe >> '$nlist'" + done + + if test -n "$exclude_expsyms"; then + $opt_dry_run || { + eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + if test -n "$export_symbols_regex"; then + $opt_dry_run || { + eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + export_symbols="$output_objdir/$outputname.exp" + $opt_dry_run || { + $RM $export_symbols + eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' + case $host in + *cygwin* | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' + ;; + esac + } + else + $opt_dry_run || { + eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' + eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + case $host in + *cygwin | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' + ;; + esac + } + fi + fi + + for dlprefile in $dlprefiles; do + func_verbose "extracting global C symbols from \`$dlprefile'" + func_basename "$dlprefile" + name="$func_basename_result" + $opt_dry_run || { + eval '$ECHO ": $name " >> "$nlist"' + eval "$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'" + } + done + + $opt_dry_run || { + # Make sure we have at least an empty file. + test -f "$nlist" || : > "$nlist" + + if test -n "$exclude_expsyms"; then + $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T + $MV "$nlist"T "$nlist" + fi + + # Try sorting and uniquifying the output. + if $GREP -v "^: " < "$nlist" | + if sort -k 3 /dev/null 2>&1; then + sort -k 3 + else + sort +2 + fi | + uniq > "$nlist"S; then + : + else + $GREP -v "^: " < "$nlist" > "$nlist"S + fi + + if test -f "$nlist"S; then + eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' + else + $ECHO '/* NONE */' >> "$output_objdir/$my_dlsyms" + fi + + $ECHO >> "$output_objdir/$my_dlsyms" "\ + +/* The mapping between symbol names and symbols. */ +typedef struct { + const char *name; + void *address; +} lt_dlsymlist; +" + case $host in + *cygwin* | *mingw* | *cegcc* ) + $ECHO >> "$output_objdir/$my_dlsyms" "\ +/* DATA imports from DLLs on WIN32 con't be const, because + runtime relocations are performed -- see ld's documentation + on pseudo-relocs. */" + lt_dlsym_const= ;; + *osf5*) + echo >> "$output_objdir/$my_dlsyms" "\ +/* This system does not cope well with relocations in const data */" + lt_dlsym_const= ;; + *) + lt_dlsym_const=const ;; + esac + + $ECHO >> "$output_objdir/$my_dlsyms" "\ +extern $lt_dlsym_const lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[]; +$lt_dlsym_const lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[] = +{\ + { \"$my_originator\", (void *) 0 }," + + case $need_lib_prefix in + no) + eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + *) + eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + esac + $ECHO >> "$output_objdir/$my_dlsyms" "\ + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt_${my_prefix}_LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif\ +" + } # !$opt_dry_run + + pic_flag_for_symtable= + case "$compile_command " in + *" -static "*) ;; + *) + case $host in + # compiling the symbol table file with pic_flag works around + # a FreeBSD bug that causes programs to crash when -lm is + # linked before any other PIC object. But we must not use + # pic_flag when linking with -static. The problem exists in + # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. + *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) + pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; + *-*-hpux*) + pic_flag_for_symtable=" $pic_flag" ;; + *) + if test "X$my_pic_p" != Xno; then + pic_flag_for_symtable=" $pic_flag" + fi + ;; + esac + ;; + esac + symtab_cflags= + for arg in $LTCFLAGS; do + case $arg in + -pie | -fpie | -fPIE) ;; + *) symtab_cflags="$symtab_cflags $arg" ;; + esac + done + + # Now compile the dynamic symbol file. + func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' + + # Clean up the generated files. + func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' + + # Transform the symbol file into the correct name. + symfileobj="$output_objdir/${my_outputname}S.$objext" + case $host in + *cygwin* | *mingw* | *cegcc* ) + if test -f "$output_objdir/$my_outputname.def"; then + compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + else + compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` + fi + ;; + *) + compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` + ;; + esac + ;; + *) + func_fatal_error "unknown suffix for \`$my_dlsyms'" + ;; + esac + else + # We keep going just in case the user didn't refer to + # lt_preloaded_symbols. The linker will fail if global_symbol_pipe + # really was required. + + # Nullify the symbol file. + compile_command=`$ECHO "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` + finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` + fi +} + +# func_win32_libid arg +# return the library type of file 'arg' +# +# Need a lot of goo to handle *both* DLLs and import libs +# Has to be a shell function in order to 'eat' the argument +# that is supplied when $file_magic_command is called. +func_win32_libid () +{ + $opt_debug + win32_libid_type="unknown" + win32_fileres=`file -L $1 2>/dev/null` + case $win32_fileres in + *ar\ archive\ import\ library*) # definitely import + win32_libid_type="x86 archive import" + ;; + *ar\ archive*) # could be an import, or static + if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | + $EGREP 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then + win32_nmres=`eval $NM -f posix -A $1 | + $SED -n -e ' + 1,100{ + / I /{ + s,.*,import, + p + q + } + }'` + case $win32_nmres in + import*) win32_libid_type="x86 archive import";; + *) win32_libid_type="x86 archive static";; + esac + fi + ;; + *DLL*) + win32_libid_type="x86 DLL" + ;; + *executable*) # but shell scripts are "executable" too... + case $win32_fileres in + *MS\ Windows\ PE\ Intel*) + win32_libid_type="x86 DLL" + ;; + esac + ;; + esac + $ECHO "$win32_libid_type" +} + + + +# func_extract_an_archive dir oldlib +func_extract_an_archive () +{ + $opt_debug + f_ex_an_ar_dir="$1"; shift + f_ex_an_ar_oldlib="$1" + func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" 'exit $?' + if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then + : + else + func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" + fi +} + + +# func_extract_archives gentop oldlib ... +func_extract_archives () +{ + $opt_debug + my_gentop="$1"; shift + my_oldlibs=${1+"$@"} + my_oldobjs="" + my_xlib="" + my_xabs="" + my_xdir="" + + for my_xlib in $my_oldlibs; do + # Extract the objects. + case $my_xlib in + [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; + *) my_xabs=`pwd`"/$my_xlib" ;; + esac + func_basename "$my_xlib" + my_xlib="$func_basename_result" + my_xlib_u=$my_xlib + while :; do + case " $extracted_archives " in + *" $my_xlib_u "*) + func_arith $extracted_serial + 1 + extracted_serial=$func_arith_result + my_xlib_u=lt$extracted_serial-$my_xlib ;; + *) break ;; + esac + done + extracted_archives="$extracted_archives $my_xlib_u" + my_xdir="$my_gentop/$my_xlib_u" + + func_mkdir_p "$my_xdir" + + case $host in + *-darwin*) + func_verbose "Extracting $my_xabs" + # Do not bother doing anything if just a dry run + $opt_dry_run || { + darwin_orig_dir=`pwd` + cd $my_xdir || exit $? + darwin_archive=$my_xabs + darwin_curdir=`pwd` + darwin_base_archive=`basename "$darwin_archive"` + darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` + if test -n "$darwin_arches"; then + darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` + darwin_arch= + func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" + for darwin_arch in $darwin_arches ; do + func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" + $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" + cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" + func_extract_an_archive "`pwd`" "${darwin_base_archive}" + cd "$darwin_curdir" + $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" + done # $darwin_arches + ## Okay now we've a bunch of thin objects, gotta fatten them up :) + darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` + darwin_file= + darwin_files= + for darwin_file in $darwin_filelist; do + darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP` + $LIPO -create -output "$darwin_file" $darwin_files + done # $darwin_filelist + $RM -rf unfat-$$ + cd "$darwin_orig_dir" + else + cd $darwin_orig_dir + func_extract_an_archive "$my_xdir" "$my_xabs" + fi # $darwin_arches + } # !$opt_dry_run + ;; + *) + func_extract_an_archive "$my_xdir" "$my_xabs" + ;; + esac + my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` + done + + func_extract_archives_result="$my_oldobjs" +} + + + +# func_emit_wrapper_part1 [arg=no] +# +# Emit the first part of a libtool wrapper script on stdout. +# For more information, see the description associated with +# func_emit_wrapper(), below. +func_emit_wrapper_part1 () +{ + func_emit_wrapper_part1_arg1=no + if test -n "$1" ; then + func_emit_wrapper_part1_arg1=$1 + fi + + $ECHO "\ +#! $SHELL + +# $output - temporary wrapper script for $objdir/$outputname +# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION +# +# The $output program cannot be directly executed until all the libtool +# libraries that it depends on are installed. +# +# This wrapper script should never be moved out of the build directory. +# If it is, it will not operate correctly. + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed='${SED} -e 1s/^X//' +sed_quote_subst='$sed_quote_subst' + +# Be Bourne compatible +if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac +fi +BIN_SH=xpg4; export BIN_SH # for Tru64 +DUALCASE=1; export DUALCASE # for MKS sh + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +relink_command=\"$relink_command\" + +# This environment variable determines our operation mode. +if test \"\$libtool_install_magic\" = \"$magic\"; then + # install mode needs the following variables: + generated_by_libtool_version='$macro_version' + notinst_deplibs='$notinst_deplibs' +else + # When we are sourced in execute mode, \$file and \$ECHO are already set. + if test \"\$libtool_execute_magic\" != \"$magic\"; then + ECHO=\"$qecho\" + file=\"\$0\" + # Make sure echo works. + if test \"X\$1\" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift + elif test \"X\`{ \$ECHO '\t'; } 2>/dev/null\`\" = 'X\t'; then + # Yippee, \$ECHO works! + : + else + # Restart under the correct shell, and then maybe \$ECHO will work. + exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"} + fi + fi\ +" + $ECHO "\ + + # Find the directory that this script lives in. + thisdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\` + test \"x\$thisdir\" = \"x\$file\" && thisdir=. + + # Follow symbolic links until we get to the real thisdir. + file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\` + while test -n \"\$file\"; do + destdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\` + + # If there was a directory component, then change thisdir. + if test \"x\$destdir\" != \"x\$file\"; then + case \"\$destdir\" in + [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; + *) thisdir=\"\$thisdir/\$destdir\" ;; + esac + fi + + file=\`\$ECHO \"X\$file\" | \$Xsed -e 's%^.*/%%'\` + file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\` + done +" +} +# end: func_emit_wrapper_part1 + +# func_emit_wrapper_part2 [arg=no] +# +# Emit the second part of a libtool wrapper script on stdout. +# For more information, see the description associated with +# func_emit_wrapper(), below. +func_emit_wrapper_part2 () +{ + func_emit_wrapper_part2_arg1=no + if test -n "$1" ; then + func_emit_wrapper_part2_arg1=$1 + fi + + $ECHO "\ + + # Usually 'no', except on cygwin/mingw when embedded into + # the cwrapper. + WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_part2_arg1 + if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then + # special case for '.' + if test \"\$thisdir\" = \".\"; then + thisdir=\`pwd\` + fi + # remove .libs from thisdir + case \"\$thisdir\" in + *[\\\\/]$objdir ) thisdir=\`\$ECHO \"X\$thisdir\" | \$Xsed -e 's%[\\\\/][^\\\\/]*$%%'\` ;; + $objdir ) thisdir=. ;; + esac + fi + + # Try to get the absolute directory name. + absdir=\`cd \"\$thisdir\" && pwd\` + test -n \"\$absdir\" && thisdir=\"\$absdir\" +" + + if test "$fast_install" = yes; then + $ECHO "\ + program=lt-'$outputname'$exeext + progdir=\"\$thisdir/$objdir\" + + if test ! -f \"\$progdir/\$program\" || + { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ + test \"X\$file\" != \"X\$progdir/\$program\"; }; then + + file=\"\$\$-\$program\" + + if test ! -d \"\$progdir\"; then + $MKDIR \"\$progdir\" + else + $RM \"\$progdir/\$file\" + fi" + + $ECHO "\ + + # relink executable if necessary + if test -n \"\$relink_command\"; then + if relink_command_output=\`eval \$relink_command 2>&1\`; then : + else + $ECHO \"\$relink_command_output\" >&2 + $RM \"\$progdir/\$file\" + exit 1 + fi + fi + + $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || + { $RM \"\$progdir/\$program\"; + $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } + $RM \"\$progdir/\$file\" + fi" + else + $ECHO "\ + program='$outputname' + progdir=\"\$thisdir/$objdir\" +" + fi + + $ECHO "\ + + if test -f \"\$progdir/\$program\"; then" + + # Export our shlibpath_var if we have one. + if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then + $ECHO "\ + # Add our own library path to $shlibpath_var + $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" + + # Some systems cannot cope with colon-terminated $shlibpath_var + # The second colon is a workaround for a bug in BeOS R4 sed + $shlibpath_var=\`\$ECHO \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\` + + export $shlibpath_var +" + fi + + # fixup the dll searchpath if we need to. + if test -n "$dllsearchpath"; then + $ECHO "\ + # Add the dll search path components to the executable PATH + PATH=$dllsearchpath:\$PATH +" + fi + + $ECHO "\ + if test \"\$libtool_execute_magic\" != \"$magic\"; then + # Run the actual program with our arguments. +" + case $host in + # Backslashes separate directories on plain windows + *-*-mingw | *-*-os2* | *-cegcc*) + $ECHO "\ + exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} +" + ;; + + *) + $ECHO "\ + exec \"\$progdir/\$program\" \${1+\"\$@\"} +" + ;; + esac + $ECHO "\ + \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 + exit 1 + fi + else + # The program doesn't exist. + \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 + \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 + $ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 + exit 1 + fi +fi\ +" +} +# end: func_emit_wrapper_part2 + + +# func_emit_wrapper [arg=no] +# +# Emit a libtool wrapper script on stdout. +# Don't directly open a file because we may want to +# incorporate the script contents within a cygwin/mingw +# wrapper executable. Must ONLY be called from within +# func_mode_link because it depends on a number of variables +# set therein. +# +# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR +# variable will take. If 'yes', then the emitted script +# will assume that the directory in which it is stored is +# the $objdir directory. This is a cygwin/mingw-specific +# behavior. +func_emit_wrapper () +{ + func_emit_wrapper_arg1=no + if test -n "$1" ; then + func_emit_wrapper_arg1=$1 + fi + + # split this up so that func_emit_cwrapperexe_src + # can call each part independently. + func_emit_wrapper_part1 "${func_emit_wrapper_arg1}" + func_emit_wrapper_part2 "${func_emit_wrapper_arg1}" +} + + +# func_to_host_path arg +# +# Convert paths to host format when used with build tools. +# Intended for use with "native" mingw (where libtool itself +# is running under the msys shell), or in the following cross- +# build environments: +# $build $host +# mingw (msys) mingw [e.g. native] +# cygwin mingw +# *nix + wine mingw +# where wine is equipped with the `winepath' executable. +# In the native mingw case, the (msys) shell automatically +# converts paths for any non-msys applications it launches, +# but that facility isn't available from inside the cwrapper. +# Similar accommodations are necessary for $host mingw and +# $build cygwin. Calling this function does no harm for other +# $host/$build combinations not listed above. +# +# ARG is the path (on $build) that should be converted to +# the proper representation for $host. The result is stored +# in $func_to_host_path_result. +func_to_host_path () +{ + func_to_host_path_result="$1" + if test -n "$1" ; then + case $host in + *mingw* ) + lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' + case $build in + *mingw* ) # actually, msys + # awkward: cmd appends spaces to result + lt_sed_strip_trailing_spaces="s/[ ]*\$//" + func_to_host_path_tmp1=`( cmd //c echo "$1" |\ + $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""` + func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ + $SED -e "$lt_sed_naive_backslashify"` + ;; + *cygwin* ) + func_to_host_path_tmp1=`cygpath -w "$1"` + func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ + $SED -e "$lt_sed_naive_backslashify"` + ;; + * ) + # Unfortunately, winepath does not exit with a non-zero + # error code, so we are forced to check the contents of + # stdout. On the other hand, if the command is not + # found, the shell will set an exit code of 127 and print + # *an error message* to stdout. So we must check for both + # error code of zero AND non-empty stdout, which explains + # the odd construction: + func_to_host_path_tmp1=`winepath -w "$1" 2>/dev/null` + if test "$?" -eq 0 && test -n "${func_to_host_path_tmp1}"; then + func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\ + $SED -e "$lt_sed_naive_backslashify"` + else + # Allow warning below. + func_to_host_path_result="" + fi + ;; + esac + if test -z "$func_to_host_path_result" ; then + func_error "Could not determine host path corresponding to" + func_error " '$1'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback: + func_to_host_path_result="$1" + fi + ;; + esac + fi +} +# end: func_to_host_path + +# func_to_host_pathlist arg +# +# Convert pathlists to host format when used with build tools. +# See func_to_host_path(), above. This function supports the +# following $build/$host combinations (but does no harm for +# combinations not listed here): +# $build $host +# mingw (msys) mingw [e.g. native] +# cygwin mingw +# *nix + wine mingw +# +# Path separators are also converted from $build format to +# $host format. If ARG begins or ends with a path separator +# character, it is preserved (but converted to $host format) +# on output. +# +# ARG is a pathlist (on $build) that should be converted to +# the proper representation on $host. The result is stored +# in $func_to_host_pathlist_result. +func_to_host_pathlist () +{ + func_to_host_pathlist_result="$1" + if test -n "$1" ; then + case $host in + *mingw* ) + lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' + # Remove leading and trailing path separator characters from + # ARG. msys behavior is inconsistent here, cygpath turns them + # into '.;' and ';.', and winepath ignores them completely. + func_to_host_pathlist_tmp2="$1" + # Once set for this call, this variable should not be + # reassigned. It is used in tha fallback case. + func_to_host_pathlist_tmp1=`echo "$func_to_host_pathlist_tmp2" |\ + $SED -e 's|^:*||' -e 's|:*$||'` + case $build in + *mingw* ) # Actually, msys. + # Awkward: cmd appends spaces to result. + lt_sed_strip_trailing_spaces="s/[ ]*\$//" + func_to_host_pathlist_tmp2=`( cmd //c echo "$func_to_host_pathlist_tmp1" |\ + $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""` + func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\ + $SED -e "$lt_sed_naive_backslashify"` + ;; + *cygwin* ) + func_to_host_pathlist_tmp2=`cygpath -w -p "$func_to_host_pathlist_tmp1"` + func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\ + $SED -e "$lt_sed_naive_backslashify"` + ;; + * ) + # unfortunately, winepath doesn't convert pathlists + func_to_host_pathlist_result="" + func_to_host_pathlist_oldIFS=$IFS + IFS=: + for func_to_host_pathlist_f in $func_to_host_pathlist_tmp1 ; do + IFS=$func_to_host_pathlist_oldIFS + if test -n "$func_to_host_pathlist_f" ; then + func_to_host_path "$func_to_host_pathlist_f" + if test -n "$func_to_host_path_result" ; then + if test -z "$func_to_host_pathlist_result" ; then + func_to_host_pathlist_result="$func_to_host_path_result" + else + func_to_host_pathlist_result="$func_to_host_pathlist_result;$func_to_host_path_result" + fi + fi + fi + IFS=: + done + IFS=$func_to_host_pathlist_oldIFS + ;; + esac + if test -z "$func_to_host_pathlist_result" ; then + func_error "Could not determine the host path(s) corresponding to" + func_error " '$1'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback. This may break if $1 contains DOS-style drive + # specifications. The fix is not to complicate the expression + # below, but for the user to provide a working wine installation + # with winepath so that path translation in the cross-to-mingw + # case works properly. + lt_replace_pathsep_nix_to_dos="s|:|;|g" + func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp1" |\ + $SED -e "$lt_replace_pathsep_nix_to_dos"` + fi + # Now, add the leading and trailing path separators back + case "$1" in + :* ) func_to_host_pathlist_result=";$func_to_host_pathlist_result" + ;; + esac + case "$1" in + *: ) func_to_host_pathlist_result="$func_to_host_pathlist_result;" + ;; + esac + ;; + esac + fi +} +# end: func_to_host_pathlist + +# func_emit_cwrapperexe_src +# emit the source code for a wrapper executable on stdout +# Must ONLY be called from within func_mode_link because +# it depends on a number of variable set therein. +func_emit_cwrapperexe_src () +{ + cat < +#include +#ifdef _MSC_VER +# include +# include +# include +# define setmode _setmode +#else +# include +# include +# ifdef __CYGWIN__ +# include +# define HAVE_SETENV +# ifdef __STRICT_ANSI__ +char *realpath (const char *, char *); +int putenv (char *); +int setenv (const char *, const char *, int); +# endif +# endif +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(PATH_MAX) +# define LT_PATHMAX PATH_MAX +#elif defined(MAXPATHLEN) +# define LT_PATHMAX MAXPATHLEN +#else +# define LT_PATHMAX 1024 +#endif + +#ifndef S_IXOTH +# define S_IXOTH 0 +#endif +#ifndef S_IXGRP +# define S_IXGRP 0 +#endif + +#ifdef _MSC_VER +# define S_IXUSR _S_IEXEC +# define stat _stat +# ifndef _INTPTR_T_DEFINED +# define intptr_t int +# endif +#endif + +#ifndef DIR_SEPARATOR +# define DIR_SEPARATOR '/' +# define PATH_SEPARATOR ':' +#endif + +#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ + defined (__OS2__) +# define HAVE_DOS_BASED_FILE_SYSTEM +# define FOPEN_WB "wb" +# ifndef DIR_SEPARATOR_2 +# define DIR_SEPARATOR_2 '\\' +# endif +# ifndef PATH_SEPARATOR_2 +# define PATH_SEPARATOR_2 ';' +# endif +#endif + +#ifndef DIR_SEPARATOR_2 +# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) +#else /* DIR_SEPARATOR_2 */ +# define IS_DIR_SEPARATOR(ch) \ + (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) +#endif /* DIR_SEPARATOR_2 */ + +#ifndef PATH_SEPARATOR_2 +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) +#else /* PATH_SEPARATOR_2 */ +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) +#endif /* PATH_SEPARATOR_2 */ + +#ifdef __CYGWIN__ +# define FOPEN_WB "wb" +#endif + +#ifndef FOPEN_WB +# define FOPEN_WB "w" +#endif +#ifndef _O_BINARY +# define _O_BINARY 0 +#endif + +#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) +#define XFREE(stale) do { \ + if (stale) { free ((void *) stale); stale = 0; } \ +} while (0) + +#undef LTWRAPPER_DEBUGPRINTF +#if defined DEBUGWRAPPER +# define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args +static void +ltwrapper_debugprintf (const char *fmt, ...) +{ + va_list args; + va_start (args, fmt); + (void) vfprintf (stderr, fmt, args); + va_end (args); +} +#else +# define LTWRAPPER_DEBUGPRINTF(args) +#endif + +const char *program_name = NULL; + +void *xmalloc (size_t num); +char *xstrdup (const char *string); +const char *base_name (const char *name); +char *find_executable (const char *wrapper); +char *chase_symlinks (const char *pathspec); +int make_executable (const char *path); +int check_executable (const char *path); +char *strendzap (char *str, const char *pat); +void lt_fatal (const char *message, ...); +void lt_setenv (const char *name, const char *value); +char *lt_extend_str (const char *orig_value, const char *add, int to_end); +void lt_opt_process_env_set (const char *arg); +void lt_opt_process_env_prepend (const char *arg); +void lt_opt_process_env_append (const char *arg); +int lt_split_name_value (const char *arg, char** name, char** value); +void lt_update_exe_path (const char *name, const char *value); +void lt_update_lib_path (const char *name, const char *value); + +static const char *script_text_part1 = +EOF + + func_emit_wrapper_part1 yes | + $SED -e 's/\([\\"]\)/\\\1/g' \ + -e 's/^/ "/' -e 's/$/\\n"/' + echo ";" + cat <"))); + for (i = 0; i < newargc; i++) + { + LTWRAPPER_DEBUGPRINTF (("(main) newargz[%d] : %s\n", i, (newargz[i] ? newargz[i] : ""))); + } + +EOF + + case $host_os in + mingw*) + cat <<"EOF" + /* execv doesn't actually work on mingw as expected on unix */ + rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz); + if (rval == -1) + { + /* failed to start process */ + LTWRAPPER_DEBUGPRINTF (("(main) failed to launch target \"%s\": errno = %d\n", lt_argv_zero, errno)); + return 127; + } + return rval; +EOF + ;; + *) + cat <<"EOF" + execv (lt_argv_zero, newargz); + return rval; /* =127, but avoids unused variable warning */ +EOF + ;; + esac + + cat <<"EOF" +} + +void * +xmalloc (size_t num) +{ + void *p = (void *) malloc (num); + if (!p) + lt_fatal ("Memory exhausted"); + + return p; +} + +char * +xstrdup (const char *string) +{ + return string ? strcpy ((char *) xmalloc (strlen (string) + 1), + string) : NULL; +} + +const char * +base_name (const char *name) +{ + const char *base; + +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + /* Skip over the disk name in MSDOS pathnames. */ + if (isalpha ((unsigned char) name[0]) && name[1] == ':') + name += 2; +#endif + + for (base = name; *name; name++) + if (IS_DIR_SEPARATOR (*name)) + base = name + 1; + return base; +} + +int +check_executable (const char *path) +{ + struct stat st; + + LTWRAPPER_DEBUGPRINTF (("(check_executable) : %s\n", + path ? (*path ? path : "EMPTY!") : "NULL!")); + if ((!path) || (!*path)) + return 0; + + if ((stat (path, &st) >= 0) + && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) + return 1; + else + return 0; +} + +int +make_executable (const char *path) +{ + int rval = 0; + struct stat st; + + LTWRAPPER_DEBUGPRINTF (("(make_executable) : %s\n", + path ? (*path ? path : "EMPTY!") : "NULL!")); + if ((!path) || (!*path)) + return 0; + + if (stat (path, &st) >= 0) + { + rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); + } + return rval; +} + +/* Searches for the full path of the wrapper. Returns + newly allocated full path name if found, NULL otherwise + Does not chase symlinks, even on platforms that support them. +*/ +char * +find_executable (const char *wrapper) +{ + int has_slash = 0; + const char *p; + const char *p_next; + /* static buffer for getcwd */ + char tmp[LT_PATHMAX + 1]; + int tmp_len; + char *concat_name; + + LTWRAPPER_DEBUGPRINTF (("(find_executable) : %s\n", + wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!")); + + if ((wrapper == NULL) || (*wrapper == '\0')) + return NULL; + + /* Absolute path? */ +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + else + { +#endif + if (IS_DIR_SEPARATOR (wrapper[0])) + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + } +#endif + + for (p = wrapper; *p; p++) + if (*p == '/') + { + has_slash = 1; + break; + } + if (!has_slash) + { + /* no slashes; search PATH */ + const char *path = getenv ("PATH"); + if (path != NULL) + { + for (p = path; *p; p = p_next) + { + const char *q; + size_t p_len; + for (q = p; *q; q++) + if (IS_PATH_SEPARATOR (*q)) + break; + p_len = q - p; + p_next = (*q == '\0' ? q : q + 1); + if (p_len == 0) + { + /* empty path: current directory */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal ("getcwd failed"); + tmp_len = strlen (tmp); + concat_name = + XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + } + else + { + concat_name = + XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, p, p_len); + concat_name[p_len] = '/'; + strcpy (concat_name + p_len + 1, wrapper); + } + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + } + /* not found in PATH; assume curdir */ + } + /* Relative path | not found in path: prepend cwd */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal ("getcwd failed"); + tmp_len = strlen (tmp); + concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + return NULL; +} + +char * +chase_symlinks (const char *pathspec) +{ +#ifndef S_ISLNK + return xstrdup (pathspec); +#else + char buf[LT_PATHMAX]; + struct stat s; + char *tmp_pathspec = xstrdup (pathspec); + char *p; + int has_symlinks = 0; + while (strlen (tmp_pathspec) && !has_symlinks) + { + LTWRAPPER_DEBUGPRINTF (("checking path component for symlinks: %s\n", + tmp_pathspec)); + if (lstat (tmp_pathspec, &s) == 0) + { + if (S_ISLNK (s.st_mode) != 0) + { + has_symlinks = 1; + break; + } + + /* search backwards for last DIR_SEPARATOR */ + p = tmp_pathspec + strlen (tmp_pathspec) - 1; + while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + p--; + if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + { + /* no more DIR_SEPARATORS left */ + break; + } + *p = '\0'; + } + else + { + char *errstr = strerror (errno); + lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr); + } + } + XFREE (tmp_pathspec); + + if (!has_symlinks) + { + return xstrdup (pathspec); + } + + tmp_pathspec = realpath (pathspec, buf); + if (tmp_pathspec == 0) + { + lt_fatal ("Could not follow symlinks for %s", pathspec); + } + return xstrdup (tmp_pathspec); +#endif +} + +char * +strendzap (char *str, const char *pat) +{ + size_t len, patlen; + + assert (str != NULL); + assert (pat != NULL); + + len = strlen (str); + patlen = strlen (pat); + + if (patlen <= len) + { + str += len - patlen; + if (strcmp (str, pat) == 0) + *str = '\0'; + } + return str; +} + +static void +lt_error_core (int exit_status, const char *mode, + const char *message, va_list ap) +{ + fprintf (stderr, "%s: %s: ", program_name, mode); + vfprintf (stderr, message, ap); + fprintf (stderr, ".\n"); + + if (exit_status >= 0) + exit (exit_status); +} + +void +lt_fatal (const char *message, ...) +{ + va_list ap; + va_start (ap, message); + lt_error_core (EXIT_FAILURE, "FATAL", message, ap); + va_end (ap); +} + +void +lt_setenv (const char *name, const char *value) +{ + LTWRAPPER_DEBUGPRINTF (("(lt_setenv) setting '%s' to '%s'\n", + (name ? name : ""), + (value ? value : ""))); + { +#ifdef HAVE_SETENV + /* always make a copy, for consistency with !HAVE_SETENV */ + char *str = xstrdup (value); + setenv (name, str, 1); +#else + int len = strlen (name) + 1 + strlen (value) + 1; + char *str = XMALLOC (char, len); + sprintf (str, "%s=%s", name, value); + if (putenv (str) != EXIT_SUCCESS) + { + XFREE (str); + } +#endif + } +} + +char * +lt_extend_str (const char *orig_value, const char *add, int to_end) +{ + char *new_value; + if (orig_value && *orig_value) + { + int orig_value_len = strlen (orig_value); + int add_len = strlen (add); + new_value = XMALLOC (char, add_len + orig_value_len + 1); + if (to_end) + { + strcpy (new_value, orig_value); + strcpy (new_value + orig_value_len, add); + } + else + { + strcpy (new_value, add); + strcpy (new_value + add_len, orig_value); + } + } + else + { + new_value = xstrdup (add); + } + return new_value; +} + +int +lt_split_name_value (const char *arg, char** name, char** value) +{ + const char *p; + int len; + if (!arg || !*arg) + return 1; + + p = strchr (arg, (int)'='); + + if (!p) + return 1; + + *value = xstrdup (++p); + + len = strlen (arg) - strlen (*value); + *name = XMALLOC (char, len); + strncpy (*name, arg, len-1); + (*name)[len - 1] = '\0'; + + return 0; +} + +void +lt_opt_process_env_set (const char *arg) +{ + char *name = NULL; + char *value = NULL; + + if (lt_split_name_value (arg, &name, &value) != 0) + { + XFREE (name); + XFREE (value); + lt_fatal ("bad argument for %s: '%s'", env_set_opt, arg); + } + + lt_setenv (name, value); + XFREE (name); + XFREE (value); +} + +void +lt_opt_process_env_prepend (const char *arg) +{ + char *name = NULL; + char *value = NULL; + char *new_value = NULL; + + if (lt_split_name_value (arg, &name, &value) != 0) + { + XFREE (name); + XFREE (value); + lt_fatal ("bad argument for %s: '%s'", env_prepend_opt, arg); + } + + new_value = lt_extend_str (getenv (name), value, 0); + lt_setenv (name, new_value); + XFREE (new_value); + XFREE (name); + XFREE (value); +} + +void +lt_opt_process_env_append (const char *arg) +{ + char *name = NULL; + char *value = NULL; + char *new_value = NULL; + + if (lt_split_name_value (arg, &name, &value) != 0) + { + XFREE (name); + XFREE (value); + lt_fatal ("bad argument for %s: '%s'", env_append_opt, arg); + } + + new_value = lt_extend_str (getenv (name), value, 1); + lt_setenv (name, new_value); + XFREE (new_value); + XFREE (name); + XFREE (value); +} + +void +lt_update_exe_path (const char *name, const char *value) +{ + LTWRAPPER_DEBUGPRINTF (("(lt_update_exe_path) modifying '%s' by prepending '%s'\n", + (name ? name : ""), + (value ? value : ""))); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + /* some systems can't cope with a ':'-terminated path #' */ + int len = strlen (new_value); + while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) + { + new_value[len-1] = '\0'; + } + lt_setenv (name, new_value); + XFREE (new_value); + } +} + +void +lt_update_lib_path (const char *name, const char *value) +{ + LTWRAPPER_DEBUGPRINTF (("(lt_update_lib_path) modifying '%s' by prepending '%s'\n", + (name ? name : ""), + (value ? value : ""))); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + lt_setenv (name, new_value); + XFREE (new_value); + } +} + + +EOF +} +# end: func_emit_cwrapperexe_src + +# func_mode_link arg... +func_mode_link () +{ + $opt_debug + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + # It is impossible to link a dll without this setting, and + # we shouldn't force the makefile maintainer to figure out + # which system we are compiling for in order to pass an extra + # flag for every libtool invocation. + # allow_undefined=no + + # FIXME: Unfortunately, there are problems with the above when trying + # to make a dll which has undefined symbols, in which case not + # even a static library is built. For now, we need to specify + # -no-undefined on the libtool link line when we can be certain + # that all symbols are satisfied, otherwise we get a static library. + allow_undefined=yes + ;; + *) + allow_undefined=yes + ;; + esac + libtool_args=$nonopt + base_compile="$nonopt $@" + compile_command=$nonopt + finalize_command=$nonopt + + compile_rpath= + finalize_rpath= + compile_shlibpath= + finalize_shlibpath= + convenience= + old_convenience= + deplibs= + old_deplibs= + compiler_flags= + linker_flags= + dllsearchpath= + lib_search_path=`pwd` + inst_prefix_dir= + new_inherited_linker_flags= + + avoid_version=no + dlfiles= + dlprefiles= + dlself=no + export_dynamic=no + export_symbols= + export_symbols_regex= + generated= + libobjs= + ltlibs= + module=no + no_install=no + objs= + non_pic_objects= + precious_files_regex= + prefer_static_libs=no + preload=no + prev= + prevarg= + release= + rpath= + xrpath= + perm_rpath= + temp_rpath= + thread_safe=no + vinfo= + vinfo_number=no + weak_libs= + single_module="${wl}-single_module" + func_infer_tag $base_compile + + # We need to know -static, to get the right output filenames. + for arg + do + case $arg in + -shared) + test "$build_libtool_libs" != yes && \ + func_fatal_configuration "can not build a shared library" + build_old_libs=no + break + ;; + -all-static | -static | -static-libtool-libs) + case $arg in + -all-static) + if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then + func_warning "complete static linking is impossible in this configuration" + fi + if test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + -static) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=built + ;; + -static-libtool-libs) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + esac + build_libtool_libs=no + build_old_libs=yes + break + ;; + esac + done + + # See if our shared archives depend on static archives. + test -n "$old_archive_from_new_cmds" && build_old_libs=yes + + # Go through the arguments, transforming them on the way. + while test "$#" -gt 0; do + arg="$1" + shift + func_quote_for_eval "$arg" + qarg=$func_quote_for_eval_unquoted_result + func_append libtool_args " $func_quote_for_eval_result" + + # If the previous option needs an argument, assign it. + if test -n "$prev"; then + case $prev in + output) + func_append compile_command " @OUTPUT@" + func_append finalize_command " @OUTPUT@" + ;; + esac + + case $prev in + dlfiles|dlprefiles) + if test "$preload" = no; then + # Add the symbol object into the linking commands. + func_append compile_command " @SYMFILE@" + func_append finalize_command " @SYMFILE@" + preload=yes + fi + case $arg in + *.la | *.lo) ;; # We handle these cases below. + force) + if test "$dlself" = no; then + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + self) + if test "$prev" = dlprefiles; then + dlself=yes + elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then + dlself=yes + else + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + *) + if test "$prev" = dlfiles; then + dlfiles="$dlfiles $arg" + else + dlprefiles="$dlprefiles $arg" + fi + prev= + continue + ;; + esac + ;; + expsyms) + export_symbols="$arg" + test -f "$arg" \ + || func_fatal_error "symbol file \`$arg' does not exist" + prev= + continue + ;; + expsyms_regex) + export_symbols_regex="$arg" + prev= + continue + ;; + framework) + case $host in + *-*-darwin*) + case "$deplibs " in + *" $qarg.ltframework "*) ;; + *) deplibs="$deplibs $qarg.ltframework" # this is fixed later + ;; + esac + ;; + esac + prev= + continue + ;; + inst_prefix) + inst_prefix_dir="$arg" + prev= + continue + ;; + objectlist) + if test -f "$arg"; then + save_arg=$arg + moreargs= + for fil in `cat "$save_arg"` + do +# moreargs="$moreargs $fil" + arg=$fil + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test "$pic_object" = none && + test "$non_pic_object" = none; then + func_fatal_error "cannot find name of object for \`$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + dlfiles="$dlfiles $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + dlprefiles="$dlprefiles $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object="$pic_object" + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "\`$arg' is not a valid libtool object" + fi + fi + done + else + func_fatal_error "link input file \`$arg' does not exist" + fi + arg=$save_arg + prev= + continue + ;; + precious_regex) + precious_files_regex="$arg" + prev= + continue + ;; + release) + release="-$arg" + prev= + continue + ;; + rpath | xrpath) + # We need an absolute path. + case $arg in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + if test "$prev" = rpath; then + case "$rpath " in + *" $arg "*) ;; + *) rpath="$rpath $arg" ;; + esac + else + case "$xrpath " in + *" $arg "*) ;; + *) xrpath="$xrpath $arg" ;; + esac + fi + prev= + continue + ;; + shrext) + shrext_cmds="$arg" + prev= + continue + ;; + weak) + weak_libs="$weak_libs $arg" + prev= + continue + ;; + xcclinker) + linker_flags="$linker_flags $qarg" + compiler_flags="$compiler_flags $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xcompiler) + compiler_flags="$compiler_flags $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xlinker) + linker_flags="$linker_flags $qarg" + compiler_flags="$compiler_flags $wl$qarg" + prev= + func_append compile_command " $wl$qarg" + func_append finalize_command " $wl$qarg" + continue + ;; + *) + eval "$prev=\"\$arg\"" + prev= + continue + ;; + esac + fi # test -n "$prev" + + prevarg="$arg" + + case $arg in + -all-static) + if test -n "$link_static_flag"; then + # See comment for -static flag below, for more details. + func_append compile_command " $link_static_flag" + func_append finalize_command " $link_static_flag" + fi + continue + ;; + + -allow-undefined) + # FIXME: remove this flag sometime in the future. + func_fatal_error "\`-allow-undefined' must not be used because it is the default" + ;; + + -avoid-version) + avoid_version=yes + continue + ;; + + -dlopen) + prev=dlfiles + continue + ;; + + -dlpreopen) + prev=dlprefiles + continue + ;; + + -export-dynamic) + export_dynamic=yes + continue + ;; + + -export-symbols | -export-symbols-regex) + if test -n "$export_symbols" || test -n "$export_symbols_regex"; then + func_fatal_error "more than one -exported-symbols argument is not allowed" + fi + if test "X$arg" = "X-export-symbols"; then + prev=expsyms + else + prev=expsyms_regex + fi + continue + ;; + + -framework) + prev=framework + continue + ;; + + -inst-prefix-dir) + prev=inst_prefix + continue + ;; + + # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* + # so, if we see these flags be careful not to treat them like -L + -L[A-Z][A-Z]*:*) + case $with_gcc/$host in + no/*-*-irix* | /*-*-irix*) + func_append compile_command " $arg" + func_append finalize_command " $arg" + ;; + esac + continue + ;; + + -L*) + func_stripname '-L' '' "$arg" + dir=$func_stripname_result + if test -z "$dir"; then + if test "$#" -gt 0; then + func_fatal_error "require no space between \`-L' and \`$1'" + else + func_fatal_error "need path for \`-L' option" + fi + fi + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + absdir=`cd "$dir" && pwd` + test -z "$absdir" && \ + func_fatal_error "cannot determine absolute directory name of \`$dir'" + dir="$absdir" + ;; + esac + case "$deplibs " in + *" -L$dir "*) ;; + *) + deplibs="$deplibs -L$dir" + lib_search_path="$lib_search_path $dir" + ;; + esac + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`$ECHO "X$dir" | $Xsed -e 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$dir:"*) ;; + ::) dllsearchpath=$dir;; + *) dllsearchpath="$dllsearchpath:$dir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) dllsearchpath="$dllsearchpath:$testbindir";; + esac + ;; + esac + continue + ;; + + -l*) + if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc*) + # These systems don't actually have a C or math library (as such) + continue + ;; + *-*-os2*) + # These systems don't actually have a C library (as such) + test "X$arg" = "X-lc" && continue + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc due to us having libc/libc_r. + test "X$arg" = "X-lc" && continue + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C and math libraries are in the System framework + deplibs="$deplibs System.ltframework" + continue + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + test "X$arg" = "X-lc" && continue + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + test "X$arg" = "X-lc" && continue + ;; + esac + elif test "X$arg" = "X-lc_r"; then + case $host in + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc_r directly, use -pthread flag. + continue + ;; + esac + fi + deplibs="$deplibs $arg" + continue + ;; + + -module) + module=yes + continue + ;; + + # Tru64 UNIX uses -model [arg] to determine the layout of C++ + # classes, name mangling, and exception handling. + # Darwin uses the -arch flag to determine output architecture. + -model|-arch|-isysroot) + compiler_flags="$compiler_flags $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + prev=xcompiler + continue + ;; + + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) + compiler_flags="$compiler_flags $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + case "$new_inherited_linker_flags " in + *" $arg "*) ;; + * ) new_inherited_linker_flags="$new_inherited_linker_flags $arg" ;; + esac + continue + ;; + + -multi_module) + single_module="${wl}-multi_module" + continue + ;; + + -no-fast-install) + fast_install=no + continue + ;; + + -no-install) + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) + # The PATH hackery in wrapper scripts is required on Windows + # and Darwin in order for the loader to find any dlls it needs. + func_warning "\`-no-install' is ignored for $host" + func_warning "assuming \`-no-fast-install' instead" + fast_install=no + ;; + *) no_install=yes ;; + esac + continue + ;; + + -no-undefined) + allow_undefined=no + continue + ;; + + -objectlist) + prev=objectlist + continue + ;; + + -o) prev=output ;; + + -precious-files-regex) + prev=precious_regex + continue + ;; + + -release) + prev=release + continue + ;; + + -rpath) + prev=rpath + continue + ;; + + -R) + prev=xrpath + continue + ;; + + -R*) + func_stripname '-R' '' "$arg" + dir=$func_stripname_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + case "$xrpath " in + *" $dir "*) ;; + *) xrpath="$xrpath $dir" ;; + esac + continue + ;; + + -shared) + # The effects of -shared are defined in a previous loop. + continue + ;; + + -shrext) + prev=shrext + continue + ;; + + -static | -static-libtool-libs) + # The effects of -static are defined in a previous loop. + # We used to do the same as -all-static on platforms that + # didn't have a PIC flag, but the assumption that the effects + # would be equivalent was wrong. It would break on at least + # Digital Unix and AIX. + continue + ;; + + -thread-safe) + thread_safe=yes + continue + ;; + + -version-info) + prev=vinfo + continue + ;; + + -version-number) + prev=vinfo + vinfo_number=yes + continue + ;; + + -weak) + prev=weak + continue + ;; + + -Wc,*) + func_stripname '-Wc,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + func_quote_for_eval "$flag" + arg="$arg $wl$func_quote_for_eval_result" + compiler_flags="$compiler_flags $func_quote_for_eval_result" + done + IFS="$save_ifs" + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Wl,*) + func_stripname '-Wl,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + func_quote_for_eval "$flag" + arg="$arg $wl$func_quote_for_eval_result" + compiler_flags="$compiler_flags $wl$func_quote_for_eval_result" + linker_flags="$linker_flags $func_quote_for_eval_result" + done + IFS="$save_ifs" + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Xcompiler) + prev=xcompiler + continue + ;; + + -Xlinker) + prev=xlinker + continue + ;; + + -XCClinker) + prev=xcclinker + continue + ;; + + # -msg_* for osf cc + -msg_*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + + # -64, -mips[0-9] enable 64-bit mode on the SGI compiler + # -r[0-9][0-9]* specifies the processor on the SGI compiler + # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler + # +DA*, +DD* enable 64-bit mode on the HP compiler + # -q* pass through compiler args for the IBM compiler + # -m*, -t[45]*, -txscale* pass through architecture-specific + # compiler args for GCC + # -F/path gives path to uninstalled frameworks, gcc on darwin + # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC + # @file GCC response files + -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ + -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + func_append compile_command " $arg" + func_append finalize_command " $arg" + compiler_flags="$compiler_flags $arg" + continue + ;; + + # Some other compiler flag. + -* | +*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + + *.$objext) + # A standard object. + objs="$objs $arg" + ;; + + *.lo) + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test "$pic_object" = none && + test "$non_pic_object" = none; then + func_fatal_error "cannot find name of object for \`$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + dlfiles="$dlfiles $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + dlprefiles="$dlprefiles $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object="$pic_object" + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "\`$arg' is not a valid libtool object" + fi + fi + ;; + + *.$libext) + # An archive. + deplibs="$deplibs $arg" + old_deplibs="$old_deplibs $arg" + continue + ;; + + *.la) + # A libtool-controlled library. + + if test "$prev" = dlfiles; then + # This library was specified with -dlopen. + dlfiles="$dlfiles $arg" + prev= + elif test "$prev" = dlprefiles; then + # The library was specified with -dlpreopen. + dlprefiles="$dlprefiles $arg" + prev= + else + deplibs="$deplibs $arg" + fi + continue + ;; + + # Some other compiler argument. + *) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + esac # arg + + # Now actually substitute the argument into the commands. + if test -n "$arg"; then + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + done # argument parsing loop + + test -n "$prev" && \ + func_fatal_help "the \`$prevarg' option requires an argument" + + if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then + eval arg=\"$export_dynamic_flag_spec\" + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + + oldlibs= + # calculate the name of the file, without its directory + func_basename "$output" + outputname="$func_basename_result" + libobjs_save="$libobjs" + + if test -n "$shlibpath_var"; then + # get the directories listed in $shlibpath_var + eval shlib_search_path=\`\$ECHO \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` + else + shlib_search_path= + fi + eval sys_lib_search_path=\"$sys_lib_search_path_spec\" + eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" + + func_dirname "$output" "/" "" + output_objdir="$func_dirname_result$objdir" + # Create the object directory. + func_mkdir_p "$output_objdir" + + # Determine the type of output + case $output in + "") + func_fatal_help "you must specify an output file" + ;; + *.$libext) linkmode=oldlib ;; + *.lo | *.$objext) linkmode=obj ;; + *.la) linkmode=lib ;; + *) linkmode=prog ;; # Anything else should be a program. + esac + + specialdeplibs= + + libs= + # Find all interdependent deplibs by searching for libraries + # that are linked more than once (e.g. -la -lb -la) + for deplib in $deplibs; do + if $opt_duplicate_deps ; then + case "$libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + libs="$libs $deplib" + done + + if test "$linkmode" = lib; then + libs="$predeps $libs $compiler_lib_search_path $postdeps" + + # Compute libraries that are listed more than once in $predeps + # $postdeps and mark them as special (i.e., whose duplicates are + # not to be eliminated). + pre_post_deps= + if $opt_duplicate_compiler_generated_deps; then + for pre_post_dep in $predeps $postdeps; do + case "$pre_post_deps " in + *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; + esac + pre_post_deps="$pre_post_deps $pre_post_dep" + done + fi + pre_post_deps= + fi + + deplibs= + newdependency_libs= + newlib_search_path= + need_relink=no # whether we're linking any uninstalled libtool libraries + notinst_deplibs= # not-installed libtool libraries + notinst_path= # paths that contain not-installed libtool libraries + + case $linkmode in + lib) + passes="conv dlpreopen link" + for file in $dlfiles $dlprefiles; do + case $file in + *.la) ;; + *) + func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" + ;; + esac + done + ;; + prog) + compile_deplibs= + finalize_deplibs= + alldeplibs=no + newdlfiles= + newdlprefiles= + passes="conv scan dlopen dlpreopen link" + ;; + *) passes="conv" + ;; + esac + + for pass in $passes; do + # The preopen pass in lib mode reverses $deplibs; put it back here + # so that -L comes before libs that need it for instance... + if test "$linkmode,$pass" = "lib,link"; then + ## FIXME: Find the place where the list is rebuilt in the wrong + ## order, and fix it there properly + tmp_deplibs= + for deplib in $deplibs; do + tmp_deplibs="$deplib $tmp_deplibs" + done + deplibs="$tmp_deplibs" + fi + + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan"; then + libs="$deplibs" + deplibs= + fi + if test "$linkmode" = prog; then + case $pass in + dlopen) libs="$dlfiles" ;; + dlpreopen) libs="$dlprefiles" ;; + link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; + esac + fi + if test "$linkmode,$pass" = "lib,dlpreopen"; then + # Collect and forward deplibs of preopened libtool libs + for lib in $dlprefiles; do + # Ignore non-libtool-libs + dependency_libs= + case $lib in + *.la) func_source "$lib" ;; + esac + + # Collect preopened libtool deplibs, except any this library + # has declared as weak libs + for deplib in $dependency_libs; do + deplib_base=`$ECHO "X$deplib" | $Xsed -e "$basename"` + case " $weak_libs " in + *" $deplib_base "*) ;; + *) deplibs="$deplibs $deplib" ;; + esac + done + done + libs="$dlprefiles" + fi + if test "$pass" = dlopen; then + # Collect dlpreopened libraries + save_deplibs="$deplibs" + deplibs= + fi + + for deplib in $libs; do + lib= + found=no + case $deplib in + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + compiler_flags="$compiler_flags $deplib" + if test "$linkmode" = lib ; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; + esac + fi + fi + continue + ;; + -l*) + if test "$linkmode" != lib && test "$linkmode" != prog; then + func_warning "\`-l' is ignored for archives/objects" + continue + fi + func_stripname '-l' '' "$deplib" + name=$func_stripname_result + if test "$linkmode" = lib; then + searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" + else + searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" + fi + for searchdir in $searchdirs; do + for search_ext in .la $std_shrext .so .a; do + # Search the libtool library + lib="$searchdir/lib${name}${search_ext}" + if test -f "$lib"; then + if test "$search_ext" = ".la"; then + found=yes + else + found=no + fi + break 2 + fi + done + done + if test "$found" != yes; then + # deplib doesn't seem to be a libtool library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + else # deplib is a libtool library + # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, + # We need to do some special things here, and not later. + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $deplib "*) + if func_lalib_p "$lib"; then + library_names= + old_library= + func_source "$lib" + for l in $old_library $library_names; do + ll="$l" + done + if test "X$ll" = "X$old_library" ; then # only static version available + found=no + func_dirname "$lib" "" "." + ladir="$func_dirname_result" + lib=$ladir/$old_library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + fi + fi + ;; + *) ;; + esac + fi + fi + ;; # -l + *.ltframework) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + if test "$linkmode" = lib ; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; + esac + fi + fi + continue + ;; + -L*) + case $linkmode in + lib) + deplibs="$deplib $deplibs" + test "$pass" = conv && continue + newdependency_libs="$deplib $newdependency_libs" + func_stripname '-L' '' "$deplib" + newlib_search_path="$newlib_search_path $func_stripname_result" + ;; + prog) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + if test "$pass" = scan; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + func_stripname '-L' '' "$deplib" + newlib_search_path="$newlib_search_path $func_stripname_result" + ;; + *) + func_warning "\`-L' is ignored for archives/objects" + ;; + esac # linkmode + continue + ;; # -L + -R*) + if test "$pass" = link; then + func_stripname '-R' '' "$deplib" + dir=$func_stripname_result + # Make sure the xrpath contains only unique directories. + case "$xrpath " in + *" $dir "*) ;; + *) xrpath="$xrpath $dir" ;; + esac + fi + deplibs="$deplib $deplibs" + continue + ;; + *.la) lib="$deplib" ;; + *.$libext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + case $linkmode in + lib) + # Linking convenience modules into shared libraries is allowed, + # but linking other static libraries is non-portable. + case " $dlpreconveniencelibs " in + *" $deplib "*) ;; + *) + valid_a_lib=no + case $deplibs_check_method in + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + if eval "\$ECHO \"X$deplib\"" 2>/dev/null | $Xsed -e 10q \ + | $EGREP "$match_pattern_regex" > /dev/null; then + valid_a_lib=yes + fi + ;; + pass_all) + valid_a_lib=yes + ;; + esac + if test "$valid_a_lib" != yes; then + $ECHO + $ECHO "*** Warning: Trying to link with static lib archive $deplib." + $ECHO "*** I have the capability to make that library automatically link in when" + $ECHO "*** you link to this library. But I can only do this if you have a" + $ECHO "*** shared version of the library, which you do not appear to have" + $ECHO "*** because the file extensions .$libext of this argument makes me believe" + $ECHO "*** that it is just a static archive that I should not use here." + else + $ECHO + $ECHO "*** Warning: Linking the shared library $output against the" + $ECHO "*** static library $deplib is not portable!" + deplibs="$deplib $deplibs" + fi + ;; + esac + continue + ;; + prog) + if test "$pass" != link; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + continue + ;; + esac # linkmode + ;; # *.$libext + *.lo | *.$objext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + elif test "$linkmode" = prog; then + if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then + # If there is no dlopen support or we're linking statically, + # we need to preload. + newdlprefiles="$newdlprefiles $deplib" + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + newdlfiles="$newdlfiles $deplib" + fi + fi + continue + ;; + %DEPLIBS%) + alldeplibs=yes + continue + ;; + esac # case $deplib + + if test "$found" = yes || test -f "$lib"; then : + else + func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" + fi + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$lib" \ + || func_fatal_error "\`$lib' is not a valid libtool archive" + + func_dirname "$lib" "" "." + ladir="$func_dirname_result" + + dlname= + dlopen= + dlpreopen= + libdir= + library_names= + old_library= + inherited_linker_flags= + # If the library was installed with an old release of libtool, + # it will not redefine variables installed, or shouldnotlink + installed=yes + shouldnotlink=no + avoidtemprpath= + + + # Read the .la file + func_source "$lib" + + # Convert "-framework foo" to "foo.ltframework" + if test -n "$inherited_linker_flags"; then + tmp_inherited_linker_flags=`$ECHO "X$inherited_linker_flags" | $Xsed -e 's/-framework \([^ $]*\)/\1.ltframework/g'` + for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do + case " $new_inherited_linker_flags " in + *" $tmp_inherited_linker_flag "*) ;; + *) new_inherited_linker_flags="$new_inherited_linker_flags $tmp_inherited_linker_flag";; + esac + done + fi + dependency_libs=`$ECHO "X $dependency_libs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan" || + { test "$linkmode" != prog && test "$linkmode" != lib; }; then + test -n "$dlopen" && dlfiles="$dlfiles $dlopen" + test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" + fi + + if test "$pass" = conv; then + # Only check for convenience libraries + deplibs="$lib $deplibs" + if test -z "$libdir"; then + if test -z "$old_library"; then + func_fatal_error "cannot find name of link library for \`$lib'" + fi + # It is a libtool convenience library, so add in its objects. + convenience="$convenience $ladir/$objdir/$old_library" + old_convenience="$old_convenience $ladir/$objdir/$old_library" + elif test "$linkmode" != prog && test "$linkmode" != lib; then + func_fatal_error "\`$lib' is not a convenience library" + fi + tmp_libs= + for deplib in $dependency_libs; do + deplibs="$deplib $deplibs" + if $opt_duplicate_deps ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done + continue + fi # $pass = conv + + + # Get the name of the library we link against. + linklib= + for l in $old_library $library_names; do + linklib="$l" + done + if test -z "$linklib"; then + func_fatal_error "cannot find name of link library for \`$lib'" + fi + + # This library was specified with -dlopen. + if test "$pass" = dlopen; then + if test -z "$libdir"; then + func_fatal_error "cannot -dlopen a convenience library: \`$lib'" + fi + if test -z "$dlname" || + test "$dlopen_support" != yes || + test "$build_libtool_libs" = no; then + # If there is no dlname, no dlopen support or we're linking + # statically, we need to preload. We also need to preload any + # dependent libraries so libltdl's deplib preloader doesn't + # bomb out in the load deplibs phase. + dlprefiles="$dlprefiles $lib $dependency_libs" + else + newdlfiles="$newdlfiles $lib" + fi + continue + fi # $pass = dlopen + + # We need an absolute path. + case $ladir in + [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; + *) + abs_ladir=`cd "$ladir" && pwd` + if test -z "$abs_ladir"; then + func_warning "cannot determine absolute directory name of \`$ladir'" + func_warning "passing it literally to the linker, although it might fail" + abs_ladir="$ladir" + fi + ;; + esac + func_basename "$lib" + laname="$func_basename_result" + + # Find the relevant object directory and library name. + if test "X$installed" = Xyes; then + if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then + func_warning "library \`$lib' was moved." + dir="$ladir" + absdir="$abs_ladir" + libdir="$abs_ladir" + else + dir="$libdir" + absdir="$libdir" + fi + test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes + else + if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then + dir="$ladir" + absdir="$abs_ladir" + # Remove this search path later + notinst_path="$notinst_path $abs_ladir" + else + dir="$ladir/$objdir" + absdir="$abs_ladir/$objdir" + # Remove this search path later + notinst_path="$notinst_path $abs_ladir" + fi + fi # $installed = yes + func_stripname 'lib' '.la' "$laname" + name=$func_stripname_result + + # This library was specified with -dlpreopen. + if test "$pass" = dlpreopen; then + if test -z "$libdir" && test "$linkmode" = prog; then + func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" + fi + # Prefer using a static library (so that no silly _DYNAMIC symbols + # are required to link). + if test -n "$old_library"; then + newdlprefiles="$newdlprefiles $dir/$old_library" + # Keep a list of preopened convenience libraries to check + # that they are being used correctly in the link pass. + test -z "$libdir" && \ + dlpreconveniencelibs="$dlpreconveniencelibs $dir/$old_library" + # Otherwise, use the dlname, so that lt_dlopen finds it. + elif test -n "$dlname"; then + newdlprefiles="$newdlprefiles $dir/$dlname" + else + newdlprefiles="$newdlprefiles $dir/$linklib" + fi + fi # $pass = dlpreopen + + if test -z "$libdir"; then + # Link the convenience library + if test "$linkmode" = lib; then + deplibs="$dir/$old_library $deplibs" + elif test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$dir/$old_library $compile_deplibs" + finalize_deplibs="$dir/$old_library $finalize_deplibs" + else + deplibs="$lib $deplibs" # used for prog,scan pass + fi + continue + fi + + + if test "$linkmode" = prog && test "$pass" != link; then + newlib_search_path="$newlib_search_path $ladir" + deplibs="$lib $deplibs" + + linkalldeplibs=no + if test "$link_all_deplibs" != no || test -z "$library_names" || + test "$build_libtool_libs" = no; then + linkalldeplibs=yes + fi + + tmp_libs= + for deplib in $dependency_libs; do + case $deplib in + -L*) func_stripname '-L' '' "$deplib" + newlib_search_path="$newlib_search_path $func_stripname_result" + ;; + esac + # Need to link against all dependency_libs? + if test "$linkalldeplibs" = yes; then + deplibs="$deplib $deplibs" + else + # Need to hardcode shared library paths + # or/and link against static libraries + newdependency_libs="$deplib $newdependency_libs" + fi + if $opt_duplicate_deps ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done # for deplib + continue + fi # $linkmode = prog... + + if test "$linkmode,$pass" = "prog,link"; then + if test -n "$library_names" && + { { test "$prefer_static_libs" = no || + test "$prefer_static_libs,$installed" = "built,yes"; } || + test -z "$old_library"; }; then + # We need to hardcode the library path + if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then + # Make sure the rpath contains only unique directories. + case "$temp_rpath:" in + *"$absdir:"*) ;; + *) temp_rpath="$temp_rpath$absdir:" ;; + esac + fi + + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) compile_rpath="$compile_rpath $absdir" + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" + esac + ;; + esac + fi # $linkmode,$pass = prog,link... + + if test "$alldeplibs" = yes && + { test "$deplibs_check_method" = pass_all || + { test "$build_libtool_libs" = yes && + test -n "$library_names"; }; }; then + # We only need to search for static libraries + continue + fi + fi + + link_static=no # Whether the deplib will be linked statically + use_static_libs=$prefer_static_libs + if test "$use_static_libs" = built && test "$installed" = yes; then + use_static_libs=no + fi + if test -n "$library_names" && + { test "$use_static_libs" = no || test -z "$old_library"; }; then + case $host in + *cygwin* | *mingw* | *cegcc*) + # No point in relinking DLLs because paths are not encoded + notinst_deplibs="$notinst_deplibs $lib" + need_relink=no + ;; + *) + if test "$installed" = no; then + notinst_deplibs="$notinst_deplibs $lib" + need_relink=yes + fi + ;; + esac + # This is a shared library + + # Warn about portability, can't link against -module's on some + # systems (darwin). Don't bleat about dlopened modules though! + dlopenmodule="" + for dlpremoduletest in $dlprefiles; do + if test "X$dlpremoduletest" = "X$lib"; then + dlopenmodule="$dlpremoduletest" + break + fi + done + if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then + $ECHO + if test "$linkmode" = prog; then + $ECHO "*** Warning: Linking the executable $output against the loadable module" + else + $ECHO "*** Warning: Linking the shared library $output against the loadable module" + fi + $ECHO "*** $linklib is not portable!" + fi + if test "$linkmode" = lib && + test "$hardcode_into_libs" = yes; then + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) compile_rpath="$compile_rpath $absdir" + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" + esac + ;; + esac + fi + + if test -n "$old_archive_from_expsyms_cmds"; then + # figure out the soname + set dummy $library_names + shift + realname="$1" + shift + libname=`eval "\\$ECHO \"$libname_spec\""` + # use dlname if we got it. it's perfectly good, no? + if test -n "$dlname"; then + soname="$dlname" + elif test -n "$soname_spec"; then + # bleh windows + case $host in + *cygwin* | mingw* | *cegcc*) + func_arith $current - $age + major=$func_arith_result + versuffix="-$major" + ;; + esac + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + + # Make a new name for the extract_expsyms_cmds to use + soroot="$soname" + func_basename "$soroot" + soname="$func_basename_result" + func_stripname 'lib' '.dll' "$soname" + newlib=libimp-$func_stripname_result.a + + # If the library has no export list, then create one now + if test -f "$output_objdir/$soname-def"; then : + else + func_verbose "extracting exported symbol list from \`$soname'" + func_execute_cmds "$extract_expsyms_cmds" 'exit $?' + fi + + # Create $newlib + if test -f "$output_objdir/$newlib"; then :; else + func_verbose "generating import library for \`$soname'" + func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' + fi + # make sure the library variables are pointing to the new library + dir=$output_objdir + linklib=$newlib + fi # test -n "$old_archive_from_expsyms_cmds" + + if test "$linkmode" = prog || test "$mode" != relink; then + add_shlibpath= + add_dir= + add= + lib_linked=yes + case $hardcode_action in + immediate | unsupported) + if test "$hardcode_direct" = no; then + add="$dir/$linklib" + case $host in + *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; + *-*-sysv4*uw2*) add_dir="-L$dir" ;; + *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ + *-*-unixware7*) add_dir="-L$dir" ;; + *-*-darwin* ) + # if the lib is a (non-dlopened) module then we can not + # link against it, someone is ignoring the earlier warnings + if /usr/bin/file -L $add 2> /dev/null | + $GREP ": [^:]* bundle" >/dev/null ; then + if test "X$dlopenmodule" != "X$lib"; then + $ECHO "*** Warning: lib $linklib is a module, not a shared library" + if test -z "$old_library" ; then + $ECHO + $ECHO "*** And there doesn't seem to be a static archive available" + $ECHO "*** The link will probably fail, sorry" + else + add="$dir/$old_library" + fi + elif test -n "$old_library"; then + add="$dir/$old_library" + fi + fi + esac + elif test "$hardcode_minus_L" = no; then + case $host in + *-*-sunos*) add_shlibpath="$dir" ;; + esac + add_dir="-L$dir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = no; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + relink) + if test "$hardcode_direct" = yes && + test "$hardcode_direct_absolute" = no; then + add="$dir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$dir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + add_dir="$add_dir -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + *) lib_linked=no ;; + esac + + if test "$lib_linked" != yes; then + func_fatal_configuration "unsupported hardcode properties" + fi + + if test -n "$add_shlibpath"; then + case :$compile_shlibpath: in + *":$add_shlibpath:"*) ;; + *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; + esac + fi + if test "$linkmode" = prog; then + test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" + test -n "$add" && compile_deplibs="$add $compile_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + if test "$hardcode_direct" != yes && + test "$hardcode_minus_L" != yes && + test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; + esac + fi + fi + fi + + if test "$linkmode" = prog || test "$mode" = relink; then + add_shlibpath= + add_dir= + add= + # Finalize command for both is simple: just hardcode it. + if test "$hardcode_direct" = yes && + test "$hardcode_direct_absolute" = no; then + add="$libdir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$libdir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; + esac + add="-l$name" + elif test "$hardcode_automatic" = yes; then + if test -n "$inst_prefix_dir" && + test -f "$inst_prefix_dir$libdir/$linklib" ; then + add="$inst_prefix_dir$libdir/$linklib" + else + add="$libdir/$linklib" + fi + else + # We cannot seem to hardcode it, guess we'll fake it. + add_dir="-L$libdir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + add_dir="$add_dir -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + fi + + if test "$linkmode" = prog; then + test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" + test -n "$add" && finalize_deplibs="$add $finalize_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + fi + fi + elif test "$linkmode" = prog; then + # Here we assume that one of hardcode_direct or hardcode_minus_L + # is not unsupported. This is valid on all known static and + # shared platforms. + if test "$hardcode_direct" != unsupported; then + test -n "$old_library" && linklib="$old_library" + compile_deplibs="$dir/$linklib $compile_deplibs" + finalize_deplibs="$dir/$linklib $finalize_deplibs" + else + compile_deplibs="-l$name -L$dir $compile_deplibs" + finalize_deplibs="-l$name -L$dir $finalize_deplibs" + fi + elif test "$build_libtool_libs" = yes; then + # Not a shared library + if test "$deplibs_check_method" != pass_all; then + # We're trying link a shared library against a static one + # but the system doesn't support it. + + # Just print a warning and add the library to dependency_libs so + # that the program can be linked against the static library. + $ECHO + $ECHO "*** Warning: This system can not link to static lib archive $lib." + $ECHO "*** I have the capability to make that library automatically link in when" + $ECHO "*** you link to this library. But I can only do this if you have a" + $ECHO "*** shared version of the library, which you do not appear to have." + if test "$module" = yes; then + $ECHO "*** But as you try to build a module library, libtool will still create " + $ECHO "*** a static module, that should work as long as the dlopening application" + $ECHO "*** is linked with the -dlopen flag to resolve symbols at runtime." + if test -z "$global_symbol_pipe"; then + $ECHO + $ECHO "*** However, this would only work if libtool was able to extract symbol" + $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" + $ECHO "*** not find such a program. So, this module is probably useless." + $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + else + deplibs="$dir/$old_library $deplibs" + link_static=yes + fi + fi # link shared/static library? + + if test "$linkmode" = lib; then + if test -n "$dependency_libs" && + { test "$hardcode_into_libs" != yes || + test "$build_old_libs" = yes || + test "$link_static" = yes; }; then + # Extract -R from dependency_libs + temp_deplibs= + for libdir in $dependency_libs; do + case $libdir in + -R*) func_stripname '-R' '' "$libdir" + temp_xrpath=$func_stripname_result + case " $xrpath " in + *" $temp_xrpath "*) ;; + *) xrpath="$xrpath $temp_xrpath";; + esac;; + *) temp_deplibs="$temp_deplibs $libdir";; + esac + done + dependency_libs="$temp_deplibs" + fi + + newlib_search_path="$newlib_search_path $absdir" + # Link against this library + test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" + # ... and its dependency_libs + tmp_libs= + for deplib in $dependency_libs; do + newdependency_libs="$deplib $newdependency_libs" + if $opt_duplicate_deps ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done + + if test "$link_all_deplibs" != no; then + # Add the search paths of all dependency libraries + for deplib in $dependency_libs; do + case $deplib in + -L*) path="$deplib" ;; + *.la) + func_dirname "$deplib" "" "." + dir="$func_dirname_result" + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; + *) + absdir=`cd "$dir" && pwd` + if test -z "$absdir"; then + func_warning "cannot determine absolute directory name of \`$dir'" + absdir="$dir" + fi + ;; + esac + if $GREP "^installed=no" $deplib > /dev/null; then + case $host in + *-*-darwin*) + depdepl= + eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` + if test -n "$deplibrary_names" ; then + for tmp in $deplibrary_names ; do + depdepl=$tmp + done + if test -f "$absdir/$objdir/$depdepl" ; then + depdepl="$absdir/$objdir/$depdepl" + darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + if test -z "$darwin_install_name"; then + darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + fi + compiler_flags="$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" + linker_flags="$linker_flags -dylib_file ${darwin_install_name}:${depdepl}" + path= + fi + fi + ;; + *) + path="-L$absdir/$objdir" + ;; + esac + else + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + test -z "$libdir" && \ + func_fatal_error "\`$deplib' is not a valid libtool archive" + test "$absdir" != "$libdir" && \ + func_warning "\`$deplib' seems to be moved" + + path="-L$absdir" + fi + ;; + esac + case " $deplibs " in + *" $path "*) ;; + *) deplibs="$path $deplibs" ;; + esac + done + fi # link_all_deplibs != no + fi # linkmode = lib + done # for deplib in $libs + if test "$pass" = link; then + if test "$linkmode" = "prog"; then + compile_deplibs="$new_inherited_linker_flags $compile_deplibs" + finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" + else + compiler_flags="$compiler_flags "`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + fi + fi + dependency_libs="$newdependency_libs" + if test "$pass" = dlpreopen; then + # Link the dlpreopened libraries before other libraries + for deplib in $save_deplibs; do + deplibs="$deplib $deplibs" + done + fi + if test "$pass" != dlopen; then + if test "$pass" != conv; then + # Make sure lib_search_path contains only unique directories. + lib_search_path= + for dir in $newlib_search_path; do + case "$lib_search_path " in + *" $dir "*) ;; + *) lib_search_path="$lib_search_path $dir" ;; + esac + done + newlib_search_path= + fi + + if test "$linkmode,$pass" != "prog,link"; then + vars="deplibs" + else + vars="compile_deplibs finalize_deplibs" + fi + for var in $vars dependency_libs; do + # Add libraries to $var in reverse order + eval tmp_libs=\"\$$var\" + new_libs= + for deplib in $tmp_libs; do + # FIXME: Pedantically, this is the right thing to do, so + # that some nasty dependency loop isn't accidentally + # broken: + #new_libs="$deplib $new_libs" + # Pragmatically, this seems to cause very few problems in + # practice: + case $deplib in + -L*) new_libs="$deplib $new_libs" ;; + -R*) ;; + *) + # And here is the reason: when a library appears more + # than once as an explicit dependence of a library, or + # is implicitly linked in more than once by the + # compiler, it is considered special, and multiple + # occurrences thereof are not removed. Compare this + # with having the same library being listed as a + # dependency of multiple other libraries: in this case, + # we know (pedantically, we assume) the library does not + # need to be listed more than once, so we keep only the + # last copy. This is not always right, but it is rare + # enough that we require users that really mean to play + # such unportable linking tricks to link the library + # using -Wl,-lname, so that libtool does not consider it + # for duplicate removal. + case " $specialdeplibs " in + *" $deplib "*) new_libs="$deplib $new_libs" ;; + *) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$deplib $new_libs" ;; + esac + ;; + esac + ;; + esac + done + tmp_libs= + for deplib in $new_libs; do + case $deplib in + -L*) + case " $tmp_libs " in + *" $deplib "*) ;; + *) tmp_libs="$tmp_libs $deplib" ;; + esac + ;; + *) tmp_libs="$tmp_libs $deplib" ;; + esac + done + eval $var=\"$tmp_libs\" + done # for var + fi + # Last step: remove runtime libs from dependency_libs + # (they stay in deplibs) + tmp_libs= + for i in $dependency_libs ; do + case " $predeps $postdeps $compiler_lib_search_path " in + *" $i "*) + i="" + ;; + esac + if test -n "$i" ; then + tmp_libs="$tmp_libs $i" + fi + done + dependency_libs=$tmp_libs + done # for pass + if test "$linkmode" = prog; then + dlfiles="$newdlfiles" + fi + if test "$linkmode" = prog || test "$linkmode" = lib; then + dlprefiles="$newdlprefiles" + fi + + case $linkmode in + oldlib) + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + func_warning "\`-dlopen' is ignored for archives" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "\`-l' and \`-L' are ignored for archives" ;; + esac + + test -n "$rpath" && \ + func_warning "\`-rpath' is ignored for archives" + + test -n "$xrpath" && \ + func_warning "\`-R' is ignored for archives" + + test -n "$vinfo" && \ + func_warning "\`-version-info/-version-number' is ignored for archives" + + test -n "$release" && \ + func_warning "\`-release' is ignored for archives" + + test -n "$export_symbols$export_symbols_regex" && \ + func_warning "\`-export-symbols' is ignored for archives" + + # Now set the variables for building old libraries. + build_libtool_libs=no + oldlibs="$output" + objs="$objs$old_deplibs" + ;; + + lib) + # Make sure we only generate libraries of the form `libNAME.la'. + case $outputname in + lib*) + func_stripname 'lib' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + ;; + *) + test "$module" = no && \ + func_fatal_help "libtool library \`$output' must begin with \`lib'" + + if test "$need_lib_prefix" != no; then + # Add the "lib" prefix for modules if required + func_stripname '' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + else + func_stripname '' '.la' "$outputname" + libname=$func_stripname_result + fi + ;; + esac + + if test -n "$objs"; then + if test "$deplibs_check_method" != pass_all; then + func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" + else + $ECHO + $ECHO "*** Warning: Linking the shared library $output against the non-libtool" + $ECHO "*** objects $objs is not portable!" + libobjs="$libobjs $objs" + fi + fi + + test "$dlself" != no && \ + func_warning "\`-dlopen self' is ignored for libtool libraries" + + set dummy $rpath + shift + test "$#" -gt 1 && \ + func_warning "ignoring multiple \`-rpath's for a libtool library" + + install_libdir="$1" + + oldlibs= + if test -z "$rpath"; then + if test "$build_libtool_libs" = yes; then + # Building a libtool convenience library. + # Some compilers have problems with a `.al' extension so + # convenience libraries should have the same extension an + # archive normally would. + oldlibs="$output_objdir/$libname.$libext $oldlibs" + build_libtool_libs=convenience + build_old_libs=yes + fi + + test -n "$vinfo" && \ + func_warning "\`-version-info/-version-number' is ignored for convenience libraries" + + test -n "$release" && \ + func_warning "\`-release' is ignored for convenience libraries" + else + + # Parse the version information argument. + save_ifs="$IFS"; IFS=':' + set dummy $vinfo 0 0 0 + shift + IFS="$save_ifs" + + test -n "$7" && \ + func_fatal_help "too many parameters to \`-version-info'" + + # convert absolute version numbers to libtool ages + # this retains compatibility with .la files and attempts + # to make the code below a bit more comprehensible + + case $vinfo_number in + yes) + number_major="$1" + number_minor="$2" + number_revision="$3" + # + # There are really only two kinds -- those that + # use the current revision as the major version + # and those that subtract age and use age as + # a minor version. But, then there is irix + # which has an extra 1 added just for fun + # + case $version_type in + darwin|linux|osf|windows|none) + func_arith $number_major + $number_minor + current=$func_arith_result + age="$number_minor" + revision="$number_revision" + ;; + freebsd-aout|freebsd-elf|sunos) + current="$number_major" + revision="$number_minor" + age="0" + ;; + irix|nonstopux) + func_arith $number_major + $number_minor + current=$func_arith_result + age="$number_minor" + revision="$number_minor" + lt_irix_increment=no + ;; + esac + ;; + no) + current="$1" + revision="$2" + age="$3" + ;; + esac + + # Check that each of the things are valid numbers. + case $current in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "CURRENT \`$current' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + case $revision in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "REVISION \`$revision' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + case $age in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "AGE \`$age' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + if test "$age" -gt "$current"; then + func_error "AGE \`$age' is greater than the current interface number \`$current'" + func_fatal_error "\`$vinfo' is not valid version information" + fi + + # Calculate the version variables. + major= + versuffix= + verstring= + case $version_type in + none) ;; + + darwin) + # Like Linux, but with the current version available in + # verstring for coding it into the library header + func_arith $current - $age + major=.$func_arith_result + versuffix="$major.$age.$revision" + # Darwin ld doesn't like 0 for these options... + func_arith $current + 1 + minor_current=$func_arith_result + xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" + verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" + ;; + + freebsd-aout) + major=".$current" + versuffix=".$current.$revision"; + ;; + + freebsd-elf) + major=".$current" + versuffix=".$current" + ;; + + irix | nonstopux) + if test "X$lt_irix_increment" = "Xno"; then + func_arith $current - $age + else + func_arith $current - $age + 1 + fi + major=$func_arith_result + + case $version_type in + nonstopux) verstring_prefix=nonstopux ;; + *) verstring_prefix=sgi ;; + esac + verstring="$verstring_prefix$major.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$revision + while test "$loop" -ne 0; do + func_arith $revision - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring="$verstring_prefix$major.$iface:$verstring" + done + + # Before this point, $major must not contain `.'. + major=.$major + versuffix="$major.$revision" + ;; + + linux) + func_arith $current - $age + major=.$func_arith_result + versuffix="$major.$age.$revision" + ;; + + osf) + func_arith $current - $age + major=.$func_arith_result + versuffix=".$current.$age.$revision" + verstring="$current.$age.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$age + while test "$loop" -ne 0; do + func_arith $current - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring="$verstring:${iface}.0" + done + + # Make executables depend on our current version. + verstring="$verstring:${current}.0" + ;; + + qnx) + major=".$current" + versuffix=".$current" + ;; + + sunos) + major=".$current" + versuffix=".$current.$revision" + ;; + + windows) + # Use '-' rather than '.', since we only want one + # extension on DOS 8.3 filesystems. + func_arith $current - $age + major=$func_arith_result + versuffix="-$major" + ;; + + *) + func_fatal_configuration "unknown library version type \`$version_type'" + ;; + esac + + # Clear the version info if we defaulted, and they specified a release. + if test -z "$vinfo" && test -n "$release"; then + major= + case $version_type in + darwin) + # we can't check for "0.0" in archive_cmds due to quoting + # problems, so we reset it completely + verstring= + ;; + *) + verstring="0.0" + ;; + esac + if test "$need_version" = no; then + versuffix= + else + versuffix=".0.0" + fi + fi + + # Remove version info from name if versioning should be avoided + if test "$avoid_version" = yes && test "$need_version" = no; then + major= + versuffix= + verstring="" + fi + + # Check to see if the archive will have undefined symbols. + if test "$allow_undefined" = yes; then + if test "$allow_undefined_flag" = unsupported; then + func_warning "undefined symbols not allowed in $host shared libraries" + build_libtool_libs=no + build_old_libs=yes + fi + else + # Don't allow undefined symbols. + allow_undefined_flag="$no_undefined_flag" + fi + + fi + + func_generate_dlsyms "$libname" "$libname" "yes" + libobjs="$libobjs $symfileobj" + test "X$libobjs" = "X " && libobjs= + + if test "$mode" != relink; then + # Remove our outputs, but don't remove object files since they + # may have been created when compiling PIC objects. + removelist= + tempremovelist=`$ECHO "$output_objdir/*"` + for p in $tempremovelist; do + case $p in + *.$objext | *.gcno) + ;; + $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) + if test "X$precious_files_regex" != "X"; then + if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 + then + continue + fi + fi + removelist="$removelist $p" + ;; + *) ;; + esac + done + test -n "$removelist" && \ + func_show_eval "${RM}r \$removelist" + fi + + # Now set the variables for building old libraries. + if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then + oldlibs="$oldlibs $output_objdir/$libname.$libext" + + # Transform .lo files to .o files. + oldobjs="$objs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP` + fi + + # Eliminate all temporary directories. + #for path in $notinst_path; do + # lib_search_path=`$ECHO "X$lib_search_path " | $Xsed -e "s% $path % %g"` + # deplibs=`$ECHO "X$deplibs " | $Xsed -e "s% -L$path % %g"` + # dependency_libs=`$ECHO "X$dependency_libs " | $Xsed -e "s% -L$path % %g"` + #done + + if test -n "$xrpath"; then + # If the user specified any rpath flags, then add them. + temp_xrpath= + for libdir in $xrpath; do + temp_xrpath="$temp_xrpath -R$libdir" + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" ;; + esac + done + if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then + dependency_libs="$temp_xrpath $dependency_libs" + fi + fi + + # Make sure dlfiles contains only unique files that won't be dlpreopened + old_dlfiles="$dlfiles" + dlfiles= + for lib in $old_dlfiles; do + case " $dlprefiles $dlfiles " in + *" $lib "*) ;; + *) dlfiles="$dlfiles $lib" ;; + esac + done + + # Make sure dlprefiles contains only unique files + old_dlprefiles="$dlprefiles" + dlprefiles= + for lib in $old_dlprefiles; do + case "$dlprefiles " in + *" $lib "*) ;; + *) dlprefiles="$dlprefiles $lib" ;; + esac + done + + if test "$build_libtool_libs" = yes; then + if test -n "$rpath"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc*) + # these systems don't actually have a c library (as such)! + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C library is in the System framework + deplibs="$deplibs System.ltframework" + ;; + *-*-netbsd*) + # Don't link with libc until the a.out ld.so is fixed. + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc due to us having libc/libc_r. + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + ;; + *) + # Add libc to deplibs on all other systems if necessary. + if test "$build_libtool_need_lc" = "yes"; then + deplibs="$deplibs -lc" + fi + ;; + esac + fi + + # Transform deplibs into only deplibs that can be linked in shared. + name_save=$name + libname_save=$libname + release_save=$release + versuffix_save=$versuffix + major_save=$major + # I'm not sure if I'm treating the release correctly. I think + # release should show up in the -l (ie -lgmp5) so we don't want to + # add it in twice. Is that correct? + release="" + versuffix="" + major="" + newdeplibs= + droppeddeps=no + case $deplibs_check_method in + pass_all) + # Don't check for shared/static. Everything works. + # This might be a little naive. We might want to check + # whether the library exists or not. But this is on + # osf3 & osf4 and I'm not really sure... Just + # implementing what was already the behavior. + newdeplibs=$deplibs + ;; + test_compile) + # This code stresses the "libraries are programs" paradigm to its + # limits. Maybe even breaks it. We compile a program, linking it + # against the deplibs as a proxy for the library. Then we can check + # whether they linked in statically or dynamically with ldd. + $opt_dry_run || $RM conftest.c + cat > conftest.c </dev/null` + for potent_lib in $potential_libs; do + # Follow soft links. + if ls -lLd "$potent_lib" 2>/dev/null | + $GREP " -> " >/dev/null; then + continue + fi + # The statement above tries to avoid entering an + # endless loop below, in case of cyclic links. + # We might still enter an endless loop, since a link + # loop can be closed while we follow links, + # but so what? + potlib="$potent_lib" + while test -h "$potlib" 2>/dev/null; do + potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` + case $potliblink in + [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; + *) potlib=`$ECHO "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";; + esac + done + if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | + $SED -e 10q | + $EGREP "$file_magic_regex" > /dev/null; then + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + $ECHO + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + $ECHO "*** I have the capability to make that library automatically link in when" + $ECHO "*** you link to this library. But I can only do this if you have a" + $ECHO "*** shared version of the library, which you do not appear to have" + $ECHO "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $ECHO "*** with $libname but no candidates were found. (...for file magic test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a file magic. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + newdeplibs="$newdeplibs $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + for a_deplib in $deplibs; do + case $a_deplib in + -l*) + func_stripname -l '' "$a_deplib" + name=$func_stripname_result + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $a_deplib "*) + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + ;; + esac + fi + if test -n "$a_deplib" ; then + libname=`eval "\\$ECHO \"$libname_spec\""` + for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do + potential_libs=`ls $i/$libname[.-]* 2>/dev/null` + for potent_lib in $potential_libs; do + potlib="$potent_lib" # see symlink-check above in file_magic test + if eval "\$ECHO \"X$potent_lib\"" 2>/dev/null | $Xsed -e 10q | \ + $EGREP "$match_pattern_regex" > /dev/null; then + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + $ECHO + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + $ECHO "*** I have the capability to make that library automatically link in when" + $ECHO "*** you link to this library. But I can only do this if you have a" + $ECHO "*** shared version of the library, which you do not appear to have" + $ECHO "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a regex pattern. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + newdeplibs="$newdeplibs $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + none | unknown | *) + newdeplibs="" + tmp_deplibs=`$ECHO "X $deplibs" | $Xsed \ + -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'` + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + for i in $predeps $postdeps ; do + # can't use Xsed below, because $i might contain '/' + tmp_deplibs=`$ECHO "X $tmp_deplibs" | $Xsed -e "s,$i,,"` + done + fi + if $ECHO "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' | + $GREP . >/dev/null; then + $ECHO + if test "X$deplibs_check_method" = "Xnone"; then + $ECHO "*** Warning: inter-library dependencies are not supported in this platform." + else + $ECHO "*** Warning: inter-library dependencies are not known to be supported." + fi + $ECHO "*** All declared inter-library dependencies are being dropped." + droppeddeps=yes + fi + ;; + esac + versuffix=$versuffix_save + major=$major_save + release=$release_save + libname=$libname_save + name=$name_save + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library with the System framework + newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's/ -lc / System.ltframework /'` + ;; + esac + + if test "$droppeddeps" = yes; then + if test "$module" = yes; then + $ECHO + $ECHO "*** Warning: libtool could not satisfy all declared inter-library" + $ECHO "*** dependencies of module $libname. Therefore, libtool will create" + $ECHO "*** a static module, that should work as long as the dlopening" + $ECHO "*** application is linked with the -dlopen flag." + if test -z "$global_symbol_pipe"; then + $ECHO + $ECHO "*** However, this would only work if libtool was able to extract symbol" + $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" + $ECHO "*** not find such a program. So, this module is probably useless." + $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + else + $ECHO "*** The inter-library dependencies that have been dropped here will be" + $ECHO "*** automatically added whenever a program is linked with this library" + $ECHO "*** or is declared to -dlopen it." + + if test "$allow_undefined" = no; then + $ECHO + $ECHO "*** Since this library must not contain undefined symbols," + $ECHO "*** because either the platform does not support them or" + $ECHO "*** it was explicitly requested with -no-undefined," + $ECHO "*** libtool will only create a static version of it." + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + fi + fi + # Done checking deplibs! + deplibs=$newdeplibs + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + case $host in + *-*-darwin*) + newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + new_inherited_linker_flags=`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + deplibs=`$ECHO "X $deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $deplibs " in + *" -L$path/$objdir "*) + new_libs="$new_libs -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$new_libs $deplib" ;; + esac + ;; + *) new_libs="$new_libs $deplib" ;; + esac + done + deplibs="$new_libs" + + # All the library-specific variables (install_libdir is set above). + library_names= + old_library= + dlname= + + # Test again, we may have decided not to build it any more + if test "$build_libtool_libs" = yes; then + if test "$hardcode_into_libs" = yes; then + # Hardcode the library paths + hardcode_libdirs= + dep_rpath= + rpath="$finalize_rpath" + test "$mode" != relink && rpath="$compile_rpath$rpath" + for libdir in $rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + dep_rpath="$dep_rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) perm_rpath="$perm_rpath $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + if test -n "$hardcode_libdir_flag_spec_ld"; then + eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\" + else + eval dep_rpath=\"$hardcode_libdir_flag_spec\" + fi + fi + if test -n "$runpath_var" && test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + rpath="$rpath$dir:" + done + eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" + fi + test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" + fi + + shlibpath="$finalize_shlibpath" + test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath" + if test -n "$shlibpath"; then + eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" + fi + + # Get the real and link names of the library. + eval shared_ext=\"$shrext_cmds\" + eval library_names=\"$library_names_spec\" + set dummy $library_names + shift + realname="$1" + shift + + if test -n "$soname_spec"; then + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + if test -z "$dlname"; then + dlname=$soname + fi + + lib="$output_objdir/$realname" + linknames= + for link + do + linknames="$linknames $link" + done + + # Use standard objects if they are pic + test -z "$pic_flag" && libobjs=`$ECHO "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + test "X$libobjs" = "X " && libobjs= + + delfiles= + if test -n "$export_symbols" && test -n "$include_expsyms"; then + $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" + export_symbols="$output_objdir/$libname.uexp" + delfiles="$delfiles $export_symbols" + fi + + orig_export_symbols= + case $host_os in + cygwin* | mingw* | cegcc*) + if test -n "$export_symbols" && test -z "$export_symbols_regex"; then + # exporting using user supplied symfile + if test "x`$SED 1q $export_symbols`" != xEXPORTS; then + # and it's NOT already a .def file. Must figure out + # which of the given symbols are data symbols and tag + # them as such. So, trigger use of export_symbols_cmds. + # export_symbols gets reassigned inside the "prepare + # the list of exported symbols" if statement, so the + # include_expsyms logic still works. + orig_export_symbols="$export_symbols" + export_symbols= + always_export_symbols=yes + fi + fi + ;; + esac + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then + func_verbose "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $opt_dry_run || $RM $export_symbols + cmds=$export_symbols_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + func_len " $cmd" + len=$func_len_result + if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + func_show_eval "$cmd" 'exit $?' + skipped_export=false + else + # The command line is too long to execute in one step. + func_verbose "using reloadable object file for export list..." + skipped_export=: + # Break out early, otherwise skipped_export may be + # set to false by a later but shorter cmd. + break + fi + done + IFS="$save_ifs" + if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + fi + + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols="$export_symbols" + test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" + $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' + fi + + if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + + tmp_deplibs= + for test_deplib in $deplibs; do + case " $convenience " in + *" $test_deplib "*) ;; + *) + tmp_deplibs="$tmp_deplibs $test_deplib" + ;; + esac + done + deplibs="$tmp_deplibs" + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec" && + test "$compiler_needs_object" = yes && + test -z "$libobjs"; then + # extract the archives, so we have objects to list. + # TODO: could optimize this to just extract one archive. + whole_archive_flag_spec= + fi + if test -n "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + else + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + + func_extract_archives $gentop $convenience + libobjs="$libobjs $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + fi + + if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then + eval flag=\"$thread_safe_flag_spec\" + linker_flags="$linker_flags $flag" + fi + + # Make a backup of the uninstalled library when relinking + if test "$mode" = relink; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? + fi + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + eval test_cmds=\"$module_expsym_cmds\" + cmds=$module_expsym_cmds + else + eval test_cmds=\"$module_cmds\" + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + eval test_cmds=\"$archive_expsym_cmds\" + cmds=$archive_expsym_cmds + else + eval test_cmds=\"$archive_cmds\" + cmds=$archive_cmds + fi + fi + + if test "X$skipped_export" != "X:" && + func_len " $test_cmds" && + len=$func_len_result && + test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + : + else + # The command line is too long to link in one step, link piecewise + # or, if using GNU ld and skipped_export is not :, use a linker + # script. + + # Save the value of $output and $libobjs because we want to + # use them later. If we have whole_archive_flag_spec, we + # want to use save_libobjs as it was before + # whole_archive_flag_spec was expanded, because we can't + # assume the linker understands whole_archive_flag_spec. + # This may have to be revisited, in case too many + # convenience libraries get linked in and end up exceeding + # the spec. + if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + fi + save_output=$output + output_la=`$ECHO "X$output" | $Xsed -e "$basename"` + + # Clear the reloadable object creation command queue and + # initialize k to one. + test_cmds= + concat_cmds= + objlist= + last_robj= + k=1 + + if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then + output=${output_objdir}/${output_la}.lnkscript + func_verbose "creating GNU ld script: $output" + $ECHO 'INPUT (' > $output + for obj in $save_libobjs + do + $ECHO "$obj" >> $output + done + $ECHO ')' >> $output + delfiles="$delfiles $output" + elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then + output=${output_objdir}/${output_la}.lnk + func_verbose "creating linker input file list: $output" + : > $output + set x $save_libobjs + shift + firstobj= + if test "$compiler_needs_object" = yes; then + firstobj="$1 " + shift + fi + for obj + do + $ECHO "$obj" >> $output + done + delfiles="$delfiles $output" + output=$firstobj\"$file_list_spec$output\" + else + if test -n "$save_libobjs"; then + func_verbose "creating reloadable object files..." + output=$output_objdir/$output_la-${k}.$objext + eval test_cmds=\"$reload_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + + # Loop over the list of objects to be linked. + for obj in $save_libobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + if test "X$objlist" = X || + test "$len" -lt "$max_cmd_len"; then + func_append objlist " $obj" + else + # The command $test_cmds is almost too long, add a + # command to the queue. + if test "$k" -eq 1 ; then + # The first file doesn't have a previous command to add. + eval concat_cmds=\"$reload_cmds $objlist $last_robj\" + else + # All subsequent reloadable object files will link in + # the last one created. + eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj~\$RM $last_robj\" + fi + last_robj=$output_objdir/$output_la-${k}.$objext + func_arith $k + 1 + k=$func_arith_result + output=$output_objdir/$output_la-${k}.$objext + objlist=$obj + func_len " $last_robj" + func_arith $len0 + $func_len_result + len=$func_arith_result + fi + done + # Handle the remaining objects by creating one last + # reloadable object file. All subsequent reloadable object + # files will link in the last one created. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\" + if test -n "$last_robj"; then + eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" + fi + delfiles="$delfiles $output" + + else + output= + fi + + if ${skipped_export-false}; then + func_verbose "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $opt_dry_run || $RM $export_symbols + libobjs=$output + # Append the command to create the export file. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" + if test -n "$last_robj"; then + eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" + fi + fi + + test -n "$save_libobjs" && + func_verbose "creating a temporary reloadable object file: $output" + + # Loop through the commands generated above and execute them. + save_ifs="$IFS"; IFS='~' + for cmd in $concat_cmds; do + IFS="$save_ifs" + $opt_silent || { + func_quote_for_expand "$cmd" + eval "func_echo $func_quote_for_expand_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test "$mode" = relink; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS="$save_ifs" + + if test -n "$export_symbols_regex" && ${skipped_export-false}; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + + if ${skipped_export-false}; then + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols="$export_symbols" + test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" + $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' + fi + + if test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + fi + + libobjs=$output + # Restore the value of output. + output=$save_output + + if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + fi + # Expand the library linking commands again to reset the + # value of $libobjs for piecewise linking. + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + cmds=$module_expsym_cmds + else + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + cmds=$archive_expsym_cmds + else + cmds=$archive_cmds + fi + fi + fi + + if test -n "$delfiles"; then + # Append the command to remove temporary files to $cmds. + eval cmds=\"\$cmds~\$RM $delfiles\" + fi + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + + func_extract_archives $gentop $dlprefiles + libobjs="$libobjs $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $opt_silent || { + func_quote_for_expand "$cmd" + eval "func_echo $func_quote_for_expand_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test "$mode" = relink; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS="$save_ifs" + + # Restore the uninstalled library and exit + if test "$mode" = relink; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? + + if test -n "$convenience"; then + if test -z "$whole_archive_flag_spec"; then + func_show_eval '${RM}r "$gentop"' + fi + fi + + exit $EXIT_SUCCESS + fi + + # Create links to the real library. + for linkname in $linknames; do + if test "$realname" != "$linkname"; then + func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' + fi + done + + # If -module or -export-dynamic was specified, set the dlname. + if test "$module" = yes || test "$export_dynamic" = yes; then + # On all known operating systems, these are identical. + dlname="$soname" + fi + fi + ;; + + obj) + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + func_warning "\`-dlopen' is ignored for objects" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "\`-l' and \`-L' are ignored for objects" ;; + esac + + test -n "$rpath" && \ + func_warning "\`-rpath' is ignored for objects" + + test -n "$xrpath" && \ + func_warning "\`-R' is ignored for objects" + + test -n "$vinfo" && \ + func_warning "\`-version-info' is ignored for objects" + + test -n "$release" && \ + func_warning "\`-release' is ignored for objects" + + case $output in + *.lo) + test -n "$objs$old_deplibs" && \ + func_fatal_error "cannot build library object \`$output' from non-libtool objects" + + libobj=$output + func_lo2o "$libobj" + obj=$func_lo2o_result + ;; + *) + libobj= + obj="$output" + ;; + esac + + # Delete the old objects. + $opt_dry_run || $RM $obj $libobj + + # Objects from convenience libraries. This assumes + # single-version convenience libraries. Whenever we create + # different ones for PIC/non-PIC, this we'll have to duplicate + # the extraction. + reload_conv_objs= + gentop= + # reload_cmds runs $LD directly, so let us get rid of + # -Wl from whole_archive_flag_spec and hope we can get by with + # turning comma into space.. + wl= + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec"; then + eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" + reload_conv_objs=$reload_objs\ `$ECHO "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'` + else + gentop="$output_objdir/${obj}x" + generated="$generated $gentop" + + func_extract_archives $gentop $convenience + reload_conv_objs="$reload_objs $func_extract_archives_result" + fi + fi + + # Create the old-style object. + reload_objs="$objs$old_deplibs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test + + output="$obj" + func_execute_cmds "$reload_cmds" 'exit $?' + + # Exit if we aren't doing a library object file. + if test -z "$libobj"; then + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + fi + + if test "$build_libtool_libs" != yes; then + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + # Create an invalid libtool object if no PIC, so that we don't + # accidentally link it into a program. + # $show "echo timestamp > $libobj" + # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? + exit $EXIT_SUCCESS + fi + + if test -n "$pic_flag" || test "$pic_mode" != default; then + # Only do commands if we really have different PIC objects. + reload_objs="$libobjs $reload_conv_objs" + output="$libobj" + func_execute_cmds "$reload_cmds" 'exit $?' + fi + + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + ;; + + prog) + case $host in + *cygwin*) func_stripname '' '.exe' "$output" + output=$func_stripname_result.exe;; + esac + test -n "$vinfo" && \ + func_warning "\`-version-info' is ignored for programs" + + test -n "$release" && \ + func_warning "\`-release' is ignored for programs" + + test "$preload" = yes \ + && test "$dlopen_support" = unknown \ + && test "$dlopen_self" = unknown \ + && test "$dlopen_self_static" = unknown && \ + func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library is the System framework + compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` + finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` + ;; + esac + + case $host in + *-*-darwin*) + # Don't allow lazy linking, it breaks C++ global constructors + # But is supposedly fixed on 10.4 or later (yay!). + if test "$tagname" = CXX ; then + case ${MACOSX_DEPLOYMENT_TARGET-10.0} in + 10.[0123]) + compile_command="$compile_command ${wl}-bind_at_load" + finalize_command="$finalize_command ${wl}-bind_at_load" + ;; + esac + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $compile_deplibs " in + *" -L$path/$objdir "*) + new_libs="$new_libs -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $compile_deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$new_libs $deplib" ;; + esac + ;; + *) new_libs="$new_libs $deplib" ;; + esac + done + compile_deplibs="$new_libs" + + + compile_command="$compile_command $compile_deplibs" + finalize_command="$finalize_command $finalize_deplibs" + + if test -n "$rpath$xrpath"; then + # If the user specified any rpath flags, then add them. + for libdir in $rpath $xrpath; do + # This is the magic to use -rpath. + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" ;; + esac + done + fi + + # Now hardcode the library paths + rpath= + hardcode_libdirs= + for libdir in $compile_rpath $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + rpath="$rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) perm_rpath="$perm_rpath $libdir" ;; + esac + fi + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$libdir:"*) ;; + ::) dllsearchpath=$libdir;; + *) dllsearchpath="$dllsearchpath:$libdir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) dllsearchpath="$dllsearchpath:$testbindir";; + esac + ;; + esac + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + compile_rpath="$rpath" + + rpath= + hardcode_libdirs= + for libdir in $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + rpath="$rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$finalize_perm_rpath " in + *" $libdir "*) ;; + *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + finalize_rpath="$rpath" + + if test -n "$libobjs" && test "$build_old_libs" = yes; then + # Transform all the library objects into standard objects. + compile_command=`$ECHO "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + finalize_command=`$ECHO "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + fi + + func_generate_dlsyms "$outputname" "@PROGRAM@" "no" + + # template prelinking step + if test -n "$prelink_cmds"; then + func_execute_cmds "$prelink_cmds" 'exit $?' + fi + + wrappers_required=yes + case $host in + *cygwin* | *mingw* ) + if test "$build_libtool_libs" != yes; then + wrappers_required=no + fi + ;; + *cegcc) + # Disable wrappers for cegcc, we are cross compiling anyway. + wrappers_required=no + ;; + *) + if test "$need_relink" = no || test "$build_libtool_libs" != yes; then + wrappers_required=no + fi + ;; + esac + if test "$wrappers_required" = no; then + # Replace the output file specification. + compile_command=`$ECHO "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` + link_command="$compile_command$compile_rpath" + + # We have no uninstalled library dependencies, so finalize right now. + exit_status=0 + func_show_eval "$link_command" 'exit_status=$?' + + # Delete the generated files. + if test -f "$output_objdir/${outputname}S.${objext}"; then + func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' + fi + + exit $exit_status + fi + + if test -n "$compile_shlibpath$finalize_shlibpath"; then + compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" + fi + if test -n "$finalize_shlibpath"; then + finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" + fi + + compile_var= + finalize_var= + if test -n "$runpath_var"; then + if test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + rpath="$rpath$dir:" + done + compile_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + if test -n "$finalize_perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $finalize_perm_rpath; do + rpath="$rpath$dir:" + done + finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + fi + + if test "$no_install" = yes; then + # We don't need to create a wrapper script. + link_command="$compile_var$compile_command$compile_rpath" + # Replace the output file specification. + link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` + # Delete the old output file. + $opt_dry_run || $RM $output + # Link the executable and exit + func_show_eval "$link_command" 'exit $?' + exit $EXIT_SUCCESS + fi + + if test "$hardcode_action" = relink; then + # Fast installation is not supported + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + + func_warning "this platform does not like uninstalled shared libraries" + func_warning "\`$output' will be relinked during installation" + else + if test "$fast_install" != no; then + link_command="$finalize_var$compile_command$finalize_rpath" + if test "$fast_install" = yes; then + relink_command=`$ECHO "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` + else + # fast_install is set to needless + relink_command= + fi + else + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + fi + fi + + # Replace the output file specification. + link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` + + # Delete the old output files. + $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname + + func_show_eval "$link_command" 'exit $?' + + # Now create the wrapper script. + func_verbose "creating $output" + + # Quote the relink command for shipping. + if test -n "$relink_command"; then + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_for_eval "$var_value" + relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" + fi + done + relink_command="(cd `pwd`; $relink_command)" + relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` + fi + + # Quote $ECHO for shipping. + if test "X$ECHO" = "X$SHELL $progpath --fallback-echo"; then + case $progpath in + [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";; + *) qecho="$SHELL `pwd`/$progpath --fallback-echo";; + esac + qecho=`$ECHO "X$qecho" | $Xsed -e "$sed_quote_subst"` + else + qecho=`$ECHO "X$ECHO" | $Xsed -e "$sed_quote_subst"` + fi + + # Only actually do things if not in dry run mode. + $opt_dry_run || { + # win32 will think the script is a binary if it has + # a .exe suffix, so we strip it off here. + case $output in + *.exe) func_stripname '' '.exe' "$output" + output=$func_stripname_result ;; + esac + # test for cygwin because mv fails w/o .exe extensions + case $host in + *cygwin*) + exeext=.exe + func_stripname '' '.exe' "$outputname" + outputname=$func_stripname_result ;; + *) exeext= ;; + esac + case $host in + *cygwin* | *mingw* ) + func_dirname_and_basename "$output" "" "." + output_name=$func_basename_result + output_path=$func_dirname_result + cwrappersource="$output_path/$objdir/lt-$output_name.c" + cwrapper="$output_path/$output_name.exe" + $RM $cwrappersource $cwrapper + trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 + + func_emit_cwrapperexe_src > $cwrappersource + + # The wrapper executable is built using the $host compiler, + # because it contains $host paths and files. If cross- + # compiling, it, like the target executable, must be + # executed on the $host or under an emulation environment. + $opt_dry_run || { + $LTCC $LTCFLAGS -o $cwrapper $cwrappersource + $STRIP $cwrapper + } + + # Now, create the wrapper script for func_source use: + func_ltwrapper_scriptname $cwrapper + $RM $func_ltwrapper_scriptname_result + trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 + $opt_dry_run || { + # note: this script will not be executed, so do not chmod. + if test "x$build" = "x$host" ; then + $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result + else + func_emit_wrapper no > $func_ltwrapper_scriptname_result + fi + } + ;; + * ) + $RM $output + trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 + + func_emit_wrapper no > $output + chmod +x $output + ;; + esac + } + exit $EXIT_SUCCESS + ;; + esac + + # See if we need to build an old-fashioned archive. + for oldlib in $oldlibs; do + + if test "$build_libtool_libs" = convenience; then + oldobjs="$libobjs_save $symfileobj" + addlibs="$convenience" + build_libtool_libs=no + else + if test "$build_libtool_libs" = module; then + oldobjs="$libobjs_save" + build_libtool_libs=no + else + oldobjs="$old_deplibs $non_pic_objects" + if test "$preload" = yes && test -f "$symfileobj"; then + oldobjs="$oldobjs $symfileobj" + fi + fi + addlibs="$old_convenience" + fi + + if test -n "$addlibs"; then + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + + func_extract_archives $gentop $addlibs + oldobjs="$oldobjs $func_extract_archives_result" + fi + + # Do each command in the archive commands. + if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then + cmds=$old_archive_from_new_cmds + else + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + + func_extract_archives $gentop $dlprefiles + oldobjs="$oldobjs $func_extract_archives_result" + fi + + # POSIX demands no paths to be encoded in archives. We have + # to avoid creating archives with duplicate basenames if we + # might have to extract them afterwards, e.g., when creating a + # static archive out of a convenience library, or when linking + # the entirety of a libtool archive into another (currently + # not supported by libtool). + if (for obj in $oldobjs + do + func_basename "$obj" + $ECHO "$func_basename_result" + done | sort | sort -uc >/dev/null 2>&1); then + : + else + $ECHO "copying selected object files to avoid basename conflicts..." + gentop="$output_objdir/${outputname}x" + generated="$generated $gentop" + func_mkdir_p "$gentop" + save_oldobjs=$oldobjs + oldobjs= + counter=1 + for obj in $save_oldobjs + do + func_basename "$obj" + objbase="$func_basename_result" + case " $oldobjs " in + " ") oldobjs=$obj ;; + *[\ /]"$objbase "*) + while :; do + # Make sure we don't pick an alternate name that also + # overlaps. + newobj=lt$counter-$objbase + func_arith $counter + 1 + counter=$func_arith_result + case " $oldobjs " in + *[\ /]"$newobj "*) ;; + *) if test ! -f "$gentop/$newobj"; then break; fi ;; + esac + done + func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" + oldobjs="$oldobjs $gentop/$newobj" + ;; + *) oldobjs="$oldobjs $obj" ;; + esac + done + fi + eval cmds=\"$old_archive_cmds\" + + func_len " $cmds" + len=$func_len_result + if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + cmds=$old_archive_cmds + else + # the command line is too long to link in one step, link in parts + func_verbose "using piecewise archive linking..." + save_RANLIB=$RANLIB + RANLIB=: + objlist= + concat_cmds= + save_oldobjs=$oldobjs + oldobjs= + # Is there a better way of finding the last object in the list? + for obj in $save_oldobjs + do + last_oldobj=$obj + done + eval test_cmds=\"$old_archive_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + for obj in $save_oldobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + func_append objlist " $obj" + if test "$len" -lt "$max_cmd_len"; then + : + else + # the above command should be used before it gets too long + oldobjs=$objlist + if test "$obj" = "$last_oldobj" ; then + RANLIB=$save_RANLIB + fi + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" + objlist= + len=$len0 + fi + done + RANLIB=$save_RANLIB + oldobjs=$objlist + if test "X$oldobjs" = "X" ; then + eval cmds=\"\$concat_cmds\" + else + eval cmds=\"\$concat_cmds~\$old_archive_cmds\" + fi + fi + fi + func_execute_cmds "$cmds" 'exit $?' + done + + test -n "$generated" && \ + func_show_eval "${RM}r$generated" + + # Now create the libtool archive. + case $output in + *.la) + old_library= + test "$build_old_libs" = yes && old_library="$libname.$libext" + func_verbose "creating $output" + + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_for_eval "$var_value" + relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" + fi + done + # Quote the link command for shipping. + relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" + relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` + if test "$hardcode_automatic" = yes ; then + relink_command= + fi + + # Only create the output if not a dry run. + $opt_dry_run || { + for installed in no yes; do + if test "$installed" = yes; then + if test -z "$install_libdir"; then + break + fi + output="$output_objdir/$outputname"i + # Replace all uninstalled libtool libraries with the installed ones + newdependency_libs= + for deplib in $dependency_libs; do + case $deplib in + *.la) + func_basename "$deplib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + test -z "$libdir" && \ + func_fatal_error "\`$deplib' is not a valid libtool archive" + if test "x$EGREP" = x ; then + EGREP=egrep + fi + # We do not want portage's install root ($D) present. Check only for + # this if the .la is being installed. + if test "$installed" = yes && test "$D"; then + eval mynewdependency_lib=`echo "$libdir/$name" |sed -e "s:$D:/:g" -e 's:/\+:/:g'` + else + mynewdependency_lib="$libdir/$name" + fi + # Do not add duplicates + if test "$mynewdependency_lib"; then + my_little_ninja_foo_1=`echo $newdependency_libs |$EGREP -e "$mynewdependency_lib"` + if test -z "$my_little_ninja_foo_1"; then + newdependency_libs="$newdependency_libs $mynewdependency_lib" + fi + fi + ;; + *) + if test "$installed" = yes; then + # Rather use S=WORKDIR if our version of portage supports it. + # This is because some ebuild (gcc) do not use $S as buildroot. + if test "$PWORKDIR"; then + S="$PWORKDIR" + fi + # We do not want portage's build root ($S) present. + my_little_ninja_foo_2=`echo $deplib |$EGREP -e "$S"` + # We do not want portage's install root ($D) present. + my_little_ninja_foo_3=`echo $deplib |$EGREP -e "$D"` + if test -n "$my_little_ninja_foo_2" && test "$S"; then + mynewdependency_lib="" + elif test -n "$my_little_ninja_foo_3" && test "$D"; then + eval mynewdependency_lib=`echo "$deplib" |sed -e "s:$D:/:g" -e 's:/\+:/:g'` + else + mynewdependency_lib="$deplib" + fi + else + mynewdependency_lib="$deplib" + fi + # Do not add duplicates + if test "$mynewdependency_lib"; then + my_little_ninja_foo_4=`echo $newdependency_libs |$EGREP -e "$mynewdependency_lib"` + if test -z "$my_little_ninja_foo_4"; then + newdependency_libs="$newdependency_libs $mynewdependency_lib" + fi + fi + ;; + esac + done + dependency_libs="$newdependency_libs" + newdlfiles= + + for lib in $dlfiles; do + case $lib in + *.la) + func_basename "$lib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "\`$lib' is not a valid libtool archive" + newdlfiles="$newdlfiles $libdir/$name" + ;; + *) newdlfiles="$newdlfiles $lib" ;; + esac + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + *.la) + # Only pass preopened files to the pseudo-archive (for + # eventual linking with the app. that links it) if we + # didn't already link the preopened objects directly into + # the library: + func_basename "$lib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "\`$lib' is not a valid libtool archive" + newdlprefiles="$newdlprefiles $libdir/$name" + ;; + esac + done + dlprefiles="$newdlprefiles" + else + newdlfiles= + for lib in $dlfiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + newdlfiles="$newdlfiles $abs" + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + newdlprefiles="$newdlprefiles $abs" + done + dlprefiles="$newdlprefiles" + fi + $RM $output + # place dlname in correct position for cygwin + tdlname=$dlname + case $host,$output,$installed,$module,$dlname in + *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;; + esac + # Do not add duplicates + if test "$installed" = yes && test "$D"; then + install_libdir=`echo "$install_libdir" |sed -e "s:$D:/:g" -e 's:/\+:/:g'` + fi + $ECHO > $output "\ +# $outputname - a libtool library file +# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION +# +# Please DO NOT delete this file! +# It is necessary for linking the library. + +# The name that we can dlopen(3). +dlname='$tdlname' + +# Names of this library. +library_names='$library_names' + +# The name of the static archive. +old_library='$old_library' + +# Linker flags that can not go in dependency_libs. +inherited_linker_flags='$new_inherited_linker_flags' + +# Libraries that this one depends upon. +dependency_libs='$dependency_libs' + +# Names of additional weak libraries provided by this library +weak_library_names='$weak_libs' + +# Version information for $libname. +current=$current +age=$age +revision=$revision + +# Is this an already installed library? +installed=$installed + +# Should we warn about portability when linking against -modules? +shouldnotlink=$module + +# Files to dlopen/dlpreopen +dlopen='$dlfiles' +dlpreopen='$dlprefiles' + +# Directory that this library needs to be installed in: +libdir='$install_libdir'" + if test "$installed" = no && test "$need_relink" = yes; then + $ECHO >> $output "\ +relink_command=\"$relink_command\"" + fi + done + } + + # Do a symbolic link so that the libtool archive can be found in + # LD_LIBRARY_PATH before the program is installed. + func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' + ;; + esac + exit $EXIT_SUCCESS +} + +{ test "$mode" = link || test "$mode" = relink; } && + func_mode_link ${1+"$@"} + + +# func_mode_uninstall arg... +func_mode_uninstall () +{ + $opt_debug + RM="$nonopt" + files= + rmforce= + exit_status=0 + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + for arg + do + case $arg in + -f) RM="$RM $arg"; rmforce=yes ;; + -*) RM="$RM $arg" ;; + *) files="$files $arg" ;; + esac + done + + test -z "$RM" && \ + func_fatal_help "you must specify an RM program" + + rmdirs= + + origobjdir="$objdir" + for file in $files; do + func_dirname "$file" "" "." + dir="$func_dirname_result" + if test "X$dir" = X.; then + objdir="$origobjdir" + else + objdir="$dir/$origobjdir" + fi + func_basename "$file" + name="$func_basename_result" + test "$mode" = uninstall && objdir="$dir" + + # Remember objdir for removal later, being careful to avoid duplicates + if test "$mode" = clean; then + case " $rmdirs " in + *" $objdir "*) ;; + *) rmdirs="$rmdirs $objdir" ;; + esac + fi + + # Don't error if the file doesn't exist and rm -f was used. + if { test -L "$file"; } >/dev/null 2>&1 || + { test -h "$file"; } >/dev/null 2>&1 || + test -f "$file"; then + : + elif test -d "$file"; then + exit_status=1 + continue + elif test "$rmforce" = yes; then + continue + fi + + rmfiles="$file" + + case $name in + *.la) + # Possibly a libtool archive, so verify it. + if func_lalib_p "$file"; then + func_source $dir/$name + + # Delete the libtool libraries and symlinks. + for n in $library_names; do + rmfiles="$rmfiles $objdir/$n" + done + test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library" + + case "$mode" in + clean) + case " $library_names " in + # " " in the beginning catches empty $dlname + *" $dlname "*) ;; + *) rmfiles="$rmfiles $objdir/$dlname" ;; + esac + test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i" + ;; + uninstall) + if test -n "$library_names"; then + # Do each command in the postuninstall commands. + func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' + fi + + if test -n "$old_library"; then + # Do each command in the old_postuninstall commands. + func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' + fi + # FIXME: should reinstall the best remaining shared library. + ;; + esac + fi + ;; + + *.lo) + # Possibly a libtool object, so verify it. + if func_lalib_p "$file"; then + + # Read the .lo file + func_source $dir/$name + + # Add PIC object to the list of files to remove. + if test -n "$pic_object" && + test "$pic_object" != none; then + rmfiles="$rmfiles $dir/$pic_object" + fi + + # Add non-PIC object to the list of files to remove. + if test -n "$non_pic_object" && + test "$non_pic_object" != none; then + rmfiles="$rmfiles $dir/$non_pic_object" + fi + fi + ;; + + *) + if test "$mode" = clean ; then + noexename=$name + case $file in + *.exe) + func_stripname '' '.exe' "$file" + file=$func_stripname_result + func_stripname '' '.exe' "$name" + noexename=$func_stripname_result + # $file with .exe has already been added to rmfiles, + # add $file without .exe + rmfiles="$rmfiles $file" + ;; + esac + # Do a test to see if this is a libtool program. + if func_ltwrapper_p "$file"; then + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + relink_command= + func_source $func_ltwrapper_scriptname_result + rmfiles="$rmfiles $func_ltwrapper_scriptname_result" + else + relink_command= + func_source $dir/$noexename + fi + + # note $name still contains .exe if it was in $file originally + # as does the version of $file that was added into $rmfiles + rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}" + if test "$fast_install" = yes && test -n "$relink_command"; then + rmfiles="$rmfiles $objdir/lt-$name" + fi + if test "X$noexename" != "X$name" ; then + rmfiles="$rmfiles $objdir/lt-${noexename}.c" + fi + fi + fi + ;; + esac + func_show_eval "$RM $rmfiles" 'exit_status=1' + done + objdir="$origobjdir" + + # Try to remove the ${objdir}s in the directories where we deleted files + for dir in $rmdirs; do + if test -d "$dir"; then + func_show_eval "rmdir $dir >/dev/null 2>&1" + fi + done + + exit $exit_status +} + +{ test "$mode" = uninstall || test "$mode" = clean; } && + func_mode_uninstall ${1+"$@"} + +test -z "$mode" && { + help="$generic_help" + func_fatal_help "you must specify a MODE" +} + +test -z "$exec_cmd" && \ + func_fatal_help "invalid operation mode \`$mode'" + +if test -n "$exec_cmd"; then + eval exec "$exec_cmd" + exit $EXIT_FAILURE +fi + +exit $exit_status + + +# The TAGs below are defined such that we never get into a situation +# in which we disable both kinds of libraries. Given conflicting +# choices, we go for a static library, that is the most portable, +# since we can't tell whether shared libraries were disabled because +# the user asked for that or because the platform doesn't support +# them. This is particularly important on AIX, because we don't +# support having both static and shared libraries enabled at the same +# time on that platform, so we default to a shared-only configuration. +# If a disable-shared tag is given, we'll fallback to a static-only +# configuration. But we'll never go from static-only to shared-only. + +# ### BEGIN LIBTOOL TAG CONFIG: disable-shared +build_libtool_libs=no +build_old_libs=yes +# ### END LIBTOOL TAG CONFIG: disable-shared + +# ### BEGIN LIBTOOL TAG CONFIG: disable-static +build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` +# ### END LIBTOOL TAG CONFIG: disable-static + +# Local Variables: +# mode:shell-script +# sh-indentation:2 +# End: +# vi:sw=2 + diff --git a/components/external/SQLite-3.8.1/make/sqlite3.pc b/components/external/SQLite-3.8.1/make/sqlite3.pc new file mode 100644 index 0000000000000000000000000000000000000000..78cd06c1757eb8dfd3c50e3adb8f31cb352c4f6f --- /dev/null +++ b/components/external/SQLite-3.8.1/make/sqlite3.pc @@ -0,0 +1,13 @@ +# Package Information for pkg-config + +prefix=/usr/local +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include + +Name: SQLite +Description: SQL database engine +Version: 3.8.1 +Libs: -L${libdir} -lsqlite3 +Libs.private: +Cflags: -I${includedir} diff --git a/components/external/SQLite-3.8.1/manifest b/components/external/SQLite-3.8.1/manifest new file mode 100644 index 0000000000000000000000000000000000000000..36384669c1b528f8ef248f368de7e3709bb2a448 --- /dev/null +++ b/components/external/SQLite-3.8.1/manifest @@ -0,0 +1,1135 @@ +C Version\s3.8.1 +D 2013-10-17T12:57:35.458 +F Makefile.arm-wince-mingw32ce-gcc d6df77f1f48d690bd73162294bbba7f59507c72f +F Makefile.in 0522b53cdc1fcfc18f3a98e0246add129136c654 +F Makefile.linux-gcc 91d710bdc4998cb015f39edf3cb314ec4f4d7e23 +F Makefile.msc ec5d662ed5a15ff819928c0495017af13910d7b6 +F Makefile.vxworks db21ed42a01d5740e656b16f92cb5d8d5e5dd315 +F README cd04a36fbc7ea56932a4052d7d0b7f09f27c33d6 +F VERSION a8d1f6839521130dc73c5408cdd24bcfd791df34 +F aclocal.m4 a5c22d164aff7ed549d53a90fa56d56955281f50 +F addopcodes.awk 17dc593f791f874d2c23a0f9360850ded0286531 +F art/sqlite370.eps aa97a671332b432a54e1d74ff5e8775be34200c2 +F art/sqlite370.ico af56c1d00fee7cd4753e8631ed60703ed0fc6e90 +F art/sqlite370.jpg d512473dae7e378a67e28ff96a34da7cb331def2 +F autoconf/INSTALL 83e4a25da9fd053c7b3665eaaaf7919707915903 +F autoconf/Makefile.am 8fc2972d92769cf20ab8e4a73ea901b84d69bf44 +F autoconf/README 14458f1046c118efa721aadec5f227e876d3cd38 +F autoconf/README.first 47dd53221023b18c836ab00dba6e00bd86132453 +F autoconf/config.guess 94cc57e2a3fdb9c235b362ace86d77e89d188cad x +F autoconf/config.sub 1efb390a8fb4bfafd74783a15a8fb5311c84300e x +F autoconf/configure.ac ba3e99ba1a8171d0682b68443517088fc5d6f13a +F autoconf/depcomp 0b26f101e3bc9fd1ff0be1da9fb4a82371142f92 x +F autoconf/install-sh 06ee6336e63bb845c8439d777c32eb2eccc4fbf1 x +F autoconf/ltmain.sh 7a658a24028f02331c1d2446562758083c5eadd1 +F autoconf/missing d7c9981a81af13370d4ed152b24c0a82b7028585 x +F autoconf/tea/Makefile.in 5c3b0bdfb66c20d55ebff59d1718864461570ca9 +F autoconf/tea/README 3e9a3c060f29a44344ab50aec506f4db903fb873 +F autoconf/tea/aclocal.m4 52c47aac44ce0ddb1f918b6993e8beb8eee88f43 +F autoconf/tea/configure.in e0466b881b53f31f5a4a69e7a91ad130902fb359 +F autoconf/tea/doc/sqlite3.n e268faa1691c33663d3a7faf9fa30673d14bd879 +F autoconf/tea/license.terms 13bd403c9610fd2b76ece0ab50c4c5eda933d523 +F autoconf/tea/pkgIndex.tcl.in 3ef61715cf1c7bdcff56947ffadb26bc991ca39d +F autoconf/tea/tclconfig/install-sh b087e5c4b92820c60bffb74acc1d9c2d40d80b8f +F autoconf/tea/tclconfig/tcl.m4 a68179d7cc45524fa59db428a36610e20bdba808 +F autoconf/tea/win/makefile.vc f89d0184d0eee5f7e356ea407964dcd139939928 +F autoconf/tea/win/nmakehlp.c 2070e086f39866b353a482d3a14dedaf26196506 +F autoconf/tea/win/rules.vc c511f222b80064096b705dbeb97060ee1d6b6d63 +F config.guess 226d9a188c6196f3033ffc651cbc9dcee1a42977 +F config.h.in 0921066a13130082764ab4ab6456f7b5bebe56de +F config.sub 9ebe4c3b3dab6431ece34f16828b594fb420da55 +F configure d9bb8485d40dd905e09c895692a0699628abace8 x +F configure.ac 4cf9f60785143fa141b10962ccc885d973792e9a +F contrib/sqlitecon.tcl 210a913ad63f9f991070821e599d600bd913e0ad +F doc/lemon.html 334dbf6621b8fb8790297ec1abf3cfa4621709d1 +F doc/pager-invariants.txt 27fed9a70ddad2088750c4a2b493b63853da2710 +F doc/vfs-shm.txt e101f27ea02a8387ce46a05be2b1a902a021d37a +F ext/README.txt 913a7bd3f4837ab14d7e063304181787658b14e1 +F ext/async/README.txt e12275968f6fde133a80e04387d0e839b0c51f91 +F ext/async/sqlite3async.c b5a3e30f538a9ffe81538b3063b4d5963f9bb422 +F ext/async/sqlite3async.h f489b080af7e72aec0e1ee6f1d98ab6cf2e4dcef +F ext/fts1/README.txt 20ac73b006a70bcfd80069bdaf59214b6cf1db5e +F ext/fts1/ft_hash.c 3927bd880e65329bdc6f506555b228b28924921b +F ext/fts1/ft_hash.h 06df7bba40dadd19597aa400a875dbc2fed705ea +F ext/fts1/fts1.c f7739dc37500a613cc0dab8fc04d1b5577d02998 +F ext/fts1/fts1.h 6060b8f62c1d925ea8356cb1a6598073eb9159a6 +F ext/fts1/fts1_hash.c 3196cee866edbebb1c0521e21672e6d599965114 +F ext/fts1/fts1_hash.h e7f0d761353996a8175eda351104acfde23afcb0 +F ext/fts1/fts1_porter.c b1c7304b8988ba3f764a147cdd32043b4913ea7b +F ext/fts1/fts1_tokenizer.h fdea722c38a9f82ed921642981234f666e47919c +F ext/fts1/fts1_tokenizer1.c fd00d1fe4dc30dfc5c64cba695ce34f4af20d2fa +F ext/fts1/fulltext.c 37698e1909584f6d8ea67d1485e3ad39dbf42d19 +F ext/fts1/fulltext.h 08525a47852d1d62a0be81d3fc3fe2d23b094efd +F ext/fts1/simple_tokenizer.c 1844d72f7194c3fd3d7e4173053911bf0661b70d +F ext/fts1/tokenizer.h 0c53421b832366d20d720d21ea3e1f6e66a36ef9 +F ext/fts2/README.tokenizers 21e3684ea5a095b55d70f6878b4ce6af5932dfb7 +F ext/fts2/README.txt 8c18f41574404623b76917b9da66fcb0ab38328d +F ext/fts2/fts2.c 72c816a9ae448049fbbe8f18a85698765fc7956c +F ext/fts2/fts2.h da5f76c65163301d1068a971fd32f4119e3c95fa +F ext/fts2/fts2_hash.c 011a1d32de45bb1b519a1fd0048e857d6a843558 +F ext/fts2/fts2_hash.h 1824b99dfd8d0225facbdb26a2c87289b2e7dcf8 +F ext/fts2/fts2_icu.c 51c5cd3c04954badd329fa738c95fcdb717b5188 +F ext/fts2/fts2_porter.c 2cd4a507bf3c3085fe66f59b0f2a325f65aaacf5 +F ext/fts2/fts2_tokenizer.c 3dbe8058e97afb55fff3ea844120ce3208b114cc +F ext/fts2/fts2_tokenizer.h 27a1a99ca2d615cf7e142839b8d79e8751b4529e +F ext/fts2/fts2_tokenizer1.c 07e223eecb483d448313b5f1553a4f299a7fb7a1 +F ext/fts2/mkfts2amal.tcl 974d5d438cb3f7c4a652639262f82418c1e4cff0 +F ext/fts3/README.content fdc666a70d5257a64fee209f97cf89e0e6e32b51 +F ext/fts3/README.syntax a19711dc5458c20734b8e485e75fb1981ec2427a +F ext/fts3/README.tokenizers e0a8b81383ea60d0334d274fadf305ea14a8c314 +F ext/fts3/README.txt 8c18f41574404623b76917b9da66fcb0ab38328d +F ext/fts3/fts3.c f25ae5729d40cc4e661c0a552685038f27e72bc9 +F ext/fts3/fts3.h 3a10a0af180d502cecc50df77b1b22df142817fe +F ext/fts3/fts3Int.h 8689f7cf85020e7f88d1e761eeac480c3b0ea7ad +F ext/fts3/fts3_aux.c 5c211e17a64885faeb16b9ba7772f9d5445c2365 +F ext/fts3/fts3_expr.c f8eb1046063ba342c7114eba175cabb31c4a64e7 +F ext/fts3/fts3_hash.c 8dd2d06b66c72c628c2732555a32bc0943114914 +F ext/fts3/fts3_hash.h 39cf6874dc239d6b4e30479b1975fe5b22a3caaf +F ext/fts3/fts3_icu.c e319e108661147bcca8dd511cd562f33a1ba81b5 +F ext/fts3/fts3_porter.c a465b49fcb8249a755792f87516eff182efa42b3 +F ext/fts3/fts3_snippet.c e8ee8c101dd9cfbc9568d134e869d2bd2f7f6d4d +F ext/fts3/fts3_term.c a521f75132f9a495bdca1bdd45949b3191c52763 +F ext/fts3/fts3_test.c f9a1a1702db1bfad3e2d0064746eeb808f125489 +F ext/fts3/fts3_tokenize_vtab.c 011170fe9eba5ff062f1a31d3188e00267716706 +F ext/fts3/fts3_tokenizer.c bbdc731bc91338050675c6d1da9ab82147391e16 +F ext/fts3/fts3_tokenizer.h 64c6ef6c5272c51ebe60fc607a896e84288fcbc3 +F ext/fts3/fts3_tokenizer1.c 5c98225a53705e5ee34824087478cf477bdb7004 +F ext/fts3/fts3_unicode.c 92391b4b4fb043564c6539ea9b8661e3bcba47b9 +F ext/fts3/fts3_unicode2.c 0113d3acf13429e6dc38e0647d1bc71211c31a4d +F ext/fts3/fts3_write.c 17817f0cb6c8555e1be5e073fbddf676c60f4ea9 +F ext/fts3/fts3speed.tcl b54caf6a18d38174f1a6e84219950d85e98bb1e9 +F ext/fts3/mkfts3amal.tcl 252ecb7fe6467854f2aa237bf2c390b74e71f100 +F ext/fts3/tool/fts3view.c 6cfc5b67a5f0e09c0d698f9fd012c784bfaa9197 +F ext/fts3/unicode/CaseFolding.txt 8c678ca52ecc95e16bc7afc2dbf6fc9ffa05db8c +F ext/fts3/unicode/UnicodeData.txt cd07314edb62d49fde34debdaf92fa2aa69011e7 +F ext/fts3/unicode/mkunicode.tcl dc6f268eb526710e2c6e496c372471d773d0c368 +F ext/icu/README.txt d9fbbad0c2f647c3fdf715fc9fd64af53aedfc43 +F ext/icu/icu.c d415ccf984defeb9df2c0e1afcfaa2f6dc05eacb +F ext/icu/sqliteicu.h 728867a802baa5a96de7495e9689a8e01715ef37 +F ext/misc/amatch.c 678056a4bfcd83c4e82dea81d37543cd1d6dbee1 +F ext/misc/closure.c 636024302cde41b2bf0c542f81c40c624cfb7012 +F ext/misc/fuzzer.c 136533c53cfce0957f0b48fa11dba27e21c5c01d +F ext/misc/ieee754.c b0362167289170627659e84173f5d2e8fee8566e +F ext/misc/nextchar.c 35c8b8baacb96d92abbb34a83a997b797075b342 +F ext/misc/percentile.c bcbee3c061b884eccb80e21651daaae8e1e43c63 +F ext/misc/regexp.c af92cdaa5058fcec1451e49becc7ba44dba023dc +F ext/misc/rot13.c 1ac6f95f99b575907b9b09c81a349114cf9be45a +F ext/misc/spellfix.c 5e1d547e9a2aed13897fa91bac924333f62fd2d9 +F ext/misc/totype.c 4a167594e791abeed95e0a8db028822b5e8fe512 +F ext/misc/vfslog.c 1abb192d8d4bd323adbddec0c024580496b51b7a +F ext/misc/vtshim.c babb0dc2bf116029e3e7c9a618b8a1377045303e +F ext/misc/wholenumber.c 784b12543d60702ebdd47da936e278aa03076212 +F ext/rtree/README 6315c0d73ebf0ec40dedb5aa0e942bc8b54e3761 +F ext/rtree/rtree.c db516d7e59a14c92df10b552789509f2b632df3a +F ext/rtree/rtree.h 834dbcb82dc85b2481cde6a07cdadfddc99e9b9e +F ext/rtree/rtree1.test cf679265ecafff494a768ac9c2f43a70915a6290 +F ext/rtree/rtree2.test acbb3a4ce0f4fbc2c304d2b4b784cfa161856bba +F ext/rtree/rtree3.test a494da55c30ee0bc9b01a91c80c81b387b22d2dc +F ext/rtree/rtree4.test c8fe384f60ebd49540a5fecc990041bf452eb6e0 +F ext/rtree/rtree5.test 6a510494f12454bf57ef28f45bc7764ea279431e +F ext/rtree/rtree6.test fb94b98c1145b7f44c72635d11492f35349ab27e +F ext/rtree/rtree7.test 1fa710b9e6bf997a0c1a537b81be7bb6fded1971 +F ext/rtree/rtree8.test db79c812f9e4a11f9b1f3f9934007884610a713a +F ext/rtree/rtree9.test d86ebf08ff6328895613ed577dd8a2a37c472c34 +F ext/rtree/rtreeA.test ace05e729a36e342d40cf94e9efc7b4723d9dcdf +F ext/rtree/rtreeB.test 983e567b49b5dca165940f66b87e161aa30e82b2 +F ext/rtree/rtree_perf.tcl 6c18c1f23cd48e0f948930c98dfdd37dfccb5195 +F ext/rtree/rtree_util.tcl 06aab2ed5b826545bf215fff90ecb9255a8647ea +F ext/rtree/sqlite3rtree.h c34c1e41d1ab80bb8ad09aae402c9c956871a765 +F ext/rtree/tkt3363.test 142ab96eded44a3615ec79fba98c7bde7d0f96de +F ext/rtree/viewrtree.tcl eea6224b3553599ae665b239bd827e182b466024 +F install-sh 9d4de14ab9fb0facae2f48780b874848cbf2f895 x +F ltmain.sh 3ff0879076df340d2e23ae905484d8c15d5fdea8 +F magic.txt 814d3de5ec227817ff2ad26cbc73159c968a2a58 +F main.mk c6a433cb334bbb019625c137ab5d5e7568b47cff +F mkdll.sh 7d09b23c05d56532e9d44a50868eb4b12ff4f74a +F mkextu.sh 416f9b7089d80e5590a29692c9d9280a10dbad9f +F mkextw.sh d2a981497b404d6498f5ff3e3b1f3816bdfcb338 +F mkopcodec.awk f6fccee29e68493bfd90a2e0466ede5fa94dd2fc +F mkopcodeh.awk e7334b45c023b5ee2efc6e8f479560c2026fa34a +F mkso.sh fd21c06b063bb16a5d25deea1752c2da6ac3ed83 +F mptest/config01.test 3c6adcbc50b991866855f1977ff172eb6d901271 +F mptest/config02.test 4415dfe36c48785f751e16e32c20b077c28ae504 +F mptest/crash01.test cce8e306d8596d5a2e497e27112dae1f6e5e3538 +F mptest/crash02.subtest f4ef05adcd15d60e5d2bd654204f2c008b519df8 +F mptest/mptest.c 499a74af4be293b7c1c7c3d40f332b67227dd739 +F mptest/multiwrite01.test 499ad0310da8dff8e8f98d2e272fc2a8aa741b2e +F spec.template 86a4a43b99ebb3e75e6b9a735d5fd293a24e90ca +F sqlite.pc.in 42b7bf0d02e08b9e77734a47798d1a55a9e0716b +F sqlite3.1 6be1ad09113570e1fc8dcaff84c9b0b337db5ffc +F sqlite3.pc.in 48fed132e7cb71ab676105d2a4dc77127d8c1f3a +F src/alter.c 2af0330bb1b601af7a7789bf7229675fd772a083 +F src/analyze.c f1c5ed1fe128c3f106dcd95e97ee9ef94db7a3fa +F src/attach.c 0a17c9364895316ca4f52d06a97a72c0af1ae8b3 +F src/auth.c 523da7fb4979469955d822ff9298352d6b31de34 +F src/backup.c 2f1987981139bd2f6d8c728d64bf09fb387443c3 +F src/bitvec.c 19a4ba637bd85f8f63fc8c9bae5ade9fb05ec1cb +F src/btmutex.c 976f45a12e37293e32cae0281b15a21d48a8aaa7 +F src/btree.c 509722ce305471b626d3401c0631a808fd33237b +F src/btree.h bfe0e8c5759b4ec77b0d18390064a6ef3cdffaaf +F src/btreeInt.h f038e818bfadf75afbd09819ed93c26a333d39e0 +F src/build.c 8ae900bf021a66ac110f5eb2dcf994d24d1c2061 +F src/callback.c f99a8957ba2adf369645fac0db09ad8adcf1caa2 +F src/complete.c dc1d136c0feee03c2f7550bafc0d29075e36deac +F src/ctime.c ea4b7f3623a0fcb1146e7f245d7410033e86859c +F src/date.c 593c744b2623971e45affd0bde347631bdfa4625 +F src/delete.c 45788c5e48734f2af4acd75a876466e5b9838e34 +F src/expr.c e7338ccffdc391c53ba2d51c5eb6a2f5299e040e +F src/fault.c 160a0c015b6c2629d3899ed2daf63d75754a32bb +F src/fkey.c 5dc10cbaa355753903cd2a64da040f948997ebf8 +F src/func.c 2c47b65e6e00e3e9374942f28254faf8adafe398 +F src/global.c 5caf4deab621abb45b4c607aad1bd21c20aac759 +F src/hash.c ac3470bbf1ca4ae4e306a8ecb0fdf1731810ffe4 +F src/hash.h 8890a25af81fb85a9ad7790d32eedab4b994da22 +F src/hwtime.h d32741c8f4df852c7d959236615444e2b1063b08 +F src/insert.c 9a3f578ffe37f18ef695a06764320db5dc1f0011 +F src/journal.c b4124532212b6952f42eb2c12fa3c25701d8ba8d +F src/legacy.c 0df0b1550b9cc1f58229644735e317ac89131f12 +F src/lempar.c cdf0a000315332fc9b50b62f3b5e22e080a0952b +F src/loadext.c 867c7b330b740c6c917af9956b13b81d0a048303 +F src/main.c 35931467ec026b05babb279cb8a573e62f6fe1a3 +F src/malloc.c 543a8eb5508eaf4cadf55a9b503379eba2088128 +F src/mem0.c 6a55ebe57c46ca1a7d98da93aaa07f99f1059645 +F src/mem1.c 437c7c4af964895d4650f29881df63535caaa1fa +F src/mem2.c dce31758da87ec2cfa52ba4c5df1aed6e07d8e8f +F src/mem3.c 61c9d47b792908c532ca3a62b999cf21795c6534 +F src/mem5.c 0025308a93838022bd5696cf9627ff4e40b19918 +F src/memjournal.c 0683aac6cab6ec2b5374c0db37c0deb2436a3785 +F src/mutex.c d3b66a569368015e0fcb1ac15f81c119f504d3bc +F src/mutex.h 5bc526e19dccc412b7ff04642f6fdad3fdfdabea +F src/mutex_noop.c 7682796b7d8d39bf1c138248858efcd10c9e1553 +F src/mutex_unix.c c3a4e00f96ba068a8dbef34084465979aaf369cc +F src/mutex_w32.c 6108c88e1cb38d8fbb3534b170793815cbedbf97 +F src/notify.c 976dd0f6171d4588e89e874fcc765e92914b6d30 +F src/os.c b4ad71336fd96f97776f75587cd9e8218288f5be +F src/os.h 4a46270a64e9193af4a0aaa3bc2c66dc07c29b3f +F src/os_common.h 92815ed65f805560b66166e3583470ff94478f04 +F src/os_unix.c 243fb37f47dc072fc59839ea241ff0a17c8d76e6 +F src/os_win.c b159b5249d9f70607d961bbdd1dbba789c75812c +F src/pager.c 2aa4444ffe86e9282d03bc349a4a5e49bd77c0e8 +F src/pager.h f094af9f6ececfaa8a1e93876905a4f34233fb0c +F src/parse.y a97566d6da75075589a7c716d1bda14b586cf8da +F src/pcache.c f8043b433a57aba85384a531e3937a804432a346 +F src/pcache.h a5e4f5d9f5d592051d91212c5949517971ae6222 +F src/pcache1.c a467393909a4ed7ca9de066d85ba5c5b04a5be63 +F src/pragma.c 64d3d1f8b4ed144ba85c061d00d96d6be8aa2fea +F src/prepare.c fa6988589f39af8504a61731614cd4f6ae71554f +F src/printf.c da9119eb31a187a4b99f60aa4a225141c0ebb74b +F src/random.c 0b2dbc37fdfbfa6bd455b091dfcef5bdb32dba68 +F src/resolve.c 572585a96bf282bb9c3d9e08785ec3cae21dc488 +F src/rowset.c 64655f1a627c9c212d9ab497899e7424a34222e0 +F src/select.c 15127b54cc11defb2cddef6914e1f384501a61c4 +F src/shell.c 6f11f0e9ded63d48e306f2c6858c521e568a47bb +F src/sqlite.h.in 4c6eb96fded1d56a27cec04b6b6803789eb28f54 +F src/sqlite3.rc 11094cc6a157a028b301a9f06b3d03089ea37c3e +F src/sqlite3ext.h 886f5a34de171002ad46fae8c36a7d8051c190fc +F src/sqliteInt.h 4dd81a25a919509ce94b1f8f120bbef14458d4b9 +F src/sqliteLimit.h 164b0e6749d31e0daa1a4589a169d31c0dec7b3d +F src/status.c 7ac05a5c7017d0b9f0b4bcd701228b784f987158 +F src/table.c 2cd62736f845d82200acfa1287e33feb3c15d62e +F src/tclsqlite.c 3b5f3716e320480659239abe887164521c575d83 +F src/test1.c 5757066e503a8ed51313cb3a5d9bcdcced2991a9 +F src/test2.c 7355101c085304b90024f2261e056cdff13c6c35 +F src/test3.c 1c0e5d6f080b8e33c1ce8b3078e7013fdbcd560c +F src/test4.c 9b32d22f5f150abe23c1830e2057c4037c45b3df +F src/test5.c a6d1ac55ac054d0b2b8f37b5e655b6c92645a013 +F src/test6.c 00af0fe1947305222b8ed488a69c76c5a2b632e2 +F src/test7.c 72b732baa5642f795655ba1126ea032af46ecfd2 +F src/test8.c c7aab1d9fbbf54fc33d43b73aa24aa55f9eaf534 +F src/test9.c bea1e8cf52aa93695487badedd6e1886c321ea60 +F src/test_async.c 21e11293a2f72080eda70e1124e9102044531cd8 +F src/test_autoext.c dea8a01a7153b9adc97bd26161e4226329546e12 +F src/test_backup.c 3875e899222b651e18b662f86e0e50daa946344e +F src/test_btree.c 5b89601dcb42a33ba8b820a6b763cc9cb48bac16 +F src/test_config.c 3d148e338b575bd937f7746824f36a9c6682d238 +F src/test_demovfs.c 69b2085076654ebc18014cbc6386f04409c959a9 +F src/test_devsym.c e7498904e72ba7491d142d5c83b476c4e76993bc +F src/test_fs.c ced436e3d4b8e4681328409b8081051ce614e28f +F src/test_func.c f8235719dff4bf9ffee04c55a190af8782ce9ab5 +F src/test_hexio.c abfdecb6fa58c354623978efceb088ca18e379cd +F src/test_init.c 66b33120ffe9cd853b5a905ec850d51151337b32 +F src/test_intarray.c 87847c71c3c36889c0bcc9c4baf9d31881665d61 +F src/test_intarray.h 2ece66438cfd177b78d1bfda7a4180cd3a10844d +F src/test_journal.c f5c0a05b7b3d5930db769b5ee6c3766dc2221a64 +F src/test_loadext.c df586c27176e3c2cb2e099c78da67bf14379a56e +F src/test_malloc.c eba4e1c5847cc98e7edc98f62265cd2abafba7a6 +F src/test_multiplex.c 5d691eeb6cb6aa7888da28eba5e62a9a857d3c0f +F src/test_multiplex.h 110a8c4d356e0aa464ca8730375608a9a0b61ae1 +F src/test_mutex.c 293042d623ebba969160f471a82aa1551626454f +F src/test_onefile.c 0396f220561f3b4eedc450cef26d40c593c69a25 +F src/test_osinst.c 90a845c8183013d80eccb1f29e8805608516edba +F src/test_pcache.c a5cd24730cb43c5b18629043314548c9169abb00 +F src/test_quota.c 30c64f0ef84734f2231a686df41ed882b0c59bc0 +F src/test_quota.h 8761e463b25e75ebc078bd67d70e39b9c817a0cb +F src/test_rtree.c f3d1d12538dccb75fd916e3fa58f250edbdd3b47 +F src/test_schema.c cd12a2223c3a394f4d07bb93bdf6d344c5c121b6 +F src/test_server.c a2615049954cbb9cfb4a62e18e2f0616e4dc38fe +F src/test_sqllog.c c1c1bbedbcaf82b93d83e4f9dd990e62476a680e +F src/test_stat.c d1569c7a4839f13e80187e2c26b2ab4da2d03935 +F src/test_superlock.c 2b97936ca127d13962c3605dbc9a4ef269c424cd +F src/test_syscall.c 16dbe79fb320fadb5acd7a0a59f49e52ab2d2091 +F src/test_tclvar.c f4dc67d5f780707210d6bb0eb6016a431c04c7fa +F src/test_thread.c 1e133a40b50e9c035b00174035b846e7eef481cb +F src/test_vfs.c e72f555ef7a59080f898fcf1a233deb9eb704ea9 +F src/test_vfstrace.c 34b544e80ba7fb77be15395a609c669df2e660a2 +F src/test_wsd.c 41cadfd9d97fe8e3e4e44f61a4a8ccd6f7ca8fe9 +F src/tokenize.c 70061085a51f2f4fc15ece94f32c03bcb78e63b2 +F src/trigger.c ba0a883cd536b7dfdd4df3733001f5372a4299da +F src/update.c f5182157f5d0d0a97bc5f5e3c9bdba0dfbe08f08 +F src/utf.c 6fc6c88d50448c469c5c196acf21617a24f90269 +F src/util.c 2fa6c821d28bbdbeec1b2a7b091a281c9ef8f918 +F src/vacuum.c f313bc97123a4dd4bfd3f50a00c4d44c08a5b1b7 +F src/vdbe.c 56e648f5ba9a91810caf216857adfed9039cd174 +F src/vdbe.h 4f554b5627f26710c4c36d919110a3fc611ca5c4 +F src/vdbeInt.h ff57f67aee1ba26a3a47e786533dab155ab6dad6 +F src/vdbeapi.c 93a22a9ba2abe292d5c2cf304d7eb2e894dde0ed +F src/vdbeaux.c 55f4858fe6abd84bd7311acbf30a75a28903ec25 +F src/vdbeblob.c 5dc79627775bd9a9b494dd956e26297946417d69 +F src/vdbemem.c 649933bad3e922465b726eaf85c72a75acba2ab7 +F src/vdbesort.c 3937e06b2a0e354500e17dc206ef4c35770a5017 +F src/vdbetrace.c e7ec40e1999ff3c6414424365d5941178966dcbc +F src/vtab.c 5a423b042eb1402ef77697d03d6a67378d97bc8d +F src/wal.c 7dc3966ef98b74422267e7e6e46e07ff6c6eb1b4 +F src/wal.h df01efe09c5cb8c8e391ff1715cca294f89668a4 +F src/walker.c e9e593d5bb798c3e67fc3893dfe7055c9e7d8d74 +F src/where.c dd2d0d69280d6653d8ef8cf3b6b4b848b9058197 +F test/8_3_names.test ebbb5cd36741350040fd28b432ceadf495be25b2 +F test/aggerror.test a867e273ef9e3d7919f03ef4f0e8c0d2767944f2 +F test/aggnested.test 45c0201e28045ad38a530b5a144b73cd4aa2cfd6 +F test/alias.test 4529fbc152f190268a15f9384a5651bbbabc9d87 +F test/all.test 6ff7b43c2b4b905c74dc4a813d201d0fa64c5783 +F test/alter.test 775a1dded3f8247983c9a3e767b011d9a5114442 +F test/alter2.test 7ea05c7d92ac99349a802ef7ada17294dd647060 +F test/alter3.test 49c9d9fba2b8fcdce2dedeca97bbf1f369cc548d +F test/alter4.test 8e93bf7a7e6919b14b0c9a6c1e4908bcf21b0165 +F test/altermalloc.test e81ac9657ed25c6c5bb09bebfa5a047cd8e4acfc +F test/amatch1.test b5ae7065f042b7f4c1c922933f4700add50cdb9f +F test/analyze.test 1772936d66471c65221e437b6d1999c3a03166c4 +F test/analyze3.test 412f690dfe95b337475e3e78a84a85d25f6f125d +F test/analyze4.test eff2df19b8dd84529966420f29ea52edc6b56213 +F test/analyze5.test 765c4e284aa69ca172772aa940946f55629bc8c4 +F test/analyze6.test d31defa011a561b938b4608d3538c1b4e0b5e92c +F test/analyze7.test bb1409afc9e8629e414387ef048b8e0e3e0bdc4f +F test/analyze8.test 093d15c1c888eed5034304a98c992f7360130b88 +F test/analyze9.test 1b9b7e9a096d1536f03d9ad7b72f638ef5669347 +F test/analyzeA.test 1a5c40079894847976d983ca39c707aaa44b6944 +F test/analyzeB.test 8bf35ee0a548aea831bf56762cb8e7fdb1db083d +F test/async.test 1d0e056ba1bb9729283a0f22718d3a25e82c277b +F test/async2.test c0a9bd20816d7d6a2ceca7b8c03d3d69c28ffb8b +F test/async3.test d73a062002376d7edc1fe3edff493edbec1fc2f7 +F test/async4.test 1787e3952128aa10238bf39945126de7ca23685a +F test/async5.test 383ab533fdb9f7ad228cc99ee66e1acb34cc0dc0 +F test/atof1.test 9bf1d25180a2e05fc12ce3940cc8003033642f68 +F test/attach.test 0d112b7713611fdf0340260192749737135fda5f +F test/attach2.test 0ec5defa340363de6cd50fd595046465e9aaba2d +F test/attach3.test d89ccfe4fe6e2b5e368d480fcdfe4b496c54cf4e +F test/attach4.test 53bf502f17647c6d6c5add46dda6bac8b6f4665c +F test/attachmalloc.test 3a4bfca9545bfe906a8d2e622de10fbac5b711b0 +F test/auth.test 9bea29041871807d9f289ee679d05d3ed103642f +F test/auth2.test a2a371aa6df15f8b0c8109b33d3d7f0f73e4c9aa +F test/auth3.test a4755e6a2a2fea547ffe63c874eb569e60a28eb5 +F test/autoinc.test bd30d372d00045252f6c2e41b5f41455e1975acf +F test/autoindex1.test d4dfe14001dfcb74cfbd7107f45a79fc1ab6183e +F test/autovacuum.test 9f22a7733f39c56ef6a5665d10145ac25d8cb574 +F test/autovacuum_ioerr2.test 8a367b224183ad801e0e24dcb7d1501f45f244b4 +F test/avtrans.test 0252654f4295ddda3b2cce0e894812259e655a85 +F test/backcompat.test ecd841f3a3bfb81518721879cc56a760670e3198 +F test/backup.test c9cdd23a495864b9edf75a9fa66f5cb7e10fcf62 +F test/backup2.test 34986ef926ea522911a51dfdb2f8e99b7b75ebcf +F test/backup4.test 2a2e4a64388090b152de753fd9e123f28f6a3bd4 +F test/backup_ioerr.test 4c3c7147cee85b024ecf6e150e090c32fdbb5135 +F test/backup_malloc.test 7162d604ec2b4683c4b3799a48657fb8b5e2d450 +F test/badutf.test d5360fc31f643d37a973ab0d8b4fb85799c3169f +F test/badutf2.test f5bc7f2d280670ecd79b9cf4f0f1760c607fe51f +F test/bc_common.tcl 5c8689cc6d2fb44b7c0968ae4f85eb26d50022fa +F test/between.test 34d375fb5ce1ae283ffe82b6b233e9f38e84fc6c +F test/bigfile.test aa74f4e5db51c8e54a1d9de9fa65d01d1eb20b59 +F test/bigfile2.test 1b489a3a39ae90c7f027b79110d6b4e1dbc71bfc +F test/bigrow.test f0aeb7573dcb8caaafea76454be3ade29b7fc747 +F test/bind.test 3c7b320969000c441a70952b0b15938fbb66237c +F test/bindxfer.test efecd12c580c14df5f4ad3b3e83c667744a4f7e0 +F test/bitvec.test 75894a880520164d73b1305c1c3f96882615e142 +F test/blob.test e7ac6c7d3a985cc4678c64f325292529a69ae252 +F test/boundary1.tcl 6421b2d920d8b09539503a8673339d32f7609eb1 +F test/boundary1.test 66d7f4706ccdb42d58eafdb081de07b0eb42d77b +F test/boundary2.tcl e34ef4e930cf1083150d4d2c603e146bd3b76bcb +F test/boundary2.test 9ae758d7dab7e882c8b6cc4a6a10278385bff8fa +F test/boundary3.tcl 23361e108a125dca9c4080c2feb884fe54d69243 +F test/boundary3.test 56ef82096b4329aca2be74fa1e2b0f762ea0eb45 +F test/boundary4.tcl 0bb4b1a94f4fc5ae59b79b9a2b7a140c405e2983 +F test/boundary4.test 89e02fa66397b8a325d5eb102b5806f961f8ec4b +F test/btreefault.test c2bcb542685eea44621275cfedbd8a13f65201e3 +F test/busy.test 76b4887f8b9160ba903c1ac22e8ff406ad6ae2f0 +F test/cache.test 13bc046b26210471ca6f2889aceb1ea52dc717de +F test/capi2.test e8b18cc61090b6e5e388f54d6b125d711d1b265a +F test/capi3.test 56ab450125ead38846cbae7e5b6a216686c3cffa +F test/capi3b.test efb2b9cfd127efa84433cd7a2d72ce0454ae0dc4 +F test/capi3c.test 93d24621c9ff84da9da060f30431e0453db1cdb0 +F test/capi3d.test 6d0fc0a86d73f42dd19a7d8b7761ab9bc02277d0 +F test/capi3e.test ad90088b18b0367125ff2d4b5400153fd2f99aab +F test/cast.test 4c275cbdc8202d6f9c54a3596701719868ac7dc3 +F test/check.test 1e9be446eb0bbd47a5f65955802e9632425096ab +F test/close.test 340bd24cc58b16c6bc01967402755027c37eb815 +F test/closure01.test dbb28f1ea9eeaf0a53ec5bc0fed352e479def8c7 +F test/coalesce.test cee0dccb9fbd2d494b77234bccf9dc6c6786eb91 +F test/collate1.test b709989e6e6ff6e1d2bd64231c2c1d8146846c9e +F test/collate2.test 9aaa410a00734e48bcb27f3872617d6f69b2a621 +F test/collate3.test 79558a286362cb9ed603c6fa543f1cda7f563f0f +F test/collate4.test 031f7265c13308b724ba3c49f41cc04612bd92b1 +F test/collate5.test 65d928034d30d2d263a80f6359f7549ee1598ec6 +F test/collate6.test 8be65a182abaac8011a622131486dafb8076e907 +F test/collate7.test 8ec29d98f3ee4ccebce6e16ce3863fb6b8c7b868 +F test/collate8.test df26649cfcbddf109c04122b340301616d3a88f6 +F test/collate9.test 3adcc799229545940df2f25308dd1ad65869145a +F test/collateA.test b8218ab90d1fa5c59dcf156efabb1b2599c580d6 +F test/colmeta.test 087c42997754b8c648819832241daf724f813322 +F test/colname.test 08948a4809d22817e0e5de89c7c0a8bd90cb551b +F test/conflict.test 0b3922d2304a14a47e3ccd61bbd6824327af659b +F test/contrib01.test 2a1cbc0f2f48955d7d073f725765da6fbceda6b4 +F test/corrupt.test 4aabd06cff3fe759e3e658bcc17b71789710665e +F test/corrupt2.test 9c0ab4becd50e9050bc1ebb8675456a4e5587bf0 +F test/corrupt3.test 889d7cdb811800303aa722d7813fe8a4299cf726 +F test/corrupt4.test b963f9e01e0f92d15c76fb0747876fd4b96dc30a +F test/corrupt5.test c23da7bfb20917cc7fdbb13ee25c7cc4e9fffeff +F test/corrupt6.test 4e4161aef1f30b9f34582bb4142334b7f47eacae +F test/corrupt7.test a90caf89c7d7cb7893ea4d92529bd0c129317ee4 +F test/corrupt8.test 48eb37ffb9a03bceada62219e2bd4c92f4b0cb75 +F test/corrupt9.test 959179e68dc0b7b99f424cf3e0381c86dcdd0112 +F test/corruptA.test fafa652aa585753be4f6b62ff0bb250266eaf7ce +F test/corruptB.test 20d4a20cbed23958888c3e8995b424a47223d647 +F test/corruptC.test 62a767fe64acb1975f58cc6171192839c783edbb +F test/corruptD.test 3b09903a2e2fe07ecafe775fea94177f8a4bb34f +F test/corruptE.test d3a3d7e864a95978195741744dda4abfd8286018 +F test/corruptF.test 1c7b6f77cf3f237fb7fbb5b61d6c921fd4c7b993 +F test/corruptG.test c67fd860e9e3943bc90b856a3049c9a28827167e +F test/count.test 454e1ce985c94d13efeac405ce54439f49336163 +F test/coveridxscan.test cdb47d01acc4a634a34fd25abe85189e0d0f1e62 +F test/crash.test fb9dc4a02dcba30d4aa5c2c226f98b220b2b959f +F test/crash2.test 5b14d4eb58b880e231361d3b609b216acda86651 +F test/crash3.test 8f5de9d32ab9ab95475a9efe7f47a940aa889418 +F test/crash4.test fe2821baf37168dc59dd733dcf7dba2a401487bc +F test/crash5.test 05dd3aa9dbb751a22d5cdaf22a9c49b6667aa219 +F test/crash6.test 4c56f1e40d0291e1110790a99807aa875b1647ba +F test/crash7.test 1a194c4900a255258cf94b7fcbfd29536db572df +F test/crash8.test 38767cb504bbe491de6be4a7006b154973a2309f +F test/crashtest1.c 09c1c7d728ccf4feb9e481671e29dda5669bbcc2 +F test/createtab.test b5de160630b209c4b8925bdcbbaf48cc90b67fe8 +F test/cse.test 277350a26264495e86b1785f34d2d0c8600e021c +F test/ctime.test 7bd009071e242aac4f18521581536b652b789a47 +F test/date.test 42973251b9429f2c41b77eb98a7b0b0ba2d3b2c0 +F test/dbstatus.test aee30c3f337e6c217ff06df59fb8fe6e6448dce2 +F test/dbstatus2.test 10418e62b3db5dca070f0c3eef3ea13946f339c2 +F test/default.test 6faf23ccb300114924353007795aa9a8ec0aa9dc +F test/delete.test a065b05d2ebf60fd16639c579a4adfb7c381c701 +F test/delete2.test 3a03f2cca1f9a67ec469915cb8babd6485db43fa +F test/delete3.test 555e84a00a99230b7d049d477a324a631126a6ab +F test/descidx1.test 6d03b44c8538fe0eb4924e19fba10cdd8f3c9240 +F test/descidx2.test 9f1a0c83fd57f8667c82310ca21b30a350888b5d +F test/descidx3.test 09ddbe3f5295f482d2f8b687cf6db8bad7acd9a2 +F test/diskfull.test 106391384780753ea6896b7b4f005d10e9866b6e +F test/distinct.test 44028aaf161a5e80a2f229622b3a174d3b352810 +F test/distinctagg.test 1a6ef9c87a58669438fc771450d7a72577417376 +F test/e_createtable.test ee9b70a38369ae44360febb411976aa3c8cf2689 +F test/e_delete.test d5186e2f5478b659f16a2c8b66c09892823e542a +F test/e_droptrigger.test 3cd080807622c13e5bbb61fc9a57bd7754da2412 +F test/e_dropview.test 0c9f7f60989164a70a67a9d9c26d1083bc808306 +F test/e_expr.test d5cdda0e4ffb17760858ed4c7c4ece07efc40f71 +F test/e_fkey.test 17cfb40002d165299681f39aac0cb5890c359935 +F test/e_fts3.test 5c02288842e4f941896fd44afdef564dd5fc1459 +F test/e_insert.test 291e056e1a442a5e5166a989a8a03a46e38225ca +F test/e_reindex.test e175794fc41f8e8aef34772e87a7d7b7a9251dd3 +F test/e_resolve.test dcce9308fb13b934ce29591105d031d3e14fbba6 +F test/e_select.test d3226cb94fae4af3f198e68e71f655e106d0be47 +F test/e_select2.test 22c660a7becf0712c95e1ca1b2d9e716a1261460 +F test/e_update.test bea00499e43ee1da77b03cdb0b20c7c864c1ec5a +F test/e_uri.test a2c92d80093a7efdcfbb11093651cbea87097b6b +F test/e_vacuum.test 5bfbdc21b65c0abf24398d0ba31dc88d93ca77a9 +F test/enc.test e54531cd6bf941ee6760be041dff19a104c7acea +F test/enc2.test 83437a79ba1545a55fb549309175c683fb334473 +F test/enc3.test 90683ad0e6ea587b9d5542ca93568af9a9858c40 +F test/enc4.test c8f1ce3618508fd0909945beb8b8831feef2c020 +F test/eqp.test 57c6c604c2807fb5531731c5323133453c24afac +F test/errmsg.test 050717f1c6a5685de9c79f5f9f6b83d7c592f73a +F test/eval.test bc269c365ba877554948441e91ad5373f9f91be3 +F test/exclusive.test c7ebbc756eacf544c108b15eed64d7d4e5f86b75 +F test/exclusive2.test 881193eccec225cfed9d7f744b65e57f26adee25 +F test/exec.test e949714dc127eaa5ecc7d723efec1ec27118fdd7 +F test/exists.test 8f7b27b61c2fbe5822f0a1f899c715d14e416e30 +F test/expr.test 67c9fd6f8f829e239dc8b0f4a08a73c08b09196d +F test/fallocate.test 3e979af17dfa7e5e9dda5eba1a696c04fa9d47f7 +F test/filectrl.test 14fa712e42c4cb791e09dfd58a6a03efb47ef13a +F test/filefmt.test cb34663f126cbc2d358af552dcaf5c72769b0146 +F test/fkey1.test e1d1fa84cde579185ea01358436839703e415a5b +F test/fkey2.test 06e0b4cc9e1b3271ae2ae6feeb19755468432111 +F test/fkey3.test 5ec899d12b13bcf1e9ef40eff7fb692fdb91392e +F test/fkey4.test 86446017011273aad8f9a99c1a65019e7bd9ca9d +F test/fkey5.test 8a1fde4e7721ae00b05b3178888833726ca2df8d +F test/fkey6.test 18e8c024d39f68f8d4bb1177c992bcffdc273464 +F test/fkey7.test e31d0e71a41c1d29349a16448d6c420e2c53a8fc +F test/fkey_malloc.test bb74c9cb8f8fceed03b58f8a7ef2df98520bbd51 +F test/format4.test 1f0cac8ff3895e9359ed87e41aaabee982a812eb +F test/fts-9fd058691.test 78b887e30ae6816df0e1fed6259de4b5a64ad33c +F test/fts1a.test 46090311f85da51bb33bd5ce84f7948359c6d8d7 +F test/fts1b.test 5d8a01aefbecc8b7442b36c94c05eb7a845462d5 +F test/fts1c.test 85a525ce7428907469b4cce13d5563ce542ce64c +F test/fts1d.test a73deace5c18df4a549b12908bade4f05dcf1a2f +F test/fts1e.test 77244843e925560b5a0b70069c3e7ab62f181ed2 +F test/fts1f.test 2d6cb10d8b7a4e6edc321bbdb3982f1f48774714 +F test/fts1i.test 6bfe08cdfdced063a39a50c8601da65e6274d879 +F test/fts1j.test e3797475796043a161e348c46a309664cac83f7f +F test/fts1k.test 65d3b41487b9f738d11b0f00eca375c0ca6bd970 +F test/fts1l.test 15c119ed2362b2b28d5300c0540a6a43eab66c36 +F test/fts1m.test 2d9ca67b095d49f037a914087cc0a61e89da4f0c +F test/fts1n.test a2317dcd27b1d087ee3878b30e0a59c593c98b7a +F test/fts1o.test fd92f82ea9090dbc2a13d4cd58aafe5afa371b6a +F test/fts1porter.test d86e9c3e0c7f8ff95add6582b4b585fb4e02b96d +F test/fts2.test e3fb95f96a650411574efc136f3fb10eef479ed7 +F test/fts2a.test 473a5c8b473a4e21a8e3fddaed1e59666e0c6ab7 +F test/fts2b.test 964abc0236c849c07ca1ae496bb25c268ae94816 +F test/fts2c.test ffb5a35230ac72c4354535c547965ce6824537c0 +F test/fts2d.test b7eaa671ca9a16997f3e5b158ee777ae21052b0b +F test/fts2e.test 2da13dbc2d009105f42196845c1e1ce136c03d38 +F test/fts2f.test cf84096235991709c1e61caa389632aa0a4f976d +F test/fts2g.test d49d6f6c900e6e20a0fb980ec1cd568dee12af76 +F test/fts2h.test 223af921323b409d4b5b18ff4e51619541b174bb +F test/fts2i.test 1b22451d1f13f7c509baec620dc3a4a754885dd6 +F test/fts2j.test 298fa1670aa21cd445b282d139b70c72e7ade12b +F test/fts2k.test c7ebf4a4937594aa07459e3e1bca1251c1be8659 +F test/fts2l.test 3333336621524cf7d60bb62d6ef6ab69647866ed +F test/fts2m.test 4b30142ead6f3ed076e880a2a464064c5ad58c51 +F test/fts2n.test 12b9c5352128cebd1c6b8395e43788d4b09087c2 +F test/fts2o.test 09cd920d585ebf1c2910b6be869efa286e308a84 +F test/fts2p.test 4b48c35c91e6a7dbf5ac8d1e5691823cc999aafb +F test/fts2q.test b2fbbe038b7a31a52a6079b215e71226d8c6a682 +F test/fts2r.test b154c30b63061d8725e320fba1a39e2201cadd5e +F test/fts2token.test d8070b241a15ff13592a9ae4a8b7c171af6f445a +F test/fts3.test 672a040ea57036fb4b6fdc09027c18d7d24ab654 +F test/fts3_common.tcl 99cf6659b87c0f74f55963c2aea03b3a7d66ceb0 +F test/fts3aa.test ad272d695095a55c16a5091dbdcce7c5f55da605 +F test/fts3ab.test 09aeaa162aee6513d9ff336b6932211008b9d1f9 +F test/fts3ac.test 636ed7486043055d4f126a0e385f2d5a82ebbf63 +F test/fts3ad.test e40570cb6f74f059129ad48bcef3d7cbc20dda49 +F test/fts3ae.test ce32a13b34b0260928e4213b4481acf801533bda +F test/fts3af.test d394978c534eabf22dd0837e718b913fd66b499c +F test/fts3ag.test 0b7d303f61ae5d620c4efb5e825713ea34ff9441 +F test/fts3ah.test dc9f66c32c296f1bc8bcc4535126bddfeca62894 +F test/fts3ai.test 24058fdc6e9e5102c1fd8459591b114b6a85d285 +F test/fts3aj.test 0ed71e1dd9b03b843a857dc3eb9b15630e0104fc +F test/fts3ak.test bd14deafe9d1586e8e9bf032411026ac4f8c925d +F test/fts3al.test 07d64326e79bbdbab20ee87fc3328fbf01641c9f +F test/fts3am.test 218aa6ba0dfc50c7c16b2022aac5c6be593d08d8 +F test/fts3an.test a49ccadc07a2f7d646ec1b81bc09da2d85a85b18 +F test/fts3ao.test 71b0675e3df5c512a5a03daaa95ee1916de23dda +F test/fts3atoken.test fca30fd86db9241d571c637751e9a8a2f50f1451 +F test/fts3auto.test b981fea19b132b4e6878f50d7c1f369b28f68eb9 +F test/fts3aux1.test f8f287a4a73f381f8fa15b6a70f36245f903d221 +F test/fts3aux2.test 7ae2b2c13aefdf4169279a27a5f51780ce57f6ba +F test/fts3b.test e93bbb653e52afde110ad53bbd793f14fe7a8984 +F test/fts3c.test fc723a9cf10b397fdfc2b32e73c53c8b1ec02958 +F test/fts3comp1.test a0f5b16a2df44dd0b15751787130af2183167c0c +F test/fts3conf.test ee8500c86dd58ec075e8831a1e216a79989436de +F test/fts3corrupt.test 2710b77983cc7789295ddbffea52c1d3b7506dbb +F test/fts3corrupt2.test 6d96efae2f8a6af3eeaf283aba437e6d0e5447ba +F test/fts3cov.test e0fb00d8b715ddae4a94c305992dfc3ef70353d7 +F test/fts3d.test bf640d79722b720fa1c81834c48cdaa45d531b1a +F test/fts3defer.test 0be4440b73a2e651fc1e472066686d6ada4b9963 +F test/fts3defer2.test a3b6cbeabaf28c9398652a4d101ea224d9358479 +F test/fts3defer3.test dd53fc13223c6d8264a98244e9b19abd35ed71cd +F test/fts3drop.test 1b906e293d6773812587b3dc458cb9e8f3f0c297 +F test/fts3e.test 1f6c6ac9cc8b772ca256e6b22aaeed50c9350851 +F test/fts3expr.test 5e745b2b6348499d9ef8d59015de3182072c564c +F test/fts3expr2.test 18da930352e5693eaa163a3eacf96233b7290d1a +F test/fts3expr3.test 9e91b8edbcb197bf2e92161aa7696446d96dce5f +F test/fts3fault.test cb72dccb0a3b9f730f16c5240f3fcb9303eb1660 +F test/fts3fault2.test 3198eef2804deea7cac8403e771d9cbcb752d887 +F test/fts3first.test dbdedd20914c8d539aa3206c9b34a23775644641 +F test/fts3malloc.test b0e4c133b8d61d4f6d112d8110f8320e9e453ef6 +F test/fts3matchinfo.test ff423e73faab8fc6d7adeefedf74dd8e2b0b14e0 +F test/fts3near.test 12895557870b0f9af7cc0be81a0171abb2d12f12 +F test/fts3prefix.test b36d4f00b128a51e7b386cc013a874246d9d7dc1 +F test/fts3prefix2.test e1f0a822ca661dced7f12ce392e14eaf65609dce +F test/fts3query.test 4fefd43ff24993bc2c9b2778f2bec0cc7629e7ed +F test/fts3rnd.test 1320d8826a845e38a96e769562bf83d7a92a15d0 +F test/fts3shared.test 57e26a801f21027b7530da77db54286a6fe4997e +F test/fts3snippet.test d524af6bcef4714e059ef559113dbdc924cd33d1 +F test/fts3sort.test ed34c716a11cc2009a35210e84ad5f9c102362ca +F test/fts3tok1.test b10d0a12a0ab5f905cea1200b745de233f37443f +F test/fts3tok_err.test 52273cd193b9036282f7bacb43da78c6be87418d +F test/fts4aa.test 0c3152322c7f0b548cc942ad763eaba0da87ccca +F test/fts4check.test 66fa274cab2b615f2fb338b257713aba8fad88a8 +F test/fts4content.test 2e7252557d6d24afa101d9ba1de710d6140e6d06 +F test/fts4docid.test e33c383cfbdff0284685604d256f347a18fdbf01 +F test/fts4incr.test 361960ed3550e781f3f313e17e2182ef9cefc0e9 +F test/fts4langid.test 24a6e41063b416bbdf371ff6b4476fa41c194aa7 +F test/fts4merge.test c424309743fdd203f8e56a1f1cd7872cd66cc0ee +F test/fts4merge2.test 5faa558d1b672f82b847d2a337465fa745e46891 +F test/fts4merge3.test aab02a09f50fe6baaddc2e159c3eabc116d45fc7 +F test/fts4merge4.test c19c85ca1faa7b6d536832b49c12e1867235f584 +F test/fts4noti.test aed33ba44808852dcb24bf70fa132e7bf530f057 +F test/fts4unicode.test e28ba1a14181e709dcdf47455f207adf14c7cfe0 +F test/full.test 6b3c8fb43c6beab6b95438c1675374b95fab245d +F test/func.test c7e80a44eebac8604397eb2ad83d0d5d9d541237 +F test/func2.test 772d66227e4e6684b86053302e2d74a2500e1e0f +F test/func3.test dbccee9133cfef1473c59ec07b5f0262b9d72f9a +F test/func4.test cb3f888a1cafad195a1f8d396875bdb11dc4faf9 +F test/fuzz-oss1.test 4912e528ec9cf2f42134456933659d371c9e0d74 +F test/fuzz.test 77fd50afc12847af50fcf1941679d90adebadde6 +F test/fuzz2.test 207d0f9d06db3eaf47a6b7bfc835b8e2fc397167 +F test/fuzz3.test aec64345184d1662bd30e6a17851ff659d596dc5 +F test/fuzz_common.tcl a87dfbb88c2a6b08a38e9a070dabd129e617b45b +F test/fuzz_malloc.test 328f70aaca63adf29b4c6f06505ed0cf57ca7c26 +F test/fuzzer1.test d4c52aaf3ef923da293a2653cfab33d02f718a36 +F test/fuzzerfault.test 8792cd77fd5bce765b05d0c8e01b9edcf8af8536 +F test/genesis.tcl 1e2e2e8e5cc4058549a154ff1892fe5c9de19f98 +F test/hook.test 45cb22b940c3cc0af616ba7430f666e245711a48 +F test/icu.test 70df4faca133254c042d02ae342c0a141f2663f4 +F test/in.test 5941096407d8c133b9eff15bd3e666624b6cbde3 +F test/in2.test 5d4c61d17493c832f7d2d32bef785119e87bde75 +F test/in3.test 3cbf58c87f4052cee3a58b37b6389777505aa0c0 +F test/in4.test 64f3cc1acde1b9161ccdd8e5bde3daefdb5b2617 +F test/in5.test 99f9a40af01711b06d2d614ecfe96129f334fba3 +F test/incrblob.test e81846d214f3637622620fbde7cd526781cfe328 +F test/incrblob2.test edc3a96e557bd61fb39acc8d2edd43371fbbaa19 +F test/incrblob3.test d8d036fde015d4a159cd3cbae9d29003b37227a4 +F test/incrblob4.test f26502a5697893e5acea268c910f16478c2f0fab +F test/incrblob_err.test d2562d2771ebffd4b3af89ef64c140dd44371597 +F test/incrblobfault.test 280474078f6da9e732cd2a215d3d854969014b6e +F test/incrvacuum.test d2a6ddf5e429720b5fe502766af747915ccf6c32 +F test/incrvacuum2.test 379eeb8740b0ef60c372c439ad4cbea20b34bb9b +F test/incrvacuum3.test 75256fb1377e7c39ef2de62bfc42bbff67be295a +F test/incrvacuum_ioerr.test 6ae2f783424e47a0033304808fe27789cf93e635 +F test/index.test f2abacfb83d384ae36b8a919fbd94b1319333e55 +F test/index2.test ee83c6b5e3173a3d7137140d945d9a5d4fdfb9d6 +F test/index3.test 423a25c789fc8cc51aaf2a4370bbdde2d9e9eed7 +F test/index4.test 2983216eb8c86ee62d9ed7cb206b5cc3331c0026 +F test/index5.test fc07c14193c0430814e7a08b5da46888ee795c33 +F test/index6.test 9996f064672c03e768e256e4bf7cff4b63e8b109 +F test/indexedby.test b2f22f3e693a53813aa3f50b812eb609ba6df1ec +F test/indexfault.test 31d4ab9a7d2f6e9616933eb079722362a883eb1d +F test/init.test 15c823093fdabbf7b531fe22cf037134d09587a7 +F test/insert.test 489aa12a027c83d291f5034a83c8c32e6be1dca2 +F test/insert2.test 4f3a04d168c728ed5ec2c88842e772606c7ce435 +F test/insert3.test 1b7db95a03ad9c5013fdf7d6722b6cd66ee55e30 +F test/insert4.test 87f6798f31d60c4e177622fcc3663367e6ecbd90 +F test/insert5.test 394f96728d1258f406fe5f5aeb0aaf29487c39a6 +F test/instr.test 737bbf80685232033f3abedc6ae92f75860b5dd2 +F test/intarray.test 066b7d7ac38d25bf96f87f1b017bfc687551cdd4 +F test/interrupt.test dfe9a67a94b0b2d8f70545ba1a6cca10780d71cc +F test/intpkey.test a9674fc6195e0952e4e6105a9981ce1e48e7f215 +F test/io.test 3a7abcef18727cc0f2399e04b0e8903eccae50f8 +F test/ioerr.test 40bb2cfcab63fb6aa7424cd97812a84bc16b5fb8 +F test/ioerr2.test 9d71166f8466eda510f1af6137bdabaa82b5408d +F test/ioerr3.test d3cec5e1a11ad6d27527d0d38573fbff14c71bdd +F test/ioerr4.test f130fe9e71008577b342b8874d52984bd04ede2c +F test/ioerr5.test 2edfa4fb0f896f733071303b42224df8bedd9da4 +F test/ioerr6.test a395a6ab144b26a9e3e21059a1ab6a7149cca65b +F test/join.test 8d63cc4d230a7affafa4b6ab0b97c49b8ccb365c +F test/join2.test f2171c265e57ee298a27e57e7051d22962f9f324 +F test/join3.test 6f0c774ff1ba0489e6c88a3e77b9d3528fb4fda0 +F test/join4.test 1a352e4e267114444c29266ce79e941af5885916 +F test/join5.test 86675fc2919269aa923c84dd00ee4249b97990fe +F test/join6.test cfe6503791ceb0cbb509966740286ec423cbf10b +F test/journal1.test 69abc726c51b4a0409189f9a85191205297c0577 +F test/journal2.test ae06f566c28552c313ded3fee79a6c69e6d049b1 +F test/journal3.test ff8af941f9e06161d3db1b46bb9f965ff0e7f307 +F test/jrnlmode.test 9ee3a78f53d52cca737db69293d15dc41c0cbd36 +F test/jrnlmode2.test 81610545a4e6ed239ea8fa661891893385e23a1d +F test/jrnlmode3.test 556b447a05be0e0963f4311e95ab1632b11c9eaa +F test/keyword1.test a2400977a2e4fde43bf33754c2929fda34dbca05 +F test/lastinsert.test 474d519c68cb79d07ecae56a763aa7f322c72f51 +F test/laststmtchanges.test ae613f53819206b3222771828d024154d51db200 +F test/like.test 935fb4f608e3ea126891496a6e99b9468372bf5c +F test/like2.test 3b2ee13149ba4a8a60b59756f4e5d345573852da +F test/limit.test cc0ab63385239b63c72452b0e93700bf5e8f0b99 +F test/loadext.test 92e6dfefd1229c3ef4aaabd87419efd8fa57a7a5 +F test/loadext2.test 0408380b57adca04004247179837a18e866a74f7 +F test/lock.test 87af515b0c4cf928576d0f89946d67d7c265dfb4 +F test/lock2.test 5242d8ac4e2d59c403aebff606af449b455aceff +F test/lock3.test f271375930711ae044080f4fe6d6eda930870d00 +F test/lock4.test e175ae13865bc87680607563bafba21f31a26f12 +F test/lock5.test 5ad6a1f536036ff1be915cfdd41481aeafda3273 +F test/lock6.test ad5b387a3a8096afd3c68a55b9535056431b0cf5 +F test/lock7.test 49f1eaff1cdc491cc5dee3669f3c671d9f172431 +F test/lock_common.tcl 0c270b121d40959fa2f3add382200c27045b3d95 +F test/lookaside.test 93f07bac140c5bb1d49f3892d2684decafdc7af2 +F test/main.test 39c4bb8a157f57298ed1659d6df89d9f35aaf2c8 +F test/make-where7.tcl 05c16b5d4f5d6512881dfec560cb793915932ef9 +F test/malloc.test fd368e31fe98d4779ed80442f311ed9f03bcd1f7 +F test/malloc3.test e3b32c724b5a124b57cb0ed177f675249ad0c66a +F test/malloc4.test 957337613002b7058a85116493a262f679f3a261 +F test/malloc5.test fafce0aa9157060445cd1a56ad50fc79d82f28c3 +F test/malloc6.test 2f039d9821927eacae43e1831f815e157659a151 +F test/malloc7.test 7c68a32942858bc715284856c5507446bba88c3a +F test/malloc8.test 9b7a3f8cb9cf0b12fff566e80a980b1767bd961d +F test/malloc9.test 2307c6ee3703b0a21391f3ea92388b4b73f9105e +F test/mallocA.test 1ba0367fb5434e7bc2fa4afcb30b14174d91b160 +F test/mallocAll.test 98f1be74bc9f49a858bc4f361fc58e26486798be +F test/mallocB.test bc475ab850cda896142ab935bbfbc74c24e51ed6 +F test/mallocC.test 3dffe16532f109293ce1ccecd0c31dca55ef08c4 +F test/mallocD.test f78c295e8e18ea3029e65ca08278690e00c22100 +F test/mallocE.test db1ed69d7eded1b080952e2a7c37f364ad241b08 +F test/mallocF.test 2d5c590ebc2fc7f0dcebdf5aa8498b9aed69107e +F test/mallocG.test 0ff91b65c50bdaba680fb75d87fe4ad35bb7934f +F test/mallocH.test 79b65aed612c9b3ed2dcdaa727c85895fd1bfbdb +F test/mallocI.test a88c2b9627c8506bf4703d8397420043a786cdb6 +F test/mallocJ.test b5d1839da331d96223e5f458856f8ffe1366f62e +F test/mallocK.test d79968641d1b70d88f6c01bdb9a7eb4a55582cc9 +F test/malloc_common.tcl 58e54229c4132ef882a11fab6419ec4cd3073589 +F test/manydb.test 28385ae2087967aa05c38624cec7d96ec74feb3e +F test/mem5.test c6460fba403c5703141348cd90de1c294188c68f +F test/memdb.test db5260330676de007be8530d6ecc7c9ab2b06ad3 +F test/memleak.test 10b9c6c57e19fc68c32941495e9ba1c50123f6e2 +F test/memsubsys1.test f97cfd0b30e85c2f1ed16d642e7ac58006be84b2 +F test/memsubsys2.test 3a1c1a9de48e5726faa85108b02459fae8cb9ee9 +F test/minmax.test 42fbad0e81afaa6e0de41c960329f2b2c3526efd +F test/minmax2.test b44bae787fc7b227597b01b0ca5575c7cb54d3bc +F test/minmax3.test cc1e8b010136db0d01a6f2a29ba5a9f321034354 +F test/minmax4.test 536a3360470633a177e42fbc19660d146b51daef +F test/misc1.test 889b40722442380a2f6575f30831b32b2372d70e +F test/misc2.test 00d7de54eda90e237fc9a38b9e5ccc769ebf6d4d +F test/misc3.test fe55130a43e444ee75e2156ff75dc96e964b5738 +F test/misc4.test 9c078510fbfff05a9869a0b6d8b86a623ad2c4f6 +F test/misc5.test 528468b26d03303b1f047146e5eefc941b9069f5 +F test/misc6.test 953cc693924d88e6117aeba16f46f0bf5abede91 +F test/misc7.test 50c02c35ef7924c246eb3d8d71dfbf90ba352f8f +F test/misuse.test ba4fb5d1a6101d1c171ea38b3c613d0661c83054 +F test/mmap1.test 93d167b328255cbe6679fe1e1a23be1b1197d07b +F test/mmap2.test 9d6dd9ddb4ad2379f29cc78f38ce1e63ed418022 +F test/mmap3.test c92273e16eb8d23c1d55c9815b446bb72ef0512e +F test/mmapfault.test 97507ee06172df99057dbf1c40294eabd82cbb13 +F test/multiplex.test e08cc7177bd6d85990ee1d71100bb6c684c02256 +F test/multiplex2.test 580ca5817c7edbe4cc68fa150609c9473393003a +F test/multiplex3.test d228f59eac91839a977eac19f21d053f03e4d101 +F test/mutex1.test 78b2b9bb320e51d156c4efdb71b99b051e7a4b41 +F test/mutex2.test bfeaeac2e73095b2ac32285d2756e3a65e681660 +F test/nan.test e9648b9d007c7045242af35e11a984d4b169443a +F test/notify1.test 669b2b743618efdc18ca4b02f45423d5d2304abf +F test/notify2.test ce23eb522c9e1fff6443f96376fe67872202061c +F test/notify3.test 10ff25cde502e72a92053a2f215d64bece4ef934 +F test/notnull.test 2afad748d18fd66d01f66463de73b3e2501fb226 +F test/null.test a8b09b8ed87852742343b33441a9240022108993 +F test/numcast.test 5d126f7f581432e86a90d1e35cac625164aec4a1 +F test/openv2.test 0d3040974bf402e19b7df4b783e447289d7ab394 +F test/orderby1.test 9b524aff9147288da43a6d7ddfdcff47fa2303c6 +F test/orderby2.test bc11009f7cd99d96b1b11e57b199b00633eb5b04 +F test/orderby3.test 8619d06a3debdcd80a27c0fdea5c40b468854b99 +F test/orderby4.test 4d39bfbaaa3ae64d026ca2ff166353d2edca4ba4 +F test/orderby5.test 02eca502a0f97c77ce383b0dfa17e99c6a107b8d +F test/oserror.test 50417780d0e0d7cd23cf12a8277bb44024765df3 +F test/pager1.test 16b649c8f0b38d446acbcff8a7bf055a9be43276 +F test/pager2.test 67b8f40ae98112bcdba1f2b2d03ea83266418c71 +F test/pager3.test 3856d9c80839be0668efee1b74811b1b7f7fc95f +F test/pagerfault.test 7285379906ab2f1108b8e82bbdf2d386cc8ff3ff +F test/pagerfault2.test caf4c7facb914fd3b03a17b31ae2b180c8d6ca1f +F test/pagerfault3.test 1003fcda009bf48a8e22a516e193b6ef0dd1bbd8 +F test/pageropt.test 6b8f6a123a5572c195ad4ae40f2987007923bbd6 +F test/pagesize.test 1dd51367e752e742f58e861e65ed7390603827a0 +F test/pcache.test b09104b03160aca0d968d99e8cd2c5b1921a993d +F test/pcache2.test a83efe2dec0d392f814bfc998def1d1833942025 +F test/percentile.test b98fc868d71eb5619d42a1702e9ab91718cbed54 +F test/permutations.test e154f5ed66d4d4913a99a110e870c9407f75b055 +F test/pragma.test 5e7de6c32a5d764f09437d2025f07e4917b9e178 +F test/pragma2.test aea7b3d82c76034a2df2b38a13745172ddc0bc13 +F test/printf.test ec9870c4dce8686a37818e0bf1aba6e6a1863552 +F test/progress.test a282973d1d17f08071bc58a77d6b80f2a81c354d +F test/ptrchng.test ef1aa72d6cf35a2bbd0869a649b744e9d84977fc +F test/queryonly.test 5f653159e0f552f0552d43259890c1089391dcca +F test/quick.test 1681febc928d686362d50057c642f77a02c62e57 +F test/quota-glob.test 32901e9eed6705d68ca3faee2a06b73b57cb3c26 +F test/quota.test 2379902c25e291eac5c12b4cf96946a3447e3744 +F test/quota2.test 7dc12e08b11cbc4c16c9ba2aa2e040ea8d8ab4b8 +F test/quote.test 215897dbe8de1a6f701265836d6601cc6ed103e6 +F test/randexpr1.tcl 40dec52119ed3a2b8b2a773bce24b63a3a746459 +F test/randexpr1.test eda062a97e60f9c38ae8d806b03b0ddf23d796df +F test/rdonly.test c267d050a1d9a6a321de502b737daf28821a518d +F test/regexp1.test 497ea812f264d12b6198d6e50a76be4a1973a9d8 +F test/reindex.test 44edd3966b474468b823d481eafef0c305022254 +F test/releasetest.mk 2eced2f9ae701fd0a29e714a241760503ccba25a +F test/releasetest.tcl 06d289d8255794073a58d2850742f627924545ce +F test/resolver01.test 33abf37ff8335e6bf98f2b45a0af3e06996ccd9a +F test/rollback.test a1b4784b864331eae8b2a98c189efa2a8b11ff07 +F test/rowhash.test 0bc1d31415e4575d10cacf31e1a66b5cc0f8be81 +F test/rowid.test f777404492adb0e00868fd706a3721328fd3af48 +F test/rtree.test 0c8d9dd458d6824e59683c19ab2ffa9ef946f798 +F test/savepoint.test f5acd87d0c7a5f4ad6c547b47fd18c0e1aeaf048 +F test/savepoint2.test 9b8543940572a2f01a18298c3135ad0c9f4f67d7 +F test/savepoint3.test e328085853b14898d78ceea00dfe7db18bb6a9ec +F test/savepoint4.test c8f8159ade6d2acd9128be61e1230f1c1edc6cc0 +F test/savepoint5.test 0735db177e0ebbaedc39812c8d065075d563c4fd +F test/savepoint6.test f41279c5e137139fa5c21485773332c7adb98cd7 +F test/savepoint7.test fbf319a7b2dda089ec5be30a424a0e95f121d423 +F test/schema.test 8f7999be894260f151adf15c2c7540f1c6d6a481 +F test/schema2.test 906408621ea881fdb496d878b1822572a34e32c5 +F test/schema3.test 1bc1008e1f8cb5654b248c55f27249366eb7ed38 +F test/schema4.test e6a66e20cc69f0e306667c08be7fda3d11707dc5 +F test/schema5.test 0103e4c0313b3725b5ae5600bdca53006ab53db3 +F test/securedel.test 87a2561151af1f1e349071a89fdd77059f50113c +F test/securedel2.test 2d54c28e46eb1fd6902089958b20b1b056c6f1c5 +F test/select1.test fc2a61f226a649393664ad54bc5376631801517c +F test/select2.test 352480e0e9c66eda9c3044e412abdf5be0215b56 +F test/select3.test 2ce595f8fb8e2ac10071d3b4e424cadd4634a054 +F test/select4.test 00179be44e531fe04c1c3f15df216439dff2519d +F test/select5.test e758b8ef94f69b111df4cb819008856655dcd535 +F test/select6.test e76bd10a56988f15726c097a5d5a7966fe82d3b2 +F test/select7.test dad6f00f0d49728a879d6eb6451d4752db0b0abe +F test/select8.test 391de11bdd52339c30580dabbbbe97e3e9a3c79d +F test/select9.test aebc2bb0c3bc44606125033cbcaac2c8d1f33a95 +F test/selectA.test 99cf21df033b93033ea4f34aba14a500f48f04fe +F test/selectB.test 954e4e49cf1f896d61794e440669e03a27ceea25 +F test/selectC.test 871fb55d884d3de5943c4057ebd22c2459e71977 +F test/selectD.test b0f02a04ef7737decb24e08be2c39b9664b43394 +F test/selectE.test fc02a1eb04c8eb537091482644b7d778ae8759b7 +F test/server1.test 46803bd3fe8b99b30dbc5ff38ffc756f5c13a118 +F test/shared.test 1da9dbad400cee0d93f252ccf76e1ae007a63746 +F test/shared2.test 03eb4a8d372e290107d34b6ce1809919a698e879 +F test/shared3.test fcd65cb11d189eff5f5c85cc4fad246fb0933108 +F test/shared4.test 72d90821e8d2fc918a08f16d32880868d8ee8e9d +F test/shared6.test 866bb4982c45ce216c61ded5e8fde4e7e2f3ffa9 +F test/shared7.test a81e99f83e6c51b02ac99c96fb3a2a7b5978c956 +F test/shared8.test 00a07bf5e1337ecf72e94542bdefdc330d7a2538 +F test/shared9.test 5f2a8f79b4d6c7d107a01ffa1ed05ae7e6333e21 +F test/sharedA.test 0cdf1a76dfa00e6beee66af5b534b1e8df2720f5 +F test/shared_err.test 0079c05c97d88cfa03989b7c20a8b266983087aa +F test/sharedlock.test 5ede3c37439067c43b0198f580fd374ebf15d304 +F test/shell1.test e7c0b9ebda25d5e78f0a3ea0dc4e31bb6d8098c0 +F test/shell2.test e1d3790f064e50b2f973502f45750012667486df +F test/shell3.test 5e8545ec72c4413a0e8d4c6be56496e3c257ca29 +F test/shell4.test aa4eef8118b412d1a01477a53426ece169ea86a9 +F test/shell5.test 46c8c18d62732415c4fe084816c13d559831705e +F test/shortread1.test bb591ef20f0fd9ed26d0d12e80eee6d7ac8897a3 +F test/shrink.test 8c70f62b6e8eb4d54533de6d65bd06b1b9a17868 +F test/sidedelete.test f0ad71abe6233e3b153100f3b8d679b19a488329 +F test/soak.test 0b5b6375c9f4110c828070b826b3b4b0bb65cd5f +F test/softheap1.test 40562fe6cac6d9827b7b42b86d45aedf12c15e24 +F test/sort.test 0e4456e729e5a92a625907c63dcdedfbe72c5dc5 +F test/speed1.test f2974a91d79f58507ada01864c0e323093065452 +F test/speed1p.explain d841e650a04728b39e6740296b852dccdca9b2cb +F test/speed1p.test b180e98609c7677382cf618c0ec9b69f789033a8 +F test/speed2.test 53177056baf6556dcbdcf032bbdfc41c1aa74ded +F test/speed3.test d32043614c08c53eafdc80f33191d5bd9b920523 +F test/speed4.test abc0ad3399dcf9703abed2fff8705e4f8e416715 +F test/speed4p.explain 6b5f104ebeb34a038b2f714150f51d01143e59aa +F test/speed4p.test 0e51908951677de5a969b723e03a27a1c45db38b +F test/spellfix.test 8c40b169b104086d8795781f670ba3c786d6d8be +F test/sqllimits1.test b1aae27cc98eceb845e7f7adf918561256e31298 +F test/stat.test be8d477306006ec696bc86757cfb34bec79447ce +F test/stmt.test 25d64e3dbf9a3ce89558667d7f39d966fe2a71b9 +F test/subquery.test 666fdecceac258f5fd84bed09a64e49d9f37edd9 +F test/subquery2.test 91e1e364072aeff431d1f9689b15147e421d88c7 +F test/subselect.test d24fd8757daf97dafd2e889c73ea4c4272dcf4e4 +F test/substr.test 18f57c4ca8a598805c4d64e304c418734d843c1a +F test/superlock.test 1cde669f68d2dd37d6c9bd35eee1d95491ae3fc2 +F test/sync.test a34cd43e98b7fb84eabbf38f7ed8f7349b3f3d85 +F test/syscall.test a653783d985108c4912cc64d341ffbbb55ad2806 +F test/sysfault.test fa776e60bf46bdd3ae69f0b73e46ee3977a58ae6 +F test/table.test 30423211108121884588d24d6776c7f38702ad7b +F test/tableapi.test 2674633fa95d80da917571ebdd759a14d9819126 +F test/tclsqlite.test 37a61c2da7e3bfe3b8c1a2867199f6b860df5d43 +F test/tempdb.test 19d0f66e2e3eeffd68661a11c83ba5e6ace9128c +F test/temptable.test d2c9b87a54147161bcd1822e30c1d1cd891e5b30 +F test/temptrigger.test 26670ed7a39cf2296a7f0a9e0a1d7bdb7abe936d +F test/tester.tcl 5e97d1fe08f45fa3cc2320cee437e315c75ce995 +F test/thread001.test 9f22fd3525a307ff42a326b6bc7b0465be1745a5 +F test/thread002.test e630504f8a06c00bf8bbe68528774dd96aeb2e58 +F test/thread003.test ee4c9efc3b86a6a2767516a37bd64251272560a7 +F test/thread004.test f51dfc3936184aaf73ee85f315224baad272a87f +F test/thread005.test 50d10b5684399676174bd96c94ad4250b1a2c8b6 +F test/thread1.test df115faa10a4ba1d456e9d4d9ec165016903eae4 +F test/thread2.test f35d2106452b77523b3a2b7d1dcde2e5ee8f9e46 +F test/thread_common.tcl 334639cadcb9f912bf82aa73f49efd5282e6cadd +F test/threadtest1.c 6029d9c5567db28e6dc908a0c63099c3ba6c383b +F test/threadtest2.c ace893054fa134af3fc8d6e7cfecddb8e3acefb9 +F test/threadtest3.c 0ed13e09690f6204d7455fac3b0e8ece490f6eef +F test/tkt-02a8e81d44.test 6c80d9c7514e2a42d4918bf87bf6bc54f379110c +F test/tkt-26ff0c2d1e.test 888324e751512972c6e0d1a09df740d8f5aaf660 +F test/tkt-2a5629202f.test 0521bd25658428baa26665aa53ffed9367d33af2 +F test/tkt-2d1a5c67d.test d371279946622698ab393ff88cad9f5f6d82960b +F test/tkt-2ea2425d34.test 1cf13e6f75d149b3209a0cb32927a82d3d79fb28 +F test/tkt-31338dca7e.test 6fb8807851964da0d24e942f2e19c7c705b9fb58 +F test/tkt-313723c356.test c47f8a9330523e6f35698bf4489bcb29609b53ac +F test/tkt-385a5b56b9.test c0a06ada41d7f06b1686da0e718553f853771d1e +F test/tkt-38cb5df375.test f3cc8671f1eb604d4ae9cf886ed4366bec656678 +F test/tkt-3998683a16.test 6d1d04d551ed1704eb3396ca87bb9ccc8c5c1eb7 +F test/tkt-3a77c9714e.test b08bca26de1140bdf004a37716582a43d7bd8be8 +F test/tkt-3fe897352e.test 27e26eb0f1811aeba4d65aba43a4c52e99da5e70 +F test/tkt-4a03edc4c8.test 2865e4edbc075b954daa82f8da7cc973033ec76e +F test/tkt-4dd95f6943.test 3d0ce415d2ee15d3d564121960016b9c7be79407 +F test/tkt-54844eea3f.test a12b851128f46a695e4e378cca67409b9b8f5894 +F test/tkt-5d863f876e.test c9f36ca503fa154a3655f92a69d2c30da1747bfa +F test/tkt-5e10420e8d.test 904d1687b3c06d43e5b3555bbcf6802e7c0ffd84 +F test/tkt-5ee23731f.test 9db6e1d7209dc0794948b260d6f82b2b1de83a9f +F test/tkt-6bfb98dfc0.test 24780633627b5cfc0635a5500c2389ebfb563336 +F test/tkt-752e1646fc.test ea78d88d14fe9866bdd991c634483334639e13bf +F test/tkt-78e04e52ea.test b0190d3375cf88b97d32188149cc99ccf22f556b +F test/tkt-7a31705a7e6.test e75a2bba4eec801b92c8040eb22096ac6d35e844 +F test/tkt-7bbfb7d442.test 7b2cd79c7a17ae6750e75ec1a7846712a69c9d18 +F test/tkt-80ba201079.test 105a721e6aad0ae3c5946d7615d1e4d03f6145b8 +F test/tkt-80e031a00f.test 9a154173461a4dbe2de49cda73963e04842d52f7 +F test/tkt-8454a207b9.test c583a9f814a82a2b5ba95207f55001c9f0cd816c +F test/tkt-868145d012.test a5f941107ece6a64410ca4755c6329b7eb57a356 +F test/tkt-91e2e8ba6f.test 08c4f94ae07696b05c9b822da0b4e5337a2f54c5 +F test/tkt-94c04eaadb.test fa9c71192f7e2ea2d51bf078bc34e8da6088bf71 +F test/tkt-9d68c883.test 458f7d82a523d7644b54b497c986378a7d8c8b67 +F test/tkt-9f2eb3abac.test 85bc63e749f050e6a61c8f9207f1eee65c9d3395 +F test/tkt-a7b7803e.test 159ef554234fa1f9fb318c751b284bd1cf858da4 +F test/tkt-b1d3a2e531.test 610ef582413171b379652663111b1f996d9f8f78 +F test/tkt-b351d95f9.test d14a503c414c5c58fdde3e80f9a3cfef986498c0 +F test/tkt-b72787b1.test a95e8cdad0b98af1853ac7f0afd4ab27b77bf5f3 +F test/tkt-bd484a090c.test 60460bf946f79a79712b71f202eda501ca99b898 +F test/tkt-bdc6bbbb38.test fc38bb09bdd440e3513a1f5f98fc60a075182d7d +F test/tkt-c48d99d690.test ba61977d62ab612fc515b3c488a6fbd6464a2447 +F test/tkt-cbd054fa6b.test 06ccd57af3c0c7895d0f7dc844f13c51f8258885 +F test/tkt-d11f09d36e.test d999b548fef885d1d1afa49a0e8544ecf436869d +F test/tkt-d635236375.test 9d37e988b47d87505bc9445be0ca447002df5d09 +F test/tkt-d82e3f3721.test bcc0dfba658d15bab30fd4a9320c9e35d214ce30 +F test/tkt-f3e5abed55.test d5a0126118142d13e27f6ce9f4c47096e9321c00 +F test/tkt-f777251dc7a.test af6531446c64bfd268416f07b4df7be7f9c749d2 +F test/tkt-f7b4edec.test d998a08ff2b18b7f62edce8e3044317c45efe6c7 +F test/tkt-f973c7ac31.test 28ef85c7f015477916795246d8286aeda39d4ead +F test/tkt-fa7bf5ec.test 9102dfea58aa371d78969da735f9392c57e2e035 +F test/tkt-fc62af4523.test 72825d3febdedcd5593a27989fc05accdbfc2bb4 +F test/tkt-fc7bd6358f.test 634bb4af7d661e82d6b61b80c86727bad698e08f +F test/tkt1435.test f8c52c41de6e5ca02f1845f3a46e18e25cadac00 +F test/tkt1443.test bacc311da5c96a227bf8c167e77a30c99f8e8368 +F test/tkt1444.test a9d72f9e942708bd82dde6c707da61c489e213e9 +F test/tkt1449.test 93584a449752d52b07d2cfc280a69842b6e16ed5 +F test/tkt1473.test 9d000af3e11a4450d4c596f5e58b4b0d24eb0f8b +F test/tkt1501.test 2064f98e00871848af4b2f517e46c1a7fb2e32db +F test/tkt1512.test a1df1f66caf0b9122d6220c15dcee230298c2c2f +F test/tkt1514.test ddef38e34fea72eb1ab935ded9f17a3fb71dd9df +F test/tkt1536.test 83ff7a7b6e248016f8d682d4f7a4ae114070d466 +F test/tkt1537.test e3a14332de9770be8ff14bd15c19a49cbec10808 +F test/tkt1567.test 18023cc3626a365f0118e17b66decedec93b1a6f +F test/tkt1644.test 80b6a2bb17885f3cf1cb886d97cdad13232bb869 +F test/tkt1667.test 4700d931ed19ea3983e8e703becb28079250b460 +F test/tkt1873.test 0e1b8c023050a430c2525179ed4022ddc7c31264 +F test/tkt2141.test f543d96f50d5a5dc0bc744f7db74ea166720ce46 +F test/tkt2192.test ff40157e5f42e65f844255d220fc6b290470942f +F test/tkt2213.test a9702175601a57b61aba095a233b001d6f362474 +F test/tkt2251.test 5aab8c7898cd2df2a68fe19289cc29e8f5cf8c82 +F test/tkt2285.test cca17be61cf600b397188e77e7143844d2b977e9 +F test/tkt2332.test fc955609b958ca86dfa102832243370a0cc84070 +F test/tkt2339.test 73bd17818924cd2ac442e5fd9916b58565739450 +F test/tkt2391.test ab7a11be7402da8b51a5be603425367aa0684567 +F test/tkt2409.test be0d60e7d283f639dccea4b0b5e1cd3a4851fb5b +F test/tkt2450.test 77ed94863f2049c1420288ddfea2d41e5e0971d6 +F test/tkt2565.test 8be666e927cb207aae88188f31c331870878b650 +F test/tkt2640.test 28134f5d1e05658ef182520cf0b680fa3de5211b +F test/tkt2643.test 3f3ebb743da00d4fed4fcf6daed92a0e18e57813 +F test/tkt2686.test 6ee01c9b9e9c48f6d3a1fdd553b1cc4258f903d6 +F test/tkt2767.test 569000d842678f9cf2db7e0d1b27cbc9011381b0 +F test/tkt2817.test f31839e01f4243cff7399ef654d3af3558cb8d8d +F test/tkt2820.test 39940276b3436d125deb7d8ebeee053e4cf13213 +F test/tkt2822.test f391776423a7c0d0949edfce375708bfb0f3141e +F test/tkt2832.test a9b0b74a02dca166a04d9e37739c414b10929caa +F test/tkt2854.test e432965db29e27e16f539b2ba7f502eb2ccc49af +F test/tkt2920.test a8737380e4ae6424e00c0273dc12775704efbebf +F test/tkt2927.test 4752868b9eeeb07a217f7f19f4cbaac98d6d086d +F test/tkt2942.test c5c87d179799ca6d1fbe83c815510b87cd5ec7ce +F test/tkt3080.test 1bca7579260920a66b4dd7e196e807c0f25ff804 +F test/tkt3093.test fbdbc5b4969244ad11f540759003e361fcaf391f +F test/tkt3121.test 536df66a02838c26a12fe98639354ca1290ca68b +F test/tkt3201.test f1500ccecc0d578dc4cde7d3242008297c4d59b3 +F test/tkt3292.test 962465a0984a3b8c757efe59c2c59144871ee1dd +F test/tkt3298.test 20fd8773b825cb602e033aa04f8602e1ebdcd93c +F test/tkt3334.test ea13a53cb176e90571a76c86605b14a09efe366d +F test/tkt3346.test 6f67c3ed7db94dfc5df4f5f0b63809a1f611e01a +F test/tkt3357.test 77c37c6482b526fe89941ce951c22d011f5922ed +F test/tkt3419.test 1bbf36d7ea03b638c15804251287c2391f5c1f6b +F test/tkt3424.test 61f831bd2b071bd128fa5d00fbda57e656ca5812 +F test/tkt3442.test 53840ec5325bb94544792aad4c20476f81dc26b1 +F test/tkt3457.test 44e980fe5334753dcc27b94fa4deabc485a92f74 +F test/tkt3461.test 228ea328a5a21e8663f80ee3d212a6ad92549a19 +F test/tkt3493.test 1686cbde85f8721fc1bdc0ee72f2ef2f63139218 +F test/tkt3508.test d75704db9501625c7f7deec119fcaf1696aefb7d +F test/tkt3522.test 22ce2ebbcb04a6be56c0977d405c207967318fd6 +F test/tkt3527.test 1a6a48441b560bdc53aec581a868eb576234874d +F test/tkt3541.test 5dc257bde9bc833ab9cc6844bf170b998dbb950a +F test/tkt3554.test f599967f279077bace39220cbe76085c7b423725 +F test/tkt3581.test 1966b7193f1e3f14951cce8c66907ae69454e9a3 +F test/tkt35xx.test 69d038ce5898f1b64f2084b780bbab1cf9be0a25 +F test/tkt3630.test 929f64852103054125200bc825c316d5f75d42f7 +F test/tkt3718.test 3b59dcb5c4e7754dacd91e7fd353a61492cc402a +F test/tkt3731.test 0c5f4cbffe102d43c3b2188af91a9e36348f974b +F test/tkt3757.test 10cd679a88675c880533083fc79ac04324525595 +F test/tkt3761.test b95ea9c98f21cf91325f18a984887e62caceab33 +F test/tkt3762.test 4d439ff7abdc8d9323150269d182c37c2d514576 +F test/tkt3773.test 7bca904d2a647a6a4a291bd86d7fd7c73855b789 +F test/tkt3791.test a6624b9a80b216a26cf473607f42f3e51898c267 +F test/tkt3793.test d90ffd75c52413908d15e1c44fc2ea9c80fcc449 +F test/tkt3810.test 90fa0635dfa7da9680c8cd3513350a49b3a8ae12 +F test/tkt3824.test 150aa00bb6220672e5f0eb14dc8eaa36750425f0 +F test/tkt3832.test 2300d10d57562b89875b72148338ac3e14f8847d +F test/tkt3838.test 292e72489101cd1320d7278dc111c173ebf334d4 +F test/tkt3841.test 4659845bc53f809a5932c61c6ce8c5bb9d6b947f +F test/tkt3871.test 43ecbc8d90dc83908e2a454aef345acc9d160c6f +F test/tkt3879.test 2ad5bef2c87e9991ce941e054c31abe26ef7fb90 +F test/tkt3911.test 74cd324f3ba653040cc6d94cc4857b290d12d633 +F test/tkt3918.test ea78bf164e4d55cbde0d83c671ef6fbe930a0032 +F test/tkt3922.test f26be40ab4fe6c00795629bd2006d96e270d9b1a +F test/tkt3929.test cdf67acf5aa936ec4ffead81db87f8a71fe40e59 +F test/tkt3935.test e15261fedb9e30a4305a311da614a5d8e693c767 +F test/tkt3992.test f3e7d548ac26f763b47bc0f750da3d03c81071da +F test/tkt3997.test a335fa41ca3985660a139df7b734a26ef53284bd +F test/tkt4018.test 7c2c9ba4df489c676a0a7a0e809a1fb9b2185bd1 +F test/tokenize.test ce430a7aed48fc98301611429595883fdfcab5d7 +F test/tpch01.test 8f4ac52f62f3e9f6bce0889105aecdf0275e331b +F test/trace.test 4b36a41a3e9c7842151af6da5998f5080cdad9e5 +F test/trace2.test e7a988fdd982cdec62f1f1f34b0360e6476d01a0 +F test/trans.test 6e1b4c6a42dba31bd65f8fa5e61a2708e08ddde6 +F test/trans2.test d5337e61de45e66b1fcbf9db833fa8c82e624b22 +F test/trans3.test 373ac5183cc56be69f48ae44090e7f672939f732 +F test/transitive1.test 0ee69546d6fa20e577a4a706d7daa01c7eba9239 +F test/trigger1.test dc47573ac79ffe0ee3eecaa517d70d8dacbccd03 +F test/trigger2.test 834187beafd1db383af0c659cfa49b0576832816 +F test/trigger3.test aa640bb2bbb03edd5ff69c055117ea088f121945 +F test/trigger4.test 74700b76ebf3947b2f7a92405141eb2cf2a5d359 +F test/trigger5.test 619391a3e9fc194081d22cefd830d811e7badf83 +F test/trigger6.test 0e411654f122552da6590f0b4e6f781048a4a9b9 +F test/trigger7.test b39e6dee1debe0ff9c2ef66326668f149f07c9c4 +F test/trigger8.test 30cb0530bd7c4728055420e3f739aa00412eafa4 +F test/trigger9.test 5b0789f1c5c4600961f8e68511b825b87be53e31 +F test/triggerA.test fe5597f47ee21bacb4936dc827994ed94161e332 +F test/triggerB.test 56780c031b454abac2340dbb3b71ac5c56c3d7fe +F test/triggerC.test a7b4367392c755bc5fd5fff88011753e6b6afe90 +F test/triggerD.test 8e7f3921a92a5797d472732108109e44575fa650 +F test/triggerE.test 355e9c5cbaed5cd039a60baad1fb2197caeb8e52 +F test/tt3_checkpoint.c 415eccce672d681b297485fc20f44cdf0eac93af +F test/types.test bf816ce73c7dfcfe26b700c19f97ef4050d194ff +F test/types2.test 3555aacf8ed8dc883356e59efc314707e6247a84 +F test/types3.test 99e009491a54f4dc02c06bdbc0c5eea56ae3e25a +F test/unique.test cadb172bbd5a2e83cd644d186ccd602085e54edc +F test/unixexcl.test a9870e46cc6f8390a494513d4f2bf55b5a8b3e46 +F test/unordered.test ef85ac8f2f3c93ed2b9e811b684de73175fc464c +F test/update.test 8bc86fd7ef1a00014f76dc6a6a7c974df4aef172 +F test/uri.test 63e03df051620a18f794b4f4adcdefb3c23b6751 +F test/utf16align.test 54cd35a27c005a9b6e7815d887718780b6a462ae +F test/vacuum.test ce91c39f7f91a4273bf620efad21086b5aa6ef1d +F test/vacuum2.test af432e6e3bfc0ea20a80cb86a03c7d9876d38324 +F test/vacuum3.test 77ecdd54592b45a0bcb133339f99f1ae0ae94d0d +F test/vacuum4.test d3f8ecff345f166911568f397d2432c16d2867d9 +F test/varint.test ab7b110089a08b9926ed7390e7e97bdefeb74102 +F test/veryquick.test 57ab846bacf7b90cf4e9a672721ea5c5b669b661 +F test/view.test 4057630287bfa5955628fe90a13d4c225d1c7352 +F test/vtab1.test 1550abf90bc2b996f8c34e0be3fdb251af54fa41 +F test/vtab2.test 7bcffc050da5c68f4f312e49e443063e2d391c0d +F test/vtab3.test baad99fd27217f5d6db10660522e0b7192446de1 +F test/vtab4.test 942f8b8280b3ea8a41dae20e7822d065ca1cb275 +F test/vtab5.test 889f444970393c73f1e077e2bdc5d845e157a391 +F test/vtab6.test 5f5380c425e52993560ab4763db4f826d2ba7b09 +F test/vtab7.test ae560ebea870ed04e9aa4177cc302f910faaabb5 +F test/vtab8.test e19fa4a538fcd1bb66c22825fa8f71618fb13583 +F test/vtab9.test ea58d2b95d61955f87226381716b2d0b1d4e4f9b +F test/vtabA.test c86e1990b7e1e2bb34602a06fffa4c69f2b516dc +F test/vtabB.test 04df5dc531b9f44d9ca65b9c1b79f12b5922a796 +F test/vtabC.test 4528f459a13136f982e75614d120aef165f17292 +F test/vtabD.test 05b3f1d77117271671089e48719524b676842e96 +F test/vtabE.test 7c4693638d7797ce2eda17af74292b97e705cc61 +F test/vtabF.test fd5ad376f5a34fe0891df1f3cddb4fe7c3eb077e +F test/vtab_alter.test 9e374885248f69e251bdaacf480b04a197f125e5 +F test/vtab_err.test 0d4d8eb4def1d053ac7c5050df3024fd47a3fbd8 +F test/vtab_shared.test 82f463886e18d7f8395a4b6167c91815efe54839 +F test/wal.test 3a6ebdf0287b38b5537c07c517b30dda9aaac317 +F test/wal2.test d4b470f13c87f6d8268b004380afa04c3c67cb90 +F test/wal3.test b22eb662bcbc148c5f6d956eaf94b047f7afe9c0 +F test/wal4.test 4744e155cd6299c6bd99d3eab1c82f77db9cdb3c +F test/wal5.test 8f888b50f66b78821e61ed0e233ded5de378224b +F test/wal6.test 527581f5527bf9c24394991e2be83000aace5f9e +F test/wal7.test 2ae8f427d240099cc4b2dfef63cff44e2a68a1bd +F test/wal8.test 75c42e1bc4545c277fed212f8fc9b7723cd02216 +F test/wal9.test 378e76a9ad09cd9bee06c172ad3547b0129a6750 +F test/wal_common.tcl a98f17fba96206122eff624db0ab13ec377be4fe +F test/walbak.test b9f68e39646375c2b877be906babcc15d38b4877 +F test/walbig.test f437473a16cfb314867c6b5d1dbcd519e73e3434 +F test/walcksum.test 9afeb96240296c08c72fc524d199c912cfe34daa +F test/walcrash.test 451d79e528add5c42764cea74aa2750754171b25 +F test/walcrash2.test a0edab4e5390f03b99a790de89aad15d6ec70b36 +F test/walcrash3.test e426aa58122d20f2b9fbe9a507f9eb8cab85b8af +F test/walfault.test 54ad6e849c727f4da463964b9eb8c8e8e155cf82 +F test/walhook.test ed00a40ba7255da22d6b66433ab61fab16a63483 +F test/walmode.test 4022fe03ae6e830583672caa101f046438a0473c +F test/walnoshm.test 84ca10c544632a756467336b7c3b864d493ee496 +F test/walpersist.test 8c6b7e3ec1ba91b5e4dc4e0921d6d3f87cd356a6 +F test/walro.test 6cc247a0cc9b36aeea2057dd28a922a1cdfbd630 +F test/walshared.test 0befc811dcf0b287efae21612304d15576e35417 +F test/walslow.test e7be6d9888f83aa5d3d3c7c08aa9b5c28b93609a +F test/walthread.test de8dbaf6d9e41481c460ba31ca61e163d7348f8e +F test/where.test 701a633ed16c661cd597b9d504b485197a0f49d7 +F test/where2.test ed6baa9420a109d8be683dbef5d153d186f3690b +F test/where3.test d28c51f257e60be30f74308fa385ceeddfb54a6e +F test/where4.test e9b9e2f2f98f00379e6031db6a6fca29bae782a2 +F test/where5.test fdf66f96d29a064b63eb543e28da4dfdccd81ad2 +F test/where6.test 5da5a98cec820d488e82708301b96cb8c18a258b +F test/where7.test 5a4b0abc207d71da4deecd734ad8579e8dd40aa8 +F test/where8.test 6f95896633cf2d307b5263145b942b7d33e837c6 +F test/where8m.test da346596e19d54f0aba35ebade032a7c47d79739 +F test/where9.test 4f3eab951353a3ae164befc521c777dfa903e46c +F test/whereA.test 4d253178d135ec46d1671e440cd8f2b916aa6e6b +F test/whereB.test 0def95db3bdec220a731c7e4bec5930327c1d8c5 +F test/whereC.test d6f4ecd4fa2d9429681a5b22a25d2bda8e86ab8a +F test/whereD.test 6c2feb79ef1f68381b07f39017fe5f9b96da8d62 +F test/whereE.test b3a055eef928c992b0a33198a7b8dc10eea5ad2f +F test/whereF.test 5b2ba0dbe8074aa13e416b37c753991f0a2492d7 +F test/whereG.test 2a3d5181decc801b36600fa1c40b0dad2ccc267f +F test/wherelimit.test 5e9fd41e79bb2b2d588ed999d641d9c965619b31 +F test/wild001.test bca33f499866f04c24510d74baf1e578d4e44b1c +F test/win32lock.test 7a6bd73a5dcdee39b5bb93e92395e1773a194361 +F test/win32longpath.test e2aafc07e6990fe86c69be22a3d1a0e210cd329b +F test/zeroblob.test caaecfb4f908f7bc086ed238668049f96774d688 +F test/zerodamage.test 209d7ed441f44cc5299e4ebffbef06fd5aabfefd +F tool/build-all-msvc.bat 38623a30fd58288fda5cc7f7df2682aaab75c9d5 x +F tool/build-shell.sh 950f47c6174f1eea171319438b93ba67ff5bf367 +F tool/checkSpacing.c 810e51703529a204fc4e1eb060e9ab663e3c06d2 +F tool/diffdb.c 7524b1b5df217c20cd0431f6789851a4e0cb191b +F tool/extract.c 054069d81b095fbdc189a6f5d4466e40380505e2 +F tool/fast_vacuum.c 5ba0d6f5963a0a63bdc42840f678bad75b2ebce1 +F tool/fragck.tcl 5265a95126abcf6ab357f7efa544787e5963f439 +F tool/genfkey.README cf68fddd4643bbe3ff8e31b8b6d8b0a1b85e20f4 +F tool/genfkey.test 4196a8928b78f51d54ef58e99e99401ab2f0a7e5 +F tool/getlock.c f4c39b651370156cae979501a7b156bdba50e7ce +F tool/lemon.c 796930d5fc2036c7636f3f1ee12f9ae03719a2eb +F tool/lempar.c 01ca97f87610d1dac6d8cd96ab109ab1130e76dc +F tool/logest.c 7ad625cac3d54012b27d468b7af6612f78b9ba75 +F tool/mkautoconfamal.sh f8d8dbf7d62f409ebed5134998bf5b51d7266383 +F tool/mkkeywordhash.c bb52064aa614e1426445e4b2b9b00eeecd23cc79 +F tool/mkopts.tcl 66ac10d240cc6e86abd37dc908d50382f84ff46e +F tool/mkpragmatab.tcl 3fc52e00a234750675e8a569d2919ff48558e9eb +F tool/mkspeedsql.tcl a1a334d288f7adfe6e996f2e712becf076745c97 +F tool/mksqlite3c-noext.tcl 8bce31074e4cbe631bb7676526a048335f4c9f02 +F tool/mksqlite3c.tcl d8dc444d403019167260e5578f5c362741f03696 +F tool/mksqlite3h.tcl ba24038056f51fde07c0079c41885ab85e2cff12 +F tool/mksqlite3internalh.tcl 3dca7bb5374cee003379b8cbac73714f610ef795 +F tool/mkvsix.tcl 6477fb9dab838b7eea1eed50658ff1cda04850b5 +F tool/offsets.c fe4262fdfa378e8f5499a42136d17bf3b98f6091 +F tool/omittest.tcl 4665982e95a6e5c1bd806cf7bc3dea95be422d77 +F tool/opcodeDoc.awk b3a2a3d5d3075b8bd90b7afe24283efdd586659c +F tool/pagesig.c ff0ca355fd3c2398e933da5e22439bbff89b803b +F tool/restore_jrnl.tcl 6957a34f8f1f0f8285e07536225ec3b292a9024a +F tool/rollback-test.c 9fc98427d1e23e84429d7e6d07d9094fbdec65a5 +F tool/showdb.c 525ecc443578647703051308ad50a93de6ba2c4b +F tool/showjournal.c b62cecaab86a4053d944c276bb5232e4d17ece02 +F tool/showwal.c 3f7f7da5ec0cba51b1449a75f700493377da57b5 +F tool/soak1.tcl 8d407956e1a45b485a8e072470a3e629a27037fe +F tool/space_used.tcl f714c41a59e326b8b9042f415b628b561bafa06b +F tool/spaceanal.tcl d8c11da184b1a13d0456d786e70b3867e141b74a +F tool/speedtest.tcl 06c76698485ccf597b9e7dbb1ac70706eb873355 +F tool/speedtest16.c c8a9c793df96db7e4933f0852abb7a03d48f2e81 +F tool/speedtest2.tcl ee2149167303ba8e95af97873c575c3e0fab58ff +F tool/speedtest8.c 2902c46588c40b55661e471d7a86e4dd71a18224 +F tool/speedtest8inst1.c 293327bc76823f473684d589a8160bde1f52c14e +F tool/split-sqlite3c.tcl d9be87f1c340285a3e081eb19b4a247981ed290c +F tool/stack_usage.tcl f8e71b92cdb099a147dad572375595eae55eca43 +F tool/symbols-mingw.sh 4dbcea7e74768305384c9fd2ed2b41bbf9f0414d +F tool/symbols.sh fec58532668296d7c7dc48be9c87f75ccdb5814f +F tool/tostr.awk e75472c2f98dd76e06b8c9c1367f4ab07e122d06 +F tool/vdbe-compress.tcl f12c884766bd14277f4fcedcae07078011717381 +F tool/warnings-clang.sh f6aa929dc20ef1f856af04a730772f59283631d4 +F tool/warnings.sh d1a6de74685f360ab718efda6265994b99bbea01 +F tool/win/sqlite.vsix 030f3eeaf2cb811a3692ab9c14d021a75ce41fff +P e5a439cfa5c921187e4aa7050832ec2660fba13d +R 306f92498230c90834f5567c36b98354 +T +bgcolor * #d0c0ff +T +sym-release * +T +sym-version-3.8.1 * +U drh +Z 83ae1adeb4d6f6ab1edc809d597efad3 diff --git a/components/external/SQLite-3.8.1/manifest.uuid b/components/external/SQLite-3.8.1/manifest.uuid new file mode 100644 index 0000000000000000000000000000000000000000..b27cb5709a2c09f6a67118fc461e3533822c8c86 --- /dev/null +++ b/components/external/SQLite-3.8.1/manifest.uuid @@ -0,0 +1 @@ +c78be6d786c19073b3a6730dfe3fb1be54f5657a diff --git a/components/external/SQLite-3.8.1/mkdll.sh b/components/external/SQLite-3.8.1/mkdll.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e368d1d23bc5049ee932a8eb35423a49e247f17 --- /dev/null +++ b/components/external/SQLite-3.8.1/mkdll.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# +# This script is used to compile SQLite into a DLL. +# +# Two separate DLLs are generated. "sqlite3.dll" is the core +# library. "tclsqlite3.dll" contains the TCL bindings and is the +# library that is loaded into TCL in order to run SQLite. +# +make sqlite3.c +PATH=$PATH:/opt/mingw/bin +TCLDIR=/home/drh/tcltk/846/win/846win +TCLSTUBLIB=$TCLDIR/libtcl84stub.a +OPTS='-DUSE_TCL_STUBS=1 -DBUILD_sqlite=1 -DSQLITE_OS_WIN=1' +OPTS="$OPTS -DSQLITE_THREADSAFE=1" +OPTS="$OPTS -DSQLITE_ENABLE_FTS3=1" +OPTS="$OPTS -DSQLITE_ENABLE_RTREE=1" +OPTS="$OPTS -DSQLITE_ENABLE_COLUMN_METADATA=1" +CC="i386-mingw32msvc-gcc -Os $OPTS -Itsrc -I$TCLDIR" +NM="i386-mingw32msvc-nm" +CMD="$CC -c sqlite3.c" +echo $CMD +$CMD +CMD="$CC -c tclsqlite3.c" +echo $CMD +$CMD +echo 'EXPORTS' >tclsqlite3.def +$NM tclsqlite3.o | grep ' T ' >temp1 +grep '_Init$' temp1 >temp2 +grep '_SafeInit$' temp1 >>temp2 +grep ' T _sqlite3_' temp1 >>temp2 +echo 'EXPORTS' >tclsqlite3.def +sed 's/^.* T _//' temp2 | sort | uniq >>tclsqlite3.def +i386-mingw32msvc-dllwrap \ + --def tclsqlite3.def -v --export-all \ + --driver-name i386-mingw32msvc-gcc \ + --dlltool-name i386-mingw32msvc-dlltool \ + --as i386-mingw32msvc-as \ + --target i386-mingw32 \ + -dllname tclsqlite3.dll -lmsvcrt tclsqlite3.o $TCLSTUBLIB +$NM sqlite3.o | grep ' T ' >temp1 +echo 'EXPORTS' >sqlite3.def +grep ' _sqlite3_' temp1 | sed 's/^.* _//' >>sqlite3.def +i386-mingw32msvc-dllwrap \ + --def sqlite3.def -v --export-all \ + --driver-name i386-mingw32msvc-gcc \ + --dlltool-name i386-mingw32msvc-dlltool \ + --as i386-mingw32msvc-as \ + --target i386-mingw32 \ + -dllname sqlite3.dll -lmsvcrt sqlite3.o diff --git a/components/external/SQLite-3.8.1/mkextu.sh b/components/external/SQLite-3.8.1/mkextu.sh new file mode 100644 index 0000000000000000000000000000000000000000..1d968977694309800cdcc6ade0d32796571ad8b0 --- /dev/null +++ b/components/external/SQLite-3.8.1/mkextu.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# +# This script is used to compile SQLite into a shared library on Linux. +# +# Two separate shared libraries are generated. "sqlite3.so" is the core +# library. "tclsqlite3.so" contains the TCL bindings and is the +# library that is loaded into TCL in order to run SQLite. +# +CFLAGS=-O2 -Wall +make fts2amal.c +echo gcc $CFLAGS -shared fts2amal.c -o fts2.so +gcc $CFLAGS -shared fts2amal.c -o fts2.so +strip fts2.so diff --git a/components/external/SQLite-3.8.1/mkextw.sh b/components/external/SQLite-3.8.1/mkextw.sh new file mode 100644 index 0000000000000000000000000000000000000000..909a126c38aa2098670d1d6181595dacc5590f8e --- /dev/null +++ b/components/external/SQLite-3.8.1/mkextw.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# +# This script is used to compile SQLite extensions into DLLs. +# +make fts2amal.c +PATH=$PATH:/opt/mingw/bin +OPTS='-DTHREADSAFE=1 -DBUILD_sqlite=1 -DSQLITE_OS_WIN=1' +CC="i386-mingw32msvc-gcc -O2 $OPTS -Itsrc" +NM="i386-mingw32msvc-nm" +CMD="$CC -c fts2amal.c" +echo $CMD +$CMD +echo 'EXPORTS' >fts2.def +echo 'sqlite3_fts2_init' >>fts2.def +i386-mingw32msvc-dllwrap \ + --def fts2.def -v --export-all \ + --driver-name i386-mingw32msvc-gcc \ + --dlltool-name i386-mingw32msvc-dlltool \ + --as i386-mingw32msvc-as \ + --target i386-mingw32 \ + -dllname fts2.dll -lmsvcrt fts2amal.o +zip fts2dll.zip fts2.dll fts2.def diff --git a/components/external/SQLite-3.8.1/mkopcodec.awk b/components/external/SQLite-3.8.1/mkopcodec.awk new file mode 100644 index 0000000000000000000000000000000000000000..2ef77d4cca86bcc4181d9e4c961ffdac6d9a753f --- /dev/null +++ b/components/external/SQLite-3.8.1/mkopcodec.awk @@ -0,0 +1,36 @@ +#!/usr/bin/awk -f +# +# This AWK script scans the opcodes.h file (which is itself generated by +# another awk script) and uses the information gleaned to create the +# opcodes.c source file. +# +# Opcodes.c contains strings which are the symbolic names for the various +# opcodes used by the VDBE. These strings are used when disassembling a +# VDBE program during tracing or as a result of the EXPLAIN keyword. +# +BEGIN { + print "/* Automatically generated. Do not edit */" + print "/* See the mkopcodec.awk script for details. */" + printf "#if !defined(SQLITE_OMIT_EXPLAIN)" + printf " || !defined(NDEBUG)" + printf " || defined(VDBE_PROFILE)" + print " || defined(SQLITE_DEBUG)" + print "const char *sqlite3OpcodeName(int i){" + print " static const char *const azName[] = { \"?\"," + mx = 0 +} +/define OP_/ { + sub("OP_","",$2) + i = $3+0 + label[i] = $2 + if( mx=0 ) continue; + if( name=="OP_Function" \ + || name=="OP_AggStep" \ + || name=="OP_Transaction" \ + || name=="OP_AutoCommit" \ + || name=="OP_Savepoint" \ + || name=="OP_Checkpoint" \ + || name=="OP_Vacuum" \ + || name=="OP_JournalMode" \ + || name=="OP_VUpdate" \ + || name=="OP_VFilter" \ + || name=="OP_Next" \ + || name=="OP_SorterNext" \ + || name=="OP_Prev" \ + ){ + cnt++ + while( used[cnt] ) cnt++ + op[name] = cnt + used[cnt] = 1 + def[cnt] = name + } + } + + # Generate the numeric values for opcodes + for(i=0; i +#if defined(_WIN32) +# define WIN32_LEAN_AND_MEAN +# include +#else +# include +#endif +#include +#include +#include +#include + +/* The suffix to append to the child command lines, if any */ +#if defined(_WIN32) +# define GETPID (int)GetCurrentProcessId +#else +# define GETPID getpid +#endif + +/* Mark a parameter as unused to suppress compiler warnings */ +#define UNUSED_PARAMETER(x) (void)x + +/* Global data +*/ +static struct Global { + char *argv0; /* Name of the executable */ + const char *zVfs; /* Name of VFS to use. Often NULL meaning "default" */ + char *zDbFile; /* Name of the database */ + sqlite3 *db; /* Open connection to database */ + char *zErrLog; /* Filename for error log */ + FILE *pErrLog; /* Where to write errors */ + char *zLog; /* Name of output log file */ + FILE *pLog; /* Where to write log messages */ + char zName[32]; /* Symbolic name of this process */ + int taskId; /* Task ID. 0 means supervisor. */ + int iTrace; /* Tracing level */ + int bSqlTrace; /* True to trace SQL commands */ + int bIgnoreSqlErrors; /* Ignore errors in SQL statements */ + int nError; /* Number of errors */ + int nTest; /* Number of --match operators */ + int iTimeout; /* Milliseconds until a busy timeout */ + int bSync; /* Call fsync() */ +} g; + +/* Default timeout */ +#define DEFAULT_TIMEOUT 10000 + +/* +** Print a message adding zPrefix[] to the beginning of every line. +*/ +static void printWithPrefix(FILE *pOut, const char *zPrefix, const char *zMsg){ + while( zMsg && zMsg[0] ){ + int i; + for(i=0; zMsg[i] && zMsg[i]!='\n' && zMsg[i]!='\r'; i++){} + fprintf(pOut, "%s%.*s\n", zPrefix, i, zMsg); + zMsg += i; + while( zMsg[0]=='\n' || zMsg[0]=='\r' ) zMsg++; + } +} + +/* +** Compare two pointers to strings, where the pointers might be NULL. +*/ +static int safe_strcmp(const char *a, const char *b){ + if( a==b ) return 0; + if( a==0 ) return -1; + if( b==0 ) return 1; + return strcmp(a,b); +} + +/* +** Return TRUE if string z[] matches glob pattern zGlob[]. +** Return FALSE if the pattern does not match. +** +** Globbing rules: +** +** '*' Matches any sequence of zero or more characters. +** +** '?' Matches exactly one character. +** +** [...] Matches one character from the enclosed list of +** characters. +** +** [^...] Matches one character not in the enclosed list. +** +** '#' Matches any sequence of one or more digits with an +** optional + or - sign in front +*/ +int strglob(const char *zGlob, const char *z){ + int c, c2; + int invert; + int seen; + + while( (c = (*(zGlob++)))!=0 ){ + if( c=='*' ){ + while( (c=(*(zGlob++))) == '*' || c=='?' ){ + if( c=='?' && (*(z++))==0 ) return 0; + } + if( c==0 ){ + return 1; + }else if( c=='[' ){ + while( *z && strglob(zGlob-1,z) ){ + z++; + } + return (*z)!=0; + } + while( (c2 = (*(z++)))!=0 ){ + while( c2!=c ){ + c2 = *(z++); + if( c2==0 ) return 0; + } + if( strglob(zGlob,z) ) return 1; + } + return 0; + }else if( c=='?' ){ + if( (*(z++))==0 ) return 0; + }else if( c=='[' ){ + int prior_c = 0; + seen = 0; + invert = 0; + c = *(z++); + if( c==0 ) return 0; + c2 = *(zGlob++); + if( c2=='^' ){ + invert = 1; + c2 = *(zGlob++); + } + if( c2==']' ){ + if( c==']' ) seen = 1; + c2 = *(zGlob++); + } + while( c2 && c2!=']' ){ + if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ + c2 = *(zGlob++); + if( c>=prior_c && c<=c2 ) seen = 1; + prior_c = 0; + }else{ + if( c==c2 ){ + seen = 1; + } + prior_c = c2; + } + c2 = *(zGlob++); + } + if( c2==0 || (seen ^ invert)==0 ) return 0; + }else if( c=='#' ){ + if( (z[0]=='-' || z[0]=='+') && isdigit(z[1]) ) z++; + if( !isdigit(z[0]) ) return 0; + z++; + while( isdigit(z[0]) ){ z++; } + }else{ + if( c!=(*(z++)) ) return 0; + } + } + return *z==0; +} + +/* +** Close output stream pOut if it is not stdout or stderr +*/ +static void maybeClose(FILE *pOut){ + if( pOut!=stdout && pOut!=stderr ) fclose(pOut); +} + +/* +** Print an error message +*/ +static void errorMessage(const char *zFormat, ...){ + va_list ap; + char *zMsg; + char zPrefix[30]; + va_start(ap, zFormat); + zMsg = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:ERROR: ", g.zName); + if( g.pLog ){ + printWithPrefix(g.pLog, zPrefix, zMsg); + fflush(g.pLog); + } + if( g.pErrLog && safe_strcmp(g.zErrLog,g.zLog) ){ + printWithPrefix(g.pErrLog, zPrefix, zMsg); + fflush(g.pErrLog); + } + sqlite3_free(zMsg); + g.nError++; +} + +/* Forward declaration */ +static int trySql(const char*, ...); + +/* +** Print an error message and then quit. +*/ +static void fatalError(const char *zFormat, ...){ + va_list ap; + char *zMsg; + char zPrefix[30]; + va_start(ap, zFormat); + zMsg = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:FATAL: ", g.zName); + if( g.pLog ){ + printWithPrefix(g.pLog, zPrefix, zMsg); + fflush(g.pLog); + maybeClose(g.pLog); + } + if( g.pErrLog && safe_strcmp(g.zErrLog,g.zLog) ){ + printWithPrefix(g.pErrLog, zPrefix, zMsg); + fflush(g.pErrLog); + maybeClose(g.pErrLog); + } + sqlite3_free(zMsg); + if( g.db ){ + int nTry = 0; + g.iTimeout = 0; + while( trySql("UPDATE client SET wantHalt=1;")==SQLITE_BUSY + && (nTry++)<100 ){ + sqlite3_sleep(10); + } + } + sqlite3_close(g.db); + exit(1); +} + + +/* +** Print a log message +*/ +static void logMessage(const char *zFormat, ...){ + va_list ap; + char *zMsg; + char zPrefix[30]; + va_start(ap, zFormat); + zMsg = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s: ", g.zName); + if( g.pLog ){ + printWithPrefix(g.pLog, zPrefix, zMsg); + fflush(g.pLog); + } + sqlite3_free(zMsg); +} + +/* +** Return the length of a string omitting trailing whitespace +*/ +static int clipLength(const char *z){ + int n = (int)strlen(z); + while( n>0 && isspace(z[n-1]) ){ n--; } + return n; +} + +/* +** Auxiliary SQL function to return the name of the VFS +*/ +static void vfsNameFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + char *zVfs = 0; + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + sqlite3_file_control(db, "main", SQLITE_FCNTL_VFSNAME, &zVfs); + if( zVfs ){ + sqlite3_result_text(context, zVfs, -1, sqlite3_free); + } +} + +/* +** Busy handler with a g.iTimeout-millisecond timeout +*/ +static int busyHandler(void *pCD, int count){ + UNUSED_PARAMETER(pCD); + if( count*10>g.iTimeout ){ + if( g.iTimeout>0 ) errorMessage("timeout after %dms", g.iTimeout); + return 0; + } + sqlite3_sleep(10); + return 1; +} + +/* +** SQL Trace callback +*/ +static void sqlTraceCallback(void *NotUsed1, const char *zSql){ + UNUSED_PARAMETER(NotUsed1); + logMessage("[%.*s]", clipLength(zSql), zSql); +} + +/* +** SQL error log callback +*/ +static void sqlErrorCallback(void *pArg, int iErrCode, const char *zMsg){ + UNUSED_PARAMETER(pArg); + if( iErrCode==SQLITE_ERROR && g.bIgnoreSqlErrors ) return; + if( (iErrCode&0xff)==SQLITE_SCHEMA && g.iTrace<3 ) return; + if( g.iTimeout==0 && (iErrCode&0xff)==SQLITE_BUSY && g.iTrace<3 ) return; + if( (iErrCode&0xff)==SQLITE_NOTICE ){ + logMessage("(info) %s", zMsg); + }else{ + errorMessage("(errcode=%d) %s", iErrCode, zMsg); + } +} + +/* +** Prepare an SQL statement. Issue a fatal error if unable. +*/ +static sqlite3_stmt *prepareSql(const char *zFormat, ...){ + va_list ap; + char *zSql; + int rc; + sqlite3_stmt *pStmt = 0; + va_start(ap, zFormat); + zSql = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + rc = sqlite3_prepare_v2(g.db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + sqlite3_finalize(pStmt); + fatalError("%s\n%s\n", sqlite3_errmsg(g.db), zSql); + } + sqlite3_free(zSql); + return pStmt; +} + +/* +** Run arbitrary SQL. Issue a fatal error on failure. +*/ +static void runSql(const char *zFormat, ...){ + va_list ap; + char *zSql; + int rc; + va_start(ap, zFormat); + zSql = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + rc = sqlite3_exec(g.db, zSql, 0, 0, 0); + if( rc!=SQLITE_OK ){ + fatalError("%s\n%s\n", sqlite3_errmsg(g.db), zSql); + } + sqlite3_free(zSql); +} + +/* +** Try to run arbitrary SQL. Return success code. +*/ +static int trySql(const char *zFormat, ...){ + va_list ap; + char *zSql; + int rc; + va_start(ap, zFormat); + zSql = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + rc = sqlite3_exec(g.db, zSql, 0, 0, 0); + sqlite3_free(zSql); + return rc; +} + +/* Structure for holding an arbitrary length string +*/ +typedef struct String String; +struct String { + char *z; /* the string */ + int n; /* Slots of z[] used */ + int nAlloc; /* Slots of z[] allocated */ +}; + +/* Free a string */ +static void stringFree(String *p){ + if( p->z ) sqlite3_free(p->z); + memset(p, 0, sizeof(*p)); +} + +/* Append n bytes of text to a string. If n<0 append the entire string. */ +static void stringAppend(String *p, const char *z, int n){ + if( n<0 ) n = (int)strlen(z); + if( p->n+n>=p->nAlloc ){ + int nAlloc = p->nAlloc*2 + n + 100; + char *z = sqlite3_realloc(p->z, nAlloc); + if( z==0 ) fatalError("out of memory"); + p->z = z; + p->nAlloc = nAlloc; + } + memcpy(p->z+p->n, z, n); + p->n += n; + p->z[p->n] = 0; +} + +/* Reset a string to an empty string */ +static void stringReset(String *p){ + if( p->z==0 ) stringAppend(p, " ", 1); + p->n = 0; + p->z[0] = 0; +} + +/* Append a new token onto the end of the string */ +static void stringAppendTerm(String *p, const char *z){ + int i; + if( p->n ) stringAppend(p, " ", 1); + if( z==0 ){ + stringAppend(p, "nil", 3); + return; + } + for(i=0; z[i] && !isspace(z[i]); i++){} + if( i>0 && z[i]==0 ){ + stringAppend(p, z, i); + return; + } + stringAppend(p, "'", 1); + while( z[0] ){ + for(i=0; z[i] && z[i]!='\''; i++){} + if( z[i] ){ + stringAppend(p, z, i+1); + stringAppend(p, "'", 1); + z += i+1; + }else{ + stringAppend(p, z, i); + break; + } + } + stringAppend(p, "'", 1); +} + +/* +** Callback function for evalSql() +*/ +static int evalCallback(void *pCData, int argc, char **argv, char **azCol){ + String *p = (String*)pCData; + int i; + UNUSED_PARAMETER(azCol); + for(i=0; i0 ); + rc = sqlite3_exec(g.db, zSql, evalCallback, p, &zErrMsg); + sqlite3_free(zSql); + if( rc ){ + char zErr[30]; + sqlite3_snprintf(sizeof(zErr), zErr, "error(%d)", rc); + stringAppendTerm(p, zErr); + if( zErrMsg ){ + stringAppendTerm(p, zErrMsg); + sqlite3_free(zErrMsg); + } + } + return rc; +} + +/* +** Auxiliary SQL function to recursively evaluate SQL. +*/ +static void evalFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + const char *zSql = (const char*)sqlite3_value_text(argv[0]); + String res; + char *zErrMsg = 0; + int rc; + UNUSED_PARAMETER(argc); + memset(&res, 0, sizeof(res)); + rc = sqlite3_exec(db, zSql, evalCallback, &res, &zErrMsg); + if( zErrMsg ){ + sqlite3_result_error(context, zErrMsg, -1); + sqlite3_free(zErrMsg); + }else if( rc ){ + sqlite3_result_error_code(context, rc); + }else{ + sqlite3_result_text(context, res.z, -1, SQLITE_TRANSIENT); + } + stringFree(&res); +} + +/* +** Look up the next task for client iClient in the database. +** Return the task script and the task number and mark that +** task as being under way. +*/ +static int startScript( + int iClient, /* The client number */ + char **pzScript, /* Write task script here */ + int *pTaskId, /* Write task number here */ + char **pzTaskName /* Name of the task */ +){ + sqlite3_stmt *pStmt = 0; + int taskId; + int rc; + int totalTime = 0; + + *pzScript = 0; + g.iTimeout = 0; + while(1){ + rc = trySql("BEGIN IMMEDIATE"); + if( rc==SQLITE_BUSY ){ + sqlite3_sleep(10); + totalTime += 10; + continue; + } + if( rc!=SQLITE_OK ){ + fatalError("in startScript: %s", sqlite3_errmsg(g.db)); + } + if( g.nError || g.nTest ){ + runSql("UPDATE counters SET nError=nError+%d, nTest=nTest+%d", + g.nError, g.nTest); + g.nError = 0; + g.nTest = 0; + } + pStmt = prepareSql("SELECT 1 FROM client WHERE id=%d AND wantHalt",iClient); + rc = sqlite3_step(pStmt); + sqlite3_finalize(pStmt); + if( rc==SQLITE_ROW ){ + runSql("DELETE FROM client WHERE id=%d", iClient); + g.iTimeout = DEFAULT_TIMEOUT; + runSql("COMMIT TRANSACTION;"); + return SQLITE_DONE; + } + pStmt = prepareSql( + "SELECT script, id, name FROM task" + " WHERE client=%d AND starttime IS NULL" + " ORDER BY id LIMIT 1", iClient); + rc = sqlite3_step(pStmt); + if( rc==SQLITE_ROW ){ + int n = sqlite3_column_bytes(pStmt, 0); + *pzScript = sqlite3_malloc(n+1); + strcpy(*pzScript, (const char*)sqlite3_column_text(pStmt, 0)); + *pTaskId = taskId = sqlite3_column_int(pStmt, 1); + *pzTaskName = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 2)); + sqlite3_finalize(pStmt); + runSql("UPDATE task" + " SET starttime=strftime('%%Y-%%m-%%d %%H:%%M:%%f','now')" + " WHERE id=%d;", taskId); + g.iTimeout = DEFAULT_TIMEOUT; + runSql("COMMIT TRANSACTION;"); + return SQLITE_OK; + } + sqlite3_finalize(pStmt); + if( rc==SQLITE_DONE ){ + if( totalTime>30000 ){ + errorMessage("Waited over 30 seconds with no work. Giving up."); + runSql("DELETE FROM client WHERE id=%d; COMMIT;", iClient); + sqlite3_close(g.db); + exit(1); + } + while( trySql("COMMIT")==SQLITE_BUSY ){ + sqlite3_sleep(10); + totalTime += 10; + } + sqlite3_sleep(100); + totalTime += 100; + continue; + } + fatalError("%s", sqlite3_errmsg(g.db)); + } + g.iTimeout = DEFAULT_TIMEOUT; +} + +/* +** Mark a script as having finished. Remove the CLIENT table entry +** if bShutdown is true. +*/ +static int finishScript(int iClient, int taskId, int bShutdown){ + runSql("UPDATE task" + " SET endtime=strftime('%%Y-%%m-%%d %%H:%%M:%%f','now')" + " WHERE id=%d;", taskId); + if( bShutdown ){ + runSql("DELETE FROM client WHERE id=%d", iClient); + } + return SQLITE_OK; +} + +/* +** Start up a client process for iClient, if it is not already +** running. If the client is already running, then this routine +** is a no-op. +*/ +static void startClient(int iClient){ + runSql("INSERT OR IGNORE INTO client VALUES(%d,0)", iClient); + if( sqlite3_changes(g.db) ){ + char *zSys; + int rc; + zSys = sqlite3_mprintf("%s \"%s\" --client %d --trace %d", + g.argv0, g.zDbFile, iClient, g.iTrace); + if( g.bSqlTrace ){ + zSys = sqlite3_mprintf("%z --sqltrace", zSys); + } + if( g.bSync ){ + zSys = sqlite3_mprintf("%z --sync", zSys); + } + if( g.zVfs ){ + zSys = sqlite3_mprintf("%z --vfs \"%s\"", zSys, g.zVfs); + } + if( g.iTrace>=2 ) logMessage("system('%q')", zSys); +#if !defined(_WIN32) + zSys = sqlite3_mprintf("%z &", zSys); + rc = system(zSys); + if( rc ) errorMessage("system() fails with error code %d", rc); +#else + { + STARTUPINFOA startupInfo; + PROCESS_INFORMATION processInfo; + memset(&startupInfo, 0, sizeof(startupInfo)); + startupInfo.cb = sizeof(startupInfo); + memset(&processInfo, 0, sizeof(processInfo)); + rc = CreateProcessA(NULL, zSys, NULL, NULL, FALSE, 0, NULL, NULL, + &startupInfo, &processInfo); + if( rc ){ + CloseHandle(processInfo.hThread); + CloseHandle(processInfo.hProcess); + }else{ + errorMessage("CreateProcessA() fails with error code %lu", + GetLastError()); + } + } +#endif + sqlite3_free(zSys); + } +} + +/* +** Read the entire content of a file into memory +*/ +static char *readFile(const char *zFilename){ + FILE *in = fopen(zFilename, "rb"); + long sz; + char *z; + if( in==0 ){ + fatalError("cannot open \"%s\" for reading", zFilename); + } + fseek(in, 0, SEEK_END); + sz = ftell(in); + rewind(in); + z = sqlite3_malloc( sz+1 ); + sz = (long)fread(z, 1, sz, in); + z[sz] = 0; + fclose(in); + return z; +} + +/* +** Return the length of the next token. +*/ +static int tokenLength(const char *z, int *pnLine){ + int n = 0; + if( isspace(z[0]) || (z[0]=='/' && z[1]=='*') ){ + int inC = 0; + int c; + if( z[0]=='/' ){ + inC = 1; + n = 2; + } + while( (c = z[n++])!=0 ){ + if( c=='\n' ) (*pnLine)++; + if( isspace(c) ) continue; + if( inC && c=='*' && z[n]=='/' ){ + n++; + inC = 0; + }else if( !inC && c=='/' && z[n]=='*' ){ + n++; + inC = 1; + }else if( !inC ){ + break; + } + } + n--; + }else if( z[0]=='-' && z[1]=='-' ){ + for(n=2; z[n] && z[n]!='\n'; n++){} + if( z[n] ){ (*pnLine)++; n++; } + }else if( z[0]=='"' || z[0]=='\'' ){ + int delim = z[0]; + for(n=1; z[n]; n++){ + if( z[n]=='\n' ) (*pnLine)++; + if( z[n]==delim ){ + n++; + if( z[n+1]!=delim ) break; + } + } + }else{ + int c; + for(n=1; (c = z[n])!=0 && !isspace(c) && c!='"' && c!='\'' && c!=';'; n++){} + } + return n; +} + +/* +** Copy a single token into a string buffer. +*/ +static int extractToken(const char *zIn, int nIn, char *zOut, int nOut){ + int i; + if( nIn<=0 ){ + zOut[0] = 0; + return 0; + } + for(i=0; i0 ){ + pStmt = prepareSql( + "SELECT 1 FROM task" + " WHERE client=%d" + " AND client IN (SELECT id FROM client)" + " AND endtime IS NULL", + iClient); + }else{ + pStmt = prepareSql( + "SELECT 1 FROM task" + " WHERE client IN (SELECT id FROM client)" + " AND endtime IS NULL"); + } + g.iTimeout = 0; + while( ((rc = sqlite3_step(pStmt))==SQLITE_BUSY || rc==SQLITE_ROW) + && iTimeout>0 + ){ + sqlite3_reset(pStmt); + sqlite3_sleep(50); + iTimeout -= 50; + } + sqlite3_finalize(pStmt); + g.iTimeout = DEFAULT_TIMEOUT; + if( rc!=SQLITE_DONE ){ + if( zErrPrefix==0 ) zErrPrefix = ""; + if( iClient>0 ){ + errorMessage("%stimeout waiting for client %d", zErrPrefix, iClient); + }else{ + errorMessage("%stimeout waiting for all clients", zErrPrefix); + } + } +} + +/* Return a pointer to the tail of a filename +*/ +static char *filenameTail(char *z){ + int i, j; + for(i=j=0; z[i]; i++) if( z[i]=='/' ) j = i+1; + return z+j; +} + +/* +** Interpret zArg as a boolean value. Return either 0 or 1. +*/ +static int booleanValue(char *zArg){ + int i; + if( zArg==0 ) return 0; + for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} + if( i>0 && zArg[i]==0 ) return atoi(zArg); + if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ + return 1; + } + if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ + return 0; + } + errorMessage("unknown boolean: [%s]", zArg); + return 0; +} + + +/* This routine exists as a convenient place to set a debugger +** breakpoint. +*/ +static void test_breakpoint(void){ static volatile int cnt = 0; cnt++; } + +/* Maximum number of arguments to a --command */ +#define MX_ARG 2 + +/* +** Run a script. +*/ +static void runScript( + int iClient, /* The client number, or 0 for the master */ + int taskId, /* The task ID for clients. 0 for master */ + char *zScript, /* Text of the script */ + char *zFilename /* File from which script was read. */ +){ + int lineno = 1; + int prevLine = 1; + int ii = 0; + int iBegin = 0; + int n, c, j; + int len; + int nArg; + String sResult; + char zCmd[30]; + char zError[1000]; + char azArg[MX_ARG][100]; + + memset(&sResult, 0, sizeof(sResult)); + stringReset(&sResult); + while( (c = zScript[ii])!=0 ){ + prevLine = lineno; + len = tokenLength(zScript+ii, &lineno); + if( isspace(c) || (c=='/' && zScript[ii+1]=='*') ){ + ii += len; + continue; + } + if( c!='-' || zScript[ii+1]!='-' || !isalpha(zScript[ii+2]) ){ + ii += len; + continue; + } + + /* Run any prior SQL before processing the new --command */ + if( ii>iBegin ){ + char *zSql = sqlite3_mprintf("%.*s", ii-iBegin, zScript+iBegin); + evalSql(&sResult, zSql); + sqlite3_free(zSql); + iBegin = ii + len; + } + + /* Parse the --command */ + if( g.iTrace>=2 ) logMessage("%.*s", len, zScript+ii); + n = extractToken(zScript+ii+2, len-2, zCmd, sizeof(zCmd)); + for(nArg=0; n=len-2 ) break; + n += extractToken(zScript+ii+2+n, len-2-n, + azArg[nArg], sizeof(azArg[nArg])); + } + for(j=nArg; j0 then exit without shutting down + ** SQLite. (In other words, simulate a crash.) + */ + if( strcmp(zCmd, "exit")==0 ){ + int rc = atoi(azArg[0]); + finishScript(iClient, taskId, 1); + if( rc==0 ) sqlite3_close(g.db); + exit(rc); + }else + + /* + ** --testcase NAME + ** + ** Begin a new test case. Announce in the log that the test case + ** has begun. + */ + if( strcmp(zCmd, "testcase")==0 ){ + if( g.iTrace==1 ) logMessage("%.*s", len - 1, zScript+ii); + stringReset(&sResult); + }else + + /* + ** --finish + ** + ** Mark the current task as having finished, even if it is not. + ** This can be used in conjunction with --exit to simulate a crash. + */ + if( strcmp(zCmd, "finish")==0 && iClient>0 ){ + finishScript(iClient, taskId, 1); + }else + + /* + ** --reset + ** + ** Reset accumulated results back to an empty string + */ + if( strcmp(zCmd, "reset")==0 ){ + stringReset(&sResult); + }else + + /* + ** --match ANSWER... + ** + ** Check to see if output matches ANSWER. Report an error if not. + */ + if( strcmp(zCmd, "match")==0 ){ + int jj; + char *zAns = zScript+ii; + for(jj=7; jj=0 && zFilename[k]!='/'; k--){} + if( k>0 ){ + zNewFile = zToDel = sqlite3_mprintf("%.*s/%s", k,zFilename,zNewFile); + } + } + zNewScript = readFile(zNewFile); + if( g.iTrace ) logMessage("begin script [%s]\n", zNewFile); + runScript(0, 0, zNewScript, zNewFile); + sqlite3_free(zNewScript); + if( g.iTrace ) logMessage("end script [%s]\n", zNewFile); + sqlite3_free(zToDel); + }else + + /* + ** --print MESSAGE.... + ** + ** Output the remainder of the line to the log file + */ + if( strcmp(zCmd, "print")==0 ){ + int jj; + for(jj=7; jj0 ){ + startClient(iNewClient); + } + }else + + /* + ** --wait CLIENT TIMEOUT + ** + ** Wait until all tasks complete for the given client. If CLIENT is + ** "all" then wait for all clients to complete. Wait no longer than + ** TIMEOUT milliseconds (default 10,000) + */ + if( strcmp(zCmd, "wait")==0 && iClient==0 ){ + int iTimeout = nArg>=2 ? atoi(azArg[1]) : 10000; + sqlite3_snprintf(sizeof(zError),zError,"line %d of %s\n", + prevLine, zFilename); + waitForClient(atoi(azArg[0]), iTimeout, zError); + }else + + /* + ** --task CLIENT + ** + ** --end + ** + ** Assign work to a client. Start the client if it is not running + ** already. + */ + if( strcmp(zCmd, "task")==0 && iClient==0 ){ + int iTarget = atoi(azArg[0]); + int iEnd; + char *zTask; + char *zTName; + iEnd = findEnd(zScript+ii+len, &lineno); + if( iTarget<0 ){ + errorMessage("line %d of %s: bad client number: %d", + prevLine, zFilename, iTarget); + }else{ + zTask = sqlite3_mprintf("%.*s", iEnd, zScript+ii+len); + if( nArg>1 ){ + zTName = sqlite3_mprintf("%s", azArg[1]); + }else{ + zTName = sqlite3_mprintf("%s:%d", filenameTail(zFilename), prevLine); + } + startClient(iTarget); + runSql("INSERT INTO task(client,script,name)" + " VALUES(%d,'%q',%Q)", iTarget, zTask, zTName); + sqlite3_free(zTask); + sqlite3_free(zTName); + } + iEnd += tokenLength(zScript+ii+len+iEnd, &lineno); + len += iEnd; + iBegin = ii+len; + }else + + /* + ** --breakpoint + ** + ** This command calls "test_breakpoint()" which is a routine provided + ** as a convenient place to set a debugger breakpoint. + */ + if( strcmp(zCmd, "breakpoint")==0 ){ + test_breakpoint(); + }else + + /* + ** --show-sql-errors BOOLEAN + ** + ** Turn display of SQL errors on and off. + */ + if( strcmp(zCmd, "show-sql-errors")==0 ){ + g.bIgnoreSqlErrors = nArg>=1 ? !booleanValue(azArg[0]) : 1; + }else + + + /* error */{ + errorMessage("line %d of %s: unknown command --%s", + prevLine, zFilename, zCmd); + } + ii += len; + } + if( iBegin= nArg ) break; + z = azArg[i]; + if( z[0]!='-' ) continue; + z++; + if( z[0]=='-' ){ + if( z[1]==0 ) break; + z++; + } + if( strcmp(z,zOption)==0 ){ + if( hasArg && i==nArg-1 ){ + fatalError("command-line option \"--%s\" requires an argument", z); + } + if( hasArg ){ + zReturn = azArg[i+1]; + }else{ + zReturn = azArg[i]; + } + j = i+1+(hasArg!=0); + while( j0 ){ + printf("With SQLite " SQLITE_VERSION " " SQLITE_SOURCE_ID "\n" ); + for(i=0; (zCOption = sqlite3_compileoption_get(i))!=0; i++){ + printf("-DSQLITE_%s\n", zCOption); + } + fflush(stdout); + } + iClient = 0; + unlink(g.zDbFile); + openFlags |= SQLITE_OPEN_CREATE; + } + rc = sqlite3_open_v2(g.zDbFile, &g.db, openFlags, g.zVfs); + if( rc ) fatalError("cannot open [%s]", g.zDbFile); + sqlite3_enable_load_extension(g.db, 1); + sqlite3_busy_handler(g.db, busyHandler, 0); + sqlite3_create_function(g.db, "vfsname", 0, SQLITE_UTF8, 0, + vfsNameFunc, 0, 0); + sqlite3_create_function(g.db, "eval", 1, SQLITE_UTF8, 0, + evalFunc, 0, 0); + g.iTimeout = DEFAULT_TIMEOUT; + if( g.bSqlTrace ) sqlite3_trace(g.db, sqlTraceCallback, 0); + if( !g.bSync ) trySql("PRAGMA synchronous=OFF"); + if( iClient>0 ){ + if( n>0 ) unrecognizedArguments(argv[0], n, argv+2); + if( g.iTrace ) logMessage("start-client"); + while(1){ + char *zTaskName = 0; + rc = startScript(iClient, &zScript, &taskId, &zTaskName); + if( rc==SQLITE_DONE ) break; + if( g.iTrace ) logMessage("begin %s (%d)", zTaskName, taskId); + runScript(iClient, taskId, zScript, zTaskName); + if( g.iTrace ) logMessage("end %s (%d)", zTaskName, taskId); + finishScript(iClient, taskId, 0); + sqlite3_free(zTaskName); + sqlite3_sleep(10); + } + if( g.iTrace ) logMessage("end-client"); + }else{ + sqlite3_stmt *pStmt; + int iTimeout; + if( n==0 ){ + fatalError("missing script filename"); + } + if( n>1 ) unrecognizedArguments(argv[0], n, argv+2); + runSql( + "CREATE TABLE task(\n" + " id INTEGER PRIMARY KEY,\n" + " name TEXT,\n" + " client INTEGER,\n" + " starttime DATE,\n" + " endtime DATE,\n" + " script TEXT\n" + ");" + "CREATE INDEX task_i1 ON task(client, starttime);\n" + "CREATE INDEX task_i2 ON task(client, endtime);\n" + "CREATE TABLE counters(nError,nTest);\n" + "INSERT INTO counters VALUES(0,0);\n" + "CREATE TABLE client(id INTEGER PRIMARY KEY, wantHalt);\n" + ); + zScript = readFile(argv[2]); + if( g.iTrace ) logMessage("begin script [%s]\n", argv[2]); + runScript(0, 0, zScript, argv[2]); + sqlite3_free(zScript); + if( g.iTrace ) logMessage("end script [%s]\n", argv[2]); + waitForClient(0, 2000, "during shutdown...\n"); + trySql("UPDATE client SET wantHalt=1"); + sqlite3_sleep(10); + g.iTimeout = 0; + iTimeout = 1000; + while( ((rc = trySql("SELECT 1 FROM client"))==SQLITE_BUSY + || rc==SQLITE_ROW) && iTimeout>0 ){ + sqlite3_sleep(10); + iTimeout -= 10; + } + sqlite3_sleep(100); + pStmt = prepareSql("SELECT nError, nTest FROM counters"); + iTimeout = 1000; + while( (rc = sqlite3_step(pStmt))==SQLITE_BUSY && iTimeout>0 ){ + sqlite3_sleep(10); + iTimeout -= 10; + } + if( rc==SQLITE_ROW ){ + g.nError += sqlite3_column_int(pStmt, 0); + g.nTest += sqlite3_column_int(pStmt, 1); + } + sqlite3_finalize(pStmt); + } + sqlite3_close(g.db); + maybeClose(g.pLog); + maybeClose(g.pErrLog); + if( iClient==0 ){ + printf("Summary: %d errors in %d tests\n", g.nError, g.nTest); + } + return g.nError>0; +} diff --git a/components/external/SQLite-3.8.1/mptest/multiwrite01.test b/components/external/SQLite-3.8.1/mptest/multiwrite01.test new file mode 100644 index 0000000000000000000000000000000000000000..4f88a689495607ab78c2903bb41ccf8ccb096e3c --- /dev/null +++ b/components/external/SQLite-3.8.1/mptest/multiwrite01.test @@ -0,0 +1,405 @@ +/* +** This script sets up five different tasks all writing and updating +** the database at the same time, but each in its own table. +*/ +--task 1 build-t1 + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + --sleep 1 + INSERT INTO t1 VALUES(1, randomblob(2000)); + INSERT INTO t1 VALUES(2, randomblob(1000)); + --sleep 1 + INSERT INTO t1 SELECT a+2, randomblob(1500) FROM t1; + INSERT INTO t1 SELECT a+4, randomblob(1500) FROM t1; + INSERT INTO t1 SELECT a+8, randomblob(1500) FROM t1; + --sleep 1 + INSERT INTO t1 SELECT a+16, randomblob(1500) FROM t1; + --sleep 1 + INSERT INTO t1 SELECT a+32, randomblob(1500) FROM t1; + SELECT count(*) FROM t1; + --match 64 + SELECT avg(length(b)) FROM t1; + --match 1500.0 + --sleep 2 + UPDATE t1 SET b='x'||a||'y'; + SELECT sum(length(b)) FROM t1; + --match 247 + SELECT a FROM t1 WHERE b='x17y'; + --match 17 + CREATE INDEX t1b ON t1(b); + SELECT a FROM t1 WHERE b='x17y'; + --match 17 + SELECT a FROM t1 WHERE b GLOB 'x2?y' ORDER BY b DESC LIMIT 5; + --match 29 28 27 26 25 +--end + + +--task 2 build-t2 + DROP TABLE IF EXISTS t2; + CREATE TABLE t2(a INTEGER PRIMARY KEY, b); + --sleep 1 + INSERT INTO t2 VALUES(1, randomblob(2000)); + INSERT INTO t2 VALUES(2, randomblob(1000)); + --sleep 1 + INSERT INTO t2 SELECT a+2, randomblob(1500) FROM t2; + INSERT INTO t2 SELECT a+4, randomblob(1500) FROM t2; + INSERT INTO t2 SELECT a+8, randomblob(1500) FROM t2; + --sleep 1 + INSERT INTO t2 SELECT a+16, randomblob(1500) FROM t2; + --sleep 1 + INSERT INTO t2 SELECT a+32, randomblob(1500) FROM t2; + SELECT count(*) FROM t2; + --match 64 + SELECT avg(length(b)) FROM t2; + --match 1500.0 + --sleep 2 + UPDATE t2 SET b='x'||a||'y'; + SELECT sum(length(b)) FROM t2; + --match 247 + SELECT a FROM t2 WHERE b='x17y'; + --match 17 + CREATE INDEX t2b ON t2(b); + SELECT a FROM t2 WHERE b='x17y'; + --match 17 + SELECT a FROM t2 WHERE b GLOB 'x2?y' ORDER BY b DESC LIMIT 5; + --match 29 28 27 26 25 +--end + +--task 3 build-t3 + DROP TABLE IF EXISTS t3; + CREATE TABLE t3(a INTEGER PRIMARY KEY, b); + --sleep 1 + INSERT INTO t3 VALUES(1, randomblob(2000)); + INSERT INTO t3 VALUES(2, randomblob(1000)); + --sleep 1 + INSERT INTO t3 SELECT a+2, randomblob(1500) FROM t3; + INSERT INTO t3 SELECT a+4, randomblob(1500) FROM t3; + INSERT INTO t3 SELECT a+8, randomblob(1500) FROM t3; + --sleep 1 + INSERT INTO t3 SELECT a+16, randomblob(1500) FROM t3; + --sleep 1 + INSERT INTO t3 SELECT a+32, randomblob(1500) FROM t3; + SELECT count(*) FROM t3; + --match 64 + SELECT avg(length(b)) FROM t3; + --match 1500.0 + --sleep 2 + UPDATE t3 SET b='x'||a||'y'; + SELECT sum(length(b)) FROM t3; + --match 247 + SELECT a FROM t3 WHERE b='x17y'; + --match 17 + CREATE INDEX t3b ON t3(b); + SELECT a FROM t3 WHERE b='x17y'; + --match 17 + SELECT a FROM t3 WHERE b GLOB 'x2?y' ORDER BY b DESC LIMIT 5; + --match 29 28 27 26 25 +--end + +--task 4 build-t4 + DROP TABLE IF EXISTS t4; + CREATE TABLE t4(a INTEGER PRIMARY KEY, b); + --sleep 1 + INSERT INTO t4 VALUES(1, randomblob(2000)); + INSERT INTO t4 VALUES(2, randomblob(1000)); + --sleep 1 + INSERT INTO t4 SELECT a+2, randomblob(1500) FROM t4; + INSERT INTO t4 SELECT a+4, randomblob(1500) FROM t4; + INSERT INTO t4 SELECT a+8, randomblob(1500) FROM t4; + --sleep 1 + INSERT INTO t4 SELECT a+16, randomblob(1500) FROM t4; + --sleep 1 + INSERT INTO t4 SELECT a+32, randomblob(1500) FROM t4; + SELECT count(*) FROM t4; + --match 64 + SELECT avg(length(b)) FROM t4; + --match 1500.0 + --sleep 2 + UPDATE t4 SET b='x'||a||'y'; + SELECT sum(length(b)) FROM t4; + --match 247 + SELECT a FROM t4 WHERE b='x17y'; + --match 17 + CREATE INDEX t4b ON t4(b); + SELECT a FROM t4 WHERE b='x17y'; + --match 17 + SELECT a FROM t4 WHERE b GLOB 'x2?y' ORDER BY b DESC LIMIT 5; + --match 29 28 27 26 25 +--end + +--task 5 build-t5 + DROP TABLE IF EXISTS t5; + CREATE TABLE t5(a INTEGER PRIMARY KEY, b); + --sleep 1 + INSERT INTO t5 VALUES(1, randomblob(2000)); + INSERT INTO t5 VALUES(2, randomblob(1000)); + --sleep 1 + INSERT INTO t5 SELECT a+2, randomblob(1500) FROM t5; + INSERT INTO t5 SELECT a+4, randomblob(1500) FROM t5; + INSERT INTO t5 SELECT a+8, randomblob(1500) FROM t5; + --sleep 1 + INSERT INTO t5 SELECT a+16, randomblob(1500) FROM t5; + --sleep 1 + INSERT INTO t5 SELECT a+32, randomblob(1500) FROM t5; + SELECT count(*) FROM t5; + --match 64 + SELECT avg(length(b)) FROM t5; + --match 1500.0 + --sleep 2 + UPDATE t5 SET b='x'||a||'y'; + SELECT sum(length(b)) FROM t5; + --match 247 + SELECT a FROM t5 WHERE b='x17y'; + --match 17 + CREATE INDEX t5b ON t5(b); + SELECT a FROM t5 WHERE b='x17y'; + --match 17 + SELECT a FROM t5 WHERE b GLOB 'x2?y' ORDER BY b DESC LIMIT 5; + --match 29 28 27 26 25 +--end + +--wait all +SELECT count(*), sum(length(b)) FROM t1; +--match 64 247 +SELECT count(*), sum(length(b)) FROM t2; +--match 64 247 +SELECT count(*), sum(length(b)) FROM t3; +--match 64 247 +SELECT count(*), sum(length(b)) FROM t4; +--match 64 247 +SELECT count(*), sum(length(b)) FROM t5; +--match 64 247 + +--task 1 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 5 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 3 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 2 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 4 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--wait all + +--task 5 + DROP INDEX t5b; + --sleep 5 + PRAGMA integrity_check(10); + --match ok + CREATE INDEX t5b ON t5(b DESC); +--end +--task 3 + DROP INDEX t3b; + --sleep 5 + PRAGMA integrity_check(10); + --match ok + CREATE INDEX t3b ON t3(b DESC); +--end +--task 1 + DROP INDEX t1b; + --sleep 5 + PRAGMA integrity_check(10); + --match ok + CREATE INDEX t1b ON t1(b DESC); +--end +--task 2 + DROP INDEX t2b; + --sleep 5 + PRAGMA integrity_check(10); + --match ok + CREATE INDEX t2b ON t2(b DESC); +--end +--task 4 + DROP INDEX t4b; + --sleep 5 + PRAGMA integrity_check(10); + --match ok + CREATE INDEX t4b ON t4(b DESC); +--end +--wait all + +--task 1 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 5 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 3 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 2 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 4 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--wait all + +VACUUM; +PRAGMA integrity_check(10); +--match ok + +--task 1 + UPDATE t1 SET b=randomblob(20000); + --sleep 5 + UPDATE t1 SET b='x'||a||'y'; + SELECT a FROM t1 WHERE b='x63y'; + --match 63 +--end +--task 2 + UPDATE t2 SET b=randomblob(20000); + --sleep 5 + UPDATE t2 SET b='x'||a||'y'; + SELECT a FROM t2 WHERE b='x63y'; + --match 63 +--end +--task 3 + UPDATE t3 SET b=randomblob(20000); + --sleep 5 + UPDATE t3 SET b='x'||a||'y'; + SELECT a FROM t3 WHERE b='x63y'; + --match 63 +--end +--task 4 + UPDATE t4 SET b=randomblob(20000); + --sleep 5 + UPDATE t4 SET b='x'||a||'y'; + SELECT a FROM t4 WHERE b='x63y'; + --match 63 +--end +--task 5 + UPDATE t5 SET b=randomblob(20000); + --sleep 5 + UPDATE t5 SET b='x'||a||'y'; + SELECT a FROM t5 WHERE b='x63y'; + --match 63 +--end +--wait all + +--task 1 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 5 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 3 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 2 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--task 4 + SELECT t1.a FROM t1, t2 + WHERE t2.b GLOB 'x3?y' AND t1.b=('x'||(t2.a+3)||'y') + ORDER BY t1.a LIMIT 4 + --match 33 34 35 36 + SELECT t3.a FROM t3, t4 + WHERE t4.b GLOB 'x4?y' AND t3.b=('x'||(t4.a+5)||'y') + ORDER BY t3.a LIMIT 7 + --match 45 46 47 48 49 50 51 +--end +--wait all diff --git a/components/external/SQLite-3.8.1/spec.template b/components/external/SQLite-3.8.1/spec.template new file mode 100644 index 0000000000000000000000000000000000000000..6cc7ab2eabed0e610a671c7ac7822b0c67dbb1b9 --- /dev/null +++ b/components/external/SQLite-3.8.1/spec.template @@ -0,0 +1,67 @@ +%define name sqlite +%define version SQLITE_VERSION +%define release 1 + +Name: %{name} +Summary: SQLite is a C library that implements an embeddable SQL database engine +Version: %{version} +Release: %{release} +Source: %{name}-%{version}.tar.gz +Group: System/Libraries +URL: http://www.sqlite.org/ +License: Public Domain +BuildRoot: %{_tmppath}/%{name}-%{version}-root + +%description +SQLite is a software library that implements a self-contained, serverless, +zero-configuration, transactional SQL database engine. +Programs that link with the SQLite library can have SQL database access +without running a separate RDBMS process. The distribution comes with a +standalone command-line access program (sqlite) that can be used to +administer an SQLite database and which serves as an example of how to +use the SQLite library. + +%package -n %{name}-devel +Summary: Header files and libraries for developing apps which will use sqlite +Group: Development/C +Requires: %{name} = %{version}-%{release} + +%description -n %{name}-devel +The sqlite-devel package contains the header files and libraries needed +to develop programs that use the SQLite database library. + +%prep +%setup -q -n %{name} + +%build +CFLAGS="%optflags -DNDEBUG=1" CXXFLAGS="%optflags -DNDEBUG=1" ./configure --prefix=%{_prefix} + +make +make doc + +%install +install -d $RPM_BUILD_ROOT/%{_prefix} +install -d $RPM_BUILD_ROOT/%{_prefix}/bin +install -d $RPM_BUILD_ROOT/%{_prefix}/include +install -d $RPM_BUILD_ROOT/%{_prefix}/lib +make install prefix=$RPM_BUILD_ROOT/%{_prefix} + +%post -p /sbin/ldconfig + +%postun -p /sbin/ldconfig + +%clean +rm -fr $RPM_BUILD_ROOT + +%files +%defattr(-, root, root) +%{_libdir}/*.so* +%{_bindir}/* + +%files -n %{name}-devel +%defattr(-, root, root) +%{_libdir}/pkgconfig/sqlite3.pc +%{_libdir}/*.a +%{_libdir}/*.la +%{_includedir}/* +%doc doc/* diff --git a/components/external/SQLite-3.8.1/sqlite.pc.in b/components/external/SQLite-3.8.1/sqlite.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..d3c944928bc33269a1b74d0fdddb3d7d12af64d7 --- /dev/null +++ b/components/external/SQLite-3.8.1/sqlite.pc.in @@ -0,0 +1,13 @@ +# Package Information for pkg-config + +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: SQLite +Description: SQL database engine +Version: @RELEASE@ +Libs: -L${libdir} -lsqlite +Libs.private: @LIBS@ +Cflags: -I${includedir} diff --git a/components/external/SQLite-3.8.1/sqlite3.1 b/components/external/SQLite-3.8.1/sqlite3.1 new file mode 100644 index 0000000000000000000000000000000000000000..785995bf60e3c5d9e294c71c025e36437db8e8e4 --- /dev/null +++ b/components/external/SQLite-3.8.1/sqlite3.1 @@ -0,0 +1,229 @@ +.\" Hey, EMACS: -*- nroff -*- +.\" First parameter, NAME, should be all caps +.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection +.\" other parameters are allowed: see man(7), man(1) +.TH SQLITE3 1 "Mon Apr 15 23:49:17 2002" +.\" Please adjust this date whenever revising the manpage. +.\" +.\" Some roff macros, for reference: +.\" .nh disable hyphenation +.\" .hy enable hyphenation +.\" .ad l left justify +.\" .ad b justify to both left and right margins +.\" .nf disable filling +.\" .fi enable filling +.\" .br insert line break +.\" .sp insert n+1 empty lines +.\" for manpage-specific macros, see man(7) +.SH NAME +.B sqlite3 +\- A command line interface for SQLite version 3 + +.SH SYNOPSIS +.B sqlite3 +.RI [ options ] +.RI [ databasefile ] +.RI [ SQL ] + +.SH SUMMARY +.PP +.B sqlite3 +is a terminal-based front-end to the SQLite library that can evaluate +queries interactively and display the results in multiple formats. +.B sqlite3 +can also be used within shell scripts and other applications to provide +batch processing features. + +.SH DESCRIPTION +To start a +.B sqlite3 +interactive session, invoke the +.B sqlite3 +command and optionally provide the name of a database file. If the +database file does not exist, it will be created. If the database file +does exist, it will be opened. + +For example, to create a new database file named "mydata.db", create +a table named "memos" and insert a couple of records into that table: +.sp +$ +.B sqlite3 mydata.db +.br +SQLite version 3.1.3 +.br +Enter ".help" for instructions +.br +sqlite> +.B create table memos(text, priority INTEGER); +.br +sqlite> +.B insert into memos values('deliver project description', 10); +.br +sqlite> +.B insert into memos values('lunch with Christine', 100); +.br +sqlite> +.B select * from memos; +.br +deliver project description|10 +.br +lunch with Christine|100 +.br +sqlite> +.sp + +If no database name is supplied, the ATTACH sql command can be used +to attach to existing or create new database files. ATTACH can also +be used to attach to multiple databases within the same interactive +session. This is useful for migrating data between databases, +possibly changing the schema along the way. + +Optionally, a SQL statement or set of SQL statements can be supplied as +a single argument. Multiple statements should be separated by +semi-colons. + +For example: +.sp +$ +.B sqlite3 -line mydata.db 'select * from memos where priority > 20;' +.br + text = lunch with Christine +.br +priority = 100 +.br +.sp + +.SS SQLITE META-COMMANDS +.PP +The interactive interpreter offers a set of meta-commands that can be +used to control the output format, examine the currently attached +database files, or perform administrative operations upon the +attached databases (such as rebuilding indices). Meta-commands are +always prefixed with a dot (.). + +A list of available meta-commands can be viewed at any time by issuing +the '.help' command. For example: +.sp +sqlite> +.B .help +.nf +.cc | +.databases List names and files of attached databases +.dump ?TABLE? ... Dump the database in an SQL text format +.echo ON|OFF Turn command echo on or off +.exit Exit this program +.explain ON|OFF Turn output mode suitable for EXPLAIN on or off. +.header(s) ON|OFF Turn display of headers on or off +.help Show this message +.import FILE TABLE Import data from FILE into TABLE +.indices TABLE Show names of all indices on TABLE +.mode MODE ?TABLE? Set output mode where MODE is one of: + csv Comma-separated values + column Left-aligned columns. (See .width) + html HTML
code + insert SQL insert statements for TABLE + line One value per line + list Values delimited by .separator string + tabs Tab-separated values + tcl TCL list elements +.nullvalue STRING Print STRING in place of NULL values +.output FILENAME Send output to FILENAME +.output stdout Send output to the screen +.prompt MAIN CONTINUE Replace the standard prompts +.quit Exit this program +.read FILENAME Execute SQL in FILENAME +.schema ?TABLE? Show the CREATE statements +.separator STRING Change separator used by output mode and .import +.show Show the current values for various settings +.tables ?PATTERN? List names of tables matching a LIKE pattern +.timeout MS Try opening locked tables for MS milliseconds +.width NUM NUM ... Set column widths for "column" mode +sqlite> +|cc . +.sp +.fi + +.SH OPTIONS +.B sqlite3 +has the following options: +.TP +.BI \-init\ file +Read and execute commands from +.I file +, which can contain a mix of SQL statements and meta-commands. +.TP +.B \-echo +Print commands before execution. +.TP +.B \-[no]header +Turn headers on or off. +.TP +.B \-column +Query results will be displayed in a table like form, using +whitespace characters to separate the columns and align the +output. +.TP +.B \-html +Query results will be output as simple HTML tables. +.TP +.B \-line +Query results will be displayed with one value per line, rows +separated by a blank line. Designed to be easily parsed by +scripts or other programs +.TP +.B \-list +Query results will be displayed with the separator (|, by default) +character between each field value. The default. +.TP +.BI \-separator\ separator +Set output field separator. Default is '|'. +.TP +.BI \-nullvalue\ string +Set string used to represent NULL values. Default is '' +(empty string). +.TP +.B \-version +Show SQLite version. +.TP +.B \-help +Show help on options and exit. + + +.SH INIT FILE +.B sqlite3 +reads an initialization file to set the configuration of the +interactive environment. Throughout initialization, any previously +specified setting can be overridden. The sequence of initialization is +as follows: + +o The default configuration is established as follows: + +.sp +.nf +.cc | +mode = LIST +separator = "|" +main prompt = "sqlite> " +continue prompt = " ...> " +|cc . +.sp +.fi + +o If the file +.B ~/.sqliterc +exists, it is processed first. +can be found in the user's home directory, it is +read and processed. It should generally only contain meta-commands. + +o If the -init option is present, the specified file is processed. + +o All other command line options are processed. + +.SH SEE ALSO +http://www.sqlite.org/ +.br +The sqlite-doc package +.SH AUTHOR +This manual page was originally written by Andreas Rottmann +, for the Debian GNU/Linux system (but may be used +by others). It was subsequently revised by Bill Bumgarner . diff --git a/components/external/SQLite-3.8.1/sqlite3.pc.in b/components/external/SQLite-3.8.1/sqlite3.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..3799671e613b34a4551d1010c13e334b89123ea1 --- /dev/null +++ b/components/external/SQLite-3.8.1/sqlite3.pc.in @@ -0,0 +1,13 @@ +# Package Information for pkg-config + +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: SQLite +Description: SQL database engine +Version: @PACKAGE_VERSION@ +Libs: -L${libdir} -lsqlite3 +Libs.private: @LIBS@ +Cflags: -I${includedir} diff --git a/components/external/SQLite-3.8.1/src/alter.c b/components/external/SQLite-3.8.1/src/alter.c new file mode 100644 index 0000000000000000000000000000000000000000..9d34b07b0c0c079e6351a4b8d49aea49f18f9668 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/alter.c @@ -0,0 +1,826 @@ +/* +** 2005 February 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that used to generate VDBE code +** that implements the ALTER TABLE command. +*/ +#include "sqliteInt.h" + +/* +** The code in this file only exists if we are not omitting the +** ALTER TABLE logic from the build. +*/ +#ifndef SQLITE_OMIT_ALTERTABLE + + +/* +** This function is used by SQL generated to implement the +** ALTER TABLE command. The first argument is the text of a CREATE TABLE or +** CREATE INDEX command. The second is a table name. The table name in +** the CREATE TABLE or CREATE INDEX statement is replaced with the third +** argument and the result returned. Examples: +** +** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def') +** -> 'CREATE TABLE def(a, b, c)' +** +** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def') +** -> 'CREATE INDEX i ON def(a, b, c)' +*/ +static void renameTableFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + unsigned char const *zSql = sqlite3_value_text(argv[0]); + unsigned char const *zTableName = sqlite3_value_text(argv[1]); + + int token; + Token tname; + unsigned char const *zCsr = zSql; + int len = 0; + char *zRet; + + sqlite3 *db = sqlite3_context_db_handle(context); + + UNUSED_PARAMETER(NotUsed); + + /* The principle used to locate the table name in the CREATE TABLE + ** statement is that the table name is the first non-space token that + ** is immediately followed by a TK_LP or TK_USING token. + */ + if( zSql ){ + do { + if( !*zCsr ){ + /* Ran out of input before finding an opening bracket. Return NULL. */ + return; + } + + /* Store the token that zCsr points to in tname. */ + tname.z = (char*)zCsr; + tname.n = len; + + /* Advance zCsr to the next token. Store that token type in 'token', + ** and its length in 'len' (to be used next iteration of this loop). + */ + do { + zCsr += len; + len = sqlite3GetToken(zCsr, &token); + } while( token==TK_SPACE ); + assert( len>0 ); + } while( token!=TK_LP && token!=TK_USING ); + + zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, + zTableName, tname.z+tname.n); + sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); + } +} + +/* +** This C function implements an SQL user function that is used by SQL code +** generated by the ALTER TABLE ... RENAME command to modify the definition +** of any foreign key constraints that use the table being renamed as the +** parent table. It is passed three arguments: +** +** 1) The complete text of the CREATE TABLE statement being modified, +** 2) The old name of the table being renamed, and +** 3) The new name of the table being renamed. +** +** It returns the new CREATE TABLE statement. For example: +** +** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3') +** -> 'CREATE TABLE t1(a REFERENCES t3)' +*/ +#ifndef SQLITE_OMIT_FOREIGN_KEY +static void renameParentFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + char *zOutput = 0; + char *zResult; + unsigned char const *zInput = sqlite3_value_text(argv[0]); + unsigned char const *zOld = sqlite3_value_text(argv[1]); + unsigned char const *zNew = sqlite3_value_text(argv[2]); + + unsigned const char *z; /* Pointer to token */ + int n; /* Length of token z */ + int token; /* Type of token */ + + UNUSED_PARAMETER(NotUsed); + for(z=zInput; *z; z=z+n){ + n = sqlite3GetToken(z, &token); + if( token==TK_REFERENCES ){ + char *zParent; + do { + z += n; + n = sqlite3GetToken(z, &token); + }while( token==TK_SPACE ); + + zParent = sqlite3DbStrNDup(db, (const char *)z, n); + if( zParent==0 ) break; + sqlite3Dequote(zParent); + if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){ + char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", + (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew + ); + sqlite3DbFree(db, zOutput); + zOutput = zOut; + zInput = &z[n]; + } + sqlite3DbFree(db, zParent); + } + } + + zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), + sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC); + sqlite3DbFree(db, zOutput); +} +#endif + +#ifndef SQLITE_OMIT_TRIGGER +/* This function is used by SQL generated to implement the +** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER +** statement. The second is a table name. The table name in the CREATE +** TRIGGER statement is replaced with the third argument and the result +** returned. This is analagous to renameTableFunc() above, except for CREATE +** TRIGGER, not CREATE INDEX and CREATE TABLE. +*/ +static void renameTriggerFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + unsigned char const *zSql = sqlite3_value_text(argv[0]); + unsigned char const *zTableName = sqlite3_value_text(argv[1]); + + int token; + Token tname; + int dist = 3; + unsigned char const *zCsr = zSql; + int len = 0; + char *zRet; + sqlite3 *db = sqlite3_context_db_handle(context); + + UNUSED_PARAMETER(NotUsed); + + /* The principle used to locate the table name in the CREATE TRIGGER + ** statement is that the table name is the first token that is immediatedly + ** preceded by either TK_ON or TK_DOT and immediatedly followed by one + ** of TK_WHEN, TK_BEGIN or TK_FOR. + */ + if( zSql ){ + do { + + if( !*zCsr ){ + /* Ran out of input before finding the table name. Return NULL. */ + return; + } + + /* Store the token that zCsr points to in tname. */ + tname.z = (char*)zCsr; + tname.n = len; + + /* Advance zCsr to the next token. Store that token type in 'token', + ** and its length in 'len' (to be used next iteration of this loop). + */ + do { + zCsr += len; + len = sqlite3GetToken(zCsr, &token); + }while( token==TK_SPACE ); + assert( len>0 ); + + /* Variable 'dist' stores the number of tokens read since the most + ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN + ** token is read and 'dist' equals 2, the condition stated above + ** to be met. + ** + ** Note that ON cannot be a database, table or column name, so + ** there is no need to worry about syntax like + ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. + */ + dist++; + if( token==TK_DOT || token==TK_ON ){ + dist = 0; + } + } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) ); + + /* Variable tname now contains the token that is the old table-name + ** in the CREATE TRIGGER statement. + */ + zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, + zTableName, tname.z+tname.n); + sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); + } +} +#endif /* !SQLITE_OMIT_TRIGGER */ + +/* +** Register built-in functions used to help implement ALTER TABLE +*/ +void sqlite3AlterFunctions(void){ + static SQLITE_WSD FuncDef aAlterTableFuncs[] = { + FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc), +#ifndef SQLITE_OMIT_TRIGGER + FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc), +#endif +#ifndef SQLITE_OMIT_FOREIGN_KEY + FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc), +#endif + }; + int i; + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs); + + for(i=0; i OR name= OR ... +** +** If argument zWhere is NULL, then a pointer string containing the text +** "name=" is returned, where is the quoted version +** of the string passed as argument zConstant. The returned buffer is +** allocated using sqlite3DbMalloc(). It is the responsibility of the +** caller to ensure that it is eventually freed. +** +** If argument zWhere is not NULL, then the string returned is +** " OR name=", where is the contents of zWhere. +** In this case zWhere is passed to sqlite3DbFree() before returning. +** +*/ +static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){ + char *zNew; + if( !zWhere ){ + zNew = sqlite3MPrintf(db, "name=%Q", zConstant); + }else{ + zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant); + sqlite3DbFree(db, zWhere); + } + return zNew; +} + +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) +/* +** Generate the text of a WHERE expression which can be used to select all +** tables that have foreign key constraints that refer to table pTab (i.e. +** constraints for which pTab is the parent table) from the sqlite_master +** table. +*/ +static char *whereForeignKeys(Parse *pParse, Table *pTab){ + FKey *p; + char *zWhere = 0; + for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ + zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName); + } + return zWhere; +} +#endif + +/* +** Generate the text of a WHERE expression which can be used to select all +** temporary triggers on table pTab from the sqlite_temp_master table. If +** table pTab has no temporary triggers, or is itself stored in the +** temporary database, NULL is returned. +*/ +static char *whereTempTriggers(Parse *pParse, Table *pTab){ + Trigger *pTrig; + char *zWhere = 0; + const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */ + + /* If the table is not located in the temp-db (in which case NULL is + ** returned, loop through the tables list of triggers. For each trigger + ** that is not part of the temp-db schema, add a clause to the WHERE + ** expression being built up in zWhere. + */ + if( pTab->pSchema!=pTempSchema ){ + sqlite3 *db = pParse->db; + for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ + if( pTrig->pSchema==pTempSchema ){ + zWhere = whereOrName(db, zWhere, pTrig->zName); + } + } + } + if( zWhere ){ + char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere); + sqlite3DbFree(pParse->db, zWhere); + zWhere = zNew; + } + return zWhere; +} + +/* +** Generate code to drop and reload the internal representation of table +** pTab from the database, including triggers and temporary triggers. +** Argument zName is the name of the table in the database schema at +** the time the generated code is executed. This can be different from +** pTab->zName if this function is being called to code part of an +** "ALTER TABLE RENAME TO" statement. +*/ +static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){ + Vdbe *v; + char *zWhere; + int iDb; /* Index of database containing pTab */ +#ifndef SQLITE_OMIT_TRIGGER + Trigger *pTrig; +#endif + + v = sqlite3GetVdbe(pParse); + if( NEVER(v==0) ) return; + assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + assert( iDb>=0 ); + +#ifndef SQLITE_OMIT_TRIGGER + /* Drop any table triggers from the internal schema. */ + for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ + int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); + assert( iTrigDb==iDb || iTrigDb==1 ); + sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0); + } +#endif + + /* Drop the table and index from the internal schema. */ + sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); + + /* Reload the table, index and permanent trigger schemas. */ + zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName); + if( !zWhere ) return; + sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); + +#ifndef SQLITE_OMIT_TRIGGER + /* Now, if the table is not stored in the temp database, reload any temp + ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. + */ + if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ + sqlite3VdbeAddParseSchemaOp(v, 1, zWhere); + } +#endif +} + +/* +** Parameter zName is the name of a table that is about to be altered +** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). +** If the table is a system table, this function leaves an error message +** in pParse->zErr (system tables may not be altered) and returns non-zero. +** +** Or, if zName is not a system table, zero is returned. +*/ +static int isSystemTable(Parse *pParse, const char *zName){ + if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ + sqlite3ErrorMsg(pParse, "table %s may not be altered", zName); + return 1; + } + return 0; +} + +/* +** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" +** command. +*/ +void sqlite3AlterRenameTable( + Parse *pParse, /* Parser context. */ + SrcList *pSrc, /* The table to rename. */ + Token *pName /* The new table name. */ +){ + int iDb; /* Database that contains the table */ + char *zDb; /* Name of database iDb */ + Table *pTab; /* Table being renamed */ + char *zName = 0; /* NULL-terminated version of pName */ + sqlite3 *db = pParse->db; /* Database connection */ + int nTabName; /* Number of UTF-8 characters in zTabName */ + const char *zTabName; /* Original name of the table */ + Vdbe *v; +#ifndef SQLITE_OMIT_TRIGGER + char *zWhere = 0; /* Where clause to locate temp triggers */ +#endif + VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */ + int savedDbFlags; /* Saved value of db->flags */ + + savedDbFlags = db->flags; + if( NEVER(db->mallocFailed) ) goto exit_rename_table; + assert( pSrc->nSrc==1 ); + assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); + + pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); + if( !pTab ) goto exit_rename_table; + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + zDb = db->aDb[iDb].zName; + db->flags |= SQLITE_PreferBuiltin; + + /* Get a NULL terminated version of the new table name. */ + zName = sqlite3NameFromToken(db, pName); + if( !zName ) goto exit_rename_table; + + /* Check that a table or index named 'zName' does not already exist + ** in database iDb. If so, this is an error. + */ + if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){ + sqlite3ErrorMsg(pParse, + "there is already another table or index with this name: %s", zName); + goto exit_rename_table; + } + + /* Make sure it is not a system table being altered, or a reserved name + ** that the table is being renamed to. + */ + if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ + goto exit_rename_table; + } + if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto + exit_rename_table; + } + +#ifndef SQLITE_OMIT_VIEW + if( pTab->pSelect ){ + sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); + goto exit_rename_table; + } +#endif + +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Invoke the authorization callback. */ + if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ + goto exit_rename_table; + } +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto exit_rename_table; + } + if( IsVirtual(pTab) ){ + pVTab = sqlite3GetVTable(db, pTab); + if( pVTab->pVtab->pModule->xRename==0 ){ + pVTab = 0; + } + } +#endif + + /* Begin a transaction and code the VerifyCookie for database iDb. + ** Then modify the schema cookie (since the ALTER TABLE modifies the + ** schema). Open a statement transaction if the table is a virtual + ** table. + */ + v = sqlite3GetVdbe(pParse); + if( v==0 ){ + goto exit_rename_table; + } + sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb); + sqlite3ChangeCookie(pParse, iDb); + + /* If this is a virtual table, invoke the xRename() function if + ** one is defined. The xRename() callback will modify the names + ** of any resources used by the v-table implementation (including other + ** SQLite tables) that are identified by the name of the virtual table. + */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pVTab ){ + int i = ++pParse->nMem; + sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0); + sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB); + sqlite3MayAbort(pParse); + } +#endif + + /* figure out how many UTF-8 characters are in zName */ + zTabName = pTab->zName; + nTabName = sqlite3Utf8CharLen(zTabName, -1); + +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + if( db->flags&SQLITE_ForeignKeys ){ + /* If foreign-key support is enabled, rewrite the CREATE TABLE + ** statements corresponding to all child tables of foreign key constraints + ** for which the renamed table is the parent table. */ + if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){ + sqlite3NestedParse(pParse, + "UPDATE \"%w\".%s SET " + "sql = sqlite_rename_parent(sql, %Q, %Q) " + "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere); + sqlite3DbFree(db, zWhere); + } + } +#endif + + /* Modify the sqlite_master table to use the new table name. */ + sqlite3NestedParse(pParse, + "UPDATE %Q.%s SET " +#ifdef SQLITE_OMIT_TRIGGER + "sql = sqlite_rename_table(sql, %Q), " +#else + "sql = CASE " + "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" + "ELSE sqlite_rename_table(sql, %Q) END, " +#endif + "tbl_name = %Q, " + "name = CASE " + "WHEN type='table' THEN %Q " + "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " + "'sqlite_autoindex_' || %Q || substr(name,%d+18) " + "ELSE name END " + "WHERE tbl_name=%Q COLLATE nocase AND " + "(type='table' OR type='index' OR type='trigger');", + zDb, SCHEMA_TABLE(iDb), zName, zName, zName, +#ifndef SQLITE_OMIT_TRIGGER + zName, +#endif + zName, nTabName, zTabName + ); + +#ifndef SQLITE_OMIT_AUTOINCREMENT + /* If the sqlite_sequence table exists in this database, then update + ** it with the new table name. + */ + if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ + sqlite3NestedParse(pParse, + "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", + zDb, zName, pTab->zName); + } +#endif + +#ifndef SQLITE_OMIT_TRIGGER + /* If there are TEMP triggers on this table, modify the sqlite_temp_master + ** table. Don't do this if the table being ALTERed is itself located in + ** the temp database. + */ + if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ + sqlite3NestedParse(pParse, + "UPDATE sqlite_temp_master SET " + "sql = sqlite_rename_trigger(sql, %Q), " + "tbl_name = %Q " + "WHERE %s;", zName, zName, zWhere); + sqlite3DbFree(db, zWhere); + } +#endif + +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + if( db->flags&SQLITE_ForeignKeys ){ + FKey *p; + for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ + Table *pFrom = p->pFrom; + if( pFrom!=pTab ){ + reloadTableSchema(pParse, p->pFrom, pFrom->zName); + } + } + } +#endif + + /* Drop and reload the internal table schema. */ + reloadTableSchema(pParse, pTab, zName); + +exit_rename_table: + sqlite3SrcListDelete(db, pSrc); + sqlite3DbFree(db, zName); + db->flags = savedDbFlags; +} + + +/* +** Generate code to make sure the file format number is at least minFormat. +** The generated code will increase the file format number if necessary. +*/ +void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){ + Vdbe *v; + v = sqlite3GetVdbe(pParse); + /* The VDBE should have been allocated before this routine is called. + ** If that allocation failed, we would have quit before reaching this + ** point */ + if( ALWAYS(v) ){ + int r1 = sqlite3GetTempReg(pParse); + int r2 = sqlite3GetTempReg(pParse); + int j1; + sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); + sqlite3VdbeUsesBtree(v, iDb); + sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2); + j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2); + sqlite3VdbeJumpHere(v, j1); + sqlite3ReleaseTempReg(pParse, r1); + sqlite3ReleaseTempReg(pParse, r2); + } +} + +/* +** This function is called after an "ALTER TABLE ... ADD" statement +** has been parsed. Argument pColDef contains the text of the new +** column definition. +** +** The Table structure pParse->pNewTable was extended to include +** the new column during parsing. +*/ +void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ + Table *pNew; /* Copy of pParse->pNewTable */ + Table *pTab; /* Table being altered */ + int iDb; /* Database number */ + const char *zDb; /* Database name */ + const char *zTab; /* Table name */ + char *zCol; /* Null-terminated column definition */ + Column *pCol; /* The new column */ + Expr *pDflt; /* Default value for the new column */ + sqlite3 *db; /* The database connection; */ + + db = pParse->db; + if( pParse->nErr || db->mallocFailed ) return; + pNew = pParse->pNewTable; + assert( pNew ); + + assert( sqlite3BtreeHoldsAllMutexes(db) ); + iDb = sqlite3SchemaToIndex(db, pNew->pSchema); + zDb = db->aDb[iDb].zName; + zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ + pCol = &pNew->aCol[pNew->nCol-1]; + pDflt = pCol->pDflt; + pTab = sqlite3FindTable(db, zTab, zDb); + assert( pTab ); + +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Invoke the authorization callback. */ + if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ + return; + } +#endif + + /* If the default value for the new column was specified with a + ** literal NULL, then set pDflt to 0. This simplifies checking + ** for an SQL NULL default below. + */ + if( pDflt && pDflt->op==TK_NULL ){ + pDflt = 0; + } + + /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. + ** If there is a NOT NULL constraint, then the default value for the + ** column must not be NULL. + */ + if( pCol->colFlags & COLFLAG_PRIMKEY ){ + sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); + return; + } + if( pNew->pIndex ){ + sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column"); + return; + } + if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){ + sqlite3ErrorMsg(pParse, + "Cannot add a REFERENCES column with non-NULL default value"); + return; + } + if( pCol->notNull && !pDflt ){ + sqlite3ErrorMsg(pParse, + "Cannot add a NOT NULL column with default value NULL"); + return; + } + + /* Ensure the default expression is something that sqlite3ValueFromExpr() + ** can handle (i.e. not CURRENT_TIME etc.) + */ + if( pDflt ){ + sqlite3_value *pVal = 0; + if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){ + db->mallocFailed = 1; + return; + } + if( !pVal ){ + sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default"); + return; + } + sqlite3ValueFree(pVal); + } + + /* Modify the CREATE TABLE statement. */ + zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n); + if( zCol ){ + char *zEnd = &zCol[pColDef->n-1]; + int savedDbFlags = db->flags; + while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ + *zEnd-- = '\0'; + } + db->flags |= SQLITE_PreferBuiltin; + sqlite3NestedParse(pParse, + "UPDATE \"%w\".%s SET " + "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " + "WHERE type = 'table' AND name = %Q", + zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1, + zTab + ); + sqlite3DbFree(db, zCol); + db->flags = savedDbFlags; + } + + /* If the default value of the new column is NULL, then set the file + ** format to 2. If the default value of the new column is not NULL, + ** the file format becomes 3. + */ + sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2); + + /* Reload the schema of the modified table. */ + reloadTableSchema(pParse, pTab, pTab->zName); +} + +/* +** This function is called by the parser after the table-name in +** an "ALTER TABLE ADD" statement is parsed. Argument +** pSrc is the full-name of the table being altered. +** +** This routine makes a (partial) copy of the Table structure +** for the table being altered and sets Parse.pNewTable to point +** to it. Routines called by the parser as the column definition +** is parsed (i.e. sqlite3AddColumn()) add the new Column data to +** the copy. The copy of the Table structure is deleted by tokenize.c +** after parsing is finished. +** +** Routine sqlite3AlterFinishAddColumn() will be called to complete +** coding the "ALTER TABLE ... ADD" statement. +*/ +void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ + Table *pNew; + Table *pTab; + Vdbe *v; + int iDb; + int i; + int nAlloc; + sqlite3 *db = pParse->db; + + /* Look up the table being altered. */ + assert( pParse->pNewTable==0 ); + assert( sqlite3BtreeHoldsAllMutexes(db) ); + if( db->mallocFailed ) goto exit_begin_add_column; + pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); + if( !pTab ) goto exit_begin_add_column; + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); + goto exit_begin_add_column; + } +#endif + + /* Make sure this is not an attempt to ALTER a view. */ + if( pTab->pSelect ){ + sqlite3ErrorMsg(pParse, "Cannot add a column to a view"); + goto exit_begin_add_column; + } + if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ + goto exit_begin_add_column; + } + + assert( pTab->addColOffset>0 ); + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + + /* Put a copy of the Table struct in Parse.pNewTable for the + ** sqlite3AddColumn() function and friends to modify. But modify + ** the name by adding an "sqlite_altertab_" prefix. By adding this + ** prefix, we insure that the name will not collide with an existing + ** table because user table are not allowed to have the "sqlite_" + ** prefix on their name. + */ + pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table)); + if( !pNew ) goto exit_begin_add_column; + pParse->pNewTable = pNew; + pNew->nRef = 1; + pNew->nCol = pTab->nCol; + assert( pNew->nCol>0 ); + nAlloc = (((pNew->nCol-1)/8)*8)+8; + assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); + pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc); + pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); + if( !pNew->aCol || !pNew->zName ){ + db->mallocFailed = 1; + goto exit_begin_add_column; + } + memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); + for(i=0; inCol; i++){ + Column *pCol = &pNew->aCol[i]; + pCol->zName = sqlite3DbStrDup(db, pCol->zName); + pCol->zColl = 0; + pCol->zType = 0; + pCol->pDflt = 0; + pCol->zDflt = 0; + } + pNew->pSchema = db->aDb[iDb].pSchema; + pNew->addColOffset = pTab->addColOffset; + pNew->nRef = 1; + + /* Begin a transaction and increment the schema cookie. */ + sqlite3BeginWriteOperation(pParse, 0, iDb); + v = sqlite3GetVdbe(pParse); + if( !v ) goto exit_begin_add_column; + sqlite3ChangeCookie(pParse, iDb); + +exit_begin_add_column: + sqlite3SrcListDelete(db, pSrc); + return; +} +#endif /* SQLITE_ALTER_TABLE */ diff --git a/components/external/SQLite-3.8.1/src/analyze.c b/components/external/SQLite-3.8.1/src/analyze.c new file mode 100644 index 0000000000000000000000000000000000000000..30ea0f6065fd53cb227322651f9b7b76f1694b2e --- /dev/null +++ b/components/external/SQLite-3.8.1/src/analyze.c @@ -0,0 +1,1647 @@ +/* +** 2005-07-08 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code associated with the ANALYZE command. +** +** The ANALYZE command gather statistics about the content of tables +** and indices. These statistics are made available to the query planner +** to help it make better decisions about how to perform queries. +** +** The following system tables are or have been supported: +** +** CREATE TABLE sqlite_stat1(tbl, idx, stat); +** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample); +** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample); +** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample); +** +** Additional tables might be added in future releases of SQLite. +** The sqlite_stat2 table is not created or used unless the SQLite version +** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled +** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated. +** The sqlite_stat2 table is superseded by sqlite_stat3, which is only +** created and used by SQLite versions 3.7.9 and later and with +** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3 +** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced +** version of sqlite_stat3 and is only available when compiled with +** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is +** not possible to enable both STAT3 and STAT4 at the same time. If they +** are both enabled, then STAT4 takes precedence. +** +** For most applications, sqlite_stat1 provides all the statisics required +** for the query planner to make good choices. +** +** Format of sqlite_stat1: +** +** There is normally one row per index, with the index identified by the +** name in the idx column. The tbl column is the name of the table to +** which the index belongs. In each such row, the stat column will be +** a string consisting of a list of integers. The first integer in this +** list is the number of rows in the index. (This is the same as the +** number of rows in the table, except for partial indices.) The second +** integer is the average number of rows in the index that have the same +** value in the first column of the index. The third integer is the average +** number of rows in the index that have the same value for the first two +** columns. The N-th integer (for N>1) is the average number of rows in +** the index which have the same value for the first N-1 columns. For +** a K-column index, there will be K+1 integers in the stat column. If +** the index is unique, then the last integer will be 1. +** +** The list of integers in the stat column can optionally be followed +** by the keyword "unordered". The "unordered" keyword, if it is present, +** must be separated from the last integer by a single space. If the +** "unordered" keyword is present, then the query planner assumes that +** the index is unordered and will not use the index for a range query. +** +** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat +** column contains a single integer which is the (estimated) number of +** rows in the table identified by sqlite_stat1.tbl. +** +** Format of sqlite_stat2: +** +** The sqlite_stat2 is only created and is only used if SQLite is compiled +** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between +** 3.6.18 and 3.7.8. The "stat2" table contains additional information +** about the distribution of keys within an index. The index is identified by +** the "idx" column and the "tbl" column is the name of the table to which +** the index belongs. There are usually 10 rows in the sqlite_stat2 +** table for each index. +** +** The sqlite_stat2 entries for an index that have sampleno between 0 and 9 +** inclusive are samples of the left-most key value in the index taken at +** evenly spaced points along the index. Let the number of samples be S +** (10 in the standard build) and let C be the number of rows in the index. +** Then the sampled rows are given by: +** +** rownumber = (i*C*2 + C)/(S*2) +** +** For i between 0 and S-1. Conceptually, the index space is divided into +** S uniform buckets and the samples are the middle row from each bucket. +** +** The format for sqlite_stat2 is recorded here for legacy reference. This +** version of SQLite does not support sqlite_stat2. It neither reads nor +** writes the sqlite_stat2 table. This version of SQLite only supports +** sqlite_stat3. +** +** Format for sqlite_stat3: +** +** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the +** sqlite_stat4 format will be described first. Further information +** about sqlite_stat3 follows the sqlite_stat4 description. +** +** Format for sqlite_stat4: +** +** As with sqlite_stat2, the sqlite_stat4 table contains histogram data +** to aid the query planner in choosing good indices based on the values +** that indexed columns are compared against in the WHERE clauses of +** queries. +** +** The sqlite_stat4 table contains multiple entries for each index. +** The idx column names the index and the tbl column is the table of the +** index. If the idx and tbl columns are the same, then the sample is +** of the INTEGER PRIMARY KEY. The sample column is a blob which is the +** binary encoding of a key from the index. The nEq column is a +** list of integers. The first integer is the approximate number +** of entries in the index whose left-most column exactly matches +** the left-most column of the sample. The second integer in nEq +** is the approximate number of entries in the index where the +** first two columns match the first two columns of the sample. +** And so forth. nLt is another list of integers that show the approximate +** number of entries that are strictly less than the sample. The first +** integer in nLt contains the number of entries in the index where the +** left-most column is less than the left-most column of the sample. +** The K-th integer in the nLt entry is the number of index entries +** where the first K columns are less than the first K columns of the +** sample. The nDLt column is like nLt except that it contains the +** number of distinct entries in the index that are less than the +** sample. +** +** There can be an arbitrary number of sqlite_stat4 entries per index. +** The ANALYZE command will typically generate sqlite_stat4 tables +** that contain between 10 and 40 samples which are distributed across +** the key space, though not uniformly, and which include samples with +** large nEq values. +** +** Format for sqlite_stat3 redux: +** +** The sqlite_stat3 table is like sqlite_stat4 except that it only +** looks at the left-most column of the index. The sqlite_stat3.sample +** column contains the actual value of the left-most column instead +** of a blob encoding of the complete index key as is found in +** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3 +** all contain just a single integer which is the same as the first +** integer in the equivalent columns in sqlite_stat4. +*/ +#ifndef SQLITE_OMIT_ANALYZE +#include "sqliteInt.h" + +#if defined(SQLITE_ENABLE_STAT4) +# define IsStat4 1 +# define IsStat3 0 +#elif defined(SQLITE_ENABLE_STAT3) +# define IsStat4 0 +# define IsStat3 1 +#else +# define IsStat4 0 +# define IsStat3 0 +# undef SQLITE_STAT4_SAMPLES +# define SQLITE_STAT4_SAMPLES 1 +#endif +#define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */ + +/* +** This routine generates code that opens the sqlite_statN tables. +** The sqlite_stat1 table is always relevant. sqlite_stat2 is now +** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when +** appropriate compile-time options are provided. +** +** If the sqlite_statN tables do not previously exist, it is created. +** +** Argument zWhere may be a pointer to a buffer containing a table name, +** or it may be a NULL pointer. If it is not NULL, then all entries in +** the sqlite_statN tables associated with the named table are deleted. +** If zWhere==0, then code is generated to delete all stat table entries. +*/ +static void openStatTable( + Parse *pParse, /* Parsing context */ + int iDb, /* The database we are looking in */ + int iStatCur, /* Open the sqlite_stat1 table on this cursor */ + const char *zWhere, /* Delete entries for this table or index */ + const char *zWhereType /* Either "tbl" or "idx" */ +){ + static const struct { + const char *zName; + const char *zCols; + } aTable[] = { + { "sqlite_stat1", "tbl,idx,stat" }, +#if defined(SQLITE_ENABLE_STAT4) + { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" }, + { "sqlite_stat3", 0 }, +#elif defined(SQLITE_ENABLE_STAT3) + { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" }, + { "sqlite_stat4", 0 }, +#else + { "sqlite_stat3", 0 }, + { "sqlite_stat4", 0 }, +#endif + }; + int i; + sqlite3 *db = pParse->db; + Db *pDb; + Vdbe *v = sqlite3GetVdbe(pParse); + int aRoot[ArraySize(aTable)]; + u8 aCreateTbl[ArraySize(aTable)]; + + if( v==0 ) return; + assert( sqlite3BtreeHoldsAllMutexes(db) ); + assert( sqlite3VdbeDb(v)==db ); + pDb = &db->aDb[iDb]; + + /* Create new statistic tables if they do not exist, or clear them + ** if they do already exist. + */ + for(i=0; izName))==0 ){ + if( aTable[i].zCols ){ + /* The sqlite_statN table does not exist. Create it. Note that a + ** side-effect of the CREATE TABLE statement is to leave the rootpage + ** of the new table in register pParse->regRoot. This is important + ** because the OpenWrite opcode below will be needing it. */ + sqlite3NestedParse(pParse, + "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols + ); + aRoot[i] = pParse->regRoot; + aCreateTbl[i] = OPFLAG_P2ISREG; + } + }else{ + /* The table already exists. If zWhere is not NULL, delete all entries + ** associated with the table zWhere. If zWhere is NULL, delete the + ** entire contents of the table. */ + aRoot[i] = pStat->tnum; + aCreateTbl[i] = 0; + sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab); + if( zWhere ){ + sqlite3NestedParse(pParse, + "DELETE FROM %Q.%s WHERE %s=%Q", + pDb->zName, zTab, zWhereType, zWhere + ); + }else{ + /* The sqlite_stat[134] table already exists. Delete all rows. */ + sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb); + } + } + } + + /* Open the sqlite_stat[134] tables for writing. */ + for(i=0; aTable[i].zCols; i++){ + assert( i1 ); /* >1 because it includes the rowid column */ + nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol; + + /* Allocate the space required for the Stat4Accum object */ + n = sizeof(*p) + + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */ + + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */ + + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */ + + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample) +#endif + ; + p = sqlite3MallocZero(n); + if( p==0 ){ + sqlite3_result_error_nomem(context); + return; + } + + p->nRow = 0; + p->nCol = nCol; + p->current.anDLt = (tRowcnt*)&p[1]; + p->current.anEq = &p->current.anDLt[nColUp]; + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + { + u8 *pSpace; /* Allocated space not yet assigned */ + int i; /* Used to iterate through p->aSample[] */ + + p->iGet = -1; + p->mxSample = mxSample; + p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1); + p->current.anLt = &p->current.anEq[nColUp]; + p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565; + + /* Set up the Stat4Accum.a[] and aBest[] arrays */ + p->a = (struct Stat4Sample*)&p->current.anLt[nColUp]; + p->aBest = &p->a[mxSample]; + pSpace = (u8*)(&p->a[mxSample+nCol]); + for(i=0; i<(mxSample+nCol); i++){ + p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); + p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); + p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); + } + assert( (pSpace - (u8*)p)==n ); + + for(i=0; iaBest[i].iCol = i; + } + } +#endif + + /* Return a pointer to the allocated object to the caller */ + sqlite3_result_blob(context, p, sizeof(p), sqlite3_free); +} +static const FuncDef statInitFuncdef = { + 1+IsStat34, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + statInit, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "stat_init", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ +}; + +#ifdef SQLITE_ENABLE_STAT4 +/* +** pNew and pOld are both candidate non-periodic samples selected for +** the same column (pNew->iCol==pOld->iCol). Ignoring this column and +** considering only any trailing columns and the sample hash value, this +** function returns true if sample pNew is to be preferred over pOld. +** In other words, if we assume that the cardinalities of the selected +** column for pNew and pOld are equal, is pNew to be preferred over pOld. +** +** This function assumes that for each argument sample, the contents of +** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. +*/ +static int sampleIsBetterPost( + Stat4Accum *pAccum, + Stat4Sample *pNew, + Stat4Sample *pOld +){ + int nCol = pAccum->nCol; + int i; + assert( pNew->iCol==pOld->iCol ); + for(i=pNew->iCol+1; ianEq[i]>pOld->anEq[i] ) return 1; + if( pNew->anEq[i]anEq[i] ) return 0; + } + if( pNew->iHash>pOld->iHash ) return 1; + return 0; +} +#endif + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Return true if pNew is to be preferred over pOld. +** +** This function assumes that for each argument sample, the contents of +** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. +*/ +static int sampleIsBetter( + Stat4Accum *pAccum, + Stat4Sample *pNew, + Stat4Sample *pOld +){ + tRowcnt nEqNew = pNew->anEq[pNew->iCol]; + tRowcnt nEqOld = pOld->anEq[pOld->iCol]; + + assert( pOld->isPSample==0 && pNew->isPSample==0 ); + assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) ); + + if( (nEqNew>nEqOld) ) return 1; +#ifdef SQLITE_ENABLE_STAT4 + if( nEqNew==nEqOld ){ + if( pNew->iColiCol ) return 1; + return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld)); + } + return 0; +#else + return (nEqNew==nEqOld && pNew->iHash>pOld->iHash); +#endif +} + +/* +** Copy the contents of object (*pFrom) into (*pTo). +*/ +static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){ + pTo->iRowid = pFrom->iRowid; + pTo->isPSample = pFrom->isPSample; + pTo->iCol = pFrom->iCol; + pTo->iHash = pFrom->iHash; + memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol); + memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol); + memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol); +} + +/* +** Copy the contents of sample *pNew into the p->a[] array. If necessary, +** remove the least desirable sample from p->a[] to make room. +*/ +static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ + Stat4Sample *pSample; + int i; + + assert( IsStat4 || nEqZero==0 ); + +#ifdef SQLITE_ENABLE_STAT4 + if( pNew->isPSample==0 ){ + Stat4Sample *pUpgrade = 0; + assert( pNew->anEq[pNew->iCol]>0 ); + + /* This sample is being added because the prefix that ends in column + ** iCol occurs many times in the table. However, if we have already + ** added a sample that shares this prefix, there is no need to add + ** this one. Instead, upgrade the priority of the highest priority + ** existing sample that shares this prefix. */ + for(i=p->nSample-1; i>=0; i--){ + Stat4Sample *pOld = &p->a[i]; + if( pOld->anEq[pNew->iCol]==0 ){ + if( pOld->isPSample ) return; + assert( pOld->iCol>pNew->iCol ); + assert( sampleIsBetter(p, pNew, pOld) ); + if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){ + pUpgrade = pOld; + } + } + } + if( pUpgrade ){ + pUpgrade->iCol = pNew->iCol; + pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol]; + goto find_new_min; + } + } +#endif + + /* If necessary, remove sample iMin to make room for the new sample. */ + if( p->nSample>=p->mxSample ){ + Stat4Sample *pMin = &p->a[p->iMin]; + tRowcnt *anEq = pMin->anEq; + tRowcnt *anLt = pMin->anLt; + tRowcnt *anDLt = pMin->anDLt; + memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1)); + pSample = &p->a[p->nSample-1]; + pSample->anEq = anEq; + pSample->anDLt = anDLt; + pSample->anLt = anLt; + p->nSample = p->mxSample-1; + } + + /* The "rows less-than" for the rowid column must be greater than that + ** for the last sample in the p->a[] array. Otherwise, the samples would + ** be out of order. */ +#ifdef SQLITE_ENABLE_STAT4 + assert( p->nSample==0 + || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] ); +#endif + + /* Insert the new sample */ + pSample = &p->a[p->nSample]; + sampleCopy(p, pSample, pNew); + p->nSample++; + + /* Zero the first nEqZero entries in the anEq[] array. */ + memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero); + +#ifdef SQLITE_ENABLE_STAT4 + find_new_min: +#endif + if( p->nSample>=p->mxSample ){ + int iMin = -1; + for(i=0; imxSample; i++){ + if( p->a[i].isPSample ) continue; + if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){ + iMin = i; + } + } + assert( iMin>=0 ); + p->iMin = iMin; + } +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +/* +** Field iChng of the index being scanned has changed. So at this point +** p->current contains a sample that reflects the previous row of the +** index. The value of anEq[iChng] and subsequent anEq[] elements are +** correct at this point. +*/ +static void samplePushPrevious(Stat4Accum *p, int iChng){ +#ifdef SQLITE_ENABLE_STAT4 + int i; + + /* Check if any samples from the aBest[] array should be pushed + ** into IndexSample.a[] at this point. */ + for(i=(p->nCol-2); i>=iChng; i--){ + Stat4Sample *pBest = &p->aBest[i]; + pBest->anEq[i] = p->current.anEq[i]; + if( p->nSamplemxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){ + sampleInsert(p, pBest, i); + } + } + + /* Update the anEq[] fields of any samples already collected. */ + for(i=p->nSample-1; i>=0; i--){ + int j; + for(j=iChng; jnCol; j++){ + if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j]; + } + } +#endif + +#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4) + if( iChng==0 ){ + tRowcnt nLt = p->current.anLt[0]; + tRowcnt nEq = p->current.anEq[0]; + + /* Check if this is to be a periodic sample. If so, add it. */ + if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){ + p->current.isPSample = 1; + sampleInsert(p, &p->current, 0); + p->current.isPSample = 0; + }else + + /* Or if it is a non-periodic sample. Add it in this case too. */ + if( p->nSamplemxSample + || sampleIsBetter(p, &p->current, &p->a[p->iMin]) + ){ + sampleInsert(p, &p->current, 0); + } + } +#endif + +#ifndef SQLITE_ENABLE_STAT3_OR_STAT4 + UNUSED_PARAMETER( p ); + UNUSED_PARAMETER( iChng ); +#endif +} + +/* +** Implementation of the stat_push SQL function: stat_push(P,R,C) +** Arguments: +** +** P Pointer to the Stat4Accum object created by stat_init() +** C Index of left-most column to differ from previous row +** R Rowid for the current row +** +** The SQL function always returns NULL. +** +** The R parameter is only used for STAT3 and STAT4. +*/ +static void statPush( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int i; + + /* The three function arguments */ + Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); + int iChng = sqlite3_value_int(argv[1]); + + UNUSED_PARAMETER( argc ); + UNUSED_PARAMETER( context ); + assert( p->nCol>1 ); /* Includes rowid field */ + assert( iChngnCol ); + + if( p->nRow==0 ){ + /* This is the first call to this function. Do initialization. */ + for(i=0; inCol; i++) p->current.anEq[i] = 1; + }else{ + /* Second and subsequent calls get processed here */ + samplePushPrevious(p, iChng); + + /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply + ** to the current row of the index. */ + for(i=0; icurrent.anEq[i]++; + } + for(i=iChng; inCol; i++){ + p->current.anDLt[i]++; +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + p->current.anLt[i] += p->current.anEq[i]; +#endif + p->current.anEq[i] = 1; + } + } + p->nRow++; +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + p->current.iRowid = sqlite3_value_int64(argv[2]); + p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345; +#endif + +#ifdef SQLITE_ENABLE_STAT4 + { + tRowcnt nLt = p->current.anLt[p->nCol-1]; + + /* Check if this is to be a periodic sample. If so, add it. */ + if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){ + p->current.isPSample = 1; + p->current.iCol = 0; + sampleInsert(p, &p->current, p->nCol-1); + p->current.isPSample = 0; + } + + /* Update the aBest[] array. */ + for(i=0; i<(p->nCol-1); i++){ + p->current.iCol = i; + if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){ + sampleCopy(p, &p->aBest[i], &p->current); + } + } + } +#endif +} +static const FuncDef statPushFuncdef = { + 2+IsStat34, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + statPush, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "stat_push", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ +}; + +#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */ +#define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */ +#define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */ +#define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */ +#define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */ + +/* +** Implementation of the stat_get(P,J) SQL function. This routine is +** used to query the results. Content is returned for parameter J +** which is one of the STAT_GET_xxxx values defined above. +** +** If neither STAT3 nor STAT4 are enabled, then J is always +** STAT_GET_STAT1 and is hence omitted and this routine becomes +** a one-parameter function, stat_get(P), that always returns the +** stat1 table entry information. +*/ +static void statGet( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + /* STAT3 and STAT4 have a parameter on this routine. */ + int eCall = sqlite3_value_int(argv[1]); + assert( argc==2 ); + assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ + || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT + || eCall==STAT_GET_NDLT + ); + if( eCall==STAT_GET_STAT1 ) +#else + assert( argc==1 ); +#endif + { + /* Return the value to store in the "stat" column of the sqlite_stat1 + ** table for this index. + ** + ** The value is a string composed of a list of integers describing + ** the index. The first integer in the list is the total number of + ** entries in the index. There is one additional integer in the list + ** for each indexed column. This additional integer is an estimate of + ** the number of rows matched by a stabbing query on the index using + ** a key with the corresponding number of fields. In other words, + ** if the index is on columns (a,b) and the sqlite_stat1 value is + ** "100 10 2", then SQLite estimates that: + ** + ** * the index contains 100 rows, + ** * "WHERE a=?" matches 10 rows, and + ** * "WHERE a=? AND b=?" matches 2 rows. + ** + ** If D is the count of distinct values and K is the total number of + ** rows, then each estimate is computed as: + ** + ** I = (K+D-1)/D + */ + char *z; + int i; + + char *zRet = sqlite3MallocZero(p->nCol * 25); + if( zRet==0 ){ + sqlite3_result_error_nomem(context); + return; + } + + sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow); + z = zRet + sqlite3Strlen30(zRet); + for(i=0; i<(p->nCol-1); i++){ + u64 nDistinct = p->current.anDLt[i] + 1; + u64 iVal = (p->nRow + nDistinct - 1) / nDistinct; + sqlite3_snprintf(24, z, " %llu", iVal); + z += sqlite3Strlen30(z); + assert( p->current.anEq[i] ); + } + assert( z[0]=='\0' && z>zRet ); + + sqlite3_result_text(context, zRet, -1, sqlite3_free); + } +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + else if( eCall==STAT_GET_ROWID ){ + if( p->iGet<0 ){ + samplePushPrevious(p, 0); + p->iGet = 0; + } + if( p->iGetnSample ){ + sqlite3_result_int64(context, p->a[p->iGet].iRowid); + } + }else{ + tRowcnt *aCnt = 0; + + assert( p->iGetnSample ); + switch( eCall ){ + case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break; + case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break; + default: { + aCnt = p->a[p->iGet].anDLt; + p->iGet++; + break; + } + } + + if( IsStat3 ){ + sqlite3_result_int64(context, (i64)aCnt[0]); + }else{ + char *zRet = sqlite3MallocZero(p->nCol * 25); + if( zRet==0 ){ + sqlite3_result_error_nomem(context); + }else{ + int i; + char *z = zRet; + for(i=0; inCol; i++){ + sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]); + z += sqlite3Strlen30(z); + } + assert( z[0]=='\0' && z>zRet ); + z[-1] = '\0'; + sqlite3_result_text(context, zRet, -1, sqlite3_free); + } + } + } +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#ifndef SQLITE_DEBUG + UNUSED_PARAMETER( argc ); +#endif +} +static const FuncDef statGetFuncdef = { + 1+IsStat34, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + statGet, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "stat_get", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ +}; + +static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){ + assert( regOut!=regStat4 && regOut!=regStat4+1 ); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1); +#elif SQLITE_DEBUG + assert( iParam==STAT_GET_STAT1 ); +#else + UNUSED_PARAMETER( iParam ); +#endif + sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut); + sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, 1 + IsStat34); +} + +/* +** Generate code to do an analysis of all indices associated with +** a single table. +*/ +static void analyzeOneTable( + Parse *pParse, /* Parser context */ + Table *pTab, /* Table whose indices are to be analyzed */ + Index *pOnlyIdx, /* If not NULL, only analyze this one index */ + int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ + int iMem, /* Available memory locations begin here */ + int iTab /* Next available cursor */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + Index *pIdx; /* An index to being analyzed */ + int iIdxCur; /* Cursor open on index being analyzed */ + int iTabCur; /* Table cursor */ + Vdbe *v; /* The virtual machine being built up */ + int i; /* Loop counter */ + int jZeroRows = -1; /* Jump from here if number of rows is zero */ + int iDb; /* Index of database containing pTab */ + u8 needTableCnt = 1; /* True to count the table */ + int regNewRowid = iMem++; /* Rowid for the inserted record */ + int regStat4 = iMem++; /* Register to hold Stat4Accum object */ + int regChng = iMem++; /* Index of changed index field */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + int regRowid = iMem++; /* Rowid argument passed to stat_push() */ +#endif + int regTemp = iMem++; /* Temporary use register */ + int regTabname = iMem++; /* Register containing table name */ + int regIdxname = iMem++; /* Register containing index name */ + int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */ + int regPrev = iMem; /* MUST BE LAST (see below) */ + + pParse->nMem = MAX(pParse->nMem, iMem); + v = sqlite3GetVdbe(pParse); + if( v==0 || NEVER(pTab==0) ){ + return; + } + if( pTab->tnum==0 ){ + /* Do not gather statistics on views or virtual tables */ + return; + } + if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){ + /* Do not gather statistics on system tables */ + return; + } + assert( sqlite3BtreeHoldsAllMutexes(db) ); + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( iDb>=0 ); + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); +#ifndef SQLITE_OMIT_AUTHORIZATION + if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0, + db->aDb[iDb].zName ) ){ + return; + } +#endif + + /* Establish a read-lock on the table at the shared-cache level. + ** Open a read-only cursor on the table. Also allocate a cursor number + ** to use for scanning indexes (iIdxCur). No index cursor is opened at + ** this time though. */ + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + iTabCur = iTab++; + iIdxCur = iTab++; + pParse->nTab = MAX(pParse->nTab, iTab); + sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); + sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0); + + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + int nCol; /* Number of columns indexed by pIdx */ + KeyInfo *pKey; /* KeyInfo structure for pIdx */ + int *aGotoChng; /* Array of jump instruction addresses */ + int addrRewind; /* Address of "OP_Rewind iIdxCur" */ + int addrGotoChng0; /* Address of "Goto addr_chng_0" */ + int addrNextRow; /* Address of "next_row:" */ + + if( pOnlyIdx && pOnlyIdx!=pIdx ) continue; + if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0; + VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName)); + nCol = pIdx->nColumn; + aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1)); + if( aGotoChng==0 ) continue; + pKey = sqlite3IndexKeyinfo(pParse, pIdx); + + /* Populate the register containing the index name. */ + sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0); + + /* + ** Pseudo-code for loop that calls stat_push(): + ** + ** Rewind csr + ** if eof(csr) goto end_of_scan; + ** regChng = 0 + ** goto chng_addr_0; + ** + ** next_row: + ** regChng = 0 + ** if( idx(0) != regPrev(0) ) goto chng_addr_0 + ** regChng = 1 + ** if( idx(1) != regPrev(1) ) goto chng_addr_1 + ** ... + ** regChng = N + ** goto chng_addr_N + ** + ** chng_addr_0: + ** regPrev(0) = idx(0) + ** chng_addr_1: + ** regPrev(1) = idx(1) + ** ... + ** + ** chng_addr_N: + ** regRowid = idx(rowid) + ** stat_push(P, regChng, regRowid) + ** Next csr + ** if !eof(csr) goto next_row; + ** + ** end_of_scan: + */ + + /* Make sure there are enough memory cells allocated to accommodate + ** the regPrev array and a trailing rowid (the rowid slot is required + ** when building a record to insert into the sample column of + ** the sqlite_stat4 table. */ + pParse->nMem = MAX(pParse->nMem, regPrev+nCol); + + /* Open a read-only cursor on the index being analyzed. */ + assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) ); + sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb); + sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIdx->zName)); + + /* Invoke the stat_init() function. The arguments are: + ** + ** (1) the number of columns in the index including the rowid, + ** (2) the number of rows in the index, + ** + ** The second argument is only used for STAT3 and STAT4 + */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2); +#endif + sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1); + sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4); + sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, 1+IsStat34); + + /* Implementation of the following: + ** + ** Rewind csr + ** if eof(csr) goto end_of_scan; + ** regChng = 0 + ** goto next_push_0; + ** + */ + addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur); + sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng); + addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto); + + /* + ** next_row: + ** regChng = 0 + ** if( idx(0) != regPrev(0) ) goto chng_addr_0 + ** regChng = 1 + ** if( idx(1) != regPrev(1) ) goto chng_addr_1 + ** ... + ** regChng = N + ** goto chng_addr_N + */ + addrNextRow = sqlite3VdbeCurrentAddr(v); + for(i=0; iazColl[i]); + sqlite3VdbeAddOp2(v, OP_Integer, i, regChng); + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp); + aGotoChng[i] = + sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ); + sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); + } + sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng); + aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto); + + /* + ** chng_addr_0: + ** regPrev(0) = idx(0) + ** chng_addr_1: + ** regPrev(1) = idx(1) + ** ... + */ + sqlite3VdbeJumpHere(v, addrGotoChng0); + for(i=0; inMem = MAX(pParse->nMem, regCol+nCol+1); + + addrNext = sqlite3VdbeCurrentAddr(v); + callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid); + addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid); + callStatGet(v, regStat4, STAT_GET_NEQ, regEq); + callStatGet(v, regStat4, STAT_GET_NLT, regLt); + callStatGet(v, regStat4, STAT_GET_NDLT, regDLt); + sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid); +#ifdef SQLITE_ENABLE_STAT3 + sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, + pIdx->aiColumn[0], regSample); +#else + for(i=0; iaiColumn[i]; + sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i); + } + sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample); +#endif + sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0); + sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid); + sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext); + sqlite3VdbeJumpHere(v, addrIsNull); + } +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + + /* End of analysis */ + sqlite3VdbeJumpHere(v, addrRewind); + sqlite3DbFree(db, aGotoChng); + } + + + /* Create a single sqlite_stat1 entry containing NULL as the index + ** name and the row count as the content. + */ + if( pOnlyIdx==0 && needTableCnt ){ + VdbeComment((v, "%s", pTab->zName)); + sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1); + jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); + sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname); + sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0); + sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); + sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3VdbeJumpHere(v, jZeroRows); + } +} + + +/* +** Generate code that will cause the most recent index analysis to +** be loaded into internal hash tables where is can be used. +*/ +static void loadAnalysis(Parse *pParse, int iDb){ + Vdbe *v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb); + } +} + +/* +** Generate code that will do an analysis of an entire database +*/ +static void analyzeDatabase(Parse *pParse, int iDb){ + sqlite3 *db = pParse->db; + Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */ + HashElem *k; + int iStatCur; + int iMem; + int iTab; + + sqlite3BeginWriteOperation(pParse, 0, iDb); + iStatCur = pParse->nTab; + pParse->nTab += 3; + openStatTable(pParse, iDb, iStatCur, 0, 0); + iMem = pParse->nMem+1; + iTab = pParse->nTab; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ + Table *pTab = (Table*)sqliteHashData(k); + analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab); + } + loadAnalysis(pParse, iDb); +} + +/* +** Generate code that will do an analysis of a single table in +** a database. If pOnlyIdx is not NULL then it is a single index +** in pTab that should be analyzed. +*/ +static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){ + int iDb; + int iStatCur; + + assert( pTab!=0 ); + assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + sqlite3BeginWriteOperation(pParse, 0, iDb); + iStatCur = pParse->nTab; + pParse->nTab += 3; + if( pOnlyIdx ){ + openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx"); + }else{ + openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl"); + } + analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab); + loadAnalysis(pParse, iDb); +} + +/* +** Generate code for the ANALYZE command. The parser calls this routine +** when it recognizes an ANALYZE command. +** +** ANALYZE -- 1 +** ANALYZE -- 2 +** ANALYZE ?.? -- 3 +** +** Form 1 causes all indices in all attached databases to be analyzed. +** Form 2 analyzes all indices the single database named. +** Form 3 analyzes all indices associated with the named table. +*/ +void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ + sqlite3 *db = pParse->db; + int iDb; + int i; + char *z, *zDb; + Table *pTab; + Index *pIdx; + Token *pTableName; + + /* Read the database schema. If an error occurs, leave an error message + ** and code in pParse and return NULL. */ + assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + return; + } + + assert( pName2!=0 || pName1==0 ); + if( pName1==0 ){ + /* Form 1: Analyze everything */ + for(i=0; inDb; i++){ + if( i==1 ) continue; /* Do not analyze the TEMP database */ + analyzeDatabase(pParse, i); + } + }else if( pName2->n==0 ){ + /* Form 2: Analyze the database or table named */ + iDb = sqlite3FindDb(db, pName1); + if( iDb>=0 ){ + analyzeDatabase(pParse, iDb); + }else{ + z = sqlite3NameFromToken(db, pName1); + if( z ){ + if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){ + analyzeTable(pParse, pIdx->pTable, pIdx); + }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){ + analyzeTable(pParse, pTab, 0); + } + sqlite3DbFree(db, z); + } + } + }else{ + /* Form 3: Analyze the fully qualified table name */ + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName); + if( iDb>=0 ){ + zDb = db->aDb[iDb].zName; + z = sqlite3NameFromToken(db, pTableName); + if( z ){ + if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){ + analyzeTable(pParse, pIdx->pTable, pIdx); + }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){ + analyzeTable(pParse, pTab, 0); + } + sqlite3DbFree(db, z); + } + } + } +} + +/* +** Used to pass information from the analyzer reader through to the +** callback routine. +*/ +typedef struct analysisInfo analysisInfo; +struct analysisInfo { + sqlite3 *db; + const char *zDatabase; +}; + +/* +** The first argument points to a nul-terminated string containing a +** list of space separated integers. Read the first nOut of these into +** the array aOut[]. +*/ +static void decodeIntArray( + char *zIntArray, /* String containing int array to decode */ + int nOut, /* Number of slots in aOut[] */ + tRowcnt *aOut, /* Store integers here */ + Index *pIndex /* Handle extra flags for this index, if not NULL */ +){ + char *z = zIntArray; + int c; + int i; + tRowcnt v; + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( z==0 ) z = ""; +#else + if( NEVER(z==0) ) z = ""; +#endif + for(i=0; *z && i='0' && c<='9' ){ + v = v*10 + c - '0'; + z++; + } + aOut[i] = v; + if( *z==' ' ) z++; + } +#ifndef SQLITE_ENABLE_STAT3_OR_STAT4 + assert( pIndex!=0 ); +#else + if( pIndex ) +#endif + { + if( strcmp(z, "unordered")==0 ){ + pIndex->bUnordered = 1; + }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){ + int v32 = 0; + sqlite3GetInt32(z+3, &v32); + pIndex->szIdxRow = sqlite3LogEst(v32); + } + } +} + +/* +** This callback is invoked once for each index when reading the +** sqlite_stat1 table. +** +** argv[0] = name of the table +** argv[1] = name of the index (might be NULL) +** argv[2] = results of analysis - on integer for each column +** +** Entries for which argv[1]==NULL simply record the number of rows in +** the table. +*/ +static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){ + analysisInfo *pInfo = (analysisInfo*)pData; + Index *pIndex; + Table *pTable; + const char *z; + + assert( argc==3 ); + UNUSED_PARAMETER2(NotUsed, argc); + + if( argv==0 || argv[0]==0 || argv[2]==0 ){ + return 0; + } + pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase); + if( pTable==0 ){ + return 0; + } + if( argv[1] ){ + pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase); + }else{ + pIndex = 0; + } + z = argv[2]; + + if( pIndex ){ + decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, pIndex); + if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0]; + }else{ + Index fakeIdx; + fakeIdx.szIdxRow = pTable->szTabRow; + decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx); + pTable->szTabRow = fakeIdx.szIdxRow; + } + + return 0; +} + +/* +** If the Index.aSample variable is not NULL, delete the aSample[] array +** and its contents. +*/ +void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( pIdx->aSample ){ + int j; + for(j=0; jnSample; j++){ + IndexSample *p = &pIdx->aSample[j]; + sqlite3DbFree(db, p->p); + } + sqlite3DbFree(db, pIdx->aSample); + } + if( db && db->pnBytesFreed==0 ){ + pIdx->nSample = 0; + pIdx->aSample = 0; + } +#else + UNUSED_PARAMETER(db); + UNUSED_PARAMETER(pIdx); +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +} + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Populate the pIdx->aAvgEq[] array based on the samples currently +** stored in pIdx->aSample[]. +*/ +static void initAvgEq(Index *pIdx){ + if( pIdx ){ + IndexSample *aSample = pIdx->aSample; + IndexSample *pFinal = &aSample[pIdx->nSample-1]; + int iCol; + for(iCol=0; iColnColumn; iCol++){ + int i; /* Used to iterate through samples */ + tRowcnt sumEq = 0; /* Sum of the nEq values */ + tRowcnt nSum = 0; /* Number of terms contributing to sumEq */ + tRowcnt avgEq = 0; + tRowcnt nDLt = pFinal->anDLt[iCol]; + + /* Set nSum to the number of distinct (iCol+1) field prefixes that + ** occur in the stat4 table for this index before pFinal. Set + ** sumEq to the sum of the nEq values for column iCol for the same + ** set (adding the value only once where there exist dupicate + ** prefixes). */ + for(i=0; i<(pIdx->nSample-1); i++){ + if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){ + sumEq += aSample[i].anEq[iCol]; + nSum++; + } + } + if( nDLt>nSum ){ + avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum); + } + if( avgEq==0 ) avgEq = 1; + pIdx->aAvgEq[iCol] = avgEq; + if( pIdx->nSampleCol==1 ) break; + } + } +} + +/* +** Load the content from either the sqlite_stat4 or sqlite_stat3 table +** into the relevant Index.aSample[] arrays. +** +** Arguments zSql1 and zSql2 must point to SQL statements that return +** data equivalent to the following (statements are different for stat3, +** see the caller of this function for details): +** +** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx +** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4 +** +** where %Q is replaced with the database name before the SQL is executed. +*/ +static int loadStatTbl( + sqlite3 *db, /* Database handle */ + int bStat3, /* Assume single column records only */ + const char *zSql1, /* SQL statement 1 (see above) */ + const char *zSql2, /* SQL statement 2 (see above) */ + const char *zDb /* Database name (e.g. "main") */ +){ + int rc; /* Result codes from subroutines */ + sqlite3_stmt *pStmt = 0; /* An SQL statement being run */ + char *zSql; /* Text of the SQL statement */ + Index *pPrevIdx = 0; /* Previous index in the loop */ + IndexSample *pSample; /* A slot in pIdx->aSample[] */ + + assert( db->lookaside.bEnabled==0 ); + zSql = sqlite3MPrintf(db, zSql1, zDb); + if( !zSql ){ + return SQLITE_NOMEM; + } + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + sqlite3DbFree(db, zSql); + if( rc ) return rc; + + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + int nIdxCol = 1; /* Number of columns in stat4 records */ + int nAvgCol = 1; /* Number of entries in Index.aAvgEq */ + + char *zIndex; /* Index name */ + Index *pIdx; /* Pointer to the index object */ + int nSample; /* Number of samples */ + int nByte; /* Bytes of space required */ + int i; /* Bytes of space required */ + tRowcnt *pSpace; + + zIndex = (char *)sqlite3_column_text(pStmt, 0); + if( zIndex==0 ) continue; + nSample = sqlite3_column_int(pStmt, 1); + pIdx = sqlite3FindIndex(db, zIndex, zDb); + assert( pIdx==0 || bStat3 || pIdx->nSample==0 ); + /* Index.nSample is non-zero at this point if data has already been + ** loaded from the stat4 table. In this case ignore stat3 data. */ + if( pIdx==0 || pIdx->nSample ) continue; + if( bStat3==0 ){ + nIdxCol = pIdx->nColumn+1; + nAvgCol = pIdx->nColumn; + } + pIdx->nSampleCol = nIdxCol; + nByte = sizeof(IndexSample) * nSample; + nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample; + nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */ + + pIdx->aSample = sqlite3DbMallocZero(db, nByte); + if( pIdx->aSample==0 ){ + sqlite3_finalize(pStmt); + return SQLITE_NOMEM; + } + pSpace = (tRowcnt*)&pIdx->aSample[nSample]; + pIdx->aAvgEq = pSpace; pSpace += nAvgCol; + for(i=0; iaSample[i].anEq = pSpace; pSpace += nIdxCol; + pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol; + pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol; + } + assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) ); + } + rc = sqlite3_finalize(pStmt); + if( rc ) return rc; + + zSql = sqlite3MPrintf(db, zSql2, zDb); + if( !zSql ){ + return SQLITE_NOMEM; + } + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + sqlite3DbFree(db, zSql); + if( rc ) return rc; + + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + char *zIndex; /* Index name */ + Index *pIdx; /* Pointer to the index object */ + int nCol = 1; /* Number of columns in index */ + + zIndex = (char *)sqlite3_column_text(pStmt, 0); + if( zIndex==0 ) continue; + pIdx = sqlite3FindIndex(db, zIndex, zDb); + if( pIdx==0 ) continue; + /* This next condition is true if data has already been loaded from + ** the sqlite_stat4 table. In this case ignore stat3 data. */ + nCol = pIdx->nSampleCol; + if( bStat3 && nCol>1 ) continue; + if( pIdx!=pPrevIdx ){ + initAvgEq(pPrevIdx); + pPrevIdx = pIdx; + } + pSample = &pIdx->aSample[pIdx->nSample]; + decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0); + decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0); + decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0); + + /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer. + ** This is in case the sample record is corrupted. In that case, the + ** sqlite3VdbeRecordCompare() may read up to two varints past the + ** end of the allocated buffer before it realizes it is dealing with + ** a corrupt record. Adding the two 0x00 bytes prevents this from causing + ** a buffer overread. */ + pSample->n = sqlite3_column_bytes(pStmt, 4); + pSample->p = sqlite3DbMallocZero(db, pSample->n + 2); + if( pSample->p==0 ){ + sqlite3_finalize(pStmt); + return SQLITE_NOMEM; + } + memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n); + pIdx->nSample++; + } + rc = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ) initAvgEq(pPrevIdx); + return rc; +} + +/* +** Load content from the sqlite_stat4 and sqlite_stat3 tables into +** the Index.aSample[] arrays of all indices. +*/ +static int loadStat4(sqlite3 *db, const char *zDb){ + int rc = SQLITE_OK; /* Result codes from subroutines */ + + assert( db->lookaside.bEnabled==0 ); + if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){ + rc = loadStatTbl(db, 0, + "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", + "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4", + zDb + ); + } + + if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){ + rc = loadStatTbl(db, 1, + "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", + "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3", + zDb + ); + } + + return rc; +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +/* +** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The +** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] +** arrays. The contents of sqlite_stat3/4 are used to populate the +** Index.aSample[] arrays. +** +** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR +** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined +** during compilation and the sqlite_stat3/4 table is present, no data is +** read from it. +** +** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the +** sqlite_stat4 table is not present in the database, SQLITE_ERROR is +** returned. However, in this case, data is read from the sqlite_stat1 +** table (if it is present) before returning. +** +** If an OOM error occurs, this function always sets db->mallocFailed. +** This means if the caller does not care about other errors, the return +** code may be ignored. +*/ +int sqlite3AnalysisLoad(sqlite3 *db, int iDb){ + analysisInfo sInfo; + HashElem *i; + char *zSql; + int rc; + + assert( iDb>=0 && iDbnDb ); + assert( db->aDb[iDb].pBt!=0 ); + + /* Clear any prior statistics */ + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ + Index *pIdx = sqliteHashData(i); + sqlite3DefaultRowEst(pIdx); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sqlite3DeleteIndexSamples(db, pIdx); + pIdx->aSample = 0; +#endif + } + + /* Check to make sure the sqlite_stat1 table exists */ + sInfo.db = db; + sInfo.zDatabase = db->aDb[iDb].zName; + if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){ + return SQLITE_ERROR; + } + + /* Load new statistics out of the sqlite_stat1 table */ + zSql = sqlite3MPrintf(db, + "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase); + if( zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0); + sqlite3DbFree(db, zSql); + } + + + /* Load the statistics from the sqlite_stat4 table. */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( rc==SQLITE_OK ){ + int lookasideEnabled = db->lookaside.bEnabled; + db->lookaside.bEnabled = 0; + rc = loadStat4(db, sInfo.zDatabase); + db->lookaside.bEnabled = lookasideEnabled; + } +#endif + + if( rc==SQLITE_NOMEM ){ + db->mallocFailed = 1; + } + return rc; +} + + +#endif /* SQLITE_OMIT_ANALYZE */ diff --git a/components/external/SQLite-3.8.1/src/attach.c b/components/external/SQLite-3.8.1/src/attach.c new file mode 100644 index 0000000000000000000000000000000000000000..223c166482842f0b8a56915427b78f2116daa7a9 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/attach.c @@ -0,0 +1,578 @@ +/* +** 2003 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the ATTACH and DETACH commands. +*/ +#include "sqliteInt.h" + +#ifndef SQLITE_OMIT_ATTACH +/* +** Resolve an expression that was part of an ATTACH or DETACH statement. This +** is slightly different from resolving a normal SQL expression, because simple +** identifiers are treated as strings, not possible column names or aliases. +** +** i.e. if the parser sees: +** +** ATTACH DATABASE abc AS def +** +** it treats the two expressions as literal strings 'abc' and 'def' instead of +** looking for columns of the same name. +** +** This only applies to the root node of pExpr, so the statement: +** +** ATTACH DATABASE abc||def AS 'db2' +** +** will fail because neither abc or def can be resolved. +*/ +static int resolveAttachExpr(NameContext *pName, Expr *pExpr) +{ + int rc = SQLITE_OK; + if( pExpr ){ + if( pExpr->op!=TK_ID ){ + rc = sqlite3ResolveExprNames(pName, pExpr); + if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){ + sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken); + return SQLITE_ERROR; + } + }else{ + pExpr->op = TK_STRING; + } + } + return rc; +} + +/* +** An SQL user-function registered to do the work of an ATTACH statement. The +** three arguments to the function come directly from an attach statement: +** +** ATTACH DATABASE x AS y KEY z +** +** SELECT sqlite_attach(x, y, z) +** +** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the +** third argument. +*/ +static void attachFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + int i; + int rc = 0; + sqlite3 *db = sqlite3_context_db_handle(context); + const char *zName; + const char *zFile; + char *zPath = 0; + char *zErr = 0; + unsigned int flags; + Db *aNew; + char *zErrDyn = 0; + sqlite3_vfs *pVfs; + + UNUSED_PARAMETER(NotUsed); + + zFile = (const char *)sqlite3_value_text(argv[0]); + zName = (const char *)sqlite3_value_text(argv[1]); + if( zFile==0 ) zFile = ""; + if( zName==0 ) zName = ""; + + /* Check for the following errors: + ** + ** * Too many attached databases, + ** * Transaction currently open + ** * Specified database name already being used. + */ + if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){ + zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", + db->aLimit[SQLITE_LIMIT_ATTACHED] + ); + goto attach_error; + } + if( !db->autoCommit ){ + zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction"); + goto attach_error; + } + for(i=0; inDb; i++){ + char *z = db->aDb[i].zName; + assert( z && zName ); + if( sqlite3StrICmp(z, zName)==0 ){ + zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName); + goto attach_error; + } + } + + /* Allocate the new entry in the db->aDb[] array and initialize the schema + ** hash tables. + */ + if( db->aDb==db->aDbStatic ){ + aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 ); + if( aNew==0 ) return; + memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); + }else{ + aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); + if( aNew==0 ) return; + } + db->aDb = aNew; + aNew = &db->aDb[db->nDb]; + memset(aNew, 0, sizeof(*aNew)); + + /* Open the database file. If the btree is successfully opened, use + ** it to obtain the database schema. At this point the schema may + ** or may not be initialized. + */ + flags = db->openFlags; + rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM ) db->mallocFailed = 1; + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); + return; + } + assert( pVfs ); + flags |= SQLITE_OPEN_MAIN_DB; + rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags); + sqlite3_free( zPath ); + db->nDb++; + if( rc==SQLITE_CONSTRAINT ){ + rc = SQLITE_ERROR; + zErrDyn = sqlite3MPrintf(db, "database is already attached"); + }else if( rc==SQLITE_OK ){ + Pager *pPager; + aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt); + if( !aNew->pSchema ){ + rc = SQLITE_NOMEM; + }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){ + zErrDyn = sqlite3MPrintf(db, + "attached databases must use the same text encoding as main database"); + rc = SQLITE_ERROR; + } + pPager = sqlite3BtreePager(aNew->pBt); + sqlite3PagerLockingMode(pPager, db->dfltLockMode); + sqlite3BtreeSecureDelete(aNew->pBt, + sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) ); +#ifndef SQLITE_OMIT_PAGER_PRAGMAS + sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK)); +#endif + } + aNew->safety_level = 3; + aNew->zName = sqlite3DbStrDup(db, zName); + if( rc==SQLITE_OK && aNew->zName==0 ){ + rc = SQLITE_NOMEM; + } + + +#ifdef SQLITE_HAS_CODEC + if( rc==SQLITE_OK ){ + extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); + extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); + int nKey; + char *zKey; + int t = sqlite3_value_type(argv[2]); + switch( t ){ + case SQLITE_INTEGER: + case SQLITE_FLOAT: + zErrDyn = sqlite3DbStrDup(db, "Invalid key value"); + rc = SQLITE_ERROR; + break; + + case SQLITE_TEXT: + case SQLITE_BLOB: + nKey = sqlite3_value_bytes(argv[2]); + zKey = (char *)sqlite3_value_blob(argv[2]); + rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); + break; + + case SQLITE_NULL: + /* No key specified. Use the key from the main database */ + sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); + if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){ + rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); + } + break; + } + } +#endif + + /* If the file was opened successfully, read the schema for the new database. + ** If this fails, or if opening the file failed, then close the file and + ** remove the entry from the db->aDb[] array. i.e. put everything back the way + ** we found it. + */ + if( rc==SQLITE_OK ){ + sqlite3BtreeEnterAll(db); + rc = sqlite3Init(db, &zErrDyn); + sqlite3BtreeLeaveAll(db); + } + if( rc ){ + int iDb = db->nDb - 1; + assert( iDb>=2 ); + if( db->aDb[iDb].pBt ){ + sqlite3BtreeClose(db->aDb[iDb].pBt); + db->aDb[iDb].pBt = 0; + db->aDb[iDb].pSchema = 0; + } + sqlite3ResetAllSchemasOfConnection(db); + db->nDb = iDb; + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ + db->mallocFailed = 1; + sqlite3DbFree(db, zErrDyn); + zErrDyn = sqlite3MPrintf(db, "out of memory"); + }else if( zErrDyn==0 ){ + zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile); + } + goto attach_error; + } + + return; + +attach_error: + /* Return an error if we get here */ + if( zErrDyn ){ + sqlite3_result_error(context, zErrDyn, -1); + sqlite3DbFree(db, zErrDyn); + } + if( rc ) sqlite3_result_error_code(context, rc); +} + +/* +** An SQL user-function registered to do the work of an DETACH statement. The +** three arguments to the function come directly from a detach statement: +** +** DETACH DATABASE x +** +** SELECT sqlite_detach(x) +*/ +static void detachFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + const char *zName = (const char *)sqlite3_value_text(argv[0]); + sqlite3 *db = sqlite3_context_db_handle(context); + int i; + Db *pDb = 0; + char zErr[128]; + + UNUSED_PARAMETER(NotUsed); + + if( zName==0 ) zName = ""; + for(i=0; inDb; i++){ + pDb = &db->aDb[i]; + if( pDb->pBt==0 ) continue; + if( sqlite3StrICmp(pDb->zName, zName)==0 ) break; + } + + if( i>=db->nDb ){ + sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName); + goto detach_error; + } + if( i<2 ){ + sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName); + goto detach_error; + } + if( !db->autoCommit ){ + sqlite3_snprintf(sizeof(zErr), zErr, + "cannot DETACH database within transaction"); + goto detach_error; + } + if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){ + sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName); + goto detach_error; + } + + sqlite3BtreeClose(pDb->pBt); + pDb->pBt = 0; + pDb->pSchema = 0; + sqlite3ResetAllSchemasOfConnection(db); + return; + +detach_error: + sqlite3_result_error(context, zErr, -1); +} + +/* +** This procedure generates VDBE code for a single invocation of either the +** sqlite_detach() or sqlite_attach() SQL user functions. +*/ +static void codeAttach( + Parse *pParse, /* The parser context */ + int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */ + FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */ + Expr *pAuthArg, /* Expression to pass to authorization callback */ + Expr *pFilename, /* Name of database file */ + Expr *pDbname, /* Name of the database to use internally */ + Expr *pKey /* Database key for encryption extension */ +){ + int rc; + NameContext sName; + Vdbe *v; + sqlite3* db = pParse->db; + int regArgs; + + memset(&sName, 0, sizeof(NameContext)); + sName.pParse = pParse; + + if( + SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) || + SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) || + SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey)) + ){ + pParse->nErr++; + goto attach_end; + } + +#ifndef SQLITE_OMIT_AUTHORIZATION + if( pAuthArg ){ + char *zAuthArg; + if( pAuthArg->op==TK_STRING ){ + zAuthArg = pAuthArg->u.zToken; + }else{ + zAuthArg = 0; + } + rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); + if(rc!=SQLITE_OK ){ + goto attach_end; + } + } +#endif /* SQLITE_OMIT_AUTHORIZATION */ + + + v = sqlite3GetVdbe(pParse); + regArgs = sqlite3GetTempRange(pParse, 4); + sqlite3ExprCode(pParse, pFilename, regArgs); + sqlite3ExprCode(pParse, pDbname, regArgs+1); + sqlite3ExprCode(pParse, pKey, regArgs+2); + + assert( v || db->mallocFailed ); + if( v ){ + sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3); + assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg ); + sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg)); + sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF); + + /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this + ** statement only). For DETACH, set it to false (expire all existing + ** statements). + */ + sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH)); + } + +attach_end: + sqlite3ExprDelete(db, pFilename); + sqlite3ExprDelete(db, pDbname); + sqlite3ExprDelete(db, pKey); +} + +/* +** Called by the parser to compile a DETACH statement. +** +** DETACH pDbname +*/ +void sqlite3Detach(Parse *pParse, Expr *pDbname){ + static const FuncDef detach_func = { + 1, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + detachFunc, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "sqlite_detach", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ + }; + codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname); +} + +/* +** Called by the parser to compile an ATTACH statement. +** +** ATTACH p AS pDbname KEY pKey +*/ +void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){ + static const FuncDef attach_func = { + 3, /* nArg */ + SQLITE_UTF8, /* funcFlags */ + 0, /* pUserData */ + 0, /* pNext */ + attachFunc, /* xFunc */ + 0, /* xStep */ + 0, /* xFinalize */ + "sqlite_attach", /* zName */ + 0, /* pHash */ + 0 /* pDestructor */ + }; + codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey); +} +#endif /* SQLITE_OMIT_ATTACH */ + +/* +** Initialize a DbFixer structure. This routine must be called prior +** to passing the structure to one of the sqliteFixAAAA() routines below. +*/ +void sqlite3FixInit( + DbFixer *pFix, /* The fixer to be initialized */ + Parse *pParse, /* Error messages will be written here */ + int iDb, /* This is the database that must be used */ + const char *zType, /* "view", "trigger", or "index" */ + const Token *pName /* Name of the view, trigger, or index */ +){ + sqlite3 *db; + + db = pParse->db; + assert( db->nDb>iDb ); + pFix->pParse = pParse; + pFix->zDb = db->aDb[iDb].zName; + pFix->pSchema = db->aDb[iDb].pSchema; + pFix->zType = zType; + pFix->pName = pName; + pFix->bVarOnly = (iDb==1); +} + +/* +** The following set of routines walk through the parse tree and assign +** a specific database to all table references where the database name +** was left unspecified in the original SQL statement. The pFix structure +** must have been initialized by a prior call to sqlite3FixInit(). +** +** These routines are used to make sure that an index, trigger, or +** view in one database does not refer to objects in a different database. +** (Exception: indices, triggers, and views in the TEMP database are +** allowed to refer to anything.) If a reference is explicitly made +** to an object in a different database, an error message is added to +** pParse->zErrMsg and these routines return non-zero. If everything +** checks out, these routines return 0. +*/ +int sqlite3FixSrcList( + DbFixer *pFix, /* Context of the fixation */ + SrcList *pList /* The Source list to check and modify */ +){ + int i; + const char *zDb; + struct SrcList_item *pItem; + + if( NEVER(pList==0) ) return 0; + zDb = pFix->zDb; + for(i=0, pItem=pList->a; inSrc; i++, pItem++){ + if( pFix->bVarOnly==0 ){ + if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){ + sqlite3ErrorMsg(pFix->pParse, + "%s %T cannot reference objects in database %s", + pFix->zType, pFix->pName, pItem->zDatabase); + return 1; + } + sqlite3DbFree(pFix->pParse->db, pItem->zDatabase); + pItem->zDatabase = 0; + pItem->pSchema = pFix->pSchema; + } +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) + if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1; + if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1; +#endif + } + return 0; +} +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) +int sqlite3FixSelect( + DbFixer *pFix, /* Context of the fixation */ + Select *pSelect /* The SELECT statement to be fixed to one database */ +){ + while( pSelect ){ + if( sqlite3FixExprList(pFix, pSelect->pEList) ){ + return 1; + } + if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pSelect->pWhere) ){ + return 1; + } + if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pSelect->pHaving) ){ + return 1; + } + if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pSelect->pLimit) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pSelect->pOffset) ){ + return 1; + } + pSelect = pSelect->pPrior; + } + return 0; +} +int sqlite3FixExpr( + DbFixer *pFix, /* Context of the fixation */ + Expr *pExpr /* The expression to be fixed to one database */ +){ + while( pExpr ){ + if( pExpr->op==TK_VARIABLE ){ + if( pFix->pParse->db->init.busy ){ + pExpr->op = TK_NULL; + }else{ + sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType); + return 1; + } + } + if( ExprHasProperty(pExpr, EP_TokenOnly) ) break; + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1; + }else{ + if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1; + } + if( sqlite3FixExpr(pFix, pExpr->pRight) ){ + return 1; + } + pExpr = pExpr->pLeft; + } + return 0; +} +int sqlite3FixExprList( + DbFixer *pFix, /* Context of the fixation */ + ExprList *pList /* The expression to be fixed to one database */ +){ + int i; + struct ExprList_item *pItem; + if( pList==0 ) return 0; + for(i=0, pItem=pList->a; inExpr; i++, pItem++){ + if( sqlite3FixExpr(pFix, pItem->pExpr) ){ + return 1; + } + } + return 0; +} +#endif + +#ifndef SQLITE_OMIT_TRIGGER +int sqlite3FixTriggerStep( + DbFixer *pFix, /* Context of the fixation */ + TriggerStep *pStep /* The trigger step be fixed to one database */ +){ + while( pStep ){ + if( sqlite3FixSelect(pFix, pStep->pSelect) ){ + return 1; + } + if( sqlite3FixExpr(pFix, pStep->pWhere) ){ + return 1; + } + if( sqlite3FixExprList(pFix, pStep->pExprList) ){ + return 1; + } + pStep = pStep->pNext; + } + return 0; +} +#endif diff --git a/components/external/SQLite-3.8.1/src/auth.c b/components/external/SQLite-3.8.1/src/auth.c new file mode 100644 index 0000000000000000000000000000000000000000..d38bb836a784fbfab6ab7b03d4e6dd43edc41fa7 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/auth.c @@ -0,0 +1,249 @@ +/* +** 2003 January 11 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the sqlite3_set_authorizer() +** API. This facility is an optional feature of the library. Embedded +** systems that do not need this facility may omit it by recompiling +** the library with -DSQLITE_OMIT_AUTHORIZATION=1 +*/ +#include "sqliteInt.h" + +/* +** All of the code in this file may be omitted by defining a single +** macro. +*/ +#ifndef SQLITE_OMIT_AUTHORIZATION + +/* +** Set or clear the access authorization function. +** +** The access authorization function is be called during the compilation +** phase to verify that the user has read and/or write access permission on +** various fields of the database. The first argument to the auth function +** is a copy of the 3rd argument to this routine. The second argument +** to the auth function is one of these constants: +** +** SQLITE_CREATE_INDEX +** SQLITE_CREATE_TABLE +** SQLITE_CREATE_TEMP_INDEX +** SQLITE_CREATE_TEMP_TABLE +** SQLITE_CREATE_TEMP_TRIGGER +** SQLITE_CREATE_TEMP_VIEW +** SQLITE_CREATE_TRIGGER +** SQLITE_CREATE_VIEW +** SQLITE_DELETE +** SQLITE_DROP_INDEX +** SQLITE_DROP_TABLE +** SQLITE_DROP_TEMP_INDEX +** SQLITE_DROP_TEMP_TABLE +** SQLITE_DROP_TEMP_TRIGGER +** SQLITE_DROP_TEMP_VIEW +** SQLITE_DROP_TRIGGER +** SQLITE_DROP_VIEW +** SQLITE_INSERT +** SQLITE_PRAGMA +** SQLITE_READ +** SQLITE_SELECT +** SQLITE_TRANSACTION +** SQLITE_UPDATE +** +** The third and fourth arguments to the auth function are the name of +** the table and the column that are being accessed. The auth function +** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If +** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY +** means that the SQL statement will never-run - the sqlite3_exec() call +** will return with an error. SQLITE_IGNORE means that the SQL statement +** should run but attempts to read the specified column will return NULL +** and attempts to write the column will be ignored. +** +** Setting the auth function to NULL disables this hook. The default +** setting of the auth function is NULL. +*/ +int sqlite3_set_authorizer( + sqlite3 *db, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pArg +){ + sqlite3_mutex_enter(db->mutex); + db->xAuth = xAuth; + db->pAuthArg = pArg; + sqlite3ExpirePreparedStatements(db); + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +/* +** Write an error message into pParse->zErrMsg that explains that the +** user-supplied authorization function returned an illegal value. +*/ +static void sqliteAuthBadReturnCode(Parse *pParse){ + sqlite3ErrorMsg(pParse, "authorizer malfunction"); + pParse->rc = SQLITE_ERROR; +} + +/* +** Invoke the authorization callback for permission to read column zCol from +** table zTab in database zDb. This function assumes that an authorization +** callback has been registered (i.e. that sqlite3.xAuth is not NULL). +** +** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed +** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE +** is treated as SQLITE_DENY. In this case an error is left in pParse. +*/ +int sqlite3AuthReadCol( + Parse *pParse, /* The parser context */ + const char *zTab, /* Table name */ + const char *zCol, /* Column name */ + int iDb /* Index of containing database. */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + char *zDb = db->aDb[iDb].zName; /* Name of attached database */ + int rc; /* Auth callback return code */ + + rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext); + if( rc==SQLITE_DENY ){ + if( db->nDb>2 || iDb!=0 ){ + sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol); + }else{ + sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol); + } + pParse->rc = SQLITE_AUTH; + }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){ + sqliteAuthBadReturnCode(pParse); + } + return rc; +} + +/* +** The pExpr should be a TK_COLUMN expression. The table referred to +** is in pTabList or else it is the NEW or OLD table of a trigger. +** Check to see if it is OK to read this particular column. +** +** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN +** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, +** then generate an error. +*/ +void sqlite3AuthRead( + Parse *pParse, /* The parser context */ + Expr *pExpr, /* The expression to check authorization on */ + Schema *pSchema, /* The schema of the expression */ + SrcList *pTabList /* All table that pExpr might refer to */ +){ + sqlite3 *db = pParse->db; + Table *pTab = 0; /* The table being read */ + const char *zCol; /* Name of the column of the table */ + int iSrc; /* Index in pTabList->a[] of table being read */ + int iDb; /* The index of the database the expression refers to */ + int iCol; /* Index of column in table */ + + if( db->xAuth==0 ) return; + iDb = sqlite3SchemaToIndex(pParse->db, pSchema); + if( iDb<0 ){ + /* An attempt to read a column out of a subquery or other + ** temporary table. */ + return; + } + + assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); + if( pExpr->op==TK_TRIGGER ){ + pTab = pParse->pTriggerTab; + }else{ + assert( pTabList ); + for(iSrc=0; ALWAYS(iSrcnSrc); iSrc++){ + if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ + pTab = pTabList->a[iSrc].pTab; + break; + } + } + } + iCol = pExpr->iColumn; + if( NEVER(pTab==0) ) return; + + if( iCol>=0 ){ + assert( iColnCol ); + zCol = pTab->aCol[iCol].zName; + }else if( pTab->iPKey>=0 ){ + assert( pTab->iPKeynCol ); + zCol = pTab->aCol[pTab->iPKey].zName; + }else{ + zCol = "ROWID"; + } + assert( iDb>=0 && iDbnDb ); + if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ + pExpr->op = TK_NULL; + } +} + +/* +** Do an authorization check using the code and arguments given. Return +** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY +** is returned, then the error count and error message in pParse are +** modified appropriately. +*/ +int sqlite3AuthCheck( + Parse *pParse, + int code, + const char *zArg1, + const char *zArg2, + const char *zArg3 +){ + sqlite3 *db = pParse->db; + int rc; + + /* Don't do any authorization checks if the database is initialising + ** or if the parser is being invoked from within sqlite3_declare_vtab. + */ + if( db->init.busy || IN_DECLARE_VTAB ){ + return SQLITE_OK; + } + + if( db->xAuth==0 ){ + return SQLITE_OK; + } + rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext); + if( rc==SQLITE_DENY ){ + sqlite3ErrorMsg(pParse, "not authorized"); + pParse->rc = SQLITE_AUTH; + }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ + rc = SQLITE_DENY; + sqliteAuthBadReturnCode(pParse); + } + return rc; +} + +/* +** Push an authorization context. After this routine is called, the +** zArg3 argument to authorization callbacks will be zContext until +** popped. Or if pParse==0, this routine is a no-op. +*/ +void sqlite3AuthContextPush( + Parse *pParse, + AuthContext *pContext, + const char *zContext +){ + assert( pParse ); + pContext->pParse = pParse; + pContext->zAuthContext = pParse->zAuthContext; + pParse->zAuthContext = zContext; +} + +/* +** Pop an authorization context that was previously pushed +** by sqlite3AuthContextPush +*/ +void sqlite3AuthContextPop(AuthContext *pContext){ + if( pContext->pParse ){ + pContext->pParse->zAuthContext = pContext->zAuthContext; + pContext->pParse = 0; + } +} + +#endif /* SQLITE_OMIT_AUTHORIZATION */ diff --git a/components/external/SQLite-3.8.1/src/backup.c b/components/external/SQLite-3.8.1/src/backup.c new file mode 100644 index 0000000000000000000000000000000000000000..afbaeeb10971dbaefe277e6f9c7ae9f62cb9cb73 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/backup.c @@ -0,0 +1,747 @@ +/* +** 2009 January 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the implementation of the sqlite3_backup_XXX() +** API functions and the related features. +*/ +#include "sqliteInt.h" +#include "btreeInt.h" + +/* +** Structure allocated for each backup operation. +*/ +struct sqlite3_backup { + sqlite3* pDestDb; /* Destination database handle */ + Btree *pDest; /* Destination b-tree file */ + u32 iDestSchema; /* Original schema cookie in destination */ + int bDestLocked; /* True once a write-transaction is open on pDest */ + + Pgno iNext; /* Page number of the next source page to copy */ + sqlite3* pSrcDb; /* Source database handle */ + Btree *pSrc; /* Source b-tree file */ + + int rc; /* Backup process error code */ + + /* These two variables are set by every call to backup_step(). They are + ** read by calls to backup_remaining() and backup_pagecount(). + */ + Pgno nRemaining; /* Number of pages left to copy */ + Pgno nPagecount; /* Total number of pages to copy */ + + int isAttached; /* True once backup has been registered with pager */ + sqlite3_backup *pNext; /* Next backup associated with source pager */ +}; + +/* +** THREAD SAFETY NOTES: +** +** Once it has been created using backup_init(), a single sqlite3_backup +** structure may be accessed via two groups of thread-safe entry points: +** +** * Via the sqlite3_backup_XXX() API function backup_step() and +** backup_finish(). Both these functions obtain the source database +** handle mutex and the mutex associated with the source BtShared +** structure, in that order. +** +** * Via the BackupUpdate() and BackupRestart() functions, which are +** invoked by the pager layer to report various state changes in +** the page cache associated with the source database. The mutex +** associated with the source database BtShared structure will always +** be held when either of these functions are invoked. +** +** The other sqlite3_backup_XXX() API functions, backup_remaining() and +** backup_pagecount() are not thread-safe functions. If they are called +** while some other thread is calling backup_step() or backup_finish(), +** the values returned may be invalid. There is no way for a call to +** BackupUpdate() or BackupRestart() to interfere with backup_remaining() +** or backup_pagecount(). +** +** Depending on the SQLite configuration, the database handles and/or +** the Btree objects may have their own mutexes that require locking. +** Non-sharable Btrees (in-memory databases for example), do not have +** associated mutexes. +*/ + +/* +** Return a pointer corresponding to database zDb (i.e. "main", "temp") +** in connection handle pDb. If such a database cannot be found, return +** a NULL pointer and write an error message to pErrorDb. +** +** If the "temp" database is requested, it may need to be opened by this +** function. If an error occurs while doing so, return 0 and write an +** error message to pErrorDb. +*/ +static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ + int i = sqlite3FindDbName(pDb, zDb); + + if( i==1 ){ + Parse *pParse; + int rc = 0; + pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse)); + if( pParse==0 ){ + sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory"); + rc = SQLITE_NOMEM; + }else{ + pParse->db = pDb; + if( sqlite3OpenTempDatabase(pParse) ){ + sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg); + rc = SQLITE_ERROR; + } + sqlite3DbFree(pErrorDb, pParse->zErrMsg); + sqlite3StackFree(pErrorDb, pParse); + } + if( rc ){ + return 0; + } + } + + if( i<0 ){ + sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb); + return 0; + } + + return pDb->aDb[i].pBt; +} + +/* +** Attempt to set the page size of the destination to match the page size +** of the source. +*/ +static int setDestPgsz(sqlite3_backup *p){ + int rc; + rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0); + return rc; +} + +/* +** Create an sqlite3_backup process to copy the contents of zSrcDb from +** connection handle pSrcDb to zDestDb in pDestDb. If successful, return +** a pointer to the new sqlite3_backup object. +** +** If an error occurs, NULL is returned and an error code and error message +** stored in database handle pDestDb. +*/ +sqlite3_backup *sqlite3_backup_init( + sqlite3* pDestDb, /* Database to write to */ + const char *zDestDb, /* Name of database within pDestDb */ + sqlite3* pSrcDb, /* Database connection to read from */ + const char *zSrcDb /* Name of database within pSrcDb */ +){ + sqlite3_backup *p; /* Value to return */ + + /* Lock the source database handle. The destination database + ** handle is not locked in this routine, but it is locked in + ** sqlite3_backup_step(). The user is required to ensure that no + ** other thread accesses the destination handle for the duration + ** of the backup operation. Any attempt to use the destination + ** database connection while a backup is in progress may cause + ** a malfunction or a deadlock. + */ + sqlite3_mutex_enter(pSrcDb->mutex); + sqlite3_mutex_enter(pDestDb->mutex); + + if( pSrcDb==pDestDb ){ + sqlite3Error( + pDestDb, SQLITE_ERROR, "source and destination must be distinct" + ); + p = 0; + }else { + /* Allocate space for a new sqlite3_backup object... + ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a + ** call to sqlite3_backup_init() and is destroyed by a call to + ** sqlite3_backup_finish(). */ + p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup)); + if( !p ){ + sqlite3Error(pDestDb, SQLITE_NOMEM, 0); + } + } + + /* If the allocation succeeded, populate the new object. */ + if( p ){ + p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb); + p->pDest = findBtree(pDestDb, pDestDb, zDestDb); + p->pDestDb = pDestDb; + p->pSrcDb = pSrcDb; + p->iNext = 1; + p->isAttached = 0; + + if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){ + /* One (or both) of the named databases did not exist or an OOM + ** error was hit. The error has already been written into the + ** pDestDb handle. All that is left to do here is free the + ** sqlite3_backup structure. + */ + sqlite3_free(p); + p = 0; + } + } + if( p ){ + p->pSrc->nBackup++; + } + + sqlite3_mutex_leave(pDestDb->mutex); + sqlite3_mutex_leave(pSrcDb->mutex); + return p; +} + +/* +** Argument rc is an SQLite error code. Return true if this error is +** considered fatal if encountered during a backup operation. All errors +** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED. +*/ +static int isFatalError(int rc){ + return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED)); +} + +/* +** Parameter zSrcData points to a buffer containing the data for +** page iSrcPg from the source database. Copy this data into the +** destination database. +*/ +static int backupOnePage( + sqlite3_backup *p, /* Backup handle */ + Pgno iSrcPg, /* Source database page to backup */ + const u8 *zSrcData, /* Source database page data */ + int bUpdate /* True for an update, false otherwise */ +){ + Pager * const pDestPager = sqlite3BtreePager(p->pDest); + const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc); + int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest); + const int nCopy = MIN(nSrcPgsz, nDestPgsz); + const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz; +#ifdef SQLITE_HAS_CODEC + /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is + ** guaranteed that the shared-mutex is held by this thread, handle + ** p->pSrc may not actually be the owner. */ + int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc); + int nDestReserve = sqlite3BtreeGetReserve(p->pDest); +#endif + int rc = SQLITE_OK; + i64 iOff; + + assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 ); + assert( p->bDestLocked ); + assert( !isFatalError(p->rc) ); + assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ); + assert( zSrcData ); + + /* Catch the case where the destination is an in-memory database and the + ** page sizes of the source and destination differ. + */ + if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){ + rc = SQLITE_READONLY; + } + +#ifdef SQLITE_HAS_CODEC + /* Backup is not possible if the page size of the destination is changing + ** and a codec is in use. + */ + if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){ + rc = SQLITE_READONLY; + } + + /* Backup is not possible if the number of bytes of reserve space differ + ** between source and destination. If there is a difference, try to + ** fix the destination to agree with the source. If that is not possible, + ** then the backup cannot proceed. + */ + if( nSrcReserve!=nDestReserve ){ + u32 newPgsz = nSrcPgsz; + rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve); + if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY; + } +#endif + + /* This loop runs once for each destination page spanned by the source + ** page. For each iteration, variable iOff is set to the byte offset + ** of the destination page. + */ + for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOffpDest->pBt) ) continue; + if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg)) + && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg)) + ){ + const u8 *zIn = &zSrcData[iOff%nSrcPgsz]; + u8 *zDestData = sqlite3PagerGetData(pDestPg); + u8 *zOut = &zDestData[iOff%nDestPgsz]; + + /* Copy the data from the source page into the destination page. + ** Then clear the Btree layer MemPage.isInit flag. Both this module + ** and the pager code use this trick (clearing the first byte + ** of the page 'extra' space to invalidate the Btree layers + ** cached parse of the page). MemPage.isInit is marked + ** "MUST BE FIRST" for this purpose. + */ + memcpy(zOut, zIn, nCopy); + ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0; + if( iOff==0 && bUpdate==0 ){ + sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc)); + } + } + sqlite3PagerUnref(pDestPg); + } + + return rc; +} + +/* +** If pFile is currently larger than iSize bytes, then truncate it to +** exactly iSize bytes. If pFile is not larger than iSize bytes, then +** this function is a no-op. +** +** Return SQLITE_OK if everything is successful, or an SQLite error +** code if an error occurs. +*/ +static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){ + i64 iCurrent; + int rc = sqlite3OsFileSize(pFile, &iCurrent); + if( rc==SQLITE_OK && iCurrent>iSize ){ + rc = sqlite3OsTruncate(pFile, iSize); + } + return rc; +} + +/* +** Register this backup object with the associated source pager for +** callbacks when pages are changed or the cache invalidated. +*/ +static void attachBackupObject(sqlite3_backup *p){ + sqlite3_backup **pp; + assert( sqlite3BtreeHoldsMutex(p->pSrc) ); + pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); + p->pNext = *pp; + *pp = p; + p->isAttached = 1; +} + +/* +** Copy nPage pages from the source b-tree to the destination. +*/ +int sqlite3_backup_step(sqlite3_backup *p, int nPage){ + int rc; + int destMode; /* Destination journal mode */ + int pgszSrc = 0; /* Source page size */ + int pgszDest = 0; /* Destination page size */ + + sqlite3_mutex_enter(p->pSrcDb->mutex); + sqlite3BtreeEnter(p->pSrc); + if( p->pDestDb ){ + sqlite3_mutex_enter(p->pDestDb->mutex); + } + + rc = p->rc; + if( !isFatalError(rc) ){ + Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */ + Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */ + int ii; /* Iterator variable */ + int nSrcPage = -1; /* Size of source db in pages */ + int bCloseTrans = 0; /* True if src db requires unlocking */ + + /* If the source pager is currently in a write-transaction, return + ** SQLITE_BUSY immediately. + */ + if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){ + rc = SQLITE_BUSY; + }else{ + rc = SQLITE_OK; + } + + /* Lock the destination database, if it is not locked already. */ + if( SQLITE_OK==rc && p->bDestLocked==0 + && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) + ){ + p->bDestLocked = 1; + sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema); + } + + /* If there is no open read-transaction on the source database, open + ** one now. If a transaction is opened here, then it will be closed + ** before this function exits. + */ + if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){ + rc = sqlite3BtreeBeginTrans(p->pSrc, 0); + bCloseTrans = 1; + } + + /* Do not allow backup if the destination database is in WAL mode + ** and the page sizes are different between source and destination */ + pgszSrc = sqlite3BtreeGetPageSize(p->pSrc); + pgszDest = sqlite3BtreeGetPageSize(p->pDest); + destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest)); + if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){ + rc = SQLITE_READONLY; + } + + /* Now that there is a read-lock on the source database, query the + ** source pager for the number of pages in the database. + */ + nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc); + assert( nSrcPage>=0 ); + for(ii=0; (nPage<0 || iiiNext<=(Pgno)nSrcPage && !rc; ii++){ + const Pgno iSrcPg = p->iNext; /* Source page number */ + if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){ + DbPage *pSrcPg; /* Source page object */ + rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg, + PAGER_GET_READONLY); + if( rc==SQLITE_OK ){ + rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0); + sqlite3PagerUnref(pSrcPg); + } + } + p->iNext++; + } + if( rc==SQLITE_OK ){ + p->nPagecount = nSrcPage; + p->nRemaining = nSrcPage+1-p->iNext; + if( p->iNext>(Pgno)nSrcPage ){ + rc = SQLITE_DONE; + }else if( !p->isAttached ){ + attachBackupObject(p); + } + } + + /* Update the schema version field in the destination database. This + ** is to make sure that the schema-version really does change in + ** the case where the source and destination databases have the + ** same schema version. + */ + if( rc==SQLITE_DONE ){ + if( nSrcPage==0 ){ + rc = sqlite3BtreeNewDb(p->pDest); + nSrcPage = 1; + } + if( rc==SQLITE_OK || rc==SQLITE_DONE ){ + rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1); + } + if( rc==SQLITE_OK ){ + if( p->pDestDb ){ + sqlite3ResetAllSchemasOfConnection(p->pDestDb); + } + if( destMode==PAGER_JOURNALMODE_WAL ){ + rc = sqlite3BtreeSetVersion(p->pDest, 2); + } + } + if( rc==SQLITE_OK ){ + int nDestTruncate; + /* Set nDestTruncate to the final number of pages in the destination + ** database. The complication here is that the destination page + ** size may be different to the source page size. + ** + ** If the source page size is smaller than the destination page size, + ** round up. In this case the call to sqlite3OsTruncate() below will + ** fix the size of the file. However it is important to call + ** sqlite3PagerTruncateImage() here so that any pages in the + ** destination file that lie beyond the nDestTruncate page mark are + ** journalled by PagerCommitPhaseOne() before they are destroyed + ** by the file truncation. + */ + assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) ); + assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) ); + if( pgszSrcpDest->pBt) ){ + nDestTruncate--; + } + }else{ + nDestTruncate = nSrcPage * (pgszSrc/pgszDest); + } + assert( nDestTruncate>0 ); + + if( pgszSrc= iSize || ( + nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1) + && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest + )); + + /* This block ensures that all data required to recreate the original + ** database has been stored in the journal for pDestPager and the + ** journal synced to disk. So at this point we may safely modify + ** the database file in any way, knowing that if a power failure + ** occurs, the original database will be reconstructed from the + ** journal file. */ + sqlite3PagerPagecount(pDestPager, &nDstPage); + for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){ + if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){ + DbPage *pPg; + rc = sqlite3PagerGet(pDestPager, iPg, &pPg); + if( rc==SQLITE_OK ){ + rc = sqlite3PagerWrite(pPg); + sqlite3PagerUnref(pPg); + } + } + } + if( rc==SQLITE_OK ){ + rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1); + } + + /* Write the extra pages and truncate the database file as required */ + iEnd = MIN(PENDING_BYTE + pgszDest, iSize); + for( + iOff=PENDING_BYTE+pgszSrc; + rc==SQLITE_OK && iOffpDest, 0)) + ){ + rc = SQLITE_DONE; + } + } + } + + /* If bCloseTrans is true, then this function opened a read transaction + ** on the source database. Close the read transaction here. There is + ** no need to check the return values of the btree methods here, as + ** "committing" a read-only transaction cannot fail. + */ + if( bCloseTrans ){ + TESTONLY( int rc2 ); + TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0); + TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0); + assert( rc2==SQLITE_OK ); + } + + if( rc==SQLITE_IOERR_NOMEM ){ + rc = SQLITE_NOMEM; + } + p->rc = rc; + } + if( p->pDestDb ){ + sqlite3_mutex_leave(p->pDestDb->mutex); + } + sqlite3BtreeLeave(p->pSrc); + sqlite3_mutex_leave(p->pSrcDb->mutex); + return rc; +} + +/* +** Release all resources associated with an sqlite3_backup* handle. +*/ +int sqlite3_backup_finish(sqlite3_backup *p){ + sqlite3_backup **pp; /* Ptr to head of pagers backup list */ + sqlite3 *pSrcDb; /* Source database connection */ + int rc; /* Value to return */ + + /* Enter the mutexes */ + if( p==0 ) return SQLITE_OK; + pSrcDb = p->pSrcDb; + sqlite3_mutex_enter(pSrcDb->mutex); + sqlite3BtreeEnter(p->pSrc); + if( p->pDestDb ){ + sqlite3_mutex_enter(p->pDestDb->mutex); + } + + /* Detach this backup from the source pager. */ + if( p->pDestDb ){ + p->pSrc->nBackup--; + } + if( p->isAttached ){ + pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); + while( *pp!=p ){ + pp = &(*pp)->pNext; + } + *pp = p->pNext; + } + + /* If a transaction is still open on the Btree, roll it back. */ + sqlite3BtreeRollback(p->pDest, SQLITE_OK); + + /* Set the error code of the destination database handle. */ + rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc; + sqlite3Error(p->pDestDb, rc, 0); + + /* Exit the mutexes and free the backup context structure. */ + if( p->pDestDb ){ + sqlite3LeaveMutexAndCloseZombie(p->pDestDb); + } + sqlite3BtreeLeave(p->pSrc); + if( p->pDestDb ){ + /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a + ** call to sqlite3_backup_init() and is destroyed by a call to + ** sqlite3_backup_finish(). */ + sqlite3_free(p); + } + sqlite3LeaveMutexAndCloseZombie(pSrcDb); + return rc; +} + +/* +** Return the number of pages still to be backed up as of the most recent +** call to sqlite3_backup_step(). +*/ +int sqlite3_backup_remaining(sqlite3_backup *p){ + return p->nRemaining; +} + +/* +** Return the total number of pages in the source database as of the most +** recent call to sqlite3_backup_step(). +*/ +int sqlite3_backup_pagecount(sqlite3_backup *p){ + return p->nPagecount; +} + +/* +** This function is called after the contents of page iPage of the +** source database have been modified. If page iPage has already been +** copied into the destination database, then the data written to the +** destination is now invalidated. The destination copy of iPage needs +** to be updated with the new data before the backup operation is +** complete. +** +** It is assumed that the mutex associated with the BtShared object +** corresponding to the source database is held when this function is +** called. +*/ +void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){ + sqlite3_backup *p; /* Iterator variable */ + for(p=pBackup; p; p=p->pNext){ + assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); + if( !isFatalError(p->rc) && iPageiNext ){ + /* The backup process p has already copied page iPage. But now it + ** has been modified by a transaction on the source pager. Copy + ** the new data into the backup. + */ + int rc; + assert( p->pDestDb ); + sqlite3_mutex_enter(p->pDestDb->mutex); + rc = backupOnePage(p, iPage, aData, 1); + sqlite3_mutex_leave(p->pDestDb->mutex); + assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED ); + if( rc!=SQLITE_OK ){ + p->rc = rc; + } + } + } +} + +/* +** Restart the backup process. This is called when the pager layer +** detects that the database has been modified by an external database +** connection. In this case there is no way of knowing which of the +** pages that have been copied into the destination database are still +** valid and which are not, so the entire process needs to be restarted. +** +** It is assumed that the mutex associated with the BtShared object +** corresponding to the source database is held when this function is +** called. +*/ +void sqlite3BackupRestart(sqlite3_backup *pBackup){ + sqlite3_backup *p; /* Iterator variable */ + for(p=pBackup; p; p=p->pNext){ + assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); + p->iNext = 1; + } +} + +#ifndef SQLITE_OMIT_VACUUM +/* +** Copy the complete content of pBtFrom into pBtTo. A transaction +** must be active for both files. +** +** The size of file pTo may be reduced by this operation. If anything +** goes wrong, the transaction on pTo is rolled back. If successful, the +** transaction is committed before returning. +*/ +int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){ + int rc; + sqlite3_file *pFd; /* File descriptor for database pTo */ + sqlite3_backup b; + sqlite3BtreeEnter(pTo); + sqlite3BtreeEnter(pFrom); + + assert( sqlite3BtreeIsInTrans(pTo) ); + pFd = sqlite3PagerFile(sqlite3BtreePager(pTo)); + if( pFd->pMethods ){ + i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom); + rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte); + if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; + if( rc ) goto copy_finished; + } + + /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set + ** to 0. This is used by the implementations of sqlite3_backup_step() + ** and sqlite3_backup_finish() to detect that they are being called + ** from this function, not directly by the user. + */ + memset(&b, 0, sizeof(b)); + b.pSrcDb = pFrom->db; + b.pSrc = pFrom; + b.pDest = pTo; + b.iNext = 1; + + /* 0x7FFFFFFF is the hard limit for the number of pages in a database + ** file. By passing this as the number of pages to copy to + ** sqlite3_backup_step(), we can guarantee that the copy finishes + ** within a single call (unless an error occurs). The assert() statement + ** checks this assumption - (p->rc) should be set to either SQLITE_DONE + ** or an error code. + */ + sqlite3_backup_step(&b, 0x7FFFFFFF); + assert( b.rc!=SQLITE_OK ); + rc = sqlite3_backup_finish(&b); + if( rc==SQLITE_OK ){ + pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; + }else{ + sqlite3PagerClearCache(sqlite3BtreePager(b.pDest)); + } + + assert( sqlite3BtreeIsInTrans(pTo)==0 ); +copy_finished: + sqlite3BtreeLeave(pFrom); + sqlite3BtreeLeave(pTo); + return rc; +} +#endif /* SQLITE_OMIT_VACUUM */ diff --git a/components/external/SQLite-3.8.1/src/bitvec.c b/components/external/SQLite-3.8.1/src/bitvec.c new file mode 100644 index 0000000000000000000000000000000000000000..52184aa964ce1898f35d1b3d87871c2d0ef4c53d --- /dev/null +++ b/components/external/SQLite-3.8.1/src/bitvec.c @@ -0,0 +1,407 @@ +/* +** 2008 February 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements an object that represents a fixed-length +** bitmap. Bits are numbered starting with 1. +** +** A bitmap is used to record which pages of a database file have been +** journalled during a transaction, or which pages have the "dont-write" +** property. Usually only a few pages are meet either condition. +** So the bitmap is usually sparse and has low cardinality. +** But sometimes (for example when during a DROP of a large table) most +** or all of the pages in a database can get journalled. In those cases, +** the bitmap becomes dense with high cardinality. The algorithm needs +** to handle both cases well. +** +** The size of the bitmap is fixed when the object is created. +** +** All bits are clear when the bitmap is created. Individual bits +** may be set or cleared one at a time. +** +** Test operations are about 100 times more common that set operations. +** Clear operations are exceedingly rare. There are usually between +** 5 and 500 set operations per Bitvec object, though the number of sets can +** sometimes grow into tens of thousands or larger. The size of the +** Bitvec object is the number of pages in the database file at the +** start of a transaction, and is thus usually less than a few thousand, +** but can be as large as 2 billion for a really big database. +*/ +#include "sqliteInt.h" + +/* Size of the Bitvec structure in bytes. */ +#define BITVEC_SZ 512 + +/* Round the union size down to the nearest pointer boundary, since that's how +** it will be aligned within the Bitvec struct. */ +#define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) + +/* Type of the array "element" for the bitmap representation. +** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. +** Setting this to the "natural word" size of your CPU may improve +** performance. */ +#define BITVEC_TELEM u8 +/* Size, in bits, of the bitmap element. */ +#define BITVEC_SZELEM 8 +/* Number of elements in a bitmap array. */ +#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM)) +/* Number of bits in the bitmap array. */ +#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM) + +/* Number of u32 values in hash table. */ +#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32)) +/* Maximum number of entries in hash table before +** sub-dividing and re-hashing. */ +#define BITVEC_MXHASH (BITVEC_NINT/2) +/* Hashing function for the aHash representation. +** Empirical testing showed that the *37 multiplier +** (an arbitrary prime)in the hash function provided +** no fewer collisions than the no-op *1. */ +#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT) + +#define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *)) + + +/* +** A bitmap is an instance of the following structure. +** +** This bitmap records the existence of zero or more bits +** with values between 1 and iSize, inclusive. +** +** There are three possible representations of the bitmap. +** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight +** bitmap. The least significant bit is bit 1. +** +** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is +** a hash table that will hold up to BITVEC_MXHASH distinct values. +** +** Otherwise, the value i is redirected into one of BITVEC_NPTR +** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap +** handles up to iDivisor separate values of i. apSub[0] holds +** values between 1 and iDivisor. apSub[1] holds values between +** iDivisor+1 and 2*iDivisor. apSub[N] holds values between +** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized +** to hold deal with values between 1 and iDivisor. +*/ +struct Bitvec { + u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */ + u32 nSet; /* Number of bits that are set - only valid for aHash + ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512, + ** this would be 125. */ + u32 iDivisor; /* Number of bits handled by each apSub[] entry. */ + /* Should >=0 for apSub element. */ + /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */ + /* For a BITVEC_SZ of 512, this would be 34,359,739. */ + union { + BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */ + u32 aHash[BITVEC_NINT]; /* Hash table representation */ + Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */ + } u; +}; + +/* +** Create a new bitmap object able to handle bits between 0 and iSize, +** inclusive. Return a pointer to the new object. Return NULL if +** malloc fails. +*/ +Bitvec *sqlite3BitvecCreate(u32 iSize){ + Bitvec *p; + assert( sizeof(*p)==BITVEC_SZ ); + p = sqlite3MallocZero( sizeof(*p) ); + if( p ){ + p->iSize = iSize; + } + return p; +} + +/* +** Check to see if the i-th bit is set. Return true or false. +** If p is NULL (if the bitmap has not been created) or if +** i is out of range, then return false. +*/ +int sqlite3BitvecTest(Bitvec *p, u32 i){ + if( p==0 ) return 0; + if( i>p->iSize || i==0 ) return 0; + i--; + while( p->iDivisor ){ + u32 bin = i/p->iDivisor; + i = i%p->iDivisor; + p = p->u.apSub[bin]; + if (!p) { + return 0; + } + } + if( p->iSize<=BITVEC_NBIT ){ + return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0; + } else{ + u32 h = BITVEC_HASH(i++); + while( p->u.aHash[h] ){ + if( p->u.aHash[h]==i ) return 1; + h = (h+1) % BITVEC_NINT; + } + return 0; + } +} + +/* +** Set the i-th bit. Return 0 on success and an error code if +** anything goes wrong. +** +** This routine might cause sub-bitmaps to be allocated. Failing +** to get the memory needed to hold the sub-bitmap is the only +** that can go wrong with an insert, assuming p and i are valid. +** +** The calling function must ensure that p is a valid Bitvec object +** and that the value for "i" is within range of the Bitvec object. +** Otherwise the behavior is undefined. +*/ +int sqlite3BitvecSet(Bitvec *p, u32 i){ + u32 h; + if( p==0 ) return SQLITE_OK; + assert( i>0 ); + assert( i<=p->iSize ); + i--; + while((p->iSize > BITVEC_NBIT) && p->iDivisor) { + u32 bin = i/p->iDivisor; + i = i%p->iDivisor; + if( p->u.apSub[bin]==0 ){ + p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor ); + if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM; + } + p = p->u.apSub[bin]; + } + if( p->iSize<=BITVEC_NBIT ){ + p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1)); + return SQLITE_OK; + } + h = BITVEC_HASH(i++); + /* if there wasn't a hash collision, and this doesn't */ + /* completely fill the hash, then just add it without */ + /* worring about sub-dividing and re-hashing. */ + if( !p->u.aHash[h] ){ + if (p->nSet<(BITVEC_NINT-1)) { + goto bitvec_set_end; + } else { + goto bitvec_set_rehash; + } + } + /* there was a collision, check to see if it's already */ + /* in hash, if not, try to find a spot for it */ + do { + if( p->u.aHash[h]==i ) return SQLITE_OK; + h++; + if( h>=BITVEC_NINT ) h = 0; + } while( p->u.aHash[h] ); + /* we didn't find it in the hash. h points to the first */ + /* available free spot. check to see if this is going to */ + /* make our hash too "full". */ +bitvec_set_rehash: + if( p->nSet>=BITVEC_MXHASH ){ + unsigned int j; + int rc; + u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash)); + if( aiValues==0 ){ + return SQLITE_NOMEM; + }else{ + memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); + memset(p->u.apSub, 0, sizeof(p->u.apSub)); + p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR; + rc = sqlite3BitvecSet(p, i); + for(j=0; jnSet++; + p->u.aHash[h] = i; + return SQLITE_OK; +} + +/* +** Clear the i-th bit. +** +** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage +** that BitvecClear can use to rebuilt its hash table. +*/ +void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ + if( p==0 ) return; + assert( i>0 ); + i--; + while( p->iDivisor ){ + u32 bin = i/p->iDivisor; + i = i%p->iDivisor; + p = p->u.apSub[bin]; + if (!p) { + return; + } + } + if( p->iSize<=BITVEC_NBIT ){ + p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1))); + }else{ + unsigned int j; + u32 *aiValues = pBuf; + memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); + memset(p->u.aHash, 0, sizeof(p->u.aHash)); + p->nSet = 0; + for(j=0; jnSet++; + while( p->u.aHash[h] ){ + h++; + if( h>=BITVEC_NINT ) h = 0; + } + p->u.aHash[h] = aiValues[j]; + } + } + } +} + +/* +** Destroy a bitmap object. Reclaim all memory used. +*/ +void sqlite3BitvecDestroy(Bitvec *p){ + if( p==0 ) return; + if( p->iDivisor ){ + unsigned int i; + for(i=0; iu.apSub[i]); + } + } + sqlite3_free(p); +} + +/* +** Return the value of the iSize parameter specified when Bitvec *p +** was created. +*/ +u32 sqlite3BitvecSize(Bitvec *p){ + return p->iSize; +} + +#ifndef SQLITE_OMIT_BUILTIN_TEST +/* +** Let V[] be an array of unsigned characters sufficient to hold +** up to N bits. Let I be an integer between 0 and N. 0<=I>3] |= (1<<(I&7)) +#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7)) +#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0 + +/* +** This routine runs an extensive test of the Bitvec code. +** +** The input is an array of integers that acts as a program +** to test the Bitvec. The integers are opcodes followed +** by 0, 1, or 3 operands, depending on the opcode. Another +** opcode follows immediately after the last operand. +** +** There are 6 opcodes numbered from 0 through 5. 0 is the +** "halt" opcode and causes the test to end. +** +** 0 Halt and return the number of errors +** 1 N S X Set N bits beginning with S and incrementing by X +** 2 N S X Clear N bits beginning with S and incrementing by X +** 3 N Set N randomly chosen bits +** 4 N Clear N randomly chosen bits +** 5 N S X Set N bits from S increment X in array only, not in bitvec +** +** The opcodes 1 through 4 perform set and clear operations are performed +** on both a Bitvec object and on a linear array of bits obtained from malloc. +** Opcode 5 works on the linear array only, not on the Bitvec. +** Opcode 5 is used to deliberately induce a fault in order to +** confirm that error detection works. +** +** At the conclusion of the test the linear array is compared +** against the Bitvec object. If there are any differences, +** an error is returned. If they are the same, zero is returned. +** +** If a memory allocation error occurs, return -1. +*/ +int sqlite3BitvecBuiltinTest(int sz, int *aOp){ + Bitvec *pBitvec = 0; + unsigned char *pV = 0; + int rc = -1; + int i, nx, pc, op; + void *pTmpSpace; + + /* Allocate the Bitvec to be tested and a linear array of + ** bits to act as the reference */ + pBitvec = sqlite3BitvecCreate( sz ); + pV = sqlite3MallocZero( (sz+7)/8 + 1 ); + pTmpSpace = sqlite3_malloc(BITVEC_SZ); + if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end; + + /* NULL pBitvec tests */ + sqlite3BitvecSet(0, 1); + sqlite3BitvecClear(0, 1, pTmpSpace); + + /* Run the program */ + pc = 0; + while( (op = aOp[pc])!=0 ){ + switch( op ){ + case 1: + case 2: + case 5: { + nx = 4; + i = aOp[pc+2] - 1; + aOp[pc+2] += aOp[pc+3]; + break; + } + case 3: + case 4: + default: { + nx = 2; + sqlite3_randomness(sizeof(i), &i); + break; + } + } + if( (--aOp[pc+1]) > 0 ) nx = 0; + pc += nx; + i = (i & 0x7fffffff)%sz; + if( (op & 1)!=0 ){ + SETBIT(pV, (i+1)); + if( op!=5 ){ + if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end; + } + }else{ + CLEARBIT(pV, (i+1)); + sqlite3BitvecClear(pBitvec, i+1, pTmpSpace); + } + } + + /* Test to make sure the linear array exactly matches the + ** Bitvec object. Start with the assumption that they do + ** match (rc==0). Change rc to non-zero if a discrepancy + ** is found. + */ + rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1) + + sqlite3BitvecTest(pBitvec, 0) + + (sqlite3BitvecSize(pBitvec) - sz); + for(i=1; i<=sz; i++){ + if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){ + rc = i; + break; + } + } + + /* Free allocated structure */ +bitvec_end: + sqlite3_free(pTmpSpace); + sqlite3_free(pV); + sqlite3BitvecDestroy(pBitvec); + return rc; +} +#endif /* SQLITE_OMIT_BUILTIN_TEST */ diff --git a/components/external/SQLite-3.8.1/src/btmutex.c b/components/external/SQLite-3.8.1/src/btmutex.c new file mode 100644 index 0000000000000000000000000000000000000000..d87d4d5feeb6307aecdc9a83111489ab30c678c3 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/btmutex.c @@ -0,0 +1,287 @@ +/* +** 2007 August 27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used to implement mutexes on Btree objects. +** This code really belongs in btree.c. But btree.c is getting too +** big and we want to break it down some. This packaged seemed like +** a good breakout. +*/ +#include "btreeInt.h" +#ifndef SQLITE_OMIT_SHARED_CACHE +#if SQLITE_THREADSAFE + +/* +** Obtain the BtShared mutex associated with B-Tree handle p. Also, +** set BtShared.db to the database handle associated with p and the +** p->locked boolean to true. +*/ +static void lockBtreeMutex(Btree *p){ + assert( p->locked==0 ); + assert( sqlite3_mutex_notheld(p->pBt->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); + + sqlite3_mutex_enter(p->pBt->mutex); + p->pBt->db = p->db; + p->locked = 1; +} + +/* +** Release the BtShared mutex associated with B-Tree handle p and +** clear the p->locked boolean. +*/ +static void unlockBtreeMutex(Btree *p){ + BtShared *pBt = p->pBt; + assert( p->locked==1 ); + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); + assert( p->db==pBt->db ); + + sqlite3_mutex_leave(pBt->mutex); + p->locked = 0; +} + +/* +** Enter a mutex on the given BTree object. +** +** If the object is not sharable, then no mutex is ever required +** and this routine is a no-op. The underlying mutex is non-recursive. +** But we keep a reference count in Btree.wantToLock so the behavior +** of this interface is recursive. +** +** To avoid deadlocks, multiple Btrees are locked in the same order +** by all database connections. The p->pNext is a list of other +** Btrees belonging to the same database connection as the p Btree +** which need to be locked after p. If we cannot get a lock on +** p, then first unlock all of the others on p->pNext, then wait +** for the lock to become available on p, then relock all of the +** subsequent Btrees that desire a lock. +*/ +void sqlite3BtreeEnter(Btree *p){ + Btree *pLater; + + /* Some basic sanity checking on the Btree. The list of Btrees + ** connected by pNext and pPrev should be in sorted order by + ** Btree.pBt value. All elements of the list should belong to + ** the same connection. Only shared Btrees are on the list. */ + assert( p->pNext==0 || p->pNext->pBt>p->pBt ); + assert( p->pPrev==0 || p->pPrev->pBtpBt ); + assert( p->pNext==0 || p->pNext->db==p->db ); + assert( p->pPrev==0 || p->pPrev->db==p->db ); + assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); + + /* Check for locking consistency */ + assert( !p->locked || p->wantToLock>0 ); + assert( p->sharable || p->wantToLock==0 ); + + /* We should already hold a lock on the database connection */ + assert( sqlite3_mutex_held(p->db->mutex) ); + + /* Unless the database is sharable and unlocked, then BtShared.db + ** should already be set correctly. */ + assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db ); + + if( !p->sharable ) return; + p->wantToLock++; + if( p->locked ) return; + + /* In most cases, we should be able to acquire the lock we + ** want without having to go throught the ascending lock + ** procedure that follows. Just be sure not to block. + */ + if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ + p->pBt->db = p->db; + p->locked = 1; + return; + } + + /* To avoid deadlock, first release all locks with a larger + ** BtShared address. Then acquire our lock. Then reacquire + ** the other BtShared locks that we used to hold in ascending + ** order. + */ + for(pLater=p->pNext; pLater; pLater=pLater->pNext){ + assert( pLater->sharable ); + assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt ); + assert( !pLater->locked || pLater->wantToLock>0 ); + if( pLater->locked ){ + unlockBtreeMutex(pLater); + } + } + lockBtreeMutex(p); + for(pLater=p->pNext; pLater; pLater=pLater->pNext){ + if( pLater->wantToLock ){ + lockBtreeMutex(pLater); + } + } +} + +/* +** Exit the recursive mutex on a Btree. +*/ +void sqlite3BtreeLeave(Btree *p){ + if( p->sharable ){ + assert( p->wantToLock>0 ); + p->wantToLock--; + if( p->wantToLock==0 ){ + unlockBtreeMutex(p); + } + } +} + +#ifndef NDEBUG +/* +** Return true if the BtShared mutex is held on the btree, or if the +** B-Tree is not marked as sharable. +** +** This routine is used only from within assert() statements. +*/ +int sqlite3BtreeHoldsMutex(Btree *p){ + assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); + assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); + assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); + assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); + + return (p->sharable==0 || p->locked); +} +#endif + + +#ifndef SQLITE_OMIT_INCRBLOB +/* +** Enter and leave a mutex on a Btree given a cursor owned by that +** Btree. These entry points are used by incremental I/O and can be +** omitted if that module is not used. +*/ +void sqlite3BtreeEnterCursor(BtCursor *pCur){ + sqlite3BtreeEnter(pCur->pBtree); +} +void sqlite3BtreeLeaveCursor(BtCursor *pCur){ + sqlite3BtreeLeave(pCur->pBtree); +} +#endif /* SQLITE_OMIT_INCRBLOB */ + + +/* +** Enter the mutex on every Btree associated with a database +** connection. This is needed (for example) prior to parsing +** a statement since we will be comparing table and column names +** against all schemas and we do not want those schemas being +** reset out from under us. +** +** There is a corresponding leave-all procedures. +** +** Enter the mutexes in accending order by BtShared pointer address +** to avoid the possibility of deadlock when two threads with +** two or more btrees in common both try to lock all their btrees +** at the same instant. +*/ +void sqlite3BtreeEnterAll(sqlite3 *db){ + int i; + Btree *p; + assert( sqlite3_mutex_held(db->mutex) ); + for(i=0; inDb; i++){ + p = db->aDb[i].pBt; + if( p ) sqlite3BtreeEnter(p); + } +} +void sqlite3BtreeLeaveAll(sqlite3 *db){ + int i; + Btree *p; + assert( sqlite3_mutex_held(db->mutex) ); + for(i=0; inDb; i++){ + p = db->aDb[i].pBt; + if( p ) sqlite3BtreeLeave(p); + } +} + +/* +** Return true if a particular Btree requires a lock. Return FALSE if +** no lock is ever required since it is not sharable. +*/ +int sqlite3BtreeSharable(Btree *p){ + return p->sharable; +} + +#ifndef NDEBUG +/* +** Return true if the current thread holds the database connection +** mutex and all required BtShared mutexes. +** +** This routine is used inside assert() statements only. +*/ +int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ + int i; + if( !sqlite3_mutex_held(db->mutex) ){ + return 0; + } + for(i=0; inDb; i++){ + Btree *p; + p = db->aDb[i].pBt; + if( p && p->sharable && + (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ + return 0; + } + } + return 1; +} +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* +** Return true if the correct mutexes are held for accessing the +** db->aDb[iDb].pSchema structure. The mutexes required for schema +** access are: +** +** (1) The mutex on db +** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. +** +** If pSchema is not NULL, then iDb is computed from pSchema and +** db using sqlite3SchemaToIndex(). +*/ +int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){ + Btree *p; + assert( db!=0 ); + if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); + assert( iDb>=0 && iDbnDb ); + if( !sqlite3_mutex_held(db->mutex) ) return 0; + if( iDb==1 ) return 1; + p = db->aDb[iDb].pBt; + assert( p!=0 ); + return p->sharable==0 || p->locked==1; +} +#endif /* NDEBUG */ + +#else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */ +/* +** The following are special cases for mutex enter routines for use +** in single threaded applications that use shared cache. Except for +** these two routines, all mutex operations are no-ops in that case and +** are null #defines in btree.h. +** +** If shared cache is disabled, then all btree mutex routines, including +** the ones below, are no-ops and are null #defines in btree.h. +*/ + +void sqlite3BtreeEnter(Btree *p){ + p->pBt->db = p->db; +} +void sqlite3BtreeEnterAll(sqlite3 *db){ + int i; + for(i=0; inDb; i++){ + Btree *p = db->aDb[i].pBt; + if( p ){ + p->pBt->db = p->db; + } + } +} +#endif /* if SQLITE_THREADSAFE */ +#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */ diff --git a/components/external/SQLite-3.8.1/src/btree.c b/components/external/SQLite-3.8.1/src/btree.c new file mode 100644 index 0000000000000000000000000000000000000000..d56dfbddbbd33d3aa320fa750cac2d6355a5c758 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/btree.c @@ -0,0 +1,8522 @@ +/* +** 2004 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements a external (disk-based) database using BTrees. +** See the header comment on "btreeInt.h" for additional information. +** Including a description of file format and an overview of operation. +*/ +#include "btreeInt.h" + +/* +** The header string that appears at the beginning of every +** SQLite database. +*/ +static const char zMagicHeader[] = SQLITE_FILE_HEADER; + +/* +** Set this global variable to 1 to enable tracing using the TRACE +** macro. +*/ +#if 0 +int sqlite3BtreeTrace=1; /* True to enable tracing */ +# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} +#else +# define TRACE(X) +#endif + +/* +** Extract a 2-byte big-endian integer from an array of unsigned bytes. +** But if the value is zero, make it 65536. +** +** This routine is used to extract the "offset to cell content area" value +** from the header of a btree page. If the page size is 65536 and the page +** is empty, the offset should be 65536, but the 2-byte value stores zero. +** This routine makes the necessary adjustment to 65536. +*/ +#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) + +/* +** Values passed as the 5th argument to allocateBtreePage() +*/ +#define BTALLOC_ANY 0 /* Allocate any page */ +#define BTALLOC_EXACT 1 /* Allocate exact page if possible */ +#define BTALLOC_LE 2 /* Allocate any page <= the parameter */ + +/* +** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not +** defined, or 0 if it is. For example: +** +** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum); +*/ +#ifndef SQLITE_OMIT_AUTOVACUUM +#define IfNotOmitAV(expr) (expr) +#else +#define IfNotOmitAV(expr) 0 +#endif + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** A list of BtShared objects that are eligible for participation +** in shared cache. This variable has file scope during normal builds, +** but the test harness needs to access it so we make it global for +** test builds. +** +** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. +*/ +#ifdef SQLITE_TEST +BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; +#else +static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; +#endif +#endif /* SQLITE_OMIT_SHARED_CACHE */ + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** Enable or disable the shared pager and schema features. +** +** This routine has no effect on existing database connections. +** The shared cache setting effects only future calls to +** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). +*/ +int sqlite3_enable_shared_cache(int enable){ + sqlite3GlobalConfig.sharedCacheEnabled = enable; + return SQLITE_OK; +} +#endif + + + +#ifdef SQLITE_OMIT_SHARED_CACHE + /* + ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), + ** and clearAllSharedCacheTableLocks() + ** manipulate entries in the BtShared.pLock linked list used to store + ** shared-cache table level locks. If the library is compiled with the + ** shared-cache feature disabled, then there is only ever one user + ** of each BtShared structure and so this locking is not necessary. + ** So define the lock related functions as no-ops. + */ + #define querySharedCacheTableLock(a,b,c) SQLITE_OK + #define setSharedCacheTableLock(a,b,c) SQLITE_OK + #define clearAllSharedCacheTableLocks(a) + #define downgradeAllSharedCacheTableLocks(a) + #define hasSharedCacheTableLock(a,b,c,d) 1 + #define hasReadConflicts(a, b) 0 +#endif + +#ifndef SQLITE_OMIT_SHARED_CACHE + +#ifdef SQLITE_DEBUG +/* +**** This function is only used as part of an assert() statement. *** +** +** Check to see if pBtree holds the required locks to read or write to the +** table with root page iRoot. Return 1 if it does and 0 if not. +** +** For example, when writing to a table with root-page iRoot via +** Btree connection pBtree: +** +** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); +** +** When writing to an index that resides in a sharable database, the +** caller should have first obtained a lock specifying the root page of +** the corresponding table. This makes things a bit more complicated, +** as this module treats each table as a separate structure. To determine +** the table corresponding to the index being written, this +** function has to search through the database schema. +** +** Instead of a lock on the table/index rooted at page iRoot, the caller may +** hold a write-lock on the schema table (root page 1). This is also +** acceptable. +*/ +static int hasSharedCacheTableLock( + Btree *pBtree, /* Handle that must hold lock */ + Pgno iRoot, /* Root page of b-tree */ + int isIndex, /* True if iRoot is the root of an index b-tree */ + int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ +){ + Schema *pSchema = (Schema *)pBtree->pBt->pSchema; + Pgno iTab = 0; + BtLock *pLock; + + /* If this database is not shareable, or if the client is reading + ** and has the read-uncommitted flag set, then no lock is required. + ** Return true immediately. + */ + if( (pBtree->sharable==0) + || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted)) + ){ + return 1; + } + + /* If the client is reading or writing an index and the schema is + ** not loaded, then it is too difficult to actually check to see if + ** the correct locks are held. So do not bother - just return true. + ** This case does not come up very often anyhow. + */ + if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){ + return 1; + } + + /* Figure out the root-page that the lock should be held on. For table + ** b-trees, this is just the root page of the b-tree being read or + ** written. For index b-trees, it is the root page of the associated + ** table. */ + if( isIndex ){ + HashElem *p; + for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ + Index *pIdx = (Index *)sqliteHashData(p); + if( pIdx->tnum==(int)iRoot ){ + iTab = pIdx->pTable->tnum; + } + } + }else{ + iTab = iRoot; + } + + /* Search for the required lock. Either a write-lock on root-page iTab, a + ** write-lock on the schema table, or (if the client is reading) a + ** read-lock on iTab will suffice. Return 1 if any of these are found. */ + for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){ + if( pLock->pBtree==pBtree + && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1)) + && pLock->eLock>=eLockType + ){ + return 1; + } + } + + /* Failed to find the required lock. */ + return 0; +} +#endif /* SQLITE_DEBUG */ + +#ifdef SQLITE_DEBUG +/* +**** This function may be used as part of assert() statements only. **** +** +** Return true if it would be illegal for pBtree to write into the +** table or index rooted at iRoot because other shared connections are +** simultaneously reading that same table or index. +** +** It is illegal for pBtree to write if some other Btree object that +** shares the same BtShared object is currently reading or writing +** the iRoot table. Except, if the other Btree object has the +** read-uncommitted flag set, then it is OK for the other object to +** have a read cursor. +** +** For example, before writing to any part of the table or index +** rooted at page iRoot, one should call: +** +** assert( !hasReadConflicts(pBtree, iRoot) ); +*/ +static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ + BtCursor *p; + for(p=pBtree->pBt->pCursor; p; p=p->pNext){ + if( p->pgnoRoot==iRoot + && p->pBtree!=pBtree + && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted) + ){ + return 1; + } + } + return 0; +} +#endif /* #ifdef SQLITE_DEBUG */ + +/* +** Query to see if Btree handle p may obtain a lock of type eLock +** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return +** SQLITE_OK if the lock may be obtained (by calling +** setSharedCacheTableLock()), or SQLITE_LOCKED if not. +*/ +static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ + BtShared *pBt = p->pBt; + BtLock *pIter; + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); + assert( p->db!=0 ); + assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 ); + + /* If requesting a write-lock, then the Btree must have an open write + ** transaction on this file. And, obviously, for this to be so there + ** must be an open write transaction on the file itself. + */ + assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) ); + assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); + + /* This routine is a no-op if the shared-cache is not enabled */ + if( !p->sharable ){ + return SQLITE_OK; + } + + /* If some other connection is holding an exclusive lock, the + ** requested lock may not be obtained. + */ + if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ + sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); + return SQLITE_LOCKED_SHAREDCACHE; + } + + for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ + /* The condition (pIter->eLock!=eLock) in the following if(...) + ** statement is a simplification of: + ** + ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) + ** + ** since we know that if eLock==WRITE_LOCK, then no other connection + ** may hold a WRITE_LOCK on any table in this file (since there can + ** only be a single writer). + */ + assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); + assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); + if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ + sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); + if( eLock==WRITE_LOCK ){ + assert( p==pBt->pWriter ); + pBt->btsFlags |= BTS_PENDING; + } + return SQLITE_LOCKED_SHAREDCACHE; + } + } + return SQLITE_OK; +} +#endif /* !SQLITE_OMIT_SHARED_CACHE */ + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** Add a lock on the table with root-page iTable to the shared-btree used +** by Btree handle p. Parameter eLock must be either READ_LOCK or +** WRITE_LOCK. +** +** This function assumes the following: +** +** (a) The specified Btree object p is connected to a sharable +** database (one with the BtShared.sharable flag set), and +** +** (b) No other Btree objects hold a lock that conflicts +** with the requested lock (i.e. querySharedCacheTableLock() has +** already been called and returned SQLITE_OK). +** +** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM +** is returned if a malloc attempt fails. +*/ +static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ + BtShared *pBt = p->pBt; + BtLock *pLock = 0; + BtLock *pIter; + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); + assert( p->db!=0 ); + + /* A connection with the read-uncommitted flag set will never try to + ** obtain a read-lock using this function. The only read-lock obtained + ** by a connection in read-uncommitted mode is on the sqlite_master + ** table, and that lock is obtained in BtreeBeginTrans(). */ + assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK ); + + /* This function should only be called on a sharable b-tree after it + ** has been determined that no other b-tree holds a conflicting lock. */ + assert( p->sharable ); + assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); + + /* First search the list for an existing lock on this table. */ + for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ + if( pIter->iTable==iTable && pIter->pBtree==p ){ + pLock = pIter; + break; + } + } + + /* If the above search did not find a BtLock struct associating Btree p + ** with table iTable, allocate one and link it into the list. + */ + if( !pLock ){ + pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); + if( !pLock ){ + return SQLITE_NOMEM; + } + pLock->iTable = iTable; + pLock->pBtree = p; + pLock->pNext = pBt->pLock; + pBt->pLock = pLock; + } + + /* Set the BtLock.eLock variable to the maximum of the current lock + ** and the requested lock. This means if a write-lock was already held + ** and a read-lock requested, we don't incorrectly downgrade the lock. + */ + assert( WRITE_LOCK>READ_LOCK ); + if( eLock>pLock->eLock ){ + pLock->eLock = eLock; + } + + return SQLITE_OK; +} +#endif /* !SQLITE_OMIT_SHARED_CACHE */ + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** Release all the table locks (locks obtained via calls to +** the setSharedCacheTableLock() procedure) held by Btree object p. +** +** This function assumes that Btree p has an open read or write +** transaction. If it does not, then the BTS_PENDING flag +** may be incorrectly cleared. +*/ +static void clearAllSharedCacheTableLocks(Btree *p){ + BtShared *pBt = p->pBt; + BtLock **ppIter = &pBt->pLock; + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( p->sharable || 0==*ppIter ); + assert( p->inTrans>0 ); + + while( *ppIter ){ + BtLock *pLock = *ppIter; + assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree ); + assert( pLock->pBtree->inTrans>=pLock->eLock ); + if( pLock->pBtree==p ){ + *ppIter = pLock->pNext; + assert( pLock->iTable!=1 || pLock==&p->lock ); + if( pLock->iTable!=1 ){ + sqlite3_free(pLock); + } + }else{ + ppIter = &pLock->pNext; + } + } + + assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter ); + if( pBt->pWriter==p ){ + pBt->pWriter = 0; + pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); + }else if( pBt->nTransaction==2 ){ + /* This function is called when Btree p is concluding its + ** transaction. If there currently exists a writer, and p is not + ** that writer, then the number of locks held by connections other + ** than the writer must be about to drop to zero. In this case + ** set the BTS_PENDING flag to 0. + ** + ** If there is not currently a writer, then BTS_PENDING must + ** be zero already. So this next line is harmless in that case. + */ + pBt->btsFlags &= ~BTS_PENDING; + } +} + +/* +** This function changes all write-locks held by Btree p into read-locks. +*/ +static void downgradeAllSharedCacheTableLocks(Btree *p){ + BtShared *pBt = p->pBt; + if( pBt->pWriter==p ){ + BtLock *pLock; + pBt->pWriter = 0; + pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); + for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ + assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); + pLock->eLock = READ_LOCK; + } + } +} + +#endif /* SQLITE_OMIT_SHARED_CACHE */ + +static void releasePage(MemPage *pPage); /* Forward reference */ + +/* +***** This routine is used inside of assert() only **** +** +** Verify that the cursor holds the mutex on its BtShared +*/ +#ifdef SQLITE_DEBUG +static int cursorHoldsMutex(BtCursor *p){ + return sqlite3_mutex_held(p->pBt->mutex); +} +#endif + + +#ifndef SQLITE_OMIT_INCRBLOB +/* +** Invalidate the overflow page-list cache for cursor pCur, if any. +*/ +static void invalidateOverflowCache(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + sqlite3_free(pCur->aOverflow); + pCur->aOverflow = 0; +} + +/* +** Invalidate the overflow page-list cache for all cursors opened +** on the shared btree structure pBt. +*/ +static void invalidateAllOverflowCache(BtShared *pBt){ + BtCursor *p; + assert( sqlite3_mutex_held(pBt->mutex) ); + for(p=pBt->pCursor; p; p=p->pNext){ + invalidateOverflowCache(p); + } +} + +/* +** This function is called before modifying the contents of a table +** to invalidate any incrblob cursors that are open on the +** row or one of the rows being modified. +** +** If argument isClearTable is true, then the entire contents of the +** table is about to be deleted. In this case invalidate all incrblob +** cursors open on any row within the table with root-page pgnoRoot. +** +** Otherwise, if argument isClearTable is false, then the row with +** rowid iRow is being replaced or deleted. In this case invalidate +** only those incrblob cursors open on that specific row. +*/ +static void invalidateIncrblobCursors( + Btree *pBtree, /* The database file to check */ + i64 iRow, /* The rowid that might be changing */ + int isClearTable /* True if all rows are being deleted */ +){ + BtCursor *p; + BtShared *pBt = pBtree->pBt; + assert( sqlite3BtreeHoldsMutex(pBtree) ); + for(p=pBt->pCursor; p; p=p->pNext){ + if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){ + p->eState = CURSOR_INVALID; + } + } +} + +#else + /* Stub functions when INCRBLOB is omitted */ + #define invalidateOverflowCache(x) + #define invalidateAllOverflowCache(x) + #define invalidateIncrblobCursors(x,y,z) +#endif /* SQLITE_OMIT_INCRBLOB */ + +/* +** Set bit pgno of the BtShared.pHasContent bitvec. This is called +** when a page that previously contained data becomes a free-list leaf +** page. +** +** The BtShared.pHasContent bitvec exists to work around an obscure +** bug caused by the interaction of two useful IO optimizations surrounding +** free-list leaf pages: +** +** 1) When all data is deleted from a page and the page becomes +** a free-list leaf page, the page is not written to the database +** (as free-list leaf pages contain no meaningful data). Sometimes +** such a page is not even journalled (as it will not be modified, +** why bother journalling it?). +** +** 2) When a free-list leaf page is reused, its content is not read +** from the database or written to the journal file (why should it +** be, if it is not at all meaningful?). +** +** By themselves, these optimizations work fine and provide a handy +** performance boost to bulk delete or insert operations. However, if +** a page is moved to the free-list and then reused within the same +** transaction, a problem comes up. If the page is not journalled when +** it is moved to the free-list and it is also not journalled when it +** is extracted from the free-list and reused, then the original data +** may be lost. In the event of a rollback, it may not be possible +** to restore the database to its original configuration. +** +** The solution is the BtShared.pHasContent bitvec. Whenever a page is +** moved to become a free-list leaf page, the corresponding bit is +** set in the bitvec. Whenever a leaf page is extracted from the free-list, +** optimization 2 above is omitted if the corresponding bit is already +** set in BtShared.pHasContent. The contents of the bitvec are cleared +** at the end of every transaction. +*/ +static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ + int rc = SQLITE_OK; + if( !pBt->pHasContent ){ + assert( pgno<=pBt->nPage ); + pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); + if( !pBt->pHasContent ){ + rc = SQLITE_NOMEM; + } + } + if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ + rc = sqlite3BitvecSet(pBt->pHasContent, pgno); + } + return rc; +} + +/* +** Query the BtShared.pHasContent vector. +** +** This function is called when a free-list leaf page is removed from the +** free-list for reuse. It returns false if it is safe to retrieve the +** page from the pager layer with the 'no-content' flag set. True otherwise. +*/ +static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ + Bitvec *p = pBt->pHasContent; + return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno))); +} + +/* +** Clear (destroy) the BtShared.pHasContent bitvec. This should be +** invoked at the conclusion of each write-transaction. +*/ +static void btreeClearHasContent(BtShared *pBt){ + sqlite3BitvecDestroy(pBt->pHasContent); + pBt->pHasContent = 0; +} + +/* +** Release all of the apPage[] pages for a cursor. +*/ +static void btreeReleaseAllCursorPages(BtCursor *pCur){ + int i; + for(i=0; i<=pCur->iPage; i++){ + releasePage(pCur->apPage[i]); + pCur->apPage[i] = 0; + } + pCur->iPage = -1; +} + + +/* +** Save the current cursor position in the variables BtCursor.nKey +** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. +** +** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) +** prior to calling this routine. +*/ +static int saveCursorPosition(BtCursor *pCur){ + int rc; + + assert( CURSOR_VALID==pCur->eState ); + assert( 0==pCur->pKey ); + assert( cursorHoldsMutex(pCur) ); + + rc = sqlite3BtreeKeySize(pCur, &pCur->nKey); + assert( rc==SQLITE_OK ); /* KeySize() cannot fail */ + + /* If this is an intKey table, then the above call to BtreeKeySize() + ** stores the integer key in pCur->nKey. In this case this value is + ** all that is required. Otherwise, if pCur is not open on an intKey + ** table, then malloc space for and store the pCur->nKey bytes of key + ** data. + */ + if( 0==pCur->apPage[0]->intKey ){ + void *pKey = sqlite3Malloc( (int)pCur->nKey ); + if( pKey ){ + rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey); + if( rc==SQLITE_OK ){ + pCur->pKey = pKey; + }else{ + sqlite3_free(pKey); + } + }else{ + rc = SQLITE_NOMEM; + } + } + assert( !pCur->apPage[0]->intKey || !pCur->pKey ); + + if( rc==SQLITE_OK ){ + btreeReleaseAllCursorPages(pCur); + pCur->eState = CURSOR_REQUIRESEEK; + } + + invalidateOverflowCache(pCur); + return rc; +} + +/* +** Save the positions of all cursors (except pExcept) that are open on +** the table with root-page iRoot. Usually, this is called just before cursor +** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()). +*/ +static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ + BtCursor *p; + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( pExcept==0 || pExcept->pBt==pBt ); + for(p=pBt->pCursor; p; p=p->pNext){ + if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ + if( p->eState==CURSOR_VALID ){ + int rc = saveCursorPosition(p); + if( SQLITE_OK!=rc ){ + return rc; + } + }else{ + testcase( p->iPage>0 ); + btreeReleaseAllCursorPages(p); + } + } + } + return SQLITE_OK; +} + +/* +** Clear the current cursor position. +*/ +void sqlite3BtreeClearCursor(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + sqlite3_free(pCur->pKey); + pCur->pKey = 0; + pCur->eState = CURSOR_INVALID; +} + +/* +** In this version of BtreeMoveto, pKey is a packed index record +** such as is generated by the OP_MakeRecord opcode. Unpack the +** record and then call BtreeMovetoUnpacked() to do the work. +*/ +static int btreeMoveto( + BtCursor *pCur, /* Cursor open on the btree to be searched */ + const void *pKey, /* Packed key if the btree is an index */ + i64 nKey, /* Integer key for tables. Size of pKey for indices */ + int bias, /* Bias search to the high end */ + int *pRes /* Write search results here */ +){ + int rc; /* Status code */ + UnpackedRecord *pIdxKey; /* Unpacked index key */ + char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */ + char *pFree = 0; + + if( pKey ){ + assert( nKey==(i64)(int)nKey ); + pIdxKey = sqlite3VdbeAllocUnpackedRecord( + pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree + ); + if( pIdxKey==0 ) return SQLITE_NOMEM; + sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey); + }else{ + pIdxKey = 0; + } + rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); + if( pFree ){ + sqlite3DbFree(pCur->pKeyInfo->db, pFree); + } + return rc; +} + +/* +** Restore the cursor to the position it was in (or as close to as possible) +** when saveCursorPosition() was called. Note that this call deletes the +** saved position info stored by saveCursorPosition(), so there can be +** at most one effective restoreCursorPosition() call after each +** saveCursorPosition(). +*/ +static int btreeRestoreCursorPosition(BtCursor *pCur){ + int rc; + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState>=CURSOR_REQUIRESEEK ); + if( pCur->eState==CURSOR_FAULT ){ + return pCur->skipNext; + } + pCur->eState = CURSOR_INVALID; + rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext); + if( rc==SQLITE_OK ){ + sqlite3_free(pCur->pKey); + pCur->pKey = 0; + assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); + if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ + pCur->eState = CURSOR_SKIPNEXT; + } + } + return rc; +} + +#define restoreCursorPosition(p) \ + (p->eState>=CURSOR_REQUIRESEEK ? \ + btreeRestoreCursorPosition(p) : \ + SQLITE_OK) + +/* +** Determine whether or not a cursor has moved from the position it +** was last placed at. Cursors can move when the row they are pointing +** at is deleted out from under them. +** +** This routine returns an error code if something goes wrong. The +** integer *pHasMoved is set to one if the cursor has moved and 0 if not. +*/ +int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){ + int rc; + + rc = restoreCursorPosition(pCur); + if( rc ){ + *pHasMoved = 1; + return rc; + } + if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){ + *pHasMoved = 1; + }else{ + *pHasMoved = 0; + } + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_AUTOVACUUM +/* +** Given a page number of a regular database page, return the page +** number for the pointer-map page that contains the entry for the +** input page number. +** +** Return 0 (not a valid page) for pgno==1 since there is +** no pointer map associated with page 1. The integrity_check logic +** requires that ptrmapPageno(*,1)!=1. +*/ +static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ + int nPagesPerMapPage; + Pgno iPtrMap, ret; + assert( sqlite3_mutex_held(pBt->mutex) ); + if( pgno<2 ) return 0; + nPagesPerMapPage = (pBt->usableSize/5)+1; + iPtrMap = (pgno-2)/nPagesPerMapPage; + ret = (iPtrMap*nPagesPerMapPage) + 2; + if( ret==PENDING_BYTE_PAGE(pBt) ){ + ret++; + } + return ret; +} + +/* +** Write an entry into the pointer map. +** +** This routine updates the pointer map entry for page number 'key' +** so that it maps to type 'eType' and parent page number 'pgno'. +** +** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is +** a no-op. If an error occurs, the appropriate error code is written +** into *pRC. +*/ +static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ + DbPage *pDbPage; /* The pointer map page */ + u8 *pPtrmap; /* The pointer map data */ + Pgno iPtrmap; /* The pointer map page number */ + int offset; /* Offset in pointer map page */ + int rc; /* Return code from subfunctions */ + + if( *pRC ) return; + + assert( sqlite3_mutex_held(pBt->mutex) ); + /* The master-journal page number must never be used as a pointer map page */ + assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); + + assert( pBt->autoVacuum ); + if( key==0 ){ + *pRC = SQLITE_CORRUPT_BKPT; + return; + } + iPtrmap = PTRMAP_PAGENO(pBt, key); + rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); + if( rc!=SQLITE_OK ){ + *pRC = rc; + return; + } + offset = PTRMAP_PTROFFSET(iPtrmap, key); + if( offset<0 ){ + *pRC = SQLITE_CORRUPT_BKPT; + goto ptrmap_exit; + } + assert( offset <= (int)pBt->usableSize-5 ); + pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); + + if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ + TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); + *pRC= rc = sqlite3PagerWrite(pDbPage); + if( rc==SQLITE_OK ){ + pPtrmap[offset] = eType; + put4byte(&pPtrmap[offset+1], parent); + } + } + +ptrmap_exit: + sqlite3PagerUnref(pDbPage); +} + +/* +** Read an entry from the pointer map. +** +** This routine retrieves the pointer map entry for page 'key', writing +** the type and parent page number to *pEType and *pPgno respectively. +** An error code is returned if something goes wrong, otherwise SQLITE_OK. +*/ +static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ + DbPage *pDbPage; /* The pointer map page */ + int iPtrmap; /* Pointer map page index */ + u8 *pPtrmap; /* Pointer map page data */ + int offset; /* Offset of entry in pointer map */ + int rc; + + assert( sqlite3_mutex_held(pBt->mutex) ); + + iPtrmap = PTRMAP_PAGENO(pBt, key); + rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); + if( rc!=0 ){ + return rc; + } + pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); + + offset = PTRMAP_PTROFFSET(iPtrmap, key); + if( offset<0 ){ + sqlite3PagerUnref(pDbPage); + return SQLITE_CORRUPT_BKPT; + } + assert( offset <= (int)pBt->usableSize-5 ); + assert( pEType!=0 ); + *pEType = pPtrmap[offset]; + if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); + + sqlite3PagerUnref(pDbPage); + if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT; + return SQLITE_OK; +} + +#else /* if defined SQLITE_OMIT_AUTOVACUUM */ + #define ptrmapPut(w,x,y,z,rc) + #define ptrmapGet(w,x,y,z) SQLITE_OK + #define ptrmapPutOvflPtr(x, y, rc) +#endif + +/* +** Given a btree page and a cell index (0 means the first cell on +** the page, 1 means the second cell, and so forth) return a pointer +** to the cell content. +** +** This routine works only for pages that do not contain overflow cells. +*/ +#define findCell(P,I) \ + ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)]))) +#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I))))) + + +/* +** This a more complex version of findCell() that works for +** pages that do contain overflow cells. +*/ +static u8 *findOverflowCell(MemPage *pPage, int iCell){ + int i; + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + for(i=pPage->nOverflow-1; i>=0; i--){ + int k; + k = pPage->aiOvfl[i]; + if( k<=iCell ){ + if( k==iCell ){ + return pPage->apOvfl[i]; + } + iCell--; + } + } + return findCell(pPage, iCell); +} + +/* +** Parse a cell content block and fill in the CellInfo structure. There +** are two versions of this function. btreeParseCell() takes a +** cell index as the second argument and btreeParseCellPtr() +** takes a pointer to the body of the cell as its second argument. +** +** Within this file, the parseCell() macro can be called instead of +** btreeParseCellPtr(). Using some compilers, this will be faster. +*/ +static void btreeParseCellPtr( + MemPage *pPage, /* Page containing the cell */ + u8 *pCell, /* Pointer to the cell text. */ + CellInfo *pInfo /* Fill in this structure */ +){ + u16 n; /* Number bytes in cell content header */ + u32 nPayload; /* Number of bytes of cell payload */ + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + + pInfo->pCell = pCell; + assert( pPage->leaf==0 || pPage->leaf==1 ); + n = pPage->childPtrSize; + assert( n==4-4*pPage->leaf ); + if( pPage->intKey ){ + if( pPage->hasData ){ + assert( n==0 ); + n = getVarint32(pCell, nPayload); + }else{ + nPayload = 0; + } + n += getVarint(&pCell[n], (u64*)&pInfo->nKey); + pInfo->nData = nPayload; + }else{ + pInfo->nData = 0; + n += getVarint32(&pCell[n], nPayload); + pInfo->nKey = nPayload; + } + pInfo->nPayload = nPayload; + pInfo->nHeader = n; + testcase( nPayload==pPage->maxLocal ); + testcase( nPayload==pPage->maxLocal+1 ); + if( likely(nPayload<=pPage->maxLocal) ){ + /* This is the (easy) common case where the entire payload fits + ** on the local page. No overflow is required. + */ + if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4; + pInfo->nLocal = (u16)nPayload; + pInfo->iOverflow = 0; + }else{ + /* If the payload will not fit completely on the local page, we have + ** to decide how much to store locally and how much to spill onto + ** overflow pages. The strategy is to minimize the amount of unused + ** space on overflow pages while keeping the amount of local storage + ** in between minLocal and maxLocal. + ** + ** Warning: changing the way overflow payload is distributed in any + ** way will result in an incompatible file format. + */ + int minLocal; /* Minimum amount of payload held locally */ + int maxLocal; /* Maximum amount of payload held locally */ + int surplus; /* Overflow payload available for local storage */ + + minLocal = pPage->minLocal; + maxLocal = pPage->maxLocal; + surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4); + testcase( surplus==maxLocal ); + testcase( surplus==maxLocal+1 ); + if( surplus <= maxLocal ){ + pInfo->nLocal = (u16)surplus; + }else{ + pInfo->nLocal = (u16)minLocal; + } + pInfo->iOverflow = (u16)(pInfo->nLocal + n); + pInfo->nSize = pInfo->iOverflow + 4; + } +} +#define parseCell(pPage, iCell, pInfo) \ + btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo)) +static void btreeParseCell( + MemPage *pPage, /* Page containing the cell */ + int iCell, /* The cell index. First cell is 0 */ + CellInfo *pInfo /* Fill in this structure */ +){ + parseCell(pPage, iCell, pInfo); +} + +/* +** Compute the total number of bytes that a Cell needs in the cell +** data area of the btree-page. The return number includes the cell +** data header and the local payload, but not any overflow page or +** the space used by the cell pointer. +*/ +static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ + u8 *pIter = &pCell[pPage->childPtrSize]; + u32 nSize; + +#ifdef SQLITE_DEBUG + /* The value returned by this function should always be the same as + ** the (CellInfo.nSize) value found by doing a full parse of the + ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of + ** this function verifies that this invariant is not violated. */ + CellInfo debuginfo; + btreeParseCellPtr(pPage, pCell, &debuginfo); +#endif + + if( pPage->intKey ){ + u8 *pEnd; + if( pPage->hasData ){ + pIter += getVarint32(pIter, nSize); + }else{ + nSize = 0; + } + + /* pIter now points at the 64-bit integer key value, a variable length + ** integer. The following block moves pIter to point at the first byte + ** past the end of the key value. */ + pEnd = &pIter[9]; + while( (*pIter++)&0x80 && pItermaxLocal ); + testcase( nSize==pPage->maxLocal+1 ); + if( nSize>pPage->maxLocal ){ + int minLocal = pPage->minLocal; + nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); + testcase( nSize==pPage->maxLocal ); + testcase( nSize==pPage->maxLocal+1 ); + if( nSize>pPage->maxLocal ){ + nSize = minLocal; + } + nSize += 4; + } + nSize += (u32)(pIter - pCell); + + /* The minimum size of any cell is 4 bytes. */ + if( nSize<4 ){ + nSize = 4; + } + + assert( nSize==debuginfo.nSize ); + return (u16)nSize; +} + +#ifdef SQLITE_DEBUG +/* This variation on cellSizePtr() is used inside of assert() statements +** only. */ +static u16 cellSize(MemPage *pPage, int iCell){ + return cellSizePtr(pPage, findCell(pPage, iCell)); +} +#endif + +#ifndef SQLITE_OMIT_AUTOVACUUM +/* +** If the cell pCell, part of page pPage contains a pointer +** to an overflow page, insert an entry into the pointer-map +** for the overflow page. +*/ +static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ + CellInfo info; + if( *pRC ) return; + assert( pCell!=0 ); + btreeParseCellPtr(pPage, pCell, &info); + assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload ); + if( info.iOverflow ){ + Pgno ovfl = get4byte(&pCell[info.iOverflow]); + ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); + } +} +#endif + + +/* +** Defragment the page given. All Cells are moved to the +** end of the page and all free space is collected into one +** big FreeBlk that occurs in between the header and cell +** pointer array and the cell content area. +*/ +static int defragmentPage(MemPage *pPage){ + int i; /* Loop counter */ + int pc; /* Address of a i-th cell */ + int hdr; /* Offset to the page header */ + int size; /* Size of a cell */ + int usableSize; /* Number of usable bytes on a page */ + int cellOffset; /* Offset to the cell pointer array */ + int cbrk; /* Offset to the cell content area */ + int nCell; /* Number of cells on the page */ + unsigned char *data; /* The page data */ + unsigned char *temp; /* Temp area for cell content */ + int iCellFirst; /* First allowable cell index */ + int iCellLast; /* Last possible cell index */ + + + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( pPage->pBt!=0 ); + assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); + assert( pPage->nOverflow==0 ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + temp = sqlite3PagerTempSpace(pPage->pBt->pPager); + data = pPage->aData; + hdr = pPage->hdrOffset; + cellOffset = pPage->cellOffset; + nCell = pPage->nCell; + assert( nCell==get2byte(&data[hdr+3]) ); + usableSize = pPage->pBt->usableSize; + cbrk = get2byte(&data[hdr+5]); + memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk); + cbrk = usableSize; + iCellFirst = cellOffset + 2*nCell; + iCellLast = usableSize - 4; + for(i=0; iiCellLast ){ + return SQLITE_CORRUPT_BKPT; + } +#endif + assert( pc>=iCellFirst && pc<=iCellLast ); + size = cellSizePtr(pPage, &temp[pc]); + cbrk -= size; +#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) + if( cbrkusableSize ){ + return SQLITE_CORRUPT_BKPT; + } +#endif + assert( cbrk+size<=usableSize && cbrk>=iCellFirst ); + testcase( cbrk+size==usableSize ); + testcase( pc+size==usableSize ); + memcpy(&data[cbrk], &temp[pc], size); + put2byte(pAddr, cbrk); + } + assert( cbrk>=iCellFirst ); + put2byte(&data[hdr+5], cbrk); + data[hdr+1] = 0; + data[hdr+2] = 0; + data[hdr+7] = 0; + memset(&data[iCellFirst], 0, cbrk-iCellFirst); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + if( cbrk-iCellFirst!=pPage->nFree ){ + return SQLITE_CORRUPT_BKPT; + } + return SQLITE_OK; +} + +/* +** Allocate nByte bytes of space from within the B-Tree page passed +** as the first argument. Write into *pIdx the index into pPage->aData[] +** of the first byte of allocated space. Return either SQLITE_OK or +** an error code (usually SQLITE_CORRUPT). +** +** The caller guarantees that there is sufficient space to make the +** allocation. This routine might need to defragment in order to bring +** all the space together, however. This routine will avoid using +** the first two bytes past the cell pointer area since presumably this +** allocation is being made in order to insert a new cell, so we will +** also end up needing a new cell pointer. +*/ +static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ + const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ + u8 * const data = pPage->aData; /* Local cache of pPage->aData */ + int nFrag; /* Number of fragmented bytes on pPage */ + int top; /* First byte of cell content area */ + int gap; /* First byte of gap between cell pointers and cell content */ + int rc; /* Integer return code */ + int usableSize; /* Usable size of the page */ + + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( pPage->pBt ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( nByte>=0 ); /* Minimum cell size is 4 */ + assert( pPage->nFree>=nByte ); + assert( pPage->nOverflow==0 ); + usableSize = pPage->pBt->usableSize; + assert( nByte < usableSize-8 ); + + nFrag = data[hdr+7]; + assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); + gap = pPage->cellOffset + 2*pPage->nCell; + top = get2byteNotZero(&data[hdr+5]); + if( gap>top ) return SQLITE_CORRUPT_BKPT; + testcase( gap+2==top ); + testcase( gap+1==top ); + testcase( gap==top ); + + if( nFrag>=60 ){ + /* Always defragment highly fragmented pages */ + rc = defragmentPage(pPage); + if( rc ) return rc; + top = get2byteNotZero(&data[hdr+5]); + }else if( gap+2<=top ){ + /* Search the freelist looking for a free slot big enough to satisfy + ** the request. The allocation is made from the first free slot in + ** the list that is large enough to accommodate it. + */ + int pc, addr; + for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){ + int size; /* Size of the free slot */ + if( pc>usableSize-4 || pc=nByte ){ + int x = size - nByte; + testcase( x==4 ); + testcase( x==3 ); + if( x<4 ){ + /* Remove the slot from the free-list. Update the number of + ** fragmented bytes within the page. */ + memcpy(&data[addr], &data[pc], 2); + data[hdr+7] = (u8)(nFrag + x); + }else if( size+pc > usableSize ){ + return SQLITE_CORRUPT_BKPT; + }else{ + /* The slot remains on the free-list. Reduce its size to account + ** for the portion used by the new allocation. */ + put2byte(&data[pc+2], x); + } + *pIdx = pc + x; + return SQLITE_OK; + } + } + } + + /* Check to make sure there is enough space in the gap to satisfy + ** the allocation. If not, defragment. + */ + testcase( gap+2+nByte==top ); + if( gap+2+nByte>top ){ + rc = defragmentPage(pPage); + if( rc ) return rc; + top = get2byteNotZero(&data[hdr+5]); + assert( gap+nByte<=top ); + } + + + /* Allocate memory from the gap in between the cell pointer array + ** and the cell content area. The btreeInitPage() call has already + ** validated the freelist. Given that the freelist is valid, there + ** is no way that the allocation can extend off the end of the page. + ** The assert() below verifies the previous sentence. + */ + top -= nByte; + put2byte(&data[hdr+5], top); + assert( top+nByte <= (int)pPage->pBt->usableSize ); + *pIdx = top; + return SQLITE_OK; +} + +/* +** Return a section of the pPage->aData to the freelist. +** The first byte of the new free block is pPage->aDisk[start] +** and the size of the block is "size" bytes. +** +** Most of the effort here is involved in coalesing adjacent +** free blocks into a single big free block. +*/ +static int freeSpace(MemPage *pPage, int start, int size){ + int addr, pbegin, hdr; + int iLast; /* Largest possible freeblock offset */ + unsigned char *data = pPage->aData; + + assert( pPage->pBt!=0 ); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( start>=pPage->hdrOffset+6+pPage->childPtrSize ); + assert( (start + size) <= (int)pPage->pBt->usableSize ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( size>=0 ); /* Minimum cell size is 4 */ + + if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){ + /* Overwrite deleted information with zeros when the secure_delete + ** option is enabled */ + memset(&data[start], 0, size); + } + + /* Add the space back into the linked list of freeblocks. Note that + ** even though the freeblock list was checked by btreeInitPage(), + ** btreeInitPage() did not detect overlapping cells or + ** freeblocks that overlapped cells. Nor does it detect when the + ** cell content area exceeds the value in the page header. If these + ** situations arise, then subsequent insert operations might corrupt + ** the freelist. So we do need to check for corruption while scanning + ** the freelist. + */ + hdr = pPage->hdrOffset; + addr = hdr + 1; + iLast = pPage->pBt->usableSize - 4; + assert( start<=iLast ); + while( (pbegin = get2byte(&data[addr]))0 ){ + if( pbeginiLast ){ + return SQLITE_CORRUPT_BKPT; + } + assert( pbegin>addr || pbegin==0 ); + put2byte(&data[addr], start); + put2byte(&data[start], pbegin); + put2byte(&data[start+2], size); + pPage->nFree = pPage->nFree + (u16)size; + + /* Coalesce adjacent free blocks */ + addr = hdr + 1; + while( (pbegin = get2byte(&data[addr]))>0 ){ + int pnext, psize, x; + assert( pbegin>addr ); + assert( pbegin <= (int)pPage->pBt->usableSize-4 ); + pnext = get2byte(&data[pbegin]); + psize = get2byte(&data[pbegin+2]); + if( pbegin + psize + 3 >= pnext && pnext>0 ){ + int frag = pnext - (pbegin+psize); + if( (frag<0) || (frag>(int)data[hdr+7]) ){ + return SQLITE_CORRUPT_BKPT; + } + data[hdr+7] -= (u8)frag; + x = get2byte(&data[pnext]); + put2byte(&data[pbegin], x); + x = pnext + get2byte(&data[pnext+2]) - pbegin; + put2byte(&data[pbegin+2], x); + }else{ + addr = pbegin; + } + } + + /* If the cell content area begins with a freeblock, remove it. */ + if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){ + int top; + pbegin = get2byte(&data[hdr+1]); + memcpy(&data[hdr+1], &data[pbegin], 2); + top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]); + put2byte(&data[hdr+5], top); + } + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + return SQLITE_OK; +} + +/* +** Decode the flags byte (the first byte of the header) for a page +** and initialize fields of the MemPage structure accordingly. +** +** Only the following combinations are supported. Anything different +** indicates a corrupt database files: +** +** PTF_ZERODATA +** PTF_ZERODATA | PTF_LEAF +** PTF_LEAFDATA | PTF_INTKEY +** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF +*/ +static int decodeFlags(MemPage *pPage, int flagByte){ + BtShared *pBt; /* A copy of pPage->pBt */ + + assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); + flagByte &= ~PTF_LEAF; + pPage->childPtrSize = 4-4*pPage->leaf; + pBt = pPage->pBt; + if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ + pPage->intKey = 1; + pPage->hasData = pPage->leaf; + pPage->maxLocal = pBt->maxLeaf; + pPage->minLocal = pBt->minLeaf; + }else if( flagByte==PTF_ZERODATA ){ + pPage->intKey = 0; + pPage->hasData = 0; + pPage->maxLocal = pBt->maxLocal; + pPage->minLocal = pBt->minLocal; + }else{ + return SQLITE_CORRUPT_BKPT; + } + pPage->max1bytePayload = pBt->max1bytePayload; + return SQLITE_OK; +} + +/* +** Initialize the auxiliary information for a disk block. +** +** Return SQLITE_OK on success. If we see that the page does +** not contain a well-formed database page, then return +** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not +** guarantee that the page is well-formed. It only shows that +** we failed to detect any corruption. +*/ +static int btreeInitPage(MemPage *pPage){ + + assert( pPage->pBt!=0 ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); + assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); + assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); + + if( !pPage->isInit ){ + u16 pc; /* Address of a freeblock within pPage->aData[] */ + u8 hdr; /* Offset to beginning of page header */ + u8 *data; /* Equal to pPage->aData */ + BtShared *pBt; /* The main btree structure */ + int usableSize; /* Amount of usable space on each page */ + u16 cellOffset; /* Offset from start of page to first cell pointer */ + int nFree; /* Number of unused bytes on the page */ + int top; /* First byte of the cell content area */ + int iCellFirst; /* First allowable cell or freeblock offset */ + int iCellLast; /* Last possible cell or freeblock offset */ + + pBt = pPage->pBt; + + hdr = pPage->hdrOffset; + data = pPage->aData; + if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT; + assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); + pPage->maskPage = (u16)(pBt->pageSize - 1); + pPage->nOverflow = 0; + usableSize = pBt->usableSize; + pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf; + pPage->aDataEnd = &data[usableSize]; + pPage->aCellIdx = &data[cellOffset]; + top = get2byteNotZero(&data[hdr+5]); + pPage->nCell = get2byte(&data[hdr+3]); + if( pPage->nCell>MX_CELL(pBt) ){ + /* To many cells for a single page. The page must be corrupt */ + return SQLITE_CORRUPT_BKPT; + } + testcase( pPage->nCell==MX_CELL(pBt) ); + + /* A malformed database page might cause us to read past the end + ** of page when parsing a cell. + ** + ** The following block of code checks early to see if a cell extends + ** past the end of a page boundary and causes SQLITE_CORRUPT to be + ** returned if it does. + */ + iCellFirst = cellOffset + 2*pPage->nCell; + iCellLast = usableSize - 4; +#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) + { + int i; /* Index into the cell pointer array */ + int sz; /* Size of a cell */ + + if( !pPage->leaf ) iCellLast--; + for(i=0; inCell; i++){ + pc = get2byte(&data[cellOffset+i*2]); + testcase( pc==iCellFirst ); + testcase( pc==iCellLast ); + if( pciCellLast ){ + return SQLITE_CORRUPT_BKPT; + } + sz = cellSizePtr(pPage, &data[pc]); + testcase( pc+sz==usableSize ); + if( pc+sz>usableSize ){ + return SQLITE_CORRUPT_BKPT; + } + } + if( !pPage->leaf ) iCellLast++; + } +#endif + + /* Compute the total free space on the page */ + pc = get2byte(&data[hdr+1]); + nFree = data[hdr+7] + top; + while( pc>0 ){ + u16 next, size; + if( pciCellLast ){ + /* Start of free block is off the page */ + return SQLITE_CORRUPT_BKPT; + } + next = get2byte(&data[pc]); + size = get2byte(&data[pc+2]); + if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){ + /* Free blocks must be in ascending order. And the last byte of + ** the free-block must lie on the database page. */ + return SQLITE_CORRUPT_BKPT; + } + nFree = nFree + size; + pc = next; + } + + /* At this point, nFree contains the sum of the offset to the start + ** of the cell-content area plus the number of free bytes within + ** the cell-content area. If this is greater than the usable-size + ** of the page, then the page must be corrupted. This check also + ** serves to verify that the offset to the start of the cell-content + ** area, according to the page header, lies within the page. + */ + if( nFree>usableSize ){ + return SQLITE_CORRUPT_BKPT; + } + pPage->nFree = (u16)(nFree - iCellFirst); + pPage->isInit = 1; + } + return SQLITE_OK; +} + +/* +** Set up a raw page so that it looks like a database page holding +** no entries. +*/ +static void zeroPage(MemPage *pPage, int flags){ + unsigned char *data = pPage->aData; + BtShared *pBt = pPage->pBt; + u8 hdr = pPage->hdrOffset; + u16 first; + + assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); + assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); + assert( sqlite3PagerGetData(pPage->pDbPage) == data ); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( sqlite3_mutex_held(pBt->mutex) ); + if( pBt->btsFlags & BTS_SECURE_DELETE ){ + memset(&data[hdr], 0, pBt->usableSize - hdr); + } + data[hdr] = (char)flags; + first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0); + memset(&data[hdr+1], 0, 4); + data[hdr+7] = 0; + put2byte(&data[hdr+5], pBt->usableSize); + pPage->nFree = (u16)(pBt->usableSize - first); + decodeFlags(pPage, flags); + pPage->hdrOffset = hdr; + pPage->cellOffset = first; + pPage->aDataEnd = &data[pBt->usableSize]; + pPage->aCellIdx = &data[first]; + pPage->nOverflow = 0; + assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); + pPage->maskPage = (u16)(pBt->pageSize - 1); + pPage->nCell = 0; + pPage->isInit = 1; +} + + +/* +** Convert a DbPage obtained from the pager into a MemPage used by +** the btree layer. +*/ +static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ + MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); + pPage->aData = sqlite3PagerGetData(pDbPage); + pPage->pDbPage = pDbPage; + pPage->pBt = pBt; + pPage->pgno = pgno; + pPage->hdrOffset = pPage->pgno==1 ? 100 : 0; + return pPage; +} + +/* +** Get a page from the pager. Initialize the MemPage.pBt and +** MemPage.aData elements if needed. +** +** If the noContent flag is set, it means that we do not care about +** the content of the page at this time. So do not go to the disk +** to fetch the content. Just fill in the content with zeros for now. +** If in the future we call sqlite3PagerWrite() on this page, that +** means we have started to be concerned about content and the disk +** read should occur at that point. +*/ +static int btreeGetPage( + BtShared *pBt, /* The btree */ + Pgno pgno, /* Number of the page to fetch */ + MemPage **ppPage, /* Return the page in this parameter */ + int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ +){ + int rc; + DbPage *pDbPage; + + assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); + assert( sqlite3_mutex_held(pBt->mutex) ); + rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); + if( rc ) return rc; + *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); + return SQLITE_OK; +} + +/* +** Retrieve a page from the pager cache. If the requested page is not +** already in the pager cache return NULL. Initialize the MemPage.pBt and +** MemPage.aData elements if needed. +*/ +static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ + DbPage *pDbPage; + assert( sqlite3_mutex_held(pBt->mutex) ); + pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); + if( pDbPage ){ + return btreePageFromDbPage(pDbPage, pgno, pBt); + } + return 0; +} + +/* +** Return the size of the database file in pages. If there is any kind of +** error, return ((unsigned int)-1). +*/ +static Pgno btreePagecount(BtShared *pBt){ + return pBt->nPage; +} +u32 sqlite3BtreeLastPage(Btree *p){ + assert( sqlite3BtreeHoldsMutex(p) ); + assert( ((p->pBt->nPage)&0x8000000)==0 ); + return (int)btreePagecount(p->pBt); +} + +/* +** Get a page from the pager and initialize it. This routine is just a +** convenience wrapper around separate calls to btreeGetPage() and +** btreeInitPage(). +** +** If an error occurs, then the value *ppPage is set to is undefined. It +** may remain unchanged, or it may be set to an invalid value. +*/ +static int getAndInitPage( + BtShared *pBt, /* The database file */ + Pgno pgno, /* Number of the page to get */ + MemPage **ppPage, /* Write the page pointer here */ + int bReadonly /* PAGER_GET_READONLY or 0 */ +){ + int rc; + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 ); + + if( pgno>btreePagecount(pBt) ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = btreeGetPage(pBt, pgno, ppPage, bReadonly); + if( rc==SQLITE_OK ){ + rc = btreeInitPage(*ppPage); + if( rc!=SQLITE_OK ){ + releasePage(*ppPage); + } + } + } + + testcase( pgno==0 ); + assert( pgno!=0 || rc==SQLITE_CORRUPT ); + return rc; +} + +/* +** Release a MemPage. This should be called once for each prior +** call to btreeGetPage. +*/ +static void releasePage(MemPage *pPage){ + if( pPage ){ + assert( pPage->aData ); + assert( pPage->pBt ); + assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); + assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + sqlite3PagerUnref(pPage->pDbPage); + } +} + +/* +** During a rollback, when the pager reloads information into the cache +** so that the cache is restored to its original state at the start of +** the transaction, for each page restored this routine is called. +** +** This routine needs to reset the extra data section at the end of the +** page to agree with the restored data. +*/ +static void pageReinit(DbPage *pData){ + MemPage *pPage; + pPage = (MemPage *)sqlite3PagerGetExtra(pData); + assert( sqlite3PagerPageRefcount(pData)>0 ); + if( pPage->isInit ){ + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + pPage->isInit = 0; + if( sqlite3PagerPageRefcount(pData)>1 ){ + /* pPage might not be a btree page; it might be an overflow page + ** or ptrmap page or a free page. In those cases, the following + ** call to btreeInitPage() will likely return SQLITE_CORRUPT. + ** But no harm is done by this. And it is very important that + ** btreeInitPage() be called on every btree page so we make + ** the call for every page that comes in for re-initing. */ + btreeInitPage(pPage); + } + } +} + +/* +** Invoke the busy handler for a btree. +*/ +static int btreeInvokeBusyHandler(void *pArg){ + BtShared *pBt = (BtShared*)pArg; + assert( pBt->db ); + assert( sqlite3_mutex_held(pBt->db->mutex) ); + return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); +} + +/* +** Open a database file. +** +** zFilename is the name of the database file. If zFilename is NULL +** then an ephemeral database is created. The ephemeral database might +** be exclusively in memory, or it might use a disk-based memory cache. +** Either way, the ephemeral database will be automatically deleted +** when sqlite3BtreeClose() is called. +** +** If zFilename is ":memory:" then an in-memory database is created +** that is automatically destroyed when it is closed. +** +** The "flags" parameter is a bitmask that might contain bits like +** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. +** +** If the database is already opened in the same database connection +** and we are in shared cache mode, then the open will fail with an +** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared +** objects in the same database connection since doing so will lead +** to problems with locking. +*/ +int sqlite3BtreeOpen( + sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ + const char *zFilename, /* Name of the file containing the BTree database */ + sqlite3 *db, /* Associated database handle */ + Btree **ppBtree, /* Pointer to new Btree object written here */ + int flags, /* Options */ + int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ +){ + BtShared *pBt = 0; /* Shared part of btree structure */ + Btree *p; /* Handle to return */ + sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ + int rc = SQLITE_OK; /* Result code from this function */ + u8 nReserve; /* Byte of unused space on each page */ + unsigned char zDbHeader[100]; /* Database header content */ + + /* True if opening an ephemeral, temporary database */ + const int isTempDb = zFilename==0 || zFilename[0]==0; + + /* Set the variable isMemdb to true for an in-memory database, or + ** false for a file-based database. + */ +#ifdef SQLITE_OMIT_MEMORYDB + const int isMemdb = 0; +#else + const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) + || (isTempDb && sqlite3TempInMemory(db)) + || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; +#endif + + assert( db!=0 ); + assert( pVfs!=0 ); + assert( sqlite3_mutex_held(db->mutex) ); + assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ + + /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ + assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); + + /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ + assert( (flags & BTREE_SINGLE)==0 || isTempDb ); + + if( isMemdb ){ + flags |= BTREE_MEMORY; + } + if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ + vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; + } + p = sqlite3MallocZero(sizeof(Btree)); + if( !p ){ + return SQLITE_NOMEM; + } + p->inTrans = TRANS_NONE; + p->db = db; +#ifndef SQLITE_OMIT_SHARED_CACHE + p->lock.pBtree = p; + p->lock.iTable = 1; +#endif + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) + /* + ** If this Btree is a candidate for shared cache, try to find an + ** existing BtShared object that we can share with + */ + if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ + if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ + int nFullPathname = pVfs->mxPathname+1; + char *zFullPathname = sqlite3Malloc(nFullPathname); + MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) + p->sharable = 1; + if( !zFullPathname ){ + sqlite3_free(p); + return SQLITE_NOMEM; + } + if( isMemdb ){ + memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1); + }else{ + rc = sqlite3OsFullPathname(pVfs, zFilename, + nFullPathname, zFullPathname); + if( rc ){ + sqlite3_free(zFullPathname); + sqlite3_free(p); + return rc; + } + } +#if SQLITE_THREADSAFE + mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); + sqlite3_mutex_enter(mutexOpen); + mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); + sqlite3_mutex_enter(mutexShared); +#endif + for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ + assert( pBt->nRef>0 ); + if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) + && sqlite3PagerVfs(pBt->pPager)==pVfs ){ + int iDb; + for(iDb=db->nDb-1; iDb>=0; iDb--){ + Btree *pExisting = db->aDb[iDb].pBt; + if( pExisting && pExisting->pBt==pBt ){ + sqlite3_mutex_leave(mutexShared); + sqlite3_mutex_leave(mutexOpen); + sqlite3_free(zFullPathname); + sqlite3_free(p); + return SQLITE_CONSTRAINT; + } + } + p->pBt = pBt; + pBt->nRef++; + break; + } + } + sqlite3_mutex_leave(mutexShared); + sqlite3_free(zFullPathname); + } +#ifdef SQLITE_DEBUG + else{ + /* In debug mode, we mark all persistent databases as sharable + ** even when they are not. This exercises the locking code and + ** gives more opportunity for asserts(sqlite3_mutex_held()) + ** statements to find locking problems. + */ + p->sharable = 1; + } +#endif + } +#endif + if( pBt==0 ){ + /* + ** The following asserts make sure that structures used by the btree are + ** the right size. This is to guard against size changes that result + ** when compiling on a different architecture. + */ + assert( sizeof(i64)==8 || sizeof(i64)==4 ); + assert( sizeof(u64)==8 || sizeof(u64)==4 ); + assert( sizeof(u32)==4 ); + assert( sizeof(u16)==2 ); + assert( sizeof(Pgno)==4 ); + + pBt = sqlite3MallocZero( sizeof(*pBt) ); + if( pBt==0 ){ + rc = SQLITE_NOMEM; + goto btree_open_out; + } + rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, + EXTRA_SIZE, flags, vfsFlags, pageReinit); + if( rc==SQLITE_OK ){ + sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); + rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); + } + if( rc!=SQLITE_OK ){ + goto btree_open_out; + } + pBt->openFlags = (u8)flags; + pBt->db = db; + sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); + p->pBt = pBt; + + pBt->pCursor = 0; + pBt->pPage1 = 0; + if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; +#ifdef SQLITE_SECURE_DELETE + pBt->btsFlags |= BTS_SECURE_DELETE; +#endif + pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); + if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE + || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ + pBt->pageSize = 0; +#ifndef SQLITE_OMIT_AUTOVACUUM + /* If the magic name ":memory:" will create an in-memory database, then + ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if + ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if + ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a + ** regular file-name. In this case the auto-vacuum applies as per normal. + */ + if( zFilename && !isMemdb ){ + pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); + pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); + } +#endif + nReserve = 0; + }else{ + nReserve = zDbHeader[20]; + pBt->btsFlags |= BTS_PAGESIZE_FIXED; +#ifndef SQLITE_OMIT_AUTOVACUUM + pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); + pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); +#endif + } + rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); + if( rc ) goto btree_open_out; + pBt->usableSize = pBt->pageSize - nReserve; + assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) + /* Add the new BtShared object to the linked list sharable BtShareds. + */ + if( p->sharable ){ + MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) + pBt->nRef = 1; + MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);) + if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ + pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); + if( pBt->mutex==0 ){ + rc = SQLITE_NOMEM; + db->mallocFailed = 0; + goto btree_open_out; + } + } + sqlite3_mutex_enter(mutexShared); + pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); + GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; + sqlite3_mutex_leave(mutexShared); + } +#endif + } + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) + /* If the new Btree uses a sharable pBtShared, then link the new + ** Btree into the list of all sharable Btrees for the same connection. + ** The list is kept in ascending order by pBt address. + */ + if( p->sharable ){ + int i; + Btree *pSib; + for(i=0; inDb; i++){ + if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ + while( pSib->pPrev ){ pSib = pSib->pPrev; } + if( p->pBtpBt ){ + p->pNext = pSib; + p->pPrev = 0; + pSib->pPrev = p; + }else{ + while( pSib->pNext && pSib->pNext->pBtpBt ){ + pSib = pSib->pNext; + } + p->pNext = pSib->pNext; + p->pPrev = pSib; + if( p->pNext ){ + p->pNext->pPrev = p; + } + pSib->pNext = p; + } + break; + } + } + } +#endif + *ppBtree = p; + +btree_open_out: + if( rc!=SQLITE_OK ){ + if( pBt && pBt->pPager ){ + sqlite3PagerClose(pBt->pPager); + } + sqlite3_free(pBt); + sqlite3_free(p); + *ppBtree = 0; + }else{ + /* If the B-Tree was successfully opened, set the pager-cache size to the + ** default value. Except, when opening on an existing shared pager-cache, + ** do not change the pager-cache size. + */ + if( sqlite3BtreeSchema(p, 0, 0)==0 ){ + sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE); + } + } + if( mutexOpen ){ + assert( sqlite3_mutex_held(mutexOpen) ); + sqlite3_mutex_leave(mutexOpen); + } + return rc; +} + +/* +** Decrement the BtShared.nRef counter. When it reaches zero, +** remove the BtShared structure from the sharing list. Return +** true if the BtShared.nRef counter reaches zero and return +** false if it is still positive. +*/ +static int removeFromSharingList(BtShared *pBt){ +#ifndef SQLITE_OMIT_SHARED_CACHE + MUTEX_LOGIC( sqlite3_mutex *pMaster; ) + BtShared *pList; + int removed = 0; + + assert( sqlite3_mutex_notheld(pBt->mutex) ); + MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + sqlite3_mutex_enter(pMaster); + pBt->nRef--; + if( pBt->nRef<=0 ){ + if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ + GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; + }else{ + pList = GLOBAL(BtShared*,sqlite3SharedCacheList); + while( ALWAYS(pList) && pList->pNext!=pBt ){ + pList=pList->pNext; + } + if( ALWAYS(pList) ){ + pList->pNext = pBt->pNext; + } + } + if( SQLITE_THREADSAFE ){ + sqlite3_mutex_free(pBt->mutex); + } + removed = 1; + } + sqlite3_mutex_leave(pMaster); + return removed; +#else + return 1; +#endif +} + +/* +** Make sure pBt->pTmpSpace points to an allocation of +** MX_CELL_SIZE(pBt) bytes. +*/ +static void allocateTempSpace(BtShared *pBt){ + if( !pBt->pTmpSpace ){ + pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); + + /* One of the uses of pBt->pTmpSpace is to format cells before + ** inserting them into a leaf page (function fillInCell()). If + ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes + ** by the various routines that manipulate binary cells. Which + ** can mean that fillInCell() only initializes the first 2 or 3 + ** bytes of pTmpSpace, but that the first 4 bytes are copied from + ** it into a database page. This is not actually a problem, but it + ** does cause a valgrind error when the 1 or 2 bytes of unitialized + ** data is passed to system call write(). So to avoid this error, + ** zero the first 4 bytes of temp space here. */ + if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4); + } +} + +/* +** Free the pBt->pTmpSpace allocation +*/ +static void freeTempSpace(BtShared *pBt){ + sqlite3PageFree( pBt->pTmpSpace); + pBt->pTmpSpace = 0; +} + +/* +** Close an open database and invalidate all cursors. +*/ +int sqlite3BtreeClose(Btree *p){ + BtShared *pBt = p->pBt; + BtCursor *pCur; + + /* Close all cursors opened via this handle. */ + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + pCur = pBt->pCursor; + while( pCur ){ + BtCursor *pTmp = pCur; + pCur = pCur->pNext; + if( pTmp->pBtree==p ){ + sqlite3BtreeCloseCursor(pTmp); + } + } + + /* Rollback any active transaction and free the handle structure. + ** The call to sqlite3BtreeRollback() drops any table-locks held by + ** this handle. + */ + sqlite3BtreeRollback(p, SQLITE_OK); + sqlite3BtreeLeave(p); + + /* If there are still other outstanding references to the shared-btree + ** structure, return now. The remainder of this procedure cleans + ** up the shared-btree. + */ + assert( p->wantToLock==0 && p->locked==0 ); + if( !p->sharable || removeFromSharingList(pBt) ){ + /* The pBt is no longer on the sharing list, so we can access + ** it without having to hold the mutex. + ** + ** Clean out and delete the BtShared object. + */ + assert( !pBt->pCursor ); + sqlite3PagerClose(pBt->pPager); + if( pBt->xFreeSchema && pBt->pSchema ){ + pBt->xFreeSchema(pBt->pSchema); + } + sqlite3DbFree(0, pBt->pSchema); + freeTempSpace(pBt); + sqlite3_free(pBt); + } + +#ifndef SQLITE_OMIT_SHARED_CACHE + assert( p->wantToLock==0 ); + assert( p->locked==0 ); + if( p->pPrev ) p->pPrev->pNext = p->pNext; + if( p->pNext ) p->pNext->pPrev = p->pPrev; +#endif + + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Change the limit on the number of pages allowed in the cache. +** +** The maximum number of cache pages is set to the absolute +** value of mxPage. If mxPage is negative, the pager will +** operate asynchronously - it will not stop to do fsync()s +** to insure data is written to the disk surface before +** continuing. Transactions still work if synchronous is off, +** and the database cannot be corrupted if this program +** crashes. But if the operating system crashes or there is +** an abrupt power failure when synchronous is off, the database +** could be left in an inconsistent and unrecoverable state. +** Synchronous is on by default so database corruption is not +** normally a worry. +*/ +int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ + BtShared *pBt = p->pBt; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + sqlite3PagerSetCachesize(pBt->pPager, mxPage); + sqlite3BtreeLeave(p); + return SQLITE_OK; +} + +/* +** Change the limit on the amount of the database file that may be +** memory mapped. +*/ +int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ + BtShared *pBt = p->pBt; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); + sqlite3BtreeLeave(p); + return SQLITE_OK; +} + +/* +** Change the way data is synced to disk in order to increase or decrease +** how well the database resists damage due to OS crashes and power +** failures. Level 1 is the same as asynchronous (no syncs() occur and +** there is a high probability of damage) Level 2 is the default. There +** is a very low but non-zero probability of damage. Level 3 reduces the +** probability of damage to near zero but with a write performance reduction. +*/ +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +int sqlite3BtreeSetPagerFlags( + Btree *p, /* The btree to set the safety level on */ + unsigned pgFlags /* Various PAGER_* flags */ +){ + BtShared *pBt = p->pBt; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + sqlite3PagerSetFlags(pBt->pPager, pgFlags); + sqlite3BtreeLeave(p); + return SQLITE_OK; +} +#endif + +/* +** Return TRUE if the given btree is set to safety level 1. In other +** words, return TRUE if no sync() occurs on the disk files. +*/ +int sqlite3BtreeSyncDisabled(Btree *p){ + BtShared *pBt = p->pBt; + int rc; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + assert( pBt && pBt->pPager ); + rc = sqlite3PagerNosync(pBt->pPager); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Change the default pages size and the number of reserved bytes per page. +** Or, if the page size has already been fixed, return SQLITE_READONLY +** without changing anything. +** +** The page size must be a power of 2 between 512 and 65536. If the page +** size supplied does not meet this constraint then the page size is not +** changed. +** +** Page sizes are constrained to be a power of two so that the region +** of the database file used for locking (beginning at PENDING_BYTE, +** the first byte past the 1GB boundary, 0x40000000) needs to occur +** at the beginning of a page. +** +** If parameter nReserve is less than zero, then the number of reserved +** bytes per page is left unchanged. +** +** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size +** and autovacuum mode can no longer be changed. +*/ +int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ + int rc = SQLITE_OK; + BtShared *pBt = p->pBt; + assert( nReserve>=-1 && nReserve<=255 ); + sqlite3BtreeEnter(p); + if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ + sqlite3BtreeLeave(p); + return SQLITE_READONLY; + } + if( nReserve<0 ){ + nReserve = pBt->pageSize - pBt->usableSize; + } + assert( nReserve>=0 && nReserve<=255 ); + if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && + ((pageSize-1)&pageSize)==0 ){ + assert( (pageSize & 7)==0 ); + assert( !pBt->pPage1 && !pBt->pCursor ); + pBt->pageSize = (u32)pageSize; + freeTempSpace(pBt); + } + rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); + pBt->usableSize = pBt->pageSize - (u16)nReserve; + if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Return the currently defined page size +*/ +int sqlite3BtreeGetPageSize(Btree *p){ + return p->pBt->pageSize; +} + +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG) +/* +** This function is similar to sqlite3BtreeGetReserve(), except that it +** may only be called if it is guaranteed that the b-tree mutex is already +** held. +** +** This is useful in one special case in the backup API code where it is +** known that the shared b-tree mutex is held, but the mutex on the +** database handle that owns *p is not. In this case if sqlite3BtreeEnter() +** were to be called, it might collide with some other operation on the +** database handle that owns *p, causing undefined behavior. +*/ +int sqlite3BtreeGetReserveNoMutex(Btree *p){ + assert( sqlite3_mutex_held(p->pBt->mutex) ); + return p->pBt->pageSize - p->pBt->usableSize; +} +#endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */ + +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) +/* +** Return the number of bytes of space at the end of every page that +** are intentually left unused. This is the "reserved" space that is +** sometimes used by extensions. +*/ +int sqlite3BtreeGetReserve(Btree *p){ + int n; + sqlite3BtreeEnter(p); + n = p->pBt->pageSize - p->pBt->usableSize; + sqlite3BtreeLeave(p); + return n; +} + +/* +** Set the maximum page count for a database if mxPage is positive. +** No changes are made if mxPage is 0 or negative. +** Regardless of the value of mxPage, return the maximum page count. +*/ +int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ + int n; + sqlite3BtreeEnter(p); + n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); + sqlite3BtreeLeave(p); + return n; +} + +/* +** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1, +** then make no changes. Always return the value of the BTS_SECURE_DELETE +** setting after the change. +*/ +int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ + int b; + if( p==0 ) return 0; + sqlite3BtreeEnter(p); + if( newFlag>=0 ){ + p->pBt->btsFlags &= ~BTS_SECURE_DELETE; + if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE; + } + b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0; + sqlite3BtreeLeave(p); + return b; +} +#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */ + +/* +** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' +** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it +** is disabled. The default value for the auto-vacuum property is +** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. +*/ +int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ +#ifdef SQLITE_OMIT_AUTOVACUUM + return SQLITE_READONLY; +#else + BtShared *pBt = p->pBt; + int rc = SQLITE_OK; + u8 av = (u8)autoVacuum; + + sqlite3BtreeEnter(p); + if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ + rc = SQLITE_READONLY; + }else{ + pBt->autoVacuum = av ?1:0; + pBt->incrVacuum = av==2 ?1:0; + } + sqlite3BtreeLeave(p); + return rc; +#endif +} + +/* +** Return the value of the 'auto-vacuum' property. If auto-vacuum is +** enabled 1 is returned. Otherwise 0. +*/ +int sqlite3BtreeGetAutoVacuum(Btree *p){ +#ifdef SQLITE_OMIT_AUTOVACUUM + return BTREE_AUTOVACUUM_NONE; +#else + int rc; + sqlite3BtreeEnter(p); + rc = ( + (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: + (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: + BTREE_AUTOVACUUM_INCR + ); + sqlite3BtreeLeave(p); + return rc; +#endif +} + + +/* +** Get a reference to pPage1 of the database file. This will +** also acquire a readlock on that file. +** +** SQLITE_OK is returned on success. If the file is not a +** well-formed database file, then SQLITE_CORRUPT is returned. +** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM +** is returned if we run out of memory. +*/ +static int lockBtree(BtShared *pBt){ + int rc; /* Result code from subfunctions */ + MemPage *pPage1; /* Page 1 of the database file */ + int nPage; /* Number of pages in the database */ + int nPageFile = 0; /* Number of pages in the database file */ + int nPageHeader; /* Number of pages in the database according to hdr */ + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( pBt->pPage1==0 ); + rc = sqlite3PagerSharedLock(pBt->pPager); + if( rc!=SQLITE_OK ) return rc; + rc = btreeGetPage(pBt, 1, &pPage1, 0); + if( rc!=SQLITE_OK ) return rc; + + /* Do some checking to help insure the file we opened really is + ** a valid database file. + */ + nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData); + sqlite3PagerPagecount(pBt->pPager, &nPageFile); + if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ + nPage = nPageFile; + } + if( nPage>0 ){ + u32 pageSize; + u32 usableSize; + u8 *page1 = pPage1->aData; + rc = SQLITE_NOTADB; + if( memcmp(page1, zMagicHeader, 16)!=0 ){ + goto page1_init_failed; + } + +#ifdef SQLITE_OMIT_WAL + if( page1[18]>1 ){ + pBt->btsFlags |= BTS_READ_ONLY; + } + if( page1[19]>1 ){ + goto page1_init_failed; + } +#else + if( page1[18]>2 ){ + pBt->btsFlags |= BTS_READ_ONLY; + } + if( page1[19]>2 ){ + goto page1_init_failed; + } + + /* If the write version is set to 2, this database should be accessed + ** in WAL mode. If the log is not already open, open it now. Then + ** return SQLITE_OK and return without populating BtShared.pPage1. + ** The caller detects this and calls this function again. This is + ** required as the version of page 1 currently in the page1 buffer + ** may not be the latest version - there may be a newer one in the log + ** file. + */ + if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ + int isOpen = 0; + rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); + if( rc!=SQLITE_OK ){ + goto page1_init_failed; + }else if( isOpen==0 ){ + releasePage(pPage1); + return SQLITE_OK; + } + rc = SQLITE_NOTADB; + } +#endif + + /* The maximum embedded fraction must be exactly 25%. And the minimum + ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data. + ** The original design allowed these amounts to vary, but as of + ** version 3.6.0, we require them to be fixed. + */ + if( memcmp(&page1[21], "\100\040\040",3)!=0 ){ + goto page1_init_failed; + } + pageSize = (page1[16]<<8) | (page1[17]<<16); + if( ((pageSize-1)&pageSize)!=0 + || pageSize>SQLITE_MAX_PAGE_SIZE + || pageSize<=256 + ){ + goto page1_init_failed; + } + assert( (pageSize & 7)==0 ); + usableSize = pageSize - page1[20]; + if( (u32)pageSize!=pBt->pageSize ){ + /* After reading the first page of the database assuming a page size + ** of BtShared.pageSize, we have discovered that the page-size is + ** actually pageSize. Unlock the database, leave pBt->pPage1 at + ** zero and return SQLITE_OK. The caller will call this function + ** again with the correct page-size. + */ + releasePage(pPage1); + pBt->usableSize = usableSize; + pBt->pageSize = pageSize; + freeTempSpace(pBt); + rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, + pageSize-usableSize); + return rc; + } + if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){ + rc = SQLITE_CORRUPT_BKPT; + goto page1_init_failed; + } + if( usableSize<480 ){ + goto page1_init_failed; + } + pBt->pageSize = pageSize; + pBt->usableSize = usableSize; +#ifndef SQLITE_OMIT_AUTOVACUUM + pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0); + pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0); +#endif + } + + /* maxLocal is the maximum amount of payload to store locally for + ** a cell. Make sure it is small enough so that at least minFanout + ** cells can will fit on one page. We assume a 10-byte page header. + ** Besides the payload, the cell must store: + ** 2-byte pointer to the cell + ** 4-byte child pointer + ** 9-byte nKey value + ** 4-byte nData value + ** 4-byte overflow page pointer + ** So a cell consists of a 2-byte pointer, a header which is as much as + ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow + ** page pointer. + */ + pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); + pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); + pBt->maxLeaf = (u16)(pBt->usableSize - 35); + pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); + if( pBt->maxLocal>127 ){ + pBt->max1bytePayload = 127; + }else{ + pBt->max1bytePayload = (u8)pBt->maxLocal; + } + assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); + pBt->pPage1 = pPage1; + pBt->nPage = nPage; + return SQLITE_OK; + +page1_init_failed: + releasePage(pPage1); + pBt->pPage1 = 0; + return rc; +} + +#ifndef NDEBUG +/* +** Return the number of cursors open on pBt. This is for use +** in assert() expressions, so it is only compiled if NDEBUG is not +** defined. +** +** Only write cursors are counted if wrOnly is true. If wrOnly is +** false then all cursors are counted. +** +** For the purposes of this routine, a cursor is any cursor that +** is capable of reading or writing to the databse. Cursors that +** have been tripped into the CURSOR_FAULT state are not counted. +*/ +static int countValidCursors(BtShared *pBt, int wrOnly){ + BtCursor *pCur; + int r = 0; + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ + if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++; + } + return r; +} +#endif + +/* +** If there are no outstanding cursors and we are not in the middle +** of a transaction but there is a read lock on the database, then +** this routine unrefs the first page of the database file which +** has the effect of releasing the read lock. +** +** If there is a transaction in progress, this routine is a no-op. +*/ +static void unlockBtreeIfUnused(BtShared *pBt){ + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); + if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ + assert( pBt->pPage1->aData ); + assert( sqlite3PagerRefcount(pBt->pPager)==1 ); + assert( pBt->pPage1->aData ); + releasePage(pBt->pPage1); + pBt->pPage1 = 0; + } +} + +/* +** If pBt points to an empty file then convert that empty file +** into a new empty database by initializing the first page of +** the database. +*/ +static int newDatabase(BtShared *pBt){ + MemPage *pP1; + unsigned char *data; + int rc; + + assert( sqlite3_mutex_held(pBt->mutex) ); + if( pBt->nPage>0 ){ + return SQLITE_OK; + } + pP1 = pBt->pPage1; + assert( pP1!=0 ); + data = pP1->aData; + rc = sqlite3PagerWrite(pP1->pDbPage); + if( rc ) return rc; + memcpy(data, zMagicHeader, sizeof(zMagicHeader)); + assert( sizeof(zMagicHeader)==16 ); + data[16] = (u8)((pBt->pageSize>>8)&0xff); + data[17] = (u8)((pBt->pageSize>>16)&0xff); + data[18] = 1; + data[19] = 1; + assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); + data[20] = (u8)(pBt->pageSize - pBt->usableSize); + data[21] = 64; + data[22] = 32; + data[23] = 32; + memset(&data[24], 0, 100-24); + zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); + pBt->btsFlags |= BTS_PAGESIZE_FIXED; +#ifndef SQLITE_OMIT_AUTOVACUUM + assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); + assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); + put4byte(&data[36 + 4*4], pBt->autoVacuum); + put4byte(&data[36 + 7*4], pBt->incrVacuum); +#endif + pBt->nPage = 1; + data[31] = 1; + return SQLITE_OK; +} + +/* +** Initialize the first page of the database file (creating a database +** consisting of a single page and no schema objects). Return SQLITE_OK +** if successful, or an SQLite error code otherwise. +*/ +int sqlite3BtreeNewDb(Btree *p){ + int rc; + sqlite3BtreeEnter(p); + p->pBt->nPage = 0; + rc = newDatabase(p->pBt); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Attempt to start a new transaction. A write-transaction +** is started if the second argument is nonzero, otherwise a read- +** transaction. If the second argument is 2 or more and exclusive +** transaction is started, meaning that no other process is allowed +** to access the database. A preexisting transaction may not be +** upgraded to exclusive by calling this routine a second time - the +** exclusivity flag only works for a new transaction. +** +** A write-transaction must be started before attempting any +** changes to the database. None of the following routines +** will work unless a transaction is started first: +** +** sqlite3BtreeCreateTable() +** sqlite3BtreeCreateIndex() +** sqlite3BtreeClearTable() +** sqlite3BtreeDropTable() +** sqlite3BtreeInsert() +** sqlite3BtreeDelete() +** sqlite3BtreeUpdateMeta() +** +** If an initial attempt to acquire the lock fails because of lock contention +** and the database was previously unlocked, then invoke the busy handler +** if there is one. But if there was previously a read-lock, do not +** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is +** returned when there is already a read-lock in order to avoid a deadlock. +** +** Suppose there are two processes A and B. A has a read lock and B has +** a reserved lock. B tries to promote to exclusive but is blocked because +** of A's read lock. A tries to promote to reserved but is blocked by B. +** One or the other of the two processes must give way or there can be +** no progress. By returning SQLITE_BUSY and not invoking the busy callback +** when A already has a read lock, we encourage A to give up and let B +** proceed. +*/ +int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ + sqlite3 *pBlock = 0; + BtShared *pBt = p->pBt; + int rc = SQLITE_OK; + + sqlite3BtreeEnter(p); + btreeIntegrity(p); + + /* If the btree is already in a write-transaction, or it + ** is already in a read-transaction and a read-transaction + ** is requested, this is a no-op. + */ + if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ + goto trans_begun; + } + assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); + + /* Write transactions are not possible on a read-only database */ + if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ + rc = SQLITE_READONLY; + goto trans_begun; + } + +#ifndef SQLITE_OMIT_SHARED_CACHE + /* If another database handle has already opened a write transaction + ** on this shared-btree structure and a second write transaction is + ** requested, return SQLITE_LOCKED. + */ + if( (wrflag && pBt->inTransaction==TRANS_WRITE) + || (pBt->btsFlags & BTS_PENDING)!=0 + ){ + pBlock = pBt->pWriter->db; + }else if( wrflag>1 ){ + BtLock *pIter; + for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ + if( pIter->pBtree!=p ){ + pBlock = pIter->pBtree->db; + break; + } + } + } + if( pBlock ){ + sqlite3ConnectionBlocked(p->db, pBlock); + rc = SQLITE_LOCKED_SHAREDCACHE; + goto trans_begun; + } +#endif + + /* Any read-only or read-write transaction implies a read-lock on + ** page 1. So if some other shared-cache client already has a write-lock + ** on page 1, the transaction cannot be opened. */ + rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); + if( SQLITE_OK!=rc ) goto trans_begun; + + pBt->btsFlags &= ~BTS_INITIALLY_EMPTY; + if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY; + do { + /* Call lockBtree() until either pBt->pPage1 is populated or + ** lockBtree() returns something other than SQLITE_OK. lockBtree() + ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after + ** reading page 1 it discovers that the page-size of the database + ** file is not pBt->pageSize. In this case lockBtree() will update + ** pBt->pageSize to the page-size of the file on disk. + */ + while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); + + if( rc==SQLITE_OK && wrflag ){ + if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ + rc = SQLITE_READONLY; + }else{ + rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db)); + if( rc==SQLITE_OK ){ + rc = newDatabase(pBt); + } + } + } + + if( rc!=SQLITE_OK ){ + unlockBtreeIfUnused(pBt); + } + }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && + btreeInvokeBusyHandler(pBt) ); + + if( rc==SQLITE_OK ){ + if( p->inTrans==TRANS_NONE ){ + pBt->nTransaction++; +#ifndef SQLITE_OMIT_SHARED_CACHE + if( p->sharable ){ + assert( p->lock.pBtree==p && p->lock.iTable==1 ); + p->lock.eLock = READ_LOCK; + p->lock.pNext = pBt->pLock; + pBt->pLock = &p->lock; + } +#endif + } + p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); + if( p->inTrans>pBt->inTransaction ){ + pBt->inTransaction = p->inTrans; + } + if( wrflag ){ + MemPage *pPage1 = pBt->pPage1; +#ifndef SQLITE_OMIT_SHARED_CACHE + assert( !pBt->pWriter ); + pBt->pWriter = p; + pBt->btsFlags &= ~BTS_EXCLUSIVE; + if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE; +#endif + + /* If the db-size header field is incorrect (as it may be if an old + ** client has been writing the database file), update it now. Doing + ** this sooner rather than later means the database size can safely + ** re-read the database size from page 1 if a savepoint or transaction + ** rollback occurs within the transaction. + */ + if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ + rc = sqlite3PagerWrite(pPage1->pDbPage); + if( rc==SQLITE_OK ){ + put4byte(&pPage1->aData[28], pBt->nPage); + } + } + } + } + + +trans_begun: + if( rc==SQLITE_OK && wrflag ){ + /* This call makes sure that the pager has the correct number of + ** open savepoints. If the second parameter is greater than 0 and + ** the sub-journal is not already open, then it will be opened here. + */ + rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint); + } + + btreeIntegrity(p); + sqlite3BtreeLeave(p); + return rc; +} + +#ifndef SQLITE_OMIT_AUTOVACUUM + +/* +** Set the pointer-map entries for all children of page pPage. Also, if +** pPage contains cells that point to overflow pages, set the pointer +** map entries for the overflow pages as well. +*/ +static int setChildPtrmaps(MemPage *pPage){ + int i; /* Counter variable */ + int nCell; /* Number of cells in page pPage */ + int rc; /* Return code */ + BtShared *pBt = pPage->pBt; + u8 isInitOrig = pPage->isInit; + Pgno pgno = pPage->pgno; + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + rc = btreeInitPage(pPage); + if( rc!=SQLITE_OK ){ + goto set_child_ptrmaps_out; + } + nCell = pPage->nCell; + + for(i=0; ileaf ){ + Pgno childPgno = get4byte(pCell); + ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); + } + } + + if( !pPage->leaf ){ + Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); + ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); + } + +set_child_ptrmaps_out: + pPage->isInit = isInitOrig; + return rc; +} + +/* +** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so +** that it points to iTo. Parameter eType describes the type of pointer to +** be modified, as follows: +** +** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child +** page of pPage. +** +** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow +** page pointed to by one of the cells on pPage. +** +** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next +** overflow page in the list. +*/ +static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + if( eType==PTRMAP_OVERFLOW2 ){ + /* The pointer is always the first 4 bytes of the page in this case. */ + if( get4byte(pPage->aData)!=iFrom ){ + return SQLITE_CORRUPT_BKPT; + } + put4byte(pPage->aData, iTo); + }else{ + u8 isInitOrig = pPage->isInit; + int i; + int nCell; + + btreeInitPage(pPage); + nCell = pPage->nCell; + + for(i=0; iaData+pPage->maskPage + && iFrom==get4byte(&pCell[info.iOverflow]) + ){ + put4byte(&pCell[info.iOverflow], iTo); + break; + } + }else{ + if( get4byte(pCell)==iFrom ){ + put4byte(pCell, iTo); + break; + } + } + } + + if( i==nCell ){ + if( eType!=PTRMAP_BTREE || + get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ + return SQLITE_CORRUPT_BKPT; + } + put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); + } + + pPage->isInit = isInitOrig; + } + return SQLITE_OK; +} + + +/* +** Move the open database page pDbPage to location iFreePage in the +** database. The pDbPage reference remains valid. +** +** The isCommit flag indicates that there is no need to remember that +** the journal needs to be sync()ed before database page pDbPage->pgno +** can be written to. The caller has already promised not to write to that +** page. +*/ +static int relocatePage( + BtShared *pBt, /* Btree */ + MemPage *pDbPage, /* Open page to move */ + u8 eType, /* Pointer map 'type' entry for pDbPage */ + Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ + Pgno iFreePage, /* The location to move pDbPage to */ + int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ +){ + MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ + Pgno iDbPage = pDbPage->pgno; + Pager *pPager = pBt->pPager; + int rc; + + assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || + eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( pDbPage->pBt==pBt ); + + /* Move page iDbPage from its current location to page number iFreePage */ + TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", + iDbPage, iFreePage, iPtrPage, eType)); + rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); + if( rc!=SQLITE_OK ){ + return rc; + } + pDbPage->pgno = iFreePage; + + /* If pDbPage was a btree-page, then it may have child pages and/or cells + ** that point to overflow pages. The pointer map entries for all these + ** pages need to be changed. + ** + ** If pDbPage is an overflow page, then the first 4 bytes may store a + ** pointer to a subsequent overflow page. If this is the case, then + ** the pointer map needs to be updated for the subsequent overflow page. + */ + if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){ + rc = setChildPtrmaps(pDbPage); + if( rc!=SQLITE_OK ){ + return rc; + } + }else{ + Pgno nextOvfl = get4byte(pDbPage->aData); + if( nextOvfl!=0 ){ + ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc); + if( rc!=SQLITE_OK ){ + return rc; + } + } + } + + /* Fix the database pointer on page iPtrPage that pointed at iDbPage so + ** that it points at iFreePage. Also fix the pointer map entry for + ** iPtrPage. + */ + if( eType!=PTRMAP_ROOTPAGE ){ + rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + rc = sqlite3PagerWrite(pPtrPage->pDbPage); + if( rc!=SQLITE_OK ){ + releasePage(pPtrPage); + return rc; + } + rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); + releasePage(pPtrPage); + if( rc==SQLITE_OK ){ + ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); + } + } + return rc; +} + +/* Forward declaration required by incrVacuumStep(). */ +static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); + +/* +** Perform a single step of an incremental-vacuum. If successful, return +** SQLITE_OK. If there is no work to do (and therefore no point in +** calling this function again), return SQLITE_DONE. Or, if an error +** occurs, return some other error code. +** +** More specificly, this function attempts to re-organize the database so +** that the last page of the file currently in use is no longer in use. +** +** Parameter nFin is the number of pages that this database would contain +** were this function called until it returns SQLITE_DONE. +** +** If the bCommit parameter is non-zero, this function assumes that the +** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE +** or an error. bCommit is passed true for an auto-vacuum-on-commmit +** operation, or false for an incremental vacuum. +*/ +static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ + Pgno nFreeList; /* Number of pages still on the free-list */ + int rc; + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( iLastPg>nFin ); + + if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ + u8 eType; + Pgno iPtrPage; + + nFreeList = get4byte(&pBt->pPage1->aData[36]); + if( nFreeList==0 ){ + return SQLITE_DONE; + } + + rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); + if( rc!=SQLITE_OK ){ + return rc; + } + if( eType==PTRMAP_ROOTPAGE ){ + return SQLITE_CORRUPT_BKPT; + } + + if( eType==PTRMAP_FREEPAGE ){ + if( bCommit==0 ){ + /* Remove the page from the files free-list. This is not required + ** if bCommit is non-zero. In that case, the free-list will be + ** truncated to zero after this function returns, so it doesn't + ** matter if it still contains some garbage entries. + */ + Pgno iFreePg; + MemPage *pFreePg; + rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT); + if( rc!=SQLITE_OK ){ + return rc; + } + assert( iFreePg==iLastPg ); + releasePage(pFreePg); + } + } else { + Pgno iFreePg; /* Index of free page to move pLastPg to */ + MemPage *pLastPg; + u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */ + Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ + + rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + + /* If bCommit is zero, this loop runs exactly once and page pLastPg + ** is swapped with the first free page pulled off the free list. + ** + ** On the other hand, if bCommit is greater than zero, then keep + ** looping until a free-page located within the first nFin pages + ** of the file is found. + */ + if( bCommit==0 ){ + eMode = BTALLOC_LE; + iNear = nFin; + } + do { + MemPage *pFreePg; + rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); + if( rc!=SQLITE_OK ){ + releasePage(pLastPg); + return rc; + } + releasePage(pFreePg); + }while( bCommit && iFreePg>nFin ); + assert( iFreePgbDoTruncate = 1; + pBt->nPage = iLastPg; + } + return SQLITE_OK; +} + +/* +** The database opened by the first argument is an auto-vacuum database +** nOrig pages in size containing nFree free pages. Return the expected +** size of the database in pages following an auto-vacuum operation. +*/ +static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ + int nEntry; /* Number of entries on one ptrmap page */ + Pgno nPtrmap; /* Number of PtrMap pages to be freed */ + Pgno nFin; /* Return value */ + + nEntry = pBt->usableSize/5; + nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; + nFin = nOrig - nFree - nPtrmap; + if( nOrig>PENDING_BYTE_PAGE(pBt) && nFinpBt; + + sqlite3BtreeEnter(p); + assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); + if( !pBt->autoVacuum ){ + rc = SQLITE_DONE; + }else{ + Pgno nOrig = btreePagecount(pBt); + Pgno nFree = get4byte(&pBt->pPage1->aData[36]); + Pgno nFin = finalDbSize(pBt, nOrig, nFree); + + if( nOrig0 ){ + rc = saveAllCursors(pBt, 0, 0); + if( rc==SQLITE_OK ){ + invalidateAllOverflowCache(pBt); + rc = incrVacuumStep(pBt, nFin, nOrig, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + put4byte(&pBt->pPage1->aData[28], pBt->nPage); + } + }else{ + rc = SQLITE_DONE; + } + } + sqlite3BtreeLeave(p); + return rc; +} + +/* +** This routine is called prior to sqlite3PagerCommit when a transaction +** is committed for an auto-vacuum database. +** +** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages +** the database file should be truncated to during the commit process. +** i.e. the database has been reorganized so that only the first *pnTrunc +** pages are in use. +*/ +static int autoVacuumCommit(BtShared *pBt){ + int rc = SQLITE_OK; + Pager *pPager = pBt->pPager; + VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) ); + + assert( sqlite3_mutex_held(pBt->mutex) ); + invalidateAllOverflowCache(pBt); + assert(pBt->autoVacuum); + if( !pBt->incrVacuum ){ + Pgno nFin; /* Number of pages in database after autovacuuming */ + Pgno nFree; /* Number of pages on the freelist initially */ + Pgno iFree; /* The next page to be freed */ + Pgno nOrig; /* Database size before freeing */ + + nOrig = btreePagecount(pBt); + if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ + /* It is not possible to create a database for which the final page + ** is either a pointer-map page or the pending-byte page. If one + ** is encountered, this indicates corruption. + */ + return SQLITE_CORRUPT_BKPT; + } + + nFree = get4byte(&pBt->pPage1->aData[36]); + nFin = finalDbSize(pBt, nOrig, nFree); + if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; + if( nFinnFin && rc==SQLITE_OK; iFree--){ + rc = incrVacuumStep(pBt, nFin, iFree, 1); + } + if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + put4byte(&pBt->pPage1->aData[32], 0); + put4byte(&pBt->pPage1->aData[36], 0); + put4byte(&pBt->pPage1->aData[28], nFin); + pBt->bDoTruncate = 1; + pBt->nPage = nFin; + } + if( rc!=SQLITE_OK ){ + sqlite3PagerRollback(pPager); + } + } + + assert( nRef>=sqlite3PagerRefcount(pPager) ); + return rc; +} + +#else /* ifndef SQLITE_OMIT_AUTOVACUUM */ +# define setChildPtrmaps(x) SQLITE_OK +#endif + +/* +** This routine does the first phase of a two-phase commit. This routine +** causes a rollback journal to be created (if it does not already exist) +** and populated with enough information so that if a power loss occurs +** the database can be restored to its original state by playing back +** the journal. Then the contents of the journal are flushed out to +** the disk. After the journal is safely on oxide, the changes to the +** database are written into the database file and flushed to oxide. +** At the end of this call, the rollback journal still exists on the +** disk and we are still holding all locks, so the transaction has not +** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the +** commit process. +** +** This call is a no-op if no write-transaction is currently active on pBt. +** +** Otherwise, sync the database file for the btree pBt. zMaster points to +** the name of a master journal file that should be written into the +** individual journal file, or is NULL, indicating no master journal file +** (single database transaction). +** +** When this is called, the master journal should already have been +** created, populated with this journal pointer and synced to disk. +** +** Once this is routine has returned, the only thing required to commit +** the write-transaction for this database file is to delete the journal. +*/ +int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ + int rc = SQLITE_OK; + if( p->inTrans==TRANS_WRITE ){ + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum ){ + rc = autoVacuumCommit(pBt); + if( rc!=SQLITE_OK ){ + sqlite3BtreeLeave(p); + return rc; + } + } + if( pBt->bDoTruncate ){ + sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); + } +#endif + rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); + sqlite3BtreeLeave(p); + } + return rc; +} + +/* +** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() +** at the conclusion of a transaction. +*/ +static void btreeEndTransaction(Btree *p){ + BtShared *pBt = p->pBt; + sqlite3 *db = p->db; + assert( sqlite3BtreeHoldsMutex(p) ); + +#ifndef SQLITE_OMIT_AUTOVACUUM + pBt->bDoTruncate = 0; +#endif + if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){ + /* If there are other active statements that belong to this database + ** handle, downgrade to a read-only transaction. The other statements + ** may still be reading from the database. */ + downgradeAllSharedCacheTableLocks(p); + p->inTrans = TRANS_READ; + }else{ + /* If the handle had any kind of transaction open, decrement the + ** transaction count of the shared btree. If the transaction count + ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() + ** call below will unlock the pager. */ + if( p->inTrans!=TRANS_NONE ){ + clearAllSharedCacheTableLocks(p); + pBt->nTransaction--; + if( 0==pBt->nTransaction ){ + pBt->inTransaction = TRANS_NONE; + } + } + + /* Set the current transaction state to TRANS_NONE and unlock the + ** pager if this call closed the only read or write transaction. */ + p->inTrans = TRANS_NONE; + unlockBtreeIfUnused(pBt); + } + + btreeIntegrity(p); +} + +/* +** Commit the transaction currently in progress. +** +** This routine implements the second phase of a 2-phase commit. The +** sqlite3BtreeCommitPhaseOne() routine does the first phase and should +** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() +** routine did all the work of writing information out to disk and flushing the +** contents so that they are written onto the disk platter. All this +** routine has to do is delete or truncate or zero the header in the +** the rollback journal (which causes the transaction to commit) and +** drop locks. +** +** Normally, if an error occurs while the pager layer is attempting to +** finalize the underlying journal file, this function returns an error and +** the upper layer will attempt a rollback. However, if the second argument +** is non-zero then this b-tree transaction is part of a multi-file +** transaction. In this case, the transaction has already been committed +** (by deleting a master journal file) and the caller will ignore this +** functions return code. So, even if an error occurs in the pager layer, +** reset the b-tree objects internal state to indicate that the write +** transaction has been closed. This is quite safe, as the pager will have +** transitioned to the error state. +** +** This will release the write lock on the database file. If there +** are no active cursors, it also releases the read lock. +*/ +int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ + + if( p->inTrans==TRANS_NONE ) return SQLITE_OK; + sqlite3BtreeEnter(p); + btreeIntegrity(p); + + /* If the handle has a write-transaction open, commit the shared-btrees + ** transaction and set the shared state to TRANS_READ. + */ + if( p->inTrans==TRANS_WRITE ){ + int rc; + BtShared *pBt = p->pBt; + assert( pBt->inTransaction==TRANS_WRITE ); + assert( pBt->nTransaction>0 ); + rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); + if( rc!=SQLITE_OK && bCleanup==0 ){ + sqlite3BtreeLeave(p); + return rc; + } + pBt->inTransaction = TRANS_READ; + btreeClearHasContent(pBt); + } + + btreeEndTransaction(p); + sqlite3BtreeLeave(p); + return SQLITE_OK; +} + +/* +** Do both phases of a commit. +*/ +int sqlite3BtreeCommit(Btree *p){ + int rc; + sqlite3BtreeEnter(p); + rc = sqlite3BtreeCommitPhaseOne(p, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeCommitPhaseTwo(p, 0); + } + sqlite3BtreeLeave(p); + return rc; +} + +/* +** This routine sets the state to CURSOR_FAULT and the error +** code to errCode for every cursor on BtShared that pBtree +** references. +** +** Every cursor is tripped, including cursors that belong +** to other database connections that happen to be sharing +** the cache with pBtree. +** +** This routine gets called when a rollback occurs. +** All cursors using the same cache must be tripped +** to prevent them from trying to use the btree after +** the rollback. The rollback may have deleted tables +** or moved root pages, so it is not sufficient to +** save the state of the cursor. The cursor must be +** invalidated. +*/ +void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){ + BtCursor *p; + if( pBtree==0 ) return; + sqlite3BtreeEnter(pBtree); + for(p=pBtree->pBt->pCursor; p; p=p->pNext){ + int i; + sqlite3BtreeClearCursor(p); + p->eState = CURSOR_FAULT; + p->skipNext = errCode; + for(i=0; i<=p->iPage; i++){ + releasePage(p->apPage[i]); + p->apPage[i] = 0; + } + } + sqlite3BtreeLeave(pBtree); +} + +/* +** Rollback the transaction in progress. All cursors will be +** invalided by this operation. Any attempt to use a cursor +** that was open at the beginning of this operation will result +** in an error. +** +** This will release the write lock on the database file. If there +** are no active cursors, it also releases the read lock. +*/ +int sqlite3BtreeRollback(Btree *p, int tripCode){ + int rc; + BtShared *pBt = p->pBt; + MemPage *pPage1; + + sqlite3BtreeEnter(p); + if( tripCode==SQLITE_OK ){ + rc = tripCode = saveAllCursors(pBt, 0, 0); + }else{ + rc = SQLITE_OK; + } + if( tripCode ){ + sqlite3BtreeTripAllCursors(p, tripCode); + } + btreeIntegrity(p); + + if( p->inTrans==TRANS_WRITE ){ + int rc2; + + assert( TRANS_WRITE==pBt->inTransaction ); + rc2 = sqlite3PagerRollback(pBt->pPager); + if( rc2!=SQLITE_OK ){ + rc = rc2; + } + + /* The rollback may have destroyed the pPage1->aData value. So + ** call btreeGetPage() on page 1 again to make + ** sure pPage1->aData is set correctly. */ + if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ + int nPage = get4byte(28+(u8*)pPage1->aData); + testcase( nPage==0 ); + if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); + testcase( pBt->nPage!=nPage ); + pBt->nPage = nPage; + releasePage(pPage1); + } + assert( countValidCursors(pBt, 1)==0 ); + pBt->inTransaction = TRANS_READ; + btreeClearHasContent(pBt); + } + + btreeEndTransaction(p); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Start a statement subtransaction. The subtransaction can can be rolled +** back independently of the main transaction. You must start a transaction +** before starting a subtransaction. The subtransaction is ended automatically +** if the main transaction commits or rolls back. +** +** Statement subtransactions are used around individual SQL statements +** that are contained within a BEGIN...COMMIT block. If a constraint +** error occurs within the statement, the effect of that one statement +** can be rolled back without having to rollback the entire transaction. +** +** A statement sub-transaction is implemented as an anonymous savepoint. The +** value passed as the second parameter is the total number of savepoints, +** including the new anonymous savepoint, open on the B-Tree. i.e. if there +** are no active savepoints and no other statement-transactions open, +** iStatement is 1. This anonymous savepoint can be released or rolled back +** using the sqlite3BtreeSavepoint() function. +*/ +int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ + int rc; + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); + assert( p->inTrans==TRANS_WRITE ); + assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); + assert( iStatement>0 ); + assert( iStatement>p->db->nSavepoint ); + assert( pBt->inTransaction==TRANS_WRITE ); + /* At the pager level, a statement transaction is a savepoint with + ** an index greater than all savepoints created explicitly using + ** SQL statements. It is illegal to open, release or rollback any + ** such savepoints while the statement transaction savepoint is active. + */ + rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** The second argument to this function, op, is always SAVEPOINT_ROLLBACK +** or SAVEPOINT_RELEASE. This function either releases or rolls back the +** savepoint identified by parameter iSavepoint, depending on the value +** of op. +** +** Normally, iSavepoint is greater than or equal to zero. However, if op is +** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the +** contents of the entire transaction are rolled back. This is different +** from a normal transaction rollback, as no locks are released and the +** transaction remains open. +*/ +int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ + int rc = SQLITE_OK; + if( p && p->inTrans==TRANS_WRITE ){ + BtShared *pBt = p->pBt; + assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); + assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); + sqlite3BtreeEnter(p); + rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); + if( rc==SQLITE_OK ){ + if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ + pBt->nPage = 0; + } + rc = newDatabase(pBt); + pBt->nPage = get4byte(28 + pBt->pPage1->aData); + + /* The database size was written into the offset 28 of the header + ** when the transaction started, so we know that the value at offset + ** 28 is nonzero. */ + assert( pBt->nPage>0 ); + } + sqlite3BtreeLeave(p); + } + return rc; +} + +/* +** Create a new cursor for the BTree whose root is on the page +** iTable. If a read-only cursor is requested, it is assumed that +** the caller already has at least a read-only transaction open +** on the database already. If a write-cursor is requested, then +** the caller is assumed to have an open write transaction. +** +** If wrFlag==0, then the cursor can only be used for reading. +** If wrFlag==1, then the cursor can be used for reading or for +** writing if other conditions for writing are also met. These +** are the conditions that must be met in order for writing to +** be allowed: +** +** 1: The cursor must have been opened with wrFlag==1 +** +** 2: Other database connections that share the same pager cache +** but which are not in the READ_UNCOMMITTED state may not have +** cursors open with wrFlag==0 on the same table. Otherwise +** the changes made by this write cursor would be visible to +** the read cursors in the other database connection. +** +** 3: The database must be writable (not on read-only media) +** +** 4: There must be an active transaction. +** +** No checking is done to make sure that page iTable really is the +** root page of a b-tree. If it is not, then the cursor acquired +** will not work correctly. +** +** It is assumed that the sqlite3BtreeCursorZero() has been called +** on pCur to initialize the memory space prior to invoking this routine. +*/ +static int btreeCursor( + Btree *p, /* The btree */ + int iTable, /* Root page of table to open */ + int wrFlag, /* 1 to write. 0 read-only */ + struct KeyInfo *pKeyInfo, /* First arg to comparison function */ + BtCursor *pCur /* Space for new cursor */ +){ + BtShared *pBt = p->pBt; /* Shared b-tree handle */ + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( wrFlag==0 || wrFlag==1 ); + + /* The following assert statements verify that if this is a sharable + ** b-tree database, the connection is holding the required table locks, + ** and that no other connection has any open cursor that conflicts with + ** this lock. */ + assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) ); + assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); + + /* Assert that the caller has opened the required transaction. */ + assert( p->inTrans>TRANS_NONE ); + assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); + assert( pBt->pPage1 && pBt->pPage1->aData ); + + if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){ + return SQLITE_READONLY; + } + if( iTable==1 && btreePagecount(pBt)==0 ){ + assert( wrFlag==0 ); + iTable = 0; + } + + /* Now that no other errors can occur, finish filling in the BtCursor + ** variables and link the cursor into the BtShared list. */ + pCur->pgnoRoot = (Pgno)iTable; + pCur->iPage = -1; + pCur->pKeyInfo = pKeyInfo; + pCur->pBtree = p; + pCur->pBt = pBt; + pCur->wrFlag = (u8)wrFlag; + pCur->pNext = pBt->pCursor; + if( pCur->pNext ){ + pCur->pNext->pPrev = pCur; + } + pBt->pCursor = pCur; + pCur->eState = CURSOR_INVALID; + pCur->cachedRowid = 0; + return SQLITE_OK; +} +int sqlite3BtreeCursor( + Btree *p, /* The btree */ + int iTable, /* Root page of table to open */ + int wrFlag, /* 1 to write. 0 read-only */ + struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ + BtCursor *pCur /* Write new cursor here */ +){ + int rc; + sqlite3BtreeEnter(p); + rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Return the size of a BtCursor object in bytes. +** +** This interfaces is needed so that users of cursors can preallocate +** sufficient storage to hold a cursor. The BtCursor object is opaque +** to users so they cannot do the sizeof() themselves - they must call +** this routine. +*/ +int sqlite3BtreeCursorSize(void){ + return ROUND8(sizeof(BtCursor)); +} + +/* +** Initialize memory that will be converted into a BtCursor object. +** +** The simple approach here would be to memset() the entire object +** to zero. But it turns out that the apPage[] and aiIdx[] arrays +** do not need to be zeroed and they are large, so we can save a lot +** of run-time by skipping the initialization of those elements. +*/ +void sqlite3BtreeCursorZero(BtCursor *p){ + memset(p, 0, offsetof(BtCursor, iPage)); +} + +/* +** Set the cached rowid value of every cursor in the same database file +** as pCur and having the same root page number as pCur. The value is +** set to iRowid. +** +** Only positive rowid values are considered valid for this cache. +** The cache is initialized to zero, indicating an invalid cache. +** A btree will work fine with zero or negative rowids. We just cannot +** cache zero or negative rowids, which means tables that use zero or +** negative rowids might run a little slower. But in practice, zero +** or negative rowids are very uncommon so this should not be a problem. +*/ +void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){ + BtCursor *p; + for(p=pCur->pBt->pCursor; p; p=p->pNext){ + if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid; + } + assert( pCur->cachedRowid==iRowid ); +} + +/* +** Return the cached rowid for the given cursor. A negative or zero +** return value indicates that the rowid cache is invalid and should be +** ignored. If the rowid cache has never before been set, then a +** zero is returned. +*/ +sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){ + return pCur->cachedRowid; +} + +/* +** Close a cursor. The read lock on the database file is released +** when the last cursor is closed. +*/ +int sqlite3BtreeCloseCursor(BtCursor *pCur){ + Btree *pBtree = pCur->pBtree; + if( pBtree ){ + int i; + BtShared *pBt = pCur->pBt; + sqlite3BtreeEnter(pBtree); + sqlite3BtreeClearCursor(pCur); + if( pCur->pPrev ){ + pCur->pPrev->pNext = pCur->pNext; + }else{ + pBt->pCursor = pCur->pNext; + } + if( pCur->pNext ){ + pCur->pNext->pPrev = pCur->pPrev; + } + for(i=0; i<=pCur->iPage; i++){ + releasePage(pCur->apPage[i]); + } + unlockBtreeIfUnused(pBt); + invalidateOverflowCache(pCur); + /* sqlite3_free(pCur); */ + sqlite3BtreeLeave(pBtree); + } + return SQLITE_OK; +} + +/* +** Make sure the BtCursor* given in the argument has a valid +** BtCursor.info structure. If it is not already valid, call +** btreeParseCell() to fill it in. +** +** BtCursor.info is a cache of the information in the current cell. +** Using this cache reduces the number of calls to btreeParseCell(). +** +** 2007-06-25: There is a bug in some versions of MSVC that cause the +** compiler to crash when getCellInfo() is implemented as a macro. +** But there is a measureable speed advantage to using the macro on gcc +** (when less compiler optimizations like -Os or -O0 are used and the +** compiler is not doing agressive inlining.) So we use a real function +** for MSVC and a macro for everything else. Ticket #2457. +*/ +#ifndef NDEBUG + static void assertCellInfo(BtCursor *pCur){ + CellInfo info; + int iPage = pCur->iPage; + memset(&info, 0, sizeof(info)); + btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info); + assert( memcmp(&info, &pCur->info, sizeof(info))==0 ); + } +#else + #define assertCellInfo(x) +#endif +#ifdef _MSC_VER + /* Use a real function in MSVC to work around bugs in that compiler. */ + static void getCellInfo(BtCursor *pCur){ + if( pCur->info.nSize==0 ){ + int iPage = pCur->iPage; + btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); + pCur->validNKey = 1; + }else{ + assertCellInfo(pCur); + } + } +#else /* if not _MSC_VER */ + /* Use a macro in all other compilers so that the function is inlined */ +#define getCellInfo(pCur) \ + if( pCur->info.nSize==0 ){ \ + int iPage = pCur->iPage; \ + btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \ + pCur->validNKey = 1; \ + }else{ \ + assertCellInfo(pCur); \ + } +#endif /* _MSC_VER */ + +#ifndef NDEBUG /* The next routine used only within assert() statements */ +/* +** Return true if the given BtCursor is valid. A valid cursor is one +** that is currently pointing to a row in a (non-empty) table. +** This is a verification routine is used only within assert() statements. +*/ +int sqlite3BtreeCursorIsValid(BtCursor *pCur){ + return pCur && pCur->eState==CURSOR_VALID; +} +#endif /* NDEBUG */ + +/* +** Set *pSize to the size of the buffer needed to hold the value of +** the key for the current entry. If the cursor is not pointing +** to a valid entry, *pSize is set to 0. +** +** For a table with the INTKEY flag set, this routine returns the key +** itself, not the number of bytes in the key. +** +** The caller must position the cursor prior to invoking this routine. +** +** This routine cannot fail. It always returns SQLITE_OK. +*/ +int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID ); + if( pCur->eState!=CURSOR_VALID ){ + *pSize = 0; + }else{ + getCellInfo(pCur); + *pSize = pCur->info.nKey; + } + return SQLITE_OK; +} + +/* +** Set *pSize to the number of bytes of data in the entry the +** cursor currently points to. +** +** The caller must guarantee that the cursor is pointing to a non-NULL +** valid entry. In other words, the calling procedure must guarantee +** that the cursor has Cursor.eState==CURSOR_VALID. +** +** Failure is not possible. This function always returns SQLITE_OK. +** It might just as well be a procedure (returning void) but we continue +** to return an integer result code for historical reasons. +*/ +int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + getCellInfo(pCur); + *pSize = pCur->info.nData; + return SQLITE_OK; +} + +/* +** Given the page number of an overflow page in the database (parameter +** ovfl), this function finds the page number of the next page in the +** linked list of overflow pages. If possible, it uses the auto-vacuum +** pointer-map data instead of reading the content of page ovfl to do so. +** +** If an error occurs an SQLite error code is returned. Otherwise: +** +** The page number of the next overflow page in the linked list is +** written to *pPgnoNext. If page ovfl is the last page in its linked +** list, *pPgnoNext is set to zero. +** +** If ppPage is not NULL, and a reference to the MemPage object corresponding +** to page number pOvfl was obtained, then *ppPage is set to point to that +** reference. It is the responsibility of the caller to call releasePage() +** on *ppPage to free the reference. In no reference was obtained (because +** the pointer-map was used to obtain the value for *pPgnoNext), then +** *ppPage is set to zero. +*/ +static int getOverflowPage( + BtShared *pBt, /* The database file */ + Pgno ovfl, /* Current overflow page number */ + MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */ + Pgno *pPgnoNext /* OUT: Next overflow page number */ +){ + Pgno next = 0; + MemPage *pPage = 0; + int rc = SQLITE_OK; + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert(pPgnoNext); + +#ifndef SQLITE_OMIT_AUTOVACUUM + /* Try to find the next page in the overflow list using the + ** autovacuum pointer-map pages. Guess that the next page in + ** the overflow list is page number (ovfl+1). If that guess turns + ** out to be wrong, fall back to loading the data of page + ** number ovfl to determine the next page number. + */ + if( pBt->autoVacuum ){ + Pgno pgno; + Pgno iGuess = ovfl+1; + u8 eType; + + while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){ + iGuess++; + } + + if( iGuess<=btreePagecount(pBt) ){ + rc = ptrmapGet(pBt, iGuess, &eType, &pgno); + if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ + next = iGuess; + rc = SQLITE_DONE; + } + } + } +#endif + + assert( next==0 || rc==SQLITE_DONE ); + if( rc==SQLITE_OK ){ + rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0); + assert( rc==SQLITE_OK || pPage==0 ); + if( rc==SQLITE_OK ){ + next = get4byte(pPage->aData); + } + } + + *pPgnoNext = next; + if( ppPage ){ + *ppPage = pPage; + }else{ + releasePage(pPage); + } + return (rc==SQLITE_DONE ? SQLITE_OK : rc); +} + +/* +** Copy data from a buffer to a page, or from a page to a buffer. +** +** pPayload is a pointer to data stored on database page pDbPage. +** If argument eOp is false, then nByte bytes of data are copied +** from pPayload to the buffer pointed at by pBuf. If eOp is true, +** then sqlite3PagerWrite() is called on pDbPage and nByte bytes +** of data are copied from the buffer pBuf to pPayload. +** +** SQLITE_OK is returned on success, otherwise an error code. +*/ +static int copyPayload( + void *pPayload, /* Pointer to page data */ + void *pBuf, /* Pointer to buffer */ + int nByte, /* Number of bytes to copy */ + int eOp, /* 0 -> copy from page, 1 -> copy to page */ + DbPage *pDbPage /* Page containing pPayload */ +){ + if( eOp ){ + /* Copy data from buffer to page (a write operation) */ + int rc = sqlite3PagerWrite(pDbPage); + if( rc!=SQLITE_OK ){ + return rc; + } + memcpy(pPayload, pBuf, nByte); + }else{ + /* Copy data from page to buffer (a read operation) */ + memcpy(pBuf, pPayload, nByte); + } + return SQLITE_OK; +} + +/* +** This function is used to read or overwrite payload information +** for the entry that the pCur cursor is pointing to. If the eOp +** parameter is 0, this is a read operation (data copied into +** buffer pBuf). If it is non-zero, a write (data copied from +** buffer pBuf). +** +** A total of "amt" bytes are read or written beginning at "offset". +** Data is read to or from the buffer pBuf. +** +** The content being read or written might appear on the main page +** or be scattered out on multiple overflow pages. +** +** If the BtCursor.isIncrblobHandle flag is set, and the current +** cursor entry uses one or more overflow pages, this function +** allocates space for and lazily popluates the overflow page-list +** cache array (BtCursor.aOverflow). Subsequent calls use this +** cache to make seeking to the supplied offset more efficient. +** +** Once an overflow page-list cache has been allocated, it may be +** invalidated if some other cursor writes to the same table, or if +** the cursor is moved to a different row. Additionally, in auto-vacuum +** mode, the following events may invalidate an overflow page-list cache. +** +** * An incremental vacuum, +** * A commit in auto_vacuum="full" mode, +** * Creating a table (may require moving an overflow page). +*/ +static int accessPayload( + BtCursor *pCur, /* Cursor pointing to entry to read from */ + u32 offset, /* Begin reading this far into payload */ + u32 amt, /* Read this many bytes */ + unsigned char *pBuf, /* Write the bytes into this buffer */ + int eOp /* zero to read. non-zero to write. */ +){ + unsigned char *aPayload; + int rc = SQLITE_OK; + u32 nKey; + int iIdx = 0; + MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */ + BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ + + assert( pPage ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->aiIdx[pCur->iPage]nCell ); + assert( cursorHoldsMutex(pCur) ); + + getCellInfo(pCur); + aPayload = pCur->info.pCell + pCur->info.nHeader; + nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey); + + if( NEVER(offset+amt > nKey+pCur->info.nData) + || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] + ){ + /* Trying to read or write past the end of the data is an error */ + return SQLITE_CORRUPT_BKPT; + } + + /* Check if data must be read/written to/from the btree page itself. */ + if( offsetinfo.nLocal ){ + int a = amt; + if( a+offset>pCur->info.nLocal ){ + a = pCur->info.nLocal - offset; + } + rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); + offset = 0; + pBuf += a; + amt -= a; + }else{ + offset -= pCur->info.nLocal; + } + + if( rc==SQLITE_OK && amt>0 ){ + const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ + Pgno nextPage; + + nextPage = get4byte(&aPayload[pCur->info.nLocal]); + +#ifndef SQLITE_OMIT_INCRBLOB + /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[] + ** has not been allocated, allocate it now. The array is sized at + ** one entry for each overflow page in the overflow chain. The + ** page number of the first overflow page is stored in aOverflow[0], + ** etc. A value of 0 in the aOverflow[] array means "not yet known" + ** (the cache is lazily populated). + */ + if( pCur->isIncrblobHandle && !pCur->aOverflow ){ + int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; + pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl); + /* nOvfl is always positive. If it were zero, fetchPayload would have + ** been used instead of this routine. */ + if( ALWAYS(nOvfl) && !pCur->aOverflow ){ + rc = SQLITE_NOMEM; + } + } + + /* If the overflow page-list cache has been allocated and the + ** entry for the first required overflow page is valid, skip + ** directly to it. + */ + if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){ + iIdx = (offset/ovflSize); + nextPage = pCur->aOverflow[iIdx]; + offset = (offset%ovflSize); + } +#endif + + for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){ + +#ifndef SQLITE_OMIT_INCRBLOB + /* If required, populate the overflow page-list cache. */ + if( pCur->aOverflow ){ + assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage); + pCur->aOverflow[iIdx] = nextPage; + } +#endif + + if( offset>=ovflSize ){ + /* The only reason to read this page is to obtain the page + ** number for the next page in the overflow chain. The page + ** data is not required. So first try to lookup the overflow + ** page-list cache, if any, then fall back to the getOverflowPage() + ** function. + */ +#ifndef SQLITE_OMIT_INCRBLOB + if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){ + nextPage = pCur->aOverflow[iIdx+1]; + } else +#endif + rc = getOverflowPage(pBt, nextPage, 0, &nextPage); + offset -= ovflSize; + }else{ + /* Need to read this page properly. It contains some of the + ** range of data that is being read (eOp==0) or written (eOp!=0). + */ +#ifdef SQLITE_DIRECT_OVERFLOW_READ + sqlite3_file *fd; +#endif + int a = amt; + if( a + offset > ovflSize ){ + a = ovflSize - offset; + } + +#ifdef SQLITE_DIRECT_OVERFLOW_READ + /* If all the following are true: + ** + ** 1) this is a read operation, and + ** 2) data is required from the start of this overflow page, and + ** 3) the database is file-backed, and + ** 4) there is no open write-transaction, and + ** 5) the database is not a WAL database, + ** + ** then data can be read directly from the database file into the + ** output buffer, bypassing the page-cache altogether. This speeds + ** up loading large records that span many overflow pages. + */ + if( eOp==0 /* (1) */ + && offset==0 /* (2) */ + && pBt->inTransaction==TRANS_READ /* (4) */ + && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */ + && pBt->pPage1->aData[19]==0x01 /* (5) */ + ){ + u8 aSave[4]; + u8 *aWrite = &pBuf[-4]; + memcpy(aSave, aWrite, 4); + rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); + nextPage = get4byte(aWrite); + memcpy(aWrite, aSave, 4); + }else +#endif + + { + DbPage *pDbPage; + rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage, + (eOp==0 ? PAGER_GET_READONLY : 0) + ); + if( rc==SQLITE_OK ){ + aPayload = sqlite3PagerGetData(pDbPage); + nextPage = get4byte(aPayload); + rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); + sqlite3PagerUnref(pDbPage); + offset = 0; + } + } + amt -= a; + pBuf += a; + } + } + } + + if( rc==SQLITE_OK && amt>0 ){ + return SQLITE_CORRUPT_BKPT; + } + return rc; +} + +/* +** Read part of the key associated with cursor pCur. Exactly +** "amt" bytes will be transfered into pBuf[]. The transfer +** begins at "offset". +** +** The caller must ensure that pCur is pointing to a valid row +** in the table. +** +** Return SQLITE_OK on success or an error code if anything goes +** wrong. An error is returned if "offset+amt" is larger than +** the available payload. +*/ +int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); + assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); + return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); +} + +/* +** Read part of the data associated with cursor pCur. Exactly +** "amt" bytes will be transfered into pBuf[]. The transfer +** begins at "offset". +** +** Return SQLITE_OK on success or an error code if anything goes +** wrong. An error is returned if "offset+amt" is larger than +** the available payload. +*/ +int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ + int rc; + +#ifndef SQLITE_OMIT_INCRBLOB + if ( pCur->eState==CURSOR_INVALID ){ + return SQLITE_ABORT; + } +#endif + + assert( cursorHoldsMutex(pCur) ); + rc = restoreCursorPosition(pCur); + if( rc==SQLITE_OK ){ + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); + assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); + rc = accessPayload(pCur, offset, amt, pBuf, 0); + } + return rc; +} + +/* +** Return a pointer to payload information from the entry that the +** pCur cursor is pointing to. The pointer is to the beginning of +** the key if skipKey==0 and it points to the beginning of data if +** skipKey==1. The number of bytes of available key/data is written +** into *pAmt. If *pAmt==0, then the value returned will not be +** a valid pointer. +** +** This routine is an optimization. It is common for the entire key +** and data to fit on the local page and for there to be no overflow +** pages. When that is so, this routine can be used to access the +** key and data without making a copy. If the key and/or data spills +** onto overflow pages, then accessPayload() must be used to reassemble +** the key/data and copy it into a preallocated buffer. +** +** The pointer returned by this routine looks directly into the cached +** page of the database. The data might change or move the next time +** any btree routine is called. +*/ +static const unsigned char *fetchPayload( + BtCursor *pCur, /* Cursor pointing to entry to read from */ + int *pAmt, /* Write the number of available bytes here */ + int skipKey /* read beginning at data if this is true */ +){ + unsigned char *aPayload; + MemPage *pPage; + u32 nKey; + u32 nLocal; + + assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]); + assert( pCur->eState==CURSOR_VALID ); + assert( cursorHoldsMutex(pCur) ); + pPage = pCur->apPage[pCur->iPage]; + assert( pCur->aiIdx[pCur->iPage]nCell ); + if( NEVER(pCur->info.nSize==0) ){ + btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage], + &pCur->info); + } + aPayload = pCur->info.pCell; + aPayload += pCur->info.nHeader; + if( pPage->intKey ){ + nKey = 0; + }else{ + nKey = (int)pCur->info.nKey; + } + if( skipKey ){ + aPayload += nKey; + nLocal = pCur->info.nLocal - nKey; + }else{ + nLocal = pCur->info.nLocal; + assert( nLocal<=nKey ); + } + *pAmt = nLocal; + return aPayload; +} + + +/* +** For the entry that cursor pCur is point to, return as +** many bytes of the key or data as are available on the local +** b-tree page. Write the number of available bytes into *pAmt. +** +** The pointer returned is ephemeral. The key/data may move +** or be destroyed on the next call to any Btree routine, +** including calls from other threads against the same cache. +** Hence, a mutex on the BtShared should be held prior to calling +** this routine. +** +** These routines is used to get quick access to key and data +** in the common case where no overflow pages are used. +*/ +const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){ + const void *p = 0; + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( cursorHoldsMutex(pCur) ); + if( ALWAYS(pCur->eState==CURSOR_VALID) ){ + p = (const void*)fetchPayload(pCur, pAmt, 0); + } + return p; +} +const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){ + const void *p = 0; + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( cursorHoldsMutex(pCur) ); + if( ALWAYS(pCur->eState==CURSOR_VALID) ){ + p = (const void*)fetchPayload(pCur, pAmt, 1); + } + return p; +} + + +/* +** Move the cursor down to a new child page. The newPgno argument is the +** page number of the child page to move to. +** +** This function returns SQLITE_CORRUPT if the page-header flags field of +** the new child page does not match the flags field of the parent (i.e. +** if an intkey page appears to be the parent of a non-intkey page, or +** vice-versa). +*/ +static int moveToChild(BtCursor *pCur, u32 newPgno){ + int rc; + int i = pCur->iPage; + MemPage *pNewPage; + BtShared *pBt = pCur->pBt; + + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->iPageiPage>=0 ); + if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ + return SQLITE_CORRUPT_BKPT; + } + rc = getAndInitPage(pBt, newPgno, &pNewPage, + pCur->wrFlag==0 ? PAGER_GET_READONLY : 0); + if( rc ) return rc; + pCur->apPage[i+1] = pNewPage; + pCur->aiIdx[i+1] = 0; + pCur->iPage++; + + pCur->info.nSize = 0; + pCur->validNKey = 0; + if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){ + return SQLITE_CORRUPT_BKPT; + } + return SQLITE_OK; +} + +#if 0 +/* +** Page pParent is an internal (non-leaf) tree page. This function +** asserts that page number iChild is the left-child if the iIdx'th +** cell in page pParent. Or, if iIdx is equal to the total number of +** cells in pParent, that page number iChild is the right-child of +** the page. +*/ +static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ + assert( iIdx<=pParent->nCell ); + if( iIdx==pParent->nCell ){ + assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild ); + }else{ + assert( get4byte(findCell(pParent, iIdx))==iChild ); + } +} +#else +# define assertParentIndex(x,y,z) +#endif + +/* +** Move the cursor up to the parent page. +** +** pCur->idx is set to the cell index that contains the pointer +** to the page we are coming from. If we are coming from the +** right-most child page then pCur->idx is set to one more than +** the largest cell index. +*/ +static void moveToParent(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->iPage>0 ); + assert( pCur->apPage[pCur->iPage] ); + + /* UPDATE: It is actually possible for the condition tested by the assert + ** below to be untrue if the database file is corrupt. This can occur if + ** one cursor has modified page pParent while a reference to it is held + ** by a second cursor. Which can only happen if a single page is linked + ** into more than one b-tree structure in a corrupt database. */ +#if 0 + assertParentIndex( + pCur->apPage[pCur->iPage-1], + pCur->aiIdx[pCur->iPage-1], + pCur->apPage[pCur->iPage]->pgno + ); +#endif + testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); + + releasePage(pCur->apPage[pCur->iPage]); + pCur->iPage--; + pCur->info.nSize = 0; + pCur->validNKey = 0; +} + +/* +** Move the cursor to point to the root page of its b-tree structure. +** +** If the table has a virtual root page, then the cursor is moved to point +** to the virtual root page instead of the actual root page. A table has a +** virtual root page when the actual root page contains no cells and a +** single child page. This can only happen with the table rooted at page 1. +** +** If the b-tree structure is empty, the cursor state is set to +** CURSOR_INVALID. Otherwise, the cursor is set to point to the first +** cell located on the root (or virtual root) page and the cursor state +** is set to CURSOR_VALID. +** +** If this function returns successfully, it may be assumed that the +** page-header flags indicate that the [virtual] root-page is the expected +** kind of b-tree page (i.e. if when opening the cursor the caller did not +** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, +** indicating a table b-tree, or if the caller did specify a KeyInfo +** structure the flags byte is set to 0x02 or 0x0A, indicating an index +** b-tree). +*/ +static int moveToRoot(BtCursor *pCur){ + MemPage *pRoot; + int rc = SQLITE_OK; + Btree *p = pCur->pBtree; + BtShared *pBt = p->pBt; + + assert( cursorHoldsMutex(pCur) ); + assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); + assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); + assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); + if( pCur->eState>=CURSOR_REQUIRESEEK ){ + if( pCur->eState==CURSOR_FAULT ){ + assert( pCur->skipNext!=SQLITE_OK ); + return pCur->skipNext; + } + sqlite3BtreeClearCursor(pCur); + } + + if( pCur->iPage>=0 ){ + int i; + for(i=1; i<=pCur->iPage; i++){ + releasePage(pCur->apPage[i]); + } + pCur->iPage = 0; + }else if( pCur->pgnoRoot==0 ){ + pCur->eState = CURSOR_INVALID; + return SQLITE_OK; + }else{ + rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0], + pCur->wrFlag==0 ? PAGER_GET_READONLY : 0); + if( rc!=SQLITE_OK ){ + pCur->eState = CURSOR_INVALID; + return rc; + } + pCur->iPage = 0; + + /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor + ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is + ** NULL, the caller expects a table b-tree. If this is not the case, + ** return an SQLITE_CORRUPT error. */ + assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 ); + if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){ + return SQLITE_CORRUPT_BKPT; + } + } + + /* Assert that the root page is of the correct type. This must be the + ** case as the call to this function that loaded the root-page (either + ** this call or a previous invocation) would have detected corruption + ** if the assumption were not true, and it is not possible for the flags + ** byte to have been modified while this cursor is holding a reference + ** to the page. */ + pRoot = pCur->apPage[0]; + assert( pRoot->pgno==pCur->pgnoRoot ); + assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey ); + + pCur->aiIdx[0] = 0; + pCur->info.nSize = 0; + pCur->atLast = 0; + pCur->validNKey = 0; + + if( pRoot->nCell==0 && !pRoot->leaf ){ + Pgno subpage; + if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; + subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); + pCur->eState = CURSOR_VALID; + rc = moveToChild(pCur, subpage); + }else{ + pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID); + } + return rc; +} + +/* +** Move the cursor down to the left-most leaf entry beneath the +** entry to which it is currently pointing. +** +** The left-most leaf is the one with the smallest key - the first +** in ascending order. +*/ +static int moveToLeftmost(BtCursor *pCur){ + Pgno pgno; + int rc = SQLITE_OK; + MemPage *pPage; + + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){ + assert( pCur->aiIdx[pCur->iPage]nCell ); + pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage])); + rc = moveToChild(pCur, pgno); + } + return rc; +} + +/* +** Move the cursor down to the right-most leaf entry beneath the +** page to which it is currently pointing. Notice the difference +** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() +** finds the left-most entry beneath the *entry* whereas moveToRightmost() +** finds the right-most entry beneath the *page*. +** +** The right-most entry is the one with the largest key - the last +** key in ascending order. +*/ +static int moveToRightmost(BtCursor *pCur){ + Pgno pgno; + int rc = SQLITE_OK; + MemPage *pPage = 0; + + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){ + pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); + pCur->aiIdx[pCur->iPage] = pPage->nCell; + rc = moveToChild(pCur, pgno); + } + if( rc==SQLITE_OK ){ + pCur->aiIdx[pCur->iPage] = pPage->nCell-1; + pCur->info.nSize = 0; + pCur->validNKey = 0; + } + return rc; +} + +/* Move the cursor to the first entry in the table. Return SQLITE_OK +** on success. Set *pRes to 0 if the cursor actually points to something +** or set *pRes to 1 if the table is empty. +*/ +int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ + int rc; + + assert( cursorHoldsMutex(pCur) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + rc = moveToRoot(pCur); + if( rc==SQLITE_OK ){ + if( pCur->eState==CURSOR_INVALID ){ + assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); + *pRes = 1; + }else{ + assert( pCur->apPage[pCur->iPage]->nCell>0 ); + *pRes = 0; + rc = moveToLeftmost(pCur); + } + } + return rc; +} + +/* Move the cursor to the last entry in the table. Return SQLITE_OK +** on success. Set *pRes to 0 if the cursor actually points to something +** or set *pRes to 1 if the table is empty. +*/ +int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ + int rc; + + assert( cursorHoldsMutex(pCur) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + + /* If the cursor already points to the last entry, this is a no-op. */ + if( CURSOR_VALID==pCur->eState && pCur->atLast ){ +#ifdef SQLITE_DEBUG + /* This block serves to assert() that the cursor really does point + ** to the last entry in the b-tree. */ + int ii; + for(ii=0; iiiPage; ii++){ + assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); + } + assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 ); + assert( pCur->apPage[pCur->iPage]->leaf ); +#endif + return SQLITE_OK; + } + + rc = moveToRoot(pCur); + if( rc==SQLITE_OK ){ + if( CURSOR_INVALID==pCur->eState ){ + assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); + *pRes = 1; + }else{ + assert( pCur->eState==CURSOR_VALID ); + *pRes = 0; + rc = moveToRightmost(pCur); + pCur->atLast = rc==SQLITE_OK ?1:0; + } + } + return rc; +} + +/* Move the cursor so that it points to an entry near the key +** specified by pIdxKey or intKey. Return a success code. +** +** For INTKEY tables, the intKey parameter is used. pIdxKey +** must be NULL. For index tables, pIdxKey is used and intKey +** is ignored. +** +** If an exact match is not found, then the cursor is always +** left pointing at a leaf page which would hold the entry if it +** were present. The cursor might point to an entry that comes +** before or after the key. +** +** An integer is written into *pRes which is the result of +** comparing the key with the entry to which the cursor is +** pointing. The meaning of the integer written into +** *pRes is as follows: +** +** *pRes<0 The cursor is left pointing at an entry that +** is smaller than intKey/pIdxKey or if the table is empty +** and the cursor is therefore left point to nothing. +** +** *pRes==0 The cursor is left pointing at an entry that +** exactly matches intKey/pIdxKey. +** +** *pRes>0 The cursor is left pointing at an entry that +** is larger than intKey/pIdxKey. +** +*/ +int sqlite3BtreeMovetoUnpacked( + BtCursor *pCur, /* The cursor to be moved */ + UnpackedRecord *pIdxKey, /* Unpacked index key */ + i64 intKey, /* The table key */ + int biasRight, /* If true, bias the search to the high end */ + int *pRes /* Write search results here */ +){ + int rc; + + assert( cursorHoldsMutex(pCur) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( pRes ); + assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); + + /* If the cursor is already positioned at the point we are trying + ** to move to, then just return without doing any work */ + if( pCur->eState==CURSOR_VALID && pCur->validNKey + && pCur->apPage[0]->intKey + ){ + if( pCur->info.nKey==intKey ){ + *pRes = 0; + return SQLITE_OK; + } + if( pCur->atLast && pCur->info.nKeypgnoRoot==0 || pCur->apPage[pCur->iPage] ); + assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit ); + assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 ); + if( pCur->eState==CURSOR_INVALID ){ + *pRes = -1; + assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); + return SQLITE_OK; + } + assert( pCur->apPage[0]->intKey || pIdxKey ); + for(;;){ + int lwr, upr, idx; + Pgno chldPg; + MemPage *pPage = pCur->apPage[pCur->iPage]; + int c; + + /* pPage->nCell must be greater than zero. If this is the root-page + ** the cursor would have been INVALID above and this for(;;) loop + ** not run. If this is not the root-page, then the moveToChild() routine + ** would have already detected db corruption. Similarly, pPage must + ** be the right kind (index or table) of b-tree page. Otherwise + ** a moveToChild() or moveToRoot() call would have detected corruption. */ + assert( pPage->nCell>0 ); + assert( pPage->intKey==(pIdxKey==0) ); + lwr = 0; + upr = pPage->nCell-1; + if( biasRight ){ + pCur->aiIdx[pCur->iPage] = (u16)(idx = upr); + }else{ + pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2); + } + for(;;){ + u8 *pCell; /* Pointer to current cell in pPage */ + + assert( idx==pCur->aiIdx[pCur->iPage] ); + pCur->info.nSize = 0; + pCell = findCell(pPage, idx) + pPage->childPtrSize; + if( pPage->intKey ){ + i64 nCellKey; + if( pPage->hasData ){ + u32 dummy; + pCell += getVarint32(pCell, dummy); + } + getVarint(pCell, (u64*)&nCellKey); + if( nCellKey==intKey ){ + c = 0; + }else if( nCellKeyintKey ); + c = +1; + } + pCur->validNKey = 1; + pCur->info.nKey = nCellKey; + }else{ + /* The maximum supported page-size is 65536 bytes. This means that + ** the maximum number of record bytes stored on an index B-Tree + ** page is less than 16384 bytes and may be stored as a 2-byte + ** varint. This information is used to attempt to avoid parsing + ** the entire cell by checking for the cases where the record is + ** stored entirely within the b-tree page by inspecting the first + ** 2 bytes of the cell. + */ + int nCell = pCell[0]; + if( nCell<=pPage->max1bytePayload + /* && (pCell+nCell)aDataEnd */ + ){ + /* This branch runs if the record-size field of the cell is a + ** single byte varint and the record fits entirely on the main + ** b-tree page. */ + testcase( pCell+nCell+1==pPage->aDataEnd ); + c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey); + }else if( !(pCell[1] & 0x80) + && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal + /* && (pCell+nCell+2)<=pPage->aDataEnd */ + ){ + /* The record-size field is a 2 byte varint and the record + ** fits entirely on the main b-tree page. */ + testcase( pCell+nCell+2==pPage->aDataEnd ); + c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey); + }else{ + /* The record flows over onto one or more overflow pages. In + ** this case the whole cell needs to be parsed, a buffer allocated + ** and accessPayload() used to retrieve the record into the + ** buffer before VdbeRecordCompare() can be called. */ + void *pCellKey; + u8 * const pCellBody = pCell - pPage->childPtrSize; + btreeParseCellPtr(pPage, pCellBody, &pCur->info); + nCell = (int)pCur->info.nKey; + pCellKey = sqlite3Malloc( nCell ); + if( pCellKey==0 ){ + rc = SQLITE_NOMEM; + goto moveto_finish; + } + rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); + if( rc ){ + sqlite3_free(pCellKey); + goto moveto_finish; + } + c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); + sqlite3_free(pCellKey); + } + } + if( c==0 ){ + if( pPage->intKey && !pPage->leaf ){ + lwr = idx; + break; + }else{ + *pRes = 0; + rc = SQLITE_OK; + goto moveto_finish; + } + } + if( c<0 ){ + lwr = idx+1; + }else{ + upr = idx-1; + } + if( lwr>upr ){ + break; + } + pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2); + } + assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); + assert( pPage->isInit ); + if( pPage->leaf ){ + chldPg = 0; + }else if( lwr>=pPage->nCell ){ + chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); + }else{ + chldPg = get4byte(findCell(pPage, lwr)); + } + if( chldPg==0 ){ + assert( pCur->aiIdx[pCur->iPage]apPage[pCur->iPage]->nCell ); + *pRes = c; + rc = SQLITE_OK; + goto moveto_finish; + } + pCur->aiIdx[pCur->iPage] = (u16)lwr; + pCur->info.nSize = 0; + pCur->validNKey = 0; + rc = moveToChild(pCur, chldPg); + if( rc ) goto moveto_finish; + } +moveto_finish: + return rc; +} + + +/* +** Return TRUE if the cursor is not pointing at an entry of the table. +** +** TRUE will be returned after a call to sqlite3BtreeNext() moves +** past the last entry in the table or sqlite3BtreePrev() moves past +** the first entry. TRUE is also returned if the table is empty. +*/ +int sqlite3BtreeEof(BtCursor *pCur){ + /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries + ** have been deleted? This API will need to change to return an error code + ** as well as the boolean result value. + */ + return (CURSOR_VALID!=pCur->eState); +} + +/* +** Advance the cursor to the next entry in the database. If +** successful then set *pRes=0. If the cursor +** was already pointing to the last entry in the database before +** this routine was called, then set *pRes=1. +*/ +int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ + int rc; + int idx; + MemPage *pPage; + + assert( cursorHoldsMutex(pCur) ); + assert( pRes!=0 ); + assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); + if( pCur->eState!=CURSOR_VALID ){ + rc = restoreCursorPosition(pCur); + if( rc!=SQLITE_OK ){ + *pRes = 0; + return rc; + } + if( CURSOR_INVALID==pCur->eState ){ + *pRes = 1; + return SQLITE_OK; + } + if( pCur->skipNext ){ + assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); + pCur->eState = CURSOR_VALID; + if( pCur->skipNext>0 ){ + pCur->skipNext = 0; + *pRes = 0; + return SQLITE_OK; + } + pCur->skipNext = 0; + } + } + + pPage = pCur->apPage[pCur->iPage]; + idx = ++pCur->aiIdx[pCur->iPage]; + assert( pPage->isInit ); + + /* If the database file is corrupt, it is possible for the value of idx + ** to be invalid here. This can only occur if a second cursor modifies + ** the page while cursor pCur is holding a reference to it. Which can + ** only happen if the database is corrupt in such a way as to link the + ** page into more than one b-tree structure. */ + testcase( idx>pPage->nCell ); + + pCur->info.nSize = 0; + pCur->validNKey = 0; + if( idx>=pPage->nCell ){ + if( !pPage->leaf ){ + rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); + if( rc ){ + *pRes = 0; + return rc; + } + rc = moveToLeftmost(pCur); + *pRes = 0; + return rc; + } + do{ + if( pCur->iPage==0 ){ + *pRes = 1; + pCur->eState = CURSOR_INVALID; + return SQLITE_OK; + } + moveToParent(pCur); + pPage = pCur->apPage[pCur->iPage]; + }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell ); + *pRes = 0; + if( pPage->intKey ){ + rc = sqlite3BtreeNext(pCur, pRes); + }else{ + rc = SQLITE_OK; + } + return rc; + } + *pRes = 0; + if( pPage->leaf ){ + return SQLITE_OK; + } + rc = moveToLeftmost(pCur); + return rc; +} + + +/* +** Step the cursor to the back to the previous entry in the database. If +** successful then set *pRes=0. If the cursor +** was already pointing to the first entry in the database before +** this routine was called, then set *pRes=1. +*/ +int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){ + int rc; + MemPage *pPage; + + assert( cursorHoldsMutex(pCur) ); + assert( pRes!=0 ); + assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); + pCur->atLast = 0; + if( pCur->eState!=CURSOR_VALID ){ + if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){ + rc = btreeRestoreCursorPosition(pCur); + if( rc!=SQLITE_OK ){ + *pRes = 0; + return rc; + } + } + if( CURSOR_INVALID==pCur->eState ){ + *pRes = 1; + return SQLITE_OK; + } + if( pCur->skipNext ){ + assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); + pCur->eState = CURSOR_VALID; + if( pCur->skipNext<0 ){ + pCur->skipNext = 0; + *pRes = 0; + return SQLITE_OK; + } + pCur->skipNext = 0; + } + } + + pPage = pCur->apPage[pCur->iPage]; + assert( pPage->isInit ); + if( !pPage->leaf ){ + int idx = pCur->aiIdx[pCur->iPage]; + rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); + if( rc ){ + *pRes = 0; + return rc; + } + rc = moveToRightmost(pCur); + }else{ + while( pCur->aiIdx[pCur->iPage]==0 ){ + if( pCur->iPage==0 ){ + pCur->eState = CURSOR_INVALID; + *pRes = 1; + return SQLITE_OK; + } + moveToParent(pCur); + } + pCur->info.nSize = 0; + pCur->validNKey = 0; + + pCur->aiIdx[pCur->iPage]--; + pPage = pCur->apPage[pCur->iPage]; + if( pPage->intKey && !pPage->leaf ){ + rc = sqlite3BtreePrevious(pCur, pRes); + }else{ + rc = SQLITE_OK; + } + } + *pRes = 0; + return rc; +} + +/* +** Allocate a new page from the database file. +** +** The new page is marked as dirty. (In other words, sqlite3PagerWrite() +** has already been called on the new page.) The new page has also +** been referenced and the calling routine is responsible for calling +** sqlite3PagerUnref() on the new page when it is done. +** +** SQLITE_OK is returned on success. Any other return value indicates +** an error. *ppPage and *pPgno are undefined in the event of an error. +** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned. +** +** If the "nearby" parameter is not 0, then an effort is made to +** locate a page close to the page number "nearby". This can be used in an +** attempt to keep related pages close to each other in the database file, +** which in turn can make database access faster. +** +** If the eMode parameter is BTALLOC_EXACT and the nearby page exists +** anywhere on the free-list, then it is guaranteed to be returned. If +** eMode is BTALLOC_LT then the page returned will be less than or equal +** to nearby if any such page exists. If eMode is BTALLOC_ANY then there +** are no restrictions on which page is returned. +*/ +static int allocateBtreePage( + BtShared *pBt, /* The btree */ + MemPage **ppPage, /* Store pointer to the allocated page here */ + Pgno *pPgno, /* Store the page number here */ + Pgno nearby, /* Search for a page near this one */ + u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ +){ + MemPage *pPage1; + int rc; + u32 n; /* Number of pages on the freelist */ + u32 k; /* Number of leaves on the trunk of the freelist */ + MemPage *pTrunk = 0; + MemPage *pPrevTrunk = 0; + Pgno mxPage; /* Total size of the database file */ + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); + pPage1 = pBt->pPage1; + mxPage = btreePagecount(pBt); + n = get4byte(&pPage1->aData[36]); + testcase( n==mxPage-1 ); + if( n>=mxPage ){ + return SQLITE_CORRUPT_BKPT; + } + if( n>0 ){ + /* There are pages on the freelist. Reuse one of those pages. */ + Pgno iTrunk; + u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ + + /* If eMode==BTALLOC_EXACT and a query of the pointer-map + ** shows that the page 'nearby' is somewhere on the free-list, then + ** the entire-list will be searched for that page. + */ +#ifndef SQLITE_OMIT_AUTOVACUUM + if( eMode==BTALLOC_EXACT ){ + if( nearby<=mxPage ){ + u8 eType; + assert( nearby>0 ); + assert( pBt->autoVacuum ); + rc = ptrmapGet(pBt, nearby, &eType, 0); + if( rc ) return rc; + if( eType==PTRMAP_FREEPAGE ){ + searchList = 1; + } + } + }else if( eMode==BTALLOC_LE ){ + searchList = 1; + } +#endif + + /* Decrement the free-list count by 1. Set iTrunk to the index of the + ** first free-list trunk page. iPrevTrunk is initially 1. + */ + rc = sqlite3PagerWrite(pPage1->pDbPage); + if( rc ) return rc; + put4byte(&pPage1->aData[36], n-1); + + /* The code within this loop is run only once if the 'searchList' variable + ** is not true. Otherwise, it runs once for each trunk-page on the + ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) + ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) + */ + do { + pPrevTrunk = pTrunk; + if( pPrevTrunk ){ + iTrunk = get4byte(&pPrevTrunk->aData[0]); + }else{ + iTrunk = get4byte(&pPage1->aData[32]); + } + testcase( iTrunk==mxPage ); + if( iTrunk>mxPage ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); + } + if( rc ){ + pTrunk = 0; + goto end_allocate_page; + } + assert( pTrunk!=0 ); + assert( pTrunk->aData!=0 ); + + k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */ + if( k==0 && !searchList ){ + /* The trunk has no leaves and the list is not being searched. + ** So extract the trunk page itself and use it as the newly + ** allocated page */ + assert( pPrevTrunk==0 ); + rc = sqlite3PagerWrite(pTrunk->pDbPage); + if( rc ){ + goto end_allocate_page; + } + *pPgno = iTrunk; + memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); + *ppPage = pTrunk; + pTrunk = 0; + TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); + }else if( k>(u32)(pBt->usableSize/4 - 2) ){ + /* Value of k is out of range. Database corruption */ + rc = SQLITE_CORRUPT_BKPT; + goto end_allocate_page; +#ifndef SQLITE_OMIT_AUTOVACUUM + }else if( searchList + && (nearby==iTrunk || (iTrunkpDbPage); + if( rc ){ + goto end_allocate_page; + } + if( k==0 ){ + if( !pPrevTrunk ){ + memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); + }else{ + rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); + if( rc!=SQLITE_OK ){ + goto end_allocate_page; + } + memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); + } + }else{ + /* The trunk page is required by the caller but it contains + ** pointers to free-list leaves. The first leaf becomes a trunk + ** page in this case. + */ + MemPage *pNewTrunk; + Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); + if( iNewTrunk>mxPage ){ + rc = SQLITE_CORRUPT_BKPT; + goto end_allocate_page; + } + testcase( iNewTrunk==mxPage ); + rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0); + if( rc!=SQLITE_OK ){ + goto end_allocate_page; + } + rc = sqlite3PagerWrite(pNewTrunk->pDbPage); + if( rc!=SQLITE_OK ){ + releasePage(pNewTrunk); + goto end_allocate_page; + } + memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); + put4byte(&pNewTrunk->aData[4], k-1); + memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); + releasePage(pNewTrunk); + if( !pPrevTrunk ){ + assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); + put4byte(&pPage1->aData[32], iNewTrunk); + }else{ + rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); + if( rc ){ + goto end_allocate_page; + } + put4byte(&pPrevTrunk->aData[0], iNewTrunk); + } + } + pTrunk = 0; + TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); +#endif + }else if( k>0 ){ + /* Extract a leaf from the trunk */ + u32 closest; + Pgno iPage; + unsigned char *aData = pTrunk->aData; + if( nearby>0 ){ + u32 i; + closest = 0; + if( eMode==BTALLOC_LE ){ + for(i=0; imxPage ){ + rc = SQLITE_CORRUPT_BKPT; + goto end_allocate_page; + } + testcase( iPage==mxPage ); + if( !searchList + || (iPage==nearby || (iPagepgno, n-1)); + rc = sqlite3PagerWrite(pTrunk->pDbPage); + if( rc ) goto end_allocate_page; + if( closestpDbPage); + if( rc!=SQLITE_OK ){ + releasePage(*ppPage); + } + } + searchList = 0; + } + } + releasePage(pPrevTrunk); + pPrevTrunk = 0; + }while( searchList ); + }else{ + /* There are no pages on the freelist, so append a new page to the + ** database image. + ** + ** Normally, new pages allocated by this block can be requested from the + ** pager layer with the 'no-content' flag set. This prevents the pager + ** from trying to read the pages content from disk. However, if the + ** current transaction has already run one or more incremental-vacuum + ** steps, then the page we are about to allocate may contain content + ** that is required in the event of a rollback. In this case, do + ** not set the no-content flag. This causes the pager to load and journal + ** the current page content before overwriting it. + ** + ** Note that the pager will not actually attempt to load or journal + ** content for any page that really does lie past the end of the database + ** file on disk. So the effects of disabling the no-content optimization + ** here are confined to those pages that lie between the end of the + ** database image and the end of the database file. + */ + int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0; + + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + if( rc ) return rc; + pBt->nPage++; + if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; + +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ + /* If *pPgno refers to a pointer-map page, allocate two new pages + ** at the end of the file instead of one. The first allocated page + ** becomes a new pointer-map page, the second is used by the caller. + */ + MemPage *pPg = 0; + TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); + assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); + rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent); + if( rc==SQLITE_OK ){ + rc = sqlite3PagerWrite(pPg->pDbPage); + releasePage(pPg); + } + if( rc ) return rc; + pBt->nPage++; + if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } + } +#endif + put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); + *pPgno = pBt->nPage; + + assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); + rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent); + if( rc ) return rc; + rc = sqlite3PagerWrite((*ppPage)->pDbPage); + if( rc!=SQLITE_OK ){ + releasePage(*ppPage); + } + TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); + } + + assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); + +end_allocate_page: + releasePage(pTrunk); + releasePage(pPrevTrunk); + if( rc==SQLITE_OK ){ + if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ + releasePage(*ppPage); + return SQLITE_CORRUPT_BKPT; + } + (*ppPage)->isInit = 0; + }else{ + *ppPage = 0; + } + assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) ); + return rc; +} + +/* +** This function is used to add page iPage to the database file free-list. +** It is assumed that the page is not already a part of the free-list. +** +** The value passed as the second argument to this function is optional. +** If the caller happens to have a pointer to the MemPage object +** corresponding to page iPage handy, it may pass it as the second value. +** Otherwise, it may pass NULL. +** +** If a pointer to a MemPage object is passed as the second argument, +** its reference count is not altered by this function. +*/ +static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ + MemPage *pTrunk = 0; /* Free-list trunk page */ + Pgno iTrunk = 0; /* Page number of free-list trunk page */ + MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ + MemPage *pPage; /* Page being freed. May be NULL. */ + int rc; /* Return Code */ + int nFree; /* Initial number of pages on free-list */ + + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( iPage>1 ); + assert( !pMemPage || pMemPage->pgno==iPage ); + + if( pMemPage ){ + pPage = pMemPage; + sqlite3PagerRef(pPage->pDbPage); + }else{ + pPage = btreePageLookup(pBt, iPage); + } + + /* Increment the free page count on pPage1 */ + rc = sqlite3PagerWrite(pPage1->pDbPage); + if( rc ) goto freepage_out; + nFree = get4byte(&pPage1->aData[36]); + put4byte(&pPage1->aData[36], nFree+1); + + if( pBt->btsFlags & BTS_SECURE_DELETE ){ + /* If the secure_delete option is enabled, then + ** always fully overwrite deleted information with zeros. + */ + if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) + || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) + ){ + goto freepage_out; + } + memset(pPage->aData, 0, pPage->pBt->pageSize); + } + + /* If the database supports auto-vacuum, write an entry in the pointer-map + ** to indicate that the page is free. + */ + if( ISAUTOVACUUM ){ + ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); + if( rc ) goto freepage_out; + } + + /* Now manipulate the actual database free-list structure. There are two + ** possibilities. If the free-list is currently empty, or if the first + ** trunk page in the free-list is full, then this page will become a + ** new free-list trunk page. Otherwise, it will become a leaf of the + ** first trunk page in the current free-list. This block tests if it + ** is possible to add the page as a new free-list leaf. + */ + if( nFree!=0 ){ + u32 nLeaf; /* Initial number of leaf cells on trunk page */ + + iTrunk = get4byte(&pPage1->aData[32]); + rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); + if( rc!=SQLITE_OK ){ + goto freepage_out; + } + + nLeaf = get4byte(&pTrunk->aData[4]); + assert( pBt->usableSize>32 ); + if( nLeaf > (u32)pBt->usableSize/4 - 2 ){ + rc = SQLITE_CORRUPT_BKPT; + goto freepage_out; + } + if( nLeaf < (u32)pBt->usableSize/4 - 8 ){ + /* In this case there is room on the trunk page to insert the page + ** being freed as a new leaf. + ** + ** Note that the trunk page is not really full until it contains + ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have + ** coded. But due to a coding error in versions of SQLite prior to + ** 3.6.0, databases with freelist trunk pages holding more than + ** usableSize/4 - 8 entries will be reported as corrupt. In order + ** to maintain backwards compatibility with older versions of SQLite, + ** we will continue to restrict the number of entries to usableSize/4 - 8 + ** for now. At some point in the future (once everyone has upgraded + ** to 3.6.0 or later) we should consider fixing the conditional above + ** to read "usableSize/4-2" instead of "usableSize/4-8". + */ + rc = sqlite3PagerWrite(pTrunk->pDbPage); + if( rc==SQLITE_OK ){ + put4byte(&pTrunk->aData[4], nLeaf+1); + put4byte(&pTrunk->aData[8+nLeaf*4], iPage); + if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ + sqlite3PagerDontWrite(pPage->pDbPage); + } + rc = btreeSetHasContent(pBt, iPage); + } + TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); + goto freepage_out; + } + } + + /* If control flows to this point, then it was not possible to add the + ** the page being freed as a leaf page of the first trunk in the free-list. + ** Possibly because the free-list is empty, or possibly because the + ** first trunk in the free-list is full. Either way, the page being freed + ** will become the new first trunk page in the free-list. + */ + if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ + goto freepage_out; + } + rc = sqlite3PagerWrite(pPage->pDbPage); + if( rc!=SQLITE_OK ){ + goto freepage_out; + } + put4byte(pPage->aData, iTrunk); + put4byte(&pPage->aData[4], 0); + put4byte(&pPage1->aData[32], iPage); + TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk)); + +freepage_out: + if( pPage ){ + pPage->isInit = 0; + } + releasePage(pPage); + releasePage(pTrunk); + return rc; +} +static void freePage(MemPage *pPage, int *pRC){ + if( (*pRC)==SQLITE_OK ){ + *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); + } +} + +/* +** Free any overflow pages associated with the given Cell. +*/ +static int clearCell(MemPage *pPage, unsigned char *pCell){ + BtShared *pBt = pPage->pBt; + CellInfo info; + Pgno ovflPgno; + int rc; + int nOvfl; + u32 ovflPageSize; + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + btreeParseCellPtr(pPage, pCell, &info); + if( info.iOverflow==0 ){ + return SQLITE_OK; /* No overflow pages. Return without doing anything */ + } + if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){ + return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */ + } + ovflPgno = get4byte(&pCell[info.iOverflow]); + assert( pBt->usableSize > 4 ); + ovflPageSize = pBt->usableSize - 4; + nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize; + assert( ovflPgno==0 || nOvfl>0 ); + while( nOvfl-- ){ + Pgno iNext = 0; + MemPage *pOvfl = 0; + if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){ + /* 0 is not a legal page number and page 1 cannot be an + ** overflow page. Therefore if ovflPgno<2 or past the end of the + ** file the database must be corrupt. */ + return SQLITE_CORRUPT_BKPT; + } + if( nOvfl ){ + rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); + if( rc ) return rc; + } + + if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) + && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 + ){ + /* There is no reason any cursor should have an outstanding reference + ** to an overflow page belonging to a cell that is being deleted/updated. + ** So if there exists more than one reference to this page, then it + ** must not really be an overflow page and the database must be corrupt. + ** It is helpful to detect this before calling freePage2(), as + ** freePage2() may zero the page contents if secure-delete mode is + ** enabled. If this 'overflow' page happens to be a page that the + ** caller is iterating through or using in some other way, this + ** can be problematic. + */ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = freePage2(pBt, pOvfl, ovflPgno); + } + + if( pOvfl ){ + sqlite3PagerUnref(pOvfl->pDbPage); + } + if( rc ) return rc; + ovflPgno = iNext; + } + return SQLITE_OK; +} + +/* +** Create the byte sequence used to represent a cell on page pPage +** and write that byte sequence into pCell[]. Overflow pages are +** allocated and filled in as necessary. The calling procedure +** is responsible for making sure sufficient space has been allocated +** for pCell[]. +** +** Note that pCell does not necessary need to point to the pPage->aData +** area. pCell might point to some temporary storage. The cell will +** be constructed in this temporary area then copied into pPage->aData +** later. +*/ +static int fillInCell( + MemPage *pPage, /* The page that contains the cell */ + unsigned char *pCell, /* Complete text of the cell */ + const void *pKey, i64 nKey, /* The key */ + const void *pData,int nData, /* The data */ + int nZero, /* Extra zero bytes to append to pData */ + int *pnSize /* Write cell size here */ +){ + int nPayload; + const u8 *pSrc; + int nSrc, n, rc; + int spaceLeft; + MemPage *pOvfl = 0; + MemPage *pToRelease = 0; + unsigned char *pPrior; + unsigned char *pPayload; + BtShared *pBt = pPage->pBt; + Pgno pgnoOvfl = 0; + int nHeader; + CellInfo info; + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + + /* pPage is not necessarily writeable since pCell might be auxiliary + ** buffer space that is separate from the pPage buffer area */ + assert( pCellaData || pCell>=&pPage->aData[pBt->pageSize] + || sqlite3PagerIswriteable(pPage->pDbPage) ); + + /* Fill in the header. */ + nHeader = 0; + if( !pPage->leaf ){ + nHeader += 4; + } + if( pPage->hasData ){ + nHeader += putVarint(&pCell[nHeader], nData+nZero); + }else{ + nData = nZero = 0; + } + nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey); + btreeParseCellPtr(pPage, pCell, &info); + assert( info.nHeader==nHeader ); + assert( info.nKey==nKey ); + assert( info.nData==(u32)(nData+nZero) ); + + /* Fill in the payload */ + nPayload = nData + nZero; + if( pPage->intKey ){ + pSrc = pData; + nSrc = nData; + nData = 0; + }else{ + if( NEVER(nKey>0x7fffffff || pKey==0) ){ + return SQLITE_CORRUPT_BKPT; + } + nPayload += (int)nKey; + pSrc = pKey; + nSrc = (int)nKey; + } + *pnSize = info.nSize; + spaceLeft = info.nLocal; + pPayload = &pCell[nHeader]; + pPrior = &pCell[info.iOverflow]; + + while( nPayload>0 ){ + if( spaceLeft==0 ){ +#ifndef SQLITE_OMIT_AUTOVACUUM + Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ + if( pBt->autoVacuum ){ + do{ + pgnoOvfl++; + } while( + PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) + ); + } +#endif + rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); +#ifndef SQLITE_OMIT_AUTOVACUUM + /* If the database supports auto-vacuum, and the second or subsequent + ** overflow page is being allocated, add an entry to the pointer-map + ** for that page now. + ** + ** If this is the first overflow page, then write a partial entry + ** to the pointer-map. If we write nothing to this pointer-map slot, + ** then the optimistic overflow chain processing in clearCell() + ** may misinterpret the uninitialized values and delete the + ** wrong pages from the database. + */ + if( pBt->autoVacuum && rc==SQLITE_OK ){ + u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); + ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); + if( rc ){ + releasePage(pOvfl); + } + } +#endif + if( rc ){ + releasePage(pToRelease); + return rc; + } + + /* If pToRelease is not zero than pPrior points into the data area + ** of pToRelease. Make sure pToRelease is still writeable. */ + assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); + + /* If pPrior is part of the data area of pPage, then make sure pPage + ** is still writeable */ + assert( pPrioraData || pPrior>=&pPage->aData[pBt->pageSize] + || sqlite3PagerIswriteable(pPage->pDbPage) ); + + put4byte(pPrior, pgnoOvfl); + releasePage(pToRelease); + pToRelease = pOvfl; + pPrior = pOvfl->aData; + put4byte(pPrior, 0); + pPayload = &pOvfl->aData[4]; + spaceLeft = pBt->usableSize - 4; + } + n = nPayload; + if( n>spaceLeft ) n = spaceLeft; + + /* If pToRelease is not zero than pPayload points into the data area + ** of pToRelease. Make sure pToRelease is still writeable. */ + assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); + + /* If pPayload is part of the data area of pPage, then make sure pPage + ** is still writeable */ + assert( pPayloadaData || pPayload>=&pPage->aData[pBt->pageSize] + || sqlite3PagerIswriteable(pPage->pDbPage) ); + + if( nSrc>0 ){ + if( n>nSrc ) n = nSrc; + assert( pSrc ); + memcpy(pPayload, pSrc, n); + }else{ + memset(pPayload, 0, n); + } + nPayload -= n; + pPayload += n; + pSrc += n; + nSrc -= n; + spaceLeft -= n; + if( nSrc==0 ){ + nSrc = nData; + pSrc = pData; + } + } + releasePage(pToRelease); + return SQLITE_OK; +} + +/* +** Remove the i-th cell from pPage. This routine effects pPage only. +** The cell content is not freed or deallocated. It is assumed that +** the cell content has been copied someplace else. This routine just +** removes the reference to the cell from pPage. +** +** "sz" must be the number of bytes in the cell. +*/ +static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ + u32 pc; /* Offset to cell content of cell being deleted */ + u8 *data; /* pPage->aData */ + u8 *ptr; /* Used to move bytes around within data[] */ + u8 *endPtr; /* End of loop */ + int rc; /* The return code */ + int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ + + if( *pRC ) return; + + assert( idx>=0 && idxnCell ); + assert( sz==cellSize(pPage, idx) ); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + data = pPage->aData; + ptr = &pPage->aCellIdx[2*idx]; + pc = get2byte(ptr); + hdr = pPage->hdrOffset; + testcase( pc==get2byte(&data[hdr+5]) ); + testcase( pc+sz==pPage->pBt->usableSize ); + if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){ + *pRC = SQLITE_CORRUPT_BKPT; + return; + } + rc = freeSpace(pPage, pc, sz); + if( rc ){ + *pRC = rc; + return; + } + endPtr = &pPage->aCellIdx[2*pPage->nCell - 2]; + assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */ + while( ptrnCell--; + put2byte(&data[hdr+3], pPage->nCell); + pPage->nFree += 2; +} + +/* +** Insert a new cell on pPage at cell index "i". pCell points to the +** content of the cell. +** +** If the cell content will fit on the page, then put it there. If it +** will not fit, then make a copy of the cell content into pTemp if +** pTemp is not null. Regardless of pTemp, allocate a new entry +** in pPage->apOvfl[] and make it point to the cell content (either +** in pTemp or the original pCell) and also record its index. +** Allocating a new entry in pPage->aCell[] implies that +** pPage->nOverflow is incremented. +** +** If nSkip is non-zero, then do not copy the first nSkip bytes of the +** cell. The caller will overwrite them after this function returns. If +** nSkip is non-zero, then pCell may not point to an invalid memory location +** (but pCell+nSkip is always valid). +*/ +static void insertCell( + MemPage *pPage, /* Page into which we are copying */ + int i, /* New cell becomes the i-th cell of the page */ + u8 *pCell, /* Content of the new cell */ + int sz, /* Bytes of content in pCell */ + u8 *pTemp, /* Temp storage space for pCell, if needed */ + Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ + int *pRC /* Read and write return code from here */ +){ + int idx = 0; /* Where to write new cell content in data[] */ + int j; /* Loop counter */ + int end; /* First byte past the last cell pointer in data[] */ + int ins; /* Index in data[] where new cell pointer is inserted */ + int cellOffset; /* Address of first cell pointer in data[] */ + u8 *data; /* The content of the whole page */ + u8 *ptr; /* Used for moving information around in data[] */ + u8 *endPtr; /* End of the loop */ + + int nSkip = (iChild ? 4 : 0); + + if( *pRC ) return; + + assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); + assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 ); + assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); + assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + /* The cell should normally be sized correctly. However, when moving a + ** malformed cell from a leaf page to an interior page, if the cell size + ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size + ** might be less than 8 (leaf-size + pointer) on the interior node. Hence + ** the term after the || in the following assert(). */ + assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) ); + if( pPage->nOverflow || sz+2>pPage->nFree ){ + if( pTemp ){ + memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip); + pCell = pTemp; + } + if( iChild ){ + put4byte(pCell, iChild); + } + j = pPage->nOverflow++; + assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) ); + pPage->apOvfl[j] = pCell; + pPage->aiOvfl[j] = (u16)i; + }else{ + int rc = sqlite3PagerWrite(pPage->pDbPage); + if( rc!=SQLITE_OK ){ + *pRC = rc; + return; + } + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + data = pPage->aData; + cellOffset = pPage->cellOffset; + end = cellOffset + 2*pPage->nCell; + ins = cellOffset + 2*i; + rc = allocateSpace(pPage, sz, &idx); + if( rc ){ *pRC = rc; return; } + /* The allocateSpace() routine guarantees the following two properties + ** if it returns success */ + assert( idx >= end+2 ); + assert( idx+sz <= (int)pPage->pBt->usableSize ); + pPage->nCell++; + pPage->nFree -= (u16)(2 + sz); + memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip); + if( iChild ){ + put4byte(&data[idx], iChild); + } + ptr = &data[end]; + endPtr = &data[ins]; + assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */ + while( ptr>endPtr ){ + *(u16*)ptr = *(u16*)&ptr[-2]; + ptr -= 2; + } + put2byte(&data[ins], idx); + put2byte(&data[pPage->hdrOffset+3], pPage->nCell); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pPage->pBt->autoVacuum ){ + /* The cell may contain a pointer to an overflow page. If so, write + ** the entry for the overflow page into the pointer map. + */ + ptrmapPutOvflPtr(pPage, pCell, pRC); + } +#endif + } +} + +/* +** Add a list of cells to a page. The page should be initially empty. +** The cells are guaranteed to fit on the page. +*/ +static void assemblePage( + MemPage *pPage, /* The page to be assemblied */ + int nCell, /* The number of cells to add to this page */ + u8 **apCell, /* Pointers to cell bodies */ + u16 *aSize /* Sizes of the cells */ +){ + int i; /* Loop counter */ + u8 *pCellptr; /* Address of next cell pointer */ + int cellbody; /* Address of next cell body */ + u8 * const data = pPage->aData; /* Pointer to data for pPage */ + const int hdr = pPage->hdrOffset; /* Offset of header on pPage */ + const int nUsable = pPage->pBt->usableSize; /* Usable size of page */ + + assert( pPage->nOverflow==0 ); + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt) + && (int)MX_CELL(pPage->pBt)<=10921); + assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + + /* Check that the page has just been zeroed by zeroPage() */ + assert( pPage->nCell==0 ); + assert( get2byteNotZero(&data[hdr+5])==nUsable ); + + pCellptr = &pPage->aCellIdx[nCell*2]; + cellbody = nUsable; + for(i=nCell-1; i>=0; i--){ + u16 sz = aSize[i]; + pCellptr -= 2; + cellbody -= sz; + put2byte(pCellptr, cellbody); + memcpy(&data[cellbody], apCell[i], sz); + } + put2byte(&data[hdr+3], nCell); + put2byte(&data[hdr+5], cellbody); + pPage->nFree -= (nCell*2 + nUsable - cellbody); + pPage->nCell = (u16)nCell; +} + +/* +** The following parameters determine how many adjacent pages get involved +** in a balancing operation. NN is the number of neighbors on either side +** of the page that participate in the balancing operation. NB is the +** total number of pages that participate, including the target page and +** NN neighbors on either side. +** +** The minimum value of NN is 1 (of course). Increasing NN above 1 +** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance +** in exchange for a larger degradation in INSERT and UPDATE performance. +** The value of NN appears to give the best results overall. +*/ +#define NN 1 /* Number of neighbors on either side of pPage */ +#define NB (NN*2+1) /* Total pages involved in the balance */ + + +#ifndef SQLITE_OMIT_QUICKBALANCE +/* +** This version of balance() handles the common special case where +** a new entry is being inserted on the extreme right-end of the +** tree, in other words, when the new entry will become the largest +** entry in the tree. +** +** Instead of trying to balance the 3 right-most leaf pages, just add +** a new page to the right-hand side and put the one new entry in +** that page. This leaves the right side of the tree somewhat +** unbalanced. But odds are that we will be inserting new entries +** at the end soon afterwards so the nearly empty page will quickly +** fill up. On average. +** +** pPage is the leaf page which is the right-most page in the tree. +** pParent is its parent. pPage must have a single overflow entry +** which is also the right-most entry on the page. +** +** The pSpace buffer is used to store a temporary copy of the divider +** cell that will be inserted into pParent. Such a cell consists of a 4 +** byte page number followed by a variable length integer. In other +** words, at most 13 bytes. Hence the pSpace buffer must be at +** least 13 bytes in size. +*/ +static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ + BtShared *const pBt = pPage->pBt; /* B-Tree Database */ + MemPage *pNew; /* Newly allocated page */ + int rc; /* Return Code */ + Pgno pgnoNew; /* Page number of pNew */ + + assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + assert( pPage->nOverflow==1 ); + + /* This error condition is now caught prior to reaching this function */ + if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; + + /* Allocate a new page. This page will become the right-sibling of + ** pPage. Make the parent page writable, so that the new divider cell + ** may be inserted. If both these operations are successful, proceed. + */ + rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); + + if( rc==SQLITE_OK ){ + + u8 *pOut = &pSpace[4]; + u8 *pCell = pPage->apOvfl[0]; + u16 szCell = cellSizePtr(pPage, pCell); + u8 *pStop; + + assert( sqlite3PagerIswriteable(pNew->pDbPage) ); + assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); + zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); + assemblePage(pNew, 1, &pCell, &szCell); + + /* If this is an auto-vacuum database, update the pointer map + ** with entries for the new page, and any pointer from the + ** cell on the page to an overflow page. If either of these + ** operations fails, the return code is set, but the contents + ** of the parent page are still manipulated by thh code below. + ** That is Ok, at this point the parent page is guaranteed to + ** be marked as dirty. Returning an error code will cause a + ** rollback, undoing any changes made to the parent page. + */ + if( ISAUTOVACUUM ){ + ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc); + if( szCell>pNew->minLocal ){ + ptrmapPutOvflPtr(pNew, pCell, &rc); + } + } + + /* Create a divider cell to insert into pParent. The divider cell + ** consists of a 4-byte page number (the page number of pPage) and + ** a variable length key value (which must be the same value as the + ** largest key on pPage). + ** + ** To find the largest key value on pPage, first find the right-most + ** cell on pPage. The first two fields of this cell are the + ** record-length (a variable length integer at most 32-bits in size) + ** and the key value (a variable length integer, may have any value). + ** The first of the while(...) loops below skips over the record-length + ** field. The second while(...) loop copies the key value from the + ** cell on pPage into the pSpace buffer. + */ + pCell = findCell(pPage, pPage->nCell-1); + pStop = &pCell[9]; + while( (*(pCell++)&0x80) && pCellnCell, pSpace, (int)(pOut-pSpace), + 0, pPage->pgno, &rc); + + /* Set the right-child pointer of pParent to point to the new page. */ + put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); + + /* Release the reference to the new page. */ + releasePage(pNew); + } + + return rc; +} +#endif /* SQLITE_OMIT_QUICKBALANCE */ + +#if 0 +/* +** This function does not contribute anything to the operation of SQLite. +** it is sometimes activated temporarily while debugging code responsible +** for setting pointer-map entries. +*/ +static int ptrmapCheckPages(MemPage **apPage, int nPage){ + int i, j; + for(i=0; ipBt; + assert( pPage->isInit ); + + for(j=0; jnCell; j++){ + CellInfo info; + u8 *z; + + z = findCell(pPage, j); + btreeParseCellPtr(pPage, z, &info); + if( info.iOverflow ){ + Pgno ovfl = get4byte(&z[info.iOverflow]); + ptrmapGet(pBt, ovfl, &e, &n); + assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 ); + } + if( !pPage->leaf ){ + Pgno child = get4byte(z); + ptrmapGet(pBt, child, &e, &n); + assert( n==pPage->pgno && e==PTRMAP_BTREE ); + } + } + if( !pPage->leaf ){ + Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]); + ptrmapGet(pBt, child, &e, &n); + assert( n==pPage->pgno && e==PTRMAP_BTREE ); + } + } + return 1; +} +#endif + +/* +** This function is used to copy the contents of the b-tree node stored +** on page pFrom to page pTo. If page pFrom was not a leaf page, then +** the pointer-map entries for each child page are updated so that the +** parent page stored in the pointer map is page pTo. If pFrom contained +** any cells with overflow page pointers, then the corresponding pointer +** map entries are also updated so that the parent page is page pTo. +** +** If pFrom is currently carrying any overflow cells (entries in the +** MemPage.apOvfl[] array), they are not copied to pTo. +** +** Before returning, page pTo is reinitialized using btreeInitPage(). +** +** The performance of this function is not critical. It is only used by +** the balance_shallower() and balance_deeper() procedures, neither of +** which are called often under normal circumstances. +*/ +static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ + if( (*pRC)==SQLITE_OK ){ + BtShared * const pBt = pFrom->pBt; + u8 * const aFrom = pFrom->aData; + u8 * const aTo = pTo->aData; + int const iFromHdr = pFrom->hdrOffset; + int const iToHdr = ((pTo->pgno==1) ? 100 : 0); + int rc; + int iData; + + + assert( pFrom->isInit ); + assert( pFrom->nFree>=iToHdr ); + assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize ); + + /* Copy the b-tree node content from page pFrom to page pTo. */ + iData = get2byte(&aFrom[iFromHdr+5]); + memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); + memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); + + /* Reinitialize page pTo so that the contents of the MemPage structure + ** match the new data. The initialization of pTo can actually fail under + ** fairly obscure circumstances, even though it is a copy of initialized + ** page pFrom. + */ + pTo->isInit = 0; + rc = btreeInitPage(pTo); + if( rc!=SQLITE_OK ){ + *pRC = rc; + return; + } + + /* If this is an auto-vacuum database, update the pointer-map entries + ** for any b-tree or overflow pages that pTo now contains the pointers to. + */ + if( ISAUTOVACUUM ){ + *pRC = setChildPtrmaps(pTo); + } + } +} + +/* +** This routine redistributes cells on the iParentIdx'th child of pParent +** (hereafter "the page") and up to 2 siblings so that all pages have about the +** same amount of free space. Usually a single sibling on either side of the +** page are used in the balancing, though both siblings might come from one +** side if the page is the first or last child of its parent. If the page +** has fewer than 2 siblings (something which can only happen if the page +** is a root page or a child of a root page) then all available siblings +** participate in the balancing. +** +** The number of siblings of the page might be increased or decreased by +** one or two in an effort to keep pages nearly full but not over full. +** +** Note that when this routine is called, some of the cells on the page +** might not actually be stored in MemPage.aData[]. This can happen +** if the page is overfull. This routine ensures that all cells allocated +** to the page and its siblings fit into MemPage.aData[] before returning. +** +** In the course of balancing the page and its siblings, cells may be +** inserted into or removed from the parent page (pParent). Doing so +** may cause the parent page to become overfull or underfull. If this +** happens, it is the responsibility of the caller to invoke the correct +** balancing routine to fix this problem (see the balance() routine). +** +** If this routine fails for any reason, it might leave the database +** in a corrupted state. So if this routine fails, the database should +** be rolled back. +** +** The third argument to this function, aOvflSpace, is a pointer to a +** buffer big enough to hold one page. If while inserting cells into the parent +** page (pParent) the parent page becomes overfull, this buffer is +** used to store the parent's overflow cells. Because this function inserts +** a maximum of four divider cells into the parent page, and the maximum +** size of a cell stored within an internal node is always less than 1/4 +** of the page-size, the aOvflSpace[] buffer is guaranteed to be large +** enough for all overflow cells. +** +** If aOvflSpace is set to a null pointer, this function returns +** SQLITE_NOMEM. +*/ +#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM) +#pragma optimize("", off) +#endif +static int balance_nonroot( + MemPage *pParent, /* Parent page of siblings being balanced */ + int iParentIdx, /* Index of "the page" in pParent */ + u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ + int isRoot, /* True if pParent is a root-page */ + int bBulk /* True if this call is part of a bulk load */ +){ + BtShared *pBt; /* The whole database */ + int nCell = 0; /* Number of cells in apCell[] */ + int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ + int nNew = 0; /* Number of pages in apNew[] */ + int nOld; /* Number of pages in apOld[] */ + int i, j, k; /* Loop counters */ + int nxDiv; /* Next divider slot in pParent->aCell[] */ + int rc = SQLITE_OK; /* The return code */ + u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ + int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ + int usableSpace; /* Bytes in pPage beyond the header */ + int pageFlags; /* Value of pPage->aData[0] */ + int subtotal; /* Subtotal of bytes in cells on one page */ + int iSpace1 = 0; /* First unused byte of aSpace1[] */ + int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ + int szScratch; /* Size of scratch memory requested */ + MemPage *apOld[NB]; /* pPage and up to two siblings */ + MemPage *apCopy[NB]; /* Private copies of apOld[] pages */ + MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ + u8 *pRight; /* Location in parent of right-sibling pointer */ + u8 *apDiv[NB-1]; /* Divider cells in pParent */ + int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */ + int szNew[NB+2]; /* Combined size of cells place on i-th page */ + u8 **apCell = 0; /* All cells begin balanced */ + u16 *szCell; /* Local size of all cells in apCell[] */ + u8 *aSpace1; /* Space for copies of dividers cells */ + Pgno pgno; /* Temp var to store a page number in */ + + pBt = pParent->pBt; + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + +#if 0 + TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); +#endif + + /* At this point pParent may have at most one overflow cell. And if + ** this overflow cell is present, it must be the cell with + ** index iParentIdx. This scenario comes about when this function + ** is called (indirectly) from sqlite3BtreeDelete(). + */ + assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); + assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); + + if( !aOvflSpace ){ + return SQLITE_NOMEM; + } + + /* Find the sibling pages to balance. Also locate the cells in pParent + ** that divide the siblings. An attempt is made to find NN siblings on + ** either side of pPage. More siblings are taken from one side, however, + ** if there are fewer than NN siblings on the other side. If pParent + ** has NB or fewer children then all children of pParent are taken. + ** + ** This loop also drops the divider cells from the parent page. This + ** way, the remainder of the function does not have to deal with any + ** overflow cells in the parent page, since if any existed they will + ** have already been removed. + */ + i = pParent->nOverflow + pParent->nCell; + if( i<2 ){ + nxDiv = 0; + }else{ + assert( bBulk==0 || bBulk==1 ); + if( iParentIdx==0 ){ + nxDiv = 0; + }else if( iParentIdx==i ){ + nxDiv = i-2+bBulk; + }else{ + assert( bBulk==0 ); + nxDiv = iParentIdx-1; + } + i = 2-bBulk; + } + nOld = i+1; + if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ + pRight = &pParent->aData[pParent->hdrOffset+8]; + }else{ + pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); + } + pgno = get4byte(pRight); + while( 1 ){ + rc = getAndInitPage(pBt, pgno, &apOld[i], 0); + if( rc ){ + memset(apOld, 0, (i+1)*sizeof(MemPage*)); + goto balance_cleanup; + } + nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; + if( (i--)==0 ) break; + + if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){ + apDiv[i] = pParent->apOvfl[0]; + pgno = get4byte(apDiv[i]); + szNew[i] = cellSizePtr(pParent, apDiv[i]); + pParent->nOverflow = 0; + }else{ + apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); + pgno = get4byte(apDiv[i]); + szNew[i] = cellSizePtr(pParent, apDiv[i]); + + /* Drop the cell from the parent page. apDiv[i] still points to + ** the cell within the parent, even though it has been dropped. + ** This is safe because dropping a cell only overwrites the first + ** four bytes of it, and this function does not need the first + ** four bytes of the divider cell. So the pointer is safe to use + ** later on. + ** + ** But not if we are in secure-delete mode. In secure-delete mode, + ** the dropCell() routine will overwrite the entire cell with zeroes. + ** In this case, temporarily copy the cell into the aOvflSpace[] + ** buffer. It will be copied out again as soon as the aSpace[] buffer + ** is allocated. */ + if( pBt->btsFlags & BTS_SECURE_DELETE ){ + int iOff; + + iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); + if( (iOff+szNew[i])>(int)pBt->usableSize ){ + rc = SQLITE_CORRUPT_BKPT; + memset(apOld, 0, (i+1)*sizeof(MemPage*)); + goto balance_cleanup; + }else{ + memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); + apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; + } + } + dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); + } + } + + /* Make nMaxCells a multiple of 4 in order to preserve 8-byte + ** alignment */ + nMaxCells = (nMaxCells + 3)&~3; + + /* + ** Allocate space for memory structures + */ + k = pBt->pageSize + ROUND8(sizeof(MemPage)); + szScratch = + nMaxCells*sizeof(u8*) /* apCell */ + + nMaxCells*sizeof(u16) /* szCell */ + + pBt->pageSize /* aSpace1 */ + + k*nOld; /* Page copies (apCopy) */ + apCell = sqlite3ScratchMalloc( szScratch ); + if( apCell==0 ){ + rc = SQLITE_NOMEM; + goto balance_cleanup; + } + szCell = (u16*)&apCell[nMaxCells]; + aSpace1 = (u8*)&szCell[nMaxCells]; + assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); + + /* + ** Load pointers to all cells on sibling pages and the divider cells + ** into the local apCell[] array. Make copies of the divider cells + ** into space obtained from aSpace1[] and remove the divider cells + ** from pParent. + ** + ** If the siblings are on leaf pages, then the child pointers of the + ** divider cells are stripped from the cells before they are copied + ** into aSpace1[]. In this way, all cells in apCell[] are without + ** child pointers. If siblings are not leaves, then all cell in + ** apCell[] include child pointers. Either way, all cells in apCell[] + ** are alike. + ** + ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. + ** leafData: 1 if pPage holds key+data and pParent holds only keys. + */ + leafCorrection = apOld[0]->leaf*4; + leafData = apOld[0]->hasData; + for(i=0; ipageSize + k*i]; + memcpy(pOld, apOld[i], sizeof(MemPage)); + pOld->aData = (void*)&pOld[1]; + memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize); + + limit = pOld->nCell+pOld->nOverflow; + if( pOld->nOverflow>0 ){ + for(j=0; jaData; + u16 maskPage = pOld->maskPage; + u16 cellOffset = pOld->cellOffset; + for(j=0; jmaxLocal+23 ); + assert( iSpace1 <= (int)pBt->pageSize ); + memcpy(pTemp, apDiv[i], sz); + apCell[nCell] = pTemp+leafCorrection; + assert( leafCorrection==0 || leafCorrection==4 ); + szCell[nCell] = szCell[nCell] - leafCorrection; + if( !pOld->leaf ){ + assert( leafCorrection==0 ); + assert( pOld->hdrOffset==0 ); + /* The right pointer of the child page pOld becomes the left + ** pointer of the divider cell */ + memcpy(apCell[nCell], &pOld->aData[8], 4); + }else{ + assert( leafCorrection==4 ); + if( szCell[nCell]<4 ){ + /* Do not allow any cells smaller than 4 bytes. */ + szCell[nCell] = 4; + } + } + nCell++; + } + } + + /* + ** Figure out the number of pages needed to hold all nCell cells. + ** Store this number in "k". Also compute szNew[] which is the total + ** size of all cells on the i-th page and cntNew[] which is the index + ** in apCell[] of the cell that divides page i from page i+1. + ** cntNew[k] should equal nCell. + ** + ** Values computed by this block: + ** + ** k: The total number of sibling pages + ** szNew[i]: Spaced used on the i-th sibling page. + ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to + ** the right of the i-th sibling page. + ** usableSpace: Number of bytes of space available on each sibling. + ** + */ + usableSpace = pBt->usableSize - 12 + leafCorrection; + for(subtotal=k=i=0; i usableSpace ){ + szNew[k] = subtotal - szCell[i]; + cntNew[k] = i; + if( leafData ){ i--; } + subtotal = 0; + k++; + if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } + } + } + szNew[k] = subtotal; + cntNew[k] = nCell; + k++; + + /* + ** The packing computed by the previous block is biased toward the siblings + ** on the left side. The left siblings are always nearly full, while the + ** right-most sibling might be nearly empty. This block of code attempts + ** to adjust the packing of siblings to get a better balance. + ** + ** This adjustment is more than an optimization. The packing above might + ** be so out of balance as to be illegal. For example, the right-most + ** sibling might be completely empty. This adjustment is not optional. + */ + for(i=k-1; i>0; i--){ + int szRight = szNew[i]; /* Size of sibling on the right */ + int szLeft = szNew[i-1]; /* Size of sibling on the left */ + int r; /* Index of right-most cell in left sibling */ + int d; /* Index of first cell to the left of right sibling */ + + r = cntNew[i-1] - 1; + d = r + 1 - leafData; + assert( d0) or pPage is + ** a virtual root page. A virtual root page is when the real root + ** page is page 1 and we are the only child of that page. + ** + ** UPDATE: The assert() below is not necessarily true if the database + ** file is corrupt. The corruption will be detected and reported later + ** in this procedure so there is no need to act upon it now. + */ +#if 0 + assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) ); +#endif + + TRACE(("BALANCE: old: %d %d %d ", + apOld[0]->pgno, + nOld>=2 ? apOld[1]->pgno : 0, + nOld>=3 ? apOld[2]->pgno : 0 + )); + + /* + ** Allocate k new pages. Reuse old pages where possible. + */ + if( apOld[0]->pgno<=1 ){ + rc = SQLITE_CORRUPT_BKPT; + goto balance_cleanup; + } + pageFlags = apOld[0]->aData[0]; + for(i=0; ipDbPage); + nNew++; + if( rc ) goto balance_cleanup; + }else{ + assert( i>0 ); + rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); + if( rc ) goto balance_cleanup; + apNew[i] = pNew; + nNew++; + + /* Set the pointer-map entry for the new sibling page. */ + if( ISAUTOVACUUM ){ + ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); + if( rc!=SQLITE_OK ){ + goto balance_cleanup; + } + } + } + } + + /* Free any old pages that were not reused as new pages. + */ + while( ipgno; + int minI = i; + for(j=i+1; jpgno<(unsigned)minV ){ + minI = j; + minV = apNew[j]->pgno; + } + } + if( minI>i ){ + MemPage *pT; + pT = apNew[i]; + apNew[i] = apNew[minI]; + apNew[minI] = pT; + } + } + TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n", + apNew[0]->pgno, szNew[0], + nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0, + nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0, + nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0, + nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0)); + + assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + put4byte(pRight, apNew[nNew-1]->pgno); + + /* + ** Evenly distribute the data in apCell[] across the new pages. + ** Insert divider cells into pParent as necessary. + */ + j = 0; + for(i=0; inCell>0 || (nNew==1 && cntNew[0]==0) ); + assert( pNew->nOverflow==0 ); + + j = cntNew[i]; + + /* If the sibling page assembled above was not the right-most sibling, + ** insert a divider cell into the parent page. + */ + assert( ileaf ){ + memcpy(&pNew->aData[8], pCell, 4); + }else if( leafData ){ + /* If the tree is a leaf-data tree, and the siblings are leaves, + ** then there is no divider cell in apCell[]. Instead, the divider + ** cell consists of the integer key for the right-most cell of + ** the sibling-page assembled above only. + */ + CellInfo info; + j--; + btreeParseCellPtr(pNew, apCell[j], &info); + pCell = pTemp; + sz = 4 + putVarint(&pCell[4], info.nKey); + pTemp = 0; + }else{ + pCell -= 4; + /* Obscure case for non-leaf-data trees: If the cell at pCell was + ** previously stored on a leaf node, and its reported size was 4 + ** bytes, then it may actually be smaller than this + ** (see btreeParseCellPtr(), 4 bytes is the minimum size of + ** any cell). But it is important to pass the correct size to + ** insertCell(), so reparse the cell now. + ** + ** Note that this can never happen in an SQLite data file, as all + ** cells are at least 4 bytes. It only happens in b-trees used + ** to evaluate "IN (SELECT ...)" and similar clauses. + */ + if( szCell[j]==4 ){ + assert(leafCorrection==4); + sz = cellSizePtr(pParent, pCell); + } + } + iOvflSpace += sz; + assert( sz<=pBt->maxLocal+23 ); + assert( iOvflSpace <= (int)pBt->pageSize ); + insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc); + if( rc!=SQLITE_OK ) goto balance_cleanup; + assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + + j++; + nxDiv++; + } + } + assert( j==nCell ); + assert( nOld>0 ); + assert( nNew>0 ); + if( (pageFlags & PTF_LEAF)==0 ){ + u8 *zChild = &apCopy[nOld-1]->aData[8]; + memcpy(&apNew[nNew-1]->aData[8], zChild, 4); + } + + if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){ + /* The root page of the b-tree now contains no cells. The only sibling + ** page is the right-child of the parent. Copy the contents of the + ** child page into the parent, decreasing the overall height of the + ** b-tree structure by one. This is described as the "balance-shallower" + ** sub-algorithm in some documentation. + ** + ** If this is an auto-vacuum database, the call to copyNodeContent() + ** sets all pointer-map entries corresponding to database image pages + ** for which the pointer is stored within the content being copied. + ** + ** The second assert below verifies that the child page is defragmented + ** (it must be, as it was just reconstructed using assemblePage()). This + ** is important if the parent page happens to be page 1 of the database + ** image. */ + assert( nNew==1 ); + assert( apNew[0]->nFree == + (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) + ); + copyNodeContent(apNew[0], pParent, &rc); + freePage(apNew[0], &rc); + }else if( ISAUTOVACUUM ){ + /* Fix the pointer-map entries for all the cells that were shifted around. + ** There are several different types of pointer-map entries that need to + ** be dealt with by this routine. Some of these have been set already, but + ** many have not. The following is a summary: + ** + ** 1) The entries associated with new sibling pages that were not + ** siblings when this function was called. These have already + ** been set. We don't need to worry about old siblings that were + ** moved to the free-list - the freePage() code has taken care + ** of those. + ** + ** 2) The pointer-map entries associated with the first overflow + ** page in any overflow chains used by new divider cells. These + ** have also already been taken care of by the insertCell() code. + ** + ** 3) If the sibling pages are not leaves, then the child pages of + ** cells stored on the sibling pages may need to be updated. + ** + ** 4) If the sibling pages are not internal intkey nodes, then any + ** overflow pages used by these cells may need to be updated + ** (internal intkey nodes never contain pointers to overflow pages). + ** + ** 5) If the sibling pages are not leaves, then the pointer-map + ** entries for the right-child pages of each sibling may need + ** to be updated. + ** + ** Cases 1 and 2 are dealt with above by other code. The next + ** block deals with cases 3 and 4 and the one after that, case 5. Since + ** setting a pointer map entry is a relatively expensive operation, this + ** code only sets pointer map entries for child or overflow pages that have + ** actually moved between pages. */ + MemPage *pNew = apNew[0]; + MemPage *pOld = apCopy[0]; + int nOverflow = pOld->nOverflow; + int iNextOld = pOld->nCell + nOverflow; + int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1); + j = 0; /* Current 'old' sibling page */ + k = 0; /* Current 'new' sibling page */ + for(i=0; inCell + pOld->nOverflow; + if( pOld->nOverflow ){ + nOverflow = pOld->nOverflow; + iOverflow = i + !leafData + pOld->aiOvfl[0]; + } + isDivider = !leafData; + } + + assert(nOverflow>0 || iOverflowaiOvfl[0]==pOld->aiOvfl[1]-1); + assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1); + if( i==iOverflow ){ + isDivider = 1; + if( (--nOverflow)>0 ){ + iOverflow++; + } + } + + if( i==cntNew[k] ){ + /* Cell i is the cell immediately following the last cell on new + ** sibling page k. If the siblings are not leaf pages of an + ** intkey b-tree, then cell i is a divider cell. */ + pNew = apNew[++k]; + if( !leafData ) continue; + } + assert( jpgno!=pNew->pgno ){ + if( !leafCorrection ){ + ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc); + } + if( szCell[i]>pNew->minLocal ){ + ptrmapPutOvflPtr(pNew, apCell[i], &rc); + } + } + } + + if( !leafCorrection ){ + for(i=0; iaData[8]); + ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc); + } + } + +#if 0 + /* The ptrmapCheckPages() contains assert() statements that verify that + ** all pointer map pages are set correctly. This is helpful while + ** debugging. This is usually disabled because a corrupt database may + ** cause an assert() statement to fail. */ + ptrmapCheckPages(apNew, nNew); + ptrmapCheckPages(&pParent, 1); +#endif + } + + assert( pParent->isInit ); + TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n", + nOld, nNew, nCell)); + + /* + ** Cleanup before returning. + */ +balance_cleanup: + sqlite3ScratchFree(apCell); + for(i=0; i= 1700 && defined(_M_ARM) +#pragma optimize("", on) +#endif + + +/* +** This function is called when the root page of a b-tree structure is +** overfull (has one or more overflow pages). +** +** A new child page is allocated and the contents of the current root +** page, including overflow cells, are copied into the child. The root +** page is then overwritten to make it an empty page with the right-child +** pointer pointing to the new page. +** +** Before returning, all pointer-map entries corresponding to pages +** that the new child-page now contains pointers to are updated. The +** entry corresponding to the new right-child pointer of the root +** page is also updated. +** +** If successful, *ppChild is set to contain a reference to the child +** page and SQLITE_OK is returned. In this case the caller is required +** to call releasePage() on *ppChild exactly once. If an error occurs, +** an error code is returned and *ppChild is set to 0. +*/ +static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ + int rc; /* Return value from subprocedures */ + MemPage *pChild = 0; /* Pointer to a new child page */ + Pgno pgnoChild = 0; /* Page number of the new child page */ + BtShared *pBt = pRoot->pBt; /* The BTree */ + + assert( pRoot->nOverflow>0 ); + assert( sqlite3_mutex_held(pBt->mutex) ); + + /* Make pRoot, the root page of the b-tree, writable. Allocate a new + ** page that will become the new right-child of pPage. Copy the contents + ** of the node stored on pRoot into the new child page. + */ + rc = sqlite3PagerWrite(pRoot->pDbPage); + if( rc==SQLITE_OK ){ + rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); + copyNodeContent(pRoot, pChild, &rc); + if( ISAUTOVACUUM ){ + ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc); + } + } + if( rc ){ + *ppChild = 0; + releasePage(pChild); + return rc; + } + assert( sqlite3PagerIswriteable(pChild->pDbPage) ); + assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); + assert( pChild->nCell==pRoot->nCell ); + + TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); + + /* Copy the overflow cells from pRoot to pChild */ + memcpy(pChild->aiOvfl, pRoot->aiOvfl, + pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); + memcpy(pChild->apOvfl, pRoot->apOvfl, + pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); + pChild->nOverflow = pRoot->nOverflow; + + /* Zero the contents of pRoot. Then install pChild as the right-child. */ + zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); + put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); + + *ppChild = pChild; + return SQLITE_OK; +} + +/* +** The page that pCur currently points to has just been modified in +** some way. This function figures out if this modification means the +** tree needs to be balanced, and if so calls the appropriate balancing +** routine. Balancing routines are: +** +** balance_quick() +** balance_deeper() +** balance_nonroot() +*/ +static int balance(BtCursor *pCur){ + int rc = SQLITE_OK; + const int nMin = pCur->pBt->usableSize * 2 / 3; + u8 aBalanceQuickSpace[13]; + u8 *pFree = 0; + + TESTONLY( int balance_quick_called = 0 ); + TESTONLY( int balance_deeper_called = 0 ); + + do { + int iPage = pCur->iPage; + MemPage *pPage = pCur->apPage[iPage]; + + if( iPage==0 ){ + if( pPage->nOverflow ){ + /* The root page of the b-tree is overfull. In this case call the + ** balance_deeper() function to create a new child for the root-page + ** and copy the current contents of the root-page to it. The + ** next iteration of the do-loop will balance the child page. + */ + assert( (balance_deeper_called++)==0 ); + rc = balance_deeper(pPage, &pCur->apPage[1]); + if( rc==SQLITE_OK ){ + pCur->iPage = 1; + pCur->aiIdx[0] = 0; + pCur->aiIdx[1] = 0; + assert( pCur->apPage[1]->nOverflow ); + } + }else{ + break; + } + }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ + break; + }else{ + MemPage * const pParent = pCur->apPage[iPage-1]; + int const iIdx = pCur->aiIdx[iPage-1]; + + rc = sqlite3PagerWrite(pParent->pDbPage); + if( rc==SQLITE_OK ){ +#ifndef SQLITE_OMIT_QUICKBALANCE + if( pPage->hasData + && pPage->nOverflow==1 + && pPage->aiOvfl[0]==pPage->nCell + && pParent->pgno!=1 + && pParent->nCell==iIdx + ){ + /* Call balance_quick() to create a new sibling of pPage on which + ** to store the overflow cell. balance_quick() inserts a new cell + ** into pParent, which may cause pParent overflow. If this + ** happens, the next interation of the do-loop will balance pParent + ** use either balance_nonroot() or balance_deeper(). Until this + ** happens, the overflow cell is stored in the aBalanceQuickSpace[] + ** buffer. + ** + ** The purpose of the following assert() is to check that only a + ** single call to balance_quick() is made for each call to this + ** function. If this were not verified, a subtle bug involving reuse + ** of the aBalanceQuickSpace[] might sneak in. + */ + assert( (balance_quick_called++)==0 ); + rc = balance_quick(pParent, pPage, aBalanceQuickSpace); + }else +#endif + { + /* In this case, call balance_nonroot() to redistribute cells + ** between pPage and up to 2 of its sibling pages. This involves + ** modifying the contents of pParent, which may cause pParent to + ** become overfull or underfull. The next iteration of the do-loop + ** will balance the parent page to correct this. + ** + ** If the parent page becomes overfull, the overflow cell or cells + ** are stored in the pSpace buffer allocated immediately below. + ** A subsequent iteration of the do-loop will deal with this by + ** calling balance_nonroot() (balance_deeper() may be called first, + ** but it doesn't deal with overflow cells - just moves them to a + ** different page). Once this subsequent call to balance_nonroot() + ** has completed, it is safe to release the pSpace buffer used by + ** the previous call, as the overflow cell data will have been + ** copied either into the body of a database page or into the new + ** pSpace buffer passed to the latter call to balance_nonroot(). + */ + u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); + rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints); + if( pFree ){ + /* If pFree is not NULL, it points to the pSpace buffer used + ** by a previous call to balance_nonroot(). Its contents are + ** now stored either on real database pages or within the + ** new pSpace buffer, so it may be safely freed here. */ + sqlite3PageFree(pFree); + } + + /* The pSpace buffer will be freed after the next call to + ** balance_nonroot(), or just before this function returns, whichever + ** comes first. */ + pFree = pSpace; + } + } + + pPage->nOverflow = 0; + + /* The next iteration of the do-loop balances the parent page. */ + releasePage(pPage); + pCur->iPage--; + } + }while( rc==SQLITE_OK ); + + if( pFree ){ + sqlite3PageFree(pFree); + } + return rc; +} + + +/* +** Insert a new record into the BTree. The key is given by (pKey,nKey) +** and the data is given by (pData,nData). The cursor is used only to +** define what table the record should be inserted into. The cursor +** is left pointing at a random location. +** +** For an INTKEY table, only the nKey value of the key is used. pKey is +** ignored. For a ZERODATA table, the pData and nData are both ignored. +** +** If the seekResult parameter is non-zero, then a successful call to +** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already +** been performed. seekResult is the search result returned (a negative +** number if pCur points at an entry that is smaller than (pKey, nKey), or +** a positive value if pCur points at an etry that is larger than +** (pKey, nKey)). +** +** If the seekResult parameter is non-zero, then the caller guarantees that +** cursor pCur is pointing at the existing copy of a row that is to be +** overwritten. If the seekResult parameter is 0, then cursor pCur may +** point to any entry or to no entry at all and so this function has to seek +** the cursor before the new key can be inserted. +*/ +int sqlite3BtreeInsert( + BtCursor *pCur, /* Insert data into the table of this cursor */ + const void *pKey, i64 nKey, /* The key of the new record */ + const void *pData, int nData, /* The data of the new record */ + int nZero, /* Number of extra 0 bytes to append to data */ + int appendBias, /* True if this is likely an append */ + int seekResult /* Result of prior MovetoUnpacked() call */ +){ + int rc; + int loc = seekResult; /* -1: before desired location +1: after */ + int szNew = 0; + int idx; + MemPage *pPage; + Btree *p = pCur->pBtree; + BtShared *pBt = p->pBt; + unsigned char *oldCell; + unsigned char *newCell = 0; + + if( pCur->eState==CURSOR_FAULT ){ + assert( pCur->skipNext!=SQLITE_OK ); + return pCur->skipNext; + } + + assert( cursorHoldsMutex(pCur) ); + assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE + && (pBt->btsFlags & BTS_READ_ONLY)==0 ); + assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); + + /* Assert that the caller has been consistent. If this cursor was opened + ** expecting an index b-tree, then the caller should be inserting blob + ** keys with no associated data. If the cursor was opened expecting an + ** intkey table, the caller should be inserting integer keys with a + ** blob of associated data. */ + assert( (pKey==0)==(pCur->pKeyInfo==0) ); + + /* Save the positions of any other cursors open on this table. + ** + ** In some cases, the call to btreeMoveto() below is a no-op. For + ** example, when inserting data into a table with auto-generated integer + ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the + ** integer key to use. It then calls this function to actually insert the + ** data into the intkey B-Tree. In this case btreeMoveto() recognizes + ** that the cursor is already where it needs to be and returns without + ** doing any work. To avoid thwarting these optimizations, it is important + ** not to clear the cursor here. + */ + rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); + if( rc ) return rc; + + /* If this is an insert into a table b-tree, invalidate any incrblob + ** cursors open on the row being replaced (assuming this is a replace + ** operation - if it is not, the following is a no-op). */ + if( pCur->pKeyInfo==0 ){ + invalidateIncrblobCursors(p, nKey, 0); + } + + if( !loc ){ + rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc); + if( rc ) return rc; + } + assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) ); + + pPage = pCur->apPage[pCur->iPage]; + assert( pPage->intKey || nKey>=0 ); + assert( pPage->leaf || !pPage->intKey ); + + TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", + pCur->pgnoRoot, nKey, nData, pPage->pgno, + loc==0 ? "overwrite" : "new entry")); + assert( pPage->isInit ); + allocateTempSpace(pBt); + newCell = pBt->pTmpSpace; + if( newCell==0 ) return SQLITE_NOMEM; + rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew); + if( rc ) goto end_insert; + assert( szNew==cellSizePtr(pPage, newCell) ); + assert( szNew <= MX_CELL_SIZE(pBt) ); + idx = pCur->aiIdx[pCur->iPage]; + if( loc==0 ){ + u16 szOld; + assert( idxnCell ); + rc = sqlite3PagerWrite(pPage->pDbPage); + if( rc ){ + goto end_insert; + } + oldCell = findCell(pPage, idx); + if( !pPage->leaf ){ + memcpy(newCell, oldCell, 4); + } + szOld = cellSizePtr(pPage, oldCell); + rc = clearCell(pPage, oldCell); + dropCell(pPage, idx, szOld, &rc); + if( rc ) goto end_insert; + }else if( loc<0 && pPage->nCell>0 ){ + assert( pPage->leaf ); + idx = ++pCur->aiIdx[pCur->iPage]; + }else{ + assert( pPage->leaf ); + } + insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); + assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); + + /* If no error has occurred and pPage has an overflow cell, call balance() + ** to redistribute the cells within the tree. Since balance() may move + ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey + ** variables. + ** + ** Previous versions of SQLite called moveToRoot() to move the cursor + ** back to the root page as balance() used to invalidate the contents + ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, + ** set the cursor state to "invalid". This makes common insert operations + ** slightly faster. + ** + ** There is a subtle but important optimization here too. When inserting + ** multiple records into an intkey b-tree using a single cursor (as can + ** happen while processing an "INSERT INTO ... SELECT" statement), it + ** is advantageous to leave the cursor pointing to the last entry in + ** the b-tree if possible. If the cursor is left pointing to the last + ** entry in the table, and the next row inserted has an integer key + ** larger than the largest existing key, it is possible to insert the + ** row without seeking the cursor. This can be a big performance boost. + */ + pCur->info.nSize = 0; + pCur->validNKey = 0; + if( rc==SQLITE_OK && pPage->nOverflow ){ + rc = balance(pCur); + + /* Must make sure nOverflow is reset to zero even if the balance() + ** fails. Internal data structure corruption will result otherwise. + ** Also, set the cursor state to invalid. This stops saveCursorPosition() + ** from trying to save the current position of the cursor. */ + pCur->apPage[pCur->iPage]->nOverflow = 0; + pCur->eState = CURSOR_INVALID; + } + assert( pCur->apPage[pCur->iPage]->nOverflow==0 ); + +end_insert: + return rc; +} + +/* +** Delete the entry that the cursor is pointing to. The cursor +** is left pointing at a arbitrary location. +*/ +int sqlite3BtreeDelete(BtCursor *pCur){ + Btree *p = pCur->pBtree; + BtShared *pBt = p->pBt; + int rc; /* Return code */ + MemPage *pPage; /* Page to delete cell from */ + unsigned char *pCell; /* Pointer to cell to delete */ + int iCellIdx; /* Index of cell to delete */ + int iCellDepth; /* Depth of node containing pCell */ + + assert( cursorHoldsMutex(pCur) ); + assert( pBt->inTransaction==TRANS_WRITE ); + assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); + assert( pCur->wrFlag ); + assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); + assert( !hasReadConflicts(p, pCur->pgnoRoot) ); + + if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) + || NEVER(pCur->eState!=CURSOR_VALID) + ){ + return SQLITE_ERROR; /* Something has gone awry. */ + } + + iCellDepth = pCur->iPage; + iCellIdx = pCur->aiIdx[iCellDepth]; + pPage = pCur->apPage[iCellDepth]; + pCell = findCell(pPage, iCellIdx); + + /* If the page containing the entry to delete is not a leaf page, move + ** the cursor to the largest entry in the tree that is smaller than + ** the entry being deleted. This cell will replace the cell being deleted + ** from the internal node. The 'previous' entry is used for this instead + ** of the 'next' entry, as the previous entry is always a part of the + ** sub-tree headed by the child page of the cell being deleted. This makes + ** balancing the tree following the delete operation easier. */ + if( !pPage->leaf ){ + int notUsed; + rc = sqlite3BtreePrevious(pCur, ¬Used); + if( rc ) return rc; + } + + /* Save the positions of any other cursors open on this table before + ** making any modifications. Make the page containing the entry to be + ** deleted writable. Then free any overflow pages associated with the + ** entry and finally remove the cell itself from within the page. + */ + rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); + if( rc ) return rc; + + /* If this is a delete operation to remove a row from a table b-tree, + ** invalidate any incrblob cursors open on the row being deleted. */ + if( pCur->pKeyInfo==0 ){ + invalidateIncrblobCursors(p, pCur->info.nKey, 0); + } + + rc = sqlite3PagerWrite(pPage->pDbPage); + if( rc ) return rc; + rc = clearCell(pPage, pCell); + dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc); + if( rc ) return rc; + + /* If the cell deleted was not located on a leaf page, then the cursor + ** is currently pointing to the largest entry in the sub-tree headed + ** by the child-page of the cell that was just deleted from an internal + ** node. The cell from the leaf node needs to be moved to the internal + ** node to replace the deleted cell. */ + if( !pPage->leaf ){ + MemPage *pLeaf = pCur->apPage[pCur->iPage]; + int nCell; + Pgno n = pCur->apPage[iCellDepth+1]->pgno; + unsigned char *pTmp; + + pCell = findCell(pLeaf, pLeaf->nCell-1); + nCell = cellSizePtr(pLeaf, pCell); + assert( MX_CELL_SIZE(pBt) >= nCell ); + + allocateTempSpace(pBt); + pTmp = pBt->pTmpSpace; + + rc = sqlite3PagerWrite(pLeaf->pDbPage); + insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); + dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); + if( rc ) return rc; + } + + /* Balance the tree. If the entry deleted was located on a leaf page, + ** then the cursor still points to that page. In this case the first + ** call to balance() repairs the tree, and the if(...) condition is + ** never true. + ** + ** Otherwise, if the entry deleted was on an internal node page, then + ** pCur is pointing to the leaf page from which a cell was removed to + ** replace the cell deleted from the internal node. This is slightly + ** tricky as the leaf node may be underfull, and the internal node may + ** be either under or overfull. In this case run the balancing algorithm + ** on the leaf node first. If the balance proceeds far enough up the + ** tree that we can be sure that any problem in the internal node has + ** been corrected, so be it. Otherwise, after balancing the leaf node, + ** walk the cursor up the tree to the internal node and balance it as + ** well. */ + rc = balance(pCur); + if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){ + while( pCur->iPage>iCellDepth ){ + releasePage(pCur->apPage[pCur->iPage--]); + } + rc = balance(pCur); + } + + if( rc==SQLITE_OK ){ + moveToRoot(pCur); + } + return rc; +} + +/* +** Create a new BTree table. Write into *piTable the page +** number for the root page of the new table. +** +** The type of type is determined by the flags parameter. Only the +** following values of flags are currently in use. Other values for +** flags might not work: +** +** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys +** BTREE_ZERODATA Used for SQL indices +*/ +static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ + BtShared *pBt = p->pBt; + MemPage *pRoot; + Pgno pgnoRoot; + int rc; + int ptfFlags; /* Page-type flage for the root page of new table */ + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( pBt->inTransaction==TRANS_WRITE ); + assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); + +#ifdef SQLITE_OMIT_AUTOVACUUM + rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); + if( rc ){ + return rc; + } +#else + if( pBt->autoVacuum ){ + Pgno pgnoMove; /* Move a page here to make room for the root-page */ + MemPage *pPageMove; /* The page to move to. */ + + /* Creating a new table may probably require moving an existing database + ** to make room for the new tables root page. In case this page turns + ** out to be an overflow page, delete all overflow page-map caches + ** held by open cursors. + */ + invalidateAllOverflowCache(pBt); + + /* Read the value of meta[3] from the database to determine where the + ** root page of the new table should go. meta[3] is the largest root-page + ** created so far, so the new root-page is (meta[3]+1). + */ + sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); + pgnoRoot++; + + /* The new root-page may not be allocated on a pointer-map page, or the + ** PENDING_BYTE page. + */ + while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || + pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ + pgnoRoot++; + } + assert( pgnoRoot>=3 ); + + /* Allocate a page. The page that currently resides at pgnoRoot will + ** be moved to the allocated page (unless the allocated page happens + ** to reside at pgnoRoot). + */ + rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT); + if( rc!=SQLITE_OK ){ + return rc; + } + + if( pgnoMove!=pgnoRoot ){ + /* pgnoRoot is the page that will be used for the root-page of + ** the new table (assuming an error did not occur). But we were + ** allocated pgnoMove. If required (i.e. if it was not allocated + ** by extending the file), the current page at position pgnoMove + ** is already journaled. + */ + u8 eType = 0; + Pgno iPtrPage = 0; + + /* Save the positions of any open cursors. This is required in + ** case they are holding a reference to an xFetch reference + ** corresponding to page pgnoRoot. */ + rc = saveAllCursors(pBt, 0, 0); + releasePage(pPageMove); + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Move the page currently at pgnoRoot to pgnoMove. */ + rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); + if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ + rc = SQLITE_CORRUPT_BKPT; + } + if( rc!=SQLITE_OK ){ + releasePage(pRoot); + return rc; + } + assert( eType!=PTRMAP_ROOTPAGE ); + assert( eType!=PTRMAP_FREEPAGE ); + rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); + releasePage(pRoot); + + /* Obtain the page at pgnoRoot */ + if( rc!=SQLITE_OK ){ + return rc; + } + rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + rc = sqlite3PagerWrite(pRoot->pDbPage); + if( rc!=SQLITE_OK ){ + releasePage(pRoot); + return rc; + } + }else{ + pRoot = pPageMove; + } + + /* Update the pointer-map and meta-data with the new root-page number. */ + ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc); + if( rc ){ + releasePage(pRoot); + return rc; + } + + /* When the new root page was allocated, page 1 was made writable in + ** order either to increase the database filesize, or to decrement the + ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. + */ + assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); + rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); + if( NEVER(rc) ){ + releasePage(pRoot); + return rc; + } + + }else{ + rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); + if( rc ) return rc; + } +#endif + assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); + if( createTabFlags & BTREE_INTKEY ){ + ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; + }else{ + ptfFlags = PTF_ZERODATA | PTF_LEAF; + } + zeroPage(pRoot, ptfFlags); + sqlite3PagerUnref(pRoot->pDbPage); + assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 ); + *piTable = (int)pgnoRoot; + return SQLITE_OK; +} +int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ + int rc; + sqlite3BtreeEnter(p); + rc = btreeCreateTable(p, piTable, flags); + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Erase the given database page and all its children. Return +** the page to the freelist. +*/ +static int clearDatabasePage( + BtShared *pBt, /* The BTree that contains the table */ + Pgno pgno, /* Page number to clear */ + int freePageFlag, /* Deallocate page if true */ + int *pnChange /* Add number of Cells freed to this counter */ +){ + MemPage *pPage; + int rc; + unsigned char *pCell; + int i; + + assert( sqlite3_mutex_held(pBt->mutex) ); + if( pgno>btreePagecount(pBt) ){ + return SQLITE_CORRUPT_BKPT; + } + + rc = getAndInitPage(pBt, pgno, &pPage, 0); + if( rc ) return rc; + for(i=0; inCell; i++){ + pCell = findCell(pPage, i); + if( !pPage->leaf ){ + rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); + if( rc ) goto cleardatabasepage_out; + } + rc = clearCell(pPage, pCell); + if( rc ) goto cleardatabasepage_out; + } + if( !pPage->leaf ){ + rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange); + if( rc ) goto cleardatabasepage_out; + }else if( pnChange ){ + assert( pPage->intKey ); + *pnChange += pPage->nCell; + } + if( freePageFlag ){ + freePage(pPage, &rc); + }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ + zeroPage(pPage, pPage->aData[0] | PTF_LEAF); + } + +cleardatabasepage_out: + releasePage(pPage); + return rc; +} + +/* +** Delete all information from a single table in the database. iTable is +** the page number of the root of the table. After this routine returns, +** the root page is empty, but still exists. +** +** This routine will fail with SQLITE_LOCKED if there are any open +** read cursors on the table. Open write cursors are moved to the +** root of the table. +** +** If pnChange is not NULL, then table iTable must be an intkey table. The +** integer value pointed to by pnChange is incremented by the number of +** entries in the table. +*/ +int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ + int rc; + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); + assert( p->inTrans==TRANS_WRITE ); + + rc = saveAllCursors(pBt, (Pgno)iTable, 0); + + if( SQLITE_OK==rc ){ + /* Invalidate all incrblob cursors open on table iTable (assuming iTable + ** is the root of a table b-tree - if it is not, the following call is + ** a no-op). */ + invalidateIncrblobCursors(p, 0, 1); + rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); + } + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Erase all information in a table and add the root of the table to +** the freelist. Except, the root of the principle table (the one on +** page 1) is never added to the freelist. +** +** This routine will fail with SQLITE_LOCKED if there are any open +** cursors on the table. +** +** If AUTOVACUUM is enabled and the page at iTable is not the last +** root page in the database file, then the last root page +** in the database file is moved into the slot formerly occupied by +** iTable and that last slot formerly occupied by the last root page +** is added to the freelist instead of iTable. In this say, all +** root pages are kept at the beginning of the database file, which +** is necessary for AUTOVACUUM to work right. *piMoved is set to the +** page number that used to be the last root page in the file before +** the move. If no page gets moved, *piMoved is set to 0. +** The last root page is recorded in meta[3] and the value of +** meta[3] is updated by this procedure. +*/ +static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ + int rc; + MemPage *pPage = 0; + BtShared *pBt = p->pBt; + + assert( sqlite3BtreeHoldsMutex(p) ); + assert( p->inTrans==TRANS_WRITE ); + + /* It is illegal to drop a table if any cursors are open on the + ** database. This is because in auto-vacuum mode the backend may + ** need to move another root-page to fill a gap left by the deleted + ** root page. If an open cursor was using this page a problem would + ** occur. + ** + ** This error is caught long before control reaches this point. + */ + if( NEVER(pBt->pCursor) ){ + sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db); + return SQLITE_LOCKED_SHAREDCACHE; + } + + rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); + if( rc ) return rc; + rc = sqlite3BtreeClearTable(p, iTable, 0); + if( rc ){ + releasePage(pPage); + return rc; + } + + *piMoved = 0; + + if( iTable>1 ){ +#ifdef SQLITE_OMIT_AUTOVACUUM + freePage(pPage, &rc); + releasePage(pPage); +#else + if( pBt->autoVacuum ){ + Pgno maxRootPgno; + sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); + + if( iTable==maxRootPgno ){ + /* If the table being dropped is the table with the largest root-page + ** number in the database, put the root page on the free list. + */ + freePage(pPage, &rc); + releasePage(pPage); + if( rc!=SQLITE_OK ){ + return rc; + } + }else{ + /* The table being dropped does not have the largest root-page + ** number in the database. So move the page that does into the + ** gap left by the deleted root-page. + */ + MemPage *pMove; + releasePage(pPage); + rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); + if( rc!=SQLITE_OK ){ + return rc; + } + rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); + releasePage(pMove); + if( rc!=SQLITE_OK ){ + return rc; + } + pMove = 0; + rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); + freePage(pMove, &rc); + releasePage(pMove); + if( rc!=SQLITE_OK ){ + return rc; + } + *piMoved = maxRootPgno; + } + + /* Set the new 'max-root-page' value in the database header. This + ** is the old value less one, less one more if that happens to + ** be a root-page number, less one again if that is the + ** PENDING_BYTE_PAGE. + */ + maxRootPgno--; + while( maxRootPgno==PENDING_BYTE_PAGE(pBt) + || PTRMAP_ISPAGE(pBt, maxRootPgno) ){ + maxRootPgno--; + } + assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); + + rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); + }else{ + freePage(pPage, &rc); + releasePage(pPage); + } +#endif + }else{ + /* If sqlite3BtreeDropTable was called on page 1. + ** This really never should happen except in a corrupt + ** database. + */ + zeroPage(pPage, PTF_INTKEY|PTF_LEAF ); + releasePage(pPage); + } + return rc; +} +int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ + int rc; + sqlite3BtreeEnter(p); + rc = btreeDropTable(p, iTable, piMoved); + sqlite3BtreeLeave(p); + return rc; +} + + +/* +** This function may only be called if the b-tree connection already +** has a read or write transaction open on the database. +** +** Read the meta-information out of a database file. Meta[0] +** is the number of free pages currently in the database. Meta[1] +** through meta[15] are available for use by higher layers. Meta[0] +** is read-only, the others are read/write. +** +** The schema layer numbers meta values differently. At the schema +** layer (and the SetCookie and ReadCookie opcodes) the number of +** free pages is not visible. So Cookie[0] is the same as Meta[1]. +*/ +void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ + BtShared *pBt = p->pBt; + + sqlite3BtreeEnter(p); + assert( p->inTrans>TRANS_NONE ); + assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) ); + assert( pBt->pPage1 ); + assert( idx>=0 && idx<=15 ); + + *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); + + /* If auto-vacuum is disabled in this build and this is an auto-vacuum + ** database, mark the database as read-only. */ +#ifdef SQLITE_OMIT_AUTOVACUUM + if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){ + pBt->btsFlags |= BTS_READ_ONLY; + } +#endif + + sqlite3BtreeLeave(p); +} + +/* +** Write meta-information back into the database. Meta[0] is +** read-only and may not be written. +*/ +int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ + BtShared *pBt = p->pBt; + unsigned char *pP1; + int rc; + assert( idx>=1 && idx<=15 ); + sqlite3BtreeEnter(p); + assert( p->inTrans==TRANS_WRITE ); + assert( pBt->pPage1!=0 ); + pP1 = pBt->pPage1->aData; + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + if( rc==SQLITE_OK ){ + put4byte(&pP1[36 + idx*4], iMeta); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( idx==BTREE_INCR_VACUUM ){ + assert( pBt->autoVacuum || iMeta==0 ); + assert( iMeta==0 || iMeta==1 ); + pBt->incrVacuum = (u8)iMeta; + } +#endif + } + sqlite3BtreeLeave(p); + return rc; +} + +#ifndef SQLITE_OMIT_BTREECOUNT +/* +** The first argument, pCur, is a cursor opened on some b-tree. Count the +** number of entries in the b-tree and write the result to *pnEntry. +** +** SQLITE_OK is returned if the operation is successfully executed. +** Otherwise, if an error is encountered (i.e. an IO error or database +** corruption) an SQLite error code is returned. +*/ +int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ + i64 nEntry = 0; /* Value to return in *pnEntry */ + int rc; /* Return code */ + + if( pCur->pgnoRoot==0 ){ + *pnEntry = 0; + return SQLITE_OK; + } + rc = moveToRoot(pCur); + + /* Unless an error occurs, the following loop runs one iteration for each + ** page in the B-Tree structure (not including overflow pages). + */ + while( rc==SQLITE_OK ){ + int iIdx; /* Index of child node in parent */ + MemPage *pPage; /* Current page of the b-tree */ + + /* If this is a leaf page or the tree is not an int-key tree, then + ** this page contains countable entries. Increment the entry counter + ** accordingly. + */ + pPage = pCur->apPage[pCur->iPage]; + if( pPage->leaf || !pPage->intKey ){ + nEntry += pPage->nCell; + } + + /* pPage is a leaf node. This loop navigates the cursor so that it + ** points to the first interior cell that it points to the parent of + ** the next page in the tree that has not yet been visited. The + ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell + ** of the page, or to the number of cells in the page if the next page + ** to visit is the right-child of its parent. + ** + ** If all pages in the tree have been visited, return SQLITE_OK to the + ** caller. + */ + if( pPage->leaf ){ + do { + if( pCur->iPage==0 ){ + /* All pages of the b-tree have been visited. Return successfully. */ + *pnEntry = nEntry; + return SQLITE_OK; + } + moveToParent(pCur); + }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell ); + + pCur->aiIdx[pCur->iPage]++; + pPage = pCur->apPage[pCur->iPage]; + } + + /* Descend to the child node of the cell that the cursor currently + ** points at. This is the right-child if (iIdx==pPage->nCell). + */ + iIdx = pCur->aiIdx[pCur->iPage]; + if( iIdx==pPage->nCell ){ + rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); + }else{ + rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx))); + } + } + + /* An error has occurred. Return an error code. */ + return rc; +} +#endif + +/* +** Return the pager associated with a BTree. This routine is used for +** testing and debugging only. +*/ +Pager *sqlite3BtreePager(Btree *p){ + return p->pBt->pPager; +} + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK +/* +** Append a message to the error message string. +*/ +static void checkAppendMsg( + IntegrityCk *pCheck, + char *zMsg1, + const char *zFormat, + ... +){ + va_list ap; + if( !pCheck->mxErr ) return; + pCheck->mxErr--; + pCheck->nErr++; + va_start(ap, zFormat); + if( pCheck->errMsg.nChar ){ + sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1); + } + if( zMsg1 ){ + sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1); + } + sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap); + va_end(ap); + if( pCheck->errMsg.accError==STRACCUM_NOMEM ){ + pCheck->mallocFailed = 1; + } +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK + +/* +** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that +** corresponds to page iPg is already set. +*/ +static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ + assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); + return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); +} + +/* +** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. +*/ +static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ + assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); + pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); +} + + +/* +** Add 1 to the reference count for page iPage. If this is the second +** reference to the page, add an error message to pCheck->zErrMsg. +** Return 1 if there are 2 ore more references to the page and 0 if +** if this is the first reference to the page. +** +** Also check that the page number is in bounds. +*/ +static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){ + if( iPage==0 ) return 1; + if( iPage>pCheck->nPage ){ + checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage); + return 1; + } + if( getPageReferenced(pCheck, iPage) ){ + checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage); + return 1; + } + setPageReferenced(pCheck, iPage); + return 0; +} + +#ifndef SQLITE_OMIT_AUTOVACUUM +/* +** Check that the entry in the pointer-map for page iChild maps to +** page iParent, pointer type ptrType. If not, append an error message +** to pCheck. +*/ +static void checkPtrmap( + IntegrityCk *pCheck, /* Integrity check context */ + Pgno iChild, /* Child page number */ + u8 eType, /* Expected pointer map type */ + Pgno iParent, /* Expected pointer map parent page number */ + char *zContext /* Context description (used for error msg) */ +){ + int rc; + u8 ePtrmapType; + Pgno iPtrmapParent; + + rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1; + checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild); + return; + } + + if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ + checkAppendMsg(pCheck, zContext, + "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", + iChild, eType, iParent, ePtrmapType, iPtrmapParent); + } +} +#endif + +/* +** Check the integrity of the freelist or of an overflow page list. +** Verify that the number of pages on the list is N. +*/ +static void checkList( + IntegrityCk *pCheck, /* Integrity checking context */ + int isFreeList, /* True for a freelist. False for overflow page list */ + int iPage, /* Page number for first page in the list */ + int N, /* Expected number of pages in the list */ + char *zContext /* Context for error messages */ +){ + int i; + int expected = N; + int iFirst = iPage; + while( N-- > 0 && pCheck->mxErr ){ + DbPage *pOvflPage; + unsigned char *pOvflData; + if( iPage<1 ){ + checkAppendMsg(pCheck, zContext, + "%d of %d pages missing from overflow list starting at %d", + N+1, expected, iFirst); + break; + } + if( checkRef(pCheck, iPage, zContext) ) break; + if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){ + checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage); + break; + } + pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); + if( isFreeList ){ + int n = get4byte(&pOvflData[4]); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pCheck->pBt->autoVacuum ){ + checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext); + } +#endif + if( n>(int)pCheck->pBt->usableSize/4-2 ){ + checkAppendMsg(pCheck, zContext, + "freelist leaf count too big on page %d", iPage); + N--; + }else{ + for(i=0; ipBt->autoVacuum ){ + checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext); + } +#endif + checkRef(pCheck, iFreePage, zContext); + } + N -= n; + } + } +#ifndef SQLITE_OMIT_AUTOVACUUM + else{ + /* If this database supports auto-vacuum and iPage is not the last + ** page in this overflow list, check that the pointer-map entry for + ** the following page matches iPage. + */ + if( pCheck->pBt->autoVacuum && N>0 ){ + i = get4byte(pOvflData); + checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext); + } + } +#endif + iPage = get4byte(pOvflData); + sqlite3PagerUnref(pOvflPage); + } +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK +/* +** Do various sanity checks on a single page of a tree. Return +** the tree depth. Root pages return 0. Parents of root pages +** return 1, and so forth. +** +** These checks are done: +** +** 1. Make sure that cells and freeblocks do not overlap +** but combine to completely cover the page. +** NO 2. Make sure cell keys are in order. +** NO 3. Make sure no key is less than or equal to zLowerBound. +** NO 4. Make sure no key is greater than or equal to zUpperBound. +** 5. Check the integrity of overflow pages. +** 6. Recursively call checkTreePage on all children. +** 7. Verify that the depth of all children is the same. +** 8. Make sure this page is at least 33% full or else it is +** the root of the tree. +*/ +static int checkTreePage( + IntegrityCk *pCheck, /* Context for the sanity check */ + int iPage, /* Page number of the page to check */ + char *zParentContext, /* Parent context */ + i64 *pnParentMinKey, + i64 *pnParentMaxKey +){ + MemPage *pPage; + int i, rc, depth, d2, pgno, cnt; + int hdr, cellStart; + int nCell; + u8 *data; + BtShared *pBt; + int usableSize; + char zContext[100]; + char *hit = 0; + i64 nMinKey = 0; + i64 nMaxKey = 0; + + sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage); + + /* Check that the page exists + */ + pBt = pCheck->pBt; + usableSize = pBt->usableSize; + if( iPage==0 ) return 0; + if( checkRef(pCheck, iPage, zParentContext) ) return 0; + if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){ + checkAppendMsg(pCheck, zContext, + "unable to get the page. error code=%d", rc); + return 0; + } + + /* Clear MemPage.isInit to make sure the corruption detection code in + ** btreeInitPage() is executed. */ + pPage->isInit = 0; + if( (rc = btreeInitPage(pPage))!=0 ){ + assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ + checkAppendMsg(pCheck, zContext, + "btreeInitPage() returns error code %d", rc); + releasePage(pPage); + return 0; + } + + /* Check out all the cells. + */ + depth = 0; + for(i=0; inCell && pCheck->mxErr; i++){ + u8 *pCell; + u32 sz; + CellInfo info; + + /* Check payload overflow pages + */ + sqlite3_snprintf(sizeof(zContext), zContext, + "On tree page %d cell %d: ", iPage, i); + pCell = findCell(pPage,i); + btreeParseCellPtr(pPage, pCell, &info); + sz = info.nData; + if( !pPage->intKey ) sz += (int)info.nKey; + /* For intKey pages, check that the keys are in order. + */ + else if( i==0 ) nMinKey = nMaxKey = info.nKey; + else{ + if( info.nKey <= nMaxKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey); + } + nMaxKey = info.nKey; + } + assert( sz==info.nPayload ); + if( (sz>info.nLocal) + && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize]) + ){ + int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4); + Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum ){ + checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext); + } +#endif + checkList(pCheck, 0, pgnoOvfl, nPage, zContext); + } + + /* Check sanity of left child page. + */ + if( !pPage->leaf ){ + pgno = get4byte(pCell); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum ){ + checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); + } +#endif + d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey); + if( i>0 && d2!=depth ){ + checkAppendMsg(pCheck, zContext, "Child page depth differs"); + } + depth = d2; + } + } + + if( !pPage->leaf ){ + pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); + sqlite3_snprintf(sizeof(zContext), zContext, + "On page %d at right child: ", iPage); +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum ){ + checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); + } +#endif + checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey); + } + + /* For intKey leaf pages, check that the min/max keys are in order + ** with any left/parent/right pages. + */ + if( pPage->leaf && pPage->intKey ){ + /* if we are a left child page */ + if( pnParentMinKey ){ + /* if we are the left most child page */ + if( !pnParentMaxKey ){ + if( nMaxKey > *pnParentMinKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (max larger than parent min of %lld)", + nMaxKey, *pnParentMinKey); + } + }else{ + if( nMinKey <= *pnParentMinKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (min less than parent min of %lld)", + nMinKey, *pnParentMinKey); + } + if( nMaxKey > *pnParentMaxKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (max larger than parent max of %lld)", + nMaxKey, *pnParentMaxKey); + } + *pnParentMinKey = nMaxKey; + } + /* else if we're a right child page */ + } else if( pnParentMaxKey ){ + if( nMinKey <= *pnParentMaxKey ){ + checkAppendMsg(pCheck, zContext, + "Rowid %lld out of order (min less than parent max of %lld)", + nMinKey, *pnParentMaxKey); + } + } + } + + /* Check for complete coverage of the page + */ + data = pPage->aData; + hdr = pPage->hdrOffset; + hit = sqlite3PageMalloc( pBt->pageSize ); + if( hit==0 ){ + pCheck->mallocFailed = 1; + }else{ + int contentOffset = get2byteNotZero(&data[hdr+5]); + assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ + memset(hit+contentOffset, 0, usableSize-contentOffset); + memset(hit, 1, contentOffset); + nCell = get2byte(&data[hdr+3]); + cellStart = hdr + 12 - 4*pPage->leaf; + for(i=0; i=usableSize ){ + checkAppendMsg(pCheck, 0, + "Corruption detected in cell %d on page %d",i,iPage); + }else{ + for(j=pc+size-1; j>=pc; j--) hit[j]++; + } + } + i = get2byte(&data[hdr+1]); + while( i>0 ){ + int size, j; + assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */ + size = get2byte(&data[i+2]); + assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */ + for(j=i+size-1; j>=i; j--) hit[j]++; + j = get2byte(&data[i]); + assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */ + assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */ + i = j; + } + for(i=cnt=0; i1 ){ + checkAppendMsg(pCheck, 0, + "Multiple uses for byte %d of page %d", i, iPage); + break; + } + } + if( cnt!=data[hdr+7] ){ + checkAppendMsg(pCheck, 0, + "Fragmentation of %d bytes reported as %d on page %d", + cnt, data[hdr+7], iPage); + } + } + sqlite3PageFree(hit); + releasePage(pPage); + return depth+1; +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK +/* +** This routine does a complete check of the given BTree file. aRoot[] is +** an array of pages numbers were each page number is the root page of +** a table. nRoot is the number of entries in aRoot. +** +** A read-only or read-write transaction must be opened before calling +** this function. +** +** Write the number of error seen in *pnErr. Except for some memory +** allocation errors, an error message held in memory obtained from +** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is +** returned. If a memory allocation error occurs, NULL is returned. +*/ +char *sqlite3BtreeIntegrityCheck( + Btree *p, /* The btree to be checked */ + int *aRoot, /* An array of root pages numbers for individual trees */ + int nRoot, /* Number of entries in aRoot[] */ + int mxErr, /* Stop reporting errors after this many */ + int *pnErr /* Write number of errors seen to this variable */ +){ + Pgno i; + int nRef; + IntegrityCk sCheck; + BtShared *pBt = p->pBt; + char zErr[100]; + + sqlite3BtreeEnter(p); + assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); + nRef = sqlite3PagerRefcount(pBt->pPager); + sCheck.pBt = pBt; + sCheck.pPager = pBt->pPager; + sCheck.nPage = btreePagecount(sCheck.pBt); + sCheck.mxErr = mxErr; + sCheck.nErr = 0; + sCheck.mallocFailed = 0; + *pnErr = 0; + if( sCheck.nPage==0 ){ + sqlite3BtreeLeave(p); + return 0; + } + + sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); + if( !sCheck.aPgRef ){ + *pnErr = 1; + sqlite3BtreeLeave(p); + return 0; + } + i = PENDING_BYTE_PAGE(pBt); + if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); + sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); + sCheck.errMsg.useMalloc = 2; + + /* Check the integrity of the freelist + */ + checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), + get4byte(&pBt->pPage1->aData[36]), "Main freelist: "); + + /* Check all the tables. + */ + for(i=0; (int)iautoVacuum && aRoot[i]>1 ){ + checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0); + } +#endif + checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL); + } + + /* Make sure every page in the file is referenced + */ + for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ +#ifdef SQLITE_OMIT_AUTOVACUUM + if( getPageReferenced(&sCheck, i)==0 ){ + checkAppendMsg(&sCheck, 0, "Page %d is never used", i); + } +#else + /* If the database supports auto-vacuum, make sure no tables contain + ** references to pointer-map pages. + */ + if( getPageReferenced(&sCheck, i)==0 && + (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ + checkAppendMsg(&sCheck, 0, "Page %d is never used", i); + } + if( getPageReferenced(&sCheck, i)!=0 && + (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ + checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i); + } +#endif + } + + /* Make sure this analysis did not leave any unref() pages. + ** This is an internal consistency check; an integrity check + ** of the integrity check. + */ + if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){ + checkAppendMsg(&sCheck, 0, + "Outstanding page count goes from %d to %d during this analysis", + nRef, sqlite3PagerRefcount(pBt->pPager) + ); + } + + /* Clean up and report errors. + */ + sqlite3BtreeLeave(p); + sqlite3_free(sCheck.aPgRef); + if( sCheck.mallocFailed ){ + sqlite3StrAccumReset(&sCheck.errMsg); + *pnErr = sCheck.nErr+1; + return 0; + } + *pnErr = sCheck.nErr; + if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg); + return sqlite3StrAccumFinish(&sCheck.errMsg); +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +/* +** Return the full pathname of the underlying database file. Return +** an empty string if the database is in-memory or a TEMP database. +** +** The pager filename is invariant as long as the pager is +** open so it is safe to access without the BtShared mutex. +*/ +const char *sqlite3BtreeGetFilename(Btree *p){ + assert( p->pBt->pPager!=0 ); + return sqlite3PagerFilename(p->pBt->pPager, 1); +} + +/* +** Return the pathname of the journal file for this database. The return +** value of this routine is the same regardless of whether the journal file +** has been created or not. +** +** The pager journal filename is invariant as long as the pager is +** open so it is safe to access without the BtShared mutex. +*/ +const char *sqlite3BtreeGetJournalname(Btree *p){ + assert( p->pBt->pPager!=0 ); + return sqlite3PagerJournalname(p->pBt->pPager); +} + +/* +** Return non-zero if a transaction is active. +*/ +int sqlite3BtreeIsInTrans(Btree *p){ + assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); + return (p && (p->inTrans==TRANS_WRITE)); +} + +#ifndef SQLITE_OMIT_WAL +/* +** Run a checkpoint on the Btree passed as the first argument. +** +** Return SQLITE_LOCKED if this or any other connection has an open +** transaction on the shared-cache the argument Btree is connected to. +** +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +*/ +int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ + int rc = SQLITE_OK; + if( p ){ + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); + if( pBt->inTransaction!=TRANS_NONE ){ + rc = SQLITE_LOCKED; + }else{ + rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt); + } + sqlite3BtreeLeave(p); + } + return rc; +} +#endif + +/* +** Return non-zero if a read (or write) transaction is active. +*/ +int sqlite3BtreeIsInReadTrans(Btree *p){ + assert( p ); + assert( sqlite3_mutex_held(p->db->mutex) ); + return p->inTrans!=TRANS_NONE; +} + +int sqlite3BtreeIsInBackup(Btree *p){ + assert( p ); + assert( sqlite3_mutex_held(p->db->mutex) ); + return p->nBackup!=0; +} + +/* +** This function returns a pointer to a blob of memory associated with +** a single shared-btree. The memory is used by client code for its own +** purposes (for example, to store a high-level schema associated with +** the shared-btree). The btree layer manages reference counting issues. +** +** The first time this is called on a shared-btree, nBytes bytes of memory +** are allocated, zeroed, and returned to the caller. For each subsequent +** call the nBytes parameter is ignored and a pointer to the same blob +** of memory returned. +** +** If the nBytes parameter is 0 and the blob of memory has not yet been +** allocated, a null pointer is returned. If the blob has already been +** allocated, it is returned as normal. +** +** Just before the shared-btree is closed, the function passed as the +** xFree argument when the memory allocation was made is invoked on the +** blob of allocated memory. The xFree function should not call sqlite3_free() +** on the memory, the btree layer does that. +*/ +void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ + BtShared *pBt = p->pBt; + sqlite3BtreeEnter(p); + if( !pBt->pSchema && nBytes ){ + pBt->pSchema = sqlite3DbMallocZero(0, nBytes); + pBt->xFreeSchema = xFree; + } + sqlite3BtreeLeave(p); + return pBt->pSchema; +} + +/* +** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared +** btree as the argument handle holds an exclusive lock on the +** sqlite_master table. Otherwise SQLITE_OK. +*/ +int sqlite3BtreeSchemaLocked(Btree *p){ + int rc; + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); + assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE ); + sqlite3BtreeLeave(p); + return rc; +} + + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** Obtain a lock on the table whose root page is iTab. The +** lock is a write lock if isWritelock is true or a read lock +** if it is false. +*/ +int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ + int rc = SQLITE_OK; + assert( p->inTrans!=TRANS_NONE ); + if( p->sharable ){ + u8 lockType = READ_LOCK + isWriteLock; + assert( READ_LOCK+1==WRITE_LOCK ); + assert( isWriteLock==0 || isWriteLock==1 ); + + sqlite3BtreeEnter(p); + rc = querySharedCacheTableLock(p, iTab, lockType); + if( rc==SQLITE_OK ){ + rc = setSharedCacheTableLock(p, iTab, lockType); + } + sqlite3BtreeLeave(p); + } + return rc; +} +#endif + +#ifndef SQLITE_OMIT_INCRBLOB +/* +** Argument pCsr must be a cursor opened for writing on an +** INTKEY table currently pointing at a valid table entry. +** This function modifies the data stored as part of that entry. +** +** Only the data content may only be modified, it is not possible to +** change the length of the data stored. If this function is called with +** parameters that attempt to write past the end of the existing data, +** no modifications are made and SQLITE_CORRUPT is returned. +*/ +int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ + int rc; + assert( cursorHoldsMutex(pCsr) ); + assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); + assert( pCsr->isIncrblobHandle ); + + rc = restoreCursorPosition(pCsr); + if( rc!=SQLITE_OK ){ + return rc; + } + assert( pCsr->eState!=CURSOR_REQUIRESEEK ); + if( pCsr->eState!=CURSOR_VALID ){ + return SQLITE_ABORT; + } + + /* Save the positions of all other cursors open on this table. This is + ** required in case any of them are holding references to an xFetch + ** version of the b-tree page modified by the accessPayload call below. + ** + ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition() + ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence + ** saveAllCursors can only return SQLITE_OK. + */ + VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); + assert( rc==SQLITE_OK ); + + /* Check some assumptions: + ** (a) the cursor is open for writing, + ** (b) there is a read/write transaction open, + ** (c) the connection holds a write-lock on the table (if required), + ** (d) there are no conflicting read-locks, and + ** (e) the cursor points at a valid row of an intKey table. + */ + if( !pCsr->wrFlag ){ + return SQLITE_READONLY; + } + assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0 + && pCsr->pBt->inTransaction==TRANS_WRITE ); + assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); + assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); + assert( pCsr->apPage[pCsr->iPage]->intKey ); + + return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); +} + +/* +** Set a flag on this cursor to cache the locations of pages from the +** overflow list for the current row. This is used by cursors opened +** for incremental blob IO only. +** +** This function sets a flag only. The actual page location cache +** (stored in BtCursor.aOverflow[]) is allocated and used by function +** accessPayload() (the worker function for sqlite3BtreeData() and +** sqlite3BtreePutData()). +*/ +void sqlite3BtreeCacheOverflow(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + invalidateOverflowCache(pCur); + pCur->isIncrblobHandle = 1; +} +#endif + +/* +** Set both the "read version" (single byte at byte offset 18) and +** "write version" (single byte at byte offset 19) fields in the database +** header to iVersion. +*/ +int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ + BtShared *pBt = pBtree->pBt; + int rc; /* Return code */ + + assert( iVersion==1 || iVersion==2 ); + + /* If setting the version fields to 1, do not automatically open the + ** WAL connection, even if the version fields are currently set to 2. + */ + pBt->btsFlags &= ~BTS_NO_WAL; + if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; + + rc = sqlite3BtreeBeginTrans(pBtree, 0); + if( rc==SQLITE_OK ){ + u8 *aData = pBt->pPage1->aData; + if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ + rc = sqlite3BtreeBeginTrans(pBtree, 2); + if( rc==SQLITE_OK ){ + rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + if( rc==SQLITE_OK ){ + aData[18] = (u8)iVersion; + aData[19] = (u8)iVersion; + } + } + } + } + + pBt->btsFlags &= ~BTS_NO_WAL; + return rc; +} + +/* +** set the mask of hint flags for cursor pCsr. Currently the only valid +** values are 0 and BTREE_BULKLOAD. +*/ +void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){ + assert( mask==BTREE_BULKLOAD || mask==0 ); + pCsr->hints = mask; +} diff --git a/components/external/SQLite-3.8.1/src/btree.h b/components/external/SQLite-3.8.1/src/btree.h new file mode 100644 index 0000000000000000000000000000000000000000..33b3ed1f089e70c221ec79b17943dafa862cf322 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/btree.h @@ -0,0 +1,253 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite B-Tree file +** subsystem. See comments in the source code for a detailed description +** of what each interface routine does. +*/ +#ifndef _BTREE_H_ +#define _BTREE_H_ + +/* TODO: This definition is just included so other modules compile. It +** needs to be revisited. +*/ +#define SQLITE_N_BTREE_META 10 + +/* +** If defined as non-zero, auto-vacuum is enabled by default. Otherwise +** it must be turned on for each database using "PRAGMA auto_vacuum = 1". +*/ +#ifndef SQLITE_DEFAULT_AUTOVACUUM + #define SQLITE_DEFAULT_AUTOVACUUM 0 +#endif + +#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ +#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ +#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ + +/* +** Forward declarations of structure +*/ +typedef struct Btree Btree; +typedef struct BtCursor BtCursor; +typedef struct BtShared BtShared; + + +int sqlite3BtreeOpen( + sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ + const char *zFilename, /* Name of database file to open */ + sqlite3 *db, /* Associated database connection */ + Btree **ppBtree, /* Return open Btree* here */ + int flags, /* Flags */ + int vfsFlags /* Flags passed through to VFS open */ +); + +/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the +** following values. +** +** NOTE: These values must match the corresponding PAGER_ values in +** pager.h. +*/ +#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ +#define BTREE_MEMORY 2 /* This is an in-memory DB */ +#define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */ +#define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */ + +int sqlite3BtreeClose(Btree*); +int sqlite3BtreeSetCacheSize(Btree*,int); +int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64); +int sqlite3BtreeSetPagerFlags(Btree*,unsigned); +int sqlite3BtreeSyncDisabled(Btree*); +int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); +int sqlite3BtreeGetPageSize(Btree*); +int sqlite3BtreeMaxPageCount(Btree*,int); +u32 sqlite3BtreeLastPage(Btree*); +int sqlite3BtreeSecureDelete(Btree*,int); +int sqlite3BtreeGetReserve(Btree*); +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG) +int sqlite3BtreeGetReserveNoMutex(Btree *p); +#endif +int sqlite3BtreeSetAutoVacuum(Btree *, int); +int sqlite3BtreeGetAutoVacuum(Btree *); +int sqlite3BtreeBeginTrans(Btree*,int); +int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); +int sqlite3BtreeCommitPhaseTwo(Btree*, int); +int sqlite3BtreeCommit(Btree*); +int sqlite3BtreeRollback(Btree*,int); +int sqlite3BtreeBeginStmt(Btree*,int); +int sqlite3BtreeCreateTable(Btree*, int*, int flags); +int sqlite3BtreeIsInTrans(Btree*); +int sqlite3BtreeIsInReadTrans(Btree*); +int sqlite3BtreeIsInBackup(Btree*); +void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); +int sqlite3BtreeSchemaLocked(Btree *pBtree); +int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); +int sqlite3BtreeSavepoint(Btree *, int, int); + +const char *sqlite3BtreeGetFilename(Btree *); +const char *sqlite3BtreeGetJournalname(Btree *); +int sqlite3BtreeCopyFile(Btree *, Btree *); + +int sqlite3BtreeIncrVacuum(Btree *); + +/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR +** of the flags shown below. +** +** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. +** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data +** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With +** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored +** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL +** indices.) +*/ +#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ +#define BTREE_BLOBKEY 2 /* Table has keys only - no data */ + +int sqlite3BtreeDropTable(Btree*, int, int*); +int sqlite3BtreeClearTable(Btree*, int, int*); +void sqlite3BtreeTripAllCursors(Btree*, int); + +void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); +int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); + +int sqlite3BtreeNewDb(Btree *p); + +/* +** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta +** should be one of the following values. The integer values are assigned +** to constants so that the offset of the corresponding field in an +** SQLite database header may be found using the following formula: +** +** offset = 36 + (idx * 4) +** +** For example, the free-page-count field is located at byte offset 36 of +** the database file header. The incr-vacuum-flag field is located at +** byte offset 64 (== 36+4*7). +*/ +#define BTREE_FREE_PAGE_COUNT 0 +#define BTREE_SCHEMA_VERSION 1 +#define BTREE_FILE_FORMAT 2 +#define BTREE_DEFAULT_CACHE_SIZE 3 +#define BTREE_LARGEST_ROOT_PAGE 4 +#define BTREE_TEXT_ENCODING 5 +#define BTREE_USER_VERSION 6 +#define BTREE_INCR_VACUUM 7 +#define BTREE_APPLICATION_ID 8 + +/* +** Values that may be OR'd together to form the second argument of an +** sqlite3BtreeCursorHints() call. +*/ +#define BTREE_BULKLOAD 0x00000001 + +int sqlite3BtreeCursor( + Btree*, /* BTree containing table to open */ + int iTable, /* Index of root page */ + int wrFlag, /* 1 for writing. 0 for read-only */ + struct KeyInfo*, /* First argument to compare function */ + BtCursor *pCursor /* Space to write cursor structure */ +); +int sqlite3BtreeCursorSize(void); +void sqlite3BtreeCursorZero(BtCursor*); + +int sqlite3BtreeCloseCursor(BtCursor*); +int sqlite3BtreeMovetoUnpacked( + BtCursor*, + UnpackedRecord *pUnKey, + i64 intKey, + int bias, + int *pRes +); +int sqlite3BtreeCursorHasMoved(BtCursor*, int*); +int sqlite3BtreeDelete(BtCursor*); +int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey, + const void *pData, int nData, + int nZero, int bias, int seekResult); +int sqlite3BtreeFirst(BtCursor*, int *pRes); +int sqlite3BtreeLast(BtCursor*, int *pRes); +int sqlite3BtreeNext(BtCursor*, int *pRes); +int sqlite3BtreeEof(BtCursor*); +int sqlite3BtreePrevious(BtCursor*, int *pRes); +int sqlite3BtreeKeySize(BtCursor*, i64 *pSize); +int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); +const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt); +const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt); +int sqlite3BtreeDataSize(BtCursor*, u32 *pSize); +int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); +void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64); +sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*); + +char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); +struct Pager *sqlite3BtreePager(Btree*); + +int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); +void sqlite3BtreeCacheOverflow(BtCursor *); +void sqlite3BtreeClearCursor(BtCursor *); +int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); +void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask); + +#ifndef NDEBUG +int sqlite3BtreeCursorIsValid(BtCursor*); +#endif + +#ifndef SQLITE_OMIT_BTREECOUNT +int sqlite3BtreeCount(BtCursor *, i64 *); +#endif + +#ifdef SQLITE_TEST +int sqlite3BtreeCursorInfo(BtCursor*, int*, int); +void sqlite3BtreeCursorList(Btree*); +#endif + +#ifndef SQLITE_OMIT_WAL + int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); +#endif + +/* +** If we are not using shared cache, then there is no need to +** use mutexes to access the BtShared structures. So make the +** Enter and Leave procedures no-ops. +*/ +#ifndef SQLITE_OMIT_SHARED_CACHE + void sqlite3BtreeEnter(Btree*); + void sqlite3BtreeEnterAll(sqlite3*); +#else +# define sqlite3BtreeEnter(X) +# define sqlite3BtreeEnterAll(X) +#endif + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE + int sqlite3BtreeSharable(Btree*); + void sqlite3BtreeLeave(Btree*); + void sqlite3BtreeEnterCursor(BtCursor*); + void sqlite3BtreeLeaveCursor(BtCursor*); + void sqlite3BtreeLeaveAll(sqlite3*); +#ifndef NDEBUG + /* These routines are used inside assert() statements only. */ + int sqlite3BtreeHoldsMutex(Btree*); + int sqlite3BtreeHoldsAllMutexes(sqlite3*); + int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); +#endif +#else + +# define sqlite3BtreeSharable(X) 0 +# define sqlite3BtreeLeave(X) +# define sqlite3BtreeEnterCursor(X) +# define sqlite3BtreeLeaveCursor(X) +# define sqlite3BtreeLeaveAll(X) + +# define sqlite3BtreeHoldsMutex(X) 1 +# define sqlite3BtreeHoldsAllMutexes(X) 1 +# define sqlite3SchemaMutexHeld(X,Y,Z) 1 +#endif + + +#endif /* _BTREE_H_ */ diff --git a/components/external/SQLite-3.8.1/src/btreeInt.h b/components/external/SQLite-3.8.1/src/btreeInt.h new file mode 100644 index 0000000000000000000000000000000000000000..3ebdeb663e75156ebeca9b481d4f59a5002d2169 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/btreeInt.h @@ -0,0 +1,668 @@ +/* +** 2004 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements a external (disk-based) database using BTrees. +** For a detailed discussion of BTrees, refer to +** +** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: +** "Sorting And Searching", pages 473-480. Addison-Wesley +** Publishing Company, Reading, Massachusetts. +** +** The basic idea is that each page of the file contains N database +** entries and N+1 pointers to subpages. +** +** ---------------------------------------------------------------- +** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) | +** ---------------------------------------------------------------- +** +** All of the keys on the page that Ptr(0) points to have values less +** than Key(0). All of the keys on page Ptr(1) and its subpages have +** values greater than Key(0) and less than Key(1). All of the keys +** on Ptr(N) and its subpages have values greater than Key(N-1). And +** so forth. +** +** Finding a particular key requires reading O(log(M)) pages from the +** disk where M is the number of entries in the tree. +** +** In this implementation, a single file can hold one or more separate +** BTrees. Each BTree is identified by the index of its root page. The +** key and data for any entry are combined to form the "payload". A +** fixed amount of payload can be carried directly on the database +** page. If the payload is larger than the preset amount then surplus +** bytes are stored on overflow pages. The payload for an entry +** and the preceding pointer are combined to form a "Cell". Each +** page has a small header which contains the Ptr(N) pointer and other +** information such as the size of key and data. +** +** FORMAT DETAILS +** +** The file is divided into pages. The first page is called page 1, +** the second is page 2, and so forth. A page number of zero indicates +** "no such page". The page size can be any power of 2 between 512 and 65536. +** Each page can be either a btree page, a freelist page, an overflow +** page, or a pointer-map page. +** +** The first page is always a btree page. The first 100 bytes of the first +** page contain a special header (the "file header") that describes the file. +** The format of the file header is as follows: +** +** OFFSET SIZE DESCRIPTION +** 0 16 Header string: "SQLite format 3\000" +** 16 2 Page size in bytes. (1 means 65536) +** 18 1 File format write version +** 19 1 File format read version +** 20 1 Bytes of unused space at the end of each page +** 21 1 Max embedded payload fraction (must be 64) +** 22 1 Min embedded payload fraction (must be 32) +** 23 1 Min leaf payload fraction (must be 32) +** 24 4 File change counter +** 28 4 Reserved for future use +** 32 4 First freelist page +** 36 4 Number of freelist pages in the file +** 40 60 15 4-byte meta values passed to higher layers +** +** 40 4 Schema cookie +** 44 4 File format of schema layer +** 48 4 Size of page cache +** 52 4 Largest root-page (auto/incr_vacuum) +** 56 4 1=UTF-8 2=UTF16le 3=UTF16be +** 60 4 User version +** 64 4 Incremental vacuum mode +** 68 4 Application-ID +** 72 20 unused +** 92 4 The version-valid-for number +** 96 4 SQLITE_VERSION_NUMBER +** +** All of the integer values are big-endian (most significant byte first). +** +** The file change counter is incremented when the database is changed +** This counter allows other processes to know when the file has changed +** and thus when they need to flush their cache. +** +** The max embedded payload fraction is the amount of the total usable +** space in a page that can be consumed by a single cell for standard +** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default +** is to limit the maximum cell size so that at least 4 cells will fit +** on one page. Thus the default max embedded payload fraction is 64. +** +** If the payload for a cell is larger than the max payload, then extra +** payload is spilled to overflow pages. Once an overflow page is allocated, +** as many bytes as possible are moved into the overflow pages without letting +** the cell size drop below the min embedded payload fraction. +** +** The min leaf payload fraction is like the min embedded payload fraction +** except that it applies to leaf nodes in a LEAFDATA tree. The maximum +** payload fraction for a LEAFDATA tree is always 100% (or 255) and it +** not specified in the header. +** +** Each btree pages is divided into three sections: The header, the +** cell pointer array, and the cell content area. Page 1 also has a 100-byte +** file header that occurs before the page header. +** +** |----------------| +** | file header | 100 bytes. Page 1 only. +** |----------------| +** | page header | 8 bytes for leaves. 12 bytes for interior nodes +** |----------------| +** | cell pointer | | 2 bytes per cell. Sorted order. +** | array | | Grows downward +** | | v +** |----------------| +** | unallocated | +** | space | +** |----------------| ^ Grows upwards +** | cell content | | Arbitrary order interspersed with freeblocks. +** | area | | and free space fragments. +** |----------------| +** +** The page headers looks like this: +** +** OFFSET SIZE DESCRIPTION +** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf +** 1 2 byte offset to the first freeblock +** 3 2 number of cells on this page +** 5 2 first byte of the cell content area +** 7 1 number of fragmented free bytes +** 8 4 Right child (the Ptr(N) value). Omitted on leaves. +** +** The flags define the format of this btree page. The leaf flag means that +** this page has no children. The zerodata flag means that this page carries +** only keys and no data. The intkey flag means that the key is a integer +** which is stored in the key size entry of the cell header rather than in +** the payload area. +** +** The cell pointer array begins on the first byte after the page header. +** The cell pointer array contains zero or more 2-byte numbers which are +** offsets from the beginning of the page to the cell content in the cell +** content area. The cell pointers occur in sorted order. The system strives +** to keep free space after the last cell pointer so that new cells can +** be easily added without having to defragment the page. +** +** Cell content is stored at the very end of the page and grows toward the +** beginning of the page. +** +** Unused space within the cell content area is collected into a linked list of +** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset +** to the first freeblock is given in the header. Freeblocks occur in +** increasing order. Because a freeblock must be at least 4 bytes in size, +** any group of 3 or fewer unused bytes in the cell content area cannot +** exist on the freeblock chain. A group of 3 or fewer free bytes is called +** a fragment. The total number of bytes in all fragments is recorded. +** in the page header at offset 7. +** +** SIZE DESCRIPTION +** 2 Byte offset of the next freeblock +** 2 Bytes in this freeblock +** +** Cells are of variable length. Cells are stored in the cell content area at +** the end of the page. Pointers to the cells are in the cell pointer array +** that immediately follows the page header. Cells is not necessarily +** contiguous or in order, but cell pointers are contiguous and in order. +** +** Cell content makes use of variable length integers. A variable +** length integer is 1 to 9 bytes where the lower 7 bits of each +** byte are used. The integer consists of all bytes that have bit 8 set and +** the first byte with bit 8 clear. The most significant byte of the integer +** appears first. A variable-length integer may not be more than 9 bytes long. +** As a special case, all 8 bytes of the 9th byte are used as data. This +** allows a 64-bit integer to be encoded in 9 bytes. +** +** 0x00 becomes 0x00000000 +** 0x7f becomes 0x0000007f +** 0x81 0x00 becomes 0x00000080 +** 0x82 0x00 becomes 0x00000100 +** 0x80 0x7f becomes 0x0000007f +** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678 +** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081 +** +** Variable length integers are used for rowids and to hold the number of +** bytes of key and data in a btree cell. +** +** The content of a cell looks like this: +** +** SIZE DESCRIPTION +** 4 Page number of the left child. Omitted if leaf flag is set. +** var Number of bytes of data. Omitted if the zerodata flag is set. +** var Number of bytes of key. Or the key itself if intkey flag is set. +** * Payload +** 4 First page of the overflow chain. Omitted if no overflow +** +** Overflow pages form a linked list. Each page except the last is completely +** filled with data (pagesize - 4 bytes). The last page can have as little +** as 1 byte of data. +** +** SIZE DESCRIPTION +** 4 Page number of next overflow page +** * Data +** +** Freelist pages come in two subtypes: trunk pages and leaf pages. The +** file header points to the first in a linked list of trunk page. Each trunk +** page points to multiple leaf pages. The content of a leaf page is +** unspecified. A trunk page looks like this: +** +** SIZE DESCRIPTION +** 4 Page number of next trunk page +** 4 Number of leaf pointers on this page +** * zero or more pages numbers of leaves +*/ +#include "sqliteInt.h" + + +/* The following value is the maximum cell size assuming a maximum page +** size give above. +*/ +#define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8)) + +/* The maximum number of cells on a single page of the database. This +** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself +** plus 2 bytes for the index to the cell in the page header). Such +** small cells will be rare, but they are possible. +*/ +#define MX_CELL(pBt) ((pBt->pageSize-8)/6) + +/* Forward declarations */ +typedef struct MemPage MemPage; +typedef struct BtLock BtLock; + +/* +** This is a magic string that appears at the beginning of every +** SQLite database in order to identify the file as a real database. +** +** You can change this value at compile-time by specifying a +** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The +** header must be exactly 16 bytes including the zero-terminator so +** the string itself should be 15 characters long. If you change +** the header, then your custom library will not be able to read +** databases generated by the standard tools and the standard tools +** will not be able to read databases created by your custom library. +*/ +#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */ +# define SQLITE_FILE_HEADER "SQLite format 3" +#endif + +/* +** Page type flags. An ORed combination of these flags appear as the +** first byte of on-disk image of every BTree page. +*/ +#define PTF_INTKEY 0x01 +#define PTF_ZERODATA 0x02 +#define PTF_LEAFDATA 0x04 +#define PTF_LEAF 0x08 + +/* +** As each page of the file is loaded into memory, an instance of the following +** structure is appended and initialized to zero. This structure stores +** information about the page that is decoded from the raw file page. +** +** The pParent field points back to the parent page. This allows us to +** walk up the BTree from any leaf to the root. Care must be taken to +** unref() the parent page pointer when this page is no longer referenced. +** The pageDestructor() routine handles that chore. +** +** Access to all fields of this structure is controlled by the mutex +** stored in MemPage.pBt->mutex. +*/ +struct MemPage { + u8 isInit; /* True if previously initialized. MUST BE FIRST! */ + u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ + u8 intKey; /* True if intkey flag is set */ + u8 leaf; /* True if leaf flag is set */ + u8 hasData; /* True if this page stores data */ + u8 hdrOffset; /* 100 for page 1. 0 otherwise */ + u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ + u8 max1bytePayload; /* min(maxLocal,127) */ + u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ + u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ + u16 cellOffset; /* Index in aData of first cell pointer */ + u16 nFree; /* Number of free bytes on the page */ + u16 nCell; /* Number of cells on this page, local and ovfl */ + u16 maskPage; /* Mask for page offset */ + u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th + ** non-overflow cell */ + u8 *apOvfl[5]; /* Pointers to the body of overflow cells */ + BtShared *pBt; /* Pointer to BtShared that this page is part of */ + u8 *aData; /* Pointer to disk image of the page data */ + u8 *aDataEnd; /* One byte past the end of usable data */ + u8 *aCellIdx; /* The cell index area */ + DbPage *pDbPage; /* Pager page handle */ + Pgno pgno; /* Page number for this page */ +}; + +/* +** The in-memory image of a disk page has the auxiliary information appended +** to the end. EXTRA_SIZE is the number of bytes of space needed to hold +** that extra information. +*/ +#define EXTRA_SIZE sizeof(MemPage) + +/* +** A linked list of the following structures is stored at BtShared.pLock. +** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor +** is opened on the table with root page BtShared.iTable. Locks are removed +** from this list when a transaction is committed or rolled back, or when +** a btree handle is closed. +*/ +struct BtLock { + Btree *pBtree; /* Btree handle holding this lock */ + Pgno iTable; /* Root page of table */ + u8 eLock; /* READ_LOCK or WRITE_LOCK */ + BtLock *pNext; /* Next in BtShared.pLock list */ +}; + +/* Candidate values for BtLock.eLock */ +#define READ_LOCK 1 +#define WRITE_LOCK 2 + +/* A Btree handle +** +** A database connection contains a pointer to an instance of +** this object for every database file that it has open. This structure +** is opaque to the database connection. The database connection cannot +** see the internals of this structure and only deals with pointers to +** this structure. +** +** For some database files, the same underlying database cache might be +** shared between multiple connections. In that case, each connection +** has it own instance of this object. But each instance of this object +** points to the same BtShared object. The database cache and the +** schema associated with the database file are all contained within +** the BtShared object. +** +** All fields in this structure are accessed under sqlite3.mutex. +** The pBt pointer itself may not be changed while there exists cursors +** in the referenced BtShared that point back to this Btree since those +** cursors have to go through this Btree to find their BtShared and +** they often do so without holding sqlite3.mutex. +*/ +struct Btree { + sqlite3 *db; /* The database connection holding this btree */ + BtShared *pBt; /* Sharable content of this btree */ + u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ + u8 sharable; /* True if we can share pBt with another db */ + u8 locked; /* True if db currently has pBt locked */ + int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ + int nBackup; /* Number of backup operations reading this btree */ + Btree *pNext; /* List of other sharable Btrees from the same db */ + Btree *pPrev; /* Back pointer of the same list */ +#ifndef SQLITE_OMIT_SHARED_CACHE + BtLock lock; /* Object used to lock page 1 */ +#endif +}; + +/* +** Btree.inTrans may take one of the following values. +** +** If the shared-data extension is enabled, there may be multiple users +** of the Btree structure. At most one of these may open a write transaction, +** but any number may have active read transactions. +*/ +#define TRANS_NONE 0 +#define TRANS_READ 1 +#define TRANS_WRITE 2 + +/* +** An instance of this object represents a single database file. +** +** A single database file can be in use at the same time by two +** or more database connections. When two or more connections are +** sharing the same database file, each connection has it own +** private Btree object for the file and each of those Btrees points +** to this one BtShared object. BtShared.nRef is the number of +** connections currently sharing this database file. +** +** Fields in this structure are accessed under the BtShared.mutex +** mutex, except for nRef and pNext which are accessed under the +** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field +** may not be modified once it is initially set as long as nRef>0. +** The pSchema field may be set once under BtShared.mutex and +** thereafter is unchanged as long as nRef>0. +** +** isPending: +** +** If a BtShared client fails to obtain a write-lock on a database +** table (because there exists one or more read-locks on the table), +** the shared-cache enters 'pending-lock' state and isPending is +** set to true. +** +** The shared-cache leaves the 'pending lock' state when either of +** the following occur: +** +** 1) The current writer (BtShared.pWriter) concludes its transaction, OR +** 2) The number of locks held by other connections drops to zero. +** +** while in the 'pending-lock' state, no connection may start a new +** transaction. +** +** This feature is included to help prevent writer-starvation. +*/ +struct BtShared { + Pager *pPager; /* The page cache */ + sqlite3 *db; /* Database connection currently using this Btree */ + BtCursor *pCursor; /* A list of all open cursors */ + MemPage *pPage1; /* First page of the database */ + u8 openFlags; /* Flags to sqlite3BtreeOpen() */ +#ifndef SQLITE_OMIT_AUTOVACUUM + u8 autoVacuum; /* True if auto-vacuum is enabled */ + u8 incrVacuum; /* True if incr-vacuum is enabled */ + u8 bDoTruncate; /* True to truncate db on commit */ +#endif + u8 inTransaction; /* Transaction state */ + u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */ + u16 btsFlags; /* Boolean parameters. See BTS_* macros below */ + u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ + u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */ + u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */ + u16 minLeaf; /* Minimum local payload in a LEAFDATA table */ + u32 pageSize; /* Total number of bytes on a page */ + u32 usableSize; /* Number of usable bytes on each page */ + int nTransaction; /* Number of open transactions (read + write) */ + u32 nPage; /* Number of pages in the database */ + void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ + void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */ + sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */ + Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */ +#ifndef SQLITE_OMIT_SHARED_CACHE + int nRef; /* Number of references to this structure */ + BtShared *pNext; /* Next on a list of sharable BtShared structs */ + BtLock *pLock; /* List of locks held on this shared-btree struct */ + Btree *pWriter; /* Btree with currently open write transaction */ +#endif + u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */ +}; + +/* +** Allowed values for BtShared.btsFlags +*/ +#define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */ +#define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */ +#define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */ +#define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */ +#define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */ +#define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */ +#define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */ + +/* +** An instance of the following structure is used to hold information +** about a cell. The parseCellPtr() function fills in this structure +** based on information extract from the raw disk page. +*/ +typedef struct CellInfo CellInfo; +struct CellInfo { + i64 nKey; /* The key for INTKEY tables, or number of bytes in key */ + u8 *pCell; /* Pointer to the start of cell content */ + u32 nData; /* Number of bytes of data */ + u32 nPayload; /* Total amount of payload */ + u16 nHeader; /* Size of the cell content header in bytes */ + u16 nLocal; /* Amount of payload held locally */ + u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */ + u16 nSize; /* Size of the cell content on the main b-tree page */ +}; + +/* +** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than +** this will be declared corrupt. This value is calculated based on a +** maximum database size of 2^31 pages a minimum fanout of 2 for a +** root-node and 3 for all other internal nodes. +** +** If a tree that appears to be taller than this is encountered, it is +** assumed that the database is corrupt. +*/ +#define BTCURSOR_MAX_DEPTH 20 + +/* +** A cursor is a pointer to a particular entry within a particular +** b-tree within a database file. +** +** The entry is identified by its MemPage and the index in +** MemPage.aCell[] of the entry. +** +** A single database file can be shared by two more database connections, +** but cursors cannot be shared. Each cursor is associated with a +** particular database connection identified BtCursor.pBtree.db. +** +** Fields in this structure are accessed under the BtShared.mutex +** found at self->pBt->mutex. +*/ +struct BtCursor { + Btree *pBtree; /* The Btree to which this cursor belongs */ + BtShared *pBt; /* The BtShared this cursor points to */ + BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */ + struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */ +#ifndef SQLITE_OMIT_INCRBLOB + Pgno *aOverflow; /* Cache of overflow page locations */ +#endif + Pgno pgnoRoot; /* The root page of this tree */ + sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */ + CellInfo info; /* A parse of the cell we are pointing at */ + i64 nKey; /* Size of pKey, or last integer key */ + void *pKey; /* Saved key that was cursor's last known position */ + int skipNext; /* Prev() is noop if negative. Next() is noop if positive */ + u8 wrFlag; /* True if writable */ + u8 atLast; /* Cursor pointing to the last entry */ + u8 validNKey; /* True if info.nKey is valid */ + u8 eState; /* One of the CURSOR_XXX constants (see below) */ +#ifndef SQLITE_OMIT_INCRBLOB + u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */ +#endif + u8 hints; /* As configured by CursorSetHints() */ + i16 iPage; /* Index of current page in apPage */ + u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */ + MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */ +}; + +/* +** Potential values for BtCursor.eState. +** +** CURSOR_INVALID: +** Cursor does not point to a valid entry. This can happen (for example) +** because the table is empty or because BtreeCursorFirst() has not been +** called. +** +** CURSOR_VALID: +** Cursor points to a valid entry. getPayload() etc. may be called. +** +** CURSOR_SKIPNEXT: +** Cursor is valid except that the Cursor.skipNext field is non-zero +** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious() +** operation should be a no-op. +** +** CURSOR_REQUIRESEEK: +** The table that this cursor was opened on still exists, but has been +** modified since the cursor was last used. The cursor position is saved +** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in +** this state, restoreCursorPosition() can be called to attempt to +** seek the cursor to the saved position. +** +** CURSOR_FAULT: +** A unrecoverable error (an I/O error or a malloc failure) has occurred +** on a different connection that shares the BtShared cache with this +** cursor. The error has left the cache in an inconsistent state. +** Do nothing else with this cursor. Any attempt to use the cursor +** should return the error code stored in BtCursor.skip +*/ +#define CURSOR_INVALID 0 +#define CURSOR_VALID 1 +#define CURSOR_SKIPNEXT 2 +#define CURSOR_REQUIRESEEK 3 +#define CURSOR_FAULT 4 + +/* +** The database page the PENDING_BYTE occupies. This page is never used. +*/ +# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt) + +/* +** These macros define the location of the pointer-map entry for a +** database page. The first argument to each is the number of usable +** bytes on each page of the database (often 1024). The second is the +** page number to look up in the pointer map. +** +** PTRMAP_PAGENO returns the database page number of the pointer-map +** page that stores the required pointer. PTRMAP_PTROFFSET returns +** the offset of the requested map entry. +** +** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page, +** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be +** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements +** this test. +*/ +#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno) +#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1)) +#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno)) + +/* +** The pointer map is a lookup table that identifies the parent page for +** each child page in the database file. The parent page is the page that +** contains a pointer to the child. Every page in the database contains +** 0 or 1 parent pages. (In this context 'database page' refers +** to any page that is not part of the pointer map itself.) Each pointer map +** entry consists of a single byte 'type' and a 4 byte parent page number. +** The PTRMAP_XXX identifiers below are the valid types. +** +** The purpose of the pointer map is to facility moving pages from one +** position in the file to another as part of autovacuum. When a page +** is moved, the pointer in its parent must be updated to point to the +** new location. The pointer map is used to locate the parent page quickly. +** +** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not +** used in this case. +** +** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number +** is not used in this case. +** +** PTRMAP_OVERFLOW1: The database page is the first page in a list of +** overflow pages. The page number identifies the page that +** contains the cell with a pointer to this overflow page. +** +** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of +** overflow pages. The page-number identifies the previous +** page in the overflow page list. +** +** PTRMAP_BTREE: The database page is a non-root btree page. The page number +** identifies the parent page in the btree. +*/ +#define PTRMAP_ROOTPAGE 1 +#define PTRMAP_FREEPAGE 2 +#define PTRMAP_OVERFLOW1 3 +#define PTRMAP_OVERFLOW2 4 +#define PTRMAP_BTREE 5 + +/* A bunch of assert() statements to check the transaction state variables +** of handle p (type Btree*) are internally consistent. +*/ +#define btreeIntegrity(p) \ + assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \ + assert( p->pBt->inTransaction>=p->inTrans ); + + +/* +** The ISAUTOVACUUM macro is used within balance_nonroot() to determine +** if the database supports auto-vacuum or not. Because it is used +** within an expression that is an argument to another macro +** (sqliteMallocRaw), it is not possible to use conditional compilation. +** So, this macro is defined instead. +*/ +#ifndef SQLITE_OMIT_AUTOVACUUM +#define ISAUTOVACUUM (pBt->autoVacuum) +#else +#define ISAUTOVACUUM 0 +#endif + + +/* +** This structure is passed around through all the sanity checking routines +** in order to keep track of some global state information. +** +** The aRef[] array is allocated so that there is 1 bit for each page in +** the database. As the integrity-check proceeds, for each page used in +** the database the corresponding bit is set. This allows integrity-check to +** detect pages that are used twice and orphaned pages (both of which +** indicate corruption). +*/ +typedef struct IntegrityCk IntegrityCk; +struct IntegrityCk { + BtShared *pBt; /* The tree being checked out */ + Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */ + u8 *aPgRef; /* 1 bit per page in the db (see above) */ + Pgno nPage; /* Number of pages in the database */ + int mxErr; /* Stop accumulating errors when this reaches zero */ + int nErr; /* Number of messages written to zErrMsg so far */ + int mallocFailed; /* A memory allocation error has occurred */ + StrAccum errMsg; /* Accumulate the error message text here */ +}; + +/* +** Routines to read or write a two- and four-byte big-endian integer values. +*/ +#define get2byte(x) ((x)[0]<<8 | (x)[1]) +#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) +#define get4byte sqlite3Get4byte +#define put4byte sqlite3Put4byte diff --git a/components/external/SQLite-3.8.1/src/build.c b/components/external/SQLite-3.8.1/src/build.c new file mode 100644 index 0000000000000000000000000000000000000000..6868e60e0fc43b7bd60ee4080baadc1bd5eea04e --- /dev/null +++ b/components/external/SQLite-3.8.1/src/build.c @@ -0,0 +1,3886 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that are called by the SQLite parser +** when syntax rules are reduced. The routines in this file handle the +** following kinds of SQL syntax: +** +** CREATE TABLE +** DROP TABLE +** CREATE INDEX +** DROP INDEX +** creating ID lists +** BEGIN TRANSACTION +** COMMIT +** ROLLBACK +*/ +#include "sqliteInt.h" + +/* +** This routine is called when a new SQL statement is beginning to +** be parsed. Initialize the pParse structure as needed. +*/ +void sqlite3BeginParse(Parse *pParse, int explainFlag){ + pParse->explain = (u8)explainFlag; + pParse->nVar = 0; +} + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* +** The TableLock structure is only used by the sqlite3TableLock() and +** codeTableLocks() functions. +*/ +struct TableLock { + int iDb; /* The database containing the table to be locked */ + int iTab; /* The root page of the table to be locked */ + u8 isWriteLock; /* True for write lock. False for a read lock */ + const char *zName; /* Name of the table */ +}; + +/* +** Record the fact that we want to lock a table at run-time. +** +** The table to be locked has root page iTab and is found in database iDb. +** A read or a write lock can be taken depending on isWritelock. +** +** This routine just records the fact that the lock is desired. The +** code to make the lock occur is generated by a later call to +** codeTableLocks() which occurs during sqlite3FinishCoding(). +*/ +void sqlite3TableLock( + Parse *pParse, /* Parsing context */ + int iDb, /* Index of the database containing the table to lock */ + int iTab, /* Root page number of the table to be locked */ + u8 isWriteLock, /* True for a write lock */ + const char *zName /* Name of the table to be locked */ +){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + int i; + int nBytes; + TableLock *p; + assert( iDb>=0 ); + + for(i=0; inTableLock; i++){ + p = &pToplevel->aTableLock[i]; + if( p->iDb==iDb && p->iTab==iTab ){ + p->isWriteLock = (p->isWriteLock || isWriteLock); + return; + } + } + + nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); + pToplevel->aTableLock = + sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); + if( pToplevel->aTableLock ){ + p = &pToplevel->aTableLock[pToplevel->nTableLock++]; + p->iDb = iDb; + p->iTab = iTab; + p->isWriteLock = isWriteLock; + p->zName = zName; + }else{ + pToplevel->nTableLock = 0; + pToplevel->db->mallocFailed = 1; + } +} + +/* +** Code an OP_TableLock instruction for each table locked by the +** statement (configured by calls to sqlite3TableLock()). +*/ +static void codeTableLocks(Parse *pParse){ + int i; + Vdbe *pVdbe; + + pVdbe = sqlite3GetVdbe(pParse); + assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ + + for(i=0; inTableLock; i++){ + TableLock *p = &pParse->aTableLock[i]; + int p1 = p->iDb; + sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, + p->zName, P4_STATIC); + } +} +#else + #define codeTableLocks(x) +#endif + +/* +** This routine is called after a single SQL statement has been +** parsed and a VDBE program to execute that statement has been +** prepared. This routine puts the finishing touches on the +** VDBE program and resets the pParse structure for the next +** parse. +** +** Note that if an error occurred, it might be the case that +** no VDBE code was generated. +*/ +void sqlite3FinishCoding(Parse *pParse){ + sqlite3 *db; + Vdbe *v; + + assert( pParse->pToplevel==0 ); + db = pParse->db; + if( db->mallocFailed ) return; + if( pParse->nested ) return; + if( pParse->nErr ) return; + + /* Begin by generating some termination code at the end of the + ** vdbe program + */ + v = sqlite3GetVdbe(pParse); + assert( !pParse->isMultiWrite + || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); + if( v ){ + sqlite3VdbeAddOp0(v, OP_Halt); + + /* The cookie mask contains one bit for each database file open. + ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are + ** set for each database that is used. Generate code to start a + ** transaction on each used database and to verify the schema cookie + ** on each used database. + */ + if( pParse->cookieGoto>0 ){ + yDbMask mask; + int iDb; + sqlite3VdbeJumpHere(v, pParse->cookieGoto-1); + for(iDb=0, mask=1; iDbnDb; mask<<=1, iDb++){ + if( (mask & pParse->cookieMask)==0 ) continue; + sqlite3VdbeUsesBtree(v, iDb); + sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0); + if( db->init.busy==0 ){ + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + sqlite3VdbeAddOp3(v, OP_VerifyCookie, + iDb, pParse->cookieValue[iDb], + db->aDb[iDb].pSchema->iGeneration); + } + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + { + int i; + for(i=0; inVtabLock; i++){ + char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); + sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); + } + pParse->nVtabLock = 0; + } +#endif + + /* Once all the cookies have been verified and transactions opened, + ** obtain the required table-locks. This is a no-op unless the + ** shared-cache feature is enabled. + */ + codeTableLocks(pParse); + + /* Initialize any AUTOINCREMENT data structures required. + */ + sqlite3AutoincrementBegin(pParse); + + /* Finally, jump back to the beginning of the executable code. */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto); + } + } + + + /* Get the VDBE program ready for execution + */ + if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){ +#ifdef SQLITE_DEBUG + FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0; + sqlite3VdbeTrace(v, trace); +#endif + assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ + /* A minimum of one cursor is required if autoincrement is used + * See ticket [a696379c1f08866] */ + if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; + sqlite3VdbeMakeReady(v, pParse); + pParse->rc = SQLITE_DONE; + pParse->colNamesSet = 0; + }else{ + pParse->rc = SQLITE_ERROR; + } + pParse->nTab = 0; + pParse->nMem = 0; + pParse->nSet = 0; + pParse->nVar = 0; + pParse->cookieMask = 0; + pParse->cookieGoto = 0; +} + +/* +** Run the parser and code generator recursively in order to generate +** code for the SQL statement given onto the end of the pParse context +** currently under construction. When the parser is run recursively +** this way, the final OP_Halt is not appended and other initialization +** and finalization steps are omitted because those are handling by the +** outermost parser. +** +** Not everything is nestable. This facility is designed to permit +** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use +** care if you decide to try to use this routine for some other purposes. +*/ +void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ + va_list ap; + char *zSql; + char *zErrMsg = 0; + sqlite3 *db = pParse->db; +# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) + char saveBuf[SAVE_SZ]; + + if( pParse->nErr ) return; + assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ + va_start(ap, zFormat); + zSql = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + if( zSql==0 ){ + return; /* A malloc must have failed */ + } + pParse->nested++; + memcpy(saveBuf, &pParse->nVar, SAVE_SZ); + memset(&pParse->nVar, 0, SAVE_SZ); + sqlite3RunParser(pParse, zSql, &zErrMsg); + sqlite3DbFree(db, zErrMsg); + sqlite3DbFree(db, zSql); + memcpy(&pParse->nVar, saveBuf, SAVE_SZ); + pParse->nested--; +} + +/* +** Locate the in-memory structure that describes a particular database +** table given the name of that table and (optionally) the name of the +** database containing the table. Return NULL if not found. +** +** If zDatabase is 0, all databases are searched for the table and the +** first matching table is returned. (No checking for duplicate table +** names is done.) The search order is TEMP first, then MAIN, then any +** auxiliary databases added using the ATTACH command. +** +** See also sqlite3LocateTable(). +*/ +Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ + Table *p = 0; + int i; + int nName; + assert( zName!=0 ); + nName = sqlite3Strlen30(zName); + /* All mutexes are required for schema access. Make sure we hold them. */ + assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); + for(i=OMIT_TEMPDB; inDb; i++){ + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ + if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; + assert( sqlite3SchemaMutexHeld(db, j, 0) ); + p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName); + if( p ) break; + } + return p; +} + +/* +** Locate the in-memory structure that describes a particular database +** table given the name of that table and (optionally) the name of the +** database containing the table. Return NULL if not found. Also leave an +** error message in pParse->zErrMsg. +** +** The difference between this routine and sqlite3FindTable() is that this +** routine leaves an error message in pParse->zErrMsg where +** sqlite3FindTable() does not. +*/ +Table *sqlite3LocateTable( + Parse *pParse, /* context in which to report errors */ + int isView, /* True if looking for a VIEW rather than a TABLE */ + const char *zName, /* Name of the table we are looking for */ + const char *zDbase /* Name of the database. Might be NULL */ +){ + Table *p; + + /* Read the database schema. If an error occurs, leave an error message + ** and code in pParse and return NULL. */ + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + return 0; + } + + p = sqlite3FindTable(pParse->db, zName, zDbase); + if( p==0 ){ + const char *zMsg = isView ? "no such view" : "no such table"; + if( zDbase ){ + sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); + }else{ + sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); + } + pParse->checkSchema = 1; + } + return p; +} + +/* +** Locate the table identified by *p. +** +** This is a wrapper around sqlite3LocateTable(). The difference between +** sqlite3LocateTable() and this function is that this function restricts +** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be +** non-NULL if it is part of a view or trigger program definition. See +** sqlite3FixSrcList() for details. +*/ +Table *sqlite3LocateTableItem( + Parse *pParse, + int isView, + struct SrcList_item *p +){ + const char *zDb; + assert( p->pSchema==0 || p->zDatabase==0 ); + if( p->pSchema ){ + int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); + zDb = pParse->db->aDb[iDb].zName; + }else{ + zDb = p->zDatabase; + } + return sqlite3LocateTable(pParse, isView, p->zName, zDb); +} + +/* +** Locate the in-memory structure that describes +** a particular index given the name of that index +** and the name of the database that contains the index. +** Return NULL if not found. +** +** If zDatabase is 0, all databases are searched for the +** table and the first matching index is returned. (No checking +** for duplicate index names is done.) The search order is +** TEMP first, then MAIN, then any auxiliary databases added +** using the ATTACH command. +*/ +Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ + Index *p = 0; + int i; + int nName = sqlite3Strlen30(zName); + /* All mutexes are required for schema access. Make sure we hold them. */ + assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); + for(i=OMIT_TEMPDB; inDb; i++){ + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ + Schema *pSchema = db->aDb[j].pSchema; + assert( pSchema ); + if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; + assert( sqlite3SchemaMutexHeld(db, j, 0) ); + p = sqlite3HashFind(&pSchema->idxHash, zName, nName); + if( p ) break; + } + return p; +} + +/* +** Reclaim the memory used by an index +*/ +static void freeIndex(sqlite3 *db, Index *p){ +#ifndef SQLITE_OMIT_ANALYZE + sqlite3DeleteIndexSamples(db, p); +#endif + sqlite3ExprDelete(db, p->pPartIdxWhere); + sqlite3DbFree(db, p->zColAff); + sqlite3DbFree(db, p); +} + +/* +** For the index called zIdxName which is found in the database iDb, +** unlike that index from its Table then remove the index from +** the index hash table and free all memory structures associated +** with the index. +*/ +void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ + Index *pIndex; + int len; + Hash *pHash; + + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pHash = &db->aDb[iDb].pSchema->idxHash; + len = sqlite3Strlen30(zIdxName); + pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0); + if( ALWAYS(pIndex) ){ + if( pIndex->pTable->pIndex==pIndex ){ + pIndex->pTable->pIndex = pIndex->pNext; + }else{ + Index *p; + /* Justification of ALWAYS(); The index must be on the list of + ** indices. */ + p = pIndex->pTable->pIndex; + while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } + if( ALWAYS(p && p->pNext==pIndex) ){ + p->pNext = pIndex->pNext; + } + } + freeIndex(db, pIndex); + } + db->flags |= SQLITE_InternChanges; +} + +/* +** Look through the list of open database files in db->aDb[] and if +** any have been closed, remove them from the list. Reallocate the +** db->aDb[] structure to a smaller size, if possible. +** +** Entry 0 (the "main" database) and entry 1 (the "temp" database) +** are never candidates for being collapsed. +*/ +void sqlite3CollapseDatabaseArray(sqlite3 *db){ + int i, j; + for(i=j=2; inDb; i++){ + struct Db *pDb = &db->aDb[i]; + if( pDb->pBt==0 ){ + sqlite3DbFree(db, pDb->zName); + pDb->zName = 0; + continue; + } + if( jaDb[j] = db->aDb[i]; + } + j++; + } + memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); + db->nDb = j; + if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ + memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); + sqlite3DbFree(db, db->aDb); + db->aDb = db->aDbStatic; + } +} + +/* +** Reset the schema for the database at index iDb. Also reset the +** TEMP schema. +*/ +void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ + Db *pDb; + assert( iDbnDb ); + + /* Case 1: Reset the single schema identified by iDb */ + pDb = &db->aDb[iDb]; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( pDb->pSchema!=0 ); + sqlite3SchemaClear(pDb->pSchema); + + /* If any database other than TEMP is reset, then also reset TEMP + ** since TEMP might be holding triggers that reference tables in the + ** other database. + */ + if( iDb!=1 ){ + pDb = &db->aDb[1]; + assert( pDb->pSchema!=0 ); + sqlite3SchemaClear(pDb->pSchema); + } + return; +} + +/* +** Erase all schema information from all attached databases (including +** "main" and "temp") for a single database connection. +*/ +void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ + int i; + sqlite3BtreeEnterAll(db); + for(i=0; inDb; i++){ + Db *pDb = &db->aDb[i]; + if( pDb->pSchema ){ + sqlite3SchemaClear(pDb->pSchema); + } + } + db->flags &= ~SQLITE_InternChanges; + sqlite3VtabUnlockList(db); + sqlite3BtreeLeaveAll(db); + sqlite3CollapseDatabaseArray(db); +} + +/* +** This routine is called when a commit occurs. +*/ +void sqlite3CommitInternalChanges(sqlite3 *db){ + db->flags &= ~SQLITE_InternChanges; +} + +/* +** Delete memory allocated for the column names of a table or view (the +** Table.aCol[] array). +*/ +static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){ + int i; + Column *pCol; + assert( pTable!=0 ); + if( (pCol = pTable->aCol)!=0 ){ + for(i=0; inCol; i++, pCol++){ + sqlite3DbFree(db, pCol->zName); + sqlite3ExprDelete(db, pCol->pDflt); + sqlite3DbFree(db, pCol->zDflt); + sqlite3DbFree(db, pCol->zType); + sqlite3DbFree(db, pCol->zColl); + } + sqlite3DbFree(db, pTable->aCol); + } +} + +/* +** Remove the memory data structures associated with the given +** Table. No changes are made to disk by this routine. +** +** This routine just deletes the data structure. It does not unlink +** the table data structure from the hash table. But it does destroy +** memory structures of the indices and foreign keys associated with +** the table. +** +** The db parameter is optional. It is needed if the Table object +** contains lookaside memory. (Table objects in the schema do not use +** lookaside memory, but some ephemeral Table objects do.) Or the +** db parameter can be used with db->pnBytesFreed to measure the memory +** used by the Table object. +*/ +void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ + Index *pIndex, *pNext; + TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */ + + assert( !pTable || pTable->nRef>0 ); + + /* Do not delete the table until the reference count reaches zero. */ + if( !pTable ) return; + if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return; + + /* Record the number of outstanding lookaside allocations in schema Tables + ** prior to doing any free() operations. Since schema Tables do not use + ** lookaside, this number should not change. */ + TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ? + db->lookaside.nOut : 0 ); + + /* Delete all indices associated with this table. */ + for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ + pNext = pIndex->pNext; + assert( pIndex->pSchema==pTable->pSchema ); + if( !db || db->pnBytesFreed==0 ){ + char *zName = pIndex->zName; + TESTONLY ( Index *pOld = ) sqlite3HashInsert( + &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0 + ); + assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); + assert( pOld==pIndex || pOld==0 ); + } + freeIndex(db, pIndex); + } + + /* Delete any foreign keys attached to this table. */ + sqlite3FkDelete(db, pTable); + + /* Delete the Table structure itself. + */ + sqliteDeleteColumnNames(db, pTable); + sqlite3DbFree(db, pTable->zName); + sqlite3DbFree(db, pTable->zColAff); + sqlite3SelectDelete(db, pTable->pSelect); +#ifndef SQLITE_OMIT_CHECK + sqlite3ExprListDelete(db, pTable->pCheck); +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3VtabClear(db, pTable); +#endif + sqlite3DbFree(db, pTable); + + /* Verify that no lookaside memory was used by schema tables */ + assert( nLookaside==0 || nLookaside==db->lookaside.nOut ); +} + +/* +** Unlink the given table from the hash tables and the delete the +** table structure with all its indices and foreign keys. +*/ +void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ + Table *p; + Db *pDb; + + assert( db!=0 ); + assert( iDb>=0 && iDbnDb ); + assert( zTabName ); + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ + pDb = &db->aDb[iDb]; + p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, + sqlite3Strlen30(zTabName),0); + sqlite3DeleteTable(db, p); + db->flags |= SQLITE_InternChanges; +} + +/* +** Given a token, return a string that consists of the text of that +** token. Space to hold the returned string +** is obtained from sqliteMalloc() and must be freed by the calling +** function. +** +** Any quotation marks (ex: "name", 'name', [name], or `name`) that +** surround the body of the token are removed. +** +** Tokens are often just pointers into the original SQL text and so +** are not \000 terminated and are not persistent. The returned string +** is \000 terminated and is persistent. +*/ +char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ + char *zName; + if( pName ){ + zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); + sqlite3Dequote(zName); + }else{ + zName = 0; + } + return zName; +} + +/* +** Open the sqlite_master table stored in database number iDb for +** writing. The table is opened using cursor 0. +*/ +void sqlite3OpenMasterTable(Parse *p, int iDb){ + Vdbe *v = sqlite3GetVdbe(p); + sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); + sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb); + sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */ + if( p->nTab==0 ){ + p->nTab = 1; + } +} + +/* +** Parameter zName points to a nul-terminated buffer containing the name +** of a database ("main", "temp" or the name of an attached db). This +** function returns the index of the named database in db->aDb[], or +** -1 if the named db cannot be found. +*/ +int sqlite3FindDbName(sqlite3 *db, const char *zName){ + int i = -1; /* Database number */ + if( zName ){ + Db *pDb; + int n = sqlite3Strlen30(zName); + for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ + if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && + 0==sqlite3StrICmp(pDb->zName, zName) ){ + break; + } + } + } + return i; +} + +/* +** The token *pName contains the name of a database (either "main" or +** "temp" or the name of an attached db). This routine returns the +** index of the named database in db->aDb[], or -1 if the named db +** does not exist. +*/ +int sqlite3FindDb(sqlite3 *db, Token *pName){ + int i; /* Database number */ + char *zName; /* Name we are searching for */ + zName = sqlite3NameFromToken(db, pName); + i = sqlite3FindDbName(db, zName); + sqlite3DbFree(db, zName); + return i; +} + +/* The table or view or trigger name is passed to this routine via tokens +** pName1 and pName2. If the table name was fully qualified, for example: +** +** CREATE TABLE xxx.yyy (...); +** +** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if +** the table name is not fully qualified, i.e.: +** +** CREATE TABLE yyy(...); +** +** Then pName1 is set to "yyy" and pName2 is "". +** +** This routine sets the *ppUnqual pointer to point at the token (pName1 or +** pName2) that stores the unqualified table name. The index of the +** database "xxx" is returned. +*/ +int sqlite3TwoPartName( + Parse *pParse, /* Parsing and code generating context */ + Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ + Token *pName2, /* The "yyy" in the name "xxx.yyy" */ + Token **pUnqual /* Write the unqualified object name here */ +){ + int iDb; /* Database holding the object */ + sqlite3 *db = pParse->db; + + if( ALWAYS(pName2!=0) && pName2->n>0 ){ + if( db->init.busy ) { + sqlite3ErrorMsg(pParse, "corrupt database"); + pParse->nErr++; + return -1; + } + *pUnqual = pName2; + iDb = sqlite3FindDb(db, pName1); + if( iDb<0 ){ + sqlite3ErrorMsg(pParse, "unknown database %T", pName1); + pParse->nErr++; + return -1; + } + }else{ + assert( db->init.iDb==0 || db->init.busy ); + iDb = db->init.iDb; + *pUnqual = pName1; + } + return iDb; +} + +/* +** This routine is used to check if the UTF-8 string zName is a legal +** unqualified name for a new schema object (table, index, view or +** trigger). All names are legal except those that begin with the string +** "sqlite_" (in upper, lower or mixed case). This portion of the namespace +** is reserved for internal use. +*/ +int sqlite3CheckObjectName(Parse *pParse, const char *zName){ + if( !pParse->db->init.busy && pParse->nested==0 + && (pParse->db->flags & SQLITE_WriteSchema)==0 + && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ + sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); + return SQLITE_ERROR; + } + return SQLITE_OK; +} + +/* +** Begin constructing a new table representation in memory. This is +** the first of several action routines that get called in response +** to a CREATE TABLE statement. In particular, this routine is called +** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp +** flag is true if the table should be stored in the auxiliary database +** file instead of in the main database file. This is normally the case +** when the "TEMP" or "TEMPORARY" keyword occurs in between +** CREATE and TABLE. +** +** The new table record is initialized and put in pParse->pNewTable. +** As more of the CREATE TABLE statement is parsed, additional action +** routines will be called to add more information to this record. +** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine +** is called to complete the construction of the new table record. +*/ +void sqlite3StartTable( + Parse *pParse, /* Parser context */ + Token *pName1, /* First part of the name of the table or view */ + Token *pName2, /* Second part of the name of the table or view */ + int isTemp, /* True if this is a TEMP table */ + int isView, /* True if this is a VIEW */ + int isVirtual, /* True if this is a VIRTUAL table */ + int noErr /* Do nothing if table already exists */ +){ + Table *pTable; + char *zName = 0; /* The name of the new table */ + sqlite3 *db = pParse->db; + Vdbe *v; + int iDb; /* Database number to create the table in */ + Token *pName; /* Unqualified name of the table to create */ + + /* The table or view name to create is passed to this routine via tokens + ** pName1 and pName2. If the table name was fully qualified, for example: + ** + ** CREATE TABLE xxx.yyy (...); + ** + ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if + ** the table name is not fully qualified, i.e.: + ** + ** CREATE TABLE yyy(...); + ** + ** Then pName1 is set to "yyy" and pName2 is "". + ** + ** The call below sets the pName pointer to point at the token (pName1 or + ** pName2) that stores the unqualified table name. The variable iDb is + ** set to the index of the database that the table or view is to be + ** created in. + */ + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); + if( iDb<0 ) return; + if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ + /* If creating a temp table, the name may not be qualified. Unless + ** the database name is "temp" anyway. */ + sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); + return; + } + if( !OMIT_TEMPDB && isTemp ) iDb = 1; + + pParse->sNameToken = *pName; + zName = sqlite3NameFromToken(db, pName); + if( zName==0 ) return; + if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ + goto begin_table_error; + } + if( db->init.iDb==1 ) isTemp = 1; +#ifndef SQLITE_OMIT_AUTHORIZATION + assert( (isTemp & 1)==isTemp ); + { + int code; + char *zDb = db->aDb[iDb].zName; + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ + goto begin_table_error; + } + if( isView ){ + if( !OMIT_TEMPDB && isTemp ){ + code = SQLITE_CREATE_TEMP_VIEW; + }else{ + code = SQLITE_CREATE_VIEW; + } + }else{ + if( !OMIT_TEMPDB && isTemp ){ + code = SQLITE_CREATE_TEMP_TABLE; + }else{ + code = SQLITE_CREATE_TABLE; + } + } + if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ + goto begin_table_error; + } + } +#endif + + /* Make sure the new table name does not collide with an existing + ** index or table name in the same database. Issue an error message if + ** it does. The exception is if the statement being parsed was passed + ** to an sqlite3_declare_vtab() call. In that case only the column names + ** and types will be used, so there is no need to test for namespace + ** collisions. + */ + if( !IN_DECLARE_VTAB ){ + char *zDb = db->aDb[iDb].zName; + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + goto begin_table_error; + } + pTable = sqlite3FindTable(db, zName, zDb); + if( pTable ){ + if( !noErr ){ + sqlite3ErrorMsg(pParse, "table %T already exists", pName); + }else{ + assert( !db->init.busy ); + sqlite3CodeVerifySchema(pParse, iDb); + } + goto begin_table_error; + } + if( sqlite3FindIndex(db, zName, zDb)!=0 ){ + sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); + goto begin_table_error; + } + } + + pTable = sqlite3DbMallocZero(db, sizeof(Table)); + if( pTable==0 ){ + db->mallocFailed = 1; + pParse->rc = SQLITE_NOMEM; + pParse->nErr++; + goto begin_table_error; + } + pTable->zName = zName; + pTable->iPKey = -1; + pTable->pSchema = db->aDb[iDb].pSchema; + pTable->nRef = 1; + pTable->nRowEst = 1048576; + assert( pParse->pNewTable==0 ); + pParse->pNewTable = pTable; + + /* If this is the magic sqlite_sequence table used by autoincrement, + ** then record a pointer to this table in the main database structure + ** so that INSERT can find the table easily. + */ +#ifndef SQLITE_OMIT_AUTOINCREMENT + if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pTable->pSchema->pSeqTab = pTable; + } +#endif + + /* Begin generating the code that will insert the table record into + ** the SQLITE_MASTER table. Note in particular that we must go ahead + ** and allocate the record number for the table entry now. Before any + ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause + ** indices to be created and the table record must come before the + ** indices. Hence, the record number for the table must be allocated + ** now. + */ + if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ + int j1; + int fileFormat; + int reg1, reg2, reg3; + sqlite3BeginWriteOperation(pParse, 0, iDb); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( isVirtual ){ + sqlite3VdbeAddOp0(v, OP_VBegin); + } +#endif + + /* If the file format and encoding in the database have not been set, + ** set them now. + */ + reg1 = pParse->regRowid = ++pParse->nMem; + reg2 = pParse->regRoot = ++pParse->nMem; + reg3 = ++pParse->nMem; + sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); + sqlite3VdbeUsesBtree(v, iDb); + j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); + fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? + 1 : SQLITE_MAX_FILE_FORMAT; + sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3); + sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3); + sqlite3VdbeJumpHere(v, j1); + + /* This just creates a place-holder record in the sqlite_master table. + ** The record created does not contain anything yet. It will be replaced + ** by the real entry in code generated at sqlite3EndTable(). + ** + ** The rowid for the new entry is left in register pParse->regRowid. + ** The root page number of the new table is left in reg pParse->regRoot. + ** The rowid and root page number values are needed by the code that + ** sqlite3EndTable will generate. + */ +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) + if( isView || isVirtual ){ + sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); + }else +#endif + { + sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); + } + sqlite3OpenMasterTable(pParse, iDb); + sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); + sqlite3VdbeAddOp2(v, OP_Null, 0, reg3); + sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3VdbeAddOp0(v, OP_Close); + } + + /* Normal (non-error) return. */ + return; + + /* If an error occurs, we jump here */ +begin_table_error: + sqlite3DbFree(db, zName); + return; +} + +/* +** This macro is used to compare two strings in a case-insensitive manner. +** It is slightly faster than calling sqlite3StrICmp() directly, but +** produces larger code. +** +** WARNING: This macro is not compatible with the strcmp() family. It +** returns true if the two strings are equal, otherwise false. +*/ +#define STRICMP(x, y) (\ +sqlite3UpperToLower[*(unsigned char *)(x)]== \ +sqlite3UpperToLower[*(unsigned char *)(y)] \ +&& sqlite3StrICmp((x)+1,(y)+1)==0 ) + +/* +** Add a new column to the table currently being constructed. +** +** The parser calls this routine once for each column declaration +** in a CREATE TABLE statement. sqlite3StartTable() gets called +** first to get things going. Then this routine is called for each +** column. +*/ +void sqlite3AddColumn(Parse *pParse, Token *pName){ + Table *p; + int i; + char *z; + Column *pCol; + sqlite3 *db = pParse->db; + if( (p = pParse->pNewTable)==0 ) return; +#if SQLITE_MAX_COLUMN + if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); + return; + } +#endif + z = sqlite3NameFromToken(db, pName); + if( z==0 ) return; + for(i=0; inCol; i++){ + if( STRICMP(z, p->aCol[i].zName) ){ + sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); + sqlite3DbFree(db, z); + return; + } + } + if( (p->nCol & 0x7)==0 ){ + Column *aNew; + aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); + if( aNew==0 ){ + sqlite3DbFree(db, z); + return; + } + p->aCol = aNew; + } + pCol = &p->aCol[p->nCol]; + memset(pCol, 0, sizeof(p->aCol[0])); + pCol->zName = z; + + /* If there is no type specified, columns have the default affinity + ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will + ** be called next to set pCol->affinity correctly. + */ + pCol->affinity = SQLITE_AFF_NONE; + pCol->szEst = 1; + p->nCol++; +} + +/* +** This routine is called by the parser while in the middle of +** parsing a CREATE TABLE statement. A "NOT NULL" constraint has +** been seen on a column. This routine sets the notNull flag on +** the column currently under construction. +*/ +void sqlite3AddNotNull(Parse *pParse, int onError){ + Table *p; + p = pParse->pNewTable; + if( p==0 || NEVER(p->nCol<1) ) return; + p->aCol[p->nCol-1].notNull = (u8)onError; +} + +/* +** Scan the column type name zType (length nType) and return the +** associated affinity type. +** +** This routine does a case-independent search of zType for the +** substrings in the following table. If one of the substrings is +** found, the corresponding affinity is returned. If zType contains +** more than one of the substrings, entries toward the top of +** the table take priority. For example, if zType is 'BLOBINT', +** SQLITE_AFF_INTEGER is returned. +** +** Substring | Affinity +** -------------------------------- +** 'INT' | SQLITE_AFF_INTEGER +** 'CHAR' | SQLITE_AFF_TEXT +** 'CLOB' | SQLITE_AFF_TEXT +** 'TEXT' | SQLITE_AFF_TEXT +** 'BLOB' | SQLITE_AFF_NONE +** 'REAL' | SQLITE_AFF_REAL +** 'FLOA' | SQLITE_AFF_REAL +** 'DOUB' | SQLITE_AFF_REAL +** +** If none of the substrings in the above table are found, +** SQLITE_AFF_NUMERIC is returned. +*/ +char sqlite3AffinityType(const char *zIn, u8 *pszEst){ + u32 h = 0; + char aff = SQLITE_AFF_NUMERIC; + const char *zChar = 0; + + if( zIn==0 ) return aff; + while( zIn[0] ){ + h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; + zIn++; + if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ + aff = SQLITE_AFF_TEXT; + zChar = zIn; + }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ + aff = SQLITE_AFF_TEXT; + }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ + aff = SQLITE_AFF_TEXT; + }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ + && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ + aff = SQLITE_AFF_NONE; + if( zIn[0]=='(' ) zChar = zIn; +#ifndef SQLITE_OMIT_FLOATING_POINT + }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ + && aff==SQLITE_AFF_NUMERIC ){ + aff = SQLITE_AFF_REAL; + }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ + && aff==SQLITE_AFF_NUMERIC ){ + aff = SQLITE_AFF_REAL; + }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ + && aff==SQLITE_AFF_NUMERIC ){ + aff = SQLITE_AFF_REAL; +#endif + }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ + aff = SQLITE_AFF_INTEGER; + break; + } + } + + /* If pszEst is not NULL, store an estimate of the field size. The + ** estimate is scaled so that the size of an integer is 1. */ + if( pszEst ){ + *pszEst = 1; /* default size is approx 4 bytes */ + if( aff<=SQLITE_AFF_NONE ){ + if( zChar ){ + while( zChar[0] ){ + if( sqlite3Isdigit(zChar[0]) ){ + int v = 0; + sqlite3GetInt32(zChar, &v); + v = v/4 + 1; + if( v>255 ) v = 255; + *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ + break; + } + zChar++; + } + }else{ + *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ + } + } + } + return aff; +} + +/* +** This routine is called by the parser while in the middle of +** parsing a CREATE TABLE statement. The pFirst token is the first +** token in the sequence of tokens that describe the type of the +** column currently under construction. pLast is the last token +** in the sequence. Use this information to construct a string +** that contains the typename of the column and store that string +** in zType. +*/ +void sqlite3AddColumnType(Parse *pParse, Token *pType){ + Table *p; + Column *pCol; + + p = pParse->pNewTable; + if( p==0 || NEVER(p->nCol<1) ) return; + pCol = &p->aCol[p->nCol-1]; + assert( pCol->zType==0 ); + pCol->zType = sqlite3NameFromToken(pParse->db, pType); + pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst); +} + +/* +** The expression is the default value for the most recently added column +** of the table currently under construction. +** +** Default value expressions must be constant. Raise an exception if this +** is not the case. +** +** This routine is called by the parser while in the middle of +** parsing a CREATE TABLE statement. +*/ +void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ + Table *p; + Column *pCol; + sqlite3 *db = pParse->db; + p = pParse->pNewTable; + if( p!=0 ){ + pCol = &(p->aCol[p->nCol-1]); + if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){ + sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", + pCol->zName); + }else{ + /* A copy of pExpr is used instead of the original, as pExpr contains + ** tokens that point to volatile memory. The 'span' of the expression + ** is required by pragma table_info. + */ + sqlite3ExprDelete(db, pCol->pDflt); + pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE); + sqlite3DbFree(db, pCol->zDflt); + pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart, + (int)(pSpan->zEnd - pSpan->zStart)); + } + } + sqlite3ExprDelete(db, pSpan->pExpr); +} + +/* +** Designate the PRIMARY KEY for the table. pList is a list of names +** of columns that form the primary key. If pList is NULL, then the +** most recently added column of the table is the primary key. +** +** A table can have at most one primary key. If the table already has +** a primary key (and this is the second primary key) then create an +** error. +** +** If the PRIMARY KEY is on a single column whose datatype is INTEGER, +** then we will try to use that column as the rowid. Set the Table.iPKey +** field of the table under construction to be the index of the +** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is +** no INTEGER PRIMARY KEY. +** +** If the key is not an INTEGER PRIMARY KEY, then create a unique +** index for the key. No index is created for INTEGER PRIMARY KEYs. +*/ +void sqlite3AddPrimaryKey( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* List of field names to be indexed */ + int onError, /* What to do with a uniqueness conflict */ + int autoInc, /* True if the AUTOINCREMENT keyword is present */ + int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ +){ + Table *pTab = pParse->pNewTable; + char *zType = 0; + int iCol = -1, i; + if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; + if( pTab->tabFlags & TF_HasPrimaryKey ){ + sqlite3ErrorMsg(pParse, + "table \"%s\" has more than one primary key", pTab->zName); + goto primary_key_exit; + } + pTab->tabFlags |= TF_HasPrimaryKey; + if( pList==0 ){ + iCol = pTab->nCol - 1; + pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; + }else{ + for(i=0; inExpr; i++){ + for(iCol=0; iColnCol; iCol++){ + if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ + break; + } + } + if( iColnCol ){ + pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; + } + } + if( pList->nExpr>1 ) iCol = -1; + } + if( iCol>=0 && iColnCol ){ + zType = pTab->aCol[iCol].zType; + } + if( zType && sqlite3StrICmp(zType, "INTEGER")==0 + && sortOrder==SQLITE_SO_ASC ){ + pTab->iPKey = iCol; + pTab->keyConf = (u8)onError; + assert( autoInc==0 || autoInc==1 ); + pTab->tabFlags |= autoInc*TF_Autoincrement; + }else if( autoInc ){ +#ifndef SQLITE_OMIT_AUTOINCREMENT + sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " + "INTEGER PRIMARY KEY"); +#endif + }else{ + Index *p; + p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, + 0, sortOrder, 0); + if( p ){ + p->autoIndex = 2; + } + pList = 0; + } + +primary_key_exit: + sqlite3ExprListDelete(pParse->db, pList); + return; +} + +/* +** Add a new CHECK constraint to the table currently under construction. +*/ +void sqlite3AddCheckConstraint( + Parse *pParse, /* Parsing context */ + Expr *pCheckExpr /* The check expression */ +){ +#ifndef SQLITE_OMIT_CHECK + Table *pTab = pParse->pNewTable; + if( pTab && !IN_DECLARE_VTAB ){ + pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); + if( pParse->constraintName.n ){ + sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); + } + }else +#endif + { + sqlite3ExprDelete(pParse->db, pCheckExpr); + } +} + +/* +** Set the collation function of the most recently parsed table column +** to the CollSeq given. +*/ +void sqlite3AddCollateType(Parse *pParse, Token *pToken){ + Table *p; + int i; + char *zColl; /* Dequoted name of collation sequence */ + sqlite3 *db; + + if( (p = pParse->pNewTable)==0 ) return; + i = p->nCol-1; + db = pParse->db; + zColl = sqlite3NameFromToken(db, pToken); + if( !zColl ) return; + + if( sqlite3LocateCollSeq(pParse, zColl) ){ + Index *pIdx; + sqlite3DbFree(db, p->aCol[i].zColl); + p->aCol[i].zColl = zColl; + + /* If the column is declared as " PRIMARY KEY COLLATE ", + ** then an index may have been created on this column before the + ** collation type was added. Correct this if it is the case. + */ + for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ + assert( pIdx->nColumn==1 ); + if( pIdx->aiColumn[0]==i ){ + pIdx->azColl[0] = p->aCol[i].zColl; + } + } + }else{ + sqlite3DbFree(db, zColl); + } +} + +/* +** This function returns the collation sequence for database native text +** encoding identified by the string zName, length nName. +** +** If the requested collation sequence is not available, or not available +** in the database native encoding, the collation factory is invoked to +** request it. If the collation factory does not supply such a sequence, +** and the sequence is available in another text encoding, then that is +** returned instead. +** +** If no versions of the requested collations sequence are available, or +** another error occurs, NULL is returned and an error message written into +** pParse. +** +** This routine is a wrapper around sqlite3FindCollSeq(). This routine +** invokes the collation factory if the named collation cannot be found +** and generates an error message. +** +** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() +*/ +CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ + sqlite3 *db = pParse->db; + u8 enc = ENC(db); + u8 initbusy = db->init.busy; + CollSeq *pColl; + + pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); + if( !initbusy && (!pColl || !pColl->xCmp) ){ + pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); + } + + return pColl; +} + + +/* +** Generate code that will increment the schema cookie. +** +** The schema cookie is used to determine when the schema for the +** database changes. After each schema change, the cookie value +** changes. When a process first reads the schema it records the +** cookie. Thereafter, whenever it goes to access the database, +** it checks the cookie to make sure the schema has not changed +** since it was last read. +** +** This plan is not completely bullet-proof. It is possible for +** the schema to change multiple times and for the cookie to be +** set back to prior value. But schema changes are infrequent +** and the probability of hitting the same cookie value is only +** 1 chance in 2^32. So we're safe enough. +*/ +void sqlite3ChangeCookie(Parse *pParse, int iDb){ + int r1 = sqlite3GetTempReg(pParse); + sqlite3 *db = pParse->db; + Vdbe *v = pParse->pVdbe; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1); + sqlite3ReleaseTempReg(pParse, r1); +} + +/* +** Measure the number of characters needed to output the given +** identifier. The number returned includes any quotes used +** but does not include the null terminator. +** +** The estimate is conservative. It might be larger that what is +** really needed. +*/ +static int identLength(const char *z){ + int n; + for(n=0; *z; n++, z++){ + if( *z=='"' ){ n++; } + } + return n + 2; +} + +/* +** The first parameter is a pointer to an output buffer. The second +** parameter is a pointer to an integer that contains the offset at +** which to write into the output buffer. This function copies the +** nul-terminated string pointed to by the third parameter, zSignedIdent, +** to the specified offset in the buffer and updates *pIdx to refer +** to the first byte after the last byte written before returning. +** +** If the string zSignedIdent consists entirely of alpha-numeric +** characters, does not begin with a digit and is not an SQL keyword, +** then it is copied to the output buffer exactly as it is. Otherwise, +** it is quoted using double-quotes. +*/ +static void identPut(char *z, int *pIdx, char *zSignedIdent){ + unsigned char *zIdent = (unsigned char*)zSignedIdent; + int i, j, needQuote; + i = *pIdx; + + for(j=0; zIdent[j]; j++){ + if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; + } + needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID; + if( !needQuote ){ + needQuote = zIdent[j]; + } + + if( needQuote ) z[i++] = '"'; + for(j=0; zIdent[j]; j++){ + z[i++] = zIdent[j]; + if( zIdent[j]=='"' ) z[i++] = '"'; + } + if( needQuote ) z[i++] = '"'; + z[i] = 0; + *pIdx = i; +} + +/* +** Generate a CREATE TABLE statement appropriate for the given +** table. Memory to hold the text of the statement is obtained +** from sqliteMalloc() and must be freed by the calling function. +*/ +static char *createTableStmt(sqlite3 *db, Table *p){ + int i, k, n; + char *zStmt; + char *zSep, *zSep2, *zEnd; + Column *pCol; + n = 0; + for(pCol = p->aCol, i=0; inCol; i++, pCol++){ + n += identLength(pCol->zName) + 5; + } + n += identLength(p->zName); + if( n<50 ){ + zSep = ""; + zSep2 = ","; + zEnd = ")"; + }else{ + zSep = "\n "; + zSep2 = ",\n "; + zEnd = "\n)"; + } + n += 35 + 6*p->nCol; + zStmt = sqlite3DbMallocRaw(0, n); + if( zStmt==0 ){ + db->mallocFailed = 1; + return 0; + } + sqlite3_snprintf(n, zStmt, "CREATE TABLE "); + k = sqlite3Strlen30(zStmt); + identPut(zStmt, &k, p->zName); + zStmt[k++] = '('; + for(pCol=p->aCol, i=0; inCol; i++, pCol++){ + static const char * const azType[] = { + /* SQLITE_AFF_TEXT */ " TEXT", + /* SQLITE_AFF_NONE */ "", + /* SQLITE_AFF_NUMERIC */ " NUM", + /* SQLITE_AFF_INTEGER */ " INT", + /* SQLITE_AFF_REAL */ " REAL" + }; + int len; + const char *zType; + + sqlite3_snprintf(n-k, &zStmt[k], zSep); + k += sqlite3Strlen30(&zStmt[k]); + zSep = zSep2; + identPut(zStmt, &k, pCol->zName); + assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 ); + assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) ); + testcase( pCol->affinity==SQLITE_AFF_TEXT ); + testcase( pCol->affinity==SQLITE_AFF_NONE ); + testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); + testcase( pCol->affinity==SQLITE_AFF_INTEGER ); + testcase( pCol->affinity==SQLITE_AFF_REAL ); + + zType = azType[pCol->affinity - SQLITE_AFF_TEXT]; + len = sqlite3Strlen30(zType); + assert( pCol->affinity==SQLITE_AFF_NONE + || pCol->affinity==sqlite3AffinityType(zType, 0) ); + memcpy(&zStmt[k], zType, len); + k += len; + assert( k<=n ); + } + sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); + return zStmt; +} + +/* +** Estimate the total row width for a table. +*/ +static void estimateTableWidth(Table *pTab){ + unsigned wTable = 0; + const Column *pTabCol; + int i; + for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ + wTable += pTabCol->szEst; + } + if( pTab->iPKey<0 ) wTable++; + pTab->szTabRow = sqlite3LogEst(wTable*4); +} + +/* +** Estimate the average size of a row for an index. +*/ +static void estimateIndexWidth(Index *pIdx){ + unsigned wIndex = 1; + int i; + const Column *aCol = pIdx->pTable->aCol; + for(i=0; inColumn; i++){ + assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]pTable->nCol ); + wIndex += aCol[pIdx->aiColumn[i]].szEst; + } + pIdx->szIdxRow = sqlite3LogEst(wIndex*4); +} + +/* +** This routine is called to report the final ")" that terminates +** a CREATE TABLE statement. +** +** The table structure that other action routines have been building +** is added to the internal hash tables, assuming no errors have +** occurred. +** +** An entry for the table is made in the master table on disk, unless +** this is a temporary table or db->init.busy==1. When db->init.busy==1 +** it means we are reading the sqlite_master table because we just +** connected to the database or because the sqlite_master table has +** recently changed, so the entry for this table already exists in +** the sqlite_master table. We do not want to create it again. +** +** If the pSelect argument is not NULL, it means that this routine +** was called to create a table generated from a +** "CREATE TABLE ... AS SELECT ..." statement. The column names of +** the new table will match the result set of the SELECT. +*/ +void sqlite3EndTable( + Parse *pParse, /* Parse context */ + Token *pCons, /* The ',' token after the last column defn. */ + Token *pEnd, /* The final ')' token in the CREATE TABLE */ + Select *pSelect /* Select from a "CREATE ... AS SELECT" */ +){ + Table *p; /* The new table */ + sqlite3 *db = pParse->db; /* The database connection */ + int iDb; /* Database in which the table lives */ + Index *pIdx; /* An implied index of the table */ + + if( (pEnd==0 && pSelect==0) || db->mallocFailed ){ + return; + } + p = pParse->pNewTable; + if( p==0 ) return; + + assert( !db->init.busy || !pSelect ); + + iDb = sqlite3SchemaToIndex(db, p->pSchema); + +#ifndef SQLITE_OMIT_CHECK + /* Resolve names in all CHECK constraint expressions. + */ + if( p->pCheck ){ + sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); + } +#endif /* !defined(SQLITE_OMIT_CHECK) */ + + /* Estimate the average row size for the table and for all implied indices */ + estimateTableWidth(p); + for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ + estimateIndexWidth(pIdx); + } + + /* If the db->init.busy is 1 it means we are reading the SQL off the + ** "sqlite_master" or "sqlite_temp_master" table on the disk. + ** So do not write to the disk again. Extract the root page number + ** for the table from the db->init.newTnum field. (The page number + ** should have been put there by the sqliteOpenCb routine.) + */ + if( db->init.busy ){ + p->tnum = db->init.newTnum; + } + + /* If not initializing, then create a record for the new table + ** in the SQLITE_MASTER table of the database. + ** + ** If this is a TEMPORARY table, write the entry into the auxiliary + ** file instead of into the main database file. + */ + if( !db->init.busy ){ + int n; + Vdbe *v; + char *zType; /* "view" or "table" */ + char *zType2; /* "VIEW" or "TABLE" */ + char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ + + v = sqlite3GetVdbe(pParse); + if( NEVER(v==0) ) return; + + sqlite3VdbeAddOp1(v, OP_Close, 0); + + /* + ** Initialize zType for the new view or table. + */ + if( p->pSelect==0 ){ + /* A regular table */ + zType = "table"; + zType2 = "TABLE"; +#ifndef SQLITE_OMIT_VIEW + }else{ + /* A view */ + zType = "view"; + zType2 = "VIEW"; +#endif + } + + /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT + ** statement to populate the new table. The root-page number for the + ** new table is in register pParse->regRoot. + ** + ** Once the SELECT has been coded by sqlite3Select(), it is in a + ** suitable state to query for the column names and types to be used + ** by the new table. + ** + ** A shared-cache write-lock is not required to write to the new table, + ** as a schema-lock must have already been obtained to create it. Since + ** a schema-lock excludes all other database users, the write-lock would + ** be redundant. + */ + if( pSelect ){ + SelectDest dest; + Table *pSelTab; + + assert(pParse->nTab==1); + sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); + sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); + pParse->nTab = 2; + sqlite3SelectDestInit(&dest, SRT_Table, 1); + sqlite3Select(pParse, pSelect, &dest); + sqlite3VdbeAddOp1(v, OP_Close, 1); + if( pParse->nErr==0 ){ + pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); + if( pSelTab==0 ) return; + assert( p->aCol==0 ); + p->nCol = pSelTab->nCol; + p->aCol = pSelTab->aCol; + pSelTab->nCol = 0; + pSelTab->aCol = 0; + sqlite3DeleteTable(db, pSelTab); + } + } + + /* Compute the complete text of the CREATE statement */ + if( pSelect ){ + zStmt = createTableStmt(db, p); + }else{ + n = (int)(pEnd->z - pParse->sNameToken.z) + 1; + zStmt = sqlite3MPrintf(db, + "CREATE %s %.*s", zType2, n, pParse->sNameToken.z + ); + } + + /* A slot for the record has already been allocated in the + ** SQLITE_MASTER table. We just need to update that slot with all + ** the information we've collected. + */ + sqlite3NestedParse(pParse, + "UPDATE %Q.%s " + "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " + "WHERE rowid=#%d", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), + zType, + p->zName, + p->zName, + pParse->regRoot, + zStmt, + pParse->regRowid + ); + sqlite3DbFree(db, zStmt); + sqlite3ChangeCookie(pParse, iDb); + +#ifndef SQLITE_OMIT_AUTOINCREMENT + /* Check to see if we need to create an sqlite_sequence table for + ** keeping track of autoincrement keys. + */ + if( p->tabFlags & TF_Autoincrement ){ + Db *pDb = &db->aDb[iDb]; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( pDb->pSchema->pSeqTab==0 ){ + sqlite3NestedParse(pParse, + "CREATE TABLE %Q.sqlite_sequence(name,seq)", + pDb->zName + ); + } + } +#endif + + /* Reparse everything to update our internal data structures */ + sqlite3VdbeAddParseSchemaOp(v, iDb, + sqlite3MPrintf(db, "tbl_name='%q'", p->zName)); + } + + + /* Add the table to the in-memory representation of the database. + */ + if( db->init.busy ){ + Table *pOld; + Schema *pSchema = p->pSchema; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, + sqlite3Strlen30(p->zName),p); + if( pOld ){ + assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ + db->mallocFailed = 1; + return; + } + pParse->pNewTable = 0; + db->flags |= SQLITE_InternChanges; + +#ifndef SQLITE_OMIT_ALTERTABLE + if( !p->pSelect ){ + const char *zName = (const char *)pParse->sNameToken.z; + int nName; + assert( !pSelect && pCons && pEnd ); + if( pCons->z==0 ){ + pCons = pEnd; + } + nName = (int)((const char *)pCons->z - zName); + p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); + } +#endif + } +} + +#ifndef SQLITE_OMIT_VIEW +/* +** The parser calls this routine in order to create a new VIEW +*/ +void sqlite3CreateView( + Parse *pParse, /* The parsing context */ + Token *pBegin, /* The CREATE token that begins the statement */ + Token *pName1, /* The token that holds the name of the view */ + Token *pName2, /* The token that holds the name of the view */ + Select *pSelect, /* A SELECT statement that will become the new view */ + int isTemp, /* TRUE for a TEMPORARY view */ + int noErr /* Suppress error messages if VIEW already exists */ +){ + Table *p; + int n; + const char *z; + Token sEnd; + DbFixer sFix; + Token *pName = 0; + int iDb; + sqlite3 *db = pParse->db; + + if( pParse->nVar>0 ){ + sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); + sqlite3SelectDelete(db, pSelect); + return; + } + sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); + p = pParse->pNewTable; + if( p==0 || pParse->nErr ){ + sqlite3SelectDelete(db, pSelect); + return; + } + sqlite3TwoPartName(pParse, pName1, pName2, &pName); + iDb = sqlite3SchemaToIndex(db, p->pSchema); + sqlite3FixInit(&sFix, pParse, iDb, "view", pName); + if( sqlite3FixSelect(&sFix, pSelect) ){ + sqlite3SelectDelete(db, pSelect); + return; + } + + /* Make a copy of the entire SELECT statement that defines the view. + ** This will force all the Expr.token.z values to be dynamically + ** allocated rather than point to the input string - which means that + ** they will persist after the current sqlite3_exec() call returns. + */ + p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + sqlite3SelectDelete(db, pSelect); + if( db->mallocFailed ){ + return; + } + if( !db->init.busy ){ + sqlite3ViewGetColumnNames(pParse, p); + } + + /* Locate the end of the CREATE VIEW statement. Make sEnd point to + ** the end. + */ + sEnd = pParse->sLastToken; + if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){ + sEnd.z += sEnd.n; + } + sEnd.n = 0; + n = (int)(sEnd.z - pBegin->z); + z = pBegin->z; + while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; } + sEnd.z = &z[n-1]; + sEnd.n = 1; + + /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ + sqlite3EndTable(pParse, 0, &sEnd, 0); + return; +} +#endif /* SQLITE_OMIT_VIEW */ + +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) +/* +** The Table structure pTable is really a VIEW. Fill in the names of +** the columns of the view in the pTable structure. Return the number +** of errors. If an error is seen leave an error message in pParse->zErrMsg. +*/ +int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ + Table *pSelTab; /* A fake table from which we get the result set */ + Select *pSel; /* Copy of the SELECT that implements the view */ + int nErr = 0; /* Number of errors encountered */ + int n; /* Temporarily holds the number of cursors assigned */ + sqlite3 *db = pParse->db; /* Database connection for malloc errors */ + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); + + assert( pTable ); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( sqlite3VtabCallConnect(pParse, pTable) ){ + return SQLITE_ERROR; + } + if( IsVirtual(pTable) ) return 0; +#endif + +#ifndef SQLITE_OMIT_VIEW + /* A positive nCol means the columns names for this view are + ** already known. + */ + if( pTable->nCol>0 ) return 0; + + /* A negative nCol is a special marker meaning that we are currently + ** trying to compute the column names. If we enter this routine with + ** a negative nCol, it means two or more views form a loop, like this: + ** + ** CREATE VIEW one AS SELECT * FROM two; + ** CREATE VIEW two AS SELECT * FROM one; + ** + ** Actually, the error above is now caught prior to reaching this point. + ** But the following test is still important as it does come up + ** in the following: + ** + ** CREATE TABLE main.ex1(a); + ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; + ** SELECT * FROM temp.ex1; + */ + if( pTable->nCol<0 ){ + sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); + return 1; + } + assert( pTable->nCol>=0 ); + + /* If we get this far, it means we need to compute the table names. + ** Note that the call to sqlite3ResultSetOfSelect() will expand any + ** "*" elements in the results set of the view and will assign cursors + ** to the elements of the FROM clause. But we do not want these changes + ** to be permanent. So the computation is done on a copy of the SELECT + ** statement that defines the view. + */ + assert( pTable->pSelect ); + pSel = sqlite3SelectDup(db, pTable->pSelect, 0); + if( pSel ){ + u8 enableLookaside = db->lookaside.bEnabled; + n = pParse->nTab; + sqlite3SrcListAssignCursors(pParse, pSel->pSrc); + pTable->nCol = -1; + db->lookaside.bEnabled = 0; +#ifndef SQLITE_OMIT_AUTHORIZATION + xAuth = db->xAuth; + db->xAuth = 0; + pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); + db->xAuth = xAuth; +#else + pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); +#endif + db->lookaside.bEnabled = enableLookaside; + pParse->nTab = n; + if( pSelTab ){ + assert( pTable->aCol==0 ); + pTable->nCol = pSelTab->nCol; + pTable->aCol = pSelTab->aCol; + pSelTab->nCol = 0; + pSelTab->aCol = 0; + sqlite3DeleteTable(db, pSelTab); + assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); + pTable->pSchema->flags |= DB_UnresetViews; + }else{ + pTable->nCol = 0; + nErr++; + } + sqlite3SelectDelete(db, pSel); + } else { + nErr++; + } +#endif /* SQLITE_OMIT_VIEW */ + return nErr; +} +#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ + +#ifndef SQLITE_OMIT_VIEW +/* +** Clear the column names from every VIEW in database idx. +*/ +static void sqliteViewResetAll(sqlite3 *db, int idx){ + HashElem *i; + assert( sqlite3SchemaMutexHeld(db, idx, 0) ); + if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; + for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ + Table *pTab = sqliteHashData(i); + if( pTab->pSelect ){ + sqliteDeleteColumnNames(db, pTab); + pTab->aCol = 0; + pTab->nCol = 0; + } + } + DbClearProperty(db, idx, DB_UnresetViews); +} +#else +# define sqliteViewResetAll(A,B) +#endif /* SQLITE_OMIT_VIEW */ + +/* +** This function is called by the VDBE to adjust the internal schema +** used by SQLite when the btree layer moves a table root page. The +** root-page of a table or index in database iDb has changed from iFrom +** to iTo. +** +** Ticket #1728: The symbol table might still contain information +** on tables and/or indices that are the process of being deleted. +** If you are unlucky, one of those deleted indices or tables might +** have the same rootpage number as the real table or index that is +** being moved. So we cannot stop searching after the first match +** because the first match might be for one of the deleted indices +** or tables and not the table/index that is actually being moved. +** We must continue looping until all tables and indices with +** rootpage==iFrom have been converted to have a rootpage of iTo +** in order to be certain that we got the right one. +*/ +#ifndef SQLITE_OMIT_AUTOVACUUM +void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){ + HashElem *pElem; + Hash *pHash; + Db *pDb; + + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pDb = &db->aDb[iDb]; + pHash = &pDb->pSchema->tblHash; + for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ + Table *pTab = sqliteHashData(pElem); + if( pTab->tnum==iFrom ){ + pTab->tnum = iTo; + } + } + pHash = &pDb->pSchema->idxHash; + for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ + Index *pIdx = sqliteHashData(pElem); + if( pIdx->tnum==iFrom ){ + pIdx->tnum = iTo; + } + } +} +#endif + +/* +** Write code to erase the table with root-page iTable from database iDb. +** Also write code to modify the sqlite_master table and internal schema +** if a root-page of another table is moved by the btree-layer whilst +** erasing iTable (this can happen with an auto-vacuum database). +*/ +static void destroyRootPage(Parse *pParse, int iTable, int iDb){ + Vdbe *v = sqlite3GetVdbe(pParse); + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); + sqlite3MayAbort(pParse); +#ifndef SQLITE_OMIT_AUTOVACUUM + /* OP_Destroy stores an in integer r1. If this integer + ** is non-zero, then it is the root page number of a table moved to + ** location iTable. The following code modifies the sqlite_master table to + ** reflect this. + ** + ** The "#NNN" in the SQL is a special constant that means whatever value + ** is in register NNN. See grammar rules associated with the TK_REGISTER + ** token for additional information. + */ + sqlite3NestedParse(pParse, + "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", + pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); +#endif + sqlite3ReleaseTempReg(pParse, r1); +} + +/* +** Write VDBE code to erase table pTab and all associated indices on disk. +** Code to update the sqlite_master tables and internal schema definitions +** in case a root-page belonging to another table is moved by the btree layer +** is also added (this can happen with an auto-vacuum database). +*/ +static void destroyTable(Parse *pParse, Table *pTab){ +#ifdef SQLITE_OMIT_AUTOVACUUM + Index *pIdx; + int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + destroyRootPage(pParse, pTab->tnum, iDb); + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + destroyRootPage(pParse, pIdx->tnum, iDb); + } +#else + /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM + ** is not defined), then it is important to call OP_Destroy on the + ** table and index root-pages in order, starting with the numerically + ** largest root-page number. This guarantees that none of the root-pages + ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the + ** following were coded: + ** + ** OP_Destroy 4 0 + ** ... + ** OP_Destroy 5 0 + ** + ** and root page 5 happened to be the largest root-page number in the + ** database, then root page 5 would be moved to page 4 by the + ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit + ** a free-list page. + */ + int iTab = pTab->tnum; + int iDestroyed = 0; + + while( 1 ){ + Index *pIdx; + int iLargest = 0; + + if( iDestroyed==0 || iTabpIndex; pIdx; pIdx=pIdx->pNext){ + int iIdx = pIdx->tnum; + assert( pIdx->pSchema==pTab->pSchema ); + if( (iDestroyed==0 || (iIdxiLargest ){ + iLargest = iIdx; + } + } + if( iLargest==0 ){ + return; + }else{ + int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + assert( iDb>=0 && iDbdb->nDb ); + destroyRootPage(pParse, iLargest, iDb); + iDestroyed = iLargest; + } + } +#endif +} + +/* +** Remove entries from the sqlite_statN tables (for N in (1,2,3)) +** after a DROP INDEX or DROP TABLE command. +*/ +static void sqlite3ClearStatTables( + Parse *pParse, /* The parsing context */ + int iDb, /* The database number */ + const char *zType, /* "idx" or "tbl" */ + const char *zName /* Name of index or table */ +){ + int i; + const char *zDbName = pParse->db->aDb[iDb].zName; + for(i=1; i<=4; i++){ + char zTab[24]; + sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); + if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ + sqlite3NestedParse(pParse, + "DELETE FROM %Q.%s WHERE %s=%Q", + zDbName, zTab, zType, zName + ); + } + } +} + +/* +** Generate code to drop a table. +*/ +void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ + Vdbe *v; + sqlite3 *db = pParse->db; + Trigger *pTrigger; + Db *pDb = &db->aDb[iDb]; + + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); + sqlite3BeginWriteOperation(pParse, 1, iDb); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + sqlite3VdbeAddOp0(v, OP_VBegin); + } +#endif + + /* Drop all triggers associated with the table being dropped. Code + ** is generated to remove entries from sqlite_master and/or + ** sqlite_temp_master if required. + */ + pTrigger = sqlite3TriggerList(pParse, pTab); + while( pTrigger ){ + assert( pTrigger->pSchema==pTab->pSchema || + pTrigger->pSchema==db->aDb[1].pSchema ); + sqlite3DropTriggerPtr(pParse, pTrigger); + pTrigger = pTrigger->pNext; + } + +#ifndef SQLITE_OMIT_AUTOINCREMENT + /* Remove any entries of the sqlite_sequence table associated with + ** the table being dropped. This is done before the table is dropped + ** at the btree level, in case the sqlite_sequence table needs to + ** move as a result of the drop (can happen in auto-vacuum mode). + */ + if( pTab->tabFlags & TF_Autoincrement ){ + sqlite3NestedParse(pParse, + "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", + pDb->zName, pTab->zName + ); + } +#endif + + /* Drop all SQLITE_MASTER table and index entries that refer to the + ** table. The program name loops through the master table and deletes + ** every row that refers to a table of the same name as the one being + ** dropped. Triggers are handled separately because a trigger can be + ** created in the temp database that refers to a table in another + ** database. + */ + sqlite3NestedParse(pParse, + "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", + pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); + if( !isView && !IsVirtual(pTab) ){ + destroyTable(pParse, pTab); + } + + /* Remove the table entry from SQLite's internal schema and modify + ** the schema cookie. + */ + if( IsVirtual(pTab) ){ + sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); + } + sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); + sqlite3ChangeCookie(pParse, iDb); + sqliteViewResetAll(db, iDb); +} + +/* +** This routine is called to do the work of a DROP TABLE statement. +** pName is the name of the table to be dropped. +*/ +void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ + Table *pTab; + Vdbe *v; + sqlite3 *db = pParse->db; + int iDb; + + if( db->mallocFailed ){ + goto exit_drop_table; + } + assert( pParse->nErr==0 ); + assert( pName->nSrc==1 ); + if( noErr ) db->suppressErr++; + pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); + if( noErr ) db->suppressErr--; + + if( pTab==0 ){ + if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); + goto exit_drop_table; + } + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( iDb>=0 && iDbnDb ); + + /* If pTab is a virtual table, call ViewGetColumnNames() to ensure + ** it is initialized. + */ + if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto exit_drop_table; + } +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int code; + const char *zTab = SCHEMA_TABLE(iDb); + const char *zDb = db->aDb[iDb].zName; + const char *zArg2 = 0; + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ + goto exit_drop_table; + } + if( isView ){ + if( !OMIT_TEMPDB && iDb==1 ){ + code = SQLITE_DROP_TEMP_VIEW; + }else{ + code = SQLITE_DROP_VIEW; + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + }else if( IsVirtual(pTab) ){ + code = SQLITE_DROP_VTABLE; + zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; +#endif + }else{ + if( !OMIT_TEMPDB && iDb==1 ){ + code = SQLITE_DROP_TEMP_TABLE; + }else{ + code = SQLITE_DROP_TABLE; + } + } + if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ + goto exit_drop_table; + } + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ + goto exit_drop_table; + } + } +#endif + if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 + && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ + sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); + goto exit_drop_table; + } + +#ifndef SQLITE_OMIT_VIEW + /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used + ** on a table. + */ + if( isView && pTab->pSelect==0 ){ + sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); + goto exit_drop_table; + } + if( !isView && pTab->pSelect ){ + sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); + goto exit_drop_table; + } +#endif + + /* Generate code to remove the table from the master table + ** on disk. + */ + v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3BeginWriteOperation(pParse, 1, iDb); + sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); + sqlite3FkDropTable(pParse, pName, pTab); + sqlite3CodeDropTable(pParse, pTab, iDb, isView); + } + +exit_drop_table: + sqlite3SrcListDelete(db, pName); +} + +/* +** This routine is called to create a new foreign key on the table +** currently under construction. pFromCol determines which columns +** in the current table point to the foreign key. If pFromCol==0 then +** connect the key to the last column inserted. pTo is the name of +** the table referred to. pToCol is a list of tables in the other +** pTo table that the foreign key points to. flags contains all +** information about the conflict resolution algorithms specified +** in the ON DELETE, ON UPDATE and ON INSERT clauses. +** +** An FKey structure is created and added to the table currently +** under construction in the pParse->pNewTable field. +** +** The foreign key is set for IMMEDIATE processing. A subsequent call +** to sqlite3DeferForeignKey() might change this to DEFERRED. +*/ +void sqlite3CreateForeignKey( + Parse *pParse, /* Parsing context */ + ExprList *pFromCol, /* Columns in this table that point to other table */ + Token *pTo, /* Name of the other table */ + ExprList *pToCol, /* Columns in the other table */ + int flags /* Conflict resolution algorithms. */ +){ + sqlite3 *db = pParse->db; +#ifndef SQLITE_OMIT_FOREIGN_KEY + FKey *pFKey = 0; + FKey *pNextTo; + Table *p = pParse->pNewTable; + int nByte; + int i; + int nCol; + char *z; + + assert( pTo!=0 ); + if( p==0 || IN_DECLARE_VTAB ) goto fk_end; + if( pFromCol==0 ){ + int iCol = p->nCol-1; + if( NEVER(iCol<0) ) goto fk_end; + if( pToCol && pToCol->nExpr!=1 ){ + sqlite3ErrorMsg(pParse, "foreign key on %s" + " should reference only one column of table %T", + p->aCol[iCol].zName, pTo); + goto fk_end; + } + nCol = 1; + }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ + sqlite3ErrorMsg(pParse, + "number of columns in foreign key does not match the number of " + "columns in the referenced table"); + goto fk_end; + }else{ + nCol = pFromCol->nExpr; + } + nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; + if( pToCol ){ + for(i=0; inExpr; i++){ + nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; + } + } + pFKey = sqlite3DbMallocZero(db, nByte ); + if( pFKey==0 ){ + goto fk_end; + } + pFKey->pFrom = p; + pFKey->pNextFrom = p->pFKey; + z = (char*)&pFKey->aCol[nCol]; + pFKey->zTo = z; + memcpy(z, pTo->z, pTo->n); + z[pTo->n] = 0; + sqlite3Dequote(z); + z += pTo->n+1; + pFKey->nCol = nCol; + if( pFromCol==0 ){ + pFKey->aCol[0].iFrom = p->nCol-1; + }else{ + for(i=0; inCol; j++){ + if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ + pFKey->aCol[i].iFrom = j; + break; + } + } + if( j>=p->nCol ){ + sqlite3ErrorMsg(pParse, + "unknown column \"%s\" in foreign key definition", + pFromCol->a[i].zName); + goto fk_end; + } + } + } + if( pToCol ){ + for(i=0; ia[i].zName); + pFKey->aCol[i].zCol = z; + memcpy(z, pToCol->a[i].zName, n); + z[n] = 0; + z += n+1; + } + } + pFKey->isDeferred = 0; + pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ + pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ + + assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); + pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, + pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey + ); + if( pNextTo==pFKey ){ + db->mallocFailed = 1; + goto fk_end; + } + if( pNextTo ){ + assert( pNextTo->pPrevTo==0 ); + pFKey->pNextTo = pNextTo; + pNextTo->pPrevTo = pFKey; + } + + /* Link the foreign key to the table as the last step. + */ + p->pFKey = pFKey; + pFKey = 0; + +fk_end: + sqlite3DbFree(db, pFKey); +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ + sqlite3ExprListDelete(db, pFromCol); + sqlite3ExprListDelete(db, pToCol); +} + +/* +** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED +** clause is seen as part of a foreign key definition. The isDeferred +** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. +** The behavior of the most recently created foreign key is adjusted +** accordingly. +*/ +void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ +#ifndef SQLITE_OMIT_FOREIGN_KEY + Table *pTab; + FKey *pFKey; + if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; + assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ + pFKey->isDeferred = (u8)isDeferred; +#endif +} + +/* +** Generate code that will erase and refill index *pIdx. This is +** used to initialize a newly created index or to recompute the +** content of an index in response to a REINDEX command. +** +** if memRootPage is not negative, it means that the index is newly +** created. The register specified by memRootPage contains the +** root page number of the index. If memRootPage is negative, then +** the index already exists and must be cleared before being refilled and +** the root page number of the index is taken from pIndex->tnum. +*/ +static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ + Table *pTab = pIndex->pTable; /* The table that is indexed */ + int iTab = pParse->nTab++; /* Btree cursor used for pTab */ + int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ + int iSorter; /* Cursor opened by OpenSorter (if in use) */ + int addr1; /* Address of top of loop */ + int addr2; /* Address to jump to for next iteration */ + int tnum; /* Root page of index */ + int iPartIdxLabel; /* Jump to this label to skip a row */ + Vdbe *v; /* Generate code into this virtual machine */ + KeyInfo *pKey; /* KeyInfo for index */ + int regRecord; /* Register holding assemblied index record */ + sqlite3 *db = pParse->db; /* The database connection */ + int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); + +#ifndef SQLITE_OMIT_AUTHORIZATION + if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, + db->aDb[iDb].zName ) ){ + return; + } +#endif + + /* Require a write-lock on the table to perform this operation */ + sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); + + v = sqlite3GetVdbe(pParse); + if( v==0 ) return; + if( memRootPage>=0 ){ + tnum = memRootPage; + }else{ + tnum = pIndex->tnum; + sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); + } + pKey = sqlite3IndexKeyinfo(pParse, pIndex); + sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, + (char *)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); + + /* Open the sorter cursor if we are to use one. */ + iSorter = pParse->nTab++; + sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO); + + /* Open the table. Loop through all rows of the table, inserting index + ** records into the sorter. */ + sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); + addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); + regRecord = sqlite3GetTempReg(pParse); + + sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel); + sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); + sqlite3VdbeResolveLabel(v, iPartIdxLabel); + sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); + sqlite3VdbeJumpHere(v, addr1); + addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); + if( pIndex->onError!=OE_None ){ + int j2 = sqlite3VdbeCurrentAddr(v) + 3; + sqlite3VdbeAddOp2(v, OP_Goto, 0, j2); + addr2 = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE, + OE_Abort, "indexed columns are not unique", P4_STATIC + ); + }else{ + addr2 = sqlite3VdbeCurrentAddr(v); + } + sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord); + sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1); + sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + sqlite3ReleaseTempReg(pParse, regRecord); + sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); + sqlite3VdbeJumpHere(v, addr1); + + sqlite3VdbeAddOp1(v, OP_Close, iTab); + sqlite3VdbeAddOp1(v, OP_Close, iIdx); + sqlite3VdbeAddOp1(v, OP_Close, iSorter); +} + +/* +** Create a new index for an SQL table. pName1.pName2 is the name of the index +** and pTblList is the name of the table that is to be indexed. Both will +** be NULL for a primary key or an index that is created to satisfy a +** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable +** as the table to be indexed. pParse->pNewTable is a table that is +** currently being constructed by a CREATE TABLE statement. +** +** pList is a list of columns to be indexed. pList will be NULL if this +** is a primary key or unique-constraint on the most recent column added +** to the table currently under construction. +** +** If the index is created successfully, return a pointer to the new Index +** structure. This is used by sqlite3AddPrimaryKey() to mark the index +** as the tables primary key (Index.autoIndex==2). +*/ +Index *sqlite3CreateIndex( + Parse *pParse, /* All information about this parse */ + Token *pName1, /* First part of index name. May be NULL */ + Token *pName2, /* Second part of index name. May be NULL */ + SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ + ExprList *pList, /* A list of columns to be indexed */ + int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ + Token *pStart, /* The CREATE token that begins this statement */ + Expr *pPIWhere, /* WHERE clause for partial indices */ + int sortOrder, /* Sort order of primary key when pList==NULL */ + int ifNotExist /* Omit error if index already exists */ +){ + Index *pRet = 0; /* Pointer to return */ + Table *pTab = 0; /* Table to be indexed */ + Index *pIndex = 0; /* The index to be created */ + char *zName = 0; /* Name of the index */ + int nName; /* Number of characters in zName */ + int i, j; + Token nullId; /* Fake token for an empty ID list */ + DbFixer sFix; /* For assigning database names to pTable */ + int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ + sqlite3 *db = pParse->db; + Db *pDb; /* The specific table containing the indexed database */ + int iDb; /* Index of the database that is being written */ + Token *pName = 0; /* Unqualified name of the index to create */ + struct ExprList_item *pListItem; /* For looping over pList */ + const Column *pTabCol; /* A column in the table */ + int nCol; /* Number of columns */ + int nExtra = 0; /* Space allocated for zExtra[] */ + char *zExtra; /* Extra space after the Index object */ + + assert( pParse->nErr==0 ); /* Never called with prior errors */ + if( db->mallocFailed || IN_DECLARE_VTAB ){ + goto exit_create_index; + } + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + goto exit_create_index; + } + + /* + ** Find the table that is to be indexed. Return early if not found. + */ + if( pTblName!=0 ){ + + /* Use the two-part index name to determine the database + ** to search for the table. 'Fix' the table name to this db + ** before looking up the table. + */ + assert( pName1 && pName2 ); + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); + if( iDb<0 ) goto exit_create_index; + assert( pName && pName->z ); + +#ifndef SQLITE_OMIT_TEMPDB + /* If the index name was unqualified, check if the table + ** is a temp table. If so, set the database to 1. Do not do this + ** if initialising a database schema. + */ + if( !db->init.busy ){ + pTab = sqlite3SrcListLookup(pParse, pTblName); + if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ + iDb = 1; + } + } +#endif + + sqlite3FixInit(&sFix, pParse, iDb, "index", pName); + if( sqlite3FixSrcList(&sFix, pTblName) ){ + /* Because the parser constructs pTblName from a single identifier, + ** sqlite3FixSrcList can never fail. */ + assert(0); + } + pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); + assert( db->mallocFailed==0 || pTab==0 ); + if( pTab==0 ) goto exit_create_index; + if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ + sqlite3ErrorMsg(pParse, + "cannot create a TEMP index on non-TEMP table \"%s\"", + pTab->zName); + goto exit_create_index; + } + }else{ + assert( pName==0 ); + assert( pStart==0 ); + pTab = pParse->pNewTable; + if( !pTab ) goto exit_create_index; + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + } + pDb = &db->aDb[iDb]; + + assert( pTab!=0 ); + assert( pParse->nErr==0 ); + if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 + && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ + sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); + goto exit_create_index; + } +#ifndef SQLITE_OMIT_VIEW + if( pTab->pSelect ){ + sqlite3ErrorMsg(pParse, "views may not be indexed"); + goto exit_create_index; + } +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); + goto exit_create_index; + } +#endif + + /* + ** Find the name of the index. Make sure there is not already another + ** index or table with the same name. + ** + ** Exception: If we are reading the names of permanent indices from the + ** sqlite_master table (because some other process changed the schema) and + ** one of the index names collides with the name of a temporary table or + ** index, then we will continue to process this index. + ** + ** If pName==0 it means that we are + ** dealing with a primary key or UNIQUE constraint. We have to invent our + ** own name. + */ + if( pName ){ + zName = sqlite3NameFromToken(db, pName); + if( zName==0 ) goto exit_create_index; + assert( pName->z!=0 ); + if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ + goto exit_create_index; + } + if( !db->init.busy ){ + if( sqlite3FindTable(db, zName, 0)!=0 ){ + sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); + goto exit_create_index; + } + } + if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ + if( !ifNotExist ){ + sqlite3ErrorMsg(pParse, "index %s already exists", zName); + }else{ + assert( !db->init.busy ); + sqlite3CodeVerifySchema(pParse, iDb); + } + goto exit_create_index; + } + }else{ + int n; + Index *pLoop; + for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} + zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); + if( zName==0 ){ + goto exit_create_index; + } + } + + /* Check for authorization to create an index. + */ +#ifndef SQLITE_OMIT_AUTHORIZATION + { + const char *zDb = pDb->zName; + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ + goto exit_create_index; + } + i = SQLITE_CREATE_INDEX; + if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; + if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ + goto exit_create_index; + } + } +#endif + + /* If pList==0, it means this routine was called to make a primary + ** key out of the last column added to the table under construction. + ** So create a fake list to simulate this. + */ + if( pList==0 ){ + nullId.z = pTab->aCol[pTab->nCol-1].zName; + nullId.n = sqlite3Strlen30((char*)nullId.z); + pList = sqlite3ExprListAppend(pParse, 0, 0); + if( pList==0 ) goto exit_create_index; + sqlite3ExprListSetName(pParse, pList, &nullId, 0); + pList->a[0].sortOrder = (u8)sortOrder; + } + + /* Figure out how many bytes of space are required to store explicitly + ** specified collation sequence names. + */ + for(i=0; inExpr; i++){ + Expr *pExpr = pList->a[i].pExpr; + if( pExpr ){ + assert( pExpr->op==TK_COLLATE ); + nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); + } + } + + /* + ** Allocate the index structure. + */ + nName = sqlite3Strlen30(zName); + nCol = pList->nExpr; + pIndex = sqlite3DbMallocZero(db, + ROUND8(sizeof(Index)) + /* Index structure */ + ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */ + sizeof(char *)*nCol + /* Index.azColl */ + sizeof(int)*nCol + /* Index.aiColumn */ + sizeof(u8)*nCol + /* Index.aSortOrder */ + nName + 1 + /* Index.zName */ + nExtra /* Collation sequence names */ + ); + if( db->mallocFailed ){ + goto exit_create_index; + } + zExtra = (char*)pIndex; + pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))]; + pIndex->azColl = (char**) + ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1)); + assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) ); + assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); + pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]); + pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]); + pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]); + zExtra = (char *)(&pIndex->zName[nName+1]); + memcpy(pIndex->zName, zName, nName+1); + pIndex->pTable = pTab; + pIndex->nColumn = pList->nExpr; + pIndex->onError = (u8)onError; + pIndex->uniqNotNull = onError==OE_Abort; + pIndex->autoIndex = (u8)(pName==0); + pIndex->pSchema = db->aDb[iDb].pSchema; + if( pPIWhere ){ + sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); + pIndex->pPartIdxWhere = pPIWhere; + pPIWhere = 0; + } + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + + /* Check to see if we should honor DESC requests on index columns + */ + if( pDb->pSchema->file_format>=4 ){ + sortOrderMask = -1; /* Honor DESC */ + }else{ + sortOrderMask = 0; /* Ignore DESC */ + } + + /* Scan the names of the columns of the table to be indexed and + ** load the column indices into the Index structure. Report an error + ** if any column is not found. + ** + ** TODO: Add a test to make sure that the same column is not named + ** more than once within the same index. Only the first instance of + ** the column will ever be used by the optimizer. Note that using the + ** same column more than once cannot be an error because that would + ** break backwards compatibility - it needs to be a warning. + */ + for(i=0, pListItem=pList->a; inExpr; i++, pListItem++){ + const char *zColName = pListItem->zName; + int requestedSortOrder; + char *zColl; /* Collation sequence name */ + + for(j=0, pTabCol=pTab->aCol; jnCol; j++, pTabCol++){ + if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break; + } + if( j>=pTab->nCol ){ + sqlite3ErrorMsg(pParse, "table %s has no column named %s", + pTab->zName, zColName); + pParse->checkSchema = 1; + goto exit_create_index; + } + pIndex->aiColumn[i] = j; + if( pListItem->pExpr ){ + int nColl; + assert( pListItem->pExpr->op==TK_COLLATE ); + zColl = pListItem->pExpr->u.zToken; + nColl = sqlite3Strlen30(zColl) + 1; + assert( nExtra>=nColl ); + memcpy(zExtra, zColl, nColl); + zColl = zExtra; + zExtra += nColl; + nExtra -= nColl; + }else{ + zColl = pTab->aCol[j].zColl; + if( !zColl ) zColl = "BINARY"; + } + if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ + goto exit_create_index; + } + pIndex->azColl[i] = zColl; + requestedSortOrder = pListItem->sortOrder & sortOrderMask; + pIndex->aSortOrder[i] = (u8)requestedSortOrder; + if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0; + } + sqlite3DefaultRowEst(pIndex); + if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); + + if( pTab==pParse->pNewTable ){ + /* This routine has been called to create an automatic index as a + ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or + ** a PRIMARY KEY or UNIQUE clause following the column definitions. + ** i.e. one of: + ** + ** CREATE TABLE t(x PRIMARY KEY, y); + ** CREATE TABLE t(x, y, UNIQUE(x, y)); + ** + ** Either way, check to see if the table already has such an index. If + ** so, don't bother creating this one. This only applies to + ** automatically created indices. Users can do as they wish with + ** explicit indices. + ** + ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent + ** (and thus suppressing the second one) even if they have different + ** sort orders. + ** + ** If there are different collating sequences or if the columns of + ** the constraint occur in different orders, then the constraints are + ** considered distinct and both result in separate indices. + */ + Index *pIdx; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + int k; + assert( pIdx->onError!=OE_None ); + assert( pIdx->autoIndex ); + assert( pIndex->onError!=OE_None ); + + if( pIdx->nColumn!=pIndex->nColumn ) continue; + for(k=0; knColumn; k++){ + const char *z1; + const char *z2; + if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; + z1 = pIdx->azColl[k]; + z2 = pIndex->azColl[k]; + if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; + } + if( k==pIdx->nColumn ){ + if( pIdx->onError!=pIndex->onError ){ + /* This constraint creates the same index as a previous + ** constraint specified somewhere in the CREATE TABLE statement. + ** However the ON CONFLICT clauses are different. If both this + ** constraint and the previous equivalent constraint have explicit + ** ON CONFLICT clauses this is an error. Otherwise, use the + ** explicitly specified behavior for the index. + */ + if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ + sqlite3ErrorMsg(pParse, + "conflicting ON CONFLICT clauses specified", 0); + } + if( pIdx->onError==OE_Default ){ + pIdx->onError = pIndex->onError; + } + } + goto exit_create_index; + } + } + } + + /* Link the new Index structure to its table and to the other + ** in-memory database structures. + */ + if( db->init.busy ){ + Index *p; + assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); + p = sqlite3HashInsert(&pIndex->pSchema->idxHash, + pIndex->zName, sqlite3Strlen30(pIndex->zName), + pIndex); + if( p ){ + assert( p==pIndex ); /* Malloc must have failed */ + db->mallocFailed = 1; + goto exit_create_index; + } + db->flags |= SQLITE_InternChanges; + if( pTblName!=0 ){ + pIndex->tnum = db->init.newTnum; + } + } + + /* If the db->init.busy is 0 then create the index on disk. This + ** involves writing the index into the master table and filling in the + ** index with the current table contents. + ** + ** The db->init.busy is 0 when the user first enters a CREATE INDEX + ** command. db->init.busy is 1 when a database is opened and + ** CREATE INDEX statements are read out of the master table. In + ** the latter case the index already exists on disk, which is why + ** we don't want to recreate it. + ** + ** If pTblName==0 it means this index is generated as a primary key + ** or UNIQUE constraint of a CREATE TABLE statement. Since the table + ** has just been created, it contains no data and the index initialization + ** step can be skipped. + */ + else if( pParse->nErr==0 ){ + Vdbe *v; + char *zStmt; + int iMem = ++pParse->nMem; + + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto exit_create_index; + + + /* Create the rootpage for the index + */ + sqlite3BeginWriteOperation(pParse, 1, iDb); + sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); + + /* Gather the complete text of the CREATE INDEX statement into + ** the zStmt variable + */ + if( pStart ){ + int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; + if( pName->z[n-1]==';' ) n--; + /* A named index with an explicit CREATE INDEX statement */ + zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", + onError==OE_None ? "" : " UNIQUE", n, pName->z); + }else{ + /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ + /* zStmt = sqlite3MPrintf(""); */ + zStmt = 0; + } + + /* Add an entry in sqlite_master for this index + */ + sqlite3NestedParse(pParse, + "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), + pIndex->zName, + pTab->zName, + iMem, + zStmt + ); + sqlite3DbFree(db, zStmt); + + /* Fill the index with data and reparse the schema. Code an OP_Expire + ** to invalidate all pre-compiled statements. + */ + if( pTblName ){ + sqlite3RefillIndex(pParse, pIndex, iMem); + sqlite3ChangeCookie(pParse, iDb); + sqlite3VdbeAddParseSchemaOp(v, iDb, + sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); + sqlite3VdbeAddOp1(v, OP_Expire, 0); + } + } + + /* When adding an index to the list of indices for a table, make + ** sure all indices labeled OE_Replace come after all those labeled + ** OE_Ignore. This is necessary for the correct constraint check + ** processing (in sqlite3GenerateConstraintChecks()) as part of + ** UPDATE and INSERT statements. + */ + if( db->init.busy || pTblName==0 ){ + if( onError!=OE_Replace || pTab->pIndex==0 + || pTab->pIndex->onError==OE_Replace){ + pIndex->pNext = pTab->pIndex; + pTab->pIndex = pIndex; + }else{ + Index *pOther = pTab->pIndex; + while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ + pOther = pOther->pNext; + } + pIndex->pNext = pOther->pNext; + pOther->pNext = pIndex; + } + pRet = pIndex; + pIndex = 0; + } + + /* Clean up before exiting */ +exit_create_index: + if( pIndex ) freeIndex(db, pIndex); + sqlite3ExprDelete(db, pPIWhere); + sqlite3ExprListDelete(db, pList); + sqlite3SrcListDelete(db, pTblName); + sqlite3DbFree(db, zName); + return pRet; +} + +/* +** Fill the Index.aiRowEst[] array with default information - information +** to be used when we have not run the ANALYZE command. +** +** aiRowEst[0] is suppose to contain the number of elements in the index. +** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the +** number of rows in the table that match any particular value of the +** first column of the index. aiRowEst[2] is an estimate of the number +** of rows that match any particular combiniation of the first 2 columns +** of the index. And so forth. It must always be the case that +* +** aiRowEst[N]<=aiRowEst[N-1] +** aiRowEst[N]>=1 +** +** Apart from that, we have little to go on besides intuition as to +** how aiRowEst[] should be initialized. The numbers generated here +** are based on typical values found in actual indices. +*/ +void sqlite3DefaultRowEst(Index *pIdx){ + tRowcnt *a = pIdx->aiRowEst; + int i; + tRowcnt n; + assert( a!=0 ); + a[0] = pIdx->pTable->nRowEst; + if( a[0]<10 ) a[0] = 10; + n = 10; + for(i=1; i<=pIdx->nColumn; i++){ + a[i] = n; + if( n>5 ) n--; + } + if( pIdx->onError!=OE_None ){ + a[pIdx->nColumn] = 1; + } +} + +/* +** This routine will drop an existing named index. This routine +** implements the DROP INDEX statement. +*/ +void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ + Index *pIndex; + Vdbe *v; + sqlite3 *db = pParse->db; + int iDb; + + assert( pParse->nErr==0 ); /* Never called with prior errors */ + if( db->mallocFailed ){ + goto exit_drop_index; + } + assert( pName->nSrc==1 ); + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + goto exit_drop_index; + } + pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); + if( pIndex==0 ){ + if( !ifExists ){ + sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); + }else{ + sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); + } + pParse->checkSchema = 1; + goto exit_drop_index; + } + if( pIndex->autoIndex ){ + sqlite3ErrorMsg(pParse, "index associated with UNIQUE " + "or PRIMARY KEY constraint cannot be dropped", 0); + goto exit_drop_index; + } + iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int code = SQLITE_DROP_INDEX; + Table *pTab = pIndex->pTable; + const char *zDb = db->aDb[iDb].zName; + const char *zTab = SCHEMA_TABLE(iDb); + if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ + goto exit_drop_index; + } + if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; + if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ + goto exit_drop_index; + } + } +#endif + + /* Generate code to remove the index and from the master table */ + v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3BeginWriteOperation(pParse, 1, iDb); + sqlite3NestedParse(pParse, + "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName + ); + sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); + sqlite3ChangeCookie(pParse, iDb); + destroyRootPage(pParse, pIndex->tnum, iDb); + sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); + } + +exit_drop_index: + sqlite3SrcListDelete(db, pName); +} + +/* +** pArray is a pointer to an array of objects. Each object in the +** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() +** to extend the array so that there is space for a new object at the end. +** +** When this function is called, *pnEntry contains the current size of +** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes +** in total). +** +** If the realloc() is successful (i.e. if no OOM condition occurs), the +** space allocated for the new object is zeroed, *pnEntry updated to +** reflect the new size of the array and a pointer to the new allocation +** returned. *pIdx is set to the index of the new array entry in this case. +** +** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains +** unchanged and a copy of pArray returned. +*/ +void *sqlite3ArrayAllocate( + sqlite3 *db, /* Connection to notify of malloc failures */ + void *pArray, /* Array of objects. Might be reallocated */ + int szEntry, /* Size of each object in the array */ + int *pnEntry, /* Number of objects currently in use */ + int *pIdx /* Write the index of a new slot here */ +){ + char *z; + int n = *pnEntry; + if( (n & (n-1))==0 ){ + int sz = (n==0) ? 1 : 2*n; + void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); + if( pNew==0 ){ + *pIdx = -1; + return pArray; + } + pArray = pNew; + } + z = (char*)pArray; + memset(&z[n * szEntry], 0, szEntry); + *pIdx = n; + ++*pnEntry; + return pArray; +} + +/* +** Append a new element to the given IdList. Create a new IdList if +** need be. +** +** A new IdList is returned, or NULL if malloc() fails. +*/ +IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ + int i; + if( pList==0 ){ + pList = sqlite3DbMallocZero(db, sizeof(IdList) ); + if( pList==0 ) return 0; + } + pList->a = sqlite3ArrayAllocate( + db, + pList->a, + sizeof(pList->a[0]), + &pList->nId, + &i + ); + if( i<0 ){ + sqlite3IdListDelete(db, pList); + return 0; + } + pList->a[i].zName = sqlite3NameFromToken(db, pToken); + return pList; +} + +/* +** Delete an IdList. +*/ +void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ + int i; + if( pList==0 ) return; + for(i=0; inId; i++){ + sqlite3DbFree(db, pList->a[i].zName); + } + sqlite3DbFree(db, pList->a); + sqlite3DbFree(db, pList); +} + +/* +** Return the index in pList of the identifier named zId. Return -1 +** if not found. +*/ +int sqlite3IdListIndex(IdList *pList, const char *zName){ + int i; + if( pList==0 ) return -1; + for(i=0; inId; i++){ + if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; + } + return -1; +} + +/* +** Expand the space allocated for the given SrcList object by +** creating nExtra new slots beginning at iStart. iStart is zero based. +** New slots are zeroed. +** +** For example, suppose a SrcList initially contains two entries: A,B. +** To append 3 new entries onto the end, do this: +** +** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); +** +** After the call above it would contain: A, B, nil, nil, nil. +** If the iStart argument had been 1 instead of 2, then the result +** would have been: A, nil, nil, nil, B. To prepend the new slots, +** the iStart value would be 0. The result then would +** be: nil, nil, nil, A, B. +** +** If a memory allocation fails the SrcList is unchanged. The +** db->mallocFailed flag will be set to true. +*/ +SrcList *sqlite3SrcListEnlarge( + sqlite3 *db, /* Database connection to notify of OOM errors */ + SrcList *pSrc, /* The SrcList to be enlarged */ + int nExtra, /* Number of new slots to add to pSrc->a[] */ + int iStart /* Index in pSrc->a[] of first new slot */ +){ + int i; + + /* Sanity checking on calling parameters */ + assert( iStart>=0 ); + assert( nExtra>=1 ); + assert( pSrc!=0 ); + assert( iStart<=pSrc->nSrc ); + + /* Allocate additional space if needed */ + if( pSrc->nSrc+nExtra>pSrc->nAlloc ){ + SrcList *pNew; + int nAlloc = pSrc->nSrc+nExtra; + int nGot; + pNew = sqlite3DbRealloc(db, pSrc, + sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); + if( pNew==0 ){ + assert( db->mallocFailed ); + return pSrc; + } + pSrc = pNew; + nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; + pSrc->nAlloc = (u8)nGot; + } + + /* Move existing slots that come after the newly inserted slots + ** out of the way */ + for(i=pSrc->nSrc-1; i>=iStart; i--){ + pSrc->a[i+nExtra] = pSrc->a[i]; + } + pSrc->nSrc += (i8)nExtra; + + /* Zero the newly allocated slots */ + memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); + for(i=iStart; ia[i].iCursor = -1; + } + + /* Return a pointer to the enlarged SrcList */ + return pSrc; +} + + +/* +** Append a new table name to the given SrcList. Create a new SrcList if +** need be. A new entry is created in the SrcList even if pTable is NULL. +** +** A SrcList is returned, or NULL if there is an OOM error. The returned +** SrcList might be the same as the SrcList that was input or it might be +** a new one. If an OOM error does occurs, then the prior value of pList +** that is input to this routine is automatically freed. +** +** If pDatabase is not null, it means that the table has an optional +** database name prefix. Like this: "database.table". The pDatabase +** points to the table name and the pTable points to the database name. +** The SrcList.a[].zName field is filled with the table name which might +** come from pTable (if pDatabase is NULL) or from pDatabase. +** SrcList.a[].zDatabase is filled with the database name from pTable, +** or with NULL if no database is specified. +** +** In other words, if call like this: +** +** sqlite3SrcListAppend(D,A,B,0); +** +** Then B is a table name and the database name is unspecified. If called +** like this: +** +** sqlite3SrcListAppend(D,A,B,C); +** +** Then C is the table name and B is the database name. If C is defined +** then so is B. In other words, we never have a case where: +** +** sqlite3SrcListAppend(D,A,0,C); +** +** Both pTable and pDatabase are assumed to be quoted. They are dequoted +** before being added to the SrcList. +*/ +SrcList *sqlite3SrcListAppend( + sqlite3 *db, /* Connection to notify of malloc failures */ + SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ + Token *pTable, /* Table to append */ + Token *pDatabase /* Database of the table */ +){ + struct SrcList_item *pItem; + assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ + if( pList==0 ){ + pList = sqlite3DbMallocZero(db, sizeof(SrcList) ); + if( pList==0 ) return 0; + pList->nAlloc = 1; + } + pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); + if( db->mallocFailed ){ + sqlite3SrcListDelete(db, pList); + return 0; + } + pItem = &pList->a[pList->nSrc-1]; + if( pDatabase && pDatabase->z==0 ){ + pDatabase = 0; + } + if( pDatabase ){ + Token *pTemp = pDatabase; + pDatabase = pTable; + pTable = pTemp; + } + pItem->zName = sqlite3NameFromToken(db, pTable); + pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); + return pList; +} + +/* +** Assign VdbeCursor index numbers to all tables in a SrcList +*/ +void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ + int i; + struct SrcList_item *pItem; + assert(pList || pParse->db->mallocFailed ); + if( pList ){ + for(i=0, pItem=pList->a; inSrc; i++, pItem++){ + if( pItem->iCursor>=0 ) break; + pItem->iCursor = pParse->nTab++; + if( pItem->pSelect ){ + sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); + } + } + } +} + +/* +** Delete an entire SrcList including all its substructure. +*/ +void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ + int i; + struct SrcList_item *pItem; + if( pList==0 ) return; + for(pItem=pList->a, i=0; inSrc; i++, pItem++){ + sqlite3DbFree(db, pItem->zDatabase); + sqlite3DbFree(db, pItem->zName); + sqlite3DbFree(db, pItem->zAlias); + sqlite3DbFree(db, pItem->zIndex); + sqlite3DeleteTable(db, pItem->pTab); + sqlite3SelectDelete(db, pItem->pSelect); + sqlite3ExprDelete(db, pItem->pOn); + sqlite3IdListDelete(db, pItem->pUsing); + } + sqlite3DbFree(db, pList); +} + +/* +** This routine is called by the parser to add a new term to the +** end of a growing FROM clause. The "p" parameter is the part of +** the FROM clause that has already been constructed. "p" is NULL +** if this is the first term of the FROM clause. pTable and pDatabase +** are the name of the table and database named in the FROM clause term. +** pDatabase is NULL if the database name qualifier is missing - the +** usual case. If the term has a alias, then pAlias points to the +** alias token. If the term is a subquery, then pSubquery is the +** SELECT statement that the subquery encodes. The pTable and +** pDatabase parameters are NULL for subqueries. The pOn and pUsing +** parameters are the content of the ON and USING clauses. +** +** Return a new SrcList which encodes is the FROM with the new +** term added. +*/ +SrcList *sqlite3SrcListAppendFromTerm( + Parse *pParse, /* Parsing context */ + SrcList *p, /* The left part of the FROM clause already seen */ + Token *pTable, /* Name of the table to add to the FROM clause */ + Token *pDatabase, /* Name of the database containing pTable */ + Token *pAlias, /* The right-hand side of the AS subexpression */ + Select *pSubquery, /* A subquery used in place of a table name */ + Expr *pOn, /* The ON clause of a join */ + IdList *pUsing /* The USING clause of a join */ +){ + struct SrcList_item *pItem; + sqlite3 *db = pParse->db; + if( !p && (pOn || pUsing) ){ + sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", + (pOn ? "ON" : "USING") + ); + goto append_from_error; + } + p = sqlite3SrcListAppend(db, p, pTable, pDatabase); + if( p==0 || NEVER(p->nSrc==0) ){ + goto append_from_error; + } + pItem = &p->a[p->nSrc-1]; + assert( pAlias!=0 ); + if( pAlias->n ){ + pItem->zAlias = sqlite3NameFromToken(db, pAlias); + } + pItem->pSelect = pSubquery; + pItem->pOn = pOn; + pItem->pUsing = pUsing; + return p; + + append_from_error: + assert( p==0 ); + sqlite3ExprDelete(db, pOn); + sqlite3IdListDelete(db, pUsing); + sqlite3SelectDelete(db, pSubquery); + return 0; +} + +/* +** Add an INDEXED BY or NOT INDEXED clause to the most recently added +** element of the source-list passed as the second argument. +*/ +void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ + assert( pIndexedBy!=0 ); + if( p && ALWAYS(p->nSrc>0) ){ + struct SrcList_item *pItem = &p->a[p->nSrc-1]; + assert( pItem->notIndexed==0 && pItem->zIndex==0 ); + if( pIndexedBy->n==1 && !pIndexedBy->z ){ + /* A "NOT INDEXED" clause was supplied. See parse.y + ** construct "indexed_opt" for details. */ + pItem->notIndexed = 1; + }else{ + pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy); + } + } +} + +/* +** When building up a FROM clause in the parser, the join operator +** is initially attached to the left operand. But the code generator +** expects the join operator to be on the right operand. This routine +** Shifts all join operators from left to right for an entire FROM +** clause. +** +** Example: Suppose the join is like this: +** +** A natural cross join B +** +** The operator is "natural cross join". The A and B operands are stored +** in p->a[0] and p->a[1], respectively. The parser initially stores the +** operator with A. This routine shifts that operator over to B. +*/ +void sqlite3SrcListShiftJoinType(SrcList *p){ + if( p ){ + int i; + assert( p->a || p->nSrc==0 ); + for(i=p->nSrc-1; i>0; i--){ + p->a[i].jointype = p->a[i-1].jointype; + } + p->a[0].jointype = 0; + } +} + +/* +** Begin a transaction +*/ +void sqlite3BeginTransaction(Parse *pParse, int type){ + sqlite3 *db; + Vdbe *v; + int i; + + assert( pParse!=0 ); + db = pParse->db; + assert( db!=0 ); +/* if( db->aDb[0].pBt==0 ) return; */ + if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ + return; + } + v = sqlite3GetVdbe(pParse); + if( !v ) return; + if( type!=TK_DEFERRED ){ + for(i=0; inDb; i++){ + sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); + sqlite3VdbeUsesBtree(v, i); + } + } + sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); +} + +/* +** Commit a transaction +*/ +void sqlite3CommitTransaction(Parse *pParse){ + Vdbe *v; + + assert( pParse!=0 ); + assert( pParse->db!=0 ); + if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ + return; + } + v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); + } +} + +/* +** Rollback a transaction +*/ +void sqlite3RollbackTransaction(Parse *pParse){ + Vdbe *v; + + assert( pParse!=0 ); + assert( pParse->db!=0 ); + if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ + return; + } + v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); + } +} + +/* +** This function is called by the parser when it parses a command to create, +** release or rollback an SQL savepoint. +*/ +void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ + char *zName = sqlite3NameFromToken(pParse->db, pName); + if( zName ){ + Vdbe *v = sqlite3GetVdbe(pParse); +#ifndef SQLITE_OMIT_AUTHORIZATION + static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; + assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); +#endif + if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ + sqlite3DbFree(pParse->db, zName); + return; + } + sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); + } +} + +/* +** Make sure the TEMP database is open and available for use. Return +** the number of errors. Leave any error messages in the pParse structure. +*/ +int sqlite3OpenTempDatabase(Parse *pParse){ + sqlite3 *db = pParse->db; + if( db->aDb[1].pBt==0 && !pParse->explain ){ + int rc; + Btree *pBt; + static const int flags = + SQLITE_OPEN_READWRITE | + SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | + SQLITE_OPEN_DELETEONCLOSE | + SQLITE_OPEN_TEMP_DB; + + rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); + if( rc!=SQLITE_OK ){ + sqlite3ErrorMsg(pParse, "unable to open a temporary database " + "file for storing temporary tables"); + pParse->rc = rc; + return 1; + } + db->aDb[1].pBt = pBt; + assert( db->aDb[1].pSchema ); + if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ + db->mallocFailed = 1; + return 1; + } + } + return 0; +} + +/* +** Generate VDBE code that will verify the schema cookie and start +** a read-transaction for all named database files. +** +** It is important that all schema cookies be verified and all +** read transactions be started before anything else happens in +** the VDBE program. But this routine can be called after much other +** code has been generated. So here is what we do: +** +** The first time this routine is called, we code an OP_Goto that +** will jump to a subroutine at the end of the program. Then we +** record every database that needs its schema verified in the +** pParse->cookieMask field. Later, after all other code has been +** generated, the subroutine that does the cookie verifications and +** starts the transactions will be coded and the OP_Goto P2 value +** will be made to point to that subroutine. The generation of the +** cookie verification subroutine code happens in sqlite3FinishCoding(). +** +** If iDb<0 then code the OP_Goto only - don't set flag to verify the +** schema on any databases. This can be used to position the OP_Goto +** early in the code, before we know if any database tables will be used. +*/ +void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + +#ifndef SQLITE_OMIT_TRIGGER + if( pToplevel!=pParse ){ + /* This branch is taken if a trigger is currently being coded. In this + ** case, set cookieGoto to a non-zero value to show that this function + ** has been called. This is used by the sqlite3ExprCodeConstants() + ** function. */ + pParse->cookieGoto = -1; + } +#endif + if( pToplevel->cookieGoto==0 ){ + Vdbe *v = sqlite3GetVdbe(pToplevel); + if( v==0 ) return; /* This only happens if there was a prior error */ + pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1; + } + if( iDb>=0 ){ + sqlite3 *db = pToplevel->db; + yDbMask mask; + + assert( iDbnDb ); + assert( db->aDb[iDb].pBt!=0 || iDb==1 ); + assert( iDbcookieMask & mask)==0 ){ + pToplevel->cookieMask |= mask; + pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie; + if( !OMIT_TEMPDB && iDb==1 ){ + sqlite3OpenTempDatabase(pToplevel); + } + } + } +} + +/* +** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each +** attached database. Otherwise, invoke it for the database named zDb only. +*/ +void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ + sqlite3 *db = pParse->db; + int i; + for(i=0; inDb; i++){ + Db *pDb = &db->aDb[i]; + if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){ + sqlite3CodeVerifySchema(pParse, i); + } + } +} + +/* +** Generate VDBE code that prepares for doing an operation that +** might change the database. +** +** This routine starts a new transaction if we are not already within +** a transaction. If we are already within a transaction, then a checkpoint +** is set if the setStatement parameter is true. A checkpoint should +** be set for operations that might fail (due to a constraint) part of +** the way through and which will need to undo some writes without having to +** rollback the whole transaction. For operations where all constraints +** can be checked before any changes are made to the database, it is never +** necessary to undo a write and the checkpoint should not be set. +*/ +void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + sqlite3CodeVerifySchema(pParse, iDb); + pToplevel->writeMask |= ((yDbMask)1)<isMultiWrite |= setStatement; +} + +/* +** Indicate that the statement currently under construction might write +** more than one entry (example: deleting one row then inserting another, +** inserting multiple rows in a table, or inserting a row and index entries.) +** If an abort occurs after some of these writes have completed, then it will +** be necessary to undo the completed writes. +*/ +void sqlite3MultiWrite(Parse *pParse){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + pToplevel->isMultiWrite = 1; +} + +/* +** The code generator calls this routine if is discovers that it is +** possible to abort a statement prior to completion. In order to +** perform this abort without corrupting the database, we need to make +** sure that the statement is protected by a statement transaction. +** +** Technically, we only need to set the mayAbort flag if the +** isMultiWrite flag was previously set. There is a time dependency +** such that the abort must occur after the multiwrite. This makes +** some statements involving the REPLACE conflict resolution algorithm +** go a little faster. But taking advantage of this time dependency +** makes it more difficult to prove that the code is correct (in +** particular, it prevents us from writing an effective +** implementation of sqlite3AssertMayAbort()) and so we have chosen +** to take the safe route and skip the optimization. +*/ +void sqlite3MayAbort(Parse *pParse){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + pToplevel->mayAbort = 1; +} + +/* +** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT +** error. The onError parameter determines which (if any) of the statement +** and/or current transaction is rolled back. +*/ +void sqlite3HaltConstraint( + Parse *pParse, /* Parsing context */ + int errCode, /* extended error code */ + int onError, /* Constraint type */ + char *p4, /* Error message */ + int p4type /* P4_STATIC or P4_TRANSIENT */ +){ + Vdbe *v = sqlite3GetVdbe(pParse); + assert( (errCode&0xff)==SQLITE_CONSTRAINT ); + if( onError==OE_Abort ){ + sqlite3MayAbort(pParse); + } + sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); +} + +/* +** Check to see if pIndex uses the collating sequence pColl. Return +** true if it does and false if it does not. +*/ +#ifndef SQLITE_OMIT_REINDEX +static int collationMatch(const char *zColl, Index *pIndex){ + int i; + assert( zColl!=0 ); + for(i=0; inColumn; i++){ + const char *z = pIndex->azColl[i]; + assert( z!=0 ); + if( 0==sqlite3StrICmp(z, zColl) ){ + return 1; + } + } + return 0; +} +#endif + +/* +** Recompute all indices of pTab that use the collating sequence pColl. +** If pColl==0 then recompute all indices of pTab. +*/ +#ifndef SQLITE_OMIT_REINDEX +static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ + Index *pIndex; /* An index associated with pTab */ + + for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ + if( zColl==0 || collationMatch(zColl, pIndex) ){ + int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3RefillIndex(pParse, pIndex, -1); + } + } +} +#endif + +/* +** Recompute all indices of all tables in all databases where the +** indices use the collating sequence pColl. If pColl==0 then recompute +** all indices everywhere. +*/ +#ifndef SQLITE_OMIT_REINDEX +static void reindexDatabases(Parse *pParse, char const *zColl){ + Db *pDb; /* A single database */ + int iDb; /* The database index number */ + sqlite3 *db = pParse->db; /* The database connection */ + HashElem *k; /* For looping over tables in pDb */ + Table *pTab; /* A table in the database */ + + assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ + for(iDb=0, pDb=db->aDb; iDbnDb; iDb++, pDb++){ + assert( pDb!=0 ); + for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ + pTab = (Table*)sqliteHashData(k); + reindexTable(pParse, pTab, zColl); + } + } +} +#endif + +/* +** Generate code for the REINDEX command. +** +** REINDEX -- 1 +** REINDEX -- 2 +** REINDEX ?.? -- 3 +** REINDEX ?.? -- 4 +** +** Form 1 causes all indices in all attached databases to be rebuilt. +** Form 2 rebuilds all indices in all databases that use the named +** collating function. Forms 3 and 4 rebuild the named index or all +** indices associated with the named table. +*/ +#ifndef SQLITE_OMIT_REINDEX +void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ + CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ + char *z; /* Name of a table or index */ + const char *zDb; /* Name of the database */ + Table *pTab; /* A table in the database */ + Index *pIndex; /* An index associated with pTab */ + int iDb; /* The database index number */ + sqlite3 *db = pParse->db; /* The database connection */ + Token *pObjName; /* Name of the table or index to be reindexed */ + + /* Read the database schema. If an error occurs, leave an error message + ** and code in pParse and return NULL. */ + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + return; + } + + if( pName1==0 ){ + reindexDatabases(pParse, 0); + return; + }else if( NEVER(pName2==0) || pName2->z==0 ){ + char *zColl; + assert( pName1->z ); + zColl = sqlite3NameFromToken(pParse->db, pName1); + if( !zColl ) return; + pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); + if( pColl ){ + reindexDatabases(pParse, zColl); + sqlite3DbFree(db, zColl); + return; + } + sqlite3DbFree(db, zColl); + } + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); + if( iDb<0 ) return; + z = sqlite3NameFromToken(db, pObjName); + if( z==0 ) return; + zDb = db->aDb[iDb].zName; + pTab = sqlite3FindTable(db, z, zDb); + if( pTab ){ + reindexTable(pParse, pTab, 0); + sqlite3DbFree(db, z); + return; + } + pIndex = sqlite3FindIndex(db, z, zDb); + sqlite3DbFree(db, z); + if( pIndex ){ + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3RefillIndex(pParse, pIndex, -1); + return; + } + sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); +} +#endif + +/* +** Return a dynamicly allocated KeyInfo structure that can be used +** with OP_OpenRead or OP_OpenWrite to access database index pIdx. +** +** If successful, a pointer to the new structure is returned. In this case +** the caller is responsible for calling sqlite3DbFree(db, ) on the returned +** pointer. If an error occurs (out of memory or missing collation +** sequence), NULL is returned and the state of pParse updated to reflect +** the error. +*/ +KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ + int i; + int nCol = pIdx->nColumn; + KeyInfo *pKey; + + pKey = sqlite3KeyInfoAlloc(pParse->db, nCol); + if( pKey ){ + for(i=0; iazColl[i]; + assert( zColl ); + pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl); + pKey->aSortOrder[i] = pIdx->aSortOrder[i]; + } + } + + if( pParse->nErr ){ + sqlite3DbFree(pParse->db, pKey); + pKey = 0; + } + return pKey; +} diff --git a/components/external/SQLite-3.8.1/src/callback.c b/components/external/SQLite-3.8.1/src/callback.c new file mode 100644 index 0000000000000000000000000000000000000000..66fa490894abc0fe7bc1548649a4eca49b1d5b6d --- /dev/null +++ b/components/external/SQLite-3.8.1/src/callback.c @@ -0,0 +1,478 @@ +/* +** 2005 May 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains functions used to access the internal hash tables +** of user defined functions and collation sequences. +*/ + +#include "sqliteInt.h" + +/* +** Invoke the 'collation needed' callback to request a collation sequence +** in the encoding enc of name zName, length nName. +*/ +static void callCollNeeded(sqlite3 *db, int enc, const char *zName){ + assert( !db->xCollNeeded || !db->xCollNeeded16 ); + if( db->xCollNeeded ){ + char *zExternal = sqlite3DbStrDup(db, zName); + if( !zExternal ) return; + db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal); + sqlite3DbFree(db, zExternal); + } +#ifndef SQLITE_OMIT_UTF16 + if( db->xCollNeeded16 ){ + char const *zExternal; + sqlite3_value *pTmp = sqlite3ValueNew(db); + sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC); + zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE); + if( zExternal ){ + db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal); + } + sqlite3ValueFree(pTmp); + } +#endif +} + +/* +** This routine is called if the collation factory fails to deliver a +** collation function in the best encoding but there may be other versions +** of this collation function (for other text encodings) available. Use one +** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if +** possible. +*/ +static int synthCollSeq(sqlite3 *db, CollSeq *pColl){ + CollSeq *pColl2; + char *z = pColl->zName; + int i; + static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 }; + for(i=0; i<3; i++){ + pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0); + if( pColl2->xCmp!=0 ){ + memcpy(pColl, pColl2, sizeof(CollSeq)); + pColl->xDel = 0; /* Do not copy the destructor */ + return SQLITE_OK; + } + } + return SQLITE_ERROR; +} + +/* +** This function is responsible for invoking the collation factory callback +** or substituting a collation sequence of a different encoding when the +** requested collation sequence is not available in the desired encoding. +** +** If it is not NULL, then pColl must point to the database native encoding +** collation sequence with name zName, length nName. +** +** The return value is either the collation sequence to be used in database +** db for collation type name zName, length nName, or NULL, if no collation +** sequence can be found. If no collation is found, leave an error message. +** +** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq() +*/ +CollSeq *sqlite3GetCollSeq( + Parse *pParse, /* Parsing context */ + u8 enc, /* The desired encoding for the collating sequence */ + CollSeq *pColl, /* Collating sequence with native encoding, or NULL */ + const char *zName /* Collating sequence name */ +){ + CollSeq *p; + sqlite3 *db = pParse->db; + + p = pColl; + if( !p ){ + p = sqlite3FindCollSeq(db, enc, zName, 0); + } + if( !p || !p->xCmp ){ + /* No collation sequence of this type for this encoding is registered. + ** Call the collation factory to see if it can supply us with one. + */ + callCollNeeded(db, enc, zName); + p = sqlite3FindCollSeq(db, enc, zName, 0); + } + if( p && !p->xCmp && synthCollSeq(db, p) ){ + p = 0; + } + assert( !p || p->xCmp ); + if( p==0 ){ + sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName); + } + return p; +} + +/* +** This routine is called on a collation sequence before it is used to +** check that it is defined. An undefined collation sequence exists when +** a database is loaded that contains references to collation sequences +** that have not been defined by sqlite3_create_collation() etc. +** +** If required, this routine calls the 'collation needed' callback to +** request a definition of the collating sequence. If this doesn't work, +** an equivalent collating sequence that uses a text encoding different +** from the main database is substituted, if one is available. +*/ +int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){ + if( pColl ){ + const char *zName = pColl->zName; + sqlite3 *db = pParse->db; + CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName); + if( !p ){ + return SQLITE_ERROR; + } + assert( p==pColl ); + } + return SQLITE_OK; +} + + + +/* +** Locate and return an entry from the db.aCollSeq hash table. If the entry +** specified by zName and nName is not found and parameter 'create' is +** true, then create a new entry. Otherwise return NULL. +** +** Each pointer stored in the sqlite3.aCollSeq hash table contains an +** array of three CollSeq structures. The first is the collation sequence +** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be. +** +** Stored immediately after the three collation sequences is a copy of +** the collation sequence name. A pointer to this string is stored in +** each collation sequence structure. +*/ +static CollSeq *findCollSeqEntry( + sqlite3 *db, /* Database connection */ + const char *zName, /* Name of the collating sequence */ + int create /* Create a new entry if true */ +){ + CollSeq *pColl; + int nName = sqlite3Strlen30(zName); + pColl = sqlite3HashFind(&db->aCollSeq, zName, nName); + + if( 0==pColl && create ){ + pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 ); + if( pColl ){ + CollSeq *pDel = 0; + pColl[0].zName = (char*)&pColl[3]; + pColl[0].enc = SQLITE_UTF8; + pColl[1].zName = (char*)&pColl[3]; + pColl[1].enc = SQLITE_UTF16LE; + pColl[2].zName = (char*)&pColl[3]; + pColl[2].enc = SQLITE_UTF16BE; + memcpy(pColl[0].zName, zName, nName); + pColl[0].zName[nName] = 0; + pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl); + + /* If a malloc() failure occurred in sqlite3HashInsert(), it will + ** return the pColl pointer to be deleted (because it wasn't added + ** to the hash table). + */ + assert( pDel==0 || pDel==pColl ); + if( pDel!=0 ){ + db->mallocFailed = 1; + sqlite3DbFree(db, pDel); + pColl = 0; + } + } + } + return pColl; +} + +/* +** Parameter zName points to a UTF-8 encoded string nName bytes long. +** Return the CollSeq* pointer for the collation sequence named zName +** for the encoding 'enc' from the database 'db'. +** +** If the entry specified is not found and 'create' is true, then create a +** new entry. Otherwise return NULL. +** +** A separate function sqlite3LocateCollSeq() is a wrapper around +** this routine. sqlite3LocateCollSeq() invokes the collation factory +** if necessary and generates an error message if the collating sequence +** cannot be found. +** +** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq() +*/ +CollSeq *sqlite3FindCollSeq( + sqlite3 *db, + u8 enc, + const char *zName, + int create +){ + CollSeq *pColl; + if( zName ){ + pColl = findCollSeqEntry(db, zName, create); + }else{ + pColl = db->pDfltColl; + } + assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); + assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE ); + if( pColl ) pColl += enc-1; + return pColl; +} + +/* During the search for the best function definition, this procedure +** is called to test how well the function passed as the first argument +** matches the request for a function with nArg arguments in a system +** that uses encoding enc. The value returned indicates how well the +** request is matched. A higher value indicates a better match. +** +** If nArg is -1 that means to only return a match (non-zero) if p->nArg +** is also -1. In other words, we are searching for a function that +** takes a variable number of arguments. +** +** If nArg is -2 that means that we are searching for any function +** regardless of the number of arguments it uses, so return a positive +** match score for any +** +** The returned value is always between 0 and 6, as follows: +** +** 0: Not a match. +** 1: UTF8/16 conversion required and function takes any number of arguments. +** 2: UTF16 byte order change required and function takes any number of args. +** 3: encoding matches and function takes any number of arguments +** 4: UTF8/16 conversion required - argument count matches exactly +** 5: UTF16 byte order conversion required - argument count matches exactly +** 6: Perfect match: encoding and argument count match exactly. +** +** If nArg==(-2) then any function with a non-null xStep or xFunc is +** a perfect match and any function with both xStep and xFunc NULL is +** a non-match. +*/ +#define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */ +static int matchQuality( + FuncDef *p, /* The function we are evaluating for match quality */ + int nArg, /* Desired number of arguments. (-1)==any */ + u8 enc /* Desired text encoding */ +){ + int match; + + /* nArg of -2 is a special case */ + if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH; + + /* Wrong number of arguments means "no match" */ + if( p->nArg!=nArg && p->nArg>=0 ) return 0; + + /* Give a better score to a function with a specific number of arguments + ** than to function that accepts any number of arguments. */ + if( p->nArg==nArg ){ + match = 4; + }else{ + match = 1; + } + + /* Bonus points if the text encoding matches */ + if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){ + match += 2; /* Exact encoding match */ + }else if( (enc & p->funcFlags & 2)!=0 ){ + match += 1; /* Both are UTF16, but with different byte orders */ + } + + return match; +} + +/* +** Search a FuncDefHash for a function with the given name. Return +** a pointer to the matching FuncDef if found, or 0 if there is no match. +*/ +static FuncDef *functionSearch( + FuncDefHash *pHash, /* Hash table to search */ + int h, /* Hash of the name */ + const char *zFunc, /* Name of function */ + int nFunc /* Number of bytes in zFunc */ +){ + FuncDef *p; + for(p=pHash->a[h]; p; p=p->pHash){ + if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){ + return p; + } + } + return 0; +} + +/* +** Insert a new FuncDef into a FuncDefHash hash table. +*/ +void sqlite3FuncDefInsert( + FuncDefHash *pHash, /* The hash table into which to insert */ + FuncDef *pDef /* The function definition to insert */ +){ + FuncDef *pOther; + int nName = sqlite3Strlen30(pDef->zName); + u8 c1 = (u8)pDef->zName[0]; + int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a); + pOther = functionSearch(pHash, h, pDef->zName, nName); + if( pOther ){ + assert( pOther!=pDef && pOther->pNext!=pDef ); + pDef->pNext = pOther->pNext; + pOther->pNext = pDef; + }else{ + pDef->pNext = 0; + pDef->pHash = pHash->a[h]; + pHash->a[h] = pDef; + } +} + + + +/* +** Locate a user function given a name, a number of arguments and a flag +** indicating whether the function prefers UTF-16 over UTF-8. Return a +** pointer to the FuncDef structure that defines that function, or return +** NULL if the function does not exist. +** +** If the createFlag argument is true, then a new (blank) FuncDef +** structure is created and liked into the "db" structure if a +** no matching function previously existed. +** +** If nArg is -2, then the first valid function found is returned. A +** function is valid if either xFunc or xStep is non-zero. The nArg==(-2) +** case is used to see if zName is a valid function name for some number +** of arguments. If nArg is -2, then createFlag must be 0. +** +** If createFlag is false, then a function with the required name and +** number of arguments may be returned even if the eTextRep flag does not +** match that requested. +*/ +FuncDef *sqlite3FindFunction( + sqlite3 *db, /* An open database */ + const char *zName, /* Name of the function. Not null-terminated */ + int nName, /* Number of characters in the name */ + int nArg, /* Number of arguments. -1 means any number */ + u8 enc, /* Preferred text encoding */ + u8 createFlag /* Create new entry if true and does not otherwise exist */ +){ + FuncDef *p; /* Iterator variable */ + FuncDef *pBest = 0; /* Best match found so far */ + int bestScore = 0; /* Score of best match */ + int h; /* Hash value */ + + assert( nArg>=(-2) ); + assert( nArg>=(-1) || createFlag==0 ); + assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); + h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a); + + /* First search for a match amongst the application-defined functions. + */ + p = functionSearch(&db->aFunc, h, zName, nName); + while( p ){ + int score = matchQuality(p, nArg, enc); + if( score>bestScore ){ + pBest = p; + bestScore = score; + } + p = p->pNext; + } + + /* If no match is found, search the built-in functions. + ** + ** If the SQLITE_PreferBuiltin flag is set, then search the built-in + ** functions even if a prior app-defined function was found. And give + ** priority to built-in functions. + ** + ** Except, if createFlag is true, that means that we are trying to + ** install a new function. Whatever FuncDef structure is returned it will + ** have fields overwritten with new information appropriate for the + ** new function. But the FuncDefs for built-in functions are read-only. + ** So we must not search for built-ins when creating a new function. + */ + if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){ + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + bestScore = 0; + p = functionSearch(pHash, h, zName, nName); + while( p ){ + int score = matchQuality(p, nArg, enc); + if( score>bestScore ){ + pBest = p; + bestScore = score; + } + p = p->pNext; + } + } + + /* If the createFlag parameter is true and the search did not reveal an + ** exact match for the name, number of arguments and encoding, then add a + ** new entry to the hash table and return it. + */ + if( createFlag && bestScorezName = (char *)&pBest[1]; + pBest->nArg = (u16)nArg; + pBest->funcFlags = enc; + memcpy(pBest->zName, zName, nName); + pBest->zName[nName] = 0; + sqlite3FuncDefInsert(&db->aFunc, pBest); + } + + if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){ + return pBest; + } + return 0; +} + +/* +** Free all resources held by the schema structure. The void* argument points +** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the +** pointer itself, it just cleans up subsidiary resources (i.e. the contents +** of the schema hash tables). +** +** The Schema.cache_size variable is not cleared. +*/ +void sqlite3SchemaClear(void *p){ + Hash temp1; + Hash temp2; + HashElem *pElem; + Schema *pSchema = (Schema *)p; + + temp1 = pSchema->tblHash; + temp2 = pSchema->trigHash; + sqlite3HashInit(&pSchema->trigHash); + sqlite3HashClear(&pSchema->idxHash); + for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){ + sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem)); + } + sqlite3HashClear(&temp2); + sqlite3HashInit(&pSchema->tblHash); + for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){ + Table *pTab = sqliteHashData(pElem); + sqlite3DeleteTable(0, pTab); + } + sqlite3HashClear(&temp1); + sqlite3HashClear(&pSchema->fkeyHash); + pSchema->pSeqTab = 0; + if( pSchema->flags & DB_SchemaLoaded ){ + pSchema->iGeneration++; + pSchema->flags &= ~DB_SchemaLoaded; + } +} + +/* +** Find and return the schema associated with a BTree. Create +** a new one if necessary. +*/ +Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){ + Schema * p; + if( pBt ){ + p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear); + }else{ + p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema)); + } + if( !p ){ + db->mallocFailed = 1; + }else if ( 0==p->file_format ){ + sqlite3HashInit(&p->tblHash); + sqlite3HashInit(&p->idxHash); + sqlite3HashInit(&p->trigHash); + sqlite3HashInit(&p->fkeyHash); + p->enc = SQLITE_UTF8; + } + return p; +} diff --git a/components/external/SQLite-3.8.1/src/complete.c b/components/external/SQLite-3.8.1/src/complete.c new file mode 100644 index 0000000000000000000000000000000000000000..9e9140085c0046ed3bf6f4485220692dca1743c5 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/complete.c @@ -0,0 +1,283 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** An tokenizer for SQL +** +** This file contains C code that implements the sqlite3_complete() API. +** This code used to be part of the tokenizer.c source file. But by +** separating it out, the code will be automatically omitted from +** static links that do not use it. +*/ +#include "sqliteInt.h" +#ifndef SQLITE_OMIT_COMPLETE + +/* +** This is defined in tokenize.c. We just have to import the definition. +*/ +#ifndef SQLITE_AMALGAMATION +#ifdef SQLITE_ASCII +#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) +#endif +#ifdef SQLITE_EBCDIC +extern const char sqlite3IsEbcdicIdChar[]; +#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) +#endif +#endif /* SQLITE_AMALGAMATION */ + + +/* +** Token types used by the sqlite3_complete() routine. See the header +** comments on that procedure for additional information. +*/ +#define tkSEMI 0 +#define tkWS 1 +#define tkOTHER 2 +#ifndef SQLITE_OMIT_TRIGGER +#define tkEXPLAIN 3 +#define tkCREATE 4 +#define tkTEMP 5 +#define tkTRIGGER 6 +#define tkEND 7 +#endif + +/* +** Return TRUE if the given SQL string ends in a semicolon. +** +** Special handling is require for CREATE TRIGGER statements. +** Whenever the CREATE TRIGGER keywords are seen, the statement +** must end with ";END;". +** +** This implementation uses a state machine with 8 states: +** +** (0) INVALID We have not yet seen a non-whitespace character. +** +** (1) START At the beginning or end of an SQL statement. This routine +** returns 1 if it ends in the START state and 0 if it ends +** in any other state. +** +** (2) NORMAL We are in the middle of statement which ends with a single +** semicolon. +** +** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of +** a statement. +** +** (4) CREATE The keyword CREATE has been seen at the beginning of a +** statement, possibly preceeded by EXPLAIN and/or followed by +** TEMP or TEMPORARY +** +** (5) TRIGGER We are in the middle of a trigger definition that must be +** ended by a semicolon, the keyword END, and another semicolon. +** +** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at +** the end of a trigger definition. +** +** (7) END We've seen the ";END" of the ";END;" that occurs at the end +** of a trigger difinition. +** +** Transitions between states above are determined by tokens extracted +** from the input. The following tokens are significant: +** +** (0) tkSEMI A semicolon. +** (1) tkWS Whitespace. +** (2) tkOTHER Any other SQL token. +** (3) tkEXPLAIN The "explain" keyword. +** (4) tkCREATE The "create" keyword. +** (5) tkTEMP The "temp" or "temporary" keyword. +** (6) tkTRIGGER The "trigger" keyword. +** (7) tkEND The "end" keyword. +** +** Whitespace never causes a state transition and is always ignored. +** This means that a SQL string of all whitespace is invalid. +** +** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed +** to recognize the end of a trigger can be omitted. All we have to do +** is look for a semicolon that is not part of an string or comment. +*/ +int sqlite3_complete(const char *zSql){ + u8 state = 0; /* Current state, using numbers defined in header comment */ + u8 token; /* Value of the next token */ + +#ifndef SQLITE_OMIT_TRIGGER + /* A complex statement machine used to detect the end of a CREATE TRIGGER + ** statement. This is the normal case. + */ + static const u8 trans[8][8] = { + /* Token: */ + /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ + /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, }, + /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, }, + /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, }, + /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, }, + /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, }, + /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, }, + /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, }, + /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, }, + }; +#else + /* If triggers are not supported by this compile then the statement machine + ** used to detect the end of a statement is much simplier + */ + static const u8 trans[3][3] = { + /* Token: */ + /* State: ** SEMI WS OTHER */ + /* 0 INVALID: */ { 1, 0, 2, }, + /* 1 START: */ { 1, 1, 2, }, + /* 2 NORMAL: */ { 1, 2, 2, }, + }; +#endif /* SQLITE_OMIT_TRIGGER */ + + while( *zSql ){ + switch( *zSql ){ + case ';': { /* A semicolon */ + token = tkSEMI; + break; + } + case ' ': + case '\r': + case '\t': + case '\n': + case '\f': { /* White space is ignored */ + token = tkWS; + break; + } + case '/': { /* C-style comments */ + if( zSql[1]!='*' ){ + token = tkOTHER; + break; + } + zSql += 2; + while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; } + if( zSql[0]==0 ) return 0; + zSql++; + token = tkWS; + break; + } + case '-': { /* SQL-style comments from "--" to end of line */ + if( zSql[1]!='-' ){ + token = tkOTHER; + break; + } + while( *zSql && *zSql!='\n' ){ zSql++; } + if( *zSql==0 ) return state==1; + token = tkWS; + break; + } + case '[': { /* Microsoft-style identifiers in [...] */ + zSql++; + while( *zSql && *zSql!=']' ){ zSql++; } + if( *zSql==0 ) return 0; + token = tkOTHER; + break; + } + case '`': /* Grave-accent quoted symbols used by MySQL */ + case '"': /* single- and double-quoted strings */ + case '\'': { + int c = *zSql; + zSql++; + while( *zSql && *zSql!=c ){ zSql++; } + if( *zSql==0 ) return 0; + token = tkOTHER; + break; + } + default: { +#ifdef SQLITE_EBCDIC + unsigned char c; +#endif + if( IdChar((u8)*zSql) ){ + /* Keywords and unquoted identifiers */ + int nId; + for(nId=1; IdChar(zSql[nId]); nId++){} +#ifdef SQLITE_OMIT_TRIGGER + token = tkOTHER; +#else + switch( *zSql ){ + case 'c': case 'C': { + if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){ + token = tkCREATE; + }else{ + token = tkOTHER; + } + break; + } + case 't': case 'T': { + if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){ + token = tkTRIGGER; + }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){ + token = tkTEMP; + }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){ + token = tkTEMP; + }else{ + token = tkOTHER; + } + break; + } + case 'e': case 'E': { + if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){ + token = tkEND; + }else +#ifndef SQLITE_OMIT_EXPLAIN + if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){ + token = tkEXPLAIN; + }else +#endif + { + token = tkOTHER; + } + break; + } + default: { + token = tkOTHER; + break; + } + } +#endif /* SQLITE_OMIT_TRIGGER */ + zSql += nId-1; + }else{ + /* Operators and special symbols */ + token = tkOTHER; + } + break; + } + } + state = trans[state][token]; + zSql++; + } + return state==1; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** This routine is the same as the sqlite3_complete() routine described +** above, except that the parameter is required to be UTF-16 encoded, not +** UTF-8. +*/ +int sqlite3_complete16(const void *zSql){ + sqlite3_value *pVal; + char const *zSql8; + int rc = SQLITE_NOMEM; + +#ifndef SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if( rc ) return rc; +#endif + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); + zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); + if( zSql8 ){ + rc = sqlite3_complete(zSql8); + }else{ + rc = SQLITE_NOMEM; + } + sqlite3ValueFree(pVal); + return sqlite3ApiExit(0, rc); +} +#endif /* SQLITE_OMIT_UTF16 */ +#endif /* SQLITE_OMIT_COMPLETE */ diff --git a/components/external/SQLite-3.8.1/src/ctime.c b/components/external/SQLite-3.8.1/src/ctime.c new file mode 100644 index 0000000000000000000000000000000000000000..7c915d58c6ea3f7d159bc594400b184b3d468f42 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/ctime.c @@ -0,0 +1,405 @@ +/* +** 2010 February 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements routines used to report what compile-time options +** SQLite was built with. +*/ + +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS + +#include "sqliteInt.h" + +/* +** An array of names of all compile-time options. This array should +** be sorted A-Z. +** +** This array looks large, but in a typical installation actually uses +** only a handful of compile-time options, so most times this array is usually +** rather short and uses little memory space. +*/ +static const char * const azCompileOpt[] = { + +/* These macros are provided to "stringify" the value of the define +** for those options in which the value is meaningful. */ +#define CTIMEOPT_VAL_(opt) #opt +#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) + +#ifdef SQLITE_32BIT_ROWID + "32BIT_ROWID", +#endif +#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC + "4_BYTE_ALIGNED_MALLOC", +#endif +#ifdef SQLITE_CASE_SENSITIVE_LIKE + "CASE_SENSITIVE_LIKE", +#endif +#ifdef SQLITE_CHECK_PAGES + "CHECK_PAGES", +#endif +#ifdef SQLITE_COVERAGE_TEST + "COVERAGE_TEST", +#endif +#ifdef SQLITE_DEBUG + "DEBUG", +#endif +#ifdef SQLITE_DEFAULT_LOCKING_MODE + "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), +#endif +#if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc) + "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE), +#endif +#ifdef SQLITE_DISABLE_DIRSYNC + "DISABLE_DIRSYNC", +#endif +#ifdef SQLITE_DISABLE_LFS + "DISABLE_LFS", +#endif +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + "ENABLE_ATOMIC_WRITE", +#endif +#ifdef SQLITE_ENABLE_CEROD + "ENABLE_CEROD", +#endif +#ifdef SQLITE_ENABLE_COLUMN_METADATA + "ENABLE_COLUMN_METADATA", +#endif +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT + "ENABLE_EXPENSIVE_ASSERT", +#endif +#ifdef SQLITE_ENABLE_FTS1 + "ENABLE_FTS1", +#endif +#ifdef SQLITE_ENABLE_FTS2 + "ENABLE_FTS2", +#endif +#ifdef SQLITE_ENABLE_FTS3 + "ENABLE_FTS3", +#endif +#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS + "ENABLE_FTS3_PARENTHESIS", +#endif +#ifdef SQLITE_ENABLE_FTS4 + "ENABLE_FTS4", +#endif +#ifdef SQLITE_ENABLE_ICU + "ENABLE_ICU", +#endif +#ifdef SQLITE_ENABLE_IOTRACE + "ENABLE_IOTRACE", +#endif +#ifdef SQLITE_ENABLE_LOAD_EXTENSION + "ENABLE_LOAD_EXTENSION", +#endif +#ifdef SQLITE_ENABLE_LOCKING_STYLE + "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), +#endif +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT + "ENABLE_MEMORY_MANAGEMENT", +#endif +#ifdef SQLITE_ENABLE_MEMSYS3 + "ENABLE_MEMSYS3", +#endif +#ifdef SQLITE_ENABLE_MEMSYS5 + "ENABLE_MEMSYS5", +#endif +#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK + "ENABLE_OVERSIZE_CELL_CHECK", +#endif +#ifdef SQLITE_ENABLE_RTREE + "ENABLE_RTREE", +#endif +#if defined(SQLITE_ENABLE_STAT4) + "ENABLE_STAT4", +#elif defined(SQLITE_ENABLE_STAT3) + "ENABLE_STAT3", +#endif +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + "ENABLE_UNLOCK_NOTIFY", +#endif +#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT + "ENABLE_UPDATE_DELETE_LIMIT", +#endif +#ifdef SQLITE_HAS_CODEC + "HAS_CODEC", +#endif +#ifdef SQLITE_HAVE_ISNAN + "HAVE_ISNAN", +#endif +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + "HOMEGROWN_RECURSIVE_MUTEX", +#endif +#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS + "IGNORE_AFP_LOCK_ERRORS", +#endif +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + "IGNORE_FLOCK_LOCK_ERRORS", +#endif +#ifdef SQLITE_INT64_TYPE + "INT64_TYPE", +#endif +#ifdef SQLITE_LOCK_TRACE + "LOCK_TRACE", +#endif +#if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc) + "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE), +#endif +#ifdef SQLITE_MAX_SCHEMA_RETRY + "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY), +#endif +#ifdef SQLITE_MEMDEBUG + "MEMDEBUG", +#endif +#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT + "MIXED_ENDIAN_64BIT_FLOAT", +#endif +#ifdef SQLITE_NO_SYNC + "NO_SYNC", +#endif +#ifdef SQLITE_OMIT_ALTERTABLE + "OMIT_ALTERTABLE", +#endif +#ifdef SQLITE_OMIT_ANALYZE + "OMIT_ANALYZE", +#endif +#ifdef SQLITE_OMIT_ATTACH + "OMIT_ATTACH", +#endif +#ifdef SQLITE_OMIT_AUTHORIZATION + "OMIT_AUTHORIZATION", +#endif +#ifdef SQLITE_OMIT_AUTOINCREMENT + "OMIT_AUTOINCREMENT", +#endif +#ifdef SQLITE_OMIT_AUTOINIT + "OMIT_AUTOINIT", +#endif +#ifdef SQLITE_OMIT_AUTOMATIC_INDEX + "OMIT_AUTOMATIC_INDEX", +#endif +#ifdef SQLITE_OMIT_AUTORESET + "OMIT_AUTORESET", +#endif +#ifdef SQLITE_OMIT_AUTOVACUUM + "OMIT_AUTOVACUUM", +#endif +#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION + "OMIT_BETWEEN_OPTIMIZATION", +#endif +#ifdef SQLITE_OMIT_BLOB_LITERAL + "OMIT_BLOB_LITERAL", +#endif +#ifdef SQLITE_OMIT_BTREECOUNT + "OMIT_BTREECOUNT", +#endif +#ifdef SQLITE_OMIT_BUILTIN_TEST + "OMIT_BUILTIN_TEST", +#endif +#ifdef SQLITE_OMIT_CAST + "OMIT_CAST", +#endif +#ifdef SQLITE_OMIT_CHECK + "OMIT_CHECK", +#endif +#ifdef SQLITE_OMIT_COMPLETE + "OMIT_COMPLETE", +#endif +#ifdef SQLITE_OMIT_COMPOUND_SELECT + "OMIT_COMPOUND_SELECT", +#endif +#ifdef SQLITE_OMIT_DATETIME_FUNCS + "OMIT_DATETIME_FUNCS", +#endif +#ifdef SQLITE_OMIT_DECLTYPE + "OMIT_DECLTYPE", +#endif +#ifdef SQLITE_OMIT_DEPRECATED + "OMIT_DEPRECATED", +#endif +#ifdef SQLITE_OMIT_DISKIO + "OMIT_DISKIO", +#endif +#ifdef SQLITE_OMIT_EXPLAIN + "OMIT_EXPLAIN", +#endif +#ifdef SQLITE_OMIT_FLAG_PRAGMAS + "OMIT_FLAG_PRAGMAS", +#endif +#ifdef SQLITE_OMIT_FLOATING_POINT + "OMIT_FLOATING_POINT", +#endif +#ifdef SQLITE_OMIT_FOREIGN_KEY + "OMIT_FOREIGN_KEY", +#endif +#ifdef SQLITE_OMIT_GET_TABLE + "OMIT_GET_TABLE", +#endif +#ifdef SQLITE_OMIT_INCRBLOB + "OMIT_INCRBLOB", +#endif +#ifdef SQLITE_OMIT_INTEGRITY_CHECK + "OMIT_INTEGRITY_CHECK", +#endif +#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION + "OMIT_LIKE_OPTIMIZATION", +#endif +#ifdef SQLITE_OMIT_LOAD_EXTENSION + "OMIT_LOAD_EXTENSION", +#endif +#ifdef SQLITE_OMIT_LOCALTIME + "OMIT_LOCALTIME", +#endif +#ifdef SQLITE_OMIT_LOOKASIDE + "OMIT_LOOKASIDE", +#endif +#ifdef SQLITE_OMIT_MEMORYDB + "OMIT_MEMORYDB", +#endif +#ifdef SQLITE_OMIT_OR_OPTIMIZATION + "OMIT_OR_OPTIMIZATION", +#endif +#ifdef SQLITE_OMIT_PAGER_PRAGMAS + "OMIT_PAGER_PRAGMAS", +#endif +#ifdef SQLITE_OMIT_PRAGMA + "OMIT_PRAGMA", +#endif +#ifdef SQLITE_OMIT_PROGRESS_CALLBACK + "OMIT_PROGRESS_CALLBACK", +#endif +#ifdef SQLITE_OMIT_QUICKBALANCE + "OMIT_QUICKBALANCE", +#endif +#ifdef SQLITE_OMIT_REINDEX + "OMIT_REINDEX", +#endif +#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS + "OMIT_SCHEMA_PRAGMAS", +#endif +#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS + "OMIT_SCHEMA_VERSION_PRAGMAS", +#endif +#ifdef SQLITE_OMIT_SHARED_CACHE + "OMIT_SHARED_CACHE", +#endif +#ifdef SQLITE_OMIT_SUBQUERY + "OMIT_SUBQUERY", +#endif +#ifdef SQLITE_OMIT_TCL_VARIABLE + "OMIT_TCL_VARIABLE", +#endif +#ifdef SQLITE_OMIT_TEMPDB + "OMIT_TEMPDB", +#endif +#ifdef SQLITE_OMIT_TRACE + "OMIT_TRACE", +#endif +#ifdef SQLITE_OMIT_TRIGGER + "OMIT_TRIGGER", +#endif +#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION + "OMIT_TRUNCATE_OPTIMIZATION", +#endif +#ifdef SQLITE_OMIT_UTF16 + "OMIT_UTF16", +#endif +#ifdef SQLITE_OMIT_VACUUM + "OMIT_VACUUM", +#endif +#ifdef SQLITE_OMIT_VIEW + "OMIT_VIEW", +#endif +#ifdef SQLITE_OMIT_VIRTUALTABLE + "OMIT_VIRTUALTABLE", +#endif +#ifdef SQLITE_OMIT_WAL + "OMIT_WAL", +#endif +#ifdef SQLITE_OMIT_WSD + "OMIT_WSD", +#endif +#ifdef SQLITE_OMIT_XFER_OPT + "OMIT_XFER_OPT", +#endif +#ifdef SQLITE_PERFORMANCE_TRACE + "PERFORMANCE_TRACE", +#endif +#ifdef SQLITE_PROXY_DEBUG + "PROXY_DEBUG", +#endif +#ifdef SQLITE_RTREE_INT_ONLY + "RTREE_INT_ONLY", +#endif +#ifdef SQLITE_SECURE_DELETE + "SECURE_DELETE", +#endif +#ifdef SQLITE_SMALL_STACK + "SMALL_STACK", +#endif +#ifdef SQLITE_SOUNDEX + "SOUNDEX", +#endif +#ifdef SQLITE_TCL + "TCL", +#endif +#if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc) + "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE), +#endif +#ifdef SQLITE_TEST + "TEST", +#endif +#if defined(SQLITE_THREADSAFE) + "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE), +#endif +#ifdef SQLITE_USE_ALLOCA + "USE_ALLOCA", +#endif +#ifdef SQLITE_ZERO_MALLOC + "ZERO_MALLOC" +#endif +}; + +/* +** Given the name of a compile-time option, return true if that option +** was used and false if not. +** +** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix +** is not required for a match. +*/ +int sqlite3_compileoption_used(const char *zOptName){ + int i, n; + if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7; + n = sqlite3Strlen30(zOptName); + + /* Since ArraySize(azCompileOpt) is normally in single digits, a + ** linear search is adequate. No need for a binary search. */ + for(i=0; i=0 && N +#include +#include + +#ifndef SQLITE_OMIT_DATETIME_FUNCS + + +/* +** A structure for holding a single date and time. +*/ +typedef struct DateTime DateTime; +struct DateTime { + sqlite3_int64 iJD; /* The julian day number times 86400000 */ + int Y, M, D; /* Year, month, and day */ + int h, m; /* Hour and minutes */ + int tz; /* Timezone offset in minutes */ + double s; /* Seconds */ + char validYMD; /* True (1) if Y,M,D are valid */ + char validHMS; /* True (1) if h,m,s are valid */ + char validJD; /* True (1) if iJD is valid */ + char validTZ; /* True (1) if tz is valid */ +}; + + +/* +** Convert zDate into one or more integers. Additional arguments +** come in groups of 5 as follows: +** +** N number of digits in the integer +** min minimum allowed value of the integer +** max maximum allowed value of the integer +** nextC first character after the integer +** pVal where to write the integers value. +** +** Conversions continue until one with nextC==0 is encountered. +** The function returns the number of successful conversions. +*/ +static int getDigits(const char *zDate, ...){ + va_list ap; + int val; + int N; + int min; + int max; + int nextC; + int *pVal; + int cnt = 0; + va_start(ap, zDate); + do{ + N = va_arg(ap, int); + min = va_arg(ap, int); + max = va_arg(ap, int); + nextC = va_arg(ap, int); + pVal = va_arg(ap, int*); + val = 0; + while( N-- ){ + if( !sqlite3Isdigit(*zDate) ){ + goto end_getDigits; + } + val = val*10 + *zDate - '0'; + zDate++; + } + if( valmax || (nextC!=0 && nextC!=*zDate) ){ + goto end_getDigits; + } + *pVal = val; + zDate++; + cnt++; + }while( nextC ); +end_getDigits: + va_end(ap); + return cnt; +} + +/* +** Parse a timezone extension on the end of a date-time. +** The extension is of the form: +** +** (+/-)HH:MM +** +** Or the "zulu" notation: +** +** Z +** +** If the parse is successful, write the number of minutes +** of change in p->tz and return 0. If a parser error occurs, +** return non-zero. +** +** A missing specifier is not considered an error. +*/ +static int parseTimezone(const char *zDate, DateTime *p){ + int sgn = 0; + int nHr, nMn; + int c; + while( sqlite3Isspace(*zDate) ){ zDate++; } + p->tz = 0; + c = *zDate; + if( c=='-' ){ + sgn = -1; + }else if( c=='+' ){ + sgn = +1; + }else if( c=='Z' || c=='z' ){ + zDate++; + goto zulu_time; + }else{ + return c!=0; + } + zDate++; + if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){ + return 1; + } + zDate += 5; + p->tz = sgn*(nMn + nHr*60); +zulu_time: + while( sqlite3Isspace(*zDate) ){ zDate++; } + return *zDate!=0; +} + +/* +** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF. +** The HH, MM, and SS must each be exactly 2 digits. The +** fractional seconds FFFF can be one or more digits. +** +** Return 1 if there is a parsing error and 0 on success. +*/ +static int parseHhMmSs(const char *zDate, DateTime *p){ + int h, m, s; + double ms = 0.0; + if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){ + return 1; + } + zDate += 5; + if( *zDate==':' ){ + zDate++; + if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){ + return 1; + } + zDate += 2; + if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){ + double rScale = 1.0; + zDate++; + while( sqlite3Isdigit(*zDate) ){ + ms = ms*10.0 + *zDate - '0'; + rScale *= 10.0; + zDate++; + } + ms /= rScale; + } + }else{ + s = 0; + } + p->validJD = 0; + p->validHMS = 1; + p->h = h; + p->m = m; + p->s = s + ms; + if( parseTimezone(zDate, p) ) return 1; + p->validTZ = (p->tz!=0)?1:0; + return 0; +} + +/* +** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume +** that the YYYY-MM-DD is according to the Gregorian calendar. +** +** Reference: Meeus page 61 +*/ +static void computeJD(DateTime *p){ + int Y, M, D, A, B, X1, X2; + + if( p->validJD ) return; + if( p->validYMD ){ + Y = p->Y; + M = p->M; + D = p->D; + }else{ + Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */ + M = 1; + D = 1; + } + if( M<=2 ){ + Y--; + M += 12; + } + A = Y/100; + B = 2 - A + (A/4); + X1 = 36525*(Y+4716)/100; + X2 = 306001*(M+1)/10000; + p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000); + p->validJD = 1; + if( p->validHMS ){ + p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000); + if( p->validTZ ){ + p->iJD -= p->tz*60000; + p->validYMD = 0; + p->validHMS = 0; + p->validTZ = 0; + } + } +} + +/* +** Parse dates of the form +** +** YYYY-MM-DD HH:MM:SS.FFF +** YYYY-MM-DD HH:MM:SS +** YYYY-MM-DD HH:MM +** YYYY-MM-DD +** +** Write the result into the DateTime structure and return 0 +** on success and 1 if the input string is not a well-formed +** date. +*/ +static int parseYyyyMmDd(const char *zDate, DateTime *p){ + int Y, M, D, neg; + + if( zDate[0]=='-' ){ + zDate++; + neg = 1; + }else{ + neg = 0; + } + if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){ + return 1; + } + zDate += 10; + while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; } + if( parseHhMmSs(zDate, p)==0 ){ + /* We got the time */ + }else if( *zDate==0 ){ + p->validHMS = 0; + }else{ + return 1; + } + p->validJD = 0; + p->validYMD = 1; + p->Y = neg ? -Y : Y; + p->M = M; + p->D = D; + if( p->validTZ ){ + computeJD(p); + } + return 0; +} + +/* +** Set the time to the current time reported by the VFS. +** +** Return the number of errors. +*/ +static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){ + p->iJD = sqlite3StmtCurrentTime(context); + if( p->iJD>0 ){ + p->validJD = 1; + return 0; + }else{ + return 1; + } +} + +/* +** Attempt to parse the given string into a Julian Day Number. Return +** the number of errors. +** +** The following are acceptable forms for the input string: +** +** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM +** DDDD.DD +** now +** +** In the first form, the +/-HH:MM is always optional. The fractional +** seconds extension (the ".FFF") is optional. The seconds portion +** (":SS.FFF") is option. The year and date can be omitted as long +** as there is a time string. The time string can be omitted as long +** as there is a year and date. +*/ +static int parseDateOrTime( + sqlite3_context *context, + const char *zDate, + DateTime *p +){ + double r; + if( parseYyyyMmDd(zDate,p)==0 ){ + return 0; + }else if( parseHhMmSs(zDate, p)==0 ){ + return 0; + }else if( sqlite3StrICmp(zDate,"now")==0){ + return setDateTimeToCurrent(context, p); + }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){ + p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5); + p->validJD = 1; + return 0; + } + return 1; +} + +/* +** Compute the Year, Month, and Day from the julian day number. +*/ +static void computeYMD(DateTime *p){ + int Z, A, B, C, D, E, X1; + if( p->validYMD ) return; + if( !p->validJD ){ + p->Y = 2000; + p->M = 1; + p->D = 1; + }else{ + Z = (int)((p->iJD + 43200000)/86400000); + A = (int)((Z - 1867216.25)/36524.25); + A = Z + 1 + A - (A/4); + B = A + 1524; + C = (int)((B - 122.1)/365.25); + D = (36525*C)/100; + E = (int)((B-D)/30.6001); + X1 = (int)(30.6001*E); + p->D = B - D - X1; + p->M = E<14 ? E-1 : E-13; + p->Y = p->M>2 ? C - 4716 : C - 4715; + } + p->validYMD = 1; +} + +/* +** Compute the Hour, Minute, and Seconds from the julian day number. +*/ +static void computeHMS(DateTime *p){ + int s; + if( p->validHMS ) return; + computeJD(p); + s = (int)((p->iJD + 43200000) % 86400000); + p->s = s/1000.0; + s = (int)p->s; + p->s -= s; + p->h = s/3600; + s -= p->h*3600; + p->m = s/60; + p->s += s - p->m*60; + p->validHMS = 1; +} + +/* +** Compute both YMD and HMS +*/ +static void computeYMD_HMS(DateTime *p){ + computeYMD(p); + computeHMS(p); +} + +/* +** Clear the YMD and HMS and the TZ +*/ +static void clearYMD_HMS_TZ(DateTime *p){ + p->validYMD = 0; + p->validHMS = 0; + p->validTZ = 0; +} + +/* +** On recent Windows platforms, the localtime_s() function is available +** as part of the "Secure CRT". It is essentially equivalent to +** localtime_r() available under most POSIX platforms, except that the +** order of the parameters is reversed. +** +** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx. +** +** If the user has not indicated to use localtime_r() or localtime_s() +** already, check for an MSVC build environment that provides +** localtime_s(). +*/ +#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \ + defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE) +#define HAVE_LOCALTIME_S 1 +#endif + +#ifndef SQLITE_OMIT_LOCALTIME +/* +** The following routine implements the rough equivalent of localtime_r() +** using whatever operating-system specific localtime facility that +** is available. This routine returns 0 on success and +** non-zero on any kind of error. +** +** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this +** routine will always fail. +** +** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C +** library function localtime_r() is used to assist in the calculation of +** local time. +*/ +static int osLocaltime(time_t *t, struct tm *pTm){ + int rc; +#if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \ + && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S) + struct tm *pX; +#if SQLITE_THREADSAFE>0 + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter(mutex); + pX = localtime(t); +#ifndef SQLITE_OMIT_BUILTIN_TEST + if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0; +#endif + if( pX ) *pTm = *pX; + sqlite3_mutex_leave(mutex); + rc = pX==0; +#else +#ifndef SQLITE_OMIT_BUILTIN_TEST + if( sqlite3GlobalConfig.bLocaltimeFault ) return 1; +#endif +#if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R + rc = localtime_r(t, pTm)==0; +#else + rc = localtime_s(pTm, t); +#endif /* HAVE_LOCALTIME_R */ +#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */ + return rc; +} +#endif /* SQLITE_OMIT_LOCALTIME */ + + +#ifndef SQLITE_OMIT_LOCALTIME +/* +** Compute the difference (in milliseconds) between localtime and UTC +** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs, +** return this value and set *pRc to SQLITE_OK. +** +** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value +** is undefined in this case. +*/ +static sqlite3_int64 localtimeOffset( + DateTime *p, /* Date at which to calculate offset */ + sqlite3_context *pCtx, /* Write error here if one occurs */ + int *pRc /* OUT: Error code. SQLITE_OK or ERROR */ +){ + DateTime x, y; + time_t t; + struct tm sLocal; + + /* Initialize the contents of sLocal to avoid a compiler warning. */ + memset(&sLocal, 0, sizeof(sLocal)); + + x = *p; + computeYMD_HMS(&x); + if( x.Y<1971 || x.Y>=2038 ){ + /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only + ** works for years between 1970 and 2037. For dates outside this range, + ** SQLite attempts to map the year into an equivalent year within this + ** range, do the calculation, then map the year back. + */ + x.Y = 2000; + x.M = 1; + x.D = 1; + x.h = 0; + x.m = 0; + x.s = 0.0; + } else { + int s = (int)(x.s + 0.5); + x.s = s; + } + x.tz = 0; + x.validJD = 0; + computeJD(&x); + t = (time_t)(x.iJD/1000 - 21086676*(i64)10000); + if( osLocaltime(&t, &sLocal) ){ + sqlite3_result_error(pCtx, "local time unavailable", -1); + *pRc = SQLITE_ERROR; + return 0; + } + y.Y = sLocal.tm_year + 1900; + y.M = sLocal.tm_mon + 1; + y.D = sLocal.tm_mday; + y.h = sLocal.tm_hour; + y.m = sLocal.tm_min; + y.s = sLocal.tm_sec; + y.validYMD = 1; + y.validHMS = 1; + y.validJD = 0; + y.validTZ = 0; + computeJD(&y); + *pRc = SQLITE_OK; + return y.iJD - x.iJD; +} +#endif /* SQLITE_OMIT_LOCALTIME */ + +/* +** Process a modifier to a date-time stamp. The modifiers are +** as follows: +** +** NNN days +** NNN hours +** NNN minutes +** NNN.NNNN seconds +** NNN months +** NNN years +** start of month +** start of year +** start of week +** start of day +** weekday N +** unixepoch +** localtime +** utc +** +** Return 0 on success and 1 if there is any kind of error. If the error +** is in a system call (i.e. localtime()), then an error message is written +** to context pCtx. If the error is an unrecognized modifier, no error is +** written to pCtx. +*/ +static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ + int rc = 1; + int n; + double r; + char *z, zBuf[30]; + z = zBuf; + for(n=0; niJD += localtimeOffset(p, pCtx, &rc); + clearYMD_HMS_TZ(p); + } + break; + } +#endif + case 'u': { + /* + ** unixepoch + ** + ** Treat the current value of p->iJD as the number of + ** seconds since 1970. Convert to a real julian day number. + */ + if( strcmp(z, "unixepoch")==0 && p->validJD ){ + p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000; + clearYMD_HMS_TZ(p); + rc = 0; + } +#ifndef SQLITE_OMIT_LOCALTIME + else if( strcmp(z, "utc")==0 ){ + sqlite3_int64 c1; + computeJD(p); + c1 = localtimeOffset(p, pCtx, &rc); + if( rc==SQLITE_OK ){ + p->iJD -= c1; + clearYMD_HMS_TZ(p); + p->iJD += c1 - localtimeOffset(p, pCtx, &rc); + } + } +#endif + break; + } + case 'w': { + /* + ** weekday N + ** + ** Move the date to the same time on the next occurrence of + ** weekday N where 0==Sunday, 1==Monday, and so forth. If the + ** date is already on the appropriate weekday, this is a no-op. + */ + if( strncmp(z, "weekday ", 8)==0 + && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8) + && (n=(int)r)==r && n>=0 && r<7 ){ + sqlite3_int64 Z; + computeYMD_HMS(p); + p->validTZ = 0; + p->validJD = 0; + computeJD(p); + Z = ((p->iJD + 129600000)/86400000) % 7; + if( Z>n ) Z -= 7; + p->iJD += (n - Z)*86400000; + clearYMD_HMS_TZ(p); + rc = 0; + } + break; + } + case 's': { + /* + ** start of TTTTT + ** + ** Move the date backwards to the beginning of the current day, + ** or month or year. + */ + if( strncmp(z, "start of ", 9)!=0 ) break; + z += 9; + computeYMD(p); + p->validHMS = 1; + p->h = p->m = 0; + p->s = 0.0; + p->validTZ = 0; + p->validJD = 0; + if( strcmp(z,"month")==0 ){ + p->D = 1; + rc = 0; + }else if( strcmp(z,"year")==0 ){ + computeYMD(p); + p->M = 1; + p->D = 1; + rc = 0; + }else if( strcmp(z,"day")==0 ){ + rc = 0; + } + break; + } + case '+': + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { + double rRounder; + for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){} + if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){ + rc = 1; + break; + } + if( z[n]==':' ){ + /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the + ** specified number of hours, minutes, seconds, and fractional seconds + ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be + ** omitted. + */ + const char *z2 = z; + DateTime tx; + sqlite3_int64 day; + if( !sqlite3Isdigit(*z2) ) z2++; + memset(&tx, 0, sizeof(tx)); + if( parseHhMmSs(z2, &tx) ) break; + computeJD(&tx); + tx.iJD -= 43200000; + day = tx.iJD/86400000; + tx.iJD -= day*86400000; + if( z[0]=='-' ) tx.iJD = -tx.iJD; + computeJD(p); + clearYMD_HMS_TZ(p); + p->iJD += tx.iJD; + rc = 0; + break; + } + z += n; + while( sqlite3Isspace(*z) ) z++; + n = sqlite3Strlen30(z); + if( n>10 || n<3 ) break; + if( z[n-1]=='s' ){ z[n-1] = 0; n--; } + computeJD(p); + rc = 0; + rRounder = r<0 ? -0.5 : +0.5; + if( n==3 && strcmp(z,"day")==0 ){ + p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder); + }else if( n==4 && strcmp(z,"hour")==0 ){ + p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder); + }else if( n==6 && strcmp(z,"minute")==0 ){ + p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder); + }else if( n==6 && strcmp(z,"second")==0 ){ + p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder); + }else if( n==5 && strcmp(z,"month")==0 ){ + int x, y; + computeYMD_HMS(p); + p->M += (int)r; + x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; + p->Y += x; + p->M -= x*12; + p->validJD = 0; + computeJD(p); + y = (int)r; + if( y!=r ){ + p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder); + } + }else if( n==4 && strcmp(z,"year")==0 ){ + int y = (int)r; + computeYMD_HMS(p); + p->Y += y; + p->validJD = 0; + computeJD(p); + if( y!=r ){ + p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder); + } + }else{ + rc = 1; + } + clearYMD_HMS_TZ(p); + break; + } + default: { + break; + } + } + return rc; +} + +/* +** Process time function arguments. argv[0] is a date-time stamp. +** argv[1] and following are modifiers. Parse them all and write +** the resulting time into the DateTime structure p. Return 0 +** on success and 1 if there are any errors. +** +** If there are zero parameters (if even argv[0] is undefined) +** then assume a default value of "now" for argv[0]. +*/ +static int isDate( + sqlite3_context *context, + int argc, + sqlite3_value **argv, + DateTime *p +){ + int i; + const unsigned char *z; + int eType; + memset(p, 0, sizeof(*p)); + if( argc==0 ){ + return setDateTimeToCurrent(context, p); + } + if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT + || eType==SQLITE_INTEGER ){ + p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5); + p->validJD = 1; + }else{ + z = sqlite3_value_text(argv[0]); + if( !z || parseDateOrTime(context, (char*)z, p) ){ + return 1; + } + } + for(i=1; iaLimit[SQLITE_LIMIT_LENGTH]+1 ); + testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ); + if( n(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){ + sqlite3_result_error_toobig(context); + return; + }else{ + z = sqlite3DbMallocRaw(db, (int)n); + if( z==0 ){ + sqlite3_result_error_nomem(context); + return; + } + } + computeJD(&x); + computeYMD_HMS(&x); + for(i=j=0; zFmt[i]; i++){ + if( zFmt[i]!='%' ){ + z[j++] = zFmt[i]; + }else{ + i++; + switch( zFmt[i] ){ + case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break; + case 'f': { + double s = x.s; + if( s>59.999 ) s = 59.999; + sqlite3_snprintf(7, &z[j],"%06.3f", s); + j += sqlite3Strlen30(&z[j]); + break; + } + case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break; + case 'W': /* Fall thru */ + case 'j': { + int nDay; /* Number of days since 1st day of year */ + DateTime y = x; + y.validJD = 0; + y.M = 1; + y.D = 1; + computeJD(&y); + nDay = (int)((x.iJD-y.iJD+43200000)/86400000); + if( zFmt[i]=='W' ){ + int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */ + wd = (int)(((x.iJD+43200000)/86400000)%7); + sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7); + j += 2; + }else{ + sqlite3_snprintf(4, &z[j],"%03d",nDay+1); + j += 3; + } + break; + } + case 'J': { + sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0); + j+=sqlite3Strlen30(&z[j]); + break; + } + case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break; + case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break; + case 's': { + sqlite3_snprintf(30,&z[j],"%lld", + (i64)(x.iJD/1000 - 21086676*(i64)10000)); + j += sqlite3Strlen30(&z[j]); + break; + } + case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break; + case 'w': { + z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0'; + break; + } + case 'Y': { + sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]); + break; + } + default: z[j++] = '%'; break; + } + } + } + z[j] = 0; + sqlite3_result_text(context, z, -1, + z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC); +} + +/* +** current_time() +** +** This function returns the same value as time('now'). +*/ +static void ctimeFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + timeFunc(context, 0, 0); +} + +/* +** current_date() +** +** This function returns the same value as date('now'). +*/ +static void cdateFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + dateFunc(context, 0, 0); +} + +/* +** current_timestamp() +** +** This function returns the same value as datetime('now'). +*/ +static void ctimestampFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + datetimeFunc(context, 0, 0); +} +#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */ + +#ifdef SQLITE_OMIT_DATETIME_FUNCS +/* +** If the library is compiled to omit the full-scale date and time +** handling (to get a smaller binary), the following minimal version +** of the functions current_time(), current_date() and current_timestamp() +** are included instead. This is to support column declarations that +** include "DEFAULT CURRENT_TIME" etc. +** +** This function uses the C-library functions time(), gmtime() +** and strftime(). The format string to pass to strftime() is supplied +** as the user-data for the function. +*/ +static void currentTimeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + time_t t; + char *zFormat = (char *)sqlite3_user_data(context); + sqlite3 *db; + sqlite3_int64 iT; + struct tm *pTm; + struct tm sNow; + char zBuf[20]; + + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + + iT = sqlite3StmtCurrentTime(context); + if( iT<=0 ) return; + t = iT/1000 - 10000*(sqlite3_int64)21086676; +#ifdef HAVE_GMTIME_R + pTm = gmtime_r(&t, &sNow); +#else + sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); + pTm = gmtime(&t); + if( pTm ) memcpy(&sNow, pTm, sizeof(sNow)); + sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +#endif + if( pTm ){ + strftime(zBuf, 20, zFormat, &sNow); + sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + } +} +#endif + +/* +** This function registered all of the above C functions as SQL +** functions. This should be the only routine in this file with +** external linkage. +*/ +void sqlite3RegisterDateTimeFunctions(void){ + static SQLITE_WSD FuncDef aDateTimeFuncs[] = { +#ifndef SQLITE_OMIT_DATETIME_FUNCS + FUNCTION(julianday, -1, 0, 0, juliandayFunc ), + FUNCTION(date, -1, 0, 0, dateFunc ), + FUNCTION(time, -1, 0, 0, timeFunc ), + FUNCTION(datetime, -1, 0, 0, datetimeFunc ), + FUNCTION(strftime, -1, 0, 0, strftimeFunc ), + FUNCTION(current_time, 0, 0, 0, ctimeFunc ), + FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc), + FUNCTION(current_date, 0, 0, 0, cdateFunc ), +#else + STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc), + STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc), + STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), +#endif + }; + int i; + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs); + + for(i=0; ia[0].pTab Pointer to the Table object +** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one +** +*/ +Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ + struct SrcList_item *pItem = pSrc->a; + Table *pTab; + assert( pItem && pSrc->nSrc==1 ); + pTab = sqlite3LocateTableItem(pParse, 0, pItem); + sqlite3DeleteTable(pParse->db, pItem->pTab); + pItem->pTab = pTab; + if( pTab ){ + pTab->nRef++; + } + if( sqlite3IndexedByLookup(pParse, pItem) ){ + pTab = 0; + } + return pTab; +} + +/* +** Check to make sure the given table is writable. If it is not +** writable, generate an error message and return 1. If it is +** writable return 0; +*/ +int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ + /* A table is not writable under the following circumstances: + ** + ** 1) It is a virtual table and no implementation of the xUpdate method + ** has been provided, or + ** 2) It is a system table (i.e. sqlite_master), this call is not + ** part of a nested parse and writable_schema pragma has not + ** been specified. + ** + ** In either case leave an error message in pParse and return non-zero. + */ + if( ( IsVirtual(pTab) + && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ) + || ( (pTab->tabFlags & TF_Readonly)!=0 + && (pParse->db->flags & SQLITE_WriteSchema)==0 + && pParse->nested==0 ) + ){ + sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); + return 1; + } + +#ifndef SQLITE_OMIT_VIEW + if( !viewOk && pTab->pSelect ){ + sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName); + return 1; + } +#endif + return 0; +} + + +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) +/* +** Evaluate a view and store its result in an ephemeral table. The +** pWhere argument is an optional WHERE clause that restricts the +** set of rows in the view that are to be added to the ephemeral table. +*/ +void sqlite3MaterializeView( + Parse *pParse, /* Parsing context */ + Table *pView, /* View definition */ + Expr *pWhere, /* Optional WHERE clause to be added */ + int iCur /* Cursor number for ephemerial table */ +){ + SelectDest dest; + Select *pSel; + SrcList *pFrom; + sqlite3 *db = pParse->db; + int iDb = sqlite3SchemaToIndex(db, pView->pSchema); + + pWhere = sqlite3ExprDup(db, pWhere, 0); + pFrom = sqlite3SrcListAppend(db, 0, 0, 0); + + if( pFrom ){ + assert( pFrom->nSrc==1 ); + pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName); + pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName); + assert( pFrom->a[0].pOn==0 ); + assert( pFrom->a[0].pUsing==0 ); + } + + pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0); + if( pSel ) pSel->selFlags |= SF_Materialize; + + sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); + sqlite3Select(pParse, pSel, &dest); + sqlite3SelectDelete(db, pSel); +} +#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */ + +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) +/* +** Generate an expression tree to implement the WHERE, ORDER BY, +** and LIMIT/OFFSET portion of DELETE and UPDATE statements. +** +** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1; +** \__________________________/ +** pLimitWhere (pInClause) +*/ +Expr *sqlite3LimitWhere( + Parse *pParse, /* The parser context */ + SrcList *pSrc, /* the FROM clause -- which tables to scan */ + Expr *pWhere, /* The WHERE clause. May be null */ + ExprList *pOrderBy, /* The ORDER BY clause. May be null */ + Expr *pLimit, /* The LIMIT clause. May be null */ + Expr *pOffset, /* The OFFSET clause. May be null */ + char *zStmtType /* Either DELETE or UPDATE. For error messages. */ +){ + Expr *pWhereRowid = NULL; /* WHERE rowid .. */ + Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */ + Expr *pSelectRowid = NULL; /* SELECT rowid ... */ + ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */ + SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */ + Select *pSelect = NULL; /* Complete SELECT tree */ + + /* Check that there isn't an ORDER BY without a LIMIT clause. + */ + if( pOrderBy && (pLimit == 0) ) { + sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); + goto limit_where_cleanup_2; + } + + /* We only need to generate a select expression if there + ** is a limit/offset term to enforce. + */ + if( pLimit == 0 ) { + /* if pLimit is null, pOffset will always be null as well. */ + assert( pOffset == 0 ); + return pWhere; + } + + /* Generate a select expression tree to enforce the limit/offset + ** term for the DELETE or UPDATE statement. For example: + ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 + ** becomes: + ** DELETE FROM table_a WHERE rowid IN ( + ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 + ** ); + */ + + pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0); + if( pSelectRowid == 0 ) goto limit_where_cleanup_2; + pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid); + if( pEList == 0 ) goto limit_where_cleanup_2; + + /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree + ** and the SELECT subtree. */ + pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0); + if( pSelectSrc == 0 ) { + sqlite3ExprListDelete(pParse->db, pEList); + goto limit_where_cleanup_2; + } + + /* generate the SELECT expression tree. */ + pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0, + pOrderBy,0,pLimit,pOffset); + if( pSelect == 0 ) return 0; + + /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ + pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0); + if( pWhereRowid == 0 ) goto limit_where_cleanup_1; + pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0); + if( pInClause == 0 ) goto limit_where_cleanup_1; + + pInClause->x.pSelect = pSelect; + pInClause->flags |= EP_xIsSelect; + sqlite3ExprSetHeight(pParse, pInClause); + return pInClause; + + /* something went wrong. clean up anything allocated. */ +limit_where_cleanup_1: + sqlite3SelectDelete(pParse->db, pSelect); + return 0; + +limit_where_cleanup_2: + sqlite3ExprDelete(pParse->db, pWhere); + sqlite3ExprListDelete(pParse->db, pOrderBy); + sqlite3ExprDelete(pParse->db, pLimit); + sqlite3ExprDelete(pParse->db, pOffset); + return 0; +} +#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ + +/* +** Generate code for a DELETE FROM statement. +** +** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; +** \________/ \________________/ +** pTabList pWhere +*/ +void sqlite3DeleteFrom( + Parse *pParse, /* The parser context */ + SrcList *pTabList, /* The table from which we should delete things */ + Expr *pWhere /* The WHERE clause. May be null */ +){ + Vdbe *v; /* The virtual database engine */ + Table *pTab; /* The table from which records will be deleted */ + const char *zDb; /* Name of database holding pTab */ + int end, addr = 0; /* A couple addresses of generated code */ + int i; /* Loop counter */ + WhereInfo *pWInfo; /* Information about the WHERE clause */ + Index *pIdx; /* For looping over indices of the table */ + int iCur; /* VDBE Cursor number for pTab */ + sqlite3 *db; /* Main database structure */ + AuthContext sContext; /* Authorization context */ + NameContext sNC; /* Name context to resolve expressions in */ + int iDb; /* Database number */ + int memCnt = -1; /* Memory cell used for change counting */ + int rcauth; /* Value returned by authorization callback */ + +#ifndef SQLITE_OMIT_TRIGGER + int isView; /* True if attempting to delete from a view */ + Trigger *pTrigger; /* List of table triggers, if required */ +#endif + + memset(&sContext, 0, sizeof(sContext)); + db = pParse->db; + if( pParse->nErr || db->mallocFailed ){ + goto delete_from_cleanup; + } + assert( pTabList->nSrc==1 ); + + /* Locate the table which we want to delete. This table has to be + ** put in an SrcList structure because some of the subroutines we + ** will be calling are designed to work with multiple tables and expect + ** an SrcList* parameter instead of just a Table* parameter. + */ + pTab = sqlite3SrcListLookup(pParse, pTabList); + if( pTab==0 ) goto delete_from_cleanup; + + /* Figure out if we have any triggers and if the table being + ** deleted from is a view + */ +#ifndef SQLITE_OMIT_TRIGGER + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); + isView = pTab->pSelect!=0; +#else +# define pTrigger 0 +# define isView 0 +#endif +#ifdef SQLITE_OMIT_VIEW +# undef isView +# define isView 0 +#endif + + /* If pTab is really a view, make sure it has been initialized. + */ + if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto delete_from_cleanup; + } + + if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){ + goto delete_from_cleanup; + } + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( iDbnDb ); + zDb = db->aDb[iDb].zName; + rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb); + assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE ); + if( rcauth==SQLITE_DENY ){ + goto delete_from_cleanup; + } + assert(!isView || pTrigger); + + /* Assign cursor number to the table and all its indices. + */ + assert( pTabList->nSrc==1 ); + iCur = pTabList->a[0].iCursor = pParse->nTab++; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + pParse->nTab++; + } + + /* Start the view context + */ + if( isView ){ + sqlite3AuthContextPush(pParse, &sContext, pTab->zName); + } + + /* Begin generating code. + */ + v = sqlite3GetVdbe(pParse); + if( v==0 ){ + goto delete_from_cleanup; + } + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); + sqlite3BeginWriteOperation(pParse, 1, iDb); + + /* If we are trying to delete from a view, realize that view into + ** a ephemeral table. + */ +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) + if( isView ){ + sqlite3MaterializeView(pParse, pTab, pWhere, iCur); + } +#endif + + /* Resolve the column names in the WHERE clause. + */ + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + if( sqlite3ResolveExprNames(&sNC, pWhere) ){ + goto delete_from_cleanup; + } + + /* Initialize the counter of the number of rows deleted, if + ** we are counting rows. + */ + if( db->flags & SQLITE_CountRows ){ + memCnt = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); + } + +#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION + /* Special case: A DELETE without a WHERE clause deletes everything. + ** It is easier just to erase the whole table. Prior to version 3.6.5, + ** this optimization caused the row change count (the value returned by + ** API function sqlite3_count_changes) to be set incorrectly. */ + if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) + && 0==sqlite3FkRequired(pParse, pTab, 0, 0) + ){ + assert( !isView ); + sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); + sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt, + pTab->zName, P4_STATIC); + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + assert( pIdx->pSchema==pTab->pSchema ); + sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); + } + }else +#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ + /* The usual case: There is a WHERE clause so we have to scan through + ** the table and pick which records to delete. + */ + { + int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */ + int iRowid = ++pParse->nMem; /* Used for storing rowid values. */ + int regRowid; /* Actual register containing rowids */ + + /* Collect rowids of every row to be deleted. + */ + sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); + pWInfo = sqlite3WhereBegin( + pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0 + ); + if( pWInfo==0 ) goto delete_from_cleanup; + regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0); + sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid); + if( db->flags & SQLITE_CountRows ){ + sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); + } + sqlite3WhereEnd(pWInfo); + + /* Delete every item whose key was written to the list during the + ** database scan. We have to delete items after the scan is complete + ** because deleting an item can change the scan order. */ + end = sqlite3VdbeMakeLabel(v); + + /* Unless this is a view, open cursors for the table we are + ** deleting from and all its indices. If this is a view, then the + ** only effect this statement has is to fire the INSTEAD OF + ** triggers. */ + if( !isView ){ + sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite); + } + + addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid); + + /* Delete the row */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); + sqlite3VtabMakeWritable(pParse, pTab); + sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB); + sqlite3VdbeChangeP5(v, OE_Abort); + sqlite3MayAbort(pParse); + }else +#endif + { + int count = (pParse->nested==0); /* True to count changes */ + sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default); + } + + /* End of the delete loop */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); + sqlite3VdbeResolveLabel(v, end); + + /* Close the cursors open on the table and its indexes. */ + if( !isView && !IsVirtual(pTab) ){ + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ + sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum); + } + sqlite3VdbeAddOp1(v, OP_Close, iCur); + } + } + + /* Update the sqlite_sequence table by storing the content of the + ** maximum rowid counter values recorded while inserting into + ** autoincrement tables. + */ + if( pParse->nested==0 && pParse->pTriggerTab==0 ){ + sqlite3AutoincrementEnd(pParse); + } + + /* Return the number of rows that were deleted. If this routine is + ** generating code because of a call to sqlite3NestedParse(), do not + ** invoke the callback function. + */ + if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ + sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); + } + +delete_from_cleanup: + sqlite3AuthContextPop(&sContext); + sqlite3SrcListDelete(db, pTabList); + sqlite3ExprDelete(db, pWhere); + return; +} +/* Make sure "isView" and other macros defined above are undefined. Otherwise +** thely may interfere with compilation of other functions in this file +** (or in another file, if this file becomes part of the amalgamation). */ +#ifdef isView + #undef isView +#endif +#ifdef pTrigger + #undef pTrigger +#endif + +/* +** This routine generates VDBE code that causes a single row of a +** single table to be deleted. +** +** The VDBE must be in a particular state when this routine is called. +** These are the requirements: +** +** 1. A read/write cursor pointing to pTab, the table containing the row +** to be deleted, must be opened as cursor number $iCur. +** +** 2. Read/write cursors for all indices of pTab must be open as +** cursor number base+i for the i-th index. +** +** 3. The record number of the row to be deleted must be stored in +** memory cell iRowid. +** +** This routine generates code to remove both the table record and all +** index entries that point to that record. +*/ +void sqlite3GenerateRowDelete( + Parse *pParse, /* Parsing context */ + Table *pTab, /* Table containing the row to be deleted */ + int iCur, /* Cursor number for the table */ + int iRowid, /* Memory cell that contains the rowid to delete */ + int count, /* If non-zero, increment the row change counter */ + Trigger *pTrigger, /* List of triggers to (potentially) fire */ + int onconf /* Default ON CONFLICT policy for triggers */ +){ + Vdbe *v = pParse->pVdbe; /* Vdbe */ + int iOld = 0; /* First register in OLD.* array */ + int iLabel; /* Label resolved to end of generated code */ + + /* Vdbe is guaranteed to have been allocated by this stage. */ + assert( v ); + + /* Seek cursor iCur to the row to delete. If this row no longer exists + ** (this can happen if a trigger program has already deleted it), do + ** not attempt to delete it or fire any DELETE triggers. */ + iLabel = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid); + + /* If there are any triggers to fire, allocate a range of registers to + ** use for the old.* references in the triggers. */ + if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){ + u32 mask; /* Mask of OLD.* columns in use */ + int iCol; /* Iterator used while populating OLD.* */ + + /* TODO: Could use temporary registers here. Also could attempt to + ** avoid copying the contents of the rowid register. */ + mask = sqlite3TriggerColmask( + pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf + ); + mask |= sqlite3FkOldmask(pParse, pTab); + iOld = pParse->nMem+1; + pParse->nMem += (1 + pTab->nCol); + + /* Populate the OLD.* pseudo-table register array. These values will be + ** used by any BEFORE and AFTER triggers that exist. */ + sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld); + for(iCol=0; iColnCol; iCol++){ + if( mask==0xffffffff || mask&(1<pSelect==0 ){ + sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0); + sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0)); + if( count ){ + sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); + } + } + + /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to + ** handle rows (possibly in other tables) that refer via a foreign key + ** to the row just deleted. */ + sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0); + + /* Invoke AFTER DELETE trigger programs. */ + sqlite3CodeRowTrigger(pParse, pTrigger, + TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel + ); + + /* Jump here if the row had already been deleted before any BEFORE + ** trigger programs were invoked. Or if a trigger program throws a + ** RAISE(IGNORE) exception. */ + sqlite3VdbeResolveLabel(v, iLabel); +} + +/* +** This routine generates VDBE code that causes the deletion of all +** index entries associated with a single row of a single table. +** +** The VDBE must be in a particular state when this routine is called. +** These are the requirements: +** +** 1. A read/write cursor pointing to pTab, the table containing the row +** to be deleted, must be opened as cursor number "iCur". +** +** 2. Read/write cursors for all indices of pTab must be open as +** cursor number iCur+i for the i-th index. +** +** 3. The "iCur" cursor must be pointing to the row that is to be +** deleted. +*/ +void sqlite3GenerateRowIndexDelete( + Parse *pParse, /* Parsing and code generating context */ + Table *pTab, /* Table containing the row to be deleted */ + int iCur, /* Cursor number for the table */ + int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ +){ + int i; + Index *pIdx; + int r1; + int iPartIdxLabel; + Vdbe *v = pParse->pVdbe; + + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ + if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue; + r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel); + sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1); + sqlite3VdbeResolveLabel(v, iPartIdxLabel); + } +} + +/* +** Generate code that will assemble an index key and put it in register +** regOut. The key with be for index pIdx which is an index on pTab. +** iCur is the index of a cursor open on the pTab table and pointing to +** the entry that needs indexing. +** +** Return a register number which is the first in a block of +** registers that holds the elements of the index key. The +** block of registers has already been deallocated by the time +** this routine returns. +** +** If *piPartIdxLabel is not NULL, fill it in with a label and jump +** to that label if pIdx is a partial index that should be skipped. +** A partial index should be skipped if its WHERE clause evaluates +** to false or null. If pIdx is not a partial index, *piPartIdxLabel +** will be set to zero which is an empty label that is ignored by +** sqlite3VdbeResolveLabel(). +*/ +int sqlite3GenerateIndexKey( + Parse *pParse, /* Parsing context */ + Index *pIdx, /* The index for which to generate a key */ + int iCur, /* Cursor number for the pIdx->pTable table */ + int regOut, /* Write the new index key to this register */ + int doMakeRec, /* Run the OP_MakeRecord instruction if true */ + int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */ +){ + Vdbe *v = pParse->pVdbe; + int j; + Table *pTab = pIdx->pTable; + int regBase; + int nCol; + + if( piPartIdxLabel ){ + if( pIdx->pPartIdxWhere ){ + *piPartIdxLabel = sqlite3VdbeMakeLabel(v); + pParse->iPartIdxTab = iCur; + sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, + SQLITE_JUMPIFNULL); + }else{ + *piPartIdxLabel = 0; + } + } + nCol = pIdx->nColumn; + regBase = sqlite3GetTempRange(pParse, nCol+1); + sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol); + for(j=0; jaiColumn[j]; + if( idx==pTab->iPKey ){ + sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j); + }else{ + sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j); + sqlite3ColumnDefault(v, pTab, idx, -1); + } + } + if( doMakeRec ){ + const char *zAff; + if( pTab->pSelect + || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt) + ){ + zAff = 0; + }else{ + zAff = sqlite3IndexAffinityStr(v, pIdx); + } + sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut); + sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT); + } + sqlite3ReleaseTempRange(pParse, regBase, nCol+1); + return regBase; +} diff --git a/components/external/SQLite-3.8.1/src/expr.c b/components/external/SQLite-3.8.1/src/expr.c new file mode 100644 index 0000000000000000000000000000000000000000..eb2f545639caa1d80818cb357c3ce121a24927db --- /dev/null +++ b/components/external/SQLite-3.8.1/src/expr.c @@ -0,0 +1,4270 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains routines used for analyzing expressions and +** for generating VDBE code that evaluates expressions in SQLite. +*/ +#include "sqliteInt.h" + +/* +** Return the 'affinity' of the expression pExpr if any. +** +** If pExpr is a column, a reference to a column via an 'AS' alias, +** or a sub-select with a column as the return value, then the +** affinity of that column is returned. Otherwise, 0x00 is returned, +** indicating no affinity for the expression. +** +** i.e. the WHERE clause expresssions in the following statements all +** have an affinity: +** +** CREATE TABLE t1(a); +** SELECT * FROM t1 WHERE a; +** SELECT a AS b FROM t1 WHERE b; +** SELECT * FROM t1 WHERE (select a from t1); +*/ +char sqlite3ExprAffinity(Expr *pExpr){ + int op; + pExpr = sqlite3ExprSkipCollate(pExpr); + op = pExpr->op; + if( op==TK_SELECT ){ + assert( pExpr->flags&EP_xIsSelect ); + return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); + } +#ifndef SQLITE_OMIT_CAST + if( op==TK_CAST ){ + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + return sqlite3AffinityType(pExpr->u.zToken, 0); + } +#endif + if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) + && pExpr->pTab!=0 + ){ + /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally + ** a TK_COLUMN but was previously evaluated and cached in a register */ + int j = pExpr->iColumn; + if( j<0 ) return SQLITE_AFF_INTEGER; + assert( pExpr->pTab && jpTab->nCol ); + return pExpr->pTab->aCol[j].affinity; + } + return pExpr->affinity; +} + +/* +** Set the collating sequence for expression pExpr to be the collating +** sequence named by pToken. Return a pointer to a new Expr node that +** implements the COLLATE operator. +** +** If a memory allocation error occurs, that fact is recorded in pParse->db +** and the pExpr parameter is returned unchanged. +*/ +Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){ + if( pCollName->n>0 ){ + Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1); + if( pNew ){ + pNew->pLeft = pExpr; + pNew->flags |= EP_Collate|EP_Skip; + pExpr = pNew; + } + } + return pExpr; +} +Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){ + Token s; + assert( zC!=0 ); + s.z = zC; + s.n = sqlite3Strlen30(s.z); + return sqlite3ExprAddCollateToken(pParse, pExpr, &s); +} + +/* +** Skip over any TK_COLLATE or TK_AS operators and any unlikely() +** or likelihood() function at the root of an expression. +*/ +Expr *sqlite3ExprSkipCollate(Expr *pExpr){ + while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ + if( ExprHasProperty(pExpr, EP_Unlikely) ){ + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + assert( pExpr->x.pList->nExpr>0 ); + assert( pExpr->op==TK_FUNCTION ); + pExpr = pExpr->x.pList->a[0].pExpr; + }else{ + assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS ); + pExpr = pExpr->pLeft; + } + } + return pExpr; +} + +/* +** Return the collation sequence for the expression pExpr. If +** there is no defined collating sequence, return NULL. +** +** The collating sequence might be determined by a COLLATE operator +** or by the presence of a column with a defined collating sequence. +** COLLATE operators take first precedence. Left operands take +** precedence over right operands. +*/ +CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ + sqlite3 *db = pParse->db; + CollSeq *pColl = 0; + Expr *p = pExpr; + while( p ){ + int op = p->op; + if( op==TK_CAST || op==TK_UPLUS ){ + p = p->pLeft; + continue; + } + if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){ + pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); + break; + } + if( p->pTab!=0 + && (op==TK_AGG_COLUMN || op==TK_COLUMN + || op==TK_REGISTER || op==TK_TRIGGER) + ){ + /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally + ** a TK_COLUMN but was previously evaluated and cached in a register */ + int j = p->iColumn; + if( j>=0 ){ + const char *zColl = p->pTab->aCol[j].zColl; + pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); + } + break; + } + if( p->flags & EP_Collate ){ + if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){ + p = p->pLeft; + }else{ + p = p->pRight; + } + }else{ + break; + } + } + if( sqlite3CheckCollSeq(pParse, pColl) ){ + pColl = 0; + } + return pColl; +} + +/* +** pExpr is an operand of a comparison operator. aff2 is the +** type affinity of the other operand. This routine returns the +** type affinity that should be used for the comparison operator. +*/ +char sqlite3CompareAffinity(Expr *pExpr, char aff2){ + char aff1 = sqlite3ExprAffinity(pExpr); + if( aff1 && aff2 ){ + /* Both sides of the comparison are columns. If one has numeric + ** affinity, use that. Otherwise use no affinity. + */ + if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ + return SQLITE_AFF_NUMERIC; + }else{ + return SQLITE_AFF_NONE; + } + }else if( !aff1 && !aff2 ){ + /* Neither side of the comparison is a column. Compare the + ** results directly. + */ + return SQLITE_AFF_NONE; + }else{ + /* One side is a column, the other is not. Use the columns affinity. */ + assert( aff1==0 || aff2==0 ); + return (aff1 + aff2); + } +} + +/* +** pExpr is a comparison operator. Return the type affinity that should +** be applied to both operands prior to doing the comparison. +*/ +static char comparisonAffinity(Expr *pExpr){ + char aff; + assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || + pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || + pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); + assert( pExpr->pLeft ); + aff = sqlite3ExprAffinity(pExpr->pLeft); + if( pExpr->pRight ){ + aff = sqlite3CompareAffinity(pExpr->pRight, aff); + }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); + }else if( !aff ){ + aff = SQLITE_AFF_NONE; + } + return aff; +} + +/* +** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. +** idx_affinity is the affinity of an indexed column. Return true +** if the index with affinity idx_affinity may be used to implement +** the comparison in pExpr. +*/ +int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ + char aff = comparisonAffinity(pExpr); + switch( aff ){ + case SQLITE_AFF_NONE: + return 1; + case SQLITE_AFF_TEXT: + return idx_affinity==SQLITE_AFF_TEXT; + default: + return sqlite3IsNumericAffinity(idx_affinity); + } +} + +/* +** Return the P5 value that should be used for a binary comparison +** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. +*/ +static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ + u8 aff = (char)sqlite3ExprAffinity(pExpr2); + aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; + return aff; +} + +/* +** Return a pointer to the collation sequence that should be used by +** a binary comparison operator comparing pLeft and pRight. +** +** If the left hand expression has a collating sequence type, then it is +** used. Otherwise the collation sequence for the right hand expression +** is used, or the default (BINARY) if neither expression has a collating +** type. +** +** Argument pRight (but not pLeft) may be a null pointer. In this case, +** it is not considered. +*/ +CollSeq *sqlite3BinaryCompareCollSeq( + Parse *pParse, + Expr *pLeft, + Expr *pRight +){ + CollSeq *pColl; + assert( pLeft ); + if( pLeft->flags & EP_Collate ){ + pColl = sqlite3ExprCollSeq(pParse, pLeft); + }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ + pColl = sqlite3ExprCollSeq(pParse, pRight); + }else{ + pColl = sqlite3ExprCollSeq(pParse, pLeft); + if( !pColl ){ + pColl = sqlite3ExprCollSeq(pParse, pRight); + } + } + return pColl; +} + +/* +** Generate code for a comparison operator. +*/ +static int codeCompare( + Parse *pParse, /* The parsing (and code generating) context */ + Expr *pLeft, /* The left operand */ + Expr *pRight, /* The right operand */ + int opcode, /* The comparison opcode */ + int in1, int in2, /* Register holding operands */ + int dest, /* Jump here if true. */ + int jumpIfNull /* If true, jump if either operand is NULL */ +){ + int p5; + int addr; + CollSeq *p4; + + p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); + p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); + addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, + (void*)p4, P4_COLLSEQ); + sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); + return addr; +} + +#if SQLITE_MAX_EXPR_DEPTH>0 +/* +** Check that argument nHeight is less than or equal to the maximum +** expression depth allowed. If it is not, leave an error message in +** pParse. +*/ +int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ + int rc = SQLITE_OK; + int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; + if( nHeight>mxHeight ){ + sqlite3ErrorMsg(pParse, + "Expression tree is too large (maximum depth %d)", mxHeight + ); + rc = SQLITE_ERROR; + } + return rc; +} + +/* The following three functions, heightOfExpr(), heightOfExprList() +** and heightOfSelect(), are used to determine the maximum height +** of any expression tree referenced by the structure passed as the +** first argument. +** +** If this maximum height is greater than the current value pointed +** to by pnHeight, the second parameter, then set *pnHeight to that +** value. +*/ +static void heightOfExpr(Expr *p, int *pnHeight){ + if( p ){ + if( p->nHeight>*pnHeight ){ + *pnHeight = p->nHeight; + } + } +} +static void heightOfExprList(ExprList *p, int *pnHeight){ + if( p ){ + int i; + for(i=0; inExpr; i++){ + heightOfExpr(p->a[i].pExpr, pnHeight); + } + } +} +static void heightOfSelect(Select *p, int *pnHeight){ + if( p ){ + heightOfExpr(p->pWhere, pnHeight); + heightOfExpr(p->pHaving, pnHeight); + heightOfExpr(p->pLimit, pnHeight); + heightOfExpr(p->pOffset, pnHeight); + heightOfExprList(p->pEList, pnHeight); + heightOfExprList(p->pGroupBy, pnHeight); + heightOfExprList(p->pOrderBy, pnHeight); + heightOfSelect(p->pPrior, pnHeight); + } +} + +/* +** Set the Expr.nHeight variable in the structure passed as an +** argument. An expression with no children, Expr.pList or +** Expr.pSelect member has a height of 1. Any other expression +** has a height equal to the maximum height of any other +** referenced Expr plus one. +*/ +static void exprSetHeight(Expr *p){ + int nHeight = 0; + heightOfExpr(p->pLeft, &nHeight); + heightOfExpr(p->pRight, &nHeight); + if( ExprHasProperty(p, EP_xIsSelect) ){ + heightOfSelect(p->x.pSelect, &nHeight); + }else{ + heightOfExprList(p->x.pList, &nHeight); + } + p->nHeight = nHeight + 1; +} + +/* +** Set the Expr.nHeight variable using the exprSetHeight() function. If +** the height is greater than the maximum allowed expression depth, +** leave an error in pParse. +*/ +void sqlite3ExprSetHeight(Parse *pParse, Expr *p){ + exprSetHeight(p); + sqlite3ExprCheckHeight(pParse, p->nHeight); +} + +/* +** Return the maximum height of any expression tree referenced +** by the select statement passed as an argument. +*/ +int sqlite3SelectExprHeight(Select *p){ + int nHeight = 0; + heightOfSelect(p, &nHeight); + return nHeight; +} +#else + #define exprSetHeight(y) +#endif /* SQLITE_MAX_EXPR_DEPTH>0 */ + +/* +** This routine is the core allocator for Expr nodes. +** +** Construct a new expression node and return a pointer to it. Memory +** for this node and for the pToken argument is a single allocation +** obtained from sqlite3DbMalloc(). The calling function +** is responsible for making sure the node eventually gets freed. +** +** If dequote is true, then the token (if it exists) is dequoted. +** If dequote is false, no dequoting is performance. The deQuote +** parameter is ignored if pToken is NULL or if the token does not +** appear to be quoted. If the quotes were of the form "..." (double-quotes) +** then the EP_DblQuoted flag is set on the expression node. +** +** Special case: If op==TK_INTEGER and pToken points to a string that +** can be translated into a 32-bit integer, then the token is not +** stored in u.zToken. Instead, the integer values is written +** into u.iValue and the EP_IntValue flag is set. No extra storage +** is allocated to hold the integer text and the dequote flag is ignored. +*/ +Expr *sqlite3ExprAlloc( + sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ + int op, /* Expression opcode */ + const Token *pToken, /* Token argument. Might be NULL */ + int dequote /* True to dequote */ +){ + Expr *pNew; + int nExtra = 0; + int iValue = 0; + + if( pToken ){ + if( op!=TK_INTEGER || pToken->z==0 + || sqlite3GetInt32(pToken->z, &iValue)==0 ){ + nExtra = pToken->n+1; + assert( iValue>=0 ); + } + } + pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra); + if( pNew ){ + pNew->op = (u8)op; + pNew->iAgg = -1; + if( pToken ){ + if( nExtra==0 ){ + pNew->flags |= EP_IntValue; + pNew->u.iValue = iValue; + }else{ + int c; + pNew->u.zToken = (char*)&pNew[1]; + assert( pToken->z!=0 || pToken->n==0 ); + if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); + pNew->u.zToken[pToken->n] = 0; + if( dequote && nExtra>=3 + && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){ + sqlite3Dequote(pNew->u.zToken); + if( c=='"' ) pNew->flags |= EP_DblQuoted; + } + } + } +#if SQLITE_MAX_EXPR_DEPTH>0 + pNew->nHeight = 1; +#endif + } + return pNew; +} + +/* +** Allocate a new expression node from a zero-terminated token that has +** already been dequoted. +*/ +Expr *sqlite3Expr( + sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ + int op, /* Expression opcode */ + const char *zToken /* Token argument. Might be NULL */ +){ + Token x; + x.z = zToken; + x.n = zToken ? sqlite3Strlen30(zToken) : 0; + return sqlite3ExprAlloc(db, op, &x, 0); +} + +/* +** Attach subtrees pLeft and pRight to the Expr node pRoot. +** +** If pRoot==NULL that means that a memory allocation error has occurred. +** In that case, delete the subtrees pLeft and pRight. +*/ +void sqlite3ExprAttachSubtrees( + sqlite3 *db, + Expr *pRoot, + Expr *pLeft, + Expr *pRight +){ + if( pRoot==0 ){ + assert( db->mallocFailed ); + sqlite3ExprDelete(db, pLeft); + sqlite3ExprDelete(db, pRight); + }else{ + if( pRight ){ + pRoot->pRight = pRight; + pRoot->flags |= EP_Collate & pRight->flags; + } + if( pLeft ){ + pRoot->pLeft = pLeft; + pRoot->flags |= EP_Collate & pLeft->flags; + } + exprSetHeight(pRoot); + } +} + +/* +** Allocate a Expr node which joins as many as two subtrees. +** +** One or both of the subtrees can be NULL. Return a pointer to the new +** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, +** free the subtrees and return NULL. +*/ +Expr *sqlite3PExpr( + Parse *pParse, /* Parsing context */ + int op, /* Expression opcode */ + Expr *pLeft, /* Left operand */ + Expr *pRight, /* Right operand */ + const Token *pToken /* Argument token */ +){ + Expr *p; + if( op==TK_AND && pLeft && pRight ){ + /* Take advantage of short-circuit false optimization for AND */ + p = sqlite3ExprAnd(pParse->db, pLeft, pRight); + }else{ + p = sqlite3ExprAlloc(pParse->db, op, pToken, 1); + sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); + } + if( p ) { + sqlite3ExprCheckHeight(pParse, p->nHeight); + } + return p; +} + +/* +** Return 1 if an expression must be FALSE in all cases and 0 if the +** expression might be true. This is an optimization. If is OK to +** return 0 here even if the expression really is always false (a +** false negative). But it is a bug to return 1 if the expression +** might be true in some rare circumstances (a false positive.) +** +** Note that if the expression is part of conditional for a +** LEFT JOIN, then we cannot determine at compile-time whether or not +** is it true or false, so always return 0. +*/ +static int exprAlwaysFalse(Expr *p){ + int v = 0; + if( ExprHasProperty(p, EP_FromJoin) ) return 0; + if( !sqlite3ExprIsInteger(p, &v) ) return 0; + return v==0; +} + +/* +** Join two expressions using an AND operator. If either expression is +** NULL, then just return the other expression. +** +** If one side or the other of the AND is known to be false, then instead +** of returning an AND expression, just return a constant expression with +** a value of false. +*/ +Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){ + if( pLeft==0 ){ + return pRight; + }else if( pRight==0 ){ + return pLeft; + }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){ + sqlite3ExprDelete(db, pLeft); + sqlite3ExprDelete(db, pRight); + return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0); + }else{ + Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0); + sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight); + return pNew; + } +} + +/* +** Construct a new expression node for a function with multiple +** arguments. +*/ +Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){ + Expr *pNew; + sqlite3 *db = pParse->db; + assert( pToken ); + pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); + if( pNew==0 ){ + sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ + return 0; + } + pNew->x.pList = pList; + assert( !ExprHasProperty(pNew, EP_xIsSelect) ); + sqlite3ExprSetHeight(pParse, pNew); + return pNew; +} + +/* +** Assign a variable number to an expression that encodes a wildcard +** in the original SQL statement. +** +** Wildcards consisting of a single "?" are assigned the next sequential +** variable number. +** +** Wildcards of the form "?nnn" are assigned the number "nnn". We make +** sure "nnn" is not too be to avoid a denial of service attack when +** the SQL statement comes from an external source. +** +** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number +** as the previous instance of the same wildcard. Or if this is the first +** instance of the wildcard, the next sequenial variable number is +** assigned. +*/ +void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){ + sqlite3 *db = pParse->db; + const char *z; + + if( pExpr==0 ) return; + assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); + z = pExpr->u.zToken; + assert( z!=0 ); + assert( z[0]!=0 ); + if( z[1]==0 ){ + /* Wildcard of the form "?". Assign the next variable number */ + assert( z[0]=='?' ); + pExpr->iColumn = (ynVar)(++pParse->nVar); + }else{ + ynVar x = 0; + u32 n = sqlite3Strlen30(z); + if( z[0]=='?' ){ + /* Wildcard of the form "?nnn". Convert "nnn" to an integer and + ** use it as the variable number */ + i64 i; + int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); + pExpr->iColumn = x = (ynVar)i; + testcase( i==0 ); + testcase( i==1 ); + testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); + testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); + if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ + sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", + db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); + x = 0; + } + if( i>pParse->nVar ){ + pParse->nVar = (int)i; + } + }else{ + /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable + ** number as the prior appearance of the same name, or if the name + ** has never appeared before, reuse the same variable number + */ + ynVar i; + for(i=0; inzVar; i++){ + if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){ + pExpr->iColumn = x = (ynVar)i+1; + break; + } + } + if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar); + } + if( x>0 ){ + if( x>pParse->nzVar ){ + char **a; + a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0])); + if( a==0 ) return; /* Error reported through db->mallocFailed */ + pParse->azVar = a; + memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0])); + pParse->nzVar = x; + } + if( z[0]!='?' || pParse->azVar[x-1]==0 ){ + sqlite3DbFree(db, pParse->azVar[x-1]); + pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n); + } + } + } + if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ + sqlite3ErrorMsg(pParse, "too many SQL variables"); + } +} + +/* +** Recursively delete an expression tree. +*/ +void sqlite3ExprDelete(sqlite3 *db, Expr *p){ + if( p==0 ) return; + /* Sanity check: Assert that the IntValue is non-negative if it exists */ + assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 ); + if( !ExprHasProperty(p, EP_TokenOnly) ){ + /* The Expr.x union is never used at the same time as Expr.pRight */ + assert( p->x.pList==0 || p->pRight==0 ); + sqlite3ExprDelete(db, p->pLeft); + sqlite3ExprDelete(db, p->pRight); + if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken); + if( ExprHasProperty(p, EP_xIsSelect) ){ + sqlite3SelectDelete(db, p->x.pSelect); + }else{ + sqlite3ExprListDelete(db, p->x.pList); + } + } + if( !ExprHasProperty(p, EP_Static) ){ + sqlite3DbFree(db, p); + } +} + +/* +** Return the number of bytes allocated for the expression structure +** passed as the first argument. This is always one of EXPR_FULLSIZE, +** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. +*/ +static int exprStructSize(Expr *p){ + if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; + if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; + return EXPR_FULLSIZE; +} + +/* +** The dupedExpr*Size() routines each return the number of bytes required +** to store a copy of an expression or expression tree. They differ in +** how much of the tree is measured. +** +** dupedExprStructSize() Size of only the Expr structure +** dupedExprNodeSize() Size of Expr + space for token +** dupedExprSize() Expr + token + subtree components +** +*************************************************************************** +** +** The dupedExprStructSize() function returns two values OR-ed together: +** (1) the space required for a copy of the Expr structure only and +** (2) the EP_xxx flags that indicate what the structure size should be. +** The return values is always one of: +** +** EXPR_FULLSIZE +** EXPR_REDUCEDSIZE | EP_Reduced +** EXPR_TOKENONLYSIZE | EP_TokenOnly +** +** The size of the structure can be found by masking the return value +** of this routine with 0xfff. The flags can be found by masking the +** return value with EP_Reduced|EP_TokenOnly. +** +** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size +** (unreduced) Expr objects as they or originally constructed by the parser. +** During expression analysis, extra information is computed and moved into +** later parts of teh Expr object and that extra information might get chopped +** off if the expression is reduced. Note also that it does not work to +** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal +** to reduce a pristine expression tree from the parser. The implementation +** of dupedExprStructSize() contain multiple assert() statements that attempt +** to enforce this constraint. +*/ +static int dupedExprStructSize(Expr *p, int flags){ + int nSize; + assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ + assert( EXPR_FULLSIZE<=0xfff ); + assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); + if( 0==(flags&EXPRDUP_REDUCE) ){ + nSize = EXPR_FULLSIZE; + }else{ + assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); + assert( !ExprHasProperty(p, EP_FromJoin) ); + assert( !ExprHasProperty(p, EP_MemToken) ); + assert( !ExprHasProperty(p, EP_NoReduce) ); + if( p->pLeft || p->x.pList ){ + nSize = EXPR_REDUCEDSIZE | EP_Reduced; + }else{ + assert( p->pRight==0 ); + nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; + } + } + return nSize; +} + +/* +** This function returns the space in bytes required to store the copy +** of the Expr structure and a copy of the Expr.u.zToken string (if that +** string is defined.) +*/ +static int dupedExprNodeSize(Expr *p, int flags){ + int nByte = dupedExprStructSize(p, flags) & 0xfff; + if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ + nByte += sqlite3Strlen30(p->u.zToken)+1; + } + return ROUND8(nByte); +} + +/* +** Return the number of bytes required to create a duplicate of the +** expression passed as the first argument. The second argument is a +** mask containing EXPRDUP_XXX flags. +** +** The value returned includes space to create a copy of the Expr struct +** itself and the buffer referred to by Expr.u.zToken, if any. +** +** If the EXPRDUP_REDUCE flag is set, then the return value includes +** space to duplicate all Expr nodes in the tree formed by Expr.pLeft +** and Expr.pRight variables (but not for any structures pointed to or +** descended from the Expr.x.pList or Expr.x.pSelect variables). +*/ +static int dupedExprSize(Expr *p, int flags){ + int nByte = 0; + if( p ){ + nByte = dupedExprNodeSize(p, flags); + if( flags&EXPRDUP_REDUCE ){ + nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags); + } + } + return nByte; +} + +/* +** This function is similar to sqlite3ExprDup(), except that if pzBuffer +** is not NULL then *pzBuffer is assumed to point to a buffer large enough +** to store the copy of expression p, the copies of p->u.zToken +** (if applicable), and the copies of the p->pLeft and p->pRight expressions, +** if any. Before returning, *pzBuffer is set to the first byte passed the +** portion of the buffer copied into by this function. +*/ +static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){ + Expr *pNew = 0; /* Value to return */ + if( p ){ + const int isReduced = (flags&EXPRDUP_REDUCE); + u8 *zAlloc; + u32 staticFlag = 0; + + assert( pzBuffer==0 || isReduced ); + + /* Figure out where to write the new Expr structure. */ + if( pzBuffer ){ + zAlloc = *pzBuffer; + staticFlag = EP_Static; + }else{ + zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags)); + } + pNew = (Expr *)zAlloc; + + if( pNew ){ + /* Set nNewSize to the size allocated for the structure pointed to + ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or + ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed + ** by the copy of the p->u.zToken string (if any). + */ + const unsigned nStructSize = dupedExprStructSize(p, flags); + const int nNewSize = nStructSize & 0xfff; + int nToken; + if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ + nToken = sqlite3Strlen30(p->u.zToken) + 1; + }else{ + nToken = 0; + } + if( isReduced ){ + assert( ExprHasProperty(p, EP_Reduced)==0 ); + memcpy(zAlloc, p, nNewSize); + }else{ + int nSize = exprStructSize(p); + memcpy(zAlloc, p, nSize); + memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize); + } + + /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */ + pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken); + pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); + pNew->flags |= staticFlag; + + /* Copy the p->u.zToken string, if any. */ + if( nToken ){ + char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize]; + memcpy(zToken, p->u.zToken, nToken); + } + + if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){ + /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ + if( ExprHasProperty(p, EP_xIsSelect) ){ + pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced); + }else{ + pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced); + } + } + + /* Fill in pNew->pLeft and pNew->pRight. */ + if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){ + zAlloc += dupedExprNodeSize(p, flags); + if( ExprHasProperty(pNew, EP_Reduced) ){ + pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc); + pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc); + } + if( pzBuffer ){ + *pzBuffer = zAlloc; + } + }else{ + if( !ExprHasProperty(p, EP_TokenOnly) ){ + pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); + pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); + } + } + + } + } + return pNew; +} + +/* +** The following group of routines make deep copies of expressions, +** expression lists, ID lists, and select statements. The copies can +** be deleted (by being passed to their respective ...Delete() routines) +** without effecting the originals. +** +** The expression list, ID, and source lists return by sqlite3ExprListDup(), +** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded +** by subsequent calls to sqlite*ListAppend() routines. +** +** Any tables that the SrcList might point to are not duplicated. +** +** The flags parameter contains a combination of the EXPRDUP_XXX flags. +** If the EXPRDUP_REDUCE flag is set, then the structure returned is a +** truncated version of the usual Expr structure that will be stored as +** part of the in-memory representation of the database schema. +*/ +Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){ + return exprDup(db, p, flags, 0); +} +ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){ + ExprList *pNew; + struct ExprList_item *pItem, *pOldItem; + int i; + if( p==0 ) return 0; + pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) ); + if( pNew==0 ) return 0; + pNew->iECursor = 0; + pNew->nExpr = i = p->nExpr; + if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; inExpr; i+=i){} + pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) ); + if( pItem==0 ){ + sqlite3DbFree(db, pNew); + return 0; + } + pOldItem = p->a; + for(i=0; inExpr; i++, pItem++, pOldItem++){ + Expr *pOldExpr = pOldItem->pExpr; + pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); + pItem->zName = sqlite3DbStrDup(db, pOldItem->zName); + pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan); + pItem->sortOrder = pOldItem->sortOrder; + pItem->done = 0; + pItem->bSpanIsTab = pOldItem->bSpanIsTab; + pItem->iOrderByCol = pOldItem->iOrderByCol; + pItem->iAlias = pOldItem->iAlias; + } + return pNew; +} + +/* +** If cursors, triggers, views and subqueries are all omitted from +** the build, then none of the following routines, except for +** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes +** called with a NULL argument. +*/ +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ + || !defined(SQLITE_OMIT_SUBQUERY) +SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ + SrcList *pNew; + int i; + int nByte; + if( p==0 ) return 0; + nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); + pNew = sqlite3DbMallocRaw(db, nByte ); + if( pNew==0 ) return 0; + pNew->nSrc = pNew->nAlloc = p->nSrc; + for(i=0; inSrc; i++){ + struct SrcList_item *pNewItem = &pNew->a[i]; + struct SrcList_item *pOldItem = &p->a[i]; + Table *pTab; + pNewItem->pSchema = pOldItem->pSchema; + pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); + pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); + pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); + pNewItem->jointype = pOldItem->jointype; + pNewItem->iCursor = pOldItem->iCursor; + pNewItem->addrFillSub = pOldItem->addrFillSub; + pNewItem->regReturn = pOldItem->regReturn; + pNewItem->isCorrelated = pOldItem->isCorrelated; + pNewItem->viaCoroutine = pOldItem->viaCoroutine; + pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex); + pNewItem->notIndexed = pOldItem->notIndexed; + pNewItem->pIndex = pOldItem->pIndex; + pTab = pNewItem->pTab = pOldItem->pTab; + if( pTab ){ + pTab->nRef++; + } + pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); + pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags); + pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); + pNewItem->colUsed = pOldItem->colUsed; + } + return pNew; +} +IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ + IdList *pNew; + int i; + if( p==0 ) return 0; + pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) ); + if( pNew==0 ) return 0; + pNew->nId = p->nId; + pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) ); + if( pNew->a==0 ){ + sqlite3DbFree(db, pNew); + return 0; + } + /* Note that because the size of the allocation for p->a[] is not + ** necessarily a power of two, sqlite3IdListAppend() may not be called + ** on the duplicate created by this function. */ + for(i=0; inId; i++){ + struct IdList_item *pNewItem = &pNew->a[i]; + struct IdList_item *pOldItem = &p->a[i]; + pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); + pNewItem->idx = pOldItem->idx; + } + return pNew; +} +Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ + Select *pNew, *pPrior; + if( p==0 ) return 0; + pNew = sqlite3DbMallocRaw(db, sizeof(*p) ); + if( pNew==0 ) return 0; + pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); + pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); + pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); + pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); + pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); + pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); + pNew->op = p->op; + pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags); + if( pPrior ) pPrior->pNext = pNew; + pNew->pNext = 0; + pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); + pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags); + pNew->iLimit = 0; + pNew->iOffset = 0; + pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; + pNew->pRightmost = 0; + pNew->addrOpenEphm[0] = -1; + pNew->addrOpenEphm[1] = -1; + pNew->addrOpenEphm[2] = -1; + return pNew; +} +#else +Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ + assert( p==0 ); + return 0; +} +#endif + + +/* +** Add a new element to the end of an expression list. If pList is +** initially NULL, then create a new expression list. +** +** If a memory allocation error occurs, the entire list is freed and +** NULL is returned. If non-NULL is returned, then it is guaranteed +** that the new entry was successfully appended. +*/ +ExprList *sqlite3ExprListAppend( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* List to which to append. Might be NULL */ + Expr *pExpr /* Expression to be appended. Might be NULL */ +){ + sqlite3 *db = pParse->db; + if( pList==0 ){ + pList = sqlite3DbMallocZero(db, sizeof(ExprList) ); + if( pList==0 ){ + goto no_mem; + } + pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0])); + if( pList->a==0 ) goto no_mem; + }else if( (pList->nExpr & (pList->nExpr-1))==0 ){ + struct ExprList_item *a; + assert( pList->nExpr>0 ); + a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0])); + if( a==0 ){ + goto no_mem; + } + pList->a = a; + } + assert( pList->a!=0 ); + if( 1 ){ + struct ExprList_item *pItem = &pList->a[pList->nExpr++]; + memset(pItem, 0, sizeof(*pItem)); + pItem->pExpr = pExpr; + } + return pList; + +no_mem: + /* Avoid leaking memory if malloc has failed. */ + sqlite3ExprDelete(db, pExpr); + sqlite3ExprListDelete(db, pList); + return 0; +} + +/* +** Set the ExprList.a[].zName element of the most recently added item +** on the expression list. +** +** pList might be NULL following an OOM error. But pName should never be +** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag +** is set. +*/ +void sqlite3ExprListSetName( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* List to which to add the span. */ + Token *pName, /* Name to be added */ + int dequote /* True to cause the name to be dequoted */ +){ + assert( pList!=0 || pParse->db->mallocFailed!=0 ); + if( pList ){ + struct ExprList_item *pItem; + assert( pList->nExpr>0 ); + pItem = &pList->a[pList->nExpr-1]; + assert( pItem->zName==0 ); + pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); + if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName); + } +} + +/* +** Set the ExprList.a[].zSpan element of the most recently added item +** on the expression list. +** +** pList might be NULL following an OOM error. But pSpan should never be +** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag +** is set. +*/ +void sqlite3ExprListSetSpan( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* List to which to add the span. */ + ExprSpan *pSpan /* The span to be added */ +){ + sqlite3 *db = pParse->db; + assert( pList!=0 || db->mallocFailed!=0 ); + if( pList ){ + struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; + assert( pList->nExpr>0 ); + assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr ); + sqlite3DbFree(db, pItem->zSpan); + pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart, + (int)(pSpan->zEnd - pSpan->zStart)); + } +} + +/* +** If the expression list pEList contains more than iLimit elements, +** leave an error message in pParse. +*/ +void sqlite3ExprListCheckLength( + Parse *pParse, + ExprList *pEList, + const char *zObject +){ + int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; + testcase( pEList && pEList->nExpr==mx ); + testcase( pEList && pEList->nExpr==mx+1 ); + if( pEList && pEList->nExpr>mx ){ + sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); + } +} + +/* +** Delete an entire expression list. +*/ +void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ + int i; + struct ExprList_item *pItem; + if( pList==0 ) return; + assert( pList->a!=0 || pList->nExpr==0 ); + for(pItem=pList->a, i=0; inExpr; i++, pItem++){ + sqlite3ExprDelete(db, pItem->pExpr); + sqlite3DbFree(db, pItem->zName); + sqlite3DbFree(db, pItem->zSpan); + } + sqlite3DbFree(db, pList->a); + sqlite3DbFree(db, pList); +} + +/* +** These routines are Walker callbacks. Walker.u.pi is a pointer +** to an integer. These routines are checking an expression to see +** if it is a constant. Set *Walker.u.pi to 0 if the expression is +** not constant. +** +** These callback routines are used to implement the following: +** +** sqlite3ExprIsConstant() +** sqlite3ExprIsConstantNotJoin() +** sqlite3ExprIsConstantOrFunction() +** +*/ +static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ + + /* If pWalker->u.i is 3 then any term of the expression that comes from + ** the ON or USING clauses of a join disqualifies the expression + ** from being considered constant. */ + if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){ + pWalker->u.i = 0; + return WRC_Abort; + } + + switch( pExpr->op ){ + /* Consider functions to be constant if all their arguments are constant + ** and pWalker->u.i==2 */ + case TK_FUNCTION: + if( pWalker->u.i==2 ) return 0; + /* Fall through */ + case TK_ID: + case TK_COLUMN: + case TK_AGG_FUNCTION: + case TK_AGG_COLUMN: + testcase( pExpr->op==TK_ID ); + testcase( pExpr->op==TK_COLUMN ); + testcase( pExpr->op==TK_AGG_FUNCTION ); + testcase( pExpr->op==TK_AGG_COLUMN ); + pWalker->u.i = 0; + return WRC_Abort; + default: + testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */ + testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */ + return WRC_Continue; + } +} +static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){ + UNUSED_PARAMETER(NotUsed); + pWalker->u.i = 0; + return WRC_Abort; +} +static int exprIsConst(Expr *p, int initFlag){ + Walker w; + memset(&w, 0, sizeof(w)); + w.u.i = initFlag; + w.xExprCallback = exprNodeIsConstant; + w.xSelectCallback = selectNodeIsConstant; + sqlite3WalkExpr(&w, p); + return w.u.i; +} + +/* +** Walk an expression tree. Return 1 if the expression is constant +** and 0 if it involves variables or function calls. +** +** For the purposes of this function, a double-quoted string (ex: "abc") +** is considered a variable but a single-quoted string (ex: 'abc') is +** a constant. +*/ +int sqlite3ExprIsConstant(Expr *p){ + return exprIsConst(p, 1); +} + +/* +** Walk an expression tree. Return 1 if the expression is constant +** that does no originate from the ON or USING clauses of a join. +** Return 0 if it involves variables or function calls or terms from +** an ON or USING clause. +*/ +int sqlite3ExprIsConstantNotJoin(Expr *p){ + return exprIsConst(p, 3); +} + +/* +** Walk an expression tree. Return 1 if the expression is constant +** or a function call with constant arguments. Return and 0 if there +** are any variables. +** +** For the purposes of this function, a double-quoted string (ex: "abc") +** is considered a variable but a single-quoted string (ex: 'abc') is +** a constant. +*/ +int sqlite3ExprIsConstantOrFunction(Expr *p){ + return exprIsConst(p, 2); +} + +/* +** If the expression p codes a constant integer that is small enough +** to fit in a 32-bit integer, return 1 and put the value of the integer +** in *pValue. If the expression is not an integer or if it is too big +** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. +*/ +int sqlite3ExprIsInteger(Expr *p, int *pValue){ + int rc = 0; + + /* If an expression is an integer literal that fits in a signed 32-bit + ** integer, then the EP_IntValue flag will have already been set */ + assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 + || sqlite3GetInt32(p->u.zToken, &rc)==0 ); + + if( p->flags & EP_IntValue ){ + *pValue = p->u.iValue; + return 1; + } + switch( p->op ){ + case TK_UPLUS: { + rc = sqlite3ExprIsInteger(p->pLeft, pValue); + break; + } + case TK_UMINUS: { + int v; + if( sqlite3ExprIsInteger(p->pLeft, &v) ){ + assert( v!=(-2147483647-1) ); + *pValue = -v; + rc = 1; + } + break; + } + default: break; + } + return rc; +} + +/* +** Return FALSE if there is no chance that the expression can be NULL. +** +** If the expression might be NULL or if the expression is too complex +** to tell return TRUE. +** +** This routine is used as an optimization, to skip OP_IsNull opcodes +** when we know that a value cannot be NULL. Hence, a false positive +** (returning TRUE when in fact the expression can never be NULL) might +** be a small performance hit but is otherwise harmless. On the other +** hand, a false negative (returning FALSE when the result could be NULL) +** will likely result in an incorrect answer. So when in doubt, return +** TRUE. +*/ +int sqlite3ExprCanBeNull(const Expr *p){ + u8 op; + while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } + op = p->op; + if( op==TK_REGISTER ) op = p->op2; + switch( op ){ + case TK_INTEGER: + case TK_STRING: + case TK_FLOAT: + case TK_BLOB: + return 0; + default: + return 1; + } +} + +/* +** Generate an OP_IsNull instruction that tests register iReg and jumps +** to location iDest if the value in iReg is NULL. The value in iReg +** was computed by pExpr. If we can look at pExpr at compile-time and +** determine that it can never generate a NULL, then the OP_IsNull operation +** can be omitted. +*/ +void sqlite3ExprCodeIsNullJump( + Vdbe *v, /* The VDBE under construction */ + const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */ + int iReg, /* Test the value in this register for NULL */ + int iDest /* Jump here if the value is null */ +){ + if( sqlite3ExprCanBeNull(pExpr) ){ + sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest); + } +} + +/* +** Return TRUE if the given expression is a constant which would be +** unchanged by OP_Affinity with the affinity given in the second +** argument. +** +** This routine is used to determine if the OP_Affinity operation +** can be omitted. When in doubt return FALSE. A false negative +** is harmless. A false positive, however, can result in the wrong +** answer. +*/ +int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ + u8 op; + if( aff==SQLITE_AFF_NONE ) return 1; + while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } + op = p->op; + if( op==TK_REGISTER ) op = p->op2; + switch( op ){ + case TK_INTEGER: { + return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC; + } + case TK_FLOAT: { + return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC; + } + case TK_STRING: { + return aff==SQLITE_AFF_TEXT; + } + case TK_BLOB: { + return 1; + } + case TK_COLUMN: { + assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ + return p->iColumn<0 + && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC); + } + default: { + return 0; + } + } +} + +/* +** Return TRUE if the given string is a row-id column name. +*/ +int sqlite3IsRowid(const char *z){ + if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; + if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; + if( sqlite3StrICmp(z, "OID")==0 ) return 1; + return 0; +} + +/* +** Return true if we are able to the IN operator optimization on a +** query of the form +** +** x IN (SELECT ...) +** +** Where the SELECT... clause is as specified by the parameter to this +** routine. +** +** The Select object passed in has already been preprocessed and no +** errors have been found. +*/ +#ifndef SQLITE_OMIT_SUBQUERY +static int isCandidateForInOpt(Select *p){ + SrcList *pSrc; + ExprList *pEList; + Table *pTab; + if( p==0 ) return 0; /* right-hand side of IN is SELECT */ + if( p->pPrior ) return 0; /* Not a compound SELECT */ + if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ + testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); + testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); + return 0; /* No DISTINCT keyword and no aggregate functions */ + } + assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ + if( p->pLimit ) return 0; /* Has no LIMIT clause */ + assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */ + if( p->pWhere ) return 0; /* Has no WHERE clause */ + pSrc = p->pSrc; + assert( pSrc!=0 ); + if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ + if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */ + pTab = pSrc->a[0].pTab; + if( NEVER(pTab==0) ) return 0; + assert( pTab->pSelect==0 ); /* FROM clause is not a view */ + if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ + pEList = p->pEList; + if( pEList->nExpr!=1 ) return 0; /* One column in the result set */ + if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */ + return 1; +} +#endif /* SQLITE_OMIT_SUBQUERY */ + +/* +** Code an OP_Once instruction and allocate space for its flag. Return the +** address of the new instruction. +*/ +int sqlite3CodeOnce(Parse *pParse){ + Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ + return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++); +} + +/* +** This function is used by the implementation of the IN (...) operator. +** The pX parameter is the expression on the RHS of the IN operator, which +** might be either a list of expressions or a subquery. +** +** The job of this routine is to find or create a b-tree object that can +** be used either to test for membership in the RHS set or to iterate through +** all members of the RHS set, skipping duplicates. +** +** A cursor is opened on the b-tree object that the RHS of the IN operator +** and pX->iTable is set to the index of that cursor. +** +** The returned value of this function indicates the b-tree type, as follows: +** +** IN_INDEX_ROWID - The cursor was opened on a database table. +** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index. +** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index. +** IN_INDEX_EPH - The cursor was opened on a specially created and +** populated epheremal table. +** +** An existing b-tree might be used if the RHS expression pX is a simple +** subquery such as: +** +** SELECT FROM
+** +** If the RHS of the IN operator is a list or a more complex subquery, then +** an ephemeral table might need to be generated from the RHS and then +** pX->iTable made to point to the ephermeral table instead of an +** existing table. +** +** If the prNotFound parameter is 0, then the b-tree will be used to iterate +** through the set members, skipping any duplicates. In this case an +** epheremal table must be used unless the selected is guaranteed +** to be unique - either because it is an INTEGER PRIMARY KEY or it +** has a UNIQUE constraint or UNIQUE index. +** +** If the prNotFound parameter is not 0, then the b-tree will be used +** for fast set membership tests. In this case an epheremal table must +** be used unless is an INTEGER PRIMARY KEY or an index can +** be found with as its left-most column. +** +** When the b-tree is being used for membership tests, the calling function +** needs to know whether or not the structure contains an SQL NULL +** value in order to correctly evaluate expressions like "X IN (Y, Z)". +** If there is any chance that the (...) might contain a NULL value at +** runtime, then a register is allocated and the register number written +** to *prNotFound. If there is no chance that the (...) contains a +** NULL value, then *prNotFound is left unchanged. +** +** If a register is allocated and its location stored in *prNotFound, then +** its initial value is NULL. If the (...) does not remain constant +** for the duration of the query (i.e. the SELECT within the (...) +** is a correlated subquery) then the value of the allocated register is +** reset to NULL each time the subquery is rerun. This allows the +** caller to use vdbe code equivalent to the following: +** +** if( register==NULL ){ +** has_null = +** register = 1 +** } +** +** in order to avoid running the +** test more often than is necessary. +*/ +#ifndef SQLITE_OMIT_SUBQUERY +int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ + Select *p; /* SELECT to the right of IN operator */ + int eType = 0; /* Type of RHS table. IN_INDEX_* */ + int iTab = pParse->nTab++; /* Cursor of the RHS table */ + int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */ + Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ + + assert( pX->op==TK_IN ); + + /* Check to see if an existing table or index can be used to + ** satisfy the query. This is preferable to generating a new + ** ephemeral table. + */ + p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0); + if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){ + sqlite3 *db = pParse->db; /* Database connection */ + Table *pTab; /* Table
. */ + Expr *pExpr; /* Expression */ + int iCol; /* Index of column */ + int iDb; /* Database idx for pTab */ + + assert( p ); /* Because of isCandidateForInOpt(p) */ + assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ + assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */ + assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ + pTab = p->pSrc->a[0].pTab; + pExpr = p->pEList->a[0].pExpr; + iCol = pExpr->iColumn; + + /* Code an OP_VerifyCookie and OP_TableLock for
. */ + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + + /* This function is only called from two places. In both cases the vdbe + ** has already been allocated. So assume sqlite3GetVdbe() is always + ** successful here. + */ + assert(v); + if( iCol<0 ){ + int iAddr; + + iAddr = sqlite3CodeOnce(pParse); + + sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); + eType = IN_INDEX_ROWID; + + sqlite3VdbeJumpHere(v, iAddr); + }else{ + Index *pIdx; /* Iterator variable */ + + /* The collation sequence used by the comparison. If an index is to + ** be used in place of a temp-table, it must be ordered according + ** to this collation sequence. */ + CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr); + + /* Check that the affinity that will be used to perform the + ** comparison is the same as the affinity of the column. If + ** it is not, it is not possible to use any index. + */ + int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity); + + for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){ + if( (pIdx->aiColumn[0]==iCol) + && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq + && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None)) + ){ + int iAddr; + char *pKey; + + pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx); + iAddr = sqlite3CodeOnce(pParse); + + sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb, + pKey,P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIdx->zName)); + assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); + eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; + + sqlite3VdbeJumpHere(v, iAddr); + if( prNotFound && !pTab->aCol[iCol].notNull ){ + *prNotFound = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound); + } + } + } + } + } + + if( eType==0 ){ + /* Could not found an existing table or index to use as the RHS b-tree. + ** We will have to generate an ephemeral table to do the job. + */ + u32 savedNQueryLoop = pParse->nQueryLoop; + int rMayHaveNull = 0; + eType = IN_INDEX_EPH; + if( prNotFound ){ + *prNotFound = rMayHaveNull = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound); + }else{ + testcase( pParse->nQueryLoop>0 ); + pParse->nQueryLoop = 0; + if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){ + eType = IN_INDEX_ROWID; + } + } + sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID); + pParse->nQueryLoop = savedNQueryLoop; + }else{ + pX->iTable = iTab; + } + return eType; +} +#endif + +/* +** Generate code for scalar subqueries used as a subquery expression, EXISTS, +** or IN operators. Examples: +** +** (SELECT a FROM b) -- subquery +** EXISTS (SELECT a FROM b) -- EXISTS subquery +** x IN (4,5,11) -- IN operator with list on right-hand side +** x IN (SELECT a FROM b) -- IN operator with subquery on the right +** +** The pExpr parameter describes the expression that contains the IN +** operator or subquery. +** +** If parameter isRowid is non-zero, then expression pExpr is guaranteed +** to be of the form " IN (?, ?, ?)", where is a reference +** to some integer key column of a table B-Tree. In this case, use an +** intkey B-Tree to store the set of IN(...) values instead of the usual +** (slower) variable length keys B-Tree. +** +** If rMayHaveNull is non-zero, that means that the operation is an IN +** (not a SELECT or EXISTS) and that the RHS might contains NULLs. +** Furthermore, the IN is in a WHERE clause and that we really want +** to iterate over the RHS of the IN operator in order to quickly locate +** all corresponding LHS elements. All this routine does is initialize +** the register given by rMayHaveNull to NULL. Calling routines will take +** care of changing this register value to non-NULL if the RHS is NULL-free. +** +** If rMayHaveNull is zero, that means that the subquery is being used +** for membership testing only. There is no need to initialize any +** registers to indicate the presence or absence of NULLs on the RHS. +** +** For a SELECT or EXISTS operator, return the register that holds the +** result. For IN operators or if an error occurs, the return value is 0. +*/ +#ifndef SQLITE_OMIT_SUBQUERY +int sqlite3CodeSubselect( + Parse *pParse, /* Parsing context */ + Expr *pExpr, /* The IN, SELECT, or EXISTS operator */ + int rMayHaveNull, /* Register that records whether NULLs exist in RHS */ + int isRowid /* If true, LHS of IN operator is a rowid */ +){ + int testAddr = -1; /* One-time test address */ + int rReg = 0; /* Register storing resulting */ + Vdbe *v = sqlite3GetVdbe(pParse); + if( NEVER(v==0) ) return 0; + sqlite3ExprCachePush(pParse); + + /* This code must be run in its entirety every time it is encountered + ** if any of the following is true: + ** + ** * The right-hand side is a correlated subquery + ** * The right-hand side is an expression list containing variables + ** * We are inside a trigger + ** + ** If all of the above are false, then we can run this code just once + ** save the results, and reuse the same result on subsequent invocations. + */ + if( !ExprHasProperty(pExpr, EP_VarSelect) ){ + testAddr = sqlite3CodeOnce(pParse); + } + +#ifndef SQLITE_OMIT_EXPLAIN + if( pParse->explain==2 ){ + char *zMsg = sqlite3MPrintf( + pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ", + pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId + ); + sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); + } +#endif + + switch( pExpr->op ){ + case TK_IN: { + char affinity; /* Affinity of the LHS of the IN */ + int addr; /* Address of OP_OpenEphemeral instruction */ + Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */ + KeyInfo *pKeyInfo = 0; /* Key information */ + + if( rMayHaveNull ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull); + } + + affinity = sqlite3ExprAffinity(pLeft); + + /* Whether this is an 'x IN(SELECT...)' or an 'x IN()' + ** expression it is handled the same way. An ephemeral table is + ** filled with single-field index keys representing the results + ** from the SELECT or the . + ** + ** If the 'x' expression is a column value, or the SELECT... + ** statement returns a column value, then the affinity of that + ** column is used to build the index keys. If both 'x' and the + ** SELECT... statement are columns, then numeric affinity is used + ** if either column has NUMERIC or INTEGER affinity. If neither + ** 'x' nor the SELECT... statement are columns, then numeric affinity + ** is used. + */ + pExpr->iTable = pParse->nTab++; + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid); + if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED); + pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1); + + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + /* Case 1: expr IN (SELECT ...) + ** + ** Generate code to write the results of the select into the temporary + ** table allocated and opened above. + */ + SelectDest dest; + ExprList *pEList; + + assert( !isRowid ); + sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable); + dest.affSdst = (u8)affinity; + assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable ); + pExpr->x.pSelect->iLimit = 0; + testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ + if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){ + sqlite3DbFree(pParse->db, pKeyInfo); + return 0; + } + pEList = pExpr->x.pSelect->pEList; + assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ + assert( pEList!=0 ); + assert( pEList->nExpr>0 ); + pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, + pEList->a[0].pExpr); + }else if( ALWAYS(pExpr->x.pList!=0) ){ + /* Case 2: expr IN (exprlist) + ** + ** For each expression, build an index key from the evaluation and + ** store it in the temporary table. If is a column, then use + ** that columns affinity when building index keys. If is not + ** a column, use numeric affinity. + */ + int i; + ExprList *pList = pExpr->x.pList; + struct ExprList_item *pItem; + int r1, r2, r3; + + if( !affinity ){ + affinity = SQLITE_AFF_NONE; + } + if( pKeyInfo ){ + pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); + } + + /* Loop through each expression in . */ + r1 = sqlite3GetTempReg(pParse); + r2 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_Null, 0, r2); + for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ + Expr *pE2 = pItem->pExpr; + int iValToIns; + + /* If the expression is not constant then we will need to + ** disable the test that was generated above that makes sure + ** this code only executes once. Because for a non-constant + ** expression we need to rerun this code each time. + */ + if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){ + sqlite3VdbeChangeToNoop(v, testAddr); + testAddr = -1; + } + + /* Evaluate the expression and insert it into the temp table */ + if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){ + sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns); + }else{ + r3 = sqlite3ExprCodeTarget(pParse, pE2, r1); + if( isRowid ){ + sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, + sqlite3VdbeCurrentAddr(v)+2); + sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3); + }else{ + sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1); + sqlite3ExprCacheAffinityChange(pParse, r3, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2); + } + } + } + sqlite3ReleaseTempReg(pParse, r1); + sqlite3ReleaseTempReg(pParse, r2); + } + if( pKeyInfo ){ + sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF); + } + break; + } + + case TK_EXISTS: + case TK_SELECT: + default: { + /* If this has to be a scalar SELECT. Generate code to put the + ** value of this select in a memory cell and record the number + ** of the memory cell in iColumn. If this is an EXISTS, write + ** an integer 0 (not exists) or 1 (exists) into a memory cell + ** and record that memory cell in iColumn. + */ + Select *pSel; /* SELECT statement to encode */ + SelectDest dest; /* How to deal with SELECt result */ + + testcase( pExpr->op==TK_EXISTS ); + testcase( pExpr->op==TK_SELECT ); + assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); + + assert( ExprHasProperty(pExpr, EP_xIsSelect) ); + pSel = pExpr->x.pSelect; + sqlite3SelectDestInit(&dest, 0, ++pParse->nMem); + if( pExpr->op==TK_SELECT ){ + dest.eDest = SRT_Mem; + sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm); + VdbeComment((v, "Init subquery result")); + }else{ + dest.eDest = SRT_Exists; + sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); + VdbeComment((v, "Init EXISTS result")); + } + sqlite3ExprDelete(pParse->db, pSel->pLimit); + pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, + &sqlite3IntTokens[1]); + pSel->iLimit = 0; + if( sqlite3Select(pParse, pSel, &dest) ){ + return 0; + } + rReg = dest.iSDParm; + ExprSetVVAProperty(pExpr, EP_NoReduce); + break; + } + } + + if( testAddr>=0 ){ + sqlite3VdbeJumpHere(v, testAddr); + } + sqlite3ExprCachePop(pParse, 1); + + return rReg; +} +#endif /* SQLITE_OMIT_SUBQUERY */ + +#ifndef SQLITE_OMIT_SUBQUERY +/* +** Generate code for an IN expression. +** +** x IN (SELECT ...) +** x IN (value, value, ...) +** +** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS) +** is an array of zero or more values. The expression is true if the LHS is +** contained within the RHS. The value of the expression is unknown (NULL) +** if the LHS is NULL or if the LHS is not contained within the RHS and the +** RHS contains one or more NULL values. +** +** This routine generates code will jump to destIfFalse if the LHS is not +** contained within the RHS. If due to NULLs we cannot determine if the LHS +** is contained in the RHS then jump to destIfNull. If the LHS is contained +** within the RHS then fall through. +*/ +static void sqlite3ExprCodeIN( + Parse *pParse, /* Parsing and code generating context */ + Expr *pExpr, /* The IN expression */ + int destIfFalse, /* Jump here if LHS is not contained in the RHS */ + int destIfNull /* Jump here if the results are unknown due to NULLs */ +){ + int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ + char affinity; /* Comparison affinity to use */ + int eType; /* Type of the RHS */ + int r1; /* Temporary use register */ + Vdbe *v; /* Statement under construction */ + + /* Compute the RHS. After this step, the table with cursor + ** pExpr->iTable will contains the values that make up the RHS. + */ + v = pParse->pVdbe; + assert( v!=0 ); /* OOM detected prior to this routine */ + VdbeNoopComment((v, "begin IN expr")); + eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull); + + /* Figure out the affinity to use to create a key from the results + ** of the expression. affinityStr stores a static string suitable for + ** P4 of OP_MakeRecord. + */ + affinity = comparisonAffinity(pExpr); + + /* Code the LHS, the from " IN (...)". + */ + sqlite3ExprCachePush(pParse); + r1 = sqlite3GetTempReg(pParse); + sqlite3ExprCode(pParse, pExpr->pLeft, r1); + + /* If the LHS is NULL, then the result is either false or NULL depending + ** on whether the RHS is empty or not, respectively. + */ + if( destIfNull==destIfFalse ){ + /* Shortcut for the common case where the false and NULL outcomes are + ** the same. */ + sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); + }else{ + int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); + sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse); + sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); + sqlite3VdbeJumpHere(v, addr1); + } + + if( eType==IN_INDEX_ROWID ){ + /* In this case, the RHS is the ROWID of table b-tree + */ + sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); + sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1); + }else{ + /* In this case, the RHS is an index b-tree. + */ + sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1); + + /* If the set membership test fails, then the result of the + ** "x IN (...)" expression must be either 0 or NULL. If the set + ** contains no NULL values, then the result is 0. If the set + ** contains one or more NULL values, then the result of the + ** expression is also NULL. + */ + if( rRhsHasNull==0 || destIfFalse==destIfNull ){ + /* This branch runs if it is known at compile time that the RHS + ** cannot contain NULL values. This happens as the result + ** of a "NOT NULL" constraint in the database schema. + ** + ** Also run this branch if NULL is equivalent to FALSE + ** for this particular IN operator. + */ + sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1); + + }else{ + /* In this branch, the RHS of the IN might contain a NULL and + ** the presence of a NULL on the RHS makes a difference in the + ** outcome. + */ + int j1, j2, j3; + + /* First check to see if the LHS is contained in the RHS. If so, + ** then the presence of NULLs in the RHS does not matter, so jump + ** over all of the code that follows. + */ + j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1); + + /* Here we begin generating code that runs if the LHS is not + ** contained within the RHS. Generate additional code that + ** tests the RHS for NULLs. If the RHS contains a NULL then + ** jump to destIfNull. If there are no NULLs in the RHS then + ** jump to destIfFalse. + */ + j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull); + j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1); + sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull); + sqlite3VdbeJumpHere(v, j3); + sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1); + sqlite3VdbeJumpHere(v, j2); + + /* Jump to the appropriate target depending on whether or not + ** the RHS contains a NULL + */ + sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull); + sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); + + /* The OP_Found at the top of this branch jumps here when true, + ** causing the overall IN expression evaluation to fall through. + */ + sqlite3VdbeJumpHere(v, j1); + } + } + sqlite3ReleaseTempReg(pParse, r1); + sqlite3ExprCachePop(pParse, 1); + VdbeComment((v, "end IN expr")); +} +#endif /* SQLITE_OMIT_SUBQUERY */ + +/* +** Duplicate an 8-byte value +*/ +static char *dup8bytes(Vdbe *v, const char *in){ + char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8); + if( out ){ + memcpy(out, in, 8); + } + return out; +} + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* +** Generate an instruction that will put the floating point +** value described by z[0..n-1] into register iMem. +** +** The z[] string will probably not be zero-terminated. But the +** z[n] character is guaranteed to be something that does not look +** like the continuation of the number. +*/ +static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ + if( ALWAYS(z!=0) ){ + double value; + char *zV; + sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); + assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ + if( negateFlag ) value = -value; + zV = dup8bytes(v, (char*)&value); + sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL); + } +} +#endif + + +/* +** Generate an instruction that will put the integer describe by +** text z[0..n-1] into register iMem. +** +** Expr.u.zToken is always UTF8 and zero-terminated. +*/ +static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ + Vdbe *v = pParse->pVdbe; + if( pExpr->flags & EP_IntValue ){ + int i = pExpr->u.iValue; + assert( i>=0 ); + if( negFlag ) i = -i; + sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); + }else{ + int c; + i64 value; + const char *z = pExpr->u.zToken; + assert( z!=0 ); + c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); + if( c==0 || (c==2 && negFlag) ){ + char *zV; + if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; } + zV = dup8bytes(v, (char*)&value); + sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64); + }else{ +#ifdef SQLITE_OMIT_FLOATING_POINT + sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); +#else + codeReal(v, z, negFlag, iMem); +#endif + } + } +} + +/* +** Clear a cache entry. +*/ +static void cacheEntryClear(Parse *pParse, struct yColCache *p){ + if( p->tempReg ){ + if( pParse->nTempRegaTempReg) ){ + pParse->aTempReg[pParse->nTempReg++] = p->iReg; + } + p->tempReg = 0; + } +} + + +/* +** Record in the column cache that a particular column from a +** particular table is stored in a particular register. +*/ +void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){ + int i; + int minLru; + int idxLru; + struct yColCache *p; + + assert( iReg>0 ); /* Register numbers are always positive */ + assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */ + + /* The SQLITE_ColumnCache flag disables the column cache. This is used + ** for testing only - to verify that SQLite always gets the same answer + ** with and without the column cache. + */ + if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return; + + /* First replace any existing entry. + ** + ** Actually, the way the column cache is currently used, we are guaranteed + ** that the object will never already be in cache. Verify this guarantee. + */ +#ifndef NDEBUG + for(i=0, p=pParse->aColCache; iiReg==0 || p->iTable!=iTab || p->iColumn!=iCol ); + } +#endif + + /* Find an empty slot and replace it */ + for(i=0, p=pParse->aColCache; iiReg==0 ){ + p->iLevel = pParse->iCacheLevel; + p->iTable = iTab; + p->iColumn = iCol; + p->iReg = iReg; + p->tempReg = 0; + p->lru = pParse->iCacheCnt++; + return; + } + } + + /* Replace the last recently used */ + minLru = 0x7fffffff; + idxLru = -1; + for(i=0, p=pParse->aColCache; ilrulru; + } + } + if( ALWAYS(idxLru>=0) ){ + p = &pParse->aColCache[idxLru]; + p->iLevel = pParse->iCacheLevel; + p->iTable = iTab; + p->iColumn = iCol; + p->iReg = iReg; + p->tempReg = 0; + p->lru = pParse->iCacheCnt++; + return; + } +} + +/* +** Indicate that registers between iReg..iReg+nReg-1 are being overwritten. +** Purge the range of registers from the column cache. +*/ +void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){ + int i; + int iLast = iReg + nReg - 1; + struct yColCache *p; + for(i=0, p=pParse->aColCache; iiReg; + if( r>=iReg && r<=iLast ){ + cacheEntryClear(pParse, p); + p->iReg = 0; + } + } +} + +/* +** Remember the current column cache context. Any new entries added +** added to the column cache after this call are removed when the +** corresponding pop occurs. +*/ +void sqlite3ExprCachePush(Parse *pParse){ + pParse->iCacheLevel++; +} + +/* +** Remove from the column cache any entries that were added since the +** the previous N Push operations. In other words, restore the cache +** to the state it was in N Pushes ago. +*/ +void sqlite3ExprCachePop(Parse *pParse, int N){ + int i; + struct yColCache *p; + assert( N>0 ); + assert( pParse->iCacheLevel>=N ); + pParse->iCacheLevel -= N; + for(i=0, p=pParse->aColCache; iiReg && p->iLevel>pParse->iCacheLevel ){ + cacheEntryClear(pParse, p); + p->iReg = 0; + } + } +} + +/* +** When a cached column is reused, make sure that its register is +** no longer available as a temp register. ticket #3879: that same +** register might be in the cache in multiple places, so be sure to +** get them all. +*/ +static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){ + int i; + struct yColCache *p; + for(i=0, p=pParse->aColCache; iiReg==iReg ){ + p->tempReg = 0; + } + } +} + +/* +** Generate code to extract the value of the iCol-th column of a table. +*/ +void sqlite3ExprCodeGetColumnOfTable( + Vdbe *v, /* The VDBE under construction */ + Table *pTab, /* The table containing the value */ + int iTabCur, /* The cursor for this table */ + int iCol, /* Index of the column to extract */ + int regOut /* Extract the valud into this register */ +){ + if( iCol<0 || iCol==pTab->iPKey ){ + sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); + }else{ + int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; + sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut); + } + if( iCol>=0 ){ + sqlite3ColumnDefault(v, pTab, iCol, regOut); + } +} + +/* +** Generate code that will extract the iColumn-th column from +** table pTab and store the column value in a register. An effort +** is made to store the column value in register iReg, but this is +** not guaranteed. The location of the column value is returned. +** +** There must be an open cursor to pTab in iTable when this routine +** is called. If iColumn<0 then code is generated that extracts the rowid. +*/ +int sqlite3ExprCodeGetColumn( + Parse *pParse, /* Parsing and code generating context */ + Table *pTab, /* Description of the table we are reading from */ + int iColumn, /* Index of the table column */ + int iTable, /* The cursor pointing to the table */ + int iReg, /* Store results here */ + u8 p5 /* P5 value for OP_Column */ +){ + Vdbe *v = pParse->pVdbe; + int i; + struct yColCache *p; + + for(i=0, p=pParse->aColCache; iiReg>0 && p->iTable==iTable && p->iColumn==iColumn ){ + p->lru = pParse->iCacheCnt++; + sqlite3ExprCachePinRegister(pParse, p->iReg); + return p->iReg; + } + } + assert( v!=0 ); + sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg); + if( p5 ){ + sqlite3VdbeChangeP5(v, p5); + }else{ + sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg); + } + return iReg; +} + +/* +** Clear all column cache entries. +*/ +void sqlite3ExprCacheClear(Parse *pParse){ + int i; + struct yColCache *p; + + for(i=0, p=pParse->aColCache; iiReg ){ + cacheEntryClear(pParse, p); + p->iReg = 0; + } + } +} + +/* +** Record the fact that an affinity change has occurred on iCount +** registers starting with iStart. +*/ +void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){ + sqlite3ExprCacheRemove(pParse, iStart, iCount); +} + +/* +** Generate code to move content from registers iFrom...iFrom+nReg-1 +** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. +*/ +void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ + int i; + struct yColCache *p; + assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo ); + sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1); + for(i=0, p=pParse->aColCache; iiReg; + if( x>=iFrom && xiReg += iTo-iFrom; + } + } +} + +#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) +/* +** Return true if any register in the range iFrom..iTo (inclusive) +** is used as part of the column cache. +** +** This routine is used within assert() and testcase() macros only +** and does not appear in a normal build. +*/ +static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){ + int i; + struct yColCache *p; + for(i=0, p=pParse->aColCache; iiReg; + if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/ + } + return 0; +} +#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */ + +/* +** Convert an expression node to a TK_REGISTER +*/ +static void exprToRegister(Expr *p, int iReg){ + p->op2 = p->op; + p->op = TK_REGISTER; + p->iTable = iReg; + ExprClearProperty(p, EP_Skip); +} + +/* +** Generate code into the current Vdbe to evaluate the given +** expression. Attempt to store the results in register "target". +** Return the register where results are stored. +** +** With this routine, there is no guarantee that results will +** be stored in target. The result might be stored in some other +** register if it is convenient to do so. The calling function +** must check the return code and move the results to the desired +** register. +*/ +int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ + Vdbe *v = pParse->pVdbe; /* The VM under construction */ + int op; /* The opcode being coded */ + int inReg = target; /* Results stored in register inReg */ + int regFree1 = 0; /* If non-zero free this temporary register */ + int regFree2 = 0; /* If non-zero free this temporary register */ + int r1, r2, r3, r4; /* Various register numbers */ + sqlite3 *db = pParse->db; /* The database connection */ + + assert( target>0 && target<=pParse->nMem ); + if( v==0 ){ + assert( pParse->db->mallocFailed ); + return 0; + } + + if( pExpr==0 ){ + op = TK_NULL; + }else{ + op = pExpr->op; + } + switch( op ){ + case TK_AGG_COLUMN: { + AggInfo *pAggInfo = pExpr->pAggInfo; + struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; + if( !pAggInfo->directMode ){ + assert( pCol->iMem>0 ); + inReg = pCol->iMem; + break; + }else if( pAggInfo->useSortingIdx ){ + sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, + pCol->iSorterColumn, target); + break; + } + /* Otherwise, fall thru into the TK_COLUMN case */ + } + case TK_COLUMN: { + int iTab = pExpr->iTable; + if( iTab<0 ){ + if( pParse->ckBase>0 ){ + /* Generating CHECK constraints or inserting into partial index */ + inReg = pExpr->iColumn + pParse->ckBase; + break; + }else{ + /* Deleting from a partial index */ + iTab = pParse->iPartIdxTab; + } + } + inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab, + pExpr->iColumn, iTab, target, + pExpr->op2); + break; + } + case TK_INTEGER: { + codeInteger(pParse, pExpr, 0, target); + break; + } +#ifndef SQLITE_OMIT_FLOATING_POINT + case TK_FLOAT: { + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + codeReal(v, pExpr->u.zToken, 0, target); + break; + } +#endif + case TK_STRING: { + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0); + break; + } + case TK_NULL: { + sqlite3VdbeAddOp2(v, OP_Null, 0, target); + break; + } +#ifndef SQLITE_OMIT_BLOB_LITERAL + case TK_BLOB: { + int n; + const char *z; + char *zBlob; + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); + assert( pExpr->u.zToken[1]=='\'' ); + z = &pExpr->u.zToken[2]; + n = sqlite3Strlen30(z) - 1; + assert( z[n]=='\'' ); + zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); + sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); + break; + } +#endif + case TK_VARIABLE: { + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + assert( pExpr->u.zToken!=0 ); + assert( pExpr->u.zToken[0]!=0 ); + sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); + if( pExpr->u.zToken[1]!=0 ){ + assert( pExpr->u.zToken[0]=='?' + || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 ); + sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC); + } + break; + } + case TK_REGISTER: { + inReg = pExpr->iTable; + break; + } + case TK_AS: { + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + break; + } +#ifndef SQLITE_OMIT_CAST + case TK_CAST: { + /* Expressions of the form: CAST(pLeft AS token) */ + int aff, to_op; + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + aff = sqlite3AffinityType(pExpr->u.zToken, 0); + to_op = aff - SQLITE_AFF_TEXT + OP_ToText; + assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT ); + assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE ); + assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC ); + assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER ); + assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL ); + testcase( to_op==OP_ToText ); + testcase( to_op==OP_ToBlob ); + testcase( to_op==OP_ToNumeric ); + testcase( to_op==OP_ToInt ); + testcase( to_op==OP_ToReal ); + if( inReg!=target ){ + sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); + inReg = target; + } + sqlite3VdbeAddOp1(v, to_op, inReg); + testcase( usedAsColumnCache(pParse, inReg, inReg) ); + sqlite3ExprCacheAffinityChange(pParse, inReg, 1); + break; + } +#endif /* SQLITE_OMIT_CAST */ + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_NE: + case TK_EQ: { + assert( TK_LT==OP_Lt ); + assert( TK_LE==OP_Le ); + assert( TK_GT==OP_Gt ); + assert( TK_GE==OP_Ge ); + assert( TK_EQ==OP_Eq ); + assert( TK_NE==OP_Ne ); + testcase( op==TK_LT ); + testcase( op==TK_LE ); + testcase( op==TK_GT ); + testcase( op==TK_GE ); + testcase( op==TK_EQ ); + testcase( op==TK_NE ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, inReg, SQLITE_STOREP2); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_IS: + case TK_ISNOT: { + testcase( op==TK_IS ); + testcase( op==TK_ISNOT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + op = (op==TK_IS) ? TK_EQ : TK_NE; + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_AND: + case TK_OR: + case TK_PLUS: + case TK_STAR: + case TK_MINUS: + case TK_REM: + case TK_BITAND: + case TK_BITOR: + case TK_SLASH: + case TK_LSHIFT: + case TK_RSHIFT: + case TK_CONCAT: { + assert( TK_AND==OP_And ); + assert( TK_OR==OP_Or ); + assert( TK_PLUS==OP_Add ); + assert( TK_MINUS==OP_Subtract ); + assert( TK_REM==OP_Remainder ); + assert( TK_BITAND==OP_BitAnd ); + assert( TK_BITOR==OP_BitOr ); + assert( TK_SLASH==OP_Divide ); + assert( TK_LSHIFT==OP_ShiftLeft ); + assert( TK_RSHIFT==OP_ShiftRight ); + assert( TK_CONCAT==OP_Concat ); + testcase( op==TK_AND ); + testcase( op==TK_OR ); + testcase( op==TK_PLUS ); + testcase( op==TK_MINUS ); + testcase( op==TK_REM ); + testcase( op==TK_BITAND ); + testcase( op==TK_BITOR ); + testcase( op==TK_SLASH ); + testcase( op==TK_LSHIFT ); + testcase( op==TK_RSHIFT ); + testcase( op==TK_CONCAT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + sqlite3VdbeAddOp3(v, op, r2, r1, target); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_UMINUS: { + Expr *pLeft = pExpr->pLeft; + assert( pLeft ); + if( pLeft->op==TK_INTEGER ){ + codeInteger(pParse, pLeft, 1, target); +#ifndef SQLITE_OMIT_FLOATING_POINT + }else if( pLeft->op==TK_FLOAT ){ + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + codeReal(v, pLeft->u.zToken, 1, target); +#endif + }else{ + regFree1 = r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_Integer, 0, r1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); + sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); + testcase( regFree2==0 ); + } + inReg = target; + break; + } + case TK_BITNOT: + case TK_NOT: { + assert( TK_BITNOT==OP_BitNot ); + assert( TK_NOT==OP_Not ); + testcase( op==TK_BITNOT ); + testcase( op==TK_NOT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + testcase( regFree1==0 ); + inReg = target; + sqlite3VdbeAddOp2(v, op, r1, inReg); + break; + } + case TK_ISNULL: + case TK_NOTNULL: { + int addr; + assert( TK_ISNULL==OP_IsNull ); + assert( TK_NOTNULL==OP_NotNull ); + testcase( op==TK_ISNULL ); + testcase( op==TK_NOTNULL ); + sqlite3VdbeAddOp2(v, OP_Integer, 1, target); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + testcase( regFree1==0 ); + addr = sqlite3VdbeAddOp1(v, op, r1); + sqlite3VdbeAddOp2(v, OP_AddImm, target, -1); + sqlite3VdbeJumpHere(v, addr); + break; + } + case TK_AGG_FUNCTION: { + AggInfo *pInfo = pExpr->pAggInfo; + if( pInfo==0 ){ + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); + }else{ + inReg = pInfo->aFunc[pExpr->iAgg].iMem; + } + break; + } + case TK_CONST_FUNC: + case TK_FUNCTION: { + ExprList *pFarg; /* List of function arguments */ + int nFarg; /* Number of function arguments */ + FuncDef *pDef; /* The function definition object */ + int nId; /* Length of the function name in bytes */ + const char *zId; /* The function name */ + int constMask = 0; /* Mask of function arguments that are constant */ + int i; /* Loop counter */ + u8 enc = ENC(db); /* The text encoding used by this database */ + CollSeq *pColl = 0; /* A collating sequence */ + + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + testcase( op==TK_CONST_FUNC ); + testcase( op==TK_FUNCTION ); + if( ExprHasProperty(pExpr, EP_TokenOnly) ){ + pFarg = 0; + }else{ + pFarg = pExpr->x.pList; + } + nFarg = pFarg ? pFarg->nExpr : 0; + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + zId = pExpr->u.zToken; + nId = sqlite3Strlen30(zId); + pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0); + if( pDef==0 ){ + sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId); + break; + } + + /* Attempt a direct implementation of the built-in COALESCE() and + ** IFNULL() functions. This avoids unnecessary evalation of + ** arguments past the first non-NULL argument. + */ + if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){ + int endCoalesce = sqlite3VdbeMakeLabel(v); + assert( nFarg>=2 ); + sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); + for(i=1; ia[i].pExpr, target); + sqlite3ExprCachePop(pParse, 1); + } + sqlite3VdbeResolveLabel(v, endCoalesce); + break; + } + + /* The UNLIKELY() function is a no-op. The result is the value + ** of the first argument. + */ + if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ + assert( nFarg>=1 ); + sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); + break; + } + + if( pFarg ){ + r1 = sqlite3GetTempRange(pParse, nFarg); + + /* For length() and typeof() functions with a column argument, + ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG + ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data + ** loading. + */ + if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){ + u8 exprOp; + assert( nFarg==1 ); + assert( pFarg->a[0].pExpr!=0 ); + exprOp = pFarg->a[0].pExpr->op; + if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){ + assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG ); + assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG ); + testcase( (pDef->funcFlags&~SQLITE_FUNC_ENCMASK) + ==SQLITE_FUNC_LENGTH ); + pFarg->a[0].pExpr->op2 = pDef->funcFlags&~SQLITE_FUNC_ENCMASK; + } + } + + sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */ + sqlite3ExprCodeExprList(pParse, pFarg, r1, 1); + sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */ + }else{ + r1 = 0; + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + /* Possibly overload the function if the first argument is + ** a virtual table column. + ** + ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the + ** second argument, not the first, as the argument to test to + ** see if it is a column in a virtual table. This is done because + ** the left operand of infix functions (the operand we want to + ** control overloading) ends up as the second argument to the + ** function. The expression "A glob B" is equivalent to + ** "glob(B,A). We want to use the A in "A glob B" to test + ** for function overloading. But we use the B term in "glob(B,A)". + */ + if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){ + pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); + }else if( nFarg>0 ){ + pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); + } +#endif + for(i=0; ia[i].pExpr) ){ + constMask |= (1<funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ + pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); + } + } + if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ + if( !pColl ) pColl = db->pDfltColl; + sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); + } + sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target, + (char*)pDef, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, (u8)nFarg); + if( nFarg ){ + sqlite3ReleaseTempRange(pParse, r1, nFarg); + } + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_EXISTS: + case TK_SELECT: { + testcase( op==TK_EXISTS ); + testcase( op==TK_SELECT ); + inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0); + break; + } + case TK_IN: { + int destIfFalse = sqlite3VdbeMakeLabel(v); + int destIfNull = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp2(v, OP_Null, 0, target); + sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); + sqlite3VdbeAddOp2(v, OP_Integer, 1, target); + sqlite3VdbeResolveLabel(v, destIfFalse); + sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); + sqlite3VdbeResolveLabel(v, destIfNull); + break; + } +#endif /* SQLITE_OMIT_SUBQUERY */ + + + /* + ** x BETWEEN y AND z + ** + ** This is equivalent to + ** + ** x>=y AND x<=z + ** + ** X is stored in pExpr->pLeft. + ** Y is stored in pExpr->pList->a[0].pExpr. + ** Z is stored in pExpr->pList->a[1].pExpr. + */ + case TK_BETWEEN: { + Expr *pLeft = pExpr->pLeft; + struct ExprList_item *pLItem = pExpr->x.pList->a; + Expr *pRight = pLItem->pExpr; + + r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + r3 = sqlite3GetTempReg(pParse); + r4 = sqlite3GetTempReg(pParse); + codeCompare(pParse, pLeft, pRight, OP_Ge, + r1, r2, r3, SQLITE_STOREP2); + pLItem++; + pRight = pLItem->pExpr; + sqlite3ReleaseTempReg(pParse, regFree2); + r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2); + testcase( regFree2==0 ); + codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2); + sqlite3VdbeAddOp3(v, OP_And, r3, r4, target); + sqlite3ReleaseTempReg(pParse, r3); + sqlite3ReleaseTempReg(pParse, r4); + break; + } + case TK_COLLATE: + case TK_UPLUS: { + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + break; + } + + case TK_TRIGGER: { + /* If the opcode is TK_TRIGGER, then the expression is a reference + ** to a column in the new.* or old.* pseudo-tables available to + ** trigger programs. In this case Expr.iTable is set to 1 for the + ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn + ** is set to the column of the pseudo-table to read, or to -1 to + ** read the rowid field. + ** + ** The expression is implemented using an OP_Param opcode. The p1 + ** parameter is set to 0 for an old.rowid reference, or to (i+1) + ** to reference another column of the old.* pseudo-table, where + ** i is the index of the column. For a new.rowid reference, p1 is + ** set to (n+1), where n is the number of columns in each pseudo-table. + ** For a reference to any other column in the new.* pseudo-table, p1 + ** is set to (n+2+i), where n and i are as defined previously. For + ** example, if the table on which triggers are being fired is + ** declared as: + ** + ** CREATE TABLE t1(a, b); + ** + ** Then p1 is interpreted as follows: + ** + ** p1==0 -> old.rowid p1==3 -> new.rowid + ** p1==1 -> old.a p1==4 -> new.a + ** p1==2 -> old.b p1==5 -> new.b + */ + Table *pTab = pExpr->pTab; + int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn; + + assert( pExpr->iTable==0 || pExpr->iTable==1 ); + assert( pExpr->iColumn>=-1 && pExpr->iColumnnCol ); + assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey ); + assert( p1>=0 && p1<(pTab->nCol*2+2) ); + + sqlite3VdbeAddOp2(v, OP_Param, p1, target); + VdbeComment((v, "%s.%s -> $%d", + (pExpr->iTable ? "new" : "old"), + (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName), + target + )); + +#ifndef SQLITE_OMIT_FLOATING_POINT + /* If the column has REAL affinity, it may currently be stored as an + ** integer. Use OP_RealAffinity to make sure it is really real. */ + if( pExpr->iColumn>=0 + && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL + ){ + sqlite3VdbeAddOp1(v, OP_RealAffinity, target); + } +#endif + break; + } + + + /* + ** Form A: + ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END + ** + ** Form B: + ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END + ** + ** Form A is can be transformed into the equivalent form B as follows: + ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... + ** WHEN x=eN THEN rN ELSE y END + ** + ** X (if it exists) is in pExpr->pLeft. + ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is + ** odd. The Y is also optional. If the number of elements in x.pList + ** is even, then Y is omitted and the "otherwise" result is NULL. + ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. + ** + ** The result of the expression is the Ri for the first matching Ei, + ** or if there is no matching Ei, the ELSE term Y, or if there is + ** no ELSE term, NULL. + */ + default: assert( op==TK_CASE ); { + int endLabel; /* GOTO label for end of CASE stmt */ + int nextCase; /* GOTO label for next WHEN clause */ + int nExpr; /* 2x number of WHEN terms */ + int i; /* Loop counter */ + ExprList *pEList; /* List of WHEN terms */ + struct ExprList_item *aListelem; /* Array of WHEN terms */ + Expr opCompare; /* The X==Ei expression */ + Expr cacheX; /* Cached expression X */ + Expr *pX; /* The X expression */ + Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ + VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; ) + + assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList ); + assert(pExpr->x.pList->nExpr > 0); + pEList = pExpr->x.pList; + aListelem = pEList->a; + nExpr = pEList->nExpr; + endLabel = sqlite3VdbeMakeLabel(v); + if( (pX = pExpr->pLeft)!=0 ){ + cacheX = *pX; + testcase( pX->op==TK_COLUMN ); + testcase( pX->op==TK_REGISTER ); + exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, ®Free1)); + testcase( regFree1==0 ); + opCompare.op = TK_EQ; + opCompare.pLeft = &cacheX; + pTest = &opCompare; + /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: + ** The value in regFree1 might get SCopy-ed into the file result. + ** So make sure that the regFree1 register is not reused for other + ** purposes and possibly overwritten. */ + regFree1 = 0; + } + for(i=0; iop==TK_COLUMN ); + sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); + testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); + testcase( aListelem[i+1].pExpr->op==TK_REGISTER ); + sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); + sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel); + sqlite3ExprCachePop(pParse, 1); + sqlite3VdbeResolveLabel(v, nextCase); + } + if( (nExpr&1)!=0 ){ + sqlite3ExprCachePush(pParse); + sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); + sqlite3ExprCachePop(pParse, 1); + }else{ + sqlite3VdbeAddOp2(v, OP_Null, 0, target); + } + assert( db->mallocFailed || pParse->nErr>0 + || pParse->iCacheLevel==iCacheLevel ); + sqlite3VdbeResolveLabel(v, endLabel); + break; + } +#ifndef SQLITE_OMIT_TRIGGER + case TK_RAISE: { + assert( pExpr->affinity==OE_Rollback + || pExpr->affinity==OE_Abort + || pExpr->affinity==OE_Fail + || pExpr->affinity==OE_Ignore + ); + if( !pParse->pTriggerTab ){ + sqlite3ErrorMsg(pParse, + "RAISE() may only be used within a trigger-program"); + return 0; + } + if( pExpr->affinity==OE_Abort ){ + sqlite3MayAbort(pParse); + } + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + if( pExpr->affinity==OE_Ignore ){ + sqlite3VdbeAddOp4( + v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); + }else{ + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER, + pExpr->affinity, pExpr->u.zToken, 0); + } + + break; + } +#endif + } + sqlite3ReleaseTempReg(pParse, regFree1); + sqlite3ReleaseTempReg(pParse, regFree2); + return inReg; +} + +/* +** Generate code to evaluate an expression and store the results +** into a register. Return the register number where the results +** are stored. +** +** If the register is a temporary register that can be deallocated, +** then write its number into *pReg. If the result register is not +** a temporary, then set *pReg to zero. +*/ +int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ + int r1 = sqlite3GetTempReg(pParse); + int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); + if( r2==r1 ){ + *pReg = r1; + }else{ + sqlite3ReleaseTempReg(pParse, r1); + *pReg = 0; + } + return r2; +} + +/* +** Generate code that will evaluate expression pExpr and store the +** results in register target. The results are guaranteed to appear +** in register target. +*/ +int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ + int inReg; + + assert( target>0 && target<=pParse->nMem ); + if( pExpr && pExpr->op==TK_REGISTER ){ + sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target); + }else{ + inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); + assert( pParse->pVdbe || pParse->db->mallocFailed ); + if( inReg!=target && pParse->pVdbe ){ + sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target); + } + } + return target; +} + +/* +** Generate code that evalutes the given expression and puts the result +** in register target. +** +** Also make a copy of the expression results into another "cache" register +** and modify the expression so that the next time it is evaluated, +** the result is a copy of the cache register. +** +** This routine is used for expressions that are used multiple +** times. They are evaluated once and the results of the expression +** are reused. +*/ +int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ + Vdbe *v = pParse->pVdbe; + int inReg; + inReg = sqlite3ExprCode(pParse, pExpr, target); + assert( target>0 ); + /* This routine is called for terms to INSERT or UPDATE. And the only + ** other place where expressions can be converted into TK_REGISTER is + ** in WHERE clause processing. So as currently implemented, there is + ** no way for a TK_REGISTER to exist here. But it seems prudent to + ** keep the ALWAYS() in case the conditions above change with future + ** modifications or enhancements. */ + if( ALWAYS(pExpr->op!=TK_REGISTER) ){ + int iMem; + iMem = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem); + exprToRegister(pExpr, iMem); + } + return inReg; +} + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) +/* +** Generate a human-readable explanation of an expression tree. +*/ +void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){ + int op; /* The opcode being coded */ + const char *zBinOp = 0; /* Binary operator */ + const char *zUniOp = 0; /* Unary operator */ + if( pExpr==0 ){ + op = TK_NULL; + }else{ + op = pExpr->op; + } + switch( op ){ + case TK_AGG_COLUMN: { + sqlite3ExplainPrintf(pOut, "AGG{%d:%d}", + pExpr->iTable, pExpr->iColumn); + break; + } + case TK_COLUMN: { + if( pExpr->iTable<0 ){ + /* This only happens when coding check constraints */ + sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn); + }else{ + sqlite3ExplainPrintf(pOut, "{%d:%d}", + pExpr->iTable, pExpr->iColumn); + } + break; + } + case TK_INTEGER: { + if( pExpr->flags & EP_IntValue ){ + sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue); + }else{ + sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken); + } + break; + } +#ifndef SQLITE_OMIT_FLOATING_POINT + case TK_FLOAT: { + sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken); + break; + } +#endif + case TK_STRING: { + sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken); + break; + } + case TK_NULL: { + sqlite3ExplainPrintf(pOut,"NULL"); + break; + } +#ifndef SQLITE_OMIT_BLOB_LITERAL + case TK_BLOB: { + sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken); + break; + } +#endif + case TK_VARIABLE: { + sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)", + pExpr->u.zToken, pExpr->iColumn); + break; + } + case TK_REGISTER: { + sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable); + break; + } + case TK_AS: { + sqlite3ExplainExpr(pOut, pExpr->pLeft); + break; + } +#ifndef SQLITE_OMIT_CAST + case TK_CAST: { + /* Expressions of the form: CAST(pLeft AS token) */ + const char *zAff = "unk"; + switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){ + case SQLITE_AFF_TEXT: zAff = "TEXT"; break; + case SQLITE_AFF_NONE: zAff = "NONE"; break; + case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break; + case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break; + case SQLITE_AFF_REAL: zAff = "REAL"; break; + } + sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut, ")"); + break; + } +#endif /* SQLITE_OMIT_CAST */ + case TK_LT: zBinOp = "LT"; break; + case TK_LE: zBinOp = "LE"; break; + case TK_GT: zBinOp = "GT"; break; + case TK_GE: zBinOp = "GE"; break; + case TK_NE: zBinOp = "NE"; break; + case TK_EQ: zBinOp = "EQ"; break; + case TK_IS: zBinOp = "IS"; break; + case TK_ISNOT: zBinOp = "ISNOT"; break; + case TK_AND: zBinOp = "AND"; break; + case TK_OR: zBinOp = "OR"; break; + case TK_PLUS: zBinOp = "ADD"; break; + case TK_STAR: zBinOp = "MUL"; break; + case TK_MINUS: zBinOp = "SUB"; break; + case TK_REM: zBinOp = "REM"; break; + case TK_BITAND: zBinOp = "BITAND"; break; + case TK_BITOR: zBinOp = "BITOR"; break; + case TK_SLASH: zBinOp = "DIV"; break; + case TK_LSHIFT: zBinOp = "LSHIFT"; break; + case TK_RSHIFT: zBinOp = "RSHIFT"; break; + case TK_CONCAT: zBinOp = "CONCAT"; break; + + case TK_UMINUS: zUniOp = "UMINUS"; break; + case TK_UPLUS: zUniOp = "UPLUS"; break; + case TK_BITNOT: zUniOp = "BITNOT"; break; + case TK_NOT: zUniOp = "NOT"; break; + case TK_ISNULL: zUniOp = "ISNULL"; break; + case TK_NOTNULL: zUniOp = "NOTNULL"; break; + + case TK_COLLATE: { + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken); + break; + } + + case TK_AGG_FUNCTION: + case TK_CONST_FUNC: + case TK_FUNCTION: { + ExprList *pFarg; /* List of function arguments */ + if( ExprHasProperty(pExpr, EP_TokenOnly) ){ + pFarg = 0; + }else{ + pFarg = pExpr->x.pList; + } + if( op==TK_AGG_FUNCTION ){ + sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(", + pExpr->op2, pExpr->u.zToken); + }else{ + sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken); + } + if( pFarg ){ + sqlite3ExplainExprList(pOut, pFarg); + } + sqlite3ExplainPrintf(pOut, ")"); + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_EXISTS: { + sqlite3ExplainPrintf(pOut, "EXISTS("); + sqlite3ExplainSelect(pOut, pExpr->x.pSelect); + sqlite3ExplainPrintf(pOut,")"); + break; + } + case TK_SELECT: { + sqlite3ExplainPrintf(pOut, "("); + sqlite3ExplainSelect(pOut, pExpr->x.pSelect); + sqlite3ExplainPrintf(pOut, ")"); + break; + } + case TK_IN: { + sqlite3ExplainPrintf(pOut, "IN("); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut, ","); + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + sqlite3ExplainSelect(pOut, pExpr->x.pSelect); + }else{ + sqlite3ExplainExprList(pOut, pExpr->x.pList); + } + sqlite3ExplainPrintf(pOut, ")"); + break; + } +#endif /* SQLITE_OMIT_SUBQUERY */ + + /* + ** x BETWEEN y AND z + ** + ** This is equivalent to + ** + ** x>=y AND x<=z + ** + ** X is stored in pExpr->pLeft. + ** Y is stored in pExpr->pList->a[0].pExpr. + ** Z is stored in pExpr->pList->a[1].pExpr. + */ + case TK_BETWEEN: { + Expr *pX = pExpr->pLeft; + Expr *pY = pExpr->x.pList->a[0].pExpr; + Expr *pZ = pExpr->x.pList->a[1].pExpr; + sqlite3ExplainPrintf(pOut, "BETWEEN("); + sqlite3ExplainExpr(pOut, pX); + sqlite3ExplainPrintf(pOut, ","); + sqlite3ExplainExpr(pOut, pY); + sqlite3ExplainPrintf(pOut, ","); + sqlite3ExplainExpr(pOut, pZ); + sqlite3ExplainPrintf(pOut, ")"); + break; + } + case TK_TRIGGER: { + /* If the opcode is TK_TRIGGER, then the expression is a reference + ** to a column in the new.* or old.* pseudo-tables available to + ** trigger programs. In this case Expr.iTable is set to 1 for the + ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn + ** is set to the column of the pseudo-table to read, or to -1 to + ** read the rowid field. + */ + sqlite3ExplainPrintf(pOut, "%s(%d)", + pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn); + break; + } + case TK_CASE: { + sqlite3ExplainPrintf(pOut, "CASE("); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut, ","); + sqlite3ExplainExprList(pOut, pExpr->x.pList); + break; + } +#ifndef SQLITE_OMIT_TRIGGER + case TK_RAISE: { + const char *zType = "unk"; + switch( pExpr->affinity ){ + case OE_Rollback: zType = "rollback"; break; + case OE_Abort: zType = "abort"; break; + case OE_Fail: zType = "fail"; break; + case OE_Ignore: zType = "ignore"; break; + } + sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken); + break; + } +#endif + } + if( zBinOp ){ + sqlite3ExplainPrintf(pOut,"%s(", zBinOp); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut,","); + sqlite3ExplainExpr(pOut, pExpr->pRight); + sqlite3ExplainPrintf(pOut,")"); + }else if( zUniOp ){ + sqlite3ExplainPrintf(pOut,"%s(", zUniOp); + sqlite3ExplainExpr(pOut, pExpr->pLeft); + sqlite3ExplainPrintf(pOut,")"); + } +} +#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */ + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) +/* +** Generate a human-readable explanation of an expression list. +*/ +void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){ + int i; + if( pList==0 || pList->nExpr==0 ){ + sqlite3ExplainPrintf(pOut, "(empty-list)"); + return; + }else if( pList->nExpr==1 ){ + sqlite3ExplainExpr(pOut, pList->a[0].pExpr); + }else{ + sqlite3ExplainPush(pOut); + for(i=0; inExpr; i++){ + sqlite3ExplainPrintf(pOut, "item[%d] = ", i); + sqlite3ExplainPush(pOut); + sqlite3ExplainExpr(pOut, pList->a[i].pExpr); + sqlite3ExplainPop(pOut); + if( pList->a[i].zName ){ + sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName); + } + if( pList->a[i].bSpanIsTab ){ + sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan); + } + if( inExpr-1 ){ + sqlite3ExplainNL(pOut); + } + } + sqlite3ExplainPop(pOut); + } +} +#endif /* SQLITE_DEBUG */ + +/* +** Return TRUE if pExpr is an constant expression that is appropriate +** for factoring out of a loop. Appropriate expressions are: +** +** * Any expression that evaluates to two or more opcodes. +** +** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, +** or OP_Variable that does not need to be placed in a +** specific register. +** +** There is no point in factoring out single-instruction constant +** expressions that need to be placed in a particular register. +** We could factor them out, but then we would end up adding an +** OP_SCopy instruction to move the value into the correct register +** later. We might as well just use the original instruction and +** avoid the OP_SCopy. +*/ +static int isAppropriateForFactoring(Expr *p){ + if( !sqlite3ExprIsConstantNotJoin(p) ){ + return 0; /* Only constant expressions are appropriate for factoring */ + } + if( (p->flags & EP_FixedDest)==0 ){ + return 1; /* Any constant without a fixed destination is appropriate */ + } + while( p->op==TK_UPLUS ) p = p->pLeft; + switch( p->op ){ +#ifndef SQLITE_OMIT_BLOB_LITERAL + case TK_BLOB: +#endif + case TK_VARIABLE: + case TK_INTEGER: + case TK_FLOAT: + case TK_NULL: + case TK_STRING: { + testcase( p->op==TK_BLOB ); + testcase( p->op==TK_VARIABLE ); + testcase( p->op==TK_INTEGER ); + testcase( p->op==TK_FLOAT ); + testcase( p->op==TK_NULL ); + testcase( p->op==TK_STRING ); + /* Single-instruction constants with a fixed destination are + ** better done in-line. If we factor them, they will just end + ** up generating an OP_SCopy to move the value to the destination + ** register. */ + return 0; + } + case TK_UMINUS: { + if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){ + return 0; + } + break; + } + default: { + break; + } + } + return 1; +} + +/* +** If pExpr is a constant expression that is appropriate for +** factoring out of a loop, then evaluate the expression +** into a register and convert the expression into a TK_REGISTER +** expression. +*/ +static int evalConstExpr(Walker *pWalker, Expr *pExpr){ + Parse *pParse = pWalker->pParse; + switch( pExpr->op ){ + case TK_IN: + case TK_REGISTER: { + return WRC_Prune; + } + case TK_COLLATE: { + return WRC_Continue; + } + case TK_FUNCTION: + case TK_AGG_FUNCTION: + case TK_CONST_FUNC: { + /* The arguments to a function have a fixed destination. + ** Mark them this way to avoid generated unneeded OP_SCopy + ** instructions. + */ + ExprList *pList = pExpr->x.pList; + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + if( pList ){ + int i = pList->nExpr; + struct ExprList_item *pItem = pList->a; + for(; i>0; i--, pItem++){ + if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest; + } + } + break; + } + } + if( isAppropriateForFactoring(pExpr) ){ + int r1 = ++pParse->nMem; + int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); + /* If r2!=r1, it means that register r1 is never used. That is harmless + ** but suboptimal, so we want to know about the situation to fix it. + ** Hence the following assert: */ + assert( r2==r1 ); + exprToRegister(pExpr, r2); + return WRC_Prune; + } + return WRC_Continue; +} + +/* +** Preevaluate constant subexpressions within pExpr and store the +** results in registers. Modify pExpr so that the constant subexpresions +** are TK_REGISTER opcodes that refer to the precomputed values. +** +** This routine is a no-op if the jump to the cookie-check code has +** already occur. Since the cookie-check jump is generated prior to +** any other serious processing, this check ensures that there is no +** way to accidently bypass the constant initializations. +** +** This routine is also a no-op if the SQLITE_FactorOutConst optimization +** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS) +** interface. This allows test logic to verify that the same answer is +** obtained for queries regardless of whether or not constants are +** precomputed into registers or if they are inserted in-line. +*/ +void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){ + Walker w; + if( pParse->cookieGoto ) return; + if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return; + memset(&w, 0, sizeof(w)); + w.xExprCallback = evalConstExpr; + w.pParse = pParse; + sqlite3WalkExpr(&w, pExpr); +} + + +/* +** Generate code that pushes the value of every element of the given +** expression list into a sequence of registers beginning at target. +** +** Return the number of elements evaluated. +*/ +int sqlite3ExprCodeExprList( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* The expression list to be coded */ + int target, /* Where to write results */ + int doHardCopy /* Make a hard copy of every element */ +){ + struct ExprList_item *pItem; + int i, n; + assert( pList!=0 ); + assert( target>0 ); + assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */ + n = pList->nExpr; + for(pItem=pList->a, i=0; ipExpr; + int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); + if( inReg!=target+i ){ + sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy, + inReg, target+i); + } + } + return n; +} + +/* +** Generate code for a BETWEEN operator. +** +** x BETWEEN y AND z +** +** The above is equivalent to +** +** x>=y AND x<=z +** +** Code it as such, taking care to do the common subexpression +** elementation of x. +*/ +static void exprCodeBetween( + Parse *pParse, /* Parsing and code generating context */ + Expr *pExpr, /* The BETWEEN expression */ + int dest, /* Jump here if the jump is taken */ + int jumpIfTrue, /* Take the jump if the BETWEEN is true */ + int jumpIfNull /* Take the jump if the BETWEEN is NULL */ +){ + Expr exprAnd; /* The AND operator in x>=y AND x<=z */ + Expr compLeft; /* The x>=y term */ + Expr compRight; /* The x<=z term */ + Expr exprX; /* The x subexpression */ + int regFree1 = 0; /* Temporary use register */ + + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + exprX = *pExpr->pLeft; + exprAnd.op = TK_AND; + exprAnd.pLeft = &compLeft; + exprAnd.pRight = &compRight; + compLeft.op = TK_GE; + compLeft.pLeft = &exprX; + compLeft.pRight = pExpr->x.pList->a[0].pExpr; + compRight.op = TK_LE; + compRight.pLeft = &exprX; + compRight.pRight = pExpr->x.pList->a[1].pExpr; + exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, ®Free1)); + if( jumpIfTrue ){ + sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull); + }else{ + sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull); + } + sqlite3ReleaseTempReg(pParse, regFree1); + + /* Ensure adequate test coverage */ + testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 ); + testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 ); + testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 ); + testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 ); + testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 ); + testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 ); + testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 ); + testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 ); +} + +/* +** Generate code for a boolean expression such that a jump is made +** to the label "dest" if the expression is true but execution +** continues straight thru if the expression is false. +** +** If the expression evaluates to NULL (neither true nor false), then +** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. +** +** This code depends on the fact that certain token values (ex: TK_EQ) +** are the same as opcode values (ex: OP_Eq) that implement the corresponding +** operation. Special comments in vdbe.c and the mkopcodeh.awk script in +** the make process cause these values to align. Assert()s in the code +** below verify that the numbers are aligned correctly. +*/ +void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ + Vdbe *v = pParse->pVdbe; + int op = 0; + int regFree1 = 0; + int regFree2 = 0; + int r1, r2; + + assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); + if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ + if( NEVER(pExpr==0) ) return; /* No way this can happen */ + op = pExpr->op; + switch( op ){ + case TK_AND: { + int d2 = sqlite3VdbeMakeLabel(v); + testcase( jumpIfNull==0 ); + sqlite3ExprCachePush(pParse); + sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL); + sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); + sqlite3VdbeResolveLabel(v, d2); + sqlite3ExprCachePop(pParse, 1); + break; + } + case TK_OR: { + testcase( jumpIfNull==0 ); + sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); + sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); + break; + } + case TK_NOT: { + testcase( jumpIfNull==0 ); + sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); + break; + } + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_NE: + case TK_EQ: { + assert( TK_LT==OP_Lt ); + assert( TK_LE==OP_Le ); + assert( TK_GT==OP_Gt ); + assert( TK_GE==OP_Ge ); + assert( TK_EQ==OP_Eq ); + assert( TK_NE==OP_Ne ); + testcase( op==TK_LT ); + testcase( op==TK_LE ); + testcase( op==TK_GT ); + testcase( op==TK_GE ); + testcase( op==TK_EQ ); + testcase( op==TK_NE ); + testcase( jumpIfNull==0 ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, jumpIfNull); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_IS: + case TK_ISNOT: { + testcase( op==TK_IS ); + testcase( op==TK_ISNOT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + op = (op==TK_IS) ? TK_EQ : TK_NE; + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, SQLITE_NULLEQ); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_ISNULL: + case TK_NOTNULL: { + assert( TK_ISNULL==OP_IsNull ); + assert( TK_NOTNULL==OP_NotNull ); + testcase( op==TK_ISNULL ); + testcase( op==TK_NOTNULL ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + sqlite3VdbeAddOp2(v, op, r1, dest); + testcase( regFree1==0 ); + break; + } + case TK_BETWEEN: { + testcase( jumpIfNull==0 ); + exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull); + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_IN: { + int destIfFalse = sqlite3VdbeMakeLabel(v); + int destIfNull = jumpIfNull ? dest : destIfFalse; + sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); + sqlite3VdbeAddOp2(v, OP_Goto, 0, dest); + sqlite3VdbeResolveLabel(v, destIfFalse); + break; + } +#endif + default: { + r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); + sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); + testcase( regFree1==0 ); + testcase( jumpIfNull==0 ); + break; + } + } + sqlite3ReleaseTempReg(pParse, regFree1); + sqlite3ReleaseTempReg(pParse, regFree2); +} + +/* +** Generate code for a boolean expression such that a jump is made +** to the label "dest" if the expression is false but execution +** continues straight thru if the expression is true. +** +** If the expression evaluates to NULL (neither true nor false) then +** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull +** is 0. +*/ +void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ + Vdbe *v = pParse->pVdbe; + int op = 0; + int regFree1 = 0; + int regFree2 = 0; + int r1, r2; + + assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); + if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ + if( pExpr==0 ) return; + + /* The value of pExpr->op and op are related as follows: + ** + ** pExpr->op op + ** --------- ---------- + ** TK_ISNULL OP_NotNull + ** TK_NOTNULL OP_IsNull + ** TK_NE OP_Eq + ** TK_EQ OP_Ne + ** TK_GT OP_Le + ** TK_LE OP_Gt + ** TK_GE OP_Lt + ** TK_LT OP_Ge + ** + ** For other values of pExpr->op, op is undefined and unused. + ** The value of TK_ and OP_ constants are arranged such that we + ** can compute the mapping above using the following expression. + ** Assert()s verify that the computation is correct. + */ + op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); + + /* Verify correct alignment of TK_ and OP_ constants + */ + assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); + assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); + assert( pExpr->op!=TK_NE || op==OP_Eq ); + assert( pExpr->op!=TK_EQ || op==OP_Ne ); + assert( pExpr->op!=TK_LT || op==OP_Ge ); + assert( pExpr->op!=TK_LE || op==OP_Gt ); + assert( pExpr->op!=TK_GT || op==OP_Le ); + assert( pExpr->op!=TK_GE || op==OP_Lt ); + + switch( pExpr->op ){ + case TK_AND: { + testcase( jumpIfNull==0 ); + sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); + sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); + break; + } + case TK_OR: { + int d2 = sqlite3VdbeMakeLabel(v); + testcase( jumpIfNull==0 ); + sqlite3ExprCachePush(pParse); + sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL); + sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); + sqlite3VdbeResolveLabel(v, d2); + sqlite3ExprCachePop(pParse, 1); + break; + } + case TK_NOT: { + testcase( jumpIfNull==0 ); + sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); + break; + } + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_NE: + case TK_EQ: { + testcase( op==TK_LT ); + testcase( op==TK_LE ); + testcase( op==TK_GT ); + testcase( op==TK_GE ); + testcase( op==TK_EQ ); + testcase( op==TK_NE ); + testcase( jumpIfNull==0 ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, jumpIfNull); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_IS: + case TK_ISNOT: { + testcase( pExpr->op==TK_IS ); + testcase( pExpr->op==TK_ISNOT ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, SQLITE_NULLEQ); + testcase( regFree1==0 ); + testcase( regFree2==0 ); + break; + } + case TK_ISNULL: + case TK_NOTNULL: { + testcase( op==TK_ISNULL ); + testcase( op==TK_NOTNULL ); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + sqlite3VdbeAddOp2(v, op, r1, dest); + testcase( regFree1==0 ); + break; + } + case TK_BETWEEN: { + testcase( jumpIfNull==0 ); + exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull); + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_IN: { + if( jumpIfNull ){ + sqlite3ExprCodeIN(pParse, pExpr, dest, dest); + }else{ + int destIfNull = sqlite3VdbeMakeLabel(v); + sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); + sqlite3VdbeResolveLabel(v, destIfNull); + } + break; + } +#endif + default: { + r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); + sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); + testcase( regFree1==0 ); + testcase( jumpIfNull==0 ); + break; + } + } + sqlite3ReleaseTempReg(pParse, regFree1); + sqlite3ReleaseTempReg(pParse, regFree2); +} + +/* +** Do a deep comparison of two expression trees. Return 0 if the two +** expressions are completely identical. Return 1 if they differ only +** by a COLLATE operator at the top level. Return 2 if there are differences +** other than the top-level COLLATE operator. +** +** If any subelement of pB has Expr.iTable==(-1) then it is allowed +** to compare equal to an equivalent element in pA with Expr.iTable==iTab. +** +** The pA side might be using TK_REGISTER. If that is the case and pB is +** not using TK_REGISTER but is otherwise equivalent, then still return 0. +** +** Sometimes this routine will return 2 even if the two expressions +** really are equivalent. If we cannot prove that the expressions are +** identical, we return 2 just to be safe. So if this routine +** returns 2, then you do not really know for certain if the two +** expressions are the same. But if you get a 0 or 1 return, then you +** can be sure the expressions are the same. In the places where +** this routine is used, it does not hurt to get an extra 2 - that +** just might result in some slightly slower code. But returning +** an incorrect 0 or 1 could lead to a malfunction. +*/ +int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){ + if( pA==0||pB==0 ){ + return pB==pA ? 0 : 2; + } + assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) ); + assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) ); + if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){ + return 2; + } + if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2; + if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){ + if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){ + return 1; + } + if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){ + return 1; + } + return 2; + } + if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2; + if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2; + if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; + if( pA->iColumn!=pB->iColumn ) return 2; + if( pA->iTable!=pB->iTable + && pA->op!=TK_REGISTER + && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2; + if( ExprHasProperty(pA, EP_IntValue) ){ + if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){ + return 2; + } + }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){ + if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2; + if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ + return pA->op==TK_COLLATE ? 1 : 2; + } + } + return 0; +} + +/* +** Compare two ExprList objects. Return 0 if they are identical and +** non-zero if they differ in any way. +** +** If any subelement of pB has Expr.iTable==(-1) then it is allowed +** to compare equal to an equivalent element in pA with Expr.iTable==iTab. +** +** This routine might return non-zero for equivalent ExprLists. The +** only consequence will be disabled optimizations. But this routine +** must never return 0 if the two ExprList objects are different, or +** a malfunction will result. +** +** Two NULL pointers are considered to be the same. But a NULL pointer +** always differs from a non-NULL pointer. +*/ +int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ + int i; + if( pA==0 && pB==0 ) return 0; + if( pA==0 || pB==0 ) return 1; + if( pA->nExpr!=pB->nExpr ) return 1; + for(i=0; inExpr; i++){ + Expr *pExprA = pA->a[i].pExpr; + Expr *pExprB = pB->a[i].pExpr; + if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1; + if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1; + } + return 0; +} + +/* +** Return true if we can prove the pE2 will always be true if pE1 is +** true. Return false if we cannot complete the proof or if pE2 might +** be false. Examples: +** +** pE1: x==5 pE2: x==5 Result: true +** pE1: x>0 pE2: x==5 Result: false +** pE1: x=21 pE2: x=21 OR y=43 Result: true +** pE1: x!=123 pE2: x IS NOT NULL Result: true +** pE1: x!=?1 pE2: x IS NOT NULL Result: true +** pE1: x IS NULL pE2: x IS NOT NULL Result: false +** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false +** +** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has +** Expr.iTable<0 then assume a table number given by iTab. +** +** When in doubt, return false. Returning true might give a performance +** improvement. Returning false might cause a performance reduction, but +** it will always give the correct answer and is hence always safe. +*/ +int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){ + if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){ + return 1; + } + if( pE2->op==TK_OR + && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab) + || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) ) + ){ + return 1; + } + if( pE2->op==TK_NOTNULL + && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0 + && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS) + ){ + return 1; + } + return 0; +} + +/* +** An instance of the following structure is used by the tree walker +** to count references to table columns in the arguments of an +** aggregate function, in order to implement the +** sqlite3FunctionThisSrc() routine. +*/ +struct SrcCount { + SrcList *pSrc; /* One particular FROM clause in a nested query */ + int nThis; /* Number of references to columns in pSrcList */ + int nOther; /* Number of references to columns in other FROM clauses */ +}; + +/* +** Count the number of references to columns. +*/ +static int exprSrcCount(Walker *pWalker, Expr *pExpr){ + /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc() + ** is always called before sqlite3ExprAnalyzeAggregates() and so the + ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If + ** sqlite3FunctionUsesThisSrc() is used differently in the future, the + ** NEVER() will need to be removed. */ + if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){ + int i; + struct SrcCount *p = pWalker->u.pSrcCount; + SrcList *pSrc = p->pSrc; + for(i=0; inSrc; i++){ + if( pExpr->iTable==pSrc->a[i].iCursor ) break; + } + if( inSrc ){ + p->nThis++; + }else{ + p->nOther++; + } + } + return WRC_Continue; +} + +/* +** Determine if any of the arguments to the pExpr Function reference +** pSrcList. Return true if they do. Also return true if the function +** has no arguments or has only constant arguments. Return false if pExpr +** references columns but not columns of tables found in pSrcList. +*/ +int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ + Walker w; + struct SrcCount cnt; + assert( pExpr->op==TK_AGG_FUNCTION ); + memset(&w, 0, sizeof(w)); + w.xExprCallback = exprSrcCount; + w.u.pSrcCount = &cnt; + cnt.pSrc = pSrcList; + cnt.nThis = 0; + cnt.nOther = 0; + sqlite3WalkExprList(&w, pExpr->x.pList); + return cnt.nThis>0 || cnt.nOther==0; +} + +/* +** Add a new element to the pAggInfo->aCol[] array. Return the index of +** the new element. Return a negative number if malloc fails. +*/ +static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ + int i; + pInfo->aCol = sqlite3ArrayAllocate( + db, + pInfo->aCol, + sizeof(pInfo->aCol[0]), + &pInfo->nColumn, + &i + ); + return i; +} + +/* +** Add a new element to the pAggInfo->aFunc[] array. Return the index of +** the new element. Return a negative number if malloc fails. +*/ +static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ + int i; + pInfo->aFunc = sqlite3ArrayAllocate( + db, + pInfo->aFunc, + sizeof(pInfo->aFunc[0]), + &pInfo->nFunc, + &i + ); + return i; +} + +/* +** This is the xExprCallback for a tree walker. It is used to +** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates +** for additional information. +*/ +static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ + int i; + NameContext *pNC = pWalker->u.pNC; + Parse *pParse = pNC->pParse; + SrcList *pSrcList = pNC->pSrcList; + AggInfo *pAggInfo = pNC->pAggInfo; + + switch( pExpr->op ){ + case TK_AGG_COLUMN: + case TK_COLUMN: { + testcase( pExpr->op==TK_AGG_COLUMN ); + testcase( pExpr->op==TK_COLUMN ); + /* Check to see if the column is in one of the tables in the FROM + ** clause of the aggregate query */ + if( ALWAYS(pSrcList!=0) ){ + struct SrcList_item *pItem = pSrcList->a; + for(i=0; inSrc; i++, pItem++){ + struct AggInfo_col *pCol; + assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); + if( pExpr->iTable==pItem->iCursor ){ + /* If we reach this point, it means that pExpr refers to a table + ** that is in the FROM clause of the aggregate query. + ** + ** Make an entry for the column in pAggInfo->aCol[] if there + ** is not an entry there already. + */ + int k; + pCol = pAggInfo->aCol; + for(k=0; knColumn; k++, pCol++){ + if( pCol->iTable==pExpr->iTable && + pCol->iColumn==pExpr->iColumn ){ + break; + } + } + if( (k>=pAggInfo->nColumn) + && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 + ){ + pCol = &pAggInfo->aCol[k]; + pCol->pTab = pExpr->pTab; + pCol->iTable = pExpr->iTable; + pCol->iColumn = pExpr->iColumn; + pCol->iMem = ++pParse->nMem; + pCol->iSorterColumn = -1; + pCol->pExpr = pExpr; + if( pAggInfo->pGroupBy ){ + int j, n; + ExprList *pGB = pAggInfo->pGroupBy; + struct ExprList_item *pTerm = pGB->a; + n = pGB->nExpr; + for(j=0; jpExpr; + if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable && + pE->iColumn==pExpr->iColumn ){ + pCol->iSorterColumn = j; + break; + } + } + } + if( pCol->iSorterColumn<0 ){ + pCol->iSorterColumn = pAggInfo->nSortingColumn++; + } + } + /* There is now an entry for pExpr in pAggInfo->aCol[] (either + ** because it was there before or because we just created it). + ** Convert the pExpr to be a TK_AGG_COLUMN referring to that + ** pAggInfo->aCol[] entry. + */ + ExprSetVVAProperty(pExpr, EP_NoReduce); + pExpr->pAggInfo = pAggInfo; + pExpr->op = TK_AGG_COLUMN; + pExpr->iAgg = (i16)k; + break; + } /* endif pExpr->iTable==pItem->iCursor */ + } /* end loop over pSrcList */ + } + return WRC_Prune; + } + case TK_AGG_FUNCTION: { + if( (pNC->ncFlags & NC_InAggFunc)==0 + && pWalker->walkerDepth==pExpr->op2 + ){ + /* Check to see if pExpr is a duplicate of another aggregate + ** function that is already in the pAggInfo structure + */ + struct AggInfo_func *pItem = pAggInfo->aFunc; + for(i=0; inFunc; i++, pItem++){ + if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){ + break; + } + } + if( i>=pAggInfo->nFunc ){ + /* pExpr is original. Make a new entry in pAggInfo->aFunc[] + */ + u8 enc = ENC(pParse->db); + i = addAggInfoFunc(pParse->db, pAggInfo); + if( i>=0 ){ + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + pItem = &pAggInfo->aFunc[i]; + pItem->pExpr = pExpr; + pItem->iMem = ++pParse->nMem; + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + pItem->pFunc = sqlite3FindFunction(pParse->db, + pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken), + pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0); + if( pExpr->flags & EP_Distinct ){ + pItem->iDistinct = pParse->nTab++; + }else{ + pItem->iDistinct = -1; + } + } + } + /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry + */ + assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); + ExprSetVVAProperty(pExpr, EP_NoReduce); + pExpr->iAgg = (i16)i; + pExpr->pAggInfo = pAggInfo; + return WRC_Prune; + }else{ + return WRC_Continue; + } + } + } + return WRC_Continue; +} +static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){ + UNUSED_PARAMETER(pWalker); + UNUSED_PARAMETER(pSelect); + return WRC_Continue; +} + +/* +** Analyze the pExpr expression looking for aggregate functions and +** for variables that need to be added to AggInfo object that pNC->pAggInfo +** points to. Additional entries are made on the AggInfo object as +** necessary. +** +** This routine should only be called after the expression has been +** analyzed by sqlite3ResolveExprNames(). +*/ +void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ + Walker w; + memset(&w, 0, sizeof(w)); + w.xExprCallback = analyzeAggregate; + w.xSelectCallback = analyzeAggregatesInSelect; + w.u.pNC = pNC; + assert( pNC->pSrcList!=0 ); + sqlite3WalkExpr(&w, pExpr); +} + +/* +** Call sqlite3ExprAnalyzeAggregates() for every expression in an +** expression list. Return the number of errors. +** +** If an error is found, the analysis is cut short. +*/ +void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ + struct ExprList_item *pItem; + int i; + if( pList ){ + for(pItem=pList->a, i=0; inExpr; i++, pItem++){ + sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); + } + } +} + +/* +** Allocate a single new register for use to hold some intermediate result. +*/ +int sqlite3GetTempReg(Parse *pParse){ + if( pParse->nTempReg==0 ){ + return ++pParse->nMem; + } + return pParse->aTempReg[--pParse->nTempReg]; +} + +/* +** Deallocate a register, making available for reuse for some other +** purpose. +** +** If a register is currently being used by the column cache, then +** the dallocation is deferred until the column cache line that uses +** the register becomes stale. +*/ +void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ + if( iReg && pParse->nTempRegaTempReg) ){ + int i; + struct yColCache *p; + for(i=0, p=pParse->aColCache; iiReg==iReg ){ + p->tempReg = 1; + return; + } + } + pParse->aTempReg[pParse->nTempReg++] = iReg; + } +} + +/* +** Allocate or deallocate a block of nReg consecutive registers +*/ +int sqlite3GetTempRange(Parse *pParse, int nReg){ + int i, n; + i = pParse->iRangeReg; + n = pParse->nRangeReg; + if( nReg<=n ){ + assert( !usedAsColumnCache(pParse, i, i+n-1) ); + pParse->iRangeReg += nReg; + pParse->nRangeReg -= nReg; + }else{ + i = pParse->nMem+1; + pParse->nMem += nReg; + } + return i; +} +void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ + sqlite3ExprCacheRemove(pParse, iReg, nReg); + if( nReg>pParse->nRangeReg ){ + pParse->nRangeReg = nReg; + pParse->iRangeReg = iReg; + } +} + +/* +** Mark all temporary registers as being unavailable for reuse. +*/ +void sqlite3ClearTempRegCache(Parse *pParse){ + pParse->nTempReg = 0; + pParse->nRangeReg = 0; +} diff --git a/components/external/SQLite-3.8.1/src/fault.c b/components/external/SQLite-3.8.1/src/fault.c new file mode 100644 index 0000000000000000000000000000000000000000..c3028c4f936edf96712dbe73a07662f0a26b1d0a --- /dev/null +++ b/components/external/SQLite-3.8.1/src/fault.c @@ -0,0 +1,87 @@ +/* +** 2008 Jan 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code to support the concept of "benign" +** malloc failures (when the xMalloc() or xRealloc() method of the +** sqlite3_mem_methods structure fails to allocate a block of memory +** and returns 0). +** +** Most malloc failures are non-benign. After they occur, SQLite +** abandons the current operation and returns an error code (usually +** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily +** fatal. For example, if a malloc fails while resizing a hash table, this +** is completely recoverable simply by not carrying out the resize. The +** hash table will continue to function normally. So a malloc failure +** during a hash table resize is a benign fault. +*/ + +#include "sqliteInt.h" + +#ifndef SQLITE_OMIT_BUILTIN_TEST + +/* +** Global variables. +*/ +typedef struct BenignMallocHooks BenignMallocHooks; +static SQLITE_WSD struct BenignMallocHooks { + void (*xBenignBegin)(void); + void (*xBenignEnd)(void); +} sqlite3Hooks = { 0, 0 }; + +/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks +** structure. If writable static data is unsupported on the target, +** we have to locate the state vector at run-time. In the more common +** case where writable static data is supported, wsdHooks can refer directly +** to the "sqlite3Hooks" state vector declared above. +*/ +#ifdef SQLITE_OMIT_WSD +# define wsdHooksInit \ + BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks) +# define wsdHooks x[0] +#else +# define wsdHooksInit +# define wsdHooks sqlite3Hooks +#endif + + +/* +** Register hooks to call when sqlite3BeginBenignMalloc() and +** sqlite3EndBenignMalloc() are called, respectively. +*/ +void sqlite3BenignMallocHooks( + void (*xBenignBegin)(void), + void (*xBenignEnd)(void) +){ + wsdHooksInit; + wsdHooks.xBenignBegin = xBenignBegin; + wsdHooks.xBenignEnd = xBenignEnd; +} + +/* +** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that +** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc() +** indicates that subsequent malloc failures are non-benign. +*/ +void sqlite3BeginBenignMalloc(void){ + wsdHooksInit; + if( wsdHooks.xBenignBegin ){ + wsdHooks.xBenignBegin(); + } +} +void sqlite3EndBenignMalloc(void){ + wsdHooksInit; + if( wsdHooks.xBenignEnd ){ + wsdHooks.xBenignEnd(); + } +} + +#endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */ diff --git a/components/external/SQLite-3.8.1/src/fkey.c b/components/external/SQLite-3.8.1/src/fkey.c new file mode 100644 index 0000000000000000000000000000000000000000..5c49ded876ddc7e1ca3d8662d24cdcceae0e0089 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/fkey.c @@ -0,0 +1,1305 @@ +/* +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used by the compiler to add foreign key +** support to compiled SQL statements. +*/ +#include "sqliteInt.h" + +#ifndef SQLITE_OMIT_FOREIGN_KEY +#ifndef SQLITE_OMIT_TRIGGER + +/* +** Deferred and Immediate FKs +** -------------------------- +** +** Foreign keys in SQLite come in two flavours: deferred and immediate. +** If an immediate foreign key constraint is violated, +** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current +** statement transaction rolled back. If a +** deferred foreign key constraint is violated, no action is taken +** immediately. However if the application attempts to commit the +** transaction before fixing the constraint violation, the attempt fails. +** +** Deferred constraints are implemented using a simple counter associated +** with the database handle. The counter is set to zero each time a +** database transaction is opened. Each time a statement is executed +** that causes a foreign key violation, the counter is incremented. Each +** time a statement is executed that removes an existing violation from +** the database, the counter is decremented. When the transaction is +** committed, the commit fails if the current value of the counter is +** greater than zero. This scheme has two big drawbacks: +** +** * When a commit fails due to a deferred foreign key constraint, +** there is no way to tell which foreign constraint is not satisfied, +** or which row it is not satisfied for. +** +** * If the database contains foreign key violations when the +** transaction is opened, this may cause the mechanism to malfunction. +** +** Despite these problems, this approach is adopted as it seems simpler +** than the alternatives. +** +** INSERT operations: +** +** I.1) For each FK for which the table is the child table, search +** the parent table for a match. If none is found increment the +** constraint counter. +** +** I.2) For each FK for which the table is the parent table, +** search the child table for rows that correspond to the new +** row in the parent table. Decrement the counter for each row +** found (as the constraint is now satisfied). +** +** DELETE operations: +** +** D.1) For each FK for which the table is the child table, +** search the parent table for a row that corresponds to the +** deleted row in the child table. If such a row is not found, +** decrement the counter. +** +** D.2) For each FK for which the table is the parent table, search +** the child table for rows that correspond to the deleted row +** in the parent table. For each found increment the counter. +** +** UPDATE operations: +** +** An UPDATE command requires that all 4 steps above are taken, but only +** for FK constraints for which the affected columns are actually +** modified (values must be compared at runtime). +** +** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2. +** This simplifies the implementation a bit. +** +** For the purposes of immediate FK constraints, the OR REPLACE conflict +** resolution is considered to delete rows before the new row is inserted. +** If a delete caused by OR REPLACE violates an FK constraint, an exception +** is thrown, even if the FK constraint would be satisfied after the new +** row is inserted. +** +** Immediate constraints are usually handled similarly. The only difference +** is that the counter used is stored as part of each individual statement +** object (struct Vdbe). If, after the statement has run, its immediate +** constraint counter is greater than zero, +** it returns SQLITE_CONSTRAINT_FOREIGNKEY +** and the statement transaction is rolled back. An exception is an INSERT +** statement that inserts a single row only (no triggers). In this case, +** instead of using a counter, an exception is thrown immediately if the +** INSERT violates a foreign key constraint. This is necessary as such +** an INSERT does not open a statement transaction. +** +** TODO: How should dropping a table be handled? How should renaming a +** table be handled? +** +** +** Query API Notes +** --------------- +** +** Before coding an UPDATE or DELETE row operation, the code-generator +** for those two operations needs to know whether or not the operation +** requires any FK processing and, if so, which columns of the original +** row are required by the FK processing VDBE code (i.e. if FKs were +** implemented using triggers, which of the old.* columns would be +** accessed). No information is required by the code-generator before +** coding an INSERT operation. The functions used by the UPDATE/DELETE +** generation code to query for this information are: +** +** sqlite3FkRequired() - Test to see if FK processing is required. +** sqlite3FkOldmask() - Query for the set of required old.* columns. +** +** +** Externally accessible module functions +** -------------------------------------- +** +** sqlite3FkCheck() - Check for foreign key violations. +** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions. +** sqlite3FkDelete() - Delete an FKey structure. +*/ + +/* +** VDBE Calling Convention +** ----------------------- +** +** Example: +** +** For the following INSERT statement: +** +** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c); +** INSERT INTO t1 VALUES(1, 2, 3.1); +** +** Register (x): 2 (type integer) +** Register (x+1): 1 (type integer) +** Register (x+2): NULL (type NULL) +** Register (x+3): 3.1 (type real) +*/ + +/* +** A foreign key constraint requires that the key columns in the parent +** table are collectively subject to a UNIQUE or PRIMARY KEY constraint. +** Given that pParent is the parent table for foreign key constraint pFKey, +** search the schema for a unique index on the parent key columns. +** +** If successful, zero is returned. If the parent key is an INTEGER PRIMARY +** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx +** is set to point to the unique index. +** +** If the parent key consists of a single column (the foreign key constraint +** is not a composite foreign key), output variable *paiCol is set to NULL. +** Otherwise, it is set to point to an allocated array of size N, where +** N is the number of columns in the parent key. The first element of the +** array is the index of the child table column that is mapped by the FK +** constraint to the parent table column stored in the left-most column +** of index *ppIdx. The second element of the array is the index of the +** child table column that corresponds to the second left-most column of +** *ppIdx, and so on. +** +** If the required index cannot be found, either because: +** +** 1) The named parent key columns do not exist, or +** +** 2) The named parent key columns do exist, but are not subject to a +** UNIQUE or PRIMARY KEY constraint, or +** +** 3) No parent key columns were provided explicitly as part of the +** foreign key definition, and the parent table does not have a +** PRIMARY KEY, or +** +** 4) No parent key columns were provided explicitly as part of the +** foreign key definition, and the PRIMARY KEY of the parent table +** consists of a a different number of columns to the child key in +** the child table. +** +** then non-zero is returned, and a "foreign key mismatch" error loaded +** into pParse. If an OOM error occurs, non-zero is returned and the +** pParse->db->mallocFailed flag is set. +*/ +int sqlite3FkLocateIndex( + Parse *pParse, /* Parse context to store any error in */ + Table *pParent, /* Parent table of FK constraint pFKey */ + FKey *pFKey, /* Foreign key to find index for */ + Index **ppIdx, /* OUT: Unique index on parent table */ + int **paiCol /* OUT: Map of index columns in pFKey */ +){ + Index *pIdx = 0; /* Value to return via *ppIdx */ + int *aiCol = 0; /* Value to return via *paiCol */ + int nCol = pFKey->nCol; /* Number of columns in parent key */ + char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */ + + /* The caller is responsible for zeroing output parameters. */ + assert( ppIdx && *ppIdx==0 ); + assert( !paiCol || *paiCol==0 ); + assert( pParse ); + + /* If this is a non-composite (single column) foreign key, check if it + ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx + ** and *paiCol set to zero and return early. + ** + ** Otherwise, for a composite foreign key (more than one column), allocate + ** space for the aiCol array (returned via output parameter *paiCol). + ** Non-composite foreign keys do not require the aiCol array. + */ + if( nCol==1 ){ + /* The FK maps to the IPK if any of the following are true: + ** + ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly + ** mapped to the primary key of table pParent, or + ** 2) The FK is explicitly mapped to a column declared as INTEGER + ** PRIMARY KEY. + */ + if( pParent->iPKey>=0 ){ + if( !zKey ) return 0; + if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0; + } + }else if( paiCol ){ + assert( nCol>1 ); + aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int)); + if( !aiCol ) return 1; + *paiCol = aiCol; + } + + for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ + /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number + ** of columns. If each indexed column corresponds to a foreign key + ** column of pFKey, then this index is a winner. */ + + if( zKey==0 ){ + /* If zKey is NULL, then this foreign key is implicitly mapped to + ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be + ** identified by the test (Index.autoIndex==2). */ + if( pIdx->autoIndex==2 ){ + if( aiCol ){ + int i; + for(i=0; iaCol[i].iFrom; + } + break; + } + }else{ + /* If zKey is non-NULL, then this foreign key was declared to + ** map to an explicit list of columns in table pParent. Check if this + ** index matches those columns. Also, check that the index uses + ** the default collation sequences for each column. */ + int i, j; + for(i=0; iaiColumn[i]; /* Index of column in parent tbl */ + char *zDfltColl; /* Def. collation for column */ + char *zIdxCol; /* Name of indexed column */ + + /* If the index uses a collation sequence that is different from + ** the default collation sequence for the column, this index is + ** unusable. Bail out early in this case. */ + zDfltColl = pParent->aCol[iCol].zColl; + if( !zDfltColl ){ + zDfltColl = "BINARY"; + } + if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break; + + zIdxCol = pParent->aCol[iCol].zName; + for(j=0; jaCol[j].zCol, zIdxCol)==0 ){ + if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom; + break; + } + } + if( j==nCol ) break; + } + if( i==nCol ) break; /* pIdx is usable */ + } + } + } + + if( !pIdx ){ + if( !pParse->disableTriggers ){ + sqlite3ErrorMsg(pParse, + "foreign key mismatch - \"%w\" referencing \"%w\"", + pFKey->pFrom->zName, pFKey->zTo); + } + sqlite3DbFree(pParse->db, aiCol); + return 1; + } + + *ppIdx = pIdx; + return 0; +} + +/* +** This function is called when a row is inserted into or deleted from the +** child table of foreign key constraint pFKey. If an SQL UPDATE is executed +** on the child table of pFKey, this function is invoked twice for each row +** affected - once to "delete" the old row, and then again to "insert" the +** new row. +** +** Each time it is called, this function generates VDBE code to locate the +** row in the parent table that corresponds to the row being inserted into +** or deleted from the child table. If the parent row can be found, no +** special action is taken. Otherwise, if the parent row can *not* be +** found in the parent table: +** +** Operation | FK type | Action taken +** -------------------------------------------------------------------------- +** INSERT immediate Increment the "immediate constraint counter". +** +** DELETE immediate Decrement the "immediate constraint counter". +** +** INSERT deferred Increment the "deferred constraint counter". +** +** DELETE deferred Decrement the "deferred constraint counter". +** +** These operations are identified in the comment at the top of this file +** (fkey.c) as "I.1" and "D.1". +*/ +static void fkLookupParent( + Parse *pParse, /* Parse context */ + int iDb, /* Index of database housing pTab */ + Table *pTab, /* Parent table of FK pFKey */ + Index *pIdx, /* Unique index on parent key columns in pTab */ + FKey *pFKey, /* Foreign key constraint */ + int *aiCol, /* Map from parent key columns to child table columns */ + int regData, /* Address of array containing child table row */ + int nIncr, /* Increment constraint counter by this */ + int isIgnore /* If true, pretend pTab contains all NULL values */ +){ + int i; /* Iterator variable */ + Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */ + int iCur = pParse->nTab - 1; /* Cursor number to use */ + int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */ + + /* If nIncr is less than zero, then check at runtime if there are any + ** outstanding constraints to resolve. If there are not, there is no need + ** to check if deleting this row resolves any outstanding violations. + ** + ** Check if any of the key columns in the child table row are NULL. If + ** any are, then the constraint is considered satisfied. No need to + ** search for a matching row in the parent table. */ + if( nIncr<0 ){ + sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk); + } + for(i=0; inCol; i++){ + int iReg = aiCol[i] + regData + 1; + sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); + } + + if( isIgnore==0 ){ + if( pIdx==0 ){ + /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY + ** column of the parent table (table pTab). */ + int iMustBeInt; /* Address of MustBeInt instruction */ + int regTemp = sqlite3GetTempReg(pParse); + + /* Invoke MustBeInt to coerce the child key value to an integer (i.e. + ** apply the affinity of the parent key). If this fails, then there + ** is no matching parent key. Before using MustBeInt, make a copy of + ** the value. Otherwise, the value inserted into the child key column + ** will have INTEGER affinity applied to it, which may not be correct. */ + sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp); + iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0); + + /* If the parent table is the same as the child table, and we are about + ** to increment the constraint-counter (i.e. this is an INSERT operation), + ** then check if the row being inserted matches itself. If so, do not + ** increment the constraint-counter. */ + if( pTab==pFKey->pFrom && nIncr==1 ){ + sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); + } + + sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); + sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk); + sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); + sqlite3VdbeJumpHere(v, iMustBeInt); + sqlite3ReleaseTempReg(pParse, regTemp); + }else{ + int nCol = pFKey->nCol; + int regTemp = sqlite3GetTempRange(pParse, nCol); + int regRec = sqlite3GetTempReg(pParse); + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + + sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); + sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); + for(i=0; ipFrom && nIncr==1 ){ + int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1; + for(i=0; iaiColumn[i]+1+regData; + assert( aiCol[i]!=pTab->iPKey ); + if( pIdx->aiColumn[i]==pTab->iPKey ){ + /* The parent key is a composite key that includes the IPK column */ + iParent = regData; + } + sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); + sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); + } + sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk); + } + + sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec); + sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT); + sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); + + sqlite3ReleaseTempReg(pParse, regRec); + sqlite3ReleaseTempRange(pParse, regTemp, nCol); + } + } + + if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs) + && !pParse->pToplevel + && !pParse->isMultiWrite + ){ + /* Special case: If this is an INSERT statement that will insert exactly + ** one row into the table, raise a constraint immediately instead of + ** incrementing a counter. This is necessary as the VM code is being + ** generated for will not open a statement transaction. */ + assert( nIncr==1 ); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, + OE_Abort, "foreign key constraint failed", P4_STATIC + ); + }else{ + if( nIncr>0 && pFKey->isDeferred==0 ){ + sqlite3ParseToplevel(pParse)->mayAbort = 1; + } + sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); + } + + sqlite3VdbeResolveLabel(v, iOk); + sqlite3VdbeAddOp1(v, OP_Close, iCur); +} + +/* +** This function is called to generate code executed when a row is deleted +** from the parent table of foreign key constraint pFKey and, if pFKey is +** deferred, when a row is inserted into the same table. When generating +** code for an SQL UPDATE operation, this function may be called twice - +** once to "delete" the old row and once to "insert" the new row. +** +** The code generated by this function scans through the rows in the child +** table that correspond to the parent table row being deleted or inserted. +** For each child row found, one of the following actions is taken: +** +** Operation | FK type | Action taken +** -------------------------------------------------------------------------- +** DELETE immediate Increment the "immediate constraint counter". +** Or, if the ON (UPDATE|DELETE) action is RESTRICT, +** throw a "foreign key constraint failed" exception. +** +** INSERT immediate Decrement the "immediate constraint counter". +** +** DELETE deferred Increment the "deferred constraint counter". +** Or, if the ON (UPDATE|DELETE) action is RESTRICT, +** throw a "foreign key constraint failed" exception. +** +** INSERT deferred Decrement the "deferred constraint counter". +** +** These operations are identified in the comment at the top of this file +** (fkey.c) as "I.2" and "D.2". +*/ +static void fkScanChildren( + Parse *pParse, /* Parse context */ + SrcList *pSrc, /* SrcList containing the table to scan */ + Table *pTab, + Index *pIdx, /* Foreign key index */ + FKey *pFKey, /* Foreign key relationship */ + int *aiCol, /* Map from pIdx cols to child table cols */ + int regData, /* Referenced table data starts here */ + int nIncr /* Amount to increment deferred counter by */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + int i; /* Iterator variable */ + Expr *pWhere = 0; /* WHERE clause to scan with */ + NameContext sNameContext; /* Context used to resolve WHERE clause */ + WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */ + int iFkIfZero = 0; /* Address of OP_FkIfZero */ + Vdbe *v = sqlite3GetVdbe(pParse); + + assert( !pIdx || pIdx->pTable==pTab ); + + if( nIncr<0 ){ + iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0); + } + + /* Create an Expr object representing an SQL expression like: + ** + ** = AND = ... + ** + ** The collation sequence used for the comparison should be that of + ** the parent key columns. The affinity of the parent key column should + ** be applied to each child key value before the comparison takes place. + */ + for(i=0; inCol; i++){ + Expr *pLeft; /* Value from parent table row */ + Expr *pRight; /* Column ref to child table */ + Expr *pEq; /* Expression (pLeft = pRight) */ + int iCol; /* Index of column in child table */ + const char *zCol; /* Name of column in child table */ + + pLeft = sqlite3Expr(db, TK_REGISTER, 0); + if( pLeft ){ + /* Set the collation sequence and affinity of the LHS of each TK_EQ + ** expression to the parent key column defaults. */ + if( pIdx ){ + Column *pCol; + const char *zColl; + iCol = pIdx->aiColumn[i]; + pCol = &pTab->aCol[iCol]; + if( pTab->iPKey==iCol ) iCol = -1; + pLeft->iTable = regData+iCol+1; + pLeft->affinity = pCol->affinity; + zColl = pCol->zColl; + if( zColl==0 ) zColl = db->pDfltColl->zName; + pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl); + }else{ + pLeft->iTable = regData; + pLeft->affinity = SQLITE_AFF_INTEGER; + } + } + iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; + assert( iCol>=0 ); + zCol = pFKey->pFrom->aCol[iCol].zName; + pRight = sqlite3Expr(db, TK_ID, zCol); + pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); + pWhere = sqlite3ExprAnd(db, pWhere, pEq); + } + + /* If the child table is the same as the parent table, and this scan + ** is taking place as part of a DELETE operation (operation D.2), omit the + ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE + ** clause, where $rowid is the rowid of the row being deleted. */ + if( pTab==pFKey->pFrom && nIncr>0 ){ + Expr *pEq; /* Expression (pLeft = pRight) */ + Expr *pLeft; /* Value from parent table row */ + Expr *pRight; /* Column ref to child table */ + pLeft = sqlite3Expr(db, TK_REGISTER, 0); + pRight = sqlite3Expr(db, TK_COLUMN, 0); + if( pLeft && pRight ){ + pLeft->iTable = regData; + pLeft->affinity = SQLITE_AFF_INTEGER; + pRight->iTable = pSrc->a[0].iCursor; + pRight->iColumn = -1; + } + pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0); + pWhere = sqlite3ExprAnd(db, pWhere, pEq); + } + + /* Resolve the references in the WHERE clause. */ + memset(&sNameContext, 0, sizeof(NameContext)); + sNameContext.pSrcList = pSrc; + sNameContext.pParse = pParse; + sqlite3ResolveExprNames(&sNameContext, pWhere); + + /* Create VDBE to loop through the entries in pSrc that match the WHERE + ** clause. If the constraint is not deferred, throw an exception for + ** each row found. Otherwise, for deferred constraints, increment the + ** deferred constraint counter by nIncr for each row selected. */ + pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0); + if( nIncr>0 && pFKey->isDeferred==0 ){ + sqlite3ParseToplevel(pParse)->mayAbort = 1; + } + sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); + if( pWInfo ){ + sqlite3WhereEnd(pWInfo); + } + + /* Clean up the WHERE clause constructed above. */ + sqlite3ExprDelete(db, pWhere); + if( iFkIfZero ){ + sqlite3VdbeJumpHere(v, iFkIfZero); + } +} + +/* +** This function returns a pointer to the head of a linked list of FK +** constraints for which table pTab is the parent table. For example, +** given the following schema: +** +** CREATE TABLE t1(a PRIMARY KEY); +** CREATE TABLE t2(b REFERENCES t1(a); +** +** Calling this function with table "t1" as an argument returns a pointer +** to the FKey structure representing the foreign key constraint on table +** "t2". Calling this function with "t2" as the argument would return a +** NULL pointer (as there are no FK constraints for which t2 is the parent +** table). +*/ +FKey *sqlite3FkReferences(Table *pTab){ + int nName = sqlite3Strlen30(pTab->zName); + return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName); +} + +/* +** The second argument is a Trigger structure allocated by the +** fkActionTrigger() routine. This function deletes the Trigger structure +** and all of its sub-components. +** +** The Trigger structure or any of its sub-components may be allocated from +** the lookaside buffer belonging to database handle dbMem. +*/ +static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ + if( p ){ + TriggerStep *pStep = p->step_list; + sqlite3ExprDelete(dbMem, pStep->pWhere); + sqlite3ExprListDelete(dbMem, pStep->pExprList); + sqlite3SelectDelete(dbMem, pStep->pSelect); + sqlite3ExprDelete(dbMem, p->pWhen); + sqlite3DbFree(dbMem, p); + } +} + +/* +** This function is called to generate code that runs when table pTab is +** being dropped from the database. The SrcList passed as the second argument +** to this function contains a single entry guaranteed to resolve to +** table pTab. +** +** Normally, no code is required. However, if either +** +** (a) The table is the parent table of a FK constraint, or +** (b) The table is the child table of a deferred FK constraint and it is +** determined at runtime that there are outstanding deferred FK +** constraint violations in the database, +** +** then the equivalent of "DELETE FROM " is executed before dropping +** the table from the database. Triggers are disabled while running this +** DELETE, but foreign key actions are not. +*/ +void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){ + sqlite3 *db = pParse->db; + if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){ + int iSkip = 0; + Vdbe *v = sqlite3GetVdbe(pParse); + + assert( v ); /* VDBE has already been allocated */ + if( sqlite3FkReferences(pTab)==0 ){ + /* Search for a deferred foreign key constraint for which this table + ** is the child table. If one cannot be found, return without + ** generating any VDBE code. If one can be found, then jump over + ** the entire DELETE if there are no outstanding deferred constraints + ** when this statement is run. */ + FKey *p; + for(p=pTab->pFKey; p; p=p->pNextFrom){ + if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break; + } + if( !p ) return; + iSkip = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); + } + + pParse->disableTriggers = 1; + sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0); + pParse->disableTriggers = 0; + + /* If the DELETE has generated immediate foreign key constraint + ** violations, halt the VDBE and return an error at this point, before + ** any modifications to the schema are made. This is because statement + ** transactions are not able to rollback schema changes. + ** + ** If the SQLITE_DeferFKs flag is set, then this is not required, as + ** the statement transaction will not be rolled back even if FK + ** constraints are violated. + */ + if( (db->flags & SQLITE_DeferFKs)==0 ){ + sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, + OE_Abort, "foreign key constraint failed", P4_STATIC + ); + } + + if( iSkip ){ + sqlite3VdbeResolveLabel(v, iSkip); + } + } +} + + +/* +** The second argument points to an FKey object representing a foreign key +** for which pTab is the child table. An UPDATE statement against pTab +** is currently being processed. For each column of the table that is +** actually updated, the corresponding element in the aChange[] array +** is zero or greater (if a column is unmodified the corresponding element +** is set to -1). If the rowid column is modified by the UPDATE statement +** the bChngRowid argument is non-zero. +** +** This function returns true if any of the columns that are part of the +** child key for FK constraint *p are modified. +*/ +static int fkChildIsModified( + Table *pTab, /* Table being updated */ + FKey *p, /* Foreign key for which pTab is the child */ + int *aChange, /* Array indicating modified columns */ + int bChngRowid /* True if rowid is modified by this update */ +){ + int i; + for(i=0; inCol; i++){ + int iChildKey = p->aCol[i].iFrom; + if( aChange[iChildKey]>=0 ) return 1; + if( iChildKey==pTab->iPKey && bChngRowid ) return 1; + } + return 0; +} + +/* +** The second argument points to an FKey object representing a foreign key +** for which pTab is the parent table. An UPDATE statement against pTab +** is currently being processed. For each column of the table that is +** actually updated, the corresponding element in the aChange[] array +** is zero or greater (if a column is unmodified the corresponding element +** is set to -1). If the rowid column is modified by the UPDATE statement +** the bChngRowid argument is non-zero. +** +** This function returns true if any of the columns that are part of the +** parent key for FK constraint *p are modified. +*/ +static int fkParentIsModified( + Table *pTab, + FKey *p, + int *aChange, + int bChngRowid +){ + int i; + for(i=0; inCol; i++){ + char *zKey = p->aCol[i].zCol; + int iKey; + for(iKey=0; iKeynCol; iKey++){ + if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){ + Column *pCol = &pTab->aCol[iKey]; + if( zKey ){ + if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1; + }else if( pCol->colFlags & COLFLAG_PRIMKEY ){ + return 1; + } + } + } + } + return 0; +} + +/* +** This function is called when inserting, deleting or updating a row of +** table pTab to generate VDBE code to perform foreign key constraint +** processing for the operation. +** +** For a DELETE operation, parameter regOld is passed the index of the +** first register in an array of (pTab->nCol+1) registers containing the +** rowid of the row being deleted, followed by each of the column values +** of the row being deleted, from left to right. Parameter regNew is passed +** zero in this case. +** +** For an INSERT operation, regOld is passed zero and regNew is passed the +** first register of an array of (pTab->nCol+1) registers containing the new +** row data. +** +** For an UPDATE operation, this function is called twice. Once before +** the original record is deleted from the table using the calling convention +** described for DELETE. Then again after the original record is deleted +** but before the new record is inserted using the INSERT convention. +*/ +void sqlite3FkCheck( + Parse *pParse, /* Parse context */ + Table *pTab, /* Row is being deleted from this table */ + int regOld, /* Previous row data is stored here */ + int regNew, /* New row data is stored here */ + int *aChange, /* Array indicating UPDATEd columns (or 0) */ + int bChngRowid /* True if rowid is UPDATEd */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + FKey *pFKey; /* Used to iterate through FKs */ + int iDb; /* Index of database containing pTab */ + const char *zDb; /* Name of database containing pTab */ + int isIgnoreErrors = pParse->disableTriggers; + + /* Exactly one of regOld and regNew should be non-zero. */ + assert( (regOld==0)!=(regNew==0) ); + + /* If foreign-keys are disabled, this function is a no-op. */ + if( (db->flags&SQLITE_ForeignKeys)==0 ) return; + + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + zDb = db->aDb[iDb].zName; + + /* Loop through all the foreign key constraints for which pTab is the + ** child table (the table that the foreign key definition is part of). */ + for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ + Table *pTo; /* Parent table of foreign key pFKey */ + Index *pIdx = 0; /* Index on key columns in pTo */ + int *aiFree = 0; + int *aiCol; + int iCol; + int i; + int isIgnore = 0; + + if( aChange + && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0 + && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 + ){ + continue; + } + + /* Find the parent table of this foreign key. Also find a unique index + ** on the parent key columns in the parent table. If either of these + ** schema items cannot be located, set an error in pParse and return + ** early. */ + if( pParse->disableTriggers ){ + pTo = sqlite3FindTable(db, pFKey->zTo, zDb); + }else{ + pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); + } + if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){ + assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) ); + if( !isIgnoreErrors || db->mallocFailed ) return; + if( pTo==0 ){ + /* If isIgnoreErrors is true, then a table is being dropped. In this + ** case SQLite runs a "DELETE FROM xxx" on the table being dropped + ** before actually dropping it in order to check FK constraints. + ** If the parent table of an FK constraint on the current table is + ** missing, behave as if it is empty. i.e. decrement the relevant + ** FK counter for each row of the current table with non-NULL keys. + */ + Vdbe *v = sqlite3GetVdbe(pParse); + int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1; + for(i=0; inCol; i++){ + int iReg = pFKey->aCol[i].iFrom + regOld + 1; + sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); + } + sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1); + } + continue; + } + assert( pFKey->nCol==1 || (aiFree && pIdx) ); + + if( aiFree ){ + aiCol = aiFree; + }else{ + iCol = pFKey->aCol[0].iFrom; + aiCol = &iCol; + } + for(i=0; inCol; i++){ + if( aiCol[i]==pTab->iPKey ){ + aiCol[i] = -1; + } +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Request permission to read the parent key columns. If the + ** authorization callback returns SQLITE_IGNORE, behave as if any + ** values read from the parent table are NULL. */ + if( db->xAuth ){ + int rcauth; + char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName; + rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb); + isIgnore = (rcauth==SQLITE_IGNORE); + } +#endif + } + + /* Take a shared-cache advisory read-lock on the parent table. Allocate + ** a cursor to use to search the unique index on the parent key columns + ** in the parent table. */ + sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName); + pParse->nTab++; + + if( regOld!=0 ){ + /* A row is being removed from the child table. Search for the parent. + ** If the parent does not exist, removing the child row resolves an + ** outstanding foreign key constraint violation. */ + fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore); + } + if( regNew!=0 ){ + /* A row is being added to the child table. If a parent row cannot + ** be found, adding the child row has violated the FK constraint. */ + fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore); + } + + sqlite3DbFree(db, aiFree); + } + + /* Loop through all the foreign key constraints that refer to this table */ + for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ + Index *pIdx = 0; /* Foreign key index for pFKey */ + SrcList *pSrc; + int *aiCol = 0; + + if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){ + continue; + } + + if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) + && !pParse->pToplevel && !pParse->isMultiWrite + ){ + assert( regOld==0 && regNew!=0 ); + /* Inserting a single row into a parent table cannot cause an immediate + ** foreign key violation. So do nothing in this case. */ + continue; + } + + if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){ + if( !isIgnoreErrors || db->mallocFailed ) return; + continue; + } + assert( aiCol || pFKey->nCol==1 ); + + /* Create a SrcList structure containing a single table (the table + ** the foreign key that refers to this table is attached to). This + ** is required for the sqlite3WhereXXX() interface. */ + pSrc = sqlite3SrcListAppend(db, 0, 0, 0); + if( pSrc ){ + struct SrcList_item *pItem = pSrc->a; + pItem->pTab = pFKey->pFrom; + pItem->zName = pFKey->pFrom->zName; + pItem->pTab->nRef++; + pItem->iCursor = pParse->nTab++; + + if( regNew!=0 ){ + fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1); + } + if( regOld!=0 ){ + /* If there is a RESTRICT action configured for the current operation + ** on the parent table of this FK, then throw an exception + ** immediately if the FK constraint is violated, even if this is a + ** deferred trigger. That's what RESTRICT means. To defer checking + ** the constraint, the FK should specify NO ACTION (represented + ** using OE_None). NO ACTION is the default. */ + fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1); + } + pItem->zName = 0; + sqlite3SrcListDelete(db, pSrc); + } + sqlite3DbFree(db, aiCol); + } +} + +#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x))) + +/* +** This function is called before generating code to update or delete a +** row contained in table pTab. +*/ +u32 sqlite3FkOldmask( + Parse *pParse, /* Parse context */ + Table *pTab /* Table being modified */ +){ + u32 mask = 0; + if( pParse->db->flags&SQLITE_ForeignKeys ){ + FKey *p; + int i; + for(p=pTab->pFKey; p; p=p->pNextFrom){ + for(i=0; inCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom); + } + for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ + Index *pIdx = 0; + sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0); + if( pIdx ){ + for(i=0; inColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]); + } + } + } + return mask; +} + + +/* +** This function is called before generating code to update or delete a +** row contained in table pTab. If the operation is a DELETE, then +** parameter aChange is passed a NULL value. For an UPDATE, aChange points +** to an array of size N, where N is the number of columns in table pTab. +** If the i'th column is not modified by the UPDATE, then the corresponding +** entry in the aChange[] array is set to -1. If the column is modified, +** the value is 0 or greater. Parameter chngRowid is set to true if the +** UPDATE statement modifies the rowid fields of the table. +** +** If any foreign key processing will be required, this function returns +** true. If there is no foreign key related processing, this function +** returns false. +*/ +int sqlite3FkRequired( + Parse *pParse, /* Parse context */ + Table *pTab, /* Table being modified */ + int *aChange, /* Non-NULL for UPDATE operations */ + int chngRowid /* True for UPDATE that affects rowid */ +){ + if( pParse->db->flags&SQLITE_ForeignKeys ){ + if( !aChange ){ + /* A DELETE operation. Foreign key processing is required if the + ** table in question is either the child or parent table for any + ** foreign key constraint. */ + return (sqlite3FkReferences(pTab) || pTab->pFKey); + }else{ + /* This is an UPDATE. Foreign key processing is only required if the + ** operation modifies one or more child or parent key columns. */ + FKey *p; + + /* Check if any child key columns are being modified. */ + for(p=pTab->pFKey; p; p=p->pNextFrom){ + if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1; + } + + /* Check if any parent key columns are being modified. */ + for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ + if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1; + } + } + } + return 0; +} + +/* +** This function is called when an UPDATE or DELETE operation is being +** compiled on table pTab, which is the parent table of foreign-key pFKey. +** If the current operation is an UPDATE, then the pChanges parameter is +** passed a pointer to the list of columns being modified. If it is a +** DELETE, pChanges is passed a NULL pointer. +** +** It returns a pointer to a Trigger structure containing a trigger +** equivalent to the ON UPDATE or ON DELETE action specified by pFKey. +** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is +** returned (these actions require no special handling by the triggers +** sub-system, code for them is created by fkScanChildren()). +** +** For example, if pFKey is the foreign key and pTab is table "p" in +** the following schema: +** +** CREATE TABLE p(pk PRIMARY KEY); +** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE); +** +** then the returned trigger structure is equivalent to: +** +** CREATE TRIGGER ... DELETE ON p BEGIN +** DELETE FROM c WHERE ck = old.pk; +** END; +** +** The returned pointer is cached as part of the foreign key object. It +** is eventually freed along with the rest of the foreign key object by +** sqlite3FkDelete(). +*/ +static Trigger *fkActionTrigger( + Parse *pParse, /* Parse context */ + Table *pTab, /* Table being updated or deleted from */ + FKey *pFKey, /* Foreign key to get action for */ + ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */ +){ + sqlite3 *db = pParse->db; /* Database handle */ + int action; /* One of OE_None, OE_Cascade etc. */ + Trigger *pTrigger; /* Trigger definition to return */ + int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */ + + action = pFKey->aAction[iAction]; + pTrigger = pFKey->apTrigger[iAction]; + + if( action!=OE_None && !pTrigger ){ + u8 enableLookaside; /* Copy of db->lookaside.bEnabled */ + char const *zFrom; /* Name of child table */ + int nFrom; /* Length in bytes of zFrom */ + Index *pIdx = 0; /* Parent key index for this FK */ + int *aiCol = 0; /* child table cols -> parent key cols */ + TriggerStep *pStep = 0; /* First (only) step of trigger program */ + Expr *pWhere = 0; /* WHERE clause of trigger step */ + ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */ + Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */ + int i; /* Iterator variable */ + Expr *pWhen = 0; /* WHEN clause for the trigger */ + + if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; + assert( aiCol || pFKey->nCol==1 ); + + for(i=0; inCol; i++){ + Token tOld = { "old", 3 }; /* Literal "old" token */ + Token tNew = { "new", 3 }; /* Literal "new" token */ + Token tFromCol; /* Name of column in child table */ + Token tToCol; /* Name of column in parent table */ + int iFromCol; /* Idx of column in child table */ + Expr *pEq; /* tFromCol = OLD.tToCol */ + + iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; + assert( iFromCol>=0 ); + tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid"; + tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName; + + tToCol.n = sqlite3Strlen30(tToCol.z); + tFromCol.n = sqlite3Strlen30(tFromCol.z); + + /* Create the expression "OLD.zToCol = zFromCol". It is important + ** that the "OLD.zToCol" term is on the LHS of the = operator, so + ** that the affinity and collation sequence associated with the + ** parent table are used for the comparison. */ + pEq = sqlite3PExpr(pParse, TK_EQ, + sqlite3PExpr(pParse, TK_DOT, + sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol) + , 0), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol) + , 0); + pWhere = sqlite3ExprAnd(db, pWhere, pEq); + + /* For ON UPDATE, construct the next term of the WHEN clause. + ** The final WHEN clause will be like this: + ** + ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) + */ + if( pChanges ){ + pEq = sqlite3PExpr(pParse, TK_IS, + sqlite3PExpr(pParse, TK_DOT, + sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol), + 0), + sqlite3PExpr(pParse, TK_DOT, + sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol), + 0), + 0); + pWhen = sqlite3ExprAnd(db, pWhen, pEq); + } + + if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){ + Expr *pNew; + if( action==OE_Cascade ){ + pNew = sqlite3PExpr(pParse, TK_DOT, + sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew), + sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol) + , 0); + }else if( action==OE_SetDflt ){ + Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt; + if( pDflt ){ + pNew = sqlite3ExprDup(db, pDflt, 0); + }else{ + pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0); + } + }else{ + pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0); + } + pList = sqlite3ExprListAppend(pParse, pList, pNew); + sqlite3ExprListSetName(pParse, pList, &tFromCol, 0); + } + } + sqlite3DbFree(db, aiCol); + + zFrom = pFKey->pFrom->zName; + nFrom = sqlite3Strlen30(zFrom); + + if( action==OE_Restrict ){ + Token tFrom; + Expr *pRaise; + + tFrom.z = zFrom; + tFrom.n = nFrom; + pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed"); + if( pRaise ){ + pRaise->affinity = OE_Abort; + } + pSelect = sqlite3SelectNew(pParse, + sqlite3ExprListAppend(pParse, 0, pRaise), + sqlite3SrcListAppend(db, 0, &tFrom, 0), + pWhere, + 0, 0, 0, 0, 0, 0 + ); + pWhere = 0; + } + + /* Disable lookaside memory allocation */ + enableLookaside = db->lookaside.bEnabled; + db->lookaside.bEnabled = 0; + + pTrigger = (Trigger *)sqlite3DbMallocZero(db, + sizeof(Trigger) + /* struct Trigger */ + sizeof(TriggerStep) + /* Single step in trigger program */ + nFrom + 1 /* Space for pStep->target.z */ + ); + if( pTrigger ){ + pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1]; + pStep->target.z = (char *)&pStep[1]; + pStep->target.n = nFrom; + memcpy((char *)pStep->target.z, zFrom, nFrom); + + pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); + pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + if( pWhen ){ + pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0); + pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); + } + } + + /* Re-enable the lookaside buffer, if it was disabled earlier. */ + db->lookaside.bEnabled = enableLookaside; + + sqlite3ExprDelete(db, pWhere); + sqlite3ExprDelete(db, pWhen); + sqlite3ExprListDelete(db, pList); + sqlite3SelectDelete(db, pSelect); + if( db->mallocFailed==1 ){ + fkTriggerDelete(db, pTrigger); + return 0; + } + assert( pStep!=0 ); + + switch( action ){ + case OE_Restrict: + pStep->op = TK_SELECT; + break; + case OE_Cascade: + if( !pChanges ){ + pStep->op = TK_DELETE; + break; + } + default: + pStep->op = TK_UPDATE; + } + pStep->pTrig = pTrigger; + pTrigger->pSchema = pTab->pSchema; + pTrigger->pTabSchema = pTab->pSchema; + pFKey->apTrigger[iAction] = pTrigger; + pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE); + } + + return pTrigger; +} + +/* +** This function is called when deleting or updating a row to implement +** any required CASCADE, SET NULL or SET DEFAULT actions. +*/ +void sqlite3FkActions( + Parse *pParse, /* Parse context */ + Table *pTab, /* Table being updated or deleted from */ + ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */ + int regOld, /* Address of array containing old row */ + int *aChange, /* Array indicating UPDATEd columns (or 0) */ + int bChngRowid /* True if rowid is UPDATEd */ +){ + /* If foreign-key support is enabled, iterate through all FKs that + ** refer to table pTab. If there is an action associated with the FK + ** for this operation (either update or delete), invoke the associated + ** trigger sub-program. */ + if( pParse->db->flags&SQLITE_ForeignKeys ){ + FKey *pFKey; /* Iterator variable */ + for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ + if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){ + Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges); + if( pAct ){ + sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0); + } + } + } + } +} + +#endif /* ifndef SQLITE_OMIT_TRIGGER */ + +/* +** Free all memory associated with foreign key definitions attached to +** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash +** hash table. +*/ +void sqlite3FkDelete(sqlite3 *db, Table *pTab){ + FKey *pFKey; /* Iterator variable */ + FKey *pNext; /* Copy of pFKey->pNextFrom */ + + assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) ); + for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){ + + /* Remove the FK from the fkeyHash hash table. */ + if( !db || db->pnBytesFreed==0 ){ + if( pFKey->pPrevTo ){ + pFKey->pPrevTo->pNextTo = pFKey->pNextTo; + }else{ + void *p = (void *)pFKey->pNextTo; + const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo); + sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p); + } + if( pFKey->pNextTo ){ + pFKey->pNextTo->pPrevTo = pFKey->pPrevTo; + } + } + + /* EV: R-30323-21917 Each foreign key constraint in SQLite is + ** classified as either immediate or deferred. + */ + assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 ); + + /* Delete any triggers created to implement actions for this FK. */ +#ifndef SQLITE_OMIT_TRIGGER + fkTriggerDelete(db, pFKey->apTrigger[0]); + fkTriggerDelete(db, pFKey->apTrigger[1]); +#endif + + pNext = pFKey->pNextFrom; + sqlite3DbFree(db, pFKey); + } +} +#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */ diff --git a/components/external/SQLite-3.8.1/src/func.c b/components/external/SQLite-3.8.1/src/func.c new file mode 100644 index 0000000000000000000000000000000000000000..e2ab68f0303c8a03eec2377e660c864b25d75cfe --- /dev/null +++ b/components/external/SQLite-3.8.1/src/func.c @@ -0,0 +1,1723 @@ +/* +** 2002 February 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement various SQL +** functions of SQLite. +** +** There is only one exported symbol in this file - the function +** sqliteRegisterBuildinFunctions() found at the bottom of the file. +** All other code has file scope. +*/ +#include "sqliteInt.h" +#include +#include +#include "vdbeInt.h" + +/* +** Return the collating function associated with a function. +*/ +static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ + return context->pColl; +} + +/* +** Indicate that the accumulator load should be skipped on this +** iteration of the aggregate loop. +*/ +static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ + context->skipFlag = 1; +} + +/* +** Implementation of the non-aggregate min() and max() functions +*/ +static void minmaxFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int i; + int mask; /* 0 for min() or 0xffffffff for max() */ + int iBest; + CollSeq *pColl; + + assert( argc>1 ); + mask = sqlite3_user_data(context)==0 ? 0 : -1; + pColl = sqlite3GetFuncCollSeq(context); + assert( pColl ); + assert( mask==-1 || mask==0 ); + iBest = 0; + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; + for(i=1; i=0 ){ + testcase( mask==0 ); + iBest = i; + } + } + sqlite3_result_value(context, argv[iBest]); +} + +/* +** Return the type of the argument. +*/ +static void typeofFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + const char *z = 0; + UNUSED_PARAMETER(NotUsed); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_INTEGER: z = "integer"; break; + case SQLITE_TEXT: z = "text"; break; + case SQLITE_FLOAT: z = "real"; break; + case SQLITE_BLOB: z = "blob"; break; + default: z = "null"; break; + } + sqlite3_result_text(context, z, -1, SQLITE_STATIC); +} + + +/* +** Implementation of the length() function +*/ +static void lengthFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int len; + + assert( argc==1 ); + UNUSED_PARAMETER(argc); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_BLOB: + case SQLITE_INTEGER: + case SQLITE_FLOAT: { + sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); + break; + } + case SQLITE_TEXT: { + const unsigned char *z = sqlite3_value_text(argv[0]); + if( z==0 ) return; + len = 0; + while( *z ){ + len++; + SQLITE_SKIP_UTF8(z); + } + sqlite3_result_int(context, len); + break; + } + default: { + sqlite3_result_null(context); + break; + } + } +} + +/* +** Implementation of the abs() function. +** +** IMP: R-23979-26855 The abs(X) function returns the absolute value of +** the numeric argument X. +*/ +static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + assert( argc==1 ); + UNUSED_PARAMETER(argc); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_INTEGER: { + i64 iVal = sqlite3_value_int64(argv[0]); + if( iVal<0 ){ + if( (iVal<<1)==0 ){ + /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then + ** abs(X) throws an integer overflow error since there is no + ** equivalent positive 64-bit two complement value. */ + sqlite3_result_error(context, "integer overflow", -1); + return; + } + iVal = -iVal; + } + sqlite3_result_int64(context, iVal); + break; + } + case SQLITE_NULL: { + /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ + sqlite3_result_null(context); + break; + } + default: { + /* Because sqlite3_value_double() returns 0.0 if the argument is not + ** something that can be converted into a number, we have: + ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that + ** cannot be converted to a numeric value. + */ + double rVal = sqlite3_value_double(argv[0]); + if( rVal<0 ) rVal = -rVal; + sqlite3_result_double(context, rVal); + break; + } + } +} + +/* +** Implementation of the instr() function. +** +** instr(haystack,needle) finds the first occurrence of needle +** in haystack and returns the number of previous characters plus 1, +** or 0 if needle does not occur within haystack. +** +** If both haystack and needle are BLOBs, then the result is one more than +** the number of bytes in haystack prior to the first occurrence of needle, +** or 0 if needle never occurs in haystack. +*/ +static void instrFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zHaystack; + const unsigned char *zNeedle; + int nHaystack; + int nNeedle; + int typeHaystack, typeNeedle; + int N = 1; + int isText; + + UNUSED_PARAMETER(argc); + typeHaystack = sqlite3_value_type(argv[0]); + typeNeedle = sqlite3_value_type(argv[1]); + if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; + nHaystack = sqlite3_value_bytes(argv[0]); + nNeedle = sqlite3_value_bytes(argv[1]); + if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ + zHaystack = sqlite3_value_blob(argv[0]); + zNeedle = sqlite3_value_blob(argv[1]); + isText = 0; + }else{ + zHaystack = sqlite3_value_text(argv[0]); + zNeedle = sqlite3_value_text(argv[1]); + isText = 1; + } + while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){ + N++; + do{ + nHaystack--; + zHaystack++; + }while( isText && (zHaystack[0]&0xc0)==0x80 ); + } + if( nNeedle>nHaystack ) N = 0; + sqlite3_result_int(context, N); +} + +/* +** Implementation of the substr() function. +** +** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. +** p1 is 1-indexed. So substr(x,1,1) returns the first character +** of x. If x is text, then we actually count UTF-8 characters. +** If x is a blob, then we count bytes. +** +** If p1 is negative, then we begin abs(p1) from the end of x[]. +** +** If p2 is negative, return the p2 characters preceding p1. +*/ +static void substrFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *z; + const unsigned char *z2; + int len; + int p0type; + i64 p1, p2; + int negP2 = 0; + + assert( argc==3 || argc==2 ); + if( sqlite3_value_type(argv[1])==SQLITE_NULL + || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) + ){ + return; + } + p0type = sqlite3_value_type(argv[0]); + p1 = sqlite3_value_int(argv[1]); + if( p0type==SQLITE_BLOB ){ + len = sqlite3_value_bytes(argv[0]); + z = sqlite3_value_blob(argv[0]); + if( z==0 ) return; + assert( len==sqlite3_value_bytes(argv[0]) ); + }else{ + z = sqlite3_value_text(argv[0]); + if( z==0 ) return; + len = 0; + if( p1<0 ){ + for(z2=z; *z2; len++){ + SQLITE_SKIP_UTF8(z2); + } + } + } + if( argc==3 ){ + p2 = sqlite3_value_int(argv[2]); + if( p2<0 ){ + p2 = -p2; + negP2 = 1; + } + }else{ + p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; + } + if( p1<0 ){ + p1 += len; + if( p1<0 ){ + p2 += p1; + if( p2<0 ) p2 = 0; + p1 = 0; + } + }else if( p1>0 ){ + p1--; + }else if( p2>0 ){ + p2--; + } + if( negP2 ){ + p1 -= p2; + if( p1<0 ){ + p2 += p1; + p1 = 0; + } + } + assert( p1>=0 && p2>=0 ); + if( p0type!=SQLITE_BLOB ){ + while( *z && p1 ){ + SQLITE_SKIP_UTF8(z); + p1--; + } + for(z2=z; *z2 && p2; p2--){ + SQLITE_SKIP_UTF8(z2); + } + sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT); + }else{ + if( p1+p2>len ){ + p2 = len-p1; + if( p2<0 ) p2 = 0; + } + sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT); + } +} + +/* +** Implementation of the round() function +*/ +#ifndef SQLITE_OMIT_FLOATING_POINT +static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + int n = 0; + double r; + char *zBuf; + assert( argc==1 || argc==2 ); + if( argc==2 ){ + if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; + n = sqlite3_value_int(argv[1]); + if( n>30 ) n = 30; + if( n<0 ) n = 0; + } + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; + r = sqlite3_value_double(argv[0]); + /* If Y==0 and X will fit in a 64-bit int, + ** handle the rounding directly, + ** otherwise use printf. + */ + if( n==0 && r>=0 && r0 ); + testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); + testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); + if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + sqlite3_result_error_toobig(context); + z = 0; + }else{ + z = sqlite3Malloc((int)nByte); + if( !z ){ + sqlite3_result_error_nomem(context); + } + } + return z; +} + +/* +** Implementation of the upper() and lower() SQL functions. +*/ +static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + char *z1; + const char *z2; + int i, n; + UNUSED_PARAMETER(argc); + z2 = (char*)sqlite3_value_text(argv[0]); + n = sqlite3_value_bytes(argv[0]); + /* Verify that the call to _bytes() does not invalidate the _text() pointer */ + assert( z2==(char*)sqlite3_value_text(argv[0]) ); + if( z2 ){ + z1 = contextMalloc(context, ((i64)n)+1); + if( z1 ){ + for(i=0; imatchOne; + u8 matchAll = pInfo->matchAll; + u8 matchSet = pInfo->matchSet; + u8 noCase = pInfo->noCase; + int prevEscape = 0; /* True if the previous character was 'escape' */ + + while( (c = sqlite3Utf8Read(&zPattern))!=0 ){ + if( c==matchAll && !prevEscape ){ + while( (c=sqlite3Utf8Read(&zPattern)) == matchAll + || c == matchOne ){ + if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ + return 0; + } + } + if( c==0 ){ + return 1; + }else if( c==esc ){ + c = sqlite3Utf8Read(&zPattern); + if( c==0 ){ + return 0; + } + }else if( c==matchSet ){ + assert( esc==0 ); /* This is GLOB, not LIKE */ + assert( matchSet<0x80 ); /* '[' is a single-byte character */ + while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){ + SQLITE_SKIP_UTF8(zString); + } + return *zString!=0; + } + while( (c2 = sqlite3Utf8Read(&zString))!=0 ){ + if( noCase ){ + GlobUpperToLower(c2); + GlobUpperToLower(c); + while( c2 != 0 && c2 != c ){ + c2 = sqlite3Utf8Read(&zString); + GlobUpperToLower(c2); + } + }else{ + while( c2 != 0 && c2 != c ){ + c2 = sqlite3Utf8Read(&zString); + } + } + if( c2==0 ) return 0; + if( patternCompare(zPattern,zString,pInfo,esc) ) return 1; + } + return 0; + }else if( c==matchOne && !prevEscape ){ + if( sqlite3Utf8Read(&zString)==0 ){ + return 0; + } + }else if( c==matchSet ){ + u32 prior_c = 0; + assert( esc==0 ); /* This only occurs for GLOB, not LIKE */ + seen = 0; + invert = 0; + c = sqlite3Utf8Read(&zString); + if( c==0 ) return 0; + c2 = sqlite3Utf8Read(&zPattern); + if( c2=='^' ){ + invert = 1; + c2 = sqlite3Utf8Read(&zPattern); + } + if( c2==']' ){ + if( c==']' ) seen = 1; + c2 = sqlite3Utf8Read(&zPattern); + } + while( c2 && c2!=']' ){ + if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ + c2 = sqlite3Utf8Read(&zPattern); + if( c>=prior_c && c<=c2 ) seen = 1; + prior_c = 0; + }else{ + if( c==c2 ){ + seen = 1; + } + prior_c = c2; + } + c2 = sqlite3Utf8Read(&zPattern); + } + if( c2==0 || (seen ^ invert)==0 ){ + return 0; + } + }else if( esc==c && !prevEscape ){ + prevEscape = 1; + }else{ + c2 = sqlite3Utf8Read(&zString); + if( noCase ){ + GlobUpperToLower(c); + GlobUpperToLower(c2); + } + if( c!=c2 ){ + return 0; + } + prevEscape = 0; + } + } + return *zString==0; +} + +/* +** The sqlite3_strglob() interface. +*/ +int sqlite3_strglob(const char *zGlobPattern, const char *zString){ + return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0; +} + +/* +** Count the number of times that the LIKE operator (or GLOB which is +** just a variation of LIKE) gets called. This is used for testing +** only. +*/ +#ifdef SQLITE_TEST +int sqlite3_like_count = 0; +#endif + + +/* +** Implementation of the like() SQL function. This function implements +** the build-in LIKE operator. The first argument to the function is the +** pattern and the second argument is the string. So, the SQL statements: +** +** A LIKE B +** +** is implemented as like(B,A). +** +** This same function (with a different compareInfo structure) computes +** the GLOB operator. +*/ +static void likeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zA, *zB; + u32 escape = 0; + int nPat; + sqlite3 *db = sqlite3_context_db_handle(context); + + zB = sqlite3_value_text(argv[0]); + zA = sqlite3_value_text(argv[1]); + + /* Limit the length of the LIKE or GLOB pattern to avoid problems + ** of deep recursion and N*N behavior in patternCompare(). + */ + nPat = sqlite3_value_bytes(argv[0]); + testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); + testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); + if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ + sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); + return; + } + assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */ + + if( argc==3 ){ + /* The escape character string must consist of a single UTF-8 character. + ** Otherwise, return an error. + */ + const unsigned char *zEsc = sqlite3_value_text(argv[2]); + if( zEsc==0 ) return; + if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ + sqlite3_result_error(context, + "ESCAPE expression must be a single character", -1); + return; + } + escape = sqlite3Utf8Read(&zEsc); + } + if( zA && zB ){ + struct compareInfo *pInfo = sqlite3_user_data(context); +#ifdef SQLITE_TEST + sqlite3_like_count++; +#endif + + sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape)); + } +} + +/* +** Implementation of the NULLIF(x,y) function. The result is the first +** argument if the arguments are different. The result is NULL if the +** arguments are equal to each other. +*/ +static void nullifFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + CollSeq *pColl = sqlite3GetFuncCollSeq(context); + UNUSED_PARAMETER(NotUsed); + if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ + sqlite3_result_value(context, argv[0]); + } +} + +/* +** Implementation of the sqlite_version() function. The result is the version +** of the SQLite library that is running. +*/ +static void versionFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + /* IMP: R-48699-48617 This function is an SQL wrapper around the + ** sqlite3_libversion() C-interface. */ + sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); +} + +/* +** Implementation of the sqlite_source_id() function. The result is a string +** that identifies the particular version of the source code used to build +** SQLite. +*/ +static void sourceidFunc( + sqlite3_context *context, + int NotUsed, + sqlite3_value **NotUsed2 +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + /* IMP: R-24470-31136 This function is an SQL wrapper around the + ** sqlite3_sourceid() C interface. */ + sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); +} + +/* +** Implementation of the sqlite_log() function. This is a wrapper around +** sqlite3_log(). The return value is NULL. The function exists purely for +** its side-effects. +*/ +static void errlogFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(context); + sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); +} + +/* +** Implementation of the sqlite_compileoption_used() function. +** The result is an integer that identifies if the compiler option +** was used to build SQLite. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +static void compileoptionusedFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const char *zOptName; + assert( argc==1 ); + UNUSED_PARAMETER(argc); + /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL + ** function is a wrapper around the sqlite3_compileoption_used() C/C++ + ** function. + */ + if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ + sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); + } +} +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + +/* +** Implementation of the sqlite_compileoption_get() function. +** The result is a string that identifies the compiler options +** used to build SQLite. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +static void compileoptiongetFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int n; + assert( argc==1 ); + UNUSED_PARAMETER(argc); + /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function + ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. + */ + n = sqlite3_value_int(argv[0]); + sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC); +} +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + +/* Array for converting from half-bytes (nybbles) into ASCII hex +** digits. */ +static const char hexdigits[] = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' +}; + +/* +** Implementation of the QUOTE() function. This function takes a single +** argument. If the argument is numeric, the return value is the same as +** the argument. If the argument is NULL, the return value is the string +** "NULL". Otherwise, the argument is enclosed in single quotes with +** single-quote escapes. +*/ +static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + assert( argc==1 ); + UNUSED_PARAMETER(argc); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_FLOAT: { + double r1, r2; + char zBuf[50]; + r1 = sqlite3_value_double(argv[0]); + sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1); + sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8); + if( r1!=r2 ){ + sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1); + } + sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + break; + } + case SQLITE_INTEGER: { + sqlite3_result_value(context, argv[0]); + break; + } + case SQLITE_BLOB: { + char *zText = 0; + char const *zBlob = sqlite3_value_blob(argv[0]); + int nBlob = sqlite3_value_bytes(argv[0]); + assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ + zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); + if( zText ){ + int i; + for(i=0; i>4)&0x0F]; + zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F]; + } + zText[(nBlob*2)+2] = '\''; + zText[(nBlob*2)+3] = '\0'; + zText[0] = 'X'; + zText[1] = '\''; + sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); + sqlite3_free(zText); + } + break; + } + case SQLITE_TEXT: { + int i,j; + u64 n; + const unsigned char *zArg = sqlite3_value_text(argv[0]); + char *z; + + if( zArg==0 ) return; + for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; } + z = contextMalloc(context, ((i64)i)+((i64)n)+3); + if( z ){ + z[0] = '\''; + for(i=0, j=1; zArg[i]; i++){ + z[j++] = zArg[i]; + if( zArg[i]=='\'' ){ + z[j++] = '\''; + } + } + z[j++] = '\''; + z[j] = 0; + sqlite3_result_text(context, z, j, sqlite3_free); + } + break; + } + default: { + assert( sqlite3_value_type(argv[0])==SQLITE_NULL ); + sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC); + break; + } + } +} + +/* +** The unicode() function. Return the integer unicode code-point value +** for the first character of the input string. +*/ +static void unicodeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *z = sqlite3_value_text(argv[0]); + (void)argc; + if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); +} + +/* +** The char() function takes zero or more arguments, each of which is +** an integer. It constructs a string where each character of the string +** is the unicode character for the corresponding integer argument. +*/ +static void charFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + unsigned char *z, *zOut; + int i; + zOut = z = sqlite3_malloc( argc*4 ); + if( z==0 ){ + sqlite3_result_error_nomem(context); + return; + } + for(i=0; i0x10ffff ) x = 0xfffd; + c = (unsigned)(x & 0x1fffff); + if( c<0x00080 ){ + *zOut++ = (u8)(c&0xFF); + }else if( c<0x00800 ){ + *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); + *zOut++ = 0x80 + (u8)(c & 0x3F); + }else if( c<0x10000 ){ + *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); + *zOut++ = 0x80 + (u8)(c & 0x3F); + }else{ + *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); + *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); + *zOut++ = 0x80 + (u8)(c & 0x3F); + } \ + } + sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free); +} + +/* +** The hex() function. Interpret the argument as a blob. Return +** a hexadecimal rendering as text. +*/ +static void hexFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int i, n; + const unsigned char *pBlob; + char *zHex, *z; + assert( argc==1 ); + UNUSED_PARAMETER(argc); + pBlob = sqlite3_value_blob(argv[0]); + n = sqlite3_value_bytes(argv[0]); + assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ + z = zHex = contextMalloc(context, ((i64)n)*2 + 1); + if( zHex ){ + for(i=0; i>4)&0xf]; + *(z++) = hexdigits[c&0xf]; + } + *z = 0; + sqlite3_result_text(context, zHex, n*2, sqlite3_free); + } +} + +/* +** The zeroblob(N) function returns a zero-filled blob of size N bytes. +*/ +static void zeroblobFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + i64 n; + sqlite3 *db = sqlite3_context_db_handle(context); + assert( argc==1 ); + UNUSED_PARAMETER(argc); + n = sqlite3_value_int64(argv[0]); + testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] ); + testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); + if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + sqlite3_result_error_toobig(context); + }else{ + sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */ + } +} + +/* +** The replace() function. Three arguments are all strings: call +** them A, B, and C. The result is also a string which is derived +** from A by replacing every occurrence of B with C. The match +** must be exact. Collating sequences are not used. +*/ +static void replaceFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zStr; /* The input string A */ + const unsigned char *zPattern; /* The pattern string B */ + const unsigned char *zRep; /* The replacement string C */ + unsigned char *zOut; /* The output */ + int nStr; /* Size of zStr */ + int nPattern; /* Size of zPattern */ + int nRep; /* Size of zRep */ + i64 nOut; /* Maximum size of zOut */ + int loopLimit; /* Last zStr[] that might match zPattern[] */ + int i, j; /* Loop counters */ + + assert( argc==3 ); + UNUSED_PARAMETER(argc); + zStr = sqlite3_value_text(argv[0]); + if( zStr==0 ) return; + nStr = sqlite3_value_bytes(argv[0]); + assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */ + zPattern = sqlite3_value_text(argv[1]); + if( zPattern==0 ){ + assert( sqlite3_value_type(argv[1])==SQLITE_NULL + || sqlite3_context_db_handle(context)->mallocFailed ); + return; + } + if( zPattern[0]==0 ){ + assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); + sqlite3_result_value(context, argv[0]); + return; + } + nPattern = sqlite3_value_bytes(argv[1]); + assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ + zRep = sqlite3_value_text(argv[2]); + if( zRep==0 ) return; + nRep = sqlite3_value_bytes(argv[2]); + assert( zRep==sqlite3_value_text(argv[2]) ); + nOut = nStr + 1; + assert( nOutaLimit[SQLITE_LIMIT_LENGTH] ); + testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); + if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + sqlite3_result_error_toobig(context); + sqlite3_free(zOut); + return; + } + zOld = zOut; + zOut = sqlite3_realloc(zOut, (int)nOut); + if( zOut==0 ){ + sqlite3_result_error_nomem(context); + sqlite3_free(zOld); + return; + } + memcpy(&zOut[j], zRep, nRep); + j += nRep; + i += nPattern-1; + } + } + assert( j+nStr-i+1==nOut ); + memcpy(&zOut[j], &zStr[i], nStr-i); + j += nStr - i; + assert( j<=nOut ); + zOut[j] = 0; + sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); +} + +/* +** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. +** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. +*/ +static void trimFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *zIn; /* Input string */ + const unsigned char *zCharSet; /* Set of characters to trim */ + int nIn; /* Number of bytes in input */ + int flags; /* 1: trimleft 2: trimright 3: trim */ + int i; /* Loop counter */ + unsigned char *aLen = 0; /* Length of each character in zCharSet */ + unsigned char **azChar = 0; /* Individual characters in zCharSet */ + int nChar; /* Number of characters in zCharSet */ + + if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ + return; + } + zIn = sqlite3_value_text(argv[0]); + if( zIn==0 ) return; + nIn = sqlite3_value_bytes(argv[0]); + assert( zIn==sqlite3_value_text(argv[0]) ); + if( argc==1 ){ + static const unsigned char lenOne[] = { 1 }; + static unsigned char * const azOne[] = { (u8*)" " }; + nChar = 1; + aLen = (u8*)lenOne; + azChar = (unsigned char **)azOne; + zCharSet = 0; + }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ + return; + }else{ + const unsigned char *z; + for(z=zCharSet, nChar=0; *z; nChar++){ + SQLITE_SKIP_UTF8(z); + } + if( nChar>0 ){ + azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); + if( azChar==0 ){ + return; + } + aLen = (unsigned char*)&azChar[nChar]; + for(z=zCharSet, nChar=0; *z; nChar++){ + azChar[nChar] = (unsigned char *)z; + SQLITE_SKIP_UTF8(z); + aLen[nChar] = (u8)(z - azChar[nChar]); + } + } + } + if( nChar>0 ){ + flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); + if( flags & 1 ){ + while( nIn>0 ){ + int len = 0; + for(i=0; i=nChar ) break; + zIn += len; + nIn -= len; + } + } + if( flags & 2 ){ + while( nIn>0 ){ + int len = 0; + for(i=0; i=nChar ) break; + nIn -= len; + } + } + if( zCharSet ){ + sqlite3_free(azChar); + } + } + sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); +} + + +/* IMP: R-25361-16150 This function is omitted from SQLite by default. It +** is only available if the SQLITE_SOUNDEX compile-time option is used +** when SQLite is built. +*/ +#ifdef SQLITE_SOUNDEX +/* +** Compute the soundex encoding of a word. +** +** IMP: R-59782-00072 The soundex(X) function returns a string that is the +** soundex encoding of the string X. +*/ +static void soundexFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + char zResult[8]; + const u8 *zIn; + int i, j; + static const unsigned char iCode[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, + }; + assert( argc==1 ); + zIn = (u8*)sqlite3_value_text(argv[0]); + if( zIn==0 ) zIn = (u8*)""; + for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} + if( zIn[i] ){ + u8 prevcode = iCode[zIn[i]&0x7f]; + zResult[0] = sqlite3Toupper(zIn[i]); + for(j=1; j<4 && zIn[i]; i++){ + int code = iCode[zIn[i]&0x7f]; + if( code>0 ){ + if( code!=prevcode ){ + prevcode = code; + zResult[j++] = code + '0'; + } + }else{ + prevcode = 0; + } + } + while( j<4 ){ + zResult[j++] = '0'; + } + zResult[j] = 0; + sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); + }else{ + /* IMP: R-64894-50321 The string "?000" is returned if the argument + ** is NULL or contains no ASCII alphabetic characters. */ + sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); + } +} +#endif /* SQLITE_SOUNDEX */ + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +/* +** A function that loads a shared-library extension then returns NULL. +*/ +static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ + const char *zFile = (const char *)sqlite3_value_text(argv[0]); + const char *zProc; + sqlite3 *db = sqlite3_context_db_handle(context); + char *zErrMsg = 0; + + if( argc==2 ){ + zProc = (const char *)sqlite3_value_text(argv[1]); + }else{ + zProc = 0; + } + if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ + sqlite3_result_error(context, zErrMsg, -1); + sqlite3_free(zErrMsg); + } +} +#endif + + +/* +** An instance of the following structure holds the context of a +** sum() or avg() aggregate computation. +*/ +typedef struct SumCtx SumCtx; +struct SumCtx { + double rSum; /* Floating point sum */ + i64 iSum; /* Integer sum */ + i64 cnt; /* Number of elements summed */ + u8 overflow; /* True if integer overflow seen */ + u8 approx; /* True if non-integer value was input to the sum */ +}; + +/* +** Routines used to compute the sum, average, and total. +** +** The SUM() function follows the (broken) SQL standard which means +** that it returns NULL if it sums over no inputs. TOTAL returns +** 0.0 in that case. In addition, TOTAL always returns a float where +** SUM might return an integer if it never encounters a floating point +** value. TOTAL never fails, but SUM might through an exception if +** it overflows an integer. +*/ +static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ + SumCtx *p; + int type; + assert( argc==1 ); + UNUSED_PARAMETER(argc); + p = sqlite3_aggregate_context(context, sizeof(*p)); + type = sqlite3_value_numeric_type(argv[0]); + if( p && type!=SQLITE_NULL ){ + p->cnt++; + if( type==SQLITE_INTEGER ){ + i64 v = sqlite3_value_int64(argv[0]); + p->rSum += v; + if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){ + p->overflow = 1; + } + }else{ + p->rSum += sqlite3_value_double(argv[0]); + p->approx = 1; + } + } +} +static void sumFinalize(sqlite3_context *context){ + SumCtx *p; + p = sqlite3_aggregate_context(context, 0); + if( p && p->cnt>0 ){ + if( p->overflow ){ + sqlite3_result_error(context,"integer overflow",-1); + }else if( p->approx ){ + sqlite3_result_double(context, p->rSum); + }else{ + sqlite3_result_int64(context, p->iSum); + } + } +} +static void avgFinalize(sqlite3_context *context){ + SumCtx *p; + p = sqlite3_aggregate_context(context, 0); + if( p && p->cnt>0 ){ + sqlite3_result_double(context, p->rSum/(double)p->cnt); + } +} +static void totalFinalize(sqlite3_context *context){ + SumCtx *p; + p = sqlite3_aggregate_context(context, 0); + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + sqlite3_result_double(context, p ? p->rSum : (double)0); +} + +/* +** The following structure keeps track of state information for the +** count() aggregate function. +*/ +typedef struct CountCtx CountCtx; +struct CountCtx { + i64 n; +}; + +/* +** Routines to implement the count() aggregate function. +*/ +static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ + CountCtx *p; + p = sqlite3_aggregate_context(context, sizeof(*p)); + if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ + p->n++; + } + +#ifndef SQLITE_OMIT_DEPRECATED + /* The sqlite3_aggregate_count() function is deprecated. But just to make + ** sure it still operates correctly, verify that its count agrees with our + ** internal count when using count(*) and when the total count can be + ** expressed as a 32-bit integer. */ + assert( argc==1 || p==0 || p->n>0x7fffffff + || p->n==sqlite3_aggregate_count(context) ); +#endif +} +static void countFinalize(sqlite3_context *context){ + CountCtx *p; + p = sqlite3_aggregate_context(context, 0); + sqlite3_result_int64(context, p ? p->n : 0); +} + +/* +** Routines to implement min() and max() aggregate functions. +*/ +static void minmaxStep( + sqlite3_context *context, + int NotUsed, + sqlite3_value **argv +){ + Mem *pArg = (Mem *)argv[0]; + Mem *pBest; + UNUSED_PARAMETER(NotUsed); + + pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); + if( !pBest ) return; + + if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ + if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); + }else if( pBest->flags ){ + int max; + int cmp; + CollSeq *pColl = sqlite3GetFuncCollSeq(context); + /* This step function is used for both the min() and max() aggregates, + ** the only difference between the two being that the sense of the + ** comparison is inverted. For the max() aggregate, the + ** sqlite3_user_data() function returns (void *)-1. For min() it + ** returns (void *)db, where db is the sqlite3* database pointer. + ** Therefore the next statement sets variable 'max' to 1 for the max() + ** aggregate, or 0 for min(). + */ + max = sqlite3_user_data(context)!=0; + cmp = sqlite3MemCompare(pBest, pArg, pColl); + if( (max && cmp<0) || (!max && cmp>0) ){ + sqlite3VdbeMemCopy(pBest, pArg); + }else{ + sqlite3SkipAccumulatorLoad(context); + } + }else{ + sqlite3VdbeMemCopy(pBest, pArg); + } +} +static void minMaxFinalize(sqlite3_context *context){ + sqlite3_value *pRes; + pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); + if( pRes ){ + if( pRes->flags ){ + sqlite3_result_value(context, pRes); + } + sqlite3VdbeMemRelease(pRes); + } +} + +/* +** group_concat(EXPR, ?SEPARATOR?) +*/ +static void groupConcatStep( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const char *zVal; + StrAccum *pAccum; + const char *zSep; + int nVal, nSep; + assert( argc==1 || argc==2 ); + if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; + pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); + + if( pAccum ){ + sqlite3 *db = sqlite3_context_db_handle(context); + int firstTerm = pAccum->useMalloc==0; + pAccum->useMalloc = 2; + pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; + if( !firstTerm ){ + if( argc==2 ){ + zSep = (char*)sqlite3_value_text(argv[1]); + nSep = sqlite3_value_bytes(argv[1]); + }else{ + zSep = ","; + nSep = 1; + } + sqlite3StrAccumAppend(pAccum, zSep, nSep); + } + zVal = (char*)sqlite3_value_text(argv[0]); + nVal = sqlite3_value_bytes(argv[0]); + sqlite3StrAccumAppend(pAccum, zVal, nVal); + } +} +static void groupConcatFinalize(sqlite3_context *context){ + StrAccum *pAccum; + pAccum = sqlite3_aggregate_context(context, 0); + if( pAccum ){ + if( pAccum->accError==STRACCUM_TOOBIG ){ + sqlite3_result_error_toobig(context); + }else if( pAccum->accError==STRACCUM_NOMEM ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, + sqlite3_free); + } + } +} + +/* +** This routine does per-connection function registration. Most +** of the built-in functions above are part of the global function set. +** This routine only deals with those that are not global. +*/ +void sqlite3RegisterBuiltinFunctions(sqlite3 *db){ + int rc = sqlite3_overload_function(db, "MATCH", 2); + assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); + if( rc==SQLITE_NOMEM ){ + db->mallocFailed = 1; + } +} + +/* +** Set the LIKEOPT flag on the 2-argument function with the given name. +*/ +static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){ + FuncDef *pDef; + pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName), + 2, SQLITE_UTF8, 0); + if( ALWAYS(pDef) ){ + pDef->funcFlags |= flagVal; + } +} + +/* +** Register the built-in LIKE and GLOB functions. The caseSensitive +** parameter determines whether or not the LIKE operator is case +** sensitive. GLOB is always case sensitive. +*/ +void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ + struct compareInfo *pInfo; + if( caseSensitive ){ + pInfo = (struct compareInfo*)&likeInfoAlt; + }else{ + pInfo = (struct compareInfo*)&likeInfoNorm; + } + sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); + sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); + sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, + (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0); + setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE); + setLikeOptFlag(db, "like", + caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE); +} + +/* +** pExpr points to an expression which implements a function. If +** it is appropriate to apply the LIKE optimization to that function +** then set aWc[0] through aWc[2] to the wildcard characters and +** return TRUE. If the function is not a LIKE-style function then +** return FALSE. +*/ +int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ + FuncDef *pDef; + if( pExpr->op!=TK_FUNCTION + || !pExpr->x.pList + || pExpr->x.pList->nExpr!=2 + ){ + return 0; + } + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + pDef = sqlite3FindFunction(db, pExpr->u.zToken, + sqlite3Strlen30(pExpr->u.zToken), + 2, SQLITE_UTF8, 0); + if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ + return 0; + } + + /* The memcpy() statement assumes that the wildcard characters are + ** the first three statements in the compareInfo structure. The + ** asserts() that follow verify that assumption + */ + memcpy(aWc, pDef->pUserData, 3); + assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); + assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); + assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); + *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0; + return 1; +} + +/* +** All all of the FuncDef structures in the aBuiltinFunc[] array above +** to the global function hash table. This occurs at start-time (as +** a consequence of calling sqlite3_initialize()). +** +** After this routine runs +*/ +void sqlite3RegisterGlobalFunctions(void){ + /* + ** The following array holds FuncDef structures for all of the functions + ** defined in this file. + ** + ** The array cannot be constant since changes are made to the + ** FuncDef.pHash elements at start-time. The elements of this array + ** are read-only after initialization is complete. + */ + static SQLITE_WSD FuncDef aBuiltinFunc[] = { + FUNCTION(ltrim, 1, 1, 0, trimFunc ), + FUNCTION(ltrim, 2, 1, 0, trimFunc ), + FUNCTION(rtrim, 1, 2, 0, trimFunc ), + FUNCTION(rtrim, 2, 2, 0, trimFunc ), + FUNCTION(trim, 1, 3, 0, trimFunc ), + FUNCTION(trim, 2, 3, 0, trimFunc ), + FUNCTION(min, -1, 0, 1, minmaxFunc ), + FUNCTION(min, 0, 0, 1, 0 ), + AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ), + FUNCTION(max, -1, 1, 1, minmaxFunc ), + FUNCTION(max, 0, 1, 1, 0 ), + AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ), + FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), + FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH), + FUNCTION(instr, 2, 0, 0, instrFunc ), + FUNCTION(substr, 2, 0, 0, substrFunc ), + FUNCTION(substr, 3, 0, 0, substrFunc ), + FUNCTION(unicode, 1, 0, 0, unicodeFunc ), + FUNCTION(char, -1, 0, 0, charFunc ), + FUNCTION(abs, 1, 0, 0, absFunc ), +#ifndef SQLITE_OMIT_FLOATING_POINT + FUNCTION(round, 1, 0, 0, roundFunc ), + FUNCTION(round, 2, 0, 0, roundFunc ), +#endif + FUNCTION(upper, 1, 0, 0, upperFunc ), + FUNCTION(lower, 1, 0, 0, lowerFunc ), + FUNCTION(coalesce, 1, 0, 0, 0 ), + FUNCTION(coalesce, 0, 0, 0, 0 ), + FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), + FUNCTION(hex, 1, 0, 0, hexFunc ), + FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), + FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), + FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), + FUNCTION(random, 0, 0, 0, randomFunc ), + FUNCTION(randomblob, 1, 0, 0, randomBlob ), + FUNCTION(nullif, 2, 0, 1, nullifFunc ), + FUNCTION(sqlite_version, 0, 0, 0, versionFunc ), + FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ), + FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS + FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), + FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + FUNCTION(quote, 1, 0, 0, quoteFunc ), + FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid), + FUNCTION(changes, 0, 0, 0, changes ), + FUNCTION(total_changes, 0, 0, 0, total_changes ), + FUNCTION(replace, 3, 0, 0, replaceFunc ), + FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ), + #ifdef SQLITE_SOUNDEX + FUNCTION(soundex, 1, 0, 0, soundexFunc ), + #endif + #ifndef SQLITE_OMIT_LOAD_EXTENSION + FUNCTION(load_extension, 1, 0, 0, loadExt ), + FUNCTION(load_extension, 2, 0, 0, loadExt ), + #endif + AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ), + AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ), + AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ), + /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */ + {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0}, + AGGREGATE(count, 1, 0, 0, countStep, countFinalize ), + AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize), + AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize), + + LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), + #ifdef SQLITE_CASE_SENSITIVE_LIKE + LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), + LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), + #else + LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE), + LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE), + #endif + }; + + int i; + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc); + + for(i=0; i? */ + + 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */ + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */ + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */ + 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */ + 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */ + 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */ + 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */ + 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */ + + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */ + + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */ +}; +#endif + +#ifndef SQLITE_USE_URI +# define SQLITE_USE_URI 0 +#endif + +#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN +# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1 +#endif + +/* +** The following singleton contains the global configuration for +** the SQLite library. +*/ +SQLITE_WSD struct Sqlite3Config sqlite3Config = { + SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */ + 1, /* bCoreMutex */ + SQLITE_THREADSAFE==1, /* bFullMutex */ + SQLITE_USE_URI, /* bOpenUri */ + SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */ + 0x7ffffffe, /* mxStrlen */ + 128, /* szLookaside */ + 500, /* nLookaside */ + {0,0,0,0,0,0,0,0}, /* m */ + {0,0,0,0,0,0,0,0,0}, /* mutex */ + {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */ + (void*)0, /* pHeap */ + 0, /* nHeap */ + 0, 0, /* mnHeap, mxHeap */ + SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */ + SQLITE_MAX_MMAP_SIZE, /* mxMmap */ + (void*)0, /* pScratch */ + 0, /* szScratch */ + 0, /* nScratch */ + (void*)0, /* pPage */ + 0, /* szPage */ + 0, /* nPage */ + 0, /* mxParserStack */ + 0, /* sharedCacheEnabled */ + /* All the rest should always be initialized to zero */ + 0, /* isInit */ + 0, /* inProgress */ + 0, /* isMutexInit */ + 0, /* isMallocInit */ + 0, /* isPCacheInit */ + 0, /* pInitMutex */ + 0, /* nRefInitMutex */ + 0, /* xLog */ + 0, /* pLogArg */ + 0, /* bLocaltimeFault */ +#ifdef SQLITE_ENABLE_SQLLOG + 0, /* xSqllog */ + 0 /* pSqllogArg */ +#endif +}; + + +/* +** Hash table for global functions - functions common to all +** database connections. After initialization, this table is +** read-only. +*/ +SQLITE_WSD FuncDefHash sqlite3GlobalFunctions; + +/* +** Constant tokens for values 0 and 1. +*/ +const Token sqlite3IntTokens[] = { + { "0", 1 }, + { "1", 1 } +}; + + +/* +** The value of the "pending" byte must be 0x40000000 (1 byte past the +** 1-gibabyte boundary) in a compatible database. SQLite never uses +** the database page that contains the pending byte. It never attempts +** to read or write that page. The pending byte page is set assign +** for use by the VFS layers as space for managing file locks. +** +** During testing, it is often desirable to move the pending byte to +** a different position in the file. This allows code that has to +** deal with the pending byte to run on files that are much smaller +** than 1 GiB. The sqlite3_test_control() interface can be used to +** move the pending byte. +** +** IMPORTANT: Changing the pending byte to any value other than +** 0x40000000 results in an incompatible database file format! +** Changing the pending byte during operating results in undefined +** and dileterious behavior. +*/ +#ifndef SQLITE_OMIT_WSD +int sqlite3PendingByte = 0x40000000; +#endif + +#include "opcodes.h" +/* +** Properties of opcodes. The OPFLG_INITIALIZER macro is +** created by mkopcodeh.awk during compilation. Data is obtained +** from the comments following the "case OP_xxxx:" statements in +** the vdbe.c file. +*/ +const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER; diff --git a/components/external/SQLite-3.8.1/src/hash.c b/components/external/SQLite-3.8.1/src/hash.c new file mode 100644 index 0000000000000000000000000000000000000000..e81dcf95e43848fa7086b7f781c090adc7e6ca8e --- /dev/null +++ b/components/external/SQLite-3.8.1/src/hash.c @@ -0,0 +1,281 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the implementation of generic hash-tables +** used in SQLite. +*/ +#include "sqliteInt.h" +#include + +/* Turn bulk memory into a hash table object by initializing the +** fields of the Hash structure. +** +** "pNew" is a pointer to the hash table that is to be initialized. +*/ +void sqlite3HashInit(Hash *pNew){ + assert( pNew!=0 ); + pNew->first = 0; + pNew->count = 0; + pNew->htsize = 0; + pNew->ht = 0; +} + +/* Remove all entries from a hash table. Reclaim all memory. +** Call this routine to delete a hash table or to reset a hash table +** to the empty state. +*/ +void sqlite3HashClear(Hash *pH){ + HashElem *elem; /* For looping over all elements of the table */ + + assert( pH!=0 ); + elem = pH->first; + pH->first = 0; + sqlite3_free(pH->ht); + pH->ht = 0; + pH->htsize = 0; + while( elem ){ + HashElem *next_elem = elem->next; + sqlite3_free(elem); + elem = next_elem; + } + pH->count = 0; +} + +/* +** The hashing function. +*/ +static unsigned int strHash(const char *z, int nKey){ + int h = 0; + assert( nKey>=0 ); + while( nKey > 0 ){ + h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++]; + nKey--; + } + return h; +} + + +/* Link pNew element into the hash table pH. If pEntry!=0 then also +** insert pNew into the pEntry hash bucket. +*/ +static void insertElement( + Hash *pH, /* The complete hash table */ + struct _ht *pEntry, /* The entry into which pNew is inserted */ + HashElem *pNew /* The element to be inserted */ +){ + HashElem *pHead; /* First element already in pEntry */ + if( pEntry ){ + pHead = pEntry->count ? pEntry->chain : 0; + pEntry->count++; + pEntry->chain = pNew; + }else{ + pHead = 0; + } + if( pHead ){ + pNew->next = pHead; + pNew->prev = pHead->prev; + if( pHead->prev ){ pHead->prev->next = pNew; } + else { pH->first = pNew; } + pHead->prev = pNew; + }else{ + pNew->next = pH->first; + if( pH->first ){ pH->first->prev = pNew; } + pNew->prev = 0; + pH->first = pNew; + } +} + + +/* Resize the hash table so that it cantains "new_size" buckets. +** +** The hash table might fail to resize if sqlite3_malloc() fails or +** if the new size is the same as the prior size. +** Return TRUE if the resize occurs and false if not. +*/ +static int rehash(Hash *pH, unsigned int new_size){ + struct _ht *new_ht; /* The new hash table */ + HashElem *elem, *next_elem; /* For looping over existing elements */ + +#if SQLITE_MALLOC_SOFT_LIMIT>0 + if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){ + new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht); + } + if( new_size==pH->htsize ) return 0; +#endif + + /* The inability to allocates space for a larger hash table is + ** a performance hit but it is not a fatal error. So mark the + ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of + ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero() + ** only zeroes the requested number of bytes whereas this module will + ** use the actual amount of space allocated for the hash table (which + ** may be larger than the requested amount). + */ + sqlite3BeginBenignMalloc(); + new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) ); + sqlite3EndBenignMalloc(); + + if( new_ht==0 ) return 0; + sqlite3_free(pH->ht); + pH->ht = new_ht; + pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); + memset(new_ht, 0, new_size*sizeof(struct _ht)); + for(elem=pH->first, pH->first=0; elem; elem = next_elem){ + unsigned int h = strHash(elem->pKey, elem->nKey) % new_size; + next_elem = elem->next; + insertElement(pH, &new_ht[h], elem); + } + return 1; +} + +/* This function (for internal use only) locates an element in an +** hash table that matches the given key. The hash for this key has +** already been computed and is passed as the 4th parameter. +*/ +static HashElem *findElementGivenHash( + const Hash *pH, /* The pH to be searched */ + const char *pKey, /* The key we are searching for */ + int nKey, /* Bytes in key (not counting zero terminator) */ + unsigned int h /* The hash for this key. */ +){ + HashElem *elem; /* Used to loop thru the element list */ + int count; /* Number of elements left to test */ + + if( pH->ht ){ + struct _ht *pEntry = &pH->ht[h]; + elem = pEntry->chain; + count = pEntry->count; + }else{ + elem = pH->first; + count = pH->count; + } + while( count-- && ALWAYS(elem) ){ + if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ + return elem; + } + elem = elem->next; + } + return 0; +} + +/* Remove a single entry from the hash table given a pointer to that +** element and a hash on the element's key. +*/ +static void removeElementGivenHash( + Hash *pH, /* The pH containing "elem" */ + HashElem* elem, /* The element to be removed from the pH */ + unsigned int h /* Hash value for the element */ +){ + struct _ht *pEntry; + if( elem->prev ){ + elem->prev->next = elem->next; + }else{ + pH->first = elem->next; + } + if( elem->next ){ + elem->next->prev = elem->prev; + } + if( pH->ht ){ + pEntry = &pH->ht[h]; + if( pEntry->chain==elem ){ + pEntry->chain = elem->next; + } + pEntry->count--; + assert( pEntry->count>=0 ); + } + sqlite3_free( elem ); + pH->count--; + if( pH->count==0 ){ + assert( pH->first==0 ); + assert( pH->count==0 ); + sqlite3HashClear(pH); + } +} + +/* Attempt to locate an element of the hash table pH with a key +** that matches pKey,nKey. Return the data for this element if it is +** found, or NULL if there is no match. +*/ +void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){ + HashElem *elem; /* The element that matches key */ + unsigned int h; /* A hash on key */ + + assert( pH!=0 ); + assert( pKey!=0 ); + assert( nKey>=0 ); + if( pH->ht ){ + h = strHash(pKey, nKey) % pH->htsize; + }else{ + h = 0; + } + elem = findElementGivenHash(pH, pKey, nKey, h); + return elem ? elem->data : 0; +} + +/* Insert an element into the hash table pH. The key is pKey,nKey +** and the data is "data". +** +** If no element exists with a matching key, then a new +** element is created and NULL is returned. +** +** If another element already exists with the same key, then the +** new data replaces the old data and the old data is returned. +** The key is not copied in this instance. If a malloc fails, then +** the new data is returned and the hash table is unchanged. +** +** If the "data" parameter to this function is NULL, then the +** element corresponding to "key" is removed from the hash table. +*/ +void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){ + unsigned int h; /* the hash of the key modulo hash table size */ + HashElem *elem; /* Used to loop thru the element list */ + HashElem *new_elem; /* New element added to the pH */ + + assert( pH!=0 ); + assert( pKey!=0 ); + assert( nKey>=0 ); + if( pH->htsize ){ + h = strHash(pKey, nKey) % pH->htsize; + }else{ + h = 0; + } + elem = findElementGivenHash(pH,pKey,nKey,h); + if( elem ){ + void *old_data = elem->data; + if( data==0 ){ + removeElementGivenHash(pH,elem,h); + }else{ + elem->data = data; + elem->pKey = pKey; + assert(nKey==elem->nKey); + } + return old_data; + } + if( data==0 ) return 0; + new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) ); + if( new_elem==0 ) return data; + new_elem->pKey = pKey; + new_elem->nKey = nKey; + new_elem->data = data; + pH->count++; + if( pH->count>=10 && pH->count > 2*pH->htsize ){ + if( rehash(pH, pH->count*2) ){ + assert( pH->htsize>0 ); + h = strHash(pKey, nKey) % pH->htsize; + } + } + if( pH->ht ){ + insertElement(pH, &pH->ht[h], new_elem); + }else{ + insertElement(pH, 0, new_elem); + } + return 0; +} diff --git a/components/external/SQLite-3.8.1/src/hash.h b/components/external/SQLite-3.8.1/src/hash.h new file mode 100644 index 0000000000000000000000000000000000000000..82b7c58c71090b547e101742aa0951739ff2eee7 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/hash.h @@ -0,0 +1,96 @@ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implementation +** used in SQLite. +*/ +#ifndef _SQLITE_HASH_H_ +#define _SQLITE_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct Hash Hash; +typedef struct HashElem HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, some of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +** +** All elements of the hash table are on a single doubly-linked list. +** Hash.first points to the head of this list. +** +** There are Hash.htsize buckets. Each bucket points to a spot in +** the global doubly-linked list. The contents of the bucket are the +** element pointed to plus the next _ht.count-1 elements in the list. +** +** Hash.htsize and Hash.ht may be zero. In that case lookup is done +** by a linear search of the global list. For small tables, the +** Hash.ht table is never allocated because if there are few elements +** in the table, it is faster to do a linear search than to manage +** the hash table. +*/ +struct Hash { + unsigned int htsize; /* Number of buckets in the hash table */ + unsigned int count; /* Number of entries in this table */ + HashElem *first; /* The first element of the array */ + struct _ht { /* the hash table */ + int count; /* Number of entries with this hash */ + HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct HashElem { + HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + const char *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +void sqlite3HashInit(Hash*); +void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData); +void *sqlite3HashFind(const Hash*, const char *pKey, int nKey); +void sqlite3HashClear(Hash*); + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** Hash h; +** HashElem *p; +** ... +** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ +** SomeStructure *pData = sqliteHashData(p); +** // do something with pData +** } +*/ +#define sqliteHashFirst(H) ((H)->first) +#define sqliteHashNext(E) ((E)->next) +#define sqliteHashData(E) ((E)->data) +/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ +/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ + +/* +** Number of entries in a hash table +*/ +/* #define sqliteHashCount(H) ((H)->count) // NOT USED */ + +#endif /* _SQLITE_HASH_H_ */ diff --git a/components/external/SQLite-3.8.1/src/hwtime.h b/components/external/SQLite-3.8.1/src/hwtime.h new file mode 100644 index 0000000000000000000000000000000000000000..b8bc5a295be3fac8351fa9f08a77579d59c9a8e4 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/hwtime.h @@ -0,0 +1,85 @@ +/* +** 2008 May 27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains inline asm code for retrieving "high-performance" +** counters for x86 class CPUs. +*/ +#ifndef _HWTIME_H_ +#define _HWTIME_H_ + +/* +** The following routine only works on pentium-class (or newer) processors. +** It uses the RDTSC opcode to read the cycle count value out of the +** processor and returns that value. This can be used for high-res +** profiling. +*/ +#if (defined(__GNUC__) || defined(_MSC_VER)) && \ + (defined(i386) || defined(__i386__) || defined(_M_IX86)) + + #if defined(__GNUC__) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + unsigned int lo, hi; + __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); + return (sqlite_uint64)hi << 32 | lo; + } + + #elif defined(_MSC_VER) + + __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ + __asm { + rdtsc + ret ; return value at EDX:EAX + } + } + + #endif + +#elif (defined(__GNUC__) && defined(__x86_64__)) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + unsigned long val; + __asm__ __volatile__ ("rdtsc" : "=A" (val)); + return val; + } + +#elif (defined(__GNUC__) && defined(__ppc__)) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + unsigned long long retval; + unsigned long junk; + __asm__ __volatile__ ("\n\ + 1: mftbu %1\n\ + mftb %L0\n\ + mftbu %0\n\ + cmpw %0,%1\n\ + bne 1b" + : "=r" (retval), "=r" (junk)); + return retval; + } + +#else + + #error Need implementation of sqlite3Hwtime() for your platform. + + /* + ** To compile without implementing sqlite3Hwtime() for your platform, + ** you can remove the above #error and use the following + ** stub function. You will lose timing support for many + ** of the debugging and testing utilities, but it should at + ** least compile and run. + */ + sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } + +#endif + +#endif /* !defined(_HWTIME_H_) */ diff --git a/components/external/SQLite-3.8.1/src/insert.c b/components/external/SQLite-3.8.1/src/insert.c new file mode 100644 index 0000000000000000000000000000000000000000..2f5a386cad068897a6cf5cb95be3e188641df5d6 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/insert.c @@ -0,0 +1,1925 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that are called by the parser +** to handle INSERT statements in SQLite. +*/ +#include "sqliteInt.h" + +/* +** Generate code that will open a table for reading. +*/ +void sqlite3OpenTable( + Parse *p, /* Generate code into this VDBE */ + int iCur, /* The cursor number of the table */ + int iDb, /* The database index in sqlite3.aDb[] */ + Table *pTab, /* The table to be opened */ + int opcode /* OP_OpenRead or OP_OpenWrite */ +){ + Vdbe *v; + assert( !IsVirtual(pTab) ); + v = sqlite3GetVdbe(p); + assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); + sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName); + sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb); + sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32); + VdbeComment((v, "%s", pTab->zName)); +} + +/* +** Return a pointer to the column affinity string associated with index +** pIdx. A column affinity string has one character for each column in +** the table, according to the affinity of the column: +** +** Character Column affinity +** ------------------------------ +** 'a' TEXT +** 'b' NONE +** 'c' NUMERIC +** 'd' INTEGER +** 'e' REAL +** +** An extra 'd' is appended to the end of the string to cover the +** rowid that appears as the last column in every index. +** +** Memory for the buffer containing the column index affinity string +** is managed along with the rest of the Index structure. It will be +** released when sqlite3DeleteIndex() is called. +*/ +const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ + if( !pIdx->zColAff ){ + /* The first time a column affinity string for a particular index is + ** required, it is allocated and populated here. It is then stored as + ** a member of the Index structure for subsequent use. + ** + ** The column affinity string will eventually be deleted by + ** sqliteDeleteIndex() when the Index structure itself is cleaned + ** up. + */ + int n; + Table *pTab = pIdx->pTable; + sqlite3 *db = sqlite3VdbeDb(v); + pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2); + if( !pIdx->zColAff ){ + db->mallocFailed = 1; + return 0; + } + for(n=0; nnColumn; n++){ + pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; + } + pIdx->zColAff[n++] = SQLITE_AFF_INTEGER; + pIdx->zColAff[n] = 0; + } + + return pIdx->zColAff; +} + +/* +** Set P4 of the most recently inserted opcode to a column affinity +** string for table pTab. A column affinity string has one character +** for each column indexed by the index, according to the affinity of the +** column: +** +** Character Column affinity +** ------------------------------ +** 'a' TEXT +** 'b' NONE +** 'c' NUMERIC +** 'd' INTEGER +** 'e' REAL +*/ +void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ + /* The first time a column affinity string for a particular table + ** is required, it is allocated and populated here. It is then + ** stored as a member of the Table structure for subsequent use. + ** + ** The column affinity string will eventually be deleted by + ** sqlite3DeleteTable() when the Table structure itself is cleaned up. + */ + if( !pTab->zColAff ){ + char *zColAff; + int i; + sqlite3 *db = sqlite3VdbeDb(v); + + zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); + if( !zColAff ){ + db->mallocFailed = 1; + return; + } + + for(i=0; inCol; i++){ + zColAff[i] = pTab->aCol[i].affinity; + } + zColAff[pTab->nCol] = '\0'; + + pTab->zColAff = zColAff; + } + + sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT); +} + +/* +** Return non-zero if the table pTab in database iDb or any of its indices +** have been opened at any point in the VDBE program beginning at location +** iStartAddr throught the end of the program. This is used to see if +** a statement of the form "INSERT INTO SELECT ..." can +** run without using temporary table for the results of the SELECT. +*/ +static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){ + Vdbe *v = sqlite3GetVdbe(p); + int i; + int iEnd = sqlite3VdbeCurrentAddr(v); +#ifndef SQLITE_OMIT_VIRTUALTABLE + VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; +#endif + + for(i=iStartAddr; iopcode==OP_OpenRead && pOp->p3==iDb ){ + Index *pIndex; + int tnum = pOp->p2; + if( tnum==pTab->tnum ){ + return 1; + } + for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ + if( tnum==pIndex->tnum ){ + return 1; + } + } + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ + assert( pOp->p4.pVtab!=0 ); + assert( pOp->p4type==P4_VTAB ); + return 1; + } +#endif + } + return 0; +} + +#ifndef SQLITE_OMIT_AUTOINCREMENT +/* +** Locate or create an AutoincInfo structure associated with table pTab +** which is in database iDb. Return the register number for the register +** that holds the maximum rowid. +** +** There is at most one AutoincInfo structure per table even if the +** same table is autoincremented multiple times due to inserts within +** triggers. A new AutoincInfo structure is created if this is the +** first use of table pTab. On 2nd and subsequent uses, the original +** AutoincInfo structure is used. +** +** Three memory locations are allocated: +** +** (1) Register to hold the name of the pTab table. +** (2) Register to hold the maximum ROWID of pTab. +** (3) Register to hold the rowid in sqlite_sequence of pTab +** +** The 2nd register is the one that is returned. That is all the +** insert routine needs to know about. +*/ +static int autoIncBegin( + Parse *pParse, /* Parsing context */ + int iDb, /* Index of the database holding pTab */ + Table *pTab /* The table we are writing to */ +){ + int memId = 0; /* Register holding maximum rowid */ + if( pTab->tabFlags & TF_Autoincrement ){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + AutoincInfo *pInfo; + + pInfo = pToplevel->pAinc; + while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } + if( pInfo==0 ){ + pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo)); + if( pInfo==0 ) return 0; + pInfo->pNext = pToplevel->pAinc; + pToplevel->pAinc = pInfo; + pInfo->pTab = pTab; + pInfo->iDb = iDb; + pToplevel->nMem++; /* Register to hold name of table */ + pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ + pToplevel->nMem++; /* Rowid in sqlite_sequence */ + } + memId = pInfo->regCtr; + } + return memId; +} + +/* +** This routine generates code that will initialize all of the +** register used by the autoincrement tracker. +*/ +void sqlite3AutoincrementBegin(Parse *pParse){ + AutoincInfo *p; /* Information about an AUTOINCREMENT */ + sqlite3 *db = pParse->db; /* The database connection */ + Db *pDb; /* Database only autoinc table */ + int memId; /* Register holding max rowid */ + int addr; /* A VDBE address */ + Vdbe *v = pParse->pVdbe; /* VDBE under construction */ + + /* This routine is never called during trigger-generation. It is + ** only called from the top-level */ + assert( pParse->pTriggerTab==0 ); + assert( pParse==sqlite3ParseToplevel(pParse) ); + + assert( v ); /* We failed long ago if this is not so */ + for(p = pParse->pAinc; p; p = p->pNext){ + pDb = &db->aDb[p->iDb]; + memId = p->regCtr; + assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); + sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); + sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1); + addr = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0); + sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); + sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId); + sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); + sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); + sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); + sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9); + sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); + sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); + sqlite3VdbeAddOp0(v, OP_Close); + } +} + +/* +** Update the maximum rowid for an autoincrement calculation. +** +** This routine should be called when the top of the stack holds a +** new rowid that is about to be inserted. If that new rowid is +** larger than the maximum rowid in the memId memory cell, then the +** memory cell is updated. The stack is unchanged. +*/ +static void autoIncStep(Parse *pParse, int memId, int regRowid){ + if( memId>0 ){ + sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); + } +} + +/* +** This routine generates the code needed to write autoincrement +** maximum rowid values back into the sqlite_sequence register. +** Every statement that might do an INSERT into an autoincrement +** table (either directly or through triggers) needs to call this +** routine just before the "exit" code. +*/ +void sqlite3AutoincrementEnd(Parse *pParse){ + AutoincInfo *p; + Vdbe *v = pParse->pVdbe; + sqlite3 *db = pParse->db; + + assert( v ); + for(p = pParse->pAinc; p; p = p->pNext){ + Db *pDb = &db->aDb[p->iDb]; + int j1, j2, j3, j4, j5; + int iRec; + int memId = p->regCtr; + + iRec = sqlite3GetTempReg(pParse); + assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); + sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); + j2 = sqlite3VdbeAddOp0(v, OP_Rewind); + j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec); + j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec); + sqlite3VdbeAddOp2(v, OP_Next, 0, j3); + sqlite3VdbeJumpHere(v, j2); + sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1); + j5 = sqlite3VdbeAddOp0(v, OP_Goto); + sqlite3VdbeJumpHere(v, j4); + sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1); + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeJumpHere(v, j5); + sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); + sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3VdbeAddOp0(v, OP_Close); + sqlite3ReleaseTempReg(pParse, iRec); + } +} +#else +/* +** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines +** above are all no-ops +*/ +# define autoIncBegin(A,B,C) (0) +# define autoIncStep(A,B,C) +#endif /* SQLITE_OMIT_AUTOINCREMENT */ + + +/* +** Generate code for a co-routine that will evaluate a subquery one +** row at a time. +** +** The pSelect parameter is the subquery that the co-routine will evaluation. +** Information about the location of co-routine and the registers it will use +** is returned by filling in the pDest object. +** +** Registers are allocated as follows: +** +** pDest->iSDParm The register holding the next entry-point of the +** co-routine. Run the co-routine to its next breakpoint +** by calling "OP_Yield $X" where $X is pDest->iSDParm. +** +** pDest->iSDParm+1 The register holding the "completed" flag for the +** co-routine. This register is 0 if the previous Yield +** generated a new result row, or 1 if the subquery +** has completed. If the Yield is called again +** after this register becomes 1, then the VDBE will +** halt with an SQLITE_INTERNAL error. +** +** pDest->iSdst First result register. +** +** pDest->nSdst Number of result registers. +** +** This routine handles all of the register allocation and fills in the +** pDest structure appropriately. +** +** Here is a schematic of the generated code assuming that X is the +** co-routine entry-point register reg[pDest->iSDParm], that EOF is the +** completed flag reg[pDest->iSDParm+1], and R and S are the range of +** registers that hold the result set, reg[pDest->iSdst] through +** reg[pDest->iSdst+pDest->nSdst-1]: +** +** X <- A +** EOF <- 0 +** goto B +** A: setup for the SELECT +** loop rows in the SELECT +** load results into registers R..S +** yield X +** end loop +** cleanup after the SELECT +** EOF <- 1 +** yield X +** halt-error +** B: +** +** To use this subroutine, the caller generates code as follows: +** +** [ Co-routine generated by this subroutine, shown above ] +** S: yield X +** if EOF goto E +** if skip this row, goto C +** if terminate loop, goto E +** deal with this row +** C: goto S +** E: +*/ +int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){ + int regYield; /* Register holding co-routine entry-point */ + int regEof; /* Register holding co-routine completion flag */ + int addrTop; /* Top of the co-routine */ + int j1; /* Jump instruction */ + int rc; /* Result code */ + Vdbe *v; /* VDBE under construction */ + + regYield = ++pParse->nMem; + regEof = ++pParse->nMem; + v = sqlite3GetVdbe(pParse); + addrTop = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */ + VdbeComment((v, "Co-routine entry point")); + sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */ + VdbeComment((v, "Co-routine completion flag")); + sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield); + j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); + rc = sqlite3Select(pParse, pSelect, pDest); + assert( pParse->nErr==0 || rc ); + if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM; + if( rc ) return rc; + sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */ + sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */ + sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort); + VdbeComment((v, "End of coroutine")); + sqlite3VdbeJumpHere(v, j1); /* label B: */ + return rc; +} + + + +/* Forward declaration */ +static int xferOptimization( + Parse *pParse, /* Parser context */ + Table *pDest, /* The table we are inserting into */ + Select *pSelect, /* A SELECT statement to use as the data source */ + int onError, /* How to handle constraint errors */ + int iDbDest /* The database of pDest */ +); + +/* +** This routine is call to handle SQL of the following forms: +** +** insert into TABLE (IDLIST) values(EXPRLIST) +** insert into TABLE (IDLIST) select +** +** The IDLIST following the table name is always optional. If omitted, +** then a list of all columns for the table is substituted. The IDLIST +** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. +** +** The pList parameter holds EXPRLIST in the first form of the INSERT +** statement above, and pSelect is NULL. For the second form, pList is +** NULL and pSelect is a pointer to the select statement used to generate +** data for the insert. +** +** The code generated follows one of four templates. For a simple +** select with data coming from a VALUES clause, the code executes +** once straight down through. Pseudo-code follows (we call this +** the "1st template"): +** +** open write cursor to
and its indices +** puts VALUES clause expressions onto the stack +** write the resulting record into
+** cleanup +** +** The three remaining templates assume the statement is of the form +** +** INSERT INTO
SELECT ... +** +** If the SELECT clause is of the restricted form "SELECT * FROM " - +** in other words if the SELECT pulls all columns from a single table +** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and +** if and are distinct tables but have identical +** schemas, including all the same indices, then a special optimization +** is invoked that copies raw records from over to . +** See the xferOptimization() function for the implementation of this +** template. This is the 2nd template. +** +** open a write cursor to
+** open read cursor on +** transfer all records in over to
+** close cursors +** foreach index on
+** open a write cursor on the
index +** open a read cursor on the corresponding index +** transfer all records from the read to the write cursors +** close cursors +** end foreach +** +** The 3rd template is for when the second template does not apply +** and the SELECT clause does not read from
at any time. +** The generated code follows this template: +** +** EOF <- 0 +** X <- A +** goto B +** A: setup for the SELECT +** loop over the rows in the SELECT +** load values into registers R..R+n +** yield X +** end loop +** cleanup after the SELECT +** EOF <- 1 +** yield X +** goto A +** B: open write cursor to
and its indices +** C: yield X +** if EOF goto D +** insert the select result into
from R..R+n +** goto C +** D: cleanup +** +** The 4th template is used if the insert statement takes its +** values from a SELECT but the data is being inserted into a table +** that is also read as part of the SELECT. In the third form, +** we have to use a intermediate table to store the results of +** the select. The template is like this: +** +** EOF <- 0 +** X <- A +** goto B +** A: setup for the SELECT +** loop over the tables in the SELECT +** load value into register R..R+n +** yield X +** end loop +** cleanup after the SELECT +** EOF <- 1 +** yield X +** halt-error +** B: open temp table +** L: yield X +** if EOF goto M +** insert row from R..R+n into temp table +** goto L +** M: open write cursor to
and its indices +** rewind temp table +** C: loop over rows of intermediate table +** transfer values form intermediate table into
+** end loop +** D: cleanup +*/ +void sqlite3Insert( + Parse *pParse, /* Parser context */ + SrcList *pTabList, /* Name of table into which we are inserting */ + ExprList *pList, /* List of values to be inserted */ + Select *pSelect, /* A SELECT statement to use as the data source */ + IdList *pColumn, /* Column names corresponding to IDLIST. */ + int onError /* How to handle constraint errors */ +){ + sqlite3 *db; /* The main database structure */ + Table *pTab; /* The table to insert into. aka TABLE */ + char *zTab; /* Name of the table into which we are inserting */ + const char *zDb; /* Name of the database holding this table */ + int i, j, idx; /* Loop counters */ + Vdbe *v; /* Generate code into this virtual machine */ + Index *pIdx; /* For looping over indices of the table */ + int nColumn; /* Number of columns in the data */ + int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ + int baseCur = 0; /* VDBE Cursor number for pTab */ + int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ + int endOfLoop; /* Label for the end of the insertion loop */ + int useTempTable = 0; /* Store SELECT results in intermediate table */ + int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ + int addrInsTop = 0; /* Jump to label "D" */ + int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ + int addrSelect = 0; /* Address of coroutine that implements the SELECT */ + SelectDest dest; /* Destination for SELECT on rhs of INSERT */ + int iDb; /* Index of database holding TABLE */ + Db *pDb; /* The database containing table being inserted into */ + int appendFlag = 0; /* True if the insert is likely to be an append */ + + /* Register allocations */ + int regFromSelect = 0;/* Base register for data coming from SELECT */ + int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ + int regRowCount = 0; /* Memory cell used for the row counter */ + int regIns; /* Block of regs holding rowid+data being inserted */ + int regRowid; /* registers holding insert rowid */ + int regData; /* register holding first column to insert */ + int regEof = 0; /* Register recording end of SELECT data */ + int *aRegIdx = 0; /* One register allocated to each index */ + +#ifndef SQLITE_OMIT_TRIGGER + int isView; /* True if attempting to insert into a view */ + Trigger *pTrigger; /* List of triggers on pTab, if required */ + int tmask; /* Mask of trigger times */ +#endif + + db = pParse->db; + memset(&dest, 0, sizeof(dest)); + if( pParse->nErr || db->mallocFailed ){ + goto insert_cleanup; + } + + /* Locate the table into which we will be inserting new information. + */ + assert( pTabList->nSrc==1 ); + zTab = pTabList->a[0].zName; + if( NEVER(zTab==0) ) goto insert_cleanup; + pTab = sqlite3SrcListLookup(pParse, pTabList); + if( pTab==0 ){ + goto insert_cleanup; + } + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( iDbnDb ); + pDb = &db->aDb[iDb]; + zDb = pDb->zName; + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){ + goto insert_cleanup; + } + + /* Figure out if we have any triggers and if the table being + ** inserted into is a view + */ +#ifndef SQLITE_OMIT_TRIGGER + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); + isView = pTab->pSelect!=0; +#else +# define pTrigger 0 +# define tmask 0 +# define isView 0 +#endif +#ifdef SQLITE_OMIT_VIEW +# undef isView +# define isView 0 +#endif + assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); + + /* If pTab is really a view, make sure it has been initialized. + ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual + ** module table). + */ + if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto insert_cleanup; + } + + /* Ensure that: + * (a) the table is not read-only, + * (b) that if it is a view then ON INSERT triggers exist + */ + if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ + goto insert_cleanup; + } + + /* Allocate a VDBE + */ + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto insert_cleanup; + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); + sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); + +#ifndef SQLITE_OMIT_XFER_OPT + /* If the statement is of the form + ** + ** INSERT INTO SELECT * FROM ; + ** + ** Then special optimizations can be applied that make the transfer + ** very fast and which reduce fragmentation of indices. + ** + ** This is the 2nd template. + */ + if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ + assert( !pTrigger ); + assert( pList==0 ); + goto insert_end; + } +#endif /* SQLITE_OMIT_XFER_OPT */ + + /* If this is an AUTOINCREMENT table, look up the sequence number in the + ** sqlite_sequence table and store it in memory cell regAutoinc. + */ + regAutoinc = autoIncBegin(pParse, iDb, pTab); + + /* Figure out how many columns of data are supplied. If the data + ** is coming from a SELECT statement, then generate a co-routine that + ** produces a single row of the SELECT on each invocation. The + ** co-routine is the common header to the 3rd and 4th templates. + */ + if( pSelect ){ + /* Data is coming from a SELECT. Generate a co-routine to run that + ** SELECT. */ + int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest); + if( rc ) goto insert_cleanup; + + regEof = dest.iSDParm + 1; + regFromSelect = dest.iSdst; + assert( pSelect->pEList ); + nColumn = pSelect->pEList->nExpr; + assert( dest.nSdst==nColumn ); + + /* Set useTempTable to TRUE if the result of the SELECT statement + ** should be written into a temporary table (template 4). Set to + ** FALSE if each* row of the SELECT can be written directly into + ** the destination table (template 3). + ** + ** A temp table must be used if the table being updated is also one + ** of the tables being read by the SELECT statement. Also use a + ** temp table in the case of row triggers. + */ + if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){ + useTempTable = 1; + } + + if( useTempTable ){ + /* Invoke the coroutine to extract information from the SELECT + ** and add it to a transient table srcTab. The code generated + ** here is from the 4th template: + ** + ** B: open temp table + ** L: yield X + ** if EOF goto M + ** insert row from R..R+n into temp table + ** goto L + ** M: ... + */ + int regRec; /* Register to hold packed record */ + int regTempRowid; /* Register to hold temp table ROWID */ + int addrTop; /* Label "L" */ + int addrIf; /* Address of jump to M */ + + srcTab = pParse->nTab++; + regRec = sqlite3GetTempReg(pParse); + regTempRowid = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); + addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); + addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); + sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); + sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); + sqlite3VdbeJumpHere(v, addrIf); + sqlite3ReleaseTempReg(pParse, regRec); + sqlite3ReleaseTempReg(pParse, regTempRowid); + } + }else{ + /* This is the case if the data for the INSERT is coming from a VALUES + ** clause + */ + NameContext sNC; + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + srcTab = -1; + assert( useTempTable==0 ); + nColumn = pList ? pList->nExpr : 0; + for(i=0; ia[i].pExpr) ){ + goto insert_cleanup; + } + } + } + + /* Make sure the number of columns in the source data matches the number + ** of columns to be inserted into the table. + */ + if( IsVirtual(pTab) ){ + for(i=0; inCol; i++){ + nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); + } + } + if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ + sqlite3ErrorMsg(pParse, + "table %S has %d columns but %d values were supplied", + pTabList, 0, pTab->nCol-nHidden, nColumn); + goto insert_cleanup; + } + if( pColumn!=0 && nColumn!=pColumn->nId ){ + sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); + goto insert_cleanup; + } + + /* If the INSERT statement included an IDLIST term, then make sure + ** all elements of the IDLIST really are columns of the table and + ** remember the column indices. + ** + ** If the table has an INTEGER PRIMARY KEY column and that column + ** is named in the IDLIST, then record in the keyColumn variable + ** the index into IDLIST of the primary key column. keyColumn is + ** the index of the primary key as it appears in IDLIST, not as + ** is appears in the original table. (The index of the primary + ** key in the original table is pTab->iPKey.) + */ + if( pColumn ){ + for(i=0; inId; i++){ + pColumn->a[i].idx = -1; + } + for(i=0; inId; i++){ + for(j=0; jnCol; j++){ + if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ + pColumn->a[i].idx = j; + if( j==pTab->iPKey ){ + keyColumn = i; + } + break; + } + } + if( j>=pTab->nCol ){ + if( sqlite3IsRowid(pColumn->a[i].zName) ){ + keyColumn = i; + }else{ + sqlite3ErrorMsg(pParse, "table %S has no column named %s", + pTabList, 0, pColumn->a[i].zName); + pParse->checkSchema = 1; + goto insert_cleanup; + } + } + } + } + + /* If there is no IDLIST term but the table has an integer primary + ** key, the set the keyColumn variable to the primary key column index + ** in the original table definition. + */ + if( pColumn==0 && nColumn>0 ){ + keyColumn = pTab->iPKey; + } + + /* Initialize the count of rows to be inserted + */ + if( db->flags & SQLITE_CountRows ){ + regRowCount = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); + } + + /* If this is not a view, open the table and and all indices */ + if( !isView ){ + int nIdx; + + baseCur = pParse->nTab; + nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); + aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); + if( aRegIdx==0 ){ + goto insert_cleanup; + } + for(i=0; inMem; + } + } + + /* This is the top of the main insertion loop */ + if( useTempTable ){ + /* This block codes the top of loop only. The complete loop is the + ** following pseudocode (template 4): + ** + ** rewind temp table + ** C: loop over rows of intermediate table + ** transfer values form intermediate table into
+ ** end loop + ** D: ... + */ + addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); + addrCont = sqlite3VdbeCurrentAddr(v); + }else if( pSelect ){ + /* This block codes the top of loop only. The complete loop is the + ** following pseudocode (template 3): + ** + ** C: yield X + ** if EOF goto D + ** insert the select result into
from R..R+n + ** goto C + ** D: ... + */ + addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); + addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof); + } + + /* Allocate registers for holding the rowid of the new row, + ** the content of the new row, and the assemblied row record. + */ + regRowid = regIns = pParse->nMem+1; + pParse->nMem += pTab->nCol + 1; + if( IsVirtual(pTab) ){ + regRowid++; + pParse->nMem++; + } + regData = regRowid+1; + + /* Run the BEFORE and INSTEAD OF triggers, if there are any + */ + endOfLoop = sqlite3VdbeMakeLabel(v); + if( tmask & TRIGGER_BEFORE ){ + int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); + + /* build the NEW.* reference row. Note that if there is an INTEGER + ** PRIMARY KEY into which a NULL is being inserted, that NULL will be + ** translated into a unique ID for the row. But on a BEFORE trigger, + ** we do not know what the unique ID will be (because the insert has + ** not happened yet) so we substitute a rowid of -1 + */ + if( keyColumn<0 ){ + sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); + }else{ + int j1; + if( useTempTable ){ + sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols); + }else{ + assert( pSelect==0 ); /* Otherwise useTempTable is true */ + sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols); + } + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); + sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); + } + + /* Cannot have triggers on a virtual table. If it were possible, + ** this block would have to account for hidden column. + */ + assert( !IsVirtual(pTab) ); + + /* Create the new column data + */ + for(i=0; inCol; i++){ + if( pColumn==0 ){ + j = i; + }else{ + for(j=0; jnId; j++){ + if( pColumn->a[j].idx==i ) break; + } + } + if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){ + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); + }else if( useTempTable ){ + sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); + }else{ + assert( pSelect==0 ); /* Otherwise useTempTable is true */ + sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); + } + } + + /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, + ** do not attempt any conversions before assembling the record. + ** If this is a real table, attempt conversions as required by the + ** table column affinities. + */ + if( !isView ){ + sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol); + sqlite3TableAffinityStr(v, pTab); + } + + /* Fire BEFORE or INSTEAD OF triggers */ + sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, + pTab, regCols-pTab->nCol-1, onError, endOfLoop); + + sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); + } + + /* Push the record number for the new entry onto the stack. The + ** record number is a randomly generate integer created by NewRowid + ** except when the table has an INTEGER PRIMARY KEY column, in which + ** case the record number is the same as that column. + */ + if( !isView ){ + if( IsVirtual(pTab) ){ + /* The row that the VUpdate opcode will delete: none */ + sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); + } + if( keyColumn>=0 ){ + if( useTempTable ){ + sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); + }else if( pSelect ){ + sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); + }else{ + VdbeOp *pOp; + sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); + pOp = sqlite3VdbeGetOp(v, -1); + if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ + appendFlag = 1; + pOp->opcode = OP_NewRowid; + pOp->p1 = baseCur; + pOp->p2 = regRowid; + pOp->p3 = regAutoinc; + } + } + /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid + ** to generate a unique primary key value. + */ + if( !appendFlag ){ + int j1; + if( !IsVirtual(pTab) ){ + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); + sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); + sqlite3VdbeJumpHere(v, j1); + }else{ + j1 = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); + } + sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); + } + }else if( IsVirtual(pTab) ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); + }else{ + sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); + appendFlag = 1; + } + autoIncStep(pParse, regAutoinc, regRowid); + + /* Push onto the stack, data for all columns of the new entry, beginning + ** with the first column. + */ + nHidden = 0; + for(i=0; inCol; i++){ + int iRegStore = regRowid+1+i; + if( i==pTab->iPKey ){ + /* The value of the INTEGER PRIMARY KEY column is always a NULL. + ** Whenever this column is read, the record number will be substituted + ** in its place. So will fill this column with a NULL to avoid + ** taking up data space with information that will never be used. */ + sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); + continue; + } + if( pColumn==0 ){ + if( IsHiddenColumn(&pTab->aCol[i]) ){ + assert( IsVirtual(pTab) ); + j = -1; + nHidden++; + }else{ + j = i - nHidden; + } + }else{ + for(j=0; jnId; j++){ + if( pColumn->a[j].idx==i ) break; + } + } + if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); + }else if( useTempTable ){ + sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); + }else if( pSelect ){ + sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); + }else{ + sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); + } + } + + /* Generate code to check constraints and generate index keys and + ** do the insertion. + */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); + sqlite3VtabMakeWritable(pParse, pTab); + sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); + sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); + sqlite3MayAbort(pParse); + }else +#endif + { + int isReplace; /* Set to true if constraints may cause a replace */ + sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx, + keyColumn>=0, 0, onError, endOfLoop, &isReplace + ); + sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); + sqlite3CompleteInsertion( + pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0 + ); + } + } + + /* Update the count of rows that are inserted + */ + if( (db->flags & SQLITE_CountRows)!=0 ){ + sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); + } + + if( pTrigger ){ + /* Code AFTER triggers */ + sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, + pTab, regData-2-pTab->nCol, onError, endOfLoop); + } + + /* The bottom of the main insertion loop, if the data source + ** is a SELECT statement. + */ + sqlite3VdbeResolveLabel(v, endOfLoop); + if( useTempTable ){ + sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); + sqlite3VdbeJumpHere(v, addrInsTop); + sqlite3VdbeAddOp1(v, OP_Close, srcTab); + }else if( pSelect ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont); + sqlite3VdbeJumpHere(v, addrInsTop); + } + + if( !IsVirtual(pTab) && !isView ){ + /* Close all tables opened */ + sqlite3VdbeAddOp1(v, OP_Close, baseCur); + for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ + sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur); + } + } + +insert_end: + /* Update the sqlite_sequence table by storing the content of the + ** maximum rowid counter values recorded while inserting into + ** autoincrement tables. + */ + if( pParse->nested==0 && pParse->pTriggerTab==0 ){ + sqlite3AutoincrementEnd(pParse); + } + + /* + ** Return the number of rows inserted. If this routine is + ** generating code because of a call to sqlite3NestedParse(), do not + ** invoke the callback function. + */ + if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ + sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); + } + +insert_cleanup: + sqlite3SrcListDelete(db, pTabList); + sqlite3ExprListDelete(db, pList); + sqlite3SelectDelete(db, pSelect); + sqlite3IdListDelete(db, pColumn); + sqlite3DbFree(db, aRegIdx); +} + +/* Make sure "isView" and other macros defined above are undefined. Otherwise +** thely may interfere with compilation of other functions in this file +** (or in another file, if this file becomes part of the amalgamation). */ +#ifdef isView + #undef isView +#endif +#ifdef pTrigger + #undef pTrigger +#endif +#ifdef tmask + #undef tmask +#endif + + +/* +** Generate code to do constraint checks prior to an INSERT or an UPDATE. +** +** The input is a range of consecutive registers as follows: +** +** 1. The rowid of the row after the update. +** +** 2. The data in the first column of the entry after the update. +** +** i. Data from middle columns... +** +** N. The data in the last column of the entry after the update. +** +** The regRowid parameter is the index of the register containing (1). +** +** If isUpdate is true and rowidChng is non-zero, then rowidChng contains +** the address of a register containing the rowid before the update takes +** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate +** is false, indicating an INSERT statement, then a non-zero rowidChng +** indicates that the rowid was explicitly specified as part of the +** INSERT statement. If rowidChng is false, it means that the rowid is +** computed automatically in an insert or that the rowid value is not +** modified by an update. +** +** The code generated by this routine store new index entries into +** registers identified by aRegIdx[]. No index entry is created for +** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is +** the same as the order of indices on the linked list of indices +** attached to the table. +** +** This routine also generates code to check constraints. NOT NULL, +** CHECK, and UNIQUE constraints are all checked. If a constraint fails, +** then the appropriate action is performed. There are five possible +** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. +** +** Constraint type Action What Happens +** --------------- ---------- ---------------------------------------- +** any ROLLBACK The current transaction is rolled back and +** sqlite3_exec() returns immediately with a +** return code of SQLITE_CONSTRAINT. +** +** any ABORT Back out changes from the current command +** only (do not do a complete rollback) then +** cause sqlite3_exec() to return immediately +** with SQLITE_CONSTRAINT. +** +** any FAIL Sqlite3_exec() returns immediately with a +** return code of SQLITE_CONSTRAINT. The +** transaction is not rolled back and any +** prior changes are retained. +** +** any IGNORE The record number and data is popped from +** the stack and there is an immediate jump +** to label ignoreDest. +** +** NOT NULL REPLACE The NULL value is replace by the default +** value for that column. If the default value +** is NULL, the action is the same as ABORT. +** +** UNIQUE REPLACE The other row that conflicts with the row +** being inserted is removed. +** +** CHECK REPLACE Illegal. The results in an exception. +** +** Which action to take is determined by the overrideError parameter. +** Or if overrideError==OE_Default, then the pParse->onError parameter +** is used. Or if pParse->onError==OE_Default then the onError value +** for the constraint is used. +** +** The calling routine must open a read/write cursor for pTab with +** cursor number "baseCur". All indices of pTab must also have open +** read/write cursors with cursor number baseCur+i for the i-th cursor. +** Except, if there is no possibility of a REPLACE action then +** cursors do not need to be open for indices where aRegIdx[i]==0. +*/ +void sqlite3GenerateConstraintChecks( + Parse *pParse, /* The parser context */ + Table *pTab, /* the table into which we are inserting */ + int baseCur, /* Index of a read/write cursor pointing at pTab */ + int regRowid, /* Index of the range of input registers */ + int *aRegIdx, /* Register used by each index. 0 for unused indices */ + int rowidChng, /* True if the rowid might collide with existing entry */ + int isUpdate, /* True for UPDATE, False for INSERT */ + int overrideError, /* Override onError to this if not OE_Default */ + int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ + int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */ +){ + int i; /* loop counter */ + Vdbe *v; /* VDBE under constrution */ + int nCol; /* Number of columns */ + int onError; /* Conflict resolution strategy */ + int j1; /* Addresss of jump instruction */ + int j2 = 0, j3; /* Addresses of jump instructions */ + int regData; /* Register containing first data column */ + int iCur; /* Table cursor number */ + Index *pIdx; /* Pointer to one of the indices */ + sqlite3 *db; /* Database connection */ + int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ + int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid; + + db = pParse->db; + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); + assert( pTab->pSelect==0 ); /* This table is not a VIEW */ + nCol = pTab->nCol; + regData = regRowid + 1; + + /* Test all NOT NULL constraints. + */ + for(i=0; iiPKey ){ + continue; + } + onError = pTab->aCol[i].notNull; + if( onError==OE_None ) continue; + if( overrideError!=OE_Default ){ + onError = overrideError; + }else if( onError==OE_Default ){ + onError = OE_Abort; + } + if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ + onError = OE_Abort; + } + assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail + || onError==OE_Ignore || onError==OE_Replace ); + switch( onError ){ + case OE_Abort: + sqlite3MayAbort(pParse); + case OE_Rollback: + case OE_Fail: { + char *zMsg; + sqlite3VdbeAddOp3(v, OP_HaltIfNull, + SQLITE_CONSTRAINT_NOTNULL, onError, regData+i); + zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL", + pTab->zName, pTab->aCol[i].zName); + sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); + break; + } + case OE_Ignore: { + sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest); + break; + } + default: { + assert( onError==OE_Replace ); + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); + sqlite3VdbeJumpHere(v, j1); + break; + } + } + } + + /* Test all CHECK constraints + */ +#ifndef SQLITE_OMIT_CHECK + if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ + ExprList *pCheck = pTab->pCheck; + pParse->ckBase = regData; + onError = overrideError!=OE_Default ? overrideError : OE_Abort; + for(i=0; inExpr; i++){ + int allOk = sqlite3VdbeMakeLabel(v); + sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL); + if( onError==OE_Ignore ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + }else{ + char *zConsName = pCheck->a[i].zName; + if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ + if( zConsName ){ + zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName); + }else{ + zConsName = 0; + } + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, + onError, zConsName, P4_DYNAMIC); + } + sqlite3VdbeResolveLabel(v, allOk); + } + } +#endif /* !defined(SQLITE_OMIT_CHECK) */ + + /* If we have an INTEGER PRIMARY KEY, make sure the primary key + ** of the new record does not previously exist. Except, if this + ** is an UPDATE and the primary key is not changing, that is OK. + */ + if( rowidChng ){ + onError = pTab->keyConf; + if( overrideError!=OE_Default ){ + onError = overrideError; + }else if( onError==OE_Default ){ + onError = OE_Abort; + } + + if( isUpdate ){ + j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng); + } + j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); + switch( onError ){ + default: { + onError = OE_Abort; + /* Fall thru into the next case */ + } + case OE_Rollback: + case OE_Abort: + case OE_Fail: { + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY, + onError, "PRIMARY KEY must be unique", P4_STATIC); + break; + } + case OE_Replace: { + /* If there are DELETE triggers on this table and the + ** recursive-triggers flag is set, call GenerateRowDelete() to + ** remove the conflicting row from the table. This will fire + ** the triggers and remove both the table and index b-tree entries. + ** + ** Otherwise, if there are no triggers or the recursive-triggers + ** flag is not set, but the table has one or more indexes, call + ** GenerateRowIndexDelete(). This removes the index b-tree entries + ** only. The table b-tree entry will be replaced by the new entry + ** when it is inserted. + ** + ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, + ** also invoke MultiWrite() to indicate that this VDBE may require + ** statement rollback (if the statement is aborted after the delete + ** takes place). Earlier versions called sqlite3MultiWrite() regardless, + ** but being more selective here allows statements like: + ** + ** REPLACE INTO t(rowid) VALUES($newrowid) + ** + ** to run without a statement journal if there are no indexes on the + ** table. + */ + Trigger *pTrigger = 0; + if( db->flags&SQLITE_RecTriggers ){ + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); + } + if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ + sqlite3MultiWrite(pParse); + sqlite3GenerateRowDelete( + pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace + ); + }else if( pTab->pIndex ){ + sqlite3MultiWrite(pParse); + sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); + } + seenReplace = 1; + break; + } + case OE_Ignore: { + assert( seenReplace==0 ); + sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + break; + } + } + sqlite3VdbeJumpHere(v, j3); + if( isUpdate ){ + sqlite3VdbeJumpHere(v, j2); + } + } + + /* Test all UNIQUE constraints by creating entries for each UNIQUE + ** index and making sure that duplicate entries do not already exist. + ** Add the new records to the indices as we go. + */ + for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ + int regIdx; + int regR; + int addrSkipRow = 0; + + if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ + + if( pIdx->pPartIdxWhere ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]); + addrSkipRow = sqlite3VdbeMakeLabel(v); + pParse->ckBase = regData; + sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow, + SQLITE_JUMPIFNULL); + pParse->ckBase = 0; + } + + /* Create a key for accessing the index entry */ + regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); + for(i=0; inColumn; i++){ + int idx = pIdx->aiColumn[i]; + if( idx==pTab->iPKey ){ + sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); + }else{ + sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); + } + } + sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); + sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT); + sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1); + + /* Find out what action to take in case there is an indexing conflict */ + onError = pIdx->onError; + if( onError==OE_None ){ + sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); + sqlite3VdbeResolveLabel(v, addrSkipRow); + continue; /* pIdx is not a UNIQUE index */ + } + if( overrideError!=OE_Default ){ + onError = overrideError; + }else if( onError==OE_Default ){ + onError = OE_Abort; + } + if( seenReplace ){ + if( onError==OE_Ignore ) onError = OE_Replace; + else if( onError==OE_Fail ) onError = OE_Abort; + } + + /* Check to see if the new index entry will be unique */ + regR = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR); + j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, + regR, SQLITE_INT_TO_PTR(regIdx), + P4_INT32); + sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); + + /* Generate code that executes if the new index entry is not unique */ + assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail + || onError==OE_Ignore || onError==OE_Replace ); + switch( onError ){ + case OE_Rollback: + case OE_Abort: + case OE_Fail: { + int j; + StrAccum errMsg; + const char *zSep; + char *zErr; + + sqlite3StrAccumInit(&errMsg, 0, 0, 200); + errMsg.db = db; + zSep = pIdx->nColumn>1 ? "columns " : "column "; + for(j=0; jnColumn; j++){ + char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName; + sqlite3StrAccumAppend(&errMsg, zSep, -1); + zSep = ", "; + sqlite3StrAccumAppend(&errMsg, zCol, -1); + } + sqlite3StrAccumAppend(&errMsg, + pIdx->nColumn>1 ? " are not unique" : " is not unique", -1); + zErr = sqlite3StrAccumFinish(&errMsg); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE, + onError, zErr, 0); + sqlite3DbFree(errMsg.db, zErr); + break; + } + case OE_Ignore: { + assert( seenReplace==0 ); + sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + break; + } + default: { + Trigger *pTrigger = 0; + assert( onError==OE_Replace ); + sqlite3MultiWrite(pParse); + if( db->flags&SQLITE_RecTriggers ){ + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); + } + sqlite3GenerateRowDelete( + pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace + ); + seenReplace = 1; + break; + } + } + sqlite3VdbeJumpHere(v, j3); + sqlite3VdbeResolveLabel(v, addrSkipRow); + sqlite3ReleaseTempReg(pParse, regR); + } + + if( pbMayReplace ){ + *pbMayReplace = seenReplace; + } +} + +/* +** This routine generates code to finish the INSERT or UPDATE operation +** that was started by a prior call to sqlite3GenerateConstraintChecks. +** A consecutive range of registers starting at regRowid contains the +** rowid and the content to be inserted. +** +** The arguments to this routine should be the same as the first six +** arguments to sqlite3GenerateConstraintChecks. +*/ +void sqlite3CompleteInsertion( + Parse *pParse, /* The parser context */ + Table *pTab, /* the table into which we are inserting */ + int baseCur, /* Index of a read/write cursor pointing at pTab */ + int regRowid, /* Range of content */ + int *aRegIdx, /* Register used by each index. 0 for unused indices */ + int isUpdate, /* True for UPDATE, False for INSERT */ + int appendBias, /* True if this is likely to be an append */ + int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ +){ + int i; + Vdbe *v; + Index *pIdx; + u8 pik_flags; + int regData; + int regRec; + + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); + assert( pTab->pSelect==0 ); /* This table is not a VIEW */ + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + if( aRegIdx[i]==0 ) continue; + if( pIdx->pPartIdxWhere ){ + sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); + } + sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); + if( useSeekResult ){ + sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + } + } + regData = regRowid + 1; + regRec = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); + sqlite3TableAffinityStr(v, pTab); + sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); + if( pParse->nested ){ + pik_flags = 0; + }else{ + pik_flags = OPFLAG_NCHANGE; + pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); + } + if( appendBias ){ + pik_flags |= OPFLAG_APPEND; + } + if( useSeekResult ){ + pik_flags |= OPFLAG_USESEEKRESULT; + } + sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); + if( !pParse->nested ){ + sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT); + } + sqlite3VdbeChangeP5(v, pik_flags); +} + +/* +** Generate code that will open cursors for a table and for all +** indices of that table. The "baseCur" parameter is the cursor number used +** for the table. Indices are opened on subsequent cursors. +** +** Return the number of indices on the table. +*/ +int sqlite3OpenTableAndIndices( + Parse *pParse, /* Parsing context */ + Table *pTab, /* Table to be opened */ + int baseCur, /* Cursor number assigned to the table */ + int op /* OP_OpenRead or OP_OpenWrite */ +){ + int i; + int iDb; + Index *pIdx; + Vdbe *v; + + if( IsVirtual(pTab) ) return 0; + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); + sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); + for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + assert( pIdx->pSchema==pTab->pSchema ); + sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, + (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIdx->zName)); + } + if( pParse->nTabnTab = baseCur+i; + } + return i-1; +} + + +#ifdef SQLITE_TEST +/* +** The following global variable is incremented whenever the +** transfer optimization is used. This is used for testing +** purposes only - to make sure the transfer optimization really +** is happening when it is suppose to. +*/ +int sqlite3_xferopt_count; +#endif /* SQLITE_TEST */ + + +#ifndef SQLITE_OMIT_XFER_OPT +/* +** Check to collation names to see if they are compatible. +*/ +static int xferCompatibleCollation(const char *z1, const char *z2){ + if( z1==0 ){ + return z2==0; + } + if( z2==0 ){ + return 0; + } + return sqlite3StrICmp(z1, z2)==0; +} + + +/* +** Check to see if index pSrc is compatible as a source of data +** for index pDest in an insert transfer optimization. The rules +** for a compatible index: +** +** * The index is over the same set of columns +** * The same DESC and ASC markings occurs on all columns +** * The same onError processing (OE_Abort, OE_Ignore, etc) +** * The same collating sequence on each column +** * The index has the exact same WHERE clause +*/ +static int xferCompatibleIndex(Index *pDest, Index *pSrc){ + int i; + assert( pDest && pSrc ); + assert( pDest->pTable!=pSrc->pTable ); + if( pDest->nColumn!=pSrc->nColumn ){ + return 0; /* Different number of columns */ + } + if( pDest->onError!=pSrc->onError ){ + return 0; /* Different conflict resolution strategies */ + } + for(i=0; inColumn; i++){ + if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ + return 0; /* Different columns indexed */ + } + if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ + return 0; /* Different sort orders */ + } + if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){ + return 0; /* Different collating sequences */ + } + } + if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ + return 0; /* Different WHERE clauses */ + } + + /* If no test above fails then the indices must be compatible */ + return 1; +} + +/* +** Attempt the transfer optimization on INSERTs of the form +** +** INSERT INTO tab1 SELECT * FROM tab2; +** +** The xfer optimization transfers raw records from tab2 over to tab1. +** Columns are not decoded and reassemblied, which greatly improves +** performance. Raw index records are transferred in the same way. +** +** The xfer optimization is only attempted if tab1 and tab2 are compatible. +** There are lots of rules for determining compatibility - see comments +** embedded in the code for details. +** +** This routine returns TRUE if the optimization is guaranteed to be used. +** Sometimes the xfer optimization will only work if the destination table +** is empty - a factor that can only be determined at run-time. In that +** case, this routine generates code for the xfer optimization but also +** does a test to see if the destination table is empty and jumps over the +** xfer optimization code if the test fails. In that case, this routine +** returns FALSE so that the caller will know to go ahead and generate +** an unoptimized transfer. This routine also returns FALSE if there +** is no chance that the xfer optimization can be applied. +** +** This optimization is particularly useful at making VACUUM run faster. +*/ +static int xferOptimization( + Parse *pParse, /* Parser context */ + Table *pDest, /* The table we are inserting into */ + Select *pSelect, /* A SELECT statement to use as the data source */ + int onError, /* How to handle constraint errors */ + int iDbDest /* The database of pDest */ +){ + ExprList *pEList; /* The result set of the SELECT */ + Table *pSrc; /* The table in the FROM clause of SELECT */ + Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ + struct SrcList_item *pItem; /* An element of pSelect->pSrc */ + int i; /* Loop counter */ + int iDbSrc; /* The database of pSrc */ + int iSrc, iDest; /* Cursors from source and destination */ + int addr1, addr2; /* Loop addresses */ + int emptyDestTest; /* Address of test for empty pDest */ + int emptySrcTest; /* Address of test for empty pSrc */ + Vdbe *v; /* The VDBE we are building */ + KeyInfo *pKey; /* Key information for an index */ + int regAutoinc; /* Memory register used by AUTOINC */ + int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ + int regData, regRowid; /* Registers holding data and rowid */ + + if( pSelect==0 ){ + return 0; /* Must be of the form INSERT INTO ... SELECT ... */ + } + if( sqlite3TriggerList(pParse, pDest) ){ + return 0; /* tab1 must not have triggers */ + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pDest->tabFlags & TF_Virtual ){ + return 0; /* tab1 must not be a virtual table */ + } +#endif + if( onError==OE_Default ){ + if( pDest->iPKey>=0 ) onError = pDest->keyConf; + if( onError==OE_Default ) onError = OE_Abort; + } + assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ + if( pSelect->pSrc->nSrc!=1 ){ + return 0; /* FROM clause must have exactly one term */ + } + if( pSelect->pSrc->a[0].pSelect ){ + return 0; /* FROM clause cannot contain a subquery */ + } + if( pSelect->pWhere ){ + return 0; /* SELECT may not have a WHERE clause */ + } + if( pSelect->pOrderBy ){ + return 0; /* SELECT may not have an ORDER BY clause */ + } + /* Do not need to test for a HAVING clause. If HAVING is present but + ** there is no ORDER BY, we will get an error. */ + if( pSelect->pGroupBy ){ + return 0; /* SELECT may not have a GROUP BY clause */ + } + if( pSelect->pLimit ){ + return 0; /* SELECT may not have a LIMIT clause */ + } + assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ + if( pSelect->pPrior ){ + return 0; /* SELECT may not be a compound query */ + } + if( pSelect->selFlags & SF_Distinct ){ + return 0; /* SELECT may not be DISTINCT */ + } + pEList = pSelect->pEList; + assert( pEList!=0 ); + if( pEList->nExpr!=1 ){ + return 0; /* The result set must have exactly one column */ + } + assert( pEList->a[0].pExpr ); + if( pEList->a[0].pExpr->op!=TK_ALL ){ + return 0; /* The result set must be the special operator "*" */ + } + + /* At this point we have established that the statement is of the + ** correct syntactic form to participate in this optimization. Now + ** we have to check the semantics. + */ + pItem = pSelect->pSrc->a; + pSrc = sqlite3LocateTableItem(pParse, 0, pItem); + if( pSrc==0 ){ + return 0; /* FROM clause does not contain a real table */ + } + if( pSrc==pDest ){ + return 0; /* tab1 and tab2 may not be the same table */ + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pSrc->tabFlags & TF_Virtual ){ + return 0; /* tab2 must not be a virtual table */ + } +#endif + if( pSrc->pSelect ){ + return 0; /* tab2 may not be a view */ + } + if( pDest->nCol!=pSrc->nCol ){ + return 0; /* Number of columns must be the same in tab1 and tab2 */ + } + if( pDest->iPKey!=pSrc->iPKey ){ + return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ + } + for(i=0; inCol; i++){ + if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){ + return 0; /* Affinity must be the same on all columns */ + } + if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){ + return 0; /* Collating sequence must be the same on all columns */ + } + if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){ + return 0; /* tab2 must be NOT NULL if tab1 is */ + } + } + for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ + if( pDestIdx->onError!=OE_None ){ + destHasUniqueIdx = 1; + } + for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ + if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; + } + if( pSrcIdx==0 ){ + return 0; /* pDestIdx has no corresponding index in pSrc */ + } + } +#ifndef SQLITE_OMIT_CHECK + if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ + return 0; /* Tables have different CHECK constraints. Ticket #2252 */ + } +#endif +#ifndef SQLITE_OMIT_FOREIGN_KEY + /* Disallow the transfer optimization if the destination table constains + ** any foreign key constraints. This is more restrictive than necessary. + ** But the main beneficiary of the transfer optimization is the VACUUM + ** command, and the VACUUM command disables foreign key constraints. So + ** the extra complication to make this rule less restrictive is probably + ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] + */ + if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ + return 0; + } +#endif + if( (pParse->db->flags & SQLITE_CountRows)!=0 ){ + return 0; /* xfer opt does not play well with PRAGMA count_changes */ + } + + /* If we get this far, it means that the xfer optimization is at + ** least a possibility, though it might only work if the destination + ** table (tab1) is initially empty. + */ +#ifdef SQLITE_TEST + sqlite3_xferopt_count++; +#endif + iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); + v = sqlite3GetVdbe(pParse); + sqlite3CodeVerifySchema(pParse, iDbSrc); + iSrc = pParse->nTab++; + iDest = pParse->nTab++; + regAutoinc = autoIncBegin(pParse, iDbDest, pDest); + sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); + if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ + || destHasUniqueIdx /* (2) */ + || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ + ){ + /* In some circumstances, we are able to run the xfer optimization + ** only if the destination table is initially empty. This code makes + ** that determination. Conditions under which the destination must + ** be empty: + ** + ** (1) There is no INTEGER PRIMARY KEY but there are indices. + ** (If the destination is not initially empty, the rowid fields + ** of index entries might need to change.) + ** + ** (2) The destination has a unique index. (The xfer optimization + ** is unable to test uniqueness.) + ** + ** (3) onError is something other than OE_Abort and OE_Rollback. + */ + addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); + emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); + sqlite3VdbeJumpHere(v, addr1); + }else{ + emptyDestTest = 0; + } + sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); + emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); + regData = sqlite3GetTempReg(pParse); + regRowid = sqlite3GetTempReg(pParse); + if( pDest->iPKey>=0 ){ + addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); + addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); + sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY, + onError, "PRIMARY KEY must be unique", P4_STATIC); + sqlite3VdbeJumpHere(v, addr2); + autoIncStep(pParse, regAutoinc, regRowid); + }else if( pDest->pIndex==0 ){ + addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); + }else{ + addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); + assert( (pDest->tabFlags & TF_Autoincrement)==0 ); + } + sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); + sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); + sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); + sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); + sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); + for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ + for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ + if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; + } + assert( pSrcIdx ); + sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); + sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, + (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pSrcIdx->zName)); + pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); + sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, + (char*)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); + VdbeComment((v, "%s", pDestIdx->zName)); + addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); + sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); + sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); + sqlite3VdbeJumpHere(v, addr1); + } + sqlite3VdbeJumpHere(v, emptySrcTest); + sqlite3ReleaseTempReg(pParse, regRowid); + sqlite3ReleaseTempReg(pParse, regData); + sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + if( emptyDestTest ){ + sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); + sqlite3VdbeJumpHere(v, emptyDestTest); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + return 0; + }else{ + return 1; + } +} +#endif /* SQLITE_OMIT_XFER_OPT */ diff --git a/components/external/SQLite-3.8.1/src/journal.c b/components/external/SQLite-3.8.1/src/journal.c new file mode 100644 index 0000000000000000000000000000000000000000..fed27be3e38055d2204395cde6ffc94589fbf5e8 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/journal.c @@ -0,0 +1,256 @@ +/* +** 2007 August 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements a special kind of sqlite3_file object used +** by SQLite to create journal files if the atomic-write optimization +** is enabled. +** +** The distinctive characteristic of this sqlite3_file is that the +** actual on disk file is created lazily. When the file is created, +** the caller specifies a buffer size for an in-memory buffer to +** be used to service read() and write() requests. The actual file +** on disk is not created or populated until either: +** +** 1) The in-memory representation grows too large for the allocated +** buffer, or +** 2) The sqlite3JournalCreate() function is called. +*/ +#ifdef SQLITE_ENABLE_ATOMIC_WRITE +#include "sqliteInt.h" + + +/* +** A JournalFile object is a subclass of sqlite3_file used by +** as an open file handle for journal files. +*/ +struct JournalFile { + sqlite3_io_methods *pMethod; /* I/O methods on journal files */ + int nBuf; /* Size of zBuf[] in bytes */ + char *zBuf; /* Space to buffer journal writes */ + int iSize; /* Amount of zBuf[] currently used */ + int flags; /* xOpen flags */ + sqlite3_vfs *pVfs; /* The "real" underlying VFS */ + sqlite3_file *pReal; /* The "real" underlying file descriptor */ + const char *zJournal; /* Name of the journal file */ +}; +typedef struct JournalFile JournalFile; + +/* +** If it does not already exists, create and populate the on-disk file +** for JournalFile p. +*/ +static int createFile(JournalFile *p){ + int rc = SQLITE_OK; + if( !p->pReal ){ + sqlite3_file *pReal = (sqlite3_file *)&p[1]; + rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0); + if( rc==SQLITE_OK ){ + p->pReal = pReal; + if( p->iSize>0 ){ + assert(p->iSize<=p->nBuf); + rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0); + } + if( rc!=SQLITE_OK ){ + /* If an error occurred while writing to the file, close it before + ** returning. This way, SQLite uses the in-memory journal data to + ** roll back changes made to the internal page-cache before this + ** function was called. */ + sqlite3OsClose(pReal); + p->pReal = 0; + } + } + } + return rc; +} + +/* +** Close the file. +*/ +static int jrnlClose(sqlite3_file *pJfd){ + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + sqlite3OsClose(p->pReal); + } + sqlite3_free(p->zBuf); + return SQLITE_OK; +} + +/* +** Read data from the file. +*/ +static int jrnlRead( + sqlite3_file *pJfd, /* The journal file from which to read */ + void *zBuf, /* Put the results here */ + int iAmt, /* Number of bytes to read */ + sqlite_int64 iOfst /* Begin reading at this offset */ +){ + int rc = SQLITE_OK; + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst); + }else if( (iAmt+iOfst)>p->iSize ){ + rc = SQLITE_IOERR_SHORT_READ; + }else{ + memcpy(zBuf, &p->zBuf[iOfst], iAmt); + } + return rc; +} + +/* +** Write data to the file. +*/ +static int jrnlWrite( + sqlite3_file *pJfd, /* The journal file into which to write */ + const void *zBuf, /* Take data to be written from here */ + int iAmt, /* Number of bytes to write */ + sqlite_int64 iOfst /* Begin writing at this offset into the file */ +){ + int rc = SQLITE_OK; + JournalFile *p = (JournalFile *)pJfd; + if( !p->pReal && (iOfst+iAmt)>p->nBuf ){ + rc = createFile(p); + } + if( rc==SQLITE_OK ){ + if( p->pReal ){ + rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst); + }else{ + memcpy(&p->zBuf[iOfst], zBuf, iAmt); + if( p->iSize<(iOfst+iAmt) ){ + p->iSize = (iOfst+iAmt); + } + } + } + return rc; +} + +/* +** Truncate the file. +*/ +static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){ + int rc = SQLITE_OK; + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + rc = sqlite3OsTruncate(p->pReal, size); + }else if( sizeiSize ){ + p->iSize = size; + } + return rc; +} + +/* +** Sync the file. +*/ +static int jrnlSync(sqlite3_file *pJfd, int flags){ + int rc; + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + rc = sqlite3OsSync(p->pReal, flags); + }else{ + rc = SQLITE_OK; + } + return rc; +} + +/* +** Query the size of the file in bytes. +*/ +static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){ + int rc = SQLITE_OK; + JournalFile *p = (JournalFile *)pJfd; + if( p->pReal ){ + rc = sqlite3OsFileSize(p->pReal, pSize); + }else{ + *pSize = (sqlite_int64) p->iSize; + } + return rc; +} + +/* +** Table of methods for JournalFile sqlite3_file object. +*/ +static struct sqlite3_io_methods JournalFileMethods = { + 1, /* iVersion */ + jrnlClose, /* xClose */ + jrnlRead, /* xRead */ + jrnlWrite, /* xWrite */ + jrnlTruncate, /* xTruncate */ + jrnlSync, /* xSync */ + jrnlFileSize, /* xFileSize */ + 0, /* xLock */ + 0, /* xUnlock */ + 0, /* xCheckReservedLock */ + 0, /* xFileControl */ + 0, /* xSectorSize */ + 0, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0 /* xShmUnmap */ +}; + +/* +** Open a journal file. +*/ +int sqlite3JournalOpen( + sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */ + const char *zName, /* Name of the journal file */ + sqlite3_file *pJfd, /* Preallocated, blank file handle */ + int flags, /* Opening flags */ + int nBuf /* Bytes buffered before opening the file */ +){ + JournalFile *p = (JournalFile *)pJfd; + memset(p, 0, sqlite3JournalSize(pVfs)); + if( nBuf>0 ){ + p->zBuf = sqlite3MallocZero(nBuf); + if( !p->zBuf ){ + return SQLITE_NOMEM; + } + }else{ + return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0); + } + p->pMethod = &JournalFileMethods; + p->nBuf = nBuf; + p->flags = flags; + p->zJournal = zName; + p->pVfs = pVfs; + return SQLITE_OK; +} + +/* +** If the argument p points to a JournalFile structure, and the underlying +** file has not yet been created, create it now. +*/ +int sqlite3JournalCreate(sqlite3_file *p){ + if( p->pMethods!=&JournalFileMethods ){ + return SQLITE_OK; + } + return createFile((JournalFile *)p); +} + +/* +** The file-handle passed as the only argument is guaranteed to be an open +** file. It may or may not be of class JournalFile. If the file is a +** JournalFile, and the underlying file on disk has not yet been opened, +** return 0. Otherwise, return 1. +*/ +int sqlite3JournalExists(sqlite3_file *p){ + return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0); +} + +/* +** Return the number of bytes required to store a JournalFile that uses vfs +** pVfs to create the underlying on-disk files. +*/ +int sqlite3JournalSize(sqlite3_vfs *pVfs){ + return (pVfs->szOsFile+sizeof(JournalFile)); +} +#endif diff --git a/components/external/SQLite-3.8.1/src/legacy.c b/components/external/SQLite-3.8.1/src/legacy.c new file mode 100644 index 0000000000000000000000000000000000000000..94649ae705ab9385108d0d887af0759289fb23cb --- /dev/null +++ b/components/external/SQLite-3.8.1/src/legacy.c @@ -0,0 +1,141 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Main file for the SQLite library. The routines in this file +** implement the programmer interface to the library. Routines in +** other files are for internal use by SQLite and should not be +** accessed by users of the library. +*/ + +#include "sqliteInt.h" + +/* +** Execute SQL code. Return one of the SQLITE_ success/failure +** codes. Also write an error message into memory obtained from +** malloc() and make *pzErrMsg point to that message. +** +** If the SQL is a query, then for each row in the query result +** the xCallback() function is called. pArg becomes the first +** argument to xCallback(). If xCallback=NULL then no callback +** is invoked, even for queries. +*/ +int sqlite3_exec( + sqlite3 *db, /* The database on which the SQL executes */ + const char *zSql, /* The SQL to be executed */ + sqlite3_callback xCallback, /* Invoke this callback routine */ + void *pArg, /* First argument to xCallback() */ + char **pzErrMsg /* Write error messages here */ +){ + int rc = SQLITE_OK; /* Return code */ + const char *zLeftover; /* Tail of unprocessed SQL */ + sqlite3_stmt *pStmt = 0; /* The current SQL statement */ + char **azCols = 0; /* Names of result columns */ + int callbackIsInit; /* True if callback data is initialized */ + + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( zSql==0 ) zSql = ""; + + sqlite3_mutex_enter(db->mutex); + sqlite3Error(db, SQLITE_OK, 0); + while( rc==SQLITE_OK && zSql[0] ){ + int nCol; + char **azVals = 0; + + pStmt = 0; + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); + assert( rc==SQLITE_OK || pStmt==0 ); + if( rc!=SQLITE_OK ){ + continue; + } + if( !pStmt ){ + /* this happens for a comment or white-space */ + zSql = zLeftover; + continue; + } + + callbackIsInit = 0; + nCol = sqlite3_column_count(pStmt); + + while( 1 ){ + int i; + rc = sqlite3_step(pStmt); + + /* Invoke the callback function if required */ + if( xCallback && (SQLITE_ROW==rc || + (SQLITE_DONE==rc && !callbackIsInit + && db->flags&SQLITE_NullCallback)) ){ + if( !callbackIsInit ){ + azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); + if( azCols==0 ){ + goto exec_out; + } + for(i=0; imallocFailed = 1; + goto exec_out; + } + } + } + if( xCallback(pArg, nCol, azVals, azCols) ){ + rc = SQLITE_ABORT; + sqlite3VdbeFinalize((Vdbe *)pStmt); + pStmt = 0; + sqlite3Error(db, SQLITE_ABORT, 0); + goto exec_out; + } + } + + if( rc!=SQLITE_ROW ){ + rc = sqlite3VdbeFinalize((Vdbe *)pStmt); + pStmt = 0; + zSql = zLeftover; + while( sqlite3Isspace(zSql[0]) ) zSql++; + break; + } + } + + sqlite3DbFree(db, azCols); + azCols = 0; + } + +exec_out: + if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt); + sqlite3DbFree(db, azCols); + + rc = sqlite3ApiExit(db, rc); + if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){ + int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db)); + *pzErrMsg = sqlite3Malloc(nErrMsg); + if( *pzErrMsg ){ + memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg); + }else{ + rc = SQLITE_NOMEM; + sqlite3Error(db, SQLITE_NOMEM, 0); + } + }else if( pzErrMsg ){ + *pzErrMsg = 0; + } + + assert( (rc&db->errMask)==rc ); + sqlite3_mutex_leave(db->mutex); + return rc; +} diff --git a/components/external/SQLite-3.8.1/src/lempar.c b/components/external/SQLite-3.8.1/src/lempar.c new file mode 100644 index 0000000000000000000000000000000000000000..2afaa6cea6d829602c2786c1f8a37f567cf6fd53 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/lempar.c @@ -0,0 +1,864 @@ +/* Driver template for the LEMON parser generator. +** The author disclaims copyright to this source code. +** +** This version of "lempar.c" is modified, slightly, for use by SQLite. +** The only modifications are the addition of a couple of NEVER() +** macros to disable tests that are needed in the case of a general +** LALR(1) grammar but which are always false in the +** specific grammar used by SQLite. +*/ +/* First off, code is included that follows the "include" declaration +** in the input grammar file. */ +#include +%% +/* Next is all token values, in a form suitable for use by makeheaders. +** This section will be null unless lemon is run with the -m switch. +*/ +/* +** These constants (all generated automatically by the parser generator) +** specify the various kinds of tokens (terminals) that the parser +** understands. +** +** Each symbol here is a terminal symbol in the grammar. +*/ +%% +/* Make sure the INTERFACE macro is defined. +*/ +#ifndef INTERFACE +# define INTERFACE 1 +#endif +/* The next thing included is series of defines which control +** various aspects of the generated parser. +** YYCODETYPE is the data type used for storing terminal +** and nonterminal numbers. "unsigned char" is +** used if there are fewer than 250 terminals +** and nonterminals. "int" is used otherwise. +** YYNOCODE is a number of type YYCODETYPE which corresponds +** to no legal terminal or nonterminal number. This +** number is used to fill in empty slots of the hash +** table. +** YYFALLBACK If defined, this indicates that one or more tokens +** have fall-back values which should be used if the +** original value of the token will not parse. +** YYACTIONTYPE is the data type used for storing terminal +** and nonterminal numbers. "unsigned char" is +** used if there are fewer than 250 rules and +** states combined. "int" is used otherwise. +** ParseTOKENTYPE is the data type used for minor tokens given +** directly to the parser from the tokenizer. +** YYMINORTYPE is the data type used for all minor tokens. +** This is typically a union of many types, one of +** which is ParseTOKENTYPE. The entry in the union +** for base tokens is called "yy0". +** YYSTACKDEPTH is the maximum depth of the parser's stack. If +** zero the stack is dynamically sized using realloc() +** ParseARG_SDECL A static variable declaration for the %extra_argument +** ParseARG_PDECL A parameter declaration for the %extra_argument +** ParseARG_STORE Code to store %extra_argument into yypParser +** ParseARG_FETCH Code to extract %extra_argument from yypParser +** YYNSTATE the combined number of states. +** YYNRULE the number of rules in the grammar +** YYERRORSYMBOL is the code number of the error symbol. If not +** defined, then do no error processing. +*/ +%% +#define YY_NO_ACTION (YYNSTATE+YYNRULE+2) +#define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) +#define YY_ERROR_ACTION (YYNSTATE+YYNRULE) + +/* The yyzerominor constant is used to initialize instances of +** YYMINORTYPE objects to zero. */ +static const YYMINORTYPE yyzerominor = { 0 }; + +/* Define the yytestcase() macro to be a no-op if is not already defined +** otherwise. +** +** Applications can choose to define yytestcase() in the %include section +** to a macro that can assist in verifying code coverage. For production +** code the yytestcase() macro should be turned off. But it is useful +** for testing. +*/ +#ifndef yytestcase +# define yytestcase(X) +#endif + + +/* Next are the tables used to determine what action to take based on the +** current state and lookahead token. These tables are used to implement +** functions that take a state number and lookahead value and return an +** action integer. +** +** Suppose the action integer is N. Then the action is determined as +** follows +** +** 0 <= N < YYNSTATE Shift N. That is, push the lookahead +** token onto the stack and goto state N. +** +** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. +** +** N == YYNSTATE+YYNRULE A syntax error has occurred. +** +** N == YYNSTATE+YYNRULE+1 The parser accepts its input. +** +** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused +** slots in the yy_action[] table. +** +** The action table is constructed as a single large table named yy_action[]. +** Given state S and lookahead X, the action is computed as +** +** yy_action[ yy_shift_ofst[S] + X ] +** +** If the index value yy_shift_ofst[S]+X is out of range or if the value +** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] +** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table +** and that yy_default[S] should be used instead. +** +** The formula above is for computing the action when the lookahead is +** a terminal symbol. If the lookahead is a non-terminal (as occurs after +** a reduce action) then the yy_reduce_ofst[] array is used in place of +** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of +** YY_SHIFT_USE_DFLT. +** +** The following are the tables generated in this section: +** +** yy_action[] A single table containing all actions. +** yy_lookahead[] A table containing the lookahead for each entry in +** yy_action. Used to detect hash collisions. +** yy_shift_ofst[] For each state, the offset into yy_action for +** shifting terminals. +** yy_reduce_ofst[] For each state, the offset into yy_action for +** shifting non-terminals after a reduce. +** yy_default[] Default action for each state. +*/ +%% + +/* The next table maps tokens into fallback tokens. If a construct +** like the following: +** +** %fallback ID X Y Z. +** +** appears in the grammar, then ID becomes a fallback token for X, Y, +** and Z. Whenever one of the tokens X, Y, or Z is input to the parser +** but it does not parse, the type of the token is changed to ID and +** the parse is retried before an error is thrown. +*/ +#ifdef YYFALLBACK +static const YYCODETYPE yyFallback[] = { +%% +}; +#endif /* YYFALLBACK */ + +/* The following structure represents a single element of the +** parser's stack. Information stored includes: +** +** + The state number for the parser at this level of the stack. +** +** + The value of the token stored at this level of the stack. +** (In other words, the "major" token.) +** +** + The semantic value stored at this level of the stack. This is +** the information used by the action routines in the grammar. +** It is sometimes called the "minor" token. +*/ +struct yyStackEntry { + YYACTIONTYPE stateno; /* The state-number */ + YYCODETYPE major; /* The major token value. This is the code + ** number for the token at this stack level */ + YYMINORTYPE minor; /* The user-supplied minor token value. This + ** is the value of the token */ +}; +typedef struct yyStackEntry yyStackEntry; + +/* The state of the parser is completely contained in an instance of +** the following structure */ +struct yyParser { + int yyidx; /* Index of top element in stack */ +#ifdef YYTRACKMAXSTACKDEPTH + int yyidxMax; /* Maximum value of yyidx */ +#endif + int yyerrcnt; /* Shifts left before out of the error */ + ParseARG_SDECL /* A place to hold %extra_argument */ +#if YYSTACKDEPTH<=0 + int yystksz; /* Current side of the stack */ + yyStackEntry *yystack; /* The parser's stack */ +#else + yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ +#endif +}; +typedef struct yyParser yyParser; + +#ifndef NDEBUG +#include +static FILE *yyTraceFILE = 0; +static char *yyTracePrompt = 0; +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* +** Turn parser tracing on by giving a stream to which to write the trace +** and a prompt to preface each trace message. Tracing is turned off +** by making either argument NULL +** +** Inputs: +**
    +**
  • A FILE* to which trace output should be written. +** If NULL, then tracing is turned off. +**
  • A prefix string written at the beginning of every +** line of trace output. If NULL, then tracing is +** turned off. +**
+** +** Outputs: +** None. +*/ +void ParseTrace(FILE *TraceFILE, char *zTracePrompt){ + yyTraceFILE = TraceFILE; + yyTracePrompt = zTracePrompt; + if( yyTraceFILE==0 ) yyTracePrompt = 0; + else if( yyTracePrompt==0 ) yyTraceFILE = 0; +} +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* For tracing shifts, the names of all terminals and nonterminals +** are required. The following table supplies these names */ +static const char *const yyTokenName[] = { +%% +}; +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* For tracing reduce actions, the names of all rules are required. +*/ +static const char *const yyRuleName[] = { +%% +}; +#endif /* NDEBUG */ + + +#if YYSTACKDEPTH<=0 +/* +** Try to increase the size of the parser stack. +*/ +static void yyGrowStack(yyParser *p){ + int newSize; + yyStackEntry *pNew; + + newSize = p->yystksz*2 + 100; + pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); + if( pNew ){ + p->yystack = pNew; + p->yystksz = newSize; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sStack grows to %d entries!\n", + yyTracePrompt, p->yystksz); + } +#endif + } +} +#endif + +/* +** This function allocates a new parser. +** The only argument is a pointer to a function which works like +** malloc. +** +** Inputs: +** A pointer to the function used to allocate memory. +** +** Outputs: +** A pointer to a parser. This pointer is used in subsequent calls +** to Parse and ParseFree. +*/ +void *ParseAlloc(void *(*mallocProc)(size_t)){ + yyParser *pParser; + pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); + if( pParser ){ + pParser->yyidx = -1; +#ifdef YYTRACKMAXSTACKDEPTH + pParser->yyidxMax = 0; +#endif +#if YYSTACKDEPTH<=0 + pParser->yystack = NULL; + pParser->yystksz = 0; + yyGrowStack(pParser); +#endif + } + return pParser; +} + +/* The following function deletes the value associated with a +** symbol. The symbol can be either a terminal or nonterminal. +** "yymajor" is the symbol code, and "yypminor" is a pointer to +** the value. +*/ +static void yy_destructor( + yyParser *yypParser, /* The parser */ + YYCODETYPE yymajor, /* Type code for object to destroy */ + YYMINORTYPE *yypminor /* The object to be destroyed */ +){ + ParseARG_FETCH; + switch( yymajor ){ + /* Here is inserted the actions which take place when a + ** terminal or non-terminal is destroyed. This can happen + ** when the symbol is popped from the stack during a + ** reduce or during error processing or when a parser is + ** being destroyed before it is finished parsing. + ** + ** Note: during a reduce, the only symbols destroyed are those + ** which appear on the RHS of the rule, but which are not used + ** inside the C code. + */ +%% + default: break; /* If no destructor action specified: do nothing */ + } +} + +/* +** Pop the parser's stack once. +** +** If there is a destructor routine associated with the token which +** is popped from the stack, then call it. +** +** Return the major token number for the symbol popped. +*/ +static int yy_pop_parser_stack(yyParser *pParser){ + YYCODETYPE yymajor; + yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; + + /* There is no mechanism by which the parser stack can be popped below + ** empty in SQLite. */ + if( NEVER(pParser->yyidx<0) ) return 0; +#ifndef NDEBUG + if( yyTraceFILE && pParser->yyidx>=0 ){ + fprintf(yyTraceFILE,"%sPopping %s\n", + yyTracePrompt, + yyTokenName[yytos->major]); + } +#endif + yymajor = yytos->major; + yy_destructor(pParser, yymajor, &yytos->minor); + pParser->yyidx--; + return yymajor; +} + +/* +** Deallocate and destroy a parser. Destructors are all called for +** all stack elements before shutting the parser down. +** +** Inputs: +**
    +**
  • A pointer to the parser. This should be a pointer +** obtained from ParseAlloc. +**
  • A pointer to a function used to reclaim memory obtained +** from malloc. +**
+*/ +void ParseFree( + void *p, /* The parser to be deleted */ + void (*freeProc)(void*) /* Function used to reclaim memory */ +){ + yyParser *pParser = (yyParser*)p; + /* In SQLite, we never try to destroy a parser that was not successfully + ** created in the first place. */ + if( NEVER(pParser==0) ) return; + while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); +#if YYSTACKDEPTH<=0 + free(pParser->yystack); +#endif + (*freeProc)((void*)pParser); +} + +/* +** Return the peak depth of the stack for a parser. +*/ +#ifdef YYTRACKMAXSTACKDEPTH +int ParseStackPeak(void *p){ + yyParser *pParser = (yyParser*)p; + return pParser->yyidxMax; +} +#endif + +/* +** Find the appropriate action for a parser given the terminal +** look-ahead token iLookAhead. +** +** If the look-ahead token is YYNOCODE, then check to see if the action is +** independent of the look-ahead. If it is, return the action, otherwise +** return YY_NO_ACTION. +*/ +static int yy_find_shift_action( + yyParser *pParser, /* The parser */ + YYCODETYPE iLookAhead /* The look-ahead token */ +){ + int i; + int stateno = pParser->yystack[pParser->yyidx].stateno; + + if( stateno>YY_SHIFT_COUNT + || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){ + return yy_default[stateno]; + } + assert( iLookAhead!=YYNOCODE ); + i += iLookAhead; + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ + if( iLookAhead>0 ){ +#ifdef YYFALLBACK + YYCODETYPE iFallback; /* Fallback token */ + if( iLookAhead %s\n", + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); + } +#endif + return yy_find_shift_action(pParser, iFallback); + } +#endif +#ifdef YYWILDCARD + { + int j = i - iLookAhead + YYWILDCARD; + if( +#if YY_SHIFT_MIN+YYWILDCARD<0 + j>=0 && +#endif +#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT + j %s\n", + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); + } +#endif /* NDEBUG */ + return yy_action[j]; + } + } +#endif /* YYWILDCARD */ + } + return yy_default[stateno]; + }else{ + return yy_action[i]; + } +} + +/* +** Find the appropriate action for a parser given the non-terminal +** look-ahead token iLookAhead. +** +** If the look-ahead token is YYNOCODE, then check to see if the action is +** independent of the look-ahead. If it is, return the action, otherwise +** return YY_NO_ACTION. +*/ +static int yy_find_reduce_action( + int stateno, /* Current state number */ + YYCODETYPE iLookAhead /* The look-ahead token */ +){ + int i; +#ifdef YYERRORSYMBOL + if( stateno>YY_REDUCE_COUNT ){ + return yy_default[stateno]; + } +#else + assert( stateno<=YY_REDUCE_COUNT ); +#endif + i = yy_reduce_ofst[stateno]; + assert( i!=YY_REDUCE_USE_DFLT ); + assert( iLookAhead!=YYNOCODE ); + i += iLookAhead; +#ifdef YYERRORSYMBOL + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ + return yy_default[stateno]; + } +#else + assert( i>=0 && iyyidx--; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); + } +#endif + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will execute if the parser + ** stack every overflows */ +%% + ParseARG_STORE; /* Suppress warning about unused %extra_argument var */ +} + +/* +** Perform a shift action. +*/ +static void yy_shift( + yyParser *yypParser, /* The parser to be shifted */ + int yyNewState, /* The new state to shift in */ + int yyMajor, /* The major token to shift in */ + YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */ +){ + yyStackEntry *yytos; + yypParser->yyidx++; +#ifdef YYTRACKMAXSTACKDEPTH + if( yypParser->yyidx>yypParser->yyidxMax ){ + yypParser->yyidxMax = yypParser->yyidx; + } +#endif +#if YYSTACKDEPTH>0 + if( yypParser->yyidx>=YYSTACKDEPTH ){ + yyStackOverflow(yypParser, yypMinor); + return; + } +#else + if( yypParser->yyidx>=yypParser->yystksz ){ + yyGrowStack(yypParser); + if( yypParser->yyidx>=yypParser->yystksz ){ + yyStackOverflow(yypParser, yypMinor); + return; + } + } +#endif + yytos = &yypParser->yystack[yypParser->yyidx]; + yytos->stateno = (YYACTIONTYPE)yyNewState; + yytos->major = (YYCODETYPE)yyMajor; + yytos->minor = *yypMinor; +#ifndef NDEBUG + if( yyTraceFILE && yypParser->yyidx>0 ){ + int i; + fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); + fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); + for(i=1; i<=yypParser->yyidx; i++) + fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); + fprintf(yyTraceFILE,"\n"); + } +#endif +} + +/* The following table contains information about every rule that +** is used during the reduce. +*/ +static const struct { + YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ + unsigned char nrhs; /* Number of right-hand side symbols in the rule */ +} yyRuleInfo[] = { +%% +}; + +static void yy_accept(yyParser*); /* Forward Declaration */ + +/* +** Perform a reduce action and the shift that must immediately +** follow the reduce. +*/ +static void yy_reduce( + yyParser *yypParser, /* The parser */ + int yyruleno /* Number of the rule by which to reduce */ +){ + int yygoto; /* The next state */ + int yyact; /* The next action */ + YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ + yyStackEntry *yymsp; /* The top of the parser's stack */ + int yysize; /* Amount to pop the stack */ + ParseARG_FETCH; + yymsp = &yypParser->yystack[yypParser->yyidx]; +#ifndef NDEBUG + if( yyTraceFILE && yyruleno>=0 + && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ + fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, + yyRuleName[yyruleno]); + } +#endif /* NDEBUG */ + + /* Silence complaints from purify about yygotominor being uninitialized + ** in some cases when it is copied into the stack after the following + ** switch. yygotominor is uninitialized when a rule reduces that does + ** not set the value of its left-hand side nonterminal. Leaving the + ** value of the nonterminal uninitialized is utterly harmless as long + ** as the value is never used. So really the only thing this code + ** accomplishes is to quieten purify. + ** + ** 2007-01-16: The wireshark project (www.wireshark.org) reports that + ** without this code, their parser segfaults. I'm not sure what there + ** parser is doing to make this happen. This is the second bug report + ** from wireshark this week. Clearly they are stressing Lemon in ways + ** that it has not been previously stressed... (SQLite ticket #2172) + */ + /*memset(&yygotominor, 0, sizeof(yygotominor));*/ + yygotominor = yyzerominor; + + + switch( yyruleno ){ + /* Beginning here are the reduction cases. A typical example + ** follows: + ** case 0: + ** #line + ** { ... } // User supplied code + ** #line + ** break; + */ +%% + }; + assert( yyruleno>=0 && yyrulenoyyidx -= yysize; + yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); + if( yyact < YYNSTATE ){ +#ifdef NDEBUG + /* If we are not debugging and the reduce action popped at least + ** one element off the stack, then we can push the new element back + ** onto the stack here, and skip the stack overflow test in yy_shift(). + ** That gives a significant speed improvement. */ + if( yysize ){ + yypParser->yyidx++; + yymsp -= yysize-1; + yymsp->stateno = (YYACTIONTYPE)yyact; + yymsp->major = (YYCODETYPE)yygoto; + yymsp->minor = yygotominor; + }else +#endif + { + yy_shift(yypParser,yyact,yygoto,&yygotominor); + } + }else{ + assert( yyact == YYNSTATE + YYNRULE + 1 ); + yy_accept(yypParser); + } +} + +/* +** The following code executes when the parse fails +*/ +#ifndef YYNOERRORRECOVERY +static void yy_parse_failed( + yyParser *yypParser /* The parser */ +){ + ParseARG_FETCH; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); + } +#endif + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will be executed whenever the + ** parser fails */ +%% + ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ +} +#endif /* YYNOERRORRECOVERY */ + +/* +** The following code executes when a syntax error first occurs. +*/ +static void yy_syntax_error( + yyParser *yypParser, /* The parser */ + int yymajor, /* The major type of the error token */ + YYMINORTYPE yyminor /* The minor type of the error token */ +){ + ParseARG_FETCH; +#define TOKEN (yyminor.yy0) +%% + ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ +} + +/* +** The following is executed when the parser accepts +*/ +static void yy_accept( + yyParser *yypParser /* The parser */ +){ + ParseARG_FETCH; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); + } +#endif + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will be executed whenever the + ** parser accepts */ +%% + ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ +} + +/* The main parser program. +** The first argument is a pointer to a structure obtained from +** "ParseAlloc" which describes the current state of the parser. +** The second argument is the major token number. The third is +** the minor token. The fourth optional argument is whatever the +** user wants (and specified in the grammar) and is available for +** use by the action routines. +** +** Inputs: +**
    +**
  • A pointer to the parser (an opaque structure.) +**
  • The major token number. +**
  • The minor token number. +**
  • An option argument of a grammar-specified type. +**
+** +** Outputs: +** None. +*/ +void Parse( + void *yyp, /* The parser */ + int yymajor, /* The major token code number */ + ParseTOKENTYPE yyminor /* The value for the token */ + ParseARG_PDECL /* Optional %extra_argument parameter */ +){ + YYMINORTYPE yyminorunion; + int yyact; /* The parser action. */ +#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) + int yyendofinput; /* True if we are at the end of input */ +#endif +#ifdef YYERRORSYMBOL + int yyerrorhit = 0; /* True if yymajor has invoked an error */ +#endif + yyParser *yypParser; /* The parser */ + + /* (re)initialize the parser, if necessary */ + yypParser = (yyParser*)yyp; + if( yypParser->yyidx<0 ){ +#if YYSTACKDEPTH<=0 + if( yypParser->yystksz <=0 ){ + /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/ + yyminorunion = yyzerominor; + yyStackOverflow(yypParser, &yyminorunion); + return; + } +#endif + yypParser->yyidx = 0; + yypParser->yyerrcnt = -1; + yypParser->yystack[0].stateno = 0; + yypParser->yystack[0].major = 0; + } + yyminorunion.yy0 = yyminor; +#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) + yyendofinput = (yymajor==0); +#endif + ParseARG_STORE; + +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); + } +#endif + + do{ + yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); + if( yyactyyerrcnt--; + yymajor = YYNOCODE; + }else if( yyact < YYNSTATE + YYNRULE ){ + yy_reduce(yypParser,yyact-YYNSTATE); + }else{ + assert( yyact == YY_ERROR_ACTION ); +#ifdef YYERRORSYMBOL + int yymx; +#endif +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); + } +#endif +#ifdef YYERRORSYMBOL + /* A syntax error has occurred. + ** The response to an error depends upon whether or not the + ** grammar defines an error token "ERROR". + ** + ** This is what we do if the grammar does define ERROR: + ** + ** * Call the %syntax_error function. + ** + ** * Begin popping the stack until we enter a state where + ** it is legal to shift the error symbol, then shift + ** the error symbol. + ** + ** * Set the error count to three. + ** + ** * Begin accepting and shifting new tokens. No new error + ** processing will occur until three tokens have been + ** shifted successfully. + ** + */ + if( yypParser->yyerrcnt<0 ){ + yy_syntax_error(yypParser,yymajor,yyminorunion); + } + yymx = yypParser->yystack[yypParser->yyidx].major; + if( yymx==YYERRORSYMBOL || yyerrorhit ){ +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sDiscard input token %s\n", + yyTracePrompt,yyTokenName[yymajor]); + } +#endif + yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion); + yymajor = YYNOCODE; + }else{ + while( + yypParser->yyidx >= 0 && + yymx != YYERRORSYMBOL && + (yyact = yy_find_reduce_action( + yypParser->yystack[yypParser->yyidx].stateno, + YYERRORSYMBOL)) >= YYNSTATE + ){ + yy_pop_parser_stack(yypParser); + } + if( yypParser->yyidx < 0 || yymajor==0 ){ + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); + yy_parse_failed(yypParser); + yymajor = YYNOCODE; + }else if( yymx!=YYERRORSYMBOL ){ + YYMINORTYPE u2; + u2.YYERRSYMDT = 0; + yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); + } + } + yypParser->yyerrcnt = 3; + yyerrorhit = 1; +#elif defined(YYNOERRORRECOVERY) + /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to + ** do any kind of error recovery. Instead, simply invoke the syntax + ** error routine and continue going as if nothing had happened. + ** + ** Applications can set this macro (for example inside %include) if + ** they intend to abandon the parse upon the first syntax error seen. + */ + yy_syntax_error(yypParser,yymajor,yyminorunion); + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); + yymajor = YYNOCODE; + +#else /* YYERRORSYMBOL is not defined */ + /* This is what we do if the grammar does not define ERROR: + ** + ** * Report an error message, and throw away the input token. + ** + ** * If the input token is $, then fail the parse. + ** + ** As before, subsequent error messages are suppressed until + ** three input tokens have been successfully shifted. + */ + if( yypParser->yyerrcnt<=0 ){ + yy_syntax_error(yypParser,yymajor,yyminorunion); + } + yypParser->yyerrcnt = 3; + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); + if( yyendofinput ){ + yy_parse_failed(yypParser); + } + yymajor = YYNOCODE; +#endif + } + }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); + return; +} diff --git a/components/external/SQLite-3.8.1/src/loadext.c b/components/external/SQLite-3.8.1/src/loadext.c new file mode 100644 index 0000000000000000000000000000000000000000..828e865b61e49f6ec3eac1b458cad280a8461345 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/loadext.c @@ -0,0 +1,758 @@ +/* +** 2006 June 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to dynamically load extensions into +** the SQLite library. +*/ + +#ifndef SQLITE_CORE + #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ +#endif +#include "sqlite3ext.h" +#include "sqliteInt.h" +#include + +#ifndef SQLITE_OMIT_LOAD_EXTENSION + +/* +** Some API routines are omitted when various features are +** excluded from a build of SQLite. Substitute a NULL pointer +** for any missing APIs. +*/ +#ifndef SQLITE_ENABLE_COLUMN_METADATA +# define sqlite3_column_database_name 0 +# define sqlite3_column_database_name16 0 +# define sqlite3_column_table_name 0 +# define sqlite3_column_table_name16 0 +# define sqlite3_column_origin_name 0 +# define sqlite3_column_origin_name16 0 +# define sqlite3_table_column_metadata 0 +#endif + +#ifdef SQLITE_OMIT_AUTHORIZATION +# define sqlite3_set_authorizer 0 +#endif + +#ifdef SQLITE_OMIT_UTF16 +# define sqlite3_bind_text16 0 +# define sqlite3_collation_needed16 0 +# define sqlite3_column_decltype16 0 +# define sqlite3_column_name16 0 +# define sqlite3_column_text16 0 +# define sqlite3_complete16 0 +# define sqlite3_create_collation16 0 +# define sqlite3_create_function16 0 +# define sqlite3_errmsg16 0 +# define sqlite3_open16 0 +# define sqlite3_prepare16 0 +# define sqlite3_prepare16_v2 0 +# define sqlite3_result_error16 0 +# define sqlite3_result_text16 0 +# define sqlite3_result_text16be 0 +# define sqlite3_result_text16le 0 +# define sqlite3_value_text16 0 +# define sqlite3_value_text16be 0 +# define sqlite3_value_text16le 0 +# define sqlite3_column_database_name16 0 +# define sqlite3_column_table_name16 0 +# define sqlite3_column_origin_name16 0 +#endif + +#ifdef SQLITE_OMIT_COMPLETE +# define sqlite3_complete 0 +# define sqlite3_complete16 0 +#endif + +#ifdef SQLITE_OMIT_DECLTYPE +# define sqlite3_column_decltype16 0 +# define sqlite3_column_decltype 0 +#endif + +#ifdef SQLITE_OMIT_PROGRESS_CALLBACK +# define sqlite3_progress_handler 0 +#endif + +#ifdef SQLITE_OMIT_VIRTUALTABLE +# define sqlite3_create_module 0 +# define sqlite3_create_module_v2 0 +# define sqlite3_declare_vtab 0 +# define sqlite3_vtab_config 0 +# define sqlite3_vtab_on_conflict 0 +#endif + +#ifdef SQLITE_OMIT_SHARED_CACHE +# define sqlite3_enable_shared_cache 0 +#endif + +#ifdef SQLITE_OMIT_TRACE +# define sqlite3_profile 0 +# define sqlite3_trace 0 +#endif + +#ifdef SQLITE_OMIT_GET_TABLE +# define sqlite3_free_table 0 +# define sqlite3_get_table 0 +#endif + +#ifdef SQLITE_OMIT_INCRBLOB +#define sqlite3_bind_zeroblob 0 +#define sqlite3_blob_bytes 0 +#define sqlite3_blob_close 0 +#define sqlite3_blob_open 0 +#define sqlite3_blob_read 0 +#define sqlite3_blob_write 0 +#define sqlite3_blob_reopen 0 +#endif + +/* +** The following structure contains pointers to all SQLite API routines. +** A pointer to this structure is passed into extensions when they are +** loaded so that the extension can make calls back into the SQLite +** library. +** +** When adding new APIs, add them to the bottom of this structure +** in order to preserve backwards compatibility. +** +** Extensions that use newer APIs should first call the +** sqlite3_libversion_number() to make sure that the API they +** intend to use is supported by the library. Extensions should +** also check to make sure that the pointer to the function is +** not NULL before calling it. +*/ +static const sqlite3_api_routines sqlite3Apis = { + sqlite3_aggregate_context, +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_aggregate_count, +#else + 0, +#endif + sqlite3_bind_blob, + sqlite3_bind_double, + sqlite3_bind_int, + sqlite3_bind_int64, + sqlite3_bind_null, + sqlite3_bind_parameter_count, + sqlite3_bind_parameter_index, + sqlite3_bind_parameter_name, + sqlite3_bind_text, + sqlite3_bind_text16, + sqlite3_bind_value, + sqlite3_busy_handler, + sqlite3_busy_timeout, + sqlite3_changes, + sqlite3_close, + sqlite3_collation_needed, + sqlite3_collation_needed16, + sqlite3_column_blob, + sqlite3_column_bytes, + sqlite3_column_bytes16, + sqlite3_column_count, + sqlite3_column_database_name, + sqlite3_column_database_name16, + sqlite3_column_decltype, + sqlite3_column_decltype16, + sqlite3_column_double, + sqlite3_column_int, + sqlite3_column_int64, + sqlite3_column_name, + sqlite3_column_name16, + sqlite3_column_origin_name, + sqlite3_column_origin_name16, + sqlite3_column_table_name, + sqlite3_column_table_name16, + sqlite3_column_text, + sqlite3_column_text16, + sqlite3_column_type, + sqlite3_column_value, + sqlite3_commit_hook, + sqlite3_complete, + sqlite3_complete16, + sqlite3_create_collation, + sqlite3_create_collation16, + sqlite3_create_function, + sqlite3_create_function16, + sqlite3_create_module, + sqlite3_data_count, + sqlite3_db_handle, + sqlite3_declare_vtab, + sqlite3_enable_shared_cache, + sqlite3_errcode, + sqlite3_errmsg, + sqlite3_errmsg16, + sqlite3_exec, +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_expired, +#else + 0, +#endif + sqlite3_finalize, + sqlite3_free, + sqlite3_free_table, + sqlite3_get_autocommit, + sqlite3_get_auxdata, + sqlite3_get_table, + 0, /* Was sqlite3_global_recover(), but that function is deprecated */ + sqlite3_interrupt, + sqlite3_last_insert_rowid, + sqlite3_libversion, + sqlite3_libversion_number, + sqlite3_malloc, + sqlite3_mprintf, + sqlite3_open, + sqlite3_open16, + sqlite3_prepare, + sqlite3_prepare16, + sqlite3_profile, + sqlite3_progress_handler, + sqlite3_realloc, + sqlite3_reset, + sqlite3_result_blob, + sqlite3_result_double, + sqlite3_result_error, + sqlite3_result_error16, + sqlite3_result_int, + sqlite3_result_int64, + sqlite3_result_null, + sqlite3_result_text, + sqlite3_result_text16, + sqlite3_result_text16be, + sqlite3_result_text16le, + sqlite3_result_value, + sqlite3_rollback_hook, + sqlite3_set_authorizer, + sqlite3_set_auxdata, + sqlite3_snprintf, + sqlite3_step, + sqlite3_table_column_metadata, +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_thread_cleanup, +#else + 0, +#endif + sqlite3_total_changes, + sqlite3_trace, +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_transfer_bindings, +#else + 0, +#endif + sqlite3_update_hook, + sqlite3_user_data, + sqlite3_value_blob, + sqlite3_value_bytes, + sqlite3_value_bytes16, + sqlite3_value_double, + sqlite3_value_int, + sqlite3_value_int64, + sqlite3_value_numeric_type, + sqlite3_value_text, + sqlite3_value_text16, + sqlite3_value_text16be, + sqlite3_value_text16le, + sqlite3_value_type, + sqlite3_vmprintf, + /* + ** The original API set ends here. All extensions can call any + ** of the APIs above provided that the pointer is not NULL. But + ** before calling APIs that follow, extension should check the + ** sqlite3_libversion_number() to make sure they are dealing with + ** a library that is new enough to support that API. + ************************************************************************* + */ + sqlite3_overload_function, + + /* + ** Added after 3.3.13 + */ + sqlite3_prepare_v2, + sqlite3_prepare16_v2, + sqlite3_clear_bindings, + + /* + ** Added for 3.4.1 + */ + sqlite3_create_module_v2, + + /* + ** Added for 3.5.0 + */ + sqlite3_bind_zeroblob, + sqlite3_blob_bytes, + sqlite3_blob_close, + sqlite3_blob_open, + sqlite3_blob_read, + sqlite3_blob_write, + sqlite3_create_collation_v2, + sqlite3_file_control, + sqlite3_memory_highwater, + sqlite3_memory_used, +#ifdef SQLITE_MUTEX_OMIT + 0, + 0, + 0, + 0, + 0, +#else + sqlite3_mutex_alloc, + sqlite3_mutex_enter, + sqlite3_mutex_free, + sqlite3_mutex_leave, + sqlite3_mutex_try, +#endif + sqlite3_open_v2, + sqlite3_release_memory, + sqlite3_result_error_nomem, + sqlite3_result_error_toobig, + sqlite3_sleep, + sqlite3_soft_heap_limit, + sqlite3_vfs_find, + sqlite3_vfs_register, + sqlite3_vfs_unregister, + + /* + ** Added for 3.5.8 + */ + sqlite3_threadsafe, + sqlite3_result_zeroblob, + sqlite3_result_error_code, + sqlite3_test_control, + sqlite3_randomness, + sqlite3_context_db_handle, + + /* + ** Added for 3.6.0 + */ + sqlite3_extended_result_codes, + sqlite3_limit, + sqlite3_next_stmt, + sqlite3_sql, + sqlite3_status, + + /* + ** Added for 3.7.4 + */ + sqlite3_backup_finish, + sqlite3_backup_init, + sqlite3_backup_pagecount, + sqlite3_backup_remaining, + sqlite3_backup_step, +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS + sqlite3_compileoption_get, + sqlite3_compileoption_used, +#else + 0, + 0, +#endif + sqlite3_create_function_v2, + sqlite3_db_config, + sqlite3_db_mutex, + sqlite3_db_status, + sqlite3_extended_errcode, + sqlite3_log, + sqlite3_soft_heap_limit64, + sqlite3_sourceid, + sqlite3_stmt_status, + sqlite3_strnicmp, +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + sqlite3_unlock_notify, +#else + 0, +#endif +#ifndef SQLITE_OMIT_WAL + sqlite3_wal_autocheckpoint, + sqlite3_wal_checkpoint, + sqlite3_wal_hook, +#else + 0, + 0, + 0, +#endif + sqlite3_blob_reopen, + sqlite3_vtab_config, + sqlite3_vtab_on_conflict, + sqlite3_close_v2, + sqlite3_db_filename, + sqlite3_db_readonly, + sqlite3_db_release_memory, + sqlite3_errstr, + sqlite3_stmt_busy, + sqlite3_stmt_readonly, + sqlite3_stricmp, + sqlite3_uri_boolean, + sqlite3_uri_int64, + sqlite3_uri_parameter, + sqlite3_vsnprintf, + sqlite3_wal_checkpoint_v2 +}; + +/* +** Attempt to load an SQLite extension library contained in the file +** zFile. The entry point is zProc. zProc may be 0 in which case a +** default entry point name (sqlite3_extension_init) is used. Use +** of the default name is recommended. +** +** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. +** +** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with +** error message text. The calling function should free this memory +** by calling sqlite3DbFree(db, ). +*/ +static int sqlite3LoadExtension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +){ + sqlite3_vfs *pVfs = db->pVfs; + void *handle; + int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*); + char *zErrmsg = 0; + const char *zEntry; + char *zAltEntry = 0; + void **aHandle; + int nMsg = 300 + sqlite3Strlen30(zFile); + int ii; + + /* Shared library endings to try if zFile cannot be loaded as written */ + static const char *azEndings[] = { +#if SQLITE_OS_WIN + "dll" +#elif defined(__APPLE__) + "dylib" +#else + "so" +#endif + }; + + + if( pzErrMsg ) *pzErrMsg = 0; + + /* Ticket #1863. To avoid a creating security problems for older + ** applications that relink against newer versions of SQLite, the + ** ability to run load_extension is turned off by default. One + ** must call sqlite3_enable_load_extension() to turn on extension + ** loading. Otherwise you get the following error. + */ + if( (db->flags & SQLITE_LoadExtension)==0 ){ + if( pzErrMsg ){ + *pzErrMsg = sqlite3_mprintf("not authorized"); + } + return SQLITE_ERROR; + } + + zEntry = zProc ? zProc : "sqlite3_extension_init"; + + handle = sqlite3OsDlOpen(pVfs, zFile); +#if SQLITE_OS_UNIX || SQLITE_OS_WIN + for(ii=0; ii sqlite3_example_init + ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init + */ + if( xInit==0 && zProc==0 ){ + int iFile, iEntry, c; + int ncFile = sqlite3Strlen30(zFile); + zAltEntry = sqlite3_malloc(ncFile+30); + if( zAltEntry==0 ){ + sqlite3OsDlClose(pVfs, handle); + return SQLITE_NOMEM; + } + memcpy(zAltEntry, "sqlite3_", 8); + for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){} + iFile++; + if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; + for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){ + if( sqlite3Isalpha(c) ){ + zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c]; + } + } + memcpy(zAltEntry+iEntry, "_init", 6); + zEntry = zAltEntry; + xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*)) + sqlite3OsDlSym(pVfs, handle, zEntry); + } + if( xInit==0 ){ + if( pzErrMsg ){ + nMsg += sqlite3Strlen30(zEntry); + *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); + if( zErrmsg ){ + sqlite3_snprintf(nMsg, zErrmsg, + "no entry point [%s] in shared library [%s]", zEntry, zFile); + sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); + } + } + sqlite3OsDlClose(pVfs, handle); + sqlite3_free(zAltEntry); + return SQLITE_ERROR; + } + sqlite3_free(zAltEntry); + if( xInit(db, &zErrmsg, &sqlite3Apis) ){ + if( pzErrMsg ){ + *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); + } + sqlite3_free(zErrmsg); + sqlite3OsDlClose(pVfs, handle); + return SQLITE_ERROR; + } + + /* Append the new shared library handle to the db->aExtension array. */ + aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1)); + if( aHandle==0 ){ + return SQLITE_NOMEM; + } + if( db->nExtension>0 ){ + memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension); + } + sqlite3DbFree(db, db->aExtension); + db->aExtension = aHandle; + + db->aExtension[db->nExtension++] = handle; + return SQLITE_OK; +} +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +){ + int rc; + sqlite3_mutex_enter(db->mutex); + rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Call this routine when the database connection is closing in order +** to clean up loaded extensions +*/ +void sqlite3CloseExtensions(sqlite3 *db){ + int i; + assert( sqlite3_mutex_held(db->mutex) ); + for(i=0; inExtension; i++){ + sqlite3OsDlClose(db->pVfs, db->aExtension[i]); + } + sqlite3DbFree(db, db->aExtension); +} + +/* +** Enable or disable extension loading. Extension loading is disabled by +** default so as not to open security holes in older applications. +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff){ + sqlite3_mutex_enter(db->mutex); + if( onoff ){ + db->flags |= SQLITE_LoadExtension; + }else{ + db->flags &= ~SQLITE_LoadExtension; + } + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + +/* +** The auto-extension code added regardless of whether or not extension +** loading is supported. We need a dummy sqlite3Apis pointer for that +** code if regular extension loading is not available. This is that +** dummy pointer. +*/ +#ifdef SQLITE_OMIT_LOAD_EXTENSION +static const sqlite3_api_routines sqlite3Apis = { 0 }; +#endif + + +/* +** The following object holds the list of automatically loaded +** extensions. +** +** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER +** mutex must be held while accessing this list. +*/ +typedef struct sqlite3AutoExtList sqlite3AutoExtList; +static SQLITE_WSD struct sqlite3AutoExtList { + int nExt; /* Number of entries in aExt[] */ + void (**aExt)(void); /* Pointers to the extension init functions */ +} sqlite3Autoext = { 0, 0 }; + +/* The "wsdAutoext" macro will resolve to the autoextension +** state vector. If writable static data is unsupported on the target, +** we have to locate the state vector at run-time. In the more common +** case where writable static data is supported, wsdStat can refer directly +** to the "sqlite3Autoext" state vector declared above. +*/ +#ifdef SQLITE_OMIT_WSD +# define wsdAutoextInit \ + sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) +# define wsdAutoext x[0] +#else +# define wsdAutoextInit +# define wsdAutoext sqlite3Autoext +#endif + + +/* +** Register a statically linked extension that is automatically +** loaded by every new database connection. +*/ +int sqlite3_auto_extension(void (*xInit)(void)){ + int rc = SQLITE_OK; +#ifndef SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if( rc ){ + return rc; + }else +#endif + { + int i; +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + wsdAutoextInit; + sqlite3_mutex_enter(mutex); + for(i=0; i=0; i--){ + if( wsdAutoext.aExt[i]==xInit ){ + wsdAutoext.nExt--; + wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt]; + n++; + break; + } + } + sqlite3_mutex_leave(mutex); + return n; +} + +/* +** Reset the automatic extension loading mechanism. +*/ +void sqlite3_reset_auto_extension(void){ +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize()==SQLITE_OK ) +#endif + { +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + wsdAutoextInit; + sqlite3_mutex_enter(mutex); + sqlite3_free(wsdAutoext.aExt); + wsdAutoext.aExt = 0; + wsdAutoext.nExt = 0; + sqlite3_mutex_leave(mutex); + } +} + +/* +** Load all automatic extensions. +** +** If anything goes wrong, set an error in the database connection. +*/ +void sqlite3AutoLoadExtensions(sqlite3 *db){ + int i; + int go = 1; + int rc; + int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*); + + wsdAutoextInit; + if( wsdAutoext.nExt==0 ){ + /* Common case: early out without every having to acquire a mutex */ + return; + } + for(i=0; go; i++){ + char *zErrmsg; +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter(mutex); + if( i>=wsdAutoext.nExt ){ + xInit = 0; + go = 0; + }else{ + xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*)) + wsdAutoext.aExt[i]; + } + sqlite3_mutex_leave(mutex); + zErrmsg = 0; + if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){ + sqlite3Error(db, rc, + "automatic extension loading failed: %s", zErrmsg); + go = 0; + } + sqlite3_free(zErrmsg); + } +} diff --git a/components/external/SQLite-3.8.1/src/main.c b/components/external/SQLite-3.8.1/src/main.c new file mode 100644 index 0000000000000000000000000000000000000000..407de0e4dafcae9b56f52049d5fa983f95773cc7 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/main.c @@ -0,0 +1,3349 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Main file for the SQLite library. The routines in this file +** implement the programmer interface to the library. Routines in +** other files are for internal use by SQLite and should not be +** accessed by users of the library. +*/ +#include "sqliteInt.h" + +#ifdef SQLITE_ENABLE_FTS3 +# include "fts3.h" +#endif +#ifdef SQLITE_ENABLE_RTREE +# include "rtree.h" +#endif +#ifdef SQLITE_ENABLE_ICU +# include "sqliteicu.h" +#endif + +#ifndef SQLITE_AMALGAMATION +/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant +** contains the text of SQLITE_VERSION macro. +*/ +const char sqlite3_version[] = SQLITE_VERSION; +#endif + +/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns +** a pointer to the to the sqlite3_version[] string constant. +*/ +const char *sqlite3_libversion(void){ return sqlite3_version; } + +/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a +** pointer to a string constant whose value is the same as the +** SQLITE_SOURCE_ID C preprocessor macro. +*/ +const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } + +/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function +** returns an integer equal to SQLITE_VERSION_NUMBER. +*/ +int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } + +/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns +** zero if and only if SQLite was compiled with mutexing code omitted due to +** the SQLITE_THREADSAFE compile-time option being set to 0. +*/ +int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } + +#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) +/* +** If the following function pointer is not NULL and if +** SQLITE_ENABLE_IOTRACE is enabled, then messages describing +** I/O active are written using this function. These messages +** are intended for debugging activity only. +*/ +void (*sqlite3IoTrace)(const char*, ...) = 0; +#endif + +/* +** If the following global variable points to a string which is the +** name of a directory, then that directory will be used to store +** temporary files. +** +** See also the "PRAGMA temp_store_directory" SQL command. +*/ +char *sqlite3_temp_directory = 0; + +/* +** If the following global variable points to a string which is the +** name of a directory, then that directory will be used to store +** all database files specified with a relative pathname. +** +** See also the "PRAGMA data_store_directory" SQL command. +*/ +char *sqlite3_data_directory = 0; + +/* +** Initialize SQLite. +** +** This routine must be called to initialize the memory allocation, +** VFS, and mutex subsystems prior to doing any serious work with +** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT +** this routine will be called automatically by key routines such as +** sqlite3_open(). +** +** This routine is a no-op except on its very first call for the process, +** or for the first call after a call to sqlite3_shutdown. +** +** The first thread to call this routine runs the initialization to +** completion. If subsequent threads call this routine before the first +** thread has finished the initialization process, then the subsequent +** threads must block until the first thread finishes with the initialization. +** +** The first thread might call this routine recursively. Recursive +** calls to this routine should not block, of course. Otherwise the +** initialization process would never complete. +** +** Let X be the first thread to enter this routine. Let Y be some other +** thread. Then while the initial invocation of this routine by X is +** incomplete, it is required that: +** +** * Calls to this routine from Y must block until the outer-most +** call by X completes. +** +** * Recursive calls to this routine from thread X return immediately +** without blocking. +*/ +int sqlite3_initialize(void){ + MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ + int rc; /* Result code */ +#ifdef SQLITE_EXTRA_INIT + int bRunExtraInit = 0; /* Extra initialization needed */ +#endif + +#ifdef SQLITE_OMIT_WSD + rc = sqlite3_wsd_init(4096, 24); + if( rc!=SQLITE_OK ){ + return rc; + } +#endif + + /* If SQLite is already completely initialized, then this call + ** to sqlite3_initialize() should be a no-op. But the initialization + ** must be complete. So isInit must not be set until the very end + ** of this routine. + */ + if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; + +#ifdef SQLITE_ENABLE_SQLLOG + { + extern void sqlite3_init_sqllog(void); + sqlite3_init_sqllog(); + } +#endif + + /* Make sure the mutex subsystem is initialized. If unable to + ** initialize the mutex subsystem, return early with the error. + ** If the system is so sick that we are unable to allocate a mutex, + ** there is not much SQLite is going to be able to do. + ** + ** The mutex subsystem must take care of serializing its own + ** initialization. + */ + rc = sqlite3MutexInit(); + if( rc ) return rc; + + /* Initialize the malloc() system and the recursive pInitMutex mutex. + ** This operation is protected by the STATIC_MASTER mutex. Note that + ** MutexAlloc() is called for a static mutex prior to initializing the + ** malloc subsystem - this implies that the allocation of a static + ** mutex must not require support from the malloc subsystem. + */ + MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + sqlite3_mutex_enter(pMaster); + sqlite3GlobalConfig.isMutexInit = 1; + if( !sqlite3GlobalConfig.isMallocInit ){ + rc = sqlite3MallocInit(); + } + if( rc==SQLITE_OK ){ + sqlite3GlobalConfig.isMallocInit = 1; + if( !sqlite3GlobalConfig.pInitMutex ){ + sqlite3GlobalConfig.pInitMutex = + sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); + if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ + rc = SQLITE_NOMEM; + } + } + } + if( rc==SQLITE_OK ){ + sqlite3GlobalConfig.nRefInitMutex++; + } + sqlite3_mutex_leave(pMaster); + + /* If rc is not SQLITE_OK at this point, then either the malloc + ** subsystem could not be initialized or the system failed to allocate + ** the pInitMutex mutex. Return an error in either case. */ + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Do the rest of the initialization under the recursive mutex so + ** that we will be able to handle recursive calls into + ** sqlite3_initialize(). The recursive calls normally come through + ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other + ** recursive calls might also be possible. + ** + ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls + ** to the xInit method, so the xInit method need not be threadsafe. + ** + ** The following mutex is what serializes access to the appdef pcache xInit + ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the + ** call to sqlite3PcacheInitialize(). + */ + sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); + if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + sqlite3GlobalConfig.inProgress = 1; + memset(pHash, 0, sizeof(sqlite3GlobalFunctions)); + sqlite3RegisterGlobalFunctions(); + if( sqlite3GlobalConfig.isPCacheInit==0 ){ + rc = sqlite3PcacheInitialize(); + } + if( rc==SQLITE_OK ){ + sqlite3GlobalConfig.isPCacheInit = 1; + rc = sqlite3OsInit(); + } + if( rc==SQLITE_OK ){ + sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, + sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); + sqlite3GlobalConfig.isInit = 1; +#ifdef SQLITE_EXTRA_INIT + bRunExtraInit = 1; +#endif + } + sqlite3GlobalConfig.inProgress = 0; + } + sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); + + /* Go back under the static mutex and clean up the recursive + ** mutex to prevent a resource leak. + */ + sqlite3_mutex_enter(pMaster); + sqlite3GlobalConfig.nRefInitMutex--; + if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ + assert( sqlite3GlobalConfig.nRefInitMutex==0 ); + sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); + sqlite3GlobalConfig.pInitMutex = 0; + } + sqlite3_mutex_leave(pMaster); + + /* The following is just a sanity check to make sure SQLite has + ** been compiled correctly. It is important to run this code, but + ** we don't want to run it too often and soak up CPU cycles for no + ** reason. So we run it once during initialization. + */ +#ifndef NDEBUG +#ifndef SQLITE_OMIT_FLOATING_POINT + /* This section of code's only "output" is via assert() statements. */ + if ( rc==SQLITE_OK ){ + u64 x = (((u64)1)<<63)-1; + double y; + assert(sizeof(x)==8); + assert(sizeof(x)==sizeof(y)); + memcpy(&y, &x, 8); + assert( sqlite3IsNaN(y) ); + } +#endif +#endif + + /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT + ** compile-time option. + */ +#ifdef SQLITE_EXTRA_INIT + if( bRunExtraInit ){ + int SQLITE_EXTRA_INIT(const char*); + rc = SQLITE_EXTRA_INIT(0); + } +#endif + + return rc; +} + +/* +** Undo the effects of sqlite3_initialize(). Must not be called while +** there are outstanding database connections or memory allocations or +** while any part of SQLite is otherwise in use in any thread. This +** routine is not threadsafe. But it is safe to invoke this routine +** on when SQLite is already shut down. If SQLite is already shut down +** when this routine is invoked, then this routine is a harmless no-op. +*/ +int sqlite3_shutdown(void){ + if( sqlite3GlobalConfig.isInit ){ +#ifdef SQLITE_EXTRA_SHUTDOWN + void SQLITE_EXTRA_SHUTDOWN(void); + SQLITE_EXTRA_SHUTDOWN(); +#endif + sqlite3_os_end(); + sqlite3_reset_auto_extension(); + sqlite3GlobalConfig.isInit = 0; + } + if( sqlite3GlobalConfig.isPCacheInit ){ + sqlite3PcacheShutdown(); + sqlite3GlobalConfig.isPCacheInit = 0; + } + if( sqlite3GlobalConfig.isMallocInit ){ + sqlite3MallocEnd(); + sqlite3GlobalConfig.isMallocInit = 0; + +#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES + /* The heap subsystem has now been shutdown and these values are supposed + ** to be NULL or point to memory that was obtained from sqlite3_malloc(), + ** which would rely on that heap subsystem; therefore, make sure these + ** values cannot refer to heap memory that was just invalidated when the + ** heap subsystem was shutdown. This is only done if the current call to + ** this function resulted in the heap subsystem actually being shutdown. + */ + sqlite3_data_directory = 0; + sqlite3_temp_directory = 0; +#endif + } + if( sqlite3GlobalConfig.isMutexInit ){ + sqlite3MutexEnd(); + sqlite3GlobalConfig.isMutexInit = 0; + } + + return SQLITE_OK; +} + +/* +** This API allows applications to modify the global configuration of +** the SQLite library at run-time. +** +** This routine should only be called when there are no outstanding +** database connections or memory allocations. This routine is not +** threadsafe. Failure to heed these warnings can lead to unpredictable +** behavior. +*/ +int sqlite3_config(int op, ...){ + va_list ap; + int rc = SQLITE_OK; + + /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while + ** the SQLite library is in use. */ + if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; + + va_start(ap, op); + switch( op ){ + + /* Mutex configuration options are only available in a threadsafe + ** compile. + */ +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 + case SQLITE_CONFIG_SINGLETHREAD: { + /* Disable all mutexing */ + sqlite3GlobalConfig.bCoreMutex = 0; + sqlite3GlobalConfig.bFullMutex = 0; + break; + } + case SQLITE_CONFIG_MULTITHREAD: { + /* Disable mutexing of database connections */ + /* Enable mutexing of core data structures */ + sqlite3GlobalConfig.bCoreMutex = 1; + sqlite3GlobalConfig.bFullMutex = 0; + break; + } + case SQLITE_CONFIG_SERIALIZED: { + /* Enable all mutexing */ + sqlite3GlobalConfig.bCoreMutex = 1; + sqlite3GlobalConfig.bFullMutex = 1; + break; + } + case SQLITE_CONFIG_MUTEX: { + /* Specify an alternative mutex implementation */ + sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); + break; + } + case SQLITE_CONFIG_GETMUTEX: { + /* Retrieve the current mutex implementation */ + *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; + break; + } +#endif + + + case SQLITE_CONFIG_MALLOC: { + /* Specify an alternative malloc implementation */ + sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); + break; + } + case SQLITE_CONFIG_GETMALLOC: { + /* Retrieve the current malloc() implementation */ + if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); + *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; + break; + } + case SQLITE_CONFIG_MEMSTATUS: { + /* Enable or disable the malloc status collection */ + sqlite3GlobalConfig.bMemstat = va_arg(ap, int); + break; + } + case SQLITE_CONFIG_SCRATCH: { + /* Designate a buffer for scratch memory space */ + sqlite3GlobalConfig.pScratch = va_arg(ap, void*); + sqlite3GlobalConfig.szScratch = va_arg(ap, int); + sqlite3GlobalConfig.nScratch = va_arg(ap, int); + break; + } + case SQLITE_CONFIG_PAGECACHE: { + /* Designate a buffer for page cache memory space */ + sqlite3GlobalConfig.pPage = va_arg(ap, void*); + sqlite3GlobalConfig.szPage = va_arg(ap, int); + sqlite3GlobalConfig.nPage = va_arg(ap, int); + break; + } + + case SQLITE_CONFIG_PCACHE: { + /* no-op */ + break; + } + case SQLITE_CONFIG_GETPCACHE: { + /* now an error */ + rc = SQLITE_ERROR; + break; + } + + case SQLITE_CONFIG_PCACHE2: { + /* Specify an alternative page cache implementation */ + sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); + break; + } + case SQLITE_CONFIG_GETPCACHE2: { + if( sqlite3GlobalConfig.pcache2.xInit==0 ){ + sqlite3PCacheSetDefault(); + } + *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; + break; + } + +#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) + case SQLITE_CONFIG_HEAP: { + /* Designate a buffer for heap memory space */ + sqlite3GlobalConfig.pHeap = va_arg(ap, void*); + sqlite3GlobalConfig.nHeap = va_arg(ap, int); + sqlite3GlobalConfig.mnReq = va_arg(ap, int); + + if( sqlite3GlobalConfig.mnReq<1 ){ + sqlite3GlobalConfig.mnReq = 1; + }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ + /* cap min request size at 2^12 */ + sqlite3GlobalConfig.mnReq = (1<<12); + } + + if( sqlite3GlobalConfig.pHeap==0 ){ + /* If the heap pointer is NULL, then restore the malloc implementation + ** back to NULL pointers too. This will cause the malloc to go + ** back to its default implementation when sqlite3_initialize() is + ** run. + */ + memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); + }else{ + /* The heap pointer is not NULL, then install one of the + ** mem5.c/mem3.c methods. The enclosing #if guarantees at + ** least one of these methods is currently enabled. + */ +#ifdef SQLITE_ENABLE_MEMSYS3 + sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); +#endif +#ifdef SQLITE_ENABLE_MEMSYS5 + sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); +#endif + } + break; + } +#endif + + case SQLITE_CONFIG_LOOKASIDE: { + sqlite3GlobalConfig.szLookaside = va_arg(ap, int); + sqlite3GlobalConfig.nLookaside = va_arg(ap, int); + break; + } + + /* Record a pointer to the logger function and its first argument. + ** The default is NULL. Logging is disabled if the function pointer is + ** NULL. + */ + case SQLITE_CONFIG_LOG: { + /* MSVC is picky about pulling func ptrs from va lists. + ** http://support.microsoft.com/kb/47961 + ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); + */ + typedef void(*LOGFUNC_t)(void*,int,const char*); + sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); + sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); + break; + } + + case SQLITE_CONFIG_URI: { + sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); + break; + } + + case SQLITE_CONFIG_COVERING_INDEX_SCAN: { + sqlite3GlobalConfig.bUseCis = va_arg(ap, int); + break; + } + +#ifdef SQLITE_ENABLE_SQLLOG + case SQLITE_CONFIG_SQLLOG: { + typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); + sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); + sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); + break; + } +#endif + + case SQLITE_CONFIG_MMAP_SIZE: { + sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); + sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); + if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){ + mxMmap = SQLITE_MAX_MMAP_SIZE; + } + sqlite3GlobalConfig.mxMmap = mxMmap; + if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; + if( szMmap>mxMmap) szMmap = mxMmap; + sqlite3GlobalConfig.szMmap = szMmap; + break; + } + + default: { + rc = SQLITE_ERROR; + break; + } + } + va_end(ap); + return rc; +} + +/* +** Set up the lookaside buffers for a database connection. +** Return SQLITE_OK on success. +** If lookaside is already active, return SQLITE_BUSY. +** +** The sz parameter is the number of bytes in each lookaside slot. +** The cnt parameter is the number of slots. If pStart is NULL the +** space for the lookaside memory is obtained from sqlite3_malloc(). +** If pStart is not NULL then it is sz*cnt bytes of memory to use for +** the lookaside memory. +*/ +static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ + void *pStart; + if( db->lookaside.nOut ){ + return SQLITE_BUSY; + } + /* Free any existing lookaside buffer for this handle before + ** allocating a new one so we don't have to have space for + ** both at the same time. + */ + if( db->lookaside.bMalloced ){ + sqlite3_free(db->lookaside.pStart); + } + /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger + ** than a pointer to be useful. + */ + sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ + if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; + if( cnt<0 ) cnt = 0; + if( sz==0 || cnt==0 ){ + sz = 0; + pStart = 0; + }else if( pBuf==0 ){ + sqlite3BeginBenignMalloc(); + pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ + sqlite3EndBenignMalloc(); + if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; + }else{ + pStart = pBuf; + } + db->lookaside.pStart = pStart; + db->lookaside.pFree = 0; + db->lookaside.sz = (u16)sz; + if( pStart ){ + int i; + LookasideSlot *p; + assert( sz > (int)sizeof(LookasideSlot*) ); + p = (LookasideSlot*)pStart; + for(i=cnt-1; i>=0; i--){ + p->pNext = db->lookaside.pFree; + db->lookaside.pFree = p; + p = (LookasideSlot*)&((u8*)p)[sz]; + } + db->lookaside.pEnd = p; + db->lookaside.bEnabled = 1; + db->lookaside.bMalloced = pBuf==0 ?1:0; + }else{ + db->lookaside.pEnd = 0; + db->lookaside.bEnabled = 0; + db->lookaside.bMalloced = 0; + } + return SQLITE_OK; +} + +/* +** Return the mutex associated with a database connection. +*/ +sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ + return db->mutex; +} + +/* +** Free up as much memory as we can from the given database +** connection. +*/ +int sqlite3_db_release_memory(sqlite3 *db){ + int i; + sqlite3_mutex_enter(db->mutex); + sqlite3BtreeEnterAll(db); + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + Pager *pPager = sqlite3BtreePager(pBt); + sqlite3PagerShrink(pPager); + } + } + sqlite3BtreeLeaveAll(db); + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +/* +** Configuration settings for an individual database connection +*/ +int sqlite3_db_config(sqlite3 *db, int op, ...){ + va_list ap; + int rc; + va_start(ap, op); + switch( op ){ + case SQLITE_DBCONFIG_LOOKASIDE: { + void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */ + int sz = va_arg(ap, int); /* IMP: R-47871-25994 */ + int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */ + rc = setupLookaside(db, pBuf, sz, cnt); + break; + } + default: { + static const struct { + int op; /* The opcode */ + u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ + } aFlagOp[] = { + { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, + { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, + }; + unsigned int i; + rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ + for(i=0; iflags; + if( onoff>0 ){ + db->flags |= aFlagOp[i].mask; + }else if( onoff==0 ){ + db->flags &= ~aFlagOp[i].mask; + } + if( oldFlags!=db->flags ){ + sqlite3ExpirePreparedStatements(db); + } + if( pRes ){ + *pRes = (db->flags & aFlagOp[i].mask)!=0; + } + rc = SQLITE_OK; + break; + } + } + break; + } + } + va_end(ap); + return rc; +} + + +/* +** Return true if the buffer z[0..n-1] contains all spaces. +*/ +static int allSpaces(const char *z, int n){ + while( n>0 && z[n-1]==' ' ){ n--; } + return n==0; +} + +/* +** This is the default collating function named "BINARY" which is always +** available. +** +** If the padFlag argument is not NULL then space padding at the end +** of strings is ignored. This implements the RTRIM collation. +*/ +static int binCollFunc( + void *padFlag, + int nKey1, const void *pKey1, + int nKey2, const void *pKey2 +){ + int rc, n; + n = nKey1lastRowid; +} + +/* +** Return the number of changes in the most recent call to sqlite3_exec(). +*/ +int sqlite3_changes(sqlite3 *db){ + return db->nChange; +} + +/* +** Return the number of changes since the database handle was opened. +*/ +int sqlite3_total_changes(sqlite3 *db){ + return db->nTotalChange; +} + +/* +** Close all open savepoints. This function only manipulates fields of the +** database handle object, it does not close any savepoints that may be open +** at the b-tree/pager level. +*/ +void sqlite3CloseSavepoints(sqlite3 *db){ + while( db->pSavepoint ){ + Savepoint *pTmp = db->pSavepoint; + db->pSavepoint = pTmp->pNext; + sqlite3DbFree(db, pTmp); + } + db->nSavepoint = 0; + db->nStatement = 0; + db->isTransactionSavepoint = 0; +} + +/* +** Invoke the destructor function associated with FuncDef p, if any. Except, +** if this is not the last copy of the function, do not invoke it. Multiple +** copies of a single function are created when create_function() is called +** with SQLITE_ANY as the encoding. +*/ +static void functionDestroy(sqlite3 *db, FuncDef *p){ + FuncDestructor *pDestructor = p->pDestructor; + if( pDestructor ){ + pDestructor->nRef--; + if( pDestructor->nRef==0 ){ + pDestructor->xDestroy(pDestructor->pUserData); + sqlite3DbFree(db, pDestructor); + } + } +} + +/* +** Disconnect all sqlite3_vtab objects that belong to database connection +** db. This is called when db is being closed. +*/ +static void disconnectAllVtab(sqlite3 *db){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + int i; + sqlite3BtreeEnterAll(db); + for(i=0; inDb; i++){ + Schema *pSchema = db->aDb[i].pSchema; + if( db->aDb[i].pSchema ){ + HashElem *p; + for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ + Table *pTab = (Table *)sqliteHashData(p); + if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); + } + } + } + sqlite3BtreeLeaveAll(db); +#else + UNUSED_PARAMETER(db); +#endif +} + +/* +** Return TRUE if database connection db has unfinalized prepared +** statements or unfinished sqlite3_backup objects. +*/ +static int connectionIsBusy(sqlite3 *db){ + int j; + assert( sqlite3_mutex_held(db->mutex) ); + if( db->pVdbe ) return 1; + for(j=0; jnDb; j++){ + Btree *pBt = db->aDb[j].pBt; + if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; + } + return 0; +} + +/* +** Close an existing SQLite database +*/ +static int sqlite3Close(sqlite3 *db, int forceZombie){ + if( !db ){ + return SQLITE_OK; + } + if( !sqlite3SafetyCheckSickOrOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + sqlite3_mutex_enter(db->mutex); + + /* Force xDisconnect calls on all virtual tables */ + disconnectAllVtab(db); + + /* If a transaction is open, the disconnectAllVtab() call above + ** will not have called the xDisconnect() method on any virtual + ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() + ** call will do so. We need to do this before the check for active + ** SQL statements below, as the v-table implementation may be storing + ** some prepared statements internally. + */ + sqlite3VtabRollback(db); + + /* Legacy behavior (sqlite3_close() behavior) is to return + ** SQLITE_BUSY if the connection can not be closed immediately. + */ + if( !forceZombie && connectionIsBusy(db) ){ + sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized " + "statements or unfinished backups"); + sqlite3_mutex_leave(db->mutex); + return SQLITE_BUSY; + } + +#ifdef SQLITE_ENABLE_SQLLOG + if( sqlite3GlobalConfig.xSqllog ){ + /* Closing the handle. Fourth parameter is passed the value 2. */ + sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); + } +#endif + + /* Convert the connection into a zombie and then close it. + */ + db->magic = SQLITE_MAGIC_ZOMBIE; + sqlite3LeaveMutexAndCloseZombie(db); + return SQLITE_OK; +} + +/* +** Two variations on the public interface for closing a database +** connection. The sqlite3_close() version returns SQLITE_BUSY and +** leaves the connection option if there are unfinalized prepared +** statements or unfinished sqlite3_backups. The sqlite3_close_v2() +** version forces the connection to become a zombie if there are +** unclosed resources, and arranges for deallocation when the last +** prepare statement or sqlite3_backup closes. +*/ +int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } +int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } + + +/* +** Close the mutex on database connection db. +** +** Furthermore, if database connection db is a zombie (meaning that there +** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and +** every sqlite3_stmt has now been finalized and every sqlite3_backup has +** finished, then free all resources. +*/ +void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ + HashElem *i; /* Hash table iterator */ + int j; + + /* If there are outstanding sqlite3_stmt or sqlite3_backup objects + ** or if the connection has not yet been closed by sqlite3_close_v2(), + ** then just leave the mutex and return. + */ + if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ + sqlite3_mutex_leave(db->mutex); + return; + } + + /* If we reach this point, it means that the database connection has + ** closed all sqlite3_stmt and sqlite3_backup objects and has been + ** passed to sqlite3_close (meaning that it is a zombie). Therefore, + ** go ahead and free all resources. + */ + + /* If a transaction is open, roll it back. This also ensures that if + ** any database schemas have been modified by an uncommitted transaction + ** they are reset. And that the required b-tree mutex is held to make + ** the pager rollback and schema reset an atomic operation. */ + sqlite3RollbackAll(db, SQLITE_OK); + + /* Free any outstanding Savepoint structures. */ + sqlite3CloseSavepoints(db); + + /* Close all database connections */ + for(j=0; jnDb; j++){ + struct Db *pDb = &db->aDb[j]; + if( pDb->pBt ){ + sqlite3BtreeClose(pDb->pBt); + pDb->pBt = 0; + if( j!=1 ){ + pDb->pSchema = 0; + } + } + } + /* Clear the TEMP schema separately and last */ + if( db->aDb[1].pSchema ){ + sqlite3SchemaClear(db->aDb[1].pSchema); + } + sqlite3VtabUnlockList(db); + + /* Free up the array of auxiliary databases */ + sqlite3CollapseDatabaseArray(db); + assert( db->nDb<=2 ); + assert( db->aDb==db->aDbStatic ); + + /* Tell the code in notify.c that the connection no longer holds any + ** locks and does not require any further unlock-notify callbacks. + */ + sqlite3ConnectionClosed(db); + + for(j=0; jaFunc.a); j++){ + FuncDef *pNext, *pHash, *p; + for(p=db->aFunc.a[j]; p; p=pHash){ + pHash = p->pHash; + while( p ){ + functionDestroy(db, p); + pNext = p->pNext; + sqlite3DbFree(db, p); + p = pNext; + } + } + } + for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ + CollSeq *pColl = (CollSeq *)sqliteHashData(i); + /* Invoke any destructors registered for collation sequence user data. */ + for(j=0; j<3; j++){ + if( pColl[j].xDel ){ + pColl[j].xDel(pColl[j].pUser); + } + } + sqlite3DbFree(db, pColl); + } + sqlite3HashClear(&db->aCollSeq); +#ifndef SQLITE_OMIT_VIRTUALTABLE + for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ + Module *pMod = (Module *)sqliteHashData(i); + if( pMod->xDestroy ){ + pMod->xDestroy(pMod->pAux); + } + sqlite3DbFree(db, pMod); + } + sqlite3HashClear(&db->aModule); +#endif + + sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */ + if( db->pErr ){ + sqlite3ValueFree(db->pErr); + } + sqlite3CloseExtensions(db); + + db->magic = SQLITE_MAGIC_ERROR; + + /* The temp-database schema is allocated differently from the other schema + ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). + ** So it needs to be freed here. Todo: Why not roll the temp schema into + ** the same sqliteMalloc() as the one that allocates the database + ** structure? + */ + sqlite3DbFree(db, db->aDb[1].pSchema); + sqlite3_mutex_leave(db->mutex); + db->magic = SQLITE_MAGIC_CLOSED; + sqlite3_mutex_free(db->mutex); + assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ + if( db->lookaside.bMalloced ){ + sqlite3_free(db->lookaside.pStart); + } + sqlite3_free(db); +} + +/* +** Rollback all database files. If tripCode is not SQLITE_OK, then +** any open cursors are invalidated ("tripped" - as in "tripping a circuit +** breaker") and made to return tripCode if there are any further +** attempts to use that cursor. +*/ +void sqlite3RollbackAll(sqlite3 *db, int tripCode){ + int i; + int inTrans = 0; + assert( sqlite3_mutex_held(db->mutex) ); + sqlite3BeginBenignMalloc(); + + /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). + ** This is important in case the transaction being rolled back has + ** modified the database schema. If the b-tree mutexes are not taken + ** here, then another shared-cache connection might sneak in between + ** the database rollback and schema reset, which can cause false + ** corruption reports in some cases. */ + sqlite3BtreeEnterAll(db); + + for(i=0; inDb; i++){ + Btree *p = db->aDb[i].pBt; + if( p ){ + if( sqlite3BtreeIsInTrans(p) ){ + inTrans = 1; + } + sqlite3BtreeRollback(p, tripCode); + } + } + sqlite3VtabRollback(db); + sqlite3EndBenignMalloc(); + + if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){ + sqlite3ExpirePreparedStatements(db); + sqlite3ResetAllSchemasOfConnection(db); + } + sqlite3BtreeLeaveAll(db); + + /* Any deferred constraint violations have now been resolved. */ + db->nDeferredCons = 0; + db->nDeferredImmCons = 0; + db->flags &= ~SQLITE_DeferFKs; + + /* If one has been configured, invoke the rollback-hook callback */ + if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ + db->xRollbackCallback(db->pRollbackArg); + } +} + +/* +** Return a static string containing the name corresponding to the error code +** specified in the argument. +*/ +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \ + defined(SQLITE_DEBUG_OS_TRACE) +const char *sqlite3ErrName(int rc){ + const char *zName = 0; + int i, origRc = rc; + for(i=0; i<2 && zName==0; i++, rc &= 0xff){ + switch( rc ){ + case SQLITE_OK: zName = "SQLITE_OK"; break; + case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; + case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; + case SQLITE_PERM: zName = "SQLITE_PERM"; break; + case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; + case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break; + case SQLITE_BUSY: zName = "SQLITE_BUSY"; break; + case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break; + case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break; + case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break; + case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break; + case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; + case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; + case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; + case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break; + case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; + case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; + case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; + case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; + case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break; + case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break; + case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break; + case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break; + case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break; + case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break; + case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break; + case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break; + case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break; + case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break; + case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break; + case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break; + case SQLITE_IOERR_CHECKRESERVEDLOCK: + zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; + case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break; + case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break; + case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break; + case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break; + case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break; + case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break; + case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break; + case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break; + case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break; + case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break; + case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break; + case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break; + case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break; + case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break; + case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break; + case SQLITE_FULL: zName = "SQLITE_FULL"; break; + case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break; + case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break; + case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; + case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; + case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; + case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; + case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; + case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; + case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break; + case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break; + case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break; + case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break; + case SQLITE_CONSTRAINT_FOREIGNKEY: + zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break; + case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break; + case SQLITE_CONSTRAINT_PRIMARYKEY: + zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break; + case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break; + case SQLITE_CONSTRAINT_COMMITHOOK: + zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break; + case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; + case SQLITE_CONSTRAINT_FUNCTION: + zName = "SQLITE_CONSTRAINT_FUNCTION"; break; + case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; + case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; + case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; + case SQLITE_AUTH: zName = "SQLITE_AUTH"; break; + case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break; + case SQLITE_RANGE: zName = "SQLITE_RANGE"; break; + case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break; + case SQLITE_ROW: zName = "SQLITE_ROW"; break; + case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break; + case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break; + case SQLITE_NOTICE_RECOVER_ROLLBACK: + zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break; + case SQLITE_WARNING: zName = "SQLITE_WARNING"; break; + case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break; + case SQLITE_DONE: zName = "SQLITE_DONE"; break; + } + } + if( zName==0 ){ + static char zBuf[50]; + sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); + zName = zBuf; + } + return zName; +} +#endif + +/* +** Return a static string that describes the kind of error specified in the +** argument. +*/ +const char *sqlite3ErrStr(int rc){ + static const char* const aMsg[] = { + /* SQLITE_OK */ "not an error", + /* SQLITE_ERROR */ "SQL logic error or missing database", + /* SQLITE_INTERNAL */ 0, + /* SQLITE_PERM */ "access permission denied", + /* SQLITE_ABORT */ "callback requested query abort", + /* SQLITE_BUSY */ "database is locked", + /* SQLITE_LOCKED */ "database table is locked", + /* SQLITE_NOMEM */ "out of memory", + /* SQLITE_READONLY */ "attempt to write a readonly database", + /* SQLITE_INTERRUPT */ "interrupted", + /* SQLITE_IOERR */ "disk I/O error", + /* SQLITE_CORRUPT */ "database disk image is malformed", + /* SQLITE_NOTFOUND */ "unknown operation", + /* SQLITE_FULL */ "database or disk is full", + /* SQLITE_CANTOPEN */ "unable to open database file", + /* SQLITE_PROTOCOL */ "locking protocol", + /* SQLITE_EMPTY */ "table contains no data", + /* SQLITE_SCHEMA */ "database schema has changed", + /* SQLITE_TOOBIG */ "string or blob too big", + /* SQLITE_CONSTRAINT */ "constraint failed", + /* SQLITE_MISMATCH */ "datatype mismatch", + /* SQLITE_MISUSE */ "library routine called out of sequence", + /* SQLITE_NOLFS */ "large file support is disabled", + /* SQLITE_AUTH */ "authorization denied", + /* SQLITE_FORMAT */ "auxiliary database format error", + /* SQLITE_RANGE */ "bind or column index out of range", + /* SQLITE_NOTADB */ "file is encrypted or is not a database", + }; + const char *zErr = "unknown error"; + switch( rc ){ + case SQLITE_ABORT_ROLLBACK: { + zErr = "abort due to ROLLBACK"; + break; + } + default: { + rc &= 0xff; + if( ALWAYS(rc>=0) && rcbusyTimeout; + int delay, prior; + + assert( count>=0 ); + if( count < NDELAY ){ + delay = delays[count]; + prior = totals[count]; + }else{ + delay = delays[NDELAY-1]; + prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); + } + if( prior + delay > timeout ){ + delay = timeout - prior; + if( delay<=0 ) return 0; + } + sqlite3OsSleep(db->pVfs, delay*1000); + return 1; +#else + sqlite3 *db = (sqlite3 *)ptr; + int timeout = ((sqlite3 *)ptr)->busyTimeout; + if( (count+1)*1000 > timeout ){ + return 0; + } + sqlite3OsSleep(db->pVfs, 1000000); + return 1; +#endif +} + +/* +** Invoke the given busy handler. +** +** This routine is called when an operation failed with a lock. +** If this routine returns non-zero, the lock is retried. If it +** returns 0, the operation aborts with an SQLITE_BUSY error. +*/ +int sqlite3InvokeBusyHandler(BusyHandler *p){ + int rc; + if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; + rc = p->xFunc(p->pArg, p->nBusy); + if( rc==0 ){ + p->nBusy = -1; + }else{ + p->nBusy++; + } + return rc; +} + +/* +** This routine sets the busy callback for an Sqlite database to the +** given callback function with the given argument. +*/ +int sqlite3_busy_handler( + sqlite3 *db, + int (*xBusy)(void*,int), + void *pArg +){ + sqlite3_mutex_enter(db->mutex); + db->busyHandler.xFunc = xBusy; + db->busyHandler.pArg = pArg; + db->busyHandler.nBusy = 0; + db->busyTimeout = 0; + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK +/* +** This routine sets the progress callback for an Sqlite database to the +** given callback function with the given argument. The progress callback will +** be invoked every nOps opcodes. +*/ +void sqlite3_progress_handler( + sqlite3 *db, + int nOps, + int (*xProgress)(void*), + void *pArg +){ + sqlite3_mutex_enter(db->mutex); + if( nOps>0 ){ + db->xProgress = xProgress; + db->nProgressOps = (unsigned)nOps; + db->pProgressArg = pArg; + }else{ + db->xProgress = 0; + db->nProgressOps = 0; + db->pProgressArg = 0; + } + sqlite3_mutex_leave(db->mutex); +} +#endif + + +/* +** This routine installs a default busy handler that waits for the +** specified number of milliseconds before returning 0. +*/ +int sqlite3_busy_timeout(sqlite3 *db, int ms){ + if( ms>0 ){ + sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); + db->busyTimeout = ms; + }else{ + sqlite3_busy_handler(db, 0, 0); + } + return SQLITE_OK; +} + +/* +** Cause any pending operation to stop at its earliest opportunity. +*/ +void sqlite3_interrupt(sqlite3 *db){ + db->u1.isInterrupted = 1; +} + + +/* +** This function is exactly the same as sqlite3_create_function(), except +** that it is designed to be called by internal code. The difference is +** that if a malloc() fails in sqlite3_create_function(), an error code +** is returned and the mallocFailed flag cleared. +*/ +int sqlite3CreateFunc( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int enc, + void *pUserData, + void (*xFunc)(sqlite3_context*,int,sqlite3_value **), + void (*xStep)(sqlite3_context*,int,sqlite3_value **), + void (*xFinal)(sqlite3_context*), + FuncDestructor *pDestructor +){ + FuncDef *p; + int nName; + + assert( sqlite3_mutex_held(db->mutex) ); + if( zFunctionName==0 || + (xFunc && (xFinal || xStep)) || + (!xFunc && (xFinal && !xStep)) || + (!xFunc && (!xFinal && xStep)) || + (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || + (255<(nName = sqlite3Strlen30( zFunctionName))) ){ + return SQLITE_MISUSE_BKPT; + } + +#ifndef SQLITE_OMIT_UTF16 + /* If SQLITE_UTF16 is specified as the encoding type, transform this + ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the + ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. + ** + ** If SQLITE_ANY is specified, add three versions of the function + ** to the hash table. + */ + if( enc==SQLITE_UTF16 ){ + enc = SQLITE_UTF16NATIVE; + }else if( enc==SQLITE_ANY ){ + int rc; + rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8, + pUserData, xFunc, xStep, xFinal, pDestructor); + if( rc==SQLITE_OK ){ + rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE, + pUserData, xFunc, xStep, xFinal, pDestructor); + } + if( rc!=SQLITE_OK ){ + return rc; + } + enc = SQLITE_UTF16BE; + } +#else + enc = SQLITE_UTF8; +#endif + + /* Check if an existing function is being overridden or deleted. If so, + ** and there are active VMs, then return SQLITE_BUSY. If a function + ** is being overridden/deleted but there are no active VMs, allow the + ** operation to continue but invalidate all precompiled statements. + */ + p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0); + if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){ + if( db->nVdbeActive ){ + sqlite3Error(db, SQLITE_BUSY, + "unable to delete/modify user-function due to active statements"); + assert( !db->mallocFailed ); + return SQLITE_BUSY; + }else{ + sqlite3ExpirePreparedStatements(db); + } + } + + p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1); + assert(p || db->mallocFailed); + if( !p ){ + return SQLITE_NOMEM; + } + + /* If an older version of the function with a configured destructor is + ** being replaced invoke the destructor function here. */ + functionDestroy(db, p); + + if( pDestructor ){ + pDestructor->nRef++; + } + p->pDestructor = pDestructor; + p->funcFlags &= SQLITE_FUNC_ENCMASK; + p->xFunc = xFunc; + p->xStep = xStep; + p->xFinalize = xFinal; + p->pUserData = pUserData; + p->nArg = (u16)nArg; + return SQLITE_OK; +} + +/* +** Create new user functions. +*/ +int sqlite3_create_function( + sqlite3 *db, + const char *zFunc, + int nArg, + int enc, + void *p, + void (*xFunc)(sqlite3_context*,int,sqlite3_value **), + void (*xStep)(sqlite3_context*,int,sqlite3_value **), + void (*xFinal)(sqlite3_context*) +){ + return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep, + xFinal, 0); +} + +int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunc, + int nArg, + int enc, + void *p, + void (*xFunc)(sqlite3_context*,int,sqlite3_value **), + void (*xStep)(sqlite3_context*,int,sqlite3_value **), + void (*xFinal)(sqlite3_context*), + void (*xDestroy)(void *) +){ + int rc = SQLITE_ERROR; + FuncDestructor *pArg = 0; + sqlite3_mutex_enter(db->mutex); + if( xDestroy ){ + pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); + if( !pArg ){ + xDestroy(p); + goto out; + } + pArg->xDestroy = xDestroy; + pArg->pUserData = p; + } + rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg); + if( pArg && pArg->nRef==0 ){ + assert( rc!=SQLITE_OK ); + xDestroy(p); + sqlite3DbFree(db, pArg); + } + + out: + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#ifndef SQLITE_OMIT_UTF16 +int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *p, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +){ + int rc; + char *zFunc8; + sqlite3_mutex_enter(db->mutex); + assert( !db->mallocFailed ); + zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); + rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0); + sqlite3DbFree(db, zFunc8); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} +#endif + + +/* +** Declare that a function has been overloaded by a virtual table. +** +** If the function already exists as a regular global function, then +** this routine is a no-op. If the function does not exist, then create +** a new one that always throws a run-time error. +** +** When virtual tables intend to provide an overloaded function, they +** should call this routine to make sure the global function exists. +** A global function must exist in order for name resolution to work +** properly. +*/ +int sqlite3_overload_function( + sqlite3 *db, + const char *zName, + int nArg +){ + int nName = sqlite3Strlen30(zName); + int rc = SQLITE_OK; + sqlite3_mutex_enter(db->mutex); + if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){ + rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, + 0, sqlite3InvalidFunction, 0, 0, 0); + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#ifndef SQLITE_OMIT_TRACE +/* +** Register a trace function. The pArg from the previously registered trace +** is returned. +** +** A NULL trace function means that no tracing is executes. A non-NULL +** trace is a pointer to a function that is invoked at the start of each +** SQL statement. +*/ +void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){ + void *pOld; + sqlite3_mutex_enter(db->mutex); + pOld = db->pTraceArg; + db->xTrace = xTrace; + db->pTraceArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pOld; +} +/* +** Register a profile function. The pArg from the previously registered +** profile function is returned. +** +** A NULL profile function means that no profiling is executes. A non-NULL +** profile is a pointer to a function that is invoked at the conclusion of +** each SQL statement that is run. +*/ +void *sqlite3_profile( + sqlite3 *db, + void (*xProfile)(void*,const char*,sqlite_uint64), + void *pArg +){ + void *pOld; + sqlite3_mutex_enter(db->mutex); + pOld = db->pProfileArg; + db->xProfile = xProfile; + db->pProfileArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pOld; +} +#endif /* SQLITE_OMIT_TRACE */ + +/* +** Register a function to be invoked when a transaction commits. +** If the invoked function returns non-zero, then the commit becomes a +** rollback. +*/ +void *sqlite3_commit_hook( + sqlite3 *db, /* Attach the hook to this database */ + int (*xCallback)(void*), /* Function to invoke on each commit */ + void *pArg /* Argument to the function */ +){ + void *pOld; + sqlite3_mutex_enter(db->mutex); + pOld = db->pCommitArg; + db->xCommitCallback = xCallback; + db->pCommitArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pOld; +} + +/* +** Register a callback to be invoked each time a row is updated, +** inserted or deleted using this database connection. +*/ +void *sqlite3_update_hook( + sqlite3 *db, /* Attach the hook to this database */ + void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), + void *pArg /* Argument to the function */ +){ + void *pRet; + sqlite3_mutex_enter(db->mutex); + pRet = db->pUpdateArg; + db->xUpdateCallback = xCallback; + db->pUpdateArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pRet; +} + +/* +** Register a callback to be invoked each time a transaction is rolled +** back by this database connection. +*/ +void *sqlite3_rollback_hook( + sqlite3 *db, /* Attach the hook to this database */ + void (*xCallback)(void*), /* Callback function */ + void *pArg /* Argument to the function */ +){ + void *pRet; + sqlite3_mutex_enter(db->mutex); + pRet = db->pRollbackArg; + db->xRollbackCallback = xCallback; + db->pRollbackArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pRet; +} + +#ifndef SQLITE_OMIT_WAL +/* +** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). +** Invoke sqlite3_wal_checkpoint if the number of frames in the log file +** is greater than sqlite3.pWalArg cast to an integer (the value configured by +** wal_autocheckpoint()). +*/ +int sqlite3WalDefaultHook( + void *pClientData, /* Argument */ + sqlite3 *db, /* Connection */ + const char *zDb, /* Database */ + int nFrame /* Size of WAL */ +){ + if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ + sqlite3BeginBenignMalloc(); + sqlite3_wal_checkpoint(db, zDb); + sqlite3EndBenignMalloc(); + } + return SQLITE_OK; +} +#endif /* SQLITE_OMIT_WAL */ + +/* +** Configure an sqlite3_wal_hook() callback to automatically checkpoint +** a database after committing a transaction if there are nFrame or +** more frames in the log file. Passing zero or a negative value as the +** nFrame parameter disables automatic checkpoints entirely. +** +** The callback registered by this function replaces any existing callback +** registered using sqlite3_wal_hook(). Likewise, registering a callback +** using sqlite3_wal_hook() disables the automatic checkpoint mechanism +** configured by this function. +*/ +int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ +#ifdef SQLITE_OMIT_WAL + UNUSED_PARAMETER(db); + UNUSED_PARAMETER(nFrame); +#else + if( nFrame>0 ){ + sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); + }else{ + sqlite3_wal_hook(db, 0, 0); + } +#endif + return SQLITE_OK; +} + +/* +** Register a callback to be invoked each time a transaction is written +** into the write-ahead-log by this database connection. +*/ +void *sqlite3_wal_hook( + sqlite3 *db, /* Attach the hook to this db handle */ + int(*xCallback)(void *, sqlite3*, const char*, int), + void *pArg /* First argument passed to xCallback() */ +){ +#ifndef SQLITE_OMIT_WAL + void *pRet; + sqlite3_mutex_enter(db->mutex); + pRet = db->pWalArg; + db->xWalCallback = xCallback; + db->pWalArg = pArg; + sqlite3_mutex_leave(db->mutex); + return pRet; +#else + return 0; +#endif +} + +/* +** Checkpoint database zDb. +*/ +int sqlite3_wal_checkpoint_v2( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + int *pnLog, /* OUT: Size of WAL log in frames */ + int *pnCkpt /* OUT: Total number of frames checkpointed */ +){ +#ifdef SQLITE_OMIT_WAL + return SQLITE_OK; +#else + int rc; /* Return code */ + int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ + + /* Initialize the output variables to -1 in case an error occurs. */ + if( pnLog ) *pnLog = -1; + if( pnCkpt ) *pnCkpt = -1; + + assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE ); + assert( SQLITE_CHECKPOINT_FULLSQLITE_CHECKPOINT_RESTART ){ + return SQLITE_MISUSE; + } + + sqlite3_mutex_enter(db->mutex); + if( zDb && zDb[0] ){ + iDb = sqlite3FindDbName(db, zDb); + } + if( iDb<0 ){ + rc = SQLITE_ERROR; + sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb); + }else{ + rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); + sqlite3Error(db, rc, 0); + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +#endif +} + + +/* +** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points +** to contains a zero-length string, all attached databases are +** checkpointed. +*/ +int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ + return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0); +} + +#ifndef SQLITE_OMIT_WAL +/* +** Run a checkpoint on database iDb. This is a no-op if database iDb is +** not currently open in WAL mode. +** +** If a transaction is open on the database being checkpointed, this +** function returns SQLITE_LOCKED and a checkpoint is not attempted. If +** an error occurs while running the checkpoint, an SQLite error code is +** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. +** +** The mutex on database handle db should be held by the caller. The mutex +** associated with the specific b-tree being checkpointed is taken by +** this function while the checkpoint is running. +** +** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are +** checkpointed. If an error is encountered it is returned immediately - +** no attempt is made to checkpoint any remaining databases. +** +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +*/ +int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ + int rc = SQLITE_OK; /* Return code */ + int i; /* Used to iterate through attached dbs */ + int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ + + assert( sqlite3_mutex_held(db->mutex) ); + assert( !pnLog || *pnLog==-1 ); + assert( !pnCkpt || *pnCkpt==-1 ); + + for(i=0; inDb && rc==SQLITE_OK; i++){ + if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ + rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); + pnLog = 0; + pnCkpt = 0; + if( rc==SQLITE_BUSY ){ + bBusy = 1; + rc = SQLITE_OK; + } + } + } + + return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; +} +#endif /* SQLITE_OMIT_WAL */ + +/* +** This function returns true if main-memory should be used instead of +** a temporary file for transient pager files and statement journals. +** The value returned depends on the value of db->temp_store (runtime +** parameter) and the compile time value of SQLITE_TEMP_STORE. The +** following table describes the relationship between these two values +** and this functions return value. +** +** SQLITE_TEMP_STORE db->temp_store Location of temporary database +** ----------------- -------------- ------------------------------ +** 0 any file (return 0) +** 1 1 file (return 0) +** 1 2 memory (return 1) +** 1 0 file (return 0) +** 2 1 file (return 0) +** 2 2 memory (return 1) +** 2 0 memory (return 1) +** 3 any memory (return 1) +*/ +int sqlite3TempInMemory(const sqlite3 *db){ +#if SQLITE_TEMP_STORE==1 + return ( db->temp_store==2 ); +#endif +#if SQLITE_TEMP_STORE==2 + return ( db->temp_store!=1 ); +#endif +#if SQLITE_TEMP_STORE==3 + return 1; +#endif +#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 + return 0; +#endif +} + +/* +** Return UTF-8 encoded English language explanation of the most recent +** error. +*/ +const char *sqlite3_errmsg(sqlite3 *db){ + const char *z; + if( !db ){ + return sqlite3ErrStr(SQLITE_NOMEM); + } + if( !sqlite3SafetyCheckSickOrOk(db) ){ + return sqlite3ErrStr(SQLITE_MISUSE_BKPT); + } + sqlite3_mutex_enter(db->mutex); + if( db->mallocFailed ){ + z = sqlite3ErrStr(SQLITE_NOMEM); + }else{ + z = (char*)sqlite3_value_text(db->pErr); + assert( !db->mallocFailed ); + if( z==0 ){ + z = sqlite3ErrStr(db->errCode); + } + } + sqlite3_mutex_leave(db->mutex); + return z; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Return UTF-16 encoded English language explanation of the most recent +** error. +*/ +const void *sqlite3_errmsg16(sqlite3 *db){ + static const u16 outOfMem[] = { + 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 + }; + static const u16 misuse[] = { + 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', + 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', + 'c', 'a', 'l', 'l', 'e', 'd', ' ', + 'o', 'u', 't', ' ', + 'o', 'f', ' ', + 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 + }; + + const void *z; + if( !db ){ + return (void *)outOfMem; + } + if( !sqlite3SafetyCheckSickOrOk(db) ){ + return (void *)misuse; + } + sqlite3_mutex_enter(db->mutex); + if( db->mallocFailed ){ + z = (void *)outOfMem; + }else{ + z = sqlite3_value_text16(db->pErr); + if( z==0 ){ + sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode), + SQLITE_UTF8, SQLITE_STATIC); + z = sqlite3_value_text16(db->pErr); + } + /* A malloc() may have failed within the call to sqlite3_value_text16() + ** above. If this is the case, then the db->mallocFailed flag needs to + ** be cleared before returning. Do this directly, instead of via + ** sqlite3ApiExit(), to avoid setting the database handle error message. + */ + db->mallocFailed = 0; + } + sqlite3_mutex_leave(db->mutex); + return z; +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Return the most recent error code generated by an SQLite routine. If NULL is +** passed to this function, we assume a malloc() failed during sqlite3_open(). +*/ +int sqlite3_errcode(sqlite3 *db){ + if( db && !sqlite3SafetyCheckSickOrOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + if( !db || db->mallocFailed ){ + return SQLITE_NOMEM; + } + return db->errCode & db->errMask; +} +int sqlite3_extended_errcode(sqlite3 *db){ + if( db && !sqlite3SafetyCheckSickOrOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + if( !db || db->mallocFailed ){ + return SQLITE_NOMEM; + } + return db->errCode; +} + +/* +** Return a string that describes the kind of error specified in the +** argument. For now, this simply calls the internal sqlite3ErrStr() +** function. +*/ +const char *sqlite3_errstr(int rc){ + return sqlite3ErrStr(rc); +} + +/* +** Create a new collating function for database "db". The name is zName +** and the encoding is enc. +*/ +static int createCollation( + sqlite3* db, + const char *zName, + u8 enc, + void* pCtx, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDel)(void*) +){ + CollSeq *pColl; + int enc2; + int nName = sqlite3Strlen30(zName); + + assert( sqlite3_mutex_held(db->mutex) ); + + /* If SQLITE_UTF16 is specified as the encoding type, transform this + ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the + ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. + */ + enc2 = enc; + testcase( enc2==SQLITE_UTF16 ); + testcase( enc2==SQLITE_UTF16_ALIGNED ); + if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ + enc2 = SQLITE_UTF16NATIVE; + } + if( enc2SQLITE_UTF16BE ){ + return SQLITE_MISUSE_BKPT; + } + + /* Check if this call is removing or replacing an existing collation + ** sequence. If so, and there are active VMs, return busy. If there + ** are no active VMs, invalidate any pre-compiled statements. + */ + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); + if( pColl && pColl->xCmp ){ + if( db->nVdbeActive ){ + sqlite3Error(db, SQLITE_BUSY, + "unable to delete/modify collation sequence due to active statements"); + return SQLITE_BUSY; + } + sqlite3ExpirePreparedStatements(db); + + /* If collation sequence pColl was created directly by a call to + ** sqlite3_create_collation, and not generated by synthCollSeq(), + ** then any copies made by synthCollSeq() need to be invalidated. + ** Also, collation destructor - CollSeq.xDel() - function may need + ** to be called. + */ + if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ + CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName); + int j; + for(j=0; j<3; j++){ + CollSeq *p = &aColl[j]; + if( p->enc==pColl->enc ){ + if( p->xDel ){ + p->xDel(p->pUser); + } + p->xCmp = 0; + } + } + } + } + + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); + if( pColl==0 ) return SQLITE_NOMEM; + pColl->xCmp = xCompare; + pColl->pUser = pCtx; + pColl->xDel = xDel; + pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); + sqlite3Error(db, SQLITE_OK, 0); + return SQLITE_OK; +} + + +/* +** This array defines hard upper bounds on limit values. The +** initializer must be kept in sync with the SQLITE_LIMIT_* +** #defines in sqlite3.h. +*/ +static const int aHardLimit[] = { + SQLITE_MAX_LENGTH, + SQLITE_MAX_SQL_LENGTH, + SQLITE_MAX_COLUMN, + SQLITE_MAX_EXPR_DEPTH, + SQLITE_MAX_COMPOUND_SELECT, + SQLITE_MAX_VDBE_OP, + SQLITE_MAX_FUNCTION_ARG, + SQLITE_MAX_ATTACHED, + SQLITE_MAX_LIKE_PATTERN_LENGTH, + SQLITE_MAX_VARIABLE_NUMBER, + SQLITE_MAX_TRIGGER_DEPTH, +}; + +/* +** Make sure the hard limits are set to reasonable values +*/ +#if SQLITE_MAX_LENGTH<100 +# error SQLITE_MAX_LENGTH must be at least 100 +#endif +#if SQLITE_MAX_SQL_LENGTH<100 +# error SQLITE_MAX_SQL_LENGTH must be at least 100 +#endif +#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH +# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH +#endif +#if SQLITE_MAX_COMPOUND_SELECT<2 +# error SQLITE_MAX_COMPOUND_SELECT must be at least 2 +#endif +#if SQLITE_MAX_VDBE_OP<40 +# error SQLITE_MAX_VDBE_OP must be at least 40 +#endif +#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000 +# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000 +#endif +#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62 +# error SQLITE_MAX_ATTACHED must be between 0 and 62 +#endif +#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 +# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 +#endif +#if SQLITE_MAX_COLUMN>32767 +# error SQLITE_MAX_COLUMN must not exceed 32767 +#endif +#if SQLITE_MAX_TRIGGER_DEPTH<1 +# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 +#endif + + +/* +** Change the value of a limit. Report the old value. +** If an invalid limit index is supplied, report -1. +** Make no changes but still report the old value if the +** new limit is negative. +** +** A new lower limit does not shrink existing constructs. +** It merely prevents new constructs that exceed the limit +** from forming. +*/ +int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ + int oldLimit; + + + /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME + ** there is a hard upper bound set at compile-time by a C preprocessor + ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to + ** "_MAX_".) + */ + assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); + assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); + assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); + assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); + assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); + assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); + assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); + assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); + assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== + SQLITE_MAX_LIKE_PATTERN_LENGTH ); + assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); + assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); + assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) ); + + + if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ + return -1; + } + oldLimit = db->aLimit[limitId]; + if( newLimit>=0 ){ /* IMP: R-52476-28732 */ + if( newLimit>aHardLimit[limitId] ){ + newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ + } + db->aLimit[limitId] = newLimit; + } + return oldLimit; /* IMP: R-53341-35419 */ +} + +/* +** This function is used to parse both URIs and non-URI filenames passed by the +** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database +** URIs specified as part of ATTACH statements. +** +** The first argument to this function is the name of the VFS to use (or +** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" +** query parameter. The second argument contains the URI (or non-URI filename) +** itself. When this function is called the *pFlags variable should contain +** the default flags to open the database handle with. The value stored in +** *pFlags may be updated before returning if the URI filename contains +** "cache=xxx" or "mode=xxx" query parameters. +** +** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to +** the VFS that should be used to open the database file. *pzFile is set to +** point to a buffer containing the name of the file to open. It is the +** responsibility of the caller to eventually call sqlite3_free() to release +** this buffer. +** +** If an error occurs, then an SQLite error code is returned and *pzErrMsg +** may be set to point to a buffer containing an English language error +** message. It is the responsibility of the caller to eventually release +** this buffer by calling sqlite3_free(). +*/ +int sqlite3ParseUri( + const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ + const char *zUri, /* Nul-terminated URI to parse */ + unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ + sqlite3_vfs **ppVfs, /* OUT: VFS to use */ + char **pzFile, /* OUT: Filename component of URI */ + char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ +){ + int rc = SQLITE_OK; + unsigned int flags = *pFlags; + const char *zVfs = zDefaultVfs; + char *zFile; + char c; + int nUri = sqlite3Strlen30(zUri); + + assert( *pzErrMsg==0 ); + + if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) + && nUri>=5 && memcmp(zUri, "file:", 5)==0 + ){ + char *zOpt; + int eState; /* Parser state when parsing URI */ + int iIn; /* Input character index */ + int iOut = 0; /* Output character index */ + int nByte = nUri+2; /* Bytes of space to allocate */ + + /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen + ** method that there may be extra parameters following the file-name. */ + flags |= SQLITE_OPEN_URI; + + for(iIn=0; iIn=0 && octet<256 ); + if( octet==0 ){ + /* This branch is taken when "%00" appears within the URI. In this + ** case we ignore all text in the remainder of the path, name or + ** value currently being parsed. So ignore the current character + ** and skip to the next "?", "=" or "&", as appropriate. */ + while( (c = zUri[iIn])!=0 && c!='#' + && (eState!=0 || c!='?') + && (eState!=1 || (c!='=' && c!='&')) + && (eState!=2 || c!='&') + ){ + iIn++; + } + continue; + } + c = octet; + }else if( eState==1 && (c=='&' || c=='=') ){ + if( zFile[iOut-1]==0 ){ + /* An empty option name. Ignore this option altogether. */ + while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; + continue; + } + if( c=='&' ){ + zFile[iOut++] = '\0'; + }else{ + eState = 2; + } + c = 0; + }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ + c = 0; + eState = 1; + } + zFile[iOut++] = c; + } + if( eState==1 ) zFile[iOut++] = '\0'; + zFile[iOut++] = '\0'; + zFile[iOut++] = '\0'; + + /* Check if there were any options specified that should be interpreted + ** here. Options that are interpreted here include "vfs" and those that + ** correspond to flags that may be passed to the sqlite3_open_v2() + ** method. */ + zOpt = &zFile[sqlite3Strlen30(zFile)+1]; + while( zOpt[0] ){ + int nOpt = sqlite3Strlen30(zOpt); + char *zVal = &zOpt[nOpt+1]; + int nVal = sqlite3Strlen30(zVal); + + if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ + zVfs = zVal; + }else{ + struct OpenMode { + const char *z; + int mode; + } *aMode = 0; + char *zModeType = 0; + int mask = 0; + int limit = 0; + + if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ + static struct OpenMode aCacheMode[] = { + { "shared", SQLITE_OPEN_SHAREDCACHE }, + { "private", SQLITE_OPEN_PRIVATECACHE }, + { 0, 0 } + }; + + mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; + aMode = aCacheMode; + limit = mask; + zModeType = "cache"; + } + if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ + static struct OpenMode aOpenMode[] = { + { "ro", SQLITE_OPEN_READONLY }, + { "rw", SQLITE_OPEN_READWRITE }, + { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, + { "memory", SQLITE_OPEN_MEMORY }, + { 0, 0 } + }; + + mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE + | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; + aMode = aOpenMode; + limit = mask & flags; + zModeType = "access"; + } + + if( aMode ){ + int i; + int mode = 0; + for(i=0; aMode[i].z; i++){ + const char *z = aMode[i].z; + if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ + mode = aMode[i].mode; + break; + } + } + if( mode==0 ){ + *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); + rc = SQLITE_ERROR; + goto parse_uri_out; + } + if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ + *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", + zModeType, zVal); + rc = SQLITE_PERM; + goto parse_uri_out; + } + flags = (flags & ~mask) | mode; + } + } + + zOpt = &zVal[nVal+1]; + } + + }else{ + zFile = sqlite3_malloc(nUri+2); + if( !zFile ) return SQLITE_NOMEM; + memcpy(zFile, zUri, nUri); + zFile[nUri] = '\0'; + zFile[nUri+1] = '\0'; + flags &= ~SQLITE_OPEN_URI; + } + + *ppVfs = sqlite3_vfs_find(zVfs); + if( *ppVfs==0 ){ + *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); + rc = SQLITE_ERROR; + } + parse_uri_out: + if( rc!=SQLITE_OK ){ + sqlite3_free(zFile); + zFile = 0; + } + *pFlags = flags; + *pzFile = zFile; + return rc; +} + + +/* +** This routine does the work of opening a database on behalf of +** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" +** is UTF-8 encoded. +*/ +static int openDatabase( + const char *zFilename, /* Database filename UTF-8 encoded */ + sqlite3 **ppDb, /* OUT: Returned database handle */ + unsigned int flags, /* Operational flags */ + const char *zVfs /* Name of the VFS to use */ +){ + sqlite3 *db; /* Store allocated handle here */ + int rc; /* Return code */ + int isThreadsafe; /* True for threadsafe connections */ + char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ + char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ + + *ppDb = 0; +#ifndef SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if( rc ) return rc; +#endif + + /* Only allow sensible combinations of bits in the flags argument. + ** Throw an error if any non-sense combination is used. If we + ** do not block illegal combinations here, it could trigger + ** assert() statements in deeper layers. Sensible combinations + ** are: + ** + ** 1: SQLITE_OPEN_READONLY + ** 2: SQLITE_OPEN_READWRITE + ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE + */ + assert( SQLITE_OPEN_READONLY == 0x01 ); + assert( SQLITE_OPEN_READWRITE == 0x02 ); + assert( SQLITE_OPEN_CREATE == 0x04 ); + testcase( (1<<(flags&7))==0x02 ); /* READONLY */ + testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ + testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ + if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT; + + if( sqlite3GlobalConfig.bCoreMutex==0 ){ + isThreadsafe = 0; + }else if( flags & SQLITE_OPEN_NOMUTEX ){ + isThreadsafe = 0; + }else if( flags & SQLITE_OPEN_FULLMUTEX ){ + isThreadsafe = 1; + }else{ + isThreadsafe = sqlite3GlobalConfig.bFullMutex; + } + if( flags & SQLITE_OPEN_PRIVATECACHE ){ + flags &= ~SQLITE_OPEN_SHAREDCACHE; + }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ + flags |= SQLITE_OPEN_SHAREDCACHE; + } + + /* Remove harmful bits from the flags parameter + ** + ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were + ** dealt with in the previous code block. Besides these, the only + ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, + ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, + ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask + ** off all other flags. + */ + flags &= ~( SQLITE_OPEN_DELETEONCLOSE | + SQLITE_OPEN_EXCLUSIVE | + SQLITE_OPEN_MAIN_DB | + SQLITE_OPEN_TEMP_DB | + SQLITE_OPEN_TRANSIENT_DB | + SQLITE_OPEN_MAIN_JOURNAL | + SQLITE_OPEN_TEMP_JOURNAL | + SQLITE_OPEN_SUBJOURNAL | + SQLITE_OPEN_MASTER_JOURNAL | + SQLITE_OPEN_NOMUTEX | + SQLITE_OPEN_FULLMUTEX | + SQLITE_OPEN_WAL + ); + + /* Allocate the sqlite data structure */ + db = sqlite3MallocZero( sizeof(sqlite3) ); + if( db==0 ) goto opendb_out; + if( isThreadsafe ){ + db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); + if( db->mutex==0 ){ + sqlite3_free(db); + db = 0; + goto opendb_out; + } + } + sqlite3_mutex_enter(db->mutex); + db->errMask = 0xff; + db->nDb = 2; + db->magic = SQLITE_MAGIC_BUSY; + db->aDb = db->aDbStatic; + + assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); + memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); + db->autoCommit = 1; + db->nextAutovac = -1; + db->szMmap = sqlite3GlobalConfig.szMmap; + db->nextPagesize = 0; + db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill +#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX + | SQLITE_AutoIndex +#endif +#if SQLITE_DEFAULT_FILE_FORMAT<4 + | SQLITE_LegacyFileFmt +#endif +#ifdef SQLITE_ENABLE_LOAD_EXTENSION + | SQLITE_LoadExtension +#endif +#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS + | SQLITE_RecTriggers +#endif +#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS + | SQLITE_ForeignKeys +#endif + ; + sqlite3HashInit(&db->aCollSeq); +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3HashInit(&db->aModule); +#endif + + /* Add the default collation sequence BINARY. BINARY works for both UTF-8 + ** and UTF-16, so add a version for each to avoid any unnecessary + ** conversions. The only error that can occur here is a malloc() failure. + */ + createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0); + createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0); + createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0); + createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); + if( db->mallocFailed ){ + goto opendb_out; + } + db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0); + assert( db->pDfltColl!=0 ); + + /* Also add a UTF-8 case-insensitive collation sequence. */ + createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); + + /* Parse the filename/URI argument. */ + db->openFlags = flags; + rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM ) db->mallocFailed = 1; + sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg); + sqlite3_free(zErrMsg); + goto opendb_out; + } + + /* Open the backend database driver */ + rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, + flags | SQLITE_OPEN_MAIN_DB); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_IOERR_NOMEM ){ + rc = SQLITE_NOMEM; + } + sqlite3Error(db, rc, 0); + goto opendb_out; + } + db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); + db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); + + + /* The default safety_level for the main database is 'full'; for the temp + ** database it is 'NONE'. This matches the pager layer defaults. + */ + db->aDb[0].zName = "main"; + db->aDb[0].safety_level = 3; + db->aDb[1].zName = "temp"; + db->aDb[1].safety_level = 1; + + db->magic = SQLITE_MAGIC_OPEN; + if( db->mallocFailed ){ + goto opendb_out; + } + + /* Register all built-in functions, but do not attempt to read the + ** database schema yet. This is delayed until the first time the database + ** is accessed. + */ + sqlite3Error(db, SQLITE_OK, 0); + sqlite3RegisterBuiltinFunctions(db); + + /* Load automatic extensions - extensions that have been registered + ** using the sqlite3_automatic_extension() API. + */ + rc = sqlite3_errcode(db); + if( rc==SQLITE_OK ){ + sqlite3AutoLoadExtensions(db); + rc = sqlite3_errcode(db); + if( rc!=SQLITE_OK ){ + goto opendb_out; + } + } + +#ifdef SQLITE_ENABLE_FTS1 + if( !db->mallocFailed ){ + extern int sqlite3Fts1Init(sqlite3*); + rc = sqlite3Fts1Init(db); + } +#endif + +#ifdef SQLITE_ENABLE_FTS2 + if( !db->mallocFailed && rc==SQLITE_OK ){ + extern int sqlite3Fts2Init(sqlite3*); + rc = sqlite3Fts2Init(db); + } +#endif + +#ifdef SQLITE_ENABLE_FTS3 + if( !db->mallocFailed && rc==SQLITE_OK ){ + rc = sqlite3Fts3Init(db); + } +#endif + +#ifdef SQLITE_ENABLE_ICU + if( !db->mallocFailed && rc==SQLITE_OK ){ + rc = sqlite3IcuInit(db); + } +#endif + +#ifdef SQLITE_ENABLE_RTREE + if( !db->mallocFailed && rc==SQLITE_OK){ + rc = sqlite3RtreeInit(db); + } +#endif + + sqlite3Error(db, rc, 0); + + /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking + ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking + ** mode. Doing nothing at all also makes NORMAL the default. + */ +#ifdef SQLITE_DEFAULT_LOCKING_MODE + db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; + sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), + SQLITE_DEFAULT_LOCKING_MODE); +#endif + + /* Enable the lookaside-malloc subsystem */ + setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, + sqlite3GlobalConfig.nLookaside); + + sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); + +opendb_out: + sqlite3_free(zOpen); + if( db ){ + assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 ); + sqlite3_mutex_leave(db->mutex); + } + rc = sqlite3_errcode(db); + assert( db!=0 || rc==SQLITE_NOMEM ); + if( rc==SQLITE_NOMEM ){ + sqlite3_close(db); + db = 0; + }else if( rc!=SQLITE_OK ){ + db->magic = SQLITE_MAGIC_SICK; + } + *ppDb = db; +#ifdef SQLITE_ENABLE_SQLLOG + if( sqlite3GlobalConfig.xSqllog ){ + /* Opening a db handle. Fourth parameter is passed 0. */ + void *pArg = sqlite3GlobalConfig.pSqllogArg; + sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); + } +#endif + return sqlite3ApiExit(0, rc); +} + +/* +** Open a new database handle. +*/ +int sqlite3_open( + const char *zFilename, + sqlite3 **ppDb +){ + return openDatabase(zFilename, ppDb, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); +} +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +){ + return openDatabase(filename, ppDb, (unsigned int)flags, zVfs); +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Open a new database handle. +*/ +int sqlite3_open16( + const void *zFilename, + sqlite3 **ppDb +){ + char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ + sqlite3_value *pVal; + int rc; + + assert( zFilename ); + assert( ppDb ); + *ppDb = 0; +#ifndef SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if( rc ) return rc; +#endif + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); + zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); + if( zFilename8 ){ + rc = openDatabase(zFilename8, ppDb, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); + assert( *ppDb || rc==SQLITE_NOMEM ); + if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ + ENC(*ppDb) = SQLITE_UTF16NATIVE; + } + }else{ + rc = SQLITE_NOMEM; + } + sqlite3ValueFree(pVal); + + return sqlite3ApiExit(0, rc); +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Register a new collation sequence with the database handle db. +*/ +int sqlite3_create_collation( + sqlite3* db, + const char *zName, + int enc, + void* pCtx, + int(*xCompare)(void*,int,const void*,int,const void*) +){ + int rc; + sqlite3_mutex_enter(db->mutex); + assert( !db->mallocFailed ); + rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Register a new collation sequence with the database handle db. +*/ +int sqlite3_create_collation_v2( + sqlite3* db, + const char *zName, + int enc, + void* pCtx, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDel)(void*) +){ + int rc; + sqlite3_mutex_enter(db->mutex); + assert( !db->mallocFailed ); + rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Register a new collation sequence with the database handle db. +*/ +int sqlite3_create_collation16( + sqlite3* db, + const void *zName, + int enc, + void* pCtx, + int(*xCompare)(void*,int,const void*,int,const void*) +){ + int rc = SQLITE_OK; + char *zName8; + sqlite3_mutex_enter(db->mutex); + assert( !db->mallocFailed ); + zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); + if( zName8 ){ + rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); + sqlite3DbFree(db, zName8); + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Register a collation sequence factory callback with the database handle +** db. Replace any previously installed collation sequence factory. +*/ +int sqlite3_collation_needed( + sqlite3 *db, + void *pCollNeededArg, + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) +){ + sqlite3_mutex_enter(db->mutex); + db->xCollNeeded = xCollNeeded; + db->xCollNeeded16 = 0; + db->pCollNeededArg = pCollNeededArg; + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Register a collation sequence factory callback with the database handle +** db. Replace any previously installed collation sequence factory. +*/ +int sqlite3_collation_needed16( + sqlite3 *db, + void *pCollNeededArg, + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) +){ + sqlite3_mutex_enter(db->mutex); + db->xCollNeeded = 0; + db->xCollNeeded16 = xCollNeeded16; + db->pCollNeededArg = pCollNeededArg; + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} +#endif /* SQLITE_OMIT_UTF16 */ + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** This function is now an anachronism. It used to be used to recover from a +** malloc() failure, but SQLite now does this automatically. +*/ +int sqlite3_global_recover(void){ + return SQLITE_OK; +} +#endif + +/* +** Test to see whether or not the database connection is in autocommit +** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on +** by default. Autocommit is disabled by a BEGIN statement and reenabled +** by the next COMMIT or ROLLBACK. +*/ +int sqlite3_get_autocommit(sqlite3 *db){ + return db->autoCommit; +} + +/* +** The following routines are subtitutes for constants SQLITE_CORRUPT, +** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error +** constants. They server two purposes: +** +** 1. Serve as a convenient place to set a breakpoint in a debugger +** to detect when version error conditions occurs. +** +** 2. Invoke sqlite3_log() to provide the source code location where +** a low-level error is first detected. +*/ +int sqlite3CorruptError(int lineno){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_CORRUPT, + "database corruption at line %d of [%.10s]", + lineno, 20+sqlite3_sourceid()); + return SQLITE_CORRUPT; +} +int sqlite3MisuseError(int lineno){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_MISUSE, + "misuse at line %d of [%.10s]", + lineno, 20+sqlite3_sourceid()); + return SQLITE_MISUSE; +} +int sqlite3CantopenError(int lineno){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_CANTOPEN, + "cannot open file at line %d of [%.10s]", + lineno, 20+sqlite3_sourceid()); + return SQLITE_CANTOPEN; +} + + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** This is a convenience routine that makes sure that all thread-specific +** data for this thread has been deallocated. +** +** SQLite no longer uses thread-specific data so this routine is now a +** no-op. It is retained for historical compatibility. +*/ +void sqlite3_thread_cleanup(void){ +} +#endif + +/* +** Return meta information about a specific column of a database table. +** See comment in sqlite3.h (sqlite.h.in) for details. +*/ +#ifdef SQLITE_ENABLE_COLUMN_METADATA +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +){ + int rc; + char *zErrMsg = 0; + Table *pTab = 0; + Column *pCol = 0; + int iCol; + + char const *zDataType = 0; + char const *zCollSeq = 0; + int notnull = 0; + int primarykey = 0; + int autoinc = 0; + + /* Ensure the database schema has been loaded */ + sqlite3_mutex_enter(db->mutex); + sqlite3BtreeEnterAll(db); + rc = sqlite3Init(db, &zErrMsg); + if( SQLITE_OK!=rc ){ + goto error_out; + } + + /* Locate the table in question */ + pTab = sqlite3FindTable(db, zTableName, zDbName); + if( !pTab || pTab->pSelect ){ + pTab = 0; + goto error_out; + } + + /* Find the column for which info is requested */ + if( sqlite3IsRowid(zColumnName) ){ + iCol = pTab->iPKey; + if( iCol>=0 ){ + pCol = &pTab->aCol[iCol]; + } + }else{ + for(iCol=0; iColnCol; iCol++){ + pCol = &pTab->aCol[iCol]; + if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ + break; + } + } + if( iCol==pTab->nCol ){ + pTab = 0; + goto error_out; + } + } + + /* The following block stores the meta information that will be returned + ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey + ** and autoinc. At this point there are two possibilities: + ** + ** 1. The specified column name was rowid", "oid" or "_rowid_" + ** and there is no explicitly declared IPK column. + ** + ** 2. The table is not a view and the column name identified an + ** explicitly declared column. Copy meta information from *pCol. + */ + if( pCol ){ + zDataType = pCol->zType; + zCollSeq = pCol->zColl; + notnull = pCol->notNull!=0; + primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; + autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; + }else{ + zDataType = "INTEGER"; + primarykey = 1; + } + if( !zCollSeq ){ + zCollSeq = "BINARY"; + } + +error_out: + sqlite3BtreeLeaveAll(db); + + /* Whether the function call succeeded or failed, set the output parameters + ** to whatever their local counterparts contain. If an error did occur, + ** this has the effect of zeroing all output parameters. + */ + if( pzDataType ) *pzDataType = zDataType; + if( pzCollSeq ) *pzCollSeq = zCollSeq; + if( pNotNull ) *pNotNull = notnull; + if( pPrimaryKey ) *pPrimaryKey = primarykey; + if( pAutoinc ) *pAutoinc = autoinc; + + if( SQLITE_OK==rc && !pTab ){ + sqlite3DbFree(db, zErrMsg); + zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, + zColumnName); + rc = SQLITE_ERROR; + } + sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg); + sqlite3DbFree(db, zErrMsg); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} +#endif + +/* +** Sleep for a little while. Return the amount of time slept. +*/ +int sqlite3_sleep(int ms){ + sqlite3_vfs *pVfs; + int rc; + pVfs = sqlite3_vfs_find(0); + if( pVfs==0 ) return 0; + + /* This function works in milliseconds, but the underlying OsSleep() + ** API uses microseconds. Hence the 1000's. + */ + rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); + return rc; +} + +/* +** Enable or disable the extended result codes. +*/ +int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ + sqlite3_mutex_enter(db->mutex); + db->errMask = onoff ? 0xffffffff : 0xff; + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +/* +** Invoke the xFileControl method on a particular database. +*/ +int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ + int rc = SQLITE_ERROR; + Btree *pBtree; + + sqlite3_mutex_enter(db->mutex); + pBtree = sqlite3DbNameToBtree(db, zDbName); + if( pBtree ){ + Pager *pPager; + sqlite3_file *fd; + sqlite3BtreeEnter(pBtree); + pPager = sqlite3BtreePager(pBtree); + assert( pPager!=0 ); + fd = sqlite3PagerFile(pPager); + assert( fd!=0 ); + if( op==SQLITE_FCNTL_FILE_POINTER ){ + *(sqlite3_file**)pArg = fd; + rc = SQLITE_OK; + }else if( fd->pMethods ){ + rc = sqlite3OsFileControl(fd, op, pArg); + }else{ + rc = SQLITE_NOTFOUND; + } + sqlite3BtreeLeave(pBtree); + } + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Interface to the testing logic. +*/ +int sqlite3_test_control(int op, ...){ + int rc = 0; +#ifndef SQLITE_OMIT_BUILTIN_TEST + va_list ap; + va_start(ap, op); + switch( op ){ + + /* + ** Save the current state of the PRNG. + */ + case SQLITE_TESTCTRL_PRNG_SAVE: { + sqlite3PrngSaveState(); + break; + } + + /* + ** Restore the state of the PRNG to the last state saved using + ** PRNG_SAVE. If PRNG_SAVE has never before been called, then + ** this verb acts like PRNG_RESET. + */ + case SQLITE_TESTCTRL_PRNG_RESTORE: { + sqlite3PrngRestoreState(); + break; + } + + /* + ** Reset the PRNG back to its uninitialized state. The next call + ** to sqlite3_randomness() will reseed the PRNG using a single call + ** to the xRandomness method of the default VFS. + */ + case SQLITE_TESTCTRL_PRNG_RESET: { + sqlite3PrngResetState(); + break; + } + + /* + ** sqlite3_test_control(BITVEC_TEST, size, program) + ** + ** Run a test against a Bitvec object of size. The program argument + ** is an array of integers that defines the test. Return -1 on a + ** memory allocation error, 0 on success, or non-zero for an error. + ** See the sqlite3BitvecBuiltinTest() for additional information. + */ + case SQLITE_TESTCTRL_BITVEC_TEST: { + int sz = va_arg(ap, int); + int *aProg = va_arg(ap, int*); + rc = sqlite3BitvecBuiltinTest(sz, aProg); + break; + } + + /* + ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) + ** + ** Register hooks to call to indicate which malloc() failures + ** are benign. + */ + case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { + typedef void (*void_function)(void); + void_function xBenignBegin; + void_function xBenignEnd; + xBenignBegin = va_arg(ap, void_function); + xBenignEnd = va_arg(ap, void_function); + sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); + break; + } + + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) + ** + ** Set the PENDING byte to the value in the argument, if X>0. + ** Make no changes if X==0. Return the value of the pending byte + ** as it existing before this routine was called. + ** + ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in + ** an incompatible database file format. Changing the PENDING byte + ** while any database connection is open results in undefined and + ** dileterious behavior. + */ + case SQLITE_TESTCTRL_PENDING_BYTE: { + rc = PENDING_BYTE; +#ifndef SQLITE_OMIT_WSD + { + unsigned int newVal = va_arg(ap, unsigned int); + if( newVal ) sqlite3PendingByte = newVal; + } +#endif + break; + } + + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) + ** + ** This action provides a run-time test to see whether or not + ** assert() was enabled at compile-time. If X is true and assert() + ** is enabled, then the return value is true. If X is true and + ** assert() is disabled, then the return value is zero. If X is + ** false and assert() is enabled, then the assertion fires and the + ** process aborts. If X is false and assert() is disabled, then the + ** return value is zero. + */ + case SQLITE_TESTCTRL_ASSERT: { + volatile int x = 0; + assert( (x = va_arg(ap,int))!=0 ); + rc = x; + break; + } + + + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) + ** + ** This action provides a run-time test to see how the ALWAYS and + ** NEVER macros were defined at compile-time. + ** + ** The return value is ALWAYS(X). + ** + ** The recommended test is X==2. If the return value is 2, that means + ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the + ** default setting. If the return value is 1, then ALWAYS() is either + ** hard-coded to true or else it asserts if its argument is false. + ** The first behavior (hard-coded to true) is the case if + ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second + ** behavior (assert if the argument to ALWAYS() is false) is the case if + ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. + ** + ** The run-time test procedure might look something like this: + ** + ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ + ** // ALWAYS() and NEVER() are no-op pass-through macros + ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ + ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. + ** }else{ + ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. + ** } + */ + case SQLITE_TESTCTRL_ALWAYS: { + int x = va_arg(ap,int); + rc = ALWAYS(x); + break; + } + + /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) + ** + ** Set the nReserve size to N for the main database on the database + ** connection db. + */ + case SQLITE_TESTCTRL_RESERVE: { + sqlite3 *db = va_arg(ap, sqlite3*); + int x = va_arg(ap,int); + sqlite3_mutex_enter(db->mutex); + sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); + sqlite3_mutex_leave(db->mutex); + break; + } + + /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) + ** + ** Enable or disable various optimizations for testing purposes. The + ** argument N is a bitmask of optimizations to be disabled. For normal + ** operation N should be 0. The idea is that a test program (like the + ** SQL Logic Test or SLT test module) can run the same SQL multiple times + ** with various optimizations disabled to verify that the same answer + ** is obtained in every case. + */ + case SQLITE_TESTCTRL_OPTIMIZATIONS: { + sqlite3 *db = va_arg(ap, sqlite3*); + db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); + break; + } + +#ifdef SQLITE_N_KEYWORD + /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) + ** + ** If zWord is a keyword recognized by the parser, then return the + ** number of keywords. Or if zWord is not a keyword, return 0. + ** + ** This test feature is only available in the amalgamation since + ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite + ** is built using separate source files. + */ + case SQLITE_TESTCTRL_ISKEYWORD: { + const char *zWord = va_arg(ap, const char*); + int n = sqlite3Strlen30(zWord); + rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; + break; + } +#endif + + /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); + ** + ** Pass pFree into sqlite3ScratchFree(). + ** If sz>0 then allocate a scratch buffer into pNew. + */ + case SQLITE_TESTCTRL_SCRATCHMALLOC: { + void *pFree, **ppNew; + int sz; + sz = va_arg(ap, int); + ppNew = va_arg(ap, void**); + pFree = va_arg(ap, void*); + if( sz ) *ppNew = sqlite3ScratchMalloc(sz); + sqlite3ScratchFree(pFree); + break; + } + + /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); + ** + ** If parameter onoff is non-zero, configure the wrappers so that all + ** subsequent calls to localtime() and variants fail. If onoff is zero, + ** undo this setting. + */ + case SQLITE_TESTCTRL_LOCALTIME_FAULT: { + sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); + break; + } + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) + /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, + ** sqlite3_stmt*,const char**); + ** + ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds + ** a string that describes the optimized parse tree. This test-control + ** returns a pointer to that string. + */ + case SQLITE_TESTCTRL_EXPLAIN_STMT: { + sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*); + const char **pzRet = va_arg(ap, const char**); + *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt); + break; + } +#endif + + } + va_end(ap); +#endif /* SQLITE_OMIT_BUILTIN_TEST */ + return rc; +} + +/* +** This is a utility routine, useful to VFS implementations, that checks +** to see if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of the query parameter. +** +** The zFilename argument is the filename pointer passed into the xOpen() +** method of a VFS implementation. The zParam argument is the name of the +** query parameter we seek. This routine returns the value of the zParam +** parameter if it exists. If the parameter does not exist, this routine +** returns a NULL pointer. +*/ +const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ + if( zFilename==0 ) return 0; + zFilename += sqlite3Strlen30(zFilename) + 1; + while( zFilename[0] ){ + int x = strcmp(zFilename, zParam); + zFilename += sqlite3Strlen30(zFilename) + 1; + if( x==0 ) return zFilename; + zFilename += sqlite3Strlen30(zFilename) + 1; + } + return 0; +} + +/* +** Return a boolean value for a query parameter. +*/ +int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ + const char *z = sqlite3_uri_parameter(zFilename, zParam); + bDflt = bDflt!=0; + return z ? sqlite3GetBoolean(z, bDflt) : bDflt; +} + +/* +** Return a 64-bit integer value for a query parameter. +*/ +sqlite3_int64 sqlite3_uri_int64( + const char *zFilename, /* Filename as passed to xOpen */ + const char *zParam, /* URI parameter sought */ + sqlite3_int64 bDflt /* return if parameter is missing */ +){ + const char *z = sqlite3_uri_parameter(zFilename, zParam); + sqlite3_int64 v; + if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){ + bDflt = v; + } + return bDflt; +} + +/* +** Return the Btree pointer identified by zDbName. Return NULL if not found. +*/ +Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ + int i; + for(i=0; inDb; i++){ + if( db->aDb[i].pBt + && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0) + ){ + return db->aDb[i].pBt; + } + } + return 0; +} + +/* +** Return the filename of the database associated with a database +** connection. +*/ +const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ + Btree *pBt = sqlite3DbNameToBtree(db, zDbName); + return pBt ? sqlite3BtreeGetFilename(pBt) : 0; +} + +/* +** Return 1 if database is read-only or 0 if read/write. Return -1 if +** no such database exists. +*/ +int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ + Btree *pBt = sqlite3DbNameToBtree(db, zDbName); + return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1; +} diff --git a/components/external/SQLite-3.8.1/src/malloc.c b/components/external/SQLite-3.8.1/src/malloc.c new file mode 100644 index 0000000000000000000000000000000000000000..799f0485d4c905616c0afcb4fecc06c671a3dc12 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/malloc.c @@ -0,0 +1,783 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** Memory allocation functions used throughout sqlite. +*/ +#include "sqliteInt.h" +#include + +/* +** Attempt to release up to n bytes of non-essential memory currently +** held by SQLite. An example of non-essential memory is memory used to +** cache database pages that are not currently in use. +*/ +int sqlite3_release_memory(int n){ +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT + return sqlite3PcacheReleaseMemory(n); +#else + /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine + ** is a no-op returning zero if SQLite is not compiled with + ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */ + UNUSED_PARAMETER(n); + return 0; +#endif +} + +/* +** An instance of the following object records the location of +** each unused scratch buffer. +*/ +typedef struct ScratchFreeslot { + struct ScratchFreeslot *pNext; /* Next unused scratch buffer */ +} ScratchFreeslot; + +/* +** State information local to the memory allocation subsystem. +*/ +static SQLITE_WSD struct Mem0Global { + sqlite3_mutex *mutex; /* Mutex to serialize access */ + + /* + ** The alarm callback and its arguments. The mem0.mutex lock will + ** be held while the callback is running. Recursive calls into + ** the memory subsystem are allowed, but no new callbacks will be + ** issued. + */ + sqlite3_int64 alarmThreshold; + void (*alarmCallback)(void*, sqlite3_int64,int); + void *alarmArg; + + /* + ** Pointers to the end of sqlite3GlobalConfig.pScratch memory + ** (so that a range test can be used to determine if an allocation + ** being freed came from pScratch) and a pointer to the list of + ** unused scratch allocations. + */ + void *pScratchEnd; + ScratchFreeslot *pScratchFree; + u32 nScratchFree; + + /* + ** True if heap is nearly "full" where "full" is defined by the + ** sqlite3_soft_heap_limit() setting. + */ + int nearlyFull; +} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 }; + +#define mem0 GLOBAL(struct Mem0Global, mem0) + +/* +** This routine runs when the memory allocator sees that the +** total memory allocation is about to exceed the soft heap +** limit. +*/ +static void softHeapLimitEnforcer( + void *NotUsed, + sqlite3_int64 NotUsed2, + int allocSize +){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + sqlite3_release_memory(allocSize); +} + +/* +** Change the alarm callback +*/ +static int sqlite3MemoryAlarm( + void(*xCallback)(void *pArg, sqlite3_int64 used,int N), + void *pArg, + sqlite3_int64 iThreshold +){ + int nUsed; + sqlite3_mutex_enter(mem0.mutex); + mem0.alarmCallback = xCallback; + mem0.alarmArg = pArg; + mem0.alarmThreshold = iThreshold; + nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed); + sqlite3_mutex_leave(mem0.mutex); + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** Deprecated external interface. Internal/core SQLite code +** should call sqlite3MemoryAlarm. +*/ +int sqlite3_memory_alarm( + void(*xCallback)(void *pArg, sqlite3_int64 used,int N), + void *pArg, + sqlite3_int64 iThreshold +){ + return sqlite3MemoryAlarm(xCallback, pArg, iThreshold); +} +#endif + +/* +** Set the soft heap-size limit for the library. Passing a zero or +** negative value indicates no limit. +*/ +sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){ + sqlite3_int64 priorLimit; + sqlite3_int64 excess; +#ifndef SQLITE_OMIT_AUTOINIT + int rc = sqlite3_initialize(); + if( rc ) return -1; +#endif + sqlite3_mutex_enter(mem0.mutex); + priorLimit = mem0.alarmThreshold; + sqlite3_mutex_leave(mem0.mutex); + if( n<0 ) return priorLimit; + if( n>0 ){ + sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n); + }else{ + sqlite3MemoryAlarm(0, 0, 0); + } + excess = sqlite3_memory_used() - n; + if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff)); + return priorLimit; +} +void sqlite3_soft_heap_limit(int n){ + if( n<0 ) n = 0; + sqlite3_soft_heap_limit64(n); +} + +/* +** Initialize the memory allocation subsystem. +*/ +int sqlite3MallocInit(void){ + if( sqlite3GlobalConfig.m.xMalloc==0 ){ + sqlite3MemSetDefault(); + } + memset(&mem0, 0, sizeof(mem0)); + if( sqlite3GlobalConfig.bCoreMutex ){ + mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + } + if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100 + && sqlite3GlobalConfig.nScratch>0 ){ + int i, n, sz; + ScratchFreeslot *pSlot; + sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch); + sqlite3GlobalConfig.szScratch = sz; + pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch; + n = sqlite3GlobalConfig.nScratch; + mem0.pScratchFree = pSlot; + mem0.nScratchFree = n; + for(i=0; ipNext = (ScratchFreeslot*)(sz+(char*)pSlot); + pSlot = pSlot->pNext; + } + pSlot->pNext = 0; + mem0.pScratchEnd = (void*)&pSlot[1]; + }else{ + mem0.pScratchEnd = 0; + sqlite3GlobalConfig.pScratch = 0; + sqlite3GlobalConfig.szScratch = 0; + sqlite3GlobalConfig.nScratch = 0; + } + if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512 + || sqlite3GlobalConfig.nPage<1 ){ + sqlite3GlobalConfig.pPage = 0; + sqlite3GlobalConfig.szPage = 0; + sqlite3GlobalConfig.nPage = 0; + } + return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData); +} + +/* +** Return true if the heap is currently under memory pressure - in other +** words if the amount of heap used is close to the limit set by +** sqlite3_soft_heap_limit(). +*/ +int sqlite3HeapNearlyFull(void){ + return mem0.nearlyFull; +} + +/* +** Deinitialize the memory allocation subsystem. +*/ +void sqlite3MallocEnd(void){ + if( sqlite3GlobalConfig.m.xShutdown ){ + sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData); + } + memset(&mem0, 0, sizeof(mem0)); +} + +/* +** Return the amount of memory currently checked out. +*/ +sqlite3_int64 sqlite3_memory_used(void){ + int n, mx; + sqlite3_int64 res; + sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0); + res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */ + return res; +} + +/* +** Return the maximum amount of memory that has ever been +** checked out since either the beginning of this process +** or since the most recent reset. +*/ +sqlite3_int64 sqlite3_memory_highwater(int resetFlag){ + int n, mx; + sqlite3_int64 res; + sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag); + res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */ + return res; +} + +/* +** Trigger the alarm +*/ +static void sqlite3MallocAlarm(int nByte){ + void (*xCallback)(void*,sqlite3_int64,int); + sqlite3_int64 nowUsed; + void *pArg; + if( mem0.alarmCallback==0 ) return; + xCallback = mem0.alarmCallback; + nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + pArg = mem0.alarmArg; + mem0.alarmCallback = 0; + sqlite3_mutex_leave(mem0.mutex); + xCallback(pArg, nowUsed, nByte); + sqlite3_mutex_enter(mem0.mutex); + mem0.alarmCallback = xCallback; + mem0.alarmArg = pArg; +} + +/* +** Do a memory allocation with statistics and alarms. Assume the +** lock is already held. +*/ +static int mallocWithAlarm(int n, void **pp){ + int nFull; + void *p; + assert( sqlite3_mutex_held(mem0.mutex) ); + nFull = sqlite3GlobalConfig.m.xRoundup(n); + sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n); + if( mem0.alarmCallback!=0 ){ + int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + if( nUsed >= mem0.alarmThreshold - nFull ){ + mem0.nearlyFull = 1; + sqlite3MallocAlarm(nFull); + }else{ + mem0.nearlyFull = 0; + } + } + p = sqlite3GlobalConfig.m.xMalloc(nFull); +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT + if( p==0 && mem0.alarmCallback ){ + sqlite3MallocAlarm(nFull); + p = sqlite3GlobalConfig.m.xMalloc(nFull); + } +#endif + if( p ){ + nFull = sqlite3MallocSize(p); + sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull); + sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1); + } + *pp = p; + return nFull; +} + +/* +** Allocate memory. This routine is like sqlite3_malloc() except that it +** assumes the memory subsystem has already been initialized. +*/ +void *sqlite3Malloc(int n){ + void *p; + if( n<=0 /* IMP: R-65312-04917 */ + || n>=0x7fffff00 + ){ + /* A memory allocation of a number of bytes which is near the maximum + ** signed integer value might cause an integer overflow inside of the + ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving + ** 255 bytes of overhead. SQLite itself will never use anything near + ** this amount. The only way to reach the limit is with sqlite3_malloc() */ + p = 0; + }else if( sqlite3GlobalConfig.bMemstat ){ + sqlite3_mutex_enter(mem0.mutex); + mallocWithAlarm(n, &p); + sqlite3_mutex_leave(mem0.mutex); + }else{ + p = sqlite3GlobalConfig.m.xMalloc(n); + } + assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */ + return p; +} + +/* +** This version of the memory allocation is for use by the application. +** First make sure the memory subsystem is initialized, then do the +** allocation. +*/ +void *sqlite3_malloc(int n){ +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + return sqlite3Malloc(n); +} + +/* +** Each thread may only have a single outstanding allocation from +** xScratchMalloc(). We verify this constraint in the single-threaded +** case by setting scratchAllocOut to 1 when an allocation +** is outstanding clearing it when the allocation is freed. +*/ +#if SQLITE_THREADSAFE==0 && !defined(NDEBUG) +static int scratchAllocOut = 0; +#endif + + +/* +** Allocate memory that is to be used and released right away. +** This routine is similar to alloca() in that it is not intended +** for situations where the memory might be held long-term. This +** routine is intended to get memory to old large transient data +** structures that would not normally fit on the stack of an +** embedded processor. +*/ +void *sqlite3ScratchMalloc(int n){ + void *p; + assert( n>0 ); + + sqlite3_mutex_enter(mem0.mutex); + if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){ + p = mem0.pScratchFree; + mem0.pScratchFree = mem0.pScratchFree->pNext; + mem0.nScratchFree--; + sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1); + sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n); + sqlite3_mutex_leave(mem0.mutex); + }else{ + if( sqlite3GlobalConfig.bMemstat ){ + sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n); + n = mallocWithAlarm(n, &p); + if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n); + sqlite3_mutex_leave(mem0.mutex); + }else{ + sqlite3_mutex_leave(mem0.mutex); + p = sqlite3GlobalConfig.m.xMalloc(n); + } + sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH); + } + assert( sqlite3_mutex_notheld(mem0.mutex) ); + + +#if SQLITE_THREADSAFE==0 && !defined(NDEBUG) + /* Verify that no more than two scratch allocations per thread + ** are outstanding at one time. (This is only checked in the + ** single-threaded case since checking in the multi-threaded case + ** would be much more complicated.) */ + assert( scratchAllocOut<=1 ); + if( p ) scratchAllocOut++; +#endif + + return p; +} +void sqlite3ScratchFree(void *p){ + if( p ){ + +#if SQLITE_THREADSAFE==0 && !defined(NDEBUG) + /* Verify that no more than two scratch allocation per thread + ** is outstanding at one time. (This is only checked in the + ** single-threaded case since checking in the multi-threaded case + ** would be much more complicated.) */ + assert( scratchAllocOut>=1 && scratchAllocOut<=2 ); + scratchAllocOut--; +#endif + + if( p>=sqlite3GlobalConfig.pScratch && ppNext = mem0.pScratchFree; + mem0.pScratchFree = pSlot; + mem0.nScratchFree++; + assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch ); + sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1); + sqlite3_mutex_leave(mem0.mutex); + }else{ + /* Release memory back to the heap */ + assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) ); + assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) ); + sqlite3MemdebugSetType(p, MEMTYPE_HEAP); + if( sqlite3GlobalConfig.bMemstat ){ + int iSize = sqlite3MallocSize(p); + sqlite3_mutex_enter(mem0.mutex); + sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize); + sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize); + sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1); + sqlite3GlobalConfig.m.xFree(p); + sqlite3_mutex_leave(mem0.mutex); + }else{ + sqlite3GlobalConfig.m.xFree(p); + } + } + } +} + +/* +** TRUE if p is a lookaside memory allocation from db +*/ +#ifndef SQLITE_OMIT_LOOKASIDE +static int isLookaside(sqlite3 *db, void *p){ + return p && p>=db->lookaside.pStart && plookaside.pEnd; +} +#else +#define isLookaside(A,B) 0 +#endif + +/* +** Return the size of a memory allocation previously obtained from +** sqlite3Malloc() or sqlite3_malloc(). +*/ +int sqlite3MallocSize(void *p){ + assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); + assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) ); + return sqlite3GlobalConfig.m.xSize(p); +} +int sqlite3DbMallocSize(sqlite3 *db, void *p){ + assert( db==0 || sqlite3_mutex_held(db->mutex) ); + if( db && isLookaside(db, p) ){ + return db->lookaside.sz; + }else{ + assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) ); + assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) ); + assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); + return sqlite3GlobalConfig.m.xSize(p); + } +} + +/* +** Free memory previously obtained from sqlite3Malloc(). +*/ +void sqlite3_free(void *p){ + if( p==0 ) return; /* IMP: R-49053-54554 */ + assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) ); + assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); + if( sqlite3GlobalConfig.bMemstat ){ + sqlite3_mutex_enter(mem0.mutex); + sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p)); + sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1); + sqlite3GlobalConfig.m.xFree(p); + sqlite3_mutex_leave(mem0.mutex); + }else{ + sqlite3GlobalConfig.m.xFree(p); + } +} + +/* +** Free memory that might be associated with a particular database +** connection. +*/ +void sqlite3DbFree(sqlite3 *db, void *p){ + assert( db==0 || sqlite3_mutex_held(db->mutex) ); + if( p==0 ) return; + if( db ){ + if( db->pnBytesFreed ){ + *db->pnBytesFreed += sqlite3DbMallocSize(db, p); + return; + } + if( isLookaside(db, p) ){ + LookasideSlot *pBuf = (LookasideSlot*)p; +#if SQLITE_DEBUG + /* Trash all content in the buffer being freed */ + memset(p, 0xaa, db->lookaside.sz); +#endif + pBuf->pNext = db->lookaside.pFree; + db->lookaside.pFree = pBuf; + db->lookaside.nOut--; + return; + } + } + assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) ); + assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) ); + assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); + sqlite3MemdebugSetType(p, MEMTYPE_HEAP); + sqlite3_free(p); +} + +/* +** Change the size of an existing memory allocation +*/ +void *sqlite3Realloc(void *pOld, int nBytes){ + int nOld, nNew, nDiff; + void *pNew; + if( pOld==0 ){ + return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */ + } + if( nBytes<=0 ){ + sqlite3_free(pOld); /* IMP: R-31593-10574 */ + return 0; + } + if( nBytes>=0x7fffff00 ){ + /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ + return 0; + } + nOld = sqlite3MallocSize(pOld); + /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second + ** argument to xRealloc is always a value returned by a prior call to + ** xRoundup. */ + nNew = sqlite3GlobalConfig.m.xRoundup(nBytes); + if( nOld==nNew ){ + pNew = pOld; + }else if( sqlite3GlobalConfig.bMemstat ){ + sqlite3_mutex_enter(mem0.mutex); + sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes); + nDiff = nNew - nOld; + if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= + mem0.alarmThreshold-nDiff ){ + sqlite3MallocAlarm(nDiff); + } + assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) ); + assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) ); + pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + if( pNew==0 && mem0.alarmCallback ){ + sqlite3MallocAlarm(nBytes); + pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + } + if( pNew ){ + nNew = sqlite3MallocSize(pNew); + sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld); + } + sqlite3_mutex_leave(mem0.mutex); + }else{ + pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + } + assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */ + return pNew; +} + +/* +** The public interface to sqlite3Realloc. Make sure that the memory +** subsystem is initialized prior to invoking sqliteRealloc. +*/ +void *sqlite3_realloc(void *pOld, int n){ +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + return sqlite3Realloc(pOld, n); +} + + +/* +** Allocate and zero memory. +*/ +void *sqlite3MallocZero(int n){ + void *p = sqlite3Malloc(n); + if( p ){ + memset(p, 0, n); + } + return p; +} + +/* +** Allocate and zero memory. If the allocation fails, make +** the mallocFailed flag in the connection pointer. +*/ +void *sqlite3DbMallocZero(sqlite3 *db, int n){ + void *p = sqlite3DbMallocRaw(db, n); + if( p ){ + memset(p, 0, n); + } + return p; +} + +/* +** Allocate and zero memory. If the allocation fails, make +** the mallocFailed flag in the connection pointer. +** +** If db!=0 and db->mallocFailed is true (indicating a prior malloc +** failure on the same database connection) then always return 0. +** Hence for a particular database connection, once malloc starts +** failing, it fails consistently until mallocFailed is reset. +** This is an important assumption. There are many places in the +** code that do things like this: +** +** int *a = (int*)sqlite3DbMallocRaw(db, 100); +** int *b = (int*)sqlite3DbMallocRaw(db, 200); +** if( b ) a[10] = 9; +** +** In other words, if a subsequent malloc (ex: "b") worked, it is assumed +** that all prior mallocs (ex: "a") worked too. +*/ +void *sqlite3DbMallocRaw(sqlite3 *db, int n){ + void *p; + assert( db==0 || sqlite3_mutex_held(db->mutex) ); + assert( db==0 || db->pnBytesFreed==0 ); +#ifndef SQLITE_OMIT_LOOKASIDE + if( db ){ + LookasideSlot *pBuf; + if( db->mallocFailed ){ + return 0; + } + if( db->lookaside.bEnabled ){ + if( n>db->lookaside.sz ){ + db->lookaside.anStat[1]++; + }else if( (pBuf = db->lookaside.pFree)==0 ){ + db->lookaside.anStat[2]++; + }else{ + db->lookaside.pFree = pBuf->pNext; + db->lookaside.nOut++; + db->lookaside.anStat[0]++; + if( db->lookaside.nOut>db->lookaside.mxOut ){ + db->lookaside.mxOut = db->lookaside.nOut; + } + return (void*)pBuf; + } + } + } +#else + if( db && db->mallocFailed ){ + return 0; + } +#endif + p = sqlite3Malloc(n); + if( !p && db ){ + db->mallocFailed = 1; + } + sqlite3MemdebugSetType(p, MEMTYPE_DB | + ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); + return p; +} + +/* +** Resize the block of memory pointed to by p to n bytes. If the +** resize fails, set the mallocFailed flag in the connection object. +*/ +void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){ + void *pNew = 0; + assert( db!=0 ); + assert( sqlite3_mutex_held(db->mutex) ); + if( db->mallocFailed==0 ){ + if( p==0 ){ + return sqlite3DbMallocRaw(db, n); + } + if( isLookaside(db, p) ){ + if( n<=db->lookaside.sz ){ + return p; + } + pNew = sqlite3DbMallocRaw(db, n); + if( pNew ){ + memcpy(pNew, p, db->lookaside.sz); + sqlite3DbFree(db, p); + } + }else{ + assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) ); + assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) ); + sqlite3MemdebugSetType(p, MEMTYPE_HEAP); + pNew = sqlite3_realloc(p, n); + if( !pNew ){ + sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP); + db->mallocFailed = 1; + } + sqlite3MemdebugSetType(pNew, MEMTYPE_DB | + (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); + } + } + return pNew; +} + +/* +** Attempt to reallocate p. If the reallocation fails, then free p +** and set the mallocFailed flag in the database connection. +*/ +void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){ + void *pNew; + pNew = sqlite3DbRealloc(db, p, n); + if( !pNew ){ + sqlite3DbFree(db, p); + } + return pNew; +} + +/* +** Make a copy of a string in memory obtained from sqliteMalloc(). These +** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This +** is because when memory debugging is turned on, these two functions are +** called via macros that record the current file and line number in the +** ThreadData structure. +*/ +char *sqlite3DbStrDup(sqlite3 *db, const char *z){ + char *zNew; + size_t n; + if( z==0 ){ + return 0; + } + n = sqlite3Strlen30(z) + 1; + assert( (n&0x7fffffff)==n ); + zNew = sqlite3DbMallocRaw(db, (int)n); + if( zNew ){ + memcpy(zNew, z, n); + } + return zNew; +} +char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){ + char *zNew; + if( z==0 ){ + return 0; + } + assert( (n&0x7fffffff)==n ); + zNew = sqlite3DbMallocRaw(db, n+1); + if( zNew ){ + memcpy(zNew, z, n); + zNew[n] = 0; + } + return zNew; +} + +/* +** Create a string from the zFromat argument and the va_list that follows. +** Store the string in memory obtained from sqliteMalloc() and make *pz +** point to that string. +*/ +void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){ + va_list ap; + char *z; + + va_start(ap, zFormat); + z = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + sqlite3DbFree(db, *pz); + *pz = z; +} + + +/* +** This function must be called before exiting any API function (i.e. +** returning control to the user) that has called sqlite3_malloc or +** sqlite3_realloc. +** +** The returned value is normally a copy of the second argument to this +** function. However, if a malloc() failure has occurred since the previous +** invocation SQLITE_NOMEM is returned instead. +** +** If the first argument, db, is not NULL and a malloc() error has occurred, +** then the connection error-code (the value returned by sqlite3_errcode()) +** is set to SQLITE_NOMEM. +*/ +int sqlite3ApiExit(sqlite3* db, int rc){ + /* If the db handle is not NULL, then we must hold the connection handle + ** mutex here. Otherwise the read (and possible write) of db->mallocFailed + ** is unsafe, as is the call to sqlite3Error(). + */ + assert( !db || sqlite3_mutex_held(db->mutex) ); + if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){ + sqlite3Error(db, SQLITE_NOMEM, 0); + db->mallocFailed = 0; + rc = SQLITE_NOMEM; + } + return rc & (db ? db->errMask : 0xff); +} diff --git a/components/external/SQLite-3.8.1/src/mem0.c b/components/external/SQLite-3.8.1/src/mem0.c new file mode 100644 index 0000000000000000000000000000000000000000..0d0b6667d60a955a0696df6289b49178969343aa --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mem0.c @@ -0,0 +1,59 @@ +/* +** 2008 October 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains a no-op memory allocation drivers for use when +** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented +** here always fail. SQLite will not operate with these drivers. These +** are merely placeholders. Real drivers must be substituted using +** sqlite3_config() before SQLite will operate. +*/ +#include "sqliteInt.h" + +/* +** This version of the memory allocator is the default. It is +** used when no other memory allocator is specified using compile-time +** macros. +*/ +#ifdef SQLITE_ZERO_MALLOC + +/* +** No-op versions of all memory allocation routines +*/ +static void *sqlite3MemMalloc(int nByte){ return 0; } +static void sqlite3MemFree(void *pPrior){ return; } +static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; } +static int sqlite3MemSize(void *pPrior){ return 0; } +static int sqlite3MemRoundup(int n){ return n; } +static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; } +static void sqlite3MemShutdown(void *NotUsed){ return; } + +/* +** This routine is the only routine in this file with external linkage. +** +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +void sqlite3MemSetDefault(void){ + static const sqlite3_mem_methods defaultMethods = { + sqlite3MemMalloc, + sqlite3MemFree, + sqlite3MemRealloc, + sqlite3MemSize, + sqlite3MemRoundup, + sqlite3MemInit, + sqlite3MemShutdown, + 0 + }; + sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); +} + +#endif /* SQLITE_ZERO_MALLOC */ diff --git a/components/external/SQLite-3.8.1/src/mem1.c b/components/external/SQLite-3.8.1/src/mem1.c new file mode 100644 index 0000000000000000000000000000000000000000..29cbfe826ec4bce2d540d40d1c214d937b12cdec --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mem1.c @@ -0,0 +1,297 @@ +/* +** 2007 August 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains low-level memory allocation drivers for when +** SQLite will use the standard C-library malloc/realloc/free interface +** to obtain the memory it needs. +** +** This file contains implementations of the low-level memory allocation +** routines specified in the sqlite3_mem_methods object. The content of +** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The +** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the +** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The +** default configuration is to use memory allocation routines in this +** file. +** +** C-preprocessor macro summary: +** +** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if +** the malloc_usable_size() interface exists +** on the target platform. Or, this symbol +** can be set manually, if desired. +** If an equivalent interface exists by +** a different name, using a separate -D +** option to rename it. +** +** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone +** memory allocator. Set this symbol to enable +** building on older macs. +** +** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of +** _msize() on windows systems. This might +** be necessary when compiling for Delphi, +** for example. +*/ +#include "sqliteInt.h" + +/* +** This version of the memory allocator is the default. It is +** used when no other memory allocator is specified using compile-time +** macros. +*/ +#ifdef SQLITE_SYSTEM_MALLOC + +/* +** The MSVCRT has malloc_usable_size() but it is called _msize(). +** The use of _msize() is automatic, but can be disabled by compiling +** with -DSQLITE_WITHOUT_MSIZE +*/ +#if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE) +# define SQLITE_MALLOCSIZE _msize +#endif + +#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) + +/* +** Use the zone allocator available on apple products unless the +** SQLITE_WITHOUT_ZONEMALLOC symbol is defined. +*/ +#include +#include +#include +static malloc_zone_t* _sqliteZone_; +#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x)) +#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x)); +#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y)) +#define SQLITE_MALLOCSIZE(x) \ + (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x)) + +#elif defined(SQLITE_OS_RTTHREAD) +#include +/* +** Use standard C library malloc and free on non-Apple systems. +** Also used by rt-thread systems if SQLITE_WITHOUT_ZONEMALLOC is defined. +*/ +#define SQLITE_MALLOC(x) rt_malloc((rt_size_t)x) +#define SQLITE_FREE(x) rt_free(x) +#define SQLITE_REALLOC(x,y) rt_realloc((x),(rt_size_t)(y)) + +#if (!defined(SQLITE_WITHOUT_MSIZE)) \ + && (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)) +# error "not have malloc_usable_size()" +#endif +#ifdef HAVE_MALLOC_USABLE_SIZE +# undef SQLITE_MALLOCSIZE +#endif + +#else /* if not __APPLE__ */ + +/* +** Use standard C library malloc and free on non-Apple systems. +** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined. +*/ +#define SQLITE_MALLOC(x) malloc(x) +#define SQLITE_FREE(x) free(x) +#define SQLITE_REALLOC(x,y) realloc((x),(y)) + +#if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \ + || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)) +# include /* Needed for malloc_usable_size on linux */ +#endif +#ifdef HAVE_MALLOC_USABLE_SIZE +# ifndef SQLITE_MALLOCSIZE +# define SQLITE_MALLOCSIZE(x) malloc_usable_size(x) +# endif +#else +# undef SQLITE_MALLOCSIZE +#endif + +#endif /* __APPLE__ or not __APPLE__ */ + +/* +** Like malloc(), but remember the size of the allocation +** so that we can find it later using sqlite3MemSize(). +** +** For this low-level routine, we are guaranteed that nByte>0 because +** cases of nByte<=0 will be intercepted and dealt with by higher level +** routines. +*/ +static void *sqlite3MemMalloc(int nByte){ +#ifdef SQLITE_MALLOCSIZE + void *p = SQLITE_MALLOC( nByte ); + if( p==0 ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); + } + return p; +#else + sqlite3_int64 *p; + assert( nByte>0 ); + nByte = ROUND8(nByte); + p = SQLITE_MALLOC( nByte+8 ); + if( p ){ + p[0] = nByte; + p++; + }else{ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); + } + return (void *)p; +#endif +} + +/* +** Like free() but works for allocations obtained from sqlite3MemMalloc() +** or sqlite3MemRealloc(). +** +** For this low-level routine, we already know that pPrior!=0 since +** cases where pPrior==0 will have been intecepted and dealt with +** by higher-level routines. +*/ +static void sqlite3MemFree(void *pPrior){ +#ifdef SQLITE_MALLOCSIZE + SQLITE_FREE(pPrior); +#else + sqlite3_int64 *p = (sqlite3_int64*)pPrior; + assert( pPrior!=0 ); + p--; + SQLITE_FREE(p); +#endif +} + +/* +** Report the allocated size of a prior return from xMalloc() +** or xRealloc(). +*/ +static int sqlite3MemSize(void *pPrior){ +#ifdef SQLITE_MALLOCSIZE + return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0; +#else + sqlite3_int64 *p; + if( pPrior==0 ) return 0; + p = (sqlite3_int64*)pPrior; + p--; + return (int)p[0]; +#endif +} + +/* +** Like realloc(). Resize an allocation previously obtained from +** sqlite3MemMalloc(). +** +** For this low-level interface, we know that pPrior!=0. Cases where +** pPrior==0 while have been intercepted by higher-level routine and +** redirected to xMalloc. Similarly, we know that nByte>0 becauses +** cases where nByte<=0 will have been intercepted by higher-level +** routines and redirected to xFree. +*/ +static void *sqlite3MemRealloc(void *pPrior, int nByte){ +#ifdef SQLITE_MALLOCSIZE + void *p = SQLITE_REALLOC(pPrior, nByte); + if( p==0 ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, + "failed memory resize %u to %u bytes", + SQLITE_MALLOCSIZE(pPrior), nByte); + } + return p; +#else + sqlite3_int64 *p = (sqlite3_int64*)pPrior; + assert( pPrior!=0 && nByte>0 ); + assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */ + p--; + p = SQLITE_REALLOC(p, nByte+8 ); + if( p ){ + p[0] = nByte; + p++; + }else{ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, + "failed memory resize %u to %u bytes", + sqlite3MemSize(pPrior), nByte); + } + return (void*)p; +#endif +} + +/* +** Round up a request size to the next valid allocation size. +*/ +static int sqlite3MemRoundup(int n){ + return ROUND8(n); +} + +/* +** Initialize this module. +*/ +static int sqlite3MemInit(void *NotUsed){ +#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) + int cpuCount; + size_t len; + if( _sqliteZone_ ){ + return SQLITE_OK; + } + len = sizeof(cpuCount); + /* One usually wants to use hw.acctivecpu for MT decisions, but not here */ + sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0); + if( cpuCount>1 ){ + /* defer MT decisions to system malloc */ + _sqliteZone_ = malloc_default_zone(); + }else{ + /* only 1 core, use our own zone to contention over global locks, + ** e.g. we have our own dedicated locks */ + bool success; + malloc_zone_t* newzone = malloc_create_zone(4096, 0); + malloc_set_zone_name(newzone, "Sqlite_Heap"); + do{ + success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, + (void * volatile *)&_sqliteZone_); + }while(!_sqliteZone_); + if( !success ){ + /* somebody registered a zone first */ + malloc_destroy_zone(newzone); + } + } +#endif + UNUSED_PARAMETER(NotUsed); + return SQLITE_OK; +} + +/* +** Deinitialize this module. +*/ +static void sqlite3MemShutdown(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + return; +} + +/* +** This routine is the only routine in this file with external linkage. +** +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +void sqlite3MemSetDefault(void){ + static const sqlite3_mem_methods defaultMethods = { + sqlite3MemMalloc, + sqlite3MemFree, + sqlite3MemRealloc, + sqlite3MemSize, + sqlite3MemRoundup, + sqlite3MemInit, + sqlite3MemShutdown, + 0 + }; + sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); +} + +#endif /* SQLITE_SYSTEM_MALLOC */ diff --git a/components/external/SQLite-3.8.1/src/mem2.c b/components/external/SQLite-3.8.1/src/mem2.c new file mode 100644 index 0000000000000000000000000000000000000000..99ea42517e371cde1c09b007bb7fc647f3756dea --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mem2.c @@ -0,0 +1,528 @@ +/* +** 2007 August 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains low-level memory allocation drivers for when +** SQLite will use the standard C-library malloc/realloc/free interface +** to obtain the memory it needs while adding lots of additional debugging +** information to each allocation in order to help detect and fix memory +** leaks and memory usage errors. +** +** This file contains implementations of the low-level memory allocation +** routines specified in the sqlite3_mem_methods object. +*/ +#include "sqliteInt.h" + +/* +** This version of the memory allocator is used only if the +** SQLITE_MEMDEBUG macro is defined +*/ +#ifdef SQLITE_MEMDEBUG + +/* +** The backtrace functionality is only available with GLIBC +*/ +#ifdef __GLIBC__ + extern int backtrace(void**,int); + extern void backtrace_symbols_fd(void*const*,int,int); +#else +# define backtrace(A,B) 1 +# define backtrace_symbols_fd(A,B,C) +#endif +#include + +/* +** Each memory allocation looks like this: +** +** ------------------------------------------------------------------------ +** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard | +** ------------------------------------------------------------------------ +** +** The application code sees only a pointer to the allocation. We have +** to back up from the allocation pointer to find the MemBlockHdr. The +** MemBlockHdr tells us the size of the allocation and the number of +** backtrace pointers. There is also a guard word at the end of the +** MemBlockHdr. +*/ +struct MemBlockHdr { + i64 iSize; /* Size of this allocation */ + struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */ + char nBacktrace; /* Number of backtraces on this alloc */ + char nBacktraceSlots; /* Available backtrace slots */ + u8 nTitle; /* Bytes of title; includes '\0' */ + u8 eType; /* Allocation type code */ + int iForeGuard; /* Guard word for sanity */ +}; + +/* +** Guard words +*/ +#define FOREGUARD 0x80F5E153 +#define REARGUARD 0xE4676B53 + +/* +** Number of malloc size increments to track. +*/ +#define NCSIZE 1000 + +/* +** All of the static variables used by this module are collected +** into a single structure named "mem". This is to keep the +** static variables organized and to reduce namespace pollution +** when this module is combined with other in the amalgamation. +*/ +static struct { + + /* + ** Mutex to control access to the memory allocation subsystem. + */ + sqlite3_mutex *mutex; + + /* + ** Head and tail of a linked list of all outstanding allocations + */ + struct MemBlockHdr *pFirst; + struct MemBlockHdr *pLast; + + /* + ** The number of levels of backtrace to save in new allocations. + */ + int nBacktrace; + void (*xBacktrace)(int, int, void **); + + /* + ** Title text to insert in front of each block + */ + int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */ + char zTitle[100]; /* The title text */ + + /* + ** sqlite3MallocDisallow() increments the following counter. + ** sqlite3MallocAllow() decrements it. + */ + int disallow; /* Do not allow memory allocation */ + + /* + ** Gather statistics on the sizes of memory allocations. + ** nAlloc[i] is the number of allocation attempts of i*8 + ** bytes. i==NCSIZE is the number of allocation attempts for + ** sizes more than NCSIZE*8 bytes. + */ + int nAlloc[NCSIZE]; /* Total number of allocations */ + int nCurrent[NCSIZE]; /* Current number of allocations */ + int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */ + +} mem; + + +/* +** Adjust memory usage statistics +*/ +static void adjustStats(int iSize, int increment){ + int i = ROUND8(iSize)/8; + if( i>NCSIZE-1 ){ + i = NCSIZE - 1; + } + if( increment>0 ){ + mem.nAlloc[i]++; + mem.nCurrent[i]++; + if( mem.nCurrent[i]>mem.mxCurrent[i] ){ + mem.mxCurrent[i] = mem.nCurrent[i]; + } + }else{ + mem.nCurrent[i]--; + assert( mem.nCurrent[i]>=0 ); + } +} + +/* +** Given an allocation, find the MemBlockHdr for that allocation. +** +** This routine checks the guards at either end of the allocation and +** if they are incorrect it asserts. +*/ +static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){ + struct MemBlockHdr *p; + int *pInt; + u8 *pU8; + int nReserve; + + p = (struct MemBlockHdr*)pAllocation; + p--; + assert( p->iForeGuard==(int)FOREGUARD ); + nReserve = ROUND8(p->iSize); + pInt = (int*)pAllocation; + pU8 = (u8*)pAllocation; + assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD ); + /* This checks any of the "extra" bytes allocated due + ** to rounding up to an 8 byte boundary to ensure + ** they haven't been overwritten. + */ + while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 ); + return p; +} + +/* +** Return the number of bytes currently allocated at address p. +*/ +static int sqlite3MemSize(void *p){ + struct MemBlockHdr *pHdr; + if( !p ){ + return 0; + } + pHdr = sqlite3MemsysGetHeader(p); + return (int)pHdr->iSize; +} + +/* +** Initialize the memory allocation subsystem. +*/ +static int sqlite3MemInit(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + assert( (sizeof(struct MemBlockHdr)&7) == 0 ); + if( !sqlite3GlobalConfig.bMemstat ){ + /* If memory status is enabled, then the malloc.c wrapper will already + ** hold the STATIC_MEM mutex when the routines here are invoked. */ + mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + } + return SQLITE_OK; +} + +/* +** Deinitialize the memory allocation subsystem. +*/ +static void sqlite3MemShutdown(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + mem.mutex = 0; +} + +/* +** Round up a request size to the next valid allocation size. +*/ +static int sqlite3MemRoundup(int n){ + return ROUND8(n); +} + +/* +** Fill a buffer with pseudo-random bytes. This is used to preset +** the content of a new memory allocation to unpredictable values and +** to clear the content of a freed allocation to unpredictable values. +*/ +static void randomFill(char *pBuf, int nByte){ + unsigned int x, y, r; + x = SQLITE_PTR_TO_INT(pBuf); + y = nByte | 1; + while( nByte >= 4 ){ + x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); + y = y*1103515245 + 12345; + r = x ^ y; + *(int*)pBuf = r; + pBuf += 4; + nByte -= 4; + } + while( nByte-- > 0 ){ + x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); + y = y*1103515245 + 12345; + r = x ^ y; + *(pBuf++) = r & 0xff; + } +} + +/* +** Allocate nByte bytes of memory. +*/ +static void *sqlite3MemMalloc(int nByte){ + struct MemBlockHdr *pHdr; + void **pBt; + char *z; + int *pInt; + void *p = 0; + int totalSize; + int nReserve; + sqlite3_mutex_enter(mem.mutex); + assert( mem.disallow==0 ); + nReserve = ROUND8(nByte); + totalSize = nReserve + sizeof(*pHdr) + sizeof(int) + + mem.nBacktrace*sizeof(void*) + mem.nTitle; + p = malloc(totalSize); + if( p ){ + z = p; + pBt = (void**)&z[mem.nTitle]; + pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace]; + pHdr->pNext = 0; + pHdr->pPrev = mem.pLast; + if( mem.pLast ){ + mem.pLast->pNext = pHdr; + }else{ + mem.pFirst = pHdr; + } + mem.pLast = pHdr; + pHdr->iForeGuard = FOREGUARD; + pHdr->eType = MEMTYPE_HEAP; + pHdr->nBacktraceSlots = mem.nBacktrace; + pHdr->nTitle = mem.nTitle; + if( mem.nBacktrace ){ + void *aAddr[40]; + pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; + memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); + assert(pBt[0]); + if( mem.xBacktrace ){ + mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); + } + }else{ + pHdr->nBacktrace = 0; + } + if( mem.nTitle ){ + memcpy(z, mem.zTitle, mem.nTitle); + } + pHdr->iSize = nByte; + adjustStats(nByte, +1); + pInt = (int*)&pHdr[1]; + pInt[nReserve/sizeof(int)] = REARGUARD; + randomFill((char*)pInt, nByte); + memset(((char*)pInt)+nByte, 0x65, nReserve-nByte); + p = (void*)pInt; + } + sqlite3_mutex_leave(mem.mutex); + return p; +} + +/* +** Free memory. +*/ +static void sqlite3MemFree(void *pPrior){ + struct MemBlockHdr *pHdr; + void **pBt; + char *z; + assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 + || mem.mutex!=0 ); + pHdr = sqlite3MemsysGetHeader(pPrior); + pBt = (void**)pHdr; + pBt -= pHdr->nBacktraceSlots; + sqlite3_mutex_enter(mem.mutex); + if( pHdr->pPrev ){ + assert( pHdr->pPrev->pNext==pHdr ); + pHdr->pPrev->pNext = pHdr->pNext; + }else{ + assert( mem.pFirst==pHdr ); + mem.pFirst = pHdr->pNext; + } + if( pHdr->pNext ){ + assert( pHdr->pNext->pPrev==pHdr ); + pHdr->pNext->pPrev = pHdr->pPrev; + }else{ + assert( mem.pLast==pHdr ); + mem.pLast = pHdr->pPrev; + } + z = (char*)pBt; + z -= pHdr->nTitle; + adjustStats((int)pHdr->iSize, -1); + randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + + (int)pHdr->iSize + sizeof(int) + pHdr->nTitle); + free(z); + sqlite3_mutex_leave(mem.mutex); +} + +/* +** Change the size of an existing memory allocation. +** +** For this debugging implementation, we *always* make a copy of the +** allocation into a new place in memory. In this way, if the +** higher level code is using pointer to the old allocation, it is +** much more likely to break and we are much more liking to find +** the error. +*/ +static void *sqlite3MemRealloc(void *pPrior, int nByte){ + struct MemBlockHdr *pOldHdr; + void *pNew; + assert( mem.disallow==0 ); + assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */ + pOldHdr = sqlite3MemsysGetHeader(pPrior); + pNew = sqlite3MemMalloc(nByte); + if( pNew ){ + memcpy(pNew, pPrior, (int)(nByteiSize ? nByte : pOldHdr->iSize)); + if( nByte>pOldHdr->iSize ){ + randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize); + } + sqlite3MemFree(pPrior); + } + return pNew; +} + +/* +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +void sqlite3MemSetDefault(void){ + static const sqlite3_mem_methods defaultMethods = { + sqlite3MemMalloc, + sqlite3MemFree, + sqlite3MemRealloc, + sqlite3MemSize, + sqlite3MemRoundup, + sqlite3MemInit, + sqlite3MemShutdown, + 0 + }; + sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); +} + +/* +** Set the "type" of an allocation. +*/ +void sqlite3MemdebugSetType(void *p, u8 eType){ + if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ + struct MemBlockHdr *pHdr; + pHdr = sqlite3MemsysGetHeader(p); + assert( pHdr->iForeGuard==FOREGUARD ); + pHdr->eType = eType; + } +} + +/* +** Return TRUE if the mask of type in eType matches the type of the +** allocation p. Also return true if p==NULL. +** +** This routine is designed for use within an assert() statement, to +** verify the type of an allocation. For example: +** +** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) ); +*/ +int sqlite3MemdebugHasType(void *p, u8 eType){ + int rc = 1; + if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ + struct MemBlockHdr *pHdr; + pHdr = sqlite3MemsysGetHeader(p); + assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ + if( (pHdr->eType&eType)==0 ){ + rc = 0; + } + } + return rc; +} + +/* +** Return TRUE if the mask of type in eType matches no bits of the type of the +** allocation p. Also return true if p==NULL. +** +** This routine is designed for use within an assert() statement, to +** verify the type of an allocation. For example: +** +** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) ); +*/ +int sqlite3MemdebugNoType(void *p, u8 eType){ + int rc = 1; + if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ + struct MemBlockHdr *pHdr; + pHdr = sqlite3MemsysGetHeader(p); + assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ + if( (pHdr->eType&eType)!=0 ){ + rc = 0; + } + } + return rc; +} + +/* +** Set the number of backtrace levels kept for each allocation. +** A value of zero turns off backtracing. The number is always rounded +** up to a multiple of 2. +*/ +void sqlite3MemdebugBacktrace(int depth){ + if( depth<0 ){ depth = 0; } + if( depth>20 ){ depth = 20; } + depth = (depth+1)&0xfe; + mem.nBacktrace = depth; +} + +void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ + mem.xBacktrace = xBacktrace; +} + +/* +** Set the title string for subsequent allocations. +*/ +void sqlite3MemdebugSettitle(const char *zTitle){ + unsigned int n = sqlite3Strlen30(zTitle) + 1; + sqlite3_mutex_enter(mem.mutex); + if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; + memcpy(mem.zTitle, zTitle, n); + mem.zTitle[n] = 0; + mem.nTitle = ROUND8(n); + sqlite3_mutex_leave(mem.mutex); +} + +void sqlite3MemdebugSync(){ + struct MemBlockHdr *pHdr; + for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ + void **pBt = (void**)pHdr; + pBt -= pHdr->nBacktraceSlots; + mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]); + } +} + +/* +** Open the file indicated and write a log of all unfreed memory +** allocations into that log. +*/ +void sqlite3MemdebugDump(const char *zFilename){ + FILE *out; + struct MemBlockHdr *pHdr; + void **pBt; + int i; + out = fopen(zFilename, "w"); + if( out==0 ){ + fprintf(stderr, "** Unable to output memory debug output log: %s **\n", + zFilename); + return; + } + for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ + char *z = (char*)pHdr; + z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle; + fprintf(out, "**** %lld bytes at %p from %s ****\n", + pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???"); + if( pHdr->nBacktrace ){ + fflush(out); + pBt = (void**)pHdr; + pBt -= pHdr->nBacktraceSlots; + backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out)); + fprintf(out, "\n"); + } + } + fprintf(out, "COUNTS:\n"); + for(i=0; i=1 ); + size = mem3.aPool[i-1].u.hdr.size4x/4; + assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); + assert( size>=2 ); + if( size <= MX_SMALL ){ + memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]); + }else{ + hash = size % N_HASH; + memsys3UnlinkFromList(i, &mem3.aiHash[hash]); + } +} + +/* +** Link the chunk at mem3.aPool[i] so that is on the list rooted +** at *pRoot. +*/ +static void memsys3LinkIntoList(u32 i, u32 *pRoot){ + assert( sqlite3_mutex_held(mem3.mutex) ); + mem3.aPool[i].u.list.next = *pRoot; + mem3.aPool[i].u.list.prev = 0; + if( *pRoot ){ + mem3.aPool[*pRoot].u.list.prev = i; + } + *pRoot = i; +} + +/* +** Link the chunk at index i into either the appropriate +** small chunk list, or into the large chunk hash table. +*/ +static void memsys3Link(u32 i){ + u32 size, hash; + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( i>=1 ); + assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); + size = mem3.aPool[i-1].u.hdr.size4x/4; + assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); + assert( size>=2 ); + if( size <= MX_SMALL ){ + memsys3LinkIntoList(i, &mem3.aiSmall[size-2]); + }else{ + hash = size % N_HASH; + memsys3LinkIntoList(i, &mem3.aiHash[hash]); + } +} + +/* +** If the STATIC_MEM mutex is not already held, obtain it now. The mutex +** will already be held (obtained by code in malloc.c) if +** sqlite3GlobalConfig.bMemStat is true. +*/ +static void memsys3Enter(void){ + if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){ + mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + } + sqlite3_mutex_enter(mem3.mutex); +} +static void memsys3Leave(void){ + sqlite3_mutex_leave(mem3.mutex); +} + +/* +** Called when we are unable to satisfy an allocation of nBytes. +*/ +static void memsys3OutOfMemory(int nByte){ + if( !mem3.alarmBusy ){ + mem3.alarmBusy = 1; + assert( sqlite3_mutex_held(mem3.mutex) ); + sqlite3_mutex_leave(mem3.mutex); + sqlite3_release_memory(nByte); + sqlite3_mutex_enter(mem3.mutex); + mem3.alarmBusy = 0; + } +} + + +/* +** Chunk i is a free chunk that has been unlinked. Adjust its +** size parameters for check-out and return a pointer to the +** user portion of the chunk. +*/ +static void *memsys3Checkout(u32 i, u32 nBlock){ + u32 x; + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( i>=1 ); + assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ); + assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock ); + x = mem3.aPool[i-1].u.hdr.size4x; + mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2); + mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock; + mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2; + return &mem3.aPool[i]; +} + +/* +** Carve a piece off of the end of the mem3.iMaster free chunk. +** Return a pointer to the new allocation. Or, if the master chunk +** is not large enough, return 0. +*/ +static void *memsys3FromMaster(u32 nBlock){ + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( mem3.szMaster>=nBlock ); + if( nBlock>=mem3.szMaster-1 ){ + /* Use the entire master */ + void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster); + mem3.iMaster = 0; + mem3.szMaster = 0; + mem3.mnMaster = 0; + return p; + }else{ + /* Split the master block. Return the tail. */ + u32 newi, x; + newi = mem3.iMaster + mem3.szMaster - nBlock; + assert( newi > mem3.iMaster+1 ); + mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock; + mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2; + mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1; + mem3.szMaster -= nBlock; + mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster; + x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; + mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; + if( mem3.szMaster < mem3.mnMaster ){ + mem3.mnMaster = mem3.szMaster; + } + return (void*)&mem3.aPool[newi]; + } +} + +/* +** *pRoot is the head of a list of free chunks of the same size +** or same size hash. In other words, *pRoot is an entry in either +** mem3.aiSmall[] or mem3.aiHash[]. +** +** This routine examines all entries on the given list and tries +** to coalesce each entries with adjacent free chunks. +** +** If it sees a chunk that is larger than mem3.iMaster, it replaces +** the current mem3.iMaster with the new larger chunk. In order for +** this mem3.iMaster replacement to work, the master chunk must be +** linked into the hash tables. That is not the normal state of +** affairs, of course. The calling routine must link the master +** chunk before invoking this routine, then must unlink the (possibly +** changed) master chunk once this routine has finished. +*/ +static void memsys3Merge(u32 *pRoot){ + u32 iNext, prev, size, i, x; + + assert( sqlite3_mutex_held(mem3.mutex) ); + for(i=*pRoot; i>0; i=iNext){ + iNext = mem3.aPool[i].u.list.next; + size = mem3.aPool[i-1].u.hdr.size4x; + assert( (size&1)==0 ); + if( (size&2)==0 ){ + memsys3UnlinkFromList(i, pRoot); + assert( i > mem3.aPool[i-1].u.hdr.prevSize ); + prev = i - mem3.aPool[i-1].u.hdr.prevSize; + if( prev==iNext ){ + iNext = mem3.aPool[prev].u.list.next; + } + memsys3Unlink(prev); + size = i + size/4 - prev; + x = mem3.aPool[prev-1].u.hdr.size4x & 2; + mem3.aPool[prev-1].u.hdr.size4x = size*4 | x; + mem3.aPool[prev+size-1].u.hdr.prevSize = size; + memsys3Link(prev); + i = prev; + }else{ + size /= 4; + } + if( size>mem3.szMaster ){ + mem3.iMaster = i; + mem3.szMaster = size; + } + } +} + +/* +** Return a block of memory of at least nBytes in size. +** Return NULL if unable. +** +** This function assumes that the necessary mutexes, if any, are +** already held by the caller. Hence "Unsafe". +*/ +static void *memsys3MallocUnsafe(int nByte){ + u32 i; + u32 nBlock; + u32 toFree; + + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( sizeof(Mem3Block)==8 ); + if( nByte<=12 ){ + nBlock = 2; + }else{ + nBlock = (nByte + 11)/8; + } + assert( nBlock>=2 ); + + /* STEP 1: + ** Look for an entry of the correct size in either the small + ** chunk table or in the large chunk hash table. This is + ** successful most of the time (about 9 times out of 10). + */ + if( nBlock <= MX_SMALL ){ + i = mem3.aiSmall[nBlock-2]; + if( i>0 ){ + memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]); + return memsys3Checkout(i, nBlock); + } + }else{ + int hash = nBlock % N_HASH; + for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){ + if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){ + memsys3UnlinkFromList(i, &mem3.aiHash[hash]); + return memsys3Checkout(i, nBlock); + } + } + } + + /* STEP 2: + ** Try to satisfy the allocation by carving a piece off of the end + ** of the master chunk. This step usually works if step 1 fails. + */ + if( mem3.szMaster>=nBlock ){ + return memsys3FromMaster(nBlock); + } + + + /* STEP 3: + ** Loop through the entire memory pool. Coalesce adjacent free + ** chunks. Recompute the master chunk as the largest free chunk. + ** Then try again to satisfy the allocation by carving a piece off + ** of the end of the master chunk. This step happens very + ** rarely (we hope!) + */ + for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){ + memsys3OutOfMemory(toFree); + if( mem3.iMaster ){ + memsys3Link(mem3.iMaster); + mem3.iMaster = 0; + mem3.szMaster = 0; + } + for(i=0; i=nBlock ){ + return memsys3FromMaster(nBlock); + } + } + } + + /* If none of the above worked, then we fail. */ + return 0; +} + +/* +** Free an outstanding memory allocation. +** +** This function assumes that the necessary mutexes, if any, are +** already held by the caller. Hence "Unsafe". +*/ +static void memsys3FreeUnsafe(void *pOld){ + Mem3Block *p = (Mem3Block*)pOld; + int i; + u32 size, x; + assert( sqlite3_mutex_held(mem3.mutex) ); + assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] ); + i = p - mem3.aPool; + assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 ); + size = mem3.aPool[i-1].u.hdr.size4x/4; + assert( i+size<=mem3.nPool+1 ); + mem3.aPool[i-1].u.hdr.size4x &= ~1; + mem3.aPool[i+size-1].u.hdr.prevSize = size; + mem3.aPool[i+size-1].u.hdr.size4x &= ~2; + memsys3Link(i); + + /* Try to expand the master using the newly freed chunk */ + if( mem3.iMaster ){ + while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){ + size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize; + mem3.iMaster -= size; + mem3.szMaster += size; + memsys3Unlink(mem3.iMaster); + x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; + mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; + mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; + } + x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; + while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){ + memsys3Unlink(mem3.iMaster+mem3.szMaster); + mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4; + mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; + mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; + } + } +} + +/* +** Return the size of an outstanding allocation, in bytes. The +** size returned omits the 8-byte header overhead. This only +** works for chunks that are currently checked out. +*/ +static int memsys3Size(void *p){ + Mem3Block *pBlock; + if( p==0 ) return 0; + pBlock = (Mem3Block*)p; + assert( (pBlock[-1].u.hdr.size4x&1)!=0 ); + return (pBlock[-1].u.hdr.size4x&~3)*2 - 4; +} + +/* +** Round up a request size to the next valid allocation size. +*/ +static int memsys3Roundup(int n){ + if( n<=12 ){ + return 12; + }else{ + return ((n+11)&~7) - 4; + } +} + +/* +** Allocate nBytes of memory. +*/ +static void *memsys3Malloc(int nBytes){ + sqlite3_int64 *p; + assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */ + memsys3Enter(); + p = memsys3MallocUnsafe(nBytes); + memsys3Leave(); + return (void*)p; +} + +/* +** Free memory. +*/ +static void memsys3Free(void *pPrior){ + assert( pPrior ); + memsys3Enter(); + memsys3FreeUnsafe(pPrior); + memsys3Leave(); +} + +/* +** Change the size of an existing memory allocation +*/ +static void *memsys3Realloc(void *pPrior, int nBytes){ + int nOld; + void *p; + if( pPrior==0 ){ + return sqlite3_malloc(nBytes); + } + if( nBytes<=0 ){ + sqlite3_free(pPrior); + return 0; + } + nOld = memsys3Size(pPrior); + if( nBytes<=nOld && nBytes>=nOld-128 ){ + return pPrior; + } + memsys3Enter(); + p = memsys3MallocUnsafe(nBytes); + if( p ){ + if( nOld>1)!=(size&1) ){ + fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]); + assert( 0 ); + break; + } + if( size&1 ){ + fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8); + }else{ + fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8, + i==mem3.iMaster ? " **master**" : ""); + } + } + for(i=0; i0; j=mem3.aPool[j].u.list.next){ + fprintf(out, " %p(%d)", &mem3.aPool[j], + (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); + } + fprintf(out, "\n"); + } + for(i=0; i0; j=mem3.aPool[j].u.list.next){ + fprintf(out, " %p(%d)", &mem3.aPool[j], + (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); + } + fprintf(out, "\n"); + } + fprintf(out, "master=%d\n", mem3.iMaster); + fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8); + fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8); + sqlite3_mutex_leave(mem3.mutex); + if( out==stdout ){ + fflush(stdout); + }else{ + fclose(out); + } +#else + UNUSED_PARAMETER(zFilename); +#endif +} + +/* +** This routine is the only routine in this file with external +** linkage. +** +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. The +** arguments specify the block of memory to manage. +** +** This routine is only called by sqlite3_config(), and therefore +** is not required to be threadsafe (it is not). +*/ +const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){ + static const sqlite3_mem_methods mempoolMethods = { + memsys3Malloc, + memsys3Free, + memsys3Realloc, + memsys3Size, + memsys3Roundup, + memsys3Init, + memsys3Shutdown, + 0 + }; + return &mempoolMethods; +} + +#endif /* SQLITE_ENABLE_MEMSYS3 */ diff --git a/components/external/SQLite-3.8.1/src/mem5.c b/components/external/SQLite-3.8.1/src/mem5.c new file mode 100644 index 0000000000000000000000000000000000000000..5f99ebf43dd614d4974a560541bfdf598fb0642b --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mem5.c @@ -0,0 +1,581 @@ +/* +** 2007 October 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement a memory +** allocation subsystem for use by SQLite. +** +** This version of the memory allocation subsystem omits all +** use of malloc(). The application gives SQLite a block of memory +** before calling sqlite3_initialize() from which allocations +** are made and returned by the xMalloc() and xRealloc() +** implementations. Once sqlite3_initialize() has been called, +** the amount of memory available to SQLite is fixed and cannot +** be changed. +** +** This version of the memory allocation subsystem is included +** in the build only if SQLITE_ENABLE_MEMSYS5 is defined. +** +** This memory allocator uses the following algorithm: +** +** 1. All memory allocations sizes are rounded up to a power of 2. +** +** 2. If two adjacent free blocks are the halves of a larger block, +** then the two blocks are coalesed into the single larger block. +** +** 3. New memory is allocated from the first available free block. +** +** This algorithm is described in: J. M. Robson. "Bounds for Some Functions +** Concerning Dynamic Storage Allocation". Journal of the Association for +** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499. +** +** Let n be the size of the largest allocation divided by the minimum +** allocation size (after rounding all sizes up to a power of 2.) Let M +** be the maximum amount of memory ever outstanding at one time. Let +** N be the total amount of memory available for allocation. Robson +** proved that this memory allocator will never breakdown due to +** fragmentation as long as the following constraint holds: +** +** N >= M*(1 + log2(n)/2) - n + 1 +** +** The sqlite3_status() logic tracks the maximum values of n and M so +** that an application can, at any time, verify this constraint. +*/ +#include "sqliteInt.h" + +/* +** This version of the memory allocator is used only when +** SQLITE_ENABLE_MEMSYS5 is defined. +*/ +#ifdef SQLITE_ENABLE_MEMSYS5 + +/* +** A minimum allocation is an instance of the following structure. +** Larger allocations are an array of these structures where the +** size of the array is a power of 2. +** +** The size of this object must be a power of two. That fact is +** verified in memsys5Init(). +*/ +typedef struct Mem5Link Mem5Link; +struct Mem5Link { + int next; /* Index of next free chunk */ + int prev; /* Index of previous free chunk */ +}; + +/* +** Maximum size of any allocation is ((1<=0 && i=0 && iLogsize<=LOGMAX ); + assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); + + next = MEM5LINK(i)->next; + prev = MEM5LINK(i)->prev; + if( prev<0 ){ + mem5.aiFreelist[iLogsize] = next; + }else{ + MEM5LINK(prev)->next = next; + } + if( next>=0 ){ + MEM5LINK(next)->prev = prev; + } +} + +/* +** Link the chunk at mem5.aPool[i] so that is on the iLogsize +** free list. +*/ +static void memsys5Link(int i, int iLogsize){ + int x; + assert( sqlite3_mutex_held(mem5.mutex) ); + assert( i>=0 && i=0 && iLogsize<=LOGMAX ); + assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); + + x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize]; + MEM5LINK(i)->prev = -1; + if( x>=0 ){ + assert( xprev = i; + } + mem5.aiFreelist[iLogsize] = i; +} + +/* +** If the STATIC_MEM mutex is not already held, obtain it now. The mutex +** will already be held (obtained by code in malloc.c) if +** sqlite3GlobalConfig.bMemStat is true. +*/ +static void memsys5Enter(void){ + sqlite3_mutex_enter(mem5.mutex); +} +static void memsys5Leave(void){ + sqlite3_mutex_leave(mem5.mutex); +} + +/* +** Return the size of an outstanding allocation, in bytes. The +** size returned omits the 8-byte header overhead. This only +** works for chunks that are currently checked out. +*/ +static int memsys5Size(void *p){ + int iSize = 0; + if( p ){ + int i = ((u8 *)p-mem5.zPool)/mem5.szAtom; + assert( i>=0 && i=0 && iLogsize<=LOGMAX ); + i = iFirst = mem5.aiFreelist[iLogsize]; + assert( iFirst>=0 ); + while( i>0 ){ + if( inext; + } + memsys5Unlink(iFirst, iLogsize); + return iFirst; +} + +/* +** Return a block of memory of at least nBytes in size. +** Return NULL if unable. Return NULL if nBytes==0. +** +** The caller guarantees that nByte is positive. +** +** The caller has obtained a mutex prior to invoking this +** routine so there is never any chance that two or more +** threads can be in this routine at the same time. +*/ +static void *memsys5MallocUnsafe(int nByte){ + int i; /* Index of a mem5.aPool[] slot */ + int iBin; /* Index into mem5.aiFreelist[] */ + int iFullSz; /* Size of allocation rounded up to power of 2 */ + int iLogsize; /* Log2 of iFullSz/POW2_MIN */ + + /* nByte must be a positive */ + assert( nByte>0 ); + + /* Keep track of the maximum allocation request. Even unfulfilled + ** requests are counted */ + if( (u32)nByte>mem5.maxRequest ){ + mem5.maxRequest = nByte; + } + + /* Abort if the requested allocation size is larger than the largest + ** power of two that we can represent using 32-bit signed integers. + */ + if( nByte > 0x40000000 ){ + return 0; + } + + /* Round nByte up to the next valid power of two */ + for(iFullSz=mem5.szAtom, iLogsize=0; iFullSzLOGMAX ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte); + return 0; + } + i = memsys5UnlinkFirst(iBin); + while( iBin>iLogsize ){ + int newSize; + + iBin--; + newSize = 1 << iBin; + mem5.aCtrl[i+newSize] = CTRL_FREE | iBin; + memsys5Link(i+newSize, iBin); + } + mem5.aCtrl[i] = iLogsize; + + /* Update allocator performance statistics. */ + mem5.nAlloc++; + mem5.totalAlloc += iFullSz; + mem5.totalExcess += iFullSz - nByte; + mem5.currentCount++; + mem5.currentOut += iFullSz; + if( mem5.maxCount=0 && iBlock0 ); + assert( mem5.currentOut>=(size*mem5.szAtom) ); + mem5.currentCount--; + mem5.currentOut -= size*mem5.szAtom; + assert( mem5.currentOut>0 || mem5.currentCount==0 ); + assert( mem5.currentCount>0 || mem5.currentOut==0 ); + + mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize; + while( ALWAYS(iLogsize>iLogsize) & 1 ){ + iBuddy = iBlock - size; + }else{ + iBuddy = iBlock + size; + } + assert( iBuddy>=0 ); + if( (iBuddy+(1<mem5.nBlock ) break; + if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break; + memsys5Unlink(iBuddy, iLogsize); + iLogsize++; + if( iBuddy0 ){ + memsys5Enter(); + p = memsys5MallocUnsafe(nBytes); + memsys5Leave(); + } + return (void*)p; +} + +/* +** Free memory. +** +** The outer layer memory allocator prevents this routine from +** being called with pPrior==0. +*/ +static void memsys5Free(void *pPrior){ + assert( pPrior!=0 ); + memsys5Enter(); + memsys5FreeUnsafe(pPrior); + memsys5Leave(); +} + +/* +** Change the size of an existing memory allocation. +** +** The outer layer memory allocator prevents this routine from +** being called with pPrior==0. +** +** nBytes is always a value obtained from a prior call to +** memsys5Round(). Hence nBytes is always a non-negative power +** of two. If nBytes==0 that means that an oversize allocation +** (an allocation larger than 0x40000000) was requested and this +** routine should return 0 without freeing pPrior. +*/ +static void *memsys5Realloc(void *pPrior, int nBytes){ + int nOld; + void *p; + assert( pPrior!=0 ); + assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */ + assert( nBytes>=0 ); + if( nBytes==0 ){ + return 0; + } + nOld = memsys5Size(pPrior); + if( nBytes<=nOld ){ + return pPrior; + } + memsys5Enter(); + p = memsys5MallocUnsafe(nBytes); + if( p ){ + memcpy(p, pPrior, nOld); + memsys5FreeUnsafe(pPrior); + } + memsys5Leave(); + return p; +} + +/* +** Round up a request size to the next valid allocation size. If +** the allocation is too large to be handled by this allocation system, +** return 0. +** +** All allocations must be a power of two and must be expressed by a +** 32-bit signed integer. Hence the largest allocation is 0x40000000 +** or 1073741824 bytes. +*/ +static int memsys5Roundup(int n){ + int iFullSz; + if( n > 0x40000000 ) return 0; + for(iFullSz=mem5.szAtom; iFullSz 0 +** memsys5Log(2) -> 1 +** memsys5Log(4) -> 2 +** memsys5Log(5) -> 3 +** memsys5Log(8) -> 3 +** memsys5Log(9) -> 4 +*/ +static int memsys5Log(int iValue){ + int iLog; + for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<mem5.szAtom ){ + mem5.szAtom = mem5.szAtom << 1; + } + + mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8))); + mem5.zPool = zByte; + mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom]; + + for(ii=0; ii<=LOGMAX; ii++){ + mem5.aiFreelist[ii] = -1; + } + + iOffset = 0; + for(ii=LOGMAX; ii>=0; ii--){ + int nAlloc = (1<mem5.nBlock); + } + + /* If a mutex is required for normal operation, allocate one */ + if( sqlite3GlobalConfig.bMemstat==0 ){ + mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + } + + return SQLITE_OK; +} + +/* +** Deinitialize this module. +*/ +static void memsys5Shutdown(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + mem5.mutex = 0; + return; +} + +#ifdef SQLITE_TEST +/* +** Open the file indicated and write a log of all unfreed memory +** allocations into that log. +*/ +void sqlite3Memsys5Dump(const char *zFilename){ + FILE *out; + int i, j, n; + int nMinLog; + + if( zFilename==0 || zFilename[0]==0 ){ + out = stdout; + }else{ + out = fopen(zFilename, "w"); + if( out==0 ){ + fprintf(stderr, "** Unable to output memory debug output log: %s **\n", + zFilename); + return; + } + } + memsys5Enter(); + nMinLog = memsys5Log(mem5.szAtom); + for(i=0; i<=LOGMAX && i+nMinLog<32; i++){ + for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){} + fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n); + } + fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc); + fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc); + fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess); + fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut); + fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount); + fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut); + fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount); + fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest); + memsys5Leave(); + if( out==stdout ){ + fflush(stdout); + }else{ + fclose(out); + } +} +#endif + +/* +** This routine is the only routine in this file with external +** linkage. It returns a pointer to a static sqlite3_mem_methods +** struct populated with the memsys5 methods. +*/ +const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){ + static const sqlite3_mem_methods memsys5Methods = { + memsys5Malloc, + memsys5Free, + memsys5Realloc, + memsys5Size, + memsys5Roundup, + memsys5Init, + memsys5Shutdown, + 0 + }; + return &memsys5Methods; +} + +#endif /* SQLITE_ENABLE_MEMSYS5 */ diff --git a/components/external/SQLite-3.8.1/src/memjournal.c b/components/external/SQLite-3.8.1/src/memjournal.c new file mode 100644 index 0000000000000000000000000000000000000000..65ed378b38fd02cee09561f552d33c7ca5f9287a --- /dev/null +++ b/components/external/SQLite-3.8.1/src/memjournal.c @@ -0,0 +1,255 @@ +/* +** 2008 October 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code use to implement an in-memory rollback journal. +** The in-memory rollback journal is used to journal transactions for +** ":memory:" databases and when the journal_mode=MEMORY pragma is used. +*/ +#include "sqliteInt.h" + +/* Forward references to internal structures */ +typedef struct MemJournal MemJournal; +typedef struct FilePoint FilePoint; +typedef struct FileChunk FileChunk; + +/* Space to hold the rollback journal is allocated in increments of +** this many bytes. +** +** The size chosen is a little less than a power of two. That way, +** the FileChunk object will have a size that almost exactly fills +** a power-of-two allocation. This mimimizes wasted space in power-of-two +** memory allocators. +*/ +#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*))) + +/* +** The rollback journal is composed of a linked list of these structures. +*/ +struct FileChunk { + FileChunk *pNext; /* Next chunk in the journal */ + u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */ +}; + +/* +** An instance of this object serves as a cursor into the rollback journal. +** The cursor can be either for reading or writing. +*/ +struct FilePoint { + sqlite3_int64 iOffset; /* Offset from the beginning of the file */ + FileChunk *pChunk; /* Specific chunk into which cursor points */ +}; + +/* +** This subclass is a subclass of sqlite3_file. Each open memory-journal +** is an instance of this class. +*/ +struct MemJournal { + sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */ + FileChunk *pFirst; /* Head of in-memory chunk-list */ + FilePoint endpoint; /* Pointer to the end of the file */ + FilePoint readpoint; /* Pointer to the end of the last xRead() */ +}; + +/* +** Read data from the in-memory journal file. This is the implementation +** of the sqlite3_vfs.xRead method. +*/ +static int memjrnlRead( + sqlite3_file *pJfd, /* The journal file from which to read */ + void *zBuf, /* Put the results here */ + int iAmt, /* Number of bytes to read */ + sqlite_int64 iOfst /* Begin reading at this offset */ +){ + MemJournal *p = (MemJournal *)pJfd; + u8 *zOut = zBuf; + int nRead = iAmt; + int iChunkOffset; + FileChunk *pChunk; + + /* SQLite never tries to read past the end of a rollback journal file */ + assert( iOfst+iAmt<=p->endpoint.iOffset ); + + if( p->readpoint.iOffset!=iOfst || iOfst==0 ){ + sqlite3_int64 iOff = 0; + for(pChunk=p->pFirst; + ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst; + pChunk=pChunk->pNext + ){ + iOff += JOURNAL_CHUNKSIZE; + } + }else{ + pChunk = p->readpoint.pChunk; + } + + iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE); + do { + int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset; + int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset)); + memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy); + zOut += nCopy; + nRead -= iSpace; + iChunkOffset = 0; + } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 ); + p->readpoint.iOffset = iOfst+iAmt; + p->readpoint.pChunk = pChunk; + + return SQLITE_OK; +} + +/* +** Write data to the file. +*/ +static int memjrnlWrite( + sqlite3_file *pJfd, /* The journal file into which to write */ + const void *zBuf, /* Take data to be written from here */ + int iAmt, /* Number of bytes to write */ + sqlite_int64 iOfst /* Begin writing at this offset into the file */ +){ + MemJournal *p = (MemJournal *)pJfd; + int nWrite = iAmt; + u8 *zWrite = (u8 *)zBuf; + + /* An in-memory journal file should only ever be appended to. Random + ** access writes are not required by sqlite. + */ + assert( iOfst==p->endpoint.iOffset ); + UNUSED_PARAMETER(iOfst); + + while( nWrite>0 ){ + FileChunk *pChunk = p->endpoint.pChunk; + int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE); + int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset); + + if( iChunkOffset==0 ){ + /* New chunk is required to extend the file. */ + FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk)); + if( !pNew ){ + return SQLITE_IOERR_NOMEM; + } + pNew->pNext = 0; + if( pChunk ){ + assert( p->pFirst ); + pChunk->pNext = pNew; + }else{ + assert( !p->pFirst ); + p->pFirst = pNew; + } + p->endpoint.pChunk = pNew; + } + + memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace); + zWrite += iSpace; + nWrite -= iSpace; + p->endpoint.iOffset += iSpace; + } + + return SQLITE_OK; +} + +/* +** Truncate the file. +*/ +static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){ + MemJournal *p = (MemJournal *)pJfd; + FileChunk *pChunk; + assert(size==0); + UNUSED_PARAMETER(size); + pChunk = p->pFirst; + while( pChunk ){ + FileChunk *pTmp = pChunk; + pChunk = pChunk->pNext; + sqlite3_free(pTmp); + } + sqlite3MemJournalOpen(pJfd); + return SQLITE_OK; +} + +/* +** Close the file. +*/ +static int memjrnlClose(sqlite3_file *pJfd){ + memjrnlTruncate(pJfd, 0); + return SQLITE_OK; +} + + +/* +** Sync the file. +** +** Syncing an in-memory journal is a no-op. And, in fact, this routine +** is never called in a working implementation. This implementation +** exists purely as a contingency, in case some malfunction in some other +** part of SQLite causes Sync to be called by mistake. +*/ +static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return SQLITE_OK; +} + +/* +** Query the size of the file in bytes. +*/ +static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){ + MemJournal *p = (MemJournal *)pJfd; + *pSize = (sqlite_int64) p->endpoint.iOffset; + return SQLITE_OK; +} + +/* +** Table of methods for MemJournal sqlite3_file object. +*/ +static const struct sqlite3_io_methods MemJournalMethods = { + 1, /* iVersion */ + memjrnlClose, /* xClose */ + memjrnlRead, /* xRead */ + memjrnlWrite, /* xWrite */ + memjrnlTruncate, /* xTruncate */ + memjrnlSync, /* xSync */ + memjrnlFileSize, /* xFileSize */ + 0, /* xLock */ + 0, /* xUnlock */ + 0, /* xCheckReservedLock */ + 0, /* xFileControl */ + 0, /* xSectorSize */ + 0, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0, /* xShmUnmap */ + 0, /* xFetch */ + 0 /* xUnfetch */ +}; + +/* +** Open a journal file. +*/ +void sqlite3MemJournalOpen(sqlite3_file *pJfd){ + MemJournal *p = (MemJournal *)pJfd; + assert( EIGHT_BYTE_ALIGNMENT(p) ); + memset(p, 0, sqlite3MemJournalSize()); + p->pMethod = (sqlite3_io_methods*)&MemJournalMethods; +} + +/* +** Return true if the file-handle passed as an argument is +** an in-memory journal +*/ +int sqlite3IsMemJournal(sqlite3_file *pJfd){ + return pJfd->pMethods==&MemJournalMethods; +} + +/* +** Return the number of bytes required to store a MemJournal file descriptor. +*/ +int sqlite3MemJournalSize(void){ + return sizeof(MemJournal); +} diff --git a/components/external/SQLite-3.8.1/src/mutex.c b/components/external/SQLite-3.8.1/src/mutex.c new file mode 100644 index 0000000000000000000000000000000000000000..b567e7c27ef2041086afe0f69666e27bf5098a59 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mutex.c @@ -0,0 +1,153 @@ +/* +** 2007 August 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement mutexes. +** +** This file contains code that is common across all mutex implementations. +*/ +#include "sqliteInt.h" + +#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT) +/* +** For debugging purposes, record when the mutex subsystem is initialized +** and uninitialized so that we can assert() if there is an attempt to +** allocate a mutex while the system is uninitialized. +*/ +static SQLITE_WSD int mutexIsInit = 0; +#endif /* SQLITE_DEBUG */ + + +#ifndef SQLITE_MUTEX_OMIT +/* +** Initialize the mutex system. +*/ +int sqlite3MutexInit(void){ + int rc = SQLITE_OK; + if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){ + /* If the xMutexAlloc method has not been set, then the user did not + ** install a mutex implementation via sqlite3_config() prior to + ** sqlite3_initialize() being called. This block copies pointers to + ** the default implementation into the sqlite3GlobalConfig structure. + */ + sqlite3_mutex_methods const *pFrom; + sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex; + + if( sqlite3GlobalConfig.bCoreMutex ){ + pFrom = sqlite3DefaultMutex(); + }else{ + pFrom = sqlite3NoopMutex(); + } + memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc)); + memcpy(&pTo->xMutexFree, &pFrom->xMutexFree, + sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree)); + pTo->xMutexAlloc = pFrom->xMutexAlloc; + } + rc = sqlite3GlobalConfig.mutex.xMutexInit(); + +#ifdef SQLITE_DEBUG + GLOBAL(int, mutexIsInit) = 1; +#endif + + return rc; +} + +/* +** Shutdown the mutex system. This call frees resources allocated by +** sqlite3MutexInit(). +*/ +int sqlite3MutexEnd(void){ + int rc = SQLITE_OK; + if( sqlite3GlobalConfig.mutex.xMutexEnd ){ + rc = sqlite3GlobalConfig.mutex.xMutexEnd(); + } + +#ifdef SQLITE_DEBUG + GLOBAL(int, mutexIsInit) = 0; +#endif + + return rc; +} + +/* +** Retrieve a pointer to a static mutex or allocate a new dynamic one. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int id){ +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + return sqlite3GlobalConfig.mutex.xMutexAlloc(id); +} + +sqlite3_mutex *sqlite3MutexAlloc(int id){ + if( !sqlite3GlobalConfig.bCoreMutex ){ + return 0; + } + assert( GLOBAL(int, mutexIsInit) ); + return sqlite3GlobalConfig.mutex.xMutexAlloc(id); +} + +/* +** Free a dynamic mutex. +*/ +void sqlite3_mutex_free(sqlite3_mutex *p){ + if( p ){ + sqlite3GlobalConfig.mutex.xMutexFree(p); + } +} + +/* +** Obtain the mutex p. If some other thread already has the mutex, block +** until it can be obtained. +*/ +void sqlite3_mutex_enter(sqlite3_mutex *p){ + if( p ){ + sqlite3GlobalConfig.mutex.xMutexEnter(p); + } +} + +/* +** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another +** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY. +*/ +int sqlite3_mutex_try(sqlite3_mutex *p){ + int rc = SQLITE_OK; + if( p ){ + return sqlite3GlobalConfig.mutex.xMutexTry(p); + } + return rc; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was previously +** entered by the same thread. The behavior is undefined if the mutex +** is not currently entered. If a NULL pointer is passed as an argument +** this function is a no-op. +*/ +void sqlite3_mutex_leave(sqlite3_mutex *p){ + if( p ){ + sqlite3GlobalConfig.mutex.xMutexLeave(p); + } +} + +#ifndef NDEBUG +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use inside assert() statements. +*/ +int sqlite3_mutex_held(sqlite3_mutex *p){ + return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p); +} +int sqlite3_mutex_notheld(sqlite3_mutex *p){ + return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p); +} +#endif + +#endif /* !defined(SQLITE_MUTEX_OMIT) */ diff --git a/components/external/SQLite-3.8.1/src/mutex.h b/components/external/SQLite-3.8.1/src/mutex.h new file mode 100644 index 0000000000000000000000000000000000000000..d472510dd8d6bc9a06b69329d6ec4cf82e895e11 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mutex.h @@ -0,0 +1,74 @@ +/* +** 2007 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the common header for all mutex implementations. +** The sqliteInt.h header #includes this file so that it is available +** to all source files. We break it out in an effort to keep the code +** better organized. +** +** NOTE: source files should *not* #include this header file directly. +** Source files should #include the sqliteInt.h file and let that file +** include this one indirectly. +*/ + + +/* +** Figure out what version of the code to use. The choices are +** +** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The +** mutexes implemention cannot be overridden +** at start-time. +** +** SQLITE_MUTEX_NOOP For single-threaded applications. No +** mutual exclusion is provided. But this +** implementation can be overridden at +** start-time. +** +** SQLITE_MUTEX_RTTHREAD For multi-threaded applications on rt-thread. +** +** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. +** +** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. +*/ +#if !SQLITE_THREADSAFE +# define SQLITE_MUTEX_OMIT +#endif +#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) +# if SQLITE_OS_UNIX +# define SQLITE_MUTEX_PTHREADS +# elif SQLITE_OS_WIN +# define SQLITE_MUTEX_W32 +# elif SQLITE_OS_RTTHREAD +# define SQLITE_MUTEX_RTTHREAD +# else +# define SQLITE_MUTEX_NOOP +# endif +#endif + +#ifdef SQLITE_MUTEX_OMIT +/* +** If this is a no-op implementation, implement everything as macros. +*/ +#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) +#define sqlite3_mutex_free(X) +#define sqlite3_mutex_enter(X) +#define sqlite3_mutex_try(X) SQLITE_OK +#define sqlite3_mutex_leave(X) +#define sqlite3_mutex_held(X) ((void)(X),1) +#define sqlite3_mutex_notheld(X) ((void)(X),1) +#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) +#define sqlite3MutexInit() SQLITE_OK +#define sqlite3MutexEnd() +#define MUTEX_LOGIC(X) +#else +#define MUTEX_LOGIC(X) X +#endif /* defined(SQLITE_MUTEX_OMIT) */ diff --git a/components/external/SQLite-3.8.1/src/mutex_noop.c b/components/external/SQLite-3.8.1/src/mutex_noop.c new file mode 100644 index 0000000000000000000000000000000000000000..456e82a25e271b0614e7f4f83c228553b7fa0158 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mutex_noop.c @@ -0,0 +1,206 @@ +/* +** 2008 October 07 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement mutexes. +** +** This implementation in this file does not provide any mutual +** exclusion and is thus suitable for use only in applications +** that use SQLite in a single thread. The routines defined +** here are place-holders. Applications can substitute working +** mutex routines at start-time using the +** +** sqlite3_config(SQLITE_CONFIG_MUTEX,...) +** +** interface. +** +** If compiled with SQLITE_DEBUG, then additional logic is inserted +** that does error checking on mutexes to make sure they are being +** called correctly. +*/ +#include "sqliteInt.h" + +#ifndef SQLITE_MUTEX_OMIT + +#ifndef SQLITE_DEBUG +/* +** Stub routines for all mutex methods. +** +** This routines provide no mutual exclusion or error checking. +*/ +static int noopMutexInit(void){ return SQLITE_OK; } +static int noopMutexEnd(void){ return SQLITE_OK; } +static sqlite3_mutex *noopMutexAlloc(int id){ + UNUSED_PARAMETER(id); + return (sqlite3_mutex*)8; +} +static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } +static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } +static int noopMutexTry(sqlite3_mutex *p){ + UNUSED_PARAMETER(p); + return SQLITE_OK; +} +static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } + +sqlite3_mutex_methods const *sqlite3NoopMutex(void){ + static const sqlite3_mutex_methods sMutex = { + noopMutexInit, + noopMutexEnd, + noopMutexAlloc, + noopMutexFree, + noopMutexEnter, + noopMutexTry, + noopMutexLeave, + + 0, + 0, + }; + + return &sMutex; +} +#endif /* !SQLITE_DEBUG */ + +#ifdef SQLITE_DEBUG +/* +** In this implementation, error checking is provided for testing +** and debugging purposes. The mutexes still do not provide any +** mutual exclusion. +*/ + +/* +** The mutex object +*/ +typedef struct sqlite3_debug_mutex { + int id; /* The mutex type */ + int cnt; /* Number of entries without a matching leave */ +} sqlite3_debug_mutex; + +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use inside assert() statements. +*/ +static int debugMutexHeld(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + return p==0 || p->cnt>0; +} +static int debugMutexNotheld(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + return p==0 || p->cnt==0; +} + +/* +** Initialize and deinitialize the mutex subsystem. +*/ +static int debugMutexInit(void){ return SQLITE_OK; } +static int debugMutexEnd(void){ return SQLITE_OK; } + +/* +** The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. If it returns NULL +** that means that a mutex could not be allocated. +*/ +static sqlite3_mutex *debugMutexAlloc(int id){ + static sqlite3_debug_mutex aStatic[6]; + sqlite3_debug_mutex *pNew = 0; + switch( id ){ + case SQLITE_MUTEX_FAST: + case SQLITE_MUTEX_RECURSIVE: { + pNew = sqlite3Malloc(sizeof(*pNew)); + if( pNew ){ + pNew->id = id; + pNew->cnt = 0; + } + break; + } + default: { + assert( id-2 >= 0 ); + assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) ); + pNew = &aStatic[id-2]; + pNew->id = id; + break; + } + } + return (sqlite3_mutex*)pNew; +} + +/* +** This routine deallocates a previously allocated mutex. +*/ +static void debugMutexFree(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + assert( p->cnt==0 ); + assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ); + sqlite3_free(p); +} + +/* +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can +** be entered multiple times by the same thread. In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. If the same thread tries to enter any other kind of mutex +** more than once, the behavior is undefined. +*/ +static void debugMutexEnter(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); + p->cnt++; +} +static int debugMutexTry(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); + p->cnt++; + return SQLITE_OK; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. The behavior +** is undefined if the mutex is not currently entered or +** is not currently allocated. SQLite will never do either. +*/ +static void debugMutexLeave(sqlite3_mutex *pX){ + sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; + assert( debugMutexHeld(pX) ); + p->cnt--; + assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); +} + +sqlite3_mutex_methods const *sqlite3NoopMutex(void){ + static const sqlite3_mutex_methods sMutex = { + debugMutexInit, + debugMutexEnd, + debugMutexAlloc, + debugMutexFree, + debugMutexEnter, + debugMutexTry, + debugMutexLeave, + + debugMutexHeld, + debugMutexNotheld + }; + + return &sMutex; +} +#endif /* SQLITE_DEBUG */ + +/* +** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation +** is used regardless of the run-time threadsafety setting. +*/ +#ifdef SQLITE_MUTEX_NOOP +sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ + return sqlite3NoopMutex(); +} +#endif /* defined(SQLITE_MUTEX_NOOP) */ +#endif /* !defined(SQLITE_MUTEX_OMIT) */ diff --git a/components/external/SQLite-3.8.1/src/mutex_rtthread.c b/components/external/SQLite-3.8.1/src/mutex_rtthread.c new file mode 100644 index 0000000000000000000000000000000000000000..a7534a8102a9d22e63013985272ca0c43cb34d4b --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mutex_rtthread.c @@ -0,0 +1,344 @@ +/* +** 2007 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement mutexes for rtthread +*/ +#include "sqliteInt.h" + +/* +** The code in this file is only used if we are compiling threadsafe +** under rt-thread with rt_mutex. +** +** Note that this implementation requires a version of rt-thread that +** supports recursive mutexes. +*/ +#ifdef SQLITE_MUTEX_RTTHREAD + +#include + +/* +** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields +** are necessary under two condidtions: (1) Debug builds and (2) using +** home-grown mutexes. Encapsulate these conditions into a single #define. +*/ +#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX) +# define SQLITE_MUTEX_NREF 1 +#else +# define SQLITE_MUTEX_NREF 0 +#endif + +/* +** Each recursive mutex is an instance of the following structure. +*/ +struct sqlite3_mutex { + struct rt_mutex mutex; /* Mutex controlling the lock */ +#if SQLITE_MUTEX_NREF + int id; /* Mutex type */ + volatile int nRef; /* Number of entrances */ + volatile rt_thread_t owner; /* Thread that is within this mutex */ + int trace; /* True to trace changes */ +#endif +}; +#define RTT_MUTEX_INITIALIZER { 0 } +#if SQLITE_MUTEX_NREF +#define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER, 0, 0, (rt_thread_t)0, 0 } +#else +#define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER } +#endif + +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use only inside assert() statements. On some platforms, +** there might be race conditions that can cause these routines to +** deliver incorrect results. In particular, if rtthread_equal() is +** not an atomic operation, then these routines might delivery +** incorrect results. On most platforms, rtthread_equal() is a +** comparison of two integers and is therefore atomic. But we are +** told that HPUX is not such a platform. If so, then these routines +** will not always work correctly on HPUX. +** +** On those platforms where rtthread_equal() is not atomic, SQLite +** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to +** make sure no assert() statements are evaluated and hence these +** routines are never called. +*/ +#if !defined(NDEBUG) || defined(SQLITE_DEBUG) +static int rtthreadMutexHeld(sqlite3_mutex *p){ + return (p->nRef != 0 && p->owner == rt_thread_self()); +} +static int rtthreadMutexNotheld(sqlite3_mutex *p){ + return (p->nRef == 0 || p->owner != rt_thread_self()); +} +#endif + +/* +** Initialize and deinitialize the mutex subsystem. +*/ +static int rtthreadMutexInit(void){ return SQLITE_OK; } +static int rtthreadMutexEnd(void){ return SQLITE_OK; } + +/* +** The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. If it returns NULL +** that means that a mutex could not be allocated. SQLite +** will unwind its stack and return an error. The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_PMEM +**
+** +** The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. But SQLite will only request a recursive mutex in +** cases where it really needs one. If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +*/ +static sqlite3_mutex* rtthreadMutexAlloc(int iType){ + static sqlite3_mutex staticMutexes[] = { + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER + }; + sqlite3_mutex *p; + switch( iType ){ + case SQLITE_MUTEX_RECURSIVE: { + p = sqlite3MallocZero( sizeof(*p) ); + if( p ){ + /* Use a recursive mutex if it is available */ + rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO); +#if SQLITE_MUTEX_NREF + p->id = iType; +#endif + } + break; + } + case SQLITE_MUTEX_FAST: { + p = sqlite3MallocZero( sizeof(*p) ); + if( p ){ +#if SQLITE_MUTEX_NREF + p->id = iType; +#endif + rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO); + } + break; + } + default: { + assert( iType-2 >= 0 ); + assert( iType-2 < ArraySize(staticMutexes) ); + p = &staticMutexes[iType-2]; +#if SQLITE_MUTEX_NREF + p->id = iType; +#endif + rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO); + break; + } + } + return p; +} + + +/* +** This routine deallocates a previously +** allocated mutex. SQLite is careful to deallocate every +** mutex that it allocates. +*/ +static void rtthreadMutexFree(sqlite3_mutex *p){ + assert( p->nRef==0 ); + assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ); + rt_mutex_detach(&p->mutex); + sqlite3_free(p); +} + +/* +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can +** be entered multiple times by the same thread. In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. If the same thread tries to enter any other kind of mutex +** more than once, the behavior is undefined. +*/ +static void rtthreadMutexEnter(sqlite3_mutex *p){ + assert( p->id==SQLITE_MUTEX_RECURSIVE || rtthreadMutexNotheld(p) ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, then we have to grow + ** our own. This implementation assumes that rtthread_equal() + ** is atomic - that it cannot be deceived into thinking self + ** and p->owner are equal if p->owner changes between two values + ** that are not equal to self while the comparison is taking place. + ** This implementation also assumes a coherent cache - that + ** separate processes cannot read different values from the same + ** address at the same time. If either of these two conditions + ** are not met, then the mutexes will fail and problems will result. + */ + { + rt_thread_t self = rt_thread_self(); + if( p->nRef>0 && (p->owner == self) ){ + p->nRef++; + }else{ + rt_mutex_take(&p->mutex, RT_WAITING_FOREVER); + assert( p->nRef==0 ); + p->owner = self; + p->nRef = 1; + } + } +#else + /* Use the built-in recursive mutexes if they are available. + */ + rt_mutex_take(&p->mutex, RT_WAITING_FOREVER); +#if SQLITE_MUTEX_NREF + assert( p->nRef>0 || p->owner==0 ); + p->owner = rt_thread_self(); + p->nRef++; +#endif +#endif + +#ifdef SQLITE_DEBUG + if( p->trace ){ + rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif +} +static int rtthreadMutexTry(sqlite3_mutex *p){ + int rc; + assert( p->id==SQLITE_MUTEX_RECURSIVE || rtthreadMutexNotheld(p) ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, then we have to grow + ** our own. This implementation assumes that rtthread_equal() + ** is atomic - that it cannot be deceived into thinking self + ** and p->owner are equal if p->owner changes between two values + ** that are not equal to self while the comparison is taking place. + ** This implementation also assumes a coherent cache - that + ** separate processes cannot read different values from the same + ** address at the same time. If either of these two conditions + ** are not met, then the mutexes will fail and problems will result. + */ + { + rt_thread_t self = rt_thread_self(); + if( p->nRef>0 && (p->owner == self) ){ + p->nRef++; + rc = SQLITE_OK; + }else if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){ + assert( p->nRef==0 ); + p->owner = self; + p->nRef = 1; + rc = SQLITE_OK; + }else{ + rc = SQLITE_BUSY; + } + } +#else + /* Use the built-in recursive mutexes if they are available. + */ + if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){ +#if SQLITE_MUTEX_NREF + p->owner = rt_thread_self(); + p->nRef++; +#endif + rc = SQLITE_OK; + }else{ + rc = SQLITE_BUSY; + } +#endif + +#ifdef SQLITE_DEBUG + if( rc==SQLITE_OK && p->trace ){ + rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif + return rc; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. The behavior +** is undefined if the mutex is not currently entered or +** is not currently allocated. SQLite will never do either. +*/ +static void rtthreadMutexLeave(sqlite3_mutex *p){ + assert( rtthreadMutexHeld(p) ); +#if SQLITE_MUTEX_NREF + p->nRef--; + if( p->nRef==0 ) p->owner = 0; +#endif + assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + if( p->nRef==0 ){ + rt_mutex_release(&p->mutex); + } +#else + rt_mutex_release(&p->mutex); +#endif + +#ifdef SQLITE_DEBUG + if( p->trace ){ + rt_kprintf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif +} + +sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ + static const sqlite3_mutex_methods sMutex = { + rtthreadMutexInit, + rtthreadMutexEnd, + rtthreadMutexAlloc, + rtthreadMutexFree, + rtthreadMutexEnter, + rtthreadMutexTry, + rtthreadMutexLeave, +#ifdef SQLITE_DEBUG + rtthreadMutexHeld, + rtthreadMutexNotheld +#else + 0, + 0 +#endif + }; + + return &sMutex; +} + +#endif /* SQLITE_MUTEX_RTTHREAD */ + diff --git a/components/external/SQLite-3.8.1/src/mutex_unix.c b/components/external/SQLite-3.8.1/src/mutex_unix.c new file mode 100644 index 0000000000000000000000000000000000000000..eca7295831c2f0ee48ba54d062914d06a1dd8ebe --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mutex_unix.c @@ -0,0 +1,351 @@ +/* +** 2007 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement mutexes for pthreads +*/ +#include "sqliteInt.h" + +/* +** The code in this file is only used if we are compiling threadsafe +** under unix with pthreads. +** +** Note that this implementation requires a version of pthreads that +** supports recursive mutexes. +*/ +#ifdef SQLITE_MUTEX_PTHREADS + +#include + +/* +** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields +** are necessary under two condidtions: (1) Debug builds and (2) using +** home-grown mutexes. Encapsulate these conditions into a single #define. +*/ +#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX) +# define SQLITE_MUTEX_NREF 1 +#else +# define SQLITE_MUTEX_NREF 0 +#endif + +/* +** Each recursive mutex is an instance of the following structure. +*/ +struct sqlite3_mutex { + pthread_mutex_t mutex; /* Mutex controlling the lock */ +#if SQLITE_MUTEX_NREF + int id; /* Mutex type */ + volatile int nRef; /* Number of entrances */ + volatile pthread_t owner; /* Thread that is within this mutex */ + int trace; /* True to trace changes */ +#endif +}; +#if SQLITE_MUTEX_NREF +#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 } +#else +#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER } +#endif + +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use only inside assert() statements. On some platforms, +** there might be race conditions that can cause these routines to +** deliver incorrect results. In particular, if pthread_equal() is +** not an atomic operation, then these routines might delivery +** incorrect results. On most platforms, pthread_equal() is a +** comparison of two integers and is therefore atomic. But we are +** told that HPUX is not such a platform. If so, then these routines +** will not always work correctly on HPUX. +** +** On those platforms where pthread_equal() is not atomic, SQLite +** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to +** make sure no assert() statements are evaluated and hence these +** routines are never called. +*/ +#if !defined(NDEBUG) || defined(SQLITE_DEBUG) +static int pthreadMutexHeld(sqlite3_mutex *p){ + return (p->nRef!=0 && pthread_equal(p->owner, pthread_self())); +} +static int pthreadMutexNotheld(sqlite3_mutex *p){ + return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0; +} +#endif + +/* +** Initialize and deinitialize the mutex subsystem. +*/ +static int pthreadMutexInit(void){ return SQLITE_OK; } +static int pthreadMutexEnd(void){ return SQLITE_OK; } + +/* +** The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. If it returns NULL +** that means that a mutex could not be allocated. SQLite +** will unwind its stack and return an error. The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_PMEM +**
+** +** The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. But SQLite will only request a recursive mutex in +** cases where it really needs one. If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +*/ +static sqlite3_mutex *pthreadMutexAlloc(int iType){ + static sqlite3_mutex staticMutexes[] = { + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER + }; + sqlite3_mutex *p; + switch( iType ){ + case SQLITE_MUTEX_RECURSIVE: { + p = sqlite3MallocZero( sizeof(*p) ); + if( p ){ +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, we will have to + ** build our own. See below. */ + pthread_mutex_init(&p->mutex, 0); +#else + /* Use a recursive mutex if it is available */ + pthread_mutexattr_t recursiveAttr; + pthread_mutexattr_init(&recursiveAttr); + pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&p->mutex, &recursiveAttr); + pthread_mutexattr_destroy(&recursiveAttr); +#endif +#if SQLITE_MUTEX_NREF + p->id = iType; +#endif + } + break; + } + case SQLITE_MUTEX_FAST: { + p = sqlite3MallocZero( sizeof(*p) ); + if( p ){ +#if SQLITE_MUTEX_NREF + p->id = iType; +#endif + pthread_mutex_init(&p->mutex, 0); + } + break; + } + default: { + assert( iType-2 >= 0 ); + assert( iType-2 < ArraySize(staticMutexes) ); + p = &staticMutexes[iType-2]; +#if SQLITE_MUTEX_NREF + p->id = iType; +#endif + break; + } + } + return p; +} + + +/* +** This routine deallocates a previously +** allocated mutex. SQLite is careful to deallocate every +** mutex that it allocates. +*/ +static void pthreadMutexFree(sqlite3_mutex *p){ + assert( p->nRef==0 ); + assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ); + pthread_mutex_destroy(&p->mutex); + sqlite3_free(p); +} + +/* +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can +** be entered multiple times by the same thread. In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. If the same thread tries to enter any other kind of mutex +** more than once, the behavior is undefined. +*/ +static void pthreadMutexEnter(sqlite3_mutex *p){ + assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, then we have to grow + ** our own. This implementation assumes that pthread_equal() + ** is atomic - that it cannot be deceived into thinking self + ** and p->owner are equal if p->owner changes between two values + ** that are not equal to self while the comparison is taking place. + ** This implementation also assumes a coherent cache - that + ** separate processes cannot read different values from the same + ** address at the same time. If either of these two conditions + ** are not met, then the mutexes will fail and problems will result. + */ + { + pthread_t self = pthread_self(); + if( p->nRef>0 && pthread_equal(p->owner, self) ){ + p->nRef++; + }else{ + pthread_mutex_lock(&p->mutex); + assert( p->nRef==0 ); + p->owner = self; + p->nRef = 1; + } + } +#else + /* Use the built-in recursive mutexes if they are available. + */ + pthread_mutex_lock(&p->mutex); +#if SQLITE_MUTEX_NREF + assert( p->nRef>0 || p->owner==0 ); + p->owner = pthread_self(); + p->nRef++; +#endif +#endif + +#ifdef SQLITE_DEBUG + if( p->trace ){ + printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif +} +static int pthreadMutexTry(sqlite3_mutex *p){ + int rc; + assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, then we have to grow + ** our own. This implementation assumes that pthread_equal() + ** is atomic - that it cannot be deceived into thinking self + ** and p->owner are equal if p->owner changes between two values + ** that are not equal to self while the comparison is taking place. + ** This implementation also assumes a coherent cache - that + ** separate processes cannot read different values from the same + ** address at the same time. If either of these two conditions + ** are not met, then the mutexes will fail and problems will result. + */ + { + pthread_t self = pthread_self(); + if( p->nRef>0 && pthread_equal(p->owner, self) ){ + p->nRef++; + rc = SQLITE_OK; + }else if( pthread_mutex_trylock(&p->mutex)==0 ){ + assert( p->nRef==0 ); + p->owner = self; + p->nRef = 1; + rc = SQLITE_OK; + }else{ + rc = SQLITE_BUSY; + } + } +#else + /* Use the built-in recursive mutexes if they are available. + */ + if( pthread_mutex_trylock(&p->mutex)==0 ){ +#if SQLITE_MUTEX_NREF + p->owner = pthread_self(); + p->nRef++; +#endif + rc = SQLITE_OK; + }else{ + rc = SQLITE_BUSY; + } +#endif + +#ifdef SQLITE_DEBUG + if( rc==SQLITE_OK && p->trace ){ + printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif + return rc; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. The behavior +** is undefined if the mutex is not currently entered or +** is not currently allocated. SQLite will never do either. +*/ +static void pthreadMutexLeave(sqlite3_mutex *p){ + assert( pthreadMutexHeld(p) ); +#if SQLITE_MUTEX_NREF + p->nRef--; + if( p->nRef==0 ) p->owner = 0; +#endif + assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + if( p->nRef==0 ){ + pthread_mutex_unlock(&p->mutex); + } +#else + pthread_mutex_unlock(&p->mutex); +#endif + +#ifdef SQLITE_DEBUG + if( p->trace ){ + printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif +} + +sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ + static const sqlite3_mutex_methods sMutex = { + pthreadMutexInit, + pthreadMutexEnd, + pthreadMutexAlloc, + pthreadMutexFree, + pthreadMutexEnter, + pthreadMutexTry, + pthreadMutexLeave, +#ifdef SQLITE_DEBUG + pthreadMutexHeld, + pthreadMutexNotheld +#else + 0, + 0 +#endif + }; + + return &sMutex; +} + +#endif /* SQLITE_MUTEX_PTHREADS */ diff --git a/components/external/SQLite-3.8.1/src/mutex_w32.c b/components/external/SQLite-3.8.1/src/mutex_w32.c new file mode 100644 index 0000000000000000000000000000000000000000..4b88c174524ede16b42ff42e7e3bc4a317d6762b --- /dev/null +++ b/components/external/SQLite-3.8.1/src/mutex_w32.c @@ -0,0 +1,342 @@ +/* +** 2007 August 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the C functions that implement mutexes for win32 +*/ +#include "sqliteInt.h" + +/* +** The code in this file is only used if we are compiling multithreaded +** on a win32 system. +*/ +#ifdef SQLITE_MUTEX_W32 + +/* +** Each recursive mutex is an instance of the following structure. +*/ +struct sqlite3_mutex { + CRITICAL_SECTION mutex; /* Mutex controlling the lock */ + int id; /* Mutex type */ +#ifdef SQLITE_DEBUG + volatile int nRef; /* Number of enterances */ + volatile DWORD owner; /* Thread holding this mutex */ + int trace; /* True to trace changes */ +#endif +}; +#define SQLITE_W32_MUTEX_INITIALIZER { 0 } +#ifdef SQLITE_DEBUG +#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 } +#else +#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 } +#endif + +/* +** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, +** or WinCE. Return false (zero) for Win95, Win98, or WinME. +** +** Here is an interesting observation: Win95, Win98, and WinME lack +** the LockFileEx() API. But we can still statically link against that +** API as long as we don't call it win running Win95/98/ME. A call to +** this routine is used to determine if the host is Win95/98/ME or +** WinNT/2K/XP so that we will know whether or not we can safely call +** the LockFileEx() API. +** +** mutexIsNT() is only used for the TryEnterCriticalSection() API call, +** which is only available if your application was compiled with +** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only +** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef +** this out as well. +*/ +#if 0 +#if SQLITE_OS_WINCE || SQLITE_OS_WINRT +# define mutexIsNT() (1) +#else + static int mutexIsNT(void){ + static int osType = 0; + if( osType==0 ){ + OSVERSIONINFO sInfo; + sInfo.dwOSVersionInfoSize = sizeof(sInfo); + GetVersionEx(&sInfo); + osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1; + } + return osType==2; + } +#endif /* SQLITE_OS_WINCE || SQLITE_OS_WINRT */ +#endif + +#ifdef SQLITE_DEBUG +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use only inside assert() statements. +*/ +static int winMutexHeld(sqlite3_mutex *p){ + return p->nRef!=0 && p->owner==GetCurrentThreadId(); +} +static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){ + return p->nRef==0 || p->owner!=tid; +} +static int winMutexNotheld(sqlite3_mutex *p){ + DWORD tid = GetCurrentThreadId(); + return winMutexNotheld2(p, tid); +} +#endif + + +/* +** Initialize and deinitialize the mutex subsystem. +*/ +static sqlite3_mutex winMutex_staticMutexes[6] = { + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER, + SQLITE3_MUTEX_INITIALIZER +}; +static int winMutex_isInit = 0; +/* As winMutexInit() and winMutexEnd() are called as part +** of the sqlite3_initialize and sqlite3_shutdown() +** processing, the "interlocked" magic is probably not +** strictly necessary. +*/ +static LONG winMutex_lock = 0; + +void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */ + +static int winMutexInit(void){ + /* The first to increment to 1 does actual initialization */ + if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){ + int i; + for(i=0; i +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_PMEM +** +** +** The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. But SQLite will only request a recursive mutex in +** cases where it really needs one. If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +*/ +static sqlite3_mutex *winMutexAlloc(int iType){ + sqlite3_mutex *p; + + switch( iType ){ + case SQLITE_MUTEX_FAST: + case SQLITE_MUTEX_RECURSIVE: { + p = sqlite3MallocZero( sizeof(*p) ); + if( p ){ +#ifdef SQLITE_DEBUG + p->id = iType; +#endif +#if SQLITE_OS_WINRT + InitializeCriticalSectionEx(&p->mutex, 0, 0); +#else + InitializeCriticalSection(&p->mutex); +#endif + } + break; + } + default: { + assert( winMutex_isInit==1 ); + assert( iType-2 >= 0 ); + assert( iType-2 < ArraySize(winMutex_staticMutexes) ); + p = &winMutex_staticMutexes[iType-2]; +#ifdef SQLITE_DEBUG + p->id = iType; +#endif + break; + } + } + return p; +} + + +/* +** This routine deallocates a previously +** allocated mutex. SQLite is careful to deallocate every +** mutex that it allocates. +*/ +static void winMutexFree(sqlite3_mutex *p){ + assert( p ); + assert( p->nRef==0 && p->owner==0 ); + assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ); + DeleteCriticalSection(&p->mutex); + sqlite3_free(p); +} + +/* +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can +** be entered multiple times by the same thread. In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. If the same thread tries to enter any other kind of mutex +** more than once, the behavior is undefined. +*/ +static void winMutexEnter(sqlite3_mutex *p){ +#ifdef SQLITE_DEBUG + DWORD tid = GetCurrentThreadId(); + assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); +#endif + EnterCriticalSection(&p->mutex); +#ifdef SQLITE_DEBUG + assert( p->nRef>0 || p->owner==0 ); + p->owner = tid; + p->nRef++; + if( p->trace ){ + printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif +} +static int winMutexTry(sqlite3_mutex *p){ +#ifndef NDEBUG + DWORD tid = GetCurrentThreadId(); +#endif + int rc = SQLITE_BUSY; + assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); + /* + ** The sqlite3_mutex_try() routine is very rarely used, and when it + ** is used it is merely an optimization. So it is OK for it to always + ** fail. + ** + ** The TryEnterCriticalSection() interface is only available on WinNT. + ** And some windows compilers complain if you try to use it without + ** first doing some #defines that prevent SQLite from building on Win98. + ** For that reason, we will omit this optimization for now. See + ** ticket #2685. + */ +#if 0 + if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){ + p->owner = tid; + p->nRef++; + rc = SQLITE_OK; + } +#else + UNUSED_PARAMETER(p); +#endif +#ifdef SQLITE_DEBUG + if( rc==SQLITE_OK && p->trace ){ + printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif + return rc; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. The behavior +** is undefined if the mutex is not currently entered or +** is not currently allocated. SQLite will never do either. +*/ +static void winMutexLeave(sqlite3_mutex *p){ +#ifndef NDEBUG + DWORD tid = GetCurrentThreadId(); + assert( p->nRef>0 ); + assert( p->owner==tid ); + p->nRef--; + if( p->nRef==0 ) p->owner = 0; + assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); +#endif + LeaveCriticalSection(&p->mutex); +#ifdef SQLITE_DEBUG + if( p->trace ){ + printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif +} + +sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ + static const sqlite3_mutex_methods sMutex = { + winMutexInit, + winMutexEnd, + winMutexAlloc, + winMutexFree, + winMutexEnter, + winMutexTry, + winMutexLeave, +#ifdef SQLITE_DEBUG + winMutexHeld, + winMutexNotheld +#else + 0, + 0 +#endif + }; + + return &sMutex; +} +#endif /* SQLITE_MUTEX_W32 */ diff --git a/components/external/SQLite-3.8.1/src/notify.c b/components/external/SQLite-3.8.1/src/notify.c new file mode 100644 index 0000000000000000000000000000000000000000..fcab5bfaf01908d3de93fa88b5eae9e96ca3c8e8 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/notify.c @@ -0,0 +1,332 @@ +/* +** 2009 March 3 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the implementation of the sqlite3_unlock_notify() +** API method and its associated functionality. +*/ +#include "sqliteInt.h" +#include "btreeInt.h" + +/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */ +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + +/* +** Public interfaces: +** +** sqlite3ConnectionBlocked() +** sqlite3ConnectionUnlocked() +** sqlite3ConnectionClosed() +** sqlite3_unlock_notify() +*/ + +#define assertMutexHeld() \ + assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) + +/* +** Head of a linked list of all sqlite3 objects created by this process +** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection +** is not NULL. This variable may only accessed while the STATIC_MASTER +** mutex is held. +*/ +static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; + +#ifndef NDEBUG +/* +** This function is a complex assert() that verifies the following +** properties of the blocked connections list: +** +** 1) Each entry in the list has a non-NULL value for either +** pUnlockConnection or pBlockingConnection, or both. +** +** 2) All entries in the list that share a common value for +** xUnlockNotify are grouped together. +** +** 3) If the argument db is not NULL, then none of the entries in the +** blocked connections list have pUnlockConnection or pBlockingConnection +** set to db. This is used when closing connection db. +*/ +static void checkListProperties(sqlite3 *db){ + sqlite3 *p; + for(p=sqlite3BlockedList; p; p=p->pNextBlocked){ + int seen = 0; + sqlite3 *p2; + + /* Verify property (1) */ + assert( p->pUnlockConnection || p->pBlockingConnection ); + + /* Verify property (2) */ + for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ + if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; + assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); + assert( db==0 || p->pUnlockConnection!=db ); + assert( db==0 || p->pBlockingConnection!=db ); + } + } +} +#else +# define checkListProperties(x) +#endif + +/* +** Remove connection db from the blocked connections list. If connection +** db is not currently a part of the list, this function is a no-op. +*/ +static void removeFromBlockedList(sqlite3 *db){ + sqlite3 **pp; + assertMutexHeld(); + for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ + if( *pp==db ){ + *pp = (*pp)->pNextBlocked; + break; + } + } +} + +/* +** Add connection db to the blocked connections list. It is assumed +** that it is not already a part of the list. +*/ +static void addToBlockedList(sqlite3 *db){ + sqlite3 **pp; + assertMutexHeld(); + for( + pp=&sqlite3BlockedList; + *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; + pp=&(*pp)->pNextBlocked + ); + db->pNextBlocked = *pp; + *pp = db; +} + +/* +** Obtain the STATIC_MASTER mutex. +*/ +static void enterMutex(void){ + sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); + checkListProperties(0); +} + +/* +** Release the STATIC_MASTER mutex. +*/ +static void leaveMutex(void){ + assertMutexHeld(); + checkListProperties(0); + sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} + +/* +** Register an unlock-notify callback. +** +** This is called after connection "db" has attempted some operation +** but has received an SQLITE_LOCKED error because another connection +** (call it pOther) in the same process was busy using the same shared +** cache. pOther is found by looking at db->pBlockingConnection. +** +** If there is no blocking connection, the callback is invoked immediately, +** before this routine returns. +** +** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate +** a deadlock. +** +** Otherwise, make arrangements to invoke xNotify when pOther drops +** its locks. +** +** Each call to this routine overrides any prior callbacks registered +** on the same "db". If xNotify==0 then any prior callbacks are immediately +** cancelled. +*/ +int sqlite3_unlock_notify( + sqlite3 *db, + void (*xNotify)(void **, int), + void *pArg +){ + int rc = SQLITE_OK; + + sqlite3_mutex_enter(db->mutex); + enterMutex(); + + if( xNotify==0 ){ + removeFromBlockedList(db); + db->pBlockingConnection = 0; + db->pUnlockConnection = 0; + db->xUnlockNotify = 0; + db->pUnlockArg = 0; + }else if( 0==db->pBlockingConnection ){ + /* The blocking transaction has been concluded. Or there never was a + ** blocking transaction. In either case, invoke the notify callback + ** immediately. + */ + xNotify(&pArg, 1); + }else{ + sqlite3 *p; + + for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} + if( p ){ + rc = SQLITE_LOCKED; /* Deadlock detected. */ + }else{ + db->pUnlockConnection = db->pBlockingConnection; + db->xUnlockNotify = xNotify; + db->pUnlockArg = pArg; + removeFromBlockedList(db); + addToBlockedList(db); + } + } + + leaveMutex(); + assert( !db->mallocFailed ); + sqlite3Error(db, rc, (rc?"database is deadlocked":0)); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** This function is called while stepping or preparing a statement +** associated with connection db. The operation will return SQLITE_LOCKED +** to the user because it requires a lock that will not be available +** until connection pBlocker concludes its current transaction. +*/ +void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ + enterMutex(); + if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ + addToBlockedList(db); + } + db->pBlockingConnection = pBlocker; + leaveMutex(); +} + +/* +** This function is called when +** the transaction opened by database db has just finished. Locks held +** by database connection db have been released. +** +** This function loops through each entry in the blocked connections +** list and does the following: +** +** 1) If the sqlite3.pBlockingConnection member of a list entry is +** set to db, then set pBlockingConnection=0. +** +** 2) If the sqlite3.pUnlockConnection member of a list entry is +** set to db, then invoke the configured unlock-notify callback and +** set pUnlockConnection=0. +** +** 3) If the two steps above mean that pBlockingConnection==0 and +** pUnlockConnection==0, remove the entry from the blocked connections +** list. +*/ +void sqlite3ConnectionUnlocked(sqlite3 *db){ + void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ + int nArg = 0; /* Number of entries in aArg[] */ + sqlite3 **pp; /* Iterator variable */ + void **aArg; /* Arguments to the unlock callback */ + void **aDyn = 0; /* Dynamically allocated space for aArg[] */ + void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ + + aArg = aStatic; + enterMutex(); /* Enter STATIC_MASTER mutex */ + + /* This loop runs once for each entry in the blocked-connections list. */ + for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ + sqlite3 *p = *pp; + + /* Step 1. */ + if( p->pBlockingConnection==db ){ + p->pBlockingConnection = 0; + } + + /* Step 2. */ + if( p->pUnlockConnection==db ){ + assert( p->xUnlockNotify ); + if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ + xUnlockNotify(aArg, nArg); + nArg = 0; + } + + sqlite3BeginBenignMalloc(); + assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); + assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); + if( (!aDyn && nArg==(int)ArraySize(aStatic)) + || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*))) + ){ + /* The aArg[] array needs to grow. */ + void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); + if( pNew ){ + memcpy(pNew, aArg, nArg*sizeof(void *)); + sqlite3_free(aDyn); + aDyn = aArg = pNew; + }else{ + /* This occurs when the array of context pointers that need to + ** be passed to the unlock-notify callback is larger than the + ** aStatic[] array allocated on the stack and the attempt to + ** allocate a larger array from the heap has failed. + ** + ** This is a difficult situation to handle. Returning an error + ** code to the caller is insufficient, as even if an error code + ** is returned the transaction on connection db will still be + ** closed and the unlock-notify callbacks on blocked connections + ** will go unissued. This might cause the application to wait + ** indefinitely for an unlock-notify callback that will never + ** arrive. + ** + ** Instead, invoke the unlock-notify callback with the context + ** array already accumulated. We can then clear the array and + ** begin accumulating any further context pointers without + ** requiring any dynamic allocation. This is sub-optimal because + ** it means that instead of one callback with a large array of + ** context pointers the application will receive two or more + ** callbacks with smaller arrays of context pointers, which will + ** reduce the applications ability to prioritize multiple + ** connections. But it is the best that can be done under the + ** circumstances. + */ + xUnlockNotify(aArg, nArg); + nArg = 0; + } + } + sqlite3EndBenignMalloc(); + + aArg[nArg++] = p->pUnlockArg; + xUnlockNotify = p->xUnlockNotify; + p->pUnlockConnection = 0; + p->xUnlockNotify = 0; + p->pUnlockArg = 0; + } + + /* Step 3. */ + if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){ + /* Remove connection p from the blocked connections list. */ + *pp = p->pNextBlocked; + p->pNextBlocked = 0; + }else{ + pp = &p->pNextBlocked; + } + } + + if( nArg!=0 ){ + xUnlockNotify(aArg, nArg); + } + sqlite3_free(aDyn); + leaveMutex(); /* Leave STATIC_MASTER mutex */ +} + +/* +** This is called when the database connection passed as an argument is +** being closed. The connection is removed from the blocked list. +*/ +void sqlite3ConnectionClosed(sqlite3 *db){ + sqlite3ConnectionUnlocked(db); + enterMutex(); + removeFromBlockedList(db); + checkListProperties(db); + leaveMutex(); +} +#endif diff --git a/components/external/SQLite-3.8.1/src/os.c b/components/external/SQLite-3.8.1/src/os.c new file mode 100644 index 0000000000000000000000000000000000000000..be2ea4cfc0195993a340c902aeddf1be4b8ed73a --- /dev/null +++ b/components/external/SQLite-3.8.1/src/os.c @@ -0,0 +1,376 @@ +/* +** 2005 November 29 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains OS interface code that is common to all +** architectures. +*/ +#define _SQLITE_OS_C_ 1 +#include "sqliteInt.h" +#undef _SQLITE_OS_C_ + +/* +** The default SQLite sqlite3_vfs implementations do not allocate +** memory (actually, os_unix.c allocates a small amount of memory +** from within OsOpen()), but some third-party implementations may. +** So we test the effects of a malloc() failing and the sqlite3OsXXX() +** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. +** +** The following functions are instrumented for malloc() failure +** testing: +** +** sqlite3OsRead() +** sqlite3OsWrite() +** sqlite3OsSync() +** sqlite3OsFileSize() +** sqlite3OsLock() +** sqlite3OsCheckReservedLock() +** sqlite3OsFileControl() +** sqlite3OsShmMap() +** sqlite3OsOpen() +** sqlite3OsDelete() +** sqlite3OsAccess() +** sqlite3OsFullPathname() +** +*/ +#if defined(SQLITE_TEST) +int sqlite3_memdebug_vfs_oom_test = 1; + #define DO_OS_MALLOC_TEST(x) \ + if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \ + void *pTstAlloc = sqlite3Malloc(10); \ + if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \ + sqlite3_free(pTstAlloc); \ + } +#else + #define DO_OS_MALLOC_TEST(x) +#endif + +/* +** The following routines are convenience wrappers around methods +** of the sqlite3_file object. This is mostly just syntactic sugar. All +** of this would be completely automatic if SQLite were coded using +** C++ instead of plain old C. +*/ +int sqlite3OsClose(sqlite3_file *pId){ + int rc = SQLITE_OK; + if( pId->pMethods ){ + rc = pId->pMethods->xClose(pId); + pId->pMethods = 0; + } + return rc; +} +int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xRead(id, pBuf, amt, offset); +} +int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xWrite(id, pBuf, amt, offset); +} +int sqlite3OsTruncate(sqlite3_file *id, i64 size){ + return id->pMethods->xTruncate(id, size); +} +int sqlite3OsSync(sqlite3_file *id, int flags){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xSync(id, flags); +} +int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xFileSize(id, pSize); +} +int sqlite3OsLock(sqlite3_file *id, int lockType){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xLock(id, lockType); +} +int sqlite3OsUnlock(sqlite3_file *id, int lockType){ + return id->pMethods->xUnlock(id, lockType); +} +int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xCheckReservedLock(id, pResOut); +} + +/* +** Use sqlite3OsFileControl() when we are doing something that might fail +** and we need to know about the failures. Use sqlite3OsFileControlHint() +** when simply tossing information over the wall to the VFS and we do not +** really care if the VFS receives and understands the information since it +** is only a hint and can be safely ignored. The sqlite3OsFileControlHint() +** routine has no return value since the return value would be meaningless. +*/ +int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xFileControl(id, op, pArg); +} +void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){ + (void)id->pMethods->xFileControl(id, op, pArg); +} + +int sqlite3OsSectorSize(sqlite3_file *id){ + int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; + return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); +} +int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ + return id->pMethods->xDeviceCharacteristics(id); +} +int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){ + return id->pMethods->xShmLock(id, offset, n, flags); +} +void sqlite3OsShmBarrier(sqlite3_file *id){ + id->pMethods->xShmBarrier(id); +} +int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){ + return id->pMethods->xShmUnmap(id, deleteFlag); +} +int sqlite3OsShmMap( + sqlite3_file *id, /* Database file handle */ + int iPage, + int pgsz, + int bExtend, /* True to extend file if necessary */ + void volatile **pp /* OUT: Pointer to mapping */ +){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp); +} + +#if SQLITE_MAX_MMAP_SIZE>0 +/* The real implementation of xFetch and xUnfetch */ +int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ + DO_OS_MALLOC_TEST(id); + return id->pMethods->xFetch(id, iOff, iAmt, pp); +} +int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ + return id->pMethods->xUnfetch(id, iOff, p); +} +#else +/* No-op stubs to use when memory-mapped I/O is disabled */ +int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ + *pp = 0; + return SQLITE_OK; +} +int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ + return SQLITE_OK; +} +#endif + +/* +** The next group of routines are convenience wrappers around the +** VFS methods. +*/ +int sqlite3OsOpen( + sqlite3_vfs *pVfs, + const char *zPath, + sqlite3_file *pFile, + int flags, + int *pFlagsOut +){ + int rc; + DO_OS_MALLOC_TEST(0); + /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed + ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, + ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before + ** reaching the VFS. */ + rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut); + assert( rc==SQLITE_OK || pFile->pMethods==0 ); + return rc; +} +int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + DO_OS_MALLOC_TEST(0); + assert( dirSync==0 || dirSync==1 ); + return pVfs->xDelete(pVfs, zPath, dirSync); +} +int sqlite3OsAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + DO_OS_MALLOC_TEST(0); + return pVfs->xAccess(pVfs, zPath, flags, pResOut); +} +int sqlite3OsFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nPathOut, + char *zPathOut +){ + DO_OS_MALLOC_TEST(0); + zPathOut[0] = 0; + return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); +} +#ifndef SQLITE_OMIT_LOAD_EXTENSION +void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return pVfs->xDlOpen(pVfs, zPath); +} +void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + pVfs->xDlError(pVfs, nByte, zBufOut); +} +void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){ + return pVfs->xDlSym(pVfs, pHdle, zSym); +} +void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){ + pVfs->xDlClose(pVfs, pHandle); +} +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return pVfs->xRandomness(pVfs, nByte, zBufOut); +} +int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){ + return pVfs->xSleep(pVfs, nMicro); +} +int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ + int rc; + /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() + ** method to get the current date and time if that method is available + ** (if iVersion is 2 or greater and the function pointer is not NULL) and + ** will fall back to xCurrentTime() if xCurrentTimeInt64() is + ** unavailable. + */ + if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ + rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut); + }else{ + double r; + rc = pVfs->xCurrentTime(pVfs, &r); + *pTimeOut = (sqlite3_int64)(r*86400000.0); + } + return rc; +} + +int sqlite3OsOpenMalloc( + sqlite3_vfs *pVfs, + const char *zFile, + sqlite3_file **ppFile, + int flags, + int *pOutFlags +){ + int rc = SQLITE_NOMEM; + sqlite3_file *pFile; + pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile); + if( pFile ){ + rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags); + if( rc!=SQLITE_OK ){ + sqlite3_free(pFile); + }else{ + *ppFile = pFile; + } + } + return rc; +} +int sqlite3OsCloseFree(sqlite3_file *pFile){ + int rc = SQLITE_OK; + assert( pFile ); + rc = sqlite3OsClose(pFile); + sqlite3_free(pFile); + return rc; +} + +/* +** This function is a wrapper around the OS specific implementation of +** sqlite3_os_init(). The purpose of the wrapper is to provide the +** ability to simulate a malloc failure, so that the handling of an +** error in sqlite3_os_init() by the upper layers can be tested. +*/ +int sqlite3OsInit(void){ + void *p = sqlite3_malloc(10); + if( p==0 ) return SQLITE_NOMEM; + sqlite3_free(p); + return sqlite3_os_init(); +} + +/* +** The list of all registered VFS implementations. +*/ +static sqlite3_vfs * SQLITE_WSD vfsList = 0; +#define vfsList GLOBAL(sqlite3_vfs *, vfsList) + +/* +** Locate a VFS by name. If no name is given, simply return the +** first VFS on the list. +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){ + sqlite3_vfs *pVfs = 0; +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex; +#endif +#ifndef SQLITE_OMIT_AUTOINIT + int rc = sqlite3_initialize(); + if( rc ) return 0; +#endif +#if SQLITE_THREADSAFE + mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter(mutex); + for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){ + if( zVfs==0 ) break; + if( strcmp(zVfs, pVfs->zName)==0 ) break; + } + sqlite3_mutex_leave(mutex); + return pVfs; +} + +/* +** Unlink a VFS from the linked list +*/ +static void vfsUnlink(sqlite3_vfs *pVfs){ + assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ); + if( pVfs==0 ){ + /* No-op */ + }else if( vfsList==pVfs ){ + vfsList = pVfs->pNext; + }else if( vfsList ){ + sqlite3_vfs *p = vfsList; + while( p->pNext && p->pNext!=pVfs ){ + p = p->pNext; + } + if( p->pNext==pVfs ){ + p->pNext = pVfs->pNext; + } + } +} + +/* +** Register a VFS with the system. It is harmless to register the same +** VFS multiple times. The new VFS becomes the default if makeDflt is +** true. +*/ +int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){ + MUTEX_LOGIC(sqlite3_mutex *mutex;) +#ifndef SQLITE_OMIT_AUTOINIT + int rc = sqlite3_initialize(); + if( rc ) return rc; +#endif + MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + sqlite3_mutex_enter(mutex); + vfsUnlink(pVfs); + if( makeDflt || vfsList==0 ){ + pVfs->pNext = vfsList; + vfsList = pVfs; + }else{ + pVfs->pNext = vfsList->pNext; + vfsList->pNext = pVfs; + } + assert(vfsList); + sqlite3_mutex_leave(mutex); + return SQLITE_OK; +} + +/* +** Unregister a VFS so that it is no longer accessible. +*/ +int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter(mutex); + vfsUnlink(pVfs); + sqlite3_mutex_leave(mutex); + return SQLITE_OK; +} diff --git a/components/external/SQLite-3.8.1/src/os.h b/components/external/SQLite-3.8.1/src/os.h new file mode 100644 index 0000000000000000000000000000000000000000..341c9c6c01eee14161d1c674557c9ad0451d07be --- /dev/null +++ b/components/external/SQLite-3.8.1/src/os.h @@ -0,0 +1,284 @@ +/* +** 2001 September 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file (together with is companion C source-code file +** "os.c") attempt to abstract the underlying operating system so that +** the SQLite library will work on both POSIX and windows systems. +** +** This header file is #include-ed by sqliteInt.h and thus ends up +** being included by every source file. +*/ +#ifndef _SQLITE_OS_H_ +#define _SQLITE_OS_H_ + +/* +** Figure out if we are dealing with Unix, Windows, or some other +** operating system. After the following block of preprocess macros, +** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER +** will defined to either 1 or 0. One of the four will be 1. The other +** three will be 0. +*/ +#if defined(SQLITE_OS_OTHER) +# if SQLITE_OS_OTHER==1 +# undef SQLITE_OS_UNIX +# define SQLITE_OS_UNIX 0 +# undef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# undef SQLITE_OS_RTTHREAD +# define SQLITE_OS_RTTHREAD 1 +# else +# undef SQLITE_OS_OTHER +# endif +#endif +#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) +# define SQLITE_OS_OTHER 0 +# ifndef SQLITE_OS_WIN +# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) +# define SQLITE_OS_WIN 1 +# define SQLITE_OS_UNIX 0 +# else +# define SQLITE_OS_WIN 0 +# define SQLITE_OS_UNIX 1 +# endif +# else +# define SQLITE_OS_UNIX 0 +# endif +#else +# ifndef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# endif +#endif + +#if SQLITE_OS_WIN +# include +#endif + +/* +** Determine if we are dealing with Windows NT. +** +** We ought to be able to determine if we are compiling for win98 or winNT +** using the _WIN32_WINNT macro as follows: +** +** #if defined(_WIN32_WINNT) +** # define SQLITE_OS_WINNT 1 +** #else +** # define SQLITE_OS_WINNT 0 +** #endif +** +** However, vs2005 does not set _WIN32_WINNT by default, as it ought to, +** so the above test does not work. We'll just assume that everything is +** winNT unless the programmer explicitly says otherwise by setting +** SQLITE_OS_WINNT to 0. +*/ +#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT) +# define SQLITE_OS_WINNT 1 +#endif + +/* +** Determine if we are dealing with WindowsCE - which has a much +** reduced API. +*/ +#if defined(_WIN32_WCE) +# define SQLITE_OS_WINCE 1 +#else +# define SQLITE_OS_WINCE 0 +#endif + +/* +** Determine if we are dealing with WinRT, which provides only a subset of +** the full Win32 API. +*/ +#if !defined(SQLITE_OS_WINRT) +# define SQLITE_OS_WINRT 0 +#endif + +/* If the SET_FULLSYNC macro is not defined above, then make it +** a no-op +*/ +#ifndef SET_FULLSYNC +# define SET_FULLSYNC(x,y) +#endif + +/* +** The default size of a disk sector +*/ +#ifndef SQLITE_DEFAULT_SECTOR_SIZE +# define SQLITE_DEFAULT_SECTOR_SIZE 4096 +#endif + +/* +** Temporary files are named starting with this prefix followed by 16 random +** alphanumeric characters, and no file extension. They are stored in the +** OS's standard temporary file directory, and are deleted prior to exit. +** If sqlite is being embedded in another program, you may wish to change the +** prefix to reflect your program's name, so that if your program exits +** prematurely, old temporary files can be easily identified. This can be done +** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. +** +** 2006-10-31: The default prefix used to be "sqlite_". But then +** Mcafee started using SQLite in their anti-virus product and it +** started putting files with the "sqlite" name in the c:/temp folder. +** This annoyed many windows users. Those users would then do a +** Google search for "sqlite", find the telephone numbers of the +** developers and call to wake them up at night and complain. +** For this reason, the default name prefix is changed to be "sqlite" +** spelled backwards. So the temp files are still identified, but +** anybody smart enough to figure out the code is also likely smart +** enough to know that calling the developer will not help get rid +** of the file. +*/ +#ifndef SQLITE_TEMP_FILE_PREFIX +# define SQLITE_TEMP_FILE_PREFIX "etilqs_" +#endif + +/* +** The following values may be passed as the second argument to +** sqlite3OsLock(). The various locks exhibit the following semantics: +** +** SHARED: Any number of processes may hold a SHARED lock simultaneously. +** RESERVED: A single process may hold a RESERVED lock on a file at +** any time. Other processes may hold and obtain new SHARED locks. +** PENDING: A single process may hold a PENDING lock on a file at +** any one time. Existing SHARED locks may persist, but no new +** SHARED locks may be obtained by other processes. +** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. +** +** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a +** process that requests an EXCLUSIVE lock may actually obtain a PENDING +** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to +** sqlite3OsLock(). +*/ +#define NO_LOCK 0 +#define SHARED_LOCK 1 +#define RESERVED_LOCK 2 +#define PENDING_LOCK 3 +#define EXCLUSIVE_LOCK 4 + +/* +** File Locking Notes: (Mostly about windows but also some info for Unix) +** +** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because +** those functions are not available. So we use only LockFile() and +** UnlockFile(). +** +** LockFile() prevents not just writing but also reading by other processes. +** A SHARED_LOCK is obtained by locking a single randomly-chosen +** byte out of a specific range of bytes. The lock byte is obtained at +** random so two separate readers can probably access the file at the +** same time, unless they are unlucky and choose the same lock byte. +** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. +** There can only be one writer. A RESERVED_LOCK is obtained by locking +** a single byte of the file that is designated as the reserved lock byte. +** A PENDING_LOCK is obtained by locking a designated byte different from +** the RESERVED_LOCK byte. +** +** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, +** which means we can use reader/writer locks. When reader/writer locks +** are used, the lock is placed on the same range of bytes that is used +** for probabilistic locking in Win95/98/ME. Hence, the locking scheme +** will support two or more Win95 readers or two or more WinNT readers. +** But a single Win95 reader will lock out all WinNT readers and a single +** WinNT reader will lock out all other Win95 readers. +** +** The following #defines specify the range of bytes used for locking. +** SHARED_SIZE is the number of bytes available in the pool from which +** a random byte is selected for a shared lock. The pool of bytes for +** shared locks begins at SHARED_FIRST. +** +** The same locking strategy and +** byte ranges are used for Unix. This leaves open the possiblity of having +** clients on win95, winNT, and unix all talking to the same shared file +** and all locking correctly. To do so would require that samba (or whatever +** tool is being used for file sharing) implements locks correctly between +** windows and unix. I'm guessing that isn't likely to happen, but by +** using the same locking range we are at least open to the possibility. +** +** Locking in windows is manditory. For this reason, we cannot store +** actual data in the bytes used for locking. The pager never allocates +** the pages involved in locking therefore. SHARED_SIZE is selected so +** that all locks will fit on a single page even at the minimum page size. +** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE +** is set high so that we don't have to allocate an unused page except +** for very large databases. But one should test the page skipping logic +** by setting PENDING_BYTE low and running the entire regression suite. +** +** Changing the value of PENDING_BYTE results in a subtly incompatible +** file format. Depending on how it is changed, you might not notice +** the incompatibility right away, even running a full regression test. +** The default location of PENDING_BYTE is the first byte past the +** 1GB boundary. +** +*/ +#ifdef SQLITE_OMIT_WSD +# define PENDING_BYTE (0x40000000) +#else +# define PENDING_BYTE sqlite3PendingByte +#endif +#define RESERVED_BYTE (PENDING_BYTE+1) +#define SHARED_FIRST (PENDING_BYTE+2) +#define SHARED_SIZE 510 + +/* +** Wrapper around OS specific sqlite3_os_init() function. +*/ +int sqlite3OsInit(void); + +/* +** Functions for accessing sqlite3_file methods +*/ +int sqlite3OsClose(sqlite3_file*); +int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); +int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); +int sqlite3OsTruncate(sqlite3_file*, i64 size); +int sqlite3OsSync(sqlite3_file*, int); +int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); +int sqlite3OsLock(sqlite3_file*, int); +int sqlite3OsUnlock(sqlite3_file*, int); +int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); +int sqlite3OsFileControl(sqlite3_file*,int,void*); +void sqlite3OsFileControlHint(sqlite3_file*,int,void*); +#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 +int sqlite3OsSectorSize(sqlite3_file *id); +int sqlite3OsDeviceCharacteristics(sqlite3_file *id); +int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); +int sqlite3OsShmLock(sqlite3_file *id, int, int, int); +void sqlite3OsShmBarrier(sqlite3_file *id); +int sqlite3OsShmUnmap(sqlite3_file *id, int); +int sqlite3OsFetch(sqlite3_file *id, i64, int, void **); +int sqlite3OsUnfetch(sqlite3_file *, i64, void *); + + +/* +** Functions for accessing sqlite3_vfs methods +*/ +int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); +int sqlite3OsDelete(sqlite3_vfs *, const char *, int); +int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); +int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); +void sqlite3OsDlError(sqlite3_vfs *, int, char *); +void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); +void sqlite3OsDlClose(sqlite3_vfs *, void *); +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +int sqlite3OsRandomness(sqlite3_vfs *, int, char *); +int sqlite3OsSleep(sqlite3_vfs *, int); +int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); + +/* +** Convenience functions for opening and closing files using +** sqlite3_malloc() to obtain space for the file-handle structure. +*/ +int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); +int sqlite3OsCloseFree(sqlite3_file *); + +#endif /* _SQLITE_OS_H_ */ diff --git a/components/external/SQLite-3.8.1/src/os_common.h b/components/external/SQLite-3.8.1/src/os_common.h new file mode 100644 index 0000000000000000000000000000000000000000..f6c3e7ff89463086401822f481e7e3b87b2c78c7 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/os_common.h @@ -0,0 +1,115 @@ +/* +** 2004 May 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains macros and a little bit of code that is common to +** all of the platform-specific files (os_*.c) and is #included into those +** files. +** +** This file should be #included by the os_*.c files only. It is not a +** general purpose header file. +*/ +#ifndef _OS_COMMON_H_ +#define _OS_COMMON_H_ + +/* +** At least two bugs have slipped in because we changed the MEMORY_DEBUG +** macro to SQLITE_DEBUG and some older makefiles have not yet made the +** switch. The following code should catch this problem at compile-time. +*/ +#ifdef MEMORY_DEBUG +# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." +#endif + +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) +# ifndef SQLITE_DEBUG_OS_TRACE +# define SQLITE_DEBUG_OS_TRACE 0 +# endif + int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; +# define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X +#else +# define OSTRACE(X) +#endif + +/* +** Macros for performance tracing. Normally turned off. Only works +** on i486 hardware. +*/ +#ifdef SQLITE_PERFORMANCE_TRACE + +/* +** hwtime.h contains inline assembler code for implementing +** high-performance timing routines. +*/ +#include "hwtime.h" + +static sqlite_uint64 g_start; +static sqlite_uint64 g_elapsed; +#define TIMER_START g_start=sqlite3Hwtime() +#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start +#define TIMER_ELAPSED g_elapsed +#else +#define TIMER_START +#define TIMER_END +#define TIMER_ELAPSED ((sqlite_uint64)0) +#endif + +/* +** If we compile with the SQLITE_TEST macro set, then the following block +** of code will give us the ability to simulate a disk I/O error. This +** is used for testing the I/O recovery logic. +*/ +#ifdef SQLITE_TEST +int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ +int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ +int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ +int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ +int sqlite3_io_error_benign = 0; /* True if errors are benign */ +int sqlite3_diskfull_pending = 0; +int sqlite3_diskfull = 0; +#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) +#define SimulateIOError(CODE) \ + if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ + || sqlite3_io_error_pending-- == 1 ) \ + { local_ioerr(); CODE; } +static void local_ioerr(){ + IOTRACE(("IOERR\n")); + sqlite3_io_error_hit++; + if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; +} +#define SimulateDiskfullError(CODE) \ + if( sqlite3_diskfull_pending ){ \ + if( sqlite3_diskfull_pending == 1 ){ \ + local_ioerr(); \ + sqlite3_diskfull = 1; \ + sqlite3_io_error_hit = 1; \ + CODE; \ + }else{ \ + sqlite3_diskfull_pending--; \ + } \ + } +#else +#define SimulateIOErrorBenign(X) +#define SimulateIOError(A) +#define SimulateDiskfullError(A) +#endif + +/* +** When testing, keep a count of the number of open files. +*/ +#ifdef SQLITE_TEST +int sqlite3_open_file_count = 0; +#define OpenCounter(X) sqlite3_open_file_count+=(X) +#else +#define OpenCounter(X) +#endif + +#endif /* !defined(_OS_COMMON_H_) */ diff --git a/components/external/SQLite-3.8.1/src/os_rtthread.c b/components/external/SQLite-3.8.1/src/os_rtthread.c new file mode 100644 index 0000000000000000000000000000000000000000..a1d6b7017c42cd3fee882173d1bbf91e5956dc6b --- /dev/null +++ b/components/external/SQLite-3.8.1/src/os_rtthread.c @@ -0,0 +1,2658 @@ +/* +** 2004 May 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code that is specific to Windows. +*/ +#include "sqliteInt.h" +#if SQLITE_OS_RTTHREAD /* This file is used for rt-thread only */ + +#include + +/* +** Include code that is common to all os_*.c files +*/ +#include "os_common.h" + +/* +** Compiling and using WAL mode requires several APIs that are not +** available in rt-thread. +*/ +#if !defined(SQLITE_OMIT_WAL) +# error "WAL mode requires not support from the rt-thread, compile\ + with SQLITE_OMIT_WAL." +#endif + +/* +** Are most of the rtthread ANSI APIs available (i.e. with certain exceptions +** based on the sub-platform)? +*/ +#if !defined(SQLITE_RTTHREAD_NO_ANSI) +# warning "please ensure rtthread ANSI APIs is available, otherwise compile with\ + SQLITE_RTTHREAD_NO_ANSI" +# define SQLITE_RTTHREAD_HAS_ANSI +#endif + +/* +** Are most of the rtthread Unicode APIs available (i.e. with certain exceptions +** based on the sub-platform)? +*/ +#if !defined(SQLITE_RTTHREAD_NO_WIDE) +# error "rtthread not support Unicode APIs" +# define SQLITE_RTTHREAD_HAS_WIDE +#endif + +/* +** Make sure at least one set of rtthread APIs is available. +*/ +#if !defined(SQLITE_RTTHREAD_HAS_ANSI) && !defined(SQLITE_RTTHREAD_HAS_WIDE) +# error "At least one of SQLITE_RTTHREAD_HAS_ANSI and SQLITE_RTTHREAD_HAS_WIDE\ + must be defined." +#endif + +/* +** Maximum pathname length (in chars) for rtthread. This should normally be +** MAX_PATH. +*/ +#ifndef SQLITE_RTTHREAD_MAX_PATH_CHARS +# warning "default Maximum pathname length be 255, otherwise compile with\ + SQLITE_RTTHREAD_MAX_PATH_CHARS=?" +# define SQLITE_RTTHREAD_MAX_PATH_CHARS (255) +#endif + +/* +** Maximum supported path-length. +*/ +#define MAX_PATHNAME 512 + +/* +** Returns non-zero if the character should be treated as a directory +** separator. +*/ +#ifndef rtthreadIsDirSep +# define rtthreadIsDirSep(a) ((a) == '/') +#endif + +/* +** This macro is used when a local variable is set to a value that is +** [sometimes] not used by the code (e.g. via conditional compilation). +*/ +#ifndef UNUSED_VARIABLE_VALUE +# define UNUSED_VARIABLE_VALUE(x) (void)(x) +#endif + +/* +** Returns the string that should be used as the directory separator. +*/ +#ifndef rtthreadGetDirDep +# define rtthreadGetDirDep() "/" +#endif + +/* +** The winFile structure is a subclass of sqlite3_file* specific to the win32 +** portability layer. +*/ +typedef struct rtthreadFile rtthreadFile; +struct rtthreadFile { + sqlite3_io_methods const *pMethod; /* Always the first entry */ + sqlite3_vfs *pVfs; /* The VFS that created this rtthreadFile */ + int h; /* The file descriptor */ + unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */ + unsigned char eFileLock; /* The type of lock held on this fd */ + int lastErrno; /* The unix errno from last I/O error */ + void *lockingContext; /* Locking style specific state */ + const char *zPath; /* Name of the file */ + int szChunk; /* Configured by FCNTL_CHUNK_SIZE */ +#if SQLITE_ENABLE_LOCKING_STYLE + int openFlags; /* The flags specified at open() */ +#endif +#if SQLITE_ENABLE_LOCKING_STYLE + unsigned fsFlags; /* cached details from statfs() */ +#endif +#ifdef SQLITE_DEBUG + /* The next group of variables are used to track whether or not the + ** transaction counter in bytes 24-27 of database files are updated + ** whenever any part of the database changes. An assertion fault will + ** occur if a file is updated without also updating the transaction + ** counter. This test is made to avoid new problems similar to the + ** one described by ticket #3584. + */ + unsigned char transCntrChng; /* True if the transaction counter changed */ + unsigned char dbUpdate; /* True if any part of database file changed */ + unsigned char inNormalWrite; /* True if in a normal write operation */ + +#endif + +#ifdef SQLITE_TEST + /* In test mode, increase the size of this structure a bit so that + ** it is larger than the struct CrashFile defined in test6.c. + */ + char aPadding[32]; +#endif +}; + +/* +** Allowed values for the rtthreadFile.ctrlFlags bitmask: +*/ +#define UNIXFILE_EXCL 0x01 /* Connections from one process only */ +#define UNIXFILE_RDONLY 0x02 /* Connection is read only */ +#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ +#ifndef SQLITE_DISABLE_DIRSYNC +# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */ +#else +# define UNIXFILE_DIRSYNC 0x00 +#endif +#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ +#define UNIXFILE_DELETE 0x20 /* Delete on close */ +#define UNIXFILE_URI 0x40 /* Filename might have query parameters */ +#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */ +#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */ + +/* +** The following variable is (normally) set once and never changes +** thereafter. It records whether the operating system is Win9x +** or WinNT. +** +** 0: Operating system unknown. +** 1: Operating system is rtthread. +** +** In order to facilitate testing on a rtthread system, the test fixture +** can manually set this value to 1 to emulate Win98 behavior. +*/ +#ifdef SQLITE_TEST +int sqlite3_os_type = 0; +#elif !SQLITE_OS_RTTHREAD && \ + defined(SQLITE_RTTHREAD_HAS_ANSI) && defined(SQLITE_RTTHREAD_HAS_WIDE) +static int sqlite3_os_type = 0; +#endif + +#ifndef SYSCALL +# define SYSCALL sqlite3_syscall_ptr +#endif + +#include + +static int _Access(const char *pathname, int mode) +{ + int fd; + + fd = open(pathname, O_RDONLY, mode); + + if (fd >= 0) + { + close(fd); + return 0; + } + + return -1; +} + +/* +** Invoke open(). Do so multiple times, until it either succeeds or +** fails for some reason other than EINTR. +** +** If the file creation mode "m" is 0 then set it to the default for +** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally +** 0644) as modified by the system umask. If m is not 0, then +** make the file creation mode be exactly m ignoring the umask. +** +** The m parameter will be non-zero only when creating -wal, -journal, +** and -shm files. We want those files to have *exactly* the same +** permissions as their original database, unadulterated by the umask. +** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a +** transaction crashes and leaves behind hot journals, then any +** process that is able to write to the database will also be able to +** recover the hot journals. +*/ +static int robust_open(const char *z, int f, mode_t m); + +/* +** Open a file descriptor to the directory containing file zFilename. +** If successful, *pFd is set to the opened file descriptor and +** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM +** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined +** value. +** +** The directory file descriptor is used for only one thing - to +** fsync() a directory to make sure file creation and deletion events +** are flushed to disk. Such fsyncs are not needed on newer +** journaling filesystems, but are required on older filesystems. +** +** This routine can be overridden using the xSetSysCall interface. +** The ability to override this routine was added in support of the +** chromium sandbox. Opening a directory is a security risk (we are +** told) so making it overrideable allows the chromium sandbox to +** replace this routine with a harmless no-op. To make this routine +** a no-op, replace it with a stub that returns SQLITE_OK but leaves +** *pFd set to a negative number. +** +** If SQLITE_OK is returned, the caller is responsible for closing +** the file descriptor *pFd using close(). +*/ +static int openDirectory(const char *zFilename, int *pFd); + +/* +** Many system calls are accessed through pointer-to-functions so that +** they may be overridden at runtime to facilitate fault injection during +** testing and sandboxing. The following array holds the names and pointers +** to all overrideable system calls. +*/ +static struct rtthread_syscall { + const char *zName; /* Name of the system call */ + sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ + sqlite3_syscall_ptr pDefault; /* Default value */ +} aSyscall[] = { + {"sleep", (sqlite3_syscall_ptr)rt_thread_delay, 0}, +#define osSleep ((rt_err_t(*)(rt_tick_t))aSyscall[0].pCurrent) + + { "open", (sqlite3_syscall_ptr)open, 0 }, +#define osOpen ((int(*)(const char*,int,int))aSyscall[1].pCurrent) + + { "close", (sqlite3_syscall_ptr)close, 0 }, +#define osClose ((int(*)(int))aSyscall[2].pCurrent) + + { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 }, +#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent) + + { "stat", (sqlite3_syscall_ptr)stat, 0 }, +#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) + + { "fstat", (sqlite3_syscall_ptr)fstat, 0 }, +#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent) + + { "read", (sqlite3_syscall_ptr)read, 0 }, +#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[6].pCurrent) + + { "write", (sqlite3_syscall_ptr)write, 0 }, +#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[7].pCurrent) + + { "unlink", (sqlite3_syscall_ptr)unlink, 0 }, +#define osUnlink ((int(*)(const char*))aSyscall[8].pCurrent) + + { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 }, +#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[9].pCurrent) + + { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 }, +#define osMkdir ((int(*)(const char*,mode_t))aSyscall[10].pCurrent) + + { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 }, +#define osRmdir ((int(*)(const char*))aSyscall[11].pCurrent) + + {"access", (sqlite3_syscall_ptr)_Access, 0 }, +#define osAccess ((int(*)(const char*, int))aSyscall[12].pCurrent) +}; /* End of the overrideable system calls */ + +/* +** +** This function - unixLogError_x(), is only ever called via the macro +** unixLogError(). +** +** It is invoked after an error occurs in an OS function and errno has been +** set. It logs a message using sqlite3_log() containing the current value of +** errno and, if possible, the human-readable equivalent from strerror() or +** strerror_r(). +** +** The first argument passed to the macro should be the error code that +** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). +** The two subsequent arguments should be the name of the OS function that +** failed (e.g. "unlink", "open") and the associated file-system path, +** if any. +*/ +#define rtthreadLogError(a,b,c) rtthreadLogErrorAtLine(a,b,c,__LINE__) +static int rtthreadLogErrorAtLine( + int errcode, /* SQLite error code */ + const char *zFunc, /* Name of OS function that failed */ + const char *zPath, /* File path associated with error */ + int iLine /* Source line number where error occurred */ +){ + char *zErr; /* Message from strerror() or equivalent */ + int iErrno = errno; /* Saved syscall error number */ + + /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use + ** the strerror() function to obtain the human-readable error message + ** equivalent to errno. Otherwise, use strerror_r(). + */ +#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R) + char aErr[80]; + memset(aErr, 0, sizeof(aErr)); + zErr = aErr; + + /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined, + ** assume that the system provides the GNU version of strerror_r() that + ** returns a pointer to a buffer containing the error message. That pointer + ** may point to aErr[], or it may point to some static storage somewhere. + ** Otherwise, assume that the system provides the POSIX version of + ** strerror_r(), which always writes an error message into aErr[]. + ** + ** If the code incorrectly assumes that it is the POSIX version that is + ** available, the error message will often be an empty string. Not a + ** huge problem. Incorrectly concluding that the GNU version is available + ** could lead to a segfault though. + */ +#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU) + zErr = +# endif + strerror_r(iErrno, aErr, sizeof(aErr)-1); + +#elif SQLITE_THREADSAFE + /* This is a threadsafe build, but strerror_r() is not available. */ + zErr = ""; +#else + /* Non-threadsafe build, use strerror(). */ + zErr = strerror(iErrno); +#endif + + if( zPath==0 ) zPath = ""; + sqlite3_log(errcode, + "os_rtthread.c:%d: (%d) %s(%s) - %s", + iLine, iErrno, zFunc, zPath, zErr + ); + + return errcode; +} + + +/* +** Do not accept any file descriptor less than this value, in order to avoid +** opening database file using file descriptors that are commonly used for +** standard input, output, and error. +*/ +#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR +# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3 +#endif + +/* +** Invoke open(). Do so multiple times, until it either succeeds or +** fails for some reason other than EINTR. +** +** If the file creation mode "m" is 0 then set it to the default for +** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally +** 0644) as modified by the system umask. If m is not 0, then +** make the file creation mode be exactly m ignoring the umask. +** +** The m parameter will be non-zero only when creating -wal, -journal, +** and -shm files. We want those files to have *exactly* the same +** permissions as their original database, unadulterated by the umask. +** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a +** transaction crashes and leaves behind hot journals, then any +** process that is able to write to the database will also be able to +** recover the hot journals. +*/ +static int robust_open(const char *z, int f, mode_t m){ + int fd; + mode_t m2 = m ; + while(1){ +#if defined(O_CLOEXEC) + fd = osOpen(z,f|O_CLOEXEC,m2); +#else + fd = osOpen(z,f,m2); +#endif + if( fd<0 ){ + if( errno==EINTR ) continue; + break; + } + if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break; + osClose(fd); + sqlite3_log(SQLITE_WARNING, + "attempt to open \"%s\" as file descriptor %d", z, fd); + fd = -1; + if( osOpen("/000111sql.test111000", f, m)<0 ) break; + } + + return fd; +} + +/* +** Open a file descriptor to the directory containing file zFilename. +** If successful, *pFd is set to the opened file descriptor and +** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM +** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined +** value. +** +** The directory file descriptor is used for only one thing - to +** fsync() a directory to make sure file creation and deletion events +** are flushed to disk. Such fsyncs are not needed on newer +** journaling filesystems, but are required on older filesystems. +** +** This routine can be overridden using the xSetSysCall interface. +** The ability to override this routine was added in support of the +** chromium sandbox. Opening a directory is a security risk (we are +** told) so making it overrideable allows the chromium sandbox to +** replace this routine with a harmless no-op. To make this routine +** a no-op, replace it with a stub that returns SQLITE_OK but leaves +** *pFd set to a negative number. +** +** If SQLITE_OK is returned, the caller is responsible for closing +** the file descriptor *pFd using close(). +*/ +static int openDirectory(const char *zFilename, int *pFd){ + int ii; + int fd = -1; + char zDirname[MAX_PATHNAME+1]; + + sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); + for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--); + if( ii>0 ){ + zDirname[ii] = '\0'; + fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0); + if( fd>=0 ){ + OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); + } + } + *pFd = fd; + return (fd>=0?SQLITE_OK:rtthreadLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname)); +} + + + +/* +** This is the xSetSystemCall() method of sqlite3_vfs for all of the +** "win32" VFSes. Return SQLITE_OK opon successfully updating the +** system call pointer, or SQLITE_NOTFOUND if there is no configurable +** system call named zName. +*/ +static int rtthreadSetSystemCall( + sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ + const char *zName, /* Name of system call to override */ + sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ +){ + unsigned int i; + int rc = SQLITE_NOTFOUND; + + UNUSED_PARAMETER(pNotUsed); + if( zName==0 ){ + /* If no zName is given, restore all system calls to their default + ** settings and return NULL + */ + rc = SQLITE_OK; + for(i=0; izPath : 0, lineno); + } +} + +/* +** Check a rtthreadFile that is a database. Verify the following: +** +** (1) There is exactly one hard link on the file +** (2) The file is not a symbolic link +** (3) The file has not been renamed or unlinked +** +** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right. +*/ +static void verifyDbFile(rtthreadFile *pFile){ + struct stat buf; + int rc; + if( pFile->ctrlFlags & UNIXFILE_WARNED ){ + /* One or more of the following warnings have already been issued. Do not + ** repeat them so as not to clutter the error log */ + return; + } + rc = osFstat(pFile->h, &buf); + if( rc!=0 ){ + sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath); + pFile->ctrlFlags |= UNIXFILE_WARNED; + return; + } + if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){ + sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath); + pFile->ctrlFlags |= UNIXFILE_WARNED; + return; + } +} + +/* +** This function performs the parts of the "close file" operation +** common to all locking schemes. It closes the directory and file +** handles, if they are valid, and sets all fields of the rtthreadFile +** structure to 0. +** +** It is *not* necessary to hold the mutex when this routine is called, +** even on VxWorks. A mutex will be acquired on VxWorks by the +** vxworksReleaseFileId() routine. +*/ +static int closeRtthreadFile(sqlite3_file *id){ + rtthreadFile *pFile = (rtthreadFile*)id; + if( pFile->h>=0 ){ + robust_close(pFile, pFile->h, __LINE__); + pFile->h = -1; + } + OSTRACE(("CLOSE %-3d\n", pFile->h)); + OpenCounter(-1); + memset(pFile, 0, sizeof(rtthreadFile)); + return SQLITE_OK; +} + +/************** End of the posix advisory lock implementation ***************** +******************************************************************************/ + +/****************************************************************************** +****************************** No-op Locking ********************************** +** +** Of the various locking implementations available, this is by far the +** simplest: locking is ignored. No attempt is made to lock the database +** file for reading or writing. +** +** This locking mode is appropriate for use on read-only databases +** (ex: databases that are burned into CD-ROM, for example.) It can +** also be used if the application employs some external mechanism to +** prevent simultaneous access of the same database by two or more +** database connections. But there is a serious risk of database +** corruption if this locking mode is used in situations where multiple +** database connections are accessing the same database file at the same +** time and one or more of those connections are writing. +*/ + +static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){ + UNUSED_PARAMETER(NotUsed); + *pResOut = 0; + return SQLITE_OK; +} +static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return SQLITE_OK; +} +static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return SQLITE_OK; +} + +/* +** Close the file. +*/ +static int nolockClose(sqlite3_file *id) { + return closeRtthreadFile(id); +} + +/******************* End of the no-op lock implementation ********************* +******************************************************************************/ + +/****************************************************************************** +************************* Begin dot-file Locking ****************************** +** +** The dotfile locking implementation uses the existence of separate lock +** files (really a directory) to control access to the database. This works +** on just about every filesystem imaginable. But there are serious downsides: +** +** (1) There is zero concurrency. A single reader blocks all other +** connections from reading or writing the database. +** +** (2) An application crash or power loss can leave stale lock files +** sitting around that need to be cleared manually. +** +** Nevertheless, a dotlock is an appropriate locking mode for use if no +** other locking strategy is available. +** +** Dotfile locking works by creating a subdirectory in the same directory as +** the database and with the same name but with a ".lock" extension added. +** The existence of a lock directory implies an EXCLUSIVE lock. All other +** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE. +*/ + +/* +** The file suffix added to the data base filename in order to create the +** lock directory. +*/ +#define DOTLOCK_SUFFIX ".lock" + +/* +** Only set the lastErrno if the error code is a real error and not +** a normal expected return code of SQLITE_BUSY or SQLITE_OK +*/ +#define IS_LOCK_ERROR(x) (((x) != SQLITE_OK) && ((x) != SQLITE_BUSY)) + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +** +** In dotfile locking, either a lock exists or it does not. So in this +** variation of CheckReservedLock(), *pResOut is set to true if any lock +** is held on the file and false if the file is unlocked. +*/ +static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { + int rc = SQLITE_OK; + int reserved = 0; + rtthreadFile *pFile = (rtthreadFile*)id; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + + assert( pFile ); + + /* Check if a thread in this process holds such a lock */ + if( pFile->eFileLock>SHARED_LOCK ){ + /* Either this connection or some other connection in the same process + ** holds a lock on the file. No need to check further. */ + reserved = 1; + }else{ + /* The lock is held if and only if the lockfile exists */ + const char *zLockFile = (const char*)pFile->lockingContext; + reserved = 0; + } + OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved)); + *pResOut = reserved; + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +** +** With dotfile locking, we really only support state (4): EXCLUSIVE. +** But we track the other locking levels internally. +*/ +static int dotlockLock(sqlite3_file *id, int eFileLock) { + rtthreadFile *pFile = (rtthreadFile*)id; + char *zLockFile = (char *)pFile->lockingContext; + int rc = SQLITE_OK; + + + /* If we have any lock, then the lock file already exists. All we have + ** to do is adjust our internal record of the lock level. + */ + if( pFile->eFileLock > NO_LOCK ){ + pFile->eFileLock = eFileLock; + return SQLITE_OK; + } + + /* grab an exclusive lock */ + rc = osMkdir(zLockFile, 0777); + if( rc<0 ){ + /* failed to open/create the lock directory */ + int tErrno = errno; + if( EEXIST == tErrno ){ + rc = SQLITE_BUSY; + } else { + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + } + return rc; + } + + /* got it, set the type and return ok */ + pFile->eFileLock = eFileLock; + return rc; +} + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +** +** When the locking level reaches NO_LOCK, delete the lock file. +*/ +static int dotlockUnlock(sqlite3_file *id, int eFileLock) { + rtthreadFile *pFile = (rtthreadFile*)id; + char *zLockFile = (char *)pFile->lockingContext; + int rc; + + assert( pFile ); + OSTRACE(("UNLOCK %d %d was %d tnm=%s (dotlock)\n", pFile->h, eFileLock, + pFile->eFileLock, rt_thread_self()->name )); + assert( eFileLock<=SHARED_LOCK ); + + /* no-op if possible */ + if( pFile->eFileLock==eFileLock ){ + return SQLITE_OK; + } + + /* To downgrade to shared, simply update our internal notion of the + ** lock state. No need to mess with the file on disk. + */ + if( eFileLock==SHARED_LOCK ){ + pFile->eFileLock = SHARED_LOCK; + return SQLITE_OK; + } + + /* To fully unlock the database, delete the lock file */ + assert( eFileLock==NO_LOCK ); + rc = osRmdir(zLockFile); + if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile); + if( rc<0 ){ + int tErrno = errno; + rc = 0; + if( ENOENT != tErrno ){ + rc = SQLITE_IOERR_UNLOCK; + } + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + return rc; + } + pFile->eFileLock = NO_LOCK; + return SQLITE_OK; +} + +/* +** Close a file. Make sure the lock has been released before closing. +*/ +static int dotlockClose(sqlite3_file *id) { + int rc = SQLITE_OK; + if( id ){ + rtthreadFile *pFile = (rtthreadFile*)id; + dotlockUnlock(id, NO_LOCK); + sqlite3_free(pFile->lockingContext); + rc = closeRtthreadFile(id); + } + return rc; +} +/****************** End of the dot-file lock implementation ******************* +******************************************************************************/ + +/****************************************************************************** +************************** Begin flock Locking ******************************** +** +** Use the flock() system call to do file locking. +** +** flock() locking is like dot-file locking in that the various +** fine-grain locking levels supported by SQLite are collapsed into +** a single exclusive lock. In other words, SHARED, RESERVED, and +** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite +** still works when you do this, but concurrency is reduced since +** only a single process can be reading the database at a time. +** +** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if +** compiling for VXWORKS. +*/ +#if SQLITE_ENABLE_LOCKING_STYLE +#warning "rtthread file lock not available" +/* +** Retry flock() calls that fail with EINTR +*/ +static int robust_flock(int fd, int op){ + int rc = 0; + + return rc; +} + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +*/ +static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ + int rc = SQLITE_OK; + int reserved = 0; + rtthreadFile *pFile = (rtthreadFile*)id; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + + assert( pFile ); + + /* Check if a thread in this process holds such a lock */ + if( pFile->eFileLock>SHARED_LOCK ){ + reserved = 1; + } + + /* Otherwise see if some other process holds it. */ + if( !reserved ){ + /* attempt to get the lock */ + int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB); + if( !lrc ){ + /* got the lock, unlock it */ + lrc = robust_flock(pFile->h, LOCK_UN); + if ( lrc ) { + int tErrno = errno; + /* unlock failed with an error */ + lrc = SQLITE_IOERR_UNLOCK; + if( IS_LOCK_ERROR(lrc) ){ + pFile->lastErrno = tErrno; + rc = lrc; + } + } + } else { + int tErrno = errno; + reserved = 1; + /* someone else might have it reserved */ + lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( IS_LOCK_ERROR(lrc) ){ + pFile->lastErrno = tErrno; + rc = lrc; + } + } + } + OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved)); + +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ + rc = SQLITE_OK; + reserved=1; + } +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ + *pResOut = reserved; + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** flock() only really support EXCLUSIVE locks. We track intermediate +** lock states in the sqlite3_file structure, but all locks SHARED or +** above are really EXCLUSIVE locks and exclude all other processes from +** access the file. +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +*/ +static int flockLock(sqlite3_file *id, int eFileLock) { + int rc = SQLITE_OK; + rtthreadFile *pFile = (rtthreadFile*)id; + + assert( pFile ); + + /* if we already have a lock, it is exclusive. + ** Just adjust level and punt on outta here. */ + if (pFile->eFileLock > NO_LOCK) { + pFile->eFileLock = eFileLock; + return SQLITE_OK; + } + + /* grab an exclusive lock */ + + if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) { + int tErrno = errno; + /* didn't get, must be busy */ + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + } else { + /* got it, set the type and return ok */ + pFile->eFileLock = eFileLock; + } + OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), + rc==SQLITE_OK ? "ok" : "failed")); +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ + rc = SQLITE_BUSY; + } +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ + return rc; +} + + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +*/ +static int flockUnlock(sqlite3_file *id, int eFileLock) { + rtthreadFile *pFile = (rtthreadFile*)id; + + assert( pFile ); + OSTRACE(("UNLOCK %d %d was %d tnm=%s (flock)\n", pFile->h, eFileLock, + pFile->eFileLock, rt_thread_self()->name)); + assert( eFileLock<=SHARED_LOCK ); + + /* no-op if possible */ + if( pFile->eFileLock==eFileLock ){ + return SQLITE_OK; + } + + /* shared can just be set because we always have an exclusive */ + if (eFileLock==SHARED_LOCK) { + pFile->eFileLock = eFileLock; + return SQLITE_OK; + } + + /* no, really, unlock. */ + if( robust_flock(pFile->h, LOCK_UN) ){ +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + return SQLITE_OK; +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ + return SQLITE_IOERR_UNLOCK; + }else{ + pFile->eFileLock = NO_LOCK; + return SQLITE_OK; + } +} + +/* +** Close a file. +*/ +static int flockClose(sqlite3_file *id) { + int rc = SQLITE_OK; + if( id ){ + flockUnlock(id, NO_LOCK); + rc = closeRtthreadFile(id); + } + return rc; +} + +#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */ + +/******************* End of the flock lock implementation ********************* +******************************************************************************/ + +/****************************************************************************** +**************** Non-locking sqlite3_file methods ***************************** +** +** The next division contains implementations for all methods of the +** sqlite3_file object other than the locking methods. The locking +** methods were defined in divisions above (one locking method per +** division). Those methods that are common to all locking modes +** are gather together into this division. +*/ + +/* +** Seek to the offset passed as the second argument, then read cnt +** bytes into pBuf. Return the number of bytes actually read. +** +** NB: If you define USE_PREAD or USE_PREAD64, then it might also +** be necessary to define _XOPEN_SOURCE to be 500. This varies from +** one system to another. Since SQLite does not define USE_PREAD +** any any form by default, we will not attempt to define _XOPEN_SOURCE. +** See tickets #2741 and #2681. +** +** To avoid stomping the errno value on a failed read the lastErrno value +** is set before returning. +*/ +static int seekAndRead(rtthreadFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ + int got; + int prior = 0; +#if (!defined(USE_PREAD) && !defined(USE_PREAD64)) + i64 newOffset; +#endif + TIMER_START; + assert( cnt==(cnt&0x1ffff) ); + assert( id->h>2 ); + cnt &= 0x1ffff; + do{ +#if defined(USE_PREAD) + #error "rtthread pread not support" + got = osPread(id->h, pBuf, cnt, offset); + SimulateIOError( got = -1 ); +#elif defined(USE_PREAD64) + #error "rtthread pread64 not support" + got = osPread64(id->h, pBuf, cnt, offset); + SimulateIOError( got = -1 ); +#else + newOffset = lseek(id->h, offset, SEEK_SET); + SimulateIOError( newOffset-- ); + if( newOffset!=offset ){ + if( newOffset == -1 ){ + ((rtthreadFile*)id)->lastErrno = errno; + }else{ + ((rtthreadFile*)id)->lastErrno = 0; + } + return -1; + } + got = osRead(id->h, pBuf, cnt); +#endif + if( got==cnt ) break; + if( got<0 ){ + if( errno==EINTR ){ got = 1; continue; } + prior = 0; + ((rtthreadFile*)id)->lastErrno = errno; + break; + }else if( got>0 ){ + cnt -= got; + offset += got; + prior += got; + pBuf = (void*)(got + (char*)pBuf); + } + }while( got>0 ); + TIMER_END; + OSTRACE(("READ %-3d %5d %7lld %llu\n", + id->h, got+prior, offset-prior, TIMER_ELAPSED)); + return got+prior; +} + +/* +** Read data from a file into a buffer. Return SQLITE_OK if all +** bytes were read successfully and SQLITE_IOERR if anything goes +** wrong. +*/ +static int rtthreadRead( + sqlite3_file *id, + void *pBuf, + int amt, + sqlite3_int64 offset +){ + rtthreadFile *pFile = (rtthreadFile *)id; + int got; + assert( id ); + assert( offset>=0 ); + assert( amt>0 ); + + got = seekAndRead(pFile, offset, pBuf, amt); + if( got==amt ){ + return SQLITE_OK; + }else if( got<0 ){ + /* lastErrno set by seekAndRead */ + return SQLITE_IOERR_READ; + }else{ + pFile->lastErrno = 0; /* not a system error */ + /* Unread parts of the buffer must be zero-filled */ + memset(&((char*)pBuf)[got], 0, amt-got); + return SQLITE_IOERR_SHORT_READ; + } +} + +/* +** Attempt to seek the file-descriptor passed as the first argument to +** absolute offset iOff, then attempt to write nBuf bytes of data from +** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, +** return the actual number of bytes written (which may be less than +** nBuf). +*/ +static int seekAndWriteFd( + int fd, /* File descriptor to write to */ + i64 iOff, /* File offset to begin writing at */ + const void *pBuf, /* Copy data from this buffer to the file */ + int nBuf, /* Size of buffer pBuf in bytes */ + int *piErrno /* OUT: Error number if error occurs */ +){ + int rc = 0; /* Value returned by system call */ + + assert( nBuf==(nBuf&0x1ffff) ); + assert( fd>2 ); + nBuf &= 0x1ffff; + TIMER_START; + +#if defined(USE_PREAD) + do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR ); +#elif defined(USE_PREAD64) + do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR); +#else + do{ + i64 iSeek = lseek(fd, iOff, SEEK_SET); + SimulateIOError( iSeek-- ); + + if( iSeek!=iOff ){ + if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0); + return -1; + } + rc = osWrite(fd, pBuf, nBuf); + }while( rc<0 && errno==EINTR ); +#endif + + TIMER_END; + OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED)); + + if( rc<0 && piErrno ) *piErrno = errno; + return rc; +} + + +/* +** Seek to the offset in id->offset then read cnt bytes into pBuf. +** Return the number of bytes actually read. Update the offset. +** +** To avoid stomping the errno value on a failed write the lastErrno value +** is set before returning. +*/ +static int seekAndWrite(rtthreadFile *id, i64 offset, const void *pBuf, int cnt){ + return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno); +} + + +/* +** Write data from a buffer into a file. Return SQLITE_OK on success +** or some other error code on failure. +*/ +static int rtthreadWrite( + sqlite3_file *id, + const void *pBuf, + int amt, + sqlite3_int64 offset +){ + rtthreadFile *pFile = (rtthreadFile*)id; + int wrote = 0; + assert( id ); + assert( amt>0 ); + +#ifdef SQLITE_DEBUG + /* If we are doing a normal write to a database file (as opposed to + ** doing a hot-journal rollback or a write to some file other than a + ** normal database file) then record the fact that the database + ** has changed. If the transaction counter is modified, record that + ** fact too. + */ + if( pFile->inNormalWrite ){ + pFile->dbUpdate = 1; /* The database has been modified */ + if( offset<=24 && offset+amt>=27 ){ + int rc; + char oldCntr[4]; + SimulateIOErrorBenign(1); + rc = seekAndRead(pFile, 24, oldCntr, 4); + SimulateIOErrorBenign(0); + if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){ + pFile->transCntrChng = 1; /* The transaction counter has changed */ + } + } + } +#endif + + while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){ + amt -= wrote; + offset += wrote; + pBuf = &((char*)pBuf)[wrote]; + } + SimulateIOError(( wrote=(-1), amt=1 )); + SimulateDiskfullError(( wrote=0, amt=1 )); + + if( amt>0 ){ + if( wrote<0 && pFile->lastErrno!=ENOSPC ){ + /* lastErrno set by seekAndWrite */ + return SQLITE_IOERR_WRITE; + }else{ + pFile->lastErrno = 0; /* not a system error */ + return SQLITE_FULL; + } + } + + return SQLITE_OK; +} + +#ifdef SQLITE_TEST +/* +** Count the number of fullsyncs and normal syncs. This is used to test +** that syncs and fullsyncs are occurring at the right times. +*/ +int sqlite3_sync_count = 0; +int sqlite3_fullsync_count = 0; +#endif + +/* +** We do not trust systems to provide a working fdatasync(). Some do. +** Others do no. To be safe, we will stick with the (slightly slower) +** fsync(). If you know that your system does support fdatasync() correctly, +** then simply compile with -Dfdatasync=fdatasync +*/ +#if !defined(fdatasync) +#include "dfs.h" +#include "dfs_file.h" +int fdatasync(fd) +{ + struct dfs_fd *dfs_fd; + dfs_fd = fd_get(fd); + return dfs_file_flush(dfs_fd); +} +#endif + +/* +** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not +** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently +** only available on Mac OS X. But that could change. +*/ +#ifdef F_FULLFSYNC +# define HAVE_FULLFSYNC 0 +#endif + + +/* +** The fsync() system call does not work as advertised on many +** unix systems. The following procedure is an attempt to make +** it work better. +** +** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful +** for testing when we want to run through the test suite quickly. +** You are strongly advised *not* to deploy with SQLITE_NO_SYNC +** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash +** or power failure will likely corrupt the database file. +** +** SQLite sets the dataOnly flag if the size of the file is unchanged. +** The idea behind dataOnly is that it should only write the file content +** to disk, not the inode. We only set dataOnly if the file size is +** unchanged since the file size is part of the inode. However, +** Ted Ts'o tells us that fdatasync() will also write the inode if the +** file size has changed. The only real difference between fdatasync() +** and fsync(), Ted tells us, is that fdatasync() will not flush the +** inode if the mtime or owner or other inode attributes have changed. +** We only care about the file size, not the other file attributes, so +** as far as SQLite is concerned, an fdatasync() is always adequate. +** So, we always use fdatasync() if it is available, regardless of +** the value of the dataOnly flag. +*/ +static int full_fsync(int fd, int fullSync, int dataOnly){ + int rc; + + /* The following "ifdef/elif/else/" block has the same structure as + ** the one below. It is replicated here solely to avoid cluttering + ** up the real code with the UNUSED_PARAMETER() macros. + */ +#ifdef SQLITE_NO_SYNC + UNUSED_PARAMETER(fd); + UNUSED_PARAMETER(fullSync); + UNUSED_PARAMETER(dataOnly); +#elif HAVE_FULLFSYNC + UNUSED_PARAMETER(dataOnly); +#else + UNUSED_PARAMETER(fullSync); + UNUSED_PARAMETER(dataOnly); +#endif + + /* Record the number of times that we do a normal fsync() and + ** FULLSYNC. This is used during testing to verify that this procedure + ** gets called with the correct arguments. + */ +#ifdef SQLITE_TEST + if( fullSync ) sqlite3_fullsync_count++; + sqlite3_sync_count++; +#endif + + /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a + ** no-op + */ +#ifdef SQLITE_NO_SYNC + rc = SQLITE_OK; +#elif HAVE_FULLFSYNC + #error "rtthread not support FULLFSYNC" +#else + rc = fdatasync(fd); +#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */ + + return rc; +} + +/* +** Make sure all writes to a particular file are committed to disk. +** +** If dataOnly==0 then both the file itself and its metadata (file +** size, access time, etc) are synced. If dataOnly!=0 then only the +** file data is synced. +** +** Under Rtthread, also make sure that the directory entry for the file +** has been created by fsync-ing the directory that contains the file. +** If we do not do this and we encounter a power failure, the directory +** entry for the journal might not exist after we reboot. The next +** SQLite to access the file will not know that the journal exists (because +** the directory entry for the journal was never created) and the transaction +** will not roll back - possibly leading to database corruption. +*/ +static int rtthreadSync(sqlite3_file *id, int flags){ + int rc; + rtthreadFile *pFile = (rtthreadFile*)id; + + int isDataOnly = (flags&SQLITE_SYNC_DATAONLY); + int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL; + + /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ + assert((flags&0x0F)==SQLITE_SYNC_NORMAL + || (flags&0x0F)==SQLITE_SYNC_FULL + ); + + /* Rtthread cannot, but some systems may return SQLITE_FULL from here. This + ** line is to test that doing so does not cause any problems. + */ + SimulateDiskfullError( return SQLITE_FULL ); + + assert( pFile ); + OSTRACE(("SYNC %-3d\n", pFile->h)); + rc = full_fsync(pFile->h, isFullsync, isDataOnly); + SimulateIOError( rc=1 ); + if( rc ){ + pFile->lastErrno = errno; + return rtthreadLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath); + } + + /* Also fsync the directory containing the file if the DIRSYNC flag + ** is set. This is a one-time occurrence. Many systems (examples: AIX) + ** are unable to fsync a directory, so ignore errors on the fsync. + */ + if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){ + int dirfd; + OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath, + HAVE_FULLFSYNC, isFullsync)); + rc = osOpenDirectory(pFile->zPath, &dirfd); + if( rc==SQLITE_OK && dirfd>=0 ){ + full_fsync(dirfd, 0, 0); + robust_close(pFile, dirfd, __LINE__); + }else if( rc==SQLITE_CANTOPEN ){ + rc = SQLITE_OK; + } + pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC; + } + return rc; +} + +/* +** Truncate an open file to a specified size +*/ +static int rtthreadTruncate(sqlite3_file *id, i64 nByte){ + rtthreadFile *pFile = (rtthreadFile *)id; + int rc; + assert( pFile ); + SimulateIOError( return SQLITE_IOERR_TRUNCATE ); + + /* If the user has configured a chunk-size for this file, truncate the + ** file so that it consists of an integer number of chunks (i.e. the + ** actual file size after the operation may be larger than the requested + ** size). + */ + if( pFile->szChunk>0 ){ + nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; + } + + rc = robust_ftruncate(pFile->h, (off_t)nByte); + if( rc ){ + pFile->lastErrno = errno; + return rtthreadLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); + }else{ +#ifdef SQLITE_DEBUG + /* If we are doing a normal write to a database file (as opposed to + ** doing a hot-journal rollback or a write to some file other than a + ** normal database file) and we truncate the file to zero length, + ** that effectively updates the change counter. This might happen + ** when restoring a database using the backup API from a zero-length + ** source. + */ + if( pFile->inNormalWrite && nByte==0 ){ + pFile->transCntrChng = 1; + } +#endif + + return SQLITE_OK; + } +} + +/* +** Determine the current size of a file in bytes +*/ +static int rtthreadFileSize(sqlite3_file *id, i64 *pSize){ + int rc; + struct stat buf; + assert( id ); + rc = osFstat(((rtthreadFile*)id)->h, &buf); + SimulateIOError( rc=1 ); + if( rc!=0 ){ + ((rtthreadFile*)id)->lastErrno = errno; + return SQLITE_IOERR_FSTAT; + } + *pSize = buf.st_size; + + /* When opening a zero-size database, the findInodeInfo() procedure + ** writes a single byte into that file in order to work around a bug + ** in the OS-X msdos filesystem. In order to avoid problems with upper + ** layers, we need to report this file size as zero even though it is + ** really 1. Ticket #3260. + */ + if( *pSize==1 ) *pSize = 0; + + + return SQLITE_OK; +} + +/* +** This function is called to handle the SQLITE_FCNTL_SIZE_HINT +** file-control operation. Enlarge the database to nBytes in size +** (rounded up to the next chunk-size). If the database is already +** nBytes or larger, this routine is a no-op. +*/ +static int fcntlSizeHint(rtthreadFile *pFile, i64 nByte){ + if( pFile->szChunk>0 ){ + i64 nSize; /* Required file size */ + struct stat buf; /* Used to hold return values of fstat() */ + + if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT; + + nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk; + if( nSize>(i64)buf.st_size ){ + /* If the OS does not have posix_fallocate(), fake it. First use + ** ftruncate() to set the file size, then write a single byte to + ** the last byte in each block within the extended region. This + ** is the same technique used by glibc to implement posix_fallocate() + ** on systems that do not have a real fallocate() system call. + */ + int nBlk = buf.st_blksize; /* File-system block size */ + i64 iWrite; /* Next offset to write to */ + + if( robust_ftruncate(pFile->h, nSize) ){ + pFile->lastErrno = errno; + return rtthreadLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); + } + iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1; + while( iWritectrlFlags is set. +** +** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. +*/ +static void rtthreadModeBit(rtthreadFile *pFile, unsigned char mask, int *pArg){ + if( *pArg<0 ){ + *pArg = (pFile->ctrlFlags & mask)!=0; + }else if( (*pArg)==0 ){ + pFile->ctrlFlags &= ~mask; + }else{ + pFile->ctrlFlags |= mask; + } +} + +/* Forward declaration */ +static int rtthreadGetTempname(int nBuf, char *zBuf); + +/* +** Information and control of an open file handle. +*/ +static int rtthreadFileControl(sqlite3_file *id, int op, void *pArg){ + rtthreadFile *pFile = (rtthreadFile*)id; + switch( op ){ + case SQLITE_FCNTL_LOCKSTATE: { + *(int*)pArg = pFile->eFileLock; + return SQLITE_OK; + } + case SQLITE_LAST_ERRNO: { + *(int*)pArg = pFile->lastErrno; + return SQLITE_OK; + } + case SQLITE_FCNTL_CHUNK_SIZE: { + pFile->szChunk = *(int *)pArg; + return SQLITE_OK; + } + case SQLITE_FCNTL_SIZE_HINT: { + int rc; + SimulateIOErrorBenign(1); + rc = fcntlSizeHint(pFile, *(i64 *)pArg); + SimulateIOErrorBenign(0); + return rc; + } + case SQLITE_FCNTL_PERSIST_WAL: { + rtthreadModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg); + return SQLITE_OK; + } + case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { + rtthreadModeBit(pFile, UNIXFILE_PSOW, (int*)pArg); + return SQLITE_OK; + } + case SQLITE_FCNTL_VFSNAME: { + *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); + return SQLITE_OK; + } + case SQLITE_FCNTL_TEMPFILENAME: { + char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname ); + if( zTFile ){ + rtthreadGetTempname(pFile->pVfs->mxPathname, zTFile); + *(char**)pArg = zTFile; + } + return SQLITE_OK; + } +#ifdef SQLITE_DEBUG + /* The pager calls this method to signal that it has done + ** a rollback and that the database is therefore unchanged and + ** it hence it is OK for the transaction change counter to be + ** unchanged. + */ + case SQLITE_FCNTL_DB_UNCHANGED: { + ((rtthreadFile*)id)->dbUpdate = 0; + return SQLITE_OK; + } +#endif + } + return SQLITE_NOTFOUND; +} + +/* +** Return the sector size in bytes of the underlying block device for +** the specified file. This is almost always 512 bytes, but may be +** larger for some devices. +** +** SQLite code assumes this function cannot fail. It also assumes that +** if two files are created in the same file-system directory (i.e. +** a database and its journal file) that the sector size will be the +** same for both. +*/ +static int rtthreadSectorSize(sqlite3_file *NotUsed){ + UNUSED_PARAMETER(NotUsed); + return SQLITE_DEFAULT_SECTOR_SIZE; +} + + +/* +** Return the device characteristics for the file. +** +** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default. +** However, that choice is contraversial since technically the underlying +** file system does not always provide powersafe overwrites. (In other +** words, after a power-loss event, parts of the file that were never +** written might end up being altered.) However, non-PSOW behavior is very, +** very rare. And asserting PSOW makes a large reduction in the amount +** of required I/O for journaling, since a lot of padding is eliminated. +** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control +** available to turn it off and URI query parameter available to turn it off. +*/ +static int rtthreadDeviceCharacteristics(sqlite3_file *id){ + rtthreadFile *p = (rtthreadFile*)id; + int rc = 0; + + if( p->ctrlFlags & UNIXFILE_PSOW ){ + rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; + } + return rc; +} + +#ifndef SQLITE_OMIT_WAL +# error "WAL mode requires not support from the rt-thread, compile\ + with SQLITE_OMIT_WAL." +#else +# define rtthreadShmMap 0 +# define rtthreadShmLock 0 +# define rtthreadShmBarrier 0 +# define rtthreadShmUnmap 0 +#endif /* #ifndef SQLITE_OMIT_WAL */ + +#if SQLITE_MAX_MMAP_SIZE>0 +#error "rtthread not spportt mmap" +#endif /* SQLITE_MAX_MMAP_SIZE>0 */ + +/* +** If possible, return a pointer to a mapping of file fd starting at offset +** iOff. The mapping must be valid for at least nAmt bytes. +** +** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. +** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. +** Finally, if an error does occur, return an SQLite error code. The final +** value of *pp is undefined in this case. +** +** If this function does return a pointer, the caller must eventually +** release the reference by calling unixUnfetch(). +*/ +static int rtthreadFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ + + *pp = 0; + + return SQLITE_OK; +} + +/* +** If the third argument is non-NULL, then this function releases a +** reference obtained by an earlier call to unixFetch(). The second +** argument passed to this function must be the same as the corresponding +** argument that was passed to the unixFetch() invocation. +** +** Or, if the third argument is NULL, then this function is being called +** to inform the VFS layer that, according to POSIX, any existing mapping +** may now be invalid and should be unmapped. +*/ +static int rtthreadUnfetch(sqlite3_file *fd, i64 iOff, void *p){ + rtthreadFile *pFd = (rtthreadFile *)fd; /* The underlying database file */ + UNUSED_PARAMETER(iOff); + + return SQLITE_OK; +} + +/* +** Here ends the implementation of all sqlite3_file methods. +** +********************** End sqlite3_file Methods ******************************* +******************************************************************************/ + +/* +** This division contains definitions of sqlite3_io_methods objects that +** implement various file locking strategies. It also contains definitions +** of "finder" functions. A finder-function is used to locate the appropriate +** sqlite3_io_methods object for a particular database file. The pAppData +** field of the sqlite3_vfs VFS objects are initialized to be pointers to +** the correct finder-function for that VFS. +** +** Most finder functions return a pointer to a fixed sqlite3_io_methods +** object. The only interesting finder-function is autolockIoFinder, which +** looks at the filesystem type and tries to guess the best locking +** strategy from that. +** +** For finder-funtion F, two objects are created: +** +** (1) The real finder-function named "FImpt()". +** +** (2) A constant pointer to this function named just "F". +** +** +** A pointer to the F pointer is used as the pAppData value for VFS +** objects. We have to do this instead of letting pAppData point +** directly at the finder-function since C90 rules prevent a void* +** from be cast into a function pointer. +** +** +** Each instance of this macro generates two objects: +** +** * A constant sqlite3_io_methods object call METHOD that has locking +** methods CLOSE, LOCK, UNLOCK, CKRESLOCK. +** +** * An I/O method finder function called FINDER that returns a pointer +** to the METHOD object in the previous bullet. +*/ +#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \ +static const sqlite3_io_methods METHOD = { \ + VERSION, /* iVersion */ \ + CLOSE, /* xClose */ \ + rtthreadRead, /* xRead */ \ + rtthreadWrite, /* xWrite */ \ + rtthreadTruncate, /* xTruncate */ \ + rtthreadSync, /* xSync */ \ + rtthreadFileSize, /* xFileSize */ \ + LOCK, /* xLock */ \ + UNLOCK, /* xUnlock */ \ + CKLOCK, /* xCheckReservedLock */ \ + rtthreadFileControl, /* xFileControl */ \ + rtthreadSectorSize, /* xSectorSize */ \ + rtthreadDeviceCharacteristics, /* xDeviceCapabilities */ \ + rtthreadShmMap, /* xShmMap */ \ + rtthreadShmLock, /* xShmLock */ \ + rtthreadShmBarrier, /* xShmBarrier */ \ + rtthreadShmUnmap, /* xShmUnmap */ \ + rtthreadFetch, /* xFetch */ \ + rtthreadUnfetch, /* xUnfetch */ \ +}; \ +static const sqlite3_io_methods *FINDER##Impl(const char *z, rtthreadFile *p){ \ + UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \ + return &METHOD; \ +} \ +static const sqlite3_io_methods *(*const FINDER)(const char*,rtthreadFile *p) \ + = FINDER##Impl; + +/* +** Here are all of the sqlite3_io_methods objects for each of the +** locking strategies. Functions that return pointers to these methods +** are also created. +*/ +IOMETHODS( + nolockIoFinder, /* Finder function name */ + nolockIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + nolockClose, /* xClose method */ + nolockLock, /* xLock method */ + nolockUnlock, /* xUnlock method */ + nolockCheckReservedLock /* xCheckReservedLock method */ +) +IOMETHODS( + dotlockIoFinder, /* Finder function name */ + dotlockIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + dotlockClose, /* xClose method */ + dotlockLock, /* xLock method */ + dotlockUnlock, /* xUnlock method */ + dotlockCheckReservedLock /* xCheckReservedLock method */ +) + +#if SQLITE_ENABLE_LOCKING_STYLE +IOMETHODS( + flockIoFinder, /* Finder function name */ + flockIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + flockClose, /* xClose method */ + flockLock, /* xLock method */ + flockUnlock, /* xUnlock method */ + flockCheckReservedLock /* xCheckReservedLock method */ +) +#endif + +/* +** An abstract type for a pointer to a IO method finder function: +*/ +typedef const sqlite3_io_methods *(*finder_type)(const char*,rtthreadFile*); + + +/**************************************************************************** +**************************** sqlite3_vfs methods **************************** +** +** This division contains the implementation of methods on the +** sqlite3_vfs object. +*/ + +/* +** Initialize the contents of the rtthreadFile structure pointed to by pId. +*/ +static int fillInRtthreadFile( + sqlite3_vfs *pVfs, /* Pointer to vfs object */ + int h, /* Open file descriptor of file being opened */ + sqlite3_file *pId, /* Write to the rtthreadFile structure here */ + const char *zFilename, /* Name of the file being opened */ + int ctrlFlags /* Zero or more UNIXFILE_* values */ +){ + const sqlite3_io_methods *pLockingStyle; + rtthreadFile *pNew = (rtthreadFile *)pId; + int rc = SQLITE_OK; + + assert( pNew->pInode==NULL ); + + /* Usually the path zFilename should not be a relative pathname. The + ** exception is when opening the proxy "conch" file in builds that + ** include the special Apple locking styles. + */ + assert( zFilename==0 || zFilename[0]=='/' ); + + /* No locking occurs in temporary files */ + assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 ); + + OSTRACE(("OPEN %-3d %s\n", h, zFilename)); + pNew->h = h; + pNew->pVfs = pVfs; + pNew->zPath = zFilename; + pNew->ctrlFlags = (u8)ctrlFlags; + if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0), + "psow", SQLITE_POWERSAFE_OVERWRITE) ){ + pNew->ctrlFlags |= UNIXFILE_PSOW; + } + if( strcmp(pVfs->zName,"unix-excl")==0 ){ + pNew->ctrlFlags |= UNIXFILE_EXCL; + } + + if( ctrlFlags & UNIXFILE_NOLOCK ){ + pLockingStyle = &nolockIoMethods; + }else{ + pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); +#if SQLITE_ENABLE_LOCKING_STYLE + /* Cache zFilename in the locking context (AFP and dotlock override) for + ** proxyLock activation is possible (remote proxy is based on db name) + ** zFilename remains valid until file is closed, to support */ + pNew->lockingContext = (void*)zFilename; +#endif + } + + if( pLockingStyle == &dotlockIoMethods ){ + /* Dotfile locking uses the file path so it needs to be included in + ** the dotlockLockingContext + */ + char *zLockFile; + int nFilename; + assert( zFilename!=0 ); + nFilename = (int)strlen(zFilename) + 6; + zLockFile = (char *)sqlite3_malloc(nFilename); + if( zLockFile==0 ){ + rc = SQLITE_NOMEM; + }else{ + sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); + } + pNew->lockingContext = zLockFile; + } + + pNew->lastErrno = 0; + if( rc!=SQLITE_OK ){ + if( h>=0 ) robust_close(pNew, h, __LINE__); + }else{ + pNew->pMethod = pLockingStyle; + OpenCounter(+1); + verifyDbFile(pNew); + } + return rc; +} + +/* +** Return the name of a directory in which to put temporary files. +** If no suitable temporary file directory can be found, return NULL. +*/ +static const char* rtthreadTempFileDir(void){ + static const char *azDirs[] = { + 0, + "/sql", + "/sql/tmp" + "/tmp", + 0 /* List terminator */ + }; + unsigned int i; + struct stat buf; + const char *zDir = 0; + + azDirs[0] = sqlite3_temp_directory; + + for(i=0; imxPathname bytes. +*/ +static int rtthreadGetTempname(int nBuf, char *zBuf){ + static const unsigned char zChars[] = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"; + unsigned int i, j; + const char *zDir; + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. + */ + SimulateIOError( return SQLITE_IOERR ); + + zDir = rtthreadTempFileDir(); + if( zDir==0 ) zDir = "."; + + /* Check that the output buffer is large enough for the temporary file + ** name. If it is not, return SQLITE_ERROR. + */ + if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){ + return SQLITE_ERROR; + } + + do{ + sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir); + j = (int)strlen(zBuf); + sqlite3_randomness(15, &zBuf[j]); + for(i=0; i<15; i++, j++){ + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; + } + zBuf[j] = 0; + zBuf[j+1] = 0; + }while( osAccess(zBuf,0)==0 ); + return SQLITE_OK; +} + +/* +** Open the file zPath. +** +** Previously, the SQLite OS layer used three functions in place of this +** one: +** +** sqlite3OsOpenReadWrite(); +** sqlite3OsOpenReadOnly(); +** sqlite3OsOpenExclusive(); +** +** These calls correspond to the following combinations of flags: +** +** ReadWrite() -> (READWRITE | CREATE) +** ReadOnly() -> (READONLY) +** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE) +** +** The old OpenExclusive() accepted a boolean argument - "delFlag". If +** true, the file was configured to be automatically deleted when the +** file handle closed. To achieve the same effect using this new +** interface, add the DELETEONCLOSE flag to those specified above for +** OpenExclusive(). +*/ +static int rtthreadOpen( + sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ + const char *zPath, /* Pathname of file to be opened */ + sqlite3_file *pFile, /* The file descriptor to be filled in */ + int flags, /* Input flags to control the opening */ + int *pOutFlags /* Output flags returned to SQLite core */ +){ + rtthreadFile *p = (rtthreadFile *)pFile; + int fd = -1; /* File descriptor returned by open() */ + int openFlags = 0; /* Flags to pass to open() */ + int eType = flags&0xFFFFFF00; /* Type of file to open */ + int noLock; /* True to omit locking primitives */ + int rc = SQLITE_OK; /* Function Return Code */ + int ctrlFlags = 0; /* UNIXFILE_* flags */ + + int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); + int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); + int isCreate = (flags & SQLITE_OPEN_CREATE); + int isReadonly = (flags & SQLITE_OPEN_READONLY); + int isReadWrite = (flags & SQLITE_OPEN_READWRITE); +#if SQLITE_ENABLE_LOCKING_STYLE + int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY); +#endif + + /* If creating a master or main-file journal, this function will open + ** a file-descriptor on the directory too. The first time unixSync() + ** is called the directory file descriptor will be fsync()ed and close()d. + */ + int syncDir = (isCreate && ( + eType==SQLITE_OPEN_MASTER_JOURNAL + || eType==SQLITE_OPEN_MAIN_JOURNAL + || eType==SQLITE_OPEN_WAL + )); + + /* If argument zPath is a NULL pointer, this function is required to open + ** a temporary file. Use this buffer to store the file name in. + */ + char zTmpname[MAX_PATHNAME+2]; + const char *zName = zPath; + + /* Check the following statements are true: + ** + ** (a) Exactly one of the READWRITE and READONLY flags must be set, and + ** (b) if CREATE is set, then READWRITE must also be set, and + ** (c) if EXCLUSIVE is set, then CREATE must also be set. + ** (d) if DELETEONCLOSE is set, then CREATE must also be set. + */ + assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); + assert(isCreate==0 || isReadWrite); + assert(isExclusive==0 || isCreate); + assert(isDelete==0 || isCreate); + + /* The main DB, main journal, WAL file and master journal are never + ** automatically deleted. Nor are they ever temporary files. */ + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); + + /* Assert that the upper layer has set one of the "file-type" flags. */ + assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB + || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL + || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL + || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL + ); + + memset(p, 0, sizeof(rtthreadFile)); + if( !zName ){ + /* If zName is NULL, the upper layer is requesting a temp file. */ + assert(isDelete && !syncDir); + rc = rtthreadGetTempname(MAX_PATHNAME+2, zTmpname); + if( rc!=SQLITE_OK ){ + return rc; + } + zName = zTmpname; + + /* Generated temporary filenames are always double-zero terminated + ** for use by sqlite3_uri_parameter(). */ + assert( zName[strlen(zName)+1]==0 ); + } + + /* Determine the value of the flags parameter passed to POSIX function + ** open(). These must be calculated even if open() is not called, as + ** they may be stored as part of the file handle and used by the + ** 'conch file' locking functions later on. */ + if( isReadonly ) openFlags |= O_RDONLY; + if( isReadWrite ) openFlags |= O_RDWR; + if( isCreate ) openFlags |= O_CREAT; + if( isExclusive ) openFlags |= (O_EXCL|0/*O_NOFOLLOW8*/); + openFlags |= (0/*O_LARGEFILE*/|O_BINARY); + + if( fd<0 ){ + mode_t openMode = 0; /* Permissions to create file with */ + + fd = robust_open(zName, openFlags, openMode); + OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); + if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){ + /* Failed to open the file for read/write access. Try read-only. */ + flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); + openFlags &= ~(O_RDWR|O_CREAT); + flags |= SQLITE_OPEN_READONLY; + openFlags |= O_RDONLY; + isReadonly = 1; + fd = robust_open(zName, openFlags, openMode); + } + if( fd<0 ){ + rc = rtthreadLogError(SQLITE_CANTOPEN_BKPT, "open", zName); + goto open_finished; + } + } + assert( fd>=0 ); + if( pOutFlags ){ + *pOutFlags = flags; + } + + if( isDelete ){ + osUnlink(zName); + } +#if SQLITE_ENABLE_LOCKING_STYLE + else{ + p->openFlags = openFlags; + } +#endif + + noLock = eType!=SQLITE_OPEN_MAIN_DB; + + /* Set up appropriate ctrlFlags */ + if( isDelete ) ctrlFlags |= UNIXFILE_DELETE; + if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY; + if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK; + if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC; + if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI; + + rc = fillInRtthreadFile(pVfs, fd, pFile, zPath, ctrlFlags); + +open_finished: + + return rc; +} + + +/* +** Delete the file at zPath. If the dirSync argument is true, fsync() +** the directory after deleting the file. +*/ +static int rtthreadDelete( + sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ + const char *zPath, /* Name of file to be deleted */ + int dirSync /* If true, fsync() directory after deleting file */ +){ + int rc = SQLITE_OK; + UNUSED_PARAMETER(NotUsed); + SimulateIOError(return SQLITE_IOERR_DELETE); + if( osUnlink(zPath)==(-1) ){ + if( errno==ENOENT ){ + rc = SQLITE_IOERR_DELETE_NOENT; + }else{ + rc = rtthreadLogError(SQLITE_IOERR_DELETE, "unlink", zPath); + } + return rc; + } +#ifndef SQLITE_DISABLE_DIRSYNC + if( (dirSync & 1)!=0 ){ + int fd; + rc = osOpenDirectory(zPath, &fd); + if( rc==SQLITE_OK ){ + robust_close(0, fd, __LINE__); + }else if( rc==SQLITE_CANTOPEN ){ + rc = SQLITE_OK; + } + } +#endif + return rc; +} + +/* +** Test the existence of or access permissions of file zPath. The +** test performed depends on the value of flags: +** +** SQLITE_ACCESS_EXISTS: Return 1 if the file exists +** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable. +** SQLITE_ACCESS_READONLY: Return 1 if the file is readable. +** +** Otherwise return 0. +*/ +static int rtthreadAccess( + sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ + const char *zPath, /* Path of the file to examine */ + int flags, /* What do we want to learn about the zPath file? */ + int *pResOut /* Write result boolean here */ +){ + int amode = 0; + UNUSED_PARAMETER(NotUsed); + SimulateIOError( return SQLITE_IOERR_ACCESS; ); + switch( flags ){ + case SQLITE_ACCESS_EXISTS: + amode = F_OK; + break; + case SQLITE_ACCESS_READWRITE: + amode = W_OK|R_OK; + break; + case SQLITE_ACCESS_READ: + amode = R_OK; + break; + + default: + assert(!"Invalid flags argument"); + } + *pResOut = (osAccess(zPath, amode)==0); + if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){ + struct stat buf; + if( 0==osStat(zPath, &buf) && buf.st_size==0 ){ + *pResOut = 0; + } + } + return SQLITE_OK; +} + + +/* +** Turn a relative pathname into a full pathname. The relative path +** is stored as a nul-terminated string in the buffer pointed to by +** zPath. +** +** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes +** (in this case, MAX_PATHNAME bytes). The full-path is written to +** this buffer before returning. +*/ +static int rtthreadFullPathname( + sqlite3_vfs *pVfs, /* Pointer to vfs object */ + const char *zPath, /* Possibly relative input path */ + int nOut, /* Size of output buffer in bytes */ + char *zOut /* Output buffer */ +){ + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. This function could fail if, for example, the + ** current working directory has been unlinked. + */ + SimulateIOError( return SQLITE_ERROR ); + + assert( pVfs->mxPathname==MAX_PATHNAME ); + UNUSED_PARAMETER(pVfs); + + zOut[nOut-1] = '\0'; + if( zPath[0]=='/' ){ + sqlite3_snprintf(nOut, zOut, "%s", zPath); + }else{ + int nCwd; + if( osGetcwd(zOut, nOut-1)==0 ){ + return rtthreadLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath); + } + nCwd = (int)strlen(zOut); + sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath); + } + return SQLITE_OK; +} + + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +# error "rtthread not support load extension, compile with SQLITE_OMIT_WAL." +#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ + #define rtthreadDlOpen 0 + #define rtthreadDlError 0 + #define rtthreadDlSym 0 + #define rtthreadDlClose 0 +#endif + +/* +** Write nBuf bytes of random data to the supplied buffer zBuf. +*/ +static int rtthreadRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ + UNUSED_PARAMETER(NotUsed); + assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int))); + + /* We have to initialize zBuf to prevent valgrind from reporting + ** errors. The reports issued by valgrind are incorrect - we would + ** prefer that the randomness be increased by making use of the + ** uninitialized space in zBuf - but valgrind errors tend to worry + ** some users. Rather than argue, it seems easier just to initialize + ** the whole array and silence valgrind, even if that means less randomness + ** in the random seed. + ** + ** When testing, initializing zBuf[] to zero is all we do. That means + ** that we always use the same random number sequence. This makes the + ** tests repeatable. + */ + memset(zBuf, 0, nBuf); + { + int i; + char tick8, tick16; + tick8 = (char)rt_tick_get(); + tick16 = (char)(rt_tick_get() >> 8); + + for (i=0; i2GB file support on Posix if the +** underlying operating system supports it. If the OS lacks +** large file support, these should be no-ops. +** +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch +** on the compiler command line. This is necessary if you are compiling +** on a recent machine (ex: RedHat 7.2) but you want your code to work +** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2 +** without this option, LFS is enable. But LFS does not exist in the kernel +** in RedHat 6.0, so the code won't work. Hence, for maximum binary +** portability you should omit LFS. +** +** The previous paragraph was written in 2005. (This paragraph is written +** on 2008-11-28.) These days, all Linux kernels support large files, so +** you should probably leave LFS enabled. But some embedded platforms might +** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful. +*/ +#ifndef SQLITE_DISABLE_LFS +# define _LARGE_FILE 1 +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +# define _LARGEFILE_SOURCE 1 +#endif + +/* +** standard include files. +*/ +#include +#include +#include +#include +#include +#include +#include +#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 +#include +#endif + + +#if SQLITE_ENABLE_LOCKING_STYLE +# include +# if OS_VXWORKS +# include +# include +# else +# include +# include +# endif +#endif /* SQLITE_ENABLE_LOCKING_STYLE */ + +#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS) +# include +#endif + +#ifdef HAVE_UTIME +# include +#endif + +/* +** Allowed values of unixFile.fsFlags +*/ +#define SQLITE_FSFLAGS_IS_MSDOS 0x1 + +/* +** If we are to be thread-safe, include the pthreads header and define +** the SQLITE_UNIX_THREADS macro. +*/ +#if SQLITE_THREADSAFE +# include +# define SQLITE_UNIX_THREADS 1 +#endif + +/* +** Default permissions when creating a new file +*/ +#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS +# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644 +#endif + +/* +** Default permissions when creating auto proxy dir +*/ +#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS +# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755 +#endif + +/* +** Maximum supported path-length. +*/ +#define MAX_PATHNAME 512 + +/* +** Only set the lastErrno if the error code is a real error and not +** a normal expected return code of SQLITE_BUSY or SQLITE_OK +*/ +#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY)) + +/* Forward references */ +typedef struct unixShm unixShm; /* Connection shared memory */ +typedef struct unixShmNode unixShmNode; /* Shared memory instance */ +typedef struct unixInodeInfo unixInodeInfo; /* An i-node */ +typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */ + +/* +** Sometimes, after a file handle is closed by SQLite, the file descriptor +** cannot be closed immediately. In these cases, instances of the following +** structure are used to store the file descriptor while waiting for an +** opportunity to either close or reuse it. +*/ +struct UnixUnusedFd { + int fd; /* File descriptor to close */ + int flags; /* Flags this file descriptor was opened with */ + UnixUnusedFd *pNext; /* Next unused file descriptor on same file */ +}; + +/* +** The unixFile structure is subclass of sqlite3_file specific to the unix +** VFS implementations. +*/ +typedef struct unixFile unixFile; +struct unixFile { + sqlite3_io_methods const *pMethod; /* Always the first entry */ + sqlite3_vfs *pVfs; /* The VFS that created this unixFile */ + unixInodeInfo *pInode; /* Info about locks on this inode */ + int h; /* The file descriptor */ + unsigned char eFileLock; /* The type of lock held on this fd */ + unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */ + int lastErrno; /* The unix errno from last I/O error */ + void *lockingContext; /* Locking style specific state */ + UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */ + const char *zPath; /* Name of the file */ + unixShm *pShm; /* Shared memory segment information */ + int szChunk; /* Configured by FCNTL_CHUNK_SIZE */ +#if SQLITE_MAX_MMAP_SIZE>0 + int nFetchOut; /* Number of outstanding xFetch refs */ + sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */ + sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */ + sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ + void *pMapRegion; /* Memory mapped region */ +#endif +#ifdef __QNXNTO__ + int sectorSize; /* Device sector size */ + int deviceCharacteristics; /* Precomputed device characteristics */ +#endif +#if SQLITE_ENABLE_LOCKING_STYLE + int openFlags; /* The flags specified at open() */ +#endif +#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__) + unsigned fsFlags; /* cached details from statfs() */ +#endif +#if OS_VXWORKS + struct vxworksFileId *pId; /* Unique file ID */ +#endif +#ifdef SQLITE_DEBUG + /* The next group of variables are used to track whether or not the + ** transaction counter in bytes 24-27 of database files are updated + ** whenever any part of the database changes. An assertion fault will + ** occur if a file is updated without also updating the transaction + ** counter. This test is made to avoid new problems similar to the + ** one described by ticket #3584. + */ + unsigned char transCntrChng; /* True if the transaction counter changed */ + unsigned char dbUpdate; /* True if any part of database file changed */ + unsigned char inNormalWrite; /* True if in a normal write operation */ + +#endif + +#ifdef SQLITE_TEST + /* In test mode, increase the size of this structure a bit so that + ** it is larger than the struct CrashFile defined in test6.c. + */ + char aPadding[32]; +#endif +}; + +/* +** Allowed values for the unixFile.ctrlFlags bitmask: +*/ +#define UNIXFILE_EXCL 0x01 /* Connections from one process only */ +#define UNIXFILE_RDONLY 0x02 /* Connection is read only */ +#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ +#ifndef SQLITE_DISABLE_DIRSYNC +# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */ +#else +# define UNIXFILE_DIRSYNC 0x00 +#endif +#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ +#define UNIXFILE_DELETE 0x20 /* Delete on close */ +#define UNIXFILE_URI 0x40 /* Filename might have query parameters */ +#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */ +#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */ + +/* +** Include code that is common to all os_*.c files +*/ +#include "os_common.h" + +/* +** Define various macros that are missing from some systems. +*/ +#ifndef O_LARGEFILE +# define O_LARGEFILE 0 +#endif +#ifdef SQLITE_DISABLE_LFS +# undef O_LARGEFILE +# define O_LARGEFILE 0 +#endif +#ifndef O_NOFOLLOW +# define O_NOFOLLOW 0 +#endif +#ifndef O_BINARY +# define O_BINARY 0 +#endif + +/* +** The threadid macro resolves to the thread-id or to 0. Used for +** testing and debugging only. +*/ +#if SQLITE_THREADSAFE +#define threadid pthread_self() +#else +#define threadid 0 +#endif + +/* +** HAVE_MREMAP defaults to true on Linux and false everywhere else. +*/ +#if !defined(HAVE_MREMAP) +# if defined(__linux__) && defined(_GNU_SOURCE) +# define HAVE_MREMAP 1 +# else +# define HAVE_MREMAP 0 +# endif +#endif + +/* +** Different Unix systems declare open() in different ways. Same use +** open(const char*,int,mode_t). Others use open(const char*,int,...). +** The difference is important when using a pointer to the function. +** +** The safest way to deal with the problem is to always use this wrapper +** which always has the same well-defined interface. +*/ +static int posixOpen(const char *zFile, int flags, int mode){ + return open(zFile, flags, mode); +} + +/* +** On some systems, calls to fchown() will trigger a message in a security +** log if they come from non-root processes. So avoid calling fchown() if +** we are not running as root. +*/ +static int posixFchown(int fd, uid_t uid, gid_t gid){ + return geteuid() ? 0 : fchown(fd,uid,gid); +} + +/* Forward reference */ +static int openDirectory(const char*, int*); + +/* +** Many system calls are accessed through pointer-to-functions so that +** they may be overridden at runtime to facilitate fault injection during +** testing and sandboxing. The following array holds the names and pointers +** to all overrideable system calls. +*/ +static struct unix_syscall { + const char *zName; /* Name of the system call */ + sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ + sqlite3_syscall_ptr pDefault; /* Default value */ +} aSyscall[] = { + { "open", (sqlite3_syscall_ptr)posixOpen, 0 }, +#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent) + + { "close", (sqlite3_syscall_ptr)close, 0 }, +#define osClose ((int(*)(int))aSyscall[1].pCurrent) + + { "access", (sqlite3_syscall_ptr)access, 0 }, +#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent) + + { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 }, +#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent) + + { "stat", (sqlite3_syscall_ptr)stat, 0 }, +#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) + +/* +** The DJGPP compiler environment looks mostly like Unix, but it +** lacks the fcntl() system call. So redefine fcntl() to be something +** that always succeeds. This means that locking does not occur under +** DJGPP. But it is DOS - what did you expect? +*/ +#ifdef __DJGPP__ + { "fstat", 0, 0 }, +#define osFstat(a,b,c) 0 +#else + { "fstat", (sqlite3_syscall_ptr)fstat, 0 }, +#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent) +#endif + + { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 }, +#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent) + + { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 }, +#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent) + + { "read", (sqlite3_syscall_ptr)read, 0 }, +#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent) + +#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE + { "pread", (sqlite3_syscall_ptr)pread, 0 }, +#else + { "pread", (sqlite3_syscall_ptr)0, 0 }, +#endif +#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent) + +#if defined(USE_PREAD64) + { "pread64", (sqlite3_syscall_ptr)pread64, 0 }, +#else + { "pread64", (sqlite3_syscall_ptr)0, 0 }, +#endif +#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent) + + { "write", (sqlite3_syscall_ptr)write, 0 }, +#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent) + +#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE + { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 }, +#else + { "pwrite", (sqlite3_syscall_ptr)0, 0 }, +#endif +#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\ + aSyscall[12].pCurrent) + +#if defined(USE_PREAD64) + { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 }, +#else + { "pwrite64", (sqlite3_syscall_ptr)0, 0 }, +#endif +#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\ + aSyscall[13].pCurrent) + + { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 }, +#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent) + +#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE + { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 }, +#else + { "fallocate", (sqlite3_syscall_ptr)0, 0 }, +#endif +#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent) + + { "unlink", (sqlite3_syscall_ptr)unlink, 0 }, +#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent) + + { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 }, +#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent) + + { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 }, +#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent) + + { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 }, +#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent) + + { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 }, +#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent) + +#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 + { "mmap", (sqlite3_syscall_ptr)mmap, 0 }, +#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent) + + { "munmap", (sqlite3_syscall_ptr)munmap, 0 }, +#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent) + +#if HAVE_MREMAP + { "mremap", (sqlite3_syscall_ptr)mremap, 0 }, +#else + { "mremap", (sqlite3_syscall_ptr)0, 0 }, +#endif +#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent) +#endif + +}; /* End of the overrideable system calls */ + +/* +** This is the xSetSystemCall() method of sqlite3_vfs for all of the +** "unix" VFSes. Return SQLITE_OK opon successfully updating the +** system call pointer, or SQLITE_NOTFOUND if there is no configurable +** system call named zName. +*/ +static int unixSetSystemCall( + sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ + const char *zName, /* Name of system call to override */ + sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ +){ + unsigned int i; + int rc = SQLITE_NOTFOUND; + + UNUSED_PARAMETER(pNotUsed); + if( zName==0 ){ + /* If no zName is given, restore all system calls to their default + ** settings and return NULL + */ + rc = SQLITE_OK; + for(i=0; i=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break; + osClose(fd); + sqlite3_log(SQLITE_WARNING, + "attempt to open \"%s\" as file descriptor %d", z, fd); + fd = -1; + if( osOpen("/dev/null", f, m)<0 ) break; + } + if( fd>=0 ){ + if( m!=0 ){ + struct stat statbuf; + if( osFstat(fd, &statbuf)==0 + && statbuf.st_size==0 + && (statbuf.st_mode&0777)!=m + ){ + osFchmod(fd, m); + } + } +#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0) + osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC); +#endif + } + return fd; +} + +/* +** Helper functions to obtain and relinquish the global mutex. The +** global mutex is used to protect the unixInodeInfo and +** vxworksFileId objects used by this file, all of which may be +** shared by multiple threads. +** +** Function unixMutexHeld() is used to assert() that the global mutex +** is held when required. This function is only used as part of assert() +** statements. e.g. +** +** unixEnterMutex() +** assert( unixMutexHeld() ); +** unixEnterLeave() +*/ +static void unixEnterMutex(void){ + sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} +static void unixLeaveMutex(void){ + sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} +#ifdef SQLITE_DEBUG +static int unixMutexHeld(void) { + return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} +#endif + + +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) +/* +** Helper function for printing out trace information from debugging +** binaries. This returns the string represetation of the supplied +** integer lock-type. +*/ +static const char *azFileLock(int eFileLock){ + switch( eFileLock ){ + case NO_LOCK: return "NONE"; + case SHARED_LOCK: return "SHARED"; + case RESERVED_LOCK: return "RESERVED"; + case PENDING_LOCK: return "PENDING"; + case EXCLUSIVE_LOCK: return "EXCLUSIVE"; + } + return "ERROR"; +} +#endif + +#ifdef SQLITE_LOCK_TRACE +/* +** Print out information about all locking operations. +** +** This routine is used for troubleshooting locks on multithreaded +** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE +** command-line option on the compiler. This code is normally +** turned off. +*/ +static int lockTrace(int fd, int op, struct flock *p){ + char *zOpName, *zType; + int s; + int savedErrno; + if( op==F_GETLK ){ + zOpName = "GETLK"; + }else if( op==F_SETLK ){ + zOpName = "SETLK"; + }else{ + s = osFcntl(fd, op, p); + sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s); + return s; + } + if( p->l_type==F_RDLCK ){ + zType = "RDLCK"; + }else if( p->l_type==F_WRLCK ){ + zType = "WRLCK"; + }else if( p->l_type==F_UNLCK ){ + zType = "UNLCK"; + }else{ + assert( 0 ); + } + assert( p->l_whence==SEEK_SET ); + s = osFcntl(fd, op, p); + savedErrno = errno; + sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n", + threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len, + (int)p->l_pid, s); + if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){ + struct flock l2; + l2 = *p; + osFcntl(fd, F_GETLK, &l2); + if( l2.l_type==F_RDLCK ){ + zType = "RDLCK"; + }else if( l2.l_type==F_WRLCK ){ + zType = "WRLCK"; + }else if( l2.l_type==F_UNLCK ){ + zType = "UNLCK"; + }else{ + assert( 0 ); + } + sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n", + zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid); + } + errno = savedErrno; + return s; +} +#undef osFcntl +#define osFcntl lockTrace +#endif /* SQLITE_LOCK_TRACE */ + +/* +** Retry ftruncate() calls that fail due to EINTR +*/ +static int robust_ftruncate(int h, sqlite3_int64 sz){ + int rc; + do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR ); + return rc; +} + +/* +** This routine translates a standard POSIX errno code into something +** useful to the clients of the sqlite3 functions. Specifically, it is +** intended to translate a variety of "try again" errors into SQLITE_BUSY +** and a variety of "please close the file descriptor NOW" errors into +** SQLITE_IOERR +** +** Errors during initialization of locks, or file system support for locks, +** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately. +*/ +static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) { + switch (posixError) { +#if 0 + /* At one point this code was not commented out. In theory, this branch + ** should never be hit, as this function should only be called after + ** a locking-related function (i.e. fcntl()) has returned non-zero with + ** the value of errno as the first argument. Since a system call has failed, + ** errno should be non-zero. + ** + ** Despite this, if errno really is zero, we still don't want to return + ** SQLITE_OK. The system call failed, and *some* SQLite error should be + ** propagated back to the caller. Commenting this branch out means errno==0 + ** will be handled by the "default:" case below. + */ + case 0: + return SQLITE_OK; +#endif + + case EAGAIN: + case ETIMEDOUT: + case EBUSY: + case EINTR: + case ENOLCK: + /* random NFS retry error, unless during file system support + * introspection, in which it actually means what it says */ + return SQLITE_BUSY; + + case EACCES: + /* EACCES is like EAGAIN during locking operations, but not any other time*/ + if( (sqliteIOErr == SQLITE_IOERR_LOCK) || + (sqliteIOErr == SQLITE_IOERR_UNLOCK) || + (sqliteIOErr == SQLITE_IOERR_RDLOCK) || + (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){ + return SQLITE_BUSY; + } + /* else fall through */ + case EPERM: + return SQLITE_PERM; + + /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And + ** this module never makes such a call. And the code in SQLite itself + ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons + ** this case is also commented out. If the system does set errno to EDEADLK, + ** the default SQLITE_IOERR_XXX code will be returned. */ +#if 0 + case EDEADLK: + return SQLITE_IOERR_BLOCKED; +#endif + +#if EOPNOTSUPP!=ENOTSUP + case EOPNOTSUPP: + /* something went terribly awry, unless during file system support + * introspection, in which it actually means what it says */ +#endif +#ifdef ENOTSUP + case ENOTSUP: + /* invalid fd, unless during file system support introspection, in which + * it actually means what it says */ +#endif + case EIO: + case EBADF: + case EINVAL: + case ENOTCONN: + case ENODEV: + case ENXIO: + case ENOENT: +#ifdef ESTALE /* ESTALE is not defined on Interix systems */ + case ESTALE: +#endif + case ENOSYS: + /* these should force the client to close the file and reconnect */ + + default: + return sqliteIOErr; + } +} + + +/****************************************************************************** +****************** Begin Unique File ID Utility Used By VxWorks *************** +** +** On most versions of unix, we can get a unique ID for a file by concatenating +** the device number and the inode number. But this does not work on VxWorks. +** On VxWorks, a unique file id must be based on the canonical filename. +** +** A pointer to an instance of the following structure can be used as a +** unique file ID in VxWorks. Each instance of this structure contains +** a copy of the canonical filename. There is also a reference count. +** The structure is reclaimed when the number of pointers to it drops to +** zero. +** +** There are never very many files open at one time and lookups are not +** a performance-critical path, so it is sufficient to put these +** structures on a linked list. +*/ +struct vxworksFileId { + struct vxworksFileId *pNext; /* Next in a list of them all */ + int nRef; /* Number of references to this one */ + int nName; /* Length of the zCanonicalName[] string */ + char *zCanonicalName; /* Canonical filename */ +}; + +#if OS_VXWORKS +/* +** All unique filenames are held on a linked list headed by this +** variable: +*/ +static struct vxworksFileId *vxworksFileList = 0; + +/* +** Simplify a filename into its canonical form +** by making the following changes: +** +** * removing any trailing and duplicate / +** * convert /./ into just / +** * convert /A/../ where A is any simple name into just / +** +** Changes are made in-place. Return the new name length. +** +** The original filename is in z[0..n-1]. Return the number of +** characters in the simplified name. +*/ +static int vxworksSimplifyName(char *z, int n){ + int i, j; + while( n>1 && z[n-1]=='/' ){ n--; } + for(i=j=0; i0 && z[j-1]!='/' ){ j--; } + if( j>0 ){ j--; } + i += 2; + continue; + } + } + z[j++] = z[i]; + } + z[j] = 0; + return j; +} + +/* +** Find a unique file ID for the given absolute pathname. Return +** a pointer to the vxworksFileId object. This pointer is the unique +** file ID. +** +** The nRef field of the vxworksFileId object is incremented before +** the object is returned. A new vxworksFileId object is created +** and added to the global list if necessary. +** +** If a memory allocation error occurs, return NULL. +*/ +static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ + struct vxworksFileId *pNew; /* search key and new file ID */ + struct vxworksFileId *pCandidate; /* For looping over existing file IDs */ + int n; /* Length of zAbsoluteName string */ + + assert( zAbsoluteName[0]=='/' ); + n = (int)strlen(zAbsoluteName); + pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) ); + if( pNew==0 ) return 0; + pNew->zCanonicalName = (char*)&pNew[1]; + memcpy(pNew->zCanonicalName, zAbsoluteName, n+1); + n = vxworksSimplifyName(pNew->zCanonicalName, n); + + /* Search for an existing entry that matching the canonical name. + ** If found, increment the reference count and return a pointer to + ** the existing file ID. + */ + unixEnterMutex(); + for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){ + if( pCandidate->nName==n + && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0 + ){ + sqlite3_free(pNew); + pCandidate->nRef++; + unixLeaveMutex(); + return pCandidate; + } + } + + /* No match was found. We will make a new file ID */ + pNew->nRef = 1; + pNew->nName = n; + pNew->pNext = vxworksFileList; + vxworksFileList = pNew; + unixLeaveMutex(); + return pNew; +} + +/* +** Decrement the reference count on a vxworksFileId object. Free +** the object when the reference count reaches zero. +*/ +static void vxworksReleaseFileId(struct vxworksFileId *pId){ + unixEnterMutex(); + assert( pId->nRef>0 ); + pId->nRef--; + if( pId->nRef==0 ){ + struct vxworksFileId **pp; + for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){} + assert( *pp==pId ); + *pp = pId->pNext; + sqlite3_free(pId); + } + unixLeaveMutex(); +} +#endif /* OS_VXWORKS */ +/*************** End of Unique File ID Utility Used By VxWorks **************** +******************************************************************************/ + + +/****************************************************************************** +*************************** Posix Advisory Locking **************************** +** +** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996) +** section 6.5.2.2 lines 483 through 490 specify that when a process +** sets or clears a lock, that operation overrides any prior locks set +** by the same process. It does not explicitly say so, but this implies +** that it overrides locks set by the same process using a different +** file descriptor. Consider this test case: +** +** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644); +** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644); +** +** Suppose ./file1 and ./file2 are really the same file (because +** one is a hard or symbolic link to the other) then if you set +** an exclusive lock on fd1, then try to get an exclusive lock +** on fd2, it works. I would have expected the second lock to +** fail since there was already a lock on the file due to fd1. +** But not so. Since both locks came from the same process, the +** second overrides the first, even though they were on different +** file descriptors opened on different file names. +** +** This means that we cannot use POSIX locks to synchronize file access +** among competing threads of the same process. POSIX locks will work fine +** to synchronize access for threads in separate processes, but not +** threads within the same process. +** +** To work around the problem, SQLite has to manage file locks internally +** on its own. Whenever a new database is opened, we have to find the +** specific inode of the database file (the inode is determined by the +** st_dev and st_ino fields of the stat structure that fstat() fills in) +** and check for locks already existing on that inode. When locks are +** created or removed, we have to look at our own internal record of the +** locks to see if another thread has previously set a lock on that same +** inode. +** +** (Aside: The use of inode numbers as unique IDs does not work on VxWorks. +** For VxWorks, we have to use the alternative unique ID system based on +** canonical filename and implemented in the previous division.) +** +** The sqlite3_file structure for POSIX is no longer just an integer file +** descriptor. It is now a structure that holds the integer file +** descriptor and a pointer to a structure that describes the internal +** locks on the corresponding inode. There is one locking structure +** per inode, so if the same inode is opened twice, both unixFile structures +** point to the same locking structure. The locking structure keeps +** a reference count (so we will know when to delete it) and a "cnt" +** field that tells us its internal lock status. cnt==0 means the +** file is unlocked. cnt==-1 means the file has an exclusive lock. +** cnt>0 means there are cnt shared locks on the file. +** +** Any attempt to lock or unlock a file first checks the locking +** structure. The fcntl() system call is only invoked to set a +** POSIX lock if the internal lock structure transitions between +** a locked and an unlocked state. +** +** But wait: there are yet more problems with POSIX advisory locks. +** +** If you close a file descriptor that points to a file that has locks, +** all locks on that file that are owned by the current process are +** released. To work around this problem, each unixInodeInfo object +** maintains a count of the number of pending locks on tha inode. +** When an attempt is made to close an unixFile, if there are +** other unixFile open on the same inode that are holding locks, the call +** to close() the file descriptor is deferred until all of the locks clear. +** The unixInodeInfo structure keeps a list of file descriptors that need to +** be closed and that list is walked (and cleared) when the last lock +** clears. +** +** Yet another problem: LinuxThreads do not play well with posix locks. +** +** Many older versions of linux use the LinuxThreads library which is +** not posix compliant. Under LinuxThreads, a lock created by thread +** A cannot be modified or overridden by a different thread B. +** Only thread A can modify the lock. Locking behavior is correct +** if the appliation uses the newer Native Posix Thread Library (NPTL) +** on linux - with NPTL a lock created by thread A can override locks +** in thread B. But there is no way to know at compile-time which +** threading library is being used. So there is no way to know at +** compile-time whether or not thread A can override locks on thread B. +** One has to do a run-time check to discover the behavior of the +** current process. +** +** SQLite used to support LinuxThreads. But support for LinuxThreads +** was dropped beginning with version 3.7.0. SQLite will still work with +** LinuxThreads provided that (1) there is no more than one connection +** per database file in the same process and (2) database connections +** do not move across threads. +*/ + +/* +** An instance of the following structure serves as the key used +** to locate a particular unixInodeInfo object. +*/ +struct unixFileId { + dev_t dev; /* Device number */ +#if OS_VXWORKS + struct vxworksFileId *pId; /* Unique file ID for vxworks. */ +#else + ino_t ino; /* Inode number */ +#endif +}; + +/* +** An instance of the following structure is allocated for each open +** inode. Or, on LinuxThreads, there is one of these structures for +** each inode opened by each thread. +** +** A single inode can have multiple file descriptors, so each unixFile +** structure contains a pointer to an instance of this object and this +** object keeps a count of the number of unixFile pointing to it. +*/ +struct unixInodeInfo { + struct unixFileId fileId; /* The lookup key */ + int nShared; /* Number of SHARED locks held */ + unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ + unsigned char bProcessLock; /* An exclusive process lock is held */ + int nRef; /* Number of pointers to this structure */ + unixShmNode *pShmNode; /* Shared memory associated with this inode */ + int nLock; /* Number of outstanding file locks */ + UnixUnusedFd *pUnused; /* Unused file descriptors to close */ + unixInodeInfo *pNext; /* List of all unixInodeInfo objects */ + unixInodeInfo *pPrev; /* .... doubly linked */ +#if SQLITE_ENABLE_LOCKING_STYLE + unsigned long long sharedByte; /* for AFP simulated shared lock */ +#endif +#if OS_VXWORKS + sem_t *pSem; /* Named POSIX semaphore */ + char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */ +#endif +}; + +/* +** A lists of all unixInodeInfo objects. +*/ +static unixInodeInfo *inodeList = 0; + +/* +** +** This function - unixLogError_x(), is only ever called via the macro +** unixLogError(). +** +** It is invoked after an error occurs in an OS function and errno has been +** set. It logs a message using sqlite3_log() containing the current value of +** errno and, if possible, the human-readable equivalent from strerror() or +** strerror_r(). +** +** The first argument passed to the macro should be the error code that +** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). +** The two subsequent arguments should be the name of the OS function that +** failed (e.g. "unlink", "open") and the associated file-system path, +** if any. +*/ +#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__) +static int unixLogErrorAtLine( + int errcode, /* SQLite error code */ + const char *zFunc, /* Name of OS function that failed */ + const char *zPath, /* File path associated with error */ + int iLine /* Source line number where error occurred */ +){ + char *zErr; /* Message from strerror() or equivalent */ + int iErrno = errno; /* Saved syscall error number */ + + /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use + ** the strerror() function to obtain the human-readable error message + ** equivalent to errno. Otherwise, use strerror_r(). + */ +#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R) + char aErr[80]; + memset(aErr, 0, sizeof(aErr)); + zErr = aErr; + + /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined, + ** assume that the system provides the GNU version of strerror_r() that + ** returns a pointer to a buffer containing the error message. That pointer + ** may point to aErr[], or it may point to some static storage somewhere. + ** Otherwise, assume that the system provides the POSIX version of + ** strerror_r(), which always writes an error message into aErr[]. + ** + ** If the code incorrectly assumes that it is the POSIX version that is + ** available, the error message will often be an empty string. Not a + ** huge problem. Incorrectly concluding that the GNU version is available + ** could lead to a segfault though. + */ +#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU) + zErr = +# endif + strerror_r(iErrno, aErr, sizeof(aErr)-1); + +#elif SQLITE_THREADSAFE + /* This is a threadsafe build, but strerror_r() is not available. */ + zErr = ""; +#else + /* Non-threadsafe build, use strerror(). */ + zErr = strerror(iErrno); +#endif + + if( zPath==0 ) zPath = ""; + sqlite3_log(errcode, + "os_unix.c:%d: (%d) %s(%s) - %s", + iLine, iErrno, zFunc, zPath, zErr + ); + + return errcode; +} + +/* +** Close a file descriptor. +** +** We assume that close() almost always works, since it is only in a +** very sick application or on a very sick platform that it might fail. +** If it does fail, simply leak the file descriptor, but do log the +** error. +** +** Note that it is not safe to retry close() after EINTR since the +** file descriptor might have already been reused by another thread. +** So we don't even try to recover from an EINTR. Just log the error +** and move on. +*/ +static void robust_close(unixFile *pFile, int h, int lineno){ + if( osClose(h) ){ + unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close", + pFile ? pFile->zPath : 0, lineno); + } +} + +/* +** Close all file descriptors accumuated in the unixInodeInfo->pUnused list. +*/ +static void closePendingFds(unixFile *pFile){ + unixInodeInfo *pInode = pFile->pInode; + UnixUnusedFd *p; + UnixUnusedFd *pNext; + for(p=pInode->pUnused; p; p=pNext){ + pNext = p->pNext; + robust_close(pFile, p->fd, __LINE__); + sqlite3_free(p); + } + pInode->pUnused = 0; +} + +/* +** Release a unixInodeInfo structure previously allocated by findInodeInfo(). +** +** The mutex entered using the unixEnterMutex() function must be held +** when this function is called. +*/ +static void releaseInodeInfo(unixFile *pFile){ + unixInodeInfo *pInode = pFile->pInode; + assert( unixMutexHeld() ); + if( ALWAYS(pInode) ){ + pInode->nRef--; + if( pInode->nRef==0 ){ + assert( pInode->pShmNode==0 ); + closePendingFds(pFile); + if( pInode->pPrev ){ + assert( pInode->pPrev->pNext==pInode ); + pInode->pPrev->pNext = pInode->pNext; + }else{ + assert( inodeList==pInode ); + inodeList = pInode->pNext; + } + if( pInode->pNext ){ + assert( pInode->pNext->pPrev==pInode ); + pInode->pNext->pPrev = pInode->pPrev; + } + sqlite3_free(pInode); + } + } +} + +/* +** Given a file descriptor, locate the unixInodeInfo object that +** describes that file descriptor. Create a new one if necessary. The +** return value might be uninitialized if an error occurs. +** +** The mutex entered using the unixEnterMutex() function must be held +** when this function is called. +** +** Return an appropriate error code. +*/ +static int findInodeInfo( + unixFile *pFile, /* Unix file with file desc used in the key */ + unixInodeInfo **ppInode /* Return the unixInodeInfo object here */ +){ + int rc; /* System call return code */ + int fd; /* The file descriptor for pFile */ + struct unixFileId fileId; /* Lookup key for the unixInodeInfo */ + struct stat statbuf; /* Low-level file information */ + unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */ + + assert( unixMutexHeld() ); + + /* Get low-level information about the file that we can used to + ** create a unique name for the file. + */ + fd = pFile->h; + rc = osFstat(fd, &statbuf); + if( rc!=0 ){ + pFile->lastErrno = errno; +#ifdef EOVERFLOW + if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS; +#endif + return SQLITE_IOERR; + } + +#ifdef __APPLE__ + /* On OS X on an msdos filesystem, the inode number is reported + ** incorrectly for zero-size files. See ticket #3260. To work + ** around this problem (we consider it a bug in OS X, not SQLite) + ** we always increase the file size to 1 by writing a single byte + ** prior to accessing the inode number. The one byte written is + ** an ASCII 'S' character which also happens to be the first byte + ** in the header of every SQLite database. In this way, if there + ** is a race condition such that another thread has already populated + ** the first page of the database, no damage is done. + */ + if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){ + do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR ); + if( rc!=1 ){ + pFile->lastErrno = errno; + return SQLITE_IOERR; + } + rc = osFstat(fd, &statbuf); + if( rc!=0 ){ + pFile->lastErrno = errno; + return SQLITE_IOERR; + } + } +#endif + + memset(&fileId, 0, sizeof(fileId)); + fileId.dev = statbuf.st_dev; +#if OS_VXWORKS + fileId.pId = pFile->pId; +#else + fileId.ino = statbuf.st_ino; +#endif + pInode = inodeList; + while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){ + pInode = pInode->pNext; + } + if( pInode==0 ){ + pInode = sqlite3_malloc( sizeof(*pInode) ); + if( pInode==0 ){ + return SQLITE_NOMEM; + } + memset(pInode, 0, sizeof(*pInode)); + memcpy(&pInode->fileId, &fileId, sizeof(fileId)); + pInode->nRef = 1; + pInode->pNext = inodeList; + pInode->pPrev = 0; + if( inodeList ) inodeList->pPrev = pInode; + inodeList = pInode; + }else{ + pInode->nRef++; + } + *ppInode = pInode; + return SQLITE_OK; +} + + +/* +** Check a unixFile that is a database. Verify the following: +** +** (1) There is exactly one hard link on the file +** (2) The file is not a symbolic link +** (3) The file has not been renamed or unlinked +** +** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right. +*/ +static void verifyDbFile(unixFile *pFile){ + struct stat buf; + int rc; + if( pFile->ctrlFlags & UNIXFILE_WARNED ){ + /* One or more of the following warnings have already been issued. Do not + ** repeat them so as not to clutter the error log */ + return; + } + rc = osFstat(pFile->h, &buf); + if( rc!=0 ){ + sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath); + pFile->ctrlFlags |= UNIXFILE_WARNED; + return; + } + if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){ + sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath); + pFile->ctrlFlags |= UNIXFILE_WARNED; + return; + } + if( buf.st_nlink>1 ){ + sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath); + pFile->ctrlFlags |= UNIXFILE_WARNED; + return; + } + if( pFile->pInode!=0 + && ((rc = osStat(pFile->zPath, &buf))!=0 + || buf.st_ino!=pFile->pInode->fileId.ino) + ){ + sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath); + pFile->ctrlFlags |= UNIXFILE_WARNED; + return; + } +} + + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +*/ +static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ + int rc = SQLITE_OK; + int reserved = 0; + unixFile *pFile = (unixFile*)id; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + + assert( pFile ); + unixEnterMutex(); /* Because pFile->pInode is shared across threads */ + + /* Check if a thread in this process holds such a lock */ + if( pFile->pInode->eFileLock>SHARED_LOCK ){ + reserved = 1; + } + + /* Otherwise see if some other process holds it. + */ +#ifndef __DJGPP__ + if( !reserved && !pFile->pInode->bProcessLock ){ + struct flock lock; + lock.l_whence = SEEK_SET; + lock.l_start = RESERVED_BYTE; + lock.l_len = 1; + lock.l_type = F_WRLCK; + if( osFcntl(pFile->h, F_GETLK, &lock) ){ + rc = SQLITE_IOERR_CHECKRESERVEDLOCK; + pFile->lastErrno = errno; + } else if( lock.l_type!=F_UNLCK ){ + reserved = 1; + } + } +#endif + + unixLeaveMutex(); + OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved)); + + *pResOut = reserved; + return rc; +} + +/* +** Attempt to set a system-lock on the file pFile. The lock is +** described by pLock. +** +** If the pFile was opened read/write from unix-excl, then the only lock +** ever obtained is an exclusive lock, and it is obtained exactly once +** the first time any lock is attempted. All subsequent system locking +** operations become no-ops. Locking operations still happen internally, +** in order to coordinate access between separate database connections +** within this process, but all of that is handled in memory and the +** operating system does not participate. +** +** This function is a pass-through to fcntl(F_SETLK) if pFile is using +** any VFS other than "unix-excl" or if pFile is opened on "unix-excl" +** and is read-only. +** +** Zero is returned if the call completes successfully, or -1 if a call +** to fcntl() fails. In this case, errno is set appropriately (by fcntl()). +*/ +static int unixFileLock(unixFile *pFile, struct flock *pLock){ + int rc; + unixInodeInfo *pInode = pFile->pInode; + assert( unixMutexHeld() ); + assert( pInode!=0 ); + if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock) + && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0) + ){ + if( pInode->bProcessLock==0 ){ + struct flock lock; + assert( pInode->nLock==0 ); + lock.l_whence = SEEK_SET; + lock.l_start = SHARED_FIRST; + lock.l_len = SHARED_SIZE; + lock.l_type = F_WRLCK; + rc = osFcntl(pFile->h, F_SETLK, &lock); + if( rc<0 ) return rc; + pInode->bProcessLock = 1; + pInode->nLock++; + }else{ + rc = 0; + } + }else{ + rc = osFcntl(pFile->h, F_SETLK, pLock); + } + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +*/ +static int unixLock(sqlite3_file *id, int eFileLock){ + /* The following describes the implementation of the various locks and + ** lock transitions in terms of the POSIX advisory shared and exclusive + ** lock primitives (called read-locks and write-locks below, to avoid + ** confusion with SQLite lock names). The algorithms are complicated + ** slightly in order to be compatible with windows systems simultaneously + ** accessing the same database file, in case that is ever required. + ** + ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved + ** byte', each single bytes at well known offsets, and the 'shared byte + ** range', a range of 510 bytes at a well known offset. + ** + ** To obtain a SHARED lock, a read-lock is obtained on the 'pending + ** byte'. If this is successful, a random byte from the 'shared byte + ** range' is read-locked and the lock on the 'pending byte' released. + ** + ** A process may only obtain a RESERVED lock after it has a SHARED lock. + ** A RESERVED lock is implemented by grabbing a write-lock on the + ** 'reserved byte'. + ** + ** A process may only obtain a PENDING lock after it has obtained a + ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock + ** on the 'pending byte'. This ensures that no new SHARED locks can be + ** obtained, but existing SHARED locks are allowed to persist. A process + ** does not have to obtain a RESERVED lock on the way to a PENDING lock. + ** This property is used by the algorithm for rolling back a journal file + ** after a crash. + ** + ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is + ** implemented by obtaining a write-lock on the entire 'shared byte + ** range'. Since all other locks require a read-lock on one of the bytes + ** within this range, this ensures that no other locks are held on the + ** database. + ** + ** The reason a single byte cannot be used instead of the 'shared byte + ** range' is that some versions of windows do not support read-locks. By + ** locking a random byte from a range, concurrent SHARED locks may exist + ** even if the locking primitive used is always a write-lock. + */ + int rc = SQLITE_OK; + unixFile *pFile = (unixFile*)id; + unixInodeInfo *pInode; + struct flock lock; + int tErrno = 0; + + assert( pFile ); + OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h, + azFileLock(eFileLock), azFileLock(pFile->eFileLock), + azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid())); + + /* If there is already a lock of this type or more restrictive on the + ** unixFile, do nothing. Don't use the end_lock: exit path, as + ** unixEnterMutex() hasn't been called yet. + */ + if( pFile->eFileLock>=eFileLock ){ + OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h, + azFileLock(eFileLock))); + return SQLITE_OK; + } + + /* Make sure the locking sequence is correct. + ** (1) We never move from unlocked to anything higher than shared lock. + ** (2) SQLite never explicitly requests a pendig lock. + ** (3) A shared lock is always held when a reserve lock is requested. + */ + assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); + assert( eFileLock!=PENDING_LOCK ); + assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); + + /* This mutex is needed because pFile->pInode is shared across threads + */ + unixEnterMutex(); + pInode = pFile->pInode; + + /* If some thread using this PID has a lock via a different unixFile* + ** handle that precludes the requested lock, return BUSY. + */ + if( (pFile->eFileLock!=pInode->eFileLock && + (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) + ){ + rc = SQLITE_BUSY; + goto end_lock; + } + + /* If a SHARED lock is requested, and some thread using this PID already + ** has a SHARED or RESERVED lock, then increment reference counts and + ** return SQLITE_OK. + */ + if( eFileLock==SHARED_LOCK && + (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ + assert( eFileLock==SHARED_LOCK ); + assert( pFile->eFileLock==0 ); + assert( pInode->nShared>0 ); + pFile->eFileLock = SHARED_LOCK; + pInode->nShared++; + pInode->nLock++; + goto end_lock; + } + + + /* A PENDING lock is needed before acquiring a SHARED lock and before + ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will + ** be released. + */ + lock.l_len = 1L; + lock.l_whence = SEEK_SET; + if( eFileLock==SHARED_LOCK + || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLocklastErrno = tErrno; + } + goto end_lock; + } + } + + + /* If control gets to this point, then actually go ahead and make + ** operating system calls for the specified lock. + */ + if( eFileLock==SHARED_LOCK ){ + assert( pInode->nShared==0 ); + assert( pInode->eFileLock==0 ); + assert( rc==SQLITE_OK ); + + /* Now get the read-lock */ + lock.l_start = SHARED_FIRST; + lock.l_len = SHARED_SIZE; + if( unixFileLock(pFile, &lock) ){ + tErrno = errno; + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + } + + /* Drop the temporary PENDING lock */ + lock.l_start = PENDING_BYTE; + lock.l_len = 1L; + lock.l_type = F_UNLCK; + if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){ + /* This could happen with a network mount */ + tErrno = errno; + rc = SQLITE_IOERR_UNLOCK; + } + + if( rc ){ + if( rc!=SQLITE_BUSY ){ + pFile->lastErrno = tErrno; + } + goto end_lock; + }else{ + pFile->eFileLock = SHARED_LOCK; + pInode->nLock++; + pInode->nShared = 1; + } + }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ + /* We are trying for an exclusive lock but another thread in this + ** same process is still holding a shared lock. */ + rc = SQLITE_BUSY; + }else{ + /* The request was for a RESERVED or EXCLUSIVE lock. It is + ** assumed that there is a SHARED or greater lock on the file + ** already. + */ + assert( 0!=pFile->eFileLock ); + lock.l_type = F_WRLCK; + + assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK ); + if( eFileLock==RESERVED_LOCK ){ + lock.l_start = RESERVED_BYTE; + lock.l_len = 1L; + }else{ + lock.l_start = SHARED_FIRST; + lock.l_len = SHARED_SIZE; + } + + if( unixFileLock(pFile, &lock) ){ + tErrno = errno; + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( rc!=SQLITE_BUSY ){ + pFile->lastErrno = tErrno; + } + } + } + + +#ifdef SQLITE_DEBUG + /* Set up the transaction-counter change checking flags when + ** transitioning from a SHARED to a RESERVED lock. The change + ** from SHARED to RESERVED marks the beginning of a normal + ** write operation (not a hot journal rollback). + */ + if( rc==SQLITE_OK + && pFile->eFileLock<=SHARED_LOCK + && eFileLock==RESERVED_LOCK + ){ + pFile->transCntrChng = 0; + pFile->dbUpdate = 0; + pFile->inNormalWrite = 1; + } +#endif + + + if( rc==SQLITE_OK ){ + pFile->eFileLock = eFileLock; + pInode->eFileLock = eFileLock; + }else if( eFileLock==EXCLUSIVE_LOCK ){ + pFile->eFileLock = PENDING_LOCK; + pInode->eFileLock = PENDING_LOCK; + } + +end_lock: + unixLeaveMutex(); + OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), + rc==SQLITE_OK ? "ok" : "failed")); + return rc; +} + +/* +** Add the file descriptor used by file handle pFile to the corresponding +** pUnused list. +*/ +static void setPendingFd(unixFile *pFile){ + unixInodeInfo *pInode = pFile->pInode; + UnixUnusedFd *p = pFile->pUnused; + p->pNext = pInode->pUnused; + pInode->pUnused = p; + pFile->h = -1; + pFile->pUnused = 0; +} + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +** +** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED +** the byte range is divided into 2 parts and the first part is unlocked then +** set to a read lock, then the other part is simply unlocked. This works +** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to +** remove the write lock on a region when a read lock is set. +*/ +static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){ + unixFile *pFile = (unixFile*)id; + unixInodeInfo *pInode; + struct flock lock; + int rc = SQLITE_OK; + + assert( pFile ); + OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock, + pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, + getpid())); + + assert( eFileLock<=SHARED_LOCK ); + if( pFile->eFileLock<=eFileLock ){ + return SQLITE_OK; + } + unixEnterMutex(); + pInode = pFile->pInode; + assert( pInode->nShared!=0 ); + if( pFile->eFileLock>SHARED_LOCK ){ + assert( pInode->eFileLock==pFile->eFileLock ); + +#ifdef SQLITE_DEBUG + /* When reducing a lock such that other processes can start + ** reading the database file again, make sure that the + ** transaction counter was updated if any part of the database + ** file changed. If the transaction counter is not updated, + ** other connections to the same file might not realize that + ** the file has changed and hence might not know to flush their + ** cache. The use of a stale cache can lead to database corruption. + */ + pFile->inNormalWrite = 0; +#endif + + /* downgrading to a shared lock on NFS involves clearing the write lock + ** before establishing the readlock - to avoid a race condition we downgrade + ** the lock in 2 blocks, so that part of the range will be covered by a + ** write lock until the rest is covered by a read lock: + ** 1: [WWWWW] + ** 2: [....W] + ** 3: [RRRRW] + ** 4: [RRRR.] + */ + if( eFileLock==SHARED_LOCK ){ + +#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE + (void)handleNFSUnlock; + assert( handleNFSUnlock==0 ); +#endif +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE + if( handleNFSUnlock ){ + int tErrno; /* Error code from system call errors */ + off_t divSize = SHARED_SIZE - 1; + + lock.l_type = F_UNLCK; + lock.l_whence = SEEK_SET; + lock.l_start = SHARED_FIRST; + lock.l_len = divSize; + if( unixFileLock(pFile, &lock)==(-1) ){ + tErrno = errno; + rc = SQLITE_IOERR_UNLOCK; + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + goto end_unlock; + } + lock.l_type = F_RDLCK; + lock.l_whence = SEEK_SET; + lock.l_start = SHARED_FIRST; + lock.l_len = divSize; + if( unixFileLock(pFile, &lock)==(-1) ){ + tErrno = errno; + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK); + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + goto end_unlock; + } + lock.l_type = F_UNLCK; + lock.l_whence = SEEK_SET; + lock.l_start = SHARED_FIRST+divSize; + lock.l_len = SHARED_SIZE-divSize; + if( unixFileLock(pFile, &lock)==(-1) ){ + tErrno = errno; + rc = SQLITE_IOERR_UNLOCK; + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + goto end_unlock; + } + }else +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ + { + lock.l_type = F_RDLCK; + lock.l_whence = SEEK_SET; + lock.l_start = SHARED_FIRST; + lock.l_len = SHARED_SIZE; + if( unixFileLock(pFile, &lock) ){ + /* In theory, the call to unixFileLock() cannot fail because another + ** process is holding an incompatible lock. If it does, this + ** indicates that the other process is not following the locking + ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning + ** SQLITE_BUSY would confuse the upper layer (in practice it causes + ** an assert to fail). */ + rc = SQLITE_IOERR_RDLOCK; + pFile->lastErrno = errno; + goto end_unlock; + } + } + } + lock.l_type = F_UNLCK; + lock.l_whence = SEEK_SET; + lock.l_start = PENDING_BYTE; + lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE ); + if( unixFileLock(pFile, &lock)==0 ){ + pInode->eFileLock = SHARED_LOCK; + }else{ + rc = SQLITE_IOERR_UNLOCK; + pFile->lastErrno = errno; + goto end_unlock; + } + } + if( eFileLock==NO_LOCK ){ + /* Decrement the shared lock counter. Release the lock using an + ** OS call only when all threads in this same process have released + ** the lock. + */ + pInode->nShared--; + if( pInode->nShared==0 ){ + lock.l_type = F_UNLCK; + lock.l_whence = SEEK_SET; + lock.l_start = lock.l_len = 0L; + if( unixFileLock(pFile, &lock)==0 ){ + pInode->eFileLock = NO_LOCK; + }else{ + rc = SQLITE_IOERR_UNLOCK; + pFile->lastErrno = errno; + pInode->eFileLock = NO_LOCK; + pFile->eFileLock = NO_LOCK; + } + } + + /* Decrement the count of locks against this same file. When the + ** count reaches zero, close any other file descriptors whose close + ** was deferred because of outstanding locks. + */ + pInode->nLock--; + assert( pInode->nLock>=0 ); + if( pInode->nLock==0 ){ + closePendingFds(pFile); + } + } + +end_unlock: + unixLeaveMutex(); + if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock; + return rc; +} + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +*/ +static int unixUnlock(sqlite3_file *id, int eFileLock){ + assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 ); + return posixUnlock(id, eFileLock, 0); +} + +#if SQLITE_MAX_MMAP_SIZE>0 +static int unixMapfile(unixFile *pFd, i64 nByte); +static void unixUnmapfile(unixFile *pFd); +#endif + +/* +** This function performs the parts of the "close file" operation +** common to all locking schemes. It closes the directory and file +** handles, if they are valid, and sets all fields of the unixFile +** structure to 0. +** +** It is *not* necessary to hold the mutex when this routine is called, +** even on VxWorks. A mutex will be acquired on VxWorks by the +** vxworksReleaseFileId() routine. +*/ +static int closeUnixFile(sqlite3_file *id){ + unixFile *pFile = (unixFile*)id; +#if SQLITE_MAX_MMAP_SIZE>0 + unixUnmapfile(pFile); +#endif + if( pFile->h>=0 ){ + robust_close(pFile, pFile->h, __LINE__); + pFile->h = -1; + } +#if OS_VXWORKS + if( pFile->pId ){ + if( pFile->ctrlFlags & UNIXFILE_DELETE ){ + osUnlink(pFile->pId->zCanonicalName); + } + vxworksReleaseFileId(pFile->pId); + pFile->pId = 0; + } +#endif + OSTRACE(("CLOSE %-3d\n", pFile->h)); + OpenCounter(-1); + sqlite3_free(pFile->pUnused); + memset(pFile, 0, sizeof(unixFile)); + return SQLITE_OK; +} + +/* +** Close a file. +*/ +static int unixClose(sqlite3_file *id){ + int rc = SQLITE_OK; + unixFile *pFile = (unixFile *)id; + verifyDbFile(pFile); + unixUnlock(id, NO_LOCK); + unixEnterMutex(); + + /* unixFile.pInode is always valid here. Otherwise, a different close + ** routine (e.g. nolockClose()) would be called instead. + */ + assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 ); + if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){ + /* If there are outstanding locks, do not actually close the file just + ** yet because that would clear those locks. Instead, add the file + ** descriptor to pInode->pUnused list. It will be automatically closed + ** when the last lock is cleared. + */ + setPendingFd(pFile); + } + releaseInodeInfo(pFile); + rc = closeUnixFile(id); + unixLeaveMutex(); + return rc; +} + +/************** End of the posix advisory lock implementation ***************** +******************************************************************************/ + +/****************************************************************************** +****************************** No-op Locking ********************************** +** +** Of the various locking implementations available, this is by far the +** simplest: locking is ignored. No attempt is made to lock the database +** file for reading or writing. +** +** This locking mode is appropriate for use on read-only databases +** (ex: databases that are burned into CD-ROM, for example.) It can +** also be used if the application employs some external mechanism to +** prevent simultaneous access of the same database by two or more +** database connections. But there is a serious risk of database +** corruption if this locking mode is used in situations where multiple +** database connections are accessing the same database file at the same +** time and one or more of those connections are writing. +*/ + +static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){ + UNUSED_PARAMETER(NotUsed); + *pResOut = 0; + return SQLITE_OK; +} +static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return SQLITE_OK; +} +static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return SQLITE_OK; +} + +/* +** Close the file. +*/ +static int nolockClose(sqlite3_file *id) { + return closeUnixFile(id); +} + +/******************* End of the no-op lock implementation ********************* +******************************************************************************/ + +/****************************************************************************** +************************* Begin dot-file Locking ****************************** +** +** The dotfile locking implementation uses the existence of separate lock +** files (really a directory) to control access to the database. This works +** on just about every filesystem imaginable. But there are serious downsides: +** +** (1) There is zero concurrency. A single reader blocks all other +** connections from reading or writing the database. +** +** (2) An application crash or power loss can leave stale lock files +** sitting around that need to be cleared manually. +** +** Nevertheless, a dotlock is an appropriate locking mode for use if no +** other locking strategy is available. +** +** Dotfile locking works by creating a subdirectory in the same directory as +** the database and with the same name but with a ".lock" extension added. +** The existence of a lock directory implies an EXCLUSIVE lock. All other +** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE. +*/ + +/* +** The file suffix added to the data base filename in order to create the +** lock directory. +*/ +#define DOTLOCK_SUFFIX ".lock" + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +** +** In dotfile locking, either a lock exists or it does not. So in this +** variation of CheckReservedLock(), *pResOut is set to true if any lock +** is held on the file and false if the file is unlocked. +*/ +static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { + int rc = SQLITE_OK; + int reserved = 0; + unixFile *pFile = (unixFile*)id; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + + assert( pFile ); + + /* Check if a thread in this process holds such a lock */ + if( pFile->eFileLock>SHARED_LOCK ){ + /* Either this connection or some other connection in the same process + ** holds a lock on the file. No need to check further. */ + reserved = 1; + }else{ + /* The lock is held if and only if the lockfile exists */ + const char *zLockFile = (const char*)pFile->lockingContext; + reserved = osAccess(zLockFile, 0)==0; + } + OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved)); + *pResOut = reserved; + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +** +** With dotfile locking, we really only support state (4): EXCLUSIVE. +** But we track the other locking levels internally. +*/ +static int dotlockLock(sqlite3_file *id, int eFileLock) { + unixFile *pFile = (unixFile*)id; + char *zLockFile = (char *)pFile->lockingContext; + int rc = SQLITE_OK; + + + /* If we have any lock, then the lock file already exists. All we have + ** to do is adjust our internal record of the lock level. + */ + if( pFile->eFileLock > NO_LOCK ){ + pFile->eFileLock = eFileLock; + /* Always update the timestamp on the old file */ +#ifdef HAVE_UTIME + utime(zLockFile, NULL); +#else + utimes(zLockFile, NULL); +#endif + return SQLITE_OK; + } + + /* grab an exclusive lock */ + rc = osMkdir(zLockFile, 0777); + if( rc<0 ){ + /* failed to open/create the lock directory */ + int tErrno = errno; + if( EEXIST == tErrno ){ + rc = SQLITE_BUSY; + } else { + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + } + return rc; + } + + /* got it, set the type and return ok */ + pFile->eFileLock = eFileLock; + return rc; +} + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +** +** When the locking level reaches NO_LOCK, delete the lock file. +*/ +static int dotlockUnlock(sqlite3_file *id, int eFileLock) { + unixFile *pFile = (unixFile*)id; + char *zLockFile = (char *)pFile->lockingContext; + int rc; + + assert( pFile ); + OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock, + pFile->eFileLock, getpid())); + assert( eFileLock<=SHARED_LOCK ); + + /* no-op if possible */ + if( pFile->eFileLock==eFileLock ){ + return SQLITE_OK; + } + + /* To downgrade to shared, simply update our internal notion of the + ** lock state. No need to mess with the file on disk. + */ + if( eFileLock==SHARED_LOCK ){ + pFile->eFileLock = SHARED_LOCK; + return SQLITE_OK; + } + + /* To fully unlock the database, delete the lock file */ + assert( eFileLock==NO_LOCK ); + rc = osRmdir(zLockFile); + if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile); + if( rc<0 ){ + int tErrno = errno; + rc = 0; + if( ENOENT != tErrno ){ + rc = SQLITE_IOERR_UNLOCK; + } + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + return rc; + } + pFile->eFileLock = NO_LOCK; + return SQLITE_OK; +} + +/* +** Close a file. Make sure the lock has been released before closing. +*/ +static int dotlockClose(sqlite3_file *id) { + int rc = SQLITE_OK; + if( id ){ + unixFile *pFile = (unixFile*)id; + dotlockUnlock(id, NO_LOCK); + sqlite3_free(pFile->lockingContext); + rc = closeUnixFile(id); + } + return rc; +} +/****************** End of the dot-file lock implementation ******************* +******************************************************************************/ + +/****************************************************************************** +************************** Begin flock Locking ******************************** +** +** Use the flock() system call to do file locking. +** +** flock() locking is like dot-file locking in that the various +** fine-grain locking levels supported by SQLite are collapsed into +** a single exclusive lock. In other words, SHARED, RESERVED, and +** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite +** still works when you do this, but concurrency is reduced since +** only a single process can be reading the database at a time. +** +** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if +** compiling for VXWORKS. +*/ +#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS + +/* +** Retry flock() calls that fail with EINTR +*/ +#ifdef EINTR +static int robust_flock(int fd, int op){ + int rc; + do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR ); + return rc; +} +#else +# define robust_flock(a,b) flock(a,b) +#endif + + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +*/ +static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ + int rc = SQLITE_OK; + int reserved = 0; + unixFile *pFile = (unixFile*)id; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + + assert( pFile ); + + /* Check if a thread in this process holds such a lock */ + if( pFile->eFileLock>SHARED_LOCK ){ + reserved = 1; + } + + /* Otherwise see if some other process holds it. */ + if( !reserved ){ + /* attempt to get the lock */ + int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB); + if( !lrc ){ + /* got the lock, unlock it */ + lrc = robust_flock(pFile->h, LOCK_UN); + if ( lrc ) { + int tErrno = errno; + /* unlock failed with an error */ + lrc = SQLITE_IOERR_UNLOCK; + if( IS_LOCK_ERROR(lrc) ){ + pFile->lastErrno = tErrno; + rc = lrc; + } + } + } else { + int tErrno = errno; + reserved = 1; + /* someone else might have it reserved */ + lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( IS_LOCK_ERROR(lrc) ){ + pFile->lastErrno = tErrno; + rc = lrc; + } + } + } + OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved)); + +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ + rc = SQLITE_OK; + reserved=1; + } +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ + *pResOut = reserved; + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** flock() only really support EXCLUSIVE locks. We track intermediate +** lock states in the sqlite3_file structure, but all locks SHARED or +** above are really EXCLUSIVE locks and exclude all other processes from +** access the file. +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +*/ +static int flockLock(sqlite3_file *id, int eFileLock) { + int rc = SQLITE_OK; + unixFile *pFile = (unixFile*)id; + + assert( pFile ); + + /* if we already have a lock, it is exclusive. + ** Just adjust level and punt on outta here. */ + if (pFile->eFileLock > NO_LOCK) { + pFile->eFileLock = eFileLock; + return SQLITE_OK; + } + + /* grab an exclusive lock */ + + if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) { + int tErrno = errno; + /* didn't get, must be busy */ + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + } else { + /* got it, set the type and return ok */ + pFile->eFileLock = eFileLock; + } + OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), + rc==SQLITE_OK ? "ok" : "failed")); +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ + rc = SQLITE_BUSY; + } +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ + return rc; +} + + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +*/ +static int flockUnlock(sqlite3_file *id, int eFileLock) { + unixFile *pFile = (unixFile*)id; + + assert( pFile ); + OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock, + pFile->eFileLock, getpid())); + assert( eFileLock<=SHARED_LOCK ); + + /* no-op if possible */ + if( pFile->eFileLock==eFileLock ){ + return SQLITE_OK; + } + + /* shared can just be set because we always have an exclusive */ + if (eFileLock==SHARED_LOCK) { + pFile->eFileLock = eFileLock; + return SQLITE_OK; + } + + /* no, really, unlock. */ + if( robust_flock(pFile->h, LOCK_UN) ){ +#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS + return SQLITE_OK; +#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ + return SQLITE_IOERR_UNLOCK; + }else{ + pFile->eFileLock = NO_LOCK; + return SQLITE_OK; + } +} + +/* +** Close a file. +*/ +static int flockClose(sqlite3_file *id) { + int rc = SQLITE_OK; + if( id ){ + flockUnlock(id, NO_LOCK); + rc = closeUnixFile(id); + } + return rc; +} + +#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */ + +/******************* End of the flock lock implementation ********************* +******************************************************************************/ + +/****************************************************************************** +************************ Begin Named Semaphore Locking ************************ +** +** Named semaphore locking is only supported on VxWorks. +** +** Semaphore locking is like dot-lock and flock in that it really only +** supports EXCLUSIVE locking. Only a single process can read or write +** the database file at a time. This reduces potential concurrency, but +** makes the lock implementation much easier. +*/ +#if OS_VXWORKS + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +*/ +static int semCheckReservedLock(sqlite3_file *id, int *pResOut) { + int rc = SQLITE_OK; + int reserved = 0; + unixFile *pFile = (unixFile*)id; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + + assert( pFile ); + + /* Check if a thread in this process holds such a lock */ + if( pFile->eFileLock>SHARED_LOCK ){ + reserved = 1; + } + + /* Otherwise see if some other process holds it. */ + if( !reserved ){ + sem_t *pSem = pFile->pInode->pSem; + struct stat statBuf; + + if( sem_trywait(pSem)==-1 ){ + int tErrno = errno; + if( EAGAIN != tErrno ){ + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK); + pFile->lastErrno = tErrno; + } else { + /* someone else has the lock when we are in NO_LOCK */ + reserved = (pFile->eFileLock < SHARED_LOCK); + } + }else{ + /* we could have it if we want it */ + sem_post(pSem); + } + } + OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved)); + + *pResOut = reserved; + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** Semaphore locks only really support EXCLUSIVE locks. We track intermediate +** lock states in the sqlite3_file structure, but all locks SHARED or +** above are really EXCLUSIVE locks and exclude all other processes from +** access the file. +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +*/ +static int semLock(sqlite3_file *id, int eFileLock) { + unixFile *pFile = (unixFile*)id; + int fd; + sem_t *pSem = pFile->pInode->pSem; + int rc = SQLITE_OK; + + /* if we already have a lock, it is exclusive. + ** Just adjust level and punt on outta here. */ + if (pFile->eFileLock > NO_LOCK) { + pFile->eFileLock = eFileLock; + rc = SQLITE_OK; + goto sem_end_lock; + } + + /* lock semaphore now but bail out when already locked. */ + if( sem_trywait(pSem)==-1 ){ + rc = SQLITE_BUSY; + goto sem_end_lock; + } + + /* got it, set the type and return ok */ + pFile->eFileLock = eFileLock; + + sem_end_lock: + return rc; +} + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +*/ +static int semUnlock(sqlite3_file *id, int eFileLock) { + unixFile *pFile = (unixFile*)id; + sem_t *pSem = pFile->pInode->pSem; + + assert( pFile ); + assert( pSem ); + OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock, + pFile->eFileLock, getpid())); + assert( eFileLock<=SHARED_LOCK ); + + /* no-op if possible */ + if( pFile->eFileLock==eFileLock ){ + return SQLITE_OK; + } + + /* shared can just be set because we always have an exclusive */ + if (eFileLock==SHARED_LOCK) { + pFile->eFileLock = eFileLock; + return SQLITE_OK; + } + + /* no, really unlock. */ + if ( sem_post(pSem)==-1 ) { + int rc, tErrno = errno; + rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + return rc; + } + pFile->eFileLock = NO_LOCK; + return SQLITE_OK; +} + +/* + ** Close a file. + */ +static int semClose(sqlite3_file *id) { + if( id ){ + unixFile *pFile = (unixFile*)id; + semUnlock(id, NO_LOCK); + assert( pFile ); + unixEnterMutex(); + releaseInodeInfo(pFile); + unixLeaveMutex(); + closeUnixFile(id); + } + return SQLITE_OK; +} + +#endif /* OS_VXWORKS */ +/* +** Named semaphore locking is only available on VxWorks. +** +*************** End of the named semaphore lock implementation **************** +******************************************************************************/ + + +/****************************************************************************** +*************************** Begin AFP Locking ********************************* +** +** AFP is the Apple Filing Protocol. AFP is a network filesystem found +** on Apple Macintosh computers - both OS9 and OSX. +** +** Third-party implementations of AFP are available. But this code here +** only works on OSX. +*/ + +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE +/* +** The afpLockingContext structure contains all afp lock specific state +*/ +typedef struct afpLockingContext afpLockingContext; +struct afpLockingContext { + int reserved; + const char *dbPath; /* Name of the open file */ +}; + +struct ByteRangeLockPB2 +{ + unsigned long long offset; /* offset to first byte to lock */ + unsigned long long length; /* nbr of bytes to lock */ + unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */ + unsigned char unLockFlag; /* 1 = unlock, 0 = lock */ + unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */ + int fd; /* file desc to assoc this lock with */ +}; + +#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2) + +/* +** This is a utility for setting or clearing a bit-range lock on an +** AFP filesystem. +** +** Return SQLITE_OK on success, SQLITE_BUSY on failure. +*/ +static int afpSetLock( + const char *path, /* Name of the file to be locked or unlocked */ + unixFile *pFile, /* Open file descriptor on path */ + unsigned long long offset, /* First byte to be locked */ + unsigned long long length, /* Number of bytes to lock */ + int setLockFlag /* True to set lock. False to clear lock */ +){ + struct ByteRangeLockPB2 pb; + int err; + + pb.unLockFlag = setLockFlag ? 0 : 1; + pb.startEndFlag = 0; + pb.offset = offset; + pb.length = length; + pb.fd = pFile->h; + + OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", + (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""), + offset, length)); + err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0); + if ( err==-1 ) { + int rc; + int tErrno = errno; + OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n", + path, tErrno, strerror(tErrno))); +#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS + rc = SQLITE_BUSY; +#else + rc = sqliteErrorFromPosixError(tErrno, + setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK); +#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */ + if( IS_LOCK_ERROR(rc) ){ + pFile->lastErrno = tErrno; + } + return rc; + } else { + return SQLITE_OK; + } +} + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +*/ +static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ + int rc = SQLITE_OK; + int reserved = 0; + unixFile *pFile = (unixFile*)id; + afpLockingContext *context; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + + assert( pFile ); + context = (afpLockingContext *) pFile->lockingContext; + if( context->reserved ){ + *pResOut = 1; + return SQLITE_OK; + } + unixEnterMutex(); /* Because pFile->pInode is shared across threads */ + + /* Check if a thread in this process holds such a lock */ + if( pFile->pInode->eFileLock>SHARED_LOCK ){ + reserved = 1; + } + + /* Otherwise see if some other process holds it. + */ + if( !reserved ){ + /* lock the RESERVED byte */ + int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); + if( SQLITE_OK==lrc ){ + /* if we succeeded in taking the reserved lock, unlock it to restore + ** the original state */ + lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); + } else { + /* if we failed to get the lock then someone else must have it */ + reserved = 1; + } + if( IS_LOCK_ERROR(lrc) ){ + rc=lrc; + } + } + + unixLeaveMutex(); + OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved)); + + *pResOut = reserved; + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +*/ +static int afpLock(sqlite3_file *id, int eFileLock){ + int rc = SQLITE_OK; + unixFile *pFile = (unixFile*)id; + unixInodeInfo *pInode = pFile->pInode; + afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; + + assert( pFile ); + OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h, + azFileLock(eFileLock), azFileLock(pFile->eFileLock), + azFileLock(pInode->eFileLock), pInode->nShared , getpid())); + + /* If there is already a lock of this type or more restrictive on the + ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as + ** unixEnterMutex() hasn't been called yet. + */ + if( pFile->eFileLock>=eFileLock ){ + OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h, + azFileLock(eFileLock))); + return SQLITE_OK; + } + + /* Make sure the locking sequence is correct + ** (1) We never move from unlocked to anything higher than shared lock. + ** (2) SQLite never explicitly requests a pendig lock. + ** (3) A shared lock is always held when a reserve lock is requested. + */ + assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); + assert( eFileLock!=PENDING_LOCK ); + assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); + + /* This mutex is needed because pFile->pInode is shared across threads + */ + unixEnterMutex(); + pInode = pFile->pInode; + + /* If some thread using this PID has a lock via a different unixFile* + ** handle that precludes the requested lock, return BUSY. + */ + if( (pFile->eFileLock!=pInode->eFileLock && + (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) + ){ + rc = SQLITE_BUSY; + goto afp_end_lock; + } + + /* If a SHARED lock is requested, and some thread using this PID already + ** has a SHARED or RESERVED lock, then increment reference counts and + ** return SQLITE_OK. + */ + if( eFileLock==SHARED_LOCK && + (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ + assert( eFileLock==SHARED_LOCK ); + assert( pFile->eFileLock==0 ); + assert( pInode->nShared>0 ); + pFile->eFileLock = SHARED_LOCK; + pInode->nShared++; + pInode->nLock++; + goto afp_end_lock; + } + + /* A PENDING lock is needed before acquiring a SHARED lock and before + ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will + ** be released. + */ + if( eFileLock==SHARED_LOCK + || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLockdbPath, pFile, PENDING_BYTE, 1, 1); + if (failed) { + rc = failed; + goto afp_end_lock; + } + } + + /* If control gets to this point, then actually go ahead and make + ** operating system calls for the specified lock. + */ + if( eFileLock==SHARED_LOCK ){ + int lrc1, lrc2, lrc1Errno = 0; + long lk, mask; + + assert( pInode->nShared==0 ); + assert( pInode->eFileLock==0 ); + + mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff; + /* Now get the read-lock SHARED_LOCK */ + /* note that the quality of the randomness doesn't matter that much */ + lk = random(); + pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1); + lrc1 = afpSetLock(context->dbPath, pFile, + SHARED_FIRST+pInode->sharedByte, 1, 1); + if( IS_LOCK_ERROR(lrc1) ){ + lrc1Errno = pFile->lastErrno; + } + /* Drop the temporary PENDING lock */ + lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); + + if( IS_LOCK_ERROR(lrc1) ) { + pFile->lastErrno = lrc1Errno; + rc = lrc1; + goto afp_end_lock; + } else if( IS_LOCK_ERROR(lrc2) ){ + rc = lrc2; + goto afp_end_lock; + } else if( lrc1 != SQLITE_OK ) { + rc = lrc1; + } else { + pFile->eFileLock = SHARED_LOCK; + pInode->nLock++; + pInode->nShared = 1; + } + }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ + /* We are trying for an exclusive lock but another thread in this + ** same process is still holding a shared lock. */ + rc = SQLITE_BUSY; + }else{ + /* The request was for a RESERVED or EXCLUSIVE lock. It is + ** assumed that there is a SHARED or greater lock on the file + ** already. + */ + int failed = 0; + assert( 0!=pFile->eFileLock ); + if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) { + /* Acquire a RESERVED lock */ + failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); + if( !failed ){ + context->reserved = 1; + } + } + if (!failed && eFileLock == EXCLUSIVE_LOCK) { + /* Acquire an EXCLUSIVE lock */ + + /* Remove the shared lock before trying the range. we'll need to + ** reestablish the shared lock if we can't get the afpUnlock + */ + if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST + + pInode->sharedByte, 1, 0)) ){ + int failed2 = SQLITE_OK; + /* now attemmpt to get the exclusive lock range */ + failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, + SHARED_SIZE, 1); + if( failed && (failed2 = afpSetLock(context->dbPath, pFile, + SHARED_FIRST + pInode->sharedByte, 1, 1)) ){ + /* Can't reestablish the shared lock. Sqlite can't deal, this is + ** a critical I/O error + */ + rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : + SQLITE_IOERR_LOCK; + goto afp_end_lock; + } + }else{ + rc = failed; + } + } + if( failed ){ + rc = failed; + } + } + + if( rc==SQLITE_OK ){ + pFile->eFileLock = eFileLock; + pInode->eFileLock = eFileLock; + }else if( eFileLock==EXCLUSIVE_LOCK ){ + pFile->eFileLock = PENDING_LOCK; + pInode->eFileLock = PENDING_LOCK; + } + +afp_end_lock: + unixLeaveMutex(); + OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), + rc==SQLITE_OK ? "ok" : "failed")); + return rc; +} + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +*/ +static int afpUnlock(sqlite3_file *id, int eFileLock) { + int rc = SQLITE_OK; + unixFile *pFile = (unixFile*)id; + unixInodeInfo *pInode; + afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; + int skipShared = 0; +#ifdef SQLITE_TEST + int h = pFile->h; +#endif + + assert( pFile ); + OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock, + pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, + getpid())); + + assert( eFileLock<=SHARED_LOCK ); + if( pFile->eFileLock<=eFileLock ){ + return SQLITE_OK; + } + unixEnterMutex(); + pInode = pFile->pInode; + assert( pInode->nShared!=0 ); + if( pFile->eFileLock>SHARED_LOCK ){ + assert( pInode->eFileLock==pFile->eFileLock ); + SimulateIOErrorBenign(1); + SimulateIOError( h=(-1) ) + SimulateIOErrorBenign(0); + +#ifdef SQLITE_DEBUG + /* When reducing a lock such that other processes can start + ** reading the database file again, make sure that the + ** transaction counter was updated if any part of the database + ** file changed. If the transaction counter is not updated, + ** other connections to the same file might not realize that + ** the file has changed and hence might not know to flush their + ** cache. The use of a stale cache can lead to database corruption. + */ + assert( pFile->inNormalWrite==0 + || pFile->dbUpdate==0 + || pFile->transCntrChng==1 ); + pFile->inNormalWrite = 0; +#endif + + if( pFile->eFileLock==EXCLUSIVE_LOCK ){ + rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0); + if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){ + /* only re-establish the shared lock if necessary */ + int sharedLockByte = SHARED_FIRST+pInode->sharedByte; + rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1); + } else { + skipShared = 1; + } + } + if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){ + rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); + } + if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){ + rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); + if( !rc ){ + context->reserved = 0; + } + } + if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){ + pInode->eFileLock = SHARED_LOCK; + } + } + if( rc==SQLITE_OK && eFileLock==NO_LOCK ){ + + /* Decrement the shared lock counter. Release the lock using an + ** OS call only when all threads in this same process have released + ** the lock. + */ + unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte; + pInode->nShared--; + if( pInode->nShared==0 ){ + SimulateIOErrorBenign(1); + SimulateIOError( h=(-1) ) + SimulateIOErrorBenign(0); + if( !skipShared ){ + rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0); + } + if( !rc ){ + pInode->eFileLock = NO_LOCK; + pFile->eFileLock = NO_LOCK; + } + } + if( rc==SQLITE_OK ){ + pInode->nLock--; + assert( pInode->nLock>=0 ); + if( pInode->nLock==0 ){ + closePendingFds(pFile); + } + } + } + + unixLeaveMutex(); + if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock; + return rc; +} + +/* +** Close a file & cleanup AFP specific locking context +*/ +static int afpClose(sqlite3_file *id) { + int rc = SQLITE_OK; + if( id ){ + unixFile *pFile = (unixFile*)id; + afpUnlock(id, NO_LOCK); + unixEnterMutex(); + if( pFile->pInode && pFile->pInode->nLock ){ + /* If there are outstanding locks, do not actually close the file just + ** yet because that would clear those locks. Instead, add the file + ** descriptor to pInode->aPending. It will be automatically closed when + ** the last lock is cleared. + */ + setPendingFd(pFile); + } + releaseInodeInfo(pFile); + sqlite3_free(pFile->lockingContext); + rc = closeUnixFile(id); + unixLeaveMutex(); + } + return rc; +} + +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ +/* +** The code above is the AFP lock implementation. The code is specific +** to MacOSX and does not work on other unix platforms. No alternative +** is available. If you don't compile for a mac, then the "unix-afp" +** VFS is not available. +** +********************* End of the AFP lock implementation ********************** +******************************************************************************/ + +/****************************************************************************** +*************************** Begin NFS Locking ********************************/ + +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE +/* + ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock + ** must be either NO_LOCK or SHARED_LOCK. + ** + ** If the locking level of the file descriptor is already at or below + ** the requested locking level, this routine is a no-op. + */ +static int nfsUnlock(sqlite3_file *id, int eFileLock){ + return posixUnlock(id, eFileLock, 1); +} + +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ +/* +** The code above is the NFS lock implementation. The code is specific +** to MacOSX and does not work on other unix platforms. No alternative +** is available. +** +********************* End of the NFS lock implementation ********************** +******************************************************************************/ + +/****************************************************************************** +**************** Non-locking sqlite3_file methods ***************************** +** +** The next division contains implementations for all methods of the +** sqlite3_file object other than the locking methods. The locking +** methods were defined in divisions above (one locking method per +** division). Those methods that are common to all locking modes +** are gather together into this division. +*/ + +/* +** Seek to the offset passed as the second argument, then read cnt +** bytes into pBuf. Return the number of bytes actually read. +** +** NB: If you define USE_PREAD or USE_PREAD64, then it might also +** be necessary to define _XOPEN_SOURCE to be 500. This varies from +** one system to another. Since SQLite does not define USE_PREAD +** any any form by default, we will not attempt to define _XOPEN_SOURCE. +** See tickets #2741 and #2681. +** +** To avoid stomping the errno value on a failed read the lastErrno value +** is set before returning. +*/ +static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ + int got; + int prior = 0; +#if (!defined(USE_PREAD) && !defined(USE_PREAD64)) + i64 newOffset; +#endif + TIMER_START; + assert( cnt==(cnt&0x1ffff) ); + assert( id->h>2 ); + cnt &= 0x1ffff; + do{ +#if defined(USE_PREAD) + got = osPread(id->h, pBuf, cnt, offset); + SimulateIOError( got = -1 ); +#elif defined(USE_PREAD64) + got = osPread64(id->h, pBuf, cnt, offset); + SimulateIOError( got = -1 ); +#else + newOffset = lseek(id->h, offset, SEEK_SET); + SimulateIOError( newOffset-- ); + if( newOffset!=offset ){ + if( newOffset == -1 ){ + ((unixFile*)id)->lastErrno = errno; + }else{ + ((unixFile*)id)->lastErrno = 0; + } + return -1; + } + got = osRead(id->h, pBuf, cnt); +#endif + if( got==cnt ) break; + if( got<0 ){ + if( errno==EINTR ){ got = 1; continue; } + prior = 0; + ((unixFile*)id)->lastErrno = errno; + break; + }else if( got>0 ){ + cnt -= got; + offset += got; + prior += got; + pBuf = (void*)(got + (char*)pBuf); + } + }while( got>0 ); + TIMER_END; + OSTRACE(("READ %-3d %5d %7lld %llu\n", + id->h, got+prior, offset-prior, TIMER_ELAPSED)); + return got+prior; +} + +/* +** Read data from a file into a buffer. Return SQLITE_OK if all +** bytes were read successfully and SQLITE_IOERR if anything goes +** wrong. +*/ +static int unixRead( + sqlite3_file *id, + void *pBuf, + int amt, + sqlite3_int64 offset +){ + unixFile *pFile = (unixFile *)id; + int got; + assert( id ); + assert( offset>=0 ); + assert( amt>0 ); + + /* If this is a database file (not a journal, master-journal or temp + ** file), the bytes in the locking range should never be read or written. */ +#if 0 + assert( pFile->pUnused==0 + || offset>=PENDING_BYTE+512 + || offset+amt<=PENDING_BYTE + ); +#endif + +#if SQLITE_MAX_MMAP_SIZE>0 + /* Deal with as much of this read request as possible by transfering + ** data from the memory mapping using memcpy(). */ + if( offsetmmapSize ){ + if( offset+amt <= pFile->mmapSize ){ + memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); + return SQLITE_OK; + }else{ + int nCopy = pFile->mmapSize - offset; + memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); + pBuf = &((u8 *)pBuf)[nCopy]; + amt -= nCopy; + offset += nCopy; + } + } +#endif + + got = seekAndRead(pFile, offset, pBuf, amt); + if( got==amt ){ + return SQLITE_OK; + }else if( got<0 ){ + /* lastErrno set by seekAndRead */ + return SQLITE_IOERR_READ; + }else{ + pFile->lastErrno = 0; /* not a system error */ + /* Unread parts of the buffer must be zero-filled */ + memset(&((char*)pBuf)[got], 0, amt-got); + return SQLITE_IOERR_SHORT_READ; + } +} + +/* +** Attempt to seek the file-descriptor passed as the first argument to +** absolute offset iOff, then attempt to write nBuf bytes of data from +** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, +** return the actual number of bytes written (which may be less than +** nBuf). +*/ +static int seekAndWriteFd( + int fd, /* File descriptor to write to */ + i64 iOff, /* File offset to begin writing at */ + const void *pBuf, /* Copy data from this buffer to the file */ + int nBuf, /* Size of buffer pBuf in bytes */ + int *piErrno /* OUT: Error number if error occurs */ +){ + int rc = 0; /* Value returned by system call */ + + assert( nBuf==(nBuf&0x1ffff) ); + assert( fd>2 ); + nBuf &= 0x1ffff; + TIMER_START; + +#if defined(USE_PREAD) + do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR ); +#elif defined(USE_PREAD64) + do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR); +#else + do{ + i64 iSeek = lseek(fd, iOff, SEEK_SET); + SimulateIOError( iSeek-- ); + + if( iSeek!=iOff ){ + if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0); + return -1; + } + rc = osWrite(fd, pBuf, nBuf); + }while( rc<0 && errno==EINTR ); +#endif + + TIMER_END; + OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED)); + + if( rc<0 && piErrno ) *piErrno = errno; + return rc; +} + + +/* +** Seek to the offset in id->offset then read cnt bytes into pBuf. +** Return the number of bytes actually read. Update the offset. +** +** To avoid stomping the errno value on a failed write the lastErrno value +** is set before returning. +*/ +static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ + return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno); +} + + +/* +** Write data from a buffer into a file. Return SQLITE_OK on success +** or some other error code on failure. +*/ +static int unixWrite( + sqlite3_file *id, + const void *pBuf, + int amt, + sqlite3_int64 offset +){ + unixFile *pFile = (unixFile*)id; + int wrote = 0; + assert( id ); + assert( amt>0 ); + + /* If this is a database file (not a journal, master-journal or temp + ** file), the bytes in the locking range should never be read or written. */ +#if 0 + assert( pFile->pUnused==0 + || offset>=PENDING_BYTE+512 + || offset+amt<=PENDING_BYTE + ); +#endif + +#ifdef SQLITE_DEBUG + /* If we are doing a normal write to a database file (as opposed to + ** doing a hot-journal rollback or a write to some file other than a + ** normal database file) then record the fact that the database + ** has changed. If the transaction counter is modified, record that + ** fact too. + */ + if( pFile->inNormalWrite ){ + pFile->dbUpdate = 1; /* The database has been modified */ + if( offset<=24 && offset+amt>=27 ){ + int rc; + char oldCntr[4]; + SimulateIOErrorBenign(1); + rc = seekAndRead(pFile, 24, oldCntr, 4); + SimulateIOErrorBenign(0); + if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){ + pFile->transCntrChng = 1; /* The transaction counter has changed */ + } + } + } +#endif + +#if SQLITE_MAX_MMAP_SIZE>0 + /* Deal with as much of this write request as possible by transfering + ** data from the memory mapping using memcpy(). */ + if( offsetmmapSize ){ + if( offset+amt <= pFile->mmapSize ){ + memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); + return SQLITE_OK; + }else{ + int nCopy = pFile->mmapSize - offset; + memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); + pBuf = &((u8 *)pBuf)[nCopy]; + amt -= nCopy; + offset += nCopy; + } + } +#endif + + while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){ + amt -= wrote; + offset += wrote; + pBuf = &((char*)pBuf)[wrote]; + } + SimulateIOError(( wrote=(-1), amt=1 )); + SimulateDiskfullError(( wrote=0, amt=1 )); + + if( amt>0 ){ + if( wrote<0 && pFile->lastErrno!=ENOSPC ){ + /* lastErrno set by seekAndWrite */ + return SQLITE_IOERR_WRITE; + }else{ + pFile->lastErrno = 0; /* not a system error */ + return SQLITE_FULL; + } + } + + return SQLITE_OK; +} + +#ifdef SQLITE_TEST +/* +** Count the number of fullsyncs and normal syncs. This is used to test +** that syncs and fullsyncs are occurring at the right times. +*/ +int sqlite3_sync_count = 0; +int sqlite3_fullsync_count = 0; +#endif + +/* +** We do not trust systems to provide a working fdatasync(). Some do. +** Others do no. To be safe, we will stick with the (slightly slower) +** fsync(). If you know that your system does support fdatasync() correctly, +** then simply compile with -Dfdatasync=fdatasync +*/ +#if !defined(fdatasync) +# define fdatasync fsync +#endif + +/* +** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not +** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently +** only available on Mac OS X. But that could change. +*/ +#ifdef F_FULLFSYNC +# define HAVE_FULLFSYNC 1 +#else +# define HAVE_FULLFSYNC 0 +#endif + + +/* +** The fsync() system call does not work as advertised on many +** unix systems. The following procedure is an attempt to make +** it work better. +** +** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful +** for testing when we want to run through the test suite quickly. +** You are strongly advised *not* to deploy with SQLITE_NO_SYNC +** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash +** or power failure will likely corrupt the database file. +** +** SQLite sets the dataOnly flag if the size of the file is unchanged. +** The idea behind dataOnly is that it should only write the file content +** to disk, not the inode. We only set dataOnly if the file size is +** unchanged since the file size is part of the inode. However, +** Ted Ts'o tells us that fdatasync() will also write the inode if the +** file size has changed. The only real difference between fdatasync() +** and fsync(), Ted tells us, is that fdatasync() will not flush the +** inode if the mtime or owner or other inode attributes have changed. +** We only care about the file size, not the other file attributes, so +** as far as SQLite is concerned, an fdatasync() is always adequate. +** So, we always use fdatasync() if it is available, regardless of +** the value of the dataOnly flag. +*/ +static int full_fsync(int fd, int fullSync, int dataOnly){ + int rc; + + /* The following "ifdef/elif/else/" block has the same structure as + ** the one below. It is replicated here solely to avoid cluttering + ** up the real code with the UNUSED_PARAMETER() macros. + */ +#ifdef SQLITE_NO_SYNC + UNUSED_PARAMETER(fd); + UNUSED_PARAMETER(fullSync); + UNUSED_PARAMETER(dataOnly); +#elif HAVE_FULLFSYNC + UNUSED_PARAMETER(dataOnly); +#else + UNUSED_PARAMETER(fullSync); + UNUSED_PARAMETER(dataOnly); +#endif + + /* Record the number of times that we do a normal fsync() and + ** FULLSYNC. This is used during testing to verify that this procedure + ** gets called with the correct arguments. + */ +#ifdef SQLITE_TEST + if( fullSync ) sqlite3_fullsync_count++; + sqlite3_sync_count++; +#endif + + /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a + ** no-op + */ +#ifdef SQLITE_NO_SYNC + rc = SQLITE_OK; +#elif HAVE_FULLFSYNC + if( fullSync ){ + rc = osFcntl(fd, F_FULLFSYNC, 0); + }else{ + rc = 1; + } + /* If the FULLFSYNC failed, fall back to attempting an fsync(). + ** It shouldn't be possible for fullfsync to fail on the local + ** file system (on OSX), so failure indicates that FULLFSYNC + ** isn't supported for this file system. So, attempt an fsync + ** and (for now) ignore the overhead of a superfluous fcntl call. + ** It'd be better to detect fullfsync support once and avoid + ** the fcntl call every time sync is called. + */ + if( rc ) rc = fsync(fd); + +#elif defined(__APPLE__) + /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly + ** so currently we default to the macro that redefines fdatasync to fsync + */ + rc = fsync(fd); +#else + rc = fdatasync(fd); +#if OS_VXWORKS + if( rc==-1 && errno==ENOTSUP ){ + rc = fsync(fd); + } +#endif /* OS_VXWORKS */ +#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */ + + if( OS_VXWORKS && rc!= -1 ){ + rc = 0; + } + return rc; +} + +/* +** Open a file descriptor to the directory containing file zFilename. +** If successful, *pFd is set to the opened file descriptor and +** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM +** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined +** value. +** +** The directory file descriptor is used for only one thing - to +** fsync() a directory to make sure file creation and deletion events +** are flushed to disk. Such fsyncs are not needed on newer +** journaling filesystems, but are required on older filesystems. +** +** This routine can be overridden using the xSetSysCall interface. +** The ability to override this routine was added in support of the +** chromium sandbox. Opening a directory is a security risk (we are +** told) so making it overrideable allows the chromium sandbox to +** replace this routine with a harmless no-op. To make this routine +** a no-op, replace it with a stub that returns SQLITE_OK but leaves +** *pFd set to a negative number. +** +** If SQLITE_OK is returned, the caller is responsible for closing +** the file descriptor *pFd using close(). +*/ +static int openDirectory(const char *zFilename, int *pFd){ + int ii; + int fd = -1; + char zDirname[MAX_PATHNAME+1]; + + sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); + for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--); + if( ii>0 ){ + zDirname[ii] = '\0'; + fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0); + if( fd>=0 ){ + OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); + } + } + *pFd = fd; + return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname)); +} + +/* +** Make sure all writes to a particular file are committed to disk. +** +** If dataOnly==0 then both the file itself and its metadata (file +** size, access time, etc) are synced. If dataOnly!=0 then only the +** file data is synced. +** +** Under Unix, also make sure that the directory entry for the file +** has been created by fsync-ing the directory that contains the file. +** If we do not do this and we encounter a power failure, the directory +** entry for the journal might not exist after we reboot. The next +** SQLite to access the file will not know that the journal exists (because +** the directory entry for the journal was never created) and the transaction +** will not roll back - possibly leading to database corruption. +*/ +static int unixSync(sqlite3_file *id, int flags){ + int rc; + unixFile *pFile = (unixFile*)id; + + int isDataOnly = (flags&SQLITE_SYNC_DATAONLY); + int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL; + + /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ + assert((flags&0x0F)==SQLITE_SYNC_NORMAL + || (flags&0x0F)==SQLITE_SYNC_FULL + ); + + /* Unix cannot, but some systems may return SQLITE_FULL from here. This + ** line is to test that doing so does not cause any problems. + */ + SimulateDiskfullError( return SQLITE_FULL ); + + assert( pFile ); + OSTRACE(("SYNC %-3d\n", pFile->h)); + rc = full_fsync(pFile->h, isFullsync, isDataOnly); + SimulateIOError( rc=1 ); + if( rc ){ + pFile->lastErrno = errno; + return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath); + } + + /* Also fsync the directory containing the file if the DIRSYNC flag + ** is set. This is a one-time occurrence. Many systems (examples: AIX) + ** are unable to fsync a directory, so ignore errors on the fsync. + */ + if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){ + int dirfd; + OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath, + HAVE_FULLFSYNC, isFullsync)); + rc = osOpenDirectory(pFile->zPath, &dirfd); + if( rc==SQLITE_OK && dirfd>=0 ){ + full_fsync(dirfd, 0, 0); + robust_close(pFile, dirfd, __LINE__); + }else if( rc==SQLITE_CANTOPEN ){ + rc = SQLITE_OK; + } + pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC; + } + return rc; +} + +/* +** Truncate an open file to a specified size +*/ +static int unixTruncate(sqlite3_file *id, i64 nByte){ + unixFile *pFile = (unixFile *)id; + int rc; + assert( pFile ); + SimulateIOError( return SQLITE_IOERR_TRUNCATE ); + + /* If the user has configured a chunk-size for this file, truncate the + ** file so that it consists of an integer number of chunks (i.e. the + ** actual file size after the operation may be larger than the requested + ** size). + */ + if( pFile->szChunk>0 ){ + nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; + } + + rc = robust_ftruncate(pFile->h, (off_t)nByte); + if( rc ){ + pFile->lastErrno = errno; + return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); + }else{ +#ifdef SQLITE_DEBUG + /* If we are doing a normal write to a database file (as opposed to + ** doing a hot-journal rollback or a write to some file other than a + ** normal database file) and we truncate the file to zero length, + ** that effectively updates the change counter. This might happen + ** when restoring a database using the backup API from a zero-length + ** source. + */ + if( pFile->inNormalWrite && nByte==0 ){ + pFile->transCntrChng = 1; + } +#endif + +#if SQLITE_MAX_MMAP_SIZE>0 + /* If the file was just truncated to a size smaller than the currently + ** mapped region, reduce the effective mapping size as well. SQLite will + ** use read() and write() to access data beyond this point from now on. + */ + if( nBytemmapSize ){ + pFile->mmapSize = nByte; + } +#endif + + return SQLITE_OK; + } +} + +/* +** Determine the current size of a file in bytes +*/ +static int unixFileSize(sqlite3_file *id, i64 *pSize){ + int rc; + struct stat buf; + assert( id ); + rc = osFstat(((unixFile*)id)->h, &buf); + SimulateIOError( rc=1 ); + if( rc!=0 ){ + ((unixFile*)id)->lastErrno = errno; + return SQLITE_IOERR_FSTAT; + } + *pSize = buf.st_size; + + /* When opening a zero-size database, the findInodeInfo() procedure + ** writes a single byte into that file in order to work around a bug + ** in the OS-X msdos filesystem. In order to avoid problems with upper + ** layers, we need to report this file size as zero even though it is + ** really 1. Ticket #3260. + */ + if( *pSize==1 ) *pSize = 0; + + + return SQLITE_OK; +} + +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) +/* +** Handler for proxy-locking file-control verbs. Defined below in the +** proxying locking division. +*/ +static int proxyFileControl(sqlite3_file*,int,void*); +#endif + +/* +** This function is called to handle the SQLITE_FCNTL_SIZE_HINT +** file-control operation. Enlarge the database to nBytes in size +** (rounded up to the next chunk-size). If the database is already +** nBytes or larger, this routine is a no-op. +*/ +static int fcntlSizeHint(unixFile *pFile, i64 nByte){ + if( pFile->szChunk>0 ){ + i64 nSize; /* Required file size */ + struct stat buf; /* Used to hold return values of fstat() */ + + if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT; + + nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk; + if( nSize>(i64)buf.st_size ){ + +#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE + /* The code below is handling the return value of osFallocate() + ** correctly. posix_fallocate() is defined to "returns zero on success, + ** or an error number on failure". See the manpage for details. */ + int err; + do{ + err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size); + }while( err==EINTR ); + if( err ) return SQLITE_IOERR_WRITE; +#else + /* If the OS does not have posix_fallocate(), fake it. First use + ** ftruncate() to set the file size, then write a single byte to + ** the last byte in each block within the extended region. This + ** is the same technique used by glibc to implement posix_fallocate() + ** on systems that do not have a real fallocate() system call. + */ + int nBlk = buf.st_blksize; /* File-system block size */ + i64 iWrite; /* Next offset to write to */ + + if( robust_ftruncate(pFile->h, nSize) ){ + pFile->lastErrno = errno; + return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); + } + iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1; + while( iWrite0 + if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){ + int rc; + if( pFile->szChunk<=0 ){ + if( robust_ftruncate(pFile->h, nByte) ){ + pFile->lastErrno = errno; + return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); + } + } + + rc = unixMapfile(pFile, nByte); + return rc; + } +#endif + + return SQLITE_OK; +} + +/* +** If *pArg is inititially negative then this is a query. Set *pArg to +** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. +** +** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. +*/ +static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){ + if( *pArg<0 ){ + *pArg = (pFile->ctrlFlags & mask)!=0; + }else if( (*pArg)==0 ){ + pFile->ctrlFlags &= ~mask; + }else{ + pFile->ctrlFlags |= mask; + } +} + +/* Forward declaration */ +static int unixGetTempname(int nBuf, char *zBuf); + +/* +** Information and control of an open file handle. +*/ +static int unixFileControl(sqlite3_file *id, int op, void *pArg){ + unixFile *pFile = (unixFile*)id; + switch( op ){ + case SQLITE_FCNTL_LOCKSTATE: { + *(int*)pArg = pFile->eFileLock; + return SQLITE_OK; + } + case SQLITE_LAST_ERRNO: { + *(int*)pArg = pFile->lastErrno; + return SQLITE_OK; + } + case SQLITE_FCNTL_CHUNK_SIZE: { + pFile->szChunk = *(int *)pArg; + return SQLITE_OK; + } + case SQLITE_FCNTL_SIZE_HINT: { + int rc; + SimulateIOErrorBenign(1); + rc = fcntlSizeHint(pFile, *(i64 *)pArg); + SimulateIOErrorBenign(0); + return rc; + } + case SQLITE_FCNTL_PERSIST_WAL: { + unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg); + return SQLITE_OK; + } + case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { + unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg); + return SQLITE_OK; + } + case SQLITE_FCNTL_VFSNAME: { + *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); + return SQLITE_OK; + } + case SQLITE_FCNTL_TEMPFILENAME: { + char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname ); + if( zTFile ){ + unixGetTempname(pFile->pVfs->mxPathname, zTFile); + *(char**)pArg = zTFile; + } + return SQLITE_OK; + } +#if SQLITE_MAX_MMAP_SIZE>0 + case SQLITE_FCNTL_MMAP_SIZE: { + i64 newLimit = *(i64*)pArg; + int rc = SQLITE_OK; + if( newLimit>sqlite3GlobalConfig.mxMmap ){ + newLimit = sqlite3GlobalConfig.mxMmap; + } + *(i64*)pArg = pFile->mmapSizeMax; + if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ + pFile->mmapSizeMax = newLimit; + if( pFile->mmapSize>0 ){ + unixUnmapfile(pFile); + rc = unixMapfile(pFile, -1); + } + } + return rc; + } +#endif +#ifdef SQLITE_DEBUG + /* The pager calls this method to signal that it has done + ** a rollback and that the database is therefore unchanged and + ** it hence it is OK for the transaction change counter to be + ** unchanged. + */ + case SQLITE_FCNTL_DB_UNCHANGED: { + ((unixFile*)id)->dbUpdate = 0; + return SQLITE_OK; + } +#endif +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) + case SQLITE_SET_LOCKPROXYFILE: + case SQLITE_GET_LOCKPROXYFILE: { + return proxyFileControl(id,op,pArg); + } +#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */ + } + return SQLITE_NOTFOUND; +} + +/* +** Return the sector size in bytes of the underlying block device for +** the specified file. This is almost always 512 bytes, but may be +** larger for some devices. +** +** SQLite code assumes this function cannot fail. It also assumes that +** if two files are created in the same file-system directory (i.e. +** a database and its journal file) that the sector size will be the +** same for both. +*/ +#ifndef __QNXNTO__ +static int unixSectorSize(sqlite3_file *NotUsed){ + UNUSED_PARAMETER(NotUsed); + return SQLITE_DEFAULT_SECTOR_SIZE; +} +#endif + +/* +** The following version of unixSectorSize() is optimized for QNX. +*/ +#ifdef __QNXNTO__ +#include +#include +static int unixSectorSize(sqlite3_file *id){ + unixFile *pFile = (unixFile*)id; + if( pFile->sectorSize == 0 ){ + struct statvfs fsInfo; + + /* Set defaults for non-supported filesystems */ + pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; + pFile->deviceCharacteristics = 0; + if( fstatvfs(pFile->h, &fsInfo) == -1 ) { + return pFile->sectorSize; + } + + if( !strcmp(fsInfo.f_basetype, "tmp") ) { + pFile->sectorSize = fsInfo.f_bsize; + pFile->deviceCharacteristics = + SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */ + SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until + ** the write succeeds */ + SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind + ** so it is ordered */ + 0; + }else if( strstr(fsInfo.f_basetype, "etfs") ){ + pFile->sectorSize = fsInfo.f_bsize; + pFile->deviceCharacteristics = + /* etfs cluster size writes are atomic */ + (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) | + SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until + ** the write succeeds */ + SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind + ** so it is ordered */ + 0; + }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){ + pFile->sectorSize = fsInfo.f_bsize; + pFile->deviceCharacteristics = + SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */ + SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until + ** the write succeeds */ + SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind + ** so it is ordered */ + 0; + }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){ + pFile->sectorSize = fsInfo.f_bsize; + pFile->deviceCharacteristics = + /* full bitset of atomics from max sector size and smaller */ + ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 | + SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind + ** so it is ordered */ + 0; + }else if( strstr(fsInfo.f_basetype, "dos") ){ + pFile->sectorSize = fsInfo.f_bsize; + pFile->deviceCharacteristics = + /* full bitset of atomics from max sector size and smaller */ + ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 | + SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind + ** so it is ordered */ + 0; + }else{ + pFile->deviceCharacteristics = + SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */ + SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until + ** the write succeeds */ + 0; + } + } + /* Last chance verification. If the sector size isn't a multiple of 512 + ** then it isn't valid.*/ + if( pFile->sectorSize % 512 != 0 ){ + pFile->deviceCharacteristics = 0; + pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; + } + return pFile->sectorSize; +} +#endif /* __QNXNTO__ */ + +/* +** Return the device characteristics for the file. +** +** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default. +** However, that choice is contraversial since technically the underlying +** file system does not always provide powersafe overwrites. (In other +** words, after a power-loss event, parts of the file that were never +** written might end up being altered.) However, non-PSOW behavior is very, +** very rare. And asserting PSOW makes a large reduction in the amount +** of required I/O for journaling, since a lot of padding is eliminated. +** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control +** available to turn it off and URI query parameter available to turn it off. +*/ +static int unixDeviceCharacteristics(sqlite3_file *id){ + unixFile *p = (unixFile*)id; + int rc = 0; +#ifdef __QNXNTO__ + if( p->sectorSize==0 ) unixSectorSize(id); + rc = p->deviceCharacteristics; +#endif + if( p->ctrlFlags & UNIXFILE_PSOW ){ + rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; + } + return rc; +} + +#ifndef SQLITE_OMIT_WAL + + +/* +** Object used to represent an shared memory buffer. +** +** When multiple threads all reference the same wal-index, each thread +** has its own unixShm object, but they all point to a single instance +** of this unixShmNode object. In other words, each wal-index is opened +** only once per process. +** +** Each unixShmNode object is connected to a single unixInodeInfo object. +** We could coalesce this object into unixInodeInfo, but that would mean +** every open file that does not use shared memory (in other words, most +** open files) would have to carry around this extra information. So +** the unixInodeInfo object contains a pointer to this unixShmNode object +** and the unixShmNode object is created only when needed. +** +** unixMutexHeld() must be true when creating or destroying +** this object or while reading or writing the following fields: +** +** nRef +** +** The following fields are read-only after the object is created: +** +** fid +** zFilename +** +** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and +** unixMutexHeld() is true when reading or writing any other field +** in this structure. +*/ +struct unixShmNode { + unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */ + sqlite3_mutex *mutex; /* Mutex to access this object */ + char *zFilename; /* Name of the mmapped file */ + int h; /* Open file descriptor */ + int szRegion; /* Size of shared-memory regions */ + u16 nRegion; /* Size of array apRegion */ + u8 isReadonly; /* True if read-only */ + char **apRegion; /* Array of mapped shared-memory regions */ + int nRef; /* Number of unixShm objects pointing to this */ + unixShm *pFirst; /* All unixShm objects pointing to this */ +#ifdef SQLITE_DEBUG + u8 exclMask; /* Mask of exclusive locks held */ + u8 sharedMask; /* Mask of shared locks held */ + u8 nextShmId; /* Next available unixShm.id value */ +#endif +}; + +/* +** Structure used internally by this VFS to record the state of an +** open shared memory connection. +** +** The following fields are initialized when this object is created and +** are read-only thereafter: +** +** unixShm.pFile +** unixShm.id +** +** All other fields are read/write. The unixShm.pFile->mutex must be held +** while accessing any read/write fields. +*/ +struct unixShm { + unixShmNode *pShmNode; /* The underlying unixShmNode object */ + unixShm *pNext; /* Next unixShm with the same unixShmNode */ + u8 hasMutex; /* True if holding the unixShmNode mutex */ + u8 id; /* Id of this connection within its unixShmNode */ + u16 sharedMask; /* Mask of shared locks held */ + u16 exclMask; /* Mask of exclusive locks held */ +}; + +/* +** Constants used for locking +*/ +#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ +#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ + +/* +** Apply posix advisory locks for all bytes from ofst through ofst+n-1. +** +** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking +** otherwise. +*/ +static int unixShmSystemLock( + unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */ + int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */ + int ofst, /* First byte of the locking range */ + int n /* Number of bytes to lock */ +){ + struct flock f; /* The posix advisory locking structure */ + int rc = SQLITE_OK; /* Result code form fcntl() */ + + /* Access to the unixShmNode object is serialized by the caller */ + assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 ); + + /* Shared locks never span more than one byte */ + assert( n==1 || lockType!=F_RDLCK ); + + /* Locks are within range */ + assert( n>=1 && nh>=0 ){ + /* Initialize the locking parameters */ + memset(&f, 0, sizeof(f)); + f.l_type = lockType; + f.l_whence = SEEK_SET; + f.l_start = ofst; + f.l_len = n; + + rc = osFcntl(pShmNode->h, F_SETLK, &f); + rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY; + } + + /* Update the global lock state and do debug tracing */ +#ifdef SQLITE_DEBUG + { u16 mask; + OSTRACE(("SHM-LOCK ")); + mask = (1<<(ofst+n)) - (1<exclMask &= ~mask; + pShmNode->sharedMask &= ~mask; + }else if( lockType==F_RDLCK ){ + OSTRACE(("read-lock %d ok", ofst)); + pShmNode->exclMask &= ~mask; + pShmNode->sharedMask |= mask; + }else{ + assert( lockType==F_WRLCK ); + OSTRACE(("write-lock %d ok", ofst)); + pShmNode->exclMask |= mask; + pShmNode->sharedMask &= ~mask; + } + }else{ + if( lockType==F_UNLCK ){ + OSTRACE(("unlock %d failed", ofst)); + }else if( lockType==F_RDLCK ){ + OSTRACE(("read-lock failed")); + }else{ + assert( lockType==F_WRLCK ); + OSTRACE(("write-lock %d failed", ofst)); + } + } + OSTRACE((" - afterwards %03x,%03x\n", + pShmNode->sharedMask, pShmNode->exclMask)); + } +#endif + + return rc; +} + + +/* +** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0. +** +** This is not a VFS shared-memory method; it is a utility function called +** by VFS shared-memory methods. +*/ +static void unixShmPurge(unixFile *pFd){ + unixShmNode *p = pFd->pInode->pShmNode; + assert( unixMutexHeld() ); + if( p && p->nRef==0 ){ + int i; + assert( p->pInode==pFd->pInode ); + sqlite3_mutex_free(p->mutex); + for(i=0; inRegion; i++){ + if( p->h>=0 ){ + osMunmap(p->apRegion[i], p->szRegion); + }else{ + sqlite3_free(p->apRegion[i]); + } + } + sqlite3_free(p->apRegion); + if( p->h>=0 ){ + robust_close(pFd, p->h, __LINE__); + p->h = -1; + } + p->pInode->pShmNode = 0; + sqlite3_free(p); + } +} + +/* +** Open a shared-memory area associated with open database file pDbFd. +** This particular implementation uses mmapped files. +** +** The file used to implement shared-memory is in the same directory +** as the open database file and has the same name as the open database +** file with the "-shm" suffix added. For example, if the database file +** is "/home/user1/config.db" then the file that is created and mmapped +** for shared memory will be called "/home/user1/config.db-shm". +** +** Another approach to is to use files in /dev/shm or /dev/tmp or an +** some other tmpfs mount. But if a file in a different directory +** from the database file is used, then differing access permissions +** or a chroot() might cause two different processes on the same +** database to end up using different files for shared memory - +** meaning that their memory would not really be shared - resulting +** in database corruption. Nevertheless, this tmpfs file usage +** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm" +** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time +** option results in an incompatible build of SQLite; builds of SQLite +** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the +** same database file at the same time, database corruption will likely +** result. The SQLITE_SHM_DIRECTORY compile-time option is considered +** "unsupported" and may go away in a future SQLite release. +** +** When opening a new shared-memory file, if no other instances of that +** file are currently open, in this process or in other processes, then +** the file must be truncated to zero length or have its header cleared. +** +** If the original database file (pDbFd) is using the "unix-excl" VFS +** that means that an exclusive lock is held on the database file and +** that no other processes are able to read or write the database. In +** that case, we do not really need shared memory. No shared memory +** file is created. The shared memory will be simulated with heap memory. +*/ +static int unixOpenSharedMemory(unixFile *pDbFd){ + struct unixShm *p = 0; /* The connection to be opened */ + struct unixShmNode *pShmNode; /* The underlying mmapped file */ + int rc; /* Result code */ + unixInodeInfo *pInode; /* The inode of fd */ + char *zShmFilename; /* Name of the file used for SHM */ + int nShmFilename; /* Size of the SHM filename in bytes */ + + /* Allocate space for the new unixShm object. */ + p = sqlite3_malloc( sizeof(*p) ); + if( p==0 ) return SQLITE_NOMEM; + memset(p, 0, sizeof(*p)); + assert( pDbFd->pShm==0 ); + + /* Check to see if a unixShmNode object already exists. Reuse an existing + ** one if present. Create a new one if necessary. + */ + unixEnterMutex(); + pInode = pDbFd->pInode; + pShmNode = pInode->pShmNode; + if( pShmNode==0 ){ + struct stat sStat; /* fstat() info for database file */ + + /* Call fstat() to figure out the permissions on the database file. If + ** a new *-shm file is created, an attempt will be made to create it + ** with the same permissions. + */ + if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){ + rc = SQLITE_IOERR_FSTAT; + goto shm_open_err; + } + +#ifdef SQLITE_SHM_DIRECTORY + nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31; +#else + nShmFilename = 6 + (int)strlen(pDbFd->zPath); +#endif + pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename ); + if( pShmNode==0 ){ + rc = SQLITE_NOMEM; + goto shm_open_err; + } + memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename); + zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1]; +#ifdef SQLITE_SHM_DIRECTORY + sqlite3_snprintf(nShmFilename, zShmFilename, + SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x", + (u32)sStat.st_ino, (u32)sStat.st_dev); +#else + sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath); + sqlite3FileSuffix3(pDbFd->zPath, zShmFilename); +#endif + pShmNode->h = -1; + pDbFd->pInode->pShmNode = pShmNode; + pShmNode->pInode = pDbFd->pInode; + pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( pShmNode->mutex==0 ){ + rc = SQLITE_NOMEM; + goto shm_open_err; + } + + if( pInode->bProcessLock==0 ){ + int openFlags = O_RDWR | O_CREAT; + if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ + openFlags = O_RDONLY; + pShmNode->isReadonly = 1; + } + pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777)); + if( pShmNode->h<0 ){ + rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename); + goto shm_open_err; + } + + /* If this process is running as root, make sure that the SHM file + ** is owned by the same user that owns the original database. Otherwise, + ** the original owner will not be able to connect. + */ + osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid); + + /* Check to see if another process is holding the dead-man switch. + ** If not, truncate the file to zero length. + */ + rc = SQLITE_OK; + if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){ + if( robust_ftruncate(pShmNode->h, 0) ){ + rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename); + } + } + if( rc==SQLITE_OK ){ + rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1); + } + if( rc ) goto shm_open_err; + } + } + + /* Make the new connection a child of the unixShmNode */ + p->pShmNode = pShmNode; +#ifdef SQLITE_DEBUG + p->id = pShmNode->nextShmId++; +#endif + pShmNode->nRef++; + pDbFd->pShm = p; + unixLeaveMutex(); + + /* The reference count on pShmNode has already been incremented under + ** the cover of the unixEnterMutex() mutex and the pointer from the + ** new (struct unixShm) object to the pShmNode has been set. All that is + ** left to do is to link the new object into the linked list starting + ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex + ** mutex. + */ + sqlite3_mutex_enter(pShmNode->mutex); + p->pNext = pShmNode->pFirst; + pShmNode->pFirst = p; + sqlite3_mutex_leave(pShmNode->mutex); + return SQLITE_OK; + + /* Jump here on any error */ +shm_open_err: + unixShmPurge(pDbFd); /* This call frees pShmNode if required */ + sqlite3_free(p); + unixLeaveMutex(); + return rc; +} + +/* +** This function is called to obtain a pointer to region iRegion of the +** shared-memory associated with the database file fd. Shared-memory regions +** are numbered starting from zero. Each shared-memory region is szRegion +** bytes in size. +** +** If an error occurs, an error code is returned and *pp is set to NULL. +** +** Otherwise, if the bExtend parameter is 0 and the requested shared-memory +** region has not been allocated (by any client, including one running in a +** separate process), then *pp is set to NULL and SQLITE_OK returned. If +** bExtend is non-zero and the requested shared-memory region has not yet +** been allocated, it is allocated by this function. +** +** If the shared-memory region has already been allocated or is allocated by +** this call as described above, then it is mapped into this processes +** address space (if it is not already), *pp is set to point to the mapped +** memory and SQLITE_OK returned. +*/ +static int unixShmMap( + sqlite3_file *fd, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int szRegion, /* Size of regions */ + int bExtend, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + unixFile *pDbFd = (unixFile*)fd; + unixShm *p; + unixShmNode *pShmNode; + int rc = SQLITE_OK; + + /* If the shared-memory file has not yet been opened, open it now. */ + if( pDbFd->pShm==0 ){ + rc = unixOpenSharedMemory(pDbFd); + if( rc!=SQLITE_OK ) return rc; + } + + p = pDbFd->pShm; + pShmNode = p->pShmNode; + sqlite3_mutex_enter(pShmNode->mutex); + assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); + assert( pShmNode->pInode==pDbFd->pInode ); + assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 ); + assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); + + if( pShmNode->nRegion<=iRegion ){ + char **apNew; /* New apRegion[] array */ + int nByte = (iRegion+1)*szRegion; /* Minimum required file size */ + struct stat sStat; /* Used by fstat() */ + + pShmNode->szRegion = szRegion; + + if( pShmNode->h>=0 ){ + /* The requested region is not mapped into this processes address space. + ** Check to see if it has been allocated (i.e. if the wal-index file is + ** large enough to contain the requested region). + */ + if( osFstat(pShmNode->h, &sStat) ){ + rc = SQLITE_IOERR_SHMSIZE; + goto shmpage_out; + } + + if( sStat.st_sizeh, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){ + const char *zFile = pShmNode->zFilename; + rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile); + goto shmpage_out; + } + } + } + } + } + + /* Map the requested memory region into this processes address space. */ + apNew = (char **)sqlite3_realloc( + pShmNode->apRegion, (iRegion+1)*sizeof(char *) + ); + if( !apNew ){ + rc = SQLITE_IOERR_NOMEM; + goto shmpage_out; + } + pShmNode->apRegion = apNew; + while(pShmNode->nRegion<=iRegion){ + void *pMem; + if( pShmNode->h>=0 ){ + pMem = osMmap(0, szRegion, + pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, + MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion + ); + if( pMem==MAP_FAILED ){ + rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename); + goto shmpage_out; + } + }else{ + pMem = sqlite3_malloc(szRegion); + if( pMem==0 ){ + rc = SQLITE_NOMEM; + goto shmpage_out; + } + memset(pMem, 0, szRegion); + } + pShmNode->apRegion[pShmNode->nRegion] = pMem; + pShmNode->nRegion++; + } + } + +shmpage_out: + if( pShmNode->nRegion>iRegion ){ + *pp = pShmNode->apRegion[iRegion]; + }else{ + *pp = 0; + } + if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY; + sqlite3_mutex_leave(pShmNode->mutex); + return rc; +} + +/* +** Change the lock state for a shared-memory segment. +** +** Note that the relationship between SHAREd and EXCLUSIVE locks is a little +** different here than in posix. In xShmLock(), one can go from unlocked +** to shared and back or from unlocked to exclusive and back. But one may +** not go from shared to exclusive or from exclusive to shared. +*/ +static int unixShmLock( + sqlite3_file *fd, /* Database file holding the shared memory */ + int ofst, /* First lock to acquire or release */ + int n, /* Number of locks to acquire or release */ + int flags /* What to do with the lock */ +){ + unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */ + unixShm *p = pDbFd->pShm; /* The shared memory being locked */ + unixShm *pX; /* For looping over all siblings */ + unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */ + int rc = SQLITE_OK; /* Result code */ + u16 mask; /* Mask of locks to take or release */ + + assert( pShmNode==pDbFd->pInode->pShmNode ); + assert( pShmNode->pInode==pDbFd->pInode ); + assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK ); + assert( n>=1 ); + assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED) + || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE) + || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) + || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); + assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); + assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 ); + assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); + + mask = (1<<(ofst+n)) - (1<1 || mask==(1<mutex); + if( flags & SQLITE_SHM_UNLOCK ){ + u16 allMask = 0; /* Mask of locks held by siblings */ + + /* See if any siblings hold this same lock */ + for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ + if( pX==p ) continue; + assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 ); + allMask |= pX->sharedMask; + } + + /* Unlock the system-level locks */ + if( (mask & allMask)==0 ){ + rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n); + }else{ + rc = SQLITE_OK; + } + + /* Undo the local locks */ + if( rc==SQLITE_OK ){ + p->exclMask &= ~mask; + p->sharedMask &= ~mask; + } + }else if( flags & SQLITE_SHM_SHARED ){ + u16 allShared = 0; /* Union of locks held by connections other than "p" */ + + /* Find out which shared locks are already held by sibling connections. + ** If any sibling already holds an exclusive lock, go ahead and return + ** SQLITE_BUSY. + */ + for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ + if( (pX->exclMask & mask)!=0 ){ + rc = SQLITE_BUSY; + break; + } + allShared |= pX->sharedMask; + } + + /* Get shared locks at the system level, if necessary */ + if( rc==SQLITE_OK ){ + if( (allShared & mask)==0 ){ + rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n); + }else{ + rc = SQLITE_OK; + } + } + + /* Get the local shared locks */ + if( rc==SQLITE_OK ){ + p->sharedMask |= mask; + } + }else{ + /* Make sure no sibling connections hold locks that will block this + ** lock. If any do, return SQLITE_BUSY right away. + */ + for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ + if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){ + rc = SQLITE_BUSY; + break; + } + } + + /* Get the exclusive locks at the system level. Then if successful + ** also mark the local connection as being locked. + */ + if( rc==SQLITE_OK ){ + rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n); + if( rc==SQLITE_OK ){ + assert( (p->sharedMask & mask)==0 ); + p->exclMask |= mask; + } + } + } + sqlite3_mutex_leave(pShmNode->mutex); + OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n", + p->id, getpid(), p->sharedMask, p->exclMask)); + return rc; +} + +/* +** Implement a memory barrier or memory fence on shared memory. +** +** All loads and stores begun before the barrier must complete before +** any load or store begun after the barrier. +*/ +static void unixShmBarrier( + sqlite3_file *fd /* Database file holding the shared memory */ +){ + UNUSED_PARAMETER(fd); + unixEnterMutex(); + unixLeaveMutex(); +} + +/* +** Close a connection to shared-memory. Delete the underlying +** storage if deleteFlag is true. +** +** If there is no shared memory associated with the connection then this +** routine is a harmless no-op. +*/ +static int unixShmUnmap( + sqlite3_file *fd, /* The underlying database file */ + int deleteFlag /* Delete shared-memory if true */ +){ + unixShm *p; /* The connection to be closed */ + unixShmNode *pShmNode; /* The underlying shared-memory file */ + unixShm **pp; /* For looping over sibling connections */ + unixFile *pDbFd; /* The underlying database file */ + + pDbFd = (unixFile*)fd; + p = pDbFd->pShm; + if( p==0 ) return SQLITE_OK; + pShmNode = p->pShmNode; + + assert( pShmNode==pDbFd->pInode->pShmNode ); + assert( pShmNode->pInode==pDbFd->pInode ); + + /* Remove connection p from the set of connections associated + ** with pShmNode */ + sqlite3_mutex_enter(pShmNode->mutex); + for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} + *pp = p->pNext; + + /* Free the connection p */ + sqlite3_free(p); + pDbFd->pShm = 0; + sqlite3_mutex_leave(pShmNode->mutex); + + /* If pShmNode->nRef has reached 0, then close the underlying + ** shared-memory file, too */ + unixEnterMutex(); + assert( pShmNode->nRef>0 ); + pShmNode->nRef--; + if( pShmNode->nRef==0 ){ + if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename); + unixShmPurge(pDbFd); + } + unixLeaveMutex(); + + return SQLITE_OK; +} + + +#else +# define unixShmMap 0 +# define unixShmLock 0 +# define unixShmBarrier 0 +# define unixShmUnmap 0 +#endif /* #ifndef SQLITE_OMIT_WAL */ + +#if SQLITE_MAX_MMAP_SIZE>0 +/* +** If it is currently memory mapped, unmap file pFd. +*/ +static void unixUnmapfile(unixFile *pFd){ + assert( pFd->nFetchOut==0 ); + if( pFd->pMapRegion ){ + osMunmap(pFd->pMapRegion, pFd->mmapSizeActual); + pFd->pMapRegion = 0; + pFd->mmapSize = 0; + pFd->mmapSizeActual = 0; + } +} + +/* +** Return the system page size. +*/ +static int unixGetPagesize(void){ +#if HAVE_MREMAP + return 512; +#elif defined(_BSD_SOURCE) + return getpagesize(); +#else + return (int)sysconf(_SC_PAGESIZE); +#endif +} + +/* +** Attempt to set the size of the memory mapping maintained by file +** descriptor pFd to nNew bytes. Any existing mapping is discarded. +** +** If successful, this function sets the following variables: +** +** unixFile.pMapRegion +** unixFile.mmapSize +** unixFile.mmapSizeActual +** +** If unsuccessful, an error message is logged via sqlite3_log() and +** the three variables above are zeroed. In this case SQLite should +** continue accessing the database using the xRead() and xWrite() +** methods. +*/ +static void unixRemapfile( + unixFile *pFd, /* File descriptor object */ + i64 nNew /* Required mapping size */ +){ + const char *zErr = "mmap"; + int h = pFd->h; /* File descriptor open on db file */ + u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */ + i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */ + u8 *pNew = 0; /* Location of new mapping */ + int flags = PROT_READ; /* Flags to pass to mmap() */ + + assert( pFd->nFetchOut==0 ); + assert( nNew>pFd->mmapSize ); + assert( nNew<=pFd->mmapSizeMax ); + assert( nNew>0 ); + assert( pFd->mmapSizeActual>=pFd->mmapSize ); + assert( MAP_FAILED!=0 ); + + if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE; + + if( pOrig ){ + const int szSyspage = unixGetPagesize(); + i64 nReuse = (pFd->mmapSize & ~(szSyspage-1)); + u8 *pReq = &pOrig[nReuse]; + + /* Unmap any pages of the existing mapping that cannot be reused. */ + if( nReuse!=nOrig ){ + osMunmap(pReq, nOrig-nReuse); + } + +#if HAVE_MREMAP + pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE); + zErr = "mremap"; +#else + pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse); + if( pNew!=MAP_FAILED ){ + if( pNew!=pReq ){ + osMunmap(pNew, nNew - nReuse); + pNew = 0; + }else{ + pNew = pOrig; + } + } +#endif + + /* The attempt to extend the existing mapping failed. Free it. */ + if( pNew==MAP_FAILED || pNew==0 ){ + osMunmap(pOrig, nReuse); + } + } + + /* If pNew is still NULL, try to create an entirely new mapping. */ + if( pNew==0 ){ + pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0); + } + + if( pNew==MAP_FAILED ){ + pNew = 0; + nNew = 0; + unixLogError(SQLITE_OK, zErr, pFd->zPath); + + /* If the mmap() above failed, assume that all subsequent mmap() calls + ** will probably fail too. Fall back to using xRead/xWrite exclusively + ** in this case. */ + pFd->mmapSizeMax = 0; + } + pFd->pMapRegion = (void *)pNew; + pFd->mmapSize = pFd->mmapSizeActual = nNew; +} + +/* +** Memory map or remap the file opened by file-descriptor pFd (if the file +** is already mapped, the existing mapping is replaced by the new). Or, if +** there already exists a mapping for this file, and there are still +** outstanding xFetch() references to it, this function is a no-op. +** +** If parameter nByte is non-negative, then it is the requested size of +** the mapping to create. Otherwise, if nByte is less than zero, then the +** requested size is the size of the file on disk. The actual size of the +** created mapping is either the requested size or the value configured +** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller. +** +** SQLITE_OK is returned if no error occurs (even if the mapping is not +** recreated as a result of outstanding references) or an SQLite error +** code otherwise. +*/ +static int unixMapfile(unixFile *pFd, i64 nByte){ + i64 nMap = nByte; + int rc; + + assert( nMap>=0 || pFd->nFetchOut==0 ); + if( pFd->nFetchOut>0 ) return SQLITE_OK; + + if( nMap<0 ){ + struct stat statbuf; /* Low-level file information */ + rc = osFstat(pFd->h, &statbuf); + if( rc!=SQLITE_OK ){ + return SQLITE_IOERR_FSTAT; + } + nMap = statbuf.st_size; + } + if( nMap>pFd->mmapSizeMax ){ + nMap = pFd->mmapSizeMax; + } + + if( nMap!=pFd->mmapSize ){ + if( nMap>0 ){ + unixRemapfile(pFd, nMap); + }else{ + unixUnmapfile(pFd); + } + } + + return SQLITE_OK; +} +#endif /* SQLITE_MAX_MMAP_SIZE>0 */ + +/* +** If possible, return a pointer to a mapping of file fd starting at offset +** iOff. The mapping must be valid for at least nAmt bytes. +** +** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. +** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. +** Finally, if an error does occur, return an SQLite error code. The final +** value of *pp is undefined in this case. +** +** If this function does return a pointer, the caller must eventually +** release the reference by calling unixUnfetch(). +*/ +static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ +#if SQLITE_MAX_MMAP_SIZE>0 + unixFile *pFd = (unixFile *)fd; /* The underlying database file */ +#endif + *pp = 0; + +#if SQLITE_MAX_MMAP_SIZE>0 + if( pFd->mmapSizeMax>0 ){ + if( pFd->pMapRegion==0 ){ + int rc = unixMapfile(pFd, -1); + if( rc!=SQLITE_OK ) return rc; + } + if( pFd->mmapSize >= iOff+nAmt ){ + *pp = &((u8 *)pFd->pMapRegion)[iOff]; + pFd->nFetchOut++; + } + } +#endif + return SQLITE_OK; +} + +/* +** If the third argument is non-NULL, then this function releases a +** reference obtained by an earlier call to unixFetch(). The second +** argument passed to this function must be the same as the corresponding +** argument that was passed to the unixFetch() invocation. +** +** Or, if the third argument is NULL, then this function is being called +** to inform the VFS layer that, according to POSIX, any existing mapping +** may now be invalid and should be unmapped. +*/ +static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){ + unixFile *pFd = (unixFile *)fd; /* The underlying database file */ + UNUSED_PARAMETER(iOff); + +#if SQLITE_MAX_MMAP_SIZE>0 + /* If p==0 (unmap the entire file) then there must be no outstanding + ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), + ** then there must be at least one outstanding. */ + assert( (p==0)==(pFd->nFetchOut==0) ); + + /* If p!=0, it must match the iOff value. */ + assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); + + if( p ){ + pFd->nFetchOut--; + }else{ + unixUnmapfile(pFd); + } + + assert( pFd->nFetchOut>=0 ); +#endif + return SQLITE_OK; +} + +/* +** Here ends the implementation of all sqlite3_file methods. +** +********************** End sqlite3_file Methods ******************************* +******************************************************************************/ + +/* +** This division contains definitions of sqlite3_io_methods objects that +** implement various file locking strategies. It also contains definitions +** of "finder" functions. A finder-function is used to locate the appropriate +** sqlite3_io_methods object for a particular database file. The pAppData +** field of the sqlite3_vfs VFS objects are initialized to be pointers to +** the correct finder-function for that VFS. +** +** Most finder functions return a pointer to a fixed sqlite3_io_methods +** object. The only interesting finder-function is autolockIoFinder, which +** looks at the filesystem type and tries to guess the best locking +** strategy from that. +** +** For finder-funtion F, two objects are created: +** +** (1) The real finder-function named "FImpt()". +** +** (2) A constant pointer to this function named just "F". +** +** +** A pointer to the F pointer is used as the pAppData value for VFS +** objects. We have to do this instead of letting pAppData point +** directly at the finder-function since C90 rules prevent a void* +** from be cast into a function pointer. +** +** +** Each instance of this macro generates two objects: +** +** * A constant sqlite3_io_methods object call METHOD that has locking +** methods CLOSE, LOCK, UNLOCK, CKRESLOCK. +** +** * An I/O method finder function called FINDER that returns a pointer +** to the METHOD object in the previous bullet. +*/ +#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \ +static const sqlite3_io_methods METHOD = { \ + VERSION, /* iVersion */ \ + CLOSE, /* xClose */ \ + unixRead, /* xRead */ \ + unixWrite, /* xWrite */ \ + unixTruncate, /* xTruncate */ \ + unixSync, /* xSync */ \ + unixFileSize, /* xFileSize */ \ + LOCK, /* xLock */ \ + UNLOCK, /* xUnlock */ \ + CKLOCK, /* xCheckReservedLock */ \ + unixFileControl, /* xFileControl */ \ + unixSectorSize, /* xSectorSize */ \ + unixDeviceCharacteristics, /* xDeviceCapabilities */ \ + unixShmMap, /* xShmMap */ \ + unixShmLock, /* xShmLock */ \ + unixShmBarrier, /* xShmBarrier */ \ + unixShmUnmap, /* xShmUnmap */ \ + unixFetch, /* xFetch */ \ + unixUnfetch, /* xUnfetch */ \ +}; \ +static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \ + UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \ + return &METHOD; \ +} \ +static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \ + = FINDER##Impl; + +/* +** Here are all of the sqlite3_io_methods objects for each of the +** locking strategies. Functions that return pointers to these methods +** are also created. +*/ +IOMETHODS( + posixIoFinder, /* Finder function name */ + posixIoMethods, /* sqlite3_io_methods object name */ + 3, /* shared memory and mmap are enabled */ + unixClose, /* xClose method */ + unixLock, /* xLock method */ + unixUnlock, /* xUnlock method */ + unixCheckReservedLock /* xCheckReservedLock method */ +) +IOMETHODS( + nolockIoFinder, /* Finder function name */ + nolockIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + nolockClose, /* xClose method */ + nolockLock, /* xLock method */ + nolockUnlock, /* xUnlock method */ + nolockCheckReservedLock /* xCheckReservedLock method */ +) +IOMETHODS( + dotlockIoFinder, /* Finder function name */ + dotlockIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + dotlockClose, /* xClose method */ + dotlockLock, /* xLock method */ + dotlockUnlock, /* xUnlock method */ + dotlockCheckReservedLock /* xCheckReservedLock method */ +) + +#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS +IOMETHODS( + flockIoFinder, /* Finder function name */ + flockIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + flockClose, /* xClose method */ + flockLock, /* xLock method */ + flockUnlock, /* xUnlock method */ + flockCheckReservedLock /* xCheckReservedLock method */ +) +#endif + +#if OS_VXWORKS +IOMETHODS( + semIoFinder, /* Finder function name */ + semIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + semClose, /* xClose method */ + semLock, /* xLock method */ + semUnlock, /* xUnlock method */ + semCheckReservedLock /* xCheckReservedLock method */ +) +#endif + +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE +IOMETHODS( + afpIoFinder, /* Finder function name */ + afpIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + afpClose, /* xClose method */ + afpLock, /* xLock method */ + afpUnlock, /* xUnlock method */ + afpCheckReservedLock /* xCheckReservedLock method */ +) +#endif + +/* +** The proxy locking method is a "super-method" in the sense that it +** opens secondary file descriptors for the conch and lock files and +** it uses proxy, dot-file, AFP, and flock() locking methods on those +** secondary files. For this reason, the division that implements +** proxy locking is located much further down in the file. But we need +** to go ahead and define the sqlite3_io_methods and finder function +** for proxy locking here. So we forward declare the I/O methods. +*/ +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE +static int proxyClose(sqlite3_file*); +static int proxyLock(sqlite3_file*, int); +static int proxyUnlock(sqlite3_file*, int); +static int proxyCheckReservedLock(sqlite3_file*, int*); +IOMETHODS( + proxyIoFinder, /* Finder function name */ + proxyIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + proxyClose, /* xClose method */ + proxyLock, /* xLock method */ + proxyUnlock, /* xUnlock method */ + proxyCheckReservedLock /* xCheckReservedLock method */ +) +#endif + +/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */ +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE +IOMETHODS( + nfsIoFinder, /* Finder function name */ + nfsIoMethods, /* sqlite3_io_methods object name */ + 1, /* shared memory is disabled */ + unixClose, /* xClose method */ + unixLock, /* xLock method */ + nfsUnlock, /* xUnlock method */ + unixCheckReservedLock /* xCheckReservedLock method */ +) +#endif + +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE +/* +** This "finder" function attempts to determine the best locking strategy +** for the database file "filePath". It then returns the sqlite3_io_methods +** object that implements that strategy. +** +** This is for MacOSX only. +*/ +static const sqlite3_io_methods *autolockIoFinderImpl( + const char *filePath, /* name of the database file */ + unixFile *pNew /* open file object for the database file */ +){ + static const struct Mapping { + const char *zFilesystem; /* Filesystem type name */ + const sqlite3_io_methods *pMethods; /* Appropriate locking method */ + } aMap[] = { + { "hfs", &posixIoMethods }, + { "ufs", &posixIoMethods }, + { "afpfs", &afpIoMethods }, + { "smbfs", &afpIoMethods }, + { "webdav", &nolockIoMethods }, + { 0, 0 } + }; + int i; + struct statfs fsInfo; + struct flock lockInfo; + + if( !filePath ){ + /* If filePath==NULL that means we are dealing with a transient file + ** that does not need to be locked. */ + return &nolockIoMethods; + } + if( statfs(filePath, &fsInfo) != -1 ){ + if( fsInfo.f_flags & MNT_RDONLY ){ + return &nolockIoMethods; + } + for(i=0; aMap[i].zFilesystem; i++){ + if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){ + return aMap[i].pMethods; + } + } + } + + /* Default case. Handles, amongst others, "nfs". + ** Test byte-range lock using fcntl(). If the call succeeds, + ** assume that the file-system supports POSIX style locks. + */ + lockInfo.l_len = 1; + lockInfo.l_start = 0; + lockInfo.l_whence = SEEK_SET; + lockInfo.l_type = F_RDLCK; + if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { + if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){ + return &nfsIoMethods; + } else { + return &posixIoMethods; + } + }else{ + return &dotlockIoMethods; + } +} +static const sqlite3_io_methods + *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; + +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ + +#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE +/* +** This "finder" function attempts to determine the best locking strategy +** for the database file "filePath". It then returns the sqlite3_io_methods +** object that implements that strategy. +** +** This is for VXWorks only. +*/ +static const sqlite3_io_methods *autolockIoFinderImpl( + const char *filePath, /* name of the database file */ + unixFile *pNew /* the open file object */ +){ + struct flock lockInfo; + + if( !filePath ){ + /* If filePath==NULL that means we are dealing with a transient file + ** that does not need to be locked. */ + return &nolockIoMethods; + } + + /* Test if fcntl() is supported and use POSIX style locks. + ** Otherwise fall back to the named semaphore method. + */ + lockInfo.l_len = 1; + lockInfo.l_start = 0; + lockInfo.l_whence = SEEK_SET; + lockInfo.l_type = F_RDLCK; + if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { + return &posixIoMethods; + }else{ + return &semIoMethods; + } +} +static const sqlite3_io_methods + *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; + +#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */ + +/* +** An abstract type for a pointer to a IO method finder function: +*/ +typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*); + + +/**************************************************************************** +**************************** sqlite3_vfs methods **************************** +** +** This division contains the implementation of methods on the +** sqlite3_vfs object. +*/ + +/* +** Initialize the contents of the unixFile structure pointed to by pId. +*/ +static int fillInUnixFile( + sqlite3_vfs *pVfs, /* Pointer to vfs object */ + int h, /* Open file descriptor of file being opened */ + sqlite3_file *pId, /* Write to the unixFile structure here */ + const char *zFilename, /* Name of the file being opened */ + int ctrlFlags /* Zero or more UNIXFILE_* values */ +){ + const sqlite3_io_methods *pLockingStyle; + unixFile *pNew = (unixFile *)pId; + int rc = SQLITE_OK; + + assert( pNew->pInode==NULL ); + + /* Usually the path zFilename should not be a relative pathname. The + ** exception is when opening the proxy "conch" file in builds that + ** include the special Apple locking styles. + */ +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE + assert( zFilename==0 || zFilename[0]=='/' + || pVfs->pAppData==(void*)&autolockIoFinder ); +#else + assert( zFilename==0 || zFilename[0]=='/' ); +#endif + + /* No locking occurs in temporary files */ + assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 ); + + OSTRACE(("OPEN %-3d %s\n", h, zFilename)); + pNew->h = h; + pNew->pVfs = pVfs; + pNew->zPath = zFilename; + pNew->ctrlFlags = (u8)ctrlFlags; +#if SQLITE_MAX_MMAP_SIZE>0 + pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap; +#endif + if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0), + "psow", SQLITE_POWERSAFE_OVERWRITE) ){ + pNew->ctrlFlags |= UNIXFILE_PSOW; + } + if( strcmp(pVfs->zName,"unix-excl")==0 ){ + pNew->ctrlFlags |= UNIXFILE_EXCL; + } + +#if OS_VXWORKS + pNew->pId = vxworksFindFileId(zFilename); + if( pNew->pId==0 ){ + ctrlFlags |= UNIXFILE_NOLOCK; + rc = SQLITE_NOMEM; + } +#endif + + if( ctrlFlags & UNIXFILE_NOLOCK ){ + pLockingStyle = &nolockIoMethods; + }else{ + pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); +#if SQLITE_ENABLE_LOCKING_STYLE + /* Cache zFilename in the locking context (AFP and dotlock override) for + ** proxyLock activation is possible (remote proxy is based on db name) + ** zFilename remains valid until file is closed, to support */ + pNew->lockingContext = (void*)zFilename; +#endif + } + + if( pLockingStyle == &posixIoMethods +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE + || pLockingStyle == &nfsIoMethods +#endif + ){ + unixEnterMutex(); + rc = findInodeInfo(pNew, &pNew->pInode); + if( rc!=SQLITE_OK ){ + /* If an error occurred in findInodeInfo(), close the file descriptor + ** immediately, before releasing the mutex. findInodeInfo() may fail + ** in two scenarios: + ** + ** (a) A call to fstat() failed. + ** (b) A malloc failed. + ** + ** Scenario (b) may only occur if the process is holding no other + ** file descriptors open on the same file. If there were other file + ** descriptors on this file, then no malloc would be required by + ** findInodeInfo(). If this is the case, it is quite safe to close + ** handle h - as it is guaranteed that no posix locks will be released + ** by doing so. + ** + ** If scenario (a) caused the error then things are not so safe. The + ** implicit assumption here is that if fstat() fails, things are in + ** such bad shape that dropping a lock or two doesn't matter much. + */ + robust_close(pNew, h, __LINE__); + h = -1; + } + unixLeaveMutex(); + } + +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) + else if( pLockingStyle == &afpIoMethods ){ + /* AFP locking uses the file path so it needs to be included in + ** the afpLockingContext. + */ + afpLockingContext *pCtx; + pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) ); + if( pCtx==0 ){ + rc = SQLITE_NOMEM; + }else{ + /* NB: zFilename exists and remains valid until the file is closed + ** according to requirement F11141. So we do not need to make a + ** copy of the filename. */ + pCtx->dbPath = zFilename; + pCtx->reserved = 0; + srandomdev(); + unixEnterMutex(); + rc = findInodeInfo(pNew, &pNew->pInode); + if( rc!=SQLITE_OK ){ + sqlite3_free(pNew->lockingContext); + robust_close(pNew, h, __LINE__); + h = -1; + } + unixLeaveMutex(); + } + } +#endif + + else if( pLockingStyle == &dotlockIoMethods ){ + /* Dotfile locking uses the file path so it needs to be included in + ** the dotlockLockingContext + */ + char *zLockFile; + int nFilename; + assert( zFilename!=0 ); + nFilename = (int)strlen(zFilename) + 6; + zLockFile = (char *)sqlite3_malloc(nFilename); + if( zLockFile==0 ){ + rc = SQLITE_NOMEM; + }else{ + sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); + } + pNew->lockingContext = zLockFile; + } + +#if OS_VXWORKS + else if( pLockingStyle == &semIoMethods ){ + /* Named semaphore locking uses the file path so it needs to be + ** included in the semLockingContext + */ + unixEnterMutex(); + rc = findInodeInfo(pNew, &pNew->pInode); + if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){ + char *zSemName = pNew->pInode->aSemName; + int n; + sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem", + pNew->pId->zCanonicalName); + for( n=1; zSemName[n]; n++ ) + if( zSemName[n]=='/' ) zSemName[n] = '_'; + pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1); + if( pNew->pInode->pSem == SEM_FAILED ){ + rc = SQLITE_NOMEM; + pNew->pInode->aSemName[0] = '\0'; + } + } + unixLeaveMutex(); + } +#endif + + pNew->lastErrno = 0; +#if OS_VXWORKS + if( rc!=SQLITE_OK ){ + if( h>=0 ) robust_close(pNew, h, __LINE__); + h = -1; + osUnlink(zFilename); + pNew->ctrlFlags |= UNIXFILE_DELETE; + } +#endif + if( rc!=SQLITE_OK ){ + if( h>=0 ) robust_close(pNew, h, __LINE__); + }else{ + pNew->pMethod = pLockingStyle; + OpenCounter(+1); + verifyDbFile(pNew); + } + return rc; +} + +/* +** Return the name of a directory in which to put temporary files. +** If no suitable temporary file directory can be found, return NULL. +*/ +static const char *unixTempFileDir(void){ + static const char *azDirs[] = { + 0, + 0, + 0, + "/var/tmp", + "/usr/tmp", + "/tmp", + 0 /* List terminator */ + }; + unsigned int i; + struct stat buf; + const char *zDir = 0; + + azDirs[0] = sqlite3_temp_directory; + if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR"); + if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR"); + for(i=0; imxPathname bytes. +*/ +static int unixGetTempname(int nBuf, char *zBuf){ + static const unsigned char zChars[] = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"; + unsigned int i, j; + const char *zDir; + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. + */ + SimulateIOError( return SQLITE_IOERR ); + + zDir = unixTempFileDir(); + if( zDir==0 ) zDir = "."; + + /* Check that the output buffer is large enough for the temporary file + ** name. If it is not, return SQLITE_ERROR. + */ + if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){ + return SQLITE_ERROR; + } + + do{ + sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir); + j = (int)strlen(zBuf); + sqlite3_randomness(15, &zBuf[j]); + for(i=0; i<15; i++, j++){ + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; + } + zBuf[j] = 0; + zBuf[j+1] = 0; + }while( osAccess(zBuf,0)==0 ); + return SQLITE_OK; +} + +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) +/* +** Routine to transform a unixFile into a proxy-locking unixFile. +** Implementation in the proxy-lock division, but used by unixOpen() +** if SQLITE_PREFER_PROXY_LOCKING is defined. +*/ +static int proxyTransformUnixFile(unixFile*, const char*); +#endif + +/* +** Search for an unused file descriptor that was opened on the database +** file (not a journal or master-journal file) identified by pathname +** zPath with SQLITE_OPEN_XXX flags matching those passed as the second +** argument to this function. +** +** Such a file descriptor may exist if a database connection was closed +** but the associated file descriptor could not be closed because some +** other file descriptor open on the same file is holding a file-lock. +** Refer to comments in the unixClose() function and the lengthy comment +** describing "Posix Advisory Locking" at the start of this file for +** further details. Also, ticket #4018. +** +** If a suitable file descriptor is found, then it is returned. If no +** such file descriptor is located, -1 is returned. +*/ +static UnixUnusedFd *findReusableFd(const char *zPath, int flags){ + UnixUnusedFd *pUnused = 0; + + /* Do not search for an unused file descriptor on vxworks. Not because + ** vxworks would not benefit from the change (it might, we're not sure), + ** but because no way to test it is currently available. It is better + ** not to risk breaking vxworks support for the sake of such an obscure + ** feature. */ +#if !OS_VXWORKS + struct stat sStat; /* Results of stat() call */ + + /* A stat() call may fail for various reasons. If this happens, it is + ** almost certain that an open() call on the same path will also fail. + ** For this reason, if an error occurs in the stat() call here, it is + ** ignored and -1 is returned. The caller will try to open a new file + ** descriptor on the same path, fail, and return an error to SQLite. + ** + ** Even if a subsequent open() call does succeed, the consequences of + ** not searching for a resusable file descriptor are not dire. */ + if( 0==osStat(zPath, &sStat) ){ + unixInodeInfo *pInode; + + unixEnterMutex(); + pInode = inodeList; + while( pInode && (pInode->fileId.dev!=sStat.st_dev + || pInode->fileId.ino!=sStat.st_ino) ){ + pInode = pInode->pNext; + } + if( pInode ){ + UnixUnusedFd **pp; + for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext)); + pUnused = *pp; + if( pUnused ){ + *pp = pUnused->pNext; + } + } + unixLeaveMutex(); + } +#endif /* if !OS_VXWORKS */ + return pUnused; +} + +/* +** This function is called by unixOpen() to determine the unix permissions +** to create new files with. If no error occurs, then SQLITE_OK is returned +** and a value suitable for passing as the third argument to open(2) is +** written to *pMode. If an IO error occurs, an SQLite error code is +** returned and the value of *pMode is not modified. +** +** In most cases cases, this routine sets *pMode to 0, which will become +** an indication to robust_open() to create the file using +** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask. +** But if the file being opened is a WAL or regular journal file, then +** this function queries the file-system for the permissions on the +** corresponding database file and sets *pMode to this value. Whenever +** possible, WAL and journal files are created using the same permissions +** as the associated database file. +** +** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the +** original filename is unavailable. But 8_3_NAMES is only used for +** FAT filesystems and permissions do not matter there, so just use +** the default permissions. +*/ +static int findCreateFileMode( + const char *zPath, /* Path of file (possibly) being created */ + int flags, /* Flags passed as 4th argument to xOpen() */ + mode_t *pMode, /* OUT: Permissions to open file with */ + uid_t *pUid, /* OUT: uid to set on the file */ + gid_t *pGid /* OUT: gid to set on the file */ +){ + int rc = SQLITE_OK; /* Return Code */ + *pMode = 0; + *pUid = 0; + *pGid = 0; + if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ + char zDb[MAX_PATHNAME+1]; /* Database file path */ + int nDb; /* Number of valid bytes in zDb */ + struct stat sStat; /* Output of stat() on database file */ + + /* zPath is a path to a WAL or journal file. The following block derives + ** the path to the associated database file from zPath. This block handles + ** the following naming conventions: + ** + ** "-journal" + ** "-wal" + ** "-journalNN" + ** "-walNN" + ** + ** where NN is a decimal number. The NN naming schemes are + ** used by the test_multiplex.c module. + */ + nDb = sqlite3Strlen30(zPath) - 1; +#ifdef SQLITE_ENABLE_8_3_NAMES + while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--; + if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK; +#else + while( zPath[nDb]!='-' ){ + assert( nDb>0 ); + assert( zPath[nDb]!='\n' ); + nDb--; + } +#endif + memcpy(zDb, zPath, nDb); + zDb[nDb] = '\0'; + + if( 0==osStat(zDb, &sStat) ){ + *pMode = sStat.st_mode & 0777; + *pUid = sStat.st_uid; + *pGid = sStat.st_gid; + }else{ + rc = SQLITE_IOERR_FSTAT; + } + }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){ + *pMode = 0600; + } + return rc; +} + +/* +** Open the file zPath. +** +** Previously, the SQLite OS layer used three functions in place of this +** one: +** +** sqlite3OsOpenReadWrite(); +** sqlite3OsOpenReadOnly(); +** sqlite3OsOpenExclusive(); +** +** These calls correspond to the following combinations of flags: +** +** ReadWrite() -> (READWRITE | CREATE) +** ReadOnly() -> (READONLY) +** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE) +** +** The old OpenExclusive() accepted a boolean argument - "delFlag". If +** true, the file was configured to be automatically deleted when the +** file handle closed. To achieve the same effect using this new +** interface, add the DELETEONCLOSE flag to those specified above for +** OpenExclusive(). +*/ +static int unixOpen( + sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ + const char *zPath, /* Pathname of file to be opened */ + sqlite3_file *pFile, /* The file descriptor to be filled in */ + int flags, /* Input flags to control the opening */ + int *pOutFlags /* Output flags returned to SQLite core */ +){ + unixFile *p = (unixFile *)pFile; + int fd = -1; /* File descriptor returned by open() */ + int openFlags = 0; /* Flags to pass to open() */ + int eType = flags&0xFFFFFF00; /* Type of file to open */ + int noLock; /* True to omit locking primitives */ + int rc = SQLITE_OK; /* Function Return Code */ + int ctrlFlags = 0; /* UNIXFILE_* flags */ + + int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); + int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); + int isCreate = (flags & SQLITE_OPEN_CREATE); + int isReadonly = (flags & SQLITE_OPEN_READONLY); + int isReadWrite = (flags & SQLITE_OPEN_READWRITE); +#if SQLITE_ENABLE_LOCKING_STYLE + int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY); +#endif +#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE + struct statfs fsInfo; +#endif + + /* If creating a master or main-file journal, this function will open + ** a file-descriptor on the directory too. The first time unixSync() + ** is called the directory file descriptor will be fsync()ed and close()d. + */ + int syncDir = (isCreate && ( + eType==SQLITE_OPEN_MASTER_JOURNAL + || eType==SQLITE_OPEN_MAIN_JOURNAL + || eType==SQLITE_OPEN_WAL + )); + + /* If argument zPath is a NULL pointer, this function is required to open + ** a temporary file. Use this buffer to store the file name in. + */ + char zTmpname[MAX_PATHNAME+2]; + const char *zName = zPath; + + /* Check the following statements are true: + ** + ** (a) Exactly one of the READWRITE and READONLY flags must be set, and + ** (b) if CREATE is set, then READWRITE must also be set, and + ** (c) if EXCLUSIVE is set, then CREATE must also be set. + ** (d) if DELETEONCLOSE is set, then CREATE must also be set. + */ + assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); + assert(isCreate==0 || isReadWrite); + assert(isExclusive==0 || isCreate); + assert(isDelete==0 || isCreate); + + /* The main DB, main journal, WAL file and master journal are never + ** automatically deleted. Nor are they ever temporary files. */ + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); + + /* Assert that the upper layer has set one of the "file-type" flags. */ + assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB + || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL + || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL + || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL + ); + + memset(p, 0, sizeof(unixFile)); + + if( eType==SQLITE_OPEN_MAIN_DB ){ + UnixUnusedFd *pUnused; + pUnused = findReusableFd(zName, flags); + if( pUnused ){ + fd = pUnused->fd; + }else{ + pUnused = sqlite3_malloc(sizeof(*pUnused)); + if( !pUnused ){ + return SQLITE_NOMEM; + } + } + p->pUnused = pUnused; + + /* Database filenames are double-zero terminated if they are not + ** URIs with parameters. Hence, they can always be passed into + ** sqlite3_uri_parameter(). */ + assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 ); + + }else if( !zName ){ + /* If zName is NULL, the upper layer is requesting a temp file. */ + assert(isDelete && !syncDir); + rc = unixGetTempname(MAX_PATHNAME+2, zTmpname); + if( rc!=SQLITE_OK ){ + return rc; + } + zName = zTmpname; + + /* Generated temporary filenames are always double-zero terminated + ** for use by sqlite3_uri_parameter(). */ + assert( zName[strlen(zName)+1]==0 ); + } + + /* Determine the value of the flags parameter passed to POSIX function + ** open(). These must be calculated even if open() is not called, as + ** they may be stored as part of the file handle and used by the + ** 'conch file' locking functions later on. */ + if( isReadonly ) openFlags |= O_RDONLY; + if( isReadWrite ) openFlags |= O_RDWR; + if( isCreate ) openFlags |= O_CREAT; + if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW); + openFlags |= (O_LARGEFILE|O_BINARY); + + if( fd<0 ){ + mode_t openMode; /* Permissions to create file with */ + uid_t uid; /* Userid for the file */ + gid_t gid; /* Groupid for the file */ + rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid); + if( rc!=SQLITE_OK ){ + assert( !p->pUnused ); + assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL ); + return rc; + } + fd = robust_open(zName, openFlags, openMode); + OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); + if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){ + /* Failed to open the file for read/write access. Try read-only. */ + flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); + openFlags &= ~(O_RDWR|O_CREAT); + flags |= SQLITE_OPEN_READONLY; + openFlags |= O_RDONLY; + isReadonly = 1; + fd = robust_open(zName, openFlags, openMode); + } + if( fd<0 ){ + rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName); + goto open_finished; + } + + /* If this process is running as root and if creating a new rollback + ** journal or WAL file, set the ownership of the journal or WAL to be + ** the same as the original database. + */ + if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ + osFchown(fd, uid, gid); + } + } + assert( fd>=0 ); + if( pOutFlags ){ + *pOutFlags = flags; + } + + if( p->pUnused ){ + p->pUnused->fd = fd; + p->pUnused->flags = flags; + } + + if( isDelete ){ +#if OS_VXWORKS + zPath = zName; +#else + osUnlink(zName); +#endif + } +#if SQLITE_ENABLE_LOCKING_STYLE + else{ + p->openFlags = openFlags; + } +#endif + + noLock = eType!=SQLITE_OPEN_MAIN_DB; + + +#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE + if( fstatfs(fd, &fsInfo) == -1 ){ + ((unixFile*)pFile)->lastErrno = errno; + robust_close(p, fd, __LINE__); + return SQLITE_IOERR_ACCESS; + } + if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) { + ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; + } +#endif + + /* Set up appropriate ctrlFlags */ + if( isDelete ) ctrlFlags |= UNIXFILE_DELETE; + if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY; + if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK; + if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC; + if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI; + +#if SQLITE_ENABLE_LOCKING_STYLE +#if SQLITE_PREFER_PROXY_LOCKING + isAutoProxy = 1; +#endif + if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){ + char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING"); + int useProxy = 0; + + /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means + ** never use proxy, NULL means use proxy for non-local files only. */ + if( envforce!=NULL ){ + useProxy = atoi(envforce)>0; + }else{ + if( statfs(zPath, &fsInfo) == -1 ){ + /* In theory, the close(fd) call is sub-optimal. If the file opened + ** with fd is a database file, and there are other connections open + ** on that file that are currently holding advisory locks on it, + ** then the call to close() will cancel those locks. In practice, + ** we're assuming that statfs() doesn't fail very often. At least + ** not while other file descriptors opened by the same process on + ** the same file are working. */ + p->lastErrno = errno; + robust_close(p, fd, __LINE__); + rc = SQLITE_IOERR_ACCESS; + goto open_finished; + } + useProxy = !(fsInfo.f_flags&MNT_LOCAL); + } + if( useProxy ){ + rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); + if( rc==SQLITE_OK ){ + rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:"); + if( rc!=SQLITE_OK ){ + /* Use unixClose to clean up the resources added in fillInUnixFile + ** and clear all the structure's references. Specifically, + ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op + */ + unixClose(pFile); + return rc; + } + } + goto open_finished; + } + } +#endif + + rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); + +open_finished: + if( rc!=SQLITE_OK ){ + sqlite3_free(p->pUnused); + } + return rc; +} + + +/* +** Delete the file at zPath. If the dirSync argument is true, fsync() +** the directory after deleting the file. +*/ +static int unixDelete( + sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ + const char *zPath, /* Name of file to be deleted */ + int dirSync /* If true, fsync() directory after deleting file */ +){ + int rc = SQLITE_OK; + UNUSED_PARAMETER(NotUsed); + SimulateIOError(return SQLITE_IOERR_DELETE); + if( osUnlink(zPath)==(-1) ){ + if( errno==ENOENT ){ + rc = SQLITE_IOERR_DELETE_NOENT; + }else{ + rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath); + } + return rc; + } +#ifndef SQLITE_DISABLE_DIRSYNC + if( (dirSync & 1)!=0 ){ + int fd; + rc = osOpenDirectory(zPath, &fd); + if( rc==SQLITE_OK ){ +#if OS_VXWORKS + if( fsync(fd)==-1 ) +#else + if( fsync(fd) ) +#endif + { + rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath); + } + robust_close(0, fd, __LINE__); + }else if( rc==SQLITE_CANTOPEN ){ + rc = SQLITE_OK; + } + } +#endif + return rc; +} + +/* +** Test the existence of or access permissions of file zPath. The +** test performed depends on the value of flags: +** +** SQLITE_ACCESS_EXISTS: Return 1 if the file exists +** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable. +** SQLITE_ACCESS_READONLY: Return 1 if the file is readable. +** +** Otherwise return 0. +*/ +static int unixAccess( + sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ + const char *zPath, /* Path of the file to examine */ + int flags, /* What do we want to learn about the zPath file? */ + int *pResOut /* Write result boolean here */ +){ + int amode = 0; + UNUSED_PARAMETER(NotUsed); + SimulateIOError( return SQLITE_IOERR_ACCESS; ); + switch( flags ){ + case SQLITE_ACCESS_EXISTS: + amode = F_OK; + break; + case SQLITE_ACCESS_READWRITE: + amode = W_OK|R_OK; + break; + case SQLITE_ACCESS_READ: + amode = R_OK; + break; + + default: + assert(!"Invalid flags argument"); + } + *pResOut = (osAccess(zPath, amode)==0); + if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){ + struct stat buf; + if( 0==osStat(zPath, &buf) && buf.st_size==0 ){ + *pResOut = 0; + } + } + return SQLITE_OK; +} + + +/* +** Turn a relative pathname into a full pathname. The relative path +** is stored as a nul-terminated string in the buffer pointed to by +** zPath. +** +** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes +** (in this case, MAX_PATHNAME bytes). The full-path is written to +** this buffer before returning. +*/ +static int unixFullPathname( + sqlite3_vfs *pVfs, /* Pointer to vfs object */ + const char *zPath, /* Possibly relative input path */ + int nOut, /* Size of output buffer in bytes */ + char *zOut /* Output buffer */ +){ + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. This function could fail if, for example, the + ** current working directory has been unlinked. + */ + SimulateIOError( return SQLITE_ERROR ); + + assert( pVfs->mxPathname==MAX_PATHNAME ); + UNUSED_PARAMETER(pVfs); + + zOut[nOut-1] = '\0'; + if( zPath[0]=='/' ){ + sqlite3_snprintf(nOut, zOut, "%s", zPath); + }else{ + int nCwd; + if( osGetcwd(zOut, nOut-1)==0 ){ + return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath); + } + nCwd = (int)strlen(zOut); + sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath); + } + return SQLITE_OK; +} + + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +/* +** Interfaces for opening a shared library, finding entry points +** within the shared library, and closing the shared library. +*/ +#include +static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){ + UNUSED_PARAMETER(NotUsed); + return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL); +} + +/* +** SQLite calls this function immediately after a call to unixDlSym() or +** unixDlOpen() fails (returns a null pointer). If a more detailed error +** message is available, it is written to zBufOut. If no error message +** is available, zBufOut is left unmodified and SQLite uses a default +** error message. +*/ +static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){ + const char *zErr; + UNUSED_PARAMETER(NotUsed); + unixEnterMutex(); + zErr = dlerror(); + if( zErr ){ + sqlite3_snprintf(nBuf, zBufOut, "%s", zErr); + } + unixLeaveMutex(); +} +static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){ + /* + ** GCC with -pedantic-errors says that C90 does not allow a void* to be + ** cast into a pointer to a function. And yet the library dlsym() routine + ** returns a void* which is really a pointer to a function. So how do we + ** use dlsym() with -pedantic-errors? + ** + ** Variable x below is defined to be a pointer to a function taking + ** parameters void* and const char* and returning a pointer to a function. + ** We initialize x by assigning it a pointer to the dlsym() function. + ** (That assignment requires a cast.) Then we call the function that + ** x points to. + ** + ** This work-around is unlikely to work correctly on any system where + ** you really cannot cast a function pointer into void*. But then, on the + ** other hand, dlsym() will not work on such a system either, so we have + ** not really lost anything. + */ + void (*(*x)(void*,const char*))(void); + UNUSED_PARAMETER(NotUsed); + x = (void(*(*)(void*,const char*))(void))dlsym; + return (*x)(p, zSym); +} +static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){ + UNUSED_PARAMETER(NotUsed); + dlclose(pHandle); +} +#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ + #define unixDlOpen 0 + #define unixDlError 0 + #define unixDlSym 0 + #define unixDlClose 0 +#endif + +/* +** Write nBuf bytes of random data to the supplied buffer zBuf. +*/ +static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ + UNUSED_PARAMETER(NotUsed); + assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int))); + + /* We have to initialize zBuf to prevent valgrind from reporting + ** errors. The reports issued by valgrind are incorrect - we would + ** prefer that the randomness be increased by making use of the + ** uninitialized space in zBuf - but valgrind errors tend to worry + ** some users. Rather than argue, it seems easier just to initialize + ** the whole array and silence valgrind, even if that means less randomness + ** in the random seed. + ** + ** When testing, initializing zBuf[] to zero is all we do. That means + ** that we always use the same random number sequence. This makes the + ** tests repeatable. + */ + memset(zBuf, 0, nBuf); +#if !defined(SQLITE_TEST) + { + int pid, fd, got; + fd = robust_open("/dev/urandom", O_RDONLY, 0); + if( fd<0 ){ + time_t t; + time(&t); + memcpy(zBuf, &t, sizeof(t)); + pid = getpid(); + memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid)); + assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf ); + nBuf = sizeof(t) + sizeof(pid); + }else{ + do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR ); + robust_close(0, fd, __LINE__); + } + } +#endif + return nBuf; +} + + +/* +** Sleep for a little while. Return the amount of time slept. +** The argument is the number of microseconds we want to sleep. +** The return value is the number of microseconds of sleep actually +** requested from the underlying operating system, a number which +** might be greater than or equal to the argument, but not less +** than the argument. +*/ +static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){ +#if OS_VXWORKS + struct timespec sp; + + sp.tv_sec = microseconds / 1000000; + sp.tv_nsec = (microseconds % 1000000) * 1000; + nanosleep(&sp, NULL); + UNUSED_PARAMETER(NotUsed); + return microseconds; +#elif defined(HAVE_USLEEP) && HAVE_USLEEP + usleep(microseconds); + UNUSED_PARAMETER(NotUsed); + return microseconds; +#else + int seconds = (microseconds+999999)/1000000; + sleep(seconds); + UNUSED_PARAMETER(NotUsed); + return seconds*1000000; +#endif +} + +/* +** The following variable, if set to a non-zero value, is interpreted as +** the number of seconds since 1970 and is used to set the result of +** sqlite3OsCurrentTime() during testing. +*/ +#ifdef SQLITE_TEST +int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ +#endif + +/* +** Find the current time (in Universal Coordinated Time). Write into *piNow +** the current time and date as a Julian Day number times 86_400_000. In +** other words, write into *piNow the number of milliseconds since the Julian +** epoch of noon in Greenwich on November 24, 4714 B.C according to the +** proleptic Gregorian calendar. +** +** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date +** cannot be found. +*/ +static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){ + static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; + int rc = SQLITE_OK; +#if defined(NO_GETTOD) + time_t t; + time(&t); + *piNow = ((sqlite3_int64)t)*1000 + unixEpoch; +#elif OS_VXWORKS + struct timespec sNow; + clock_gettime(CLOCK_REALTIME, &sNow); + *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000; +#else + struct timeval sNow; + if( gettimeofday(&sNow, 0)==0 ){ + *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000; + }else{ + rc = SQLITE_ERROR; + } +#endif + +#ifdef SQLITE_TEST + if( sqlite3_current_time ){ + *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; + } +#endif + UNUSED_PARAMETER(NotUsed); + return rc; +} + +/* +** Find the current time (in Universal Coordinated Time). Write the +** current time and date as a Julian Day number into *prNow and +** return 0. Return 1 if the time and date cannot be found. +*/ +static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){ + sqlite3_int64 i = 0; + int rc; + UNUSED_PARAMETER(NotUsed); + rc = unixCurrentTimeInt64(0, &i); + *prNow = i/86400000.0; + return rc; +} + +/* +** We added the xGetLastError() method with the intention of providing +** better low-level error messages when operating-system problems come up +** during SQLite operation. But so far, none of that has been implemented +** in the core. So this routine is never called. For now, it is merely +** a place-holder. +*/ +static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ + UNUSED_PARAMETER(NotUsed); + UNUSED_PARAMETER(NotUsed2); + UNUSED_PARAMETER(NotUsed3); + return 0; +} + + +/* +************************ End of sqlite3_vfs methods *************************** +******************************************************************************/ + +/****************************************************************************** +************************** Begin Proxy Locking ******************************** +** +** Proxy locking is a "uber-locking-method" in this sense: It uses the +** other locking methods on secondary lock files. Proxy locking is a +** meta-layer over top of the primitive locking implemented above. For +** this reason, the division that implements of proxy locking is deferred +** until late in the file (here) after all of the other I/O methods have +** been defined - so that the primitive locking methods are available +** as services to help with the implementation of proxy locking. +** +**** +** +** The default locking schemes in SQLite use byte-range locks on the +** database file to coordinate safe, concurrent access by multiple readers +** and writers [http://sqlite.org/lockingv3.html]. The five file locking +** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented +** as POSIX read & write locks over fixed set of locations (via fsctl), +** on AFP and SMB only exclusive byte-range locks are available via fsctl +** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states. +** To simulate a F_RDLCK on the shared range, on AFP a randomly selected +** address in the shared range is taken for a SHARED lock, the entire +** shared range is taken for an EXCLUSIVE lock): +** +** PENDING_BYTE 0x40000000 +** RESERVED_BYTE 0x40000001 +** SHARED_RANGE 0x40000002 -> 0x40000200 +** +** This works well on the local file system, but shows a nearly 100x +** slowdown in read performance on AFP because the AFP client disables +** the read cache when byte-range locks are present. Enabling the read +** cache exposes a cache coherency problem that is present on all OS X +** supported network file systems. NFS and AFP both observe the +** close-to-open semantics for ensuring cache coherency +** [http://nfs.sourceforge.net/#faq_a8], which does not effectively +** address the requirements for concurrent database access by multiple +** readers and writers +** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html]. +** +** To address the performance and cache coherency issues, proxy file locking +** changes the way database access is controlled by limiting access to a +** single host at a time and moving file locks off of the database file +** and onto a proxy file on the local file system. +** +** +** Using proxy locks +** ----------------- +** +** C APIs +** +** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE, +** | ":auto:"); +** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &); +** +** +** SQL pragmas +** +** PRAGMA [database.]lock_proxy_file= | :auto: +** PRAGMA [database.]lock_proxy_file +** +** Specifying ":auto:" means that if there is a conch file with a matching +** host ID in it, the proxy path in the conch file will be used, otherwise +** a proxy path based on the user's temp dir +** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the +** actual proxy file name is generated from the name and path of the +** database file. For example: +** +** For database path "/Users/me/foo.db" +** The lock path will be "/sqliteplocks/_Users_me_foo.db:auto:") +** +** Once a lock proxy is configured for a database connection, it can not +** be removed, however it may be switched to a different proxy path via +** the above APIs (assuming the conch file is not being held by another +** connection or process). +** +** +** How proxy locking works +** ----------------------- +** +** Proxy file locking relies primarily on two new supporting files: +** +** * conch file to limit access to the database file to a single host +** at a time +** +** * proxy file to act as a proxy for the advisory locks normally +** taken on the database +** +** The conch file - to use a proxy file, sqlite must first "hold the conch" +** by taking an sqlite-style shared lock on the conch file, reading the +** contents and comparing the host's unique host ID (see below) and lock +** proxy path against the values stored in the conch. The conch file is +** stored in the same directory as the database file and the file name +** is patterned after the database file name as ".-conch". +** If the conch file does not exist, or it's contents do not match the +** host ID and/or proxy path, then the lock is escalated to an exclusive +** lock and the conch file contents is updated with the host ID and proxy +** path and the lock is downgraded to a shared lock again. If the conch +** is held by another process (with a shared lock), the exclusive lock +** will fail and SQLITE_BUSY is returned. +** +** The proxy file - a single-byte file used for all advisory file locks +** normally taken on the database file. This allows for safe sharing +** of the database file for multiple readers and writers on the same +** host (the conch ensures that they all use the same local lock file). +** +** Requesting the lock proxy does not immediately take the conch, it is +** only taken when the first request to lock database file is made. +** This matches the semantics of the traditional locking behavior, where +** opening a connection to a database file does not take a lock on it. +** The shared lock and an open file descriptor are maintained until +** the connection to the database is closed. +** +** The proxy file and the lock file are never deleted so they only need +** to be created the first time they are used. +** +** Configuration options +** --------------------- +** +** SQLITE_PREFER_PROXY_LOCKING +** +** Database files accessed on non-local file systems are +** automatically configured for proxy locking, lock files are +** named automatically using the same logic as +** PRAGMA lock_proxy_file=":auto:" +** +** SQLITE_PROXY_DEBUG +** +** Enables the logging of error messages during host id file +** retrieval and creation +** +** LOCKPROXYDIR +** +** Overrides the default directory used for lock proxy files that +** are named automatically via the ":auto:" setting +** +** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS +** +** Permissions to use when creating a directory for storing the +** lock proxy files, only used when LOCKPROXYDIR is not set. +** +** +** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING, +** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will +** force proxy locking to be used for every database file opened, and 0 +** will force automatic proxy locking to be disabled for all database +** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or +** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING). +*/ + +/* +** Proxy locking is only available on MacOSX +*/ +#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE + +/* +** The proxyLockingContext has the path and file structures for the remote +** and local proxy files in it +*/ +typedef struct proxyLockingContext proxyLockingContext; +struct proxyLockingContext { + unixFile *conchFile; /* Open conch file */ + char *conchFilePath; /* Name of the conch file */ + unixFile *lockProxy; /* Open proxy lock file */ + char *lockProxyPath; /* Name of the proxy lock file */ + char *dbPath; /* Name of the open file */ + int conchHeld; /* 1 if the conch is held, -1 if lockless */ + void *oldLockingContext; /* Original lockingcontext to restore on close */ + sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ +}; + +/* +** The proxy lock file path for the database at dbPath is written into lPath, +** which must point to valid, writable memory large enough for a maxLen length +** file path. +*/ +static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){ + int len; + int dbLen; + int i; + +#ifdef LOCKPROXYDIR + len = strlcpy(lPath, LOCKPROXYDIR, maxLen); +#else +# ifdef _CS_DARWIN_USER_TEMP_DIR + { + if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){ + OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n", + lPath, errno, getpid())); + return SQLITE_IOERR_LOCK; + } + len = strlcat(lPath, "sqliteplocks", maxLen); + } +# else + len = strlcpy(lPath, "/tmp/", maxLen); +# endif +#endif + + if( lPath[len-1]!='/' ){ + len = strlcat(lPath, "/", maxLen); + } + + /* transform the db path to a unique cache name */ + dbLen = (int)strlen(dbPath); + for( i=0; i 0) ){ + /* only mkdir if leaf dir != "." or "/" or ".." */ + if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') + || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){ + buf[i]='\0'; + if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){ + int err=errno; + if( err!=EEXIST ) { + OSTRACE(("CREATELOCKPATH FAILED creating %s, " + "'%s' proxy lock path=%s pid=%d\n", + buf, strerror(err), lockPath, getpid())); + return err; + } + } + } + start=i+1; + } + buf[i] = lockPath[i]; + } + OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid())); + return 0; +} + +/* +** Create a new VFS file descriptor (stored in memory obtained from +** sqlite3_malloc) and open the file named "path" in the file descriptor. +** +** The caller is responsible not only for closing the file descriptor +** but also for freeing the memory associated with the file descriptor. +*/ +static int proxyCreateUnixFile( + const char *path, /* path for the new unixFile */ + unixFile **ppFile, /* unixFile created and returned by ref */ + int islockfile /* if non zero missing dirs will be created */ +) { + int fd = -1; + unixFile *pNew; + int rc = SQLITE_OK; + int openFlags = O_RDWR | O_CREAT; + sqlite3_vfs dummyVfs; + int terrno = 0; + UnixUnusedFd *pUnused = NULL; + + /* 1. first try to open/create the file + ** 2. if that fails, and this is a lock file (not-conch), try creating + ** the parent directories and then try again. + ** 3. if that fails, try to open the file read-only + ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file + */ + pUnused = findReusableFd(path, openFlags); + if( pUnused ){ + fd = pUnused->fd; + }else{ + pUnused = sqlite3_malloc(sizeof(*pUnused)); + if( !pUnused ){ + return SQLITE_NOMEM; + } + } + if( fd<0 ){ + fd = robust_open(path, openFlags, 0); + terrno = errno; + if( fd<0 && errno==ENOENT && islockfile ){ + if( proxyCreateLockPath(path) == SQLITE_OK ){ + fd = robust_open(path, openFlags, 0); + } + } + } + if( fd<0 ){ + openFlags = O_RDONLY; + fd = robust_open(path, openFlags, 0); + terrno = errno; + } + if( fd<0 ){ + if( islockfile ){ + return SQLITE_BUSY; + } + switch (terrno) { + case EACCES: + return SQLITE_PERM; + case EIO: + return SQLITE_IOERR_LOCK; /* even though it is the conch */ + default: + return SQLITE_CANTOPEN_BKPT; + } + } + + pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew)); + if( pNew==NULL ){ + rc = SQLITE_NOMEM; + goto end_create_proxy; + } + memset(pNew, 0, sizeof(unixFile)); + pNew->openFlags = openFlags; + memset(&dummyVfs, 0, sizeof(dummyVfs)); + dummyVfs.pAppData = (void*)&autolockIoFinder; + dummyVfs.zName = "dummy"; + pUnused->fd = fd; + pUnused->flags = openFlags; + pNew->pUnused = pUnused; + + rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0); + if( rc==SQLITE_OK ){ + *ppFile = pNew; + return SQLITE_OK; + } +end_create_proxy: + robust_close(pNew, fd, __LINE__); + sqlite3_free(pNew); + sqlite3_free(pUnused); + return rc; +} + +#ifdef SQLITE_TEST +/* simulate multiple hosts by creating unique hostid file paths */ +int sqlite3_hostid_num = 0; +#endif + +#define PROXY_HOSTIDLEN 16 /* conch file host id length */ + +/* Not always defined in the headers as it ought to be */ +extern int gethostuuid(uuid_t id, const struct timespec *wait); + +/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN +** bytes of writable memory. +*/ +static int proxyGetHostID(unsigned char *pHostID, int *pError){ + assert(PROXY_HOSTIDLEN == sizeof(uuid_t)); + memset(pHostID, 0, PROXY_HOSTIDLEN); +#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\ + && __MAC_OS_X_VERSION_MIN_REQUIRED<1050 + { + static const struct timespec timeout = {1, 0}; /* 1 sec timeout */ + if( gethostuuid(pHostID, &timeout) ){ + int err = errno; + if( pError ){ + *pError = err; + } + return SQLITE_IOERR; + } + } +#else + UNUSED_PARAMETER(pError); +#endif +#ifdef SQLITE_TEST + /* simulate multiple hosts by creating unique hostid file paths */ + if( sqlite3_hostid_num != 0){ + pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF)); + } +#endif + + return SQLITE_OK; +} + +/* The conch file contains the header, host id and lock file path + */ +#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */ +#define PROXY_HEADERLEN 1 /* conch file header length */ +#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN) +#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN) + +/* +** Takes an open conch file, copies the contents to a new path and then moves +** it back. The newly created file's file descriptor is assigned to the +** conch file structure and finally the original conch file descriptor is +** closed. Returns zero if successful. +*/ +static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){ + proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; + unixFile *conchFile = pCtx->conchFile; + char tPath[MAXPATHLEN]; + char buf[PROXY_MAXCONCHLEN]; + char *cPath = pCtx->conchFilePath; + size_t readLen = 0; + size_t pathLen = 0; + char errmsg[64] = ""; + int fd = -1; + int rc = -1; + UNUSED_PARAMETER(myHostID); + + /* create a new path by replace the trailing '-conch' with '-break' */ + pathLen = strlcpy(tPath, cPath, MAXPATHLEN); + if( pathLen>MAXPATHLEN || pathLen<6 || + (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){ + sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen); + goto end_breaklock; + } + /* read the conch content */ + readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0); + if( readLenh, __LINE__); + conchFile->h = fd; + conchFile->openFlags = O_RDWR | O_CREAT; + +end_breaklock: + if( rc ){ + if( fd>=0 ){ + osUnlink(tPath); + robust_close(pFile, fd, __LINE__); + } + fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg); + } + return rc; +} + +/* Take the requested lock on the conch file and break a stale lock if the +** host id matches. +*/ +static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){ + proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; + unixFile *conchFile = pCtx->conchFile; + int rc = SQLITE_OK; + int nTries = 0; + struct timespec conchModTime; + + memset(&conchModTime, 0, sizeof(conchModTime)); + do { + rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); + nTries ++; + if( rc==SQLITE_BUSY ){ + /* If the lock failed (busy): + * 1st try: get the mod time of the conch, wait 0.5s and try again. + * 2nd try: fail if the mod time changed or host id is different, wait + * 10 sec and try again + * 3rd try: break the lock unless the mod time has changed. + */ + struct stat buf; + if( osFstat(conchFile->h, &buf) ){ + pFile->lastErrno = errno; + return SQLITE_IOERR_LOCK; + } + + if( nTries==1 ){ + conchModTime = buf.st_mtimespec; + usleep(500000); /* wait 0.5 sec and try the lock again*/ + continue; + } + + assert( nTries>1 ); + if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || + conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){ + return SQLITE_BUSY; + } + + if( nTries==2 ){ + char tBuf[PROXY_MAXCONCHLEN]; + int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0); + if( len<0 ){ + pFile->lastErrno = errno; + return SQLITE_IOERR_LOCK; + } + if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){ + /* don't break the lock if the host id doesn't match */ + if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){ + return SQLITE_BUSY; + } + }else{ + /* don't break the lock on short read or a version mismatch */ + return SQLITE_BUSY; + } + usleep(10000000); /* wait 10 sec and try the lock again */ + continue; + } + + assert( nTries==3 ); + if( 0==proxyBreakConchLock(pFile, myHostID) ){ + rc = SQLITE_OK; + if( lockType==EXCLUSIVE_LOCK ){ + rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); + } + if( !rc ){ + rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); + } + } + } + } while( rc==SQLITE_BUSY && nTries<3 ); + + return rc; +} + +/* Takes the conch by taking a shared lock and read the contents conch, if +** lockPath is non-NULL, the host ID and lock file path must match. A NULL +** lockPath means that the lockPath in the conch file will be used if the +** host IDs match, or a new lock path will be generated automatically +** and written to the conch file. +*/ +static int proxyTakeConch(unixFile *pFile){ + proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; + + if( pCtx->conchHeld!=0 ){ + return SQLITE_OK; + }else{ + unixFile *conchFile = pCtx->conchFile; + uuid_t myHostID; + int pError = 0; + char readBuf[PROXY_MAXCONCHLEN]; + char lockPath[MAXPATHLEN]; + char *tempLockPath = NULL; + int rc = SQLITE_OK; + int createConch = 0; + int hostIdMatch = 0; + int readLen = 0; + int tryOldLockPath = 0; + int forceNewLockPath = 0; + + OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h, + (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid())); + + rc = proxyGetHostID(myHostID, &pError); + if( (rc&0xff)==SQLITE_IOERR ){ + pFile->lastErrno = pError; + goto end_takeconch; + } + rc = proxyConchLock(pFile, myHostID, SHARED_LOCK); + if( rc!=SQLITE_OK ){ + goto end_takeconch; + } + /* read the existing conch file */ + readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN); + if( readLen<0 ){ + /* I/O error: lastErrno set by seekAndRead */ + pFile->lastErrno = conchFile->lastErrno; + rc = SQLITE_IOERR_READ; + goto end_takeconch; + }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || + readBuf[0]!=(char)PROXY_CONCHVERSION ){ + /* a short read or version format mismatch means we need to create a new + ** conch file. + */ + createConch = 1; + } + /* if the host id matches and the lock path already exists in the conch + ** we'll try to use the path there, if we can't open that path, we'll + ** retry with a new auto-generated path + */ + do { /* in case we need to try again for an :auto: named lock file */ + + if( !createConch && !forceNewLockPath ){ + hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, + PROXY_HOSTIDLEN); + /* if the conch has data compare the contents */ + if( !pCtx->lockProxyPath ){ + /* for auto-named local lock file, just check the host ID and we'll + ** use the local lock file path that's already in there + */ + if( hostIdMatch ){ + size_t pathLen = (readLen - PROXY_PATHINDEX); + + if( pathLen>=MAXPATHLEN ){ + pathLen=MAXPATHLEN-1; + } + memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen); + lockPath[pathLen] = 0; + tempLockPath = lockPath; + tryOldLockPath = 1; + /* create a copy of the lock path if the conch is taken */ + goto end_takeconch; + } + }else if( hostIdMatch + && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX], + readLen-PROXY_PATHINDEX) + ){ + /* conch host and lock path match */ + goto end_takeconch; + } + } + + /* if the conch isn't writable and doesn't match, we can't take it */ + if( (conchFile->openFlags&O_RDWR) == 0 ){ + rc = SQLITE_BUSY; + goto end_takeconch; + } + + /* either the conch didn't match or we need to create a new one */ + if( !pCtx->lockProxyPath ){ + proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); + tempLockPath = lockPath; + /* create a copy of the lock path _only_ if the conch is taken */ + } + + /* update conch with host and path (this will fail if other process + ** has a shared lock already), if the host id matches, use the big + ** stick. + */ + futimes(conchFile->h, NULL); + if( hostIdMatch && !createConch ){ + if( conchFile->pInode && conchFile->pInode->nShared>1 ){ + /* We are trying for an exclusive lock but another thread in this + ** same process is still holding a shared lock. */ + rc = SQLITE_BUSY; + } else { + rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); + } + }else{ + rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK); + } + if( rc==SQLITE_OK ){ + char writeBuffer[PROXY_MAXCONCHLEN]; + int writeSize = 0; + + writeBuffer[0] = (char)PROXY_CONCHVERSION; + memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); + if( pCtx->lockProxyPath!=NULL ){ + strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN); + }else{ + strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN); + } + writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]); + robust_ftruncate(conchFile->h, writeSize); + rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0); + fsync(conchFile->h); + /* If we created a new conch file (not just updated the contents of a + ** valid conch file), try to match the permissions of the database + */ + if( rc==SQLITE_OK && createConch ){ + struct stat buf; + int err = osFstat(pFile->h, &buf); + if( err==0 ){ + mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP | + S_IROTH|S_IWOTH); + /* try to match the database file R/W permissions, ignore failure */ +#ifndef SQLITE_PROXY_DEBUG + osFchmod(conchFile->h, cmode); +#else + do{ + rc = osFchmod(conchFile->h, cmode); + }while( rc==(-1) && errno==EINTR ); + if( rc!=0 ){ + int code = errno; + fprintf(stderr, "fchmod %o FAILED with %d %s\n", + cmode, code, strerror(code)); + } else { + fprintf(stderr, "fchmod %o SUCCEDED\n",cmode); + } + }else{ + int code = errno; + fprintf(stderr, "STAT FAILED[%d] with %d %s\n", + err, code, strerror(code)); +#endif + } + } + } + conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); + + end_takeconch: + OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h)); + if( rc==SQLITE_OK && pFile->openFlags ){ + int fd; + if( pFile->h>=0 ){ + robust_close(pFile, pFile->h, __LINE__); + } + pFile->h = -1; + fd = robust_open(pCtx->dbPath, pFile->openFlags, 0); + OSTRACE(("TRANSPROXY: OPEN %d\n", fd)); + if( fd>=0 ){ + pFile->h = fd; + }else{ + rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called + during locking */ + } + } + if( rc==SQLITE_OK && !pCtx->lockProxy ){ + char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath; + rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1); + if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){ + /* we couldn't create the proxy lock file with the old lock file path + ** so try again via auto-naming + */ + forceNewLockPath = 1; + tryOldLockPath = 0; + continue; /* go back to the do {} while start point, try again */ + } + } + if( rc==SQLITE_OK ){ + /* Need to make a copy of path if we extracted the value + ** from the conch file or the path was allocated on the stack + */ + if( tempLockPath ){ + pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath); + if( !pCtx->lockProxyPath ){ + rc = SQLITE_NOMEM; + } + } + } + if( rc==SQLITE_OK ){ + pCtx->conchHeld = 1; + + if( pCtx->lockProxy->pMethod == &afpIoMethods ){ + afpLockingContext *afpCtx; + afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext; + afpCtx->dbPath = pCtx->lockProxyPath; + } + } else { + conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); + } + OSTRACE(("TAKECONCH %d %s\n", conchFile->h, + rc==SQLITE_OK?"ok":"failed")); + return rc; + } while (1); /* in case we need to retry the :auto: lock file - + ** we should never get here except via the 'continue' call. */ + } +} + +/* +** If pFile holds a lock on a conch file, then release that lock. +*/ +static int proxyReleaseConch(unixFile *pFile){ + int rc = SQLITE_OK; /* Subroutine return code */ + proxyLockingContext *pCtx; /* The locking context for the proxy lock */ + unixFile *conchFile; /* Name of the conch file */ + + pCtx = (proxyLockingContext *)pFile->lockingContext; + conchFile = pCtx->conchFile; + OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h, + (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), + getpid())); + if( pCtx->conchHeld>0 ){ + rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); + } + pCtx->conchHeld = 0; + OSTRACE(("RELEASECONCH %d %s\n", conchFile->h, + (rc==SQLITE_OK ? "ok" : "failed"))); + return rc; +} + +/* +** Given the name of a database file, compute the name of its conch file. +** Store the conch filename in memory obtained from sqlite3_malloc(). +** Make *pConchPath point to the new name. Return SQLITE_OK on success +** or SQLITE_NOMEM if unable to obtain memory. +** +** The caller is responsible for ensuring that the allocated memory +** space is eventually freed. +** +** *pConchPath is set to NULL if a memory allocation error occurs. +*/ +static int proxyCreateConchPathname(char *dbPath, char **pConchPath){ + int i; /* Loop counter */ + int len = (int)strlen(dbPath); /* Length of database filename - dbPath */ + char *conchPath; /* buffer in which to construct conch name */ + + /* Allocate space for the conch filename and initialize the name to + ** the name of the original database file. */ + *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8); + if( conchPath==0 ){ + return SQLITE_NOMEM; + } + memcpy(conchPath, dbPath, len+1); + + /* now insert a "." before the last / character */ + for( i=(len-1); i>=0; i-- ){ + if( conchPath[i]=='/' ){ + i++; + break; + } + } + conchPath[i]='.'; + while ( ilockingContext; + char *oldPath = pCtx->lockProxyPath; + int rc = SQLITE_OK; + + if( pFile->eFileLock!=NO_LOCK ){ + return SQLITE_BUSY; + } + + /* nothing to do if the path is NULL, :auto: or matches the existing path */ + if( !path || path[0]=='\0' || !strcmp(path, ":auto:") || + (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){ + return SQLITE_OK; + }else{ + unixFile *lockProxy = pCtx->lockProxy; + pCtx->lockProxy=NULL; + pCtx->conchHeld = 0; + if( lockProxy!=NULL ){ + rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy); + if( rc ) return rc; + sqlite3_free(lockProxy); + } + sqlite3_free(oldPath); + pCtx->lockProxyPath = sqlite3DbStrDup(0, path); + } + + return rc; +} + +/* +** pFile is a file that has been opened by a prior xOpen call. dbPath +** is a string buffer at least MAXPATHLEN+1 characters in size. +** +** This routine find the filename associated with pFile and writes it +** int dbPath. +*/ +static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ +#if defined(__APPLE__) + if( pFile->pMethod == &afpIoMethods ){ + /* afp style keeps a reference to the db path in the filePath field + ** of the struct */ + assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); + strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN); + } else +#endif + if( pFile->pMethod == &dotlockIoMethods ){ + /* dot lock style uses the locking context to store the dot lock + ** file path */ + int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); + memcpy(dbPath, (char *)pFile->lockingContext, len + 1); + }else{ + /* all other styles use the locking context to store the db file path */ + assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); + strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN); + } + return SQLITE_OK; +} + +/* +** Takes an already filled in unix file and alters it so all file locking +** will be performed on the local proxy lock file. The following fields +** are preserved in the locking context so that they can be restored and +** the unix structure properly cleaned up at close time: +** ->lockingContext +** ->pMethod +*/ +static int proxyTransformUnixFile(unixFile *pFile, const char *path) { + proxyLockingContext *pCtx; + char dbPath[MAXPATHLEN+1]; /* Name of the database file */ + char *lockPath=NULL; + int rc = SQLITE_OK; + + if( pFile->eFileLock!=NO_LOCK ){ + return SQLITE_BUSY; + } + proxyGetDbPathForUnixFile(pFile, dbPath); + if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){ + lockPath=NULL; + }else{ + lockPath=(char *)path; + } + + OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h, + (lockPath ? lockPath : ":auto:"), getpid())); + + pCtx = sqlite3_malloc( sizeof(*pCtx) ); + if( pCtx==0 ){ + return SQLITE_NOMEM; + } + memset(pCtx, 0, sizeof(*pCtx)); + + rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); + if( rc==SQLITE_OK ){ + rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0); + if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){ + /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and + ** (c) the file system is read-only, then enable no-locking access. + ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts + ** that openFlags will have only one of O_RDONLY or O_RDWR. + */ + struct statfs fsInfo; + struct stat conchInfo; + int goLockless = 0; + + if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) { + int err = errno; + if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){ + goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY; + } + } + if( goLockless ){ + pCtx->conchHeld = -1; /* read only FS/ lockless */ + rc = SQLITE_OK; + } + } + } + if( rc==SQLITE_OK && lockPath ){ + pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); + } + + if( rc==SQLITE_OK ){ + pCtx->dbPath = sqlite3DbStrDup(0, dbPath); + if( pCtx->dbPath==NULL ){ + rc = SQLITE_NOMEM; + } + } + if( rc==SQLITE_OK ){ + /* all memory is allocated, proxys are created and assigned, + ** switch the locking context and pMethod then return. + */ + pCtx->oldLockingContext = pFile->lockingContext; + pFile->lockingContext = pCtx; + pCtx->pOldMethod = pFile->pMethod; + pFile->pMethod = &proxyIoMethods; + }else{ + if( pCtx->conchFile ){ + pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); + sqlite3_free(pCtx->conchFile); + } + sqlite3DbFree(0, pCtx->lockProxyPath); + sqlite3_free(pCtx->conchFilePath); + sqlite3_free(pCtx); + } + OSTRACE(("TRANSPROXY %d %s\n", pFile->h, + (rc==SQLITE_OK ? "ok" : "failed"))); + return rc; +} + + +/* +** This routine handles sqlite3_file_control() calls that are specific +** to proxy locking. +*/ +static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ + switch( op ){ + case SQLITE_GET_LOCKPROXYFILE: { + unixFile *pFile = (unixFile*)id; + if( pFile->pMethod == &proxyIoMethods ){ + proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; + proxyTakeConch(pFile); + if( pCtx->lockProxyPath ){ + *(const char **)pArg = pCtx->lockProxyPath; + }else{ + *(const char **)pArg = ":auto: (not held)"; + } + } else { + *(const char **)pArg = NULL; + } + return SQLITE_OK; + } + case SQLITE_SET_LOCKPROXYFILE: { + unixFile *pFile = (unixFile*)id; + int rc = SQLITE_OK; + int isProxyStyle = (pFile->pMethod == &proxyIoMethods); + if( pArg==NULL || (const char *)pArg==0 ){ + if( isProxyStyle ){ + /* turn off proxy locking - not supported */ + rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/; + }else{ + /* turn off proxy locking - already off - NOOP */ + rc = SQLITE_OK; + } + }else{ + const char *proxyPath = (const char *)pArg; + if( isProxyStyle ){ + proxyLockingContext *pCtx = + (proxyLockingContext*)pFile->lockingContext; + if( !strcmp(pArg, ":auto:") + || (pCtx->lockProxyPath && + !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN)) + ){ + rc = SQLITE_OK; + }else{ + rc = switchLockProxyPath(pFile, proxyPath); + } + }else{ + /* turn on proxy file locking */ + rc = proxyTransformUnixFile(pFile, proxyPath); + } + } + return rc; + } + default: { + assert( 0 ); /* The call assures that only valid opcodes are sent */ + } + } + /*NOTREACHED*/ + return SQLITE_ERROR; +} + +/* +** Within this division (the proxying locking implementation) the procedures +** above this point are all utilities. The lock-related methods of the +** proxy-locking sqlite3_io_method object follow. +*/ + + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, set *pResOut +** to a non-zero value otherwise *pResOut is set to zero. The return value +** is set to SQLITE_OK unless an I/O error occurs during lock checking. +*/ +static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { + unixFile *pFile = (unixFile*)id; + int rc = proxyTakeConch(pFile); + if( rc==SQLITE_OK ){ + proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; + if( pCtx->conchHeld>0 ){ + unixFile *proxy = pCtx->lockProxy; + return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); + }else{ /* conchHeld < 0 is lockless */ + pResOut=0; + } + } + return rc; +} + +/* +** Lock the file with the lock specified by parameter eFileLock - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** This routine will only increase a lock. Use the sqlite3OsUnlock() +** routine to lower a locking level. +*/ +static int proxyLock(sqlite3_file *id, int eFileLock) { + unixFile *pFile = (unixFile*)id; + int rc = proxyTakeConch(pFile); + if( rc==SQLITE_OK ){ + proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; + if( pCtx->conchHeld>0 ){ + unixFile *proxy = pCtx->lockProxy; + rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock); + pFile->eFileLock = proxy->eFileLock; + }else{ + /* conchHeld < 0 is lockless */ + } + } + return rc; +} + + +/* +** Lower the locking level on file descriptor pFile to eFileLock. eFileLock +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +*/ +static int proxyUnlock(sqlite3_file *id, int eFileLock) { + unixFile *pFile = (unixFile*)id; + int rc = proxyTakeConch(pFile); + if( rc==SQLITE_OK ){ + proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; + if( pCtx->conchHeld>0 ){ + unixFile *proxy = pCtx->lockProxy; + rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock); + pFile->eFileLock = proxy->eFileLock; + }else{ + /* conchHeld < 0 is lockless */ + } + } + return rc; +} + +/* +** Close a file that uses proxy locks. +*/ +static int proxyClose(sqlite3_file *id) { + if( id ){ + unixFile *pFile = (unixFile*)id; + proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; + unixFile *lockProxy = pCtx->lockProxy; + unixFile *conchFile = pCtx->conchFile; + int rc = SQLITE_OK; + + if( lockProxy ){ + rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK); + if( rc ) return rc; + rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy); + if( rc ) return rc; + sqlite3_free(lockProxy); + pCtx->lockProxy = 0; + } + if( conchFile ){ + if( pCtx->conchHeld ){ + rc = proxyReleaseConch(pFile); + if( rc ) return rc; + } + rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile); + if( rc ) return rc; + sqlite3_free(conchFile); + } + sqlite3DbFree(0, pCtx->lockProxyPath); + sqlite3_free(pCtx->conchFilePath); + sqlite3DbFree(0, pCtx->dbPath); + /* restore the original locking context and pMethod then close it */ + pFile->lockingContext = pCtx->oldLockingContext; + pFile->pMethod = pCtx->pOldMethod; + sqlite3_free(pCtx); + return pFile->pMethod->xClose(id); + } + return SQLITE_OK; +} + + + +#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ +/* +** The proxy locking style is intended for use with AFP filesystems. +** And since AFP is only supported on MacOSX, the proxy locking is also +** restricted to MacOSX. +** +** +******************* End of the proxy lock implementation ********************** +******************************************************************************/ + +/* +** Initialize the operating system interface. +** +** This routine registers all VFS implementations for unix-like operating +** systems. This routine, and the sqlite3_os_end() routine that follows, +** should be the only routines in this file that are visible from other +** files. +** +** This routine is called once during SQLite initialization and by a +** single thread. The memory allocation and mutex subsystems have not +** necessarily been initialized when this routine is called, and so they +** should not be used. +*/ +int sqlite3_os_init(void){ + /* + ** The following macro defines an initializer for an sqlite3_vfs object. + ** The name of the VFS is NAME. The pAppData is a pointer to a pointer + ** to the "finder" function. (pAppData is a pointer to a pointer because + ** silly C90 rules prohibit a void* from being cast to a function pointer + ** and so we have to go through the intermediate pointer to avoid problems + ** when compiling with -pedantic-errors on GCC.) + ** + ** The FINDER parameter to this macro is the name of the pointer to the + ** finder-function. The finder-function returns a pointer to the + ** sqlite_io_methods object that implements the desired locking + ** behaviors. See the division above that contains the IOMETHODS + ** macro for addition information on finder-functions. + ** + ** Most finders simply return a pointer to a fixed sqlite3_io_methods + ** object. But the "autolockIoFinder" available on MacOSX does a little + ** more than that; it looks at the filesystem type that hosts the + ** database file and tries to choose an locking method appropriate for + ** that filesystem time. + */ + #define UNIXVFS(VFSNAME, FINDER) { \ + 3, /* iVersion */ \ + sizeof(unixFile), /* szOsFile */ \ + MAX_PATHNAME, /* mxPathname */ \ + 0, /* pNext */ \ + VFSNAME, /* zName */ \ + (void*)&FINDER, /* pAppData */ \ + unixOpen, /* xOpen */ \ + unixDelete, /* xDelete */ \ + unixAccess, /* xAccess */ \ + unixFullPathname, /* xFullPathname */ \ + unixDlOpen, /* xDlOpen */ \ + unixDlError, /* xDlError */ \ + unixDlSym, /* xDlSym */ \ + unixDlClose, /* xDlClose */ \ + unixRandomness, /* xRandomness */ \ + unixSleep, /* xSleep */ \ + unixCurrentTime, /* xCurrentTime */ \ + unixGetLastError, /* xGetLastError */ \ + unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \ + unixSetSystemCall, /* xSetSystemCall */ \ + unixGetSystemCall, /* xGetSystemCall */ \ + unixNextSystemCall, /* xNextSystemCall */ \ + } + + /* + ** All default VFSes for unix are contained in the following array. + ** + ** Note that the sqlite3_vfs.pNext field of the VFS object is modified + ** by the SQLite core when the VFS is registered. So the following + ** array cannot be const. + */ + static sqlite3_vfs aVfs[] = { +#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__)) + UNIXVFS("unix", autolockIoFinder ), +#else + UNIXVFS("unix", posixIoFinder ), +#endif + UNIXVFS("unix-none", nolockIoFinder ), + UNIXVFS("unix-dotfile", dotlockIoFinder ), + UNIXVFS("unix-excl", posixIoFinder ), +#if OS_VXWORKS + UNIXVFS("unix-namedsem", semIoFinder ), +#endif +#if SQLITE_ENABLE_LOCKING_STYLE + UNIXVFS("unix-posix", posixIoFinder ), +#if !OS_VXWORKS + UNIXVFS("unix-flock", flockIoFinder ), +#endif +#endif +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) + UNIXVFS("unix-afp", afpIoFinder ), + UNIXVFS("unix-nfs", nfsIoFinder ), + UNIXVFS("unix-proxy", proxyIoFinder ), +#endif + }; + unsigned int i; /* Loop counter */ + + /* Double-check that the aSyscall[] array has been constructed + ** correctly. See ticket [bb3a86e890c8e96ab] */ + assert( ArraySize(aSyscall)==24 ); + + /* Register all VFSes defined in the aVfs[] array */ + for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ + sqlite3_vfs_register(&aVfs[i], i==0); + } + return SQLITE_OK; +} + +/* +** Shutdown the operating system interface. +** +** Some operating systems might need to do some cleanup in this routine, +** to release dynamically allocated objects. But not on unix. +** This routine is a no-op for unix. +*/ +int sqlite3_os_end(void){ + return SQLITE_OK; +} + +#endif /* SQLITE_OS_UNIX */ diff --git a/components/external/SQLite-3.8.1/src/os_win.c b/components/external/SQLite-3.8.1/src/os_win.c new file mode 100644 index 0000000000000000000000000000000000000000..c6c567c00cd3aef66b8c75349e98074cce0d7576 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/os_win.c @@ -0,0 +1,5221 @@ +/* +** 2004 May 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code that is specific to Windows. +*/ +#include "sqliteInt.h" +#if SQLITE_OS_WIN /* This file is used for Windows only */ + +#ifdef __CYGWIN__ +# include +# include /* amalgamator: keep */ +#endif + +/* +** Include code that is common to all os_*.c files +*/ +#include "os_common.h" + +/* +** Compiling and using WAL mode requires several APIs that are only +** available in Windows platforms based on the NT kernel. +*/ +#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL) +# error "WAL mode requires support from the Windows NT kernel, compile\ + with SQLITE_OMIT_WAL." +#endif + +/* +** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions +** based on the sub-platform)? +*/ +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI) +# define SQLITE_WIN32_HAS_ANSI +#endif + +/* +** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions +** based on the sub-platform)? +*/ +#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \ + !defined(SQLITE_WIN32_NO_WIDE) +# define SQLITE_WIN32_HAS_WIDE +#endif + +/* +** Make sure at least one set of Win32 APIs is available. +*/ +#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE) +# error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\ + must be defined." +#endif + +/* +** Maximum pathname length (in chars) for Win32. This should normally be +** MAX_PATH. +*/ +#ifndef SQLITE_WIN32_MAX_PATH_CHARS +# define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH) +#endif + +/* +** Maximum pathname length (in chars) for WinNT. This should normally be +** 32767. +*/ +#ifndef SQLITE_WINNT_MAX_PATH_CHARS +# define SQLITE_WINNT_MAX_PATH_CHARS (32767) +#endif + +/* +** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in +** characters, so we allocate 3 bytes per character assuming worst-case of +** 4-bytes-per-character for UTF8. +*/ +#ifndef SQLITE_WIN32_MAX_PATH_BYTES +# define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4) +#endif + +/* +** Maximum pathname length (in bytes) for WinNT. This should normally be +** 32767 * sizeof(WCHAR). +*/ +#ifndef SQLITE_WINNT_MAX_PATH_BYTES +# define SQLITE_WINNT_MAX_PATH_BYTES \ + (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS) +#endif + +/* +** Maximum error message length (in chars) for WinRT. +*/ +#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS +# define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024) +#endif + +/* +** Returns non-zero if the character should be treated as a directory +** separator. +*/ +#ifndef winIsDirSep +# define winIsDirSep(a) (((a) == '/') || ((a) == '\\')) +#endif + +/* +** This macro is used when a local variable is set to a value that is +** [sometimes] not used by the code (e.g. via conditional compilation). +*/ +#ifndef UNUSED_VARIABLE_VALUE +# define UNUSED_VARIABLE_VALUE(x) (void)(x) +#endif + +/* +** Returns the string that should be used as the directory separator. +*/ +#ifndef winGetDirDep +# ifdef __CYGWIN__ +# define winGetDirDep() "/" +# else +# define winGetDirDep() "\\" +# endif +#endif + +/* +** Do we need to manually define the Win32 file mapping APIs for use with WAL +** mode (e.g. these APIs are available in the Windows CE SDK; however, they +** are not present in the header file)? +*/ +#if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) +/* +** Two of the file mapping APIs are different under WinRT. Figure out which +** set we need. +*/ +#if SQLITE_OS_WINRT +WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \ + LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR); + +WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T); +#else +#if defined(SQLITE_WIN32_HAS_ANSI) +WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \ + DWORD, DWORD, DWORD, LPCSTR); +#endif /* defined(SQLITE_WIN32_HAS_ANSI) */ + +#if defined(SQLITE_WIN32_HAS_WIDE) +WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \ + DWORD, DWORD, DWORD, LPCWSTR); +#endif /* defined(SQLITE_WIN32_HAS_WIDE) */ + +WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T); +#endif /* SQLITE_OS_WINRT */ + +/* +** This file mapping API is common to both Win32 and WinRT. +*/ +WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID); +#endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */ + +/* +** Some Microsoft compilers lack this definition. +*/ +#ifndef INVALID_FILE_ATTRIBUTES +# define INVALID_FILE_ATTRIBUTES ((DWORD)-1) +#endif + +#ifndef FILE_FLAG_MASK +# define FILE_FLAG_MASK (0xFF3C0000) +#endif + +#ifndef FILE_ATTRIBUTE_MASK +# define FILE_ATTRIBUTE_MASK (0x0003FFF7) +#endif + +#ifndef SQLITE_OMIT_WAL +/* Forward references to structures used for WAL */ +typedef struct winShm winShm; /* A connection to shared-memory */ +typedef struct winShmNode winShmNode; /* A region of shared-memory */ +#endif + +/* +** WinCE lacks native support for file locking so we have to fake it +** with some code of our own. +*/ +#if SQLITE_OS_WINCE +typedef struct winceLock { + int nReaders; /* Number of reader locks obtained */ + BOOL bPending; /* Indicates a pending lock has been obtained */ + BOOL bReserved; /* Indicates a reserved lock has been obtained */ + BOOL bExclusive; /* Indicates an exclusive lock has been obtained */ +} winceLock; +#endif + +/* +** The winFile structure is a subclass of sqlite3_file* specific to the win32 +** portability layer. +*/ +typedef struct winFile winFile; +struct winFile { + const sqlite3_io_methods *pMethod; /*** Must be first ***/ + sqlite3_vfs *pVfs; /* The VFS used to open this file */ + HANDLE h; /* Handle for accessing the file */ + u8 locktype; /* Type of lock currently held on this file */ + short sharedLockByte; /* Randomly chosen byte used as a shared lock */ + u8 ctrlFlags; /* Flags. See WINFILE_* below */ + DWORD lastErrno; /* The Windows errno from the last I/O error */ +#ifndef SQLITE_OMIT_WAL + winShm *pShm; /* Instance of shared memory on this file */ +#endif + const char *zPath; /* Full pathname of this file */ + int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */ +#if SQLITE_OS_WINCE + LPWSTR zDeleteOnClose; /* Name of file to delete when closing */ + HANDLE hMutex; /* Mutex used to control access to shared lock */ + HANDLE hShared; /* Shared memory segment used for locking */ + winceLock local; /* Locks obtained by this instance of winFile */ + winceLock *shared; /* Global shared lock memory for the file */ +#endif +#if SQLITE_MAX_MMAP_SIZE>0 + int nFetchOut; /* Number of outstanding xFetch references */ + HANDLE hMap; /* Handle for accessing memory mapping */ + void *pMapRegion; /* Area memory mapped */ + sqlite3_int64 mmapSize; /* Usable size of mapped region */ + sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */ + sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ +#endif +}; + +/* +** Allowed values for winFile.ctrlFlags +*/ +#define WINFILE_RDONLY 0x02 /* Connection is read only */ +#define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ +#define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ + +/* + * The size of the buffer used by sqlite3_win32_write_debug(). + */ +#ifndef SQLITE_WIN32_DBG_BUF_SIZE +# define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD))) +#endif + +/* + * The value used with sqlite3_win32_set_directory() to specify that + * the data directory should be changed. + */ +#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE +# define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1) +#endif + +/* + * The value used with sqlite3_win32_set_directory() to specify that + * the temporary directory should be changed. + */ +#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE +# define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2) +#endif + +/* + * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the + * various Win32 API heap functions instead of our own. + */ +#ifdef SQLITE_WIN32_MALLOC + +/* + * If this is non-zero, an isolated heap will be created by the native Win32 + * allocator subsystem; otherwise, the default process heap will be used. This + * setting has no effect when compiling for WinRT. By default, this is enabled + * and an isolated heap will be created to store all allocated data. + * + ****************************************************************************** + * WARNING: It is important to note that when this setting is non-zero and the + * winMemShutdown function is called (e.g. by the sqlite3_shutdown + * function), all data that was allocated using the isolated heap will + * be freed immediately and any attempt to access any of that freed + * data will almost certainly result in an immediate access violation. + ****************************************************************************** + */ +#ifndef SQLITE_WIN32_HEAP_CREATE +# define SQLITE_WIN32_HEAP_CREATE (TRUE) +#endif + +/* + * The initial size of the Win32-specific heap. This value may be zero. + */ +#ifndef SQLITE_WIN32_HEAP_INIT_SIZE +# define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \ + (SQLITE_DEFAULT_PAGE_SIZE) + 4194304) +#endif + +/* + * The maximum size of the Win32-specific heap. This value may be zero. + */ +#ifndef SQLITE_WIN32_HEAP_MAX_SIZE +# define SQLITE_WIN32_HEAP_MAX_SIZE (0) +#endif + +/* + * The extra flags to use in calls to the Win32 heap APIs. This value may be + * zero for the default behavior. + */ +#ifndef SQLITE_WIN32_HEAP_FLAGS +# define SQLITE_WIN32_HEAP_FLAGS (0) +#endif + + +/* +** The winMemData structure stores information required by the Win32-specific +** sqlite3_mem_methods implementation. +*/ +typedef struct winMemData winMemData; +struct winMemData { +#ifndef NDEBUG + u32 magic; /* Magic number to detect structure corruption. */ +#endif + HANDLE hHeap; /* The handle to our heap. */ + BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */ +}; + +#ifndef NDEBUG +#define WINMEM_MAGIC 0x42b2830b +#endif + +static struct winMemData win_mem_data = { +#ifndef NDEBUG + WINMEM_MAGIC, +#endif + NULL, FALSE +}; + +#ifndef NDEBUG +#define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC ) +#else +#define winMemAssertMagic() +#endif + +#define winMemGetHeap() win_mem_data.hHeap + +static void *winMemMalloc(int nBytes); +static void winMemFree(void *pPrior); +static void *winMemRealloc(void *pPrior, int nBytes); +static int winMemSize(void *p); +static int winMemRoundup(int n); +static int winMemInit(void *pAppData); +static void winMemShutdown(void *pAppData); + +const sqlite3_mem_methods *sqlite3MemGetWin32(void); +#endif /* SQLITE_WIN32_MALLOC */ + +/* +** The following variable is (normally) set once and never changes +** thereafter. It records whether the operating system is Win9x +** or WinNT. +** +** 0: Operating system unknown. +** 1: Operating system is Win9x. +** 2: Operating system is WinNT. +** +** In order to facilitate testing on a WinNT system, the test fixture +** can manually set this value to 1 to emulate Win98 behavior. +*/ +#ifdef SQLITE_TEST +int sqlite3_os_type = 0; +#elif !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ + defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_HAS_WIDE) +static int sqlite3_os_type = 0; +#endif + +#ifndef SYSCALL +# define SYSCALL sqlite3_syscall_ptr +#endif + +/* +** This function is not available on Windows CE or WinRT. + */ + +#if SQLITE_OS_WINCE || SQLITE_OS_WINRT +# define osAreFileApisANSI() 1 +#endif + +/* +** Many system calls are accessed through pointer-to-functions so that +** they may be overridden at runtime to facilitate fault injection during +** testing and sandboxing. The following array holds the names and pointers +** to all overrideable system calls. +*/ +static struct win_syscall { + const char *zName; /* Name of the system call */ + sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ + sqlite3_syscall_ptr pDefault; /* Default value */ +} aSyscall[] = { +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT + { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 }, +#else + { "AreFileApisANSI", (SYSCALL)0, 0 }, +#endif + +#ifndef osAreFileApisANSI +#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent) +#endif + +#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) + { "CharLowerW", (SYSCALL)CharLowerW, 0 }, +#else + { "CharLowerW", (SYSCALL)0, 0 }, +#endif + +#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent) + +#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) + { "CharUpperW", (SYSCALL)CharUpperW, 0 }, +#else + { "CharUpperW", (SYSCALL)0, 0 }, +#endif + +#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent) + + { "CloseHandle", (SYSCALL)CloseHandle, 0 }, + +#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent) + +#if defined(SQLITE_WIN32_HAS_ANSI) + { "CreateFileA", (SYSCALL)CreateFileA, 0 }, +#else + { "CreateFileA", (SYSCALL)0, 0 }, +#endif + +#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \ + LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent) + +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) + { "CreateFileW", (SYSCALL)CreateFileW, 0 }, +#else + { "CreateFileW", (SYSCALL)0, 0 }, +#endif + +#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \ + LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent) + +#if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \ + !defined(SQLITE_OMIT_WAL)) + { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 }, +#else + { "CreateFileMappingA", (SYSCALL)0, 0 }, +#endif + +#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ + DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent) + +#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ + !defined(SQLITE_OMIT_WAL)) + { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 }, +#else + { "CreateFileMappingW", (SYSCALL)0, 0 }, +#endif + +#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ + DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent) + +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) + { "CreateMutexW", (SYSCALL)CreateMutexW, 0 }, +#else + { "CreateMutexW", (SYSCALL)0, 0 }, +#endif + +#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \ + LPCWSTR))aSyscall[8].pCurrent) + +#if defined(SQLITE_WIN32_HAS_ANSI) + { "DeleteFileA", (SYSCALL)DeleteFileA, 0 }, +#else + { "DeleteFileA", (SYSCALL)0, 0 }, +#endif + +#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent) + +#if defined(SQLITE_WIN32_HAS_WIDE) + { "DeleteFileW", (SYSCALL)DeleteFileW, 0 }, +#else + { "DeleteFileW", (SYSCALL)0, 0 }, +#endif + +#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent) + +#if SQLITE_OS_WINCE + { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 }, +#else + { "FileTimeToLocalFileTime", (SYSCALL)0, 0 }, +#endif + +#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \ + LPFILETIME))aSyscall[11].pCurrent) + +#if SQLITE_OS_WINCE + { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 }, +#else + { "FileTimeToSystemTime", (SYSCALL)0, 0 }, +#endif + +#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \ + LPSYSTEMTIME))aSyscall[12].pCurrent) + + { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 }, + +#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent) + +#if defined(SQLITE_WIN32_HAS_ANSI) + { "FormatMessageA", (SYSCALL)FormatMessageA, 0 }, +#else + { "FormatMessageA", (SYSCALL)0, 0 }, +#endif + +#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \ + DWORD,va_list*))aSyscall[14].pCurrent) + +#if defined(SQLITE_WIN32_HAS_WIDE) + { "FormatMessageW", (SYSCALL)FormatMessageW, 0 }, +#else + { "FormatMessageW", (SYSCALL)0, 0 }, +#endif + +#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \ + DWORD,va_list*))aSyscall[15].pCurrent) + +#if !defined(SQLITE_OMIT_LOAD_EXTENSION) + { "FreeLibrary", (SYSCALL)FreeLibrary, 0 }, +#else + { "FreeLibrary", (SYSCALL)0, 0 }, +#endif + +#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent) + + { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 }, + +#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent) + +#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) + { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 }, +#else + { "GetDiskFreeSpaceA", (SYSCALL)0, 0 }, +#endif + +#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \ + LPDWORD))aSyscall[18].pCurrent) + +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) + { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 }, +#else + { "GetDiskFreeSpaceW", (SYSCALL)0, 0 }, +#endif + +#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \ + LPDWORD))aSyscall[19].pCurrent) + +#if defined(SQLITE_WIN32_HAS_ANSI) + { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 }, +#else + { "GetFileAttributesA", (SYSCALL)0, 0 }, +#endif + +#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent) + +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) + { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 }, +#else + { "GetFileAttributesW", (SYSCALL)0, 0 }, +#endif + +#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent) + +#if defined(SQLITE_WIN32_HAS_WIDE) + { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 }, +#else + { "GetFileAttributesExW", (SYSCALL)0, 0 }, +#endif + +#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \ + LPVOID))aSyscall[22].pCurrent) + +#if !SQLITE_OS_WINRT + { "GetFileSize", (SYSCALL)GetFileSize, 0 }, +#else + { "GetFileSize", (SYSCALL)0, 0 }, +#endif + +#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent) + +#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) + { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 }, +#else + { "GetFullPathNameA", (SYSCALL)0, 0 }, +#endif + +#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \ + LPSTR*))aSyscall[24].pCurrent) + +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) + { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 }, +#else + { "GetFullPathNameW", (SYSCALL)0, 0 }, +#endif + +#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \ + LPWSTR*))aSyscall[25].pCurrent) + + { "GetLastError", (SYSCALL)GetLastError, 0 }, + +#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent) + +#if !defined(SQLITE_OMIT_LOAD_EXTENSION) +#if SQLITE_OS_WINCE + /* The GetProcAddressA() routine is only available on Windows CE. */ + { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 }, +#else + /* All other Windows platforms expect GetProcAddress() to take + ** an ANSI string regardless of the _UNICODE setting */ + { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 }, +#endif +#else + { "GetProcAddressA", (SYSCALL)0, 0 }, +#endif + +#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \ + LPCSTR))aSyscall[27].pCurrent) + +#if !SQLITE_OS_WINRT + { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 }, +#else + { "GetSystemInfo", (SYSCALL)0, 0 }, +#endif + +#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent) + + { "GetSystemTime", (SYSCALL)GetSystemTime, 0 }, + +#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent) + +#if !SQLITE_OS_WINCE + { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 }, +#else + { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 }, +#endif + +#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \ + LPFILETIME))aSyscall[30].pCurrent) + +#if defined(SQLITE_WIN32_HAS_ANSI) + { "GetTempPathA", (SYSCALL)GetTempPathA, 0 }, +#else + { "GetTempPathA", (SYSCALL)0, 0 }, +#endif + +#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent) + +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) + { "GetTempPathW", (SYSCALL)GetTempPathW, 0 }, +#else + { "GetTempPathW", (SYSCALL)0, 0 }, +#endif + +#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent) + +#if !SQLITE_OS_WINRT + { "GetTickCount", (SYSCALL)GetTickCount, 0 }, +#else + { "GetTickCount", (SYSCALL)0, 0 }, +#endif + +#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent) + +#if defined(SQLITE_WIN32_HAS_ANSI) + { "GetVersionExA", (SYSCALL)GetVersionExA, 0 }, +#else + { "GetVersionExA", (SYSCALL)0, 0 }, +#endif + +#define osGetVersionExA ((BOOL(WINAPI*)( \ + LPOSVERSIONINFOA))aSyscall[34].pCurrent) + +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) + { "GetVersionExW", (SYSCALL)GetVersionExW, 0 }, +#else + { "GetVersionExW", (SYSCALL)0, 0 }, +#endif + +#define osGetVersionExW ((BOOL(WINAPI*)( \ + LPOSVERSIONINFOW))aSyscall[35].pCurrent) + + { "HeapAlloc", (SYSCALL)HeapAlloc, 0 }, + +#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \ + SIZE_T))aSyscall[36].pCurrent) + +#if !SQLITE_OS_WINRT + { "HeapCreate", (SYSCALL)HeapCreate, 0 }, +#else + { "HeapCreate", (SYSCALL)0, 0 }, +#endif + +#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \ + SIZE_T))aSyscall[37].pCurrent) + +#if !SQLITE_OS_WINRT + { "HeapDestroy", (SYSCALL)HeapDestroy, 0 }, +#else + { "HeapDestroy", (SYSCALL)0, 0 }, +#endif + +#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent) + + { "HeapFree", (SYSCALL)HeapFree, 0 }, + +#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent) + + { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 }, + +#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \ + SIZE_T))aSyscall[40].pCurrent) + + { "HeapSize", (SYSCALL)HeapSize, 0 }, + +#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \ + LPCVOID))aSyscall[41].pCurrent) + +#if !SQLITE_OS_WINRT + { "HeapValidate", (SYSCALL)HeapValidate, 0 }, +#else + { "HeapValidate", (SYSCALL)0, 0 }, +#endif + +#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \ + LPCVOID))aSyscall[42].pCurrent) + +#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION) + { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 }, +#else + { "LoadLibraryA", (SYSCALL)0, 0 }, +#endif + +#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[43].pCurrent) + +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ + !defined(SQLITE_OMIT_LOAD_EXTENSION) + { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 }, +#else + { "LoadLibraryW", (SYSCALL)0, 0 }, +#endif + +#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[44].pCurrent) + +#if !SQLITE_OS_WINRT + { "LocalFree", (SYSCALL)LocalFree, 0 }, +#else + { "LocalFree", (SYSCALL)0, 0 }, +#endif + +#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[45].pCurrent) + +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT + { "LockFile", (SYSCALL)LockFile, 0 }, +#else + { "LockFile", (SYSCALL)0, 0 }, +#endif + +#ifndef osLockFile +#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ + DWORD))aSyscall[46].pCurrent) +#endif + +#if !SQLITE_OS_WINCE + { "LockFileEx", (SYSCALL)LockFileEx, 0 }, +#else + { "LockFileEx", (SYSCALL)0, 0 }, +#endif + +#ifndef osLockFileEx +#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \ + LPOVERLAPPED))aSyscall[47].pCurrent) +#endif + +#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)) + { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 }, +#else + { "MapViewOfFile", (SYSCALL)0, 0 }, +#endif + +#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ + SIZE_T))aSyscall[48].pCurrent) + + { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 }, + +#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \ + int))aSyscall[49].pCurrent) + + { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 }, + +#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \ + LARGE_INTEGER*))aSyscall[50].pCurrent) + + { "ReadFile", (SYSCALL)ReadFile, 0 }, + +#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \ + LPOVERLAPPED))aSyscall[51].pCurrent) + + { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 }, + +#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[52].pCurrent) + +#if !SQLITE_OS_WINRT + { "SetFilePointer", (SYSCALL)SetFilePointer, 0 }, +#else + { "SetFilePointer", (SYSCALL)0, 0 }, +#endif + +#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \ + DWORD))aSyscall[53].pCurrent) + +#if !SQLITE_OS_WINRT + { "Sleep", (SYSCALL)Sleep, 0 }, +#else + { "Sleep", (SYSCALL)0, 0 }, +#endif + +#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[54].pCurrent) + + { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 }, + +#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \ + LPFILETIME))aSyscall[55].pCurrent) + +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT + { "UnlockFile", (SYSCALL)UnlockFile, 0 }, +#else + { "UnlockFile", (SYSCALL)0, 0 }, +#endif + +#ifndef osUnlockFile +#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ + DWORD))aSyscall[56].pCurrent) +#endif + +#if !SQLITE_OS_WINCE + { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 }, +#else + { "UnlockFileEx", (SYSCALL)0, 0 }, +#endif + +#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ + LPOVERLAPPED))aSyscall[57].pCurrent) + +#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) + { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 }, +#else + { "UnmapViewOfFile", (SYSCALL)0, 0 }, +#endif + +#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[58].pCurrent) + + { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 }, + +#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \ + LPCSTR,LPBOOL))aSyscall[59].pCurrent) + + { "WriteFile", (SYSCALL)WriteFile, 0 }, + +#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \ + LPOVERLAPPED))aSyscall[60].pCurrent) + +#if SQLITE_OS_WINRT + { "CreateEventExW", (SYSCALL)CreateEventExW, 0 }, +#else + { "CreateEventExW", (SYSCALL)0, 0 }, +#endif + +#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \ + DWORD,DWORD))aSyscall[61].pCurrent) + +#if !SQLITE_OS_WINRT + { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 }, +#else + { "WaitForSingleObject", (SYSCALL)0, 0 }, +#endif + +#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \ + DWORD))aSyscall[62].pCurrent) + +#if SQLITE_OS_WINRT + { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 }, +#else + { "WaitForSingleObjectEx", (SYSCALL)0, 0 }, +#endif + +#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \ + BOOL))aSyscall[63].pCurrent) + +#if SQLITE_OS_WINRT + { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 }, +#else + { "SetFilePointerEx", (SYSCALL)0, 0 }, +#endif + +#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \ + PLARGE_INTEGER,DWORD))aSyscall[64].pCurrent) + +#if SQLITE_OS_WINRT + { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 }, +#else + { "GetFileInformationByHandleEx", (SYSCALL)0, 0 }, +#endif + +#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \ + FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[65].pCurrent) + +#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL) + { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 }, +#else + { "MapViewOfFileFromApp", (SYSCALL)0, 0 }, +#endif + +#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \ + SIZE_T))aSyscall[66].pCurrent) + +#if SQLITE_OS_WINRT + { "CreateFile2", (SYSCALL)CreateFile2, 0 }, +#else + { "CreateFile2", (SYSCALL)0, 0 }, +#endif + +#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \ + LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[67].pCurrent) + +#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION) + { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 }, +#else + { "LoadPackagedLibrary", (SYSCALL)0, 0 }, +#endif + +#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \ + DWORD))aSyscall[68].pCurrent) + +#if SQLITE_OS_WINRT + { "GetTickCount64", (SYSCALL)GetTickCount64, 0 }, +#else + { "GetTickCount64", (SYSCALL)0, 0 }, +#endif + +#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[69].pCurrent) + +#if SQLITE_OS_WINRT + { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 }, +#else + { "GetNativeSystemInfo", (SYSCALL)0, 0 }, +#endif + +#define osGetNativeSystemInfo ((VOID(WINAPI*)( \ + LPSYSTEM_INFO))aSyscall[70].pCurrent) + +#if defined(SQLITE_WIN32_HAS_ANSI) + { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 }, +#else + { "OutputDebugStringA", (SYSCALL)0, 0 }, +#endif + +#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[71].pCurrent) + +#if defined(SQLITE_WIN32_HAS_WIDE) + { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 }, +#else + { "OutputDebugStringW", (SYSCALL)0, 0 }, +#endif + +#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[72].pCurrent) + + { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 }, + +#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[73].pCurrent) + +#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL) + { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 }, +#else + { "CreateFileMappingFromApp", (SYSCALL)0, 0 }, +#endif + +#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \ + LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[74].pCurrent) + +}; /* End of the overrideable system calls */ + +/* +** This is the xSetSystemCall() method of sqlite3_vfs for all of the +** "win32" VFSes. Return SQLITE_OK opon successfully updating the +** system call pointer, or SQLITE_NOTFOUND if there is no configurable +** system call named zName. +*/ +static int winSetSystemCall( + sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ + const char *zName, /* Name of system call to override */ + sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ +){ + unsigned int i; + int rc = SQLITE_NOTFOUND; + + UNUSED_PARAMETER(pNotUsed); + if( zName==0 ){ + /* If no zName is given, restore all system calls to their default + ** settings and return NULL + */ + rc = SQLITE_OK; + for(i=0; i0 ){ + memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); + memcpy(zDbgBuf, zBuf, nMin); + osOutputDebugStringA(zDbgBuf); + }else{ + osOutputDebugStringA(zBuf); + } +#elif defined(SQLITE_WIN32_HAS_WIDE) + memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); + if ( osMultiByteToWideChar( + osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf, + nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){ + return; + } + osOutputDebugStringW((LPCWSTR)zDbgBuf); +#else + if( nMin>0 ){ + memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); + memcpy(zDbgBuf, zBuf, nMin); + fprintf(stderr, "%s", zDbgBuf); + }else{ + fprintf(stderr, "%s", zBuf); + } +#endif +} + +/* +** The following routine suspends the current thread for at least ms +** milliseconds. This is equivalent to the Win32 Sleep() interface. +*/ +#if SQLITE_OS_WINRT +static HANDLE sleepObj = NULL; +#endif + +void sqlite3_win32_sleep(DWORD milliseconds){ +#if SQLITE_OS_WINRT + if ( sleepObj==NULL ){ + sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET, + SYNCHRONIZE); + } + assert( sleepObj!=NULL ); + osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE); +#else + osSleep(milliseconds); +#endif +} + +/* +** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, +** or WinCE. Return false (zero) for Win95, Win98, or WinME. +** +** Here is an interesting observation: Win95, Win98, and WinME lack +** the LockFileEx() API. But we can still statically link against that +** API as long as we don't call it when running Win95/98/ME. A call to +** this routine is used to determine if the host is Win95/98/ME or +** WinNT/2K/XP so that we will know whether or not we can safely call +** the LockFileEx() API. +*/ +#ifndef NTDDI_WIN8 +# define NTDDI_WIN8 0x06020000 +#endif + +#if SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI) +# define osIsNT() (1) +#elif !defined(SQLITE_WIN32_HAS_WIDE) +# define osIsNT() (0) +#else + static int osIsNT(void){ + if( sqlite3_os_type==0 ){ +#if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8 + OSVERSIONINFOW sInfo; + sInfo.dwOSVersionInfoSize = sizeof(sInfo); + osGetVersionExW(&sInfo); +#else + OSVERSIONINFOA sInfo; + sInfo.dwOSVersionInfoSize = sizeof(sInfo); + osGetVersionExA(&sInfo); +#endif + sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1; + } + return sqlite3_os_type==2; + } +#endif + +#ifdef SQLITE_WIN32_MALLOC +/* +** Allocate nBytes of memory. +*/ +static void *winMemMalloc(int nBytes){ + HANDLE hHeap; + void *p; + + winMemAssertMagic(); + hHeap = winMemGetHeap(); + assert( hHeap!=0 ); + assert( hHeap!=INVALID_HANDLE_VALUE ); +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) + assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); +#endif + assert( nBytes>=0 ); + p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); + if( !p ){ + sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p", + nBytes, osGetLastError(), (void*)hHeap); + } + return p; +} + +/* +** Free memory. +*/ +static void winMemFree(void *pPrior){ + HANDLE hHeap; + + winMemAssertMagic(); + hHeap = winMemGetHeap(); + assert( hHeap!=0 ); + assert( hHeap!=INVALID_HANDLE_VALUE ); +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) + assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); +#endif + if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */ + if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){ + sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p", + pPrior, osGetLastError(), (void*)hHeap); + } +} + +/* +** Change the size of an existing memory allocation +*/ +static void *winMemRealloc(void *pPrior, int nBytes){ + HANDLE hHeap; + void *p; + + winMemAssertMagic(); + hHeap = winMemGetHeap(); + assert( hHeap!=0 ); + assert( hHeap!=INVALID_HANDLE_VALUE ); +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) + assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); +#endif + assert( nBytes>=0 ); + if( !pPrior ){ + p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); + }else{ + p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes); + } + if( !p ){ + sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p", + pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(), + (void*)hHeap); + } + return p; +} + +/* +** Return the size of an outstanding allocation, in bytes. +*/ +static int winMemSize(void *p){ + HANDLE hHeap; + SIZE_T n; + + winMemAssertMagic(); + hHeap = winMemGetHeap(); + assert( hHeap!=0 ); + assert( hHeap!=INVALID_HANDLE_VALUE ); +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) + assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); +#endif + if( !p ) return 0; + n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p); + if( n==(SIZE_T)-1 ){ + sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p", + p, osGetLastError(), (void*)hHeap); + return 0; + } + return (int)n; +} + +/* +** Round up a request size to the next valid allocation size. +*/ +static int winMemRoundup(int n){ + return n; +} + +/* +** Initialize this module. +*/ +static int winMemInit(void *pAppData){ + winMemData *pWinMemData = (winMemData *)pAppData; + + if( !pWinMemData ) return SQLITE_ERROR; + assert( pWinMemData->magic==WINMEM_MAGIC ); + +#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE + if( !pWinMemData->hHeap ){ + pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS, + SQLITE_WIN32_HEAP_INIT_SIZE, + SQLITE_WIN32_HEAP_MAX_SIZE); + if( !pWinMemData->hHeap ){ + sqlite3_log(SQLITE_NOMEM, + "failed to HeapCreate (%lu), flags=%u, initSize=%u, maxSize=%u", + osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, + SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE); + return SQLITE_NOMEM; + } + pWinMemData->bOwned = TRUE; + assert( pWinMemData->bOwned ); + } +#else + pWinMemData->hHeap = osGetProcessHeap(); + if( !pWinMemData->hHeap ){ + sqlite3_log(SQLITE_NOMEM, + "failed to GetProcessHeap (%lu)", osGetLastError()); + return SQLITE_NOMEM; + } + pWinMemData->bOwned = FALSE; + assert( !pWinMemData->bOwned ); +#endif + assert( pWinMemData->hHeap!=0 ); + assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) + assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); +#endif + return SQLITE_OK; +} + +/* +** Deinitialize this module. +*/ +static void winMemShutdown(void *pAppData){ + winMemData *pWinMemData = (winMemData *)pAppData; + + if( !pWinMemData ) return; + if( pWinMemData->hHeap ){ + assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) + assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); +#endif + if( pWinMemData->bOwned ){ + if( !osHeapDestroy(pWinMemData->hHeap) ){ + sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p", + osGetLastError(), (void*)pWinMemData->hHeap); + } + pWinMemData->bOwned = FALSE; + } + pWinMemData->hHeap = NULL; + } +} + +/* +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. The +** arguments specify the block of memory to manage. +** +** This routine is only called by sqlite3_config(), and therefore +** is not required to be threadsafe (it is not). +*/ +const sqlite3_mem_methods *sqlite3MemGetWin32(void){ + static const sqlite3_mem_methods winMemMethods = { + winMemMalloc, + winMemFree, + winMemRealloc, + winMemSize, + winMemRoundup, + winMemInit, + winMemShutdown, + &win_mem_data + }; + return &winMemMethods; +} + +void sqlite3MemSetDefault(void){ + sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32()); +} +#endif /* SQLITE_WIN32_MALLOC */ + +/* +** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). +** +** Space to hold the returned string is obtained from malloc. +*/ +static LPWSTR winUtf8ToUnicode(const char *zFilename){ + int nChar; + LPWSTR zWideFilename; + + nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0); + if( nChar==0 ){ + return 0; + } + zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) ); + if( zWideFilename==0 ){ + return 0; + } + nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, + nChar); + if( nChar==0 ){ + sqlite3_free(zWideFilename); + zWideFilename = 0; + } + return zWideFilename; +} + +/* +** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is +** obtained from sqlite3_malloc(). +*/ +static char *winUnicodeToUtf8(LPCWSTR zWideFilename){ + int nByte; + char *zFilename; + + nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0); + if( nByte == 0 ){ + return 0; + } + zFilename = sqlite3MallocZero( nByte ); + if( zFilename==0 ){ + return 0; + } + nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte, + 0, 0); + if( nByte == 0 ){ + sqlite3_free(zFilename); + zFilename = 0; + } + return zFilename; +} + +/* +** Convert an ANSI string to Microsoft Unicode, based on the +** current codepage settings for file apis. +** +** Space to hold the returned string is obtained +** from sqlite3_malloc. +*/ +static LPWSTR winMbcsToUnicode(const char *zFilename){ + int nByte; + LPWSTR zMbcsFilename; + int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP; + + nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL, + 0)*sizeof(WCHAR); + if( nByte==0 ){ + return 0; + } + zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) ); + if( zMbcsFilename==0 ){ + return 0; + } + nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, + nByte); + if( nByte==0 ){ + sqlite3_free(zMbcsFilename); + zMbcsFilename = 0; + } + return zMbcsFilename; +} + +/* +** Convert Microsoft Unicode to multi-byte character string, based on the +** user's ANSI codepage. +** +** Space to hold the returned string is obtained from +** sqlite3_malloc(). +*/ +static char *winUnicodeToMbcs(LPCWSTR zWideFilename){ + int nByte; + char *zFilename; + int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP; + + nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0); + if( nByte == 0 ){ + return 0; + } + zFilename = sqlite3MallocZero( nByte ); + if( zFilename==0 ){ + return 0; + } + nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, + nByte, 0, 0); + if( nByte == 0 ){ + sqlite3_free(zFilename); + zFilename = 0; + } + return zFilename; +} + +/* +** Convert multibyte character string to UTF-8. Space to hold the +** returned string is obtained from sqlite3_malloc(). +*/ +char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){ + char *zFilenameUtf8; + LPWSTR zTmpWide; + + zTmpWide = winMbcsToUnicode(zFilename); + if( zTmpWide==0 ){ + return 0; + } + zFilenameUtf8 = winUnicodeToUtf8(zTmpWide); + sqlite3_free(zTmpWide); + return zFilenameUtf8; +} + +/* +** Convert UTF-8 to multibyte character string. Space to hold the +** returned string is obtained from sqlite3_malloc(). +*/ +char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){ + char *zFilenameMbcs; + LPWSTR zTmpWide; + + zTmpWide = winUtf8ToUnicode(zFilename); + if( zTmpWide==0 ){ + return 0; + } + zFilenameMbcs = winUnicodeToMbcs(zTmpWide); + sqlite3_free(zTmpWide); + return zFilenameMbcs; +} + +/* +** This function sets the data directory or the temporary directory based on +** the provided arguments. The type argument must be 1 in order to set the +** data directory or 2 in order to set the temporary directory. The zValue +** argument is the name of the directory to use. The return value will be +** SQLITE_OK if successful. +*/ +int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){ + char **ppDirectory = 0; +#ifndef SQLITE_OMIT_AUTOINIT + int rc = sqlite3_initialize(); + if( rc ) return rc; +#endif + if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){ + ppDirectory = &sqlite3_data_directory; + }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){ + ppDirectory = &sqlite3_temp_directory; + } + assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE + || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE + ); + assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) ); + if( ppDirectory ){ + char *zValueUtf8 = 0; + if( zValue && zValue[0] ){ + zValueUtf8 = winUnicodeToUtf8(zValue); + if ( zValueUtf8==0 ){ + return SQLITE_NOMEM; + } + } + sqlite3_free(*ppDirectory); + *ppDirectory = zValueUtf8; + return SQLITE_OK; + } + return SQLITE_ERROR; +} + +/* +** The return value of winGetLastErrorMsg +** is zero if the error message fits in the buffer, or non-zero +** otherwise (if the message was truncated). +*/ +static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){ + /* FormatMessage returns 0 on failure. Otherwise it + ** returns the number of TCHARs written to the output + ** buffer, excluding the terminating null char. + */ + DWORD dwLen = 0; + char *zOut = 0; + + if( osIsNT() ){ +#if SQLITE_OS_WINRT + WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1]; + dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + lastErrno, + 0, + zTempWide, + SQLITE_WIN32_MAX_ERRMSG_CHARS, + 0); +#else + LPWSTR zTempWide = NULL; + dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + lastErrno, + 0, + (LPWSTR) &zTempWide, + 0, + 0); +#endif + if( dwLen > 0 ){ + /* allocate a buffer and convert to UTF8 */ + sqlite3BeginBenignMalloc(); + zOut = winUnicodeToUtf8(zTempWide); + sqlite3EndBenignMalloc(); +#if !SQLITE_OS_WINRT + /* free the system buffer allocated by FormatMessage */ + osLocalFree(zTempWide); +#endif + } + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + char *zTemp = NULL; + dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + lastErrno, + 0, + (LPSTR) &zTemp, + 0, + 0); + if( dwLen > 0 ){ + /* allocate a buffer and convert to UTF8 */ + sqlite3BeginBenignMalloc(); + zOut = sqlite3_win32_mbcs_to_utf8(zTemp); + sqlite3EndBenignMalloc(); + /* free the system buffer allocated by FormatMessage */ + osLocalFree(zTemp); + } + } +#endif + if( 0 == dwLen ){ + sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno); + }else{ + /* copy a maximum of nBuf chars to output buffer */ + sqlite3_snprintf(nBuf, zBuf, "%s", zOut); + /* free the UTF8 buffer */ + sqlite3_free(zOut); + } + return 0; +} + +/* +** +** This function - winLogErrorAtLine() - is only ever called via the macro +** winLogError(). +** +** This routine is invoked after an error occurs in an OS function. +** It logs a message using sqlite3_log() containing the current value of +** error code and, if possible, the human-readable equivalent from +** FormatMessage. +** +** The first argument passed to the macro should be the error code that +** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). +** The two subsequent arguments should be the name of the OS function that +** failed and the associated file-system path, if any. +*/ +#define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__) +static int winLogErrorAtLine( + int errcode, /* SQLite error code */ + DWORD lastErrno, /* Win32 last error */ + const char *zFunc, /* Name of OS function that failed */ + const char *zPath, /* File path associated with error */ + int iLine /* Source line number where error occurred */ +){ + char zMsg[500]; /* Human readable error text */ + int i; /* Loop counter */ + + zMsg[0] = 0; + winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg); + assert( errcode!=SQLITE_OK ); + if( zPath==0 ) zPath = ""; + for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){} + zMsg[i] = 0; + sqlite3_log(errcode, + "os_win.c:%d: (%lu) %s(%s) - %s", + iLine, lastErrno, zFunc, zPath, zMsg + ); + + return errcode; +} + +/* +** The number of times that a ReadFile(), WriteFile(), and DeleteFile() +** will be retried following a locking error - probably caused by +** antivirus software. Also the initial delay before the first retry. +** The delay increases linearly with each retry. +*/ +#ifndef SQLITE_WIN32_IOERR_RETRY +# define SQLITE_WIN32_IOERR_RETRY 10 +#endif +#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY +# define SQLITE_WIN32_IOERR_RETRY_DELAY 25 +#endif +static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY; +static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY; + +/* +** If a ReadFile() or WriteFile() error occurs, invoke this routine +** to see if it should be retried. Return TRUE to retry. Return FALSE +** to give up with an error. +*/ +static int winRetryIoerr(int *pnRetry, DWORD *pError){ + DWORD e = osGetLastError(); + if( *pnRetry>=winIoerrRetry ){ + if( pError ){ + *pError = e; + } + return 0; + } + if( e==ERROR_ACCESS_DENIED || + e==ERROR_LOCK_VIOLATION || + e==ERROR_SHARING_VIOLATION ){ + sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); + ++*pnRetry; + return 1; + } + if( pError ){ + *pError = e; + } + return 0; +} + +/* +** Log a I/O error retry episode. +*/ +static void winLogIoerr(int nRetry){ + if( nRetry ){ + sqlite3_log(SQLITE_IOERR, + "delayed %dms for lock/sharing conflict", + winIoerrRetryDelay*nRetry*(nRetry+1)/2 + ); + } +} + +#if SQLITE_OS_WINCE +/************************************************************************* +** This section contains code for WinCE only. +*/ +#if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API +/* +** The MSVC CRT on Windows CE may not have a localtime() function. So +** create a substitute. +*/ +#include +struct tm *__cdecl localtime(const time_t *t) +{ + static struct tm y; + FILETIME uTm, lTm; + SYSTEMTIME pTm; + sqlite3_int64 t64; + t64 = *t; + t64 = (t64 + 11644473600)*10000000; + uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF); + uTm.dwHighDateTime= (DWORD)(t64 >> 32); + osFileTimeToLocalFileTime(&uTm,&lTm); + osFileTimeToSystemTime(&lTm,&pTm); + y.tm_year = pTm.wYear - 1900; + y.tm_mon = pTm.wMonth - 1; + y.tm_wday = pTm.wDayOfWeek; + y.tm_mday = pTm.wDay; + y.tm_hour = pTm.wHour; + y.tm_min = pTm.wMinute; + y.tm_sec = pTm.wSecond; + return &y; +} +#endif + +#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)] + +/* +** Acquire a lock on the handle h +*/ +static void winceMutexAcquire(HANDLE h){ + DWORD dwErr; + do { + dwErr = osWaitForSingleObject(h, INFINITE); + } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED); +} +/* +** Release a lock acquired by winceMutexAcquire() +*/ +#define winceMutexRelease(h) ReleaseMutex(h) + +/* +** Create the mutex and shared memory used for locking in the file +** descriptor pFile +*/ +static int winceCreateLock(const char *zFilename, winFile *pFile){ + LPWSTR zTok; + LPWSTR zName; + DWORD lastErrno; + BOOL bLogged = FALSE; + BOOL bInit = TRUE; + + zName = winUtf8ToUnicode(zFilename); + if( zName==0 ){ + /* out of memory */ + return SQLITE_IOERR_NOMEM; + } + + /* Initialize the local lockdata */ + memset(&pFile->local, 0, sizeof(pFile->local)); + + /* Replace the backslashes from the filename and lowercase it + ** to derive a mutex name. */ + zTok = osCharLowerW(zName); + for (;*zTok;zTok++){ + if (*zTok == '\\') *zTok = '_'; + } + + /* Create/open the named mutex */ + pFile->hMutex = osCreateMutexW(NULL, FALSE, zName); + if (!pFile->hMutex){ + pFile->lastErrno = osGetLastError(); + sqlite3_free(zName); + return winLogError(SQLITE_IOERR, pFile->lastErrno, + "winceCreateLock1", zFilename); + } + + /* Acquire the mutex before continuing */ + winceMutexAcquire(pFile->hMutex); + + /* Since the names of named mutexes, semaphores, file mappings etc are + ** case-sensitive, take advantage of that by uppercasing the mutex name + ** and using that as the shared filemapping name. + */ + osCharUpperW(zName); + pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL, + PAGE_READWRITE, 0, sizeof(winceLock), + zName); + + /* Set a flag that indicates we're the first to create the memory so it + ** must be zero-initialized */ + lastErrno = osGetLastError(); + if (lastErrno == ERROR_ALREADY_EXISTS){ + bInit = FALSE; + } + + sqlite3_free(zName); + + /* If we succeeded in making the shared memory handle, map it. */ + if( pFile->hShared ){ + pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, + FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock)); + /* If mapping failed, close the shared memory handle and erase it */ + if( !pFile->shared ){ + pFile->lastErrno = osGetLastError(); + winLogError(SQLITE_IOERR, pFile->lastErrno, + "winceCreateLock2", zFilename); + bLogged = TRUE; + osCloseHandle(pFile->hShared); + pFile->hShared = NULL; + } + } + + /* If shared memory could not be created, then close the mutex and fail */ + if( pFile->hShared==NULL ){ + if( !bLogged ){ + pFile->lastErrno = lastErrno; + winLogError(SQLITE_IOERR, pFile->lastErrno, + "winceCreateLock3", zFilename); + bLogged = TRUE; + } + winceMutexRelease(pFile->hMutex); + osCloseHandle(pFile->hMutex); + pFile->hMutex = NULL; + return SQLITE_IOERR; + } + + /* Initialize the shared memory if we're supposed to */ + if( bInit ){ + memset(pFile->shared, 0, sizeof(winceLock)); + } + + winceMutexRelease(pFile->hMutex); + return SQLITE_OK; +} + +/* +** Destroy the part of winFile that deals with wince locks +*/ +static void winceDestroyLock(winFile *pFile){ + if (pFile->hMutex){ + /* Acquire the mutex */ + winceMutexAcquire(pFile->hMutex); + + /* The following blocks should probably assert in debug mode, but they + are to cleanup in case any locks remained open */ + if (pFile->local.nReaders){ + pFile->shared->nReaders --; + } + if (pFile->local.bReserved){ + pFile->shared->bReserved = FALSE; + } + if (pFile->local.bPending){ + pFile->shared->bPending = FALSE; + } + if (pFile->local.bExclusive){ + pFile->shared->bExclusive = FALSE; + } + + /* De-reference and close our copy of the shared memory handle */ + osUnmapViewOfFile(pFile->shared); + osCloseHandle(pFile->hShared); + + /* Done with the mutex */ + winceMutexRelease(pFile->hMutex); + osCloseHandle(pFile->hMutex); + pFile->hMutex = NULL; + } +} + +/* +** An implementation of the LockFile() API of Windows for CE +*/ +static BOOL winceLockFile( + LPHANDLE phFile, + DWORD dwFileOffsetLow, + DWORD dwFileOffsetHigh, + DWORD nNumberOfBytesToLockLow, + DWORD nNumberOfBytesToLockHigh +){ + winFile *pFile = HANDLE_TO_WINFILE(phFile); + BOOL bReturn = FALSE; + + UNUSED_PARAMETER(dwFileOffsetHigh); + UNUSED_PARAMETER(nNumberOfBytesToLockHigh); + + if (!pFile->hMutex) return TRUE; + winceMutexAcquire(pFile->hMutex); + + /* Wanting an exclusive lock? */ + if (dwFileOffsetLow == (DWORD)SHARED_FIRST + && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){ + if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){ + pFile->shared->bExclusive = TRUE; + pFile->local.bExclusive = TRUE; + bReturn = TRUE; + } + } + + /* Want a read-only lock? */ + else if (dwFileOffsetLow == (DWORD)SHARED_FIRST && + nNumberOfBytesToLockLow == 1){ + if (pFile->shared->bExclusive == 0){ + pFile->local.nReaders ++; + if (pFile->local.nReaders == 1){ + pFile->shared->nReaders ++; + } + bReturn = TRUE; + } + } + + /* Want a pending lock? */ + else if (dwFileOffsetLow == (DWORD)PENDING_BYTE + && nNumberOfBytesToLockLow == 1){ + /* If no pending lock has been acquired, then acquire it */ + if (pFile->shared->bPending == 0) { + pFile->shared->bPending = TRUE; + pFile->local.bPending = TRUE; + bReturn = TRUE; + } + } + + /* Want a reserved lock? */ + else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE + && nNumberOfBytesToLockLow == 1){ + if (pFile->shared->bReserved == 0) { + pFile->shared->bReserved = TRUE; + pFile->local.bReserved = TRUE; + bReturn = TRUE; + } + } + + winceMutexRelease(pFile->hMutex); + return bReturn; +} + +/* +** An implementation of the UnlockFile API of Windows for CE +*/ +static BOOL winceUnlockFile( + LPHANDLE phFile, + DWORD dwFileOffsetLow, + DWORD dwFileOffsetHigh, + DWORD nNumberOfBytesToUnlockLow, + DWORD nNumberOfBytesToUnlockHigh +){ + winFile *pFile = HANDLE_TO_WINFILE(phFile); + BOOL bReturn = FALSE; + + UNUSED_PARAMETER(dwFileOffsetHigh); + UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh); + + if (!pFile->hMutex) return TRUE; + winceMutexAcquire(pFile->hMutex); + + /* Releasing a reader lock or an exclusive lock */ + if (dwFileOffsetLow == (DWORD)SHARED_FIRST){ + /* Did we have an exclusive lock? */ + if (pFile->local.bExclusive){ + assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE); + pFile->local.bExclusive = FALSE; + pFile->shared->bExclusive = FALSE; + bReturn = TRUE; + } + + /* Did we just have a reader lock? */ + else if (pFile->local.nReaders){ + assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE + || nNumberOfBytesToUnlockLow == 1); + pFile->local.nReaders --; + if (pFile->local.nReaders == 0) + { + pFile->shared->nReaders --; + } + bReturn = TRUE; + } + } + + /* Releasing a pending lock */ + else if (dwFileOffsetLow == (DWORD)PENDING_BYTE + && nNumberOfBytesToUnlockLow == 1){ + if (pFile->local.bPending){ + pFile->local.bPending = FALSE; + pFile->shared->bPending = FALSE; + bReturn = TRUE; + } + } + /* Releasing a reserved lock */ + else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE + && nNumberOfBytesToUnlockLow == 1){ + if (pFile->local.bReserved) { + pFile->local.bReserved = FALSE; + pFile->shared->bReserved = FALSE; + bReturn = TRUE; + } + } + + winceMutexRelease(pFile->hMutex); + return bReturn; +} +/* +** End of the special code for wince +*****************************************************************************/ +#endif /* SQLITE_OS_WINCE */ + +/* +** Lock a file region. +*/ +static BOOL winLockFile( + LPHANDLE phFile, + DWORD flags, + DWORD offsetLow, + DWORD offsetHigh, + DWORD numBytesLow, + DWORD numBytesHigh +){ +#if SQLITE_OS_WINCE + /* + ** NOTE: Windows CE is handled differently here due its lack of the Win32 + ** API LockFile. + */ + return winceLockFile(phFile, offsetLow, offsetHigh, + numBytesLow, numBytesHigh); +#else + if( osIsNT() ){ + OVERLAPPED ovlp; + memset(&ovlp, 0, sizeof(OVERLAPPED)); + ovlp.Offset = offsetLow; + ovlp.OffsetHigh = offsetHigh; + return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp); + }else{ + return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow, + numBytesHigh); + } +#endif +} + +/* +** Unlock a file region. + */ +static BOOL winUnlockFile( + LPHANDLE phFile, + DWORD offsetLow, + DWORD offsetHigh, + DWORD numBytesLow, + DWORD numBytesHigh +){ +#if SQLITE_OS_WINCE + /* + ** NOTE: Windows CE is handled differently here due its lack of the Win32 + ** API UnlockFile. + */ + return winceUnlockFile(phFile, offsetLow, offsetHigh, + numBytesLow, numBytesHigh); +#else + if( osIsNT() ){ + OVERLAPPED ovlp; + memset(&ovlp, 0, sizeof(OVERLAPPED)); + ovlp.Offset = offsetLow; + ovlp.OffsetHigh = offsetHigh; + return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp); + }else{ + return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow, + numBytesHigh); + } +#endif +} + +/***************************************************************************** +** The next group of routines implement the I/O methods specified +** by the sqlite3_io_methods object. +******************************************************************************/ + +/* +** Some Microsoft compilers lack this definition. +*/ +#ifndef INVALID_SET_FILE_POINTER +# define INVALID_SET_FILE_POINTER ((DWORD)-1) +#endif + +/* +** Move the current position of the file handle passed as the first +** argument to offset iOffset within the file. If successful, return 0. +** Otherwise, set pFile->lastErrno and return non-zero. +*/ +static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){ +#if !SQLITE_OS_WINRT + LONG upperBits; /* Most sig. 32 bits of new offset */ + LONG lowerBits; /* Least sig. 32 bits of new offset */ + DWORD dwRet; /* Value returned by SetFilePointer() */ + DWORD lastErrno; /* Value returned by GetLastError() */ + + OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset)); + + upperBits = (LONG)((iOffset>>32) & 0x7fffffff); + lowerBits = (LONG)(iOffset & 0xffffffff); + + /* API oddity: If successful, SetFilePointer() returns a dword + ** containing the lower 32-bits of the new file-offset. Or, if it fails, + ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, + ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine + ** whether an error has actually occurred, it is also necessary to call + ** GetLastError(). + */ + dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN); + + if( (dwRet==INVALID_SET_FILE_POINTER + && ((lastErrno = osGetLastError())!=NO_ERROR)) ){ + pFile->lastErrno = lastErrno; + winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno, + "winSeekFile", pFile->zPath); + OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h)); + return 1; + } + + OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h)); + return 0; +#else + /* + ** Same as above, except that this implementation works for WinRT. + */ + + LARGE_INTEGER x; /* The new offset */ + BOOL bRet; /* Value returned by SetFilePointerEx() */ + + x.QuadPart = iOffset; + bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN); + + if(!bRet){ + pFile->lastErrno = osGetLastError(); + winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno, + "winSeekFile", pFile->zPath); + OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h)); + return 1; + } + + OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h)); + return 0; +#endif +} + +#if SQLITE_MAX_MMAP_SIZE>0 +/* Forward references to VFS helper methods used for memory mapped files */ +static int winMapfile(winFile*, sqlite3_int64); +static int winUnmapfile(winFile*); +#endif + +/* +** Close a file. +** +** It is reported that an attempt to close a handle might sometimes +** fail. This is a very unreasonable result, but Windows is notorious +** for being unreasonable so I do not doubt that it might happen. If +** the close fails, we pause for 100 milliseconds and try again. As +** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before +** giving up and returning an error. +*/ +#define MX_CLOSE_ATTEMPT 3 +static int winClose(sqlite3_file *id){ + int rc, cnt = 0; + winFile *pFile = (winFile*)id; + + assert( id!=0 ); +#ifndef SQLITE_OMIT_WAL + assert( pFile->pShm==0 ); +#endif + assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE ); + OSTRACE(("CLOSE file=%p\n", pFile->h)); + +#if SQLITE_MAX_MMAP_SIZE>0 + winUnmapfile(pFile); +#endif + + do{ + rc = osCloseHandle(pFile->h); + /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */ + }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) ); +#if SQLITE_OS_WINCE +#define WINCE_DELETION_ATTEMPTS 3 + winceDestroyLock(pFile); + if( pFile->zDeleteOnClose ){ + int cnt = 0; + while( + osDeleteFileW(pFile->zDeleteOnClose)==0 + && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff + && cnt++ < WINCE_DELETION_ATTEMPTS + ){ + sqlite3_win32_sleep(100); /* Wait a little before trying again */ + } + sqlite3_free(pFile->zDeleteOnClose); + } +#endif + if( rc ){ + pFile->h = NULL; + } + OpenCounter(-1); + OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed")); + return rc ? SQLITE_OK + : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(), + "winClose", pFile->zPath); +} + +/* +** Read data from a file into a buffer. Return SQLITE_OK if all +** bytes were read successfully and SQLITE_IOERR if anything goes +** wrong. +*/ +static int winRead( + sqlite3_file *id, /* File to read from */ + void *pBuf, /* Write content into this buffer */ + int amt, /* Number of bytes to read */ + sqlite3_int64 offset /* Begin reading at this offset */ +){ +#if !SQLITE_OS_WINCE + OVERLAPPED overlapped; /* The offset for ReadFile. */ +#endif + winFile *pFile = (winFile*)id; /* file handle */ + DWORD nRead; /* Number of bytes actually read from file */ + int nRetry = 0; /* Number of retrys */ + + assert( id!=0 ); + assert( amt>0 ); + assert( offset>=0 ); + SimulateIOError(return SQLITE_IOERR_READ); + OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n", + pFile->h, pBuf, amt, offset, pFile->locktype)); + +#if SQLITE_MAX_MMAP_SIZE>0 + /* Deal with as much of this read request as possible by transfering + ** data from the memory mapping using memcpy(). */ + if( offsetmmapSize ){ + if( offset+amt <= pFile->mmapSize ){ + memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); + OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + }else{ + int nCopy = (int)(pFile->mmapSize - offset); + memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); + pBuf = &((u8 *)pBuf)[nCopy]; + amt -= nCopy; + offset += nCopy; + } + } +#endif + +#if SQLITE_OS_WINCE + if( winSeekFile(pFile, offset) ){ + OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h)); + return SQLITE_FULL; + } + while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){ +#else + memset(&overlapped, 0, sizeof(OVERLAPPED)); + overlapped.Offset = (LONG)(offset & 0xffffffff); + overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); + while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) && + osGetLastError()!=ERROR_HANDLE_EOF ){ +#endif + DWORD lastErrno; + if( winRetryIoerr(&nRetry, &lastErrno) ) continue; + pFile->lastErrno = lastErrno; + OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h)); + return winLogError(SQLITE_IOERR_READ, pFile->lastErrno, + "winRead", pFile->zPath); + } + winLogIoerr(nRetry); + if( nRead<(DWORD)amt ){ + /* Unread parts of the buffer must be zero-filled */ + memset(&((char*)pBuf)[nRead], 0, amt-nRead); + OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h)); + return SQLITE_IOERR_SHORT_READ; + } + + OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; +} + +/* +** Write data from a buffer into a file. Return SQLITE_OK on success +** or some other error code on failure. +*/ +static int winWrite( + sqlite3_file *id, /* File to write into */ + const void *pBuf, /* The bytes to be written */ + int amt, /* Number of bytes to write */ + sqlite3_int64 offset /* Offset into the file to begin writing at */ +){ + int rc = 0; /* True if error has occurred, else false */ + winFile *pFile = (winFile*)id; /* File handle */ + int nRetry = 0; /* Number of retries */ + + assert( amt>0 ); + assert( pFile ); + SimulateIOError(return SQLITE_IOERR_WRITE); + SimulateDiskfullError(return SQLITE_FULL); + + OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n", + pFile->h, pBuf, amt, offset, pFile->locktype)); + +#if SQLITE_MAX_MMAP_SIZE>0 + /* Deal with as much of this write request as possible by transfering + ** data from the memory mapping using memcpy(). */ + if( offsetmmapSize ){ + if( offset+amt <= pFile->mmapSize ){ + memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); + OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + }else{ + int nCopy = (int)(pFile->mmapSize - offset); + memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); + pBuf = &((u8 *)pBuf)[nCopy]; + amt -= nCopy; + offset += nCopy; + } + } +#endif + +#if SQLITE_OS_WINCE + rc = winSeekFile(pFile, offset); + if( rc==0 ){ +#else + { +#endif +#if !SQLITE_OS_WINCE + OVERLAPPED overlapped; /* The offset for WriteFile. */ +#endif + u8 *aRem = (u8 *)pBuf; /* Data yet to be written */ + int nRem = amt; /* Number of bytes yet to be written */ + DWORD nWrite; /* Bytes written by each WriteFile() call */ + DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */ + +#if !SQLITE_OS_WINCE + memset(&overlapped, 0, sizeof(OVERLAPPED)); + overlapped.Offset = (LONG)(offset & 0xffffffff); + overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); +#endif + + while( nRem>0 ){ +#if SQLITE_OS_WINCE + if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){ +#else + if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){ +#endif + if( winRetryIoerr(&nRetry, &lastErrno) ) continue; + break; + } + assert( nWrite==0 || nWrite<=(DWORD)nRem ); + if( nWrite==0 || nWrite>(DWORD)nRem ){ + lastErrno = osGetLastError(); + break; + } +#if !SQLITE_OS_WINCE + offset += nWrite; + overlapped.Offset = (LONG)(offset & 0xffffffff); + overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); +#endif + aRem += nWrite; + nRem -= nWrite; + } + if( nRem>0 ){ + pFile->lastErrno = lastErrno; + rc = 1; + } + } + + if( rc ){ + if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ) + || ( pFile->lastErrno==ERROR_DISK_FULL )){ + OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h)); + return winLogError(SQLITE_FULL, pFile->lastErrno, + "winWrite1", pFile->zPath); + } + OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h)); + return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno, + "winWrite2", pFile->zPath); + }else{ + winLogIoerr(nRetry); + } + OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; +} + +/* +** Truncate an open file to a specified size +*/ +static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){ + winFile *pFile = (winFile*)id; /* File handle object */ + int rc = SQLITE_OK; /* Return code for this function */ + DWORD lastErrno; + + assert( pFile ); + SimulateIOError(return SQLITE_IOERR_TRUNCATE); + OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n", + pFile->h, nByte, pFile->locktype)); + + /* If the user has configured a chunk-size for this file, truncate the + ** file so that it consists of an integer number of chunks (i.e. the + ** actual file size after the operation may be larger than the requested + ** size). + */ + if( pFile->szChunk>0 ){ + nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; + } + + /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */ + if( winSeekFile(pFile, nByte) ){ + rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno, + "winTruncate1", pFile->zPath); + }else if( 0==osSetEndOfFile(pFile->h) && + ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){ + pFile->lastErrno = lastErrno; + rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno, + "winTruncate2", pFile->zPath); + } + +#if SQLITE_MAX_MMAP_SIZE>0 + /* If the file was truncated to a size smaller than the currently + ** mapped region, reduce the effective mapping size as well. SQLite will + ** use read() and write() to access data beyond this point from now on. + */ + if( pFile->pMapRegion && nBytemmapSize ){ + pFile->mmapSize = nByte; + } +#endif + + OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); + return rc; +} + +#ifdef SQLITE_TEST +/* +** Count the number of fullsyncs and normal syncs. This is used to test +** that syncs and fullsyncs are occuring at the right times. +*/ +int sqlite3_sync_count = 0; +int sqlite3_fullsync_count = 0; +#endif + +/* +** Make sure all writes to a particular file are committed to disk. +*/ +static int winSync(sqlite3_file *id, int flags){ +#ifndef SQLITE_NO_SYNC + /* + ** Used only when SQLITE_NO_SYNC is not defined. + */ + BOOL rc; +#endif +#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \ + (defined(SQLITE_TEST) && defined(SQLITE_DEBUG)) + /* + ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or + ** OSTRACE() macros. + */ + winFile *pFile = (winFile*)id; +#else + UNUSED_PARAMETER(id); +#endif + + assert( pFile ); + /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ + assert((flags&0x0F)==SQLITE_SYNC_NORMAL + || (flags&0x0F)==SQLITE_SYNC_FULL + ); + + /* Unix cannot, but some systems may return SQLITE_FULL from here. This + ** line is to test that doing so does not cause any problems. + */ + SimulateDiskfullError( return SQLITE_FULL ); + + OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n", + pFile->h, flags, pFile->locktype)); + +#ifndef SQLITE_TEST + UNUSED_PARAMETER(flags); +#else + if( (flags&0x0F)==SQLITE_SYNC_FULL ){ + sqlite3_fullsync_count++; + } + sqlite3_sync_count++; +#endif + + /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a + ** no-op + */ +#ifdef SQLITE_NO_SYNC + OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; +#else + rc = osFlushFileBuffers(pFile->h); + SimulateIOError( rc=FALSE ); + if( rc ){ + OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + }else{ + pFile->lastErrno = osGetLastError(); + OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h)); + return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno, + "winSync", pFile->zPath); + } +#endif +} + +/* +** Determine the current size of a file in bytes +*/ +static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ + winFile *pFile = (winFile*)id; + int rc = SQLITE_OK; + + assert( id!=0 ); + assert( pSize!=0 ); + SimulateIOError(return SQLITE_IOERR_FSTAT); + OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize)); + +#if SQLITE_OS_WINRT + { + FILE_STANDARD_INFO info; + if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo, + &info, sizeof(info)) ){ + *pSize = info.EndOfFile.QuadPart; + }else{ + pFile->lastErrno = osGetLastError(); + rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, + "winFileSize", pFile->zPath); + } + } +#else + { + DWORD upperBits; + DWORD lowerBits; + DWORD lastErrno; + + lowerBits = osGetFileSize(pFile->h, &upperBits); + *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; + if( (lowerBits == INVALID_FILE_SIZE) + && ((lastErrno = osGetLastError())!=NO_ERROR) ){ + pFile->lastErrno = lastErrno; + rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, + "winFileSize", pFile->zPath); + } + } +#endif + OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n", + pFile->h, pSize, *pSize, sqlite3ErrName(rc))); + return rc; +} + +/* +** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems. +*/ +#ifndef LOCKFILE_FAIL_IMMEDIATELY +# define LOCKFILE_FAIL_IMMEDIATELY 1 +#endif + +#ifndef LOCKFILE_EXCLUSIVE_LOCK +# define LOCKFILE_EXCLUSIVE_LOCK 2 +#endif + +/* +** Historically, SQLite has used both the LockFile and LockFileEx functions. +** When the LockFile function was used, it was always expected to fail +** immediately if the lock could not be obtained. Also, it always expected to +** obtain an exclusive lock. These flags are used with the LockFileEx function +** and reflect those expectations; therefore, they should not be changed. +*/ +#ifndef SQLITE_LOCKFILE_FLAGS +# define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \ + LOCKFILE_EXCLUSIVE_LOCK) +#endif + +/* +** Currently, SQLite never calls the LockFileEx function without wanting the +** call to fail immediately if the lock cannot be obtained. +*/ +#ifndef SQLITE_LOCKFILEEX_FLAGS +# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY) +#endif + +/* +** Acquire a reader lock. +** Different API routines are called depending on whether or not this +** is Win9x or WinNT. +*/ +static int winGetReadLock(winFile *pFile){ + int res; + OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); + if( osIsNT() ){ +#if SQLITE_OS_WINCE + /* + ** NOTE: Windows CE is handled differently here due its lack of the Win32 + ** API LockFileEx. + */ + res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0); +#else + res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0, + SHARED_SIZE, 0); +#endif + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + int lk; + sqlite3_randomness(sizeof(lk), &lk); + pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1)); + res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, + SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); + } +#endif + if( res == 0 ){ + pFile->lastErrno = osGetLastError(); + /* No need to log a failure to lock */ + } + OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res))); + return res; +} + +/* +** Undo a readlock +*/ +static int winUnlockReadLock(winFile *pFile){ + int res; + DWORD lastErrno; + OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); + if( osIsNT() ){ + res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); + } +#endif + if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){ + pFile->lastErrno = lastErrno; + winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno, + "winUnlockReadLock", pFile->zPath); + } + OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res))); + return res; +} + +/* +** Lock the file with the lock specified by parameter locktype - one +** of the following: +** +** (1) SHARED_LOCK +** (2) RESERVED_LOCK +** (3) PENDING_LOCK +** (4) EXCLUSIVE_LOCK +** +** Sometimes when requesting one lock state, additional lock states +** are inserted in between. The locking might fail on one of the later +** transitions leaving the lock state different from what it started but +** still short of its goal. The following chart shows the allowed +** transitions and the inserted intermediate states: +** +** UNLOCKED -> SHARED +** SHARED -> RESERVED +** SHARED -> (PENDING) -> EXCLUSIVE +** RESERVED -> (PENDING) -> EXCLUSIVE +** PENDING -> EXCLUSIVE +** +** This routine will only increase a lock. The winUnlock() routine +** erases all locks at once and returns us immediately to locking level 0. +** It is not possible to lower the locking level one step at a time. You +** must go straight to locking level 0. +*/ +static int winLock(sqlite3_file *id, int locktype){ + int rc = SQLITE_OK; /* Return code from subroutines */ + int res = 1; /* Result of a Windows lock call */ + int newLocktype; /* Set pFile->locktype to this value before exiting */ + int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */ + winFile *pFile = (winFile*)id; + DWORD lastErrno = NO_ERROR; + + assert( id!=0 ); + OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n", + pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); + + /* If there is already a lock of this type or more restrictive on the + ** OsFile, do nothing. Don't use the end_lock: exit path, as + ** sqlite3OsEnterMutex() hasn't been called yet. + */ + if( pFile->locktype>=locktype ){ + OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + } + + /* Make sure the locking sequence is correct + */ + assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK ); + assert( locktype!=PENDING_LOCK ); + assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); + + /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or + ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of + ** the PENDING_LOCK byte is temporary. + */ + newLocktype = pFile->locktype; + if( (pFile->locktype==NO_LOCK) + || ( (locktype==EXCLUSIVE_LOCK) + && (pFile->locktype==RESERVED_LOCK)) + ){ + int cnt = 3; + while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, + PENDING_BYTE, 0, 1, 0))==0 ){ + /* Try 3 times to get the pending lock. This is needed to work + ** around problems caused by indexing and/or anti-virus software on + ** Windows systems. + ** If you are using this code as a model for alternative VFSes, do not + ** copy this retry logic. It is a hack intended for Windows only. + */ + OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n", + pFile->h, cnt, sqlite3ErrName(res))); + if( cnt ) sqlite3_win32_sleep(1); + } + gotPendingLock = res; + if( !res ){ + lastErrno = osGetLastError(); + } + } + + /* Acquire a shared lock + */ + if( locktype==SHARED_LOCK && res ){ + assert( pFile->locktype==NO_LOCK ); + res = winGetReadLock(pFile); + if( res ){ + newLocktype = SHARED_LOCK; + }else{ + lastErrno = osGetLastError(); + } + } + + /* Acquire a RESERVED lock + */ + if( locktype==RESERVED_LOCK && res ){ + assert( pFile->locktype==SHARED_LOCK ); + res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0); + if( res ){ + newLocktype = RESERVED_LOCK; + }else{ + lastErrno = osGetLastError(); + } + } + + /* Acquire a PENDING lock + */ + if( locktype==EXCLUSIVE_LOCK && res ){ + newLocktype = PENDING_LOCK; + gotPendingLock = 0; + } + + /* Acquire an EXCLUSIVE lock + */ + if( locktype==EXCLUSIVE_LOCK && res ){ + assert( pFile->locktype>=SHARED_LOCK ); + res = winUnlockReadLock(pFile); + res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0, + SHARED_SIZE, 0); + if( res ){ + newLocktype = EXCLUSIVE_LOCK; + }else{ + lastErrno = osGetLastError(); + winGetReadLock(pFile); + } + } + + /* If we are holding a PENDING lock that ought to be released, then + ** release it now. + */ + if( gotPendingLock && locktype==SHARED_LOCK ){ + winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); + } + + /* Update the state of the lock has held in the file descriptor then + ** return the appropriate result code. + */ + if( res ){ + rc = SQLITE_OK; + }else{ + pFile->lastErrno = lastErrno; + rc = SQLITE_BUSY; + OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n", + pFile->h, locktype, newLocktype)); + } + pFile->locktype = (u8)newLocktype; + OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n", + pFile->h, pFile->locktype, sqlite3ErrName(rc))); + return rc; +} + +/* +** This routine checks if there is a RESERVED lock held on the specified +** file by this or any other process. If such a lock is held, return +** non-zero, otherwise zero. +*/ +static int winCheckReservedLock(sqlite3_file *id, int *pResOut){ + int rc; + winFile *pFile = (winFile*)id; + + SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); + OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut)); + + assert( id!=0 ); + if( pFile->locktype>=RESERVED_LOCK ){ + rc = 1; + OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc)); + }else{ + rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0); + if( rc ){ + winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); + } + rc = !rc; + OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc)); + } + *pResOut = rc; + OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", + pFile->h, pResOut, *pResOut)); + return SQLITE_OK; +} + +/* +** Lower the locking level on file descriptor id to locktype. locktype +** must be either NO_LOCK or SHARED_LOCK. +** +** If the locking level of the file descriptor is already at or below +** the requested locking level, this routine is a no-op. +** +** It is not possible for this routine to fail if the second argument +** is NO_LOCK. If the second argument is SHARED_LOCK then this routine +** might return SQLITE_IOERR; +*/ +static int winUnlock(sqlite3_file *id, int locktype){ + int type; + winFile *pFile = (winFile*)id; + int rc = SQLITE_OK; + assert( pFile!=0 ); + assert( locktype<=SHARED_LOCK ); + OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n", + pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); + type = pFile->locktype; + if( type>=EXCLUSIVE_LOCK ){ + winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); + if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){ + /* This should never happen. We should always be able to + ** reacquire the read lock */ + rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(), + "winUnlock", pFile->zPath); + } + } + if( type>=RESERVED_LOCK ){ + winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); + } + if( locktype==NO_LOCK && type>=SHARED_LOCK ){ + winUnlockReadLock(pFile); + } + if( type>=PENDING_LOCK ){ + winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); + } + pFile->locktype = (u8)locktype; + OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n", + pFile->h, pFile->locktype, sqlite3ErrName(rc))); + return rc; +} + +/* +** If *pArg is inititially negative then this is a query. Set *pArg to +** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. +** +** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. +*/ +static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){ + if( *pArg<0 ){ + *pArg = (pFile->ctrlFlags & mask)!=0; + }else if( (*pArg)==0 ){ + pFile->ctrlFlags &= ~mask; + }else{ + pFile->ctrlFlags |= mask; + } +} + +/* Forward references to VFS helper methods used for temporary files */ +static int winGetTempname(sqlite3_vfs *, char **); +static int winIsDir(const void *); +static BOOL winIsDriveLetterAndColon(const char *); + +/* +** Control and query of the open file handle. +*/ +static int winFileControl(sqlite3_file *id, int op, void *pArg){ + winFile *pFile = (winFile*)id; + OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg)); + switch( op ){ + case SQLITE_FCNTL_LOCKSTATE: { + *(int*)pArg = pFile->locktype; + OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + } + case SQLITE_LAST_ERRNO: { + *(int*)pArg = (int)pFile->lastErrno; + OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + } + case SQLITE_FCNTL_CHUNK_SIZE: { + pFile->szChunk = *(int *)pArg; + OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + } + case SQLITE_FCNTL_SIZE_HINT: { + if( pFile->szChunk>0 ){ + sqlite3_int64 oldSz; + int rc = winFileSize(id, &oldSz); + if( rc==SQLITE_OK ){ + sqlite3_int64 newSz = *(sqlite3_int64*)pArg; + if( newSz>oldSz ){ + SimulateIOErrorBenign(1); + rc = winTruncate(id, newSz); + SimulateIOErrorBenign(0); + } + } + OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); + return rc; + } + OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + } + case SQLITE_FCNTL_PERSIST_WAL: { + winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg); + OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + } + case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { + winModeBit(pFile, WINFILE_PSOW, (int*)pArg); + OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + } + case SQLITE_FCNTL_VFSNAME: { + *(char**)pArg = sqlite3_mprintf("win32"); + OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + } + case SQLITE_FCNTL_WIN32_AV_RETRY: { + int *a = (int*)pArg; + if( a[0]>0 ){ + winIoerrRetry = a[0]; + }else{ + a[0] = winIoerrRetry; + } + if( a[1]>0 ){ + winIoerrRetryDelay = a[1]; + }else{ + a[1] = winIoerrRetryDelay; + } + OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); + return SQLITE_OK; + } + case SQLITE_FCNTL_TEMPFILENAME: { + char *zTFile = 0; + int rc = winGetTempname(pFile->pVfs, &zTFile); + if( rc==SQLITE_OK ){ + *(char**)pArg = zTFile; + } + OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); + return rc; + } +#if SQLITE_MAX_MMAP_SIZE>0 + case SQLITE_FCNTL_MMAP_SIZE: { + i64 newLimit = *(i64*)pArg; + int rc = SQLITE_OK; + if( newLimit>sqlite3GlobalConfig.mxMmap ){ + newLimit = sqlite3GlobalConfig.mxMmap; + } + *(i64*)pArg = pFile->mmapSizeMax; + if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ + pFile->mmapSizeMax = newLimit; + if( pFile->mmapSize>0 ){ + winUnmapfile(pFile); + rc = winMapfile(pFile, -1); + } + } + OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); + return rc; + } +#endif + } + OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h)); + return SQLITE_NOTFOUND; +} + +/* +** Return the sector size in bytes of the underlying block device for +** the specified file. This is almost always 512 bytes, but may be +** larger for some devices. +** +** SQLite code assumes this function cannot fail. It also assumes that +** if two files are created in the same file-system directory (i.e. +** a database and its journal file) that the sector size will be the +** same for both. +*/ +static int winSectorSize(sqlite3_file *id){ + (void)id; + return SQLITE_DEFAULT_SECTOR_SIZE; +} + +/* +** Return a vector of device characteristics. +*/ +static int winDeviceCharacteristics(sqlite3_file *id){ + winFile *p = (winFile*)id; + return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | + ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0); +} + +/* +** Windows will only let you create file view mappings +** on allocation size granularity boundaries. +** During sqlite3_os_init() we do a GetSystemInfo() +** to get the granularity size. +*/ +SYSTEM_INFO winSysInfo; + +#ifndef SQLITE_OMIT_WAL + +/* +** Helper functions to obtain and relinquish the global mutex. The +** global mutex is used to protect the winLockInfo objects used by +** this file, all of which may be shared by multiple threads. +** +** Function winShmMutexHeld() is used to assert() that the global mutex +** is held when required. This function is only used as part of assert() +** statements. e.g. +** +** winShmEnterMutex() +** assert( winShmMutexHeld() ); +** winShmLeaveMutex() +*/ +static void winShmEnterMutex(void){ + sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} +static void winShmLeaveMutex(void){ + sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} +#ifdef SQLITE_DEBUG +static int winShmMutexHeld(void) { + return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} +#endif + +/* +** Object used to represent a single file opened and mmapped to provide +** shared memory. When multiple threads all reference the same +** log-summary, each thread has its own winFile object, but they all +** point to a single instance of this object. In other words, each +** log-summary is opened only once per process. +** +** winShmMutexHeld() must be true when creating or destroying +** this object or while reading or writing the following fields: +** +** nRef +** pNext +** +** The following fields are read-only after the object is created: +** +** fid +** zFilename +** +** Either winShmNode.mutex must be held or winShmNode.nRef==0 and +** winShmMutexHeld() is true when reading or writing any other field +** in this structure. +** +*/ +struct winShmNode { + sqlite3_mutex *mutex; /* Mutex to access this object */ + char *zFilename; /* Name of the file */ + winFile hFile; /* File handle from winOpen */ + + int szRegion; /* Size of shared-memory regions */ + int nRegion; /* Size of array apRegion */ + struct ShmRegion { + HANDLE hMap; /* File handle from CreateFileMapping */ + void *pMap; + } *aRegion; + DWORD lastErrno; /* The Windows errno from the last I/O error */ + + int nRef; /* Number of winShm objects pointing to this */ + winShm *pFirst; /* All winShm objects pointing to this */ + winShmNode *pNext; /* Next in list of all winShmNode objects */ +#ifdef SQLITE_DEBUG + u8 nextShmId; /* Next available winShm.id value */ +#endif +}; + +/* +** A global array of all winShmNode objects. +** +** The winShmMutexHeld() must be true while reading or writing this list. +*/ +static winShmNode *winShmNodeList = 0; + +/* +** Structure used internally by this VFS to record the state of an +** open shared memory connection. +** +** The following fields are initialized when this object is created and +** are read-only thereafter: +** +** winShm.pShmNode +** winShm.id +** +** All other fields are read/write. The winShm.pShmNode->mutex must be held +** while accessing any read/write fields. +*/ +struct winShm { + winShmNode *pShmNode; /* The underlying winShmNode object */ + winShm *pNext; /* Next winShm with the same winShmNode */ + u8 hasMutex; /* True if holding the winShmNode mutex */ + u16 sharedMask; /* Mask of shared locks held */ + u16 exclMask; /* Mask of exclusive locks held */ +#ifdef SQLITE_DEBUG + u8 id; /* Id of this connection with its winShmNode */ +#endif +}; + +/* +** Constants used for locking +*/ +#define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ +#define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ + +/* +** Apply advisory locks for all n bytes beginning at ofst. +*/ +#define _SHM_UNLCK 1 +#define _SHM_RDLCK 2 +#define _SHM_WRLCK 3 +static int winShmSystemLock( + winShmNode *pFile, /* Apply locks to this open shared-memory segment */ + int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */ + int ofst, /* Offset to first byte to be locked/unlocked */ + int nByte /* Number of bytes to lock or unlock */ +){ + int rc = 0; /* Result code form Lock/UnlockFileEx() */ + + /* Access to the winShmNode object is serialized by the caller */ + assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 ); + + OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n", + pFile->hFile.h, lockType, ofst, nByte)); + + /* Release/Acquire the system-level lock */ + if( lockType==_SHM_UNLCK ){ + rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0); + }else{ + /* Initialize the locking parameters */ + DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY; + if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK; + rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0); + } + + if( rc!= 0 ){ + rc = SQLITE_OK; + }else{ + pFile->lastErrno = osGetLastError(); + rc = SQLITE_BUSY; + } + + OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n", + pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" : + "winLockFile", pFile->lastErrno, sqlite3ErrName(rc))); + + return rc; +} + +/* Forward references to VFS methods */ +static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*); +static int winDelete(sqlite3_vfs *,const char*,int); + +/* +** Purge the winShmNodeList list of all entries with winShmNode.nRef==0. +** +** This is not a VFS shared-memory method; it is a utility function called +** by VFS shared-memory methods. +*/ +static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ + winShmNode **pp; + winShmNode *p; + assert( winShmMutexHeld() ); + OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n", + osGetCurrentProcessId(), deleteFlag)); + pp = &winShmNodeList; + while( (p = *pp)!=0 ){ + if( p->nRef==0 ){ + int i; + if( p->mutex ){ sqlite3_mutex_free(p->mutex); } + for(i=0; inRegion; i++){ + BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap); + OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n", + osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); + UNUSED_VARIABLE_VALUE(bRc); + bRc = osCloseHandle(p->aRegion[i].hMap); + OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n", + osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); + UNUSED_VARIABLE_VALUE(bRc); + } + if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){ + SimulateIOErrorBenign(1); + winClose((sqlite3_file *)&p->hFile); + SimulateIOErrorBenign(0); + } + if( deleteFlag ){ + SimulateIOErrorBenign(1); + sqlite3BeginBenignMalloc(); + winDelete(pVfs, p->zFilename, 0); + sqlite3EndBenignMalloc(); + SimulateIOErrorBenign(0); + } + *pp = p->pNext; + sqlite3_free(p->aRegion); + sqlite3_free(p); + }else{ + pp = &p->pNext; + } + } +} + +/* +** Open the shared-memory area associated with database file pDbFd. +** +** When opening a new shared-memory file, if no other instances of that +** file are currently open, in this process or in other processes, then +** the file must be truncated to zero length or have its header cleared. +*/ +static int winOpenSharedMemory(winFile *pDbFd){ + struct winShm *p; /* The connection to be opened */ + struct winShmNode *pShmNode = 0; /* The underlying mmapped file */ + int rc; /* Result code */ + struct winShmNode *pNew; /* Newly allocated winShmNode */ + int nName; /* Size of zName in bytes */ + + assert( pDbFd->pShm==0 ); /* Not previously opened */ + + /* Allocate space for the new sqlite3_shm object. Also speculatively + ** allocate space for a new winShmNode and filename. + */ + p = sqlite3MallocZero( sizeof(*p) ); + if( p==0 ) return SQLITE_IOERR_NOMEM; + nName = sqlite3Strlen30(pDbFd->zPath); + pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 ); + if( pNew==0 ){ + sqlite3_free(p); + return SQLITE_IOERR_NOMEM; + } + pNew->zFilename = (char*)&pNew[1]; + sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath); + sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); + + /* Look to see if there is an existing winShmNode that can be used. + ** If no matching winShmNode currently exists, create a new one. + */ + winShmEnterMutex(); + for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){ + /* TBD need to come up with better match here. Perhaps + ** use FILE_ID_BOTH_DIR_INFO Structure. + */ + if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break; + } + if( pShmNode ){ + sqlite3_free(pNew); + }else{ + pShmNode = pNew; + pNew = 0; + ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE; + pShmNode->pNext = winShmNodeList; + winShmNodeList = pShmNode; + + pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( pShmNode->mutex==0 ){ + rc = SQLITE_IOERR_NOMEM; + goto shm_open_err; + } + + rc = winOpen(pDbFd->pVfs, + pShmNode->zFilename, /* Name of the file (UTF-8) */ + (sqlite3_file*)&pShmNode->hFile, /* File handle here */ + SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, + 0); + if( SQLITE_OK!=rc ){ + goto shm_open_err; + } + + /* Check to see if another process is holding the dead-man switch. + ** If not, truncate the file to zero length. + */ + if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){ + rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0); + if( rc!=SQLITE_OK ){ + rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(), + "winOpenShm", pDbFd->zPath); + } + } + if( rc==SQLITE_OK ){ + winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1); + rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1); + } + if( rc ) goto shm_open_err; + } + + /* Make the new connection a child of the winShmNode */ + p->pShmNode = pShmNode; +#ifdef SQLITE_DEBUG + p->id = pShmNode->nextShmId++; +#endif + pShmNode->nRef++; + pDbFd->pShm = p; + winShmLeaveMutex(); + + /* The reference count on pShmNode has already been incremented under + ** the cover of the winShmEnterMutex() mutex and the pointer from the + ** new (struct winShm) object to the pShmNode has been set. All that is + ** left to do is to link the new object into the linked list starting + ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex + ** mutex. + */ + sqlite3_mutex_enter(pShmNode->mutex); + p->pNext = pShmNode->pFirst; + pShmNode->pFirst = p; + sqlite3_mutex_leave(pShmNode->mutex); + return SQLITE_OK; + + /* Jump here on any error */ +shm_open_err: + winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1); + winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */ + sqlite3_free(p); + sqlite3_free(pNew); + winShmLeaveMutex(); + return rc; +} + +/* +** Close a connection to shared-memory. Delete the underlying +** storage if deleteFlag is true. +*/ +static int winShmUnmap( + sqlite3_file *fd, /* Database holding shared memory */ + int deleteFlag /* Delete after closing if true */ +){ + winFile *pDbFd; /* Database holding shared-memory */ + winShm *p; /* The connection to be closed */ + winShmNode *pShmNode; /* The underlying shared-memory file */ + winShm **pp; /* For looping over sibling connections */ + + pDbFd = (winFile*)fd; + p = pDbFd->pShm; + if( p==0 ) return SQLITE_OK; + pShmNode = p->pShmNode; + + /* Remove connection p from the set of connections associated + ** with pShmNode */ + sqlite3_mutex_enter(pShmNode->mutex); + for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} + *pp = p->pNext; + + /* Free the connection p */ + sqlite3_free(p); + pDbFd->pShm = 0; + sqlite3_mutex_leave(pShmNode->mutex); + + /* If pShmNode->nRef has reached 0, then close the underlying + ** shared-memory file, too */ + winShmEnterMutex(); + assert( pShmNode->nRef>0 ); + pShmNode->nRef--; + if( pShmNode->nRef==0 ){ + winShmPurge(pDbFd->pVfs, deleteFlag); + } + winShmLeaveMutex(); + + return SQLITE_OK; +} + +/* +** Change the lock state for a shared-memory segment. +*/ +static int winShmLock( + sqlite3_file *fd, /* Database file holding the shared memory */ + int ofst, /* First lock to acquire or release */ + int n, /* Number of locks to acquire or release */ + int flags /* What to do with the lock */ +){ + winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */ + winShm *p = pDbFd->pShm; /* The shared memory being locked */ + winShm *pX; /* For looping over all siblings */ + winShmNode *pShmNode = p->pShmNode; + int rc = SQLITE_OK; /* Result code */ + u16 mask; /* Mask of locks to take or release */ + + assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK ); + assert( n>=1 ); + assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED) + || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE) + || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) + || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); + assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); + + mask = (u16)((1U<<(ofst+n)) - (1U<1 || mask==(1<mutex); + if( flags & SQLITE_SHM_UNLOCK ){ + u16 allMask = 0; /* Mask of locks held by siblings */ + + /* See if any siblings hold this same lock */ + for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ + if( pX==p ) continue; + assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 ); + allMask |= pX->sharedMask; + } + + /* Unlock the system-level locks */ + if( (mask & allMask)==0 ){ + rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n); + }else{ + rc = SQLITE_OK; + } + + /* Undo the local locks */ + if( rc==SQLITE_OK ){ + p->exclMask &= ~mask; + p->sharedMask &= ~mask; + } + }else if( flags & SQLITE_SHM_SHARED ){ + u16 allShared = 0; /* Union of locks held by connections other than "p" */ + + /* Find out which shared locks are already held by sibling connections. + ** If any sibling already holds an exclusive lock, go ahead and return + ** SQLITE_BUSY. + */ + for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ + if( (pX->exclMask & mask)!=0 ){ + rc = SQLITE_BUSY; + break; + } + allShared |= pX->sharedMask; + } + + /* Get shared locks at the system level, if necessary */ + if( rc==SQLITE_OK ){ + if( (allShared & mask)==0 ){ + rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n); + }else{ + rc = SQLITE_OK; + } + } + + /* Get the local shared locks */ + if( rc==SQLITE_OK ){ + p->sharedMask |= mask; + } + }else{ + /* Make sure no sibling connections hold locks that will block this + ** lock. If any do, return SQLITE_BUSY right away. + */ + for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ + if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){ + rc = SQLITE_BUSY; + break; + } + } + + /* Get the exclusive locks at the system level. Then if successful + ** also mark the local connection as being locked. + */ + if( rc==SQLITE_OK ){ + rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n); + if( rc==SQLITE_OK ){ + assert( (p->sharedMask & mask)==0 ); + p->exclMask |= mask; + } + } + } + sqlite3_mutex_leave(pShmNode->mutex); + OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n", + osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask, + sqlite3ErrName(rc))); + return rc; +} + +/* +** Implement a memory barrier or memory fence on shared memory. +** +** All loads and stores begun before the barrier must complete before +** any load or store begun after the barrier. +*/ +static void winShmBarrier( + sqlite3_file *fd /* Database holding the shared memory */ +){ + UNUSED_PARAMETER(fd); + /* MemoryBarrier(); // does not work -- do not know why not */ + winShmEnterMutex(); + winShmLeaveMutex(); +} + +/* +** This function is called to obtain a pointer to region iRegion of the +** shared-memory associated with the database file fd. Shared-memory regions +** are numbered starting from zero. Each shared-memory region is szRegion +** bytes in size. +** +** If an error occurs, an error code is returned and *pp is set to NULL. +** +** Otherwise, if the isWrite parameter is 0 and the requested shared-memory +** region has not been allocated (by any client, including one running in a +** separate process), then *pp is set to NULL and SQLITE_OK returned. If +** isWrite is non-zero and the requested shared-memory region has not yet +** been allocated, it is allocated by this function. +** +** If the shared-memory region has already been allocated or is allocated by +** this call as described above, then it is mapped into this processes +** address space (if it is not already), *pp is set to point to the mapped +** memory and SQLITE_OK returned. +*/ +static int winShmMap( + sqlite3_file *fd, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int szRegion, /* Size of regions */ + int isWrite, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + winFile *pDbFd = (winFile*)fd; + winShm *p = pDbFd->pShm; + winShmNode *pShmNode; + int rc = SQLITE_OK; + + if( !p ){ + rc = winOpenSharedMemory(pDbFd); + if( rc!=SQLITE_OK ) return rc; + p = pDbFd->pShm; + } + pShmNode = p->pShmNode; + + sqlite3_mutex_enter(pShmNode->mutex); + assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); + + if( pShmNode->nRegion<=iRegion ){ + struct ShmRegion *apNew; /* New aRegion[] array */ + int nByte = (iRegion+1)*szRegion; /* Minimum required file size */ + sqlite3_int64 sz; /* Current size of wal-index file */ + + pShmNode->szRegion = szRegion; + + /* The requested region is not mapped into this processes address space. + ** Check to see if it has been allocated (i.e. if the wal-index file is + ** large enough to contain the requested region). + */ + rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz); + if( rc!=SQLITE_OK ){ + rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), + "winShmMap1", pDbFd->zPath); + goto shmpage_out; + } + + if( szhFile, nByte); + if( rc!=SQLITE_OK ){ + rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), + "winShmMap2", pDbFd->zPath); + goto shmpage_out; + } + } + + /* Map the requested memory region into this processes address space. */ + apNew = (struct ShmRegion *)sqlite3_realloc( + pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0]) + ); + if( !apNew ){ + rc = SQLITE_IOERR_NOMEM; + goto shmpage_out; + } + pShmNode->aRegion = apNew; + + while( pShmNode->nRegion<=iRegion ){ + HANDLE hMap = NULL; /* file-mapping handle */ + void *pMap = 0; /* Mapped memory region */ + +#if SQLITE_OS_WINRT + hMap = osCreateFileMappingFromApp(pShmNode->hFile.h, + NULL, PAGE_READWRITE, nByte, NULL + ); +#elif defined(SQLITE_WIN32_HAS_WIDE) + hMap = osCreateFileMappingW(pShmNode->hFile.h, + NULL, PAGE_READWRITE, 0, nByte, NULL + ); +#elif defined(SQLITE_WIN32_HAS_ANSI) + hMap = osCreateFileMappingA(pShmNode->hFile.h, + NULL, PAGE_READWRITE, 0, nByte, NULL + ); +#endif + OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n", + osGetCurrentProcessId(), pShmNode->nRegion, nByte, + hMap ? "ok" : "failed")); + if( hMap ){ + int iOffset = pShmNode->nRegion*szRegion; + int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; +#if SQLITE_OS_WINRT + pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ, + iOffset - iOffsetShift, szRegion + iOffsetShift + ); +#else + pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, + 0, iOffset - iOffsetShift, szRegion + iOffsetShift + ); +#endif + OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n", + osGetCurrentProcessId(), pShmNode->nRegion, iOffset, + szRegion, pMap ? "ok" : "failed")); + } + if( !pMap ){ + pShmNode->lastErrno = osGetLastError(); + rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno, + "winShmMap3", pDbFd->zPath); + if( hMap ) osCloseHandle(hMap); + goto shmpage_out; + } + + pShmNode->aRegion[pShmNode->nRegion].pMap = pMap; + pShmNode->aRegion[pShmNode->nRegion].hMap = hMap; + pShmNode->nRegion++; + } + } + +shmpage_out: + if( pShmNode->nRegion>iRegion ){ + int iOffset = iRegion*szRegion; + int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; + char *p = (char *)pShmNode->aRegion[iRegion].pMap; + *pp = (void *)&p[iOffsetShift]; + }else{ + *pp = 0; + } + sqlite3_mutex_leave(pShmNode->mutex); + return rc; +} + +#else +# define winShmMap 0 +# define winShmLock 0 +# define winShmBarrier 0 +# define winShmUnmap 0 +#endif /* #ifndef SQLITE_OMIT_WAL */ + +/* +** Cleans up the mapped region of the specified file, if any. +*/ +#if SQLITE_MAX_MMAP_SIZE>0 +static int winUnmapfile(winFile *pFile){ + assert( pFile!=0 ); + OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, " + "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n", + osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion, + pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax)); + if( pFile->pMapRegion ){ + if( !osUnmapViewOfFile(pFile->pMapRegion) ){ + pFile->lastErrno = osGetLastError(); + OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, " + "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile, + pFile->pMapRegion)); + return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, + "winUnmapfile1", pFile->zPath); + } + pFile->pMapRegion = 0; + pFile->mmapSize = 0; + pFile->mmapSizeActual = 0; + } + if( pFile->hMap!=NULL ){ + if( !osCloseHandle(pFile->hMap) ){ + pFile->lastErrno = osGetLastError(); + OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n", + osGetCurrentProcessId(), pFile, pFile->hMap)); + return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, + "winUnmapfile2", pFile->zPath); + } + pFile->hMap = NULL; + } + OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", + osGetCurrentProcessId(), pFile)); + return SQLITE_OK; +} + +/* +** Memory map or remap the file opened by file-descriptor pFd (if the file +** is already mapped, the existing mapping is replaced by the new). Or, if +** there already exists a mapping for this file, and there are still +** outstanding xFetch() references to it, this function is a no-op. +** +** If parameter nByte is non-negative, then it is the requested size of +** the mapping to create. Otherwise, if nByte is less than zero, then the +** requested size is the size of the file on disk. The actual size of the +** created mapping is either the requested size or the value configured +** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller. +** +** SQLITE_OK is returned if no error occurs (even if the mapping is not +** recreated as a result of outstanding references) or an SQLite error +** code otherwise. +*/ +static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ + sqlite3_int64 nMap = nByte; + int rc; + + assert( nMap>=0 || pFd->nFetchOut==0 ); + OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n", + osGetCurrentProcessId(), pFd, nByte)); + + if( pFd->nFetchOut>0 ) return SQLITE_OK; + + if( nMap<0 ){ + rc = winFileSize((sqlite3_file*)pFd, &nMap); + if( rc ){ + OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n", + osGetCurrentProcessId(), pFd)); + return SQLITE_IOERR_FSTAT; + } + } + if( nMap>pFd->mmapSizeMax ){ + nMap = pFd->mmapSizeMax; + } + nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1); + + if( nMap==0 && pFd->mmapSize>0 ){ + winUnmapfile(pFd); + } + if( nMap!=pFd->mmapSize ){ + void *pNew = 0; + DWORD protect = PAGE_READONLY; + DWORD flags = FILE_MAP_READ; + + winUnmapfile(pFd); + if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){ + protect = PAGE_READWRITE; + flags |= FILE_MAP_WRITE; + } +#if SQLITE_OS_WINRT + pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL); +#elif defined(SQLITE_WIN32_HAS_WIDE) + pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect, + (DWORD)((nMap>>32) & 0xffffffff), + (DWORD)(nMap & 0xffffffff), NULL); +#elif defined(SQLITE_WIN32_HAS_ANSI) + pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect, + (DWORD)((nMap>>32) & 0xffffffff), + (DWORD)(nMap & 0xffffffff), NULL); +#endif + if( pFd->hMap==NULL ){ + pFd->lastErrno = osGetLastError(); + rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno, + "winMapfile1", pFd->zPath); + /* Log the error, but continue normal operation using xRead/xWrite */ + OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n", + osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); + return SQLITE_OK; + } + assert( (nMap % winSysInfo.dwPageSize)==0 ); + assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff ); +#if SQLITE_OS_WINRT + pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap); +#else + pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap); +#endif + if( pNew==NULL ){ + osCloseHandle(pFd->hMap); + pFd->hMap = NULL; + pFd->lastErrno = osGetLastError(); + rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno, + "winMapfile2", pFd->zPath); + /* Log the error, but continue normal operation using xRead/xWrite */ + OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n", + osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); + return SQLITE_OK; + } + pFd->pMapRegion = pNew; + pFd->mmapSize = nMap; + pFd->mmapSizeActual = nMap; + } + + OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", + osGetCurrentProcessId(), pFd)); + return SQLITE_OK; +} +#endif /* SQLITE_MAX_MMAP_SIZE>0 */ + +/* +** If possible, return a pointer to a mapping of file fd starting at offset +** iOff. The mapping must be valid for at least nAmt bytes. +** +** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. +** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. +** Finally, if an error does occur, return an SQLite error code. The final +** value of *pp is undefined in this case. +** +** If this function does return a pointer, the caller must eventually +** release the reference by calling winUnfetch(). +*/ +static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ +#if SQLITE_MAX_MMAP_SIZE>0 + winFile *pFd = (winFile*)fd; /* The underlying database file */ +#endif + *pp = 0; + + OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n", + osGetCurrentProcessId(), fd, iOff, nAmt, pp)); + +#if SQLITE_MAX_MMAP_SIZE>0 + if( pFd->mmapSizeMax>0 ){ + if( pFd->pMapRegion==0 ){ + int rc = winMapfile(pFd, -1); + if( rc!=SQLITE_OK ){ + OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n", + osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); + return rc; + } + } + if( pFd->mmapSize >= iOff+nAmt ){ + *pp = &((u8 *)pFd->pMapRegion)[iOff]; + pFd->nFetchOut++; + } + } +#endif + + OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n", + osGetCurrentProcessId(), fd, pp, *pp)); + return SQLITE_OK; +} + +/* +** If the third argument is non-NULL, then this function releases a +** reference obtained by an earlier call to winFetch(). The second +** argument passed to this function must be the same as the corresponding +** argument that was passed to the winFetch() invocation. +** +** Or, if the third argument is NULL, then this function is being called +** to inform the VFS layer that, according to POSIX, any existing mapping +** may now be invalid and should be unmapped. +*/ +static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){ +#if SQLITE_MAX_MMAP_SIZE>0 + winFile *pFd = (winFile*)fd; /* The underlying database file */ + + /* If p==0 (unmap the entire file) then there must be no outstanding + ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), + ** then there must be at least one outstanding. */ + assert( (p==0)==(pFd->nFetchOut==0) ); + + /* If p!=0, it must match the iOff value. */ + assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); + + OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n", + osGetCurrentProcessId(), pFd, iOff, p)); + + if( p ){ + pFd->nFetchOut--; + }else{ + /* FIXME: If Windows truly always prevents truncating or deleting a + ** file while a mapping is held, then the following winUnmapfile() call + ** is unnecessary can can be omitted - potentially improving + ** performance. */ + winUnmapfile(pFd); + } + + assert( pFd->nFetchOut>=0 ); +#endif + + OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n", + osGetCurrentProcessId(), fd)); + return SQLITE_OK; +} + +/* +** Here ends the implementation of all sqlite3_file methods. +** +********************** End sqlite3_file Methods ******************************* +******************************************************************************/ + +/* +** This vector defines all the methods that can operate on an +** sqlite3_file for win32. +*/ +static const sqlite3_io_methods winIoMethod = { + 3, /* iVersion */ + winClose, /* xClose */ + winRead, /* xRead */ + winWrite, /* xWrite */ + winTruncate, /* xTruncate */ + winSync, /* xSync */ + winFileSize, /* xFileSize */ + winLock, /* xLock */ + winUnlock, /* xUnlock */ + winCheckReservedLock, /* xCheckReservedLock */ + winFileControl, /* xFileControl */ + winSectorSize, /* xSectorSize */ + winDeviceCharacteristics, /* xDeviceCharacteristics */ + winShmMap, /* xShmMap */ + winShmLock, /* xShmLock */ + winShmBarrier, /* xShmBarrier */ + winShmUnmap, /* xShmUnmap */ + winFetch, /* xFetch */ + winUnfetch /* xUnfetch */ +}; + +/**************************************************************************** +**************************** sqlite3_vfs methods **************************** +** +** This division contains the implementation of methods on the +** sqlite3_vfs object. +*/ + +#if 0 +/* +** Convert a filename from whatever the underlying operating system +** supports for filenames into UTF-8. Space to hold the result is +** obtained from malloc and must be freed by the calling function. +*/ +static char *winConvertToUtf8Filename(const void *zFilename){ + char *zConverted = 0; + if( osIsNT() ){ + zConverted = winUnicodeToUtf8(zFilename); + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + zConverted = sqlite3_win32_mbcs_to_utf8(zFilename); + } +#endif + /* caller will handle out of memory */ + return zConverted; +} +#endif + +/* +** Convert a UTF-8 filename into whatever form the underlying +** operating system wants filenames in. Space to hold the result +** is obtained from malloc and must be freed by the calling +** function. +*/ +static void *winConvertFromUtf8Filename(const char *zFilename){ + void *zConverted = 0; + if( osIsNT() ){ + zConverted = winUtf8ToUnicode(zFilename); + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + zConverted = sqlite3_win32_utf8_to_mbcs(zFilename); + } +#endif + /* caller will handle out of memory */ + return zConverted; +} + +/* +** This function returns non-zero if the specified UTF-8 string buffer +** ends with a directory separator character. +*/ +static int winEndsInDirSep(char *zBuf){ + if( zBuf ){ + int nLen = sqlite3Strlen30(zBuf); + return nLen>0 && winIsDirSep(zBuf[nLen-1]); + } + return 0; +} + +/* +** Create a temporary file name and store the resulting pointer into pzBuf. +** The pointer returned in pzBuf must be freed via sqlite3_free(). +*/ +static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ + static char zChars[] = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"; + size_t i, j; + int nBuf, nLen; + char *zBuf; + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. + */ + SimulateIOError( return SQLITE_IOERR ); + + /* Allocate a temporary buffer to store the fully qualified file + ** name for the temporary file. If this fails, we cannot continue. + */ + nBuf = pVfs->mxPathname; + zBuf = sqlite3MallocZero( nBuf+2 ); + if( !zBuf ){ + OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); + return SQLITE_IOERR_NOMEM; + } + + /* Figure out the effective temporary directory. First, check if one + ** has been explicitly set by the application; otherwise, use the one + ** configured by the operating system. + */ + assert( nBuf>30 ); + if( sqlite3_temp_directory ){ + sqlite3_snprintf(nBuf-30, zBuf, "%s%s", sqlite3_temp_directory, + winEndsInDirSep(sqlite3_temp_directory) ? "" : + winGetDirDep()); + } +#if defined(__CYGWIN__) + else{ + static const char *azDirs[] = { + 0, /* getenv("SQLITE_TMPDIR") */ + 0, /* getenv("TMPDIR") */ + 0, /* getenv("TMP") */ + 0, /* getenv("TEMP") */ + 0, /* getenv("USERPROFILE") */ + "/var/tmp", + "/usr/tmp", + "/tmp", + ".", + 0 /* List terminator */ + }; + unsigned int i; + const char *zDir = 0; + + if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR"); + if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR"); + if( !azDirs[2] ) azDirs[2] = getenv("TMP"); + if( !azDirs[3] ) azDirs[3] = getenv("TEMP"); + if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE"); + for(i=0; i= nBuf ){ + sqlite3_free(zBuf); + OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); + return winLogError(SQLITE_ERROR, 0, "winGetTempname3", 0); + } + + sqlite3_snprintf(nBuf-18-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX); + + j = sqlite3Strlen30(zBuf); + sqlite3_randomness(15, &zBuf[j]); + for(i=0; i<15; i++, j++){ + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; + } + zBuf[j] = 0; + zBuf[j+1] = 0; + *pzBuf = zBuf; + + OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf)); + return SQLITE_OK; +} + +/* +** Return TRUE if the named file is really a directory. Return false if +** it is something other than a directory, or if there is any kind of memory +** allocation failure. +*/ +static int winIsDir(const void *zConverted){ + DWORD attr; + int rc = 0; + DWORD lastErrno; + + if( osIsNT() ){ + int cnt = 0; + WIN32_FILE_ATTRIBUTE_DATA sAttrData; + memset(&sAttrData, 0, sizeof(sAttrData)); + while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, + GetFileExInfoStandard, + &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} + if( !rc ){ + return 0; /* Invalid name? */ + } + attr = sAttrData.dwFileAttributes; +#if SQLITE_OS_WINCE==0 + }else{ + attr = osGetFileAttributesA((char*)zConverted); +#endif + } + return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY); +} + +/* +** Open a file. +*/ +static int winOpen( + sqlite3_vfs *pVfs, /* Used to get maximum path name length */ + const char *zName, /* Name of the file (UTF-8) */ + sqlite3_file *id, /* Write the SQLite file handle here */ + int flags, /* Open mode flags */ + int *pOutFlags /* Status return flags */ +){ + HANDLE h; + DWORD lastErrno; + DWORD dwDesiredAccess; + DWORD dwShareMode; + DWORD dwCreationDisposition; + DWORD dwFlagsAndAttributes = 0; +#if SQLITE_OS_WINCE + int isTemp = 0; +#endif + winFile *pFile = (winFile*)id; + void *zConverted; /* Filename in OS encoding */ + const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */ + int cnt = 0; + + /* If argument zPath is a NULL pointer, this function is required to open + ** a temporary file. Use this buffer to store the file name in. + */ + char *zTmpname = 0; /* For temporary filename, if necessary. */ + + int rc = SQLITE_OK; /* Function Return Code */ +#if !defined(NDEBUG) || SQLITE_OS_WINCE + int eType = flags&0xFFFFFF00; /* Type of file to open */ +#endif + + int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); + int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); + int isCreate = (flags & SQLITE_OPEN_CREATE); + int isReadonly = (flags & SQLITE_OPEN_READONLY); + int isReadWrite = (flags & SQLITE_OPEN_READWRITE); + +#ifndef NDEBUG + int isOpenJournal = (isCreate && ( + eType==SQLITE_OPEN_MASTER_JOURNAL + || eType==SQLITE_OPEN_MAIN_JOURNAL + || eType==SQLITE_OPEN_WAL + )); +#endif + + OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n", + zUtf8Name, id, flags, pOutFlags)); + + /* Check the following statements are true: + ** + ** (a) Exactly one of the READWRITE and READONLY flags must be set, and + ** (b) if CREATE is set, then READWRITE must also be set, and + ** (c) if EXCLUSIVE is set, then CREATE must also be set. + ** (d) if DELETEONCLOSE is set, then CREATE must also be set. + */ + assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); + assert(isCreate==0 || isReadWrite); + assert(isExclusive==0 || isCreate); + assert(isDelete==0 || isCreate); + + /* The main DB, main journal, WAL file and master journal are never + ** automatically deleted. Nor are they ever temporary files. */ + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); + assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); + + /* Assert that the upper layer has set one of the "file-type" flags. */ + assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB + || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL + || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL + || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL + ); + + assert( pFile!=0 ); + memset(pFile, 0, sizeof(winFile)); + pFile->h = INVALID_HANDLE_VALUE; + +#if SQLITE_OS_WINRT + if( !zUtf8Name && !sqlite3_temp_directory ){ + sqlite3_log(SQLITE_ERROR, + "sqlite3_temp_directory variable should be set for WinRT"); + } +#endif + + /* If the second argument to this function is NULL, generate a + ** temporary file name to use + */ + if( !zUtf8Name ){ + assert( isDelete && !isOpenJournal ); + rc = winGetTempname(pVfs, &zTmpname); + if( rc!=SQLITE_OK ){ + OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc))); + return rc; + } + zUtf8Name = zTmpname; + } + + /* Database filenames are double-zero terminated if they are not + ** URIs with parameters. Hence, they can always be passed into + ** sqlite3_uri_parameter(). + */ + assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) || + zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 ); + + /* Convert the filename to the system encoding. */ + zConverted = winConvertFromUtf8Filename(zUtf8Name); + if( zConverted==0 ){ + sqlite3_free(zTmpname); + OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name)); + return SQLITE_IOERR_NOMEM; + } + + if( winIsDir(zConverted) ){ + sqlite3_free(zConverted); + sqlite3_free(zTmpname); + OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name)); + return SQLITE_CANTOPEN_ISDIR; + } + + if( isReadWrite ){ + dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; + }else{ + dwDesiredAccess = GENERIC_READ; + } + + /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is + ** created. SQLite doesn't use it to indicate "exclusive access" + ** as it is usually understood. + */ + if( isExclusive ){ + /* Creates a new file, only if it does not already exist. */ + /* If the file exists, it fails. */ + dwCreationDisposition = CREATE_NEW; + }else if( isCreate ){ + /* Open existing file, or create if it doesn't exist */ + dwCreationDisposition = OPEN_ALWAYS; + }else{ + /* Opens a file, only if it exists. */ + dwCreationDisposition = OPEN_EXISTING; + } + + dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; + + if( isDelete ){ +#if SQLITE_OS_WINCE + dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; + isTemp = 1; +#else + dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY + | FILE_ATTRIBUTE_HIDDEN + | FILE_FLAG_DELETE_ON_CLOSE; +#endif + }else{ + dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; + } + /* Reports from the internet are that performance is always + ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */ +#if SQLITE_OS_WINCE + dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS; +#endif + + if( osIsNT() ){ +#if SQLITE_OS_WINRT + CREATEFILE2_EXTENDED_PARAMETERS extendedParameters; + extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); + extendedParameters.dwFileAttributes = + dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK; + extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK; + extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS; + extendedParameters.lpSecurityAttributes = NULL; + extendedParameters.hTemplateFile = NULL; + while( (h = osCreateFile2((LPCWSTR)zConverted, + dwDesiredAccess, + dwShareMode, + dwCreationDisposition, + &extendedParameters))==INVALID_HANDLE_VALUE && + winRetryIoerr(&cnt, &lastErrno) ){ + /* Noop */ + } +#else + while( (h = osCreateFileW((LPCWSTR)zConverted, + dwDesiredAccess, + dwShareMode, NULL, + dwCreationDisposition, + dwFlagsAndAttributes, + NULL))==INVALID_HANDLE_VALUE && + winRetryIoerr(&cnt, &lastErrno) ){ + /* Noop */ + } +#endif + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + while( (h = osCreateFileA((LPCSTR)zConverted, + dwDesiredAccess, + dwShareMode, NULL, + dwCreationDisposition, + dwFlagsAndAttributes, + NULL))==INVALID_HANDLE_VALUE && + winRetryIoerr(&cnt, &lastErrno) ){ + /* Noop */ + } + } +#endif + winLogIoerr(cnt); + + OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name, + dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); + + if( h==INVALID_HANDLE_VALUE ){ + pFile->lastErrno = lastErrno; + winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name); + sqlite3_free(zConverted); + sqlite3_free(zTmpname); + if( isReadWrite && !isExclusive ){ + return winOpen(pVfs, zName, id, + ((flags|SQLITE_OPEN_READONLY) & + ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), + pOutFlags); + }else{ + return SQLITE_CANTOPEN_BKPT; + } + } + + if( pOutFlags ){ + if( isReadWrite ){ + *pOutFlags = SQLITE_OPEN_READWRITE; + }else{ + *pOutFlags = SQLITE_OPEN_READONLY; + } + } + + OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, " + "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ? + *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); + +#if SQLITE_OS_WINCE + if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB + && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK + ){ + osCloseHandle(h); + sqlite3_free(zConverted); + sqlite3_free(zTmpname); + OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc))); + return rc; + } + if( isTemp ){ + pFile->zDeleteOnClose = zConverted; + }else +#endif + { + sqlite3_free(zConverted); + } + + sqlite3_free(zTmpname); + pFile->pMethod = &winIoMethod; + pFile->pVfs = pVfs; + pFile->h = h; + if( isReadonly ){ + pFile->ctrlFlags |= WINFILE_RDONLY; + } + if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){ + pFile->ctrlFlags |= WINFILE_PSOW; + } + pFile->lastErrno = NO_ERROR; + pFile->zPath = zName; +#if SQLITE_MAX_MMAP_SIZE>0 + pFile->hMap = NULL; + pFile->pMapRegion = 0; + pFile->mmapSize = 0; + pFile->mmapSizeActual = 0; + pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap; +#endif + + OpenCounter(+1); + return rc; +} + +/* +** Delete the named file. +** +** Note that Windows does not allow a file to be deleted if some other +** process has it open. Sometimes a virus scanner or indexing program +** will open a journal file shortly after it is created in order to do +** whatever it does. While this other process is holding the +** file open, we will be unable to delete it. To work around this +** problem, we delay 100 milliseconds and try to delete again. Up +** to MX_DELETION_ATTEMPTs deletion attempts are run before giving +** up and returning an error. +*/ +static int winDelete( + sqlite3_vfs *pVfs, /* Not used on win32 */ + const char *zFilename, /* Name of file to delete */ + int syncDir /* Not used on win32 */ +){ + int cnt = 0; + int rc; + DWORD attr; + DWORD lastErrno; + void *zConverted; + UNUSED_PARAMETER(pVfs); + UNUSED_PARAMETER(syncDir); + + SimulateIOError(return SQLITE_IOERR_DELETE); + OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir)); + + zConverted = winConvertFromUtf8Filename(zFilename); + if( zConverted==0 ){ + OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); + return SQLITE_IOERR_NOMEM; + } + if( osIsNT() ){ + do { +#if SQLITE_OS_WINRT + WIN32_FILE_ATTRIBUTE_DATA sAttrData; + memset(&sAttrData, 0, sizeof(sAttrData)); + if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard, + &sAttrData) ){ + attr = sAttrData.dwFileAttributes; + }else{ + lastErrno = osGetLastError(); + if( lastErrno==ERROR_FILE_NOT_FOUND + || lastErrno==ERROR_PATH_NOT_FOUND ){ + rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ + }else{ + rc = SQLITE_ERROR; + } + break; + } +#else + attr = osGetFileAttributesW(zConverted); +#endif + if ( attr==INVALID_FILE_ATTRIBUTES ){ + lastErrno = osGetLastError(); + if( lastErrno==ERROR_FILE_NOT_FOUND + || lastErrno==ERROR_PATH_NOT_FOUND ){ + rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ + }else{ + rc = SQLITE_ERROR; + } + break; + } + if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ + rc = SQLITE_ERROR; /* Files only. */ + break; + } + if ( osDeleteFileW(zConverted) ){ + rc = SQLITE_OK; /* Deleted OK. */ + break; + } + if ( !winRetryIoerr(&cnt, &lastErrno) ){ + rc = SQLITE_ERROR; /* No more retries. */ + break; + } + } while(1); + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + do { + attr = osGetFileAttributesA(zConverted); + if ( attr==INVALID_FILE_ATTRIBUTES ){ + lastErrno = osGetLastError(); + if( lastErrno==ERROR_FILE_NOT_FOUND + || lastErrno==ERROR_PATH_NOT_FOUND ){ + rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ + }else{ + rc = SQLITE_ERROR; + } + break; + } + if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ + rc = SQLITE_ERROR; /* Files only. */ + break; + } + if ( osDeleteFileA(zConverted) ){ + rc = SQLITE_OK; /* Deleted OK. */ + break; + } + if ( !winRetryIoerr(&cnt, &lastErrno) ){ + rc = SQLITE_ERROR; /* No more retries. */ + break; + } + } while(1); + } +#endif + if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){ + rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename); + }else{ + winLogIoerr(cnt); + } + sqlite3_free(zConverted); + OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc))); + return rc; +} + +/* +** Check the existence and status of a file. +*/ +static int winAccess( + sqlite3_vfs *pVfs, /* Not used on win32 */ + const char *zFilename, /* Name of file to check */ + int flags, /* Type of test to make on this file */ + int *pResOut /* OUT: Result */ +){ + DWORD attr; + int rc = 0; + DWORD lastErrno; + void *zConverted; + UNUSED_PARAMETER(pVfs); + + SimulateIOError( return SQLITE_IOERR_ACCESS; ); + OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n", + zFilename, flags, pResOut)); + + zConverted = winConvertFromUtf8Filename(zFilename); + if( zConverted==0 ){ + OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); + return SQLITE_IOERR_NOMEM; + } + if( osIsNT() ){ + int cnt = 0; + WIN32_FILE_ATTRIBUTE_DATA sAttrData; + memset(&sAttrData, 0, sizeof(sAttrData)); + while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, + GetFileExInfoStandard, + &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} + if( rc ){ + /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file + ** as if it does not exist. + */ + if( flags==SQLITE_ACCESS_EXISTS + && sAttrData.nFileSizeHigh==0 + && sAttrData.nFileSizeLow==0 ){ + attr = INVALID_FILE_ATTRIBUTES; + }else{ + attr = sAttrData.dwFileAttributes; + } + }else{ + winLogIoerr(cnt); + if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){ + sqlite3_free(zConverted); + return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", + zFilename); + }else{ + attr = INVALID_FILE_ATTRIBUTES; + } + } + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + attr = osGetFileAttributesA((char*)zConverted); + } +#endif + sqlite3_free(zConverted); + switch( flags ){ + case SQLITE_ACCESS_READ: + case SQLITE_ACCESS_EXISTS: + rc = attr!=INVALID_FILE_ATTRIBUTES; + break; + case SQLITE_ACCESS_READWRITE: + rc = attr!=INVALID_FILE_ATTRIBUTES && + (attr & FILE_ATTRIBUTE_READONLY)==0; + break; + default: + assert(!"Invalid flags argument"); + } + *pResOut = rc; + OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", + zFilename, pResOut, *pResOut)); + return SQLITE_OK; +} + +/* +** Returns non-zero if the specified path name starts with a drive letter +** followed by a colon character. +*/ +static BOOL winIsDriveLetterAndColon( + const char *zPathname +){ + return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ); +} + +/* +** Returns non-zero if the specified path name should be used verbatim. If +** non-zero is returned from this function, the calling function must simply +** use the provided path name verbatim -OR- resolve it into a full path name +** using the GetFullPathName Win32 API function (if available). +*/ +static BOOL winIsVerbatimPathname( + const char *zPathname +){ + /* + ** If the path name starts with a forward slash or a backslash, it is either + ** a legal UNC name, a volume relative path, or an absolute path name in the + ** "Unix" format on Windows. There is no easy way to differentiate between + ** the final two cases; therefore, we return the safer return value of TRUE + ** so that callers of this function will simply use it verbatim. + */ + if ( winIsDirSep(zPathname[0]) ){ + return TRUE; + } + + /* + ** If the path name starts with a letter and a colon it is either a volume + ** relative path or an absolute path. Callers of this function must not + ** attempt to treat it as a relative path name (i.e. they should simply use + ** it verbatim). + */ + if ( winIsDriveLetterAndColon(zPathname) ){ + return TRUE; + } + + /* + ** If we get to this point, the path name should almost certainly be a purely + ** relative one (i.e. not a UNC name, not absolute, and not volume relative). + */ + return FALSE; +} + +/* +** Turn a relative pathname into a full pathname. Write the full +** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname +** bytes in size. +*/ +static int winFullPathname( + sqlite3_vfs *pVfs, /* Pointer to vfs object */ + const char *zRelative, /* Possibly relative input path */ + int nFull, /* Size of output buffer in bytes */ + char *zFull /* Output buffer */ +){ + +#if defined(__CYGWIN__) + SimulateIOError( return SQLITE_ERROR ); + UNUSED_PARAMETER(nFull); + assert( nFull>=pVfs->mxPathname ); + if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ + /* + ** NOTE: We are dealing with a relative path name and the data + ** directory has been set. Therefore, use it as the basis + ** for converting the relative path name to an absolute + ** one by prepending the data directory and a slash. + */ + char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); + if( !zOut ){ + return SQLITE_IOERR_NOMEM; + } + if( cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut, + pVfs->mxPathname+1)<0 ){ + sqlite3_free(zOut); + return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, + "winFullPathname1", zRelative); + } + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s", + sqlite3_data_directory, winGetDirDep(), zOut); + sqlite3_free(zOut); + }else{ + if( cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull)<0 ){ + return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, + "winFullPathname2", zRelative); + } + } + return SQLITE_OK; +#endif + +#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__) + SimulateIOError( return SQLITE_ERROR ); + /* WinCE has no concept of a relative pathname, or so I am told. */ + /* WinRT has no way to convert a relative path to an absolute one. */ + if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ + /* + ** NOTE: We are dealing with a relative path name and the data + ** directory has been set. Therefore, use it as the basis + ** for converting the relative path name to an absolute + ** one by prepending the data directory and a backslash. + */ + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s", + sqlite3_data_directory, winGetDirDep(), zRelative); + }else{ + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative); + } + return SQLITE_OK; +#endif + +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__) + DWORD nByte; + void *zConverted; + char *zOut; + + /* If this path name begins with "/X:", where "X" is any alphabetic + ** character, discard the initial "/" from the pathname. + */ + if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){ + zRelative++; + } + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. This function could fail if, for example, the + ** current working directory has been unlinked. + */ + SimulateIOError( return SQLITE_ERROR ); + if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ + /* + ** NOTE: We are dealing with a relative path name and the data + ** directory has been set. Therefore, use it as the basis + ** for converting the relative path name to an absolute + ** one by prepending the data directory and a backslash. + */ + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s", + sqlite3_data_directory, winGetDirDep(), zRelative); + return SQLITE_OK; + } + zConverted = winConvertFromUtf8Filename(zRelative); + if( zConverted==0 ){ + return SQLITE_IOERR_NOMEM; + } + if( osIsNT() ){ + LPWSTR zTemp; + nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0); + if( nByte==0 ){ + sqlite3_free(zConverted); + return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), + "winFullPathname1", zRelative); + } + nByte += 3; + zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); + if( zTemp==0 ){ + sqlite3_free(zConverted); + return SQLITE_IOERR_NOMEM; + } + nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0); + if( nByte==0 ){ + sqlite3_free(zConverted); + sqlite3_free(zTemp); + return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), + "winFullPathname2", zRelative); + } + sqlite3_free(zConverted); + zOut = winUnicodeToUtf8(zTemp); + sqlite3_free(zTemp); + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + char *zTemp; + nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0); + if( nByte==0 ){ + sqlite3_free(zConverted); + return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), + "winFullPathname3", zRelative); + } + nByte += 3; + zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); + if( zTemp==0 ){ + sqlite3_free(zConverted); + return SQLITE_IOERR_NOMEM; + } + nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0); + if( nByte==0 ){ + sqlite3_free(zConverted); + sqlite3_free(zTemp); + return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), + "winFullPathname4", zRelative); + } + sqlite3_free(zConverted); + zOut = sqlite3_win32_mbcs_to_utf8(zTemp); + sqlite3_free(zTemp); + } +#endif + if( zOut ){ + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); + sqlite3_free(zOut); + return SQLITE_OK; + }else{ + return SQLITE_IOERR_NOMEM; + } +#endif +} + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +/* +** Interfaces for opening a shared library, finding entry points +** within the shared library, and closing the shared library. +*/ +/* +** Interfaces for opening a shared library, finding entry points +** within the shared library, and closing the shared library. +*/ +static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){ + HANDLE h; + void *zConverted = winConvertFromUtf8Filename(zFilename); + UNUSED_PARAMETER(pVfs); + if( zConverted==0 ){ + return 0; + } + if( osIsNT() ){ +#if SQLITE_OS_WINRT + h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0); +#else + h = osLoadLibraryW((LPCWSTR)zConverted); +#endif + } +#ifdef SQLITE_WIN32_HAS_ANSI + else{ + h = osLoadLibraryA((char*)zConverted); + } +#endif + sqlite3_free(zConverted); + return (void*)h; +} +static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){ + UNUSED_PARAMETER(pVfs); + winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut); +} +static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ + UNUSED_PARAMETER(pVfs); + return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym); +} +static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){ + UNUSED_PARAMETER(pVfs); + osFreeLibrary((HANDLE)pHandle); +} +#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ + #define winDlOpen 0 + #define winDlError 0 + #define winDlSym 0 + #define winDlClose 0 +#endif + + +/* +** Write up to nBuf bytes of randomness into zBuf. +*/ +static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ + int n = 0; + UNUSED_PARAMETER(pVfs); +#if defined(SQLITE_TEST) + n = nBuf; + memset(zBuf, 0, nBuf); +#else + if( sizeof(SYSTEMTIME)<=nBuf-n ){ + SYSTEMTIME x; + osGetSystemTime(&x); + memcpy(&zBuf[n], &x, sizeof(x)); + n += sizeof(x); + } + if( sizeof(DWORD)<=nBuf-n ){ + DWORD pid = osGetCurrentProcessId(); + memcpy(&zBuf[n], &pid, sizeof(pid)); + n += sizeof(pid); + } +#if SQLITE_OS_WINRT + if( sizeof(ULONGLONG)<=nBuf-n ){ + ULONGLONG cnt = osGetTickCount64(); + memcpy(&zBuf[n], &cnt, sizeof(cnt)); + n += sizeof(cnt); + } +#else + if( sizeof(DWORD)<=nBuf-n ){ + DWORD cnt = osGetTickCount(); + memcpy(&zBuf[n], &cnt, sizeof(cnt)); + n += sizeof(cnt); + } +#endif + if( sizeof(LARGE_INTEGER)<=nBuf-n ){ + LARGE_INTEGER i; + osQueryPerformanceCounter(&i); + memcpy(&zBuf[n], &i, sizeof(i)); + n += sizeof(i); + } +#endif + return n; +} + + +/* +** Sleep for a little while. Return the amount of time slept. +*/ +static int winSleep(sqlite3_vfs *pVfs, int microsec){ + sqlite3_win32_sleep((microsec+999)/1000); + UNUSED_PARAMETER(pVfs); + return ((microsec+999)/1000)*1000; +} + +/* +** The following variable, if set to a non-zero value, is interpreted as +** the number of seconds since 1970 and is used to set the result of +** sqlite3OsCurrentTime() during testing. +*/ +#ifdef SQLITE_TEST +int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ +#endif + +/* +** Find the current time (in Universal Coordinated Time). Write into *piNow +** the current time and date as a Julian Day number times 86_400_000. In +** other words, write into *piNow the number of milliseconds since the Julian +** epoch of noon in Greenwich on November 24, 4714 B.C according to the +** proleptic Gregorian calendar. +** +** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date +** cannot be found. +*/ +static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ + /* FILETIME structure is a 64-bit value representing the number of + 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). + */ + FILETIME ft; + static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000; +#ifdef SQLITE_TEST + static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; +#endif + /* 2^32 - to avoid use of LL and warnings in gcc */ + static const sqlite3_int64 max32BitValue = + (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + + (sqlite3_int64)294967296; + +#if SQLITE_OS_WINCE + SYSTEMTIME time; + osGetSystemTime(&time); + /* if SystemTimeToFileTime() fails, it returns zero. */ + if (!osSystemTimeToFileTime(&time,&ft)){ + return SQLITE_ERROR; + } +#else + osGetSystemTimeAsFileTime( &ft ); +#endif + + *piNow = winFiletimeEpoch + + ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + + (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000; + +#ifdef SQLITE_TEST + if( sqlite3_current_time ){ + *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; + } +#endif + UNUSED_PARAMETER(pVfs); + return SQLITE_OK; +} + +/* +** Find the current time (in Universal Coordinated Time). Write the +** current time and date as a Julian Day number into *prNow and +** return 0. Return 1 if the time and date cannot be found. +*/ +static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){ + int rc; + sqlite3_int64 i; + rc = winCurrentTimeInt64(pVfs, &i); + if( !rc ){ + *prNow = i/86400000.0; + } + return rc; +} + +/* +** The idea is that this function works like a combination of +** GetLastError() and FormatMessage() on Windows (or errno and +** strerror_r() on Unix). After an error is returned by an OS +** function, SQLite calls this function with zBuf pointing to +** a buffer of nBuf bytes. The OS layer should populate the +** buffer with a nul-terminated UTF-8 encoded error message +** describing the last IO error to have occurred within the calling +** thread. +** +** If the error message is too large for the supplied buffer, +** it should be truncated. The return value of xGetLastError +** is zero if the error message fits in the buffer, or non-zero +** otherwise (if the message was truncated). If non-zero is returned, +** then it is not necessary to include the nul-terminator character +** in the output buffer. +** +** Not supplying an error message will have no adverse effect +** on SQLite. It is fine to have an implementation that never +** returns an error message: +** +** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ +** assert(zBuf[0]=='\0'); +** return 0; +** } +** +** However if an error message is supplied, it will be incorporated +** by sqlite into the error message available to the user using +** sqlite3_errmsg(), possibly making IO errors easier to debug. +*/ +static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ + UNUSED_PARAMETER(pVfs); + return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf); +} + +/* +** Initialize and deinitialize the operating system interface. +*/ +int sqlite3_os_init(void){ + static sqlite3_vfs winVfs = { + 3, /* iVersion */ + sizeof(winFile), /* szOsFile */ + SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ + 0, /* pNext */ + "win32", /* zName */ + 0, /* pAppData */ + winOpen, /* xOpen */ + winDelete, /* xDelete */ + winAccess, /* xAccess */ + winFullPathname, /* xFullPathname */ + winDlOpen, /* xDlOpen */ + winDlError, /* xDlError */ + winDlSym, /* xDlSym */ + winDlClose, /* xDlClose */ + winRandomness, /* xRandomness */ + winSleep, /* xSleep */ + winCurrentTime, /* xCurrentTime */ + winGetLastError, /* xGetLastError */ + winCurrentTimeInt64, /* xCurrentTimeInt64 */ + winSetSystemCall, /* xSetSystemCall */ + winGetSystemCall, /* xGetSystemCall */ + winNextSystemCall, /* xNextSystemCall */ + }; +#if defined(SQLITE_WIN32_HAS_WIDE) + static sqlite3_vfs winLongPathVfs = { + 3, /* iVersion */ + sizeof(winFile), /* szOsFile */ + SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ + 0, /* pNext */ + "win32-longpath", /* zName */ + 0, /* pAppData */ + winOpen, /* xOpen */ + winDelete, /* xDelete */ + winAccess, /* xAccess */ + winFullPathname, /* xFullPathname */ + winDlOpen, /* xDlOpen */ + winDlError, /* xDlError */ + winDlSym, /* xDlSym */ + winDlClose, /* xDlClose */ + winRandomness, /* xRandomness */ + winSleep, /* xSleep */ + winCurrentTime, /* xCurrentTime */ + winGetLastError, /* xGetLastError */ + winCurrentTimeInt64, /* xCurrentTimeInt64 */ + winSetSystemCall, /* xSetSystemCall */ + winGetSystemCall, /* xGetSystemCall */ + winNextSystemCall, /* xNextSystemCall */ + }; +#endif + + /* Double-check that the aSyscall[] array has been constructed + ** correctly. See ticket [bb3a86e890c8e96ab] */ + assert( ArraySize(aSyscall)==75 ); + + /* get memory map allocation granularity */ + memset(&winSysInfo, 0, sizeof(SYSTEM_INFO)); +#if SQLITE_OS_WINRT + osGetNativeSystemInfo(&winSysInfo); +#else + osGetSystemInfo(&winSysInfo); +#endif + assert( winSysInfo.dwAllocationGranularity>0 ); + assert( winSysInfo.dwPageSize>0 ); + + sqlite3_vfs_register(&winVfs, 1); + +#if defined(SQLITE_WIN32_HAS_WIDE) + sqlite3_vfs_register(&winLongPathVfs, 0); +#endif + + return SQLITE_OK; +} + +int sqlite3_os_end(void){ +#if SQLITE_OS_WINRT + if( sleepObj!=NULL ){ + osCloseHandle(sleepObj); + sleepObj = NULL; + } +#endif + return SQLITE_OK; +} + +#endif /* SQLITE_OS_WIN */ diff --git a/components/external/SQLite-3.8.1/src/pager.c b/components/external/SQLite-3.8.1/src/pager.c new file mode 100644 index 0000000000000000000000000000000000000000..d675b85821ec2fd18e617311217330acb29b45e8 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/pager.c @@ -0,0 +1,7188 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the implementation of the page cache subsystem or "pager". +** +** The pager is used to access a database disk file. It implements +** atomic commit and rollback through the use of a journal file that +** is separate from the database file. The pager also implements file +** locking to prevent two processes from writing the same database +** file simultaneously, or one process from reading the database while +** another is writing. +*/ +#ifndef SQLITE_OMIT_DISKIO +#include "sqliteInt.h" +#include "wal.h" + + +/******************* NOTES ON THE DESIGN OF THE PAGER ************************ +** +** This comment block describes invariants that hold when using a rollback +** journal. These invariants do not apply for journal_mode=WAL, +** journal_mode=MEMORY, or journal_mode=OFF. +** +** Within this comment block, a page is deemed to have been synced +** automatically as soon as it is written when PRAGMA synchronous=OFF. +** Otherwise, the page is not synced until the xSync method of the VFS +** is called successfully on the file containing the page. +** +** Definition: A page of the database file is said to be "overwriteable" if +** one or more of the following are true about the page: +** +** (a) The original content of the page as it was at the beginning of +** the transaction has been written into the rollback journal and +** synced. +** +** (b) The page was a freelist leaf page at the start of the transaction. +** +** (c) The page number is greater than the largest page that existed in +** the database file at the start of the transaction. +** +** (1) A page of the database file is never overwritten unless one of the +** following are true: +** +** (a) The page and all other pages on the same sector are overwriteable. +** +** (b) The atomic page write optimization is enabled, and the entire +** transaction other than the update of the transaction sequence +** number consists of a single page change. +** +** (2) The content of a page written into the rollback journal exactly matches +** both the content in the database when the rollback journal was written +** and the content in the database at the beginning of the current +** transaction. +** +** (3) Writes to the database file are an integer multiple of the page size +** in length and are aligned on a page boundary. +** +** (4) Reads from the database file are either aligned on a page boundary and +** an integer multiple of the page size in length or are taken from the +** first 100 bytes of the database file. +** +** (5) All writes to the database file are synced prior to the rollback journal +** being deleted, truncated, or zeroed. +** +** (6) If a master journal file is used, then all writes to the database file +** are synced prior to the master journal being deleted. +** +** Definition: Two databases (or the same database at two points it time) +** are said to be "logically equivalent" if they give the same answer to +** all queries. Note in particular the content of freelist leaf +** pages can be changed arbitarily without effecting the logical equivalence +** of the database. +** +** (7) At any time, if any subset, including the empty set and the total set, +** of the unsynced changes to a rollback journal are removed and the +** journal is rolled back, the resulting database file will be logical +** equivalent to the database file at the beginning of the transaction. +** +** (8) When a transaction is rolled back, the xTruncate method of the VFS +** is called to restore the database file to the same size it was at +** the beginning of the transaction. (In some VFSes, the xTruncate +** method is a no-op, but that does not change the fact the SQLite will +** invoke it.) +** +** (9) Whenever the database file is modified, at least one bit in the range +** of bytes from 24 through 39 inclusive will be changed prior to releasing +** the EXCLUSIVE lock, thus signaling other connections on the same +** database to flush their caches. +** +** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less +** than one billion transactions. +** +** (11) A database file is well-formed at the beginning and at the conclusion +** of every transaction. +** +** (12) An EXCLUSIVE lock is held on the database file when writing to +** the database file. +** +** (13) A SHARED lock is held on the database file while reading any +** content out of the database file. +** +******************************************************************************/ + +/* +** Macros for troubleshooting. Normally turned off +*/ +#if 0 +int sqlite3PagerTrace=1; /* True to enable tracing */ +#define sqlite3DebugPrintf printf +#define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; } +#else +#define PAGERTRACE(X) +#endif + +/* +** The following two macros are used within the PAGERTRACE() macros above +** to print out file-descriptors. +** +** PAGERID() takes a pointer to a Pager struct as its argument. The +** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file +** struct as its argument. +*/ +#define PAGERID(p) ((int)(p->fd)) +#define FILEHANDLEID(fd) ((int)fd) + +/* +** The Pager.eState variable stores the current 'state' of a pager. A +** pager may be in any one of the seven states shown in the following +** state diagram. +** +** OPEN <------+------+ +** | | | +** V | | +** +---------> READER-------+ | +** | | | +** | V | +** |<-------WRITER_LOCKED------> ERROR +** | | ^ +** | V | +** |<------WRITER_CACHEMOD-------->| +** | | | +** | V | +** |<-------WRITER_DBMOD---------->| +** | | | +** | V | +** +<------WRITER_FINISHED-------->+ +** +** +** List of state transitions and the C [function] that performs each: +** +** OPEN -> READER [sqlite3PagerSharedLock] +** READER -> OPEN [pager_unlock] +** +** READER -> WRITER_LOCKED [sqlite3PagerBegin] +** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal] +** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal] +** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne] +** WRITER_*** -> READER [pager_end_transaction] +** +** WRITER_*** -> ERROR [pager_error] +** ERROR -> OPEN [pager_unlock] +** +** +** OPEN: +** +** The pager starts up in this state. Nothing is guaranteed in this +** state - the file may or may not be locked and the database size is +** unknown. The database may not be read or written. +** +** * No read or write transaction is active. +** * Any lock, or no lock at all, may be held on the database file. +** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted. +** +** READER: +** +** In this state all the requirements for reading the database in +** rollback (non-WAL) mode are met. Unless the pager is (or recently +** was) in exclusive-locking mode, a user-level read transaction is +** open. The database size is known in this state. +** +** A connection running with locking_mode=normal enters this state when +** it opens a read-transaction on the database and returns to state +** OPEN after the read-transaction is completed. However a connection +** running in locking_mode=exclusive (including temp databases) remains in +** this state even after the read-transaction is closed. The only way +** a locking_mode=exclusive connection can transition from READER to OPEN +** is via the ERROR state (see below). +** +** * A read transaction may be active (but a write-transaction cannot). +** * A SHARED or greater lock is held on the database file. +** * The dbSize variable may be trusted (even if a user-level read +** transaction is not active). The dbOrigSize and dbFileSize variables +** may not be trusted at this point. +** * If the database is a WAL database, then the WAL connection is open. +** * Even if a read-transaction is not open, it is guaranteed that +** there is no hot-journal in the file-system. +** +** WRITER_LOCKED: +** +** The pager moves to this state from READER when a write-transaction +** is first opened on the database. In WRITER_LOCKED state, all locks +** required to start a write-transaction are held, but no actual +** modifications to the cache or database have taken place. +** +** In rollback mode, a RESERVED or (if the transaction was opened with +** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when +** moving to this state, but the journal file is not written to or opened +** to in this state. If the transaction is committed or rolled back while +** in WRITER_LOCKED state, all that is required is to unlock the database +** file. +** +** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file. +** If the connection is running with locking_mode=exclusive, an attempt +** is made to obtain an EXCLUSIVE lock on the database file. +** +** * A write transaction is active. +** * If the connection is open in rollback-mode, a RESERVED or greater +** lock is held on the database file. +** * If the connection is open in WAL-mode, a WAL write transaction +** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully +** called). +** * The dbSize, dbOrigSize and dbFileSize variables are all valid. +** * The contents of the pager cache have not been modified. +** * The journal file may or may not be open. +** * Nothing (not even the first header) has been written to the journal. +** +** WRITER_CACHEMOD: +** +** A pager moves from WRITER_LOCKED state to this state when a page is +** first modified by the upper layer. In rollback mode the journal file +** is opened (if it is not already open) and a header written to the +** start of it. The database file on disk has not been modified. +** +** * A write transaction is active. +** * A RESERVED or greater lock is held on the database file. +** * The journal file is open and the first header has been written +** to it, but the header has not been synced to disk. +** * The contents of the page cache have been modified. +** +** WRITER_DBMOD: +** +** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state +** when it modifies the contents of the database file. WAL connections +** never enter this state (since they do not modify the database file, +** just the log file). +** +** * A write transaction is active. +** * An EXCLUSIVE or greater lock is held on the database file. +** * The journal file is open and the first header has been written +** and synced to disk. +** * The contents of the page cache have been modified (and possibly +** written to disk). +** +** WRITER_FINISHED: +** +** It is not possible for a WAL connection to enter this state. +** +** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD +** state after the entire transaction has been successfully written into the +** database file. In this state the transaction may be committed simply +** by finalizing the journal file. Once in WRITER_FINISHED state, it is +** not possible to modify the database further. At this point, the upper +** layer must either commit or rollback the transaction. +** +** * A write transaction is active. +** * An EXCLUSIVE or greater lock is held on the database file. +** * All writing and syncing of journal and database data has finished. +** If no error occurred, all that remains is to finalize the journal to +** commit the transaction. If an error did occur, the caller will need +** to rollback the transaction. +** +** ERROR: +** +** The ERROR state is entered when an IO or disk-full error (including +** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it +** difficult to be sure that the in-memory pager state (cache contents, +** db size etc.) are consistent with the contents of the file-system. +** +** Temporary pager files may enter the ERROR state, but in-memory pagers +** cannot. +** +** For example, if an IO error occurs while performing a rollback, +** the contents of the page-cache may be left in an inconsistent state. +** At this point it would be dangerous to change back to READER state +** (as usually happens after a rollback). Any subsequent readers might +** report database corruption (due to the inconsistent cache), and if +** they upgrade to writers, they may inadvertently corrupt the database +** file. To avoid this hazard, the pager switches into the ERROR state +** instead of READER following such an error. +** +** Once it has entered the ERROR state, any attempt to use the pager +** to read or write data returns an error. Eventually, once all +** outstanding transactions have been abandoned, the pager is able to +** transition back to OPEN state, discarding the contents of the +** page-cache and any other in-memory state at the same time. Everything +** is reloaded from disk (and, if necessary, hot-journal rollback peformed) +** when a read-transaction is next opened on the pager (transitioning +** the pager into READER state). At that point the system has recovered +** from the error. +** +** Specifically, the pager jumps into the ERROR state if: +** +** 1. An error occurs while attempting a rollback. This happens in +** function sqlite3PagerRollback(). +** +** 2. An error occurs while attempting to finalize a journal file +** following a commit in function sqlite3PagerCommitPhaseTwo(). +** +** 3. An error occurs while attempting to write to the journal or +** database file in function pagerStress() in order to free up +** memory. +** +** In other cases, the error is returned to the b-tree layer. The b-tree +** layer then attempts a rollback operation. If the error condition +** persists, the pager enters the ERROR state via condition (1) above. +** +** Condition (3) is necessary because it can be triggered by a read-only +** statement executed within a transaction. In this case, if the error +** code were simply returned to the user, the b-tree layer would not +** automatically attempt a rollback, as it assumes that an error in a +** read-only statement cannot leave the pager in an internally inconsistent +** state. +** +** * The Pager.errCode variable is set to something other than SQLITE_OK. +** * There are one or more outstanding references to pages (after the +** last reference is dropped the pager should move back to OPEN state). +** * The pager is not an in-memory pager. +** +** +** Notes: +** +** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the +** connection is open in WAL mode. A WAL connection is always in one +** of the first four states. +** +** * Normally, a connection open in exclusive mode is never in PAGER_OPEN +** state. There are two exceptions: immediately after exclusive-mode has +** been turned on (and before any read or write transactions are +** executed), and when the pager is leaving the "error state". +** +** * See also: assert_pager_state(). +*/ +#define PAGER_OPEN 0 +#define PAGER_READER 1 +#define PAGER_WRITER_LOCKED 2 +#define PAGER_WRITER_CACHEMOD 3 +#define PAGER_WRITER_DBMOD 4 +#define PAGER_WRITER_FINISHED 5 +#define PAGER_ERROR 6 + +/* +** The Pager.eLock variable is almost always set to one of the +** following locking-states, according to the lock currently held on +** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. +** This variable is kept up to date as locks are taken and released by +** the pagerLockDb() and pagerUnlockDb() wrappers. +** +** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY +** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not +** the operation was successful. In these circumstances pagerLockDb() and +** pagerUnlockDb() take a conservative approach - eLock is always updated +** when unlocking the file, and only updated when locking the file if the +** VFS call is successful. This way, the Pager.eLock variable may be set +** to a less exclusive (lower) value than the lock that is actually held +** at the system level, but it is never set to a more exclusive value. +** +** This is usually safe. If an xUnlock fails or appears to fail, there may +** be a few redundant xLock() calls or a lock may be held for longer than +** required, but nothing really goes wrong. +** +** The exception is when the database file is unlocked as the pager moves +** from ERROR to OPEN state. At this point there may be a hot-journal file +** in the file-system that needs to be rolled back (as part of a OPEN->SHARED +** transition, by the same pager or any other). If the call to xUnlock() +** fails at this point and the pager is left holding an EXCLUSIVE lock, this +** can confuse the call to xCheckReservedLock() call made later as part +** of hot-journal detection. +** +** xCheckReservedLock() is defined as returning true "if there is a RESERVED +** lock held by this process or any others". So xCheckReservedLock may +** return true because the caller itself is holding an EXCLUSIVE lock (but +** doesn't know it because of a previous error in xUnlock). If this happens +** a hot-journal may be mistaken for a journal being created by an active +** transaction in another process, causing SQLite to read from the database +** without rolling it back. +** +** To work around this, if a call to xUnlock() fails when unlocking the +** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It +** is only changed back to a real locking state after a successful call +** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition +** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK +** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE +** lock on the database file before attempting to roll it back. See function +** PagerSharedLock() for more detail. +** +** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in +** PAGER_OPEN state. +*/ +#define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1) + +/* +** A macro used for invoking the codec if there is one +*/ +#ifdef SQLITE_HAS_CODEC +# define CODEC1(P,D,N,X,E) \ + if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; } +# define CODEC2(P,D,N,X,E,O) \ + if( P->xCodec==0 ){ O=(char*)D; }else \ + if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; } +#else +# define CODEC1(P,D,N,X,E) /* NO-OP */ +# define CODEC2(P,D,N,X,E,O) O=(char*)D +#endif + +/* +** The maximum allowed sector size. 64KiB. If the xSectorsize() method +** returns a value larger than this, then MAX_SECTOR_SIZE is used instead. +** This could conceivably cause corruption following a power failure on +** such a system. This is currently an undocumented limit. +*/ +#define MAX_SECTOR_SIZE 0x10000 + +/* +** An instance of the following structure is allocated for each active +** savepoint and statement transaction in the system. All such structures +** are stored in the Pager.aSavepoint[] array, which is allocated and +** resized using sqlite3Realloc(). +** +** When a savepoint is created, the PagerSavepoint.iHdrOffset field is +** set to 0. If a journal-header is written into the main journal while +** the savepoint is active, then iHdrOffset is set to the byte offset +** immediately following the last journal record written into the main +** journal before the journal-header. This is required during savepoint +** rollback (see pagerPlaybackSavepoint()). +*/ +typedef struct PagerSavepoint PagerSavepoint; +struct PagerSavepoint { + i64 iOffset; /* Starting offset in main journal */ + i64 iHdrOffset; /* See above */ + Bitvec *pInSavepoint; /* Set of pages in this savepoint */ + Pgno nOrig; /* Original number of pages in file */ + Pgno iSubRec; /* Index of first record in sub-journal */ +#ifndef SQLITE_OMIT_WAL + u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */ +#endif +}; + +/* +** Bits of the Pager.doNotSpill flag. See further description below. +*/ +#define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */ +#define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */ +#define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */ + +/* +** A open page cache is an instance of struct Pager. A description of +** some of the more important member variables follows: +** +** eState +** +** The current 'state' of the pager object. See the comment and state +** diagram above for a description of the pager state. +** +** eLock +** +** For a real on-disk database, the current lock held on the database file - +** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. +** +** For a temporary or in-memory database (neither of which require any +** locks), this variable is always set to EXCLUSIVE_LOCK. Since such +** databases always have Pager.exclusiveMode==1, this tricks the pager +** logic into thinking that it already has all the locks it will ever +** need (and no reason to release them). +** +** In some (obscure) circumstances, this variable may also be set to +** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for +** details. +** +** changeCountDone +** +** This boolean variable is used to make sure that the change-counter +** (the 4-byte header field at byte offset 24 of the database file) is +** not updated more often than necessary. +** +** It is set to true when the change-counter field is updated, which +** can only happen if an exclusive lock is held on the database file. +** It is cleared (set to false) whenever an exclusive lock is +** relinquished on the database file. Each time a transaction is committed, +** The changeCountDone flag is inspected. If it is true, the work of +** updating the change-counter is omitted for the current transaction. +** +** This mechanism means that when running in exclusive mode, a connection +** need only update the change-counter once, for the first transaction +** committed. +** +** setMaster +** +** When PagerCommitPhaseOne() is called to commit a transaction, it may +** (or may not) specify a master-journal name to be written into the +** journal file before it is synced to disk. +** +** Whether or not a journal file contains a master-journal pointer affects +** the way in which the journal file is finalized after the transaction is +** committed or rolled back when running in "journal_mode=PERSIST" mode. +** If a journal file does not contain a master-journal pointer, it is +** finalized by overwriting the first journal header with zeroes. If +** it does contain a master-journal pointer the journal file is finalized +** by truncating it to zero bytes, just as if the connection were +** running in "journal_mode=truncate" mode. +** +** Journal files that contain master journal pointers cannot be finalized +** simply by overwriting the first journal-header with zeroes, as the +** master journal pointer could interfere with hot-journal rollback of any +** subsequently interrupted transaction that reuses the journal file. +** +** The flag is cleared as soon as the journal file is finalized (either +** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the +** journal file from being successfully finalized, the setMaster flag +** is cleared anyway (and the pager will move to ERROR state). +** +** doNotSpill +** +** This variables control the behavior of cache-spills (calls made by +** the pcache module to the pagerStress() routine to write cached data +** to the file-system in order to free up memory). +** +** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set, +** writing to the database from pagerStress() is disabled altogether. +** The SPILLFLAG_ROLLBACK case is done in a very obscure case that +** comes up during savepoint rollback that requires the pcache module +** to allocate a new page to prevent the journal file from being written +** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF +** case is a user preference. +** +** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress() +** is permitted, but syncing the journal file is not. This flag is set +** by sqlite3PagerWrite() when the file-system sector-size is larger than +** the database page-size in order to prevent a journal sync from happening +** in between the journalling of two pages on the same sector. +** +** subjInMemory +** +** This is a boolean variable. If true, then any required sub-journal +** is opened as an in-memory journal file. If false, then in-memory +** sub-journals are only used for in-memory pager files. +** +** This variable is updated by the upper layer each time a new +** write-transaction is opened. +** +** dbSize, dbOrigSize, dbFileSize +** +** Variable dbSize is set to the number of pages in the database file. +** It is valid in PAGER_READER and higher states (all states except for +** OPEN and ERROR). +** +** dbSize is set based on the size of the database file, which may be +** larger than the size of the database (the value stored at offset +** 28 of the database header by the btree). If the size of the file +** is not an integer multiple of the page-size, the value stored in +** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2). +** Except, any file that is greater than 0 bytes in size is considered +** to have at least one page. (i.e. a 1KB file with 2K page-size leads +** to dbSize==1). +** +** During a write-transaction, if pages with page-numbers greater than +** dbSize are modified in the cache, dbSize is updated accordingly. +** Similarly, if the database is truncated using PagerTruncateImage(), +** dbSize is updated. +** +** Variables dbOrigSize and dbFileSize are valid in states +** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize +** variable at the start of the transaction. It is used during rollback, +** and to determine whether or not pages need to be journalled before +** being modified. +** +** Throughout a write-transaction, dbFileSize contains the size of +** the file on disk in pages. It is set to a copy of dbSize when the +** write-transaction is first opened, and updated when VFS calls are made +** to write or truncate the database file on disk. +** +** The only reason the dbFileSize variable is required is to suppress +** unnecessary calls to xTruncate() after committing a transaction. If, +** when a transaction is committed, the dbFileSize variable indicates +** that the database file is larger than the database image (Pager.dbSize), +** pager_truncate() is called. The pager_truncate() call uses xFilesize() +** to measure the database file on disk, and then truncates it if required. +** dbFileSize is not used when rolling back a transaction. In this case +** pager_truncate() is called unconditionally (which means there may be +** a call to xFilesize() that is not strictly required). In either case, +** pager_truncate() may cause the file to become smaller or larger. +** +** dbHintSize +** +** The dbHintSize variable is used to limit the number of calls made to +** the VFS xFileControl(FCNTL_SIZE_HINT) method. +** +** dbHintSize is set to a copy of the dbSize variable when a +** write-transaction is opened (at the same time as dbFileSize and +** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called, +** dbHintSize is increased to the number of pages that correspond to the +** size-hint passed to the method call. See pager_write_pagelist() for +** details. +** +** errCode +** +** The Pager.errCode variable is only ever used in PAGER_ERROR state. It +** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode +** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX +** sub-codes. +*/ +struct Pager { + sqlite3_vfs *pVfs; /* OS functions to use for IO */ + u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */ + u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */ + u8 useJournal; /* Use a rollback journal on this file */ + u8 noSync; /* Do not sync the journal if true */ + u8 fullSync; /* Do extra syncs of the journal for robustness */ + u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */ + u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */ + u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */ + u8 tempFile; /* zFilename is a temporary file */ + u8 readOnly; /* True for a read-only database */ + u8 memDb; /* True to inhibit all file I/O */ + + /************************************************************************** + ** The following block contains those class members that change during + ** routine opertion. Class members not in this block are either fixed + ** when the pager is first created or else only change when there is a + ** significant mode change (such as changing the page_size, locking_mode, + ** or the journal_mode). From another view, these class members describe + ** the "state" of the pager, while other class members describe the + ** "configuration" of the pager. + */ + u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */ + u8 eLock; /* Current lock held on database file */ + u8 changeCountDone; /* Set after incrementing the change-counter */ + u8 setMaster; /* True if a m-j name has been written to jrnl */ + u8 doNotSpill; /* Do not spill the cache when non-zero */ + u8 subjInMemory; /* True to use in-memory sub-journals */ + Pgno dbSize; /* Number of pages in the database */ + Pgno dbOrigSize; /* dbSize before the current transaction */ + Pgno dbFileSize; /* Number of pages in the database file */ + Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */ + int errCode; /* One of several kinds of errors */ + int nRec; /* Pages journalled since last j-header written */ + u32 cksumInit; /* Quasi-random value added to every checksum */ + u32 nSubRec; /* Number of records written to sub-journal */ + Bitvec *pInJournal; /* One bit for each page in the database file */ + sqlite3_file *fd; /* File descriptor for database */ + sqlite3_file *jfd; /* File descriptor for main journal */ + sqlite3_file *sjfd; /* File descriptor for sub-journal */ + i64 journalOff; /* Current write offset in the journal file */ + i64 journalHdr; /* Byte offset to previous journal header */ + sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */ + PagerSavepoint *aSavepoint; /* Array of active savepoints */ + int nSavepoint; /* Number of elements in aSavepoint[] */ + char dbFileVers[16]; /* Changes whenever database file changes */ + + u8 bUseFetch; /* True to use xFetch() */ + int nMmapOut; /* Number of mmap pages currently outstanding */ + sqlite3_int64 szMmap; /* Desired maximum mmap size */ + PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */ + /* + ** End of the routinely-changing class members + ***************************************************************************/ + + u16 nExtra; /* Add this many bytes to each in-memory page */ + i16 nReserve; /* Number of unused bytes at end of each page */ + u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */ + u32 sectorSize; /* Assumed sector size during rollback */ + int pageSize; /* Number of bytes in a page */ + Pgno mxPgno; /* Maximum allowed size of the database */ + i64 journalSizeLimit; /* Size limit for persistent journal files */ + char *zFilename; /* Name of the database file */ + char *zJournal; /* Name of the journal file */ + int (*xBusyHandler)(void*); /* Function to call when busy */ + void *pBusyHandlerArg; /* Context argument for xBusyHandler */ + int aStat[3]; /* Total cache hits, misses and writes */ +#ifdef SQLITE_TEST + int nRead; /* Database pages read */ +#endif + void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */ +#ifdef SQLITE_HAS_CODEC + void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ + void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ + void (*xCodecFree)(void*); /* Destructor for the codec */ + void *pCodec; /* First argument to xCodec... methods */ +#endif + char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */ + PCache *pPCache; /* Pointer to page cache object */ +#ifndef SQLITE_OMIT_WAL + Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */ + char *zWal; /* File name for write-ahead log */ +#endif +}; + +/* +** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains +** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS +** or CACHE_WRITE to sqlite3_db_status(). +*/ +#define PAGER_STAT_HIT 0 +#define PAGER_STAT_MISS 1 +#define PAGER_STAT_WRITE 2 + +/* +** The following global variables hold counters used for +** testing purposes only. These variables do not exist in +** a non-testing build. These variables are not thread-safe. +*/ +#ifdef SQLITE_TEST +int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ +int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ +int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */ +# define PAGER_INCR(v) v++ +#else +# define PAGER_INCR(v) +#endif + + + +/* +** Journal files begin with the following magic string. The data +** was obtained from /dev/random. It is used only as a sanity check. +** +** Since version 2.8.0, the journal format contains additional sanity +** checking information. If the power fails while the journal is being +** written, semi-random garbage data might appear in the journal +** file after power is restored. If an attempt is then made +** to roll the journal back, the database could be corrupted. The additional +** sanity checking data is an attempt to discover the garbage in the +** journal and ignore it. +** +** The sanity checking information for the new journal format consists +** of a 32-bit checksum on each page of data. The checksum covers both +** the page number and the pPager->pageSize bytes of data for the page. +** This cksum is initialized to a 32-bit random value that appears in the +** journal file right after the header. The random initializer is important, +** because garbage data that appears at the end of a journal is likely +** data that was once in other files that have now been deleted. If the +** garbage data came from an obsolete journal file, the checksums might +** be correct. But by initializing the checksum to random value which +** is different for every journal, we minimize that risk. +*/ +static const unsigned char aJournalMagic[] = { + 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7, +}; + +/* +** The size of the of each page record in the journal is given by +** the following macro. +*/ +#define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8) + +/* +** The journal header size for this pager. This is usually the same +** size as a single disk sector. See also setSectorSize(). +*/ +#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize) + +/* +** The macro MEMDB is true if we are dealing with an in-memory database. +** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set, +** the value of MEMDB will be a constant and the compiler will optimize +** out code that would never execute. +*/ +#ifdef SQLITE_OMIT_MEMORYDB +# define MEMDB 0 +#else +# define MEMDB pPager->memDb +#endif + +/* +** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch +** interfaces to access the database using memory-mapped I/O. +*/ +#if SQLITE_MAX_MMAP_SIZE>0 +# define USEFETCH(x) ((x)->bUseFetch) +#else +# define USEFETCH(x) 0 +#endif + +/* +** The maximum legal page number is (2^31 - 1). +*/ +#define PAGER_MAX_PGNO 2147483647 + +/* +** The argument to this macro is a file descriptor (type sqlite3_file*). +** Return 0 if it is not open, or non-zero (but not 1) if it is. +** +** This is so that expressions can be written as: +** +** if( isOpen(pPager->jfd) ){ ... +** +** instead of +** +** if( pPager->jfd->pMethods ){ ... +*/ +#define isOpen(pFd) ((pFd)->pMethods) + +/* +** Return true if this pager uses a write-ahead log instead of the usual +** rollback journal. Otherwise false. +*/ +#ifndef SQLITE_OMIT_WAL +static int pagerUseWal(Pager *pPager){ + return (pPager->pWal!=0); +} +#else +# define pagerUseWal(x) 0 +# define pagerRollbackWal(x) 0 +# define pagerWalFrames(v,w,x,y) 0 +# define pagerOpenWalIfPresent(z) SQLITE_OK +# define pagerBeginReadTransaction(z) SQLITE_OK +#endif + +#ifndef NDEBUG +/* +** Usage: +** +** assert( assert_pager_state(pPager) ); +** +** This function runs many asserts to try to find inconsistencies in +** the internal state of the Pager object. +*/ +static int assert_pager_state(Pager *p){ + Pager *pPager = p; + + /* State must be valid. */ + assert( p->eState==PAGER_OPEN + || p->eState==PAGER_READER + || p->eState==PAGER_WRITER_LOCKED + || p->eState==PAGER_WRITER_CACHEMOD + || p->eState==PAGER_WRITER_DBMOD + || p->eState==PAGER_WRITER_FINISHED + || p->eState==PAGER_ERROR + ); + + /* Regardless of the current state, a temp-file connection always behaves + ** as if it has an exclusive lock on the database file. It never updates + ** the change-counter field, so the changeCountDone flag is always set. + */ + assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK ); + assert( p->tempFile==0 || pPager->changeCountDone ); + + /* If the useJournal flag is clear, the journal-mode must be "OFF". + ** And if the journal-mode is "OFF", the journal file must not be open. + */ + assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal ); + assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) ); + + /* Check that MEMDB implies noSync. And an in-memory journal. Since + ** this means an in-memory pager performs no IO at all, it cannot encounter + ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing + ** a journal file. (although the in-memory journal implementation may + ** return SQLITE_IOERR_NOMEM while the journal file is being written). It + ** is therefore not possible for an in-memory pager to enter the ERROR + ** state. + */ + if( MEMDB ){ + assert( p->noSync ); + assert( p->journalMode==PAGER_JOURNALMODE_OFF + || p->journalMode==PAGER_JOURNALMODE_MEMORY + ); + assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN ); + assert( pagerUseWal(p)==0 ); + } + + /* If changeCountDone is set, a RESERVED lock or greater must be held + ** on the file. + */ + assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK ); + assert( p->eLock!=PENDING_LOCK ); + + switch( p->eState ){ + case PAGER_OPEN: + assert( !MEMDB ); + assert( pPager->errCode==SQLITE_OK ); + assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile ); + break; + + case PAGER_READER: + assert( pPager->errCode==SQLITE_OK ); + assert( p->eLock!=UNKNOWN_LOCK ); + assert( p->eLock>=SHARED_LOCK ); + break; + + case PAGER_WRITER_LOCKED: + assert( p->eLock!=UNKNOWN_LOCK ); + assert( pPager->errCode==SQLITE_OK ); + if( !pagerUseWal(pPager) ){ + assert( p->eLock>=RESERVED_LOCK ); + } + assert( pPager->dbSize==pPager->dbOrigSize ); + assert( pPager->dbOrigSize==pPager->dbFileSize ); + assert( pPager->dbOrigSize==pPager->dbHintSize ); + assert( pPager->setMaster==0 ); + break; + + case PAGER_WRITER_CACHEMOD: + assert( p->eLock!=UNKNOWN_LOCK ); + assert( pPager->errCode==SQLITE_OK ); + if( !pagerUseWal(pPager) ){ + /* It is possible that if journal_mode=wal here that neither the + ** journal file nor the WAL file are open. This happens during + ** a rollback transaction that switches from journal_mode=off + ** to journal_mode=wal. + */ + assert( p->eLock>=RESERVED_LOCK ); + assert( isOpen(p->jfd) + || p->journalMode==PAGER_JOURNALMODE_OFF + || p->journalMode==PAGER_JOURNALMODE_WAL + ); + } + assert( pPager->dbOrigSize==pPager->dbFileSize ); + assert( pPager->dbOrigSize==pPager->dbHintSize ); + break; + + case PAGER_WRITER_DBMOD: + assert( p->eLock==EXCLUSIVE_LOCK ); + assert( pPager->errCode==SQLITE_OK ); + assert( !pagerUseWal(pPager) ); + assert( p->eLock>=EXCLUSIVE_LOCK ); + assert( isOpen(p->jfd) + || p->journalMode==PAGER_JOURNALMODE_OFF + || p->journalMode==PAGER_JOURNALMODE_WAL + ); + assert( pPager->dbOrigSize<=pPager->dbHintSize ); + break; + + case PAGER_WRITER_FINISHED: + assert( p->eLock==EXCLUSIVE_LOCK ); + assert( pPager->errCode==SQLITE_OK ); + assert( !pagerUseWal(pPager) ); + assert( isOpen(p->jfd) + || p->journalMode==PAGER_JOURNALMODE_OFF + || p->journalMode==PAGER_JOURNALMODE_WAL + ); + break; + + case PAGER_ERROR: + /* There must be at least one outstanding reference to the pager if + ** in ERROR state. Otherwise the pager should have already dropped + ** back to OPEN state. + */ + assert( pPager->errCode!=SQLITE_OK ); + assert( sqlite3PcacheRefCount(pPager->pPCache)>0 ); + break; + } + + return 1; +} +#endif /* ifndef NDEBUG */ + +#ifdef SQLITE_DEBUG +/* +** Return a pointer to a human readable string in a static buffer +** containing the state of the Pager object passed as an argument. This +** is intended to be used within debuggers. For example, as an alternative +** to "print *pPager" in gdb: +** +** (gdb) printf "%s", print_pager_state(pPager) +*/ +static char *print_pager_state(Pager *p){ + static char zRet[1024]; + + sqlite3_snprintf(1024, zRet, + "Filename: %s\n" + "State: %s errCode=%d\n" + "Lock: %s\n" + "Locking mode: locking_mode=%s\n" + "Journal mode: journal_mode=%s\n" + "Backing store: tempFile=%d memDb=%d useJournal=%d\n" + "Journal: journalOff=%lld journalHdr=%lld\n" + "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n" + , p->zFilename + , p->eState==PAGER_OPEN ? "OPEN" : + p->eState==PAGER_READER ? "READER" : + p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" : + p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" : + p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" : + p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" : + p->eState==PAGER_ERROR ? "ERROR" : "?error?" + , (int)p->errCode + , p->eLock==NO_LOCK ? "NO_LOCK" : + p->eLock==RESERVED_LOCK ? "RESERVED" : + p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" : + p->eLock==SHARED_LOCK ? "SHARED" : + p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?" + , p->exclusiveMode ? "exclusive" : "normal" + , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" : + p->journalMode==PAGER_JOURNALMODE_OFF ? "off" : + p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" : + p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" : + p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" : + p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?" + , (int)p->tempFile, (int)p->memDb, (int)p->useJournal + , p->journalOff, p->journalHdr + , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize + ); + + return zRet; +} +#endif + +/* +** Return true if it is necessary to write page *pPg into the sub-journal. +** A page needs to be written into the sub-journal if there exists one +** or more open savepoints for which: +** +** * The page-number is less than or equal to PagerSavepoint.nOrig, and +** * The bit corresponding to the page-number is not set in +** PagerSavepoint.pInSavepoint. +*/ +static int subjRequiresPage(PgHdr *pPg){ + Pager *pPager = pPg->pPager; + PagerSavepoint *p; + Pgno pgno; + int i; + if( pPager->nSavepoint ){ + pgno = pPg->pgno; + for(i=0; inSavepoint; i++){ + p = &pPager->aSavepoint[i]; + if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){ + return 1; + } + } + } + return 0; +} + +/* +** Return true if the page is already in the journal file. +*/ +static int pageInJournal(PgHdr *pPg){ + return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno); +} + +/* +** Read a 32-bit integer from the given file descriptor. Store the integer +** that is read in *pRes. Return SQLITE_OK if everything worked, or an +** error code is something goes wrong. +** +** All values are stored on disk as big-endian. +*/ +static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){ + unsigned char ac[4]; + int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset); + if( rc==SQLITE_OK ){ + *pRes = sqlite3Get4byte(ac); + } + return rc; +} + +/* +** Write a 32-bit integer into a string buffer in big-endian byte order. +*/ +#define put32bits(A,B) sqlite3Put4byte((u8*)A,B) + + +/* +** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK +** on success or an error code is something goes wrong. +*/ +static int write32bits(sqlite3_file *fd, i64 offset, u32 val){ + char ac[4]; + put32bits(ac, val); + return sqlite3OsWrite(fd, ac, 4, offset); +} + +/* +** Unlock the database file to level eLock, which must be either NO_LOCK +** or SHARED_LOCK. Regardless of whether or not the call to xUnlock() +** succeeds, set the Pager.eLock variable to match the (attempted) new lock. +** +** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is +** called, do not modify it. See the comment above the #define of +** UNKNOWN_LOCK for an explanation of this. +*/ +static int pagerUnlockDb(Pager *pPager, int eLock){ + int rc = SQLITE_OK; + + assert( !pPager->exclusiveMode || pPager->eLock==eLock ); + assert( eLock==NO_LOCK || eLock==SHARED_LOCK ); + assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 ); + if( isOpen(pPager->fd) ){ + assert( pPager->eLock>=eLock ); + rc = sqlite3OsUnlock(pPager->fd, eLock); + if( pPager->eLock!=UNKNOWN_LOCK ){ + pPager->eLock = (u8)eLock; + } + IOTRACE(("UNLOCK %p %d\n", pPager, eLock)) + } + return rc; +} + +/* +** Lock the database file to level eLock, which must be either SHARED_LOCK, +** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the +** Pager.eLock variable to the new locking state. +** +** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is +** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. +** See the comment above the #define of UNKNOWN_LOCK for an explanation +** of this. +*/ +static int pagerLockDb(Pager *pPager, int eLock){ + int rc = SQLITE_OK; + + assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK ); + if( pPager->eLockeLock==UNKNOWN_LOCK ){ + rc = sqlite3OsLock(pPager->fd, eLock); + if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){ + pPager->eLock = (u8)eLock; + IOTRACE(("LOCK %p %d\n", pPager, eLock)) + } + } + return rc; +} + +/* +** This function determines whether or not the atomic-write optimization +** can be used with this pager. The optimization can be used if: +** +** (a) the value returned by OsDeviceCharacteristics() indicates that +** a database page may be written atomically, and +** (b) the value returned by OsSectorSize() is less than or equal +** to the page size. +** +** The optimization is also always enabled for temporary files. It is +** an error to call this function if pPager is opened on an in-memory +** database. +** +** If the optimization cannot be used, 0 is returned. If it can be used, +** then the value returned is the size of the journal file when it +** contains rollback data for exactly one page. +*/ +#ifdef SQLITE_ENABLE_ATOMIC_WRITE +static int jrnlBufferSize(Pager *pPager){ + assert( !MEMDB ); + if( !pPager->tempFile ){ + int dc; /* Device characteristics */ + int nSector; /* Sector size */ + int szPage; /* Page size */ + + assert( isOpen(pPager->fd) ); + dc = sqlite3OsDeviceCharacteristics(pPager->fd); + nSector = pPager->sectorSize; + szPage = pPager->pageSize; + + assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); + assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); + if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){ + return 0; + } + } + + return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager); +} +#endif + +/* +** If SQLITE_CHECK_PAGES is defined then we do some sanity checking +** on the cache using a hash function. This is used for testing +** and debugging only. +*/ +#ifdef SQLITE_CHECK_PAGES +/* +** Return a 32-bit hash of the page data for pPage. +*/ +static u32 pager_datahash(int nByte, unsigned char *pData){ + u32 hash = 0; + int i; + for(i=0; ipPager->pageSize, (unsigned char *)pPage->pData); +} +static void pager_set_pagehash(PgHdr *pPage){ + pPage->pageHash = pager_pagehash(pPage); +} + +/* +** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES +** is defined, and NDEBUG is not defined, an assert() statement checks +** that the page is either dirty or still matches the calculated page-hash. +*/ +#define CHECK_PAGE(x) checkPage(x) +static void checkPage(PgHdr *pPg){ + Pager *pPager = pPg->pPager; + assert( pPager->eState!=PAGER_ERROR ); + assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) ); +} + +#else +#define pager_datahash(X,Y) 0 +#define pager_pagehash(X) 0 +#define pager_set_pagehash(X) +#define CHECK_PAGE(x) +#endif /* SQLITE_CHECK_PAGES */ + +/* +** When this is called the journal file for pager pPager must be open. +** This function attempts to read a master journal file name from the +** end of the file and, if successful, copies it into memory supplied +** by the caller. See comments above writeMasterJournal() for the format +** used to store a master journal file name at the end of a journal file. +** +** zMaster must point to a buffer of at least nMaster bytes allocated by +** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is +** enough space to write the master journal name). If the master journal +** name in the journal is longer than nMaster bytes (including a +** nul-terminator), then this is handled as if no master journal name +** were present in the journal. +** +** If a master journal file name is present at the end of the journal +** file, then it is copied into the buffer pointed to by zMaster. A +** nul-terminator byte is appended to the buffer following the master +** journal file name. +** +** If it is determined that no master journal file name is present +** zMaster[0] is set to 0 and SQLITE_OK returned. +** +** If an error occurs while reading from the journal file, an SQLite +** error code is returned. +*/ +static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){ + int rc; /* Return code */ + u32 len; /* Length in bytes of master journal name */ + i64 szJ; /* Total size in bytes of journal file pJrnl */ + u32 cksum; /* MJ checksum value read from journal */ + u32 u; /* Unsigned loop counter */ + unsigned char aMagic[8]; /* A buffer to hold the magic header */ + zMaster[0] = '\0'; + + if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ)) + || szJ<16 + || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len)) + || len>=nMaster + || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum)) + || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8)) + || memcmp(aMagic, aJournalMagic, 8) + || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len)) + ){ + return rc; + } + + /* See if the checksum matches the master journal name */ + for(u=0; ujournalOff, assuming a sector +** size of pPager->sectorSize bytes. +** +** i.e for a sector size of 512: +** +** Pager.journalOff Return value +** --------------------------------------- +** 0 0 +** 512 512 +** 100 512 +** 2000 2048 +** +*/ +static i64 journalHdrOffset(Pager *pPager){ + i64 offset = 0; + i64 c = pPager->journalOff; + if( c ){ + offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager); + } + assert( offset%JOURNAL_HDR_SZ(pPager)==0 ); + assert( offset>=c ); + assert( (offset-c)jfd) ); + if( pPager->journalOff ){ + const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */ + + IOTRACE(("JZEROHDR %p\n", pPager)) + if( doTruncate || iLimit==0 ){ + rc = sqlite3OsTruncate(pPager->jfd, 0); + }else{ + static const char zeroHdr[28] = {0}; + rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0); + } + if( rc==SQLITE_OK && !pPager->noSync ){ + rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags); + } + + /* At this point the transaction is committed but the write lock + ** is still held on the file. If there is a size limit configured for + ** the persistent journal and the journal file currently consumes more + ** space than that limit allows for, truncate it now. There is no need + ** to sync the file following this operation. + */ + if( rc==SQLITE_OK && iLimit>0 ){ + i64 sz; + rc = sqlite3OsFileSize(pPager->jfd, &sz); + if( rc==SQLITE_OK && sz>iLimit ){ + rc = sqlite3OsTruncate(pPager->jfd, iLimit); + } + } + } + return rc; +} + +/* +** The journal file must be open when this routine is called. A journal +** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the +** current location. +** +** The format for the journal header is as follows: +** - 8 bytes: Magic identifying journal format. +** - 4 bytes: Number of records in journal, or -1 no-sync mode is on. +** - 4 bytes: Random number used for page hash. +** - 4 bytes: Initial database page count. +** - 4 bytes: Sector size used by the process that wrote this journal. +** - 4 bytes: Database page size. +** +** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space. +*/ +static int writeJournalHdr(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */ + u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */ + u32 nWrite; /* Bytes of header sector written */ + int ii; /* Loop counter */ + + assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ + + if( nHeader>JOURNAL_HDR_SZ(pPager) ){ + nHeader = JOURNAL_HDR_SZ(pPager); + } + + /* If there are active savepoints and any of them were created + ** since the most recent journal header was written, update the + ** PagerSavepoint.iHdrOffset fields now. + */ + for(ii=0; iinSavepoint; ii++){ + if( pPager->aSavepoint[ii].iHdrOffset==0 ){ + pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff; + } + } + + pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager); + + /* + ** Write the nRec Field - the number of page records that follow this + ** journal header. Normally, zero is written to this value at this time. + ** After the records are added to the journal (and the journal synced, + ** if in full-sync mode), the zero is overwritten with the true number + ** of records (see syncJournal()). + ** + ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When + ** reading the journal this value tells SQLite to assume that the + ** rest of the journal file contains valid page records. This assumption + ** is dangerous, as if a failure occurred whilst writing to the journal + ** file it may contain some garbage data. There are two scenarios + ** where this risk can be ignored: + ** + ** * When the pager is in no-sync mode. Corruption can follow a + ** power failure in this case anyway. + ** + ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees + ** that garbage data is never appended to the journal file. + */ + assert( isOpen(pPager->fd) || pPager->noSync ); + if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY) + || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) + ){ + memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); + put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff); + }else{ + memset(zHeader, 0, sizeof(aJournalMagic)+4); + } + + /* The random check-hash initializer */ + sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit); + put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit); + /* The initial database size */ + put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize); + /* The assumed sector size for this process */ + put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize); + + /* The page size */ + put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize); + + /* Initializing the tail of the buffer is not necessary. Everything + ** works find if the following memset() is omitted. But initializing + ** the memory prevents valgrind from complaining, so we are willing to + ** take the performance hit. + */ + memset(&zHeader[sizeof(aJournalMagic)+20], 0, + nHeader-(sizeof(aJournalMagic)+20)); + + /* In theory, it is only necessary to write the 28 bytes that the + ** journal header consumes to the journal file here. Then increment the + ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next + ** record is written to the following sector (leaving a gap in the file + ** that will be implicitly filled in by the OS). + ** + ** However it has been discovered that on some systems this pattern can + ** be significantly slower than contiguously writing data to the file, + ** even if that means explicitly writing data to the block of + ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what + ** is done. + ** + ** The loop is required here in case the sector-size is larger than the + ** database page size. Since the zHeader buffer is only Pager.pageSize + ** bytes in size, more than one call to sqlite3OsWrite() may be required + ** to populate the entire journal header sector. + */ + for(nWrite=0; rc==SQLITE_OK&&nWritejournalHdr, nHeader)) + rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff); + assert( pPager->journalHdr <= pPager->journalOff ); + pPager->journalOff += nHeader; + } + + return rc; +} + +/* +** The journal file must be open when this is called. A journal header file +** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal +** file. The current location in the journal file is given by +** pPager->journalOff. See comments above function writeJournalHdr() for +** a description of the journal header format. +** +** If the header is read successfully, *pNRec is set to the number of +** page records following this header and *pDbSize is set to the size of the +** database before the transaction began, in pages. Also, pPager->cksumInit +** is set to the value read from the journal header. SQLITE_OK is returned +** in this case. +** +** If the journal header file appears to be corrupted, SQLITE_DONE is +** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes +** cannot be read from the journal file an error code is returned. +*/ +static int readJournalHdr( + Pager *pPager, /* Pager object */ + int isHot, + i64 journalSize, /* Size of the open journal file in bytes */ + u32 *pNRec, /* OUT: Value read from the nRec field */ + u32 *pDbSize /* OUT: Value of original database size field */ +){ + int rc; /* Return code */ + unsigned char aMagic[8]; /* A buffer to hold the magic header */ + i64 iHdrOff; /* Offset of journal header being read */ + + assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ + + /* Advance Pager.journalOff to the start of the next sector. If the + ** journal file is too small for there to be a header stored at this + ** point, return SQLITE_DONE. + */ + pPager->journalOff = journalHdrOffset(pPager); + if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){ + return SQLITE_DONE; + } + iHdrOff = pPager->journalOff; + + /* Read in the first 8 bytes of the journal header. If they do not match + ** the magic string found at the start of each journal header, return + ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise, + ** proceed. + */ + if( isHot || iHdrOff!=pPager->journalHdr ){ + rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff); + if( rc ){ + return rc; + } + if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){ + return SQLITE_DONE; + } + } + + /* Read the first three 32-bit fields of the journal header: The nRec + ** field, the checksum-initializer and the database size at the start + ** of the transaction. Return an error code if anything goes wrong. + */ + if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec)) + || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit)) + || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize)) + ){ + return rc; + } + + if( pPager->journalOff==0 ){ + u32 iPageSize; /* Page-size field of journal header */ + u32 iSectorSize; /* Sector-size field of journal header */ + + /* Read the page-size and sector-size journal header fields. */ + if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize)) + || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize)) + ){ + return rc; + } + + /* Versions of SQLite prior to 3.5.8 set the page-size field of the + ** journal header to zero. In this case, assume that the Pager.pageSize + ** variable is already set to the correct page size. + */ + if( iPageSize==0 ){ + iPageSize = pPager->pageSize; + } + + /* Check that the values read from the page-size and sector-size fields + ** are within range. To be 'in range', both values need to be a power + ** of two greater than or equal to 512 or 32, and not greater than their + ** respective compile time maximum limits. + */ + if( iPageSize<512 || iSectorSize<32 + || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE + || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0 + ){ + /* If the either the page-size or sector-size in the journal-header is + ** invalid, then the process that wrote the journal-header must have + ** crashed before the header was synced. In this case stop reading + ** the journal file here. + */ + return SQLITE_DONE; + } + + /* Update the page-size to match the value read from the journal. + ** Use a testcase() macro to make sure that malloc failure within + ** PagerSetPagesize() is tested. + */ + rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1); + testcase( rc!=SQLITE_OK ); + + /* Update the assumed sector-size to match the value used by + ** the process that created this journal. If this journal was + ** created by a process other than this one, then this routine + ** is being called from within pager_playback(). The local value + ** of Pager.sectorSize is restored at the end of that routine. + */ + pPager->sectorSize = iSectorSize; + } + + pPager->journalOff += JOURNAL_HDR_SZ(pPager); + return rc; +} + + +/* +** Write the supplied master journal name into the journal file for pager +** pPager at the current location. The master journal name must be the last +** thing written to a journal file. If the pager is in full-sync mode, the +** journal file descriptor is advanced to the next sector boundary before +** anything is written. The format is: +** +** + 4 bytes: PAGER_MJ_PGNO. +** + N bytes: Master journal filename in utf-8. +** + 4 bytes: N (length of master journal name in bytes, no nul-terminator). +** + 4 bytes: Master journal name checksum. +** + 8 bytes: aJournalMagic[]. +** +** The master journal page checksum is the sum of the bytes in the master +** journal name, where each byte is interpreted as a signed 8-bit integer. +** +** If zMaster is a NULL pointer (occurs for a single database transaction), +** this call is a no-op. +*/ +static int writeMasterJournal(Pager *pPager, const char *zMaster){ + int rc; /* Return code */ + int nMaster; /* Length of string zMaster */ + i64 iHdrOff; /* Offset of header in journal file */ + i64 jrnlSize; /* Size of journal file on disk */ + u32 cksum = 0; /* Checksum of string zMaster */ + + assert( pPager->setMaster==0 ); + assert( !pagerUseWal(pPager) ); + + if( !zMaster + || pPager->journalMode==PAGER_JOURNALMODE_MEMORY + || pPager->journalMode==PAGER_JOURNALMODE_OFF + ){ + return SQLITE_OK; + } + pPager->setMaster = 1; + assert( isOpen(pPager->jfd) ); + assert( pPager->journalHdr <= pPager->journalOff ); + + /* Calculate the length in bytes and the checksum of zMaster */ + for(nMaster=0; zMaster[nMaster]; nMaster++){ + cksum += zMaster[nMaster]; + } + + /* If in full-sync mode, advance to the next disk sector before writing + ** the master journal name. This is in case the previous page written to + ** the journal has already been synced. + */ + if( pPager->fullSync ){ + pPager->journalOff = journalHdrOffset(pPager); + } + iHdrOff = pPager->journalOff; + + /* Write the master journal data to the end of the journal file. If + ** an error occurs, return the error code to the caller. + */ + if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager)))) + || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4))) + || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster))) + || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum))) + || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8))) + ){ + return rc; + } + pPager->journalOff += (nMaster+20); + + /* If the pager is in peristent-journal mode, then the physical + ** journal-file may extend past the end of the master-journal name + ** and 8 bytes of magic data just written to the file. This is + ** dangerous because the code to rollback a hot-journal file + ** will not be able to find the master-journal name to determine + ** whether or not the journal is hot. + ** + ** Easiest thing to do in this scenario is to truncate the journal + ** file to the required size. + */ + if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize)) + && jrnlSize>pPager->journalOff + ){ + rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff); + } + return rc; +} + +/* +** Find a page in the hash table given its page number. Return +** a pointer to the page or NULL if the requested page is not +** already in memory. +*/ +static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){ + PgHdr *p; /* Return value */ + + /* It is not possible for a call to PcacheFetch() with createFlag==0 to + ** fail, since no attempt to allocate dynamic memory will be made. + */ + (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p); + return p; +} + +/* +** Discard the entire contents of the in-memory page-cache. +*/ +static void pager_reset(Pager *pPager){ + sqlite3BackupRestart(pPager->pBackup); + sqlite3PcacheClear(pPager->pPCache); +} + +/* +** Free all structures in the Pager.aSavepoint[] array and set both +** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal +** if it is open and the pager is not in exclusive mode. +*/ +static void releaseAllSavepoints(Pager *pPager){ + int ii; /* Iterator for looping through Pager.aSavepoint */ + for(ii=0; iinSavepoint; ii++){ + sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); + } + if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){ + sqlite3OsClose(pPager->sjfd); + } + sqlite3_free(pPager->aSavepoint); + pPager->aSavepoint = 0; + pPager->nSavepoint = 0; + pPager->nSubRec = 0; +} + +/* +** Set the bit number pgno in the PagerSavepoint.pInSavepoint +** bitvecs of all open savepoints. Return SQLITE_OK if successful +** or SQLITE_NOMEM if a malloc failure occurs. +*/ +static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){ + int ii; /* Loop counter */ + int rc = SQLITE_OK; /* Result code */ + + for(ii=0; iinSavepoint; ii++){ + PagerSavepoint *p = &pPager->aSavepoint[ii]; + if( pgno<=p->nOrig ){ + rc |= sqlite3BitvecSet(p->pInSavepoint, pgno); + testcase( rc==SQLITE_NOMEM ); + assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); + } + } + return rc; +} + +/* +** This function is a no-op if the pager is in exclusive mode and not +** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN +** state. +** +** If the pager is not in exclusive-access mode, the database file is +** completely unlocked. If the file is unlocked and the file-system does +** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is +** closed (if it is open). +** +** If the pager is in ERROR state when this function is called, the +** contents of the pager cache are discarded before switching back to +** the OPEN state. Regardless of whether the pager is in exclusive-mode +** or not, any journal file left in the file-system will be treated +** as a hot-journal and rolled back the next time a read-transaction +** is opened (by this or by any other connection). +*/ +static void pager_unlock(Pager *pPager){ + + assert( pPager->eState==PAGER_READER + || pPager->eState==PAGER_OPEN + || pPager->eState==PAGER_ERROR + ); + + sqlite3BitvecDestroy(pPager->pInJournal); + pPager->pInJournal = 0; + releaseAllSavepoints(pPager); + + if( pagerUseWal(pPager) ){ + assert( !isOpen(pPager->jfd) ); + sqlite3WalEndReadTransaction(pPager->pWal); + pPager->eState = PAGER_OPEN; + }else if( !pPager->exclusiveMode ){ + int rc; /* Error code returned by pagerUnlockDb() */ + int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0; + + /* If the operating system support deletion of open files, then + ** close the journal file when dropping the database lock. Otherwise + ** another connection with journal_mode=delete might delete the file + ** out from under us. + */ + assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 ); + assert( (PAGER_JOURNALMODE_OFF & 5)!=1 ); + assert( (PAGER_JOURNALMODE_WAL & 5)!=1 ); + assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 ); + assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); + assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); + if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN) + || 1!=(pPager->journalMode & 5) + ){ + sqlite3OsClose(pPager->jfd); + } + + /* If the pager is in the ERROR state and the call to unlock the database + ** file fails, set the current lock to UNKNOWN_LOCK. See the comment + ** above the #define for UNKNOWN_LOCK for an explanation of why this + ** is necessary. + */ + rc = pagerUnlockDb(pPager, NO_LOCK); + if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){ + pPager->eLock = UNKNOWN_LOCK; + } + + /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here + ** without clearing the error code. This is intentional - the error + ** code is cleared and the cache reset in the block below. + */ + assert( pPager->errCode || pPager->eState!=PAGER_ERROR ); + pPager->changeCountDone = 0; + pPager->eState = PAGER_OPEN; + } + + /* If Pager.errCode is set, the contents of the pager cache cannot be + ** trusted. Now that there are no outstanding references to the pager, + ** it can safely move back to PAGER_OPEN state. This happens in both + ** normal and exclusive-locking mode. + */ + if( pPager->errCode ){ + assert( !MEMDB ); + pager_reset(pPager); + pPager->changeCountDone = pPager->tempFile; + pPager->eState = PAGER_OPEN; + pPager->errCode = SQLITE_OK; + if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); + } + + pPager->journalOff = 0; + pPager->journalHdr = 0; + pPager->setMaster = 0; +} + +/* +** This function is called whenever an IOERR or FULL error that requires +** the pager to transition into the ERROR state may ahve occurred. +** The first argument is a pointer to the pager structure, the second +** the error-code about to be returned by a pager API function. The +** value returned is a copy of the second argument to this function. +** +** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the +** IOERR sub-codes, the pager enters the ERROR state and the error code +** is stored in Pager.errCode. While the pager remains in the ERROR state, +** all major API calls on the Pager will immediately return Pager.errCode. +** +** The ERROR state indicates that the contents of the pager-cache +** cannot be trusted. This state can be cleared by completely discarding +** the contents of the pager-cache. If a transaction was active when +** the persistent error occurred, then the rollback journal may need +** to be replayed to restore the contents of the database file (as if +** it were a hot-journal). +*/ +static int pager_error(Pager *pPager, int rc){ + int rc2 = rc & 0xff; + assert( rc==SQLITE_OK || !MEMDB ); + assert( + pPager->errCode==SQLITE_FULL || + pPager->errCode==SQLITE_OK || + (pPager->errCode & 0xff)==SQLITE_IOERR + ); + if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){ + pPager->errCode = rc; + pPager->eState = PAGER_ERROR; + } + return rc; +} + +static int pager_truncate(Pager *pPager, Pgno nPage); + +/* +** This routine ends a transaction. A transaction is usually ended by +** either a COMMIT or a ROLLBACK operation. This routine may be called +** after rollback of a hot-journal, or if an error occurs while opening +** the journal file or writing the very first journal-header of a +** database transaction. +** +** This routine is never called in PAGER_ERROR state. If it is called +** in PAGER_NONE or PAGER_SHARED state and the lock held is less +** exclusive than a RESERVED lock, it is a no-op. +** +** Otherwise, any active savepoints are released. +** +** If the journal file is open, then it is "finalized". Once a journal +** file has been finalized it is not possible to use it to roll back a +** transaction. Nor will it be considered to be a hot-journal by this +** or any other database connection. Exactly how a journal is finalized +** depends on whether or not the pager is running in exclusive mode and +** the current journal-mode (Pager.journalMode value), as follows: +** +** journalMode==MEMORY +** Journal file descriptor is simply closed. This destroys an +** in-memory journal. +** +** journalMode==TRUNCATE +** Journal file is truncated to zero bytes in size. +** +** journalMode==PERSIST +** The first 28 bytes of the journal file are zeroed. This invalidates +** the first journal header in the file, and hence the entire journal +** file. An invalid journal file cannot be rolled back. +** +** journalMode==DELETE +** The journal file is closed and deleted using sqlite3OsDelete(). +** +** If the pager is running in exclusive mode, this method of finalizing +** the journal file is never used. Instead, if the journalMode is +** DELETE and the pager is in exclusive mode, the method described under +** journalMode==PERSIST is used instead. +** +** After the journal is finalized, the pager moves to PAGER_READER state. +** If running in non-exclusive rollback mode, the lock on the file is +** downgraded to a SHARED_LOCK. +** +** SQLITE_OK is returned if no error occurs. If an error occurs during +** any of the IO operations to finalize the journal file or unlock the +** database then the IO error code is returned to the user. If the +** operation to finalize the journal file fails, then the code still +** tries to unlock the database file if not in exclusive mode. If the +** unlock operation fails as well, then the first error code related +** to the first error encountered (the journal finalization one) is +** returned. +*/ +static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){ + int rc = SQLITE_OK; /* Error code from journal finalization operation */ + int rc2 = SQLITE_OK; /* Error code from db file unlock operation */ + + /* Do nothing if the pager does not have an open write transaction + ** or at least a RESERVED lock. This function may be called when there + ** is no write-transaction active but a RESERVED or greater lock is + ** held under two circumstances: + ** + ** 1. After a successful hot-journal rollback, it is called with + ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK. + ** + ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE + ** lock switches back to locking_mode=normal and then executes a + ** read-transaction, this function is called with eState==PAGER_READER + ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed. + */ + assert( assert_pager_state(pPager) ); + assert( pPager->eState!=PAGER_ERROR ); + if( pPager->eStateeLockjfd) || pPager->pInJournal==0 ); + if( isOpen(pPager->jfd) ){ + assert( !pagerUseWal(pPager) ); + + /* Finalize the journal file. */ + if( sqlite3IsMemJournal(pPager->jfd) ){ + assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); + sqlite3OsClose(pPager->jfd); + }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){ + if( pPager->journalOff==0 ){ + rc = SQLITE_OK; + }else{ + rc = sqlite3OsTruncate(pPager->jfd, 0); + } + pPager->journalOff = 0; + }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST + || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL) + ){ + rc = zeroJournalHdr(pPager, hasMaster); + pPager->journalOff = 0; + }else{ + /* This branch may be executed with Pager.journalMode==MEMORY if + ** a hot-journal was just rolled back. In this case the journal + ** file should be closed and deleted. If this connection writes to + ** the database file, it will do so using an in-memory journal. + */ + int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd)); + assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE + || pPager->journalMode==PAGER_JOURNALMODE_MEMORY + || pPager->journalMode==PAGER_JOURNALMODE_WAL + ); + sqlite3OsClose(pPager->jfd); + if( bDelete ){ + rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); + } + } + } + +#ifdef SQLITE_CHECK_PAGES + sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash); + if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){ + PgHdr *p = pager_lookup(pPager, 1); + if( p ){ + p->pageHash = 0; + sqlite3PagerUnref(p); + } + } +#endif + + sqlite3BitvecDestroy(pPager->pInJournal); + pPager->pInJournal = 0; + pPager->nRec = 0; + sqlite3PcacheCleanAll(pPager->pPCache); + sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize); + + if( pagerUseWal(pPager) ){ + /* Drop the WAL write-lock, if any. Also, if the connection was in + ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE + ** lock held on the database file. + */ + rc2 = sqlite3WalEndWriteTransaction(pPager->pWal); + assert( rc2==SQLITE_OK ); + }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){ + /* This branch is taken when committing a transaction in rollback-journal + ** mode if the database file on disk is larger than the database image. + ** At this point the journal has been finalized and the transaction + ** successfully committed, but the EXCLUSIVE lock is still held on the + ** file. So it is safe to truncate the database file to its minimum + ** required size. */ + assert( pPager->eLock==EXCLUSIVE_LOCK ); + rc = pager_truncate(pPager, pPager->dbSize); + } + + if( !pPager->exclusiveMode + && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0)) + ){ + rc2 = pagerUnlockDb(pPager, SHARED_LOCK); + pPager->changeCountDone = 0; + } + pPager->eState = PAGER_READER; + pPager->setMaster = 0; + + return (rc==SQLITE_OK?rc2:rc); +} + +/* +** Execute a rollback if a transaction is active and unlock the +** database file. +** +** If the pager has already entered the ERROR state, do not attempt +** the rollback at this time. Instead, pager_unlock() is called. The +** call to pager_unlock() will discard all in-memory pages, unlock +** the database file and move the pager back to OPEN state. If this +** means that there is a hot-journal left in the file-system, the next +** connection to obtain a shared lock on the pager (which may be this one) +** will roll it back. +** +** If the pager has not already entered the ERROR state, but an IO or +** malloc error occurs during a rollback, then this will itself cause +** the pager to enter the ERROR state. Which will be cleared by the +** call to pager_unlock(), as described above. +*/ +static void pagerUnlockAndRollback(Pager *pPager){ + if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){ + assert( assert_pager_state(pPager) ); + if( pPager->eState>=PAGER_WRITER_LOCKED ){ + sqlite3BeginBenignMalloc(); + sqlite3PagerRollback(pPager); + sqlite3EndBenignMalloc(); + }else if( !pPager->exclusiveMode ){ + assert( pPager->eState==PAGER_READER ); + pager_end_transaction(pPager, 0, 0); + } + } + pager_unlock(pPager); +} + +/* +** Parameter aData must point to a buffer of pPager->pageSize bytes +** of data. Compute and return a checksum based ont the contents of the +** page of data and the current value of pPager->cksumInit. +** +** This is not a real checksum. It is really just the sum of the +** random initial value (pPager->cksumInit) and every 200th byte +** of the page data, starting with byte offset (pPager->pageSize%200). +** Each byte is interpreted as an 8-bit unsigned integer. +** +** Changing the formula used to compute this checksum results in an +** incompatible journal file format. +** +** If journal corruption occurs due to a power failure, the most likely +** scenario is that one end or the other of the record will be changed. +** It is much less likely that the two ends of the journal record will be +** correct and the middle be corrupt. Thus, this "checksum" scheme, +** though fast and simple, catches the mostly likely kind of corruption. +*/ +static u32 pager_cksum(Pager *pPager, const u8 *aData){ + u32 cksum = pPager->cksumInit; /* Checksum value to return */ + int i = pPager->pageSize-200; /* Loop counter */ + while( i>0 ){ + cksum += aData[i]; + i -= 200; + } + return cksum; +} + +/* +** Report the current page size and number of reserved bytes back +** to the codec. +*/ +#ifdef SQLITE_HAS_CODEC +static void pagerReportSize(Pager *pPager){ + if( pPager->xCodecSizeChng ){ + pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize, + (int)pPager->nReserve); + } +} +#else +# define pagerReportSize(X) /* No-op if we do not support a codec */ +#endif + +/* +** Read a single page from either the journal file (if isMainJrnl==1) or +** from the sub-journal (if isMainJrnl==0) and playback that page. +** The page begins at offset *pOffset into the file. The *pOffset +** value is increased to the start of the next page in the journal. +** +** The main rollback journal uses checksums - the statement journal does +** not. +** +** If the page number of the page record read from the (sub-)journal file +** is greater than the current value of Pager.dbSize, then playback is +** skipped and SQLITE_OK is returned. +** +** If pDone is not NULL, then it is a record of pages that have already +** been played back. If the page at *pOffset has already been played back +** (if the corresponding pDone bit is set) then skip the playback. +** Make sure the pDone bit corresponding to the *pOffset page is set +** prior to returning. +** +** If the page record is successfully read from the (sub-)journal file +** and played back, then SQLITE_OK is returned. If an IO error occurs +** while reading the record from the (sub-)journal file or while writing +** to the database file, then the IO error code is returned. If data +** is successfully read from the (sub-)journal file but appears to be +** corrupted, SQLITE_DONE is returned. Data is considered corrupted in +** two circumstances: +** +** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or +** * If the record is being rolled back from the main journal file +** and the checksum field does not match the record content. +** +** Neither of these two scenarios are possible during a savepoint rollback. +** +** If this is a savepoint rollback, then memory may have to be dynamically +** allocated by this function. If this is the case and an allocation fails, +** SQLITE_NOMEM is returned. +*/ +static int pager_playback_one_page( + Pager *pPager, /* The pager being played back */ + i64 *pOffset, /* Offset of record to playback */ + Bitvec *pDone, /* Bitvec of pages already played back */ + int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */ + int isSavepnt /* True for a savepoint rollback */ +){ + int rc; + PgHdr *pPg; /* An existing page in the cache */ + Pgno pgno; /* The page number of a page in journal */ + u32 cksum; /* Checksum used for sanity checking */ + char *aData; /* Temporary storage for the page */ + sqlite3_file *jfd; /* The file descriptor for the journal file */ + int isSynced; /* True if journal page is synced */ + + assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */ + assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */ + assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */ + assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */ + + aData = pPager->pTmpSpace; + assert( aData ); /* Temp storage must have already been allocated */ + assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) ); + + /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction + ** or savepoint rollback done at the request of the caller) or this is + ** a hot-journal rollback. If it is a hot-journal rollback, the pager + ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback + ** only reads from the main journal, not the sub-journal. + */ + assert( pPager->eState>=PAGER_WRITER_CACHEMOD + || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK) + ); + assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl ); + + /* Read the page number and page data from the journal or sub-journal + ** file. Return an error code to the caller if an IO error occurs. + */ + jfd = isMainJrnl ? pPager->jfd : pPager->sjfd; + rc = read32bits(jfd, *pOffset, &pgno); + if( rc!=SQLITE_OK ) return rc; + rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4); + if( rc!=SQLITE_OK ) return rc; + *pOffset += pPager->pageSize + 4 + isMainJrnl*4; + + /* Sanity checking on the page. This is more important that I originally + ** thought. If a power failure occurs while the journal is being written, + ** it could cause invalid data to be written into the journal. We need to + ** detect this invalid data (with high probability) and ignore it. + */ + if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){ + assert( !isSavepnt ); + return SQLITE_DONE; + } + if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){ + return SQLITE_OK; + } + if( isMainJrnl ){ + rc = read32bits(jfd, (*pOffset)-4, &cksum); + if( rc ) return rc; + if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){ + return SQLITE_DONE; + } + } + + /* If this page has already been played by before during the current + ** rollback, then don't bother to play it back again. + */ + if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){ + return rc; + } + + /* When playing back page 1, restore the nReserve setting + */ + if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){ + pPager->nReserve = ((u8*)aData)[20]; + pagerReportSize(pPager); + } + + /* If the pager is in CACHEMOD state, then there must be a copy of this + ** page in the pager cache. In this case just update the pager cache, + ** not the database file. The page is left marked dirty in this case. + ** + ** An exception to the above rule: If the database is in no-sync mode + ** and a page is moved during an incremental vacuum then the page may + ** not be in the pager cache. Later: if a malloc() or IO error occurs + ** during a Movepage() call, then the page may not be in the cache + ** either. So the condition described in the above paragraph is not + ** assert()able. + ** + ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the + ** pager cache if it exists and the main file. The page is then marked + ** not dirty. Since this code is only executed in PAGER_OPEN state for + ** a hot-journal rollback, it is guaranteed that the page-cache is empty + ** if the pager is in OPEN state. + ** + ** Ticket #1171: The statement journal might contain page content that is + ** different from the page content at the start of the transaction. + ** This occurs when a page is changed prior to the start of a statement + ** then changed again within the statement. When rolling back such a + ** statement we must not write to the original database unless we know + ** for certain that original page contents are synced into the main rollback + ** journal. Otherwise, a power loss might leave modified data in the + ** database file without an entry in the rollback journal that can + ** restore the database to its original form. Two conditions must be + ** met before writing to the database files. (1) the database must be + ** locked. (2) we know that the original page content is fully synced + ** in the main journal either because the page is not in cache or else + ** the page is marked as needSync==0. + ** + ** 2008-04-14: When attempting to vacuum a corrupt database file, it + ** is possible to fail a statement on a database that does not yet exist. + ** Do not attempt to write if database file has never been opened. + */ + if( pagerUseWal(pPager) ){ + pPg = 0; + }else{ + pPg = pager_lookup(pPager, pgno); + } + assert( pPg || !MEMDB ); + assert( pPager->eState!=PAGER_OPEN || pPg==0 ); + PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n", + PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData), + (isMainJrnl?"main-journal":"sub-journal") + )); + if( isMainJrnl ){ + isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr); + }else{ + isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC)); + } + if( isOpen(pPager->fd) + && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) + && isSynced + ){ + i64 ofst = (pgno-1)*(i64)pPager->pageSize; + testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 ); + assert( !pagerUseWal(pPager) ); + rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); + if( pgno>pPager->dbFileSize ){ + pPager->dbFileSize = pgno; + } + if( pPager->pBackup ){ + CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM); + sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); + CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData); + } + }else if( !isMainJrnl && pPg==0 ){ + /* If this is a rollback of a savepoint and data was not written to + ** the database and the page is not in-memory, there is a potential + ** problem. When the page is next fetched by the b-tree layer, it + ** will be read from the database file, which may or may not be + ** current. + ** + ** There are a couple of different ways this can happen. All are quite + ** obscure. When running in synchronous mode, this can only happen + ** if the page is on the free-list at the start of the transaction, then + ** populated, then moved using sqlite3PagerMovepage(). + ** + ** The solution is to add an in-memory page to the cache containing + ** the data just read from the sub-journal. Mark the page as dirty + ** and if the pager requires a journal-sync, then mark the page as + ** requiring a journal-sync before it is written. + */ + assert( isSavepnt ); + assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 ); + pPager->doNotSpill |= SPILLFLAG_ROLLBACK; + rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1); + assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 ); + pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK; + if( rc!=SQLITE_OK ) return rc; + pPg->flags &= ~PGHDR_NEED_READ; + sqlite3PcacheMakeDirty(pPg); + } + if( pPg ){ + /* No page should ever be explicitly rolled back that is in use, except + ** for page 1 which is held in use in order to keep the lock on the + ** database active. However such a page may be rolled back as a result + ** of an internal error resulting in an automatic call to + ** sqlite3PagerRollback(). + */ + void *pData; + pData = pPg->pData; + memcpy(pData, (u8*)aData, pPager->pageSize); + pPager->xReiniter(pPg); + if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){ + /* If the contents of this page were just restored from the main + ** journal file, then its content must be as they were when the + ** transaction was first opened. In this case we can mark the page + ** as clean, since there will be no need to write it out to the + ** database. + ** + ** There is one exception to this rule. If the page is being rolled + ** back as part of a savepoint (or statement) rollback from an + ** unsynced portion of the main journal file, then it is not safe + ** to mark the page as clean. This is because marking the page as + ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is + ** already in the journal file (recorded in Pager.pInJournal) and + ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to + ** again within this transaction, it will be marked as dirty but + ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially + ** be written out into the database file before its journal file + ** segment is synced. If a crash occurs during or following this, + ** database corruption may ensue. + */ + assert( !pagerUseWal(pPager) ); + sqlite3PcacheMakeClean(pPg); + } + pager_set_pagehash(pPg); + + /* If this was page 1, then restore the value of Pager.dbFileVers. + ** Do this before any decoding. */ + if( pgno==1 ){ + memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers)); + } + + /* Decode the page just read from disk */ + CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM); + sqlite3PcacheRelease(pPg); + } + return rc; +} + +/* +** Parameter zMaster is the name of a master journal file. A single journal +** file that referred to the master journal file has just been rolled back. +** This routine checks if it is possible to delete the master journal file, +** and does so if it is. +** +** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not +** available for use within this function. +** +** When a master journal file is created, it is populated with the names +** of all of its child journals, one after another, formatted as utf-8 +** encoded text. The end of each child journal file is marked with a +** nul-terminator byte (0x00). i.e. the entire contents of a master journal +** file for a transaction involving two databases might be: +** +** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00" +** +** A master journal file may only be deleted once all of its child +** journals have been rolled back. +** +** This function reads the contents of the master-journal file into +** memory and loops through each of the child journal names. For +** each child journal, it checks if: +** +** * if the child journal exists, and if so +** * if the child journal contains a reference to master journal +** file zMaster +** +** If a child journal can be found that matches both of the criteria +** above, this function returns without doing anything. Otherwise, if +** no such child journal can be found, file zMaster is deleted from +** the file-system using sqlite3OsDelete(). +** +** If an IO error within this function, an error code is returned. This +** function allocates memory by calling sqlite3Malloc(). If an allocation +** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors +** occur, SQLITE_OK is returned. +** +** TODO: This function allocates a single block of memory to load +** the entire contents of the master journal file. This could be +** a couple of kilobytes or so - potentially larger than the page +** size. +*/ +static int pager_delmaster(Pager *pPager, const char *zMaster){ + sqlite3_vfs *pVfs = pPager->pVfs; + int rc; /* Return code */ + sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */ + sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */ + char *zMasterJournal = 0; /* Contents of master journal file */ + i64 nMasterJournal; /* Size of master journal file */ + char *zJournal; /* Pointer to one journal within MJ file */ + char *zMasterPtr; /* Space to hold MJ filename from a journal file */ + int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */ + + /* Allocate space for both the pJournal and pMaster file descriptors. + ** If successful, open the master journal file for reading. + */ + pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2); + pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile); + if( !pMaster ){ + rc = SQLITE_NOMEM; + }else{ + const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL); + rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0); + } + if( rc!=SQLITE_OK ) goto delmaster_out; + + /* Load the entire master journal file into space obtained from + ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain + ** sufficient space (in zMasterPtr) to hold the names of master + ** journal files extracted from regular rollback-journals. + */ + rc = sqlite3OsFileSize(pMaster, &nMasterJournal); + if( rc!=SQLITE_OK ) goto delmaster_out; + nMasterPtr = pVfs->mxPathname+1; + zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1); + if( !zMasterJournal ){ + rc = SQLITE_NOMEM; + goto delmaster_out; + } + zMasterPtr = &zMasterJournal[nMasterJournal+1]; + rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0); + if( rc!=SQLITE_OK ) goto delmaster_out; + zMasterJournal[nMasterJournal] = 0; + + zJournal = zMasterJournal; + while( (zJournal-zMasterJournal)pageSize bytes). +** If the file on disk is currently larger than nPage pages, then use the VFS +** xTruncate() method to truncate it. +** +** Or, it might might be the case that the file on disk is smaller than +** nPage pages. Some operating system implementations can get confused if +** you try to truncate a file to some size that is larger than it +** currently is, so detect this case and write a single zero byte to +** the end of the new file instead. +** +** If successful, return SQLITE_OK. If an IO error occurs while modifying +** the database file, return the error code to the caller. +*/ +static int pager_truncate(Pager *pPager, Pgno nPage){ + int rc = SQLITE_OK; + assert( pPager->eState!=PAGER_ERROR ); + assert( pPager->eState!=PAGER_READER ); + + if( isOpen(pPager->fd) + && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) + ){ + i64 currentSize, newSize; + int szPage = pPager->pageSize; + assert( pPager->eLock==EXCLUSIVE_LOCK ); + /* TODO: Is it safe to use Pager.dbFileSize here? */ + rc = sqlite3OsFileSize(pPager->fd, ¤tSize); + newSize = szPage*(i64)nPage; + if( rc==SQLITE_OK && currentSize!=newSize ){ + if( currentSize>newSize ){ + rc = sqlite3OsTruncate(pPager->fd, newSize); + }else if( (currentSize+szPage)<=newSize ){ + char *pTmp = pPager->pTmpSpace; + memset(pTmp, 0, szPage); + testcase( (newSize-szPage) == currentSize ); + testcase( (newSize-szPage) > currentSize ); + rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage); + } + if( rc==SQLITE_OK ){ + pPager->dbFileSize = nPage; + } + } + } + return rc; +} + +/* +** Return a sanitized version of the sector-size of OS file pFile. The +** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE. +*/ +int sqlite3SectorSize(sqlite3_file *pFile){ + int iRet = sqlite3OsSectorSize(pFile); + if( iRet<32 ){ + iRet = 512; + }else if( iRet>MAX_SECTOR_SIZE ){ + assert( MAX_SECTOR_SIZE>=512 ); + iRet = MAX_SECTOR_SIZE; + } + return iRet; +} + +/* +** Set the value of the Pager.sectorSize variable for the given +** pager based on the value returned by the xSectorSize method +** of the open database file. The sector size will be used used +** to determine the size and alignment of journal header and +** master journal pointers within created journal files. +** +** For temporary files the effective sector size is always 512 bytes. +** +** Otherwise, for non-temporary files, the effective sector size is +** the value returned by the xSectorSize() method rounded up to 32 if +** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it +** is greater than MAX_SECTOR_SIZE. +** +** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set +** the effective sector size to its minimum value (512). The purpose of +** pPager->sectorSize is to define the "blast radius" of bytes that +** might change if a crash occurs while writing to a single byte in +** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero +** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector +** size. For backwards compatibility of the rollback journal file format, +** we cannot reduce the effective sector size below 512. +*/ +static void setSectorSize(Pager *pPager){ + assert( isOpen(pPager->fd) || pPager->tempFile ); + + if( pPager->tempFile + || (sqlite3OsDeviceCharacteristics(pPager->fd) & + SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0 + ){ + /* Sector size doesn't matter for temporary files. Also, the file + ** may not have been opened yet, in which case the OsSectorSize() + ** call will segfault. */ + pPager->sectorSize = 512; + }else{ + pPager->sectorSize = sqlite3SectorSize(pPager->fd); + } +} + +/* +** Playback the journal and thus restore the database file to +** the state it was in before we started making changes. +** +** The journal file format is as follows: +** +** (1) 8 byte prefix. A copy of aJournalMagic[]. +** (2) 4 byte big-endian integer which is the number of valid page records +** in the journal. If this value is 0xffffffff, then compute the +** number of page records from the journal size. +** (3) 4 byte big-endian integer which is the initial value for the +** sanity checksum. +** (4) 4 byte integer which is the number of pages to truncate the +** database to during a rollback. +** (5) 4 byte big-endian integer which is the sector size. The header +** is this many bytes in size. +** (6) 4 byte big-endian integer which is the page size. +** (7) zero padding out to the next sector size. +** (8) Zero or more pages instances, each as follows: +** + 4 byte page number. +** + pPager->pageSize bytes of data. +** + 4 byte checksum +** +** When we speak of the journal header, we mean the first 7 items above. +** Each entry in the journal is an instance of the 8th item. +** +** Call the value from the second bullet "nRec". nRec is the number of +** valid page entries in the journal. In most cases, you can compute the +** value of nRec from the size of the journal file. But if a power +** failure occurred while the journal was being written, it could be the +** case that the size of the journal file had already been increased but +** the extra entries had not yet made it safely to disk. In such a case, +** the value of nRec computed from the file size would be too large. For +** that reason, we always use the nRec value in the header. +** +** If the nRec value is 0xffffffff it means that nRec should be computed +** from the file size. This value is used when the user selects the +** no-sync option for the journal. A power failure could lead to corruption +** in this case. But for things like temporary table (which will be +** deleted when the power is restored) we don't care. +** +** If the file opened as the journal file is not a well-formed +** journal file then all pages up to the first corrupted page are rolled +** back (or no pages if the journal header is corrupted). The journal file +** is then deleted and SQLITE_OK returned, just as if no corruption had +** been encountered. +** +** If an I/O or malloc() error occurs, the journal-file is not deleted +** and an error code is returned. +** +** The isHot parameter indicates that we are trying to rollback a journal +** that might be a hot journal. Or, it could be that the journal is +** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE. +** If the journal really is hot, reset the pager cache prior rolling +** back any content. If the journal is merely persistent, no reset is +** needed. +*/ +static int pager_playback(Pager *pPager, int isHot){ + sqlite3_vfs *pVfs = pPager->pVfs; + i64 szJ; /* Size of the journal file in bytes */ + u32 nRec; /* Number of Records in the journal */ + u32 u; /* Unsigned loop counter */ + Pgno mxPg = 0; /* Size of the original file in pages */ + int rc; /* Result code of a subroutine */ + int res = 1; /* Value returned by sqlite3OsAccess() */ + char *zMaster = 0; /* Name of master journal file if any */ + int needPagerReset; /* True to reset page prior to first page rollback */ + int nPlayback = 0; /* Total number of pages restored from journal */ + + /* Figure out how many records are in the journal. Abort early if + ** the journal is empty. + */ + assert( isOpen(pPager->jfd) ); + rc = sqlite3OsFileSize(pPager->jfd, &szJ); + if( rc!=SQLITE_OK ){ + goto end_playback; + } + + /* Read the master journal name from the journal, if it is present. + ** If a master journal file name is specified, but the file is not + ** present on disk, then the journal is not hot and does not need to be + ** played back. + ** + ** TODO: Technically the following is an error because it assumes that + ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that + ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c, + ** mxPathname is 512, which is the same as the minimum allowable value + ** for pageSize. + */ + zMaster = pPager->pTmpSpace; + rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); + if( rc==SQLITE_OK && zMaster[0] ){ + rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); + } + zMaster = 0; + if( rc!=SQLITE_OK || !res ){ + goto end_playback; + } + pPager->journalOff = 0; + needPagerReset = isHot; + + /* This loop terminates either when a readJournalHdr() or + ** pager_playback_one_page() call returns SQLITE_DONE or an IO error + ** occurs. + */ + while( 1 ){ + /* Read the next journal header from the journal file. If there are + ** not enough bytes left in the journal file for a complete header, or + ** it is corrupted, then a process must have failed while writing it. + ** This indicates nothing more needs to be rolled back. + */ + rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + } + goto end_playback; + } + + /* If nRec is 0xffffffff, then this journal was created by a process + ** working in no-sync mode. This means that the rest of the journal + ** file consists of pages, there are no more journal headers. Compute + ** the value of nRec based on this assumption. + */ + if( nRec==0xffffffff ){ + assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ); + nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager)); + } + + /* If nRec is 0 and this rollback is of a transaction created by this + ** process and if this is the final header in the journal, then it means + ** that this part of the journal was being filled but has not yet been + ** synced to disk. Compute the number of pages based on the remaining + ** size of the file. + ** + ** The third term of the test was added to fix ticket #2565. + ** When rolling back a hot journal, nRec==0 always means that the next + ** chunk of the journal contains zero pages to be rolled back. But + ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in + ** the journal, it means that the journal might contain additional + ** pages that need to be rolled back and that the number of pages + ** should be computed based on the journal file size. + */ + if( nRec==0 && !isHot && + pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){ + nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager)); + } + + /* If this is the first header read from the journal, truncate the + ** database file back to its original size. + */ + if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){ + rc = pager_truncate(pPager, mxPg); + if( rc!=SQLITE_OK ){ + goto end_playback; + } + pPager->dbSize = mxPg; + } + + /* Copy original pages out of the journal and back into the + ** database file and/or page cache. + */ + for(u=0; ujournalOff,0,1,0); + if( rc==SQLITE_OK ){ + nPlayback++; + }else{ + if( rc==SQLITE_DONE ){ + pPager->journalOff = szJ; + break; + }else if( rc==SQLITE_IOERR_SHORT_READ ){ + /* If the journal has been truncated, simply stop reading and + ** processing the journal. This might happen if the journal was + ** not completely written and synced prior to a crash. In that + ** case, the database should have never been written in the + ** first place so it is OK to simply abandon the rollback. */ + rc = SQLITE_OK; + goto end_playback; + }else{ + /* If we are unable to rollback, quit and return the error + ** code. This will cause the pager to enter the error state + ** so that no further harm will be done. Perhaps the next + ** process to come along will be able to rollback the database. + */ + goto end_playback; + } + } + } + } + /*NOTREACHED*/ + assert( 0 ); + +end_playback: + /* Following a rollback, the database file should be back in its original + ** state prior to the start of the transaction, so invoke the + ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the + ** assertion that the transaction counter was modified. + */ +#ifdef SQLITE_DEBUG + if( pPager->fd->pMethods ){ + sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0); + } +#endif + + /* If this playback is happening automatically as a result of an IO or + ** malloc error that occurred after the change-counter was updated but + ** before the transaction was committed, then the change-counter + ** modification may just have been reverted. If this happens in exclusive + ** mode, then subsequent transactions performed by the connection will not + ** update the change-counter at all. This may lead to cache inconsistency + ** problems for other processes at some point in the future. So, just + ** in case this has happened, clear the changeCountDone flag now. + */ + pPager->changeCountDone = pPager->tempFile; + + if( rc==SQLITE_OK ){ + zMaster = pPager->pTmpSpace; + rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); + testcase( rc!=SQLITE_OK ); + } + if( rc==SQLITE_OK + && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) + ){ + rc = sqlite3PagerSync(pPager); + } + if( rc==SQLITE_OK ){ + rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0); + testcase( rc!=SQLITE_OK ); + } + if( rc==SQLITE_OK && zMaster[0] && res ){ + /* If there was a master journal and this routine will return success, + ** see if it is possible to delete the master journal. + */ + rc = pager_delmaster(pPager, zMaster); + testcase( rc!=SQLITE_OK ); + } + if( isHot && nPlayback ){ + sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s", + nPlayback, pPager->zJournal); + } + + /* The Pager.sectorSize variable may have been updated while rolling + ** back a journal created by a process with a different sector size + ** value. Reset it to the correct value for this process. + */ + setSectorSize(pPager); + return rc; +} + + +/* +** Read the content for page pPg out of the database file and into +** pPg->pData. A shared lock or greater must be held on the database +** file before this function is called. +** +** If page 1 is read, then the value of Pager.dbFileVers[] is set to +** the value read from the database file. +** +** If an IO error occurs, then the IO error is returned to the caller. +** Otherwise, SQLITE_OK is returned. +*/ +static int readDbPage(PgHdr *pPg, u32 iFrame){ + Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */ + Pgno pgno = pPg->pgno; /* Page number to read */ + int rc = SQLITE_OK; /* Return code */ + int pgsz = pPager->pageSize; /* Number of bytes to read */ + + assert( pPager->eState>=PAGER_READER && !MEMDB ); + assert( isOpen(pPager->fd) ); + +#ifndef SQLITE_OMIT_WAL + if( iFrame ){ + /* Try to pull the page from the write-ahead log. */ + rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData); + }else +#endif + { + i64 iOffset = (pgno-1)*(i64)pPager->pageSize; + rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset); + if( rc==SQLITE_IOERR_SHORT_READ ){ + rc = SQLITE_OK; + } + } + + if( pgno==1 ){ + if( rc ){ + /* If the read is unsuccessful, set the dbFileVers[] to something + ** that will never be a valid file version. dbFileVers[] is a copy + ** of bytes 24..39 of the database. Bytes 28..31 should always be + ** zero or the size of the database in page. Bytes 32..35 and 35..39 + ** should be page numbers which are never 0xffffffff. So filling + ** pPager->dbFileVers[] with all 0xff bytes should suffice. + ** + ** For an encrypted database, the situation is more complex: bytes + ** 24..39 of the database are white noise. But the probability of + ** white noising equaling 16 bytes of 0xff is vanishingly small so + ** we should still be ok. + */ + memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers)); + }else{ + u8 *dbFileVers = &((u8*)pPg->pData)[24]; + memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); + } + } + CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM); + + PAGER_INCR(sqlite3_pager_readdb_count); + PAGER_INCR(pPager->nRead); + IOTRACE(("PGIN %p %d\n", pPager, pgno)); + PAGERTRACE(("FETCH %d page %d hash(%08x)\n", + PAGERID(pPager), pgno, pager_pagehash(pPg))); + + return rc; +} + +/* +** Update the value of the change-counter at offsets 24 and 92 in +** the header and the sqlite version number at offset 96. +** +** This is an unconditional update. See also the pager_incr_changecounter() +** routine which only updates the change-counter if the update is actually +** needed, as determined by the pPager->changeCountDone state variable. +*/ +static void pager_write_changecounter(PgHdr *pPg){ + u32 change_counter; + + /* Increment the value just read and write it back to byte 24. */ + change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1; + put32bits(((char*)pPg->pData)+24, change_counter); + + /* Also store the SQLite version number in bytes 96..99 and in + ** bytes 92..95 store the change counter for which the version number + ** is valid. */ + put32bits(((char*)pPg->pData)+92, change_counter); + put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER); +} + +#ifndef SQLITE_OMIT_WAL +/* +** This function is invoked once for each page that has already been +** written into the log file when a WAL transaction is rolled back. +** Parameter iPg is the page number of said page. The pCtx argument +** is actually a pointer to the Pager structure. +** +** If page iPg is present in the cache, and has no outstanding references, +** it is discarded. Otherwise, if there are one or more outstanding +** references, the page content is reloaded from the database. If the +** attempt to reload content from the database is required and fails, +** return an SQLite error code. Otherwise, SQLITE_OK. +*/ +static int pagerUndoCallback(void *pCtx, Pgno iPg){ + int rc = SQLITE_OK; + Pager *pPager = (Pager *)pCtx; + PgHdr *pPg; + + assert( pagerUseWal(pPager) ); + pPg = sqlite3PagerLookup(pPager, iPg); + if( pPg ){ + if( sqlite3PcachePageRefcount(pPg)==1 ){ + sqlite3PcacheDrop(pPg); + }else{ + u32 iFrame = 0; + rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame); + if( rc==SQLITE_OK ){ + rc = readDbPage(pPg, iFrame); + } + if( rc==SQLITE_OK ){ + pPager->xReiniter(pPg); + } + sqlite3PagerUnref(pPg); + } + } + + /* Normally, if a transaction is rolled back, any backup processes are + ** updated as data is copied out of the rollback journal and into the + ** database. This is not generally possible with a WAL database, as + ** rollback involves simply truncating the log file. Therefore, if one + ** or more frames have already been written to the log (and therefore + ** also copied into the backup databases) as part of this transaction, + ** the backups must be restarted. + */ + sqlite3BackupRestart(pPager->pBackup); + + return rc; +} + +/* +** This function is called to rollback a transaction on a WAL database. +*/ +static int pagerRollbackWal(Pager *pPager){ + int rc; /* Return Code */ + PgHdr *pList; /* List of dirty pages to revert */ + + /* For all pages in the cache that are currently dirty or have already + ** been written (but not committed) to the log file, do one of the + ** following: + ** + ** + Discard the cached page (if refcount==0), or + ** + Reload page content from the database (if refcount>0). + */ + pPager->dbSize = pPager->dbOrigSize; + rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager); + pList = sqlite3PcacheDirtyList(pPager->pPCache); + while( pList && rc==SQLITE_OK ){ + PgHdr *pNext = pList->pDirty; + rc = pagerUndoCallback((void *)pPager, pList->pgno); + pList = pNext; + } + + return rc; +} + +/* +** This function is a wrapper around sqlite3WalFrames(). As well as logging +** the contents of the list of pages headed by pList (connected by pDirty), +** this function notifies any active backup processes that the pages have +** changed. +** +** The list of pages passed into this routine is always sorted by page number. +** Hence, if page 1 appears anywhere on the list, it will be the first page. +*/ +static int pagerWalFrames( + Pager *pPager, /* Pager object */ + PgHdr *pList, /* List of frames to log */ + Pgno nTruncate, /* Database size after this commit */ + int isCommit /* True if this is a commit */ +){ + int rc; /* Return code */ + int nList; /* Number of pages in pList */ +#if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES) + PgHdr *p; /* For looping over pages */ +#endif + + assert( pPager->pWal ); + assert( pList ); +#ifdef SQLITE_DEBUG + /* Verify that the page list is in accending order */ + for(p=pList; p && p->pDirty; p=p->pDirty){ + assert( p->pgno < p->pDirty->pgno ); + } +#endif + + assert( pList->pDirty==0 || isCommit ); + if( isCommit ){ + /* If a WAL transaction is being committed, there is no point in writing + ** any pages with page numbers greater than nTruncate into the WAL file. + ** They will never be read by any client. So remove them from the pDirty + ** list here. */ + PgHdr *p; + PgHdr **ppNext = &pList; + nList = 0; + for(p=pList; (*ppNext = p)!=0; p=p->pDirty){ + if( p->pgno<=nTruncate ){ + ppNext = &p->pDirty; + nList++; + } + } + assert( pList ); + }else{ + nList = 1; + } + pPager->aStat[PAGER_STAT_WRITE] += nList; + + if( pList->pgno==1 ) pager_write_changecounter(pList); + rc = sqlite3WalFrames(pPager->pWal, + pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags + ); + if( rc==SQLITE_OK && pPager->pBackup ){ + PgHdr *p; + for(p=pList; p; p=p->pDirty){ + sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData); + } + } + +#ifdef SQLITE_CHECK_PAGES + pList = sqlite3PcacheDirtyList(pPager->pPCache); + for(p=pList; p; p=p->pDirty){ + pager_set_pagehash(p); + } +#endif + + return rc; +} + +/* +** Begin a read transaction on the WAL. +** +** This routine used to be called "pagerOpenSnapshot()" because it essentially +** makes a snapshot of the database at the current point in time and preserves +** that snapshot for use by the reader in spite of concurrently changes by +** other writers or checkpointers. +*/ +static int pagerBeginReadTransaction(Pager *pPager){ + int rc; /* Return code */ + int changed = 0; /* True if cache must be reset */ + + assert( pagerUseWal(pPager) ); + assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); + + /* sqlite3WalEndReadTransaction() was not called for the previous + ** transaction in locking_mode=EXCLUSIVE. So call it now. If we + ** are in locking_mode=NORMAL and EndRead() was previously called, + ** the duplicate call is harmless. + */ + sqlite3WalEndReadTransaction(pPager->pWal); + + rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed); + if( rc!=SQLITE_OK || changed ){ + pager_reset(pPager); + if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); + } + + return rc; +} +#endif + +/* +** This function is called as part of the transition from PAGER_OPEN +** to PAGER_READER state to determine the size of the database file +** in pages (assuming the page size currently stored in Pager.pageSize). +** +** If no error occurs, SQLITE_OK is returned and the size of the database +** in pages is stored in *pnPage. Otherwise, an error code (perhaps +** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified. +*/ +static int pagerPagecount(Pager *pPager, Pgno *pnPage){ + Pgno nPage; /* Value to return via *pnPage */ + + /* Query the WAL sub-system for the database size. The WalDbsize() + ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or + ** if the database size is not available. The database size is not + ** available from the WAL sub-system if the log file is empty or + ** contains no valid committed transactions. + */ + assert( pPager->eState==PAGER_OPEN ); + assert( pPager->eLock>=SHARED_LOCK ); + nPage = sqlite3WalDbsize(pPager->pWal); + + /* If the database size was not available from the WAL sub-system, + ** determine it based on the size of the database file. If the size + ** of the database file is not an integer multiple of the page-size, + ** round down to the nearest page. Except, any file larger than 0 + ** bytes in size is considered to contain at least one page. + */ + if( nPage==0 ){ + i64 n = 0; /* Size of db file in bytes */ + assert( isOpen(pPager->fd) || pPager->tempFile ); + if( isOpen(pPager->fd) ){ + int rc = sqlite3OsFileSize(pPager->fd, &n); + if( rc!=SQLITE_OK ){ + return rc; + } + } + nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize); + } + + /* If the current number of pages in the file is greater than the + ** configured maximum pager number, increase the allowed limit so + ** that the file can be read. + */ + if( nPage>pPager->mxPgno ){ + pPager->mxPgno = (Pgno)nPage; + } + + *pnPage = nPage; + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_WAL +/* +** Check if the *-wal file that corresponds to the database opened by pPager +** exists if the database is not empy, or verify that the *-wal file does +** not exist (by deleting it) if the database file is empty. +** +** If the database is not empty and the *-wal file exists, open the pager +** in WAL mode. If the database is empty or if no *-wal file exists and +** if no error occurs, make sure Pager.journalMode is not set to +** PAGER_JOURNALMODE_WAL. +** +** Return SQLITE_OK or an error code. +** +** The caller must hold a SHARED lock on the database file to call this +** function. Because an EXCLUSIVE lock on the db file is required to delete +** a WAL on a none-empty database, this ensures there is no race condition +** between the xAccess() below and an xDelete() being executed by some +** other connection. +*/ +static int pagerOpenWalIfPresent(Pager *pPager){ + int rc = SQLITE_OK; + assert( pPager->eState==PAGER_OPEN ); + assert( pPager->eLock>=SHARED_LOCK ); + + if( !pPager->tempFile ){ + int isWal; /* True if WAL file exists */ + Pgno nPage; /* Size of the database file */ + + rc = pagerPagecount(pPager, &nPage); + if( rc ) return rc; + if( nPage==0 ){ + rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0); + if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK; + isWal = 0; + }else{ + rc = sqlite3OsAccess( + pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal + ); + } + if( rc==SQLITE_OK ){ + if( isWal ){ + testcase( sqlite3PcachePagecount(pPager->pPCache)==0 ); + rc = sqlite3PagerOpenWal(pPager, 0); + }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){ + pPager->journalMode = PAGER_JOURNALMODE_DELETE; + } + } + } + return rc; +} +#endif + +/* +** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback +** the entire master journal file. The case pSavepoint==NULL occurs when +** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction +** savepoint. +** +** When pSavepoint is not NULL (meaning a non-transaction savepoint is +** being rolled back), then the rollback consists of up to three stages, +** performed in the order specified: +** +** * Pages are played back from the main journal starting at byte +** offset PagerSavepoint.iOffset and continuing to +** PagerSavepoint.iHdrOffset, or to the end of the main journal +** file if PagerSavepoint.iHdrOffset is zero. +** +** * If PagerSavepoint.iHdrOffset is not zero, then pages are played +** back starting from the journal header immediately following +** PagerSavepoint.iHdrOffset to the end of the main journal file. +** +** * Pages are then played back from the sub-journal file, starting +** with the PagerSavepoint.iSubRec and continuing to the end of +** the journal file. +** +** Throughout the rollback process, each time a page is rolled back, the +** corresponding bit is set in a bitvec structure (variable pDone in the +** implementation below). This is used to ensure that a page is only +** rolled back the first time it is encountered in either journal. +** +** If pSavepoint is NULL, then pages are only played back from the main +** journal file. There is no need for a bitvec in this case. +** +** In either case, before playback commences the Pager.dbSize variable +** is reset to the value that it held at the start of the savepoint +** (or transaction). No page with a page-number greater than this value +** is played back. If one is encountered it is simply skipped. +*/ +static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ + i64 szJ; /* Effective size of the main journal */ + i64 iHdrOff; /* End of first segment of main-journal records */ + int rc = SQLITE_OK; /* Return code */ + Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */ + + assert( pPager->eState!=PAGER_ERROR ); + assert( pPager->eState>=PAGER_WRITER_LOCKED ); + + /* Allocate a bitvec to use to store the set of pages rolled back */ + if( pSavepoint ){ + pDone = sqlite3BitvecCreate(pSavepoint->nOrig); + if( !pDone ){ + return SQLITE_NOMEM; + } + } + + /* Set the database size back to the value it was before the savepoint + ** being reverted was opened. + */ + pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize; + pPager->changeCountDone = pPager->tempFile; + + if( !pSavepoint && pagerUseWal(pPager) ){ + return pagerRollbackWal(pPager); + } + + /* Use pPager->journalOff as the effective size of the main rollback + ** journal. The actual file might be larger than this in + ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything + ** past pPager->journalOff is off-limits to us. + */ + szJ = pPager->journalOff; + assert( pagerUseWal(pPager)==0 || szJ==0 ); + + /* Begin by rolling back records from the main journal starting at + ** PagerSavepoint.iOffset and continuing to the next journal header. + ** There might be records in the main journal that have a page number + ** greater than the current database size (pPager->dbSize) but those + ** will be skipped automatically. Pages are added to pDone as they + ** are played back. + */ + if( pSavepoint && !pagerUseWal(pPager) ){ + iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ; + pPager->journalOff = pSavepoint->iOffset; + while( rc==SQLITE_OK && pPager->journalOffjournalOff, pDone, 1, 1); + } + assert( rc!=SQLITE_DONE ); + }else{ + pPager->journalOff = 0; + } + + /* Continue rolling back records out of the main journal starting at + ** the first journal header seen and continuing until the effective end + ** of the main journal file. Continue to skip out-of-range pages and + ** continue adding pages rolled back to pDone. + */ + while( rc==SQLITE_OK && pPager->journalOffjournalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff" + ** test is related to ticket #2565. See the discussion in the + ** pager_playback() function for additional information. + */ + if( nJRec==0 + && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff + ){ + nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager)); + } + for(ii=0; rc==SQLITE_OK && iijournalOffjournalOff, pDone, 1, 1); + } + assert( rc!=SQLITE_DONE ); + } + assert( rc!=SQLITE_OK || pPager->journalOff>=szJ ); + + /* Finally, rollback pages from the sub-journal. Page that were + ** previously rolled back out of the main journal (and are hence in pDone) + ** will be skipped. Out-of-range pages are also skipped. + */ + if( pSavepoint ){ + u32 ii; /* Loop counter */ + i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize); + + if( pagerUseWal(pPager) ){ + rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData); + } + for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && iinSubRec; ii++){ + assert( offset==(i64)ii*(4+pPager->pageSize) ); + rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1); + } + assert( rc!=SQLITE_DONE ); + } + + sqlite3BitvecDestroy(pDone); + if( rc==SQLITE_OK ){ + pPager->journalOff = szJ; + } + + return rc; +} + +/* +** Change the maximum number of in-memory pages that are allowed. +*/ +void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){ + sqlite3PcacheSetCachesize(pPager->pPCache, mxPage); +} + +/* +** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap. +*/ +static void pagerFixMaplimit(Pager *pPager){ +#if SQLITE_MAX_MMAP_SIZE>0 + sqlite3_file *fd = pPager->fd; + if( isOpen(fd) && fd->pMethods->iVersion>=3 ){ + sqlite3_int64 sz; + sz = pPager->szMmap; + pPager->bUseFetch = (sz>0); + sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz); + } +#endif +} + +/* +** Change the maximum size of any memory mapping made of the database file. +*/ +void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){ + pPager->szMmap = szMmap; + pagerFixMaplimit(pPager); +} + +/* +** Free as much memory as possible from the pager. +*/ +void sqlite3PagerShrink(Pager *pPager){ + sqlite3PcacheShrink(pPager->pPCache); +} + +/* +** Adjust settings of the pager to those specified in the pgFlags parameter. +** +** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness +** of the database to damage due to OS crashes or power failures by +** changing the number of syncs()s when writing the journals. +** There are three levels: +** +** OFF sqlite3OsSync() is never called. This is the default +** for temporary and transient files. +** +** NORMAL The journal is synced once before writes begin on the +** database. This is normally adequate protection, but +** it is theoretically possible, though very unlikely, +** that an inopertune power failure could leave the journal +** in a state which would cause damage to the database +** when it is rolled back. +** +** FULL The journal is synced twice before writes begin on the +** database (with some additional information - the nRec field +** of the journal header - being written in between the two +** syncs). If we assume that writing a +** single disk sector is atomic, then this mode provides +** assurance that the journal will not be corrupted to the +** point of causing damage to the database during rollback. +** +** The above is for a rollback-journal mode. For WAL mode, OFF continues +** to mean that no syncs ever occur. NORMAL means that the WAL is synced +** prior to the start of checkpoint and that the database file is synced +** at the conclusion of the checkpoint if the entire content of the WAL +** was written back into the database. But no sync operations occur for +** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL +** file is synced following each commit operation, in addition to the +** syncs associated with NORMAL. +** +** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The +** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync +** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an +** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL +** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the +** synchronous=FULL versus synchronous=NORMAL setting determines when +** the xSync primitive is called and is relevant to all platforms. +** +** Numeric values associated with these states are OFF==1, NORMAL=2, +** and FULL=3. +*/ +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +void sqlite3PagerSetFlags( + Pager *pPager, /* The pager to set safety level for */ + unsigned pgFlags /* Various flags */ +){ + unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK; + assert( level>=1 && level<=3 ); + pPager->noSync = (level==1 || pPager->tempFile) ?1:0; + pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0; + if( pPager->noSync ){ + pPager->syncFlags = 0; + pPager->ckptSyncFlags = 0; + }else if( pgFlags & PAGER_FULLFSYNC ){ + pPager->syncFlags = SQLITE_SYNC_FULL; + pPager->ckptSyncFlags = SQLITE_SYNC_FULL; + }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){ + pPager->syncFlags = SQLITE_SYNC_NORMAL; + pPager->ckptSyncFlags = SQLITE_SYNC_FULL; + }else{ + pPager->syncFlags = SQLITE_SYNC_NORMAL; + pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; + } + pPager->walSyncFlags = pPager->syncFlags; + if( pPager->fullSync ){ + pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS; + } + if( pgFlags & PAGER_CACHESPILL ){ + pPager->doNotSpill &= ~SPILLFLAG_OFF; + }else{ + pPager->doNotSpill |= SPILLFLAG_OFF; + } +} +#endif + +/* +** The following global variable is incremented whenever the library +** attempts to open a temporary file. This information is used for +** testing and analysis only. +*/ +#ifdef SQLITE_TEST +int sqlite3_opentemp_count = 0; +#endif + +/* +** Open a temporary file. +** +** Write the file descriptor into *pFile. Return SQLITE_OK on success +** or some other error code if we fail. The OS will automatically +** delete the temporary file when it is closed. +** +** The flags passed to the VFS layer xOpen() call are those specified +** by parameter vfsFlags ORed with the following: +** +** SQLITE_OPEN_READWRITE +** SQLITE_OPEN_CREATE +** SQLITE_OPEN_EXCLUSIVE +** SQLITE_OPEN_DELETEONCLOSE +*/ +static int pagerOpentemp( + Pager *pPager, /* The pager object */ + sqlite3_file *pFile, /* Write the file descriptor here */ + int vfsFlags /* Flags passed through to the VFS */ +){ + int rc; /* Return code */ + +#ifdef SQLITE_TEST + sqlite3_opentemp_count++; /* Used for testing and analysis only */ +#endif + + vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; + rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0); + assert( rc!=SQLITE_OK || isOpen(pFile) ); + return rc; +} + +/* +** Set the busy handler function. +** +** The pager invokes the busy-handler if sqlite3OsLock() returns +** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock, +** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE +** lock. It does *not* invoke the busy handler when upgrading from +** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE +** (which occurs during hot-journal rollback). Summary: +** +** Transition | Invokes xBusyHandler +** -------------------------------------------------------- +** NO_LOCK -> SHARED_LOCK | Yes +** SHARED_LOCK -> RESERVED_LOCK | No +** SHARED_LOCK -> EXCLUSIVE_LOCK | No +** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes +** +** If the busy-handler callback returns non-zero, the lock is +** retried. If it returns zero, then the SQLITE_BUSY error is +** returned to the caller of the pager API function. +*/ +void sqlite3PagerSetBusyhandler( + Pager *pPager, /* Pager object */ + int (*xBusyHandler)(void *), /* Pointer to busy-handler function */ + void *pBusyHandlerArg /* Argument to pass to xBusyHandler */ +){ + pPager->xBusyHandler = xBusyHandler; + pPager->pBusyHandlerArg = pBusyHandlerArg; + + if( isOpen(pPager->fd) ){ + void **ap = (void **)&pPager->xBusyHandler; + assert( ((int(*)(void *))(ap[0]))==xBusyHandler ); + assert( ap[1]==pBusyHandlerArg ); + sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap); + } +} + +/* +** Change the page size used by the Pager object. The new page size +** is passed in *pPageSize. +** +** If the pager is in the error state when this function is called, it +** is a no-op. The value returned is the error state error code (i.e. +** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL). +** +** Otherwise, if all of the following are true: +** +** * the new page size (value of *pPageSize) is valid (a power +** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and +** +** * there are no outstanding page references, and +** +** * the database is either not an in-memory database or it is +** an in-memory database that currently consists of zero pages. +** +** then the pager object page size is set to *pPageSize. +** +** If the page size is changed, then this function uses sqlite3PagerMalloc() +** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt +** fails, SQLITE_NOMEM is returned and the page size remains unchanged. +** In all other cases, SQLITE_OK is returned. +** +** If the page size is not changed, either because one of the enumerated +** conditions above is not true, the pager was in error state when this +** function was called, or because the memory allocation attempt failed, +** then *pPageSize is set to the old, retained page size before returning. +*/ +int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){ + int rc = SQLITE_OK; + + /* It is not possible to do a full assert_pager_state() here, as this + ** function may be called from within PagerOpen(), before the state + ** of the Pager object is internally consistent. + ** + ** At one point this function returned an error if the pager was in + ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that + ** there is at least one outstanding page reference, this function + ** is a no-op for that case anyhow. + */ + + u32 pageSize = *pPageSize; + assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) ); + if( (pPager->memDb==0 || pPager->dbSize==0) + && sqlite3PcacheRefCount(pPager->pPCache)==0 + && pageSize && pageSize!=(u32)pPager->pageSize + ){ + char *pNew = NULL; /* New temp space */ + i64 nByte = 0; + + if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){ + rc = sqlite3OsFileSize(pPager->fd, &nByte); + } + if( rc==SQLITE_OK ){ + pNew = (char *)sqlite3PageMalloc(pageSize); + if( !pNew ) rc = SQLITE_NOMEM; + } + + if( rc==SQLITE_OK ){ + pager_reset(pPager); + pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize); + pPager->pageSize = pageSize; + sqlite3PageFree(pPager->pTmpSpace); + pPager->pTmpSpace = pNew; + sqlite3PcacheSetPageSize(pPager->pPCache, pageSize); + } + } + + *pPageSize = pPager->pageSize; + if( rc==SQLITE_OK ){ + if( nReserve<0 ) nReserve = pPager->nReserve; + assert( nReserve>=0 && nReserve<1000 ); + pPager->nReserve = (i16)nReserve; + pagerReportSize(pPager); + pagerFixMaplimit(pPager); + } + return rc; +} + +/* +** Return a pointer to the "temporary page" buffer held internally +** by the pager. This is a buffer that is big enough to hold the +** entire content of a database page. This buffer is used internally +** during rollback and will be overwritten whenever a rollback +** occurs. But other modules are free to use it too, as long as +** no rollbacks are happening. +*/ +void *sqlite3PagerTempSpace(Pager *pPager){ + return pPager->pTmpSpace; +} + +/* +** Attempt to set the maximum database page count if mxPage is positive. +** Make no changes if mxPage is zero or negative. And never reduce the +** maximum page count below the current size of the database. +** +** Regardless of mxPage, return the current maximum page count. +*/ +int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){ + if( mxPage>0 ){ + pPager->mxPgno = mxPage; + } + assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */ + assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */ + return pPager->mxPgno; +} + +/* +** The following set of routines are used to disable the simulated +** I/O error mechanism. These routines are used to avoid simulated +** errors in places where we do not care about errors. +** +** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops +** and generate no code. +*/ +#ifdef SQLITE_TEST +extern int sqlite3_io_error_pending; +extern int sqlite3_io_error_hit; +static int saved_cnt; +void disable_simulated_io_errors(void){ + saved_cnt = sqlite3_io_error_pending; + sqlite3_io_error_pending = -1; +} +void enable_simulated_io_errors(void){ + sqlite3_io_error_pending = saved_cnt; +} +#else +# define disable_simulated_io_errors() +# define enable_simulated_io_errors() +#endif + +/* +** Read the first N bytes from the beginning of the file into memory +** that pDest points to. +** +** If the pager was opened on a transient file (zFilename==""), or +** opened on a file less than N bytes in size, the output buffer is +** zeroed and SQLITE_OK returned. The rationale for this is that this +** function is used to read database headers, and a new transient or +** zero sized database has a header than consists entirely of zeroes. +** +** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered, +** the error code is returned to the caller and the contents of the +** output buffer undefined. +*/ +int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){ + int rc = SQLITE_OK; + memset(pDest, 0, N); + assert( isOpen(pPager->fd) || pPager->tempFile ); + + /* This routine is only called by btree immediately after creating + ** the Pager object. There has not been an opportunity to transition + ** to WAL mode yet. + */ + assert( !pagerUseWal(pPager) ); + + if( isOpen(pPager->fd) ){ + IOTRACE(("DBHDR %p 0 %d\n", pPager, N)) + rc = sqlite3OsRead(pPager->fd, pDest, N, 0); + if( rc==SQLITE_IOERR_SHORT_READ ){ + rc = SQLITE_OK; + } + } + return rc; +} + +/* +** This function may only be called when a read-transaction is open on +** the pager. It returns the total number of pages in the database. +** +** However, if the file is between 1 and bytes in size, then +** this is considered a 1 page file. +*/ +void sqlite3PagerPagecount(Pager *pPager, int *pnPage){ + assert( pPager->eState>=PAGER_READER ); + assert( pPager->eState!=PAGER_WRITER_FINISHED ); + *pnPage = (int)pPager->dbSize; +} + + +/* +** Try to obtain a lock of type locktype on the database file. If +** a similar or greater lock is already held, this function is a no-op +** (returning SQLITE_OK immediately). +** +** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke +** the busy callback if the lock is currently not available. Repeat +** until the busy callback returns false or until the attempt to +** obtain the lock succeeds. +** +** Return SQLITE_OK on success and an error code if we cannot obtain +** the lock. If the lock is obtained successfully, set the Pager.state +** variable to locktype before returning. +*/ +static int pager_wait_on_lock(Pager *pPager, int locktype){ + int rc; /* Return code */ + + /* Check that this is either a no-op (because the requested lock is + ** already held, or one of the transistions that the busy-handler + ** may be invoked during, according to the comment above + ** sqlite3PagerSetBusyhandler(). + */ + assert( (pPager->eLock>=locktype) + || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK) + || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK) + ); + + do { + rc = pagerLockDb(pPager, locktype); + }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) ); + return rc; +} + +/* +** Function assertTruncateConstraint(pPager) checks that one of the +** following is true for all dirty pages currently in the page-cache: +** +** a) The page number is less than or equal to the size of the +** current database image, in pages, OR +** +** b) if the page content were written at this time, it would not +** be necessary to write the current content out to the sub-journal +** (as determined by function subjRequiresPage()). +** +** If the condition asserted by this function were not true, and the +** dirty page were to be discarded from the cache via the pagerStress() +** routine, pagerStress() would not write the current page content to +** the database file. If a savepoint transaction were rolled back after +** this happened, the correct behavior would be to restore the current +** content of the page. However, since this content is not present in either +** the database file or the portion of the rollback journal and +** sub-journal rolled back the content could not be restored and the +** database image would become corrupt. It is therefore fortunate that +** this circumstance cannot arise. +*/ +#if defined(SQLITE_DEBUG) +static void assertTruncateConstraintCb(PgHdr *pPg){ + assert( pPg->flags&PGHDR_DIRTY ); + assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize ); +} +static void assertTruncateConstraint(Pager *pPager){ + sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb); +} +#else +# define assertTruncateConstraint(pPager) +#endif + +/* +** Truncate the in-memory database file image to nPage pages. This +** function does not actually modify the database file on disk. It +** just sets the internal state of the pager object so that the +** truncation will be done when the current transaction is committed. +** +** This function is only called right before committing a transaction. +** Once this function has been called, the transaction must either be +** rolled back or committed. It is not safe to call this function and +** then continue writing to the database. +*/ +void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){ + assert( pPager->dbSize>=nPage ); + assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); + pPager->dbSize = nPage; + + /* At one point the code here called assertTruncateConstraint() to + ** ensure that all pages being truncated away by this operation are, + ** if one or more savepoints are open, present in the savepoint + ** journal so that they can be restored if the savepoint is rolled + ** back. This is no longer necessary as this function is now only + ** called right before committing a transaction. So although the + ** Pager object may still have open savepoints (Pager.nSavepoint!=0), + ** they cannot be rolled back. So the assertTruncateConstraint() call + ** is no longer correct. */ +} + + +/* +** This function is called before attempting a hot-journal rollback. It +** syncs the journal file to disk, then sets pPager->journalHdr to the +** size of the journal file so that the pager_playback() routine knows +** that the entire journal file has been synced. +** +** Syncing a hot-journal to disk before attempting to roll it back ensures +** that if a power-failure occurs during the rollback, the process that +** attempts rollback following system recovery sees the same journal +** content as this process. +** +** If everything goes as planned, SQLITE_OK is returned. Otherwise, +** an SQLite error code. +*/ +static int pagerSyncHotJournal(Pager *pPager){ + int rc = SQLITE_OK; + if( !pPager->noSync ){ + rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL); + } + if( rc==SQLITE_OK ){ + rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr); + } + return rc; +} + +/* +** Obtain a reference to a memory mapped page object for page number pgno. +** The new object will use the pointer pData, obtained from xFetch(). +** If successful, set *ppPage to point to the new page reference +** and return SQLITE_OK. Otherwise, return an SQLite error code and set +** *ppPage to zero. +** +** Page references obtained by calling this function should be released +** by calling pagerReleaseMapPage(). +*/ +static int pagerAcquireMapPage( + Pager *pPager, /* Pager object */ + Pgno pgno, /* Page number */ + void *pData, /* xFetch()'d data for this page */ + PgHdr **ppPage /* OUT: Acquired page object */ +){ + PgHdr *p; /* Memory mapped page to return */ + + if( pPager->pMmapFreelist ){ + *ppPage = p = pPager->pMmapFreelist; + pPager->pMmapFreelist = p->pDirty; + p->pDirty = 0; + memset(p->pExtra, 0, pPager->nExtra); + }else{ + *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra); + if( p==0 ){ + sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData); + return SQLITE_NOMEM; + } + p->pExtra = (void *)&p[1]; + p->flags = PGHDR_MMAP; + p->nRef = 1; + p->pPager = pPager; + } + + assert( p->pExtra==(void *)&p[1] ); + assert( p->pPage==0 ); + assert( p->flags==PGHDR_MMAP ); + assert( p->pPager==pPager ); + assert( p->nRef==1 ); + + p->pgno = pgno; + p->pData = pData; + pPager->nMmapOut++; + + return SQLITE_OK; +} + +/* +** Release a reference to page pPg. pPg must have been returned by an +** earlier call to pagerAcquireMapPage(). +*/ +static void pagerReleaseMapPage(PgHdr *pPg){ + Pager *pPager = pPg->pPager; + pPager->nMmapOut--; + pPg->pDirty = pPager->pMmapFreelist; + pPager->pMmapFreelist = pPg; + + assert( pPager->fd->pMethods->iVersion>=3 ); + sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData); +} + +/* +** Free all PgHdr objects stored in the Pager.pMmapFreelist list. +*/ +static void pagerFreeMapHdrs(Pager *pPager){ + PgHdr *p; + PgHdr *pNext; + for(p=pPager->pMmapFreelist; p; p=pNext){ + pNext = p->pDirty; + sqlite3_free(p); + } +} + + +/* +** Shutdown the page cache. Free all memory and close all files. +** +** If a transaction was in progress when this routine is called, that +** transaction is rolled back. All outstanding pages are invalidated +** and their memory is freed. Any attempt to use a page associated +** with this page cache after this function returns will likely +** result in a coredump. +** +** This function always succeeds. If a transaction is active an attempt +** is made to roll it back. If an error occurs during the rollback +** a hot journal may be left in the filesystem but no error is returned +** to the caller. +*/ +int sqlite3PagerClose(Pager *pPager){ + u8 *pTmp = (u8 *)pPager->pTmpSpace; + + assert( assert_pager_state(pPager) ); + disable_simulated_io_errors(); + sqlite3BeginBenignMalloc(); + pagerFreeMapHdrs(pPager); + /* pPager->errCode = 0; */ + pPager->exclusiveMode = 0; +#ifndef SQLITE_OMIT_WAL + sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp); + pPager->pWal = 0; +#endif + pager_reset(pPager); + if( MEMDB ){ + pager_unlock(pPager); + }else{ + /* If it is open, sync the journal file before calling UnlockAndRollback. + ** If this is not done, then an unsynced portion of the open journal + ** file may be played back into the database. If a power failure occurs + ** while this is happening, the database could become corrupt. + ** + ** If an error occurs while trying to sync the journal, shift the pager + ** into the ERROR state. This causes UnlockAndRollback to unlock the + ** database and close the journal file without attempting to roll it + ** back or finalize it. The next database user will have to do hot-journal + ** rollback before accessing the database file. + */ + if( isOpen(pPager->jfd) ){ + pager_error(pPager, pagerSyncHotJournal(pPager)); + } + pagerUnlockAndRollback(pPager); + } + sqlite3EndBenignMalloc(); + enable_simulated_io_errors(); + PAGERTRACE(("CLOSE %d\n", PAGERID(pPager))); + IOTRACE(("CLOSE %p\n", pPager)) + sqlite3OsClose(pPager->jfd); + sqlite3OsClose(pPager->fd); + sqlite3PageFree(pTmp); + sqlite3PcacheClose(pPager->pPCache); + +#ifdef SQLITE_HAS_CODEC + if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); +#endif + + assert( !pPager->aSavepoint && !pPager->pInJournal ); + assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ); + + sqlite3_free(pPager); + return SQLITE_OK; +} + +#if !defined(NDEBUG) || defined(SQLITE_TEST) +/* +** Return the page number for page pPg. +*/ +Pgno sqlite3PagerPagenumber(DbPage *pPg){ + return pPg->pgno; +} +#endif + +/* +** Increment the reference count for page pPg. +*/ +void sqlite3PagerRef(DbPage *pPg){ + sqlite3PcacheRef(pPg); +} + +/* +** Sync the journal. In other words, make sure all the pages that have +** been written to the journal have actually reached the surface of the +** disk and can be restored in the event of a hot-journal rollback. +** +** If the Pager.noSync flag is set, then this function is a no-op. +** Otherwise, the actions required depend on the journal-mode and the +** device characteristics of the file-system, as follows: +** +** * If the journal file is an in-memory journal file, no action need +** be taken. +** +** * Otherwise, if the device does not support the SAFE_APPEND property, +** then the nRec field of the most recently written journal header +** is updated to contain the number of journal records that have +** been written following it. If the pager is operating in full-sync +** mode, then the journal file is synced before this field is updated. +** +** * If the device does not support the SEQUENTIAL property, then +** journal file is synced. +** +** Or, in pseudo-code: +** +** if( NOT ){ +** if( NOT SAFE_APPEND ){ +** if( ) xSync(); +** +** } +** if( NOT SEQUENTIAL ) xSync(); +** } +** +** If successful, this routine clears the PGHDR_NEED_SYNC flag of every +** page currently held in memory before returning SQLITE_OK. If an IO +** error is encountered, then the IO error code is returned to the caller. +*/ +static int syncJournal(Pager *pPager, int newHdr){ + int rc; /* Return code */ + + assert( pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + ); + assert( assert_pager_state(pPager) ); + assert( !pagerUseWal(pPager) ); + + rc = sqlite3PagerExclusiveLock(pPager); + if( rc!=SQLITE_OK ) return rc; + + if( !pPager->noSync ){ + assert( !pPager->tempFile ); + if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){ + const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); + assert( isOpen(pPager->jfd) ); + + if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ + /* This block deals with an obscure problem. If the last connection + ** that wrote to this database was operating in persistent-journal + ** mode, then the journal file may at this point actually be larger + ** than Pager.journalOff bytes. If the next thing in the journal + ** file happens to be a journal-header (written as part of the + ** previous connection's transaction), and a crash or power-failure + ** occurs after nRec is updated but before this connection writes + ** anything else to the journal file (or commits/rolls back its + ** transaction), then SQLite may become confused when doing the + ** hot-journal rollback following recovery. It may roll back all + ** of this connections data, then proceed to rolling back the old, + ** out-of-date data that follows it. Database corruption. + ** + ** To work around this, if the journal file does appear to contain + ** a valid header following Pager.journalOff, then write a 0x00 + ** byte to the start of it to prevent it from being recognized. + ** + ** Variable iNextHdrOffset is set to the offset at which this + ** problematic header will occur, if it exists. aMagic is used + ** as a temporary buffer to inspect the first couple of bytes of + ** the potential journal header. + */ + i64 iNextHdrOffset; + u8 aMagic[8]; + u8 zHeader[sizeof(aJournalMagic)+4]; + + memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); + put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec); + + iNextHdrOffset = journalHdrOffset(pPager); + rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset); + if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){ + static const u8 zerobyte = 0; + rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset); + } + if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ + return rc; + } + + /* Write the nRec value into the journal file header. If in + ** full-synchronous mode, sync the journal first. This ensures that + ** all data has really hit the disk before nRec is updated to mark + ** it as a candidate for rollback. + ** + ** This is not required if the persistent media supports the + ** SAFE_APPEND property. Because in this case it is not possible + ** for garbage data to be appended to the file, the nRec field + ** is populated with 0xFFFFFFFF when the journal header is written + ** and never needs to be updated. + */ + if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ + PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); + IOTRACE(("JSYNC %p\n", pPager)) + rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); + if( rc!=SQLITE_OK ) return rc; + } + IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr)); + rc = sqlite3OsWrite( + pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr + ); + if( rc!=SQLITE_OK ) return rc; + } + if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ + PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); + IOTRACE(("JSYNC %p\n", pPager)) + rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| + (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0) + ); + if( rc!=SQLITE_OK ) return rc; + } + + pPager->journalHdr = pPager->journalOff; + if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ + pPager->nRec = 0; + rc = writeJournalHdr(pPager); + if( rc!=SQLITE_OK ) return rc; + } + }else{ + pPager->journalHdr = pPager->journalOff; + } + } + + /* Unless the pager is in noSync mode, the journal file was just + ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on + ** all pages. + */ + sqlite3PcacheClearSyncFlags(pPager->pPCache); + pPager->eState = PAGER_WRITER_DBMOD; + assert( assert_pager_state(pPager) ); + return SQLITE_OK; +} + +/* +** The argument is the first in a linked list of dirty pages connected +** by the PgHdr.pDirty pointer. This function writes each one of the +** in-memory pages in the list to the database file. The argument may +** be NULL, representing an empty list. In this case this function is +** a no-op. +** +** The pager must hold at least a RESERVED lock when this function +** is called. Before writing anything to the database file, this lock +** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained, +** SQLITE_BUSY is returned and no data is written to the database file. +** +** If the pager is a temp-file pager and the actual file-system file +** is not yet open, it is created and opened before any data is +** written out. +** +** Once the lock has been upgraded and, if necessary, the file opened, +** the pages are written out to the database file in list order. Writing +** a page is skipped if it meets either of the following criteria: +** +** * The page number is greater than Pager.dbSize, or +** * The PGHDR_DONT_WRITE flag is set on the page. +** +** If writing out a page causes the database file to grow, Pager.dbFileSize +** is updated accordingly. If page 1 is written out, then the value cached +** in Pager.dbFileVers[] is updated to match the new value stored in +** the database file. +** +** If everything is successful, SQLITE_OK is returned. If an IO error +** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot +** be obtained, SQLITE_BUSY is returned. +*/ +static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ + int rc = SQLITE_OK; /* Return code */ + + /* This function is only called for rollback pagers in WRITER_DBMOD state. */ + assert( !pagerUseWal(pPager) ); + assert( pPager->eState==PAGER_WRITER_DBMOD ); + assert( pPager->eLock==EXCLUSIVE_LOCK ); + + /* If the file is a temp-file has not yet been opened, open it now. It + ** is not possible for rc to be other than SQLITE_OK if this branch + ** is taken, as pager_wait_on_lock() is a no-op for temp-files. + */ + if( !isOpen(pPager->fd) ){ + assert( pPager->tempFile && rc==SQLITE_OK ); + rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags); + } + + /* Before the first write, give the VFS a hint of what the final + ** file size will be. + */ + assert( rc!=SQLITE_OK || isOpen(pPager->fd) ); + if( rc==SQLITE_OK + && pPager->dbHintSizedbSize + && (pList->pDirty || pList->pgno>pPager->dbHintSize) + ){ + sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize; + sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile); + pPager->dbHintSize = pPager->dbSize; + } + + while( rc==SQLITE_OK && pList ){ + Pgno pgno = pList->pgno; + + /* If there are dirty pages in the page cache with page numbers greater + ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to + ** make the file smaller (presumably by auto-vacuum code). Do not write + ** any such pages to the file. + ** + ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag + ** set (set by sqlite3PagerDontWrite()). + */ + if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){ + i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */ + char *pData; /* Data to write */ + + assert( (pList->flags&PGHDR_NEED_SYNC)==0 ); + if( pList->pgno==1 ) pager_write_changecounter(pList); + + /* Encode the database */ + CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData); + + /* Write out the page data. */ + rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset); + + /* If page 1 was just written, update Pager.dbFileVers to match + ** the value now stored in the database file. If writing this + ** page caused the database file to grow, update dbFileSize. + */ + if( pgno==1 ){ + memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers)); + } + if( pgno>pPager->dbFileSize ){ + pPager->dbFileSize = pgno; + } + pPager->aStat[PAGER_STAT_WRITE]++; + + /* Update any backup objects copying the contents of this pager. */ + sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData); + + PAGERTRACE(("STORE %d page %d hash(%08x)\n", + PAGERID(pPager), pgno, pager_pagehash(pList))); + IOTRACE(("PGOUT %p %d\n", pPager, pgno)); + PAGER_INCR(sqlite3_pager_writedb_count); + }else{ + PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno)); + } + pager_set_pagehash(pList); + pList = pList->pDirty; + } + + return rc; +} + +/* +** Ensure that the sub-journal file is open. If it is already open, this +** function is a no-op. +** +** SQLITE_OK is returned if everything goes according to plan. An +** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() +** fails. +*/ +static int openSubJournal(Pager *pPager){ + int rc = SQLITE_OK; + if( !isOpen(pPager->sjfd) ){ + if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){ + sqlite3MemJournalOpen(pPager->sjfd); + }else{ + rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL); + } + } + return rc; +} + +/* +** Append a record of the current state of page pPg to the sub-journal. +** It is the callers responsibility to use subjRequiresPage() to check +** that it is really required before calling this function. +** +** If successful, set the bit corresponding to pPg->pgno in the bitvecs +** for all open savepoints before returning. +** +** This function returns SQLITE_OK if everything is successful, an IO +** error code if the attempt to write to the sub-journal fails, or +** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint +** bitvec. +*/ +static int subjournalPage(PgHdr *pPg){ + int rc = SQLITE_OK; + Pager *pPager = pPg->pPager; + if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ + + /* Open the sub-journal, if it has not already been opened */ + assert( pPager->useJournal ); + assert( isOpen(pPager->jfd) || pagerUseWal(pPager) ); + assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 ); + assert( pagerUseWal(pPager) + || pageInJournal(pPg) + || pPg->pgno>pPager->dbOrigSize + ); + rc = openSubJournal(pPager); + + /* If the sub-journal was opened successfully (or was already open), + ** write the journal record into the file. */ + if( rc==SQLITE_OK ){ + void *pData = pPg->pData; + i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize); + char *pData2; + + CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2); + PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno)); + rc = write32bits(pPager->sjfd, offset, pPg->pgno); + if( rc==SQLITE_OK ){ + rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4); + } + } + } + if( rc==SQLITE_OK ){ + pPager->nSubRec++; + assert( pPager->nSavepoint>0 ); + rc = addToSavepointBitvecs(pPager, pPg->pgno); + } + return rc; +} + +/* +** This function is called by the pcache layer when it has reached some +** soft memory limit. The first argument is a pointer to a Pager object +** (cast as a void*). The pager is always 'purgeable' (not an in-memory +** database). The second argument is a reference to a page that is +** currently dirty but has no outstanding references. The page +** is always associated with the Pager object passed as the first +** argument. +** +** The job of this function is to make pPg clean by writing its contents +** out to the database file, if possible. This may involve syncing the +** journal file. +** +** If successful, sqlite3PcacheMakeClean() is called on the page and +** SQLITE_OK returned. If an IO error occurs while trying to make the +** page clean, the IO error code is returned. If the page cannot be +** made clean for some other reason, but no error occurs, then SQLITE_OK +** is returned by sqlite3PcacheMakeClean() is not called. +*/ +static int pagerStress(void *p, PgHdr *pPg){ + Pager *pPager = (Pager *)p; + int rc = SQLITE_OK; + + assert( pPg->pPager==pPager ); + assert( pPg->flags&PGHDR_DIRTY ); + + /* The doNotSpill NOSYNC bit is set during times when doing a sync of + ** journal (and adding a new header) is not allowed. This occurs + ** during calls to sqlite3PagerWrite() while trying to journal multiple + ** pages belonging to the same sector. + ** + ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling + ** regardless of whether or not a sync is required. This is set during + ** a rollback or by user request, respectively. + ** + ** Spilling is also prohibited when in an error state since that could + ** lead to database corruption. In the current implementaton it + ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1 + ** while in the error state, hence it is impossible for this routine to + ** be called in the error state. Nevertheless, we include a NEVER() + ** test for the error state as a safeguard against future changes. + */ + if( NEVER(pPager->errCode) ) return SQLITE_OK; + testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK ); + testcase( pPager->doNotSpill & SPILLFLAG_OFF ); + testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC ); + if( pPager->doNotSpill + && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0 + || (pPg->flags & PGHDR_NEED_SYNC)!=0) + ){ + return SQLITE_OK; + } + + pPg->pDirty = 0; + if( pagerUseWal(pPager) ){ + /* Write a single frame for this page to the log. */ + if( subjRequiresPage(pPg) ){ + rc = subjournalPage(pPg); + } + if( rc==SQLITE_OK ){ + rc = pagerWalFrames(pPager, pPg, 0, 0); + } + }else{ + + /* Sync the journal file if required. */ + if( pPg->flags&PGHDR_NEED_SYNC + || pPager->eState==PAGER_WRITER_CACHEMOD + ){ + rc = syncJournal(pPager, 1); + } + + /* If the page number of this page is larger than the current size of + ** the database image, it may need to be written to the sub-journal. + ** This is because the call to pager_write_pagelist() below will not + ** actually write data to the file in this case. + ** + ** Consider the following sequence of events: + ** + ** BEGIN; + ** + ** + ** SAVEPOINT sp; + ** + ** pagerStress(page X) + ** ROLLBACK TO sp; + ** + ** If (X>Y), then when pagerStress is called page X will not be written + ** out to the database file, but will be dropped from the cache. Then, + ** following the "ROLLBACK TO sp" statement, reading page X will read + ** data from the database file. This will be the copy of page X as it + ** was when the transaction started, not as it was when "SAVEPOINT sp" + ** was executed. + ** + ** The solution is to write the current data for page X into the + ** sub-journal file now (if it is not already there), so that it will + ** be restored to its current value when the "ROLLBACK TO sp" is + ** executed. + */ + if( NEVER( + rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg) + ) ){ + rc = subjournalPage(pPg); + } + + /* Write the contents of the page out to the database file. */ + if( rc==SQLITE_OK ){ + assert( (pPg->flags&PGHDR_NEED_SYNC)==0 ); + rc = pager_write_pagelist(pPager, pPg); + } + } + + /* Mark the page as clean. */ + if( rc==SQLITE_OK ){ + PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno)); + sqlite3PcacheMakeClean(pPg); + } + + return pager_error(pPager, rc); +} + + +/* +** Allocate and initialize a new Pager object and put a pointer to it +** in *ppPager. The pager should eventually be freed by passing it +** to sqlite3PagerClose(). +** +** The zFilename argument is the path to the database file to open. +** If zFilename is NULL then a randomly-named temporary file is created +** and used as the file to be cached. Temporary files are be deleted +** automatically when they are closed. If zFilename is ":memory:" then +** all information is held in cache. It is never written to disk. +** This can be used to implement an in-memory database. +** +** The nExtra parameter specifies the number of bytes of space allocated +** along with each page reference. This space is available to the user +** via the sqlite3PagerGetExtra() API. +** +** The flags argument is used to specify properties that affect the +** operation of the pager. It should be passed some bitwise combination +** of the PAGER_* flags. +** +** The vfsFlags parameter is a bitmask to pass to the flags parameter +** of the xOpen() method of the supplied VFS when opening files. +** +** If the pager object is allocated and the specified file opened +** successfully, SQLITE_OK is returned and *ppPager set to point to +** the new pager object. If an error occurs, *ppPager is set to NULL +** and error code returned. This function may return SQLITE_NOMEM +** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or +** various SQLITE_IO_XXX errors. +*/ +int sqlite3PagerOpen( + sqlite3_vfs *pVfs, /* The virtual file system to use */ + Pager **ppPager, /* OUT: Return the Pager structure here */ + const char *zFilename, /* Name of the database file to open */ + int nExtra, /* Extra bytes append to each in-memory page */ + int flags, /* flags controlling this file */ + int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */ + void (*xReinit)(DbPage*) /* Function to reinitialize pages */ +){ + u8 *pPtr; + Pager *pPager = 0; /* Pager object to allocate and return */ + int rc = SQLITE_OK; /* Return code */ + int tempFile = 0; /* True for temp files (incl. in-memory files) */ + int memDb = 0; /* True if this is an in-memory file */ + int readOnly = 0; /* True if this is a read-only file */ + int journalFileSize; /* Bytes to allocate for each journal fd */ + char *zPathname = 0; /* Full path to database file */ + int nPathname = 0; /* Number of bytes in zPathname */ + int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */ + int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */ + u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */ + const char *zUri = 0; /* URI args to copy */ + int nUri = 0; /* Number of bytes of URI args at *zUri */ + + /* Figure out how much space is required for each journal file-handle + ** (there are two of them, the main journal and the sub-journal). This + ** is the maximum space required for an in-memory journal file handle + ** and a regular journal file-handle. Note that a "regular journal-handle" + ** may be a wrapper capable of caching the first portion of the journal + ** file in memory to implement the atomic-write optimization (see + ** source file journal.c). + */ + if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){ + journalFileSize = ROUND8(sqlite3JournalSize(pVfs)); + }else{ + journalFileSize = ROUND8(sqlite3MemJournalSize()); + } + + /* Set the output variable to NULL in case an error occurs. */ + *ppPager = 0; + +#ifndef SQLITE_OMIT_MEMORYDB + if( flags & PAGER_MEMORY ){ + memDb = 1; + if( zFilename && zFilename[0] ){ + zPathname = sqlite3DbStrDup(0, zFilename); + if( zPathname==0 ) return SQLITE_NOMEM; + nPathname = sqlite3Strlen30(zPathname); + zFilename = 0; + } + } +#endif + + /* Compute and store the full pathname in an allocated buffer pointed + ** to by zPathname, length nPathname. Or, if this is a temporary file, + ** leave both nPathname and zPathname set to 0. + */ + if( zFilename && zFilename[0] ){ + const char *z; + nPathname = pVfs->mxPathname+1; + zPathname = sqlite3DbMallocRaw(0, nPathname*2); + if( zPathname==0 ){ + return SQLITE_NOMEM; + } + zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ + rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname); + nPathname = sqlite3Strlen30(zPathname); + z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1]; + while( *z ){ + z += sqlite3Strlen30(z)+1; + z += sqlite3Strlen30(z)+1; + } + nUri = (int)(&z[1] - zUri); + assert( nUri>=0 ); + if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){ + /* This branch is taken when the journal path required by + ** the database being opened will be more than pVfs->mxPathname + ** bytes in length. This means the database cannot be opened, + ** as it will not be possible to open the journal file or even + ** check for a hot-journal before reading. + */ + rc = SQLITE_CANTOPEN_BKPT; + } + if( rc!=SQLITE_OK ){ + sqlite3DbFree(0, zPathname); + return rc; + } + } + + /* Allocate memory for the Pager structure, PCache object, the + ** three file descriptors, the database file name and the journal + ** file name. The layout in memory is as follows: + ** + ** Pager object (sizeof(Pager) bytes) + ** PCache object (sqlite3PcacheSize() bytes) + ** Database file handle (pVfs->szOsFile bytes) + ** Sub-journal file handle (journalFileSize bytes) + ** Main journal file handle (journalFileSize bytes) + ** Database file name (nPathname+1 bytes) + ** Journal file name (nPathname+8+1 bytes) + */ + pPtr = (u8 *)sqlite3MallocZero( + ROUND8(sizeof(*pPager)) + /* Pager structure */ + ROUND8(pcacheSize) + /* PCache object */ + ROUND8(pVfs->szOsFile) + /* The main db file */ + journalFileSize * 2 + /* The two journal files */ + nPathname + 1 + nUri + /* zFilename */ + nPathname + 8 + 2 /* zJournal */ +#ifndef SQLITE_OMIT_WAL + + nPathname + 4 + 2 /* zWal */ +#endif + ); + assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) ); + if( !pPtr ){ + sqlite3DbFree(0, zPathname); + return SQLITE_NOMEM; + } + pPager = (Pager*)(pPtr); + pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager))); + pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize)); + pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile)); + pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize); + pPager->zFilename = (char*)(pPtr += journalFileSize); + assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) ); + + /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */ + if( zPathname ){ + assert( nPathname>0 ); + pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri); + memcpy(pPager->zFilename, zPathname, nPathname); + if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri); + memcpy(pPager->zJournal, zPathname, nPathname); + memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2); + sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal); +#ifndef SQLITE_OMIT_WAL + pPager->zWal = &pPager->zJournal[nPathname+8+1]; + memcpy(pPager->zWal, zPathname, nPathname); + memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1); + sqlite3FileSuffix3(pPager->zFilename, pPager->zWal); +#endif + sqlite3DbFree(0, zPathname); + } + pPager->pVfs = pVfs; + pPager->vfsFlags = vfsFlags; + + /* Open the pager file. + */ + if( zFilename && zFilename[0] ){ + int fout = 0; /* VFS flags returned by xOpen() */ + rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout); + assert( !memDb ); + readOnly = (fout&SQLITE_OPEN_READONLY); + + /* If the file was successfully opened for read/write access, + ** choose a default page size in case we have to create the + ** database file. The default page size is the maximum of: + ** + ** + SQLITE_DEFAULT_PAGE_SIZE, + ** + The value returned by sqlite3OsSectorSize() + ** + The largest page size that can be written atomically. + */ + if( rc==SQLITE_OK && !readOnly ){ + setSectorSize(pPager); + assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE); + if( szPageDfltsectorSize ){ + if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){ + szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE; + }else{ + szPageDflt = (u32)pPager->sectorSize; + } + } +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + { + int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); + int ii; + assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); + assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); + assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536); + for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){ + if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){ + szPageDflt = ii; + } + } + } +#endif + } + }else{ + /* If a temporary file is requested, it is not opened immediately. + ** In this case we accept the default page size and delay actually + ** opening the file until the first call to OsWrite(). + ** + ** This branch is also run for an in-memory database. An in-memory + ** database is the same as a temp-file that is never written out to + ** disk and uses an in-memory rollback journal. + */ + tempFile = 1; + pPager->eState = PAGER_READER; + pPager->eLock = EXCLUSIVE_LOCK; + readOnly = (vfsFlags&SQLITE_OPEN_READONLY); + } + + /* The following call to PagerSetPagesize() serves to set the value of + ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer. + */ + if( rc==SQLITE_OK ){ + assert( pPager->memDb==0 ); + rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1); + testcase( rc!=SQLITE_OK ); + } + + /* If an error occurred in either of the blocks above, free the + ** Pager structure and close the file. + */ + if( rc!=SQLITE_OK ){ + assert( !pPager->pTmpSpace ); + sqlite3OsClose(pPager->fd); + sqlite3_free(pPager); + return rc; + } + + /* Initialize the PCache object. */ + assert( nExtra<1000 ); + nExtra = ROUND8(nExtra); + sqlite3PcacheOpen(szPageDflt, nExtra, !memDb, + !memDb?pagerStress:0, (void *)pPager, pPager->pPCache); + + PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename)); + IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename)) + + pPager->useJournal = (u8)useJournal; + /* pPager->stmtOpen = 0; */ + /* pPager->stmtInUse = 0; */ + /* pPager->nRef = 0; */ + /* pPager->stmtSize = 0; */ + /* pPager->stmtJSize = 0; */ + /* pPager->nPage = 0; */ + pPager->mxPgno = SQLITE_MAX_PAGE_COUNT; + /* pPager->state = PAGER_UNLOCK; */ +#if 0 + assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) ); +#endif + /* pPager->errMask = 0; */ + pPager->tempFile = (u8)tempFile; + assert( tempFile==PAGER_LOCKINGMODE_NORMAL + || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE ); + assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 ); + pPager->exclusiveMode = (u8)tempFile; + pPager->changeCountDone = pPager->tempFile; + pPager->memDb = (u8)memDb; + pPager->readOnly = (u8)readOnly; + assert( useJournal || pPager->tempFile ); + pPager->noSync = pPager->tempFile; + if( pPager->noSync ){ + assert( pPager->fullSync==0 ); + assert( pPager->syncFlags==0 ); + assert( pPager->walSyncFlags==0 ); + assert( pPager->ckptSyncFlags==0 ); + }else{ + pPager->fullSync = 1; + pPager->syncFlags = SQLITE_SYNC_NORMAL; + pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS; + pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; + } + /* pPager->pFirst = 0; */ + /* pPager->pFirstSynced = 0; */ + /* pPager->pLast = 0; */ + pPager->nExtra = (u16)nExtra; + pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT; + assert( isOpen(pPager->fd) || tempFile ); + setSectorSize(pPager); + if( !useJournal ){ + pPager->journalMode = PAGER_JOURNALMODE_OFF; + }else if( memDb ){ + pPager->journalMode = PAGER_JOURNALMODE_MEMORY; + } + /* pPager->xBusyHandler = 0; */ + /* pPager->pBusyHandlerArg = 0; */ + pPager->xReiniter = xReinit; + /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */ + /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */ + + *ppPager = pPager; + return SQLITE_OK; +} + + + +/* +** This function is called after transitioning from PAGER_UNLOCK to +** PAGER_SHARED state. It tests if there is a hot journal present in +** the file-system for the given pager. A hot journal is one that +** needs to be played back. According to this function, a hot-journal +** file exists if the following criteria are met: +** +** * The journal file exists in the file system, and +** * No process holds a RESERVED or greater lock on the database file, and +** * The database file itself is greater than 0 bytes in size, and +** * The first byte of the journal file exists and is not 0x00. +** +** If the current size of the database file is 0 but a journal file +** exists, that is probably an old journal left over from a prior +** database with the same name. In this case the journal file is +** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK +** is returned. +** +** This routine does not check if there is a master journal filename +** at the end of the file. If there is, and that master journal file +** does not exist, then the journal file is not really hot. In this +** case this routine will return a false-positive. The pager_playback() +** routine will discover that the journal file is not really hot and +** will not roll it back. +** +** If a hot-journal file is found to exist, *pExists is set to 1 and +** SQLITE_OK returned. If no hot-journal file is present, *pExists is +** set to 0 and SQLITE_OK returned. If an IO error occurs while trying +** to determine whether or not a hot-journal file exists, the IO error +** code is returned and the value of *pExists is undefined. +*/ +static int hasHotJournal(Pager *pPager, int *pExists){ + sqlite3_vfs * const pVfs = pPager->pVfs; + int rc = SQLITE_OK; /* Return code */ + int exists = 1; /* True if a journal file is present */ + int jrnlOpen = !!isOpen(pPager->jfd); + + assert( pPager->useJournal ); + assert( isOpen(pPager->fd) ); + assert( pPager->eState==PAGER_OPEN ); + + assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) & + SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN + )); + + *pExists = 0; + if( !jrnlOpen ){ + rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists); + } + if( rc==SQLITE_OK && exists ){ + int locked = 0; /* True if some process holds a RESERVED lock */ + + /* Race condition here: Another process might have been holding the + ** the RESERVED lock and have a journal open at the sqlite3OsAccess() + ** call above, but then delete the journal and drop the lock before + ** we get to the following sqlite3OsCheckReservedLock() call. If that + ** is the case, this routine might think there is a hot journal when + ** in fact there is none. This results in a false-positive which will + ** be dealt with by the playback routine. Ticket #3883. + */ + rc = sqlite3OsCheckReservedLock(pPager->fd, &locked); + if( rc==SQLITE_OK && !locked ){ + Pgno nPage; /* Number of pages in database file */ + + /* Check the size of the database file. If it consists of 0 pages, + ** then delete the journal file. See the header comment above for + ** the reasoning here. Delete the obsolete journal file under + ** a RESERVED lock to avoid race conditions and to avoid violating + ** [H33020]. + */ + rc = pagerPagecount(pPager, &nPage); + if( rc==SQLITE_OK ){ + if( nPage==0 ){ + sqlite3BeginBenignMalloc(); + if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){ + sqlite3OsDelete(pVfs, pPager->zJournal, 0); + if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK); + } + sqlite3EndBenignMalloc(); + }else{ + /* The journal file exists and no other connection has a reserved + ** or greater lock on the database file. Now check that there is + ** at least one non-zero bytes at the start of the journal file. + ** If there is, then we consider this journal to be hot. If not, + ** it can be ignored. + */ + if( !jrnlOpen ){ + int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL; + rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f); + } + if( rc==SQLITE_OK ){ + u8 first = 0; + rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0); + if( rc==SQLITE_IOERR_SHORT_READ ){ + rc = SQLITE_OK; + } + if( !jrnlOpen ){ + sqlite3OsClose(pPager->jfd); + } + *pExists = (first!=0); + }else if( rc==SQLITE_CANTOPEN ){ + /* If we cannot open the rollback journal file in order to see if + ** its has a zero header, that might be due to an I/O error, or + ** it might be due to the race condition described above and in + ** ticket #3883. Either way, assume that the journal is hot. + ** This might be a false positive. But if it is, then the + ** automatic journal playback and recovery mechanism will deal + ** with it under an EXCLUSIVE lock where we do not need to + ** worry so much with race conditions. + */ + *pExists = 1; + rc = SQLITE_OK; + } + } + } + } + } + + return rc; +} + +/* +** This function is called to obtain a shared lock on the database file. +** It is illegal to call sqlite3PagerAcquire() until after this function +** has been successfully called. If a shared-lock is already held when +** this function is called, it is a no-op. +** +** The following operations are also performed by this function. +** +** 1) If the pager is currently in PAGER_OPEN state (no lock held +** on the database file), then an attempt is made to obtain a +** SHARED lock on the database file. Immediately after obtaining +** the SHARED lock, the file-system is checked for a hot-journal, +** which is played back if present. Following any hot-journal +** rollback, the contents of the cache are validated by checking +** the 'change-counter' field of the database file header and +** discarded if they are found to be invalid. +** +** 2) If the pager is running in exclusive-mode, and there are currently +** no outstanding references to any pages, and is in the error state, +** then an attempt is made to clear the error state by discarding +** the contents of the page cache and rolling back any open journal +** file. +** +** If everything is successful, SQLITE_OK is returned. If an IO error +** occurs while locking the database, checking for a hot-journal file or +** rolling back a journal file, the IO error code is returned. +*/ +int sqlite3PagerSharedLock(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + + /* This routine is only called from b-tree and only when there are no + ** outstanding pages. This implies that the pager state should either + ** be OPEN or READER. READER is only possible if the pager is or was in + ** exclusive access mode. + */ + assert( sqlite3PcacheRefCount(pPager->pPCache)==0 ); + assert( assert_pager_state(pPager) ); + assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); + if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; } + + if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){ + int bHotJournal = 1; /* True if there exists a hot journal-file */ + + assert( !MEMDB ); + + rc = pager_wait_on_lock(pPager, SHARED_LOCK); + if( rc!=SQLITE_OK ){ + assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK ); + goto failed; + } + + /* If a journal file exists, and there is no RESERVED lock on the + ** database file, then it either needs to be played back or deleted. + */ + if( pPager->eLock<=SHARED_LOCK ){ + rc = hasHotJournal(pPager, &bHotJournal); + } + if( rc!=SQLITE_OK ){ + goto failed; + } + if( bHotJournal ){ + if( pPager->readOnly ){ + rc = SQLITE_READONLY_ROLLBACK; + goto failed; + } + + /* Get an EXCLUSIVE lock on the database file. At this point it is + ** important that a RESERVED lock is not obtained on the way to the + ** EXCLUSIVE lock. If it were, another process might open the + ** database file, detect the RESERVED lock, and conclude that the + ** database is safe to read while this process is still rolling the + ** hot-journal back. + ** + ** Because the intermediate RESERVED lock is not requested, any + ** other process attempting to access the database file will get to + ** this point in the code and fail to obtain its own EXCLUSIVE lock + ** on the database file. + ** + ** Unless the pager is in locking_mode=exclusive mode, the lock is + ** downgraded to SHARED_LOCK before this function returns. + */ + rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); + if( rc!=SQLITE_OK ){ + goto failed; + } + + /* If it is not already open and the file exists on disk, open the + ** journal for read/write access. Write access is required because + ** in exclusive-access mode the file descriptor will be kept open + ** and possibly used for a transaction later on. Also, write-access + ** is usually required to finalize the journal in journal_mode=persist + ** mode (and also for journal_mode=truncate on some systems). + ** + ** If the journal does not exist, it usually means that some + ** other connection managed to get in and roll it back before + ** this connection obtained the exclusive lock above. Or, it + ** may mean that the pager was in the error-state when this + ** function was called and the journal file does not exist. + */ + if( !isOpen(pPager->jfd) ){ + sqlite3_vfs * const pVfs = pPager->pVfs; + int bExists; /* True if journal file exists */ + rc = sqlite3OsAccess( + pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists); + if( rc==SQLITE_OK && bExists ){ + int fout = 0; + int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL; + assert( !pPager->tempFile ); + rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); + assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); + if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){ + rc = SQLITE_CANTOPEN_BKPT; + sqlite3OsClose(pPager->jfd); + } + } + } + + /* Playback and delete the journal. Drop the database write + ** lock and reacquire the read lock. Purge the cache before + ** playing back the hot-journal so that we don't end up with + ** an inconsistent cache. Sync the hot journal before playing + ** it back since the process that crashed and left the hot journal + ** probably did not sync it and we are required to always sync + ** the journal before playing it back. + */ + if( isOpen(pPager->jfd) ){ + assert( rc==SQLITE_OK ); + rc = pagerSyncHotJournal(pPager); + if( rc==SQLITE_OK ){ + rc = pager_playback(pPager, 1); + pPager->eState = PAGER_OPEN; + } + }else if( !pPager->exclusiveMode ){ + pagerUnlockDb(pPager, SHARED_LOCK); + } + + if( rc!=SQLITE_OK ){ + /* This branch is taken if an error occurs while trying to open + ** or roll back a hot-journal while holding an EXCLUSIVE lock. The + ** pager_unlock() routine will be called before returning to unlock + ** the file. If the unlock attempt fails, then Pager.eLock must be + ** set to UNKNOWN_LOCK (see the comment above the #define for + ** UNKNOWN_LOCK above for an explanation). + ** + ** In order to get pager_unlock() to do this, set Pager.eState to + ** PAGER_ERROR now. This is not actually counted as a transition + ** to ERROR state in the state diagram at the top of this file, + ** since we know that the same call to pager_unlock() will very + ** shortly transition the pager object to the OPEN state. Calling + ** assert_pager_state() would fail now, as it should not be possible + ** to be in ERROR state when there are zero outstanding page + ** references. + */ + pager_error(pPager, rc); + goto failed; + } + + assert( pPager->eState==PAGER_OPEN ); + assert( (pPager->eLock==SHARED_LOCK) + || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK) + ); + } + + if( !pPager->tempFile && ( + pPager->pBackup + || sqlite3PcachePagecount(pPager->pPCache)>0 + || USEFETCH(pPager) + )){ + /* The shared-lock has just been acquired on the database file + ** and there are already pages in the cache (from a previous + ** read or write transaction). Check to see if the database + ** has been modified. If the database has changed, flush the + ** cache. + ** + ** Database changes is detected by looking at 15 bytes beginning + ** at offset 24 into the file. The first 4 of these 16 bytes are + ** a 32-bit counter that is incremented with each change. The + ** other bytes change randomly with each file change when + ** a codec is in use. + ** + ** There is a vanishingly small chance that a change will not be + ** detected. The chance of an undetected change is so small that + ** it can be neglected. + */ + Pgno nPage = 0; + char dbFileVers[sizeof(pPager->dbFileVers)]; + + rc = pagerPagecount(pPager, &nPage); + if( rc ) goto failed; + + if( nPage>0 ){ + IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers))); + rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24); + if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ + goto failed; + } + }else{ + memset(dbFileVers, 0, sizeof(dbFileVers)); + } + + if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){ + pager_reset(pPager); + + /* Unmap the database file. It is possible that external processes + ** may have truncated the database file and then extended it back + ** to its original size while this process was not holding a lock. + ** In this case there may exist a Pager.pMap mapping that appears + ** to be the right size but is not actually valid. Avoid this + ** possibility by unmapping the db here. */ + if( USEFETCH(pPager) ){ + sqlite3OsUnfetch(pPager->fd, 0, 0); + } + } + } + + /* If there is a WAL file in the file-system, open this database in WAL + ** mode. Otherwise, the following function call is a no-op. + */ + rc = pagerOpenWalIfPresent(pPager); +#ifndef SQLITE_OMIT_WAL + assert( pPager->pWal==0 || rc==SQLITE_OK ); +#endif + } + + if( pagerUseWal(pPager) ){ + assert( rc==SQLITE_OK ); + rc = pagerBeginReadTransaction(pPager); + } + + if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){ + rc = pagerPagecount(pPager, &pPager->dbSize); + } + + failed: + if( rc!=SQLITE_OK ){ + assert( !MEMDB ); + pager_unlock(pPager); + assert( pPager->eState==PAGER_OPEN ); + }else{ + pPager->eState = PAGER_READER; + } + return rc; +} + +/* +** If the reference count has reached zero, rollback any active +** transaction and unlock the pager. +** +** Except, in locking_mode=EXCLUSIVE when there is nothing to in +** the rollback journal, the unlock is not performed and there is +** nothing to rollback, so this routine is a no-op. +*/ +static void pagerUnlockIfUnused(Pager *pPager){ + if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){ + pagerUnlockAndRollback(pPager); + } +} + +/* +** Acquire a reference to page number pgno in pager pPager (a page +** reference has type DbPage*). If the requested reference is +** successfully obtained, it is copied to *ppPage and SQLITE_OK returned. +** +** If the requested page is already in the cache, it is returned. +** Otherwise, a new page object is allocated and populated with data +** read from the database file. In some cases, the pcache module may +** choose not to allocate a new page object and may reuse an existing +** object with no outstanding references. +** +** The extra data appended to a page is always initialized to zeros the +** first time a page is loaded into memory. If the page requested is +** already in the cache when this function is called, then the extra +** data is left as it was when the page object was last used. +** +** If the database image is smaller than the requested page or if a +** non-zero value is passed as the noContent parameter and the +** requested page is not already stored in the cache, then no +** actual disk read occurs. In this case the memory image of the +** page is initialized to all zeros. +** +** If noContent is true, it means that we do not care about the contents +** of the page. This occurs in two scenarios: +** +** a) When reading a free-list leaf page from the database, and +** +** b) When a savepoint is being rolled back and we need to load +** a new page into the cache to be filled with the data read +** from the savepoint journal. +** +** If noContent is true, then the data returned is zeroed instead of +** being read from the database. Additionally, the bits corresponding +** to pgno in Pager.pInJournal (bitvec of pages already written to the +** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open +** savepoints are set. This means if the page is made writable at any +** point in the future, using a call to sqlite3PagerWrite(), its contents +** will not be journaled. This saves IO. +** +** The acquisition might fail for several reasons. In all cases, +** an appropriate error code is returned and *ppPage is set to NULL. +** +** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt +** to find a page in the in-memory cache first. If the page is not already +** in memory, this routine goes to disk to read it in whereas Lookup() +** just returns 0. This routine acquires a read-lock the first time it +** has to go to disk, and could also playback an old journal if necessary. +** Since Lookup() never goes to disk, it never has to deal with locks +** or journal files. +*/ +int sqlite3PagerAcquire( + Pager *pPager, /* The pager open on the database file */ + Pgno pgno, /* Page number to fetch */ + DbPage **ppPage, /* Write a pointer to the page here */ + int flags /* PAGER_GET_XXX flags */ +){ + int rc = SQLITE_OK; + PgHdr *pPg = 0; + u32 iFrame = 0; /* Frame to read from WAL file */ + const int noContent = (flags & PAGER_GET_NOCONTENT); + + /* It is acceptable to use a read-only (mmap) page for any page except + ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY + ** flag was specified by the caller. And so long as the db is not a + ** temporary or in-memory database. */ + const int bMmapOk = (pgno!=1 && USEFETCH(pPager) + && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY)) +#ifdef SQLITE_HAS_CODEC + && pPager->xCodec==0 +#endif + ); + + assert( pPager->eState>=PAGER_READER ); + assert( assert_pager_state(pPager) ); + assert( noContent==0 || bMmapOk==0 ); + + if( pgno==0 ){ + return SQLITE_CORRUPT_BKPT; + } + + /* If the pager is in the error state, return an error immediately. + ** Otherwise, request the page from the PCache layer. */ + if( pPager->errCode!=SQLITE_OK ){ + rc = pPager->errCode; + }else{ + + if( bMmapOk && pagerUseWal(pPager) ){ + rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); + if( rc!=SQLITE_OK ) goto pager_acquire_err; + } + + if( iFrame==0 && bMmapOk ){ + void *pData = 0; + + rc = sqlite3OsFetch(pPager->fd, + (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData + ); + + if( rc==SQLITE_OK && pData ){ + if( pPager->eState>PAGER_READER ){ + (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg); + } + if( pPg==0 ){ + rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg); + }else{ + sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData); + } + if( pPg ){ + assert( rc==SQLITE_OK ); + *ppPage = pPg; + return SQLITE_OK; + } + } + if( rc!=SQLITE_OK ){ + goto pager_acquire_err; + } + } + + rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage); + } + + if( rc!=SQLITE_OK ){ + /* Either the call to sqlite3PcacheFetch() returned an error or the + ** pager was already in the error-state when this function was called. + ** Set pPg to 0 and jump to the exception handler. */ + pPg = 0; + goto pager_acquire_err; + } + assert( (*ppPage)->pgno==pgno ); + assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 ); + + if( (*ppPage)->pPager && !noContent ){ + /* In this case the pcache already contains an initialized copy of + ** the page. Return without further ado. */ + assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) ); + pPager->aStat[PAGER_STAT_HIT]++; + return SQLITE_OK; + + }else{ + /* The pager cache has created a new page. Its content needs to + ** be initialized. */ + + pPg = *ppPage; + pPg->pPager = pPager; + + /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page + ** number greater than this, or the unused locking-page, is requested. */ + if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){ + rc = SQLITE_CORRUPT_BKPT; + goto pager_acquire_err; + } + + if( MEMDB || pPager->dbSizefd) ){ + if( pgno>pPager->mxPgno ){ + rc = SQLITE_FULL; + goto pager_acquire_err; + } + if( noContent ){ + /* Failure to set the bits in the InJournal bit-vectors is benign. + ** It merely means that we might do some extra work to journal a + ** page that does not need to be journaled. Nevertheless, be sure + ** to test the case where a malloc error occurs while trying to set + ** a bit in a bit vector. + */ + sqlite3BeginBenignMalloc(); + if( pgno<=pPager->dbOrigSize ){ + TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno); + testcase( rc==SQLITE_NOMEM ); + } + TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno); + testcase( rc==SQLITE_NOMEM ); + sqlite3EndBenignMalloc(); + } + memset(pPg->pData, 0, pPager->pageSize); + IOTRACE(("ZERO %p %d\n", pPager, pgno)); + }else{ + if( pagerUseWal(pPager) && bMmapOk==0 ){ + rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); + if( rc!=SQLITE_OK ) goto pager_acquire_err; + } + assert( pPg->pPager==pPager ); + pPager->aStat[PAGER_STAT_MISS]++; + rc = readDbPage(pPg, iFrame); + if( rc!=SQLITE_OK ){ + goto pager_acquire_err; + } + } + pager_set_pagehash(pPg); + } + + return SQLITE_OK; + +pager_acquire_err: + assert( rc!=SQLITE_OK ); + if( pPg ){ + sqlite3PcacheDrop(pPg); + } + pagerUnlockIfUnused(pPager); + + *ppPage = 0; + return rc; +} + +/* +** Acquire a page if it is already in the in-memory cache. Do +** not read the page from disk. Return a pointer to the page, +** or 0 if the page is not in cache. +** +** See also sqlite3PagerGet(). The difference between this routine +** and sqlite3PagerGet() is that _get() will go to the disk and read +** in the page if the page is not already in cache. This routine +** returns NULL if the page is not in cache or if a disk I/O error +** has ever happened. +*/ +DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){ + PgHdr *pPg = 0; + assert( pPager!=0 ); + assert( pgno!=0 ); + assert( pPager->pPCache!=0 ); + assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR ); + sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg); + return pPg; +} + +/* +** Release a page reference. +** +** If the number of references to the page drop to zero, then the +** page is added to the LRU list. When all references to all pages +** are released, a rollback occurs and the lock on the database is +** removed. +*/ +void sqlite3PagerUnref(DbPage *pPg){ + if( pPg ){ + Pager *pPager = pPg->pPager; + if( pPg->flags & PGHDR_MMAP ){ + pagerReleaseMapPage(pPg); + }else{ + sqlite3PcacheRelease(pPg); + } + pagerUnlockIfUnused(pPager); + } +} + +/* +** This function is called at the start of every write transaction. +** There must already be a RESERVED or EXCLUSIVE lock on the database +** file when this routine is called. +** +** Open the journal file for pager pPager and write a journal header +** to the start of it. If there are active savepoints, open the sub-journal +** as well. This function is only used when the journal file is being +** opened to write a rollback log for a transaction. It is not used +** when opening a hot journal file to roll it back. +** +** If the journal file is already open (as it may be in exclusive mode), +** then this function just writes a journal header to the start of the +** already open file. +** +** Whether or not the journal file is opened by this function, the +** Pager.pInJournal bitvec structure is allocated. +** +** Return SQLITE_OK if everything is successful. Otherwise, return +** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or +** an IO error code if opening or writing the journal file fails. +*/ +static int pager_open_journal(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */ + + assert( pPager->eState==PAGER_WRITER_LOCKED ); + assert( assert_pager_state(pPager) ); + assert( pPager->pInJournal==0 ); + + /* If already in the error state, this function is a no-op. But on + ** the other hand, this routine is never called if we are already in + ** an error state. */ + if( NEVER(pPager->errCode) ) return pPager->errCode; + + if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ + pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize); + if( pPager->pInJournal==0 ){ + return SQLITE_NOMEM; + } + + /* Open the journal file if it is not already open. */ + if( !isOpen(pPager->jfd) ){ + if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){ + sqlite3MemJournalOpen(pPager->jfd); + }else{ + const int flags = /* VFS flags to open journal file */ + SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE| + (pPager->tempFile ? + (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL): + (SQLITE_OPEN_MAIN_JOURNAL) + ); + #ifdef SQLITE_ENABLE_ATOMIC_WRITE + rc = sqlite3JournalOpen( + pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager) + ); + #else + rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0); + #endif + } + assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); + } + + + /* Write the first journal header to the journal file and open + ** the sub-journal if necessary. + */ + if( rc==SQLITE_OK ){ + /* TODO: Check if all of these are really required. */ + pPager->nRec = 0; + pPager->journalOff = 0; + pPager->setMaster = 0; + pPager->journalHdr = 0; + rc = writeJournalHdr(pPager); + } + } + + if( rc!=SQLITE_OK ){ + sqlite3BitvecDestroy(pPager->pInJournal); + pPager->pInJournal = 0; + }else{ + assert( pPager->eState==PAGER_WRITER_LOCKED ); + pPager->eState = PAGER_WRITER_CACHEMOD; + } + + return rc; +} + +/* +** Begin a write-transaction on the specified pager object. If a +** write-transaction has already been opened, this function is a no-op. +** +** If the exFlag argument is false, then acquire at least a RESERVED +** lock on the database file. If exFlag is true, then acquire at least +** an EXCLUSIVE lock. If such a lock is already held, no locking +** functions need be called. +** +** If the subjInMemory argument is non-zero, then any sub-journal opened +** within this transaction will be opened as an in-memory file. This +** has no effect if the sub-journal is already opened (as it may be when +** running in exclusive mode) or if the transaction does not require a +** sub-journal. If the subjInMemory argument is zero, then any required +** sub-journal is implemented in-memory if pPager is an in-memory database, +** or using a temporary file otherwise. +*/ +int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){ + int rc = SQLITE_OK; + + if( pPager->errCode ) return pPager->errCode; + assert( pPager->eState>=PAGER_READER && pPager->eStatesubjInMemory = (u8)subjInMemory; + + if( ALWAYS(pPager->eState==PAGER_READER) ){ + assert( pPager->pInJournal==0 ); + + if( pagerUseWal(pPager) ){ + /* If the pager is configured to use locking_mode=exclusive, and an + ** exclusive lock on the database is not already held, obtain it now. + */ + if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){ + rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); + if( rc!=SQLITE_OK ){ + return rc; + } + sqlite3WalExclusiveMode(pPager->pWal, 1); + } + + /* Grab the write lock on the log file. If successful, upgrade to + ** PAGER_RESERVED state. Otherwise, return an error code to the caller. + ** The busy-handler is not invoked if another connection already + ** holds the write-lock. If possible, the upper layer will call it. + */ + rc = sqlite3WalBeginWriteTransaction(pPager->pWal); + }else{ + /* Obtain a RESERVED lock on the database file. If the exFlag parameter + ** is true, then immediately upgrade this to an EXCLUSIVE lock. The + ** busy-handler callback can be used when upgrading to the EXCLUSIVE + ** lock, but not when obtaining the RESERVED lock. + */ + rc = pagerLockDb(pPager, RESERVED_LOCK); + if( rc==SQLITE_OK && exFlag ){ + rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); + } + } + + if( rc==SQLITE_OK ){ + /* Change to WRITER_LOCKED state. + ** + ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD + ** when it has an open transaction, but never to DBMOD or FINISHED. + ** This is because in those states the code to roll back savepoint + ** transactions may copy data from the sub-journal into the database + ** file as well as into the page cache. Which would be incorrect in + ** WAL mode. + */ + pPager->eState = PAGER_WRITER_LOCKED; + pPager->dbHintSize = pPager->dbSize; + pPager->dbFileSize = pPager->dbSize; + pPager->dbOrigSize = pPager->dbSize; + pPager->journalOff = 0; + } + + assert( rc==SQLITE_OK || pPager->eState==PAGER_READER ); + assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED ); + assert( assert_pager_state(pPager) ); + } + + PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager))); + return rc; +} + +/* +** Mark a single data page as writeable. The page is written into the +** main journal or sub-journal as required. If the page is written into +** one of the journals, the corresponding bit is set in the +** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs +** of any open savepoints as appropriate. +*/ +static int pager_write(PgHdr *pPg){ + void *pData = pPg->pData; + Pager *pPager = pPg->pPager; + int rc = SQLITE_OK; + + /* This routine is not called unless a write-transaction has already + ** been started. The journal file may or may not be open at this point. + ** It is never called in the ERROR state. + */ + assert( pPager->eState==PAGER_WRITER_LOCKED + || pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + ); + assert( assert_pager_state(pPager) ); + + /* If an error has been previously detected, report the same error + ** again. This should not happen, but the check provides robustness. */ + if( NEVER(pPager->errCode) ) return pPager->errCode; + + /* Higher-level routines never call this function if database is not + ** writable. But check anyway, just for robustness. */ + if( NEVER(pPager->readOnly) ) return SQLITE_PERM; + + CHECK_PAGE(pPg); + + /* The journal file needs to be opened. Higher level routines have already + ** obtained the necessary locks to begin the write-transaction, but the + ** rollback journal might not yet be open. Open it now if this is the case. + ** + ** This is done before calling sqlite3PcacheMakeDirty() on the page. + ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then + ** an error might occur and the pager would end up in WRITER_LOCKED state + ** with pages marked as dirty in the cache. + */ + if( pPager->eState==PAGER_WRITER_LOCKED ){ + rc = pager_open_journal(pPager); + if( rc!=SQLITE_OK ) return rc; + } + assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); + assert( assert_pager_state(pPager) ); + + /* Mark the page as dirty. If the page has already been written + ** to the journal then we can return right away. + */ + sqlite3PcacheMakeDirty(pPg); + if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){ + assert( !pagerUseWal(pPager) ); + }else{ + + /* The transaction journal now exists and we have a RESERVED or an + ** EXCLUSIVE lock on the main database file. Write the current page to + ** the transaction journal if it is not there already. + */ + if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){ + assert( pagerUseWal(pPager)==0 ); + if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){ + u32 cksum; + char *pData2; + i64 iOff = pPager->journalOff; + + /* We should never write to the journal file the page that + ** contains the database locks. The following assert verifies + ** that we do not. */ + assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) ); + + assert( pPager->journalHdr<=pPager->journalOff ); + CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2); + cksum = pager_cksum(pPager, (u8*)pData2); + + /* Even if an IO or diskfull error occurs while journalling the + ** page in the block above, set the need-sync flag for the page. + ** Otherwise, when the transaction is rolled back, the logic in + ** playback_one_page() will think that the page needs to be restored + ** in the database file. And if an IO error occurs while doing so, + ** then corruption may follow. + */ + pPg->flags |= PGHDR_NEED_SYNC; + + rc = write32bits(pPager->jfd, iOff, pPg->pgno); + if( rc!=SQLITE_OK ) return rc; + rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4); + if( rc!=SQLITE_OK ) return rc; + rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum); + if( rc!=SQLITE_OK ) return rc; + + IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, + pPager->journalOff, pPager->pageSize)); + PAGER_INCR(sqlite3_pager_writej_count); + PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n", + PAGERID(pPager), pPg->pgno, + ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg))); + + pPager->journalOff += 8 + pPager->pageSize; + pPager->nRec++; + assert( pPager->pInJournal!=0 ); + rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno); + testcase( rc==SQLITE_NOMEM ); + assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); + rc |= addToSavepointBitvecs(pPager, pPg->pgno); + if( rc!=SQLITE_OK ){ + assert( rc==SQLITE_NOMEM ); + return rc; + } + }else{ + if( pPager->eState!=PAGER_WRITER_DBMOD ){ + pPg->flags |= PGHDR_NEED_SYNC; + } + PAGERTRACE(("APPEND %d page %d needSync=%d\n", + PAGERID(pPager), pPg->pgno, + ((pPg->flags&PGHDR_NEED_SYNC)?1:0))); + } + } + + /* If the statement journal is open and the page is not in it, + ** then write the current page to the statement journal. Note that + ** the statement journal format differs from the standard journal format + ** in that it omits the checksums and the header. + */ + if( subjRequiresPage(pPg) ){ + rc = subjournalPage(pPg); + } + } + + /* Update the database size and return. + */ + if( pPager->dbSizepgno ){ + pPager->dbSize = pPg->pgno; + } + return rc; +} + +/* +** Mark a data page as writeable. This routine must be called before +** making changes to a page. The caller must check the return value +** of this function and be careful not to change any page data unless +** this routine returns SQLITE_OK. +** +** The difference between this function and pager_write() is that this +** function also deals with the special case where 2 or more pages +** fit on a single disk sector. In this case all co-resident pages +** must have been written to the journal file before returning. +** +** If an error occurs, SQLITE_NOMEM or an IO error code is returned +** as appropriate. Otherwise, SQLITE_OK. +*/ +int sqlite3PagerWrite(DbPage *pDbPage){ + int rc = SQLITE_OK; + + PgHdr *pPg = pDbPage; + Pager *pPager = pPg->pPager; + Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize); + + assert( (pPg->flags & PGHDR_MMAP)==0 ); + assert( pPager->eState>=PAGER_WRITER_LOCKED ); + assert( pPager->eState!=PAGER_ERROR ); + assert( assert_pager_state(pPager) ); + + if( nPagePerSector>1 ){ + Pgno nPageCount; /* Total number of pages in database file */ + Pgno pg1; /* First page of the sector pPg is located on. */ + int nPage = 0; /* Number of pages starting at pg1 to journal */ + int ii; /* Loop counter */ + int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */ + + /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow + ** a journal header to be written between the pages journaled by + ** this function. + */ + assert( !MEMDB ); + assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 ); + pPager->doNotSpill |= SPILLFLAG_NOSYNC; + + /* This trick assumes that both the page-size and sector-size are + ** an integer power of 2. It sets variable pg1 to the identifier + ** of the first page of the sector pPg is located on. + */ + pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1; + + nPageCount = pPager->dbSize; + if( pPg->pgno>nPageCount ){ + nPage = (pPg->pgno - pg1)+1; + }else if( (pg1+nPagePerSector-1)>nPageCount ){ + nPage = nPageCount+1-pg1; + }else{ + nPage = nPagePerSector; + } + assert(nPage>0); + assert(pg1<=pPg->pgno); + assert((pg1+nPage)>pPg->pgno); + + for(ii=0; iipgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){ + if( pg!=PAGER_MJ_PGNO(pPager) ){ + rc = sqlite3PagerGet(pPager, pg, &pPage); + if( rc==SQLITE_OK ){ + rc = pager_write(pPage); + if( pPage->flags&PGHDR_NEED_SYNC ){ + needSync = 1; + } + sqlite3PagerUnref(pPage); + } + } + }else if( (pPage = pager_lookup(pPager, pg))!=0 ){ + if( pPage->flags&PGHDR_NEED_SYNC ){ + needSync = 1; + } + sqlite3PagerUnref(pPage); + } + } + + /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages + ** starting at pg1, then it needs to be set for all of them. Because + ** writing to any of these nPage pages may damage the others, the + ** journal file must contain sync()ed copies of all of them + ** before any of them can be written out to the database file. + */ + if( rc==SQLITE_OK && needSync ){ + assert( !MEMDB ); + for(ii=0; iiflags |= PGHDR_NEED_SYNC; + sqlite3PagerUnref(pPage); + } + } + } + + assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 ); + pPager->doNotSpill &= ~SPILLFLAG_NOSYNC; + }else{ + rc = pager_write(pDbPage); + } + return rc; +} + +/* +** Return TRUE if the page given in the argument was previously passed +** to sqlite3PagerWrite(). In other words, return TRUE if it is ok +** to change the content of the page. +*/ +#ifndef NDEBUG +int sqlite3PagerIswriteable(DbPage *pPg){ + return pPg->flags&PGHDR_DIRTY; +} +#endif + +/* +** A call to this routine tells the pager that it is not necessary to +** write the information on page pPg back to the disk, even though +** that page might be marked as dirty. This happens, for example, when +** the page has been added as a leaf of the freelist and so its +** content no longer matters. +** +** The overlying software layer calls this routine when all of the data +** on the given page is unused. The pager marks the page as clean so +** that it does not get written to disk. +** +** Tests show that this optimization can quadruple the speed of large +** DELETE operations. +*/ +void sqlite3PagerDontWrite(PgHdr *pPg){ + Pager *pPager = pPg->pPager; + if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){ + PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager))); + IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno)) + pPg->flags |= PGHDR_DONT_WRITE; + pager_set_pagehash(pPg); + } +} + +/* +** This routine is called to increment the value of the database file +** change-counter, stored as a 4-byte big-endian integer starting at +** byte offset 24 of the pager file. The secondary change counter at +** 92 is also updated, as is the SQLite version number at offset 96. +** +** But this only happens if the pPager->changeCountDone flag is false. +** To avoid excess churning of page 1, the update only happens once. +** See also the pager_write_changecounter() routine that does an +** unconditional update of the change counters. +** +** If the isDirectMode flag is zero, then this is done by calling +** sqlite3PagerWrite() on page 1, then modifying the contents of the +** page data. In this case the file will be updated when the current +** transaction is committed. +** +** The isDirectMode flag may only be non-zero if the library was compiled +** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case, +** if isDirect is non-zero, then the database file is updated directly +** by writing an updated version of page 1 using a call to the +** sqlite3OsWrite() function. +*/ +static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ + int rc = SQLITE_OK; + + assert( pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + ); + assert( assert_pager_state(pPager) ); + + /* Declare and initialize constant integer 'isDirect'. If the + ** atomic-write optimization is enabled in this build, then isDirect + ** is initialized to the value passed as the isDirectMode parameter + ** to this function. Otherwise, it is always set to zero. + ** + ** The idea is that if the atomic-write optimization is not + ** enabled at compile time, the compiler can omit the tests of + ** 'isDirect' below, as well as the block enclosed in the + ** "if( isDirect )" condition. + */ +#ifndef SQLITE_ENABLE_ATOMIC_WRITE +# define DIRECT_MODE 0 + assert( isDirectMode==0 ); + UNUSED_PARAMETER(isDirectMode); +#else +# define DIRECT_MODE isDirectMode +#endif + + if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){ + PgHdr *pPgHdr; /* Reference to page 1 */ + + assert( !pPager->tempFile && isOpen(pPager->fd) ); + + /* Open page 1 of the file for writing. */ + rc = sqlite3PagerGet(pPager, 1, &pPgHdr); + assert( pPgHdr==0 || rc==SQLITE_OK ); + + /* If page one was fetched successfully, and this function is not + ** operating in direct-mode, make page 1 writable. When not in + ** direct mode, page 1 is always held in cache and hence the PagerGet() + ** above is always successful - hence the ALWAYS on rc==SQLITE_OK. + */ + if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){ + rc = sqlite3PagerWrite(pPgHdr); + } + + if( rc==SQLITE_OK ){ + /* Actually do the update of the change counter */ + pager_write_changecounter(pPgHdr); + + /* If running in direct mode, write the contents of page 1 to the file. */ + if( DIRECT_MODE ){ + const void *zBuf; + assert( pPager->dbFileSize>0 ); + CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf); + if( rc==SQLITE_OK ){ + rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0); + pPager->aStat[PAGER_STAT_WRITE]++; + } + if( rc==SQLITE_OK ){ + /* Update the pager's copy of the change-counter. Otherwise, the + ** next time a read transaction is opened the cache will be + ** flushed (as the change-counter values will not match). */ + const void *pCopy = (const void *)&((const char *)zBuf)[24]; + memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers)); + pPager->changeCountDone = 1; + } + }else{ + pPager->changeCountDone = 1; + } + } + + /* Release the page reference. */ + sqlite3PagerUnref(pPgHdr); + } + return rc; +} + +/* +** Sync the database file to disk. This is a no-op for in-memory databases +** or pages with the Pager.noSync flag set. +** +** If successful, or if called on a pager for which it is a no-op, this +** function returns SQLITE_OK. Otherwise, an IO error code is returned. +*/ +int sqlite3PagerSync(Pager *pPager){ + int rc = SQLITE_OK; + if( !pPager->noSync ){ + assert( !MEMDB ); + rc = sqlite3OsSync(pPager->fd, pPager->syncFlags); + }else if( isOpen(pPager->fd) ){ + assert( !MEMDB ); + rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0); + if( rc==SQLITE_NOTFOUND ){ + rc = SQLITE_OK; + } + } + return rc; +} + +/* +** This function may only be called while a write-transaction is active in +** rollback. If the connection is in WAL mode, this call is a no-op. +** Otherwise, if the connection does not already have an EXCLUSIVE lock on +** the database file, an attempt is made to obtain one. +** +** If the EXCLUSIVE lock is already held or the attempt to obtain it is +** successful, or the connection is in WAL mode, SQLITE_OK is returned. +** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is +** returned. +*/ +int sqlite3PagerExclusiveLock(Pager *pPager){ + int rc = SQLITE_OK; + assert( pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + || pPager->eState==PAGER_WRITER_LOCKED + ); + assert( assert_pager_state(pPager) ); + if( 0==pagerUseWal(pPager) ){ + rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); + } + return rc; +} + +/* +** Sync the database file for the pager pPager. zMaster points to the name +** of a master journal file that should be written into the individual +** journal file. zMaster may be NULL, which is interpreted as no master +** journal (a single database transaction). +** +** This routine ensures that: +** +** * The database file change-counter is updated, +** * the journal is synced (unless the atomic-write optimization is used), +** * all dirty pages are written to the database file, +** * the database file is truncated (if required), and +** * the database file synced. +** +** The only thing that remains to commit the transaction is to finalize +** (delete, truncate or zero the first part of) the journal file (or +** delete the master journal file if specified). +** +** Note that if zMaster==NULL, this does not overwrite a previous value +** passed to an sqlite3PagerCommitPhaseOne() call. +** +** If the final parameter - noSync - is true, then the database file itself +** is not synced. The caller must call sqlite3PagerSync() directly to +** sync the database file before calling CommitPhaseTwo() to delete the +** journal file in this case. +*/ +int sqlite3PagerCommitPhaseOne( + Pager *pPager, /* Pager object */ + const char *zMaster, /* If not NULL, the master journal name */ + int noSync /* True to omit the xSync on the db file */ +){ + int rc = SQLITE_OK; /* Return code */ + + assert( pPager->eState==PAGER_WRITER_LOCKED + || pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + || pPager->eState==PAGER_ERROR + ); + assert( assert_pager_state(pPager) ); + + /* If a prior error occurred, report that error again. */ + if( NEVER(pPager->errCode) ) return pPager->errCode; + + PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", + pPager->zFilename, zMaster, pPager->dbSize)); + + /* If no database changes have been made, return early. */ + if( pPager->eStatepBackup); + }else{ + if( pagerUseWal(pPager) ){ + PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); + PgHdr *pPageOne = 0; + if( pList==0 ){ + /* Must have at least one page for the WAL commit flag. + ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */ + rc = sqlite3PagerGet(pPager, 1, &pPageOne); + pList = pPageOne; + pList->pDirty = 0; + } + assert( rc==SQLITE_OK ); + if( ALWAYS(pList) ){ + rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1); + } + sqlite3PagerUnref(pPageOne); + if( rc==SQLITE_OK ){ + sqlite3PcacheCleanAll(pPager->pPCache); + } + }else{ + /* The following block updates the change-counter. Exactly how it + ** does this depends on whether or not the atomic-update optimization + ** was enabled at compile time, and if this transaction meets the + ** runtime criteria to use the operation: + ** + ** * The file-system supports the atomic-write property for + ** blocks of size page-size, and + ** * This commit is not part of a multi-file transaction, and + ** * Exactly one page has been modified and store in the journal file. + ** + ** If the optimization was not enabled at compile time, then the + ** pager_incr_changecounter() function is called to update the change + ** counter in 'indirect-mode'. If the optimization is compiled in but + ** is not applicable to this transaction, call sqlite3JournalCreate() + ** to make sure the journal file has actually been created, then call + ** pager_incr_changecounter() to update the change-counter in indirect + ** mode. + ** + ** Otherwise, if the optimization is both enabled and applicable, + ** then call pager_incr_changecounter() to update the change-counter + ** in 'direct' mode. In this case the journal file will never be + ** created for this transaction. + */ + #ifdef SQLITE_ENABLE_ATOMIC_WRITE + PgHdr *pPg; + assert( isOpen(pPager->jfd) + || pPager->journalMode==PAGER_JOURNALMODE_OFF + || pPager->journalMode==PAGER_JOURNALMODE_WAL + ); + if( !zMaster && isOpen(pPager->jfd) + && pPager->journalOff==jrnlBufferSize(pPager) + && pPager->dbSize>=pPager->dbOrigSize + && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty) + ){ + /* Update the db file change counter via the direct-write method. The + ** following call will modify the in-memory representation of page 1 + ** to include the updated change counter and then write page 1 + ** directly to the database file. Because of the atomic-write + ** property of the host file-system, this is safe. + */ + rc = pager_incr_changecounter(pPager, 1); + }else{ + rc = sqlite3JournalCreate(pPager->jfd); + if( rc==SQLITE_OK ){ + rc = pager_incr_changecounter(pPager, 0); + } + } + #else + rc = pager_incr_changecounter(pPager, 0); + #endif + if( rc!=SQLITE_OK ) goto commit_phase_one_exit; + + /* Write the master journal name into the journal file. If a master + ** journal file name has already been written to the journal file, + ** or if zMaster is NULL (no master journal), then this call is a no-op. + */ + rc = writeMasterJournal(pPager, zMaster); + if( rc!=SQLITE_OK ) goto commit_phase_one_exit; + + /* Sync the journal file and write all dirty pages to the database. + ** If the atomic-update optimization is being used, this sync will not + ** create the journal file or perform any real IO. + ** + ** Because the change-counter page was just modified, unless the + ** atomic-update optimization is used it is almost certain that the + ** journal requires a sync here. However, in locking_mode=exclusive + ** on a system under memory pressure it is just possible that this is + ** not the case. In this case it is likely enough that the redundant + ** xSync() call will be changed to a no-op by the OS anyhow. + */ + rc = syncJournal(pPager, 0); + if( rc!=SQLITE_OK ) goto commit_phase_one_exit; + + rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache)); + if( rc!=SQLITE_OK ){ + assert( rc!=SQLITE_IOERR_BLOCKED ); + goto commit_phase_one_exit; + } + sqlite3PcacheCleanAll(pPager->pPCache); + + /* If the file on disk is smaller than the database image, use + ** pager_truncate to grow the file here. This can happen if the database + ** image was extended as part of the current transaction and then the + ** last page in the db image moved to the free-list. In this case the + ** last page is never written out to disk, leaving the database file + ** undersized. Fix this now if it is the case. */ + if( pPager->dbSize>pPager->dbFileSize ){ + Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager)); + assert( pPager->eState==PAGER_WRITER_DBMOD ); + rc = pager_truncate(pPager, nNew); + if( rc!=SQLITE_OK ) goto commit_phase_one_exit; + } + + /* Finally, sync the database file. */ + if( !noSync ){ + rc = sqlite3PagerSync(pPager); + } + IOTRACE(("DBSYNC %p\n", pPager)) + } + } + +commit_phase_one_exit: + if( rc==SQLITE_OK && !pagerUseWal(pPager) ){ + pPager->eState = PAGER_WRITER_FINISHED; + } + return rc; +} + + +/* +** When this function is called, the database file has been completely +** updated to reflect the changes made by the current transaction and +** synced to disk. The journal file still exists in the file-system +** though, and if a failure occurs at this point it will eventually +** be used as a hot-journal and the current transaction rolled back. +** +** This function finalizes the journal file, either by deleting, +** truncating or partially zeroing it, so that it cannot be used +** for hot-journal rollback. Once this is done the transaction is +** irrevocably committed. +** +** If an error occurs, an IO error code is returned and the pager +** moves into the error state. Otherwise, SQLITE_OK is returned. +*/ +int sqlite3PagerCommitPhaseTwo(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + + /* This routine should not be called if a prior error has occurred. + ** But if (due to a coding error elsewhere in the system) it does get + ** called, just return the same error code without doing anything. */ + if( NEVER(pPager->errCode) ) return pPager->errCode; + + assert( pPager->eState==PAGER_WRITER_LOCKED + || pPager->eState==PAGER_WRITER_FINISHED + || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD) + ); + assert( assert_pager_state(pPager) ); + + /* An optimization. If the database was not actually modified during + ** this transaction, the pager is running in exclusive-mode and is + ** using persistent journals, then this function is a no-op. + ** + ** The start of the journal file currently contains a single journal + ** header with the nRec field set to 0. If such a journal is used as + ** a hot-journal during hot-journal rollback, 0 changes will be made + ** to the database file. So there is no need to zero the journal + ** header. Since the pager is in exclusive mode, there is no need + ** to drop any locks either. + */ + if( pPager->eState==PAGER_WRITER_LOCKED + && pPager->exclusiveMode + && pPager->journalMode==PAGER_JOURNALMODE_PERSIST + ){ + assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff ); + pPager->eState = PAGER_READER; + return SQLITE_OK; + } + + PAGERTRACE(("COMMIT %d\n", PAGERID(pPager))); + rc = pager_end_transaction(pPager, pPager->setMaster, 1); + return pager_error(pPager, rc); +} + +/* +** If a write transaction is open, then all changes made within the +** transaction are reverted and the current write-transaction is closed. +** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR +** state if an error occurs. +** +** If the pager is already in PAGER_ERROR state when this function is called, +** it returns Pager.errCode immediately. No work is performed in this case. +** +** Otherwise, in rollback mode, this function performs two functions: +** +** 1) It rolls back the journal file, restoring all database file and +** in-memory cache pages to the state they were in when the transaction +** was opened, and +** +** 2) It finalizes the journal file, so that it is not used for hot +** rollback at any point in the future. +** +** Finalization of the journal file (task 2) is only performed if the +** rollback is successful. +** +** In WAL mode, all cache-entries containing data modified within the +** current transaction are either expelled from the cache or reverted to +** their pre-transaction state by re-reading data from the database or +** WAL files. The WAL transaction is then closed. +*/ +int sqlite3PagerRollback(Pager *pPager){ + int rc = SQLITE_OK; /* Return code */ + PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager))); + + /* PagerRollback() is a no-op if called in READER or OPEN state. If + ** the pager is already in the ERROR state, the rollback is not + ** attempted here. Instead, the error code is returned to the caller. + */ + assert( assert_pager_state(pPager) ); + if( pPager->eState==PAGER_ERROR ) return pPager->errCode; + if( pPager->eState<=PAGER_READER ) return SQLITE_OK; + + if( pagerUseWal(pPager) ){ + int rc2; + rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1); + rc2 = pager_end_transaction(pPager, pPager->setMaster, 0); + if( rc==SQLITE_OK ) rc = rc2; + }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){ + int eState = pPager->eState; + rc = pager_end_transaction(pPager, 0, 0); + if( !MEMDB && eState>PAGER_WRITER_LOCKED ){ + /* This can happen using journal_mode=off. Move the pager to the error + ** state to indicate that the contents of the cache may not be trusted. + ** Any active readers will get SQLITE_ABORT. + */ + pPager->errCode = SQLITE_ABORT; + pPager->eState = PAGER_ERROR; + return rc; + } + }else{ + rc = pager_playback(pPager, 0); + } + + assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK ); + assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT + || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR ); + + /* If an error occurs during a ROLLBACK, we can no longer trust the pager + ** cache. So call pager_error() on the way out to make any error persistent. + */ + return pager_error(pPager, rc); +} + +/* +** Return TRUE if the database file is opened read-only. Return FALSE +** if the database is (in theory) writable. +*/ +u8 sqlite3PagerIsreadonly(Pager *pPager){ + return pPager->readOnly; +} + +/* +** Return the number of references to the pager. +*/ +int sqlite3PagerRefcount(Pager *pPager){ + return sqlite3PcacheRefCount(pPager->pPCache); +} + +/* +** Return the approximate number of bytes of memory currently +** used by the pager and its associated cache. +*/ +int sqlite3PagerMemUsed(Pager *pPager){ + int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr) + + 5*sizeof(void*); + return perPageSize*sqlite3PcachePagecount(pPager->pPCache) + + sqlite3MallocSize(pPager) + + pPager->pageSize; +} + +/* +** Return the number of references to the specified page. +*/ +int sqlite3PagerPageRefcount(DbPage *pPage){ + return sqlite3PcachePageRefcount(pPage); +} + +#ifdef SQLITE_TEST +/* +** This routine is used for testing and analysis only. +*/ +int *sqlite3PagerStats(Pager *pPager){ + static int a[11]; + a[0] = sqlite3PcacheRefCount(pPager->pPCache); + a[1] = sqlite3PcachePagecount(pPager->pPCache); + a[2] = sqlite3PcacheGetCachesize(pPager->pPCache); + a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize; + a[4] = pPager->eState; + a[5] = pPager->errCode; + a[6] = pPager->aStat[PAGER_STAT_HIT]; + a[7] = pPager->aStat[PAGER_STAT_MISS]; + a[8] = 0; /* Used to be pPager->nOvfl */ + a[9] = pPager->nRead; + a[10] = pPager->aStat[PAGER_STAT_WRITE]; + return a; +} +#endif + +/* +** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or +** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the +** current cache hit or miss count, according to the value of eStat. If the +** reset parameter is non-zero, the cache hit or miss count is zeroed before +** returning. +*/ +void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){ + + assert( eStat==SQLITE_DBSTATUS_CACHE_HIT + || eStat==SQLITE_DBSTATUS_CACHE_MISS + || eStat==SQLITE_DBSTATUS_CACHE_WRITE + ); + + assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS ); + assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE ); + assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 ); + + *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT]; + if( reset ){ + pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0; + } +} + +/* +** Return true if this is an in-memory pager. +*/ +int sqlite3PagerIsMemdb(Pager *pPager){ + return MEMDB; +} + +/* +** Check that there are at least nSavepoint savepoints open. If there are +** currently less than nSavepoints open, then open one or more savepoints +** to make up the difference. If the number of savepoints is already +** equal to nSavepoint, then this function is a no-op. +** +** If a memory allocation fails, SQLITE_NOMEM is returned. If an error +** occurs while opening the sub-journal file, then an IO error code is +** returned. Otherwise, SQLITE_OK. +*/ +int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ + int rc = SQLITE_OK; /* Return code */ + int nCurrent = pPager->nSavepoint; /* Current number of savepoints */ + + assert( pPager->eState>=PAGER_WRITER_LOCKED ); + assert( assert_pager_state(pPager) ); + + if( nSavepoint>nCurrent && pPager->useJournal ){ + int ii; /* Iterator variable */ + PagerSavepoint *aNew; /* New Pager.aSavepoint array */ + + /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM + ** if the allocation fails. Otherwise, zero the new portion in case a + ** malloc failure occurs while populating it in the for(...) loop below. + */ + aNew = (PagerSavepoint *)sqlite3Realloc( + pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint + ); + if( !aNew ){ + return SQLITE_NOMEM; + } + memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint)); + pPager->aSavepoint = aNew; + + /* Populate the PagerSavepoint structures just allocated. */ + for(ii=nCurrent; iidbSize; + if( isOpen(pPager->jfd) && pPager->journalOff>0 ){ + aNew[ii].iOffset = pPager->journalOff; + }else{ + aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager); + } + aNew[ii].iSubRec = pPager->nSubRec; + aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize); + if( !aNew[ii].pInSavepoint ){ + return SQLITE_NOMEM; + } + if( pagerUseWal(pPager) ){ + sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData); + } + pPager->nSavepoint = ii+1; + } + assert( pPager->nSavepoint==nSavepoint ); + assertTruncateConstraint(pPager); + } + + return rc; +} + +/* +** This function is called to rollback or release (commit) a savepoint. +** The savepoint to release or rollback need not be the most recently +** created savepoint. +** +** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE. +** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with +** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes +** that have occurred since the specified savepoint was created. +** +** The savepoint to rollback or release is identified by parameter +** iSavepoint. A value of 0 means to operate on the outermost savepoint +** (the first created). A value of (Pager.nSavepoint-1) means operate +** on the most recently created savepoint. If iSavepoint is greater than +** (Pager.nSavepoint-1), then this function is a no-op. +** +** If a negative value is passed to this function, then the current +** transaction is rolled back. This is different to calling +** sqlite3PagerRollback() because this function does not terminate +** the transaction or unlock the database, it just restores the +** contents of the database to its original state. +** +** In any case, all savepoints with an index greater than iSavepoint +** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE), +** then savepoint iSavepoint is also destroyed. +** +** This function may return SQLITE_NOMEM if a memory allocation fails, +** or an IO error code if an IO error occurs while rolling back a +** savepoint. If no errors occur, SQLITE_OK is returned. +*/ +int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ + int rc = pPager->errCode; /* Return code */ + + assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); + assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK ); + + if( rc==SQLITE_OK && iSavepointnSavepoint ){ + int ii; /* Iterator variable */ + int nNew; /* Number of remaining savepoints after this op. */ + + /* Figure out how many savepoints will still be active after this + ** operation. Store this value in nNew. Then free resources associated + ** with any savepoints that are destroyed by this operation. + */ + nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1); + for(ii=nNew; iinSavepoint; ii++){ + sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); + } + pPager->nSavepoint = nNew; + + /* If this is a release of the outermost savepoint, truncate + ** the sub-journal to zero bytes in size. */ + if( op==SAVEPOINT_RELEASE ){ + if( nNew==0 && isOpen(pPager->sjfd) ){ + /* Only truncate if it is an in-memory sub-journal. */ + if( sqlite3IsMemJournal(pPager->sjfd) ){ + rc = sqlite3OsTruncate(pPager->sjfd, 0); + assert( rc==SQLITE_OK ); + } + pPager->nSubRec = 0; + } + } + /* Else this is a rollback operation, playback the specified savepoint. + ** If this is a temp-file, it is possible that the journal file has + ** not yet been opened. In this case there have been no changes to + ** the database file, so the playback operation can be skipped. + */ + else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){ + PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1]; + rc = pagerPlaybackSavepoint(pPager, pSavepoint); + assert(rc!=SQLITE_DONE); + } + } + + return rc; +} + +/* +** Return the full pathname of the database file. +** +** Except, if the pager is in-memory only, then return an empty string if +** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when +** used to report the filename to the user, for compatibility with legacy +** behavior. But when the Btree needs to know the filename for matching to +** shared cache, it uses nullIfMemDb==0 so that in-memory databases can +** participate in shared-cache. +*/ +const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){ + return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename; +} + +/* +** Return the VFS structure for the pager. +*/ +const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){ + return pPager->pVfs; +} + +/* +** Return the file handle for the database file associated +** with the pager. This might return NULL if the file has +** not yet been opened. +*/ +sqlite3_file *sqlite3PagerFile(Pager *pPager){ + return pPager->fd; +} + +/* +** Return the full pathname of the journal file. +*/ +const char *sqlite3PagerJournalname(Pager *pPager){ + return pPager->zJournal; +} + +/* +** Return true if fsync() calls are disabled for this pager. Return FALSE +** if fsync()s are executed normally. +*/ +int sqlite3PagerNosync(Pager *pPager){ + return pPager->noSync; +} + +#ifdef SQLITE_HAS_CODEC +/* +** Set or retrieve the codec for this pager +*/ +void sqlite3PagerSetCodec( + Pager *pPager, + void *(*xCodec)(void*,void*,Pgno,int), + void (*xCodecSizeChng)(void*,int,int), + void (*xCodecFree)(void*), + void *pCodec +){ + if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); + pPager->xCodec = pPager->memDb ? 0 : xCodec; + pPager->xCodecSizeChng = xCodecSizeChng; + pPager->xCodecFree = xCodecFree; + pPager->pCodec = pCodec; + pagerReportSize(pPager); +} +void *sqlite3PagerGetCodec(Pager *pPager){ + return pPager->pCodec; +} + +/* +** This function is called by the wal module when writing page content +** into the log file. +** +** This function returns a pointer to a buffer containing the encrypted +** page content. If a malloc fails, this function may return NULL. +*/ +void *sqlite3PagerCodec(PgHdr *pPg){ + void *aData = 0; + CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData); + return aData; +} + +/* +** Return the current pager state +*/ +int sqlite3PagerState(Pager *pPager){ + return pPager->eState; +} +#endif /* SQLITE_HAS_CODEC */ + +#ifndef SQLITE_OMIT_AUTOVACUUM +/* +** Move the page pPg to location pgno in the file. +** +** There must be no references to the page previously located at +** pgno (which we call pPgOld) though that page is allowed to be +** in cache. If the page previously located at pgno is not already +** in the rollback journal, it is not put there by by this routine. +** +** References to the page pPg remain valid. Updating any +** meta-data associated with pPg (i.e. data stored in the nExtra bytes +** allocated along with the page) is the responsibility of the caller. +** +** A transaction must be active when this routine is called. It used to be +** required that a statement transaction was not active, but this restriction +** has been removed (CREATE INDEX needs to move a page when a statement +** transaction is active). +** +** If the fourth argument, isCommit, is non-zero, then this page is being +** moved as part of a database reorganization just before the transaction +** is being committed. In this case, it is guaranteed that the database page +** pPg refers to will not be written to again within this transaction. +** +** This function may return SQLITE_NOMEM or an IO error code if an error +** occurs. Otherwise, it returns SQLITE_OK. +*/ +int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){ + PgHdr *pPgOld; /* The page being overwritten. */ + Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */ + int rc; /* Return code */ + Pgno origPgno; /* The original page number */ + + assert( pPg->nRef>0 ); + assert( pPager->eState==PAGER_WRITER_CACHEMOD + || pPager->eState==PAGER_WRITER_DBMOD + ); + assert( assert_pager_state(pPager) ); + + /* In order to be able to rollback, an in-memory database must journal + ** the page we are moving from. + */ + if( MEMDB ){ + rc = sqlite3PagerWrite(pPg); + if( rc ) return rc; + } + + /* If the page being moved is dirty and has not been saved by the latest + ** savepoint, then save the current contents of the page into the + ** sub-journal now. This is required to handle the following scenario: + ** + ** BEGIN; + ** + ** SAVEPOINT one; + ** + ** ROLLBACK TO one; + ** + ** If page X were not written to the sub-journal here, it would not + ** be possible to restore its contents when the "ROLLBACK TO one" + ** statement were is processed. + ** + ** subjournalPage() may need to allocate space to store pPg->pgno into + ** one or more savepoint bitvecs. This is the reason this function + ** may return SQLITE_NOMEM. + */ + if( pPg->flags&PGHDR_DIRTY + && subjRequiresPage(pPg) + && SQLITE_OK!=(rc = subjournalPage(pPg)) + ){ + return rc; + } + + PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", + PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno)); + IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno)) + + /* If the journal needs to be sync()ed before page pPg->pgno can + ** be written to, store pPg->pgno in local variable needSyncPgno. + ** + ** If the isCommit flag is set, there is no need to remember that + ** the journal needs to be sync()ed before database page pPg->pgno + ** can be written to. The caller has already promised not to write to it. + */ + if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){ + needSyncPgno = pPg->pgno; + assert( pPager->journalMode==PAGER_JOURNALMODE_OFF || + pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize ); + assert( pPg->flags&PGHDR_DIRTY ); + } + + /* If the cache contains a page with page-number pgno, remove it + ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for + ** page pgno before the 'move' operation, it needs to be retained + ** for the page moved there. + */ + pPg->flags &= ~PGHDR_NEED_SYNC; + pPgOld = pager_lookup(pPager, pgno); + assert( !pPgOld || pPgOld->nRef==1 ); + if( pPgOld ){ + pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC); + if( MEMDB ){ + /* Do not discard pages from an in-memory database since we might + ** need to rollback later. Just move the page out of the way. */ + sqlite3PcacheMove(pPgOld, pPager->dbSize+1); + }else{ + sqlite3PcacheDrop(pPgOld); + } + } + + origPgno = pPg->pgno; + sqlite3PcacheMove(pPg, pgno); + sqlite3PcacheMakeDirty(pPg); + + /* For an in-memory database, make sure the original page continues + ** to exist, in case the transaction needs to roll back. Use pPgOld + ** as the original page since it has already been allocated. + */ + if( MEMDB ){ + assert( pPgOld ); + sqlite3PcacheMove(pPgOld, origPgno); + sqlite3PagerUnref(pPgOld); + } + + if( needSyncPgno ){ + /* If needSyncPgno is non-zero, then the journal file needs to be + ** sync()ed before any data is written to database file page needSyncPgno. + ** Currently, no such page exists in the page-cache and the + ** "is journaled" bitvec flag has been set. This needs to be remedied by + ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC + ** flag. + ** + ** If the attempt to load the page into the page-cache fails, (due + ** to a malloc() or IO failure), clear the bit in the pInJournal[] + ** array. Otherwise, if the page is loaded and written again in + ** this transaction, it may be written to the database file before + ** it is synced into the journal file. This way, it may end up in + ** the journal file twice, but that is not a problem. + */ + PgHdr *pPgHdr; + rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr); + if( rc!=SQLITE_OK ){ + if( needSyncPgno<=pPager->dbOrigSize ){ + assert( pPager->pTmpSpace!=0 ); + sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace); + } + return rc; + } + pPgHdr->flags |= PGHDR_NEED_SYNC; + sqlite3PcacheMakeDirty(pPgHdr); + sqlite3PagerUnref(pPgHdr); + } + + return SQLITE_OK; +} +#endif + +/* +** Return a pointer to the data for the specified page. +*/ +void *sqlite3PagerGetData(DbPage *pPg){ + assert( pPg->nRef>0 || pPg->pPager->memDb ); + return pPg->pData; +} + +/* +** Return a pointer to the Pager.nExtra bytes of "extra" space +** allocated along with the specified page. +*/ +void *sqlite3PagerGetExtra(DbPage *pPg){ + return pPg->pExtra; +} + +/* +** Get/set the locking-mode for this pager. Parameter eMode must be one +** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or +** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then +** the locking-mode is set to the value specified. +** +** The returned value is either PAGER_LOCKINGMODE_NORMAL or +** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated) +** locking-mode. +*/ +int sqlite3PagerLockingMode(Pager *pPager, int eMode){ + assert( eMode==PAGER_LOCKINGMODE_QUERY + || eMode==PAGER_LOCKINGMODE_NORMAL + || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); + assert( PAGER_LOCKINGMODE_QUERY<0 ); + assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 ); + assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) ); + if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){ + pPager->exclusiveMode = (u8)eMode; + } + return (int)pPager->exclusiveMode; +} + +/* +** Set the journal-mode for this pager. Parameter eMode must be one of: +** +** PAGER_JOURNALMODE_DELETE +** PAGER_JOURNALMODE_TRUNCATE +** PAGER_JOURNALMODE_PERSIST +** PAGER_JOURNALMODE_OFF +** PAGER_JOURNALMODE_MEMORY +** PAGER_JOURNALMODE_WAL +** +** The journalmode is set to the value specified if the change is allowed. +** The change may be disallowed for the following reasons: +** +** * An in-memory database can only have its journal_mode set to _OFF +** or _MEMORY. +** +** * Temporary databases cannot have _WAL journalmode. +** +** The returned indicate the current (possibly updated) journal-mode. +*/ +int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ + u8 eOld = pPager->journalMode; /* Prior journalmode */ + +#ifdef SQLITE_DEBUG + /* The print_pager_state() routine is intended to be used by the debugger + ** only. We invoke it once here to suppress a compiler warning. */ + print_pager_state(pPager); +#endif + + + /* The eMode parameter is always valid */ + assert( eMode==PAGER_JOURNALMODE_DELETE + || eMode==PAGER_JOURNALMODE_TRUNCATE + || eMode==PAGER_JOURNALMODE_PERSIST + || eMode==PAGER_JOURNALMODE_OFF + || eMode==PAGER_JOURNALMODE_WAL + || eMode==PAGER_JOURNALMODE_MEMORY ); + + /* This routine is only called from the OP_JournalMode opcode, and + ** the logic there will never allow a temporary file to be changed + ** to WAL mode. + */ + assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL ); + + /* Do allow the journalmode of an in-memory database to be set to + ** anything other than MEMORY or OFF + */ + if( MEMDB ){ + assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF ); + if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){ + eMode = eOld; + } + } + + if( eMode!=eOld ){ + + /* Change the journal mode. */ + assert( pPager->eState!=PAGER_ERROR ); + pPager->journalMode = (u8)eMode; + + /* When transistioning from TRUNCATE or PERSIST to any other journal + ** mode except WAL, unless the pager is in locking_mode=exclusive mode, + ** delete the journal file. + */ + assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); + assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); + assert( (PAGER_JOURNALMODE_DELETE & 5)==0 ); + assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 ); + assert( (PAGER_JOURNALMODE_OFF & 5)==0 ); + assert( (PAGER_JOURNALMODE_WAL & 5)==5 ); + + assert( isOpen(pPager->fd) || pPager->exclusiveMode ); + if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){ + + /* In this case we would like to delete the journal file. If it is + ** not possible, then that is not a problem. Deleting the journal file + ** here is an optimization only. + ** + ** Before deleting the journal file, obtain a RESERVED lock on the + ** database file. This ensures that the journal file is not deleted + ** while it is in use by some other client. + */ + sqlite3OsClose(pPager->jfd); + if( pPager->eLock>=RESERVED_LOCK ){ + sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); + }else{ + int rc = SQLITE_OK; + int state = pPager->eState; + assert( state==PAGER_OPEN || state==PAGER_READER ); + if( state==PAGER_OPEN ){ + rc = sqlite3PagerSharedLock(pPager); + } + if( pPager->eState==PAGER_READER ){ + assert( rc==SQLITE_OK ); + rc = pagerLockDb(pPager, RESERVED_LOCK); + } + if( rc==SQLITE_OK ){ + sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); + } + if( rc==SQLITE_OK && state==PAGER_READER ){ + pagerUnlockDb(pPager, SHARED_LOCK); + }else if( state==PAGER_OPEN ){ + pager_unlock(pPager); + } + assert( state==pPager->eState ); + } + } + } + + /* Return the new journal mode */ + return (int)pPager->journalMode; +} + +/* +** Return the current journal mode. +*/ +int sqlite3PagerGetJournalMode(Pager *pPager){ + return (int)pPager->journalMode; +} + +/* +** Return TRUE if the pager is in a state where it is OK to change the +** journalmode. Journalmode changes can only happen when the database +** is unmodified. +*/ +int sqlite3PagerOkToChangeJournalMode(Pager *pPager){ + assert( assert_pager_state(pPager) ); + if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0; + if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0; + return 1; +} + +/* +** Get/set the size-limit used for persistent journal files. +** +** Setting the size limit to -1 means no limit is enforced. +** An attempt to set a limit smaller than -1 is a no-op. +*/ +i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){ + if( iLimit>=-1 ){ + pPager->journalSizeLimit = iLimit; + sqlite3WalLimit(pPager->pWal, iLimit); + } + return pPager->journalSizeLimit; +} + +/* +** Return a pointer to the pPager->pBackup variable. The backup module +** in backup.c maintains the content of this variable. This module +** uses it opaquely as an argument to sqlite3BackupRestart() and +** sqlite3BackupUpdate() only. +*/ +sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){ + return &pPager->pBackup; +} + +#ifndef SQLITE_OMIT_VACUUM +/* +** Unless this is an in-memory or temporary database, clear the pager cache. +*/ +void sqlite3PagerClearCache(Pager *pPager){ + if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager); +} +#endif + +#ifndef SQLITE_OMIT_WAL +/* +** This function is called when the user invokes "PRAGMA wal_checkpoint", +** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint() +** or wal_blocking_checkpoint() API functions. +** +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +*/ +int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){ + int rc = SQLITE_OK; + if( pPager->pWal ){ + rc = sqlite3WalCheckpoint(pPager->pWal, eMode, + pPager->xBusyHandler, pPager->pBusyHandlerArg, + pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace, + pnLog, pnCkpt + ); + } + return rc; +} + +int sqlite3PagerWalCallback(Pager *pPager){ + return sqlite3WalCallback(pPager->pWal); +} + +/* +** Return true if the underlying VFS for the given pager supports the +** primitives necessary for write-ahead logging. +*/ +int sqlite3PagerWalSupported(Pager *pPager){ + const sqlite3_io_methods *pMethods = pPager->fd->pMethods; + return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap); +} + +/* +** Attempt to take an exclusive lock on the database file. If a PENDING lock +** is obtained instead, immediately release it. +*/ +static int pagerExclusiveLock(Pager *pPager){ + int rc; /* Return code */ + + assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); + rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); + if( rc!=SQLITE_OK ){ + /* If the attempt to grab the exclusive lock failed, release the + ** pending lock that may have been obtained instead. */ + pagerUnlockDb(pPager, SHARED_LOCK); + } + + return rc; +} + +/* +** Call sqlite3WalOpen() to open the WAL handle. If the pager is in +** exclusive-locking mode when this function is called, take an EXCLUSIVE +** lock on the database file and use heap-memory to store the wal-index +** in. Otherwise, use the normal shared-memory. +*/ +static int pagerOpenWal(Pager *pPager){ + int rc = SQLITE_OK; + + assert( pPager->pWal==0 && pPager->tempFile==0 ); + assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); + + /* If the pager is already in exclusive-mode, the WAL module will use + ** heap-memory for the wal-index instead of the VFS shared-memory + ** implementation. Take the exclusive lock now, before opening the WAL + ** file, to make sure this is safe. + */ + if( pPager->exclusiveMode ){ + rc = pagerExclusiveLock(pPager); + } + + /* Open the connection to the log file. If this operation fails, + ** (e.g. due to malloc() failure), return an error code. + */ + if( rc==SQLITE_OK ){ + rc = sqlite3WalOpen(pPager->pVfs, + pPager->fd, pPager->zWal, pPager->exclusiveMode, + pPager->journalSizeLimit, &pPager->pWal + ); + } + pagerFixMaplimit(pPager); + + return rc; +} + + +/* +** The caller must be holding a SHARED lock on the database file to call +** this function. +** +** If the pager passed as the first argument is open on a real database +** file (not a temp file or an in-memory database), and the WAL file +** is not already open, make an attempt to open it now. If successful, +** return SQLITE_OK. If an error occurs or the VFS used by the pager does +** not support the xShmXXX() methods, return an error code. *pbOpen is +** not modified in either case. +** +** If the pager is open on a temp-file (or in-memory database), or if +** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK +** without doing anything. +*/ +int sqlite3PagerOpenWal( + Pager *pPager, /* Pager object */ + int *pbOpen /* OUT: Set to true if call is a no-op */ +){ + int rc = SQLITE_OK; /* Return code */ + + assert( assert_pager_state(pPager) ); + assert( pPager->eState==PAGER_OPEN || pbOpen ); + assert( pPager->eState==PAGER_READER || !pbOpen ); + assert( pbOpen==0 || *pbOpen==0 ); + assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) ); + + if( !pPager->tempFile && !pPager->pWal ){ + if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN; + + /* Close any rollback journal previously open */ + sqlite3OsClose(pPager->jfd); + + rc = pagerOpenWal(pPager); + if( rc==SQLITE_OK ){ + pPager->journalMode = PAGER_JOURNALMODE_WAL; + pPager->eState = PAGER_OPEN; + } + }else{ + *pbOpen = 1; + } + + return rc; +} + +/* +** This function is called to close the connection to the log file prior +** to switching from WAL to rollback mode. +** +** Before closing the log file, this function attempts to take an +** EXCLUSIVE lock on the database file. If this cannot be obtained, an +** error (SQLITE_BUSY) is returned and the log connection is not closed. +** If successful, the EXCLUSIVE lock is not released before returning. +*/ +int sqlite3PagerCloseWal(Pager *pPager){ + int rc = SQLITE_OK; + + assert( pPager->journalMode==PAGER_JOURNALMODE_WAL ); + + /* If the log file is not already open, but does exist in the file-system, + ** it may need to be checkpointed before the connection can switch to + ** rollback mode. Open it now so this can happen. + */ + if( !pPager->pWal ){ + int logexists = 0; + rc = pagerLockDb(pPager, SHARED_LOCK); + if( rc==SQLITE_OK ){ + rc = sqlite3OsAccess( + pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists + ); + } + if( rc==SQLITE_OK && logexists ){ + rc = pagerOpenWal(pPager); + } + } + + /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on + ** the database file, the log and log-summary files will be deleted. + */ + if( rc==SQLITE_OK && pPager->pWal ){ + rc = pagerExclusiveLock(pPager); + if( rc==SQLITE_OK ){ + rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, + pPager->pageSize, (u8*)pPager->pTmpSpace); + pPager->pWal = 0; + pagerFixMaplimit(pPager); + } + } + return rc; +} + +#endif /* !SQLITE_OMIT_WAL */ + +#ifdef SQLITE_ENABLE_ZIPVFS +/* +** A read-lock must be held on the pager when this function is called. If +** the pager is in WAL mode and the WAL file currently contains one or more +** frames, return the size in bytes of the page images stored within the +** WAL frames. Otherwise, if this is not a WAL database or the WAL file +** is empty, return 0. +*/ +int sqlite3PagerWalFramesize(Pager *pPager){ + assert( pPager->eState==PAGER_READER ); + return sqlite3WalFramesize(pPager->pWal); +} +#endif + +#endif /* SQLITE_OMIT_DISKIO */ diff --git a/components/external/SQLite-3.8.1/src/pager.h b/components/external/SQLite-3.8.1/src/pager.h new file mode 100644 index 0000000000000000000000000000000000000000..7851d283454b412bf9f6822455849409eabbc627 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/pager.h @@ -0,0 +1,209 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. The page cache subsystem reads and writes a file a page +** at a time and provides a journal for rollback. +*/ + +#ifndef _PAGER_H_ +#define _PAGER_H_ + +/* +** Default maximum size for persistent journal files. A negative +** value means no limit. This value may be overridden using the +** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". +*/ +#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT + #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 +#endif + +/* +** The type used to represent a page number. The first page in a file +** is called page 1. 0 is used to represent "not a page". +*/ +typedef u32 Pgno; + +/* +** Each open file is managed by a separate instance of the "Pager" structure. +*/ +typedef struct Pager Pager; + +/* +** Handle type for pages. +*/ +typedef struct PgHdr DbPage; + +/* +** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is +** reserved for working around a windows/posix incompatibility). It is +** used in the journal to signify that the remainder of the journal file +** is devoted to storing a master journal name - there are no more pages to +** roll back. See comments for function writeMasterJournal() in pager.c +** for details. +*/ +#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) + +/* +** Allowed values for the flags parameter to sqlite3PagerOpen(). +** +** NOTE: These values must match the corresponding BTREE_ values in btree.h. +*/ +#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ +#define PAGER_MEMORY 0x0002 /* In-memory database */ + +/* +** Valid values for the second argument to sqlite3PagerLockingMode(). +*/ +#define PAGER_LOCKINGMODE_QUERY -1 +#define PAGER_LOCKINGMODE_NORMAL 0 +#define PAGER_LOCKINGMODE_EXCLUSIVE 1 + +/* +** Numeric constants that encode the journalmode. +*/ +#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ +#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ +#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ +#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ +#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ +#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ +#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ + +/* +** Flags that make up the mask passed to sqlite3PagerAcquire(). +*/ +#define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */ +#define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */ + +/* +** Flags for sqlite3PagerSetFlags() +*/ +#define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */ +#define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */ +#define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */ +#define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */ +#define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */ +#define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */ +#define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */ +#define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */ + +/* +** The remainder of this file contains the declarations of the functions +** that make up the Pager sub-system API. See source code comments for +** a detailed description of each routine. +*/ + +/* Open and close a Pager connection. */ +int sqlite3PagerOpen( + sqlite3_vfs*, + Pager **ppPager, + const char*, + int, + int, + int, + void(*)(DbPage*) +); +int sqlite3PagerClose(Pager *pPager); +int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); + +/* Functions used to configure a Pager object. */ +void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); +int sqlite3PagerSetPagesize(Pager*, u32*, int); +int sqlite3PagerMaxPageCount(Pager*, int); +void sqlite3PagerSetCachesize(Pager*, int); +void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64); +void sqlite3PagerShrink(Pager*); +void sqlite3PagerSetFlags(Pager*,unsigned); +int sqlite3PagerLockingMode(Pager *, int); +int sqlite3PagerSetJournalMode(Pager *, int); +int sqlite3PagerGetJournalMode(Pager*); +int sqlite3PagerOkToChangeJournalMode(Pager*); +i64 sqlite3PagerJournalSizeLimit(Pager *, i64); +sqlite3_backup **sqlite3PagerBackupPtr(Pager*); + +/* Functions used to obtain and release page references. */ +int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); +#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) +DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); +void sqlite3PagerRef(DbPage*); +void sqlite3PagerUnref(DbPage*); + +/* Operations on page references. */ +int sqlite3PagerWrite(DbPage*); +void sqlite3PagerDontWrite(DbPage*); +int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); +int sqlite3PagerPageRefcount(DbPage*); +void *sqlite3PagerGetData(DbPage *); +void *sqlite3PagerGetExtra(DbPage *); + +/* Functions used to manage pager transactions and savepoints. */ +void sqlite3PagerPagecount(Pager*, int*); +int sqlite3PagerBegin(Pager*, int exFlag, int); +int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); +int sqlite3PagerExclusiveLock(Pager*); +int sqlite3PagerSync(Pager *pPager); +int sqlite3PagerCommitPhaseTwo(Pager*); +int sqlite3PagerRollback(Pager*); +int sqlite3PagerOpenSavepoint(Pager *pPager, int n); +int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); +int sqlite3PagerSharedLock(Pager *pPager); + +#ifndef SQLITE_OMIT_WAL + int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*); + int sqlite3PagerWalSupported(Pager *pPager); + int sqlite3PagerWalCallback(Pager *pPager); + int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); + int sqlite3PagerCloseWal(Pager *pPager); +#endif + +#ifdef SQLITE_ENABLE_ZIPVFS + int sqlite3PagerWalFramesize(Pager *pPager); +#endif + +/* Functions used to query pager state and configuration. */ +u8 sqlite3PagerIsreadonly(Pager*); +int sqlite3PagerRefcount(Pager*); +int sqlite3PagerMemUsed(Pager*); +const char *sqlite3PagerFilename(Pager*, int); +const sqlite3_vfs *sqlite3PagerVfs(Pager*); +sqlite3_file *sqlite3PagerFile(Pager*); +const char *sqlite3PagerJournalname(Pager*); +int sqlite3PagerNosync(Pager*); +void *sqlite3PagerTempSpace(Pager*); +int sqlite3PagerIsMemdb(Pager*); +void sqlite3PagerCacheStat(Pager *, int, int, int *); +void sqlite3PagerClearCache(Pager *); +int sqlite3SectorSize(sqlite3_file *); + +/* Functions used to truncate the database file. */ +void sqlite3PagerTruncateImage(Pager*,Pgno); + +#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) +void *sqlite3PagerCodec(DbPage *); +#endif + +/* Functions to support testing and debugging. */ +#if !defined(NDEBUG) || defined(SQLITE_TEST) + Pgno sqlite3PagerPagenumber(DbPage*); + int sqlite3PagerIswriteable(DbPage*); +#endif +#ifdef SQLITE_TEST + int *sqlite3PagerStats(Pager*); + void sqlite3PagerRefdump(Pager*); + void disable_simulated_io_errors(void); + void enable_simulated_io_errors(void); +#else +# define disable_simulated_io_errors() +# define enable_simulated_io_errors() +#endif + +#endif /* _PAGER_H_ */ diff --git a/components/external/SQLite-3.8.1/src/parse.y b/components/external/SQLite-3.8.1/src/parse.y new file mode 100644 index 0000000000000000000000000000000000000000..1e8d7f751c783183a5fdcba99ff332b022567e13 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/parse.y @@ -0,0 +1,1403 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains SQLite's grammar for SQL. Process this file +** using the lemon parser generator to generate C code that runs +** the parser. Lemon will also generate a header file containing +** numeric codes for all of the tokens. +*/ + +// All token codes are small integers with #defines that begin with "TK_" +%token_prefix TK_ + +// The type of the data attached to each token is Token. This is also the +// default type for non-terminals. +// +%token_type {Token} +%default_type {Token} + +// The generated parser function takes a 4th argument as follows: +%extra_argument {Parse *pParse} + +// This code runs whenever there is a syntax error +// +%syntax_error { + UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ + assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */ + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); +} +%stack_overflow { + UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */ + sqlite3ErrorMsg(pParse, "parser stack overflow"); +} + +// The name of the generated procedure that implements the parser +// is as follows: +%name sqlite3Parser + +// The following text is included near the beginning of the C source +// code file that implements the parser. +// +%include { +#include "sqliteInt.h" + +/* +** Disable all error recovery processing in the parser push-down +** automaton. +*/ +#define YYNOERRORRECOVERY 1 + +/* +** Make yytestcase() the same as testcase() +*/ +#define yytestcase(X) testcase(X) + +/* +** An instance of this structure holds information about the +** LIMIT clause of a SELECT statement. +*/ +struct LimitVal { + Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */ + Expr *pOffset; /* The OFFSET expression. NULL if there is none */ +}; + +/* +** An instance of this structure is used to store the LIKE, +** GLOB, NOT LIKE, and NOT GLOB operators. +*/ +struct LikeOp { + Token eOperator; /* "like" or "glob" or "regexp" */ + int bNot; /* True if the NOT keyword is present */ +}; + +/* +** An instance of the following structure describes the event of a +** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT, +** TK_DELETE, or TK_INSTEAD. If the event is of the form +** +** UPDATE ON (a,b,c) +** +** Then the "b" IdList records the list "a,b,c". +*/ +struct TrigEvent { int a; IdList * b; }; + +/* +** An instance of this structure holds the ATTACH key and the key type. +*/ +struct AttachKey { int type; Token key; }; + +/* +** One or more VALUES claues +*/ +struct ValueList { + ExprList *pList; + Select *pSelect; +}; + +} // end %include + +// Input is a single SQL command +input ::= cmdlist. +cmdlist ::= cmdlist ecmd. +cmdlist ::= ecmd. +ecmd ::= SEMI. +ecmd ::= explain cmdx SEMI. +explain ::= . { sqlite3BeginParse(pParse, 0); } +%ifndef SQLITE_OMIT_EXPLAIN +explain ::= EXPLAIN. { sqlite3BeginParse(pParse, 1); } +explain ::= EXPLAIN QUERY PLAN. { sqlite3BeginParse(pParse, 2); } +%endif SQLITE_OMIT_EXPLAIN +cmdx ::= cmd. { sqlite3FinishCoding(pParse); } + +///////////////////// Begin and end transactions. //////////////////////////// +// + +cmd ::= BEGIN transtype(Y) trans_opt. {sqlite3BeginTransaction(pParse, Y);} +trans_opt ::= . +trans_opt ::= TRANSACTION. +trans_opt ::= TRANSACTION nm. +%type transtype {int} +transtype(A) ::= . {A = TK_DEFERRED;} +transtype(A) ::= DEFERRED(X). {A = @X;} +transtype(A) ::= IMMEDIATE(X). {A = @X;} +transtype(A) ::= EXCLUSIVE(X). {A = @X;} +cmd ::= COMMIT trans_opt. {sqlite3CommitTransaction(pParse);} +cmd ::= END trans_opt. {sqlite3CommitTransaction(pParse);} +cmd ::= ROLLBACK trans_opt. {sqlite3RollbackTransaction(pParse);} + +savepoint_opt ::= SAVEPOINT. +savepoint_opt ::= . +cmd ::= SAVEPOINT nm(X). { + sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &X); +} +cmd ::= RELEASE savepoint_opt nm(X). { + sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &X); +} +cmd ::= ROLLBACK trans_opt TO savepoint_opt nm(X). { + sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &X); +} + +///////////////////// The CREATE TABLE statement //////////////////////////// +// +cmd ::= create_table create_table_args. +create_table ::= createkw temp(T) TABLE ifnotexists(E) nm(Y) dbnm(Z). { + sqlite3StartTable(pParse,&Y,&Z,T,0,0,E); +} +createkw(A) ::= CREATE(X). { + pParse->db->lookaside.bEnabled = 0; + A = X; +} +%type ifnotexists {int} +ifnotexists(A) ::= . {A = 0;} +ifnotexists(A) ::= IF NOT EXISTS. {A = 1;} +%type temp {int} +%ifndef SQLITE_OMIT_TEMPDB +temp(A) ::= TEMP. {A = 1;} +%endif SQLITE_OMIT_TEMPDB +temp(A) ::= . {A = 0;} +create_table_args ::= LP columnlist conslist_opt(X) RP(Y). { + sqlite3EndTable(pParse,&X,&Y,0); +} +create_table_args ::= AS select(S). { + sqlite3EndTable(pParse,0,0,S); + sqlite3SelectDelete(pParse->db, S); +} +columnlist ::= columnlist COMMA column. +columnlist ::= column. + +// A "column" is a complete description of a single column in a +// CREATE TABLE statement. This includes the column name, its +// datatype, and other keywords such as PRIMARY KEY, UNIQUE, REFERENCES, +// NOT NULL and so forth. +// +column(A) ::= columnid(X) type carglist. { + A.z = X.z; + A.n = (int)(pParse->sLastToken.z-X.z) + pParse->sLastToken.n; +} +columnid(A) ::= nm(X). { + sqlite3AddColumn(pParse,&X); + A = X; + pParse->constraintName.n = 0; +} + + +// An IDENTIFIER can be a generic identifier, or one of several +// keywords. Any non-standard keyword can also be an identifier. +// +%type id {Token} +id(A) ::= ID(X). {A = X;} +id(A) ::= INDEXED(X). {A = X;} + +// The following directive causes tokens ABORT, AFTER, ASC, etc. to +// fallback to ID if they will not parse as their original value. +// This obviates the need for the "id" nonterminal. +// +%fallback ID + ABORT ACTION AFTER ANALYZE ASC ATTACH BEFORE BEGIN BY CASCADE CAST COLUMNKW + CONFLICT DATABASE DEFERRED DESC DETACH EACH END EXCLUSIVE EXPLAIN FAIL FOR + IGNORE IMMEDIATE INITIALLY INSTEAD LIKE_KW MATCH NO PLAN + QUERY KEY OF OFFSET PRAGMA RAISE RELEASE REPLACE RESTRICT ROW ROLLBACK + SAVEPOINT TEMP TRIGGER VACUUM VIEW VIRTUAL +%ifdef SQLITE_OMIT_COMPOUND_SELECT + EXCEPT INTERSECT UNION +%endif SQLITE_OMIT_COMPOUND_SELECT + REINDEX RENAME CTIME_KW IF + . +%wildcard ANY. + +// Define operator precedence early so that this is the first occurrence +// of the operator tokens in the grammer. Keeping the operators together +// causes them to be assigned integer values that are close together, +// which keeps parser tables smaller. +// +// The token values assigned to these symbols is determined by the order +// in which lemon first sees them. It must be the case that ISNULL/NOTNULL, +// NE/EQ, GT/LE, and GE/LT are separated by only a single value. See +// the sqlite3ExprIfFalse() routine for additional information on this +// constraint. +// +%left OR. +%left AND. +%right NOT. +%left IS MATCH LIKE_KW BETWEEN IN ISNULL NOTNULL NE EQ. +%left GT LE LT GE. +%right ESCAPE. +%left BITAND BITOR LSHIFT RSHIFT. +%left PLUS MINUS. +%left STAR SLASH REM. +%left CONCAT. +%left COLLATE. +%right BITNOT. + +// And "ids" is an identifer-or-string. +// +%type ids {Token} +ids(A) ::= ID|STRING(X). {A = X;} + +// The name of a column or table can be any of the following: +// +%type nm {Token} +nm(A) ::= id(X). {A = X;} +nm(A) ::= STRING(X). {A = X;} +nm(A) ::= JOIN_KW(X). {A = X;} + +// A typetoken is really one or more tokens that form a type name such +// as can be found after the column name in a CREATE TABLE statement. +// Multiple tokens are concatenated to form the value of the typetoken. +// +%type typetoken {Token} +type ::= . +type ::= typetoken(X). {sqlite3AddColumnType(pParse,&X);} +typetoken(A) ::= typename(X). {A = X;} +typetoken(A) ::= typename(X) LP signed RP(Y). { + A.z = X.z; + A.n = (int)(&Y.z[Y.n] - X.z); +} +typetoken(A) ::= typename(X) LP signed COMMA signed RP(Y). { + A.z = X.z; + A.n = (int)(&Y.z[Y.n] - X.z); +} +%type typename {Token} +typename(A) ::= ids(X). {A = X;} +typename(A) ::= typename(X) ids(Y). {A.z=X.z; A.n=Y.n+(int)(Y.z-X.z);} +signed ::= plus_num. +signed ::= minus_num. + +// "carglist" is a list of additional constraints that come after the +// column name and column type in a CREATE TABLE statement. +// +carglist ::= carglist ccons. +carglist ::= . +ccons ::= CONSTRAINT nm(X). {pParse->constraintName = X;} +ccons ::= DEFAULT term(X). {sqlite3AddDefaultValue(pParse,&X);} +ccons ::= DEFAULT LP expr(X) RP. {sqlite3AddDefaultValue(pParse,&X);} +ccons ::= DEFAULT PLUS term(X). {sqlite3AddDefaultValue(pParse,&X);} +ccons ::= DEFAULT MINUS(A) term(X). { + ExprSpan v; + v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, X.pExpr, 0, 0); + v.zStart = A.z; + v.zEnd = X.zEnd; + sqlite3AddDefaultValue(pParse,&v); +} +ccons ::= DEFAULT id(X). { + ExprSpan v; + spanExpr(&v, pParse, TK_STRING, &X); + sqlite3AddDefaultValue(pParse,&v); +} + +// In addition to the type name, we also care about the primary key and +// UNIQUE constraints. +// +ccons ::= NULL onconf. +ccons ::= NOT NULL onconf(R). {sqlite3AddNotNull(pParse, R);} +ccons ::= PRIMARY KEY sortorder(Z) onconf(R) autoinc(I). + {sqlite3AddPrimaryKey(pParse,0,R,I,Z);} +ccons ::= UNIQUE onconf(R). {sqlite3CreateIndex(pParse,0,0,0,0,R,0,0,0,0);} +ccons ::= CHECK LP expr(X) RP. {sqlite3AddCheckConstraint(pParse,X.pExpr);} +ccons ::= REFERENCES nm(T) idxlist_opt(TA) refargs(R). + {sqlite3CreateForeignKey(pParse,0,&T,TA,R);} +ccons ::= defer_subclause(D). {sqlite3DeferForeignKey(pParse,D);} +ccons ::= COLLATE ids(C). {sqlite3AddCollateType(pParse, &C);} + +// The optional AUTOINCREMENT keyword +%type autoinc {int} +autoinc(X) ::= . {X = 0;} +autoinc(X) ::= AUTOINCR. {X = 1;} + +// The next group of rules parses the arguments to a REFERENCES clause +// that determine if the referential integrity checking is deferred or +// or immediate and which determine what action to take if a ref-integ +// check fails. +// +%type refargs {int} +refargs(A) ::= . { A = OE_None*0x0101; /* EV: R-19803-45884 */} +refargs(A) ::= refargs(X) refarg(Y). { A = (X & ~Y.mask) | Y.value; } +%type refarg {struct {int value; int mask;}} +refarg(A) ::= MATCH nm. { A.value = 0; A.mask = 0x000000; } +refarg(A) ::= ON INSERT refact. { A.value = 0; A.mask = 0x000000; } +refarg(A) ::= ON DELETE refact(X). { A.value = X; A.mask = 0x0000ff; } +refarg(A) ::= ON UPDATE refact(X). { A.value = X<<8; A.mask = 0x00ff00; } +%type refact {int} +refact(A) ::= SET NULL. { A = OE_SetNull; /* EV: R-33326-45252 */} +refact(A) ::= SET DEFAULT. { A = OE_SetDflt; /* EV: R-33326-45252 */} +refact(A) ::= CASCADE. { A = OE_Cascade; /* EV: R-33326-45252 */} +refact(A) ::= RESTRICT. { A = OE_Restrict; /* EV: R-33326-45252 */} +refact(A) ::= NO ACTION. { A = OE_None; /* EV: R-33326-45252 */} +%type defer_subclause {int} +defer_subclause(A) ::= NOT DEFERRABLE init_deferred_pred_opt. {A = 0;} +defer_subclause(A) ::= DEFERRABLE init_deferred_pred_opt(X). {A = X;} +%type init_deferred_pred_opt {int} +init_deferred_pred_opt(A) ::= . {A = 0;} +init_deferred_pred_opt(A) ::= INITIALLY DEFERRED. {A = 1;} +init_deferred_pred_opt(A) ::= INITIALLY IMMEDIATE. {A = 0;} + +conslist_opt(A) ::= . {A.n = 0; A.z = 0;} +conslist_opt(A) ::= COMMA(X) conslist. {A = X;} +conslist ::= conslist tconscomma tcons. +conslist ::= tcons. +tconscomma ::= COMMA. {pParse->constraintName.n = 0;} +tconscomma ::= . +tcons ::= CONSTRAINT nm(X). {pParse->constraintName = X;} +tcons ::= PRIMARY KEY LP idxlist(X) autoinc(I) RP onconf(R). + {sqlite3AddPrimaryKey(pParse,X,R,I,0);} +tcons ::= UNIQUE LP idxlist(X) RP onconf(R). + {sqlite3CreateIndex(pParse,0,0,0,X,R,0,0,0,0);} +tcons ::= CHECK LP expr(E) RP onconf. + {sqlite3AddCheckConstraint(pParse,E.pExpr);} +tcons ::= FOREIGN KEY LP idxlist(FA) RP + REFERENCES nm(T) idxlist_opt(TA) refargs(R) defer_subclause_opt(D). { + sqlite3CreateForeignKey(pParse, FA, &T, TA, R); + sqlite3DeferForeignKey(pParse, D); +} +%type defer_subclause_opt {int} +defer_subclause_opt(A) ::= . {A = 0;} +defer_subclause_opt(A) ::= defer_subclause(X). {A = X;} + +// The following is a non-standard extension that allows us to declare the +// default behavior when there is a constraint conflict. +// +%type onconf {int} +%type orconf {u8} +%type resolvetype {int} +onconf(A) ::= . {A = OE_Default;} +onconf(A) ::= ON CONFLICT resolvetype(X). {A = X;} +orconf(A) ::= . {A = OE_Default;} +orconf(A) ::= OR resolvetype(X). {A = (u8)X;} +resolvetype(A) ::= raisetype(X). {A = X;} +resolvetype(A) ::= IGNORE. {A = OE_Ignore;} +resolvetype(A) ::= REPLACE. {A = OE_Replace;} + +////////////////////////// The DROP TABLE ///////////////////////////////////// +// +cmd ::= DROP TABLE ifexists(E) fullname(X). { + sqlite3DropTable(pParse, X, 0, E); +} +%type ifexists {int} +ifexists(A) ::= IF EXISTS. {A = 1;} +ifexists(A) ::= . {A = 0;} + +///////////////////// The CREATE VIEW statement ///////////////////////////// +// +%ifndef SQLITE_OMIT_VIEW +cmd ::= createkw(X) temp(T) VIEW ifnotexists(E) nm(Y) dbnm(Z) AS select(S). { + sqlite3CreateView(pParse, &X, &Y, &Z, S, T, E); +} +cmd ::= DROP VIEW ifexists(E) fullname(X). { + sqlite3DropTable(pParse, X, 1, E); +} +%endif SQLITE_OMIT_VIEW + +//////////////////////// The SELECT statement ///////////////////////////////// +// +cmd ::= select(X). { + SelectDest dest = {SRT_Output, 0, 0, 0, 0}; + sqlite3Select(pParse, X, &dest); + sqlite3ExplainBegin(pParse->pVdbe); + sqlite3ExplainSelect(pParse->pVdbe, X); + sqlite3ExplainFinish(pParse->pVdbe); + sqlite3SelectDelete(pParse->db, X); +} + +%type select {Select*} +%destructor select {sqlite3SelectDelete(pParse->db, $$);} +%type oneselect {Select*} +%destructor oneselect {sqlite3SelectDelete(pParse->db, $$);} + +select(A) ::= oneselect(X). {A = X;} +%ifndef SQLITE_OMIT_COMPOUND_SELECT +select(A) ::= select(X) multiselect_op(Y) oneselect(Z). { + if( Z ){ + Z->op = (u8)Y; + Z->pPrior = X; + if( Y!=TK_ALL ) pParse->hasCompound = 1; + }else{ + sqlite3SelectDelete(pParse->db, X); + } + A = Z; +} +%type multiselect_op {int} +multiselect_op(A) ::= UNION(OP). {A = @OP;} +multiselect_op(A) ::= UNION ALL. {A = TK_ALL;} +multiselect_op(A) ::= EXCEPT|INTERSECT(OP). {A = @OP;} +%endif SQLITE_OMIT_COMPOUND_SELECT +oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y) + groupby_opt(P) having_opt(Q) orderby_opt(Z) limit_opt(L). { + A = sqlite3SelectNew(pParse,W,X,Y,P,Q,Z,D,L.pLimit,L.pOffset); +} + +// The "distinct" nonterminal is true (1) if the DISTINCT keyword is +// present and false (0) if it is not. +// +%type distinct {u16} +distinct(A) ::= DISTINCT. {A = SF_Distinct;} +distinct(A) ::= ALL. {A = 0;} +distinct(A) ::= . {A = 0;} + +// selcollist is a list of expressions that are to become the return +// values of the SELECT statement. The "*" in statements like +// "SELECT * FROM ..." is encoded as a special expression with an +// opcode of TK_ALL. +// +%type selcollist {ExprList*} +%destructor selcollist {sqlite3ExprListDelete(pParse->db, $$);} +%type sclp {ExprList*} +%destructor sclp {sqlite3ExprListDelete(pParse->db, $$);} +sclp(A) ::= selcollist(X) COMMA. {A = X;} +sclp(A) ::= . {A = 0;} +selcollist(A) ::= sclp(P) expr(X) as(Y). { + A = sqlite3ExprListAppend(pParse, P, X.pExpr); + if( Y.n>0 ) sqlite3ExprListSetName(pParse, A, &Y, 1); + sqlite3ExprListSetSpan(pParse,A,&X); +} +selcollist(A) ::= sclp(P) STAR. { + Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0); + A = sqlite3ExprListAppend(pParse, P, p); +} +selcollist(A) ::= sclp(P) nm(X) DOT STAR(Y). { + Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &Y); + Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &X); + Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); + A = sqlite3ExprListAppend(pParse,P, pDot); +} + +// An option "AS " phrase that can follow one of the expressions that +// define the result set, or one of the tables in the FROM clause. +// +%type as {Token} +as(X) ::= AS nm(Y). {X = Y;} +as(X) ::= ids(Y). {X = Y;} +as(X) ::= . {X.n = 0;} + + +%type seltablist {SrcList*} +%destructor seltablist {sqlite3SrcListDelete(pParse->db, $$);} +%type stl_prefix {SrcList*} +%destructor stl_prefix {sqlite3SrcListDelete(pParse->db, $$);} +%type from {SrcList*} +%destructor from {sqlite3SrcListDelete(pParse->db, $$);} + +// A complete FROM clause. +// +from(A) ::= . {A = sqlite3DbMallocZero(pParse->db, sizeof(*A));} +from(A) ::= FROM seltablist(X). { + A = X; + sqlite3SrcListShiftJoinType(A); +} + +// "seltablist" is a "Select Table List" - the content of the FROM clause +// in a SELECT statement. "stl_prefix" is a prefix of this list. +// +stl_prefix(A) ::= seltablist(X) joinop(Y). { + A = X; + if( ALWAYS(A && A->nSrc>0) ) A->a[A->nSrc-1].jointype = (u8)Y; +} +stl_prefix(A) ::= . {A = 0;} +seltablist(A) ::= stl_prefix(X) nm(Y) dbnm(D) as(Z) indexed_opt(I) + on_opt(N) using_opt(U). { + A = sqlite3SrcListAppendFromTerm(pParse,X,&Y,&D,&Z,0,N,U); + sqlite3SrcListIndexedBy(pParse, A, &I); +} +%ifndef SQLITE_OMIT_SUBQUERY + seltablist(A) ::= stl_prefix(X) LP select(S) RP + as(Z) on_opt(N) using_opt(U). { + A = sqlite3SrcListAppendFromTerm(pParse,X,0,0,&Z,S,N,U); + } + seltablist(A) ::= stl_prefix(X) LP seltablist(F) RP + as(Z) on_opt(N) using_opt(U). { + if( X==0 && Z.n==0 && N==0 && U==0 ){ + A = F; + }else if( F->nSrc==1 ){ + A = sqlite3SrcListAppendFromTerm(pParse,X,0,0,&Z,0,N,U); + if( A ){ + struct SrcList_item *pNew = &A->a[A->nSrc-1]; + struct SrcList_item *pOld = F->a; + pNew->zName = pOld->zName; + pNew->zDatabase = pOld->zDatabase; + pNew->pSelect = pOld->pSelect; + pOld->zName = pOld->zDatabase = 0; + pOld->pSelect = 0; + } + sqlite3SrcListDelete(pParse->db, F); + }else{ + Select *pSubquery; + sqlite3SrcListShiftJoinType(F); + pSubquery = sqlite3SelectNew(pParse,0,F,0,0,0,0,SF_NestedFrom,0,0); + A = sqlite3SrcListAppendFromTerm(pParse,X,0,0,&Z,pSubquery,N,U); + } + } +%endif SQLITE_OMIT_SUBQUERY + +%type dbnm {Token} +dbnm(A) ::= . {A.z=0; A.n=0;} +dbnm(A) ::= DOT nm(X). {A = X;} + +%type fullname {SrcList*} +%destructor fullname {sqlite3SrcListDelete(pParse->db, $$);} +fullname(A) ::= nm(X) dbnm(Y). {A = sqlite3SrcListAppend(pParse->db,0,&X,&Y);} + +%type joinop {int} +%type joinop2 {int} +joinop(X) ::= COMMA|JOIN. { X = JT_INNER; } +joinop(X) ::= JOIN_KW(A) JOIN. { X = sqlite3JoinType(pParse,&A,0,0); } +joinop(X) ::= JOIN_KW(A) nm(B) JOIN. { X = sqlite3JoinType(pParse,&A,&B,0); } +joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN. + { X = sqlite3JoinType(pParse,&A,&B,&C); } + +%type on_opt {Expr*} +%destructor on_opt {sqlite3ExprDelete(pParse->db, $$);} +on_opt(N) ::= ON expr(E). {N = E.pExpr;} +on_opt(N) ::= . {N = 0;} + +// Note that this block abuses the Token type just a little. If there is +// no "INDEXED BY" clause, the returned token is empty (z==0 && n==0). If +// there is an INDEXED BY clause, then the token is populated as per normal, +// with z pointing to the token data and n containing the number of bytes +// in the token. +// +// If there is a "NOT INDEXED" clause, then (z==0 && n==1), which is +// normally illegal. The sqlite3SrcListIndexedBy() function +// recognizes and interprets this as a special case. +// +%type indexed_opt {Token} +indexed_opt(A) ::= . {A.z=0; A.n=0;} +indexed_opt(A) ::= INDEXED BY nm(X). {A = X;} +indexed_opt(A) ::= NOT INDEXED. {A.z=0; A.n=1;} + +%type using_opt {IdList*} +%destructor using_opt {sqlite3IdListDelete(pParse->db, $$);} +using_opt(U) ::= USING LP inscollist(L) RP. {U = L;} +using_opt(U) ::= . {U = 0;} + + +%type orderby_opt {ExprList*} +%destructor orderby_opt {sqlite3ExprListDelete(pParse->db, $$);} +%type sortlist {ExprList*} +%destructor sortlist {sqlite3ExprListDelete(pParse->db, $$);} + +orderby_opt(A) ::= . {A = 0;} +orderby_opt(A) ::= ORDER BY sortlist(X). {A = X;} +sortlist(A) ::= sortlist(X) COMMA expr(Y) sortorder(Z). { + A = sqlite3ExprListAppend(pParse,X,Y.pExpr); + if( A ) A->a[A->nExpr-1].sortOrder = (u8)Z; +} +sortlist(A) ::= expr(Y) sortorder(Z). { + A = sqlite3ExprListAppend(pParse,0,Y.pExpr); + if( A && ALWAYS(A->a) ) A->a[0].sortOrder = (u8)Z; +} + +%type sortorder {int} + +sortorder(A) ::= ASC. {A = SQLITE_SO_ASC;} +sortorder(A) ::= DESC. {A = SQLITE_SO_DESC;} +sortorder(A) ::= . {A = SQLITE_SO_ASC;} + +%type groupby_opt {ExprList*} +%destructor groupby_opt {sqlite3ExprListDelete(pParse->db, $$);} +groupby_opt(A) ::= . {A = 0;} +groupby_opt(A) ::= GROUP BY nexprlist(X). {A = X;} + +%type having_opt {Expr*} +%destructor having_opt {sqlite3ExprDelete(pParse->db, $$);} +having_opt(A) ::= . {A = 0;} +having_opt(A) ::= HAVING expr(X). {A = X.pExpr;} + +%type limit_opt {struct LimitVal} + +// The destructor for limit_opt will never fire in the current grammar. +// The limit_opt non-terminal only occurs at the end of a single production +// rule for SELECT statements. As soon as the rule that create the +// limit_opt non-terminal reduces, the SELECT statement rule will also +// reduce. So there is never a limit_opt non-terminal on the stack +// except as a transient. So there is never anything to destroy. +// +//%destructor limit_opt { +// sqlite3ExprDelete(pParse->db, $$.pLimit); +// sqlite3ExprDelete(pParse->db, $$.pOffset); +//} +limit_opt(A) ::= . {A.pLimit = 0; A.pOffset = 0;} +limit_opt(A) ::= LIMIT expr(X). {A.pLimit = X.pExpr; A.pOffset = 0;} +limit_opt(A) ::= LIMIT expr(X) OFFSET expr(Y). + {A.pLimit = X.pExpr; A.pOffset = Y.pExpr;} +limit_opt(A) ::= LIMIT expr(X) COMMA expr(Y). + {A.pOffset = X.pExpr; A.pLimit = Y.pExpr;} + +/////////////////////////// The DELETE statement ///////////////////////////// +// +%ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT +cmd ::= DELETE FROM fullname(X) indexed_opt(I) where_opt(W) + orderby_opt(O) limit_opt(L). { + sqlite3SrcListIndexedBy(pParse, X, &I); + W = sqlite3LimitWhere(pParse, X, W, O, L.pLimit, L.pOffset, "DELETE"); + sqlite3DeleteFrom(pParse,X,W); +} +%endif +%ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT +cmd ::= DELETE FROM fullname(X) indexed_opt(I) where_opt(W). { + sqlite3SrcListIndexedBy(pParse, X, &I); + sqlite3DeleteFrom(pParse,X,W); +} +%endif + +%type where_opt {Expr*} +%destructor where_opt {sqlite3ExprDelete(pParse->db, $$);} + +where_opt(A) ::= . {A = 0;} +where_opt(A) ::= WHERE expr(X). {A = X.pExpr;} + +////////////////////////// The UPDATE command //////////////////////////////// +// +%ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT +cmd ::= UPDATE orconf(R) fullname(X) indexed_opt(I) SET setlist(Y) where_opt(W) + orderby_opt(O) limit_opt(L). { + sqlite3SrcListIndexedBy(pParse, X, &I); + sqlite3ExprListCheckLength(pParse,Y,"set list"); + W = sqlite3LimitWhere(pParse, X, W, O, L.pLimit, L.pOffset, "UPDATE"); + sqlite3Update(pParse,X,Y,W,R); +} +%endif +%ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT +cmd ::= UPDATE orconf(R) fullname(X) indexed_opt(I) SET setlist(Y) + where_opt(W). { + sqlite3SrcListIndexedBy(pParse, X, &I); + sqlite3ExprListCheckLength(pParse,Y,"set list"); + sqlite3Update(pParse,X,Y,W,R); +} +%endif + +%type setlist {ExprList*} +%destructor setlist {sqlite3ExprListDelete(pParse->db, $$);} + +setlist(A) ::= setlist(Z) COMMA nm(X) EQ expr(Y). { + A = sqlite3ExprListAppend(pParse, Z, Y.pExpr); + sqlite3ExprListSetName(pParse, A, &X, 1); +} +setlist(A) ::= nm(X) EQ expr(Y). { + A = sqlite3ExprListAppend(pParse, 0, Y.pExpr); + sqlite3ExprListSetName(pParse, A, &X, 1); +} + +////////////////////////// The INSERT command ///////////////////////////////// +// +cmd ::= insert_cmd(R) INTO fullname(X) inscollist_opt(F) valuelist(Y). + {sqlite3Insert(pParse, X, Y.pList, Y.pSelect, F, R);} +cmd ::= insert_cmd(R) INTO fullname(X) inscollist_opt(F) select(S). + {sqlite3Insert(pParse, X, 0, S, F, R);} +cmd ::= insert_cmd(R) INTO fullname(X) inscollist_opt(F) DEFAULT VALUES. + {sqlite3Insert(pParse, X, 0, 0, F, R);} + +%type insert_cmd {u8} +insert_cmd(A) ::= INSERT orconf(R). {A = R;} +insert_cmd(A) ::= REPLACE. {A = OE_Replace;} + +// A ValueList is either a single VALUES clause or a comma-separated list +// of VALUES clauses. If it is a single VALUES clause then the +// ValueList.pList field points to the expression list of that clause. +// If it is a list of VALUES clauses, then those clauses are transformed +// into a set of SELECT statements without FROM clauses and connected by +// UNION ALL and the ValueList.pSelect points to the right-most SELECT in +// that compound. +%type valuelist {struct ValueList} +%destructor valuelist { + sqlite3ExprListDelete(pParse->db, $$.pList); + sqlite3SelectDelete(pParse->db, $$.pSelect); +} +valuelist(A) ::= VALUES LP nexprlist(X) RP. { + A.pList = X; + A.pSelect = 0; +} + +// Since a list of VALUEs is inplemented as a compound SELECT, we have +// to disable the value list option if compound SELECTs are disabled. +%ifndef SQLITE_OMIT_COMPOUND_SELECT +valuelist(A) ::= valuelist(X) COMMA LP exprlist(Y) RP. { + Select *pRight = sqlite3SelectNew(pParse, Y, 0, 0, 0, 0, 0, 0, 0, 0); + if( X.pList ){ + X.pSelect = sqlite3SelectNew(pParse, X.pList, 0, 0, 0, 0, 0, 0, 0, 0); + X.pList = 0; + } + A.pList = 0; + if( X.pSelect==0 || pRight==0 ){ + sqlite3SelectDelete(pParse->db, pRight); + sqlite3SelectDelete(pParse->db, X.pSelect); + A.pSelect = 0; + }else{ + pRight->op = TK_ALL; + pRight->pPrior = X.pSelect; + pRight->selFlags |= SF_Values; + pRight->pPrior->selFlags |= SF_Values; + A.pSelect = pRight; + } +} +%endif SQLITE_OMIT_COMPOUND_SELECT + +%type inscollist_opt {IdList*} +%destructor inscollist_opt {sqlite3IdListDelete(pParse->db, $$);} +%type inscollist {IdList*} +%destructor inscollist {sqlite3IdListDelete(pParse->db, $$);} + +inscollist_opt(A) ::= . {A = 0;} +inscollist_opt(A) ::= LP inscollist(X) RP. {A = X;} +inscollist(A) ::= inscollist(X) COMMA nm(Y). + {A = sqlite3IdListAppend(pParse->db,X,&Y);} +inscollist(A) ::= nm(Y). + {A = sqlite3IdListAppend(pParse->db,0,&Y);} + +/////////////////////////// Expression Processing ///////////////////////////// +// + +%type expr {ExprSpan} +%destructor expr {sqlite3ExprDelete(pParse->db, $$.pExpr);} +%type term {ExprSpan} +%destructor term {sqlite3ExprDelete(pParse->db, $$.pExpr);} + +%include { + /* This is a utility routine used to set the ExprSpan.zStart and + ** ExprSpan.zEnd values of pOut so that the span covers the complete + ** range of text beginning with pStart and going to the end of pEnd. + */ + static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){ + pOut->zStart = pStart->z; + pOut->zEnd = &pEnd->z[pEnd->n]; + } + + /* Construct a new Expr object from a single identifier. Use the + ** new Expr to populate pOut. Set the span of pOut to be the identifier + ** that created the expression. + */ + static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){ + pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue); + pOut->zStart = pValue->z; + pOut->zEnd = &pValue->z[pValue->n]; + } +} + +expr(A) ::= term(X). {A = X;} +expr(A) ::= LP(B) expr(X) RP(E). {A.pExpr = X.pExpr; spanSet(&A,&B,&E);} +term(A) ::= NULL(X). {spanExpr(&A, pParse, @X, &X);} +expr(A) ::= id(X). {spanExpr(&A, pParse, TK_ID, &X);} +expr(A) ::= JOIN_KW(X). {spanExpr(&A, pParse, TK_ID, &X);} +expr(A) ::= nm(X) DOT nm(Y). { + Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &X); + Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &Y); + A.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0); + spanSet(&A,&X,&Y); +} +expr(A) ::= nm(X) DOT nm(Y) DOT nm(Z). { + Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &X); + Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &Y); + Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &Z); + Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0); + A.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0); + spanSet(&A,&X,&Z); +} +term(A) ::= INTEGER|FLOAT|BLOB(X). {spanExpr(&A, pParse, @X, &X);} +term(A) ::= STRING(X). {spanExpr(&A, pParse, @X, &X);} +expr(A) ::= REGISTER(X). { + /* When doing a nested parse, one can include terms in an expression + ** that look like this: #1 #2 ... These terms refer to registers + ** in the virtual machine. #N is the N-th register. */ + if( pParse->nested==0 ){ + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &X); + A.pExpr = 0; + }else{ + A.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &X); + if( A.pExpr ) sqlite3GetInt32(&X.z[1], &A.pExpr->iTable); + } + spanSet(&A, &X, &X); +} +expr(A) ::= VARIABLE(X). { + spanExpr(&A, pParse, TK_VARIABLE, &X); + sqlite3ExprAssignVarNumber(pParse, A.pExpr); + spanSet(&A, &X, &X); +} +expr(A) ::= expr(E) COLLATE ids(C). { + A.pExpr = sqlite3ExprAddCollateToken(pParse, E.pExpr, &C); + A.zStart = E.zStart; + A.zEnd = &C.z[C.n]; +} +%ifndef SQLITE_OMIT_CAST +expr(A) ::= CAST(X) LP expr(E) AS typetoken(T) RP(Y). { + A.pExpr = sqlite3PExpr(pParse, TK_CAST, E.pExpr, 0, &T); + spanSet(&A,&X,&Y); +} +%endif SQLITE_OMIT_CAST +expr(A) ::= ID(X) LP distinct(D) exprlist(Y) RP(E). { + if( Y && Y->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ + sqlite3ErrorMsg(pParse, "too many arguments on function %T", &X); + } + A.pExpr = sqlite3ExprFunction(pParse, Y, &X); + spanSet(&A,&X,&E); + if( D && A.pExpr ){ + A.pExpr->flags |= EP_Distinct; + } +} +expr(A) ::= ID(X) LP STAR RP(E). { + A.pExpr = sqlite3ExprFunction(pParse, 0, &X); + spanSet(&A,&X,&E); +} +term(A) ::= CTIME_KW(OP). { + /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are + ** treated as functions that return constants */ + A.pExpr = sqlite3ExprFunction(pParse, 0,&OP); + if( A.pExpr ){ + A.pExpr->op = TK_CONST_FUNC; + } + spanSet(&A, &OP, &OP); +} + +%include { + /* This routine constructs a binary expression node out of two ExprSpan + ** objects and uses the result to populate a new ExprSpan object. + */ + static void spanBinaryExpr( + ExprSpan *pOut, /* Write the result here */ + Parse *pParse, /* The parsing context. Errors accumulate here */ + int op, /* The binary operation */ + ExprSpan *pLeft, /* The left operand */ + ExprSpan *pRight /* The right operand */ + ){ + pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0); + pOut->zStart = pLeft->zStart; + pOut->zEnd = pRight->zEnd; + } +} + +expr(A) ::= expr(X) AND(OP) expr(Y). {spanBinaryExpr(&A,pParse,@OP,&X,&Y);} +expr(A) ::= expr(X) OR(OP) expr(Y). {spanBinaryExpr(&A,pParse,@OP,&X,&Y);} +expr(A) ::= expr(X) LT|GT|GE|LE(OP) expr(Y). + {spanBinaryExpr(&A,pParse,@OP,&X,&Y);} +expr(A) ::= expr(X) EQ|NE(OP) expr(Y). {spanBinaryExpr(&A,pParse,@OP,&X,&Y);} +expr(A) ::= expr(X) BITAND|BITOR|LSHIFT|RSHIFT(OP) expr(Y). + {spanBinaryExpr(&A,pParse,@OP,&X,&Y);} +expr(A) ::= expr(X) PLUS|MINUS(OP) expr(Y). + {spanBinaryExpr(&A,pParse,@OP,&X,&Y);} +expr(A) ::= expr(X) STAR|SLASH|REM(OP) expr(Y). + {spanBinaryExpr(&A,pParse,@OP,&X,&Y);} +expr(A) ::= expr(X) CONCAT(OP) expr(Y). {spanBinaryExpr(&A,pParse,@OP,&X,&Y);} +%type likeop {struct LikeOp} +likeop(A) ::= LIKE_KW(X). {A.eOperator = X; A.bNot = 0;} +likeop(A) ::= NOT LIKE_KW(X). {A.eOperator = X; A.bNot = 1;} +likeop(A) ::= MATCH(X). {A.eOperator = X; A.bNot = 0;} +likeop(A) ::= NOT MATCH(X). {A.eOperator = X; A.bNot = 1;} +expr(A) ::= expr(X) likeop(OP) expr(Y). [LIKE_KW] { + ExprList *pList; + pList = sqlite3ExprListAppend(pParse,0, Y.pExpr); + pList = sqlite3ExprListAppend(pParse,pList, X.pExpr); + A.pExpr = sqlite3ExprFunction(pParse, pList, &OP.eOperator); + if( OP.bNot ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0); + A.zStart = X.zStart; + A.zEnd = Y.zEnd; + if( A.pExpr ) A.pExpr->flags |= EP_InfixFunc; +} +expr(A) ::= expr(X) likeop(OP) expr(Y) ESCAPE expr(E). [LIKE_KW] { + ExprList *pList; + pList = sqlite3ExprListAppend(pParse,0, Y.pExpr); + pList = sqlite3ExprListAppend(pParse,pList, X.pExpr); + pList = sqlite3ExprListAppend(pParse,pList, E.pExpr); + A.pExpr = sqlite3ExprFunction(pParse, pList, &OP.eOperator); + if( OP.bNot ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0); + A.zStart = X.zStart; + A.zEnd = E.zEnd; + if( A.pExpr ) A.pExpr->flags |= EP_InfixFunc; +} + +%include { + /* Construct an expression node for a unary postfix operator + */ + static void spanUnaryPostfix( + ExprSpan *pOut, /* Write the new expression node here */ + Parse *pParse, /* Parsing context to record errors */ + int op, /* The operator */ + ExprSpan *pOperand, /* The operand */ + Token *pPostOp /* The operand token for setting the span */ + ){ + pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0); + pOut->zStart = pOperand->zStart; + pOut->zEnd = &pPostOp->z[pPostOp->n]; + } +} + +expr(A) ::= expr(X) ISNULL|NOTNULL(E). {spanUnaryPostfix(&A,pParse,@E,&X,&E);} +expr(A) ::= expr(X) NOT NULL(E). {spanUnaryPostfix(&A,pParse,TK_NOTNULL,&X,&E);} + +%include { + /* A routine to convert a binary TK_IS or TK_ISNOT expression into a + ** unary TK_ISNULL or TK_NOTNULL expression. */ + static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){ + sqlite3 *db = pParse->db; + if( db->mallocFailed==0 && pY->op==TK_NULL ){ + pA->op = (u8)op; + sqlite3ExprDelete(db, pA->pRight); + pA->pRight = 0; + } + } +} + +// expr1 IS expr2 +// expr1 IS NOT expr2 +// +// If expr2 is NULL then code as TK_ISNULL or TK_NOTNULL. If expr2 +// is any other expression, code as TK_IS or TK_ISNOT. +// +expr(A) ::= expr(X) IS expr(Y). { + spanBinaryExpr(&A,pParse,TK_IS,&X,&Y); + binaryToUnaryIfNull(pParse, Y.pExpr, A.pExpr, TK_ISNULL); +} +expr(A) ::= expr(X) IS NOT expr(Y). { + spanBinaryExpr(&A,pParse,TK_ISNOT,&X,&Y); + binaryToUnaryIfNull(pParse, Y.pExpr, A.pExpr, TK_NOTNULL); +} + +%include { + /* Construct an expression node for a unary prefix operator + */ + static void spanUnaryPrefix( + ExprSpan *pOut, /* Write the new expression node here */ + Parse *pParse, /* Parsing context to record errors */ + int op, /* The operator */ + ExprSpan *pOperand, /* The operand */ + Token *pPreOp /* The operand token for setting the span */ + ){ + pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0); + pOut->zStart = pPreOp->z; + pOut->zEnd = pOperand->zEnd; + } +} + + + +expr(A) ::= NOT(B) expr(X). {spanUnaryPrefix(&A,pParse,@B,&X,&B);} +expr(A) ::= BITNOT(B) expr(X). {spanUnaryPrefix(&A,pParse,@B,&X,&B);} +expr(A) ::= MINUS(B) expr(X). [BITNOT] + {spanUnaryPrefix(&A,pParse,TK_UMINUS,&X,&B);} +expr(A) ::= PLUS(B) expr(X). [BITNOT] + {spanUnaryPrefix(&A,pParse,TK_UPLUS,&X,&B);} + +%type between_op {int} +between_op(A) ::= BETWEEN. {A = 0;} +between_op(A) ::= NOT BETWEEN. {A = 1;} +expr(A) ::= expr(W) between_op(N) expr(X) AND expr(Y). [BETWEEN] { + ExprList *pList = sqlite3ExprListAppend(pParse,0, X.pExpr); + pList = sqlite3ExprListAppend(pParse,pList, Y.pExpr); + A.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, W.pExpr, 0, 0); + if( A.pExpr ){ + A.pExpr->x.pList = pList; + }else{ + sqlite3ExprListDelete(pParse->db, pList); + } + if( N ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0); + A.zStart = W.zStart; + A.zEnd = Y.zEnd; +} +%ifndef SQLITE_OMIT_SUBQUERY + %type in_op {int} + in_op(A) ::= IN. {A = 0;} + in_op(A) ::= NOT IN. {A = 1;} + expr(A) ::= expr(X) in_op(N) LP exprlist(Y) RP(E). [IN] { + if( Y==0 ){ + /* Expressions of the form + ** + ** expr1 IN () + ** expr1 NOT IN () + ** + ** simplify to constants 0 (false) and 1 (true), respectively, + ** regardless of the value of expr1. + */ + A.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[N]); + sqlite3ExprDelete(pParse->db, X.pExpr); + }else{ + A.pExpr = sqlite3PExpr(pParse, TK_IN, X.pExpr, 0, 0); + if( A.pExpr ){ + A.pExpr->x.pList = Y; + sqlite3ExprSetHeight(pParse, A.pExpr); + }else{ + sqlite3ExprListDelete(pParse->db, Y); + } + if( N ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0); + } + A.zStart = X.zStart; + A.zEnd = &E.z[E.n]; + } + expr(A) ::= LP(B) select(X) RP(E). { + A.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0); + if( A.pExpr ){ + A.pExpr->x.pSelect = X; + ExprSetProperty(A.pExpr, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, A.pExpr); + }else{ + sqlite3SelectDelete(pParse->db, X); + } + A.zStart = B.z; + A.zEnd = &E.z[E.n]; + } + expr(A) ::= expr(X) in_op(N) LP select(Y) RP(E). [IN] { + A.pExpr = sqlite3PExpr(pParse, TK_IN, X.pExpr, 0, 0); + if( A.pExpr ){ + A.pExpr->x.pSelect = Y; + ExprSetProperty(A.pExpr, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, A.pExpr); + }else{ + sqlite3SelectDelete(pParse->db, Y); + } + if( N ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0); + A.zStart = X.zStart; + A.zEnd = &E.z[E.n]; + } + expr(A) ::= expr(X) in_op(N) nm(Y) dbnm(Z). [IN] { + SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&Y,&Z); + A.pExpr = sqlite3PExpr(pParse, TK_IN, X.pExpr, 0, 0); + if( A.pExpr ){ + A.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0); + ExprSetProperty(A.pExpr, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, A.pExpr); + }else{ + sqlite3SrcListDelete(pParse->db, pSrc); + } + if( N ) A.pExpr = sqlite3PExpr(pParse, TK_NOT, A.pExpr, 0, 0); + A.zStart = X.zStart; + A.zEnd = Z.z ? &Z.z[Z.n] : &Y.z[Y.n]; + } + expr(A) ::= EXISTS(B) LP select(Y) RP(E). { + Expr *p = A.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0); + if( p ){ + p->x.pSelect = Y; + ExprSetProperty(p, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, p); + }else{ + sqlite3SelectDelete(pParse->db, Y); + } + A.zStart = B.z; + A.zEnd = &E.z[E.n]; + } +%endif SQLITE_OMIT_SUBQUERY + +/* CASE expressions */ +expr(A) ::= CASE(C) case_operand(X) case_exprlist(Y) case_else(Z) END(E). { + A.pExpr = sqlite3PExpr(pParse, TK_CASE, X, 0, 0); + if( A.pExpr ){ + A.pExpr->x.pList = Z ? sqlite3ExprListAppend(pParse,Y,Z) : Y; + sqlite3ExprSetHeight(pParse, A.pExpr); + }else{ + sqlite3ExprListDelete(pParse->db, Y); + sqlite3ExprDelete(pParse->db, Z); + } + A.zStart = C.z; + A.zEnd = &E.z[E.n]; +} +%type case_exprlist {ExprList*} +%destructor case_exprlist {sqlite3ExprListDelete(pParse->db, $$);} +case_exprlist(A) ::= case_exprlist(X) WHEN expr(Y) THEN expr(Z). { + A = sqlite3ExprListAppend(pParse,X, Y.pExpr); + A = sqlite3ExprListAppend(pParse,A, Z.pExpr); +} +case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). { + A = sqlite3ExprListAppend(pParse,0, Y.pExpr); + A = sqlite3ExprListAppend(pParse,A, Z.pExpr); +} +%type case_else {Expr*} +%destructor case_else {sqlite3ExprDelete(pParse->db, $$);} +case_else(A) ::= ELSE expr(X). {A = X.pExpr;} +case_else(A) ::= . {A = 0;} +%type case_operand {Expr*} +%destructor case_operand {sqlite3ExprDelete(pParse->db, $$);} +case_operand(A) ::= expr(X). {A = X.pExpr;} +case_operand(A) ::= . {A = 0;} + +%type exprlist {ExprList*} +%destructor exprlist {sqlite3ExprListDelete(pParse->db, $$);} +%type nexprlist {ExprList*} +%destructor nexprlist {sqlite3ExprListDelete(pParse->db, $$);} + +exprlist(A) ::= nexprlist(X). {A = X;} +exprlist(A) ::= . {A = 0;} +nexprlist(A) ::= nexprlist(X) COMMA expr(Y). + {A = sqlite3ExprListAppend(pParse,X,Y.pExpr);} +nexprlist(A) ::= expr(Y). + {A = sqlite3ExprListAppend(pParse,0,Y.pExpr);} + + +///////////////////////////// The CREATE INDEX command /////////////////////// +// +cmd ::= createkw(S) uniqueflag(U) INDEX ifnotexists(NE) nm(X) dbnm(D) + ON nm(Y) LP idxlist(Z) RP where_opt(W). { + sqlite3CreateIndex(pParse, &X, &D, + sqlite3SrcListAppend(pParse->db,0,&Y,0), Z, U, + &S, W, SQLITE_SO_ASC, NE); +} + +%type uniqueflag {int} +uniqueflag(A) ::= UNIQUE. {A = OE_Abort;} +uniqueflag(A) ::= . {A = OE_None;} + +%type idxlist {ExprList*} +%destructor idxlist {sqlite3ExprListDelete(pParse->db, $$);} +%type idxlist_opt {ExprList*} +%destructor idxlist_opt {sqlite3ExprListDelete(pParse->db, $$);} + +idxlist_opt(A) ::= . {A = 0;} +idxlist_opt(A) ::= LP idxlist(X) RP. {A = X;} +idxlist(A) ::= idxlist(X) COMMA nm(Y) collate(C) sortorder(Z). { + Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &C); + A = sqlite3ExprListAppend(pParse,X, p); + sqlite3ExprListSetName(pParse,A,&Y,1); + sqlite3ExprListCheckLength(pParse, A, "index"); + if( A ) A->a[A->nExpr-1].sortOrder = (u8)Z; +} +idxlist(A) ::= nm(Y) collate(C) sortorder(Z). { + Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &C); + A = sqlite3ExprListAppend(pParse,0, p); + sqlite3ExprListSetName(pParse, A, &Y, 1); + sqlite3ExprListCheckLength(pParse, A, "index"); + if( A ) A->a[A->nExpr-1].sortOrder = (u8)Z; +} + +%type collate {Token} +collate(C) ::= . {C.z = 0; C.n = 0;} +collate(C) ::= COLLATE ids(X). {C = X;} + + +///////////////////////////// The DROP INDEX command ///////////////////////// +// +cmd ::= DROP INDEX ifexists(E) fullname(X). {sqlite3DropIndex(pParse, X, E);} + +///////////////////////////// The VACUUM command ///////////////////////////// +// +%ifndef SQLITE_OMIT_VACUUM +%ifndef SQLITE_OMIT_ATTACH +cmd ::= VACUUM. {sqlite3Vacuum(pParse);} +cmd ::= VACUUM nm. {sqlite3Vacuum(pParse);} +%endif SQLITE_OMIT_ATTACH +%endif SQLITE_OMIT_VACUUM + +///////////////////////////// The PRAGMA command ///////////////////////////// +// +%ifndef SQLITE_OMIT_PRAGMA +cmd ::= PRAGMA nm(X) dbnm(Z). {sqlite3Pragma(pParse,&X,&Z,0,0);} +cmd ::= PRAGMA nm(X) dbnm(Z) EQ nmnum(Y). {sqlite3Pragma(pParse,&X,&Z,&Y,0);} +cmd ::= PRAGMA nm(X) dbnm(Z) LP nmnum(Y) RP. {sqlite3Pragma(pParse,&X,&Z,&Y,0);} +cmd ::= PRAGMA nm(X) dbnm(Z) EQ minus_num(Y). + {sqlite3Pragma(pParse,&X,&Z,&Y,1);} +cmd ::= PRAGMA nm(X) dbnm(Z) LP minus_num(Y) RP. + {sqlite3Pragma(pParse,&X,&Z,&Y,1);} + +nmnum(A) ::= plus_num(X). {A = X;} +nmnum(A) ::= nm(X). {A = X;} +nmnum(A) ::= ON(X). {A = X;} +nmnum(A) ::= DELETE(X). {A = X;} +nmnum(A) ::= DEFAULT(X). {A = X;} +%endif SQLITE_OMIT_PRAGMA +plus_num(A) ::= PLUS number(X). {A = X;} +plus_num(A) ::= number(X). {A = X;} +minus_num(A) ::= MINUS number(X). {A = X;} +number(A) ::= INTEGER|FLOAT(X). {A = X;} + +//////////////////////////// The CREATE TRIGGER command ///////////////////// + +%ifndef SQLITE_OMIT_TRIGGER + +cmd ::= createkw trigger_decl(A) BEGIN trigger_cmd_list(S) END(Z). { + Token all; + all.z = A.z; + all.n = (int)(Z.z - A.z) + Z.n; + sqlite3FinishTrigger(pParse, S, &all); +} + +trigger_decl(A) ::= temp(T) TRIGGER ifnotexists(NOERR) nm(B) dbnm(Z) + trigger_time(C) trigger_event(D) + ON fullname(E) foreach_clause when_clause(G). { + sqlite3BeginTrigger(pParse, &B, &Z, C, D.a, D.b, E, G, T, NOERR); + A = (Z.n==0?B:Z); +} + +%type trigger_time {int} +trigger_time(A) ::= BEFORE. { A = TK_BEFORE; } +trigger_time(A) ::= AFTER. { A = TK_AFTER; } +trigger_time(A) ::= INSTEAD OF. { A = TK_INSTEAD;} +trigger_time(A) ::= . { A = TK_BEFORE; } + +%type trigger_event {struct TrigEvent} +%destructor trigger_event {sqlite3IdListDelete(pParse->db, $$.b);} +trigger_event(A) ::= DELETE|INSERT(OP). {A.a = @OP; A.b = 0;} +trigger_event(A) ::= UPDATE(OP). {A.a = @OP; A.b = 0;} +trigger_event(A) ::= UPDATE OF inscollist(X). {A.a = TK_UPDATE; A.b = X;} + +foreach_clause ::= . +foreach_clause ::= FOR EACH ROW. + +%type when_clause {Expr*} +%destructor when_clause {sqlite3ExprDelete(pParse->db, $$);} +when_clause(A) ::= . { A = 0; } +when_clause(A) ::= WHEN expr(X). { A = X.pExpr; } + +%type trigger_cmd_list {TriggerStep*} +%destructor trigger_cmd_list {sqlite3DeleteTriggerStep(pParse->db, $$);} +trigger_cmd_list(A) ::= trigger_cmd_list(Y) trigger_cmd(X) SEMI. { + assert( Y!=0 ); + Y->pLast->pNext = X; + Y->pLast = X; + A = Y; +} +trigger_cmd_list(A) ::= trigger_cmd(X) SEMI. { + assert( X!=0 ); + X->pLast = X; + A = X; +} + +// Disallow qualified table names on INSERT, UPDATE, and DELETE statements +// within a trigger. The table to INSERT, UPDATE, or DELETE is always in +// the same database as the table that the trigger fires on. +// +%type trnm {Token} +trnm(A) ::= nm(X). {A = X;} +trnm(A) ::= nm DOT nm(X). { + A = X; + sqlite3ErrorMsg(pParse, + "qualified table names are not allowed on INSERT, UPDATE, and DELETE " + "statements within triggers"); +} + +// Disallow the INDEX BY and NOT INDEXED clauses on UPDATE and DELETE +// statements within triggers. We make a specific error message for this +// since it is an exception to the default grammar rules. +// +tridxby ::= . +tridxby ::= INDEXED BY nm. { + sqlite3ErrorMsg(pParse, + "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " + "within triggers"); +} +tridxby ::= NOT INDEXED. { + sqlite3ErrorMsg(pParse, + "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " + "within triggers"); +} + + + +%type trigger_cmd {TriggerStep*} +%destructor trigger_cmd {sqlite3DeleteTriggerStep(pParse->db, $$);} +// UPDATE +trigger_cmd(A) ::= + UPDATE orconf(R) trnm(X) tridxby SET setlist(Y) where_opt(Z). + { A = sqlite3TriggerUpdateStep(pParse->db, &X, Y, Z, R); } + +// INSERT +trigger_cmd(A) ::= + insert_cmd(R) INTO trnm(X) inscollist_opt(F) valuelist(Y). + {A = sqlite3TriggerInsertStep(pParse->db, &X, F, Y.pList, Y.pSelect, R);} + +trigger_cmd(A) ::= insert_cmd(R) INTO trnm(X) inscollist_opt(F) select(S). + {A = sqlite3TriggerInsertStep(pParse->db, &X, F, 0, S, R);} + +// DELETE +trigger_cmd(A) ::= DELETE FROM trnm(X) tridxby where_opt(Y). + {A = sqlite3TriggerDeleteStep(pParse->db, &X, Y);} + +// SELECT +trigger_cmd(A) ::= select(X). {A = sqlite3TriggerSelectStep(pParse->db, X); } + +// The special RAISE expression that may occur in trigger programs +expr(A) ::= RAISE(X) LP IGNORE RP(Y). { + A.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); + if( A.pExpr ){ + A.pExpr->affinity = OE_Ignore; + } + A.zStart = X.z; + A.zEnd = &Y.z[Y.n]; +} +expr(A) ::= RAISE(X) LP raisetype(T) COMMA nm(Z) RP(Y). { + A.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &Z); + if( A.pExpr ) { + A.pExpr->affinity = (char)T; + } + A.zStart = X.z; + A.zEnd = &Y.z[Y.n]; +} +%endif !SQLITE_OMIT_TRIGGER + +%type raisetype {int} +raisetype(A) ::= ROLLBACK. {A = OE_Rollback;} +raisetype(A) ::= ABORT. {A = OE_Abort;} +raisetype(A) ::= FAIL. {A = OE_Fail;} + + +//////////////////////// DROP TRIGGER statement ////////////////////////////// +%ifndef SQLITE_OMIT_TRIGGER +cmd ::= DROP TRIGGER ifexists(NOERR) fullname(X). { + sqlite3DropTrigger(pParse,X,NOERR); +} +%endif !SQLITE_OMIT_TRIGGER + +//////////////////////// ATTACH DATABASE file AS name ///////////////////////// +%ifndef SQLITE_OMIT_ATTACH +cmd ::= ATTACH database_kw_opt expr(F) AS expr(D) key_opt(K). { + sqlite3Attach(pParse, F.pExpr, D.pExpr, K); +} +cmd ::= DETACH database_kw_opt expr(D). { + sqlite3Detach(pParse, D.pExpr); +} + +%type key_opt {Expr*} +%destructor key_opt {sqlite3ExprDelete(pParse->db, $$);} +key_opt(A) ::= . { A = 0; } +key_opt(A) ::= KEY expr(X). { A = X.pExpr; } + +database_kw_opt ::= DATABASE. +database_kw_opt ::= . +%endif SQLITE_OMIT_ATTACH + +////////////////////////// REINDEX collation ////////////////////////////////// +%ifndef SQLITE_OMIT_REINDEX +cmd ::= REINDEX. {sqlite3Reindex(pParse, 0, 0);} +cmd ::= REINDEX nm(X) dbnm(Y). {sqlite3Reindex(pParse, &X, &Y);} +%endif SQLITE_OMIT_REINDEX + +/////////////////////////////////// ANALYZE /////////////////////////////////// +%ifndef SQLITE_OMIT_ANALYZE +cmd ::= ANALYZE. {sqlite3Analyze(pParse, 0, 0);} +cmd ::= ANALYZE nm(X) dbnm(Y). {sqlite3Analyze(pParse, &X, &Y);} +%endif + +//////////////////////// ALTER TABLE table ... //////////////////////////////// +%ifndef SQLITE_OMIT_ALTERTABLE +cmd ::= ALTER TABLE fullname(X) RENAME TO nm(Z). { + sqlite3AlterRenameTable(pParse,X,&Z); +} +cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column(Y). { + sqlite3AlterFinishAddColumn(pParse, &Y); +} +add_column_fullname ::= fullname(X). { + pParse->db->lookaside.bEnabled = 0; + sqlite3AlterBeginAddColumn(pParse, X); +} +kwcolumn_opt ::= . +kwcolumn_opt ::= COLUMNKW. +%endif SQLITE_OMIT_ALTERTABLE + +//////////////////////// CREATE VIRTUAL TABLE ... ///////////////////////////// +%ifndef SQLITE_OMIT_VIRTUALTABLE +cmd ::= create_vtab. {sqlite3VtabFinishParse(pParse,0);} +cmd ::= create_vtab LP vtabarglist RP(X). {sqlite3VtabFinishParse(pParse,&X);} +create_vtab ::= createkw VIRTUAL TABLE ifnotexists(E) + nm(X) dbnm(Y) USING nm(Z). { + sqlite3VtabBeginParse(pParse, &X, &Y, &Z, E); +} +vtabarglist ::= vtabarg. +vtabarglist ::= vtabarglist COMMA vtabarg. +vtabarg ::= . {sqlite3VtabArgInit(pParse);} +vtabarg ::= vtabarg vtabargtoken. +vtabargtoken ::= ANY(X). {sqlite3VtabArgExtend(pParse,&X);} +vtabargtoken ::= lp anylist RP(X). {sqlite3VtabArgExtend(pParse,&X);} +lp ::= LP(X). {sqlite3VtabArgExtend(pParse,&X);} +anylist ::= . +anylist ::= anylist LP anylist RP. +anylist ::= anylist ANY. +%endif SQLITE_OMIT_VIRTUALTABLE diff --git a/components/external/SQLite-3.8.1/src/pcache.c b/components/external/SQLite-3.8.1/src/pcache.c new file mode 100644 index 0000000000000000000000000000000000000000..482a188bee1991bc8adac96a193a53e5462a8c10 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/pcache.c @@ -0,0 +1,619 @@ +/* +** 2008 August 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements that page cache. +*/ +#include "sqliteInt.h" + +/* +** A complete page cache is an instance of this structure. +*/ +struct PCache { + PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */ + PgHdr *pSynced; /* Last synced page in dirty page list */ + int nRef; /* Number of referenced pages */ + int szCache; /* Configured cache size */ + int szPage; /* Size of every page in this cache */ + int szExtra; /* Size of extra space for each page */ + int bPurgeable; /* True if pages are on backing store */ + int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */ + void *pStress; /* Argument to xStress */ + sqlite3_pcache *pCache; /* Pluggable cache module */ + PgHdr *pPage1; /* Reference to page 1 */ +}; + +/* +** Some of the assert() macros in this code are too expensive to run +** even during normal debugging. Use them only rarely on long-running +** tests. Enable the expensive asserts using the +** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option. +*/ +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT +# define expensive_assert(X) assert(X) +#else +# define expensive_assert(X) +#endif + +/********************************** Linked List Management ********************/ + +#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT) +/* +** Check that the pCache->pSynced variable is set correctly. If it +** is not, either fail an assert or return zero. Otherwise, return +** non-zero. This is only used in debugging builds, as follows: +** +** expensive_assert( pcacheCheckSynced(pCache) ); +*/ +static int pcacheCheckSynced(PCache *pCache){ + PgHdr *p; + for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){ + assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) ); + } + return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0); +} +#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */ + +/* +** Remove page pPage from the list of dirty pages. +*/ +static void pcacheRemoveFromDirtyList(PgHdr *pPage){ + PCache *p = pPage->pCache; + + assert( pPage->pDirtyNext || pPage==p->pDirtyTail ); + assert( pPage->pDirtyPrev || pPage==p->pDirty ); + + /* Update the PCache1.pSynced variable if necessary. */ + if( p->pSynced==pPage ){ + PgHdr *pSynced = pPage->pDirtyPrev; + while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){ + pSynced = pSynced->pDirtyPrev; + } + p->pSynced = pSynced; + } + + if( pPage->pDirtyNext ){ + pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev; + }else{ + assert( pPage==p->pDirtyTail ); + p->pDirtyTail = pPage->pDirtyPrev; + } + if( pPage->pDirtyPrev ){ + pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext; + }else{ + assert( pPage==p->pDirty ); + p->pDirty = pPage->pDirtyNext; + } + pPage->pDirtyNext = 0; + pPage->pDirtyPrev = 0; + + expensive_assert( pcacheCheckSynced(p) ); +} + +/* +** Add page pPage to the head of the dirty list (PCache1.pDirty is set to +** pPage). +*/ +static void pcacheAddToDirtyList(PgHdr *pPage){ + PCache *p = pPage->pCache; + + assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage ); + + pPage->pDirtyNext = p->pDirty; + if( pPage->pDirtyNext ){ + assert( pPage->pDirtyNext->pDirtyPrev==0 ); + pPage->pDirtyNext->pDirtyPrev = pPage; + } + p->pDirty = pPage; + if( !p->pDirtyTail ){ + p->pDirtyTail = pPage; + } + if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){ + p->pSynced = pPage; + } + expensive_assert( pcacheCheckSynced(p) ); +} + +/* +** Wrapper around the pluggable caches xUnpin method. If the cache is +** being used for an in-memory database, this function is a no-op. +*/ +static void pcacheUnpin(PgHdr *p){ + PCache *pCache = p->pCache; + if( pCache->bPurgeable ){ + if( p->pgno==1 ){ + pCache->pPage1 = 0; + } + sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0); + } +} + +/*************************************************** General Interfaces ****** +** +** Initialize and shutdown the page cache subsystem. Neither of these +** functions are threadsafe. +*/ +int sqlite3PcacheInitialize(void){ + if( sqlite3GlobalConfig.pcache2.xInit==0 ){ + /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the + ** built-in default page cache is used instead of the application defined + ** page cache. */ + sqlite3PCacheSetDefault(); + } + return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg); +} +void sqlite3PcacheShutdown(void){ + if( sqlite3GlobalConfig.pcache2.xShutdown ){ + /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */ + sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg); + } +} + +/* +** Return the size in bytes of a PCache object. +*/ +int sqlite3PcacheSize(void){ return sizeof(PCache); } + +/* +** Create a new PCache object. Storage space to hold the object +** has already been allocated and is passed in as the p pointer. +** The caller discovers how much space needs to be allocated by +** calling sqlite3PcacheSize(). +*/ +void sqlite3PcacheOpen( + int szPage, /* Size of every page */ + int szExtra, /* Extra space associated with each page */ + int bPurgeable, /* True if pages are on backing store */ + int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */ + void *pStress, /* Argument to xStress */ + PCache *p /* Preallocated space for the PCache */ +){ + memset(p, 0, sizeof(PCache)); + p->szPage = szPage; + p->szExtra = szExtra; + p->bPurgeable = bPurgeable; + p->xStress = xStress; + p->pStress = pStress; + p->szCache = 100; +} + +/* +** Change the page size for PCache object. The caller must ensure that there +** are no outstanding page references when this function is called. +*/ +void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ + assert( pCache->nRef==0 && pCache->pDirty==0 ); + if( pCache->pCache ){ + sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); + pCache->pCache = 0; + pCache->pPage1 = 0; + } + pCache->szPage = szPage; +} + +/* +** Compute the number of pages of cache requested. +*/ +static int numberOfCachePages(PCache *p){ + if( p->szCache>=0 ){ + return p->szCache; + }else{ + return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra)); + } +} + +/* +** Try to obtain a page from the cache. +*/ +int sqlite3PcacheFetch( + PCache *pCache, /* Obtain the page from this cache */ + Pgno pgno, /* Page number to obtain */ + int createFlag, /* If true, create page if it does not exist already */ + PgHdr **ppPage /* Write the page here */ +){ + sqlite3_pcache_page *pPage = 0; + PgHdr *pPgHdr = 0; + int eCreate; + + assert( pCache!=0 ); + assert( createFlag==1 || createFlag==0 ); + assert( pgno>0 ); + + /* If the pluggable cache (sqlite3_pcache*) has not been allocated, + ** allocate it now. + */ + if( !pCache->pCache && createFlag ){ + sqlite3_pcache *p; + p = sqlite3GlobalConfig.pcache2.xCreate( + pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable + ); + if( !p ){ + return SQLITE_NOMEM; + } + sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache)); + pCache->pCache = p; + } + + eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty)); + if( pCache->pCache ){ + pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate); + } + + if( !pPage && eCreate==1 ){ + PgHdr *pPg; + + /* Find a dirty page to write-out and recycle. First try to find a + ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC + ** cleared), but if that is not possible settle for any other + ** unreferenced dirty page. + */ + expensive_assert( pcacheCheckSynced(pCache) ); + for(pPg=pCache->pSynced; + pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); + pPg=pPg->pDirtyPrev + ); + pCache->pSynced = pPg; + if( !pPg ){ + for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev); + } + if( pPg ){ + int rc; +#ifdef SQLITE_LOG_CACHE_SPILL + sqlite3_log(SQLITE_FULL, + "spill page %d making room for %d - cache used: %d/%d", + pPg->pgno, pgno, + sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache), + numberOfCachePages(pCache)); +#endif + rc = pCache->xStress(pCache->pStress, pPg); + if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){ + return rc; + } + } + + pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2); + } + + if( pPage ){ + pPgHdr = (PgHdr *)pPage->pExtra; + + if( !pPgHdr->pPage ){ + memset(pPgHdr, 0, sizeof(PgHdr)); + pPgHdr->pPage = pPage; + pPgHdr->pData = pPage->pBuf; + pPgHdr->pExtra = (void *)&pPgHdr[1]; + memset(pPgHdr->pExtra, 0, pCache->szExtra); + pPgHdr->pCache = pCache; + pPgHdr->pgno = pgno; + } + assert( pPgHdr->pCache==pCache ); + assert( pPgHdr->pgno==pgno ); + assert( pPgHdr->pData==pPage->pBuf ); + assert( pPgHdr->pExtra==(void *)&pPgHdr[1] ); + + if( 0==pPgHdr->nRef ){ + pCache->nRef++; + } + pPgHdr->nRef++; + if( pgno==1 ){ + pCache->pPage1 = pPgHdr; + } + } + *ppPage = pPgHdr; + return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK; +} + +/* +** Decrement the reference count on a page. If the page is clean and the +** reference count drops to 0, then it is made elible for recycling. +*/ +void sqlite3PcacheRelease(PgHdr *p){ + assert( p->nRef>0 ); + p->nRef--; + if( p->nRef==0 ){ + PCache *pCache = p->pCache; + pCache->nRef--; + if( (p->flags&PGHDR_DIRTY)==0 ){ + pcacheUnpin(p); + }else{ + /* Move the page to the head of the dirty list. */ + pcacheRemoveFromDirtyList(p); + pcacheAddToDirtyList(p); + } + } +} + +/* +** Increase the reference count of a supplied page by 1. +*/ +void sqlite3PcacheRef(PgHdr *p){ + assert(p->nRef>0); + p->nRef++; +} + +/* +** Drop a page from the cache. There must be exactly one reference to the +** page. This function deletes that reference, so after it returns the +** page pointed to by p is invalid. +*/ +void sqlite3PcacheDrop(PgHdr *p){ + PCache *pCache; + assert( p->nRef==1 ); + if( p->flags&PGHDR_DIRTY ){ + pcacheRemoveFromDirtyList(p); + } + pCache = p->pCache; + pCache->nRef--; + if( p->pgno==1 ){ + pCache->pPage1 = 0; + } + sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1); +} + +/* +** Make sure the page is marked as dirty. If it isn't dirty already, +** make it so. +*/ +void sqlite3PcacheMakeDirty(PgHdr *p){ + p->flags &= ~PGHDR_DONT_WRITE; + assert( p->nRef>0 ); + if( 0==(p->flags & PGHDR_DIRTY) ){ + p->flags |= PGHDR_DIRTY; + pcacheAddToDirtyList( p); + } +} + +/* +** Make sure the page is marked as clean. If it isn't clean already, +** make it so. +*/ +void sqlite3PcacheMakeClean(PgHdr *p){ + if( (p->flags & PGHDR_DIRTY) ){ + pcacheRemoveFromDirtyList(p); + p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC); + if( p->nRef==0 ){ + pcacheUnpin(p); + } + } +} + +/* +** Make every page in the cache clean. +*/ +void sqlite3PcacheCleanAll(PCache *pCache){ + PgHdr *p; + while( (p = pCache->pDirty)!=0 ){ + sqlite3PcacheMakeClean(p); + } +} + +/* +** Clear the PGHDR_NEED_SYNC flag from all dirty pages. +*/ +void sqlite3PcacheClearSyncFlags(PCache *pCache){ + PgHdr *p; + for(p=pCache->pDirty; p; p=p->pDirtyNext){ + p->flags &= ~PGHDR_NEED_SYNC; + } + pCache->pSynced = pCache->pDirtyTail; +} + +/* +** Change the page number of page p to newPgno. +*/ +void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){ + PCache *pCache = p->pCache; + assert( p->nRef>0 ); + assert( newPgno>0 ); + sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno); + p->pgno = newPgno; + if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){ + pcacheRemoveFromDirtyList(p); + pcacheAddToDirtyList(p); + } +} + +/* +** Drop every cache entry whose page number is greater than "pgno". The +** caller must ensure that there are no outstanding references to any pages +** other than page 1 with a page number greater than pgno. +** +** If there is a reference to page 1 and the pgno parameter passed to this +** function is 0, then the data area associated with page 1 is zeroed, but +** the page object is not dropped. +*/ +void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){ + if( pCache->pCache ){ + PgHdr *p; + PgHdr *pNext; + for(p=pCache->pDirty; p; p=pNext){ + pNext = p->pDirtyNext; + /* This routine never gets call with a positive pgno except right + ** after sqlite3PcacheCleanAll(). So if there are dirty pages, + ** it must be that pgno==0. + */ + assert( p->pgno>0 ); + if( ALWAYS(p->pgno>pgno) ){ + assert( p->flags&PGHDR_DIRTY ); + sqlite3PcacheMakeClean(p); + } + } + if( pgno==0 && pCache->pPage1 ){ + memset(pCache->pPage1->pData, 0, pCache->szPage); + pgno = 1; + } + sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1); + } +} + +/* +** Close a cache. +*/ +void sqlite3PcacheClose(PCache *pCache){ + if( pCache->pCache ){ + sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); + } +} + +/* +** Discard the contents of the cache. +*/ +void sqlite3PcacheClear(PCache *pCache){ + sqlite3PcacheTruncate(pCache, 0); +} + +/* +** Merge two lists of pages connected by pDirty and in pgno order. +** Do not both fixing the pDirtyPrev pointers. +*/ +static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){ + PgHdr result, *pTail; + pTail = &result; + while( pA && pB ){ + if( pA->pgnopgno ){ + pTail->pDirty = pA; + pTail = pA; + pA = pA->pDirty; + }else{ + pTail->pDirty = pB; + pTail = pB; + pB = pB->pDirty; + } + } + if( pA ){ + pTail->pDirty = pA; + }else if( pB ){ + pTail->pDirty = pB; + }else{ + pTail->pDirty = 0; + } + return result.pDirty; +} + +/* +** Sort the list of pages in accending order by pgno. Pages are +** connected by pDirty pointers. The pDirtyPrev pointers are +** corrupted by this sort. +** +** Since there cannot be more than 2^31 distinct pages in a database, +** there cannot be more than 31 buckets required by the merge sorter. +** One extra bucket is added to catch overflow in case something +** ever changes to make the previous sentence incorrect. +*/ +#define N_SORT_BUCKET 32 +static PgHdr *pcacheSortDirtyList(PgHdr *pIn){ + PgHdr *a[N_SORT_BUCKET], *p; + int i; + memset(a, 0, sizeof(a)); + while( pIn ){ + p = pIn; + pIn = p->pDirty; + p->pDirty = 0; + for(i=0; ALWAYS(ipDirty; p; p=p->pDirtyNext){ + p->pDirty = p->pDirtyNext; + } + return pcacheSortDirtyList(pCache->pDirty); +} + +/* +** Return the total number of referenced pages held by the cache. +*/ +int sqlite3PcacheRefCount(PCache *pCache){ + return pCache->nRef; +} + +/* +** Return the number of references to the page supplied as an argument. +*/ +int sqlite3PcachePageRefcount(PgHdr *p){ + return p->nRef; +} + +/* +** Return the total number of pages in the cache. +*/ +int sqlite3PcachePagecount(PCache *pCache){ + int nPage = 0; + if( pCache->pCache ){ + nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache); + } + return nPage; +} + +#ifdef SQLITE_TEST +/* +** Get the suggested cache-size value. +*/ +int sqlite3PcacheGetCachesize(PCache *pCache){ + return numberOfCachePages(pCache); +} +#endif + +/* +** Set the suggested cache-size value. +*/ +void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){ + pCache->szCache = mxPage; + if( pCache->pCache ){ + sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache, + numberOfCachePages(pCache)); + } +} + +/* +** Free up as much memory as possible from the page cache. +*/ +void sqlite3PcacheShrink(PCache *pCache){ + if( pCache->pCache ){ + sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache); + } +} + +#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) +/* +** For all dirty pages currently in the cache, invoke the specified +** callback. This is only used if the SQLITE_CHECK_PAGES macro is +** defined. +*/ +void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){ + PgHdr *pDirty; + for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){ + xIter(pDirty); + } +} +#endif diff --git a/components/external/SQLite-3.8.1/src/pcache.h b/components/external/SQLite-3.8.1/src/pcache.h new file mode 100644 index 0000000000000000000000000000000000000000..f4d4ad71c10d78c6dabde25215cd415a760148ca --- /dev/null +++ b/components/external/SQLite-3.8.1/src/pcache.h @@ -0,0 +1,161 @@ +/* +** 2008 August 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. +*/ + +#ifndef _PCACHE_H_ + +typedef struct PgHdr PgHdr; +typedef struct PCache PCache; + +/* +** Every page in the cache is controlled by an instance of the following +** structure. +*/ +struct PgHdr { + sqlite3_pcache_page *pPage; /* Pcache object page handle */ + void *pData; /* Page data */ + void *pExtra; /* Extra content */ + PgHdr *pDirty; /* Transient list of dirty pages */ + Pager *pPager; /* The pager this page is part of */ + Pgno pgno; /* Page number for this page */ +#ifdef SQLITE_CHECK_PAGES + u32 pageHash; /* Hash of page content */ +#endif + u16 flags; /* PGHDR flags defined below */ + + /********************************************************************** + ** Elements above are public. All that follows is private to pcache.c + ** and should not be accessed by other modules. + */ + i16 nRef; /* Number of users of this page */ + PCache *pCache; /* Cache that owns this page */ + + PgHdr *pDirtyNext; /* Next element in list of dirty pages */ + PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ +}; + +/* Bit values for PgHdr.flags */ +#define PGHDR_DIRTY 0x002 /* Page has changed */ +#define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before + ** writing this page to the database */ +#define PGHDR_NEED_READ 0x008 /* Content is unread */ +#define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */ +#define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */ + +#define PGHDR_MMAP 0x040 /* This is an mmap page object */ + +/* Initialize and shutdown the page cache subsystem */ +int sqlite3PcacheInitialize(void); +void sqlite3PcacheShutdown(void); + +/* Page cache buffer management: +** These routines implement SQLITE_CONFIG_PAGECACHE. +*/ +void sqlite3PCacheBufferSetup(void *, int sz, int n); + +/* Create a new pager cache. +** Under memory stress, invoke xStress to try to make pages clean. +** Only clean and unpinned pages can be reclaimed. +*/ +void sqlite3PcacheOpen( + int szPage, /* Size of every page */ + int szExtra, /* Extra space associated with each page */ + int bPurgeable, /* True if pages are on backing store */ + int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ + void *pStress, /* Argument to xStress */ + PCache *pToInit /* Preallocated space for the PCache */ +); + +/* Modify the page-size after the cache has been created. */ +void sqlite3PcacheSetPageSize(PCache *, int); + +/* Return the size in bytes of a PCache object. Used to preallocate +** storage space. +*/ +int sqlite3PcacheSize(void); + +/* One release per successful fetch. Page is pinned until released. +** Reference counted. +*/ +int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**); +void sqlite3PcacheRelease(PgHdr*); + +void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ +void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ +void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ +void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ + +/* Change a page number. Used by incr-vacuum. */ +void sqlite3PcacheMove(PgHdr*, Pgno); + +/* Remove all pages with pgno>x. Reset the cache if x==0 */ +void sqlite3PcacheTruncate(PCache*, Pgno x); + +/* Get a list of all dirty pages in the cache, sorted by page number */ +PgHdr *sqlite3PcacheDirtyList(PCache*); + +/* Reset and close the cache object */ +void sqlite3PcacheClose(PCache*); + +/* Clear flags from pages of the page cache */ +void sqlite3PcacheClearSyncFlags(PCache *); + +/* Discard the contents of the cache */ +void sqlite3PcacheClear(PCache*); + +/* Return the total number of outstanding page references */ +int sqlite3PcacheRefCount(PCache*); + +/* Increment the reference count of an existing page */ +void sqlite3PcacheRef(PgHdr*); + +int sqlite3PcachePageRefcount(PgHdr*); + +/* Return the total number of pages stored in the cache */ +int sqlite3PcachePagecount(PCache*); + +#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) +/* Iterate through all dirty pages currently stored in the cache. This +** interface is only available if SQLITE_CHECK_PAGES is defined when the +** library is built. +*/ +void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); +#endif + +/* Set and get the suggested cache-size for the specified pager-cache. +** +** If no global maximum is configured, then the system attempts to limit +** the total number of pages cached by purgeable pager-caches to the sum +** of the suggested cache-sizes. +*/ +void sqlite3PcacheSetCachesize(PCache *, int); +#ifdef SQLITE_TEST +int sqlite3PcacheGetCachesize(PCache *); +#endif + +/* Free up as much memory as possible from the page cache */ +void sqlite3PcacheShrink(PCache*); + +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT +/* Try to return memory used by the pcache module to the main memory heap */ +int sqlite3PcacheReleaseMemory(int); +#endif + +#ifdef SQLITE_TEST +void sqlite3PcacheStats(int*,int*,int*,int*); +#endif + +void sqlite3PCacheSetDefault(void); + +#endif /* _PCACHE_H_ */ diff --git a/components/external/SQLite-3.8.1/src/pcache1.c b/components/external/SQLite-3.8.1/src/pcache1.c new file mode 100644 index 0000000000000000000000000000000000000000..df9d877537058127fa9788f16e3260cb5e062d06 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/pcache1.c @@ -0,0 +1,1021 @@ +/* +** 2008 November 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements the default page cache implementation (the +** sqlite3_pcache interface). It also contains part of the implementation +** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features. +** If the default page cache implementation is overriden, then neither of +** these two features are available. +*/ + +#include "sqliteInt.h" + +typedef struct PCache1 PCache1; +typedef struct PgHdr1 PgHdr1; +typedef struct PgFreeslot PgFreeslot; +typedef struct PGroup PGroup; + +/* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set +** of one or more PCaches that are able to recycle each others unpinned +** pages when they are under memory pressure. A PGroup is an instance of +** the following object. +** +** This page cache implementation works in one of two modes: +** +** (1) Every PCache is the sole member of its own PGroup. There is +** one PGroup per PCache. +** +** (2) There is a single global PGroup that all PCaches are a member +** of. +** +** Mode 1 uses more memory (since PCache instances are not able to rob +** unused pages from other PCaches) but it also operates without a mutex, +** and is therefore often faster. Mode 2 requires a mutex in order to be +** threadsafe, but recycles pages more efficiently. +** +** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single +** PGroup which is the pcache1.grp global variable and its mutex is +** SQLITE_MUTEX_STATIC_LRU. +*/ +struct PGroup { + sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */ + unsigned int nMaxPage; /* Sum of nMax for purgeable caches */ + unsigned int nMinPage; /* Sum of nMin for purgeable caches */ + unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */ + unsigned int nCurrentPage; /* Number of purgeable pages allocated */ + PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */ +}; + +/* Each page cache is an instance of the following object. Every +** open database file (including each in-memory database and each +** temporary or transient database) has a single page cache which +** is an instance of this object. +** +** Pointers to structures of this type are cast and returned as +** opaque sqlite3_pcache* handles. +*/ +struct PCache1 { + /* Cache configuration parameters. Page size (szPage) and the purgeable + ** flag (bPurgeable) are set when the cache is created. nMax may be + ** modified at any time by a call to the pcache1Cachesize() method. + ** The PGroup mutex must be held when accessing nMax. + */ + PGroup *pGroup; /* PGroup this cache belongs to */ + int szPage; /* Size of allocated pages in bytes */ + int szExtra; /* Size of extra space in bytes */ + int bPurgeable; /* True if cache is purgeable */ + unsigned int nMin; /* Minimum number of pages reserved */ + unsigned int nMax; /* Configured "cache_size" value */ + unsigned int n90pct; /* nMax*9/10 */ + unsigned int iMaxKey; /* Largest key seen since xTruncate() */ + + /* Hash table of all pages. The following variables may only be accessed + ** when the accessor is holding the PGroup mutex. + */ + unsigned int nRecyclable; /* Number of pages in the LRU list */ + unsigned int nPage; /* Total number of pages in apHash */ + unsigned int nHash; /* Number of slots in apHash[] */ + PgHdr1 **apHash; /* Hash table for fast lookup by key */ +}; + +/* +** Each cache entry is represented by an instance of the following +** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of +** PgHdr1.pCache->szPage bytes is allocated directly before this structure +** in memory. +*/ +struct PgHdr1 { + sqlite3_pcache_page page; + unsigned int iKey; /* Key value (page number) */ + PgHdr1 *pNext; /* Next in hash table chain */ + PCache1 *pCache; /* Cache that currently owns this page */ + PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */ + PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */ +}; + +/* +** Free slots in the allocator used to divide up the buffer provided using +** the SQLITE_CONFIG_PAGECACHE mechanism. +*/ +struct PgFreeslot { + PgFreeslot *pNext; /* Next free slot */ +}; + +/* +** Global data used by this cache. +*/ +static SQLITE_WSD struct PCacheGlobal { + PGroup grp; /* The global PGroup for mode (2) */ + + /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The + ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all + ** fixed at sqlite3_initialize() time and do not require mutex protection. + ** The nFreeSlot and pFree values do require mutex protection. + */ + int isInit; /* True if initialized */ + int szSlot; /* Size of each free slot */ + int nSlot; /* The number of pcache slots */ + int nReserve; /* Try to keep nFreeSlot above this */ + void *pStart, *pEnd; /* Bounds of pagecache malloc range */ + /* Above requires no mutex. Use mutex below for variable that follow. */ + sqlite3_mutex *mutex; /* Mutex for accessing the following: */ + PgFreeslot *pFree; /* Free page blocks */ + int nFreeSlot; /* Number of unused pcache slots */ + /* The following value requires a mutex to change. We skip the mutex on + ** reading because (1) most platforms read a 32-bit integer atomically and + ** (2) even if an incorrect value is read, no great harm is done since this + ** is really just an optimization. */ + int bUnderPressure; /* True if low on PAGECACHE memory */ +} pcache1_g; + +/* +** All code in this file should access the global structure above via the +** alias "pcache1". This ensures that the WSD emulation is used when +** compiling for systems that do not support real WSD. +*/ +#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g)) + +/* +** Macros to enter and leave the PCache LRU mutex. +*/ +#define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex) +#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex) + +/******************************************************************************/ +/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/ + +/* +** This function is called during initialization if a static buffer is +** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE +** verb to sqlite3_config(). Parameter pBuf points to an allocation large +** enough to contain 'n' buffers of 'sz' bytes each. +** +** This routine is called from sqlite3_initialize() and so it is guaranteed +** to be serialized already. There is no need for further mutexing. +*/ +void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){ + if( pcache1.isInit ){ + PgFreeslot *p; + sz = ROUNDDOWN8(sz); + pcache1.szSlot = sz; + pcache1.nSlot = pcache1.nFreeSlot = n; + pcache1.nReserve = n>90 ? 10 : (n/10 + 1); + pcache1.pStart = pBuf; + pcache1.pFree = 0; + pcache1.bUnderPressure = 0; + while( n-- ){ + p = (PgFreeslot*)pBuf; + p->pNext = pcache1.pFree; + pcache1.pFree = p; + pBuf = (void*)&((char*)pBuf)[sz]; + } + pcache1.pEnd = pBuf; + } +} + +/* +** Malloc function used within this file to allocate space from the buffer +** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no +** such buffer exists or there is no space left in it, this function falls +** back to sqlite3Malloc(). +** +** Multiple threads can run this routine at the same time. Global variables +** in pcache1 need to be protected via mutex. +*/ +static void *pcache1Alloc(int nByte){ + void *p = 0; + assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); + sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte); + if( nByte<=pcache1.szSlot ){ + sqlite3_mutex_enter(pcache1.mutex); + p = (PgHdr1 *)pcache1.pFree; + if( p ){ + pcache1.pFree = pcache1.pFree->pNext; + pcache1.nFreeSlot--; + pcache1.bUnderPressure = pcache1.nFreeSlot=0 ); + sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1); + } + sqlite3_mutex_leave(pcache1.mutex); + } + if( p==0 ){ + /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get + ** it from sqlite3Malloc instead. + */ + p = sqlite3Malloc(nByte); +#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS + if( p ){ + int sz = sqlite3MallocSize(p); + sqlite3_mutex_enter(pcache1.mutex); + sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz); + sqlite3_mutex_leave(pcache1.mutex); + } +#endif + sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); + } + return p; +} + +/* +** Free an allocated buffer obtained from pcache1Alloc(). +*/ +static int pcache1Free(void *p){ + int nFreed = 0; + if( p==0 ) return 0; + if( p>=pcache1.pStart && ppNext = pcache1.pFree; + pcache1.pFree = pSlot; + pcache1.nFreeSlot++; + pcache1.bUnderPressure = pcache1.nFreeSlot=pcache1.pStart && ppGroup->mutex) ); + pcache1LeaveMutex(pCache->pGroup); +#ifdef SQLITE_PCACHE_SEPARATE_HEADER + pPg = pcache1Alloc(pCache->szPage); + p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra); + if( !pPg || !p ){ + pcache1Free(pPg); + sqlite3_free(p); + pPg = 0; + } +#else + pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra); + p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage]; +#endif + pcache1EnterMutex(pCache->pGroup); + + if( pPg ){ + p->page.pBuf = pPg; + p->page.pExtra = &p[1]; + if( pCache->bPurgeable ){ + pCache->pGroup->nCurrentPage++; + } + return p; + } + return 0; +} + +/* +** Free a page object allocated by pcache1AllocPage(). +** +** The pointer is allowed to be NULL, which is prudent. But it turns out +** that the current implementation happens to never call this routine +** with a NULL pointer, so we mark the NULL test with ALWAYS(). +*/ +static void pcache1FreePage(PgHdr1 *p){ + if( ALWAYS(p) ){ + PCache1 *pCache = p->pCache; + assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) ); + pcache1Free(p->page.pBuf); +#ifdef SQLITE_PCACHE_SEPARATE_HEADER + sqlite3_free(p); +#endif + if( pCache->bPurgeable ){ + pCache->pGroup->nCurrentPage--; + } + } +} + +/* +** Malloc function used by SQLite to obtain space from the buffer configured +** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer +** exists, this function falls back to sqlite3Malloc(). +*/ +void *sqlite3PageMalloc(int sz){ + return pcache1Alloc(sz); +} + +/* +** Free an allocated buffer obtained from sqlite3PageMalloc(). +*/ +void sqlite3PageFree(void *p){ + pcache1Free(p); +} + + +/* +** Return true if it desirable to avoid allocating a new page cache +** entry. +** +** If memory was allocated specifically to the page cache using +** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then +** it is desirable to avoid allocating a new page cache entry because +** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient +** for all page cache needs and we should not need to spill the +** allocation onto the heap. +** +** Or, the heap is used for all page cache memory but the heap is +** under memory pressure, then again it is desirable to avoid +** allocating a new page cache entry in order to avoid stressing +** the heap even further. +*/ +static int pcache1UnderMemoryPressure(PCache1 *pCache){ + if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){ + return pcache1.bUnderPressure; + }else{ + return sqlite3HeapNearlyFull(); + } +} + +/******************************************************************************/ +/******** General Implementation Functions ************************************/ + +/* +** This function is used to resize the hash table used by the cache passed +** as the first argument. +** +** The PCache mutex must be held when this function is called. +*/ +static int pcache1ResizeHash(PCache1 *p){ + PgHdr1 **apNew; + unsigned int nNew; + unsigned int i; + + assert( sqlite3_mutex_held(p->pGroup->mutex) ); + + nNew = p->nHash*2; + if( nNew<256 ){ + nNew = 256; + } + + pcache1LeaveMutex(p->pGroup); + if( p->nHash ){ sqlite3BeginBenignMalloc(); } + apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew); + if( p->nHash ){ sqlite3EndBenignMalloc(); } + pcache1EnterMutex(p->pGroup); + if( apNew ){ + for(i=0; inHash; i++){ + PgHdr1 *pPage; + PgHdr1 *pNext = p->apHash[i]; + while( (pPage = pNext)!=0 ){ + unsigned int h = pPage->iKey % nNew; + pNext = pPage->pNext; + pPage->pNext = apNew[h]; + apNew[h] = pPage; + } + } + sqlite3_free(p->apHash); + p->apHash = apNew; + p->nHash = nNew; + } + + return (p->apHash ? SQLITE_OK : SQLITE_NOMEM); +} + +/* +** This function is used internally to remove the page pPage from the +** PGroup LRU list, if is part of it. If pPage is not part of the PGroup +** LRU list, then this function is a no-op. +** +** The PGroup mutex must be held when this function is called. +** +** If pPage is NULL then this routine is a no-op. +*/ +static void pcache1PinPage(PgHdr1 *pPage){ + PCache1 *pCache; + PGroup *pGroup; + + if( pPage==0 ) return; + pCache = pPage->pCache; + pGroup = pCache->pGroup; + assert( sqlite3_mutex_held(pGroup->mutex) ); + if( pPage->pLruNext || pPage==pGroup->pLruTail ){ + if( pPage->pLruPrev ){ + pPage->pLruPrev->pLruNext = pPage->pLruNext; + } + if( pPage->pLruNext ){ + pPage->pLruNext->pLruPrev = pPage->pLruPrev; + } + if( pGroup->pLruHead==pPage ){ + pGroup->pLruHead = pPage->pLruNext; + } + if( pGroup->pLruTail==pPage ){ + pGroup->pLruTail = pPage->pLruPrev; + } + pPage->pLruNext = 0; + pPage->pLruPrev = 0; + pPage->pCache->nRecyclable--; + } +} + + +/* +** Remove the page supplied as an argument from the hash table +** (PCache1.apHash structure) that it is currently stored in. +** +** The PGroup mutex must be held when this function is called. +*/ +static void pcache1RemoveFromHash(PgHdr1 *pPage){ + unsigned int h; + PCache1 *pCache = pPage->pCache; + PgHdr1 **pp; + + assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); + h = pPage->iKey % pCache->nHash; + for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext); + *pp = (*pp)->pNext; + + pCache->nPage--; +} + +/* +** If there are currently more than nMaxPage pages allocated, try +** to recycle pages to reduce the number allocated to nMaxPage. +*/ +static void pcache1EnforceMaxPage(PGroup *pGroup){ + assert( sqlite3_mutex_held(pGroup->mutex) ); + while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){ + PgHdr1 *p = pGroup->pLruTail; + assert( p->pCache->pGroup==pGroup ); + pcache1PinPage(p); + pcache1RemoveFromHash(p); + pcache1FreePage(p); + } +} + +/* +** Discard all pages from cache pCache with a page number (key value) +** greater than or equal to iLimit. Any pinned pages that meet this +** criteria are unpinned before they are discarded. +** +** The PCache mutex must be held when this function is called. +*/ +static void pcache1TruncateUnsafe( + PCache1 *pCache, /* The cache to truncate */ + unsigned int iLimit /* Drop pages with this pgno or larger */ +){ + TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */ + unsigned int h; + assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); + for(h=0; hnHash; h++){ + PgHdr1 **pp = &pCache->apHash[h]; + PgHdr1 *pPage; + while( (pPage = *pp)!=0 ){ + if( pPage->iKey>=iLimit ){ + pCache->nPage--; + *pp = pPage->pNext; + pcache1PinPage(pPage); + pcache1FreePage(pPage); + }else{ + pp = &pPage->pNext; + TESTONLY( nPage++; ) + } + } + } + assert( pCache->nPage==nPage ); +} + +/******************************************************************************/ +/******** sqlite3_pcache Methods **********************************************/ + +/* +** Implementation of the sqlite3_pcache.xInit method. +*/ +static int pcache1Init(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + assert( pcache1.isInit==0 ); + memset(&pcache1, 0, sizeof(pcache1)); + if( sqlite3GlobalConfig.bCoreMutex ){ + pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU); + pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM); + } + pcache1.grp.mxPinned = 10; + pcache1.isInit = 1; + return SQLITE_OK; +} + +/* +** Implementation of the sqlite3_pcache.xShutdown method. +** Note that the static mutex allocated in xInit does +** not need to be freed. +*/ +static void pcache1Shutdown(void *NotUsed){ + UNUSED_PARAMETER(NotUsed); + assert( pcache1.isInit!=0 ); + memset(&pcache1, 0, sizeof(pcache1)); +} + +/* +** Implementation of the sqlite3_pcache.xCreate method. +** +** Allocate a new cache. +*/ +static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ + PCache1 *pCache; /* The newly created page cache */ + PGroup *pGroup; /* The group the new page cache will belong to */ + int sz; /* Bytes of memory required to allocate the new cache */ + + /* + ** The separateCache variable is true if each PCache has its own private + ** PGroup. In other words, separateCache is true for mode (1) where no + ** mutexing is required. + ** + ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT + ** + ** * Always use a unified cache in single-threaded applications + ** + ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off) + ** use separate caches (mode-1) + */ +#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0 + const int separateCache = 0; +#else + int separateCache = sqlite3GlobalConfig.bCoreMutex>0; +#endif + + assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 ); + assert( szExtra < 300 ); + + sz = sizeof(PCache1) + sizeof(PGroup)*separateCache; + pCache = (PCache1 *)sqlite3MallocZero(sz); + if( pCache ){ + if( separateCache ){ + pGroup = (PGroup*)&pCache[1]; + pGroup->mxPinned = 10; + }else{ + pGroup = &pcache1.grp; + } + pCache->pGroup = pGroup; + pCache->szPage = szPage; + pCache->szExtra = szExtra; + pCache->bPurgeable = (bPurgeable ? 1 : 0); + if( bPurgeable ){ + pCache->nMin = 10; + pcache1EnterMutex(pGroup); + pGroup->nMinPage += pCache->nMin; + pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; + pcache1LeaveMutex(pGroup); + } + } + return (sqlite3_pcache *)pCache; +} + +/* +** Implementation of the sqlite3_pcache.xCachesize method. +** +** Configure the cache_size limit for a cache. +*/ +static void pcache1Cachesize(sqlite3_pcache *p, int nMax){ + PCache1 *pCache = (PCache1 *)p; + if( pCache->bPurgeable ){ + PGroup *pGroup = pCache->pGroup; + pcache1EnterMutex(pGroup); + pGroup->nMaxPage += (nMax - pCache->nMax); + pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; + pCache->nMax = nMax; + pCache->n90pct = pCache->nMax*9/10; + pcache1EnforceMaxPage(pGroup); + pcache1LeaveMutex(pGroup); + } +} + +/* +** Implementation of the sqlite3_pcache.xShrink method. +** +** Free up as much memory as possible. +*/ +static void pcache1Shrink(sqlite3_pcache *p){ + PCache1 *pCache = (PCache1*)p; + if( pCache->bPurgeable ){ + PGroup *pGroup = pCache->pGroup; + int savedMaxPage; + pcache1EnterMutex(pGroup); + savedMaxPage = pGroup->nMaxPage; + pGroup->nMaxPage = 0; + pcache1EnforceMaxPage(pGroup); + pGroup->nMaxPage = savedMaxPage; + pcache1LeaveMutex(pGroup); + } +} + +/* +** Implementation of the sqlite3_pcache.xPagecount method. +*/ +static int pcache1Pagecount(sqlite3_pcache *p){ + int n; + PCache1 *pCache = (PCache1*)p; + pcache1EnterMutex(pCache->pGroup); + n = pCache->nPage; + pcache1LeaveMutex(pCache->pGroup); + return n; +} + +/* +** Implementation of the sqlite3_pcache.xFetch method. +** +** Fetch a page by key value. +** +** Whether or not a new page may be allocated by this function depends on +** the value of the createFlag argument. 0 means do not allocate a new +** page. 1 means allocate a new page if space is easily available. 2 +** means to try really hard to allocate a new page. +** +** For a non-purgeable cache (a cache used as the storage for an in-memory +** database) there is really no difference between createFlag 1 and 2. So +** the calling function (pcache.c) will never have a createFlag of 1 on +** a non-purgeable cache. +** +** There are three different approaches to obtaining space for a page, +** depending on the value of parameter createFlag (which may be 0, 1 or 2). +** +** 1. Regardless of the value of createFlag, the cache is searched for a +** copy of the requested page. If one is found, it is returned. +** +** 2. If createFlag==0 and the page is not already in the cache, NULL is +** returned. +** +** 3. If createFlag is 1, and the page is not already in the cache, then +** return NULL (do not allocate a new page) if any of the following +** conditions are true: +** +** (a) the number of pages pinned by the cache is greater than +** PCache1.nMax, or +** +** (b) the number of pages pinned by the cache is greater than +** the sum of nMax for all purgeable caches, less the sum of +** nMin for all other purgeable caches, or +** +** 4. If none of the first three conditions apply and the cache is marked +** as purgeable, and if one of the following is true: +** +** (a) The number of pages allocated for the cache is already +** PCache1.nMax, or +** +** (b) The number of pages allocated for all purgeable caches is +** already equal to or greater than the sum of nMax for all +** purgeable caches, +** +** (c) The system is under memory pressure and wants to avoid +** unnecessary pages cache entry allocations +** +** then attempt to recycle a page from the LRU list. If it is the right +** size, return the recycled buffer. Otherwise, free the buffer and +** proceed to step 5. +** +** 5. Otherwise, allocate and return a new page buffer. +*/ +static sqlite3_pcache_page *pcache1Fetch( + sqlite3_pcache *p, + unsigned int iKey, + int createFlag +){ + unsigned int nPinned; + PCache1 *pCache = (PCache1 *)p; + PGroup *pGroup; + PgHdr1 *pPage = 0; + + assert( pCache->bPurgeable || createFlag!=1 ); + assert( pCache->bPurgeable || pCache->nMin==0 ); + assert( pCache->bPurgeable==0 || pCache->nMin==10 ); + assert( pCache->nMin==0 || pCache->bPurgeable ); + pcache1EnterMutex(pGroup = pCache->pGroup); + + /* Step 1: Search the hash table for an existing entry. */ + if( pCache->nHash>0 ){ + unsigned int h = iKey % pCache->nHash; + for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext); + } + + /* Step 2: Abort if no existing page is found and createFlag is 0 */ + if( pPage || createFlag==0 ){ + pcache1PinPage(pPage); + goto fetch_out; + } + + /* The pGroup local variable will normally be initialized by the + ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined, + ** then pcache1EnterMutex() is a no-op, so we have to initialize the + ** local variable here. Delaying the initialization of pGroup is an + ** optimization: The common case is to exit the module before reaching + ** this point. + */ +#ifdef SQLITE_MUTEX_OMIT + pGroup = pCache->pGroup; +#endif + + /* Step 3: Abort if createFlag is 1 but the cache is nearly full */ + assert( pCache->nPage >= pCache->nRecyclable ); + nPinned = pCache->nPage - pCache->nRecyclable; + assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage ); + assert( pCache->n90pct == pCache->nMax*9/10 ); + if( createFlag==1 && ( + nPinned>=pGroup->mxPinned + || nPinned>=pCache->n90pct + || pcache1UnderMemoryPressure(pCache) + )){ + goto fetch_out; + } + + if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){ + goto fetch_out; + } + assert( pCache->nHash>0 && pCache->apHash ); + + /* Step 4. Try to recycle a page. */ + if( pCache->bPurgeable && pGroup->pLruTail && ( + (pCache->nPage+1>=pCache->nMax) + || pGroup->nCurrentPage>=pGroup->nMaxPage + || pcache1UnderMemoryPressure(pCache) + )){ + PCache1 *pOther; + pPage = pGroup->pLruTail; + pcache1RemoveFromHash(pPage); + pcache1PinPage(pPage); + pOther = pPage->pCache; + + /* We want to verify that szPage and szExtra are the same for pOther + ** and pCache. Assert that we can verify this by comparing sums. */ + assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 ); + assert( pCache->szExtra<512 ); + assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 ); + assert( pOther->szExtra<512 ); + + if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){ + pcache1FreePage(pPage); + pPage = 0; + }else{ + pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable); + } + } + + /* Step 5. If a usable page buffer has still not been found, + ** attempt to allocate a new one. + */ + if( !pPage ){ + if( createFlag==1 ) sqlite3BeginBenignMalloc(); + pPage = pcache1AllocPage(pCache); + if( createFlag==1 ) sqlite3EndBenignMalloc(); + } + + if( pPage ){ + unsigned int h = iKey % pCache->nHash; + pCache->nPage++; + pPage->iKey = iKey; + pPage->pNext = pCache->apHash[h]; + pPage->pCache = pCache; + pPage->pLruPrev = 0; + pPage->pLruNext = 0; + *(void **)pPage->page.pExtra = 0; + pCache->apHash[h] = pPage; + } + +fetch_out: + if( pPage && iKey>pCache->iMaxKey ){ + pCache->iMaxKey = iKey; + } + pcache1LeaveMutex(pGroup); + return &pPage->page; +} + + +/* +** Implementation of the sqlite3_pcache.xUnpin method. +** +** Mark a page as unpinned (eligible for asynchronous recycling). +*/ +static void pcache1Unpin( + sqlite3_pcache *p, + sqlite3_pcache_page *pPg, + int reuseUnlikely +){ + PCache1 *pCache = (PCache1 *)p; + PgHdr1 *pPage = (PgHdr1 *)pPg; + PGroup *pGroup = pCache->pGroup; + + assert( pPage->pCache==pCache ); + pcache1EnterMutex(pGroup); + + /* It is an error to call this function if the page is already + ** part of the PGroup LRU list. + */ + assert( pPage->pLruPrev==0 && pPage->pLruNext==0 ); + assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage ); + + if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){ + pcache1RemoveFromHash(pPage); + pcache1FreePage(pPage); + }else{ + /* Add the page to the PGroup LRU list. */ + if( pGroup->pLruHead ){ + pGroup->pLruHead->pLruPrev = pPage; + pPage->pLruNext = pGroup->pLruHead; + pGroup->pLruHead = pPage; + }else{ + pGroup->pLruTail = pPage; + pGroup->pLruHead = pPage; + } + pCache->nRecyclable++; + } + + pcache1LeaveMutex(pCache->pGroup); +} + +/* +** Implementation of the sqlite3_pcache.xRekey method. +*/ +static void pcache1Rekey( + sqlite3_pcache *p, + sqlite3_pcache_page *pPg, + unsigned int iOld, + unsigned int iNew +){ + PCache1 *pCache = (PCache1 *)p; + PgHdr1 *pPage = (PgHdr1 *)pPg; + PgHdr1 **pp; + unsigned int h; + assert( pPage->iKey==iOld ); + assert( pPage->pCache==pCache ); + + pcache1EnterMutex(pCache->pGroup); + + h = iOld%pCache->nHash; + pp = &pCache->apHash[h]; + while( (*pp)!=pPage ){ + pp = &(*pp)->pNext; + } + *pp = pPage->pNext; + + h = iNew%pCache->nHash; + pPage->iKey = iNew; + pPage->pNext = pCache->apHash[h]; + pCache->apHash[h] = pPage; + if( iNew>pCache->iMaxKey ){ + pCache->iMaxKey = iNew; + } + + pcache1LeaveMutex(pCache->pGroup); +} + +/* +** Implementation of the sqlite3_pcache.xTruncate method. +** +** Discard all unpinned pages in the cache with a page number equal to +** or greater than parameter iLimit. Any pinned pages with a page number +** equal to or greater than iLimit are implicitly unpinned. +*/ +static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){ + PCache1 *pCache = (PCache1 *)p; + pcache1EnterMutex(pCache->pGroup); + if( iLimit<=pCache->iMaxKey ){ + pcache1TruncateUnsafe(pCache, iLimit); + pCache->iMaxKey = iLimit-1; + } + pcache1LeaveMutex(pCache->pGroup); +} + +/* +** Implementation of the sqlite3_pcache.xDestroy method. +** +** Destroy a cache allocated using pcache1Create(). +*/ +static void pcache1Destroy(sqlite3_pcache *p){ + PCache1 *pCache = (PCache1 *)p; + PGroup *pGroup = pCache->pGroup; + assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) ); + pcache1EnterMutex(pGroup); + pcache1TruncateUnsafe(pCache, 0); + assert( pGroup->nMaxPage >= pCache->nMax ); + pGroup->nMaxPage -= pCache->nMax; + assert( pGroup->nMinPage >= pCache->nMin ); + pGroup->nMinPage -= pCache->nMin; + pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; + pcache1EnforceMaxPage(pGroup); + pcache1LeaveMutex(pGroup); + sqlite3_free(pCache->apHash); + sqlite3_free(pCache); +} + +/* +** This function is called during initialization (sqlite3_initialize()) to +** install the default pluggable cache module, assuming the user has not +** already provided an alternative. +*/ +void sqlite3PCacheSetDefault(void){ + static const sqlite3_pcache_methods2 defaultMethods = { + 1, /* iVersion */ + 0, /* pArg */ + pcache1Init, /* xInit */ + pcache1Shutdown, /* xShutdown */ + pcache1Create, /* xCreate */ + pcache1Cachesize, /* xCachesize */ + pcache1Pagecount, /* xPagecount */ + pcache1Fetch, /* xFetch */ + pcache1Unpin, /* xUnpin */ + pcache1Rekey, /* xRekey */ + pcache1Truncate, /* xTruncate */ + pcache1Destroy, /* xDestroy */ + pcache1Shrink /* xShrink */ + }; + sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods); +} + +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT +/* +** This function is called to free superfluous dynamically allocated memory +** held by the pager system. Memory in use by any SQLite pager allocated +** by the current thread may be sqlite3_free()ed. +** +** nReq is the number of bytes of memory required. Once this much has +** been released, the function returns. The return value is the total number +** of bytes of memory released. +*/ +int sqlite3PcacheReleaseMemory(int nReq){ + int nFree = 0; + assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); + assert( sqlite3_mutex_notheld(pcache1.mutex) ); + if( pcache1.pStart==0 ){ + PgHdr1 *p; + pcache1EnterMutex(&pcache1.grp); + while( (nReq<0 || nFreepage.pBuf); +#ifdef SQLITE_PCACHE_SEPARATE_HEADER + nFree += sqlite3MemSize(p); +#endif + pcache1PinPage(p); + pcache1RemoveFromHash(p); + pcache1FreePage(p); + } + pcache1LeaveMutex(&pcache1.grp); + } + return nFree; +} +#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */ + +#ifdef SQLITE_TEST +/* +** This function is used by test procedures to inspect the internal state +** of the global cache. +*/ +void sqlite3PcacheStats( + int *pnCurrent, /* OUT: Total number of pages cached */ + int *pnMax, /* OUT: Global maximum cache size */ + int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */ + int *pnRecyclable /* OUT: Total number of pages available for recycling */ +){ + PgHdr1 *p; + int nRecyclable = 0; + for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){ + nRecyclable++; + } + *pnCurrent = pcache1.grp.nCurrentPage; + *pnMax = (int)pcache1.grp.nMaxPage; + *pnMin = (int)pcache1.grp.nMinPage; + *pnRecyclable = nRecyclable; +} +#endif diff --git a/components/external/SQLite-3.8.1/src/pragma.c b/components/external/SQLite-3.8.1/src/pragma.c new file mode 100644 index 0000000000000000000000000000000000000000..a1f32c36d35723afb179198ad9b87df459ed71f3 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/pragma.c @@ -0,0 +1,2259 @@ +/* +** 2003 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the PRAGMA command. +*/ +#include "sqliteInt.h" + +#if !defined(SQLITE_ENABLE_LOCKING_STYLE) +# if defined(__APPLE__) +# define SQLITE_ENABLE_LOCKING_STYLE 1 +# else +# define SQLITE_ENABLE_LOCKING_STYLE 0 +# endif +#endif + +/*************************************************************************** +** The next block of code, including the PragTyp_XXXX macro definitions and +** the aPragmaName[] object is composed of generated code. DO NOT EDIT. +** +** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun +** that script. Then copy/paste the output in place of the following: +*/ +#define PragTyp_HEADER_VALUE 0 +#define PragTyp_AUTO_VACUUM 1 +#define PragTyp_FLAG 2 +#define PragTyp_BUSY_TIMEOUT 3 +#define PragTyp_CACHE_SIZE 4 +#define PragTyp_CASE_SENSITIVE_LIKE 5 +#define PragTyp_COLLATION_LIST 6 +#define PragTyp_COMPILE_OPTIONS 7 +#define PragTyp_DATA_STORE_DIRECTORY 8 +#define PragTyp_DATABASE_LIST 9 +#define PragTyp_DEFAULT_CACHE_SIZE 10 +#define PragTyp_ENCODING 11 +#define PragTyp_FOREIGN_KEY_CHECK 12 +#define PragTyp_FOREIGN_KEY_LIST 13 +#define PragTyp_INCREMENTAL_VACUUM 14 +#define PragTyp_INDEX_INFO 15 +#define PragTyp_INDEX_LIST 16 +#define PragTyp_INTEGRITY_CHECK 17 +#define PragTyp_JOURNAL_MODE 18 +#define PragTyp_JOURNAL_SIZE_LIMIT 19 +#define PragTyp_LOCK_PROXY_FILE 20 +#define PragTyp_LOCKING_MODE 21 +#define PragTyp_PAGE_COUNT 22 +#define PragTyp_MMAP_SIZE 23 +#define PragTyp_PAGE_SIZE 24 +#define PragTyp_SECURE_DELETE 25 +#define PragTyp_SHRINK_MEMORY 26 +#define PragTyp_SOFT_HEAP_LIMIT 27 +#define PragTyp_STATS 28 +#define PragTyp_SYNCHRONOUS 29 +#define PragTyp_TABLE_INFO 30 +#define PragTyp_TEMP_STORE 31 +#define PragTyp_TEMP_STORE_DIRECTORY 32 +#define PragTyp_WAL_AUTOCHECKPOINT 33 +#define PragTyp_WAL_CHECKPOINT 34 +#define PragTyp_ACTIVATE_EXTENSIONS 35 +#define PragTyp_HEXKEY 36 +#define PragTyp_KEY 37 +#define PragTyp_REKEY 38 +#define PragTyp_LOCK_STATUS 39 +#define PragTyp_PARSER_TRACE 40 +#define PragFlag_NeedSchema 0x01 +static const struct sPragmaNames { + const char *const zName; /* Name of pragma */ + u8 ePragTyp; /* PragTyp_XXX value */ + u8 mPragFlag; /* Zero or more PragFlag_XXX values */ + u32 iArg; /* Extra argument */ +} aPragmaNames[] = { +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) + { /* zName: */ "activate_extensions", + /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + { /* zName: */ "application_id", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_AUTOVACUUM) + { /* zName: */ "auto_vacuum", + /* ePragTyp: */ PragTyp_AUTO_VACUUM, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX) + { /* zName: */ "automatic_index", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_AutoIndex }, +#endif + { /* zName: */ "busy_timeout", + /* ePragTyp: */ PragTyp_BUSY_TIMEOUT, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "cache_size", + /* ePragTyp: */ PragTyp_CACHE_SIZE, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif + { /* zName: */ "cache_spill", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_CacheSpill }, + { /* zName: */ "case_sensitive_like", + /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "checkpoint_fullfsync", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_CkptFullFSync }, +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "collation_list", + /* ePragTyp: */ PragTyp_COLLATION_LIST, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS) + { /* zName: */ "compile_options", + /* ePragTyp: */ PragTyp_COMPILE_OPTIONS, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "count_changes", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_CountRows }, +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN + { /* zName: */ "data_store_directory", + /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "database_list", + /* ePragTyp: */ PragTyp_DATABASE_LIST, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) + { /* zName: */ "default_cache_size", + /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + { /* zName: */ "defer_foreign_keys", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_DeferFKs }, +#endif + { /* zName: */ "empty_result_callbacks", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_NullCallback }, +#if !defined(SQLITE_OMIT_UTF16) + { /* zName: */ "encoding", + /* ePragTyp: */ PragTyp_ENCODING, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + { /* zName: */ "foreign_key_check", + /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_FOREIGN_KEY) + { /* zName: */ "foreign_key_list", + /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + { /* zName: */ "foreign_keys", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_ForeignKeys }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + { /* zName: */ "freelist_count", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "full_column_names", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_FullColNames }, + { /* zName: */ "fullfsync", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_FullFSync }, +#if defined(SQLITE_HAS_CODEC) + { /* zName: */ "hexkey", + /* ePragTyp: */ PragTyp_HEXKEY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "hexrekey", + /* ePragTyp: */ PragTyp_HEXKEY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_CHECK) + { /* zName: */ "ignore_check_constraints", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_IgnoreChecks }, +#endif +#if !defined(SQLITE_OMIT_AUTOVACUUM) + { /* zName: */ "incremental_vacuum", + /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "index_info", + /* ePragTyp: */ PragTyp_INDEX_INFO, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, + { /* zName: */ "index_list", + /* ePragTyp: */ PragTyp_INDEX_LIST, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_INTEGRITY_CHECK) + { /* zName: */ "integrity_check", + /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "journal_mode", + /* ePragTyp: */ PragTyp_JOURNAL_MODE, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, + { /* zName: */ "journal_size_limit", + /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if defined(SQLITE_HAS_CODEC) + { /* zName: */ "key", + /* ePragTyp: */ PragTyp_KEY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "legacy_file_format", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_LegacyFileFmt }, +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE + { /* zName: */ "lock_proxy_file", + /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) + { /* zName: */ "lock_status", + /* ePragTyp: */ PragTyp_LOCK_STATUS, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "locking_mode", + /* ePragTyp: */ PragTyp_LOCKING_MODE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "max_page_count", + /* ePragTyp: */ PragTyp_PAGE_COUNT, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, + { /* zName: */ "mmap_size", + /* ePragTyp: */ PragTyp_MMAP_SIZE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "page_count", + /* ePragTyp: */ PragTyp_PAGE_COUNT, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, + { /* zName: */ "page_size", + /* ePragTyp: */ PragTyp_PAGE_SIZE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if defined(SQLITE_DEBUG) + { /* zName: */ "parser_trace", + /* ePragTyp: */ PragTyp_PARSER_TRACE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "query_only", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_QueryOnly }, +#if !defined(SQLITE_OMIT_INTEGRITY_CHECK) + { /* zName: */ "quick_check", + /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif + { /* zName: */ "read_uncommitted", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_ReadUncommitted }, + { /* zName: */ "recursive_triggers", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_RecTriggers }, +#if defined(SQLITE_HAS_CODEC) + { /* zName: */ "rekey", + /* ePragTyp: */ PragTyp_REKEY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "reverse_unordered_selects", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_ReverseOrder }, +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + { /* zName: */ "schema_version", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "secure_delete", + /* ePragTyp: */ PragTyp_SECURE_DELETE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif + { /* zName: */ "short_column_names", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_ShortColNames }, + { /* zName: */ "shrink_memory", + /* ePragTyp: */ PragTyp_SHRINK_MEMORY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "soft_heap_limit", + /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#if defined(SQLITE_DEBUG) + { /* zName: */ "sql_trace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_SqlTrace }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "stats", + /* ePragTyp: */ PragTyp_STATS, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "synchronous", + /* ePragTyp: */ PragTyp_SYNCHRONOUS, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + { /* zName: */ "table_info", + /* ePragTyp: */ PragTyp_TABLE_INFO, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + { /* zName: */ "temp_store", + /* ePragTyp: */ PragTyp_TEMP_STORE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "temp_store_directory", + /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + { /* zName: */ "user_version", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, +#endif +#if defined(SQLITE_DEBUG) + { /* zName: */ "vdbe_addoptrace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_VdbeAddopTrace }, + { /* zName: */ "vdbe_debug", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace }, + { /* zName: */ "vdbe_listing", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_VdbeListing }, + { /* zName: */ "vdbe_trace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_VdbeTrace }, +#endif +#if !defined(SQLITE_OMIT_WAL) + { /* zName: */ "wal_autocheckpoint", + /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT, + /* ePragFlag: */ 0, + /* iArg: */ 0 }, + { /* zName: */ "wal_checkpoint", + /* ePragTyp: */ PragTyp_WAL_CHECKPOINT, + /* ePragFlag: */ PragFlag_NeedSchema, + /* iArg: */ 0 }, +#endif + { /* zName: */ "writable_schema", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlag: */ 0, + /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode }, +}; +/* Number of pragmas: 56 on by default, 68 total. */ +/* End of the automatically generated pragma table. +***************************************************************************/ + +/* +** Interpret the given string as a safety level. Return 0 for OFF, +** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or +** unrecognized string argument. The FULL option is disallowed +** if the omitFull parameter it 1. +** +** Note that the values returned are one less that the values that +** should be passed into sqlite3BtreeSetSafetyLevel(). The is done +** to support legacy SQL code. The safety level used to be boolean +** and older scripts may have used numbers 0 for OFF and 1 for ON. +*/ +static u8 getSafetyLevel(const char *z, int omitFull, int dflt){ + /* 123456789 123456789 */ + static const char zText[] = "onoffalseyestruefull"; + static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16}; + static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4}; + static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2}; + int i, n; + if( sqlite3Isdigit(*z) ){ + return (u8)sqlite3Atoi(z); + } + n = sqlite3Strlen30(z); + for(i=0; i=0&&i<=2)?i:0); +} +#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */ + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* +** Interpret the given string as a temp db location. Return 1 for file +** backed temporary databases, 2 for the Red-Black tree in memory database +** and 0 to use the compile-time default. +*/ +static int getTempStore(const char *z){ + if( z[0]>='0' && z[0]<='2' ){ + return z[0] - '0'; + }else if( sqlite3StrICmp(z, "file")==0 ){ + return 1; + }else if( sqlite3StrICmp(z, "memory")==0 ){ + return 2; + }else{ + return 0; + } +} +#endif /* SQLITE_PAGER_PRAGMAS */ + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* +** Invalidate temp storage, either when the temp storage is changed +** from default, or when 'file' and the temp_store_directory has changed +*/ +static int invalidateTempStorage(Parse *pParse){ + sqlite3 *db = pParse->db; + if( db->aDb[1].pBt!=0 ){ + if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){ + sqlite3ErrorMsg(pParse, "temporary storage cannot be changed " + "from within a transaction"); + return SQLITE_ERROR; + } + sqlite3BtreeClose(db->aDb[1].pBt); + db->aDb[1].pBt = 0; + sqlite3ResetAllSchemasOfConnection(db); + } + return SQLITE_OK; +} +#endif /* SQLITE_PAGER_PRAGMAS */ + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* +** If the TEMP database is open, close it and mark the database schema +** as needing reloading. This must be done when using the SQLITE_TEMP_STORE +** or DEFAULT_TEMP_STORE pragmas. +*/ +static int changeTempStorage(Parse *pParse, const char *zStorageType){ + int ts = getTempStore(zStorageType); + sqlite3 *db = pParse->db; + if( db->temp_store==ts ) return SQLITE_OK; + if( invalidateTempStorage( pParse ) != SQLITE_OK ){ + return SQLITE_ERROR; + } + db->temp_store = (u8)ts; + return SQLITE_OK; +} +#endif /* SQLITE_PAGER_PRAGMAS */ + +/* +** Generate code to return a single integer value. +*/ +static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){ + Vdbe *v = sqlite3GetVdbe(pParse); + int mem = ++pParse->nMem; + i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value)); + if( pI64 ){ + memcpy(pI64, &value, sizeof(value)); + } + sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC); + sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1); +} + + +/* +** Set the safety_level and pager flags for pager iDb. Or if iDb<0 +** set these values for all pagers. +*/ +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +static void setAllPagerFlags(sqlite3 *db){ + if( db->autoCommit ){ + Db *pDb = db->aDb; + int n = db->nDb; + assert( SQLITE_FullFSync==PAGER_FULLFSYNC ); + assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC ); + assert( SQLITE_CacheSpill==PAGER_CACHESPILL ); + assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL) + == PAGER_FLAGS_MASK ); + assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level ); + while( (n--) > 0 ){ + if( pDb->pBt ){ + sqlite3BtreeSetPagerFlags(pDb->pBt, + pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) ); + } + pDb++; + } + } +} +#else +# define setAllPagerFlags(X) /* no-op */ +#endif + + +/* +** Return a human-readable name for a constraint resolution action. +*/ +#ifndef SQLITE_OMIT_FOREIGN_KEY +static const char *actionName(u8 action){ + const char *zName; + switch( action ){ + case OE_SetNull: zName = "SET NULL"; break; + case OE_SetDflt: zName = "SET DEFAULT"; break; + case OE_Cascade: zName = "CASCADE"; break; + case OE_Restrict: zName = "RESTRICT"; break; + default: zName = "NO ACTION"; + assert( action==OE_None ); break; + } + return zName; +} +#endif + + +/* +** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants +** defined in pager.h. This function returns the associated lowercase +** journal-mode name. +*/ +const char *sqlite3JournalModename(int eMode){ + static char * const azModeName[] = { + "delete", "persist", "off", "truncate", "memory" +#ifndef SQLITE_OMIT_WAL + , "wal" +#endif + }; + assert( PAGER_JOURNALMODE_DELETE==0 ); + assert( PAGER_JOURNALMODE_PERSIST==1 ); + assert( PAGER_JOURNALMODE_OFF==2 ); + assert( PAGER_JOURNALMODE_TRUNCATE==3 ); + assert( PAGER_JOURNALMODE_MEMORY==4 ); + assert( PAGER_JOURNALMODE_WAL==5 ); + assert( eMode>=0 && eMode<=ArraySize(azModeName) ); + + if( eMode==ArraySize(azModeName) ) return 0; + return azModeName[eMode]; +} + +/* +** Process a pragma statement. +** +** Pragmas are of this form: +** +** PRAGMA [database.]id [= value] +** +** The identifier might also be a string. The value is a string, and +** identifier, or a number. If minusFlag is true, then the value is +** a number that was preceded by a minus sign. +** +** If the left side is "database.id" then pId1 is the database name +** and pId2 is the id. If the left side is just "id" then pId1 is the +** id and pId2 is any empty string. +*/ +void sqlite3Pragma( + Parse *pParse, + Token *pId1, /* First part of [database.]id field */ + Token *pId2, /* Second part of [database.]id field, or NULL */ + Token *pValue, /* Token for , or NULL */ + int minusFlag /* True if a '-' sign preceded */ +){ + char *zLeft = 0; /* Nul-terminated UTF-8 string */ + char *zRight = 0; /* Nul-terminated UTF-8 string , or NULL */ + const char *zDb = 0; /* The database name */ + Token *pId; /* Pointer to token */ + char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */ + int iDb; /* Database index for */ + int lwr, upr, mid; /* Binary search bounds */ + int rc; /* return value form SQLITE_FCNTL_PRAGMA */ + sqlite3 *db = pParse->db; /* The database connection */ + Db *pDb; /* The specific database being pragmaed */ + Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */ + + if( v==0 ) return; + sqlite3VdbeRunOnlyOnce(v); + pParse->nMem = 2; + + /* Interpret the [database.] part of the pragma statement. iDb is the + ** index of the database this pragma is being applied to in db.aDb[]. */ + iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); + if( iDb<0 ) return; + pDb = &db->aDb[iDb]; + + /* If the temp database has been explicitly named as part of the + ** pragma, make sure it is open. + */ + if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ + return; + } + + zLeft = sqlite3NameFromToken(db, pId); + if( !zLeft ) return; + if( minusFlag ){ + zRight = sqlite3MPrintf(db, "-%T", pValue); + }else{ + zRight = sqlite3NameFromToken(db, pValue); + } + + assert( pId2 ); + zDb = pId2->n>0 ? pDb->zName : 0; + if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ + goto pragma_out; + } + + /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS + ** connection. If it returns SQLITE_OK, then assume that the VFS + ** handled the pragma and generate a no-op prepared statement. + */ + aFcntl[0] = 0; + aFcntl[1] = zLeft; + aFcntl[2] = zRight; + aFcntl[3] = 0; + db->busyHandler.nBusy = 0; + rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); + if( rc==SQLITE_OK ){ + if( aFcntl[0] ){ + int mem = ++pParse->nMem; + sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC); + sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1); + sqlite3_free(aFcntl[0]); + } + goto pragma_out; + } + if( rc!=SQLITE_NOTFOUND ){ + if( aFcntl[0] ){ + sqlite3ErrorMsg(pParse, "%s", aFcntl[0]); + sqlite3_free(aFcntl[0]); + } + pParse->nErr++; + pParse->rc = rc; + goto pragma_out; + } + + /* Locate the pragma in the lookup table */ + lwr = 0; + upr = ArraySize(aPragmaNames)-1; + while( lwr<=upr ){ + mid = (lwr+upr)/2; + rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName); + if( rc==0 ) break; + if( rc<0 ){ + upr = mid - 1; + }else{ + lwr = mid + 1; + } + } + if( lwr>upr ) goto pragma_out; + + /* Make sure the database schema is loaded if the pragma requires that */ + if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){ + if( sqlite3ReadSchema(pParse) ) goto pragma_out; + } + + /* Jump to the appropriate pragma handler */ + switch( aPragmaNames[mid].ePragTyp ){ + +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) + /* + ** PRAGMA [database.]default_cache_size + ** PRAGMA [database.]default_cache_size=N + ** + ** The first form reports the current persistent setting for the + ** page cache size. The value returned is the maximum number of + ** pages in the page cache. The second form sets both the current + ** page cache size value and the persistent page cache size value + ** stored in the database file. + ** + ** Older versions of SQLite would set the default cache size to a + ** negative number to indicate synchronous=OFF. These days, synchronous + ** is always on by default regardless of the sign of the default cache + ** size. But continue to take the absolute value of the default cache + ** size of historical compatibility. + */ + case PragTyp_DEFAULT_CACHE_SIZE: { + static const VdbeOpList getCacheSize[] = { + { OP_Transaction, 0, 0, 0}, /* 0 */ + { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */ + { OP_IfPos, 1, 8, 0}, + { OP_Integer, 0, 2, 0}, + { OP_Subtract, 1, 2, 1}, + { OP_IfPos, 1, 8, 0}, + { OP_Integer, 0, 1, 0}, /* 6 */ + { OP_Noop, 0, 0, 0}, + { OP_ResultRow, 1, 1, 0}, + }; + int addr; + sqlite3VdbeUsesBtree(v, iDb); + if( !zRight ){ + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC); + pParse->nMem += 2; + addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize); + sqlite3VdbeChangeP1(v, addr, iDb); + sqlite3VdbeChangeP1(v, addr+1, iDb); + sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE); + }else{ + int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3VdbeAddOp2(v, OP_Integer, size, 1); + sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1); + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pDb->pSchema->cache_size = size; + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); + } + break; + } +#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */ + +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + /* + ** PRAGMA [database.]page_size + ** PRAGMA [database.]page_size=N + ** + ** The first form reports the current setting for the + ** database page size in bytes. The second form sets the + ** database page size value. The value can only be set if + ** the database has not yet been created. + */ + case PragTyp_PAGE_SIZE: { + Btree *pBt = pDb->pBt; + assert( pBt!=0 ); + if( !zRight ){ + int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; + returnSingleInt(pParse, "page_size", size); + }else{ + /* Malloc may fail when setting the page-size, as there is an internal + ** buffer that the pager module resizes using sqlite3_realloc(). + */ + db->nextPagesize = sqlite3Atoi(zRight); + if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ + db->mallocFailed = 1; + } + } + break; + } + + /* + ** PRAGMA [database.]secure_delete + ** PRAGMA [database.]secure_delete=ON/OFF + ** + ** The first form reports the current setting for the + ** secure_delete flag. The second form changes the secure_delete + ** flag setting and reports thenew value. + */ + case PragTyp_SECURE_DELETE: { + Btree *pBt = pDb->pBt; + int b = -1; + assert( pBt!=0 ); + if( zRight ){ + b = sqlite3GetBoolean(zRight, 0); + } + if( pId2->n==0 && b>=0 ){ + int ii; + for(ii=0; iinDb; ii++){ + sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); + } + } + b = sqlite3BtreeSecureDelete(pBt, b); + returnSingleInt(pParse, "secure_delete", b); + break; + } + + /* + ** PRAGMA [database.]max_page_count + ** PRAGMA [database.]max_page_count=N + ** + ** The first form reports the current setting for the + ** maximum number of pages in the database file. The + ** second form attempts to change this setting. Both + ** forms return the current setting. + ** + ** The absolute value of N is used. This is undocumented and might + ** change. The only purpose is to provide an easy way to test + ** the sqlite3AbsInt32() function. + ** + ** PRAGMA [database.]page_count + ** + ** Return the number of pages in the specified database. + */ + case PragTyp_PAGE_COUNT: { + int iReg; + sqlite3CodeVerifySchema(pParse, iDb); + iReg = ++pParse->nMem; + if( sqlite3Tolower(zLeft[0])=='p' ){ + sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); + }else{ + sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, + sqlite3AbsInt32(sqlite3Atoi(zRight))); + } + sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT); + break; + } + + /* + ** PRAGMA [database.]locking_mode + ** PRAGMA [database.]locking_mode = (normal|exclusive) + */ + case PragTyp_LOCKING_MODE: { + const char *zRet = "normal"; + int eMode = getLockingMode(zRight); + + if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){ + /* Simple "PRAGMA locking_mode;" statement. This is a query for + ** the current default locking mode (which may be different to + ** the locking-mode of the main database). + */ + eMode = db->dfltLockMode; + }else{ + Pager *pPager; + if( pId2->n==0 ){ + /* This indicates that no database name was specified as part + ** of the PRAGMA command. In this case the locking-mode must be + ** set on all attached databases, as well as the main db file. + ** + ** Also, the sqlite3.dfltLockMode variable is set so that + ** any subsequently attached databases also use the specified + ** locking mode. + */ + int ii; + assert(pDb==&db->aDb[0]); + for(ii=2; iinDb; ii++){ + pPager = sqlite3BtreePager(db->aDb[ii].pBt); + sqlite3PagerLockingMode(pPager, eMode); + } + db->dfltLockMode = (u8)eMode; + } + pPager = sqlite3BtreePager(pDb->pBt); + eMode = sqlite3PagerLockingMode(pPager, eMode); + } + + assert( eMode==PAGER_LOCKINGMODE_NORMAL + || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); + if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ + zRet = "exclusive"; + } + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + break; + } + + /* + ** PRAGMA [database.]journal_mode + ** PRAGMA [database.]journal_mode = + ** (delete|persist|off|truncate|memory|wal|off) + */ + case PragTyp_JOURNAL_MODE: { + int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */ + int ii; /* Loop counter */ + + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC); + + if( zRight==0 ){ + /* If there is no "=MODE" part of the pragma, do a query for the + ** current mode */ + eMode = PAGER_JOURNALMODE_QUERY; + }else{ + const char *zMode; + int n = sqlite3Strlen30(zRight); + for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ + if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; + } + if( !zMode ){ + /* If the "=MODE" part does not match any known journal mode, + ** then do a query */ + eMode = PAGER_JOURNALMODE_QUERY; + } + } + if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ + /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */ + iDb = 0; + pId2->n = 1; + } + for(ii=db->nDb-1; ii>=0; ii--){ + if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ + sqlite3VdbeUsesBtree(v, ii); + sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); + } + } + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + break; + } + + /* + ** PRAGMA [database.]journal_size_limit + ** PRAGMA [database.]journal_size_limit=N + ** + ** Get or set the size limit on rollback journal files. + */ + case PragTyp_JOURNAL_SIZE_LIMIT: { + Pager *pPager = sqlite3BtreePager(pDb->pBt); + i64 iLimit = -2; + if( zRight ){ + sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8); + if( iLimit<-1 ) iLimit = -1; + } + iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); + returnSingleInt(pParse, "journal_size_limit", iLimit); + break; + } + +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */ + + /* + ** PRAGMA [database.]auto_vacuum + ** PRAGMA [database.]auto_vacuum=N + ** + ** Get or set the value of the database 'auto-vacuum' parameter. + ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL + */ +#ifndef SQLITE_OMIT_AUTOVACUUM + case PragTyp_AUTO_VACUUM: { + Btree *pBt = pDb->pBt; + assert( pBt!=0 ); + if( !zRight ){ + returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt)); + }else{ + int eAuto = getAutoVacuum(zRight); + assert( eAuto>=0 && eAuto<=2 ); + db->nextAutovac = (u8)eAuto; + /* Call SetAutoVacuum() to set initialize the internal auto and + ** incr-vacuum flags. This is required in case this connection + ** creates the database file. It is important that it is created + ** as an auto-vacuum capable db. + */ + rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); + if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ + /* When setting the auto_vacuum mode to either "full" or + ** "incremental", write the value of meta[6] in the database + ** file. Before writing to meta[6], check that meta[3] indicates + ** that this really is an auto-vacuum capable database. + */ + static const VdbeOpList setMeta6[] = { + { OP_Transaction, 0, 1, 0}, /* 0 */ + { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE}, + { OP_If, 1, 0, 0}, /* 2 */ + { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */ + { OP_Integer, 0, 1, 0}, /* 4 */ + { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */ + }; + int iAddr; + iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6); + sqlite3VdbeChangeP1(v, iAddr, iDb); + sqlite3VdbeChangeP1(v, iAddr+1, iDb); + sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4); + sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1); + sqlite3VdbeChangeP1(v, iAddr+5, iDb); + sqlite3VdbeUsesBtree(v, iDb); + } + } + break; + } +#endif + + /* + ** PRAGMA [database.]incremental_vacuum(N) + ** + ** Do N steps of incremental vacuuming on a database. + */ +#ifndef SQLITE_OMIT_AUTOVACUUM + case PragTyp_INCREMENTAL_VACUUM: { + int iLimit, addr; + if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ + iLimit = 0x7fffffff; + } + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); + addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); + sqlite3VdbeAddOp1(v, OP_ResultRow, 1); + sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); + sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); + sqlite3VdbeJumpHere(v, addr); + break; + } +#endif + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS + /* + ** PRAGMA [database.]cache_size + ** PRAGMA [database.]cache_size=N + ** + ** The first form reports the current local setting for the + ** page cache size. The second form sets the local + ** page cache size value. If N is positive then that is the + ** number of pages in the cache. If N is negative, then the + ** number of pages is adjusted so that the cache uses -N kibibytes + ** of memory. + */ + case PragTyp_CACHE_SIZE: { + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( !zRight ){ + returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size); + }else{ + int size = sqlite3Atoi(zRight); + pDb->pSchema->cache_size = size; + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); + } + break; + } + + /* + ** PRAGMA [database.]mmap_size(N) + ** + ** Used to set mapping size limit. The mapping size limit is + ** used to limit the aggregate size of all memory mapped regions of the + ** database file. If this parameter is set to zero, then memory mapping + ** is not used at all. If N is negative, then the default memory map + ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. + ** The parameter N is measured in bytes. + ** + ** This value is advisory. The underlying VFS is free to memory map + ** as little or as much as it wants. Except, if N is set to 0 then the + ** upper layers will never invoke the xFetch interfaces to the VFS. + */ + case PragTyp_MMAP_SIZE: { + sqlite3_int64 sz; +#if SQLITE_MAX_MMAP_SIZE>0 + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( zRight ){ + int ii; + sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8); + if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; + if( pId2->n==0 ) db->szMmap = sz; + for(ii=db->nDb-1; ii>=0; ii--){ + if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ + sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); + } + } + } + sz = -1; + rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); +#else + sz = 0; + rc = SQLITE_OK; +#endif + if( rc==SQLITE_OK ){ + returnSingleInt(pParse, "mmap_size", sz); + }else if( rc!=SQLITE_NOTFOUND ){ + pParse->nErr++; + pParse->rc = rc; + } + break; + } + + /* + ** PRAGMA temp_store + ** PRAGMA temp_store = "default"|"memory"|"file" + ** + ** Return or set the local value of the temp_store flag. Changing + ** the local value does not make changes to the disk file and the default + ** value will be restored the next time the database is opened. + ** + ** Note that it is possible for the library compile-time options to + ** override this setting + */ + case PragTyp_TEMP_STORE: { + if( !zRight ){ + returnSingleInt(pParse, "temp_store", db->temp_store); + }else{ + changeTempStorage(pParse, zRight); + } + break; + } + + /* + ** PRAGMA temp_store_directory + ** PRAGMA temp_store_directory = ""|"directory_name" + ** + ** Return or set the local value of the temp_store_directory flag. Changing + ** the value sets a specific directory to be used for temporary files. + ** Setting to a null string reverts to the default temporary directory search. + ** If temporary directory is changed, then invalidateTempStorage. + ** + */ + case PragTyp_TEMP_STORE_DIRECTORY: { + if( !zRight ){ + if( sqlite3_temp_directory ){ + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, + "temp_store_directory", SQLITE_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } + }else{ +#ifndef SQLITE_OMIT_WSD + if( zRight[0] ){ + int res; + rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); + if( rc!=SQLITE_OK || res==0 ){ + sqlite3ErrorMsg(pParse, "not a writable directory"); + goto pragma_out; + } + } + if( SQLITE_TEMP_STORE==0 + || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) + || (SQLITE_TEMP_STORE==2 && db->temp_store==1) + ){ + invalidateTempStorage(pParse); + } + sqlite3_free(sqlite3_temp_directory); + if( zRight[0] ){ + sqlite3_temp_directory = sqlite3_mprintf("%s", zRight); + }else{ + sqlite3_temp_directory = 0; + } +#endif /* SQLITE_OMIT_WSD */ + } + break; + } + +#if SQLITE_OS_WIN + /* + ** PRAGMA data_store_directory + ** PRAGMA data_store_directory = ""|"directory_name" + ** + ** Return or set the local value of the data_store_directory flag. Changing + ** the value sets a specific directory to be used for database files that + ** were specified with a relative pathname. Setting to a null string reverts + ** to the default database directory, which for database files specified with + ** a relative path will probably be based on the current directory for the + ** process. Database file specified with an absolute path are not impacted + ** by this setting, regardless of its value. + ** + */ + case PragTyp_DATA_STORE_DIRECTORY: { + if( !zRight ){ + if( sqlite3_data_directory ){ + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, + "data_store_directory", SQLITE_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } + }else{ +#ifndef SQLITE_OMIT_WSD + if( zRight[0] ){ + int res; + rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); + if( rc!=SQLITE_OK || res==0 ){ + sqlite3ErrorMsg(pParse, "not a writable directory"); + goto pragma_out; + } + } + sqlite3_free(sqlite3_data_directory); + if( zRight[0] ){ + sqlite3_data_directory = sqlite3_mprintf("%s", zRight); + }else{ + sqlite3_data_directory = 0; + } +#endif /* SQLITE_OMIT_WSD */ + } + break; + } +#endif + +#if SQLITE_ENABLE_LOCKING_STYLE + /* + ** PRAGMA [database.]lock_proxy_file + ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path" + ** + ** Return or set the value of the lock_proxy_file flag. Changing + ** the value sets a specific file to be used for database access locks. + ** + */ + case PragTyp_LOCK_PROXY_FILE: { + if( !zRight ){ + Pager *pPager = sqlite3BtreePager(pDb->pBt); + char *proxy_file_path = NULL; + sqlite3_file *pFile = sqlite3PagerFile(pPager); + sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, + &proxy_file_path); + + if( proxy_file_path ){ + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, + "lock_proxy_file", SQLITE_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } + }else{ + Pager *pPager = sqlite3BtreePager(pDb->pBt); + sqlite3_file *pFile = sqlite3PagerFile(pPager); + int res; + if( zRight[0] ){ + res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, + zRight); + } else { + res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, + NULL); + } + if( res!=SQLITE_OK ){ + sqlite3ErrorMsg(pParse, "failed to set lock proxy file"); + goto pragma_out; + } + } + break; + } +#endif /* SQLITE_ENABLE_LOCKING_STYLE */ + + /* + ** PRAGMA [database.]synchronous + ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL + ** + ** Return or set the local value of the synchronous flag. Changing + ** the local value does not make changes to the disk file and the + ** default value will be restored the next time the database is + ** opened. + */ + case PragTyp_SYNCHRONOUS: { + if( !zRight ){ + returnSingleInt(pParse, "synchronous", pDb->safety_level-1); + }else{ + if( !db->autoCommit ){ + sqlite3ErrorMsg(pParse, + "Safety level may not be changed inside a transaction"); + }else{ + pDb->safety_level = getSafetyLevel(zRight,0,1)+1; + setAllPagerFlags(db); + } + } + break; + } +#endif /* SQLITE_OMIT_PAGER_PRAGMAS */ + +#ifndef SQLITE_OMIT_FLAG_PRAGMAS + case PragTyp_FLAG: { + if( zRight==0 ){ + returnSingleInt(pParse, aPragmaNames[mid].zName, + (db->flags & aPragmaNames[mid].iArg)!=0 ); + }else{ + int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */ + if( db->autoCommit==0 ){ + /* Foreign key support may not be enabled or disabled while not + ** in auto-commit mode. */ + mask &= ~(SQLITE_ForeignKeys); + } + + if( sqlite3GetBoolean(zRight, 0) ){ + db->flags |= mask; + }else{ + db->flags &= ~mask; + if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; + } + + /* Many of the flag-pragmas modify the code generated by the SQL + ** compiler (eg. count_changes). So add an opcode to expire all + ** compiled SQL statements after modifying a pragma value. + */ + sqlite3VdbeAddOp2(v, OP_Expire, 0, 0); + setAllPagerFlags(db); + } + break; + } +#endif /* SQLITE_OMIT_FLAG_PRAGMAS */ + +#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS + /* + ** PRAGMA table_info(
  • ) + ** + ** Return a single row for each column of the named table. The columns of + ** the returned data set are: + ** + ** cid: Column id (numbered from left to right, starting at 0) + ** name: Column name + ** type: Column declaration type. + ** notnull: True if 'NOT NULL' is part of column declaration + ** dflt_value: The default value for the column, if any. + */ + case PragTyp_TABLE_INFO: if( zRight ){ + Table *pTab; + pTab = sqlite3FindTable(db, zRight, zDb); + if( pTab ){ + int i, k; + int nHidden = 0; + Column *pCol; + Index *pPk; + for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){} + sqlite3VdbeSetNumCols(v, 6); + pParse->nMem = 6; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC); + sqlite3ViewGetColumnNames(pParse, pTab); + for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ + if( IsHiddenColumn(pCol) ){ + nHidden++; + continue; + } + sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + pCol->zType ? pCol->zType : "", 0); + sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4); + if( pCol->zDflt ){ + sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0); + }else{ + sqlite3VdbeAddOp2(v, OP_Null, 0, 5); + } + if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ + k = 0; + }else if( pPk==0 ){ + k = 1; + }else{ + for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){} + } + sqlite3VdbeAddOp2(v, OP_Integer, k, 6); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6); + } + } + } + break; + + case PragTyp_STATS: { + Index *pIdx; + HashElem *i; + v = sqlite3GetVdbe(pParse); + sqlite3VdbeSetNumCols(v, 4); + pParse->nMem = 4; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC); + for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ + Table *pTab = sqliteHashData(i); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0); + sqlite3VdbeAddOp2(v, OP_Null, 0, 2); + sqlite3VdbeAddOp2(v, OP_Integer, + (int)sqlite3LogEstToInt(pTab->szTabRow), 3); + sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0); + sqlite3VdbeAddOp2(v, OP_Integer, + (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3); + sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); + } + } + } + break; + + case PragTyp_INDEX_INFO: if( zRight ){ + Index *pIdx; + Table *pTab; + pIdx = sqlite3FindIndex(db, zRight, zDb); + if( pIdx ){ + int i; + pTab = pIdx->pTable; + sqlite3VdbeSetNumCols(v, 3); + pParse->nMem = 3; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC); + for(i=0; inColumn; i++){ + int cnum = pIdx->aiColumn[i]; + sqlite3VdbeAddOp2(v, OP_Integer, i, 1); + sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2); + assert( pTab->nCol>cnum ); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + } + } + } + break; + + case PragTyp_INDEX_LIST: if( zRight ){ + Index *pIdx; + Table *pTab; + int i; + pTab = sqlite3FindTable(db, zRight, zDb); + if( pTab ){ + v = sqlite3GetVdbe(pParse); + sqlite3VdbeSetNumCols(v, 3); + pParse->nMem = 3; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC); + for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ + sqlite3VdbeAddOp2(v, OP_Integer, i, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0); + sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + } + } + } + break; + + case PragTyp_DATABASE_LIST: { + int i; + sqlite3VdbeSetNumCols(v, 3); + pParse->nMem = 3; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC); + for(i=0; inDb; i++){ + if( db->aDb[i].pBt==0 ) continue; + assert( db->aDb[i].zName!=0 ); + sqlite3VdbeAddOp2(v, OP_Integer, i, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + sqlite3BtreeGetFilename(db->aDb[i].pBt), 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + } + } + break; + + case PragTyp_COLLATION_LIST: { + int i = 0; + HashElem *p; + sqlite3VdbeSetNumCols(v, 2); + pParse->nMem = 2; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC); + for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ + CollSeq *pColl = (CollSeq *)sqliteHashData(p); + sqlite3VdbeAddOp2(v, OP_Integer, i++, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); + } + } + break; +#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */ + +#ifndef SQLITE_OMIT_FOREIGN_KEY + case PragTyp_FOREIGN_KEY_LIST: if( zRight ){ + FKey *pFK; + Table *pTab; + pTab = sqlite3FindTable(db, zRight, zDb); + if( pTab ){ + v = sqlite3GetVdbe(pParse); + pFK = pTab->pFKey; + if( pFK ){ + int i = 0; + sqlite3VdbeSetNumCols(v, 8); + pParse->nMem = 8; + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC); + while(pFK){ + int j; + for(j=0; jnCol; j++){ + char *zCol = pFK->aCol[j].zCol; + char *zOnDelete = (char *)actionName(pFK->aAction[0]); + char *zOnUpdate = (char *)actionName(pFK->aAction[1]); + sqlite3VdbeAddOp2(v, OP_Integer, i, 1); + sqlite3VdbeAddOp2(v, OP_Integer, j, 2); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, + pTab->aCol[pFK->aCol[j].iFrom].zName, 0); + sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8); + } + ++i; + pFK = pFK->pNextFrom; + } + } + } + } + break; +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ + +#ifndef SQLITE_OMIT_FOREIGN_KEY +#ifndef SQLITE_OMIT_TRIGGER + case PragTyp_FOREIGN_KEY_CHECK: { + FKey *pFK; /* A foreign key constraint */ + Table *pTab; /* Child table contain "REFERENCES" keyword */ + Table *pParent; /* Parent table that child points to */ + Index *pIdx; /* Index in the parent table */ + int i; /* Loop counter: Foreign key number for pTab */ + int j; /* Loop counter: Field of the foreign key */ + HashElem *k; /* Loop counter: Next table in schema */ + int x; /* result variable */ + int regResult; /* 3 registers to hold a result row */ + int regKey; /* Register to hold key for checking the FK */ + int regRow; /* Registers to hold a row from pTab */ + int addrTop; /* Top of a loop checking foreign keys */ + int addrOk; /* Jump here if the key is OK */ + int *aiCols; /* child to parent column mapping */ + + regResult = pParse->nMem+1; + pParse->nMem += 4; + regKey = ++pParse->nMem; + regRow = ++pParse->nMem; + v = sqlite3GetVdbe(pParse); + sqlite3VdbeSetNumCols(v, 4); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC); + sqlite3CodeVerifySchema(pParse, iDb); + k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); + while( k ){ + if( zRight ){ + pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); + k = 0; + }else{ + pTab = (Table*)sqliteHashData(k); + k = sqliteHashNext(k); + } + if( pTab==0 || pTab->pFKey==0 ) continue; + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; + sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead); + sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName, + P4_TRANSIENT); + for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ + pParent = sqlite3FindTable(db, pFK->zTo, zDb); + if( pParent==0 ) continue; + pIdx = 0; + sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName); + x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); + if( x==0 ){ + if( pIdx==0 ){ + sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead); + }else{ + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb); + sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF); + } + }else{ + k = 0; + break; + } + } + assert( pParse->nErr>0 || pFK==0 ); + if( pFK ) break; + if( pParse->nTabnTab = i; + addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); + for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ + pParent = sqlite3FindTable(db, pFK->zTo, zDb); + pIdx = 0; + aiCols = 0; + if( pParent ){ + x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); + assert( x==0 ); + } + addrOk = sqlite3VdbeMakeLabel(v); + if( pParent && pIdx==0 ){ + int iKey = pFK->aCol[0].iFrom; + assert( iKey>=0 && iKeynCol ); + if( iKey!=pTab->iPKey ){ + sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow); + sqlite3ColumnDefault(v, pTab, iKey, regRow); + sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); + sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow, + sqlite3VdbeCurrentAddr(v)+3); + }else{ + sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow); + } + sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk); + sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); + }else{ + for(j=0; jnCol; j++){ + sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, + aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j); + sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); + } + if( pParent ){ + sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey); + sqlite3VdbeChangeP4(v, -1, + sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT); + sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); + } + } + sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); + sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0, + pFK->zTo, P4_TRANSIENT); + sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3); + sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); + sqlite3VdbeResolveLabel(v, addrOk); + sqlite3DbFree(db, aiCols); + } + sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); + sqlite3VdbeJumpHere(v, addrTop); + } + } + break; +#endif /* !defined(SQLITE_OMIT_TRIGGER) */ +#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ + +#ifndef NDEBUG + case PragTyp_PARSER_TRACE: { + if( zRight ){ + if( sqlite3GetBoolean(zRight, 0) ){ + sqlite3ParserTrace(stderr, "parser: "); + }else{ + sqlite3ParserTrace(0, 0); + } + } + } + break; +#endif + + /* Reinstall the LIKE and GLOB functions. The variant of LIKE + ** used will be case sensitive or not depending on the RHS. + */ + case PragTyp_CASE_SENSITIVE_LIKE: { + if( zRight ){ + sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); + } + } + break; + +#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX +# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 +#endif + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK + /* Pragma "quick_check" is reduced version of + ** integrity_check designed to detect most database corruption + ** without most of the overhead of a full integrity-check. + */ + case PragTyp_INTEGRITY_CHECK: { + int i, j, addr, mxErr; + + /* Code that appears at the end of the integrity check. If no error + ** messages have been generated, output OK. Otherwise output the + ** error message + */ + static const VdbeOpList endCode[] = { + { OP_AddImm, 1, 0, 0}, /* 0 */ + { OP_IfNeg, 1, 0, 0}, /* 1 */ + { OP_String8, 0, 3, 0}, /* 2 */ + { OP_ResultRow, 3, 1, 0}, + }; + + int isQuick = (sqlite3Tolower(zLeft[0])=='q'); + + /* If the PRAGMA command was of the form "PRAGMA .integrity_check", + ** then iDb is set to the index of the database identified by . + ** In this case, the integrity of database iDb only is verified by + ** the VDBE created below. + ** + ** Otherwise, if the command was simply "PRAGMA integrity_check" (or + ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb + ** to -1 here, to indicate that the VDBE should verify the integrity + ** of all attached databases. */ + assert( iDb>=0 ); + assert( iDb==0 || pId2->z ); + if( pId2->z==0 ) iDb = -1; + + /* Initialize the VDBE program */ + pParse->nMem = 6; + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC); + + /* Set the maximum error count */ + mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; + if( zRight ){ + sqlite3GetInt32(zRight, &mxErr); + if( mxErr<=0 ){ + mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; + } + } + sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */ + + /* Do an integrity check on each database file */ + for(i=0; inDb; i++){ + HashElem *x; + Hash *pTbls; + int cnt = 0; + + if( OMIT_TEMPDB && i==1 ) continue; + if( iDb>=0 && i!=iDb ) continue; + + sqlite3CodeVerifySchema(pParse, i); + addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */ + sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); + sqlite3VdbeJumpHere(v, addr); + + /* Do an integrity check of the B-Tree + ** + ** Begin by filling registers 2, 3, ... with the root pages numbers + ** for all tables and indices in the database. + */ + assert( sqlite3SchemaMutexHeld(db, i, 0) ); + pTbls = &db->aDb[i].pSchema->tblHash; + for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ + Table *pTab = sqliteHashData(x); + Index *pIdx; + sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt); + cnt++; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt); + cnt++; + } + } + + /* Make sure sufficient number of registers have been allocated */ + pParse->nMem = MAX( pParse->nMem, cnt+7 ); + + /* Do the b-tree integrity checks */ + sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1); + sqlite3VdbeChangeP5(v, (u8)i); + addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName), + P4_DYNAMIC); + sqlite3VdbeAddOp2(v, OP_Move, 2, 4); + sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2); + sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1); + sqlite3VdbeJumpHere(v, addr); + + /* Make sure all the indices are constructed correctly. + */ + for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){ + Table *pTab = sqliteHashData(x); + Index *pIdx; + int loopTop; + + if( pTab->pIndex==0 ) continue; + addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */ + sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); + sqlite3VdbeJumpHere(v, addr); + sqlite3ExprCacheClear(pParse); + sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead); + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */ + } + pParse->nMem = MAX(pParse->nMem, 7+j); + loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1; + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + int jmp2, jmp3; + int r1; + static const VdbeOpList idxErr[] = { + { OP_AddImm, 1, -1, 0}, + { OP_String8, 0, 3, 0}, /* 1 */ + { OP_Rowid, 1, 4, 0}, + { OP_String8, 0, 5, 0}, /* 3 */ + { OP_String8, 0, 6, 0}, /* 4 */ + { OP_Concat, 4, 3, 3}, + { OP_Concat, 5, 3, 3}, + { OP_Concat, 6, 3, 3}, + { OP_ResultRow, 3, 1, 0}, + { OP_IfPos, 1, 0, 0}, /* 9 */ + { OP_Halt, 0, 0, 0}, + }; + r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3); + sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1); /* increment entry count */ + jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1); + addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr); + sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC); + sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC); + sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT); + sqlite3VdbeJumpHere(v, addr+9); + sqlite3VdbeJumpHere(v, jmp2); + sqlite3VdbeResolveLabel(v, jmp3); + } + sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop); + sqlite3VdbeJumpHere(v, loopTop-1); +#ifndef SQLITE_OMIT_BTREECOUNT + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, + "wrong # of entries in index ", P4_STATIC); + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + addr = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); + sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); + sqlite3VdbeAddOp2(v, OP_Count, j+2, 3); + sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3); + sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT); + sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7); + sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1); + } +#endif /* SQLITE_OMIT_BTREECOUNT */ + } + } + addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode); + sqlite3VdbeChangeP2(v, addr, -mxErr); + sqlite3VdbeJumpHere(v, addr+1); + sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC); + } + break; +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +#ifndef SQLITE_OMIT_UTF16 + /* + ** PRAGMA encoding + ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" + ** + ** In its first form, this pragma returns the encoding of the main + ** database. If the database is not initialized, it is initialized now. + ** + ** The second form of this pragma is a no-op if the main database file + ** has not already been initialized. In this case it sets the default + ** encoding that will be used for the main database file if a new file + ** is created. If an existing main database file is opened, then the + ** default text encoding for the existing database is used. + ** + ** In all cases new databases created using the ATTACH command are + ** created to use the same default text encoding as the main database. If + ** the main database has not been initialized and/or created when ATTACH + ** is executed, this is done before the ATTACH operation. + ** + ** In the second form this pragma sets the text encoding to be used in + ** new database files created using this database handle. It is only + ** useful if invoked immediately after the main database i + */ + case PragTyp_ENCODING: { + static const struct EncName { + char *zName; + u8 enc; + } encnames[] = { + { "UTF8", SQLITE_UTF8 }, + { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */ + { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */ + { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */ + { "UTF16le", SQLITE_UTF16LE }, + { "UTF16be", SQLITE_UTF16BE }, + { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */ + { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */ + { 0, 0 } + }; + const struct EncName *pEnc; + if( !zRight ){ /* "PRAGMA encoding" */ + if( sqlite3ReadSchema(pParse) ) goto pragma_out; + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC); + sqlite3VdbeAddOp2(v, OP_String8, 0, 1); + assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); + assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); + assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); + sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + }else{ /* "PRAGMA encoding = XXX" */ + /* Only change the value of sqlite.enc if the database handle is not + ** initialized. If the main database exists, the new sqlite.enc value + ** will be overwritten when the schema is next loaded. If it does not + ** already exists, it will be created to use the new encoding value. + */ + if( + !(DbHasProperty(db, 0, DB_SchemaLoaded)) || + DbHasProperty(db, 0, DB_Empty) + ){ + for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ + if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ + ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; + break; + } + } + if( !pEnc->zName ){ + sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight); + } + } + } + } + break; +#endif /* SQLITE_OMIT_UTF16 */ + +#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS + /* + ** PRAGMA [database.]schema_version + ** PRAGMA [database.]schema_version = + ** + ** PRAGMA [database.]user_version + ** PRAGMA [database.]user_version = + ** + ** PRAGMA [database.]freelist_count = + ** + ** PRAGMA [database.]application_id + ** PRAGMA [database.]application_id = + ** + ** The pragma's schema_version and user_version are used to set or get + ** the value of the schema-version and user-version, respectively. Both + ** the schema-version and the user-version are 32-bit signed integers + ** stored in the database header. + ** + ** The schema-cookie is usually only manipulated internally by SQLite. It + ** is incremented by SQLite whenever the database schema is modified (by + ** creating or dropping a table or index). The schema version is used by + ** SQLite each time a query is executed to ensure that the internal cache + ** of the schema used when compiling the SQL query matches the schema of + ** the database against which the compiled query is actually executed. + ** Subverting this mechanism by using "PRAGMA schema_version" to modify + ** the schema-version is potentially dangerous and may lead to program + ** crashes or database corruption. Use with caution! + ** + ** The user-version is not used internally by SQLite. It may be used by + ** applications for any purpose. + */ + case PragTyp_HEADER_VALUE: { + int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */ + sqlite3VdbeUsesBtree(v, iDb); + switch( zLeft[0] ){ + case 'a': case 'A': + iCookie = BTREE_APPLICATION_ID; + break; + case 'f': case 'F': + iCookie = BTREE_FREE_PAGE_COUNT; + break; + case 's': case 'S': + iCookie = BTREE_SCHEMA_VERSION; + break; + default: + iCookie = BTREE_USER_VERSION; + break; + } + + if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){ + /* Write the specified cookie value */ + static const VdbeOpList setCookie[] = { + { OP_Transaction, 0, 1, 0}, /* 0 */ + { OP_Integer, 0, 1, 0}, /* 1 */ + { OP_SetCookie, 0, 0, 1}, /* 2 */ + }; + int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie); + sqlite3VdbeChangeP1(v, addr, iDb); + sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight)); + sqlite3VdbeChangeP1(v, addr+2, iDb); + sqlite3VdbeChangeP2(v, addr+2, iCookie); + }else{ + /* Read the specified cookie value */ + static const VdbeOpList readCookie[] = { + { OP_Transaction, 0, 0, 0}, /* 0 */ + { OP_ReadCookie, 0, 1, 0}, /* 1 */ + { OP_ResultRow, 1, 1, 0} + }; + int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie); + sqlite3VdbeChangeP1(v, addr, iDb); + sqlite3VdbeChangeP1(v, addr+1, iDb); + sqlite3VdbeChangeP3(v, addr+1, iCookie); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT); + } + } + break; +#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ + +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS + /* + ** PRAGMA compile_options + ** + ** Return the names of all compile-time options used in this build, + ** one option per row. + */ + case PragTyp_COMPILE_OPTIONS: { + int i = 0; + const char *zOpt; + sqlite3VdbeSetNumCols(v, 1); + pParse->nMem = 1; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC); + while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } + } + break; +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + +#ifndef SQLITE_OMIT_WAL + /* + ** PRAGMA [database.]wal_checkpoint = passive|full|restart + ** + ** Checkpoint the database. + */ + case PragTyp_WAL_CHECKPOINT: { + int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); + int eMode = SQLITE_CHECKPOINT_PASSIVE; + if( zRight ){ + if( sqlite3StrICmp(zRight, "full")==0 ){ + eMode = SQLITE_CHECKPOINT_FULL; + }else if( sqlite3StrICmp(zRight, "restart")==0 ){ + eMode = SQLITE_CHECKPOINT_RESTART; + } + } + sqlite3VdbeSetNumCols(v, 3); + pParse->nMem = 3; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC); + + sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + } + break; + + /* + ** PRAGMA wal_autocheckpoint + ** PRAGMA wal_autocheckpoint = N + ** + ** Configure a database connection to automatically checkpoint a database + ** after accumulating N frames in the log. Or query for the current value + ** of N. + */ + case PragTyp_WAL_AUTOCHECKPOINT: { + if( zRight ){ + sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); + } + returnSingleInt(pParse, "wal_autocheckpoint", + db->xWalCallback==sqlite3WalDefaultHook ? + SQLITE_PTR_TO_INT(db->pWalArg) : 0); + } + break; +#endif + + /* + ** PRAGMA shrink_memory + ** + ** This pragma attempts to free as much memory as possible from the + ** current database connection. + */ + case PragTyp_SHRINK_MEMORY: { + sqlite3_db_release_memory(db); + break; + } + + /* + ** PRAGMA busy_timeout + ** PRAGMA busy_timeout = N + ** + ** Call sqlite3_busy_timeout(db, N). Return the current timeout value + ** if one is set. If no busy handler or a different busy handler is set + ** then 0 is returned. Setting the busy_timeout to 0 or negative + ** disables the timeout. + */ + /*case PragTyp_BUSY_TIMEOUT*/ default: { + assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT ); + if( zRight ){ + sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); + } + returnSingleInt(pParse, "timeout", db->busyTimeout); + break; + } + + /* + ** PRAGMA soft_heap_limit + ** PRAGMA soft_heap_limit = N + ** + ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted, + ** use -1. + */ + case PragTyp_SOFT_HEAP_LIMIT: { + sqlite3_int64 N; + if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){ + sqlite3_soft_heap_limit64(N); + } + returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1)); + break; + } + +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) + /* + ** Report the current state of file logs for all databases + */ + case PragTyp_LOCK_STATUS: { + static const char *const azLockName[] = { + "unlocked", "shared", "reserved", "pending", "exclusive" + }; + int i; + sqlite3VdbeSetNumCols(v, 2); + pParse->nMem = 2; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC); + for(i=0; inDb; i++){ + Btree *pBt; + const char *zState = "unknown"; + int j; + if( db->aDb[i].zName==0 ) continue; + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC); + pBt = db->aDb[i].pBt; + if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ + zState = "closed"; + }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, + SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ + zState = azLockName[j]; + } + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); + } + break; + } +#endif + +#ifdef SQLITE_HAS_CODEC + case PragTyp_KEY: { + if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); + break; + } + case PragTyp_REKEY: { + if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); + break; + } + case PragTyp_HEXKEY: { + if( zRight ){ + u8 iByte; + int i; + char zKey[40]; + for(i=0, iByte=0; idb; + if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){ + if( zObj==0 ) zObj = "?"; + sqlite3SetString(pData->pzErrMsg, db, + "malformed database schema (%s)", zObj); + if( zExtra ){ + *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, + "%s - %s", *pData->pzErrMsg, zExtra); + } + } + pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT; +} + +/* +** This is the callback routine for the code that initializes the +** database. See sqlite3Init() below for additional information. +** This routine is also called from the OP_ParseSchema opcode of the VDBE. +** +** Each callback contains the following information: +** +** argv[0] = name of thing being created +** argv[1] = root page number for table or index. 0 for trigger or view. +** argv[2] = SQL text for the CREATE statement. +** +*/ +int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){ + InitData *pData = (InitData*)pInit; + sqlite3 *db = pData->db; + int iDb = pData->iDb; + + assert( argc==3 ); + UNUSED_PARAMETER2(NotUsed, argc); + assert( sqlite3_mutex_held(db->mutex) ); + DbClearProperty(db, iDb, DB_Empty); + if( db->mallocFailed ){ + corruptSchema(pData, argv[0], 0); + return 1; + } + + assert( iDb>=0 && iDbnDb ); + if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ + if( argv[1]==0 ){ + corruptSchema(pData, argv[0], 0); + }else if( argv[2] && argv[2][0] ){ + /* Call the parser to process a CREATE TABLE, INDEX or VIEW. + ** But because db->init.busy is set to 1, no VDBE code is generated + ** or executed. All the parser does is build the internal data + ** structures that describe the table, index, or view. + */ + int rc; + sqlite3_stmt *pStmt; + TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ + + assert( db->init.busy ); + db->init.iDb = iDb; + db->init.newTnum = sqlite3Atoi(argv[1]); + db->init.orphanTrigger = 0; + TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0); + rc = db->errCode; + assert( (rc&0xFF)==(rcp&0xFF) ); + db->init.iDb = 0; + if( SQLITE_OK!=rc ){ + if( db->init.orphanTrigger ){ + assert( iDb==1 ); + }else{ + pData->rc = rc; + if( rc==SQLITE_NOMEM ){ + db->mallocFailed = 1; + }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){ + corruptSchema(pData, argv[0], sqlite3_errmsg(db)); + } + } + } + sqlite3_finalize(pStmt); + }else if( argv[0]==0 ){ + corruptSchema(pData, 0, 0); + }else{ + /* If the SQL column is blank it means this is an index that + ** was created to be the PRIMARY KEY or to fulfill a UNIQUE + ** constraint for a CREATE TABLE. The index should have already + ** been created when we processed the CREATE TABLE. All we have + ** to do here is record the root page number for that index. + */ + Index *pIndex; + pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName); + if( pIndex==0 ){ + /* This can occur if there exists an index on a TEMP table which + ** has the same name as another index on a permanent index. Since + ** the permanent table is hidden by the TEMP table, we can also + ** safely ignore the index on the permanent table. + */ + /* Do Nothing */; + }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){ + corruptSchema(pData, argv[0], "invalid rootpage"); + } + } + return 0; +} + +/* +** Attempt to read the database schema and initialize internal +** data structures for a single database file. The index of the +** database file is given by iDb. iDb==0 is used for the main +** database. iDb==1 should never be used. iDb>=2 is used for +** auxiliary databases. Return one of the SQLITE_ error codes to +** indicate success or failure. +*/ +static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ + int rc; + int i; +#ifndef SQLITE_OMIT_DEPRECATED + int size; +#endif + Table *pTab; + Db *pDb; + char const *azArg[4]; + int meta[5]; + InitData initData; + char const *zMasterSchema; + char const *zMasterName; + int openedTransaction = 0; + + /* + ** The master database table has a structure like this + */ + static const char master_schema[] = + "CREATE TABLE sqlite_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" + ; +#ifndef SQLITE_OMIT_TEMPDB + static const char temp_master_schema[] = + "CREATE TEMP TABLE sqlite_temp_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" + ; +#else + #define temp_master_schema 0 +#endif + + assert( iDb>=0 && iDbnDb ); + assert( db->aDb[iDb].pSchema ); + assert( sqlite3_mutex_held(db->mutex) ); + assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); + + /* zMasterSchema and zInitScript are set to point at the master schema + ** and initialisation script appropriate for the database being + ** initialized. zMasterName is the name of the master table. + */ + if( !OMIT_TEMPDB && iDb==1 ){ + zMasterSchema = temp_master_schema; + }else{ + zMasterSchema = master_schema; + } + zMasterName = SCHEMA_TABLE(iDb); + + /* Construct the schema tables. */ + azArg[0] = zMasterName; + azArg[1] = "1"; + azArg[2] = zMasterSchema; + azArg[3] = 0; + initData.db = db; + initData.iDb = iDb; + initData.rc = SQLITE_OK; + initData.pzErrMsg = pzErrMsg; + sqlite3InitCallback(&initData, 3, (char **)azArg, 0); + if( initData.rc ){ + rc = initData.rc; + goto error_out; + } + pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName); + if( ALWAYS(pTab) ){ + pTab->tabFlags |= TF_Readonly; + } + + /* Create a cursor to hold the database open + */ + pDb = &db->aDb[iDb]; + if( pDb->pBt==0 ){ + if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){ + DbSetProperty(db, 1, DB_SchemaLoaded); + } + return SQLITE_OK; + } + + /* If there is not already a read-only (or read-write) transaction opened + ** on the b-tree database, open one now. If a transaction is opened, it + ** will be closed before this function returns. */ + sqlite3BtreeEnter(pDb->pBt); + if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){ + rc = sqlite3BtreeBeginTrans(pDb->pBt, 0); + if( rc!=SQLITE_OK ){ + sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc)); + goto initone_error_out; + } + openedTransaction = 1; + } + + /* Get the database meta information. + ** + ** Meta values are as follows: + ** meta[0] Schema cookie. Changes with each schema change. + ** meta[1] File format of schema layer. + ** meta[2] Size of the page cache. + ** meta[3] Largest rootpage (auto/incr_vacuum mode) + ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE + ** meta[5] User version + ** meta[6] Incremental vacuum mode + ** meta[7] unused + ** meta[8] unused + ** meta[9] unused + ** + ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to + ** the possible values of meta[4]. + */ + for(i=0; ipBt, i+1, (u32 *)&meta[i]); + } + pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1]; + + /* If opening a non-empty database, check the text encoding. For the + ** main database, set sqlite3.enc to the encoding of the main database. + ** For an attached db, it is an error if the encoding is not the same + ** as sqlite3.enc. + */ + if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */ + if( iDb==0 ){ +#ifndef SQLITE_OMIT_UTF16 + u8 encoding; + /* If opening the main database, set ENC(db). */ + encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3; + if( encoding==0 ) encoding = SQLITE_UTF8; + ENC(db) = encoding; +#else + ENC(db) = SQLITE_UTF8; +#endif + }else{ + /* If opening an attached database, the encoding much match ENC(db) */ + if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){ + sqlite3SetString(pzErrMsg, db, "attached databases must use the same" + " text encoding as main database"); + rc = SQLITE_ERROR; + goto initone_error_out; + } + } + }else{ + DbSetProperty(db, iDb, DB_Empty); + } + pDb->pSchema->enc = ENC(db); + + if( pDb->pSchema->cache_size==0 ){ +#ifndef SQLITE_OMIT_DEPRECATED + size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]); + if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; } + pDb->pSchema->cache_size = size; +#else + pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE; +#endif + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); + } + + /* + ** file_format==1 Version 3.0.0. + ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN + ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults + ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants + */ + pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1]; + if( pDb->pSchema->file_format==0 ){ + pDb->pSchema->file_format = 1; + } + if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){ + sqlite3SetString(pzErrMsg, db, "unsupported file format"); + rc = SQLITE_ERROR; + goto initone_error_out; + } + + /* Ticket #2804: When we open a database in the newer file format, + ** clear the legacy_file_format pragma flag so that a VACUUM will + ** not downgrade the database and thus invalidate any descending + ** indices that the user might have created. + */ + if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){ + db->flags &= ~SQLITE_LegacyFileFmt; + } + + /* Read the schema information out of the schema tables + */ + assert( db->init.busy ); + { + char *zSql; + zSql = sqlite3MPrintf(db, + "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid", + db->aDb[iDb].zName, zMasterName); +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); + xAuth = db->xAuth; + db->xAuth = 0; +#endif + rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); +#ifndef SQLITE_OMIT_AUTHORIZATION + db->xAuth = xAuth; + } +#endif + if( rc==SQLITE_OK ) rc = initData.rc; + sqlite3DbFree(db, zSql); +#ifndef SQLITE_OMIT_ANALYZE + if( rc==SQLITE_OK ){ + sqlite3AnalysisLoad(db, iDb); + } +#endif + } + if( db->mallocFailed ){ + rc = SQLITE_NOMEM; + sqlite3ResetAllSchemasOfConnection(db); + } + if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){ + /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider + ** the schema loaded, even if errors occurred. In this situation the + ** current sqlite3_prepare() operation will fail, but the following one + ** will attempt to compile the supplied statement against whatever subset + ** of the schema was loaded before the error occurred. The primary + ** purpose of this is to allow access to the sqlite_master table + ** even when its contents have been corrupted. + */ + DbSetProperty(db, iDb, DB_SchemaLoaded); + rc = SQLITE_OK; + } + + /* Jump here for an error that occurs after successfully allocating + ** curMain and calling sqlite3BtreeEnter(). For an error that occurs + ** before that point, jump to error_out. + */ +initone_error_out: + if( openedTransaction ){ + sqlite3BtreeCommit(pDb->pBt); + } + sqlite3BtreeLeave(pDb->pBt); + +error_out: + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ + db->mallocFailed = 1; + } + return rc; +} + +/* +** Initialize all database files - the main database file, the file +** used to store temporary tables, and any additional database files +** created using ATTACH statements. Return a success code. If an +** error occurs, write an error message into *pzErrMsg. +** +** After a database is initialized, the DB_SchemaLoaded bit is set +** bit is set in the flags field of the Db structure. If the database +** file was of zero-length, then the DB_Empty flag is also set. +*/ +int sqlite3Init(sqlite3 *db, char **pzErrMsg){ + int i, rc; + int commit_internal = !(db->flags&SQLITE_InternChanges); + + assert( sqlite3_mutex_held(db->mutex) ); + rc = SQLITE_OK; + db->init.busy = 1; + for(i=0; rc==SQLITE_OK && inDb; i++){ + if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue; + rc = sqlite3InitOne(db, i, pzErrMsg); + if( rc ){ + sqlite3ResetOneSchema(db, i); + } + } + + /* Once all the other databases have been initialized, load the schema + ** for the TEMP database. This is loaded last, as the TEMP database + ** schema may contain references to objects in other databases. + */ +#ifndef SQLITE_OMIT_TEMPDB + if( rc==SQLITE_OK && ALWAYS(db->nDb>1) + && !DbHasProperty(db, 1, DB_SchemaLoaded) ){ + rc = sqlite3InitOne(db, 1, pzErrMsg); + if( rc ){ + sqlite3ResetOneSchema(db, 1); + } + } +#endif + + db->init.busy = 0; + if( rc==SQLITE_OK && commit_internal ){ + sqlite3CommitInternalChanges(db); + } + + return rc; +} + +/* +** This routine is a no-op if the database schema is already initialized. +** Otherwise, the schema is loaded. An error code is returned. +*/ +int sqlite3ReadSchema(Parse *pParse){ + int rc = SQLITE_OK; + sqlite3 *db = pParse->db; + assert( sqlite3_mutex_held(db->mutex) ); + if( !db->init.busy ){ + rc = sqlite3Init(db, &pParse->zErrMsg); + } + if( rc!=SQLITE_OK ){ + pParse->rc = rc; + pParse->nErr++; + } + return rc; +} + + +/* +** Check schema cookies in all databases. If any cookie is out +** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies +** make no changes to pParse->rc. +*/ +static void schemaIsValid(Parse *pParse){ + sqlite3 *db = pParse->db; + int iDb; + int rc; + int cookie; + + assert( pParse->checkSchema ); + assert( sqlite3_mutex_held(db->mutex) ); + for(iDb=0; iDbnDb; iDb++){ + int openedTransaction = 0; /* True if a transaction is opened */ + Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */ + if( pBt==0 ) continue; + + /* If there is not already a read-only (or read-write) transaction opened + ** on the b-tree database, open one now. If a transaction is opened, it + ** will be closed immediately after reading the meta-value. */ + if( !sqlite3BtreeIsInReadTrans(pBt) ){ + rc = sqlite3BtreeBeginTrans(pBt, 0); + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ + db->mallocFailed = 1; + } + if( rc!=SQLITE_OK ) return; + openedTransaction = 1; + } + + /* Read the schema cookie from the database. If it does not match the + ** value stored as part of the in-memory schema representation, + ** set Parse.rc to SQLITE_SCHEMA. */ + sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie); + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){ + sqlite3ResetOneSchema(db, iDb); + pParse->rc = SQLITE_SCHEMA; + } + + /* Close the transaction, if one was opened. */ + if( openedTransaction ){ + sqlite3BtreeCommit(pBt); + } + } +} + +/* +** Convert a schema pointer into the iDb index that indicates +** which database file in db->aDb[] the schema refers to. +** +** If the same database is attached more than once, the first +** attached database is returned. +*/ +int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ + int i = -1000000; + + /* If pSchema is NULL, then return -1000000. This happens when code in + ** expr.c is trying to resolve a reference to a transient table (i.e. one + ** created by a sub-select). In this case the return value of this + ** function should never be used. + ** + ** We return -1000000 instead of the more usual -1 simply because using + ** -1000000 as the incorrect index into db->aDb[] is much + ** more likely to cause a segfault than -1 (of course there are assert() + ** statements too, but it never hurts to play the odds). + */ + assert( sqlite3_mutex_held(db->mutex) ); + if( pSchema ){ + for(i=0; ALWAYS(inDb); i++){ + if( db->aDb[i].pSchema==pSchema ){ + break; + } + } + assert( i>=0 && inDb ); + } + return i; +} + +/* +** Compile the UTF-8 encoded SQL statement zSql into a statement handle. +*/ +static int sqlite3Prepare( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ + Vdbe *pReprepare, /* VM being reprepared */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +){ + Parse *pParse; /* Parsing context */ + char *zErrMsg = 0; /* Error message */ + int rc = SQLITE_OK; /* Result code */ + int i; /* Loop counter */ + + /* Allocate the parsing context */ + pParse = sqlite3StackAllocZero(db, sizeof(*pParse)); + if( pParse==0 ){ + rc = SQLITE_NOMEM; + goto end_prepare; + } + pParse->pReprepare = pReprepare; + assert( ppStmt && *ppStmt==0 ); + assert( !db->mallocFailed ); + assert( sqlite3_mutex_held(db->mutex) ); + + /* Check to verify that it is possible to get a read lock on all + ** database schemas. The inability to get a read lock indicates that + ** some other database connection is holding a write-lock, which in + ** turn means that the other connection has made uncommitted changes + ** to the schema. + ** + ** Were we to proceed and prepare the statement against the uncommitted + ** schema changes and if those schema changes are subsequently rolled + ** back and different changes are made in their place, then when this + ** prepared statement goes to run the schema cookie would fail to detect + ** the schema change. Disaster would follow. + ** + ** This thread is currently holding mutexes on all Btrees (because + ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it + ** is not possible for another thread to start a new schema change + ** while this routine is running. Hence, we do not need to hold + ** locks on the schema, we just need to make sure nobody else is + ** holding them. + ** + ** Note that setting READ_UNCOMMITTED overrides most lock detection, + ** but it does *not* override schema lock detection, so this all still + ** works even if READ_UNCOMMITTED is set. + */ + for(i=0; inDb; i++) { + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + assert( sqlite3BtreeHoldsMutex(pBt) ); + rc = sqlite3BtreeSchemaLocked(pBt); + if( rc ){ + const char *zDb = db->aDb[i].zName; + sqlite3Error(db, rc, "database schema is locked: %s", zDb); + testcase( db->flags & SQLITE_ReadUncommitted ); + goto end_prepare; + } + } + } + + sqlite3VtabUnlockList(db); + + pParse->db = db; + pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */ + if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){ + char *zSqlCopy; + int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; + testcase( nBytes==mxLen ); + testcase( nBytes==mxLen+1 ); + if( nBytes>mxLen ){ + sqlite3Error(db, SQLITE_TOOBIG, "statement too long"); + rc = sqlite3ApiExit(db, SQLITE_TOOBIG); + goto end_prepare; + } + zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes); + if( zSqlCopy ){ + sqlite3RunParser(pParse, zSqlCopy, &zErrMsg); + sqlite3DbFree(db, zSqlCopy); + pParse->zTail = &zSql[pParse->zTail-zSqlCopy]; + }else{ + pParse->zTail = &zSql[nBytes]; + } + }else{ + sqlite3RunParser(pParse, zSql, &zErrMsg); + } + assert( 0==pParse->nQueryLoop ); + + if( db->mallocFailed ){ + pParse->rc = SQLITE_NOMEM; + } + if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK; + if( pParse->checkSchema ){ + schemaIsValid(pParse); + } + if( db->mallocFailed ){ + pParse->rc = SQLITE_NOMEM; + } + if( pzTail ){ + *pzTail = pParse->zTail; + } + rc = pParse->rc; + +#ifndef SQLITE_OMIT_EXPLAIN + if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){ + static const char * const azColName[] = { + "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", + "selectid", "order", "from", "detail" + }; + int iFirst, mx; + if( pParse->explain==2 ){ + sqlite3VdbeSetNumCols(pParse->pVdbe, 4); + iFirst = 8; + mx = 12; + }else{ + sqlite3VdbeSetNumCols(pParse->pVdbe, 8); + iFirst = 0; + mx = 8; + } + for(i=iFirst; ipVdbe, i-iFirst, COLNAME_NAME, + azColName[i], SQLITE_STATIC); + } + } +#endif + + if( db->init.busy==0 ){ + Vdbe *pVdbe = pParse->pVdbe; + sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag); + } + if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){ + sqlite3VdbeFinalize(pParse->pVdbe); + assert(!(*ppStmt)); + }else{ + *ppStmt = (sqlite3_stmt*)pParse->pVdbe; + } + + if( zErrMsg ){ + sqlite3Error(db, rc, "%s", zErrMsg); + sqlite3DbFree(db, zErrMsg); + }else{ + sqlite3Error(db, rc, 0); + } + + /* Delete any TriggerPrg structures allocated while parsing this statement. */ + while( pParse->pTriggerPrg ){ + TriggerPrg *pT = pParse->pTriggerPrg; + pParse->pTriggerPrg = pT->pNext; + sqlite3DbFree(db, pT); + } + +end_prepare: + + sqlite3StackFree(db, pParse); + rc = sqlite3ApiExit(db, rc); + assert( (rc&db->errMask)==rc ); + return rc; +} +static int sqlite3LockAndPrepare( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ + Vdbe *pOld, /* VM being reprepared */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +){ + int rc; + assert( ppStmt!=0 ); + *ppStmt = 0; + if( !sqlite3SafetyCheckOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + sqlite3_mutex_enter(db->mutex); + sqlite3BtreeEnterAll(db); + rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); + if( rc==SQLITE_SCHEMA ){ + sqlite3_finalize(*ppStmt); + rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); + } + sqlite3BtreeLeaveAll(db); + sqlite3_mutex_leave(db->mutex); + assert( rc==SQLITE_OK || *ppStmt==0 ); + return rc; +} + +/* +** Rerun the compilation of a statement after a schema change. +** +** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, +** if the statement cannot be recompiled because another connection has +** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error +** occurs, return SQLITE_SCHEMA. +*/ +int sqlite3Reprepare(Vdbe *p){ + int rc; + sqlite3_stmt *pNew; + const char *zSql; + sqlite3 *db; + + assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) ); + zSql = sqlite3_sql((sqlite3_stmt *)p); + assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */ + db = sqlite3VdbeDb(p); + assert( sqlite3_mutex_held(db->mutex) ); + rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0); + if( rc ){ + if( rc==SQLITE_NOMEM ){ + db->mallocFailed = 1; + } + assert( pNew==0 ); + return rc; + }else{ + assert( pNew!=0 ); + } + sqlite3VdbeSwap((Vdbe*)pNew, p); + sqlite3TransferBindings(pNew, (sqlite3_stmt*)p); + sqlite3VdbeResetStepResult((Vdbe*)pNew); + sqlite3VdbeFinalize((Vdbe*)pNew); + return SQLITE_OK; +} + + +/* +** Two versions of the official API. Legacy and new use. In the legacy +** version, the original SQL text is not saved in the prepared statement +** and so if a schema change occurs, SQLITE_SCHEMA is returned by +** sqlite3_step(). In the new version, the original SQL text is retained +** and the statement is automatically recompiled if an schema change +** occurs. +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +){ + int rc; + rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + return rc; +} +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +){ + int rc; + rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + return rc; +} + + +#ifndef SQLITE_OMIT_UTF16 +/* +** Compile the UTF-16 encoded SQL statement zSql into a statement handle. +*/ +static int sqlite3Prepare16( + sqlite3 *db, /* Database handle. */ + const void *zSql, /* UTF-16 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const void **pzTail /* OUT: End of parsed string */ +){ + /* This function currently works by first transforming the UTF-16 + ** encoded string to UTF-8, then invoking sqlite3_prepare(). The + ** tricky bit is figuring out the pointer to return in *pzTail. + */ + char *zSql8; + const char *zTail8 = 0; + int rc = SQLITE_OK; + + assert( ppStmt ); + *ppStmt = 0; + if( !sqlite3SafetyCheckOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + if( nBytes>=0 ){ + int sz; + const char *z = (const char*)zSql; + for(sz=0; szmutex); + zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); + if( zSql8 ){ + rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8); + } + + if( zTail8 && pzTail ){ + /* If sqlite3_prepare returns a tail pointer, we calculate the + ** equivalent pointer into the UTF-16 string by counting the unicode + ** characters between zSql8 and zTail8, and then returning a pointer + ** the same number of characters into the UTF-16 string. + */ + int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); + *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); + } + sqlite3DbFree(db, zSql8); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Two versions of the official API. Legacy and new use. In the legacy +** version, the original SQL text is not saved in the prepared statement +** and so if a schema change occurs, SQLITE_SCHEMA is returned by +** sqlite3_step(). In the new version, the original SQL text is retained +** and the statement is automatically recompiled if an schema change +** occurs. +*/ +int sqlite3_prepare16( + sqlite3 *db, /* Database handle. */ + const void *zSql, /* UTF-16 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const void **pzTail /* OUT: End of parsed string */ +){ + int rc; + rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + return rc; +} +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle. */ + const void *zSql, /* UTF-16 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const void **pzTail /* OUT: End of parsed string */ +){ + int rc; + rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + return rc; +} + +#endif /* SQLITE_OMIT_UTF16 */ diff --git a/components/external/SQLite-3.8.1/src/printf.c b/components/external/SQLite-3.8.1/src/printf.c new file mode 100644 index 0000000000000000000000000000000000000000..f9e5c6406d76167fd1e06a5bdc708d6fde39c19f --- /dev/null +++ b/components/external/SQLite-3.8.1/src/printf.c @@ -0,0 +1,965 @@ +/* +** The "printf" code that follows dates from the 1980's. It is in +** the public domain. The original comments are included here for +** completeness. They are very out-of-date but might be useful as +** an historical reference. Most of the "enhancements" have been backed +** out so that the functionality is now the same as standard printf(). +** +************************************************************************** +** +** This file contains code for a set of "printf"-like routines. These +** routines format strings much like the printf() from the standard C +** library, though the implementation here has enhancements to support +** SQLlite. +*/ +#include "sqliteInt.h" + +/* +** Conversion types fall into various categories as defined by the +** following enumeration. +*/ +#define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */ +#define etFLOAT 2 /* Floating point. %f */ +#define etEXP 3 /* Exponentional notation. %e and %E */ +#define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */ +#define etSIZE 5 /* Return number of characters processed so far. %n */ +#define etSTRING 6 /* Strings. %s */ +#define etDYNSTRING 7 /* Dynamically allocated strings. %z */ +#define etPERCENT 8 /* Percent symbol. %% */ +#define etCHARX 9 /* Characters. %c */ +/* The rest are extensions, not normally found in printf() */ +#define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */ +#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '', + NULL pointers replaced by SQL NULL. %Q */ +#define etTOKEN 12 /* a pointer to a Token structure */ +#define etSRCLIST 13 /* a pointer to a SrcList */ +#define etPOINTER 14 /* The %p conversion */ +#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */ +#define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ + +#define etINVALID 0 /* Any unrecognized conversion type */ + + +/* +** An "etByte" is an 8-bit unsigned value. +*/ +typedef unsigned char etByte; + +/* +** Each builtin conversion character (ex: the 'd' in "%d") is described +** by an instance of the following structure +*/ +typedef struct et_info { /* Information about each format field */ + char fmttype; /* The format field code letter */ + etByte base; /* The base for radix conversion */ + etByte flags; /* One or more of FLAG_ constants below */ + etByte type; /* Conversion paradigm */ + etByte charset; /* Offset into aDigits[] of the digits string */ + etByte prefix; /* Offset into aPrefix[] of the prefix string */ +} et_info; + +/* +** Allowed values for et_info.flags +*/ +#define FLAG_SIGNED 1 /* True if the value to convert is signed */ +#define FLAG_INTERN 2 /* True if for internal use only */ +#define FLAG_STRING 4 /* Allow infinity precision */ + + +/* +** The following table is searched linearly, so it is good to put the +** most frequently used conversion types first. +*/ +static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; +static const char aPrefix[] = "-x0\000X0"; +static const et_info fmtinfo[] = { + { 'd', 10, 1, etRADIX, 0, 0 }, + { 's', 0, 4, etSTRING, 0, 0 }, + { 'g', 0, 1, etGENERIC, 30, 0 }, + { 'z', 0, 4, etDYNSTRING, 0, 0 }, + { 'q', 0, 4, etSQLESCAPE, 0, 0 }, + { 'Q', 0, 4, etSQLESCAPE2, 0, 0 }, + { 'w', 0, 4, etSQLESCAPE3, 0, 0 }, + { 'c', 0, 0, etCHARX, 0, 0 }, + { 'o', 8, 0, etRADIX, 0, 2 }, + { 'u', 10, 0, etRADIX, 0, 0 }, + { 'x', 16, 0, etRADIX, 16, 1 }, + { 'X', 16, 0, etRADIX, 0, 4 }, +#ifndef SQLITE_OMIT_FLOATING_POINT + { 'f', 0, 1, etFLOAT, 0, 0 }, + { 'e', 0, 1, etEXP, 30, 0 }, + { 'E', 0, 1, etEXP, 14, 0 }, + { 'G', 0, 1, etGENERIC, 14, 0 }, +#endif + { 'i', 10, 1, etRADIX, 0, 0 }, + { 'n', 0, 0, etSIZE, 0, 0 }, + { '%', 0, 0, etPERCENT, 0, 0 }, + { 'p', 16, 0, etPOINTER, 0, 1 }, + +/* All the rest have the FLAG_INTERN bit set and are thus for internal +** use only */ + { 'T', 0, 2, etTOKEN, 0, 0 }, + { 'S', 0, 2, etSRCLIST, 0, 0 }, + { 'r', 10, 3, etORDINAL, 0, 0 }, +}; + +/* +** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point +** conversions will work. +*/ +#ifndef SQLITE_OMIT_FLOATING_POINT +/* +** "*val" is a double such that 0.1 <= *val < 10.0 +** Return the ascii code for the leading digit of *val, then +** multiply "*val" by 10.0 to renormalize. +** +** Example: +** input: *val = 3.14159 +** output: *val = 1.4159 function return = '3' +** +** The counter *cnt is incremented each time. After counter exceeds +** 16 (the number of significant digits in a 64-bit float) '0' is +** always returned. +*/ +static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){ + int digit; + LONGDOUBLE_TYPE d; + if( (*cnt)<=0 ) return '0'; + (*cnt)--; + digit = (int)*val; + d = digit; + digit += '0'; + *val = (*val - d)*10.0; + return (char)digit; +} +#endif /* SQLITE_OMIT_FLOATING_POINT */ + +/* +** Append N space characters to the given string buffer. +*/ +void sqlite3AppendSpace(StrAccum *pAccum, int N){ + static const char zSpaces[] = " "; + while( N>=(int)sizeof(zSpaces)-1 ){ + sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1); + N -= sizeof(zSpaces)-1; + } + if( N>0 ){ + sqlite3StrAccumAppend(pAccum, zSpaces, N); + } +} + +/* +** On machines with a small stack size, you can redefine the +** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired. +*/ +#ifndef SQLITE_PRINT_BUF_SIZE +# define SQLITE_PRINT_BUF_SIZE 70 +#endif +#define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */ + +/* +** Render a string given by "fmt" into the StrAccum object. +*/ +void sqlite3VXPrintf( + StrAccum *pAccum, /* Accumulate results here */ + int useExtended, /* Allow extended %-conversions */ + const char *fmt, /* Format string */ + va_list ap /* arguments */ +){ + int c; /* Next character in the format string */ + char *bufpt; /* Pointer to the conversion buffer */ + int precision; /* Precision of the current field */ + int length; /* Length of the field */ + int idx; /* A general purpose loop counter */ + int width; /* Width of the current field */ + etByte flag_leftjustify; /* True if "-" flag is present */ + etByte flag_plussign; /* True if "+" flag is present */ + etByte flag_blanksign; /* True if " " flag is present */ + etByte flag_alternateform; /* True if "#" flag is present */ + etByte flag_altform2; /* True if "!" flag is present */ + etByte flag_zeropad; /* True if field width constant starts with zero */ + etByte flag_long; /* True if "l" flag is present */ + etByte flag_longlong; /* True if the "ll" flag is present */ + etByte done; /* Loop termination flag */ + etByte xtype = 0; /* Conversion paradigm */ + char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ + sqlite_uint64 longvalue; /* Value for integer types */ + LONGDOUBLE_TYPE realvalue; /* Value for real types */ + const et_info *infop; /* Pointer to the appropriate info structure */ + char *zOut; /* Rendering buffer */ + int nOut; /* Size of the rendering buffer */ + char *zExtra; /* Malloced memory used by some conversion */ +#ifndef SQLITE_OMIT_FLOATING_POINT + int exp, e2; /* exponent of real numbers */ + int nsd; /* Number of significant digits returned */ + double rounder; /* Used for rounding floating point values */ + etByte flag_dp; /* True if decimal point should be shown */ + etByte flag_rtz; /* True if trailing zeros should be removed */ +#endif + char buf[etBUFSIZE]; /* Conversion buffer */ + + bufpt = 0; + for(; (c=(*fmt))!=0; ++fmt){ + if( c!='%' ){ + int amt; + bufpt = (char *)fmt; + amt = 1; + while( (c=(*++fmt))!='%' && c!=0 ) amt++; + sqlite3StrAccumAppend(pAccum, bufpt, amt); + if( c==0 ) break; + } + if( (c=(*++fmt))==0 ){ + sqlite3StrAccumAppend(pAccum, "%", 1); + break; + } + /* Find out what flags are present */ + flag_leftjustify = flag_plussign = flag_blanksign = + flag_alternateform = flag_altform2 = flag_zeropad = 0; + done = 0; + do{ + switch( c ){ + case '-': flag_leftjustify = 1; break; + case '+': flag_plussign = 1; break; + case ' ': flag_blanksign = 1; break; + case '#': flag_alternateform = 1; break; + case '!': flag_altform2 = 1; break; + case '0': flag_zeropad = 1; break; + default: done = 1; break; + } + }while( !done && (c=(*++fmt))!=0 ); + /* Get the field width */ + width = 0; + if( c=='*' ){ + width = va_arg(ap,int); + if( width<0 ){ + flag_leftjustify = 1; + width = -width; + } + c = *++fmt; + }else{ + while( c>='0' && c<='9' ){ + width = width*10 + c - '0'; + c = *++fmt; + } + } + /* Get the precision */ + if( c=='.' ){ + precision = 0; + c = *++fmt; + if( c=='*' ){ + precision = va_arg(ap,int); + if( precision<0 ) precision = -precision; + c = *++fmt; + }else{ + while( c>='0' && c<='9' ){ + precision = precision*10 + c - '0'; + c = *++fmt; + } + } + }else{ + precision = -1; + } + /* Get the conversion type modifier */ + if( c=='l' ){ + flag_long = 1; + c = *++fmt; + if( c=='l' ){ + flag_longlong = 1; + c = *++fmt; + }else{ + flag_longlong = 0; + } + }else{ + flag_long = flag_longlong = 0; + } + /* Fetch the info entry for the field */ + infop = &fmtinfo[0]; + xtype = etINVALID; + for(idx=0; idxflags & FLAG_INTERN)==0 ){ + xtype = infop->type; + }else{ + return; + } + break; + } + } + zExtra = 0; + + /* + ** At this point, variables are initialized as follows: + ** + ** flag_alternateform TRUE if a '#' is present. + ** flag_altform2 TRUE if a '!' is present. + ** flag_plussign TRUE if a '+' is present. + ** flag_leftjustify TRUE if a '-' is present or if the + ** field width was negative. + ** flag_zeropad TRUE if the width began with 0. + ** flag_long TRUE if the letter 'l' (ell) prefixed + ** the conversion character. + ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed + ** the conversion character. + ** flag_blanksign TRUE if a ' ' is present. + ** width The specified field width. This is + ** always non-negative. Zero is the default. + ** precision The specified precision. The default + ** is -1. + ** xtype The class of the conversion. + ** infop Pointer to the appropriate info struct. + */ + switch( xtype ){ + case etPOINTER: + flag_longlong = sizeof(char*)==sizeof(i64); + flag_long = sizeof(char*)==sizeof(long int); + /* Fall through into the next case */ + case etORDINAL: + case etRADIX: + if( infop->flags & FLAG_SIGNED ){ + i64 v; + if( flag_longlong ){ + v = va_arg(ap,i64); + }else if( flag_long ){ + v = va_arg(ap,long int); + }else{ + v = va_arg(ap,int); + } + if( v<0 ){ + if( v==SMALLEST_INT64 ){ + longvalue = ((u64)1)<<63; + }else{ + longvalue = -v; + } + prefix = '-'; + }else{ + longvalue = v; + if( flag_plussign ) prefix = '+'; + else if( flag_blanksign ) prefix = ' '; + else prefix = 0; + } + }else{ + if( flag_longlong ){ + longvalue = va_arg(ap,u64); + }else if( flag_long ){ + longvalue = va_arg(ap,unsigned long int); + }else{ + longvalue = va_arg(ap,unsigned int); + } + prefix = 0; + } + if( longvalue==0 ) flag_alternateform = 0; + if( flag_zeropad && precisionaccError = STRACCUM_NOMEM; + return; + } + } + bufpt = &zOut[nOut-1]; + if( xtype==etORDINAL ){ + static const char zOrd[] = "thstndrd"; + int x = (int)(longvalue % 10); + if( x>=4 || (longvalue/10)%10==1 ){ + x = 0; + } + *(--bufpt) = zOrd[x*2+1]; + *(--bufpt) = zOrd[x*2]; + } + { + register const char *cset; /* Use registers for speed */ + register int base; + cset = &aDigits[infop->charset]; + base = infop->base; + do{ /* Convert to ascii */ + *(--bufpt) = cset[longvalue%base]; + longvalue = longvalue/base; + }while( longvalue>0 ); + } + length = (int)(&zOut[nOut-1]-bufpt); + for(idx=precision-length; idx>0; idx--){ + *(--bufpt) = '0'; /* Zero pad */ + } + if( prefix ) *(--bufpt) = prefix; /* Add sign */ + if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ + const char *pre; + char x; + pre = &aPrefix[infop->prefix]; + for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; + } + length = (int)(&zOut[nOut-1]-bufpt); + break; + case etFLOAT: + case etEXP: + case etGENERIC: + realvalue = va_arg(ap,double); +#ifdef SQLITE_OMIT_FLOATING_POINT + length = 0; +#else + if( precision<0 ) precision = 6; /* Set default precision */ + if( realvalue<0.0 ){ + realvalue = -realvalue; + prefix = '-'; + }else{ + if( flag_plussign ) prefix = '+'; + else if( flag_blanksign ) prefix = ' '; + else prefix = 0; + } + if( xtype==etGENERIC && precision>0 ) precision--; + for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){} + if( xtype==etFLOAT ) realvalue += rounder; + /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ + exp = 0; + if( sqlite3IsNaN((double)realvalue) ){ + bufpt = "NaN"; + length = 3; + break; + } + if( realvalue>0.0 ){ + LONGDOUBLE_TYPE scale = 1.0; + while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;} + while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; } + while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; } + while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; } + realvalue /= scale; + while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; } + while( realvalue<1.0 ){ realvalue *= 10.0; exp--; } + if( exp>350 ){ + if( prefix=='-' ){ + bufpt = "-Inf"; + }else if( prefix=='+' ){ + bufpt = "+Inf"; + }else{ + bufpt = "Inf"; + } + length = sqlite3Strlen30(bufpt); + break; + } + } + bufpt = buf; + /* + ** If the field type is etGENERIC, then convert to either etEXP + ** or etFLOAT, as appropriate. + */ + if( xtype!=etFLOAT ){ + realvalue += rounder; + if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; } + } + if( xtype==etGENERIC ){ + flag_rtz = !flag_alternateform; + if( exp<-4 || exp>precision ){ + xtype = etEXP; + }else{ + precision = precision - exp; + xtype = etFLOAT; + } + }else{ + flag_rtz = flag_altform2; + } + if( xtype==etEXP ){ + e2 = 0; + }else{ + e2 = exp; + } + if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){ + bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 ); + if( bufpt==0 ){ + pAccum->accError = STRACCUM_NOMEM; + return; + } + } + zOut = bufpt; + nsd = 16 + flag_altform2*10; + flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2; + /* The sign in front of the number */ + if( prefix ){ + *(bufpt++) = prefix; + } + /* Digits prior to the decimal point */ + if( e2<0 ){ + *(bufpt++) = '0'; + }else{ + for(; e2>=0; e2--){ + *(bufpt++) = et_getdigit(&realvalue,&nsd); + } + } + /* The decimal point */ + if( flag_dp ){ + *(bufpt++) = '.'; + } + /* "0" digits after the decimal point but before the first + ** significant digit of the number */ + for(e2++; e2<0; precision--, e2++){ + assert( precision>0 ); + *(bufpt++) = '0'; + } + /* Significant digits after the decimal point */ + while( (precision--)>0 ){ + *(bufpt++) = et_getdigit(&realvalue,&nsd); + } + /* Remove trailing zeros and the "." if no digits follow the "." */ + if( flag_rtz && flag_dp ){ + while( bufpt[-1]=='0' ) *(--bufpt) = 0; + assert( bufpt>zOut ); + if( bufpt[-1]=='.' ){ + if( flag_altform2 ){ + *(bufpt++) = '0'; + }else{ + *(--bufpt) = 0; + } + } + } + /* Add the "eNNN" suffix */ + if( xtype==etEXP ){ + *(bufpt++) = aDigits[infop->charset]; + if( exp<0 ){ + *(bufpt++) = '-'; exp = -exp; + }else{ + *(bufpt++) = '+'; + } + if( exp>=100 ){ + *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */ + exp %= 100; + } + *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */ + *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */ + } + *bufpt = 0; + + /* The converted number is in buf[] and zero terminated. Output it. + ** Note that the number is in the usual order, not reversed as with + ** integer conversions. */ + length = (int)(bufpt-zOut); + bufpt = zOut; + + /* Special case: Add leading zeros if the flag_zeropad flag is + ** set and we are not left justified */ + if( flag_zeropad && !flag_leftjustify && length < width){ + int i; + int nPad = width - length; + for(i=width; i>=nPad; i--){ + bufpt[i] = bufpt[i-nPad]; + } + i = prefix!=0; + while( nPad-- ) bufpt[i++] = '0'; + length = width; + } +#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */ + break; + case etSIZE: + *(va_arg(ap,int*)) = pAccum->nChar; + length = width = 0; + break; + case etPERCENT: + buf[0] = '%'; + bufpt = buf; + length = 1; + break; + case etCHARX: + c = va_arg(ap,int); + buf[0] = (char)c; + if( precision>=0 ){ + for(idx=1; idx=0 ){ + for(length=0; lengthetBUFSIZE ){ + bufpt = zExtra = sqlite3Malloc( n ); + if( bufpt==0 ){ + pAccum->accError = STRACCUM_NOMEM; + return; + } + }else{ + bufpt = buf; + } + j = 0; + if( needQuote ) bufpt[j++] = q; + k = i; + for(i=0; i=0 && precisionz, pToken->n); + } + length = width = 0; + break; + } + case etSRCLIST: { + SrcList *pSrc = va_arg(ap, SrcList*); + int k = va_arg(ap, int); + struct SrcList_item *pItem = &pSrc->a[k]; + assert( k>=0 && knSrc ); + if( pItem->zDatabase ){ + sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1); + sqlite3StrAccumAppend(pAccum, ".", 1); + } + sqlite3StrAccumAppend(pAccum, pItem->zName, -1); + length = width = 0; + break; + } + default: { + assert( xtype==etINVALID ); + return; + } + }/* End switch over the format type */ + /* + ** The text of the conversion is pointed to by "bufpt" and is + ** "length" characters long. The field width is "width". Do + ** the output. + */ + if( !flag_leftjustify ){ + register int nspace; + nspace = width-length; + if( nspace>0 ){ + sqlite3AppendSpace(pAccum, nspace); + } + } + if( length>0 ){ + sqlite3StrAccumAppend(pAccum, bufpt, length); + } + if( flag_leftjustify ){ + register int nspace; + nspace = width-length; + if( nspace>0 ){ + sqlite3AppendSpace(pAccum, nspace); + } + } + sqlite3_free(zExtra); + }/* End for loop over the format string */ +} /* End of function */ + +/* +** Append N bytes of text from z to the StrAccum object. +*/ +void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ + assert( z!=0 || N==0 ); + if( p->accError ){ + testcase(p->accError==STRACCUM_TOOBIG); + testcase(p->accError==STRACCUM_NOMEM); + return; + } + assert( p->zText!=0 || p->nChar==0 ); + if( N<=0 ){ + if( N==0 || z[0]==0 ) return; + N = sqlite3Strlen30(z); + } + if( p->nChar+N >= p->nAlloc ){ + char *zNew; + if( !p->useMalloc ){ + p->accError = STRACCUM_TOOBIG; + N = p->nAlloc - p->nChar - 1; + if( N<=0 ){ + return; + } + }else{ + char *zOld = (p->zText==p->zBase ? 0 : p->zText); + i64 szNew = p->nChar; + szNew += N + 1; + if( szNew > p->mxAlloc ){ + sqlite3StrAccumReset(p); + p->accError = STRACCUM_TOOBIG; + return; + }else{ + p->nAlloc = (int)szNew; + } + if( p->useMalloc==1 ){ + zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); + }else{ + zNew = sqlite3_realloc(zOld, p->nAlloc); + } + if( zNew ){ + if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); + p->zText = zNew; + }else{ + p->accError = STRACCUM_NOMEM; + sqlite3StrAccumReset(p); + return; + } + } + } + assert( p->zText ); + memcpy(&p->zText[p->nChar], z, N); + p->nChar += N; +} + +/* +** Finish off a string by making sure it is zero-terminated. +** Return a pointer to the resulting string. Return a NULL +** pointer if any kind of error was encountered. +*/ +char *sqlite3StrAccumFinish(StrAccum *p){ + if( p->zText ){ + p->zText[p->nChar] = 0; + if( p->useMalloc && p->zText==p->zBase ){ + if( p->useMalloc==1 ){ + p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 ); + }else{ + p->zText = sqlite3_malloc(p->nChar+1); + } + if( p->zText ){ + memcpy(p->zText, p->zBase, p->nChar+1); + }else{ + p->accError = STRACCUM_NOMEM; + } + } + } + return p->zText; +} + +/* +** Reset an StrAccum string. Reclaim all malloced memory. +*/ +void sqlite3StrAccumReset(StrAccum *p){ + if( p->zText!=p->zBase ){ + if( p->useMalloc==1 ){ + sqlite3DbFree(p->db, p->zText); + }else{ + sqlite3_free(p->zText); + } + } + p->zText = 0; +} + +/* +** Initialize a string accumulator +*/ +void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){ + p->zText = p->zBase = zBase; + p->db = 0; + p->nChar = 0; + p->nAlloc = n; + p->mxAlloc = mx; + p->useMalloc = 1; + p->accError = 0; +} + +/* +** Print into memory obtained from sqliteMalloc(). Use the internal +** %-conversion extensions. +*/ +char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){ + char *z; + char zBase[SQLITE_PRINT_BUF_SIZE]; + StrAccum acc; + assert( db!=0 ); + sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), + db->aLimit[SQLITE_LIMIT_LENGTH]); + acc.db = db; + sqlite3VXPrintf(&acc, 1, zFormat, ap); + z = sqlite3StrAccumFinish(&acc); + if( acc.accError==STRACCUM_NOMEM ){ + db->mallocFailed = 1; + } + return z; +} + +/* +** Print into memory obtained from sqliteMalloc(). Use the internal +** %-conversion extensions. +*/ +char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){ + va_list ap; + char *z; + va_start(ap, zFormat); + z = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + return z; +} + +/* +** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting +** the string and before returnning. This routine is intended to be used +** to modify an existing string. For example: +** +** x = sqlite3MPrintf(db, x, "prefix %s suffix", x); +** +*/ +char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){ + va_list ap; + char *z; + va_start(ap, zFormat); + z = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + sqlite3DbFree(db, zStr); + return z; +} + +/* +** Print into memory obtained from sqlite3_malloc(). Omit the internal +** %-conversion extensions. +*/ +char *sqlite3_vmprintf(const char *zFormat, va_list ap){ + char *z; + char zBase[SQLITE_PRINT_BUF_SIZE]; + StrAccum acc; +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH); + acc.useMalloc = 2; + sqlite3VXPrintf(&acc, 0, zFormat, ap); + z = sqlite3StrAccumFinish(&acc); + return z; +} + +/* +** Print into memory obtained from sqlite3_malloc()(). Omit the internal +** %-conversion extensions. +*/ +char *sqlite3_mprintf(const char *zFormat, ...){ + va_list ap; + char *z; +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return 0; +#endif + va_start(ap, zFormat); + z = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + return z; +} + +/* +** sqlite3_snprintf() works like snprintf() except that it ignores the +** current locale settings. This is important for SQLite because we +** are not able to use a "," as the decimal point in place of "." as +** specified by some locales. +** +** Oops: The first two arguments of sqlite3_snprintf() are backwards +** from the snprintf() standard. Unfortunately, it is too late to change +** this without breaking compatibility, so we just have to live with the +** mistake. +** +** sqlite3_vsnprintf() is the varargs version. +*/ +char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){ + StrAccum acc; + if( n<=0 ) return zBuf; + sqlite3StrAccumInit(&acc, zBuf, n, 0); + acc.useMalloc = 0; + sqlite3VXPrintf(&acc, 0, zFormat, ap); + return sqlite3StrAccumFinish(&acc); +} +char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ + char *z; + va_list ap; + va_start(ap,zFormat); + z = sqlite3_vsnprintf(n, zBuf, zFormat, ap); + va_end(ap); + return z; +} + +/* +** This is the routine that actually formats the sqlite3_log() message. +** We house it in a separate routine from sqlite3_log() to avoid using +** stack space on small-stack systems when logging is disabled. +** +** sqlite3_log() must render into a static buffer. It cannot dynamically +** allocate memory because it might be called while the memory allocator +** mutex is held. +*/ +static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ + StrAccum acc; /* String accumulator */ + char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ + + sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0); + acc.useMalloc = 0; + sqlite3VXPrintf(&acc, 0, zFormat, ap); + sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode, + sqlite3StrAccumFinish(&acc)); +} + +/* +** Format and write a message to the log if logging is enabled. +*/ +void sqlite3_log(int iErrCode, const char *zFormat, ...){ + va_list ap; /* Vararg list */ + if( sqlite3GlobalConfig.xLog ){ + va_start(ap, zFormat); + renderLogMsg(iErrCode, zFormat, ap); + va_end(ap); + } +} + +#if defined(SQLITE_DEBUG) +/* +** A version of printf() that understands %lld. Used for debugging. +** The printf() built into some versions of windows does not understand %lld +** and segfaults if you give it a long long int. +*/ +void sqlite3DebugPrintf(const char *zFormat, ...){ + va_list ap; + StrAccum acc; + char zBuf[500]; + sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0); + acc.useMalloc = 0; + va_start(ap,zFormat); + sqlite3VXPrintf(&acc, 0, zFormat, ap); + va_end(ap); + sqlite3StrAccumFinish(&acc); + fprintf(stdout,"%s", zBuf); + fflush(stdout); +} +#endif + +#ifndef SQLITE_OMIT_TRACE +/* +** variable-argument wrapper around sqlite3VXPrintf(). +*/ +void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){ + va_list ap; + va_start(ap,zFormat); + sqlite3VXPrintf(p, 1, zFormat, ap); + va_end(ap); +} +#endif diff --git a/components/external/SQLite-3.8.1/src/random.c b/components/external/SQLite-3.8.1/src/random.c new file mode 100644 index 0000000000000000000000000000000000000000..7afff50885a97edfd1f4f457fdf4f47d9457c115 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/random.c @@ -0,0 +1,122 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code to implement a pseudo-random number +** generator (PRNG) for SQLite. +** +** Random numbers are used by some of the database backends in order +** to generate random integer keys for tables or random filenames. +*/ +#include "sqliteInt.h" + + +/* All threads share a single random number generator. +** This structure is the current state of the generator. +*/ +static SQLITE_WSD struct sqlite3PrngType { + unsigned char isInit; /* True if initialized */ + unsigned char i, j; /* State variables */ + unsigned char s[256]; /* State variables */ +} sqlite3Prng; + +/* +** Return N random bytes. +*/ +void sqlite3_randomness(int N, void *pBuf){ + unsigned char t; + unsigned char *zBuf = pBuf; + + /* The "wsdPrng" macro will resolve to the pseudo-random number generator + ** state vector. If writable static data is unsupported on the target, + ** we have to locate the state vector at run-time. In the more common + ** case where writable static data is supported, wsdPrng can refer directly + ** to the "sqlite3Prng" state vector declared above. + */ +#ifdef SQLITE_OMIT_WSD + struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); +# define wsdPrng p[0] +#else +# define wsdPrng sqlite3Prng +#endif + +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); + sqlite3_mutex_enter(mutex); +#endif + + /* Initialize the state of the random number generator once, + ** the first time this routine is called. The seed value does + ** not need to contain a lot of randomness since we are not + ** trying to do secure encryption or anything like that... + ** + ** Nothing in this file or anywhere else in SQLite does any kind of + ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random + ** number generator) not as an encryption device. + */ + if( !wsdPrng.isInit ){ + int i; + char k[256]; + wsdPrng.j = 0; + wsdPrng.i = 0; + sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k); + for(i=0; i<256; i++){ + wsdPrng.s[i] = (u8)i; + } + for(i=0; i<256; i++){ + wsdPrng.j += wsdPrng.s[i] + k[i]; + t = wsdPrng.s[wsdPrng.j]; + wsdPrng.s[wsdPrng.j] = wsdPrng.s[i]; + wsdPrng.s[i] = t; + } + wsdPrng.isInit = 1; + } + + while( N-- ){ + wsdPrng.i++; + t = wsdPrng.s[wsdPrng.i]; + wsdPrng.j += t; + wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j]; + wsdPrng.s[wsdPrng.j] = t; + t += wsdPrng.s[wsdPrng.i]; + *(zBuf++) = wsdPrng.s[t]; + } + sqlite3_mutex_leave(mutex); +} + +#ifndef SQLITE_OMIT_BUILTIN_TEST +/* +** For testing purposes, we sometimes want to preserve the state of +** PRNG and restore the PRNG to its saved state at a later time, or +** to reset the PRNG to its initial state. These routines accomplish +** those tasks. +** +** The sqlite3_test_control() interface calls these routines to +** control the PRNG. +*/ +static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng; +void sqlite3PrngSaveState(void){ + memcpy( + &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), + &GLOBAL(struct sqlite3PrngType, sqlite3Prng), + sizeof(sqlite3Prng) + ); +} +void sqlite3PrngRestoreState(void){ + memcpy( + &GLOBAL(struct sqlite3PrngType, sqlite3Prng), + &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), + sizeof(sqlite3Prng) + ); +} +void sqlite3PrngResetState(void){ + GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0; +} +#endif /* SQLITE_OMIT_BUILTIN_TEST */ diff --git a/components/external/SQLite-3.8.1/src/resolve.c b/components/external/SQLite-3.8.1/src/resolve.c new file mode 100644 index 0000000000000000000000000000000000000000..92fbaaf15afa6890a0c304072d8a1094eb78fbcd --- /dev/null +++ b/components/external/SQLite-3.8.1/src/resolve.c @@ -0,0 +1,1451 @@ +/* +** 2008 August 18 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains routines used for walking the parser tree and +** resolve all identifiers by associating them with a particular +** table and column. +*/ +#include "sqliteInt.h" +#include +#include + +/* +** Walk the expression tree pExpr and increase the aggregate function +** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node. +** This needs to occur when copying a TK_AGG_FUNCTION node from an +** outer query into an inner subquery. +** +** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..) +** is a helper function - a callback for the tree walker. +*/ +static int incrAggDepth(Walker *pWalker, Expr *pExpr){ + if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i; + return WRC_Continue; +} +static void incrAggFunctionDepth(Expr *pExpr, int N){ + if( N>0 ){ + Walker w; + memset(&w, 0, sizeof(w)); + w.xExprCallback = incrAggDepth; + w.u.i = N; + sqlite3WalkExpr(&w, pExpr); + } +} + +/* +** Turn the pExpr expression into an alias for the iCol-th column of the +** result set in pEList. +** +** If the result set column is a simple column reference, then this routine +** makes an exact copy. But for any other kind of expression, this +** routine make a copy of the result set column as the argument to the +** TK_AS operator. The TK_AS operator causes the expression to be +** evaluated just once and then reused for each alias. +** +** The reason for suppressing the TK_AS term when the expression is a simple +** column reference is so that the column reference will be recognized as +** usable by indices within the WHERE clause processing logic. +** +** The TK_AS operator is inhibited if zType[0]=='G'. This means +** that in a GROUP BY clause, the expression is evaluated twice. Hence: +** +** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x +** +** Is equivalent to: +** +** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5 +** +** The result of random()%5 in the GROUP BY clause is probably different +** from the result in the result-set. On the other hand Standard SQL does +** not allow the GROUP BY clause to contain references to result-set columns. +** So this should never come up in well-formed queries. +** +** If the reference is followed by a COLLATE operator, then make sure +** the COLLATE operator is preserved. For example: +** +** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase; +** +** Should be transformed into: +** +** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase; +** +** The nSubquery parameter specifies how many levels of subquery the +** alias is removed from the original expression. The usually value is +** zero but it might be more if the alias is contained within a subquery +** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION +** structures must be increased by the nSubquery amount. +*/ +static void resolveAlias( + Parse *pParse, /* Parsing context */ + ExprList *pEList, /* A result set */ + int iCol, /* A column in the result set. 0..pEList->nExpr-1 */ + Expr *pExpr, /* Transform this into an alias to the result set */ + const char *zType, /* "GROUP" or "ORDER" or "" */ + int nSubquery /* Number of subqueries that the label is moving */ +){ + Expr *pOrig; /* The iCol-th column of the result set */ + Expr *pDup; /* Copy of pOrig */ + sqlite3 *db; /* The database connection */ + + assert( iCol>=0 && iColnExpr ); + pOrig = pEList->a[iCol].pExpr; + assert( pOrig!=0 ); + assert( pOrig->flags & EP_Resolved ); + db = pParse->db; + pDup = sqlite3ExprDup(db, pOrig, 0); + if( pDup==0 ) return; + if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){ + incrAggFunctionDepth(pDup, nSubquery); + pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0); + if( pDup==0 ) return; + ExprSetProperty(pDup, EP_Skip); + if( pEList->a[iCol].iAlias==0 ){ + pEList->a[iCol].iAlias = (u16)(++pParse->nAlias); + } + pDup->iTable = pEList->a[iCol].iAlias; + } + if( pExpr->op==TK_COLLATE ){ + pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); + } + + /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This + ** prevents ExprDelete() from deleting the Expr structure itself, + ** allowing it to be repopulated by the memcpy() on the following line. + ** The pExpr->u.zToken might point into memory that will be freed by the + ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to + ** make a copy of the token before doing the sqlite3DbFree(). + */ + ExprSetProperty(pExpr, EP_Static); + sqlite3ExprDelete(db, pExpr); + memcpy(pExpr, pDup, sizeof(*pExpr)); + if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ + assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); + pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken); + pExpr->flags |= EP_MemToken; + } + sqlite3DbFree(db, pDup); +} + + +/* +** Return TRUE if the name zCol occurs anywhere in the USING clause. +** +** Return FALSE if the USING clause is NULL or if it does not contain +** zCol. +*/ +static int nameInUsingClause(IdList *pUsing, const char *zCol){ + if( pUsing ){ + int k; + for(k=0; knId; k++){ + if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1; + } + } + return 0; +} + +/* +** Subqueries stores the original database, table and column names for their +** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN". +** Check to see if the zSpan given to this routine matches the zDb, zTab, +** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will +** match anything. +*/ +int sqlite3MatchSpanName( + const char *zSpan, + const char *zCol, + const char *zTab, + const char *zDb +){ + int n; + for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} + if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ + return 0; + } + zSpan += n+1; + for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} + if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ + return 0; + } + zSpan += n+1; + if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){ + return 0; + } + return 1; +} + +/* +** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up +** that name in the set of source tables in pSrcList and make the pExpr +** expression node refer back to that source column. The following changes +** are made to pExpr: +** +** pExpr->iDb Set the index in db->aDb[] of the database X +** (even if X is implied). +** pExpr->iTable Set to the cursor number for the table obtained +** from pSrcList. +** pExpr->pTab Points to the Table structure of X.Y (even if +** X and/or Y are implied.) +** pExpr->iColumn Set to the column number within the table. +** pExpr->op Set to TK_COLUMN. +** pExpr->pLeft Any expression this points to is deleted +** pExpr->pRight Any expression this points to is deleted. +** +** The zDb variable is the name of the database (the "X"). This value may be +** NULL meaning that name is of the form Y.Z or Z. Any available database +** can be used. The zTable variable is the name of the table (the "Y"). This +** value can be NULL if zDb is also NULL. If zTable is NULL it +** means that the form of the name is Z and that columns from any table +** can be used. +** +** If the name cannot be resolved unambiguously, leave an error message +** in pParse and return WRC_Abort. Return WRC_Prune on success. +*/ +static int lookupName( + Parse *pParse, /* The parsing context */ + const char *zDb, /* Name of the database containing table, or NULL */ + const char *zTab, /* Name of table containing column, or NULL */ + const char *zCol, /* Name of the column. */ + NameContext *pNC, /* The name context used to resolve the name */ + Expr *pExpr /* Make this EXPR node point to the selected column */ +){ + int i, j; /* Loop counters */ + int cnt = 0; /* Number of matching column names */ + int cntTab = 0; /* Number of matching table names */ + int nSubquery = 0; /* How many levels of subquery */ + sqlite3 *db = pParse->db; /* The database connection */ + struct SrcList_item *pItem; /* Use for looping over pSrcList items */ + struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ + NameContext *pTopNC = pNC; /* First namecontext in the list */ + Schema *pSchema = 0; /* Schema of the expression */ + int isTrigger = 0; + + assert( pNC ); /* the name context cannot be NULL. */ + assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ + assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); + + /* Initialize the node to no-match */ + pExpr->iTable = -1; + pExpr->pTab = 0; + ExprSetVVAProperty(pExpr, EP_NoReduce); + + /* Translate the schema name in zDb into a pointer to the corresponding + ** schema. If not found, pSchema will remain NULL and nothing will match + ** resulting in an appropriate error message toward the end of this routine + */ + if( zDb ){ + testcase( pNC->ncFlags & NC_PartIdx ); + testcase( pNC->ncFlags & NC_IsCheck ); + if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ + /* Silently ignore database qualifiers inside CHECK constraints and partial + ** indices. Do not raise errors because that might break legacy and + ** because it does not hurt anything to just ignore the database name. */ + zDb = 0; + }else{ + for(i=0; inDb; i++){ + assert( db->aDb[i].zName ); + if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){ + pSchema = db->aDb[i].pSchema; + break; + } + } + } + } + + /* Start at the inner-most context and move outward until a match is found */ + while( pNC && cnt==0 ){ + ExprList *pEList; + SrcList *pSrcList = pNC->pSrcList; + + if( pSrcList ){ + for(i=0, pItem=pSrcList->a; inSrc; i++, pItem++){ + Table *pTab; + Column *pCol; + + pTab = pItem->pTab; + assert( pTab!=0 && pTab->zName!=0 ); + assert( pTab->nCol>0 ); + if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ + int hit = 0; + pEList = pItem->pSelect->pEList; + for(j=0; jnExpr; j++){ + if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ + cnt++; + cntTab = 2; + pMatch = pItem; + pExpr->iColumn = j; + hit = 1; + } + } + if( hit || zTab==0 ) continue; + } + if( zDb && pTab->pSchema!=pSchema ){ + continue; + } + if( zTab ){ + const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; + assert( zTabName!=0 ); + if( sqlite3StrICmp(zTabName, zTab)!=0 ){ + continue; + } + } + if( 0==(cntTab++) ){ + pMatch = pItem; + } + for(j=0, pCol=pTab->aCol; jnCol; j++, pCol++){ + if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ + /* If there has been exactly one prior match and this match + ** is for the right-hand table of a NATURAL JOIN or is in a + ** USING clause, then skip this match. + */ + if( cnt==1 ){ + if( pItem->jointype & JT_NATURAL ) continue; + if( nameInUsingClause(pItem->pUsing, zCol) ) continue; + } + cnt++; + pMatch = pItem; + /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ + pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; + break; + } + } + } + if( pMatch ){ + pExpr->iTable = pMatch->iCursor; + pExpr->pTab = pMatch->pTab; + pSchema = pExpr->pTab->pSchema; + } + } /* if( pSrcList ) */ + +#ifndef SQLITE_OMIT_TRIGGER + /* If we have not already resolved the name, then maybe + ** it is a new.* or old.* trigger argument reference + */ + if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){ + int op = pParse->eTriggerOp; + Table *pTab = 0; + assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); + if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ + pExpr->iTable = 1; + pTab = pParse->pTriggerTab; + }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ + pExpr->iTable = 0; + pTab = pParse->pTriggerTab; + } + + if( pTab ){ + int iCol; + pSchema = pTab->pSchema; + cntTab++; + for(iCol=0; iColnCol; iCol++){ + Column *pCol = &pTab->aCol[iCol]; + if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ + if( iCol==pTab->iPKey ){ + iCol = -1; + } + break; + } + } + if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){ + iCol = -1; /* IMP: R-44911-55124 */ + } + if( iColnCol ){ + cnt++; + if( iCol<0 ){ + pExpr->affinity = SQLITE_AFF_INTEGER; + }else if( pExpr->iTable==0 ){ + testcase( iCol==31 ); + testcase( iCol==32 ); + pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<iColumn = (i16)iCol; + pExpr->pTab = pTab; + isTrigger = 1; + } + } + } +#endif /* !defined(SQLITE_OMIT_TRIGGER) */ + + /* + ** Perhaps the name is a reference to the ROWID + */ + if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){ + cnt = 1; + pExpr->iColumn = -1; /* IMP: R-44911-55124 */ + pExpr->affinity = SQLITE_AFF_INTEGER; + } + + /* + ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z + ** might refer to an result-set alias. This happens, for example, when + ** we are resolving names in the WHERE clause of the following command: + ** + ** SELECT a+b AS x FROM table WHERE x<10; + ** + ** In cases like this, replace pExpr with a copy of the expression that + ** forms the result set entry ("a+b" in the example) and return immediately. + ** Note that the expression in the result set should have already been + ** resolved by the time the WHERE clause is resolved. + ** + ** The ability to use an output result-set column in the WHERE, GROUP BY, + ** or HAVING clauses, or as part of a larger expression in the ORDRE BY + ** clause is not standard SQL. This is a (goofy) SQLite extension, that + ** is supported for backwards compatibility only. TO DO: Issue a warning + ** on sqlite3_log() whenever the capability is used. + */ + if( (pEList = pNC->pEList)!=0 + && zTab==0 + && cnt==0 + ){ + for(j=0; jnExpr; j++){ + char *zAs = pEList->a[j].zName; + if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ + Expr *pOrig; + assert( pExpr->pLeft==0 && pExpr->pRight==0 ); + assert( pExpr->x.pList==0 ); + assert( pExpr->x.pSelect==0 ); + pOrig = pEList->a[j].pExpr; + if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ + sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); + return WRC_Abort; + } + resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); + cnt = 1; + pMatch = 0; + assert( zTab==0 && zDb==0 ); + goto lookupname_end; + } + } + } + + /* Advance to the next name context. The loop will exit when either + ** we have a match (cnt>0) or when we run out of name contexts. + */ + if( cnt==0 ){ + pNC = pNC->pNext; + nSubquery++; + } + } + + /* + ** If X and Y are NULL (in other words if only the column name Z is + ** supplied) and the value of Z is enclosed in double-quotes, then + ** Z is a string literal if it doesn't match any column names. In that + ** case, we need to return right away and not make any changes to + ** pExpr. + ** + ** Because no reference was made to outer contexts, the pNC->nRef + ** fields are not changed in any context. + */ + if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){ + pExpr->op = TK_STRING; + pExpr->pTab = 0; + return WRC_Prune; + } + + /* + ** cnt==0 means there was not match. cnt>1 means there were two or + ** more matches. Either way, we have an error. + */ + if( cnt!=1 ){ + const char *zErr; + zErr = cnt==0 ? "no such column" : "ambiguous column name"; + if( zDb ){ + sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); + }else if( zTab ){ + sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); + }else{ + sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); + } + pParse->checkSchema = 1; + pTopNC->nErr++; + } + + /* If a column from a table in pSrcList is referenced, then record + ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes + ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the + ** column number is greater than the number of bits in the bitmask + ** then set the high-order bit of the bitmask. + */ + if( pExpr->iColumn>=0 && pMatch!=0 ){ + int n = pExpr->iColumn; + testcase( n==BMS-1 ); + if( n>=BMS ){ + n = BMS-1; + } + assert( pMatch->iCursor==pExpr->iTable ); + pMatch->colUsed |= ((Bitmask)1)<pLeft); + pExpr->pLeft = 0; + sqlite3ExprDelete(db, pExpr->pRight); + pExpr->pRight = 0; + pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN); +lookupname_end: + if( cnt==1 ){ + assert( pNC!=0 ); + if( pExpr->op!=TK_AS ){ + sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); + } + /* Increment the nRef value on all name contexts from TopNC up to + ** the point where the name matched. */ + for(;;){ + assert( pTopNC!=0 ); + pTopNC->nRef++; + if( pTopNC==pNC ) break; + pTopNC = pTopNC->pNext; + } + return WRC_Prune; + } else { + return WRC_Abort; + } +} + +/* +** Allocate and return a pointer to an expression to load the column iCol +** from datasource iSrc in SrcList pSrc. +*/ +Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ + Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0); + if( p ){ + struct SrcList_item *pItem = &pSrc->a[iSrc]; + p->pTab = pItem->pTab; + p->iTable = pItem->iCursor; + if( p->pTab->iPKey==iCol ){ + p->iColumn = -1; + }else{ + p->iColumn = (ynVar)iCol; + testcase( iCol==BMS ); + testcase( iCol==BMS-1 ); + pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); + } + ExprSetProperty(p, EP_Resolved); + } + return p; +} + +/* +** Report an error that an expression is not valid for a partial index WHERE +** clause. +*/ +static void notValidPartIdxWhere( + Parse *pParse, /* Leave error message here */ + NameContext *pNC, /* The name context */ + const char *zMsg /* Type of error */ +){ + if( (pNC->ncFlags & NC_PartIdx)!=0 ){ + sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses", + zMsg); + } +} + +#ifndef SQLITE_OMIT_CHECK +/* +** Report an error that an expression is not valid for a CHECK constraint. +*/ +static void notValidCheckConstraint( + Parse *pParse, /* Leave error message here */ + NameContext *pNC, /* The name context */ + const char *zMsg /* Type of error */ +){ + if( (pNC->ncFlags & NC_IsCheck)!=0 ){ + sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg); + } +} +#else +# define notValidCheckConstraint(P,N,M) +#endif + +/* +** Expression p should encode a floating point value between 1.0 and 0.0. +** Return 1024 times this value. Or return -1 if p is not a floating point +** value between 1.0 and 0.0. +*/ +static int exprProbability(Expr *p){ + double r = -1.0; + if( p->op!=TK_FLOAT ) return -1; + sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); + assert( r>=0.0 ); + if( r>1.0 ) return -1; + return (int)(r*1000.0); +} + +/* +** This routine is callback for sqlite3WalkExpr(). +** +** Resolve symbolic names into TK_COLUMN operators for the current +** node in the expression tree. Return 0 to continue the search down +** the tree or 2 to abort the tree walk. +** +** This routine also does error checking and name resolution for +** function names. The operator for aggregate functions is changed +** to TK_AGG_FUNCTION. +*/ +static int resolveExprStep(Walker *pWalker, Expr *pExpr){ + NameContext *pNC; + Parse *pParse; + + pNC = pWalker->u.pNC; + assert( pNC!=0 ); + pParse = pNC->pParse; + assert( pParse==pWalker->pParse ); + + if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune; + ExprSetProperty(pExpr, EP_Resolved); +#ifndef NDEBUG + if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ + SrcList *pSrcList = pNC->pSrcList; + int i; + for(i=0; ipSrcList->nSrc; i++){ + assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursornTab); + } + } +#endif + switch( pExpr->op ){ + +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) + /* The special operator TK_ROW means use the rowid for the first + ** column in the FROM clause. This is used by the LIMIT and ORDER BY + ** clause processing on UPDATE and DELETE statements. + */ + case TK_ROW: { + SrcList *pSrcList = pNC->pSrcList; + struct SrcList_item *pItem; + assert( pSrcList && pSrcList->nSrc==1 ); + pItem = pSrcList->a; + pExpr->op = TK_COLUMN; + pExpr->pTab = pItem->pTab; + pExpr->iTable = pItem->iCursor; + pExpr->iColumn = -1; + pExpr->affinity = SQLITE_AFF_INTEGER; + break; + } +#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ + + /* A lone identifier is the name of a column. + */ + case TK_ID: { + return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr); + } + + /* A table name and column name: ID.ID + ** Or a database, table and column: ID.ID.ID + */ + case TK_DOT: { + const char *zColumn; + const char *zTable; + const char *zDb; + Expr *pRight; + + /* if( pSrcList==0 ) break; */ + pRight = pExpr->pRight; + if( pRight->op==TK_ID ){ + zDb = 0; + zTable = pExpr->pLeft->u.zToken; + zColumn = pRight->u.zToken; + }else{ + assert( pRight->op==TK_DOT ); + zDb = pExpr->pLeft->u.zToken; + zTable = pRight->pLeft->u.zToken; + zColumn = pRight->pRight->u.zToken; + } + return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); + } + + /* Resolve function names + */ + case TK_CONST_FUNC: + case TK_FUNCTION: { + ExprList *pList = pExpr->x.pList; /* The argument list */ + int n = pList ? pList->nExpr : 0; /* Number of arguments */ + int no_such_func = 0; /* True if no such function exists */ + int wrong_num_args = 0; /* True if wrong number of arguments */ + int is_agg = 0; /* True if is an aggregate function */ + int auth; /* Authorization to use the function */ + int nId; /* Number of characters in function name */ + const char *zId; /* The function name. */ + FuncDef *pDef; /* Information about the function */ + u8 enc = ENC(pParse->db); /* The database encoding */ + + testcase( pExpr->op==TK_CONST_FUNC ); + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); + notValidPartIdxWhere(pParse, pNC, "functions"); + zId = pExpr->u.zToken; + nId = sqlite3Strlen30(zId); + pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0); + if( pDef==0 ){ + pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0); + if( pDef==0 ){ + no_such_func = 1; + }else{ + wrong_num_args = 1; + } + }else{ + is_agg = pDef->xFunc==0; + if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ + ExprSetProperty(pExpr, EP_Unlikely|EP_Skip); + if( n==2 ){ + pExpr->iTable = exprProbability(pList->a[1].pExpr); + if( pExpr->iTable<0 ){ + sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a " + "constant between 0.0 and 1.0"); + pNC->nErr++; + } + }else{ + /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to + ** likelihood(X, 0.0625). + ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for + ** likelihood(X,0.0625). */ + pExpr->iTable = 62; /* TUNING: Default 2nd arg to unlikely() is 0.0625 */ + } + } + } +#ifndef SQLITE_OMIT_AUTHORIZATION + if( pDef ){ + auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0); + if( auth!=SQLITE_OK ){ + if( auth==SQLITE_DENY ){ + sqlite3ErrorMsg(pParse, "not authorized to use function: %s", + pDef->zName); + pNC->nErr++; + } + pExpr->op = TK_NULL; + return WRC_Prune; + } + } +#endif + if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){ + sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId); + pNC->nErr++; + is_agg = 0; + }else if( no_such_func && pParse->db->init.busy==0 ){ + sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); + pNC->nErr++; + }else if( wrong_num_args ){ + sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", + nId, zId); + pNC->nErr++; + } + if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg; + sqlite3WalkExprList(pWalker, pList); + if( is_agg ){ + NameContext *pNC2 = pNC; + pExpr->op = TK_AGG_FUNCTION; + pExpr->op2 = 0; + while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ + pExpr->op2++; + pNC2 = pNC2->pNext; + } + if( pNC2 ) pNC2->ncFlags |= NC_HasAgg; + pNC->ncFlags |= NC_AllowAgg; + } + /* FIX ME: Compute pExpr->affinity based on the expected return + ** type of the function + */ + return WRC_Prune; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_SELECT: + case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); +#endif + case TK_IN: { + testcase( pExpr->op==TK_IN ); + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + int nRef = pNC->nRef; + notValidCheckConstraint(pParse, pNC, "subqueries"); + notValidPartIdxWhere(pParse, pNC, "subqueries"); + sqlite3WalkSelect(pWalker, pExpr->x.pSelect); + assert( pNC->nRef>=nRef ); + if( nRef!=pNC->nRef ){ + ExprSetProperty(pExpr, EP_VarSelect); + } + } + break; + } + case TK_VARIABLE: { + notValidCheckConstraint(pParse, pNC, "parameters"); + notValidPartIdxWhere(pParse, pNC, "parameters"); + break; + } + } + return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue; +} + +/* +** pEList is a list of expressions which are really the result set of the +** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. +** This routine checks to see if pE is a simple identifier which corresponds +** to the AS-name of one of the terms of the expression list. If it is, +** this routine return an integer between 1 and N where N is the number of +** elements in pEList, corresponding to the matching entry. If there is +** no match, or if pE is not a simple identifier, then this routine +** return 0. +** +** pEList has been resolved. pE has not. +*/ +static int resolveAsName( + Parse *pParse, /* Parsing context for error messages */ + ExprList *pEList, /* List of expressions to scan */ + Expr *pE /* Expression we are trying to match */ +){ + int i; /* Loop counter */ + + UNUSED_PARAMETER(pParse); + + if( pE->op==TK_ID ){ + char *zCol = pE->u.zToken; + for(i=0; inExpr; i++){ + char *zAs = pEList->a[i].zName; + if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ + return i+1; + } + } + } + return 0; +} + +/* +** pE is a pointer to an expression which is a single term in the +** ORDER BY of a compound SELECT. The expression has not been +** name resolved. +** +** At the point this routine is called, we already know that the +** ORDER BY term is not an integer index into the result set. That +** case is handled by the calling routine. +** +** Attempt to match pE against result set columns in the left-most +** SELECT statement. Return the index i of the matching column, +** as an indication to the caller that it should sort by the i-th column. +** The left-most column is 1. In other words, the value returned is the +** same integer value that would be used in the SQL statement to indicate +** the column. +** +** If there is no match, return 0. Return -1 if an error occurs. +*/ +static int resolveOrderByTermToExprList( + Parse *pParse, /* Parsing context for error messages */ + Select *pSelect, /* The SELECT statement with the ORDER BY clause */ + Expr *pE /* The specific ORDER BY term */ +){ + int i; /* Loop counter */ + ExprList *pEList; /* The columns of the result set */ + NameContext nc; /* Name context for resolving pE */ + sqlite3 *db; /* Database connection */ + int rc; /* Return code from subprocedures */ + u8 savedSuppErr; /* Saved value of db->suppressErr */ + + assert( sqlite3ExprIsInteger(pE, &i)==0 ); + pEList = pSelect->pEList; + + /* Resolve all names in the ORDER BY term expression + */ + memset(&nc, 0, sizeof(nc)); + nc.pParse = pParse; + nc.pSrcList = pSelect->pSrc; + nc.pEList = pEList; + nc.ncFlags = NC_AllowAgg; + nc.nErr = 0; + db = pParse->db; + savedSuppErr = db->suppressErr; + db->suppressErr = 1; + rc = sqlite3ResolveExprNames(&nc, pE); + db->suppressErr = savedSuppErr; + if( rc ) return 0; + + /* Try to match the ORDER BY expression against an expression + ** in the result set. Return an 1-based index of the matching + ** result-set entry. + */ + for(i=0; inExpr; i++){ + if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){ + return i+1; + } + } + + /* If no match, return 0. */ + return 0; +} + +/* +** Generate an ORDER BY or GROUP BY term out-of-range error. +*/ +static void resolveOutOfRangeError( + Parse *pParse, /* The error context into which to write the error */ + const char *zType, /* "ORDER" or "GROUP" */ + int i, /* The index (1-based) of the term out of range */ + int mx /* Largest permissible value of i */ +){ + sqlite3ErrorMsg(pParse, + "%r %s BY term out of range - should be " + "between 1 and %d", i, zType, mx); +} + +/* +** Analyze the ORDER BY clause in a compound SELECT statement. Modify +** each term of the ORDER BY clause is a constant integer between 1 +** and N where N is the number of columns in the compound SELECT. +** +** ORDER BY terms that are already an integer between 1 and N are +** unmodified. ORDER BY terms that are integers outside the range of +** 1 through N generate an error. ORDER BY terms that are expressions +** are matched against result set expressions of compound SELECT +** beginning with the left-most SELECT and working toward the right. +** At the first match, the ORDER BY expression is transformed into +** the integer column number. +** +** Return the number of errors seen. +*/ +static int resolveCompoundOrderBy( + Parse *pParse, /* Parsing context. Leave error messages here */ + Select *pSelect /* The SELECT statement containing the ORDER BY */ +){ + int i; + ExprList *pOrderBy; + ExprList *pEList; + sqlite3 *db; + int moreToDo = 1; + + pOrderBy = pSelect->pOrderBy; + if( pOrderBy==0 ) return 0; + db = pParse->db; +#if SQLITE_MAX_COLUMN + if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); + return 1; + } +#endif + for(i=0; inExpr; i++){ + pOrderBy->a[i].done = 0; + } + pSelect->pNext = 0; + while( pSelect->pPrior ){ + pSelect->pPrior->pNext = pSelect; + pSelect = pSelect->pPrior; + } + while( pSelect && moreToDo ){ + struct ExprList_item *pItem; + moreToDo = 0; + pEList = pSelect->pEList; + assert( pEList!=0 ); + for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ + int iCol = -1; + Expr *pE, *pDup; + if( pItem->done ) continue; + pE = sqlite3ExprSkipCollate(pItem->pExpr); + if( sqlite3ExprIsInteger(pE, &iCol) ){ + if( iCol<=0 || iCol>pEList->nExpr ){ + resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr); + return 1; + } + }else{ + iCol = resolveAsName(pParse, pEList, pE); + if( iCol==0 ){ + pDup = sqlite3ExprDup(db, pE, 0); + if( !db->mallocFailed ){ + assert(pDup); + iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); + } + sqlite3ExprDelete(db, pDup); + } + } + if( iCol>0 ){ + /* Convert the ORDER BY term into an integer column number iCol, + ** taking care to preserve the COLLATE clause if it exists */ + Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); + if( pNew==0 ) return 1; + pNew->flags |= EP_IntValue; + pNew->u.iValue = iCol; + if( pItem->pExpr==pE ){ + pItem->pExpr = pNew; + }else{ + assert( pItem->pExpr->op==TK_COLLATE ); + assert( pItem->pExpr->pLeft==pE ); + pItem->pExpr->pLeft = pNew; + } + sqlite3ExprDelete(db, pE); + pItem->iOrderByCol = (u16)iCol; + pItem->done = 1; + }else{ + moreToDo = 1; + } + } + pSelect = pSelect->pNext; + } + for(i=0; inExpr; i++){ + if( pOrderBy->a[i].done==0 ){ + sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " + "column in the result set", i+1); + return 1; + } + } + return 0; +} + +/* +** Check every term in the ORDER BY or GROUP BY clause pOrderBy of +** the SELECT statement pSelect. If any term is reference to a +** result set expression (as determined by the ExprList.a.iOrderByCol field) +** then convert that term into a copy of the corresponding result set +** column. +** +** If any errors are detected, add an error message to pParse and +** return non-zero. Return zero if no errors are seen. +*/ +int sqlite3ResolveOrderGroupBy( + Parse *pParse, /* Parsing context. Leave error messages here */ + Select *pSelect, /* The SELECT statement containing the clause */ + ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ + const char *zType /* "ORDER" or "GROUP" */ +){ + int i; + sqlite3 *db = pParse->db; + ExprList *pEList; + struct ExprList_item *pItem; + + if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; +#if SQLITE_MAX_COLUMN + if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); + return 1; + } +#endif + pEList = pSelect->pEList; + assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ + for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ + if( pItem->iOrderByCol ){ + if( pItem->iOrderByCol>pEList->nExpr ){ + resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr); + return 1; + } + resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0); + } + } + return 0; +} + +/* +** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. +** The Name context of the SELECT statement is pNC. zType is either +** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. +** +** This routine resolves each term of the clause into an expression. +** If the order-by term is an integer I between 1 and N (where N is the +** number of columns in the result set of the SELECT) then the expression +** in the resolution is a copy of the I-th result-set expression. If +** the order-by term is an identifier that corresponds to the AS-name of +** a result-set expression, then the term resolves to a copy of the +** result-set expression. Otherwise, the expression is resolved in +** the usual way - using sqlite3ResolveExprNames(). +** +** This routine returns the number of errors. If errors occur, then +** an appropriate error message might be left in pParse. (OOM errors +** excepted.) +*/ +static int resolveOrderGroupBy( + NameContext *pNC, /* The name context of the SELECT statement */ + Select *pSelect, /* The SELECT statement holding pOrderBy */ + ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ + const char *zType /* Either "ORDER" or "GROUP", as appropriate */ +){ + int i, j; /* Loop counters */ + int iCol; /* Column number */ + struct ExprList_item *pItem; /* A term of the ORDER BY clause */ + Parse *pParse; /* Parsing context */ + int nResult; /* Number of terms in the result set */ + + if( pOrderBy==0 ) return 0; + nResult = pSelect->pEList->nExpr; + pParse = pNC->pParse; + for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ + Expr *pE = pItem->pExpr; + Expr *pE2 = sqlite3ExprSkipCollate(pE); + if( zType[0]!='G' ){ + iCol = resolveAsName(pParse, pSelect->pEList, pE2); + if( iCol>0 ){ + /* If an AS-name match is found, mark this ORDER BY column as being + ** a copy of the iCol-th result-set column. The subsequent call to + ** sqlite3ResolveOrderGroupBy() will convert the expression to a + ** copy of the iCol-th result-set expression. */ + pItem->iOrderByCol = (u16)iCol; + continue; + } + } + if( sqlite3ExprIsInteger(pE2, &iCol) ){ + /* The ORDER BY term is an integer constant. Again, set the column + ** number so that sqlite3ResolveOrderGroupBy() will convert the + ** order-by term to a copy of the result-set expression */ + if( iCol<1 || iCol>0xffff ){ + resolveOutOfRangeError(pParse, zType, i+1, nResult); + return 1; + } + pItem->iOrderByCol = (u16)iCol; + continue; + } + + /* Otherwise, treat the ORDER BY term as an ordinary expression */ + pItem->iOrderByCol = 0; + if( sqlite3ResolveExprNames(pNC, pE) ){ + return 1; + } + for(j=0; jpEList->nExpr; j++){ + if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ + pItem->iOrderByCol = j+1; + } + } + } + return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); +} + +/* +** Resolve names in the SELECT statement p and all of its descendents. +*/ +static int resolveSelectStep(Walker *pWalker, Select *p){ + NameContext *pOuterNC; /* Context that contains this SELECT */ + NameContext sNC; /* Name context of this SELECT */ + int isCompound; /* True if p is a compound select */ + int nCompound; /* Number of compound terms processed so far */ + Parse *pParse; /* Parsing context */ + ExprList *pEList; /* Result set expression list */ + int i; /* Loop counter */ + ExprList *pGroupBy; /* The GROUP BY clause */ + Select *pLeftmost; /* Left-most of SELECT of a compound */ + sqlite3 *db; /* Database connection */ + + + assert( p!=0 ); + if( p->selFlags & SF_Resolved ){ + return WRC_Prune; + } + pOuterNC = pWalker->u.pNC; + pParse = pWalker->pParse; + db = pParse->db; + + /* Normally sqlite3SelectExpand() will be called first and will have + ** already expanded this SELECT. However, if this is a subquery within + ** an expression, sqlite3ResolveExprNames() will be called without a + ** prior call to sqlite3SelectExpand(). When that happens, let + ** sqlite3SelectPrep() do all of the processing for this SELECT. + ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and + ** this routine in the correct order. + */ + if( (p->selFlags & SF_Expanded)==0 ){ + sqlite3SelectPrep(pParse, p, pOuterNC); + return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune; + } + + isCompound = p->pPrior!=0; + nCompound = 0; + pLeftmost = p; + while( p ){ + assert( (p->selFlags & SF_Expanded)!=0 ); + assert( (p->selFlags & SF_Resolved)==0 ); + p->selFlags |= SF_Resolved; + + /* Resolve the expressions in the LIMIT and OFFSET clauses. These + ** are not allowed to refer to any names, so pass an empty NameContext. + */ + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + if( sqlite3ResolveExprNames(&sNC, p->pLimit) || + sqlite3ResolveExprNames(&sNC, p->pOffset) ){ + return WRC_Abort; + } + + /* Recursively resolve names in all subqueries + */ + for(i=0; ipSrc->nSrc; i++){ + struct SrcList_item *pItem = &p->pSrc->a[i]; + if( pItem->pSelect ){ + NameContext *pNC; /* Used to iterate name contexts */ + int nRef = 0; /* Refcount for pOuterNC and outer contexts */ + const char *zSavedContext = pParse->zAuthContext; + + /* Count the total number of references to pOuterNC and all of its + ** parent contexts. After resolving references to expressions in + ** pItem->pSelect, check if this value has changed. If so, then + ** SELECT statement pItem->pSelect must be correlated. Set the + ** pItem->isCorrelated flag if this is the case. */ + for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef; + + if( pItem->zName ) pParse->zAuthContext = pItem->zName; + sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); + pParse->zAuthContext = zSavedContext; + if( pParse->nErr || db->mallocFailed ) return WRC_Abort; + + for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef; + assert( pItem->isCorrelated==0 && nRef<=0 ); + pItem->isCorrelated = (nRef!=0); + } + } + + /* Set up the local name-context to pass to sqlite3ResolveExprNames() to + ** resolve the result-set expression list. + */ + sNC.ncFlags = NC_AllowAgg; + sNC.pSrcList = p->pSrc; + sNC.pNext = pOuterNC; + + /* Resolve names in the result set. */ + pEList = p->pEList; + assert( pEList!=0 ); + for(i=0; inExpr; i++){ + Expr *pX = pEList->a[i].pExpr; + if( sqlite3ResolveExprNames(&sNC, pX) ){ + return WRC_Abort; + } + } + + /* If there are no aggregate functions in the result-set, and no GROUP BY + ** expression, do not allow aggregates in any of the other expressions. + */ + assert( (p->selFlags & SF_Aggregate)==0 ); + pGroupBy = p->pGroupBy; + if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){ + p->selFlags |= SF_Aggregate; + }else{ + sNC.ncFlags &= ~NC_AllowAgg; + } + + /* If a HAVING clause is present, then there must be a GROUP BY clause. + */ + if( p->pHaving && !pGroupBy ){ + sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); + return WRC_Abort; + } + + /* Add the output column list to the name-context before parsing the + ** other expressions in the SELECT statement. This is so that + ** expressions in the WHERE clause (etc.) can refer to expressions by + ** aliases in the result set. + ** + ** Minor point: If this is the case, then the expression will be + ** re-evaluated for each reference to it. + */ + sNC.pEList = p->pEList; + if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; + if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; + + /* The ORDER BY and GROUP BY clauses may not refer to terms in + ** outer queries + */ + sNC.pNext = 0; + sNC.ncFlags |= NC_AllowAgg; + + /* Process the ORDER BY clause for singleton SELECT statements. + ** The ORDER BY clause for compounds SELECT statements is handled + ** below, after all of the result-sets for all of the elements of + ** the compound have been resolved. + */ + if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){ + return WRC_Abort; + } + if( db->mallocFailed ){ + return WRC_Abort; + } + + /* Resolve the GROUP BY clause. At the same time, make sure + ** the GROUP BY clause does not contain aggregate functions. + */ + if( pGroupBy ){ + struct ExprList_item *pItem; + + if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){ + return WRC_Abort; + } + for(i=0, pItem=pGroupBy->a; inExpr; i++, pItem++){ + if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ + sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " + "the GROUP BY clause"); + return WRC_Abort; + } + } + } + + /* Advance to the next term of the compound + */ + p = p->pPrior; + nCompound++; + } + + /* Resolve the ORDER BY on a compound SELECT after all terms of + ** the compound have been resolved. + */ + if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){ + return WRC_Abort; + } + + return WRC_Prune; +} + +/* +** This routine walks an expression tree and resolves references to +** table columns and result-set columns. At the same time, do error +** checking on function usage and set a flag if any aggregate functions +** are seen. +** +** To resolve table columns references we look for nodes (or subtrees) of the +** form X.Y.Z or Y.Z or just Z where +** +** X: The name of a database. Ex: "main" or "temp" or +** the symbolic name assigned to an ATTACH-ed database. +** +** Y: The name of a table in a FROM clause. Or in a trigger +** one of the special names "old" or "new". +** +** Z: The name of a column in table Y. +** +** The node at the root of the subtree is modified as follows: +** +** Expr.op Changed to TK_COLUMN +** Expr.pTab Points to the Table object for X.Y +** Expr.iColumn The column index in X.Y. -1 for the rowid. +** Expr.iTable The VDBE cursor number for X.Y +** +** +** To resolve result-set references, look for expression nodes of the +** form Z (with no X and Y prefix) where the Z matches the right-hand +** size of an AS clause in the result-set of a SELECT. The Z expression +** is replaced by a copy of the left-hand side of the result-set expression. +** Table-name and function resolution occurs on the substituted expression +** tree. For example, in: +** +** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; +** +** The "x" term of the order by is replaced by "a+b" to render: +** +** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; +** +** Function calls are checked to make sure that the function is +** defined and that the correct number of arguments are specified. +** If the function is an aggregate function, then the NC_HasAgg flag is +** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. +** If an expression contains aggregate functions then the EP_Agg +** property on the expression is set. +** +** An error message is left in pParse if anything is amiss. The number +** if errors is returned. +*/ +int sqlite3ResolveExprNames( + NameContext *pNC, /* Namespace to resolve expressions in. */ + Expr *pExpr /* The expression to be analyzed. */ +){ + u8 savedHasAgg; + Walker w; + + if( pExpr==0 ) return 0; +#if SQLITE_MAX_EXPR_DEPTH>0 + { + Parse *pParse = pNC->pParse; + if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){ + return 1; + } + pParse->nHeight += pExpr->nHeight; + } +#endif + savedHasAgg = pNC->ncFlags & NC_HasAgg; + pNC->ncFlags &= ~NC_HasAgg; + memset(&w, 0, sizeof(w)); + w.xExprCallback = resolveExprStep; + w.xSelectCallback = resolveSelectStep; + w.pParse = pNC->pParse; + w.u.pNC = pNC; + sqlite3WalkExpr(&w, pExpr); +#if SQLITE_MAX_EXPR_DEPTH>0 + pNC->pParse->nHeight -= pExpr->nHeight; +#endif + if( pNC->nErr>0 || w.pParse->nErr>0 ){ + ExprSetProperty(pExpr, EP_Error); + } + if( pNC->ncFlags & NC_HasAgg ){ + ExprSetProperty(pExpr, EP_Agg); + }else if( savedHasAgg ){ + pNC->ncFlags |= NC_HasAgg; + } + return ExprHasProperty(pExpr, EP_Error); +} + + +/* +** Resolve all names in all expressions of a SELECT and in all +** decendents of the SELECT, including compounds off of p->pPrior, +** subqueries in expressions, and subqueries used as FROM clause +** terms. +** +** See sqlite3ResolveExprNames() for a description of the kinds of +** transformations that occur. +** +** All SELECT statements should have been expanded using +** sqlite3SelectExpand() prior to invoking this routine. +*/ +void sqlite3ResolveSelectNames( + Parse *pParse, /* The parser context */ + Select *p, /* The SELECT statement being coded. */ + NameContext *pOuterNC /* Name context for parent SELECT statement */ +){ + Walker w; + + assert( p!=0 ); + memset(&w, 0, sizeof(w)); + w.xExprCallback = resolveExprStep; + w.xSelectCallback = resolveSelectStep; + w.pParse = pParse; + w.u.pNC = pOuterNC; + sqlite3WalkSelect(&w, p); +} + +/* +** Resolve names in expressions that can only reference a single table: +** +** * CHECK constraints +** * WHERE clauses on partial indices +** +** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression +** is set to -1 and the Expr.iColumn value is set to the column number. +** +** Any errors cause an error message to be set in pParse. +*/ +void sqlite3ResolveSelfReference( + Parse *pParse, /* Parsing context */ + Table *pTab, /* The table being referenced */ + int type, /* NC_IsCheck or NC_PartIdx */ + Expr *pExpr, /* Expression to resolve. May be NULL. */ + ExprList *pList /* Expression list to resolve. May be NUL. */ +){ + SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ + NameContext sNC; /* Name context for pParse->pNewTable */ + int i; /* Loop counter */ + + assert( type==NC_IsCheck || type==NC_PartIdx ); + memset(&sNC, 0, sizeof(sNC)); + memset(&sSrc, 0, sizeof(sSrc)); + sSrc.nSrc = 1; + sSrc.a[0].zName = pTab->zName; + sSrc.a[0].pTab = pTab; + sSrc.a[0].iCursor = -1; + sNC.pParse = pParse; + sNC.pSrcList = &sSrc; + sNC.ncFlags = type; + if( sqlite3ResolveExprNames(&sNC, pExpr) ) return; + if( pList ){ + for(i=0; inExpr; i++){ + if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){ + return; + } + } + } +} diff --git a/components/external/SQLite-3.8.1/src/rowset.c b/components/external/SQLite-3.8.1/src/rowset.c new file mode 100644 index 0000000000000000000000000000000000000000..5761f98550b176cce11dcbcec93899a075bb64fd --- /dev/null +++ b/components/external/SQLite-3.8.1/src/rowset.c @@ -0,0 +1,508 @@ +/* +** 2008 December 3 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This module implements an object we call a "RowSet". +** +** The RowSet object is a collection of rowids. Rowids +** are inserted into the RowSet in an arbitrary order. Inserts +** can be intermixed with tests to see if a given rowid has been +** previously inserted into the RowSet. +** +** After all inserts are finished, it is possible to extract the +** elements of the RowSet in sorted order. Once this extraction +** process has started, no new elements may be inserted. +** +** Hence, the primitive operations for a RowSet are: +** +** CREATE +** INSERT +** TEST +** SMALLEST +** DESTROY +** +** The CREATE and DESTROY primitives are the constructor and destructor, +** obviously. The INSERT primitive adds a new element to the RowSet. +** TEST checks to see if an element is already in the RowSet. SMALLEST +** extracts the least value from the RowSet. +** +** The INSERT primitive might allocate additional memory. Memory is +** allocated in chunks so most INSERTs do no allocation. There is an +** upper bound on the size of allocated memory. No memory is freed +** until DESTROY. +** +** The TEST primitive includes a "batch" number. The TEST primitive +** will only see elements that were inserted before the last change +** in the batch number. In other words, if an INSERT occurs between +** two TESTs where the TESTs have the same batch nubmer, then the +** value added by the INSERT will not be visible to the second TEST. +** The initial batch number is zero, so if the very first TEST contains +** a non-zero batch number, it will see all prior INSERTs. +** +** No INSERTs may occurs after a SMALLEST. An assertion will fail if +** that is attempted. +** +** The cost of an INSERT is roughly constant. (Sometime new memory +** has to be allocated on an INSERT.) The cost of a TEST with a new +** batch number is O(NlogN) where N is the number of elements in the RowSet. +** The cost of a TEST using the same batch number is O(logN). The cost +** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST +** primitives are constant time. The cost of DESTROY is O(N). +** +** There is an added cost of O(N) when switching between TEST and +** SMALLEST primitives. +*/ +#include "sqliteInt.h" + + +/* +** Target size for allocation chunks. +*/ +#define ROWSET_ALLOCATION_SIZE 1024 + +/* +** The number of rowset entries per allocation chunk. +*/ +#define ROWSET_ENTRY_PER_CHUNK \ + ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry)) + +/* +** Each entry in a RowSet is an instance of the following object. +** +** This same object is reused to store a linked list of trees of RowSetEntry +** objects. In that alternative use, pRight points to the next entry +** in the list, pLeft points to the tree, and v is unused. The +** RowSet.pForest value points to the head of this forest list. +*/ +struct RowSetEntry { + i64 v; /* ROWID value for this entry */ + struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */ + struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */ +}; + +/* +** RowSetEntry objects are allocated in large chunks (instances of the +** following structure) to reduce memory allocation overhead. The +** chunks are kept on a linked list so that they can be deallocated +** when the RowSet is destroyed. +*/ +struct RowSetChunk { + struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */ + struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */ +}; + +/* +** A RowSet in an instance of the following structure. +** +** A typedef of this structure if found in sqliteInt.h. +*/ +struct RowSet { + struct RowSetChunk *pChunk; /* List of all chunk allocations */ + sqlite3 *db; /* The database connection */ + struct RowSetEntry *pEntry; /* List of entries using pRight */ + struct RowSetEntry *pLast; /* Last entry on the pEntry list */ + struct RowSetEntry *pFresh; /* Source of new entry objects */ + struct RowSetEntry *pForest; /* List of binary trees of entries */ + u16 nFresh; /* Number of objects on pFresh */ + u8 rsFlags; /* Various flags */ + u8 iBatch; /* Current insert batch */ +}; + +/* +** Allowed values for RowSet.rsFlags +*/ +#define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */ +#define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */ + +/* +** Turn bulk memory into a RowSet object. N bytes of memory +** are available at pSpace. The db pointer is used as a memory context +** for any subsequent allocations that need to occur. +** Return a pointer to the new RowSet object. +** +** It must be the case that N is sufficient to make a Rowset. If not +** an assertion fault occurs. +** +** If N is larger than the minimum, use the surplus as an initial +** allocation of entries available to be filled. +*/ +RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){ + RowSet *p; + assert( N >= ROUND8(sizeof(*p)) ); + p = pSpace; + p->pChunk = 0; + p->db = db; + p->pEntry = 0; + p->pLast = 0; + p->pForest = 0; + p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); + p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); + p->rsFlags = ROWSET_SORTED; + p->iBatch = 0; + return p; +} + +/* +** Deallocate all chunks from a RowSet. This frees all memory that +** the RowSet has allocated over its lifetime. This routine is +** the destructor for the RowSet. +*/ +void sqlite3RowSetClear(RowSet *p){ + struct RowSetChunk *pChunk, *pNextChunk; + for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){ + pNextChunk = pChunk->pNextChunk; + sqlite3DbFree(p->db, pChunk); + } + p->pChunk = 0; + p->nFresh = 0; + p->pEntry = 0; + p->pLast = 0; + p->pForest = 0; + p->rsFlags = ROWSET_SORTED; +} + +/* +** Allocate a new RowSetEntry object that is associated with the +** given RowSet. Return a pointer to the new and completely uninitialized +** objected. +** +** In an OOM situation, the RowSet.db->mallocFailed flag is set and this +** routine returns NULL. +*/ +static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){ + assert( p!=0 ); + if( p->nFresh==0 ){ + struct RowSetChunk *pNew; + pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew)); + if( pNew==0 ){ + return 0; + } + pNew->pNextChunk = p->pChunk; + p->pChunk = pNew; + p->pFresh = pNew->aEntry; + p->nFresh = ROWSET_ENTRY_PER_CHUNK; + } + p->nFresh--; + return p->pFresh++; +} + +/* +** Insert a new value into a RowSet. +** +** The mallocFailed flag of the database connection is set if a +** memory allocation fails. +*/ +void sqlite3RowSetInsert(RowSet *p, i64 rowid){ + struct RowSetEntry *pEntry; /* The new entry */ + struct RowSetEntry *pLast; /* The last prior entry */ + + /* This routine is never called after sqlite3RowSetNext() */ + assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); + + pEntry = rowSetEntryAlloc(p); + if( pEntry==0 ) return; + pEntry->v = rowid; + pEntry->pRight = 0; + pLast = p->pLast; + if( pLast ){ + if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){ + p->rsFlags &= ~ROWSET_SORTED; + } + pLast->pRight = pEntry; + }else{ + p->pEntry = pEntry; + } + p->pLast = pEntry; +} + +/* +** Merge two lists of RowSetEntry objects. Remove duplicates. +** +** The input lists are connected via pRight pointers and are +** assumed to each already be in sorted order. +*/ +static struct RowSetEntry *rowSetEntryMerge( + struct RowSetEntry *pA, /* First sorted list to be merged */ + struct RowSetEntry *pB /* Second sorted list to be merged */ +){ + struct RowSetEntry head; + struct RowSetEntry *pTail; + + pTail = &head; + while( pA && pB ){ + assert( pA->pRight==0 || pA->v<=pA->pRight->v ); + assert( pB->pRight==0 || pB->v<=pB->pRight->v ); + if( pA->vv ){ + pTail->pRight = pA; + pA = pA->pRight; + pTail = pTail->pRight; + }else if( pB->vv ){ + pTail->pRight = pB; + pB = pB->pRight; + pTail = pTail->pRight; + }else{ + pA = pA->pRight; + } + } + if( pA ){ + assert( pA->pRight==0 || pA->v<=pA->pRight->v ); + pTail->pRight = pA; + }else{ + assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v ); + pTail->pRight = pB; + } + return head.pRight; +} + +/* +** Sort all elements on the list of RowSetEntry objects into order of +** increasing v. +*/ +static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){ + unsigned int i; + struct RowSetEntry *pNext, *aBucket[40]; + + memset(aBucket, 0, sizeof(aBucket)); + while( pIn ){ + pNext = pIn->pRight; + pIn->pRight = 0; + for(i=0; aBucket[i]; i++){ + pIn = rowSetEntryMerge(aBucket[i], pIn); + aBucket[i] = 0; + } + aBucket[i] = pIn; + pIn = pNext; + } + pIn = 0; + for(i=0; ipLeft ){ + struct RowSetEntry *p; + rowSetTreeToList(pIn->pLeft, ppFirst, &p); + p->pRight = pIn; + }else{ + *ppFirst = pIn; + } + if( pIn->pRight ){ + rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast); + }else{ + *ppLast = pIn; + } + assert( (*ppLast)->pRight==0 ); +} + + +/* +** Convert a sorted list of elements (connected by pRight) into a binary +** tree with depth of iDepth. A depth of 1 means the tree contains a single +** node taken from the head of *ppList. A depth of 2 means a tree with +** three nodes. And so forth. +** +** Use as many entries from the input list as required and update the +** *ppList to point to the unused elements of the list. If the input +** list contains too few elements, then construct an incomplete tree +** and leave *ppList set to NULL. +** +** Return a pointer to the root of the constructed binary tree. +*/ +static struct RowSetEntry *rowSetNDeepTree( + struct RowSetEntry **ppList, + int iDepth +){ + struct RowSetEntry *p; /* Root of the new tree */ + struct RowSetEntry *pLeft; /* Left subtree */ + if( *ppList==0 ){ + return 0; + } + if( iDepth==1 ){ + p = *ppList; + *ppList = p->pRight; + p->pLeft = p->pRight = 0; + return p; + } + pLeft = rowSetNDeepTree(ppList, iDepth-1); + p = *ppList; + if( p==0 ){ + return pLeft; + } + p->pLeft = pLeft; + *ppList = p->pRight; + p->pRight = rowSetNDeepTree(ppList, iDepth-1); + return p; +} + +/* +** Convert a sorted list of elements into a binary tree. Make the tree +** as deep as it needs to be in order to contain the entire list. +*/ +static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){ + int iDepth; /* Depth of the tree so far */ + struct RowSetEntry *p; /* Current tree root */ + struct RowSetEntry *pLeft; /* Left subtree */ + + assert( pList!=0 ); + p = pList; + pList = p->pRight; + p->pLeft = p->pRight = 0; + for(iDepth=1; pList; iDepth++){ + pLeft = p; + p = pList; + pList = p->pRight; + p->pLeft = pLeft; + p->pRight = rowSetNDeepTree(&pList, iDepth); + } + return p; +} + +/* +** Take all the entries on p->pEntry and on the trees in p->pForest and +** sort them all together into one big ordered list on p->pEntry. +** +** This routine should only be called once in the life of a RowSet. +*/ +static void rowSetToList(RowSet *p){ + + /* This routine is called only once */ + assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); + + if( (p->rsFlags & ROWSET_SORTED)==0 ){ + p->pEntry = rowSetEntrySort(p->pEntry); + } + + /* While this module could theoretically support it, sqlite3RowSetNext() + ** is never called after sqlite3RowSetText() for the same RowSet. So + ** there is never a forest to deal with. Should this change, simply + ** remove the assert() and the #if 0. */ + assert( p->pForest==0 ); +#if 0 + while( p->pForest ){ + struct RowSetEntry *pTree = p->pForest->pLeft; + if( pTree ){ + struct RowSetEntry *pHead, *pTail; + rowSetTreeToList(pTree, &pHead, &pTail); + p->pEntry = rowSetEntryMerge(p->pEntry, pHead); + } + p->pForest = p->pForest->pRight; + } +#endif + p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */ +} + +/* +** Extract the smallest element from the RowSet. +** Write the element into *pRowid. Return 1 on success. Return +** 0 if the RowSet is already empty. +** +** After this routine has been called, the sqlite3RowSetInsert() +** routine may not be called again. +*/ +int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ + assert( p!=0 ); + + /* Merge the forest into a single sorted list on first call */ + if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p); + + /* Return the next entry on the list */ + if( p->pEntry ){ + *pRowid = p->pEntry->v; + p->pEntry = p->pEntry->pRight; + if( p->pEntry==0 ){ + sqlite3RowSetClear(p); + } + return 1; + }else{ + return 0; + } +} + +/* +** Check to see if element iRowid was inserted into the rowset as +** part of any insert batch prior to iBatch. Return 1 or 0. +** +** If this is the first test of a new batch and if there exist entires +** on pRowSet->pEntry, then sort those entires into the forest at +** pRowSet->pForest so that they can be tested. +*/ +int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){ + struct RowSetEntry *p, *pTree; + + /* This routine is never called after sqlite3RowSetNext() */ + assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 ); + + /* Sort entries into the forest on the first test of a new batch + */ + if( iBatch!=pRowSet->iBatch ){ + p = pRowSet->pEntry; + if( p ){ + struct RowSetEntry **ppPrevTree = &pRowSet->pForest; + if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ + p = rowSetEntrySort(p); + } + for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ + ppPrevTree = &pTree->pRight; + if( pTree->pLeft==0 ){ + pTree->pLeft = rowSetListToTree(p); + break; + }else{ + struct RowSetEntry *pAux, *pTail; + rowSetTreeToList(pTree->pLeft, &pAux, &pTail); + pTree->pLeft = 0; + p = rowSetEntryMerge(pAux, p); + } + } + if( pTree==0 ){ + *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet); + if( pTree ){ + pTree->v = 0; + pTree->pRight = 0; + pTree->pLeft = rowSetListToTree(p); + } + } + pRowSet->pEntry = 0; + pRowSet->pLast = 0; + pRowSet->rsFlags |= ROWSET_SORTED; + } + pRowSet->iBatch = iBatch; + } + + /* Test to see if the iRowid value appears anywhere in the forest. + ** Return 1 if it does and 0 if not. + */ + for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ + p = pTree->pLeft; + while( p ){ + if( p->vpRight; + }else if( p->v>iRowid ){ + p = p->pLeft; + }else{ + return 1; + } + } + } + return 0; +} diff --git a/components/external/SQLite-3.8.1/src/select.c b/components/external/SQLite-3.8.1/src/select.c new file mode 100644 index 0000000000000000000000000000000000000000..badd6249a20888b03cf9ea9cbcf7144a72ed6ca9 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/select.c @@ -0,0 +1,4877 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that are called by the parser +** to handle SELECT statements in SQLite. +*/ +#include "sqliteInt.h" + + +/* +** Delete all the content of a Select structure but do not deallocate +** the select structure itself. +*/ +static void clearSelect(sqlite3 *db, Select *p){ + sqlite3ExprListDelete(db, p->pEList); + sqlite3SrcListDelete(db, p->pSrc); + sqlite3ExprDelete(db, p->pWhere); + sqlite3ExprListDelete(db, p->pGroupBy); + sqlite3ExprDelete(db, p->pHaving); + sqlite3ExprListDelete(db, p->pOrderBy); + sqlite3SelectDelete(db, p->pPrior); + sqlite3ExprDelete(db, p->pLimit); + sqlite3ExprDelete(db, p->pOffset); +} + +/* +** Initialize a SelectDest structure. +*/ +void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ + pDest->eDest = (u8)eDest; + pDest->iSDParm = iParm; + pDest->affSdst = 0; + pDest->iSdst = 0; + pDest->nSdst = 0; +} + + +/* +** Allocate a new Select structure and return a pointer to that +** structure. +*/ +Select *sqlite3SelectNew( + Parse *pParse, /* Parsing context */ + ExprList *pEList, /* which columns to include in the result */ + SrcList *pSrc, /* the FROM clause -- which tables to scan */ + Expr *pWhere, /* the WHERE clause */ + ExprList *pGroupBy, /* the GROUP BY clause */ + Expr *pHaving, /* the HAVING clause */ + ExprList *pOrderBy, /* the ORDER BY clause */ + u16 selFlags, /* Flag parameters, such as SF_Distinct */ + Expr *pLimit, /* LIMIT value. NULL means not used */ + Expr *pOffset /* OFFSET value. NULL means no offset */ +){ + Select *pNew; + Select standin; + sqlite3 *db = pParse->db; + pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); + assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */ + if( pNew==0 ){ + assert( db->mallocFailed ); + pNew = &standin; + memset(pNew, 0, sizeof(*pNew)); + } + if( pEList==0 ){ + pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0)); + } + pNew->pEList = pEList; + if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc)); + pNew->pSrc = pSrc; + pNew->pWhere = pWhere; + pNew->pGroupBy = pGroupBy; + pNew->pHaving = pHaving; + pNew->pOrderBy = pOrderBy; + pNew->selFlags = selFlags; + pNew->op = TK_SELECT; + pNew->pLimit = pLimit; + pNew->pOffset = pOffset; + assert( pOffset==0 || pLimit!=0 ); + pNew->addrOpenEphm[0] = -1; + pNew->addrOpenEphm[1] = -1; + pNew->addrOpenEphm[2] = -1; + if( db->mallocFailed ) { + clearSelect(db, pNew); + if( pNew!=&standin ) sqlite3DbFree(db, pNew); + pNew = 0; + }else{ + assert( pNew->pSrc!=0 || pParse->nErr>0 ); + } + assert( pNew!=&standin ); + return pNew; +} + +/* +** Delete the given Select structure and all of its substructures. +*/ +void sqlite3SelectDelete(sqlite3 *db, Select *p){ + if( p ){ + clearSelect(db, p); + sqlite3DbFree(db, p); + } +} + +/* +** Given 1 to 3 identifiers preceding the JOIN keyword, determine the +** type of join. Return an integer constant that expresses that type +** in terms of the following bit values: +** +** JT_INNER +** JT_CROSS +** JT_OUTER +** JT_NATURAL +** JT_LEFT +** JT_RIGHT +** +** A full outer join is the combination of JT_LEFT and JT_RIGHT. +** +** If an illegal or unsupported join type is seen, then still return +** a join type, but put an error in the pParse structure. +*/ +int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ + int jointype = 0; + Token *apAll[3]; + Token *p; + /* 0123456789 123456789 123456789 123 */ + static const char zKeyText[] = "naturaleftouterightfullinnercross"; + static const struct { + u8 i; /* Beginning of keyword text in zKeyText[] */ + u8 nChar; /* Length of the keyword in characters */ + u8 code; /* Join type mask */ + } aKeyword[] = { + /* natural */ { 0, 7, JT_NATURAL }, + /* left */ { 6, 4, JT_LEFT|JT_OUTER }, + /* outer */ { 10, 5, JT_OUTER }, + /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, + /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, + /* inner */ { 23, 5, JT_INNER }, + /* cross */ { 28, 5, JT_INNER|JT_CROSS }, + }; + int i, j; + apAll[0] = pA; + apAll[1] = pB; + apAll[2] = pC; + for(i=0; i<3 && apAll[i]; i++){ + p = apAll[i]; + for(j=0; jn==aKeyword[j].nChar + && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ + jointype |= aKeyword[j].code; + break; + } + } + testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); + if( j>=ArraySize(aKeyword) ){ + jointype |= JT_ERROR; + break; + } + } + if( + (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || + (jointype & JT_ERROR)!=0 + ){ + const char *zSp = " "; + assert( pB!=0 ); + if( pC==0 ){ zSp++; } + sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " + "%T %T%s%T", pA, pB, zSp, pC); + jointype = JT_INNER; + }else if( (jointype & JT_OUTER)!=0 + && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ + sqlite3ErrorMsg(pParse, + "RIGHT and FULL OUTER JOINs are not currently supported"); + jointype = JT_INNER; + } + return jointype; +} + +/* +** Return the index of a column in a table. Return -1 if the column +** is not contained in the table. +*/ +static int columnIndex(Table *pTab, const char *zCol){ + int i; + for(i=0; inCol; i++){ + if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; + } + return -1; +} + +/* +** Search the first N tables in pSrc, from left to right, looking for a +** table that has a column named zCol. +** +** When found, set *piTab and *piCol to the table index and column index +** of the matching column and return TRUE. +** +** If not found, return FALSE. +*/ +static int tableAndColumnIndex( + SrcList *pSrc, /* Array of tables to search */ + int N, /* Number of tables in pSrc->a[] to search */ + const char *zCol, /* Name of the column we are looking for */ + int *piTab, /* Write index of pSrc->a[] here */ + int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ +){ + int i; /* For looping over tables in pSrc */ + int iCol; /* Index of column matching zCol */ + + assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ + for(i=0; ia[i].pTab, zCol); + if( iCol>=0 ){ + if( piTab ){ + *piTab = i; + *piCol = iCol; + } + return 1; + } + } + return 0; +} + +/* +** This function is used to add terms implied by JOIN syntax to the +** WHERE clause expression of a SELECT statement. The new term, which +** is ANDed with the existing WHERE clause, is of the form: +** +** (tab1.col1 = tab2.col2) +** +** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the +** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is +** column iColRight of tab2. +*/ +static void addWhereTerm( + Parse *pParse, /* Parsing context */ + SrcList *pSrc, /* List of tables in FROM clause */ + int iLeft, /* Index of first table to join in pSrc */ + int iColLeft, /* Index of column in first table */ + int iRight, /* Index of second table in pSrc */ + int iColRight, /* Index of column in second table */ + int isOuterJoin, /* True if this is an OUTER join */ + Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ +){ + sqlite3 *db = pParse->db; + Expr *pE1; + Expr *pE2; + Expr *pEq; + + assert( iLeftnSrc>iRight ); + assert( pSrc->a[iLeft].pTab ); + assert( pSrc->a[iRight].pTab ); + + pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); + pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); + + pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0); + if( pEq && isOuterJoin ){ + ExprSetProperty(pEq, EP_FromJoin); + assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); + ExprSetVVAProperty(pEq, EP_NoReduce); + pEq->iRightJoinTable = (i16)pE2->iTable; + } + *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); +} + +/* +** Set the EP_FromJoin property on all terms of the given expression. +** And set the Expr.iRightJoinTable to iTable for every term in the +** expression. +** +** The EP_FromJoin property is used on terms of an expression to tell +** the LEFT OUTER JOIN processing logic that this term is part of the +** join restriction specified in the ON or USING clause and not a part +** of the more general WHERE clause. These terms are moved over to the +** WHERE clause during join processing but we need to remember that they +** originated in the ON or USING clause. +** +** The Expr.iRightJoinTable tells the WHERE clause processing that the +** expression depends on table iRightJoinTable even if that table is not +** explicitly mentioned in the expression. That information is needed +** for cases like this: +** +** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 +** +** The where clause needs to defer the handling of the t1.x=5 +** term until after the t2 loop of the join. In that way, a +** NULL t2 row will be inserted whenever t1.x!=5. If we do not +** defer the handling of t1.x=5, it will be processed immediately +** after the t1 loop and rows with t1.x!=5 will never appear in +** the output, which is incorrect. +*/ +static void setJoinExpr(Expr *p, int iTable){ + while( p ){ + ExprSetProperty(p, EP_FromJoin); + assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); + ExprSetVVAProperty(p, EP_NoReduce); + p->iRightJoinTable = (i16)iTable; + setJoinExpr(p->pLeft, iTable); + p = p->pRight; + } +} + +/* +** This routine processes the join information for a SELECT statement. +** ON and USING clauses are converted into extra terms of the WHERE clause. +** NATURAL joins also create extra WHERE clause terms. +** +** The terms of a FROM clause are contained in the Select.pSrc structure. +** The left most table is the first entry in Select.pSrc. The right-most +** table is the last entry. The join operator is held in the entry to +** the left. Thus entry 0 contains the join operator for the join between +** entries 0 and 1. Any ON or USING clauses associated with the join are +** also attached to the left entry. +** +** This routine returns the number of errors encountered. +*/ +static int sqliteProcessJoin(Parse *pParse, Select *p){ + SrcList *pSrc; /* All tables in the FROM clause */ + int i, j; /* Loop counters */ + struct SrcList_item *pLeft; /* Left table being joined */ + struct SrcList_item *pRight; /* Right table being joined */ + + pSrc = p->pSrc; + pLeft = &pSrc->a[0]; + pRight = &pLeft[1]; + for(i=0; inSrc-1; i++, pRight++, pLeft++){ + Table *pLeftTab = pLeft->pTab; + Table *pRightTab = pRight->pTab; + int isOuter; + + if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; + isOuter = (pRight->jointype & JT_OUTER)!=0; + + /* When the NATURAL keyword is present, add WHERE clause terms for + ** every column that the two tables have in common. + */ + if( pRight->jointype & JT_NATURAL ){ + if( pRight->pOn || pRight->pUsing ){ + sqlite3ErrorMsg(pParse, "a NATURAL join may not have " + "an ON or USING clause", 0); + return 1; + } + for(j=0; jnCol; j++){ + char *zName; /* Name of column in the right table */ + int iLeft; /* Matching left table */ + int iLeftCol; /* Matching column in the left table */ + + zName = pRightTab->aCol[j].zName; + if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ + addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, + isOuter, &p->pWhere); + } + } + } + + /* Disallow both ON and USING clauses in the same join + */ + if( pRight->pOn && pRight->pUsing ){ + sqlite3ErrorMsg(pParse, "cannot have both ON and USING " + "clauses in the same join"); + return 1; + } + + /* Add the ON clause to the end of the WHERE clause, connected by + ** an AND operator. + */ + if( pRight->pOn ){ + if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); + p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); + pRight->pOn = 0; + } + + /* Create extra terms on the WHERE clause for each column named + ** in the USING clause. Example: If the two tables to be joined are + ** A and B and the USING clause names X, Y, and Z, then add this + ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z + ** Report an error if any column mentioned in the USING clause is + ** not contained in both tables to be joined. + */ + if( pRight->pUsing ){ + IdList *pList = pRight->pUsing; + for(j=0; jnId; j++){ + char *zName; /* Name of the term in the USING clause */ + int iLeft; /* Table on the left with matching column name */ + int iLeftCol; /* Column number of matching column on the left */ + int iRightCol; /* Column number of matching column on the right */ + + zName = pList->a[j].zName; + iRightCol = columnIndex(pRightTab, zName); + if( iRightCol<0 + || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) + ){ + sqlite3ErrorMsg(pParse, "cannot join using column %s - column " + "not present in both tables", zName); + return 1; + } + addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, + isOuter, &p->pWhere); + } + } + } + return 0; +} + +/* +** Insert code into "v" that will push the record on the top of the +** stack into the sorter. +*/ +static void pushOntoSorter( + Parse *pParse, /* Parser context */ + ExprList *pOrderBy, /* The ORDER BY clause */ + Select *pSelect, /* The whole SELECT statement */ + int regData /* Register holding data to be sorted */ +){ + Vdbe *v = pParse->pVdbe; + int nExpr = pOrderBy->nExpr; + int regBase = sqlite3GetTempRange(pParse, nExpr+2); + int regRecord = sqlite3GetTempReg(pParse); + int op; + sqlite3ExprCacheClear(pParse); + sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0); + sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr); + sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord); + if( pSelect->selFlags & SF_UseSorter ){ + op = OP_SorterInsert; + }else{ + op = OP_IdxInsert; + } + sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord); + sqlite3ReleaseTempReg(pParse, regRecord); + sqlite3ReleaseTempRange(pParse, regBase, nExpr+2); + if( pSelect->iLimit ){ + int addr1, addr2; + int iLimit; + if( pSelect->iOffset ){ + iLimit = pSelect->iOffset+1; + }else{ + iLimit = pSelect->iLimit; + } + addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); + sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1); + addr2 = sqlite3VdbeAddOp0(v, OP_Goto); + sqlite3VdbeJumpHere(v, addr1); + sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor); + sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor); + sqlite3VdbeJumpHere(v, addr2); + } +} + +/* +** Add code to implement the OFFSET +*/ +static void codeOffset( + Vdbe *v, /* Generate code into this VM */ + Select *p, /* The SELECT statement being coded */ + int iContinue /* Jump here to skip the current record */ +){ + if( p->iOffset && iContinue!=0 ){ + int addr; + sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1); + addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset); + sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue); + VdbeComment((v, "skip OFFSET records")); + sqlite3VdbeJumpHere(v, addr); + } +} + +/* +** Add code that will check to make sure the N registers starting at iMem +** form a distinct entry. iTab is a sorting index that holds previously +** seen combinations of the N values. A new entry is made in iTab +** if the current N values are new. +** +** A jump to addrRepeat is made and the N+1 values are popped from the +** stack if the top N elements are not distinct. +*/ +static void codeDistinct( + Parse *pParse, /* Parsing and code generating context */ + int iTab, /* A sorting index used to test for distinctness */ + int addrRepeat, /* Jump to here if not distinct */ + int N, /* Number of elements */ + int iMem /* First element */ +){ + Vdbe *v; + int r1; + + v = pParse->pVdbe; + r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); + sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); + sqlite3ReleaseTempReg(pParse, r1); +} + +#ifndef SQLITE_OMIT_SUBQUERY +/* +** Generate an error message when a SELECT is used within a subexpression +** (example: "a IN (SELECT * FROM table)") but it has more than 1 result +** column. We do this in a subroutine because the error used to occur +** in multiple places. (The error only occurs in one place now, but we +** retain the subroutine to minimize code disruption.) +*/ +static int checkForMultiColumnSelectError( + Parse *pParse, /* Parse context. */ + SelectDest *pDest, /* Destination of SELECT results */ + int nExpr /* Number of result columns returned by SELECT */ +){ + int eDest = pDest->eDest; + if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ + sqlite3ErrorMsg(pParse, "only a single result allowed for " + "a SELECT that is part of an expression"); + return 1; + }else{ + return 0; + } +} +#endif + +/* +** An instance of the following object is used to record information about +** how to process the DISTINCT keyword, to simplify passing that information +** into the selectInnerLoop() routine. +*/ +typedef struct DistinctCtx DistinctCtx; +struct DistinctCtx { + u8 isTnct; /* True if the DISTINCT keyword is present */ + u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ + int tabTnct; /* Ephemeral table used for DISTINCT processing */ + int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ +}; + +/* +** This routine generates the code for the inside of the inner loop +** of a SELECT. +** +** If srcTab and nColumn are both zero, then the pEList expressions +** are evaluated in order to get the data for this row. If nColumn>0 +** then data is pulled from srcTab and pEList is used only to get the +** datatypes for each column. +*/ +static void selectInnerLoop( + Parse *pParse, /* The parser context */ + Select *p, /* The complete select statement being coded */ + ExprList *pEList, /* List of values being extracted */ + int srcTab, /* Pull data from this table */ + int nColumn, /* Number of columns in the source table */ + ExprList *pOrderBy, /* If not NULL, sort results using this key */ + DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ + SelectDest *pDest, /* How to dispose of the results */ + int iContinue, /* Jump here to continue with next row */ + int iBreak /* Jump here to break out of the inner loop */ +){ + Vdbe *v = pParse->pVdbe; + int i; + int hasDistinct; /* True if the DISTINCT keyword is present */ + int regResult; /* Start of memory holding result set */ + int eDest = pDest->eDest; /* How to dispose of results */ + int iParm = pDest->iSDParm; /* First argument to disposal method */ + int nResultCol; /* Number of result columns */ + + assert( v ); + if( NEVER(v==0) ) return; + assert( pEList!=0 ); + hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; + if( pOrderBy==0 && !hasDistinct ){ + codeOffset(v, p, iContinue); + } + + /* Pull the requested columns. + */ + if( nColumn>0 ){ + nResultCol = nColumn; + }else{ + nResultCol = pEList->nExpr; + } + if( pDest->iSdst==0 ){ + pDest->iSdst = pParse->nMem+1; + pDest->nSdst = nResultCol; + pParse->nMem += nResultCol; + }else{ + assert( pDest->nSdst==nResultCol ); + } + regResult = pDest->iSdst; + if( nColumn>0 ){ + for(i=0; inExpr==nColumn ); + switch( pDistinct->eTnctType ){ + case WHERE_DISTINCT_ORDERED: { + VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ + int iJump; /* Jump destination */ + int regPrev; /* Previous row content */ + + /* Allocate space for the previous row */ + regPrev = pParse->nMem+1; + pParse->nMem += nColumn; + + /* Change the OP_OpenEphemeral coded earlier to an OP_Null + ** sets the MEM_Cleared bit on the first register of the + ** previous value. This will cause the OP_Ne below to always + ** fail on the first iteration of the loop even if the first + ** row is all NULLs. + */ + sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); + pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); + pOp->opcode = OP_Null; + pOp->p1 = 1; + pOp->p2 = regPrev; + + iJump = sqlite3VdbeCurrentAddr(v) + nColumn; + for(i=0; ia[i].pExpr); + if( iaddrTnct); + break; + } + + default: { + assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); + codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult); + break; + } + } + if( pOrderBy==0 ){ + codeOffset(v, p, iContinue); + } + } + + switch( eDest ){ + /* In this mode, write each query result to the key of the temporary + ** table iParm. + */ +#ifndef SQLITE_OMIT_COMPOUND_SELECT + case SRT_Union: { + int r1; + r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); + sqlite3ReleaseTempReg(pParse, r1); + break; + } + + /* Construct a record from the query result, but instead of + ** saving that record, use it as a key to delete elements from + ** the temporary table iParm. + */ + case SRT_Except: { + sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn); + break; + } +#endif + + /* Store the result as data using a unique key. + */ + case SRT_Table: + case SRT_EphemTab: { + int r1 = sqlite3GetTempReg(pParse); + testcase( eDest==SRT_Table ); + testcase( eDest==SRT_EphemTab ); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); + if( pOrderBy ){ + pushOntoSorter(pParse, pOrderBy, p, r1); + }else{ + int r2 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); + sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3ReleaseTempReg(pParse, r2); + } + sqlite3ReleaseTempReg(pParse, r1); + break; + } + +#ifndef SQLITE_OMIT_SUBQUERY + /* If we are creating a set for an "expr IN (SELECT ...)" construct, + ** then there should be a single item on the stack. Write this + ** item into the set table with bogus data. + */ + case SRT_Set: { + assert( nColumn==1 ); + pDest->affSdst = + sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst); + if( pOrderBy ){ + /* At first glance you would think we could optimize out the + ** ORDER BY in this case since the order of entries in the set + ** does not matter. But there might be a LIMIT clause, in which + ** case the order does matter */ + pushOntoSorter(pParse, pOrderBy, p, regResult); + }else{ + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1); + sqlite3ExprCacheAffinityChange(pParse, regResult, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); + sqlite3ReleaseTempReg(pParse, r1); + } + break; + } + + /* If any row exist in the result set, record that fact and abort. + */ + case SRT_Exists: { + sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); + /* The LIMIT clause will terminate the loop for us */ + break; + } + + /* If this is a scalar select that is part of an expression, then + ** store the results in the appropriate memory cell and break out + ** of the scan loop. + */ + case SRT_Mem: { + assert( nColumn==1 ); + if( pOrderBy ){ + pushOntoSorter(pParse, pOrderBy, p, regResult); + }else{ + sqlite3ExprCodeMove(pParse, regResult, iParm, 1); + /* The LIMIT clause will jump out of the loop for us */ + } + break; + } +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */ + + /* Send the data to the callback function or to a subroutine. In the + ** case of a subroutine, the subroutine itself is responsible for + ** popping the data from the stack. + */ + case SRT_Coroutine: + case SRT_Output: { + testcase( eDest==SRT_Coroutine ); + testcase( eDest==SRT_Output ); + if( pOrderBy ){ + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); + pushOntoSorter(pParse, pOrderBy, p, r1); + sqlite3ReleaseTempReg(pParse, r1); + }else if( eDest==SRT_Coroutine ){ + sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); + }else{ + sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); + sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn); + } + break; + } + +#if !defined(SQLITE_OMIT_TRIGGER) + /* Discard the results. This is used for SELECT statements inside + ** the body of a TRIGGER. The purpose of such selects is to call + ** user-defined functions that have side effects. We do not care + ** about the actual results of the select. + */ + default: { + assert( eDest==SRT_Discard ); + break; + } +#endif + } + + /* Jump to the end of the loop if the LIMIT is reached. Except, if + ** there is a sorter, in which case the sorter has already limited + ** the output for us. + */ + if( pOrderBy==0 && p->iLimit ){ + sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); + } +} + +/* +** Allocate a KeyInfo object sufficient for an index of N columns. +** +** Actually, always allocate one extra column for the rowid at the end +** of the index. So the KeyInfo returned will have space sufficient for +** N+1 columns. +*/ +KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){ + KeyInfo *p = sqlite3DbMallocZero(db, + sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1)); + if( p ){ + p->aSortOrder = (u8*)&p->aColl[N+1]; + p->nField = (u16)N; + p->enc = ENC(db); + p->db = db; + } + return p; +} + +/* +** Given an expression list, generate a KeyInfo structure that records +** the collating sequence for each expression in that expression list. +** +** If the ExprList is an ORDER BY or GROUP BY clause then the resulting +** KeyInfo structure is appropriate for initializing a virtual index to +** implement that clause. If the ExprList is the result set of a SELECT +** then the KeyInfo structure is appropriate for initializing a virtual +** index to implement a DISTINCT test. +** +** Space to hold the KeyInfo structure is obtain from malloc. The calling +** function is responsible for seeing that this structure is eventually +** freed. Add the KeyInfo structure to the P4 field of an opcode using +** P4_KEYINFO_HANDOFF is the usual way of dealing with this. +*/ +static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ + int nExpr; + KeyInfo *pInfo; + struct ExprList_item *pItem; + sqlite3 *db = pParse->db; + int i; + + nExpr = pList->nExpr; + pInfo = sqlite3KeyInfoAlloc(db, nExpr); + if( pInfo ){ + for(i=0, pItem=pList->a; ipExpr); + if( !pColl ) pColl = db->pDfltColl; + pInfo->aColl[i] = pColl; + pInfo->aSortOrder[i] = pItem->sortOrder; + } + } + return pInfo; +} + +#ifndef SQLITE_OMIT_COMPOUND_SELECT +/* +** Name of the connection operator, used for error messages. +*/ +static const char *selectOpName(int id){ + char *z; + switch( id ){ + case TK_ALL: z = "UNION ALL"; break; + case TK_INTERSECT: z = "INTERSECT"; break; + case TK_EXCEPT: z = "EXCEPT"; break; + default: z = "UNION"; break; + } + return z; +} +#endif /* SQLITE_OMIT_COMPOUND_SELECT */ + +#ifndef SQLITE_OMIT_EXPLAIN +/* +** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function +** is a no-op. Otherwise, it adds a single row of output to the EQP result, +** where the caption is of the form: +** +** "USE TEMP B-TREE FOR xxx" +** +** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which +** is determined by the zUsage argument. +*/ +static void explainTempTable(Parse *pParse, const char *zUsage){ + if( pParse->explain==2 ){ + Vdbe *v = pParse->pVdbe; + char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); + sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); + } +} + +/* +** Assign expression b to lvalue a. A second, no-op, version of this macro +** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code +** in sqlite3Select() to assign values to structure member variables that +** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the +** code with #ifndef directives. +*/ +# define explainSetInteger(a, b) a = b + +#else +/* No-op versions of the explainXXX() functions and macros. */ +# define explainTempTable(y,z) +# define explainSetInteger(y,z) +#endif + +#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) +/* +** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function +** is a no-op. Otherwise, it adds a single row of output to the EQP result, +** where the caption is of one of the two forms: +** +** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" +** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" +** +** where iSub1 and iSub2 are the integers passed as the corresponding +** function parameters, and op is the text representation of the parameter +** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, +** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is +** false, or the second form if it is true. +*/ +static void explainComposite( + Parse *pParse, /* Parse context */ + int op, /* One of TK_UNION, TK_EXCEPT etc. */ + int iSub1, /* Subquery id 1 */ + int iSub2, /* Subquery id 2 */ + int bUseTmp /* True if a temp table was used */ +){ + assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); + if( pParse->explain==2 ){ + Vdbe *v = pParse->pVdbe; + char *zMsg = sqlite3MPrintf( + pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, + bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) + ); + sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); + } +} +#else +/* No-op versions of the explainXXX() functions and macros. */ +# define explainComposite(v,w,x,y,z) +#endif + +/* +** If the inner loop was generated using a non-null pOrderBy argument, +** then the results were placed in a sorter. After the loop is terminated +** we need to run the sorter and output the results. The following +** routine generates the code needed to do that. +*/ +static void generateSortTail( + Parse *pParse, /* Parsing context */ + Select *p, /* The SELECT statement */ + Vdbe *v, /* Generate code into this VDBE */ + int nColumn, /* Number of columns of data */ + SelectDest *pDest /* Write the sorted results here */ +){ + int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */ + int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ + int addr; + int iTab; + int pseudoTab = 0; + ExprList *pOrderBy = p->pOrderBy; + + int eDest = pDest->eDest; + int iParm = pDest->iSDParm; + + int regRow; + int regRowid; + + iTab = pOrderBy->iECursor; + regRow = sqlite3GetTempReg(pParse); + if( eDest==SRT_Output || eDest==SRT_Coroutine ){ + pseudoTab = pParse->nTab++; + sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn); + regRowid = 0; + }else{ + regRowid = sqlite3GetTempReg(pParse); + } + if( p->selFlags & SF_UseSorter ){ + int regSortOut = ++pParse->nMem; + int ptab2 = pParse->nTab++; + sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2); + addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); + codeOffset(v, p, addrContinue); + sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut); + sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow); + sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); + }else{ + addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); + codeOffset(v, p, addrContinue); + sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow); + } + switch( eDest ){ + case SRT_Table: + case SRT_EphemTab: { + testcase( eDest==SRT_Table ); + testcase( eDest==SRT_EphemTab ); + sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); + sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case SRT_Set: { + assert( nColumn==1 ); + sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, + &pDest->affSdst, 1); + sqlite3ExprCacheAffinityChange(pParse, regRow, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); + break; + } + case SRT_Mem: { + assert( nColumn==1 ); + sqlite3ExprCodeMove(pParse, regRow, iParm, 1); + /* The LIMIT clause will terminate the loop for us */ + break; + } +#endif + default: { + int i; + assert( eDest==SRT_Output || eDest==SRT_Coroutine ); + testcase( eDest==SRT_Output ); + testcase( eDest==SRT_Coroutine ); + for(i=0; iiSdst+i ); + sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i); + if( i==0 ){ + sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); + } + } + if( eDest==SRT_Output ){ + sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); + sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); + }else{ + sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); + } + break; + } + } + sqlite3ReleaseTempReg(pParse, regRow); + sqlite3ReleaseTempReg(pParse, regRowid); + + /* The bottom of the loop + */ + sqlite3VdbeResolveLabel(v, addrContinue); + if( p->selFlags & SF_UseSorter ){ + sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); + }else{ + sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); + } + sqlite3VdbeResolveLabel(v, addrBreak); + if( eDest==SRT_Output || eDest==SRT_Coroutine ){ + sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); + } +} + +/* +** Return a pointer to a string containing the 'declaration type' of the +** expression pExpr. The string may be treated as static by the caller. +** +** Also try to estimate the size of the returned value and return that +** result in *pEstWidth. +** +** The declaration type is the exact datatype definition extracted from the +** original CREATE TABLE statement if the expression is a column. The +** declaration type for a ROWID field is INTEGER. Exactly when an expression +** is considered a column can be complex in the presence of subqueries. The +** result-set expression in all of the following SELECT statements is +** considered a column by this function. +** +** SELECT col FROM tbl; +** SELECT (SELECT col FROM tbl; +** SELECT (SELECT col FROM tbl); +** SELECT abc FROM (SELECT col AS abc FROM tbl); +** +** The declaration type for any expression other than a column is NULL. +** +** This routine has either 3 or 6 parameters depending on whether or not +** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. +*/ +#ifdef SQLITE_ENABLE_COLUMN_METADATA +# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F) +static const char *columnTypeImpl( + NameContext *pNC, + Expr *pExpr, + const char **pzOrigDb, + const char **pzOrigTab, + const char **pzOrigCol, + u8 *pEstWidth +){ + char const *zOrigDb = 0; + char const *zOrigTab = 0; + char const *zOrigCol = 0; +#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ +# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F) +static const char *columnTypeImpl( + NameContext *pNC, + Expr *pExpr, + u8 *pEstWidth +){ +#endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */ + char const *zType = 0; + int j; + u8 estWidth = 1; + + if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0; + switch( pExpr->op ){ + case TK_AGG_COLUMN: + case TK_COLUMN: { + /* The expression is a column. Locate the table the column is being + ** extracted from in NameContext.pSrcList. This table may be real + ** database table or a subquery. + */ + Table *pTab = 0; /* Table structure column is extracted from */ + Select *pS = 0; /* Select the column is extracted from */ + int iCol = pExpr->iColumn; /* Index of column in pTab */ + testcase( pExpr->op==TK_AGG_COLUMN ); + testcase( pExpr->op==TK_COLUMN ); + while( pNC && !pTab ){ + SrcList *pTabList = pNC->pSrcList; + for(j=0;jnSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); + if( jnSrc ){ + pTab = pTabList->a[j].pTab; + pS = pTabList->a[j].pSelect; + }else{ + pNC = pNC->pNext; + } + } + + if( pTab==0 ){ + /* At one time, code such as "SELECT new.x" within a trigger would + ** cause this condition to run. Since then, we have restructured how + ** trigger code is generated and so this condition is no longer + ** possible. However, it can still be true for statements like + ** the following: + ** + ** CREATE TABLE t1(col INTEGER); + ** SELECT (SELECT t1.col) FROM FROM t1; + ** + ** when columnType() is called on the expression "t1.col" in the + ** sub-select. In this case, set the column type to NULL, even + ** though it should really be "INTEGER". + ** + ** This is not a problem, as the column type of "t1.col" is never + ** used. When columnType() is called on the expression + ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT + ** branch below. */ + break; + } + + assert( pTab && pExpr->pTab==pTab ); + if( pS ){ + /* The "table" is actually a sub-select or a view in the FROM clause + ** of the SELECT statement. Return the declaration type and origin + ** data for the result-set column of the sub-select. + */ + if( iCol>=0 && ALWAYS(iColpEList->nExpr) ){ + /* If iCol is less than zero, then the expression requests the + ** rowid of the sub-select or view. This expression is legal (see + ** test case misc2.2.2) - it always evaluates to NULL. + */ + NameContext sNC; + Expr *p = pS->pEList->a[iCol].pExpr; + sNC.pSrcList = pS->pSrc; + sNC.pNext = pNC; + sNC.pParse = pNC->pParse; + zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); + } + }else if( ALWAYS(pTab->pSchema) ){ + /* A real table */ + assert( !pS ); + if( iCol<0 ) iCol = pTab->iPKey; + assert( iCol==-1 || (iCol>=0 && iColnCol) ); +#ifdef SQLITE_ENABLE_COLUMN_METADATA + if( iCol<0 ){ + zType = "INTEGER"; + zOrigCol = "rowid"; + }else{ + zType = pTab->aCol[iCol].zType; + zOrigCol = pTab->aCol[iCol].zName; + estWidth = pTab->aCol[iCol].szEst; + } + zOrigTab = pTab->zName; + if( pNC->pParse ){ + int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); + zOrigDb = pNC->pParse->db->aDb[iDb].zName; + } +#else + if( iCol<0 ){ + zType = "INTEGER"; + }else{ + zType = pTab->aCol[iCol].zType; + estWidth = pTab->aCol[iCol].szEst; + } +#endif + } + break; + } +#ifndef SQLITE_OMIT_SUBQUERY + case TK_SELECT: { + /* The expression is a sub-select. Return the declaration type and + ** origin info for the single column in the result set of the SELECT + ** statement. + */ + NameContext sNC; + Select *pS = pExpr->x.pSelect; + Expr *p = pS->pEList->a[0].pExpr; + assert( ExprHasProperty(pExpr, EP_xIsSelect) ); + sNC.pSrcList = pS->pSrc; + sNC.pNext = pNC; + sNC.pParse = pNC->pParse; + zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); + break; + } +#endif + } + +#ifdef SQLITE_ENABLE_COLUMN_METADATA + if( pzOrigDb ){ + assert( pzOrigTab && pzOrigCol ); + *pzOrigDb = zOrigDb; + *pzOrigTab = zOrigTab; + *pzOrigCol = zOrigCol; + } +#endif + if( pEstWidth ) *pEstWidth = estWidth; + return zType; +} + +/* +** Generate code that will tell the VDBE the declaration types of columns +** in the result set. +*/ +static void generateColumnTypes( + Parse *pParse, /* Parser context */ + SrcList *pTabList, /* List of tables */ + ExprList *pEList /* Expressions defining the result set */ +){ +#ifndef SQLITE_OMIT_DECLTYPE + Vdbe *v = pParse->pVdbe; + int i; + NameContext sNC; + sNC.pSrcList = pTabList; + sNC.pParse = pParse; + for(i=0; inExpr; i++){ + Expr *p = pEList->a[i].pExpr; + const char *zType; +#ifdef SQLITE_ENABLE_COLUMN_METADATA + const char *zOrigDb = 0; + const char *zOrigTab = 0; + const char *zOrigCol = 0; + zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0); + + /* The vdbe must make its own copy of the column-type and other + ** column specific strings, in case the schema is reset before this + ** virtual machine is deleted. + */ + sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); +#else + zType = columnType(&sNC, p, 0, 0, 0, 0); +#endif + sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); + } +#endif /* !defined(SQLITE_OMIT_DECLTYPE) */ +} + +/* +** Generate code that will tell the VDBE the names of columns +** in the result set. This information is used to provide the +** azCol[] values in the callback. +*/ +static void generateColumnNames( + Parse *pParse, /* Parser context */ + SrcList *pTabList, /* List of tables */ + ExprList *pEList /* Expressions defining the result set */ +){ + Vdbe *v = pParse->pVdbe; + int i, j; + sqlite3 *db = pParse->db; + int fullNames, shortNames; + +#ifndef SQLITE_OMIT_EXPLAIN + /* If this is an EXPLAIN, skip this step */ + if( pParse->explain ){ + return; + } +#endif + + if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return; + pParse->colNamesSet = 1; + fullNames = (db->flags & SQLITE_FullColNames)!=0; + shortNames = (db->flags & SQLITE_ShortColNames)!=0; + sqlite3VdbeSetNumCols(v, pEList->nExpr); + for(i=0; inExpr; i++){ + Expr *p; + p = pEList->a[i].pExpr; + if( NEVER(p==0) ) continue; + if( pEList->a[i].zName ){ + char *zName = pEList->a[i].zName; + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); + }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){ + Table *pTab; + char *zCol; + int iCol = p->iColumn; + for(j=0; ALWAYS(jnSrc); j++){ + if( pTabList->a[j].iCursor==p->iTable ) break; + } + assert( jnSrc ); + pTab = pTabList->a[j].pTab; + if( iCol<0 ) iCol = pTab->iPKey; + assert( iCol==-1 || (iCol>=0 && iColnCol) ); + if( iCol<0 ){ + zCol = "rowid"; + }else{ + zCol = pTab->aCol[iCol].zName; + } + if( !shortNames && !fullNames ){ + sqlite3VdbeSetColName(v, i, COLNAME_NAME, + sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); + }else if( fullNames ){ + char *zName = 0; + zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); + }else{ + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); + } + }else{ + sqlite3VdbeSetColName(v, i, COLNAME_NAME, + sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); + } + } + generateColumnTypes(pParse, pTabList, pEList); +} + +/* +** Given a an expression list (which is really the list of expressions +** that form the result set of a SELECT statement) compute appropriate +** column names for a table that would hold the expression list. +** +** All column names will be unique. +** +** Only the column names are computed. Column.zType, Column.zColl, +** and other fields of Column are zeroed. +** +** Return SQLITE_OK on success. If a memory allocation error occurs, +** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. +*/ +static int selectColumnsFromExprList( + Parse *pParse, /* Parsing context */ + ExprList *pEList, /* Expr list from which to derive column names */ + i16 *pnCol, /* Write the number of columns here */ + Column **paCol /* Write the new column list here */ +){ + sqlite3 *db = pParse->db; /* Database connection */ + int i, j; /* Loop counters */ + int cnt; /* Index added to make the name unique */ + Column *aCol, *pCol; /* For looping over result columns */ + int nCol; /* Number of columns in the result set */ + Expr *p; /* Expression for a single result column */ + char *zName; /* Column name */ + int nName; /* Size of name in zName[] */ + + if( pEList ){ + nCol = pEList->nExpr; + aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); + testcase( aCol==0 ); + }else{ + nCol = 0; + aCol = 0; + } + *pnCol = nCol; + *paCol = aCol; + + for(i=0, pCol=aCol; ia[i].pExpr); + if( (zName = pEList->a[i].zName)!=0 ){ + /* If the column contains an "AS " phrase, use as the name */ + zName = sqlite3DbStrDup(db, zName); + }else{ + Expr *pColExpr = p; /* The expression that is the result column name */ + Table *pTab; /* Table associated with this expression */ + while( pColExpr->op==TK_DOT ){ + pColExpr = pColExpr->pRight; + assert( pColExpr!=0 ); + } + if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ + /* For columns use the column name name */ + int iCol = pColExpr->iColumn; + pTab = pColExpr->pTab; + if( iCol<0 ) iCol = pTab->iPKey; + zName = sqlite3MPrintf(db, "%s", + iCol>=0 ? pTab->aCol[iCol].zName : "rowid"); + }else if( pColExpr->op==TK_ID ){ + assert( !ExprHasProperty(pColExpr, EP_IntValue) ); + zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken); + }else{ + /* Use the original text of the column expression as its name */ + zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan); + } + } + if( db->mallocFailed ){ + sqlite3DbFree(db, zName); + break; + } + + /* Make sure the column name is unique. If the name is not unique, + ** append a integer to the name so that it becomes unique. + */ + nName = sqlite3Strlen30(zName); + for(j=cnt=0; j1 && sqlite3Isdigit(zName[k]); k--){} + if( zName[k]==':' ) nName = k; + zName[nName] = 0; + zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt); + sqlite3DbFree(db, zName); + zName = zNewName; + j = -1; + if( zName==0 ) break; + } + } + pCol->zName = zName; + } + if( db->mallocFailed ){ + for(j=0; jdb; + NameContext sNC; + Column *pCol; + CollSeq *pColl; + int i; + Expr *p; + struct ExprList_item *a; + u64 szAll = 0; + + assert( pSelect!=0 ); + assert( (pSelect->selFlags & SF_Resolved)!=0 ); + assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); + if( db->mallocFailed ) return; + memset(&sNC, 0, sizeof(sNC)); + sNC.pSrcList = pSelect->pSrc; + a = pSelect->pEList->a; + for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ + p = a[i].pExpr; + pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst)); + szAll += pCol->szEst; + pCol->affinity = sqlite3ExprAffinity(p); + if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE; + pColl = sqlite3ExprCollSeq(pParse, p); + if( pColl ){ + pCol->zColl = sqlite3DbStrDup(db, pColl->zName); + } + } + pTab->szTabRow = sqlite3LogEst(szAll*4); +} + +/* +** Given a SELECT statement, generate a Table structure that describes +** the result set of that SELECT. +*/ +Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ + Table *pTab; + sqlite3 *db = pParse->db; + int savedFlags; + + savedFlags = db->flags; + db->flags &= ~SQLITE_FullColNames; + db->flags |= SQLITE_ShortColNames; + sqlite3SelectPrep(pParse, pSelect, 0); + if( pParse->nErr ) return 0; + while( pSelect->pPrior ) pSelect = pSelect->pPrior; + db->flags = savedFlags; + pTab = sqlite3DbMallocZero(db, sizeof(Table) ); + if( pTab==0 ){ + return 0; + } + /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside + ** is disabled */ + assert( db->lookaside.bEnabled==0 ); + pTab->nRef = 1; + pTab->zName = 0; + pTab->nRowEst = 1048576; + selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); + selectAddColumnTypeAndCollation(pParse, pTab, pSelect); + pTab->iPKey = -1; + if( db->mallocFailed ){ + sqlite3DeleteTable(db, pTab); + return 0; + } + return pTab; +} + +/* +** Get a VDBE for the given parser context. Create a new one if necessary. +** If an error occurs, return NULL and leave a message in pParse. +*/ +Vdbe *sqlite3GetVdbe(Parse *pParse){ + Vdbe *v = pParse->pVdbe; + if( v==0 ){ + v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); +#ifndef SQLITE_OMIT_TRACE + if( v ){ + sqlite3VdbeAddOp0(v, OP_Trace); + } +#endif + } + return v; +} + + +/* +** Compute the iLimit and iOffset fields of the SELECT based on the +** pLimit and pOffset expressions. pLimit and pOffset hold the expressions +** that appear in the original SQL statement after the LIMIT and OFFSET +** keywords. Or NULL if those keywords are omitted. iLimit and iOffset +** are the integer memory register numbers for counters used to compute +** the limit and offset. If there is no limit and/or offset, then +** iLimit and iOffset are negative. +** +** This routine changes the values of iLimit and iOffset only if +** a limit or offset is defined by pLimit and pOffset. iLimit and +** iOffset should have been preset to appropriate default values +** (usually but not always -1) prior to calling this routine. +** Only if pLimit!=0 or pOffset!=0 do the limit registers get +** redefined. The UNION ALL operator uses this property to force +** the reuse of the same limit and offset registers across multiple +** SELECT statements. +*/ +static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ + Vdbe *v = 0; + int iLimit = 0; + int iOffset; + int addr1, n; + if( p->iLimit ) return; + + /* + ** "LIMIT -1" always shows all rows. There is some + ** controversy about what the correct behavior should be. + ** The current implementation interprets "LIMIT 0" to mean + ** no rows. + */ + sqlite3ExprCacheClear(pParse); + assert( p->pOffset==0 || p->pLimit!=0 ); + if( p->pLimit ){ + p->iLimit = iLimit = ++pParse->nMem; + v = sqlite3GetVdbe(pParse); + if( NEVER(v==0) ) return; /* VDBE should have already been allocated */ + if( sqlite3ExprIsInteger(p->pLimit, &n) ){ + sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); + VdbeComment((v, "LIMIT counter")); + if( n==0 ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); + }else if( n>=0 && p->nSelectRow>(u64)n ){ + p->nSelectRow = n; + } + }else{ + sqlite3ExprCode(pParse, p->pLimit, iLimit); + sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); + VdbeComment((v, "LIMIT counter")); + sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); + } + if( p->pOffset ){ + p->iOffset = iOffset = ++pParse->nMem; + pParse->nMem++; /* Allocate an extra register for limit+offset */ + sqlite3ExprCode(pParse, p->pOffset, iOffset); + sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); + VdbeComment((v, "OFFSET counter")); + addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); + sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); + sqlite3VdbeJumpHere(v, addr1); + sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); + VdbeComment((v, "LIMIT+OFFSET")); + addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); + sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); + sqlite3VdbeJumpHere(v, addr1); + } + } +} + +#ifndef SQLITE_OMIT_COMPOUND_SELECT +/* +** Return the appropriate collating sequence for the iCol-th column of +** the result set for the compound-select statement "p". Return NULL if +** the column has no default collating sequence. +** +** The collating sequence for the compound select is taken from the +** left-most term of the select that has a collating sequence. +*/ +static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ + CollSeq *pRet; + if( p->pPrior ){ + pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); + }else{ + pRet = 0; + } + assert( iCol>=0 ); + if( pRet==0 && iColpEList->nExpr ){ + pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); + } + return pRet; +} +#endif /* SQLITE_OMIT_COMPOUND_SELECT */ + +/* Forward reference */ +static int multiSelectOrderBy( + Parse *pParse, /* Parsing context */ + Select *p, /* The right-most of SELECTs to be coded */ + SelectDest *pDest /* What to do with query results */ +); + + +#ifndef SQLITE_OMIT_COMPOUND_SELECT +/* +** This routine is called to process a compound query form from +** two or more separate queries using UNION, UNION ALL, EXCEPT, or +** INTERSECT +** +** "p" points to the right-most of the two queries. the query on the +** left is p->pPrior. The left query could also be a compound query +** in which case this routine will be called recursively. +** +** The results of the total query are to be written into a destination +** of type eDest with parameter iParm. +** +** Example 1: Consider a three-way compound SQL statement. +** +** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 +** +** This statement is parsed up as follows: +** +** SELECT c FROM t3 +** | +** `-----> SELECT b FROM t2 +** | +** `------> SELECT a FROM t1 +** +** The arrows in the diagram above represent the Select.pPrior pointer. +** So if this routine is called with p equal to the t3 query, then +** pPrior will be the t2 query. p->op will be TK_UNION in this case. +** +** Notice that because of the way SQLite parses compound SELECTs, the +** individual selects always group from left to right. +*/ +static int multiSelect( + Parse *pParse, /* Parsing context */ + Select *p, /* The right-most of SELECTs to be coded */ + SelectDest *pDest /* What to do with query results */ +){ + int rc = SQLITE_OK; /* Success code from a subroutine */ + Select *pPrior; /* Another SELECT immediately to our left */ + Vdbe *v; /* Generate code to this VDBE */ + SelectDest dest; /* Alternative data destination */ + Select *pDelete = 0; /* Chain of simple selects to delete */ + sqlite3 *db; /* Database connection */ +#ifndef SQLITE_OMIT_EXPLAIN + int iSub1; /* EQP id of left-hand query */ + int iSub2; /* EQP id of right-hand query */ +#endif + + /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only + ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. + */ + assert( p && p->pPrior ); /* Calling function guarantees this much */ + db = pParse->db; + pPrior = p->pPrior; + assert( pPrior->pRightmost!=pPrior ); + assert( pPrior->pRightmost==p->pRightmost ); + dest = *pDest; + if( pPrior->pOrderBy ){ + sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", + selectOpName(p->op)); + rc = 1; + goto multi_select_end; + } + if( pPrior->pLimit ){ + sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", + selectOpName(p->op)); + rc = 1; + goto multi_select_end; + } + + v = sqlite3GetVdbe(pParse); + assert( v!=0 ); /* The VDBE already created by calling function */ + + /* Create the destination temporary table if necessary + */ + if( dest.eDest==SRT_EphemTab ){ + assert( p->pEList ); + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); + sqlite3VdbeChangeP5(v, BTREE_UNORDERED); + dest.eDest = SRT_Table; + } + + /* Make sure all SELECTs in the statement have the same number of elements + ** in their result sets. + */ + assert( p->pEList && pPrior->pEList ); + if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ + if( p->selFlags & SF_Values ){ + sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); + }else{ + sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" + " do not have the same number of result columns", selectOpName(p->op)); + } + rc = 1; + goto multi_select_end; + } + + /* Compound SELECTs that have an ORDER BY clause are handled separately. + */ + if( p->pOrderBy ){ + return multiSelectOrderBy(pParse, p, pDest); + } + + /* Generate code for the left and right SELECT statements. + */ + switch( p->op ){ + case TK_ALL: { + int addr = 0; + int nLimit; + assert( !pPrior->pLimit ); + pPrior->iLimit = p->iLimit; + pPrior->iOffset = p->iOffset; + pPrior->pLimit = p->pLimit; + pPrior->pOffset = p->pOffset; + explainSetInteger(iSub1, pParse->iNextSelectId); + rc = sqlite3Select(pParse, pPrior, &dest); + p->pLimit = 0; + p->pOffset = 0; + if( rc ){ + goto multi_select_end; + } + p->pPrior = 0; + p->iLimit = pPrior->iLimit; + p->iOffset = pPrior->iOffset; + if( p->iLimit ){ + addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); + VdbeComment((v, "Jump ahead if LIMIT reached")); + } + explainSetInteger(iSub2, pParse->iNextSelectId); + rc = sqlite3Select(pParse, p, &dest); + testcase( rc!=SQLITE_OK ); + pDelete = p->pPrior; + p->pPrior = pPrior; + p->nSelectRow += pPrior->nSelectRow; + if( pPrior->pLimit + && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) + && nLimit>0 && p->nSelectRow > (u64)nLimit + ){ + p->nSelectRow = nLimit; + } + if( addr ){ + sqlite3VdbeJumpHere(v, addr); + } + break; + } + case TK_EXCEPT: + case TK_UNION: { + int unionTab; /* Cursor number of the temporary table holding result */ + u8 op = 0; /* One of the SRT_ operations to apply to self */ + int priorOp; /* The SRT_ operation to apply to prior selects */ + Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ + int addr; + SelectDest uniondest; + + testcase( p->op==TK_EXCEPT ); + testcase( p->op==TK_UNION ); + priorOp = SRT_Union; + if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){ + /* We can reuse a temporary table generated by a SELECT to our + ** right. + */ + assert( p->pRightmost!=p ); /* Can only happen for leftward elements + ** of a 3-way or more compound */ + assert( p->pLimit==0 ); /* Not allowed on leftward elements */ + assert( p->pOffset==0 ); /* Not allowed on leftward elements */ + unionTab = dest.iSDParm; + }else{ + /* We will need to create our own temporary table to hold the + ** intermediate results. + */ + unionTab = pParse->nTab++; + assert( p->pOrderBy==0 ); + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); + assert( p->addrOpenEphm[0] == -1 ); + p->addrOpenEphm[0] = addr; + p->pRightmost->selFlags |= SF_UsesEphemeral; + assert( p->pEList ); + } + + /* Code the SELECT statements to our left + */ + assert( !pPrior->pOrderBy ); + sqlite3SelectDestInit(&uniondest, priorOp, unionTab); + explainSetInteger(iSub1, pParse->iNextSelectId); + rc = sqlite3Select(pParse, pPrior, &uniondest); + if( rc ){ + goto multi_select_end; + } + + /* Code the current SELECT statement + */ + if( p->op==TK_EXCEPT ){ + op = SRT_Except; + }else{ + assert( p->op==TK_UNION ); + op = SRT_Union; + } + p->pPrior = 0; + pLimit = p->pLimit; + p->pLimit = 0; + pOffset = p->pOffset; + p->pOffset = 0; + uniondest.eDest = op; + explainSetInteger(iSub2, pParse->iNextSelectId); + rc = sqlite3Select(pParse, p, &uniondest); + testcase( rc!=SQLITE_OK ); + /* Query flattening in sqlite3Select() might refill p->pOrderBy. + ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ + sqlite3ExprListDelete(db, p->pOrderBy); + pDelete = p->pPrior; + p->pPrior = pPrior; + p->pOrderBy = 0; + if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow; + sqlite3ExprDelete(db, p->pLimit); + p->pLimit = pLimit; + p->pOffset = pOffset; + p->iLimit = 0; + p->iOffset = 0; + + /* Convert the data in the temporary table into whatever form + ** it is that we currently need. + */ + assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); + if( dest.eDest!=priorOp ){ + int iCont, iBreak, iStart; + assert( p->pEList ); + if( dest.eDest==SRT_Output ){ + Select *pFirst = p; + while( pFirst->pPrior ) pFirst = pFirst->pPrior; + generateColumnNames(pParse, 0, pFirst->pEList); + } + iBreak = sqlite3VdbeMakeLabel(v); + iCont = sqlite3VdbeMakeLabel(v); + computeLimitRegisters(pParse, p, iBreak); + sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); + iStart = sqlite3VdbeCurrentAddr(v); + selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, + 0, 0, &dest, iCont, iBreak); + sqlite3VdbeResolveLabel(v, iCont); + sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); + sqlite3VdbeResolveLabel(v, iBreak); + sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); + } + break; + } + default: assert( p->op==TK_INTERSECT ); { + int tab1, tab2; + int iCont, iBreak, iStart; + Expr *pLimit, *pOffset; + int addr; + SelectDest intersectdest; + int r1; + + /* INTERSECT is different from the others since it requires + ** two temporary tables. Hence it has its own case. Begin + ** by allocating the tables we will need. + */ + tab1 = pParse->nTab++; + tab2 = pParse->nTab++; + assert( p->pOrderBy==0 ); + + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); + assert( p->addrOpenEphm[0] == -1 ); + p->addrOpenEphm[0] = addr; + p->pRightmost->selFlags |= SF_UsesEphemeral; + assert( p->pEList ); + + /* Code the SELECTs to our left into temporary table "tab1". + */ + sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); + explainSetInteger(iSub1, pParse->iNextSelectId); + rc = sqlite3Select(pParse, pPrior, &intersectdest); + if( rc ){ + goto multi_select_end; + } + + /* Code the current SELECT into temporary table "tab2" + */ + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); + assert( p->addrOpenEphm[1] == -1 ); + p->addrOpenEphm[1] = addr; + p->pPrior = 0; + pLimit = p->pLimit; + p->pLimit = 0; + pOffset = p->pOffset; + p->pOffset = 0; + intersectdest.iSDParm = tab2; + explainSetInteger(iSub2, pParse->iNextSelectId); + rc = sqlite3Select(pParse, p, &intersectdest); + testcase( rc!=SQLITE_OK ); + pDelete = p->pPrior; + p->pPrior = pPrior; + if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; + sqlite3ExprDelete(db, p->pLimit); + p->pLimit = pLimit; + p->pOffset = pOffset; + + /* Generate code to take the intersection of the two temporary + ** tables. + */ + assert( p->pEList ); + if( dest.eDest==SRT_Output ){ + Select *pFirst = p; + while( pFirst->pPrior ) pFirst = pFirst->pPrior; + generateColumnNames(pParse, 0, pFirst->pEList); + } + iBreak = sqlite3VdbeMakeLabel(v); + iCont = sqlite3VdbeMakeLabel(v); + computeLimitRegisters(pParse, p, iBreak); + sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); + r1 = sqlite3GetTempReg(pParse); + iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); + sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); + sqlite3ReleaseTempReg(pParse, r1); + selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, + 0, 0, &dest, iCont, iBreak); + sqlite3VdbeResolveLabel(v, iCont); + sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); + sqlite3VdbeResolveLabel(v, iBreak); + sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); + sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); + break; + } + } + + explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); + + /* Compute collating sequences used by + ** temporary tables needed to implement the compound select. + ** Attach the KeyInfo structure to all temporary tables. + ** + ** This section is run by the right-most SELECT statement only. + ** SELECT statements to the left always skip this part. The right-most + ** SELECT might also skip this part if it has no ORDER BY clause and + ** no temp tables are required. + */ + if( p->selFlags & SF_UsesEphemeral ){ + int i; /* Loop counter */ + KeyInfo *pKeyInfo; /* Collating sequence for the result set */ + Select *pLoop; /* For looping through SELECT statements */ + CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ + int nCol; /* Number of columns in result set */ + + assert( p->pRightmost==p ); + nCol = p->pEList->nExpr; + pKeyInfo = sqlite3KeyInfoAlloc(db, nCol); + if( !pKeyInfo ){ + rc = SQLITE_NOMEM; + goto multi_select_end; + } + for(i=0, apColl=pKeyInfo->aColl; ipDfltColl; + } + } + + for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ + for(i=0; i<2; i++){ + int addr = pLoop->addrOpenEphm[i]; + if( addr<0 ){ + /* If [0] is unused then [1] is also unused. So we can + ** always safely abort as soon as the first unused slot is found */ + assert( pLoop->addrOpenEphm[1]<0 ); + break; + } + sqlite3VdbeChangeP2(v, addr, nCol); + sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); + pLoop->addrOpenEphm[i] = -1; + } + } + sqlite3DbFree(db, pKeyInfo); + } + +multi_select_end: + pDest->iSdst = dest.iSdst; + pDest->nSdst = dest.nSdst; + sqlite3SelectDelete(db, pDelete); + return rc; +} +#endif /* SQLITE_OMIT_COMPOUND_SELECT */ + +/* +** Code an output subroutine for a coroutine implementation of a +** SELECT statment. +** +** The data to be output is contained in pIn->iSdst. There are +** pIn->nSdst columns to be output. pDest is where the output should +** be sent. +** +** regReturn is the number of the register holding the subroutine +** return address. +** +** If regPrev>0 then it is the first register in a vector that +** records the previous output. mem[regPrev] is a flag that is false +** if there has been no previous output. If regPrev>0 then code is +** generated to suppress duplicates. pKeyInfo is used for comparing +** keys. +** +** If the LIMIT found in p->iLimit is reached, jump immediately to +** iBreak. +*/ +static int generateOutputSubroutine( + Parse *pParse, /* Parsing context */ + Select *p, /* The SELECT statement */ + SelectDest *pIn, /* Coroutine supplying data */ + SelectDest *pDest, /* Where to send the data */ + int regReturn, /* The return address register */ + int regPrev, /* Previous result register. No uniqueness if 0 */ + KeyInfo *pKeyInfo, /* For comparing with previous entry */ + int p4type, /* The p4 type for pKeyInfo */ + int iBreak /* Jump here if we hit the LIMIT */ +){ + Vdbe *v = pParse->pVdbe; + int iContinue; + int addr; + + addr = sqlite3VdbeCurrentAddr(v); + iContinue = sqlite3VdbeMakeLabel(v); + + /* Suppress duplicates for UNION, EXCEPT, and INTERSECT + */ + if( regPrev ){ + int j1, j2; + j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); + j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, + (char*)pKeyInfo, p4type); + sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); + sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); + } + if( pParse->db->mallocFailed ) return 0; + + /* Suppress the first OFFSET entries if there is an OFFSET clause + */ + codeOffset(v, p, iContinue); + + switch( pDest->eDest ){ + /* Store the result as data using a unique key. + */ + case SRT_Table: + case SRT_EphemTab: { + int r1 = sqlite3GetTempReg(pParse); + int r2 = sqlite3GetTempReg(pParse); + testcase( pDest->eDest==SRT_Table ); + testcase( pDest->eDest==SRT_EphemTab ); + sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); + sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); + sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3ReleaseTempReg(pParse, r2); + sqlite3ReleaseTempReg(pParse, r1); + break; + } + +#ifndef SQLITE_OMIT_SUBQUERY + /* If we are creating a set for an "expr IN (SELECT ...)" construct, + ** then there should be a single item on the stack. Write this + ** item into the set table with bogus data. + */ + case SRT_Set: { + int r1; + assert( pIn->nSdst==1 ); + pDest->affSdst = + sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst); + r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1); + sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1); + sqlite3ReleaseTempReg(pParse, r1); + break; + } + +#if 0 /* Never occurs on an ORDER BY query */ + /* If any row exist in the result set, record that fact and abort. + */ + case SRT_Exists: { + sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm); + /* The LIMIT clause will terminate the loop for us */ + break; + } +#endif + + /* If this is a scalar select that is part of an expression, then + ** store the results in the appropriate memory cell and break out + ** of the scan loop. + */ + case SRT_Mem: { + assert( pIn->nSdst==1 ); + sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); + /* The LIMIT clause will jump out of the loop for us */ + break; + } +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */ + + /* The results are stored in a sequence of registers + ** starting at pDest->iSdst. Then the co-routine yields. + */ + case SRT_Coroutine: { + if( pDest->iSdst==0 ){ + pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); + pDest->nSdst = pIn->nSdst; + } + sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst); + sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); + break; + } + + /* If none of the above, then the result destination must be + ** SRT_Output. This routine is never called with any other + ** destination other than the ones handled above or SRT_Output. + ** + ** For SRT_Output, results are stored in a sequence of registers. + ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to + ** return the next row of result. + */ + default: { + assert( pDest->eDest==SRT_Output ); + sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); + sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); + break; + } + } + + /* Jump to the end of the loop if the LIMIT is reached. + */ + if( p->iLimit ){ + sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); + } + + /* Generate the subroutine return + */ + sqlite3VdbeResolveLabel(v, iContinue); + sqlite3VdbeAddOp1(v, OP_Return, regReturn); + + return addr; +} + +/* +** Alternative compound select code generator for cases when there +** is an ORDER BY clause. +** +** We assume a query of the following form: +** +** ORDER BY +** +** is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea +** is to code both and with the ORDER BY clause as +** co-routines. Then run the co-routines in parallel and merge the results +** into the output. In addition to the two coroutines (called selectA and +** selectB) there are 7 subroutines: +** +** outA: Move the output of the selectA coroutine into the output +** of the compound query. +** +** outB: Move the output of the selectB coroutine into the output +** of the compound query. (Only generated for UNION and +** UNION ALL. EXCEPT and INSERTSECT never output a row that +** appears only in B.) +** +** AltB: Called when there is data from both coroutines and AB. +** +** EofA: Called when data is exhausted from selectA. +** +** EofB: Called when data is exhausted from selectB. +** +** The implementation of the latter five subroutines depend on which +** is used: +** +** +** UNION ALL UNION EXCEPT INTERSECT +** ------------- ----------------- -------------- ----------------- +** AltB: outA, nextA outA, nextA outA, nextA nextA +** +** AeqB: outA, nextA nextA nextA outA, nextA +** +** AgtB: outB, nextB outB, nextB nextB nextB +** +** EofA: outB, nextB outB, nextB halt halt +** +** EofB: outA, nextA outA, nextA outA, nextA halt +** +** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA +** causes an immediate jump to EofA and an EOF on B following nextB causes +** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or +** following nextX causes a jump to the end of the select processing. +** +** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled +** within the output subroutine. The regPrev register set holds the previously +** output value. A comparison is made against this value and the output +** is skipped if the next results would be the same as the previous. +** +** The implementation plan is to implement the two coroutines and seven +** subroutines first, then put the control logic at the bottom. Like this: +** +** goto Init +** coA: coroutine for left query (A) +** coB: coroutine for right query (B) +** outA: output one row of A +** outB: output one row of B (UNION and UNION ALL only) +** EofA: ... +** EofB: ... +** AltB: ... +** AeqB: ... +** AgtB: ... +** Init: initialize coroutine registers +** yield coA +** if eof(A) goto EofA +** yield coB +** if eof(B) goto EofB +** Cmpr: Compare A, B +** Jump AltB, AeqB, AgtB +** End: ... +** +** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not +** actually called using Gosub and they do not Return. EofA and EofB loop +** until all data is exhausted then jump to the "end" labe. AltB, AeqB, +** and AgtB jump to either L2 or to one of EofA or EofB. +*/ +#ifndef SQLITE_OMIT_COMPOUND_SELECT +static int multiSelectOrderBy( + Parse *pParse, /* Parsing context */ + Select *p, /* The right-most of SELECTs to be coded */ + SelectDest *pDest /* What to do with query results */ +){ + int i, j; /* Loop counters */ + Select *pPrior; /* Another SELECT immediately to our left */ + Vdbe *v; /* Generate code to this VDBE */ + SelectDest destA; /* Destination for coroutine A */ + SelectDest destB; /* Destination for coroutine B */ + int regAddrA; /* Address register for select-A coroutine */ + int regEofA; /* Flag to indicate when select-A is complete */ + int regAddrB; /* Address register for select-B coroutine */ + int regEofB; /* Flag to indicate when select-B is complete */ + int addrSelectA; /* Address of the select-A coroutine */ + int addrSelectB; /* Address of the select-B coroutine */ + int regOutA; /* Address register for the output-A subroutine */ + int regOutB; /* Address register for the output-B subroutine */ + int addrOutA; /* Address of the output-A subroutine */ + int addrOutB = 0; /* Address of the output-B subroutine */ + int addrEofA; /* Address of the select-A-exhausted subroutine */ + int addrEofB; /* Address of the select-B-exhausted subroutine */ + int addrAltB; /* Address of the AB subroutine */ + int regLimitA; /* Limit register for select-A */ + int regLimitB; /* Limit register for select-A */ + int regPrev; /* A range of registers to hold previous output */ + int savedLimit; /* Saved value of p->iLimit */ + int savedOffset; /* Saved value of p->iOffset */ + int labelCmpr; /* Label for the start of the merge algorithm */ + int labelEnd; /* Label for the end of the overall SELECT stmt */ + int j1; /* Jump instructions that get retargetted */ + int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ + KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ + KeyInfo *pKeyMerge; /* Comparison information for merging rows */ + sqlite3 *db; /* Database connection */ + ExprList *pOrderBy; /* The ORDER BY clause */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + int *aPermute; /* Mapping from ORDER BY terms to result set columns */ +#ifndef SQLITE_OMIT_EXPLAIN + int iSub1; /* EQP id of left-hand query */ + int iSub2; /* EQP id of right-hand query */ +#endif + + assert( p->pOrderBy!=0 ); + assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ + db = pParse->db; + v = pParse->pVdbe; + assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ + labelEnd = sqlite3VdbeMakeLabel(v); + labelCmpr = sqlite3VdbeMakeLabel(v); + + + /* Patch up the ORDER BY clause + */ + op = p->op; + pPrior = p->pPrior; + assert( pPrior->pOrderBy==0 ); + pOrderBy = p->pOrderBy; + assert( pOrderBy ); + nOrderBy = pOrderBy->nExpr; + + /* For operators other than UNION ALL we have to make sure that + ** the ORDER BY clause covers every term of the result set. Add + ** terms to the ORDER BY clause as necessary. + */ + if( op!=TK_ALL ){ + for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ + struct ExprList_item *pItem; + for(j=0, pItem=pOrderBy->a; jiOrderByCol>0 ); + if( pItem->iOrderByCol==i ) break; + } + if( j==nOrderBy ){ + Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); + if( pNew==0 ) return SQLITE_NOMEM; + pNew->flags |= EP_IntValue; + pNew->u.iValue = i; + pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); + if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i; + } + } + } + + /* Compute the comparison permutation and keyinfo that is used with + ** the permutation used to determine if the next + ** row of results comes from selectA or selectB. Also add explicit + ** collations to the ORDER BY clause terms so that when the subqueries + ** to the right and the left are evaluated, they use the correct + ** collation. + */ + aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); + if( aPermute ){ + struct ExprList_item *pItem; + for(i=0, pItem=pOrderBy->a; iiOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr ); + aPermute[i] = pItem->iOrderByCol - 1; + } + pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy); + if( pKeyMerge ){ + for(i=0; ia[i].pExpr; + if( pTerm->flags & EP_Collate ){ + pColl = sqlite3ExprCollSeq(pParse, pTerm); + }else{ + pColl = multiSelectCollSeq(pParse, p, aPermute[i]); + if( pColl==0 ) pColl = db->pDfltColl; + pOrderBy->a[i].pExpr = + sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); + } + pKeyMerge->aColl[i] = pColl; + pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder; + } + } + }else{ + pKeyMerge = 0; + } + + /* Reattach the ORDER BY clause to the query. + */ + p->pOrderBy = pOrderBy; + pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); + + /* Allocate a range of temporary registers and the KeyInfo needed + ** for the logic that removes duplicate result rows when the + ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). + */ + if( op==TK_ALL ){ + regPrev = 0; + }else{ + int nExpr = p->pEList->nExpr; + assert( nOrderBy>=nExpr || db->mallocFailed ); + regPrev = pParse->nMem+1; + pParse->nMem += nExpr+1; + sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); + pKeyDup = sqlite3KeyInfoAlloc(db, nExpr); + if( pKeyDup ){ + for(i=0; iaColl[i] = multiSelectCollSeq(pParse, p, i); + pKeyDup->aSortOrder[i] = 0; + } + } + } + + /* Separate the left and the right query from one another + */ + p->pPrior = 0; + sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); + if( pPrior->pPrior==0 ){ + sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); + } + + /* Compute the limit registers */ + computeLimitRegisters(pParse, p, labelEnd); + if( p->iLimit && op==TK_ALL ){ + regLimitA = ++pParse->nMem; + regLimitB = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, + regLimitA); + sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); + }else{ + regLimitA = regLimitB = 0; + } + sqlite3ExprDelete(db, p->pLimit); + p->pLimit = 0; + sqlite3ExprDelete(db, p->pOffset); + p->pOffset = 0; + + regAddrA = ++pParse->nMem; + regEofA = ++pParse->nMem; + regAddrB = ++pParse->nMem; + regEofB = ++pParse->nMem; + regOutA = ++pParse->nMem; + regOutB = ++pParse->nMem; + sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); + sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); + + /* Jump past the various subroutines and coroutines to the main + ** merge loop + */ + j1 = sqlite3VdbeAddOp0(v, OP_Goto); + addrSelectA = sqlite3VdbeCurrentAddr(v); + + + /* Generate a coroutine to evaluate the SELECT statement to the + ** left of the compound operator - the "A" select. + */ + VdbeNoopComment((v, "Begin coroutine for left SELECT")); + pPrior->iLimit = regLimitA; + explainSetInteger(iSub1, pParse->iNextSelectId); + sqlite3Select(pParse, pPrior, &destA); + sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA); + sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); + VdbeNoopComment((v, "End coroutine for left SELECT")); + + /* Generate a coroutine to evaluate the SELECT statement on + ** the right - the "B" select + */ + addrSelectB = sqlite3VdbeCurrentAddr(v); + VdbeNoopComment((v, "Begin coroutine for right SELECT")); + savedLimit = p->iLimit; + savedOffset = p->iOffset; + p->iLimit = regLimitB; + p->iOffset = 0; + explainSetInteger(iSub2, pParse->iNextSelectId); + sqlite3Select(pParse, p, &destB); + p->iLimit = savedLimit; + p->iOffset = savedOffset; + sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB); + sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); + VdbeNoopComment((v, "End coroutine for right SELECT")); + + /* Generate a subroutine that outputs the current row of the A + ** select as the next output row of the compound select. + */ + VdbeNoopComment((v, "Output routine for A")); + addrOutA = generateOutputSubroutine(pParse, + p, &destA, pDest, regOutA, + regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd); + + /* Generate a subroutine that outputs the current row of the B + ** select as the next output row of the compound select. + */ + if( op==TK_ALL || op==TK_UNION ){ + VdbeNoopComment((v, "Output routine for B")); + addrOutB = generateOutputSubroutine(pParse, + p, &destB, pDest, regOutB, + regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd); + } + + /* Generate a subroutine to run when the results from select A + ** are exhausted and only data in select B remains. + */ + VdbeNoopComment((v, "eof-A subroutine")); + if( op==TK_EXCEPT || op==TK_INTERSECT ){ + addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd); + }else{ + addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd); + sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); + sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA); + p->nSelectRow += pPrior->nSelectRow; + } + + /* Generate a subroutine to run when the results from select B + ** are exhausted and only data in select A remains. + */ + if( op==TK_INTERSECT ){ + addrEofB = addrEofA; + if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; + }else{ + VdbeNoopComment((v, "eof-B subroutine")); + addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd); + sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); + sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB); + } + + /* Generate code to handle the case of AB + */ + VdbeNoopComment((v, "A-gt-B subroutine")); + addrAgtB = sqlite3VdbeCurrentAddr(v); + if( op==TK_ALL || op==TK_UNION ){ + sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); + } + sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); + sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); + sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); + + /* This code runs once to initialize everything. + */ + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA); + sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB); + sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA); + sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB); + sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); + sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); + + /* Implement the main merge loop + */ + sqlite3VdbeResolveLabel(v, labelCmpr); + sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); + sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, + (char*)pKeyMerge, P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); + sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); + + /* Jump to the this point in order to terminate the query. + */ + sqlite3VdbeResolveLabel(v, labelEnd); + + /* Set the number of output columns + */ + if( pDest->eDest==SRT_Output ){ + Select *pFirst = pPrior; + while( pFirst->pPrior ) pFirst = pFirst->pPrior; + generateColumnNames(pParse, 0, pFirst->pEList); + } + + /* Reassembly the compound query so that it will be freed correctly + ** by the calling function */ + if( p->pPrior ){ + sqlite3SelectDelete(db, p->pPrior); + } + p->pPrior = pPrior; + + /*** TBD: Insert subroutine calls to close cursors on incomplete + **** subqueries ****/ + explainComposite(pParse, p->op, iSub1, iSub2, 0); + return SQLITE_OK; +} +#endif + +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) +/* Forward Declarations */ +static void substExprList(sqlite3*, ExprList*, int, ExprList*); +static void substSelect(sqlite3*, Select *, int, ExprList *); + +/* +** Scan through the expression pExpr. Replace every reference to +** a column in table number iTable with a copy of the iColumn-th +** entry in pEList. (But leave references to the ROWID column +** unchanged.) +** +** This routine is part of the flattening procedure. A subquery +** whose result set is defined by pEList appears as entry in the +** FROM clause of a SELECT such that the VDBE cursor assigned to that +** FORM clause entry is iTable. This routine make the necessary +** changes to pExpr so that it refers directly to the source table +** of the subquery rather the result set of the subquery. +*/ +static Expr *substExpr( + sqlite3 *db, /* Report malloc errors to this connection */ + Expr *pExpr, /* Expr in which substitution occurs */ + int iTable, /* Table to be substituted */ + ExprList *pEList /* Substitute expressions */ +){ + if( pExpr==0 ) return 0; + if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ + if( pExpr->iColumn<0 ){ + pExpr->op = TK_NULL; + }else{ + Expr *pNew; + assert( pEList!=0 && pExpr->iColumnnExpr ); + assert( pExpr->pLeft==0 && pExpr->pRight==0 ); + pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); + sqlite3ExprDelete(db, pExpr); + pExpr = pNew; + } + }else{ + pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); + pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + substSelect(db, pExpr->x.pSelect, iTable, pEList); + }else{ + substExprList(db, pExpr->x.pList, iTable, pEList); + } + } + return pExpr; +} +static void substExprList( + sqlite3 *db, /* Report malloc errors here */ + ExprList *pList, /* List to scan and in which to make substitutes */ + int iTable, /* Table to be substituted */ + ExprList *pEList /* Substitute values */ +){ + int i; + if( pList==0 ) return; + for(i=0; inExpr; i++){ + pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); + } +} +static void substSelect( + sqlite3 *db, /* Report malloc errors here */ + Select *p, /* SELECT statement in which to make substitutions */ + int iTable, /* Table to be replaced */ + ExprList *pEList /* Substitute values */ +){ + SrcList *pSrc; + struct SrcList_item *pItem; + int i; + if( !p ) return; + substExprList(db, p->pEList, iTable, pEList); + substExprList(db, p->pGroupBy, iTable, pEList); + substExprList(db, p->pOrderBy, iTable, pEList); + p->pHaving = substExpr(db, p->pHaving, iTable, pEList); + p->pWhere = substExpr(db, p->pWhere, iTable, pEList); + substSelect(db, p->pPrior, iTable, pEList); + pSrc = p->pSrc; + assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ + if( ALWAYS(pSrc) ){ + for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ + substSelect(db, pItem->pSelect, iTable, pEList); + } + } +} +#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ + +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) +/* +** This routine attempts to flatten subqueries as a performance optimization. +** This routine returns 1 if it makes changes and 0 if no flattening occurs. +** +** To understand the concept of flattening, consider the following +** query: +** +** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 +** +** The default way of implementing this query is to execute the +** subquery first and store the results in a temporary table, then +** run the outer query on that temporary table. This requires two +** passes over the data. Furthermore, because the temporary table +** has no indices, the WHERE clause on the outer query cannot be +** optimized. +** +** This routine attempts to rewrite queries such as the above into +** a single flat select, like this: +** +** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 +** +** The code generated for this simpification gives the same result +** but only has to scan the data once. And because indices might +** exist on the table t1, a complete scan of the data might be +** avoided. +** +** Flattening is only attempted if all of the following are true: +** +** (1) The subquery and the outer query do not both use aggregates. +** +** (2) The subquery is not an aggregate or the outer query is not a join. +** +** (3) The subquery is not the right operand of a left outer join +** (Originally ticket #306. Strengthened by ticket #3300) +** +** (4) The subquery is not DISTINCT. +** +** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT +** sub-queries that were excluded from this optimization. Restriction +** (4) has since been expanded to exclude all DISTINCT subqueries. +** +** (6) The subquery does not use aggregates or the outer query is not +** DISTINCT. +** +** (7) The subquery has a FROM clause. TODO: For subqueries without +** A FROM clause, consider adding a FROM close with the special +** table sqlite_once that consists of a single row containing a +** single NULL. +** +** (8) The subquery does not use LIMIT or the outer query is not a join. +** +** (9) The subquery does not use LIMIT or the outer query does not use +** aggregates. +** +** (10) The subquery does not use aggregates or the outer query does not +** use LIMIT. +** +** (11) The subquery and the outer query do not both have ORDER BY clauses. +** +** (**) Not implemented. Subsumed into restriction (3). Was previously +** a separate restriction deriving from ticket #350. +** +** (13) The subquery and outer query do not both use LIMIT. +** +** (14) The subquery does not use OFFSET. +** +** (15) The outer query is not part of a compound select or the +** subquery does not have a LIMIT clause. +** (See ticket #2339 and ticket [02a8e81d44]). +** +** (16) The outer query is not an aggregate or the subquery does +** not contain ORDER BY. (Ticket #2942) This used to not matter +** until we introduced the group_concat() function. +** +** (17) The sub-query is not a compound select, or it is a UNION ALL +** compound clause made up entirely of non-aggregate queries, and +** the parent query: +** +** * is not itself part of a compound select, +** * is not an aggregate or DISTINCT query, and +** * is not a join +** +** The parent and sub-query may contain WHERE clauses. Subject to +** rules (11), (13) and (14), they may also contain ORDER BY, +** LIMIT and OFFSET clauses. The subquery cannot use any compound +** operator other than UNION ALL because all the other compound +** operators have an implied DISTINCT which is disallowed by +** restriction (4). +** +** Also, each component of the sub-query must return the same number +** of result columns. This is actually a requirement for any compound +** SELECT statement, but all the code here does is make sure that no +** such (illegal) sub-query is flattened. The caller will detect the +** syntax error and return a detailed message. +** +** (18) If the sub-query is a compound select, then all terms of the +** ORDER by clause of the parent must be simple references to +** columns of the sub-query. +** +** (19) The subquery does not use LIMIT or the outer query does not +** have a WHERE clause. +** +** (20) If the sub-query is a compound select, then it must not use +** an ORDER BY clause. Ticket #3773. We could relax this constraint +** somewhat by saying that the terms of the ORDER BY clause must +** appear as unmodified result columns in the outer query. But we +** have other optimizations in mind to deal with that case. +** +** (21) The subquery does not use LIMIT or the outer query is not +** DISTINCT. (See ticket [752e1646fc]). +** +** In this routine, the "p" parameter is a pointer to the outer query. +** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query +** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. +** +** If flattening is not attempted, this routine is a no-op and returns 0. +** If flattening is attempted this routine returns 1. +** +** All of the expression analysis must occur on both the outer query and +** the subquery before this routine runs. +*/ +static int flattenSubquery( + Parse *pParse, /* Parsing context */ + Select *p, /* The parent or outer SELECT statement */ + int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ + int isAgg, /* True if outer SELECT uses aggregate functions */ + int subqueryIsAgg /* True if the subquery uses aggregate functions */ +){ + const char *zSavedAuthContext = pParse->zAuthContext; + Select *pParent; + Select *pSub; /* The inner query or "subquery" */ + Select *pSub1; /* Pointer to the rightmost select in sub-query */ + SrcList *pSrc; /* The FROM clause of the outer query */ + SrcList *pSubSrc; /* The FROM clause of the subquery */ + ExprList *pList; /* The result set of the outer query */ + int iParent; /* VDBE cursor number of the pSub result set temp table */ + int i; /* Loop counter */ + Expr *pWhere; /* The WHERE clause */ + struct SrcList_item *pSubitem; /* The subquery */ + sqlite3 *db = pParse->db; + + /* Check to see if flattening is permitted. Return 0 if not. + */ + assert( p!=0 ); + assert( p->pPrior==0 ); /* Unable to flatten compound queries */ + if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; + pSrc = p->pSrc; + assert( pSrc && iFrom>=0 && iFromnSrc ); + pSubitem = &pSrc->a[iFrom]; + iParent = pSubitem->iCursor; + pSub = pSubitem->pSelect; + assert( pSub!=0 ); + if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ + if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */ + pSubSrc = pSub->pSrc; + assert( pSubSrc ); + /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, + ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET + ** because they could be computed at compile-time. But when LIMIT and OFFSET + ** became arbitrary expressions, we were forced to add restrictions (13) + ** and (14). */ + if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ + if( pSub->pOffset ) return 0; /* Restriction (14) */ + if( p->pRightmost && pSub->pLimit ){ + return 0; /* Restriction (15) */ + } + if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ + if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ + if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ + return 0; /* Restrictions (8)(9) */ + } + if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ + return 0; /* Restriction (6) */ + } + if( p->pOrderBy && pSub->pOrderBy ){ + return 0; /* Restriction (11) */ + } + if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ + if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ + if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ + return 0; /* Restriction (21) */ + } + + /* OBSOLETE COMMENT 1: + ** Restriction 3: If the subquery is a join, make sure the subquery is + ** not used as the right operand of an outer join. Examples of why this + ** is not allowed: + ** + ** t1 LEFT OUTER JOIN (t2 JOIN t3) + ** + ** If we flatten the above, we would get + ** + ** (t1 LEFT OUTER JOIN t2) JOIN t3 + ** + ** which is not at all the same thing. + ** + ** OBSOLETE COMMENT 2: + ** Restriction 12: If the subquery is the right operand of a left outer + ** join, make sure the subquery has no WHERE clause. + ** An examples of why this is not allowed: + ** + ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) + ** + ** If we flatten the above, we would get + ** + ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 + ** + ** But the t2.x>0 test will always fail on a NULL row of t2, which + ** effectively converts the OUTER JOIN into an INNER JOIN. + ** + ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: + ** Ticket #3300 shows that flattening the right term of a LEFT JOIN + ** is fraught with danger. Best to avoid the whole thing. If the + ** subquery is the right term of a LEFT JOIN, then do not flatten. + */ + if( (pSubitem->jointype & JT_OUTER)!=0 ){ + return 0; + } + + /* Restriction 17: If the sub-query is a compound SELECT, then it must + ** use only the UNION ALL operator. And none of the simple select queries + ** that make up the compound SELECT are allowed to be aggregate or distinct + ** queries. + */ + if( pSub->pPrior ){ + if( pSub->pOrderBy ){ + return 0; /* Restriction 20 */ + } + if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ + return 0; + } + for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ + testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); + testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); + assert( pSub->pSrc!=0 ); + if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 + || (pSub1->pPrior && pSub1->op!=TK_ALL) + || pSub1->pSrc->nSrc<1 + || pSub->pEList->nExpr!=pSub1->pEList->nExpr + ){ + return 0; + } + testcase( pSub1->pSrc->nSrc>1 ); + } + + /* Restriction 18. */ + if( p->pOrderBy ){ + int ii; + for(ii=0; iipOrderBy->nExpr; ii++){ + if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0; + } + } + } + + /***** If we reach this point, flattening is permitted. *****/ + + /* Authorize the subquery */ + pParse->zAuthContext = pSubitem->zName; + TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); + testcase( i==SQLITE_DENY ); + pParse->zAuthContext = zSavedAuthContext; + + /* If the sub-query is a compound SELECT statement, then (by restrictions + ** 17 and 18 above) it must be a UNION ALL and the parent query must + ** be of the form: + ** + ** SELECT FROM () + ** + ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block + ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or + ** OFFSET clauses and joins them to the left-hand-side of the original + ** using UNION ALL operators. In this case N is the number of simple + ** select statements in the compound sub-query. + ** + ** Example: + ** + ** SELECT a+1 FROM ( + ** SELECT x FROM tab + ** UNION ALL + ** SELECT y FROM tab + ** UNION ALL + ** SELECT abs(z*2) FROM tab2 + ** ) WHERE a!=5 ORDER BY 1 + ** + ** Transformed into: + ** + ** SELECT x+1 FROM tab WHERE x+1!=5 + ** UNION ALL + ** SELECT y+1 FROM tab WHERE y+1!=5 + ** UNION ALL + ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 + ** ORDER BY 1 + ** + ** We call this the "compound-subquery flattening". + */ + for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ + Select *pNew; + ExprList *pOrderBy = p->pOrderBy; + Expr *pLimit = p->pLimit; + Expr *pOffset = p->pOffset; + Select *pPrior = p->pPrior; + p->pOrderBy = 0; + p->pSrc = 0; + p->pPrior = 0; + p->pLimit = 0; + p->pOffset = 0; + pNew = sqlite3SelectDup(db, p, 0); + p->pOffset = pOffset; + p->pLimit = pLimit; + p->pOrderBy = pOrderBy; + p->pSrc = pSrc; + p->op = TK_ALL; + p->pRightmost = 0; + if( pNew==0 ){ + pNew = pPrior; + }else{ + pNew->pPrior = pPrior; + pNew->pRightmost = 0; + } + p->pPrior = pNew; + if( db->mallocFailed ) return 1; + } + + /* Begin flattening the iFrom-th entry of the FROM clause + ** in the outer query. + */ + pSub = pSub1 = pSubitem->pSelect; + + /* Delete the transient table structure associated with the + ** subquery + */ + sqlite3DbFree(db, pSubitem->zDatabase); + sqlite3DbFree(db, pSubitem->zName); + sqlite3DbFree(db, pSubitem->zAlias); + pSubitem->zDatabase = 0; + pSubitem->zName = 0; + pSubitem->zAlias = 0; + pSubitem->pSelect = 0; + + /* Defer deleting the Table object associated with the + ** subquery until code generation is + ** complete, since there may still exist Expr.pTab entries that + ** refer to the subquery even after flattening. Ticket #3346. + ** + ** pSubitem->pTab is always non-NULL by test restrictions and tests above. + */ + if( ALWAYS(pSubitem->pTab!=0) ){ + Table *pTabToDel = pSubitem->pTab; + if( pTabToDel->nRef==1 ){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + pTabToDel->pNextZombie = pToplevel->pZombieTab; + pToplevel->pZombieTab = pTabToDel; + }else{ + pTabToDel->nRef--; + } + pSubitem->pTab = 0; + } + + /* The following loop runs once for each term in a compound-subquery + ** flattening (as described above). If we are doing a different kind + ** of flattening - a flattening other than a compound-subquery flattening - + ** then this loop only runs once. + ** + ** This loop moves all of the FROM elements of the subquery into the + ** the FROM clause of the outer query. Before doing this, remember + ** the cursor number for the original outer query FROM element in + ** iParent. The iParent cursor will never be used. Subsequent code + ** will scan expressions looking for iParent references and replace + ** those references with expressions that resolve to the subquery FROM + ** elements we are now copying in. + */ + for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ + int nSubSrc; + u8 jointype = 0; + pSubSrc = pSub->pSrc; /* FROM clause of subquery */ + nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ + pSrc = pParent->pSrc; /* FROM clause of the outer query */ + + if( pSrc ){ + assert( pParent==p ); /* First time through the loop */ + jointype = pSubitem->jointype; + }else{ + assert( pParent!=p ); /* 2nd and subsequent times through the loop */ + pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); + if( pSrc==0 ){ + assert( db->mallocFailed ); + break; + } + } + + /* The subquery uses a single slot of the FROM clause of the outer + ** query. If the subquery has more than one element in its FROM clause, + ** then expand the outer query to make space for it to hold all elements + ** of the subquery. + ** + ** Example: + ** + ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; + ** + ** The outer query has 3 slots in its FROM clause. One slot of the + ** outer query (the middle slot) is used by the subquery. The next + ** block of code will expand the out query to 4 slots. The middle + ** slot is expanded to two slots in order to make space for the + ** two elements in the FROM clause of the subquery. + */ + if( nSubSrc>1 ){ + pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); + if( db->mallocFailed ){ + break; + } + } + + /* Transfer the FROM clause terms from the subquery into the + ** outer query. + */ + for(i=0; ia[i+iFrom].pUsing); + pSrc->a[i+iFrom] = pSubSrc->a[i]; + memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); + } + pSrc->a[iFrom].jointype = jointype; + + /* Now begin substituting subquery result set expressions for + ** references to the iParent in the outer query. + ** + ** Example: + ** + ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; + ** \ \_____________ subquery __________/ / + ** \_____________________ outer query ______________________________/ + ** + ** We look at every expression in the outer query and every place we see + ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". + */ + pList = pParent->pEList; + for(i=0; inExpr; i++){ + if( pList->a[i].zName==0 ){ + char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); + sqlite3Dequote(zName); + pList->a[i].zName = zName; + } + } + substExprList(db, pParent->pEList, iParent, pSub->pEList); + if( isAgg ){ + substExprList(db, pParent->pGroupBy, iParent, pSub->pEList); + pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); + } + if( pSub->pOrderBy ){ + assert( pParent->pOrderBy==0 ); + pParent->pOrderBy = pSub->pOrderBy; + pSub->pOrderBy = 0; + }else if( pParent->pOrderBy ){ + substExprList(db, pParent->pOrderBy, iParent, pSub->pEList); + } + if( pSub->pWhere ){ + pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); + }else{ + pWhere = 0; + } + if( subqueryIsAgg ){ + assert( pParent->pHaving==0 ); + pParent->pHaving = pParent->pWhere; + pParent->pWhere = pWhere; + pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList); + pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, + sqlite3ExprDup(db, pSub->pHaving, 0)); + assert( pParent->pGroupBy==0 ); + pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); + }else{ + pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList); + pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); + } + + /* The flattened query is distinct if either the inner or the + ** outer query is distinct. + */ + pParent->selFlags |= pSub->selFlags & SF_Distinct; + + /* + ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; + ** + ** One is tempted to try to add a and b to combine the limits. But this + ** does not work if either limit is negative. + */ + if( pSub->pLimit ){ + pParent->pLimit = pSub->pLimit; + pSub->pLimit = 0; + } + } + + /* Finially, delete what is left of the subquery and return + ** success. + */ + sqlite3SelectDelete(db, pSub1); + + return 1; +} +#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ + +/* +** Based on the contents of the AggInfo structure indicated by the first +** argument, this function checks if the following are true: +** +** * the query contains just a single aggregate function, +** * the aggregate function is either min() or max(), and +** * the argument to the aggregate function is a column value. +** +** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX +** is returned as appropriate. Also, *ppMinMax is set to point to the +** list of arguments passed to the aggregate before returning. +** +** Or, if the conditions above are not met, *ppMinMax is set to 0 and +** WHERE_ORDERBY_NORMAL is returned. +*/ +static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){ + int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ + + *ppMinMax = 0; + if( pAggInfo->nFunc==1 ){ + Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */ + ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */ + + assert( pExpr->op==TK_AGG_FUNCTION ); + if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){ + const char *zFunc = pExpr->u.zToken; + if( sqlite3StrICmp(zFunc, "min")==0 ){ + eRet = WHERE_ORDERBY_MIN; + *ppMinMax = pEList; + }else if( sqlite3StrICmp(zFunc, "max")==0 ){ + eRet = WHERE_ORDERBY_MAX; + *ppMinMax = pEList; + } + } + } + + assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 ); + return eRet; +} + +/* +** The select statement passed as the first argument is an aggregate query. +** The second argment is the associated aggregate-info object. This +** function tests if the SELECT is of the form: +** +** SELECT count(*) FROM +** +** where table is a database table, not a sub-select or view. If the query +** does match this pattern, then a pointer to the Table object representing +** is returned. Otherwise, 0 is returned. +*/ +static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ + Table *pTab; + Expr *pExpr; + + assert( !p->pGroupBy ); + + if( p->pWhere || p->pEList->nExpr!=1 + || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect + ){ + return 0; + } + pTab = p->pSrc->a[0].pTab; + pExpr = p->pEList->a[0].pExpr; + assert( pTab && !pTab->pSelect && pExpr ); + + if( IsVirtual(pTab) ) return 0; + if( pExpr->op!=TK_AGG_FUNCTION ) return 0; + if( NEVER(pAggInfo->nFunc==0) ) return 0; + if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; + if( pExpr->flags&EP_Distinct ) return 0; + + return pTab; +} + +/* +** If the source-list item passed as an argument was augmented with an +** INDEXED BY clause, then try to locate the specified index. If there +** was such a clause and the named index cannot be found, return +** SQLITE_ERROR and leave an error in pParse. Otherwise, populate +** pFrom->pIndex and return SQLITE_OK. +*/ +int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ + if( pFrom->pTab && pFrom->zIndex ){ + Table *pTab = pFrom->pTab; + char *zIndex = pFrom->zIndex; + Index *pIdx; + for(pIdx=pTab->pIndex; + pIdx && sqlite3StrICmp(pIdx->zName, zIndex); + pIdx=pIdx->pNext + ); + if( !pIdx ){ + sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0); + pParse->checkSchema = 1; + return SQLITE_ERROR; + } + pFrom->pIndex = pIdx; + } + return SQLITE_OK; +} +/* +** Detect compound SELECT statements that use an ORDER BY clause with +** an alternative collating sequence. +** +** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... +** +** These are rewritten as a subquery: +** +** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) +** ORDER BY ... COLLATE ... +** +** This transformation is necessary because the multiSelectOrderBy() routine +** above that generates the code for a compound SELECT with an ORDER BY clause +** uses a merge algorithm that requires the same collating sequence on the +** result columns as on the ORDER BY clause. See ticket +** http://www.sqlite.org/src/info/6709574d2a +** +** This transformation is only needed for EXCEPT, INTERSECT, and UNION. +** The UNION ALL operator works fine with multiSelectOrderBy() even when +** there are COLLATE terms in the ORDER BY. +*/ +static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ + int i; + Select *pNew; + Select *pX; + sqlite3 *db; + struct ExprList_item *a; + SrcList *pNewSrc; + Parse *pParse; + Token dummy; + + if( p->pPrior==0 ) return WRC_Continue; + if( p->pOrderBy==0 ) return WRC_Continue; + for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} + if( pX==0 ) return WRC_Continue; + a = p->pOrderBy->a; + for(i=p->pOrderBy->nExpr-1; i>=0; i--){ + if( a[i].pExpr->flags & EP_Collate ) break; + } + if( i<0 ) return WRC_Continue; + + /* If we reach this point, that means the transformation is required. */ + + pParse = pWalker->pParse; + db = pParse->db; + pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); + if( pNew==0 ) return WRC_Abort; + memset(&dummy, 0, sizeof(dummy)); + pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); + if( pNewSrc==0 ) return WRC_Abort; + *pNew = *p; + p->pSrc = pNewSrc; + p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0)); + p->op = TK_SELECT; + p->pWhere = 0; + pNew->pGroupBy = 0; + pNew->pHaving = 0; + pNew->pOrderBy = 0; + p->pPrior = 0; + pNew->pLimit = 0; + pNew->pOffset = 0; + return WRC_Continue; +} + +/* +** This routine is a Walker callback for "expanding" a SELECT statement. +** "Expanding" means to do the following: +** +** (1) Make sure VDBE cursor numbers have been assigned to every +** element of the FROM clause. +** +** (2) Fill in the pTabList->a[].pTab fields in the SrcList that +** defines FROM clause. When views appear in the FROM clause, +** fill pTabList->a[].pSelect with a copy of the SELECT statement +** that implements the view. A copy is made of the view's SELECT +** statement so that we can freely modify or delete that statement +** without worrying about messing up the presistent representation +** of the view. +** +** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword +** on joins and the ON and USING clause of joins. +** +** (4) Scan the list of columns in the result set (pEList) looking +** for instances of the "*" operator or the TABLE.* operator. +** If found, expand each "*" to be every column in every table +** and TABLE.* to be every column in TABLE. +** +*/ +static int selectExpander(Walker *pWalker, Select *p){ + Parse *pParse = pWalker->pParse; + int i, j, k; + SrcList *pTabList; + ExprList *pEList; + struct SrcList_item *pFrom; + sqlite3 *db = pParse->db; + Expr *pE, *pRight, *pExpr; + u16 selFlags = p->selFlags; + + p->selFlags |= SF_Expanded; + if( db->mallocFailed ){ + return WRC_Abort; + } + if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ + return WRC_Prune; + } + pTabList = p->pSrc; + pEList = p->pEList; + + /* Make sure cursor numbers have been assigned to all entries in + ** the FROM clause of the SELECT statement. + */ + sqlite3SrcListAssignCursors(pParse, pTabList); + + /* Look up every table named in the FROM clause of the select. If + ** an entry of the FROM clause is a subquery instead of a table or view, + ** then create a transient table structure to describe the subquery. + */ + for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ + Table *pTab; + if( pFrom->pTab!=0 ){ + /* This statement has already been prepared. There is no need + ** to go further. */ + assert( i==0 ); + return WRC_Prune; + } + if( pFrom->zName==0 ){ +#ifndef SQLITE_OMIT_SUBQUERY + Select *pSel = pFrom->pSelect; + /* A sub-query in the FROM clause of a SELECT */ + assert( pSel!=0 ); + assert( pFrom->pTab==0 ); + sqlite3WalkSelect(pWalker, pSel); + pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); + if( pTab==0 ) return WRC_Abort; + pTab->nRef = 1; + pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab); + while( pSel->pPrior ){ pSel = pSel->pPrior; } + selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol); + pTab->iPKey = -1; + pTab->nRowEst = 1048576; + pTab->tabFlags |= TF_Ephemeral; +#endif + }else{ + /* An ordinary table or view name in the FROM clause */ + assert( pFrom->pTab==0 ); + pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); + if( pTab==0 ) return WRC_Abort; + if( pTab->nRef==0xffff ){ + sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", + pTab->zName); + pFrom->pTab = 0; + return WRC_Abort; + } + pTab->nRef++; +#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) + if( pTab->pSelect || IsVirtual(pTab) ){ + /* We reach here if the named table is a really a view */ + if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; + assert( pFrom->pSelect==0 ); + pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); + sqlite3WalkSelect(pWalker, pFrom->pSelect); + } +#endif + } + + /* Locate the index named by the INDEXED BY clause, if any. */ + if( sqlite3IndexedByLookup(pParse, pFrom) ){ + return WRC_Abort; + } + } + + /* Process NATURAL keywords, and ON and USING clauses of joins. + */ + if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ + return WRC_Abort; + } + + /* For every "*" that occurs in the column list, insert the names of + ** all columns in all tables. And for every TABLE.* insert the names + ** of all columns in TABLE. The parser inserted a special expression + ** with the TK_ALL operator for each "*" that it found in the column list. + ** The following code just has to locate the TK_ALL expressions and expand + ** each one to the list of all columns in all tables. + ** + ** The first loop just checks to see if there are any "*" operators + ** that need expanding. + */ + for(k=0; knExpr; k++){ + pE = pEList->a[k].pExpr; + if( pE->op==TK_ALL ) break; + assert( pE->op!=TK_DOT || pE->pRight!=0 ); + assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); + if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break; + } + if( knExpr ){ + /* + ** If we get here it means the result set contains one or more "*" + ** operators that need to be expanded. Loop through each expression + ** in the result set and expand them one by one. + */ + struct ExprList_item *a = pEList->a; + ExprList *pNew = 0; + int flags = pParse->db->flags; + int longNames = (flags & SQLITE_FullColNames)!=0 + && (flags & SQLITE_ShortColNames)==0; + + /* When processing FROM-clause subqueries, it is always the case + ** that full_column_names=OFF and short_column_names=ON. The + ** sqlite3ResultSetOfSelect() routine makes it so. */ + assert( (p->selFlags & SF_NestedFrom)==0 + || ((flags & SQLITE_FullColNames)==0 && + (flags & SQLITE_ShortColNames)!=0) ); + + for(k=0; knExpr; k++){ + pE = a[k].pExpr; + pRight = pE->pRight; + assert( pE->op!=TK_DOT || pRight!=0 ); + if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){ + /* This particular expression does not need to be expanded. + */ + pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); + if( pNew ){ + pNew->a[pNew->nExpr-1].zName = a[k].zName; + pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; + a[k].zName = 0; + a[k].zSpan = 0; + } + a[k].pExpr = 0; + }else{ + /* This expression is a "*" or a "TABLE.*" and needs to be + ** expanded. */ + int tableSeen = 0; /* Set to 1 when TABLE matches */ + char *zTName = 0; /* text of name of TABLE */ + if( pE->op==TK_DOT ){ + assert( pE->pLeft!=0 ); + assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); + zTName = pE->pLeft->u.zToken; + } + for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ + Table *pTab = pFrom->pTab; + Select *pSub = pFrom->pSelect; + char *zTabName = pFrom->zAlias; + const char *zSchemaName = 0; + int iDb; + if( zTabName==0 ){ + zTabName = pTab->zName; + } + if( db->mallocFailed ) break; + if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ + pSub = 0; + if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ + continue; + } + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*"; + } + for(j=0; jnCol; j++){ + char *zName = pTab->aCol[j].zName; + char *zColname; /* The computed column name */ + char *zToFree; /* Malloced string that needs to be freed */ + Token sColname; /* Computed column name as a token */ + + assert( zName ); + if( zTName && pSub + && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 + ){ + continue; + } + + /* If a column is marked as 'hidden' (currently only possible + ** for virtual tables), do not include it in the expanded + ** result-set list. + */ + if( IsHiddenColumn(&pTab->aCol[j]) ){ + assert(IsVirtual(pTab)); + continue; + } + tableSeen = 1; + + if( i>0 && zTName==0 ){ + if( (pFrom->jointype & JT_NATURAL)!=0 + && tableAndColumnIndex(pTabList, i, zName, 0, 0) + ){ + /* In a NATURAL join, omit the join columns from the + ** table to the right of the join */ + continue; + } + if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ + /* In a join with a USING clause, omit columns in the + ** using clause from the table on the right. */ + continue; + } + } + pRight = sqlite3Expr(db, TK_ID, zName); + zColname = zName; + zToFree = 0; + if( longNames || pTabList->nSrc>1 ){ + Expr *pLeft; + pLeft = sqlite3Expr(db, TK_ID, zTabName); + pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); + if( zSchemaName ){ + pLeft = sqlite3Expr(db, TK_ID, zSchemaName); + pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0); + } + if( longNames ){ + zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); + zToFree = zColname; + } + }else{ + pExpr = pRight; + } + pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); + sColname.z = zColname; + sColname.n = sqlite3Strlen30(zColname); + sqlite3ExprListSetName(pParse, pNew, &sColname, 0); + if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ + struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; + if( pSub ){ + pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); + testcase( pX->zSpan==0 ); + }else{ + pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", + zSchemaName, zTabName, zColname); + testcase( pX->zSpan==0 ); + } + pX->bSpanIsTab = 1; + } + sqlite3DbFree(db, zToFree); + } + } + if( !tableSeen ){ + if( zTName ){ + sqlite3ErrorMsg(pParse, "no such table: %s", zTName); + }else{ + sqlite3ErrorMsg(pParse, "no tables specified"); + } + } + } + } + sqlite3ExprListDelete(db, pEList); + p->pEList = pNew; + } +#if SQLITE_MAX_COLUMN + if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + sqlite3ErrorMsg(pParse, "too many columns in result set"); + } +#endif + return WRC_Continue; +} + +/* +** No-op routine for the parse-tree walker. +** +** When this routine is the Walker.xExprCallback then expression trees +** are walked without any actions being taken at each node. Presumably, +** when this routine is used for Walker.xExprCallback then +** Walker.xSelectCallback is set to do something useful for every +** subquery in the parser tree. +*/ +static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return WRC_Continue; +} + +/* +** This routine "expands" a SELECT statement and all of its subqueries. +** For additional information on what it means to "expand" a SELECT +** statement, see the comment on the selectExpand worker callback above. +** +** Expanding a SELECT statement is the first step in processing a +** SELECT statement. The SELECT statement must be expanded before +** name resolution is performed. +** +** If anything goes wrong, an error message is written into pParse. +** The calling function can detect the problem by looking at pParse->nErr +** and/or pParse->db->mallocFailed. +*/ +static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ + Walker w; + memset(&w, 0, sizeof(w)); + w.xExprCallback = exprWalkNoop; + w.pParse = pParse; + if( pParse->hasCompound ){ + w.xSelectCallback = convertCompoundSelectToSubquery; + sqlite3WalkSelect(&w, pSelect); + } + w.xSelectCallback = selectExpander; + sqlite3WalkSelect(&w, pSelect); +} + + +#ifndef SQLITE_OMIT_SUBQUERY +/* +** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() +** interface. +** +** For each FROM-clause subquery, add Column.zType and Column.zColl +** information to the Table structure that represents the result set +** of that subquery. +** +** The Table structure that represents the result set was constructed +** by selectExpander() but the type and collation information was omitted +** at that point because identifiers had not yet been resolved. This +** routine is called after identifier resolution. +*/ +static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ + Parse *pParse; + int i; + SrcList *pTabList; + struct SrcList_item *pFrom; + + assert( p->selFlags & SF_Resolved ); + if( (p->selFlags & SF_HasTypeInfo)==0 ){ + p->selFlags |= SF_HasTypeInfo; + pParse = pWalker->pParse; + pTabList = p->pSrc; + for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ + Table *pTab = pFrom->pTab; + if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){ + /* A sub-query in the FROM clause of a SELECT */ + Select *pSel = pFrom->pSelect; + assert( pSel ); + while( pSel->pPrior ) pSel = pSel->pPrior; + selectAddColumnTypeAndCollation(pParse, pTab, pSel); + } + } + } + return WRC_Continue; +} +#endif + + +/* +** This routine adds datatype and collating sequence information to +** the Table structures of all FROM-clause subqueries in a +** SELECT statement. +** +** Use this routine after name resolution. +*/ +static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ +#ifndef SQLITE_OMIT_SUBQUERY + Walker w; + memset(&w, 0, sizeof(w)); + w.xSelectCallback = selectAddSubqueryTypeInfo; + w.xExprCallback = exprWalkNoop; + w.pParse = pParse; + w.bSelectDepthFirst = 1; + sqlite3WalkSelect(&w, pSelect); +#endif +} + + +/* +** This routine sets up a SELECT statement for processing. The +** following is accomplished: +** +** * VDBE Cursor numbers are assigned to all FROM-clause terms. +** * Ephemeral Table objects are created for all FROM-clause subqueries. +** * ON and USING clauses are shifted into WHERE statements +** * Wildcards "*" and "TABLE.*" in result sets are expanded. +** * Identifiers in expression are matched to tables. +** +** This routine acts recursively on all subqueries within the SELECT. +*/ +void sqlite3SelectPrep( + Parse *pParse, /* The parser context */ + Select *p, /* The SELECT statement being coded. */ + NameContext *pOuterNC /* Name context for container */ +){ + sqlite3 *db; + if( NEVER(p==0) ) return; + db = pParse->db; + if( db->mallocFailed ) return; + if( p->selFlags & SF_HasTypeInfo ) return; + sqlite3SelectExpand(pParse, p); + if( pParse->nErr || db->mallocFailed ) return; + sqlite3ResolveSelectNames(pParse, p, pOuterNC); + if( pParse->nErr || db->mallocFailed ) return; + sqlite3SelectAddTypeInfo(pParse, p); +} + +/* +** Reset the aggregate accumulator. +** +** The aggregate accumulator is a set of memory cells that hold +** intermediate results while calculating an aggregate. This +** routine generates code that stores NULLs in all of those memory +** cells. +*/ +static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ + Vdbe *v = pParse->pVdbe; + int i; + struct AggInfo_func *pFunc; + if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ + return; + } + for(i=0; inColumn; i++){ + sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); + } + for(pFunc=pAggInfo->aFunc, i=0; inFunc; i++, pFunc++){ + sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); + if( pFunc->iDistinct>=0 ){ + Expr *pE = pFunc->pExpr; + assert( !ExprHasProperty(pE, EP_xIsSelect) ); + if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ + sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " + "argument"); + pFunc->iDistinct = -1; + }else{ + KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList); + sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, + (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + } + } + } +} + +/* +** Invoke the OP_AggFinalize opcode for every aggregate function +** in the AggInfo structure. +*/ +static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ + Vdbe *v = pParse->pVdbe; + int i; + struct AggInfo_func *pF; + for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ + ExprList *pList = pF->pExpr->x.pList; + assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); + sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, + (void*)pF->pFunc, P4_FUNCDEF); + } +} + +/* +** Update the accumulator memory cells for an aggregate based on +** the current cursor position. +*/ +static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ + Vdbe *v = pParse->pVdbe; + int i; + int regHit = 0; + int addrHitTest = 0; + struct AggInfo_func *pF; + struct AggInfo_col *pC; + + pAggInfo->directMode = 1; + sqlite3ExprCacheClear(pParse); + for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ + int nArg; + int addrNext = 0; + int regAgg; + ExprList *pList = pF->pExpr->x.pList; + assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); + if( pList ){ + nArg = pList->nExpr; + regAgg = sqlite3GetTempRange(pParse, nArg); + sqlite3ExprCodeExprList(pParse, pList, regAgg, 1); + }else{ + nArg = 0; + regAgg = 0; + } + if( pF->iDistinct>=0 ){ + addrNext = sqlite3VdbeMakeLabel(v); + assert( nArg==1 ); + codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); + } + if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ + CollSeq *pColl = 0; + struct ExprList_item *pItem; + int j; + assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ + for(j=0, pItem=pList->a; !pColl && jpExpr); + } + if( !pColl ){ + pColl = pParse->db->pDfltColl; + } + if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; + sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); + } + sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, + (void*)pF->pFunc, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, (u8)nArg); + sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); + sqlite3ReleaseTempRange(pParse, regAgg, nArg); + if( addrNext ){ + sqlite3VdbeResolveLabel(v, addrNext); + sqlite3ExprCacheClear(pParse); + } + } + + /* Before populating the accumulator registers, clear the column cache. + ** Otherwise, if any of the required column values are already present + ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value + ** to pC->iMem. But by the time the value is used, the original register + ** may have been used, invalidating the underlying buffer holding the + ** text or blob value. See ticket [883034dcb5]. + ** + ** Another solution would be to change the OP_SCopy used to copy cached + ** values to an OP_Copy. + */ + if( regHit ){ + addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); + } + sqlite3ExprCacheClear(pParse); + for(i=0, pC=pAggInfo->aCol; inAccumulator; i++, pC++){ + sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); + } + pAggInfo->directMode = 0; + sqlite3ExprCacheClear(pParse); + if( addrHitTest ){ + sqlite3VdbeJumpHere(v, addrHitTest); + } +} + +/* +** Add a single OP_Explain instruction to the VDBE to explain a simple +** count(*) query ("SELECT count(*) FROM pTab"). +*/ +#ifndef SQLITE_OMIT_EXPLAIN +static void explainSimpleCount( + Parse *pParse, /* Parse context */ + Table *pTab, /* Table being queried */ + Index *pIdx /* Index used to optimize scan, or NULL */ +){ + if( pParse->explain==2 ){ + char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", + pTab->zName, + pIdx ? " USING COVERING INDEX " : "", + pIdx ? pIdx->zName : "" + ); + sqlite3VdbeAddOp4( + pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC + ); + } +} +#else +# define explainSimpleCount(a,b,c) +#endif + +/* +** Generate code for the SELECT statement given in the p argument. +** +** The results are distributed in various ways depending on the +** contents of the SelectDest structure pointed to by argument pDest +** as follows: +** +** pDest->eDest Result +** ------------ ------------------------------------------- +** SRT_Output Generate a row of output (using the OP_ResultRow +** opcode) for each row in the result set. +** +** SRT_Mem Only valid if the result is a single column. +** Store the first column of the first result row +** in register pDest->iSDParm then abandon the rest +** of the query. This destination implies "LIMIT 1". +** +** SRT_Set The result must be a single column. Store each +** row of result as the key in table pDest->iSDParm. +** Apply the affinity pDest->affSdst before storing +** results. Used to implement "IN (SELECT ...)". +** +** SRT_Union Store results as a key in a temporary table +** identified by pDest->iSDParm. +** +** SRT_Except Remove results from the temporary table pDest->iSDParm. +** +** SRT_Table Store results in temporary table pDest->iSDParm. +** This is like SRT_EphemTab except that the table +** is assumed to already be open. +** +** SRT_EphemTab Create an temporary table pDest->iSDParm and store +** the result there. The cursor is left open after +** returning. This is like SRT_Table except that +** this destination uses OP_OpenEphemeral to create +** the table first. +** +** SRT_Coroutine Generate a co-routine that returns a new row of +** results each time it is invoked. The entry point +** of the co-routine is stored in register pDest->iSDParm. +** +** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result +** set is not empty. +** +** SRT_Discard Throw the results away. This is used by SELECT +** statements within triggers whose only purpose is +** the side-effects of functions. +** +** This routine returns the number of errors. If any errors are +** encountered, then an appropriate error message is left in +** pParse->zErrMsg. +** +** This routine does NOT free the Select structure passed in. The +** calling function needs to do that. +*/ +int sqlite3Select( + Parse *pParse, /* The parser context */ + Select *p, /* The SELECT statement being coded. */ + SelectDest *pDest /* What to do with the query results */ +){ + int i, j; /* Loop counters */ + WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ + Vdbe *v; /* The virtual machine under construction */ + int isAgg; /* True for select lists like "count(*)" */ + ExprList *pEList; /* List of columns to extract. */ + SrcList *pTabList; /* List of tables to select from */ + Expr *pWhere; /* The WHERE clause. May be NULL */ + ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ + ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ + Expr *pHaving; /* The HAVING clause. May be NULL */ + int rc = 1; /* Value to return from this function */ + int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ + DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ + AggInfo sAggInfo; /* Information used by aggregate queries */ + int iEnd; /* Address of the end of the query */ + sqlite3 *db; /* The database connection */ + +#ifndef SQLITE_OMIT_EXPLAIN + int iRestoreSelectId = pParse->iSelectId; + pParse->iSelectId = pParse->iNextSelectId++; +#endif + + db = pParse->db; + if( p==0 || db->mallocFailed || pParse->nErr ){ + return 1; + } + if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; + memset(&sAggInfo, 0, sizeof(sAggInfo)); + + if( IgnorableOrderby(pDest) ){ + assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || + pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); + /* If ORDER BY makes no difference in the output then neither does + ** DISTINCT so it can be removed too. */ + sqlite3ExprListDelete(db, p->pOrderBy); + p->pOrderBy = 0; + p->selFlags &= ~SF_Distinct; + } + sqlite3SelectPrep(pParse, p, 0); + pOrderBy = p->pOrderBy; + pTabList = p->pSrc; + pEList = p->pEList; + if( pParse->nErr || db->mallocFailed ){ + goto select_end; + } + isAgg = (p->selFlags & SF_Aggregate)!=0; + assert( pEList!=0 ); + + /* Begin generating code. + */ + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto select_end; + + /* If writing to memory or generating a set + ** only a single column may be output. + */ +#ifndef SQLITE_OMIT_SUBQUERY + if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ + goto select_end; + } +#endif + + /* Generate code for all sub-queries in the FROM clause + */ +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) + for(i=0; !p->pPrior && inSrc; i++){ + struct SrcList_item *pItem = &pTabList->a[i]; + SelectDest dest; + Select *pSub = pItem->pSelect; + int isAggSub; + + if( pSub==0 ) continue; + + /* Sometimes the code for a subquery will be generated more than + ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, + ** for example. In that case, do not regenerate the code to manifest + ** a view or the co-routine to implement a view. The first instance + ** is sufficient, though the subroutine to manifest the view does need + ** to be invoked again. */ + if( pItem->addrFillSub ){ + if( pItem->viaCoroutine==0 ){ + sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); + } + continue; + } + + /* Increment Parse.nHeight by the height of the largest expression + ** tree referred to by this, the parent select. The child select + ** may contain expression trees of at most + ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit + ** more conservative than necessary, but much easier than enforcing + ** an exact limit. + */ + pParse->nHeight += sqlite3SelectExprHeight(p); + + isAggSub = (pSub->selFlags & SF_Aggregate)!=0; + if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ + /* This subquery can be absorbed into its parent. */ + if( isAggSub ){ + isAgg = 1; + p->selFlags |= SF_Aggregate; + } + i = -1; + }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0 + && OptimizationEnabled(db, SQLITE_SubqCoroutine) + ){ + /* Implement a co-routine that will return a single row of the result + ** set on each invocation. + */ + int addrTop; + int addrEof; + pItem->regReturn = ++pParse->nMem; + addrEof = ++pParse->nMem; + /* Before coding the OP_Goto to jump to the start of the main routine, + ** ensure that the jump to the verify-schema routine has already + ** been coded. Otherwise, the verify-schema would likely be coded as + ** part of the co-routine. If the main routine then accessed the + ** database before invoking the co-routine for the first time (for + ** example to initialize a LIMIT register from a sub-select), it would + ** be doing so without having verified the schema version and obtained + ** the required db locks. See ticket d6b36be38. */ + sqlite3CodeVerifySchema(pParse, -1); + sqlite3VdbeAddOp0(v, OP_Goto); + addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor); + sqlite3VdbeChangeP5(v, 1); + VdbeComment((v, "coroutine for %s", pItem->pTab->zName)); + pItem->addrFillSub = addrTop; + sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof); + sqlite3VdbeChangeP5(v, 1); + sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); + explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); + sqlite3Select(pParse, pSub, &dest); + pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow; + pItem->viaCoroutine = 1; + sqlite3VdbeChangeP2(v, addrTop, dest.iSdst); + sqlite3VdbeChangeP3(v, addrTop, dest.nSdst); + sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof); + sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn); + VdbeComment((v, "end %s", pItem->pTab->zName)); + sqlite3VdbeJumpHere(v, addrTop-1); + sqlite3ClearTempRegCache(pParse); + }else{ + /* Generate a subroutine that will fill an ephemeral table with + ** the content of this subquery. pItem->addrFillSub will point + ** to the address of the generated subroutine. pItem->regReturn + ** is a register allocated to hold the subroutine return address + */ + int topAddr; + int onceAddr = 0; + int retAddr; + assert( pItem->addrFillSub==0 ); + pItem->regReturn = ++pParse->nMem; + topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); + pItem->addrFillSub = topAddr+1; + VdbeNoopComment((v, "materialize %s", pItem->pTab->zName)); + if( pItem->isCorrelated==0 ){ + /* If the subquery is not correlated and if we are not inside of + ** a trigger, then we only need to compute the value of the subquery + ** once. */ + onceAddr = sqlite3CodeOnce(pParse); + } + sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); + explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); + sqlite3Select(pParse, pSub, &dest); + pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow; + if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); + retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); + VdbeComment((v, "end %s", pItem->pTab->zName)); + sqlite3VdbeChangeP1(v, topAddr, retAddr); + sqlite3ClearTempRegCache(pParse); + } + if( /*pParse->nErr ||*/ db->mallocFailed ){ + goto select_end; + } + pParse->nHeight -= sqlite3SelectExprHeight(p); + pTabList = p->pSrc; + if( !IgnorableOrderby(pDest) ){ + pOrderBy = p->pOrderBy; + } + } + pEList = p->pEList; +#endif + pWhere = p->pWhere; + pGroupBy = p->pGroupBy; + pHaving = p->pHaving; + sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; + +#ifndef SQLITE_OMIT_COMPOUND_SELECT + /* If there is are a sequence of queries, do the earlier ones first. + */ + if( p->pPrior ){ + if( p->pRightmost==0 ){ + Select *pLoop, *pRight = 0; + int cnt = 0; + int mxSelect; + for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ + pLoop->pRightmost = p; + pLoop->pNext = pRight; + pRight = pLoop; + } + mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; + if( mxSelect && cnt>mxSelect ){ + sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); + goto select_end; + } + } + rc = multiSelect(pParse, p, pDest); + explainSetInteger(pParse->iSelectId, iRestoreSelectId); + return rc; + } +#endif + + /* If there is both a GROUP BY and an ORDER BY clause and they are + ** identical, then disable the ORDER BY clause since the GROUP BY + ** will cause elements to come out in the correct order. This is + ** an optimization - the correct answer should result regardless. + ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER + ** to disable this optimization for testing purposes. + */ + if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0 + && OptimizationEnabled(db, SQLITE_GroupByOrder) ){ + pOrderBy = 0; + } + + /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and + ** if the select-list is the same as the ORDER BY list, then this query + ** can be rewritten as a GROUP BY. In other words, this: + ** + ** SELECT DISTINCT xyz FROM ... ORDER BY xyz + ** + ** is transformed to: + ** + ** SELECT xyz FROM ... GROUP BY xyz + ** + ** The second form is preferred as a single index (or temp-table) may be + ** used for both the ORDER BY and DISTINCT processing. As originally + ** written the query must use a temp-table for at least one of the ORDER + ** BY and DISTINCT, and an index or separate temp-table for the other. + */ + if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct + && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0 + ){ + p->selFlags &= ~SF_Distinct; + p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0); + pGroupBy = p->pGroupBy; + pOrderBy = 0; + /* Notice that even thought SF_Distinct has been cleared from p->selFlags, + ** the sDistinct.isTnct is still set. Hence, isTnct represents the + ** original setting of the SF_Distinct flag, not the current setting */ + assert( sDistinct.isTnct ); + } + + /* If there is an ORDER BY clause, then this sorting + ** index might end up being unused if the data can be + ** extracted in pre-sorted order. If that is the case, then the + ** OP_OpenEphemeral instruction will be changed to an OP_Noop once + ** we figure out that the sorting index is not needed. The addrSortIndex + ** variable is used to facilitate that change. + */ + if( pOrderBy ){ + KeyInfo *pKeyInfo; + pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); + pOrderBy->iECursor = pParse->nTab++; + p->addrOpenEphm[2] = addrSortIndex = + sqlite3VdbeAddOp4(v, OP_OpenEphemeral, + pOrderBy->iECursor, pOrderBy->nExpr+2, 0, + (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + }else{ + addrSortIndex = -1; + } + + /* If the output is destined for a temporary table, open that table. + */ + if( pDest->eDest==SRT_EphemTab ){ + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); + } + + /* Set the limiter. + */ + iEnd = sqlite3VdbeMakeLabel(v); + p->nSelectRow = LARGEST_INT64; + computeLimitRegisters(pParse, p, iEnd); + if( p->iLimit==0 && addrSortIndex>=0 ){ + sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen; + p->selFlags |= SF_UseSorter; + } + + /* Open a virtual index to use for the distinct set. + */ + if( p->selFlags & SF_Distinct ){ + sDistinct.tabTnct = pParse->nTab++; + sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, + sDistinct.tabTnct, 0, 0, + (char*)keyInfoFromExprList(pParse, p->pEList), + P4_KEYINFO_HANDOFF); + sqlite3VdbeChangeP5(v, BTREE_UNORDERED); + sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; + }else{ + sDistinct.eTnctType = WHERE_DISTINCT_NOOP; + } + + if( !isAgg && pGroupBy==0 ){ + /* No aggregate functions and no GROUP BY clause */ + u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); + + /* Begin the database scan. */ + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList, + wctrlFlags, 0); + if( pWInfo==0 ) goto select_end; + if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ + p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); + } + if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ + sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); + } + if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0; + + /* If sorting index that was created by a prior OP_OpenEphemeral + ** instruction ended up not being needed, then change the OP_OpenEphemeral + ** into an OP_Noop. + */ + if( addrSortIndex>=0 && pOrderBy==0 ){ + sqlite3VdbeChangeToNoop(v, addrSortIndex); + p->addrOpenEphm[2] = -1; + } + + /* Use the standard inner loop. */ + selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest, + sqlite3WhereContinueLabel(pWInfo), + sqlite3WhereBreakLabel(pWInfo)); + + /* End the database scan loop. + */ + sqlite3WhereEnd(pWInfo); + }else{ + /* This case when there exist aggregate functions or a GROUP BY clause + ** or both */ + NameContext sNC; /* Name context for processing aggregate information */ + int iAMem; /* First Mem address for storing current GROUP BY */ + int iBMem; /* First Mem address for previous GROUP BY */ + int iUseFlag; /* Mem address holding flag indicating that at least + ** one row of the input to the aggregator has been + ** processed */ + int iAbortFlag; /* Mem address which causes query abort if positive */ + int groupBySort; /* Rows come from source in GROUP BY order */ + int addrEnd; /* End of processing for this SELECT */ + int sortPTab = 0; /* Pseudotable used to decode sorting results */ + int sortOut = 0; /* Output register from the sorter */ + + /* Remove any and all aliases between the result set and the + ** GROUP BY clause. + */ + if( pGroupBy ){ + int k; /* Loop counter */ + struct ExprList_item *pItem; /* For looping over expression in a list */ + + for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ + pItem->iAlias = 0; + } + for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ + pItem->iAlias = 0; + } + if( p->nSelectRow>100 ) p->nSelectRow = 100; + }else{ + p->nSelectRow = 1; + } + + + /* Create a label to jump to when we want to abort the query */ + addrEnd = sqlite3VdbeMakeLabel(v); + + /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in + ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the + ** SELECT statement. + */ + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + sNC.pAggInfo = &sAggInfo; + sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; + sAggInfo.pGroupBy = pGroupBy; + sqlite3ExprAnalyzeAggList(&sNC, pEList); + sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); + if( pHaving ){ + sqlite3ExprAnalyzeAggregates(&sNC, pHaving); + } + sAggInfo.nAccumulator = sAggInfo.nColumn; + for(i=0; ix.pList); + sNC.ncFlags &= ~NC_InAggFunc; + } + if( db->mallocFailed ) goto select_end; + + /* Processing for aggregates with GROUP BY is very different and + ** much more complex than aggregates without a GROUP BY. + */ + if( pGroupBy ){ + KeyInfo *pKeyInfo; /* Keying information for the group by clause */ + int j1; /* A-vs-B comparision jump */ + int addrOutputRow; /* Start of subroutine that outputs a result row */ + int regOutputRow; /* Return address register for output subroutine */ + int addrSetAbort; /* Set the abort flag and return */ + int addrTopOfLoop; /* Top of the input loop */ + int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ + int addrReset; /* Subroutine for resetting the accumulator */ + int regReset; /* Return address register for reset subroutine */ + + /* If there is a GROUP BY clause we might need a sorting index to + ** implement it. Allocate that sorting index now. If it turns out + ** that we do not need it after all, the OP_SorterOpen instruction + ** will be converted into a Noop. + */ + sAggInfo.sortingIdx = pParse->nTab++; + pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); + addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, + sAggInfo.sortingIdx, sAggInfo.nSortingColumn, + 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + + /* Initialize memory locations used by GROUP BY aggregate processing + */ + iUseFlag = ++pParse->nMem; + iAbortFlag = ++pParse->nMem; + regOutputRow = ++pParse->nMem; + addrOutputRow = sqlite3VdbeMakeLabel(v); + regReset = ++pParse->nMem; + addrReset = sqlite3VdbeMakeLabel(v); + iAMem = pParse->nMem + 1; + pParse->nMem += pGroupBy->nExpr; + iBMem = pParse->nMem + 1; + pParse->nMem += pGroupBy->nExpr; + sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); + VdbeComment((v, "clear abort flag")); + sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); + VdbeComment((v, "indicate accumulator empty")); + sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); + + /* Begin a loop that will extract all source rows in GROUP BY order. + ** This might involve two separate loops with an OP_Sort in between, or + ** it might be a single loop that uses an index to extract information + ** in the right order to begin with. + */ + sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, + WHERE_GROUPBY, 0); + if( pWInfo==0 ) goto select_end; + if( sqlite3WhereIsOrdered(pWInfo) ){ + /* The optimizer is able to deliver rows in group by order so + ** we do not have to sort. The OP_OpenEphemeral table will be + ** cancelled later because we still need to use the pKeyInfo + */ + groupBySort = 0; + }else{ + /* Rows are coming out in undetermined order. We have to push + ** each row into a sorting index, terminate the first loop, + ** then loop over the sorting index in order to get the output + ** in sorted order + */ + int regBase; + int regRecord; + int nCol; + int nGroupBy; + + explainTempTable(pParse, + (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? + "DISTINCT" : "GROUP BY"); + + groupBySort = 1; + nGroupBy = pGroupBy->nExpr; + nCol = nGroupBy + 1; + j = nGroupBy+1; + for(i=0; i=j ){ + nCol++; + j++; + } + } + regBase = sqlite3GetTempRange(pParse, nCol); + sqlite3ExprCacheClear(pParse); + sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0); + sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); + j = nGroupBy+1; + for(i=0; iiSorterColumn>=j ){ + int r1 = j + regBase; + int r2; + + r2 = sqlite3ExprCodeGetColumn(pParse, + pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0); + if( r1!=r2 ){ + sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1); + } + j++; + } + } + regRecord = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); + sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); + sqlite3ReleaseTempReg(pParse, regRecord); + sqlite3ReleaseTempRange(pParse, regBase, nCol); + sqlite3WhereEnd(pWInfo); + sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; + sortOut = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); + sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); + VdbeComment((v, "GROUP BY sort")); + sAggInfo.useSortingIdx = 1; + sqlite3ExprCacheClear(pParse); + } + + /* Evaluate the current GROUP BY terms and store in b0, b1, b2... + ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) + ** Then compare the current GROUP BY terms against the GROUP BY terms + ** from the previous row currently stored in a0, a1, a2... + */ + addrTopOfLoop = sqlite3VdbeCurrentAddr(v); + sqlite3ExprCacheClear(pParse); + if( groupBySort ){ + sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut); + } + for(j=0; jnExpr; j++){ + if( groupBySort ){ + sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); + if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE); + }else{ + sAggInfo.directMode = 1; + sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); + } + } + sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, + (char*)pKeyInfo, P4_KEYINFO); + j1 = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); + + /* Generate code that runs whenever the GROUP BY changes. + ** Changes in the GROUP BY are detected by the previous code + ** block. If there were no changes, this block is skipped. + ** + ** This code copies current group by terms in b0,b1,b2,... + ** over to a0,a1,a2. It then calls the output subroutine + ** and resets the aggregate accumulator registers in preparation + ** for the next GROUP BY batch. + */ + sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); + sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); + VdbeComment((v, "output one row")); + sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); + VdbeComment((v, "check abort flag")); + sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); + VdbeComment((v, "reset accumulator")); + + /* Update the aggregate accumulators based on the content of + ** the current row + */ + sqlite3VdbeJumpHere(v, j1); + updateAccumulator(pParse, &sAggInfo); + sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); + VdbeComment((v, "indicate data in accumulator")); + + /* End of the loop + */ + if( groupBySort ){ + sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); + }else{ + sqlite3WhereEnd(pWInfo); + sqlite3VdbeChangeToNoop(v, addrSortingIdx); + } + + /* Output the final row of result + */ + sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); + VdbeComment((v, "output final row")); + + /* Jump over the subroutines + */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd); + + /* Generate a subroutine that outputs a single row of the result + ** set. This subroutine first looks at the iUseFlag. If iUseFlag + ** is less than or equal to zero, the subroutine is a no-op. If + ** the processing calls for the query to abort, this subroutine + ** increments the iAbortFlag memory location before returning in + ** order to signal the caller to abort. + */ + addrSetAbort = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); + VdbeComment((v, "set abort flag")); + sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + sqlite3VdbeResolveLabel(v, addrOutputRow); + addrOutputRow = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); + VdbeComment((v, "Groupby result generator entry point")); + sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + finalizeAggFunctions(pParse, &sAggInfo); + sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); + selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, + &sDistinct, pDest, + addrOutputRow+1, addrSetAbort); + sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + VdbeComment((v, "end groupby result generator")); + + /* Generate a subroutine that will reset the group-by accumulator + */ + sqlite3VdbeResolveLabel(v, addrReset); + resetAccumulator(pParse, &sAggInfo); + sqlite3VdbeAddOp1(v, OP_Return, regReset); + + } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ + else { + ExprList *pDel = 0; +#ifndef SQLITE_OMIT_BTREECOUNT + Table *pTab; + if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ + /* If isSimpleCount() returns a pointer to a Table structure, then + ** the SQL statement is of the form: + ** + ** SELECT count(*) FROM + ** + ** where the Table structure returned represents table . + ** + ** This statement is so common that it is optimized specially. The + ** OP_Count instruction is executed either on the intkey table that + ** contains the data for table or on one of its indexes. It + ** is better to execute the op on an index, as indexes are almost + ** always spread across less pages than their corresponding tables. + */ + const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ + Index *pIdx; /* Iterator variable */ + KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ + Index *pBest = 0; /* Best index found so far */ + int iRoot = pTab->tnum; /* Root page of scanned b-tree */ + + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + + /* Search for the index that has the lowest scan cost. + ** + ** (2011-04-15) Do not do a full scan of an unordered index. + ** + ** (2013-10-03) Do not count the entires in a partial index. + ** + ** In practice the KeyInfo structure will not be used. It is only + ** passed to keep OP_OpenRead happy. + */ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->bUnordered==0 + && pIdx->szIdxRowszTabRow + && pIdx->pPartIdxWhere==0 + && (!pBest || pIdx->szIdxRowszIdxRow) + ){ + pBest = pIdx; + } + } + if( pBest ){ + iRoot = pBest->tnum; + pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest); + } + + /* Open a read-only cursor, execute the OP_Count, close the cursor. */ + sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb); + if( pKeyInfo ){ + sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF); + } + sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); + sqlite3VdbeAddOp1(v, OP_Close, iCsr); + explainSimpleCount(pParse, pTab, pBest); + }else +#endif /* SQLITE_OMIT_BTREECOUNT */ + { + /* Check if the query is of one of the following forms: + ** + ** SELECT min(x) FROM ... + ** SELECT max(x) FROM ... + ** + ** If it is, then ask the code in where.c to attempt to sort results + ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. + ** If where.c is able to produce results sorted in this order, then + ** add vdbe code to break out of the processing loop after the + ** first iteration (since the first iteration of the loop is + ** guaranteed to operate on the row with the minimum or maximum + ** value of x, the only row required). + ** + ** A special flag must be passed to sqlite3WhereBegin() to slightly + ** modify behavior as follows: + ** + ** + If the query is a "SELECT min(x)", then the loop coded by + ** where.c should not iterate over any values with a NULL value + ** for x. + ** + ** + The optimizer code in where.c (the thing that decides which + ** index or indices to use) should place a different priority on + ** satisfying the 'ORDER BY' clause than it does in other cases. + ** Refer to code and comments in where.c for details. + */ + ExprList *pMinMax = 0; + u8 flag = WHERE_ORDERBY_NORMAL; + + assert( p->pGroupBy==0 ); + assert( flag==0 ); + if( p->pHaving==0 ){ + flag = minMaxQuery(&sAggInfo, &pMinMax); + } + assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) ); + + if( flag ){ + pMinMax = sqlite3ExprListDup(db, pMinMax, 0); + pDel = pMinMax; + if( pMinMax && !db->mallocFailed ){ + pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; + pMinMax->a[0].pExpr->op = TK_COLUMN; + } + } + + /* This case runs if the aggregate has no GROUP BY clause. The + ** processing is much simpler since there is only a single row + ** of output. + */ + resetAccumulator(pParse, &sAggInfo); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0); + if( pWInfo==0 ){ + sqlite3ExprListDelete(db, pDel); + goto select_end; + } + updateAccumulator(pParse, &sAggInfo); + assert( pMinMax==0 || pMinMax->nExpr==1 ); + if( sqlite3WhereIsOrdered(pWInfo) ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo)); + VdbeComment((v, "%s() by index", + (flag==WHERE_ORDERBY_MIN?"min":"max"))); + } + sqlite3WhereEnd(pWInfo); + finalizeAggFunctions(pParse, &sAggInfo); + } + + pOrderBy = 0; + sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); + selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0, + pDest, addrEnd, addrEnd); + sqlite3ExprListDelete(db, pDel); + } + sqlite3VdbeResolveLabel(v, addrEnd); + + } /* endif aggregate query */ + + if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ + explainTempTable(pParse, "DISTINCT"); + } + + /* If there is an ORDER BY clause, then we need to sort the results + ** and send them to the callback one by one. + */ + if( pOrderBy ){ + explainTempTable(pParse, "ORDER BY"); + generateSortTail(pParse, p, v, pEList->nExpr, pDest); + } + + /* Jump here to skip this query + */ + sqlite3VdbeResolveLabel(v, iEnd); + + /* The SELECT was successfully coded. Set the return code to 0 + ** to indicate no errors. + */ + rc = 0; + + /* Control jumps to here if an error is encountered above, or upon + ** successful coding of the SELECT. + */ +select_end: + explainSetInteger(pParse->iSelectId, iRestoreSelectId); + + /* Identify column names if results of the SELECT are to be output. + */ + if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ + generateColumnNames(pParse, pTabList, pEList); + } + + sqlite3DbFree(db, sAggInfo.aCol); + sqlite3DbFree(db, sAggInfo.aFunc); + return rc; +} + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) +/* +** Generate a human-readable description of a the Select object. +*/ +static void explainOneSelect(Vdbe *pVdbe, Select *p){ + sqlite3ExplainPrintf(pVdbe, "SELECT "); + if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ + if( p->selFlags & SF_Distinct ){ + sqlite3ExplainPrintf(pVdbe, "DISTINCT "); + } + if( p->selFlags & SF_Aggregate ){ + sqlite3ExplainPrintf(pVdbe, "agg_flag "); + } + sqlite3ExplainNL(pVdbe); + sqlite3ExplainPrintf(pVdbe, " "); + } + sqlite3ExplainExprList(pVdbe, p->pEList); + sqlite3ExplainNL(pVdbe); + if( p->pSrc && p->pSrc->nSrc ){ + int i; + sqlite3ExplainPrintf(pVdbe, "FROM "); + sqlite3ExplainPush(pVdbe); + for(i=0; ipSrc->nSrc; i++){ + struct SrcList_item *pItem = &p->pSrc->a[i]; + sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor); + if( pItem->pSelect ){ + sqlite3ExplainSelect(pVdbe, pItem->pSelect); + if( pItem->pTab ){ + sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName); + } + }else if( pItem->zName ){ + sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName); + } + if( pItem->zAlias ){ + sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias); + } + if( pItem->jointype & JT_LEFT ){ + sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN"); + } + sqlite3ExplainNL(pVdbe); + } + sqlite3ExplainPop(pVdbe); + } + if( p->pWhere ){ + sqlite3ExplainPrintf(pVdbe, "WHERE "); + sqlite3ExplainExpr(pVdbe, p->pWhere); + sqlite3ExplainNL(pVdbe); + } + if( p->pGroupBy ){ + sqlite3ExplainPrintf(pVdbe, "GROUPBY "); + sqlite3ExplainExprList(pVdbe, p->pGroupBy); + sqlite3ExplainNL(pVdbe); + } + if( p->pHaving ){ + sqlite3ExplainPrintf(pVdbe, "HAVING "); + sqlite3ExplainExpr(pVdbe, p->pHaving); + sqlite3ExplainNL(pVdbe); + } + if( p->pOrderBy ){ + sqlite3ExplainPrintf(pVdbe, "ORDERBY "); + sqlite3ExplainExprList(pVdbe, p->pOrderBy); + sqlite3ExplainNL(pVdbe); + } + if( p->pLimit ){ + sqlite3ExplainPrintf(pVdbe, "LIMIT "); + sqlite3ExplainExpr(pVdbe, p->pLimit); + sqlite3ExplainNL(pVdbe); + } + if( p->pOffset ){ + sqlite3ExplainPrintf(pVdbe, "OFFSET "); + sqlite3ExplainExpr(pVdbe, p->pOffset); + sqlite3ExplainNL(pVdbe); + } +} +void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){ + if( p==0 ){ + sqlite3ExplainPrintf(pVdbe, "(null-select)"); + return; + } + while( p->pPrior ){ + p->pPrior->pNext = p; + p = p->pPrior; + } + sqlite3ExplainPush(pVdbe); + while( p ){ + explainOneSelect(pVdbe, p); + p = p->pNext; + if( p==0 ) break; + sqlite3ExplainNL(pVdbe); + sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op)); + } + sqlite3ExplainPrintf(pVdbe, "END"); + sqlite3ExplainPop(pVdbe); +} + +/* End of the structure debug printing code +*****************************************************************************/ +#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */ diff --git a/components/external/SQLite-3.8.1/src/shell.c b/components/external/SQLite-3.8.1/src/shell.c new file mode 100644 index 0000000000000000000000000000000000000000..41ea56492e71884843a56a4c4c65ab18864e1f26 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/shell.c @@ -0,0 +1,3400 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code to implement the "sqlite" command line +** utility for accessing SQLite databases. +*/ +#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) +/* This needs to come before any includes for MSVC compiler */ +#define _CRT_SECURE_NO_WARNINGS +#endif + +/* +** Enable large-file support for fopen() and friends on unix. +*/ +#ifndef SQLITE_DISABLE_LFS +# define _LARGE_FILE 1 +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +# define _LARGEFILE_SOURCE 1 +#endif + +#include +#include +#include +#include +#include "sqlite3.h" +#include +#include + +#if !defined(_WIN32) && !defined(WIN32) +# include +# if !defined(__RTP__) && !defined(_WRS_KERNEL) +# include +# endif +# include +# include +#endif + +#ifdef HAVE_EDITLINE +# include +#endif +#if defined(HAVE_READLINE) && HAVE_READLINE==1 +# include +# include +#endif +#if !defined(HAVE_EDITLINE) && (!defined(HAVE_READLINE) || HAVE_READLINE!=1) +# define add_history(X) +# define read_history(X) +# define write_history(X) +# define stifle_history(X) +#endif + +#if defined(_WIN32) || defined(WIN32) +# include +#define isatty(h) _isatty(h) +#define access(f,m) _access((f),(m)) +#undef popen +#define popen _popen +#undef pclose +#define pclose _pclose +#else +/* Make sure isatty() has a prototype. +*/ +extern int isatty(int); + +/* popen and pclose are not C89 functions and so are sometimes omitted from +** the header */ +extern FILE *popen(const char*,const char*); +extern int pclose(FILE*); +#endif + +#if defined(_WIN32_WCE) +/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() + * thus we always assume that we have a console. That can be + * overridden with the -batch command line option. + */ +#define isatty(x) 1 +#endif + +/* True if the timer is enabled */ +static int enableTimer = 0; + +/* ctype macros that work with signed characters */ +#define IsSpace(X) isspace((unsigned char)X) +#define IsDigit(X) isdigit((unsigned char)X) +#define ToLower(X) (char)tolower((unsigned char)X) + +#if !defined(_WIN32) && !defined(WIN32) && !defined(_WRS_KERNEL) \ + && !defined(__minux) +#include +#include + +/* Saved resource information for the beginning of an operation */ +static struct rusage sBegin; + +/* +** Begin timing an operation +*/ +static void beginTimer(void){ + if( enableTimer ){ + getrusage(RUSAGE_SELF, &sBegin); + } +} + +/* Return the difference of two time_structs in seconds */ +static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ + return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + + (double)(pEnd->tv_sec - pStart->tv_sec); +} + +/* +** Print the timing results. +*/ +static void endTimer(void){ + if( enableTimer ){ + struct rusage sEnd; + getrusage(RUSAGE_SELF, &sEnd); + printf("CPU Time: user %f sys %f\n", + timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), + timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); + } +} + +#define BEGIN_TIMER beginTimer() +#define END_TIMER endTimer() +#define HAS_TIMER 1 + +#elif (defined(_WIN32) || defined(WIN32)) + +#include + +/* Saved resource information for the beginning of an operation */ +static HANDLE hProcess; +static FILETIME ftKernelBegin; +static FILETIME ftUserBegin; +typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME); +static GETPROCTIMES getProcessTimesAddr = NULL; + +/* +** Check to see if we have timer support. Return 1 if necessary +** support found (or found previously). +*/ +static int hasTimer(void){ + if( getProcessTimesAddr ){ + return 1; + } else { + /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions. + ** See if the version we are running on has it, and if it does, save off + ** a pointer to it and the current process handle. + */ + hProcess = GetCurrentProcess(); + if( hProcess ){ + HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); + if( NULL != hinstLib ){ + getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); + if( NULL != getProcessTimesAddr ){ + return 1; + } + FreeLibrary(hinstLib); + } + } + } + return 0; +} + +/* +** Begin timing an operation +*/ +static void beginTimer(void){ + if( enableTimer && getProcessTimesAddr ){ + FILETIME ftCreation, ftExit; + getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin); + } +} + +/* Return the difference of two FILETIME structs in seconds */ +static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ + sqlite_int64 i64Start = *((sqlite_int64 *) pStart); + sqlite_int64 i64End = *((sqlite_int64 *) pEnd); + return (double) ((i64End - i64Start) / 10000000.0); +} + +/* +** Print the timing results. +*/ +static void endTimer(void){ + if( enableTimer && getProcessTimesAddr){ + FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; + getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd); + printf("CPU Time: user %f sys %f\n", + timeDiff(&ftUserBegin, &ftUserEnd), + timeDiff(&ftKernelBegin, &ftKernelEnd)); + } +} + +#define BEGIN_TIMER beginTimer() +#define END_TIMER endTimer() +#define HAS_TIMER hasTimer() + +#else +#define BEGIN_TIMER +#define END_TIMER +#define HAS_TIMER 0 +#endif + +/* +** Used to prevent warnings about unused parameters +*/ +#define UNUSED_PARAMETER(x) (void)(x) + +/* +** If the following flag is set, then command execution stops +** at an error if we are not interactive. +*/ +static int bail_on_error = 0; + +/* +** Threat stdin as an interactive input if the following variable +** is true. Otherwise, assume stdin is connected to a file or pipe. +*/ +static int stdin_is_interactive = 1; + +/* +** The following is the open SQLite database. We make a pointer +** to this database a static variable so that it can be accessed +** by the SIGINT handler to interrupt database processing. +*/ +static sqlite3 *db = 0; + +/* +** True if an interrupt (Control-C) has been received. +*/ +static volatile int seenInterrupt = 0; + +/* +** This is the name of our program. It is set in main(), used +** in a number of other places, mostly for error messages. +*/ +static char *Argv0; + +/* +** Prompt strings. Initialized in main. Settable with +** .prompt main continue +*/ +static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ +static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ + +/* +** Write I/O traces to the following stream. +*/ +#ifdef SQLITE_ENABLE_IOTRACE +static FILE *iotrace = 0; +#endif + +/* +** This routine works like printf in that its first argument is a +** format string and subsequent arguments are values to be substituted +** in place of % fields. The result of formatting this string +** is written to iotrace. +*/ +#ifdef SQLITE_ENABLE_IOTRACE +static void iotracePrintf(const char *zFormat, ...){ + va_list ap; + char *z; + if( iotrace==0 ) return; + va_start(ap, zFormat); + z = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + fprintf(iotrace, "%s", z); + sqlite3_free(z); +} +#endif + + +/* +** Determines if a string is a number of not. +*/ +static int isNumber(const char *z, int *realnum){ + if( *z=='-' || *z=='+' ) z++; + if( !IsDigit(*z) ){ + return 0; + } + z++; + if( realnum ) *realnum = 0; + while( IsDigit(*z) ){ z++; } + if( *z=='.' ){ + z++; + if( !IsDigit(*z) ) return 0; + while( IsDigit(*z) ){ z++; } + if( realnum ) *realnum = 1; + } + if( *z=='e' || *z=='E' ){ + z++; + if( *z=='+' || *z=='-' ) z++; + if( !IsDigit(*z) ) return 0; + while( IsDigit(*z) ){ z++; } + if( realnum ) *realnum = 1; + } + return *z==0; +} + +/* +** A global char* and an SQL function to access its current value +** from within an SQL statement. This program used to use the +** sqlite_exec_printf() API to substitue a string into an SQL statement. +** The correct way to do this with sqlite3 is to use the bind API, but +** since the shell is built around the callback paradigm it would be a lot +** of work. Instead just use this hack, which is quite harmless. +*/ +static const char *zShellStatic = 0; +static void shellstaticFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + assert( 0==argc ); + assert( zShellStatic ); + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC); +} + + +/* +** This routine reads a line of text from FILE in, stores +** the text in memory obtained from malloc() and returns a pointer +** to the text. NULL is returned at end of file, or if malloc() +** fails. +** +** If zLine is not NULL then it is a malloced buffer returned from +** a previous call to this routine that may be reused. +*/ +static char *local_getline(char *zLine, FILE *in){ + int nLine = zLine==0 ? 0 : 100; + int n = 0; + + while( 1 ){ + if( n+100>nLine ){ + nLine = nLine*2 + 100; + zLine = realloc(zLine, nLine); + if( zLine==0 ) return 0; + } + if( fgets(&zLine[n], nLine - n, in)==0 ){ + if( n==0 ){ + free(zLine); + return 0; + } + zLine[n] = 0; + break; + } + while( zLine[n] ) n++; + if( n>0 && zLine[n-1]=='\n' ){ + n--; + if( n>0 && zLine[n-1]=='\r' ) n--; + zLine[n] = 0; + break; + } + } + return zLine; +} + +/* +** Retrieve a single line of input text. +** +** If in==0 then read from standard input and prompt before each line. +** If isContinuation is true, then a continuation prompt is appropriate. +** If isContinuation is zero, then the main prompt should be used. +** +** If zPrior is not NULL then it is a buffer from a prior call to this +** routine that can be reused. +** +** The result is stored in space obtained from malloc() and must either +** be freed by the caller or else passed back into this routine via the +** zPrior argument for reuse. +*/ +static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ + char *zPrompt; + char *zResult; + if( in!=0 ){ + zResult = local_getline(zPrior, in); + }else{ + zPrompt = isContinuation ? continuePrompt : mainPrompt; +#if defined(HAVE_READLINE) && HAVE_READLINE==1 + free(zPrior); + zResult = readline(zPrompt); + if( zResult && *zResult ) add_history(zResult); +#else + printf("%s", zPrompt); + fflush(stdout); + zResult = local_getline(zPrior, stdin); +#endif + } + return zResult; +} + +struct previous_mode_data { + int valid; /* Is there legit data in here? */ + int mode; + int showHeader; + int colWidth[100]; +}; + +/* +** An pointer to an instance of this structure is passed from +** the main program to the callback. This is used to communicate +** state and mode information. +*/ +struct callback_data { + sqlite3 *db; /* The database */ + int echoOn; /* True to echo input commands */ + int statsOn; /* True to display memory stats before each finalize */ + int cnt; /* Number of records displayed so far */ + FILE *out; /* Write results here */ + FILE *traceOut; /* Output for sqlite3_trace() */ + int nErr; /* Number of errors seen */ + int mode; /* An output mode setting */ + int writableSchema; /* True if PRAGMA writable_schema=ON */ + int showHeader; /* True to show column names in List or Column mode */ + char *zDestTable; /* Name of destination table when MODE_Insert */ + char separator[20]; /* Separator character for MODE_List */ + int colWidth[100]; /* Requested width of each column when in column mode*/ + int actualWidth[100]; /* Actual width of each column */ + char nullvalue[20]; /* The text to print when a NULL comes back from + ** the database */ + struct previous_mode_data explainPrev; + /* Holds the mode information just before + ** .explain ON */ + char outfile[FILENAME_MAX]; /* Filename for *out */ + const char *zDbFilename; /* name of the database file */ + const char *zVfs; /* Name of VFS to use */ + sqlite3_stmt *pStmt; /* Current statement if any. */ + FILE *pLog; /* Write log output here */ +}; + +/* +** These are the allowed modes. +*/ +#define MODE_Line 0 /* One column per line. Blank line between records */ +#define MODE_Column 1 /* One record per line in neat columns */ +#define MODE_List 2 /* One record per line with a separator */ +#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ +#define MODE_Html 4 /* Generate an XHTML table */ +#define MODE_Insert 5 /* Generate SQL "insert" statements */ +#define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */ +#define MODE_Csv 7 /* Quote strings, numbers are plain */ +#define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */ + +static const char *modeDescr[] = { + "line", + "column", + "list", + "semi", + "html", + "insert", + "tcl", + "csv", + "explain", +}; + +/* +** Number of elements in an array +*/ +#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) + +/* +** Compute a string length that is limited to what can be stored in +** lower 30 bits of a 32-bit signed integer. +*/ +static int strlen30(const char *z){ + const char *z2 = z; + while( *z2 ){ z2++; } + return 0x3fffffff & (int)(z2 - z); +} + +/* +** A callback for the sqlite3_log() interface. +*/ +static void shellLog(void *pArg, int iErrCode, const char *zMsg){ + struct callback_data *p = (struct callback_data*)pArg; + if( p->pLog==0 ) return; + fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg); + fflush(p->pLog); +} + +/* +** Output the given string as a hex-encoded blob (eg. X'1234' ) +*/ +static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ + int i; + char *zBlob = (char *)pBlob; + fprintf(out,"X'"); + for(i=0; i0 ){ + fprintf(out,"%.*s",i,z); + } + if( z[i]=='<' ){ + fprintf(out,"<"); + }else if( z[i]=='&' ){ + fprintf(out,"&"); + }else if( z[i]=='>' ){ + fprintf(out,">"); + }else if( z[i]=='\"' ){ + fprintf(out,"""); + }else if( z[i]=='\'' ){ + fprintf(out,"'"); + }else{ + break; + } + z += i + 1; + } +} + +/* +** If a field contains any character identified by a 1 in the following +** array, then the string must be quoted for CSV. +*/ +static const char needCsvQuote[] = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, +}; + +/* +** Output a single term of CSV. Actually, p->separator is used for +** the separator, which may or may not be a comma. p->nullvalue is +** the null value. Strings are quoted if necessary. +*/ +static void output_csv(struct callback_data *p, const char *z, int bSep){ + FILE *out = p->out; + if( z==0 ){ + fprintf(out,"%s",p->nullvalue); + }else{ + int i; + int nSep = strlen30(p->separator); + for(i=0; z[i]; i++){ + if( needCsvQuote[((unsigned char*)z)[i]] + || (z[i]==p->separator[0] && + (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){ + i = 0; + break; + } + } + if( i==0 ){ + putc('"', out); + for(i=0; z[i]; i++){ + if( z[i]=='"' ) putc('"', out); + putc(z[i], out); + } + putc('"', out); + }else{ + fprintf(out, "%s", z); + } + } + if( bSep ){ + fprintf(p->out, "%s", p->separator); + } +} + +#ifdef SIGINT +/* +** This routine runs when the user presses Ctrl-C +*/ +static void interrupt_handler(int NotUsed){ + UNUSED_PARAMETER(NotUsed); + seenInterrupt = 1; + if( db ) sqlite3_interrupt(db); +} +#endif + +/* +** This is the callback routine that the shell +** invokes for each row of a query result. +*/ +static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){ + int i; + struct callback_data *p = (struct callback_data*)pArg; + + switch( p->mode ){ + case MODE_Line: { + int w = 5; + if( azArg==0 ) break; + for(i=0; iw ) w = len; + } + if( p->cnt++>0 ) fprintf(p->out,"\n"); + for(i=0; iout,"%*s = %s\n", w, azCol[i], + azArg[i] ? azArg[i] : p->nullvalue); + } + break; + } + case MODE_Explain: + case MODE_Column: { + if( p->cnt++==0 ){ + for(i=0; icolWidth) ){ + w = p->colWidth[i]; + }else{ + w = 0; + } + if( w==0 ){ + w = strlen30(azCol[i] ? azCol[i] : ""); + if( w<10 ) w = 10; + n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue); + if( wactualWidth) ){ + p->actualWidth[i] = w; + } + if( p->showHeader ){ + if( w<0 ){ + fprintf(p->out,"%*.*s%s",-w,-w,azCol[i], i==nArg-1 ? "\n": " "); + }else{ + fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " "); + } + } + } + if( p->showHeader ){ + for(i=0; iactualWidth) ){ + w = p->actualWidth[i]; + if( w<0 ) w = -w; + }else{ + w = 10; + } + fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------" + "----------------------------------------------------------", + i==nArg-1 ? "\n": " "); + } + } + } + if( azArg==0 ) break; + for(i=0; iactualWidth) ){ + w = p->actualWidth[i]; + }else{ + w = 10; + } + if( p->mode==MODE_Explain && azArg[i] && + strlen30(azArg[i])>w ){ + w = strlen30(azArg[i]); + } + if( w<0 ){ + fprintf(p->out,"%*.*s%s",-w,-w, + azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " "); + }else{ + fprintf(p->out,"%-*.*s%s",w,w, + azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " "); + } + } + break; + } + case MODE_Semi: + case MODE_List: { + if( p->cnt++==0 && p->showHeader ){ + for(i=0; iout,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator); + } + } + if( azArg==0 ) break; + for(i=0; inullvalue; + fprintf(p->out, "%s", z); + if( iout, "%s", p->separator); + }else if( p->mode==MODE_Semi ){ + fprintf(p->out, ";\n"); + }else{ + fprintf(p->out, "\n"); + } + } + break; + } + case MODE_Html: { + if( p->cnt++==0 && p->showHeader ){ + fprintf(p->out,""); + for(i=0; iout,"\n"); + } + fprintf(p->out,"\n"); + } + if( azArg==0 ) break; + fprintf(p->out,""); + for(i=0; iout,"\n"); + } + fprintf(p->out,"\n"); + break; + } + case MODE_Tcl: { + if( p->cnt++==0 && p->showHeader ){ + for(i=0; iout,azCol[i] ? azCol[i] : ""); + if(iout, "%s", p->separator); + } + fprintf(p->out,"\n"); + } + if( azArg==0 ) break; + for(i=0; iout, azArg[i] ? azArg[i] : p->nullvalue); + if(iout, "%s", p->separator); + } + fprintf(p->out,"\n"); + break; + } + case MODE_Csv: { + if( p->cnt++==0 && p->showHeader ){ + for(i=0; iout,"\n"); + } + if( azArg==0 ) break; + for(i=0; iout,"\n"); + break; + } + case MODE_Insert: { + p->cnt++; + if( azArg==0 ) break; + fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable); + for(i=0; i0 ? ",": ""; + if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ + fprintf(p->out,"%sNULL",zSep); + }else if( aiType && aiType[i]==SQLITE_TEXT ){ + if( zSep[0] ) fprintf(p->out,"%s",zSep); + output_quoted_string(p->out, azArg[i]); + }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){ + fprintf(p->out,"%s%s",zSep, azArg[i]); + }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ + const void *pBlob = sqlite3_column_blob(p->pStmt, i); + int nBlob = sqlite3_column_bytes(p->pStmt, i); + if( zSep[0] ) fprintf(p->out,"%s",zSep); + output_hex_blob(p->out, pBlob, nBlob); + }else if( isNumber(azArg[i], 0) ){ + fprintf(p->out,"%s%s",zSep, azArg[i]); + }else{ + if( zSep[0] ) fprintf(p->out,"%s",zSep); + output_quoted_string(p->out, azArg[i]); + } + } + fprintf(p->out,");\n"); + break; + } + } + return 0; +} + +/* +** This is the callback routine that the SQLite library +** invokes for each row of a query result. +*/ +static int callback(void *pArg, int nArg, char **azArg, char **azCol){ + /* since we don't have type info, call the shell_callback with a NULL value */ + return shell_callback(pArg, nArg, azArg, azCol, NULL); +} + +/* +** Set the destination table field of the callback_data structure to +** the name of the table given. Escape any quote characters in the +** table name. +*/ +static void set_table_name(struct callback_data *p, const char *zName){ + int i, n; + int needQuote; + char *z; + + if( p->zDestTable ){ + free(p->zDestTable); + p->zDestTable = 0; + } + if( zName==0 ) return; + needQuote = !isalpha((unsigned char)*zName) && *zName!='_'; + for(i=n=0; zName[i]; i++, n++){ + if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){ + needQuote = 1; + if( zName[i]=='\'' ) n++; + } + } + if( needQuote ) n += 2; + z = p->zDestTable = malloc( n+1 ); + if( z==0 ){ + fprintf(stderr,"Error: out of memory\n"); + exit(1); + } + n = 0; + if( needQuote ) z[n++] = '\''; + for(i=0; zName[i]; i++){ + z[n++] = zName[i]; + if( zName[i]=='\'' ) z[n++] = '\''; + } + if( needQuote ) z[n++] = '\''; + z[n] = 0; +} + +/* zIn is either a pointer to a NULL-terminated string in memory obtained +** from malloc(), or a NULL pointer. The string pointed to by zAppend is +** added to zIn, and the result returned in memory obtained from malloc(). +** zIn, if it was not NULL, is freed. +** +** If the third argument, quote, is not '\0', then it is used as a +** quote character for zAppend. +*/ +static char *appendText(char *zIn, char const *zAppend, char quote){ + int len; + int i; + int nAppend = strlen30(zAppend); + int nIn = (zIn?strlen30(zIn):0); + + len = nAppend+nIn+1; + if( quote ){ + len += 2; + for(i=0; idb, zSelect, -1, &pSelect, 0); + if( rc!=SQLITE_OK || !pSelect ){ + fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); + if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; + return rc; + } + rc = sqlite3_step(pSelect); + nResult = sqlite3_column_count(pSelect); + while( rc==SQLITE_ROW ){ + if( zFirstRow ){ + fprintf(p->out, "%s", zFirstRow); + zFirstRow = 0; + } + z = (const char*)sqlite3_column_text(pSelect, 0); + fprintf(p->out, "%s", z); + for(i=1; iout, ",%s", sqlite3_column_text(pSelect, i)); + } + if( z==0 ) z = ""; + while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; + if( z[0] ){ + fprintf(p->out, "\n;\n"); + }else{ + fprintf(p->out, ";\n"); + } + rc = sqlite3_step(pSelect); + } + rc = sqlite3_finalize(pSelect); + if( rc!=SQLITE_OK ){ + fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); + if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; + } + return rc; +} + +/* +** Allocate space and save off current error string. +*/ +static char *save_err_msg( + sqlite3 *db /* Database to query */ +){ + int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); + char *zErrMsg = sqlite3_malloc(nErrMsg); + if( zErrMsg ){ + memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); + } + return zErrMsg; +} + +/* +** Display memory stats. +*/ +static int display_stats( + sqlite3 *db, /* Database to query */ + struct callback_data *pArg, /* Pointer to struct callback_data */ + int bReset /* True to reset the stats */ +){ + int iCur; + int iHiwtr; + + if( pArg && pArg->out ){ + + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr); +/* +** Not currently used by the CLI. +** iHiwtr = iCur = -1; +** sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset); +** fprintf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr); +*/ + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); +/* +** Not currently used by the CLI. +** iHiwtr = iCur = -1; +** sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset); +** fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr); +*/ + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr); +#ifdef YYTRACKMAXSTACKDEPTH + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr); +#endif + } + + if( pArg && pArg->out && db ){ + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); + fprintf(pArg->out, "Page cache hits: %d\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); + fprintf(pArg->out, "Page cache misses: %d\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); + fprintf(pArg->out, "Page cache writes: %d\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur); + } + + if( pArg && pArg->out && db && pArg->pStmt ){ + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset); + fprintf(pArg->out, "Fullscan Steps: %d\n", iCur); + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); + fprintf(pArg->out, "Sort Operations: %d\n", iCur); + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset); + fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur); + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); + fprintf(pArg->out, "Virtual Machine Steps: %d\n", iCur); + } + + return 0; +} + +/* +** Execute a statement or set of statements. Print +** any result rows/columns depending on the current mode +** set via the supplied callback. +** +** This is very similar to SQLite's built-in sqlite3_exec() +** function except it takes a slightly different callback +** and callback data argument. +*/ +static int shell_exec( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */ + /* (not the same as sqlite3_exec) */ + struct callback_data *pArg, /* Pointer to struct callback_data */ + char **pzErrMsg /* Error msg written here */ +){ + sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ + int rc = SQLITE_OK; /* Return Code */ + int rc2; + const char *zLeftover; /* Tail of unprocessed SQL */ + + if( pzErrMsg ){ + *pzErrMsg = NULL; + } + + while( zSql[0] && (SQLITE_OK == rc) ){ + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); + if( SQLITE_OK != rc ){ + if( pzErrMsg ){ + *pzErrMsg = save_err_msg(db); + } + }else{ + if( !pStmt ){ + /* this happens for a comment or white-space */ + zSql = zLeftover; + while( IsSpace(zSql[0]) ) zSql++; + continue; + } + + /* save off the prepared statment handle and reset row count */ + if( pArg ){ + pArg->pStmt = pStmt; + pArg->cnt = 0; + } + + /* echo the sql statement if echo on */ + if( pArg && pArg->echoOn ){ + const char *zStmtSql = sqlite3_sql(pStmt); + fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); + } + + /* Output TESTCTRL_EXPLAIN text of requested */ + if( pArg && pArg->mode==MODE_Explain ){ + const char *zExplain = 0; + sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain); + if( zExplain && zExplain[0] ){ + fprintf(pArg->out, "%s", zExplain); + } + } + + /* perform the first step. this will tell us if we + ** have a result set or not and how wide it is. + */ + rc = sqlite3_step(pStmt); + /* if we have a result set... */ + if( SQLITE_ROW == rc ){ + /* if we have a callback... */ + if( xCallback ){ + /* allocate space for col name ptr, value ptr, and type */ + int nCol = sqlite3_column_count(pStmt); + void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1); + if( !pData ){ + rc = SQLITE_NOMEM; + }else{ + char **azCols = (char **)pData; /* Names of result columns */ + char **azVals = &azCols[nCol]; /* Results */ + int *aiTypes = (int *)&azVals[nCol]; /* Result types */ + int i, x; + assert(sizeof(int) <= sizeof(char *)); + /* save off ptrs to column names */ + for(i=0; imode==MODE_Insert ){ + azVals[i] = ""; + }else{ + azVals[i] = (char*)sqlite3_column_text(pStmt, i); + } + if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ + rc = SQLITE_NOMEM; + break; /* from for */ + } + } /* end for */ + + /* if data and types extracted successfully... */ + if( SQLITE_ROW == rc ){ + /* call the supplied callback with the result row data */ + if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){ + rc = SQLITE_ABORT; + }else{ + rc = sqlite3_step(pStmt); + } + } + } while( SQLITE_ROW == rc ); + sqlite3_free(pData); + } + }else{ + do{ + rc = sqlite3_step(pStmt); + } while( rc == SQLITE_ROW ); + } + } + + /* print usage stats if stats on */ + if( pArg && pArg->statsOn ){ + display_stats(db, pArg, 0); + } + + /* Finalize the statement just executed. If this fails, save a + ** copy of the error message. Otherwise, set zSql to point to the + ** next statement to execute. */ + rc2 = sqlite3_finalize(pStmt); + if( rc!=SQLITE_NOMEM ) rc = rc2; + if( rc==SQLITE_OK ){ + zSql = zLeftover; + while( IsSpace(zSql[0]) ) zSql++; + }else if( pzErrMsg ){ + *pzErrMsg = save_err_msg(db); + } + + /* clear saved stmt handle */ + if( pArg ){ + pArg->pStmt = NULL; + } + } + } /* end while */ + + return rc; +} + + +/* +** This is a different callback routine used for dumping the database. +** Each row received by this callback consists of a table name, +** the table type ("index" or "table") and SQL to create the table. +** This routine should print text sufficient to recreate the table. +*/ +static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ + int rc; + const char *zTable; + const char *zType; + const char *zSql; + const char *zPrepStmt = 0; + struct callback_data *p = (struct callback_data *)pArg; + + UNUSED_PARAMETER(azCol); + if( nArg!=3 ) return 1; + zTable = azArg[0]; + zType = azArg[1]; + zSql = azArg[2]; + + if( strcmp(zTable, "sqlite_sequence")==0 ){ + zPrepStmt = "DELETE FROM sqlite_sequence;\n"; + }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ + fprintf(p->out, "ANALYZE sqlite_master;\n"); + }else if( strncmp(zTable, "sqlite_", 7)==0 ){ + return 0; + }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ + char *zIns; + if( !p->writableSchema ){ + fprintf(p->out, "PRAGMA writable_schema=ON;\n"); + p->writableSchema = 1; + } + zIns = sqlite3_mprintf( + "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" + "VALUES('table','%q','%q',0,'%q');", + zTable, zTable, zSql); + fprintf(p->out, "%s\n", zIns); + sqlite3_free(zIns); + return 0; + }else{ + fprintf(p->out, "%s;\n", zSql); + } + + if( strcmp(zType, "table")==0 ){ + sqlite3_stmt *pTableInfo = 0; + char *zSelect = 0; + char *zTableInfo = 0; + char *zTmp = 0; + int nRow = 0; + + zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0); + zTableInfo = appendText(zTableInfo, zTable, '"'); + zTableInfo = appendText(zTableInfo, ");", 0); + + rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0); + free(zTableInfo); + if( rc!=SQLITE_OK || !pTableInfo ){ + return 1; + } + + zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0); + /* Always quote the table name, even if it appears to be pure ascii, + ** in case it is a keyword. Ex: INSERT INTO "table" ... */ + zTmp = appendText(zTmp, zTable, '"'); + if( zTmp ){ + zSelect = appendText(zSelect, zTmp, '\''); + free(zTmp); + } + zSelect = appendText(zSelect, " || ' VALUES(' || ", 0); + rc = sqlite3_step(pTableInfo); + while( rc==SQLITE_ROW ){ + const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1); + zSelect = appendText(zSelect, "quote(", 0); + zSelect = appendText(zSelect, zText, '"'); + rc = sqlite3_step(pTableInfo); + if( rc==SQLITE_ROW ){ + zSelect = appendText(zSelect, "), ", 0); + }else{ + zSelect = appendText(zSelect, ") ", 0); + } + nRow++; + } + rc = sqlite3_finalize(pTableInfo); + if( rc!=SQLITE_OK || nRow==0 ){ + free(zSelect); + return 1; + } + zSelect = appendText(zSelect, "|| ')' FROM ", 0); + zSelect = appendText(zSelect, zTable, '"'); + + rc = run_table_dump_query(p, zSelect, zPrepStmt); + if( rc==SQLITE_CORRUPT ){ + zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0); + run_table_dump_query(p, zSelect, 0); + } + free(zSelect); + } + return 0; +} + +/* +** Run zQuery. Use dump_callback() as the callback routine so that +** the contents of the query are output as SQL statements. +** +** If we get a SQLITE_CORRUPT error, rerun the query after appending +** "ORDER BY rowid DESC" to the end. +*/ +static int run_schema_dump_query( + struct callback_data *p, + const char *zQuery +){ + int rc; + char *zErr = 0; + rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); + if( rc==SQLITE_CORRUPT ){ + char *zQ2; + int len = strlen30(zQuery); + fprintf(p->out, "/****** CORRUPTION ERROR *******/\n"); + if( zErr ){ + fprintf(p->out, "/****** %s ******/\n", zErr); + sqlite3_free(zErr); + zErr = 0; + } + zQ2 = malloc( len+100 ); + if( zQ2==0 ) return rc; + sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); + rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); + if( rc ){ + fprintf(p->out, "/****** ERROR: %s ******/\n", zErr); + }else{ + rc = SQLITE_CORRUPT; + } + sqlite3_free(zErr); + free(zQ2); + } + return rc; +} + +/* +** Text of a help message +*/ +static char zHelp[] = + ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n" + ".bail ON|OFF Stop after hitting an error. Default OFF\n" + ".databases List names and files of attached databases\n" + ".dump ?TABLE? ... Dump the database in an SQL text format\n" + " If TABLE specified, only dump tables matching\n" + " LIKE pattern TABLE.\n" + ".echo ON|OFF Turn command echo on or off\n" + ".exit Exit this program\n" + ".explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off.\n" + " With no args, it turns EXPLAIN on.\n" + ".header(s) ON|OFF Turn display of headers on or off\n" + ".help Show this message\n" + ".import FILE TABLE Import data from FILE into TABLE\n" + ".indices ?TABLE? Show names of all indices\n" + " If TABLE specified, only show indices for tables\n" + " matching LIKE pattern TABLE.\n" +#ifdef SQLITE_ENABLE_IOTRACE + ".iotrace FILE Enable I/O diagnostic logging to FILE\n" +#endif +#ifndef SQLITE_OMIT_LOAD_EXTENSION + ".load FILE ?ENTRY? Load an extension library\n" +#endif + ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n" + ".mode MODE ?TABLE? Set output mode where MODE is one of:\n" + " csv Comma-separated values\n" + " column Left-aligned columns. (See .width)\n" + " html HTML
    "); + output_html_string(p->out, azCol[i]); + fprintf(p->out,"
    "); + output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue); + fprintf(p->out,"
    code\n" + " insert SQL insert statements for TABLE\n" + " line One value per line\n" + " list Values delimited by .separator string\n" + " tabs Tab-separated values\n" + " tcl TCL list elements\n" + ".nullvalue STRING Use STRING in place of NULL values\n" + ".output FILENAME Send output to FILENAME\n" + ".output stdout Send output to the screen\n" + ".print STRING... Print literal STRING\n" + ".prompt MAIN CONTINUE Replace the standard prompts\n" + ".quit Exit this program\n" + ".read FILENAME Execute SQL in FILENAME\n" + ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n" + ".schema ?TABLE? Show the CREATE statements\n" + " If TABLE specified, only show tables matching\n" + " LIKE pattern TABLE.\n" + ".separator STRING Change separator used by output mode and .import\n" + ".show Show the current values for various settings\n" + ".stats ON|OFF Turn stats on or off\n" + ".tables ?TABLE? List names of tables\n" + " If TABLE specified, only list tables matching\n" + " LIKE pattern TABLE.\n" + ".timeout MS Try opening locked tables for MS milliseconds\n" + ".trace FILE|off Output each SQL statement as it is run\n" + ".vfsname ?AUX? Print the name of the VFS stack\n" + ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n" +; + +static char zTimerHelp[] = + ".timer ON|OFF Turn the CPU timer measurement on or off\n" +; + +/* Forward reference */ +static int process_input(struct callback_data *p, FILE *in); + +/* +** Make sure the database is open. If it is not, then open it. If +** the database fails to open, print an error message and exit. +*/ +static void open_db(struct callback_data *p){ + if( p->db==0 ){ + sqlite3_initialize(); + sqlite3_open(p->zDbFilename, &p->db); + db = p->db; + if( db && sqlite3_errcode(db)==SQLITE_OK ){ + sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0, + shellstaticFunc, 0, 0); + } + if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){ + fprintf(stderr,"Error: unable to open database \"%s\": %s\n", + p->zDbFilename, sqlite3_errmsg(db)); + exit(1); + } +#ifndef SQLITE_OMIT_LOAD_EXTENSION + sqlite3_enable_load_extension(p->db, 1); +#endif + } +} + +/* +** Do C-language style dequoting. +** +** \t -> tab +** \n -> newline +** \r -> carriage return +** \" -> " +** \NNN -> ascii character NNN in octal +** \\ -> backslash +*/ +static void resolve_backslashes(char *z){ + int i, j; + char c; + for(i=j=0; (c = z[i])!=0; i++, j++){ + if( c=='\\' ){ + c = z[++i]; + if( c=='n' ){ + c = '\n'; + }else if( c=='t' ){ + c = '\t'; + }else if( c=='r' ){ + c = '\r'; + }else if( c=='\\' ){ + c = '\\'; + }else if( c>='0' && c<='7' ){ + c -= '0'; + if( z[i+1]>='0' && z[i+1]<='7' ){ + i++; + c = (c<<3) + z[i] - '0'; + if( z[i+1]>='0' && z[i+1]<='7' ){ + i++; + c = (c<<3) + z[i] - '0'; + } + } + } + } + z[j] = c; + } + z[j] = 0; +} + +/* +** Return the value of a hexadecimal digit. Return -1 if the input +** is not a hex digit. +*/ +static int hexDigitValue(char c){ + if( c>='0' && c<='9' ) return c - '0'; + if( c>='a' && c<='f' ) return c - 'a' + 10; + if( c>='A' && c<='F' ) return c - 'A' + 10; + return -1; +} + +/* +** Interpret zArg as an integer value, possibly with suffixes. +*/ +static sqlite3_int64 integerValue(const char *zArg){ + sqlite3_int64 v = 0; + static const struct { char *zSuffix; int iMult; } aMult[] = { + { "KiB", 1024 }, + { "MiB", 1024*1024 }, + { "GiB", 1024*1024*1024 }, + { "KB", 1000 }, + { "MB", 1000000 }, + { "GB", 1000000000 }, + { "K", 1000 }, + { "M", 1000000 }, + { "G", 1000000000 }, + }; + int i; + int isNeg = 0; + if( zArg[0]=='-' ){ + isNeg = 1; + zArg++; + }else if( zArg[0]=='+' ){ + zArg++; + } + if( zArg[0]=='0' && zArg[1]=='x' ){ + int x; + zArg += 2; + while( (x = hexDigitValue(zArg[0]))>=0 ){ + v = (v<<4) + x; + zArg++; + } + }else{ + while( IsDigit(zArg[0]) ){ + v = v*10 + zArg[0] - '0'; + zArg++; + } + } + for(i=0; i=0; i++){} + }else{ + for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} + } + if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); + if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ + return 1; + } + if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ + return 0; + } + fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", + zArg); + return 0; +} + +/* +** Close an output file, assuming it is not stderr or stdout +*/ +static void output_file_close(FILE *f){ + if( f && f!=stdout && f!=stderr ) fclose(f); +} + +/* +** Try to open an output file. The names "stdout" and "stderr" are +** recognized and do the right thing. NULL is returned if the output +** filename is "off". +*/ +static FILE *output_file_open(const char *zFile){ + FILE *f; + if( strcmp(zFile,"stdout")==0 ){ + f = stdout; + }else if( strcmp(zFile, "stderr")==0 ){ + f = stderr; + }else if( strcmp(zFile, "off")==0 ){ + f = 0; + }else{ + f = fopen(zFile, "wb"); + if( f==0 ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); + } + } + return f; +} + +/* +** A routine for handling output from sqlite3_trace(). +*/ +static void sql_trace_callback(void *pArg, const char *z){ + FILE *f = (FILE*)pArg; + if( f ) fprintf(f, "%s\n", z); +} + +/* +** A no-op routine that runs with the ".breakpoint" doc-command. This is +** a useful spot to set a debugger breakpoint. +*/ +static void test_breakpoint(void){ + static int nCall = 0; + nCall++; +} + +/* +** An object used to read a CSV file +*/ +typedef struct CSVReader CSVReader; +struct CSVReader { + const char *zFile; /* Name of the input file */ + FILE *in; /* Read the CSV text from this input stream */ + char *z; /* Accumulated text for a field */ + int n; /* Number of bytes in z */ + int nAlloc; /* Space allocated for z[] */ + int nLine; /* Current line number */ + int cTerm; /* Character that terminated the most recent field */ + int cSeparator; /* The separator character. (Usually ",") */ +}; + +/* Append a single byte to z[] */ +static void csv_append_char(CSVReader *p, int c){ + if( p->n+1>=p->nAlloc ){ + p->nAlloc += p->nAlloc + 100; + p->z = sqlite3_realloc(p->z, p->nAlloc); + if( p->z==0 ){ + fprintf(stderr, "out of memory\n"); + exit(1); + } + } + p->z[p->n++] = (char)c; +} + +/* Read a single field of CSV text. Compatible with rfc4180 and extended +** with the option of having a separator other than ",". +** +** + Input comes from p->in. +** + Store results in p->z of length p->n. Space to hold p->z comes +** from sqlite3_malloc(). +** + Use p->cSep as the separator. The default is ",". +** + Keep track of the line number in p->nLine. +** + Store the character that terminates the field in p->cTerm. Store +** EOF on end-of-file. +** + Report syntax errors on stderr +*/ +static char *csv_read_one_field(CSVReader *p){ + int c, pc; + int cSep = p->cSeparator; + p->n = 0; + c = fgetc(p->in); + if( c==EOF || seenInterrupt ){ + p->cTerm = EOF; + return 0; + } + if( c=='"' ){ + int startLine = p->nLine; + int cQuote = c; + pc = 0; + while( 1 ){ + c = fgetc(p->in); + if( c=='\n' ) p->nLine++; + if( c==cQuote ){ + if( pc==cQuote ){ + pc = 0; + continue; + } + } + if( (c==cSep && pc==cQuote) + || (c=='\n' && pc==cQuote) + || (c=='\n' && pc=='\r' && p->n>=2 && p->z[p->n-2]==cQuote) + || (c==EOF && pc==cQuote) + ){ + do{ p->n--; }while( p->z[p->n]!=cQuote ); + p->cTerm = c; + break; + } + if( pc==cQuote && c!='\r' ){ + fprintf(stderr, "%s:%d: unescaped %c character\n", + p->zFile, p->nLine, cQuote); + } + if( c==EOF ){ + fprintf(stderr, "%s:%d: unterminated %c-quoted field\n", + p->zFile, startLine, cQuote); + p->cTerm = EOF; + break; + } + csv_append_char(p, c); + pc = c; + } + }else{ + while( c!=EOF && c!=cSep && c!='\n' ){ + csv_append_char(p, c); + c = fgetc(p->in); + } + if( c=='\n' ){ + p->nLine++; + if( p->n>1 && p->z[p->n-1]=='\r' ) p->n--; + } + p->cTerm = c; + } + if( p->z ) p->z[p->n] = 0; + return p->z; +} + +/* +** If an input line begins with "." then invoke this routine to +** process that line. +** +** Return 1 on error, 2 to exit, and 0 otherwise. +*/ +static int do_meta_command(char *zLine, struct callback_data *p){ + int i = 1; + int nArg = 0; + int n, c; + int rc = 0; + char *azArg[50]; + + /* Parse the input line into tokens. + */ + while( zLine[i] && nArg=3 && strncmp(azArg[0], "backup", n)==0 ){ + const char *zDestFile = 0; + const char *zDb = 0; + sqlite3 *pDest; + sqlite3_backup *pBackup; + int j; + for(j=1; jdb, zDb); + if( pBackup==0 ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); + sqlite3_close(pDest); + return 1; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = 0; + }else{ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); + rc = 1; + } + sqlite3_close(pDest); + }else + + if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){ + bail_on_error = booleanValue(azArg[1]); + }else + + /* The undocumented ".breakpoint" command causes a call to the no-op + ** routine named test_breakpoint(). + */ + if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ + test_breakpoint(); + }else + + if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){ + struct callback_data data; + char *zErrMsg = 0; + open_db(p); + memcpy(&data, p, sizeof(data)); + data.showHeader = 1; + data.mode = MODE_Column; + data.colWidth[0] = 3; + data.colWidth[1] = 15; + data.colWidth[2] = 58; + data.cnt = 0; + sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg); + if( zErrMsg ){ + fprintf(stderr,"Error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + rc = 1; + } + }else + + if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){ + open_db(p); + /* When playing back a "dump", the content might appear in an order + ** which causes immediate foreign key constraints to be violated. + ** So disable foreign-key constraint enforcement to prevent problems. */ + fprintf(p->out, "PRAGMA foreign_keys=OFF;\n"); + fprintf(p->out, "BEGIN TRANSACTION;\n"); + p->writableSchema = 0; + sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); + p->nErr = 0; + if( nArg==1 ){ + run_schema_dump_query(p, + "SELECT name, type, sql FROM sqlite_master " + "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" + ); + run_schema_dump_query(p, + "SELECT name, type, sql FROM sqlite_master " + "WHERE name=='sqlite_sequence'" + ); + run_table_dump_query(p, + "SELECT sql FROM sqlite_master " + "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 + ); + }else{ + int i; + for(i=1; iwritableSchema ){ + fprintf(p->out, "PRAGMA writable_schema=OFF;\n"); + p->writableSchema = 0; + } + sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); + sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); + fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n"); + }else + + if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){ + p->echoOn = booleanValue(azArg[1]); + }else + + if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ + if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); + rc = 2; + }else + + if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){ + int val = nArg>=2 ? booleanValue(azArg[1]) : 1; + if(val == 1) { + if(!p->explainPrev.valid) { + p->explainPrev.valid = 1; + p->explainPrev.mode = p->mode; + p->explainPrev.showHeader = p->showHeader; + memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth)); + } + /* We could put this code under the !p->explainValid + ** condition so that it does not execute if we are already in + ** explain mode. However, always executing it allows us an easy + ** was to reset to explain mode in case the user previously + ** did an .explain followed by a .width, .mode or .header + ** command. + */ + p->mode = MODE_Explain; + p->showHeader = 1; + memset(p->colWidth,0,ArraySize(p->colWidth)); + p->colWidth[0] = 4; /* addr */ + p->colWidth[1] = 13; /* opcode */ + p->colWidth[2] = 4; /* P1 */ + p->colWidth[3] = 4; /* P2 */ + p->colWidth[4] = 4; /* P3 */ + p->colWidth[5] = 13; /* P4 */ + p->colWidth[6] = 2; /* P5 */ + p->colWidth[7] = 13; /* Comment */ + }else if (p->explainPrev.valid) { + p->explainPrev.valid = 0; + p->mode = p->explainPrev.mode; + p->showHeader = p->explainPrev.showHeader; + memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth)); + } + }else + + if( c=='h' && (strncmp(azArg[0], "header", n)==0 || + strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){ + p->showHeader = booleanValue(azArg[1]); + }else + + if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ + fprintf(stderr,"%s",zHelp); + if( HAS_TIMER ){ + fprintf(stderr,"%s",zTimerHelp); + } + }else + + if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){ + char *zTable = azArg[2]; /* Insert data into this table */ + char *zFile = azArg[1]; /* Name of file to extra content from */ + sqlite3_stmt *pStmt = NULL; /* A statement */ + int nCol; /* Number of columns in the table */ + int nByte; /* Number of bytes in an SQL string */ + int i, j; /* Loop counters */ + int needCommit; /* True to COMMIT or ROLLBACK at end */ + int nSep; /* Number of bytes in p->separator[] */ + char *zSql; /* An SQL statement */ + CSVReader sCsv; /* Reader context */ + int (*xCloser)(FILE*); /* Procedure to close th3 connection */ + + seenInterrupt = 0; + memset(&sCsv, 0, sizeof(sCsv)); + open_db(p); + nSep = strlen30(p->separator); + if( nSep==0 ){ + fprintf(stderr, "Error: non-null separator required for import\n"); + return 1; + } + if( nSep>1 ){ + fprintf(stderr, "Error: multi-character separators not allowed" + " for import\n"); + return 1; + } + sCsv.zFile = zFile; + sCsv.nLine = 1; + if( sCsv.zFile[0]=='|' ){ + sCsv.in = popen(sCsv.zFile+1, "r"); + sCsv.zFile = ""; + xCloser = pclose; + }else{ + sCsv.in = fopen(sCsv.zFile, "rb"); + xCloser = fclose; + } + if( sCsv.in==0 ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); + return 1; + } + sCsv.cSeparator = p->separator[0]; + zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); + if( zSql==0 ){ + fprintf(stderr, "Error: out of memory\n"); + xCloser(sCsv.in); + return 1; + } + nByte = strlen30(zSql); + rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); + if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(db))==0 ){ + char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); + char cSep = '('; + while( csv_read_one_field(&sCsv) ){ + zCreate = sqlite3_mprintf("%z%c\n \"%s\" TEXT", zCreate, cSep, sCsv.z); + cSep = ','; + if( sCsv.cTerm!=sCsv.cSeparator ) break; + } + if( cSep=='(' ){ + sqlite3_free(zCreate); + sqlite3_free(sCsv.z); + xCloser(sCsv.in); + fprintf(stderr,"%s: empty file\n", sCsv.zFile); + return 1; + } + zCreate = sqlite3_mprintf("%z\n)", zCreate); + rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); + sqlite3_free(zCreate); + if( rc ){ + fprintf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, + sqlite3_errmsg(db)); + sqlite3_free(sCsv.z); + xCloser(sCsv.in); + return 1; + } + rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); + } + sqlite3_free(zSql); + if( rc ){ + if (pStmt) sqlite3_finalize(pStmt); + fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db)); + xCloser(sCsv.in); + return 1; + } + nCol = sqlite3_column_count(pStmt); + sqlite3_finalize(pStmt); + pStmt = 0; + if( nCol==0 ) return 0; /* no columns, no error */ + zSql = sqlite3_malloc( nByte*2 + 20 + nCol*2 ); + if( zSql==0 ){ + fprintf(stderr, "Error: out of memory\n"); + xCloser(sCsv.in); + return 1; + } + sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); + j = strlen30(zSql); + for(i=1; idb, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + if( rc ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); + if (pStmt) sqlite3_finalize(pStmt); + xCloser(sCsv.in); + return 1; + } + needCommit = sqlite3_get_autocommit(db); + if( needCommit ) sqlite3_exec(db, "BEGIN", 0, 0, 0); + do{ + int startLine = sCsv.nLine; + for(i=0; i=nCol ){ + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + if( rc!=SQLITE_OK ){ + fprintf(stderr, "%s:%d: INSERT failed: %s\n", sCsv.zFile, startLine, + sqlite3_errmsg(db)); + } + } + }while( sCsv.cTerm!=EOF ); + + xCloser(sCsv.in); + sqlite3_free(sCsv.z); + sqlite3_finalize(pStmt); + if( needCommit ) sqlite3_exec(db, "COMMIT", 0, 0, 0); + }else + + if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){ + struct callback_data data; + char *zErrMsg = 0; + open_db(p); + memcpy(&data, p, sizeof(data)); + data.showHeader = 0; + data.mode = MODE_List; + if( nArg==1 ){ + rc = sqlite3_exec(p->db, + "SELECT name FROM sqlite_master " + "WHERE type='index' AND name NOT LIKE 'sqlite_%' " + "UNION ALL " + "SELECT name FROM sqlite_temp_master " + "WHERE type='index' " + "ORDER BY 1", + callback, &data, &zErrMsg + ); + }else{ + zShellStatic = azArg[1]; + rc = sqlite3_exec(p->db, + "SELECT name FROM sqlite_master " + "WHERE type='index' AND tbl_name LIKE shellstatic() " + "UNION ALL " + "SELECT name FROM sqlite_temp_master " + "WHERE type='index' AND tbl_name LIKE shellstatic() " + "ORDER BY 1", + callback, &data, &zErrMsg + ); + zShellStatic = 0; + } + if( zErrMsg ){ + fprintf(stderr,"Error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + rc = 1; + }else if( rc != SQLITE_OK ){ + fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n"); + rc = 1; + } + }else + +#ifdef SQLITE_ENABLE_IOTRACE + if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ + extern void (*sqlite3IoTrace)(const char*, ...); + if( iotrace && iotrace!=stdout ) fclose(iotrace); + iotrace = 0; + if( nArg<2 ){ + sqlite3IoTrace = 0; + }else if( strcmp(azArg[1], "-")==0 ){ + sqlite3IoTrace = iotracePrintf; + iotrace = stdout; + }else{ + iotrace = fopen(azArg[1], "w"); + if( iotrace==0 ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); + sqlite3IoTrace = 0; + rc = 1; + }else{ + sqlite3IoTrace = iotracePrintf; + } + } + }else +#endif + +#ifndef SQLITE_OMIT_LOAD_EXTENSION + if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){ + const char *zFile, *zProc; + char *zErrMsg = 0; + zFile = azArg[1]; + zProc = nArg>=3 ? azArg[2] : 0; + open_db(p); + rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); + if( rc!=SQLITE_OK ){ + fprintf(stderr, "Error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + rc = 1; + } + }else +#endif + + if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){ + const char *zFile = azArg[1]; + output_file_close(p->pLog); + p->pLog = output_file_open(zFile); + }else + + if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){ + int n2 = strlen30(azArg[1]); + if( (n2==4 && strncmp(azArg[1],"line",n2)==0) + || + (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){ + p->mode = MODE_Line; + }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0) + || + (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){ + p->mode = MODE_Column; + }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){ + p->mode = MODE_List; + }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){ + p->mode = MODE_Html; + }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){ + p->mode = MODE_Tcl; + sqlite3_snprintf(sizeof(p->separator), p->separator, " "); + }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){ + p->mode = MODE_Csv; + sqlite3_snprintf(sizeof(p->separator), p->separator, ","); + }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){ + p->mode = MODE_List; + sqlite3_snprintf(sizeof(p->separator), p->separator, "\t"); + }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){ + p->mode = MODE_Insert; + set_table_name(p, "table"); + }else { + fprintf(stderr,"Error: mode should be one of: " + "column csv html insert line list tabs tcl\n"); + rc = 1; + } + }else + + if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){ + int n2 = strlen30(azArg[1]); + if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){ + p->mode = MODE_Insert; + set_table_name(p, azArg[2]); + }else { + fprintf(stderr, "Error: invalid arguments: " + " \"%s\". Enter \".help\" for help\n", azArg[2]); + rc = 1; + } + }else + + if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) { + sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue, + "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]); + }else + + if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){ + if( p->outfile[0]=='|' ){ + pclose(p->out); + }else{ + output_file_close(p->out); + } + p->outfile[0] = 0; + if( azArg[1][0]=='|' ){ + p->out = popen(&azArg[1][1], "w"); + if( p->out==0 ){ + fprintf(stderr,"Error: cannot open pipe \"%s\"\n", &azArg[1][1]); + p->out = stdout; + rc = 1; + }else{ + sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]); + } + }else{ + p->out = output_file_open(azArg[1]); + if( p->out==0 ){ + if( strcmp(azArg[1],"off")!=0 ){ + fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]); + } + p->out = stdout; + rc = 1; + } else { + sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]); + } + } + }else + + if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ + int i; + for(i=1; i1 ) fprintf(p->out, " "); + fprintf(p->out, "%s", azArg[i]); + } + fprintf(p->out, "\n"); + }else + + if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){ + if( nArg >= 2) { + strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); + } + if( nArg >= 3) { + strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); + } + }else + + if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){ + rc = 2; + }else + + if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){ + FILE *alt = fopen(azArg[1], "rb"); + if( alt==0 ){ + fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); + rc = 1; + }else{ + rc = process_input(p, alt); + fclose(alt); + } + }else + + if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){ + const char *zSrcFile; + const char *zDb; + sqlite3 *pSrc; + sqlite3_backup *pBackup; + int nTimeout = 0; + + if( nArg==2 ){ + zSrcFile = azArg[1]; + zDb = "main"; + }else{ + zSrcFile = azArg[2]; + zDb = azArg[1]; + } + rc = sqlite3_open(zSrcFile, &pSrc); + if( rc!=SQLITE_OK ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); + sqlite3_close(pSrc); + return 1; + } + open_db(p); + pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); + if( pBackup==0 ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); + sqlite3_close(pSrc); + return 1; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK + || rc==SQLITE_BUSY ){ + if( rc==SQLITE_BUSY ){ + if( nTimeout++ >= 3 ) break; + sqlite3_sleep(100); + } + } + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = 0; + }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ + fprintf(stderr, "Error: source database is busy\n"); + rc = 1; + }else{ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); + rc = 1; + } + sqlite3_close(pSrc); + }else + + if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){ + struct callback_data data; + char *zErrMsg = 0; + open_db(p); + memcpy(&data, p, sizeof(data)); + data.showHeader = 0; + data.mode = MODE_Semi; + if( nArg>1 ){ + int i; + for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]); + if( strcmp(azArg[1],"sqlite_master")==0 ){ + char *new_argv[2], *new_colv[2]; + new_argv[0] = "CREATE TABLE sqlite_master (\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")"; + new_argv[1] = 0; + new_colv[0] = "sql"; + new_colv[1] = 0; + callback(&data, 1, new_argv, new_colv); + rc = SQLITE_OK; + }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){ + char *new_argv[2], *new_colv[2]; + new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")"; + new_argv[1] = 0; + new_colv[0] = "sql"; + new_colv[1] = 0; + callback(&data, 1, new_argv, new_colv); + rc = SQLITE_OK; + }else{ + zShellStatic = azArg[1]; + rc = sqlite3_exec(p->db, + "SELECT sql FROM " + " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" + " FROM sqlite_master UNION ALL" + " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " + "WHERE lower(tbl_name) LIKE shellstatic()" + " AND type!='meta' AND sql NOTNULL " + "ORDER BY rowid", + callback, &data, &zErrMsg); + zShellStatic = 0; + } + }else{ + rc = sqlite3_exec(p->db, + "SELECT sql FROM " + " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" + " FROM sqlite_master UNION ALL" + " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " + "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'" + "ORDER BY rowid", + callback, &data, &zErrMsg + ); + } + if( zErrMsg ){ + fprintf(stderr,"Error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + rc = 1; + }else if( rc != SQLITE_OK ){ + fprintf(stderr,"Error: querying schema information\n"); + rc = 1; + }else{ + rc = 0; + } + }else + +#ifdef SQLITE_DEBUG + /* Undocumented commands for internal testing. Subject to change + ** without notice. */ + if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ + if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ + int i, v; + for(i=1; iout, "%s: %d 0x%x\n", azArg[i], v, v); + } + } + if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ + int i; sqlite3_int64 v; + for(i=1; iout, "%s", zBuf); + } + } + }else +#endif + + if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){ + sqlite3_snprintf(sizeof(p->separator), p->separator, + "%.*s", (int)sizeof(p->separator)-1, azArg[1]); + }else + + if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){ + int i; + fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off"); + fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off"); + fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off"); + fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]); + fprintf(p->out,"%9.9s: ", "nullvalue"); + output_c_string(p->out, p->nullvalue); + fprintf(p->out, "\n"); + fprintf(p->out,"%9.9s: %s\n","output", + strlen30(p->outfile) ? p->outfile : "stdout"); + fprintf(p->out,"%9.9s: ", "separator"); + output_c_string(p->out, p->separator); + fprintf(p->out, "\n"); + fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off"); + fprintf(p->out,"%9.9s: ","width"); + for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { + fprintf(p->out,"%d ",p->colWidth[i]); + } + fprintf(p->out,"\n"); + }else + + if( c=='s' && strncmp(azArg[0], "stats", n)==0 && nArg>1 && nArg<3 ){ + p->statsOn = booleanValue(azArg[1]); + }else + + if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){ + sqlite3_stmt *pStmt; + char **azResult; + int nRow, nAlloc; + char *zSql = 0; + int ii; + open_db(p); + rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); + if( rc ) return rc; + zSql = sqlite3_mprintf( + "SELECT name FROM sqlite_master" + " WHERE type IN ('table','view')" + " AND name NOT LIKE 'sqlite_%%'" + " AND name LIKE ?1"); + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); + if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue; + if( strcmp(zDbName,"temp")==0 ){ + zSql = sqlite3_mprintf( + "%z UNION ALL " + "SELECT 'temp.' || name FROM sqlite_temp_master" + " WHERE type IN ('table','view')" + " AND name NOT LIKE 'sqlite_%%'" + " AND name LIKE ?1", zSql); + }else{ + zSql = sqlite3_mprintf( + "%z UNION ALL " + "SELECT '%q.' || name FROM \"%w\".sqlite_master" + " WHERE type IN ('table','view')" + " AND name NOT LIKE 'sqlite_%%'" + " AND name LIKE ?1", zSql, zDbName, zDbName); + } + } + sqlite3_finalize(pStmt); + zSql = sqlite3_mprintf("%z ORDER BY 1", zSql); + rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + if( rc ) return rc; + nRow = nAlloc = 0; + azResult = 0; + if( nArg>1 ){ + sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); + }else{ + sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); + } + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + if( nRow>=nAlloc ){ + char **azNew; + int n = nAlloc*2 + 10; + azNew = sqlite3_realloc(azResult, sizeof(azResult[0])*n); + if( azNew==0 ){ + fprintf(stderr, "Error: out of memory\n"); + break; + } + nAlloc = n; + azResult = azNew; + } + azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); + if( azResult[nRow] ) nRow++; + } + sqlite3_finalize(pStmt); + if( nRow>0 ){ + int len, maxlen = 0; + int i, j; + int nPrintCol, nPrintRow; + for(i=0; imaxlen ) maxlen = len; + } + nPrintCol = 80/(maxlen+2); + if( nPrintCol<1 ) nPrintCol = 1; + nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; + for(i=0; iout, "%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : ""); + } + fprintf(p->out, "\n"); + } + } + for(ii=0; ii=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){ + static const struct { + const char *zCtrlName; /* Name of a test-control option */ + int ctrlCode; /* Integer code for that option */ + } aCtrl[] = { + { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE }, + { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE }, + { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET }, + { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST }, + { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL }, + { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS }, + { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE }, + { "assert", SQLITE_TESTCTRL_ASSERT }, + { "always", SQLITE_TESTCTRL_ALWAYS }, + { "reserve", SQLITE_TESTCTRL_RESERVE }, + { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS }, + { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD }, + { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC }, + }; + int testctrl = -1; + int rc = 0; + int i, n; + open_db(p); + + /* convert testctrl text option to value. allow any unique prefix + ** of the option name, or a numerical value. */ + n = strlen30(azArg[1]); + for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){ + if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){ + if( testctrl<0 ){ + testctrl = aCtrl[i].ctrlCode; + }else{ + fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]); + testctrl = -1; + break; + } + } + } + if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]); + if( (testctrlSQLITE_TESTCTRL_LAST) ){ + fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]); + }else{ + switch(testctrl){ + + /* sqlite3_test_control(int, db, int) */ + case SQLITE_TESTCTRL_OPTIMIZATIONS: + case SQLITE_TESTCTRL_RESERVE: + if( nArg==3 ){ + int opt = (int)strtol(azArg[2], 0, 0); + rc = sqlite3_test_control(testctrl, p->db, opt); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single int option\n", + azArg[1]); + } + break; + + /* sqlite3_test_control(int) */ + case SQLITE_TESTCTRL_PRNG_SAVE: + case SQLITE_TESTCTRL_PRNG_RESTORE: + case SQLITE_TESTCTRL_PRNG_RESET: + if( nArg==2 ){ + rc = sqlite3_test_control(testctrl); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]); + } + break; + + /* sqlite3_test_control(int, uint) */ + case SQLITE_TESTCTRL_PENDING_BYTE: + if( nArg==3 ){ + unsigned int opt = (unsigned int)integerValue(azArg[2]); + rc = sqlite3_test_control(testctrl, opt); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single unsigned" + " int option\n", azArg[1]); + } + break; + + /* sqlite3_test_control(int, int) */ + case SQLITE_TESTCTRL_ASSERT: + case SQLITE_TESTCTRL_ALWAYS: + if( nArg==3 ){ + int opt = booleanValue(azArg[2]); + rc = sqlite3_test_control(testctrl, opt); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single int option\n", + azArg[1]); + } + break; + + /* sqlite3_test_control(int, char *) */ +#ifdef SQLITE_N_KEYWORD + case SQLITE_TESTCTRL_ISKEYWORD: + if( nArg==3 ){ + const char *opt = azArg[2]; + rc = sqlite3_test_control(testctrl, opt); + fprintf(p->out, "%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single char * option\n", + azArg[1]); + } + break; +#endif + + case SQLITE_TESTCTRL_BITVEC_TEST: + case SQLITE_TESTCTRL_FAULT_INSTALL: + case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: + case SQLITE_TESTCTRL_SCRATCHMALLOC: + default: + fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n", + azArg[1]); + break; + } + } + }else + + if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){ + open_db(p); + sqlite3_busy_timeout(p->db, (int)integerValue(azArg[1])); + }else + + if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 + && nArg==2 + ){ + enableTimer = booleanValue(azArg[1]); + }else + + if( c=='t' && strncmp(azArg[0], "trace", n)==0 && nArg>1 ){ + open_db(p); + output_file_close(p->traceOut); + p->traceOut = output_file_open(azArg[1]); +#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) + if( p->traceOut==0 ){ + sqlite3_trace(p->db, 0, 0); + }else{ + sqlite3_trace(p->db, sql_trace_callback, p->traceOut); + } +#endif + }else + + if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ + fprintf(p->out, "SQLite %s %s\n" /*extra-version-info*/, + sqlite3_libversion(), sqlite3_sourceid()); + }else + + if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ + const char *zDbName = nArg==2 ? azArg[1] : "main"; + char *zVfsName = 0; + if( p->db ){ + sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); + if( zVfsName ){ + fprintf(p->out, "%s\n", zVfsName); + sqlite3_free(zVfsName); + } + } + }else + +#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) + if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ + extern int sqlite3WhereTrace; + sqlite3WhereTrace = booleanValue(azArg[1]); + }else +#endif + + if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){ + int j; + assert( nArg<=ArraySize(azArg) ); + for(j=1; jcolWidth); j++){ + p->colWidth[j-1] = (int)integerValue(azArg[j]); + } + }else + + { + fprintf(stderr, "Error: unknown command or invalid arguments: " + " \"%s\". Enter \".help\" for help\n", azArg[0]); + rc = 1; + } + + return rc; +} + +/* +** Return TRUE if a semicolon occurs anywhere in the first N characters +** of string z[]. +*/ +static int line_contains_semicolon(const char *z, int N){ + int i; + for(i=0; iout); + zLine = one_input_line(in, zLine, nSql>0); + if( zLine==0 ){ + /* End of input */ + if( stdin_is_interactive ) printf("\n"); + break; + } + if( seenInterrupt ){ + if( in!=0 ) break; + seenInterrupt = 0; + } + lineno++; + if( nSql==0 && _all_whitespace(zLine) ) continue; + if( zLine && zLine[0]=='.' && nSql==0 ){ + if( p->echoOn ) printf("%s\n", zLine); + rc = do_meta_command(zLine, p); + if( rc==2 ){ /* exit requested */ + break; + }else if( rc ){ + errCnt++; + } + continue; + } + if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ + memcpy(zLine,";",2); + } + nLine = strlen30(zLine); + if( nSql+nLine+2>=nAlloc ){ + nAlloc = nSql+nLine+100; + zSql = realloc(zSql, nAlloc); + if( zSql==0 ){ + fprintf(stderr, "Error: out of memory\n"); + exit(1); + } + } + nSqlPrior = nSql; + if( nSql==0 ){ + int i; + for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} + assert( nAlloc>0 && zSql!=0 ); + memcpy(zSql, zLine+i, nLine+1-i); + startline = lineno; + nSql = nLine-i; + }else{ + zSql[nSql++] = '\n'; + memcpy(zSql+nSql, zLine, nLine+1); + nSql += nLine; + } + if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) + && sqlite3_complete(zSql) ){ + p->cnt = 0; + open_db(p); + BEGIN_TIMER; + rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg); + END_TIMER; + if( rc || zErrMsg ){ + char zPrefix[100]; + if( in!=0 || !stdin_is_interactive ){ + sqlite3_snprintf(sizeof(zPrefix), zPrefix, + "Error: near line %d:", startline); + }else{ + sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); + } + if( zErrMsg!=0 ){ + fprintf(stderr, "%s %s\n", zPrefix, zErrMsg); + sqlite3_free(zErrMsg); + zErrMsg = 0; + }else{ + fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); + } + errCnt++; + } + nSql = 0; + }else if( nSql && _all_whitespace(zSql) ){ + nSql = 0; + } + } + if( nSql ){ + if( !_all_whitespace(zSql) ){ + fprintf(stderr, "Error: incomplete SQL: %s\n", zSql); + } + free(zSql); + } + free(zLine); + return errCnt>0; +} + +/* +** Return a pathname which is the user's home directory. A +** 0 return indicates an error of some kind. +*/ +static char *find_home_dir(void){ + static char *home_dir = NULL; + if( home_dir ) return home_dir; + +#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL) + { + struct passwd *pwent; + uid_t uid = getuid(); + if( (pwent=getpwuid(uid)) != NULL) { + home_dir = pwent->pw_dir; + } + } +#endif + +#if defined(_WIN32_WCE) + /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() + */ + home_dir = "/"; +#else + +#if defined(_WIN32) || defined(WIN32) + if (!home_dir) { + home_dir = getenv("USERPROFILE"); + } +#endif + + if (!home_dir) { + home_dir = getenv("HOME"); + } + +#if defined(_WIN32) || defined(WIN32) + if (!home_dir) { + char *zDrive, *zPath; + int n; + zDrive = getenv("HOMEDRIVE"); + zPath = getenv("HOMEPATH"); + if( zDrive && zPath ){ + n = strlen30(zDrive) + strlen30(zPath) + 1; + home_dir = malloc( n ); + if( home_dir==0 ) return 0; + sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); + return home_dir; + } + home_dir = "c:\\"; + } +#endif + +#endif /* !_WIN32_WCE */ + + if( home_dir ){ + int n = strlen30(home_dir) + 1; + char *z = malloc( n ); + if( z ) memcpy(z, home_dir, n); + home_dir = z; + } + + return home_dir; +} + +/* +** Read input from the file given by sqliterc_override. Or if that +** parameter is NULL, take input from ~/.sqliterc +** +** Returns the number of errors. +*/ +static int process_sqliterc( + struct callback_data *p, /* Configuration data */ + const char *sqliterc_override /* Name of config file. NULL to use default */ +){ + char *home_dir = NULL; + const char *sqliterc = sqliterc_override; + char *zBuf = 0; + FILE *in = NULL; + int rc = 0; + + if (sqliterc == NULL) { + home_dir = find_home_dir(); + if( home_dir==0 ){ +#if !defined(__RTP__) && !defined(_WRS_KERNEL) + fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0); +#endif + return 1; + } + sqlite3_initialize(); + zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); + sqliterc = zBuf; + } + in = fopen(sqliterc,"rb"); + if( in ){ + if( stdin_is_interactive ){ + fprintf(stderr,"-- Loading resources from %s\n",sqliterc); + } + rc = process_input(p,in); + fclose(in); + } + sqlite3_free(zBuf); + return rc; +} + +/* +** Show available command line options +*/ +static const char zOptions[] = + " -bail stop after hitting an error\n" + " -batch force batch I/O\n" + " -column set output mode to 'column'\n" + " -cmd COMMAND run \"COMMAND\" before reading stdin\n" + " -csv set output mode to 'csv'\n" + " -echo print commands before execution\n" + " -init FILENAME read/process named file\n" + " -[no]header turn headers on or off\n" +#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) + " -heap SIZE Size of heap for memsys3 or memsys5\n" +#endif + " -help show this message\n" + " -html set output mode to HTML\n" + " -interactive force interactive I/O\n" + " -line set output mode to 'line'\n" + " -list set output mode to 'list'\n" + " -mmap N default mmap size set to N\n" +#ifdef SQLITE_ENABLE_MULTIPLEX + " -multiplex enable the multiplexor VFS\n" +#endif + " -nullvalue TEXT set text string for NULL values. Default ''\n" + " -separator SEP set output field separator. Default: '|'\n" + " -stats print memory stats before each finalize\n" + " -version show SQLite version\n" + " -vfs NAME use NAME as the default VFS\n" +#ifdef SQLITE_ENABLE_VFSTRACE + " -vfstrace enable tracing of all VFS calls\n" +#endif +; +static void usage(int showDetail){ + fprintf(stderr, + "Usage: %s [OPTIONS] FILENAME [SQL]\n" + "FILENAME is the name of an SQLite database. A new database is created\n" + "if the file does not previously exist.\n", Argv0); + if( showDetail ){ + fprintf(stderr, "OPTIONS include:\n%s", zOptions); + }else{ + fprintf(stderr, "Use the -help option for additional information\n"); + } + exit(1); +} + +/* +** Initialize the state information in data +*/ +static void main_init(struct callback_data *data) { + memset(data, 0, sizeof(*data)); + data->mode = MODE_List; + memcpy(data->separator,"|", 2); + data->showHeader = 0; + sqlite3_config(SQLITE_CONFIG_URI, 1); + sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); + sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); + sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); + sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); +} + +/* +** Get the argument to an --option. Throw an error and die if no argument +** is available. +*/ +static char *cmdline_option_value(int argc, char **argv, int i){ + if( i==argc ){ + fprintf(stderr, "%s: Error: missing argument to %s\n", + argv[0], argv[argc-1]); + exit(1); + } + return argv[i]; +} + +int main(int argc, char **argv){ + char *zErrMsg = 0; + struct callback_data data; + const char *zInitFile = 0; + char *zFirstCmd = 0; + int i; + int rc = 0; + + if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){ + fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", + sqlite3_sourceid(), SQLITE_SOURCE_ID); + exit(1); + } + Argv0 = argv[0]; + main_init(&data); + stdin_is_interactive = isatty(0); + + /* Make sure we have a valid signal handler early, before anything + ** else is done. + */ +#ifdef SIGINT + signal(SIGINT, interrupt_handler); +#endif + + /* Do an initial pass through the command-line argument to locate + ** the name of the database file, the name of the initialization file, + ** the size of the alternative malloc heap, + ** and the first command to execute. + */ + for(i=1; i0x7fff0000 ) szHeap = 0x7fff0000; + sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); +#endif +#ifdef SQLITE_ENABLE_VFSTRACE + }else if( strcmp(z,"-vfstrace")==0 ){ + extern int vfstrace_register( + const char *zTraceName, + const char *zOldVfsName, + int (*xOut)(const char*,void*), + void *pOutArg, + int makeDefault + ); + vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); +#endif +#ifdef SQLITE_ENABLE_MULTIPLEX + }else if( strcmp(z,"-multiplex")==0 ){ + extern int sqlite3_multiple_initialize(const char*,int); + sqlite3_multiplex_initialize(0, 1); +#endif + }else if( strcmp(z,"-mmap")==0 ){ + sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); + sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); + }else if( strcmp(z,"-vfs")==0 ){ + sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i)); + if( pVfs ){ + sqlite3_vfs_register(pVfs, 1); + }else{ + fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]); + exit(1); + } + } + } + if( data.zDbFilename==0 ){ +#ifndef SQLITE_OMIT_MEMORYDB + data.zDbFilename = ":memory:"; +#else + fprintf(stderr,"%s: Error: no database filename specified\n", Argv0); + return 1; +#endif + } + data.out = stdout; + + /* Go ahead and open the database file if it already exists. If the + ** file does not exist, delay opening it. This prevents empty database + ** files from being created if a user mistypes the database name argument + ** to the sqlite command-line tool. + */ + if( access(data.zDbFilename, 0)==0 ){ + open_db(&data); + } + + /* Process the initialization file if there is one. If no -init option + ** is given on the command line, look for a file named ~/.sqliterc and + ** try to process it. + */ + rc = process_sqliterc(&data,zInitFile); + if( rc>0 ){ + return rc; + } + + /* Make a second pass through the command-line argument and set + ** options. This second pass is delayed until after the initialization + ** file is processed so that the command-line arguments will override + ** settings in the initialization file. + */ + for(i=1; i /* Needed for the definition of va_list */ + +/* +** Make sure we can call this stuff from C++. +*/ +#ifdef __cplusplus +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +/* +** These no-op macros are used in front of interfaces to mark those +** interfaces as either deprecated or experimental. New applications +** should not use deprecated interfaces - they are support for backwards +** compatibility only. Application writers should be aware that +** experimental interfaces are subject to change in point releases. +** +** These macros used to resolve to various kinds of compiler magic that +** would generate warning messages when they were used. But that +** compiler magic ended up generating such a flurry of bug reports +** that we have taken it all out and gone back to using simple +** noop macros. +*/ +#define SQLITE_DEPRECATED +#define SQLITE_EXPERIMENTAL + +/* +** Ensure these symbols were not defined by some previous header file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers +** +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header +** evaluates to a string literal that is the SQLite version in the +** format "X.Y.Z" where X is the major version number (always 3 for +** SQLite3) and Y is the minor version number and Z is the release number.)^ +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same +** numbers used in [SQLITE_VERSION].)^ +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also +** be larger than the release from which it is derived. Either Y will +** be held constant and Z will be incremented or else Y will be incremented +** and Z will be reset to zero. +** +** Since version 3.6.18, SQLite source code has been stored in the +** Fossil configuration management +** system. ^The SQLITE_SOURCE_ID macro evaluates to +** a string which identifies a particular check-in of SQLite +** within its configuration management system. ^The SQLITE_SOURCE_ID +** string contains the date and time of the check-in (UTC) and an SHA1 +** hash of the entire source tree. +** +** See also: [sqlite3_libversion()], +** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** [sqlite_version()] and [sqlite_source_id()]. +*/ +#define SQLITE_VERSION "--VERS--" +#define SQLITE_VERSION_NUMBER --VERSION-NUMBER-- +#define SQLITE_SOURCE_ID "--SOURCE-ID--" + +/* +** CAPI3REF: Run-Time Library Version Numbers +** KEYWORDS: sqlite3_version, sqlite3_sourceid +** +** These interfaces provide the same information as the [SQLITE_VERSION], +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros +** but are associated with the library instead of the header file. ^(Cautious +** programmers might include assert() statements in their application to +** verify that values returned by these interfaces match the macros in +** the header, and thus insure that the application is +** compiled with matching library and header files. +** +**
    +** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
    +** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
    +** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
    +** 
    )^ +** +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The sqlite3_libversion() function returns a pointer to the +** to the sqlite3_version[] string constant. The sqlite3_libversion() +** function is provided for use in DLLs since DLL users usually do not have +** direct access to string constants within the DLL. ^The +** sqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns +** a pointer to a string constant whose value is the same as the +** [SQLITE_SOURCE_ID] C preprocessor macro. +** +** See also: [sqlite_version()] and [sqlite_source_id()]. +*/ +SQLITE_EXTERN const char sqlite3_version[]; +const char *sqlite3_libversion(void); +const char *sqlite3_sourceid(void); +int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Run-Time Library Compilation Options Diagnostics +** +** ^The sqlite3_compileoption_used() function returns 0 or 1 +** indicating whether the specified option was defined at +** compile time. ^The SQLITE_ prefix may be omitted from the +** option name passed to sqlite3_compileoption_used(). +** +** ^The sqlite3_compileoption_get() function allows iterating +** over the list of options that were defined at compile time by +** returning the N-th compile time option string. ^If N is out of range, +** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** prefix is omitted from any strings returned by +** sqlite3_compileoption_get(). +** +** ^Support for the diagnostic functions sqlite3_compileoption_used() +** and sqlite3_compileoption_get() may be omitted by specifying the +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. +** +** See also: SQL functions [sqlite_compileoption_used()] and +** [sqlite_compileoption_get()] and the [compile_options pragma]. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +int sqlite3_compileoption_used(const char *zOptName); +const char *sqlite3_compileoption_get(int N); +#endif + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe +** +** ^The sqlite3_threadsafe() function returns zero if and only if +** SQLite was compiled with mutexing code omitted due to the +** [SQLITE_THREADSAFE] compile-time option being set to 0. +** +** SQLite can be compiled with or without mutexes. When +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes +** are enabled and SQLite is threadsafe. When the +** [SQLITE_THREADSAFE] macro is 0, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite concurrently from more than one thread. +** +** Enabling mutexes incurs a measurable performance penalty. +** So if speed is of utmost importance, it makes sense to disable +** the mutexes. But for maximum safety, mutexes should be enabled. +** ^The default behavior is for mutexes to be enabled. +** +** This interface can be used by an application to make sure that the +** version of SQLite that it is linking against was compiled with +** the desired setting of the [SQLITE_THREADSAFE] macro. +** +** This interface only reports on the compile-time mutex setting +** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but +** can be fully or partially disabled using a call to [sqlite3_config()] +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], +** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the +** sqlite3_threadsafe() function shows only the compile-time setting of +** thread safety, not any run-time changes to that setting made by +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() +** is unchanged by calls to sqlite3_config().)^ +** +** See the [threading mode] documentation for additional information. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle +** KEYWORDS: {database connection} {database connections} +** +** Each open SQLite database is represented by a pointer to an instance of +** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] +** and [sqlite3_close_v2()] are its destructors. There are many other +** interfaces (such as +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on an +** sqlite3 object. +*/ +typedef struct sqlite3 sqlite3; + +/* +** CAPI3REF: 64-Bit Integer Types +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The sqlite_int64 and sqlite_uint64 types are supported for backwards +** compatibility only. +** +** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** between -9223372036854775808 and +9223372036854775807 inclusive. ^The +** sqlite3_uint64 and sqlite_uint64 types can store integer values +** between 0 and +18446744073709551615 inclusive. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection +** +** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors +** for the [sqlite3] object. +** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if +** the [sqlite3] object is successfully destroyed and all associated +** resources are deallocated. +** +** ^If the database connection is associated with unfinalized prepared +** statements or unfinished sqlite3_backup objects then sqlite3_close() +** will leave the database connection open and return [SQLITE_BUSY]. +** ^If sqlite3_close_v2() is called with unfinalized prepared statements +** and unfinished sqlite3_backups, then the database connection becomes +** an unusable "zombie" which will automatically be deallocated when the +** last prepared statement is finalized or the last sqlite3_backup is +** finished. The sqlite3_close_v2() interface is intended for use with +** host languages that are garbage collected, and where the order in which +** destructors are called is arbitrary. +** +** Applications should [sqlite3_finalize | finalize] all [prepared statements], +** [sqlite3_blob_close | close] all [BLOB handles], and +** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated +** with the [sqlite3] object prior to attempting to close the object. ^If +** sqlite3_close_v2() is called on a [database connection] that still has +** outstanding [prepared statements], [BLOB handles], and/or +** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation +** of resources is deferred until all [prepared statements], [BLOB handles], +** and [sqlite3_backup] objects are also destroyed. +** +** ^If an [sqlite3] object is destroyed while a transaction is open, +** the transaction is automatically rolled back. +** +** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] +** must be either a NULL +** pointer or an [sqlite3] object pointer obtained +** from [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()], and not previously closed. +** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer +** argument is a harmless no-op. +*/ +int sqlite3_close(sqlite3*); +int sqlite3_close_v2(sqlite3*); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface +** +** The sqlite3_exec() interface is a convenience wrapper around +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** that allows an application to run multiple statements of SQL +** without having to use a lot of C code. +** +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** semicolon-separate SQL statements passed into its 2nd argument, +** in the context of the [database connection] passed in as its 1st +** argument. ^If the callback function of the 3rd argument to +** sqlite3_exec() is not NULL, then it is invoked for each result row +** coming out of the evaluated SQL statements. ^The 4th argument to +** sqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to sqlite3_exec() +** is NULL, then no callback is ever invoked and result rows are +** ignored. +** +** ^If an error occurs while evaluating the SQL statements passed into +** sqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** is not NULL then any error message is written into memory obtained +** from [sqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [sqlite3_free()] +** on error message strings returned through the 5th parameter of +** of sqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** NULL before returning. +** +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** routine returns SQLITE_ABORT without invoking the callback again and +** without running any subsequent SQL statements. +** +** ^The 2nd argument to the sqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** callback is an array of pointers to strings obtained as if from +** [sqlite3_column_text()], one for each column. ^If an element of a +** result row is NULL then the corresponding string pointer for the +** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** sqlite3_exec() callback is an array of pointers to strings where each +** entry represents the name of corresponding result column as obtained +** from [sqlite3_column_name()]. +** +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** to an empty string, or a pointer that contains only whitespace and/or +** SQL comments, then no SQL statements are evaluated and the database +** is not changed. +** +** Restrictions: +** +**
      +**
    • The application must insure that the 1st parameter to sqlite3_exec() +** is a valid and open [database connection]. +**
    • The application must not close [database connection] specified by +** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +**
    • The application must not modify the SQL statement text passed into +** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +**
    +*/ +int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes +** KEYWORDS: SQLITE_OK {error code} {error codes} +** KEYWORDS: {result code} {result codes} +** +** Many SQLite functions return an integer result code from the set shown +** here in order to indicate success or failure. +** +** New error codes may be added in future versions of SQLite. +** +** See also: [SQLITE_IOERR_READ | extended result codes], +** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes]. +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ +#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes +** KEYWORDS: {extended error code} {extended error codes} +** KEYWORDS: {extended result code} {extended result codes} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that many of +** these result codes are too coarse-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. The extended result codes are enabled or disabled +** on a per database connection basis using the +** [sqlite3_extended_result_codes()] API. +** +** Some of the available extended result codes are listed here. +** One may expect the number of extended result codes will be expand +** over time. Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) +#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) +#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) +#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) +#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) +#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) +#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) +#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) +#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) +#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) +#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) +#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) +#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) +#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) +#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) +#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) +#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) +#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) +#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) +#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) +#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) +#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) +#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) +#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) +#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) +#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) +#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) +#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) +#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) +#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) +#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) +#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) +#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) +#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) +#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) +#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) + +/* +** CAPI3REF: Flags For File Open Operations +** +** These bit values are intended for use in the +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter to the [sqlite3_vfs.xOpen] method. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ +#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ +#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ +#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ + +/* Reserved: 0x00F00000 */ + +/* +** CAPI3REF: Device Characteristics +** +** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** object returns an integer which is a vector of these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that +** after reboot following a crash or power loss, the only bytes in a +** file that were written at the application level might have changed +** and that adjacent bytes, even bytes within the same sector are +** guaranteed to be unchanged. +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 +#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 + +/* +** CAPI3REF: File Locking Levels +** +** SQLite uses one of these integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags +** +** When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of +** these integer values as the second argument. +** +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. If the lower four bits of the flag +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. +** If the lower four bits equal SQLITE_SYNC_FULL, that means +** to use Mac OS X style fullsync instead of fsync(). +** +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL +** settings. The [synchronous pragma] determines when calls to the +** xSync VFS method occur and applies uniformly across all platforms. +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how +** energetic or rigorous or forceful the sync operations are and +** only make a difference on Mac OSX for the default SQLite code. +** (Third-party VFS implementations might also make the distinction +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the +** operating systems natively supported by SQLite, only Mac OSX +** cares about the difference.) +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + +/* +** CAPI3REF: OS Interface Open File Handle +** +** An [sqlite3_file] object represents an open file in the +** [sqlite3_vfs | OS interface layer]. Individual OS interface +** implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object +** +** Every file opened by the [sqlite3_vfs.xOpen] method populates an +** [sqlite3_file] object (or, more commonly, a subclass of the +** [sqlite3_file] object) with a pointer to an instance of this object. +** This object defines the methods used to perform various operations +** against the open file represented by the [sqlite3_file] object. +** +** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method +** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The +** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] +** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element +** to NULL. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] +** flag may be ORed in to indicate that only the data of the file +** and not its inode needs to be synced. +** +** The integer values to xLock() and xUnlock() are one of +**
      +**
    • [SQLITE_LOCK_NONE], +**
    • [SQLITE_LOCK_SHARED], +**
    • [SQLITE_LOCK_RESERVED], +**
    • [SQLITE_LOCK_PENDING], or +**
    • [SQLITE_LOCK_EXCLUSIVE]. +**
    +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method checks whether any database connection, +** either in this process or in some other process, is holding a RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false otherwise. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument is an +** integer opcode. The third argument is a generic pointer intended to +** point to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves all opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. VFS implementations should +** return [SQLITE_NOTFOUND] for file control opcodes that they do not +** recognize. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
      +**
    • [SQLITE_IOCAP_ATOMIC] +**
    • [SQLITE_IOCAP_ATOMIC512] +**
    • [SQLITE_IOCAP_ATOMIC1K] +**
    • [SQLITE_IOCAP_ATOMIC2K] +**
    • [SQLITE_IOCAP_ATOMIC4K] +**
    • [SQLITE_IOCAP_ATOMIC8K] +**
    • [SQLITE_IOCAP_ATOMIC16K] +**
    • [SQLITE_IOCAP_ATOMIC32K] +**
    • [SQLITE_IOCAP_ATOMIC64K] +**
    • [SQLITE_IOCAP_SAFE_APPEND] +**
    • [SQLITE_IOCAP_SEQUENTIAL] +**
    +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +** +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill +** in the unread portions of the buffer with zeros. A VFS that +** fails to zero-fill short reads might seem to work. However, +** failure to zero-fill short reads will eventually lead to +** database corruption. +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Methods above are valid for version 1 */ + int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(sqlite3_file*); + int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + /* Methods above are valid for version 2 */ + int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); + int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); + /* Methods above are valid for version 3 */ + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** interface. +** +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode causes the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +**
      +**
    • [[SQLITE_FCNTL_SIZE_HINT]] +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS +** layer a hint of how large the database file will grow to be during the +** current transaction. This hint is not guaranteed to be accurate but it +** is often close. The underlying VFS might choose to preallocate database +** file space based on this hint in order to help writes to the database +** file run faster. +** +**
    • [[SQLITE_FCNTL_CHUNK_SIZE]] +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS +** extends and truncates the database file in chunks of a size specified +** by the user. The fourth argument to [sqlite3_file_control()] should +** point to an integer (type int) containing the new chunk-size to use +** for the nominated database. Allocating database file space in large +** chunks (say 1MB at a time), may reduce file-system fragmentation and +** improve performance on some systems. +** +**
    • [[SQLITE_FCNTL_FILE_POINTER]] +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with a particular database +** connection. See the [sqlite3_file_control()] documentation for +** additional information. +** +**
    • [[SQLITE_FCNTL_SYNC_OMITTED]] +** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by +** SQLite and sent to all VFSes in place of a call to the xSync method +** when the database connection has [PRAGMA synchronous] set to OFF.)^ +** Some specialized VFSes need this signal in order to operate correctly +** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most +** VFSes do not need this signal and should silently ignore this opcode. +** Applications should not call [sqlite3_file_control()] with this +** opcode as doing so may disrupt the operation of the specialized VFSes +** that do require it. +** +**
    • [[SQLITE_FCNTL_WIN32_AV_RETRY]] +** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic +** retry counts and intervals for certain disk I/O operations for the +** windows [VFS] in order to provide robustness in the presence of +** anti-virus programs. By default, the windows VFS will retry file read, +** file write, and file delete operations up to 10 times, with a delay +** of 25 milliseconds before the first retry and with the delay increasing +** by an additional 25 milliseconds with each subsequent retry. This +** opcode allows these two values (10 retries and 25 milliseconds of delay) +** to be adjusted. The values are changed for all database connections +** within the same process. The argument is a pointer to an array of two +** integers where the first integer i the new retry count and the second +** integer is the delay. If either integer is negative, then the setting +** is not changed but instead the prior value of that setting is written +** into the array entry, allowing the current retry settings to be +** interrogated. The zDbName parameter is ignored. +** +**
    • [[SQLITE_FCNTL_PERSIST_WAL]] +** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the +** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary +** write ahead log and shared memory files used for transaction control +** are automatically deleted when the latest connection to the database +** closes. Setting persistent WAL mode causes those files to persist after +** close. Persisting the files is useful when other processes that do not +** have write permission on the directory containing the database file want +** to read the database file, as the WAL and shared memory files must exist +** in order for the database to be readable. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable persistent WAL mode or 1 to enable persistent +** WAL mode. If the integer is -1, then it is overwritten with the current +** WAL persistence setting. +** +**
    • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] +** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the +** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting +** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the +** xDeviceCharacteristics methods. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage +** mode. If the integer is -1, then it is overwritten with the current +** zero-damage mode setting. +** +**
    • [[SQLITE_FCNTL_OVERWRITE]] +** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening +** a write transaction to indicate that, unless it is rolled back for some +** reason, the entire database file will be overwritten by the current +** transaction. This is used by VACUUM operations. +** +**
    • [[SQLITE_FCNTL_VFSNAME]] +** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of +** all [VFSes] in the VFS stack. The names are of all VFS shims and the +** final bottom-level VFS are written into memory obtained from +** [sqlite3_malloc()] and the result is stored in the char* variable +** that the fourth parameter of [sqlite3_file_control()] points to. +** The caller is responsible for freeing the memory when done. As with +** all file-control actions, there is no guarantee that this will actually +** do anything. Callers should initialize the char* variable to a NULL +** pointer in case this file-control is not implemented. This file-control +** is intended for diagnostic use only. +** +**
    • [[SQLITE_FCNTL_PRAGMA]] +** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] +** file control is sent to the open [sqlite3_file] object corresponding +** to the database file to which the pragma statement refers. ^The argument +** to the [SQLITE_FCNTL_PRAGMA] file control is an array of +** pointers to strings (char**) in which the second element of the array +** is the name of the pragma and the third element is the argument to the +** pragma or NULL if the pragma has no argument. ^The handler for an +** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element +** of the char** argument point to a string obtained from [sqlite3_mprintf()] +** or the equivalent and that string will become the result of the pragma or +** the error message if the pragma fails. ^If the +** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal +** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] +** file control returns [SQLITE_OK], then the parser assumes that the +** VFS has handled the PRAGMA itself and the parser generates a no-op +** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns +** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means +** that the VFS encountered an error while handling the [PRAGMA] and the +** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] +** file control occurs at the beginning of pragma statement analysis and so +** it is able to override built-in [PRAGMA] statements. +** +**
    • [[SQLITE_FCNTL_BUSYHANDLER]] +** ^The [SQLITE_FCNTL_BUSYHANDLER] +** file-control may be invoked by SQLite on the database file handle +** shortly after it is opened in order to provide a custom VFS with access +** to the connections busy-handler callback. The argument is of type (void **) +** - an array of two (void *) values. The first (void *) actually points +** to a function of type (int (*)(void *)). In order to invoke the connections +** busy-handler, this function should be invoked with the second (void *) in +** the array as the only argument. If it returns non-zero, then the operation +** should be retried. If it returns zero, the custom VFS should abandon the +** current operation. +** +**
    • [[SQLITE_FCNTL_TEMPFILENAME]] +** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control +** to have SQLite generate a +** temporary filename using the same algorithm that is followed to generate +** temporary filenames for TEMP tables and other internal uses. The +** argument should be a char** which will be filled with the filename +** written into memory obtained from [sqlite3_malloc()]. The caller should +** invoke [sqlite3_free()] on the result to avoid a memory leak. +** +**
    • [[SQLITE_FCNTL_MMAP_SIZE]] +** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the +** maximum number of bytes that will be used for memory-mapped I/O. +** The argument is a pointer to a value of type sqlite3_int64 that +** is an advisory maximum number of bytes in the file to memory map. The +** pointer is overwritten with the old value. The limit is not changed if +** the value originally pointed to is negative, and so the current limit +** can be queried by passing in a pointer to a negative number. This +** file-control is used internally to implement [PRAGMA mmap_size]. +** +**
    +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 +#define SQLITE_GET_LOCKPROXYFILE 2 +#define SQLITE_SET_LOCKPROXYFILE 3 +#define SQLITE_LAST_ERRNO 4 +#define SQLITE_FCNTL_SIZE_HINT 5 +#define SQLITE_FCNTL_CHUNK_SIZE 6 +#define SQLITE_FCNTL_FILE_POINTER 7 +#define SQLITE_FCNTL_SYNC_OMITTED 8 +#define SQLITE_FCNTL_WIN32_AV_RETRY 9 +#define SQLITE_FCNTL_PERSIST_WAL 10 +#define SQLITE_FCNTL_OVERWRITE 11 +#define SQLITE_FCNTL_VFSNAME 12 +#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 +#define SQLITE_FCNTL_PRAGMA 14 +#define SQLITE_FCNTL_BUSYHANDLER 15 +#define SQLITE_FCNTL_TEMPFILENAME 16 +#define SQLITE_FCNTL_MMAP_SIZE 18 + +/* +** CAPI3REF: Mutex Handle +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object +** +** An instance of the sqlite3_vfs object defines the interface between +** the SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". See +** the [VFS | VFS documentation] for further information. +** +** The value of the iVersion field is initially 1 but may be larger in +** future versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. Note that the structure +** of the sqlite3_vfs object changes in the transaction between +** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not +** modified. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered sqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. Neither the application code nor the VFS +** implementation should use the pNext pointer. +** +** The pNext field is the only field in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** [[sqlite3_vfs.xOpen]] +** ^SQLite guarantees that the zFilename parameter to xOpen +** is either a NULL pointer or string obtained +** from xFullPathname() with an optional suffix added. +** ^If a suffix is added to the zFilename parameter, it will +** consist of a single "-" character followed by no more than +** 11 alphanumeric and/or "-" characters. +** ^SQLite further guarantees that +** the string will be valid and unchanged until xClose() is +** called. Because of the previous sentence, +** the [sqlite3_file] can safely store a pointer to the +** filename if it needs to remember the filename for some reason. +** If the zFilename parameter to xOpen is a NULL pointer then xOpen +** must invent its own temporary name for the file. ^Whenever the +** xFilename parameter is NULL it will also be the case that the +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. +** +** The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. +** +** ^(SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
      +**
    • [SQLITE_OPEN_MAIN_DB] +**
    • [SQLITE_OPEN_MAIN_JOURNAL] +**
    • [SQLITE_OPEN_TEMP_DB] +**
    • [SQLITE_OPEN_TEMP_JOURNAL] +**
    • [SQLITE_OPEN_TRANSIENT_DB] +**
    • [SQLITE_OPEN_SUBJOURNAL] +**
    • [SQLITE_OPEN_MASTER_JOURNAL] +**
    • [SQLITE_OPEN_WAL] +**
    )^ +** +** The file I/O implementation can use the object type flags to +** change the way it deals with files. For example, an application +** that does not care about crash recovery or rollback might make +** the open of a journal file a no-op. Writes to this journal would +** also be no-ops, and any attempt to read the journal would return +** SQLITE_IOERR. Or the implementation might recognize that a database +** file will be doing page-aligned sector reads and writes in a random +** order and set up its I/O subsystem accordingly. +** +** SQLite might also add one of the following flags to the xOpen method: +** +**
      +**
    • [SQLITE_OPEN_DELETEONCLOSE] +**
    • [SQLITE_OPEN_EXCLUSIVE] +**
    +** +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases and their journals, transient +** databases, and subjournals. +** +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction +** with the [SQLITE_OPEN_CREATE] flag, which are both directly +** analogous to the O_EXCL and O_CREAT flags of the POSIX open() +** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the +** SQLITE_OPEN_CREATE, is used to indicate that file should always +** be created, and that it is an error if it already exists. +** It is not used to indicate the file should be opened +** for exclusive access. +** +** ^At least szOsFile bytes of memory are allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. The xOpen method does not have to +** allocate the structure; it should just fill it in. Note that +** the xOpen method must set the sqlite3_file.pMethods to either +** a valid [sqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** element will be valid after xOpen returns regardless of the success +** or failure of the xOpen call. +** +** [[sqlite3_vfs.xAccess]] +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test whether a file is at least readable. The file can be a +** directory. +** +** ^SQLite will always allocate at least mxPathname+1 bytes for the +** output buffer xFullPathname. The exact size of the output buffer +** is also passed as a parameter to both methods. If the output buffer +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is +** handled as a fatal error by SQLite, vfs implementations should endeavor +** to prevent this by setting mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() +** interfaces are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. +** The xSleep() method causes the calling thread to sleep for at +** least the number of microseconds given. ^The xCurrentTime() +** method returns a Julian Day Number for the current date and time as +** a floating point value. +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian +** Day Number multiplied by 86400000 (the number of milliseconds in +** a 24-hour day). +** ^SQLite will use the xCurrentTimeInt64() method to get the current +** date and time if that method is available (if iVersion is 2 or +** greater and the function pointer is not NULL) and will fall back +** to xCurrentTime() if xCurrentTimeInt64() is unavailable. +** +** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces +** are not used by the SQLite core. These optional interfaces are provided +** by some VFSes to facilitate testing of the VFS code. By overriding +** system calls with functions under its control, a test program can +** simulate faults and error conditions that would otherwise be difficult +** or impossible to induce. The set of system calls that can be overridden +** varies from one VFS to another, and from one version of the same VFS to the +** next. Applications that use these interfaces must be prepared for any +** or all of these interfaces to be NULL or for their behavior to change +** from one release to the next. Applications must not attempt to access +** any of these methods if the iVersion of the VFS is less than 3. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +typedef void (*sqlite3_syscall_ptr)(void); +struct sqlite3_vfs { + int iVersion; /* Structure version number (currently 3) */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + int (*xGetLastError)(sqlite3_vfs*, int, char *); + /* + ** The methods above are in version 1 of the sqlite_vfs object + ** definition. Those that follow are added in version 2 or later + */ + int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + /* + ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + ** Those below are for version 3 and greater. + */ + int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); + sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); + const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); + /* + ** The methods above are in versions 1 through 3 of the sqlite_vfs object. + ** New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. + */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method +** +** These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. They determine +** what kind of permissions the xAccess method is looking for. +** With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks whether the file exists. +** With SQLITE_ACCESS_READWRITE, the xAccess method +** checks whether the named directory is both readable and writable +** (in other words, if files can be added, removed, and renamed within +** the directory). +** The SQLITE_ACCESS_READWRITE constant is currently used only by the +** [temp_store_directory pragma], though this could change in a future +** release of SQLite. +** With SQLITE_ACCESS_READ, the xAccess method +** checks whether the file is readable. The SQLITE_ACCESS_READ constant is +** currently unused, though it might be used in a future release of +** SQLite. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ +#define SQLITE_ACCESS_READ 2 /* Unused */ + +/* +** CAPI3REF: Flags for the xShmLock VFS method +** +** These integer constants define the various locking operations +** allowed by the xShmLock method of [sqlite3_io_methods]. The +** following are the only legal combinations of flags to the +** xShmLock method: +** +**
      +**
    • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED +**
    • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE +**
    • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED +**
    • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE +**
    +** +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as +** was given no the corresponding lock. +** +** The xShmLock method can transition between unlocked and SHARED or +** between unlocked and EXCLUSIVE. It cannot transition between SHARED +** and EXCLUSIVE. +*/ +#define SQLITE_SHM_UNLOCK 1 +#define SQLITE_SHM_LOCK 2 +#define SQLITE_SHM_SHARED 4 +#define SQLITE_SHM_EXCLUSIVE 8 + +/* +** CAPI3REF: Maximum xShmLock index +** +** The xShmLock method on [sqlite3_io_methods] may use values +** between 0 and this upper bound as its "offset" argument. +** The SQLite core will never attempt to acquire or release a +** lock outside of this range +*/ +#define SQLITE_SHM_NLOCK 8 + + +/* +** CAPI3REF: Initialize The SQLite Library +** +** ^The sqlite3_initialize() routine initializes the +** SQLite library. ^The sqlite3_shutdown() routine +** deallocates any resources that were allocated by sqlite3_initialize(). +** These routines are designed to aid in process initialization and +** shutdown on embedded systems. Workstation applications using +** SQLite normally do not need to invoke either of these routines. +** +** A call to sqlite3_initialize() is an "effective" call if it is +** the first time sqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time sqlite3_initialize() is invoked +** following a call to sqlite3_shutdown(). ^(Only an effective call +** of sqlite3_initialize() does any initialization. All other calls +** are harmless no-ops.)^ +** +** A call to sqlite3_shutdown() is an "effective" call if it is the first +** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only +** an effective call to sqlite3_shutdown() does any deinitialization. +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() +** is not. The sqlite3_shutdown() interface must only be called from a +** single thread. All open [database connections] must be closed and all +** other SQLite resources must be deallocated prior to invoking +** sqlite3_shutdown(). +** +** Among other things, ^sqlite3_initialize() will invoke +** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() +** will invoke sqlite3_os_end(). +** +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, sqlite3_initialize() is unable to initialize +** the library (perhaps it is unable to allocate a needed resource such +** as a mutex) it returns an [error code] other than [SQLITE_OK]. +** +** ^The sqlite3_initialize() routine is called internally by many other +** SQLite interfaces so that an application usually does not need to +** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] +** calls sqlite3_initialize() so the SQLite library will be automatically +** initialized when [sqlite3_open()] is called if it has not be initialized +** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] +** compile-time option, then the automatic calls to sqlite3_initialize() +** are omitted and the application must call sqlite3_initialize() directly +** prior to using any other SQLite interface. For maximum portability, +** it is recommended that applications always invoke sqlite3_initialize() +** directly prior to using any other SQLite interface. Future releases +** of SQLite may require this. In other words, the behavior exhibited +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the +** default behavior in some future release of SQLite. +** +** The sqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The sqlite3_os_end() +** routine undoes the effect of sqlite3_os_init(). Typical tasks +** performed by these routines include allocation or deallocation +** of static resources, initialization of global variables, +** setting up a default [sqlite3_vfs] module, or setting up +** a default configuration using [sqlite3_config()]. +** +** The application should never invoke either sqlite3_os_init() +** or sqlite3_os_end() directly. The application should only invoke +** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() +** interface is called automatically by sqlite3_initialize() and +** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate +** implementations for sqlite3_os_init() and sqlite3_os_end() +** are built into SQLite when it is compiled for Unix, Windows, or OS/2. +** When [custom builds | built for other platforms] +** (using the [SQLITE_OS_OTHER=1] compile-time +** option) the application must supply a suitable implementation for +** sqlite3_os_init() and sqlite3_os_end(). An application-supplied +** implementation of sqlite3_os_init() or sqlite3_os_end() +** must return [SQLITE_OK] on success and some other [error code] upon +** failure. +*/ +int sqlite3_initialize(void); +int sqlite3_shutdown(void); +int sqlite3_os_init(void); +int sqlite3_os_end(void); + +/* +** CAPI3REF: Configuring The SQLite Library +** +** The sqlite3_config() interface is used to make global configuration +** changes to SQLite in order to tune SQLite to the specific needs of +** the application. The default configuration is recommended for most +** applications and so this routine is usually not necessary. It is +** provided to support rare applications with unusual needs. +** +** The sqlite3_config() interface is not threadsafe. The application +** must insure that no other SQLite interfaces are invoked by other +** threads while sqlite3_config() is running. Furthermore, sqlite3_config() +** may only be invoked prior to library initialization using +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before +** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. +** Note, however, that ^sqlite3_config() can be called as part of the +** implementation of an application-defined [sqlite3_os_init()]. +** +** The first argument to sqlite3_config() is an integer +** [configuration option] that determines +** what property of SQLite is to be configured. Subsequent arguments +** vary depending on the [configuration option] +** in the first argument. +** +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^If the option is unknown or SQLite is unable to set the option +** then this routine returns a non-zero [error code]. +*/ +int sqlite3_config(int, ...); + +/* +** CAPI3REF: Configure database connections +** +** The sqlite3_db_config() interface is used to make configuration +** changes to a [database connection]. The interface is similar to +** [sqlite3_config()] except that the changes apply to a single +** [database connection] (specified in the first argument). +** +** The second argument to sqlite3_db_config(D,V,...) is the +** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code +** that indicates what aspect of the [database connection] is being configured. +** Subsequent arguments vary depending on the configuration verb. +** +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** the call is considered successful. +*/ +int sqlite3_db_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Memory Allocation Routines +** +** An instance of this object defines the interface between SQLite +** and low-level memory allocation routines. +** +** This object is used in only one place in the SQLite interface. +** A pointer to an instance of this object is the argument to +** [sqlite3_config()] when the configuration option is +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. +** By creating an instance of this object +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** during configuration, an application can specify an alternative +** memory allocation subsystem for SQLite to use for all of its +** dynamic memory needs. +** +** Note that SQLite comes with several [built-in memory allocators] +** that are perfectly adequate for the overwhelming majority of applications +** and that this object is only useful to a tiny minority of applications +** with specialized memory allocation requirements. This object is +** also used during testing of SQLite in order to specify an alternative +** memory allocator that simulates memory out-of-memory conditions in +** order to verify that SQLite recovers gracefully from such +** conditions. +** +** The xMalloc, xRealloc, and xFree methods must work like the +** malloc(), realloc() and free() functions from the standard C library. +** ^SQLite guarantees that the second argument to +** xRealloc is always a value returned by a prior call to xRoundup. +** +** xSize should return the allocated size of a memory allocation +** previously obtained from xMalloc or xRealloc. The allocated size +** is always at least as big as the requested size but may be larger. +** +** The xRoundup method returns what would be the allocated size of +** a memory allocation given a particular requested size. Most memory +** allocators round up memory allocations at least to the next multiple +** of 8. Some allocators round up to a larger multiple or to a power of 2. +** Every memory allocation request coming in through [sqlite3_malloc()] +** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** that causes the corresponding memory allocation to fail. +** +** The xInit method initializes the memory allocator. (For example, +** it might allocate any require mutexes or initialize internal data +** structures. The xShutdown method is invoked (indirectly) by +** [sqlite3_shutdown()] and should deallocate any resources acquired +** by xInit. The pAppData pointer is used as the only parameter to +** xInit and xShutdown. +** +** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes +** the xInit method, so the xInit method need not be threadsafe. The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. For all other methods, SQLite +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which +** it is by default) and so the methods are automatically serialized. +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other +** methods must be threadsafe or else make their own arrangements for +** serialization. +** +** SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +*/ +typedef struct sqlite3_mem_methods sqlite3_mem_methods; +struct sqlite3_mem_methods { + void *(*xMalloc)(int); /* Memory allocation function */ + void (*xFree)(void*); /* Free a prior allocation */ + void *(*xRealloc)(void*,int); /* Resize an allocation */ + int (*xSize)(void*); /* Return the size of an allocation */ + int (*xRoundup)(int); /* Round up request size to allocation size */ + int (*xInit)(void*); /* Initialize the memory allocator */ + void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + void *pAppData; /* Argument to xInit() and xShutdown() */ +}; + +/* +** CAPI3REF: Configuration Options +** KEYWORDS: {configuration option} +** +** These constants are the available integer configuration options that +** can be passed as the first argument to the [sqlite3_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_config()] to make sure that +** the call worked. The [sqlite3_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
    +** [[SQLITE_CONFIG_SINGLETHREAD]]
    SQLITE_CONFIG_SINGLETHREAD
    +**
    There are no arguments to this option. ^This option sets the +** [threading mode] to Single-thread. In other words, it disables +** all mutexing and puts SQLite into a mode where it can only be used +** by a single thread. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to change the [threading mode] from its default +** value of Single-thread and so [sqlite3_config()] will return +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD +** configuration option.
    +** +** [[SQLITE_CONFIG_MULTITHREAD]]
    SQLITE_CONFIG_MULTITHREAD
    +**
    There are no arguments to this option. ^This option sets the +** [threading mode] to Multi-thread. In other words, it disables +** mutexing on [database connection] and [prepared statement] objects. +** The application is responsible for serializing access to +** [database connections] and [prepared statements]. But other mutexes +** are enabled so that SQLite will be safe to use in a multi-threaded +** environment as long as no two threads attempt to use the same +** [database connection] at the same time. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Multi-thread [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_MULTITHREAD configuration option.
    +** +** [[SQLITE_CONFIG_SERIALIZED]]
    SQLITE_CONFIG_SERIALIZED
    +**
    There are no arguments to this option. ^This option sets the +** [threading mode] to Serialized. In other words, this option enables +** all mutexes including the recursive +** mutexes on [database connection] and [prepared statement] objects. +** In this mode (which is the default when SQLite is compiled with +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access +** to [database connections] and [prepared statements] so that the +** application is free to use the same [database connection] or the +** same [prepared statement] in different threads at the same time. +** ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Serialized [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_SERIALIZED configuration option.
    +** +** [[SQLITE_CONFIG_MALLOC]]
    SQLITE_CONFIG_MALLOC
    +**
    ^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The argument specifies +** alternative low-level memory allocation routines to be used in place of +** the memory allocation routines built into SQLite.)^ ^SQLite makes +** its own private copy of the content of the [sqlite3_mem_methods] structure +** before the [sqlite3_config()] call returns.
    +** +** [[SQLITE_CONFIG_GETMALLOC]]
    SQLITE_CONFIG_GETMALLOC
    +**
    ^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] +** structure is filled with the currently defined memory allocation routines.)^ +** This option can be used to overload the default memory allocation +** routines with a wrapper that simulations memory allocation failure or +** tracks memory usage, for example.
    +** +** [[SQLITE_CONFIG_MEMSTATUS]]
    SQLITE_CONFIG_MEMSTATUS
    +**
    ^This option takes single argument of type int, interpreted as a +** boolean, which enables or disables the collection of memory allocation +** statistics. ^(When memory allocation statistics are disabled, the +** following SQLite interfaces become non-operational: +**
      +**
    • [sqlite3_memory_used()] +**
    • [sqlite3_memory_highwater()] +**
    • [sqlite3_soft_heap_limit64()] +**
    • [sqlite3_status()] +**
    )^ +** ^Memory allocation statistics are enabled by default unless SQLite is +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory +** allocation statistics are disabled by default. +**
    +** +** [[SQLITE_CONFIG_SCRATCH]]
    SQLITE_CONFIG_SCRATCH
    +**
    ^This option specifies a static memory buffer that SQLite can use for +** scratch memory. There are three arguments: A pointer an 8-byte +** aligned memory buffer from which the scratch allocations will be +** drawn, the size of each scratch allocation (sz), +** and the maximum number of scratch allocations (N). The sz +** argument must be a multiple of 16. +** The first argument must be a pointer to an 8-byte aligned buffer +** of at least sz*N bytes of memory. +** ^SQLite will use no more than two scratch buffers per thread. So +** N should be set to twice the expected maximum number of threads. +** ^SQLite will never require a scratch buffer that is more than 6 +** times the database page size. ^If SQLite needs needs additional +** scratch memory beyond what is provided by this configuration option, then +** [sqlite3_malloc()] will be used to obtain the memory needed.
    +** +** [[SQLITE_CONFIG_PAGECACHE]]
    SQLITE_CONFIG_PAGECACHE
    +**
    ^This option specifies a static memory buffer that SQLite can use for +** the database page cache with the default page cache implementation. +** This configuration should not be used if an application-define page +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option. +** There are three arguments to this option: A pointer to 8-byte aligned +** memory, the size of each page buffer (sz), and the number of pages (N). +** The sz argument should be the size of the largest database page +** (a power of two between 512 and 32768) plus a little extra for each +** page header. ^The page header size is 20 to 40 bytes depending on +** the host architecture. ^It is harmless, apart from the wasted memory, +** to make sz a little too large. The first +** argument should point to an allocation of at least sz*N bytes of memory. +** ^SQLite will use the memory provided by the first argument to satisfy its +** memory needs for the first N pages that it adds to cache. ^If additional +** page cache memory is needed beyond what is provided by this option, then +** SQLite goes to [sqlite3_malloc()] for the additional storage space. +** The pointer in the first argument must +** be aligned to an 8-byte boundary or subsequent behavior of SQLite +** will be undefined.
    +** +** [[SQLITE_CONFIG_HEAP]]
    SQLITE_CONFIG_HEAP
    +**
    ^This option specifies a static memory buffer that SQLite will use +** for all of its dynamic memory allocation needs beyond those provided +** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. +** There are three arguments: An 8-byte aligned pointer to the memory, +** the number of bytes in the memory buffer, and the minimum allocation size. +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts +** to using its default memory allocator (the system malloc() implementation), +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the +** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or +** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory +** allocator is engaged to handle all of SQLites memory allocation needs. +** The first pointer (the memory pointer) must be aligned to an 8-byte +** boundary or subsequent behavior of SQLite will be undefined. +** The minimum allocation size is capped at 2**12. Reasonable values +** for the minimum allocation size are 2**5 through 2**8.
    +** +** [[SQLITE_CONFIG_MUTEX]]
    SQLITE_CONFIG_MUTEX
    +**
    ^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The argument specifies +** alternative low-level mutex routines to be used in place +** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the +** content of the [sqlite3_mutex_methods] structure before the call to +** [sqlite3_config()] returns. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** return [SQLITE_ERROR].
    +** +** [[SQLITE_CONFIG_GETMUTEX]]
    SQLITE_CONFIG_GETMUTEX
    +**
    ^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The +** [sqlite3_mutex_methods] +** structure is filled with the currently defined mutex routines.)^ +** This option can be used to overload the default mutex allocation +** routines with a wrapper used to track mutex usage for performance +** profiling or testing, for example. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** return [SQLITE_ERROR].
    +** +** [[SQLITE_CONFIG_LOOKASIDE]]
    SQLITE_CONFIG_LOOKASIDE
    +**
    ^(This option takes two arguments that determine the default +** memory allocation for the lookaside memory allocator on each +** [database connection]. The first argument is the +** size of each lookaside buffer slot and the second is the number of +** slots allocated to each database connection.)^ ^(This option sets the +** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] +** verb to [sqlite3_db_config()] can be used to change the lookaside +** configuration on individual connections.)^
    +** +** [[SQLITE_CONFIG_PCACHE2]]
    SQLITE_CONFIG_PCACHE2
    +**
    ^(This option takes a single argument which is a pointer to +** an [sqlite3_pcache_methods2] object. This object specifies the interface +** to a custom page cache implementation.)^ ^SQLite makes a copy of the +** object and uses it for page cache memory allocations.
    +** +** [[SQLITE_CONFIG_GETPCACHE2]]
    SQLITE_CONFIG_GETPCACHE2
    +**
    ^(This option takes a single argument which is a pointer to an +** [sqlite3_pcache_methods2] object. SQLite copies of the current +** page cache implementation into that object.)^
    +** +** [[SQLITE_CONFIG_LOG]]
    SQLITE_CONFIG_LOG
    +**
    The SQLITE_CONFIG_LOG option is used to configure the SQLite +** global [error log]. +** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a +** function with a call signature of void(*)(void*,int,const char*), +** and a pointer to void. ^If the function pointer is not NULL, it is +** invoked by [sqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is +** passed through as the first parameter to the application-defined logger +** function whenever that function is invoked. ^The second parameter to +** the logger function is a copy of the first parameter to the corresponding +** [sqlite3_log()] call and is intended to be a [result code] or an +** [extended result code]. ^The third parameter passed to the logger is +** log message after formatting via [sqlite3_snprintf()]. +** The SQLite logging interface is not reentrant; the logger function +** supplied by the application must not invoke any SQLite interface. +** In a multi-threaded application, the application-defined logger +** function must be threadsafe.
    +** +** [[SQLITE_CONFIG_URI]]
    SQLITE_CONFIG_URI +**
    ^(This option takes a single argument of type int. If non-zero, then +** URI handling is globally enabled. If the parameter is zero, then URI handling +** is globally disabled.)^ ^If URI handling is globally enabled, all filenames +** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or +** specified as part of [ATTACH] commands are interpreted as URIs, regardless +** of whether or not the [SQLITE_OPEN_URI] flag is set when the database +** connection is opened. ^If it is globally disabled, filenames are +** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the +** database connection is opened. ^(By default, URI handling is globally +** disabled. The default value may be changed by compiling with the +** [SQLITE_USE_URI] symbol defined.)^ +** +** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
    SQLITE_CONFIG_COVERING_INDEX_SCAN +**
    ^This option takes a single integer argument which is interpreted as +** a boolean in order to enable or disable the use of covering indices for +** full table scans in the query optimizer. ^The default setting is determined +** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" +** if that compile-time option is omitted. +** The ability to disable the use of covering indices for full table scans +** is because some incorrectly coded legacy applications might malfunction +** when the optimization is enabled. Providing the ability to +** disable the optimization allows the older, buggy application code to work +** without change even with newer versions of SQLite. +** +** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] +**
    SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE +**
    These options are obsolete and should not be used by new code. +** They are retained for backwards compatibility but are now no-ops. +**
    +** +** [[SQLITE_CONFIG_SQLLOG]] +**
    SQLITE_CONFIG_SQLLOG +**
    This option is only available if sqlite is compiled with the +** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should +** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). +** The second should be of type (void*). The callback is invoked by the library +** in three separate circumstances, identified by the value passed as the +** fourth parameter. If the fourth parameter is 0, then the database connection +** passed as the second argument has just been opened. The third argument +** points to a buffer containing the name of the main database file. If the +** fourth parameter is 1, then the SQL statement that the third parameter +** points to has just been executed. Or, if the fourth parameter is 2, then +** the connection being passed as the second parameter is being closed. The +** third parameter is passed NULL In this case. An example of using this +** configuration option can be seen in the "test_sqllog.c" source file in +** the canonical SQLite source tree.
    +** +** [[SQLITE_CONFIG_MMAP_SIZE]] +**
    SQLITE_CONFIG_MMAP_SIZE +**
    ^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values +** that are the default mmap size limit (the default setting for +** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. +** ^The default setting can be overridden by each database connection using +** either the [PRAGMA mmap_size] command, or by using the +** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size +** cannot be changed at run-time. Nor may the maximum allowed mmap size +** exceed the compile-time maximum mmap size set by the +** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ +** ^If either argument to this option is negative, then that argument is +** changed to its compile-time default. +**
    +*/ +#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ +#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ +#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ +#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ +#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ +#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ +#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ +#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ +#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ +#define SQLITE_CONFIG_PCACHE 14 /* no-op */ +#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ +#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ +#define SQLITE_CONFIG_URI 17 /* int */ +#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ +#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ +#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ + +/* +** CAPI3REF: Database Connection Configuration Options +** +** These constants are the available integer configuration options that +** can be passed as the second argument to the [sqlite3_db_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_db_config()] to make sure that +** the call worked. ^The [sqlite3_db_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
    +**
    SQLITE_DBCONFIG_LOOKASIDE
    +**
    ^This option takes three additional arguments that determine the +** [lookaside memory allocator] configuration for the [database connection]. +** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** pointer to a memory buffer to use for lookaside memory. +** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb +** may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the +** size of each lookaside buffer slot. ^The third argument is the number of +** slots. The size of the buffer in the first argument must be greater than +** or equal to the product of the second and third arguments. The buffer +** must be aligned to an 8-byte boundary. ^If the second argument to +** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally +** rounded down to the next smaller multiple of 8. ^(The lookaside memory +** configuration for a database connection can only be changed when that +** connection is not currently using lookaside memory, or in other words +** when the "current value" returned by +** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. +** Any attempt to change the lookaside memory configuration when lookaside +** memory is in use leaves the configuration unchanged and returns +** [SQLITE_BUSY].)^
    +** +**
    SQLITE_DBCONFIG_ENABLE_FKEY
    +**
    ^This option is used to enable or disable the enforcement of +** [foreign key constraints]. There should be two additional arguments. +** The first argument is an integer which is 0 to disable FK enforcement, +** positive to enable FK enforcement or negative to leave FK enforcement +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether FK enforcement is off or on +** following this call. The second parameter may be a NULL pointer, in +** which case the FK enforcement setting is not reported back.
    +** +**
    SQLITE_DBCONFIG_ENABLE_TRIGGER
    +**
    ^This option is used to enable or disable [CREATE TRIGGER | triggers]. +** There should be two additional arguments. +** The first argument is an integer which is 0 to disable triggers, +** positive to enable triggers or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether triggers are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the trigger setting is not reported back.
    +** +**
    +*/ +#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ +#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ + + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes +** +** ^The sqlite3_extended_result_codes() routine enables or disables the +** [extended result codes] feature of SQLite. ^The extended result +** codes are disabled by default for historical compatibility. +*/ +int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid +** +** ^Each entry in an SQLite table has a unique 64-bit signed +** integer key called the [ROWID | "rowid"]. ^The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. ^If +** the table has a column of type [INTEGER PRIMARY KEY] then that column +** is another alias for the rowid. +** +** ^This routine returns the [rowid] of the most recent +** successful [INSERT] into the database from the [database connection] +** in the first argument. ^As of SQLite version 3.7.7, this routines +** records the last insert rowid of both ordinary tables and [virtual tables]. +** ^If no successful [INSERT]s +** have ever occurred on that database connection, zero is returned. +** +** ^(If an [INSERT] occurs within a trigger or within a [virtual table] +** method, then this routine will return the [rowid] of the inserted +** row as long as the trigger or virtual table method is running. +** But once the trigger or virtual table method ends, the value returned +** by this routine reverts to what it was before the trigger or virtual +** table method began.)^ +** +** ^An [INSERT] that fails due to a constraint violation is not a +** successful [INSERT] and does not change the value returned by this +** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. ^(When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface.)^ +** +** ^For the purposes of this routine, an [INSERT] is considered to +** be successful even if it is subsequently rolled back. +** +** This function is accessible to SQL statements via the +** [last_insert_rowid() SQL function]. +** +** If a separate thread performs a new [INSERT] on the same +** database connection while the [sqlite3_last_insert_rowid()] +** function is running and thus changes the last insert [rowid], +** then the value returned by [sqlite3_last_insert_rowid()] is +** unpredictable and might not equal either the old or the new +** last insert [rowid]. +*/ +sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified +** +** ^This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the [database connection] specified by the first parameter. +** ^(Only changes that are directly specified by the [INSERT], [UPDATE], +** or [DELETE] statement are counted. Auxiliary changes caused by +** triggers or [foreign key actions] are not counted.)^ Use the +** [sqlite3_total_changes()] function to find the total number of changes +** including changes caused by triggers and foreign key actions. +** +** ^Changes to a view that are simulated by an [INSTEAD OF trigger] +** are not counted. Only real table changes are counted. +** +** ^(A "row change" is a change to a single row of a single table +** caused by an INSERT, DELETE, or UPDATE statement. Rows that +** are changed as side effects of [REPLACE] constraint resolution, +** rollback, ABORT processing, [DROP TABLE], or by any other +** mechanisms do not count as direct row changes.)^ +** +** A "trigger context" is a scope of execution that begins and +** ends with the script of a [CREATE TRIGGER | trigger]. +** Most SQL statements are +** evaluated outside of any trigger. This is the "top level" +** trigger context. If a trigger fires from the top level, a +** new trigger context is entered for the duration of that one +** trigger. Subtriggers create subcontexts for their duration. +** +** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does +** not create a new trigger context. +** +** ^This function returns the number of direct row changes in the +** most recent INSERT, UPDATE, or DELETE statement within the same +** trigger context. +** +** ^Thus, when called from the top level, this function returns the +** number of changes in the most recent INSERT, UPDATE, or DELETE +** that also occurred at the top level. ^(Within the body of a trigger, +** the sqlite3_changes() interface can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** However, the number returned does not include changes +** caused by subtriggers since those have their own context.)^ +** +** See also the [sqlite3_total_changes()] interface, the +** [count_changes pragma], and the [changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and not meaningful. +*/ +int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified +** +** ^This function returns the number of row changes caused by [INSERT], +** [UPDATE] or [DELETE] statements since the [database connection] was opened. +** ^(The count returned by sqlite3_total_changes() includes all changes +** from all [CREATE TRIGGER | trigger] contexts and changes made by +** [foreign key actions]. However, +** the count does not include changes used to implement [REPLACE] constraints, +** do rollbacks or ABORT processing, or [DROP TABLE] processing. The +** count does not include rows of views that fire an [INSTEAD OF trigger], +** though if the INSTEAD OF trigger makes changes of its own, those changes +** are counted.)^ +** ^The sqlite3_total_changes() function counts the changes as soon as +** the statement that makes them is completed (when the statement handle +** is passed to [sqlite3_reset()] or [sqlite3_finalize()]). +** +** See also the [sqlite3_changes()] interface, the +** [count_changes pragma], and the [total_changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and not meaningful. +*/ +int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query +** +** ^This function causes any pending database operation to abort and +** return at its earliest opportunity. This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** ^It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. But it +** is not safe to call this routine with a [database connection] that +** is closed or might close before sqlite3_interrupt() returns. +** +** ^If an SQL operation is very nearly finished at the time when +** sqlite3_interrupt() is called, then it might not have an opportunity +** to be interrupted and might continue to completion. +** +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE +** that is inside an explicit transaction, then the entire transaction +** will be rolled back automatically. +** +** ^The sqlite3_interrupt(D) call is in effect until all currently running +** SQL statements on [database connection] D complete. ^Any new SQL statements +** that are started after the sqlite3_interrupt() call and before the +** running statements reaches zero are interrupted as if they had been +** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the running statement count reaches zero are +** not effected by the sqlite3_interrupt(). +** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** SQL statements is a no-op and has no effect on SQL statements +** that are started after the sqlite3_interrupt() call returns. +** +** If the database connection closes while [sqlite3_interrupt()] +** is running then bad things will likely happen. +*/ +void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete +** +** These routines are useful during command-line input to determine if the +** currently entered text seems to form a complete SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. ^These routines return 1 if the input string +** appears to be a complete SQL statement. ^A statement is judged to be +** complete if it ends with a semicolon token and is not a prefix of a +** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within +** string literals or quoted identifier names or comments are not +** independent tokens (they are part of the token in which they are +** embedded) and thus do not count as a statement terminator. ^Whitespace +** and comments that follow the final semicolon are ignored. +** +** ^These routines return 0 if the statement is incomplete. ^If a +** memory allocation fails, then SQLITE_NOMEM is returned. +** +** ^These routines do not parse the SQL statements thus +** will not detect syntactically incorrect SQL. +** +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked +** automatically by sqlite3_complete16(). If that initialization fails, +** then the return value from sqlite3_complete16() will be non-zero +** regardless of whether or not the input SQL is complete.)^ +** +** The input to [sqlite3_complete()] must be a zero-terminated +** UTF-8 string. +** +** The input to [sqlite3_complete16()] must be a zero-terminated +** UTF-16 string in native byte order. +*/ +int sqlite3_complete(const char *sql); +int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors +** +** ^This routine sets a callback function that might be invoked whenever +** an attempt is made to open a database table that another thread +** or process has locked. +** +** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. ^If the busy callback +** is not NULL, then the callback might be invoked with two arguments. +** +** ^The first argument to the busy handler is a copy of the void* pointer which +** is the third argument to sqlite3_busy_handler(). ^The second argument to +** the busy handler callback is the number of times that the busy handler has +** been invoked for this locking event. ^If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** ^If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that it will be invoked +** when there is lock contention. ^If SQLite determines that invoking the busy +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** ^The default busy callback is NULL. +** +** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. ^If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion +** forces an automatic rollback of the changes. See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** ^(There can only be a single busy handler defined for each +** [database connection]. Setting a new busy handler clears any +** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** will also set or clear the busy handler. +** +** The busy callback should not take any actions which modify the +** database connection that invoked the busy handler. Any such actions +** result in undefined behavior. +** +** A busy handler must not close the database connection +** or [prepared statement] that invoked the busy handler. +*/ +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout +** +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** for a specified amount of time when a table is locked. ^The handler +** will sleep multiple times until at least "ms" milliseconds of sleeping +** have accumulated. ^After at least "ms" milliseconds of sleeping, +** the handler returns 0 which causes [sqlite3_step()] to return +** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** ^Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** ^(There can only be a single busy handler for a particular +** [database connection] any any given moment. If another busy handler +** was defined (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared.)^ +*/ +int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries +** +** This is a legacy interface that is preserved for backwards compatibility. +** Use of this interface is not recommended. +** +** Definition: A result table is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** The table conceptually has a number of rows and columns. But +** these numbers are not part of the result table itself. These +** numbers are obtained separately. Let N be the number of rows +** and M be the number of columns. +** +** A result table is an array of pointers to zero-terminated UTF-8 strings. +** There are (N+1)*M elements in the array. The first M pointers point +** to zero-terminated strings that contain the names of the columns. +** The remaining entries all point to query results. NULL values result +** in NULL pointers. All other values are in their UTF-8 zero-terminated +** string representation as returned by [sqlite3_column_text()]. +** +** A result table might consist of one or more memory allocations. +** It is not safe to pass a result table directly to [sqlite3_free()]. +** A result table should be deallocated using [sqlite3_free_table()]. +** +** ^(As an example of the result table format, suppose a query result +** is as follows: +** +**
    +**        Name        | Age
    +**        -----------------------
    +**        Alice       | 43
    +**        Bob         | 28
    +**        Cindy       | 21
    +** 
    +** +** There are two column (M==2) and three rows (N==3). Thus the +** result table has 8 entries. Suppose the result table is stored +** in an array names azResult. Then azResult holds this content: +** +**
    +**        azResult[0] = "Name";
    +**        azResult[1] = "Age";
    +**        azResult[2] = "Alice";
    +**        azResult[3] = "43";
    +**        azResult[4] = "Bob";
    +**        azResult[5] = "28";
    +**        azResult[6] = "Cindy";
    +**        azResult[7] = "21";
    +** 
    )^ +** +** ^The sqlite3_get_table() function evaluates one or more +** semicolon-separated SQL statements in the zero-terminated UTF-8 +** string of its 2nd parameter and returns a result table to the +** pointer given in its 3rd parameter. +** +** After the application has finished with the result from sqlite3_get_table(), +** it must pass the result table pointer to sqlite3_free_table() in order to +** release the memory that was malloced. Because of the way the +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling +** function must not try to call [sqlite3_free()] directly. Only +** [sqlite3_free_table()] is able to release the memory properly and safely. +** +** The sqlite3_get_table() interface is implemented as a wrapper around +** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** to any internal data structures of SQLite. It uses only the public +** interface defined here. As a consequence, errors that occur in the +** wrapper layer outside of the internal [sqlite3_exec()] call are not +** reflected in subsequent calls to [sqlite3_errcode()] or +** [sqlite3_errmsg()]. +*/ +int sqlite3_get_table( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + char ***pazResult, /* Results of the query */ + int *pnRow, /* Number of result rows written here */ + int *pnColumn, /* Number of result columns written here */ + char **pzErrmsg /* Error msg written here */ +); +void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions +** +** These routines are work-alikes of the "printf()" family of functions +** from the standard C library. +** +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** The strings returned by these two routines should be +** released by [sqlite3_free()]. ^Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. Note that the order of the +** first two parameters is reversed from snprintf().)^ This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. ^(Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer.)^ We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. ^The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. So the longest string that can be completely +** written will be n-1 characters. +** +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf() formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** ^(The %q option works like %s in that it substitutes a nul-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal.)^ By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, assume the string variable zText contains text as follows: +** +**
    +**  char *zText = "It's a happy day!";
    +** 
    +** +** One can use this text in an SQL statement as follows: +** +**
    +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
    +**  sqlite3_exec(db, zSQL, 0, 0, 0);
    +**  sqlite3_free(zSQL);
    +** 
    +** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
    +**  INSERT INTO table1 VALUES('It''s a happy day!')
    +** 
    +** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
    +**  INSERT INTO table1 VALUES('It's a happy day!');
    +** 
    +** +** This second example is an SQL syntax error. As a general rule you should +** always use %q instead of %s when inserting text into a string literal. +** +** ^(The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Additionally, if the parameter in the +** argument list is a NULL pointer, %Q substitutes the text "NULL" (without +** single quotes).)^ So, for example, one could say: +** +**
    +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
    +**  sqlite3_exec(db, zSQL, 0, 0, 0);
    +**  sqlite3_free(zSQL);
    +** 
    +** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** ^(The "%z" formatting option works like "%s" but with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string.)^ +*/ +char *sqlite3_mprintf(const char*,...); +char *sqlite3_vmprintf(const char*, va_list); +char *sqlite3_snprintf(int,char*,const char*, ...); +char *sqlite3_vsnprintf(int,char*,const char*, va_list); + +/* +** CAPI3REF: Memory Allocation Subsystem +** +** The SQLite core uses these three routines for all of its own +** internal memory allocation needs. "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** Windows VFS uses native malloc() and free() for some operations. +** +** ^The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** ^If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. ^If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** ^Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. ^The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** +** ^(The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter.)^ ^ If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** ^If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** ^sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** ^If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** ^If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** ^The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary, or to a +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time +** option is used. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be used. +** +** Prior to SQLite version 3.7.10, the Windows OS interface layer called +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular Windows +** installation. Memory allocation errors were detected, but +** they were reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +** +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else pointers obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** not yet been released. +** +** The application must not read or write any part of +** a block of memory after it has been released using +** [sqlite3_free()] or [sqlite3_realloc()]. +*/ +void *sqlite3_malloc(int); +void *sqlite3_realloc(void*, int); +void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** routines, which form the built-in memory allocation subsystem. +** +** ^The [sqlite3_memory_used()] routine returns the number of bytes +** of memory currently outstanding (malloced but not freed). +** ^The [sqlite3_memory_highwater()] routine returns the maximum +** value of [sqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [sqlite3_memory_used()] and +** [sqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [sqlite3_malloc()], +** but not overhead added by the any underlying system library +** routines that [sqlite3_malloc()] may call. +** +** ^The memory high-water mark is reset to the current value of +** [sqlite3_memory_used()] if and only if the parameter to +** [sqlite3_memory_highwater()] is true. ^The value returned +** by [sqlite3_memory_highwater(1)] is the high-water mark +** prior to the reset. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Pseudo-Random Number Generator +** +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to +** select random [ROWID | ROWIDs] when inserting new records into a table that +** already uses the largest possible [ROWID]. The PRNG is also used for +** the build-in random() and randomblob() SQL functions. This interface allows +** applications to access the same PRNG for other purposes. +** +** ^A call to this routine stores N bytes of randomness into buffer P. +** +** ^The first time this routine is invoked (either internally or by +** the application) the PRNG is seeded using randomness obtained +** from the xRandomness method of the default [sqlite3_vfs] object. +** ^On all subsequent invocations, the pseudo-randomness is generated +** internally and without recourse to the [sqlite3_vfs] xRandomness +** method. +*/ +void sqlite3_randomness(int N, void *P); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks +** +** ^This routine registers an authorizer callback with a particular +** [database connection], supplied in the first argument. +** ^The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. ^The authorizer callback should +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. ^If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. ^When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer will fail with an error message explaining that +** access is denied. +** +** ^The first parameter to the authorizer callback is a copy of the third +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** to the callback is an integer [SQLITE_COPY | action code] that specifies +** the particular action to be authorized. ^The third through sixth parameters +** to the callback are zero-terminated strings that contain additional +** details about the action to be authorized. +** +** ^If the action code is [SQLITE_READ] +** and the callback returns [SQLITE_IGNORE] then the +** [prepared statement] statement is constructed to substitute +** a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] +** return can be used to deny an untrusted user access to individual +** columns of a table. +** ^If the action code is [SQLITE_DELETE] and the callback returns +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the +** [truncate optimization] is disabled and all rows are deleted individually. +** +** An authorizer is used when [sqlite3_prepare | preparing] +** SQL statements from an untrusted source, to ensure that the SQL statements +** do not try to access data they are not allowed to see, or that they do not +** try to execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being [sqlite3_prepare | prepared] that +** disallows everything except [SELECT] statements. +** +** Applications that need to process SQL from untrusted sources +** might also consider lowering resource limits using [sqlite3_limit()] +** and limiting database size using the [max_page_count] [PRAGMA] +** in addition to using an authorizer. +** +** ^(Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call.)^ ^Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. +** +** The authorizer callback must not do anything that will modify +** the database connection that invoked the authorizer callback. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [sqlite3_step()] due to a +** schema change. Hence, the application should ensure that the +** correct authorizer callback remains in place during the [sqlite3_step()]. +** +** ^Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [sqlite3_step()], unless +** as stated in the previous paragraph, sqlite3_step() invokes +** sqlite3_prepare_v2() to reprepare a statement after a schema change. +*/ +int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +** +** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code] +** from the [sqlite3_vtab_on_conflict()] interface. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorize certain SQL statement actions. The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. +** +** These action code values signify what kind of operation is to be +** authorized. The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. ^(The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* Operation NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* NULL Function Name */ +#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** ^The callback function registered by sqlite3_trace() is invoked at +** various times when an SQL statement is being run by [sqlite3_step()]. +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** SQL statement text as the statement first begins executing. +** ^(Additional sqlite3_trace() callbacks might occur +** as each triggered subprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger.)^ +** +** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit +** the length of [bound parameter] expansion in the output of sqlite3_trace(). +** +** ^The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. ^The profile callback contains +** the original statement text and an estimate of wall-clock time +** of how long that statement took to run. ^The profile callback +** time is in units of nanoseconds, however the current implementation +** is only capable of millisecond resolution so the six least significant +** digits in the time are meaningless. Future versions of SQLite +** might provide greater resolution on the profiler callback. The +** sqlite3_profile() function is considered experimental and is +** subject to change in future versions of SQLite. +*/ +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks +** +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** function X to be invoked periodically during long running calls to +** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for +** database connection D. An example use for this +** interface is to keep a GUI updated during a large query. +** +** ^The parameter P is passed through as the only parameter to the +** callback function X. ^The parameter N is the approximate number of +** [virtual machine instructions] that are evaluated between successive +** invocations of the callback X. ^If N is less than one then the progress +** handler is disabled. +** +** ^Only a single progress handler may be defined at one time per +** [database connection]; setting a new progress handler cancels the +** old one. ^Setting parameter X to NULL disables the progress handler. +** ^The progress handler is also disabled by setting N to a value less +** than 1. +** +** ^If the progress callback returns non-zero, the operation is +** interrupted. This feature can be used to implement a +** "Cancel" button on a GUI progress dialog box. +** +** The progress handler callback must not do anything that will modify +** the database connection that invoked the progress handler. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +*/ +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection +** +** ^These routines open an SQLite database file as specified by the +** filename argument. ^The filename argument is interpreted as UTF-8 for +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte +** order for sqlite3_open16(). ^(A [database connection] handle is usually +** returned in *ppDb, even if an error occurs. The only exception is that +** if SQLite is unable to allocate memory to hold the [sqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** object.)^ ^(If the database is opened (and/or created) successfully, then +** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error following a failure of any +** of the sqlite3_open() routines. +** +** ^The default encoding for the database will be UTF-8 if +** sqlite3_open() or sqlite3_open_v2() is called and +** UTF-16 in the native byte order if sqlite3_open16() is used. +** +** Whether or not an error occurs when it is opened, resources +** associated with the [database connection] handle should be released by +** passing it to [sqlite3_close()] when it is no longer required. +** +** The sqlite3_open_v2() interface works like sqlite3_open() +** except that it accepts two additional parameters for additional control +** over the new database connection. ^(The flags parameter to +** sqlite3_open_v2() can take one of +** the following three values, optionally combined with the +** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], +** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ +** +**
    +** ^(
    [SQLITE_OPEN_READONLY]
    +**
    The database is opened in read-only mode. If the database does not +** already exist, an error is returned.
    )^ +** +** ^(
    [SQLITE_OPEN_READWRITE]
    +**
    The database is opened for reading and writing if possible, or reading +** only if the file is write protected by the operating system. In either +** case the database must already exist, otherwise an error is returned.
    )^ +** +** ^(
    [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
    +**
    The database is opened for reading and writing, and is created if +** it does not already exist. This is the behavior that is always used for +** sqlite3_open() and sqlite3_open16().
    )^ +**
    +** +** If the 3rd parameter to sqlite3_open_v2() is not one of the +** combinations shown above optionally combined with other +** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] +** then the behavior is undefined. +** +** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection +** opens in the multi-thread [threading mode] as long as the single-thread +** mode has not been set at compile-time or start-time. ^If the +** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens +** in the serialized [threading mode] unless single-thread was +** previously selected at compile-time or start-time. +** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be +** eligible to use [shared cache mode], regardless of whether or not shared +** cache is enabled using [sqlite3_enable_shared_cache()]. ^The +** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not +** participate in [shared cache mode] even if it is enabled. +** +** ^The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system interface that +** the new database connection should use. ^If the fourth parameter is +** a NULL pointer then the default [sqlite3_vfs] object is used. +** +** ^If the filename is ":memory:", then a private, temporary in-memory database +** is created for the connection. ^This in-memory database will vanish when +** the database connection is closed. Future versions of SQLite might +** make use of additional special filenames that begin with the ":" character. +** It is recommended that when a database filename actually does begin with +** a ":" character you should prefix the filename with a pathname such as +** "./" to avoid ambiguity. +** +** ^If the filename is an empty string, then a private, temporary +** on-disk database will be created. ^This private database will be +** automatically deleted as soon as the database connection is closed. +** +** [[URI filenames in sqlite3_open()]]

    URI Filenames

    +** +** ^If [URI filename] interpretation is enabled, and the filename argument +** begins with "file:", then the filename is interpreted as a URI. ^URI +** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is +** set in the fourth argument to sqlite3_open_v2(), or if it has +** been enabled globally using the [SQLITE_CONFIG_URI] option with the +** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. +** As of SQLite version 3.7.7, URI filename interpretation is turned off +** by default, but future releases of SQLite might enable URI filename +** interpretation by default. See "[URI filenames]" for additional +** information. +** +** URI filenames are parsed according to RFC 3986. ^If the URI contains an +** authority, then it must be either an empty string or the string +** "localhost". ^If the authority is not an empty string or "localhost", an +** error is returned to the caller. ^The fragment component of a URI, if +** present, is ignored. +** +** ^SQLite uses the path component of the URI as the name of the disk file +** which contains the database. ^If the path begins with a '/' character, +** then it is interpreted as an absolute path. ^If the path does not begin +** with a '/' (meaning that the authority section is omitted from the URI) +** then the path is interpreted as a relative path. +** ^On windows, the first component of an absolute path +** is a drive specification (e.g. "C:"). +** +** [[core URI query parameters]] +** The query component of a URI may contain parameters that are interpreted +** either by SQLite itself, or by a [VFS | custom VFS implementation]. +** SQLite interprets the following three query parameters: +** +**
      +**
    • vfs: ^The "vfs" parameter may be used to specify the name of +** a VFS object that provides the operating system interface that should +** be used to access the database file on disk. ^If this option is set to +** an empty string the default VFS object is used. ^Specifying an unknown +** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is +** present, then the VFS specified by the option takes precedence over +** the value passed as the fourth parameter to sqlite3_open_v2(). +** +**
    • mode: ^(The mode parameter may be set to either "ro", "rw", +** "rwc", or "memory". Attempting to set it to any other value is +** an error)^. +** ^If "ro" is specified, then the database is opened for read-only +** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the +** third argument to sqlite3_open_v2(). ^If the mode option is set to +** "rw", then the database is opened for read-write (but not create) +** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had +** been set. ^Value "rwc" is equivalent to setting both +** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is +** set to "memory" then a pure [in-memory database] that never reads +** or writes from disk is used. ^It is an error to specify a value for +** the mode parameter that is less restrictive than that specified by +** the flags passed in the third parameter to sqlite3_open_v2(). +** +**
    • cache: ^The cache parameter may be set to either "shared" or +** "private". ^Setting it to "shared" is equivalent to setting the +** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to +** sqlite3_open_v2(). ^Setting the cache parameter to "private" is +** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. +** ^If sqlite3_open_v2() is used and the "cache" parameter is present in +** a URI filename, its value overrides any behavior requested by setting +** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. +**
    +** +** ^Specifying an unknown parameter in the query component of a URI is not an +** error. Future versions of SQLite might understand additional query +** parameters. See "[query parameters with special meaning to SQLite]" for +** additional information. +** +** [[URI filename examples]]

    URI filename examples

    +** +**
    +**
    URI filenames Results +**
    file:data.db +** Open the file "data.db" in the current directory. +**
    file:/home/fred/data.db
    +** file:///home/fred/data.db
    +** file://localhost/home/fred/data.db
    +** Open the database file "/home/fred/data.db". +**
    file://darkstar/home/fred/data.db +** An error. "darkstar" is not a recognized authority. +**
    +** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db +** Windows only: Open the file "data.db" on fred's desktop on drive +** C:. Note that the %20 escaping in this example is not strictly +** necessary - space characters can be used literally +** in URI filenames. +**
    file:data.db?mode=ro&cache=private +** Open file "data.db" in the current directory for read-only access. +** Regardless of whether or not shared-cache mode is enabled by +** default, use a private cache. +**
    file:/home/fred/data.db?vfs=unix-nolock +** Open file "/home/fred/data.db". Use the special VFS "unix-nolock". +**
    file:data.db?mode=readonly +** An error. "readonly" is not a valid option for the "mode" parameter. +**
    +** +** ^URI hexadecimal escape sequences (%HH) are supported within the path and +** query components of a URI. A hexadecimal escape sequence consists of a +** percent sign - "%" - followed by exactly two hexadecimal digits +** specifying an octet value. ^Before the path or query components of a +** URI filename are interpreted, they are encoded using UTF-8 and all +** hexadecimal escape sequences replaced by a single byte containing the +** corresponding octet. If this process generates an invalid UTF-8 encoding, +** the results are undefined. +** +** Note to Windows users: The encoding used for the filename argument +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** sqlite3_open() or sqlite3_open_v2(). +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various +** features that require the use of temporary files may fail. +** +** See also: [sqlite3_temp_directory] +*/ +int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Obtain Values For URI Parameters +** +** These are utility routines, useful to VFS implementations, that check +** to see if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of that query parameter. +** +** If F is the database filename pointer passed into the xOpen() method of +** a VFS implementation when the flags parameter to xOpen() has one or +** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and +** P is the name of the query parameter, then +** sqlite3_uri_parameter(F,P) returns the value of the P +** parameter if it exists or a NULL pointer if P does not appear as a +** query parameter on F. If P is a query parameter of F +** has no explicit value, then sqlite3_uri_parameter(F,P) returns +** a pointer to an empty string. +** +** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean +** parameter and returns true (1) or false (0) according to the value +** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the +** value of query parameter P is one of "yes", "true", or "on" in any +** case or if the value begins with a non-zero number. The +** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of +** query parameter P is one of "no", "false", or "off" in any case or +** if the value begins with a numeric zero. If P is not a query +** parameter on F or if the value of P is does not match any of the +** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). +** +** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a +** 64-bit signed integer and returns that integer, or D if P does not +** exist. If the value of P is something other than an integer, then +** zero is returned. +** +** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and +** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and +** is not a database file pathname pointer that SQLite passed into the xOpen +** VFS method, then the behavior of this routine is undefined and probably +** undesirable. +*/ +const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); +int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); +sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); + + +/* +** CAPI3REF: Error Codes And Messages +** +** ^The sqlite3_errcode() interface returns the numeric [result code] or +** [extended result code] for the most recent failed sqlite3_* API call +** associated with a [database connection]. If a prior API call failed +** but the most recent API call succeeded, the return value from +** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode() +** interface is the same except that it always returns the +** [extended result code] even when extended result codes are +** disabled. +** +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF-8 or UTF-16 respectively. +** ^(Memory to hold the error message string is managed internally. +** The application does not need to worry about freeing the result. +** However, the error string might be overwritten or deallocated by +** subsequent calls to other SQLite interface functions.)^ +** +** ^The sqlite3_errstr() interface returns the English-language text +** that describes the [result code], as UTF-8. +** ^(Memory to hold the error message string is managed internally +** and must not be freed by the application)^. +** +** When the serialized [threading mode] is in use, it might be the +** case that a second error occurs on a separate thread in between +** the time of the first error and the call to these interfaces. +** When that happens, the second error will be reported since these +** interfaces always report the most recent result. To avoid +** this, each thread can obtain exclusive use of the [database connection] D +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** all calls to the interfaces listed here are completed. +** +** If an interface fails with SQLITE_MISUSE, that means the interface +** was invoked incorrectly by the application. In that case, the +** error code and message may or may not be set. +*/ +int sqlite3_errcode(sqlite3 *db); +int sqlite3_extended_errcode(sqlite3 *db); +const char *sqlite3_errmsg(sqlite3*); +const void *sqlite3_errmsg16(sqlite3*); +const char *sqlite3_errstr(int); + +/* +** CAPI3REF: SQL Statement Object +** KEYWORDS: {prepared statement} {prepared statements} +** +** An instance of this object represents a single SQL statement. +** This object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
      +**
    1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
    2. Bind values to [host parameters] using the sqlite3_bind_*() +** interfaces. +**
    3. Run the SQL by calling [sqlite3_step()] one or more times. +**
    4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
    5. Destroy the object using [sqlite3_finalize()]. +**
    +** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Run-time Limits +** +** ^(This interface allows the size of various constructs to be limited +** on a connection by connection basis. The first parameter is the +** [database connection] whose limit is to be set or queried. The +** second parameter is one of the [limit categories] that define a +** class of constructs to be size limited. The third parameter is the +** new limit for that construct.)^ +** +** ^If the new limit is a negative number, the limit is unchanged. +** ^(For each limit category SQLITE_LIMIT_NAME there is a +** [limits | hard upper bound] +** set at compile-time by a C preprocessor macro called +** [limits | SQLITE_MAX_NAME]. +** (The "_LIMIT_" in the name is changed to "_MAX_".))^ +** ^Attempts to increase a limit above its hard upper bound are +** silently truncated to the hard upper bound. +** +** ^Regardless of whether or not the limit was changed, the +** [sqlite3_limit()] interface returns the prior value of the limit. +** ^Hence, to find the current value of a limit without changing it, +** simply invoke this interface with the third parameter set to -1. +** +** Run-time limits are intended for use in applications that manage +** both their own internal database and also databases that are controlled +** by untrusted external sources. An example application might be a +** web browser that has its own databases for storing history and +** separate databases controlled by JavaScript applications downloaded +** off the Internet. The internal databases can be given the +** large, default limits. Databases managed by external sources can +** be given much smaller limits designed to prevent a denial of service +** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** interface to further control untrusted SQL. The size of the database +** created by an untrusted script can be contained using the +** [max_page_count] [PRAGMA]. +** +** New run-time limit categories may be added in future releases. +*/ +int sqlite3_limit(sqlite3*, int id, int newVal); + +/* +** CAPI3REF: Run-Time Limit Categories +** KEYWORDS: {limit category} {*limit categories} +** +** These constants define various performance limits +** that can be lowered at run-time using [sqlite3_limit()]. +** The synopsis of the meanings of the various limits is shown below. +** Additional information is available at [limits | Limits in SQLite]. +** +**
    +** [[SQLITE_LIMIT_LENGTH]] ^(
    SQLITE_LIMIT_LENGTH
    +**
    The maximum size of any string or BLOB or table row, in bytes.
    )^ +** +** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
    SQLITE_LIMIT_SQL_LENGTH
    +**
    The maximum length of an SQL statement, in bytes.
    )^ +** +** [[SQLITE_LIMIT_COLUMN]] ^(
    SQLITE_LIMIT_COLUMN
    +**
    The maximum number of columns in a table definition or in the +** result set of a [SELECT] or the maximum number of columns in an index +** or in an ORDER BY or GROUP BY clause.
    )^ +** +** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
    SQLITE_LIMIT_EXPR_DEPTH
    +**
    The maximum depth of the parse tree on any expression.
    )^ +** +** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
    SQLITE_LIMIT_COMPOUND_SELECT
    +**
    The maximum number of terms in a compound SELECT statement.
    )^ +** +** [[SQLITE_LIMIT_VDBE_OP]] ^(
    SQLITE_LIMIT_VDBE_OP
    +**
    The maximum number of instructions in a virtual machine program +** used to implement an SQL statement. This limit is not currently +** enforced, though that might be added in some future release of +** SQLite.
    )^ +** +** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
    SQLITE_LIMIT_FUNCTION_ARG
    +**
    The maximum number of arguments on a function.
    )^ +** +** [[SQLITE_LIMIT_ATTACHED]] ^(
    SQLITE_LIMIT_ATTACHED
    +**
    The maximum number of [ATTACH | attached databases].)^
    +** +** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] +** ^(
    SQLITE_LIMIT_LIKE_PATTERN_LENGTH
    +**
    The maximum length of the pattern argument to the [LIKE] or +** [GLOB] operators.
    )^ +** +** [[SQLITE_LIMIT_VARIABLE_NUMBER]] +** ^(
    SQLITE_LIMIT_VARIABLE_NUMBER
    +**
    The maximum index number of any [parameter] in an SQL statement.)^ +** +** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
    SQLITE_LIMIT_TRIGGER_DEPTH
    +**
    The maximum depth of recursion for triggers.
    )^ +**
    +*/ +#define SQLITE_LIMIT_LENGTH 0 +#define SQLITE_LIMIT_SQL_LENGTH 1 +#define SQLITE_LIMIT_COLUMN 2 +#define SQLITE_LIMIT_EXPR_DEPTH 3 +#define SQLITE_LIMIT_COMPOUND_SELECT 4 +#define SQLITE_LIMIT_VDBE_OP 5 +#define SQLITE_LIMIT_FUNCTION_ARG 6 +#define SQLITE_LIMIT_ATTACHED 7 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 +#define SQLITE_LIMIT_VARIABLE_NUMBER 9 +#define SQLITE_LIMIT_TRIGGER_DEPTH 10 + +/* +** CAPI3REF: Compiling An SQL Statement +** KEYWORDS: {SQL statement compiler} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** The first argument, "db", is a [database connection] obtained from a +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or +** [sqlite3_open16()]. The database connection must not have been closed. +** +** The second argument, "zSql", is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. +** +** ^If the nByte argument is less than zero, then zSql is read up to the +** first zero terminator. ^If nByte is non-negative, then it is the maximum +** number of bytes read from zSql. ^When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** the nByte-th byte, whichever comes first. If the caller knows +** that the supplied string is nul-terminated, then there is a small +** performance advantage to be gained by passing an nByte parameter that +** is equal to the number of bytes in the input string including +** the nul-terminator bytes as this saves SQLite from having to +** make a copy of the input string. +** +** ^If pzTail is not NULL then *pzTail is made to point to the first byte +** past the end of the first SQL statement in zSql. These routines only +** compile the first statement in zSql, so *pzTail is left pointing to +** what remains uncompiled. +** +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be +** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** to NULL. ^If the input text contains no SQL (if the input is an empty +** string or a comment) then *ppStmt is set to NULL. +** The calling procedure is responsible for deleting the compiled +** SQL statement using [sqlite3_finalize()] after it has finished with it. +** ppStmt may not be NULL. +** +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** otherwise an [error code] is returned. +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** ^In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [sqlite3_step()] interface to +** behave differently in three ways: +** +**
      +**
    1. +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] +** retries will occur before sqlite3_step() gives up and returns an error. +**
    2. +** +**
    3. +** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** [error codes] or [extended error codes]. ^The legacy behavior was that +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [sqlite3_reset()] +** in order to find the underlying cause of the problem. With the "v2" prepare +** interfaces, the underlying reason for the error is returned immediately. +**
    4. +** +**
    5. +** ^If the specific value bound to [parameter | host parameter] in the +** WHERE clause might influence the choice of query plan for a statement, +** then the statement will be automatically recompiled, as if there had been +** a schema change, on the first [sqlite3_step()] call following any change +** to the [sqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of WHERE-clause [parameter] might influence the +** choice of query plan if the parameter is the left-hand side of a [LIKE] +** or [GLOB] operator or if the parameter is compared to an indexed column +** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. +** the +**
    6. +**
    +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPI3REF: Retrieving Statement SQL +** +** ^This interface can be used to retrieve a saved copy of the original +** SQL text used to create a [prepared statement] if that statement was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If An SQL Statement Writes The Database +** +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** and only if the [prepared statement] X makes no direct changes to +** the content of the database file. +** +** Note that [application-defined SQL functions] or +** [virtual tables] might change the database indirectly as a side effect. +** ^(For example, if an application defines a function "eval()" that +** calls [sqlite3_exec()], then the following SQL statement would +** change the database file through side-effects: +** +**
    +**    SELECT eval('DELETE FROM t1') FROM t2;
    +** 
    +** +** But because the [SELECT] statement does not change the database file +** directly, sqlite3_stmt_readonly() would still return true.)^ +** +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** since the statements themselves do not actually modify the database but +** rather they control the timing of when other statements modify the +** database. ^The [ATTACH] and [DETACH] statements also cause +** sqlite3_stmt_readonly() to return true since, while those statements +** change the configuration of a database connection, they do not make +** changes to the content of the database files on disk. +*/ +int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If A Prepared Statement Has Been Reset +** +** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the +** [prepared statement] S has been stepped at least once using +** [sqlite3_step(S)] but has not run to completion and/or has not +** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) +** interface returns false if S is a NULL pointer. If S is not a +** NULL pointer and is not a pointer to a valid [prepared statement] +** object, then the behavior is undefined and probably undesirable. +** +** This interface can be used in combination [sqlite3_next_stmt()] +** to locate all prepared statements associated with a database +** connection that are in need of being reset. This can be used, +** for example, in diagnostic routines to search for prepared +** statements that are holding a transaction open. +*/ +int sqlite3_stmt_busy(sqlite3_stmt*); + +/* +** CAPI3REF: Dynamically Typed Value Object +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** +** SQLite uses the sqlite3_value object to represent all values +** that can be stored in a database table. SQLite uses dynamic typing +** for the values it stores. ^Values stored in sqlite3_value objects +** can be integers, floating point values, strings, BLOBs, or NULL. +** +** An sqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected sqlite3_value. Other interfaces +** will accept either a protected or an unprotected sqlite3_value. +** Every interface that accepts sqlite3_value arguments specifies +** whether or not it requires a protected sqlite3_value. +** +** The terms "protected" and "unprotected" refer to whether or not +** a mutex is held. An internal mutex is held for a protected +** sqlite3_value object but no mutex is held for an unprotected +** sqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** or if SQLite is run in one of reduced mutex modes +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] +** then there is no distinction between protected and unprotected +** sqlite3_value objects and they can be used interchangeably. However, +** for maximum code portability it is recommended that applications +** still make the distinction between protected and unprotected +** sqlite3_value objects even when not strictly required. +** +** ^The sqlite3_value objects that are passed as parameters into the +** implementation of [application-defined SQL functions] are protected. +** ^The sqlite3_value object returned by +** [sqlite3_column_value()] is unprotected. +** Unprotected sqlite3_value objects may only be used with +** [sqlite3_result_value()] and [sqlite3_bind_value()]. +** The [sqlite3_value_blob | sqlite3_value_type()] family of +** interfaces require protected sqlite3_value objects. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. ^A pointer to an sqlite3_context object +** is always first parameter to [application-defined SQL functions]. +** The application-defined SQL function implementation will pass this +** pointer through into calls to [sqlite3_result_int | sqlite3_result()], +** [sqlite3_aggregate_context()], [sqlite3_user_data()], +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], +** and/or [sqlite3_set_auxdata()]. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements +** KEYWORDS: {host parameter} {host parameters} {host parameter name} +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** literals may be replaced by a [parameter] that matches one of following +** templates: +** +**
      +**
    • ? +**
    • ?NNN +**
    • :VVV +**
    • @VVV +**
    • $VVV +**
    +** +** In the templates above, NNN represents an integer literal, +** and VVV represents an alphanumeric identifier.)^ ^The values of these +** parameters (also called "host parameter names" or "SQL parameters") +** can be set using the sqlite3_bind_*() routines defined here. +** +** ^The first argument to the sqlite3_bind_*() routines is always +** a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. +** +** ^The second argument is the index of the SQL parameter to be set. +** ^The leftmost SQL parameter has an index of 1. ^When the same named +** SQL parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** ^The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_index()] API if desired. ^The index +** for "?NNN" parameters is the value of NNN. +** ^The NNN value must be between 1 and the [sqlite3_limit()] +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). +** +** ^The third argument is the value to bind to the parameter. +** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter +** is ignored and the end result is the same as sqlite3_bind_null(). +** +** ^(In those routines that have a fourth argument, its value is the +** number of bytes in the parameter. To be clear: the value is the +** number of bytes in the value, not the number of characters.)^ +** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** is negative, then the length of the string is +** the number of bytes up to the first zero terminator. +** If the fourth parameter to sqlite3_bind_blob() is negative, then +** the behavior is undefined. +** If a non-negative fourth parameter is provided to sqlite3_bind_text() +** or sqlite3_bind_text16() then that parameter must be the byte offset +** where the NUL terminator would occur assuming the string were NUL +** terminated. If any NUL characters occur at byte offsets less than +** the value of the fourth parameter then the resulting string value will +** contain embedded NULs. The result of expressions involving strings +** with embedded NULs is undefined. +** +** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** string after SQLite has finished with it. ^The destructor is called +** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), +** sqlite3_bind_text(), or sqlite3_bind_text16() fails. +** ^If the fifth argument is +** the special value [SQLITE_STATIC], then SQLite assumes that the +** information is in static, unmanaged space and does not need to be freed. +** ^If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. +** +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeroes. ^A zeroblob uses a fixed amount of memory +** (just an integer to hold its size) while it is being processed. +** Zeroblobs are intended to serve as placeholders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | incremental BLOB I/O] routines. +** ^A negative value for the zeroblob results in a zero-length BLOB. +** +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** for the [prepared statement] or with a prepared statement for which +** [sqlite3_step()] has been called more recently than [sqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** routine is passed a [prepared statement] that has been finalized, the +** result is undefined and probably harmful. +** +** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Unbound parameters are interpreted as NULL. +** +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** [error code] if anything goes wrong. +** ^[SQLITE_RANGE] is returned if the parameter +** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. +** +** See also: [sqlite3_bind_parameter_count()], +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +*/ +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +int sqlite3_bind_double(sqlite3_stmt*, int, double); +int sqlite3_bind_int(sqlite3_stmt*, int, int); +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +int sqlite3_bind_null(sqlite3_stmt*, int); +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of SQL Parameters +** +** ^This routine can be used to find the number of [SQL parameters] +** in a [prepared statement]. SQL parameters are tokens of the +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as +** placeholders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** ^(This routine actually returns the index of the largest (rightmost) +** parameter. For all forms except ?NNN, this will correspond to the +** number of unique parameters. If parameters of the ?NNN form are used, +** there may be gaps in the list.)^ +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_name()], and +** [sqlite3_bind_parameter_index()]. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter +** +** ^The sqlite3_bind_parameter_name(P,N) interface returns +** the name of the N-th [SQL parameter] in the [prepared statement] P. +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" +** respectively. +** In other words, the initial ":" or "$" or "@" or "?" +** is included as part of the name.)^ +** ^Parameters of the form "?" without a following integer have no name +** and are referred to as "nameless" or "anonymous parameters". +** +** ^The first host parameter has an index of 1, not 0. +** +** ^If the value N is out of range or if the N-th parameter is +** nameless, then NULL is returned. ^The returned string is +** always in UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name +** +** ^Return the index of an SQL parameter given its name. ^The +** index value returned is suitable for use as the second +** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** is returned if no matching parameter is found. ^The parameter +** name must be given in UTF-8 even if the original statement +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement +** +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset +** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Use this routine to reset all host parameters to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set +** +** ^Return the number of columns in the result set returned by the +** [prepared statement]. ^This routine returns 0 if pStmt is an SQL +** statement that does not return data (for example an [UPDATE]). +** +** See also: [sqlite3_data_count()] +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set +** +** ^These routines return the name assigned to a particular column +** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF-8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF-16 string. ^The first parameter is the [prepared statement] +** that implements the [SELECT] statement. ^The second parameter is the +** column number. ^The leftmost column is number 0. +** +** ^The returned string pointer is valid until either the [prepared statement] +** is destroyed by [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the next call to +** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** +** ^If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +** +** ^The name of a result column is the value of the "AS" clause for +** that column, if there is an AS clause. If there is no AS clause +** then the name of the column is unspecified and may change from +** one release of SQLite to the next. +*/ +const char *sqlite3_column_name(sqlite3_stmt*, int N); +const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result +** +** ^These routines provide a means to determine the database, table, and +** table column that is the origin of a particular result column in +** [SELECT] statement. +** ^The name of the database or table or column can be returned as +** either a UTF-8 or UTF-16 string. ^The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. +** ^The returned string is valid until the [prepared statement] is destroyed +** using [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the same information is requested +** again in a different encoding. +** +** ^The names returned are the original un-aliased names of the +** database, table, and column. +** +** ^The first argument to these interfaces is a [prepared statement]. +** ^These functions return information about the Nth result column returned by +** the statement, where N is the second function argument. +** ^The left-most column is column 0 for these routines. +** +** ^If the Nth column returned by the statement is an expression or +** subquery and is not a column value, then all of these functions return +** NULL. ^These routine might also return NULL if a memory allocation error +** occurs. ^Otherwise, they return the name of the attached database, table, +** or column that query result column was extracted from. +** +** ^As with all other SQLite APIs, those whose names end with "16" return +** UTF-16 encoded strings and the other functions return UTF-8. +** +** ^These APIs are only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. +** +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +** +** If two or more threads call one or more +** [sqlite3_column_database_name | column metadata interfaces] +** for the same [prepared statement] and result column +** at the same time then the results are undefined. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt*,int); +const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +const char *sqlite3_column_table_name(sqlite3_stmt*,int); +const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result +** +** ^(The first parameter is a [prepared statement]. +** If this statement is a [SELECT] statement and the Nth column of the +** returned result set of that [SELECT] is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned.)^ ^If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** ^The returned string is always UTF-8 encoded. +** +** ^(For example, given the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** and the following statement to be compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** this routine would return the string "VARIANT" for the second result +** column (i==1), and a NULL pointer for the first result column (i==0).)^ +** +** ^SQLite uses dynamic run-time typing. ^So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. ^Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt*,int); +const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement +** +** After a [prepared statement] has been prepared using either +** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** must be called one or more times to evaluate the statement. +** +** The details of the behavior of the sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** ^In the legacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** ^With the "v2" interface, any of the other [result codes] or +** [extended result codes] might be returned as well. +** +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. ^If the statement is a [COMMIT] +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a [COMMIT] and occurs within an +** explicit transaction then you should rollback the transaction before +** continuing. +** +** ^[SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] +** is returned each time a new row of data is ready for processing by the +** caller. The values may be accessed using the [column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** ^With the legacy interface, a more specific error code (for example, +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [prepared statement]. ^In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** For all versions of SQLite up to and including 3.6.23.1, a call to +** [sqlite3_reset()] was required after sqlite3_step() returned anything +** other than [SQLITE_ROW] before any subsequent invocation of +** sqlite3_step(). Failure to reset the prepared statement using +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began +** calling [sqlite3_reset()] automatically in this circumstance rather +** than returning [SQLITE_MISUSE]. This is not considered a compatibility +** break because any application that ever receives an SQLITE_MISUSE error +** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option +** can be used to restore the legacy behavior. +** +** Goofy Interface Alert: In the legacy interface, the sqlite3_step() +** API always returns a generic error code, [SQLITE_ERROR], following any +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** specific [error codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** then the more specific [error codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set +** +** ^The sqlite3_data_count(P) interface returns the number of columns in the +** current row of the result set of [prepared statement] P. +** ^If prepared statement P does not have results ready to return +** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of +** interfaces) then sqlite3_data_count(P) returns 0. +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** ^The sqlite3_data_count(P) routine returns 0 if the previous call to +** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) +** will return non-zero if previous call to [sqlite3_step](P) returned +** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] +** where it always returns zero since each step of that multi-step +** pragma returns 0 columns of data. +** +** See also: [sqlite3_column_count()] +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes +** KEYWORDS: SQLITE_TEXT +** +** ^(Every value in SQLite has one of five fundamental datatypes: +** +**
      +**
    • 64-bit signed integer +**
    • 64-bit IEEE floating point number +**
    • string +**
    • BLOB +**
    • NULL +**
    )^ +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Result Values From A Query +** KEYWORDS: {column access functions} +** +** These routines form the "result set" interface. +** +** ^These routines return information about a single column of the current +** result row of a query. ^In every case the first argument is a pointer +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] +** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** and the second argument is the index of the column for which information +** should be returned. ^The leftmost column of the result set has the index 0. +** ^The number of columns in the result can be determined using +** [sqlite3_column_count()]. +** +** If the SQL statement does not currently point to a valid row, or if the +** column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** ^The sqlite3_column_type() routine returns the +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. ^The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** the string to UTF-16 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes16() uses +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** +** ^The values returned by [sqlite3_column_bytes()] and +** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** of the string. ^For clarity: the values returned by +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** bytes in the string, not the number of characters. +** +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even empty strings, are always zero-terminated. ^The return +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** ^The object returned by [sqlite3_column_value()] is an +** [unprotected sqlite3_value] object. An unprotected sqlite3_value object +** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. +** If the [unprotected sqlite3_value] object returned by +** [sqlite3_column_value()] is used in any other way, including calls +** to routines like [sqlite3_value_int()], [sqlite3_value_text()], +** or [sqlite3_value_bytes()], then the behavior is undefined. +** +** These routines attempt to convert the value where appropriate. ^For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to perform the +** conversion automatically. ^(The following table details the conversions +** that are applied: +** +**
    +** +**
    Internal
    Type
    Requested
    Type
    Conversion +** +**
    NULL INTEGER Result is 0 +**
    NULL FLOAT Result is 0.0 +**
    NULL TEXT Result is NULL pointer +**
    NULL BLOB Result is NULL pointer +**
    INTEGER FLOAT Convert from integer to float +**
    INTEGER TEXT ASCII rendering of the integer +**
    INTEGER BLOB Same as INTEGER->TEXT +**
    FLOAT INTEGER Convert from float to integer +**
    FLOAT TEXT ASCII rendering of the float +**
    FLOAT BLOB Same as FLOAT->TEXT +**
    TEXT INTEGER Use atoi() +**
    TEXT FLOAT Use atof() +**
    TEXT BLOB No change +**
    BLOB INTEGER Convert to TEXT then use atoi() +**
    BLOB FLOAT Convert to TEXT then use atof() +**
    BLOB TEXT Add a zero terminator if needed +**
    +**
    )^ +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** own equivalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
      +**
    • The initial content is a BLOB and sqlite3_column_text() or +** sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.
    • +**
    • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.
    • +**
    • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.
    • +**
    +** +** ^Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer references will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometimes they +** are not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
      +**
    • sqlite3_column_text() followed by sqlite3_column_bytes()
    • +**
    • sqlite3_column_blob() followed by sqlite3_column_bytes()
    • +**
    • sqlite3_column_text16() followed by sqlite3_column_bytes16()
    • +**
    +** +** In other words, you should call sqlite3_column_text(), +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result +** into the desired format, then invoke sqlite3_column_bytes() or +** sqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to sqlite3_column_text() or sqlite3_column_blob() with calls to +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() +** with calls to sqlite3_column_bytes(). +** +** ^The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** ^(If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM].)^ +*/ +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +double sqlite3_column_double(sqlite3_stmt*, int iCol); +int sqlite3_column_int(sqlite3_stmt*, int iCol); +sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +int sqlite3_column_type(sqlite3_stmt*, int iCol); +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object +** +** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^If the most recent evaluation of the statement encountered no errors +** or if the statement is never been evaluated, then sqlite3_finalize() returns +** SQLITE_OK. ^If the most recent evaluation of statement S failed, then +** sqlite3_finalize(S) returns the appropriate [error code] or +** [extended error code]. +** +** ^The sqlite3_finalize(S) routine can be called at any point during +** the life cycle of [prepared statement] S: +** before statement S is ever evaluated, after +** one or more calls to [sqlite3_reset()], or after any call +** to [sqlite3_step()] regardless of whether or not the statement has +** completed execution. +** +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** +** The application must finalize every [prepared statement] in order to avoid +** resource leaks. It is a grievous error for the application to try to use +** a prepared statement after it has been finalized. Any use of a prepared +** statement after it has been finalized can result in undefined and +** undesirable behavior such as segfaults and heap corruption. +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object +** +** The sqlite3_reset() function is called to reset a [prepared statement] +** object back to its initial state, ready to be re-executed. +** ^Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +** +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** back to the beginning of its program. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], +** or if [sqlite3_step(S)] has never before been called on S, +** then [sqlite3_reset(S)] returns [SQLITE_OK]. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S indicated an error, then +** [sqlite3_reset(S)] returns an appropriate [error code]. +** +** ^The [sqlite3_reset(S)] interface does not change the values +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +*/ +int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions +** KEYWORDS: {function creation routines} +** KEYWORDS: {application-defined SQL function} +** KEYWORDS: {application-defined SQL functions} +** +** ^These functions (collectively known as "function creation routines") +** are used to add SQL functions or aggregates or to redefine the behavior +** of existing SQL functions or aggregates. The only differences between +** these routines are the text encoding expected for +** the second parameter (the name of the function being created) +** and the presence or absence of a destructor callback for +** the application data pointer. +** +** ^The first parameter is the [database connection] to which the SQL +** function is to be added. ^If an application uses more than one database +** connection then application-defined SQL functions must be added +** to each database connection separately. +** +** ^The second parameter is the name of the SQL function to be created or +** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 +** representation, exclusive of the zero-terminator. ^Note that the name +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. +** ^Any attempt to create a function with a longer name +** will result in [SQLITE_MISUSE] being returned. +** +** ^The third parameter (nArg) +** is the number of arguments that the SQL function or +** aggregate takes. ^If this parameter is -1, then the SQL function or +** aggregate may take any number of arguments between 0 and the limit +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** parameter is less than -1 or greater than 127 then the behavior is +** undefined. +** +** ^The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Every SQL function implementation must be able to work +** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. ^An application may +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** ^When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what text +** encoding is used, then the fourth argument should be [SQLITE_ANY]. +** +** ^(The fifth parameter is an arbitrary pointer. The implementation of the +** function can gain access to this pointer using [sqlite3_user_data()].)^ +** +** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL function or +** aggregate. ^A scalar SQL function requires an implementation of the xFunc +** callback only; NULL pointers must be passed as the xStep and xFinal +** parameters. ^An aggregate SQL function requires an implementation of xStep +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing +** SQL function or aggregate, pass NULL pointers for all three function +** callbacks. +** +** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, +** then it is destructor for the application data pointer. +** The destructor is invoked when the function is deleted, either by being +** overloaded or when the database connection closes.)^ +** ^The destructor is also invoked if the call to +** sqlite3_create_function_v2() fails. +** ^When the destructor callback of the tenth parameter is invoked, it +** is passed a single argument which is a copy of the application data +** pointer which was the fifth parameter to sqlite3_create_function_v2(). +** +** ^It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing preferred text encodings. ^SQLite will use +** the implementation that most closely matches the way in which the +** SQL function is used. ^A function implementation with a non-negative +** nArg parameter is a better match than a function implementation with +** a negative nArg. ^A function where the preferred text encoding +** matches the database encoding is a better +** match than a function where the encoding is different. +** ^A function where the encoding difference is between UTF16le and UTF16be +** is a closer match than a function where the encoding difference is +** between UTF8 and UTF16. +** +** ^Built-in functions may be overloaded by new application-defined functions. +** +** ^An application-defined function is permitted to call other +** SQLite interfaces. However, such calls must not +** close the database connection nor finalize or reset the prepared +** statement in which the function is running. +*/ +int sqlite3_create_function( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*) +); + +/* +** CAPI3REF: Text Encodings +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Deprecated Functions +** DEPRECATED +** +** These functions are [deprecated]. In order to maintain +** backwards compatibility with older code, these functions continue +** to be supported. However, new applications should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you what they do. +*/ +#ifndef SQLITE_OMIT_DEPRECATED +SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); +SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); +SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +SQLITE_DEPRECATED int sqlite3_global_recover(void); +SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); +SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), + void*,sqlite3_int64); +#endif + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 3rd parameter to these callbacks is an array of pointers to +** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work only with [protected sqlite3_value] objects. +** Any attempt to use these routines on an [unprotected sqlite3_value] +** object results in undefined behavior. +** +** ^These routines work just like the corresponding [column access functions] +** except that these routines take a single [protected sqlite3_value] object +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** +** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** in the native byte-order of the host machine. ^The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF-16 strings as big-endian and little-endian respectively. +** +** ^(The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words, if the value is a string that looks like a number) +** then the conversion is performed. Otherwise no conversion occurs. +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ +** +** Please pay particular attention to the fact that the pointer returned +** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the [sqlite3_value*] parameters. +*/ +const void *sqlite3_value_blob(sqlite3_value*); +int sqlite3_value_bytes(sqlite3_value*); +int sqlite3_value_bytes16(sqlite3_value*); +double sqlite3_value_double(sqlite3_value*); +int sqlite3_value_int(sqlite3_value*); +sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +const unsigned char *sqlite3_value_text(sqlite3_value*); +const void *sqlite3_value_text16(sqlite3_value*); +const void *sqlite3_value_text16le(sqlite3_value*); +const void *sqlite3_value_text16be(sqlite3_value*); +int sqlite3_value_type(sqlite3_value*); +int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context +** +** Implementations of aggregate SQL functions use this +** routine to allocate memory for storing their state. +** +** ^The first time the sqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite +** allocates N of memory, zeroes out that memory, and returns a pointer +** to the new memory. ^On second and subsequent calls to +** sqlite3_aggregate_context() for the same aggregate function instance, +** the same buffer is returned. Sqlite3_aggregate_context() is normally +** called once for each invocation of the xStep callback and then one +** last time when the xFinal callback is invoked. ^(When no rows match +** an aggregate query, the xStep() callback of the aggregate function +** implementation is never called and xFinal() is called exactly once. +** In those cases, sqlite3_aggregate_context() might be called for the +** first time from within xFinal().)^ +** +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer +** when first called if N is less than or equal to zero or if a memory +** allocate error occurs. +** +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** determined by the N parameter on first successful call. Changing the +** value of N in subsequent call to sqlite3_aggregate_context() within +** the same aggregate function instance will not resize the memory +** allocation.)^ Within the xFinal callback, it is customary to set +** N=0 in calls to sqlite3_aggregate_context(C,N) so that no +** pointless memory allocations occur. +** +** ^SQLite automatically frees the memory allocated by +** sqlite3_aggregate_context() when the aggregate query concludes. +** +** The first parameter must be a copy of the +** [sqlite3_context | SQL function context] that is the first parameter +** to the xStep or xFinal callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions +** +** ^The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +** +** This routine must be called from the same thread in which +** the application-defined function is running. +*/ +void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Database Connection For Functions +** +** ^The sqlite3_context_db_handle() interface returns a copy of +** the pointer to the [database connection] (the 1st parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +*/ +sqlite3 *sqlite3_context_db_handle(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data +** +** These functions may be used by (non-aggregate) SQL functions to +** associate metadata with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated metadata may be preserved. An example +** of where this might be useful is in a regular-expression matching +** function. The compiled version of the regular expression can be stored as +** metadata associated with the pattern string. +** Then as long as the pattern string remains the same, +** the compiled regular expression can be reused on multiple +** invocations of the same function. +** +** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. ^If there is no metadata +** associated with the function argument, this sqlite3_get_auxdata() interface +** returns a NULL pointer. +** +** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th +** argument of the application-defined function. ^Subsequent +** calls to sqlite3_get_auxdata(C,N) return P from the most recent +** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or +** NULL if the metadata has been discarded. +** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, +** SQLite will invoke the destructor function X with parameter P exactly +** once, when the metadata is discarded. +** SQLite is free to discard the metadata at any time, including:
      +**
    • when the corresponding function parameter changes, or +**
    • when [sqlite3_reset()] or [sqlite3_finalize()] is called for the +** SQL statement, or +**
    • when sqlite3_set_auxdata() is invoked again on the same parameter, or +**
    • during the original sqlite3_set_auxdata() call when a memory +** allocation error occurs.
    )^ +** +** Note the last bullet in particular. The destructor X in +** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the +** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() +** should be called near the end of the function implementation and the +** function implementation should not make any use of P after +** sqlite3_set_auxdata() has been called. +** +** ^(In practice, metadata is preserved between function calls for +** function parameters that are compile-time constants, including literal +** values and [parameters] and expressions composed from the same.)^ +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +void *sqlite3_get_auxdata(sqlite3_context*, int N); +void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior +** +** These are special values for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. ^The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the [parameter binding] family of +** functions used to bind values to host parameters in prepared statements. +** Refer to the [SQL parameter] documentation for additional information. +** +** ^The sqlite3_result_blob() interface sets the result from +** an application-defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** +** ^The sqlite3_result_zeroblob() interfaces set the result of +** the application-defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** ^The sqlite3_result_double() interface sets the result from +** an application-defined function to be a floating point value specified +** by its 2nd argument. +** +** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** ^SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. ^SQLite interprets the error +** message string from sqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from sqlite3_result_error16() as UTF-16 in native +** byte order. ^If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** ^If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** ^The sqlite3_result_error() and sqlite3_result_error16() +** routines make a private copy of the error message text before +** they return. Hence, the calling function can deallocate or +** modify the text after they return without harm. +** ^The sqlite3_result_error_code() function changes the error code +** returned by SQLite as a result of an error in a function. ^By default, +** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() +** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** +** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an +** error indicating that a string or BLOB is too long to represent. +** +** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an +** error indicating that a memory allocation failed. +** +** ^The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** ^The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** ^The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** ^The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** ^SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. If the 3rd parameter is non-negative, then it +** must be the byte offset into the string where the NUL terminator would +** appear if the string where NUL terminated. If any NUL characters occur +** in the string at a byte offset that is less than the value of the 3rd +** parameter, then the resulting string will contain embedded NULs and the +** result of expressions operating on strings with embedded NULs is undefined. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or BLOB result when it has +** finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces or to +** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** assumes that the text or BLOB result is in constant space and does not +** copy the content of the parameter nor call a destructor on the content +** when it has finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** ^The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the +** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that the [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** ^A [protected sqlite3_value] object may always be used where an +** [unprotected sqlite3_value] object is required, so either +** kind of [sqlite3_value] object can be used with this interface. +** +** If these routines are called from within the different thread +** than the one containing the application-defined function that received +** the [sqlite3_context] pointer, the results are undefined. +*/ +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_double(sqlite3_context*, double); +void sqlite3_result_error(sqlite3_context*, const char*, int); +void sqlite3_result_error16(sqlite3_context*, const void*, int); +void sqlite3_result_error_toobig(sqlite3_context*); +void sqlite3_result_error_nomem(sqlite3_context*); +void sqlite3_result_error_code(sqlite3_context*, int); +void sqlite3_result_int(sqlite3_context*, int); +void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +void sqlite3_result_null(sqlite3_context*); +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences +** +** ^These functions add, remove, or modify a [collation] associated +** with the [database connection] specified as the first argument. +** +** ^The name of the collation is a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for sqlite3_create_collation16(). +** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** considered to be the same name. +** +** ^(The third argument (eTextRep) must be one of the constants: +**
      +**
    • [SQLITE_UTF8], +**
    • [SQLITE_UTF16LE], +**
    • [SQLITE_UTF16BE], +**
    • [SQLITE_UTF16], or +**
    • [SQLITE_UTF16_ALIGNED]. +**
    )^ +** ^The eTextRep argument determines the encoding of strings passed +** to the collating function callback, xCallback. +** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep +** force strings to be UTF16 with native byte order. +** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin +** on an even byte address. +** +** ^The fourth argument, pArg, is an application data pointer that is passed +** through as the first argument to the collating function callback. +** +** ^The fifth argument, xCallback, is a pointer to the collating function. +** ^Multiple collating functions can be registered using the same name but +** with different eTextRep parameters and SQLite will use whichever +** function requires the least amount of data transformation. +** ^If the xCallback argument is NULL then the collating function is +** deleted. ^When all collating functions having the same name are deleted, +** that collation is no longer usable. +** +** ^The collating function callback is invoked with a copy of the pArg +** application data pointer and with two strings in the encoding specified +** by the eTextRep argument. The collating function must return an +** integer that is negative, zero, or positive +** if the first string is less than, equal to, or greater than the second, +** respectively. A collating function must always return the same answer +** given the same inputs. If two or more collating functions are registered +** to the same collation name (using different eTextRep values) then all +** must give an equivalent answer when invoked with equivalent strings. +** The collating function must obey the following properties for all +** strings A, B, and C: +** +**
      +**
    1. If A==B then B==A. +**
    2. If A==B and B==C then A==C. +**
    3. If A<B THEN B>A. +**
    4. If A<B and B<C then A<C. +**
    +** +** If a collating function fails any of the above constraints and that +** collating function is registered and used, then the behavior of SQLite +** is undefined. +** +** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** with the addition that the xDestroy callback is invoked on pArg when +** the collating function is deleted. +** ^Collating functions are deleted when they are overridden by later +** calls to the collation creation functions or when the +** [database connection] is closed using [sqlite3_close()]. +** +** ^The xDestroy callback is not called if the +** sqlite3_create_collation_v2() function fails. Applications that invoke +** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** check the return code and dispose of the application data pointer +** themselves rather than expecting SQLite to deal with it for them. +** This is different from every other SQLite interface. The inconsistency +** is unfortunate but cannot be changed without breaking backwards +** compatibility. +** +** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +*/ +int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); +int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +int sqlite3_create_collation16( + sqlite3*, + const void *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks +** +** ^To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** [database connection] to be invoked whenever an undefined collation +** sequence is required. +** +** ^If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** the names are passed as UTF-16 in machine native byte order. +** ^A call to either function replaces the existing collation-needed callback. +** +** ^(When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). The second argument is the database +** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE], indicating the most desirable form of the collation +** sequence function required. The fourth parameter is the name of the +** required collation sequence.)^ +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +#ifdef SQLITE_HAS_CODEC +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); +int sqlite3_key_v2( + sqlite3 *db, /* Database to be rekeyed */ + const char *zDbName, /* Name of the database */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); +int sqlite3_rekey_v2( + sqlite3 *db, /* Database to be rekeyed */ + const char *zDbName, /* Name of the database */ + const void *pKey, int nKey /* The new key */ +); + +/* +** Specify the activation key for a SEE database. Unless +** activated, none of the SEE routines will work. +*/ +void sqlite3_activate_see( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +#ifdef SQLITE_ENABLE_CEROD +/* +** Specify the activation key for a CEROD database. Unless +** activated, none of the CEROD routines will work. +*/ +void sqlite3_activate_cerod( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +/* +** CAPI3REF: Suspend Execution For A Short Time +** +** The sqlite3_sleep() function causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** ^SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. If the xSleep() method +** of the default VFS is not implemented correctly, or not implemented at +** all, then the behavior of sqlite3_sleep() may deviate from the description +** in the previous paragraphs. +*/ +int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all temporary files +** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** will be placed in that directory.)^ ^If this variable +** is a NULL pointer, then SQLite performs a search for an appropriate +** temporary file directory. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [temp_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [temp_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [temp_store_directory pragma] should be avoided. +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various +** features that require the use of temporary files may fail. Here is an +** example of how to do this using C++ with the Windows Runtime: +** +**
    +** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
    +**       TemporaryFolder->Path->Data();
    +** char zPathBuf[MAX_PATH + 1];
    +** memset(zPathBuf, 0, sizeof(zPathBuf));
    +** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
    +**       NULL, NULL);
    +** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
    +** 
    +*/ +SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Name Of The Folder Holding Database Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all database files +** specified with a relative pathname and created or accessed by +** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed +** to be relative to that directory.)^ ^If this variable is a NULL +** pointer, then SQLite assumes that all database files specified +** with a relative pathname are relative to the current directory +** for the process. Only the windows VFS makes use of this global +** variable; it is ignored by the unix VFS. +** +** Changing the value of this variable while a database connection is +** open can result in a corrupt database. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [data_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [data_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [data_store_directory pragma] should be avoided. +*/ +SQLITE_EXTERN char *sqlite3_data_directory; + +/* +** CAPI3REF: Test For Auto-Commit Mode +** KEYWORDS: {autocommit mode} +** +** ^The sqlite3_get_autocommit() interface returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. ^Autocommit mode is on by default. +** ^Autocommit mode is disabled by a [BEGIN] statement. +** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** +** If certain kinds of errors occur on a statement within a multi-statement +** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. The only way to +** find out whether SQLite automatically rolled back the transaction after +** an error is to use this function. +** +** If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. +*/ +int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement +** +** ^The sqlite3_db_handle interface returns the [database connection] handle +** to which a [prepared statement] belongs. ^The [database connection] +** returned by sqlite3_db_handle is the same [database connection] +** that was the first argument +** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** create the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + +/* +** CAPI3REF: Return The Filename For A Database Connection +** +** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename +** associated with database N of connection D. ^The main database file +** has the name "main". If there is no attached database N on the database +** connection D, or if database N is a temporary or in-memory database, then +** a NULL pointer is returned. +** +** ^The filename returned by this function is the output of the +** xFullPathname method of the [VFS]. ^In other words, the filename +** will be an absolute pathname, even if the filename used +** to open the database originally was a URI or relative pathname. +*/ +const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Determine if a database is read-only +** +** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N +** of connection D is read-only, 0 if it is read/write, or -1 if N is not +** the name of a database on connection D. +*/ +int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Find the next prepared statement +** +** ^This interface returns a pointer to the next [prepared statement] after +** pStmt associated with the [database connection] pDb. ^If pStmt is NULL +** then this interface returns a pointer to the first prepared statement +** associated with the database connection pDb. ^If no prepared statement +** satisfies the conditions of this routine, it returns NULL. +** +** The [database connection] pointer D in a call to +** [sqlite3_next_stmt(D,S)] must refer to an open database +** connection and in particular must not be a NULL pointer. +*/ +sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks +** +** ^The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is [COMMIT | committed]. +** ^Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** ^The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. +** ^Any callback set by a previous call to sqlite3_rollback_hook() +** for the same database connection is overridden. +** ^The pArg argument is passed through to the callback. +** ^If the callback on a commit hook function returns non-zero, +** then the commit is converted into a rollback. +** +** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** return the P argument from the previous call of the same function +** on the same [database connection] D, or NULL for +** the first call for each function on D. +** +** The commit and rollback hook callbacks are not reentrant. +** The callback implementation must not do anything that will modify +** the database connection that invoked the callback. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the commit +** or rollback hook in the first place. +** Note that running any other SQL statements, including SELECT statements, +** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify +** the database connections for the meaning of "modify" in this paragraph. +** +** ^Registering a NULL function disables the callback. +** +** ^When the commit hook callback routine returns zero, the [COMMIT] +** operation is allowed to continue normally. ^If the commit hook +** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. +** ^The rollback hook is invoked on a rollback that results from a commit +** hook returning non-zero, just as it would be with any other rollback. +** +** ^For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** ^The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** +** See also the [sqlite3_update_hook()] interface. +*/ +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks +** +** ^The sqlite3_update_hook() interface registers a callback function +** with the [database connection] identified by the first argument +** to be invoked whenever a row is updated, inserted or deleted. +** ^Any callback set by a previous call to this function +** for the same database connection is overridden. +** +** ^The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** ^The first argument to the callback is a copy of the third argument +** to sqlite3_update_hook(). +** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], +** or [SQLITE_UPDATE], depending on the operation that caused the callback +** to be invoked. +** ^The third and fourth arguments to the callback contain pointers to the +** database and table name containing the affected row. +** ^The final callback parameter is the [rowid] of the row. +** ^In the case of an update, this is the [rowid] after the update takes place. +** +** ^(The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence).)^ +** +** ^In the current implementation, the update hook +** is not invoked when duplication rows are deleted because of an +** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook +** invoked when rows are deleted using the [truncate optimization]. +** The exceptions defined in this paragraph might change in a future +** release of SQLite. +** +** The update hook implementation must not do anything that will modify +** the database connection that invoked the update hook. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the update hook. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^The sqlite3_update_hook(D,C,P) function +** returns the P argument from the previous call +** on the same [database connection] D, or NULL for +** the first call on D. +** +** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] +** interfaces. +*/ +void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache +** +** ^(This routine enables or disables the sharing of the database cache +** and schema data structures between [database connection | connections] +** to the same database. Sharing is enabled if the argument is true +** and disabled if the argument is false.)^ +** +** ^Cache sharing is enabled and disabled for an entire process. +** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, +** sharing was enabled or disabled for each thread separately. +** +** ^(The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** Existing database connections continue use the sharing mode +** that was in effect at the time they were opened.)^ +** +** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled +** successfully. An [error code] is returned otherwise.)^ +** +** ^Shared cache is disabled by default. But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +** +** This interface is threadsafe on processors where writing a +** 32-bit integer is atomic. +** +** See Also: [SQLite Shared-Cache Mode] +*/ +int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory +** +** ^The sqlite3_release_memory() interface attempts to free N bytes +** of heap memory by deallocating non-essential memory allocations +** held by the database library. Memory used to cache database +** pages to improve performance is an example of non-essential memory. +** ^sqlite3_release_memory() returns the number of bytes actually freed, +** which might be more or less than the amount requested. +** ^The sqlite3_release_memory() routine is a no-op returning zero +** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** See also: [sqlite3_db_release_memory()] +*/ +int sqlite3_release_memory(int); + +/* +** CAPI3REF: Free Memory Used By A Database Connection +** +** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap +** memory as possible from database connection D. Unlike the +** [sqlite3_release_memory()] interface, this interface is effect even +** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is +** omitted. +** +** See also: [sqlite3_release_memory()] +*/ +int sqlite3_db_release_memory(sqlite3*); + +/* +** CAPI3REF: Impose A Limit On Heap Size +** +** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** soft limit on the amount of heap memory that may be allocated by SQLite. +** ^SQLite strives to keep heap memory utilization below the soft heap +** limit by reducing the number of pages held in the page cache +** as heap memory usages approaches the limit. +** ^The soft heap limit is "soft" because even though SQLite strives to stay +** below the limit, it will exceed the limit rather than generate +** an [SQLITE_NOMEM] error. In other words, the soft heap limit +** is advisory only. +** +** ^The return value from sqlite3_soft_heap_limit64() is the size of +** the soft heap limit prior to the call, or negative in the case of an +** error. ^If the argument N is negative +** then no change is made to the soft heap limit. Hence, the current +** size of the soft heap limit can be determined by invoking +** sqlite3_soft_heap_limit64() with a negative argument. +** +** ^If the argument N is zero then the soft heap limit is disabled. +** +** ^(The soft heap limit is not enforced in the current implementation +** if one or more of following conditions are true: +** +**
      +**
    • The soft heap limit is set to zero. +**
    • Memory accounting is disabled using a combination of the +** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. +**
    • An alternative page cache implementation is specified using +** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). +**
    • The page cache allocates from its own memory pool supplied +** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** from the heap. +**
    )^ +** +** Beginning with SQLite version 3.7.3, the soft heap limit is enforced +** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] +** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], +** the soft heap limit is enforced on every memory allocation. Without +** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced +** when memory is allocated by the page cache. Testing suggests that because +** the page cache is the predominate memory user in SQLite, most +** applications will achieve adequate soft heap limit enforcement without +** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** The circumstances under which SQLite will enforce the soft heap limit may +** changes in future releases of SQLite. +*/ +sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); + +/* +** CAPI3REF: Deprecated Soft Heap Limit Interface +** DEPRECATED +** +** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** interface. This routine is provided for historical compatibility +** only. All new applications should use the +** [sqlite3_soft_heap_limit64()] interface rather than this one. +*/ +SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); + + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table +** +** ^This routine returns metadata about a specific column of a specific +** database table accessible using the [database connection] handle +** passed as the first function argument. +** +** ^The column is identified by the second, third and fourth parameters to +** this function. ^The second parameter is either the name of the database +** (i.e. "main", "temp", or an attached database) containing the specified +** table or NULL. ^If it is NULL, then all attached databases are searched +** for the table using the same algorithm used by the database engine to +** resolve unqualified table references. +** +** ^The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** ^Metadata is returned by writing to the memory locations passed as the 5th +** and subsequent parameters to this function. ^Any of these arguments may be +** NULL, in which case the corresponding element of metadata is omitted. +** +** ^(
    +** +**
    Parameter Output
    Type
    Description +** +**
    5th const char* Data type +**
    6th const char* Name of default collation sequence +**
    7th int True if column has a NOT NULL constraint +**
    8th int True if column is part of the PRIMARY KEY +**
    9th int True if column is [AUTOINCREMENT] +**
    +**
    )^ +** +** ^The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any SQLite API function. +** +** ^If the specified table is actually a view, an [error code] is returned. +** +** ^If the specified column is "rowid", "oid" or "_rowid_" and an +** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. ^(If there is no +** explicitly declared [INTEGER PRIMARY KEY] column, then the output +** parameters are set as follows: +** +**
    +**     data type: "INTEGER"
    +**     collation sequence: "BINARY"
    +**     not null: 0
    +**     primary key: 1
    +**     auto increment: 0
    +** 
    )^ +** +** ^(This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an [error code] is returned and an error message left +** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^ +** +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +*/ +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension +** +** ^This interface loads an SQLite extension library from the named file. +** +** ^The sqlite3_load_extension() interface attempts to load an +** [SQLite extension] library contained in the file zFile. If +** the file cannot be loaded directly, attempts are made to load +** with various operating-system specific extensions added. +** So for example, if "samplelib" cannot be loaded, then names like +** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might +** be tried also. +** +** ^The entry point is zProc. +** ^(zProc may be 0, in which case SQLite will try to come up with an +** entry point name on its own. It first tries "sqlite3_extension_init". +** If that does not work, it constructs a name "sqlite3_X_init" where the +** X is consists of the lower-case equivalent of all ASCII alphabetic +** characters in the filename from the last "/" to the first following +** "." and omitting any initial "lib".)^ +** ^The sqlite3_load_extension() interface returns +** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** ^If an error occurs and pzErrMsg is not 0, then the +** [sqlite3_load_extension()] interface shall attempt to +** fill *pzErrMsg with error message text stored in memory +** obtained from [sqlite3_malloc()]. The calling function +** should free this memory by calling [sqlite3_free()]. +** +** ^Extension loading must be enabled using +** [sqlite3_enable_load_extension()] prior to calling this API, +** otherwise an error will be returned. +** +** See also the [load_extension() SQL function]. +*/ +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading +** +** ^So as not to open security holes in older applications that are +** unprepared to deal with [extension loading], and as a means of disabling +** [extension loading] while evaluating user-entered SQL, the following API +** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** +** ^Extension loading is off by default. +** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** to turn extension loading on and call it with onoff==0 to turn +** it back off again. +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Automatically Load Statically Linked Extensions +** +** ^This interface causes the xEntryPoint() function to be invoked for +** each new [database connection] that is created. The idea here is that +** xEntryPoint() is the entry point for a statically linked [SQLite extension] +** that is to be automatically loaded into all new database connections. +** +** ^(Even though the function prototype shows that xEntryPoint() takes +** no arguments and returns void, SQLite invokes xEntryPoint() with three +** arguments and expects and integer result as if the signature of the +** entry point where as follows: +** +**
    +**    int xEntryPoint(
    +**      sqlite3 *db,
    +**      const char **pzErrMsg,
    +**      const struct sqlite3_api_routines *pThunk
    +**    );
    +** 
    )^ +** +** If the xEntryPoint routine encounters an error, it should make *pzErrMsg +** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg +** is NULL before calling the xEntryPoint(). ^SQLite will invoke +** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], +** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** +** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** on the list of automatic extensions is a harmless no-op. ^No entry point +** will be called more than once for each database connection that is opened. +** +** See also: [sqlite3_reset_auto_extension()] +** and [sqlite3_cancel_auto_extension()] +*/ +int sqlite3_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Cancel Automatic Extension Loading +** +** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the +** initialization routine X that was registered using a prior call to +** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] +** routine returns 1 if initialization routine X was successfully +** unregistered and it returns 0 if X was not on the list of initialization +** routines. +*/ +int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Reset Automatic Extension Loading +** +** ^This interface disables all automatic extensions previously +** registered using [sqlite3_auto_extension()]. +*/ +void sqlite3_reset_auto_extension(void); + +/* +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** CAPI3REF: Virtual Table Object +** KEYWORDS: sqlite3_module {virtual table module} +** +** This structure, sometimes called a "virtual table module", +** defines the implementation of a [virtual tables]. +** This structure consists mostly of methods for the module. +** +** ^A virtual table module is created by filling in a persistent +** instance of this structure and passing a pointer to that instance +** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** ^The registration remains valid until it is replaced by a different +** module or until the [database connection] closes. The content +** of this structure must not change while it is registered with +** any database connection. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + /* The methods above are in version 1 of the sqlite_module object. Those + ** below are for version 2 and greater. */ + int (*xSavepoint)(sqlite3_vtab *pVTab, int); + int (*xRelease)(sqlite3_vtab *pVTab, int); + int (*xRollbackTo)(sqlite3_vtab *pVTab, int); +}; + +/* +** CAPI3REF: Virtual Table Indexing Information +** KEYWORDS: sqlite3_index_info +** +** The sqlite3_index_info structure and its substructures is used as part +** of the [virtual table] interface to +** pass information into and receive the reply from the [xBestIndex] +** method of a [virtual table module]. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** ^(The aConstraint[] array records WHERE clause constraints of the form: +** +**
    column OP expr
    +** +** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is +** stored in aConstraint[].op using one of the +** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ +** ^(The index of the column is stored in +** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot.)^ +** +** ^The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** ^The aConstraint[] array only reports WHERE clause terms that are +** relevant to the particular virtual table being queried. +** +** ^Information about the ORDER BY clause is stored in aOrderBy[]. +** ^Each term of aOrderBy records a column of the ORDER BY clause. +** +** The [xBestIndex] method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. ^If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite.)^ +** +** ^The idxNum and idxPtr values are recorded and passed into the +** [xFilter] method. +** ^[sqlite3_free()] is used to free idxPtr if and only if +** needToFreeIdxPtr is true. +** +** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** ^The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; + +/* +** CAPI3REF: Virtual Table Constraint Operator Codes +** +** These macros defined the allowed values for the +** [sqlite3_index_info].aConstraint[].op field. Each value represents +** an operator that is part of a constraint term in the wHERE clause of +** a query that uses a [virtual table]. +*/ +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** CAPI3REF: Register A Virtual Table Implementation +** +** ^These routines are used to register a new [virtual table module] name. +** ^Module names must be registered before +** creating a new [virtual table] using the module and before using a +** preexisting [virtual table] for the module. +** +** ^The module name is registered on the [database connection] specified +** by the first parameter. ^The name of the module is given by the +** second parameter. ^The third parameter is a pointer to +** the implementation of the [virtual table module]. ^The fourth +** parameter is an arbitrary client data pointer that is passed through +** into the [xCreate] and [xConnect] methods of the virtual table module +** when a new virtual table is be being created or reinitialized. +** +** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** is a pointer to a destructor for the pClientData. ^SQLite will +** invoke the destructor function (if it is not NULL) when SQLite +** no longer needs the pClientData pointer. ^The destructor will also +** be invoked if the call to sqlite3_create_module_v2() fails. +** ^The sqlite3_create_module() +** interface is equivalent to sqlite3_create_module_v2() with a NULL +** destructor. +*/ +int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData /* Client data for xCreate/xConnect */ +); +int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** CAPI3REF: Virtual Table Instance Object +** KEYWORDS: sqlite3_vtab +** +** Every [virtual table module] implementation uses a subclass +** of this object to describe a particular instance +** of the [virtual table]. Each subclass will +** be tailored to the specific needs of the module implementation. +** The purpose of this superclass is to define certain fields that are +** common to all module implementations. +** +** ^Virtual tables methods can set an error message by assigning a +** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [sqlite3_free()] +** prior to assigning a new string to zErrMsg. ^After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* NO LONGER USED */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Virtual Table Cursor Object +** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** +** Every [virtual table module] implementation uses a subclass of the +** following structure to describe cursors that point into the +** [virtual table] and are used +** to loop through the virtual table. Cursors are created using the +** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods +** of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Declare The Schema Of A Virtual Table +** +** ^The [xCreate] and [xConnect] methods of a +** [virtual table module] call this interface +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +int sqlite3_declare_vtab(sqlite3*, const char *zSQL); + +/* +** CAPI3REF: Overload A Function For A Virtual Table +** +** ^(Virtual tables can provide alternative implementations of functions +** using the [xFindFunction] method of the [virtual table module]. +** But global versions of those functions +** must exist in order to be overloaded.)^ +** +** ^(This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created.)^ ^The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a placeholder function that can be overloaded +** by a [virtual table]. +*/ +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB +** KEYWORDS: {BLOB handle} {BLOB handles} +** +** An instance of this object represents an open BLOB on which +** [sqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [sqlite3_blob_open()] +** and destroyed by [sqlite3_blob_close()]. +** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the BLOB. +** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O +** +** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located +** in row iRow, column zColumn, table zTable in database zDb; +** in other words, the same BLOB that would be selected by: +** +**
    +**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
    +** 
    )^ +** +** ^If the flags parameter is non-zero, then the BLOB is opened for read +** and write access. ^If it is zero, the BLOB is opened for read access. +** ^It is not possible to open a column that is part of an index or primary +** key for writing. ^If [foreign key constraints] are enabled, it is +** not possible to open a column that is part of a [child key] for writing. +** +** ^Note that the database name is not the filename that contains +** the database but rather the symbolic name of the database that +** appears after the AS keyword when the database is connected using [ATTACH]. +** ^For the main database file, the database name is "main". +** ^For TEMP tables, the database name is "temp". +** +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written +** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set +** to be a null pointer.)^ +** ^This function sets the [database connection] error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related +** functions. ^Note that the *ppBlob variable is always initialized in a +** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob +** regardless of the success or failure of this routine. +** +** ^(If the row that a BLOB handle points to is modified by an +** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects +** then the BLOB handle is marked as "expired". +** This is true if any column of the row is changed, even a column +** other than the one the BLOB handle is open on.)^ +** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. +** ^(Changes written into a BLOB prior to the BLOB expiring are not +** rolled back by the expiration of the BLOB. Such changes will eventually +** commit if the transaction continues to completion.)^ +** +** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** the opened blob. ^The size of a blob may not be changed by this +** interface. Use the [UPDATE] SQL command to change the size of a +** blob. +** +** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** and the built-in [zeroblob] SQL function can be used, if desired, +** to create an empty, zero-filled blob in which to read or write using +** this interface. +** +** To avoid a resource leak, every open [BLOB handle] should eventually +** be released by a call to [sqlite3_blob_close()]. +*/ +int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Move a BLOB Handle to a New Row +** +** ^This function is used to move an existing blob handle so that it points +** to a different row of the same database table. ^The new row is identified +** by the rowid value passed as the second argument. Only the row can be +** changed. ^The database, table and column on which the blob handle is open +** remain the same. Moving an existing blob handle to a new row can be +** faster than closing the existing handle and opening a new one. +** +** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** it must exist and there must be either a blob or text value stored in +** the nominated column.)^ ^If the new row is not present in the table, or if +** it does not contain a blob or text value, or if another error occurs, an +** SQLite error code is returned and the blob handle is considered aborted. +** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or +** [sqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** always returns zero. +** +** ^This function sets the database handle error code and message. +*/ +SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); + +/* +** CAPI3REF: Close A BLOB Handle +** +** ^Closes an open [BLOB handle]. +** +** ^Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in [autocommit mode]. +** ^If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. +** +** ^(Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. Any errors that occur during +** closing are reported as a non-zero return value.)^ +** +** ^(The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed.)^ +** +** ^Calling this routine with a null pointer (such as would be returned +** by a failed call to [sqlite3_blob_open()]) is a harmless no-op. +*/ +int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB +** +** ^Returns the size in bytes of the BLOB accessible via the +** successfully opened [BLOB handle] in its only argument. ^The +** incremental blob I/O routines can only read or overwriting existing +** blob content; they cannot change the size of a blob. +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +*/ +int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally +** +** ^(This function is used to read data from an open [BLOB handle] into a +** caller-supplied buffer. N bytes of data are copied into buffer Z +** from the open BLOB, starting at offset iOffset.)^ +** +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is +** less than zero, [SQLITE_ERROR] is returned and no data is read. +** ^The size of the blob (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to read from an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. +** +** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_write()]. +*/ +int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally +** +** ^This function is used to write data into an open [BLOB handle] from a +** caller-supplied buffer. ^N bytes of data are copied from the buffer Z +** into the open BLOB, starting at offset iOffset. +** +** ^If the [BLOB handle] passed as the first argument was not opened for +** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** this function returns [SQLITE_READONLY]. +** +** ^This function may only modify the contents of the BLOB; it is +** not possible to increase the size of a BLOB using this API. +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is written. ^If N is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** The size of the BLOB (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to write to an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred +** before the [BLOB handle] expired are not rolled back by the +** expiration of the handle, though of course those changes might +** have been overwritten by the statement that expired the BLOB handle +** or by other independent statements. +** +** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_read()]. +*/ +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most SQLite builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^Names are case sensitive. +** ^Names are zero-terminated UTF-8 strings. +** ^If there is no match, a NULL pointer is returned. +** ^If zVfsName is NULL then the default VFS is returned. +** +** ^New VFSes are registered with sqlite3_vfs_register(). +** ^Each new VFS becomes the default VFS if the makeDflt flag is set. +** ^The same VFS can be registered multiple times without injury. +** ^To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. If two different VFSes with the +** same name are registered, the behavior is undefined. If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^(If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary.)^ +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. ^(The following +** implementations are available in the SQLite core: +** +**
      +**
    • SQLITE_MUTEX_PTHREADS +**
    • SQLITE_MUTEX_W32 +**
    • SQLITE_MUTEX_NOOP +**
    )^ +** +** ^The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and +** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix +** and Windows. +** +** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. In this case the +** application must supply a custom mutex implementation using the +** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function +** before calling sqlite3_initialize() or any other public sqlite3_ +** function that calls sqlite3_initialize().)^ +** +** ^The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^If it returns NULL +** that means that a mutex could not be allocated. ^SQLite +** will unwind its stack and return an error. ^(The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
      +**
    • SQLITE_MUTEX_FAST +**
    • SQLITE_MUTEX_RECURSIVE +**
    • SQLITE_MUTEX_STATIC_MASTER +**
    • SQLITE_MUTEX_STATIC_MEM +**
    • SQLITE_MUTEX_STATIC_MEM2 +**
    • SQLITE_MUTEX_STATIC_PRNG +**
    • SQLITE_MUTEX_STATIC_LRU +**
    • SQLITE_MUTEX_STATIC_LRU2 +**
    )^ +** +** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) +** cause sqlite3_mutex_alloc() to create +** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. ^SQLite will only request a recursive mutex in +** cases where it really needs one. ^If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return +** a pointer to a static preexisting mutex. ^Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. ^But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +** +** ^The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. ^SQLite is careful to deallocate every +** dynamic mutex that it allocates. The dynamic mutexes must not be in +** use when they are deallocated. Attempting to deallocate a static +** mutex results in undefined behavior. ^SQLite never deallocates +** a static mutex. +** +** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. ^If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** upon successful entry. ^(Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter.)^ ^(If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** SQLite will never exhibit +** such behavior in its own use of mutexes.)^ +** +** ^(Some systems (for example, Windows 95) do not support the operation +** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** will always return SQLITE_BUSY. The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^ +** +** ^The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. ^(The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. SQLite will +** never do either.)^ +** +** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or +** sqlite3_mutex_leave() is a NULL pointer, then all three routines +** behave as no-ops. +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int); +void sqlite3_mutex_free(sqlite3_mutex*); +void sqlite3_mutex_enter(sqlite3_mutex*); +int sqlite3_mutex_try(sqlite3_mutex*); +void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Methods Object +** +** An instance of this structure defines the low-level routines +** used to allocate and use mutexes. +** +** Usually, the default mutex implementations provided by SQLite are +** sufficient, however the user has the option of substituting a custom +** implementation for specialized deployments or systems for which SQLite +** does not provide a suitable implementation. In this case, the user +** creates and populates an instance of this structure to pass +** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** Additionally, an instance of this structure can be used as an +** output variable when querying the system for the current mutex +** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. +** +** ^The xMutexInit method defined by this structure is invoked as +** part of system initialization by the sqlite3_initialize() function. +** ^The xMutexInit routine is called by SQLite exactly once for each +** effective call to [sqlite3_initialize()]. +** +** ^The xMutexEnd method defined by this structure is invoked as +** part of system shutdown by the sqlite3_shutdown() function. The +** implementation of this method is expected to release all outstanding +** resources obtained by the mutex methods implementation, especially +** those obtained by the xMutexInit method. ^The xMutexEnd() +** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** +** ^(The remaining seven methods defined by this structure (xMutexAlloc, +** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and +** xMutexNotheld) implement the following interfaces (respectively): +** +**
      +**
    • [sqlite3_mutex_alloc()]
    • +**
    • [sqlite3_mutex_free()]
    • +**
    • [sqlite3_mutex_enter()]
    • +**
    • [sqlite3_mutex_try()]
    • +**
    • [sqlite3_mutex_leave()]
    • +**
    • [sqlite3_mutex_held()]
    • +**
    • [sqlite3_mutex_notheld()]
    • +**
    )^ +** +** The only difference is that the public sqlite3_XXX functions enumerated +** above silently ignore any invocations that pass a NULL pointer instead +** of a valid mutex handle. The implementations of the methods defined +** by this structure are not required to handle this case, the results +** of passing a NULL pointer instead of a valid mutex handle are undefined +** (i.e. it is acceptable to provide an implementation that segfaults if +** it is passed a NULL pointer). +** +** The xMutexInit() method must be threadsafe. ^It must be harmless to +** invoke xMutexInit() multiple times within the same process and without +** intervening calls to xMutexEnd(). Second and subsequent calls to +** xMutexInit() must be no-ops. +** +** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory +** allocation for a static mutex. ^However xMutexAlloc() may use SQLite +** memory allocation for a fast or recursive mutex. +** +** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** called, but only if the prior call to xMutexInit returned SQLITE_OK. +** If xMutexInit fails in any way, it is expected to clean up after itself +** prior to returning. +*/ +typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; +struct sqlite3_mutex_methods { + int (*xMutexInit)(void); + int (*xMutexEnd)(void); + sqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(sqlite3_mutex *); + void (*xMutexEnter)(sqlite3_mutex *); + int (*xMutexTry)(sqlite3_mutex *); + void (*xMutexLeave)(sqlite3_mutex *); + int (*xMutexHeld)(sqlite3_mutex *); + int (*xMutexNotheld)(sqlite3_mutex *); +}; + +/* +** CAPI3REF: Mutex Verification Routines +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. ^The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. ^The SQLite core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. ^External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** ^These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. +** +** ^The implementation is not required to provide versions of these +** routines that actually work. If the implementation does not provide working +** versions of these routines, it should at least provide stubs that always +** return true so that one does not get spurious assertion failures. +** +** ^If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. ^The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +#ifndef NDEBUG +int sqlite3_mutex_held(sqlite3_mutex*); +int sqlite3_mutex_notheld(sqlite3_mutex*); +#endif + +/* +** CAPI3REF: Mutex Types +** +** The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. +** +** The set of static mutexes may change from one SQLite release to the +** next. Applications that override the built-in mutex logic must be +** prepared to accommodate additional static mutexes. +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ +#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ + +/* +** CAPI3REF: Retrieve the mutex for a database connection +** +** ^This interface returns a pointer the [sqlite3_mutex] object that +** serializes access to the [database connection] given in the argument +** when the [threading mode] is Serialized. +** ^If the [threading mode] is Single-thread or Multi-thread then this +** routine returns a NULL pointer. +*/ +sqlite3_mutex *sqlite3_db_mutex(sqlite3*); + +/* +** CAPI3REF: Low-Level Control Of Database Files +** +** ^The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. ^The +** name of the database is "main" for the main database or "temp" for the +** TEMP database, or the name that appears after the AS keyword for +** databases that are added using the [ATTACH] SQL command. +** ^A NULL pointer can be used in place of "main" to refer to the +** main database file. +** ^The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. ^The return value of the xFileControl +** method becomes the return value of this routine. +** +** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes +** a pointer to the underlying [sqlite3_file] object to be written into +** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER +** case is a short-circuit path which does not actually invoke the +** underlying sqlite3_io_methods.xFileControl method. +** +** ^If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. ^This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. The underlying xFileControl method might +** also return SQLITE_ERROR. There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** CAPI3REF: Testing Interface +** +** ^The sqlite3_test_control() interface is used to read out internal +** state of SQLite and to inject faults into SQLite for testing +** purposes. ^The first parameter is an operation code that determines +** the number, meaning, and operation of all subsequent parameters. +** +** This interface is not for use by applications. It exists solely +** for verifying the correct operation of the SQLite library. Depending +** on how the SQLite library is compiled, this interface might not exist. +** +** The details of the operation codes, their meanings, the parameters +** they take, and what they do are all subject to change without notice. +** Unlike most of the SQLite API, this function is not guaranteed to +** operate consistently from one release to the next. +*/ +int sqlite3_test_control(int op, ...); + +/* +** CAPI3REF: Testing Interface Operation Codes +** +** These constants are the valid operation code parameters used +** as the first argument to [sqlite3_test_control()]. +** +** These parameters and their meanings are subject to change +** without notice. These values are for testing purposes only. +** Applications should not use any of these parameters or the +** [sqlite3_test_control()] interface. +*/ +#define SQLITE_TESTCTRL_FIRST 5 +#define SQLITE_TESTCTRL_PRNG_SAVE 5 +#define SQLITE_TESTCTRL_PRNG_RESTORE 6 +#define SQLITE_TESTCTRL_PRNG_RESET 7 +#define SQLITE_TESTCTRL_BITVEC_TEST 8 +#define SQLITE_TESTCTRL_FAULT_INSTALL 9 +#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 +#define SQLITE_TESTCTRL_PENDING_BYTE 11 +#define SQLITE_TESTCTRL_ASSERT 12 +#define SQLITE_TESTCTRL_ALWAYS 13 +#define SQLITE_TESTCTRL_RESERVE 14 +#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 +#define SQLITE_TESTCTRL_ISKEYWORD 16 +#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 +#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 +#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 +#define SQLITE_TESTCTRL_LAST 19 + +/* +** CAPI3REF: SQLite Runtime Status +** +** ^This interface is used to retrieve runtime status information +** about the performance of SQLite, and optionally to reset various +** highwater marks. ^The first argument is an integer code for +** the specific parameter to measure. ^(Recognized integer codes +** are of the form [status parameters | SQLITE_STATUS_...].)^ +** ^The current value of the parameter is returned into *pCurrent. +** ^The highest recorded value is returned in *pHighwater. ^If the +** resetFlag is true, then the highest record value is reset after +** *pHighwater is written. ^(Some parameters do not record the highest +** value. For those parameters +** nothing is written into *pHighwater and the resetFlag is ignored.)^ +** ^(Other parameters record only the highwater mark and not the current +** value. For these latter parameters nothing is written into *pCurrent.)^ +** +** ^The sqlite3_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** This routine is threadsafe but is not atomic. This routine can be +** called while other threads are running the same or different SQLite +** interfaces. However the values returned in *pCurrent and +** *pHighwater reflect the status of SQLite at different points in time +** and it is possible that another thread might change the parameter +** in between the times when *pCurrent and *pHighwater are written. +** +** See also: [sqlite3_db_status()] +*/ +int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); + + +/* +** CAPI3REF: Status Parameters +** KEYWORDS: {status parameters} +** +** These integer constants designate various run-time status parameters +** that can be returned by [sqlite3_status()]. +** +**
    +** [[SQLITE_STATUS_MEMORY_USED]] ^(
    SQLITE_STATUS_MEMORY_USED
    +**
    This parameter is the current amount of memory checked out +** using [sqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [sqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Scratch memory +** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache +** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in +** this parameter. The amount returned is the sum of the allocation +** sizes as reported by the xSize method in [sqlite3_mem_methods].
    )^ +** +** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
    SQLITE_STATUS_MALLOC_SIZE
    +**
    This parameter records the largest memory allocation request +** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** internal equivalents). Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
    )^ +** +** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
    SQLITE_STATUS_MALLOC_COUNT
    +**
    This parameter records the number of separate memory allocations +** currently checked out.
    )^ +** +** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
    SQLITE_STATUS_PAGECACHE_USED
    +**
    This parameter returns the number of pages used out of the +** [pagecache memory allocator] that was configured using +** [SQLITE_CONFIG_PAGECACHE]. The +** value returned is in pages, not in bytes.
    )^ +** +** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] +** ^(
    SQLITE_STATUS_PAGECACHE_OVERFLOW
    +**
    This parameter returns the number of bytes of page cache +** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] +** buffer and where forced to overflow to [sqlite3_malloc()]. The +** returned value includes allocations that overflowed because they +** where too large (they were larger than the "sz" parameter to +** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because +** no space was left in the page cache.
    )^ +** +** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
    SQLITE_STATUS_PAGECACHE_SIZE
    +**
    This parameter records the largest memory allocation request +** handed to [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
    )^ +** +** [[SQLITE_STATUS_SCRATCH_USED]] ^(
    SQLITE_STATUS_SCRATCH_USED
    +**
    This parameter returns the number of allocations used out of the +** [scratch memory allocator] configured using +** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not +** in bytes. Since a single thread may only have one scratch allocation +** outstanding at time, this parameter also reports the number of threads +** using scratch memory at the same time.
    )^ +** +** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
    SQLITE_STATUS_SCRATCH_OVERFLOW
    +**
    This parameter returns the number of bytes of scratch memory +** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] +** buffer and where forced to overflow to [sqlite3_malloc()]. The values +** returned include overflows because the requested allocation was too +** larger (that is, because the requested allocation was larger than the +** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer +** slots were available. +**
    )^ +** +** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(
    SQLITE_STATUS_SCRATCH_SIZE
    +**
    This parameter records the largest memory allocation request +** handed to [scratch memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
    )^ +** +** [[SQLITE_STATUS_PARSER_STACK]] ^(
    SQLITE_STATUS_PARSER_STACK
    +**
    This parameter records the deepest parser stack. It is only +** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
    )^ +**
    +** +** New status parameters may be added from time to time. +*/ +#define SQLITE_STATUS_MEMORY_USED 0 +#define SQLITE_STATUS_PAGECACHE_USED 1 +#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 +#define SQLITE_STATUS_SCRATCH_USED 3 +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 +#define SQLITE_STATUS_MALLOC_SIZE 5 +#define SQLITE_STATUS_PARSER_STACK 6 +#define SQLITE_STATUS_PAGECACHE_SIZE 7 +#define SQLITE_STATUS_SCRATCH_SIZE 8 +#define SQLITE_STATUS_MALLOC_COUNT 9 + +/* +** CAPI3REF: Database Connection Status +** +** ^This interface is used to retrieve runtime status information +** about a single [database connection]. ^The first argument is the +** database connection object to be interrogated. ^The second argument +** is an integer constant, taken from the set of +** [SQLITE_DBSTATUS options], that +** determines the parameter to interrogate. The set of +** [SQLITE_DBSTATUS options] is likely +** to grow in future releases of SQLite. +** +** ^The current value of the requested parameter is written into *pCur +** and the highest instantaneous value is written into *pHiwtr. ^If +** the resetFlg is true, then the highest instantaneous value is +** reset back down to the current value. +** +** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +*/ +int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + +/* +** CAPI3REF: Status Parameters for database connections +** KEYWORDS: {SQLITE_DBSTATUS options} +** +** These constants are the available integer "verbs" that can be passed as +** the second argument to the [sqlite3_db_status()] interface. +** +** New verbs may be added in future releases of SQLite. Existing verbs +** might be discontinued. Applications should check the return code from +** [sqlite3_db_status()] to make sure that the call worked. +** The [sqlite3_db_status()] interface will return a non-zero error code +** if a discontinued or unsupported verb is invoked. +** +**
    +** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
    SQLITE_DBSTATUS_LOOKASIDE_USED
    +**
    This parameter returns the number of lookaside memory slots currently +** checked out.
    )^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
    SQLITE_DBSTATUS_LOOKASIDE_HIT
    +**
    This parameter returns the number malloc attempts that were +** satisfied using lookaside memory. Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] +** ^(
    SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
    +**
    This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to the amount of +** memory requested being larger than the lookaside slot size. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] +** ^(
    SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
    +**
    This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to all lookaside +** memory already being in use. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
    SQLITE_DBSTATUS_CACHE_USED
    +**
    This parameter returns the approximate number of of bytes of heap +** memory used by all pager caches associated with the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** +** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
    SQLITE_DBSTATUS_SCHEMA_USED
    +**
    This parameter returns the approximate number of of bytes of heap +** memory used to store the schema for all databases associated +** with the connection - main, temp, and any [ATTACH]-ed databases.)^ +** ^The full amount of memory used by the schemas is reported, even if the +** schema memory is shared with other database connections due to +** [shared cache mode] being enabled. +** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** +** [[SQLITE_DBSTATUS_STMT_USED]] ^(
    SQLITE_DBSTATUS_STMT_USED
    +**
    This parameter returns the approximate number of of bytes of heap +** and lookaside memory used by all prepared statements associated with +** the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. +**
    +** +** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
    SQLITE_DBSTATUS_CACHE_HIT
    +**
    This parameter returns the number of pager cache hits that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT +** is always 0. +**
    +** +** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
    SQLITE_DBSTATUS_CACHE_MISS
    +**
    This parameter returns the number of pager cache misses that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS +** is always 0. +**
    +** +** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
    SQLITE_DBSTATUS_CACHE_WRITE
    +**
    This parameter returns the number of dirty cache entries that have +** been written to disk. Specifically, the number of pages written to the +** wal file in wal mode databases, or the number of pages written to the +** database file in rollback mode databases. Any pages written as part of +** transaction rollback or database recovery operations are not included. +** If an IO or other error occurs while writing a page to disk, the effect +** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The +** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. +**
    +** +** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(
    SQLITE_DBSTATUS_DEFERRED_FKS
    +**
    This parameter returns zero for the current value if and only if +** all foreign key constraints (deferred or immediate) have been +** resolved.)^ ^The highwater mark is always 0. +**
    +**
    +*/ +#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 +#define SQLITE_DBSTATUS_CACHE_USED 1 +#define SQLITE_DBSTATUS_SCHEMA_USED 2 +#define SQLITE_DBSTATUS_STMT_USED 3 +#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 +#define SQLITE_DBSTATUS_CACHE_HIT 7 +#define SQLITE_DBSTATUS_CACHE_MISS 8 +#define SQLITE_DBSTATUS_CACHE_WRITE 9 +#define SQLITE_DBSTATUS_DEFERRED_FKS 10 +#define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */ + + +/* +** CAPI3REF: Prepared Statement Status +** +** ^(Each prepared statement maintains various +** [SQLITE_STMTSTATUS counters] that measure the number +** of times it has performed specific operations.)^ These counters can +** be used to monitor the performance characteristics of the prepared +** statements. For example, if the number of table steps greatly exceeds +** the number of table searches or result rows, that would tend to indicate +** that the prepared statement is using a full table scan rather than +** an index. +** +** ^(This interface is used to retrieve and reset counter values from +** a [prepared statement]. The first argument is the prepared statement +** object to be interrogated. The second argument +** is an integer code for a specific [SQLITE_STMTSTATUS counter] +** to be interrogated.)^ +** ^The current value of the requested counter is returned. +** ^If the resetFlg is true, then the counter is reset to zero after this +** interface call returns. +** +** See also: [sqlite3_status()] and [sqlite3_db_status()]. +*/ +int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + +/* +** CAPI3REF: Status Parameters for prepared statements +** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} +** +** These preprocessor macros define integer codes that name counter +** values associated with the [sqlite3_stmt_status()] interface. +** The meanings of the various counters are as follows: +** +**
    +** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
    SQLITE_STMTSTATUS_FULLSCAN_STEP
    +**
    ^This is the number of times that SQLite has stepped forward in +** a table as part of a full table scan. Large numbers for this counter +** may indicate opportunities for performance improvement through +** careful use of indices.
    +** +** [[SQLITE_STMTSTATUS_SORT]]
    SQLITE_STMTSTATUS_SORT
    +**
    ^This is the number of sort operations that have occurred. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance through careful use of indices.
    +** +** [[SQLITE_STMTSTATUS_AUTOINDEX]]
    SQLITE_STMTSTATUS_AUTOINDEX
    +**
    ^This is the number of rows inserted into transient indices that +** were created automatically in order to help joins run faster. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance by adding permanent indices that do not +** need to be reinitialized each time the statement is run.
    +** +** [[SQLITE_STMTSTATUS_VM_STEP]]
    SQLITE_STMTSTATUS_VM_STEP
    +**
    ^This is the number of virtual machine operations executed +** by the prepared statement if that number is less than or equal +** to 2147483647. The number of virtual machine operations can be +** used as a proxy for the total work done by the prepared statement. +** If the number of virtual machine operations exceeds 2147483647 +** then the value returned by this statement status code is undefined. +**
    +**
    +*/ +#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 +#define SQLITE_STMTSTATUS_SORT 2 +#define SQLITE_STMTSTATUS_AUTOINDEX 3 +#define SQLITE_STMTSTATUS_VM_STEP 4 + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache type is opaque. It is implemented by +** the pluggable module. The SQLite core has no knowledge of +** its size or internal structure and never deals with the +** sqlite3_pcache object except by holding and passing pointers +** to the object. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache sqlite3_pcache; + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache_page object represents a single page in the +** page cache. The page cache will allocate instances of this +** object. Various methods of the page cache use pointers to instances +** of this object as parameters or as their return value. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache_page sqlite3_pcache_page; +struct sqlite3_pcache_page { + void *pBuf; /* The content of the page */ + void *pExtra; /* Extra information associated with the page */ +}; + +/* +** CAPI3REF: Application Defined Page Cache. +** KEYWORDS: {page cache} +** +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can +** register an alternative page cache implementation by passing in an +** instance of the sqlite3_pcache_methods2 structure.)^ +** In many applications, most of the heap memory allocated by +** SQLite is used for the page cache. +** By implementing a +** custom page cache using this API, an application can better control +** the amount of memory consumed by SQLite, the way in which +** that memory is allocated and released, and the policies used to +** determine exactly which parts of a database file are cached and for +** how long. +** +** The alternative page cache mechanism is an +** extreme measure that is only needed by the most demanding applications. +** The built-in page cache is recommended for most uses. +** +** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an +** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** the application may discard the parameter after the call to +** [sqlite3_config()] returns.)^ +** +** [[the xInit() page cache method]] +** ^(The xInit() method is called once for each effective +** call to [sqlite3_initialize()])^ +** (usually only once during the lifetime of the process). ^(The xInit() +** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ +** The intent of the xInit() method is to set up global data structures +** required by the custom page cache implementation. +** ^(If the xInit() method is NULL, then the +** built-in default page cache is used instead of the application defined +** page cache.)^ +** +** [[the xShutdown() page cache method]] +** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** It can be used to clean up +** any outstanding resources before process shutdown, if required. +** ^The xShutdown() method may be NULL. +** +** ^SQLite automatically serializes calls to the xInit method, +** so the xInit method need not be threadsafe. ^The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. All other methods must be threadsafe +** in multithreaded applications. +** +** ^SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +** +** [[the xCreate() page cache methods]] +** ^SQLite invokes the xCreate() method to construct a new cache instance. +** SQLite will typically create one cache instance for each open database file, +** though this is not guaranteed. ^The +** first parameter, szPage, is the size in bytes of the pages that must +** be allocated by the cache. ^szPage will always a power of two. ^The +** second parameter szExtra is a number of bytes of extra storage +** associated with each page cache entry. ^The szExtra parameter will +** a number less than 250. SQLite will use the +** extra szExtra bytes on each page to store metadata about the underlying +** database page on disk. The value passed into szExtra depends +** on the SQLite version, the target platform, and how SQLite was compiled. +** ^The third argument to xCreate(), bPurgeable, is true if the cache being +** created will be used to cache database pages of a file stored on disk, or +** false if it is used for an in-memory database. The cache implementation +** does not have to do anything special based with the value of bPurgeable; +** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will +** never invoke xUnpin() except to deliberately delete a page. +** ^In other words, calls to xUnpin() on a cache with bPurgeable set to +** false will always have the "discard" flag set to true. +** ^Hence, a cache created with bPurgeable false will +** never contain any unpinned pages. +** +** [[the xCachesize() page cache method]] +** ^(The xCachesize() method may be called at any time by SQLite to set the +** suggested maximum cache-size (number of pages stored by) the cache +** instance passed as the first argument. This is the value configured using +** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable +** parameter, the implementation is not required to do anything with this +** value; it is advisory only. +** +** [[the xPagecount() page cache methods]] +** The xPagecount() method must return the number of pages currently +** stored in the cache, both pinned and unpinned. +** +** [[the xFetch() page cache methods]] +** The xFetch() method locates a page in the cache and returns a pointer to +** an sqlite3_pcache_page object associated with that page, or a NULL pointer. +** The pBuf element of the returned sqlite3_pcache_page object will be a +** pointer to a buffer of szPage bytes used to store the content of a +** single database page. The pExtra element of sqlite3_pcache_page will be +** a pointer to the szExtra bytes of extra storage that SQLite has requested +** for each entry in the page cache. +** +** The page to be fetched is determined by the key. ^The minimum key value +** is 1. After it has been retrieved using xFetch, the page is considered +** to be "pinned". +** +** If the requested page is already in the page cache, then the page cache +** implementation must return a pointer to the page buffer with its content +** intact. If the requested page is not already in the cache, then the +** cache implementation should use the value of the createFlag +** parameter to help it determined what action to take: +** +** +**
    createFlag Behavior when page is not already in cache +**
    0 Do not allocate a new page. Return NULL. +**
    1 Allocate a new page if it easy and convenient to do so. +** Otherwise return NULL. +**
    2 Make every effort to allocate a new page. Only return +** NULL if allocating a new page is effectively impossible. +**
    +** +** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite +** will only use a createFlag of 2 after a prior call with a createFlag of 1 +** failed.)^ In between the to xFetch() calls, SQLite may +** attempt to unpin one or more cache pages by spilling the content of +** pinned pages to disk and synching the operating system disk cache. +** +** [[the xUnpin() page cache method]] +** ^xUnpin() is called by SQLite with a pointer to a currently pinned page +** as its second argument. If the third parameter, discard, is non-zero, +** then the page must be evicted from the cache. +** ^If the discard parameter is +** zero, then the page may be discarded or retained at the discretion of +** page cache implementation. ^The page cache implementation +** may choose to evict unpinned pages at any time. +** +** The cache must not perform any reference counting. A single +** call to xUnpin() unpins the page regardless of the number of prior calls +** to xFetch(). +** +** [[the xRekey() page cache methods]] +** The xRekey() method is used to change the key value associated with the +** page passed as the second argument. If the cache +** previously contains an entry associated with newKey, it must be +** discarded. ^Any prior cache entry associated with newKey is guaranteed not +** to be pinned. +** +** When SQLite calls the xTruncate() method, the cache must discard all +** existing cache entries with page numbers (keys) greater than or equal +** to the value of the iLimit parameter passed to xTruncate(). If any +** of these pages are pinned, they are implicitly unpinned, meaning that +** they can be safely discarded. +** +** [[the xDestroy() page cache method]] +** ^The xDestroy() method is used to delete a cache allocated by xCreate(). +** All resources associated with the specified cache should be freed. ^After +** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] +** handle invalid, and will not use it with any other sqlite3_pcache_methods2 +** functions. +** +** [[the xShrink() page cache method]] +** ^SQLite invokes the xShrink() method when it wants the page cache to +** free up as much of heap memory as possible. The page cache implementation +** is not obligated to free any memory, but well-behaved implementations should +** do their best. +*/ +typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; +struct sqlite3_pcache_methods2 { + int iVersion; + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); + void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, + unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); + void (*xShrink)(sqlite3_pcache*); +}; + +/* +** This is the obsolete pcache_methods object that has now been replaced +** by sqlite3_pcache_methods2. This object is not used by SQLite. It is +** retained in the header file for backwards compatibility only. +*/ +typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; +struct sqlite3_pcache_methods { + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, void*, int discard); + void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); +}; + + +/* +** CAPI3REF: Online Backup Object +** +** The sqlite3_backup object records state information about an ongoing +** online backup operation. ^The sqlite3_backup object is created by +** a call to [sqlite3_backup_init()] and is destroyed by a call to +** [sqlite3_backup_finish()]. +** +** See Also: [Using the SQLite Online Backup API] +*/ +typedef struct sqlite3_backup sqlite3_backup; + +/* +** CAPI3REF: Online Backup API. +** +** The backup API copies the content of one database into another. +** It is useful either for creating backups of databases or +** for copying in-memory databases to or from persistent files. +** +** See Also: [Using the SQLite Online Backup API] +** +** ^SQLite holds a write transaction open on the destination database file +** for the duration of the backup operation. +** ^The source database is read-locked only while it is being read; +** it is not locked continuously for the entire backup operation. +** ^Thus, the backup may be performed on a live source database without +** preventing other database connections from +** reading or writing to the source database while the backup is underway. +** +** ^(To perform a backup operation: +**
      +**
    1. sqlite3_backup_init() is called once to initialize the +** backup, +**
    2. sqlite3_backup_step() is called one or more times to transfer +** the data between the two databases, and finally +**
    3. sqlite3_backup_finish() is called to release all resources +** associated with the backup operation. +**
    )^ +** There should be exactly one call to sqlite3_backup_finish() for each +** successful call to sqlite3_backup_init(). +** +** [[sqlite3_backup_init()]] sqlite3_backup_init() +** +** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** [database connection] associated with the destination database +** and the database name, respectively. +** ^The database name is "main" for the main database, "temp" for the +** temporary database, or the name specified after the AS keyword in +** an [ATTACH] statement for an attached database. +** ^The S and M arguments passed to +** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** and database name of the source database, respectively. +** ^The source and destination [database connections] (parameters S and D) +** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** an error. +** +** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** returned and an error code and error message are stored in the +** destination [database connection] D. +** ^The error code and message for the failed call to sqlite3_backup_init() +** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or +** [sqlite3_errmsg16()] functions. +** ^A successful call to sqlite3_backup_init() returns a pointer to an +** [sqlite3_backup] object. +** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and +** sqlite3_backup_finish() functions to perform the specified backup +** operation. +** +** [[sqlite3_backup_step()]] sqlite3_backup_step() +** +** ^Function sqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [sqlite3_backup] object B. +** ^If N is negative, all remaining source pages are copied. +** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** are still more pages to be copied, then the function returns [SQLITE_OK]. +** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** from source to destination, then it returns [SQLITE_DONE]. +** ^If an error occurs while running sqlite3_backup_step(B,N), +** then an [error code] is returned. ^As well as [SQLITE_OK] and +** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. +** +** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +**
      +**
    1. the destination database was opened read-only, or +**
    2. the destination database is using write-ahead-log journaling +** and the destination and source page sizes differ, or +**
    3. the destination database is an in-memory database and the +** destination and source page sizes differ. +**
    )^ +** +** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then +** the [sqlite3_busy_handler | busy-handler function] +** is invoked (if one is specified). ^If the +** busy-handler returns non-zero before the lock is available, then +** [SQLITE_BUSY] is returned to the caller. ^In this case the call to +** sqlite3_backup_step() can be retried later. ^If the source +** [database connection] +** is being used to write to the source database when sqlite3_backup_step() +** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this +** case the call to sqlite3_backup_step() can be retried later on. ^(If +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or +** [SQLITE_READONLY] is returned, then +** there is no point in retrying the call to sqlite3_backup_step(). These +** errors are considered fatal.)^ The application must accept +** that the backup operation has failed and pass the backup operation handle +** to the sqlite3_backup_finish() to release associated resources. +** +** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** on the destination file. ^The exclusive lock is not released until either +** sqlite3_backup_finish() is called or the backup operation is complete +** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** sqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the sqlite3_backup_step() call. +** ^Because the source database is not locked between calls to +** sqlite3_backup_step(), the source database may be modified mid-way +** through the backup process. ^If the source database is modified by an +** external process or via a database connection other than the one being +** used by the backup operation, then the backup will be automatically +** restarted by the next call to sqlite3_backup_step(). ^If the source +** database is modified by the using the same database connection as is used +** by the backup operation, then the backup database is automatically +** updated at the same time. +** +** [[sqlite3_backup_finish()]] sqlite3_backup_finish() +** +** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** application wishes to abandon the backup operation, the application +** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). +** ^The sqlite3_backup_finish() interfaces releases all +** resources associated with the [sqlite3_backup] object. +** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** active write-transaction on the destination database is rolled back. +** The [sqlite3_backup] object is invalid +** and may not be used following a call to sqlite3_backup_finish(). +** +** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no +** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() completed. +** ^If an out-of-memory condition or IO error occurred during any prior +** sqlite3_backup_step() call on the same [sqlite3_backup] object, then +** sqlite3_backup_finish() returns the corresponding [error code]. +** +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** is not a permanent error and does not affect the return value of +** sqlite3_backup_finish(). +** +** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]] +** sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** +** ^Each call to sqlite3_backup_step() sets two values inside +** the [sqlite3_backup] object: the number of pages still to be backed +** up and the total number of pages in the source database file. +** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces +** retrieve these two values, respectively. +** +** ^The values returned by these functions are only updated by +** sqlite3_backup_step(). ^If the source database is modified during a backup +** operation, then the values are not updated to account for any extra +** pages that need to be updated or the size of the source database file +** changing. +** +** Concurrent Usage of Database Handles +** +** ^The source [database connection] may be used by the application for other +** purposes while a backup operation is underway or being initialized. +** ^If SQLite is compiled and configured to support threadsafe database +** connections, then the source database connection may be used concurrently +** from within other threads. +** +** However, the application must guarantee that the destination +** [database connection] is not passed to any other API (by any thread) after +** sqlite3_backup_init() is called and before the corresponding call to +** sqlite3_backup_finish(). SQLite does not currently check to see +** if the application incorrectly accesses the destination [database connection] +** and so no error code is reported, but the operations may malfunction +** nevertheless. Use of the destination database connection while a +** backup is in progress might also also cause a mutex deadlock. +** +** If running in [shared cache mode], the application must +** guarantee that the shared cache used by the destination database +** is not accessed while the backup is running. In practice this means +** that the application must guarantee that the disk file being +** backed up to is not accessed by any connection within the process, +** not just the specific connection that was passed to sqlite3_backup_init(). +** +** The [sqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to sqlite3_backup_step(). +** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** APIs are not strictly speaking threadsafe. If they are invoked at the +** same time as another thread is invoking sqlite3_backup_step() it is +** possible that they return invalid values. +*/ +sqlite3_backup *sqlite3_backup_init( + sqlite3 *pDest, /* Destination database handle */ + const char *zDestName, /* Destination database name */ + sqlite3 *pSource, /* Source database handle */ + const char *zSourceName /* Source database name */ +); +int sqlite3_backup_step(sqlite3_backup *p, int nPage); +int sqlite3_backup_finish(sqlite3_backup *p); +int sqlite3_backup_remaining(sqlite3_backup *p); +int sqlite3_backup_pagecount(sqlite3_backup *p); + +/* +** CAPI3REF: Unlock Notification +** +** ^When running in shared-cache mode, a database operation may fail with +** an [SQLITE_LOCKED] error if the required locks on the shared-cache or +** individual tables within the shared-cache cannot be obtained. See +** [SQLite Shared-Cache Mode] for a description of shared-cache locking. +** ^This API may be used to register a callback that SQLite will invoke +** when the connection currently holding the required lock relinquishes it. +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. +** +** See Also: [Using the SQLite Unlock Notification Feature]. +** +** ^Shared-cache locks are released when a database connection concludes +** its current transaction, either by committing it or rolling it back. +** +** ^When a connection (known as the blocked connection) fails to obtain a +** shared-cache lock and SQLITE_LOCKED is returned to the caller, the +** identity of the database connection (the blocking connection) that +** has locked the required resource is stored internally. ^After an +** application receives an SQLITE_LOCKED error, it may call the +** sqlite3_unlock_notify() method with the blocked connection handle as +** the first argument to register for a callback that will be invoked +** when the blocking connections current transaction is concluded. ^The +** callback is invoked from within the [sqlite3_step] or [sqlite3_close] +** call that concludes the blocking connections transaction. +** +** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** there is a chance that the blocking connection will have already +** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** If this happens, then the specified callback is invoked immediately, +** from within the call to sqlite3_unlock_notify().)^ +** +** ^If the blocked connection is attempting to obtain a write-lock on a +** shared-cache table, and more than one other connection currently holds +** a read-lock on the same table, then SQLite arbitrarily selects one of +** the other connections to use as the blocking connection. +** +** ^(There may be at most one unlock-notify callback registered by a +** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection already has a registered unlock-notify callback, +** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** called with a NULL pointer as its second argument, then any existing +** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback may also be canceled by closing the blocked +** connection using [sqlite3_close()]. +** +** The unlock-notify callback is not reentrant. If an application invokes +** any sqlite3_xxx API functions from within an unlock-notify callback, a +** crash or deadlock may be the result. +** +** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** returns SQLITE_OK. +** +** Callback Invocation Details +** +** When an unlock-notify callback is registered, the application provides a +** single void* pointer that is passed to the callback when it is invoked. +** However, the signature of the callback function allows SQLite to pass +** it an array of void* context pointers. The first argument passed to +** an unlock-notify callback is a pointer to an array of void* pointers, +** and the second is the number of entries in the array. +** +** When a blocking connections transaction is concluded, there may be +** more than one blocked connection that has registered for an unlock-notify +** callback. ^If two or more such blocked connections have specified the +** same callback function, then instead of invoking the callback function +** multiple times, it is invoked once with the set of void* context pointers +** specified by the blocked connections bundled together into an array. +** This gives the application an opportunity to prioritize any actions +** related to the set of unblocked database connections. +** +** Deadlock Detection +** +** Assuming that after registering for an unlock-notify callback a +** database waits for the callback to be issued before taking any further +** action (a reasonable assumption), then using this API may cause the +** application to deadlock. For example, if connection X is waiting for +** connection Y's transaction to be concluded, and similarly connection +** Y is waiting on connection X's transaction, then neither connection +** will proceed and the system may remain deadlocked indefinitely. +** +** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to sqlite3_unlock_notify() would put the +** system in a deadlocked state, then SQLITE_LOCKED is returned and no +** unlock-notify callback is registered. The system is said to be in +** a deadlocked state if connection A has registered for an unlock-notify +** callback on the conclusion of connection B's transaction, and connection +** B has itself registered for an unlock-notify callback when connection +** A's transaction is concluded. ^Indirect deadlock is also detected, so +** the system is also considered to be deadlocked if connection B has +** registered for an unlock-notify callback on the conclusion of connection +** C's transaction, where connection C is waiting on connection A. ^Any +** number of levels of indirection are allowed. +** +** The "DROP TABLE" Exception +** +** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call sqlite3_unlock_notify(). There is however, +** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, +** SQLite checks if there are any currently executing SELECT statements +** that belong to the same connection. If there are, SQLITE_LOCKED is +** returned. In this case there is no "blocking connection", so invoking +** sqlite3_unlock_notify() results in the unlock-notify callback being +** invoked immediately. If the application then re-attempts the "DROP TABLE" +** or "DROP INDEX" query, an infinite loop might be the result. +** +** One way around this problem is to check the extended error code returned +** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in +** the special "DROP TABLE/INDEX" case, the extended error code is just +** SQLITE_LOCKED.)^ +*/ +int sqlite3_unlock_notify( + sqlite3 *pBlocked, /* Waiting connection */ + void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ + void *pNotifyArg /* Argument to pass to xNotify */ +); + + +/* +** CAPI3REF: String Comparison +** +** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications +** and extensions to compare the contents of two buffers containing UTF-8 +** strings in a case-independent fashion, using the same definition of "case +** independence" that SQLite uses internally when comparing identifiers. +*/ +int sqlite3_stricmp(const char *, const char *); +int sqlite3_strnicmp(const char *, const char *, int); + +/* +** CAPI3REF: String Globbing +* +** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches +** the glob pattern P, and it returns non-zero if string X does not match +** the glob pattern P. ^The definition of glob pattern matching used in +** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the +** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case +** sensitive. +** +** Note that this routine returns zero on a match and non-zero if the strings +** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +*/ +int sqlite3_strglob(const char *zGlob, const char *zStr); + +/* +** CAPI3REF: Error Logging Interface +** +** ^The [sqlite3_log()] interface writes a message into the [error log] +** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^If logging is enabled, the zFormat string and subsequent arguments are +** used with [sqlite3_snprintf()] to generate the final output string. +** +** The sqlite3_log() interface is intended for use by extensions such as +** virtual tables, collating functions, and SQL functions. While there is +** nothing to prevent an application from calling sqlite3_log(), doing so +** is considered bad form. +** +** The zFormat string must not be NULL. +** +** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** will not use dynamically allocated memory. The log message is stored in +** a fixed-length buffer on the stack. If the log message is longer than +** a few hundred characters, it will be truncated to the length of the +** buffer. +*/ +void sqlite3_log(int iErrCode, const char *zFormat, ...); + +/* +** CAPI3REF: Write-Ahead Log Commit Hook +** +** ^The [sqlite3_wal_hook()] function is used to register a callback that +** will be invoked each time a database connection commits data to a +** [write-ahead log] (i.e. whenever a transaction is committed in +** [journal_mode | journal_mode=WAL mode]). +** +** ^The callback is invoked by SQLite after the commit has taken place and +** the associated write-lock on the database released, so the implementation +** may read, write or [checkpoint] the database as required. +** +** ^The first parameter passed to the callback function when it is invoked +** is a copy of the third parameter passed to sqlite3_wal_hook() when +** registering the callback. ^The second is a copy of the database handle. +** ^The third parameter is the name of the database that was written to - +** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter +** is the number of pages currently in the write-ahead log file, +** including those that were just committed. +** +** The callback function should normally return [SQLITE_OK]. ^If an error +** code is returned, that error will propagate back up through the +** SQLite code base to cause the statement that provoked the callback +** to report an error, though the commit will have still occurred. If the +** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value +** that does not correspond to any valid SQLite error code, the results +** are undefined. +** +** A single database handle may have at most a single write-ahead log callback +** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** previously registered write-ahead log callback. ^Note that the +** [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will +** those overwrite any prior [sqlite3_wal_hook()] settings. +*/ +void *sqlite3_wal_hook( + sqlite3*, + int(*)(void *,sqlite3*,const char*,int), + void* +); + +/* +** CAPI3REF: Configure an auto-checkpoint +** +** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [sqlite3_wal_hook()] that causes any database on [database connection] D +** to automatically [checkpoint] +** after committing a transaction if there are N or +** more frames in the [write-ahead log] file. ^Passing zero or +** a negative value as the nFrame parameter disables automatic +** checkpoints entirely. +** +** ^The callback registered by this function replaces any existing callback +** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback +** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** configured by this function. +** +** ^The [wal_autocheckpoint pragma] can be used to invoke this interface +** from SQL. +** +** ^Every new [database connection] defaults to having the auto-checkpoint +** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] +** pages. The use of this interface +** is only necessary if the default setting is found to be suboptimal +** for a particular application. +*/ +int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); + +/* +** CAPI3REF: Checkpoint a database +** +** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X +** on [database connection] D to be [checkpointed]. ^If X is NULL or an +** empty string, then a checkpoint is run on all databases of +** connection D. ^If the database connection D is not in +** [WAL | write-ahead log mode] then this interface is a harmless no-op. +** +** ^The [wal_checkpoint pragma] can be used to invoke this interface +** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] can be used to cause this interface to be +** run whenever the WAL reaches a certain size threshold. +** +** See also: [sqlite3_wal_checkpoint_v2()] +*/ +int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Checkpoint a database +** +** Run a checkpoint operation on WAL database zDb attached to database +** handle db. The specific operation is determined by the value of the +** eMode parameter: +** +**
    +**
    SQLITE_CHECKPOINT_PASSIVE
    +** Checkpoint as many frames as possible without waiting for any database +** readers or writers to finish. Sync the db file if all frames in the log +** are checkpointed. This mode is the same as calling +** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked. +** +**
    SQLITE_CHECKPOINT_FULL
    +** This mode blocks (calls the busy-handler callback) until there is no +** database writer and all readers are reading from the most recent database +** snapshot. It then checkpoints all frames in the log file and syncs the +** database file. This call blocks database writers while it is running, +** but not database readers. +** +**
    SQLITE_CHECKPOINT_RESTART
    +** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after +** checkpointing the log file it blocks (calls the busy-handler callback) +** until all readers are reading from the database file only. This ensures +** that the next client to write to the database file restarts the log file +** from the beginning. This call blocks database writers while it is running, +** but not database readers. +**
    +** +** If pnLog is not NULL, then *pnLog is set to the total number of frames in +** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to +** the total number of checkpointed frames (including any that were already +** checkpointed when this function is called). *pnLog and *pnCkpt may be +** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK. +** If no values are available because of an error, they are both set to -1 +** before returning to communicate this to the caller. +** +** All calls obtain an exclusive "checkpoint" lock on the database file. If +** any other process is running a checkpoint operation at the same time, the +** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a +** busy-handler configured, it will not be invoked in this case. +** +** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive +** "writer" lock on the database file. If the writer lock cannot be obtained +** immediately, and a busy-handler is configured, it is invoked and the writer +** lock retried until either the busy-handler returns 0 or the lock is +** successfully obtained. The busy-handler is also invoked while waiting for +** database readers as described above. If the busy-handler returns 0 before +** the writer lock is obtained or while waiting for database readers, the +** checkpoint operation proceeds from that point in the same way as +** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible +** without blocking any further. SQLITE_BUSY is returned in this case. +** +** If parameter zDb is NULL or points to a zero length string, then the +** specified operation is attempted on all WAL databases. In this case the +** values written to output parameters *pnLog and *pnCkpt are undefined. If +** an SQLITE_BUSY error is encountered when processing one or more of the +** attached WAL databases, the operation is still attempted on any remaining +** attached databases and SQLITE_BUSY is returned to the caller. If any other +** error occurs while processing an attached database, processing is abandoned +** and the error code returned to the caller immediately. If no error +** (SQLITE_BUSY or otherwise) is encountered while processing the attached +** databases, SQLITE_OK is returned. +** +** If database zDb is the name of an attached database that is not in WAL +** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If +** zDb is not NULL (or a zero length string) and is not the name of any +** attached database, SQLITE_ERROR is returned to the caller. +*/ +int sqlite3_wal_checkpoint_v2( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + int *pnLog, /* OUT: Size of WAL log in frames */ + int *pnCkpt /* OUT: Total number of frames checkpointed */ +); + +/* +** CAPI3REF: Checkpoint operation parameters +** +** These constants can be used as the 3rd parameter to +** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()] +** documentation for additional information about the meaning and use of +** each of these values. +*/ +#define SQLITE_CHECKPOINT_PASSIVE 0 +#define SQLITE_CHECKPOINT_FULL 1 +#define SQLITE_CHECKPOINT_RESTART 2 + +/* +** CAPI3REF: Virtual Table Interface Configuration +** +** This function may be called by either the [xConnect] or [xCreate] method +** of a [virtual table] implementation to configure +** various facets of the virtual table interface. +** +** If this interface is invoked outside the context of an xConnect or +** xCreate virtual table method then the behavior is undefined. +** +** At present, there is only one option that may be configured using +** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options +** may be added in the future. +*/ +int sqlite3_vtab_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Virtual Table Configuration Options +** +** These macros define the various options to the +** [sqlite3_vtab_config()] interface that [virtual table] implementations +** can use to customize and optimize their behavior. +** +**
    +**
    SQLITE_VTAB_CONSTRAINT_SUPPORT +**
    Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, +** where X is an integer. If X is zero, then the [virtual table] whose +** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not +** support constraints. In this configuration (which is the default) if +** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire +** statement is rolled back as if [ON CONFLICT | OR ABORT] had been +** specified as part of the users SQL statement, regardless of the actual +** ON CONFLICT mode specified. +** +** If X is non-zero, then the virtual table implementation guarantees +** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before +** any modifications to internal or persistent data structures have been made. +** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite +** is able to roll back a statement or database transaction, and abandon +** or continue processing the current SQL statement as appropriate. +** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns +** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode +** had been ABORT. +** +** Virtual table implementations that are required to handle OR REPLACE +** must do so within the [xUpdate] method. If a call to the +** [sqlite3_vtab_on_conflict()] function indicates that the current ON +** CONFLICT policy is REPLACE, the virtual table implementation should +** silently replace the appropriate rows within the xUpdate callback and +** return SQLITE_OK. Or, if this is not possible, it may return +** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT +** constraint handling. +**
    +*/ +#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 + +/* +** CAPI3REF: Determine The Virtual Table Conflict Policy +** +** This function may only be called from within a call to the [xUpdate] method +** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The +** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], +** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode +** of the SQL statement that triggered the call to the [xUpdate] method of the +** [virtual table]. +*/ +int sqlite3_vtab_on_conflict(sqlite3 *); + +/* +** CAPI3REF: Conflict resolution modes +** +** These constants are returned by [sqlite3_vtab_on_conflict()] to +** inform a [virtual table] implementation what the [ON CONFLICT] mode +** is for the SQL statement being evaluated. +** +** Note that the [SQLITE_IGNORE] constant is also used as a potential +** return value from the [sqlite3_set_authorizer()] callback and that +** [SQLITE_ABORT] is also a [result code]. +*/ +#define SQLITE_ROLLBACK 1 +/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ +#define SQLITE_FAIL 3 +/* #define SQLITE_ABORT 4 // Also an error code */ +#define SQLITE_REPLACE 5 + + + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#ifdef __cplusplus +} /* End of the 'extern "C"' block */ +#endif +#endif /* _SQLITE3_H_ */ diff --git a/components/external/SQLite-3.8.1/src/sqlite3.rc b/components/external/SQLite-3.8.1/src/sqlite3.rc new file mode 100644 index 0000000000000000000000000000000000000000..aedbb63ebd9cb4a042b69b5bf42f93c000911339 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/sqlite3.rc @@ -0,0 +1,73 @@ +/* +** 2012 September 2 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code and resources that are specific to Windows. +*/ + +#if !defined(_WIN32_WCE) +#include "winresrc.h" +#else +#include "windows.h" +#endif /* !defined(_WIN32_WCE) */ + +#if !defined(VS_FF_NONE) +# define VS_FF_NONE 0x00000000L +#endif /* !defined(VS_FF_NONE) */ + +#include "sqlite3.h" +#include "sqlite3rc.h" + +/* + * English (U.S.) resources + */ + +#if defined(_WIN32) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif /* defined(_WIN32) */ + +/* + * Version + */ + +VS_VERSION_INFO VERSIONINFO + FILEVERSION SQLITE_RESOURCE_VERSION + PRODUCTVERSION SQLITE_RESOURCE_VERSION + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#if defined(_DEBUG) + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS VS_FF_NONE +#endif /* defined(_DEBUG) */ + FILEOS VOS__WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE VFT2_UNKNOWN +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "SQLite Development Team" + VALUE "FileDescription", "SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine." + VALUE "FileVersion", SQLITE_VERSION + VALUE "InternalName", "sqlite3" + VALUE "LegalCopyright", "http://www.sqlite.org/copyright.html" + VALUE "ProductName", "SQLite" + VALUE "ProductVersion", SQLITE_VERSION + VALUE "SourceId", SQLITE_SOURCE_ID + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 0x4b0 + END +END diff --git a/components/external/SQLite-3.8.1/src/sqlite3ext.h b/components/external/SQLite-3.8.1/src/sqlite3ext.h new file mode 100644 index 0000000000000000000000000000000000000000..ecf93f62f6cd9c3bf5044e781556e06fe011ec0e --- /dev/null +++ b/components/external/SQLite-3.8.1/src/sqlite3ext.h @@ -0,0 +1,487 @@ +/* +** 2006 June 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the SQLite interface for use by +** shared libraries that want to be imported as extensions into +** an SQLite instance. Shared libraries that intend to be loaded +** as extensions by SQLite should #include this file instead of +** sqlite3.h. +*/ +#ifndef _SQLITE3EXT_H_ +#define _SQLITE3EXT_H_ +#include "sqlite3.h" + +typedef struct sqlite3_api_routines sqlite3_api_routines; + +/* +** The following structure holds pointers to all of the SQLite API +** routines. +** +** WARNING: In order to maintain backwards compatibility, add new +** interfaces to the end of this structure only. If you insert new +** interfaces in the middle of this structure, then older different +** versions of SQLite will not be able to load each others' shared +** libraries! +*/ +struct sqlite3_api_routines { + void * (*aggregate_context)(sqlite3_context*,int nBytes); + int (*aggregate_count)(sqlite3_context*); + int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); + int (*bind_double)(sqlite3_stmt*,int,double); + int (*bind_int)(sqlite3_stmt*,int,int); + int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); + int (*bind_null)(sqlite3_stmt*,int); + int (*bind_parameter_count)(sqlite3_stmt*); + int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); + const char * (*bind_parameter_name)(sqlite3_stmt*,int); + int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); + int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); + int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); + int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); + int (*busy_timeout)(sqlite3*,int ms); + int (*changes)(sqlite3*); + int (*close)(sqlite3*); + int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, + int eTextRep,const char*)); + int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, + int eTextRep,const void*)); + const void * (*column_blob)(sqlite3_stmt*,int iCol); + int (*column_bytes)(sqlite3_stmt*,int iCol); + int (*column_bytes16)(sqlite3_stmt*,int iCol); + int (*column_count)(sqlite3_stmt*pStmt); + const char * (*column_database_name)(sqlite3_stmt*,int); + const void * (*column_database_name16)(sqlite3_stmt*,int); + const char * (*column_decltype)(sqlite3_stmt*,int i); + const void * (*column_decltype16)(sqlite3_stmt*,int); + double (*column_double)(sqlite3_stmt*,int iCol); + int (*column_int)(sqlite3_stmt*,int iCol); + sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); + const char * (*column_name)(sqlite3_stmt*,int); + const void * (*column_name16)(sqlite3_stmt*,int); + const char * (*column_origin_name)(sqlite3_stmt*,int); + const void * (*column_origin_name16)(sqlite3_stmt*,int); + const char * (*column_table_name)(sqlite3_stmt*,int); + const void * (*column_table_name16)(sqlite3_stmt*,int); + const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); + const void * (*column_text16)(sqlite3_stmt*,int iCol); + int (*column_type)(sqlite3_stmt*,int iCol); + sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); + void * (*commit_hook)(sqlite3*,int(*)(void*),void*); + int (*complete)(const char*sql); + int (*complete16)(const void*sql); + int (*create_collation)(sqlite3*,const char*,int,void*, + int(*)(void*,int,const void*,int,const void*)); + int (*create_collation16)(sqlite3*,const void*,int,void*, + int(*)(void*,int,const void*,int,const void*)); + int (*create_function)(sqlite3*,const char*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*)); + int (*create_function16)(sqlite3*,const void*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*)); + int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); + int (*data_count)(sqlite3_stmt*pStmt); + sqlite3 * (*db_handle)(sqlite3_stmt*); + int (*declare_vtab)(sqlite3*,const char*); + int (*enable_shared_cache)(int); + int (*errcode)(sqlite3*db); + const char * (*errmsg)(sqlite3*); + const void * (*errmsg16)(sqlite3*); + int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); + int (*expired)(sqlite3_stmt*); + int (*finalize)(sqlite3_stmt*pStmt); + void (*free)(void*); + void (*free_table)(char**result); + int (*get_autocommit)(sqlite3*); + void * (*get_auxdata)(sqlite3_context*,int); + int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); + int (*global_recover)(void); + void (*interruptx)(sqlite3*); + sqlite_int64 (*last_insert_rowid)(sqlite3*); + const char * (*libversion)(void); + int (*libversion_number)(void); + void *(*malloc)(int); + char * (*mprintf)(const char*,...); + int (*open)(const char*,sqlite3**); + int (*open16)(const void*,sqlite3**); + int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); + void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); + void *(*realloc)(void*,int); + int (*reset)(sqlite3_stmt*pStmt); + void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_double)(sqlite3_context*,double); + void (*result_error)(sqlite3_context*,const char*,int); + void (*result_error16)(sqlite3_context*,const void*,int); + void (*result_int)(sqlite3_context*,int); + void (*result_int64)(sqlite3_context*,sqlite_int64); + void (*result_null)(sqlite3_context*); + void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); + void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_value)(sqlite3_context*,sqlite3_value*); + void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); + int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, + const char*,const char*),void*); + void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); + char * (*snprintf)(int,char*,const char*,...); + int (*step)(sqlite3_stmt*); + int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, + char const**,char const**,int*,int*,int*); + void (*thread_cleanup)(void); + int (*total_changes)(sqlite3*); + void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); + int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); + void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, + sqlite_int64),void*); + void * (*user_data)(sqlite3_context*); + const void * (*value_blob)(sqlite3_value*); + int (*value_bytes)(sqlite3_value*); + int (*value_bytes16)(sqlite3_value*); + double (*value_double)(sqlite3_value*); + int (*value_int)(sqlite3_value*); + sqlite_int64 (*value_int64)(sqlite3_value*); + int (*value_numeric_type)(sqlite3_value*); + const unsigned char * (*value_text)(sqlite3_value*); + const void * (*value_text16)(sqlite3_value*); + const void * (*value_text16be)(sqlite3_value*); + const void * (*value_text16le)(sqlite3_value*); + int (*value_type)(sqlite3_value*); + char *(*vmprintf)(const char*,va_list); + /* Added ??? */ + int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); + /* Added by 3.3.13 */ + int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + int (*clear_bindings)(sqlite3_stmt*); + /* Added by 3.4.1 */ + int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, + void (*xDestroy)(void *)); + /* Added by 3.5.0 */ + int (*bind_zeroblob)(sqlite3_stmt*,int,int); + int (*blob_bytes)(sqlite3_blob*); + int (*blob_close)(sqlite3_blob*); + int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, + int,sqlite3_blob**); + int (*blob_read)(sqlite3_blob*,void*,int,int); + int (*blob_write)(sqlite3_blob*,const void*,int,int); + int (*create_collation_v2)(sqlite3*,const char*,int,void*, + int(*)(void*,int,const void*,int,const void*), + void(*)(void*)); + int (*file_control)(sqlite3*,const char*,int,void*); + sqlite3_int64 (*memory_highwater)(int); + sqlite3_int64 (*memory_used)(void); + sqlite3_mutex *(*mutex_alloc)(int); + void (*mutex_enter)(sqlite3_mutex*); + void (*mutex_free)(sqlite3_mutex*); + void (*mutex_leave)(sqlite3_mutex*); + int (*mutex_try)(sqlite3_mutex*); + int (*open_v2)(const char*,sqlite3**,int,const char*); + int (*release_memory)(int); + void (*result_error_nomem)(sqlite3_context*); + void (*result_error_toobig)(sqlite3_context*); + int (*sleep)(int); + void (*soft_heap_limit)(int); + sqlite3_vfs *(*vfs_find)(const char*); + int (*vfs_register)(sqlite3_vfs*,int); + int (*vfs_unregister)(sqlite3_vfs*); + int (*xthreadsafe)(void); + void (*result_zeroblob)(sqlite3_context*,int); + void (*result_error_code)(sqlite3_context*,int); + int (*test_control)(int, ...); + void (*randomness)(int,void*); + sqlite3 *(*context_db_handle)(sqlite3_context*); + int (*extended_result_codes)(sqlite3*,int); + int (*limit)(sqlite3*,int,int); + sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); + const char *(*sql)(sqlite3_stmt*); + int (*status)(int,int*,int*,int); + int (*backup_finish)(sqlite3_backup*); + sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); + int (*backup_pagecount)(sqlite3_backup*); + int (*backup_remaining)(sqlite3_backup*); + int (*backup_step)(sqlite3_backup*,int); + const char *(*compileoption_get)(int); + int (*compileoption_used)(const char*); + int (*create_function_v2)(sqlite3*,const char*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*)); + int (*db_config)(sqlite3*,int,...); + sqlite3_mutex *(*db_mutex)(sqlite3*); + int (*db_status)(sqlite3*,int,int*,int*,int); + int (*extended_errcode)(sqlite3*); + void (*log)(int,const char*,...); + sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); + const char *(*sourceid)(void); + int (*stmt_status)(sqlite3_stmt*,int,int); + int (*strnicmp)(const char*,const char*,int); + int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); + int (*wal_autocheckpoint)(sqlite3*,int); + int (*wal_checkpoint)(sqlite3*,const char*); + void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); + int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); + int (*vtab_config)(sqlite3*,int op,...); + int (*vtab_on_conflict)(sqlite3*); + /* Version 3.7.16 and later */ + int (*close_v2)(sqlite3*); + const char *(*db_filename)(sqlite3*,const char*); + int (*db_readonly)(sqlite3*,const char*); + int (*db_release_memory)(sqlite3*); + const char *(*errstr)(int); + int (*stmt_busy)(sqlite3_stmt*); + int (*stmt_readonly)(sqlite3_stmt*); + int (*stricmp)(const char*,const char*); + int (*uri_boolean)(const char*,const char*,int); + sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); + const char *(*uri_parameter)(const char*,const char*); + char *(*vsnprintf)(int,char*,const char*,va_list); + int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); +}; + +/* +** The following macros redefine the API routines so that they are +** redirected throught the global sqlite3_api structure. +** +** This header file is also used by the loadext.c source file +** (part of the main SQLite library - not an extension) so that +** it can get access to the sqlite3_api_routines structure +** definition. But the main library does not want to redefine +** the API. So the redefinition macros are only valid if the +** SQLITE_CORE macros is undefined. +*/ +#ifndef SQLITE_CORE +#define sqlite3_aggregate_context sqlite3_api->aggregate_context +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_aggregate_count sqlite3_api->aggregate_count +#endif +#define sqlite3_bind_blob sqlite3_api->bind_blob +#define sqlite3_bind_double sqlite3_api->bind_double +#define sqlite3_bind_int sqlite3_api->bind_int +#define sqlite3_bind_int64 sqlite3_api->bind_int64 +#define sqlite3_bind_null sqlite3_api->bind_null +#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count +#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index +#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name +#define sqlite3_bind_text sqlite3_api->bind_text +#define sqlite3_bind_text16 sqlite3_api->bind_text16 +#define sqlite3_bind_value sqlite3_api->bind_value +#define sqlite3_busy_handler sqlite3_api->busy_handler +#define sqlite3_busy_timeout sqlite3_api->busy_timeout +#define sqlite3_changes sqlite3_api->changes +#define sqlite3_close sqlite3_api->close +#define sqlite3_collation_needed sqlite3_api->collation_needed +#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 +#define sqlite3_column_blob sqlite3_api->column_blob +#define sqlite3_column_bytes sqlite3_api->column_bytes +#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 +#define sqlite3_column_count sqlite3_api->column_count +#define sqlite3_column_database_name sqlite3_api->column_database_name +#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 +#define sqlite3_column_decltype sqlite3_api->column_decltype +#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 +#define sqlite3_column_double sqlite3_api->column_double +#define sqlite3_column_int sqlite3_api->column_int +#define sqlite3_column_int64 sqlite3_api->column_int64 +#define sqlite3_column_name sqlite3_api->column_name +#define sqlite3_column_name16 sqlite3_api->column_name16 +#define sqlite3_column_origin_name sqlite3_api->column_origin_name +#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 +#define sqlite3_column_table_name sqlite3_api->column_table_name +#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 +#define sqlite3_column_text sqlite3_api->column_text +#define sqlite3_column_text16 sqlite3_api->column_text16 +#define sqlite3_column_type sqlite3_api->column_type +#define sqlite3_column_value sqlite3_api->column_value +#define sqlite3_commit_hook sqlite3_api->commit_hook +#define sqlite3_complete sqlite3_api->complete +#define sqlite3_complete16 sqlite3_api->complete16 +#define sqlite3_create_collation sqlite3_api->create_collation +#define sqlite3_create_collation16 sqlite3_api->create_collation16 +#define sqlite3_create_function sqlite3_api->create_function +#define sqlite3_create_function16 sqlite3_api->create_function16 +#define sqlite3_create_module sqlite3_api->create_module +#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 +#define sqlite3_data_count sqlite3_api->data_count +#define sqlite3_db_handle sqlite3_api->db_handle +#define sqlite3_declare_vtab sqlite3_api->declare_vtab +#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache +#define sqlite3_errcode sqlite3_api->errcode +#define sqlite3_errmsg sqlite3_api->errmsg +#define sqlite3_errmsg16 sqlite3_api->errmsg16 +#define sqlite3_exec sqlite3_api->exec +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_expired sqlite3_api->expired +#endif +#define sqlite3_finalize sqlite3_api->finalize +#define sqlite3_free sqlite3_api->free +#define sqlite3_free_table sqlite3_api->free_table +#define sqlite3_get_autocommit sqlite3_api->get_autocommit +#define sqlite3_get_auxdata sqlite3_api->get_auxdata +#define sqlite3_get_table sqlite3_api->get_table +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_global_recover sqlite3_api->global_recover +#endif +#define sqlite3_interrupt sqlite3_api->interruptx +#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid +#define sqlite3_libversion sqlite3_api->libversion +#define sqlite3_libversion_number sqlite3_api->libversion_number +#define sqlite3_malloc sqlite3_api->malloc +#define sqlite3_mprintf sqlite3_api->mprintf +#define sqlite3_open sqlite3_api->open +#define sqlite3_open16 sqlite3_api->open16 +#define sqlite3_prepare sqlite3_api->prepare +#define sqlite3_prepare16 sqlite3_api->prepare16 +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_profile sqlite3_api->profile +#define sqlite3_progress_handler sqlite3_api->progress_handler +#define sqlite3_realloc sqlite3_api->realloc +#define sqlite3_reset sqlite3_api->reset +#define sqlite3_result_blob sqlite3_api->result_blob +#define sqlite3_result_double sqlite3_api->result_double +#define sqlite3_result_error sqlite3_api->result_error +#define sqlite3_result_error16 sqlite3_api->result_error16 +#define sqlite3_result_int sqlite3_api->result_int +#define sqlite3_result_int64 sqlite3_api->result_int64 +#define sqlite3_result_null sqlite3_api->result_null +#define sqlite3_result_text sqlite3_api->result_text +#define sqlite3_result_text16 sqlite3_api->result_text16 +#define sqlite3_result_text16be sqlite3_api->result_text16be +#define sqlite3_result_text16le sqlite3_api->result_text16le +#define sqlite3_result_value sqlite3_api->result_value +#define sqlite3_rollback_hook sqlite3_api->rollback_hook +#define sqlite3_set_authorizer sqlite3_api->set_authorizer +#define sqlite3_set_auxdata sqlite3_api->set_auxdata +#define sqlite3_snprintf sqlite3_api->snprintf +#define sqlite3_step sqlite3_api->step +#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata +#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup +#define sqlite3_total_changes sqlite3_api->total_changes +#define sqlite3_trace sqlite3_api->trace +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings +#endif +#define sqlite3_update_hook sqlite3_api->update_hook +#define sqlite3_user_data sqlite3_api->user_data +#define sqlite3_value_blob sqlite3_api->value_blob +#define sqlite3_value_bytes sqlite3_api->value_bytes +#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 +#define sqlite3_value_double sqlite3_api->value_double +#define sqlite3_value_int sqlite3_api->value_int +#define sqlite3_value_int64 sqlite3_api->value_int64 +#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type +#define sqlite3_value_text sqlite3_api->value_text +#define sqlite3_value_text16 sqlite3_api->value_text16 +#define sqlite3_value_text16be sqlite3_api->value_text16be +#define sqlite3_value_text16le sqlite3_api->value_text16le +#define sqlite3_value_type sqlite3_api->value_type +#define sqlite3_vmprintf sqlite3_api->vmprintf +#define sqlite3_overload_function sqlite3_api->overload_function +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_clear_bindings sqlite3_api->clear_bindings +#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob +#define sqlite3_blob_bytes sqlite3_api->blob_bytes +#define sqlite3_blob_close sqlite3_api->blob_close +#define sqlite3_blob_open sqlite3_api->blob_open +#define sqlite3_blob_read sqlite3_api->blob_read +#define sqlite3_blob_write sqlite3_api->blob_write +#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 +#define sqlite3_file_control sqlite3_api->file_control +#define sqlite3_memory_highwater sqlite3_api->memory_highwater +#define sqlite3_memory_used sqlite3_api->memory_used +#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc +#define sqlite3_mutex_enter sqlite3_api->mutex_enter +#define sqlite3_mutex_free sqlite3_api->mutex_free +#define sqlite3_mutex_leave sqlite3_api->mutex_leave +#define sqlite3_mutex_try sqlite3_api->mutex_try +#define sqlite3_open_v2 sqlite3_api->open_v2 +#define sqlite3_release_memory sqlite3_api->release_memory +#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem +#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig +#define sqlite3_sleep sqlite3_api->sleep +#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit +#define sqlite3_vfs_find sqlite3_api->vfs_find +#define sqlite3_vfs_register sqlite3_api->vfs_register +#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister +#define sqlite3_threadsafe sqlite3_api->xthreadsafe +#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob +#define sqlite3_result_error_code sqlite3_api->result_error_code +#define sqlite3_test_control sqlite3_api->test_control +#define sqlite3_randomness sqlite3_api->randomness +#define sqlite3_context_db_handle sqlite3_api->context_db_handle +#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes +#define sqlite3_limit sqlite3_api->limit +#define sqlite3_next_stmt sqlite3_api->next_stmt +#define sqlite3_sql sqlite3_api->sql +#define sqlite3_status sqlite3_api->status +#define sqlite3_backup_finish sqlite3_api->backup_finish +#define sqlite3_backup_init sqlite3_api->backup_init +#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount +#define sqlite3_backup_remaining sqlite3_api->backup_remaining +#define sqlite3_backup_step sqlite3_api->backup_step +#define sqlite3_compileoption_get sqlite3_api->compileoption_get +#define sqlite3_compileoption_used sqlite3_api->compileoption_used +#define sqlite3_create_function_v2 sqlite3_api->create_function_v2 +#define sqlite3_db_config sqlite3_api->db_config +#define sqlite3_db_mutex sqlite3_api->db_mutex +#define sqlite3_db_status sqlite3_api->db_status +#define sqlite3_extended_errcode sqlite3_api->extended_errcode +#define sqlite3_log sqlite3_api->log +#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 +#define sqlite3_sourceid sqlite3_api->sourceid +#define sqlite3_stmt_status sqlite3_api->stmt_status +#define sqlite3_strnicmp sqlite3_api->strnicmp +#define sqlite3_unlock_notify sqlite3_api->unlock_notify +#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint +#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint +#define sqlite3_wal_hook sqlite3_api->wal_hook +#define sqlite3_blob_reopen sqlite3_api->blob_reopen +#define sqlite3_vtab_config sqlite3_api->vtab_config +#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict +/* Version 3.7.16 and later */ +#define sqlite3_close_v2 sqlite3_api->close_v2 +#define sqlite3_db_filename sqlite3_api->db_filename +#define sqlite3_db_readonly sqlite3_api->db_readonly +#define sqlite3_db_release_memory sqlite3_api->db_release_memory +#define sqlite3_errstr sqlite3_api->errstr +#define sqlite3_stmt_busy sqlite3_api->stmt_busy +#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly +#define sqlite3_stricmp sqlite3_api->stricmp +#define sqlite3_uri_boolean sqlite3_api->uri_boolean +#define sqlite3_uri_int64 sqlite3_api->uri_int64 +#define sqlite3_uri_parameter sqlite3_api->uri_parameter +#define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf +#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 +#endif /* SQLITE_CORE */ + +#ifndef SQLITE_CORE + /* This case when the file really is being compiled as a loadable + ** extension */ +# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; +# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; +# define SQLITE_EXTENSION_INIT3 \ + extern const sqlite3_api_routines *sqlite3_api; +#else + /* This case when the file is being statically linked into the + ** application */ +# define SQLITE_EXTENSION_INIT1 /*no-op*/ +# define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */ +# define SQLITE_EXTENSION_INIT3 /*no-op*/ +#endif + +#endif /* _SQLITE3EXT_H_ */ diff --git a/components/external/SQLite-3.8.1/src/sqliteInt.h b/components/external/SQLite-3.8.1/src/sqliteInt.h new file mode 100644 index 0000000000000000000000000000000000000000..0b2dbe01647842c683bc080a1957d3eadc9ac2ac --- /dev/null +++ b/components/external/SQLite-3.8.1/src/sqliteInt.h @@ -0,0 +1,3390 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Internal interface definitions for SQLite. +** +*/ +#include "sqlite3.h" +#ifndef _SQLITEINT_H_ +#define _SQLITEINT_H_ + +/* +** These #defines should enable >2GB file support on POSIX if the +** underlying operating system supports it. If the OS lacks +** large file support, or if the OS is windows, these should be no-ops. +** +** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any +** system #includes. Hence, this block of code must be the very first +** code in all source files. +** +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch +** on the compiler command line. This is necessary if you are compiling +** on a recent machine (ex: Red Hat 7.2) but you want your code to work +** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 +** without this option, LFS is enable. But LFS does not exist in the kernel +** in Red Hat 6.0, so the code won't work. Hence, for maximum binary +** portability you should omit LFS. +** +** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. +*/ +#ifndef SQLITE_DISABLE_LFS +# define _LARGE_FILE 1 +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +# define _LARGEFILE_SOURCE 1 +#endif + +/* +** Include the configuration header output by 'configure' if we're using the +** autoconf-based build +*/ +#ifdef _HAVE_SQLITE_CONFIG_H +#include "config.h" +#endif + +#include "sqliteLimit.h" + +/* Disable nuisance warnings on Borland compilers */ +#if defined(__BORLANDC__) +#pragma warn -rch /* unreachable code */ +#pragma warn -ccc /* Condition is always true or false */ +#pragma warn -aus /* Assigned value is never used */ +#pragma warn -csu /* Comparing signed and unsigned */ +#pragma warn -spa /* Suspicious pointer arithmetic */ +#endif + +/* Needed for various definitions... */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE +#endif + +#if defined(__OpenBSD__) && !defined(_BSD_SOURCE) +# define _BSD_SOURCE +#endif + +/* +** Include standard header files as necessary +*/ +#ifdef HAVE_STDINT_H +#include +#endif +#ifdef HAVE_INTTYPES_H +#include +#endif + +/* +** The following macros are used to cast pointers to integers and +** integers to pointers. The way you do this varies from one compiler +** to the next, so we have developed the following set of #if statements +** to generate appropriate macros for a wide range of compilers. +** +** The correct "ANSI" way to do this is to use the intptr_t type. +** Unfortunately, that typedef is not available on all compilers, or +** if it is available, it requires an #include of specific headers +** that vary from one machine to the next. +** +** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on +** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). +** So we have to define the macros in different ways depending on the +** compiler. +*/ +#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ +# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) +#elif !defined(__GNUC__) /* Works for compilers other than LLVM */ +# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) +# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) +#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ +# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) +#else /* Generates a warning - but it always works */ +# define SQLITE_INT_TO_PTR(X) ((void*)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(X)) +#endif + +/* +** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. +** 0 means mutexes are permanently disable and the library is never +** threadsafe. 1 means the library is serialized which is the highest +** level of threadsafety. 2 means the library is multithreaded - multiple +** threads can use SQLite as long as no two threads try to use the same +** database connection at the same time. +** +** Older versions of SQLite used an optional THREADSAFE macro. +** We support that for legacy. +*/ +#if !defined(SQLITE_THREADSAFE) +# if defined(THREADSAFE) +# define SQLITE_THREADSAFE THREADSAFE +# else +# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ +# endif +#endif + +/* +** Powersafe overwrite is on by default. But can be turned off using +** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option. +*/ +#ifndef SQLITE_POWERSAFE_OVERWRITE +# define SQLITE_POWERSAFE_OVERWRITE 1 +#endif + +/* +** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. +** It determines whether or not the features related to +** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can +** be overridden at runtime using the sqlite3_config() API. +*/ +#if !defined(SQLITE_DEFAULT_MEMSTATUS) +# define SQLITE_DEFAULT_MEMSTATUS 1 +#endif + +/* +** Exactly one of the following macros must be defined in order to +** specify which memory allocation subsystem to use. +** +** SQLITE_SYSTEM_MALLOC // Use normal system malloc() +** SQLITE_WIN32_MALLOC // Use Win32 native heap API +** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails +** SQLITE_MEMDEBUG // Debugging version of system malloc() +** +** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the +** assert() macro is enabled, each call into the Win32 native heap subsystem +** will cause HeapValidate to be called. If heap validation should fail, an +** assertion will be triggered. +** +** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as +** the default. +*/ +#if defined(SQLITE_SYSTEM_MALLOC) \ + + defined(SQLITE_WIN32_MALLOC) \ + + defined(SQLITE_ZERO_MALLOC) \ + + defined(SQLITE_MEMDEBUG)>1 +# error "Two or more of the following compile-time configuration options\ + are defined but at most one is allowed:\ + SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\ + SQLITE_ZERO_MALLOC" +#endif +#if defined(SQLITE_SYSTEM_MALLOC) \ + + defined(SQLITE_WIN32_MALLOC) \ + + defined(SQLITE_ZERO_MALLOC) \ + + defined(SQLITE_MEMDEBUG)==0 +# define SQLITE_SYSTEM_MALLOC 1 +#endif + +/* +** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the +** sizes of memory allocations below this value where possible. +*/ +#if !defined(SQLITE_MALLOC_SOFT_LIMIT) +# define SQLITE_MALLOC_SOFT_LIMIT 1024 +#endif + +/* +** We need to define _XOPEN_SOURCE as follows in order to enable +** recursive mutexes on most Unix systems and fchmod() on OpenBSD. +** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit +** it. +*/ +#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) +# define _XOPEN_SOURCE 600 +#endif + +/* +** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that +** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true, +** make it true by defining or undefining NDEBUG. +** +** Setting NDEBUG makes the code smaller and faster by disabling the +** assert() statements in the code. So we want the default action +** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG +** is set. Thus NDEBUG becomes an opt-in rather than an opt-out +** feature. +*/ +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif +#if defined(NDEBUG) && defined(SQLITE_DEBUG) +# undef NDEBUG +#endif + +/* +** The testcase() macro is used to aid in coverage testing. When +** doing coverage testing, the condition inside the argument to +** testcase() must be evaluated both true and false in order to +** get full branch coverage. The testcase() macro is inserted +** to help ensure adequate test coverage in places where simple +** condition/decision coverage is inadequate. For example, testcase() +** can be used to make sure boundary values are tested. For +** bitmask tests, testcase() can be used to make sure each bit +** is significant and used at least once. On switch statements +** where multiple cases go to the same block of code, testcase() +** can insure that all cases are evaluated. +** +*/ +#ifdef SQLITE_COVERAGE_TEST + void sqlite3Coverage(int); +# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } +#else +# define testcase(X) +#endif + +/* +** The TESTONLY macro is used to enclose variable declarations or +** other bits of code that are needed to support the arguments +** within testcase() and assert() macros. +*/ +#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) +# define TESTONLY(X) X +#else +# define TESTONLY(X) +#endif + +/* +** Sometimes we need a small amount of code such as a variable initialization +** to setup for a later assert() statement. We do not want this code to +** appear when assert() is disabled. The following macro is therefore +** used to contain that setup code. The "VVA" acronym stands for +** "Verification, Validation, and Accreditation". In other words, the +** code within VVA_ONLY() will only run during verification processes. +*/ +#ifndef NDEBUG +# define VVA_ONLY(X) X +#else +# define VVA_ONLY(X) +#endif + +/* +** The ALWAYS and NEVER macros surround boolean expressions which +** are intended to always be true or false, respectively. Such +** expressions could be omitted from the code completely. But they +** are included in a few cases in order to enhance the resilience +** of SQLite to unexpected behavior - to make the code "self-healing" +** or "ductile" rather than being "brittle" and crashing at the first +** hint of unplanned behavior. +** +** In other words, ALWAYS and NEVER are added for defensive code. +** +** When doing coverage testing ALWAYS and NEVER are hard-coded to +** be true and false so that the unreachable code they specify will +** not be counted as untested code. +*/ +#if defined(SQLITE_COVERAGE_TEST) +# define ALWAYS(X) (1) +# define NEVER(X) (0) +#elif !defined(NDEBUG) +# define ALWAYS(X) ((X)?1:(assert(0),0)) +# define NEVER(X) ((X)?(assert(0),1):0) +#else +# define ALWAYS(X) (X) +# define NEVER(X) (X) +#endif + +/* +** Return true (non-zero) if the input is a integer that is too large +** to fit in 32-bits. This macro is used inside of various testcase() +** macros to verify that we have tested SQLite for large-file support. +*/ +#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) + +/* +** The macro unlikely() is a hint that surrounds a boolean +** expression that is usually false. Macro likely() surrounds +** a boolean expression that is usually true. These hints could, +** in theory, be used by the compiler to generate better code, but +** currently they are just comments for human readers. +*/ +#define likely(X) (X) +#define unlikely(X) (X) + +#include "hash.h" +#include "parse.h" +#include +#include +#include +#include +#include + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite_int64 +# define float sqlite_int64 +# define LONGDOUBLE_TYPE sqlite_int64 +# ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) +# endif +# define SQLITE_OMIT_DATETIME_FUNCS 1 +# define SQLITE_OMIT_TRACE 1 +# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT +# undef SQLITE_HAVE_ISNAN +#endif +#ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (1e99) +#endif + +/* +** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 +** afterward. Having this macro allows us to cause the C compiler +** to omit code used by TEMP tables without messy #ifndef statements. +*/ +#ifdef SQLITE_OMIT_TEMPDB +#define OMIT_TEMPDB 1 +#else +#define OMIT_TEMPDB 0 +#endif + +/* +** The "file format" number is an integer that is incremented whenever +** the VDBE-level file format changes. The following macros define the +** the default file format for new databases and the maximum file format +** that the library can read. +*/ +#define SQLITE_MAX_FILE_FORMAT 4 +#ifndef SQLITE_DEFAULT_FILE_FORMAT +# define SQLITE_DEFAULT_FILE_FORMAT 4 +#endif + +/* +** Determine whether triggers are recursive by default. This can be +** changed at run-time using a pragma. +*/ +#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS +# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 +#endif + +/* +** Provide a default value for SQLITE_TEMP_STORE in case it is not specified +** on the command-line +*/ +#ifndef SQLITE_TEMP_STORE +# define SQLITE_TEMP_STORE 1 +# define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */ +#endif + +/* +** GCC does not define the offsetof() macro so we'll have to do it +** ourselves. +*/ +#ifndef offsetof +#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) +#endif + +/* +** Macros to compute minimum and maximum of two numbers. +*/ +#define MIN(A,B) ((A)<(B)?(A):(B)) +#define MAX(A,B) ((A)>(B)?(A):(B)) + +/* +** Check to see if this machine uses EBCDIC. (Yes, believe it or +** not, there are still machines out there that use EBCDIC.) +*/ +#if 'A' == '\301' +# define SQLITE_EBCDIC 1 +#else +# define SQLITE_ASCII 1 +#endif + +/* +** Integers of known sizes. These typedefs might change for architectures +** where the sizes very. Preprocessor macros are available so that the +** types can be conveniently redefined at compile-type. Like this: +** +** cc '-DUINTPTR_TYPE=long long int' ... +*/ +#ifndef UINT32_TYPE +# ifdef HAVE_UINT32_T +# define UINT32_TYPE uint32_t +# else +# define UINT32_TYPE unsigned int +# endif +#endif +#ifndef UINT16_TYPE +# ifdef HAVE_UINT16_T +# define UINT16_TYPE uint16_t +# else +# define UINT16_TYPE unsigned short int +# endif +#endif +#ifndef INT16_TYPE +# ifdef HAVE_INT16_T +# define INT16_TYPE int16_t +# else +# define INT16_TYPE short int +# endif +#endif +#ifndef UINT8_TYPE +# ifdef HAVE_UINT8_T +# define UINT8_TYPE uint8_t +# else +# define UINT8_TYPE unsigned char +# endif +#endif +#ifndef INT8_TYPE +# ifdef HAVE_INT8_T +# define INT8_TYPE int8_t +# else +# define INT8_TYPE signed char +# endif +#endif +#ifndef LONGDOUBLE_TYPE +# define LONGDOUBLE_TYPE long double +#endif +typedef sqlite_int64 i64; /* 8-byte signed integer */ +typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ +typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ +typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ +typedef INT16_TYPE i16; /* 2-byte signed integer */ +typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ +typedef INT8_TYPE i8; /* 1-byte signed integer */ + +/* +** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value +** that can be stored in a u32 without loss of data. The value +** is 0x00000000ffffffff. But because of quirks of some compilers, we +** have to specify the value in the less intuitive manner shown: +*/ +#define SQLITE_MAX_U32 ((((u64)1)<<32)-1) + +/* +** The datatype used to store estimates of the number of rows in a +** table or index. This is an unsigned integer type. For 99.9% of +** the world, a 32-bit integer is sufficient. But a 64-bit integer +** can be used at compile-time if desired. +*/ +#ifdef SQLITE_64BIT_STATS + typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */ +#else + typedef u32 tRowcnt; /* 32-bit is the default */ +#endif + +/* +** Estimated quantities used for query planning are stored as 16-bit +** logarithms. For quantity X, the value stored is 10*log2(X). This +** gives a possible range of values of approximately 1.0e986 to 1e-986. +** But the allowed values are "grainy". Not every value is representable. +** For example, quantities 16 and 17 are both represented by a LogEst +** of 40. However, since LogEst quantatites are suppose to be estimates, +** not exact values, this imprecision is not a problem. +** +** "LogEst" is short for "Logarithimic Estimate". +** +** Examples: +** 1 -> 0 20 -> 43 10000 -> 132 +** 2 -> 10 25 -> 46 25000 -> 146 +** 3 -> 16 100 -> 66 1000000 -> 199 +** 4 -> 20 1000 -> 99 1048576 -> 200 +** 10 -> 33 1024 -> 100 4294967296 -> 320 +** +** The LogEst can be negative to indicate fractional values. +** Examples: +** +** 0.5 -> -10 0.1 -> -33 0.0625 -> -40 +*/ +typedef INT16_TYPE LogEst; + +/* +** Macros to determine whether the machine is big or little endian, +** evaluated at runtime. +*/ +#ifdef SQLITE_AMALGAMATION +const int sqlite3one = 1; +#else +extern const int sqlite3one; +#endif +#if defined(i386) || defined(__i386__) || defined(_M_IX86)\ + || defined(__x86_64) || defined(__x86_64__) +# define SQLITE_BIGENDIAN 0 +# define SQLITE_LITTLEENDIAN 1 +# define SQLITE_UTF16NATIVE SQLITE_UTF16LE +#else +# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) +# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) +# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) +#endif + +/* +** Constants for the largest and smallest possible 64-bit signed integers. +** These macros are designed to work correctly on both 32-bit and 64-bit +** compilers. +*/ +#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) +#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) + +/* +** Round up a number to the next larger multiple of 8. This is used +** to force 8-byte alignment on 64-bit architectures. +*/ +#define ROUND8(x) (((x)+7)&~7) + +/* +** Round down to the nearest multiple of 8 +*/ +#define ROUNDDOWN8(x) ((x)&~7) + +/* +** Assert that the pointer X is aligned to an 8-byte boundary. This +** macro is used only within assert() to verify that the code gets +** all alignment restrictions correct. +** +** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the +** underlying malloc() implemention might return us 4-byte aligned +** pointers. In that case, only verify 4-byte alignment. +*/ +#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) +#else +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) +#endif + +/* +** Disable MMAP on platforms where it is known to not work +*/ +#if defined(__OpenBSD__) || defined(__QNXNTO__) +# undef SQLITE_MAX_MMAP_SIZE +# define SQLITE_MAX_MMAP_SIZE 0 +#endif + +/* +** Default maximum size of memory used by memory-mapped I/O in the VFS +*/ +#ifdef __APPLE__ +# include +# if TARGET_OS_IPHONE +# undef SQLITE_MAX_MMAP_SIZE +# define SQLITE_MAX_MMAP_SIZE 0 +# endif +#endif +#ifndef SQLITE_MAX_MMAP_SIZE +# if defined(SQLITE_OS_RTTHREAD) +# define SQLITE_MAX_MMAP_SIZE 0 +# elif defined(__linux__) \ + || defined(_WIN32) \ + || (defined(__APPLE__) && defined(__MACH__)) \ + || defined(__sun) +# define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */ +# else +# define SQLITE_MAX_MMAP_SIZE 0 +# endif +# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */ +#endif + +/* +** The default MMAP_SIZE is zero on all platforms. Or, even if a larger +** default MMAP_SIZE is specified at compile-time, make sure that it does +** not exceed the maximum mmap size. +*/ +#ifndef SQLITE_DEFAULT_MMAP_SIZE +# define SQLITE_DEFAULT_MMAP_SIZE 0 +# define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */ +#endif +#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE +# undef SQLITE_DEFAULT_MMAP_SIZE +# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE +#endif + +/* +** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined. +** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also +** define SQLITE_ENABLE_STAT3_OR_STAT4 +*/ +#ifdef SQLITE_ENABLE_STAT4 +# undef SQLITE_ENABLE_STAT3 +# define SQLITE_ENABLE_STAT3_OR_STAT4 1 +#elif SQLITE_ENABLE_STAT3 +# define SQLITE_ENABLE_STAT3_OR_STAT4 1 +#elif SQLITE_ENABLE_STAT3_OR_STAT4 +# undef SQLITE_ENABLE_STAT3_OR_STAT4 +#endif + +/* +** An instance of the following structure is used to store the busy-handler +** callback for a given sqlite handle. +** +** The sqlite.busyHandler member of the sqlite struct contains the busy +** callback for the database handle. Each pager opened via the sqlite +** handle is passed a pointer to sqlite.busyHandler. The busy-handler +** callback is currently invoked only from within pager.c. +*/ +typedef struct BusyHandler BusyHandler; +struct BusyHandler { + int (*xFunc)(void *,int); /* The busy callback */ + void *pArg; /* First arg to busy callback */ + int nBusy; /* Incremented with each busy call */ +}; + +/* +** Name of the master database table. The master database table +** is a special table that holds the names and attributes of all +** user tables and indices. +*/ +#define MASTER_NAME "sqlite_master" +#define TEMP_MASTER_NAME "sqlite_temp_master" + +/* +** The root-page of the master database table. +*/ +#define MASTER_ROOT 1 + +/* +** The name of the schema table. +*/ +#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) + +/* +** A convenience macro that returns the number of elements in +** an array. +*/ +#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) + +/* +** Determine if the argument is a power of two +*/ +#define IsPowerOfTwo(X) (((X)&((X)-1))==0) + +/* +** The following value as a destructor means to use sqlite3DbFree(). +** The sqlite3DbFree() routine requires two parameters instead of the +** one parameter that destructors normally want. So we have to introduce +** this magic value that the code knows to handle differently. Any +** pointer will work here as long as it is distinct from SQLITE_STATIC +** and SQLITE_TRANSIENT. +*/ +#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize) + +/* +** When SQLITE_OMIT_WSD is defined, it means that the target platform does +** not support Writable Static Data (WSD) such as global and static variables. +** All variables must either be on the stack or dynamically allocated from +** the heap. When WSD is unsupported, the variable declarations scattered +** throughout the SQLite code must become constants instead. The SQLITE_WSD +** macro is used for this purpose. And instead of referencing the variable +** directly, we use its constant as a key to lookup the run-time allocated +** buffer that holds real variable. The constant is also the initializer +** for the run-time allocated buffer. +** +** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL +** macros become no-ops and have zero performance impact. +*/ +#ifdef SQLITE_OMIT_WSD + #define SQLITE_WSD const + #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) + #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) + int sqlite3_wsd_init(int N, int J); + void *sqlite3_wsd_find(void *K, int L); +#else + #define SQLITE_WSD + #define GLOBAL(t,v) v + #define sqlite3GlobalConfig sqlite3Config +#endif + +/* +** The following macros are used to suppress compiler warnings and to +** make it clear to human readers when a function parameter is deliberately +** left unused within the body of a function. This usually happens when +** a function is called via a function pointer. For example the +** implementation of an SQL aggregate step callback may not use the +** parameter indicating the number of arguments passed to the aggregate, +** if it knows that this is enforced elsewhere. +** +** When a function parameter is not used at all within the body of a function, +** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. +** However, these macros may also be used to suppress warnings related to +** parameters that may or may not be used depending on compilation options. +** For example those parameters only used in assert() statements. In these +** cases the parameters are named as per the usual conventions. +*/ +#define UNUSED_PARAMETER(x) (void)(x) +#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) + +/* +** Forward references to structures +*/ +typedef struct AggInfo AggInfo; +typedef struct AuthContext AuthContext; +typedef struct AutoincInfo AutoincInfo; +typedef struct Bitvec Bitvec; +typedef struct CollSeq CollSeq; +typedef struct Column Column; +typedef struct Db Db; +typedef struct Schema Schema; +typedef struct Expr Expr; +typedef struct ExprList ExprList; +typedef struct ExprSpan ExprSpan; +typedef struct FKey FKey; +typedef struct FuncDestructor FuncDestructor; +typedef struct FuncDef FuncDef; +typedef struct FuncDefHash FuncDefHash; +typedef struct IdList IdList; +typedef struct Index Index; +typedef struct IndexSample IndexSample; +typedef struct KeyClass KeyClass; +typedef struct KeyInfo KeyInfo; +typedef struct Lookaside Lookaside; +typedef struct LookasideSlot LookasideSlot; +typedef struct Module Module; +typedef struct NameContext NameContext; +typedef struct Parse Parse; +typedef struct RowSet RowSet; +typedef struct Savepoint Savepoint; +typedef struct Select Select; +typedef struct SelectDest SelectDest; +typedef struct SrcList SrcList; +typedef struct StrAccum StrAccum; +typedef struct Table Table; +typedef struct TableLock TableLock; +typedef struct Token Token; +typedef struct Trigger Trigger; +typedef struct TriggerPrg TriggerPrg; +typedef struct TriggerStep TriggerStep; +typedef struct UnpackedRecord UnpackedRecord; +typedef struct VTable VTable; +typedef struct VtabCtx VtabCtx; +typedef struct Walker Walker; +typedef struct WhereInfo WhereInfo; + +/* +** Defer sourcing vdbe.h and btree.h until after the "u8" and +** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque +** pointer types (i.e. FuncDef) defined above. +*/ +#include "btree.h" +#include "vdbe.h" +#include "pager.h" +#include "pcache.h" + +#include "os.h" +#include "mutex.h" + + +/* +** Each database file to be accessed by the system is an instance +** of the following structure. There are normally two of these structures +** in the sqlite.aDb[] array. aDb[0] is the main database file and +** aDb[1] is the database file used to hold temporary tables. Additional +** databases may be attached. +*/ +struct Db { + char *zName; /* Name of this database */ + Btree *pBt; /* The B*Tree structure for this database file */ + u8 safety_level; /* How aggressive at syncing data to disk */ + Schema *pSchema; /* Pointer to database schema (possibly shared) */ +}; + +/* +** An instance of the following structure stores a database schema. +** +** Most Schema objects are associated with a Btree. The exception is +** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing. +** In shared cache mode, a single Schema object can be shared by multiple +** Btrees that refer to the same underlying BtShared object. +** +** Schema objects are automatically deallocated when the last Btree that +** references them is destroyed. The TEMP Schema is manually freed by +** sqlite3_close(). +* +** A thread must be holding a mutex on the corresponding Btree in order +** to access Schema content. This implies that the thread must also be +** holding a mutex on the sqlite3 connection pointer that owns the Btree. +** For a TEMP Schema, only the connection mutex is required. +*/ +struct Schema { + int schema_cookie; /* Database schema version number for this file */ + int iGeneration; /* Generation counter. Incremented with each change */ + Hash tblHash; /* All tables indexed by name */ + Hash idxHash; /* All (named) indices indexed by name */ + Hash trigHash; /* All triggers indexed by name */ + Hash fkeyHash; /* All foreign keys by referenced table name */ + Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ + u8 file_format; /* Schema format version for this file */ + u8 enc; /* Text encoding used by this database */ + u16 flags; /* Flags associated with this schema */ + int cache_size; /* Number of pages to use in the cache */ +}; + +/* +** These macros can be used to test, set, or clear bits in the +** Db.pSchema->flags field. +*/ +#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) +#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) +#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) +#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) + +/* +** Allowed values for the DB.pSchema->flags field. +** +** The DB_SchemaLoaded flag is set after the database schema has been +** read into internal hash tables. +** +** DB_UnresetViews means that one or more views have column names that +** have been filled out. If the schema changes, these column names might +** changes and so the view will need to be reset. +*/ +#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ +#define DB_UnresetViews 0x0002 /* Some views have defined column names */ +#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ + +/* +** The number of different kinds of things that can be limited +** using the sqlite3_limit() interface. +*/ +#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1) + +/* +** Lookaside malloc is a set of fixed-size buffers that can be used +** to satisfy small transient memory allocation requests for objects +** associated with a particular database connection. The use of +** lookaside malloc provides a significant performance enhancement +** (approx 10%) by avoiding numerous malloc/free requests while parsing +** SQL statements. +** +** The Lookaside structure holds configuration information about the +** lookaside malloc subsystem. Each available memory allocation in +** the lookaside subsystem is stored on a linked list of LookasideSlot +** objects. +** +** Lookaside allocations are only allowed for objects that are associated +** with a particular database connection. Hence, schema information cannot +** be stored in lookaside because in shared cache mode the schema information +** is shared by multiple database connections. Therefore, while parsing +** schema information, the Lookaside.bEnabled flag is cleared so that +** lookaside allocations are not used to construct the schema objects. +*/ +struct Lookaside { + u16 sz; /* Size of each buffer in bytes */ + u8 bEnabled; /* False to disable new lookaside allocations */ + u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ + int nOut; /* Number of buffers currently checked out */ + int mxOut; /* Highwater mark for nOut */ + int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ + LookasideSlot *pFree; /* List of available buffers */ + void *pStart; /* First byte of available memory space */ + void *pEnd; /* First byte past end of available space */ +}; +struct LookasideSlot { + LookasideSlot *pNext; /* Next buffer in the list of free buffers */ +}; + +/* +** A hash table for function definitions. +** +** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. +** Collisions are on the FuncDef.pHash chain. +*/ +struct FuncDefHash { + FuncDef *a[23]; /* Hash table for functions */ +}; + +/* +** Each database connection is an instance of the following structure. +*/ +struct sqlite3 { + sqlite3_vfs *pVfs; /* OS Interface */ + struct Vdbe *pVdbe; /* List of active virtual machines */ + CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ + sqlite3_mutex *mutex; /* Connection mutex */ + Db *aDb; /* All backends */ + int nDb; /* Number of backends currently in use */ + int flags; /* Miscellaneous flags. See below */ + i64 lastRowid; /* ROWID of most recent insert (see above) */ + i64 szMmap; /* Default mmap_size setting */ + unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ + int errCode; /* Most recent error code (SQLITE_*) */ + int errMask; /* & result codes with this before returning */ + u16 dbOptFlags; /* Flags to enable/disable optimizations */ + u8 autoCommit; /* The auto-commit flag. */ + u8 temp_store; /* 1: file 2: memory 0: default */ + u8 mallocFailed; /* True if we have seen a malloc failure */ + u8 dfltLockMode; /* Default locking-mode for attached dbs */ + signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ + u8 suppressErr; /* Do not issue error messages if true */ + u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ + u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ + int nextPagesize; /* Pagesize after VACUUM if >0 */ + u32 magic; /* Magic number for detect library misuse */ + int nChange; /* Value returned by sqlite3_changes() */ + int nTotalChange; /* Value returned by sqlite3_total_changes() */ + int aLimit[SQLITE_N_LIMIT]; /* Limits */ + struct sqlite3InitInfo { /* Information used during initialization */ + int newTnum; /* Rootpage of table being initialized */ + u8 iDb; /* Which db file is being initialized */ + u8 busy; /* TRUE if currently initializing */ + u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ + } init; + int nVdbeActive; /* Number of VDBEs currently running */ + int nVdbeRead; /* Number of active VDBEs that read or write */ + int nVdbeWrite; /* Number of active VDBEs that read and write */ + int nVdbeExec; /* Number of nested calls to VdbeExec() */ + int nExtension; /* Number of loaded extensions */ + void **aExtension; /* Array of shared library handles */ + void (*xTrace)(void*,const char*); /* Trace function */ + void *pTraceArg; /* Argument to the trace function */ + void (*xProfile)(void*,const char*,u64); /* Profiling function */ + void *pProfileArg; /* Argument to profile function */ + void *pCommitArg; /* Argument to xCommitCallback() */ + int (*xCommitCallback)(void*); /* Invoked at every commit. */ + void *pRollbackArg; /* Argument to xRollbackCallback() */ + void (*xRollbackCallback)(void*); /* Invoked at every commit. */ + void *pUpdateArg; + void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); +#ifndef SQLITE_OMIT_WAL + int (*xWalCallback)(void *, sqlite3 *, const char *, int); + void *pWalArg; +#endif + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); + void *pCollNeededArg; + sqlite3_value *pErr; /* Most recent error message */ + union { + volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ + double notUsed1; /* Spacer */ + } u1; + Lookaside lookaside; /* Lookaside malloc configuration */ +#ifndef SQLITE_OMIT_AUTHORIZATION + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); + /* Access authorization function */ + void *pAuthArg; /* 1st argument to the access auth function */ +#endif +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + int (*xProgress)(void *); /* The progress callback */ + void *pProgressArg; /* Argument to the progress callback */ + unsigned nProgressOps; /* Number of opcodes for progress callback */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + int nVTrans; /* Allocated size of aVTrans */ + Hash aModule; /* populated by sqlite3_create_module() */ + VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ + VTable **aVTrans; /* Virtual tables with open transactions */ + VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ +#endif + FuncDefHash aFunc; /* Hash table of connection functions */ + Hash aCollSeq; /* All collating sequences */ + BusyHandler busyHandler; /* Busy callback */ + Db aDbStatic[2]; /* Static space for the 2 default backends */ + Savepoint *pSavepoint; /* List of active savepoints */ + int busyTimeout; /* Busy handler timeout, in msec */ + int nSavepoint; /* Number of non-transaction savepoints */ + int nStatement; /* Number of nested statement-transactions */ + i64 nDeferredCons; /* Net deferred constraints this transaction. */ + i64 nDeferredImmCons; /* Net deferred immediate constraints */ + int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + /* The following variables are all protected by the STATIC_MASTER + ** mutex, not by sqlite3.mutex. They are used by code in notify.c. + ** + ** When X.pUnlockConnection==Y, that means that X is waiting for Y to + ** unlock so that it can proceed. + ** + ** When X.pBlockingConnection==Y, that means that something that X tried + ** tried to do recently failed with an SQLITE_LOCKED error due to locks + ** held by Y. + */ + sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ + sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ + void *pUnlockArg; /* Argument to xUnlockNotify */ + void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ + sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ +#endif +}; + +/* +** A macro to discover the encoding of a database. +*/ +#define ENC(db) ((db)->aDb[0].pSchema->enc) + +/* +** Possible values for the sqlite3.flags. +*/ +#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ +#define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */ +#define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */ +#define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */ +#define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */ +#define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */ +#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ +#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ + /* DELETE, or UPDATE and return */ + /* the count using a callback. */ +#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ + /* result set is empty */ +#define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */ +#define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */ +#define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */ +#define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */ +#define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */ +#define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */ +#define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */ +#define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */ +#define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */ +#define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */ +#define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */ +#define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */ +#define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */ +#define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */ +#define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */ +#define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */ +#define SQLITE_QueryOnly 0x02000000 /* Disable database changes */ + + +/* +** Bits of the sqlite3.dbOptFlags field that are used by the +** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to +** selectively disable various optimizations. +*/ +#define SQLITE_QueryFlattener 0x0001 /* Query flattening */ +#define SQLITE_ColumnCache 0x0002 /* Column cache */ +#define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */ +#define SQLITE_FactorOutConst 0x0008 /* Constant factoring */ +#define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */ +#define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */ +#define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */ +#define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */ +#define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */ +#define SQLITE_Transitive 0x0200 /* Transitive constraints */ +#define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */ +#define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */ +#define SQLITE_AdjustOutEst 0x1000 /* Adjust output estimates using WHERE */ +#define SQLITE_AllOpts 0xffff /* All optimizations */ + +/* +** Macros for testing whether or not optimizations are enabled or disabled. +*/ +#ifndef SQLITE_OMIT_BUILTIN_TEST +#define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0) +#define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0) +#else +#define OptimizationDisabled(db, mask) 0 +#define OptimizationEnabled(db, mask) 1 +#endif + +/* +** Possible values for the sqlite.magic field. +** The numbers are obtained at random and have no special meaning, other +** than being distinct from one another. +*/ +#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ +#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ +#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ +#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ +#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ +#define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */ + +/* +** Each SQL function is defined by an instance of the following +** structure. A pointer to this structure is stored in the sqlite.aFunc +** hash table. When multiple functions have the same name, the hash table +** points to a linked list of these structures. +*/ +struct FuncDef { + i16 nArg; /* Number of arguments. -1 means unlimited */ + u16 funcFlags; /* Some combination of SQLITE_FUNC_* */ + void *pUserData; /* User data parameter */ + FuncDef *pNext; /* Next function with same name */ + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ + void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ + void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */ + char *zName; /* SQL name of the function. */ + FuncDef *pHash; /* Next with a different name but the same hash */ + FuncDestructor *pDestructor; /* Reference counted destructor function */ +}; + +/* +** This structure encapsulates a user-function destructor callback (as +** configured using create_function_v2()) and a reference counter. When +** create_function_v2() is called to create a function with a destructor, +** a single object of this type is allocated. FuncDestructor.nRef is set to +** the number of FuncDef objects created (either 1 or 3, depending on whether +** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor +** member of each of the new FuncDef objects is set to point to the allocated +** FuncDestructor. +** +** Thereafter, when one of the FuncDef objects is deleted, the reference +** count on this object is decremented. When it reaches 0, the destructor +** is invoked and the FuncDestructor structure freed. +*/ +struct FuncDestructor { + int nRef; + void (*xDestroy)(void *); + void *pUserData; +}; + +/* +** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF +** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There +** are assert() statements in the code to verify this. +*/ +#define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */ +#define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */ +#define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */ +#define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */ +#define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */ +#define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */ +#define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */ +#define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */ +#define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */ +#define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */ + +/* +** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are +** used to create the initializers for the FuncDef structures. +** +** FUNCTION(zName, nArg, iArg, bNC, xFunc) +** Used to create a scalar function definition of a function zName +** implemented by C function xFunc that accepts nArg arguments. The +** value passed as iArg is cast to a (void*) and made available +** as the user-data (sqlite3_user_data()) for the function. If +** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. +** +** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) +** Used to create an aggregate function definition implemented by +** the C functions xStep and xFinal. The first four parameters +** are interpreted in the same way as the first 4 parameters to +** FUNCTION(). +** +** LIKEFUNC(zName, nArg, pArg, flags) +** Used to create a scalar function definition of a function zName +** that accepts nArg arguments and is implemented by a call to C +** function likeFunc. Argument pArg is cast to a (void *) and made +** available as the function user-data (sqlite3_user_data()). The +** FuncDef.flags variable is set to the value passed as the flags +** parameter. +*/ +#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} +#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \ + {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \ + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} +#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ + pArg, 0, xFunc, 0, 0, #zName, 0, 0} +#define LIKEFUNC(zName, nArg, arg, flags) \ + {nArg, SQLITE_UTF8|flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0} +#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ + {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \ + SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0} + +/* +** All current savepoints are stored in a linked list starting at +** sqlite3.pSavepoint. The first element in the list is the most recently +** opened savepoint. Savepoints are added to the list by the vdbe +** OP_Savepoint instruction. +*/ +struct Savepoint { + char *zName; /* Savepoint name (nul-terminated) */ + i64 nDeferredCons; /* Number of deferred fk violations */ + i64 nDeferredImmCons; /* Number of deferred imm fk. */ + Savepoint *pNext; /* Parent savepoint (if any) */ +}; + +/* +** The following are used as the second parameter to sqlite3Savepoint(), +** and as the P1 argument to the OP_Savepoint instruction. +*/ +#define SAVEPOINT_BEGIN 0 +#define SAVEPOINT_RELEASE 1 +#define SAVEPOINT_ROLLBACK 2 + + +/* +** Each SQLite module (virtual table definition) is defined by an +** instance of the following structure, stored in the sqlite3.aModule +** hash table. +*/ +struct Module { + const sqlite3_module *pModule; /* Callback pointers */ + const char *zName; /* Name passed to create_module() */ + void *pAux; /* pAux passed to create_module() */ + void (*xDestroy)(void *); /* Module destructor function */ +}; + +/* +** information about each column of an SQL table is held in an instance +** of this structure. +*/ +struct Column { + char *zName; /* Name of this column */ + Expr *pDflt; /* Default value of this column */ + char *zDflt; /* Original text of the default value */ + char *zType; /* Data type for this column */ + char *zColl; /* Collating sequence. If NULL, use the default */ + u8 notNull; /* An OE_ code for handling a NOT NULL constraint */ + char affinity; /* One of the SQLITE_AFF_... values */ + u8 szEst; /* Estimated size of this column. INT==1 */ + u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */ +}; + +/* Allowed values for Column.colFlags: +*/ +#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */ +#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */ + +/* +** A "Collating Sequence" is defined by an instance of the following +** structure. Conceptually, a collating sequence consists of a name and +** a comparison routine that defines the order of that sequence. +** +** If CollSeq.xCmp is NULL, it means that the +** collating sequence is undefined. Indices built on an undefined +** collating sequence may not be read or written. +*/ +struct CollSeq { + char *zName; /* Name of the collating sequence, UTF-8 encoded */ + u8 enc; /* Text encoding handled by xCmp() */ + void *pUser; /* First argument to xCmp() */ + int (*xCmp)(void*,int, const void*, int, const void*); + void (*xDel)(void*); /* Destructor for pUser */ +}; + +/* +** A sort order can be either ASC or DESC. +*/ +#define SQLITE_SO_ASC 0 /* Sort in ascending order */ +#define SQLITE_SO_DESC 1 /* Sort in ascending order */ + +/* +** Column affinity types. +** +** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and +** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve +** the speed a little by numbering the values consecutively. +** +** But rather than start with 0 or 1, we begin with 'a'. That way, +** when multiple affinity types are concatenated into a string and +** used as the P4 operand, they will be more readable. +** +** Note also that the numeric types are grouped together so that testing +** for a numeric type is a single comparison. +*/ +#define SQLITE_AFF_TEXT 'a' +#define SQLITE_AFF_NONE 'b' +#define SQLITE_AFF_NUMERIC 'c' +#define SQLITE_AFF_INTEGER 'd' +#define SQLITE_AFF_REAL 'e' + +#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) + +/* +** The SQLITE_AFF_MASK values masks off the significant bits of an +** affinity value. +*/ +#define SQLITE_AFF_MASK 0x67 + +/* +** Additional bit values that can be ORed with an affinity without +** changing the affinity. +*/ +#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ +#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ +#define SQLITE_NULLEQ 0x80 /* NULL=NULL */ + +/* +** An object of this type is created for each virtual table present in +** the database schema. +** +** If the database schema is shared, then there is one instance of this +** structure for each database connection (sqlite3*) that uses the shared +** schema. This is because each database connection requires its own unique +** instance of the sqlite3_vtab* handle used to access the virtual table +** implementation. sqlite3_vtab* handles can not be shared between +** database connections, even when the rest of the in-memory database +** schema is shared, as the implementation often stores the database +** connection handle passed to it via the xConnect() or xCreate() method +** during initialization internally. This database connection handle may +** then be used by the virtual table implementation to access real tables +** within the database. So that they appear as part of the callers +** transaction, these accesses need to be made via the same database +** connection as that used to execute SQL operations on the virtual table. +** +** All VTable objects that correspond to a single table in a shared +** database schema are initially stored in a linked-list pointed to by +** the Table.pVTable member variable of the corresponding Table object. +** When an sqlite3_prepare() operation is required to access the virtual +** table, it searches the list for the VTable that corresponds to the +** database connection doing the preparing so as to use the correct +** sqlite3_vtab* handle in the compiled query. +** +** When an in-memory Table object is deleted (for example when the +** schema is being reloaded for some reason), the VTable objects are not +** deleted and the sqlite3_vtab* handles are not xDisconnect()ed +** immediately. Instead, they are moved from the Table.pVTable list to +** another linked list headed by the sqlite3.pDisconnect member of the +** corresponding sqlite3 structure. They are then deleted/xDisconnected +** next time a statement is prepared using said sqlite3*. This is done +** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. +** Refer to comments above function sqlite3VtabUnlockList() for an +** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect +** list without holding the corresponding sqlite3.mutex mutex. +** +** The memory for objects of this type is always allocated by +** sqlite3DbMalloc(), using the connection handle stored in VTable.db as +** the first argument. +*/ +struct VTable { + sqlite3 *db; /* Database connection associated with this table */ + Module *pMod; /* Pointer to module implementation */ + sqlite3_vtab *pVtab; /* Pointer to vtab instance */ + int nRef; /* Number of pointers to this structure */ + u8 bConstraint; /* True if constraints are supported */ + int iSavepoint; /* Depth of the SAVEPOINT stack */ + VTable *pNext; /* Next in linked list (see above) */ +}; + +/* +** Each SQL table is represented in memory by an instance of the +** following structure. +** +** Table.zName is the name of the table. The case of the original +** CREATE TABLE statement is stored, but case is not significant for +** comparisons. +** +** Table.nCol is the number of columns in this table. Table.aCol is a +** pointer to an array of Column structures, one for each column. +** +** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of +** the column that is that key. Otherwise Table.iPKey is negative. Note +** that the datatype of the PRIMARY KEY must be INTEGER for this field to +** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of +** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid +** is generated for each row of the table. TF_HasPrimaryKey is set if +** the table has any PRIMARY KEY, INTEGER or otherwise. +** +** Table.tnum is the page number for the root BTree page of the table in the +** database file. If Table.iDb is the index of the database table backend +** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that +** holds temporary tables and indices. If TF_Ephemeral is set +** then the table is stored in a file that is automatically deleted +** when the VDBE cursor to the table is closed. In this case Table.tnum +** refers VDBE cursor number that holds the table open, not to the root +** page number. Transient tables are used to hold the results of a +** sub-query that appears instead of a real table name in the FROM clause +** of a SELECT statement. +*/ +struct Table { + char *zName; /* Name of the table or view */ + Column *aCol; /* Information about each column */ + Index *pIndex; /* List of SQL indexes on this table. */ + Select *pSelect; /* NULL for tables. Points to definition if a view. */ + FKey *pFKey; /* Linked list of all foreign keys in this table */ + char *zColAff; /* String defining the affinity of each column */ +#ifndef SQLITE_OMIT_CHECK + ExprList *pCheck; /* All CHECK constraints */ +#endif + tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */ + int tnum; /* Root BTree node for this table (see note above) */ + i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */ + i16 nCol; /* Number of columns in this table */ + u16 nRef; /* Number of pointers to this Table */ + LogEst szTabRow; /* Estimated size of each table row in bytes */ + u8 tabFlags; /* Mask of TF_* values */ + u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ +#ifndef SQLITE_OMIT_ALTERTABLE + int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + int nModuleArg; /* Number of arguments to the module */ + char **azModuleArg; /* Text of all module args. [0] is module name */ + VTable *pVTable; /* List of VTable objects. */ +#endif + Trigger *pTrigger; /* List of triggers stored in pSchema */ + Schema *pSchema; /* Schema that contains this table */ + Table *pNextZombie; /* Next on the Parse.pZombieTab list */ +}; + +/* +** Allowed values for Tabe.tabFlags. +*/ +#define TF_Readonly 0x01 /* Read-only system table */ +#define TF_Ephemeral 0x02 /* An ephemeral table */ +#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ +#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ +#define TF_Virtual 0x10 /* Is a virtual table */ + + +/* +** Test to see whether or not a table is a virtual table. This is +** done as a macro so that it will be optimized out when virtual +** table support is omitted from the build. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE +# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) +# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) +#else +# define IsVirtual(X) 0 +# define IsHiddenColumn(X) 0 +#endif + +/* +** Each foreign key constraint is an instance of the following structure. +** +** A foreign key is associated with two tables. The "from" table is +** the table that contains the REFERENCES clause that creates the foreign +** key. The "to" table is the table that is named in the REFERENCES clause. +** Consider this example: +** +** CREATE TABLE ex1( +** a INTEGER PRIMARY KEY, +** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) +** ); +** +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". +** +** Each REFERENCES clause generates an instance of the following structure +** which is attached to the from-table. The to-table need not exist when +** the from-table is created. The existence of the to-table is not checked. +*/ +struct FKey { + Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ + FKey *pNextFrom; /* Next foreign key in pFrom */ + char *zTo; /* Name of table that the key points to (aka: Parent) */ + FKey *pNextTo; /* Next foreign key on table named zTo */ + FKey *pPrevTo; /* Previous foreign key on table named zTo */ + int nCol; /* Number of columns in this key */ + /* EV: R-30323-21917 */ + u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ + u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ + Trigger *apTrigger[2]; /* Triggers for aAction[] actions */ + struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ + int iFrom; /* Index of column in pFrom */ + char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ + } aCol[1]; /* One entry for each of nCol column s */ +}; + +/* +** SQLite supports many different ways to resolve a constraint +** error. ROLLBACK processing means that a constraint violation +** causes the operation in process to fail and for the current transaction +** to be rolled back. ABORT processing means the operation in process +** fails and any prior changes from that one operation are backed out, +** but the transaction is not rolled back. FAIL processing means that +** the operation in progress stops and returns an error code. But prior +** changes due to the same operation are not backed out and no rollback +** occurs. IGNORE means that the particular row that caused the constraint +** error is not inserted or updated. Processing continues and no error +** is returned. REPLACE means that preexisting database rows that caused +** a UNIQUE constraint violation are removed so that the new insert or +** update can proceed. Processing continues and no error is reported. +** +** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. +** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the +** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign +** key is set to NULL. CASCADE means that a DELETE or UPDATE of the +** referenced table row is propagated into the row that holds the +** foreign key. +** +** The following symbolic values are used to record which type +** of action to take. +*/ +#define OE_None 0 /* There is no constraint to check */ +#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ +#define OE_Abort 2 /* Back out changes but do no rollback transaction */ +#define OE_Fail 3 /* Stop the operation but leave all prior changes */ +#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ +#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ + +#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ +#define OE_SetNull 7 /* Set the foreign key value to NULL */ +#define OE_SetDflt 8 /* Set the foreign key value to its default */ +#define OE_Cascade 9 /* Cascade the changes */ + +#define OE_Default 10 /* Do whatever the default action is */ + + +/* +** An instance of the following structure is passed as the first +** argument to sqlite3VdbeKeyCompare and is used to control the +** comparison of the two index keys. +** +** Note that aSortOrder[] and aColl[] have nField+1 slots. There +** are nField slots for the columns of an index then one extra slot +** for the rowid at the end. +*/ +struct KeyInfo { + sqlite3 *db; /* The database connection */ + u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ + u16 nField; /* Maximum index for aColl[] and aSortOrder[] */ + u8 *aSortOrder; /* Sort order for each column. */ + CollSeq *aColl[1]; /* Collating sequence for each term of the key */ +}; + +/* +** An instance of the following structure holds information about a +** single index record that has already been parsed out into individual +** values. +** +** A record is an object that contains one or more fields of data. +** Records are used to store the content of a table row and to store +** the key of an index. A blob encoding of a record is created by +** the OP_MakeRecord opcode of the VDBE and is disassembled by the +** OP_Column opcode. +** +** This structure holds a record that has already been disassembled +** into its constituent fields. +*/ +struct UnpackedRecord { + KeyInfo *pKeyInfo; /* Collation and sort-order information */ + u16 nField; /* Number of entries in apMem[] */ + u8 flags; /* Boolean settings. UNPACKED_... below */ + i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ + Mem *aMem; /* Values */ +}; + +/* +** Allowed values of UnpackedRecord.flags +*/ +#define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */ +#define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */ +#define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */ + +/* +** Each SQL index is represented in memory by an +** instance of the following structure. +** +** The columns of the table that are to be indexed are described +** by the aiColumn[] field of this structure. For example, suppose +** we have the following table and index: +** +** CREATE TABLE Ex1(c1 int, c2 int, c3 text); +** CREATE INDEX Ex2 ON Ex1(c3,c1); +** +** In the Table structure describing Ex1, nCol==3 because there are +** three columns in the table. In the Index structure describing +** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. +** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the +** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. +** The second column to be indexed (c1) has an index of 0 in +** Ex1.aCol[], hence Ex2.aiColumn[1]==0. +** +** The Index.onError field determines whether or not the indexed columns +** must be unique and what to do if they are not. When Index.onError=OE_None, +** it means this is not a unique index. Otherwise it is a unique index +** and the value of Index.onError indicate the which conflict resolution +** algorithm to employ whenever an attempt is made to insert a non-unique +** element. +*/ +struct Index { + char *zName; /* Name of this index */ + int *aiColumn; /* Which columns are used by this index. 1st is 0 */ + tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */ + Table *pTable; /* The SQL table being indexed */ + char *zColAff; /* String defining the affinity of each column */ + Index *pNext; /* The next index associated with the same table */ + Schema *pSchema; /* Schema containing this index */ + u8 *aSortOrder; /* for each column: True==DESC, False==ASC */ + char **azColl; /* Array of collation sequence names for index */ + Expr *pPartIdxWhere; /* WHERE clause for partial indices */ + int tnum; /* DB Page containing root of this index */ + LogEst szIdxRow; /* Estimated average row size in bytes */ + u16 nColumn; /* Number of columns in table used by this index */ + u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ + unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */ + unsigned bUnordered:1; /* Use this index for == or IN queries only */ + unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + int nSample; /* Number of elements in aSample[] */ + int nSampleCol; /* Size of IndexSample.anEq[] and so on */ + tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */ + IndexSample *aSample; /* Samples of the left-most key */ +#endif +}; + +/* +** Each sample stored in the sqlite_stat3 table is represented in memory +** using a structure of this type. See documentation at the top of the +** analyze.c source file for additional information. +*/ +struct IndexSample { + void *p; /* Pointer to sampled record */ + int n; /* Size of record in bytes */ + tRowcnt *anEq; /* Est. number of rows where the key equals this sample */ + tRowcnt *anLt; /* Est. number of rows where key is less than this sample */ + tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */ +}; + +/* +** Each token coming out of the lexer is an instance of +** this structure. Tokens are also used as part of an expression. +** +** Note if Token.z==0 then Token.dyn and Token.n are undefined and +** may contain random values. Do not make any assumptions about Token.dyn +** and Token.n when Token.z==0. +*/ +struct Token { + const char *z; /* Text of the token. Not NULL-terminated! */ + unsigned int n; /* Number of characters in this token */ +}; + +/* +** An instance of this structure contains information needed to generate +** code for a SELECT that contains aggregate functions. +** +** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a +** pointer to this structure. The Expr.iColumn field is the index in +** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate +** code for that node. +** +** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the +** original Select structure that describes the SELECT statement. These +** fields do not need to be freed when deallocating the AggInfo structure. +*/ +struct AggInfo { + u8 directMode; /* Direct rendering mode means take data directly + ** from source tables rather than from accumulators */ + u8 useSortingIdx; /* In direct mode, reference the sorting index rather + ** than the source table */ + int sortingIdx; /* Cursor number of the sorting index */ + int sortingIdxPTab; /* Cursor number of pseudo-table */ + int nSortingColumn; /* Number of columns in the sorting index */ + ExprList *pGroupBy; /* The group by clause */ + struct AggInfo_col { /* For each column used in source tables */ + Table *pTab; /* Source table */ + int iTable; /* Cursor number of the source table */ + int iColumn; /* Column number within the source table */ + int iSorterColumn; /* Column number in the sorting index */ + int iMem; /* Memory location that acts as accumulator */ + Expr *pExpr; /* The original expression */ + } *aCol; + int nColumn; /* Number of used entries in aCol[] */ + int nAccumulator; /* Number of columns that show through to the output. + ** Additional columns are used only as parameters to + ** aggregate functions */ + struct AggInfo_func { /* For each aggregate function */ + Expr *pExpr; /* Expression encoding the function */ + FuncDef *pFunc; /* The aggregate function implementation */ + int iMem; /* Memory location that acts as accumulator */ + int iDistinct; /* Ephemeral table used to enforce DISTINCT */ + } *aFunc; + int nFunc; /* Number of entries in aFunc[] */ +}; + +/* +** The datatype ynVar is a signed integer, either 16-bit or 32-bit. +** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater +** than 32767 we have to make it 32-bit. 16-bit is preferred because +** it uses less memory in the Expr object, which is a big memory user +** in systems with lots of prepared statements. And few applications +** need more than about 10 or 20 variables. But some extreme users want +** to have prepared statements with over 32767 variables, and for them +** the option is available (at compile-time). +*/ +#if SQLITE_MAX_VARIABLE_NUMBER<=32767 +typedef i16 ynVar; +#else +typedef int ynVar; +#endif + +/* +** Each node of an expression in the parse tree is an instance +** of this structure. +** +** Expr.op is the opcode. The integer parser token codes are reused +** as opcodes here. For example, the parser defines TK_GE to be an integer +** code representing the ">=" operator. This same integer code is reused +** to represent the greater-than-or-equal-to operator in the expression +** tree. +** +** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, +** or TK_STRING), then Expr.token contains the text of the SQL literal. If +** the expression is a variable (TK_VARIABLE), then Expr.token contains the +** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), +** then Expr.token contains the name of the function. +** +** Expr.pRight and Expr.pLeft are the left and right subexpressions of a +** binary operator. Either or both may be NULL. +** +** Expr.x.pList is a list of arguments if the expression is an SQL function, +** a CASE expression or an IN expression of the form " IN (, ...)". +** Expr.x.pSelect is used if the expression is a sub-select or an expression of +** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the +** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is +** valid. +** +** An expression of the form ID or ID.ID refers to a column in a table. +** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is +** the integer cursor number of a VDBE cursor pointing to that table and +** Expr.iColumn is the column number for the specific column. If the +** expression is used as a result in an aggregate SELECT, then the +** value is also stored in the Expr.iAgg column in the aggregate so that +** it can be accessed after all aggregates are computed. +** +** If the expression is an unbound variable marker (a question mark +** character '?' in the original SQL) then the Expr.iTable holds the index +** number for that variable. +** +** If the expression is a subquery then Expr.iColumn holds an integer +** register number containing the result of the subquery. If the +** subquery gives a constant result, then iTable is -1. If the subquery +** gives a different answer at different times during statement processing +** then iTable is the address of a subroutine that computes the subquery. +** +** If the Expr is of type OP_Column, and the table it is selecting from +** is a disk table or the "old.*" pseudo-table, then pTab points to the +** corresponding table definition. +** +** ALLOCATION NOTES: +** +** Expr objects can use a lot of memory space in database schema. To +** help reduce memory requirements, sometimes an Expr object will be +** truncated. And to reduce the number of memory allocations, sometimes +** two or more Expr objects will be stored in a single memory allocation, +** together with Expr.zToken strings. +** +** If the EP_Reduced and EP_TokenOnly flags are set when +** an Expr object is truncated. When EP_Reduced is set, then all +** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees +** are contained within the same memory allocation. Note, however, that +** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately +** allocated, regardless of whether or not EP_Reduced is set. +*/ +struct Expr { + u8 op; /* Operation performed by this node */ + char affinity; /* The affinity of the column or 0 if not a column */ + u32 flags; /* Various flags. EP_* See below */ + union { + char *zToken; /* Token value. Zero terminated and dequoted */ + int iValue; /* Non-negative integer value if EP_IntValue */ + } u; + + /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no + ** space is allocated for the fields below this point. An attempt to + ** access them will result in a segfault or malfunction. + *********************************************************************/ + + Expr *pLeft; /* Left subnode */ + Expr *pRight; /* Right subnode */ + union { + ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */ + Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */ + } x; + + /* If the EP_Reduced flag is set in the Expr.flags mask, then no + ** space is allocated for the fields below this point. An attempt to + ** access them will result in a segfault or malfunction. + *********************************************************************/ + +#if SQLITE_MAX_EXPR_DEPTH>0 + int nHeight; /* Height of the tree headed by this node */ +#endif + int iTable; /* TK_COLUMN: cursor number of table holding column + ** TK_REGISTER: register number + ** TK_TRIGGER: 1 -> new, 0 -> old + ** EP_Unlikely: 1000 times likelihood */ + ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid. + ** TK_VARIABLE: variable number (always >= 1). */ + i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */ + i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */ + u8 op2; /* TK_REGISTER: original value of Expr.op + ** TK_COLUMN: the value of p5 for OP_Column + ** TK_AGG_FUNCTION: nesting depth */ + AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */ + Table *pTab; /* Table for TK_COLUMN expressions. */ +}; + +/* +** The following are the meanings of bits in the Expr.flags field. +*/ +#define EP_FromJoin 0x000001 /* Originated in ON or USING clause of a join */ +#define EP_Agg 0x000002 /* Contains one or more aggregate functions */ +#define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */ +#define EP_Error 0x000008 /* Expression contains one or more errors */ +#define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */ +#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */ +#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */ +#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */ +#define EP_Collate 0x000100 /* Tree contains a TK_COLLATE opeartor */ +#define EP_FixedDest 0x000200 /* Result needed in a specific register */ +#define EP_IntValue 0x000400 /* Integer value contained in u.iValue */ +#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */ +#define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */ +#define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */ +#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */ +#define EP_Static 0x008000 /* Held in memory not obtained from malloc() */ +#define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */ +#define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */ +#define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */ + +/* +** These macros can be used to test, set, or clear bits in the +** Expr.flags field. +*/ +#define ExprHasProperty(E,P) (((E)->flags&(P))!=0) +#define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P)) +#define ExprSetProperty(E,P) (E)->flags|=(P) +#define ExprClearProperty(E,P) (E)->flags&=~(P) + +/* The ExprSetVVAProperty() macro is used for Verification, Validation, +** and Accreditation only. It works like ExprSetProperty() during VVA +** processes but is a no-op for delivery. +*/ +#ifdef SQLITE_DEBUG +# define ExprSetVVAProperty(E,P) (E)->flags|=(P) +#else +# define ExprSetVVAProperty(E,P) +#endif + +/* +** Macros to determine the number of bytes required by a normal Expr +** struct, an Expr struct with the EP_Reduced flag set in Expr.flags +** and an Expr struct with the EP_TokenOnly flag set. +*/ +#define EXPR_FULLSIZE sizeof(Expr) /* Full size */ +#define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */ +#define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */ + +/* +** Flags passed to the sqlite3ExprDup() function. See the header comment +** above sqlite3ExprDup() for details. +*/ +#define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */ + +/* +** A list of expressions. Each expression may optionally have a +** name. An expr/name combination can be used in several ways, such +** as the list of "expr AS ID" fields following a "SELECT" or in the +** list of "ID = expr" items in an UPDATE. A list of expressions can +** also be used as the argument to a function, in which case the a.zName +** field is not used. +** +** By default the Expr.zSpan field holds a human-readable description of +** the expression that is used in the generation of error messages and +** column labels. In this case, Expr.zSpan is typically the text of a +** column expression as it exists in a SELECT statement. However, if +** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name +** of the result column in the form: DATABASE.TABLE.COLUMN. This later +** form is used for name resolution with nested FROM clauses. +*/ +struct ExprList { + int nExpr; /* Number of expressions on the list */ + int iECursor; /* VDBE Cursor associated with this ExprList */ + struct ExprList_item { /* For each expression in the list */ + Expr *pExpr; /* The list of expressions */ + char *zName; /* Token associated with this expression */ + char *zSpan; /* Original text of the expression */ + u8 sortOrder; /* 1 for DESC or 0 for ASC */ + unsigned done :1; /* A flag to indicate when processing is finished */ + unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */ + u16 iOrderByCol; /* For ORDER BY, column number in result set */ + u16 iAlias; /* Index into Parse.aAlias[] for zName */ + } *a; /* Alloc a power of two greater or equal to nExpr */ +}; + +/* +** An instance of this structure is used by the parser to record both +** the parse tree for an expression and the span of input text for an +** expression. +*/ +struct ExprSpan { + Expr *pExpr; /* The expression parse tree */ + const char *zStart; /* First character of input text */ + const char *zEnd; /* One character past the end of input text */ +}; + +/* +** An instance of this structure can hold a simple list of identifiers, +** such as the list "a,b,c" in the following statements: +** +** INSERT INTO t(a,b,c) VALUES ...; +** CREATE INDEX idx ON t(a,b,c); +** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...; +** +** The IdList.a.idx field is used when the IdList represents the list of +** column names after a table name in an INSERT statement. In the statement +** +** INSERT INTO t(a,b,c) ... +** +** If "a" is the k-th column of table "t", then IdList.a[0].idx==k. +*/ +struct IdList { + struct IdList_item { + char *zName; /* Name of the identifier */ + int idx; /* Index in some Table.aCol[] of a column named zName */ + } *a; + int nId; /* Number of identifiers on the list */ +}; + +/* +** The bitmask datatype defined below is used for various optimizations. +** +** Changing this from a 64-bit to a 32-bit type limits the number of +** tables in a join to 32 instead of 64. But it also reduces the size +** of the library by 738 bytes on ix86. +*/ +typedef u64 Bitmask; + +/* +** The number of bits in a Bitmask. "BMS" means "BitMask Size". +*/ +#define BMS ((int)(sizeof(Bitmask)*8)) + +/* +** A bit in a Bitmask +*/ +#define MASKBIT(n) (((Bitmask)1)<<(n)) + +/* +** The following structure describes the FROM clause of a SELECT statement. +** Each table or subquery in the FROM clause is a separate element of +** the SrcList.a[] array. +** +** With the addition of multiple database support, the following structure +** can also be used to describe a particular table such as the table that +** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL, +** such a table must be a simple name: ID. But in SQLite, the table can +** now be identified by a database name, a dot, then the table name: ID.ID. +** +** The jointype starts out showing the join type between the current table +** and the next table on the list. The parser builds the list this way. +** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each +** jointype expresses the join between the table and the previous table. +** +** In the colUsed field, the high-order bit (bit 63) is set if the table +** contains more than 63 columns and the 64-th or later column is used. +*/ +struct SrcList { + u8 nSrc; /* Number of tables or subqueries in the FROM clause */ + u8 nAlloc; /* Number of entries allocated in a[] below */ + struct SrcList_item { + Schema *pSchema; /* Schema to which this item is fixed */ + char *zDatabase; /* Name of database holding this table */ + char *zName; /* Name of the table */ + char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */ + Table *pTab; /* An SQL table corresponding to zName */ + Select *pSelect; /* A SELECT statement used in place of a table name */ + int addrFillSub; /* Address of subroutine to manifest a subquery */ + int regReturn; /* Register holding return address of addrFillSub */ + u8 jointype; /* Type of join between this able and the previous */ + unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */ + unsigned isCorrelated :1; /* True if sub-query is correlated */ + unsigned viaCoroutine :1; /* Implemented as a co-routine */ +#ifndef SQLITE_OMIT_EXPLAIN + u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */ +#endif + int iCursor; /* The VDBE cursor number used to access this table */ + Expr *pOn; /* The ON clause of a join */ + IdList *pUsing; /* The USING clause of a join */ + Bitmask colUsed; /* Bit N (1<" clause */ + Index *pIndex; /* Index structure corresponding to zIndex, if any */ + } a[1]; /* One entry for each identifier on the list */ +}; + +/* +** Permitted values of the SrcList.a.jointype field +*/ +#define JT_INNER 0x0001 /* Any kind of inner or cross join */ +#define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */ +#define JT_NATURAL 0x0004 /* True for a "natural" join */ +#define JT_LEFT 0x0008 /* Left outer join */ +#define JT_RIGHT 0x0010 /* Right outer join */ +#define JT_OUTER 0x0020 /* The "OUTER" keyword is present */ +#define JT_ERROR 0x0040 /* unknown or unsupported join type */ + + +/* +** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin() +** and the WhereInfo.wctrlFlags member. +*/ +#define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */ +#define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */ +#define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */ +#define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */ +#define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */ +#define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */ +#define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */ +#define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */ +#define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */ +#define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */ +#define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */ +#define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */ + +/* Allowed return values from sqlite3WhereIsDistinct() +*/ +#define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */ +#define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */ +#define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */ +#define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */ + +/* +** A NameContext defines a context in which to resolve table and column +** names. The context consists of a list of tables (the pSrcList) field and +** a list of named expression (pEList). The named expression list may +** be NULL. The pSrc corresponds to the FROM clause of a SELECT or +** to the table being operated on by INSERT, UPDATE, or DELETE. The +** pEList corresponds to the result set of a SELECT and is NULL for +** other statements. +** +** NameContexts can be nested. When resolving names, the inner-most +** context is searched first. If no match is found, the next outer +** context is checked. If there is still no match, the next context +** is checked. This process continues until either a match is found +** or all contexts are check. When a match is found, the nRef member of +** the context containing the match is incremented. +** +** Each subquery gets a new NameContext. The pNext field points to the +** NameContext in the parent query. Thus the process of scanning the +** NameContext list corresponds to searching through successively outer +** subqueries looking for a match. +*/ +struct NameContext { + Parse *pParse; /* The parser */ + SrcList *pSrcList; /* One or more tables used to resolve names */ + ExprList *pEList; /* Optional list of result-set columns */ + AggInfo *pAggInfo; /* Information about aggregates at this level */ + NameContext *pNext; /* Next outer name context. NULL for outermost */ + int nRef; /* Number of names resolved by this context */ + int nErr; /* Number of errors encountered while resolving names */ + u8 ncFlags; /* Zero or more NC_* flags defined below */ +}; + +/* +** Allowed values for the NameContext, ncFlags field. +*/ +#define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */ +#define NC_HasAgg 0x02 /* One or more aggregate functions seen */ +#define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */ +#define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */ +#define NC_PartIdx 0x10 /* True if resolving a partial index WHERE */ + +/* +** An instance of the following structure contains all information +** needed to generate code for a single SELECT statement. +** +** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0. +** If there is a LIMIT clause, the parser sets nLimit to the value of the +** limit and nOffset to the value of the offset (or 0 if there is not +** offset). But later on, nLimit and nOffset become the memory locations +** in the VDBE that record the limit and offset counters. +** +** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes. +** These addresses must be stored so that we can go back and fill in +** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor +** the number of columns in P2 can be computed at the same time +** as the OP_OpenEphm instruction is coded because not +** enough information about the compound query is known at that point. +** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences +** for the result set. The KeyInfo for addrOpenEphm[2] contains collating +** sequences for the ORDER BY clause. +*/ +struct Select { + ExprList *pEList; /* The fields of the result */ + u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */ + u16 selFlags; /* Various SF_* values */ + int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */ + int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */ + u64 nSelectRow; /* Estimated number of result rows */ + SrcList *pSrc; /* The FROM clause */ + Expr *pWhere; /* The WHERE clause */ + ExprList *pGroupBy; /* The GROUP BY clause */ + Expr *pHaving; /* The HAVING clause */ + ExprList *pOrderBy; /* The ORDER BY clause */ + Select *pPrior; /* Prior select in a compound select statement */ + Select *pNext; /* Next select to the left in a compound */ + Select *pRightmost; /* Right-most select in a compound select statement */ + Expr *pLimit; /* LIMIT expression. NULL means not used. */ + Expr *pOffset; /* OFFSET expression. NULL means not used. */ +}; + +/* +** Allowed values for Select.selFlags. The "SF" prefix stands for +** "Select Flag". +*/ +#define SF_Distinct 0x0001 /* Output should be DISTINCT */ +#define SF_Resolved 0x0002 /* Identifiers have been resolved */ +#define SF_Aggregate 0x0004 /* Contains aggregate functions */ +#define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */ +#define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */ +#define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */ +#define SF_UseSorter 0x0040 /* Sort using a sorter */ +#define SF_Values 0x0080 /* Synthesized from VALUES clause */ +#define SF_Materialize 0x0100 /* Force materialization of views */ +#define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */ +#define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */ + + +/* +** The results of a select can be distributed in several ways. The +** "SRT" prefix means "SELECT Result Type". +*/ +#define SRT_Union 1 /* Store result as keys in an index */ +#define SRT_Except 2 /* Remove result from a UNION index */ +#define SRT_Exists 3 /* Store 1 if the result is not empty */ +#define SRT_Discard 4 /* Do not save the results anywhere */ + +/* The ORDER BY clause is ignored for all of the above */ +#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard) + +#define SRT_Output 5 /* Output each row of result */ +#define SRT_Mem 6 /* Store result in a memory cell */ +#define SRT_Set 7 /* Store results as keys in an index */ +#define SRT_Table 8 /* Store result as data with an automatic rowid */ +#define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */ +#define SRT_Coroutine 10 /* Generate a single row of result */ + +/* +** An instance of this object describes where to put of the results of +** a SELECT statement. +*/ +struct SelectDest { + u8 eDest; /* How to dispose of the results. On of SRT_* above. */ + char affSdst; /* Affinity used when eDest==SRT_Set */ + int iSDParm; /* A parameter used by the eDest disposal method */ + int iSdst; /* Base register where results are written */ + int nSdst; /* Number of registers allocated */ +}; + +/* +** During code generation of statements that do inserts into AUTOINCREMENT +** tables, the following information is attached to the Table.u.autoInc.p +** pointer of each autoincrement table to record some side information that +** the code generator needs. We have to keep per-table autoincrement +** information in case inserts are down within triggers. Triggers do not +** normally coordinate their activities, but we do need to coordinate the +** loading and saving of autoincrement information. +*/ +struct AutoincInfo { + AutoincInfo *pNext; /* Next info block in a list of them all */ + Table *pTab; /* Table this info block refers to */ + int iDb; /* Index in sqlite3.aDb[] of database holding pTab */ + int regCtr; /* Memory register holding the rowid counter */ +}; + +/* +** Size of the column cache +*/ +#ifndef SQLITE_N_COLCACHE +# define SQLITE_N_COLCACHE 10 +#endif + +/* +** At least one instance of the following structure is created for each +** trigger that may be fired while parsing an INSERT, UPDATE or DELETE +** statement. All such objects are stored in the linked list headed at +** Parse.pTriggerPrg and deleted once statement compilation has been +** completed. +** +** A Vdbe sub-program that implements the body and WHEN clause of trigger +** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of +** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable. +** The Parse.pTriggerPrg list never contains two entries with the same +** values for both pTrigger and orconf. +** +** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns +** accessed (or set to 0 for triggers fired as a result of INSERT +** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to +** a mask of new.* columns used by the program. +*/ +struct TriggerPrg { + Trigger *pTrigger; /* Trigger this program was coded from */ + TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */ + SubProgram *pProgram; /* Program implementing pTrigger/orconf */ + int orconf; /* Default ON CONFLICT policy */ + u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */ +}; + +/* +** The yDbMask datatype for the bitmask of all attached databases. +*/ +#if SQLITE_MAX_ATTACHED>30 + typedef sqlite3_uint64 yDbMask; +#else + typedef unsigned int yDbMask; +#endif + +/* +** An SQL parser context. A copy of this structure is passed through +** the parser and down into all the parser action routine in order to +** carry around information that is global to the entire parse. +** +** The structure is divided into two parts. When the parser and code +** generate call themselves recursively, the first part of the structure +** is constant but the second part is reset at the beginning and end of +** each recursion. +** +** The nTableLock and aTableLock variables are only used if the shared-cache +** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are +** used to store the set of table-locks required by the statement being +** compiled. Function sqlite3TableLock() is used to add entries to the +** list. +*/ +struct Parse { + sqlite3 *db; /* The main database structure */ + char *zErrMsg; /* An error message */ + Vdbe *pVdbe; /* An engine for executing database bytecode */ + int rc; /* Return code from execution */ + u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */ + u8 checkSchema; /* Causes schema cookie check after an error */ + u8 nested; /* Number of nested calls to the parser/code generator */ + u8 nTempReg; /* Number of temporary registers in aTempReg[] */ + u8 nTempInUse; /* Number of aTempReg[] currently checked out */ + u8 nColCache; /* Number of entries in aColCache[] */ + u8 iColCache; /* Next entry in aColCache[] to replace */ + u8 isMultiWrite; /* True if statement may modify/insert multiple rows */ + u8 mayAbort; /* True if statement may throw an ABORT exception */ + u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */ + int aTempReg[8]; /* Holding area for temporary registers */ + int nRangeReg; /* Size of the temporary register block */ + int iRangeReg; /* First register in temporary register block */ + int nErr; /* Number of errors seen */ + int nTab; /* Number of previously allocated VDBE cursors */ + int nMem; /* Number of memory cells used so far */ + int nSet; /* Number of sets used so far */ + int nOnce; /* Number of OP_Once instructions so far */ + int ckBase; /* Base register of data during check constraints */ + int iPartIdxTab; /* Table corresponding to a partial index */ + int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */ + int iCacheCnt; /* Counter used to generate aColCache[].lru values */ + struct yColCache { + int iTable; /* Table cursor number */ + int iColumn; /* Table column number */ + u8 tempReg; /* iReg is a temp register that needs to be freed */ + int iLevel; /* Nesting level */ + int iReg; /* Reg with value of this column. 0 means none. */ + int lru; /* Least recently used entry has the smallest value */ + } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */ + yDbMask writeMask; /* Start a write transaction on these databases */ + yDbMask cookieMask; /* Bitmask of schema verified databases */ + int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */ + int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */ + int regRowid; /* Register holding rowid of CREATE TABLE entry */ + int regRoot; /* Register holding root page number for new objects */ + int nMaxArg; /* Max args passed to user function by sub-program */ + Token constraintName;/* Name of the constraint currently being parsed */ +#ifndef SQLITE_OMIT_SHARED_CACHE + int nTableLock; /* Number of locks in aTableLock */ + TableLock *aTableLock; /* Required table locks for shared-cache mode */ +#endif + AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */ + + /* Information used while coding trigger programs. */ + Parse *pToplevel; /* Parse structure for main program (or NULL) */ + Table *pTriggerTab; /* Table triggers are being coded for */ + u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */ + u32 oldmask; /* Mask of old.* columns referenced */ + u32 newmask; /* Mask of new.* columns referenced */ + u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */ + u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */ + u8 disableTriggers; /* True to disable triggers */ + + /* Above is constant between recursions. Below is reset before and after + ** each recursion */ + + int nVar; /* Number of '?' variables seen in the SQL so far */ + int nzVar; /* Number of available slots in azVar[] */ + u8 explain; /* True if the EXPLAIN flag is found on the query */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + u8 declareVtab; /* True if inside sqlite3_declare_vtab() */ + int nVtabLock; /* Number of virtual tables to lock */ +#endif + int nAlias; /* Number of aliased result set columns */ + int nHeight; /* Expression tree height of current sub-select */ +#ifndef SQLITE_OMIT_EXPLAIN + int iSelectId; /* ID of current select for EXPLAIN output */ + int iNextSelectId; /* Next available select ID for EXPLAIN output */ +#endif + char **azVar; /* Pointers to names of parameters */ + Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */ + int *aAlias; /* Register used to hold aliased result */ + const char *zTail; /* All SQL text past the last semicolon parsed */ + Table *pNewTable; /* A table being constructed by CREATE TABLE */ + Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */ + const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */ + Token sNameToken; /* Token with unqualified schema object name */ + Token sLastToken; /* The last token parsed */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + Token sArg; /* Complete text of a module argument */ + Table **apVtabLock; /* Pointer to virtual tables needing locking */ +#endif + Table *pZombieTab; /* List of Table objects to delete after code gen */ + TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */ +}; + +/* +** Return true if currently inside an sqlite3_declare_vtab() call. +*/ +#ifdef SQLITE_OMIT_VIRTUALTABLE + #define IN_DECLARE_VTAB 0 +#else + #define IN_DECLARE_VTAB (pParse->declareVtab) +#endif + +/* +** An instance of the following structure can be declared on a stack and used +** to save the Parse.zAuthContext value so that it can be restored later. +*/ +struct AuthContext { + const char *zAuthContext; /* Put saved Parse.zAuthContext here */ + Parse *pParse; /* The Parse structure */ +}; + +/* +** Bitfield flags for P5 value in various opcodes. +*/ +#define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */ +#define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */ +#define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */ +#define OPFLAG_APPEND 0x08 /* This is likely to be an append */ +#define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */ +#define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */ +#define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */ +#define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */ +#define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */ +#define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */ +#define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */ + +/* + * Each trigger present in the database schema is stored as an instance of + * struct Trigger. + * + * Pointers to instances of struct Trigger are stored in two ways. + * 1. In the "trigHash" hash table (part of the sqlite3* that represents the + * database). This allows Trigger structures to be retrieved by name. + * 2. All triggers associated with a single table form a linked list, using the + * pNext member of struct Trigger. A pointer to the first element of the + * linked list is stored as the "pTrigger" member of the associated + * struct Table. + * + * The "step_list" member points to the first element of a linked list + * containing the SQL statements specified as the trigger program. + */ +struct Trigger { + char *zName; /* The name of the trigger */ + char *table; /* The table or view to which the trigger applies */ + u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */ + u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ + Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */ + IdList *pColumns; /* If this is an UPDATE OF trigger, + the is stored here */ + Schema *pSchema; /* Schema containing the trigger */ + Schema *pTabSchema; /* Schema containing the table */ + TriggerStep *step_list; /* Link list of trigger program steps */ + Trigger *pNext; /* Next trigger associated with the table */ +}; + +/* +** A trigger is either a BEFORE or an AFTER trigger. The following constants +** determine which. +** +** If there are multiple triggers, you might of some BEFORE and some AFTER. +** In that cases, the constants below can be ORed together. +*/ +#define TRIGGER_BEFORE 1 +#define TRIGGER_AFTER 2 + +/* + * An instance of struct TriggerStep is used to store a single SQL statement + * that is a part of a trigger-program. + * + * Instances of struct TriggerStep are stored in a singly linked list (linked + * using the "pNext" member) referenced by the "step_list" member of the + * associated struct Trigger instance. The first element of the linked list is + * the first step of the trigger-program. + * + * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or + * "SELECT" statement. The meanings of the other members is determined by the + * value of "op" as follows: + * + * (op == TK_INSERT) + * orconf -> stores the ON CONFLICT algorithm + * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then + * this stores a pointer to the SELECT statement. Otherwise NULL. + * target -> A token holding the quoted name of the table to insert into. + * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then + * this stores values to be inserted. Otherwise NULL. + * pIdList -> If this is an INSERT INTO ... () VALUES ... + * statement, then this stores the column-names to be + * inserted into. + * + * (op == TK_DELETE) + * target -> A token holding the quoted name of the table to delete from. + * pWhere -> The WHERE clause of the DELETE statement if one is specified. + * Otherwise NULL. + * + * (op == TK_UPDATE) + * target -> A token holding the quoted name of the table to update rows of. + * pWhere -> The WHERE clause of the UPDATE statement if one is specified. + * Otherwise NULL. + * pExprList -> A list of the columns to update and the expressions to update + * them to. See sqlite3Update() documentation of "pChanges" + * argument. + * + */ +struct TriggerStep { + u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */ + u8 orconf; /* OE_Rollback etc. */ + Trigger *pTrig; /* The trigger that this step is a part of */ + Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */ + Token target; /* Target table for DELETE, UPDATE, INSERT */ + Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */ + ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */ + IdList *pIdList; /* Column names for INSERT */ + TriggerStep *pNext; /* Next in the link-list */ + TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */ +}; + +/* +** The following structure contains information used by the sqliteFix... +** routines as they walk the parse tree to make database references +** explicit. +*/ +typedef struct DbFixer DbFixer; +struct DbFixer { + Parse *pParse; /* The parsing context. Error messages written here */ + Schema *pSchema; /* Fix items to this schema */ + int bVarOnly; /* Check for variable references only */ + const char *zDb; /* Make sure all objects are contained in this database */ + const char *zType; /* Type of the container - used for error messages */ + const Token *pName; /* Name of the container - used for error messages */ +}; + +/* +** An objected used to accumulate the text of a string where we +** do not necessarily know how big the string will be in the end. +*/ +struct StrAccum { + sqlite3 *db; /* Optional database for lookaside. Can be NULL */ + char *zBase; /* A base allocation. Not from malloc. */ + char *zText; /* The string collected so far */ + int nChar; /* Length of the string so far */ + int nAlloc; /* Amount of space allocated in zText */ + int mxAlloc; /* Maximum allowed string length */ + u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */ + u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */ +}; +#define STRACCUM_NOMEM 1 +#define STRACCUM_TOOBIG 2 + +/* +** A pointer to this structure is used to communicate information +** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback. +*/ +typedef struct { + sqlite3 *db; /* The database being initialized */ + char **pzErrMsg; /* Error message stored here */ + int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */ + int rc; /* Result code stored here */ +} InitData; + +/* +** Structure containing global configuration data for the SQLite library. +** +** This structure also contains some state information. +*/ +struct Sqlite3Config { + int bMemstat; /* True to enable memory status */ + int bCoreMutex; /* True to enable core mutexing */ + int bFullMutex; /* True to enable full mutexing */ + int bOpenUri; /* True to interpret filenames as URIs */ + int bUseCis; /* Use covering indices for full-scans */ + int mxStrlen; /* Maximum string length */ + int szLookaside; /* Default lookaside buffer size */ + int nLookaside; /* Default lookaside buffer count */ + sqlite3_mem_methods m; /* Low-level memory allocation interface */ + sqlite3_mutex_methods mutex; /* Low-level mutex interface */ + sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */ + void *pHeap; /* Heap storage space */ + int nHeap; /* Size of pHeap[] */ + int mnReq, mxReq; /* Min and max heap requests sizes */ + sqlite3_int64 szMmap; /* mmap() space per open file */ + sqlite3_int64 mxMmap; /* Maximum value for szMmap */ + void *pScratch; /* Scratch memory */ + int szScratch; /* Size of each scratch buffer */ + int nScratch; /* Number of scratch buffers */ + void *pPage; /* Page cache memory */ + int szPage; /* Size of each page in pPage[] */ + int nPage; /* Number of pages in pPage[] */ + int mxParserStack; /* maximum depth of the parser stack */ + int sharedCacheEnabled; /* true if shared-cache mode enabled */ + /* The above might be initialized to non-zero. The following need to always + ** initially be zero, however. */ + int isInit; /* True after initialization has finished */ + int inProgress; /* True while initialization in progress */ + int isMutexInit; /* True after mutexes are initialized */ + int isMallocInit; /* True after malloc is initialized */ + int isPCacheInit; /* True after malloc is initialized */ + sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */ + int nRefInitMutex; /* Number of users of pInitMutex */ + void (*xLog)(void*,int,const char*); /* Function for logging */ + void *pLogArg; /* First argument to xLog() */ + int bLocaltimeFault; /* True to fail localtime() calls */ +#ifdef SQLITE_ENABLE_SQLLOG + void(*xSqllog)(void*,sqlite3*,const char*, int); + void *pSqllogArg; +#endif +}; + +/* +** Context pointer passed down through the tree-walk. +*/ +struct Walker { + int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */ + int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */ + Parse *pParse; /* Parser context. */ + int walkerDepth; /* Number of subqueries */ + u8 bSelectDepthFirst; /* Do subqueries first */ + union { /* Extra data for callback */ + NameContext *pNC; /* Naming context */ + int i; /* Integer value */ + SrcList *pSrcList; /* FROM clause */ + struct SrcCount *pSrcCount; /* Counting column references */ + } u; +}; + +/* Forward declarations */ +int sqlite3WalkExpr(Walker*, Expr*); +int sqlite3WalkExprList(Walker*, ExprList*); +int sqlite3WalkSelect(Walker*, Select*); +int sqlite3WalkSelectExpr(Walker*, Select*); +int sqlite3WalkSelectFrom(Walker*, Select*); + +/* +** Return code from the parse-tree walking primitives and their +** callbacks. +*/ +#define WRC_Continue 0 /* Continue down into children */ +#define WRC_Prune 1 /* Omit children but continue walking siblings */ +#define WRC_Abort 2 /* Abandon the tree walk */ + +/* +** Assuming zIn points to the first byte of a UTF-8 character, +** advance zIn to point to the first byte of the next UTF-8 character. +*/ +#define SQLITE_SKIP_UTF8(zIn) { \ + if( (*(zIn++))>=0xc0 ){ \ + while( (*zIn & 0xc0)==0x80 ){ zIn++; } \ + } \ +} + +/* +** The SQLITE_*_BKPT macros are substitutes for the error codes with +** the same name but without the _BKPT suffix. These macros invoke +** routines that report the line-number on which the error originated +** using sqlite3_log(). The routines also provide a convenient place +** to set a debugger breakpoint. +*/ +int sqlite3CorruptError(int); +int sqlite3MisuseError(int); +int sqlite3CantopenError(int); +#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__) +#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__) +#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__) + + +/* +** FTS4 is really an extension for FTS3. It is enabled using the +** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all +** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3. +*/ +#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) +# define SQLITE_ENABLE_FTS3 +#endif + +/* +** The ctype.h header is needed for non-ASCII systems. It is also +** needed by FTS3 when FTS3 is included in the amalgamation. +*/ +#if !defined(SQLITE_ASCII) || \ + (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION)) +# include +#endif + +/* +** The following macros mimic the standard library functions toupper(), +** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The +** sqlite versions only work for ASCII characters, regardless of locale. +*/ +#ifdef SQLITE_ASCII +# define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) +# define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01) +# define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06) +# define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02) +# define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04) +# define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08) +# define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)]) +#else +# define sqlite3Toupper(x) toupper((unsigned char)(x)) +# define sqlite3Isspace(x) isspace((unsigned char)(x)) +# define sqlite3Isalnum(x) isalnum((unsigned char)(x)) +# define sqlite3Isalpha(x) isalpha((unsigned char)(x)) +# define sqlite3Isdigit(x) isdigit((unsigned char)(x)) +# define sqlite3Isxdigit(x) isxdigit((unsigned char)(x)) +# define sqlite3Tolower(x) tolower((unsigned char)(x)) +#endif + +/* +** Internal function prototypes +*/ +#define sqlite3StrICmp sqlite3_stricmp +int sqlite3Strlen30(const char*); +#define sqlite3StrNICmp sqlite3_strnicmp + +int sqlite3MallocInit(void); +void sqlite3MallocEnd(void); +void *sqlite3Malloc(int); +void *sqlite3MallocZero(int); +void *sqlite3DbMallocZero(sqlite3*, int); +void *sqlite3DbMallocRaw(sqlite3*, int); +char *sqlite3DbStrDup(sqlite3*,const char*); +char *sqlite3DbStrNDup(sqlite3*,const char*, int); +void *sqlite3Realloc(void*, int); +void *sqlite3DbReallocOrFree(sqlite3 *, void *, int); +void *sqlite3DbRealloc(sqlite3 *, void *, int); +void sqlite3DbFree(sqlite3*, void*); +int sqlite3MallocSize(void*); +int sqlite3DbMallocSize(sqlite3*, void*); +void *sqlite3ScratchMalloc(int); +void sqlite3ScratchFree(void*); +void *sqlite3PageMalloc(int); +void sqlite3PageFree(void*); +void sqlite3MemSetDefault(void); +void sqlite3BenignMallocHooks(void (*)(void), void (*)(void)); +int sqlite3HeapNearlyFull(void); + +/* +** On systems with ample stack space and that support alloca(), make +** use of alloca() to obtain space for large automatic objects. By default, +** obtain space from malloc(). +** +** The alloca() routine never returns NULL. This will cause code paths +** that deal with sqlite3StackAlloc() failures to be unreachable. +*/ +#ifdef SQLITE_USE_ALLOCA +# define sqlite3StackAllocRaw(D,N) alloca(N) +# define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N) +# define sqlite3StackFree(D,P) +#else +# define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N) +# define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N) +# define sqlite3StackFree(D,P) sqlite3DbFree(D,P) +#endif + +#ifdef SQLITE_ENABLE_MEMSYS3 +const sqlite3_mem_methods *sqlite3MemGetMemsys3(void); +#endif +#ifdef SQLITE_ENABLE_MEMSYS5 +const sqlite3_mem_methods *sqlite3MemGetMemsys5(void); +#endif + + +#ifndef SQLITE_MUTEX_OMIT + sqlite3_mutex_methods const *sqlite3DefaultMutex(void); + sqlite3_mutex_methods const *sqlite3NoopMutex(void); + sqlite3_mutex *sqlite3MutexAlloc(int); + int sqlite3MutexInit(void); + int sqlite3MutexEnd(void); +#endif + +int sqlite3StatusValue(int); +void sqlite3StatusAdd(int, int); +void sqlite3StatusSet(int, int); + +#ifndef SQLITE_OMIT_FLOATING_POINT + int sqlite3IsNaN(double); +#else +# define sqlite3IsNaN(X) 0 +#endif + +void sqlite3VXPrintf(StrAccum*, int, const char*, va_list); +#ifndef SQLITE_OMIT_TRACE +void sqlite3XPrintf(StrAccum*, const char*, ...); +#endif +char *sqlite3MPrintf(sqlite3*,const char*, ...); +char *sqlite3VMPrintf(sqlite3*,const char*, va_list); +char *sqlite3MAppendf(sqlite3*,char*,const char*,...); +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) + void sqlite3DebugPrintf(const char*, ...); +#endif +#if defined(SQLITE_TEST) + void *sqlite3TestTextToPtr(const char*); +#endif + +/* Output formatting for SQLITE_TESTCTRL_EXPLAIN */ +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) + void sqlite3ExplainBegin(Vdbe*); + void sqlite3ExplainPrintf(Vdbe*, const char*, ...); + void sqlite3ExplainNL(Vdbe*); + void sqlite3ExplainPush(Vdbe*); + void sqlite3ExplainPop(Vdbe*); + void sqlite3ExplainFinish(Vdbe*); + void sqlite3ExplainSelect(Vdbe*, Select*); + void sqlite3ExplainExpr(Vdbe*, Expr*); + void sqlite3ExplainExprList(Vdbe*, ExprList*); + const char *sqlite3VdbeExplanation(Vdbe*); +#else +# define sqlite3ExplainBegin(X) +# define sqlite3ExplainSelect(A,B) +# define sqlite3ExplainExpr(A,B) +# define sqlite3ExplainExprList(A,B) +# define sqlite3ExplainFinish(X) +# define sqlite3VdbeExplanation(X) 0 +#endif + + +void sqlite3SetString(char **, sqlite3*, const char*, ...); +void sqlite3ErrorMsg(Parse*, const char*, ...); +int sqlite3Dequote(char*); +int sqlite3KeywordCode(const unsigned char*, int); +int sqlite3RunParser(Parse*, const char*, char **); +void sqlite3FinishCoding(Parse*); +int sqlite3GetTempReg(Parse*); +void sqlite3ReleaseTempReg(Parse*,int); +int sqlite3GetTempRange(Parse*,int); +void sqlite3ReleaseTempRange(Parse*,int,int); +void sqlite3ClearTempRegCache(Parse*); +Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int); +Expr *sqlite3Expr(sqlite3*,int,const char*); +void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*); +Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*); +Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*); +Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*); +void sqlite3ExprAssignVarNumber(Parse*, Expr*); +void sqlite3ExprDelete(sqlite3*, Expr*); +ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*); +void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int); +void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*); +void sqlite3ExprListDelete(sqlite3*, ExprList*); +int sqlite3Init(sqlite3*, char**); +int sqlite3InitCallback(void*, int, char**, char**); +void sqlite3Pragma(Parse*,Token*,Token*,Token*,int); +void sqlite3ResetAllSchemasOfConnection(sqlite3*); +void sqlite3ResetOneSchema(sqlite3*,int); +void sqlite3CollapseDatabaseArray(sqlite3*); +void sqlite3BeginParse(Parse*,int); +void sqlite3CommitInternalChanges(sqlite3*); +Table *sqlite3ResultSetOfSelect(Parse*,Select*); +void sqlite3OpenMasterTable(Parse *, int); +void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int); +void sqlite3AddColumn(Parse*,Token*); +void sqlite3AddNotNull(Parse*, int); +void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int); +void sqlite3AddCheckConstraint(Parse*, Expr*); +void sqlite3AddColumnType(Parse*,Token*); +void sqlite3AddDefaultValue(Parse*,ExprSpan*); +void sqlite3AddCollateType(Parse*, Token*); +void sqlite3EndTable(Parse*,Token*,Token*,Select*); +int sqlite3ParseUri(const char*,const char*,unsigned int*, + sqlite3_vfs**,char**,char **); +Btree *sqlite3DbNameToBtree(sqlite3*,const char*); +int sqlite3CodeOnce(Parse *); + +Bitvec *sqlite3BitvecCreate(u32); +int sqlite3BitvecTest(Bitvec*, u32); +int sqlite3BitvecSet(Bitvec*, u32); +void sqlite3BitvecClear(Bitvec*, u32, void*); +void sqlite3BitvecDestroy(Bitvec*); +u32 sqlite3BitvecSize(Bitvec*); +int sqlite3BitvecBuiltinTest(int,int*); + +RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int); +void sqlite3RowSetClear(RowSet*); +void sqlite3RowSetInsert(RowSet*, i64); +int sqlite3RowSetTest(RowSet*, u8 iBatch, i64); +int sqlite3RowSetNext(RowSet*, i64*); + +void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int); + +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) + int sqlite3ViewGetColumnNames(Parse*,Table*); +#else +# define sqlite3ViewGetColumnNames(A,B) 0 +#endif + +void sqlite3DropTable(Parse*, SrcList*, int, int); +void sqlite3CodeDropTable(Parse*, Table*, int, int); +void sqlite3DeleteTable(sqlite3*, Table*); +#ifndef SQLITE_OMIT_AUTOINCREMENT + void sqlite3AutoincrementBegin(Parse *pParse); + void sqlite3AutoincrementEnd(Parse *pParse); +#else +# define sqlite3AutoincrementBegin(X) +# define sqlite3AutoincrementEnd(X) +#endif +int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*); +void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int); +void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*); +IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*); +int sqlite3IdListIndex(IdList*,const char*); +SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int); +SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*); +SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, + Token*, Select*, Expr*, IdList*); +void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *); +int sqlite3IndexedByLookup(Parse *, struct SrcList_item *); +void sqlite3SrcListShiftJoinType(SrcList*); +void sqlite3SrcListAssignCursors(Parse*, SrcList*); +void sqlite3IdListDelete(sqlite3*, IdList*); +void sqlite3SrcListDelete(sqlite3*, SrcList*); +Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, + Expr*, int, int); +void sqlite3DropIndex(Parse*, SrcList*, int); +int sqlite3Select(Parse*, Select*, SelectDest*); +Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*, + Expr*,ExprList*,u16,Expr*,Expr*); +void sqlite3SelectDelete(sqlite3*, Select*); +Table *sqlite3SrcListLookup(Parse*, SrcList*); +int sqlite3IsReadOnly(Parse*, Table*, int); +void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int); +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) +Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*); +#endif +void sqlite3DeleteFrom(Parse*, SrcList*, Expr*); +void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int); +WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int); +void sqlite3WhereEnd(WhereInfo*); +u64 sqlite3WhereOutputRowCount(WhereInfo*); +int sqlite3WhereIsDistinct(WhereInfo*); +int sqlite3WhereIsOrdered(WhereInfo*); +int sqlite3WhereContinueLabel(WhereInfo*); +int sqlite3WhereBreakLabel(WhereInfo*); +int sqlite3WhereOkOnePass(WhereInfo*); +int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8); +void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int); +void sqlite3ExprCodeMove(Parse*, int, int, int); +void sqlite3ExprCacheStore(Parse*, int, int, int); +void sqlite3ExprCachePush(Parse*); +void sqlite3ExprCachePop(Parse*, int); +void sqlite3ExprCacheRemove(Parse*, int, int); +void sqlite3ExprCacheClear(Parse*); +void sqlite3ExprCacheAffinityChange(Parse*, int, int); +int sqlite3ExprCode(Parse*, Expr*, int); +int sqlite3ExprCodeTemp(Parse*, Expr*, int*); +int sqlite3ExprCodeTarget(Parse*, Expr*, int); +int sqlite3ExprCodeAndCache(Parse*, Expr*, int); +void sqlite3ExprCodeConstants(Parse*, Expr*); +int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int); +void sqlite3ExprIfTrue(Parse*, Expr*, int, int); +void sqlite3ExprIfFalse(Parse*, Expr*, int, int); +Table *sqlite3FindTable(sqlite3*,const char*, const char*); +Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*); +Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *); +Index *sqlite3FindIndex(sqlite3*,const char*, const char*); +void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*); +void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*); +void sqlite3Vacuum(Parse*); +int sqlite3RunVacuum(char**, sqlite3*); +char *sqlite3NameFromToken(sqlite3*, Token*); +int sqlite3ExprCompare(Expr*, Expr*, int); +int sqlite3ExprListCompare(ExprList*, ExprList*, int); +int sqlite3ExprImpliesExpr(Expr*, Expr*, int); +void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*); +void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*); +int sqlite3FunctionUsesThisSrc(Expr*, SrcList*); +Vdbe *sqlite3GetVdbe(Parse*); +void sqlite3PrngSaveState(void); +void sqlite3PrngRestoreState(void); +void sqlite3PrngResetState(void); +void sqlite3RollbackAll(sqlite3*,int); +void sqlite3CodeVerifySchema(Parse*, int); +void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb); +void sqlite3BeginTransaction(Parse*, int); +void sqlite3CommitTransaction(Parse*); +void sqlite3RollbackTransaction(Parse*); +void sqlite3Savepoint(Parse*, int, Token*); +void sqlite3CloseSavepoints(sqlite3 *); +void sqlite3LeaveMutexAndCloseZombie(sqlite3*); +int sqlite3ExprIsConstant(Expr*); +int sqlite3ExprIsConstantNotJoin(Expr*); +int sqlite3ExprIsConstantOrFunction(Expr*); +int sqlite3ExprIsInteger(Expr*, int*); +int sqlite3ExprCanBeNull(const Expr*); +void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int); +int sqlite3ExprNeedsNoAffinityChange(const Expr*, char); +int sqlite3IsRowid(const char*); +void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int); +void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*); +int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*); +void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int, + int*,int,int,int,int,int*); +void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int); +int sqlite3OpenTableAndIndices(Parse*, Table*, int, int); +void sqlite3BeginWriteOperation(Parse*, int, int); +void sqlite3MultiWrite(Parse*); +void sqlite3MayAbort(Parse*); +void sqlite3HaltConstraint(Parse*, int, int, char*, int); +Expr *sqlite3ExprDup(sqlite3*,Expr*,int); +ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int); +SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int); +IdList *sqlite3IdListDup(sqlite3*,IdList*); +Select *sqlite3SelectDup(sqlite3*,Select*,int); +void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*); +FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8); +void sqlite3RegisterBuiltinFunctions(sqlite3*); +void sqlite3RegisterDateTimeFunctions(void); +void sqlite3RegisterGlobalFunctions(void); +int sqlite3SafetyCheckOk(sqlite3*); +int sqlite3SafetyCheckSickOrOk(sqlite3*); +void sqlite3ChangeCookie(Parse*, int); + +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) +void sqlite3MaterializeView(Parse*, Table*, Expr*, int); +#endif + +#ifndef SQLITE_OMIT_TRIGGER + void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*, + Expr*,int, int); + void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*); + void sqlite3DropTrigger(Parse*, SrcList*, int); + void sqlite3DropTriggerPtr(Parse*, Trigger*); + Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask); + Trigger *sqlite3TriggerList(Parse *, Table *); + void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *, + int, int, int); + void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int); + void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*); + void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*); + TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*); + TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*, + ExprList*,Select*,u8); + TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8); + TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*); + void sqlite3DeleteTrigger(sqlite3*, Trigger*); + void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*); + u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int); +# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p)) +#else +# define sqlite3TriggersExist(B,C,D,E,F) 0 +# define sqlite3DeleteTrigger(A,B) +# define sqlite3DropTriggerPtr(A,B) +# define sqlite3UnlinkAndDeleteTrigger(A,B,C) +# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) +# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F) +# define sqlite3TriggerList(X, Y) 0 +# define sqlite3ParseToplevel(p) p +# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0 +#endif + +int sqlite3JoinType(Parse*, Token*, Token*, Token*); +void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int); +void sqlite3DeferForeignKey(Parse*, int); +#ifndef SQLITE_OMIT_AUTHORIZATION + void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*); + int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*); + void sqlite3AuthContextPush(Parse*, AuthContext*, const char*); + void sqlite3AuthContextPop(AuthContext*); + int sqlite3AuthReadCol(Parse*, const char *, const char *, int); +#else +# define sqlite3AuthRead(a,b,c,d) +# define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK +# define sqlite3AuthContextPush(a,b,c) +# define sqlite3AuthContextPop(a) ((void)(a)) +#endif +void sqlite3Attach(Parse*, Expr*, Expr*, Expr*); +void sqlite3Detach(Parse*, Expr*); +void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*); +int sqlite3FixSrcList(DbFixer*, SrcList*); +int sqlite3FixSelect(DbFixer*, Select*); +int sqlite3FixExpr(DbFixer*, Expr*); +int sqlite3FixExprList(DbFixer*, ExprList*); +int sqlite3FixTriggerStep(DbFixer*, TriggerStep*); +int sqlite3AtoF(const char *z, double*, int, u8); +int sqlite3GetInt32(const char *, int*); +int sqlite3Atoi(const char*); +int sqlite3Utf16ByteLen(const void *pData, int nChar); +int sqlite3Utf8CharLen(const char *pData, int nByte); +u32 sqlite3Utf8Read(const u8**); +LogEst sqlite3LogEst(u64); +LogEst sqlite3LogEstAdd(LogEst,LogEst); +#ifndef SQLITE_OMIT_VIRTUALTABLE +LogEst sqlite3LogEstFromDouble(double); +#endif +u64 sqlite3LogEstToInt(LogEst); + +/* +** Routines to read and write variable-length integers. These used to +** be defined locally, but now we use the varint routines in the util.c +** file. Code should use the MACRO forms below, as the Varint32 versions +** are coded to assume the single byte case is already handled (which +** the MACRO form does). +*/ +int sqlite3PutVarint(unsigned char*, u64); +int sqlite3PutVarint32(unsigned char*, u32); +u8 sqlite3GetVarint(const unsigned char *, u64 *); +u8 sqlite3GetVarint32(const unsigned char *, u32 *); +int sqlite3VarintLen(u64 v); + +/* +** The header of a record consists of a sequence variable-length integers. +** These integers are almost always small and are encoded as a single byte. +** The following macros take advantage this fact to provide a fast encode +** and decode of the integers in a record header. It is faster for the common +** case where the integer is a single byte. It is a little slower when the +** integer is two or more bytes. But overall it is faster. +** +** The following expressions are equivalent: +** +** x = sqlite3GetVarint32( A, &B ); +** x = sqlite3PutVarint32( A, B ); +** +** x = getVarint32( A, B ); +** x = putVarint32( A, B ); +** +*/ +#define getVarint32(A,B) \ + (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B))) +#define putVarint32(A,B) \ + (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\ + sqlite3PutVarint32((A),(B))) +#define getVarint sqlite3GetVarint +#define putVarint sqlite3PutVarint + + +const char *sqlite3IndexAffinityStr(Vdbe *, Index *); +void sqlite3TableAffinityStr(Vdbe *, Table *); +char sqlite3CompareAffinity(Expr *pExpr, char aff2); +int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity); +char sqlite3ExprAffinity(Expr *pExpr); +int sqlite3Atoi64(const char*, i64*, int, u8); +void sqlite3Error(sqlite3*, int, const char*,...); +void *sqlite3HexToBlob(sqlite3*, const char *z, int n); +u8 sqlite3HexToInt(int h); +int sqlite3TwoPartName(Parse *, Token *, Token *, Token **); + +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \ + defined(SQLITE_DEBUG_OS_TRACE) +const char *sqlite3ErrName(int); +#endif + +const char *sqlite3ErrStr(int); +int sqlite3ReadSchema(Parse *pParse); +CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int); +CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName); +CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr); +Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*); +Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*); +Expr *sqlite3ExprSkipCollate(Expr*); +int sqlite3CheckCollSeq(Parse *, CollSeq *); +int sqlite3CheckObjectName(Parse *, const char *); +void sqlite3VdbeSetChanges(sqlite3 *, int); +int sqlite3AddInt64(i64*,i64); +int sqlite3SubInt64(i64*,i64); +int sqlite3MulInt64(i64*,i64); +int sqlite3AbsInt32(int); +#ifdef SQLITE_ENABLE_8_3_NAMES +void sqlite3FileSuffix3(const char*, char*); +#else +# define sqlite3FileSuffix3(X,Y) +#endif +u8 sqlite3GetBoolean(const char *z,int); + +const void *sqlite3ValueText(sqlite3_value*, u8); +int sqlite3ValueBytes(sqlite3_value*, u8); +void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, + void(*)(void*)); +void sqlite3ValueFree(sqlite3_value*); +sqlite3_value *sqlite3ValueNew(sqlite3 *); +char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8); +int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **); +void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8); +#ifndef SQLITE_AMALGAMATION +extern const unsigned char sqlite3OpcodeProperty[]; +extern const unsigned char sqlite3UpperToLower[]; +extern const unsigned char sqlite3CtypeMap[]; +extern const Token sqlite3IntTokens[]; +extern SQLITE_WSD struct Sqlite3Config sqlite3Config; +extern SQLITE_WSD FuncDefHash sqlite3GlobalFunctions; +#ifndef SQLITE_OMIT_WSD +extern int sqlite3PendingByte; +#endif +#endif +void sqlite3RootPageMoved(sqlite3*, int, int, int); +void sqlite3Reindex(Parse*, Token*, Token*); +void sqlite3AlterFunctions(void); +void sqlite3AlterRenameTable(Parse*, SrcList*, Token*); +int sqlite3GetToken(const unsigned char *, int *); +void sqlite3NestedParse(Parse*, const char*, ...); +void sqlite3ExpirePreparedStatements(sqlite3*); +int sqlite3CodeSubselect(Parse *, Expr *, int, int); +void sqlite3SelectPrep(Parse*, Select*, NameContext*); +int sqlite3MatchSpanName(const char*, const char*, const char*, const char*); +int sqlite3ResolveExprNames(NameContext*, Expr*); +void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*); +void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*); +int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*); +void sqlite3ColumnDefault(Vdbe *, Table *, int, int); +void sqlite3AlterFinishAddColumn(Parse *, Token *); +void sqlite3AlterBeginAddColumn(Parse *, SrcList *); +CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*); +char sqlite3AffinityType(const char*, u8*); +void sqlite3Analyze(Parse*, Token*, Token*); +int sqlite3InvokeBusyHandler(BusyHandler*); +int sqlite3FindDb(sqlite3*, Token*); +int sqlite3FindDbName(sqlite3 *, const char *); +int sqlite3AnalysisLoad(sqlite3*,int iDB); +void sqlite3DeleteIndexSamples(sqlite3*,Index*); +void sqlite3DefaultRowEst(Index*); +void sqlite3RegisterLikeFunctions(sqlite3*, int); +int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*); +void sqlite3MinimumFileFormat(Parse*, int, int); +void sqlite3SchemaClear(void *); +Schema *sqlite3SchemaGet(sqlite3 *, Btree *); +int sqlite3SchemaToIndex(sqlite3 *db, Schema *); +KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int); +KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *); +int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, + void (*)(sqlite3_context*,int,sqlite3_value **), + void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*), + FuncDestructor *pDestructor +); +int sqlite3ApiExit(sqlite3 *db, int); +int sqlite3OpenTempDatabase(Parse *); + +void sqlite3StrAccumInit(StrAccum*, char*, int, int); +void sqlite3StrAccumAppend(StrAccum*,const char*,int); +void sqlite3AppendSpace(StrAccum*,int); +char *sqlite3StrAccumFinish(StrAccum*); +void sqlite3StrAccumReset(StrAccum*); +void sqlite3SelectDestInit(SelectDest*,int,int); +Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int); + +void sqlite3BackupRestart(sqlite3_backup *); +void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *); + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +void sqlite3AnalyzeFunctions(void); +int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*); +void sqlite3Stat4ProbeFree(UnpackedRecord*); +#endif + +/* +** The interface to the LEMON-generated parser +*/ +void *sqlite3ParserAlloc(void*(*)(size_t)); +void sqlite3ParserFree(void*, void(*)(void*)); +void sqlite3Parser(void*, int, Token, Parse*); +#ifdef YYTRACKMAXSTACKDEPTH + int sqlite3ParserStackPeak(void*); +#endif + +void sqlite3AutoLoadExtensions(sqlite3*); +#ifndef SQLITE_OMIT_LOAD_EXTENSION + void sqlite3CloseExtensions(sqlite3*); +#else +# define sqlite3CloseExtensions(X) +#endif + +#ifndef SQLITE_OMIT_SHARED_CACHE + void sqlite3TableLock(Parse *, int, int, u8, const char *); +#else + #define sqlite3TableLock(v,w,x,y,z) +#endif + +#ifdef SQLITE_TEST + int sqlite3Utf8To8(unsigned char*); +#endif + +#ifdef SQLITE_OMIT_VIRTUALTABLE +# define sqlite3VtabClear(Y) +# define sqlite3VtabSync(X,Y) SQLITE_OK +# define sqlite3VtabRollback(X) +# define sqlite3VtabCommit(X) +# define sqlite3VtabInSync(db) 0 +# define sqlite3VtabLock(X) +# define sqlite3VtabUnlock(X) +# define sqlite3VtabUnlockList(X) +# define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK +# define sqlite3GetVTable(X,Y) ((VTable*)0) +#else + void sqlite3VtabClear(sqlite3 *db, Table*); + void sqlite3VtabDisconnect(sqlite3 *db, Table *p); + int sqlite3VtabSync(sqlite3 *db, Vdbe*); + int sqlite3VtabRollback(sqlite3 *db); + int sqlite3VtabCommit(sqlite3 *db); + void sqlite3VtabLock(VTable *); + void sqlite3VtabUnlock(VTable *); + void sqlite3VtabUnlockList(sqlite3*); + int sqlite3VtabSavepoint(sqlite3 *, int, int); + void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*); + VTable *sqlite3GetVTable(sqlite3*, Table*); +# define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0) +#endif +void sqlite3VtabMakeWritable(Parse*,Table*); +void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int); +void sqlite3VtabFinishParse(Parse*, Token*); +void sqlite3VtabArgInit(Parse*); +void sqlite3VtabArgExtend(Parse*, Token*); +int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **); +int sqlite3VtabCallConnect(Parse*, Table*); +int sqlite3VtabCallDestroy(sqlite3*, int, const char *); +int sqlite3VtabBegin(sqlite3 *, VTable *); +FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*); +void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**); +sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*); +int sqlite3VdbeParameterIndex(Vdbe*, const char*, int); +int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *); +int sqlite3Reprepare(Vdbe*); +void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*); +CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *); +int sqlite3TempInMemory(const sqlite3*); +const char *sqlite3JournalModename(int); +#ifndef SQLITE_OMIT_WAL + int sqlite3Checkpoint(sqlite3*, int, int, int*, int*); + int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int); +#endif + +/* Declarations for functions in fkey.c. All of these are replaced by +** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign +** key functionality is available. If OMIT_TRIGGER is defined but +** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In +** this case foreign keys are parsed, but no other functionality is +** provided (enforcement of FK constraints requires the triggers sub-system). +*/ +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + void sqlite3FkCheck(Parse*, Table*, int, int, int*, int); + void sqlite3FkDropTable(Parse*, SrcList *, Table*); + void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int); + int sqlite3FkRequired(Parse*, Table*, int*, int); + u32 sqlite3FkOldmask(Parse*, Table*); + FKey *sqlite3FkReferences(Table *); +#else + #define sqlite3FkActions(a,b,c,d,e,f) + #define sqlite3FkCheck(a,b,c,d,e,f) + #define sqlite3FkDropTable(a,b,c) + #define sqlite3FkOldmask(a,b) 0 + #define sqlite3FkRequired(a,b,c,d) 0 +#endif +#ifndef SQLITE_OMIT_FOREIGN_KEY + void sqlite3FkDelete(sqlite3 *, Table*); + int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**); +#else + #define sqlite3FkDelete(a,b) + #define sqlite3FkLocateIndex(a,b,c,d,e) +#endif + + +/* +** Available fault injectors. Should be numbered beginning with 0. +*/ +#define SQLITE_FAULTINJECTOR_MALLOC 0 +#define SQLITE_FAULTINJECTOR_COUNT 1 + +/* +** The interface to the code in fault.c used for identifying "benign" +** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST +** is not defined. +*/ +#ifndef SQLITE_OMIT_BUILTIN_TEST + void sqlite3BeginBenignMalloc(void); + void sqlite3EndBenignMalloc(void); +#else + #define sqlite3BeginBenignMalloc() + #define sqlite3EndBenignMalloc() +#endif + +#define IN_INDEX_ROWID 1 +#define IN_INDEX_EPH 2 +#define IN_INDEX_INDEX_ASC 3 +#define IN_INDEX_INDEX_DESC 4 +int sqlite3FindInIndex(Parse *, Expr *, int*); + +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int); + int sqlite3JournalSize(sqlite3_vfs *); + int sqlite3JournalCreate(sqlite3_file *); + int sqlite3JournalExists(sqlite3_file *p); +#else + #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile) + #define sqlite3JournalExists(p) 1 +#endif + +void sqlite3MemJournalOpen(sqlite3_file *); +int sqlite3MemJournalSize(void); +int sqlite3IsMemJournal(sqlite3_file *); + +#if SQLITE_MAX_EXPR_DEPTH>0 + void sqlite3ExprSetHeight(Parse *pParse, Expr *p); + int sqlite3SelectExprHeight(Select *); + int sqlite3ExprCheckHeight(Parse*, int); +#else + #define sqlite3ExprSetHeight(x,y) + #define sqlite3SelectExprHeight(x) 0 + #define sqlite3ExprCheckHeight(x,y) +#endif + +u32 sqlite3Get4byte(const u8*); +void sqlite3Put4byte(u8*, u32); + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *); + void sqlite3ConnectionUnlocked(sqlite3 *db); + void sqlite3ConnectionClosed(sqlite3 *db); +#else + #define sqlite3ConnectionBlocked(x,y) + #define sqlite3ConnectionUnlocked(x) + #define sqlite3ConnectionClosed(x) +#endif + +#ifdef SQLITE_DEBUG + void sqlite3ParserTrace(FILE*, char *); +#endif + +/* +** If the SQLITE_ENABLE IOTRACE exists then the global variable +** sqlite3IoTrace is a pointer to a printf-like routine used to +** print I/O tracing messages. +*/ +#ifdef SQLITE_ENABLE_IOTRACE +# define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; } + void sqlite3VdbeIOTraceSql(Vdbe*); +SQLITE_EXTERN void (*sqlite3IoTrace)(const char*,...); +#else +# define IOTRACE(A) +# define sqlite3VdbeIOTraceSql(X) +#endif + +/* +** These routines are available for the mem2.c debugging memory allocator +** only. They are used to verify that different "types" of memory +** allocations are properly tracked by the system. +** +** sqlite3MemdebugSetType() sets the "type" of an allocation to one of +** the MEMTYPE_* macros defined below. The type must be a bitmask with +** a single bit set. +** +** sqlite3MemdebugHasType() returns true if any of the bits in its second +** argument match the type set by the previous sqlite3MemdebugSetType(). +** sqlite3MemdebugHasType() is intended for use inside assert() statements. +** +** sqlite3MemdebugNoType() returns true if none of the bits in its second +** argument match the type set by the previous sqlite3MemdebugSetType(). +** +** Perhaps the most important point is the difference between MEMTYPE_HEAP +** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means +** it might have been allocated by lookaside, except the allocation was +** too large or lookaside was already full. It is important to verify +** that allocations that might have been satisfied by lookaside are not +** passed back to non-lookaside free() routines. Asserts such as the +** example above are placed on the non-lookaside free() routines to verify +** this constraint. +** +** All of this is no-op for a production build. It only comes into +** play when the SQLITE_MEMDEBUG compile-time option is used. +*/ +#ifdef SQLITE_MEMDEBUG + void sqlite3MemdebugSetType(void*,u8); + int sqlite3MemdebugHasType(void*,u8); + int sqlite3MemdebugNoType(void*,u8); +#else +# define sqlite3MemdebugSetType(X,Y) /* no-op */ +# define sqlite3MemdebugHasType(X,Y) 1 +# define sqlite3MemdebugNoType(X,Y) 1 +#endif +#define MEMTYPE_HEAP 0x01 /* General heap allocations */ +#define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */ +#define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */ +#define MEMTYPE_PCACHE 0x08 /* Page cache allocations */ +#define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */ + +#endif /* _SQLITEINT_H_ */ diff --git a/components/external/SQLite-3.8.1/src/sqliteLimit.h b/components/external/SQLite-3.8.1/src/sqliteLimit.h new file mode 100644 index 0000000000000000000000000000000000000000..c7aee53cebca94da51e71a822ea5a6deb90385df --- /dev/null +++ b/components/external/SQLite-3.8.1/src/sqliteLimit.h @@ -0,0 +1,208 @@ +/* +** 2007 May 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file defines various limits of what SQLite can process. +*/ + +/* +** The maximum length of a TEXT or BLOB in bytes. This also +** limits the size of a row in a table or index. +** +** The hard limit is the ability of a 32-bit signed integer +** to count the size: 2^31-1 or 2147483647. +*/ +#ifndef SQLITE_MAX_LENGTH +# define SQLITE_MAX_LENGTH 1000000000 +#endif + +/* +** This is the maximum number of +** +** * Columns in a table +** * Columns in an index +** * Columns in a view +** * Terms in the SET clause of an UPDATE statement +** * Terms in the result set of a SELECT statement +** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. +** * Terms in the VALUES clause of an INSERT statement +** +** The hard upper limit here is 32676. Most database people will +** tell you that in a well-normalized database, you usually should +** not have more than a dozen or so columns in any table. And if +** that is the case, there is no point in having more than a few +** dozen values in any of the other situations described above. +*/ +#ifndef SQLITE_MAX_COLUMN +# define SQLITE_MAX_COLUMN 2000 +#endif + +/* +** The maximum length of a single SQL statement in bytes. +** +** It used to be the case that setting this value to zero would +** turn the limit off. That is no longer true. It is not possible +** to turn this limit off. +*/ +#ifndef SQLITE_MAX_SQL_LENGTH +# define SQLITE_MAX_SQL_LENGTH 1000000000 +#endif + +/* +** The maximum depth of an expression tree. This is limited to +** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might +** want to place more severe limits on the complexity of an +** expression. +** +** A value of 0 used to mean that the limit was not enforced. +** But that is no longer true. The limit is now strictly enforced +** at all times. +*/ +#ifndef SQLITE_MAX_EXPR_DEPTH +# define SQLITE_MAX_EXPR_DEPTH 1000 +#endif + +/* +** The maximum number of terms in a compound SELECT statement. +** The code generator for compound SELECT statements does one +** level of recursion for each term. A stack overflow can result +** if the number of terms is too large. In practice, most SQL +** never has more than 3 or 4 terms. Use a value of 0 to disable +** any limit on the number of terms in a compount SELECT. +*/ +#ifndef SQLITE_MAX_COMPOUND_SELECT +# define SQLITE_MAX_COMPOUND_SELECT 500 +#endif + +/* +** The maximum number of opcodes in a VDBE program. +** Not currently enforced. +*/ +#ifndef SQLITE_MAX_VDBE_OP +# define SQLITE_MAX_VDBE_OP 25000 +#endif + +/* +** The maximum number of arguments to an SQL function. +*/ +#ifndef SQLITE_MAX_FUNCTION_ARG +# define SQLITE_MAX_FUNCTION_ARG 127 +#endif + +/* +** The maximum number of in-memory pages to use for the main database +** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE +*/ +#ifndef SQLITE_DEFAULT_CACHE_SIZE +# define SQLITE_DEFAULT_CACHE_SIZE 2000 +#endif +#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE +# define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500 +#endif + +/* +** The default number of frames to accumulate in the log file before +** checkpointing the database in WAL mode. +*/ +#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT +# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000 +#endif + +/* +** The maximum number of attached databases. This must be between 0 +** and 62. The upper bound on 62 is because a 64-bit integer bitmap +** is used internally to track attached databases. +*/ +#ifndef SQLITE_MAX_ATTACHED +# define SQLITE_MAX_ATTACHED 10 +#endif + + +/* +** The maximum value of a ?nnn wildcard that the parser will accept. +*/ +#ifndef SQLITE_MAX_VARIABLE_NUMBER +# define SQLITE_MAX_VARIABLE_NUMBER 999 +#endif + +/* Maximum page size. The upper bound on this value is 65536. This a limit +** imposed by the use of 16-bit offsets within each page. +** +** Earlier versions of SQLite allowed the user to change this value at +** compile time. This is no longer permitted, on the grounds that it creates +** a library that is technically incompatible with an SQLite library +** compiled with a different limit. If a process operating on a database +** with a page-size of 65536 bytes crashes, then an instance of SQLite +** compiled with the default page-size limit will not be able to rollback +** the aborted transaction. This could lead to database corruption. +*/ +#ifdef SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_PAGE_SIZE +#endif +#define SQLITE_MAX_PAGE_SIZE 65536 + + +/* +** The default size of a database page. +*/ +#ifndef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE 1024 +#endif +#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + +/* +** Ordinarily, if no value is explicitly provided, SQLite creates databases +** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain +** device characteristics (sector-size and atomic write() support), +** SQLite may choose a larger value. This constant is the maximum value +** SQLite will choose on its own. +*/ +#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 +#endif +#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + + +/* +** Maximum number of pages in one database file. +** +** This is really just the default value for the max_page_count pragma. +** This value can be lowered (or raised) at run-time using that the +** max_page_count macro. +*/ +#ifndef SQLITE_MAX_PAGE_COUNT +# define SQLITE_MAX_PAGE_COUNT 1073741823 +#endif + +/* +** Maximum length (in bytes) of the pattern in a LIKE or GLOB +** operator. +*/ +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 +#endif + +/* +** Maximum depth of recursion for triggers. +** +** A value of 1 means that a trigger program will not be able to itself +** fire any triggers. A value of 0 means that no trigger programs at all +** may be executed. +*/ +#ifndef SQLITE_MAX_TRIGGER_DEPTH +# define SQLITE_MAX_TRIGGER_DEPTH 1000 +#endif diff --git a/components/external/SQLite-3.8.1/src/status.c b/components/external/SQLite-3.8.1/src/status.c new file mode 100644 index 0000000000000000000000000000000000000000..5fcb68ddc3836827f66264b1d6932079b1fb2e81 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/status.c @@ -0,0 +1,262 @@ +/* +** 2008 June 18 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This module implements the sqlite3_status() interface and related +** functionality. +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" + +/* +** Variables in which to record status information. +*/ +typedef struct sqlite3StatType sqlite3StatType; +static SQLITE_WSD struct sqlite3StatType { + int nowValue[10]; /* Current value */ + int mxValue[10]; /* Maximum value */ +} sqlite3Stat = { {0,}, {0,} }; + + +/* The "wsdStat" macro will resolve to the status information +** state vector. If writable static data is unsupported on the target, +** we have to locate the state vector at run-time. In the more common +** case where writable static data is supported, wsdStat can refer directly +** to the "sqlite3Stat" state vector declared above. +*/ +#ifdef SQLITE_OMIT_WSD +# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat) +# define wsdStat x[0] +#else +# define wsdStatInit +# define wsdStat sqlite3Stat +#endif + +/* +** Return the current value of a status parameter. +*/ +int sqlite3StatusValue(int op){ + wsdStatInit; + assert( op>=0 && op=0 && opwsdStat.mxValue[op] ){ + wsdStat.mxValue[op] = wsdStat.nowValue[op]; + } +} + +/* +** Set the value of a status to X. +*/ +void sqlite3StatusSet(int op, int X){ + wsdStatInit; + assert( op>=0 && opwsdStat.mxValue[op] ){ + wsdStat.mxValue[op] = wsdStat.nowValue[op]; + } +} + +/* +** Query status information. +** +** This implementation assumes that reading or writing an aligned +** 32-bit integer is an atomic operation. If that assumption is not true, +** then this routine is not threadsafe. +*/ +int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){ + wsdStatInit; + if( op<0 || op>=ArraySize(wsdStat.nowValue) ){ + return SQLITE_MISUSE_BKPT; + } + *pCurrent = wsdStat.nowValue[op]; + *pHighwater = wsdStat.mxValue[op]; + if( resetFlag ){ + wsdStat.mxValue[op] = wsdStat.nowValue[op]; + } + return SQLITE_OK; +} + +/* +** Query status information for a single database connection +*/ +int sqlite3_db_status( + sqlite3 *db, /* The database connection whose status is desired */ + int op, /* Status verb */ + int *pCurrent, /* Write current value here */ + int *pHighwater, /* Write high-water mark here */ + int resetFlag /* Reset high-water mark if true */ +){ + int rc = SQLITE_OK; /* Return code */ + sqlite3_mutex_enter(db->mutex); + switch( op ){ + case SQLITE_DBSTATUS_LOOKASIDE_USED: { + *pCurrent = db->lookaside.nOut; + *pHighwater = db->lookaside.mxOut; + if( resetFlag ){ + db->lookaside.mxOut = db->lookaside.nOut; + } + break; + } + + case SQLITE_DBSTATUS_LOOKASIDE_HIT: + case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE: + case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: { + testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT ); + testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE ); + testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL ); + assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 ); + assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 ); + *pCurrent = 0; + *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT]; + if( resetFlag ){ + db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0; + } + break; + } + + /* + ** Return an approximation for the amount of memory currently used + ** by all pagers associated with the given database connection. The + ** highwater mark is meaningless and is returned as zero. + */ + case SQLITE_DBSTATUS_CACHE_USED: { + int totalUsed = 0; + int i; + sqlite3BtreeEnterAll(db); + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + Pager *pPager = sqlite3BtreePager(pBt); + totalUsed += sqlite3PagerMemUsed(pPager); + } + } + sqlite3BtreeLeaveAll(db); + *pCurrent = totalUsed; + *pHighwater = 0; + break; + } + + /* + ** *pCurrent gets an accurate estimate of the amount of memory used + ** to store the schema for all databases (main, temp, and any ATTACHed + ** databases. *pHighwater is set to zero. + */ + case SQLITE_DBSTATUS_SCHEMA_USED: { + int i; /* Used to iterate through schemas */ + int nByte = 0; /* Used to accumulate return value */ + + sqlite3BtreeEnterAll(db); + db->pnBytesFreed = &nByte; + for(i=0; inDb; i++){ + Schema *pSchema = db->aDb[i].pSchema; + if( ALWAYS(pSchema!=0) ){ + HashElem *p; + + nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * ( + pSchema->tblHash.count + + pSchema->trigHash.count + + pSchema->idxHash.count + + pSchema->fkeyHash.count + ); + nByte += sqlite3MallocSize(pSchema->tblHash.ht); + nByte += sqlite3MallocSize(pSchema->trigHash.ht); + nByte += sqlite3MallocSize(pSchema->idxHash.ht); + nByte += sqlite3MallocSize(pSchema->fkeyHash.ht); + + for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){ + sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p)); + } + for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ + sqlite3DeleteTable(db, (Table *)sqliteHashData(p)); + } + } + } + db->pnBytesFreed = 0; + sqlite3BtreeLeaveAll(db); + + *pHighwater = 0; + *pCurrent = nByte; + break; + } + + /* + ** *pCurrent gets an accurate estimate of the amount of memory used + ** to store all prepared statements. + ** *pHighwater is set to zero. + */ + case SQLITE_DBSTATUS_STMT_USED: { + struct Vdbe *pVdbe; /* Used to iterate through VMs */ + int nByte = 0; /* Used to accumulate return value */ + + db->pnBytesFreed = &nByte; + for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){ + sqlite3VdbeClearObject(db, pVdbe); + sqlite3DbFree(db, pVdbe); + } + db->pnBytesFreed = 0; + + *pHighwater = 0; + *pCurrent = nByte; + + break; + } + + /* + ** Set *pCurrent to the total cache hits or misses encountered by all + ** pagers the database handle is connected to. *pHighwater is always set + ** to zero. + */ + case SQLITE_DBSTATUS_CACHE_HIT: + case SQLITE_DBSTATUS_CACHE_MISS: + case SQLITE_DBSTATUS_CACHE_WRITE:{ + int i; + int nRet = 0; + assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 ); + assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 ); + + for(i=0; inDb; i++){ + if( db->aDb[i].pBt ){ + Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt); + sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet); + } + } + *pHighwater = 0; + *pCurrent = nRet; + break; + } + + /* Set *pCurrent to non-zero if there are unresolved deferred foreign + ** key constraints. Set *pCurrent to zero if all foreign key constraints + ** have been satisfied. The *pHighwater is always set to zero. + */ + case SQLITE_DBSTATUS_DEFERRED_FKS: { + *pHighwater = 0; + *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0; + break; + } + + default: { + rc = SQLITE_ERROR; + } + } + sqlite3_mutex_leave(db->mutex); + return rc; +} diff --git a/components/external/SQLite-3.8.1/src/table.c b/components/external/SQLite-3.8.1/src/table.c new file mode 100644 index 0000000000000000000000000000000000000000..26bbfb4f456c42982529ea1a63a01751dd3ee95a --- /dev/null +++ b/components/external/SQLite-3.8.1/src/table.c @@ -0,0 +1,197 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the sqlite3_get_table() and sqlite3_free_table() +** interface routines. These are just wrappers around the main +** interface routine of sqlite3_exec(). +** +** These routines are in a separate files so that they will not be linked +** if they are not used. +*/ +#include "sqliteInt.h" +#include +#include + +#ifndef SQLITE_OMIT_GET_TABLE + +/* +** This structure is used to pass data from sqlite3_get_table() through +** to the callback function is uses to build the result. +*/ +typedef struct TabResult { + char **azResult; /* Accumulated output */ + char *zErrMsg; /* Error message text, if an error occurs */ + int nAlloc; /* Slots allocated for azResult[] */ + int nRow; /* Number of rows in the result */ + int nColumn; /* Number of columns in the result */ + int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */ + int rc; /* Return code from sqlite3_exec() */ +} TabResult; + +/* +** This routine is called once for each row in the result table. Its job +** is to fill in the TabResult structure appropriately, allocating new +** memory as necessary. +*/ +static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ + TabResult *p = (TabResult*)pArg; /* Result accumulator */ + int need; /* Slots needed in p->azResult[] */ + int i; /* Loop counter */ + char *z; /* A single column of result */ + + /* Make sure there is enough space in p->azResult to hold everything + ** we need to remember from this invocation of the callback. + */ + if( p->nRow==0 && argv!=0 ){ + need = nCol*2; + }else{ + need = nCol; + } + if( p->nData + need > p->nAlloc ){ + char **azNew; + p->nAlloc = p->nAlloc*2 + need; + azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc ); + if( azNew==0 ) goto malloc_failed; + p->azResult = azNew; + } + + /* If this is the first row, then generate an extra row containing + ** the names of all columns. + */ + if( p->nRow==0 ){ + p->nColumn = nCol; + for(i=0; iazResult[p->nData++] = z; + } + }else if( p->nColumn!=nCol ){ + sqlite3_free(p->zErrMsg); + p->zErrMsg = sqlite3_mprintf( + "sqlite3_get_table() called with two or more incompatible queries" + ); + p->rc = SQLITE_ERROR; + return 1; + } + + /* Copy over the row data + */ + if( argv!=0 ){ + for(i=0; iazResult[p->nData++] = z; + } + p->nRow++; + } + return 0; + +malloc_failed: + p->rc = SQLITE_NOMEM; + return 1; +} + +/* +** Query the database. But instead of invoking a callback for each row, +** malloc() for space to hold the result and return the entire results +** at the conclusion of the call. +** +** The result that is written to ***pazResult is held in memory obtained +** from malloc(). But the caller cannot free this memory directly. +** Instead, the entire table should be passed to sqlite3_free_table() when +** the calling procedure is finished using it. +*/ +int sqlite3_get_table( + sqlite3 *db, /* The database on which the SQL executes */ + const char *zSql, /* The SQL to be executed */ + char ***pazResult, /* Write the result table here */ + int *pnRow, /* Write the number of rows in the result here */ + int *pnColumn, /* Write the number of columns of result here */ + char **pzErrMsg /* Write error messages here */ +){ + int rc; + TabResult res; + + *pazResult = 0; + if( pnColumn ) *pnColumn = 0; + if( pnRow ) *pnRow = 0; + if( pzErrMsg ) *pzErrMsg = 0; + res.zErrMsg = 0; + res.nRow = 0; + res.nColumn = 0; + res.nData = 1; + res.nAlloc = 20; + res.rc = SQLITE_OK; + res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc ); + if( res.azResult==0 ){ + db->errCode = SQLITE_NOMEM; + return SQLITE_NOMEM; + } + res.azResult[0] = 0; + rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg); + assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); + res.azResult[0] = SQLITE_INT_TO_PTR(res.nData); + if( (rc&0xff)==SQLITE_ABORT ){ + sqlite3_free_table(&res.azResult[1]); + if( res.zErrMsg ){ + if( pzErrMsg ){ + sqlite3_free(*pzErrMsg); + *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); + } + sqlite3_free(res.zErrMsg); + } + db->errCode = res.rc; /* Assume 32-bit assignment is atomic */ + return res.rc; + } + sqlite3_free(res.zErrMsg); + if( rc!=SQLITE_OK ){ + sqlite3_free_table(&res.azResult[1]); + return rc; + } + if( res.nAlloc>res.nData ){ + char **azNew; + azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData ); + if( azNew==0 ){ + sqlite3_free_table(&res.azResult[1]); + db->errCode = SQLITE_NOMEM; + return SQLITE_NOMEM; + } + res.azResult = azNew; + } + *pazResult = &res.azResult[1]; + if( pnColumn ) *pnColumn = res.nColumn; + if( pnRow ) *pnRow = res.nRow; + return rc; +} + +/* +** This routine frees the space the sqlite3_get_table() malloced. +*/ +void sqlite3_free_table( + char **azResult /* Result returned from from sqlite3_get_table() */ +){ + if( azResult ){ + int i, n; + azResult--; + assert( azResult!=0 ); + n = SQLITE_PTR_TO_INT(azResult[0]); + for(i=1; i + +/* +** Some additional include files are needed if this file is not +** appended to the amalgamation. +*/ +#ifndef SQLITE_AMALGAMATION +# include "sqlite3.h" +# include +# include +# include + typedef unsigned char u8; +#endif +#include + +/* Used to get the current process ID */ +#if !defined(_WIN32) +# include +# define GETPID getpid +#elif !defined(_WIN32_WCE) +# ifndef SQLITE_AMALGAMATION +# define WIN32_LEAN_AND_MEAN +# include +# endif +# define GETPID (int)GetCurrentProcessId +#endif + +/* + * Windows needs to know which symbols to export. Unix does not. + * BUILD_sqlite should be undefined for Unix. + */ +#ifdef BUILD_sqlite +#undef TCL_STORAGE_CLASS +#define TCL_STORAGE_CLASS DLLEXPORT +#endif /* BUILD_sqlite */ + +#define NUM_PREPARED_STMTS 10 +#define MAX_PREPARED_STMTS 100 + +/* Forward declaration */ +typedef struct SqliteDb SqliteDb; + +/* +** New SQL functions can be created as TCL scripts. Each such function +** is described by an instance of the following structure. +*/ +typedef struct SqlFunc SqlFunc; +struct SqlFunc { + Tcl_Interp *interp; /* The TCL interpret to execute the function */ + Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */ + SqliteDb *pDb; /* Database connection that owns this function */ + int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */ + char *zName; /* Name of this function */ + SqlFunc *pNext; /* Next function on the list of them all */ +}; + +/* +** New collation sequences function can be created as TCL scripts. Each such +** function is described by an instance of the following structure. +*/ +typedef struct SqlCollate SqlCollate; +struct SqlCollate { + Tcl_Interp *interp; /* The TCL interpret to execute the function */ + char *zScript; /* The script to be run */ + SqlCollate *pNext; /* Next function on the list of them all */ +}; + +/* +** Prepared statements are cached for faster execution. Each prepared +** statement is described by an instance of the following structure. +*/ +typedef struct SqlPreparedStmt SqlPreparedStmt; +struct SqlPreparedStmt { + SqlPreparedStmt *pNext; /* Next in linked list */ + SqlPreparedStmt *pPrev; /* Previous on the list */ + sqlite3_stmt *pStmt; /* The prepared statement */ + int nSql; /* chars in zSql[] */ + const char *zSql; /* Text of the SQL statement */ + int nParm; /* Size of apParm array */ + Tcl_Obj **apParm; /* Array of referenced object pointers */ +}; + +typedef struct IncrblobChannel IncrblobChannel; + +/* +** There is one instance of this structure for each SQLite database +** that has been opened by the SQLite TCL interface. +** +** If this module is built with SQLITE_TEST defined (to create the SQLite +** testfixture executable), then it may be configured to use either +** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements. +** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used. +*/ +struct SqliteDb { + sqlite3 *db; /* The "real" database structure. MUST BE FIRST */ + Tcl_Interp *interp; /* The interpreter used for this database */ + char *zBusy; /* The busy callback routine */ + char *zCommit; /* The commit hook callback routine */ + char *zTrace; /* The trace callback routine */ + char *zProfile; /* The profile callback routine */ + char *zProgress; /* The progress callback routine */ + char *zAuth; /* The authorization callback routine */ + int disableAuth; /* Disable the authorizer if it exists */ + char *zNull; /* Text to substitute for an SQL NULL value */ + SqlFunc *pFunc; /* List of SQL functions */ + Tcl_Obj *pUpdateHook; /* Update hook script (if any) */ + Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */ + Tcl_Obj *pWalHook; /* WAL hook script (if any) */ + Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */ + SqlCollate *pCollate; /* List of SQL collation functions */ + int rc; /* Return code of most recent sqlite3_exec() */ + Tcl_Obj *pCollateNeeded; /* Collation needed script */ + SqlPreparedStmt *stmtList; /* List of prepared statements*/ + SqlPreparedStmt *stmtLast; /* Last statement in the list */ + int maxStmt; /* The next maximum number of stmtList */ + int nStmt; /* Number of statements in stmtList */ + IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */ + int nStep, nSort, nIndex; /* Statistics for most recent operation */ + int nTransaction; /* Number of nested [transaction] methods */ +#ifdef SQLITE_TEST + int bLegacyPrepare; /* True to use sqlite3_prepare() */ +#endif +}; + +struct IncrblobChannel { + sqlite3_blob *pBlob; /* sqlite3 blob handle */ + SqliteDb *pDb; /* Associated database connection */ + int iSeek; /* Current seek offset */ + Tcl_Channel channel; /* Channel identifier */ + IncrblobChannel *pNext; /* Linked list of all open incrblob channels */ + IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */ +}; + +/* +** Compute a string length that is limited to what can be stored in +** lower 30 bits of a 32-bit signed integer. +*/ +static int strlen30(const char *z){ + const char *z2 = z; + while( *z2 ){ z2++; } + return 0x3fffffff & (int)(z2 - z); +} + + +#ifndef SQLITE_OMIT_INCRBLOB +/* +** Close all incrblob channels opened using database connection pDb. +** This is called when shutting down the database connection. +*/ +static void closeIncrblobChannels(SqliteDb *pDb){ + IncrblobChannel *p; + IncrblobChannel *pNext; + + for(p=pDb->pIncrblob; p; p=pNext){ + pNext = p->pNext; + + /* Note: Calling unregister here call Tcl_Close on the incrblob channel, + ** which deletes the IncrblobChannel structure at *p. So do not + ** call Tcl_Free() here. + */ + Tcl_UnregisterChannel(pDb->interp, p->channel); + } +} + +/* +** Close an incremental blob channel. +*/ +static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){ + IncrblobChannel *p = (IncrblobChannel *)instanceData; + int rc = sqlite3_blob_close(p->pBlob); + sqlite3 *db = p->pDb->db; + + /* Remove the channel from the SqliteDb.pIncrblob list. */ + if( p->pNext ){ + p->pNext->pPrev = p->pPrev; + } + if( p->pPrev ){ + p->pPrev->pNext = p->pNext; + } + if( p->pDb->pIncrblob==p ){ + p->pDb->pIncrblob = p->pNext; + } + + /* Free the IncrblobChannel structure */ + Tcl_Free((char *)p); + + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Read data from an incremental blob channel. +*/ +static int incrblobInput( + ClientData instanceData, + char *buf, + int bufSize, + int *errorCodePtr +){ + IncrblobChannel *p = (IncrblobChannel *)instanceData; + int nRead = bufSize; /* Number of bytes to read */ + int nBlob; /* Total size of the blob */ + int rc; /* sqlite error code */ + + nBlob = sqlite3_blob_bytes(p->pBlob); + if( (p->iSeek+nRead)>nBlob ){ + nRead = nBlob-p->iSeek; + } + if( nRead<=0 ){ + return 0; + } + + rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek); + if( rc!=SQLITE_OK ){ + *errorCodePtr = rc; + return -1; + } + + p->iSeek += nRead; + return nRead; +} + +/* +** Write data to an incremental blob channel. +*/ +static int incrblobOutput( + ClientData instanceData, + CONST char *buf, + int toWrite, + int *errorCodePtr +){ + IncrblobChannel *p = (IncrblobChannel *)instanceData; + int nWrite = toWrite; /* Number of bytes to write */ + int nBlob; /* Total size of the blob */ + int rc; /* sqlite error code */ + + nBlob = sqlite3_blob_bytes(p->pBlob); + if( (p->iSeek+nWrite)>nBlob ){ + *errorCodePtr = EINVAL; + return -1; + } + if( nWrite<=0 ){ + return 0; + } + + rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek); + if( rc!=SQLITE_OK ){ + *errorCodePtr = EIO; + return -1; + } + + p->iSeek += nWrite; + return nWrite; +} + +/* +** Seek an incremental blob channel. +*/ +static int incrblobSeek( + ClientData instanceData, + long offset, + int seekMode, + int *errorCodePtr +){ + IncrblobChannel *p = (IncrblobChannel *)instanceData; + + switch( seekMode ){ + case SEEK_SET: + p->iSeek = offset; + break; + case SEEK_CUR: + p->iSeek += offset; + break; + case SEEK_END: + p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset; + break; + + default: assert(!"Bad seekMode"); + } + + return p->iSeek; +} + + +static void incrblobWatch(ClientData instanceData, int mode){ + /* NO-OP */ +} +static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){ + return TCL_ERROR; +} + +static Tcl_ChannelType IncrblobChannelType = { + "incrblob", /* typeName */ + TCL_CHANNEL_VERSION_2, /* version */ + incrblobClose, /* closeProc */ + incrblobInput, /* inputProc */ + incrblobOutput, /* outputProc */ + incrblobSeek, /* seekProc */ + 0, /* setOptionProc */ + 0, /* getOptionProc */ + incrblobWatch, /* watchProc (this is a no-op) */ + incrblobHandle, /* getHandleProc (always returns error) */ + 0, /* close2Proc */ + 0, /* blockModeProc */ + 0, /* flushProc */ + 0, /* handlerProc */ + 0, /* wideSeekProc */ +}; + +/* +** Create a new incrblob channel. +*/ +static int createIncrblobChannel( + Tcl_Interp *interp, + SqliteDb *pDb, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite_int64 iRow, + int isReadonly +){ + IncrblobChannel *p; + sqlite3 *db = pDb->db; + sqlite3_blob *pBlob; + int rc; + int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE); + + /* This variable is used to name the channels: "incrblob_[incr count]" */ + static int count = 0; + char zChannel[64]; + + rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); + return TCL_ERROR; + } + + p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel)); + p->iSeek = 0; + p->pBlob = pBlob; + + sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count); + p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags); + Tcl_RegisterChannel(interp, p->channel); + + /* Link the new channel into the SqliteDb.pIncrblob list. */ + p->pNext = pDb->pIncrblob; + p->pPrev = 0; + if( p->pNext ){ + p->pNext->pPrev = p; + } + pDb->pIncrblob = p; + p->pDb = pDb; + + Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE); + return TCL_OK; +} +#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */ + #define closeIncrblobChannels(pDb) +#endif + +/* +** Look at the script prefix in pCmd. We will be executing this script +** after first appending one or more arguments. This routine analyzes +** the script to see if it is safe to use Tcl_EvalObjv() on the script +** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much +** faster. +** +** Scripts that are safe to use with Tcl_EvalObjv() consists of a +** command name followed by zero or more arguments with no [...] or $ +** or {...} or ; to be seen anywhere. Most callback scripts consist +** of just a single procedure name and they meet this requirement. +*/ +static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){ + /* We could try to do something with Tcl_Parse(). But we will instead + ** just do a search for forbidden characters. If any of the forbidden + ** characters appear in pCmd, we will report the string as unsafe. + */ + const char *z; + int n; + z = Tcl_GetStringFromObj(pCmd, &n); + while( n-- > 0 ){ + int c = *(z++); + if( c=='$' || c=='[' || c==';' ) return 0; + } + return 1; +} + +/* +** Find an SqlFunc structure with the given name. Or create a new +** one if an existing one cannot be found. Return a pointer to the +** structure. +*/ +static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){ + SqlFunc *p, *pNew; + int i; + pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 ); + pNew->zName = (char*)&pNew[1]; + for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); } + pNew->zName[i] = 0; + for(p=pDb->pFunc; p; p=p->pNext){ + if( strcmp(p->zName, pNew->zName)==0 ){ + Tcl_Free((char*)pNew); + return p; + } + } + pNew->interp = pDb->interp; + pNew->pDb = pDb; + pNew->pScript = 0; + pNew->pNext = pDb->pFunc; + pDb->pFunc = pNew; + return pNew; +} + +/* +** Free a single SqlPreparedStmt object. +*/ +static void dbFreeStmt(SqlPreparedStmt *pStmt){ +#ifdef SQLITE_TEST + if( sqlite3_sql(pStmt->pStmt)==0 ){ + Tcl_Free((char *)pStmt->zSql); + } +#endif + sqlite3_finalize(pStmt->pStmt); + Tcl_Free((char *)pStmt); +} + +/* +** Finalize and free a list of prepared statements +*/ +static void flushStmtCache(SqliteDb *pDb){ + SqlPreparedStmt *pPreStmt; + SqlPreparedStmt *pNext; + + for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){ + pNext = pPreStmt->pNext; + dbFreeStmt(pPreStmt); + } + pDb->nStmt = 0; + pDb->stmtLast = 0; + pDb->stmtList = 0; +} + +/* +** TCL calls this procedure when an sqlite3 database command is +** deleted. +*/ +static void DbDeleteCmd(void *db){ + SqliteDb *pDb = (SqliteDb*)db; + flushStmtCache(pDb); + closeIncrblobChannels(pDb); + sqlite3_close(pDb->db); + while( pDb->pFunc ){ + SqlFunc *pFunc = pDb->pFunc; + pDb->pFunc = pFunc->pNext; + assert( pFunc->pDb==pDb ); + Tcl_DecrRefCount(pFunc->pScript); + Tcl_Free((char*)pFunc); + } + while( pDb->pCollate ){ + SqlCollate *pCollate = pDb->pCollate; + pDb->pCollate = pCollate->pNext; + Tcl_Free((char*)pCollate); + } + if( pDb->zBusy ){ + Tcl_Free(pDb->zBusy); + } + if( pDb->zTrace ){ + Tcl_Free(pDb->zTrace); + } + if( pDb->zProfile ){ + Tcl_Free(pDb->zProfile); + } + if( pDb->zAuth ){ + Tcl_Free(pDb->zAuth); + } + if( pDb->zNull ){ + Tcl_Free(pDb->zNull); + } + if( pDb->pUpdateHook ){ + Tcl_DecrRefCount(pDb->pUpdateHook); + } + if( pDb->pRollbackHook ){ + Tcl_DecrRefCount(pDb->pRollbackHook); + } + if( pDb->pWalHook ){ + Tcl_DecrRefCount(pDb->pWalHook); + } + if( pDb->pCollateNeeded ){ + Tcl_DecrRefCount(pDb->pCollateNeeded); + } + Tcl_Free((char*)pDb); +} + +/* +** This routine is called when a database file is locked while trying +** to execute SQL. +*/ +static int DbBusyHandler(void *cd, int nTries){ + SqliteDb *pDb = (SqliteDb*)cd; + int rc; + char zVal[30]; + + sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries); + rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0); + if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ + return 0; + } + return 1; +} + +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK +/* +** This routine is invoked as the 'progress callback' for the database. +*/ +static int DbProgressHandler(void *cd){ + SqliteDb *pDb = (SqliteDb*)cd; + int rc; + + assert( pDb->zProgress ); + rc = Tcl_Eval(pDb->interp, pDb->zProgress); + if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ + return 1; + } + return 0; +} +#endif + +#ifndef SQLITE_OMIT_TRACE +/* +** This routine is called by the SQLite trace handler whenever a new +** block of SQL is executed. The TCL script in pDb->zTrace is executed. +*/ +static void DbTraceHandler(void *cd, const char *zSql){ + SqliteDb *pDb = (SqliteDb*)cd; + Tcl_DString str; + + Tcl_DStringInit(&str); + Tcl_DStringAppend(&str, pDb->zTrace, -1); + Tcl_DStringAppendElement(&str, zSql); + Tcl_Eval(pDb->interp, Tcl_DStringValue(&str)); + Tcl_DStringFree(&str); + Tcl_ResetResult(pDb->interp); +} +#endif + +#ifndef SQLITE_OMIT_TRACE +/* +** This routine is called by the SQLite profile handler after a statement +** SQL has executed. The TCL script in pDb->zProfile is evaluated. +*/ +static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){ + SqliteDb *pDb = (SqliteDb*)cd; + Tcl_DString str; + char zTm[100]; + + sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm); + Tcl_DStringInit(&str); + Tcl_DStringAppend(&str, pDb->zProfile, -1); + Tcl_DStringAppendElement(&str, zSql); + Tcl_DStringAppendElement(&str, zTm); + Tcl_Eval(pDb->interp, Tcl_DStringValue(&str)); + Tcl_DStringFree(&str); + Tcl_ResetResult(pDb->interp); +} +#endif + +/* +** This routine is called when a transaction is committed. The +** TCL script in pDb->zCommit is executed. If it returns non-zero or +** if it throws an exception, the transaction is rolled back instead +** of being committed. +*/ +static int DbCommitHandler(void *cd){ + SqliteDb *pDb = (SqliteDb*)cd; + int rc; + + rc = Tcl_Eval(pDb->interp, pDb->zCommit); + if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ + return 1; + } + return 0; +} + +static void DbRollbackHandler(void *clientData){ + SqliteDb *pDb = (SqliteDb*)clientData; + assert(pDb->pRollbackHook); + if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){ + Tcl_BackgroundError(pDb->interp); + } +} + +/* +** This procedure handles wal_hook callbacks. +*/ +static int DbWalHandler( + void *clientData, + sqlite3 *db, + const char *zDb, + int nEntry +){ + int ret = SQLITE_OK; + Tcl_Obj *p; + SqliteDb *pDb = (SqliteDb*)clientData; + Tcl_Interp *interp = pDb->interp; + assert(pDb->pWalHook); + + p = Tcl_DuplicateObj(pDb->pWalHook); + Tcl_IncrRefCount(p); + Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1)); + Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry)); + if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0) + || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret) + ){ + Tcl_BackgroundError(interp); + } + Tcl_DecrRefCount(p); + + return ret; +} + +#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) +static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){ + char zBuf[64]; + sprintf(zBuf, "%d", iArg); + Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY); + sprintf(zBuf, "%d", nArg); + Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY); +} +#else +# define setTestUnlockNotifyVars(x,y,z) +#endif + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY +static void DbUnlockNotify(void **apArg, int nArg){ + int i; + for(i=0; iinterp, i, nArg); + assert( pDb->pUnlockNotify); + Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags); + Tcl_DecrRefCount(pDb->pUnlockNotify); + pDb->pUnlockNotify = 0; + } +} +#endif + +static void DbUpdateHandler( + void *p, + int op, + const char *zDb, + const char *zTbl, + sqlite_int64 rowid +){ + SqliteDb *pDb = (SqliteDb *)p; + Tcl_Obj *pCmd; + + assert( pDb->pUpdateHook ); + assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE ); + + pCmd = Tcl_DuplicateObj(pDb->pUpdateHook); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj( + ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid)); + Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); +} + +static void tclCollateNeeded( + void *pCtx, + sqlite3 *db, + int enc, + const char *zName +){ + SqliteDb *pDb = (SqliteDb *)pCtx; + Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded); + Tcl_IncrRefCount(pScript); + Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1)); + Tcl_EvalObjEx(pDb->interp, pScript, 0); + Tcl_DecrRefCount(pScript); +} + +/* +** This routine is called to evaluate an SQL collation function implemented +** using TCL script. +*/ +static int tclSqlCollate( + void *pCtx, + int nA, + const void *zA, + int nB, + const void *zB +){ + SqlCollate *p = (SqlCollate *)pCtx; + Tcl_Obj *pCmd; + + pCmd = Tcl_NewStringObj(p->zScript, -1); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA)); + Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB)); + Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); + return (atoi(Tcl_GetStringResult(p->interp))); +} + +/* +** This routine is called to evaluate an SQL function implemented +** using TCL script. +*/ +static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){ + SqlFunc *p = sqlite3_user_data(context); + Tcl_Obj *pCmd; + int i; + int rc; + + if( argc==0 ){ + /* If there are no arguments to the function, call Tcl_EvalObjEx on the + ** script object directly. This allows the TCL compiler to generate + ** bytecode for the command on the first invocation and thus make + ** subsequent invocations much faster. */ + pCmd = p->pScript; + Tcl_IncrRefCount(pCmd); + rc = Tcl_EvalObjEx(p->interp, pCmd, 0); + Tcl_DecrRefCount(pCmd); + }else{ + /* If there are arguments to the function, make a shallow copy of the + ** script object, lappend the arguments, then evaluate the copy. + ** + ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated. + ** The new Tcl_Obj contains pointers to the original list elements. + ** That way, when Tcl_EvalObjv() is run and shimmers the first element + ** of the list to tclCmdNameType, that alternate representation will + ** be preserved and reused on the next invocation. + */ + Tcl_Obj **aArg; + int nArg; + if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){ + sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); + return; + } + pCmd = Tcl_NewListObj(nArg, aArg); + Tcl_IncrRefCount(pCmd); + for(i=0; i=-2147483647 && v<=2147483647 ){ + pVal = Tcl_NewIntObj((int)v); + }else{ + pVal = Tcl_NewWideIntObj(v); + } + break; + } + case SQLITE_FLOAT: { + double r = sqlite3_value_double(pIn); + pVal = Tcl_NewDoubleObj(r); + break; + } + case SQLITE_NULL: { + pVal = Tcl_NewStringObj(p->pDb->zNull, -1); + break; + } + default: { + int bytes = sqlite3_value_bytes(pIn); + pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes); + break; + } + } + rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal); + if( rc ){ + Tcl_DecrRefCount(pCmd); + sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); + return; + } + } + if( !p->useEvalObjv ){ + /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd + ** is a list without a string representation. To prevent this from + ** happening, make sure pCmd has a valid string representation */ + Tcl_GetString(pCmd); + } + rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); + } + + if( rc && rc!=TCL_RETURN ){ + sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); + }else{ + Tcl_Obj *pVar = Tcl_GetObjResult(p->interp); + int n; + u8 *data; + const char *zType = (pVar->typePtr ? pVar->typePtr->name : ""); + char c = zType[0]; + if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){ + /* Only return a BLOB type if the Tcl variable is a bytearray and + ** has no string representation. */ + data = Tcl_GetByteArrayFromObj(pVar, &n); + sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT); + }else if( c=='b' && strcmp(zType,"boolean")==0 ){ + Tcl_GetIntFromObj(0, pVar, &n); + sqlite3_result_int(context, n); + }else if( c=='d' && strcmp(zType,"double")==0 ){ + double r; + Tcl_GetDoubleFromObj(0, pVar, &r); + sqlite3_result_double(context, r); + }else if( (c=='w' && strcmp(zType,"wideInt")==0) || + (c=='i' && strcmp(zType,"int")==0) ){ + Tcl_WideInt v; + Tcl_GetWideIntFromObj(0, pVar, &v); + sqlite3_result_int64(context, v); + }else{ + data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n); + sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT); + } + } +} + +#ifndef SQLITE_OMIT_AUTHORIZATION +/* +** This is the authentication function. It appends the authentication +** type code and the two arguments to zCmd[] then invokes the result +** on the interpreter. The reply is examined to determine if the +** authentication fails or succeeds. +*/ +static int auth_callback( + void *pArg, + int code, + const char *zArg1, + const char *zArg2, + const char *zArg3, + const char *zArg4 +){ + char *zCode; + Tcl_DString str; + int rc; + const char *zReply; + SqliteDb *pDb = (SqliteDb*)pArg; + if( pDb->disableAuth ) return SQLITE_OK; + + switch( code ){ + case SQLITE_COPY : zCode="SQLITE_COPY"; break; + case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break; + case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break; + case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break; + case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break; + case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break; + case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break; + case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break; + case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break; + case SQLITE_DELETE : zCode="SQLITE_DELETE"; break; + case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break; + case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break; + case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break; + case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break; + case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break; + case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break; + case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break; + case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break; + case SQLITE_INSERT : zCode="SQLITE_INSERT"; break; + case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break; + case SQLITE_READ : zCode="SQLITE_READ"; break; + case SQLITE_SELECT : zCode="SQLITE_SELECT"; break; + case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break; + case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break; + case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break; + case SQLITE_DETACH : zCode="SQLITE_DETACH"; break; + case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break; + case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break; + case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break; + case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break; + case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break; + case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break; + case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break; + default : zCode="????"; break; + } + Tcl_DStringInit(&str); + Tcl_DStringAppend(&str, pDb->zAuth, -1); + Tcl_DStringAppendElement(&str, zCode); + Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : ""); + Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : ""); + Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : ""); + Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : ""); + rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str)); + Tcl_DStringFree(&str); + zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY"; + if( strcmp(zReply,"SQLITE_OK")==0 ){ + rc = SQLITE_OK; + }else if( strcmp(zReply,"SQLITE_DENY")==0 ){ + rc = SQLITE_DENY; + }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){ + rc = SQLITE_IGNORE; + }else{ + rc = 999; + } + return rc; +} +#endif /* SQLITE_OMIT_AUTHORIZATION */ + +/* +** This routine reads a line of text from FILE in, stores +** the text in memory obtained from malloc() and returns a pointer +** to the text. NULL is returned at end of file, or if malloc() +** fails. +** +** The interface is like "readline" but no command-line editing +** is done. +** +** copied from shell.c from '.import' command +*/ +static char *local_getline(char *zPrompt, FILE *in){ + char *zLine; + int nLine; + int n; + + nLine = 100; + zLine = malloc( nLine ); + if( zLine==0 ) return 0; + n = 0; + while( 1 ){ + if( n+100>nLine ){ + nLine = nLine*2 + 100; + zLine = realloc(zLine, nLine); + if( zLine==0 ) return 0; + } + if( fgets(&zLine[n], nLine - n, in)==0 ){ + if( n==0 ){ + free(zLine); + return 0; + } + zLine[n] = 0; + break; + } + while( zLine[n] ){ n++; } + if( n>0 && zLine[n-1]=='\n' ){ + n--; + zLine[n] = 0; + break; + } + } + zLine = realloc( zLine, n+1 ); + return zLine; +} + + +/* +** This function is part of the implementation of the command: +** +** $db transaction [-deferred|-immediate|-exclusive] SCRIPT +** +** It is invoked after evaluating the script SCRIPT to commit or rollback +** the transaction or savepoint opened by the [transaction] command. +*/ +static int DbTransPostCmd( + ClientData data[], /* data[0] is the Sqlite3Db* for $db */ + Tcl_Interp *interp, /* Tcl interpreter */ + int result /* Result of evaluating SCRIPT */ +){ + static const char *azEnd[] = { + "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */ + "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */ + "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction", + "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */ + }; + SqliteDb *pDb = (SqliteDb*)data[0]; + int rc = result; + const char *zEnd; + + pDb->nTransaction--; + zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)]; + + pDb->disableAuth++; + if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){ + /* This is a tricky scenario to handle. The most likely cause of an + ** error is that the exec() above was an attempt to commit the + ** top-level transaction that returned SQLITE_BUSY. Or, less likely, + ** that an IO-error has occurred. In either case, throw a Tcl exception + ** and try to rollback the transaction. + ** + ** But it could also be that the user executed one or more BEGIN, + ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing + ** this method's logic. Not clear how this would be best handled. + */ + if( rc!=TCL_ERROR ){ + Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0); + rc = TCL_ERROR; + } + sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0); + } + pDb->disableAuth--; + + return rc; +} + +/* +** Unless SQLITE_TEST is defined, this function is a simple wrapper around +** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either +** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending +** on whether or not the [db_use_legacy_prepare] command has been used to +** configure the connection. +*/ +static int dbPrepare( + SqliteDb *pDb, /* Database object */ + const char *zSql, /* SQL to compile */ + sqlite3_stmt **ppStmt, /* OUT: Prepared statement */ + const char **pzOut /* OUT: Pointer to next SQL statement */ +){ +#ifdef SQLITE_TEST + if( pDb->bLegacyPrepare ){ + return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut); + } +#endif + return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut); +} + +/* +** Search the cache for a prepared-statement object that implements the +** first SQL statement in the buffer pointed to by parameter zIn. If +** no such prepared-statement can be found, allocate and prepare a new +** one. In either case, bind the current values of the relevant Tcl +** variables to any $var, :var or @var variables in the statement. Before +** returning, set *ppPreStmt to point to the prepared-statement object. +** +** Output parameter *pzOut is set to point to the next SQL statement in +** buffer zIn, or to the '\0' byte at the end of zIn if there is no +** next statement. +** +** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned +** and an error message loaded into interpreter pDb->interp. +*/ +static int dbPrepareAndBind( + SqliteDb *pDb, /* Database object */ + char const *zIn, /* SQL to compile */ + char const **pzOut, /* OUT: Pointer to next SQL statement */ + SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */ +){ + const char *zSql = zIn; /* Pointer to first SQL statement in zIn */ + sqlite3_stmt *pStmt; /* Prepared statement object */ + SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */ + int nSql; /* Length of zSql in bytes */ + int nVar; /* Number of variables in statement */ + int iParm = 0; /* Next free entry in apParm */ + int i; + Tcl_Interp *interp = pDb->interp; + + *ppPreStmt = 0; + + /* Trim spaces from the start of zSql and calculate the remaining length. */ + while( isspace(zSql[0]) ){ zSql++; } + nSql = strlen30(zSql); + + for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){ + int n = pPreStmt->nSql; + if( nSql>=n + && memcmp(pPreStmt->zSql, zSql, n)==0 + && (zSql[n]==0 || zSql[n-1]==';') + ){ + pStmt = pPreStmt->pStmt; + *pzOut = &zSql[pPreStmt->nSql]; + + /* When a prepared statement is found, unlink it from the + ** cache list. It will later be added back to the beginning + ** of the cache list in order to implement LRU replacement. + */ + if( pPreStmt->pPrev ){ + pPreStmt->pPrev->pNext = pPreStmt->pNext; + }else{ + pDb->stmtList = pPreStmt->pNext; + } + if( pPreStmt->pNext ){ + pPreStmt->pNext->pPrev = pPreStmt->pPrev; + }else{ + pDb->stmtLast = pPreStmt->pPrev; + } + pDb->nStmt--; + nVar = sqlite3_bind_parameter_count(pStmt); + break; + } + } + + /* If no prepared statement was found. Compile the SQL text. Also allocate + ** a new SqlPreparedStmt structure. */ + if( pPreStmt==0 ){ + int nByte; + + if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1)); + return TCL_ERROR; + } + if( pStmt==0 ){ + if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){ + /* A compile-time error in the statement. */ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1)); + return TCL_ERROR; + }else{ + /* The statement was a no-op. Continue to the next statement + ** in the SQL string. + */ + return TCL_OK; + } + } + + assert( pPreStmt==0 ); + nVar = sqlite3_bind_parameter_count(pStmt); + nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *); + pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte); + memset(pPreStmt, 0, nByte); + + pPreStmt->pStmt = pStmt; + pPreStmt->nSql = (int)(*pzOut - zSql); + pPreStmt->zSql = sqlite3_sql(pStmt); + pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1]; +#ifdef SQLITE_TEST + if( pPreStmt->zSql==0 ){ + char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1); + memcpy(zCopy, zSql, pPreStmt->nSql); + zCopy[pPreStmt->nSql] = '\0'; + pPreStmt->zSql = zCopy; + } +#endif + } + assert( pPreStmt ); + assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql ); + assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) ); + + /* Bind values to parameters that begin with $ or : */ + for(i=1; i<=nVar; i++){ + const char *zVar = sqlite3_bind_parameter_name(pStmt, i); + if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){ + Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0); + if( pVar ){ + int n; + u8 *data; + const char *zType = (pVar->typePtr ? pVar->typePtr->name : ""); + char c = zType[0]; + if( zVar[0]=='@' || + (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){ + /* Load a BLOB type if the Tcl variable is a bytearray and + ** it has no string representation or the host + ** parameter name begins with "@". */ + data = Tcl_GetByteArrayFromObj(pVar, &n); + sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC); + Tcl_IncrRefCount(pVar); + pPreStmt->apParm[iParm++] = pVar; + }else if( c=='b' && strcmp(zType,"boolean")==0 ){ + Tcl_GetIntFromObj(interp, pVar, &n); + sqlite3_bind_int(pStmt, i, n); + }else if( c=='d' && strcmp(zType,"double")==0 ){ + double r; + Tcl_GetDoubleFromObj(interp, pVar, &r); + sqlite3_bind_double(pStmt, i, r); + }else if( (c=='w' && strcmp(zType,"wideInt")==0) || + (c=='i' && strcmp(zType,"int")==0) ){ + Tcl_WideInt v; + Tcl_GetWideIntFromObj(interp, pVar, &v); + sqlite3_bind_int64(pStmt, i, v); + }else{ + data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n); + sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC); + Tcl_IncrRefCount(pVar); + pPreStmt->apParm[iParm++] = pVar; + } + }else{ + sqlite3_bind_null(pStmt, i); + } + } + } + pPreStmt->nParm = iParm; + *ppPreStmt = pPreStmt; + + return TCL_OK; +} + +/* +** Release a statement reference obtained by calling dbPrepareAndBind(). +** There should be exactly one call to this function for each call to +** dbPrepareAndBind(). +** +** If the discard parameter is non-zero, then the statement is deleted +** immediately. Otherwise it is added to the LRU list and may be returned +** by a subsequent call to dbPrepareAndBind(). +*/ +static void dbReleaseStmt( + SqliteDb *pDb, /* Database handle */ + SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */ + int discard /* True to delete (not cache) the pPreStmt */ +){ + int i; + + /* Free the bound string and blob parameters */ + for(i=0; inParm; i++){ + Tcl_DecrRefCount(pPreStmt->apParm[i]); + } + pPreStmt->nParm = 0; + + if( pDb->maxStmt<=0 || discard ){ + /* If the cache is turned off, deallocated the statement */ + dbFreeStmt(pPreStmt); + }else{ + /* Add the prepared statement to the beginning of the cache list. */ + pPreStmt->pNext = pDb->stmtList; + pPreStmt->pPrev = 0; + if( pDb->stmtList ){ + pDb->stmtList->pPrev = pPreStmt; + } + pDb->stmtList = pPreStmt; + if( pDb->stmtLast==0 ){ + assert( pDb->nStmt==0 ); + pDb->stmtLast = pPreStmt; + }else{ + assert( pDb->nStmt>0 ); + } + pDb->nStmt++; + + /* If we have too many statement in cache, remove the surplus from + ** the end of the cache list. */ + while( pDb->nStmt>pDb->maxStmt ){ + SqlPreparedStmt *pLast = pDb->stmtLast; + pDb->stmtLast = pLast->pPrev; + pDb->stmtLast->pNext = 0; + pDb->nStmt--; + dbFreeStmt(pLast); + } + } +} + +/* +** Structure used with dbEvalXXX() functions: +** +** dbEvalInit() +** dbEvalStep() +** dbEvalFinalize() +** dbEvalRowInfo() +** dbEvalColumnValue() +*/ +typedef struct DbEvalContext DbEvalContext; +struct DbEvalContext { + SqliteDb *pDb; /* Database handle */ + Tcl_Obj *pSql; /* Object holding string zSql */ + const char *zSql; /* Remaining SQL to execute */ + SqlPreparedStmt *pPreStmt; /* Current statement */ + int nCol; /* Number of columns returned by pStmt */ + Tcl_Obj *pArray; /* Name of array variable */ + Tcl_Obj **apColName; /* Array of column names */ +}; + +/* +** Release any cache of column names currently held as part of +** the DbEvalContext structure passed as the first argument. +*/ +static void dbReleaseColumnNames(DbEvalContext *p){ + if( p->apColName ){ + int i; + for(i=0; inCol; i++){ + Tcl_DecrRefCount(p->apColName[i]); + } + Tcl_Free((char *)p->apColName); + p->apColName = 0; + } + p->nCol = 0; +} + +/* +** Initialize a DbEvalContext structure. +** +** If pArray is not NULL, then it contains the name of a Tcl array +** variable. The "*" member of this array is set to a list containing +** the names of the columns returned by the statement as part of each +** call to dbEvalStep(), in order from left to right. e.g. if the names +** of the returned columns are a, b and c, it does the equivalent of the +** tcl command: +** +** set ${pArray}(*) {a b c} +*/ +static void dbEvalInit( + DbEvalContext *p, /* Pointer to structure to initialize */ + SqliteDb *pDb, /* Database handle */ + Tcl_Obj *pSql, /* Object containing SQL script */ + Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */ +){ + memset(p, 0, sizeof(DbEvalContext)); + p->pDb = pDb; + p->zSql = Tcl_GetString(pSql); + p->pSql = pSql; + Tcl_IncrRefCount(pSql); + if( pArray ){ + p->pArray = pArray; + Tcl_IncrRefCount(pArray); + } +} + +/* +** Obtain information about the row that the DbEvalContext passed as the +** first argument currently points to. +*/ +static void dbEvalRowInfo( + DbEvalContext *p, /* Evaluation context */ + int *pnCol, /* OUT: Number of column names */ + Tcl_Obj ***papColName /* OUT: Array of column names */ +){ + /* Compute column names */ + if( 0==p->apColName ){ + sqlite3_stmt *pStmt = p->pPreStmt->pStmt; + int i; /* Iterator variable */ + int nCol; /* Number of columns returned by pStmt */ + Tcl_Obj **apColName = 0; /* Array of column names */ + + p->nCol = nCol = sqlite3_column_count(pStmt); + if( nCol>0 && (papColName || p->pArray) ){ + apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol ); + for(i=0; iapColName = apColName; + } + + /* If results are being stored in an array variable, then create + ** the array(*) entry for that array + */ + if( p->pArray ){ + Tcl_Interp *interp = p->pDb->interp; + Tcl_Obj *pColList = Tcl_NewObj(); + Tcl_Obj *pStar = Tcl_NewStringObj("*", -1); + + for(i=0; ipArray, pStar, pColList, 0); + Tcl_DecrRefCount(pStar); + } + } + + if( papColName ){ + *papColName = p->apColName; + } + if( pnCol ){ + *pnCol = p->nCol; + } +} + +/* +** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is +** returned, then an error message is stored in the interpreter before +** returning. +** +** A return value of TCL_OK means there is a row of data available. The +** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This +** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK +** is returned, then the SQL script has finished executing and there are +** no further rows available. This is similar to SQLITE_DONE. +*/ +static int dbEvalStep(DbEvalContext *p){ + const char *zPrevSql = 0; /* Previous value of p->zSql */ + + while( p->zSql[0] || p->pPreStmt ){ + int rc; + if( p->pPreStmt==0 ){ + zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql); + rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt); + if( rc!=TCL_OK ) return rc; + }else{ + int rcs; + SqliteDb *pDb = p->pDb; + SqlPreparedStmt *pPreStmt = p->pPreStmt; + sqlite3_stmt *pStmt = pPreStmt->pStmt; + + rcs = sqlite3_step(pStmt); + if( rcs==SQLITE_ROW ){ + return TCL_OK; + } + if( p->pArray ){ + dbEvalRowInfo(p, 0, 0); + } + rcs = sqlite3_reset(pStmt); + + pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1); + pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1); + pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1); + dbReleaseColumnNames(p); + p->pPreStmt = 0; + + if( rcs!=SQLITE_OK ){ + /* If a run-time error occurs, report the error and stop reading + ** the SQL. */ + dbReleaseStmt(pDb, pPreStmt, 1); +#if SQLITE_TEST + if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){ + /* If the runtime error was an SQLITE_SCHEMA, and the database + ** handle is configured to use the legacy sqlite3_prepare() + ** interface, retry prepare()/step() on the same SQL statement. + ** This only happens once. If there is a second SQLITE_SCHEMA + ** error, the error will be returned to the caller. */ + p->zSql = zPrevSql; + continue; + } +#endif + Tcl_SetObjResult(pDb->interp, + Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1)); + return TCL_ERROR; + }else{ + dbReleaseStmt(pDb, pPreStmt, 0); + } + } + } + + /* Finished */ + return TCL_BREAK; +} + +/* +** Free all resources currently held by the DbEvalContext structure passed +** as the first argument. There should be exactly one call to this function +** for each call to dbEvalInit(). +*/ +static void dbEvalFinalize(DbEvalContext *p){ + if( p->pPreStmt ){ + sqlite3_reset(p->pPreStmt->pStmt); + dbReleaseStmt(p->pDb, p->pPreStmt, 0); + p->pPreStmt = 0; + } + if( p->pArray ){ + Tcl_DecrRefCount(p->pArray); + p->pArray = 0; + } + Tcl_DecrRefCount(p->pSql); + dbReleaseColumnNames(p); +} + +/* +** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains +** the value for the iCol'th column of the row currently pointed to by +** the DbEvalContext structure passed as the first argument. +*/ +static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){ + sqlite3_stmt *pStmt = p->pPreStmt->pStmt; + switch( sqlite3_column_type(pStmt, iCol) ){ + case SQLITE_BLOB: { + int bytes = sqlite3_column_bytes(pStmt, iCol); + const char *zBlob = sqlite3_column_blob(pStmt, iCol); + if( !zBlob ) bytes = 0; + return Tcl_NewByteArrayObj((u8*)zBlob, bytes); + } + case SQLITE_INTEGER: { + sqlite_int64 v = sqlite3_column_int64(pStmt, iCol); + if( v>=-2147483647 && v<=2147483647 ){ + return Tcl_NewIntObj((int)v); + }else{ + return Tcl_NewWideIntObj(v); + } + } + case SQLITE_FLOAT: { + return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol)); + } + case SQLITE_NULL: { + return Tcl_NewStringObj(p->pDb->zNull, -1); + } + } + + return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1); +} + +/* +** If using Tcl version 8.6 or greater, use the NR functions to avoid +** recursive evalution of scripts by the [db eval] and [db trans] +** commands. Even if the headers used while compiling the extension +** are 8.6 or newer, the code still tests the Tcl version at runtime. +** This allows stubs-enabled builds to be used with older Tcl libraries. +*/ +#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6) +# define SQLITE_TCL_NRE 1 +static int DbUseNre(void){ + int major, minor; + Tcl_GetVersion(&major, &minor, 0, 0); + return( (major==8 && minor>=6) || major>8 ); +} +#else +/* +** Compiling using headers earlier than 8.6. In this case NR cannot be +** used, so DbUseNre() to always return zero. Add #defines for the other +** Tcl_NRxxx() functions to prevent them from causing compilation errors, +** even though the only invocations of them are within conditional blocks +** of the form: +** +** if( DbUseNre() ) { ... } +*/ +# define SQLITE_TCL_NRE 0 +# define DbUseNre() 0 +# define Tcl_NRAddCallback(a,b,c,d,e,f) 0 +# define Tcl_NREvalObj(a,b,c) 0 +# define Tcl_NRCreateCommand(a,b,c,d,e,f) 0 +#endif + +/* +** This function is part of the implementation of the command: +** +** $db eval SQL ?ARRAYNAME? SCRIPT +*/ +static int DbEvalNextCmd( + ClientData data[], /* data[0] is the (DbEvalContext*) */ + Tcl_Interp *interp, /* Tcl interpreter */ + int result /* Result so far */ +){ + int rc = result; /* Return code */ + + /* The first element of the data[] array is a pointer to a DbEvalContext + ** structure allocated using Tcl_Alloc(). The second element of data[] + ** is a pointer to a Tcl_Obj containing the script to run for each row + ** returned by the queries encapsulated in data[0]. */ + DbEvalContext *p = (DbEvalContext *)data[0]; + Tcl_Obj *pScript = (Tcl_Obj *)data[1]; + Tcl_Obj *pArray = p->pArray; + + while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){ + int i; + int nCol; + Tcl_Obj **apColName; + dbEvalRowInfo(p, &nCol, &apColName); + for(i=0; i3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zAuth ){ + Tcl_AppendResult(interp, pDb->zAuth, 0); + } + }else{ + char *zAuth; + int len; + if( pDb->zAuth ){ + Tcl_Free(pDb->zAuth); + } + zAuth = Tcl_GetStringFromObj(objv[2], &len); + if( zAuth && len>0 ){ + pDb->zAuth = Tcl_Alloc( len + 1 ); + memcpy(pDb->zAuth, zAuth, len+1); + }else{ + pDb->zAuth = 0; + } + if( pDb->zAuth ){ + pDb->interp = interp; + sqlite3_set_authorizer(pDb->db, auth_callback, pDb); + }else{ + sqlite3_set_authorizer(pDb->db, 0, 0); + } + } +#endif + break; + } + + /* $db backup ?DATABASE? FILENAME + ** + ** Open or create a database file named FILENAME. Transfer the + ** content of local database DATABASE (default: "main") into the + ** FILENAME database. + */ + case DB_BACKUP: { + const char *zDestFile; + const char *zSrcDb; + sqlite3 *pDest; + sqlite3_backup *pBackup; + + if( objc==3 ){ + zSrcDb = "main"; + zDestFile = Tcl_GetString(objv[2]); + }else if( objc==4 ){ + zSrcDb = Tcl_GetString(objv[2]); + zDestFile = Tcl_GetString(objv[3]); + }else{ + Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME"); + return TCL_ERROR; + } + rc = sqlite3_open(zDestFile, &pDest); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "cannot open target database: ", + sqlite3_errmsg(pDest), (char*)0); + sqlite3_close(pDest); + return TCL_ERROR; + } + pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb); + if( pBackup==0 ){ + Tcl_AppendResult(interp, "backup failed: ", + sqlite3_errmsg(pDest), (char*)0); + sqlite3_close(pDest); + return TCL_ERROR; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = TCL_OK; + }else{ + Tcl_AppendResult(interp, "backup failed: ", + sqlite3_errmsg(pDest), (char*)0); + rc = TCL_ERROR; + } + sqlite3_close(pDest); + break; + } + + /* $db busy ?CALLBACK? + ** + ** Invoke the given callback if an SQL statement attempts to open + ** a locked database file. + */ + case DB_BUSY: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zBusy ){ + Tcl_AppendResult(interp, pDb->zBusy, 0); + } + }else{ + char *zBusy; + int len; + if( pDb->zBusy ){ + Tcl_Free(pDb->zBusy); + } + zBusy = Tcl_GetStringFromObj(objv[2], &len); + if( zBusy && len>0 ){ + pDb->zBusy = Tcl_Alloc( len + 1 ); + memcpy(pDb->zBusy, zBusy, len+1); + }else{ + pDb->zBusy = 0; + } + if( pDb->zBusy ){ + pDb->interp = interp; + sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb); + }else{ + sqlite3_busy_handler(pDb->db, 0, 0); + } + } + break; + } + + /* $db cache flush + ** $db cache size n + ** + ** Flush the prepared statement cache, or set the maximum number of + ** cached statements. + */ + case DB_CACHE: { + char *subCmd; + int n; + + if( objc<=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?"); + return TCL_ERROR; + } + subCmd = Tcl_GetStringFromObj( objv[2], 0 ); + if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){ + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "flush"); + return TCL_ERROR; + }else{ + flushStmtCache( pDb ); + } + }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){ + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "size n"); + return TCL_ERROR; + }else{ + if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){ + Tcl_AppendResult( interp, "cannot convert \"", + Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0); + return TCL_ERROR; + }else{ + if( n<0 ){ + flushStmtCache( pDb ); + n = 0; + }else if( n>MAX_PREPARED_STMTS ){ + n = MAX_PREPARED_STMTS; + } + pDb->maxStmt = n; + } + } + }else{ + Tcl_AppendResult( interp, "bad option \"", + Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0); + return TCL_ERROR; + } + break; + } + + /* $db changes + ** + ** Return the number of rows that were modified, inserted, or deleted by + ** the most recent INSERT, UPDATE or DELETE statement, not including + ** any changes made by trigger programs. + */ + case DB_CHANGES: { + Tcl_Obj *pResult; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + pResult = Tcl_GetObjResult(interp); + Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db)); + break; + } + + /* $db close + ** + ** Shutdown the database + */ + case DB_CLOSE: { + Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0)); + break; + } + + /* + ** $db collate NAME SCRIPT + ** + ** Create a new SQL collation function called NAME. Whenever + ** that function is called, invoke SCRIPT to evaluate the function. + */ + case DB_COLLATE: { + SqlCollate *pCollate; + char *zName; + char *zScript; + int nScript; + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT"); + return TCL_ERROR; + } + zName = Tcl_GetStringFromObj(objv[2], 0); + zScript = Tcl_GetStringFromObj(objv[3], &nScript); + pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 ); + if( pCollate==0 ) return TCL_ERROR; + pCollate->interp = interp; + pCollate->pNext = pDb->pCollate; + pCollate->zScript = (char*)&pCollate[1]; + pDb->pCollate = pCollate; + memcpy(pCollate->zScript, zScript, nScript+1); + if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8, + pCollate, tclSqlCollate) ){ + Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); + return TCL_ERROR; + } + break; + } + + /* + ** $db collation_needed SCRIPT + ** + ** Create a new SQL collation function called NAME. Whenever + ** that function is called, invoke SCRIPT to evaluate the function. + */ + case DB_COLLATION_NEEDED: { + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT"); + return TCL_ERROR; + } + if( pDb->pCollateNeeded ){ + Tcl_DecrRefCount(pDb->pCollateNeeded); + } + pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]); + Tcl_IncrRefCount(pDb->pCollateNeeded); + sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded); + break; + } + + /* $db commit_hook ?CALLBACK? + ** + ** Invoke the given callback just before committing every SQL transaction. + ** If the callback throws an exception or returns non-zero, then the + ** transaction is aborted. If CALLBACK is an empty string, the callback + ** is disabled. + */ + case DB_COMMIT_HOOK: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zCommit ){ + Tcl_AppendResult(interp, pDb->zCommit, 0); + } + }else{ + char *zCommit; + int len; + if( pDb->zCommit ){ + Tcl_Free(pDb->zCommit); + } + zCommit = Tcl_GetStringFromObj(objv[2], &len); + if( zCommit && len>0 ){ + pDb->zCommit = Tcl_Alloc( len + 1 ); + memcpy(pDb->zCommit, zCommit, len+1); + }else{ + pDb->zCommit = 0; + } + if( pDb->zCommit ){ + pDb->interp = interp; + sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb); + }else{ + sqlite3_commit_hook(pDb->db, 0, 0); + } + } + break; + } + + /* $db complete SQL + ** + ** Return TRUE if SQL is a complete SQL statement. Return FALSE if + ** additional lines of input are needed. This is similar to the + ** built-in "info complete" command of Tcl. + */ + case DB_COMPLETE: { +#ifndef SQLITE_OMIT_COMPLETE + Tcl_Obj *pResult; + int isComplete; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SQL"); + return TCL_ERROR; + } + isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) ); + pResult = Tcl_GetObjResult(interp); + Tcl_SetBooleanObj(pResult, isComplete); +#endif + break; + } + + /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR? + ** + ** Copy data into table from filename, optionally using SEPARATOR + ** as column separators. If a column contains a null string, or the + ** value of NULLINDICATOR, a NULL is inserted for the column. + ** conflict-algorithm is one of the sqlite conflict algorithms: + ** rollback, abort, fail, ignore, replace + ** On success, return the number of lines processed, not necessarily same + ** as 'db changes' due to conflict-algorithm selected. + ** + ** This code is basically an implementation/enhancement of + ** the sqlite3 shell.c ".import" command. + ** + ** This command usage is equivalent to the sqlite2.x COPY statement, + ** which imports file data into a table using the PostgreSQL COPY file format: + ** $db copy $conflit_algo $table_name $filename \t \\N + */ + case DB_COPY: { + char *zTable; /* Insert data into this table */ + char *zFile; /* The file from which to extract data */ + char *zConflict; /* The conflict algorithm to use */ + sqlite3_stmt *pStmt; /* A statement */ + int nCol; /* Number of columns in the table */ + int nByte; /* Number of bytes in an SQL string */ + int i, j; /* Loop counters */ + int nSep; /* Number of bytes in zSep[] */ + int nNull; /* Number of bytes in zNull[] */ + char *zSql; /* An SQL statement */ + char *zLine; /* A single line of input from the file */ + char **azCol; /* zLine[] broken up into columns */ + char *zCommit; /* How to commit changes */ + FILE *in; /* The input file */ + int lineno = 0; /* Line number of input file */ + char zLineNum[80]; /* Line number print buffer */ + Tcl_Obj *pResult; /* interp result */ + + char *zSep; + char *zNull; + if( objc<5 || objc>7 ){ + Tcl_WrongNumArgs(interp, 2, objv, + "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?"); + return TCL_ERROR; + } + if( objc>=6 ){ + zSep = Tcl_GetStringFromObj(objv[5], 0); + }else{ + zSep = "\t"; + } + if( objc>=7 ){ + zNull = Tcl_GetStringFromObj(objv[6], 0); + }else{ + zNull = ""; + } + zConflict = Tcl_GetStringFromObj(objv[2], 0); + zTable = Tcl_GetStringFromObj(objv[3], 0); + zFile = Tcl_GetStringFromObj(objv[4], 0); + nSep = strlen30(zSep); + nNull = strlen30(zNull); + if( nSep==0 ){ + Tcl_AppendResult(interp,"Error: non-null separator required for copy",0); + return TCL_ERROR; + } + if(strcmp(zConflict, "rollback") != 0 && + strcmp(zConflict, "abort" ) != 0 && + strcmp(zConflict, "fail" ) != 0 && + strcmp(zConflict, "ignore" ) != 0 && + strcmp(zConflict, "replace" ) != 0 ) { + Tcl_AppendResult(interp, "Error: \"", zConflict, + "\", conflict-algorithm must be one of: rollback, " + "abort, fail, ignore, or replace", 0); + return TCL_ERROR; + } + zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable); + if( zSql==0 ){ + Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0); + return TCL_ERROR; + } + nByte = strlen30(zSql); + rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + if( rc ){ + Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0); + nCol = 0; + }else{ + nCol = sqlite3_column_count(pStmt); + } + sqlite3_finalize(pStmt); + if( nCol==0 ) { + return TCL_ERROR; + } + zSql = malloc( nByte + 50 + nCol*2 ); + if( zSql==0 ) { + Tcl_AppendResult(interp, "Error: can't malloc()", 0); + return TCL_ERROR; + } + sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?", + zConflict, zTable); + j = strlen30(zSql); + for(i=1; idb, zSql, -1, &pStmt, 0); + free(zSql); + if( rc ){ + Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0); + sqlite3_finalize(pStmt); + return TCL_ERROR; + } + in = fopen(zFile, "rb"); + if( in==0 ){ + Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL); + sqlite3_finalize(pStmt); + return TCL_ERROR; + } + azCol = malloc( sizeof(azCol[0])*(nCol+1) ); + if( azCol==0 ) { + Tcl_AppendResult(interp, "Error: can't malloc()", 0); + fclose(in); + return TCL_ERROR; + } + (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0); + zCommit = "COMMIT"; + while( (zLine = local_getline(0, in))!=0 ){ + char *z; + lineno++; + azCol[0] = zLine; + for(i=0, z=zLine; *z; z++){ + if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){ + *z = 0; + i++; + if( i0 && strcmp(azCol[i], zNull)==0) + || strlen30(azCol[i])==0 + ){ + sqlite3_bind_null(pStmt, i+1); + }else{ + sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC); + } + } + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + free(zLine); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0); + zCommit = "ROLLBACK"; + break; + } + } + free(azCol); + fclose(in); + sqlite3_finalize(pStmt); + (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0); + + if( zCommit[0] == 'C' ){ + /* success, set result as number of lines processed */ + pResult = Tcl_GetObjResult(interp); + Tcl_SetIntObj(pResult, lineno); + rc = TCL_OK; + }else{ + /* failure, append lineno where failed */ + sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno); + Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0); + rc = TCL_ERROR; + } + break; + } + + /* + ** $db enable_load_extension BOOLEAN + ** + ** Turn the extension loading feature on or off. It if off by + ** default. + */ + case DB_ENABLE_LOAD_EXTENSION: { +#ifndef SQLITE_OMIT_LOAD_EXTENSION + int onoff; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){ + return TCL_ERROR; + } + sqlite3_enable_load_extension(pDb->db, onoff); + break; +#else + Tcl_AppendResult(interp, "extension loading is turned off at compile-time", + 0); + return TCL_ERROR; +#endif + } + + /* + ** $db errorcode + ** + ** Return the numeric error code that was returned by the most recent + ** call to sqlite3_exec(). + */ + case DB_ERRORCODE: { + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db))); + break; + } + + /* + ** $db exists $sql + ** $db onecolumn $sql + ** + ** The onecolumn method is the equivalent of: + ** lindex [$db eval $sql] 0 + */ + case DB_EXISTS: + case DB_ONECOLUMN: { + DbEvalContext sEval; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SQL"); + return TCL_ERROR; + } + + dbEvalInit(&sEval, pDb, objv[2], 0); + rc = dbEvalStep(&sEval); + if( choice==DB_ONECOLUMN ){ + if( rc==TCL_OK ){ + Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0)); + }else if( rc==TCL_BREAK ){ + Tcl_ResetResult(interp); + } + }else if( rc==TCL_BREAK || rc==TCL_OK ){ + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK)); + } + dbEvalFinalize(&sEval); + + if( rc==TCL_BREAK ){ + rc = TCL_OK; + } + break; + } + + /* + ** $db eval $sql ?array? ?{ ...code... }? + ** + ** The SQL statement in $sql is evaluated. For each row, the values are + ** placed in elements of the array named "array" and ...code... is executed. + ** If "array" and "code" are omitted, then no callback is every invoked. + ** If "array" is an empty string, then the values are placed in variables + ** that have the same name as the fields extracted by the query. + */ + case DB_EVAL: { + if( objc<3 || objc>5 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?"); + return TCL_ERROR; + } + + if( objc==3 ){ + DbEvalContext sEval; + Tcl_Obj *pRet = Tcl_NewObj(); + Tcl_IncrRefCount(pRet); + dbEvalInit(&sEval, pDb, objv[2], 0); + while( TCL_OK==(rc = dbEvalStep(&sEval)) ){ + int i; + int nCol; + dbEvalRowInfo(&sEval, &nCol, 0); + for(i=0; i2 && strncmp(z, "-argcount",n)==0 ){ + if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR; + if( nArg<0 ){ + Tcl_AppendResult(interp, "number of arguments must be non-negative", + (char*)0); + return TCL_ERROR; + } + } + pScript = objv[5]; + }else if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT"); + return TCL_ERROR; + }else{ + pScript = objv[3]; + } + zName = Tcl_GetStringFromObj(objv[2], 0); + pFunc = findSqlFunc(pDb, zName); + if( pFunc==0 ) return TCL_ERROR; + if( pFunc->pScript ){ + Tcl_DecrRefCount(pFunc->pScript); + } + pFunc->pScript = pScript; + Tcl_IncrRefCount(pScript); + pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript); + rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8, + pFunc, tclSqlFunc, 0, 0); + if( rc!=SQLITE_OK ){ + rc = TCL_ERROR; + Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); + } + break; + } + + /* + ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID + */ + case DB_INCRBLOB: { +#ifdef SQLITE_OMIT_INCRBLOB + Tcl_AppendResult(interp, "incrblob not available in this build", 0); + return TCL_ERROR; +#else + int isReadonly = 0; + const char *zDb = "main"; + const char *zTable; + const char *zColumn; + Tcl_WideInt iRow; + + /* Check for the -readonly option */ + if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){ + isReadonly = 1; + } + + if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){ + Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID"); + return TCL_ERROR; + } + + if( objc==(6+isReadonly) ){ + zDb = Tcl_GetString(objv[2]); + } + zTable = Tcl_GetString(objv[objc-3]); + zColumn = Tcl_GetString(objv[objc-2]); + rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow); + + if( rc==TCL_OK ){ + rc = createIncrblobChannel( + interp, pDb, zDb, zTable, zColumn, iRow, isReadonly + ); + } +#endif + break; + } + + /* + ** $db interrupt + ** + ** Interrupt the execution of the inner-most SQL interpreter. This + ** causes the SQL statement to return an error of SQLITE_INTERRUPT. + */ + case DB_INTERRUPT: { + sqlite3_interrupt(pDb->db); + break; + } + + /* + ** $db nullvalue ?STRING? + ** + ** Change text used when a NULL comes back from the database. If ?STRING? + ** is not present, then the current string used for NULL is returned. + ** If STRING is present, then STRING is returned. + ** + */ + case DB_NULLVALUE: { + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE"); + return TCL_ERROR; + } + if( objc==3 ){ + int len; + char *zNull = Tcl_GetStringFromObj(objv[2], &len); + if( pDb->zNull ){ + Tcl_Free(pDb->zNull); + } + if( zNull && len>0 ){ + pDb->zNull = Tcl_Alloc( len + 1 ); + memcpy(pDb->zNull, zNull, len); + pDb->zNull[len] = '\0'; + }else{ + pDb->zNull = 0; + } + } + Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1)); + break; + } + + /* + ** $db last_insert_rowid + ** + ** Return an integer which is the ROWID for the most recent insert. + */ + case DB_LAST_INSERT_ROWID: { + Tcl_Obj *pResult; + Tcl_WideInt rowid; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + rowid = sqlite3_last_insert_rowid(pDb->db); + pResult = Tcl_GetObjResult(interp); + Tcl_SetWideIntObj(pResult, rowid); + break; + } + + /* + ** The DB_ONECOLUMN method is implemented together with DB_EXISTS. + */ + + /* $db progress ?N CALLBACK? + ** + ** Invoke the given callback every N virtual machine opcodes while executing + ** queries. + */ + case DB_PROGRESS: { + if( objc==2 ){ + if( pDb->zProgress ){ + Tcl_AppendResult(interp, pDb->zProgress, 0); + } + }else if( objc==4 ){ + char *zProgress; + int len; + int N; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){ + return TCL_ERROR; + }; + if( pDb->zProgress ){ + Tcl_Free(pDb->zProgress); + } + zProgress = Tcl_GetStringFromObj(objv[3], &len); + if( zProgress && len>0 ){ + pDb->zProgress = Tcl_Alloc( len + 1 ); + memcpy(pDb->zProgress, zProgress, len+1); + }else{ + pDb->zProgress = 0; + } +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + if( pDb->zProgress ){ + pDb->interp = interp; + sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb); + }else{ + sqlite3_progress_handler(pDb->db, 0, 0, 0); + } +#endif + }else{ + Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK"); + return TCL_ERROR; + } + break; + } + + /* $db profile ?CALLBACK? + ** + ** Make arrangements to invoke the CALLBACK routine after each SQL statement + ** that has run. The text of the SQL and the amount of elapse time are + ** appended to CALLBACK before the script is run. + */ + case DB_PROFILE: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zProfile ){ + Tcl_AppendResult(interp, pDb->zProfile, 0); + } + }else{ + char *zProfile; + int len; + if( pDb->zProfile ){ + Tcl_Free(pDb->zProfile); + } + zProfile = Tcl_GetStringFromObj(objv[2], &len); + if( zProfile && len>0 ){ + pDb->zProfile = Tcl_Alloc( len + 1 ); + memcpy(pDb->zProfile, zProfile, len+1); + }else{ + pDb->zProfile = 0; + } +#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) + if( pDb->zProfile ){ + pDb->interp = interp; + sqlite3_profile(pDb->db, DbProfileHandler, pDb); + }else{ + sqlite3_profile(pDb->db, 0, 0); + } +#endif + } + break; + } + + /* + ** $db rekey KEY + ** + ** Change the encryption key on the currently open database. + */ + case DB_REKEY: { +#ifdef SQLITE_HAS_CODEC + int nKey; + void *pKey; +#endif + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "KEY"); + return TCL_ERROR; + } +#ifdef SQLITE_HAS_CODEC + pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey); + rc = sqlite3_rekey(pDb->db, pKey, nKey); + if( rc ){ + Tcl_AppendResult(interp, sqlite3_errstr(rc), 0); + rc = TCL_ERROR; + } +#endif + break; + } + + /* $db restore ?DATABASE? FILENAME + ** + ** Open a database file named FILENAME. Transfer the content + ** of FILENAME into the local database DATABASE (default: "main"). + */ + case DB_RESTORE: { + const char *zSrcFile; + const char *zDestDb; + sqlite3 *pSrc; + sqlite3_backup *pBackup; + int nTimeout = 0; + + if( objc==3 ){ + zDestDb = "main"; + zSrcFile = Tcl_GetString(objv[2]); + }else if( objc==4 ){ + zDestDb = Tcl_GetString(objv[2]); + zSrcFile = Tcl_GetString(objv[3]); + }else{ + Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME"); + return TCL_ERROR; + } + rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "cannot open source database: ", + sqlite3_errmsg(pSrc), (char*)0); + sqlite3_close(pSrc); + return TCL_ERROR; + } + pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main"); + if( pBackup==0 ){ + Tcl_AppendResult(interp, "restore failed: ", + sqlite3_errmsg(pDb->db), (char*)0); + sqlite3_close(pSrc); + return TCL_ERROR; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK + || rc==SQLITE_BUSY ){ + if( rc==SQLITE_BUSY ){ + if( nTimeout++ >= 3 ) break; + sqlite3_sleep(100); + } + } + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = TCL_OK; + }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ + Tcl_AppendResult(interp, "restore failed: source database busy", + (char*)0); + rc = TCL_ERROR; + }else{ + Tcl_AppendResult(interp, "restore failed: ", + sqlite3_errmsg(pDb->db), (char*)0); + rc = TCL_ERROR; + } + sqlite3_close(pSrc); + break; + } + + /* + ** $db status (step|sort|autoindex) + ** + ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or + ** SQLITE_STMTSTATUS_SORT for the most recent eval. + */ + case DB_STATUS: { + int v; + const char *zOp; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)"); + return TCL_ERROR; + } + zOp = Tcl_GetString(objv[2]); + if( strcmp(zOp, "step")==0 ){ + v = pDb->nStep; + }else if( strcmp(zOp, "sort")==0 ){ + v = pDb->nSort; + }else if( strcmp(zOp, "autoindex")==0 ){ + v = pDb->nIndex; + }else{ + Tcl_AppendResult(interp, + "bad argument: should be autoindex, step, or sort", + (char*)0); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(v)); + break; + } + + /* + ** $db timeout MILLESECONDS + ** + ** Delay for the number of milliseconds specified when a file is locked. + */ + case DB_TIMEOUT: { + int ms; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR; + sqlite3_busy_timeout(pDb->db, ms); + break; + } + + /* + ** $db total_changes + ** + ** Return the number of rows that were modified, inserted, or deleted + ** since the database handle was created. + */ + case DB_TOTAL_CHANGES: { + Tcl_Obj *pResult; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + pResult = Tcl_GetObjResult(interp); + Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db)); + break; + } + + /* $db trace ?CALLBACK? + ** + ** Make arrangements to invoke the CALLBACK routine for each SQL statement + ** that is executed. The text of the SQL is appended to CALLBACK before + ** it is executed. + */ + case DB_TRACE: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zTrace ){ + Tcl_AppendResult(interp, pDb->zTrace, 0); + } + }else{ + char *zTrace; + int len; + if( pDb->zTrace ){ + Tcl_Free(pDb->zTrace); + } + zTrace = Tcl_GetStringFromObj(objv[2], &len); + if( zTrace && len>0 ){ + pDb->zTrace = Tcl_Alloc( len + 1 ); + memcpy(pDb->zTrace, zTrace, len+1); + }else{ + pDb->zTrace = 0; + } +#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) + if( pDb->zTrace ){ + pDb->interp = interp; + sqlite3_trace(pDb->db, DbTraceHandler, pDb); + }else{ + sqlite3_trace(pDb->db, 0, 0); + } +#endif + } + break; + } + + /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT + ** + ** Start a new transaction (if we are not already in the midst of a + ** transaction) and execute the TCL script SCRIPT. After SCRIPT + ** completes, either commit the transaction or roll it back if SCRIPT + ** throws an exception. Or if no new transation was started, do nothing. + ** pass the exception on up the stack. + ** + ** This command was inspired by Dave Thomas's talk on Ruby at the + ** 2005 O'Reilly Open Source Convention (OSCON). + */ + case DB_TRANSACTION: { + Tcl_Obj *pScript; + const char *zBegin = "SAVEPOINT _tcl_transaction"; + if( objc!=3 && objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT"); + return TCL_ERROR; + } + + if( pDb->nTransaction==0 && objc==4 ){ + static const char *TTYPE_strs[] = { + "deferred", "exclusive", "immediate", 0 + }; + enum TTYPE_enum { + TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE + }; + int ttype; + if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type", + 0, &ttype) ){ + return TCL_ERROR; + } + switch( (enum TTYPE_enum)ttype ){ + case TTYPE_DEFERRED: /* no-op */; break; + case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break; + case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break; + } + } + pScript = objv[objc-1]; + + /* Run the SQLite BEGIN command to open a transaction or savepoint. */ + pDb->disableAuth++; + rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0); + pDb->disableAuth--; + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0); + return TCL_ERROR; + } + pDb->nTransaction++; + + /* If using NRE, schedule a callback to invoke the script pScript, then + ** a second callback to commit (or rollback) the transaction or savepoint + ** opened above. If not using NRE, evaluate the script directly, then + ** call function DbTransPostCmd() to commit (or rollback) the transaction + ** or savepoint. */ + if( DbUseNre() ){ + Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0); + Tcl_NREvalObj(interp, pScript, 0); + }else{ + rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0)); + } + break; + } + + /* + ** $db unlock_notify ?script? + */ + case DB_UNLOCK_NOTIFY: { +#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY + Tcl_AppendResult(interp, "unlock_notify not available in this build", 0); + rc = TCL_ERROR; +#else + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); + rc = TCL_ERROR; + }else{ + void (*xNotify)(void **, int) = 0; + void *pNotifyArg = 0; + + if( pDb->pUnlockNotify ){ + Tcl_DecrRefCount(pDb->pUnlockNotify); + pDb->pUnlockNotify = 0; + } + + if( objc==3 ){ + xNotify = DbUnlockNotify; + pNotifyArg = (void *)pDb; + pDb->pUnlockNotify = objv[2]; + Tcl_IncrRefCount(pDb->pUnlockNotify); + } + + if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){ + Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0); + rc = TCL_ERROR; + } + } +#endif + break; + } + + /* + ** $db wal_hook ?script? + ** $db update_hook ?script? + ** $db rollback_hook ?script? + */ + case DB_WAL_HOOK: + case DB_UPDATE_HOOK: + case DB_ROLLBACK_HOOK: { + + /* set ppHook to point at pUpdateHook or pRollbackHook, depending on + ** whether [$db update_hook] or [$db rollback_hook] was invoked. + */ + Tcl_Obj **ppHook; + if( choice==DB_UPDATE_HOOK ){ + ppHook = &pDb->pUpdateHook; + }else if( choice==DB_WAL_HOOK ){ + ppHook = &pDb->pWalHook; + }else{ + ppHook = &pDb->pRollbackHook; + } + + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); + return TCL_ERROR; + } + if( *ppHook ){ + Tcl_SetObjResult(interp, *ppHook); + if( objc==3 ){ + Tcl_DecrRefCount(*ppHook); + *ppHook = 0; + } + } + if( objc==3 ){ + assert( !(*ppHook) ); + if( Tcl_GetCharLength(objv[2])>0 ){ + *ppHook = objv[2]; + Tcl_IncrRefCount(*ppHook); + } + } + + sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb); + sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb); + sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb); + + break; + } + + /* $db version + ** + ** Return the version string for this database. + */ + case DB_VERSION: { + Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC); + break; + } + + + } /* End of the SWITCH statement */ + return rc; +} + +#if SQLITE_TCL_NRE +/* +** Adaptor that provides an objCmd interface to the NRE-enabled +** interface implementation. +*/ +static int DbObjCmdAdaptor( + void *cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const*objv +){ + return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv); +} +#endif /* SQLITE_TCL_NRE */ + +/* +** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN? +** ?-create BOOLEAN? ?-nomutex BOOLEAN? +** +** This is the main Tcl command. When the "sqlite" Tcl command is +** invoked, this routine runs to process that command. +** +** The first argument, DBNAME, is an arbitrary name for a new +** database connection. This command creates a new command named +** DBNAME that is used to control that connection. The database +** connection is deleted when the DBNAME command is deleted. +** +** The second argument is the name of the database file. +** +*/ +static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){ + SqliteDb *p; + const char *zArg; + char *zErrMsg; + int i; + const char *zFile; + const char *zVfs = 0; + int flags; + Tcl_DString translatedFilename; +#ifdef SQLITE_HAS_CODEC + void *pKey = 0; + int nKey = 0; +#endif + int rc; + + /* In normal use, each TCL interpreter runs in a single thread. So + ** by default, we can turn of mutexing on SQLite database connections. + ** However, for testing purposes it is useful to have mutexes turned + ** on. So, by default, mutexes default off. But if compiled with + ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on. + */ +#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX + flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; +#else + flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX; +#endif + + if( objc==2 ){ + zArg = Tcl_GetStringFromObj(objv[1], 0); + if( strcmp(zArg,"-version")==0 ){ + Tcl_AppendResult(interp,sqlite3_version,0); + return TCL_OK; + } + if( strcmp(zArg,"-has-codec")==0 ){ +#ifdef SQLITE_HAS_CODEC + Tcl_AppendResult(interp,"1",0); +#else + Tcl_AppendResult(interp,"0",0); +#endif + return TCL_OK; + } + } + for(i=3; i+1db, flags, zVfs); + Tcl_DStringFree(&translatedFilename); + if( p->db ){ + if( SQLITE_OK!=sqlite3_errcode(p->db) ){ + zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db)); + sqlite3_close(p->db); + p->db = 0; + } + }else{ + zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc)); + } +#ifdef SQLITE_HAS_CODEC + if( p->db ){ + sqlite3_key(p->db, pKey, nKey); + } +#endif + if( p->db==0 ){ + Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE); + Tcl_Free((char*)p); + sqlite3_free(zErrMsg); + return TCL_ERROR; + } + p->maxStmt = NUM_PREPARED_STMTS; + p->interp = interp; + zArg = Tcl_GetStringFromObj(objv[1], 0); + if( DbUseNre() ){ + Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd, + (char*)p, DbDeleteCmd); + }else{ + Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd); + } + return TCL_OK; +} + +/* +** Provide a dummy Tcl_InitStubs if we are using this as a static +** library. +*/ +#ifndef USE_TCL_STUBS +# undef Tcl_InitStubs +# define Tcl_InitStubs(a,b,c) TCL_VERSION +#endif + +/* +** Make sure we have a PACKAGE_VERSION macro defined. This will be +** defined automatically by the TEA makefile. But other makefiles +** do not define it. +*/ +#ifndef PACKAGE_VERSION +# define PACKAGE_VERSION SQLITE_VERSION +#endif + +/* +** Initialize this module. +** +** This Tcl module contains only a single new Tcl command named "sqlite". +** (Hence there is no namespace. There is no point in using a namespace +** if the extension only supplies one new name!) The "sqlite" command is +** used to open a new SQLite database. See the DbMain() routine above +** for additional information. +** +** The EXTERN macros are required by TCL in order to work on windows. +*/ +EXTERN int Sqlite3_Init(Tcl_Interp *interp){ + int rc = Tcl_InitStubs(interp, "8.4", 0)==0 ? TCL_ERROR : TCL_OK; + if( rc==TCL_OK ){ + Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0); +#ifndef SQLITE_3_SUFFIX_ONLY + /* The "sqlite" alias is undocumented. It is here only to support + ** legacy scripts. All new scripts should use only the "sqlite3" + ** command. */ + Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0); +#endif + rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION); + } + return rc; +} +EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } +EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } +EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } + +/* Because it accesses the file-system and uses persistent state, SQLite +** is not considered appropriate for safe interpreters. Hence, we deliberately +** omit the _SafeInit() interfaces. +*/ + +#ifndef SQLITE_3_SUFFIX_ONLY +int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } +int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } +int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } +int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } +#endif + +#ifdef TCLSH +/***************************************************************************** +** All of the code that follows is used to build standalone TCL interpreters +** that are statically linked with SQLite. Enable these by compiling +** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard +** tclsh but with SQLite built in. An n of 2 generates the SQLite space +** analysis program. +*/ + +#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) +/* + * This code implements the MD5 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + * + * Equivalent code is available from RSA Data Security, Inc. + * This code has been tested against that, and is equivalent, + * except that you don't need to include two pages of legalese + * with every copy. + * + * To compute the message digest of a chunk of bytes, declare an + * MD5Context structure, pass it to MD5Init, call MD5Update as + * needed on buffers full of bytes, and then call MD5Final, which + * will fill a supplied 16-byte array with the digest. + */ + +/* + * If compiled on a machine that doesn't have a 32-bit integer, + * you just set "uint32" to the appropriate datatype for an + * unsigned 32-bit integer. For example: + * + * cc -Duint32='unsigned long' md5.c + * + */ +#ifndef uint32 +# define uint32 unsigned int +#endif + +struct MD5Context { + int isInit; + uint32 buf[4]; + uint32 bits[2]; + unsigned char in[64]; +}; +typedef struct MD5Context MD5Context; + +/* + * Note: this code is harmless on little-endian machines. + */ +static void byteReverse (unsigned char *buf, unsigned longs){ + uint32 t; + do { + t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 | + ((unsigned)buf[1]<<8 | buf[0]); + *(uint32 *)buf = t; + buf += 4; + } while (--longs); +} +/* The four core functions - F1 is optimized somewhat */ + +/* #define F1(x, y, z) (x & y | ~x & z) */ +#define F1(x, y, z) (z ^ (x & (y ^ z))) +#define F2(x, y, z) F1(z, x, y) +#define F3(x, y, z) (x ^ y ^ z) +#define F4(x, y, z) (y ^ (x | ~z)) + +/* This is the central step in the MD5 algorithm. */ +#define MD5STEP(f, w, x, y, z, data, s) \ + ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + +/* + * The core of the MD5 algorithm, this alters an existing MD5 hash to + * reflect the addition of 16 longwords of new data. MD5Update blocks + * the data and converts bytes into longwords for this routine. + */ +static void MD5Transform(uint32 buf[4], const uint32 in[16]){ + register uint32 a, b, c, d; + + a = buf[0]; + b = buf[1]; + c = buf[2]; + d = buf[3]; + + MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17); + MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17); + MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22); + MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7); + MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12); + MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17); + MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22); + MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7); + MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12); + MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17); + MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22); + + MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9); + MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14); + MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9); + MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14); + MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20); + + MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11); + MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16); + MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23); + MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16); + MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23); + MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23); + MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4); + MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11); + MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16); + MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23); + + MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6); + MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10); + MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15); + MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10); + MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15); + MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6); + MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10); + MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15); + MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21); + MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6); + MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10); + MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} + +/* + * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious + * initialization constants. + */ +static void MD5Init(MD5Context *ctx){ + ctx->isInit = 1; + ctx->buf[0] = 0x67452301; + ctx->buf[1] = 0xefcdab89; + ctx->buf[2] = 0x98badcfe; + ctx->buf[3] = 0x10325476; + ctx->bits[0] = 0; + ctx->bits[1] = 0; +} + +/* + * Update context to reflect the concatenation of another buffer full + * of bytes. + */ +static +void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){ + uint32 t; + + /* Update bitcount */ + + t = ctx->bits[0]; + if ((ctx->bits[0] = t + ((uint32)len << 3)) < t) + ctx->bits[1]++; /* Carry from low to high */ + ctx->bits[1] += len >> 29; + + t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ + + /* Handle any leading odd-sized chunks */ + + if ( t ) { + unsigned char *p = (unsigned char *)ctx->in + t; + + t = 64-t; + if (len < t) { + memcpy(p, buf, len); + return; + } + memcpy(p, buf, t); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32 *)ctx->in); + buf += t; + len -= t; + } + + /* Process data in 64-byte chunks */ + + while (len >= 64) { + memcpy(ctx->in, buf, 64); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32 *)ctx->in); + buf += 64; + len -= 64; + } + + /* Handle any remaining bytes of data. */ + + memcpy(ctx->in, buf, len); +} + +/* + * Final wrapup - pad to 64-byte boundary with the bit pattern + * 1 0* (64-bit count of bits processed, MSB-first) + */ +static void MD5Final(unsigned char digest[16], MD5Context *ctx){ + unsigned count; + unsigned char *p; + + /* Compute number of bytes mod 64 */ + count = (ctx->bits[0] >> 3) & 0x3F; + + /* Set the first char of padding to 0x80. This is safe since there is + always at least one byte free */ + p = ctx->in + count; + *p++ = 0x80; + + /* Bytes of padding needed to make 64 bytes */ + count = 64 - 1 - count; + + /* Pad out to 56 mod 64 */ + if (count < 8) { + /* Two lots of padding: Pad the first block to 64 bytes */ + memset(p, 0, count); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32 *)ctx->in); + + /* Now fill the next block with 56 bytes */ + memset(ctx->in, 0, 56); + } else { + /* Pad block to 56 bytes */ + memset(p, 0, count-8); + } + byteReverse(ctx->in, 14); + + /* Append length in bits and transform */ + ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0]; + ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1]; + + MD5Transform(ctx->buf, (uint32 *)ctx->in); + byteReverse((unsigned char *)ctx->buf, 4); + memcpy(digest, ctx->buf, 16); +} + +/* +** Convert a 128-bit MD5 digest into a 32-digit base-16 number. +*/ +static void MD5DigestToBase16(unsigned char *digest, char *zBuf){ + static char const zEncode[] = "0123456789abcdef"; + int i, j; + + for(j=i=0; i<16; i++){ + int a = digest[i]; + zBuf[j++] = zEncode[(a>>4)&0xf]; + zBuf[j++] = zEncode[a & 0xf]; + } + zBuf[j] = 0; +} + + +/* +** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers +** each representing 16 bits of the digest and separated from each +** other by a "-" character. +*/ +static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){ + int i, j; + unsigned int x; + for(i=j=0; i<16; i+=2){ + x = digest[i]*256 + digest[i+1]; + if( i>0 ) zDigest[j++] = '-'; + sprintf(&zDigest[j], "%05u", x); + j += 5; + } + zDigest[j] = 0; +} + +/* +** A TCL command for md5. The argument is the text to be hashed. The +** Result is the hash in base64. +*/ +static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){ + MD5Context ctx; + unsigned char digest[16]; + char zBuf[50]; + void (*converter)(unsigned char*, char*); + + if( argc!=2 ){ + Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0], + " TEXT\"", 0); + return TCL_ERROR; + } + MD5Init(&ctx); + MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1])); + MD5Final(digest, &ctx); + converter = (void(*)(unsigned char*,char*))cd; + converter(digest, zBuf); + Tcl_AppendResult(interp, zBuf, (char*)0); + return TCL_OK; +} + +/* +** A TCL command to take the md5 hash of a file. The argument is the +** name of the file. +*/ +static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){ + FILE *in; + MD5Context ctx; + void (*converter)(unsigned char*, char*); + unsigned char digest[16]; + char zBuf[10240]; + + if( argc!=2 ){ + Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0], + " FILENAME\"", 0); + return TCL_ERROR; + } + in = fopen(argv[1],"rb"); + if( in==0 ){ + Tcl_AppendResult(interp,"unable to open file \"", argv[1], + "\" for reading", 0); + return TCL_ERROR; + } + MD5Init(&ctx); + for(;;){ + int n; + n = (int)fread(zBuf, 1, sizeof(zBuf), in); + if( n<=0 ) break; + MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n); + } + fclose(in); + MD5Final(digest, &ctx); + converter = (void(*)(unsigned char*,char*))cd; + converter(digest, zBuf); + Tcl_AppendResult(interp, zBuf, (char*)0); + return TCL_OK; +} + +/* +** Register the four new TCL commands for generating MD5 checksums +** with the TCL interpreter. +*/ +int Md5_Init(Tcl_Interp *interp){ + Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd, + MD5DigestToBase16, 0); + Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd, + MD5DigestToBase10x8, 0); + Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd, + MD5DigestToBase16, 0); + Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd, + MD5DigestToBase10x8, 0); + return TCL_OK; +} +#endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */ + +#if defined(SQLITE_TEST) +/* +** During testing, the special md5sum() aggregate function is available. +** inside SQLite. The following routines implement that function. +*/ +static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){ + MD5Context *p; + int i; + if( argc<1 ) return; + p = sqlite3_aggregate_context(context, sizeof(*p)); + if( p==0 ) return; + if( !p->isInit ){ + MD5Init(p); + } + for(i=0; i \"\n" + "} else {\n" + "puts -nonewline \"% \"\n" + "}\n" + "flush stdout\n" + "append line [gets stdin]\n" + "if {[info complete $line]} {\n" + "if {[catch {uplevel #0 $line} result]} {\n" + "puts stderr \"Error: $result\"\n" + "} elseif {$result!=\"\"} {\n" + "puts $result\n" + "}\n" + "set line {}\n" + "} else {\n" + "append line \\n\n" + "}\n" + "}\n" + ; + return zMainloop; +} +#endif +#if TCLSH==2 +static const char *tclsh_main_loop(void); +#endif + +#ifdef SQLITE_TEST +static void init_all(Tcl_Interp *); +static int init_all_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + + Tcl_Interp *slave; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SLAVE"); + return TCL_ERROR; + } + + slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1])); + if( !slave ){ + return TCL_ERROR; + } + + init_all(slave); + return TCL_OK; +} + +/* +** Tclcmd: db_use_legacy_prepare DB BOOLEAN +** +** The first argument to this command must be a database command created by +** [sqlite3]. If the second argument is true, then the handle is configured +** to use the sqlite3_prepare_v2() function to prepare statements. If it +** is false, sqlite3_prepare(). +*/ +static int db_use_legacy_prepare_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_CmdInfo cmdInfo; + SqliteDb *pDb; + int bPrepare; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN"); + return TCL_ERROR; + } + + if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){ + Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0); + return TCL_ERROR; + } + pDb = (SqliteDb*)cmdInfo.objClientData; + if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){ + return TCL_ERROR; + } + + pDb->bLegacyPrepare = bPrepare; + + Tcl_ResetResult(interp); + return TCL_OK; +} +#endif + +/* +** Configure the interpreter passed as the first argument to have access +** to the commands and linked variables that make up: +** +** * the [sqlite3] extension itself, +** +** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and +** +** * If SQLITE_TEST is set, the various test interfaces used by the Tcl +** test suite. +*/ +static void init_all(Tcl_Interp *interp){ + Sqlite3_Init(interp); + +#if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) + Md5_Init(interp); +#endif + + /* Install the [register_dbstat_vtab] command to access the implementation + ** of virtual table dbstat (source file test_stat.c). This command is + ** required for testfixture and sqlite3_analyzer, but not by the production + ** Tcl extension. */ +#if defined(SQLITE_TEST) || TCLSH==2 + { + extern int SqlitetestStat_Init(Tcl_Interp*); + SqlitetestStat_Init(interp); + } +#endif + +#ifdef SQLITE_TEST + { + extern int Sqliteconfig_Init(Tcl_Interp*); + extern int Sqlitetest1_Init(Tcl_Interp*); + extern int Sqlitetest2_Init(Tcl_Interp*); + extern int Sqlitetest3_Init(Tcl_Interp*); + extern int Sqlitetest4_Init(Tcl_Interp*); + extern int Sqlitetest5_Init(Tcl_Interp*); + extern int Sqlitetest6_Init(Tcl_Interp*); + extern int Sqlitetest7_Init(Tcl_Interp*); + extern int Sqlitetest8_Init(Tcl_Interp*); + extern int Sqlitetest9_Init(Tcl_Interp*); + extern int Sqlitetestasync_Init(Tcl_Interp*); + extern int Sqlitetest_autoext_Init(Tcl_Interp*); + extern int Sqlitetest_demovfs_Init(Tcl_Interp *); + extern int Sqlitetest_func_Init(Tcl_Interp*); + extern int Sqlitetest_hexio_Init(Tcl_Interp*); + extern int Sqlitetest_init_Init(Tcl_Interp*); + extern int Sqlitetest_malloc_Init(Tcl_Interp*); + extern int Sqlitetest_mutex_Init(Tcl_Interp*); + extern int Sqlitetestschema_Init(Tcl_Interp*); + extern int Sqlitetestsse_Init(Tcl_Interp*); + extern int Sqlitetesttclvar_Init(Tcl_Interp*); + extern int Sqlitetestfs_Init(Tcl_Interp*); + extern int SqlitetestThread_Init(Tcl_Interp*); + extern int SqlitetestOnefile_Init(); + extern int SqlitetestOsinst_Init(Tcl_Interp*); + extern int Sqlitetestbackup_Init(Tcl_Interp*); + extern int Sqlitetestintarray_Init(Tcl_Interp*); + extern int Sqlitetestvfs_Init(Tcl_Interp *); + extern int Sqlitetestrtree_Init(Tcl_Interp*); + extern int Sqlitequota_Init(Tcl_Interp*); + extern int Sqlitemultiplex_Init(Tcl_Interp*); + extern int SqliteSuperlock_Init(Tcl_Interp*); + extern int SqlitetestSyscall_Init(Tcl_Interp*); + +#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) + extern int Sqlitetestfts3_Init(Tcl_Interp *interp); +#endif + +#ifdef SQLITE_ENABLE_ZIPVFS + extern int Zipvfs_Init(Tcl_Interp*); + Zipvfs_Init(interp); +#endif + + Sqliteconfig_Init(interp); + Sqlitetest1_Init(interp); + Sqlitetest2_Init(interp); + Sqlitetest3_Init(interp); + Sqlitetest4_Init(interp); + Sqlitetest5_Init(interp); + Sqlitetest6_Init(interp); + Sqlitetest7_Init(interp); + Sqlitetest8_Init(interp); + Sqlitetest9_Init(interp); + Sqlitetestasync_Init(interp); + Sqlitetest_autoext_Init(interp); + Sqlitetest_demovfs_Init(interp); + Sqlitetest_func_Init(interp); + Sqlitetest_hexio_Init(interp); + Sqlitetest_init_Init(interp); + Sqlitetest_malloc_Init(interp); + Sqlitetest_mutex_Init(interp); + Sqlitetestschema_Init(interp); + Sqlitetesttclvar_Init(interp); + Sqlitetestfs_Init(interp); + SqlitetestThread_Init(interp); + SqlitetestOnefile_Init(interp); + SqlitetestOsinst_Init(interp); + Sqlitetestbackup_Init(interp); + Sqlitetestintarray_Init(interp); + Sqlitetestvfs_Init(interp); + Sqlitetestrtree_Init(interp); + Sqlitequota_Init(interp); + Sqlitemultiplex_Init(interp); + SqliteSuperlock_Init(interp); + SqlitetestSyscall_Init(interp); + +#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) + Sqlitetestfts3_Init(interp); +#endif + + Tcl_CreateObjCommand( + interp, "load_testfixture_extensions", init_all_cmd, 0, 0 + ); + Tcl_CreateObjCommand( + interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0 + ); + +#ifdef SQLITE_SSE + Sqlitetestsse_Init(interp); +#endif + } +#endif +} + +#define TCLSH_MAIN main /* Needed to fake out mktclapp */ +int TCLSH_MAIN(int argc, char **argv){ + Tcl_Interp *interp; + +#if !defined(_WIN32_WCE) + if( getenv("BREAK") ){ + fprintf(stderr, + "attach debugger to process %d and press any key to continue.\n", + GETPID()); + fgetc(stdin); + } +#endif + + /* Call sqlite3_shutdown() once before doing anything else. This is to + ** test that sqlite3_shutdown() can be safely called by a process before + ** sqlite3_initialize() is. */ + sqlite3_shutdown(); + + Tcl_FindExecutable(argv[0]); + interp = Tcl_CreateInterp(); + +#if TCLSH==2 + sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); +#endif + + init_all(interp); + if( argc>=2 ){ + int i; + char zArgc[32]; + sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH)); + Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY); + Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY); + for(i=3-TCLSH; i +#include + +/* +** This is a copy of the first part of the SqliteDb structure in +** tclsqlite.c. We need it here so that the get_sqlite_pointer routine +** can extract the sqlite3* pointer from an existing Tcl SQLite +** connection. +*/ +struct SqliteDb { + sqlite3 *db; +}; + +/* +** Convert text generated by the "%p" conversion format back into +** a pointer. +*/ +static int testHexToInt(int h){ + if( h>='0' && h<='9' ){ + return h - '0'; + }else if( h>='a' && h<='f' ){ + return h - 'a' + 10; + }else{ + assert( h>='A' && h<='F' ); + return h - 'A' + 10; + } +} +void *sqlite3TestTextToPtr(const char *z){ + void *p; + u64 v; + u32 v2; + if( z[0]=='0' && z[1]=='x' ){ + z += 2; + } + v = 0; + while( *z ){ + v = (v<<4) + testHexToInt(*z); + z++; + } + if( sizeof(p)==sizeof(v) ){ + memcpy(&p, &v, sizeof(p)); + }else{ + assert( sizeof(p)==sizeof(v2) ); + v2 = (u32)v; + memcpy(&p, &v2, sizeof(p)); + } + return p; +} + + +/* +** A TCL command that returns the address of the sqlite* pointer +** for an sqlite connection instance. Bad things happen if the +** input is not an sqlite connection. +*/ +static int get_sqlite_pointer( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct SqliteDb *p; + Tcl_CmdInfo cmdInfo; + char zBuf[100]; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SQLITE-CONNECTION"); + return TCL_ERROR; + } + if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){ + Tcl_AppendResult(interp, "command not found: ", + Tcl_GetString(objv[1]), (char*)0); + return TCL_ERROR; + } + p = (struct SqliteDb*)cmdInfo.objClientData; + sprintf(zBuf, "%p", p->db); + if( strncmp(zBuf,"0x",2) ){ + sprintf(zBuf, "0x%p", p->db); + } + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Decode a pointer to an sqlite3 object. +*/ +int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb){ + struct SqliteDb *p; + Tcl_CmdInfo cmdInfo; + if( Tcl_GetCommandInfo(interp, zA, &cmdInfo) ){ + p = (struct SqliteDb*)cmdInfo.objClientData; + *ppDb = p->db; + }else{ + *ppDb = (sqlite3*)sqlite3TestTextToPtr(zA); + } + return TCL_OK; +} + +extern const char *sqlite3ErrName(int); +#define t1ErrorName sqlite3ErrName + +/* +** Convert an sqlite3_stmt* into an sqlite3*. This depends on the +** fact that the sqlite3* is the first field in the Vdbe structure. +*/ +#define StmtToDb(X) sqlite3_db_handle(X) + +/* +** Check a return value to make sure it agrees with the results +** from sqlite3_errcode. +*/ +int sqlite3TestErrCode(Tcl_Interp *interp, sqlite3 *db, int rc){ + if( sqlite3_threadsafe()==0 && rc!=SQLITE_MISUSE && rc!=SQLITE_OK + && sqlite3_errcode(db)!=rc ){ + char zBuf[200]; + int r2 = sqlite3_errcode(db); + sprintf(zBuf, "error code %s (%d) does not match sqlite3_errcode %s (%d)", + t1ErrorName(rc), rc, t1ErrorName(r2), r2); + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, zBuf, 0); + return 1; + } + return 0; +} + +/* +** Decode a pointer to an sqlite3_stmt object. +*/ +static int getStmtPointer( + Tcl_Interp *interp, + const char *zArg, + sqlite3_stmt **ppStmt +){ + *ppStmt = (sqlite3_stmt*)sqlite3TestTextToPtr(zArg); + return TCL_OK; +} + +/* +** Generate a text representation of a pointer that can be understood +** by the getDbPointer and getVmPointer routines above. +** +** The problem is, on some machines (Solaris) if you do a printf with +** "%p" you cannot turn around and do a scanf with the same "%p" and +** get your pointer back. You have to prepend a "0x" before it will +** work. Or at least that is what is reported to me (drh). But this +** behavior varies from machine to machine. The solution used her is +** to test the string right after it is generated to see if it can be +** understood by scanf, and if not, try prepending an "0x" to see if +** that helps. If nothing works, a fatal error is generated. +*/ +int sqlite3TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p){ + sqlite3_snprintf(100, zPtr, "%p", p); + return TCL_OK; +} + +/* +** The callback routine for sqlite3_exec_printf(). +*/ +static int exec_printf_cb(void *pArg, int argc, char **argv, char **name){ + Tcl_DString *str = (Tcl_DString*)pArg; + int i; + + if( Tcl_DStringLength(str)==0 ){ + for(i=0; imutex); + return TCL_OK; +} +static int db_leave( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + sqlite3_mutex_leave(db->mutex); + return TCL_OK; +} + +/* +** Usage: sqlite3_exec DB SQL +** +** Invoke the sqlite3_exec interface using the open database DB +*/ +static int test_exec( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + Tcl_DString str; + int rc; + char *zErr = 0; + char *zSql; + int i, j; + char zBuf[30]; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB SQL", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + Tcl_DStringInit(&str); + zSql = sqlite3_mprintf("%s", argv[2]); + for(i=j=0; zSql[i];){ + if( zSql[i]=='%' ){ + zSql[j++] = (testHexToInt(zSql[i+1])<<4) + testHexToInt(zSql[i+2]); + i += 3; + }else{ + zSql[j++] = zSql[i++]; + } + } + zSql[j] = 0; + rc = sqlite3_exec(db, zSql, exec_printf_cb, &str, &zErr); + sqlite3_free(zSql); + sprintf(zBuf, "%d", rc); + Tcl_AppendElement(interp, zBuf); + Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr); + Tcl_DStringFree(&str); + if( zErr ) sqlite3_free(zErr); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Usage: sqlite3_exec_nr DB SQL +** +** Invoke the sqlite3_exec interface using the open database DB. Discard +** all results +*/ +static int test_exec_nr( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + int rc; + char *zErr = 0; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB SQL", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_exec(db, argv[2], 0, 0, &zErr); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_z_test SEPARATOR ARG0 ARG1 ... +** +** Test the %z format of sqlite_mprintf(). Use multiple mprintf() calls to +** concatenate arg0 through argn using separator as the separator. +** Return the result. +*/ +static int test_mprintf_z( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + char *zResult = 0; + int i; + + for(i=2; isizeof(zStr) ) n = sizeof(zStr); + sqlite3_snprintf(sizeof(zStr), zStr, "abcdefghijklmnopqrstuvwxyz"); + sqlite3_snprintf(n, zStr, zFormat, a1); + Tcl_AppendResult(interp, zStr, 0); + return TCL_OK; +} + +#ifndef SQLITE_OMIT_GET_TABLE + +/* +** Usage: sqlite3_get_table_printf DB FORMAT STRING ?--no-counts? +** +** Invoke the sqlite3_get_table_printf() interface using the open database +** DB. The SQL is the string FORMAT. The format string should contain +** one %s or %q. STRING is the value inserted into %s or %q. +*/ +static int test_get_table_printf( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + Tcl_DString str; + int rc; + char *zErr = 0; + int nRow, nCol; + char **aResult; + int i; + char zBuf[30]; + char *zSql; + int resCount = -1; + if( argc==5 ){ + if( Tcl_GetInt(interp, argv[4], &resCount) ) return TCL_ERROR; + } + if( argc!=4 && argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB FORMAT STRING ?COUNT?", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + Tcl_DStringInit(&str); + zSql = sqlite3_mprintf(argv[2],argv[3]); + if( argc==5 ){ + rc = sqlite3_get_table(db, zSql, &aResult, 0, 0, &zErr); + }else{ + rc = sqlite3_get_table(db, zSql, &aResult, &nRow, &nCol, &zErr); + resCount = (nRow+1)*nCol; + } + sqlite3_free(zSql); + sprintf(zBuf, "%d", rc); + Tcl_AppendElement(interp, zBuf); + if( rc==SQLITE_OK ){ + if( argc==4 ){ + sprintf(zBuf, "%d", nRow); + Tcl_AppendElement(interp, zBuf); + sprintf(zBuf, "%d", nCol); + Tcl_AppendElement(interp, zBuf); + } + for(i=0; inUsed + n + 2 > p->nAlloc ){ + char *zNew; + p->nAlloc = p->nAlloc*2 + n + 200; + zNew = sqlite3_realloc(p->z, p->nAlloc); + if( zNew==0 ){ + sqlite3_free(p->z); + memset(p, 0, sizeof(*p)); + return; + } + p->z = zNew; + } + if( divider && p->nUsed>0 ){ + p->z[p->nUsed++] = divider; + } + memcpy(&p->z[p->nUsed], z, n+1); + p->nUsed += n; +} + +/* +** Invoked for each callback from sqlite3ExecFunc +*/ +static int execFuncCallback(void *pData, int argc, char **argv, char **NotUsed){ + struct dstr *p = (struct dstr*)pData; + int i; + for(i=0; imutex); + pVal = sqlite3ValueNew(db); + sqlite3ValueSetStr(pVal, -1, "x_sqlite_exec", SQLITE_UTF8, SQLITE_STATIC); + zUtf16 = sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); + if( db->mallocFailed ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_create_function16(db, zUtf16, + 1, SQLITE_UTF16, db, sqlite3ExecFunc, 0, 0); + } + sqlite3ValueFree(pVal); + sqlite3_mutex_leave(db->mutex); + } +#endif + + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + +/* +** Routines to implement the x_count() aggregate function. +** +** x_count() counts the number of non-null arguments. But there are +** some twists for testing purposes. +** +** If the argument to x_count() is 40 then a UTF-8 error is reported +** on the step function. If x_count(41) is seen, then a UTF-16 error +** is reported on the step function. If the total count is 42, then +** a UTF-8 error is reported on the finalize function. +*/ +typedef struct t1CountCtx t1CountCtx; +struct t1CountCtx { + int n; +}; +static void t1CountStep( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + t1CountCtx *p; + p = sqlite3_aggregate_context(context, sizeof(*p)); + if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0]) ) && p ){ + p->n++; + } + if( argc>0 ){ + int v = sqlite3_value_int(argv[0]); + if( v==40 ){ + sqlite3_result_error(context, "value of 40 handed to x_count", -1); +#ifndef SQLITE_OMIT_UTF16 + }else if( v==41 ){ + const char zUtf16ErrMsg[] = { 0, 0x61, 0, 0x62, 0, 0x63, 0, 0, 0}; + sqlite3_result_error16(context, &zUtf16ErrMsg[1-SQLITE_BIGENDIAN], -1); +#endif + } + } +} +static void t1CountFinalize(sqlite3_context *context){ + t1CountCtx *p; + p = sqlite3_aggregate_context(context, sizeof(*p)); + if( p ){ + if( p->n==42 ){ + sqlite3_result_error(context, "x_count totals to 42", -1); + }else{ + sqlite3_result_int(context, p ? p->n : 0); + } + } +} + +#ifndef SQLITE_OMIT_DEPRECATED +static void legacyCountStep( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + /* no-op */ +} + +static void legacyCountFinalize(sqlite3_context *context){ + sqlite3_result_int(context, sqlite3_aggregate_count(context)); +} +#endif + +/* +** Usage: sqlite3_create_aggregate DB +** +** Call the sqlite3_create_function API on the given database in order +** to create a function named "x_count". This function is similar +** to the built-in count() function, with a few special quirks +** for testing the sqlite3_result_error() APIs. +** +** The original motivation for this routine was to be able to call the +** sqlite3_create_aggregate function while a query is in progress in order +** to test the SQLITE_MISUSE detection logic. See misuse.test. +** +** This routine was later extended to test the use of sqlite3_result_error() +** within aggregate functions. +** +** Later: It is now also extended to register the aggregate function +** "legacy_count()" with the supplied database handle. This is used +** to test the deprecated sqlite3_aggregate_count() API. +*/ +static int test_create_aggregate( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FILENAME\"", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_create_function(db, "x_count", 0, SQLITE_UTF8, 0, 0, + t1CountStep,t1CountFinalize); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "x_count", 1, SQLITE_UTF8, 0, 0, + t1CountStep,t1CountFinalize); + } +#ifndef SQLITE_OMIT_DEPRECATED + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "legacy_count", 0, SQLITE_ANY, 0, 0, + legacyCountStep, legacyCountFinalize + ); + } +#endif + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + + +/* +** Usage: printf TEXT +** +** Send output to printf. Use this rather than puts to merge the output +** in the correct sequence with debugging printfs inserted into C code. +** Puts uses a separate buffer and debugging statements will be out of +** sequence if it is used. +*/ +static int test_printf( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " TEXT\"", 0); + return TCL_ERROR; + } + printf("%s\n", argv[1]); + return TCL_OK; +} + + + +/* +** Usage: sqlite3_mprintf_int FORMAT INTEGER INTEGER INTEGER +** +** Call mprintf with three integer arguments +*/ +static int sqlite3_mprintf_int( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int a[3], i; + char *z; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT INT\"", 0); + return TCL_ERROR; + } + for(i=2; i<5; i++){ + if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR; + } + z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_int64 FORMAT INTEGER INTEGER INTEGER +** +** Call mprintf with three 64-bit integer arguments +*/ +static int sqlite3_mprintf_int64( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int i; + sqlite_int64 a[3]; + char *z; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT INT\"", 0); + return TCL_ERROR; + } + for(i=2; i<5; i++){ + if( sqlite3Atoi64(argv[i], &a[i-2], 1000000, SQLITE_UTF8) ){ + Tcl_AppendResult(interp, "argument is not a valid 64-bit integer", 0); + return TCL_ERROR; + } + } + z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_long FORMAT INTEGER INTEGER INTEGER +** +** Call mprintf with three long integer arguments. This might be the +** same as sqlite3_mprintf_int or sqlite3_mprintf_int64, depending on +** platform. +*/ +static int sqlite3_mprintf_long( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int i; + long int a[3]; + int b[3]; + char *z; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT INT\"", 0); + return TCL_ERROR; + } + for(i=2; i<5; i++){ + if( Tcl_GetInt(interp, argv[i], &b[i-2]) ) return TCL_ERROR; + a[i-2] = (long int)b[i-2]; + a[i-2] &= (((u64)1)<<(sizeof(int)*8))-1; + } + z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_str FORMAT INTEGER INTEGER STRING +** +** Call mprintf with two integer arguments and one string argument +*/ +static int sqlite3_mprintf_str( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int a[3], i; + char *z; + if( argc<4 || argc>5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT ?STRING?\"", 0); + return TCL_ERROR; + } + for(i=2; i<4; i++){ + if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR; + } + z = sqlite3_mprintf(argv[1], a[0], a[1], argc>4 ? argv[4] : NULL); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_snprintf_str INTEGER FORMAT INTEGER INTEGER STRING +** +** Call mprintf with two integer arguments and one string argument +*/ +static int sqlite3_snprintf_str( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int a[3], i; + int n; + char *z; + if( argc<5 || argc>6 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " INT FORMAT INT INT ?STRING?\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[1], &n) ) return TCL_ERROR; + if( n<0 ){ + Tcl_AppendResult(interp, "N must be non-negative", 0); + return TCL_ERROR; + } + for(i=3; i<5; i++){ + if( Tcl_GetInt(interp, argv[i], &a[i-3]) ) return TCL_ERROR; + } + z = sqlite3_malloc( n+1 ); + sqlite3_snprintf(n, z, argv[2], a[0], a[1], argc>4 ? argv[5] : NULL); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_double FORMAT INTEGER INTEGER DOUBLE +** +** Call mprintf with two integer arguments and one double argument +*/ +static int sqlite3_mprintf_double( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int a[3], i; + double r; + char *z; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT INT INT DOUBLE\"", 0); + return TCL_ERROR; + } + for(i=2; i<4; i++){ + if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR; + } + if( Tcl_GetDouble(interp, argv[4], &r) ) return TCL_ERROR; + z = sqlite3_mprintf(argv[1], a[0], a[1], r); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_scaled FORMAT DOUBLE DOUBLE +** +** Call mprintf with a single double argument which is the product of the +** two arguments given above. This is used to generate overflow and underflow +** doubles to test that they are converted properly. +*/ +static int sqlite3_mprintf_scaled( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + int i; + double r[2]; + char *z; + if( argc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT DOUBLE DOUBLE\"", 0); + return TCL_ERROR; + } + for(i=2; i<4; i++){ + if( Tcl_GetDouble(interp, argv[i], &r[i-2]) ) return TCL_ERROR; + } + z = sqlite3_mprintf(argv[1], r[0]*r[1]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_stronly FORMAT STRING +** +** Call mprintf with a single double argument which is the product of the +** two arguments given above. This is used to generate overflow and underflow +** doubles to test that they are converted properly. +*/ +static int sqlite3_mprintf_stronly( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + char *z; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT STRING\"", 0); + return TCL_ERROR; + } + z = sqlite3_mprintf(argv[1], argv[2]); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_mprintf_hexdouble FORMAT HEX +** +** Call mprintf with a single double argument which is derived from the +** hexadecimal encoding of an IEEE double. +*/ +static int sqlite3_mprintf_hexdouble( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + char *z; + double r; + unsigned int x1, x2; + sqlite_uint64 d; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FORMAT STRING\"", 0); + return TCL_ERROR; + } + if( sscanf(argv[2], "%08x%08x", &x2, &x1)!=2 ){ + Tcl_AppendResult(interp, "2nd argument should be 16-characters of hex", 0); + return TCL_ERROR; + } + d = x2; + d = (d<<32) + x1; + memcpy(&r, &d, sizeof(r)); + z = sqlite3_mprintf(argv[1], r); + Tcl_AppendResult(interp, z, 0); + sqlite3_free(z); + return TCL_OK; +} + +/* +** Usage: sqlite3_enable_shared_cache ?BOOLEAN? +** +*/ +#if !defined(SQLITE_OMIT_SHARED_CACHE) +static int test_enable_shared( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int rc; + int enable; + int ret = 0; + + if( objc!=2 && objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?BOOLEAN?"); + return TCL_ERROR; + } + ret = sqlite3GlobalConfig.sharedCacheEnabled; + + if( objc==2 ){ + if( Tcl_GetBooleanFromObj(interp, objv[1], &enable) ){ + return TCL_ERROR; + } + rc = sqlite3_enable_shared_cache(enable); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3ErrStr(rc), TCL_STATIC); + return TCL_ERROR; + } + } + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(ret)); + return TCL_OK; +} +#endif + + + +/* +** Usage: sqlite3_extended_result_codes DB BOOLEAN +** +*/ +static int test_extended_result_codes( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int enable; + sqlite3 *db; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( Tcl_GetBooleanFromObj(interp, objv[2], &enable) ) return TCL_ERROR; + sqlite3_extended_result_codes(db, enable); + return TCL_OK; +} + +/* +** Usage: sqlite3_libversion_number +** +*/ +static int test_libversion_number( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_libversion_number())); + return TCL_OK; +} + +/* +** Usage: sqlite3_table_column_metadata DB dbname tblname colname +** +*/ +#ifdef SQLITE_ENABLE_COLUMN_METADATA +static int test_table_column_metadata( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + const char *zDb; + const char *zTbl; + const char *zCol; + int rc; + Tcl_Obj *pRet; + + const char *zDatatype; + const char *zCollseq; + int notnull; + int primarykey; + int autoincrement; + + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB dbname tblname colname"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zDb = Tcl_GetString(objv[2]); + zTbl = Tcl_GetString(objv[3]); + zCol = Tcl_GetString(objv[4]); + + if( strlen(zDb)==0 ) zDb = 0; + + rc = sqlite3_table_column_metadata(db, zDb, zTbl, zCol, + &zDatatype, &zCollseq, ¬null, &primarykey, &autoincrement); + + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3_errmsg(db), 0); + return TCL_ERROR; + } + + pRet = Tcl_NewObj(); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zDatatype, -1)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zCollseq, -1)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(notnull)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(primarykey)); + Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(autoincrement)); + Tcl_SetObjResult(interp, pRet); + + return TCL_OK; +} +#endif + +#ifndef SQLITE_OMIT_INCRBLOB + +static int blobHandleFromObj( + Tcl_Interp *interp, + Tcl_Obj *pObj, + sqlite3_blob **ppBlob +){ + char *z; + int n; + + z = Tcl_GetStringFromObj(pObj, &n); + if( n==0 ){ + *ppBlob = 0; + }else{ + int notUsed; + Tcl_Channel channel; + ClientData instanceData; + + channel = Tcl_GetChannel(interp, z, ¬Used); + if( !channel ) return TCL_ERROR; + + Tcl_Flush(channel); + Tcl_Seek(channel, 0, SEEK_SET); + + instanceData = Tcl_GetChannelInstanceData(channel); + *ppBlob = *((sqlite3_blob **)instanceData); + } + + return TCL_OK; +} + +/* +** sqlite3_blob_bytes CHANNEL +*/ +static int test_blob_bytes( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_blob *pBlob; + int nByte; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + nByte = sqlite3_blob_bytes(pBlob); + Tcl_SetObjResult(interp, Tcl_NewIntObj(nByte)); + + return TCL_OK; +} + +/* +** sqlite3_blob_close CHANNEL +*/ +static int test_blob_close( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_blob *pBlob; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + sqlite3_blob_close(pBlob); + + return TCL_OK; +} + +/* +** sqlite3_blob_read CHANNEL OFFSET N +** +** This command is used to test the sqlite3_blob_read() in ways that +** the Tcl channel interface does not. The first argument should +** be the name of a valid channel created by the [incrblob] method +** of a database handle. This function calls sqlite3_blob_read() +** to read N bytes from offset OFFSET from the underlying SQLite +** blob handle. +** +** On success, a byte-array object containing the read data is +** returned. On failure, the interpreter result is set to the +** text representation of the returned error code (i.e. "SQLITE_NOMEM") +** and a Tcl exception is thrown. +*/ +static int test_blob_read( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_blob *pBlob; + int nByte; + int iOffset; + unsigned char *zBuf = 0; + int rc; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL OFFSET N"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iOffset) + || TCL_OK!=Tcl_GetIntFromObj(interp, objv[3], &nByte) + ){ + return TCL_ERROR; + } + + if( nByte>0 ){ + zBuf = (unsigned char *)Tcl_Alloc(nByte); + } + rc = sqlite3_blob_read(pBlob, zBuf, nByte, iOffset); + if( rc==SQLITE_OK ){ + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(zBuf, nByte)); + }else{ + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + } + Tcl_Free((char *)zBuf); + + return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR); +} + +/* +** sqlite3_blob_write CHANNEL OFFSET DATA ?NDATA? +** +** This command is used to test the sqlite3_blob_write() in ways that +** the Tcl channel interface does not. The first argument should +** be the name of a valid channel created by the [incrblob] method +** of a database handle. This function calls sqlite3_blob_write() +** to write the DATA byte-array to the underlying SQLite blob handle. +** at offset OFFSET. +** +** On success, an empty string is returned. On failure, the interpreter +** result is set to the text representation of the returned error code +** (i.e. "SQLITE_NOMEM") and a Tcl exception is thrown. +*/ +static int test_blob_write( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_blob *pBlob; + int iOffset; + int rc; + + unsigned char *zBuf; + int nBuf; + + if( objc!=4 && objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL OFFSET DATA ?NDATA?"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iOffset) ){ + return TCL_ERROR; + } + + zBuf = Tcl_GetByteArrayFromObj(objv[3], &nBuf); + if( objc==5 && Tcl_GetIntFromObj(interp, objv[4], &nBuf) ){ + return TCL_ERROR; + } + rc = sqlite3_blob_write(pBlob, zBuf, nBuf, iOffset); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + } + + return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR); +} + +static int test_blob_reopen( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_WideInt iRowid; + sqlite3_blob *pBlob; + int rc; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL ROWID"); + return TCL_ERROR; + } + + if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR; + if( Tcl_GetWideIntFromObj(interp, objv[2], &iRowid) ) return TCL_ERROR; + + rc = sqlite3_blob_reopen(pBlob, iRowid); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + } + + return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR); +} + +#endif + +/* +** Usage: sqlite3_create_collation_v2 DB-HANDLE NAME CMP-PROC DEL-PROC +** +** This Tcl proc is used for testing the experimental +** sqlite3_create_collation_v2() interface. +*/ +struct TestCollationX { + Tcl_Interp *interp; + Tcl_Obj *pCmp; + Tcl_Obj *pDel; +}; +typedef struct TestCollationX TestCollationX; +static void testCreateCollationDel(void *pCtx){ + TestCollationX *p = (TestCollationX *)pCtx; + + int rc = Tcl_EvalObjEx(p->interp, p->pDel, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL); + if( rc!=TCL_OK ){ + Tcl_BackgroundError(p->interp); + } + + Tcl_DecrRefCount(p->pCmp); + Tcl_DecrRefCount(p->pDel); + sqlite3_free((void *)p); +} +static int testCreateCollationCmp( + void *pCtx, + int nLeft, + const void *zLeft, + int nRight, + const void *zRight +){ + TestCollationX *p = (TestCollationX *)pCtx; + Tcl_Obj *pScript = Tcl_DuplicateObj(p->pCmp); + int iRes = 0; + + Tcl_IncrRefCount(pScript); + Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj((char *)zLeft, nLeft)); + Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj((char *)zRight,nRight)); + + if( TCL_OK!=Tcl_EvalObjEx(p->interp, pScript, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL) + || TCL_OK!=Tcl_GetIntFromObj(p->interp, Tcl_GetObjResult(p->interp), &iRes) + ){ + Tcl_BackgroundError(p->interp); + } + Tcl_DecrRefCount(pScript); + + return iRes; +} +static int test_create_collation_v2( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + TestCollationX *p; + sqlite3 *db; + int rc; + + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE NAME CMP-PROC DEL-PROC"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + p = (TestCollationX *)sqlite3_malloc(sizeof(TestCollationX)); + p->pCmp = objv[3]; + p->pDel = objv[4]; + p->interp = interp; + Tcl_IncrRefCount(p->pCmp); + Tcl_IncrRefCount(p->pDel); + + rc = sqlite3_create_collation_v2(db, Tcl_GetString(objv[2]), 16, + (void *)p, testCreateCollationCmp, testCreateCollationDel + ); + if( rc!=SQLITE_MISUSE ){ + Tcl_AppendResult(interp, "sqlite3_create_collate_v2() failed to detect " + "an invalid encoding", (char*)0); + return TCL_ERROR; + } + rc = sqlite3_create_collation_v2(db, Tcl_GetString(objv[2]), SQLITE_UTF8, + (void *)p, testCreateCollationCmp, testCreateCollationDel + ); + return TCL_OK; +} + +/* +** USAGE: sqlite3_create_function_v2 DB NAME NARG ENC ?SWITCHES? +** +** Available switches are: +** +** -func SCRIPT +** -step SCRIPT +** -final SCRIPT +** -destroy SCRIPT +*/ +typedef struct CreateFunctionV2 CreateFunctionV2; +struct CreateFunctionV2 { + Tcl_Interp *interp; + Tcl_Obj *pFunc; /* Script for function invocation */ + Tcl_Obj *pStep; /* Script for agg. step invocation */ + Tcl_Obj *pFinal; /* Script for agg. finalization invocation */ + Tcl_Obj *pDestroy; /* Destructor script */ +}; +static void cf2Func(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ +} +static void cf2Step(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ +} +static void cf2Final(sqlite3_context *ctx){ +} +static void cf2Destroy(void *pUser){ + CreateFunctionV2 *p = (CreateFunctionV2 *)pUser; + + if( p->interp && p->pDestroy ){ + int rc = Tcl_EvalObjEx(p->interp, p->pDestroy, 0); + if( rc!=TCL_OK ) Tcl_BackgroundError(p->interp); + } + + if( p->pFunc ) Tcl_DecrRefCount(p->pFunc); + if( p->pStep ) Tcl_DecrRefCount(p->pStep); + if( p->pFinal ) Tcl_DecrRefCount(p->pFinal); + if( p->pDestroy ) Tcl_DecrRefCount(p->pDestroy); + sqlite3_free(p); +} +static int test_create_function_v2( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The invoking TCL interpreter */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + const char *zFunc; + int nArg; + int enc; + CreateFunctionV2 *p; + int i; + int rc; + + struct EncTable { + const char *zEnc; + int enc; + } aEnc[] = { + {"utf8", SQLITE_UTF8 }, + {"utf16", SQLITE_UTF16 }, + {"utf16le", SQLITE_UTF16LE }, + {"utf16be", SQLITE_UTF16BE }, + {"any", SQLITE_ANY }, + {"0", 0 } + }; + + if( objc<5 || (objc%2)==0 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB NAME NARG ENC SWITCHES..."); + return TCL_ERROR; + } + + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zFunc = Tcl_GetString(objv[2]); + if( Tcl_GetIntFromObj(interp, objv[3], &nArg) ) return TCL_ERROR; + if( Tcl_GetIndexFromObjStruct(interp, objv[4], aEnc, sizeof(aEnc[0]), + "encoding", 0, &enc) + ){ + return TCL_ERROR; + } + enc = aEnc[enc].enc; + + p = sqlite3_malloc(sizeof(CreateFunctionV2)); + assert( p ); + memset(p, 0, sizeof(CreateFunctionV2)); + p->interp = interp; + + for(i=5; ipFunc = objv[i+1]; break; + case 1: p->pStep = objv[i+1]; break; + case 2: p->pFinal = objv[i+1]; break; + case 3: p->pDestroy = objv[i+1]; break; + } + } + if( p->pFunc ) p->pFunc = Tcl_DuplicateObj(p->pFunc); + if( p->pStep ) p->pStep = Tcl_DuplicateObj(p->pStep); + if( p->pFinal ) p->pFinal = Tcl_DuplicateObj(p->pFinal); + if( p->pDestroy ) p->pDestroy = Tcl_DuplicateObj(p->pDestroy); + + if( p->pFunc ) Tcl_IncrRefCount(p->pFunc); + if( p->pStep ) Tcl_IncrRefCount(p->pStep); + if( p->pFinal ) Tcl_IncrRefCount(p->pFinal); + if( p->pDestroy ) Tcl_IncrRefCount(p->pDestroy); + + rc = sqlite3_create_function_v2(db, zFunc, nArg, enc, (void *)p, + (p->pFunc ? cf2Func : 0), + (p->pStep ? cf2Step : 0), + (p->pFinal ? cf2Final : 0), + cf2Destroy + ); + if( rc!=SQLITE_OK ){ + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: sqlite3_load_extension DB-HANDLE FILE ?PROC? +*/ +static int test_load_extension( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_CmdInfo cmdInfo; + sqlite3 *db; + int rc; + char *zDb; + char *zFile; + char *zProc = 0; + char *zErr = 0; + + if( objc!=4 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE FILE ?PROC?"); + return TCL_ERROR; + } + zDb = Tcl_GetString(objv[1]); + zFile = Tcl_GetString(objv[2]); + if( objc==4 ){ + zProc = Tcl_GetString(objv[3]); + } + + /* Extract the C database handle from the Tcl command name */ + if( !Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){ + Tcl_AppendResult(interp, "command not found: ", zDb, (char*)0); + return TCL_ERROR; + } + db = ((struct SqliteDb*)cmdInfo.objClientData)->db; + assert(db); + + /* Call the underlying C function. If an error occurs, set rc to + ** TCL_ERROR and load any error string into the interpreter. If no + ** error occurs, set rc to TCL_OK. + */ +#ifdef SQLITE_OMIT_LOAD_EXTENSION + rc = SQLITE_ERROR; + zErr = sqlite3_mprintf("this build omits sqlite3_load_extension()"); +#else + rc = sqlite3_load_extension(db, zFile, zProc, &zErr); +#endif + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, zErr ? zErr : "", TCL_VOLATILE); + rc = TCL_ERROR; + }else{ + rc = TCL_OK; + } + sqlite3_free(zErr); + + return rc; +} + +/* +** Usage: sqlite3_enable_load_extension DB-HANDLE ONOFF +*/ +static int test_enable_load( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_CmdInfo cmdInfo; + sqlite3 *db; + char *zDb; + int onoff; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE ONOFF"); + return TCL_ERROR; + } + zDb = Tcl_GetString(objv[1]); + + /* Extract the C database handle from the Tcl command name */ + if( !Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){ + Tcl_AppendResult(interp, "command not found: ", zDb, (char*)0); + return TCL_ERROR; + } + db = ((struct SqliteDb*)cmdInfo.objClientData)->db; + assert(db); + + /* Get the onoff parameter */ + if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){ + return TCL_ERROR; + } + +#ifdef SQLITE_OMIT_LOAD_EXTENSION + Tcl_AppendResult(interp, "this build omits sqlite3_load_extension()"); + return TCL_ERROR; +#else + sqlite3_enable_load_extension(db, onoff); + return TCL_OK; +#endif +} + +/* +** Usage: sqlite_abort +** +** Shutdown the process immediately. This is not a clean shutdown. +** This command is used to test the recoverability of a database in +** the event of a program crash. +*/ +static int sqlite_abort( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ +#if defined(_MSC_VER) + /* We do this, otherwise the test will halt with a popup message + * that we have to click away before the test will continue. + */ + _set_abort_behavior( 0, _CALL_REPORTFAULT ); +#endif + exit(255); + assert( interp==0 ); /* This will always fail */ + return TCL_OK; +} + +/* +** The following routine is a user-defined SQL function whose purpose +** is to test the sqlite_set_result() API. +*/ +static void testFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + while( argc>=2 ){ + const char *zArg0 = (char*)sqlite3_value_text(argv[0]); + if( zArg0 ){ + if( 0==sqlite3StrICmp(zArg0, "int") ){ + sqlite3_result_int(context, sqlite3_value_int(argv[1])); + }else if( sqlite3StrICmp(zArg0,"int64")==0 ){ + sqlite3_result_int64(context, sqlite3_value_int64(argv[1])); + }else if( sqlite3StrICmp(zArg0,"string")==0 ){ + sqlite3_result_text(context, (char*)sqlite3_value_text(argv[1]), -1, + SQLITE_TRANSIENT); + }else if( sqlite3StrICmp(zArg0,"double")==0 ){ + sqlite3_result_double(context, sqlite3_value_double(argv[1])); + }else if( sqlite3StrICmp(zArg0,"null")==0 ){ + sqlite3_result_null(context); + }else if( sqlite3StrICmp(zArg0,"value")==0 ){ + sqlite3_result_value(context, argv[sqlite3_value_int(argv[1])]); + }else{ + goto error_out; + } + }else{ + goto error_out; + } + argc -= 2; + argv += 2; + } + return; + +error_out: + sqlite3_result_error(context,"first argument should be one of: " + "int int64 string double null value", -1); +} + +/* +** Usage: sqlite_register_test_function DB NAME +** +** Register the test SQL function on the database DB under the name NAME. +*/ +static int test_register_func( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3 *db; + int rc; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB FUNCTION-NAME", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_create_function(db, argv[2], -1, SQLITE_UTF8, 0, + testFunc, 0, 0); + if( rc!=0 ){ + Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0); + return TCL_ERROR; + } + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Usage: sqlite3_finalize STMT +** +** Finalize a statement handle. +*/ +static int test_finalize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + sqlite3 *db = 0; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + + if( pStmt ){ + db = StmtToDb(pStmt); + } + rc = sqlite3_finalize(pStmt); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); + if( db && sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Usage: sqlite3_stmt_status STMT CODE RESETFLAG +** +** Get the value of a status counter from a statement. +*/ +static int test_stmt_status( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int iValue; + int i, op, resetFlag; + const char *zOpName; + sqlite3_stmt *pStmt; + + static const struct { + const char *zName; + int op; + } aOp[] = { + { "SQLITE_STMTSTATUS_FULLSCAN_STEP", SQLITE_STMTSTATUS_FULLSCAN_STEP }, + { "SQLITE_STMTSTATUS_SORT", SQLITE_STMTSTATUS_SORT }, + { "SQLITE_STMTSTATUS_AUTOINDEX", SQLITE_STMTSTATUS_AUTOINDEX }, + { "SQLITE_STMTSTATUS_VM_STEP", SQLITE_STMTSTATUS_VM_STEP }, + }; + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT PARAMETER RESETFLAG"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + zOpName = Tcl_GetString(objv[2]); + for(i=0; i=ArraySize(aOp) ){ + if( Tcl_GetIntFromObj(interp, objv[2], &op) ) return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[3], &resetFlag) ) return TCL_ERROR; + iValue = sqlite3_stmt_status(pStmt, op, resetFlag); + Tcl_SetObjResult(interp, Tcl_NewIntObj(iValue)); + return TCL_OK; +} + +/* +** Usage: sqlite3_next_stmt DB STMT +** +** Return the next statment in sequence after STMT. +*/ +static int test_next_stmt( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + sqlite3 *db = 0; + char zBuf[50]; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " DB STMT", 0); + return TCL_ERROR; + } + + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( getStmtPointer(interp, Tcl_GetString(objv[2]), &pStmt) ) return TCL_ERROR; + pStmt = sqlite3_next_stmt(db, pStmt); + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_stmt_readonly STMT +** +** Return true if STMT is a NULL pointer or a pointer to a statement +** that is guaranteed to leave the database unmodified. +*/ +static int test_stmt_readonly( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + rc = sqlite3_stmt_readonly(pStmt); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc)); + return TCL_OK; +} + +/* +** Usage: sqlite3_stmt_busy STMT +** +** Return true if STMT is a non-NULL pointer to a statement +** that has been stepped but not to completion. +*/ +static int test_stmt_busy( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + rc = sqlite3_stmt_busy(pStmt); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc)); + return TCL_OK; +} + +/* +** Usage: uses_stmt_journal STMT +** +** Return true if STMT uses a statement journal. +*/ +static int uses_stmt_journal( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + sqlite3_stmt_readonly(pStmt); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(((Vdbe *)pStmt)->usesStmtJournal)); + return TCL_OK; +} + + +/* +** Usage: sqlite3_reset STMT +** +** Reset a statement handle. +*/ +static int test_reset( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + + rc = sqlite3_reset(pStmt); + if( pStmt && sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ){ + return TCL_ERROR; + } + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); +/* + if( rc ){ + return TCL_ERROR; + } +*/ + return TCL_OK; +} + +/* +** Usage: sqlite3_expired STMT +** +** Return TRUE if a recompilation of the statement is recommended. +*/ +static int test_expired( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_stmt *pStmt; + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(sqlite3_expired(pStmt))); +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_transfer_bindings FROMSTMT TOSTMT +** +** Transfer all bindings from FROMSTMT over to TOSTMT +*/ +static int test_transfer_bind( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_stmt *pStmt1, *pStmt2; + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " FROM-STMT TO-STMT", 0); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt1)) return TCL_ERROR; + if( getStmtPointer(interp, Tcl_GetString(objv[2]), &pStmt2)) return TCL_ERROR; + Tcl_SetObjResult(interp, + Tcl_NewIntObj(sqlite3_transfer_bindings(pStmt1,pStmt2))); +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_changes DB +** +** Return the number of changes made to the database by the last SQL +** execution. +*/ +static int test_changes( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_changes(db))); + return TCL_OK; +} + +/* +** This is the "static_bind_value" that variables are bound to when +** the FLAG option of sqlite3_bind is "static" +*/ +static char *sqlite_static_bind_value = 0; +static int sqlite_static_bind_nbyte = 0; + +/* +** Usage: sqlite3_bind VM IDX VALUE FLAGS +** +** Sets the value of the IDX-th occurrence of "?" in the original SQL +** string. VALUE is the new value. If FLAGS=="null" then VALUE is +** ignored and the value is set to NULL. If FLAGS=="static" then +** the value is set to the value of a static variable named +** "sqlite_static_bind_value". If FLAGS=="normal" then a copy +** of the VALUE is made. If FLAGS=="blob10" then a VALUE is ignored +** an a 10-byte blob "abc\000xyz\000pq" is inserted. +*/ +static int test_bind( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + sqlite3_stmt *pStmt; + int rc; + int idx; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " VM IDX VALUE (null|static|normal)\"", 0); + return TCL_ERROR; + } + if( getStmtPointer(interp, argv[1], &pStmt) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[2], &idx) ) return TCL_ERROR; + if( strcmp(argv[4],"null")==0 ){ + rc = sqlite3_bind_null(pStmt, idx); + }else if( strcmp(argv[4],"static")==0 ){ + rc = sqlite3_bind_text(pStmt, idx, sqlite_static_bind_value, -1, 0); + }else if( strcmp(argv[4],"static-nbytes")==0 ){ + rc = sqlite3_bind_text(pStmt, idx, sqlite_static_bind_value, + sqlite_static_bind_nbyte, 0); + }else if( strcmp(argv[4],"normal")==0 ){ + rc = sqlite3_bind_text(pStmt, idx, argv[3], -1, SQLITE_TRANSIENT); + }else if( strcmp(argv[4],"blob10")==0 ){ + rc = sqlite3_bind_text(pStmt, idx, "abc\000xyz\000pq", 10, SQLITE_STATIC); + }else{ + Tcl_AppendResult(interp, "4th argument should be " + "\"null\" or \"static\" or \"normal\"", 0); + return TCL_ERROR; + } + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc ){ + char zBuf[50]; + sprintf(zBuf, "(%d) ", rc); + Tcl_AppendResult(interp, zBuf, sqlite3ErrStr(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +#ifndef SQLITE_OMIT_UTF16 +/* +** Usage: add_test_collate +** +** This function is used to test that SQLite selects the correct collation +** sequence callback when multiple versions (for different text encodings) +** are available. +** +** Calling this routine registers the collation sequence "test_collate" +** with database handle . The second argument must be a list of three +** boolean values. If the first is true, then a version of test_collate is +** registered for UTF-8, if the second is true, a version is registered for +** UTF-16le, if the third is true, a UTF-16be version is available. +** Previous versions of test_collate are deleted. +** +** The collation sequence test_collate is implemented by calling the +** following TCL script: +** +** "test_collate " +** +** The and are the two values being compared, encoded in UTF-8. +** The parameter is the encoding of the collation function that +** SQLite selected to call. The TCL test script implements the +** "test_collate" proc. +** +** Note that this will only work with one intepreter at a time, as the +** interp pointer to use when evaluating the TCL script is stored in +** pTestCollateInterp. +*/ +static Tcl_Interp* pTestCollateInterp; +static int test_collate_func( + void *pCtx, + int nA, const void *zA, + int nB, const void *zB +){ + Tcl_Interp *i = pTestCollateInterp; + int encin = SQLITE_PTR_TO_INT(pCtx); + int res; + int n; + + sqlite3_value *pVal; + Tcl_Obj *pX; + + pX = Tcl_NewStringObj("test_collate", -1); + Tcl_IncrRefCount(pX); + + switch( encin ){ + case SQLITE_UTF8: + Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-8",-1)); + break; + case SQLITE_UTF16LE: + Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16LE",-1)); + break; + case SQLITE_UTF16BE: + Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16BE",-1)); + break; + default: + assert(0); + } + + sqlite3BeginBenignMalloc(); + pVal = sqlite3ValueNew(0); + if( pVal ){ + sqlite3ValueSetStr(pVal, nA, zA, encin, SQLITE_STATIC); + n = sqlite3_value_bytes(pVal); + Tcl_ListObjAppendElement(i,pX, + Tcl_NewStringObj((char*)sqlite3_value_text(pVal),n)); + sqlite3ValueSetStr(pVal, nB, zB, encin, SQLITE_STATIC); + n = sqlite3_value_bytes(pVal); + Tcl_ListObjAppendElement(i,pX, + Tcl_NewStringObj((char*)sqlite3_value_text(pVal),n)); + sqlite3ValueFree(pVal); + } + sqlite3EndBenignMalloc(); + + Tcl_EvalObjEx(i, pX, 0); + Tcl_DecrRefCount(pX); + Tcl_GetIntFromObj(i, Tcl_GetObjResult(i), &res); + return res; +} +static int test_collate( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int val; + sqlite3_value *pVal; + int rc; + + if( objc!=5 ) goto bad_args; + pTestCollateInterp = interp; + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR; + rc = sqlite3_create_collation(db, "test_collate", SQLITE_UTF8, + (void *)SQLITE_UTF8, val?test_collate_func:0); + if( rc==SQLITE_OK ){ + const void *zUtf16; + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &val) ) return TCL_ERROR; + rc = sqlite3_create_collation(db, "test_collate", SQLITE_UTF16LE, + (void *)SQLITE_UTF16LE, val?test_collate_func:0); + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR; + +#if 0 + if( sqlite3_iMallocFail>0 ){ + sqlite3_iMallocFail++; + } +#endif + sqlite3_mutex_enter(db->mutex); + pVal = sqlite3ValueNew(db); + sqlite3ValueSetStr(pVal, -1, "test_collate", SQLITE_UTF8, SQLITE_STATIC); + zUtf16 = sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); + if( db->mallocFailed ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_create_collation16(db, zUtf16, SQLITE_UTF16BE, + (void *)SQLITE_UTF16BE, val?test_collate_func:0); + } + sqlite3ValueFree(pVal); + sqlite3_mutex_leave(db->mutex); + } + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; + +bad_args: + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; +} + +/* +** When the collation needed callback is invoked, record the name of +** the requested collating function here. The recorded name is linked +** to a TCL variable and used to make sure that the requested collation +** name is correct. +*/ +static char zNeededCollation[200]; +static char *pzNeededCollation = zNeededCollation; + + +/* +** Called when a collating sequence is needed. Registered using +** sqlite3_collation_needed16(). +*/ +static void test_collate_needed_cb( + void *pCtx, + sqlite3 *db, + int eTextRep, + const void *pName +){ + int enc = ENC(db); + int i; + char *z; + for(z = (char*)pName, i=0; *z || z[1]; z++){ + if( *z ) zNeededCollation[i++] = *z; + } + zNeededCollation[i] = 0; + sqlite3_create_collation( + db, "test_collate", ENC(db), SQLITE_INT_TO_PTR(enc), test_collate_func); +} + +/* +** Usage: add_test_collate_needed DB +*/ +static int test_collate_needed( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int rc; + + if( objc!=2 ) goto bad_args; + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_collation_needed16(db, 0, test_collate_needed_cb); + zNeededCollation[0] = 0; + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + return TCL_OK; + +bad_args: + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; +} + +/* +** tclcmd: add_alignment_test_collations DB +** +** Add two new collating sequences to the database DB +** +** utf16_aligned +** utf16_unaligned +** +** Both collating sequences use the same sort order as BINARY. +** The only difference is that the utf16_aligned collating +** sequence is declared with the SQLITE_UTF16_ALIGNED flag. +** Both collating functions increment the unaligned utf16 counter +** whenever they see a string that begins on an odd byte boundary. +*/ +static int unaligned_string_counter = 0; +static int alignmentCollFunc( + void *NotUsed, + int nKey1, const void *pKey1, + int nKey2, const void *pKey2 +){ + int rc, n; + n = nKey10 && 1==(1&(SQLITE_PTR_TO_INT(pKey1))) ) unaligned_string_counter++; + if( nKey2>0 && 1==(1&(SQLITE_PTR_TO_INT(pKey2))) ) unaligned_string_counter++; + rc = memcmp(pKey1, pKey2, n); + if( rc==0 ){ + rc = nKey1 - nKey2; + } + return rc; +} +static int add_alignment_test_collations( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + if( objc>=2 ){ + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + sqlite3_create_collation(db, "utf16_unaligned", SQLITE_UTF16, + 0, alignmentCollFunc); + sqlite3_create_collation(db, "utf16_aligned", SQLITE_UTF16_ALIGNED, + 0, alignmentCollFunc); + } + return SQLITE_OK; +} +#endif /* !defined(SQLITE_OMIT_UTF16) */ + +/* +** Usage: add_test_function +** +** This function is used to test that SQLite selects the correct user +** function callback when multiple versions (for different text encodings) +** are available. +** +** Calling this routine registers up to three versions of the user function +** "test_function" with database handle . If the second argument is +** true, then a version of test_function is registered for UTF-8, if the +** third is true, a version is registered for UTF-16le, if the fourth is +** true, a UTF-16be version is available. Previous versions of +** test_function are deleted. +** +** The user function is implemented by calling the following TCL script: +** +** "test_function " +** +** Where is one of UTF-8, UTF-16LE or UTF16BE, and is the +** single argument passed to the SQL function. The value returned by +** the TCL script is used as the return value of the SQL function. It +** is passed to SQLite using UTF-16BE for a UTF-8 test_function(), UTF-8 +** for a UTF-16LE test_function(), and UTF-16LE for an implementation that +** prefers UTF-16BE. +*/ +#ifndef SQLITE_OMIT_UTF16 +static void test_function_utf8( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + Tcl_Interp *interp; + Tcl_Obj *pX; + sqlite3_value *pVal; + interp = (Tcl_Interp *)sqlite3_user_data(pCtx); + pX = Tcl_NewStringObj("test_function", -1); + Tcl_IncrRefCount(pX); + Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-8", -1)); + Tcl_ListObjAppendElement(interp, pX, + Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1)); + Tcl_EvalObjEx(interp, pX, 0); + Tcl_DecrRefCount(pX); + sqlite3_result_text(pCtx, Tcl_GetStringResult(interp), -1, SQLITE_TRANSIENT); + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), + SQLITE_UTF8, SQLITE_STATIC); + sqlite3_result_text16be(pCtx, sqlite3_value_text16be(pVal), + -1, SQLITE_TRANSIENT); + sqlite3ValueFree(pVal); +} +static void test_function_utf16le( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + Tcl_Interp *interp; + Tcl_Obj *pX; + sqlite3_value *pVal; + interp = (Tcl_Interp *)sqlite3_user_data(pCtx); + pX = Tcl_NewStringObj("test_function", -1); + Tcl_IncrRefCount(pX); + Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16LE", -1)); + Tcl_ListObjAppendElement(interp, pX, + Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1)); + Tcl_EvalObjEx(interp, pX, 0); + Tcl_DecrRefCount(pX); + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), + SQLITE_UTF8, SQLITE_STATIC); + sqlite3_result_text(pCtx,(char*)sqlite3_value_text(pVal),-1,SQLITE_TRANSIENT); + sqlite3ValueFree(pVal); +} +static void test_function_utf16be( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + Tcl_Interp *interp; + Tcl_Obj *pX; + sqlite3_value *pVal; + interp = (Tcl_Interp *)sqlite3_user_data(pCtx); + pX = Tcl_NewStringObj("test_function", -1); + Tcl_IncrRefCount(pX); + Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16BE", -1)); + Tcl_ListObjAppendElement(interp, pX, + Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1)); + Tcl_EvalObjEx(interp, pX, 0); + Tcl_DecrRefCount(pX); + pVal = sqlite3ValueNew(0); + sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), + SQLITE_UTF8, SQLITE_STATIC); + sqlite3_result_text16(pCtx, sqlite3_value_text16le(pVal), + -1, SQLITE_TRANSIENT); + sqlite3_result_text16be(pCtx, sqlite3_value_text16le(pVal), + -1, SQLITE_TRANSIENT); + sqlite3_result_text16le(pCtx, sqlite3_value_text16le(pVal), + -1, SQLITE_TRANSIENT); + sqlite3ValueFree(pVal); +} +#endif /* SQLITE_OMIT_UTF16 */ +static int test_function( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3 *db; + int val; + + if( objc!=5 ) goto bad_args; + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR; + if( val ){ + sqlite3_create_function(db, "test_function", 1, SQLITE_UTF8, + interp, test_function_utf8, 0, 0); + } + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &val) ) return TCL_ERROR; + if( val ){ + sqlite3_create_function(db, "test_function", 1, SQLITE_UTF16LE, + interp, test_function_utf16le, 0, 0); + } + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR; + if( val ){ + sqlite3_create_function(db, "test_function", 1, SQLITE_UTF16BE, + interp, test_function_utf16be, 0, 0); + } + + return TCL_OK; +bad_args: + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_ERROR; +} + +/* +** Usage: sqlite3_test_errstr +** +** Test that the english language string equivalents for sqlite error codes +** are sane. The parameter is an integer representing an sqlite error code. +** The result is a list of two elements, the string representation of the +** error code and the english language explanation. +*/ +static int test_errstr( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + char *zCode; + int i; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + } + + zCode = Tcl_GetString(objv[1]); + for(i=0; i<200; i++){ + if( 0==strcmp(t1ErrorName(i), zCode) ) break; + } + Tcl_SetResult(interp, (char *)sqlite3ErrStr(i), 0); + return TCL_OK; +} + +/* +** Usage: breakpoint +** +** This routine exists for one purpose - to provide a place to put a +** breakpoint with GDB that can be triggered using TCL code. The use +** for this is when a particular test fails on (say) the 1485th iteration. +** In the TCL test script, we can add code like this: +** +** if {$i==1485} breakpoint +** +** Then run testfixture in the debugger and wait for the breakpoint to +** fire. Then additional breakpoints can be set to trace down the bug. +*/ +static int test_breakpoint( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + char **argv /* Text of each argument */ +){ + return TCL_OK; /* Do nothing */ +} + +/* +** Usage: sqlite3_bind_zeroblob STMT IDX N +** +** Test the sqlite3_bind_zeroblob interface. STMT is a prepared statement. +** IDX is the index of a wildcard in the prepared statement. This command +** binds a N-byte zero-filled BLOB to the wildcard. +*/ +static int test_bind_zeroblob( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int n; + int rc; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT IDX N"); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &n) ) return TCL_ERROR; + + rc = sqlite3_bind_zeroblob(pStmt, idx, n); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_int STMT N VALUE +** +** Test the sqlite3_bind_int interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a 32-bit integer VALUE to that wildcard. +*/ +static int test_bind_int( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int value; + int rc; + + if( objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &value) ) return TCL_ERROR; + + rc = sqlite3_bind_int(pStmt, idx, value); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + + +/* +** Usage: sqlite3_bind_int64 STMT N VALUE +** +** Test the sqlite3_bind_int64 interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a 64-bit integer VALUE to that wildcard. +*/ +static int test_bind_int64( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + Tcl_WideInt value; + int rc; + + if( objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + if( Tcl_GetWideIntFromObj(interp, objv[3], &value) ) return TCL_ERROR; + + rc = sqlite3_bind_int64(pStmt, idx, value); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + + +/* +** Usage: sqlite3_bind_double STMT N VALUE +** +** Test the sqlite3_bind_double interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a 64-bit integer VALUE to that wildcard. +*/ +static int test_bind_double( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + double value; + int rc; + const char *zVal; + int i; + static const struct { + const char *zName; /* Name of the special floating point value */ + unsigned int iUpper; /* Upper 32 bits */ + unsigned int iLower; /* Lower 32 bits */ + } aSpecialFp[] = { + { "NaN", 0x7fffffff, 0xffffffff }, + { "SNaN", 0x7ff7ffff, 0xffffffff }, + { "-NaN", 0xffffffff, 0xffffffff }, + { "-SNaN", 0xfff7ffff, 0xffffffff }, + { "+Inf", 0x7ff00000, 0x00000000 }, + { "-Inf", 0xfff00000, 0x00000000 }, + { "Epsilon", 0x00000000, 0x00000001 }, + { "-Epsilon", 0x80000000, 0x00000001 }, + { "NaN0", 0x7ff80000, 0x00000000 }, + { "-NaN0", 0xfff80000, 0x00000000 }, + }; + + if( objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + + /* Intercept the string "NaN" and generate a NaN value for it. + ** All other strings are passed through to Tcl_GetDoubleFromObj(). + ** Tcl_GetDoubleFromObj() should understand "NaN" but some versions + ** contain a bug. + */ + zVal = Tcl_GetString(objv[3]); + for(i=0; i=sizeof(aSpecialFp)/sizeof(aSpecialFp[0]) && + Tcl_GetDoubleFromObj(interp, objv[3], &value) ){ + return TCL_ERROR; + } + rc = sqlite3_bind_double(pStmt, idx, value); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_null STMT N +** +** Test the sqlite3_bind_null interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a NULL to the wildcard. +*/ +static int test_bind_null( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int rc; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + + rc = sqlite3_bind_null(pStmt, idx); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_text STMT N STRING BYTES +** +** Test the sqlite3_bind_text interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a UTF-8 string STRING to the wildcard. The string is BYTES bytes +** long. +*/ +static int test_bind_text( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int bytes; + char *value; + int rc; + + if( objc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE BYTES", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + value = (char*)Tcl_GetByteArrayFromObj(objv[3], &bytes); + if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR; + + rc = sqlite3_bind_text(pStmt, idx, value, bytes, SQLITE_TRANSIENT); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_text16 ?-static? STMT N STRING BYTES +** +** Test the sqlite3_bind_text16 interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a UTF-16 string STRING to the wildcard. The string is BYTES bytes +** long. +*/ +static int test_bind_text16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3_stmt *pStmt; + int idx; + int bytes; + char *value; + int rc; + + void (*xDel)(void*) = (objc==6?SQLITE_STATIC:SQLITE_TRANSIENT); + Tcl_Obj *oStmt = objv[objc-4]; + Tcl_Obj *oN = objv[objc-3]; + Tcl_Obj *oString = objv[objc-2]; + Tcl_Obj *oBytes = objv[objc-1]; + + if( objc!=5 && objc!=6){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE BYTES", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(oStmt), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, oN, &idx) ) return TCL_ERROR; + value = (char*)Tcl_GetByteArrayFromObj(oString, 0); + if( Tcl_GetIntFromObj(interp, oBytes, &bytes) ) return TCL_ERROR; + + rc = sqlite3_bind_text16(pStmt, idx, (void *)value, bytes, xDel); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_blob ?-static? STMT N DATA BYTES +** +** Test the sqlite3_bind_blob interface. STMT is a prepared statement. +** N is the index of a wildcard in the prepared statement. This command +** binds a BLOB to the wildcard. The BLOB is BYTES bytes in size. +*/ +static int test_bind_blob( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int idx; + int bytes; + char *value; + int rc; + sqlite3_destructor_type xDestructor = SQLITE_TRANSIENT; + + if( objc!=5 && objc!=6 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " STMT N DATA BYTES", 0); + return TCL_ERROR; + } + + if( objc==6 ){ + xDestructor = SQLITE_STATIC; + objv++; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR; + value = Tcl_GetString(objv[3]); + if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR; + + rc = sqlite3_bind_blob(pStmt, idx, value, bytes, xDestructor); + if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_parameter_count STMT +** +** Return the number of wildcards in the given statement. +*/ +static int test_bind_parameter_count( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_bind_parameter_count(pStmt))); + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_parameter_name STMT N +** +** Return the name of the Nth wildcard. The first wildcard is 1. +** An empty string is returned if N is out of range or if the wildcard +** is nameless. +*/ +static int test_bind_parameter_name( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int i; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT N"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &i) ) return TCL_ERROR; + Tcl_SetObjResult(interp, + Tcl_NewStringObj(sqlite3_bind_parameter_name(pStmt,i),-1) + ); + return TCL_OK; +} + +/* +** Usage: sqlite3_bind_parameter_index STMT NAME +** +** Return the index of the wildcard called NAME. Return 0 if there is +** no such wildcard. +*/ +static int test_bind_parameter_index( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT NAME"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetObjResult(interp, + Tcl_NewIntObj( + sqlite3_bind_parameter_index(pStmt,Tcl_GetString(objv[2])) + ) + ); + return TCL_OK; +} + +/* +** Usage: sqlite3_clear_bindings STMT +** +*/ +static int test_clear_bindings( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_clear_bindings(pStmt))); + return TCL_OK; +} + +/* +** Usage: sqlite3_sleep MILLISECONDS +*/ +static int test_sleep( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int ms; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "MILLISECONDS"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &ms) ){ + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_sleep(ms))); + return TCL_OK; +} + +/* +** Usage: sqlite3_extended_errcode DB +** +** Return the string representation of the most recent sqlite3_* API +** error code. e.g. "SQLITE_ERROR". +*/ +static int test_ex_errcode( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_extended_errcode(db); + Tcl_AppendResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + + +/* +** Usage: sqlite3_errcode DB +** +** Return the string representation of the most recent sqlite3_* API +** error code. e.g. "SQLITE_ERROR". +*/ +static int test_errcode( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_errcode(db); + Tcl_AppendResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + +/* +** Usage: sqlite3_errmsg DB +** +** Returns the UTF-8 representation of the error message string for the +** most recent sqlite3_* API call. +*/ +static int test_errmsg( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zErr; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + zErr = sqlite3_errmsg(db); + Tcl_SetObjResult(interp, Tcl_NewStringObj(zErr, -1)); + return TCL_OK; +} + +/* +** Usage: test_errmsg16 DB +** +** Returns the UTF-16 representation of the error message string for the +** most recent sqlite3_* API call. This is a byte array object at the TCL +** level, and it includes the 0x00 0x00 terminator bytes at the end of the +** UTF-16 string. +*/ +static int test_errmsg16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3 *db; + const void *zErr; + const char *z; + int bytes = 0; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + zErr = sqlite3_errmsg16(db); + if( zErr ){ + z = zErr; + for(bytes=0; z[bytes] || z[bytes+1]; bytes+=2){} + } + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(zErr, bytes)); +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_prepare DB sql bytes ?tailvar? +** +** Compile up to bytes of the supplied SQL string using +** database handle . The parameter is the name of a global +** variable that is set to the unused portion of (if any). A +** STMT handle is returned. +*/ +static int test_prepare( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zSql; + int bytes; + const char *zTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetString(objv[2]); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + rc = sqlite3_prepare(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0); + Tcl_ResetResult(interp); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( zTail && objc>=5 ){ + if( bytes>=0 ){ + bytes = bytes - (int)(zTail-zSql); + } + if( (int)strlen(zTail) bytes of the supplied SQL string using +** database handle . The parameter is the name of a global +** variable that is set to the unused portion of (if any). A +** STMT handle is returned. +*/ +static int test_prepare_v2( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zSql; + int bytes; + const char *zTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetString(objv[2]); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + rc = sqlite3_prepare_v2(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0); + assert(rc==SQLITE_OK || pStmt==0); + Tcl_ResetResult(interp); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( zTail && objc>=5 ){ + if( bytes>=0 ){ + bytes = bytes - (int)(zTail-zSql); + } + Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0); + } + if( rc!=SQLITE_OK ){ + assert( pStmt==0 ); + sprintf(zBuf, "(%d) ", rc); + Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0); + return TCL_ERROR; + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_prepare_tkt3134 DB +** +** Generate a prepared statement for a zero-byte string as a test +** for ticket #3134. The string should be preceeded by a zero byte. +*/ +static int test_prepare_tkt3134( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + static const char zSql[] = "\000SELECT 1"; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_prepare_v2(db, &zSql[1], 0, &pStmt, 0); + assert(rc==SQLITE_OK || pStmt==0); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( rc!=SQLITE_OK ){ + assert( pStmt==0 ); + sprintf(zBuf, "(%d) ", rc); + Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0); + return TCL_ERROR; + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_prepare16 DB sql bytes tailvar +** +** Compile up to bytes of the supplied SQL string using +** database handle . The parameter is the name of a global +** variable that is set to the unused portion of (if any). A +** STMT handle is returned. +*/ +static int test_prepare16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3 *db; + const void *zSql; + const void *zTail = 0; + Tcl_Obj *pTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + int bytes; /* The integer specified as arg 3 */ + int objlen; /* The byte-array length of arg 2 */ + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetByteArrayFromObj(objv[2], &objlen); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + rc = sqlite3_prepare16(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( rc ){ + return TCL_ERROR; + } + + if( objc>=5 ){ + if( zTail ){ + objlen = objlen - (int)((u8 *)zTail-(u8 *)zSql); + }else{ + objlen = 0; + } + pTail = Tcl_NewByteArrayObj((u8 *)zTail, objlen); + Tcl_IncrRefCount(pTail); + Tcl_ObjSetVar2(interp, objv[4], 0, pTail, 0); + Tcl_DecrRefCount(pTail); + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + } + Tcl_AppendResult(interp, zBuf, 0); +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_prepare16_v2 DB sql bytes ?tailvar? +** +** Compile up to bytes of the supplied SQL string using +** database handle . The parameter is the name of a global +** variable that is set to the unused portion of (if any). A +** STMT handle is returned. +*/ +static int test_prepare16_v2( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3 *db; + const void *zSql; + const void *zTail = 0; + Tcl_Obj *pTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + int bytes; /* The integer specified as arg 3 */ + int objlen; /* The byte-array length of arg 2 */ + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetByteArrayFromObj(objv[2], &objlen); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + rc = sqlite3_prepare16_v2(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0); + if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR; + if( rc ){ + return TCL_ERROR; + } + + if( objc>=5 ){ + if( zTail ){ + objlen = objlen - (int)((u8 *)zTail-(u8 *)zSql); + }else{ + objlen = 0; + } + pTail = Tcl_NewByteArrayObj((u8 *)zTail, objlen); + Tcl_IncrRefCount(pTail); + Tcl_ObjSetVar2(interp, objv[4], 0, pTail, 0); + Tcl_DecrRefCount(pTail); + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + } + Tcl_AppendResult(interp, zBuf, 0); +#endif /* SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_open filename ?options-list? +*/ +static int test_open( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; + sqlite3 *db; + char zBuf[100]; + + if( objc!=3 && objc!=2 && objc!=1 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " filename options-list", 0); + return TCL_ERROR; + } + + zFilename = objc>1 ? Tcl_GetString(objv[1]) : 0; + sqlite3_open(zFilename, &db); + + if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: sqlite3_open_v2 FILENAME FLAGS VFS +*/ +static int test_open_v2( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; + const char *zVfs; + int flags = 0; + sqlite3 *db; + int rc; + char zBuf[100]; + + int nFlag; + Tcl_Obj **apFlag; + int i; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME FLAGS VFS"); + return TCL_ERROR; + } + zFilename = Tcl_GetString(objv[1]); + zVfs = Tcl_GetString(objv[3]); + if( zVfs[0]==0x00 ) zVfs = 0; + + rc = Tcl_ListObjGetElements(interp, objv[2], &nFlag, &apFlag); + if( rc!=TCL_OK ) return rc; + for(i=0; i +** +** Return 1 if the supplied argument is a complete SQL statement, or zero +** otherwise. +*/ +static int test_complete16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#if !defined(SQLITE_OMIT_COMPLETE) && !defined(SQLITE_OMIT_UTF16) + char *zBuf; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + zBuf = (char*)Tcl_GetByteArrayFromObj(objv[1], 0); + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_complete16(zBuf))); +#endif /* SQLITE_OMIT_COMPLETE && SQLITE_OMIT_UTF16 */ + return TCL_OK; +} + +/* +** Usage: sqlite3_step STMT +** +** Advance the statement to the next row. +*/ +static int test_step( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + rc = sqlite3_step(pStmt); + + /* if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ) return TCL_ERROR; */ + Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} + +static int test_sql( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + Tcl_SetResult(interp, (char *)sqlite3_sql(pStmt), TCL_VOLATILE); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_count STMT +** +** Return the number of columns returned by the sql statement STMT. +*/ +static int test_column_count( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_column_count(pStmt))); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_type STMT column +** +** Return the type of the data in column 'column' of the current row. +*/ +static int test_column_type( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + int tp; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + tp = sqlite3_column_type(pStmt, col); + switch( tp ){ + case SQLITE_INTEGER: + Tcl_SetResult(interp, "INTEGER", TCL_STATIC); + break; + case SQLITE_NULL: + Tcl_SetResult(interp, "NULL", TCL_STATIC); + break; + case SQLITE_FLOAT: + Tcl_SetResult(interp, "FLOAT", TCL_STATIC); + break; + case SQLITE_TEXT: + Tcl_SetResult(interp, "TEXT", TCL_STATIC); + break; + case SQLITE_BLOB: + Tcl_SetResult(interp, "BLOB", TCL_STATIC); + break; + default: + assert(0); + } + + return TCL_OK; +} + +/* +** Usage: sqlite3_column_int64 STMT column +** +** Return the data in column 'column' of the current row cast as an +** wide (64-bit) integer. +*/ +static int test_column_int64( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + i64 iVal; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + iVal = sqlite3_column_int64(pStmt, col); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(iVal)); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_blob STMT column +*/ +static int test_column_blob( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + + int len; + const void *pBlob; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + len = sqlite3_column_bytes(pStmt, col); + pBlob = sqlite3_column_blob(pStmt, col); + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pBlob, len)); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_double STMT column +** +** Return the data in column 'column' of the current row cast as a double. +*/ +static int test_column_double( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + double rVal; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + rVal = sqlite3_column_double(pStmt, col); + Tcl_SetObjResult(interp, Tcl_NewDoubleObj(rVal)); + return TCL_OK; +} + +/* +** Usage: sqlite3_data_count STMT +** +** Return the number of columns returned by the sql statement STMT. +*/ +static int test_data_count( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_data_count(pStmt))); + return TCL_OK; +} + +/* +** Usage: sqlite3_column_text STMT column +** +** Usage: sqlite3_column_decltype STMT column +** +** Usage: sqlite3_column_name STMT column +*/ +static int test_stmt_utf8( + void * clientData, /* Pointer to SQLite API function to be invoke */ + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + const char *(*xFunc)(sqlite3_stmt*, int); + const char *zRet; + + xFunc = (const char *(*)(sqlite3_stmt*, int))clientData; + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + zRet = xFunc(pStmt, col); + if( zRet ){ + Tcl_SetResult(interp, (char *)zRet, 0); + } + return TCL_OK; +} + +static int test_global_recover( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_DEPRECATED + int rc; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + rc = sqlite3_global_recover(); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_column_text STMT column +** +** Usage: sqlite3_column_decltype STMT column +** +** Usage: sqlite3_column_name STMT column +*/ +static int test_stmt_utf16( + void * clientData, /* Pointer to SQLite API function to be invoked */ + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3_stmt *pStmt; + int col; + Tcl_Obj *pRet; + const void *zName16; + const void *(*xFunc)(sqlite3_stmt*, int); + + xFunc = (const void *(*)(sqlite3_stmt*, int))clientData; + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + zName16 = xFunc(pStmt, col); + if( zName16 ){ + int n; + const char *z = zName16; + for(n=0; z[n] || z[n+1]; n+=2){} + pRet = Tcl_NewByteArrayObj(zName16, n+2); + Tcl_SetObjResult(interp, pRet); + } +#endif /* SQLITE_OMIT_UTF16 */ + + return TCL_OK; +} + +/* +** Usage: sqlite3_column_int STMT column +** +** Usage: sqlite3_column_bytes STMT column +** +** Usage: sqlite3_column_bytes16 STMT column +** +*/ +static int test_stmt_int( + void * clientData, /* Pointer to SQLite API function to be invoked */ + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_stmt *pStmt; + int col; + int (*xFunc)(sqlite3_stmt*, int); + + xFunc = (int (*)(sqlite3_stmt*, int))clientData; + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " STMT column", 0); + return TCL_ERROR; + } + + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR; + + Tcl_SetObjResult(interp, Tcl_NewIntObj(xFunc(pStmt, col))); + return TCL_OK; +} + +/* +** Usage: sqlite_set_magic DB MAGIC-NUMBER +** +** Set the db->magic value. This is used to test error recovery logic. +*/ +static int sqlite_set_magic( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + sqlite3 *db; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB MAGIC", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + if( strcmp(argv[2], "SQLITE_MAGIC_OPEN")==0 ){ + db->magic = SQLITE_MAGIC_OPEN; + }else if( strcmp(argv[2], "SQLITE_MAGIC_CLOSED")==0 ){ + db->magic = SQLITE_MAGIC_CLOSED; + }else if( strcmp(argv[2], "SQLITE_MAGIC_BUSY")==0 ){ + db->magic = SQLITE_MAGIC_BUSY; + }else if( strcmp(argv[2], "SQLITE_MAGIC_ERROR")==0 ){ + db->magic = SQLITE_MAGIC_ERROR; + }else if( Tcl_GetInt(interp, argv[2], (int*)&db->magic) ){ + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: sqlite3_interrupt DB +** +** Trigger an interrupt on DB +*/ +static int test_interrupt( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + sqlite3 *db; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + sqlite3_interrupt(db); + return TCL_OK; +} + +static u8 *sqlite3_stack_baseline = 0; + +/* +** Fill the stack with a known bitpattern. +*/ +static void prepStack(void){ + int i; + u32 bigBuf[65536]; + for(i=0; i=0 && ((u32*)sqlite3_stack_baseline)[-i]==0xdeadbeef; i--){} + Tcl_SetObjResult(interp, Tcl_NewIntObj(i*4)); + return TCL_OK; +} + +/* +** Usage: sqlite_delete_function DB function-name +** +** Delete the user function 'function-name' from database handle DB. It +** is assumed that the user function was created as UTF8, any number of +** arguments (the way the TCL interface does it). +*/ +static int delete_function( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + int rc; + sqlite3 *db; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB function-name", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_create_function(db, argv[2], -1, SQLITE_UTF8, 0, 0, 0, 0); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** Usage: sqlite_delete_collation DB collation-name +** +** Delete the collation sequence 'collation-name' from database handle +** DB. It is assumed that the collation sequence was created as UTF8 (the +** way the TCL interface does it). +*/ +static int delete_collation( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + int rc; + sqlite3 *db; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB function-name", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + rc = sqlite3_create_collation(db, argv[2], SQLITE_UTF8, 0, 0); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** Usage: sqlite3_get_autocommit DB +** +** Return true if the database DB is currently in auto-commit mode. +** Return false if not. +*/ +static int get_autocommit( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + char zBuf[30]; + sqlite3 *db; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + sprintf(zBuf, "%d", sqlite3_get_autocommit(db)); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: sqlite3_busy_timeout DB MS +** +** Set the busy timeout. This is more easily done using the timeout +** method of the TCL interface. But we need a way to test the case +** where it returns SQLITE_MISUSE. +*/ +static int test_busy_timeout( + void * clientData, + Tcl_Interp *interp, + int argc, + char **argv +){ + int rc, ms; + sqlite3 *db; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[2], &ms) ) return TCL_ERROR; + rc = sqlite3_busy_timeout(db, ms); + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_OK; +} + +/* +** Usage: tcl_variable_type VARIABLENAME +** +** Return the name of the internal representation for the +** value of the given variable. +*/ +static int tcl_variable_type( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Obj *pVar; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "VARIABLE"); + return TCL_ERROR; + } + pVar = Tcl_GetVar2Ex(interp, Tcl_GetString(objv[1]), 0, TCL_LEAVE_ERR_MSG); + if( pVar==0 ) return TCL_ERROR; + if( pVar->typePtr ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(pVar->typePtr->name, -1)); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_release_memory ?N? +** +** Attempt to release memory currently held but not actually required. +** The integer N is the number of bytes we are trying to release. The +** return value is the amount of memory actually released. +*/ +static int test_release_memory( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO) + int N; + int amt; + if( objc!=1 && objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?N?"); + return TCL_ERROR; + } + if( objc==2 ){ + if( Tcl_GetIntFromObj(interp, objv[1], &N) ) return TCL_ERROR; + }else{ + N = -1; + } + amt = sqlite3_release_memory(N); + Tcl_SetObjResult(interp, Tcl_NewIntObj(amt)); +#endif + return TCL_OK; +} + + +/* +** Usage: sqlite3_db_release_memory DB +** +** Attempt to release memory currently held by database DB. Return the +** result code (which in the current implementation is always zero). +*/ +static int test_db_release_memory( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int rc; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_db_release_memory(db); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** Usage: sqlite3_db_filename DB DBNAME +** +** Return the name of a file associated with a database. +*/ +static int test_db_filename( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zDbName; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB DBNAME"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zDbName = Tcl_GetString(objv[2]); + Tcl_AppendResult(interp, sqlite3_db_filename(db, zDbName), (void*)0); + return TCL_OK; +} + +/* +** Usage: sqlite3_db_readonly DB DBNAME +** +** Return 1 or 0 if DBNAME is readonly or not. Return -1 if DBNAME does +** not exist. +*/ +static int test_db_readonly( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zDbName; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB DBNAME"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zDbName = Tcl_GetString(objv[2]); + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_db_readonly(db, zDbName))); + return TCL_OK; +} + +/* +** Usage: sqlite3_soft_heap_limit ?N? +** +** Query or set the soft heap limit for the current thread. The +** limit is only changed if the N is present. The previous limit +** is returned. +*/ +static int test_soft_heap_limit( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_int64 amt; + Tcl_WideInt N = -1; + if( objc!=1 && objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?N?"); + return TCL_ERROR; + } + if( objc==2 ){ + if( Tcl_GetWideIntFromObj(interp, objv[1], &N) ) return TCL_ERROR; + } + amt = sqlite3_soft_heap_limit64(N); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(amt)); + return TCL_OK; +} + +/* +** Usage: sqlite3_thread_cleanup +** +** Call the sqlite3_thread_cleanup API. +*/ +static int test_thread_cleanup( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_thread_cleanup(); +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_pager_refcounts DB +** +** Return a list of numbers which are the PagerRefcount for all +** pagers on each database connection. +*/ +static int test_pager_refcounts( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + int i; + int v, *a; + Tcl_Obj *pResult; + + if( objc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " DB", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + pResult = Tcl_NewObj(); + for(i=0; inDb; i++){ + if( db->aDb[i].pBt==0 ){ + v = -1; + }else{ + sqlite3_mutex_enter(db->mutex); + a = sqlite3PagerStats(sqlite3BtreePager(db->aDb[i].pBt)); + v = a[0]; + sqlite3_mutex_leave(db->mutex); + } + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(v)); + } + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + + +/* +** tclcmd: working_64bit_int +** +** Some TCL builds (ex: cygwin) do not support 64-bit integers. This +** leads to a number of test failures. The present command checks the +** TCL build to see whether or not it supports 64-bit integers. It +** returns TRUE if it does and FALSE if not. +** +** This command is used to warn users that their TCL build is defective +** and that the errors they are seeing in the test scripts might be +** a result of their defective TCL rather than problems in SQLite. +*/ +static int working_64bit_int( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + Tcl_Obj *pTestObj; + int working = 0; + + pTestObj = Tcl_NewWideIntObj(1000000*(i64)1234567890); + working = strcmp(Tcl_GetString(pTestObj), "1234567890000000")==0; + Tcl_DecrRefCount(pTestObj); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(working)); + return TCL_OK; +} + + +/* +** tclcmd: vfs_unlink_test +** +** This TCL command unregisters the primary VFS and then registers +** it back again. This is used to test the ability to register a +** VFS when none are previously registered, and the ability to +** unregister the only available VFS. Ticket #2738 +*/ +static int vfs_unlink_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int i; + sqlite3_vfs *pMain; + sqlite3_vfs *apVfs[20]; + sqlite3_vfs one, two; + + sqlite3_vfs_unregister(0); /* Unregister of NULL is harmless */ + one.zName = "__one"; + two.zName = "__two"; + + /* Calling sqlite3_vfs_register with 2nd argument of 0 does not + ** change the default VFS + */ + pMain = sqlite3_vfs_find(0); + sqlite3_vfs_register(&one, 0); + assert( pMain==0 || pMain==sqlite3_vfs_find(0) ); + sqlite3_vfs_register(&two, 0); + assert( pMain==0 || pMain==sqlite3_vfs_find(0) ); + + /* We can find a VFS by its name */ + assert( sqlite3_vfs_find("__one")==&one ); + assert( sqlite3_vfs_find("__two")==&two ); + + /* Calling sqlite_vfs_register with non-zero second parameter changes the + ** default VFS, even if the 1st parameter is an existig VFS that is + ** previously registered as the non-default. + */ + sqlite3_vfs_register(&one, 1); + assert( sqlite3_vfs_find("__one")==&one ); + assert( sqlite3_vfs_find("__two")==&two ); + assert( sqlite3_vfs_find(0)==&one ); + sqlite3_vfs_register(&two, 1); + assert( sqlite3_vfs_find("__one")==&one ); + assert( sqlite3_vfs_find("__two")==&two ); + assert( sqlite3_vfs_find(0)==&two ); + if( pMain ){ + sqlite3_vfs_register(pMain, 1); + assert( sqlite3_vfs_find("__one")==&one ); + assert( sqlite3_vfs_find("__two")==&two ); + assert( sqlite3_vfs_find(0)==pMain ); + } + + /* Unlink the default VFS. Repeat until there are no more VFSes + ** registered. + */ + for(i=0; izName) ); + sqlite3_vfs_unregister(apVfs[i]); + assert( 0==sqlite3_vfs_find(apVfs[i]->zName) ); + } + } + assert( 0==sqlite3_vfs_find(0) ); + + /* Register the main VFS as non-default (will be made default, since + ** it'll be the only one in existence). + */ + sqlite3_vfs_register(pMain, 0); + assert( sqlite3_vfs_find(0)==pMain ); + + /* Un-register the main VFS again to restore an empty VFS list */ + sqlite3_vfs_unregister(pMain); + assert( 0==sqlite3_vfs_find(0) ); + + /* Relink all VFSes in reverse order. */ + for(i=sizeof(apVfs)/sizeof(apVfs[0])-1; i>=0; i--){ + if( apVfs[i] ){ + sqlite3_vfs_register(apVfs[i], 1); + assert( apVfs[i]==sqlite3_vfs_find(0) ); + assert( apVfs[i]==sqlite3_vfs_find(apVfs[i]->zName) ); + } + } + + /* Unregister out sample VFSes. */ + sqlite3_vfs_unregister(&one); + sqlite3_vfs_unregister(&two); + + /* Unregistering a VFS that is not currently registered is harmless */ + sqlite3_vfs_unregister(&one); + sqlite3_vfs_unregister(&two); + assert( sqlite3_vfs_find("__one")==0 ); + assert( sqlite3_vfs_find("__two")==0 ); + + /* We should be left with the original default VFS back as the + ** original */ + assert( sqlite3_vfs_find(0)==pMain ); + + return TCL_OK; +} + +/* +** tclcmd: vfs_initfail_test +** +** This TCL command attempts to vfs_find and vfs_register when the +** sqlite3_initialize() interface is failing. All calls should fail. +*/ +static int vfs_initfail_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_vfs one; + one.zName = "__one"; + + if( sqlite3_vfs_find(0) ) return TCL_ERROR; + sqlite3_vfs_register(&one, 0); + if( sqlite3_vfs_find(0) ) return TCL_ERROR; + sqlite3_vfs_register(&one, 1); + if( sqlite3_vfs_find(0) ) return TCL_ERROR; + return TCL_OK; +} + +/* +** Saved VFSes +*/ +static sqlite3_vfs *apVfs[20]; +static int nVfs = 0; + +/* +** tclcmd: vfs_unregister_all +** +** Unregister all VFSes. +*/ +static int vfs_unregister_all( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int i; + for(i=0; ipNext){ + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(pVfs->zName, -1)); + } + Tcl_SetObjResult(interp, pRet); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_limit DB ID VALUE +** +** This TCL command runs the sqlite3_limit interface and +** verifies correct operation of the same. +*/ +static int test_limit( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + int rc; + static const struct { + char *zName; + int id; + } aId[] = { + { "SQLITE_LIMIT_LENGTH", SQLITE_LIMIT_LENGTH }, + { "SQLITE_LIMIT_SQL_LENGTH", SQLITE_LIMIT_SQL_LENGTH }, + { "SQLITE_LIMIT_COLUMN", SQLITE_LIMIT_COLUMN }, + { "SQLITE_LIMIT_EXPR_DEPTH", SQLITE_LIMIT_EXPR_DEPTH }, + { "SQLITE_LIMIT_COMPOUND_SELECT", SQLITE_LIMIT_COMPOUND_SELECT }, + { "SQLITE_LIMIT_VDBE_OP", SQLITE_LIMIT_VDBE_OP }, + { "SQLITE_LIMIT_FUNCTION_ARG", SQLITE_LIMIT_FUNCTION_ARG }, + { "SQLITE_LIMIT_ATTACHED", SQLITE_LIMIT_ATTACHED }, + { "SQLITE_LIMIT_LIKE_PATTERN_LENGTH", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, + { "SQLITE_LIMIT_VARIABLE_NUMBER", SQLITE_LIMIT_VARIABLE_NUMBER }, + { "SQLITE_LIMIT_TRIGGER_DEPTH", SQLITE_LIMIT_TRIGGER_DEPTH }, + + /* Out of range test cases */ + { "SQLITE_LIMIT_TOOSMALL", -1, }, + { "SQLITE_LIMIT_TOOBIG", SQLITE_LIMIT_TRIGGER_DEPTH+1 }, + }; + int i, id; + int val; + const char *zId; + + if( objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " DB ID VALUE", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zId = Tcl_GetString(objv[2]); + for(i=0; i=sizeof(aId)/sizeof(aId[0]) ){ + Tcl_AppendResult(interp, "unknown limit type: ", zId, (char*)0); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[3], &val) ) return TCL_ERROR; + rc = sqlite3_limit(db, id, val); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: save_prng_state +** +** Save the state of the pseudo-random number generator. +** At the same time, verify that sqlite3_test_control works even when +** called with an out-of-range opcode. +*/ +static int save_prng_state( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int rc = sqlite3_test_control(9999); + assert( rc==0 ); + rc = sqlite3_test_control(-1); + assert( rc==0 ); + sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SAVE); + return TCL_OK; +} +/* +** tclcmd: restore_prng_state +*/ +static int restore_prng_state( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_test_control(SQLITE_TESTCTRL_PRNG_RESTORE); + return TCL_OK; +} +/* +** tclcmd: reset_prng_state +*/ +static int reset_prng_state( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_test_control(SQLITE_TESTCTRL_PRNG_RESET); + return TCL_OK; +} + +/* +** tclcmd: pcache_stats +*/ +static int test_pcache_stats( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int nMin; + int nMax; + int nCurrent; + int nRecyclable; + Tcl_Obj *pRet; + + sqlite3PcacheStats(&nCurrent, &nMax, &nMin, &nRecyclable); + + pRet = Tcl_NewObj(); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("current", -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nCurrent)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("max", -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nMax)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("min", -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nMin)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("recyclable", -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nRecyclable)); + + Tcl_SetObjResult(interp, pRet); + + return TCL_OK; +} + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY +static void test_unlock_notify_cb(void **aArg, int nArg){ + int ii; + for(ii=0; ii2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SCRIPT"); + return TCL_ERROR; + } + if( logcallback.pObj ){ + Tcl_DecrRefCount(logcallback.pObj); + logcallback.pObj = 0; + logcallback.pInterp = 0; + sqlite3_config(SQLITE_CONFIG_LOG, 0, 0); + } + if( objc>1 ){ + logcallback.pObj = objv[1]; + Tcl_IncrRefCount(logcallback.pObj); + logcallback.pInterp = interp; + sqlite3_config(SQLITE_CONFIG_LOG, xLogcallback, 0); + } + return TCL_OK; +} + +/* +** tcl_objproc COMMANDNAME ARGS... +** +** Run a TCL command using its objProc interface. Throw an error if +** the command has no objProc interface. +*/ +static int runAsObjProc( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_CmdInfo cmdInfo; + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "COMMAND ..."); + return TCL_ERROR; + } + if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){ + Tcl_AppendResult(interp, "command not found: ", + Tcl_GetString(objv[1]), (char*)0); + return TCL_ERROR; + } + if( cmdInfo.objProc==0 ){ + Tcl_AppendResult(interp, "command has no objProc: ", + Tcl_GetString(objv[1]), (char*)0); + return TCL_ERROR; + } + return cmdInfo.objProc(cmdInfo.objClientData, interp, objc-1, objv+1); +} + +#ifndef SQLITE_OMIT_EXPLAIN +/* +** WARNING: The following function, printExplainQueryPlan() is an exact +** copy of example code from eqp.in (eqp.html). If this code is modified, +** then the documentation copy needs to be modified as well. +*/ +/* +** Argument pStmt is a prepared SQL statement. This function compiles +** an EXPLAIN QUERY PLAN command to report on the prepared statement, +** and prints the report to stdout using printf(). +*/ +int printExplainQueryPlan(sqlite3_stmt *pStmt){ + const char *zSql; /* Input SQL */ + char *zExplain; /* SQL with EXPLAIN QUERY PLAN prepended */ + sqlite3_stmt *pExplain; /* Compiled EXPLAIN QUERY PLAN command */ + int rc; /* Return code from sqlite3_prepare_v2() */ + + zSql = sqlite3_sql(pStmt); + if( zSql==0 ) return SQLITE_ERROR; + + zExplain = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zSql); + if( zExplain==0 ) return SQLITE_NOMEM; + + rc = sqlite3_prepare_v2(sqlite3_db_handle(pStmt), zExplain, -1, &pExplain, 0); + sqlite3_free(zExplain); + if( rc!=SQLITE_OK ) return rc; + + while( SQLITE_ROW==sqlite3_step(pExplain) ){ + int iSelectid = sqlite3_column_int(pExplain, 0); + int iOrder = sqlite3_column_int(pExplain, 1); + int iFrom = sqlite3_column_int(pExplain, 2); + const char *zDetail = (const char *)sqlite3_column_text(pExplain, 3); + + printf("%d %d %d %s\n", iSelectid, iOrder, iFrom, zDetail); + } + + return sqlite3_finalize(pExplain); +} + +static int test_print_eqp( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + sqlite3_stmt *pStmt; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR; + rc = printExplainQueryPlan(pStmt); + /* This is needed on Windows so that a test case using this + ** function can open a read pipe and get the output of + ** printExplainQueryPlan() immediately. + */ + fflush(stdout); + Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0); + return TCL_OK; +} +#endif /* SQLITE_OMIT_EXPLAIN */ + +/* +** sqlite3_test_control VERB ARGS... +*/ +static int test_test_control( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct Verb { + const char *zName; + int i; + } aVerb[] = { + { "SQLITE_TESTCTRL_LOCALTIME_FAULT", SQLITE_TESTCTRL_LOCALTIME_FAULT }, + }; + int iVerb; + int iFlag; + int rc; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "VERB ARGS..."); + return TCL_ERROR; + } + + rc = Tcl_GetIndexFromObjStruct( + interp, objv[1], aVerb, sizeof(aVerb[0]), "VERB", 0, &iVerb + ); + if( rc!=TCL_OK ) return rc; + + iFlag = aVerb[iVerb].i; + switch( iFlag ){ + case SQLITE_TESTCTRL_LOCALTIME_FAULT: { + int val; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "ONOFF"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR; + sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, val); + break; + } + } + + Tcl_ResetResult(interp); + return TCL_OK; +} + +#if SQLITE_OS_UNIX +#include +#include + +static int test_getrusage( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + char buf[1024]; + struct rusage r; + memset(&r, 0, sizeof(r)); + getrusage(RUSAGE_SELF, &r); + + sprintf(buf, "ru_utime=%d.%06d ru_stime=%d.%06d ru_minflt=%d ru_majflt=%d", + (int)r.ru_utime.tv_sec, (int)r.ru_utime.tv_usec, + (int)r.ru_stime.tv_sec, (int)r.ru_stime.tv_usec, + (int)r.ru_minflt, (int)r.ru_majflt + ); + Tcl_SetObjResult(interp, Tcl_NewStringObj(buf, -1)); + return TCL_OK; +} +#endif + +#if SQLITE_OS_WIN +/* +** Information passed from the main thread into the windows file locker +** background thread. +*/ +struct win32FileLocker { + char *evName; /* Name of event to signal thread startup */ + HANDLE h; /* Handle of the file to be locked */ + int delay1; /* Delay before locking */ + int delay2; /* Delay before unlocking */ + int ok; /* Finished ok */ + int err; /* True if an error occurs */ +}; +#endif + + +#if SQLITE_OS_WIN +#include +/* +** The background thread that does file locking. +*/ +static void win32_file_locker(void *pAppData){ + struct win32FileLocker *p = (struct win32FileLocker*)pAppData; + if( p->evName ){ + HANDLE ev = OpenEvent(EVENT_MODIFY_STATE, FALSE, p->evName); + if ( ev ){ + SetEvent(ev); + CloseHandle(ev); + } + } + if( p->delay1 ) Sleep(p->delay1); + if( LockFile(p->h, 0, 0, 100000000, 0) ){ + Sleep(p->delay2); + UnlockFile(p->h, 0, 0, 100000000, 0); + p->ok = 1; + }else{ + p->err = 1; + } + CloseHandle(p->h); + p->h = 0; + p->delay1 = 0; + p->delay2 = 0; +} +#endif + +#if SQLITE_OS_WIN +/* +** lock_win32_file FILENAME DELAY1 DELAY2 +** +** Get an exclusive manditory lock on file for DELAY2 milliseconds. +** Wait DELAY1 milliseconds before acquiring the lock. +*/ +static int win32_file_lock( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + static struct win32FileLocker x = { "win32_file_lock", 0, 0, 0, 0, 0 }; + const char *zFilename; + char zBuf[200]; + int retry = 0; + HANDLE ev; + DWORD wResult; + + if( objc!=4 && objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME DELAY1 DELAY2"); + return TCL_ERROR; + } + if( objc==1 ){ + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d %d %d %d %d", + x.ok, x.err, x.delay1, x.delay2, x.h); + Tcl_AppendResult(interp, zBuf, (char*)0); + return TCL_OK; + } + while( x.h && retry<30 ){ + retry++; + Sleep(100); + } + if( x.h ){ + Tcl_AppendResult(interp, "busy", (char*)0); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[2], &x.delay1) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &x.delay2) ) return TCL_ERROR; + zFilename = Tcl_GetString(objv[1]); + x.h = CreateFile(zFilename, GENERIC_READ|GENERIC_WRITE, + FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, 0); + if( !x.h ){ + Tcl_AppendResult(interp, "cannot open file: ", zFilename, (char*)0); + return TCL_ERROR; + } + ev = CreateEvent(NULL, TRUE, FALSE, x.evName); + if ( !ev ){ + Tcl_AppendResult(interp, "cannot create event: ", x.evName, (char*)0); + return TCL_ERROR; + } + _beginthread(win32_file_locker, 0, (void*)&x); + Sleep(0); + if ( (wResult = WaitForSingleObject(ev, 10000))!=WAIT_OBJECT_0 ){ + sqlite3_snprintf(sizeof(zBuf), zBuf, "0x%x", wResult); + Tcl_AppendResult(interp, "wait failed: ", zBuf, (char*)0); + CloseHandle(ev); + return TCL_ERROR; + } + CloseHandle(ev); + return TCL_OK; +} + +/* +** exists_win32_path PATH +** +** Returns non-zero if the specified path exists, whose fully qualified name +** may exceed 260 characters if it is prefixed with "\\?\". +*/ +static int win32_exists_path( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PATH"); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewBooleanObj( + GetFileAttributesW( Tcl_GetUnicode(objv[1]))!=INVALID_FILE_ATTRIBUTES )); + return TCL_OK; +} + +/* +** find_win32_file PATTERN +** +** Returns a list of entries in a directory that match the specified pattern, +** whose fully qualified name may exceed 248 characters if it is prefixed with +** "\\?\". +*/ +static int win32_find_file( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + HANDLE hFindFile = INVALID_HANDLE_VALUE; + WIN32_FIND_DATAW findData; + Tcl_Obj *listObj; + DWORD lastErrno; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PATTERN"); + return TCL_ERROR; + } + hFindFile = FindFirstFileW(Tcl_GetUnicode(objv[1]), &findData); + if( hFindFile==INVALID_HANDLE_VALUE ){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + listObj = Tcl_NewObj(); + Tcl_IncrRefCount(listObj); + do { + Tcl_ListObjAppendElement(interp, listObj, Tcl_NewUnicodeObj( + findData.cFileName, -1)); + Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj( + findData.dwFileAttributes)); + } while( FindNextFileW(hFindFile, &findData) ); + lastErrno = GetLastError(); + if( lastErrno!=NO_ERROR && lastErrno!=ERROR_NO_MORE_FILES ){ + FindClose(hFindFile); + Tcl_DecrRefCount(listObj); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + FindClose(hFindFile); + Tcl_SetObjResult(interp, listObj); + return TCL_OK; +} + +/* +** delete_win32_file FILENAME +** +** Deletes the specified file, whose fully qualified name may exceed 260 +** characters if it is prefixed with "\\?\". +*/ +static int win32_delete_file( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } + if( !DeleteFileW(Tcl_GetUnicode(objv[1])) ){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + Tcl_ResetResult(interp); + return TCL_OK; +} + +/* +** make_win32_dir DIRECTORY +** +** Creates the specified directory, whose fully qualified name may exceed 248 +** characters if it is prefixed with "\\?\". +*/ +static int win32_mkdir( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DIRECTORY"); + return TCL_ERROR; + } + if( !CreateDirectoryW(Tcl_GetUnicode(objv[1]), NULL) ){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + Tcl_ResetResult(interp); + return TCL_OK; +} + +/* +** remove_win32_dir DIRECTORY +** +** Removes the specified directory, whose fully qualified name may exceed 248 +** characters if it is prefixed with "\\?\". +*/ +static int win32_rmdir( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DIRECTORY"); + return TCL_ERROR; + } + if( !RemoveDirectoryW(Tcl_GetUnicode(objv[1])) ){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(GetLastError())); + return TCL_ERROR; + } + Tcl_ResetResult(interp); + return TCL_OK; +} +#endif + + +/* +** optimization_control DB OPT BOOLEAN +** +** Enable or disable query optimizations using the sqlite3_test_control() +** interface. Disable if BOOLEAN is false and enable if BOOLEAN is true. +** OPT is the name of the optimization to be disabled. +*/ +static int optimization_control( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int i; + sqlite3 *db; + const char *zOpt; + int onoff; + int mask = 0; + static const struct { + const char *zOptName; + int mask; + } aOpt[] = { + { "all", SQLITE_AllOpts }, + { "none", 0 }, + { "query-flattener", SQLITE_QueryFlattener }, + { "column-cache", SQLITE_ColumnCache }, + { "groupby-order", SQLITE_GroupByOrder }, + { "factor-constants", SQLITE_FactorOutConst }, + { "real-as-int", SQLITE_IdxRealAsInt }, + { "distinct-opt", SQLITE_DistinctOpt }, + { "cover-idx-scan", SQLITE_CoverIdxScan }, + { "order-by-idx-join", SQLITE_OrderByIdxJoin }, + { "transitive", SQLITE_Transitive }, + { "subquery-coroutine", SQLITE_SubqCoroutine }, + { "omit-noop-join", SQLITE_OmitNoopJoin }, + { "stat3", SQLITE_Stat3 }, + }; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB OPT BOOLEAN"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( Tcl_GetBooleanFromObj(interp, objv[3], &onoff) ) return TCL_ERROR; + zOpt = Tcl_GetString(objv[2]); + for(i=0; i=sizeof(aOpt)/sizeof(aOpt[0]) ){ + Tcl_AppendResult(interp, "unknown optimization - should be one of:", + (char*)0); + for(i=0; i=ArraySize(aExtension) ){ + Tcl_AppendResult(interp, "no such extension: ", zName, (char*)0); + return TCL_ERROR; + } + rc = aExtension[i].pInit(db, &zErrMsg, 0); + if( rc!=SQLITE_OK || zErrMsg ){ + Tcl_AppendResult(interp, "initialization of ", zName, " failed: ", zErrMsg, + (char*)0); + sqlite3_free(zErrMsg); + return TCL_ERROR; + } + } + return TCL_OK; +} + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest1_Init(Tcl_Interp *interp){ + extern int sqlite3_search_count; + extern int sqlite3_found_count; + extern int sqlite3_interrupt_count; + extern int sqlite3_open_file_count; + extern int sqlite3_sort_count; + extern int sqlite3_current_time; +#if SQLITE_OS_UNIX && defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE + extern int sqlite3_hostid_num; +#endif + extern int sqlite3_max_blobsize; + extern int sqlite3BtreeSharedCacheReport(void*, + Tcl_Interp*,int,Tcl_Obj*CONST*); + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "db_enter", (Tcl_CmdProc*)db_enter }, + { "db_leave", (Tcl_CmdProc*)db_leave }, + { "sqlite3_mprintf_int", (Tcl_CmdProc*)sqlite3_mprintf_int }, + { "sqlite3_mprintf_int64", (Tcl_CmdProc*)sqlite3_mprintf_int64 }, + { "sqlite3_mprintf_long", (Tcl_CmdProc*)sqlite3_mprintf_long }, + { "sqlite3_mprintf_str", (Tcl_CmdProc*)sqlite3_mprintf_str }, + { "sqlite3_snprintf_str", (Tcl_CmdProc*)sqlite3_snprintf_str }, + { "sqlite3_mprintf_stronly", (Tcl_CmdProc*)sqlite3_mprintf_stronly}, + { "sqlite3_mprintf_double", (Tcl_CmdProc*)sqlite3_mprintf_double }, + { "sqlite3_mprintf_scaled", (Tcl_CmdProc*)sqlite3_mprintf_scaled }, + { "sqlite3_mprintf_hexdouble", (Tcl_CmdProc*)sqlite3_mprintf_hexdouble}, + { "sqlite3_mprintf_z_test", (Tcl_CmdProc*)test_mprintf_z }, + { "sqlite3_mprintf_n_test", (Tcl_CmdProc*)test_mprintf_n }, + { "sqlite3_snprintf_int", (Tcl_CmdProc*)test_snprintf_int }, + { "sqlite3_last_insert_rowid", (Tcl_CmdProc*)test_last_rowid }, + { "sqlite3_exec_printf", (Tcl_CmdProc*)test_exec_printf }, + { "sqlite3_exec_hex", (Tcl_CmdProc*)test_exec_hex }, + { "sqlite3_exec", (Tcl_CmdProc*)test_exec }, + { "sqlite3_exec_nr", (Tcl_CmdProc*)test_exec_nr }, +#ifndef SQLITE_OMIT_GET_TABLE + { "sqlite3_get_table_printf", (Tcl_CmdProc*)test_get_table_printf }, +#endif + { "sqlite3_close", (Tcl_CmdProc*)sqlite_test_close }, + { "sqlite3_close_v2", (Tcl_CmdProc*)sqlite_test_close_v2 }, + { "sqlite3_create_function", (Tcl_CmdProc*)test_create_function }, + { "sqlite3_create_aggregate", (Tcl_CmdProc*)test_create_aggregate }, + { "sqlite_register_test_function", (Tcl_CmdProc*)test_register_func }, + { "sqlite_abort", (Tcl_CmdProc*)sqlite_abort }, + { "sqlite_bind", (Tcl_CmdProc*)test_bind }, + { "breakpoint", (Tcl_CmdProc*)test_breakpoint }, + { "sqlite3_key", (Tcl_CmdProc*)test_key }, + { "sqlite3_rekey", (Tcl_CmdProc*)test_rekey }, + { "sqlite_set_magic", (Tcl_CmdProc*)sqlite_set_magic }, + { "sqlite3_interrupt", (Tcl_CmdProc*)test_interrupt }, + { "sqlite_delete_function", (Tcl_CmdProc*)delete_function }, + { "sqlite_delete_collation", (Tcl_CmdProc*)delete_collation }, + { "sqlite3_get_autocommit", (Tcl_CmdProc*)get_autocommit }, + { "sqlite3_stack_used", (Tcl_CmdProc*)test_stack_used }, + { "sqlite3_busy_timeout", (Tcl_CmdProc*)test_busy_timeout }, + { "printf", (Tcl_CmdProc*)test_printf }, + { "sqlite3IoTrace", (Tcl_CmdProc*)test_io_trace }, + }; + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "sqlite3_connection_pointer", get_sqlite_pointer, 0 }, + { "sqlite3_bind_int", test_bind_int, 0 }, + { "sqlite3_bind_zeroblob", test_bind_zeroblob, 0 }, + { "sqlite3_bind_int64", test_bind_int64, 0 }, + { "sqlite3_bind_double", test_bind_double, 0 }, + { "sqlite3_bind_null", test_bind_null ,0 }, + { "sqlite3_bind_text", test_bind_text ,0 }, + { "sqlite3_bind_text16", test_bind_text16 ,0 }, + { "sqlite3_bind_blob", test_bind_blob ,0 }, + { "sqlite3_bind_parameter_count", test_bind_parameter_count, 0}, + { "sqlite3_bind_parameter_name", test_bind_parameter_name, 0}, + { "sqlite3_bind_parameter_index", test_bind_parameter_index, 0}, + { "sqlite3_clear_bindings", test_clear_bindings, 0}, + { "sqlite3_sleep", test_sleep, 0}, + { "sqlite3_errcode", test_errcode ,0 }, + { "sqlite3_extended_errcode", test_ex_errcode ,0 }, + { "sqlite3_errmsg", test_errmsg ,0 }, + { "sqlite3_errmsg16", test_errmsg16 ,0 }, + { "sqlite3_open", test_open ,0 }, + { "sqlite3_open16", test_open16 ,0 }, + { "sqlite3_open_v2", test_open_v2 ,0 }, + { "sqlite3_complete16", test_complete16 ,0 }, + + { "sqlite3_prepare", test_prepare ,0 }, + { "sqlite3_prepare16", test_prepare16 ,0 }, + { "sqlite3_prepare_v2", test_prepare_v2 ,0 }, + { "sqlite3_prepare_tkt3134", test_prepare_tkt3134, 0}, + { "sqlite3_prepare16_v2", test_prepare16_v2 ,0 }, + { "sqlite3_finalize", test_finalize ,0 }, + { "sqlite3_stmt_status", test_stmt_status ,0 }, + { "sqlite3_reset", test_reset ,0 }, + { "sqlite3_expired", test_expired ,0 }, + { "sqlite3_transfer_bindings", test_transfer_bind ,0 }, + { "sqlite3_changes", test_changes ,0 }, + { "sqlite3_step", test_step ,0 }, + { "sqlite3_sql", test_sql ,0 }, + { "sqlite3_next_stmt", test_next_stmt ,0 }, + { "sqlite3_stmt_readonly", test_stmt_readonly ,0 }, + { "sqlite3_stmt_busy", test_stmt_busy ,0 }, + { "uses_stmt_journal", uses_stmt_journal ,0 }, + + { "sqlite3_release_memory", test_release_memory, 0}, + { "sqlite3_db_release_memory", test_db_release_memory, 0}, + { "sqlite3_db_filename", test_db_filename, 0}, + { "sqlite3_db_readonly", test_db_readonly, 0}, + { "sqlite3_soft_heap_limit", test_soft_heap_limit, 0}, + { "sqlite3_thread_cleanup", test_thread_cleanup, 0}, + { "sqlite3_pager_refcounts", test_pager_refcounts, 0}, + + { "sqlite3_load_extension", test_load_extension, 0}, + { "sqlite3_enable_load_extension", test_enable_load, 0}, + { "sqlite3_extended_result_codes", test_extended_result_codes, 0}, + { "sqlite3_limit", test_limit, 0}, + + { "save_prng_state", save_prng_state, 0 }, + { "restore_prng_state", restore_prng_state, 0 }, + { "reset_prng_state", reset_prng_state, 0 }, + { "optimization_control", optimization_control,0}, +#if SQLITE_OS_WIN + { "lock_win32_file", win32_file_lock, 0 }, + { "exists_win32_path", win32_exists_path, 0 }, + { "find_win32_file", win32_find_file, 0 }, + { "delete_win32_file", win32_delete_file, 0 }, + { "make_win32_dir", win32_mkdir, 0 }, + { "remove_win32_dir", win32_rmdir, 0 }, +#endif + { "tcl_objproc", runAsObjProc, 0 }, + + /* sqlite3_column_*() API */ + { "sqlite3_column_count", test_column_count ,0 }, + { "sqlite3_data_count", test_data_count ,0 }, + { "sqlite3_column_type", test_column_type ,0 }, + { "sqlite3_column_blob", test_column_blob ,0 }, + { "sqlite3_column_double", test_column_double ,0 }, + { "sqlite3_column_int64", test_column_int64 ,0 }, + { "sqlite3_column_text", test_stmt_utf8, (void*)sqlite3_column_text }, + { "sqlite3_column_name", test_stmt_utf8, (void*)sqlite3_column_name }, + { "sqlite3_column_int", test_stmt_int, (void*)sqlite3_column_int }, + { "sqlite3_column_bytes", test_stmt_int, (void*)sqlite3_column_bytes}, +#ifndef SQLITE_OMIT_DECLTYPE + { "sqlite3_column_decltype",test_stmt_utf8,(void*)sqlite3_column_decltype}, +#endif +#ifdef SQLITE_ENABLE_COLUMN_METADATA +{ "sqlite3_column_database_name",test_stmt_utf8,(void*)sqlite3_column_database_name}, +{ "sqlite3_column_table_name",test_stmt_utf8,(void*)sqlite3_column_table_name}, +{ "sqlite3_column_origin_name",test_stmt_utf8,(void*)sqlite3_column_origin_name}, +#endif + +#ifndef SQLITE_OMIT_UTF16 + { "sqlite3_column_bytes16", test_stmt_int, (void*)sqlite3_column_bytes16 }, + { "sqlite3_column_text16", test_stmt_utf16, (void*)sqlite3_column_text16}, + { "sqlite3_column_name16", test_stmt_utf16, (void*)sqlite3_column_name16}, + { "add_alignment_test_collations", add_alignment_test_collations, 0 }, +#ifndef SQLITE_OMIT_DECLTYPE + { "sqlite3_column_decltype16",test_stmt_utf16,(void*)sqlite3_column_decltype16}, +#endif +#ifdef SQLITE_ENABLE_COLUMN_METADATA +{"sqlite3_column_database_name16", + test_stmt_utf16, (void*)sqlite3_column_database_name16}, +{"sqlite3_column_table_name16", test_stmt_utf16, (void*)sqlite3_column_table_name16}, +{"sqlite3_column_origin_name16", test_stmt_utf16, (void*)sqlite3_column_origin_name16}, +#endif +#endif + { "sqlite3_create_collation_v2", test_create_collation_v2, 0 }, + { "sqlite3_global_recover", test_global_recover, 0 }, + { "working_64bit_int", working_64bit_int, 0 }, + { "vfs_unlink_test", vfs_unlink_test, 0 }, + { "vfs_initfail_test", vfs_initfail_test, 0 }, + { "vfs_unregister_all", vfs_unregister_all, 0 }, + { "vfs_reregister_all", vfs_reregister_all, 0 }, + { "file_control_test", file_control_test, 0 }, + { "file_control_lasterrno_test", file_control_lasterrno_test, 0 }, + { "file_control_lockproxy_test", file_control_lockproxy_test, 0 }, + { "file_control_chunksize_test", file_control_chunksize_test, 0 }, + { "file_control_sizehint_test", file_control_sizehint_test, 0 }, + { "file_control_win32_av_retry", file_control_win32_av_retry, 0 }, + { "file_control_persist_wal", file_control_persist_wal, 0 }, + { "file_control_powersafe_overwrite",file_control_powersafe_overwrite,0}, + { "file_control_vfsname", file_control_vfsname, 0 }, + { "file_control_tempfilename", file_control_tempfilename, 0 }, + { "sqlite3_vfs_list", vfs_list, 0 }, + { "sqlite3_create_function_v2", test_create_function_v2, 0 }, + + /* Functions from os.h */ +#ifndef SQLITE_OMIT_UTF16 + { "add_test_collate", test_collate, 0 }, + { "add_test_collate_needed", test_collate_needed, 0 }, + { "add_test_function", test_function, 0 }, +#endif + { "sqlite3_test_errstr", test_errstr, 0 }, + { "tcl_variable_type", tcl_variable_type, 0 }, +#ifndef SQLITE_OMIT_SHARED_CACHE + { "sqlite3_enable_shared_cache", test_enable_shared, 0 }, + { "sqlite3_shared_cache_report", sqlite3BtreeSharedCacheReport, 0}, +#endif + { "sqlite3_libversion_number", test_libversion_number, 0 }, +#ifdef SQLITE_ENABLE_COLUMN_METADATA + { "sqlite3_table_column_metadata", test_table_column_metadata, 0 }, +#endif +#ifndef SQLITE_OMIT_INCRBLOB + { "sqlite3_blob_read", test_blob_read, 0 }, + { "sqlite3_blob_write", test_blob_write, 0 }, + { "sqlite3_blob_reopen", test_blob_reopen, 0 }, + { "sqlite3_blob_bytes", test_blob_bytes, 0 }, + { "sqlite3_blob_close", test_blob_close, 0 }, +#endif + { "pcache_stats", test_pcache_stats, 0 }, +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + { "sqlite3_unlock_notify", test_unlock_notify, 0 }, +#endif + { "sqlite3_wal_checkpoint", test_wal_checkpoint, 0 }, + { "sqlite3_wal_checkpoint_v2",test_wal_checkpoint_v2, 0 }, + { "test_sqlite3_log", test_sqlite3_log, 0 }, +#ifndef SQLITE_OMIT_EXPLAIN + { "print_explain_query_plan", test_print_eqp, 0 }, +#endif + { "sqlite3_test_control", test_test_control }, +#if SQLITE_OS_UNIX + { "getrusage", test_getrusage }, +#endif + { "load_static_extension", tclLoadStaticExtensionCmd }, + }; + static int bitmask_size = sizeof(Bitmask)*8; + int i; + extern int sqlite3_sync_count, sqlite3_fullsync_count; + extern int sqlite3_opentemp_count; + extern int sqlite3_like_count; + extern int sqlite3_xferopt_count; + extern int sqlite3_pager_readdb_count; + extern int sqlite3_pager_writedb_count; + extern int sqlite3_pager_writej_count; +#if SQLITE_OS_WIN + extern int sqlite3_os_type; +#endif +#ifdef SQLITE_DEBUG + extern int sqlite3WhereTrace; + extern int sqlite3OSTrace; + extern int sqlite3WalTrace; +#endif +#ifdef SQLITE_TEST +#ifdef SQLITE_ENABLE_FTS3 + extern int sqlite3_fts3_enable_parentheses; +#endif +#endif + + for(i=0; i +#include +#include + +extern const char *sqlite3ErrName(int); + +/* +** Page size and reserved size used for testing. +*/ +static int test_pagesize = 1024; + +/* +** Dummy page reinitializer +*/ +static void pager_test_reiniter(DbPage *pNotUsed){ + return; +} + +/* +** Usage: pager_open FILENAME N-PAGE +** +** Open a new pager +*/ +static int pager_open( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + u32 pageSize; + Pager *pPager; + int nPage; + int rc; + char zBuf[100]; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FILENAME N-PAGE\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[2], &nPage) ) return TCL_ERROR; + rc = sqlite3PagerOpen(sqlite3_vfs_find(0), &pPager, argv[1], 0, 0, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MAIN_DB, + pager_test_reiniter); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3PagerSetCachesize(pPager, nPage); + pageSize = test_pagesize; + sqlite3PagerSetPagesize(pPager, &pageSize, -1); + sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPager); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: pager_close ID +** +** Close the given pager. +*/ +static int pager_close( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerClose(pPager); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_rollback ID +** +** Rollback changes +*/ +static int pager_rollback( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerRollback(pPager); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_commit ID +** +** Commit all changes +*/ +static int pager_commit( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerCommitPhaseOne(pPager, 0, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + rc = sqlite3PagerCommitPhaseTwo(pPager); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_stmt_begin ID +** +** Start a new checkpoint. +*/ +static int pager_stmt_begin( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerOpenSavepoint(pPager, 1); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_stmt_rollback ID +** +** Rollback changes to a checkpoint +*/ +static int pager_stmt_rollback( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, 0); + sqlite3PagerSavepoint(pPager, SAVEPOINT_RELEASE, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_stmt_commit ID +** +** Commit changes to a checkpoint +*/ +static int pager_stmt_commit( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_RELEASE, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: pager_stats ID +** +** Return pager statistics. +*/ +static int pager_stats( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int i, *a; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + a = sqlite3PagerStats(pPager); + for(i=0; i<9; i++){ + static char *zName[] = { + "ref", "page", "max", "size", "state", "err", + "hit", "miss", "ovfl", + }; + char zBuf[100]; + Tcl_AppendElement(interp, zName[i]); + sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",a[i]); + Tcl_AppendElement(interp, zBuf); + } + return TCL_OK; +} + +/* +** Usage: pager_pagecount ID +** +** Return the size of the database file. +*/ +static int pager_pagecount( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + char zBuf[100]; + int nPage; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + sqlite3PagerPagecount(pPager, &nPage); + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nPage); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: page_get ID PGNO +** +** Return a pointer to a page from the database. +*/ +static int page_get( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + char zBuf[100]; + DbPage *pPage; + int pgno; + int rc; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID PGNO\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &pgno) ) return TCL_ERROR; + rc = sqlite3PagerSharedLock(pPager); + if( rc==SQLITE_OK ){ + rc = sqlite3PagerGet(pPager, pgno, &pPage); + } + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPage); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: page_lookup ID PGNO +** +** Return a pointer to a page if the page is already in cache. +** If not in cache, return an empty string. +*/ +static int page_lookup( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + char zBuf[100]; + DbPage *pPage; + int pgno; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID PGNO\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &pgno) ) return TCL_ERROR; + pPage = sqlite3PagerLookup(pPager, pgno); + if( pPage ){ + sqlite3_snprintf(sizeof(zBuf),zBuf,"%p",pPage); + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +/* +** Usage: pager_truncate ID PGNO +*/ +static int pager_truncate( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Pager *pPager; + int pgno; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID PGNO\"", 0); + return TCL_ERROR; + } + pPager = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &pgno) ) return TCL_ERROR; + sqlite3PagerTruncateImage(pPager, pgno); + return TCL_OK; +} + + +/* +** Usage: page_unref PAGE +** +** Drop a pointer to a page. +*/ +static int page_unref( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + DbPage *pPage; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PAGE\"", 0); + return TCL_ERROR; + } + pPage = (DbPage *)sqlite3TestTextToPtr(argv[1]); + sqlite3PagerUnref(pPage); + return TCL_OK; +} + +/* +** Usage: page_read PAGE +** +** Return the content of a page +*/ +static int page_read( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + char zBuf[100]; + DbPage *pPage; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PAGE\"", 0); + return TCL_ERROR; + } + pPage = sqlite3TestTextToPtr(argv[1]); + memcpy(zBuf, sqlite3PagerGetData(pPage), sizeof(zBuf)); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: page_number PAGE +** +** Return the page number for a page. +*/ +static int page_number( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + char zBuf[100]; + DbPage *pPage; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PAGE\"", 0); + return TCL_ERROR; + } + pPage = (DbPage *)sqlite3TestTextToPtr(argv[1]); + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", sqlite3PagerPagenumber(pPage)); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: page_write PAGE DATA +** +** Write something into a page. +*/ +static int page_write( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + DbPage *pPage; + char *pData; + int rc; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PAGE DATA\"", 0); + return TCL_ERROR; + } + pPage = (DbPage *)sqlite3TestTextToPtr(argv[1]); + rc = sqlite3PagerWrite(pPage); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + pData = sqlite3PagerGetData(pPage); + strncpy(pData, argv[2], test_pagesize-1); + pData[test_pagesize-1] = 0; + return TCL_OK; +} + +#ifndef SQLITE_OMIT_DISKIO +/* +** Usage: fake_big_file N FILENAME +** +** Write a few bytes at the N megabyte point of FILENAME. This will +** create a large file. If the file was a valid SQLite database, then +** the next time the database is opened, SQLite will begin allocating +** new pages after N. If N is 2096 or bigger, this will test the +** ability of SQLite to write to large files. +*/ +static int fake_big_file( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + sqlite3_vfs *pVfs; + sqlite3_file *fd = 0; + int rc; + int n; + i64 offset; + char *zFile; + int nFile; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " N-MEGABYTES FILE\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[1], &n) ) return TCL_ERROR; + + pVfs = sqlite3_vfs_find(0); + nFile = (int)strlen(argv[2]); + zFile = sqlite3_malloc( nFile+2 ); + if( zFile==0 ) return TCL_ERROR; + memcpy(zFile, argv[2], nFile+1); + zFile[nFile+1] = 0; + rc = sqlite3OsOpenMalloc(pVfs, zFile, &fd, + (SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB), 0 + ); + if( rc ){ + Tcl_AppendResult(interp, "open failed: ", sqlite3ErrName(rc), 0); + sqlite3_free(zFile); + return TCL_ERROR; + } + offset = n; + offset *= 1024*1024; + rc = sqlite3OsWrite(fd, "Hello, World!", 14, offset); + sqlite3OsCloseFree(fd); + sqlite3_free(zFile); + if( rc ){ + Tcl_AppendResult(interp, "write failed: ", sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} +#endif + + +/* +** test_control_pending_byte PENDING_BYTE +** +** Set the PENDING_BYTE using the sqlite3_test_control() interface. +*/ +static int testPendingByte( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int pbyte; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " PENDING-BYTE\"", (void*)0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[1], &pbyte) ) return TCL_ERROR; + rc = sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, pbyte); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** sqlite3BitvecBuiltinTest SIZE PROGRAM +** +** Invoke the SQLITE_TESTCTRL_BITVEC_TEST operator on test_control. +** See comments on sqlite3BitvecBuiltinTest() for additional information. +*/ +static int testBitvecBuiltinTest( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int sz, rc; + int nProg = 0; + int aProg[100]; + const char *z; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " SIZE PROGRAM\"", (void*)0); + } + if( Tcl_GetInt(interp, argv[1], &sz) ) return TCL_ERROR; + z = argv[2]; + while( nProg<99 && *z ){ + while( *z && !sqlite3Isdigit(*z) ){ z++; } + if( *z==0 ) break; + aProg[nProg++] = atoi(z); + while( sqlite3Isdigit(*z) ){ z++; } + } + aProg[nProg] = 0; + rc = sqlite3_test_control(SQLITE_TESTCTRL_BITVEC_TEST, sz, aProg); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest2_Init(Tcl_Interp *interp){ + extern int sqlite3_io_error_persist; + extern int sqlite3_io_error_pending; + extern int sqlite3_io_error_hit; + extern int sqlite3_io_error_hardhit; + extern int sqlite3_diskfull_pending; + extern int sqlite3_diskfull; + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "pager_open", (Tcl_CmdProc*)pager_open }, + { "pager_close", (Tcl_CmdProc*)pager_close }, + { "pager_commit", (Tcl_CmdProc*)pager_commit }, + { "pager_rollback", (Tcl_CmdProc*)pager_rollback }, + { "pager_stmt_begin", (Tcl_CmdProc*)pager_stmt_begin }, + { "pager_stmt_commit", (Tcl_CmdProc*)pager_stmt_commit }, + { "pager_stmt_rollback", (Tcl_CmdProc*)pager_stmt_rollback }, + { "pager_stats", (Tcl_CmdProc*)pager_stats }, + { "pager_pagecount", (Tcl_CmdProc*)pager_pagecount }, + { "page_get", (Tcl_CmdProc*)page_get }, + { "page_lookup", (Tcl_CmdProc*)page_lookup }, + { "page_unref", (Tcl_CmdProc*)page_unref }, + { "page_read", (Tcl_CmdProc*)page_read }, + { "page_write", (Tcl_CmdProc*)page_write }, + { "page_number", (Tcl_CmdProc*)page_number }, + { "pager_truncate", (Tcl_CmdProc*)pager_truncate }, +#ifndef SQLITE_OMIT_DISKIO + { "fake_big_file", (Tcl_CmdProc*)fake_big_file }, +#endif + { "sqlite3BitvecBuiltinTest",(Tcl_CmdProc*)testBitvecBuiltinTest }, + { "sqlite3_test_control_pending_byte", (Tcl_CmdProc*)testPendingByte }, + }; + int i; + for(i=0; i +#include + +extern const char *sqlite3ErrName(int); + +/* +** A bogus sqlite3 connection structure for use in the btree +** tests. +*/ +static sqlite3 sDb; +static int nRefSqlite3 = 0; + +/* +** Usage: btree_open FILENAME NCACHE +** +** Open a new database +*/ +static int btree_open( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int rc, nCache; + char zBuf[100]; + int n; + char *zFilename; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " FILENAME NCACHE FLAGS\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[2], &nCache) ) return TCL_ERROR; + nRefSqlite3++; + if( nRefSqlite3==1 ){ + sDb.pVfs = sqlite3_vfs_find(0); + sDb.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); + sqlite3_mutex_enter(sDb.mutex); + } + n = (int)strlen(argv[1]); + zFilename = sqlite3_malloc( n+2 ); + if( zFilename==0 ) return TCL_ERROR; + memcpy(zFilename, argv[1], n+1); + zFilename[n+1] = 0; + rc = sqlite3BtreeOpen(sDb.pVfs, zFilename, &sDb, &pBt, 0, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MAIN_DB); + sqlite3_free(zFilename); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3BtreeSetCacheSize(pBt, nCache); + sqlite3_snprintf(sizeof(zBuf), zBuf,"%p", pBt); + Tcl_AppendResult(interp, zBuf, 0); + return TCL_OK; +} + +/* +** Usage: btree_close ID +** +** Close the given database. +*/ +static int btree_close( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + rc = sqlite3BtreeClose(pBt); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + nRefSqlite3--; + if( nRefSqlite3==0 ){ + sqlite3_mutex_leave(sDb.mutex); + sqlite3_mutex_free(sDb.mutex); + sDb.mutex = 0; + sDb.pVfs = 0; + } + return TCL_OK; +} + + +/* +** Usage: btree_begin_transaction ID +** +** Start a new transaction +*/ +static int btree_begin_transaction( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int rc; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pBt); + rc = sqlite3BtreeBeginTrans(pBt, 1); + sqlite3BtreeLeave(pBt); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** Usage: btree_pager_stats ID +** +** Returns pager statistics +*/ +static int btree_pager_stats( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int i; + int *a; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + + /* Normally in this file, with a b-tree handle opened using the + ** [btree_open] command it is safe to call sqlite3BtreeEnter() directly. + ** But this function is sometimes called with a btree handle obtained + ** from an open SQLite connection (using [btree_from_db]). In this case + ** we need to obtain the mutex for the controlling SQLite handle before + ** it is safe to call sqlite3BtreeEnter(). + */ + sqlite3_mutex_enter(pBt->db->mutex); + + sqlite3BtreeEnter(pBt); + a = sqlite3PagerStats(sqlite3BtreePager(pBt)); + for(i=0; i<11; i++){ + static char *zName[] = { + "ref", "page", "max", "size", "state", "err", + "hit", "miss", "ovfl", "read", "write" + }; + char zBuf[100]; + Tcl_AppendElement(interp, zName[i]); + sqlite3_snprintf(sizeof(zBuf), zBuf,"%d",a[i]); + Tcl_AppendElement(interp, zBuf); + } + sqlite3BtreeLeave(pBt); + + /* Release the mutex on the SQLite handle that controls this b-tree */ + sqlite3_mutex_leave(pBt->db->mutex); + return TCL_OK; +} + +/* +** Usage: btree_cursor ID TABLENUM WRITEABLE +** +** Create a new cursor. Return the ID for the cursor. +*/ +static int btree_cursor( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int iTable; + BtCursor *pCur; + int rc = SQLITE_OK; + int wrFlag; + char zBuf[30]; + + if( argc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID TABLENUM WRITEABLE\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &iTable) ) return TCL_ERROR; + if( Tcl_GetBoolean(interp, argv[3], &wrFlag) ) return TCL_ERROR; + pCur = (BtCursor *)ckalloc(sqlite3BtreeCursorSize()); + memset(pCur, 0, sqlite3BtreeCursorSize()); + sqlite3BtreeEnter(pBt); +#ifndef SQLITE_OMIT_SHARED_CACHE + rc = sqlite3BtreeLockTable(pBt, iTable, wrFlag); +#endif + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeCursor(pBt, iTable, wrFlag, 0, pCur); + } + sqlite3BtreeLeave(pBt); + if( rc ){ + ckfree((char *)pCur); + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3_snprintf(sizeof(zBuf), zBuf,"%p", pCur); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** Usage: btree_close_cursor ID +** +** Close a cursor opened using btree_cursor. +*/ +static int btree_close_cursor( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + Btree *pBt; + int rc; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + pBt = pCur->pBtree; + sqlite3BtreeEnter(pBt); + rc = sqlite3BtreeCloseCursor(pCur); + sqlite3BtreeLeave(pBt); + ckfree((char *)pCur); + if( rc ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + return SQLITE_OK; +} + +/* +** Usage: btree_next ID +** +** Move the cursor to the next entry in the table. Return 0 on success +** or 1 if the cursor was already on the last entry in the table or if +** the table is empty. +*/ +static int btree_next( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + int rc; + int res = 0; + char zBuf[100]; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pCur->pBtree); + rc = sqlite3BtreeNext(pCur, &res); + sqlite3BtreeLeave(pCur->pBtree); + if( rc ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",res); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** Usage: btree_first ID +** +** Move the cursor to the first entry in the table. Return 0 if the +** cursor was left point to something and 1 if the table is empty. +*/ +static int btree_first( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + int rc; + int res = 0; + char zBuf[100]; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pCur->pBtree); + rc = sqlite3BtreeFirst(pCur, &res); + sqlite3BtreeLeave(pCur->pBtree); + if( rc ){ + Tcl_AppendResult(interp, sqlite3ErrName(rc), 0); + return TCL_ERROR; + } + sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",res); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** Usage: btree_eof ID +** +** Return TRUE if the given cursor is not pointing at a valid entry. +** Return FALSE if the cursor does point to a valid entry. +*/ +static int btree_eof( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + int rc; + char zBuf[50]; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pCur->pBtree); + rc = sqlite3BtreeEof(pCur); + sqlite3BtreeLeave(pCur->pBtree); + sqlite3_snprintf(sizeof(zBuf),zBuf, "%d", rc); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** Usage: btree_payload_size ID +** +** Return the number of bytes of payload +*/ +static int btree_payload_size( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + BtCursor *pCur; + int n2; + u64 n1; + char zBuf[50]; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pCur = sqlite3TestTextToPtr(argv[1]); + sqlite3BtreeEnter(pCur->pBtree); + + /* The cursor may be in "require-seek" state. If this is the case, the + ** call to BtreeDataSize() will fix it. */ + sqlite3BtreeDataSize(pCur, (u32*)&n2); + if( pCur->apPage[pCur->iPage]->intKey ){ + n1 = 0; + }else{ + sqlite3BtreeKeySize(pCur, (i64*)&n1); + } + sqlite3BtreeLeave(pCur->pBtree); + sqlite3_snprintf(sizeof(zBuf),zBuf, "%d", (int)(n1+n2)); + Tcl_AppendResult(interp, zBuf, 0); + return SQLITE_OK; +} + +/* +** usage: varint_test START MULTIPLIER COUNT INCREMENT +** +** This command tests the putVarint() and getVarint() +** routines, both for accuracy and for speed. +** +** An integer is written using putVarint() and read back with +** getVarint() and varified to be unchanged. This repeats COUNT +** times. The first integer is START*MULTIPLIER. Each iteration +** increases the integer by INCREMENT. +** +** This command returns nothing if it works. It returns an error message +** if something goes wrong. +*/ +static int btree_varint_test( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + u32 start, mult, count, incr; + u64 in, out; + int n1, n2, i, j; + unsigned char zBuf[100]; + if( argc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " START MULTIPLIER COUNT INCREMENT\"", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[1], (int*)&start) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[2], (int*)&mult) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[3], (int*)&count) ) return TCL_ERROR; + if( Tcl_GetInt(interp, argv[4], (int*)&incr) ) return TCL_ERROR; + in = start; + in *= mult; + for(i=0; i<(int)count; i++){ + char zErr[200]; + n1 = putVarint(zBuf, in); + if( n1>9 || n1<1 ){ + sprintf(zErr, "putVarint returned %d - should be between 1 and 9", n1); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + n2 = getVarint(zBuf, &out); + if( n1!=n2 ){ + sprintf(zErr, "putVarint returned %d and getVarint returned %d", n1, n2); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + if( in!=out ){ + sprintf(zErr, "Wrote 0x%016llx and got back 0x%016llx", in, out); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + if( (in & 0xffffffff)==in ){ + u32 out32; + n2 = getVarint32(zBuf, out32); + out = out32; + if( n1!=n2 ){ + sprintf(zErr, "putVarint returned %d and GetVarint32 returned %d", + n1, n2); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + if( in!=out ){ + sprintf(zErr, "Wrote 0x%016llx and got back 0x%016llx from GetVarint32", + in, out); + Tcl_AppendResult(interp, zErr, 0); + return TCL_ERROR; + } + } + + /* In order to get realistic timings, run getVarint 19 more times. + ** This is because getVarint is called about 20 times more often + ** than putVarint. + */ + for(j=0; j<19; j++){ + getVarint(zBuf, &out); + } + in += incr; + } + return TCL_OK; +} + +/* +** usage: btree_from_db DB-HANDLE +** +** This command returns the btree handle for the main database associated +** with the database-handle passed as the argument. Example usage: +** +** sqlite3 db test.db +** set bt [btree_from_db db] +*/ +static int btree_from_db( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + char zBuf[100]; + Tcl_CmdInfo info; + sqlite3 *db; + Btree *pBt; + int iDb = 0; + + if( argc!=2 && argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " DB-HANDLE ?N?\"", 0); + return TCL_ERROR; + } + + if( 1!=Tcl_GetCommandInfo(interp, argv[1], &info) ){ + Tcl_AppendResult(interp, "No such db-handle: \"", argv[1], "\"", 0); + return TCL_ERROR; + } + if( argc==3 ){ + iDb = atoi(argv[2]); + } + + db = *((sqlite3 **)info.objClientData); + assert( db ); + + pBt = db->aDb[iDb].pBt; + sqlite3_snprintf(sizeof(zBuf), zBuf, "%p", pBt); + Tcl_SetResult(interp, zBuf, TCL_VOLATILE); + return TCL_OK; +} + +/* +** Usage: btree_ismemdb ID +** +** Return true if the B-Tree is in-memory. +*/ +static int btree_ismemdb( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + Btree *pBt; + int res; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + sqlite3_mutex_enter(pBt->db->mutex); + sqlite3BtreeEnter(pBt); + res = sqlite3PagerIsMemdb(sqlite3BtreePager(pBt)); + sqlite3BtreeLeave(pBt); + sqlite3_mutex_leave(pBt->db->mutex); + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(res)); + return SQLITE_OK; +} + +/* +** usage: btree_set_cache_size ID NCACHE +** +** Set the size of the cache used by btree $ID. +*/ +static int btree_set_cache_size( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int nCache; + Btree *pBt; + + if( argc!=3 ){ + Tcl_AppendResult( + interp, "wrong # args: should be \"", argv[0], " BT NCACHE\"", 0); + return TCL_ERROR; + } + pBt = sqlite3TestTextToPtr(argv[1]); + if( Tcl_GetInt(interp, argv[2], &nCache) ) return TCL_ERROR; + + sqlite3_mutex_enter(pBt->db->mutex); + sqlite3BtreeEnter(pBt); + sqlite3BtreeSetCacheSize(pBt, nCache); + sqlite3BtreeLeave(pBt); + sqlite3_mutex_leave(pBt->db->mutex); + return TCL_OK; +} + + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest3_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "btree_open", (Tcl_CmdProc*)btree_open }, + { "btree_close", (Tcl_CmdProc*)btree_close }, + { "btree_begin_transaction", (Tcl_CmdProc*)btree_begin_transaction }, + { "btree_pager_stats", (Tcl_CmdProc*)btree_pager_stats }, + { "btree_cursor", (Tcl_CmdProc*)btree_cursor }, + { "btree_close_cursor", (Tcl_CmdProc*)btree_close_cursor }, + { "btree_next", (Tcl_CmdProc*)btree_next }, + { "btree_eof", (Tcl_CmdProc*)btree_eof }, + { "btree_payload_size", (Tcl_CmdProc*)btree_payload_size }, + { "btree_first", (Tcl_CmdProc*)btree_first }, + { "btree_varint_test", (Tcl_CmdProc*)btree_varint_test }, + { "btree_from_db", (Tcl_CmdProc*)btree_from_db }, + { "btree_ismemdb", (Tcl_CmdProc*)btree_ismemdb }, + { "btree_set_cache_size", (Tcl_CmdProc*)btree_set_cache_size } + }; + int i; + + for(i=0; i +#include +#include +#include +#include + +extern const char *sqlite3ErrName(int); + +/* +** Each thread is controlled by an instance of the following +** structure. +*/ +typedef struct Thread Thread; +struct Thread { + /* The first group of fields are writable by the master and read-only + ** to the thread. */ + char *zFilename; /* Name of database file */ + void (*xOp)(Thread*); /* next operation to do */ + char *zArg; /* argument usable by xOp */ + int opnum; /* Operation number */ + int busy; /* True if this thread is in use */ + + /* The next group of fields are writable by the thread but read-only to the + ** master. */ + int completed; /* Number of operations completed */ + sqlite3 *db; /* Open database */ + sqlite3_stmt *pStmt; /* Pending operation */ + char *zErr; /* operation error */ + char *zStaticErr; /* Static error message */ + int rc; /* operation return code */ + int argc; /* number of columns in result */ + const char *argv[100]; /* result columns */ + const char *colv[100]; /* result column names */ +}; + +/* +** There can be as many as 26 threads running at once. Each is named +** by a capital letter: A, B, C, ..., Y, Z. +*/ +#define N_THREAD 26 +static Thread threadset[N_THREAD]; + + +/* +** The main loop for a thread. Threads use busy waiting. +*/ +static void *thread_main(void *pArg){ + Thread *p = (Thread*)pArg; + if( p->db ){ + sqlite3_close(p->db); + } + sqlite3_open(p->zFilename, &p->db); + if( SQLITE_OK!=sqlite3_errcode(p->db) ){ + p->zErr = strdup(sqlite3_errmsg(p->db)); + sqlite3_close(p->db); + p->db = 0; + } + p->pStmt = 0; + p->completed = 1; + while( p->opnum<=p->completed ) sched_yield(); + while( p->xOp ){ + if( p->zErr && p->zErr!=p->zStaticErr ){ + sqlite3_free(p->zErr); + p->zErr = 0; + } + (*p->xOp)(p); + p->completed++; + while( p->opnum<=p->completed ) sched_yield(); + } + if( p->pStmt ){ + sqlite3_finalize(p->pStmt); + p->pStmt = 0; + } + if( p->db ){ + sqlite3_close(p->db); + p->db = 0; + } + if( p->zErr && p->zErr!=p->zStaticErr ){ + sqlite3_free(p->zErr); + p->zErr = 0; + } + p->completed++; +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_thread_cleanup(); +#endif + return 0; +} + +/* +** Get a thread ID which is an upper case letter. Return the index. +** If the argument is not a valid thread ID put an error message in +** the interpreter and return -1. +*/ +static int parse_thread_id(Tcl_Interp *interp, const char *zArg){ + if( zArg==0 || zArg[0]==0 || zArg[1]!=0 || !isupper((unsigned char)zArg[0]) ){ + Tcl_AppendResult(interp, "thread ID must be an upper case letter", 0); + return -1; + } + return zArg[0] - 'A'; +} + +/* +** Usage: thread_create NAME FILENAME +** +** NAME should be an upper case letter. Start the thread running with +** an open connection to the given database. +*/ +static int tcl_thread_create( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + pthread_t x; + int rc; + + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID FILENAME", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( threadset[i].busy ){ + Tcl_AppendResult(interp, "thread ", argv[1], " is already running", 0); + return TCL_ERROR; + } + threadset[i].busy = 1; + sqlite3_free(threadset[i].zFilename); + threadset[i].zFilename = sqlite3_mprintf("%s", argv[2]); + threadset[i].opnum = 1; + threadset[i].completed = 0; + rc = pthread_create(&x, 0, thread_main, &threadset[i]); + if( rc ){ + Tcl_AppendResult(interp, "failed to create the thread", 0); + sqlite3_free(threadset[i].zFilename); + threadset[i].busy = 0; + return TCL_ERROR; + } + pthread_detach(x); + return TCL_OK; +} + +/* +** Wait for a thread to reach its idle state. +*/ +static void thread_wait(Thread *p){ + while( p->opnum>p->completed ) sched_yield(); +} + +/* +** Usage: thread_wait ID +** +** Wait on thread ID to reach its idle state. +*/ +static int tcl_thread_wait( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + return TCL_OK; +} + +/* +** Stop a thread. +*/ +static void stop_thread(Thread *p){ + thread_wait(p); + p->xOp = 0; + p->opnum++; + thread_wait(p); + sqlite3_free(p->zArg); + p->zArg = 0; + sqlite3_free(p->zFilename); + p->zFilename = 0; + p->busy = 0; +} + +/* +** Usage: thread_halt ID +** +** Cause a thread to shut itself down. Wait for the shutdown to be +** completed. If ID is "*" then stop all threads. +*/ +static int tcl_thread_halt( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + if( argv[1][0]=='*' && argv[1][1]==0 ){ + for(i=0; i=threadset[i].argc ){ + Tcl_AppendResult(interp, "column number out of range", 0); + return TCL_ERROR; + } + Tcl_AppendResult(interp, threadset[i].argv[n], 0); + return TCL_OK; +} + +/* +** Usage: thread_colname ID N +** +** Wait on the most recent thread_step to complete, then return the +** name of the N-th columns in the result set. +*/ +static int tcl_thread_colname( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + int n; + + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID N", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR; + thread_wait(&threadset[i]); + if( n<0 || n>=threadset[i].argc ){ + Tcl_AppendResult(interp, "column number out of range", 0); + return TCL_ERROR; + } + Tcl_AppendResult(interp, threadset[i].colv[n], 0); + return TCL_OK; +} + +/* +** Usage: thread_result ID +** +** Wait on the most recent operation to complete, then return the +** result code from that operation. +*/ +static int tcl_thread_result( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + const char *zName; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + zName = sqlite3ErrName(threadset[i].rc); + Tcl_AppendResult(interp, zName, 0); + return TCL_OK; +} + +/* +** Usage: thread_error ID +** +** Wait on the most recent operation to complete, then return the +** error string. +*/ +static int tcl_thread_error( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + Tcl_AppendResult(interp, threadset[i].zErr, 0); + return TCL_OK; +} + +/* +** This procedure runs in the thread to compile an SQL statement. +*/ +static void do_compile(Thread *p){ + if( p->db==0 ){ + p->zErr = p->zStaticErr = "no database is open"; + p->rc = SQLITE_ERROR; + return; + } + if( p->pStmt ){ + sqlite3_finalize(p->pStmt); + p->pStmt = 0; + } + p->rc = sqlite3_prepare(p->db, p->zArg, -1, &p->pStmt, 0); +} + +/* +** Usage: thread_compile ID SQL +** +** Compile a new virtual machine. +*/ +static int tcl_thread_compile( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID SQL", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + threadset[i].xOp = do_compile; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = sqlite3_mprintf("%s", argv[2]); + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to step the virtual machine. +*/ +static void do_step(Thread *p){ + int i; + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_step(p->pStmt); + if( p->rc==SQLITE_ROW ){ + p->argc = sqlite3_column_count(p->pStmt); + for(i=0; ipStmt); i++){ + p->argv[i] = (char*)sqlite3_column_text(p->pStmt, i); + } + for(i=0; iargc; i++){ + p->colv[i] = sqlite3_column_name(p->pStmt, i); + } + } +} + +/* +** Usage: thread_step ID +** +** Advance the virtual machine by one step +*/ +static int tcl_thread_step( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + threadset[i].xOp = do_step; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to finalize a virtual machine. +*/ +static void do_finalize(Thread *p){ + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_finalize(p->pStmt); + p->pStmt = 0; +} + +/* +** Usage: thread_finalize ID +** +** Finalize the virtual machine. +*/ +static int tcl_thread_finalize( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + threadset[i].xOp = do_finalize; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = 0; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** Usage: thread_swap ID ID +** +** Interchange the sqlite* pointer between two threads. +*/ +static int tcl_thread_swap( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i, j; + sqlite3 *temp; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID1 ID2", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + j = parse_thread_id(interp, argv[2]); + if( j<0 ) return TCL_ERROR; + if( !threadset[j].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[j]); + temp = threadset[i].db; + threadset[i].db = threadset[j].db; + threadset[j].db = temp; + return TCL_OK; +} + +/* +** Usage: thread_db_get ID +** +** Return the database connection pointer for the given thread. Then +** remove the pointer from the thread itself. Afterwards, the thread +** can be stopped and the connection can be used by the main thread. +*/ +static int tcl_thread_db_get( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + char zBuf[100]; + extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*); + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + sqlite3TestMakePointerStr(interp, zBuf, threadset[i].db); + threadset[i].db = 0; + Tcl_AppendResult(interp, zBuf, (char*)0); + return TCL_OK; +} + +/* +** Usage: thread_db_put ID DB +** +*/ +static int tcl_thread_db_put( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*); + extern void *sqlite3TestTextToPtr(const char *); + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID DB", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + assert( !threadset[i].db ); + threadset[i].db = (sqlite3*)sqlite3TestTextToPtr(argv[2]); + return TCL_OK; +} + +/* +** Usage: thread_stmt_get ID +** +** Return the database stmt pointer for the given thread. Then +** remove the pointer from the thread itself. +*/ +static int tcl_thread_stmt_get( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + char zBuf[100]; + extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*); + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_thread_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + thread_wait(&threadset[i]); + sqlite3TestMakePointerStr(interp, zBuf, threadset[i].pStmt); + threadset[i].pStmt = 0; + Tcl_AppendResult(interp, zBuf, (char*)0); + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest4_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "thread_create", (Tcl_CmdProc*)tcl_thread_create }, + { "thread_wait", (Tcl_CmdProc*)tcl_thread_wait }, + { "thread_halt", (Tcl_CmdProc*)tcl_thread_halt }, + { "thread_argc", (Tcl_CmdProc*)tcl_thread_argc }, + { "thread_argv", (Tcl_CmdProc*)tcl_thread_argv }, + { "thread_colname", (Tcl_CmdProc*)tcl_thread_colname }, + { "thread_result", (Tcl_CmdProc*)tcl_thread_result }, + { "thread_error", (Tcl_CmdProc*)tcl_thread_error }, + { "thread_compile", (Tcl_CmdProc*)tcl_thread_compile }, + { "thread_step", (Tcl_CmdProc*)tcl_thread_step }, + { "thread_finalize", (Tcl_CmdProc*)tcl_thread_finalize }, + { "thread_swap", (Tcl_CmdProc*)tcl_thread_swap }, + { "thread_db_get", (Tcl_CmdProc*)tcl_thread_db_get }, + { "thread_db_put", (Tcl_CmdProc*)tcl_thread_db_put }, + { "thread_stmt_get", (Tcl_CmdProc*)tcl_thread_stmt_get }, + }; + int i; + + for(i=0; i +#include + +/* +** The first argument is a TCL UTF-8 string. Return the byte array +** object with the encoded representation of the string, including +** the NULL terminator. +*/ +static int binarize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int len; + char *bytes; + Tcl_Obj *pRet; + assert(objc==2); + + bytes = Tcl_GetStringFromObj(objv[1], &len); + pRet = Tcl_NewByteArrayObj((u8*)bytes, len+1); + Tcl_SetObjResult(interp, pRet); + return TCL_OK; +} + +/* +** Usage: test_value_overhead . +** +** This routine is used to test the overhead of calls to +** sqlite3_value_text(), on a value that contains a UTF-8 string. The idea +** is to figure out whether or not it is a problem to use sqlite3_value +** structures with collation sequence functions. +** +** If is 0, then the calls to sqlite3_value_text() are not +** actually made. +*/ +static int test_value_overhead( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int do_calls; + int repeat_count; + int i; + Mem val; + + if( objc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), " ", 0); + return TCL_ERROR; + } + + if( Tcl_GetIntFromObj(interp, objv[1], &repeat_count) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &do_calls) ) return TCL_ERROR; + + val.flags = MEM_Str|MEM_Term|MEM_Static; + val.z = "hello world"; + val.type = SQLITE_TEXT; + val.enc = SQLITE_UTF8; + + for(i=0; izName; pEnc++){ + if( 0==sqlite3StrICmp(z, pEnc->zName) ){ + break; + } + } + if( !pEnc->enc ){ + Tcl_AppendResult(interp, "No such encoding: ", z, 0); + } + if( pEnc->enc==SQLITE_UTF16 ){ + return SQLITE_UTF16NATIVE; + } + return pEnc->enc; +} + +/* +** Usage: test_translate ?? +** +*/ +static int test_translate( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + u8 enc_from; + u8 enc_to; + sqlite3_value *pVal; + + char *z; + int len; + void (*xDel)(void *p) = SQLITE_STATIC; + + if( objc!=4 && objc!=5 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetStringFromObj(objv[0], 0), + " ", 0 + ); + return TCL_ERROR; + } + if( objc==5 ){ + xDel = sqlite3_free; + } + + enc_from = name_to_enc(interp, objv[2]); + if( !enc_from ) return TCL_ERROR; + enc_to = name_to_enc(interp, objv[3]); + if( !enc_to ) return TCL_ERROR; + + pVal = sqlite3ValueNew(0); + + if( enc_from==SQLITE_UTF8 ){ + z = Tcl_GetString(objv[1]); + if( objc==5 ){ + z = sqlite3_mprintf("%s", z); + } + sqlite3ValueSetStr(pVal, -1, z, enc_from, xDel); + }else{ + z = (char*)Tcl_GetByteArrayFromObj(objv[1], &len); + if( objc==5 ){ + char *zTmp = z; + z = sqlite3_malloc(len); + memcpy(z, zTmp, len); + } + sqlite3ValueSetStr(pVal, -1, z, enc_from, xDel); + } + + z = (char *)sqlite3ValueText(pVal, enc_to); + len = sqlite3ValueBytes(pVal, enc_to) + (enc_to==SQLITE_UTF8?1:2); + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj((u8*)z, len)); + + sqlite3ValueFree(pVal); + + return TCL_OK; +} + +/* +** Usage: translate_selftest +** +** Call sqlite3UtfSelfTest() to run the internal tests for unicode +** translation. If there is a problem an assert() will fail. +**/ +void sqlite3UtfSelfTest(void); +static int test_translate_selftest( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_UTF16 + sqlite3UtfSelfTest(); +#endif + return SQLITE_OK; +} + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest5_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aCmd[] = { + { "binarize", (Tcl_ObjCmdProc*)binarize }, + { "test_value_overhead", (Tcl_ObjCmdProc*)test_value_overhead }, + { "test_translate", (Tcl_ObjCmdProc*)test_translate }, + { "translate_selftest", (Tcl_ObjCmdProc*)test_translate_selftest}, + }; + int i; + for(i=0; iflags&SQLITE_OPEN_MAIN_DB) ){ + iSkip = 512; + } + if( (iAmt-iSkip)>0 ){ + rc = sqlite3OsWrite(p->pRealFile, &z[iSkip], (int)(iAmt-iSkip), iOff+iSkip); + } + return rc; +} + +/* +** Flush the write-list as if xSync() had been called on file handle +** pFile. If isCrash is true, simulate a crash. +*/ +static int writeListSync(CrashFile *pFile, int isCrash){ + int rc = SQLITE_OK; + int iDc = g.iDeviceCharacteristics; + + WriteBuffer *pWrite; + WriteBuffer **ppPtr; + + /* If this is not a crash simulation, set pFinal to point to the + ** last element of the write-list that is associated with file handle + ** pFile. + ** + ** If this is a crash simulation, set pFinal to an arbitrarily selected + ** element of the write-list. + */ + WriteBuffer *pFinal = 0; + if( !isCrash ){ + for(pWrite=g.pWriteList; pWrite; pWrite=pWrite->pNext){ + if( pWrite->pFile==pFile ){ + pFinal = pWrite; + } + } + }else if( iDc&(SQLITE_IOCAP_SEQUENTIAL|SQLITE_IOCAP_SAFE_APPEND) ){ + int nWrite = 0; + int iFinal; + for(pWrite=g.pWriteList; pWrite; pWrite=pWrite->pNext) nWrite++; + sqlite3_randomness(sizeof(int), &iFinal); + iFinal = ((iFinal<0)?-1*iFinal:iFinal)%nWrite; + for(pWrite=g.pWriteList; iFinal>0; pWrite=pWrite->pNext) iFinal--; + pFinal = pWrite; + } + +#ifdef TRACE_CRASHTEST + printf("Sync %s (is %s crash)\n", pFile->zName, (isCrash?"a":"not a")); +#endif + + ppPtr = &g.pWriteList; + for(pWrite=*ppPtr; rc==SQLITE_OK && pWrite; pWrite=*ppPtr){ + sqlite3_file *pRealFile = pWrite->pFile->pRealFile; + + /* (eAction==1) -> write block out normally, + ** (eAction==2) -> do nothing, + ** (eAction==3) -> trash sectors. + */ + int eAction = 0; + if( !isCrash ){ + eAction = 2; + if( (pWrite->pFile==pFile || iDc&SQLITE_IOCAP_SEQUENTIAL) ){ + eAction = 1; + } + }else{ + char random; + sqlite3_randomness(1, &random); + + /* Do not select option 3 (sector trashing) if the IOCAP_ATOMIC flag + ** is set or this is an OsTruncate(), not an Oswrite(). + */ + if( (iDc&SQLITE_IOCAP_ATOMIC) || (pWrite->zBuf==0) ){ + random &= 0x01; + } + + /* If IOCAP_SEQUENTIAL is set and this is not the final entry + ** in the truncated write-list, always select option 1 (write + ** out correctly). + */ + if( (iDc&SQLITE_IOCAP_SEQUENTIAL && pWrite!=pFinal) ){ + random = 0; + } + + /* If IOCAP_SAFE_APPEND is set and this OsWrite() operation is + ** an append (first byte of the written region is 1 byte past the + ** current EOF), always select option 1 (write out correctly). + */ + if( iDc&SQLITE_IOCAP_SAFE_APPEND && pWrite->zBuf ){ + i64 iSize; + sqlite3OsFileSize(pRealFile, &iSize); + if( iSize==pWrite->iOffset ){ + random = 0; + } + } + + if( (random&0x06)==0x06 ){ + eAction = 3; + }else{ + eAction = ((random&0x01)?2:1); + } + } + + switch( eAction ){ + case 1: { /* Write out correctly */ + if( pWrite->zBuf ){ + rc = writeDbFile( + pWrite->pFile, pWrite->zBuf, pWrite->nBuf, pWrite->iOffset + ); + }else{ + rc = sqlite3OsTruncate(pRealFile, pWrite->iOffset); + } + *ppPtr = pWrite->pNext; +#ifdef TRACE_CRASHTEST + if( isCrash ){ + printf("Writing %d bytes @ %d (%s)\n", + pWrite->nBuf, (int)pWrite->iOffset, pWrite->pFile->zName + ); + } +#endif + crash_free(pWrite); + break; + } + case 2: { /* Do nothing */ + ppPtr = &pWrite->pNext; +#ifdef TRACE_CRASHTEST + if( isCrash ){ + printf("Omiting %d bytes @ %d (%s)\n", + pWrite->nBuf, (int)pWrite->iOffset, pWrite->pFile->zName + ); + } +#endif + break; + } + case 3: { /* Trash sectors */ + u8 *zGarbage; + int iFirst = (int)(pWrite->iOffset/g.iSectorSize); + int iLast = (int)((pWrite->iOffset+pWrite->nBuf-1)/g.iSectorSize); + + assert(pWrite->zBuf); + +#ifdef TRACE_CRASHTEST + printf("Trashing %d sectors @ %lld (sector %d) (%s)\n", + 1+iLast-iFirst, pWrite->iOffset, iFirst, pWrite->pFile->zName + ); +#endif + + zGarbage = crash_malloc(g.iSectorSize); + if( zGarbage ){ + sqlite3_int64 i; + for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){ + sqlite3_randomness(g.iSectorSize, zGarbage); + rc = writeDbFile( + pWrite->pFile, zGarbage, g.iSectorSize, i*g.iSectorSize + ); + } + crash_free(zGarbage); + }else{ + rc = SQLITE_NOMEM; + } + + ppPtr = &pWrite->pNext; + break; + } + + default: + assert(!"Cannot happen"); + } + + if( pWrite==pFinal ) break; + } + + if( rc==SQLITE_OK && isCrash ){ + exit(-1); + } + + for(pWrite=g.pWriteList; pWrite && pWrite->pNext; pWrite=pWrite->pNext); + g.pWriteListEnd = pWrite; + + return rc; +} + +/* +** Add an entry to the end of the write-list. +*/ +static int writeListAppend( + sqlite3_file *pFile, + sqlite3_int64 iOffset, + const u8 *zBuf, + int nBuf +){ + WriteBuffer *pNew; + + assert((zBuf && nBuf) || (!nBuf && !zBuf)); + + pNew = (WriteBuffer *)crash_malloc(sizeof(WriteBuffer) + nBuf); + if( pNew==0 ){ + fprintf(stderr, "out of memory in the crash simulator\n"); + } + memset(pNew, 0, sizeof(WriteBuffer)+nBuf); + pNew->iOffset = iOffset; + pNew->nBuf = nBuf; + pNew->pFile = (CrashFile *)pFile; + if( zBuf ){ + pNew->zBuf = (u8 *)&pNew[1]; + memcpy(pNew->zBuf, zBuf, nBuf); + } + + if( g.pWriteList ){ + assert(g.pWriteListEnd); + g.pWriteListEnd->pNext = pNew; + }else{ + g.pWriteList = pNew; + } + g.pWriteListEnd = pNew; + + return SQLITE_OK; +} + +/* +** Close a crash-file. +*/ +static int cfClose(sqlite3_file *pFile){ + CrashFile *pCrash = (CrashFile *)pFile; + writeListSync(pCrash, 0); + sqlite3OsClose(pCrash->pRealFile); + return SQLITE_OK; +} + +/* +** Read data from a crash-file. +*/ +static int cfRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + CrashFile *pCrash = (CrashFile *)pFile; + + /* Check the file-size to see if this is a short-read */ + if( pCrash->iSize<(iOfst+iAmt) ){ + return SQLITE_IOERR_SHORT_READ; + } + + memcpy(zBuf, &pCrash->zData[iOfst], iAmt); + return SQLITE_OK; +} + +/* +** Write data to a crash-file. +*/ +static int cfWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + CrashFile *pCrash = (CrashFile *)pFile; + if( iAmt+iOfst>pCrash->iSize ){ + pCrash->iSize = (int)(iAmt+iOfst); + } + while( pCrash->iSize>pCrash->nData ){ + u8 *zNew; + int nNew = (pCrash->nData*2) + 4096; + zNew = crash_realloc(pCrash->zData, nNew); + if( !zNew ){ + return SQLITE_NOMEM; + } + memset(&zNew[pCrash->nData], 0, nNew-pCrash->nData); + pCrash->nData = nNew; + pCrash->zData = zNew; + } + memcpy(&pCrash->zData[iOfst], zBuf, iAmt); + return writeListAppend(pFile, iOfst, zBuf, iAmt); +} + +/* +** Truncate a crash-file. +*/ +static int cfTruncate(sqlite3_file *pFile, sqlite_int64 size){ + CrashFile *pCrash = (CrashFile *)pFile; + assert(size>=0); + if( pCrash->iSize>size ){ + pCrash->iSize = (int)size; + } + return writeListAppend(pFile, size, 0, 0); +} + +/* +** Sync a crash-file. +*/ +static int cfSync(sqlite3_file *pFile, int flags){ + CrashFile *pCrash = (CrashFile *)pFile; + int isCrash = 0; + + const char *zName = pCrash->zName; + const char *zCrashFile = g.zCrashFile; + int nName = (int)strlen(zName); + int nCrashFile = (int)strlen(zCrashFile); + + if( nCrashFile>0 && zCrashFile[nCrashFile-1]=='*' ){ + nCrashFile--; + if( nName>nCrashFile ) nName = nCrashFile; + } + +#ifdef TRACE_CRASHTEST + printf("cfSync(): nName = %d, nCrashFile = %d, zName = %s, zCrashFile = %s\n", + nName, nCrashFile, zName, zCrashFile); +#endif + + if( nName==nCrashFile && 0==memcmp(zName, zCrashFile, nName) ){ +#ifdef TRACE_CRASHTEST + printf("cfSync(): name matched, g.iCrash = %d\n", g.iCrash); +#endif + if( (--g.iCrash)==0 ) isCrash = 1; + } + + return writeListSync(pCrash, isCrash); +} + +/* +** Return the current file-size of the crash-file. +*/ +static int cfFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + CrashFile *pCrash = (CrashFile *)pFile; + *pSize = (i64)pCrash->iSize; + return SQLITE_OK; +} + +/* +** Calls related to file-locks are passed on to the real file handle. +*/ +static int cfLock(sqlite3_file *pFile, int eLock){ + return sqlite3OsLock(((CrashFile *)pFile)->pRealFile, eLock); +} +static int cfUnlock(sqlite3_file *pFile, int eLock){ + return sqlite3OsUnlock(((CrashFile *)pFile)->pRealFile, eLock); +} +static int cfCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + return sqlite3OsCheckReservedLock(((CrashFile *)pFile)->pRealFile, pResOut); +} +static int cfFileControl(sqlite3_file *pFile, int op, void *pArg){ + if( op==SQLITE_FCNTL_SIZE_HINT ){ + CrashFile *pCrash = (CrashFile *)pFile; + i64 nByte = *(i64 *)pArg; + if( nByte>pCrash->iSize ){ + if( SQLITE_OK==writeListAppend(pFile, nByte, 0, 0) ){ + pCrash->iSize = (int)nByte; + } + } + return SQLITE_OK; + } + return sqlite3OsFileControl(((CrashFile *)pFile)->pRealFile, op, pArg); +} + +/* +** The xSectorSize() and xDeviceCharacteristics() functions return +** the global values configured by the [sqlite_crashparams] tcl +* interface. +*/ +static int cfSectorSize(sqlite3_file *pFile){ + return g.iSectorSize; +} +static int cfDeviceCharacteristics(sqlite3_file *pFile){ + return g.iDeviceCharacteristics; +} + +/* +** Pass-throughs for WAL support. +*/ +static int cfShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ + return sqlite3OsShmLock(((CrashFile*)pFile)->pRealFile, ofst, n, flags); +} +static void cfShmBarrier(sqlite3_file *pFile){ + sqlite3OsShmBarrier(((CrashFile*)pFile)->pRealFile); +} +static int cfShmUnmap(sqlite3_file *pFile, int delFlag){ + return sqlite3OsShmUnmap(((CrashFile*)pFile)->pRealFile, delFlag); +} +static int cfShmMap( + sqlite3_file *pFile, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int sz, /* Size of regions */ + int w, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + return sqlite3OsShmMap(((CrashFile*)pFile)->pRealFile, iRegion, sz, w, pp); +} + +static const sqlite3_io_methods CrashFileVtab = { + 2, /* iVersion */ + cfClose, /* xClose */ + cfRead, /* xRead */ + cfWrite, /* xWrite */ + cfTruncate, /* xTruncate */ + cfSync, /* xSync */ + cfFileSize, /* xFileSize */ + cfLock, /* xLock */ + cfUnlock, /* xUnlock */ + cfCheckReservedLock, /* xCheckReservedLock */ + cfFileControl, /* xFileControl */ + cfSectorSize, /* xSectorSize */ + cfDeviceCharacteristics, /* xDeviceCharacteristics */ + cfShmMap, /* xShmMap */ + cfShmLock, /* xShmLock */ + cfShmBarrier, /* xShmBarrier */ + cfShmUnmap /* xShmUnmap */ +}; + +/* +** Application data for the crash VFS +*/ +struct crashAppData { + sqlite3_vfs *pOrig; /* Wrapped vfs structure */ +}; + +/* +** Open a crash-file file handle. +** +** The caller will have allocated pVfs->szOsFile bytes of space +** at pFile. This file uses this space for the CrashFile structure +** and allocates space for the "real" file structure using +** sqlite3_malloc(). The assumption here is (pVfs->szOsFile) is +** equal or greater than sizeof(CrashFile). +*/ +static int cfOpen( + sqlite3_vfs *pCfVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + int rc; + CrashFile *pWrapper = (CrashFile *)pFile; + sqlite3_file *pReal = (sqlite3_file*)&pWrapper[1]; + + memset(pWrapper, 0, sizeof(CrashFile)); + rc = sqlite3OsOpen(pVfs, zName, pReal, flags, pOutFlags); + + if( rc==SQLITE_OK ){ + i64 iSize; + pWrapper->pMethod = &CrashFileVtab; + pWrapper->zName = (char *)zName; + pWrapper->pRealFile = pReal; + rc = sqlite3OsFileSize(pReal, &iSize); + pWrapper->iSize = (int)iSize; + pWrapper->flags = flags; + } + if( rc==SQLITE_OK ){ + pWrapper->nData = (4096 + pWrapper->iSize); + pWrapper->zData = crash_malloc(pWrapper->nData); + if( pWrapper->zData ){ + /* os_unix.c contains an assert() that fails if the caller attempts + ** to read data from the 512-byte locking region of a file opened + ** with the SQLITE_OPEN_MAIN_DB flag. This region of a database file + ** never contains valid data anyhow. So avoid doing such a read here. + ** + ** UPDATE: It also contains an assert() verifying that each call + ** to the xRead() method reads less than 128KB of data. + */ + const int isDb = (flags&SQLITE_OPEN_MAIN_DB); + i64 iOff; + + memset(pWrapper->zData, 0, pWrapper->nData); + for(iOff=0; iOffiSize; iOff += 512){ + int nRead = pWrapper->iSize - (int)iOff; + if( nRead>512 ) nRead = 512; + if( isDb && iOff==PENDING_BYTE ) continue; + rc = sqlite3OsRead(pReal, &pWrapper->zData[iOff], nRead, iOff); + } + }else{ + rc = SQLITE_NOMEM; + } + } + if( rc!=SQLITE_OK && pWrapper->pMethod ){ + sqlite3OsClose(pFile); + } + return rc; +} + +static int cfDelete(sqlite3_vfs *pCfVfs, const char *zPath, int dirSync){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xDelete(pVfs, zPath, dirSync); +} +static int cfAccess( + sqlite3_vfs *pCfVfs, + const char *zPath, + int flags, + int *pResOut +){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xAccess(pVfs, zPath, flags, pResOut); +} +static int cfFullPathname( + sqlite3_vfs *pCfVfs, + const char *zPath, + int nPathOut, + char *zPathOut +){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); +} +static void *cfDlOpen(sqlite3_vfs *pCfVfs, const char *zPath){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xDlOpen(pVfs, zPath); +} +static void cfDlError(sqlite3_vfs *pCfVfs, int nByte, char *zErrMsg){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + pVfs->xDlError(pVfs, nByte, zErrMsg); +} +static void (*cfDlSym(sqlite3_vfs *pCfVfs, void *pH, const char *zSym))(void){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xDlSym(pVfs, pH, zSym); +} +static void cfDlClose(sqlite3_vfs *pCfVfs, void *pHandle){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + pVfs->xDlClose(pVfs, pHandle); +} +static int cfRandomness(sqlite3_vfs *pCfVfs, int nByte, char *zBufOut){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xRandomness(pVfs, nByte, zBufOut); +} +static int cfSleep(sqlite3_vfs *pCfVfs, int nMicro){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xSleep(pVfs, nMicro); +} +static int cfCurrentTime(sqlite3_vfs *pCfVfs, double *pTimeOut){ + sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; + return pVfs->xCurrentTime(pVfs, pTimeOut); +} + +static int processDevSymArgs( + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[], + int *piDeviceChar, + int *piSectorSize +){ + struct DeviceFlag { + char *zName; + int iValue; + } aFlag[] = { + { "atomic", SQLITE_IOCAP_ATOMIC }, + { "atomic512", SQLITE_IOCAP_ATOMIC512 }, + { "atomic1k", SQLITE_IOCAP_ATOMIC1K }, + { "atomic2k", SQLITE_IOCAP_ATOMIC2K }, + { "atomic4k", SQLITE_IOCAP_ATOMIC4K }, + { "atomic8k", SQLITE_IOCAP_ATOMIC8K }, + { "atomic16k", SQLITE_IOCAP_ATOMIC16K }, + { "atomic32k", SQLITE_IOCAP_ATOMIC32K }, + { "atomic64k", SQLITE_IOCAP_ATOMIC64K }, + { "sequential", SQLITE_IOCAP_SEQUENTIAL }, + { "safe_append", SQLITE_IOCAP_SAFE_APPEND }, + { "powersafe_overwrite", SQLITE_IOCAP_POWERSAFE_OVERWRITE }, + { 0, 0 } + }; + + int i; + int iDc = 0; + int iSectorSize = 0; + int setSectorsize = 0; + int setDeviceChar = 0; + + for(i=0; i11 || nOpt<2 || strncmp("-sectorsize", zOpt, nOpt)) + && (nOpt>16 || nOpt<2 || strncmp("-characteristics", zOpt, nOpt)) + ){ + Tcl_AppendResult(interp, + "Bad option: \"", zOpt, + "\" - must be \"-characteristics\" or \"-sectorsize\"", 0 + ); + return TCL_ERROR; + } + if( i==objc-1 ){ + Tcl_AppendResult(interp, "Option requires an argument: \"", zOpt, "\"",0); + return TCL_ERROR; + } + + if( zOpt[1]=='s' ){ + if( Tcl_GetIntFromObj(interp, objv[i+1], &iSectorSize) ){ + return TCL_ERROR; + } + setSectorsize = 1; + }else{ + int j; + Tcl_Obj **apObj; + int nObj; + if( Tcl_ListObjGetElements(interp, objv[i+1], &nObj, &apObj) ){ + return TCL_ERROR; + } + for(j=0; jmxPathname; + crashVfs.pAppData = (void *)pOriginalVfs; + crashVfs.szOsFile = sizeof(CrashFile) + pOriginalVfs->szOsFile; + sqlite3_vfs_register(&crashVfs, 0); + }else{ + crashVfs.pAppData = 0; + sqlite3_vfs_unregister(&crashVfs); + } + + return TCL_OK; +} + +/* +** tclcmd: sqlite_crashparams ?OPTIONS? DELAY CRASHFILE +** +** This procedure implements a TCL command that enables crash testing +** in testfixture. Once enabled, crash testing cannot be disabled. +** +** Available options are "-characteristics" and "-sectorsize". Both require +** an argument. For -sectorsize, this is the simulated sector size in +** bytes. For -characteristics, the argument must be a list of io-capability +** flags to simulate. Valid flags are "atomic", "atomic512", "atomic1K", +** "atomic2K", "atomic4K", "atomic8K", "atomic16K", "atomic32K", +** "atomic64K", "sequential" and "safe_append". +** +** Example: +** +** sqlite_crashparams -sect 1024 -char {atomic sequential} ./test.db 1 +** +*/ +static int crashParamsObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int iDelay; + const char *zCrashFile; + int nCrashFile, iDc, iSectorSize; + + iDc = -1; + iSectorSize = -1; + + if( objc<3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?OPTIONS? DELAY CRASHFILE"); + goto error; + } + + zCrashFile = Tcl_GetStringFromObj(objv[objc-1], &nCrashFile); + if( nCrashFile>=sizeof(g.zCrashFile) ){ + Tcl_AppendResult(interp, "Filename is too long: \"", zCrashFile, "\"", 0); + goto error; + } + if( Tcl_GetIntFromObj(interp, objv[objc-2], &iDelay) ){ + goto error; + } + + if( processDevSymArgs(interp, objc-3, &objv[1], &iDc, &iSectorSize) ){ + return TCL_ERROR; + } + + if( iDc>=0 ){ + g.iDeviceCharacteristics = iDc; + } + if( iSectorSize>=0 ){ + g.iSectorSize = iSectorSize; + } + + g.iCrash = iDelay; + memcpy(g.zCrashFile, zCrashFile, nCrashFile+1); + sqlite3CrashTestEnable = 1; + return TCL_OK; + +error: + return TCL_ERROR; +} + +static int devSymObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + void devsym_register(int iDeviceChar, int iSectorSize); + + int iDc = -1; + int iSectorSize = -1; + + if( processDevSymArgs(interp, objc-1, &objv[1], &iDc, &iSectorSize) ){ + return TCL_ERROR; + } + devsym_register(iDc, iSectorSize); + + return TCL_OK; +} + +/* +** tclcmd: register_jt_vfs ?-default? PARENT-VFS +*/ +static int jtObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int jt_register(char *, int); + char *zParent = 0; + + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?-default? PARENT-VFS"); + return TCL_ERROR; + } + zParent = Tcl_GetString(objv[1]); + if( objc==3 ){ + if( strcmp(zParent, "-default") ){ + Tcl_AppendResult(interp, + "bad option \"", zParent, "\": must be -default", 0 + ); + return TCL_ERROR; + } + zParent = Tcl_GetString(objv[2]); + } + + if( !(*zParent) ){ + zParent = 0; + } + if( jt_register(zParent, objc==3) ){ + Tcl_AppendResult(interp, "Error in jt_register", 0); + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** tclcmd: unregister_jt_vfs +*/ +static int jtUnregisterObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + void jt_unregister(void); + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + jt_unregister(); + return TCL_OK; +} + +#endif /* SQLITE_OMIT_DISKIO */ + +/* +** This procedure registers the TCL procedures defined in this file. +*/ +int Sqlitetest6_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_DISKIO + Tcl_CreateObjCommand(interp, "sqlite3_crash_enable", crashEnableCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_crashparams", crashParamsObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_simulate_device", devSymObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "register_jt_vfs", jtObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "unregister_jt_vfs", jtUnregisterObjCmd, 0, 0); +#endif + return TCL_OK; +} + +#endif /* SQLITE_TEST */ diff --git a/components/external/SQLite-3.8.1/src/test7.c b/components/external/SQLite-3.8.1/src/test7.c new file mode 100644 index 0000000000000000000000000000000000000000..93bf1e4898b004ce10dc131a1f4258b8a3f20aaf --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test7.c @@ -0,0 +1,714 @@ +/* +** 2006 January 09 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing the client/server version of the SQLite library. +** Derived from test4.c. +*/ +#include "sqliteInt.h" +#include "tcl.h" + +/* +** This test only works on UNIX with a SQLITE_THREADSAFE build that includes +** the SQLITE_SERVER option. +*/ +#if defined(SQLITE_SERVER) && !defined(SQLITE_OMIT_SHARED_CACHE) && \ + SQLITE_OS_UNIX && SQLITE_THREADSAFE + +#include +#include +#include +#include +#include + +/* +** Interfaces defined in server.c +*/ +int sqlite3_client_open(const char*, sqlite3**); +int sqlite3_client_prepare(sqlite3*,const char*,int, + sqlite3_stmt**,const char**); +int sqlite3_client_step(sqlite3_stmt*); +int sqlite3_client_reset(sqlite3_stmt*); +int sqlite3_client_finalize(sqlite3_stmt*); +int sqlite3_client_close(sqlite3*); +int sqlite3_server_start(void); +int sqlite3_server_stop(void); +void sqlite3_server_start2(int *pnDecr); + +/* +** Each thread is controlled by an instance of the following +** structure. +*/ +typedef struct Thread Thread; +struct Thread { + /* The first group of fields are writable by the supervisor thread + ** and read-only to the client threads + */ + char *zFilename; /* Name of database file */ + void (*xOp)(Thread*); /* next operation to do */ + char *zArg; /* argument usable by xOp */ + volatile int opnum; /* Operation number */ + volatile int busy; /* True if this thread is in use */ + + /* The next group of fields are writable by the client threads + ** but read-only to the superviser thread. + */ + volatile int completed; /* Number of operations completed */ + sqlite3 *db; /* Open database */ + sqlite3_stmt *pStmt; /* Pending operation */ + char *zErr; /* operation error */ + char *zStaticErr; /* Static error message */ + int rc; /* operation return code */ + int argc; /* number of columns in result */ + const char *argv[100]; /* result columns */ + const char *colv[100]; /* result column names */ + + /* Initialized to 1 by the supervisor thread when the client is + ** created, and then deemed read-only to the supervisor thread. + ** Is set to 0 by the server thread belonging to this client + ** just before it exits. + */ + int nServer; /* Number of server threads running */ +}; + +/* +** There can be as many as 26 threads running at once. Each is named +** by a capital letter: A, B, C, ..., Y, Z. +*/ +#define N_THREAD 26 +static Thread threadset[N_THREAD]; + +/* +** The main loop for a thread. Threads use busy waiting. +*/ +static void *client_main(void *pArg){ + Thread *p = (Thread*)pArg; + if( p->db ){ + sqlite3_client_close(p->db); + } + sqlite3_client_open(p->zFilename, &p->db); + if( SQLITE_OK!=sqlite3_errcode(p->db) ){ + p->zErr = strdup(sqlite3_errmsg(p->db)); + sqlite3_client_close(p->db); + p->db = 0; + } + p->pStmt = 0; + p->completed = 1; + while( p->opnum<=p->completed ) sched_yield(); + while( p->xOp ){ + if( p->zErr && p->zErr!=p->zStaticErr ){ + sqlite3_free(p->zErr); + p->zErr = 0; + } + (*p->xOp)(p); + p->completed++; + while( p->opnum<=p->completed ) sched_yield(); + } + if( p->pStmt ){ + sqlite3_client_finalize(p->pStmt); + p->pStmt = 0; + } + if( p->db ){ + sqlite3_client_close(p->db); + p->db = 0; + } + if( p->zErr && p->zErr!=p->zStaticErr ){ + sqlite3_free(p->zErr); + p->zErr = 0; + } + p->completed++; +#ifndef SQLITE_OMIT_DEPRECATED + sqlite3_thread_cleanup(); +#endif + return 0; +} + +/* +** Get a thread ID which is an upper case letter. Return the index. +** If the argument is not a valid thread ID put an error message in +** the interpreter and return -1. +*/ +static int parse_client_id(Tcl_Interp *interp, const char *zArg){ + if( zArg==0 || zArg[0]==0 || zArg[1]!=0 || !isupper((unsigned char)zArg[0]) ){ + Tcl_AppendResult(interp, "thread ID must be an upper case letter", 0); + return -1; + } + return zArg[0] - 'A'; +} + +/* +** Usage: client_create NAME FILENAME +** +** NAME should be an upper case letter. Start the thread running with +** an open connection to the given database. +*/ +static int tcl_client_create( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + pthread_t x; + int rc; + + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID FILENAME", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( threadset[i].busy ){ + Tcl_AppendResult(interp, "thread ", argv[1], " is already running", 0); + return TCL_ERROR; + } + threadset[i].busy = 1; + sqlite3_free(threadset[i].zFilename); + threadset[i].zFilename = sqlite3_mprintf("%s", argv[2]); + threadset[i].opnum = 1; + threadset[i].completed = 0; + rc = pthread_create(&x, 0, client_main, &threadset[i]); + if( rc ){ + Tcl_AppendResult(interp, "failed to create the thread", 0); + sqlite3_free(threadset[i].zFilename); + threadset[i].busy = 0; + return TCL_ERROR; + } + pthread_detach(x); + if( threadset[i].nServer==0 ){ + threadset[i].nServer = 1; + sqlite3_server_start2(&threadset[i].nServer); + } + return TCL_OK; +} + +/* +** Wait for a thread to reach its idle state. +*/ +static void client_wait(Thread *p){ + while( p->opnum>p->completed ) sched_yield(); +} + +/* +** Usage: client_wait ID +** +** Wait on thread ID to reach its idle state. +*/ +static int tcl_client_wait( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + return TCL_OK; +} + +/* +** Stop a thread. +*/ +static void stop_thread(Thread *p){ + client_wait(p); + p->xOp = 0; + p->opnum++; + client_wait(p); + sqlite3_free(p->zArg); + p->zArg = 0; + sqlite3_free(p->zFilename); + p->zFilename = 0; + p->busy = 0; +} + +/* +** Usage: client_halt ID +** +** Cause a client thread to shut itself down. Wait for the shutdown to be +** completed. If ID is "*" then stop all client threads. +*/ +static int tcl_client_halt( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + if( argv[1][0]=='*' && argv[1][1]==0 ){ + for(i=0; i=N_THREAD ){ + sqlite3_server_stop(); + while( 1 ){ + for(i=0; i=threadset[i].argc ){ + Tcl_AppendResult(interp, "column number out of range", 0); + return TCL_ERROR; + } + Tcl_AppendResult(interp, threadset[i].argv[n], 0); + return TCL_OK; +} + +/* +** Usage: client_colname ID N +** +** Wait on the most recent client_step to complete, then return the +** name of the N-th columns in the result set. +*/ +static int tcl_client_colname( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + int n; + + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID N", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR; + client_wait(&threadset[i]); + if( n<0 || n>=threadset[i].argc ){ + Tcl_AppendResult(interp, "column number out of range", 0); + return TCL_ERROR; + } + Tcl_AppendResult(interp, threadset[i].colv[n], 0); + return TCL_OK; +} + +extern const char *sqlite3ErrName(int); + +/* +** Usage: client_result ID +** +** Wait on the most recent operation to complete, then return the +** result code from that operation. +*/ +static int tcl_client_result( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + const char *zName; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + zName = sqlite3ErrName(threadset[i].rc); + Tcl_AppendResult(interp, zName, 0); + return TCL_OK; +} + +/* +** Usage: client_error ID +** +** Wait on the most recent operation to complete, then return the +** error string. +*/ +static int tcl_client_error( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + Tcl_AppendResult(interp, threadset[i].zErr, 0); + return TCL_OK; +} + +/* +** This procedure runs in the thread to compile an SQL statement. +*/ +static void do_compile(Thread *p){ + if( p->db==0 ){ + p->zErr = p->zStaticErr = "no database is open"; + p->rc = SQLITE_ERROR; + return; + } + if( p->pStmt ){ + sqlite3_client_finalize(p->pStmt); + p->pStmt = 0; + } + p->rc = sqlite3_client_prepare(p->db, p->zArg, -1, &p->pStmt, 0); +} + +/* +** Usage: client_compile ID SQL +** +** Compile a new virtual machine. +*/ +static int tcl_client_compile( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID SQL", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + threadset[i].xOp = do_compile; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = sqlite3_mprintf("%s", argv[2]); + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to step the virtual machine. +*/ +static void do_step(Thread *p){ + int i; + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_client_step(p->pStmt); + if( p->rc==SQLITE_ROW ){ + p->argc = sqlite3_column_count(p->pStmt); + for(i=0; ipStmt); i++){ + p->argv[i] = (char*)sqlite3_column_text(p->pStmt, i); + } + for(i=0; iargc; i++){ + p->colv[i] = sqlite3_column_name(p->pStmt, i); + } + } +} + +/* +** Usage: client_step ID +** +** Advance the virtual machine by one step +*/ +static int tcl_client_step( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + threadset[i].xOp = do_step; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to finalize a virtual machine. +*/ +static void do_finalize(Thread *p){ + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_client_finalize(p->pStmt); + p->pStmt = 0; +} + +/* +** Usage: client_finalize ID +** +** Finalize the virtual machine. +*/ +static int tcl_client_finalize( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + threadset[i].xOp = do_finalize; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = 0; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** This procedure runs in the thread to reset a virtual machine. +*/ +static void do_reset(Thread *p){ + if( p->pStmt==0 ){ + p->zErr = p->zStaticErr = "no virtual machine available"; + p->rc = SQLITE_ERROR; + return; + } + p->rc = sqlite3_client_reset(p->pStmt); + p->pStmt = 0; +} + +/* +** Usage: client_reset ID +** +** Finalize the virtual machine. +*/ +static int tcl_client_reset( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i; + if( argc!=2 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " IDL", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + threadset[i].xOp = do_reset; + sqlite3_free(threadset[i].zArg); + threadset[i].zArg = 0; + threadset[i].opnum++; + return TCL_OK; +} + +/* +** Usage: client_swap ID ID +** +** Interchange the sqlite* pointer between two threads. +*/ +static int tcl_client_swap( + void *NotUsed, + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int argc, /* Number of arguments */ + const char **argv /* Text of each argument */ +){ + int i, j; + sqlite3 *temp; + if( argc!=3 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], + " ID1 ID2", 0); + return TCL_ERROR; + } + i = parse_client_id(interp, argv[1]); + if( i<0 ) return TCL_ERROR; + if( !threadset[i].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[i]); + j = parse_client_id(interp, argv[2]); + if( j<0 ) return TCL_ERROR; + if( !threadset[j].busy ){ + Tcl_AppendResult(interp, "no such thread", 0); + return TCL_ERROR; + } + client_wait(&threadset[j]); + temp = threadset[i].db; + threadset[i].db = threadset[j].db; + threadset[j].db = temp; + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest7_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_CmdProc *xProc; + } aCmd[] = { + { "client_create", (Tcl_CmdProc*)tcl_client_create }, + { "client_wait", (Tcl_CmdProc*)tcl_client_wait }, + { "client_halt", (Tcl_CmdProc*)tcl_client_halt }, + { "client_argc", (Tcl_CmdProc*)tcl_client_argc }, + { "client_argv", (Tcl_CmdProc*)tcl_client_argv }, + { "client_colname", (Tcl_CmdProc*)tcl_client_colname }, + { "client_result", (Tcl_CmdProc*)tcl_client_result }, + { "client_error", (Tcl_CmdProc*)tcl_client_error }, + { "client_compile", (Tcl_CmdProc*)tcl_client_compile }, + { "client_step", (Tcl_CmdProc*)tcl_client_step }, + { "client_reset", (Tcl_CmdProc*)tcl_client_reset }, + { "client_finalize", (Tcl_CmdProc*)tcl_client_finalize }, + { "client_swap", (Tcl_CmdProc*)tcl_client_swap }, + }; + int i; + + for(i=0; i +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +typedef struct echo_vtab echo_vtab; +typedef struct echo_cursor echo_cursor; + +/* +** The test module defined in this file uses four global Tcl variables to +** commicate with test-scripts: +** +** $::echo_module +** $::echo_module_sync_fail +** $::echo_module_begin_fail +** $::echo_module_cost +** +** The variable ::echo_module is a list. Each time one of the following +** methods is called, one or more elements are appended to the list. +** This is used for automated testing of virtual table modules. +** +** The ::echo_module_sync_fail variable is set by test scripts and read +** by code in this file. If it is set to the name of a real table in the +** the database, then all xSync operations on echo virtual tables that +** use the named table as a backing store will fail. +*/ + +/* +** Errors can be provoked within the following echo virtual table methods: +** +** xBestIndex xOpen xFilter xNext +** xColumn xRowid xUpdate xSync +** xBegin xRename +** +** This is done by setting the global tcl variable: +** +** echo_module_fail($method,$tbl) +** +** where $method is set to the name of the virtual table method to fail +** (i.e. "xBestIndex") and $tbl is the name of the table being echoed (not +** the name of the virtual table, the name of the underlying real table). +*/ + +/* +** An echo virtual-table object. +** +** echo.vtab.aIndex is an array of booleans. The nth entry is true if +** the nth column of the real table is the left-most column of an index +** (implicit or otherwise). In other words, if SQLite can optimize +** a query like "SELECT * FROM real_table WHERE col = ?". +** +** Member variable aCol[] contains copies of the column names of the real +** table. +*/ +struct echo_vtab { + sqlite3_vtab base; + Tcl_Interp *interp; /* Tcl interpreter containing debug variables */ + sqlite3 *db; /* Database connection */ + + int isPattern; + int inTransaction; /* True if within a transaction */ + char *zThis; /* Name of the echo table */ + char *zTableName; /* Name of the real table */ + char *zLogName; /* Name of the log table */ + int nCol; /* Number of columns in the real table */ + int *aIndex; /* Array of size nCol. True if column has an index */ + char **aCol; /* Array of size nCol. Column names */ +}; + +/* An echo cursor object */ +struct echo_cursor { + sqlite3_vtab_cursor base; + sqlite3_stmt *pStmt; +}; + +static int simulateVtabError(echo_vtab *p, const char *zMethod){ + const char *zErr; + char zVarname[128]; + zVarname[127] = '\0'; + sqlite3_snprintf(127, zVarname, "echo_module_fail(%s,%s)", zMethod, p->zTableName); + zErr = Tcl_GetVar(p->interp, zVarname, TCL_GLOBAL_ONLY); + if( zErr ){ + p->base.zErrMsg = sqlite3_mprintf("echo-vtab-error: %s", zErr); + } + return (zErr!=0); +} + +/* +** Convert an SQL-style quoted string into a normal string by removing +** the quote characters. The conversion is done in-place. If the +** input does not begin with a quote character, then this routine +** is a no-op. +** +** Examples: +** +** "abc" becomes abc +** 'xyz' becomes xyz +** [pqr] becomes pqr +** `mno` becomes mno +*/ +static void dequoteString(char *z){ + int quote; + int i, j; + if( z==0 ) return; + quote = z[0]; + switch( quote ){ + case '\'': break; + case '"': break; + case '`': break; /* For MySQL compatibility */ + case '[': quote = ']'; break; /* For MS SqlServer compatibility */ + default: return; + } + for(i=1, j=0; z[i]; i++){ + if( z[i]==quote ){ + if( z[i+1]==quote ){ + z[j++] = quote; + i++; + }else{ + z[j++] = 0; + break; + } + }else{ + z[j++] = z[i]; + } + } +} + +/* +** Retrieve the column names for the table named zTab via database +** connection db. SQLITE_OK is returned on success, or an sqlite error +** code otherwise. +** +** If successful, the number of columns is written to *pnCol. *paCol is +** set to point at sqlite3_malloc()'d space containing the array of +** nCol column names. The caller is responsible for calling sqlite3_free +** on *paCol. +*/ +static int getColumnNames( + sqlite3 *db, + const char *zTab, + char ***paCol, + int *pnCol +){ + char **aCol = 0; + char *zSql; + sqlite3_stmt *pStmt = 0; + int rc = SQLITE_OK; + int nCol = 0; + + /* Prepare the statement "SELECT * FROM ". The column names + ** of the result set of the compiled SELECT will be the same as + ** the column names of table . + */ + zSql = sqlite3_mprintf("SELECT * FROM %Q", zTab); + if( !zSql ){ + rc = SQLITE_NOMEM; + goto out; + } + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + + if( rc==SQLITE_OK ){ + int ii; + int nBytes; + char *zSpace; + nCol = sqlite3_column_count(pStmt); + + /* Figure out how much space to allocate for the array of column names + ** (including space for the strings themselves). Then allocate it. + */ + nBytes = sizeof(char *) * nCol; + for(ii=0; ii=0 && cidzTableName ){ + sqlite3_stmt *pStmt = 0; + rc = sqlite3_prepare(db, + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", + -1, &pStmt, 0); + if( rc==SQLITE_OK ){ + sqlite3_bind_text(pStmt, 1, pVtab->zTableName, -1, 0); + if( sqlite3_step(pStmt)==SQLITE_ROW ){ + int rc2; + const char *zCreateTable = (const char *)sqlite3_column_text(pStmt, 0); + rc = sqlite3_declare_vtab(db, zCreateTable); + rc2 = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } else { + rc = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ){ + rc = SQLITE_ERROR; + } + } + if( rc==SQLITE_OK ){ + rc = getColumnNames(db, pVtab->zTableName, &pVtab->aCol, &pVtab->nCol); + } + if( rc==SQLITE_OK ){ + rc = getIndexArray(db, pVtab->zTableName, pVtab->nCol, &pVtab->aIndex); + } + } + } + + return rc; +} + +/* +** This function frees all runtime structures associated with the virtual +** table pVtab. +*/ +static int echoDestructor(sqlite3_vtab *pVtab){ + echo_vtab *p = (echo_vtab*)pVtab; + sqlite3_free(p->aIndex); + sqlite3_free(p->aCol); + sqlite3_free(p->zThis); + sqlite3_free(p->zTableName); + sqlite3_free(p->zLogName); + sqlite3_free(p); + return 0; +} + +typedef struct EchoModule EchoModule; +struct EchoModule { + Tcl_Interp *interp; +}; + +/* +** This function is called to do the work of the xConnect() method - +** to allocate the required in-memory structures for a newly connected +** virtual table. +*/ +static int echoConstructor( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int rc; + int i; + echo_vtab *pVtab; + + /* Allocate the sqlite3_vtab/echo_vtab structure itself */ + pVtab = sqlite3MallocZero( sizeof(*pVtab) ); + if( !pVtab ){ + return SQLITE_NOMEM; + } + pVtab->interp = ((EchoModule *)pAux)->interp; + pVtab->db = db; + + /* Allocate echo_vtab.zThis */ + pVtab->zThis = sqlite3_mprintf("%s", argv[2]); + if( !pVtab->zThis ){ + echoDestructor((sqlite3_vtab *)pVtab); + return SQLITE_NOMEM; + } + + /* Allocate echo_vtab.zTableName */ + if( argc>3 ){ + pVtab->zTableName = sqlite3_mprintf("%s", argv[3]); + dequoteString(pVtab->zTableName); + if( pVtab->zTableName && pVtab->zTableName[0]=='*' ){ + char *z = sqlite3_mprintf("%s%s", argv[2], &(pVtab->zTableName[1])); + sqlite3_free(pVtab->zTableName); + pVtab->zTableName = z; + pVtab->isPattern = 1; + } + if( !pVtab->zTableName ){ + echoDestructor((sqlite3_vtab *)pVtab); + return SQLITE_NOMEM; + } + } + + /* Log the arguments to this function to Tcl var ::echo_module */ + for(i=0; iinterp, argv[i]); + } + + /* Invoke sqlite3_declare_vtab and set up other members of the echo_vtab + ** structure. If an error occurs, delete the sqlite3_vtab structure and + ** return an error code. + */ + rc = echoDeclareVtab(pVtab, db); + if( rc!=SQLITE_OK ){ + echoDestructor((sqlite3_vtab *)pVtab); + return rc; + } + + /* Success. Set *ppVtab and return */ + *ppVtab = &pVtab->base; + return SQLITE_OK; +} + +/* +** Echo virtual table module xCreate method. +*/ +static int echoCreate( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int rc = SQLITE_OK; + appendToEchoModule(((EchoModule *)pAux)->interp, "xCreate"); + rc = echoConstructor(db, pAux, argc, argv, ppVtab, pzErr); + + /* If there were two arguments passed to the module at the SQL level + ** (i.e. "CREATE VIRTUAL TABLE tbl USING echo(arg1, arg2)"), then + ** the second argument is used as a table name. Attempt to create + ** such a table with a single column, "logmsg". This table will + ** be used to log calls to the xUpdate method. It will be deleted + ** when the virtual table is DROPed. + ** + ** Note: The main point of this is to test that we can drop tables + ** from within an xDestroy method call. + */ + if( rc==SQLITE_OK && argc==5 ){ + char *zSql; + echo_vtab *pVtab = *(echo_vtab **)ppVtab; + pVtab->zLogName = sqlite3_mprintf("%s", argv[4]); + zSql = sqlite3_mprintf("CREATE TABLE %Q(logmsg)", pVtab->zLogName); + rc = sqlite3_exec(db, zSql, 0, 0, 0); + sqlite3_free(zSql); + if( rc!=SQLITE_OK ){ + *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + } + } + + if( *ppVtab && rc!=SQLITE_OK ){ + echoDestructor(*ppVtab); + *ppVtab = 0; + } + + if( rc==SQLITE_OK ){ + (*(echo_vtab**)ppVtab)->inTransaction = 1; + } + + return rc; +} + +/* +** Echo virtual table module xConnect method. +*/ +static int echoConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + appendToEchoModule(((EchoModule *)pAux)->interp, "xConnect"); + return echoConstructor(db, pAux, argc, argv, ppVtab, pzErr); +} + +/* +** Echo virtual table module xDisconnect method. +*/ +static int echoDisconnect(sqlite3_vtab *pVtab){ + appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDisconnect"); + return echoDestructor(pVtab); +} + +/* +** Echo virtual table module xDestroy method. +*/ +static int echoDestroy(sqlite3_vtab *pVtab){ + int rc = SQLITE_OK; + echo_vtab *p = (echo_vtab *)pVtab; + appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDestroy"); + + /* Drop the "log" table, if one exists (see echoCreate() for details) */ + if( p && p->zLogName ){ + char *zSql; + zSql = sqlite3_mprintf("DROP TABLE %Q", p->zLogName); + rc = sqlite3_exec(p->db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } + + if( rc==SQLITE_OK ){ + rc = echoDestructor(pVtab); + } + return rc; +} + +/* +** Echo virtual table module xOpen method. +*/ +static int echoOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + echo_cursor *pCur; + if( simulateVtabError((echo_vtab *)pVTab, "xOpen") ){ + return SQLITE_ERROR; + } + pCur = sqlite3MallocZero(sizeof(echo_cursor)); + *ppCursor = (sqlite3_vtab_cursor *)pCur; + return (pCur ? SQLITE_OK : SQLITE_NOMEM); +} + +/* +** Echo virtual table module xClose method. +*/ +static int echoClose(sqlite3_vtab_cursor *cur){ + int rc; + echo_cursor *pCur = (echo_cursor *)cur; + sqlite3_stmt *pStmt = pCur->pStmt; + pCur->pStmt = 0; + sqlite3_free(pCur); + rc = sqlite3_finalize(pStmt); + return rc; +} + +/* +** Return non-zero if the cursor does not currently point to a valid record +** (i.e if the scan has finished), or zero otherwise. +*/ +static int echoEof(sqlite3_vtab_cursor *cur){ + return (((echo_cursor *)cur)->pStmt ? 0 : 1); +} + +/* +** Echo virtual table module xNext method. +*/ +static int echoNext(sqlite3_vtab_cursor *cur){ + int rc = SQLITE_OK; + echo_cursor *pCur = (echo_cursor *)cur; + + if( simulateVtabError((echo_vtab *)(cur->pVtab), "xNext") ){ + return SQLITE_ERROR; + } + + if( pCur->pStmt ){ + rc = sqlite3_step(pCur->pStmt); + if( rc==SQLITE_ROW ){ + rc = SQLITE_OK; + }else{ + rc = sqlite3_finalize(pCur->pStmt); + pCur->pStmt = 0; + } + } + + return rc; +} + +/* +** Echo virtual table module xColumn method. +*/ +static int echoColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + int iCol = i + 1; + sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt; + + if( simulateVtabError((echo_vtab *)(cur->pVtab), "xColumn") ){ + return SQLITE_ERROR; + } + + if( !pStmt ){ + sqlite3_result_null(ctx); + }else{ + assert( sqlite3_data_count(pStmt)>iCol ); + sqlite3_result_value(ctx, sqlite3_column_value(pStmt, iCol)); + } + return SQLITE_OK; +} + +/* +** Echo virtual table module xRowid method. +*/ +static int echoRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt; + + if( simulateVtabError((echo_vtab *)(cur->pVtab), "xRowid") ){ + return SQLITE_ERROR; + } + + *pRowid = sqlite3_column_int64(pStmt, 0); + return SQLITE_OK; +} + +/* +** Compute a simple hash of the null terminated string zString. +** +** This module uses only sqlite3_index_info.idxStr, not +** sqlite3_index_info.idxNum. So to test idxNum, when idxStr is set +** in echoBestIndex(), idxNum is set to the corresponding hash value. +** In echoFilter(), code assert()s that the supplied idxNum value is +** indeed the hash of the supplied idxStr. +*/ +static int hashString(const char *zString){ + int val = 0; + int ii; + for(ii=0; zString[ii]; ii++){ + val = (val << 3) + (int)zString[ii]; + } + return val; +} + +/* +** Echo virtual table module xFilter method. +*/ +static int echoFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + int rc; + int i; + + echo_cursor *pCur = (echo_cursor *)pVtabCursor; + echo_vtab *pVtab = (echo_vtab *)pVtabCursor->pVtab; + sqlite3 *db = pVtab->db; + + if( simulateVtabError(pVtab, "xFilter") ){ + return SQLITE_ERROR; + } + + /* Check that idxNum matches idxStr */ + assert( idxNum==hashString(idxStr) ); + + /* Log arguments to the ::echo_module Tcl variable */ + appendToEchoModule(pVtab->interp, "xFilter"); + appendToEchoModule(pVtab->interp, idxStr); + for(i=0; iinterp, (const char*)sqlite3_value_text(argv[i])); + } + + sqlite3_finalize(pCur->pStmt); + pCur->pStmt = 0; + + /* Prepare the SQL statement created by echoBestIndex and bind the + ** runtime parameters passed to this function to it. + */ + rc = sqlite3_prepare(db, idxStr, -1, &pCur->pStmt, 0); + assert( pCur->pStmt || rc!=SQLITE_OK ); + for(i=0; rc==SQLITE_OK && ipStmt, i+1, argv[i]); + } + + /* If everything was successful, advance to the first row of the scan */ + if( rc==SQLITE_OK ){ + rc = echoNext(pVtabCursor); + } + + return rc; +} + + +/* +** A helper function used by echoUpdate() and echoBestIndex() for +** manipulating strings in concert with the sqlite3_mprintf() function. +** +** Parameter pzStr points to a pointer to a string allocated with +** sqlite3_mprintf. The second parameter, zAppend, points to another +** string. The two strings are concatenated together and *pzStr +** set to point at the result. The initial buffer pointed to by *pzStr +** is deallocated via sqlite3_free(). +** +** If the third argument, doFree, is true, then sqlite3_free() is +** also called to free the buffer pointed to by zAppend. +*/ +static void string_concat(char **pzStr, char *zAppend, int doFree, int *pRc){ + char *zIn = *pzStr; + if( !zAppend && doFree && *pRc==SQLITE_OK ){ + *pRc = SQLITE_NOMEM; + } + if( *pRc!=SQLITE_OK ){ + sqlite3_free(zIn); + zIn = 0; + }else{ + if( zIn ){ + char *zTemp = zIn; + zIn = sqlite3_mprintf("%s%s", zIn, zAppend); + sqlite3_free(zTemp); + }else{ + zIn = sqlite3_mprintf("%s", zAppend); + } + if( !zIn ){ + *pRc = SQLITE_NOMEM; + } + } + *pzStr = zIn; + if( doFree ){ + sqlite3_free(zAppend); + } +} + +/* +** The echo module implements the subset of query constraints and sort +** orders that may take advantage of SQLite indices on the underlying +** real table. For example, if the real table is declared as: +** +** CREATE TABLE real(a, b, c); +** CREATE INDEX real_index ON real(b); +** +** then the echo module handles WHERE or ORDER BY clauses that refer +** to the column "b", but not "a" or "c". If a multi-column index is +** present, only its left most column is considered. +** +** This xBestIndex method encodes the proposed search strategy as +** an SQL query on the real table underlying the virtual echo module +** table and stores the query in sqlite3_index_info.idxStr. The SQL +** statement is of the form: +** +** SELECT rowid, * FROM ?? ?? +** +** where the and are determined +** by the contents of the structure pointed to by the pIdxInfo argument. +*/ +static int echoBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int ii; + char *zQuery = 0; + char *zNew; + int nArg = 0; + const char *zSep = "WHERE"; + echo_vtab *pVtab = (echo_vtab *)tab; + sqlite3_stmt *pStmt = 0; + Tcl_Interp *interp = pVtab->interp; + + int nRow; + int useIdx = 0; + int rc = SQLITE_OK; + int useCost = 0; + double cost; + int isIgnoreUsable = 0; + if( Tcl_GetVar(interp, "echo_module_ignore_usable", TCL_GLOBAL_ONLY) ){ + isIgnoreUsable = 1; + } + + if( simulateVtabError(pVtab, "xBestIndex") ){ + return SQLITE_ERROR; + } + + /* Determine the number of rows in the table and store this value in local + ** variable nRow. The 'estimated-cost' of the scan will be the number of + ** rows in the table for a linear scan, or the log (base 2) of the + ** number of rows if the proposed scan uses an index. + */ + if( Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY) ){ + cost = atof(Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY)); + useCost = 1; + } else { + zQuery = sqlite3_mprintf("SELECT count(*) FROM %Q", pVtab->zTableName); + if( !zQuery ){ + return SQLITE_NOMEM; + } + rc = sqlite3_prepare(pVtab->db, zQuery, -1, &pStmt, 0); + sqlite3_free(zQuery); + if( rc!=SQLITE_OK ){ + return rc; + } + sqlite3_step(pStmt); + nRow = sqlite3_column_int(pStmt, 0); + rc = sqlite3_finalize(pStmt); + if( rc!=SQLITE_OK ){ + return rc; + } + } + + zQuery = sqlite3_mprintf("SELECT rowid, * FROM %Q", pVtab->zTableName); + if( !zQuery ){ + return SQLITE_NOMEM; + } + for(ii=0; iinConstraint; ii++){ + const struct sqlite3_index_constraint *pConstraint; + struct sqlite3_index_constraint_usage *pUsage; + int iCol; + + pConstraint = &pIdxInfo->aConstraint[ii]; + pUsage = &pIdxInfo->aConstraintUsage[ii]; + + if( !isIgnoreUsable && !pConstraint->usable ) continue; + + iCol = pConstraint->iColumn; + if( iCol<0 || pVtab->aIndex[iCol] ){ + char *zCol = iCol>=0 ? pVtab->aCol[iCol] : "rowid"; + char *zOp = 0; + useIdx = 1; + switch( pConstraint->op ){ + case SQLITE_INDEX_CONSTRAINT_EQ: + zOp = "="; break; + case SQLITE_INDEX_CONSTRAINT_LT: + zOp = "<"; break; + case SQLITE_INDEX_CONSTRAINT_GT: + zOp = ">"; break; + case SQLITE_INDEX_CONSTRAINT_LE: + zOp = "<="; break; + case SQLITE_INDEX_CONSTRAINT_GE: + zOp = ">="; break; + case SQLITE_INDEX_CONSTRAINT_MATCH: + zOp = "LIKE"; break; + } + if( zOp[0]=='L' ){ + zNew = sqlite3_mprintf(" %s %s LIKE (SELECT '%%'||?||'%%')", + zSep, zCol); + } else { + zNew = sqlite3_mprintf(" %s %s %s ?", zSep, zCol, zOp); + } + string_concat(&zQuery, zNew, 1, &rc); + + zSep = "AND"; + pUsage->argvIndex = ++nArg; + pUsage->omit = 1; + } + } + + /* If there is only one term in the ORDER BY clause, and it is + ** on a column that this virtual table has an index for, then consume + ** the ORDER BY clause. + */ + if( pIdxInfo->nOrderBy==1 && ( + pIdxInfo->aOrderBy->iColumn<0 || + pVtab->aIndex[pIdxInfo->aOrderBy->iColumn]) ){ + int iCol = pIdxInfo->aOrderBy->iColumn; + char *zCol = iCol>=0 ? pVtab->aCol[iCol] : "rowid"; + char *zDir = pIdxInfo->aOrderBy->desc?"DESC":"ASC"; + zNew = sqlite3_mprintf(" ORDER BY %s %s", zCol, zDir); + string_concat(&zQuery, zNew, 1, &rc); + pIdxInfo->orderByConsumed = 1; + } + + appendToEchoModule(pVtab->interp, "xBestIndex");; + appendToEchoModule(pVtab->interp, zQuery); + + if( !zQuery ){ + return rc; + } + pIdxInfo->idxNum = hashString(zQuery); + pIdxInfo->idxStr = zQuery; + pIdxInfo->needToFreeIdxStr = 1; + if( useCost ){ + pIdxInfo->estimatedCost = cost; + }else if( useIdx ){ + /* Approximation of log2(nRow). */ + for( ii=0; ii<(sizeof(int)*8); ii++ ){ + if( nRow & (1<estimatedCost = (double)ii; + } + } + }else{ + pIdxInfo->estimatedCost = (double)nRow; + } + return rc; +} + +/* +** The xUpdate method for echo module virtual tables. +** +** apData[0] apData[1] apData[2..] +** +** INTEGER DELETE +** +** INTEGER NULL (nCol args) UPDATE (do not set rowid) +** INTEGER INTEGER (nCol args) UPDATE (with SET rowid = ) +** +** NULL NULL (nCol args) INSERT INTO (automatic rowid value) +** NULL INTEGER (nCol args) INSERT (incl. rowid value) +** +*/ +int echoUpdate( + sqlite3_vtab *tab, + int nData, + sqlite3_value **apData, + sqlite_int64 *pRowid +){ + echo_vtab *pVtab = (echo_vtab *)tab; + sqlite3 *db = pVtab->db; + int rc = SQLITE_OK; + + sqlite3_stmt *pStmt; + char *z = 0; /* SQL statement to execute */ + int bindArgZero = 0; /* True to bind apData[0] to sql var no. nData */ + int bindArgOne = 0; /* True to bind apData[1] to sql var no. 1 */ + int i; /* Counter variable used by for loops */ + + assert( nData==pVtab->nCol+2 || nData==1 ); + + /* Ticket #3083 - make sure we always start a transaction prior to + ** making any changes to a virtual table */ + assert( pVtab->inTransaction ); + + if( simulateVtabError(pVtab, "xUpdate") ){ + return SQLITE_ERROR; + } + + /* If apData[0] is an integer and nData>1 then do an UPDATE */ + if( nData>1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){ + char *zSep = " SET"; + z = sqlite3_mprintf("UPDATE %Q", pVtab->zTableName); + if( !z ){ + rc = SQLITE_NOMEM; + } + + bindArgOne = (apData[1] && sqlite3_value_type(apData[1])==SQLITE_INTEGER); + bindArgZero = 1; + + if( bindArgOne ){ + string_concat(&z, " SET rowid=?1 ", 0, &rc); + zSep = ","; + } + for(i=2; iaCol[i-2], i), 1, &rc); + zSep = ","; + } + string_concat(&z, sqlite3_mprintf(" WHERE rowid=?%d", nData), 1, &rc); + } + + /* If apData[0] is an integer and nData==1 then do a DELETE */ + else if( nData==1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){ + z = sqlite3_mprintf("DELETE FROM %Q WHERE rowid = ?1", pVtab->zTableName); + if( !z ){ + rc = SQLITE_NOMEM; + } + bindArgZero = 1; + } + + /* If the first argument is NULL and there are more than two args, INSERT */ + else if( nData>2 && sqlite3_value_type(apData[0])==SQLITE_NULL ){ + int ii; + char *zInsert = 0; + char *zValues = 0; + + zInsert = sqlite3_mprintf("INSERT INTO %Q (", pVtab->zTableName); + if( !zInsert ){ + rc = SQLITE_NOMEM; + } + if( sqlite3_value_type(apData[1])==SQLITE_INTEGER ){ + bindArgOne = 1; + zValues = sqlite3_mprintf("?"); + string_concat(&zInsert, "rowid", 0, &rc); + } + + assert((pVtab->nCol+2)==nData); + for(ii=2; iiaCol[ii-2]), 1, &rc); + string_concat(&zValues, + sqlite3_mprintf("%s?%d", zValues?", ":"", ii), 1, &rc); + } + + string_concat(&z, zInsert, 1, &rc); + string_concat(&z, ") VALUES(", 0, &rc); + string_concat(&z, zValues, 1, &rc); + string_concat(&z, ")", 0, &rc); + } + + /* Anything else is an error */ + else{ + assert(0); + return SQLITE_ERROR; + } + + if( rc==SQLITE_OK ){ + rc = sqlite3_prepare(db, z, -1, &pStmt, 0); + } + assert( rc!=SQLITE_OK || pStmt ); + sqlite3_free(z); + if( rc==SQLITE_OK ) { + if( bindArgZero ){ + sqlite3_bind_value(pStmt, nData, apData[0]); + } + if( bindArgOne ){ + sqlite3_bind_value(pStmt, 1, apData[1]); + } + for(i=2; izErrMsg = sqlite3_mprintf("echo-vtab-error: %s", sqlite3_errmsg(db)); + } + + return rc; +} + +/* +** xBegin, xSync, xCommit and xRollback callbacks for echo module +** virtual tables. Do nothing other than add the name of the callback +** to the $::echo_module Tcl variable. +*/ +static int echoTransactionCall(sqlite3_vtab *tab, const char *zCall){ + char *z; + echo_vtab *pVtab = (echo_vtab *)tab; + z = sqlite3_mprintf("echo(%s)", pVtab->zTableName); + if( z==0 ) return SQLITE_NOMEM; + appendToEchoModule(pVtab->interp, zCall); + appendToEchoModule(pVtab->interp, z); + sqlite3_free(z); + return SQLITE_OK; +} +static int echoBegin(sqlite3_vtab *tab){ + int rc; + echo_vtab *pVtab = (echo_vtab *)tab; + Tcl_Interp *interp = pVtab->interp; + const char *zVal; + + /* Ticket #3083 - do not start a transaction if we are already in + ** a transaction */ + assert( !pVtab->inTransaction ); + + if( simulateVtabError(pVtab, "xBegin") ){ + return SQLITE_ERROR; + } + + rc = echoTransactionCall(tab, "xBegin"); + + if( rc==SQLITE_OK ){ + /* Check if the $::echo_module_begin_fail variable is defined. If it is, + ** and it is set to the name of the real table underlying this virtual + ** echo module table, then cause this xSync operation to fail. + */ + zVal = Tcl_GetVar(interp, "echo_module_begin_fail", TCL_GLOBAL_ONLY); + if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){ + rc = SQLITE_ERROR; + } + } + if( rc==SQLITE_OK ){ + pVtab->inTransaction = 1; + } + return rc; +} +static int echoSync(sqlite3_vtab *tab){ + int rc; + echo_vtab *pVtab = (echo_vtab *)tab; + Tcl_Interp *interp = pVtab->interp; + const char *zVal; + + /* Ticket #3083 - Only call xSync if we have previously started a + ** transaction */ + assert( pVtab->inTransaction ); + + if( simulateVtabError(pVtab, "xSync") ){ + return SQLITE_ERROR; + } + + rc = echoTransactionCall(tab, "xSync"); + + if( rc==SQLITE_OK ){ + /* Check if the $::echo_module_sync_fail variable is defined. If it is, + ** and it is set to the name of the real table underlying this virtual + ** echo module table, then cause this xSync operation to fail. + */ + zVal = Tcl_GetVar(interp, "echo_module_sync_fail", TCL_GLOBAL_ONLY); + if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){ + rc = -1; + } + } + return rc; +} +static int echoCommit(sqlite3_vtab *tab){ + echo_vtab *pVtab = (echo_vtab*)tab; + int rc; + + /* Ticket #3083 - Only call xCommit if we have previously started + ** a transaction */ + assert( pVtab->inTransaction ); + + if( simulateVtabError(pVtab, "xCommit") ){ + return SQLITE_ERROR; + } + + sqlite3BeginBenignMalloc(); + rc = echoTransactionCall(tab, "xCommit"); + sqlite3EndBenignMalloc(); + pVtab->inTransaction = 0; + return rc; +} +static int echoRollback(sqlite3_vtab *tab){ + int rc; + echo_vtab *pVtab = (echo_vtab*)tab; + + /* Ticket #3083 - Only call xRollback if we have previously started + ** a transaction */ + assert( pVtab->inTransaction ); + + rc = echoTransactionCall(tab, "xRollback"); + pVtab->inTransaction = 0; + return rc; +} + +/* +** Implementation of "GLOB" function on the echo module. Pass +** all arguments to the ::echo_glob_overload procedure of TCL +** and return the result of that procedure as a string. +*/ +static void overloadedGlobFunction( + sqlite3_context *pContext, + int nArg, + sqlite3_value **apArg +){ + Tcl_Interp *interp = sqlite3_user_data(pContext); + Tcl_DString str; + int i; + int rc; + Tcl_DStringInit(&str); + Tcl_DStringAppendElement(&str, "::echo_glob_overload"); + for(i=0; iinterp; + Tcl_CmdInfo info; + if( strcmp(zFuncName,"glob")!=0 ){ + return 0; + } + if( Tcl_GetCommandInfo(interp, "::echo_glob_overload", &info)==0 ){ + return 0; + } + *pxFunc = overloadedGlobFunction; + *ppArg = interp; + return 1; +} + +static int echoRename(sqlite3_vtab *vtab, const char *zNewName){ + int rc = SQLITE_OK; + echo_vtab *p = (echo_vtab *)vtab; + + if( simulateVtabError(p, "xRename") ){ + return SQLITE_ERROR; + } + + if( p->isPattern ){ + int nThis = (int)strlen(p->zThis); + char *zSql = sqlite3_mprintf("ALTER TABLE %s RENAME TO %s%s", + p->zTableName, zNewName, &p->zTableName[nThis] + ); + rc = sqlite3_exec(p->db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } + + return rc; +} + +static int echoSavepoint(sqlite3_vtab *pVTab, int iSavepoint){ + assert( pVTab ); + return SQLITE_OK; +} + +static int echoRelease(sqlite3_vtab *pVTab, int iSavepoint){ + assert( pVTab ); + return SQLITE_OK; +} + +static int echoRollbackTo(sqlite3_vtab *pVTab, int iSavepoint){ + assert( pVTab ); + return SQLITE_OK; +} + +/* +** A virtual table module that merely "echos" the contents of another +** table (like an SQL VIEW). +*/ +static sqlite3_module echoModule = { + 1, /* iVersion */ + echoCreate, + echoConnect, + echoBestIndex, + echoDisconnect, + echoDestroy, + echoOpen, /* xOpen - open a cursor */ + echoClose, /* xClose - close a cursor */ + echoFilter, /* xFilter - configure scan constraints */ + echoNext, /* xNext - advance a cursor */ + echoEof, /* xEof */ + echoColumn, /* xColumn - read data */ + echoRowid, /* xRowid - read data */ + echoUpdate, /* xUpdate - write data */ + echoBegin, /* xBegin - begin transaction */ + echoSync, /* xSync - sync transaction */ + echoCommit, /* xCommit - commit transaction */ + echoRollback, /* xRollback - rollback transaction */ + echoFindFunction, /* xFindFunction - function overloading */ + echoRename /* xRename - rename the table */ +}; + +static sqlite3_module echoModuleV2 = { + 2, /* iVersion */ + echoCreate, + echoConnect, + echoBestIndex, + echoDisconnect, + echoDestroy, + echoOpen, /* xOpen - open a cursor */ + echoClose, /* xClose - close a cursor */ + echoFilter, /* xFilter - configure scan constraints */ + echoNext, /* xNext - advance a cursor */ + echoEof, /* xEof */ + echoColumn, /* xColumn - read data */ + echoRowid, /* xRowid - read data */ + echoUpdate, /* xUpdate - write data */ + echoBegin, /* xBegin - begin transaction */ + echoSync, /* xSync - sync transaction */ + echoCommit, /* xCommit - commit transaction */ + echoRollback, /* xRollback - rollback transaction */ + echoFindFunction, /* xFindFunction - function overloading */ + echoRename, /* xRename - rename the table */ + echoSavepoint, + echoRelease, + echoRollbackTo +}; + +/* +** Decode a pointer to an sqlite3 object. +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); +extern const char *sqlite3ErrName(int); + +static void moduleDestroy(void *p){ + sqlite3_free(p); +} + +/* +** Register the echo virtual table module. +*/ +static int register_echo_module( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int rc; + sqlite3 *db; + EchoModule *pMod; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + + /* Virtual table module "echo" */ + pMod = sqlite3_malloc(sizeof(EchoModule)); + pMod->interp = interp; + rc = sqlite3_create_module_v2( + db, "echo", &echoModule, (void*)pMod, moduleDestroy + ); + + /* Virtual table module "echo_v2" */ + if( rc==SQLITE_OK ){ + pMod = sqlite3_malloc(sizeof(EchoModule)); + pMod->interp = interp; + rc = sqlite3_create_module_v2(db, "echo_v2", + &echoModuleV2, (void*)pMod, moduleDestroy + ); + } + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** Tcl interface to sqlite3_declare_vtab, invoked as follows from Tcl: +** +** sqlite3_declare_vtab DB SQL +*/ +static int declare_vtab( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + int rc; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB SQL"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_declare_vtab(db, Tcl_GetString(objv[2])); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE); + return TCL_ERROR; + } + return TCL_OK; +} + +#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest8_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "register_echo_module", register_echo_module, 0 }, + { "sqlite3_declare_vtab", declare_vtab, 0 }, + }; + int i; + for(i=0; i +#include + +/* +** c_collation_test +*/ +static int c_collation_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + const char *zErrFunction = "N/A"; + sqlite3 *db; + + int rc; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + /* Open a database. */ + rc = sqlite3_open(":memory:", &db); + if( rc!=SQLITE_OK ){ + zErrFunction = "sqlite3_open"; + goto error_out; + } + + rc = sqlite3_create_collation(db, "collate", 456, 0, 0); + if( rc!=SQLITE_MISUSE ){ + sqlite3_close(db); + zErrFunction = "sqlite3_create_collation"; + goto error_out; + } + + sqlite3_close(db); + return TCL_OK; + +error_out: + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "Error testing function: ", zErrFunction, 0); + return TCL_ERROR; +} + +/* +** c_realloc_test +*/ +static int c_realloc_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + void *p; + const char *zErrFunction = "N/A"; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + p = sqlite3_malloc(5); + if( !p ){ + zErrFunction = "sqlite3_malloc"; + goto error_out; + } + + /* Test that realloc()ing a block of memory to a negative size is + ** the same as free()ing that memory. + */ + p = sqlite3_realloc(p, -1); + if( p ){ + zErrFunction = "sqlite3_realloc"; + goto error_out; + } + + return TCL_OK; + +error_out: + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "Error testing function: ", zErrFunction, 0); + return TCL_ERROR; +} + + +/* +** c_misuse_test +*/ +static int c_misuse_test( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + const char *zErrFunction = "N/A"; + sqlite3 *db = 0; + sqlite3_stmt *pStmt; + int rc; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + /* Open a database. Then close it again. We need to do this so that + ** we have a "closed database handle" to pass to various API functions. + */ + rc = sqlite3_open(":memory:", &db); + if( rc!=SQLITE_OK ){ + zErrFunction = "sqlite3_open"; + goto error_out; + } + sqlite3_close(db); + + + rc = sqlite3_errcode(db); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_errcode"; + goto error_out; + } + + pStmt = (sqlite3_stmt*)1234; + rc = sqlite3_prepare(db, 0, 0, &pStmt, 0); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_prepare"; + goto error_out; + } + assert( pStmt==0 ); /* Verify that pStmt is zeroed even on a MISUSE error */ + + pStmt = (sqlite3_stmt*)1234; + rc = sqlite3_prepare_v2(db, 0, 0, &pStmt, 0); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_prepare_v2"; + goto error_out; + } + assert( pStmt==0 ); + +#ifndef SQLITE_OMIT_UTF16 + pStmt = (sqlite3_stmt*)1234; + rc = sqlite3_prepare16(db, 0, 0, &pStmt, 0); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_prepare16"; + goto error_out; + } + assert( pStmt==0 ); + pStmt = (sqlite3_stmt*)1234; + rc = sqlite3_prepare16_v2(db, 0, 0, &pStmt, 0); + if( rc!=SQLITE_MISUSE ){ + zErrFunction = "sqlite3_prepare16_v2"; + goto error_out; + } + assert( pStmt==0 ); +#endif + + return TCL_OK; + +error_out: + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, "Error testing function: ", zErrFunction, 0); + return TCL_ERROR; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest9_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "c_misuse_test", c_misuse_test, 0 }, + { "c_realloc_test", c_realloc_test, 0 }, + { "c_collation_test", c_collation_test, 0 }, + }; + int i; + for(i=0; i + +#ifdef SQLITE_ENABLE_ASYNCIO + +#include "sqlite3async.h" +#include "sqlite3.h" +#include + +/* From main.c */ +extern const char *sqlite3ErrName(int); + + +struct TestAsyncGlobal { + int isInstalled; /* True when async VFS is installed */ +} testasync_g = { 0 }; + +TCL_DECLARE_MUTEX(testasync_g_writerMutex); + +/* +** sqlite3async_initialize PARENT-VFS ISDEFAULT +*/ +static int testAsyncInit( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zParent; + int isDefault; + int rc; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PARENT-VFS ISDEFAULT"); + return TCL_ERROR; + } + zParent = Tcl_GetString(objv[1]); + if( !*zParent ) { + zParent = 0; + } + if( Tcl_GetBooleanFromObj(interp, objv[2], &isDefault) ){ + return TCL_ERROR; + } + + rc = sqlite3async_initialize(zParent, isDefault); + if( rc!=SQLITE_OK ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); + return TCL_ERROR; + } + return TCL_OK; +} + +/* +** sqlite3async_shutdown +*/ +static int testAsyncShutdown( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3async_shutdown(); + return TCL_OK; +} + +static Tcl_ThreadCreateType tclWriterThread(ClientData pIsStarted){ + Tcl_MutexLock(&testasync_g_writerMutex); + *((int *)pIsStarted) = 1; + sqlite3async_run(); + Tcl_MutexUnlock(&testasync_g_writerMutex); + Tcl_ExitThread(0); + TCL_THREAD_CREATE_RETURN; +} + +/* +** sqlite3async_start +** +** Start a new writer thread. +*/ +static int testAsyncStart( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + volatile int isStarted = 0; + ClientData threadData = (ClientData)&isStarted; + + Tcl_ThreadId x; + const int nStack = TCL_THREAD_STACK_DEFAULT; + const int flags = TCL_THREAD_NOFLAGS; + int rc; + + rc = Tcl_CreateThread(&x, tclWriterThread, threadData, nStack, flags); + if( rc!=TCL_OK ){ + Tcl_AppendResult(interp, "Tcl_CreateThread() failed", 0); + return TCL_ERROR; + } + + while( isStarted==0 ) { /* Busy loop */ } + return TCL_OK; +} + +/* +** sqlite3async_wait +** +** Wait for the current writer thread to terminate. +** +** If the current writer thread is set to run forever then this +** command would block forever. To prevent that, an error is returned. +*/ +static int testAsyncWait( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int eCond; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + sqlite3async_control(SQLITEASYNC_GET_HALT, &eCond); + if( eCond==SQLITEASYNC_HALT_NEVER ){ + Tcl_AppendResult(interp, "would block forever", (char*)0); + return TCL_ERROR; + } + + Tcl_MutexLock(&testasync_g_writerMutex); + Tcl_MutexUnlock(&testasync_g_writerMutex); + return TCL_OK; +} + +/* +** sqlite3async_control OPTION ?VALUE? +*/ +static int testAsyncControl( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = SQLITE_OK; + int aeOpt[] = { SQLITEASYNC_HALT, SQLITEASYNC_DELAY, SQLITEASYNC_LOCKFILES }; + const char *azOpt[] = { "halt", "delay", "lockfiles", 0 }; + const char *az[] = { "never", "now", "idle", 0 }; + int iVal; + int eOpt; + + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "OPTION ?VALUE?"); + return TCL_ERROR; + } + if( Tcl_GetIndexFromObj(interp, objv[1], azOpt, "option", 0, &eOpt) ){ + return TCL_ERROR; + } + eOpt = aeOpt[eOpt]; + + if( objc==3 ){ + switch( eOpt ){ + case SQLITEASYNC_HALT: { + assert( SQLITEASYNC_HALT_NEVER==0 ); + assert( SQLITEASYNC_HALT_NOW==1 ); + assert( SQLITEASYNC_HALT_IDLE==2 ); + if( Tcl_GetIndexFromObj(interp, objv[2], az, "value", 0, &iVal) ){ + return TCL_ERROR; + } + break; + } + case SQLITEASYNC_DELAY: + if( Tcl_GetIntFromObj(interp, objv[2], &iVal) ){ + return TCL_ERROR; + } + break; + + case SQLITEASYNC_LOCKFILES: + if( Tcl_GetBooleanFromObj(interp, objv[2], &iVal) ){ + return TCL_ERROR; + } + break; + } + + rc = sqlite3async_control(eOpt, iVal); + } + + if( rc==SQLITE_OK ){ + rc = sqlite3async_control( + eOpt==SQLITEASYNC_HALT ? SQLITEASYNC_GET_HALT : + eOpt==SQLITEASYNC_DELAY ? SQLITEASYNC_GET_DELAY : + SQLITEASYNC_GET_LOCKFILES, &iVal); + } + + if( rc!=SQLITE_OK ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); + return TCL_ERROR; + } + + if( eOpt==SQLITEASYNC_HALT ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(az[iVal], -1)); + }else{ + Tcl_SetObjResult(interp, Tcl_NewIntObj(iVal)); + } + + return TCL_OK; +} + +#endif /* SQLITE_ENABLE_ASYNCIO */ + +/* +** This routine registers the custom TCL commands defined in this +** module. This should be the only procedure visible from outside +** of this module. +*/ +int Sqlitetestasync_Init(Tcl_Interp *interp){ +#ifdef SQLITE_ENABLE_ASYNCIO + Tcl_CreateObjCommand(interp,"sqlite3async_start",testAsyncStart,0,0); + Tcl_CreateObjCommand(interp,"sqlite3async_wait",testAsyncWait,0,0); + + Tcl_CreateObjCommand(interp,"sqlite3async_control",testAsyncControl,0,0); + Tcl_CreateObjCommand(interp,"sqlite3async_initialize",testAsyncInit,0,0); + Tcl_CreateObjCommand(interp,"sqlite3async_shutdown",testAsyncShutdown,0,0); +#endif /* SQLITE_ENABLE_ASYNCIO */ + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/src/test_autoext.c b/components/external/SQLite-3.8.1/src/test_autoext.c new file mode 100644 index 0000000000000000000000000000000000000000..a5236d23908d45e00c0cc13dd78d3397692ec167 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_autoext.c @@ -0,0 +1,221 @@ +/* +** 2006 August 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Test extension for testing the sqlite3_auto_extension() function. +*/ +#include "tcl.h" +#include "sqlite3ext.h" + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +SQLITE_EXTENSION_INIT1 + +/* +** The sqr() SQL function returns the square of its input value. +*/ +static void sqrFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + double r = sqlite3_value_double(argv[0]); + sqlite3_result_double(context, r*r); +} + +/* +** This is the entry point to register the extension for the sqr() function. +*/ +static int sqr_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi); + sqlite3_create_function(db, "sqr", 1, SQLITE_ANY, 0, sqrFunc, 0, 0); + return 0; +} + +/* +** The cube() SQL function returns the cube of its input value. +*/ +static void cubeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + double r = sqlite3_value_double(argv[0]); + sqlite3_result_double(context, r*r*r); +} + +/* +** This is the entry point to register the extension for the cube() function. +*/ +static int cube_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi); + sqlite3_create_function(db, "cube", 1, SQLITE_ANY, 0, cubeFunc, 0, 0); + return 0; +} + +/* +** This is a broken extension entry point +*/ +static int broken_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + char *zErr; + SQLITE_EXTENSION_INIT2(pApi); + zErr = sqlite3_mprintf("broken autoext!"); + *pzErrMsg = zErr; + return 1; +} + +/* +** tclcmd: sqlite3_auto_extension_sqr +** +** Register the "sqr" extension to be loaded automatically. +*/ +static int autoExtSqrObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_auto_extension((void*)sqr_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_cancel_auto_extension_sqr +** +** Unregister the "sqr" extension. +*/ +static int cancelAutoExtSqrObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_cancel_auto_extension((void*)sqr_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_auto_extension_cube +** +** Register the "cube" extension to be loaded automatically. +*/ +static int autoExtCubeObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_auto_extension((void*)cube_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_cancel_auto_extension_cube +** +** Unregister the "cube" extension. +*/ +static int cancelAutoExtCubeObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_cancel_auto_extension((void*)cube_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_auto_extension_broken +** +** Register the broken extension to be loaded automatically. +*/ +static int autoExtBrokenObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_auto_extension((void*)broken_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +/* +** tclcmd: sqlite3_cancel_auto_extension_broken +** +** Unregister the broken extension. +*/ +static int cancelAutoExtBrokenObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = sqlite3_cancel_auto_extension((void*)broken_init); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return SQLITE_OK; +} + +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + + +/* +** tclcmd: sqlite3_reset_auto_extension +** +** Reset all auto-extensions +*/ +static int resetAutoExtObjCmd( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_reset_auto_extension(); + return SQLITE_OK; +} + + +/* +** This procedure registers the TCL procs defined in this file. +*/ +int Sqlitetest_autoext_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_LOAD_EXTENSION + Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_sqr", + autoExtSqrObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_cube", + autoExtCubeObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_broken", + autoExtBrokenObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_cancel_auto_extension_sqr", + cancelAutoExtSqrObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_cancel_auto_extension_cube", + cancelAutoExtCubeObjCmd, 0, 0); + Tcl_CreateObjCommand(interp, "sqlite3_cancel_auto_extension_broken", + cancelAutoExtBrokenObjCmd, 0, 0); +#endif + Tcl_CreateObjCommand(interp, "sqlite3_reset_auto_extension", + resetAutoExtObjCmd, 0, 0); + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/src/test_backup.c b/components/external/SQLite-3.8.1/src/test_backup.c new file mode 100644 index 0000000000000000000000000000000000000000..e967424a290f738aecfdac578e9b87a4c4ae8d7f --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_backup.c @@ -0,0 +1,150 @@ +/* +** 2009 January 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains test logic for the sqlite3_backup() interface. +** +*/ + +#include "tcl.h" +#include +#include + +/* These functions are implemented in main.c. */ +extern const char *sqlite3ErrName(int); + +/* These functions are implemented in test1.c. */ +extern int getDbPointer(Tcl_Interp *, const char *, sqlite3 **); + +static int backupTestCmd( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const*objv +){ + enum BackupSubCommandEnum { + BACKUP_STEP, BACKUP_FINISH, BACKUP_REMAINING, BACKUP_PAGECOUNT + }; + struct BackupSubCommand { + const char *zCmd; + enum BackupSubCommandEnum eCmd; + int nArg; + const char *zArg; + } aSub[] = { + {"step", BACKUP_STEP , 1, "npage" }, + {"finish", BACKUP_FINISH , 0, "" }, + {"remaining", BACKUP_REMAINING , 0, "" }, + {"pagecount", BACKUP_PAGECOUNT , 0, "" }, + {0, 0, 0, 0} + }; + + sqlite3_backup *p = (sqlite3_backup *)clientData; + int iCmd; + int rc; + + rc = Tcl_GetIndexFromObjStruct( + interp, objv[1], aSub, sizeof(aSub[0]), "option", 0, &iCmd + ); + if( rc!=TCL_OK ){ + return rc; + } + if( objc!=(2 + aSub[iCmd].nArg) ){ + Tcl_WrongNumArgs(interp, 2, objv, aSub[iCmd].zArg); + return TCL_ERROR; + } + + switch( aSub[iCmd].eCmd ){ + + case BACKUP_FINISH: { + const char *zCmdName; + Tcl_CmdInfo cmdInfo; + zCmdName = Tcl_GetString(objv[0]); + Tcl_GetCommandInfo(interp, zCmdName, &cmdInfo); + cmdInfo.deleteProc = 0; + Tcl_SetCommandInfo(interp, zCmdName, &cmdInfo); + Tcl_DeleteCommand(interp, zCmdName); + + rc = sqlite3_backup_finish(p); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + break; + } + + case BACKUP_STEP: { + int nPage; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &nPage) ){ + return TCL_ERROR; + } + rc = sqlite3_backup_step(p, nPage); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + break; + } + + case BACKUP_REMAINING: + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_backup_remaining(p))); + break; + + case BACKUP_PAGECOUNT: + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_backup_pagecount(p))); + break; + } + + return TCL_OK; +} + +static void backupTestFinish(ClientData clientData){ + sqlite3_backup *pBackup = (sqlite3_backup *)clientData; + sqlite3_backup_finish(pBackup); +} + +/* +** sqlite3_backup CMDNAME DESTHANDLE DESTNAME SRCHANDLE SRCNAME +** +*/ +static int backupTestInit( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const*objv +){ + sqlite3_backup *pBackup; + sqlite3 *pDestDb; + sqlite3 *pSrcDb; + const char *zDestName; + const char *zSrcName; + const char *zCmd; + + if( objc!=6 ){ + Tcl_WrongNumArgs( + interp, 1, objv, "CMDNAME DESTHANDLE DESTNAME SRCHANDLE SRCNAME" + ); + return TCL_ERROR; + } + + zCmd = Tcl_GetString(objv[1]); + getDbPointer(interp, Tcl_GetString(objv[2]), &pDestDb); + zDestName = Tcl_GetString(objv[3]); + getDbPointer(interp, Tcl_GetString(objv[4]), &pSrcDb); + zSrcName = Tcl_GetString(objv[5]); + + pBackup = sqlite3_backup_init(pDestDb, zDestName, pSrcDb, zSrcName); + if( !pBackup ){ + Tcl_AppendResult(interp, "sqlite3_backup_init() failed", 0); + return TCL_ERROR; + } + + Tcl_CreateObjCommand(interp, zCmd, backupTestCmd, pBackup, backupTestFinish); + Tcl_SetObjResult(interp, objv[1]); + return TCL_OK; +} + +int Sqlitetestbackup_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "sqlite3_backup", backupTestInit, 0, 0); + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/src/test_btree.c b/components/external/SQLite-3.8.1/src/test_btree.c new file mode 100644 index 0000000000000000000000000000000000000000..db72889b2afb6272828dda866dccf122a49a7299 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_btree.c @@ -0,0 +1,62 @@ +/* +** 2007 May 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing the btree.c module in SQLite. This code +** is not included in the SQLite library. It is used for automated +** testing of the SQLite library. +*/ +#include "btreeInt.h" +#include + +/* +** Usage: sqlite3_shared_cache_report +** +** Return a list of file that are shared and the number of +** references to each file. +*/ +int sqlite3BtreeSharedCacheReport( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_OMIT_SHARED_CACHE + extern BtShared *sqlite3SharedCacheList; + BtShared *pBt; + Tcl_Obj *pRet = Tcl_NewObj(); + for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ + const char *zFile = sqlite3PagerFilename(pBt->pPager, 1); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(zFile, -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(pBt->nRef)); + } + Tcl_SetObjResult(interp, pRet); +#endif + return TCL_OK; +} + +/* +** Print debugging information about all cursors to standard output. +*/ +void sqlite3BtreeCursorList(Btree *p){ +#ifdef SQLITE_DEBUG + BtCursor *pCur; + BtShared *pBt = p->pBt; + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ + MemPage *pPage = pCur->apPage[pCur->iPage]; + char *zMode = pCur->wrFlag ? "rw" : "ro"; + sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n", + pCur, pCur->pgnoRoot, zMode, + pPage ? pPage->pgno : 0, pCur->aiIdx[pCur->iPage], + (pCur->eState==CURSOR_VALID) ? "" : " eof" + ); + } +#endif +} diff --git a/components/external/SQLite-3.8.1/src/test_config.c b/components/external/SQLite-3.8.1/src/test_config.c new file mode 100644 index 0000000000000000000000000000000000000000..de1822e3b13143d97cc03acfdcaf115e3628b9d9 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_config.c @@ -0,0 +1,656 @@ +/* +** 2007 May 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used for testing the SQLite system. +** None of the code in this file goes into a deliverable build. +** +** The focus of this file is providing the TCL testing layer +** access to compile-time constants. +*/ + +#include "sqliteLimit.h" + +#include "sqliteInt.h" +#include "tcl.h" +#include +#include + +/* +** Macro to stringify the results of the evaluation a pre-processor +** macro. i.e. so that STRINGVALUE(SQLITE_NOMEM) -> "7". +*/ +#define STRINGVALUE2(x) #x +#define STRINGVALUE(x) STRINGVALUE2(x) + +/* +** This routine sets entries in the global ::sqlite_options() array variable +** according to the compile-time configuration of the database. Test +** procedures use this to determine when tests should be omitted. +*/ +static void set_options(Tcl_Interp *interp){ +#ifdef HAVE_MALLOC_USABLE_SIZE + Tcl_SetVar2(interp, "sqlite_options", "malloc_usable_size", "1", + TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "malloc_usable_size", "0", + TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_32BIT_ROWID + Tcl_SetVar2(interp, "sqlite_options", "rowid32", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "rowid32", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_CASE_SENSITIVE_LIKE + Tcl_SetVar2(interp, "sqlite_options","casesensitivelike","1",TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options","casesensitivelike","0",TCL_GLOBAL_ONLY); +#endif + +#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT + Tcl_SetVar2(interp, "sqlite_options", "curdir", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "curdir", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DEBUG + Tcl_SetVar2(interp, "sqlite_options", "debug", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "debug", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DIRECT_OVERFLOW_READ + Tcl_SetVar2(interp, "sqlite_options", "direct_read", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "direct_read", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DISABLE_DIRSYNC + Tcl_SetVar2(interp, "sqlite_options", "dirsync", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "dirsync", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DISABLE_LFS + Tcl_SetVar2(interp, "sqlite_options", "lfs", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "lfs", "1", TCL_GLOBAL_ONLY); +#endif + +#if SQLITE_MAX_MMAP_SIZE>0 + Tcl_SetVar2(interp, "sqlite_options", "mmap", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mmap", "0", TCL_GLOBAL_ONLY); +#endif + +#if 1 /* def SQLITE_MEMDEBUG */ + Tcl_SetVar2(interp, "sqlite_options", "memdebug", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "memdebug", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_8_3_NAMES + Tcl_SetVar2(interp, "sqlite_options", "8_3_names", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "8_3_names", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_MEMSYS3 + Tcl_SetVar2(interp, "sqlite_options", "mem3", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mem3", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_MEMSYS5 + Tcl_SetVar2(interp, "sqlite_options", "mem5", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mem5", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_MUTEX_OMIT + Tcl_SetVar2(interp, "sqlite_options", "mutex", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mutex", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_MUTEX_NOOP + Tcl_SetVar2(interp, "sqlite_options", "mutex_noop", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "mutex_noop", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_ALTERTABLE + Tcl_SetVar2(interp, "sqlite_options", "altertable", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "altertable", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_ANALYZE + Tcl_SetVar2(interp, "sqlite_options", "analyze", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "analyze", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + Tcl_SetVar2(interp, "sqlite_options", "atomicwrite", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "atomicwrite", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_ATTACH + Tcl_SetVar2(interp, "sqlite_options", "attach", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "attach", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTHORIZATION + Tcl_SetVar2(interp, "sqlite_options", "auth", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "auth", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTOINCREMENT + Tcl_SetVar2(interp, "sqlite_options", "autoinc", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "autoinc", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTOMATIC_INDEX + Tcl_SetVar2(interp, "sqlite_options", "autoindex", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "autoindex", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTORESET + Tcl_SetVar2(interp, "sqlite_options", "autoreset", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "autoreset", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_AUTOVACUUM + Tcl_SetVar2(interp, "sqlite_options", "autovacuum", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "autovacuum", "1", TCL_GLOBAL_ONLY); +#endif /* SQLITE_OMIT_AUTOVACUUM */ +#if !defined(SQLITE_DEFAULT_AUTOVACUUM) + Tcl_SetVar2(interp,"sqlite_options","default_autovacuum","0",TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "default_autovacuum", + STRINGVALUE(SQLITE_DEFAULT_AUTOVACUUM), TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION + Tcl_SetVar2(interp, "sqlite_options", "between_opt", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "between_opt", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_BUILTIN_TEST + Tcl_SetVar2(interp, "sqlite_options", "builtin_test", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "builtin_test", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_BLOB_LITERAL + Tcl_SetVar2(interp, "sqlite_options", "bloblit", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "bloblit", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_CAST + Tcl_SetVar2(interp, "sqlite_options", "cast", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "cast", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_CHECK + Tcl_SetVar2(interp, "sqlite_options", "check", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "check", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_COLUMN_METADATA + Tcl_SetVar2(interp, "sqlite_options", "columnmetadata", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "columnmetadata", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK + Tcl_SetVar2(interp, "sqlite_options", "oversize_cell_check", "1", + TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "oversize_cell_check", "0", + TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS + Tcl_SetVar2(interp, "sqlite_options", "compileoption_diags", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "compileoption_diags", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_COMPLETE + Tcl_SetVar2(interp, "sqlite_options", "complete", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "complete", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_COMPOUND_SELECT + Tcl_SetVar2(interp, "sqlite_options", "compound", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "compound", "1", TCL_GLOBAL_ONLY); +#endif + + Tcl_SetVar2(interp, "sqlite_options", "conflict", "1", TCL_GLOBAL_ONLY); + +#if SQLITE_OS_UNIX + Tcl_SetVar2(interp, "sqlite_options", "crashtest", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "crashtest", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_DATETIME_FUNCS + Tcl_SetVar2(interp, "sqlite_options", "datetime", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "datetime", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_DECLTYPE + Tcl_SetVar2(interp, "sqlite_options", "decltype", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "decltype", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_DEPRECATED + Tcl_SetVar2(interp, "sqlite_options", "deprecated", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "deprecated", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_DISKIO + Tcl_SetVar2(interp, "sqlite_options", "diskio", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "diskio", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_EXPLAIN + Tcl_SetVar2(interp, "sqlite_options", "explain", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "explain", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_FLOATING_POINT + Tcl_SetVar2(interp, "sqlite_options", "floatingpoint", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "floatingpoint", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_FOREIGN_KEY + Tcl_SetVar2(interp, "sqlite_options", "foreignkey", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "foreignkey", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_FTS1 + Tcl_SetVar2(interp, "sqlite_options", "fts1", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts1", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_FTS2 + Tcl_SetVar2(interp, "sqlite_options", "fts2", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts2", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_FTS3 + Tcl_SetVar2(interp, "sqlite_options", "fts3", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts3", "0", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_ENABLE_FTS4_UNICODE61) + Tcl_SetVar2(interp, "sqlite_options", "fts3_unicode", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts3_unicode", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_DISABLE_FTS4_DEFERRED + Tcl_SetVar2(interp, "sqlite_options", "fts4_deferred", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "fts4_deferred", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_GET_TABLE + Tcl_SetVar2(interp, "sqlite_options", "gettable", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "gettable", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_ICU + Tcl_SetVar2(interp, "sqlite_options", "icu", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "icu", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_INCRBLOB + Tcl_SetVar2(interp, "sqlite_options", "incrblob", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "incrblob", "1", TCL_GLOBAL_ONLY); +#endif /* SQLITE_OMIT_AUTOVACUUM */ + +#ifdef SQLITE_OMIT_INTEGRITY_CHECK + Tcl_SetVar2(interp, "sqlite_options", "integrityck", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "integrityck", "1", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_DEFAULT_FILE_FORMAT) && SQLITE_DEFAULT_FILE_FORMAT==1 + Tcl_SetVar2(interp, "sqlite_options", "legacyformat", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "legacyformat", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION + Tcl_SetVar2(interp, "sqlite_options", "like_opt", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "like_opt", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_LOAD_EXTENSION + Tcl_SetVar2(interp, "sqlite_options", "load_ext", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "load_ext", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_LOCALTIME + Tcl_SetVar2(interp, "sqlite_options", "localtime", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "localtime", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_LOOKASIDE + Tcl_SetVar2(interp, "sqlite_options", "lookaside", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "lookaside", "1", TCL_GLOBAL_ONLY); +#endif + +Tcl_SetVar2(interp, "sqlite_options", "long_double", + sizeof(LONGDOUBLE_TYPE)>sizeof(double) ? "1" : "0", + TCL_GLOBAL_ONLY); + +#ifdef SQLITE_OMIT_MEMORYDB + Tcl_SetVar2(interp, "sqlite_options", "memorydb", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "memorydb", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT + Tcl_SetVar2(interp, "sqlite_options", "memorymanage", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "memorymanage", "0", TCL_GLOBAL_ONLY); +#endif + +Tcl_SetVar2(interp, "sqlite_options", "mergesort", "1", TCL_GLOBAL_ONLY); + +#ifdef SQLITE_OMIT_OR_OPTIMIZATION + Tcl_SetVar2(interp, "sqlite_options", "or_opt", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "or_opt", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_PAGER_PRAGMAS + Tcl_SetVar2(interp, "sqlite_options", "pager_pragmas", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "pager_pragmas", "1", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_OMIT_PRAGMA) || defined(SQLITE_OMIT_FLAG_PRAGMAS) + Tcl_SetVar2(interp, "sqlite_options", "pragma", "0", TCL_GLOBAL_ONLY); + Tcl_SetVar2(interp, "sqlite_options", "integrityck", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "pragma", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_PROGRESS_CALLBACK + Tcl_SetVar2(interp, "sqlite_options", "progress", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "progress", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_REINDEX + Tcl_SetVar2(interp, "sqlite_options", "reindex", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "reindex", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_RTREE + Tcl_SetVar2(interp, "sqlite_options", "rtree", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "rtree", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_RTREE_INT_ONLY + Tcl_SetVar2(interp, "sqlite_options", "rtree_int_only", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "rtree_int_only", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS + Tcl_SetVar2(interp, "sqlite_options", "schema_pragmas", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "schema_pragmas", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS + Tcl_SetVar2(interp, "sqlite_options", "schema_version", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "schema_version", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_ENABLE_STAT4 + Tcl_SetVar2(interp, "sqlite_options", "stat4", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "stat4", "0", TCL_GLOBAL_ONLY); +#endif +#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4) + Tcl_SetVar2(interp, "sqlite_options", "stat3", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "stat3", "0", TCL_GLOBAL_ONLY); +#endif + +#if !defined(SQLITE_ENABLE_LOCKING_STYLE) +# if defined(__APPLE__) +# define SQLITE_ENABLE_LOCKING_STYLE 1 +# else +# define SQLITE_ENABLE_LOCKING_STYLE 0 +# endif +#endif +#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) + Tcl_SetVar2(interp,"sqlite_options","lock_proxy_pragmas","1",TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp,"sqlite_options","lock_proxy_pragmas","0",TCL_GLOBAL_ONLY); +#endif +#if defined(SQLITE_PREFER_PROXY_LOCKING) && defined(__APPLE__) + Tcl_SetVar2(interp,"sqlite_options","prefer_proxy_locking","1",TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp,"sqlite_options","prefer_proxy_locking","0",TCL_GLOBAL_ONLY); +#endif + + +#ifdef SQLITE_OMIT_SHARED_CACHE + Tcl_SetVar2(interp, "sqlite_options", "shared_cache", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "shared_cache", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_SUBQUERY + Tcl_SetVar2(interp, "sqlite_options", "subquery", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "subquery", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_TCL_VARIABLE + Tcl_SetVar2(interp, "sqlite_options", "tclvar", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "tclvar", "1", TCL_GLOBAL_ONLY); +#endif + + Tcl_SetVar2(interp, "sqlite_options", "threadsafe", + STRINGVALUE(SQLITE_THREADSAFE), TCL_GLOBAL_ONLY); + assert( sqlite3_threadsafe()==SQLITE_THREADSAFE ); + +#ifdef SQLITE_OMIT_TEMPDB + Tcl_SetVar2(interp, "sqlite_options", "tempdb", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "tempdb", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_TRACE + Tcl_SetVar2(interp, "sqlite_options", "trace", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "trace", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_TRIGGER + Tcl_SetVar2(interp, "sqlite_options", "trigger", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "trigger", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION + Tcl_SetVar2(interp, "sqlite_options", "truncate_opt", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "truncate_opt", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_UTF16 + Tcl_SetVar2(interp, "sqlite_options", "utf16", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "utf16", "1", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_OMIT_VACUUM) || defined(SQLITE_OMIT_ATTACH) + Tcl_SetVar2(interp, "sqlite_options", "vacuum", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "vacuum", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_VIEW + Tcl_SetVar2(interp, "sqlite_options", "view", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "view", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_VIRTUALTABLE + Tcl_SetVar2(interp, "sqlite_options", "vtab", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "vtab", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_WAL + Tcl_SetVar2(interp, "sqlite_options", "wal", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "wal", "1", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_OMIT_WSD + Tcl_SetVar2(interp, "sqlite_options", "wsd", "0", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "wsd", "1", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) + Tcl_SetVar2(interp, "sqlite_options", "update_delete_limit", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "update_delete_limit", "0", TCL_GLOBAL_ONLY); +#endif + +#if defined(SQLITE_ENABLE_UNLOCK_NOTIFY) + Tcl_SetVar2(interp, "sqlite_options", "unlock_notify", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "unlock_notify", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_SECURE_DELETE + Tcl_SetVar2(interp, "sqlite_options", "secure_delete", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "secure_delete", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef SQLITE_MULTIPLEX_EXT_OVWR + Tcl_SetVar2(interp, "sqlite_options", "multiplex_ext_overwrite", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "multiplex_ext_overwrite", "0", TCL_GLOBAL_ONLY); +#endif + +#ifdef YYTRACKMAXSTACKDEPTH + Tcl_SetVar2(interp, "sqlite_options", "yytrackmaxstackdepth", "1", TCL_GLOBAL_ONLY); +#else + Tcl_SetVar2(interp, "sqlite_options", "yytrackmaxstackdepth", "0", TCL_GLOBAL_ONLY); +#endif + +#define LINKVAR(x) { \ + static const int cv_ ## x = SQLITE_ ## x; \ + Tcl_LinkVar(interp, "SQLITE_" #x, (char *)&(cv_ ## x), \ + TCL_LINK_INT | TCL_LINK_READ_ONLY); } + + LINKVAR( MAX_LENGTH ); + LINKVAR( MAX_COLUMN ); + LINKVAR( MAX_SQL_LENGTH ); + LINKVAR( MAX_EXPR_DEPTH ); + LINKVAR( MAX_COMPOUND_SELECT ); + LINKVAR( MAX_VDBE_OP ); + LINKVAR( MAX_FUNCTION_ARG ); + LINKVAR( MAX_VARIABLE_NUMBER ); + LINKVAR( MAX_PAGE_SIZE ); + LINKVAR( MAX_PAGE_COUNT ); + LINKVAR( MAX_LIKE_PATTERN_LENGTH ); + LINKVAR( MAX_TRIGGER_DEPTH ); + LINKVAR( DEFAULT_TEMP_CACHE_SIZE ); + LINKVAR( DEFAULT_CACHE_SIZE ); + LINKVAR( DEFAULT_PAGE_SIZE ); + LINKVAR( DEFAULT_FILE_FORMAT ); + LINKVAR( MAX_ATTACHED ); + LINKVAR( MAX_DEFAULT_PAGE_SIZE ); + + { + static const int cv_TEMP_STORE = SQLITE_TEMP_STORE; + Tcl_LinkVar(interp, "TEMP_STORE", (char *)&(cv_TEMP_STORE), + TCL_LINK_INT | TCL_LINK_READ_ONLY); + } + +#ifdef _MSC_VER + { + static const int cv__MSC_VER = 1; + Tcl_LinkVar(interp, "_MSC_VER", (char *)&(cv__MSC_VER), + TCL_LINK_INT | TCL_LINK_READ_ONLY); + } +#endif +#ifdef __GNUC__ + { + static const int cv___GNUC__ = 1; + Tcl_LinkVar(interp, "__GNUC__", (char *)&(cv___GNUC__), + TCL_LINK_INT | TCL_LINK_READ_ONLY); + } +#endif +} + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqliteconfig_Init(Tcl_Interp *interp){ + set_options(interp); + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/src/test_demovfs.c b/components/external/SQLite-3.8.1/src/test_demovfs.c new file mode 100644 index 0000000000000000000000000000000000000000..c63b0a8b7a19bc398e1edb5d523757f2a0973e88 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_demovfs.c @@ -0,0 +1,679 @@ +/* +** 2010 April 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements an example of a simple VFS implementation that +** omits complex features often not required or not possible on embedded +** platforms. Code is included to buffer writes to the journal file, +** which can be a significant performance improvement on some embedded +** platforms. +** +** OVERVIEW +** +** The code in this file implements a minimal SQLite VFS that can be +** used on Linux and other posix-like operating systems. The following +** system calls are used: +** +** File-system: access(), unlink(), getcwd() +** File IO: open(), read(), write(), fsync(), close(), fstat() +** Other: sleep(), usleep(), time() +** +** The following VFS features are omitted: +** +** 1. File locking. The user must ensure that there is at most one +** connection to each database when using this VFS. Multiple +** connections to a single shared-cache count as a single connection +** for the purposes of the previous statement. +** +** 2. The loading of dynamic extensions (shared libraries). +** +** 3. Temporary files. The user must configure SQLite to use in-memory +** temp files when using this VFS. The easiest way to do this is to +** compile with: +** +** -DSQLITE_TEMP_STORE=3 +** +** 4. File truncation. As of version 3.6.24, SQLite may run without +** a working xTruncate() call, providing the user does not configure +** SQLite to use "journal_mode=truncate", or use both +** "journal_mode=persist" and ATTACHed databases. +** +** It is assumed that the system uses UNIX-like path-names. Specifically, +** that '/' characters are used to separate path components and that +** a path-name is a relative path unless it begins with a '/'. And that +** no UTF-8 encoded paths are greater than 512 bytes in length. +** +** JOURNAL WRITE-BUFFERING +** +** To commit a transaction to the database, SQLite first writes rollback +** information into the journal file. This usually consists of 4 steps: +** +** 1. The rollback information is sequentially written into the journal +** file, starting at the start of the file. +** 2. The journal file is synced to disk. +** 3. A modification is made to the first few bytes of the journal file. +** 4. The journal file is synced to disk again. +** +** Most of the data is written in step 1 using a series of calls to the +** VFS xWrite() method. The buffers passed to the xWrite() calls are of +** various sizes. For example, as of version 3.6.24, when committing a +** transaction that modifies 3 pages of a database file that uses 4096 +** byte pages residing on a media with 512 byte sectors, SQLite makes +** eleven calls to the xWrite() method to create the rollback journal, +** as follows: +** +** Write offset | Bytes written +** ---------------------------- +** 0 512 +** 512 4 +** 516 4096 +** 4612 4 +** 4616 4 +** 4620 4096 +** 8716 4 +** 8720 4 +** 8724 4096 +** 12820 4 +** ++++++++++++SYNC+++++++++++ +** 0 12 +** ++++++++++++SYNC+++++++++++ +** +** On many operating systems, this is an efficient way to write to a file. +** However, on some embedded systems that do not cache writes in OS +** buffers it is much more efficient to write data in blocks that are +** an integer multiple of the sector-size in size and aligned at the +** start of a sector. +** +** To work around this, the code in this file allocates a fixed size +** buffer of SQLITE_DEMOVFS_BUFFERSZ using sqlite3_malloc() whenever a +** journal file is opened. It uses the buffer to coalesce sequential +** writes into aligned SQLITE_DEMOVFS_BUFFERSZ blocks. When SQLite +** invokes the xSync() method to sync the contents of the file to disk, +** all accumulated data is written out, even if it does not constitute +** a complete block. This means the actual IO to create the rollback +** journal for the example transaction above is this: +** +** Write offset | Bytes written +** ---------------------------- +** 0 8192 +** 8192 4632 +** ++++++++++++SYNC+++++++++++ +** 0 12 +** ++++++++++++SYNC+++++++++++ +** +** Much more efficient if the underlying OS is not caching write +** operations. +*/ + +#if !defined(SQLITE_TEST) || SQLITE_OS_UNIX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* +** Size of the write buffer used by journal files in bytes. +*/ +#ifndef SQLITE_DEMOVFS_BUFFERSZ +# define SQLITE_DEMOVFS_BUFFERSZ 8192 +#endif + +/* +** The maximum pathname length supported by this VFS. +*/ +#define MAXPATHNAME 512 + +/* +** When using this VFS, the sqlite3_file* handles that SQLite uses are +** actually pointers to instances of type DemoFile. +*/ +typedef struct DemoFile DemoFile; +struct DemoFile { + sqlite3_file base; /* Base class. Must be first. */ + int fd; /* File descriptor */ + + char *aBuffer; /* Pointer to malloc'd buffer */ + int nBuffer; /* Valid bytes of data in zBuffer */ + sqlite3_int64 iBufferOfst; /* Offset in file of zBuffer[0] */ +}; + +/* +** Write directly to the file passed as the first argument. Even if the +** file has a write-buffer (DemoFile.aBuffer), ignore it. +*/ +static int demoDirectWrite( + DemoFile *p, /* File handle */ + const void *zBuf, /* Buffer containing data to write */ + int iAmt, /* Size of data to write in bytes */ + sqlite_int64 iOfst /* File offset to write to */ +){ + off_t ofst; /* Return value from lseek() */ + size_t nWrite; /* Return value from write() */ + + ofst = lseek(p->fd, iOfst, SEEK_SET); + if( ofst!=iOfst ){ + return SQLITE_IOERR_WRITE; + } + + nWrite = write(p->fd, zBuf, iAmt); + if( nWrite!=iAmt ){ + return SQLITE_IOERR_WRITE; + } + + return SQLITE_OK; +} + +/* +** Flush the contents of the DemoFile.aBuffer buffer to disk. This is a +** no-op if this particular file does not have a buffer (i.e. it is not +** a journal file) or if the buffer is currently empty. +*/ +static int demoFlushBuffer(DemoFile *p){ + int rc = SQLITE_OK; + if( p->nBuffer ){ + rc = demoDirectWrite(p, p->aBuffer, p->nBuffer, p->iBufferOfst); + p->nBuffer = 0; + } + return rc; +} + +/* +** Close a file. +*/ +static int demoClose(sqlite3_file *pFile){ + int rc; + DemoFile *p = (DemoFile*)pFile; + rc = demoFlushBuffer(p); + sqlite3_free(p->aBuffer); + close(p->fd); + return rc; +} + +/* +** Read data from a file. +*/ +static int demoRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + DemoFile *p = (DemoFile*)pFile; + off_t ofst; /* Return value from lseek() */ + int nRead; /* Return value from read() */ + int rc; /* Return code from demoFlushBuffer() */ + + /* Flush any data in the write buffer to disk in case this operation + ** is trying to read data the file-region currently cached in the buffer. + ** It would be possible to detect this case and possibly save an + ** unnecessary write here, but in practice SQLite will rarely read from + ** a journal file when there is data cached in the write-buffer. + */ + rc = demoFlushBuffer(p); + if( rc!=SQLITE_OK ){ + return rc; + } + + ofst = lseek(p->fd, iOfst, SEEK_SET); + if( ofst!=iOfst ){ + return SQLITE_IOERR_READ; + } + nRead = read(p->fd, zBuf, iAmt); + + if( nRead==iAmt ){ + return SQLITE_OK; + }else if( nRead>=0 ){ + return SQLITE_IOERR_SHORT_READ; + } + + return SQLITE_IOERR_READ; +} + +/* +** Write data to a crash-file. +*/ +static int demoWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + DemoFile *p = (DemoFile*)pFile; + + if( p->aBuffer ){ + char *z = (char *)zBuf; /* Pointer to remaining data to write */ + int n = iAmt; /* Number of bytes at z */ + sqlite3_int64 i = iOfst; /* File offset to write to */ + + while( n>0 ){ + int nCopy; /* Number of bytes to copy into buffer */ + + /* If the buffer is full, or if this data is not being written directly + ** following the data already buffered, flush the buffer. Flushing + ** the buffer is a no-op if it is empty. + */ + if( p->nBuffer==SQLITE_DEMOVFS_BUFFERSZ || p->iBufferOfst+p->nBuffer!=i ){ + int rc = demoFlushBuffer(p); + if( rc!=SQLITE_OK ){ + return rc; + } + } + assert( p->nBuffer==0 || p->iBufferOfst+p->nBuffer==i ); + p->iBufferOfst = i - p->nBuffer; + + /* Copy as much data as possible into the buffer. */ + nCopy = SQLITE_DEMOVFS_BUFFERSZ - p->nBuffer; + if( nCopy>n ){ + nCopy = n; + } + memcpy(&p->aBuffer[p->nBuffer], z, nCopy); + p->nBuffer += nCopy; + + n -= nCopy; + i += nCopy; + z += nCopy; + } + }else{ + return demoDirectWrite(p, zBuf, iAmt, iOfst); + } + + return SQLITE_OK; +} + +/* +** Truncate a file. This is a no-op for this VFS (see header comments at +** the top of the file). +*/ +static int demoTruncate(sqlite3_file *pFile, sqlite_int64 size){ +#if 0 + if( ftruncate(((DemoFile *)pFile)->fd, size) ) return SQLITE_IOERR_TRUNCATE; +#endif + return SQLITE_OK; +} + +/* +** Sync the contents of the file to the persistent media. +*/ +static int demoSync(sqlite3_file *pFile, int flags){ + DemoFile *p = (DemoFile*)pFile; + int rc; + + rc = demoFlushBuffer(p); + if( rc!=SQLITE_OK ){ + return rc; + } + + rc = fsync(p->fd); + return (rc==0 ? SQLITE_OK : SQLITE_IOERR_FSYNC); +} + +/* +** Write the size of the file in bytes to *pSize. +*/ +static int demoFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + DemoFile *p = (DemoFile*)pFile; + int rc; /* Return code from fstat() call */ + struct stat sStat; /* Output of fstat() call */ + + /* Flush the contents of the buffer to disk. As with the flush in the + ** demoRead() method, it would be possible to avoid this and save a write + ** here and there. But in practice this comes up so infrequently it is + ** not worth the trouble. + */ + rc = demoFlushBuffer(p); + if( rc!=SQLITE_OK ){ + return rc; + } + + rc = fstat(p->fd, &sStat); + if( rc!=0 ) return SQLITE_IOERR_FSTAT; + *pSize = sStat.st_size; + return SQLITE_OK; +} + +/* +** Locking functions. The xLock() and xUnlock() methods are both no-ops. +** The xCheckReservedLock() always indicates that no other process holds +** a reserved lock on the database file. This ensures that if a hot-journal +** file is found in the file-system it is rolled back. +*/ +static int demoLock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} +static int demoUnlock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} +static int demoCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + *pResOut = 0; + return SQLITE_OK; +} + +/* +** No xFileControl() verbs are implemented by this VFS. +*/ +static int demoFileControl(sqlite3_file *pFile, int op, void *pArg){ + return SQLITE_OK; +} + +/* +** The xSectorSize() and xDeviceCharacteristics() methods. These two +** may return special values allowing SQLite to optimize file-system +** access to some extent. But it is also safe to simply return 0. +*/ +static int demoSectorSize(sqlite3_file *pFile){ + return 0; +} +static int demoDeviceCharacteristics(sqlite3_file *pFile){ + return 0; +} + +/* +** Open a file handle. +*/ +static int demoOpen( + sqlite3_vfs *pVfs, /* VFS */ + const char *zName, /* File to open, or 0 for a temp file */ + sqlite3_file *pFile, /* Pointer to DemoFile struct to populate */ + int flags, /* Input SQLITE_OPEN_XXX flags */ + int *pOutFlags /* Output SQLITE_OPEN_XXX flags (or NULL) */ +){ + static const sqlite3_io_methods demoio = { + 1, /* iVersion */ + demoClose, /* xClose */ + demoRead, /* xRead */ + demoWrite, /* xWrite */ + demoTruncate, /* xTruncate */ + demoSync, /* xSync */ + demoFileSize, /* xFileSize */ + demoLock, /* xLock */ + demoUnlock, /* xUnlock */ + demoCheckReservedLock, /* xCheckReservedLock */ + demoFileControl, /* xFileControl */ + demoSectorSize, /* xSectorSize */ + demoDeviceCharacteristics /* xDeviceCharacteristics */ + }; + + DemoFile *p = (DemoFile*)pFile; /* Populate this structure */ + int oflags = 0; /* flags to pass to open() call */ + char *aBuf = 0; + + if( zName==0 ){ + return SQLITE_IOERR; + } + + if( flags&SQLITE_OPEN_MAIN_JOURNAL ){ + aBuf = (char *)sqlite3_malloc(SQLITE_DEMOVFS_BUFFERSZ); + if( !aBuf ){ + return SQLITE_NOMEM; + } + } + + if( flags&SQLITE_OPEN_EXCLUSIVE ) oflags |= O_EXCL; + if( flags&SQLITE_OPEN_CREATE ) oflags |= O_CREAT; + if( flags&SQLITE_OPEN_READONLY ) oflags |= O_RDONLY; + if( flags&SQLITE_OPEN_READWRITE ) oflags |= O_RDWR; + + memset(p, 0, sizeof(DemoFile)); + p->fd = open(zName, oflags, 0600); + if( p->fd<0 ){ + sqlite3_free(aBuf); + return SQLITE_CANTOPEN; + } + p->aBuffer = aBuf; + + if( pOutFlags ){ + *pOutFlags = flags; + } + p->base.pMethods = &demoio; + return SQLITE_OK; +} + +/* +** Delete the file identified by argument zPath. If the dirSync parameter +** is non-zero, then ensure the file-system modification to delete the +** file has been synced to disk before returning. +*/ +static int demoDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc; /* Return code */ + + rc = unlink(zPath); + if( rc!=0 && errno==ENOENT ) return SQLITE_OK; + + if( rc==0 && dirSync ){ + int dfd; /* File descriptor open on directory */ + int i; /* Iterator variable */ + char zDir[MAXPATHNAME+1]; /* Name of directory containing file zPath */ + + /* Figure out the directory name from the path of the file deleted. */ + sqlite3_snprintf(MAXPATHNAME, zDir, "%s", zPath); + zDir[MAXPATHNAME] = '\0'; + for(i=strlen(zDir); i>1 && zDir[i]!='/'; i++); + zDir[i] = '\0'; + + /* Open a file-descriptor on the directory. Sync. Close. */ + dfd = open(zDir, O_RDONLY, 0); + if( dfd<0 ){ + rc = -1; + }else{ + rc = fsync(dfd); + close(dfd); + } + } + return (rc==0 ? SQLITE_OK : SQLITE_IOERR_DELETE); +} + +#ifndef F_OK +# define F_OK 0 +#endif +#ifndef R_OK +# define R_OK 4 +#endif +#ifndef W_OK +# define W_OK 2 +#endif + +/* +** Query the file-system to see if the named file exists, is readable or +** is both readable and writable. +*/ +static int demoAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + int rc; /* access() return code */ + int eAccess = F_OK; /* Second argument to access() */ + + assert( flags==SQLITE_ACCESS_EXISTS /* access(zPath, F_OK) */ + || flags==SQLITE_ACCESS_READ /* access(zPath, R_OK) */ + || flags==SQLITE_ACCESS_READWRITE /* access(zPath, R_OK|W_OK) */ + ); + + if( flags==SQLITE_ACCESS_READWRITE ) eAccess = R_OK|W_OK; + if( flags==SQLITE_ACCESS_READ ) eAccess = R_OK; + + rc = access(zPath, eAccess); + *pResOut = (rc==0); + return SQLITE_OK; +} + +/* +** Argument zPath points to a nul-terminated string containing a file path. +** If zPath is an absolute path, then it is copied as is into the output +** buffer. Otherwise, if it is a relative path, then the equivalent full +** path is written to the output buffer. +** +** This function assumes that paths are UNIX style. Specifically, that: +** +** 1. Path components are separated by a '/'. and +** 2. Full paths begin with a '/' character. +*/ +static int demoFullPathname( + sqlite3_vfs *pVfs, /* VFS */ + const char *zPath, /* Input path (possibly a relative path) */ + int nPathOut, /* Size of output buffer in bytes */ + char *zPathOut /* Pointer to output buffer */ +){ + char zDir[MAXPATHNAME+1]; + if( zPath[0]=='/' ){ + zDir[0] = '\0'; + }else{ + if( getcwd(zDir, sizeof(zDir))==0 ) return SQLITE_IOERR; + } + zDir[MAXPATHNAME] = '\0'; + + sqlite3_snprintf(nPathOut, zPathOut, "%s/%s", zDir, zPath); + zPathOut[nPathOut-1] = '\0'; + + return SQLITE_OK; +} + +/* +** The following four VFS methods: +** +** xDlOpen +** xDlError +** xDlSym +** xDlClose +** +** are supposed to implement the functionality needed by SQLite to load +** extensions compiled as shared objects. This simple VFS does not support +** this functionality, so the following functions are no-ops. +*/ +static void *demoDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return 0; +} +static void demoDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + sqlite3_snprintf(nByte, zErrMsg, "Loadable extensions are not supported"); + zErrMsg[nByte-1] = '\0'; +} +static void (*demoDlSym(sqlite3_vfs *pVfs, void *pH, const char *z))(void){ + return 0; +} +static void demoDlClose(sqlite3_vfs *pVfs, void *pHandle){ + return; +} + +/* +** Parameter zByte points to a buffer nByte bytes in size. Populate this +** buffer with pseudo-random data. +*/ +static int demoRandomness(sqlite3_vfs *pVfs, int nByte, char *zByte){ + return SQLITE_OK; +} + +/* +** Sleep for at least nMicro microseconds. Return the (approximate) number +** of microseconds slept for. +*/ +static int demoSleep(sqlite3_vfs *pVfs, int nMicro){ + sleep(nMicro / 1000000); + usleep(nMicro % 1000000); + return nMicro; +} + +/* +** Set *pTime to the current UTC time expressed as a Julian day. Return +** SQLITE_OK if successful, or an error code otherwise. +** +** http://en.wikipedia.org/wiki/Julian_day +** +** This implementation is not very good. The current time is rounded to +** an integer number of seconds. Also, assuming time_t is a signed 32-bit +** value, it will stop working some time in the year 2038 AD (the so-called +** "year 2038" problem that afflicts systems that store time this way). +*/ +static int demoCurrentTime(sqlite3_vfs *pVfs, double *pTime){ + time_t t = time(0); + *pTime = t/86400.0 + 2440587.5; + return SQLITE_OK; +} + +/* +** This function returns a pointer to the VFS implemented in this file. +** To make the VFS available to SQLite: +** +** sqlite3_vfs_register(sqlite3_demovfs(), 0); +*/ +sqlite3_vfs *sqlite3_demovfs(void){ + static sqlite3_vfs demovfs = { + 1, /* iVersion */ + sizeof(DemoFile), /* szOsFile */ + MAXPATHNAME, /* mxPathname */ + 0, /* pNext */ + "demo", /* zName */ + 0, /* pAppData */ + demoOpen, /* xOpen */ + demoDelete, /* xDelete */ + demoAccess, /* xAccess */ + demoFullPathname, /* xFullPathname */ + demoDlOpen, /* xDlOpen */ + demoDlError, /* xDlError */ + demoDlSym, /* xDlSym */ + demoDlClose, /* xDlClose */ + demoRandomness, /* xRandomness */ + demoSleep, /* xSleep */ + demoCurrentTime, /* xCurrentTime */ + }; + return &demovfs; +} + +#endif /* !defined(SQLITE_TEST) || SQLITE_OS_UNIX */ + + +#ifdef SQLITE_TEST + +#include + +#if SQLITE_OS_UNIX +static int register_demovfs( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_vfs_register(sqlite3_demovfs(), 1); + return TCL_OK; +} +static int unregister_demovfs( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_vfs_unregister(sqlite3_demovfs()); + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest_demovfs_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "register_demovfs", register_demovfs, 0, 0); + Tcl_CreateObjCommand(interp, "unregister_demovfs", unregister_demovfs, 0, 0); + return TCL_OK; +} + +#else +int Sqlitetest_demovfs_Init(Tcl_Interp *interp){ return TCL_OK; } +#endif + +#endif /* SQLITE_TEST */ diff --git a/components/external/SQLite-3.8.1/src/test_devsym.c b/components/external/SQLite-3.8.1/src/test_devsym.c new file mode 100644 index 0000000000000000000000000000000000000000..21f0f684d861116770defcdecd532ba3eeaba975 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_devsym.c @@ -0,0 +1,398 @@ +/* +** 2008 Jan 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code that modified the OS layer in order to simulate +** different device types (by overriding the return values of the +** xDeviceCharacteristics() and xSectorSize() methods). +*/ +#if SQLITE_TEST /* This file is used for testing only */ + +#include "sqlite3.h" +#include "sqliteInt.h" + +/* +** Maximum pathname length supported by the devsym backend. +*/ +#define DEVSYM_MAX_PATHNAME 512 + +/* +** Name used to identify this VFS. +*/ +#define DEVSYM_VFS_NAME "devsym" + +typedef struct devsym_file devsym_file; +struct devsym_file { + sqlite3_file base; + sqlite3_file *pReal; +}; + +/* +** Method declarations for devsym_file. +*/ +static int devsymClose(sqlite3_file*); +static int devsymRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int devsymWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); +static int devsymTruncate(sqlite3_file*, sqlite3_int64 size); +static int devsymSync(sqlite3_file*, int flags); +static int devsymFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int devsymLock(sqlite3_file*, int); +static int devsymUnlock(sqlite3_file*, int); +static int devsymCheckReservedLock(sqlite3_file*, int *); +static int devsymFileControl(sqlite3_file*, int op, void *pArg); +static int devsymSectorSize(sqlite3_file*); +static int devsymDeviceCharacteristics(sqlite3_file*); +static int devsymShmLock(sqlite3_file*,int,int,int); +static int devsymShmMap(sqlite3_file*,int,int,int, void volatile **); +static void devsymShmBarrier(sqlite3_file*); +static int devsymShmUnmap(sqlite3_file*,int); + +/* +** Method declarations for devsym_vfs. +*/ +static int devsymOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int devsymDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int devsymAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int devsymFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +static void *devsymDlOpen(sqlite3_vfs*, const char *zFilename); +static void devsymDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*devsymDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void); +static void devsymDlClose(sqlite3_vfs*, void*); +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +static int devsymRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int devsymSleep(sqlite3_vfs*, int microseconds); +static int devsymCurrentTime(sqlite3_vfs*, double*); + +static sqlite3_vfs devsym_vfs = { + 2, /* iVersion */ + sizeof(devsym_file), /* szOsFile */ + DEVSYM_MAX_PATHNAME, /* mxPathname */ + 0, /* pNext */ + DEVSYM_VFS_NAME, /* zName */ + 0, /* pAppData */ + devsymOpen, /* xOpen */ + devsymDelete, /* xDelete */ + devsymAccess, /* xAccess */ + devsymFullPathname, /* xFullPathname */ +#ifndef SQLITE_OMIT_LOAD_EXTENSION + devsymDlOpen, /* xDlOpen */ + devsymDlError, /* xDlError */ + devsymDlSym, /* xDlSym */ + devsymDlClose, /* xDlClose */ +#else + 0, /* xDlOpen */ + 0, /* xDlError */ + 0, /* xDlSym */ + 0, /* xDlClose */ +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + devsymRandomness, /* xRandomness */ + devsymSleep, /* xSleep */ + devsymCurrentTime, /* xCurrentTime */ + 0, /* xGetLastError */ + 0 /* xCurrentTimeInt64 */ +}; + +static sqlite3_io_methods devsym_io_methods = { + 2, /* iVersion */ + devsymClose, /* xClose */ + devsymRead, /* xRead */ + devsymWrite, /* xWrite */ + devsymTruncate, /* xTruncate */ + devsymSync, /* xSync */ + devsymFileSize, /* xFileSize */ + devsymLock, /* xLock */ + devsymUnlock, /* xUnlock */ + devsymCheckReservedLock, /* xCheckReservedLock */ + devsymFileControl, /* xFileControl */ + devsymSectorSize, /* xSectorSize */ + devsymDeviceCharacteristics, /* xDeviceCharacteristics */ + devsymShmMap, /* xShmMap */ + devsymShmLock, /* xShmLock */ + devsymShmBarrier, /* xShmBarrier */ + devsymShmUnmap /* xShmUnmap */ +}; + +struct DevsymGlobal { + sqlite3_vfs *pVfs; + int iDeviceChar; + int iSectorSize; +}; +struct DevsymGlobal g = {0, 0, 512}; + +/* +** Close an devsym-file. +*/ +static int devsymClose(sqlite3_file *pFile){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsClose(p->pReal); +} + +/* +** Read data from an devsym-file. +*/ +static int devsymRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst); +} + +/* +** Write data to an devsym-file. +*/ +static int devsymWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst); +} + +/* +** Truncate an devsym-file. +*/ +static int devsymTruncate(sqlite3_file *pFile, sqlite_int64 size){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsTruncate(p->pReal, size); +} + +/* +** Sync an devsym-file. +*/ +static int devsymSync(sqlite3_file *pFile, int flags){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsSync(p->pReal, flags); +} + +/* +** Return the current file-size of an devsym-file. +*/ +static int devsymFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsFileSize(p->pReal, pSize); +} + +/* +** Lock an devsym-file. +*/ +static int devsymLock(sqlite3_file *pFile, int eLock){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsLock(p->pReal, eLock); +} + +/* +** Unlock an devsym-file. +*/ +static int devsymUnlock(sqlite3_file *pFile, int eLock){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsUnlock(p->pReal, eLock); +} + +/* +** Check if another file-handle holds a RESERVED lock on an devsym-file. +*/ +static int devsymCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsCheckReservedLock(p->pReal, pResOut); +} + +/* +** File control method. For custom operations on an devsym-file. +*/ +static int devsymFileControl(sqlite3_file *pFile, int op, void *pArg){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsFileControl(p->pReal, op, pArg); +} + +/* +** Return the sector-size in bytes for an devsym-file. +*/ +static int devsymSectorSize(sqlite3_file *pFile){ + return g.iSectorSize; +} + +/* +** Return the device characteristic flags supported by an devsym-file. +*/ +static int devsymDeviceCharacteristics(sqlite3_file *pFile){ + return g.iDeviceChar; +} + +/* +** Shared-memory methods are all pass-thrus. +*/ +static int devsymShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsShmLock(p->pReal, ofst, n, flags); +} +static int devsymShmMap( + sqlite3_file *pFile, + int iRegion, + int szRegion, + int isWrite, + void volatile **pp +){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsShmMap(p->pReal, iRegion, szRegion, isWrite, pp); +} +static void devsymShmBarrier(sqlite3_file *pFile){ + devsym_file *p = (devsym_file *)pFile; + sqlite3OsShmBarrier(p->pReal); +} +static int devsymShmUnmap(sqlite3_file *pFile, int delFlag){ + devsym_file *p = (devsym_file *)pFile; + return sqlite3OsShmUnmap(p->pReal, delFlag); +} + + + +/* +** Open an devsym file handle. +*/ +static int devsymOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + devsym_file *p = (devsym_file *)pFile; + p->pReal = (sqlite3_file *)&p[1]; + rc = sqlite3OsOpen(g.pVfs, zName, p->pReal, flags, pOutFlags); + if( p->pReal->pMethods ){ + pFile->pMethods = &devsym_io_methods; + } + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int devsymDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + return sqlite3OsDelete(g.pVfs, zPath, dirSync); +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int devsymAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + return sqlite3OsAccess(g.pVfs, zPath, flags, pResOut); +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (DEVSYM_MAX_PATHNAME+1) bytes. +*/ +static int devsymFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + return sqlite3OsFullPathname(g.pVfs, zPath, nOut, zOut); +} + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *devsymDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return sqlite3OsDlOpen(g.pVfs, zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void devsymDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + sqlite3OsDlError(g.pVfs, nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*devsymDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return sqlite3OsDlSym(g.pVfs, p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void devsymDlClose(sqlite3_vfs *pVfs, void *pHandle){ + sqlite3OsDlClose(g.pVfs, pHandle); +} +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int devsymRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return sqlite3OsRandomness(g.pVfs, nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int devsymSleep(sqlite3_vfs *pVfs, int nMicro){ + return sqlite3OsSleep(g.pVfs, nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int devsymCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + return g.pVfs->xCurrentTime(g.pVfs, pTimeOut); +} + + +/* +** This procedure registers the devsym vfs with SQLite. If the argument is +** true, the devsym vfs becomes the new default vfs. It is the only publicly +** available function in this file. +*/ +void devsym_register(int iDeviceChar, int iSectorSize){ + if( g.pVfs==0 ){ + g.pVfs = sqlite3_vfs_find(0); + devsym_vfs.szOsFile += g.pVfs->szOsFile; + sqlite3_vfs_register(&devsym_vfs, 0); + } + if( iDeviceChar>=0 ){ + g.iDeviceChar = iDeviceChar; + }else{ + g.iDeviceChar = 0; + } + if( iSectorSize>=0 ){ + g.iSectorSize = iSectorSize; + }else{ + g.iSectorSize = 512; + } +} + +#endif diff --git a/components/external/SQLite-3.8.1/src/test_fs.c b/components/external/SQLite-3.8.1/src/test_fs.c new file mode 100644 index 0000000000000000000000000000000000000000..417c81b49f2a44c5f41c8ff6f5d684377f22b184 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_fs.c @@ -0,0 +1,335 @@ +/* +** 2013 Jan 11 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing the virtual table interfaces. This code +** is not included in the SQLite library. It is used for automated +** testing of the SQLite library. +** +** The FS virtual table is created as follows: +** +** CREATE VIRTUAL TABLE tbl USING fs(idx); +** +** where idx is the name of a table in the db with 2 columns. The virtual +** table also has two columns - file path and file contents. +** +** The first column of table idx must be an IPK, and the second contains file +** paths. For example: +** +** CREATE TABLE idx(id INTEGER PRIMARY KEY, path TEXT); +** INSERT INTO idx VALUES(4, '/etc/passwd'); +** +** Adding the row to the idx table automatically creates a row in the +** virtual table with rowid=4, path=/etc/passwd and a text field that +** contains data read from file /etc/passwd on disk. +*/ +#include "sqliteInt.h" +#include "tcl.h" + +#include +#include +#include +#include +#include + +#if SQLITE_OS_UNIX +# include +#endif +#if SQLITE_OS_WIN +# include +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +typedef struct fs_vtab fs_vtab; +typedef struct fs_cursor fs_cursor; + +/* +** A fs virtual-table object +*/ +struct fs_vtab { + sqlite3_vtab base; + sqlite3 *db; + char *zDb; /* Name of db containing zTbl */ + char *zTbl; /* Name of docid->file map table */ +}; + +/* A fs cursor object */ +struct fs_cursor { + sqlite3_vtab_cursor base; + sqlite3_stmt *pStmt; + char *zBuf; + int nBuf; + int nAlloc; +}; + +/* +** This function is the implementation of both the xConnect and xCreate +** methods of the fs virtual table. +** +** The argv[] array contains the following: +** +** argv[0] -> module name ("fs") +** argv[1] -> database name +** argv[2] -> table name +** argv[...] -> other module argument fields. +*/ +static int fsConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + fs_vtab *pVtab; + int nByte; + const char *zTbl; + const char *zDb = argv[1]; + + if( argc!=4 ){ + *pzErr = sqlite3_mprintf("wrong number of arguments"); + return SQLITE_ERROR; + } + zTbl = argv[3]; + + nByte = sizeof(fs_vtab) + (int)strlen(zTbl) + 1 + (int)strlen(zDb) + 1; + pVtab = (fs_vtab *)sqlite3MallocZero( nByte ); + if( !pVtab ) return SQLITE_NOMEM; + + pVtab->zTbl = (char *)&pVtab[1]; + pVtab->zDb = &pVtab->zTbl[strlen(zTbl)+1]; + pVtab->db = db; + memcpy(pVtab->zTbl, zTbl, strlen(zTbl)); + memcpy(pVtab->zDb, zDb, strlen(zDb)); + *ppVtab = &pVtab->base; + sqlite3_declare_vtab(db, "CREATE TABLE xyz(path TEXT, data TEXT)"); + + return SQLITE_OK; +} +/* Note that for this virtual table, the xCreate and xConnect +** methods are identical. */ + +static int fsDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} +/* The xDisconnect and xDestroy methods are also the same */ + +/* +** Open a new fs cursor. +*/ +static int fsOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + fs_cursor *pCur; + pCur = sqlite3MallocZero(sizeof(fs_cursor)); + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Close a fs cursor. +*/ +static int fsClose(sqlite3_vtab_cursor *cur){ + fs_cursor *pCur = (fs_cursor *)cur; + sqlite3_finalize(pCur->pStmt); + sqlite3_free(pCur->zBuf); + sqlite3_free(pCur); + return SQLITE_OK; +} + +static int fsNext(sqlite3_vtab_cursor *cur){ + fs_cursor *pCur = (fs_cursor *)cur; + int rc; + + rc = sqlite3_step(pCur->pStmt); + if( rc==SQLITE_ROW || rc==SQLITE_DONE ) rc = SQLITE_OK; + + return rc; +} + +static int fsFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + int rc; + fs_cursor *pCur = (fs_cursor *)pVtabCursor; + fs_vtab *p = (fs_vtab *)(pVtabCursor->pVtab); + + assert( (idxNum==0 && argc==0) || (idxNum==1 && argc==1) ); + if( idxNum==1 ){ + char *zStmt = sqlite3_mprintf( + "SELECT * FROM %Q.%Q WHERE rowid=?", p->zDb, p->zTbl); + if( !zStmt ) return SQLITE_NOMEM; + rc = sqlite3_prepare_v2(p->db, zStmt, -1, &pCur->pStmt, 0); + sqlite3_free(zStmt); + if( rc==SQLITE_OK ){ + sqlite3_bind_value(pCur->pStmt, 1, argv[0]); + } + }else{ + char *zStmt = sqlite3_mprintf("SELECT * FROM %Q.%Q", p->zDb, p->zTbl); + if( !zStmt ) return SQLITE_NOMEM; + rc = sqlite3_prepare_v2(p->db, zStmt, -1, &pCur->pStmt, 0); + sqlite3_free(zStmt); + } + + if( rc==SQLITE_OK ){ + rc = fsNext(pVtabCursor); + } + return rc; +} + +static int fsColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + fs_cursor *pCur = (fs_cursor*)cur; + + assert( i==0 || i==1 ); + if( i==0 ){ + sqlite3_result_value(ctx, sqlite3_column_value(pCur->pStmt, 0)); + }else{ + const char *zFile = (const char *)sqlite3_column_text(pCur->pStmt, 1); + struct stat sbuf; + int fd; + int n; + + fd = open(zFile, O_RDONLY); + if( fd<0 ) return SQLITE_IOERR; + fstat(fd, &sbuf); + + if( sbuf.st_size>=pCur->nAlloc ){ + int nNew = sbuf.st_size*2; + char *zNew; + if( nNew<1024 ) nNew = 1024; + + zNew = sqlite3Realloc(pCur->zBuf, nNew); + if( zNew==0 ){ + close(fd); + return SQLITE_NOMEM; + } + pCur->zBuf = zNew; + pCur->nAlloc = nNew; + } + + n = (int)read(fd, pCur->zBuf, sbuf.st_size); + close(fd); + if( n!=sbuf.st_size ) return SQLITE_ERROR; + pCur->nBuf = sbuf.st_size; + pCur->zBuf[pCur->nBuf] = '\0'; + + sqlite3_result_text(ctx, pCur->zBuf, -1, SQLITE_TRANSIENT); + } + return SQLITE_OK; +} + +static int fsRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + fs_cursor *pCur = (fs_cursor*)cur; + *pRowid = sqlite3_column_int64(pCur->pStmt, 0); + return SQLITE_OK; +} + +static int fsEof(sqlite3_vtab_cursor *cur){ + fs_cursor *pCur = (fs_cursor*)cur; + return (sqlite3_data_count(pCur->pStmt)==0); +} + +static int fsBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int ii; + + for(ii=0; iinConstraint; ii++){ + struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii]; + if( pCons->iColumn<0 && pCons->usable + && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + struct sqlite3_index_constraint_usage *pUsage; + pUsage = &pIdxInfo->aConstraintUsage[ii]; + pUsage->omit = 0; + pUsage->argvIndex = 1; + pIdxInfo->idxNum = 1; + pIdxInfo->estimatedCost = 1.0; + break; + } + } + + return SQLITE_OK; +} + +/* +** A virtual table module that provides read-only access to a +** Tcl global variable namespace. +*/ +static sqlite3_module fsModule = { + 0, /* iVersion */ + fsConnect, + fsConnect, + fsBestIndex, + fsDisconnect, + fsDisconnect, + fsOpen, /* xOpen - open a cursor */ + fsClose, /* xClose - close a cursor */ + fsFilter, /* xFilter - configure scan constraints */ + fsNext, /* xNext - advance a cursor */ + fsEof, /* xEof - check for end of scan */ + fsColumn, /* xColumn - read data */ + fsRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +/* +** Decode a pointer to an sqlite3 object. +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); + +/* +** Register the echo virtual table module. +*/ +static int register_fs_module( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_create_module(db, "fs", &fsModule, (void *)interp); +#endif + return TCL_OK; +} + +#endif + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetestfs_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "register_fs_module", register_fs_module, 0 }, + }; + int i; + for(i=0; i +#include +#include + +#include "sqliteInt.h" +#include "vdbeInt.h" + + +/* +** Allocate nByte bytes of space using sqlite3_malloc(). If the +** allocation fails, call sqlite3_result_error_nomem() to notify +** the database handle that malloc() has failed. +*/ +static void *testContextMalloc(sqlite3_context *context, int nByte){ + char *z = sqlite3_malloc(nByte); + if( !z && nByte>0 ){ + sqlite3_result_error_nomem(context); + } + return z; +} + +/* +** This function generates a string of random characters. Used for +** generating test data. +*/ +static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){ + static const unsigned char zSrc[] = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + ".-!,:*^+=_|?/<> "; + int iMin, iMax, n, r, i; + unsigned char zBuf[1000]; + + /* It used to be possible to call randstr() with any number of arguments, + ** but now it is registered with SQLite as requiring exactly 2. + */ + assert(argc==2); + + iMin = sqlite3_value_int(argv[0]); + if( iMin<0 ) iMin = 0; + if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1; + iMax = sqlite3_value_int(argv[1]); + if( iMax=sizeof(zBuf) ) iMax = sizeof(zBuf)-1; + n = iMin; + if( iMax>iMin ){ + sqlite3_randomness(sizeof(r), &r); + r &= 0x7fffffff; + n += r%(iMax + 1 - iMin); + } + assert( n='0' && c<='9' ){ + return c - '0'; + }else if( c>='a' && c<='f' ){ + return c - 'a' + 10; + }else if( c>='A' && c<='F' ){ + return c - 'A' + 10; + } + return 0; +} + +/* +** Convert hex to binary. +*/ +static void testHexToBin(const char *zIn, char *zOut){ + while( zIn[0] && zIn[1] ){ + *(zOut++) = (testHexChar(zIn[0])<<4) + testHexChar(zIn[1]); + zIn += 2; + } +} + +/* +** hex_to_utf16be(HEX) +** +** Convert the input string from HEX into binary. Then return the +** result using sqlite3_result_text16le(). +*/ +#ifndef SQLITE_OMIT_UTF16 +static void testHexToUtf16be( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + int n; + const char *zIn; + char *zOut; + assert( nArg==1 ); + n = sqlite3_value_bytes(argv[0]); + zIn = (const char*)sqlite3_value_text(argv[0]); + zOut = sqlite3_malloc( n/2 ); + if( zOut==0 ){ + sqlite3_result_error_nomem(pCtx); + }else{ + testHexToBin(zIn, zOut); + sqlite3_result_text16be(pCtx, zOut, n/2, sqlite3_free); + } +} +#endif + +/* +** hex_to_utf8(HEX) +** +** Convert the input string from HEX into binary. Then return the +** result using sqlite3_result_text16le(). +*/ +static void testHexToUtf8( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + int n; + const char *zIn; + char *zOut; + assert( nArg==1 ); + n = sqlite3_value_bytes(argv[0]); + zIn = (const char*)sqlite3_value_text(argv[0]); + zOut = sqlite3_malloc( n/2 ); + if( zOut==0 ){ + sqlite3_result_error_nomem(pCtx); + }else{ + testHexToBin(zIn, zOut); + sqlite3_result_text(pCtx, zOut, n/2, sqlite3_free); + } +} + +/* +** hex_to_utf16le(HEX) +** +** Convert the input string from HEX into binary. Then return the +** result using sqlite3_result_text16le(). +*/ +#ifndef SQLITE_OMIT_UTF16 +static void testHexToUtf16le( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **argv +){ + int n; + const char *zIn; + char *zOut; + assert( nArg==1 ); + n = sqlite3_value_bytes(argv[0]); + zIn = (const char*)sqlite3_value_text(argv[0]); + zOut = sqlite3_malloc( n/2 ); + if( zOut==0 ){ + sqlite3_result_error_nomem(pCtx); + }else{ + testHexToBin(zIn, zOut); + sqlite3_result_text16le(pCtx, zOut, n/2, sqlite3_free); + } +} +#endif + +/* +** SQL function: real2hex(X) +** +** If argument X is a real number, then convert it into a string which is +** the big-endian hexadecimal representation of the ieee754 encoding of +** that number. If X is not a real number, return NULL. +*/ +static void real2hex( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + union { + sqlite3_uint64 i; + double r; + unsigned char x[8]; + } v; + char zOut[20]; + int i; + int bigEndian; + v.i = 1; + bigEndian = v.x[0]==0; + v.r = sqlite3_value_double(argv[0]); + for(i=0; i<8; i++){ + if( bigEndian ){ + zOut[i*2] = "0123456789abcdef"[v.x[i]>>4]; + zOut[i*2+1] = "0123456789abcdef"[v.x[i]&0xf]; + }else{ + zOut[14-i*2] = "0123456789abcdef"[v.x[i]>>4]; + zOut[14-i*2+1] = "0123456789abcdef"[v.x[i]&0xf]; + } + } + zOut[16] = 0; + sqlite3_result_text(context, zOut, -1, SQLITE_TRANSIENT); +} + +/* +** tclcmd: test_extract(record, field) +** +** This function implements an SQL user-function that accepts a blob +** containing a formatted database record as the first argument. The +** second argument is the index of the field within that record to +** extract and return. +*/ +static void test_extract( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + u8 *pRec; + u8 *pEndHdr; /* Points to one byte past record header */ + u8 *pHdr; /* Current point in record header */ + u8 *pBody; /* Current point in record data */ + u64 nHdr; /* Bytes in record header */ + int iIdx; /* Required field */ + int iCurrent = 0; /* Current field */ + + assert( argc==2 ); + pRec = (u8*)sqlite3_value_blob(argv[0]); + iIdx = sqlite3_value_int(argv[1]); + + pHdr = pRec + sqlite3GetVarint(pRec, &nHdr); + pBody = pEndHdr = &pRec[nHdr]; + + for(iCurrent=0; pHdr> 4) & 0x0F)]; + hex[1] = hexdigit[(z[i] & 0x0F)]; + hex[2] = '\0'; + Tcl_AppendStringsToObj(pVal, hex, 0); + } + Tcl_AppendStringsToObj(pVal, "'", 0); + break; + } + + case SQLITE_FLOAT: + pVal = Tcl_NewDoubleObj(sqlite3_value_double(&mem)); + break; + + case SQLITE_INTEGER: + pVal = Tcl_NewWideIntObj(sqlite3_value_int64(&mem)); + break; + + case SQLITE_NULL: + pVal = Tcl_NewStringObj("NULL", -1); + break; + + default: + assert( 0 ); + } + + Tcl_ListObjAppendElement(0, pRet, pVal); + + if( mem.zMalloc ){ + sqlite3DbFree(db, mem.zMalloc); + } + } + + sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); + Tcl_DecrRefCount(pRet); +} + + +static int registerTestFunctions(sqlite3 *db){ + static const struct { + char *zName; + signed char nArg; + unsigned char eTextRep; /* 1: UTF-16. 0: UTF-8 */ + void (*xFunc)(sqlite3_context*,int,sqlite3_value **); + } aFuncs[] = { + { "randstr", 2, SQLITE_UTF8, randStr }, + { "test_destructor", 1, SQLITE_UTF8, test_destructor}, +#ifndef SQLITE_OMIT_UTF16 + { "test_destructor16", 1, SQLITE_UTF8, test_destructor16}, + { "hex_to_utf16be", 1, SQLITE_UTF8, testHexToUtf16be}, + { "hex_to_utf16le", 1, SQLITE_UTF8, testHexToUtf16le}, +#endif + { "hex_to_utf8", 1, SQLITE_UTF8, testHexToUtf8}, + { "test_destructor_count", 0, SQLITE_UTF8, test_destructor_count}, + { "test_auxdata", -1, SQLITE_UTF8, test_auxdata}, + { "test_error", 1, SQLITE_UTF8, test_error}, + { "test_error", 2, SQLITE_UTF8, test_error}, + { "test_eval", 1, SQLITE_UTF8, test_eval}, + { "test_isolation", 2, SQLITE_UTF8, test_isolation}, + { "test_counter", 1, SQLITE_UTF8, counterFunc}, + { "real2hex", 1, SQLITE_UTF8, real2hex}, + { "test_decode", 1, SQLITE_UTF8, test_decode}, + { "test_extract", 2, SQLITE_UTF8, test_extract}, + }; + int i; + + for(i=0; i +#include +#include + + +/* +** Convert binary to hex. The input zBuf[] contains N bytes of +** binary data. zBuf[] is 2*n+1 bytes long. Overwrite zBuf[] +** with a hexadecimal representation of its original binary input. +*/ +void sqlite3TestBinToHex(unsigned char *zBuf, int N){ + const unsigned char zHex[] = "0123456789ABCDEF"; + int i, j; + unsigned char c; + i = N*2; + zBuf[i--] = 0; + for(j=N-1; j>=0; j--){ + c = zBuf[j]; + zBuf[i--] = zHex[c&0xf]; + zBuf[i--] = zHex[c>>4]; + } + assert( i==-1 ); +} + +/* +** Convert hex to binary. The input zIn[] contains N bytes of +** hexadecimal. Convert this into binary and write aOut[] with +** the binary data. Spaces in the original input are ignored. +** Return the number of bytes of binary rendered. +*/ +int sqlite3TestHexToBin(const unsigned char *zIn, int N, unsigned char *aOut){ + const unsigned char aMap[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 0, 0, 0, 0, 0, 0, + 0,11,12,13,14,15,16, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0,11,12,13,14,15,16, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + }; + int i, j; + int hi=1; + unsigned char c; + + for(i=j=0; i=4 ){ + memcpy(aNum, aOut, 4); + }else{ + memset(aNum, 0, sizeof(aNum)); + memcpy(&aNum[4-nOut], aOut, nOut); + } + sqlite3_free(aOut); + val = (aNum[0]<<24) | (aNum[1]<<16) | (aNum[2]<<8) | aNum[3]; + Tcl_SetObjResult(interp, Tcl_NewIntObj(val)); + return TCL_OK; +} + + +/* +** USAGE: hexio_render_int16 INTEGER +** +** Render INTEGER has a 16-bit big-endian integer in hexadecimal. +*/ +static int hexio_render_int16( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int val; + unsigned char aNum[10]; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "INTEGER"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &val) ) return TCL_ERROR; + aNum[0] = val>>8; + aNum[1] = val; + sqlite3TestBinToHex(aNum, 2); + Tcl_SetObjResult(interp, Tcl_NewStringObj((char*)aNum, 4)); + return TCL_OK; +} + + +/* +** USAGE: hexio_render_int32 INTEGER +** +** Render INTEGER has a 32-bit big-endian integer in hexadecimal. +*/ +static int hexio_render_int32( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int val; + unsigned char aNum[10]; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "INTEGER"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &val) ) return TCL_ERROR; + aNum[0] = val>>24; + aNum[1] = val>>16; + aNum[2] = val>>8; + aNum[3] = val; + sqlite3TestBinToHex(aNum, 4); + Tcl_SetObjResult(interp, Tcl_NewStringObj((char*)aNum, 8)); + return TCL_OK; +} + +/* +** USAGE: utf8_to_utf8 HEX +** +** The argument is a UTF8 string represented in hexadecimal. +** The UTF8 might not be well-formed. Run this string through +** sqlite3Utf8to8() convert it back to hex and return the result. +*/ +static int utf8_to_utf8( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifdef SQLITE_DEBUG + int n; + int nOut; + const unsigned char *zOrig; + unsigned char *z; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HEX"); + return TCL_ERROR; + } + zOrig = (unsigned char *)Tcl_GetStringFromObj(objv[1], &n); + z = sqlite3_malloc( n+3 ); + n = sqlite3TestHexToBin(zOrig, n, z); + z[n] = 0; + nOut = sqlite3Utf8To8(z); + sqlite3TestBinToHex(z,nOut); + Tcl_AppendResult(interp, (char*)z, 0); + sqlite3_free(z); + return TCL_OK; +#else + Tcl_AppendResult(interp, + "[utf8_to_utf8] unavailable - SQLITE_DEBUG not defined", 0 + ); + return TCL_ERROR; +#endif +} + +static int getFts3Varint(const char *p, sqlite_int64 *v){ + const unsigned char *q = (const unsigned char *) p; + sqlite_uint64 x = 0, y = 1; + while( (*q & 0x80) == 0x80 ){ + x += y * (*q++ & 0x7f); + y <<= 7; + } + x += y * (*q++); + *v = (sqlite_int64) x; + return (int) (q - (unsigned char *)p); +} + + +/* +** USAGE: read_fts3varint BLOB VARNAME +** +** Read a varint from the start of BLOB. Set variable VARNAME to contain +** the interpreted value. Return the number of bytes of BLOB consumed. +*/ +static int read_fts3varint( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int nBlob; + unsigned char *zBlob; + sqlite3_int64 iVal; + int nVal; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BLOB VARNAME"); + return TCL_ERROR; + } + zBlob = Tcl_GetByteArrayFromObj(objv[1], &nBlob); + + nVal = getFts3Varint((char*)zBlob, (sqlite3_int64 *)(&iVal)); + Tcl_ObjSetVar2(interp, objv[2], 0, Tcl_NewWideIntObj(iVal), 0); + Tcl_SetObjResult(interp, Tcl_NewIntObj(nVal)); + return TCL_OK; +} + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest_hexio_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aObjCmd[] = { + { "hexio_read", hexio_read }, + { "hexio_write", hexio_write }, + { "hexio_get_int", hexio_get_int }, + { "hexio_render_int16", hexio_render_int16 }, + { "hexio_render_int32", hexio_render_int32 }, + { "utf8_to_utf8", utf8_to_utf8 }, + { "read_fts3varint", read_fts3varint }, + }; + int i; + for(i=0; i +#include + +static struct Wrapped { + sqlite3_pcache_methods2 pcache; + sqlite3_mem_methods mem; + sqlite3_mutex_methods mutex; + + int mem_init; /* True if mem subsystem is initalized */ + int mem_fail; /* True to fail mem subsystem inialization */ + int mutex_init; /* True if mutex subsystem is initalized */ + int mutex_fail; /* True to fail mutex subsystem inialization */ + int pcache_init; /* True if pcache subsystem is initalized */ + int pcache_fail; /* True to fail pcache subsystem inialization */ +} wrapped; + +static int wrMemInit(void *pAppData){ + int rc; + if( wrapped.mem_fail ){ + rc = SQLITE_ERROR; + }else{ + rc = wrapped.mem.xInit(wrapped.mem.pAppData); + } + if( rc==SQLITE_OK ){ + wrapped.mem_init = 1; + } + return rc; +} +static void wrMemShutdown(void *pAppData){ + wrapped.mem.xShutdown(wrapped.mem.pAppData); + wrapped.mem_init = 0; +} +static void *wrMemMalloc(int n) {return wrapped.mem.xMalloc(n);} +static void wrMemFree(void *p) {wrapped.mem.xFree(p);} +static void *wrMemRealloc(void *p, int n) {return wrapped.mem.xRealloc(p, n);} +static int wrMemSize(void *p) {return wrapped.mem.xSize(p);} +static int wrMemRoundup(int n) {return wrapped.mem.xRoundup(n);} + + +static int wrMutexInit(void){ + int rc; + if( wrapped.mutex_fail ){ + rc = SQLITE_ERROR; + }else{ + rc = wrapped.mutex.xMutexInit(); + } + if( rc==SQLITE_OK ){ + wrapped.mutex_init = 1; + } + return rc; +} +static int wrMutexEnd(void){ + wrapped.mutex.xMutexEnd(); + wrapped.mutex_init = 0; + return SQLITE_OK; +} +static sqlite3_mutex *wrMutexAlloc(int e){ + return wrapped.mutex.xMutexAlloc(e); +} +static void wrMutexFree(sqlite3_mutex *p){ + wrapped.mutex.xMutexFree(p); +} +static void wrMutexEnter(sqlite3_mutex *p){ + wrapped.mutex.xMutexEnter(p); +} +static int wrMutexTry(sqlite3_mutex *p){ + return wrapped.mutex.xMutexTry(p); +} +static void wrMutexLeave(sqlite3_mutex *p){ + wrapped.mutex.xMutexLeave(p); +} +static int wrMutexHeld(sqlite3_mutex *p){ + return wrapped.mutex.xMutexHeld(p); +} +static int wrMutexNotheld(sqlite3_mutex *p){ + return wrapped.mutex.xMutexNotheld(p); +} + + + +static int wrPCacheInit(void *pArg){ + int rc; + if( wrapped.pcache_fail ){ + rc = SQLITE_ERROR; + }else{ + rc = wrapped.pcache.xInit(wrapped.pcache.pArg); + } + if( rc==SQLITE_OK ){ + wrapped.pcache_init = 1; + } + return rc; +} +static void wrPCacheShutdown(void *pArg){ + wrapped.pcache.xShutdown(wrapped.pcache.pArg); + wrapped.pcache_init = 0; +} + +static sqlite3_pcache *wrPCacheCreate(int a, int b, int c){ + return wrapped.pcache.xCreate(a, b, c); +} +static void wrPCacheCachesize(sqlite3_pcache *p, int n){ + wrapped.pcache.xCachesize(p, n); +} +static int wrPCachePagecount(sqlite3_pcache *p){ + return wrapped.pcache.xPagecount(p); +} +static sqlite3_pcache_page *wrPCacheFetch(sqlite3_pcache *p, unsigned a, int b){ + return wrapped.pcache.xFetch(p, a, b); +} +static void wrPCacheUnpin(sqlite3_pcache *p, sqlite3_pcache_page *a, int b){ + wrapped.pcache.xUnpin(p, a, b); +} +static void wrPCacheRekey( + sqlite3_pcache *p, + sqlite3_pcache_page *a, + unsigned b, + unsigned c +){ + wrapped.pcache.xRekey(p, a, b, c); +} +static void wrPCacheTruncate(sqlite3_pcache *p, unsigned a){ + wrapped.pcache.xTruncate(p, a); +} +static void wrPCacheDestroy(sqlite3_pcache *p){ + wrapped.pcache.xDestroy(p); +} + +static void installInitWrappers(void){ + sqlite3_mutex_methods mutexmethods = { + wrMutexInit, wrMutexEnd, wrMutexAlloc, + wrMutexFree, wrMutexEnter, wrMutexTry, + wrMutexLeave, wrMutexHeld, wrMutexNotheld + }; + sqlite3_pcache_methods2 pcachemethods = { + 1, 0, + wrPCacheInit, wrPCacheShutdown, wrPCacheCreate, + wrPCacheCachesize, wrPCachePagecount, wrPCacheFetch, + wrPCacheUnpin, wrPCacheRekey, wrPCacheTruncate, + wrPCacheDestroy + }; + sqlite3_mem_methods memmethods = { + wrMemMalloc, wrMemFree, wrMemRealloc, + wrMemSize, wrMemRoundup, wrMemInit, + wrMemShutdown, + 0 + }; + + memset(&wrapped, 0, sizeof(wrapped)); + + sqlite3_shutdown(); + sqlite3_config(SQLITE_CONFIG_GETMUTEX, &wrapped.mutex); + sqlite3_config(SQLITE_CONFIG_GETMALLOC, &wrapped.mem); + sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &wrapped.pcache); + sqlite3_config(SQLITE_CONFIG_MUTEX, &mutexmethods); + sqlite3_config(SQLITE_CONFIG_MALLOC, &memmethods); + sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcachemethods); +} + +static int init_wrapper_install( + ClientData clientData, /* Unused */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + int i; + installInitWrappers(); + for(i=1; i +#include + + +/* +** Definition of the sqlite3_intarray object. +** +** The internal representation of an intarray object is subject +** to change, is not externally visible, and should be used by +** the implementation of intarray only. This object is opaque +** to users. +*/ +struct sqlite3_intarray { + int n; /* Number of elements in the array */ + sqlite3_int64 *a; /* Contents of the array */ + void (*xFree)(void*); /* Function used to free a[] */ +}; + +/* Objects used internally by the virtual table implementation */ +typedef struct intarray_vtab intarray_vtab; +typedef struct intarray_cursor intarray_cursor; + +/* A intarray table object */ +struct intarray_vtab { + sqlite3_vtab base; /* Base class */ + sqlite3_intarray *pContent; /* Content of the integer array */ +}; + +/* A intarray cursor object */ +struct intarray_cursor { + sqlite3_vtab_cursor base; /* Base class */ + int i; /* Current cursor position */ +}; + +/* +** None of this works unless we have virtual tables. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Free an sqlite3_intarray object. +*/ +static void intarrayFree(sqlite3_intarray *p){ + if( p->xFree ){ + p->xFree(p->a); + } + sqlite3_free(p); +} + +/* +** Table destructor for the intarray module. +*/ +static int intarrayDestroy(sqlite3_vtab *p){ + intarray_vtab *pVtab = (intarray_vtab*)p; + sqlite3_free(pVtab); + return 0; +} + +/* +** Table constructor for the intarray module. +*/ +static int intarrayCreate( + sqlite3 *db, /* Database where module is created */ + void *pAux, /* clientdata for the module */ + int argc, /* Number of arguments */ + const char *const*argv, /* Value for all arguments */ + sqlite3_vtab **ppVtab, /* Write the new virtual table object here */ + char **pzErr /* Put error message text here */ +){ + int rc = SQLITE_NOMEM; + intarray_vtab *pVtab = sqlite3_malloc(sizeof(intarray_vtab)); + + if( pVtab ){ + memset(pVtab, 0, sizeof(intarray_vtab)); + pVtab->pContent = (sqlite3_intarray*)pAux; + rc = sqlite3_declare_vtab(db, "CREATE TABLE x(value INTEGER PRIMARY KEY)"); + } + *ppVtab = (sqlite3_vtab *)pVtab; + return rc; +} + +/* +** Open a new cursor on the intarray table. +*/ +static int intarrayOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + int rc = SQLITE_NOMEM; + intarray_cursor *pCur; + pCur = sqlite3_malloc(sizeof(intarray_cursor)); + if( pCur ){ + memset(pCur, 0, sizeof(intarray_cursor)); + *ppCursor = (sqlite3_vtab_cursor *)pCur; + rc = SQLITE_OK; + } + return rc; +} + +/* +** Close a intarray table cursor. +*/ +static int intarrayClose(sqlite3_vtab_cursor *cur){ + intarray_cursor *pCur = (intarray_cursor *)cur; + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Retrieve a column of data. +*/ +static int intarrayColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + intarray_cursor *pCur = (intarray_cursor*)cur; + intarray_vtab *pVtab = (intarray_vtab*)cur->pVtab; + if( pCur->i>=0 && pCur->ipContent->n ){ + sqlite3_result_int64(ctx, pVtab->pContent->a[pCur->i]); + } + return SQLITE_OK; +} + +/* +** Retrieve the current rowid. +*/ +static int intarrayRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + intarray_cursor *pCur = (intarray_cursor *)cur; + *pRowid = pCur->i; + return SQLITE_OK; +} + +static int intarrayEof(sqlite3_vtab_cursor *cur){ + intarray_cursor *pCur = (intarray_cursor *)cur; + intarray_vtab *pVtab = (intarray_vtab *)cur->pVtab; + return pCur->i>=pVtab->pContent->n; +} + +/* +** Advance the cursor to the next row. +*/ +static int intarrayNext(sqlite3_vtab_cursor *cur){ + intarray_cursor *pCur = (intarray_cursor *)cur; + pCur->i++; + return SQLITE_OK; +} + +/* +** Reset a intarray table cursor. +*/ +static int intarrayFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + intarray_cursor *pCur = (intarray_cursor *)pVtabCursor; + pCur->i = 0; + return SQLITE_OK; +} + +/* +** Analyse the WHERE condition. +*/ +static int intarrayBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + return SQLITE_OK; +} + +/* +** A virtual table module that merely echos method calls into TCL +** variables. +*/ +static sqlite3_module intarrayModule = { + 0, /* iVersion */ + intarrayCreate, /* xCreate - create a new virtual table */ + intarrayCreate, /* xConnect - connect to an existing vtab */ + intarrayBestIndex, /* xBestIndex - find the best query index */ + intarrayDestroy, /* xDisconnect - disconnect a vtab */ + intarrayDestroy, /* xDestroy - destroy a vtab */ + intarrayOpen, /* xOpen - open a cursor */ + intarrayClose, /* xClose - close a cursor */ + intarrayFilter, /* xFilter - configure scan constraints */ + intarrayNext, /* xNext - advance a cursor */ + intarrayEof, /* xEof */ + intarrayColumn, /* xColumn - read data */ + intarrayRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ + +/* +** Invoke this routine to create a specific instance of an intarray object. +** The new intarray object is returned by the 3rd parameter. +** +** Each intarray object corresponds to a virtual table in the TEMP table +** with a name of zName. +** +** Destroy the intarray object by dropping the virtual table. If not done +** explicitly by the application, the virtual table will be dropped implicitly +** by the system when the database connection is closed. +*/ +int sqlite3_intarray_create( + sqlite3 *db, + const char *zName, + sqlite3_intarray **ppReturn +){ + int rc = SQLITE_OK; +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_intarray *p; + + *ppReturn = p = sqlite3_malloc( sizeof(*p) ); + if( p==0 ){ + return SQLITE_NOMEM; + } + memset(p, 0, sizeof(*p)); + rc = sqlite3_create_module_v2(db, zName, &intarrayModule, p, + (void(*)(void*))intarrayFree); + if( rc==SQLITE_OK ){ + char *zSql; + zSql = sqlite3_mprintf("CREATE VIRTUAL TABLE temp.%Q USING %Q", + zName, zName); + rc = sqlite3_exec(db, zSql, 0, 0, 0); + sqlite3_free(zSql); + } +#endif + return rc; +} + +/* +** Bind a new array array of integers to a specific intarray object. +** +** The array of integers bound must be unchanged for the duration of +** any query against the corresponding virtual table. If the integer +** array does change or is deallocated undefined behavior will result. +*/ +int sqlite3_intarray_bind( + sqlite3_intarray *pIntArray, /* The intarray object to bind to */ + int nElements, /* Number of elements in the intarray */ + sqlite3_int64 *aElements, /* Content of the intarray */ + void (*xFree)(void*) /* How to dispose of the intarray when done */ +){ + if( pIntArray->xFree ){ + pIntArray->xFree(pIntArray->a); + } + pIntArray->n = nElements; + pIntArray->a = aElements; + pIntArray->xFree = xFree; + return SQLITE_OK; +} + + +/***************************************************************************** +** Everything below is interface for testing this module. +*/ +#ifdef SQLITE_TEST +#include + +/* +** Routines to encode and decode pointers +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); +extern void *sqlite3TestTextToPtr(const char*); +extern int sqlite3TestMakePointerStr(Tcl_Interp*, char *zPtr, void*); +extern const char *sqlite3ErrName(int); + +/* +** sqlite3_intarray_create DB NAME +** +** Invoke the sqlite3_intarray_create interface. A string that becomes +** the first parameter to sqlite3_intarray_bind. +*/ +static int test_intarray_create( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + const char *zName; + sqlite3_intarray *pArray; + int rc = SQLITE_OK; + char zPtr[100]; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zName = Tcl_GetString(objv[2]); +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = sqlite3_intarray_create(db, zName, &pArray); +#endif + if( rc!=SQLITE_OK ){ + assert( pArray==0 ); + Tcl_AppendResult(interp, sqlite3ErrName(rc), (char*)0); + return TCL_ERROR; + } + sqlite3TestMakePointerStr(interp, zPtr, pArray); + Tcl_AppendResult(interp, zPtr, (char*)0); + return TCL_OK; +} + +/* +** sqlite3_intarray_bind INTARRAY ?VALUE ...? +** +** Invoke the sqlite3_intarray_bind interface on the given array of integers. +*/ +static int test_intarray_bind( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3_intarray *pArray; + int rc = SQLITE_OK; + int i, n; + sqlite3_int64 *a; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "INTARRAY"); + return TCL_ERROR; + } + pArray = (sqlite3_intarray*)sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + n = objc - 2; +#ifndef SQLITE_OMIT_VIRTUALTABLE + a = sqlite3_malloc( sizeof(a[0])*n ); + if( a==0 ){ + Tcl_AppendResult(interp, "SQLITE_NOMEM", (char*)0); + return TCL_ERROR; + } + for(i=0; ipWritable); + sqlite3_free(p->aCksum); + p->pWritable = 0; + p->aCksum = 0; + p->nSync = 0; +} + +/* +** Close an jt-file. +*/ +static int jtClose(sqlite3_file *pFile){ + jt_file **pp; + jt_file *p = (jt_file *)pFile; + + closeTransaction(p); + enterJtMutex(); + if( p->zName ){ + for(pp=&g.pList; *pp!=p; pp=&(*pp)->pNext); + *pp = p->pNext; + } + leaveJtMutex(); + return sqlite3OsClose(p->pReal); +} + +/* +** Read data from an jt-file. +*/ +static int jtRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst); +} + +/* +** Parameter zJournal is the name of a journal file that is currently +** open. This function locates and returns the handle opened on the +** corresponding database file by the pager that currently has the +** journal file opened. This file-handle is identified by the +** following properties: +** +** a) SQLITE_OPEN_MAIN_DB was specified when the file was opened. +** +** b) The file-name specified when the file was opened matches +** all but the final 8 characters of the journal file name. +** +** c) There is currently a reserved lock on the file. +**/ +static jt_file *locateDatabaseHandle(const char *zJournal){ + jt_file *pMain = 0; + enterJtMutex(); + for(pMain=g.pList; pMain; pMain=pMain->pNext){ + int nName = (int)(strlen(zJournal) - strlen("-journal")); + if( (pMain->flags&SQLITE_OPEN_MAIN_DB) + && ((int)strlen(pMain->zName)==nName) + && 0==memcmp(pMain->zName, zJournal, nName) + && (pMain->eLock>=SQLITE_LOCK_RESERVED) + ){ + break; + } + } + leaveJtMutex(); + return pMain; +} + +/* +** Parameter z points to a buffer of 4 bytes in size containing a +** unsigned 32-bit integer stored in big-endian format. Decode the +** integer and return its value. +*/ +static u32 decodeUint32(const unsigned char *z){ + return (z[0]<<24) + (z[1]<<16) + (z[2]<<8) + z[3]; +} + +/* +** Calculate a checksum from the buffer of length n bytes pointed to +** by parameter z. +*/ +static u32 genCksum(const unsigned char *z, int n){ + int i; + u32 cksum = 0; + for(i=0; ipReal; + int rc = SQLITE_OK; + + closeTransaction(pMain); + aData = sqlite3_malloc(pMain->nPagesize); + pMain->pWritable = sqlite3BitvecCreate(pMain->nPage); + pMain->aCksum = sqlite3_malloc(sizeof(u32) * (pMain->nPage + 1)); + pJournal->iMaxOff = 0; + + if( !pMain->pWritable || !pMain->aCksum || !aData ){ + rc = SQLITE_IOERR_NOMEM; + }else if( pMain->nPage>0 ){ + u32 iTrunk; + int iSave; + int iSave2; + + stop_ioerr_simulation(&iSave, &iSave2); + + /* Read the database free-list. Add the page-number for each free-list + ** leaf to the jt_file.pWritable bitvec. + */ + rc = sqlite3OsRead(p, aData, pMain->nPagesize, 0); + if( rc==SQLITE_OK ){ + u32 nDbsize = decodeUint32(&aData[28]); + if( nDbsize>0 && memcmp(&aData[24], &aData[92], 4)==0 ){ + u32 iPg; + for(iPg=nDbsize+1; iPg<=pMain->nPage; iPg++){ + sqlite3BitvecSet(pMain->pWritable, iPg); + } + } + } + iTrunk = decodeUint32(&aData[32]); + while( rc==SQLITE_OK && iTrunk>0 ){ + u32 nLeaf; + u32 iLeaf; + sqlite3_int64 iOff = (i64)(iTrunk-1)*pMain->nPagesize; + rc = sqlite3OsRead(p, aData, pMain->nPagesize, iOff); + nLeaf = decodeUint32(&aData[4]); + for(iLeaf=0; rc==SQLITE_OK && iLeafpWritable, pgno); + } + iTrunk = decodeUint32(aData); + } + + /* Calculate and store a checksum for each page in the database file. */ + if( rc==SQLITE_OK ){ + int ii; + for(ii=0; rc==SQLITE_OK && ii<(int)pMain->nPage; ii++){ + i64 iOff = (i64)(pMain->nPagesize) * (i64)ii; + if( iOff==PENDING_BYTE ) continue; + rc = sqlite3OsRead(pMain->pReal, aData, pMain->nPagesize, iOff); + pMain->aCksum[ii] = genCksum(aData, pMain->nPagesize); + if( ii+1==pMain->nPage && rc==SQLITE_IOERR_SHORT_READ ) rc = SQLITE_OK; + } + } + + start_ioerr_simulation(iSave, iSave2); + } + + sqlite3_free(aData); + return rc; +} + +/* +** The first argument to this function is a handle open on a journal file. +** This function reads the journal file and adds the page number for each +** page in the journal to the Bitvec object passed as the second argument. +*/ +static int readJournalFile(jt_file *p, jt_file *pMain){ + int rc = SQLITE_OK; + unsigned char zBuf[28]; + sqlite3_file *pReal = p->pReal; + sqlite3_int64 iOff = 0; + sqlite3_int64 iSize = p->iMaxOff; + unsigned char *aPage; + int iSave; + int iSave2; + + aPage = sqlite3_malloc(pMain->nPagesize); + if( !aPage ){ + return SQLITE_IOERR_NOMEM; + } + + stop_ioerr_simulation(&iSave, &iSave2); + + while( rc==SQLITE_OK && iOff=(iOff+nSector) ){ + rc = sqlite3OsRead(pReal, zBuf, 28, iOff); + if( rc!=SQLITE_OK || 0==decodeJournalHdr(zBuf, 0, 0, 0, 0) ){ + continue; + } + } + nRec = (u32)((iSize-iOff) / (pMain->nPagesize+8)); + } + + /* Read all the records that follow the journal-header just read. */ + for(ii=0; rc==SQLITE_OK && ii0 && pgno<=pMain->nPage ){ + if( 0==sqlite3BitvecTest(pMain->pWritable, pgno) ){ + rc = sqlite3OsRead(pReal, aPage, pMain->nPagesize, iOff+4); + if( rc==SQLITE_OK ){ + u32 cksum = genCksum(aPage, pMain->nPagesize); + assert( cksum==pMain->aCksum[pgno-1] ); + } + } + sqlite3BitvecSet(pMain->pWritable, pgno); + } + iOff += (8 + pMain->nPagesize); + } + } + + iOff = ((iOff + (nSector-1)) / nSector) * nSector; + } + +finish_rjf: + start_ioerr_simulation(iSave, iSave2); + sqlite3_free(aPage); + if( rc==SQLITE_IOERR_SHORT_READ ){ + rc = SQLITE_OK; + } + return rc; +} + +/* +** Write data to an jt-file. +*/ +static int jtWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc; + jt_file *p = (jt_file *)pFile; + if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){ + if( iOfst==0 ){ + jt_file *pMain = locateDatabaseHandle(p->zName); + assert( pMain ); + + if( iAmt==28 ){ + /* Zeroing the first journal-file header. This is the end of a + ** transaction. */ + closeTransaction(pMain); + }else if( iAmt!=12 ){ + /* Writing the first journal header to a journal file. This happens + ** when a transaction is first started. */ + u8 *z = (u8 *)zBuf; + pMain->nPage = decodeUint32(&z[16]); + pMain->nPagesize = decodeUint32(&z[24]); + if( SQLITE_OK!=(rc=openTransaction(pMain, p)) ){ + return rc; + } + } + } + if( p->iMaxOff<(iOfst + iAmt) ){ + p->iMaxOff = iOfst + iAmt; + } + } + + if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){ + if( iAmt<(int)p->nPagesize + && p->nPagesize%iAmt==0 + && iOfst>=(PENDING_BYTE+512) + && iOfst+iAmt<=PENDING_BYTE+p->nPagesize + ){ + /* No-op. This special case is hit when the backup code is copying a + ** to a database with a larger page-size than the source database and + ** it needs to fill in the non-locking-region part of the original + ** pending-byte page. + */ + }else{ + u32 pgno = (u32)(iOfst/p->nPagesize + 1); + assert( (iAmt==1||iAmt==p->nPagesize) && ((iOfst+iAmt)%p->nPagesize)==0 ); + assert( pgno<=p->nPage || p->nSync>0 ); + assert( pgno>p->nPage || sqlite3BitvecTest(p->pWritable, pgno) ); + } + } + + rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst); + if( (p->flags&SQLITE_OPEN_MAIN_JOURNAL) && iAmt==12 ){ + jt_file *pMain = locateDatabaseHandle(p->zName); + int rc2 = readJournalFile(p, pMain); + if( rc==SQLITE_OK ) rc = rc2; + } + return rc; +} + +/* +** Truncate an jt-file. +*/ +static int jtTruncate(sqlite3_file *pFile, sqlite_int64 size){ + jt_file *p = (jt_file *)pFile; + if( p->flags&SQLITE_OPEN_MAIN_JOURNAL && size==0 ){ + /* Truncating a journal file. This is the end of a transaction. */ + jt_file *pMain = locateDatabaseHandle(p->zName); + closeTransaction(pMain); + } + if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){ + u32 pgno; + u32 locking_page = (u32)(PENDING_BYTE/p->nPagesize+1); + for(pgno=(u32)(size/p->nPagesize+1); pgno<=p->nPage; pgno++){ + assert( pgno==locking_page || sqlite3BitvecTest(p->pWritable, pgno) ); + } + } + return sqlite3OsTruncate(p->pReal, size); +} + +/* +** Sync an jt-file. +*/ +static int jtSync(sqlite3_file *pFile, int flags){ + jt_file *p = (jt_file *)pFile; + + if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){ + int rc; + jt_file *pMain; /* The associated database file */ + + /* The journal file is being synced. At this point, we inspect the + ** contents of the file up to this point and set each bit in the + ** jt_file.pWritable bitvec of the main database file associated with + ** this journal file. + */ + pMain = locateDatabaseHandle(p->zName); + assert(pMain); + + /* Set the bitvec values */ + if( pMain->pWritable ){ + pMain->nSync++; + rc = readJournalFile(p, pMain); + if( rc!=SQLITE_OK ){ + return rc; + } + } + } + + return sqlite3OsSync(p->pReal, flags); +} + +/* +** Return the current file-size of an jt-file. +*/ +static int jtFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsFileSize(p->pReal, pSize); +} + +/* +** Lock an jt-file. +*/ +static int jtLock(sqlite3_file *pFile, int eLock){ + int rc; + jt_file *p = (jt_file *)pFile; + rc = sqlite3OsLock(p->pReal, eLock); + if( rc==SQLITE_OK && eLock>p->eLock ){ + p->eLock = eLock; + } + return rc; +} + +/* +** Unlock an jt-file. +*/ +static int jtUnlock(sqlite3_file *pFile, int eLock){ + int rc; + jt_file *p = (jt_file *)pFile; + rc = sqlite3OsUnlock(p->pReal, eLock); + if( rc==SQLITE_OK && eLockeLock ){ + p->eLock = eLock; + } + return rc; +} + +/* +** Check if another file-handle holds a RESERVED lock on an jt-file. +*/ +static int jtCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsCheckReservedLock(p->pReal, pResOut); +} + +/* +** File control method. For custom operations on an jt-file. +*/ +static int jtFileControl(sqlite3_file *pFile, int op, void *pArg){ + jt_file *p = (jt_file *)pFile; + return p->pReal->pMethods->xFileControl(p->pReal, op, pArg); +} + +/* +** Return the sector-size in bytes for an jt-file. +*/ +static int jtSectorSize(sqlite3_file *pFile){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsSectorSize(p->pReal); +} + +/* +** Return the device characteristic flags supported by an jt-file. +*/ +static int jtDeviceCharacteristics(sqlite3_file *pFile){ + jt_file *p = (jt_file *)pFile; + return sqlite3OsDeviceCharacteristics(p->pReal); +} + +/* +** Open an jt file handle. +*/ +static int jtOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + jt_file *p = (jt_file *)pFile; + pFile->pMethods = 0; + p->pReal = (sqlite3_file *)&p[1]; + p->pReal->pMethods = 0; + rc = sqlite3OsOpen(g.pVfs, zName, p->pReal, flags, pOutFlags); + assert( rc==SQLITE_OK || p->pReal->pMethods==0 ); + if( rc==SQLITE_OK ){ + pFile->pMethods = &jt_io_methods; + p->eLock = 0; + p->zName = zName; + p->flags = flags; + p->pNext = 0; + p->pWritable = 0; + p->aCksum = 0; + enterJtMutex(); + if( zName ){ + p->pNext = g.pList; + g.pList = p; + } + leaveJtMutex(); + } + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int jtDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int nPath = (int)strlen(zPath); + if( nPath>8 && 0==strcmp("-journal", &zPath[nPath-8]) ){ + /* Deleting a journal file. The end of a transaction. */ + jt_file *pMain = locateDatabaseHandle(zPath); + if( pMain ){ + closeTransaction(pMain); + } + } + + return sqlite3OsDelete(g.pVfs, zPath, dirSync); +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int jtAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + return sqlite3OsAccess(g.pVfs, zPath, flags, pResOut); +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (JT_MAX_PATHNAME+1) bytes. +*/ +static int jtFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + return sqlite3OsFullPathname(g.pVfs, zPath, nOut, zOut); +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *jtDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return g.pVfs->xDlOpen(g.pVfs, zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void jtDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + g.pVfs->xDlError(g.pVfs, nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*jtDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return g.pVfs->xDlSym(g.pVfs, p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void jtDlClose(sqlite3_vfs *pVfs, void *pHandle){ + g.pVfs->xDlClose(g.pVfs, pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int jtRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return sqlite3OsRandomness(g.pVfs, nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int jtSleep(sqlite3_vfs *pVfs, int nMicro){ + return sqlite3OsSleep(g.pVfs, nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int jtCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + return g.pVfs->xCurrentTime(g.pVfs, pTimeOut); +} +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int jtCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ + return g.pVfs->xCurrentTimeInt64(g.pVfs, pTimeOut); +} + +/************************************************************************** +** Start of public API. +*/ + +/* +** Configure the jt VFS as a wrapper around the VFS named by parameter +** zWrap. If the isDefault parameter is true, then the jt VFS is installed +** as the new default VFS for SQLite connections. If isDefault is not +** true, then the jt VFS is installed as non-default. In this case it +** is available via its name, "jt". +*/ +int jt_register(char *zWrap, int isDefault){ + g.pVfs = sqlite3_vfs_find(zWrap); + if( g.pVfs==0 ){ + return SQLITE_ERROR; + } + jt_vfs.szOsFile = sizeof(jt_file) + g.pVfs->szOsFile; + if( g.pVfs->iVersion==1 ){ + jt_vfs.iVersion = 1; + }else if( g.pVfs->xCurrentTimeInt64==0 ){ + jt_vfs.xCurrentTimeInt64 = 0; + } + sqlite3_vfs_register(&jt_vfs, isDefault); + return SQLITE_OK; +} + +/* +** Uninstall the jt VFS, if it is installed. +*/ +void jt_unregister(void){ + sqlite3_vfs_unregister(&jt_vfs); +} + +#endif diff --git a/components/external/SQLite-3.8.1/src/test_loadext.c b/components/external/SQLite-3.8.1/src/test_loadext.c new file mode 100644 index 0000000000000000000000000000000000000000..1137e3a9aae92906b8289f6c3daa61f0d070f55a --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_loadext.c @@ -0,0 +1,122 @@ +/* +** 2006 June 14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Test extension for testing the sqlite3_load_extension() function. +*/ +#include +#include "sqlite3ext.h" +SQLITE_EXTENSION_INIT1 + +/* +** The half() SQL function returns half of its input value. +*/ +static void halfFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3_result_double(context, 0.5*sqlite3_value_double(argv[0])); +} + +/* +** SQL functions to call the sqlite3_status function and return results. +*/ +static void statusFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int op, mx, cur, resetFlag, rc; + if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){ + op = sqlite3_value_int(argv[0]); + }else if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){ + int i; + const char *zName; + static const struct { + const char *zName; + int op; + } aOp[] = { + { "MEMORY_USED", SQLITE_STATUS_MEMORY_USED }, + { "PAGECACHE_USED", SQLITE_STATUS_PAGECACHE_USED }, + { "PAGECACHE_OVERFLOW", SQLITE_STATUS_PAGECACHE_OVERFLOW }, + { "SCRATCH_USED", SQLITE_STATUS_SCRATCH_USED }, + { "SCRATCH_OVERFLOW", SQLITE_STATUS_SCRATCH_OVERFLOW }, + { "MALLOC_SIZE", SQLITE_STATUS_MALLOC_SIZE }, + }; + int nOp = sizeof(aOp)/sizeof(aOp[0]); + zName = (const char*)sqlite3_value_text(argv[0]); + for(i=0; i=nOp ){ + char *zMsg = sqlite3_mprintf("unknown status property: %s", zName); + sqlite3_result_error(context, zMsg, -1); + sqlite3_free(zMsg); + return; + } + }else{ + sqlite3_result_error(context, "unknown status type", -1); + return; + } + if( argc==2 ){ + resetFlag = sqlite3_value_int(argv[1]); + }else{ + resetFlag = 0; + } + rc = sqlite3_status(op, &cur, &mx, resetFlag); + if( rc!=SQLITE_OK ){ + char *zMsg = sqlite3_mprintf("sqlite3_status(%d,...) returns %d", op, rc); + sqlite3_result_error(context, zMsg, -1); + sqlite3_free(zMsg); + return; + } + if( argc==2 ){ + sqlite3_result_int(context, mx); + }else{ + sqlite3_result_int(context, cur); + } +} + +/* +** Extension load function. +*/ +int testloadext_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int nErr = 0; + SQLITE_EXTENSION_INIT2(pApi); + nErr |= sqlite3_create_function(db, "half", 1, SQLITE_ANY, 0, halfFunc, 0, 0); + nErr |= sqlite3_create_function(db, "sqlite3_status", 1, SQLITE_ANY, 0, + statusFunc, 0, 0); + nErr |= sqlite3_create_function(db, "sqlite3_status", 2, SQLITE_ANY, 0, + statusFunc, 0, 0); + return nErr ? SQLITE_ERROR : SQLITE_OK; +} + +/* +** Another extension entry point. This one always fails. +*/ +int testbrokenext_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + char *zErr; + SQLITE_EXTENSION_INIT2(pApi); + zErr = sqlite3_mprintf("broken!"); + *pzErrMsg = zErr; + return 1; +} diff --git a/components/external/SQLite-3.8.1/src/test_malloc.c b/components/external/SQLite-3.8.1/src/test_malloc.c new file mode 100644 index 0000000000000000000000000000000000000000..f513e24bf4cddb353fbb16461f5a4af7848d14c7 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_malloc.c @@ -0,0 +1,1494 @@ +/* +** 2007 August 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used to implement test interfaces to the +** memory allocation subsystem. +*/ +#include "sqliteInt.h" +#include "tcl.h" +#include +#include +#include + +/* +** This structure is used to encapsulate the global state variables used +** by malloc() fault simulation. +*/ +static struct MemFault { + int iCountdown; /* Number of pending successes before a failure */ + int nRepeat; /* Number of times to repeat the failure */ + int nBenign; /* Number of benign failures seen since last config */ + int nFail; /* Number of failures seen since last config */ + u8 enable; /* True if enabled */ + int isInstalled; /* True if the fault simulation layer is installed */ + int isBenignMode; /* True if malloc failures are considered benign */ + sqlite3_mem_methods m; /* 'Real' malloc implementation */ +} memfault; + +/* +** This routine exists as a place to set a breakpoint that will +** fire on any simulated malloc() failure. +*/ +static void sqlite3Fault(void){ + static int cnt = 0; + cnt++; +} + +/* +** Check to see if a fault should be simulated. Return true to simulate +** the fault. Return false if the fault should not be simulated. +*/ +static int faultsimStep(void){ + if( likely(!memfault.enable) ){ + return 0; + } + if( memfault.iCountdown>0 ){ + memfault.iCountdown--; + return 0; + } + sqlite3Fault(); + memfault.nFail++; + if( memfault.isBenignMode>0 ){ + memfault.nBenign++; + } + memfault.nRepeat--; + if( memfault.nRepeat<=0 ){ + memfault.enable = 0; + } + return 1; +} + +/* +** A version of sqlite3_mem_methods.xMalloc() that includes fault simulation +** logic. +*/ +static void *faultsimMalloc(int n){ + void *p = 0; + if( !faultsimStep() ){ + p = memfault.m.xMalloc(n); + } + return p; +} + + +/* +** A version of sqlite3_mem_methods.xRealloc() that includes fault simulation +** logic. +*/ +static void *faultsimRealloc(void *pOld, int n){ + void *p = 0; + if( !faultsimStep() ){ + p = memfault.m.xRealloc(pOld, n); + } + return p; +} + +/* +** The following method calls are passed directly through to the underlying +** malloc system: +** +** xFree +** xSize +** xRoundup +** xInit +** xShutdown +*/ +static void faultsimFree(void *p){ + memfault.m.xFree(p); +} +static int faultsimSize(void *p){ + return memfault.m.xSize(p); +} +static int faultsimRoundup(int n){ + return memfault.m.xRoundup(n); +} +static int faultsimInit(void *p){ + return memfault.m.xInit(memfault.m.pAppData); +} +static void faultsimShutdown(void *p){ + memfault.m.xShutdown(memfault.m.pAppData); +} + +/* +** This routine configures the malloc failure simulation. After +** calling this routine, the next nDelay mallocs will succeed, followed +** by a block of nRepeat failures, after which malloc() calls will begin +** to succeed again. +*/ +static void faultsimConfig(int nDelay, int nRepeat){ + memfault.iCountdown = nDelay; + memfault.nRepeat = nRepeat; + memfault.nBenign = 0; + memfault.nFail = 0; + memfault.enable = nDelay>=0; + + /* Sometimes, when running multi-threaded tests, the isBenignMode + ** variable is not properly incremented/decremented so that it is + ** 0 when not inside a benign malloc block. This doesn't affect + ** the multi-threaded tests, as they do not use this system. But + ** it does affect OOM tests run later in the same process. So + ** zero the variable here, just to be sure. + */ + memfault.isBenignMode = 0; +} + +/* +** Return the number of faults (both hard and benign faults) that have +** occurred since the injector was last configured. +*/ +static int faultsimFailures(void){ + return memfault.nFail; +} + +/* +** Return the number of benign faults that have occurred since the +** injector was last configured. +*/ +static int faultsimBenignFailures(void){ + return memfault.nBenign; +} + +/* +** Return the number of successes that will occur before the next failure. +** If no failures are scheduled, return -1. +*/ +static int faultsimPending(void){ + if( memfault.enable ){ + return memfault.iCountdown; + }else{ + return -1; + } +} + + +static void faultsimBeginBenign(void){ + memfault.isBenignMode++; +} +static void faultsimEndBenign(void){ + memfault.isBenignMode--; +} + +/* +** Add or remove the fault-simulation layer using sqlite3_config(). If +** the argument is non-zero, the +*/ +static int faultsimInstall(int install){ + static struct sqlite3_mem_methods m = { + faultsimMalloc, /* xMalloc */ + faultsimFree, /* xFree */ + faultsimRealloc, /* xRealloc */ + faultsimSize, /* xSize */ + faultsimRoundup, /* xRoundup */ + faultsimInit, /* xInit */ + faultsimShutdown, /* xShutdown */ + 0 /* pAppData */ + }; + int rc; + + install = (install ? 1 : 0); + assert(memfault.isInstalled==1 || memfault.isInstalled==0); + + if( install==memfault.isInstalled ){ + return SQLITE_ERROR; + } + + if( install ){ + rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memfault.m); + assert(memfault.m.xMalloc); + if( rc==SQLITE_OK ){ + rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &m); + } + sqlite3_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, + faultsimBeginBenign, faultsimEndBenign + ); + }else{ + sqlite3_mem_methods m; + assert(memfault.m.xMalloc); + + /* One should be able to reset the default memory allocator by storing + ** a zeroed allocator then calling GETMALLOC. */ + memset(&m, 0, sizeof(m)); + sqlite3_config(SQLITE_CONFIG_MALLOC, &m); + sqlite3_config(SQLITE_CONFIG_GETMALLOC, &m); + assert( memcmp(&m, &memfault.m, sizeof(m))==0 ); + + rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memfault.m); + sqlite3_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 0, 0); + } + + if( rc==SQLITE_OK ){ + memfault.isInstalled = 1; + } + return rc; +} + +#ifdef SQLITE_TEST + +/* +** This function is implemented in main.c. Returns a pointer to a static +** buffer containing the symbolic SQLite error code that corresponds to +** the least-significant 8-bits of the integer passed as an argument. +** For example: +** +** sqlite3ErrName(1) -> "SQLITE_ERROR" +*/ +extern const char *sqlite3ErrName(int); + +/* +** Transform pointers to text and back again +*/ +static void pointerToText(void *p, char *z){ + static const char zHex[] = "0123456789abcdef"; + int i, k; + unsigned int u; + sqlite3_uint64 n; + if( p==0 ){ + strcpy(z, "0"); + return; + } + if( sizeof(n)==sizeof(p) ){ + memcpy(&n, &p, sizeof(p)); + }else if( sizeof(u)==sizeof(p) ){ + memcpy(&u, &p, sizeof(u)); + n = u; + }else{ + assert( 0 ); + } + for(i=0, k=sizeof(p)*2-1; i>= 4; + } + z[sizeof(p)*2] = 0; +} +static int hexToInt(int h){ + if( h>='0' && h<='9' ){ + return h - '0'; + }else if( h>='a' && h<='f' ){ + return h - 'a' + 10; + }else{ + return -1; + } +} +static int textToPointer(const char *z, void **pp){ + sqlite3_uint64 n = 0; + int i; + unsigned int u; + for(i=0; isizeof(zBin)*2 ) n = sizeof(zBin)*2; + n = sqlite3TestHexToBin(zHex, n, zBin); + if( n==0 ){ + Tcl_AppendResult(interp, "no data", (char*)0); + return TCL_ERROR; + } + zOut = p; + for(i=0; i0 ){ + if( size>(sizeof(zHex)-1)/2 ){ + n = (sizeof(zHex)-1)/2; + }else{ + n = size; + } + memcpy(zHex, zBin, n); + zBin += n; + size -= n; + sqlite3TestBinToHex(zHex, n); + Tcl_AppendResult(interp, zHex, (char*)0); + } + return TCL_OK; +} + +/* +** Usage: sqlite3_memory_used +** +** Raw test interface for sqlite3_memory_used(). +*/ +static int test_memory_used( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(sqlite3_memory_used())); + return TCL_OK; +} + +/* +** Usage: sqlite3_memory_highwater ?RESETFLAG? +** +** Raw test interface for sqlite3_memory_highwater(). +*/ +static int test_memory_highwater( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int resetFlag = 0; + if( objc!=1 && objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?RESET?"); + return TCL_ERROR; + } + if( objc==2 ){ + if( Tcl_GetBooleanFromObj(interp, objv[1], &resetFlag) ) return TCL_ERROR; + } + Tcl_SetObjResult(interp, + Tcl_NewWideIntObj(sqlite3_memory_highwater(resetFlag))); + return TCL_OK; +} + +/* +** Usage: sqlite3_memdebug_backtrace DEPTH +** +** Set the depth of backtracing. If SQLITE_MEMDEBUG is not defined +** then this routine is a no-op. +*/ +static int test_memdebug_backtrace( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int depth; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DEPT"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &depth) ) return TCL_ERROR; +#ifdef SQLITE_MEMDEBUG + { + extern void sqlite3MemdebugBacktrace(int); + sqlite3MemdebugBacktrace(depth); + } +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_memdebug_dump FILENAME +** +** Write a summary of unfreed memory to FILENAME. +*/ +static int test_memdebug_dump( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } +#if defined(SQLITE_MEMDEBUG) || defined(SQLITE_MEMORY_SIZE) \ + || defined(SQLITE_POW2_MEMORY_SIZE) + { + extern void sqlite3MemdebugDump(const char*); + sqlite3MemdebugDump(Tcl_GetString(objv[1])); + } +#endif + return TCL_OK; +} + +/* +** Usage: sqlite3_memdebug_malloc_count +** +** Return the total number of times malloc() has been called. +*/ +static int test_memdebug_malloc_count( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int nMalloc = -1; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } +#if defined(SQLITE_MEMDEBUG) + { + extern int sqlite3MemdebugMallocCount(); + nMalloc = sqlite3MemdebugMallocCount(); + } +#endif + Tcl_SetObjResult(interp, Tcl_NewIntObj(nMalloc)); + return TCL_OK; +} + + +/* +** Usage: sqlite3_memdebug_fail COUNTER ?OPTIONS? +** +** where options are: +** +** -repeat +** -benigncnt +** +** Arrange for a simulated malloc() failure after COUNTER successes. +** If a repeat count is specified, the fault is repeated that many +** times. +** +** Each call to this routine overrides the prior counter value. +** This routine returns the number of simulated failures that have +** happened since the previous call to this routine. +** +** To disable simulated failures, use a COUNTER of -1. +*/ +static int test_memdebug_fail( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int ii; + int iFail; + int nRepeat = 1; + Tcl_Obj *pBenignCnt = 0; + int nBenign; + int nFail = 0; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "COUNTER ?OPTIONS?"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &iFail) ) return TCL_ERROR; + + for(ii=2; ii1 && strncmp(zOption, "-repeat", nOption)==0 ){ + if( ii==(objc-1) ){ + zErr = "option requires an argument: "; + }else{ + if( Tcl_GetIntFromObj(interp, objv[ii+1], &nRepeat) ){ + return TCL_ERROR; + } + } + }else if( nOption>1 && strncmp(zOption, "-benigncnt", nOption)==0 ){ + if( ii==(objc-1) ){ + zErr = "option requires an argument: "; + }else{ + pBenignCnt = objv[ii+1]; + } + }else{ + zErr = "unknown option: "; + } + + if( zErr ){ + Tcl_AppendResult(interp, zErr, zOption, 0); + return TCL_ERROR; + } + } + + nBenign = faultsimBenignFailures(); + nFail = faultsimFailures(); + faultsimConfig(iFail, nRepeat); + + if( pBenignCnt ){ + Tcl_ObjSetVar2(interp, pBenignCnt, 0, Tcl_NewIntObj(nBenign), 0); + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(nFail)); + return TCL_OK; +} + +/* +** Usage: sqlite3_memdebug_pending +** +** Return the number of malloc() calls that will succeed before a +** simulated failure occurs. A negative return value indicates that +** no malloc() failure is scheduled. +*/ +static int test_memdebug_pending( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int nPending; + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + nPending = faultsimPending(); + Tcl_SetObjResult(interp, Tcl_NewIntObj(nPending)); + return TCL_OK; +} + + +/* +** Usage: sqlite3_memdebug_settitle TITLE +** +** Set a title string stored with each allocation. The TITLE is +** typically the name of the test that was running when the +** allocation occurred. The TITLE is stored with the allocation +** and can be used to figure out which tests are leaking memory. +** +** Each title overwrite the previous. +*/ +static int test_memdebug_settitle( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "TITLE"); + return TCL_ERROR; + } +#ifdef SQLITE_MEMDEBUG + { + const char *zTitle; + extern int sqlite3MemdebugSettitle(const char*); + zTitle = Tcl_GetString(objv[1]); + sqlite3MemdebugSettitle(zTitle); + } +#endif + return TCL_OK; +} + +#define MALLOC_LOG_FRAMES 10 +#define MALLOC_LOG_KEYINTS ( \ + 10 * ((sizeof(int)>=sizeof(void*)) ? 1 : sizeof(void*)/sizeof(int)) \ +) +static Tcl_HashTable aMallocLog; +static int mallocLogEnabled = 0; + +typedef struct MallocLog MallocLog; +struct MallocLog { + int nCall; + int nByte; +}; + +#ifdef SQLITE_MEMDEBUG +static void test_memdebug_callback(int nByte, int nFrame, void **aFrame){ + if( mallocLogEnabled ){ + MallocLog *pLog; + Tcl_HashEntry *pEntry; + int isNew; + + int aKey[MALLOC_LOG_KEYINTS]; + unsigned int nKey = sizeof(int)*MALLOC_LOG_KEYINTS; + + memset(aKey, 0, nKey); + if( (sizeof(void*)*nFrame)nCall++; + pLog->nByte += nByte; + } +} +#endif /* SQLITE_MEMDEBUG */ + +static void test_memdebug_log_clear(void){ + Tcl_HashSearch search; + Tcl_HashEntry *pEntry; + for( + pEntry=Tcl_FirstHashEntry(&aMallocLog, &search); + pEntry; + pEntry=Tcl_NextHashEntry(&search) + ){ + MallocLog *pLog = (MallocLog *)Tcl_GetHashValue(pEntry); + Tcl_Free((char *)pLog); + } + Tcl_DeleteHashTable(&aMallocLog); + Tcl_InitHashTable(&aMallocLog, MALLOC_LOG_KEYINTS); +} + +static int test_memdebug_log( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + static int isInit = 0; + int iSub; + + static const char *MB_strs[] = { "start", "stop", "dump", "clear", "sync" }; + enum MB_enum { + MB_LOG_START, MB_LOG_STOP, MB_LOG_DUMP, MB_LOG_CLEAR, MB_LOG_SYNC + }; + + if( !isInit ){ +#ifdef SQLITE_MEMDEBUG + extern void sqlite3MemdebugBacktraceCallback( + void (*xBacktrace)(int, int, void **)); + sqlite3MemdebugBacktraceCallback(test_memdebug_callback); +#endif + Tcl_InitHashTable(&aMallocLog, MALLOC_LOG_KEYINTS); + isInit = 1; + } + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND ..."); + } + if( Tcl_GetIndexFromObj(interp, objv[1], MB_strs, "sub-command", 0, &iSub) ){ + return TCL_ERROR; + } + + switch( (enum MB_enum)iSub ){ + case MB_LOG_START: + mallocLogEnabled = 1; + break; + case MB_LOG_STOP: + mallocLogEnabled = 0; + break; + case MB_LOG_DUMP: { + Tcl_HashSearch search; + Tcl_HashEntry *pEntry; + Tcl_Obj *pRet = Tcl_NewObj(); + + assert(sizeof(Tcl_WideInt)>=sizeof(void*)); + + for( + pEntry=Tcl_FirstHashEntry(&aMallocLog, &search); + pEntry; + pEntry=Tcl_NextHashEntry(&search) + ){ + Tcl_Obj *apElem[MALLOC_LOG_FRAMES+2]; + MallocLog *pLog = (MallocLog *)Tcl_GetHashValue(pEntry); + Tcl_WideInt *aKey = (Tcl_WideInt *)Tcl_GetHashKey(&aMallocLog, pEntry); + int ii; + + apElem[0] = Tcl_NewIntObj(pLog->nCall); + apElem[1] = Tcl_NewIntObj(pLog->nByte); + for(ii=0; ii5 ){ + Tcl_WrongNumArgs(interp, 1, objv, + "INSTALLFLAG DISCARDCHANCE PRNGSEEED HIGHSTRESS"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &installFlag) ) return TCL_ERROR; + if( objc>=3 && Tcl_GetIntFromObj(interp, objv[2], &discardChance) ){ + return TCL_ERROR; + } + if( objc>=4 && Tcl_GetIntFromObj(interp, objv[3], &prngSeed) ){ + return TCL_ERROR; + } + if( objc>=5 && Tcl_GetIntFromObj(interp, objv[4], &highStress) ){ + return TCL_ERROR; + } + if( discardChance<0 || discardChance>100 ){ + Tcl_AppendResult(interp, "discard-chance should be between 0 and 100", + (char*)0); + return TCL_ERROR; + } + installTestPCache(installFlag, (unsigned)discardChance, (unsigned)prngSeed, + (unsigned)highStress); + return TCL_OK; +} + +/* +** Usage: sqlite3_config_memstatus BOOLEAN +** +** Enable or disable memory status reporting using SQLITE_CONFIG_MEMSTATUS. +*/ +static int test_config_memstatus( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int enable, rc; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[1], &enable) ) return TCL_ERROR; + rc = sqlite3_config(SQLITE_CONFIG_MEMSTATUS, enable); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** Usage: sqlite3_config_lookaside SIZE COUNT +** +*/ +static int test_config_lookaside( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int sz, cnt; + Tcl_Obj *pRet; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SIZE COUNT"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[1], &sz) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &cnt) ) return TCL_ERROR; + pRet = Tcl_NewObj(); + Tcl_ListObjAppendElement( + interp, pRet, Tcl_NewIntObj(sqlite3GlobalConfig.szLookaside) + ); + Tcl_ListObjAppendElement( + interp, pRet, Tcl_NewIntObj(sqlite3GlobalConfig.nLookaside) + ); + sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, cnt); + Tcl_SetObjResult(interp, pRet); + return TCL_OK; +} + + +/* +** Usage: sqlite3_db_config_lookaside CONNECTION BUFID SIZE COUNT +** +** There are two static buffers with BUFID 1 and 2. Each static buffer +** is 10KB in size. A BUFID of 0 indicates that the buffer should be NULL +** which will cause sqlite3_db_config() to allocate space on its own. +*/ +static int test_db_config_lookaside( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + int sz, cnt; + sqlite3 *db; + int bufid; + static char azBuf[2][10000]; + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BUFID SIZE COUNT"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[2], &bufid) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &sz) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[4], &cnt) ) return TCL_ERROR; + if( bufid==0 ){ + rc = sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE, 0, sz, cnt); + }else if( bufid>=1 && bufid<=2 && sz*cnt<=sizeof(azBuf[0]) ){ + rc = sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE, azBuf[bufid], sz,cnt); + }else{ + Tcl_AppendResult(interp, "illegal arguments - see documentation", (char*)0); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** Usage: sqlite3_config_heap NBYTE NMINALLOC +*/ +static int test_config_heap( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + static char *zBuf; /* Use this memory */ + int nByte; /* Size of buffer to pass to sqlite3_config() */ + int nMinAlloc; /* Size of minimum allocation */ + int rc; /* Return code of sqlite3_config() */ + + Tcl_Obj * CONST *aArg = &objv[1]; + int nArg = objc-1; + + if( nArg!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "NBYTE NMINALLOC"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, aArg[0], &nByte) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, aArg[1], &nMinAlloc) ) return TCL_ERROR; + + if( nByte==0 ){ + free( zBuf ); + zBuf = 0; + rc = sqlite3_config(SQLITE_CONFIG_HEAP, (void*)0, 0, 0); + }else{ + zBuf = realloc(zBuf, nByte); + rc = sqlite3_config(SQLITE_CONFIG_HEAP, zBuf, nByte, nMinAlloc); + } + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** Usage: sqlite3_config_error [DB] +** +** Invoke sqlite3_config() or sqlite3_db_config() with invalid +** opcodes and verify that they return errors. +*/ +static int test_config_error( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + + if( objc!=2 && objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, "[DB]"); + return TCL_ERROR; + } + if( objc==2 ){ + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + if( sqlite3_db_config(db, 99999)!=SQLITE_ERROR ){ + Tcl_AppendResult(interp, + "sqlite3_db_config(db, 99999) does not return SQLITE_ERROR", + (char*)0); + return TCL_ERROR; + } + }else{ + if( sqlite3_config(99999)!=SQLITE_ERROR ){ + Tcl_AppendResult(interp, + "sqlite3_config(99999) does not return SQLITE_ERROR", + (char*)0); + return TCL_ERROR; + } + } + return TCL_OK; +} + +/* +** Usage: sqlite3_config_uri BOOLEAN +** +** Enables or disables interpretation of URI parameters by default using +** SQLITE_CONFIG_URI. +*/ +static int test_config_uri( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + int bOpenUri; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOL"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[1], &bOpenUri) ){ + return TCL_ERROR; + } + + rc = sqlite3_config(SQLITE_CONFIG_URI, bOpenUri); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + + return TCL_OK; +} + +/* +** Usage: sqlite3_config_cis BOOLEAN +** +** Enables or disables the use of the covering-index scan optimization. +** SQLITE_CONFIG_COVERING_INDEX_SCAN. +*/ +static int test_config_cis( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + int bUseCis; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOL"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[1], &bUseCis) ){ + return TCL_ERROR; + } + + rc = sqlite3_config(SQLITE_CONFIG_COVERING_INDEX_SCAN, bUseCis); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + + return TCL_OK; +} + +/* +** Usage: sqlite3_dump_memsys3 FILENAME +** sqlite3_dump_memsys5 FILENAME +** +** Write a summary of unfreed memsys3 allocations to FILENAME. +*/ +static int test_dump_memsys3( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } + + switch( SQLITE_PTR_TO_INT(clientData) ){ + case 3: { +#ifdef SQLITE_ENABLE_MEMSYS3 + extern void sqlite3Memsys3Dump(const char*); + sqlite3Memsys3Dump(Tcl_GetString(objv[1])); + break; +#endif + } + case 5: { +#ifdef SQLITE_ENABLE_MEMSYS5 + extern void sqlite3Memsys5Dump(const char*); + sqlite3Memsys5Dump(Tcl_GetString(objv[1])); + break; +#endif + } + } + return TCL_OK; +} + +/* +** Usage: sqlite3_status OPCODE RESETFLAG +** +** Return a list of three elements which are the sqlite3_status() return +** code, the current value, and the high-water mark value. +*/ +static int test_status( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc, iValue, mxValue; + int i, op, resetFlag; + const char *zOpName; + static const struct { + const char *zName; + int op; + } aOp[] = { + { "SQLITE_STATUS_MEMORY_USED", SQLITE_STATUS_MEMORY_USED }, + { "SQLITE_STATUS_MALLOC_SIZE", SQLITE_STATUS_MALLOC_SIZE }, + { "SQLITE_STATUS_PAGECACHE_USED", SQLITE_STATUS_PAGECACHE_USED }, + { "SQLITE_STATUS_PAGECACHE_OVERFLOW", SQLITE_STATUS_PAGECACHE_OVERFLOW }, + { "SQLITE_STATUS_PAGECACHE_SIZE", SQLITE_STATUS_PAGECACHE_SIZE }, + { "SQLITE_STATUS_SCRATCH_USED", SQLITE_STATUS_SCRATCH_USED }, + { "SQLITE_STATUS_SCRATCH_OVERFLOW", SQLITE_STATUS_SCRATCH_OVERFLOW }, + { "SQLITE_STATUS_SCRATCH_SIZE", SQLITE_STATUS_SCRATCH_SIZE }, + { "SQLITE_STATUS_PARSER_STACK", SQLITE_STATUS_PARSER_STACK }, + { "SQLITE_STATUS_MALLOC_COUNT", SQLITE_STATUS_MALLOC_COUNT }, + }; + Tcl_Obj *pResult; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PARAMETER RESETFLAG"); + return TCL_ERROR; + } + zOpName = Tcl_GetString(objv[1]); + for(i=0; i=ArraySize(aOp) ){ + if( Tcl_GetIntFromObj(interp, objv[1], &op) ) return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[2], &resetFlag) ) return TCL_ERROR; + iValue = 0; + mxValue = 0; + rc = sqlite3_status(op, &iValue, &mxValue, resetFlag); + pResult = Tcl_NewObj(); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(rc)); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(iValue)); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(mxValue)); + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + +/* +** Usage: sqlite3_db_status DATABASE OPCODE RESETFLAG +** +** Return a list of three elements which are the sqlite3_db_status() return +** code, the current value, and the high-water mark value. +*/ +static int test_db_status( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc, iValue, mxValue; + int i, op, resetFlag; + const char *zOpName; + sqlite3 *db; + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + static const struct { + const char *zName; + int op; + } aOp[] = { + { "LOOKASIDE_USED", SQLITE_DBSTATUS_LOOKASIDE_USED }, + { "CACHE_USED", SQLITE_DBSTATUS_CACHE_USED }, + { "SCHEMA_USED", SQLITE_DBSTATUS_SCHEMA_USED }, + { "STMT_USED", SQLITE_DBSTATUS_STMT_USED }, + { "LOOKASIDE_HIT", SQLITE_DBSTATUS_LOOKASIDE_HIT }, + { "LOOKASIDE_MISS_SIZE", SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE }, + { "LOOKASIDE_MISS_FULL", SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL }, + { "CACHE_HIT", SQLITE_DBSTATUS_CACHE_HIT }, + { "CACHE_MISS", SQLITE_DBSTATUS_CACHE_MISS }, + { "CACHE_WRITE", SQLITE_DBSTATUS_CACHE_WRITE }, + { "DEFERRED_FKS", SQLITE_DBSTATUS_DEFERRED_FKS } + }; + Tcl_Obj *pResult; + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB PARAMETER RESETFLAG"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zOpName = Tcl_GetString(objv[2]); + if( memcmp(zOpName, "SQLITE_", 7)==0 ) zOpName += 7; + if( memcmp(zOpName, "DBSTATUS_", 9)==0 ) zOpName += 9; + for(i=0; i=ArraySize(aOp) ){ + if( Tcl_GetIntFromObj(interp, objv[2], &op) ) return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[3], &resetFlag) ) return TCL_ERROR; + iValue = 0; + mxValue = 0; + rc = sqlite3_db_status(db, op, &iValue, &mxValue, resetFlag); + pResult = Tcl_NewObj(); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(rc)); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(iValue)); + Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(mxValue)); + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + +/* +** install_malloc_faultsim BOOLEAN +*/ +static int test_install_malloc_faultsim( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + int isInstall; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN"); + return TCL_ERROR; + } + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[1], &isInstall) ){ + return TCL_ERROR; + } + rc = faultsimInstall(isInstall); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** sqlite3_install_memsys3 +*/ +static int test_install_memsys3( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = SQLITE_MISUSE; +#ifdef SQLITE_ENABLE_MEMSYS3 + const sqlite3_mem_methods *sqlite3MemGetMemsys3(void); + rc = sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetMemsys3()); +#endif + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +static int test_vfs_oom_test( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + extern int sqlite3_memdebug_vfs_oom_test; + if( objc>2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "?INTEGER?"); + return TCL_ERROR; + }else if( objc==2 ){ + int iNew; + if( Tcl_GetIntFromObj(interp, objv[1], &iNew) ) return TCL_ERROR; + sqlite3_memdebug_vfs_oom_test = iNew; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_memdebug_vfs_oom_test)); + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetest_malloc_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + int clientData; + } aObjCmd[] = { + { "sqlite3_malloc", test_malloc ,0 }, + { "sqlite3_realloc", test_realloc ,0 }, + { "sqlite3_free", test_free ,0 }, + { "memset", test_memset ,0 }, + { "memget", test_memget ,0 }, + { "sqlite3_memory_used", test_memory_used ,0 }, + { "sqlite3_memory_highwater", test_memory_highwater ,0 }, + { "sqlite3_memdebug_backtrace", test_memdebug_backtrace ,0 }, + { "sqlite3_memdebug_dump", test_memdebug_dump ,0 }, + { "sqlite3_memdebug_fail", test_memdebug_fail ,0 }, + { "sqlite3_memdebug_pending", test_memdebug_pending ,0 }, + { "sqlite3_memdebug_settitle", test_memdebug_settitle ,0 }, + { "sqlite3_memdebug_malloc_count", test_memdebug_malloc_count ,0 }, + { "sqlite3_memdebug_log", test_memdebug_log ,0 }, + { "sqlite3_config_scratch", test_config_scratch ,0 }, + { "sqlite3_config_pagecache", test_config_pagecache ,0 }, + { "sqlite3_config_alt_pcache", test_alt_pcache ,0 }, + { "sqlite3_status", test_status ,0 }, + { "sqlite3_db_status", test_db_status ,0 }, + { "install_malloc_faultsim", test_install_malloc_faultsim ,0 }, + { "sqlite3_config_heap", test_config_heap ,0 }, + { "sqlite3_config_memstatus", test_config_memstatus ,0 }, + { "sqlite3_config_lookaside", test_config_lookaside ,0 }, + { "sqlite3_config_error", test_config_error ,0 }, + { "sqlite3_config_uri", test_config_uri ,0 }, + { "sqlite3_config_cis", test_config_cis ,0 }, + { "sqlite3_db_config_lookaside",test_db_config_lookaside ,0 }, + { "sqlite3_dump_memsys3", test_dump_memsys3 ,3 }, + { "sqlite3_dump_memsys5", test_dump_memsys3 ,5 }, + { "sqlite3_install_memsys3", test_install_memsys3 ,0 }, + { "sqlite3_memdebug_vfs_oom_test", test_vfs_oom_test ,0 }, + }; + int i; + for(i=0; i +#include +#include +#include "test_multiplex.h" + +#ifndef SQLITE_CORE + #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ +#endif +#include "sqlite3ext.h" + +/* +** These should be defined to be the same as the values in +** sqliteInt.h. They are defined separately here so that +** the multiplex VFS shim can be built as a loadable +** module. +*/ +#define UNUSED_PARAMETER(x) (void)(x) +#define MAX_PAGE_SIZE 0x10000 +#define DEFAULT_SECTOR_SIZE 0x1000 + +/* +** For a build without mutexes, no-op the mutex calls. +*/ +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0 +#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) +#define sqlite3_mutex_free(X) +#define sqlite3_mutex_enter(X) +#define sqlite3_mutex_try(X) SQLITE_OK +#define sqlite3_mutex_leave(X) +#define sqlite3_mutex_held(X) ((void)(X),1) +#define sqlite3_mutex_notheld(X) ((void)(X),1) +#endif /* SQLITE_THREADSAFE==0 */ + +/* Maximum chunk number */ +#define MX_CHUNK_NUMBER 299 + +/* First chunk for rollback journal files */ +#define SQLITE_MULTIPLEX_JOURNAL_8_3_OFFSET 400 +#define SQLITE_MULTIPLEX_WAL_8_3_OFFSET 700 + + +/************************ Shim Definitions ******************************/ + +#ifndef SQLITE_MULTIPLEX_VFS_NAME +# define SQLITE_MULTIPLEX_VFS_NAME "multiplex" +#endif + +/* This is the limit on the chunk size. It may be changed by calling +** the xFileControl() interface. It will be rounded up to a +** multiple of MAX_PAGE_SIZE. We default it here to 2GiB less 64KiB. +*/ +#ifndef SQLITE_MULTIPLEX_CHUNK_SIZE +# define SQLITE_MULTIPLEX_CHUNK_SIZE 2147418112 +#endif + +/* This used to be the default limit on number of chunks, but +** it is no longer enforced. There is currently no limit to the +** number of chunks. +** +** May be changed by calling the xFileControl() interface. +*/ +#ifndef SQLITE_MULTIPLEX_MAX_CHUNKS +# define SQLITE_MULTIPLEX_MAX_CHUNKS 12 +#endif + +/************************ Object Definitions ******************************/ + +/* Forward declaration of all object types */ +typedef struct multiplexGroup multiplexGroup; +typedef struct multiplexConn multiplexConn; + +/* +** A "multiplex group" is a collection of files that collectively +** makeup a single SQLite DB file. This allows the size of the DB +** to exceed the limits imposed by the file system. +** +** There is an instance of the following object for each defined multiplex +** group. +*/ +struct multiplexGroup { + struct multiplexReal { /* For each chunk */ + sqlite3_file *p; /* Handle for the chunk */ + char *z; /* Name of this chunk */ + } *aReal; /* list of all chunks */ + int nReal; /* Number of chunks */ + char *zName; /* Base filename of this group */ + int nName; /* Length of base filename */ + int flags; /* Flags used for original opening */ + unsigned int szChunk; /* Chunk size used for this group */ + unsigned char bEnabled; /* TRUE to use Multiplex VFS for this file */ + unsigned char bTruncate; /* TRUE to enable truncation of databases */ + multiplexGroup *pNext, *pPrev; /* Doubly linked list of all group objects */ +}; + +/* +** An instance of the following object represents each open connection +** to a file that is multiplex'ed. This object is a +** subclass of sqlite3_file. The sqlite3_file object for the underlying +** VFS is appended to this structure. +*/ +struct multiplexConn { + sqlite3_file base; /* Base class - must be first */ + multiplexGroup *pGroup; /* The underlying group of files */ +}; + +/************************* Global Variables **********************************/ +/* +** All global variables used by this file are containing within the following +** gMultiplex structure. +*/ +static struct { + /* The pOrigVfs is the real, original underlying VFS implementation. + ** Most operations pass-through to the real VFS. This value is read-only + ** during operation. It is only modified at start-time and thus does not + ** require a mutex. + */ + sqlite3_vfs *pOrigVfs; + + /* The sThisVfs is the VFS structure used by this shim. It is initialized + ** at start-time and thus does not require a mutex + */ + sqlite3_vfs sThisVfs; + + /* The sIoMethods defines the methods used by sqlite3_file objects + ** associated with this shim. It is initialized at start-time and does + ** not require a mutex. + ** + ** When the underlying VFS is called to open a file, it might return + ** either a version 1 or a version 2 sqlite3_file object. This shim + ** has to create a wrapper sqlite3_file of the same version. Hence + ** there are two I/O method structures, one for version 1 and the other + ** for version 2. + */ + sqlite3_io_methods sIoMethodsV1; + sqlite3_io_methods sIoMethodsV2; + + /* True when this shim has been initialized. + */ + int isInitialized; + + /* For run-time access any of the other global data structures in this + ** shim, the following mutex must be held. + */ + sqlite3_mutex *pMutex; + + /* List of multiplexGroup objects. + */ + multiplexGroup *pGroups; +} gMultiplex; + +/************************* Utility Routines *********************************/ +/* +** Acquire and release the mutex used to serialize access to the +** list of multiplexGroups. +*/ +static void multiplexEnter(void){ sqlite3_mutex_enter(gMultiplex.pMutex); } +static void multiplexLeave(void){ sqlite3_mutex_leave(gMultiplex.pMutex); } + +/* +** Compute a string length that is limited to what can be stored in +** lower 30 bits of a 32-bit signed integer. +** +** The value returned will never be negative. Nor will it ever be greater +** than the actual length of the string. For very long strings (greater +** than 1GiB) the value returned might be less than the true string length. +*/ +static int multiplexStrlen30(const char *z){ + const char *z2 = z; + if( z==0 ) return 0; + while( *z2 ){ z2++; } + return 0x3fffffff & (int)(z2 - z); +} + +/* +** Generate the file-name for chunk iChunk of the group with base name +** zBase. The file-name is written to buffer zOut before returning. Buffer +** zOut must be allocated by the caller so that it is at least (nBase+5) +** bytes in size, where nBase is the length of zBase, not including the +** nul-terminator. +** +** If iChunk is 0 (or 400 - the number for the first journal file chunk), +** the output is a copy of the input string. Otherwise, if +** SQLITE_ENABLE_8_3_NAMES is not defined or the input buffer does not contain +** a "." character, then the output is a copy of the input string with the +** three-digit zero-padded decimal representation if iChunk appended to it. +** For example: +** +** zBase="test.db", iChunk=4 -> zOut="test.db004" +** +** Or, if SQLITE_ENABLE_8_3_NAMES is defined and the input buffer contains +** a "." character, then everything after the "." is replaced by the +** three-digit representation of iChunk. +** +** zBase="test.db", iChunk=4 -> zOut="test.004" +** +** The output buffer string is terminated by 2 0x00 bytes. This makes it safe +** to pass to sqlite3_uri_parameter() and similar. +*/ +static void multiplexFilename( + const char *zBase, /* Filename for chunk 0 */ + int nBase, /* Size of zBase in bytes (without \0) */ + int flags, /* Flags used to open file */ + int iChunk, /* Chunk to generate filename for */ + char *zOut /* Buffer to write generated name to */ +){ + int n = nBase; + memcpy(zOut, zBase, n+1); + if( iChunk!=0 && iChunk<=MX_CHUNK_NUMBER ){ +#ifdef SQLITE_ENABLE_8_3_NAMES + int i; + for(i=n-1; i>0 && i>=n-4 && zOut[i]!='.'; i--){} + if( i>=n-4 ) n = i+1; + if( flags & SQLITE_OPEN_MAIN_JOURNAL ){ + /* The extensions on overflow files for main databases are 001, 002, + ** 003 and so forth. To avoid name collisions, add 400 to the + ** extensions of journal files so that they are 401, 402, 403, .... + */ + iChunk += SQLITE_MULTIPLEX_JOURNAL_8_3_OFFSET; + }else if( flags & SQLITE_OPEN_WAL ){ + /* To avoid name collisions, add 700 to the + ** extensions of WAL files so that they are 701, 702, 703, .... + */ + iChunk += SQLITE_MULTIPLEX_WAL_8_3_OFFSET; + } +#endif + sqlite3_snprintf(4,&zOut[n],"%03d",iChunk); + n += 3; + } + + assert( zOut[n]=='\0' ); + zOut[n+1] = '\0'; +} + +/* Compute the filename for the iChunk-th chunk +*/ +static int multiplexSubFilename(multiplexGroup *pGroup, int iChunk){ + if( iChunk>=pGroup->nReal ){ + struct multiplexReal *p; + p = sqlite3_realloc(pGroup->aReal, (iChunk+1)*sizeof(*p)); + if( p==0 ){ + return SQLITE_NOMEM; + } + memset(&p[pGroup->nReal], 0, sizeof(p[0])*(iChunk+1-pGroup->nReal)); + pGroup->aReal = p; + pGroup->nReal = iChunk+1; + } + if( pGroup->zName && pGroup->aReal[iChunk].z==0 ){ + char *z; + int n = pGroup->nName; + pGroup->aReal[iChunk].z = z = sqlite3_malloc( n+5 ); + if( z==0 ){ + return SQLITE_NOMEM; + } + multiplexFilename(pGroup->zName, pGroup->nName, pGroup->flags, iChunk, z); + } + return SQLITE_OK; +} + +/* Translate an sqlite3_file* that is really a multiplexGroup* into +** the sqlite3_file* for the underlying original VFS. +** +** For chunk 0, the pGroup->flags determines whether or not a new file +** is created if it does not already exist. For chunks 1 and higher, the +** file is created only if createFlag is 1. +*/ +static sqlite3_file *multiplexSubOpen( + multiplexGroup *pGroup, /* The multiplexor group */ + int iChunk, /* Which chunk to open. 0==original file */ + int *rc, /* Result code in and out */ + int *pOutFlags, /* Output flags */ + int createFlag /* True to create if iChunk>0 */ +){ + sqlite3_file *pSubOpen = 0; + sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs; /* Real VFS */ + +#ifdef SQLITE_ENABLE_8_3_NAMES + /* If JOURNAL_8_3_OFFSET is set to (say) 400, then any overflow files are + ** part of a database journal are named db.401, db.402, and so on. A + ** database may therefore not grow to larger than 400 chunks. Attempting + ** to open chunk 401 indicates the database is full. */ + if( iChunk>=SQLITE_MULTIPLEX_JOURNAL_8_3_OFFSET ){ + sqlite3_log(SQLITE_FULL, "multiplexed chunk overflow: %s", pGroup->zName); + *rc = SQLITE_FULL; + return 0; + } +#endif + + *rc = multiplexSubFilename(pGroup, iChunk); + if( (*rc)==SQLITE_OK && (pSubOpen = pGroup->aReal[iChunk].p)==0 ){ + int flags, bExists; + flags = pGroup->flags; + if( createFlag ){ + flags |= SQLITE_OPEN_CREATE; + }else if( iChunk==0 ){ + /* Fall through */ + }else if( pGroup->aReal[iChunk].z==0 ){ + return 0; + }else{ + *rc = pOrigVfs->xAccess(pOrigVfs, pGroup->aReal[iChunk].z, + SQLITE_ACCESS_EXISTS, &bExists); + if( *rc || !bExists ){ + if( *rc ){ + sqlite3_log(*rc, "multiplexor.xAccess failure on %s", + pGroup->aReal[iChunk].z); + } + return 0; + } + flags &= ~SQLITE_OPEN_CREATE; + } + pSubOpen = sqlite3_malloc( pOrigVfs->szOsFile ); + if( pSubOpen==0 ){ + *rc = SQLITE_IOERR_NOMEM; + return 0; + } + pGroup->aReal[iChunk].p = pSubOpen; + *rc = pOrigVfs->xOpen(pOrigVfs, pGroup->aReal[iChunk].z, pSubOpen, + flags, pOutFlags); + if( (*rc)!=SQLITE_OK ){ + sqlite3_log(*rc, "multiplexor.xOpen failure on %s", + pGroup->aReal[iChunk].z); + sqlite3_free(pSubOpen); + pGroup->aReal[iChunk].p = 0; + return 0; + } + } + return pSubOpen; +} + +/* +** Return the size, in bytes, of chunk number iChunk. If that chunk +** does not exist, then return 0. This function does not distingish between +** non-existant files and zero-length files. +*/ +static sqlite3_int64 multiplexSubSize( + multiplexGroup *pGroup, /* The multiplexor group */ + int iChunk, /* Which chunk to open. 0==original file */ + int *rc /* Result code in and out */ +){ + sqlite3_file *pSub; + sqlite3_int64 sz = 0; + + if( *rc ) return 0; + pSub = multiplexSubOpen(pGroup, iChunk, rc, NULL, 0); + if( pSub==0 ) return 0; + *rc = pSub->pMethods->xFileSize(pSub, &sz); + return sz; +} + +/* +** This is the implementation of the multiplex_control() SQL function. +*/ +static void multiplexControlFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int rc = SQLITE_OK; + sqlite3 *db = sqlite3_context_db_handle(context); + int op; + int iVal; + + if( !db || argc!=2 ){ + rc = SQLITE_ERROR; + }else{ + /* extract params */ + op = sqlite3_value_int(argv[0]); + iVal = sqlite3_value_int(argv[1]); + /* map function op to file_control op */ + switch( op ){ + case 1: + op = MULTIPLEX_CTRL_ENABLE; + break; + case 2: + op = MULTIPLEX_CTRL_SET_CHUNK_SIZE; + break; + case 3: + op = MULTIPLEX_CTRL_SET_MAX_CHUNKS; + break; + default: + rc = SQLITE_NOTFOUND; + break; + } + } + if( rc==SQLITE_OK ){ + rc = sqlite3_file_control(db, 0, op, &iVal); + } + sqlite3_result_error_code(context, rc); +} + +/* +** This is the entry point to register the auto-extension for the +** multiplex_control() function. +*/ +static int multiplexFuncInit( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc; + rc = sqlite3_create_function(db, "multiplex_control", 2, SQLITE_ANY, + 0, multiplexControlFunc, 0, 0); + return rc; +} + +/* +** Close a single sub-file in the connection group. +*/ +static void multiplexSubClose( + multiplexGroup *pGroup, + int iChunk, + sqlite3_vfs *pOrigVfs +){ + sqlite3_file *pSubOpen = pGroup->aReal[iChunk].p; + if( pSubOpen ){ + pSubOpen->pMethods->xClose(pSubOpen); + if( pOrigVfs && pGroup->aReal[iChunk].z ){ + pOrigVfs->xDelete(pOrigVfs, pGroup->aReal[iChunk].z, 0); + } + sqlite3_free(pGroup->aReal[iChunk].p); + } + sqlite3_free(pGroup->aReal[iChunk].z); + memset(&pGroup->aReal[iChunk], 0, sizeof(pGroup->aReal[iChunk])); +} + +/* +** Deallocate memory held by a multiplexGroup +*/ +static void multiplexFreeComponents(multiplexGroup *pGroup){ + int i; + for(i=0; inReal; i++){ multiplexSubClose(pGroup, i, 0); } + sqlite3_free(pGroup->aReal); + pGroup->aReal = 0; + pGroup->nReal = 0; +} + + +/************************* VFS Method Wrappers *****************************/ + +/* +** This is the xOpen method used for the "multiplex" VFS. +** +** Most of the work is done by the underlying original VFS. This method +** simply links the new file into the appropriate multiplex group if it is a +** file that needs to be tracked. +*/ +static int multiplexOpen( + sqlite3_vfs *pVfs, /* The multiplex VFS */ + const char *zName, /* Name of file to be opened */ + sqlite3_file *pConn, /* Fill in this file descriptor */ + int flags, /* Flags to control the opening */ + int *pOutFlags /* Flags showing results of opening */ +){ + int rc = SQLITE_OK; /* Result code */ + multiplexConn *pMultiplexOpen; /* The new multiplex file descriptor */ + multiplexGroup *pGroup = 0; /* Corresponding multiplexGroup object */ + sqlite3_file *pSubOpen = 0; /* Real file descriptor */ + sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs; /* Real VFS */ + int nName = 0; + int sz = 0; + char *zToFree = 0; + + UNUSED_PARAMETER(pVfs); + memset(pConn, 0, pVfs->szOsFile); + assert( zName || (flags & SQLITE_OPEN_DELETEONCLOSE) ); + + /* We need to create a group structure and manage + ** access to this group of files. + */ + multiplexEnter(); + pMultiplexOpen = (multiplexConn*)pConn; + + if( rc==SQLITE_OK ){ + /* allocate space for group */ + nName = zName ? multiplexStrlen30(zName) : 0; + sz = sizeof(multiplexGroup) /* multiplexGroup */ + + nName + 1; /* zName */ + pGroup = sqlite3_malloc( sz ); + if( pGroup==0 ){ + rc = SQLITE_NOMEM; + } + } + + if( rc==SQLITE_OK ){ + const char *zUri = (flags & SQLITE_OPEN_URI) ? zName : 0; + /* assign pointers to extra space allocated */ + memset(pGroup, 0, sz); + pMultiplexOpen->pGroup = pGroup; + pGroup->bEnabled = -1; + pGroup->bTruncate = sqlite3_uri_boolean(zUri, "truncate", + (flags & SQLITE_OPEN_MAIN_DB)==0); + pGroup->szChunk = (int)sqlite3_uri_int64(zUri, "chunksize", + SQLITE_MULTIPLEX_CHUNK_SIZE); + pGroup->szChunk = (pGroup->szChunk+0xffff)&~0xffff; + if( zName ){ + char *p = (char *)&pGroup[1]; + pGroup->zName = p; + memcpy(pGroup->zName, zName, nName+1); + pGroup->nName = nName; + } + if( pGroup->bEnabled ){ + /* Make sure that the chunksize is such that the pending byte does not + ** falls at the end of a chunk. A region of up to 64K following + ** the pending byte is never written, so if the pending byte occurs + ** near the end of a chunk, that chunk will be too small. */ +#ifndef SQLITE_OMIT_WSD + extern int sqlite3PendingByte; +#else + int sqlite3PendingByte = 0x40000000; +#endif + while( (sqlite3PendingByte % pGroup->szChunk)>=(pGroup->szChunk-65536) ){ + pGroup->szChunk += 65536; + } + } + pGroup->flags = flags; + rc = multiplexSubFilename(pGroup, 1); + if( rc==SQLITE_OK ){ + pSubOpen = multiplexSubOpen(pGroup, 0, &rc, pOutFlags, 0); + if( pSubOpen==0 && rc==SQLITE_OK ) rc = SQLITE_CANTOPEN; + } + if( rc==SQLITE_OK ){ + sqlite3_int64 sz; + + rc = pSubOpen->pMethods->xFileSize(pSubOpen, &sz); + if( rc==SQLITE_OK && zName ){ + int bExists; + if( sz==0 ){ + if( flags & SQLITE_OPEN_MAIN_JOURNAL ){ + /* If opening a main journal file and the first chunk is zero + ** bytes in size, delete any subsequent chunks from the + ** file-system. */ + int iChunk = 1; + do { + rc = pOrigVfs->xAccess(pOrigVfs, + pGroup->aReal[iChunk].z, SQLITE_ACCESS_EXISTS, &bExists + ); + if( rc==SQLITE_OK && bExists ){ + rc = pOrigVfs->xDelete(pOrigVfs, pGroup->aReal[iChunk].z, 0); + if( rc==SQLITE_OK ){ + rc = multiplexSubFilename(pGroup, ++iChunk); + } + } + }while( rc==SQLITE_OK && bExists ); + } + }else{ + /* If the first overflow file exists and if the size of the main file + ** is different from the chunk size, that means the chunk size is set + ** set incorrectly. So fix it. + ** + ** Or, if the first overflow file does not exist and the main file is + ** larger than the chunk size, that means the chunk size is too small. + ** But we have no way of determining the intended chunk size, so + ** just disable the multiplexor all togethre. + */ + rc = pOrigVfs->xAccess(pOrigVfs, pGroup->aReal[1].z, + SQLITE_ACCESS_EXISTS, &bExists); + bExists = multiplexSubSize(pGroup, 1, &rc)>0; + if( rc==SQLITE_OK && bExists && sz==(sz&0xffff0000) && sz>0 + && sz!=pGroup->szChunk ){ + pGroup->szChunk = (int)sz; + }else if( rc==SQLITE_OK && !bExists && sz>pGroup->szChunk ){ + pGroup->bEnabled = 0; + } + } + } + } + + if( rc==SQLITE_OK ){ + if( pSubOpen->pMethods->iVersion==1 ){ + pMultiplexOpen->base.pMethods = &gMultiplex.sIoMethodsV1; + }else{ + pMultiplexOpen->base.pMethods = &gMultiplex.sIoMethodsV2; + } + /* place this group at the head of our list */ + pGroup->pNext = gMultiplex.pGroups; + if( gMultiplex.pGroups ) gMultiplex.pGroups->pPrev = pGroup; + gMultiplex.pGroups = pGroup; + }else{ + multiplexFreeComponents(pGroup); + sqlite3_free(pGroup); + } + } + multiplexLeave(); + sqlite3_free(zToFree); + return rc; +} + +/* +** This is the xDelete method used for the "multiplex" VFS. +** It attempts to delete the filename specified. +*/ +static int multiplexDelete( + sqlite3_vfs *pVfs, /* The multiplex VFS */ + const char *zName, /* Name of file to delete */ + int syncDir +){ + int rc; + sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs; /* Real VFS */ + rc = pOrigVfs->xDelete(pOrigVfs, zName, syncDir); + if( rc==SQLITE_OK ){ + /* If the main chunk was deleted successfully, also delete any subsequent + ** chunks - starting with the last (highest numbered). + */ + int nName = (int)strlen(zName); + char *z; + z = sqlite3_malloc(nName + 5); + if( z==0 ){ + rc = SQLITE_IOERR_NOMEM; + }else{ + int iChunk = 0; + int bExists; + do{ + multiplexFilename(zName, nName, SQLITE_OPEN_MAIN_JOURNAL, ++iChunk, z); + rc = pOrigVfs->xAccess(pOrigVfs, z, SQLITE_ACCESS_EXISTS, &bExists); + }while( rc==SQLITE_OK && bExists ); + while( rc==SQLITE_OK && iChunk>1 ){ + multiplexFilename(zName, nName, SQLITE_OPEN_MAIN_JOURNAL, --iChunk, z); + rc = pOrigVfs->xDelete(pOrigVfs, z, syncDir); + } + if( rc==SQLITE_OK ){ + iChunk = 0; + do{ + multiplexFilename(zName, nName, SQLITE_OPEN_WAL, ++iChunk, z); + rc = pOrigVfs->xAccess(pOrigVfs, z, SQLITE_ACCESS_EXISTS, &bExists); + }while( rc==SQLITE_OK && bExists ); + while( rc==SQLITE_OK && iChunk>1 ){ + multiplexFilename(zName, nName, SQLITE_OPEN_WAL, --iChunk, z); + rc = pOrigVfs->xDelete(pOrigVfs, z, syncDir); + } + } + } + sqlite3_free(z); + } + return rc; +} + +static int multiplexAccess(sqlite3_vfs *a, const char *b, int c, int *d){ + return gMultiplex.pOrigVfs->xAccess(gMultiplex.pOrigVfs, b, c, d); +} +static int multiplexFullPathname(sqlite3_vfs *a, const char *b, int c, char *d){ + return gMultiplex.pOrigVfs->xFullPathname(gMultiplex.pOrigVfs, b, c, d); +} +static void *multiplexDlOpen(sqlite3_vfs *a, const char *b){ + return gMultiplex.pOrigVfs->xDlOpen(gMultiplex.pOrigVfs, b); +} +static void multiplexDlError(sqlite3_vfs *a, int b, char *c){ + gMultiplex.pOrigVfs->xDlError(gMultiplex.pOrigVfs, b, c); +} +static void (*multiplexDlSym(sqlite3_vfs *a, void *b, const char *c))(void){ + return gMultiplex.pOrigVfs->xDlSym(gMultiplex.pOrigVfs, b, c); +} +static void multiplexDlClose(sqlite3_vfs *a, void *b){ + gMultiplex.pOrigVfs->xDlClose(gMultiplex.pOrigVfs, b); +} +static int multiplexRandomness(sqlite3_vfs *a, int b, char *c){ + return gMultiplex.pOrigVfs->xRandomness(gMultiplex.pOrigVfs, b, c); +} +static int multiplexSleep(sqlite3_vfs *a, int b){ + return gMultiplex.pOrigVfs->xSleep(gMultiplex.pOrigVfs, b); +} +static int multiplexCurrentTime(sqlite3_vfs *a, double *b){ + return gMultiplex.pOrigVfs->xCurrentTime(gMultiplex.pOrigVfs, b); +} +static int multiplexGetLastError(sqlite3_vfs *a, int b, char *c){ + return gMultiplex.pOrigVfs->xGetLastError(gMultiplex.pOrigVfs, b, c); +} +static int multiplexCurrentTimeInt64(sqlite3_vfs *a, sqlite3_int64 *b){ + return gMultiplex.pOrigVfs->xCurrentTimeInt64(gMultiplex.pOrigVfs, b); +} + +/************************ I/O Method Wrappers *******************************/ + +/* xClose requests get passed through to the original VFS. +** We loop over all open chunk handles and close them. +** The group structure for this file is unlinked from +** our list of groups and freed. +*/ +static int multiplexClose(sqlite3_file *pConn){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + multiplexEnter(); + multiplexFreeComponents(pGroup); + /* remove from linked list */ + if( pGroup->pNext ) pGroup->pNext->pPrev = pGroup->pPrev; + if( pGroup->pPrev ){ + pGroup->pPrev->pNext = pGroup->pNext; + }else{ + gMultiplex.pGroups = pGroup->pNext; + } + sqlite3_free(pGroup); + multiplexLeave(); + return rc; +} + +/* Pass xRead requests thru to the original VFS after +** determining the correct chunk to operate on. +** Break up reads across chunk boundaries. +*/ +static int multiplexRead( + sqlite3_file *pConn, + void *pBuf, + int iAmt, + sqlite3_int64 iOfst +){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + multiplexEnter(); + if( !pGroup->bEnabled ){ + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen==0 ){ + rc = SQLITE_IOERR_READ; + }else{ + rc = pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt, iOfst); + } + }else{ + while( iAmt > 0 ){ + int i = (int)(iOfst / pGroup->szChunk); + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1); + if( pSubOpen ){ + int extra = ((int)(iOfst % pGroup->szChunk) + iAmt) - pGroup->szChunk; + if( extra<0 ) extra = 0; + iAmt -= extra; + rc = pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt, + iOfst % pGroup->szChunk); + if( rc!=SQLITE_OK ) break; + pBuf = (char *)pBuf + iAmt; + iOfst += iAmt; + iAmt = extra; + }else{ + rc = SQLITE_IOERR_READ; + break; + } + } + } + multiplexLeave(); + return rc; +} + +/* Pass xWrite requests thru to the original VFS after +** determining the correct chunk to operate on. +** Break up writes across chunk boundaries. +*/ +static int multiplexWrite( + sqlite3_file *pConn, + const void *pBuf, + int iAmt, + sqlite3_int64 iOfst +){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + multiplexEnter(); + if( !pGroup->bEnabled ){ + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen==0 ){ + rc = SQLITE_IOERR_WRITE; + }else{ + rc = pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt, iOfst); + } + }else{ + while( rc==SQLITE_OK && iAmt>0 ){ + int i = (int)(iOfst / pGroup->szChunk); + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1); + if( pSubOpen ){ + int extra = ((int)(iOfst % pGroup->szChunk) + iAmt) - + pGroup->szChunk; + if( extra<0 ) extra = 0; + iAmt -= extra; + rc = pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt, + iOfst % pGroup->szChunk); + pBuf = (char *)pBuf + iAmt; + iOfst += iAmt; + iAmt = extra; + } + } + } + multiplexLeave(); + return rc; +} + +/* Pass xTruncate requests thru to the original VFS after +** determining the correct chunk to operate on. Delete any +** chunks above the truncate mark. +*/ +static int multiplexTruncate(sqlite3_file *pConn, sqlite3_int64 size){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + multiplexEnter(); + if( !pGroup->bEnabled ){ + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen==0 ){ + rc = SQLITE_IOERR_TRUNCATE; + }else{ + rc = pSubOpen->pMethods->xTruncate(pSubOpen, size); + } + }else{ + int i; + int iBaseGroup = (int)(size / pGroup->szChunk); + sqlite3_file *pSubOpen; + sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs; /* Real VFS */ + /* delete the chunks above the truncate limit */ + for(i = pGroup->nReal-1; i>iBaseGroup && rc==SQLITE_OK; i--){ + if( pGroup->bTruncate ){ + multiplexSubClose(pGroup, i, pOrigVfs); + }else{ + pSubOpen = multiplexSubOpen(pGroup, i, &rc, 0, 0); + if( pSubOpen ){ + rc = pSubOpen->pMethods->xTruncate(pSubOpen, 0); + } + } + } + if( rc==SQLITE_OK ){ + pSubOpen = multiplexSubOpen(pGroup, iBaseGroup, &rc, 0, 0); + if( pSubOpen ){ + rc = pSubOpen->pMethods->xTruncate(pSubOpen, size % pGroup->szChunk); + } + } + if( rc ) rc = SQLITE_IOERR_TRUNCATE; + } + multiplexLeave(); + return rc; +} + +/* Pass xSync requests through to the original VFS without change +*/ +static int multiplexSync(sqlite3_file *pConn, int flags){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + int i; + multiplexEnter(); + for(i=0; inReal; i++){ + sqlite3_file *pSubOpen = pGroup->aReal[i].p; + if( pSubOpen ){ + int rc2 = pSubOpen->pMethods->xSync(pSubOpen, flags); + if( rc2!=SQLITE_OK ) rc = rc2; + } + } + multiplexLeave(); + return rc; +} + +/* Pass xFileSize requests through to the original VFS. +** Aggregate the size of all the chunks before returning. +*/ +static int multiplexFileSize(sqlite3_file *pConn, sqlite3_int64 *pSize){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_OK; + int i; + multiplexEnter(); + if( !pGroup->bEnabled ){ + sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen==0 ){ + rc = SQLITE_IOERR_FSTAT; + }else{ + rc = pSubOpen->pMethods->xFileSize(pSubOpen, pSize); + } + }else{ + *pSize = 0; + for(i=0; rc==SQLITE_OK; i++){ + sqlite3_int64 sz = multiplexSubSize(pGroup, i, &rc); + if( sz==0 ) break; + *pSize = i*(sqlite3_int64)pGroup->szChunk + sz; + } + } + multiplexLeave(); + return rc; +} + +/* Pass xLock requests through to the original VFS unchanged. +*/ +static int multiplexLock(sqlite3_file *pConn, int lock){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xLock(pSubOpen, lock); + } + return SQLITE_BUSY; +} + +/* Pass xUnlock requests through to the original VFS unchanged. +*/ +static int multiplexUnlock(sqlite3_file *pConn, int lock){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xUnlock(pSubOpen, lock); + } + return SQLITE_IOERR_UNLOCK; +} + +/* Pass xCheckReservedLock requests through to the original VFS unchanged. +*/ +static int multiplexCheckReservedLock(sqlite3_file *pConn, int *pResOut){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xCheckReservedLock(pSubOpen, pResOut); + } + return SQLITE_IOERR_CHECKRESERVEDLOCK; +} + +/* Pass xFileControl requests through to the original VFS unchanged, +** except for any MULTIPLEX_CTRL_* requests here. +*/ +static int multiplexFileControl(sqlite3_file *pConn, int op, void *pArg){ + multiplexConn *p = (multiplexConn*)pConn; + multiplexGroup *pGroup = p->pGroup; + int rc = SQLITE_ERROR; + sqlite3_file *pSubOpen; + + if( !gMultiplex.isInitialized ) return SQLITE_MISUSE; + switch( op ){ + case MULTIPLEX_CTRL_ENABLE: + if( pArg ) { + int bEnabled = *(int *)pArg; + pGroup->bEnabled = bEnabled; + rc = SQLITE_OK; + } + break; + case MULTIPLEX_CTRL_SET_CHUNK_SIZE: + if( pArg ) { + unsigned int szChunk = *(unsigned*)pArg; + if( szChunk<1 ){ + rc = SQLITE_MISUSE; + }else{ + /* Round up to nearest multiple of MAX_PAGE_SIZE. */ + szChunk = (szChunk + (MAX_PAGE_SIZE-1)); + szChunk &= ~(MAX_PAGE_SIZE-1); + pGroup->szChunk = szChunk; + rc = SQLITE_OK; + } + } + break; + case MULTIPLEX_CTRL_SET_MAX_CHUNKS: + rc = SQLITE_OK; + break; + case SQLITE_FCNTL_SIZE_HINT: + case SQLITE_FCNTL_CHUNK_SIZE: + /* no-op these */ + rc = SQLITE_OK; + break; + default: + pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + rc = pSubOpen->pMethods->xFileControl(pSubOpen, op, pArg); + if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){ + *(char**)pArg = sqlite3_mprintf("multiplex/%z", *(char**)pArg); + } + } + break; + } + return rc; +} + +/* Pass xSectorSize requests through to the original VFS unchanged. +*/ +static int multiplexSectorSize(sqlite3_file *pConn){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen && pSubOpen->pMethods->xSectorSize ){ + return pSubOpen->pMethods->xSectorSize(pSubOpen); + } + return DEFAULT_SECTOR_SIZE; +} + +/* Pass xDeviceCharacteristics requests through to the original VFS unchanged. +*/ +static int multiplexDeviceCharacteristics(sqlite3_file *pConn){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xDeviceCharacteristics(pSubOpen); + } + return 0; +} + +/* Pass xShmMap requests through to the original VFS unchanged. +*/ +static int multiplexShmMap( + sqlite3_file *pConn, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int szRegion, /* Size of regions */ + int bExtend, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xShmMap(pSubOpen, iRegion, szRegion, bExtend,pp); + } + return SQLITE_IOERR; +} + +/* Pass xShmLock requests through to the original VFS unchanged. +*/ +static int multiplexShmLock( + sqlite3_file *pConn, /* Database file holding the shared memory */ + int ofst, /* First lock to acquire or release */ + int n, /* Number of locks to acquire or release */ + int flags /* What to do with the lock */ +){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xShmLock(pSubOpen, ofst, n, flags); + } + return SQLITE_BUSY; +} + +/* Pass xShmBarrier requests through to the original VFS unchanged. +*/ +static void multiplexShmBarrier(sqlite3_file *pConn){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + pSubOpen->pMethods->xShmBarrier(pSubOpen); + } +} + +/* Pass xShmUnmap requests through to the original VFS unchanged. +*/ +static int multiplexShmUnmap(sqlite3_file *pConn, int deleteFlag){ + multiplexConn *p = (multiplexConn*)pConn; + int rc; + sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0); + if( pSubOpen ){ + return pSubOpen->pMethods->xShmUnmap(pSubOpen, deleteFlag); + } + return SQLITE_OK; +} + +/************************** Public Interfaces *****************************/ +/* +** CAPI: Initialize the multiplex VFS shim - sqlite3_multiplex_initialize() +** +** Use the VFS named zOrigVfsName as the VFS that does the actual work. +** Use the default if zOrigVfsName==NULL. +** +** The multiplex VFS shim is named "multiplex". It will become the default +** VFS if makeDefault is non-zero. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once +** during start-up. +*/ +int sqlite3_multiplex_initialize(const char *zOrigVfsName, int makeDefault){ + sqlite3_vfs *pOrigVfs; + if( gMultiplex.isInitialized ) return SQLITE_MISUSE; + pOrigVfs = sqlite3_vfs_find(zOrigVfsName); + if( pOrigVfs==0 ) return SQLITE_ERROR; + assert( pOrigVfs!=&gMultiplex.sThisVfs ); + gMultiplex.pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( !gMultiplex.pMutex ){ + return SQLITE_NOMEM; + } + gMultiplex.pGroups = NULL; + gMultiplex.isInitialized = 1; + gMultiplex.pOrigVfs = pOrigVfs; + gMultiplex.sThisVfs = *pOrigVfs; + gMultiplex.sThisVfs.szOsFile += sizeof(multiplexConn); + gMultiplex.sThisVfs.zName = SQLITE_MULTIPLEX_VFS_NAME; + gMultiplex.sThisVfs.xOpen = multiplexOpen; + gMultiplex.sThisVfs.xDelete = multiplexDelete; + gMultiplex.sThisVfs.xAccess = multiplexAccess; + gMultiplex.sThisVfs.xFullPathname = multiplexFullPathname; + gMultiplex.sThisVfs.xDlOpen = multiplexDlOpen; + gMultiplex.sThisVfs.xDlError = multiplexDlError; + gMultiplex.sThisVfs.xDlSym = multiplexDlSym; + gMultiplex.sThisVfs.xDlClose = multiplexDlClose; + gMultiplex.sThisVfs.xRandomness = multiplexRandomness; + gMultiplex.sThisVfs.xSleep = multiplexSleep; + gMultiplex.sThisVfs.xCurrentTime = multiplexCurrentTime; + gMultiplex.sThisVfs.xGetLastError = multiplexGetLastError; + gMultiplex.sThisVfs.xCurrentTimeInt64 = multiplexCurrentTimeInt64; + + gMultiplex.sIoMethodsV1.iVersion = 1; + gMultiplex.sIoMethodsV1.xClose = multiplexClose; + gMultiplex.sIoMethodsV1.xRead = multiplexRead; + gMultiplex.sIoMethodsV1.xWrite = multiplexWrite; + gMultiplex.sIoMethodsV1.xTruncate = multiplexTruncate; + gMultiplex.sIoMethodsV1.xSync = multiplexSync; + gMultiplex.sIoMethodsV1.xFileSize = multiplexFileSize; + gMultiplex.sIoMethodsV1.xLock = multiplexLock; + gMultiplex.sIoMethodsV1.xUnlock = multiplexUnlock; + gMultiplex.sIoMethodsV1.xCheckReservedLock = multiplexCheckReservedLock; + gMultiplex.sIoMethodsV1.xFileControl = multiplexFileControl; + gMultiplex.sIoMethodsV1.xSectorSize = multiplexSectorSize; + gMultiplex.sIoMethodsV1.xDeviceCharacteristics = + multiplexDeviceCharacteristics; + gMultiplex.sIoMethodsV2 = gMultiplex.sIoMethodsV1; + gMultiplex.sIoMethodsV2.iVersion = 2; + gMultiplex.sIoMethodsV2.xShmMap = multiplexShmMap; + gMultiplex.sIoMethodsV2.xShmLock = multiplexShmLock; + gMultiplex.sIoMethodsV2.xShmBarrier = multiplexShmBarrier; + gMultiplex.sIoMethodsV2.xShmUnmap = multiplexShmUnmap; + sqlite3_vfs_register(&gMultiplex.sThisVfs, makeDefault); + + sqlite3_auto_extension((void*)multiplexFuncInit); + + return SQLITE_OK; +} + +/* +** CAPI: Shutdown the multiplex system - sqlite3_multiplex_shutdown() +** +** All SQLite database connections must be closed before calling this +** routine. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once while +** shutting down in order to free all remaining multiplex groups. +*/ +int sqlite3_multiplex_shutdown(void){ + if( gMultiplex.isInitialized==0 ) return SQLITE_MISUSE; + if( gMultiplex.pGroups ) return SQLITE_MISUSE; + gMultiplex.isInitialized = 0; + sqlite3_mutex_free(gMultiplex.pMutex); + sqlite3_vfs_unregister(&gMultiplex.sThisVfs); + memset(&gMultiplex, 0, sizeof(gMultiplex)); + return SQLITE_OK; +} + +/***************************** Test Code ***********************************/ +#ifdef SQLITE_TEST +#include +extern const char *sqlite3ErrName(int); + + +/* +** tclcmd: sqlite3_multiplex_initialize NAME MAKEDEFAULT +*/ +static int test_multiplex_initialize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zName; /* Name of new multiplex VFS */ + int makeDefault; /* True to make the new VFS the default */ + int rc; /* Value returned by multiplex_initialize() */ + + UNUSED_PARAMETER(clientData); + + /* Process arguments */ + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "NAME MAKEDEFAULT"); + return TCL_ERROR; + } + zName = Tcl_GetString(objv[1]); + if( Tcl_GetBooleanFromObj(interp, objv[2], &makeDefault) ) return TCL_ERROR; + if( zName[0]=='\0' ) zName = 0; + + /* Call sqlite3_multiplex_initialize() */ + rc = sqlite3_multiplex_initialize(zName, makeDefault); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + + return TCL_OK; +} + +/* +** tclcmd: sqlite3_multiplex_shutdown +*/ +static int test_multiplex_shutdown( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; /* Value returned by multiplex_shutdown() */ + + UNUSED_PARAMETER(clientData); + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + /* Call sqlite3_multiplex_shutdown() */ + rc = sqlite3_multiplex_shutdown(); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + + return TCL_OK; +} + +/* +** tclcmd: sqlite3_multiplex_dump +*/ +static int test_multiplex_dump( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Obj *pResult; + Tcl_Obj *pGroupTerm; + multiplexGroup *pGroup; + int i; + int nChunks = 0; + + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); + + pResult = Tcl_NewObj(); + multiplexEnter(); + for(pGroup=gMultiplex.pGroups; pGroup; pGroup=pGroup->pNext){ + pGroupTerm = Tcl_NewObj(); + + if( pGroup->zName ){ + pGroup->zName[pGroup->nName] = '\0'; + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewStringObj(pGroup->zName, -1)); + }else{ + Tcl_ListObjAppendElement(interp, pGroupTerm, Tcl_NewObj()); + } + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(pGroup->nName)); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(pGroup->flags)); + + /* count number of chunks with open handles */ + for(i=0; inReal; i++){ + if( pGroup->aReal[i].p!=0 ) nChunks++; + } + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(nChunks)); + + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(pGroup->szChunk)); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewIntObj(pGroup->nReal)); + + Tcl_ListObjAppendElement(interp, pResult, pGroupTerm); + } + multiplexLeave(); + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + +/* +** Tclcmd: test_multiplex_control HANDLE DBNAME SUB-COMMAND ?INT-VALUE? +*/ +static int test_multiplex_control( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; /* Return code from file_control() */ + int idx; /* Index in aSub[] */ + Tcl_CmdInfo cmdInfo; /* Command info structure for HANDLE */ + sqlite3 *db; /* Underlying db handle for HANDLE */ + int iValue = 0; + void *pArg = 0; + + struct SubCommand { + const char *zName; + int op; + int argtype; + } aSub[] = { + { "enable", MULTIPLEX_CTRL_ENABLE, 1 }, + { "chunk_size", MULTIPLEX_CTRL_SET_CHUNK_SIZE, 1 }, + { "max_chunks", MULTIPLEX_CTRL_SET_MAX_CHUNKS, 1 }, + { 0, 0, 0 } + }; + + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE DBNAME SUB-COMMAND INT-VALUE"); + return TCL_ERROR; + } + + if( 0==Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){ + Tcl_AppendResult(interp, "expected database handle, got \"", 0); + Tcl_AppendResult(interp, Tcl_GetString(objv[1]), "\"", 0); + return TCL_ERROR; + }else{ + db = *(sqlite3 **)cmdInfo.objClientData; + } + + rc = Tcl_GetIndexFromObjStruct( + interp, objv[3], aSub, sizeof(aSub[0]), "sub-command", 0, &idx + ); + if( rc!=TCL_OK ) return rc; + + switch( aSub[idx].argtype ){ + case 1: + if( Tcl_GetIntFromObj(interp, objv[4], &iValue) ){ + return TCL_ERROR; + } + pArg = (void *)&iValue; + break; + default: + Tcl_WrongNumArgs(interp, 4, objv, "SUB-COMMAND"); + return TCL_ERROR; + } + + rc = sqlite3_file_control(db, Tcl_GetString(objv[2]), aSub[idx].op, pArg); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + return (rc==SQLITE_OK) ? TCL_OK : TCL_ERROR; +} + +/* +** This routine registers the custom TCL commands defined in this +** module. This should be the only procedure visible from outside +** of this module. +*/ +int Sqlitemultiplex_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aCmd[] = { + { "sqlite3_multiplex_initialize", test_multiplex_initialize }, + { "sqlite3_multiplex_shutdown", test_multiplex_shutdown }, + { "sqlite3_multiplex_dump", test_multiplex_dump }, + { "sqlite3_multiplex_control", test_multiplex_control }, + }; + int i; + + for(i=0; i,); +** +** =1 MULTIPLEX_CTRL_ENABLE +** =0 disable +** =1 enable +** +** =2 MULTIPLEX_CTRL_SET_CHUNK_SIZE +** int, chunk size +** +** =3 MULTIPLEX_CTRL_SET_MAX_CHUNKS +** int, max chunks +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once +** during start-up. +*/ +extern int sqlite3_multiplex_initialize(const char *zOrigVfsName, int makeDefault); + +/* +** CAPI: Shutdown the multiplex system - sqlite3_multiplex_shutdown() +** +** All SQLite database connections must be closed before calling this +** routine. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once while +** shutting down in order to free all remaining multiplex groups. +*/ +extern int sqlite3_multiplex_shutdown(void); + +#ifdef __cplusplus +} /* End of the 'extern "C"' block */ +#endif + +#endif /* _TEST_MULTIPLEX_H */ diff --git a/components/external/SQLite-3.8.1/src/test_mutex.c b/components/external/SQLite-3.8.1/src/test_mutex.c new file mode 100644 index 0000000000000000000000000000000000000000..c9b4a29ab75c77ea5f36b5193256d70fe6580e95 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_mutex.c @@ -0,0 +1,439 @@ +/* +** 2008 June 18 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains test logic for the sqlite3_mutex interfaces. +*/ + +#include "tcl.h" +#include "sqlite3.h" +#include "sqliteInt.h" +#include +#include +#include + +/* defined in main.c */ +extern const char *sqlite3ErrName(int); + +/* A countable mutex */ +struct sqlite3_mutex { + sqlite3_mutex *pReal; + int eType; +}; + +/* State variables */ +static struct test_mutex_globals { + int isInstalled; /* True if installed */ + int disableInit; /* True to cause sqlite3_initalize() to fail */ + int disableTry; /* True to force sqlite3_mutex_try() to fail */ + int isInit; /* True if initialized */ + sqlite3_mutex_methods m; /* Interface to "real" mutex system */ + int aCounter[8]; /* Number of grabs of each type of mutex */ + sqlite3_mutex aStatic[6]; /* The six static mutexes */ +} g = {0}; + +/* Return true if the countable mutex is currently held */ +static int counterMutexHeld(sqlite3_mutex *p){ + return g.m.xMutexHeld(p->pReal); +} + +/* Return true if the countable mutex is not currently held */ +static int counterMutexNotheld(sqlite3_mutex *p){ + return g.m.xMutexNotheld(p->pReal); +} + +/* Initialize the countable mutex interface +** Or, if g.disableInit is non-zero, then do not initialize but instead +** return the value of g.disableInit as the result code. This can be used +** to simulate an initialization failure. +*/ +static int counterMutexInit(void){ + int rc; + if( g.disableInit ) return g.disableInit; + rc = g.m.xMutexInit(); + g.isInit = 1; + return rc; +} + +/* +** Uninitialize the mutex subsystem +*/ +static int counterMutexEnd(void){ + g.isInit = 0; + return g.m.xMutexEnd(); +} + +/* +** Allocate a countable mutex +*/ +static sqlite3_mutex *counterMutexAlloc(int eType){ + sqlite3_mutex *pReal; + sqlite3_mutex *pRet = 0; + + assert( g.isInit ); + assert(eType<8 && eType>=0); + + pReal = g.m.xMutexAlloc(eType); + if( !pReal ) return 0; + + if( eType==SQLITE_MUTEX_FAST || eType==SQLITE_MUTEX_RECURSIVE ){ + pRet = (sqlite3_mutex *)malloc(sizeof(sqlite3_mutex)); + }else{ + pRet = &g.aStatic[eType-2]; + } + + pRet->eType = eType; + pRet->pReal = pReal; + return pRet; +} + +/* +** Free a countable mutex +*/ +static void counterMutexFree(sqlite3_mutex *p){ + assert( g.isInit ); + g.m.xMutexFree(p->pReal); + if( p->eType==SQLITE_MUTEX_FAST || p->eType==SQLITE_MUTEX_RECURSIVE ){ + free(p); + } +} + +/* +** Enter a countable mutex. Block until entry is safe. +*/ +static void counterMutexEnter(sqlite3_mutex *p){ + assert( g.isInit ); + g.aCounter[p->eType]++; + g.m.xMutexEnter(p->pReal); +} + +/* +** Try to enter a mutex. Return true on success. +*/ +static int counterMutexTry(sqlite3_mutex *p){ + assert( g.isInit ); + g.aCounter[p->eType]++; + if( g.disableTry ) return SQLITE_BUSY; + return g.m.xMutexTry(p->pReal); +} + +/* Leave a mutex +*/ +static void counterMutexLeave(sqlite3_mutex *p){ + assert( g.isInit ); + g.m.xMutexLeave(p->pReal); +} + +/* +** sqlite3_shutdown +*/ +static int test_shutdown( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + rc = sqlite3_shutdown(); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** sqlite3_initialize +*/ +static int test_initialize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + rc = sqlite3_initialize(); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** install_mutex_counters BOOLEAN +*/ +static int test_install_mutex_counters( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc = SQLITE_OK; + int isInstall; + + sqlite3_mutex_methods counter_methods = { + counterMutexInit, + counterMutexEnd, + counterMutexAlloc, + counterMutexFree, + counterMutexEnter, + counterMutexTry, + counterMutexLeave, + counterMutexHeld, + counterMutexNotheld + }; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN"); + return TCL_ERROR; + } + if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[1], &isInstall) ){ + return TCL_ERROR; + } + + assert(isInstall==0 || isInstall==1); + assert(g.isInstalled==0 || g.isInstalled==1); + if( isInstall==g.isInstalled ){ + Tcl_AppendResult(interp, "mutex counters are ", 0); + Tcl_AppendResult(interp, isInstall?"already installed":"not installed", 0); + return TCL_ERROR; + } + + if( isInstall ){ + assert( g.m.xMutexAlloc==0 ); + rc = sqlite3_config(SQLITE_CONFIG_GETMUTEX, &g.m); + if( rc==SQLITE_OK ){ + sqlite3_config(SQLITE_CONFIG_MUTEX, &counter_methods); + } + g.disableTry = 0; + }else{ + assert( g.m.xMutexAlloc ); + rc = sqlite3_config(SQLITE_CONFIG_MUTEX, &g.m); + memset(&g.m, 0, sizeof(sqlite3_mutex_methods)); + } + + if( rc==SQLITE_OK ){ + g.isInstalled = isInstall; + } + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +/* +** read_mutex_counters +*/ +static int test_read_mutex_counters( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Obj *pRet; + int ii; + char *aName[8] = { + "fast", "recursive", "static_master", "static_mem", + "static_open", "static_prng", "static_lru", "static_pmem" + }; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + pRet = Tcl_NewObj(); + Tcl_IncrRefCount(pRet); + for(ii=0; ii<8; ii++){ + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(aName[ii], -1)); + Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(g.aCounter[ii])); + } + Tcl_SetObjResult(interp, pRet); + Tcl_DecrRefCount(pRet); + + return TCL_OK; +} + +/* +** clear_mutex_counters +*/ +static int test_clear_mutex_counters( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int ii; + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + for(ii=0; ii<8; ii++){ + g.aCounter[ii] = 0; + } + return TCL_OK; +} + +/* +** Create and free a mutex. Return the mutex pointer. The pointer +** will be invalid since the mutex has already been freed. The +** return pointer just checks to see if the mutex really was allocated. +*/ +static int test_alloc_mutex( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#if SQLITE_THREADSAFE + sqlite3_mutex *p = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + char zBuf[100]; + sqlite3_mutex_free(p); + sqlite3_snprintf(sizeof(zBuf), zBuf, "%p", p); + Tcl_AppendResult(interp, zBuf, (char*)0); +#endif + return TCL_OK; +} + +/* +** sqlite3_config OPTION +** +** OPTION can be either one of the keywords: +** +** SQLITE_CONFIG_SINGLETHREAD +** SQLITE_CONFIG_MULTITHREAD +** SQLITE_CONFIG_SERIALIZED +** +** Or OPTION can be an raw integer. +*/ +static int test_config( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct ConfigOption { + const char *zName; + int iValue; + } aOpt[] = { + {"singlethread", SQLITE_CONFIG_SINGLETHREAD}, + {"multithread", SQLITE_CONFIG_MULTITHREAD}, + {"serialized", SQLITE_CONFIG_SERIALIZED}, + {0, 0} + }; + int s = sizeof(struct ConfigOption); + int i; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + if( Tcl_GetIndexFromObjStruct(interp, objv[1], aOpt, s, "flag", 0, &i) ){ + if( Tcl_GetIntFromObj(interp, objv[1], &i) ){ + return TCL_ERROR; + } + }else{ + i = aOpt[i].iValue; + } + + rc = sqlite3_config(i); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_VOLATILE); + return TCL_OK; +} + +static sqlite3 *getDbPointer(Tcl_Interp *pInterp, Tcl_Obj *pObj){ + sqlite3 *db; + Tcl_CmdInfo info; + char *zCmd = Tcl_GetString(pObj); + if( Tcl_GetCommandInfo(pInterp, zCmd, &info) ){ + db = *((sqlite3 **)info.objClientData); + }else{ + db = (sqlite3*)sqlite3TestTextToPtr(zCmd); + } + assert( db ); + return db; +} + +static int test_enter_db_mutex( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + db = getDbPointer(interp, objv[1]); + if( !db ){ + return TCL_ERROR; + } + sqlite3_mutex_enter(sqlite3_db_mutex(db)); + return TCL_OK; +} + +static int test_leave_db_mutex( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + db = getDbPointer(interp, objv[1]); + if( !db ){ + return TCL_ERROR; + } + sqlite3_mutex_leave(sqlite3_db_mutex(db)); + return TCL_OK; +} + +int Sqlitetest_mutex_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aCmd[] = { + { "sqlite3_shutdown", (Tcl_ObjCmdProc*)test_shutdown }, + { "sqlite3_initialize", (Tcl_ObjCmdProc*)test_initialize }, + { "sqlite3_config", (Tcl_ObjCmdProc*)test_config }, + + { "enter_db_mutex", (Tcl_ObjCmdProc*)test_enter_db_mutex }, + { "leave_db_mutex", (Tcl_ObjCmdProc*)test_leave_db_mutex }, + + { "alloc_dealloc_mutex", (Tcl_ObjCmdProc*)test_alloc_mutex }, + { "install_mutex_counters", (Tcl_ObjCmdProc*)test_install_mutex_counters }, + { "read_mutex_counters", (Tcl_ObjCmdProc*)test_read_mutex_counters }, + { "clear_mutex_counters", (Tcl_ObjCmdProc*)test_clear_mutex_counters }, + }; + int i; + for(i=0; i +#include + +/* +** Maximum pathname length supported by the fs backend. +*/ +#define BLOCKSIZE 512 +#define BLOBSIZE 10485760 + +/* +** Name used to identify this VFS. +*/ +#define FS_VFS_NAME "fs" + +typedef struct fs_real_file fs_real_file; +struct fs_real_file { + sqlite3_file *pFile; + const char *zName; + int nDatabase; /* Current size of database region */ + int nJournal; /* Current size of journal region */ + int nBlob; /* Total size of allocated blob */ + int nRef; /* Number of pointers to this structure */ + fs_real_file *pNext; + fs_real_file **ppThis; +}; + +typedef struct fs_file fs_file; +struct fs_file { + sqlite3_file base; + int eType; + fs_real_file *pReal; +}; + +typedef struct tmp_file tmp_file; +struct tmp_file { + sqlite3_file base; + int nSize; + int nAlloc; + char *zAlloc; +}; + +/* Values for fs_file.eType. */ +#define DATABASE_FILE 1 +#define JOURNAL_FILE 2 + +/* +** Method declarations for fs_file. +*/ +static int fsClose(sqlite3_file*); +static int fsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int fsWrite(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); +static int fsTruncate(sqlite3_file*, sqlite3_int64 size); +static int fsSync(sqlite3_file*, int flags); +static int fsFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int fsLock(sqlite3_file*, int); +static int fsUnlock(sqlite3_file*, int); +static int fsCheckReservedLock(sqlite3_file*, int *pResOut); +static int fsFileControl(sqlite3_file*, int op, void *pArg); +static int fsSectorSize(sqlite3_file*); +static int fsDeviceCharacteristics(sqlite3_file*); + +/* +** Method declarations for tmp_file. +*/ +static int tmpClose(sqlite3_file*); +static int tmpRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int tmpWrite(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); +static int tmpTruncate(sqlite3_file*, sqlite3_int64 size); +static int tmpSync(sqlite3_file*, int flags); +static int tmpFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int tmpLock(sqlite3_file*, int); +static int tmpUnlock(sqlite3_file*, int); +static int tmpCheckReservedLock(sqlite3_file*, int *pResOut); +static int tmpFileControl(sqlite3_file*, int op, void *pArg); +static int tmpSectorSize(sqlite3_file*); +static int tmpDeviceCharacteristics(sqlite3_file*); + +/* +** Method declarations for fs_vfs. +*/ +static int fsOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int fsDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int fsAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int fsFullPathname(sqlite3_vfs*, const char *zName, int nOut,char *zOut); +static void *fsDlOpen(sqlite3_vfs*, const char *zFilename); +static void fsDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*fsDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void); +static void fsDlClose(sqlite3_vfs*, void*); +static int fsRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int fsSleep(sqlite3_vfs*, int microseconds); +static int fsCurrentTime(sqlite3_vfs*, double*); + + +typedef struct fs_vfs_t fs_vfs_t; +struct fs_vfs_t { + sqlite3_vfs base; + fs_real_file *pFileList; + sqlite3_vfs *pParent; +}; + +static fs_vfs_t fs_vfs = { + { + 1, /* iVersion */ + 0, /* szOsFile */ + 0, /* mxPathname */ + 0, /* pNext */ + FS_VFS_NAME, /* zName */ + 0, /* pAppData */ + fsOpen, /* xOpen */ + fsDelete, /* xDelete */ + fsAccess, /* xAccess */ + fsFullPathname, /* xFullPathname */ + fsDlOpen, /* xDlOpen */ + fsDlError, /* xDlError */ + fsDlSym, /* xDlSym */ + fsDlClose, /* xDlClose */ + fsRandomness, /* xRandomness */ + fsSleep, /* xSleep */ + fsCurrentTime, /* xCurrentTime */ + 0 /* xCurrentTimeInt64 */ + }, + 0, /* pFileList */ + 0 /* pParent */ +}; + +static sqlite3_io_methods fs_io_methods = { + 1, /* iVersion */ + fsClose, /* xClose */ + fsRead, /* xRead */ + fsWrite, /* xWrite */ + fsTruncate, /* xTruncate */ + fsSync, /* xSync */ + fsFileSize, /* xFileSize */ + fsLock, /* xLock */ + fsUnlock, /* xUnlock */ + fsCheckReservedLock, /* xCheckReservedLock */ + fsFileControl, /* xFileControl */ + fsSectorSize, /* xSectorSize */ + fsDeviceCharacteristics, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0 /* xShmUnmap */ +}; + + +static sqlite3_io_methods tmp_io_methods = { + 1, /* iVersion */ + tmpClose, /* xClose */ + tmpRead, /* xRead */ + tmpWrite, /* xWrite */ + tmpTruncate, /* xTruncate */ + tmpSync, /* xSync */ + tmpFileSize, /* xFileSize */ + tmpLock, /* xLock */ + tmpUnlock, /* xUnlock */ + tmpCheckReservedLock, /* xCheckReservedLock */ + tmpFileControl, /* xFileControl */ + tmpSectorSize, /* xSectorSize */ + tmpDeviceCharacteristics, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0 /* xShmUnmap */ +}; + +/* Useful macros used in several places */ +#define MIN(x,y) ((x)<(y)?(x):(y)) +#define MAX(x,y) ((x)>(y)?(x):(y)) + + +/* +** Close a tmp-file. +*/ +static int tmpClose(sqlite3_file *pFile){ + tmp_file *pTmp = (tmp_file *)pFile; + sqlite3_free(pTmp->zAlloc); + return SQLITE_OK; +} + +/* +** Read data from a tmp-file. +*/ +static int tmpRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + tmp_file *pTmp = (tmp_file *)pFile; + if( (iAmt+iOfst)>pTmp->nSize ){ + return SQLITE_IOERR_SHORT_READ; + } + memcpy(zBuf, &pTmp->zAlloc[iOfst], iAmt); + return SQLITE_OK; +} + +/* +** Write data to a tmp-file. +*/ +static int tmpWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + tmp_file *pTmp = (tmp_file *)pFile; + if( (iAmt+iOfst)>pTmp->nAlloc ){ + int nNew = (int)(2*(iAmt+iOfst+pTmp->nAlloc)); + char *zNew = sqlite3_realloc(pTmp->zAlloc, nNew); + if( !zNew ){ + return SQLITE_NOMEM; + } + pTmp->zAlloc = zNew; + pTmp->nAlloc = nNew; + } + memcpy(&pTmp->zAlloc[iOfst], zBuf, iAmt); + pTmp->nSize = (int)MAX(pTmp->nSize, iOfst+iAmt); + return SQLITE_OK; +} + +/* +** Truncate a tmp-file. +*/ +static int tmpTruncate(sqlite3_file *pFile, sqlite_int64 size){ + tmp_file *pTmp = (tmp_file *)pFile; + pTmp->nSize = (int)MIN(pTmp->nSize, size); + return SQLITE_OK; +} + +/* +** Sync a tmp-file. +*/ +static int tmpSync(sqlite3_file *pFile, int flags){ + return SQLITE_OK; +} + +/* +** Return the current file-size of a tmp-file. +*/ +static int tmpFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + tmp_file *pTmp = (tmp_file *)pFile; + *pSize = pTmp->nSize; + return SQLITE_OK; +} + +/* +** Lock a tmp-file. +*/ +static int tmpLock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} + +/* +** Unlock a tmp-file. +*/ +static int tmpUnlock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} + +/* +** Check if another file-handle holds a RESERVED lock on a tmp-file. +*/ +static int tmpCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + *pResOut = 0; + return SQLITE_OK; +} + +/* +** File control method. For custom operations on a tmp-file. +*/ +static int tmpFileControl(sqlite3_file *pFile, int op, void *pArg){ + return SQLITE_OK; +} + +/* +** Return the sector-size in bytes for a tmp-file. +*/ +static int tmpSectorSize(sqlite3_file *pFile){ + return 0; +} + +/* +** Return the device characteristic flags supported by a tmp-file. +*/ +static int tmpDeviceCharacteristics(sqlite3_file *pFile){ + return 0; +} + +/* +** Close an fs-file. +*/ +static int fsClose(sqlite3_file *pFile){ + int rc = SQLITE_OK; + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + + /* Decrement the real_file ref-count. */ + pReal->nRef--; + assert(pReal->nRef>=0); + + /* When the ref-count reaches 0, destroy the structure */ + if( pReal->nRef==0 ){ + *pReal->ppThis = pReal->pNext; + if( pReal->pNext ){ + pReal->pNext->ppThis = pReal->ppThis; + } + rc = pReal->pFile->pMethods->xClose(pReal->pFile); + sqlite3_free(pReal); + } + + return rc; +} + +/* +** Read data from an fs-file. +*/ +static int fsRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc = SQLITE_OK; + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + sqlite3_file *pF = pReal->pFile; + + if( (p->eType==DATABASE_FILE && (iAmt+iOfst)>pReal->nDatabase) + || (p->eType==JOURNAL_FILE && (iAmt+iOfst)>pReal->nJournal) + ){ + rc = SQLITE_IOERR_SHORT_READ; + }else if( p->eType==DATABASE_FILE ){ + rc = pF->pMethods->xRead(pF, zBuf, iAmt, iOfst+BLOCKSIZE); + }else{ + /* Journal file. */ + int iRem = iAmt; + int iBuf = 0; + int ii = (int)iOfst; + while( iRem>0 && rc==SQLITE_OK ){ + int iRealOff = pReal->nBlob - BLOCKSIZE*((ii/BLOCKSIZE)+1) + ii%BLOCKSIZE; + int iRealAmt = MIN(iRem, BLOCKSIZE - (iRealOff%BLOCKSIZE)); + + rc = pF->pMethods->xRead(pF, &((char *)zBuf)[iBuf], iRealAmt, iRealOff); + ii += iRealAmt; + iBuf += iRealAmt; + iRem -= iRealAmt; + } + } + + return rc; +} + +/* +** Write data to an fs-file. +*/ +static int fsWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc = SQLITE_OK; + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + sqlite3_file *pF = pReal->pFile; + + if( p->eType==DATABASE_FILE ){ + if( (iAmt+iOfst+BLOCKSIZE)>(pReal->nBlob-pReal->nJournal) ){ + rc = SQLITE_FULL; + }else{ + rc = pF->pMethods->xWrite(pF, zBuf, iAmt, iOfst+BLOCKSIZE); + if( rc==SQLITE_OK ){ + pReal->nDatabase = (int)MAX(pReal->nDatabase, iAmt+iOfst); + } + } + }else{ + /* Journal file. */ + int iRem = iAmt; + int iBuf = 0; + int ii = (int)iOfst; + while( iRem>0 && rc==SQLITE_OK ){ + int iRealOff = pReal->nBlob - BLOCKSIZE*((ii/BLOCKSIZE)+1) + ii%BLOCKSIZE; + int iRealAmt = MIN(iRem, BLOCKSIZE - (iRealOff%BLOCKSIZE)); + + if( iRealOff<(pReal->nDatabase+BLOCKSIZE) ){ + rc = SQLITE_FULL; + }else{ + rc = pF->pMethods->xWrite(pF, &((char *)zBuf)[iBuf], iRealAmt,iRealOff); + ii += iRealAmt; + iBuf += iRealAmt; + iRem -= iRealAmt; + } + } + if( rc==SQLITE_OK ){ + pReal->nJournal = (int)MAX(pReal->nJournal, iAmt+iOfst); + } + } + + return rc; +} + +/* +** Truncate an fs-file. +*/ +static int fsTruncate(sqlite3_file *pFile, sqlite_int64 size){ + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + if( p->eType==DATABASE_FILE ){ + pReal->nDatabase = (int)MIN(pReal->nDatabase, size); + }else{ + pReal->nJournal = (int)MIN(pReal->nJournal, size); + } + return SQLITE_OK; +} + +/* +** Sync an fs-file. +*/ +static int fsSync(sqlite3_file *pFile, int flags){ + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + sqlite3_file *pRealFile = pReal->pFile; + int rc = SQLITE_OK; + + if( p->eType==DATABASE_FILE ){ + unsigned char zSize[4]; + zSize[0] = (pReal->nDatabase&0xFF000000)>>24; + zSize[1] = (pReal->nDatabase&0x00FF0000)>>16; + zSize[2] = (pReal->nDatabase&0x0000FF00)>>8; + zSize[3] = (pReal->nDatabase&0x000000FF); + rc = pRealFile->pMethods->xWrite(pRealFile, zSize, 4, 0); + } + if( rc==SQLITE_OK ){ + rc = pRealFile->pMethods->xSync(pRealFile, flags&(~SQLITE_SYNC_DATAONLY)); + } + + return rc; +} + +/* +** Return the current file-size of an fs-file. +*/ +static int fsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = p->pReal; + if( p->eType==DATABASE_FILE ){ + *pSize = pReal->nDatabase; + }else{ + *pSize = pReal->nJournal; + } + return SQLITE_OK; +} + +/* +** Lock an fs-file. +*/ +static int fsLock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} + +/* +** Unlock an fs-file. +*/ +static int fsUnlock(sqlite3_file *pFile, int eLock){ + return SQLITE_OK; +} + +/* +** Check if another file-handle holds a RESERVED lock on an fs-file. +*/ +static int fsCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + *pResOut = 0; + return SQLITE_OK; +} + +/* +** File control method. For custom operations on an fs-file. +*/ +static int fsFileControl(sqlite3_file *pFile, int op, void *pArg){ + return SQLITE_OK; +} + +/* +** Return the sector-size in bytes for an fs-file. +*/ +static int fsSectorSize(sqlite3_file *pFile){ + return BLOCKSIZE; +} + +/* +** Return the device characteristic flags supported by an fs-file. +*/ +static int fsDeviceCharacteristics(sqlite3_file *pFile){ + return 0; +} + +/* +** Open an fs file handle. +*/ +static int fsOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + fs_vfs_t *pFsVfs = (fs_vfs_t *)pVfs; + fs_file *p = (fs_file *)pFile; + fs_real_file *pReal = 0; + int eType; + int nName; + int rc = SQLITE_OK; + + if( 0==(flags&(SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_MAIN_JOURNAL)) ){ + tmp_file *p = (tmp_file *)pFile; + memset(p, 0, sizeof(*p)); + p->base.pMethods = &tmp_io_methods; + return SQLITE_OK; + } + + eType = ((flags&(SQLITE_OPEN_MAIN_DB))?DATABASE_FILE:JOURNAL_FILE); + p->base.pMethods = &fs_io_methods; + p->eType = eType; + + assert(strlen("-journal")==8); + nName = (int)strlen(zName)-((eType==JOURNAL_FILE)?8:0); + pReal=pFsVfs->pFileList; + for(; pReal && strncmp(pReal->zName, zName, nName); pReal=pReal->pNext); + + if( !pReal ){ + int real_flags = (flags&~(SQLITE_OPEN_MAIN_DB))|SQLITE_OPEN_TEMP_DB; + sqlite3_int64 size; + sqlite3_file *pRealFile; + sqlite3_vfs *pParent = pFsVfs->pParent; + assert(eType==DATABASE_FILE); + + pReal = (fs_real_file *)sqlite3_malloc(sizeof(*pReal)+pParent->szOsFile); + if( !pReal ){ + rc = SQLITE_NOMEM; + goto open_out; + } + memset(pReal, 0, sizeof(*pReal)+pParent->szOsFile); + pReal->zName = zName; + pReal->pFile = (sqlite3_file *)(&pReal[1]); + + rc = pParent->xOpen(pParent, zName, pReal->pFile, real_flags, pOutFlags); + if( rc!=SQLITE_OK ){ + goto open_out; + } + pRealFile = pReal->pFile; + + rc = pRealFile->pMethods->xFileSize(pRealFile, &size); + if( rc!=SQLITE_OK ){ + goto open_out; + } + if( size==0 ){ + rc = pRealFile->pMethods->xWrite(pRealFile, "\0", 1, BLOBSIZE-1); + pReal->nBlob = BLOBSIZE; + }else{ + unsigned char zS[4]; + pReal->nBlob = (int)size; + rc = pRealFile->pMethods->xRead(pRealFile, zS, 4, 0); + pReal->nDatabase = (zS[0]<<24)+(zS[1]<<16)+(zS[2]<<8)+zS[3]; + if( rc==SQLITE_OK ){ + rc = pRealFile->pMethods->xRead(pRealFile, zS, 4, pReal->nBlob-4); + if( zS[0] || zS[1] || zS[2] || zS[3] ){ + pReal->nJournal = pReal->nBlob; + } + } + } + + if( rc==SQLITE_OK ){ + pReal->pNext = pFsVfs->pFileList; + if( pReal->pNext ){ + pReal->pNext->ppThis = &pReal->pNext; + } + pReal->ppThis = &pFsVfs->pFileList; + pFsVfs->pFileList = pReal; + } + } + +open_out: + if( pReal ){ + if( rc==SQLITE_OK ){ + p->pReal = pReal; + pReal->nRef++; + }else{ + if( pReal->pFile->pMethods ){ + pReal->pFile->pMethods->xClose(pReal->pFile); + } + sqlite3_free(pReal); + } + } + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int fsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc = SQLITE_OK; + fs_vfs_t *pFsVfs = (fs_vfs_t *)pVfs; + fs_real_file *pReal; + sqlite3_file *pF; + int nName = (int)strlen(zPath) - 8; + + assert(strlen("-journal")==8); + assert(strcmp("-journal", &zPath[nName])==0); + + pReal = pFsVfs->pFileList; + for(; pReal && strncmp(pReal->zName, zPath, nName); pReal=pReal->pNext); + if( pReal ){ + pF = pReal->pFile; + rc = pF->pMethods->xWrite(pF, "\0\0\0\0", 4, pReal->nBlob-BLOCKSIZE); + if( rc==SQLITE_OK ){ + pReal->nJournal = 0; + } + } + return rc; +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int fsAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + fs_vfs_t *pFsVfs = (fs_vfs_t *)pVfs; + fs_real_file *pReal; + int isJournal = 0; + int nName = (int)strlen(zPath); + + if( flags!=SQLITE_ACCESS_EXISTS ){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xAccess(pParent, zPath, flags, pResOut); + } + + assert(strlen("-journal")==8); + if( nName>8 && strcmp("-journal", &zPath[nName-8])==0 ){ + nName -= 8; + isJournal = 1; + } + + pReal = pFsVfs->pFileList; + for(; pReal && strncmp(pReal->zName, zPath, nName); pReal=pReal->pNext); + + *pResOut = (pReal && (!isJournal || pReal->nJournal>0)); + return SQLITE_OK; +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (FS_MAX_PATHNAME+1) bytes. +*/ +static int fsFullPathname( + sqlite3_vfs *pVfs, /* Pointer to vfs object */ + const char *zPath, /* Possibly relative input path */ + int nOut, /* Size of output buffer in bytes */ + char *zOut /* Output buffer */ +){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xFullPathname(pParent, zPath, nOut, zOut); +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *fsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xDlOpen(pParent, zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void fsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + pParent->xDlError(pParent, nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*fsDlSym(sqlite3_vfs *pVfs, void *pH, const char *zSym))(void){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xDlSym(pParent, pH, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void fsDlClose(sqlite3_vfs *pVfs, void *pHandle){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + pParent->xDlClose(pParent, pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int fsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xRandomness(pParent, nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int fsSleep(sqlite3_vfs *pVfs, int nMicro){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xSleep(pParent, nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int fsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + sqlite3_vfs *pParent = ((fs_vfs_t *)pVfs)->pParent; + return pParent->xCurrentTime(pParent, pTimeOut); +} + +/* +** This procedure registers the fs vfs with SQLite. If the argument is +** true, the fs vfs becomes the new default vfs. It is the only publicly +** available function in this file. +*/ +int fs_register(void){ + if( fs_vfs.pParent ) return SQLITE_OK; + fs_vfs.pParent = sqlite3_vfs_find(0); + fs_vfs.base.mxPathname = fs_vfs.pParent->mxPathname; + fs_vfs.base.szOsFile = MAX(sizeof(tmp_file), sizeof(fs_file)); + return sqlite3_vfs_register(&fs_vfs.base, 0); +} + +#ifdef SQLITE_TEST + int SqlitetestOnefile_Init() {return fs_register();} +#endif diff --git a/components/external/SQLite-3.8.1/src/test_osinst.c b/components/external/SQLite-3.8.1/src/test_osinst.c new file mode 100644 index 0000000000000000000000000000000000000000..531433313ee36c07eb21c02f3115cb7a37486c79 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_osinst.c @@ -0,0 +1,1215 @@ +/* +** 2008 April 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains the implementation of an SQLite vfs wrapper that +** adds instrumentation to all vfs and file methods. C and Tcl interfaces +** are provided to control the instrumentation. +*/ + +/* +** This module contains code for a wrapper VFS that causes a log of +** most VFS calls to be written into a nominated file on disk. The log +** is stored in a compressed binary format to reduce the amount of IO +** overhead introduced into the application by logging. +** +** All calls on sqlite3_file objects except xFileControl() are logged. +** Additionally, calls to the xAccess(), xOpen(), and xDelete() +** methods are logged. The other sqlite3_vfs object methods (xDlXXX, +** xRandomness, xSleep, xCurrentTime, xGetLastError and xCurrentTimeInt64) +** are not logged. +** +** The binary log files are read using a virtual table implementation +** also contained in this file. +** +** CREATING LOG FILES: +** +** int sqlite3_vfslog_new( +** const char *zVfs, // Name of new VFS +** const char *zParentVfs, // Name of parent VFS (or NULL) +** const char *zLog // Name of log file to write to +** ); +** +** int sqlite3_vfslog_finalize(const char *zVfs); +** +** ANNOTATING LOG FILES: +** +** To write an arbitrary message into a log file: +** +** int sqlite3_vfslog_annotate(const char *zVfs, const char *zMsg); +** +** READING LOG FILES: +** +** Log files are read using the "vfslog" virtual table implementation +** in this file. To register the virtual table with SQLite, use: +** +** int sqlite3_vfslog_register(sqlite3 *db); +** +** Then, if the log file is named "vfs.log", the following SQL command: +** +** CREATE VIRTUAL TABLE v USING vfslog('vfs.log'); +** +** creates a virtual table with 6 columns, as follows: +** +** CREATE TABLE v( +** event TEXT, // "xOpen", "xRead" etc. +** file TEXT, // Name of file this call applies to +** clicks INTEGER, // Time spent in call +** rc INTEGER, // Return value +** size INTEGER, // Bytes read or written +** offset INTEGER // File offset read or written +** ); +*/ + +#include "sqlite3.h" +#include +#include + + +/* +** Maximum pathname length supported by the vfslog backend. +*/ +#define INST_MAX_PATHNAME 512 + +#define OS_ACCESS 1 +#define OS_CHECKRESERVEDLOCK 2 +#define OS_CLOSE 3 +#define OS_CURRENTTIME 4 +#define OS_DELETE 5 +#define OS_DEVCHAR 6 +#define OS_FILECONTROL 7 +#define OS_FILESIZE 8 +#define OS_FULLPATHNAME 9 +#define OS_LOCK 11 +#define OS_OPEN 12 +#define OS_RANDOMNESS 13 +#define OS_READ 14 +#define OS_SECTORSIZE 15 +#define OS_SLEEP 16 +#define OS_SYNC 17 +#define OS_TRUNCATE 18 +#define OS_UNLOCK 19 +#define OS_WRITE 20 +#define OS_SHMUNMAP 22 +#define OS_SHMMAP 23 +#define OS_SHMLOCK 25 +#define OS_SHMBARRIER 26 +#define OS_ANNOTATE 28 + +#define OS_NUMEVENTS 29 + +#define VFSLOG_BUFFERSIZE 8192 + +typedef struct VfslogVfs VfslogVfs; +typedef struct VfslogFile VfslogFile; + +struct VfslogVfs { + sqlite3_vfs base; /* VFS methods */ + sqlite3_vfs *pVfs; /* Parent VFS */ + int iNextFileId; /* Next file id */ + sqlite3_file *pLog; /* Log file handle */ + sqlite3_int64 iOffset; /* Log file offset of start of write buffer */ + int nBuf; /* Number of valid bytes in aBuf[] */ + char aBuf[VFSLOG_BUFFERSIZE]; /* Write buffer */ +}; + +struct VfslogFile { + sqlite3_file base; /* IO methods */ + sqlite3_file *pReal; /* Underlying file handle */ + sqlite3_vfs *pVfslog; /* Associated VsflogVfs object */ + int iFileId; /* File id number */ +}; + +#define REALVFS(p) (((VfslogVfs *)(p))->pVfs) + + + +/* +** Method declarations for vfslog_file. +*/ +static int vfslogClose(sqlite3_file*); +static int vfslogRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int vfslogWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); +static int vfslogTruncate(sqlite3_file*, sqlite3_int64 size); +static int vfslogSync(sqlite3_file*, int flags); +static int vfslogFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int vfslogLock(sqlite3_file*, int); +static int vfslogUnlock(sqlite3_file*, int); +static int vfslogCheckReservedLock(sqlite3_file*, int *pResOut); +static int vfslogFileControl(sqlite3_file*, int op, void *pArg); +static int vfslogSectorSize(sqlite3_file*); +static int vfslogDeviceCharacteristics(sqlite3_file*); + +static int vfslogShmLock(sqlite3_file *pFile, int ofst, int n, int flags); +static int vfslogShmMap(sqlite3_file *pFile,int,int,int,volatile void **); +static void vfslogShmBarrier(sqlite3_file*); +static int vfslogShmUnmap(sqlite3_file *pFile, int deleteFlag); + +/* +** Method declarations for vfslog_vfs. +*/ +static int vfslogOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int vfslogDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int vfslogAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int vfslogFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); +static void *vfslogDlOpen(sqlite3_vfs*, const char *zFilename); +static void vfslogDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*vfslogDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void); +static void vfslogDlClose(sqlite3_vfs*, void*); +static int vfslogRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int vfslogSleep(sqlite3_vfs*, int microseconds); +static int vfslogCurrentTime(sqlite3_vfs*, double*); + +static int vfslogGetLastError(sqlite3_vfs*, int, char *); +static int vfslogCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); + +static sqlite3_vfs vfslog_vfs = { + 1, /* iVersion */ + sizeof(VfslogFile), /* szOsFile */ + INST_MAX_PATHNAME, /* mxPathname */ + 0, /* pNext */ + 0, /* zName */ + 0, /* pAppData */ + vfslogOpen, /* xOpen */ + vfslogDelete, /* xDelete */ + vfslogAccess, /* xAccess */ + vfslogFullPathname, /* xFullPathname */ + vfslogDlOpen, /* xDlOpen */ + vfslogDlError, /* xDlError */ + vfslogDlSym, /* xDlSym */ + vfslogDlClose, /* xDlClose */ + vfslogRandomness, /* xRandomness */ + vfslogSleep, /* xSleep */ + vfslogCurrentTime, /* xCurrentTime */ + vfslogGetLastError, /* xGetLastError */ + vfslogCurrentTimeInt64 /* xCurrentTime */ +}; + +static sqlite3_io_methods vfslog_io_methods = { + 2, /* iVersion */ + vfslogClose, /* xClose */ + vfslogRead, /* xRead */ + vfslogWrite, /* xWrite */ + vfslogTruncate, /* xTruncate */ + vfslogSync, /* xSync */ + vfslogFileSize, /* xFileSize */ + vfslogLock, /* xLock */ + vfslogUnlock, /* xUnlock */ + vfslogCheckReservedLock, /* xCheckReservedLock */ + vfslogFileControl, /* xFileControl */ + vfslogSectorSize, /* xSectorSize */ + vfslogDeviceCharacteristics, /* xDeviceCharacteristics */ + vfslogShmMap, /* xShmMap */ + vfslogShmLock, /* xShmLock */ + vfslogShmBarrier, /* xShmBarrier */ + vfslogShmUnmap /* xShmUnmap */ +}; + +#if SQLITE_OS_UNIX && !defined(NO_GETTOD) +#include +static sqlite3_uint64 vfslog_time(){ + struct timeval sTime; + gettimeofday(&sTime, 0); + return sTime.tv_usec + (sqlite3_uint64)sTime.tv_sec * 1000000; +} +#elif SQLITE_OS_WIN +#include +#include +static sqlite3_uint64 vfslog_time(){ + FILETIME ft; + sqlite3_uint64 u64time = 0; + + GetSystemTimeAsFileTime(&ft); + + u64time |= ft.dwHighDateTime; + u64time <<= 32; + u64time |= ft.dwLowDateTime; + + /* ft is 100-nanosecond intervals, we want microseconds */ + return u64time /(sqlite3_uint64)10; +} +#else +static sqlite3_uint64 vfslog_time(){ + return 0; +} +#endif + +static void vfslog_call(sqlite3_vfs *, int, int, sqlite3_int64, int, int, int); +static void vfslog_string(sqlite3_vfs *, const char *); + +/* +** Close an vfslog-file. +*/ +static int vfslogClose(sqlite3_file *pFile){ + sqlite3_uint64 t; + int rc = SQLITE_OK; + VfslogFile *p = (VfslogFile *)pFile; + + t = vfslog_time(); + if( p->pReal->pMethods ){ + rc = p->pReal->pMethods->xClose(p->pReal); + } + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_CLOSE, p->iFileId, t, rc, 0, 0); + return rc; +} + +/* +** Read data from an vfslog-file. +*/ +static int vfslogRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_READ, p->iFileId, t, rc, iAmt, (int)iOfst); + return rc; +} + +/* +** Write data to an vfslog-file. +*/ +static int vfslogWrite( + sqlite3_file *pFile, + const void *z, + int iAmt, + sqlite_int64 iOfst +){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xWrite(p->pReal, z, iAmt, iOfst); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_WRITE, p->iFileId, t, rc, iAmt, (int)iOfst); + return rc; +} + +/* +** Truncate an vfslog-file. +*/ +static int vfslogTruncate(sqlite3_file *pFile, sqlite_int64 size){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xTruncate(p->pReal, size); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_TRUNCATE, p->iFileId, t, rc, 0, (int)size); + return rc; +} + +/* +** Sync an vfslog-file. +*/ +static int vfslogSync(sqlite3_file *pFile, int flags){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xSync(p->pReal, flags); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SYNC, p->iFileId, t, rc, flags, 0); + return rc; +} + +/* +** Return the current file-size of an vfslog-file. +*/ +static int vfslogFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_FILESIZE, p->iFileId, t, rc, 0, (int)*pSize); + return rc; +} + +/* +** Lock an vfslog-file. +*/ +static int vfslogLock(sqlite3_file *pFile, int eLock){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xLock(p->pReal, eLock); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_LOCK, p->iFileId, t, rc, eLock, 0); + return rc; +} + +/* +** Unlock an vfslog-file. +*/ +static int vfslogUnlock(sqlite3_file *pFile, int eLock){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xUnlock(p->pReal, eLock); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_UNLOCK, p->iFileId, t, rc, eLock, 0); + return rc; +} + +/* +** Check if another file-handle holds a RESERVED lock on an vfslog-file. +*/ +static int vfslogCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_CHECKRESERVEDLOCK, p->iFileId, t, rc, *pResOut, 0); + return rc; +} + +/* +** File control method. For custom operations on an vfslog-file. +*/ +static int vfslogFileControl(sqlite3_file *pFile, int op, void *pArg){ + VfslogFile *p = (VfslogFile *)pFile; + int rc = p->pReal->pMethods->xFileControl(p->pReal, op, pArg); + if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){ + *(char**)pArg = sqlite3_mprintf("vfslog/%z", *(char**)pArg); + } + return rc; +} + +/* +** Return the sector-size in bytes for an vfslog-file. +*/ +static int vfslogSectorSize(sqlite3_file *pFile){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xSectorSize(p->pReal); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SECTORSIZE, p->iFileId, t, rc, 0, 0); + return rc; +} + +/* +** Return the device characteristic flags supported by an vfslog-file. +*/ +static int vfslogDeviceCharacteristics(sqlite3_file *pFile){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xDeviceCharacteristics(p->pReal); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_DEVCHAR, p->iFileId, t, rc, 0, 0); + return rc; +} + +static int vfslogShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SHMLOCK, p->iFileId, t, rc, 0, 0); + return rc; +} +static int vfslogShmMap( + sqlite3_file *pFile, + int iRegion, + int szRegion, + int isWrite, + volatile void **pp +){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SHMMAP, p->iFileId, t, rc, 0, 0); + return rc; +} +static void vfslogShmBarrier(sqlite3_file *pFile){ + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + p->pReal->pMethods->xShmBarrier(p->pReal); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SHMBARRIER, p->iFileId, t, SQLITE_OK, 0, 0); +} +static int vfslogShmUnmap(sqlite3_file *pFile, int deleteFlag){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + t = vfslog_time(); + rc = p->pReal->pMethods->xShmUnmap(p->pReal, deleteFlag); + t = vfslog_time() - t; + vfslog_call(p->pVfslog, OS_SHMUNMAP, p->iFileId, t, rc, 0, 0); + return rc; +} + + +/* +** Open an vfslog file handle. +*/ +static int vfslogOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + sqlite3_uint64 t; + VfslogFile *p = (VfslogFile *)pFile; + VfslogVfs *pLog = (VfslogVfs *)pVfs; + + pFile->pMethods = &vfslog_io_methods; + p->pReal = (sqlite3_file *)&p[1]; + p->pVfslog = pVfs; + p->iFileId = ++pLog->iNextFileId; + + t = vfslog_time(); + rc = REALVFS(pVfs)->xOpen(REALVFS(pVfs), zName, p->pReal, flags, pOutFlags); + t = vfslog_time() - t; + + vfslog_call(pVfs, OS_OPEN, p->iFileId, t, rc, 0, 0); + vfslog_string(pVfs, zName); + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int vfslogDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc; + sqlite3_uint64 t; + t = vfslog_time(); + rc = REALVFS(pVfs)->xDelete(REALVFS(pVfs), zPath, dirSync); + t = vfslog_time() - t; + vfslog_call(pVfs, OS_DELETE, 0, t, rc, dirSync, 0); + vfslog_string(pVfs, zPath); + return rc; +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int vfslogAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + int rc; + sqlite3_uint64 t; + t = vfslog_time(); + rc = REALVFS(pVfs)->xAccess(REALVFS(pVfs), zPath, flags, pResOut); + t = vfslog_time() - t; + vfslog_call(pVfs, OS_ACCESS, 0, t, rc, flags, *pResOut); + vfslog_string(pVfs, zPath); + return rc; +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (INST_MAX_PATHNAME+1) bytes. +*/ +static int vfslogFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + return REALVFS(pVfs)->xFullPathname(REALVFS(pVfs), zPath, nOut, zOut); +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *vfslogDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return REALVFS(pVfs)->xDlOpen(REALVFS(pVfs), zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void vfslogDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + REALVFS(pVfs)->xDlError(REALVFS(pVfs), nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*vfslogDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return REALVFS(pVfs)->xDlSym(REALVFS(pVfs), p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void vfslogDlClose(sqlite3_vfs *pVfs, void *pHandle){ + REALVFS(pVfs)->xDlClose(REALVFS(pVfs), pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int vfslogRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return REALVFS(pVfs)->xRandomness(REALVFS(pVfs), nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int vfslogSleep(sqlite3_vfs *pVfs, int nMicro){ + return REALVFS(pVfs)->xSleep(REALVFS(pVfs), nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int vfslogCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + return REALVFS(pVfs)->xCurrentTime(REALVFS(pVfs), pTimeOut); +} + +static int vfslogGetLastError(sqlite3_vfs *pVfs, int a, char *b){ + return REALVFS(pVfs)->xGetLastError(REALVFS(pVfs), a, b); +} +static int vfslogCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){ + return REALVFS(pVfs)->xCurrentTimeInt64(REALVFS(pVfs), p); +} + +static void vfslog_flush(VfslogVfs *p){ +#ifdef SQLITE_TEST + extern int sqlite3_io_error_pending; + extern int sqlite3_io_error_persist; + extern int sqlite3_diskfull_pending; + + int pending = sqlite3_io_error_pending; + int persist = sqlite3_io_error_persist; + int diskfull = sqlite3_diskfull_pending; + + sqlite3_io_error_pending = 0; + sqlite3_io_error_persist = 0; + sqlite3_diskfull_pending = 0; +#endif + + if( p->nBuf ){ + p->pLog->pMethods->xWrite(p->pLog, p->aBuf, p->nBuf, p->iOffset); + p->iOffset += p->nBuf; + p->nBuf = 0; + } + +#ifdef SQLITE_TEST + sqlite3_io_error_pending = pending; + sqlite3_io_error_persist = persist; + sqlite3_diskfull_pending = diskfull; +#endif +} + +static void put32bits(unsigned char *p, unsigned int v){ + p[0] = v>>24; + p[1] = v>>16; + p[2] = v>>8; + p[3] = v; +} + +static void vfslog_call( + sqlite3_vfs *pVfs, + int eEvent, + int iFileid, + sqlite3_int64 nClick, + int return_code, + int size, + int offset +){ + VfslogVfs *p = (VfslogVfs *)pVfs; + unsigned char *zRec; + if( (24+p->nBuf)>sizeof(p->aBuf) ){ + vfslog_flush(p); + } + zRec = (unsigned char *)&p->aBuf[p->nBuf]; + put32bits(&zRec[0], eEvent); + put32bits(&zRec[4], iFileid); + put32bits(&zRec[8], (unsigned int)(nClick&0xffff)); + put32bits(&zRec[12], return_code); + put32bits(&zRec[16], size); + put32bits(&zRec[20], offset); + p->nBuf += 24; +} + +static void vfslog_string(sqlite3_vfs *pVfs, const char *zStr){ + VfslogVfs *p = (VfslogVfs *)pVfs; + unsigned char *zRec; + int nStr = zStr ? (int)strlen(zStr) : 0; + if( (4+nStr+p->nBuf)>sizeof(p->aBuf) ){ + vfslog_flush(p); + } + zRec = (unsigned char *)&p->aBuf[p->nBuf]; + put32bits(&zRec[0], nStr); + if( zStr ){ + memcpy(&zRec[4], zStr, nStr); + } + p->nBuf += (4 + nStr); +} + +static void vfslog_finalize(VfslogVfs *p){ + if( p->pLog->pMethods ){ + vfslog_flush(p); + p->pLog->pMethods->xClose(p->pLog); + } + sqlite3_free(p); +} + +int sqlite3_vfslog_finalize(const char *zVfs){ + sqlite3_vfs *pVfs; + pVfs = sqlite3_vfs_find(zVfs); + if( !pVfs || pVfs->xOpen!=vfslogOpen ){ + return SQLITE_ERROR; + } + sqlite3_vfs_unregister(pVfs); + vfslog_finalize((VfslogVfs *)pVfs); + return SQLITE_OK; +} + +int sqlite3_vfslog_new( + const char *zVfs, /* New VFS name */ + const char *zParentVfs, /* Parent VFS name (or NULL) */ + const char *zLog /* Log file name */ +){ + VfslogVfs *p; + sqlite3_vfs *pParent; + int nByte; + int flags; + int rc; + char *zFile; + int nVfs; + + pParent = sqlite3_vfs_find(zParentVfs); + if( !pParent ){ + return SQLITE_ERROR; + } + + nVfs = (int)strlen(zVfs); + nByte = sizeof(VfslogVfs) + pParent->szOsFile + nVfs+1+pParent->mxPathname+1; + p = (VfslogVfs *)sqlite3_malloc(nByte); + memset(p, 0, nByte); + + p->pVfs = pParent; + p->pLog = (sqlite3_file *)&p[1]; + memcpy(&p->base, &vfslog_vfs, sizeof(sqlite3_vfs)); + p->base.zName = &((char *)p->pLog)[pParent->szOsFile]; + p->base.szOsFile += pParent->szOsFile; + memcpy((char *)p->base.zName, zVfs, nVfs); + + zFile = (char *)&p->base.zName[nVfs+1]; + pParent->xFullPathname(pParent, zLog, pParent->mxPathname, zFile); + + flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MASTER_JOURNAL; + pParent->xDelete(pParent, zFile, 0); + rc = pParent->xOpen(pParent, zFile, p->pLog, flags, &flags); + if( rc==SQLITE_OK ){ + memcpy(p->aBuf, "sqlite_ostrace1.....", 20); + p->iOffset = 0; + p->nBuf = 20; + rc = sqlite3_vfs_register((sqlite3_vfs *)p, 1); + } + if( rc ){ + vfslog_finalize(p); + } + return rc; +} + +int sqlite3_vfslog_annotate(const char *zVfs, const char *zMsg){ + sqlite3_vfs *pVfs; + pVfs = sqlite3_vfs_find(zVfs); + if( !pVfs || pVfs->xOpen!=vfslogOpen ){ + return SQLITE_ERROR; + } + vfslog_call(pVfs, OS_ANNOTATE, 0, 0, 0, 0, 0); + vfslog_string(pVfs, zMsg); + return SQLITE_OK; +} + +static const char *vfslog_eventname(int eEvent){ + const char *zEvent = 0; + + switch( eEvent ){ + case OS_CLOSE: zEvent = "xClose"; break; + case OS_READ: zEvent = "xRead"; break; + case OS_WRITE: zEvent = "xWrite"; break; + case OS_TRUNCATE: zEvent = "xTruncate"; break; + case OS_SYNC: zEvent = "xSync"; break; + case OS_FILESIZE: zEvent = "xFilesize"; break; + case OS_LOCK: zEvent = "xLock"; break; + case OS_UNLOCK: zEvent = "xUnlock"; break; + case OS_CHECKRESERVEDLOCK: zEvent = "xCheckResLock"; break; + case OS_FILECONTROL: zEvent = "xFileControl"; break; + case OS_SECTORSIZE: zEvent = "xSectorSize"; break; + case OS_DEVCHAR: zEvent = "xDeviceChar"; break; + case OS_OPEN: zEvent = "xOpen"; break; + case OS_DELETE: zEvent = "xDelete"; break; + case OS_ACCESS: zEvent = "xAccess"; break; + case OS_FULLPATHNAME: zEvent = "xFullPathname"; break; + case OS_RANDOMNESS: zEvent = "xRandomness"; break; + case OS_SLEEP: zEvent = "xSleep"; break; + case OS_CURRENTTIME: zEvent = "xCurrentTime"; break; + + case OS_SHMUNMAP: zEvent = "xShmUnmap"; break; + case OS_SHMLOCK: zEvent = "xShmLock"; break; + case OS_SHMBARRIER: zEvent = "xShmBarrier"; break; + case OS_SHMMAP: zEvent = "xShmMap"; break; + + case OS_ANNOTATE: zEvent = "annotation"; break; + } + + return zEvent; +} + +typedef struct VfslogVtab VfslogVtab; +typedef struct VfslogCsr VfslogCsr; + +/* +** Virtual table type for the vfslog reader module. +*/ +struct VfslogVtab { + sqlite3_vtab base; /* Base class */ + sqlite3_file *pFd; /* File descriptor open on vfslog file */ + sqlite3_int64 nByte; /* Size of file in bytes */ + char *zFile; /* File name for pFd */ +}; + +/* +** Virtual table cursor type for the vfslog reader module. +*/ +struct VfslogCsr { + sqlite3_vtab_cursor base; /* Base class */ + sqlite3_int64 iRowid; /* Current rowid. */ + sqlite3_int64 iOffset; /* Offset of next record in file */ + char *zTransient; /* Transient 'file' string */ + int nFile; /* Size of array azFile[] */ + char **azFile; /* File strings */ + unsigned char aBuf[1024]; /* Current vfs log entry (read from file) */ +}; + +static unsigned int get32bits(unsigned char *p){ + return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; +} + +/* +** The argument must point to a buffer containing a nul-terminated string. +** If the string begins with an SQL quote character it is overwritten by +** the dequoted version. Otherwise the buffer is left unmodified. +*/ +static void dequote(char *z){ + char quote; /* Quote character (if any ) */ + quote = z[0]; + if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ + int iIn = 1; /* Index of next byte to read from input */ + int iOut = 0; /* Index of next byte to write to output */ + if( quote=='[' ) quote = ']'; + while( z[iIn] ){ + if( z[iIn]==quote ){ + if( z[iIn+1]!=quote ) break; + z[iOut++] = quote; + iIn += 2; + }else{ + z[iOut++] = z[iIn++]; + } + } + z[iOut] = '\0'; + } +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Connect to or create a vfslog virtual table. +*/ +static int vlogConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + sqlite3_vfs *pVfs; /* VFS used to read log file */ + int flags; /* flags passed to pVfs->xOpen() */ + VfslogVtab *p; + int rc; + int nByte; + char *zFile; + + *ppVtab = 0; + pVfs = sqlite3_vfs_find(0); + nByte = sizeof(VfslogVtab) + pVfs->szOsFile + pVfs->mxPathname; + p = sqlite3_malloc(nByte); + if( p==0 ) return SQLITE_NOMEM; + memset(p, 0, nByte); + + p->pFd = (sqlite3_file *)&p[1]; + p->zFile = &((char *)p->pFd)[pVfs->szOsFile]; + + zFile = sqlite3_mprintf("%s", argv[3]); + if( !zFile ){ + sqlite3_free(p); + return SQLITE_NOMEM; + } + dequote(zFile); + pVfs->xFullPathname(pVfs, zFile, pVfs->mxPathname, p->zFile); + sqlite3_free(zFile); + + flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MASTER_JOURNAL; + rc = pVfs->xOpen(pVfs, p->zFile, p->pFd, flags, &flags); + + if( rc==SQLITE_OK ){ + p->pFd->pMethods->xFileSize(p->pFd, &p->nByte); + sqlite3_declare_vtab(db, + "CREATE TABLE xxx(event, file, click, rc, size, offset)" + ); + *ppVtab = &p->base; + }else{ + sqlite3_free(p); + } + + return rc; +} + +/* +** There is no "best-index". This virtual table always does a linear +** scan of the binary VFS log file. +*/ +static int vlogBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + pIdxInfo->estimatedCost = 10.0; + return SQLITE_OK; +} + +/* +** Disconnect from or destroy a vfslog virtual table. +*/ +static int vlogDisconnect(sqlite3_vtab *pVtab){ + VfslogVtab *p = (VfslogVtab *)pVtab; + if( p->pFd->pMethods ){ + p->pFd->pMethods->xClose(p->pFd); + p->pFd->pMethods = 0; + } + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Open a new vfslog cursor. +*/ +static int vlogOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + VfslogCsr *pCsr; /* Newly allocated cursor object */ + + pCsr = sqlite3_malloc(sizeof(VfslogCsr)); + if( !pCsr ) return SQLITE_NOMEM; + memset(pCsr, 0, sizeof(VfslogCsr)); + *ppCursor = &pCsr->base; + return SQLITE_OK; +} + +/* +** Close a vfslog cursor. +*/ +static int vlogClose(sqlite3_vtab_cursor *pCursor){ + VfslogCsr *p = (VfslogCsr *)pCursor; + int i; + for(i=0; inFile; i++){ + sqlite3_free(p->azFile[i]); + } + sqlite3_free(p->azFile); + sqlite3_free(p->zTransient); + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Move a vfslog cursor to the next entry in the file. +*/ +static int vlogNext(sqlite3_vtab_cursor *pCursor){ + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + VfslogVtab *p = (VfslogVtab *)pCursor->pVtab; + int rc = SQLITE_OK; + int nRead; + + sqlite3_free(pCsr->zTransient); + pCsr->zTransient = 0; + + nRead = 24; + if( pCsr->iOffset+nRead<=p->nByte ){ + int eEvent; + rc = p->pFd->pMethods->xRead(p->pFd, pCsr->aBuf, nRead, pCsr->iOffset); + + eEvent = get32bits(pCsr->aBuf); + if( (rc==SQLITE_OK) + && (eEvent==OS_OPEN || eEvent==OS_DELETE || eEvent==OS_ACCESS) + ){ + char buf[4]; + rc = p->pFd->pMethods->xRead(p->pFd, buf, 4, pCsr->iOffset+nRead); + nRead += 4; + if( rc==SQLITE_OK ){ + int nStr = get32bits((unsigned char *)buf); + char *zStr = sqlite3_malloc(nStr+1); + rc = p->pFd->pMethods->xRead(p->pFd, zStr, nStr, pCsr->iOffset+nRead); + zStr[nStr] = '\0'; + nRead += nStr; + + if( eEvent==OS_OPEN ){ + int iFileid = get32bits(&pCsr->aBuf[4]); + if( iFileid>=pCsr->nFile ){ + int nNew = sizeof(pCsr->azFile[0])*(iFileid+1); + pCsr->azFile = (char **)sqlite3_realloc(pCsr->azFile, nNew); + nNew -= sizeof(pCsr->azFile[0])*pCsr->nFile; + memset(&pCsr->azFile[pCsr->nFile], 0, nNew); + pCsr->nFile = iFileid+1; + } + sqlite3_free(pCsr->azFile[iFileid]); + pCsr->azFile[iFileid] = zStr; + }else{ + pCsr->zTransient = zStr; + } + } + } + } + + pCsr->iRowid += 1; + pCsr->iOffset += nRead; + return rc; +} + +static int vlogEof(sqlite3_vtab_cursor *pCursor){ + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + VfslogVtab *p = (VfslogVtab *)pCursor->pVtab; + return (pCsr->iOffset>=p->nByte); +} + +static int vlogFilter( + sqlite3_vtab_cursor *pCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + pCsr->iRowid = 0; + pCsr->iOffset = 20; + return vlogNext(pCursor); +} + +static int vlogColumn( + sqlite3_vtab_cursor *pCursor, + sqlite3_context *ctx, + int i +){ + unsigned int val; + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + + assert( i<7 ); + val = get32bits(&pCsr->aBuf[4*i]); + + switch( i ){ + case 0: { + sqlite3_result_text(ctx, vfslog_eventname(val), -1, SQLITE_STATIC); + break; + } + case 1: { + char *zStr = pCsr->zTransient; + if( val!=0 && val<(unsigned)pCsr->nFile ){ + zStr = pCsr->azFile[val]; + } + sqlite3_result_text(ctx, zStr, -1, SQLITE_TRANSIENT); + break; + } + default: + sqlite3_result_int(ctx, val); + break; + } + + return SQLITE_OK; +} + +static int vlogRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + VfslogCsr *pCsr = (VfslogCsr *)pCursor; + *pRowid = pCsr->iRowid; + return SQLITE_OK; +} + +int sqlite3_vfslog_register(sqlite3 *db){ + static sqlite3_module vfslog_module = { + 0, /* iVersion */ + vlogConnect, /* xCreate */ + vlogConnect, /* xConnect */ + vlogBestIndex, /* xBestIndex */ + vlogDisconnect, /* xDisconnect */ + vlogDisconnect, /* xDestroy */ + vlogOpen, /* xOpen - open a cursor */ + vlogClose, /* xClose - close a cursor */ + vlogFilter, /* xFilter - configure scan constraints */ + vlogNext, /* xNext - advance a cursor */ + vlogEof, /* xEof - check for end of scan */ + vlogColumn, /* xColumn - read data */ + vlogRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + }; + + sqlite3_create_module(db, "vfslog", &vfslog_module, 0); + return SQLITE_OK; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/************************************************************************** +*************************************************************************** +** Tcl interface starts here. +*/ + +#if defined(SQLITE_TEST) || defined(TCLSH) + +#include + +static int test_vfslog( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct SqliteDb { sqlite3 *db; }; + sqlite3 *db; + Tcl_CmdInfo cmdInfo; + int rc = SQLITE_ERROR; + + static const char *strs[] = { "annotate", "finalize", "new", "register", 0 }; + enum VL_enum { VL_ANNOTATE, VL_FINALIZE, VL_NEW, VL_REGISTER }; + int iSub; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND ..."); + return TCL_ERROR; + } + if( Tcl_GetIndexFromObj(interp, objv[1], strs, "sub-command", 0, &iSub) ){ + return TCL_ERROR; + } + + switch( (enum VL_enum)iSub ){ + case VL_ANNOTATE: { + int rc; + char *zVfs; + char *zMsg; + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 3, objv, "VFS"); + return TCL_ERROR; + } + zVfs = Tcl_GetString(objv[2]); + zMsg = Tcl_GetString(objv[3]); + rc = sqlite3_vfslog_annotate(zVfs, zMsg); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "failed", 0); + return TCL_ERROR; + } + break; + } + case VL_FINALIZE: { + int rc; + char *zVfs; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "VFS"); + return TCL_ERROR; + } + zVfs = Tcl_GetString(objv[2]); + rc = sqlite3_vfslog_finalize(zVfs); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "failed", 0); + return TCL_ERROR; + } + break; + }; + + case VL_NEW: { + int rc; + char *zVfs; + char *zParent; + char *zLog; + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 2, objv, "VFS PARENT LOGFILE"); + return TCL_ERROR; + } + zVfs = Tcl_GetString(objv[2]); + zParent = Tcl_GetString(objv[3]); + zLog = Tcl_GetString(objv[4]); + if( *zParent=='\0' ) zParent = 0; + rc = sqlite3_vfslog_new(zVfs, zParent, zLog); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "failed", 0); + return TCL_ERROR; + } + break; + }; + + case VL_REGISTER: { + char *zDb; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "DB"); + return TCL_ERROR; + } +#ifdef SQLITE_OMIT_VIRTUALTABLE + Tcl_AppendResult(interp, "vfslog not available because of " + "SQLITE_OMIT_VIRTUALTABLE", (void*)0); + return TCL_ERROR; +#else + zDb = Tcl_GetString(objv[2]); + if( Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){ + db = ((struct SqliteDb*)cmdInfo.objClientData)->db; + rc = sqlite3_vfslog_register(db); + } + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "bad sqlite3 handle: ", zDb, (void*)0); + return TCL_ERROR; + } + break; +#endif + } + } + + return TCL_OK; +} + +int SqlitetestOsinst_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "vfslog", test_vfslog, 0, 0); + return TCL_OK; +} + +#endif /* SQLITE_TEST */ diff --git a/components/external/SQLite-3.8.1/src/test_pcache.c b/components/external/SQLite-3.8.1/src/test_pcache.c new file mode 100644 index 0000000000000000000000000000000000000000..8fcfe7e26e3ff17496b840f5d63c75783aff8162 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_pcache.c @@ -0,0 +1,467 @@ +/* +** 2008 November 18 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used for testing the SQLite system. +** None of the code in this file goes into a deliverable build. +** +** This file contains an application-defined pager cache +** implementation that can be plugged in in place of the +** default pcache. This alternative pager cache will throw +** some errors that the default cache does not. +** +** This pagecache implementation is designed for simplicity +** not speed. +*/ +#include "sqlite3.h" +#include +#include + +/* +** Global data used by this test implementation. There is no +** mutexing, which means this page cache will not work in a +** multi-threaded test. +*/ +typedef struct testpcacheGlobalType testpcacheGlobalType; +struct testpcacheGlobalType { + void *pDummy; /* Dummy allocation to simulate failures */ + int nInstance; /* Number of current instances */ + unsigned discardChance; /* Chance of discarding on an unpin (0-100) */ + unsigned prngSeed; /* Seed for the PRNG */ + unsigned highStress; /* Call xStress agressively */ +}; +static testpcacheGlobalType testpcacheGlobal; + +/* +** Initializer. +** +** Verify that the initializer is only called when the system is +** uninitialized. Allocate some memory and report SQLITE_NOMEM if +** the allocation fails. This provides a means to test the recovery +** from a failed initialization attempt. It also verifies that the +** the destructor always gets call - otherwise there would be a +** memory leak. +*/ +static int testpcacheInit(void *pArg){ + assert( pArg==(void*)&testpcacheGlobal ); + assert( testpcacheGlobal.pDummy==0 ); + assert( testpcacheGlobal.nInstance==0 ); + testpcacheGlobal.pDummy = sqlite3_malloc(10); + return testpcacheGlobal.pDummy==0 ? SQLITE_NOMEM : SQLITE_OK; +} + +/* +** Destructor +** +** Verify that this is only called after initialization. +** Free the memory allocated by the initializer. +*/ +static void testpcacheShutdown(void *pArg){ + assert( pArg==(void*)&testpcacheGlobal ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance==0 ); + sqlite3_free( testpcacheGlobal.pDummy ); + testpcacheGlobal.pDummy = 0; +} + +/* +** Number of pages in a cache. +** +** The number of pages is a hard upper bound in this test module. +** If more pages are requested, sqlite3PcacheFetch() returns NULL. +** +** If testing with in-memory temp tables, provide a larger pcache. +** Some of the test cases need this. +*/ +#if defined(SQLITE_TEMP_STORE) && SQLITE_TEMP_STORE>=2 +# define TESTPCACHE_NPAGE 499 +#else +# define TESTPCACHE_NPAGE 217 +#endif +#define TESTPCACHE_RESERVE 17 + +/* +** Magic numbers used to determine validity of the page cache. +*/ +#define TESTPCACHE_VALID 0x364585fd +#define TESTPCACHE_CLEAR 0xd42670d4 + +/* +** Private implementation of a page cache. +*/ +typedef struct testpcache testpcache; +struct testpcache { + int szPage; /* Size of each page. Multiple of 8. */ + int szExtra; /* Size of extra data that accompanies each page */ + int bPurgeable; /* True if the page cache is purgeable */ + int nFree; /* Number of unused slots in a[] */ + int nPinned; /* Number of pinned slots in a[] */ + unsigned iRand; /* State of the PRNG */ + unsigned iMagic; /* Magic number for sanity checking */ + struct testpcachePage { + sqlite3_pcache_page page; /* Base class */ + unsigned key; /* The key for this page. 0 means unallocated */ + int isPinned; /* True if the page is pinned */ + } a[TESTPCACHE_NPAGE]; /* All pages in the cache */ +}; + +/* +** Get a random number using the PRNG in the given page cache. +*/ +static unsigned testpcacheRandom(testpcache *p){ + unsigned x = 0; + int i; + for(i=0; i<4; i++){ + p->iRand = (p->iRand*69069 + 5); + x = (x<<8) | ((p->iRand>>16)&0xff); + } + return x; +} + + +/* +** Allocate a new page cache instance. +*/ +static sqlite3_pcache *testpcacheCreate( + int szPage, + int szExtra, + int bPurgeable +){ + int nMem; + char *x; + testpcache *p; + int i; + assert( testpcacheGlobal.pDummy!=0 ); + szPage = (szPage+7)&~7; + nMem = sizeof(testpcache) + TESTPCACHE_NPAGE*(szPage+szExtra); + p = sqlite3_malloc( nMem ); + if( p==0 ) return 0; + x = (char*)&p[1]; + p->szPage = szPage; + p->szExtra = szExtra; + p->nFree = TESTPCACHE_NPAGE; + p->nPinned = 0; + p->iRand = testpcacheGlobal.prngSeed; + p->bPurgeable = bPurgeable; + p->iMagic = TESTPCACHE_VALID; + for(i=0; ia[i].key = 0; + p->a[i].isPinned = 0; + p->a[i].page.pBuf = (void*)x; + p->a[i].page.pExtra = (void*)&x[szPage]; + } + testpcacheGlobal.nInstance++; + return (sqlite3_pcache*)p; +} + +/* +** Set the cache size +*/ +static void testpcacheCachesize(sqlite3_pcache *pCache, int newSize){ + testpcache *p = (testpcache*)pCache; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); +} + +/* +** Return the number of pages in the cache that are being used. +** This includes both pinned and unpinned pages. +*/ +static int testpcachePagecount(sqlite3_pcache *pCache){ + testpcache *p = (testpcache*)pCache; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + return TESTPCACHE_NPAGE - p->nFree; +} + +/* +** Fetch a page. +*/ +static sqlite3_pcache_page *testpcacheFetch( + sqlite3_pcache *pCache, + unsigned key, + int createFlag +){ + testpcache *p = (testpcache*)pCache; + int i, j; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + + /* See if the page is already in cache. Return immediately if it is */ + for(i=0; ia[i].key==key ){ + if( !p->a[i].isPinned ){ + p->nPinned++; + assert( p->nPinned <= TESTPCACHE_NPAGE - p->nFree ); + p->a[i].isPinned = 1; + } + return &p->a[i].page; + } + } + + /* If createFlag is 0, never allocate a new page */ + if( createFlag==0 ){ + return 0; + } + + /* If no pages are available, always fail */ + if( p->nPinned==TESTPCACHE_NPAGE ){ + return 0; + } + + /* Do not allocate the last TESTPCACHE_RESERVE pages unless createFlag is 2 */ + if( p->nPinned>=TESTPCACHE_NPAGE-TESTPCACHE_RESERVE && createFlag<2 ){ + return 0; + } + + /* Do not allocate if highStress is enabled and createFlag is not 2. + ** + ** The highStress setting causes pagerStress() to be called much more + ** often, which exercises the pager logic more intensely. + */ + if( testpcacheGlobal.highStress && createFlag<2 ){ + return 0; + } + + /* Find a free page to allocate if there are any free pages. + ** Withhold TESTPCACHE_RESERVE free pages until createFlag is 2. + */ + if( p->nFree>TESTPCACHE_RESERVE || (createFlag==2 && p->nFree>0) ){ + j = testpcacheRandom(p) % TESTPCACHE_NPAGE; + for(i=0; ia[j].key==0 ){ + p->a[j].key = key; + p->a[j].isPinned = 1; + memset(p->a[j].page.pBuf, 0, p->szPage); + memset(p->a[j].page.pExtra, 0, p->szExtra); + p->nPinned++; + p->nFree--; + assert( p->nPinned <= TESTPCACHE_NPAGE - p->nFree ); + return &p->a[j].page; + } + } + + /* The prior loop always finds a freepage to allocate */ + assert( 0 ); + } + + /* If this cache is not purgeable then we have to fail. + */ + if( p->bPurgeable==0 ){ + return 0; + } + + /* If there are no free pages, recycle a page. The page to + ** recycle is selected at random from all unpinned pages. + */ + j = testpcacheRandom(p) % TESTPCACHE_NPAGE; + for(i=0; ia[j].key>0 && p->a[j].isPinned==0 ){ + p->a[j].key = key; + p->a[j].isPinned = 1; + memset(p->a[j].page.pBuf, 0, p->szPage); + memset(p->a[j].page.pExtra, 0, p->szExtra); + p->nPinned++; + assert( p->nPinned <= TESTPCACHE_NPAGE - p->nFree ); + return &p->a[j].page; + } + } + + /* The previous loop always finds a page to recycle. */ + assert(0); + return 0; +} + +/* +** Unpin a page. +*/ +static void testpcacheUnpin( + sqlite3_pcache *pCache, + sqlite3_pcache_page *pOldPage, + int discard +){ + testpcache *p = (testpcache*)pCache; + int i; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + + /* Randomly discard pages as they are unpinned according to the + ** discardChance setting. If discardChance is 0, the random discard + ** never happens. If discardChance is 100, it always happens. + */ + if( p->bPurgeable + && (100-testpcacheGlobal.discardChance) <= (testpcacheRandom(p)%100) + ){ + discard = 1; + } + + for(i=0; ia[i].page==pOldPage ){ + /* The pOldPage pointer always points to a pinned page */ + assert( p->a[i].isPinned ); + p->a[i].isPinned = 0; + p->nPinned--; + assert( p->nPinned>=0 ); + if( discard ){ + p->a[i].key = 0; + p->nFree++; + assert( p->nFree<=TESTPCACHE_NPAGE ); + } + return; + } + } + + /* The pOldPage pointer always points to a valid page */ + assert( 0 ); +} + + +/* +** Rekey a single page. +*/ +static void testpcacheRekey( + sqlite3_pcache *pCache, + sqlite3_pcache_page *pOldPage, + unsigned oldKey, + unsigned newKey +){ + testpcache *p = (testpcache*)pCache; + int i; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + + /* If there already exists another page at newKey, verify that + ** the other page is unpinned and discard it. + */ + for(i=0; ia[i].key==newKey ){ + /* The new key is never a page that is already pinned */ + assert( p->a[i].isPinned==0 ); + p->a[i].key = 0; + p->nFree++; + assert( p->nFree<=TESTPCACHE_NPAGE ); + break; + } + } + + /* Find the page to be rekeyed and rekey it. + */ + for(i=0; ia[i].key==oldKey ){ + /* The oldKey and pOldPage parameters match */ + assert( &p->a[i].page==pOldPage ); + /* Page to be rekeyed must be pinned */ + assert( p->a[i].isPinned ); + p->a[i].key = newKey; + return; + } + } + + /* Rekey is always given a valid page to work with */ + assert( 0 ); +} + + +/* +** Truncate the page cache. Every page with a key of iLimit or larger +** is discarded. +*/ +static void testpcacheTruncate(sqlite3_pcache *pCache, unsigned iLimit){ + testpcache *p = (testpcache*)pCache; + unsigned int i; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + for(i=0; ia[i].key>=iLimit ){ + p->a[i].key = 0; + if( p->a[i].isPinned ){ + p->nPinned--; + assert( p->nPinned>=0 ); + } + p->nFree++; + assert( p->nFree<=TESTPCACHE_NPAGE ); + } + } +} + +/* +** Destroy a page cache. +*/ +static void testpcacheDestroy(sqlite3_pcache *pCache){ + testpcache *p = (testpcache*)pCache; + assert( p->iMagic==TESTPCACHE_VALID ); + assert( testpcacheGlobal.pDummy!=0 ); + assert( testpcacheGlobal.nInstance>0 ); + p->iMagic = TESTPCACHE_CLEAR; + sqlite3_free(p); + testpcacheGlobal.nInstance--; +} + + +/* +** Invoke this routine to register or unregister the testing pager cache +** implemented by this file. +** +** Install the test pager cache if installFlag is 1 and uninstall it if +** installFlag is 0. +** +** When installing, discardChance is a number between 0 and 100 that +** indicates the probability of discarding a page when unpinning the +** page. 0 means never discard (unless the discard flag is set). +** 100 means always discard. +*/ +void installTestPCache( + int installFlag, /* True to install. False to uninstall. */ + unsigned discardChance, /* 0-100. Chance to discard on unpin */ + unsigned prngSeed, /* Seed for the PRNG */ + unsigned highStress /* Call xStress agressively */ +){ + static const sqlite3_pcache_methods2 testPcache = { + 1, + (void*)&testpcacheGlobal, + testpcacheInit, + testpcacheShutdown, + testpcacheCreate, + testpcacheCachesize, + testpcachePagecount, + testpcacheFetch, + testpcacheUnpin, + testpcacheRekey, + testpcacheTruncate, + testpcacheDestroy, + }; + static sqlite3_pcache_methods2 defaultPcache; + static int isInstalled = 0; + + assert( testpcacheGlobal.nInstance==0 ); + assert( testpcacheGlobal.pDummy==0 ); + assert( discardChance<=100 ); + testpcacheGlobal.discardChance = discardChance; + testpcacheGlobal.prngSeed = prngSeed ^ (prngSeed<<16); + testpcacheGlobal.highStress = highStress; + if( installFlag!=isInstalled ){ + if( installFlag ){ + sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &defaultPcache); + assert( defaultPcache.xCreate!=testpcacheCreate ); + sqlite3_config(SQLITE_CONFIG_PCACHE2, &testPcache); + }else{ + assert( defaultPcache.xCreate!=0 ); + sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultPcache); + } + isInstalled = installFlag; + } +} diff --git a/components/external/SQLite-3.8.1/src/test_quota.c b/components/external/SQLite-3.8.1/src/test_quota.c new file mode 100644 index 0000000000000000000000000000000000000000..e590996ca4b8574ab1e4185d577756664ad2495f --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_quota.c @@ -0,0 +1,2008 @@ +/* +** 2010 September 31 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains a VFS "shim" - a layer that sits in between the +** pager and the real VFS. +** +** This particular shim enforces a quota system on files. One or more +** database files are in a "quota group" that is defined by a GLOB +** pattern. A quota is set for the combined size of all files in the +** the group. A quota of zero means "no limit". If the total size +** of all files in the quota group is greater than the limit, then +** write requests that attempt to enlarge a file fail with SQLITE_FULL. +** +** However, before returning SQLITE_FULL, the write requests invoke +** a callback function that is configurable for each quota group. +** This callback has the opportunity to enlarge the quota. If the +** callback does enlarge the quota such that the total size of all +** files within the group is less than the new quota, then the write +** continues as if nothing had happened. +*/ +#include "test_quota.h" +#include +#include + +/* +** For an build without mutexes, no-op the mutex calls. +*/ +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0 +#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) +#define sqlite3_mutex_free(X) +#define sqlite3_mutex_enter(X) +#define sqlite3_mutex_try(X) SQLITE_OK +#define sqlite3_mutex_leave(X) +#define sqlite3_mutex_held(X) ((void)(X),1) +#define sqlite3_mutex_notheld(X) ((void)(X),1) +#endif /* SQLITE_THREADSAFE==0 */ + + +/* +** Figure out if we are dealing with Unix, Windows, or some other +** operating system. After the following block of preprocess macros, +** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER +** will defined to either 1 or 0. One of the four will be 1. The other +** three will be 0. +*/ +#if defined(SQLITE_OS_OTHER) +# if SQLITE_OS_OTHER==1 +# undef SQLITE_OS_UNIX +# define SQLITE_OS_UNIX 0 +# undef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# else +# undef SQLITE_OS_OTHER +# endif +#endif +#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) +# define SQLITE_OS_OTHER 0 +# ifndef SQLITE_OS_WIN +# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) \ + || defined(__MINGW32__) || defined(__BORLANDC__) +# define SQLITE_OS_WIN 1 +# define SQLITE_OS_UNIX 0 +# else +# define SQLITE_OS_WIN 0 +# define SQLITE_OS_UNIX 1 +# endif +# else +# define SQLITE_OS_UNIX 0 +# endif +#else +# ifndef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# endif +#endif + +#if SQLITE_OS_UNIX +# include +#endif +#if SQLITE_OS_WIN +# include +# include +#endif + + +/************************ Object Definitions ******************************/ + +/* Forward declaration of all object types */ +typedef struct quotaGroup quotaGroup; +typedef struct quotaConn quotaConn; +typedef struct quotaFile quotaFile; + +/* +** A "quota group" is a collection of files whose collective size we want +** to limit. Each quota group is defined by a GLOB pattern. +** +** There is an instance of the following object for each defined quota +** group. This object records the GLOB pattern that defines which files +** belong to the quota group. The object also remembers the size limit +** for the group (the quota) and the callback to be invoked when the +** sum of the sizes of the files within the group goes over the limit. +** +** A quota group must be established (using sqlite3_quota_set(...)) +** prior to opening any of the database connections that access files +** within the quota group. +*/ +struct quotaGroup { + const char *zPattern; /* Filename pattern to be quotaed */ + sqlite3_int64 iLimit; /* Upper bound on total file size */ + sqlite3_int64 iSize; /* Current size of all files */ + void (*xCallback)( /* Callback invoked when going over quota */ + const char *zFilename, /* Name of file whose size increases */ + sqlite3_int64 *piLimit, /* IN/OUT: The current limit */ + sqlite3_int64 iSize, /* Total size of all files in the group */ + void *pArg /* Client data */ + ); + void *pArg; /* Third argument to the xCallback() */ + void (*xDestroy)(void*); /* Optional destructor for pArg */ + quotaGroup *pNext, **ppPrev; /* Doubly linked list of all quota objects */ + quotaFile *pFiles; /* Files within this group */ +}; + +/* +** An instance of this structure represents a single file that is part +** of a quota group. A single file can be opened multiple times. In +** order keep multiple openings of the same file from causing the size +** of the file to count against the quota multiple times, each file +** has a unique instance of this object and multiple open connections +** to the same file each point to a single instance of this object. +*/ +struct quotaFile { + char *zFilename; /* Name of this file */ + quotaGroup *pGroup; /* Quota group to which this file belongs */ + sqlite3_int64 iSize; /* Current size of this file */ + int nRef; /* Number of times this file is open */ + int deleteOnClose; /* True to delete this file when it closes */ + quotaFile *pNext, **ppPrev; /* Linked list of files in the same group */ +}; + +/* +** An instance of the following object represents each open connection +** to a file that participates in quota tracking. This object is a +** subclass of sqlite3_file. The sqlite3_file object for the underlying +** VFS is appended to this structure. +*/ +struct quotaConn { + sqlite3_file base; /* Base class - must be first */ + quotaFile *pFile; /* The underlying file */ + /* The underlying VFS sqlite3_file is appended to this object */ +}; + +/* +** An instance of the following object records the state of an +** open file. This object is opaque to all users - the internal +** structure is only visible to the functions below. +*/ +struct quota_FILE { + FILE *f; /* Open stdio file pointer */ + sqlite3_int64 iOfst; /* Current offset into the file */ + quotaFile *pFile; /* The file record in the quota system */ +#if SQLITE_OS_WIN + char *zMbcsName; /* Full MBCS pathname of the file */ +#endif +}; + + +/************************* Global Variables **********************************/ +/* +** All global variables used by this file are containing within the following +** gQuota structure. +*/ +static struct { + /* The pOrigVfs is the real, original underlying VFS implementation. + ** Most operations pass-through to the real VFS. This value is read-only + ** during operation. It is only modified at start-time and thus does not + ** require a mutex. + */ + sqlite3_vfs *pOrigVfs; + + /* The sThisVfs is the VFS structure used by this shim. It is initialized + ** at start-time and thus does not require a mutex + */ + sqlite3_vfs sThisVfs; + + /* The sIoMethods defines the methods used by sqlite3_file objects + ** associated with this shim. It is initialized at start-time and does + ** not require a mutex. + ** + ** When the underlying VFS is called to open a file, it might return + ** either a version 1 or a version 2 sqlite3_file object. This shim + ** has to create a wrapper sqlite3_file of the same version. Hence + ** there are two I/O method structures, one for version 1 and the other + ** for version 2. + */ + sqlite3_io_methods sIoMethodsV1; + sqlite3_io_methods sIoMethodsV2; + + /* True when this shim as been initialized. + */ + int isInitialized; + + /* For run-time access any of the other global data structures in this + ** shim, the following mutex must be held. + */ + sqlite3_mutex *pMutex; + + /* List of quotaGroup objects. + */ + quotaGroup *pGroup; + +} gQuota; + +/************************* Utility Routines *********************************/ +/* +** Acquire and release the mutex used to serialize access to the +** list of quotaGroups. +*/ +static void quotaEnter(void){ sqlite3_mutex_enter(gQuota.pMutex); } +static void quotaLeave(void){ sqlite3_mutex_leave(gQuota.pMutex); } + +/* Count the number of open files in a quotaGroup +*/ +static int quotaGroupOpenFileCount(quotaGroup *pGroup){ + int N = 0; + quotaFile *pFile = pGroup->pFiles; + while( pFile ){ + if( pFile->nRef ) N++; + pFile = pFile->pNext; + } + return N; +} + +/* Remove a file from a quota group. +*/ +static void quotaRemoveFile(quotaFile *pFile){ + quotaGroup *pGroup = pFile->pGroup; + pGroup->iSize -= pFile->iSize; + *pFile->ppPrev = pFile->pNext; + if( pFile->pNext ) pFile->pNext->ppPrev = pFile->ppPrev; + sqlite3_free(pFile); +} + +/* Remove all files from a quota group. It is always the case that +** all files will be closed when this routine is called. +*/ +static void quotaRemoveAllFiles(quotaGroup *pGroup){ + while( pGroup->pFiles ){ + assert( pGroup->pFiles->nRef==0 ); + quotaRemoveFile(pGroup->pFiles); + } +} + + +/* If the reference count and threshold for a quotaGroup are both +** zero, then destroy the quotaGroup. +*/ +static void quotaGroupDeref(quotaGroup *pGroup){ + if( pGroup->iLimit==0 && quotaGroupOpenFileCount(pGroup)==0 ){ + quotaRemoveAllFiles(pGroup); + *pGroup->ppPrev = pGroup->pNext; + if( pGroup->pNext ) pGroup->pNext->ppPrev = pGroup->ppPrev; + if( pGroup->xDestroy ) pGroup->xDestroy(pGroup->pArg); + sqlite3_free(pGroup); + } +} + +/* +** Return TRUE if string z matches glob pattern zGlob. +** +** Globbing rules: +** +** '*' Matches any sequence of zero or more characters. +** +** '?' Matches exactly one character. +** +** [...] Matches one character from the enclosed list of +** characters. +** +** [^...] Matches one character not in the enclosed list. +** +** / Matches "/" or "\\" +** +*/ +static int quotaStrglob(const char *zGlob, const char *z){ + int c, c2, cx; + int invert; + int seen; + + while( (c = (*(zGlob++)))!=0 ){ + if( c=='*' ){ + while( (c=(*(zGlob++))) == '*' || c=='?' ){ + if( c=='?' && (*(z++))==0 ) return 0; + } + if( c==0 ){ + return 1; + }else if( c=='[' ){ + while( *z && quotaStrglob(zGlob-1,z)==0 ){ + z++; + } + return (*z)!=0; + } + cx = (c=='/') ? '\\' : c; + while( (c2 = (*(z++)))!=0 ){ + while( c2!=c && c2!=cx ){ + c2 = *(z++); + if( c2==0 ) return 0; + } + if( quotaStrglob(zGlob,z) ) return 1; + } + return 0; + }else if( c=='?' ){ + if( (*(z++))==0 ) return 0; + }else if( c=='[' ){ + int prior_c = 0; + seen = 0; + invert = 0; + c = *(z++); + if( c==0 ) return 0; + c2 = *(zGlob++); + if( c2=='^' ){ + invert = 1; + c2 = *(zGlob++); + } + if( c2==']' ){ + if( c==']' ) seen = 1; + c2 = *(zGlob++); + } + while( c2 && c2!=']' ){ + if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ + c2 = *(zGlob++); + if( c>=prior_c && c<=c2 ) seen = 1; + prior_c = 0; + }else{ + if( c==c2 ){ + seen = 1; + } + prior_c = c2; + } + c2 = *(zGlob++); + } + if( c2==0 || (seen ^ invert)==0 ) return 0; + }else if( c=='/' ){ + if( z[0]!='/' && z[0]!='\\' ) return 0; + z++; + }else{ + if( c!=(*(z++)) ) return 0; + } + } + return *z==0; +} + + +/* Find a quotaGroup given the filename. +** +** Return a pointer to the quotaGroup object. Return NULL if not found. +*/ +static quotaGroup *quotaGroupFind(const char *zFilename){ + quotaGroup *p; + for(p=gQuota.pGroup; p && quotaStrglob(p->zPattern, zFilename)==0; + p=p->pNext){} + return p; +} + +/* Translate an sqlite3_file* that is really a quotaConn* into +** the sqlite3_file* for the underlying original VFS. +*/ +static sqlite3_file *quotaSubOpen(sqlite3_file *pConn){ + quotaConn *p = (quotaConn*)pConn; + return (sqlite3_file*)&p[1]; +} + +/* Find a file in a quota group and return a pointer to that file. +** Return NULL if the file is not in the group. +*/ +static quotaFile *quotaFindFile( + quotaGroup *pGroup, /* Group in which to look for the file */ + const char *zName, /* Full pathname of the file */ + int createFlag /* Try to create the file if not found */ +){ + quotaFile *pFile = pGroup->pFiles; + while( pFile && strcmp(pFile->zFilename, zName)!=0 ){ + pFile = pFile->pNext; + } + if( pFile==0 && createFlag ){ + int nName = (int)(strlen(zName) & 0x3fffffff); + pFile = (quotaFile *)sqlite3_malloc( sizeof(*pFile) + nName + 1 ); + if( pFile ){ + memset(pFile, 0, sizeof(*pFile)); + pFile->zFilename = (char*)&pFile[1]; + memcpy(pFile->zFilename, zName, nName+1); + pFile->pNext = pGroup->pFiles; + if( pGroup->pFiles ) pGroup->pFiles->ppPrev = &pFile->pNext; + pFile->ppPrev = &pGroup->pFiles; + pGroup->pFiles = pFile; + pFile->pGroup = pGroup; + } + } + return pFile; +} +/* +** Translate UTF8 to MBCS for use in fopen() calls. Return a pointer to the +** translated text.. Call quota_mbcs_free() to deallocate any memory +** used to store the returned pointer when done. +*/ +static char *quota_utf8_to_mbcs(const char *zUtf8){ +#if SQLITE_OS_WIN + size_t n; /* Bytes in zUtf8 */ + int nWide; /* number of UTF-16 characters */ + int nMbcs; /* Bytes of MBCS */ + LPWSTR zTmpWide; /* The UTF16 text */ + char *zMbcs; /* The MBCS text */ + int codepage; /* Code page used by fopen() */ + + n = strlen(zUtf8); + nWide = MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, NULL, 0); + if( nWide==0 ) return 0; + zTmpWide = (LPWSTR)sqlite3_malloc( (nWide+1)*sizeof(zTmpWide[0]) ); + if( zTmpWide==0 ) return 0; + MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, zTmpWide, nWide); + codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; + nMbcs = WideCharToMultiByte(codepage, 0, zTmpWide, nWide, 0, 0, 0, 0); + zMbcs = nMbcs ? (char*)sqlite3_malloc( nMbcs+1 ) : 0; + if( zMbcs ){ + WideCharToMultiByte(codepage, 0, zTmpWide, nWide, zMbcs, nMbcs, 0, 0); + } + sqlite3_free(zTmpWide); + return zMbcs; +#else + return (char*)zUtf8; /* No-op on unix */ +#endif +} + +/* +** Deallocate any memory allocated by quota_utf8_to_mbcs(). +*/ +static void quota_mbcs_free(char *zOld){ +#if SQLITE_OS_WIN + sqlite3_free(zOld); +#else + /* No-op on unix */ +#endif +} + +/************************* VFS Method Wrappers *****************************/ +/* +** This is the xOpen method used for the "quota" VFS. +** +** Most of the work is done by the underlying original VFS. This method +** simply links the new file into the appropriate quota group if it is a +** file that needs to be tracked. +*/ +static int quotaOpen( + sqlite3_vfs *pVfs, /* The quota VFS */ + const char *zName, /* Name of file to be opened */ + sqlite3_file *pConn, /* Fill in this file descriptor */ + int flags, /* Flags to control the opening */ + int *pOutFlags /* Flags showing results of opening */ +){ + int rc; /* Result code */ + quotaConn *pQuotaOpen; /* The new quota file descriptor */ + quotaFile *pFile; /* Corresponding quotaFile obj */ + quotaGroup *pGroup; /* The group file belongs to */ + sqlite3_file *pSubOpen; /* Real file descriptor */ + sqlite3_vfs *pOrigVfs = gQuota.pOrigVfs; /* Real VFS */ + + /* If the file is not a main database file or a WAL, then use the + ** normal xOpen method. + */ + if( (flags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_WAL))==0 ){ + return pOrigVfs->xOpen(pOrigVfs, zName, pConn, flags, pOutFlags); + } + + /* If the name of the file does not match any quota group, then + ** use the normal xOpen method. + */ + quotaEnter(); + pGroup = quotaGroupFind(zName); + if( pGroup==0 ){ + rc = pOrigVfs->xOpen(pOrigVfs, zName, pConn, flags, pOutFlags); + }else{ + /* If we get to this point, it means the file needs to be quota tracked. + */ + pQuotaOpen = (quotaConn*)pConn; + pSubOpen = quotaSubOpen(pConn); + rc = pOrigVfs->xOpen(pOrigVfs, zName, pSubOpen, flags, pOutFlags); + if( rc==SQLITE_OK ){ + pFile = quotaFindFile(pGroup, zName, 1); + if( pFile==0 ){ + quotaLeave(); + pSubOpen->pMethods->xClose(pSubOpen); + return SQLITE_NOMEM; + } + pFile->deleteOnClose = (flags & SQLITE_OPEN_DELETEONCLOSE)!=0; + pFile->nRef++; + pQuotaOpen->pFile = pFile; + if( pSubOpen->pMethods->iVersion==1 ){ + pQuotaOpen->base.pMethods = &gQuota.sIoMethodsV1; + }else{ + pQuotaOpen->base.pMethods = &gQuota.sIoMethodsV2; + } + } + } + quotaLeave(); + return rc; +} + +/* +** This is the xDelete method used for the "quota" VFS. +** +** If the file being deleted is part of the quota group, then reduce +** the size of the quota group accordingly. And remove the file from +** the set of files in the quota group. +*/ +static int quotaDelete( + sqlite3_vfs *pVfs, /* The quota VFS */ + const char *zName, /* Name of file to be deleted */ + int syncDir /* Do a directory sync after deleting */ +){ + int rc; /* Result code */ + quotaFile *pFile; /* Files in the quota */ + quotaGroup *pGroup; /* The group file belongs to */ + sqlite3_vfs *pOrigVfs = gQuota.pOrigVfs; /* Real VFS */ + + /* Do the actual file delete */ + rc = pOrigVfs->xDelete(pOrigVfs, zName, syncDir); + + /* If the file just deleted is a member of a quota group, then remove + ** it from that quota group. + */ + if( rc==SQLITE_OK ){ + quotaEnter(); + pGroup = quotaGroupFind(zName); + if( pGroup ){ + pFile = quotaFindFile(pGroup, zName, 0); + if( pFile ){ + if( pFile->nRef ){ + pFile->deleteOnClose = 1; + }else{ + quotaRemoveFile(pFile); + quotaGroupDeref(pGroup); + } + } + } + quotaLeave(); + } + return rc; +} + + +/************************ I/O Method Wrappers *******************************/ + +/* xClose requests get passed through to the original VFS. But we +** also have to unlink the quotaConn from the quotaFile and quotaGroup. +** The quotaFile and/or quotaGroup are freed if they are no longer in use. +*/ +static int quotaClose(sqlite3_file *pConn){ + quotaConn *p = (quotaConn*)pConn; + quotaFile *pFile = p->pFile; + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + int rc; + rc = pSubOpen->pMethods->xClose(pSubOpen); + quotaEnter(); + pFile->nRef--; + if( pFile->nRef==0 ){ + quotaGroup *pGroup = pFile->pGroup; + if( pFile->deleteOnClose ){ + gQuota.pOrigVfs->xDelete(gQuota.pOrigVfs, pFile->zFilename, 0); + quotaRemoveFile(pFile); + } + quotaGroupDeref(pGroup); + } + quotaLeave(); + return rc; +} + +/* Pass xRead requests directory thru to the original VFS without +** further processing. +*/ +static int quotaRead( + sqlite3_file *pConn, + void *pBuf, + int iAmt, + sqlite3_int64 iOfst +){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt, iOfst); +} + +/* Check xWrite requests to see if they expand the file. If they do, +** the perform a quota check before passing them through to the +** original VFS. +*/ +static int quotaWrite( + sqlite3_file *pConn, + const void *pBuf, + int iAmt, + sqlite3_int64 iOfst +){ + quotaConn *p = (quotaConn*)pConn; + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + sqlite3_int64 iEnd = iOfst+iAmt; + quotaGroup *pGroup; + quotaFile *pFile = p->pFile; + sqlite3_int64 szNew; + + if( pFile->iSizepGroup; + quotaEnter(); + szNew = pGroup->iSize - pFile->iSize + iEnd; + if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){ + if( pGroup->xCallback ){ + pGroup->xCallback(pFile->zFilename, &pGroup->iLimit, szNew, + pGroup->pArg); + } + if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){ + quotaLeave(); + return SQLITE_FULL; + } + } + pGroup->iSize = szNew; + pFile->iSize = iEnd; + quotaLeave(); + } + return pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt, iOfst); +} + +/* Pass xTruncate requests thru to the original VFS. If the +** success, update the file size. +*/ +static int quotaTruncate(sqlite3_file *pConn, sqlite3_int64 size){ + quotaConn *p = (quotaConn*)pConn; + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + int rc = pSubOpen->pMethods->xTruncate(pSubOpen, size); + quotaFile *pFile = p->pFile; + quotaGroup *pGroup; + if( rc==SQLITE_OK ){ + quotaEnter(); + pGroup = pFile->pGroup; + pGroup->iSize -= pFile->iSize; + pFile->iSize = size; + pGroup->iSize += size; + quotaLeave(); + } + return rc; +} + +/* Pass xSync requests through to the original VFS without change +*/ +static int quotaSync(sqlite3_file *pConn, int flags){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xSync(pSubOpen, flags); +} + +/* Pass xFileSize requests through to the original VFS but then +** update the quotaGroup with the new size before returning. +*/ +static int quotaFileSize(sqlite3_file *pConn, sqlite3_int64 *pSize){ + quotaConn *p = (quotaConn*)pConn; + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + quotaFile *pFile = p->pFile; + quotaGroup *pGroup; + sqlite3_int64 sz; + int rc; + + rc = pSubOpen->pMethods->xFileSize(pSubOpen, &sz); + if( rc==SQLITE_OK ){ + quotaEnter(); + pGroup = pFile->pGroup; + pGroup->iSize -= pFile->iSize; + pFile->iSize = sz; + pGroup->iSize += sz; + quotaLeave(); + *pSize = sz; + } + return rc; +} + +/* Pass xLock requests through to the original VFS unchanged. +*/ +static int quotaLock(sqlite3_file *pConn, int lock){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xLock(pSubOpen, lock); +} + +/* Pass xUnlock requests through to the original VFS unchanged. +*/ +static int quotaUnlock(sqlite3_file *pConn, int lock){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xUnlock(pSubOpen, lock); +} + +/* Pass xCheckReservedLock requests through to the original VFS unchanged. +*/ +static int quotaCheckReservedLock(sqlite3_file *pConn, int *pResOut){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xCheckReservedLock(pSubOpen, pResOut); +} + +/* Pass xFileControl requests through to the original VFS unchanged. +*/ +static int quotaFileControl(sqlite3_file *pConn, int op, void *pArg){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + int rc = pSubOpen->pMethods->xFileControl(pSubOpen, op, pArg); +#if defined(SQLITE_FCNTL_VFSNAME) + if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){ + *(char**)pArg = sqlite3_mprintf("quota/%z", *(char**)pArg); + } +#endif + return rc; +} + +/* Pass xSectorSize requests through to the original VFS unchanged. +*/ +static int quotaSectorSize(sqlite3_file *pConn){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xSectorSize(pSubOpen); +} + +/* Pass xDeviceCharacteristics requests through to the original VFS unchanged. +*/ +static int quotaDeviceCharacteristics(sqlite3_file *pConn){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xDeviceCharacteristics(pSubOpen); +} + +/* Pass xShmMap requests through to the original VFS unchanged. +*/ +static int quotaShmMap( + sqlite3_file *pConn, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int szRegion, /* Size of regions */ + int bExtend, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xShmMap(pSubOpen, iRegion, szRegion, bExtend, pp); +} + +/* Pass xShmLock requests through to the original VFS unchanged. +*/ +static int quotaShmLock( + sqlite3_file *pConn, /* Database file holding the shared memory */ + int ofst, /* First lock to acquire or release */ + int n, /* Number of locks to acquire or release */ + int flags /* What to do with the lock */ +){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xShmLock(pSubOpen, ofst, n, flags); +} + +/* Pass xShmBarrier requests through to the original VFS unchanged. +*/ +static void quotaShmBarrier(sqlite3_file *pConn){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + pSubOpen->pMethods->xShmBarrier(pSubOpen); +} + +/* Pass xShmUnmap requests through to the original VFS unchanged. +*/ +static int quotaShmUnmap(sqlite3_file *pConn, int deleteFlag){ + sqlite3_file *pSubOpen = quotaSubOpen(pConn); + return pSubOpen->pMethods->xShmUnmap(pSubOpen, deleteFlag); +} + +/************************** Public Interfaces *****************************/ +/* +** Initialize the quota VFS shim. Use the VFS named zOrigVfsName +** as the VFS that does the actual work. Use the default if +** zOrigVfsName==NULL. +** +** The quota VFS shim is named "quota". It will become the default +** VFS if makeDefault is non-zero. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once +** during start-up. +*/ +int sqlite3_quota_initialize(const char *zOrigVfsName, int makeDefault){ + sqlite3_vfs *pOrigVfs; + if( gQuota.isInitialized ) return SQLITE_MISUSE; + pOrigVfs = sqlite3_vfs_find(zOrigVfsName); + if( pOrigVfs==0 ) return SQLITE_ERROR; + assert( pOrigVfs!=&gQuota.sThisVfs ); + gQuota.pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( !gQuota.pMutex ){ + return SQLITE_NOMEM; + } + gQuota.isInitialized = 1; + gQuota.pOrigVfs = pOrigVfs; + gQuota.sThisVfs = *pOrigVfs; + gQuota.sThisVfs.xOpen = quotaOpen; + gQuota.sThisVfs.xDelete = quotaDelete; + gQuota.sThisVfs.szOsFile += sizeof(quotaConn); + gQuota.sThisVfs.zName = "quota"; + gQuota.sIoMethodsV1.iVersion = 1; + gQuota.sIoMethodsV1.xClose = quotaClose; + gQuota.sIoMethodsV1.xRead = quotaRead; + gQuota.sIoMethodsV1.xWrite = quotaWrite; + gQuota.sIoMethodsV1.xTruncate = quotaTruncate; + gQuota.sIoMethodsV1.xSync = quotaSync; + gQuota.sIoMethodsV1.xFileSize = quotaFileSize; + gQuota.sIoMethodsV1.xLock = quotaLock; + gQuota.sIoMethodsV1.xUnlock = quotaUnlock; + gQuota.sIoMethodsV1.xCheckReservedLock = quotaCheckReservedLock; + gQuota.sIoMethodsV1.xFileControl = quotaFileControl; + gQuota.sIoMethodsV1.xSectorSize = quotaSectorSize; + gQuota.sIoMethodsV1.xDeviceCharacteristics = quotaDeviceCharacteristics; + gQuota.sIoMethodsV2 = gQuota.sIoMethodsV1; + gQuota.sIoMethodsV2.iVersion = 2; + gQuota.sIoMethodsV2.xShmMap = quotaShmMap; + gQuota.sIoMethodsV2.xShmLock = quotaShmLock; + gQuota.sIoMethodsV2.xShmBarrier = quotaShmBarrier; + gQuota.sIoMethodsV2.xShmUnmap = quotaShmUnmap; + sqlite3_vfs_register(&gQuota.sThisVfs, makeDefault); + return SQLITE_OK; +} + +/* +** Shutdown the quota system. +** +** All SQLite database connections must be closed before calling this +** routine. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once while +** shutting down in order to free all remaining quota groups. +*/ +int sqlite3_quota_shutdown(void){ + quotaGroup *pGroup; + if( gQuota.isInitialized==0 ) return SQLITE_MISUSE; + for(pGroup=gQuota.pGroup; pGroup; pGroup=pGroup->pNext){ + if( quotaGroupOpenFileCount(pGroup)>0 ) return SQLITE_MISUSE; + } + while( gQuota.pGroup ){ + pGroup = gQuota.pGroup; + gQuota.pGroup = pGroup->pNext; + pGroup->iLimit = 0; + assert( quotaGroupOpenFileCount(pGroup)==0 ); + quotaGroupDeref(pGroup); + } + gQuota.isInitialized = 0; + sqlite3_mutex_free(gQuota.pMutex); + sqlite3_vfs_unregister(&gQuota.sThisVfs); + memset(&gQuota, 0, sizeof(gQuota)); + return SQLITE_OK; +} + +/* +** Create or destroy a quota group. +** +** The quota group is defined by the zPattern. When calling this routine +** with a zPattern for a quota group that already exists, this routine +** merely updates the iLimit, xCallback, and pArg values for that quota +** group. If zPattern is new, then a new quota group is created. +** +** If the iLimit for a quota group is set to zero, then the quota group +** is disabled and will be deleted when the last database connection using +** the quota group is closed. +** +** Calling this routine on a zPattern that does not exist and with a +** zero iLimit is a no-op. +** +** A quota group must exist with a non-zero iLimit prior to opening +** database connections if those connections are to participate in the +** quota group. Creating a quota group does not affect database connections +** that are already open. +*/ +int sqlite3_quota_set( + const char *zPattern, /* The filename pattern */ + sqlite3_int64 iLimit, /* New quota to set for this quota group */ + void (*xCallback)( /* Callback invoked when going over quota */ + const char *zFilename, /* Name of file whose size increases */ + sqlite3_int64 *piLimit, /* IN/OUT: The current limit */ + sqlite3_int64 iSize, /* Total size of all files in the group */ + void *pArg /* Client data */ + ), + void *pArg, /* client data passed thru to callback */ + void (*xDestroy)(void*) /* Optional destructor for pArg */ +){ + quotaGroup *pGroup; + quotaEnter(); + pGroup = gQuota.pGroup; + while( pGroup && strcmp(pGroup->zPattern, zPattern)!=0 ){ + pGroup = pGroup->pNext; + } + if( pGroup==0 ){ + int nPattern = (int)(strlen(zPattern) & 0x3fffffff); + if( iLimit<=0 ){ + quotaLeave(); + return SQLITE_OK; + } + pGroup = (quotaGroup *)sqlite3_malloc( sizeof(*pGroup) + nPattern + 1 ); + if( pGroup==0 ){ + quotaLeave(); + return SQLITE_NOMEM; + } + memset(pGroup, 0, sizeof(*pGroup)); + pGroup->zPattern = (char*)&pGroup[1]; + memcpy((char *)pGroup->zPattern, zPattern, nPattern+1); + if( gQuota.pGroup ) gQuota.pGroup->ppPrev = &pGroup->pNext; + pGroup->pNext = gQuota.pGroup; + pGroup->ppPrev = &gQuota.pGroup; + gQuota.pGroup = pGroup; + } + pGroup->iLimit = iLimit; + pGroup->xCallback = xCallback; + if( pGroup->xDestroy && pGroup->pArg!=pArg ){ + pGroup->xDestroy(pGroup->pArg); + } + pGroup->pArg = pArg; + pGroup->xDestroy = xDestroy; + quotaGroupDeref(pGroup); + quotaLeave(); + return SQLITE_OK; +} + +/* +** Bring the named file under quota management. Or if it is already under +** management, update its size. +*/ +int sqlite3_quota_file(const char *zFilename){ + char *zFull; + sqlite3_file *fd; + int rc; + int outFlags = 0; + sqlite3_int64 iSize; + int nAlloc = gQuota.sThisVfs.szOsFile + gQuota.sThisVfs.mxPathname+2; + + /* Allocate space for a file-handle and the full path for file zFilename */ + fd = (sqlite3_file *)sqlite3_malloc(nAlloc); + if( fd==0 ){ + rc = SQLITE_NOMEM; + }else{ + zFull = &((char *)fd)[gQuota.sThisVfs.szOsFile]; + rc = gQuota.pOrigVfs->xFullPathname(gQuota.pOrigVfs, zFilename, + gQuota.sThisVfs.mxPathname+1, zFull); + } + + if( rc==SQLITE_OK ){ + zFull[strlen(zFull)+1] = '\0'; + rc = quotaOpen(&gQuota.sThisVfs, zFull, fd, + SQLITE_OPEN_READONLY | SQLITE_OPEN_MAIN_DB, &outFlags); + if( rc==SQLITE_OK ){ + fd->pMethods->xFileSize(fd, &iSize); + fd->pMethods->xClose(fd); + }else if( rc==SQLITE_CANTOPEN ){ + quotaGroup *pGroup; + quotaFile *pFile; + quotaEnter(); + pGroup = quotaGroupFind(zFull); + if( pGroup ){ + pFile = quotaFindFile(pGroup, zFull, 0); + if( pFile ) quotaRemoveFile(pFile); + } + quotaLeave(); + } + } + + sqlite3_free(fd); + return rc; +} + +/* +** Open a potentially quotaed file for I/O. +*/ +quota_FILE *sqlite3_quota_fopen(const char *zFilename, const char *zMode){ + quota_FILE *p = 0; + char *zFull = 0; + char *zFullTranslated = 0; + int rc; + quotaGroup *pGroup; + quotaFile *pFile; + + zFull = (char*)sqlite3_malloc(gQuota.sThisVfs.mxPathname + 1); + if( zFull==0 ) return 0; + rc = gQuota.pOrigVfs->xFullPathname(gQuota.pOrigVfs, zFilename, + gQuota.sThisVfs.mxPathname+1, zFull); + if( rc ) goto quota_fopen_error; + p = (quota_FILE*)sqlite3_malloc(sizeof(*p)); + if( p==0 ) goto quota_fopen_error; + memset(p, 0, sizeof(*p)); + zFullTranslated = quota_utf8_to_mbcs(zFull); + if( zFullTranslated==0 ) goto quota_fopen_error; + p->f = fopen(zFullTranslated, zMode); + if( p->f==0 ) goto quota_fopen_error; + quotaEnter(); + pGroup = quotaGroupFind(zFull); + if( pGroup ){ + pFile = quotaFindFile(pGroup, zFull, 1); + if( pFile==0 ){ + quotaLeave(); + goto quota_fopen_error; + } + pFile->nRef++; + p->pFile = pFile; + } + quotaLeave(); + sqlite3_free(zFull); +#if SQLITE_OS_WIN + p->zMbcsName = zFullTranslated; +#endif + return p; + +quota_fopen_error: + quota_mbcs_free(zFullTranslated); + sqlite3_free(zFull); + if( p && p->f ) fclose(p->f); + sqlite3_free(p); + return 0; +} + +/* +** Read content from a quota_FILE +*/ +size_t sqlite3_quota_fread( + void *pBuf, /* Store the content here */ + size_t size, /* Size of each element */ + size_t nmemb, /* Number of elements to read */ + quota_FILE *p /* Read from this quota_FILE object */ +){ + return fread(pBuf, size, nmemb, p->f); +} + +/* +** Write content into a quota_FILE. Invoke the quota callback and block +** the write if we exceed quota. +*/ +size_t sqlite3_quota_fwrite( + const void *pBuf, /* Take content to write from here */ + size_t size, /* Size of each element */ + size_t nmemb, /* Number of elements */ + quota_FILE *p /* Write to this quota_FILE objecct */ +){ + sqlite3_int64 iOfst; + sqlite3_int64 iEnd; + sqlite3_int64 szNew; + quotaFile *pFile; + size_t rc; + + iOfst = ftell(p->f); + iEnd = iOfst + size*nmemb; + pFile = p->pFile; + if( pFile && pFile->iSizepGroup; + quotaEnter(); + szNew = pGroup->iSize - pFile->iSize + iEnd; + if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){ + if( pGroup->xCallback ){ + pGroup->xCallback(pFile->zFilename, &pGroup->iLimit, szNew, + pGroup->pArg); + } + if( szNew>pGroup->iLimit && pGroup->iLimit>0 ){ + iEnd = pGroup->iLimit - pGroup->iSize + pFile->iSize; + nmemb = (size_t)((iEnd - iOfst)/size); + iEnd = iOfst + size*nmemb; + szNew = pGroup->iSize - pFile->iSize + iEnd; + } + } + pGroup->iSize = szNew; + pFile->iSize = iEnd; + quotaLeave(); + }else{ + pFile = 0; + } + rc = fwrite(pBuf, size, nmemb, p->f); + + /* If the write was incomplete, adjust the file size and group size + ** downward */ + if( rcpGroup->iSize += iNewEnd - pFile->iSize; + pFile->iSize = iNewEnd; + quotaLeave(); + } + return rc; +} + +/* +** Close an open quota_FILE stream. +*/ +int sqlite3_quota_fclose(quota_FILE *p){ + int rc; + quotaFile *pFile; + rc = fclose(p->f); + pFile = p->pFile; + if( pFile ){ + quotaEnter(); + pFile->nRef--; + if( pFile->nRef==0 ){ + quotaGroup *pGroup = pFile->pGroup; + if( pFile->deleteOnClose ){ + gQuota.pOrigVfs->xDelete(gQuota.pOrigVfs, pFile->zFilename, 0); + quotaRemoveFile(pFile); + } + quotaGroupDeref(pGroup); + } + quotaLeave(); + } +#if SQLITE_OS_WIN + quota_mbcs_free(p->zMbcsName); +#endif + sqlite3_free(p); + return rc; +} + +/* +** Flush memory buffers for a quota_FILE to disk. +*/ +int sqlite3_quota_fflush(quota_FILE *p, int doFsync){ + int rc; + rc = fflush(p->f); + if( rc==0 && doFsync ){ +#if SQLITE_OS_UNIX + rc = fsync(fileno(p->f)); +#endif +#if SQLITE_OS_WIN + rc = _commit(_fileno(p->f)); +#endif + } + return rc!=0; +} + +/* +** Seek on a quota_FILE stream. +*/ +int sqlite3_quota_fseek(quota_FILE *p, long offset, int whence){ + return fseek(p->f, offset, whence); +} + +/* +** rewind a quota_FILE stream. +*/ +void sqlite3_quota_rewind(quota_FILE *p){ + rewind(p->f); +} + +/* +** Tell the current location of a quota_FILE stream. +*/ +long sqlite3_quota_ftell(quota_FILE *p){ + return ftell(p->f); +} + +/* +** Test the error indicator for the given file. +*/ +int sqlite3_quota_ferror(quota_FILE *p){ + return ferror(p->f); +} + +/* +** Truncate a file to szNew bytes. +*/ +int sqlite3_quota_ftruncate(quota_FILE *p, sqlite3_int64 szNew){ + quotaFile *pFile = p->pFile; + int rc; + if( (pFile = p->pFile)!=0 && pFile->iSizeiSizepGroup; + quotaEnter(); + pGroup->iSize += szNew - pFile->iSize; + quotaLeave(); + } +#if SQLITE_OS_UNIX + rc = ftruncate(fileno(p->f), szNew); +#endif +#if SQLITE_OS_WIN +# if defined(__MINGW32__) && defined(SQLITE_TEST) + /* _chsize_s() is missing from MingW (as of 2012-11-06). Use + ** _chsize() as a work-around for testing purposes. */ + rc = _chsize(_fileno(p->f), (long)szNew); +# else + rc = _chsize_s(_fileno(p->f), szNew); +# endif +#endif + if( pFile && rc==0 ){ + quotaGroup *pGroup = pFile->pGroup; + quotaEnter(); + pGroup->iSize += szNew - pFile->iSize; + pFile->iSize = szNew; + quotaLeave(); + } + return rc; +} + +/* +** Determine the time that the given file was last modified, in +** seconds size 1970. Write the result into *pTime. Return 0 on +** success and non-zero on any kind of error. +*/ +int sqlite3_quota_file_mtime(quota_FILE *p, time_t *pTime){ + int rc; +#if SQLITE_OS_UNIX + struct stat buf; + rc = fstat(fileno(p->f), &buf); +#endif +#if SQLITE_OS_WIN + struct _stati64 buf; + rc = _stati64(p->zMbcsName, &buf); +#endif + if( rc==0 ) *pTime = buf.st_mtime; + return rc; +} + +/* +** Return the true size of the file, as reported by the operating +** system. +*/ +sqlite3_int64 sqlite3_quota_file_truesize(quota_FILE *p){ + int rc; +#if SQLITE_OS_UNIX + struct stat buf; + rc = fstat(fileno(p->f), &buf); +#endif +#if SQLITE_OS_WIN + struct _stati64 buf; + rc = _stati64(p->zMbcsName, &buf); +#endif + return rc==0 ? buf.st_size : -1; +} + +/* +** Return the size of the file, as it is known to the quota subsystem. +*/ +sqlite3_int64 sqlite3_quota_file_size(quota_FILE *p){ + return p->pFile ? p->pFile->iSize : -1; +} + +/* +** Determine the amount of data in bytes available for reading +** in the given file. +*/ +long sqlite3_quota_file_available(quota_FILE *p){ + FILE* f = p->f; + long pos1, pos2; + int rc; + pos1 = ftell(f); + if ( pos1 < 0 ) return -1; + rc = fseek(f, 0, SEEK_END); + if ( rc != 0 ) return -1; + pos2 = ftell(f); + if ( pos2 < 0 ) return -1; + rc = fseek(f, pos1, SEEK_SET); + if ( rc != 0 ) return -1; + return pos2 - pos1; +} + +/* +** Remove a managed file. Update quotas accordingly. +*/ +int sqlite3_quota_remove(const char *zFilename){ + char *zFull; /* Full pathname for zFilename */ + size_t nFull; /* Number of bytes in zFilename */ + int rc; /* Result code */ + quotaGroup *pGroup; /* Group containing zFilename */ + quotaFile *pFile; /* A file in the group */ + quotaFile *pNextFile; /* next file in the group */ + int diff; /* Difference between filenames */ + char c; /* First character past end of pattern */ + + zFull = (char*)sqlite3_malloc(gQuota.sThisVfs.mxPathname + 1); + if( zFull==0 ) return SQLITE_NOMEM; + rc = gQuota.pOrigVfs->xFullPathname(gQuota.pOrigVfs, zFilename, + gQuota.sThisVfs.mxPathname+1, zFull); + if( rc ){ + sqlite3_free(zFull); + return rc; + } + + /* Figure out the length of the full pathname. If the name ends with + ** / (or \ on windows) then remove the trailing /. + */ + nFull = strlen(zFull); + if( nFull>0 && (zFull[nFull-1]=='/' || zFull[nFull-1]=='\\') ){ + nFull--; + zFull[nFull] = 0; + } + + quotaEnter(); + pGroup = quotaGroupFind(zFull); + if( pGroup ){ + for(pFile=pGroup->pFiles; pFile && rc==SQLITE_OK; pFile=pNextFile){ + pNextFile = pFile->pNext; + diff = strncmp(zFull, pFile->zFilename, nFull); + if( diff==0 && ((c = pFile->zFilename[nFull])==0 || c=='/' || c=='\\') ){ + if( pFile->nRef ){ + pFile->deleteOnClose = 1; + }else{ + rc = gQuota.pOrigVfs->xDelete(gQuota.pOrigVfs, pFile->zFilename, 0); + quotaRemoveFile(pFile); + quotaGroupDeref(pGroup); + } + } + } + } + quotaLeave(); + sqlite3_free(zFull); + return rc; +} + +/***************************** Test Code ***********************************/ +#ifdef SQLITE_TEST +#include + +/* +** Argument passed to a TCL quota-over-limit callback. +*/ +typedef struct TclQuotaCallback TclQuotaCallback; +struct TclQuotaCallback { + Tcl_Interp *interp; /* Interpreter in which to run the script */ + Tcl_Obj *pScript; /* Script to be run */ +}; + +extern const char *sqlite3ErrName(int); + + +/* +** This is the callback from a quota-over-limit. +*/ +static void tclQuotaCallback( + const char *zFilename, /* Name of file whose size increases */ + sqlite3_int64 *piLimit, /* IN/OUT: The current limit */ + sqlite3_int64 iSize, /* Total size of all files in the group */ + void *pArg /* Client data */ +){ + TclQuotaCallback *p; /* Callback script object */ + Tcl_Obj *pEval; /* Script to evaluate */ + Tcl_Obj *pVarname; /* Name of variable to pass as 2nd arg */ + unsigned int rnd; /* Random part of pVarname */ + int rc; /* Tcl error code */ + + p = (TclQuotaCallback *)pArg; + if( p==0 ) return; + + pVarname = Tcl_NewStringObj("::piLimit_", -1); + Tcl_IncrRefCount(pVarname); + sqlite3_randomness(sizeof(rnd), (void *)&rnd); + Tcl_AppendObjToObj(pVarname, Tcl_NewIntObj((int)(rnd&0x7FFFFFFF))); + Tcl_ObjSetVar2(p->interp, pVarname, 0, Tcl_NewWideIntObj(*piLimit), 0); + + pEval = Tcl_DuplicateObj(p->pScript); + Tcl_IncrRefCount(pEval); + Tcl_ListObjAppendElement(0, pEval, Tcl_NewStringObj(zFilename, -1)); + Tcl_ListObjAppendElement(0, pEval, pVarname); + Tcl_ListObjAppendElement(0, pEval, Tcl_NewWideIntObj(iSize)); + rc = Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL); + + if( rc==TCL_OK ){ + Tcl_WideInt x; + Tcl_Obj *pLimit = Tcl_ObjGetVar2(p->interp, pVarname, 0, 0); + rc = Tcl_GetWideIntFromObj(p->interp, pLimit, &x); + *piLimit = x; + Tcl_UnsetVar(p->interp, Tcl_GetString(pVarname), 0); + } + + Tcl_DecrRefCount(pEval); + Tcl_DecrRefCount(pVarname); + if( rc!=TCL_OK ) Tcl_BackgroundError(p->interp); +} + +/* +** Destructor for a TCL quota-over-limit callback. +*/ +static void tclCallbackDestructor(void *pObj){ + TclQuotaCallback *p = (TclQuotaCallback*)pObj; + if( p ){ + Tcl_DecrRefCount(p->pScript); + sqlite3_free((char *)p); + } +} + +/* +** tclcmd: sqlite3_quota_initialize NAME MAKEDEFAULT +*/ +static int test_quota_initialize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zName; /* Name of new quota VFS */ + int makeDefault; /* True to make the new VFS the default */ + int rc; /* Value returned by quota_initialize() */ + + /* Process arguments */ + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "NAME MAKEDEFAULT"); + return TCL_ERROR; + } + zName = Tcl_GetString(objv[1]); + if( Tcl_GetBooleanFromObj(interp, objv[2], &makeDefault) ) return TCL_ERROR; + if( zName[0]=='\0' ) zName = 0; + + /* Call sqlite3_quota_initialize() */ + rc = sqlite3_quota_initialize(zName, makeDefault); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_shutdown +*/ +static int test_quota_shutdown( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int rc; /* Value returned by quota_shutdown() */ + + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + + /* Call sqlite3_quota_shutdown() */ + rc = sqlite3_quota_shutdown(); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_set PATTERN LIMIT SCRIPT +*/ +static int test_quota_set( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zPattern; /* File pattern to configure */ + Tcl_WideInt iLimit; /* Initial quota in bytes */ + Tcl_Obj *pScript; /* Tcl script to invoke to increase quota */ + int rc; /* Value returned by quota_set() */ + TclQuotaCallback *p; /* Callback object */ + int nScript; /* Length of callback script */ + void (*xDestroy)(void*); /* Optional destructor for pArg */ + void (*xCallback)(const char *, sqlite3_int64 *, sqlite3_int64, void *); + + /* Process arguments */ + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PATTERN LIMIT SCRIPT"); + return TCL_ERROR; + } + zPattern = Tcl_GetString(objv[1]); + if( Tcl_GetWideIntFromObj(interp, objv[2], &iLimit) ) return TCL_ERROR; + pScript = objv[3]; + Tcl_GetStringFromObj(pScript, &nScript); + + if( nScript>0 ){ + /* Allocate a TclQuotaCallback object */ + p = (TclQuotaCallback *)sqlite3_malloc(sizeof(TclQuotaCallback)); + if( !p ){ + Tcl_SetResult(interp, (char *)"SQLITE_NOMEM", TCL_STATIC); + return TCL_OK; + } + memset(p, 0, sizeof(TclQuotaCallback)); + p->interp = interp; + Tcl_IncrRefCount(pScript); + p->pScript = pScript; + xDestroy = tclCallbackDestructor; + xCallback = tclQuotaCallback; + }else{ + p = 0; + xDestroy = 0; + xCallback = 0; + } + + /* Invoke sqlite3_quota_set() */ + rc = sqlite3_quota_set(zPattern, iLimit, xCallback, (void*)p, xDestroy); + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file FILENAME +*/ +static int test_quota_file( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; /* File pattern to configure */ + int rc; /* Value returned by quota_file() */ + + /* Process arguments */ + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } + zFilename = Tcl_GetString(objv[1]); + + /* Invoke sqlite3_quota_file() */ + rc = sqlite3_quota_file(zFilename); + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_dump +*/ +static int test_quota_dump( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Obj *pResult; + Tcl_Obj *pGroupTerm; + Tcl_Obj *pFileTerm; + quotaGroup *pGroup; + quotaFile *pFile; + + pResult = Tcl_NewObj(); + quotaEnter(); + for(pGroup=gQuota.pGroup; pGroup; pGroup=pGroup->pNext){ + pGroupTerm = Tcl_NewObj(); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewStringObj(pGroup->zPattern, -1)); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewWideIntObj(pGroup->iLimit)); + Tcl_ListObjAppendElement(interp, pGroupTerm, + Tcl_NewWideIntObj(pGroup->iSize)); + for(pFile=pGroup->pFiles; pFile; pFile=pFile->pNext){ + int i; + char zTemp[1000]; + pFileTerm = Tcl_NewObj(); + sqlite3_snprintf(sizeof(zTemp), zTemp, "%s", pFile->zFilename); + for(i=0; zTemp[i]; i++){ if( zTemp[i]=='\\' ) zTemp[i] = '/'; } + Tcl_ListObjAppendElement(interp, pFileTerm, + Tcl_NewStringObj(zTemp, -1)); + Tcl_ListObjAppendElement(interp, pFileTerm, + Tcl_NewWideIntObj(pFile->iSize)); + Tcl_ListObjAppendElement(interp, pFileTerm, + Tcl_NewWideIntObj(pFile->nRef)); + Tcl_ListObjAppendElement(interp, pFileTerm, + Tcl_NewWideIntObj(pFile->deleteOnClose)); + Tcl_ListObjAppendElement(interp, pGroupTerm, pFileTerm); + } + Tcl_ListObjAppendElement(interp, pResult, pGroupTerm); + } + quotaLeave(); + Tcl_SetObjResult(interp, pResult); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fopen FILENAME MODE +*/ +static int test_quota_fopen( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; /* File pattern to configure */ + const char *zMode; /* Mode string */ + quota_FILE *p; /* Open string object */ + char zReturn[50]; /* Name of pointer to return */ + + /* Process arguments */ + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME MODE"); + return TCL_ERROR; + } + zFilename = Tcl_GetString(objv[1]); + zMode = Tcl_GetString(objv[2]); + p = sqlite3_quota_fopen(zFilename, zMode); + sqlite3_snprintf(sizeof(zReturn), zReturn, "%p", p); + Tcl_SetResult(interp, zReturn, TCL_VOLATILE); + return TCL_OK; +} + +/* Defined in test1.c */ +extern void *sqlite3TestTextToPtr(const char*); + +/* +** tclcmd: sqlite3_quota_fread HANDLE SIZE NELEM +*/ +static int test_quota_fread( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + char *zBuf; + int sz; + int nElem; + size_t got; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE SIZE NELEM"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( Tcl_GetIntFromObj(interp, objv[2], &sz) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &nElem) ) return TCL_ERROR; + zBuf = (char*)sqlite3_malloc( sz*nElem + 1 ); + if( zBuf==0 ){ + Tcl_SetResult(interp, "out of memory", TCL_STATIC); + return TCL_ERROR; + } + got = sqlite3_quota_fread(zBuf, sz, nElem, p); + zBuf[got*sz] = 0; + Tcl_SetResult(interp, zBuf, TCL_VOLATILE); + sqlite3_free(zBuf); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fwrite HANDLE SIZE NELEM CONTENT +*/ +static int test_quota_fwrite( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + char *zBuf; + int sz; + int nElem; + size_t got; + + if( objc!=5 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE SIZE NELEM CONTENT"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( Tcl_GetIntFromObj(interp, objv[2], &sz) ) return TCL_ERROR; + if( Tcl_GetIntFromObj(interp, objv[3], &nElem) ) return TCL_ERROR; + zBuf = Tcl_GetString(objv[4]); + got = sqlite3_quota_fwrite(zBuf, sz, nElem, p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(got)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fclose HANDLE +*/ +static int test_quota_fclose( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + rc = sqlite3_quota_fclose(p); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fflush HANDLE ?HARDSYNC? +*/ +static int test_quota_fflush( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + int rc; + int doSync = 0; + + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE ?HARDSYNC?"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( objc==3 ){ + if( Tcl_GetBooleanFromObj(interp, objv[2], &doSync) ) return TCL_ERROR; + } + rc = sqlite3_quota_fflush(p, doSync); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_fseek HANDLE OFFSET WHENCE +*/ +static int test_quota_fseek( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + int ofst; + const char *zWhence; + int whence; + int rc; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE OFFSET WHENCE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( Tcl_GetIntFromObj(interp, objv[2], &ofst) ) return TCL_ERROR; + zWhence = Tcl_GetString(objv[3]); + if( strcmp(zWhence, "SEEK_SET")==0 ){ + whence = SEEK_SET; + }else if( strcmp(zWhence, "SEEK_CUR")==0 ){ + whence = SEEK_CUR; + }else if( strcmp(zWhence, "SEEK_END")==0 ){ + whence = SEEK_END; + }else{ + Tcl_AppendResult(interp, + "WHENCE should be SEEK_SET, SEEK_CUR, or SEEK_END", (char*)0); + return TCL_ERROR; + } + rc = sqlite3_quota_fseek(p, ofst, whence); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_rewind HANDLE +*/ +static int test_quota_rewind( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + sqlite3_quota_rewind(p); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_ftell HANDLE +*/ +static int test_quota_ftell( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_ftell(p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(x)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_ftruncate HANDLE SIZE +*/ +static int test_quota_ftruncate( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + Tcl_WideInt w; + int rc; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE SIZE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + if( Tcl_GetWideIntFromObj(interp, objv[2], &w) ) return TCL_ERROR; + x = (sqlite3_int64)w; + rc = sqlite3_quota_ftruncate(p, x); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file_size HANDLE +*/ +static int test_quota_file_size( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_file_size(p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(x)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file_truesize HANDLE +*/ +static int test_quota_file_truesize( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_file_truesize(p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(x)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file_mtime HANDLE +*/ +static int test_quota_file_mtime( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + time_t t; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + t = 0; + sqlite3_quota_file_mtime(p, &t); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(t)); + return TCL_OK; +} + + +/* +** tclcmd: sqlite3_quota_remove FILENAME +*/ +static int test_quota_remove( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zFilename; /* File pattern to configure */ + int rc; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "FILENAME"); + return TCL_ERROR; + } + zFilename = Tcl_GetString(objv[1]); + rc = sqlite3_quota_remove(zFilename); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_glob PATTERN TEXT +** +** Test the glob pattern matching. Return 1 if TEXT matches PATTERN +** and return 0 if it does not. +*/ +static int test_quota_glob( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zPattern; /* The glob pattern */ + const char *zText; /* Text to compare agains the pattern */ + int rc; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 1, objv, "PATTERN TEXT"); + return TCL_ERROR; + } + zPattern = Tcl_GetString(objv[1]); + zText = Tcl_GetString(objv[2]); + rc = quotaStrglob(zPattern, zText); + Tcl_SetObjResult(interp, Tcl_NewIntObj(rc)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_file_available HANDLE +** +** Return the number of bytes from the current file point to the end of +** the file. +*/ +static int test_quota_file_available( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + sqlite3_int64 x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_file_available(p); + Tcl_SetObjResult(interp, Tcl_NewWideIntObj(x)); + return TCL_OK; +} + +/* +** tclcmd: sqlite3_quota_ferror HANDLE +** +** Return true if the file handle is in the error state. +*/ +static int test_quota_ferror( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + quota_FILE *p; + int x; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "HANDLE"); + return TCL_ERROR; + } + p = sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + x = sqlite3_quota_ferror(p); + Tcl_SetObjResult(interp, Tcl_NewIntObj(x)); + return TCL_OK; +} + +/* +** This routine registers the custom TCL commands defined in this +** module. This should be the only procedure visible from outside +** of this module. +*/ +int Sqlitequota_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + } aCmd[] = { + { "sqlite3_quota_initialize", test_quota_initialize }, + { "sqlite3_quota_shutdown", test_quota_shutdown }, + { "sqlite3_quota_set", test_quota_set }, + { "sqlite3_quota_file", test_quota_file }, + { "sqlite3_quota_dump", test_quota_dump }, + { "sqlite3_quota_fopen", test_quota_fopen }, + { "sqlite3_quota_fread", test_quota_fread }, + { "sqlite3_quota_fwrite", test_quota_fwrite }, + { "sqlite3_quota_fclose", test_quota_fclose }, + { "sqlite3_quota_fflush", test_quota_fflush }, + { "sqlite3_quota_fseek", test_quota_fseek }, + { "sqlite3_quota_rewind", test_quota_rewind }, + { "sqlite3_quota_ftell", test_quota_ftell }, + { "sqlite3_quota_ftruncate", test_quota_ftruncate }, + { "sqlite3_quota_file_size", test_quota_file_size }, + { "sqlite3_quota_file_truesize", test_quota_file_truesize }, + { "sqlite3_quota_file_mtime", test_quota_file_mtime }, + { "sqlite3_quota_remove", test_quota_remove }, + { "sqlite3_quota_glob", test_quota_glob }, + { "sqlite3_quota_file_available",test_quota_file_available }, + { "sqlite3_quota_ferror", test_quota_ferror }, + }; + int i; + + for(i=0; i +#include +#include +#if SQLITE_OS_UNIX +# include +#endif +#if SQLITE_OS_WIN +# include +#endif + +/* Make this callable from C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Initialize the quota VFS shim. Use the VFS named zOrigVfsName +** as the VFS that does the actual work. Use the default if +** zOrigVfsName==NULL. +** +** The quota VFS shim is named "quota". It will become the default +** VFS if makeDefault is non-zero. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once +** during start-up. +*/ +int sqlite3_quota_initialize(const char *zOrigVfsName, int makeDefault); + +/* +** Shutdown the quota system. +** +** All SQLite database connections must be closed before calling this +** routine. +** +** THIS ROUTINE IS NOT THREADSAFE. Call this routine exactly once while +** shutting down in order to free all remaining quota groups. +*/ +int sqlite3_quota_shutdown(void); + +/* +** Create or destroy a quota group. +** +** The quota group is defined by the zPattern. When calling this routine +** with a zPattern for a quota group that already exists, this routine +** merely updates the iLimit, xCallback, and pArg values for that quota +** group. If zPattern is new, then a new quota group is created. +** +** The zPattern is always compared against the full pathname of the file. +** Even if APIs are called with relative pathnames, SQLite converts the +** name to a full pathname before comparing it against zPattern. zPattern +** is a glob pattern with the following matching rules: +** +** '*' Matches any sequence of zero or more characters. +** +** '?' Matches exactly one character. +** +** [...] Matches one character from the enclosed list of +** characters. "]" can be part of the list if it is +** the first character. Within the list "X-Y" matches +** characters X or Y or any character in between the +** two. Ex: "[0-9]" matches any digit. +** +** [^...] Matches one character not in the enclosed list. +** +** / Matches either / or \. This allows glob patterns +** containing / to work on both unix and windows. +** +** Note that, unlike unix shell globbing, the directory separator "/" +** can match a wildcard. So, for example, the pattern "/abc/xyz/" "*" +** matches any files anywhere in the directory hierarchy beneath +** /abc/xyz. +** +** The glob algorithm works on bytes. Multi-byte UTF8 characters are +** matched as if each byte were a separate character. +** +** If the iLimit for a quota group is set to zero, then the quota group +** is disabled and will be deleted when the last database connection using +** the quota group is closed. +** +** Calling this routine on a zPattern that does not exist and with a +** zero iLimit is a no-op. +** +** A quota group must exist with a non-zero iLimit prior to opening +** database connections if those connections are to participate in the +** quota group. Creating a quota group does not affect database connections +** that are already open. +** +** The patterns that define the various quota groups should be distinct. +** If the same filename matches more than one quota group pattern, then +** the behavior of this package is undefined. +*/ +int sqlite3_quota_set( + const char *zPattern, /* The filename pattern */ + sqlite3_int64 iLimit, /* New quota to set for this quota group */ + void (*xCallback)( /* Callback invoked when going over quota */ + const char *zFilename, /* Name of file whose size increases */ + sqlite3_int64 *piLimit, /* IN/OUT: The current limit */ + sqlite3_int64 iSize, /* Total size of all files in the group */ + void *pArg /* Client data */ + ), + void *pArg, /* client data passed thru to callback */ + void (*xDestroy)(void*) /* Optional destructor for pArg */ +); + +/* +** Bring the named file under quota management, assuming its name matches +** the glob pattern of some quota group. Or if it is already under +** management, update its size. If zFilename does not match the glob +** pattern of any quota group, this routine is a no-op. +*/ +int sqlite3_quota_file(const char *zFilename); + +/* +** The following object serves the same role as FILE in the standard C +** library. It represents an open connection to a file on disk for I/O. +** +** A single quota_FILE should not be used by two or more threads at the +** same time. Multiple threads can be using different quota_FILE objects +** simultaneously, but not the same quota_FILE object. +*/ +typedef struct quota_FILE quota_FILE; + +/* +** Create a new quota_FILE object used to read and/or write to the +** file zFilename. The zMode parameter is as with standard library zMode. +*/ +quota_FILE *sqlite3_quota_fopen(const char *zFilename, const char *zMode); + +/* +** Perform I/O against a quota_FILE object. When doing writes, the +** quota mechanism may result in a short write, in order to prevent +** the sum of sizes of all files from going over quota. +*/ +size_t sqlite3_quota_fread(void*, size_t, size_t, quota_FILE*); +size_t sqlite3_quota_fwrite(const void*, size_t, size_t, quota_FILE*); + +/* +** Flush all written content held in memory buffers out to disk. +** This is the equivalent of fflush() in the standard library. +** +** If the hardSync parameter is true (non-zero) then this routine +** also forces OS buffers to disk - the equivalent of fsync(). +** +** This routine return zero on success and non-zero if something goes +** wrong. +*/ +int sqlite3_quota_fflush(quota_FILE*, int hardSync); + +/* +** Close a quota_FILE object and free all associated resources. The +** file remains under quota management. +*/ +int sqlite3_quota_fclose(quota_FILE*); + +/* +** Move the read/write pointer for a quota_FILE object. Or tell the +** current location of the read/write pointer. +*/ +int sqlite3_quota_fseek(quota_FILE*, long, int); +void sqlite3_quota_rewind(quota_FILE*); +long sqlite3_quota_ftell(quota_FILE*); + +/* +** Test the error indicator for the given file. +** +** Return non-zero if the error indicator is set. +*/ +int sqlite3_quota_ferror(quota_FILE*); + +/* +** Truncate a file previously opened by sqlite3_quota_fopen(). Return +** zero on success and non-zero on any kind of failure. +** +** The newSize argument must be less than or equal to the current file size. +** Any attempt to "truncate" a file to a larger size results in +** undefined behavior. +*/ +int sqlite3_quota_ftruncate(quota_FILE*, sqlite3_int64 newSize); + +/* +** Return the last modification time of the opened file, in seconds +** since 1970. +*/ +int sqlite3_quota_file_mtime(quota_FILE*, time_t *pTime); + +/* +** Return the size of the file as it is known to the quota system. +** +** This size might be different from the true size of the file on +** disk if some outside process has modified the file without using the +** quota mechanism, or if calls to sqlite3_quota_fwrite() have occurred +** which have increased the file size, but those writes have not yet been +** forced to disk using sqlite3_quota_fflush(). +** +** Return -1 if the file is not participating in quota management. +*/ +sqlite3_int64 sqlite3_quota_file_size(quota_FILE*); + +/* +** Return the true size of the file. +** +** The true size should be the same as the size of the file as known +** to the quota system, however the sizes might be different if the +** file has been extended or truncated via some outside process or if +** pending writes have not yet been flushed to disk. +** +** Return -1 if the file does not exist or if the size of the file +** cannot be determined for some reason. +*/ +sqlite3_int64 sqlite3_quota_file_truesize(quota_FILE*); + +/* +** Determine the amount of data in bytes available for reading +** in the given file. +** +** Return -1 if the amount cannot be determined for some reason. +*/ +long sqlite3_quota_file_available(quota_FILE*); + +/* +** Delete a file from the disk, if that file is under quota management. +** Adjust quotas accordingly. +** +** If zFilename is the name of a directory that matches one of the +** quota glob patterns, then all files under quota management that +** are contained within that directory are deleted. +** +** A standard SQLite result code is returned (SQLITE_OK, SQLITE_NOMEM, etc.) +** When deleting a directory of files, if the deletion of any one +** file fails (for example due to an I/O error), then this routine +** returns immediately, with the error code, and does not try to +** delete any of the other files in the specified directory. +** +** All files are removed from quota management and deleted from disk. +** However, no attempt is made to remove empty directories. +** +** This routine is a no-op for files that are not under quota management. +*/ +int sqlite3_quota_remove(const char *zFilename); + +#ifdef __cplusplus +} /* end of the 'extern "C"' block */ +#endif +#endif /* _QUOTA_H_ */ diff --git a/components/external/SQLite-3.8.1/src/test_rtree.c b/components/external/SQLite-3.8.1/src/test_rtree.c new file mode 100644 index 0000000000000000000000000000000000000000..e1966c243736b1c773c6fa515bdcee85063fbe57 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_rtree.c @@ -0,0 +1,305 @@ +/* +** 2010 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing all sorts of SQLite interfaces. This code +** is not included in the SQLite library. +*/ + +#include +#include + +/* Solely for the UNUSED_PARAMETER() macro. */ +#include "sqliteInt.h" + +#ifdef SQLITE_ENABLE_RTREE +/* +** Type used to cache parameter information for the "circle" r-tree geometry +** callback. +*/ +typedef struct Circle Circle; +struct Circle { + struct Box { + double xmin; + double xmax; + double ymin; + double ymax; + } aBox[2]; + double centerx; + double centery; + double radius; +}; + +/* +** Destructor function for Circle objects allocated by circle_geom(). +*/ +static void circle_del(void *p){ + sqlite3_free(p); +} + +/* +** Implementation of "circle" r-tree geometry callback. +*/ +static int circle_geom( + sqlite3_rtree_geometry *p, + int nCoord, +#ifdef SQLITE_RTREE_INT_ONLY + sqlite3_int64 *aCoord, +#else + double *aCoord, +#endif + int *pRes +){ + int i; /* Iterator variable */ + Circle *pCircle; /* Structure defining circular region */ + double xmin, xmax; /* X dimensions of box being tested */ + double ymin, ymax; /* X dimensions of box being tested */ + + if( p->pUser==0 ){ + /* If pUser is still 0, then the parameter values have not been tested + ** for correctness or stored into a Circle structure yet. Do this now. */ + + /* This geometry callback is for use with a 2-dimensional r-tree table. + ** Return an error if the table does not have exactly 2 dimensions. */ + if( nCoord!=4 ) return SQLITE_ERROR; + + /* Test that the correct number of parameters (3) have been supplied, + ** and that the parameters are in range (that the radius of the circle + ** radius is greater than zero). */ + if( p->nParam!=3 || p->aParam[2]<0.0 ) return SQLITE_ERROR; + + /* Allocate a structure to cache parameter data in. Return SQLITE_NOMEM + ** if the allocation fails. */ + pCircle = (Circle *)(p->pUser = sqlite3_malloc(sizeof(Circle))); + if( !pCircle ) return SQLITE_NOMEM; + p->xDelUser = circle_del; + + /* Record the center and radius of the circular region. One way that + ** tested bounding boxes that intersect the circular region are detected + ** is by testing if each corner of the bounding box lies within radius + ** units of the center of the circle. */ + pCircle->centerx = p->aParam[0]; + pCircle->centery = p->aParam[1]; + pCircle->radius = p->aParam[2]; + + /* Define two bounding box regions. The first, aBox[0], extends to + ** infinity in the X dimension. It covers the same range of the Y dimension + ** as the circular region. The second, aBox[1], extends to infinity in + ** the Y dimension and is constrained to the range of the circle in the + ** X dimension. + ** + ** Then imagine each box is split in half along its short axis by a line + ** that intersects the center of the circular region. A bounding box + ** being tested can be said to intersect the circular region if it contains + ** points from each half of either of the two infinite bounding boxes. + */ + pCircle->aBox[0].xmin = pCircle->centerx; + pCircle->aBox[0].xmax = pCircle->centerx; + pCircle->aBox[0].ymin = pCircle->centery + pCircle->radius; + pCircle->aBox[0].ymax = pCircle->centery - pCircle->radius; + pCircle->aBox[1].xmin = pCircle->centerx + pCircle->radius; + pCircle->aBox[1].xmax = pCircle->centerx - pCircle->radius; + pCircle->aBox[1].ymin = pCircle->centery; + pCircle->aBox[1].ymax = pCircle->centery; + } + + pCircle = (Circle *)p->pUser; + xmin = aCoord[0]; + xmax = aCoord[1]; + ymin = aCoord[2]; + ymax = aCoord[3]; + + /* Check if any of the 4 corners of the bounding-box being tested lie + ** inside the circular region. If they do, then the bounding-box does + ** intersect the region of interest. Set the output variable to true and + ** return SQLITE_OK in this case. */ + for(i=0; i<4; i++){ + double x = (i&0x01) ? xmax : xmin; + double y = (i&0x02) ? ymax : ymin; + double d2; + + d2 = (x-pCircle->centerx)*(x-pCircle->centerx); + d2 += (y-pCircle->centery)*(y-pCircle->centery); + if( d2<(pCircle->radius*pCircle->radius) ){ + *pRes = 1; + return SQLITE_OK; + } + } + + /* Check if the bounding box covers any other part of the circular region. + ** See comments above for a description of how this test works. If it does + ** cover part of the circular region, set the output variable to true + ** and return SQLITE_OK. */ + for(i=0; i<2; i++){ + if( xmin<=pCircle->aBox[i].xmin + && xmax>=pCircle->aBox[i].xmax + && ymin<=pCircle->aBox[i].ymin + && ymax>=pCircle->aBox[i].ymax + ){ + *pRes = 1; + return SQLITE_OK; + } + } + + /* The specified bounding box does not intersect the circular region. Set + ** the output variable to zero and return SQLITE_OK. */ + *pRes = 0; + return SQLITE_OK; +} + +/* END of implementation of "circle" geometry callback. +************************************************************************** +*************************************************************************/ + +#include +#include "tcl.h" + +typedef struct Cube Cube; +struct Cube { + double x; + double y; + double z; + double width; + double height; + double depth; +}; + +static void cube_context_free(void *p){ + sqlite3_free(p); +} + +/* +** The context pointer registered along with the 'cube' callback is +** always ((void *)&gHere). This is just to facilitate testing, it is not +** actually used for anything. +*/ +static int gHere = 42; + +/* +** Implementation of a simple r-tree geom callback to test for intersection +** of r-tree rows with a "cube" shape. Cubes are defined by six scalar +** coordinates as follows: +** +** cube(x, y, z, width, height, depth) +** +** The width, height and depth parameters must all be greater than zero. +*/ +static int cube_geom( + sqlite3_rtree_geometry *p, + int nCoord, +#ifdef SQLITE_RTREE_INT_ONLY + sqlite3_int64 *aCoord, +#else + double *aCoord, +#endif + int *piRes +){ + Cube *pCube = (Cube *)p->pUser; + + assert( p->pContext==(void *)&gHere ); + + if( pCube==0 ){ + if( p->nParam!=6 || nCoord!=6 + || p->aParam[3]<=0.0 || p->aParam[4]<=0.0 || p->aParam[5]<=0.0 + ){ + return SQLITE_ERROR; + } + pCube = (Cube *)sqlite3_malloc(sizeof(Cube)); + if( !pCube ){ + return SQLITE_NOMEM; + } + pCube->x = p->aParam[0]; + pCube->y = p->aParam[1]; + pCube->z = p->aParam[2]; + pCube->width = p->aParam[3]; + pCube->height = p->aParam[4]; + pCube->depth = p->aParam[5]; + + p->pUser = (void *)pCube; + p->xDelUser = cube_context_free; + } + + assert( nCoord==6 ); + *piRes = 0; + if( aCoord[0]<=(pCube->x+pCube->width) + && aCoord[1]>=pCube->x + && aCoord[2]<=(pCube->y+pCube->height) + && aCoord[3]>=pCube->y + && aCoord[4]<=(pCube->z+pCube->depth) + && aCoord[5]>=pCube->z + ){ + *piRes = 1; + } + + return SQLITE_OK; +} +#endif /* SQLITE_ENABLE_RTREE */ + +static int register_cube_geom( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_ENABLE_RTREE + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(interp); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); +#else + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + extern const char *sqlite3ErrName(int); + sqlite3 *db; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_rtree_geometry_callback(db, "cube", cube_geom, (void *)&gHere); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); +#endif + return TCL_OK; +} + +static int register_circle_geom( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifndef SQLITE_ENABLE_RTREE + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(interp); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); +#else + extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**); + extern const char *sqlite3ErrName(int); + sqlite3 *db; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + rc = sqlite3_rtree_geometry_callback(db, "circle", circle_geom, 0); + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC); +#endif + return TCL_OK; +} + +int Sqlitetestrtree_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "register_cube_geom", register_cube_geom, 0, 0); + Tcl_CreateObjCommand(interp, "register_circle_geom",register_circle_geom,0,0); + return TCL_OK; +} diff --git a/components/external/SQLite-3.8.1/src/test_schema.c b/components/external/SQLite-3.8.1/src/test_schema.c new file mode 100644 index 0000000000000000000000000000000000000000..00a9f4dd903baf64fa27ab1ebe223a8a80d6bee0 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_schema.c @@ -0,0 +1,362 @@ +/* +** 2006 June 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Code for testing the virtual table interfaces. This code +** is not included in the SQLite library. It is used for automated +** testing of the SQLite library. +*/ + +/* The code in this file defines a sqlite3 virtual-table module that +** provides a read-only view of the current database schema. There is one +** row in the schema table for each column in the database schema. +*/ +#define SCHEMA \ +"CREATE TABLE x(" \ + "database," /* Name of database (i.e. main, temp etc.) */ \ + "tablename," /* Name of table */ \ + "cid," /* Column number (from left-to-right, 0 upward) */ \ + "name," /* Column name */ \ + "type," /* Specified type (i.e. VARCHAR(32)) */ \ + "not_null," /* Boolean. True if NOT NULL was specified */ \ + "dflt_value," /* Default value for this column */ \ + "pk" /* True if this column is part of the primary key */ \ +")" + +/* If SQLITE_TEST is defined this code is preprocessed for use as part +** of the sqlite test binary "testfixture". Otherwise it is preprocessed +** to be compiled into an sqlite dynamic extension. +*/ +#ifdef SQLITE_TEST + #include "sqliteInt.h" + #include "tcl.h" +#else + #include "sqlite3ext.h" + SQLITE_EXTENSION_INIT1 +#endif + +#include +#include +#include + +typedef struct schema_vtab schema_vtab; +typedef struct schema_cursor schema_cursor; + +/* A schema table object */ +struct schema_vtab { + sqlite3_vtab base; + sqlite3 *db; +}; + +/* A schema table cursor object */ +struct schema_cursor { + sqlite3_vtab_cursor base; + sqlite3_stmt *pDbList; + sqlite3_stmt *pTableList; + sqlite3_stmt *pColumnList; + int rowid; +}; + +/* +** None of this works unless we have virtual tables. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Table destructor for the schema module. +*/ +static int schemaDestroy(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return 0; +} + +/* +** Table constructor for the schema module. +*/ +static int schemaCreate( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int rc = SQLITE_NOMEM; + schema_vtab *pVtab = sqlite3_malloc(sizeof(schema_vtab)); + if( pVtab ){ + memset(pVtab, 0, sizeof(schema_vtab)); + pVtab->db = db; +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = sqlite3_declare_vtab(db, SCHEMA); +#endif + } + *ppVtab = (sqlite3_vtab *)pVtab; + return rc; +} + +/* +** Open a new cursor on the schema table. +*/ +static int schemaOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + int rc = SQLITE_NOMEM; + schema_cursor *pCur; + pCur = sqlite3_malloc(sizeof(schema_cursor)); + if( pCur ){ + memset(pCur, 0, sizeof(schema_cursor)); + *ppCursor = (sqlite3_vtab_cursor *)pCur; + rc = SQLITE_OK; + } + return rc; +} + +/* +** Close a schema table cursor. +*/ +static int schemaClose(sqlite3_vtab_cursor *cur){ + schema_cursor *pCur = (schema_cursor *)cur; + sqlite3_finalize(pCur->pDbList); + sqlite3_finalize(pCur->pTableList); + sqlite3_finalize(pCur->pColumnList); + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Retrieve a column of data. +*/ +static int schemaColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + schema_cursor *pCur = (schema_cursor *)cur; + switch( i ){ + case 0: + sqlite3_result_value(ctx, sqlite3_column_value(pCur->pDbList, 1)); + break; + case 1: + sqlite3_result_value(ctx, sqlite3_column_value(pCur->pTableList, 0)); + break; + default: + sqlite3_result_value(ctx, sqlite3_column_value(pCur->pColumnList, i-2)); + break; + } + return SQLITE_OK; +} + +/* +** Retrieve the current rowid. +*/ +static int schemaRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + schema_cursor *pCur = (schema_cursor *)cur; + *pRowid = pCur->rowid; + return SQLITE_OK; +} + +static int finalize(sqlite3_stmt **ppStmt){ + int rc = sqlite3_finalize(*ppStmt); + *ppStmt = 0; + return rc; +} + +static int schemaEof(sqlite3_vtab_cursor *cur){ + schema_cursor *pCur = (schema_cursor *)cur; + return (pCur->pDbList ? 0 : 1); +} + +/* +** Advance the cursor to the next row. +*/ +static int schemaNext(sqlite3_vtab_cursor *cur){ + int rc = SQLITE_OK; + schema_cursor *pCur = (schema_cursor *)cur; + schema_vtab *pVtab = (schema_vtab *)(cur->pVtab); + char *zSql = 0; + + while( !pCur->pColumnList || SQLITE_ROW!=sqlite3_step(pCur->pColumnList) ){ + if( SQLITE_OK!=(rc = finalize(&pCur->pColumnList)) ) goto next_exit; + + while( !pCur->pTableList || SQLITE_ROW!=sqlite3_step(pCur->pTableList) ){ + if( SQLITE_OK!=(rc = finalize(&pCur->pTableList)) ) goto next_exit; + + assert(pCur->pDbList); + while( SQLITE_ROW!=sqlite3_step(pCur->pDbList) ){ + rc = finalize(&pCur->pDbList); + goto next_exit; + } + + /* Set zSql to the SQL to pull the list of tables from the + ** sqlite_master (or sqlite_temp_master) table of the database + ** identfied by the row pointed to by the SQL statement pCur->pDbList + ** (iterating through a "PRAGMA database_list;" statement). + */ + if( sqlite3_column_int(pCur->pDbList, 0)==1 ){ + zSql = sqlite3_mprintf( + "SELECT name FROM sqlite_temp_master WHERE type='table'" + ); + }else{ + sqlite3_stmt *pDbList = pCur->pDbList; + zSql = sqlite3_mprintf( + "SELECT name FROM %Q.sqlite_master WHERE type='table'", + sqlite3_column_text(pDbList, 1) + ); + } + if( !zSql ){ + rc = SQLITE_NOMEM; + goto next_exit; + } + + rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pTableList, 0); + sqlite3_free(zSql); + if( rc!=SQLITE_OK ) goto next_exit; + } + + /* Set zSql to the SQL to the table_info pragma for the table currently + ** identified by the rows pointed to by statements pCur->pDbList and + ** pCur->pTableList. + */ + zSql = sqlite3_mprintf("PRAGMA %Q.table_info(%Q)", + sqlite3_column_text(pCur->pDbList, 1), + sqlite3_column_text(pCur->pTableList, 0) + ); + + if( !zSql ){ + rc = SQLITE_NOMEM; + goto next_exit; + } + rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pColumnList, 0); + sqlite3_free(zSql); + if( rc!=SQLITE_OK ) goto next_exit; + } + pCur->rowid++; + +next_exit: + /* TODO: Handle rc */ + return rc; +} + +/* +** Reset a schema table cursor. +*/ +static int schemaFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + int rc; + schema_vtab *pVtab = (schema_vtab *)(pVtabCursor->pVtab); + schema_cursor *pCur = (schema_cursor *)pVtabCursor; + pCur->rowid = 0; + finalize(&pCur->pTableList); + finalize(&pCur->pColumnList); + finalize(&pCur->pDbList); + rc = sqlite3_prepare(pVtab->db,"PRAGMA database_list", -1, &pCur->pDbList, 0); + return (rc==SQLITE_OK ? schemaNext(pVtabCursor) : rc); +} + +/* +** Analyse the WHERE condition. +*/ +static int schemaBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + return SQLITE_OK; +} + +/* +** A virtual table module that merely echos method calls into TCL +** variables. +*/ +static sqlite3_module schemaModule = { + 0, /* iVersion */ + schemaCreate, + schemaCreate, + schemaBestIndex, + schemaDestroy, + schemaDestroy, + schemaOpen, /* xOpen - open a cursor */ + schemaClose, /* xClose - close a cursor */ + schemaFilter, /* xFilter - configure scan constraints */ + schemaNext, /* xNext - advance a cursor */ + schemaEof, /* xEof */ + schemaColumn, /* xColumn - read data */ + schemaRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ + +#ifdef SQLITE_TEST + +/* +** Decode a pointer to an sqlite3 object. +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); + +/* +** Register the schema virtual table module. +*/ +static int register_schema_module( + ClientData clientData, /* Not used */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_create_module(db, "schema", &schemaModule, 0); +#endif + return TCL_OK; +} + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetestschema_Init(Tcl_Interp *interp){ + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "register_schema_module", register_schema_module, 0 }, + }; + int i; + for(i=0; i +#include "sqlite3.h" + +/* +** Messages are passed from client to server and back again as +** instances of the following structure. +*/ +typedef struct SqlMessage SqlMessage; +struct SqlMessage { + int op; /* Opcode for the message */ + sqlite3 *pDb; /* The SQLite connection */ + sqlite3_stmt *pStmt; /* A specific statement */ + int errCode; /* Error code returned */ + const char *zIn; /* Input filename or SQL statement */ + int nByte; /* Size of the zIn parameter for prepare() */ + const char *zOut; /* Tail of the SQL statement */ + SqlMessage *pNext; /* Next message in the queue */ + SqlMessage *pPrev; /* Previous message in the queue */ + pthread_mutex_t clientMutex; /* Hold this mutex to access the message */ + pthread_cond_t clientWakeup; /* Signal to wake up the client */ +}; + +/* +** Legal values for SqlMessage.op +*/ +#define MSG_Open 1 /* sqlite3_open(zIn, &pDb) */ +#define MSG_Prepare 2 /* sqlite3_prepare(pDb, zIn, nByte, &pStmt, &zOut) */ +#define MSG_Step 3 /* sqlite3_step(pStmt) */ +#define MSG_Reset 4 /* sqlite3_reset(pStmt) */ +#define MSG_Finalize 5 /* sqlite3_finalize(pStmt) */ +#define MSG_Close 6 /* sqlite3_close(pDb) */ +#define MSG_Done 7 /* Server has finished with this message */ + + +/* +** State information about the server is stored in a static variable +** named "g" as follows: +*/ +static struct ServerState { + pthread_mutex_t queueMutex; /* Hold this mutex to access the msg queue */ + pthread_mutex_t serverMutex; /* Held by the server while it is running */ + pthread_cond_t serverWakeup; /* Signal this condvar to wake up the server */ + volatile int serverHalt; /* Server halts itself when true */ + SqlMessage *pQueueHead; /* Head of the message queue */ + SqlMessage *pQueueTail; /* Tail of the message queue */ +} g = { + PTHREAD_MUTEX_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER, + PTHREAD_COND_INITIALIZER, +}; + +/* +** Send a message to the server. Block until we get a reply. +** +** The mutex and condition variable in the message are uninitialized +** when this routine is called. This routine takes care of +** initializing them and destroying them when it has finished. +*/ +static void sendToServer(SqlMessage *pMsg){ + /* Initialize the mutex and condition variable on the message + */ + pthread_mutex_init(&pMsg->clientMutex, 0); + pthread_cond_init(&pMsg->clientWakeup, 0); + + /* Add the message to the head of the server's message queue. + */ + pthread_mutex_lock(&g.queueMutex); + pMsg->pNext = g.pQueueHead; + if( g.pQueueHead==0 ){ + g.pQueueTail = pMsg; + }else{ + g.pQueueHead->pPrev = pMsg; + } + pMsg->pPrev = 0; + g.pQueueHead = pMsg; + pthread_mutex_unlock(&g.queueMutex); + + /* Signal the server that the new message has be queued, then + ** block waiting for the server to process the message. + */ + pthread_mutex_lock(&pMsg->clientMutex); + pthread_cond_signal(&g.serverWakeup); + while( pMsg->op!=MSG_Done ){ + pthread_cond_wait(&pMsg->clientWakeup, &pMsg->clientMutex); + } + pthread_mutex_unlock(&pMsg->clientMutex); + + /* Destroy the mutex and condition variable of the message. + */ + pthread_mutex_destroy(&pMsg->clientMutex); + pthread_cond_destroy(&pMsg->clientWakeup); +} + +/* +** The following 6 routines are client-side implementations of the +** core SQLite interfaces: +** +** sqlite3_open +** sqlite3_prepare +** sqlite3_step +** sqlite3_reset +** sqlite3_finalize +** sqlite3_close +** +** Clients should use the following client-side routines instead of +** the core routines above. +** +** sqlite3_client_open +** sqlite3_client_prepare +** sqlite3_client_step +** sqlite3_client_reset +** sqlite3_client_finalize +** sqlite3_client_close +** +** Each of these routines creates a message for the desired operation, +** sends that message to the server, waits for the server to process +** then message and return a response. +*/ +int sqlite3_client_open(const char *zDatabaseName, sqlite3 **ppDb){ + SqlMessage msg; + msg.op = MSG_Open; + msg.zIn = zDatabaseName; + sendToServer(&msg); + *ppDb = msg.pDb; + return msg.errCode; +} +int sqlite3_client_prepare( + sqlite3 *pDb, + const char *zSql, + int nByte, + sqlite3_stmt **ppStmt, + const char **pzTail +){ + SqlMessage msg; + msg.op = MSG_Prepare; + msg.pDb = pDb; + msg.zIn = zSql; + msg.nByte = nByte; + sendToServer(&msg); + *ppStmt = msg.pStmt; + if( pzTail ) *pzTail = msg.zOut; + return msg.errCode; +} +int sqlite3_client_step(sqlite3_stmt *pStmt){ + SqlMessage msg; + msg.op = MSG_Step; + msg.pStmt = pStmt; + sendToServer(&msg); + return msg.errCode; +} +int sqlite3_client_reset(sqlite3_stmt *pStmt){ + SqlMessage msg; + msg.op = MSG_Reset; + msg.pStmt = pStmt; + sendToServer(&msg); + return msg.errCode; +} +int sqlite3_client_finalize(sqlite3_stmt *pStmt){ + SqlMessage msg; + msg.op = MSG_Finalize; + msg.pStmt = pStmt; + sendToServer(&msg); + return msg.errCode; +} +int sqlite3_client_close(sqlite3 *pDb){ + SqlMessage msg; + msg.op = MSG_Close; + msg.pDb = pDb; + sendToServer(&msg); + return msg.errCode; +} + +/* +** This routine implements the server. To start the server, first +** make sure g.serverHalt is false, then create a new detached thread +** on this procedure. See the sqlite3_server_start() routine below +** for an example. This procedure loops until g.serverHalt becomes +** true. +*/ +void *sqlite3_server(void *NotUsed){ + if( pthread_mutex_trylock(&g.serverMutex) ){ + return 0; /* Another server is already running */ + } + sqlite3_enable_shared_cache(1); + while( !g.serverHalt ){ + SqlMessage *pMsg; + + /* Remove the last message from the message queue. + */ + pthread_mutex_lock(&g.queueMutex); + while( g.pQueueTail==0 && g.serverHalt==0 ){ + pthread_cond_wait(&g.serverWakeup, &g.queueMutex); + } + pMsg = g.pQueueTail; + if( pMsg ){ + if( pMsg->pPrev ){ + pMsg->pPrev->pNext = 0; + }else{ + g.pQueueHead = 0; + } + g.pQueueTail = pMsg->pPrev; + } + pthread_mutex_unlock(&g.queueMutex); + if( pMsg==0 ) break; + + /* Process the message just removed + */ + pthread_mutex_lock(&pMsg->clientMutex); + switch( pMsg->op ){ + case MSG_Open: { + pMsg->errCode = sqlite3_open(pMsg->zIn, &pMsg->pDb); + break; + } + case MSG_Prepare: { + pMsg->errCode = sqlite3_prepare(pMsg->pDb, pMsg->zIn, pMsg->nByte, + &pMsg->pStmt, &pMsg->zOut); + break; + } + case MSG_Step: { + pMsg->errCode = sqlite3_step(pMsg->pStmt); + break; + } + case MSG_Reset: { + pMsg->errCode = sqlite3_reset(pMsg->pStmt); + break; + } + case MSG_Finalize: { + pMsg->errCode = sqlite3_finalize(pMsg->pStmt); + break; + } + case MSG_Close: { + pMsg->errCode = sqlite3_close(pMsg->pDb); + break; + } + } + + /* Signal the client that the message has been processed. + */ + pMsg->op = MSG_Done; + pthread_mutex_unlock(&pMsg->clientMutex); + pthread_cond_signal(&pMsg->clientWakeup); + } + pthread_mutex_unlock(&g.serverMutex); + return 0; +} + +/* +** Start a server thread if one is not already running. If there +** is aleady a server thread running, the new thread will quickly +** die and this routine is effectively a no-op. +*/ +void sqlite3_server_start(void){ + pthread_t x; + int rc; + g.serverHalt = 0; + rc = pthread_create(&x, 0, sqlite3_server, 0); + if( rc==0 ){ + pthread_detach(x); + } +} + +/* +** A wrapper around sqlite3_server() that decrements the int variable +** pointed to by the first argument after the sqlite3_server() call +** returns. +*/ +static void *serverWrapper(void *pnDecr){ + void *p = sqlite3_server(0); + (*(int*)pnDecr)--; + return p; +} + +/* +** This function is the similar to sqlite3_server_start(), except that +** the integer pointed to by the first argument is decremented when +** the server thread exits. +*/ +void sqlite3_server_start2(int *pnDecr){ + pthread_t x; + int rc; + g.serverHalt = 0; + rc = pthread_create(&x, 0, serverWrapper, (void*)pnDecr); + if( rc==0 ){ + pthread_detach(x); + } +} + +/* +** If a server thread is running, then stop it. If no server is +** running, this routine is effectively a no-op. +** +** This routine waits until the server has actually stopped before +** returning. +*/ +void sqlite3_server_stop(void){ + g.serverHalt = 1; + pthread_cond_broadcast(&g.serverWakeup); + pthread_mutex_lock(&g.serverMutex); + pthread_mutex_unlock(&g.serverMutex); +} + +#endif /* SQLITE_OS_UNIX && SQLITE_THREADSAFE */ +#endif /* defined(SQLITE_SERVER) */ diff --git a/components/external/SQLite-3.8.1/src/test_sqllog.c b/components/external/SQLite-3.8.1/src/test_sqllog.c new file mode 100644 index 0000000000000000000000000000000000000000..4aa68b7c429323b8eebe6c9c2d07fc660d8d47c9 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_sqllog.c @@ -0,0 +1,507 @@ +/* +** 2012 November 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** OVERVIEW +** +** This file contains experimental code used to record data from live +** SQLite applications that may be useful for offline analysis. +** Specifically, this module can be used to capture the following +** information: +** +** 1) The initial contents of all database files opened by the +** application, and +** +** 2) All SQL statements executed by the application. +** +** The captured information can then be used to run (for example) +** performance analysis looking for slow queries or to look for +** optimization opportunities in either the application or in SQLite +** itself. +** +** USAGE +** +** To use this module, SQLite must be compiled with the SQLITE_ENABLE_SQLLOG +** pre-processor symbol defined and this file linked into the application. +** One way to link this file into the application is to append the content +** of this file onto the end of the "sqlite3.c" amalgamation and then +** recompile the application as normal except with the addition of the +** -DSQLITE_ENABLE_SQLLOG option. +** +** At runtime, logging is enabled by setting environment variable +** SQLITE_SQLLOG_DIR to the name of a directory in which to store logged +** data. The logging directory must already exist. +** +** Usually, if the application opens the same database file more than once +** (either by attaching it or by using more than one database handle), only +** a single copy is made. This behavior may be overridden (so that a +** separate copy is taken each time the database file is opened or attached) +** by setting the environment variable SQLITE_SQLLOG_REUSE_FILES to 0. +** +** OUTPUT: +** +** The SQLITE_SQLLOG_DIR is populated with three types of files: +** +** sqllog_N.db - Copies of database files. N may be any integer. +** +** sqllog_N.sql - A list of SQL statements executed by a single +** connection. N may be any integer. +** +** sqllog.idx - An index mapping from integer N to a database +** file name - indicating the full path of the +** database from which sqllog_N.db was copied. +** +** ERROR HANDLING: +** +** This module attempts to make a best effort to continue logging if an +** IO or other error is encountered. For example, if a log file cannot +** be opened logs are not collected for that connection, but other +** logging proceeds as expected. Errors are logged by calling sqlite3_log(). +*/ + +#ifndef _SQLITE3_H_ +#include "sqlite3.h" +#endif +#include +#include +#include +#include + +#include +#include +static int getProcessId(void){ +#if SQLITE_OS_WIN + return (int)_getpid(); +#else + return (int)getpid(); +#endif +} + +/* Names of environment variables to be used */ +#define ENVIRONMENT_VARIABLE1_NAME "SQLITE_SQLLOG_DIR" +#define ENVIRONMENT_VARIABLE2_NAME "SQLITE_SQLLOG_REUSE_FILES" + +/* Assume that all database and database file names are shorted than this. */ +#define SQLLOG_NAMESZ 512 + +/* Maximum number of simultaneous database connections the process may +** open (if any more are opened an error is logged using sqlite3_log() +** and processing is halted). +*/ +#define MAX_CONNECTIONS 256 + +/* There is one instance of this object for each SQLite database connection +** that is being logged. +*/ +struct SLConn { + int isErr; /* True if an error has occurred */ + sqlite3 *db; /* Connection handle */ + int iLog; /* First integer value used in file names */ + FILE *fd; /* File descriptor for log file */ +}; + +/* This object is a singleton that keeps track of all data loggers. +*/ +static struct SLGlobal { + /* Protected by MUTEX_STATIC_MASTER */ + sqlite3_mutex *mutex; /* Recursive mutex */ + int nConn; /* Size of aConn[] array */ + + /* Protected by SLGlobal.mutex */ + int bReuse; /* True to avoid extra copies of db files */ + char zPrefix[SQLLOG_NAMESZ]; /* Prefix for all created files */ + char zIdx[SQLLOG_NAMESZ]; /* Full path to *.idx file */ + int iNextLog; /* Used to allocate file names */ + int iNextDb; /* Used to allocate database file names */ + int bRec; /* True if testSqllog() is called rec. */ + int iClock; /* Clock value */ + struct SLConn aConn[MAX_CONNECTIONS]; +} sqllogglobal; + +/* +** Return true if c is an ASCII whitespace character. +*/ +static int sqllog_isspace(char c){ + return (c==' ' || c=='\t' || c=='\n' || c=='\v' || c=='\f' || c=='\r'); +} + +/* +** The first argument points to a nul-terminated string containing an SQL +** command. Before returning, this function sets *pz to point to the start +** of the first token in this command, and *pn to the number of bytes in +** the token. This is used to check if the SQL command is an "ATTACH" or +** not. +*/ +static void sqllogTokenize(const char *z, const char **pz, int *pn){ + const char *p = z; + int n; + + /* Skip past any whitespace */ + while( sqllog_isspace(*p) ){ + p++; + } + + /* Figure out how long the first token is */ + *pz = p; + n = 0; + while( (p[n]>='a' && p[n]<='z') || (p[n]>='A' && p[n]<='Z') ) n++; + *pn = n; +} + +/* +** Check if the logs directory already contains a copy of database file +** zFile. If so, return a pointer to the full path of the copy. Otherwise, +** return NULL. +** +** If a non-NULL value is returned, then the caller must arrange to +** eventually free it using sqlite3_free(). +*/ +static char *sqllogFindFile(const char *zFile){ + char *zRet = 0; + FILE *fd = 0; + + /* Open the index file for reading */ + fd = fopen(sqllogglobal.zIdx, "r"); + if( fd==0 ){ + sqlite3_log(SQLITE_IOERR, "sqllogFindFile(): error in fopen()"); + return 0; + } + + /* Loop through each entry in the index file. If zFile is not NULL and the + ** entry is a match, then set zRet to point to the filename of the existing + ** copy and break out of the loop. */ + while( feof(fd)==0 ){ + char zLine[SQLLOG_NAMESZ*2+5]; + if( fgets(zLine, sizeof(zLine), fd) ){ + int n; + char *z; + + zLine[sizeof(zLine)-1] = '\0'; + z = zLine; + while( *z>='0' && *z<='9' ) z++; + while( *z==' ' ) z++; + + n = strlen(z); + while( n>0 && sqllog_isspace(z[n-1]) ) n--; + + if( n==strlen(zFile) && 0==memcmp(zFile, z, n) ){ + char zBuf[16]; + memset(zBuf, 0, sizeof(zBuf)); + z = zLine; + while( *z>='0' && *z<='9' ){ + zBuf[z-zLine] = *z; + z++; + } + zRet = sqlite3_mprintf("%s_%s.db", sqllogglobal.zPrefix, zBuf); + break; + } + } + } + + if( ferror(fd) ){ + sqlite3_log(SQLITE_IOERR, "sqllogFindFile(): error reading index file"); + } + + fclose(fd); + return zRet; +} + +static int sqllogFindAttached( + struct SLConn *p, /* Database connection */ + const char *zSearch, /* Name to search for (or NULL) */ + char *zName, /* OUT: Name of attached database */ + char *zFile /* OUT: Name of attached file */ +){ + sqlite3_stmt *pStmt; + int rc; + + /* The "PRAGMA database_list" command returns a list of databases in the + ** order that they were attached. So a newly attached database is + ** described by the last row returned. */ + assert( sqllogglobal.bRec==0 ); + sqllogglobal.bRec = 1; + rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); + if( rc==SQLITE_OK ){ + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + const char *zVal1; int nVal1; + const char *zVal2; int nVal2; + + zVal1 = (const char*)sqlite3_column_text(pStmt, 1); + nVal1 = sqlite3_column_bytes(pStmt, 1); + memcpy(zName, zVal1, nVal1+1); + + zVal2 = (const char*)sqlite3_column_text(pStmt, 2); + nVal2 = sqlite3_column_bytes(pStmt, 2); + memcpy(zFile, zVal2, nVal2+1); + + if( zSearch && strlen(zSearch)==nVal1 + && 0==sqlite3_strnicmp(zSearch, zVal1, nVal1) + ){ + break; + } + } + rc = sqlite3_finalize(pStmt); + } + sqllogglobal.bRec = 0; + + if( rc!=SQLITE_OK ){ + sqlite3_log(rc, "sqllogFindAttached(): error in \"PRAGMA database_list\""); + } + return rc; +} + + +/* +** Parameter zSearch is the name of a database attached to the database +** connection associated with the first argument. This function creates +** a backup of this database in the logs directory. +** +** The name used for the backup file is automatically generated. Call +** it zFile. +** +** If the bLog parameter is true, then a statement of the following form +** is written to the log file associated with *p: +** +** ATTACH 'zFile' AS 'zName'; +** +** Otherwise, if bLog is false, a comment is added to the log file: +** +** -- Main database file is 'zFile' +** +** The SLGlobal.mutex mutex is always held when this function is called. +*/ +static void sqllogCopydb(struct SLConn *p, const char *zSearch, int bLog){ + char zName[SQLLOG_NAMESZ]; /* Attached database name */ + char zFile[SQLLOG_NAMESZ]; /* Database file name */ + char *zFree; + char *zInit = 0; + int rc; + + rc = sqllogFindAttached(p, zSearch, zName, zFile); + if( rc!=SQLITE_OK ) return; + + if( zFile[0]=='\0' ){ + zInit = sqlite3_mprintf(""); + }else{ + if( sqllogglobal.bReuse ){ + zInit = sqllogFindFile(zFile); + }else{ + zInit = 0; + } + if( zInit==0 ){ + int rc; + sqlite3 *copy = 0; + int iDb; + + /* Generate a file-name to use for the copy of this database */ + iDb = sqllogglobal.iNextDb++; + zInit = sqlite3_mprintf("%s_%d.db", sqllogglobal.zPrefix, iDb); + + /* Create the backup */ + assert( sqllogglobal.bRec==0 ); + sqllogglobal.bRec = 1; + rc = sqlite3_open(zInit, ©); + if( rc==SQLITE_OK ){ + sqlite3_backup *pBak; + sqlite3_exec(copy, "PRAGMA synchronous = 0", 0, 0, 0); + pBak = sqlite3_backup_init(copy, "main", p->db, zName); + if( pBak ){ + sqlite3_backup_step(pBak, -1); + rc = sqlite3_backup_finish(pBak); + }else{ + rc = sqlite3_errcode(copy); + } + sqlite3_close(copy); + } + sqllogglobal.bRec = 0; + + if( rc==SQLITE_OK ){ + /* Write an entry into the database index file */ + FILE *fd = fopen(sqllogglobal.zIdx, "a"); + if( fd ){ + fprintf(fd, "%d %s\n", iDb, zFile); + fclose(fd); + } + }else{ + sqlite3_log(rc, "sqllogCopydb(): error backing up database"); + } + } + } + + if( bLog ){ + zFree = sqlite3_mprintf("ATTACH '%q' AS '%q'; -- clock=%d\n", + zInit, zName, sqllogglobal.iClock++ + ); + }else{ + zFree = sqlite3_mprintf("-- Main database is '%q'\n", zInit); + } + fprintf(p->fd, "%s", zFree); + sqlite3_free(zFree); + + sqlite3_free(zInit); +} + +/* +** If it is not already open, open the log file for connection *p. +** +** The SLGlobal.mutex mutex is always held when this function is called. +*/ +static void sqllogOpenlog(struct SLConn *p){ + /* If the log file has not yet been opened, open it now. */ + if( p->fd==0 ){ + char *zLog; + + /* If it is still NULL, have global.zPrefix point to a copy of + ** environment variable $ENVIRONMENT_VARIABLE1_NAME. */ + if( sqllogglobal.zPrefix[0]==0 ){ + FILE *fd; + char *zVar = getenv(ENVIRONMENT_VARIABLE1_NAME); + if( zVar==0 || strlen(zVar)+10>=(sizeof(sqllogglobal.zPrefix)) ) return; + sprintf(sqllogglobal.zPrefix, "%s/sqllog_%d", zVar, getProcessId()); + sprintf(sqllogglobal.zIdx, "%s.idx", sqllogglobal.zPrefix); + if( getenv(ENVIRONMENT_VARIABLE2_NAME) ){ + sqllogglobal.bReuse = atoi(getenv(ENVIRONMENT_VARIABLE2_NAME)); + } + fd = fopen(sqllogglobal.zIdx, "w"); + if( fd ) fclose(fd); + } + + /* Open the log file */ + zLog = sqlite3_mprintf("%s_%d.sql", sqllogglobal.zPrefix, p->iLog); + p->fd = fopen(zLog, "w"); + sqlite3_free(zLog); + if( p->fd==0 ){ + sqlite3_log(SQLITE_IOERR, "sqllogOpenlog(): Failed to open log file"); + } + } +} + +/* +** This function is called if the SQLLOG callback is invoked to report +** execution of an SQL statement. Parameter p is the connection the statement +** was executed by and parameter zSql is the text of the statement itself. +*/ +static void testSqllogStmt(struct SLConn *p, const char *zSql){ + const char *zFirst; /* Pointer to first token in zSql */ + int nFirst; /* Size of token zFirst in bytes */ + + sqllogTokenize(zSql, &zFirst, &nFirst); + if( nFirst!=6 || 0!=sqlite3_strnicmp("ATTACH", zFirst, 6) ){ + /* Not an ATTACH statement. Write this directly to the log. */ + fprintf(p->fd, "%s; -- clock=%d\n", zSql, sqllogglobal.iClock++); + }else{ + /* This is an ATTACH statement. Copy the database. */ + sqllogCopydb(p, 0, 1); + } +} + +/* +** The SQLITE_CONFIG_SQLLOG callback registered by sqlite3_init_sqllog(). +** +** The eType parameter has the following values: +** +** 0: Opening a new database connection. zSql is the name of the +** file being opened. db is a pointer to the newly created database +** connection. +** +** 1: An SQL statement has run to completion. zSql is the text of the +** SQL statement with all parameters expanded to their actual values. +** +** 2: Closing a database connection. zSql is NULL. The db pointer to +** the database connection being closed has already been shut down +** and cannot be used for any further SQL. +** +** The pCtx parameter is a copy of the pointer that was originally passed +** into the sqlite3_config(SQLITE_CONFIG_SQLLOG) statement. In this +** particular implementation, pCtx is always a pointer to the +** sqllogglobal global variable define above. +*/ +static void testSqllog(void *pCtx, sqlite3 *db, const char *zSql, int eType){ + struct SLConn *p = 0; + sqlite3_mutex *master = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); + + assert( eType==0 || eType==1 || eType==2 ); + assert( (eType==2)==(zSql==0) ); + + /* This is a database open command. */ + if( eType==0 ){ + sqlite3_mutex_enter(master); + if( sqllogglobal.mutex==0 ){ + sqllogglobal.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE); + } + p = &sqllogglobal.aConn[sqllogglobal.nConn++]; + p->fd = 0; + p->db = db; + p->iLog = sqllogglobal.iNextLog++; + sqlite3_mutex_leave(master); + + /* Open the log and take a copy of the main database file */ + sqlite3_mutex_enter(sqllogglobal.mutex); + if( sqllogglobal.bRec==0 ){ + sqllogOpenlog(p); + if( p->fd ) sqllogCopydb(p, "main", 0); + } + sqlite3_mutex_leave(sqllogglobal.mutex); + } + + else{ + + int i; + for(i=0; idb==db ) break; + } + if( i==sqllogglobal.nConn ) return; + + /* A database handle close command */ + if( eType==2 ){ + sqlite3_mutex_enter(master); + if( p->fd ) fclose(p->fd); + p->db = 0; + p->fd = 0; + + sqllogglobal.nConn--; + if( sqllogglobal.nConn==0 ){ + sqlite3_mutex_free(sqllogglobal.mutex); + sqllogglobal.mutex = 0; + }else{ + int nShift = &sqllogglobal.aConn[sqllogglobal.nConn] - p; + if( nShift>0 ){ + memmove(p, &p[1], nShift*sizeof(struct SLConn)); + } + } + sqlite3_mutex_leave(master); + + /* An ordinary SQL command. */ + }else if( p->fd ){ + sqlite3_mutex_enter(sqllogglobal.mutex); + if( sqllogglobal.bRec==0 ){ + testSqllogStmt(p, zSql); + } + sqlite3_mutex_leave(sqllogglobal.mutex); + } + } +} + +/* +** This function is called either before sqlite3_initialized() or by it. +** It checks if the SQLITE_SQLLOG_DIR variable is defined, and if so +** registers an SQLITE_CONFIG_SQLLOG callback to record the applications +** database activity. +*/ +void sqlite3_init_sqllog(void){ + if( getenv(ENVIRONMENT_VARIABLE1_NAME) ){ + if( SQLITE_OK==sqlite3_config(SQLITE_CONFIG_SQLLOG, testSqllog, 0) ){ + memset(&sqllogglobal, 0, sizeof(sqllogglobal)); + sqllogglobal.bReuse = 1; + } + } +} diff --git a/components/external/SQLite-3.8.1/src/test_stat.c b/components/external/SQLite-3.8.1/src/test_stat.c new file mode 100644 index 0000000000000000000000000000000000000000..d4c902b5ea111ad58a737112c28f0038434c85c0 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_stat.c @@ -0,0 +1,639 @@ +/* +** 2010 July 12 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains an implementation of the "dbstat" virtual table. +** +** The dbstat virtual table is used to extract low-level formatting +** information from an SQLite database in order to implement the +** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script +** for an example implementation. +*/ + +#ifndef SQLITE_AMALGAMATION +# include "sqliteInt.h" +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Page paths: +** +** The value of the 'path' column describes the path taken from the +** root-node of the b-tree structure to each page. The value of the +** root-node path is '/'. +** +** The value of the path for the left-most child page of the root of +** a b-tree is '/000/'. (Btrees store content ordered from left to right +** so the pages to the left have smaller keys than the pages to the right.) +** The next to left-most child of the root page is +** '/001', and so on, each sibling page identified by a 3-digit hex +** value. The children of the 451st left-most sibling have paths such +** as '/1c2/000/, '/1c2/001/' etc. +** +** Overflow pages are specified by appending a '+' character and a +** six-digit hexadecimal value to the path to the cell they are linked +** from. For example, the three overflow pages in a chain linked from +** the left-most cell of the 450th child of the root page are identified +** by the paths: +** +** '/1c2/000+000000' // First page in overflow chain +** '/1c2/000+000001' // Second page in overflow chain +** '/1c2/000+000002' // Third page in overflow chain +** +** If the paths are sorted using the BINARY collation sequence, then +** the overflow pages associated with a cell will appear earlier in the +** sort-order than its child page: +** +** '/1c2/000/' // Left-most child of 451st child of root +*/ +#define VTAB_SCHEMA \ + "CREATE TABLE xx( " \ + " name STRING, /* Name of table or index */" \ + " path INTEGER, /* Path to page from root */" \ + " pageno INTEGER, /* Page number */" \ + " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */" \ + " ncell INTEGER, /* Cells on page (0 for overflow) */" \ + " payload INTEGER, /* Bytes of payload on this page */" \ + " unused INTEGER, /* Bytes of unused space on this page */" \ + " mx_payload INTEGER, /* Largest payload size of all cells */" \ + " pgoffset INTEGER, /* Offset of page in file */" \ + " pgsize INTEGER /* Size of the page */" \ + ");" + + +typedef struct StatTable StatTable; +typedef struct StatCursor StatCursor; +typedef struct StatPage StatPage; +typedef struct StatCell StatCell; + +struct StatCell { + int nLocal; /* Bytes of local payload */ + u32 iChildPg; /* Child node (or 0 if this is a leaf) */ + int nOvfl; /* Entries in aOvfl[] */ + u32 *aOvfl; /* Array of overflow page numbers */ + int nLastOvfl; /* Bytes of payload on final overflow page */ + int iOvfl; /* Iterates through aOvfl[] */ +}; + +struct StatPage { + u32 iPgno; + DbPage *pPg; + int iCell; + + char *zPath; /* Path to this page */ + + /* Variables populated by statDecodePage(): */ + u8 flags; /* Copy of flags byte */ + int nCell; /* Number of cells on page */ + int nUnused; /* Number of unused bytes on page */ + StatCell *aCell; /* Array of parsed cells */ + u32 iRightChildPg; /* Right-child page number (or 0) */ + int nMxPayload; /* Largest payload of any cell on this page */ +}; + +struct StatCursor { + sqlite3_vtab_cursor base; + sqlite3_stmt *pStmt; /* Iterates through set of root pages */ + int isEof; /* After pStmt has returned SQLITE_DONE */ + + StatPage aPage[32]; + int iPage; /* Current entry in aPage[] */ + + /* Values to return. */ + char *zName; /* Value of 'name' column */ + char *zPath; /* Value of 'path' column */ + u32 iPageno; /* Value of 'pageno' column */ + char *zPagetype; /* Value of 'pagetype' column */ + int nCell; /* Value of 'ncell' column */ + int nPayload; /* Value of 'payload' column */ + int nUnused; /* Value of 'unused' column */ + int nMxPayload; /* Value of 'mx_payload' column */ + i64 iOffset; /* Value of 'pgOffset' column */ + int szPage; /* Value of 'pgSize' column */ +}; + +struct StatTable { + sqlite3_vtab base; + sqlite3 *db; +}; + +#ifndef get2byte +# define get2byte(x) ((x)[0]<<8 | (x)[1]) +#endif + +/* +** Connect to or create a statvfs virtual table. +*/ +static int statConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + StatTable *pTab; + + pTab = (StatTable *)sqlite3_malloc(sizeof(StatTable)); + memset(pTab, 0, sizeof(StatTable)); + pTab->db = db; + + sqlite3_declare_vtab(db, VTAB_SCHEMA); + *ppVtab = &pTab->base; + return SQLITE_OK; +} + +/* +** Disconnect from or destroy a statvfs virtual table. +*/ +static int statDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} + +/* +** There is no "best-index". This virtual table always does a linear +** scan of the binary VFS log file. +*/ +static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + + /* Records are always returned in ascending order of (name, path). + ** If this will satisfy the client, set the orderByConsumed flag so that + ** SQLite does not do an external sort. + */ + if( ( pIdxInfo->nOrderBy==1 + && pIdxInfo->aOrderBy[0].iColumn==0 + && pIdxInfo->aOrderBy[0].desc==0 + ) || + ( pIdxInfo->nOrderBy==2 + && pIdxInfo->aOrderBy[0].iColumn==0 + && pIdxInfo->aOrderBy[0].desc==0 + && pIdxInfo->aOrderBy[1].iColumn==1 + && pIdxInfo->aOrderBy[1].desc==0 + ) + ){ + pIdxInfo->orderByConsumed = 1; + } + + pIdxInfo->estimatedCost = 10.0; + return SQLITE_OK; +} + +/* +** Open a new statvfs cursor. +*/ +static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + StatTable *pTab = (StatTable *)pVTab; + StatCursor *pCsr; + int rc; + + pCsr = (StatCursor *)sqlite3_malloc(sizeof(StatCursor)); + memset(pCsr, 0, sizeof(StatCursor)); + pCsr->base.pVtab = pVTab; + + rc = sqlite3_prepare_v2(pTab->db, + "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type" + " UNION ALL " + "SELECT name, rootpage, type FROM sqlite_master WHERE rootpage!=0" + " ORDER BY name", -1, + &pCsr->pStmt, 0 + ); + if( rc!=SQLITE_OK ){ + sqlite3_free(pCsr); + return rc; + } + + *ppCursor = (sqlite3_vtab_cursor *)pCsr; + return SQLITE_OK; +} + +static void statClearPage(StatPage *p){ + int i; + for(i=0; inCell; i++){ + sqlite3_free(p->aCell[i].aOvfl); + } + sqlite3PagerUnref(p->pPg); + sqlite3_free(p->aCell); + sqlite3_free(p->zPath); + memset(p, 0, sizeof(StatPage)); +} + +static void statResetCsr(StatCursor *pCsr){ + int i; + sqlite3_reset(pCsr->pStmt); + for(i=0; iaPage); i++){ + statClearPage(&pCsr->aPage[i]); + } + pCsr->iPage = 0; + sqlite3_free(pCsr->zPath); + pCsr->zPath = 0; +} + +/* +** Close a statvfs cursor. +*/ +static int statClose(sqlite3_vtab_cursor *pCursor){ + StatCursor *pCsr = (StatCursor *)pCursor; + statResetCsr(pCsr); + sqlite3_finalize(pCsr->pStmt); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +static void getLocalPayload( + int nUsable, /* Usable bytes per page */ + u8 flags, /* Page flags */ + int nTotal, /* Total record (payload) size */ + int *pnLocal /* OUT: Bytes stored locally */ +){ + int nLocal; + int nMinLocal; + int nMaxLocal; + + if( flags==0x0D ){ /* Table leaf node */ + nMinLocal = (nUsable - 12) * 32 / 255 - 23; + nMaxLocal = nUsable - 35; + }else{ /* Index interior and leaf nodes */ + nMinLocal = (nUsable - 12) * 32 / 255 - 23; + nMaxLocal = (nUsable - 12) * 64 / 255 - 23; + } + + nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4); + if( nLocal>nMaxLocal ) nLocal = nMinLocal; + *pnLocal = nLocal; +} + +static int statDecodePage(Btree *pBt, StatPage *p){ + int nUnused; + int iOff; + int nHdr; + int isLeaf; + int szPage; + + u8 *aData = sqlite3PagerGetData(p->pPg); + u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0]; + + p->flags = aHdr[0]; + p->nCell = get2byte(&aHdr[3]); + p->nMxPayload = 0; + + isLeaf = (p->flags==0x0A || p->flags==0x0D); + nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100; + + nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell; + nUnused += (int)aHdr[7]; + iOff = get2byte(&aHdr[1]); + while( iOff ){ + nUnused += get2byte(&aData[iOff+2]); + iOff = get2byte(&aData[iOff]); + } + p->nUnused = nUnused; + p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]); + szPage = sqlite3BtreeGetPageSize(pBt); + + if( p->nCell ){ + int i; /* Used to iterate through cells */ + int nUsable = szPage - sqlite3BtreeGetReserve(pBt); + + p->aCell = sqlite3_malloc((p->nCell+1) * sizeof(StatCell)); + memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell)); + + for(i=0; inCell; i++){ + StatCell *pCell = &p->aCell[i]; + + iOff = get2byte(&aData[nHdr+i*2]); + if( !isLeaf ){ + pCell->iChildPg = sqlite3Get4byte(&aData[iOff]); + iOff += 4; + } + if( p->flags==0x05 ){ + /* A table interior node. nPayload==0. */ + }else{ + u32 nPayload; /* Bytes of payload total (local+overflow) */ + int nLocal; /* Bytes of payload stored locally */ + iOff += getVarint32(&aData[iOff], nPayload); + if( p->flags==0x0D ){ + u64 dummy; + iOff += sqlite3GetVarint(&aData[iOff], &dummy); + } + if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload; + getLocalPayload(nUsable, p->flags, nPayload, &nLocal); + pCell->nLocal = nLocal; + assert( nLocal>=0 ); + assert( nPayload>=(u32)nLocal ); + assert( nLocal<=(nUsable-35) ); + if( nPayload>(u32)nLocal ){ + int j; + int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4); + pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4); + pCell->nOvfl = nOvfl; + pCell->aOvfl = sqlite3_malloc(sizeof(u32)*nOvfl); + pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]); + for(j=1; jaOvfl[j-1]; + DbPage *pPg = 0; + rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg); + if( rc!=SQLITE_OK ){ + assert( pPg==0 ); + return rc; + } + pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg)); + sqlite3PagerUnref(pPg); + } + } + } + } + } + + return SQLITE_OK; +} + +/* +** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on +** the current value of pCsr->iPageno. +*/ +static void statSizeAndOffset(StatCursor *pCsr){ + StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab; + Btree *pBt = pTab->db->aDb[0].pBt; + Pager *pPager = sqlite3BtreePager(pBt); + sqlite3_file *fd; + sqlite3_int64 x[2]; + + /* The default page size and offset */ + pCsr->szPage = sqlite3BtreeGetPageSize(pBt); + pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1); + + /* If connected to a ZIPVFS backend, override the page size and + ** offset with actual values obtained from ZIPVFS. + */ + fd = sqlite3PagerFile(pPager); + x[0] = pCsr->iPageno; + if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){ + pCsr->iOffset = x[0]; + pCsr->szPage = (int)x[1]; + } +} + +/* +** Move a statvfs cursor to the next entry in the file. +*/ +static int statNext(sqlite3_vtab_cursor *pCursor){ + int rc; + int nPayload; + StatCursor *pCsr = (StatCursor *)pCursor; + StatTable *pTab = (StatTable *)pCursor->pVtab; + Btree *pBt = pTab->db->aDb[0].pBt; + Pager *pPager = sqlite3BtreePager(pBt); + + sqlite3_free(pCsr->zPath); + pCsr->zPath = 0; + + if( pCsr->aPage[0].pPg==0 ){ + rc = sqlite3_step(pCsr->pStmt); + if( rc==SQLITE_ROW ){ + int nPage; + u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1); + sqlite3PagerPagecount(pPager, &nPage); + if( nPage==0 ){ + pCsr->isEof = 1; + return sqlite3_reset(pCsr->pStmt); + } + rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg); + pCsr->aPage[0].iPgno = iRoot; + pCsr->aPage[0].iCell = 0; + pCsr->aPage[0].zPath = sqlite3_mprintf("/"); + pCsr->iPage = 0; + }else{ + pCsr->isEof = 1; + return sqlite3_reset(pCsr->pStmt); + } + }else{ + + /* Page p itself has already been visited. */ + StatPage *p = &pCsr->aPage[pCsr->iPage]; + + while( p->iCellnCell ){ + StatCell *pCell = &p->aCell[p->iCell]; + if( pCell->iOvflnOvfl ){ + int nUsable = sqlite3BtreeGetPageSize(pBt)-sqlite3BtreeGetReserve(pBt); + pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0); + pCsr->iPageno = pCell->aOvfl[pCell->iOvfl]; + pCsr->zPagetype = "overflow"; + pCsr->nCell = 0; + pCsr->nMxPayload = 0; + pCsr->zPath = sqlite3_mprintf( + "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl + ); + if( pCell->iOvflnOvfl-1 ){ + pCsr->nUnused = 0; + pCsr->nPayload = nUsable - 4; + }else{ + pCsr->nPayload = pCell->nLastOvfl; + pCsr->nUnused = nUsable - 4 - pCsr->nPayload; + } + pCell->iOvfl++; + statSizeAndOffset(pCsr); + return SQLITE_OK; + } + if( p->iRightChildPg ) break; + p->iCell++; + } + + while( !p->iRightChildPg || p->iCell>p->nCell ){ + statClearPage(p); + if( pCsr->iPage==0 ) return statNext(pCursor); + pCsr->iPage--; + p = &pCsr->aPage[pCsr->iPage]; + } + pCsr->iPage++; + assert( p==&pCsr->aPage[pCsr->iPage-1] ); + + if( p->iCell==p->nCell ){ + p[1].iPgno = p->iRightChildPg; + }else{ + p[1].iPgno = p->aCell[p->iCell].iChildPg; + } + rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg); + p[1].iCell = 0; + p[1].zPath = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell); + p->iCell++; + } + + + /* Populate the StatCursor fields with the values to be returned + ** by the xColumn() and xRowid() methods. + */ + if( rc==SQLITE_OK ){ + int i; + StatPage *p = &pCsr->aPage[pCsr->iPage]; + pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0); + pCsr->iPageno = p->iPgno; + + statDecodePage(pBt, p); + statSizeAndOffset(pCsr); + + switch( p->flags ){ + case 0x05: /* table internal */ + case 0x02: /* index internal */ + pCsr->zPagetype = "internal"; + break; + case 0x0D: /* table leaf */ + case 0x0A: /* index leaf */ + pCsr->zPagetype = "leaf"; + break; + default: + pCsr->zPagetype = "corrupted"; + break; + } + pCsr->nCell = p->nCell; + pCsr->nUnused = p->nUnused; + pCsr->nMxPayload = p->nMxPayload; + pCsr->zPath = sqlite3_mprintf("%s", p->zPath); + nPayload = 0; + for(i=0; inCell; i++){ + nPayload += p->aCell[i].nLocal; + } + pCsr->nPayload = nPayload; + } + + return rc; +} + +static int statEof(sqlite3_vtab_cursor *pCursor){ + StatCursor *pCsr = (StatCursor *)pCursor; + return pCsr->isEof; +} + +static int statFilter( + sqlite3_vtab_cursor *pCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + StatCursor *pCsr = (StatCursor *)pCursor; + + statResetCsr(pCsr); + return statNext(pCursor); +} + +static int statColumn( + sqlite3_vtab_cursor *pCursor, + sqlite3_context *ctx, + int i +){ + StatCursor *pCsr = (StatCursor *)pCursor; + switch( i ){ + case 0: /* name */ + sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_STATIC); + break; + case 1: /* path */ + sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT); + break; + case 2: /* pageno */ + sqlite3_result_int64(ctx, pCsr->iPageno); + break; + case 3: /* pagetype */ + sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC); + break; + case 4: /* ncell */ + sqlite3_result_int(ctx, pCsr->nCell); + break; + case 5: /* payload */ + sqlite3_result_int(ctx, pCsr->nPayload); + break; + case 6: /* unused */ + sqlite3_result_int(ctx, pCsr->nUnused); + break; + case 7: /* mx_payload */ + sqlite3_result_int(ctx, pCsr->nMxPayload); + break; + case 8: /* pgoffset */ + sqlite3_result_int64(ctx, pCsr->iOffset); + break; + case 9: /* pgsize */ + sqlite3_result_int(ctx, pCsr->szPage); + break; + } + return SQLITE_OK; +} + +static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + StatCursor *pCsr = (StatCursor *)pCursor; + *pRowid = pCsr->iPageno; + return SQLITE_OK; +} + +int sqlite3_dbstat_register(sqlite3 *db){ + static sqlite3_module dbstat_module = { + 0, /* iVersion */ + statConnect, /* xCreate */ + statConnect, /* xConnect */ + statBestIndex, /* xBestIndex */ + statDisconnect, /* xDisconnect */ + statDisconnect, /* xDestroy */ + statOpen, /* xOpen - open a cursor */ + statClose, /* xClose - close a cursor */ + statFilter, /* xFilter - configure scan constraints */ + statNext, /* xNext - advance a cursor */ + statEof, /* xEof - check for end of scan */ + statColumn, /* xColumn - read data */ + statRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + }; + sqlite3_create_module(db, "dbstat", &dbstat_module, 0); + return SQLITE_OK; +} + +#endif + +#if defined(SQLITE_TEST) || TCLSH==2 +#include + +static int test_dbstat( + void *clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ +#ifdef SQLITE_OMIT_VIRTUALTABLE + Tcl_AppendResult(interp, "dbstat not available because of " + "SQLITE_OMIT_VIRTUALTABLE", (void*)0); + return TCL_ERROR; +#else + struct SqliteDb { sqlite3 *db; }; + char *zDb; + Tcl_CmdInfo cmdInfo; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + + zDb = Tcl_GetString(objv[1]); + if( Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){ + sqlite3* db = ((struct SqliteDb*)cmdInfo.objClientData)->db; + sqlite3_dbstat_register(db); + } + return TCL_OK; +#endif +} + +int SqlitetestStat_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "register_dbstat_vtab", test_dbstat, 0, 0); + return TCL_OK; +} +#endif /* if defined(SQLITE_TEST) || TCLSH==2 */ diff --git a/components/external/SQLite-3.8.1/src/test_superlock.c b/components/external/SQLite-3.8.1/src/test_superlock.c new file mode 100644 index 0000000000000000000000000000000000000000..936fcad0c56f6bc85809742f6ae1c1eeb8b7d2f1 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_superlock.c @@ -0,0 +1,356 @@ +/* +** 2010 November 19 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Example code for obtaining an exclusive lock on an SQLite database +** file. This method is complicated, but works for both WAL and rollback +** mode database files. The interface to the example code in this file +** consists of the following two functions: +** +** sqlite3demo_superlock() +** sqlite3demo_superunlock() +*/ + +#include +#include /* memset(), strlen() */ +#include /* assert() */ + +/* +** A structure to collect a busy-handler callback and argument and a count +** of the number of times it has been invoked. +*/ +struct SuperlockBusy { + int (*xBusy)(void*,int); /* Pointer to busy-handler function */ + void *pBusyArg; /* First arg to pass to xBusy */ + int nBusy; /* Number of times xBusy has been invoked */ +}; +typedef struct SuperlockBusy SuperlockBusy; + +/* +** An instance of the following structure is allocated for each active +** superlock. The opaque handle returned by sqlite3demo_superlock() is +** actually a pointer to an instance of this structure. +*/ +struct Superlock { + sqlite3 *db; /* Database handle used to lock db */ + int bWal; /* True if db is a WAL database */ +}; +typedef struct Superlock Superlock; + +/* +** The pCtx pointer passed to this function is actually a pointer to a +** SuperlockBusy structure. Invoke the busy-handler function encapsulated +** by the structure and return the result. +*/ +static int superlockBusyHandler(void *pCtx, int UNUSED){ + SuperlockBusy *pBusy = (SuperlockBusy *)pCtx; + if( pBusy->xBusy==0 ) return 0; + return pBusy->xBusy(pBusy->pBusyArg, pBusy->nBusy++); +} + +/* +** This function is used to determine if the main database file for +** connection db is open in WAL mode or not. If no error occurs and the +** database file is in WAL mode, set *pbWal to true and return SQLITE_OK. +** If it is not in WAL mode, set *pbWal to false. +** +** If an error occurs, return an SQLite error code. The value of *pbWal +** is undefined in this case. +*/ +static int superlockIsWal(Superlock *pLock){ + int rc; /* Return Code */ + sqlite3_stmt *pStmt; /* Compiled PRAGMA journal_mode statement */ + + rc = sqlite3_prepare(pLock->db, "PRAGMA main.journal_mode", -1, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + + pLock->bWal = 0; + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + const char *zMode = (const char *)sqlite3_column_text(pStmt, 0); + if( zMode && strlen(zMode)==3 && sqlite3_strnicmp("wal", zMode, 3)==0 ){ + pLock->bWal = 1; + } + } + + return sqlite3_finalize(pStmt); +} + +/* +** Obtain an exclusive shm-lock on nByte bytes starting at offset idx +** of the file fd. If the lock cannot be obtained immediately, invoke +** the busy-handler until either it is obtained or the busy-handler +** callback returns 0. +*/ +static int superlockShmLock( + sqlite3_file *fd, /* Database file handle */ + int idx, /* Offset of shm-lock to obtain */ + int nByte, /* Number of consective bytes to lock */ + SuperlockBusy *pBusy /* Busy-handler wrapper object */ +){ + int rc; + int (*xShmLock)(sqlite3_file*, int, int, int) = fd->pMethods->xShmLock; + do { + rc = xShmLock(fd, idx, nByte, SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE); + }while( rc==SQLITE_BUSY && superlockBusyHandler((void *)pBusy, 0) ); + return rc; +} + +/* +** Obtain the extra locks on the database file required for WAL databases. +** Invoke the supplied busy-handler as required. +*/ +static int superlockWalLock( + sqlite3 *db, /* Database handle open on WAL database */ + SuperlockBusy *pBusy /* Busy handler wrapper object */ +){ + int rc; /* Return code */ + sqlite3_file *fd = 0; /* Main database file handle */ + void volatile *p = 0; /* Pointer to first page of shared memory */ + + /* Obtain a pointer to the sqlite3_file object open on the main db file. */ + rc = sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, (void *)&fd); + if( rc!=SQLITE_OK ) return rc; + + /* Obtain the "recovery" lock. Normally, this lock is only obtained by + ** clients running database recovery. + */ + rc = superlockShmLock(fd, 2, 1, pBusy); + if( rc!=SQLITE_OK ) return rc; + + /* Zero the start of the first shared-memory page. This means that any + ** clients that open read or write transactions from this point on will + ** have to run recovery before proceeding. Since they need the "recovery" + ** lock that this process is holding to do that, no new read or write + ** transactions may now be opened. Nor can a checkpoint be run, for the + ** same reason. + */ + rc = fd->pMethods->xShmMap(fd, 0, 32*1024, 1, &p); + if( rc!=SQLITE_OK ) return rc; + memset((void *)p, 0, 32); + + /* Obtain exclusive locks on all the "read-lock" slots. Once these locks + ** are held, it is guaranteed that there are no active reader, writer or + ** checkpointer clients. + */ + rc = superlockShmLock(fd, 3, SQLITE_SHM_NLOCK-3, pBusy); + return rc; +} + +/* +** Release a superlock held on a database file. The argument passed to +** this function must have been obtained from a successful call to +** sqlite3demo_superlock(). +*/ +void sqlite3demo_superunlock(void *pLock){ + Superlock *p = (Superlock *)pLock; + if( p->bWal ){ + int rc; /* Return code */ + int flags = SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE; + sqlite3_file *fd = 0; + rc = sqlite3_file_control(p->db, "main", SQLITE_FCNTL_FILE_POINTER, (void *)&fd); + if( rc==SQLITE_OK ){ + fd->pMethods->xShmLock(fd, 2, 1, flags); + fd->pMethods->xShmLock(fd, 3, SQLITE_SHM_NLOCK-3, flags); + } + } + sqlite3_close(p->db); + sqlite3_free(p); +} + +/* +** Obtain a superlock on the database file identified by zPath, using the +** locking primitives provided by VFS zVfs. If successful, SQLITE_OK is +** returned and output variable *ppLock is populated with an opaque handle +** that may be used with sqlite3demo_superunlock() to release the lock. +** +** If an error occurs, *ppLock is set to 0 and an SQLite error code +** (e.g. SQLITE_BUSY) is returned. +** +** If a required lock cannot be obtained immediately and the xBusy parameter +** to this function is not NULL, then xBusy is invoked in the same way +** as a busy-handler registered with SQLite (using sqlite3_busy_handler()) +** until either the lock can be obtained or the busy-handler function returns +** 0 (indicating "give up"). +*/ +int sqlite3demo_superlock( + const char *zPath, /* Path to database file to lock */ + const char *zVfs, /* VFS to use to access database file */ + int (*xBusy)(void*,int), /* Busy handler callback */ + void *pBusyArg, /* Context arg for busy handler */ + void **ppLock /* OUT: Context to pass to superunlock() */ +){ + SuperlockBusy busy = {0, 0, 0}; /* Busy handler wrapper object */ + int rc; /* Return code */ + Superlock *pLock; + + pLock = sqlite3_malloc(sizeof(Superlock)); + if( !pLock ) return SQLITE_NOMEM; + memset(pLock, 0, sizeof(Superlock)); + + /* Open a database handle on the file to superlock. */ + rc = sqlite3_open_v2( + zPath, &pLock->db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs + ); + + /* Install a busy-handler and execute a BEGIN EXCLUSIVE. If this is not + ** a WAL database, this is all we need to do. + ** + ** A wrapper function is used to invoke the busy-handler instead of + ** registering the busy-handler function supplied by the user directly + ** with SQLite. This is because the same busy-handler function may be + ** invoked directly later on when attempting to obtain the extra locks + ** required in WAL mode. By using the wrapper, we are able to guarantee + ** that the "nBusy" integer parameter passed to the users busy-handler + ** represents the total number of busy-handler invocations made within + ** this call to sqlite3demo_superlock(), including any made during the + ** "BEGIN EXCLUSIVE". + */ + if( rc==SQLITE_OK ){ + busy.xBusy = xBusy; + busy.pBusyArg = pBusyArg; + sqlite3_busy_handler(pLock->db, superlockBusyHandler, (void *)&busy); + rc = sqlite3_exec(pLock->db, "BEGIN EXCLUSIVE", 0, 0, 0); + } + + /* If the BEGIN EXCLUSIVE was executed successfully and this is a WAL + ** database, call superlockWalLock() to obtain the extra locks required + ** to prevent readers, writers and/or checkpointers from accessing the + ** db while this process is holding the superlock. + ** + ** Before attempting any WAL locks, commit the transaction started above + ** to drop the WAL read and write locks currently held. Otherwise, the + ** new WAL locks may conflict with the old. + */ + if( rc==SQLITE_OK ){ + if( SQLITE_OK==(rc = superlockIsWal(pLock)) && pLock->bWal ){ + rc = sqlite3_exec(pLock->db, "COMMIT", 0, 0, 0); + if( rc==SQLITE_OK ){ + rc = superlockWalLock(pLock->db, &busy); + } + } + } + + if( rc!=SQLITE_OK ){ + sqlite3demo_superunlock(pLock); + *ppLock = 0; + }else{ + *ppLock = pLock; + } + + return rc; +} + +/* +** End of example code. Everything below here is the test harness. +************************************************************************** +************************************************************************** +*************************************************************************/ + + +#ifdef SQLITE_TEST + +#include + +struct InterpAndScript { + Tcl_Interp *interp; + Tcl_Obj *pScript; +}; +typedef struct InterpAndScript InterpAndScript; + +static void superunlock_del(ClientData cd){ + sqlite3demo_superunlock((void *)cd); +} + +static int superunlock_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + if( objc!=1 ){ + Tcl_WrongNumArgs(interp, 1, objv, ""); + return TCL_ERROR; + } + Tcl_DeleteCommand(interp, Tcl_GetString(objv[0])); + return TCL_OK; +} + +static int superlock_busy(void *pCtx, int nBusy){ + InterpAndScript *p = (InterpAndScript *)pCtx; + Tcl_Obj *pEval; /* Script to evaluate */ + int iVal = 0; /* Value to return */ + + pEval = Tcl_DuplicateObj(p->pScript); + Tcl_IncrRefCount(pEval); + Tcl_ListObjAppendElement(p->interp, pEval, Tcl_NewIntObj(nBusy)); + Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL); + Tcl_GetIntFromObj(p->interp, Tcl_GetObjResult(p->interp), &iVal); + Tcl_DecrRefCount(pEval); + + return iVal; +} + +/* +** Tclcmd: sqlite3demo_superlock CMDNAME PATH VFS BUSY-HANDLER-SCRIPT +*/ +static int superlock_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + void *pLock; /* Lock context */ + char *zPath; + char *zVfs = 0; + InterpAndScript busy = {0, 0}; + int (*xBusy)(void*,int) = 0; /* Busy handler callback */ + int rc; /* Return code from sqlite3demo_superlock() */ + + if( objc<3 || objc>5 ){ + Tcl_WrongNumArgs( + interp, 1, objv, "CMDNAME PATH ?VFS? ?BUSY-HANDLER-SCRIPT?"); + return TCL_ERROR; + } + + zPath = Tcl_GetString(objv[2]); + + if( objc>3 ){ + zVfs = Tcl_GetString(objv[3]); + if( strlen(zVfs)==0 ) zVfs = 0; + } + if( objc>4 ){ + busy.interp = interp; + busy.pScript = objv[4]; + xBusy = superlock_busy; + } + + rc = sqlite3demo_superlock(zPath, zVfs, xBusy, &busy, &pLock); + assert( rc==SQLITE_OK || pLock==0 ); + assert( rc!=SQLITE_OK || pLock!=0 ); + + if( rc!=SQLITE_OK ){ + extern const char *sqlite3ErrStr(int); + Tcl_ResetResult(interp); + Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0); + return TCL_ERROR; + } + + Tcl_CreateObjCommand( + interp, Tcl_GetString(objv[1]), superunlock_cmd, pLock, superunlock_del + ); + Tcl_SetObjResult(interp, objv[1]); + return TCL_OK; +} + +int SqliteSuperlock_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "sqlite3demo_superlock", superlock_cmd, 0, 0); + return TCL_OK; +} +#endif diff --git a/components/external/SQLite-3.8.1/src/test_syscall.c b/components/external/SQLite-3.8.1/src/test_syscall.c new file mode 100644 index 0000000000000000000000000000000000000000..7c0873c16d843202f30e2db9459fa29975ea5e68 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_syscall.c @@ -0,0 +1,705 @@ +/* +** 2011 March 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** The code in this file implements a Tcl interface used to test error +** handling in the os_unix.c module. Wrapper functions that support fault +** injection are registered as the low-level OS functions using the +** xSetSystemCall() method of the VFS. The Tcl interface is as follows: +** +** +** test_syscall install LIST +** Install wrapper functions for all system calls in argument LIST. +** LIST must be a list consisting of zero or more of the following +** literal values: +** +** open close access getcwd stat fstat +** ftruncate fcntl read pread pread64 write +** pwrite pwrite64 fchmod fallocate mmap +** +** test_syscall uninstall +** Uninstall all wrapper functions. +** +** test_syscall fault ?COUNT PERSIST? +** If [test_syscall fault] is invoked without the two arguments, fault +** injection is disabled. Otherwise, fault injection is configured to +** cause a failure on the COUNT'th next call to a system call with a +** wrapper function installed. A COUNT value of 1 means fail the next +** system call. +** +** Argument PERSIST is interpreted as a boolean. If true, the all +** system calls following the initial failure also fail. Otherwise, only +** the single transient failure is injected. +** +** test_syscall errno CALL ERRNO +** Set the value that the global "errno" is set to following a fault +** in call CALL. Argument CALL must be one of the system call names +** listed above (under [test_syscall install]). ERRNO is a symbolic +** name (i.e. "EACCES"). Not all errno codes are supported. Add extra +** to the aErrno table in function test_syscall_errno() below as +** required. +** +** test_syscall reset ?SYSTEM-CALL? +** With no argument, this is an alias for the [uninstall] command. However, +** this command uses a VFS call of the form: +** +** xSetSystemCall(pVfs, 0, 0); +** +** To restore the default system calls. The [uninstall] command restores +** each system call individually by calling (i.e.): +** +** xSetSystemCall(pVfs, "open", 0); +** +** With an argument, this command attempts to reset the system call named +** by the parameter using the same method as [uninstall]. +** +** test_syscall exists SYSTEM-CALL +** Return true if the named system call exists. Or false otherwise. +** +** test_syscall list +** Return a list of all system calls. The list is constructed using +** the xNextSystemCall() VFS method. +*/ + +#include "sqliteInt.h" +#include "sqlite3.h" +#include "tcl.h" +#include +#include +#include + +#if SQLITE_OS_UNIX + +/* From main.c */ +extern const char *sqlite3ErrName(int); + +#include +#include +#include + +static struct TestSyscallGlobal { + int bPersist; /* 1 for persistent errors, 0 for transient */ + int nCount; /* Fail after this many more calls */ + int nFail; /* Number of failures that have occurred */ +} gSyscall = { 0, 0 }; + +static int ts_open(const char *, int, int); +static int ts_close(int fd); +static int ts_access(const char *zPath, int mode); +static char *ts_getcwd(char *zPath, size_t nPath); +static int ts_stat(const char *zPath, struct stat *p); +static int ts_fstat(int fd, struct stat *p); +static int ts_ftruncate(int fd, off_t n); +static int ts_fcntl(int fd, int cmd, ... ); +static int ts_read(int fd, void *aBuf, size_t nBuf); +static int ts_pread(int fd, void *aBuf, size_t nBuf, off_t off); +static int ts_pread64(int fd, void *aBuf, size_t nBuf, off_t off); +static int ts_write(int fd, const void *aBuf, size_t nBuf); +static int ts_pwrite(int fd, const void *aBuf, size_t nBuf, off_t off); +static int ts_pwrite64(int fd, const void *aBuf, size_t nBuf, off_t off); +static int ts_fchmod(int fd, mode_t mode); +static int ts_fallocate(int fd, off_t off, off_t len); +static void *ts_mmap(void *, size_t, int, int, int, off_t); +static void *ts_mremap(void*, size_t, size_t, int, ...); + +struct TestSyscallArray { + const char *zName; + sqlite3_syscall_ptr xTest; + sqlite3_syscall_ptr xOrig; + int default_errno; /* Default value for errno following errors */ + int custom_errno; /* Current value for errno if error */ +} aSyscall[] = { + /* 0 */ { "open", (sqlite3_syscall_ptr)ts_open, 0, EACCES, 0 }, + /* 1 */ { "close", (sqlite3_syscall_ptr)ts_close, 0, 0, 0 }, + /* 2 */ { "access", (sqlite3_syscall_ptr)ts_access, 0, 0, 0 }, + /* 3 */ { "getcwd", (sqlite3_syscall_ptr)ts_getcwd, 0, 0, 0 }, + /* 4 */ { "stat", (sqlite3_syscall_ptr)ts_stat, 0, 0, 0 }, + /* 5 */ { "fstat", (sqlite3_syscall_ptr)ts_fstat, 0, 0, 0 }, + /* 6 */ { "ftruncate", (sqlite3_syscall_ptr)ts_ftruncate, 0, EIO, 0 }, + /* 7 */ { "fcntl", (sqlite3_syscall_ptr)ts_fcntl, 0, EACCES, 0 }, + /* 8 */ { "read", (sqlite3_syscall_ptr)ts_read, 0, 0, 0 }, + /* 9 */ { "pread", (sqlite3_syscall_ptr)ts_pread, 0, 0, 0 }, + /* 10 */ { "pread64", (sqlite3_syscall_ptr)ts_pread64, 0, 0, 0 }, + /* 11 */ { "write", (sqlite3_syscall_ptr)ts_write, 0, 0, 0 }, + /* 12 */ { "pwrite", (sqlite3_syscall_ptr)ts_pwrite, 0, 0, 0 }, + /* 13 */ { "pwrite64", (sqlite3_syscall_ptr)ts_pwrite64, 0, 0, 0 }, + /* 14 */ { "fchmod", (sqlite3_syscall_ptr)ts_fchmod, 0, 0, 0 }, + /* 15 */ { "fallocate", (sqlite3_syscall_ptr)ts_fallocate, 0, 0, 0 }, + /* 16 */ { "mmap", (sqlite3_syscall_ptr)ts_mmap, 0, 0, 0 }, + /* 17 */ { "mremap", (sqlite3_syscall_ptr)ts_mremap, 0, 0, 0 }, + { 0, 0, 0, 0, 0 } +}; + +#define orig_open ((int(*)(const char *, int, int))aSyscall[0].xOrig) +#define orig_close ((int(*)(int))aSyscall[1].xOrig) +#define orig_access ((int(*)(const char*,int))aSyscall[2].xOrig) +#define orig_getcwd ((char*(*)(char*,size_t))aSyscall[3].xOrig) +#define orig_stat ((int(*)(const char*,struct stat*))aSyscall[4].xOrig) +#define orig_fstat ((int(*)(int,struct stat*))aSyscall[5].xOrig) +#define orig_ftruncate ((int(*)(int,off_t))aSyscall[6].xOrig) +#define orig_fcntl ((int(*)(int,int,...))aSyscall[7].xOrig) +#define orig_read ((ssize_t(*)(int,void*,size_t))aSyscall[8].xOrig) +#define orig_pread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].xOrig) +#define orig_pread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].xOrig) +#define orig_write ((ssize_t(*)(int,const void*,size_t))aSyscall[11].xOrig) +#define orig_pwrite ((ssize_t(*)(int,const void*,size_t,off_t))\ + aSyscall[12].xOrig) +#define orig_pwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\ + aSyscall[13].xOrig) +#define orig_fchmod ((int(*)(int,mode_t))aSyscall[14].xOrig) +#define orig_fallocate ((int(*)(int,off_t,off_t))aSyscall[15].xOrig) +#define orig_mmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[16].xOrig) +#define orig_mremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[17].xOrig) + +/* +** This function is called exactly once from within each invocation of a +** system call wrapper in this file. It returns 1 if the function should +** fail, or 0 if it should succeed. +*/ +static int tsIsFail(void){ + gSyscall.nCount--; + if( gSyscall.nCount==0 || (gSyscall.nFail && gSyscall.bPersist) ){ + gSyscall.nFail++; + return 1; + } + return 0; +} + +/* +** Return the current error-number value for function zFunc. zFunc must be +** the name of a system call in the aSyscall[] table. +** +** Usually, the current error-number is the value that errno should be set +** to if the named system call fails. The exception is "fallocate". See +** comments above the implementation of ts_fallocate() for details. +*/ +static int tsErrno(const char *zFunc){ + int i; + int nFunc = strlen(zFunc); + for(i=0; aSyscall[i].zName; i++){ + if( strlen(aSyscall[i].zName)!=nFunc ) continue; + if( memcmp(aSyscall[i].zName, zFunc, nFunc) ) continue; + return aSyscall[i].custom_errno; + } + + assert(0); + return 0; +} + +/* +** A wrapper around tsIsFail(). If tsIsFail() returns non-zero, set the +** value of errno before returning. +*/ +static int tsIsFailErrno(const char *zFunc){ + if( tsIsFail() ){ + errno = tsErrno(zFunc); + return 1; + } + return 0; +} + +/* +** A wrapper around open(). +*/ +static int ts_open(const char *zFile, int flags, int mode){ + if( tsIsFailErrno("open") ){ + return -1; + } + return orig_open(zFile, flags, mode); +} + +/* +** A wrapper around close(). +*/ +static int ts_close(int fd){ + if( tsIsFail() ){ + /* Even if simulating an error, close the original file-descriptor. + ** This is to stop the test process from running out of file-descriptors + ** when running a long test. If a call to close() appears to fail, SQLite + ** never attempts to use the file-descriptor afterwards (or even to close + ** it a second time). */ + orig_close(fd); + return -1; + } + return orig_close(fd); +} + +/* +** A wrapper around access(). +*/ +static int ts_access(const char *zPath, int mode){ + if( tsIsFail() ){ + return -1; + } + return orig_access(zPath, mode); +} + +/* +** A wrapper around getcwd(). +*/ +static char *ts_getcwd(char *zPath, size_t nPath){ + if( tsIsFail() ){ + return NULL; + } + return orig_getcwd(zPath, nPath); +} + +/* +** A wrapper around stat(). +*/ +static int ts_stat(const char *zPath, struct stat *p){ + if( tsIsFail() ){ + return -1; + } + return orig_stat(zPath, p); +} + +/* +** A wrapper around fstat(). +*/ +static int ts_fstat(int fd, struct stat *p){ + if( tsIsFailErrno("fstat") ){ + return -1; + } + return orig_fstat(fd, p); +} + +/* +** A wrapper around ftruncate(). +*/ +static int ts_ftruncate(int fd, off_t n){ + if( tsIsFailErrno("ftruncate") ){ + return -1; + } + return orig_ftruncate(fd, n); +} + +/* +** A wrapper around fcntl(). +*/ +static int ts_fcntl(int fd, int cmd, ... ){ + va_list ap; + void *pArg; + if( tsIsFailErrno("fcntl") ){ + return -1; + } + va_start(ap, cmd); + pArg = va_arg(ap, void *); + return orig_fcntl(fd, cmd, pArg); +} + +/* +** A wrapper around read(). +*/ +static int ts_read(int fd, void *aBuf, size_t nBuf){ + if( tsIsFailErrno("read") ){ + return -1; + } + return orig_read(fd, aBuf, nBuf); +} + +/* +** A wrapper around pread(). +*/ +static int ts_pread(int fd, void *aBuf, size_t nBuf, off_t off){ + if( tsIsFailErrno("pread") ){ + return -1; + } + return orig_pread(fd, aBuf, nBuf, off); +} + +/* +** A wrapper around pread64(). +*/ +static int ts_pread64(int fd, void *aBuf, size_t nBuf, off_t off){ + if( tsIsFailErrno("pread64") ){ + return -1; + } + return orig_pread64(fd, aBuf, nBuf, off); +} + +/* +** A wrapper around write(). +*/ +static int ts_write(int fd, const void *aBuf, size_t nBuf){ + if( tsIsFailErrno("write") ){ + if( tsErrno("write")==EINTR ) orig_write(fd, aBuf, nBuf/2); + return -1; + } + return orig_write(fd, aBuf, nBuf); +} + +/* +** A wrapper around pwrite(). +*/ +static int ts_pwrite(int fd, const void *aBuf, size_t nBuf, off_t off){ + if( tsIsFailErrno("pwrite") ){ + return -1; + } + return orig_pwrite(fd, aBuf, nBuf, off); +} + +/* +** A wrapper around pwrite64(). +*/ +static int ts_pwrite64(int fd, const void *aBuf, size_t nBuf, off_t off){ + if( tsIsFailErrno("pwrite64") ){ + return -1; + } + return orig_pwrite64(fd, aBuf, nBuf, off); +} + +/* +** A wrapper around fchmod(). +*/ +static int ts_fchmod(int fd, mode_t mode){ + if( tsIsFail() ){ + return -1; + } + return orig_fchmod(fd, mode); +} + +/* +** A wrapper around fallocate(). +** +** SQLite assumes that the fallocate() function is compatible with +** posix_fallocate(). According to the Linux man page (2009-09-30): +** +** posix_fallocate() returns zero on success, or an error number on +** failure. Note that errno is not set. +*/ +static int ts_fallocate(int fd, off_t off, off_t len){ + if( tsIsFail() ){ + return tsErrno("fallocate"); + } + return orig_fallocate(fd, off, len); +} + +static void *ts_mmap( + void *pAddr, + size_t nByte, + int prot, + int flags, + int fd, + off_t iOff +){ + if( tsIsFailErrno("mmap") ){ + return MAP_FAILED; + } + return orig_mmap(pAddr, nByte, prot, flags, fd, iOff); +} + +static void *ts_mremap(void *a, size_t b, size_t c, int d, ...){ + va_list ap; + void *pArg; + if( tsIsFailErrno("mremap") ){ + return MAP_FAILED; + } + va_start(ap, d); + pArg = va_arg(ap, void *); + return orig_mremap(a, b, c, d, pArg); +} + +static int test_syscall_install( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + int nElem; + int i; + Tcl_Obj **apElem; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SYSCALL-LIST"); + return TCL_ERROR; + } + if( Tcl_ListObjGetElements(interp, objv[2], &nElem, &apElem) ){ + return TCL_ERROR; + } + pVfs = sqlite3_vfs_find(0); + + for(i=0; ixGetSystemCall(pVfs, aSyscall[iCall].zName); + pVfs->xSetSystemCall(pVfs, aSyscall[iCall].zName, aSyscall[iCall].xTest); + } + aSyscall[iCall].custom_errno = aSyscall[iCall].default_errno; + } + + return TCL_OK; +} + +static int test_syscall_uninstall( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + int i; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + for(i=0; aSyscall[i].zName; i++){ + if( aSyscall[i].xOrig ){ + pVfs->xSetSystemCall(pVfs, aSyscall[i].zName, 0); + aSyscall[i].xOrig = 0; + } + } + return TCL_OK; +} + +static int test_syscall_reset( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + int i; + int rc; + + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + if( objc==2 ){ + rc = pVfs->xSetSystemCall(pVfs, 0, 0); + for(i=0; aSyscall[i].zName; i++) aSyscall[i].xOrig = 0; + }else{ + int nFunc; + char *zFunc = Tcl_GetStringFromObj(objv[2], &nFunc); + rc = pVfs->xSetSystemCall(pVfs, Tcl_GetString(objv[2]), 0); + for(i=0; rc==SQLITE_OK && aSyscall[i].zName; i++){ + if( strlen(aSyscall[i].zName)!=nFunc ) continue; + if( memcmp(aSyscall[i].zName, zFunc, nFunc) ) continue; + aSyscall[i].xOrig = 0; + } + } + if( rc!=SQLITE_OK ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); + return TCL_ERROR; + } + + Tcl_ResetResult(interp); + return TCL_OK; +} + +static int test_syscall_exists( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + sqlite3_syscall_ptr x; + + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + x = pVfs->xGetSystemCall(pVfs, Tcl_GetString(objv[2])); + + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(x!=0)); + return TCL_OK; +} + +static int test_syscall_fault( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int nCount = 0; + int bPersist = 0; + + if( objc!=2 && objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?COUNT PERSIST?"); + return TCL_ERROR; + } + + if( objc==4 ){ + if( Tcl_GetIntFromObj(interp, objv[2], &nCount) + || Tcl_GetBooleanFromObj(interp, objv[3], &bPersist) + ){ + return TCL_ERROR; + } + } + + Tcl_SetObjResult(interp, Tcl_NewIntObj(gSyscall.nFail)); + gSyscall.nCount = nCount; + gSyscall.bPersist = bPersist; + gSyscall.nFail = 0; + return TCL_OK; +} + +static int test_syscall_errno( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int iCall; + int iErrno; + int rc; + + struct Errno { + const char *z; + int i; + } aErrno[] = { + { "EACCES", EACCES }, + { "EINTR", EINTR }, + { "EIO", EIO }, + { "EOVERFLOW", EOVERFLOW }, + { "ENOMEM", ENOMEM }, + { "EAGAIN", EAGAIN }, + { "ETIMEDOUT", ETIMEDOUT }, + { "EBUSY", EBUSY }, + { "EPERM", EPERM }, + { "EDEADLK", EDEADLK }, + { "ENOLCK", ENOLCK }, + { 0, 0 } + }; + + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SYSCALL ERRNO"); + return TCL_ERROR; + } + + rc = Tcl_GetIndexFromObjStruct(interp, + objv[2], aSyscall, sizeof(aSyscall[0]), "system-call", 0, &iCall + ); + if( rc!=TCL_OK ) return rc; + rc = Tcl_GetIndexFromObjStruct(interp, + objv[3], aErrno, sizeof(aErrno[0]), "errno", 0, &iErrno + ); + if( rc!=TCL_OK ) return rc; + + aSyscall[iCall].custom_errno = aErrno[iErrno].i; + return TCL_OK; +} + +static int test_syscall_list( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + const char *zSys; + sqlite3_vfs *pVfs; + Tcl_Obj *pList; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + pList = Tcl_NewObj(); + Tcl_IncrRefCount(pList); + for(zSys = pVfs->xNextSystemCall(pVfs, 0); + zSys!=0; + zSys = pVfs->xNextSystemCall(pVfs, zSys) + ){ + Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj(zSys, -1)); + } + + Tcl_SetObjResult(interp, pList); + Tcl_DecrRefCount(pList); + return TCL_OK; +} + +static int test_syscall_defaultvfs( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3_vfs *pVfs; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + + pVfs = sqlite3_vfs_find(0); + Tcl_SetObjResult(interp, Tcl_NewStringObj(pVfs->zName, -1)); + return TCL_OK; +} + +static int test_syscall( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct SyscallCmd { + const char *zName; + Tcl_ObjCmdProc *xCmd; + } aCmd[] = { + { "fault", test_syscall_fault }, + { "install", test_syscall_install }, + { "uninstall", test_syscall_uninstall }, + { "reset", test_syscall_reset }, + { "errno", test_syscall_errno }, + { "exists", test_syscall_exists }, + { "list", test_syscall_list }, + { "defaultvfs", test_syscall_defaultvfs }, + { 0, 0 } + }; + int iCmd; + int rc; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND ..."); + return TCL_ERROR; + } + rc = Tcl_GetIndexFromObjStruct(interp, + objv[1], aCmd, sizeof(aCmd[0]), "sub-command", 0, &iCmd + ); + if( rc!=TCL_OK ) return rc; + return aCmd[iCmd].xCmd(clientData, interp, objc, objv); +} + +int SqlitetestSyscall_Init(Tcl_Interp *interp){ + struct SyscallCmd { + const char *zName; + Tcl_ObjCmdProc *xCmd; + } aCmd[] = { + { "test_syscall", test_syscall}, + }; + int i; + + for(i=0; i +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +typedef struct tclvar_vtab tclvar_vtab; +typedef struct tclvar_cursor tclvar_cursor; + +/* +** A tclvar virtual-table object +*/ +struct tclvar_vtab { + sqlite3_vtab base; + Tcl_Interp *interp; +}; + +/* A tclvar cursor object */ +struct tclvar_cursor { + sqlite3_vtab_cursor base; + + Tcl_Obj *pList1; /* Result of [info vars ?pattern?] */ + Tcl_Obj *pList2; /* Result of [array names [lindex $pList1 $i1]] */ + int i1; /* Current item in pList1 */ + int i2; /* Current item (if any) in pList2 */ +}; + +/* Methods for the tclvar module */ +static int tclvarConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + tclvar_vtab *pVtab; + static const char zSchema[] = + "CREATE TABLE whatever(name TEXT, arrayname TEXT, value TEXT)"; + pVtab = sqlite3MallocZero( sizeof(*pVtab) ); + if( pVtab==0 ) return SQLITE_NOMEM; + *ppVtab = &pVtab->base; + pVtab->interp = (Tcl_Interp *)pAux; + sqlite3_declare_vtab(db, zSchema); + return SQLITE_OK; +} +/* Note that for this virtual table, the xCreate and xConnect +** methods are identical. */ + +static int tclvarDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} +/* The xDisconnect and xDestroy methods are also the same */ + +/* +** Open a new tclvar cursor. +*/ +static int tclvarOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + tclvar_cursor *pCur; + pCur = sqlite3MallocZero(sizeof(tclvar_cursor)); + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Close a tclvar cursor. +*/ +static int tclvarClose(sqlite3_vtab_cursor *cur){ + tclvar_cursor *pCur = (tclvar_cursor *)cur; + if( pCur->pList1 ){ + Tcl_DecrRefCount(pCur->pList1); + } + if( pCur->pList2 ){ + Tcl_DecrRefCount(pCur->pList2); + } + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Returns 1 if data is ready, or 0 if not. +*/ +static int next2(Tcl_Interp *interp, tclvar_cursor *pCur, Tcl_Obj *pObj){ + Tcl_Obj *p; + + if( pObj ){ + if( !pCur->pList2 ){ + p = Tcl_NewStringObj("array names", -1); + Tcl_IncrRefCount(p); + Tcl_ListObjAppendElement(0, p, pObj); + Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL); + Tcl_DecrRefCount(p); + pCur->pList2 = Tcl_GetObjResult(interp); + Tcl_IncrRefCount(pCur->pList2); + assert( pCur->i2==0 ); + }else{ + int n = 0; + pCur->i2++; + Tcl_ListObjLength(0, pCur->pList2, &n); + if( pCur->i2>=n ){ + Tcl_DecrRefCount(pCur->pList2); + pCur->pList2 = 0; + pCur->i2 = 0; + return 0; + } + } + } + + return 1; +} + +static int tclvarNext(sqlite3_vtab_cursor *cur){ + Tcl_Obj *pObj; + int n = 0; + int ok = 0; + + tclvar_cursor *pCur = (tclvar_cursor *)cur; + Tcl_Interp *interp = ((tclvar_vtab *)(cur->pVtab))->interp; + + Tcl_ListObjLength(0, pCur->pList1, &n); + while( !ok && pCur->i1pList1, pCur->i1, &pObj); + ok = next2(interp, pCur, pObj); + if( !ok ){ + pCur->i1++; + } + } + + return 0; +} + +static int tclvarFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + tclvar_cursor *pCur = (tclvar_cursor *)pVtabCursor; + Tcl_Interp *interp = ((tclvar_vtab *)(pVtabCursor->pVtab))->interp; + + Tcl_Obj *p = Tcl_NewStringObj("info vars", -1); + Tcl_IncrRefCount(p); + + assert( argc==0 || argc==1 ); + if( argc==1 ){ + Tcl_Obj *pArg = Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1); + Tcl_ListObjAppendElement(0, p, pArg); + } + Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL); + if( pCur->pList1 ){ + Tcl_DecrRefCount(pCur->pList1); + } + if( pCur->pList2 ){ + Tcl_DecrRefCount(pCur->pList2); + pCur->pList2 = 0; + } + pCur->i1 = 0; + pCur->i2 = 0; + pCur->pList1 = Tcl_GetObjResult(interp); + Tcl_IncrRefCount(pCur->pList1); + assert( pCur->i1==0 && pCur->i2==0 && pCur->pList2==0 ); + + Tcl_DecrRefCount(p); + return tclvarNext(pVtabCursor); +} + +static int tclvarColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ + Tcl_Obj *p1; + Tcl_Obj *p2; + const char *z1; + const char *z2 = ""; + tclvar_cursor *pCur = (tclvar_cursor*)cur; + Tcl_Interp *interp = ((tclvar_vtab *)cur->pVtab)->interp; + + Tcl_ListObjIndex(interp, pCur->pList1, pCur->i1, &p1); + Tcl_ListObjIndex(interp, pCur->pList2, pCur->i2, &p2); + z1 = Tcl_GetString(p1); + if( p2 ){ + z2 = Tcl_GetString(p2); + } + switch (i) { + case 0: { + sqlite3_result_text(ctx, z1, -1, SQLITE_TRANSIENT); + break; + } + case 1: { + sqlite3_result_text(ctx, z2, -1, SQLITE_TRANSIENT); + break; + } + case 2: { + Tcl_Obj *pVal = Tcl_GetVar2Ex(interp, z1, *z2?z2:0, TCL_GLOBAL_ONLY); + sqlite3_result_text(ctx, Tcl_GetString(pVal), -1, SQLITE_TRANSIENT); + break; + } + } + return SQLITE_OK; +} + +static int tclvarRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + *pRowid = 0; + return SQLITE_OK; +} + +static int tclvarEof(sqlite3_vtab_cursor *cur){ + tclvar_cursor *pCur = (tclvar_cursor*)cur; + return (pCur->pList2?0:1); +} + +static int tclvarBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ + int ii; + + for(ii=0; iinConstraint; ii++){ + struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii]; + if( pCons->iColumn==0 && pCons->usable + && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + struct sqlite3_index_constraint_usage *pUsage; + pUsage = &pIdxInfo->aConstraintUsage[ii]; + pUsage->omit = 0; + pUsage->argvIndex = 1; + return SQLITE_OK; + } + } + + for(ii=0; iinConstraint; ii++){ + struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii]; + if( pCons->iColumn==0 && pCons->usable + && pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ + struct sqlite3_index_constraint_usage *pUsage; + pUsage = &pIdxInfo->aConstraintUsage[ii]; + pUsage->omit = 1; + pUsage->argvIndex = 1; + return SQLITE_OK; + } + } + + return SQLITE_OK; +} + +/* +** A virtual table module that provides read-only access to a +** Tcl global variable namespace. +*/ +static sqlite3_module tclvarModule = { + 0, /* iVersion */ + tclvarConnect, + tclvarConnect, + tclvarBestIndex, + tclvarDisconnect, + tclvarDisconnect, + tclvarOpen, /* xOpen - open a cursor */ + tclvarClose, /* xClose - close a cursor */ + tclvarFilter, /* xFilter - configure scan constraints */ + tclvarNext, /* xNext - advance a cursor */ + tclvarEof, /* xEof - check for end of scan */ + tclvarColumn, /* xColumn - read data */ + tclvarRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +/* +** Decode a pointer to an sqlite3 object. +*/ +extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); + +/* +** Register the echo virtual table module. +*/ +static int register_tclvar_module( + ClientData clientData, /* Pointer to sqlite3_enable_XXX function */ + Tcl_Interp *interp, /* The TCL interpreter that invoked this command */ + int objc, /* Number of arguments */ + Tcl_Obj *CONST objv[] /* Command arguments */ +){ + sqlite3 *db; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "DB"); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_create_module(db, "tclvar", &tclvarModule, (void *)interp); +#endif + return TCL_OK; +} + +#endif + + +/* +** Register commands with the TCL interpreter. +*/ +int Sqlitetesttclvar_Init(Tcl_Interp *interp){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + static struct { + char *zName; + Tcl_ObjCmdProc *xProc; + void *clientData; + } aObjCmd[] = { + { "register_tclvar_module", register_tclvar_module, 0 }, + }; + int i; + for(i=0; i + +#if SQLITE_THREADSAFE + +#include + +#if !defined(_MSC_VER) +#include +#endif + +/* +** One of these is allocated for each thread created by [sqlthread spawn]. +*/ +typedef struct SqlThread SqlThread; +struct SqlThread { + Tcl_ThreadId parent; /* Thread id of parent thread */ + Tcl_Interp *interp; /* Parent interpreter */ + char *zScript; /* The script to execute. */ + char *zVarname; /* Varname in parent script */ +}; + +/* +** A custom Tcl_Event type used by this module. When the event is +** handled, script zScript is evaluated in interpreter interp. If +** the evaluation throws an exception (returns TCL_ERROR), then the +** error is handled by Tcl_BackgroundError(). If no error occurs, +** the result is simply discarded. +*/ +typedef struct EvalEvent EvalEvent; +struct EvalEvent { + Tcl_Event base; /* Base class of type Tcl_Event */ + char *zScript; /* The script to execute. */ + Tcl_Interp *interp; /* The interpreter to execute it in. */ +}; + +static Tcl_ObjCmdProc sqlthread_proc; +static Tcl_ObjCmdProc clock_seconds_proc; +#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) +static Tcl_ObjCmdProc blocking_step_proc; +static Tcl_ObjCmdProc blocking_prepare_v2_proc; +#endif +int Sqlitetest1_Init(Tcl_Interp *); +int Sqlite3_Init(Tcl_Interp *); + +/* Functions from main.c */ +extern const char *sqlite3ErrName(int); + +/* Functions from test1.c */ +extern void *sqlite3TestTextToPtr(const char *); +extern int getDbPointer(Tcl_Interp *, const char *, sqlite3 **); +extern int sqlite3TestMakePointerStr(Tcl_Interp *, char *, void *); +extern int sqlite3TestErrCode(Tcl_Interp *, sqlite3 *, int); + +/* +** Handler for events of type EvalEvent. +*/ +static int tclScriptEvent(Tcl_Event *evPtr, int flags){ + int rc; + EvalEvent *p = (EvalEvent *)evPtr; + rc = Tcl_Eval(p->interp, p->zScript); + if( rc!=TCL_OK ){ + Tcl_BackgroundError(p->interp); + } + UNUSED_PARAMETER(flags); + return 1; +} + +/* +** Register an EvalEvent to evaluate the script pScript in the +** parent interpreter/thread of SqlThread p. +*/ +static void postToParent(SqlThread *p, Tcl_Obj *pScript){ + EvalEvent *pEvent; + char *zMsg; + int nMsg; + + zMsg = Tcl_GetStringFromObj(pScript, &nMsg); + pEvent = (EvalEvent *)ckalloc(sizeof(EvalEvent)+nMsg+1); + pEvent->base.nextPtr = 0; + pEvent->base.proc = tclScriptEvent; + pEvent->zScript = (char *)&pEvent[1]; + memcpy(pEvent->zScript, zMsg, nMsg+1); + pEvent->interp = p->interp; + + Tcl_ThreadQueueEvent(p->parent, (Tcl_Event *)pEvent, TCL_QUEUE_TAIL); + Tcl_ThreadAlert(p->parent); +} + +/* +** The main function for threads created with [sqlthread spawn]. +*/ +static Tcl_ThreadCreateType tclScriptThread(ClientData pSqlThread){ + Tcl_Interp *interp; + Tcl_Obj *pRes; + Tcl_Obj *pList; + int rc; + SqlThread *p = (SqlThread *)pSqlThread; + extern int Sqlitetest_mutex_Init(Tcl_Interp*); + + interp = Tcl_CreateInterp(); + Tcl_CreateObjCommand(interp, "clock_seconds", clock_seconds_proc, 0, 0); + Tcl_CreateObjCommand(interp, "sqlthread", sqlthread_proc, pSqlThread, 0); +#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) + Tcl_CreateObjCommand(interp, "sqlite3_blocking_step", blocking_step_proc,0,0); + Tcl_CreateObjCommand(interp, + "sqlite3_blocking_prepare_v2", blocking_prepare_v2_proc, (void *)1, 0); + Tcl_CreateObjCommand(interp, + "sqlite3_nonblocking_prepare_v2", blocking_prepare_v2_proc, 0, 0); +#endif + Sqlitetest1_Init(interp); + Sqlitetest_mutex_Init(interp); + Sqlite3_Init(interp); + + rc = Tcl_Eval(interp, p->zScript); + pRes = Tcl_GetObjResult(interp); + pList = Tcl_NewObj(); + Tcl_IncrRefCount(pList); + Tcl_IncrRefCount(pRes); + + if( rc!=TCL_OK ){ + Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj("error", -1)); + Tcl_ListObjAppendElement(interp, pList, pRes); + postToParent(p, pList); + Tcl_DecrRefCount(pList); + pList = Tcl_NewObj(); + } + + Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj("set", -1)); + Tcl_ListObjAppendElement(interp, pList, Tcl_NewStringObj(p->zVarname, -1)); + Tcl_ListObjAppendElement(interp, pList, pRes); + postToParent(p, pList); + + ckfree((void *)p); + Tcl_DecrRefCount(pList); + Tcl_DecrRefCount(pRes); + Tcl_DeleteInterp(interp); + while( Tcl_DoOneEvent(TCL_ALL_EVENTS|TCL_DONT_WAIT) ); + Tcl_ExitThread(0); + TCL_THREAD_CREATE_RETURN; +} + +/* +** sqlthread spawn VARNAME SCRIPT +** +** Spawn a new thread with its own Tcl interpreter and run the +** specified SCRIPT(s) in it. The thread terminates after running +** the script. The result of the script is stored in the variable +** VARNAME. +** +** The caller can wait for the script to terminate using [vwait VARNAME]. +*/ +static int sqlthread_spawn( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_ThreadId x; + SqlThread *pNew; + int rc; + + int nVarname; char *zVarname; + int nScript; char *zScript; + + /* Parameters for thread creation */ + const int nStack = TCL_THREAD_STACK_DEFAULT; + const int flags = TCL_THREAD_NOFLAGS; + + assert(objc==4); + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + + zVarname = Tcl_GetStringFromObj(objv[2], &nVarname); + zScript = Tcl_GetStringFromObj(objv[3], &nScript); + + pNew = (SqlThread *)ckalloc(sizeof(SqlThread)+nVarname+nScript+2); + pNew->zVarname = (char *)&pNew[1]; + pNew->zScript = (char *)&pNew->zVarname[nVarname+1]; + memcpy(pNew->zVarname, zVarname, nVarname+1); + memcpy(pNew->zScript, zScript, nScript+1); + pNew->parent = Tcl_GetCurrentThread(); + pNew->interp = interp; + + rc = Tcl_CreateThread(&x, tclScriptThread, (void *)pNew, nStack, flags); + if( rc!=TCL_OK ){ + Tcl_AppendResult(interp, "Error in Tcl_CreateThread()", 0); + ckfree((char *)pNew); + return TCL_ERROR; + } + + return TCL_OK; +} + +/* +** sqlthread parent SCRIPT +** +** This can be called by spawned threads only. It sends the specified +** script back to the parent thread for execution. The result of +** evaluating the SCRIPT is returned. The parent thread must enter +** the event loop for this to work - otherwise the caller will +** block indefinitely. +** +** NOTE: At the moment, this doesn't work. FIXME. +*/ +static int sqlthread_parent( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + EvalEvent *pEvent; + char *zMsg; + int nMsg; + SqlThread *p = (SqlThread *)clientData; + + assert(objc==3); + UNUSED_PARAMETER(objc); + + if( p==0 ){ + Tcl_AppendResult(interp, "no parent thread", 0); + return TCL_ERROR; + } + + zMsg = Tcl_GetStringFromObj(objv[2], &nMsg); + pEvent = (EvalEvent *)ckalloc(sizeof(EvalEvent)+nMsg+1); + pEvent->base.nextPtr = 0; + pEvent->base.proc = tclScriptEvent; + pEvent->zScript = (char *)&pEvent[1]; + memcpy(pEvent->zScript, zMsg, nMsg+1); + pEvent->interp = p->interp; + Tcl_ThreadQueueEvent(p->parent, (Tcl_Event *)pEvent, TCL_QUEUE_TAIL); + Tcl_ThreadAlert(p->parent); + + return TCL_OK; +} + +static int xBusy(void *pArg, int nBusy){ + UNUSED_PARAMETER(pArg); + UNUSED_PARAMETER(nBusy); + sqlite3_sleep(50); + return 1; /* Try again... */ +} + +/* +** sqlthread open +** +** Open a database handle and return the string representation of +** the pointer value. +*/ +static int sqlthread_open( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + int sqlite3TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p); + + const char *zFilename; + sqlite3 *db; + char zBuf[100]; + extern void Md5_Register(sqlite3*); + + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + + zFilename = Tcl_GetString(objv[2]); + sqlite3_open(zFilename, &db); +#ifdef SQLITE_HAS_CODEC + if( db && objc>=4 ){ + const char *zKey; + int nKey; + int rc; + zKey = Tcl_GetStringFromObj(objv[3], &nKey); + rc = sqlite3_key(db, zKey, nKey); + if( rc!=SQLITE_OK ){ + char *zErrMsg = sqlite3_mprintf("error %d: %s", rc, sqlite3_errmsg(db)); + sqlite3_close(db); + Tcl_AppendResult(interp, zErrMsg, (char*)0); + sqlite3_free(zErrMsg); + return TCL_ERROR; + } + } +#endif + Md5_Register(db); + sqlite3_busy_handler(db, xBusy, 0); + + if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + + return TCL_OK; +} + + +/* +** sqlthread open +** +** Return the current thread-id (Tcl_GetCurrentThread()) cast to +** an integer. +*/ +static int sqlthread_id( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_ThreadId id = Tcl_GetCurrentThread(); + Tcl_SetObjResult(interp, Tcl_NewIntObj(SQLITE_PTR_TO_INT(id))); + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); + return TCL_OK; +} + + +/* +** Dispatch routine for the sub-commands of [sqlthread]. +*/ +static int sqlthread_proc( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + struct SubCommand { + char *zName; + Tcl_ObjCmdProc *xProc; + int nArg; + char *zUsage; + } aSub[] = { + {"parent", sqlthread_parent, 1, "SCRIPT"}, + {"spawn", sqlthread_spawn, 2, "VARNAME SCRIPT"}, + {"open", sqlthread_open, 1, "DBNAME"}, + {"id", sqlthread_id, 0, ""}, + {0, 0, 0} + }; + struct SubCommand *pSub; + int rc; + int iIndex; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUB-COMMAND"); + return TCL_ERROR; + } + + rc = Tcl_GetIndexFromObjStruct( + interp, objv[1], aSub, sizeof(aSub[0]), "sub-command", 0, &iIndex + ); + if( rc!=TCL_OK ) return rc; + pSub = &aSub[iIndex]; + + if( objc<(pSub->nArg+2) ){ + Tcl_WrongNumArgs(interp, 2, objv, pSub->zUsage); + return TCL_ERROR; + } + + return pSub->xProc(clientData, interp, objc, objv); +} + +/* +** The [clock_seconds] command. This is more or less the same as the +** regular tcl [clock seconds], except that it is available in testfixture +** when linked against both Tcl 8.4 and 8.5. Because [clock seconds] is +** implemented as a script in Tcl 8.5, it is not usually available to +** testfixture. +*/ +static int clock_seconds_proc( + ClientData clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Tcl_Time now; + Tcl_GetTime(&now); + Tcl_SetObjResult(interp, Tcl_NewIntObj(now.sec)); + UNUSED_PARAMETER(clientData); + UNUSED_PARAMETER(objc); + UNUSED_PARAMETER(objv); + return TCL_OK; +} + +/************************************************************************* +** This block contains the implementation of the [sqlite3_blocking_step] +** command available to threads created by [sqlthread spawn] commands. It +** is only available on UNIX for now. This is because pthread condition +** variables are used. +** +** The source code for the C functions sqlite3_blocking_step(), +** blocking_step_notify() and the structure UnlockNotification is +** automatically extracted from this file and used as part of the +** documentation for the sqlite3_unlock_notify() API function. This +** should be considered if these functions are to be extended (i.e. to +** support windows) in the future. +*/ +#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) + +/* BEGIN_SQLITE_BLOCKING_STEP */ +/* This example uses the pthreads API */ +#include + +/* +** A pointer to an instance of this structure is passed as the user-context +** pointer when registering for an unlock-notify callback. +*/ +typedef struct UnlockNotification UnlockNotification; +struct UnlockNotification { + int fired; /* True after unlock event has occurred */ + pthread_cond_t cond; /* Condition variable to wait on */ + pthread_mutex_t mutex; /* Mutex to protect structure */ +}; + +/* +** This function is an unlock-notify callback registered with SQLite. +*/ +static void unlock_notify_cb(void **apArg, int nArg){ + int i; + for(i=0; imutex); + p->fired = 1; + pthread_cond_signal(&p->cond); + pthread_mutex_unlock(&p->mutex); + } +} + +/* +** This function assumes that an SQLite API call (either sqlite3_prepare_v2() +** or sqlite3_step()) has just returned SQLITE_LOCKED. The argument is the +** associated database connection. +** +** This function calls sqlite3_unlock_notify() to register for an +** unlock-notify callback, then blocks until that callback is delivered +** and returns SQLITE_OK. The caller should then retry the failed operation. +** +** Or, if sqlite3_unlock_notify() indicates that to block would deadlock +** the system, then this function returns SQLITE_LOCKED immediately. In +** this case the caller should not retry the operation and should roll +** back the current transaction (if any). +*/ +static int wait_for_unlock_notify(sqlite3 *db){ + int rc; + UnlockNotification un; + + /* Initialize the UnlockNotification structure. */ + un.fired = 0; + pthread_mutex_init(&un.mutex, 0); + pthread_cond_init(&un.cond, 0); + + /* Register for an unlock-notify callback. */ + rc = sqlite3_unlock_notify(db, unlock_notify_cb, (void *)&un); + assert( rc==SQLITE_LOCKED || rc==SQLITE_OK ); + + /* The call to sqlite3_unlock_notify() always returns either SQLITE_LOCKED + ** or SQLITE_OK. + ** + ** If SQLITE_LOCKED was returned, then the system is deadlocked. In this + ** case this function needs to return SQLITE_LOCKED to the caller so + ** that the current transaction can be rolled back. Otherwise, block + ** until the unlock-notify callback is invoked, then return SQLITE_OK. + */ + if( rc==SQLITE_OK ){ + pthread_mutex_lock(&un.mutex); + if( !un.fired ){ + pthread_cond_wait(&un.cond, &un.mutex); + } + pthread_mutex_unlock(&un.mutex); + } + + /* Destroy the mutex and condition variables. */ + pthread_cond_destroy(&un.cond); + pthread_mutex_destroy(&un.mutex); + + return rc; +} + +/* +** This function is a wrapper around the SQLite function sqlite3_step(). +** It functions in the same way as step(), except that if a required +** shared-cache lock cannot be obtained, this function may block waiting for +** the lock to become available. In this scenario the normal API step() +** function always returns SQLITE_LOCKED. +** +** If this function returns SQLITE_LOCKED, the caller should rollback +** the current transaction (if any) and try again later. Otherwise, the +** system may become deadlocked. +*/ +int sqlite3_blocking_step(sqlite3_stmt *pStmt){ + int rc; + while( SQLITE_LOCKED==(rc = sqlite3_step(pStmt)) ){ + rc = wait_for_unlock_notify(sqlite3_db_handle(pStmt)); + if( rc!=SQLITE_OK ) break; + sqlite3_reset(pStmt); + } + return rc; +} + +/* +** This function is a wrapper around the SQLite function sqlite3_prepare_v2(). +** It functions in the same way as prepare_v2(), except that if a required +** shared-cache lock cannot be obtained, this function may block waiting for +** the lock to become available. In this scenario the normal API prepare_v2() +** function always returns SQLITE_LOCKED. +** +** If this function returns SQLITE_LOCKED, the caller should rollback +** the current transaction (if any) and try again later. Otherwise, the +** system may become deadlocked. +*/ +int sqlite3_blocking_prepare_v2( + sqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nSql, /* Length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pz /* OUT: End of parsed string */ +){ + int rc; + while( SQLITE_LOCKED==(rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, pz)) ){ + rc = wait_for_unlock_notify(db); + if( rc!=SQLITE_OK ) break; + } + return rc; +} +/* END_SQLITE_BLOCKING_STEP */ + +/* +** Usage: sqlite3_blocking_step STMT +** +** Advance the statement to the next row. +*/ +static int blocking_step_proc( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + + sqlite3_stmt *pStmt; + int rc; + + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "STMT"); + return TCL_ERROR; + } + + pStmt = (sqlite3_stmt*)sqlite3TestTextToPtr(Tcl_GetString(objv[1])); + rc = sqlite3_blocking_step(pStmt); + + Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), 0); + return TCL_OK; +} + +/* +** Usage: sqlite3_blocking_prepare_v2 DB sql bytes ?tailvar? +** Usage: sqlite3_nonblocking_prepare_v2 DB sql bytes ?tailvar? +*/ +static int blocking_prepare_v2_proc( + void * clientData, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + sqlite3 *db; + const char *zSql; + int bytes; + const char *zTail = 0; + sqlite3_stmt *pStmt = 0; + char zBuf[50]; + int rc; + int isBlocking = !(clientData==0); + + if( objc!=5 && objc!=4 ){ + Tcl_AppendResult(interp, "wrong # args: should be \"", + Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0); + return TCL_ERROR; + } + if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; + zSql = Tcl_GetString(objv[2]); + if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR; + + if( isBlocking ){ + rc = sqlite3_blocking_prepare_v2(db, zSql, bytes, &pStmt, &zTail); + }else{ + rc = sqlite3_prepare_v2(db, zSql, bytes, &pStmt, &zTail); + } + + assert(rc==SQLITE_OK || pStmt==0); + if( zTail && objc>=5 ){ + if( bytes>=0 ){ + bytes = bytes - (zTail-zSql); + } + Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0); + } + if( rc!=SQLITE_OK ){ + assert( pStmt==0 ); + sprintf(zBuf, "%s ", (char *)sqlite3ErrName(rc)); + Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0); + return TCL_ERROR; + } + + if( pStmt ){ + if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR; + Tcl_AppendResult(interp, zBuf, 0); + } + return TCL_OK; +} + +#endif /* SQLITE_OS_UNIX && SQLITE_ENABLE_UNLOCK_NOTIFY */ +/* +** End of implementation of [sqlite3_blocking_step]. +************************************************************************/ + +/* +** Register commands with the TCL interpreter. +*/ +int SqlitetestThread_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "sqlthread", sqlthread_proc, 0, 0); + Tcl_CreateObjCommand(interp, "clock_seconds", clock_seconds_proc, 0, 0); +#if SQLITE_OS_UNIX && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) + Tcl_CreateObjCommand(interp, "sqlite3_blocking_step", blocking_step_proc,0,0); + Tcl_CreateObjCommand(interp, + "sqlite3_blocking_prepare_v2", blocking_prepare_v2_proc, (void *)1, 0); + Tcl_CreateObjCommand(interp, + "sqlite3_nonblocking_prepare_v2", blocking_prepare_v2_proc, 0, 0); +#endif + return TCL_OK; +} +#else +int SqlitetestThread_Init(Tcl_Interp *interp){ + return TCL_OK; +} +#endif diff --git a/components/external/SQLite-3.8.1/src/test_vfs.c b/components/external/SQLite-3.8.1/src/test_vfs.c new file mode 100644 index 0000000000000000000000000000000000000000..613b0fce77482b74116d23e9f59d0899ae56e078 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_vfs.c @@ -0,0 +1,1510 @@ +/* +** 2010 May 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains the implementation of the Tcl [testvfs] command, +** used to create SQLite VFS implementations with various properties and +** instrumentation to support testing SQLite. +** +** testvfs VFSNAME ?OPTIONS? +** +** Available options are: +** +** -noshm BOOLEAN (True to omit shm methods. Default false) +** -default BOOLEAN (True to make the vfs default. Default false) +** -szosfile INTEGER (Value for sqlite3_vfs.szOsFile) +** -mxpathname INTEGER (Value for sqlite3_vfs.mxPathname) +** -iversion INTEGER (Value for sqlite3_vfs.iVersion) +*/ +#if SQLITE_TEST /* This file is used for testing only */ + +#include "sqlite3.h" +#include "sqliteInt.h" +#include + +typedef struct Testvfs Testvfs; +typedef struct TestvfsShm TestvfsShm; +typedef struct TestvfsBuffer TestvfsBuffer; +typedef struct TestvfsFile TestvfsFile; +typedef struct TestvfsFd TestvfsFd; + +/* +** An open file handle. +*/ +struct TestvfsFile { + sqlite3_file base; /* Base class. Must be first */ + TestvfsFd *pFd; /* File data */ +}; +#define tvfsGetFd(pFile) (((TestvfsFile *)pFile)->pFd) + +struct TestvfsFd { + sqlite3_vfs *pVfs; /* The VFS */ + const char *zFilename; /* Filename as passed to xOpen() */ + sqlite3_file *pReal; /* The real, underlying file descriptor */ + Tcl_Obj *pShmId; /* Shared memory id for Tcl callbacks */ + + TestvfsBuffer *pShm; /* Shared memory buffer */ + u32 excllock; /* Mask of exclusive locks */ + u32 sharedlock; /* Mask of shared locks */ + TestvfsFd *pNext; /* Next handle opened on the same file */ +}; + + +#define FAULT_INJECT_NONE 0 +#define FAULT_INJECT_TRANSIENT 1 +#define FAULT_INJECT_PERSISTENT 2 + +typedef struct TestFaultInject TestFaultInject; +struct TestFaultInject { + int iCnt; /* Remaining calls before fault injection */ + int eFault; /* A FAULT_INJECT_* value */ + int nFail; /* Number of faults injected */ +}; + +/* +** An instance of this structure is allocated for each VFS created. The +** sqlite3_vfs.pAppData field of the VFS structure registered with SQLite +** is set to point to it. +*/ +struct Testvfs { + char *zName; /* Name of this VFS */ + sqlite3_vfs *pParent; /* The VFS to use for file IO */ + sqlite3_vfs *pVfs; /* The testvfs registered with SQLite */ + Tcl_Interp *interp; /* Interpreter to run script in */ + Tcl_Obj *pScript; /* Script to execute */ + TestvfsBuffer *pBuffer; /* List of shared buffers */ + int isNoshm; + int isFullshm; + + int mask; /* Mask controlling [script] and [ioerr] */ + + TestFaultInject ioerr_err; + TestFaultInject full_err; + TestFaultInject cantopen_err; + +#if 0 + int iIoerrCnt; + int ioerr; + int nIoerrFail; + int iFullCnt; + int fullerr; + int nFullFail; +#endif + + int iDevchar; + int iSectorsize; +}; + +/* +** The Testvfs.mask variable is set to a combination of the following. +** If a bit is clear in Testvfs.mask, then calls made by SQLite to the +** corresponding VFS method is ignored for purposes of: +** +** + Simulating IO errors, and +** + Invoking the Tcl callback script. +*/ +#define TESTVFS_SHMOPEN_MASK 0x00000001 +#define TESTVFS_SHMLOCK_MASK 0x00000010 +#define TESTVFS_SHMMAP_MASK 0x00000020 +#define TESTVFS_SHMBARRIER_MASK 0x00000040 +#define TESTVFS_SHMCLOSE_MASK 0x00000080 + +#define TESTVFS_OPEN_MASK 0x00000100 +#define TESTVFS_SYNC_MASK 0x00000200 +#define TESTVFS_DELETE_MASK 0x00000400 +#define TESTVFS_CLOSE_MASK 0x00000800 +#define TESTVFS_WRITE_MASK 0x00001000 +#define TESTVFS_TRUNCATE_MASK 0x00002000 +#define TESTVFS_ACCESS_MASK 0x00004000 +#define TESTVFS_FULLPATHNAME_MASK 0x00008000 +#define TESTVFS_READ_MASK 0x00010000 +#define TESTVFS_UNLOCK_MASK 0x00020000 + +#define TESTVFS_ALL_MASK 0x0003FFFF + + +#define TESTVFS_MAX_PAGES 1024 + +/* +** A shared-memory buffer. There is one of these objects for each shared +** memory region opened by clients. If two clients open the same file, +** there are two TestvfsFile structures but only one TestvfsBuffer structure. +*/ +struct TestvfsBuffer { + char *zFile; /* Associated file name */ + int pgsz; /* Page size */ + u8 *aPage[TESTVFS_MAX_PAGES]; /* Array of ckalloc'd pages */ + TestvfsFd *pFile; /* List of open handles */ + TestvfsBuffer *pNext; /* Next in linked list of all buffers */ +}; + + +#define PARENTVFS(x) (((Testvfs *)((x)->pAppData))->pParent) + +#define TESTVFS_MAX_ARGS 12 + + +/* +** Method declarations for TestvfsFile. +*/ +static int tvfsClose(sqlite3_file*); +static int tvfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int tvfsWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); +static int tvfsTruncate(sqlite3_file*, sqlite3_int64 size); +static int tvfsSync(sqlite3_file*, int flags); +static int tvfsFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int tvfsLock(sqlite3_file*, int); +static int tvfsUnlock(sqlite3_file*, int); +static int tvfsCheckReservedLock(sqlite3_file*, int *); +static int tvfsFileControl(sqlite3_file*, int op, void *pArg); +static int tvfsSectorSize(sqlite3_file*); +static int tvfsDeviceCharacteristics(sqlite3_file*); + +/* +** Method declarations for tvfs_vfs. +*/ +static int tvfsOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int tvfsDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int tvfsAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int tvfsFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +static void *tvfsDlOpen(sqlite3_vfs*, const char *zFilename); +static void tvfsDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*tvfsDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void); +static void tvfsDlClose(sqlite3_vfs*, void*); +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +static int tvfsRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int tvfsSleep(sqlite3_vfs*, int microseconds); +static int tvfsCurrentTime(sqlite3_vfs*, double*); + +static int tvfsShmOpen(sqlite3_file*); +static int tvfsShmLock(sqlite3_file*, int , int, int); +static int tvfsShmMap(sqlite3_file*,int,int,int, void volatile **); +static void tvfsShmBarrier(sqlite3_file*); +static int tvfsShmUnmap(sqlite3_file*, int); + +static int tvfsFetch(sqlite3_file*, sqlite3_int64, int, void**); +static int tvfsUnfetch(sqlite3_file*, sqlite3_int64, void*); + +static sqlite3_io_methods tvfs_io_methods = { + 3, /* iVersion */ + tvfsClose, /* xClose */ + tvfsRead, /* xRead */ + tvfsWrite, /* xWrite */ + tvfsTruncate, /* xTruncate */ + tvfsSync, /* xSync */ + tvfsFileSize, /* xFileSize */ + tvfsLock, /* xLock */ + tvfsUnlock, /* xUnlock */ + tvfsCheckReservedLock, /* xCheckReservedLock */ + tvfsFileControl, /* xFileControl */ + tvfsSectorSize, /* xSectorSize */ + tvfsDeviceCharacteristics, /* xDeviceCharacteristics */ + tvfsShmMap, /* xShmMap */ + tvfsShmLock, /* xShmLock */ + tvfsShmBarrier, /* xShmBarrier */ + tvfsShmUnmap, /* xShmUnmap */ + tvfsFetch, + tvfsUnfetch +}; + +static int tvfsResultCode(Testvfs *p, int *pRc){ + struct errcode { + int eCode; + const char *zCode; + } aCode[] = { + { SQLITE_OK, "SQLITE_OK" }, + { SQLITE_ERROR, "SQLITE_ERROR" }, + { SQLITE_IOERR, "SQLITE_IOERR" }, + { SQLITE_LOCKED, "SQLITE_LOCKED" }, + { SQLITE_BUSY, "SQLITE_BUSY" }, + }; + + const char *z; + int i; + + z = Tcl_GetStringResult(p->interp); + for(i=0; ieFault ){ + p->iCnt--; + if( p->iCnt==0 || (p->iCnt<0 && p->eFault==FAULT_INJECT_PERSISTENT ) ){ + ret = 1; + p->nFail++; + } + } + return ret; +} + + +static int tvfsInjectIoerr(Testvfs *p){ + return tvfsInjectFault(&p->ioerr_err); +} + +static int tvfsInjectFullerr(Testvfs *p){ + return tvfsInjectFault(&p->full_err); +} +static int tvfsInjectCantopenerr(Testvfs *p){ + return tvfsInjectFault(&p->cantopen_err); +} + + +static void tvfsExecTcl( + Testvfs *p, + const char *zMethod, + Tcl_Obj *arg1, + Tcl_Obj *arg2, + Tcl_Obj *arg3, + Tcl_Obj *arg4 +){ + int rc; /* Return code from Tcl_EvalObj() */ + Tcl_Obj *pEval; + assert( p->pScript ); + + assert( zMethod ); + assert( p ); + assert( arg2==0 || arg1!=0 ); + assert( arg3==0 || arg2!=0 ); + + pEval = Tcl_DuplicateObj(p->pScript); + Tcl_IncrRefCount(p->pScript); + Tcl_ListObjAppendElement(p->interp, pEval, Tcl_NewStringObj(zMethod, -1)); + if( arg1 ) Tcl_ListObjAppendElement(p->interp, pEval, arg1); + if( arg2 ) Tcl_ListObjAppendElement(p->interp, pEval, arg2); + if( arg3 ) Tcl_ListObjAppendElement(p->interp, pEval, arg3); + if( arg4 ) Tcl_ListObjAppendElement(p->interp, pEval, arg4); + + rc = Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL); + if( rc!=TCL_OK ){ + Tcl_BackgroundError(p->interp); + Tcl_ResetResult(p->interp); + } +} + + +/* +** Close an tvfs-file. +*/ +static int tvfsClose(sqlite3_file *pFile){ + int rc; + TestvfsFile *pTestfile = (TestvfsFile *)pFile; + TestvfsFd *pFd = pTestfile->pFd; + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_CLOSE_MASK ){ + tvfsExecTcl(p, "xClose", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, 0, 0 + ); + } + + if( pFd->pShmId ){ + Tcl_DecrRefCount(pFd->pShmId); + pFd->pShmId = 0; + } + if( pFile->pMethods ){ + ckfree((char *)pFile->pMethods); + } + rc = sqlite3OsClose(pFd->pReal); + ckfree((char *)pFd); + pTestfile->pFd = 0; + return rc; +} + +/* +** Read data from an tvfs-file. +*/ +static int tvfsRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + if( p->pScript && p->mask&TESTVFS_READ_MASK ){ + tvfsExecTcl(p, "xRead", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, 0, 0 + ); + tvfsResultCode(p, &rc); + } + if( rc==SQLITE_OK && p->mask&TESTVFS_READ_MASK && tvfsInjectIoerr(p) ){ + rc = SQLITE_IOERR; + } + if( rc==SQLITE_OK ){ + rc = sqlite3OsRead(pFd->pReal, zBuf, iAmt, iOfst); + } + return rc; +} + +/* +** Write data to an tvfs-file. +*/ +static int tvfsWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_WRITE_MASK ){ + tvfsExecTcl(p, "xWrite", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, + Tcl_NewWideIntObj(iOfst), Tcl_NewIntObj(iAmt) + ); + tvfsResultCode(p, &rc); + } + + if( rc==SQLITE_OK && tvfsInjectFullerr(p) ){ + rc = SQLITE_FULL; + } + if( rc==SQLITE_OK && p->mask&TESTVFS_WRITE_MASK && tvfsInjectIoerr(p) ){ + rc = SQLITE_IOERR; + } + + if( rc==SQLITE_OK ){ + rc = sqlite3OsWrite(pFd->pReal, zBuf, iAmt, iOfst); + } + return rc; +} + +/* +** Truncate an tvfs-file. +*/ +static int tvfsTruncate(sqlite3_file *pFile, sqlite_int64 size){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_TRUNCATE_MASK ){ + tvfsExecTcl(p, "xTruncate", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, 0, 0 + ); + tvfsResultCode(p, &rc); + } + + if( rc==SQLITE_OK ){ + rc = sqlite3OsTruncate(pFd->pReal, size); + } + return rc; +} + +/* +** Sync an tvfs-file. +*/ +static int tvfsSync(sqlite3_file *pFile, int flags){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_SYNC_MASK ){ + char *zFlags; + + switch( flags ){ + case SQLITE_SYNC_NORMAL: + zFlags = "normal"; + break; + case SQLITE_SYNC_FULL: + zFlags = "full"; + break; + case SQLITE_SYNC_NORMAL|SQLITE_SYNC_DATAONLY: + zFlags = "normal|dataonly"; + break; + case SQLITE_SYNC_FULL|SQLITE_SYNC_DATAONLY: + zFlags = "full|dataonly"; + break; + default: + assert(0); + } + + tvfsExecTcl(p, "xSync", + Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, + Tcl_NewStringObj(zFlags, -1), 0 + ); + tvfsResultCode(p, &rc); + } + + if( rc==SQLITE_OK && tvfsInjectFullerr(p) ) rc = SQLITE_FULL; + + if( rc==SQLITE_OK ){ + rc = sqlite3OsSync(pFd->pReal, flags); + } + + return rc; +} + +/* +** Return the current file-size of an tvfs-file. +*/ +static int tvfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + TestvfsFd *p = tvfsGetFd(pFile); + return sqlite3OsFileSize(p->pReal, pSize); +} + +/* +** Lock an tvfs-file. +*/ +static int tvfsLock(sqlite3_file *pFile, int eLock){ + TestvfsFd *p = tvfsGetFd(pFile); + return sqlite3OsLock(p->pReal, eLock); +} + +/* +** Unlock an tvfs-file. +*/ +static int tvfsUnlock(sqlite3_file *pFile, int eLock){ + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + if( p->mask&TESTVFS_WRITE_MASK && tvfsInjectIoerr(p) ){ + return SQLITE_IOERR_UNLOCK; + } + return sqlite3OsUnlock(pFd->pReal, eLock); +} + +/* +** Check if another file-handle holds a RESERVED lock on an tvfs-file. +*/ +static int tvfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + TestvfsFd *p = tvfsGetFd(pFile); + return sqlite3OsCheckReservedLock(p->pReal, pResOut); +} + +/* +** File control method. For custom operations on an tvfs-file. +*/ +static int tvfsFileControl(sqlite3_file *pFile, int op, void *pArg){ + TestvfsFd *p = tvfsGetFd(pFile); + if( op==SQLITE_FCNTL_PRAGMA ){ + char **argv = (char**)pArg; + if( sqlite3_stricmp(argv[1],"error")==0 ){ + int rc = SQLITE_ERROR; + if( argv[2] ){ + const char *z = argv[2]; + int x = atoi(z); + if( x ){ + rc = x; + while( sqlite3Isdigit(z[0]) ){ z++; } + while( sqlite3Isspace(z[0]) ){ z++; } + } + if( z[0] ) argv[0] = sqlite3_mprintf("%s", z); + } + return rc; + } + if( sqlite3_stricmp(argv[1], "filename")==0 ){ + argv[0] = sqlite3_mprintf("%s", p->zFilename); + return SQLITE_OK; + } + } + return sqlite3OsFileControl(p->pReal, op, pArg); +} + +/* +** Return the sector-size in bytes for an tvfs-file. +*/ +static int tvfsSectorSize(sqlite3_file *pFile){ + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + if( p->iSectorsize>=0 ){ + return p->iSectorsize; + } + return sqlite3OsSectorSize(pFd->pReal); +} + +/* +** Return the device characteristic flags supported by an tvfs-file. +*/ +static int tvfsDeviceCharacteristics(sqlite3_file *pFile){ + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)pFd->pVfs->pAppData; + if( p->iDevchar>=0 ){ + return p->iDevchar; + } + return sqlite3OsDeviceCharacteristics(pFd->pReal); +} + +/* +** Open an tvfs file handle. +*/ +static int tvfsOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + TestvfsFile *pTestfile = (TestvfsFile *)pFile; + TestvfsFd *pFd; + Tcl_Obj *pId = 0; + Testvfs *p = (Testvfs *)pVfs->pAppData; + + pFd = (TestvfsFd *)ckalloc(sizeof(TestvfsFd) + PARENTVFS(pVfs)->szOsFile); + memset(pFd, 0, sizeof(TestvfsFd) + PARENTVFS(pVfs)->szOsFile); + pFd->pShm = 0; + pFd->pShmId = 0; + pFd->zFilename = zName; + pFd->pVfs = pVfs; + pFd->pReal = (sqlite3_file *)&pFd[1]; + memset(pTestfile, 0, sizeof(TestvfsFile)); + pTestfile->pFd = pFd; + + /* Evaluate the Tcl script: + ** + ** SCRIPT xOpen FILENAME KEY-VALUE-ARGS + ** + ** If the script returns an SQLite error code other than SQLITE_OK, an + ** error is returned to the caller. If it returns SQLITE_OK, the new + ** connection is named "anon". Otherwise, the value returned by the + ** script is used as the connection name. + */ + Tcl_ResetResult(p->interp); + if( p->pScript && p->mask&TESTVFS_OPEN_MASK ){ + Tcl_Obj *pArg = Tcl_NewObj(); + Tcl_IncrRefCount(pArg); + if( flags&SQLITE_OPEN_MAIN_DB ){ + const char *z = &zName[strlen(zName)+1]; + while( *z ){ + Tcl_ListObjAppendElement(0, pArg, Tcl_NewStringObj(z, -1)); + z += strlen(z) + 1; + Tcl_ListObjAppendElement(0, pArg, Tcl_NewStringObj(z, -1)); + z += strlen(z) + 1; + } + } + tvfsExecTcl(p, "xOpen", Tcl_NewStringObj(pFd->zFilename, -1), pArg, 0, 0); + Tcl_DecrRefCount(pArg); + if( tvfsResultCode(p, &rc) ){ + if( rc!=SQLITE_OK ) return rc; + }else{ + pId = Tcl_GetObjResult(p->interp); + } + } + + if( (p->mask&TESTVFS_OPEN_MASK) && tvfsInjectIoerr(p) ) return SQLITE_IOERR; + if( tvfsInjectCantopenerr(p) ) return SQLITE_CANTOPEN; + if( tvfsInjectFullerr(p) ) return SQLITE_FULL; + + if( !pId ){ + pId = Tcl_NewStringObj("anon", -1); + } + Tcl_IncrRefCount(pId); + pFd->pShmId = pId; + Tcl_ResetResult(p->interp); + + rc = sqlite3OsOpen(PARENTVFS(pVfs), zName, pFd->pReal, flags, pOutFlags); + if( pFd->pReal->pMethods ){ + sqlite3_io_methods *pMethods; + int nByte; + + if( pVfs->iVersion>1 ){ + nByte = sizeof(sqlite3_io_methods); + }else{ + nByte = offsetof(sqlite3_io_methods, xShmMap); + } + + pMethods = (sqlite3_io_methods *)ckalloc(nByte); + memcpy(pMethods, &tvfs_io_methods, nByte); + pMethods->iVersion = pFd->pReal->pMethods->iVersion; + if( pMethods->iVersion>pVfs->iVersion ){ + pMethods->iVersion = pVfs->iVersion; + } + if( pVfs->iVersion>1 && ((Testvfs *)pVfs->pAppData)->isNoshm ){ + pMethods->xShmUnmap = 0; + pMethods->xShmLock = 0; + pMethods->xShmBarrier = 0; + pMethods->xShmMap = 0; + } + pFile->pMethods = pMethods; + } + + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int tvfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc = SQLITE_OK; + Testvfs *p = (Testvfs *)pVfs->pAppData; + + if( p->pScript && p->mask&TESTVFS_DELETE_MASK ){ + tvfsExecTcl(p, "xDelete", + Tcl_NewStringObj(zPath, -1), Tcl_NewIntObj(dirSync), 0, 0 + ); + tvfsResultCode(p, &rc); + } + if( rc==SQLITE_OK ){ + rc = sqlite3OsDelete(PARENTVFS(pVfs), zPath, dirSync); + } + return rc; +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int tvfsAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + Testvfs *p = (Testvfs *)pVfs->pAppData; + if( p->pScript && p->mask&TESTVFS_ACCESS_MASK ){ + int rc; + char *zArg = 0; + if( flags==SQLITE_ACCESS_EXISTS ) zArg = "SQLITE_ACCESS_EXISTS"; + if( flags==SQLITE_ACCESS_READWRITE ) zArg = "SQLITE_ACCESS_READWRITE"; + if( flags==SQLITE_ACCESS_READ ) zArg = "SQLITE_ACCESS_READ"; + tvfsExecTcl(p, "xAccess", + Tcl_NewStringObj(zPath, -1), Tcl_NewStringObj(zArg, -1), 0, 0 + ); + if( tvfsResultCode(p, &rc) ){ + if( rc!=SQLITE_OK ) return rc; + }else{ + Tcl_Interp *interp = p->interp; + if( TCL_OK==Tcl_GetBooleanFromObj(0, Tcl_GetObjResult(interp), pResOut) ){ + return SQLITE_OK; + } + } + } + return sqlite3OsAccess(PARENTVFS(pVfs), zPath, flags, pResOut); +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (DEVSYM_MAX_PATHNAME+1) bytes. +*/ +static int tvfsFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + Testvfs *p = (Testvfs *)pVfs->pAppData; + if( p->pScript && p->mask&TESTVFS_FULLPATHNAME_MASK ){ + int rc; + tvfsExecTcl(p, "xFullPathname", Tcl_NewStringObj(zPath, -1), 0, 0, 0); + if( tvfsResultCode(p, &rc) ){ + if( rc!=SQLITE_OK ) return rc; + } + } + return sqlite3OsFullPathname(PARENTVFS(pVfs), zPath, nOut, zOut); +} + +#ifndef SQLITE_OMIT_LOAD_EXTENSION +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *tvfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + return sqlite3OsDlOpen(PARENTVFS(pVfs), zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void tvfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + sqlite3OsDlError(PARENTVFS(pVfs), nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*tvfsDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return sqlite3OsDlSym(PARENTVFS(pVfs), p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void tvfsDlClose(sqlite3_vfs *pVfs, void *pHandle){ + sqlite3OsDlClose(PARENTVFS(pVfs), pHandle); +} +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int tvfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return sqlite3OsRandomness(PARENTVFS(pVfs), nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int tvfsSleep(sqlite3_vfs *pVfs, int nMicro){ + return sqlite3OsSleep(PARENTVFS(pVfs), nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int tvfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + return PARENTVFS(pVfs)->xCurrentTime(PARENTVFS(pVfs), pTimeOut); +} + +static int tvfsShmOpen(sqlite3_file *pFile){ + Testvfs *p; + int rc = SQLITE_OK; /* Return code */ + TestvfsBuffer *pBuffer; /* Buffer to open connection to */ + TestvfsFd *pFd; /* The testvfs file structure */ + + pFd = tvfsGetFd(pFile); + p = (Testvfs *)pFd->pVfs->pAppData; + assert( 0==p->isFullshm ); + assert( pFd->pShmId && pFd->pShm==0 && pFd->pNext==0 ); + + /* Evaluate the Tcl script: + ** + ** SCRIPT xShmOpen FILENAME + */ + Tcl_ResetResult(p->interp); + if( p->pScript && p->mask&TESTVFS_SHMOPEN_MASK ){ + tvfsExecTcl(p, "xShmOpen", Tcl_NewStringObj(pFd->zFilename, -1), 0, 0, 0); + if( tvfsResultCode(p, &rc) ){ + if( rc!=SQLITE_OK ) return rc; + } + } + + assert( rc==SQLITE_OK ); + if( p->mask&TESTVFS_SHMOPEN_MASK && tvfsInjectIoerr(p) ){ + return SQLITE_IOERR; + } + + /* Search for a TestvfsBuffer. Create a new one if required. */ + for(pBuffer=p->pBuffer; pBuffer; pBuffer=pBuffer->pNext){ + if( 0==strcmp(pFd->zFilename, pBuffer->zFile) ) break; + } + if( !pBuffer ){ + int nByte = sizeof(TestvfsBuffer) + (int)strlen(pFd->zFilename) + 1; + pBuffer = (TestvfsBuffer *)ckalloc(nByte); + memset(pBuffer, 0, nByte); + pBuffer->zFile = (char *)&pBuffer[1]; + strcpy(pBuffer->zFile, pFd->zFilename); + pBuffer->pNext = p->pBuffer; + p->pBuffer = pBuffer; + } + + /* Connect the TestvfsBuffer to the new TestvfsShm handle and return. */ + pFd->pNext = pBuffer->pFile; + pBuffer->pFile = pFd; + pFd->pShm = pBuffer; + return SQLITE_OK; +} + +static void tvfsAllocPage(TestvfsBuffer *p, int iPage, int pgsz){ + assert( iPageaPage[iPage]==0 ){ + p->aPage[iPage] = (u8 *)ckalloc(pgsz); + memset(p->aPage[iPage], 0, pgsz); + p->pgsz = pgsz; + } +} + +static int tvfsShmMap( + sqlite3_file *pFile, /* Handle open on database file */ + int iPage, /* Page to retrieve */ + int pgsz, /* Size of pages */ + int isWrite, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData); + + if( p->isFullshm ){ + return sqlite3OsShmMap(pFd->pReal, iPage, pgsz, isWrite, pp); + } + + if( 0==pFd->pShm ){ + rc = tvfsShmOpen(pFile); + if( rc!=SQLITE_OK ){ + return rc; + } + } + + if( p->pScript && p->mask&TESTVFS_SHMMAP_MASK ){ + Tcl_Obj *pArg = Tcl_NewObj(); + Tcl_IncrRefCount(pArg); + Tcl_ListObjAppendElement(p->interp, pArg, Tcl_NewIntObj(iPage)); + Tcl_ListObjAppendElement(p->interp, pArg, Tcl_NewIntObj(pgsz)); + Tcl_ListObjAppendElement(p->interp, pArg, Tcl_NewIntObj(isWrite)); + tvfsExecTcl(p, "xShmMap", + Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, pArg, 0 + ); + tvfsResultCode(p, &rc); + Tcl_DecrRefCount(pArg); + } + if( rc==SQLITE_OK && p->mask&TESTVFS_SHMMAP_MASK && tvfsInjectIoerr(p) ){ + rc = SQLITE_IOERR; + } + + if( rc==SQLITE_OK && isWrite && !pFd->pShm->aPage[iPage] ){ + tvfsAllocPage(pFd->pShm, iPage, pgsz); + } + *pp = (void volatile *)pFd->pShm->aPage[iPage]; + + return rc; +} + + +static int tvfsShmLock( + sqlite3_file *pFile, + int ofst, + int n, + int flags +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData); + int nLock; + char zLock[80]; + + if( p->isFullshm ){ + return sqlite3OsShmLock(pFd->pReal, ofst, n, flags); + } + + if( p->pScript && p->mask&TESTVFS_SHMLOCK_MASK ){ + sqlite3_snprintf(sizeof(zLock), zLock, "%d %d", ofst, n); + nLock = (int)strlen(zLock); + if( flags & SQLITE_SHM_LOCK ){ + strcpy(&zLock[nLock], " lock"); + }else{ + strcpy(&zLock[nLock], " unlock"); + } + nLock += (int)strlen(&zLock[nLock]); + if( flags & SQLITE_SHM_SHARED ){ + strcpy(&zLock[nLock], " shared"); + }else{ + strcpy(&zLock[nLock], " exclusive"); + } + tvfsExecTcl(p, "xShmLock", + Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, + Tcl_NewStringObj(zLock, -1), 0 + ); + tvfsResultCode(p, &rc); + } + + if( rc==SQLITE_OK && p->mask&TESTVFS_SHMLOCK_MASK && tvfsInjectIoerr(p) ){ + rc = SQLITE_IOERR; + } + + if( rc==SQLITE_OK ){ + int isLock = (flags & SQLITE_SHM_LOCK); + int isExcl = (flags & SQLITE_SHM_EXCLUSIVE); + u32 mask = (((1<pShm->pFile; p2; p2=p2->pNext){ + if( p2==pFd ) continue; + if( (p2->excllock&mask) || (isExcl && p2->sharedlock&mask) ){ + rc = SQLITE_BUSY; + break; + } + } + if( rc==SQLITE_OK ){ + if( isExcl ) pFd->excllock |= mask; + if( !isExcl ) pFd->sharedlock |= mask; + } + }else{ + if( isExcl ) pFd->excllock &= (~mask); + if( !isExcl ) pFd->sharedlock &= (~mask); + } + } + + return rc; +} + +static void tvfsShmBarrier(sqlite3_file *pFile){ + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData); + + if( p->isFullshm ){ + sqlite3OsShmBarrier(pFd->pReal); + return; + } + + if( p->pScript && p->mask&TESTVFS_SHMBARRIER_MASK ){ + tvfsExecTcl(p, "xShmBarrier", + Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, 0, 0 + ); + } +} + +static int tvfsShmUnmap( + sqlite3_file *pFile, + int deleteFlag +){ + int rc = SQLITE_OK; + TestvfsFd *pFd = tvfsGetFd(pFile); + Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData); + TestvfsBuffer *pBuffer = pFd->pShm; + TestvfsFd **ppFd; + + if( p->isFullshm ){ + return sqlite3OsShmUnmap(pFd->pReal, deleteFlag); + } + + if( !pBuffer ) return SQLITE_OK; + assert( pFd->pShmId && pFd->pShm ); + + if( p->pScript && p->mask&TESTVFS_SHMCLOSE_MASK ){ + tvfsExecTcl(p, "xShmUnmap", + Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, 0, 0 + ); + tvfsResultCode(p, &rc); + } + + for(ppFd=&pBuffer->pFile; *ppFd!=pFd; ppFd=&((*ppFd)->pNext)); + assert( (*ppFd)==pFd ); + *ppFd = pFd->pNext; + pFd->pNext = 0; + + if( pBuffer->pFile==0 ){ + int i; + TestvfsBuffer **pp; + for(pp=&p->pBuffer; *pp!=pBuffer; pp=&((*pp)->pNext)); + *pp = (*pp)->pNext; + for(i=0; pBuffer->aPage[i]; i++){ + ckfree((char *)pBuffer->aPage[i]); + } + ckfree((char *)pBuffer); + } + pFd->pShm = 0; + + return rc; +} + +static int tvfsFetch( + sqlite3_file *pFile, + sqlite3_int64 iOfst, + int iAmt, + void **pp +){ + TestvfsFd *pFd = tvfsGetFd(pFile); + return sqlite3OsFetch(pFd->pReal, iOfst, iAmt, pp); +} + +static int tvfsUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *p){ + TestvfsFd *pFd = tvfsGetFd(pFile); + return sqlite3OsUnfetch(pFd->pReal, iOfst, p); +} + +static int testvfs_obj_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + Testvfs *p = (Testvfs *)cd; + + enum DB_enum { + CMD_SHM, CMD_DELETE, CMD_FILTER, CMD_IOERR, CMD_SCRIPT, + CMD_DEVCHAR, CMD_SECTORSIZE, CMD_FULLERR, CMD_CANTOPENERR + }; + struct TestvfsSubcmd { + char *zName; + enum DB_enum eCmd; + } aSubcmd[] = { + { "shm", CMD_SHM }, + { "delete", CMD_DELETE }, + { "filter", CMD_FILTER }, + { "ioerr", CMD_IOERR }, + { "fullerr", CMD_FULLERR }, + { "cantopenerr", CMD_CANTOPENERR }, + { "script", CMD_SCRIPT }, + { "devchar", CMD_DEVCHAR }, + { "sectorsize", CMD_SECTORSIZE }, + { 0, 0 } + }; + int i; + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ..."); + return TCL_ERROR; + } + if( Tcl_GetIndexFromObjStruct( + interp, objv[1], aSubcmd, sizeof(aSubcmd[0]), "subcommand", 0, &i) + ){ + return TCL_ERROR; + } + Tcl_ResetResult(interp); + + switch( aSubcmd[i].eCmd ){ + case CMD_SHM: { + Tcl_Obj *pObj; + int i, rc; + TestvfsBuffer *pBuffer; + char *zName; + if( objc!=3 && objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "FILE ?VALUE?"); + return TCL_ERROR; + } + zName = ckalloc(p->pParent->mxPathname); + rc = p->pParent->xFullPathname( + p->pParent, Tcl_GetString(objv[2]), + p->pParent->mxPathname, zName + ); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "failed to get full path: ", + Tcl_GetString(objv[2]), 0); + ckfree(zName); + return TCL_ERROR; + } + for(pBuffer=p->pBuffer; pBuffer; pBuffer=pBuffer->pNext){ + if( 0==strcmp(pBuffer->zFile, zName) ) break; + } + ckfree(zName); + if( !pBuffer ){ + Tcl_AppendResult(interp, "no such file: ", Tcl_GetString(objv[2]), 0); + return TCL_ERROR; + } + if( objc==4 ){ + int n; + u8 *a = Tcl_GetByteArrayFromObj(objv[3], &n); + int pgsz = pBuffer->pgsz; + if( pgsz==0 ) pgsz = 65536; + for(i=0; i*pgszaPage[i], &a[i*pgsz], nByte); + } + } + + pObj = Tcl_NewObj(); + for(i=0; pBuffer->aPage[i]; i++){ + int pgsz = pBuffer->pgsz; + if( pgsz==0 ) pgsz = 65536; + Tcl_AppendObjToObj(pObj, Tcl_NewByteArrayObj(pBuffer->aPage[i], pgsz)); + } + Tcl_SetObjResult(interp, pObj); + break; + } + + case CMD_FILTER: { + static struct VfsMethod { + char *zName; + int mask; + } vfsmethod [] = { + { "xShmOpen", TESTVFS_SHMOPEN_MASK }, + { "xShmLock", TESTVFS_SHMLOCK_MASK }, + { "xShmBarrier", TESTVFS_SHMBARRIER_MASK }, + { "xShmUnmap", TESTVFS_SHMCLOSE_MASK }, + { "xShmMap", TESTVFS_SHMMAP_MASK }, + { "xSync", TESTVFS_SYNC_MASK }, + { "xDelete", TESTVFS_DELETE_MASK }, + { "xWrite", TESTVFS_WRITE_MASK }, + { "xRead", TESTVFS_READ_MASK }, + { "xTruncate", TESTVFS_TRUNCATE_MASK }, + { "xOpen", TESTVFS_OPEN_MASK }, + { "xClose", TESTVFS_CLOSE_MASK }, + { "xAccess", TESTVFS_ACCESS_MASK }, + { "xFullPathname", TESTVFS_FULLPATHNAME_MASK }, + { "xUnlock", TESTVFS_UNLOCK_MASK }, + }; + Tcl_Obj **apElem = 0; + int nElem = 0; + int i; + int mask = 0; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "LIST"); + return TCL_ERROR; + } + if( Tcl_ListObjGetElements(interp, objv[2], &nElem, &apElem) ){ + return TCL_ERROR; + } + Tcl_ResetResult(interp); + for(i=0; imask = mask; + break; + } + + case CMD_SCRIPT: { + if( objc==3 ){ + int nByte; + if( p->pScript ){ + Tcl_DecrRefCount(p->pScript); + p->pScript = 0; + } + Tcl_GetStringFromObj(objv[2], &nByte); + if( nByte>0 ){ + p->pScript = Tcl_DuplicateObj(objv[2]); + Tcl_IncrRefCount(p->pScript); + } + }else if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); + return TCL_ERROR; + } + + Tcl_ResetResult(interp); + if( p->pScript ) Tcl_SetObjResult(interp, p->pScript); + + break; + } + + /* + ** TESTVFS ioerr ?IFAIL PERSIST? + ** + ** Where IFAIL is an integer and PERSIST is boolean. + */ + case CMD_CANTOPENERR: + case CMD_IOERR: + case CMD_FULLERR: { + TestFaultInject *pTest; + int iRet; + + switch( aSubcmd[i].eCmd ){ + case CMD_IOERR: pTest = &p->ioerr_err; break; + case CMD_FULLERR: pTest = &p->full_err; break; + case CMD_CANTOPENERR: pTest = &p->cantopen_err; break; + default: assert(0); + } + iRet = pTest->nFail; + pTest->nFail = 0; + pTest->eFault = 0; + pTest->iCnt = 0; + + if( objc==4 ){ + int iCnt, iPersist; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iCnt) + || TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &iPersist) + ){ + return TCL_ERROR; + } + pTest->eFault = iPersist?FAULT_INJECT_PERSISTENT:FAULT_INJECT_TRANSIENT; + pTest->iCnt = iCnt; + }else if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CNT PERSIST?"); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(iRet)); + break; + } + + case CMD_DELETE: { + Tcl_DeleteCommand(interp, Tcl_GetString(objv[0])); + break; + } + + case CMD_DEVCHAR: { + struct DeviceFlag { + char *zName; + int iValue; + } aFlag[] = { + { "default", -1 }, + { "atomic", SQLITE_IOCAP_ATOMIC }, + { "atomic512", SQLITE_IOCAP_ATOMIC512 }, + { "atomic1k", SQLITE_IOCAP_ATOMIC1K }, + { "atomic2k", SQLITE_IOCAP_ATOMIC2K }, + { "atomic4k", SQLITE_IOCAP_ATOMIC4K }, + { "atomic8k", SQLITE_IOCAP_ATOMIC8K }, + { "atomic16k", SQLITE_IOCAP_ATOMIC16K }, + { "atomic32k", SQLITE_IOCAP_ATOMIC32K }, + { "atomic64k", SQLITE_IOCAP_ATOMIC64K }, + { "sequential", SQLITE_IOCAP_SEQUENTIAL }, + { "safe_append", SQLITE_IOCAP_SAFE_APPEND }, + { "undeletable_when_open", SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN }, + { "powersafe_overwrite", SQLITE_IOCAP_POWERSAFE_OVERWRITE }, + { 0, 0 } + }; + Tcl_Obj *pRet; + int iFlag; + + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?ATTR-LIST?"); + return TCL_ERROR; + } + if( objc==3 ){ + int j; + int iNew = 0; + Tcl_Obj **flags = 0; + int nFlags = 0; + + if( Tcl_ListObjGetElements(interp, objv[2], &nFlags, &flags) ){ + return TCL_ERROR; + } + + for(j=0; j1 ){ + Tcl_AppendResult(interp, "bad flags: ", Tcl_GetString(objv[2]), 0); + return TCL_ERROR; + } + iNew |= aFlag[idx].iValue; + } + + p->iDevchar = iNew| 0x10000000; + } + + pRet = Tcl_NewObj(); + for(iFlag=0; iFlagiDevchar & aFlag[iFlag].iValue ){ + Tcl_ListObjAppendElement( + interp, pRet, Tcl_NewStringObj(aFlag[iFlag].zName, -1) + ); + } + } + Tcl_SetObjResult(interp, pRet); + + break; + } + + case CMD_SECTORSIZE: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?VALUE?"); + return TCL_ERROR; + } + if( objc==3 ){ + int iNew = 0; + if( Tcl_GetIntFromObj(interp, objv[2], &iNew) ){ + return TCL_ERROR; + } + p->iSectorsize = iNew; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(p->iSectorsize)); + break; + } + } + + return TCL_OK; +} + +static void testvfs_obj_del(ClientData cd){ + Testvfs *p = (Testvfs *)cd; + if( p->pScript ) Tcl_DecrRefCount(p->pScript); + sqlite3_vfs_unregister(p->pVfs); + ckfree((char *)p->pVfs); + ckfree((char *)p); +} + +/* +** Usage: testvfs VFSNAME ?SWITCHES? +** +** Switches are: +** +** -noshm BOOLEAN (True to omit shm methods. Default false) +** -default BOOLEAN (True to make the vfs default. Default false) +** +** This command creates two things when it is invoked: an SQLite VFS, and +** a Tcl command. Both are named VFSNAME. The VFS is installed. It is not +** installed as the default VFS. +** +** The VFS passes all file I/O calls through to the underlying VFS. +** +** Whenever the xShmMap method of the VFS +** is invoked, the SCRIPT is executed as follows: +** +** SCRIPT xShmMap FILENAME ID +** +** The value returned by the invocation of SCRIPT above is interpreted as +** an SQLite error code and returned to SQLite. Either a symbolic +** "SQLITE_OK" or numeric "0" value may be returned. +** +** The contents of the shared-memory buffer associated with a given file +** may be read and set using the following command: +** +** VFSNAME shm FILENAME ?NEWVALUE? +** +** When the xShmLock method is invoked by SQLite, the following script is +** run: +** +** SCRIPT xShmLock FILENAME ID LOCK +** +** where LOCK is of the form "OFFSET NBYTE lock/unlock shared/exclusive" +*/ +static int testvfs_cmd( + ClientData cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *CONST objv[] +){ + static sqlite3_vfs tvfs_vfs = { + 3, /* iVersion */ + 0, /* szOsFile */ + 0, /* mxPathname */ + 0, /* pNext */ + 0, /* zName */ + 0, /* pAppData */ + tvfsOpen, /* xOpen */ + tvfsDelete, /* xDelete */ + tvfsAccess, /* xAccess */ + tvfsFullPathname, /* xFullPathname */ +#ifndef SQLITE_OMIT_LOAD_EXTENSION + tvfsDlOpen, /* xDlOpen */ + tvfsDlError, /* xDlError */ + tvfsDlSym, /* xDlSym */ + tvfsDlClose, /* xDlClose */ +#else + 0, /* xDlOpen */ + 0, /* xDlError */ + 0, /* xDlSym */ + 0, /* xDlClose */ +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + tvfsRandomness, /* xRandomness */ + tvfsSleep, /* xSleep */ + tvfsCurrentTime, /* xCurrentTime */ + 0, /* xGetLastError */ + 0, /* xCurrentTimeInt64 */ + 0, /* xSetSystemCall */ + 0, /* xGetSystemCall */ + 0, /* xNextSystemCall */ + }; + + Testvfs *p; /* New object */ + sqlite3_vfs *pVfs; /* New VFS */ + char *zVfs; + int nByte; /* Bytes of space to allocate at p */ + + int i; + int isNoshm = 0; /* True if -noshm is passed */ + int isFullshm = 0; /* True if -fullshm is passed */ + int isDefault = 0; /* True if -default is passed */ + int szOsFile = 0; /* Value passed to -szosfile */ + int mxPathname = -1; /* Value passed to -mxpathname */ + int iVersion = 3; /* Value passed to -iversion */ + + if( objc<2 || 0!=(objc%2) ) goto bad_args; + for(i=2; i2 && 0==strncmp("-noshm", zSwitch, nSwitch) ){ + if( Tcl_GetBooleanFromObj(interp, objv[i+1], &isNoshm) ){ + return TCL_ERROR; + } + if( isNoshm ) isFullshm = 0; + } + else if( nSwitch>2 && 0==strncmp("-default", zSwitch, nSwitch) ){ + if( Tcl_GetBooleanFromObj(interp, objv[i+1], &isDefault) ){ + return TCL_ERROR; + } + } + else if( nSwitch>2 && 0==strncmp("-szosfile", zSwitch, nSwitch) ){ + if( Tcl_GetIntFromObj(interp, objv[i+1], &szOsFile) ){ + return TCL_ERROR; + } + } + else if( nSwitch>2 && 0==strncmp("-mxpathname", zSwitch, nSwitch) ){ + if( Tcl_GetIntFromObj(interp, objv[i+1], &mxPathname) ){ + return TCL_ERROR; + } + } + else if( nSwitch>2 && 0==strncmp("-iversion", zSwitch, nSwitch) ){ + if( Tcl_GetIntFromObj(interp, objv[i+1], &iVersion) ){ + return TCL_ERROR; + } + } + else if( nSwitch>2 && 0==strncmp("-fullshm", zSwitch, nSwitch) ){ + if( Tcl_GetBooleanFromObj(interp, objv[i+1], &isFullshm) ){ + return TCL_ERROR; + } + if( isFullshm ) isNoshm = 0; + } + else{ + goto bad_args; + } + } + + if( szOsFileiDevchar = -1; + p->iSectorsize = -1; + + /* Create the new object command before querying SQLite for a default VFS + ** to use for 'real' IO operations. This is because creating the new VFS + ** may delete an existing [testvfs] VFS of the same name. If such a VFS + ** is currently the default, the new [testvfs] may end up calling the + ** methods of a deleted object. + */ + Tcl_CreateObjCommand(interp, zVfs, testvfs_obj_cmd, p, testvfs_obj_del); + p->pParent = sqlite3_vfs_find(0); + p->interp = interp; + + p->zName = (char *)&p[1]; + memcpy(p->zName, zVfs, strlen(zVfs)+1); + + pVfs = (sqlite3_vfs *)ckalloc(sizeof(sqlite3_vfs)); + memcpy(pVfs, &tvfs_vfs, sizeof(sqlite3_vfs)); + pVfs->pAppData = (void *)p; + pVfs->iVersion = iVersion; + pVfs->zName = p->zName; + pVfs->mxPathname = p->pParent->mxPathname; + if( mxPathname>=0 && mxPathnamemxPathname ){ + pVfs->mxPathname = mxPathname; + } + pVfs->szOsFile = szOsFile; + p->pVfs = pVfs; + p->isNoshm = isNoshm; + p->isFullshm = isFullshm; + p->mask = TESTVFS_ALL_MASK; + + sqlite3_vfs_register(pVfs, isDefault); + + return TCL_OK; + + bad_args: + Tcl_WrongNumArgs(interp, 1, objv, "VFSNAME ?-noshm BOOL? ?-default BOOL? ?-mxpathname INT? ?-szosfile INT? ?-iversion INT?"); + return TCL_ERROR; +} + +int Sqlitetestvfs_Init(Tcl_Interp *interp){ + Tcl_CreateObjCommand(interp, "testvfs", testvfs_cmd, 0, 0); + return TCL_OK; +} + +#endif diff --git a/components/external/SQLite-3.8.1/src/test_vfstrace.c b/components/external/SQLite-3.8.1/src/test_vfstrace.c new file mode 100644 index 0000000000000000000000000000000000000000..0aacc01fe42e77feb858e4bed0cb7e04a435b210 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_vfstrace.c @@ -0,0 +1,887 @@ +/* +** 2011 March 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains code implements a VFS shim that writes diagnostic +** output for each VFS call, similar to "strace". +** +** USAGE: +** +** This source file exports a single symbol which is the name of a +** function: +** +** int vfstrace_register( +** const char *zTraceName, // Name of the newly constructed VFS +** const char *zOldVfsName, // Name of the underlying VFS +** int (*xOut)(const char*,void*), // Output routine. ex: fputs +** void *pOutArg, // 2nd argument to xOut. ex: stderr +** int makeDefault // Make the new VFS the default +** ); +** +** Applications that want to trace their VFS usage must provide a callback +** function with this prototype: +** +** int traceOutput(const char *zMessage, void *pAppData); +** +** This function will "output" the trace messages, where "output" can +** mean different things to different applications. The traceOutput function +** for the command-line shell (see shell.c) is "fputs" from the standard +** library, which means that all trace output is written on the stream +** specified by the second argument. In the case of the command-line shell +** the second argument is stderr. Other applications might choose to output +** trace information to a file, over a socket, or write it into a buffer. +** +** The vfstrace_register() function creates a new "shim" VFS named by +** the zTraceName parameter. A "shim" VFS is an SQLite backend that does +** not really perform the duties of a true backend, but simply filters or +** interprets VFS calls before passing them off to another VFS which does +** the actual work. In this case the other VFS - the one that does the +** real work - is identified by the second parameter, zOldVfsName. If +** the 2nd parameter is NULL then the default VFS is used. The common +** case is for the 2nd parameter to be NULL. +** +** The third and fourth parameters are the pointer to the output function +** and the second argument to the output function. For the SQLite +** command-line shell, when the -vfstrace option is used, these parameters +** are fputs and stderr, respectively. +** +** The fifth argument is true (non-zero) to cause the newly created VFS +** to become the default VFS. The common case is for the fifth parameter +** to be true. +** +** The call to vfstrace_register() simply creates the shim VFS that does +** tracing. The application must also arrange to use the new VFS for +** all database connections that are created and for which tracing is +** desired. This can be done by specifying the trace VFS using URI filename +** notation, or by specifying the trace VFS as the 4th parameter to +** sqlite3_open_v2() or by making the trace VFS be the default (by setting +** the 5th parameter of vfstrace_register() to 1). +** +** +** ENABLING VFSTRACE IN A COMMAND-LINE SHELL +** +** The SQLite command line shell implemented by the shell.c source file +** can be used with this module. To compile in -vfstrace support, first +** gather this file (test_vfstrace.c), the shell source file (shell.c), +** and the SQLite amalgamation source files (sqlite3.c, sqlite3.h) into +** the working directory. Then compile using a command like the following: +** +** gcc -o sqlite3 -Os -I. -DSQLITE_ENABLE_VFSTRACE \ +** -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE \ +** -DHAVE_READLINE -DHAVE_USLEEP=1 \ +** shell.c test_vfstrace.c sqlite3.c -ldl -lreadline -lncurses +** +** The gcc command above works on Linux and provides (in addition to the +** -vfstrace option) support for FTS3 and FTS4, RTREE, and command-line +** editing using the readline library. The command-line shell does not +** use threads so we added -DSQLITE_THREADSAFE=0 just to make the code +** run a little faster. For compiling on a Mac, you'll probably need +** to omit the -DHAVE_READLINE, the -lreadline, and the -lncurses options. +** The compilation could be simplified to just this: +** +** gcc -DSQLITE_ENABLE_VFSTRACE \ +** shell.c test_vfstrace.c sqlite3.c -ldl -lpthread +** +** In this second example, all unnecessary options have been removed +** Note that since the code is now threadsafe, we had to add the -lpthread +** option to pull in the pthreads library. +** +** To cross-compile for windows using MinGW, a command like this might +** work: +** +** /opt/mingw/bin/i386-mingw32msvc-gcc -o sqlite3.exe -Os -I \ +** -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_VFSTRACE \ +** shell.c test_vfstrace.c sqlite3.c +** +** Similar compiler commands will work on different systems. The key +** invariants are (1) you must have -DSQLITE_ENABLE_VFSTRACE so that +** the shell.c source file will know to include the -vfstrace command-line +** option and (2) you must compile and link the three source files +** shell,c, test_vfstrace.c, and sqlite3.c. +*/ +#include +#include +#include "sqlite3.h" + +/* +** An instance of this structure is attached to the each trace VFS to +** provide auxiliary information. +*/ +typedef struct vfstrace_info vfstrace_info; +struct vfstrace_info { + sqlite3_vfs *pRootVfs; /* The underlying real VFS */ + int (*xOut)(const char*, void*); /* Send output here */ + void *pOutArg; /* First argument to xOut */ + const char *zVfsName; /* Name of this trace-VFS */ + sqlite3_vfs *pTraceVfs; /* Pointer back to the trace VFS */ +}; + +/* +** The sqlite3_file object for the trace VFS +*/ +typedef struct vfstrace_file vfstrace_file; +struct vfstrace_file { + sqlite3_file base; /* Base class. Must be first */ + vfstrace_info *pInfo; /* The trace-VFS to which this file belongs */ + const char *zFName; /* Base name of the file */ + sqlite3_file *pReal; /* The real underlying file */ +}; + +/* +** Method declarations for vfstrace_file. +*/ +static int vfstraceClose(sqlite3_file*); +static int vfstraceRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); +static int vfstraceWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64); +static int vfstraceTruncate(sqlite3_file*, sqlite3_int64 size); +static int vfstraceSync(sqlite3_file*, int flags); +static int vfstraceFileSize(sqlite3_file*, sqlite3_int64 *pSize); +static int vfstraceLock(sqlite3_file*, int); +static int vfstraceUnlock(sqlite3_file*, int); +static int vfstraceCheckReservedLock(sqlite3_file*, int *); +static int vfstraceFileControl(sqlite3_file*, int op, void *pArg); +static int vfstraceSectorSize(sqlite3_file*); +static int vfstraceDeviceCharacteristics(sqlite3_file*); +static int vfstraceShmLock(sqlite3_file*,int,int,int); +static int vfstraceShmMap(sqlite3_file*,int,int,int, void volatile **); +static void vfstraceShmBarrier(sqlite3_file*); +static int vfstraceShmUnmap(sqlite3_file*,int); + +/* +** Method declarations for vfstrace_vfs. +*/ +static int vfstraceOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); +static int vfstraceDelete(sqlite3_vfs*, const char *zName, int syncDir); +static int vfstraceAccess(sqlite3_vfs*, const char *zName, int flags, int *); +static int vfstraceFullPathname(sqlite3_vfs*, const char *zName, int, char *); +static void *vfstraceDlOpen(sqlite3_vfs*, const char *zFilename); +static void vfstraceDlError(sqlite3_vfs*, int nByte, char *zErrMsg); +static void (*vfstraceDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void); +static void vfstraceDlClose(sqlite3_vfs*, void*); +static int vfstraceRandomness(sqlite3_vfs*, int nByte, char *zOut); +static int vfstraceSleep(sqlite3_vfs*, int microseconds); +static int vfstraceCurrentTime(sqlite3_vfs*, double*); +static int vfstraceGetLastError(sqlite3_vfs*, int, char*); +static int vfstraceCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); +static int vfstraceSetSystemCall(sqlite3_vfs*,const char*, sqlite3_syscall_ptr); +static sqlite3_syscall_ptr vfstraceGetSystemCall(sqlite3_vfs*, const char *); +static const char *vfstraceNextSystemCall(sqlite3_vfs*, const char *zName); + +/* +** Return a pointer to the tail of the pathname. Examples: +** +** /home/drh/xyzzy.txt -> xyzzy.txt +** xyzzy.txt -> xyzzy.txt +*/ +static const char *fileTail(const char *z){ + int i; + if( z==0 ) return 0; + i = strlen(z)-1; + while( i>0 && z[i-1]!='/' ){ i--; } + return &z[i]; +} + +/* +** Send trace output defined by zFormat and subsequent arguments. +*/ +static void vfstrace_printf( + vfstrace_info *pInfo, + const char *zFormat, + ... +){ + va_list ap; + char *zMsg; + va_start(ap, zFormat); + zMsg = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + pInfo->xOut(zMsg, pInfo->pOutArg); + sqlite3_free(zMsg); +} + +/* +** Convert value rc into a string and print it using zFormat. zFormat +** should have exactly one %s +*/ +static void vfstrace_print_errcode( + vfstrace_info *pInfo, + const char *zFormat, + int rc +){ + char zBuf[50]; + char *zVal; + switch( rc ){ + case SQLITE_OK: zVal = "SQLITE_OK"; break; + case SQLITE_ERROR: zVal = "SQLITE_ERROR"; break; + case SQLITE_PERM: zVal = "SQLITE_PERM"; break; + case SQLITE_ABORT: zVal = "SQLITE_ABORT"; break; + case SQLITE_BUSY: zVal = "SQLITE_BUSY"; break; + case SQLITE_NOMEM: zVal = "SQLITE_NOMEM"; break; + case SQLITE_READONLY: zVal = "SQLITE_READONLY"; break; + case SQLITE_INTERRUPT: zVal = "SQLITE_INTERRUPT"; break; + case SQLITE_IOERR: zVal = "SQLITE_IOERR"; break; + case SQLITE_CORRUPT: zVal = "SQLITE_CORRUPT"; break; + case SQLITE_FULL: zVal = "SQLITE_FULL"; break; + case SQLITE_CANTOPEN: zVal = "SQLITE_CANTOPEN"; break; + case SQLITE_PROTOCOL: zVal = "SQLITE_PROTOCOL"; break; + case SQLITE_EMPTY: zVal = "SQLITE_EMPTY"; break; + case SQLITE_SCHEMA: zVal = "SQLITE_SCHEMA"; break; + case SQLITE_CONSTRAINT: zVal = "SQLITE_CONSTRAINT"; break; + case SQLITE_MISMATCH: zVal = "SQLITE_MISMATCH"; break; + case SQLITE_MISUSE: zVal = "SQLITE_MISUSE"; break; + case SQLITE_NOLFS: zVal = "SQLITE_NOLFS"; break; + case SQLITE_IOERR_READ: zVal = "SQLITE_IOERR_READ"; break; + case SQLITE_IOERR_SHORT_READ: zVal = "SQLITE_IOERR_SHORT_READ"; break; + case SQLITE_IOERR_WRITE: zVal = "SQLITE_IOERR_WRITE"; break; + case SQLITE_IOERR_FSYNC: zVal = "SQLITE_IOERR_FSYNC"; break; + case SQLITE_IOERR_DIR_FSYNC: zVal = "SQLITE_IOERR_DIR_FSYNC"; break; + case SQLITE_IOERR_TRUNCATE: zVal = "SQLITE_IOERR_TRUNCATE"; break; + case SQLITE_IOERR_FSTAT: zVal = "SQLITE_IOERR_FSTAT"; break; + case SQLITE_IOERR_UNLOCK: zVal = "SQLITE_IOERR_UNLOCK"; break; + case SQLITE_IOERR_RDLOCK: zVal = "SQLITE_IOERR_RDLOCK"; break; + case SQLITE_IOERR_DELETE: zVal = "SQLITE_IOERR_DELETE"; break; + case SQLITE_IOERR_BLOCKED: zVal = "SQLITE_IOERR_BLOCKED"; break; + case SQLITE_IOERR_NOMEM: zVal = "SQLITE_IOERR_NOMEM"; break; + case SQLITE_IOERR_ACCESS: zVal = "SQLITE_IOERR_ACCESS"; break; + case SQLITE_IOERR_CHECKRESERVEDLOCK: + zVal = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; + case SQLITE_IOERR_LOCK: zVal = "SQLITE_IOERR_LOCK"; break; + case SQLITE_IOERR_CLOSE: zVal = "SQLITE_IOERR_CLOSE"; break; + case SQLITE_IOERR_DIR_CLOSE: zVal = "SQLITE_IOERR_DIR_CLOSE"; break; + case SQLITE_IOERR_SHMOPEN: zVal = "SQLITE_IOERR_SHMOPEN"; break; + case SQLITE_IOERR_SHMSIZE: zVal = "SQLITE_IOERR_SHMSIZE"; break; + case SQLITE_IOERR_SHMLOCK: zVal = "SQLITE_IOERR_SHMLOCK"; break; + case SQLITE_LOCKED_SHAREDCACHE: zVal = "SQLITE_LOCKED_SHAREDCACHE"; break; + case SQLITE_BUSY_RECOVERY: zVal = "SQLITE_BUSY_RECOVERY"; break; + case SQLITE_CANTOPEN_NOTEMPDIR: zVal = "SQLITE_CANTOPEN_NOTEMPDIR"; break; + default: { + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", rc); + zVal = zBuf; + break; + } + } + vfstrace_printf(pInfo, zFormat, zVal); +} + +/* +** Append to a buffer. +*/ +static void strappend(char *z, int *pI, const char *zAppend){ + int i = *pI; + while( zAppend[0] ){ z[i++] = *(zAppend++); } + z[i] = 0; + *pI = i; +} + +/* +** Close an vfstrace-file. +*/ +static int vfstraceClose(sqlite3_file *pFile){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xClose(%s)", pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xClose(p->pReal); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + if( rc==SQLITE_OK ){ + sqlite3_free((void*)p->base.pMethods); + p->base.pMethods = 0; + } + return rc; +} + +/* +** Read data from an vfstrace-file. +*/ +static int vfstraceRead( + sqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xRead(%s,n=%d,ofst=%lld)", + pInfo->zVfsName, p->zFName, iAmt, iOfst); + rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Write data to an vfstrace-file. +*/ +static int vfstraceWrite( + sqlite3_file *pFile, + const void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xWrite(%s,n=%d,ofst=%lld)", + pInfo->zVfsName, p->zFName, iAmt, iOfst); + rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Truncate an vfstrace-file. +*/ +static int vfstraceTruncate(sqlite3_file *pFile, sqlite_int64 size){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xTruncate(%s,%lld)", pInfo->zVfsName, p->zFName, + size); + rc = p->pReal->pMethods->xTruncate(p->pReal, size); + vfstrace_printf(pInfo, " -> %d\n", rc); + return rc; +} + +/* +** Sync an vfstrace-file. +*/ +static int vfstraceSync(sqlite3_file *pFile, int flags){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + int i; + char zBuf[100]; + memcpy(zBuf, "|0", 3); + i = 0; + if( flags & SQLITE_SYNC_FULL ) strappend(zBuf, &i, "|FULL"); + else if( flags & SQLITE_SYNC_NORMAL ) strappend(zBuf, &i, "|NORMAL"); + if( flags & SQLITE_SYNC_DATAONLY ) strappend(zBuf, &i, "|DATAONLY"); + if( flags & ~(SQLITE_SYNC_FULL|SQLITE_SYNC_DATAONLY) ){ + sqlite3_snprintf(sizeof(zBuf)-i, &zBuf[i], "|0x%x", flags); + } + vfstrace_printf(pInfo, "%s.xSync(%s,%s)", pInfo->zVfsName, p->zFName, + &zBuf[1]); + rc = p->pReal->pMethods->xSync(p->pReal, flags); + vfstrace_printf(pInfo, " -> %d\n", rc); + return rc; +} + +/* +** Return the current file-size of an vfstrace-file. +*/ +static int vfstraceFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xFileSize(%s)", pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); + vfstrace_print_errcode(pInfo, " -> %s,", rc); + vfstrace_printf(pInfo, " size=%lld\n", *pSize); + return rc; +} + +/* +** Return the name of a lock. +*/ +static const char *lockName(int eLock){ + const char *azLockNames[] = { + "NONE", "SHARED", "RESERVED", "PENDING", "EXCLUSIVE" + }; + if( eLock<0 || eLock>=sizeof(azLockNames)/sizeof(azLockNames[0]) ){ + return "???"; + }else{ + return azLockNames[eLock]; + } +} + +/* +** Lock an vfstrace-file. +*/ +static int vfstraceLock(sqlite3_file *pFile, int eLock){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xLock(%s,%s)", pInfo->zVfsName, p->zFName, + lockName(eLock)); + rc = p->pReal->pMethods->xLock(p->pReal, eLock); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Unlock an vfstrace-file. +*/ +static int vfstraceUnlock(sqlite3_file *pFile, int eLock){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xUnlock(%s,%s)", pInfo->zVfsName, p->zFName, + lockName(eLock)); + rc = p->pReal->pMethods->xUnlock(p->pReal, eLock); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Check if another file-handle holds a RESERVED lock on an vfstrace-file. +*/ +static int vfstraceCheckReservedLock(sqlite3_file *pFile, int *pResOut){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xCheckReservedLock(%s,%d)", + pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); + vfstrace_print_errcode(pInfo, " -> %s", rc); + vfstrace_printf(pInfo, ", out=%d\n", *pResOut); + return rc; +} + +/* +** File control method. For custom operations on an vfstrace-file. +*/ +static int vfstraceFileControl(sqlite3_file *pFile, int op, void *pArg){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + char zBuf[100]; + char *zOp; + switch( op ){ + case SQLITE_FCNTL_LOCKSTATE: zOp = "LOCKSTATE"; break; + case SQLITE_GET_LOCKPROXYFILE: zOp = "GET_LOCKPROXYFILE"; break; + case SQLITE_SET_LOCKPROXYFILE: zOp = "SET_LOCKPROXYFILE"; break; + case SQLITE_LAST_ERRNO: zOp = "LAST_ERRNO"; break; + case SQLITE_FCNTL_SIZE_HINT: { + sqlite3_snprintf(sizeof(zBuf), zBuf, "SIZE_HINT,%lld", + *(sqlite3_int64*)pArg); + zOp = zBuf; + break; + } + case SQLITE_FCNTL_CHUNK_SIZE: { + sqlite3_snprintf(sizeof(zBuf), zBuf, "CHUNK_SIZE,%d", *(int*)pArg); + zOp = zBuf; + break; + } + case SQLITE_FCNTL_FILE_POINTER: zOp = "FILE_POINTER"; break; + case SQLITE_FCNTL_SYNC_OMITTED: zOp = "SYNC_OMITTED"; break; + case SQLITE_FCNTL_WIN32_AV_RETRY: zOp = "WIN32_AV_RETRY"; break; + case SQLITE_FCNTL_PERSIST_WAL: zOp = "PERSIST_WAL"; break; + case SQLITE_FCNTL_OVERWRITE: zOp = "OVERWRITE"; break; + case SQLITE_FCNTL_VFSNAME: zOp = "VFSNAME"; break; + case SQLITE_FCNTL_TEMPFILENAME: zOp = "TEMPFILENAME"; break; + case 0xca093fa0: zOp = "DB_UNCHANGED"; break; + case SQLITE_FCNTL_PRAGMA: { + const char *const* a = (const char*const*)pArg; + sqlite3_snprintf(sizeof(zBuf), zBuf, "PRAGMA,[%s,%s]",a[1],a[2]); + zOp = zBuf; + break; + } + default: { + sqlite3_snprintf(sizeof zBuf, zBuf, "%d", op); + zOp = zBuf; + break; + } + } + vfstrace_printf(pInfo, "%s.xFileControl(%s,%s)", + pInfo->zVfsName, p->zFName, zOp); + rc = p->pReal->pMethods->xFileControl(p->pReal, op, pArg); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){ + *(char**)pArg = sqlite3_mprintf("vfstrace.%s/%z", + pInfo->zVfsName, *(char**)pArg); + } + if( (op==SQLITE_FCNTL_PRAGMA || op==SQLITE_FCNTL_TEMPFILENAME) + && rc==SQLITE_OK && *(char**)pArg ){ + vfstrace_printf(pInfo, "%s.xFileControl(%s,%s) returns %s", + pInfo->zVfsName, p->zFName, zOp, *(char**)pArg); + } + return rc; +} + +/* +** Return the sector-size in bytes for an vfstrace-file. +*/ +static int vfstraceSectorSize(sqlite3_file *pFile){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xSectorSize(%s)", pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xSectorSize(p->pReal); + vfstrace_printf(pInfo, " -> %d\n", rc); + return rc; +} + +/* +** Return the device characteristic flags supported by an vfstrace-file. +*/ +static int vfstraceDeviceCharacteristics(sqlite3_file *pFile){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xDeviceCharacteristics(%s)", + pInfo->zVfsName, p->zFName); + rc = p->pReal->pMethods->xDeviceCharacteristics(p->pReal); + vfstrace_printf(pInfo, " -> 0x%08x\n", rc); + return rc; +} + +/* +** Shared-memory operations. +*/ +static int vfstraceShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + char zLck[100]; + int i = 0; + memcpy(zLck, "|0", 3); + if( flags & SQLITE_SHM_UNLOCK ) strappend(zLck, &i, "|UNLOCK"); + if( flags & SQLITE_SHM_LOCK ) strappend(zLck, &i, "|LOCK"); + if( flags & SQLITE_SHM_SHARED ) strappend(zLck, &i, "|SHARED"); + if( flags & SQLITE_SHM_EXCLUSIVE ) strappend(zLck, &i, "|EXCLUSIVE"); + if( flags & ~(0xf) ){ + sqlite3_snprintf(sizeof(zLck)-i, &zLck[i], "|0x%x", flags); + } + vfstrace_printf(pInfo, "%s.xShmLock(%s,ofst=%d,n=%d,%s)", + pInfo->zVfsName, p->zFName, ofst, n, &zLck[1]); + rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} +static int vfstraceShmMap( + sqlite3_file *pFile, + int iRegion, + int szRegion, + int isWrite, + void volatile **pp +){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xShmMap(%s,iRegion=%d,szRegion=%d,isWrite=%d,*)", + pInfo->zVfsName, p->zFName, iRegion, szRegion, isWrite); + rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} +static void vfstraceShmBarrier(sqlite3_file *pFile){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + vfstrace_printf(pInfo, "%s.xShmBarrier(%s)\n", pInfo->zVfsName, p->zFName); + p->pReal->pMethods->xShmBarrier(p->pReal); +} +static int vfstraceShmUnmap(sqlite3_file *pFile, int delFlag){ + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = p->pInfo; + int rc; + vfstrace_printf(pInfo, "%s.xShmUnmap(%s,delFlag=%d)", + pInfo->zVfsName, p->zFName, delFlag); + rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + + + +/* +** Open an vfstrace file handle. +*/ +static int vfstraceOpen( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_file *pFile, + int flags, + int *pOutFlags +){ + int rc; + vfstrace_file *p = (vfstrace_file *)pFile; + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + p->pInfo = pInfo; + p->zFName = zName ? fileTail(zName) : ""; + p->pReal = (sqlite3_file *)&p[1]; + rc = pRoot->xOpen(pRoot, zName, p->pReal, flags, pOutFlags); + vfstrace_printf(pInfo, "%s.xOpen(%s,flags=0x%x)", + pInfo->zVfsName, p->zFName, flags); + if( p->pReal->pMethods ){ + sqlite3_io_methods *pNew = sqlite3_malloc( sizeof(*pNew) ); + const sqlite3_io_methods *pSub = p->pReal->pMethods; + memset(pNew, 0, sizeof(*pNew)); + pNew->iVersion = pSub->iVersion; + pNew->xClose = vfstraceClose; + pNew->xRead = vfstraceRead; + pNew->xWrite = vfstraceWrite; + pNew->xTruncate = vfstraceTruncate; + pNew->xSync = vfstraceSync; + pNew->xFileSize = vfstraceFileSize; + pNew->xLock = vfstraceLock; + pNew->xUnlock = vfstraceUnlock; + pNew->xCheckReservedLock = vfstraceCheckReservedLock; + pNew->xFileControl = vfstraceFileControl; + pNew->xSectorSize = vfstraceSectorSize; + pNew->xDeviceCharacteristics = vfstraceDeviceCharacteristics; + if( pNew->iVersion>=2 ){ + pNew->xShmMap = pSub->xShmMap ? vfstraceShmMap : 0; + pNew->xShmLock = pSub->xShmLock ? vfstraceShmLock : 0; + pNew->xShmBarrier = pSub->xShmBarrier ? vfstraceShmBarrier : 0; + pNew->xShmUnmap = pSub->xShmUnmap ? vfstraceShmUnmap : 0; + } + pFile->pMethods = pNew; + } + vfstrace_print_errcode(pInfo, " -> %s", rc); + if( pOutFlags ){ + vfstrace_printf(pInfo, ", outFlags=0x%x\n", *pOutFlags); + }else{ + vfstrace_printf(pInfo, "\n"); + } + return rc; +} + +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int vfstraceDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + int rc; + vfstrace_printf(pInfo, "%s.xDelete(\"%s\",%d)", + pInfo->zVfsName, zPath, dirSync); + rc = pRoot->xDelete(pRoot, zPath, dirSync); + vfstrace_print_errcode(pInfo, " -> %s\n", rc); + return rc; +} + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +*/ +static int vfstraceAccess( + sqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + int rc; + vfstrace_printf(pInfo, "%s.xDelete(\"%s\",%d)", + pInfo->zVfsName, zPath, flags); + rc = pRoot->xAccess(pRoot, zPath, flags, pResOut); + vfstrace_print_errcode(pInfo, " -> %s", rc); + vfstrace_printf(pInfo, ", out=%d\n", *pResOut); + return rc; +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (DEVSYM_MAX_PATHNAME+1) bytes. +*/ +static int vfstraceFullPathname( + sqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + int rc; + vfstrace_printf(pInfo, "%s.xFullPathname(\"%s\")", + pInfo->zVfsName, zPath); + rc = pRoot->xFullPathname(pRoot, zPath, nOut, zOut); + vfstrace_print_errcode(pInfo, " -> %s", rc); + vfstrace_printf(pInfo, ", out=\"%.*s\"\n", nOut, zOut); + return rc; +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *vfstraceDlOpen(sqlite3_vfs *pVfs, const char *zPath){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xDlOpen(\"%s\")\n", pInfo->zVfsName, zPath); + return pRoot->xDlOpen(pRoot, zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void vfstraceDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xDlError(%d)", pInfo->zVfsName, nByte); + pRoot->xDlError(pRoot, nByte, zErrMsg); + vfstrace_printf(pInfo, " -> \"%s\"", zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*vfstraceDlSym(sqlite3_vfs *pVfs,void *p,const char *zSym))(void){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xDlSym(\"%s\")\n", pInfo->zVfsName, zSym); + return pRoot->xDlSym(pRoot, p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void vfstraceDlClose(sqlite3_vfs *pVfs, void *pHandle){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xDlOpen()\n", pInfo->zVfsName); + pRoot->xDlClose(pRoot, pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int vfstraceRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + vfstrace_printf(pInfo, "%s.xRandomness(%d)\n", pInfo->zVfsName, nByte); + return pRoot->xRandomness(pRoot, nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int vfstraceSleep(sqlite3_vfs *pVfs, int nMicro){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xSleep(pRoot, nMicro); +} + +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int vfstraceCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xCurrentTime(pRoot, pTimeOut); +} +static int vfstraceCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xCurrentTimeInt64(pRoot, pTimeOut); +} + +/* +** Return th3 emost recent error code and message +*/ +static int vfstraceGetLastError(sqlite3_vfs *pVfs, int iErr, char *zErr){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xGetLastError(pRoot, iErr, zErr); +} + +/* +** Override system calls. +*/ +static int vfstraceSetSystemCall( + sqlite3_vfs *pVfs, + const char *zName, + sqlite3_syscall_ptr pFunc +){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xSetSystemCall(pRoot, zName, pFunc); +} +static sqlite3_syscall_ptr vfstraceGetSystemCall( + sqlite3_vfs *pVfs, + const char *zName +){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xGetSystemCall(pRoot, zName); +} +static const char *vfstraceNextSystemCall(sqlite3_vfs *pVfs, const char *zName){ + vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; + sqlite3_vfs *pRoot = pInfo->pRootVfs; + return pRoot->xNextSystemCall(pRoot, zName); +} + + +/* +** Clients invoke this routine to construct a new trace-vfs shim. +** +** Return SQLITE_OK on success. +** +** SQLITE_NOMEM is returned in the case of a memory allocation error. +** SQLITE_NOTFOUND is returned if zOldVfsName does not exist. +*/ +int vfstrace_register( + const char *zTraceName, /* Name of the newly constructed VFS */ + const char *zOldVfsName, /* Name of the underlying VFS */ + int (*xOut)(const char*,void*), /* Output routine. ex: fputs */ + void *pOutArg, /* 2nd argument to xOut. ex: stderr */ + int makeDefault /* True to make the new VFS the default */ +){ + sqlite3_vfs *pNew; + sqlite3_vfs *pRoot; + vfstrace_info *pInfo; + int nName; + int nByte; + + pRoot = sqlite3_vfs_find(zOldVfsName); + if( pRoot==0 ) return SQLITE_NOTFOUND; + nName = strlen(zTraceName); + nByte = sizeof(*pNew) + sizeof(*pInfo) + nName + 1; + pNew = sqlite3_malloc( nByte ); + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, nByte); + pInfo = (vfstrace_info*)&pNew[1]; + pNew->iVersion = pRoot->iVersion; + pNew->szOsFile = pRoot->szOsFile + sizeof(vfstrace_file); + pNew->mxPathname = pRoot->mxPathname; + pNew->zName = (char*)&pInfo[1]; + memcpy((char*)&pInfo[1], zTraceName, nName+1); + pNew->pAppData = pInfo; + pNew->xOpen = vfstraceOpen; + pNew->xDelete = vfstraceDelete; + pNew->xAccess = vfstraceAccess; + pNew->xFullPathname = vfstraceFullPathname; + pNew->xDlOpen = pRoot->xDlOpen==0 ? 0 : vfstraceDlOpen; + pNew->xDlError = pRoot->xDlError==0 ? 0 : vfstraceDlError; + pNew->xDlSym = pRoot->xDlSym==0 ? 0 : vfstraceDlSym; + pNew->xDlClose = pRoot->xDlClose==0 ? 0 : vfstraceDlClose; + pNew->xRandomness = vfstraceRandomness; + pNew->xSleep = vfstraceSleep; + pNew->xCurrentTime = vfstraceCurrentTime; + pNew->xGetLastError = pRoot->xGetLastError==0 ? 0 : vfstraceGetLastError; + if( pNew->iVersion>=2 ){ + pNew->xCurrentTimeInt64 = pRoot->xCurrentTimeInt64==0 ? 0 : + vfstraceCurrentTimeInt64; + if( pNew->iVersion>=3 ){ + pNew->xSetSystemCall = pRoot->xSetSystemCall==0 ? 0 : + vfstraceSetSystemCall; + pNew->xGetSystemCall = pRoot->xGetSystemCall==0 ? 0 : + vfstraceGetSystemCall; + pNew->xNextSystemCall = pRoot->xNextSystemCall==0 ? 0 : + vfstraceNextSystemCall; + } + } + pInfo->pRootVfs = pRoot; + pInfo->xOut = xOut; + pInfo->pOutArg = pOutArg; + pInfo->zVfsName = pNew->zName; + pInfo->pTraceVfs = pNew; + vfstrace_printf(pInfo, "%s.enabled_for(\"%s\")\n", + pInfo->zVfsName, pRoot->zName); + return sqlite3_vfs_register(pNew, makeDefault); +} diff --git a/components/external/SQLite-3.8.1/src/test_wsd.c b/components/external/SQLite-3.8.1/src/test_wsd.c new file mode 100644 index 0000000000000000000000000000000000000000..99e4a056581f58f4536fdb5a5df75c74698a8162 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/test_wsd.c @@ -0,0 +1,84 @@ +/* +** 2008 September 1 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** The code in this file contains sample implementations of the +** sqlite3_wsd_init() and sqlite3_wsd_find() functions required if the +** SQLITE_OMIT_WSD symbol is defined at build time. +*/ + +#if defined(SQLITE_OMIT_WSD) && defined(SQLITE_TEST) + +#include "sqliteInt.h" + +#define PLS_HASHSIZE 43 + +typedef struct ProcessLocalStorage ProcessLocalStorage; +typedef struct ProcessLocalVar ProcessLocalVar; + +struct ProcessLocalStorage { + ProcessLocalVar *aData[PLS_HASHSIZE]; + int nFree; + u8 *pFree; +}; + +struct ProcessLocalVar { + void *pKey; + ProcessLocalVar *pNext; +}; + +static ProcessLocalStorage *pGlobal = 0; + +int sqlite3_wsd_init(int N, int J){ + if( !pGlobal ){ + int nMalloc = N + sizeof(ProcessLocalStorage) + J*sizeof(ProcessLocalVar); + pGlobal = (ProcessLocalStorage *)malloc(nMalloc); + if( pGlobal ){ + memset(pGlobal, 0, sizeof(ProcessLocalStorage)); + pGlobal->nFree = nMalloc - sizeof(ProcessLocalStorage); + pGlobal->pFree = (u8 *)&pGlobal[1]; + } + } + + return pGlobal ? SQLITE_OK : SQLITE_NOMEM; +} + +void *sqlite3_wsd_find(void *K, int L){ + int i; + int iHash = 0; + ProcessLocalVar *pVar; + + /* Calculate a hash of K */ + for(i=0; iaData[iHash]; pVar && pVar->pKey!=K; pVar=pVar->pNext); + + /* If no entry for K was found, create and populate a new one. */ + if( !pVar ){ + int nByte = ROUND8(sizeof(ProcessLocalVar) + L); + assert( pGlobal->nFree>=nByte ); + pVar = (ProcessLocalVar *)pGlobal->pFree; + pVar->pKey = K; + pVar->pNext = pGlobal->aData[iHash]; + pGlobal->aData[iHash] = pVar; + pGlobal->nFree -= nByte; + pGlobal->pFree += nByte; + memcpy(&pVar[1], K, L); + } + + return (void *)&pVar[1]; +} + +#endif diff --git a/components/external/SQLite-3.8.1/src/tokenize.c b/components/external/SQLite-3.8.1/src/tokenize.c new file mode 100644 index 0000000000000000000000000000000000000000..d26157f7d232d8132d0a3612f0f504c04896e643 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/tokenize.c @@ -0,0 +1,524 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** An tokenizer for SQL +** +** This file contains C code that splits an SQL input string up into +** individual tokens and sends those tokens one-by-one over to the +** parser for analysis. +*/ +#include "sqliteInt.h" +#include + +/* +** The charMap() macro maps alphabetic characters into their +** lower-case ASCII equivalent. On ASCII machines, this is just +** an upper-to-lower case map. On EBCDIC machines we also need +** to adjust the encoding. Only alphabetic characters and underscores +** need to be translated. +*/ +#ifdef SQLITE_ASCII +# define charMap(X) sqlite3UpperToLower[(unsigned char)X] +#endif +#ifdef SQLITE_EBCDIC +# define charMap(X) ebcdicToAscii[(unsigned char)X] +const unsigned char ebcdicToAscii[] = { +/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */ + 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */ + 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */ + 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ + 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */ + 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */ + 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */ +}; +#endif + +/* +** The sqlite3KeywordCode function looks up an identifier to determine if +** it is a keyword. If it is a keyword, the token code of that keyword is +** returned. If the input is not a keyword, TK_ID is returned. +** +** The implementation of this routine was generated by a program, +** mkkeywordhash.h, located in the tool subdirectory of the distribution. +** The output of the mkkeywordhash.c program is written into a file +** named keywordhash.h and then included into this source file by +** the #include below. +*/ +#include "keywordhash.h" + + +/* +** If X is a character that can be used in an identifier then +** IdChar(X) will be true. Otherwise it is false. +** +** For ASCII, any character with the high-order bit set is +** allowed in an identifier. For 7-bit characters, +** sqlite3IsIdChar[X] must be 1. +** +** For EBCDIC, the rules are more complex but have the same +** end result. +** +** Ticket #1066. the SQL standard does not allow '$' in the +** middle of identfiers. But many SQL implementations do. +** SQLite will allow '$' in identifiers for compatibility. +** But the feature is undocumented. +*/ +#ifdef SQLITE_ASCII +#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) +#endif +#ifdef SQLITE_EBCDIC +const char sqlite3IsEbcdicIdChar[] = { +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */ + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */ + 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */ + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */ +}; +#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) +#endif + + +/* +** Return the length of the token that begins at z[0]. +** Store the token type in *tokenType before returning. +*/ +int sqlite3GetToken(const unsigned char *z, int *tokenType){ + int i, c; + switch( *z ){ + case ' ': case '\t': case '\n': case '\f': case '\r': { + testcase( z[0]==' ' ); + testcase( z[0]=='\t' ); + testcase( z[0]=='\n' ); + testcase( z[0]=='\f' ); + testcase( z[0]=='\r' ); + for(i=1; sqlite3Isspace(z[i]); i++){} + *tokenType = TK_SPACE; + return i; + } + case '-': { + if( z[1]=='-' ){ + for(i=2; (c=z[i])!=0 && c!='\n'; i++){} + *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ + return i; + } + *tokenType = TK_MINUS; + return 1; + } + case '(': { + *tokenType = TK_LP; + return 1; + } + case ')': { + *tokenType = TK_RP; + return 1; + } + case ';': { + *tokenType = TK_SEMI; + return 1; + } + case '+': { + *tokenType = TK_PLUS; + return 1; + } + case '*': { + *tokenType = TK_STAR; + return 1; + } + case '/': { + if( z[1]!='*' || z[2]==0 ){ + *tokenType = TK_SLASH; + return 1; + } + for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){} + if( c ) i++; + *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ + return i; + } + case '%': { + *tokenType = TK_REM; + return 1; + } + case '=': { + *tokenType = TK_EQ; + return 1 + (z[1]=='='); + } + case '<': { + if( (c=z[1])=='=' ){ + *tokenType = TK_LE; + return 2; + }else if( c=='>' ){ + *tokenType = TK_NE; + return 2; + }else if( c=='<' ){ + *tokenType = TK_LSHIFT; + return 2; + }else{ + *tokenType = TK_LT; + return 1; + } + } + case '>': { + if( (c=z[1])=='=' ){ + *tokenType = TK_GE; + return 2; + }else if( c=='>' ){ + *tokenType = TK_RSHIFT; + return 2; + }else{ + *tokenType = TK_GT; + return 1; + } + } + case '!': { + if( z[1]!='=' ){ + *tokenType = TK_ILLEGAL; + return 2; + }else{ + *tokenType = TK_NE; + return 2; + } + } + case '|': { + if( z[1]!='|' ){ + *tokenType = TK_BITOR; + return 1; + }else{ + *tokenType = TK_CONCAT; + return 2; + } + } + case ',': { + *tokenType = TK_COMMA; + return 1; + } + case '&': { + *tokenType = TK_BITAND; + return 1; + } + case '~': { + *tokenType = TK_BITNOT; + return 1; + } + case '`': + case '\'': + case '"': { + int delim = z[0]; + testcase( delim=='`' ); + testcase( delim=='\'' ); + testcase( delim=='"' ); + for(i=1; (c=z[i])!=0; i++){ + if( c==delim ){ + if( z[i+1]==delim ){ + i++; + }else{ + break; + } + } + } + if( c=='\'' ){ + *tokenType = TK_STRING; + return i+1; + }else if( c!=0 ){ + *tokenType = TK_ID; + return i+1; + }else{ + *tokenType = TK_ILLEGAL; + return i; + } + } + case '.': { +#ifndef SQLITE_OMIT_FLOATING_POINT + if( !sqlite3Isdigit(z[1]) ) +#endif + { + *tokenType = TK_DOT; + return 1; + } + /* If the next character is a digit, this is a floating point + ** number that begins with ".". Fall thru into the next case */ + } + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' ); + testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' ); + testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' ); + testcase( z[0]=='9' ); + *tokenType = TK_INTEGER; + for(i=0; sqlite3Isdigit(z[i]); i++){} +#ifndef SQLITE_OMIT_FLOATING_POINT + if( z[i]=='.' ){ + i++; + while( sqlite3Isdigit(z[i]) ){ i++; } + *tokenType = TK_FLOAT; + } + if( (z[i]=='e' || z[i]=='E') && + ( sqlite3Isdigit(z[i+1]) + || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2])) + ) + ){ + i += 2; + while( sqlite3Isdigit(z[i]) ){ i++; } + *tokenType = TK_FLOAT; + } +#endif + while( IdChar(z[i]) ){ + *tokenType = TK_ILLEGAL; + i++; + } + return i; + } + case '[': { + for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} + *tokenType = c==']' ? TK_ID : TK_ILLEGAL; + return i; + } + case '?': { + *tokenType = TK_VARIABLE; + for(i=1; sqlite3Isdigit(z[i]); i++){} + return i; + } + case '#': { + for(i=1; sqlite3Isdigit(z[i]); i++){} + if( i>1 ){ + /* Parameters of the form #NNN (where NNN is a number) are used + ** internally by sqlite3NestedParse. */ + *tokenType = TK_REGISTER; + return i; + } + /* Fall through into the next case if the '#' is not followed by + ** a digit. Try to match #AAAA where AAAA is a parameter name. */ + } +#ifndef SQLITE_OMIT_TCL_VARIABLE + case '$': +#endif + case '@': /* For compatibility with MS SQL Server */ + case ':': { + int n = 0; + testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' ); + *tokenType = TK_VARIABLE; + for(i=1; (c=z[i])!=0; i++){ + if( IdChar(c) ){ + n++; +#ifndef SQLITE_OMIT_TCL_VARIABLE + }else if( c=='(' && n>0 ){ + do{ + i++; + }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' ); + if( c==')' ){ + i++; + }else{ + *tokenType = TK_ILLEGAL; + } + break; + }else if( c==':' && z[i+1]==':' ){ + i++; +#endif + }else{ + break; + } + } + if( n==0 ) *tokenType = TK_ILLEGAL; + return i; + } +#ifndef SQLITE_OMIT_BLOB_LITERAL + case 'x': case 'X': { + testcase( z[0]=='x' ); testcase( z[0]=='X' ); + if( z[1]=='\'' ){ + *tokenType = TK_BLOB; + for(i=2; sqlite3Isxdigit(z[i]); i++){} + if( z[i]!='\'' || i%2 ){ + *tokenType = TK_ILLEGAL; + while( z[i] && z[i]!='\'' ){ i++; } + } + if( z[i] ) i++; + return i; + } + /* Otherwise fall through to the next case */ + } +#endif + default: { + if( !IdChar(*z) ){ + break; + } + for(i=1; IdChar(z[i]); i++){} + *tokenType = keywordCode((char*)z, i); + return i; + } + } + *tokenType = TK_ILLEGAL; + return 1; +} + +/* +** Run the parser on the given SQL string. The parser structure is +** passed in. An SQLITE_ status code is returned. If an error occurs +** then an and attempt is made to write an error message into +** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that +** error message. +*/ +int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){ + int nErr = 0; /* Number of errors encountered */ + int i; /* Loop counter */ + void *pEngine; /* The LEMON-generated LALR(1) parser */ + int tokenType; /* type of the next token */ + int lastTokenParsed = -1; /* type of the previous token */ + u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */ + sqlite3 *db = pParse->db; /* The database connection */ + int mxSqlLen; /* Max length of an SQL string */ + + + mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; + if( db->nVdbeActive==0 ){ + db->u1.isInterrupted = 0; + } + pParse->rc = SQLITE_OK; + pParse->zTail = zSql; + i = 0; + assert( pzErrMsg!=0 ); + pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc); + if( pEngine==0 ){ + db->mallocFailed = 1; + return SQLITE_NOMEM; + } + assert( pParse->pNewTable==0 ); + assert( pParse->pNewTrigger==0 ); + assert( pParse->nVar==0 ); + assert( pParse->nzVar==0 ); + assert( pParse->azVar==0 ); + enableLookaside = db->lookaside.bEnabled; + if( db->lookaside.pStart ) db->lookaside.bEnabled = 1; + while( !db->mallocFailed && zSql[i]!=0 ){ + assert( i>=0 ); + pParse->sLastToken.z = &zSql[i]; + pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType); + i += pParse->sLastToken.n; + if( i>mxSqlLen ){ + pParse->rc = SQLITE_TOOBIG; + break; + } + switch( tokenType ){ + case TK_SPACE: { + if( db->u1.isInterrupted ){ + sqlite3ErrorMsg(pParse, "interrupt"); + pParse->rc = SQLITE_INTERRUPT; + goto abort_parse; + } + break; + } + case TK_ILLEGAL: { + sqlite3DbFree(db, *pzErrMsg); + *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"", + &pParse->sLastToken); + nErr++; + goto abort_parse; + } + case TK_SEMI: { + pParse->zTail = &zSql[i]; + /* Fall thru into the default case */ + } + default: { + sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse); + lastTokenParsed = tokenType; + if( pParse->rc!=SQLITE_OK ){ + goto abort_parse; + } + break; + } + } + } +abort_parse: + if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){ + if( lastTokenParsed!=TK_SEMI ){ + sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse); + pParse->zTail = &zSql[i]; + } + sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse); + } +#ifdef YYTRACKMAXSTACKDEPTH + sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK, + sqlite3ParserStackPeak(pEngine) + ); +#endif /* YYDEBUG */ + sqlite3ParserFree(pEngine, sqlite3_free); + db->lookaside.bEnabled = enableLookaside; + if( db->mallocFailed ){ + pParse->rc = SQLITE_NOMEM; + } + if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){ + sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc)); + } + assert( pzErrMsg!=0 ); + if( pParse->zErrMsg ){ + *pzErrMsg = pParse->zErrMsg; + sqlite3_log(pParse->rc, "%s", *pzErrMsg); + pParse->zErrMsg = 0; + nErr++; + } + if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){ + sqlite3VdbeDelete(pParse->pVdbe); + pParse->pVdbe = 0; + } +#ifndef SQLITE_OMIT_SHARED_CACHE + if( pParse->nested==0 ){ + sqlite3DbFree(db, pParse->aTableLock); + pParse->aTableLock = 0; + pParse->nTableLock = 0; + } +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + sqlite3_free(pParse->apVtabLock); +#endif + + if( !IN_DECLARE_VTAB ){ + /* If the pParse->declareVtab flag is set, do not delete any table + ** structure built up in pParse->pNewTable. The calling code (see vtab.c) + ** will take responsibility for freeing the Table structure. + */ + sqlite3DeleteTable(db, pParse->pNewTable); + } + + sqlite3DeleteTrigger(db, pParse->pNewTrigger); + for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]); + sqlite3DbFree(db, pParse->azVar); + sqlite3DbFree(db, pParse->aAlias); + while( pParse->pAinc ){ + AutoincInfo *p = pParse->pAinc; + pParse->pAinc = p->pNext; + sqlite3DbFree(db, p); + } + while( pParse->pZombieTab ){ + Table *p = pParse->pZombieTab; + pParse->pZombieTab = p->pNextZombie; + sqlite3DeleteTable(db, p); + } + if( nErr>0 && pParse->rc==SQLITE_OK ){ + pParse->rc = SQLITE_ERROR; + } + return nErr; +} diff --git a/components/external/SQLite-3.8.1/src/trigger.c b/components/external/SQLite-3.8.1/src/trigger.c new file mode 100644 index 0000000000000000000000000000000000000000..774711f0f5aad2e3143e4785198ac28940dbe356 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/trigger.c @@ -0,0 +1,1135 @@ +/* +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains the implementation for TRIGGERs +*/ +#include "sqliteInt.h" + +#ifndef SQLITE_OMIT_TRIGGER +/* +** Delete a linked list of TriggerStep structures. +*/ +void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){ + while( pTriggerStep ){ + TriggerStep * pTmp = pTriggerStep; + pTriggerStep = pTriggerStep->pNext; + + sqlite3ExprDelete(db, pTmp->pWhere); + sqlite3ExprListDelete(db, pTmp->pExprList); + sqlite3SelectDelete(db, pTmp->pSelect); + sqlite3IdListDelete(db, pTmp->pIdList); + + sqlite3DbFree(db, pTmp); + } +} + +/* +** Given table pTab, return a list of all the triggers attached to +** the table. The list is connected by Trigger.pNext pointers. +** +** All of the triggers on pTab that are in the same database as pTab +** are already attached to pTab->pTrigger. But there might be additional +** triggers on pTab in the TEMP schema. This routine prepends all +** TEMP triggers on pTab to the beginning of the pTab->pTrigger list +** and returns the combined list. +** +** To state it another way: This routine returns a list of all triggers +** that fire off of pTab. The list will include any TEMP triggers on +** pTab as well as the triggers lised in pTab->pTrigger. +*/ +Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ + Schema * const pTmpSchema = pParse->db->aDb[1].pSchema; + Trigger *pList = 0; /* List of triggers to return */ + + if( pParse->disableTriggers ){ + return 0; + } + + if( pTmpSchema!=pTab->pSchema ){ + HashElem *p; + assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) ); + for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){ + Trigger *pTrig = (Trigger *)sqliteHashData(p); + if( pTrig->pTabSchema==pTab->pSchema + && 0==sqlite3StrICmp(pTrig->table, pTab->zName) + ){ + pTrig->pNext = (pList ? pList : pTab->pTrigger); + pList = pTrig; + } + } + } + + return (pList ? pList : pTab->pTrigger); +} + +/* +** This is called by the parser when it sees a CREATE TRIGGER statement +** up to the point of the BEGIN before the trigger actions. A Trigger +** structure is generated based on the information available and stored +** in pParse->pNewTrigger. After the trigger actions have been parsed, the +** sqlite3FinishTrigger() function is called to complete the trigger +** construction process. +*/ +void sqlite3BeginTrigger( + Parse *pParse, /* The parse context of the CREATE TRIGGER statement */ + Token *pName1, /* The name of the trigger */ + Token *pName2, /* The name of the trigger */ + int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */ + int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */ + IdList *pColumns, /* column list if this is an UPDATE OF trigger */ + SrcList *pTableName,/* The name of the table/view the trigger applies to */ + Expr *pWhen, /* WHEN clause */ + int isTemp, /* True if the TEMPORARY keyword is present */ + int noErr /* Suppress errors if the trigger already exists */ +){ + Trigger *pTrigger = 0; /* The new trigger */ + Table *pTab; /* Table that the trigger fires off of */ + char *zName = 0; /* Name of the trigger */ + sqlite3 *db = pParse->db; /* The database connection */ + int iDb; /* The database to store the trigger in */ + Token *pName; /* The unqualified db name */ + DbFixer sFix; /* State vector for the DB fixer */ + int iTabDb; /* Index of the database holding pTab */ + + assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */ + assert( pName2!=0 ); + assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE ); + assert( op>0 && op<0xff ); + if( isTemp ){ + /* If TEMP was specified, then the trigger name may not be qualified. */ + if( pName2->n>0 ){ + sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name"); + goto trigger_cleanup; + } + iDb = 1; + pName = pName1; + }else{ + /* Figure out the db that the trigger will be created in */ + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); + if( iDb<0 ){ + goto trigger_cleanup; + } + } + if( !pTableName || db->mallocFailed ){ + goto trigger_cleanup; + } + + /* A long-standing parser bug is that this syntax was allowed: + ** + ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab .... + ** ^^^^^^^^ + ** + ** To maintain backwards compatibility, ignore the database + ** name on pTableName if we are reparsing our of SQLITE_MASTER. + */ + if( db->init.busy && iDb!=1 ){ + sqlite3DbFree(db, pTableName->a[0].zDatabase); + pTableName->a[0].zDatabase = 0; + } + + /* If the trigger name was unqualified, and the table is a temp table, + ** then set iDb to 1 to create the trigger in the temporary database. + ** If sqlite3SrcListLookup() returns 0, indicating the table does not + ** exist, the error is caught by the block below. + */ + pTab = sqlite3SrcListLookup(pParse, pTableName); + if( db->init.busy==0 && pName2->n==0 && pTab + && pTab->pSchema==db->aDb[1].pSchema ){ + iDb = 1; + } + + /* Ensure the table name matches database name and that the table exists */ + if( db->mallocFailed ) goto trigger_cleanup; + assert( pTableName->nSrc==1 ); + sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName); + if( sqlite3FixSrcList(&sFix, pTableName) ){ + goto trigger_cleanup; + } + pTab = sqlite3SrcListLookup(pParse, pTableName); + if( !pTab ){ + /* The table does not exist. */ + if( db->init.iDb==1 ){ + /* Ticket #3810. + ** Normally, whenever a table is dropped, all associated triggers are + ** dropped too. But if a TEMP trigger is created on a non-TEMP table + ** and the table is dropped by a different database connection, the + ** trigger is not visible to the database connection that does the + ** drop so the trigger cannot be dropped. This results in an + ** "orphaned trigger" - a trigger whose associated table is missing. + */ + db->init.orphanTrigger = 1; + } + goto trigger_cleanup; + } + if( IsVirtual(pTab) ){ + sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables"); + goto trigger_cleanup; + } + + /* Check that the trigger name is not reserved and that no trigger of the + ** specified name exists */ + zName = sqlite3NameFromToken(db, pName); + if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ + goto trigger_cleanup; + } + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), + zName, sqlite3Strlen30(zName)) ){ + if( !noErr ){ + sqlite3ErrorMsg(pParse, "trigger %T already exists", pName); + }else{ + assert( !db->init.busy ); + sqlite3CodeVerifySchema(pParse, iDb); + } + goto trigger_cleanup; + } + + /* Do not create a trigger on a system table */ + if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ + sqlite3ErrorMsg(pParse, "cannot create trigger on system table"); + pParse->nErr++; + goto trigger_cleanup; + } + + /* INSTEAD of triggers are only for views and views only support INSTEAD + ** of triggers. + */ + if( pTab->pSelect && tr_tm!=TK_INSTEAD ){ + sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", + (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0); + goto trigger_cleanup; + } + if( !pTab->pSelect && tr_tm==TK_INSTEAD ){ + sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF" + " trigger on table: %S", pTableName, 0); + goto trigger_cleanup; + } + iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); + +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int code = SQLITE_CREATE_TRIGGER; + const char *zDb = db->aDb[iTabDb].zName; + const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb; + if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER; + if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){ + goto trigger_cleanup; + } + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){ + goto trigger_cleanup; + } + } +#endif + + /* INSTEAD OF triggers can only appear on views and BEFORE triggers + ** cannot appear on views. So we might as well translate every + ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code + ** elsewhere. + */ + if (tr_tm == TK_INSTEAD){ + tr_tm = TK_BEFORE; + } + + /* Build the Trigger object */ + pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger)); + if( pTrigger==0 ) goto trigger_cleanup; + pTrigger->zName = zName; + zName = 0; + pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName); + pTrigger->pSchema = db->aDb[iDb].pSchema; + pTrigger->pTabSchema = pTab->pSchema; + pTrigger->op = (u8)op; + pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER; + pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); + pTrigger->pColumns = sqlite3IdListDup(db, pColumns); + assert( pParse->pNewTrigger==0 ); + pParse->pNewTrigger = pTrigger; + +trigger_cleanup: + sqlite3DbFree(db, zName); + sqlite3SrcListDelete(db, pTableName); + sqlite3IdListDelete(db, pColumns); + sqlite3ExprDelete(db, pWhen); + if( !pParse->pNewTrigger ){ + sqlite3DeleteTrigger(db, pTrigger); + }else{ + assert( pParse->pNewTrigger==pTrigger ); + } +} + +/* +** This routine is called after all of the trigger actions have been parsed +** in order to complete the process of building the trigger. +*/ +void sqlite3FinishTrigger( + Parse *pParse, /* Parser context */ + TriggerStep *pStepList, /* The triggered program */ + Token *pAll /* Token that describes the complete CREATE TRIGGER */ +){ + Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */ + char *zName; /* Name of trigger */ + sqlite3 *db = pParse->db; /* The database */ + DbFixer sFix; /* Fixer object */ + int iDb; /* Database containing the trigger */ + Token nameToken; /* Trigger name for error reporting */ + + pParse->pNewTrigger = 0; + if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup; + zName = pTrig->zName; + iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); + pTrig->step_list = pStepList; + while( pStepList ){ + pStepList->pTrig = pTrig; + pStepList = pStepList->pNext; + } + nameToken.z = pTrig->zName; + nameToken.n = sqlite3Strlen30(nameToken.z); + sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken); + if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) + || sqlite3FixExpr(&sFix, pTrig->pWhen) + ){ + goto triggerfinish_cleanup; + } + + /* if we are not initializing, + ** build the sqlite_master entry + */ + if( !db->init.busy ){ + Vdbe *v; + char *z; + + /* Make an entry in the sqlite_master table */ + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto triggerfinish_cleanup; + sqlite3BeginWriteOperation(pParse, 0, iDb); + z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n); + sqlite3NestedParse(pParse, + "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName, + pTrig->table, z); + sqlite3DbFree(db, z); + sqlite3ChangeCookie(pParse, iDb); + sqlite3VdbeAddParseSchemaOp(v, iDb, + sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName)); + } + + if( db->init.busy ){ + Trigger *pLink = pTrig; + Hash *pHash = &db->aDb[iDb].pSchema->trigHash; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig); + if( pTrig ){ + db->mallocFailed = 1; + }else if( pLink->pSchema==pLink->pTabSchema ){ + Table *pTab; + int n = sqlite3Strlen30(pLink->table); + pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n); + assert( pTab!=0 ); + pLink->pNext = pTab->pTrigger; + pTab->pTrigger = pLink; + } + } + +triggerfinish_cleanup: + sqlite3DeleteTrigger(db, pTrig); + assert( !pParse->pNewTrigger ); + sqlite3DeleteTriggerStep(db, pStepList); +} + +/* +** Turn a SELECT statement (that the pSelect parameter points to) into +** a trigger step. Return a pointer to a TriggerStep structure. +** +** The parser calls this routine when it finds a SELECT statement in +** body of a TRIGGER. +*/ +TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){ + TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); + if( pTriggerStep==0 ) { + sqlite3SelectDelete(db, pSelect); + return 0; + } + pTriggerStep->op = TK_SELECT; + pTriggerStep->pSelect = pSelect; + pTriggerStep->orconf = OE_Default; + return pTriggerStep; +} + +/* +** Allocate space to hold a new trigger step. The allocated space +** holds both the TriggerStep object and the TriggerStep.target.z string. +** +** If an OOM error occurs, NULL is returned and db->mallocFailed is set. +*/ +static TriggerStep *triggerStepAllocate( + sqlite3 *db, /* Database connection */ + u8 op, /* Trigger opcode */ + Token *pName /* The target name */ +){ + TriggerStep *pTriggerStep; + + pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n); + if( pTriggerStep ){ + char *z = (char*)&pTriggerStep[1]; + memcpy(z, pName->z, pName->n); + pTriggerStep->target.z = z; + pTriggerStep->target.n = pName->n; + pTriggerStep->op = op; + } + return pTriggerStep; +} + +/* +** Build a trigger step out of an INSERT statement. Return a pointer +** to the new trigger step. +** +** The parser calls this routine when it sees an INSERT inside the +** body of a trigger. +*/ +TriggerStep *sqlite3TriggerInsertStep( + sqlite3 *db, /* The database connection */ + Token *pTableName, /* Name of the table into which we insert */ + IdList *pColumn, /* List of columns in pTableName to insert into */ + ExprList *pEList, /* The VALUE clause: a list of values to be inserted */ + Select *pSelect, /* A SELECT statement that supplies values */ + u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */ +){ + TriggerStep *pTriggerStep; + + assert(pEList == 0 || pSelect == 0); + assert(pEList != 0 || pSelect != 0 || db->mallocFailed); + + pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName); + if( pTriggerStep ){ + pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + pTriggerStep->pIdList = pColumn; + pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); + pTriggerStep->orconf = orconf; + }else{ + sqlite3IdListDelete(db, pColumn); + } + sqlite3ExprListDelete(db, pEList); + sqlite3SelectDelete(db, pSelect); + + return pTriggerStep; +} + +/* +** Construct a trigger step that implements an UPDATE statement and return +** a pointer to that trigger step. The parser calls this routine when it +** sees an UPDATE statement inside the body of a CREATE TRIGGER. +*/ +TriggerStep *sqlite3TriggerUpdateStep( + sqlite3 *db, /* The database connection */ + Token *pTableName, /* Name of the table to be updated */ + ExprList *pEList, /* The SET clause: list of column and new values */ + Expr *pWhere, /* The WHERE clause */ + u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */ +){ + TriggerStep *pTriggerStep; + + pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName); + if( pTriggerStep ){ + pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); + pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + pTriggerStep->orconf = orconf; + } + sqlite3ExprListDelete(db, pEList); + sqlite3ExprDelete(db, pWhere); + return pTriggerStep; +} + +/* +** Construct a trigger step that implements a DELETE statement and return +** a pointer to that trigger step. The parser calls this routine when it +** sees a DELETE statement inside the body of a CREATE TRIGGER. +*/ +TriggerStep *sqlite3TriggerDeleteStep( + sqlite3 *db, /* Database connection */ + Token *pTableName, /* The table from which rows are deleted */ + Expr *pWhere /* The WHERE clause */ +){ + TriggerStep *pTriggerStep; + + pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName); + if( pTriggerStep ){ + pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + pTriggerStep->orconf = OE_Default; + } + sqlite3ExprDelete(db, pWhere); + return pTriggerStep; +} + +/* +** Recursively delete a Trigger structure +*/ +void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){ + if( pTrigger==0 ) return; + sqlite3DeleteTriggerStep(db, pTrigger->step_list); + sqlite3DbFree(db, pTrigger->zName); + sqlite3DbFree(db, pTrigger->table); + sqlite3ExprDelete(db, pTrigger->pWhen); + sqlite3IdListDelete(db, pTrigger->pColumns); + sqlite3DbFree(db, pTrigger); +} + +/* +** This function is called to drop a trigger from the database schema. +** +** This may be called directly from the parser and therefore identifies +** the trigger by name. The sqlite3DropTriggerPtr() routine does the +** same job as this routine except it takes a pointer to the trigger +** instead of the trigger name. +**/ +void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){ + Trigger *pTrigger = 0; + int i; + const char *zDb; + const char *zName; + int nName; + sqlite3 *db = pParse->db; + + if( db->mallocFailed ) goto drop_trigger_cleanup; + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + goto drop_trigger_cleanup; + } + + assert( pName->nSrc==1 ); + zDb = pName->a[0].zDatabase; + zName = pName->a[0].zName; + nName = sqlite3Strlen30(zName); + assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); + for(i=OMIT_TEMPDB; inDb; i++){ + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ + if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue; + assert( sqlite3SchemaMutexHeld(db, j, 0) ); + pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName); + if( pTrigger ) break; + } + if( !pTrigger ){ + if( !noErr ){ + sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0); + }else{ + sqlite3CodeVerifyNamedSchema(pParse, zDb); + } + pParse->checkSchema = 1; + goto drop_trigger_cleanup; + } + sqlite3DropTriggerPtr(pParse, pTrigger); + +drop_trigger_cleanup: + sqlite3SrcListDelete(db, pName); +} + +/* +** Return a pointer to the Table structure for the table that a trigger +** is set on. +*/ +static Table *tableOfTrigger(Trigger *pTrigger){ + int n = sqlite3Strlen30(pTrigger->table); + return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n); +} + + +/* +** Drop a trigger given a pointer to that trigger. +*/ +void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ + Table *pTable; + Vdbe *v; + sqlite3 *db = pParse->db; + int iDb; + + iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema); + assert( iDb>=0 && iDbnDb ); + pTable = tableOfTrigger(pTrigger); + assert( pTable ); + assert( pTable->pSchema==pTrigger->pSchema || iDb==1 ); +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int code = SQLITE_DROP_TRIGGER; + const char *zDb = db->aDb[iDb].zName; + const char *zTab = SCHEMA_TABLE(iDb); + if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER; + if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) || + sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ + return; + } + } +#endif + + /* Generate code to destroy the database record of the trigger. + */ + assert( pTable!=0 ); + if( (v = sqlite3GetVdbe(pParse))!=0 ){ + int base; + static const VdbeOpList dropTrigger[] = { + { OP_Rewind, 0, ADDR(9), 0}, + { OP_String8, 0, 1, 0}, /* 1 */ + { OP_Column, 0, 1, 2}, + { OP_Ne, 2, ADDR(8), 1}, + { OP_String8, 0, 1, 0}, /* 4: "trigger" */ + { OP_Column, 0, 0, 2}, + { OP_Ne, 2, ADDR(8), 1}, + { OP_Delete, 0, 0, 0}, + { OP_Next, 0, ADDR(1), 0}, /* 8 */ + }; + + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3OpenMasterTable(pParse, iDb); + base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger); + sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT); + sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC); + sqlite3ChangeCookie(pParse, iDb); + sqlite3VdbeAddOp2(v, OP_Close, 0, 0); + sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0); + if( pParse->nMem<3 ){ + pParse->nMem = 3; + } + } +} + +/* +** Remove a trigger from the hash tables of the sqlite* pointer. +*/ +void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){ + Trigger *pTrigger; + Hash *pHash; + + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + pHash = &(db->aDb[iDb].pSchema->trigHash); + pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0); + if( ALWAYS(pTrigger) ){ + if( pTrigger->pSchema==pTrigger->pTabSchema ){ + Table *pTab = tableOfTrigger(pTrigger); + Trigger **pp; + for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext)); + *pp = (*pp)->pNext; + } + sqlite3DeleteTrigger(db, pTrigger); + db->flags |= SQLITE_InternChanges; + } +} + +/* +** pEList is the SET clause of an UPDATE statement. Each entry +** in pEList is of the format =. If any of the entries +** in pEList have an which matches an identifier in pIdList, +** then return TRUE. If pIdList==NULL, then it is considered a +** wildcard that matches anything. Likewise if pEList==NULL then +** it matches anything so always return true. Return false only +** if there is no match. +*/ +static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){ + int e; + if( pIdList==0 || NEVER(pEList==0) ) return 1; + for(e=0; enExpr; e++){ + if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1; + } + return 0; +} + +/* +** Return a list of all triggers on table pTab if there exists at least +** one trigger that must be fired when an operation of type 'op' is +** performed on the table, and, if that operation is an UPDATE, if at +** least one of the columns in pChanges is being modified. +*/ +Trigger *sqlite3TriggersExist( + Parse *pParse, /* Parse context */ + Table *pTab, /* The table the contains the triggers */ + int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */ + ExprList *pChanges, /* Columns that change in an UPDATE statement */ + int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ +){ + int mask = 0; + Trigger *pList = 0; + Trigger *p; + + if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){ + pList = sqlite3TriggerList(pParse, pTab); + } + assert( pList==0 || IsVirtual(pTab)==0 ); + for(p=pList; p; p=p->pNext){ + if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){ + mask |= p->tr_tm; + } + } + if( pMask ){ + *pMask = mask; + } + return (mask ? pList : 0); +} + +/* +** Convert the pStep->target token into a SrcList and return a pointer +** to that SrcList. +** +** This routine adds a specific database name, if needed, to the target when +** forming the SrcList. This prevents a trigger in one database from +** referring to a target in another database. An exception is when the +** trigger is in TEMP in which case it can refer to any other database it +** wants. +*/ +static SrcList *targetSrcList( + Parse *pParse, /* The parsing context */ + TriggerStep *pStep /* The trigger containing the target token */ +){ + int iDb; /* Index of the database to use */ + SrcList *pSrc; /* SrcList to be returned */ + + pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0); + if( pSrc ){ + assert( pSrc->nSrc>0 ); + assert( pSrc->a!=0 ); + iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema); + if( iDb==0 || iDb>=2 ){ + sqlite3 *db = pParse->db; + assert( iDbdb->nDb ); + pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName); + } + } + return pSrc; +} + +/* +** Generate VDBE code for the statements inside the body of a single +** trigger. +*/ +static int codeTriggerProgram( + Parse *pParse, /* The parser context */ + TriggerStep *pStepList, /* List of statements inside the trigger body */ + int orconf /* Conflict algorithm. (OE_Abort, etc) */ +){ + TriggerStep *pStep; + Vdbe *v = pParse->pVdbe; + sqlite3 *db = pParse->db; + + assert( pParse->pTriggerTab && pParse->pToplevel ); + assert( pStepList ); + assert( v!=0 ); + for(pStep=pStepList; pStep; pStep=pStep->pNext){ + /* Figure out the ON CONFLICT policy that will be used for this step + ** of the trigger program. If the statement that caused this trigger + ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use + ** the ON CONFLICT policy that was specified as part of the trigger + ** step statement. Example: + ** + ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN; + ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b); + ** END; + ** + ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy + ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy + */ + pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf; + + /* Clear the cookieGoto flag. When coding triggers, the cookieGoto + ** variable is used as a flag to indicate to sqlite3ExprCodeConstants() + ** that it is not safe to refactor constants (this happens after the + ** start of the first loop in the SQL statement is coded - at that + ** point code may be conditionally executed, so it is no longer safe to + ** initialize constant register values). */ + assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 ); + pParse->cookieGoto = 0; + + switch( pStep->op ){ + case TK_UPDATE: { + sqlite3Update(pParse, + targetSrcList(pParse, pStep), + sqlite3ExprListDup(db, pStep->pExprList, 0), + sqlite3ExprDup(db, pStep->pWhere, 0), + pParse->eOrconf + ); + break; + } + case TK_INSERT: { + sqlite3Insert(pParse, + targetSrcList(pParse, pStep), + sqlite3ExprListDup(db, pStep->pExprList, 0), + sqlite3SelectDup(db, pStep->pSelect, 0), + sqlite3IdListDup(db, pStep->pIdList), + pParse->eOrconf + ); + break; + } + case TK_DELETE: { + sqlite3DeleteFrom(pParse, + targetSrcList(pParse, pStep), + sqlite3ExprDup(db, pStep->pWhere, 0) + ); + break; + } + default: assert( pStep->op==TK_SELECT ); { + SelectDest sDest; + Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0); + sqlite3SelectDestInit(&sDest, SRT_Discard, 0); + sqlite3Select(pParse, pSelect, &sDest); + sqlite3SelectDelete(db, pSelect); + break; + } + } + if( pStep->op!=TK_SELECT ){ + sqlite3VdbeAddOp0(v, OP_ResetCount); + } + } + + return 0; +} + +#ifdef SQLITE_DEBUG +/* +** This function is used to add VdbeComment() annotations to a VDBE +** program. It is not used in production code, only for debugging. +*/ +static const char *onErrorText(int onError){ + switch( onError ){ + case OE_Abort: return "abort"; + case OE_Rollback: return "rollback"; + case OE_Fail: return "fail"; + case OE_Replace: return "replace"; + case OE_Ignore: return "ignore"; + case OE_Default: return "default"; + } + return "n/a"; +} +#endif + +/* +** Parse context structure pFrom has just been used to create a sub-vdbe +** (trigger program). If an error has occurred, transfer error information +** from pFrom to pTo. +*/ +static void transferParseError(Parse *pTo, Parse *pFrom){ + assert( pFrom->zErrMsg==0 || pFrom->nErr ); + assert( pTo->zErrMsg==0 || pTo->nErr ); + if( pTo->nErr==0 ){ + pTo->zErrMsg = pFrom->zErrMsg; + pTo->nErr = pFrom->nErr; + }else{ + sqlite3DbFree(pFrom->db, pFrom->zErrMsg); + } +} + +/* +** Create and populate a new TriggerPrg object with a sub-program +** implementing trigger pTrigger with ON CONFLICT policy orconf. +*/ +static TriggerPrg *codeRowTrigger( + Parse *pParse, /* Current parse context */ + Trigger *pTrigger, /* Trigger to code */ + Table *pTab, /* The table pTrigger is attached to */ + int orconf /* ON CONFLICT policy to code trigger program with */ +){ + Parse *pTop = sqlite3ParseToplevel(pParse); + sqlite3 *db = pParse->db; /* Database handle */ + TriggerPrg *pPrg; /* Value to return */ + Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */ + Vdbe *v; /* Temporary VM */ + NameContext sNC; /* Name context for sub-vdbe */ + SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */ + Parse *pSubParse; /* Parse context for sub-vdbe */ + int iEndTrigger = 0; /* Label to jump to if WHEN is false */ + + assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); + assert( pTop->pVdbe ); + + /* Allocate the TriggerPrg and SubProgram objects. To ensure that they + ** are freed if an error occurs, link them into the Parse.pTriggerPrg + ** list of the top-level Parse object sooner rather than later. */ + pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg)); + if( !pPrg ) return 0; + pPrg->pNext = pTop->pTriggerPrg; + pTop->pTriggerPrg = pPrg; + pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram)); + if( !pProgram ) return 0; + sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram); + pPrg->pTrigger = pTrigger; + pPrg->orconf = orconf; + pPrg->aColmask[0] = 0xffffffff; + pPrg->aColmask[1] = 0xffffffff; + + /* Allocate and populate a new Parse context to use for coding the + ** trigger sub-program. */ + pSubParse = sqlite3StackAllocZero(db, sizeof(Parse)); + if( !pSubParse ) return 0; + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pSubParse; + pSubParse->db = db; + pSubParse->pTriggerTab = pTab; + pSubParse->pToplevel = pTop; + pSubParse->zAuthContext = pTrigger->zName; + pSubParse->eTriggerOp = pTrigger->op; + pSubParse->nQueryLoop = pParse->nQueryLoop; + + v = sqlite3GetVdbe(pSubParse); + if( v ){ + VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", + pTrigger->zName, onErrorText(orconf), + (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"), + (pTrigger->op==TK_UPDATE ? "UPDATE" : ""), + (pTrigger->op==TK_INSERT ? "INSERT" : ""), + (pTrigger->op==TK_DELETE ? "DELETE" : ""), + pTab->zName + )); +#ifndef SQLITE_OMIT_TRACE + sqlite3VdbeChangeP4(v, -1, + sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC + ); +#endif + + /* If one was specified, code the WHEN clause. If it evaluates to false + ** (or NULL) the sub-vdbe is immediately halted by jumping to the + ** OP_Halt inserted at the end of the program. */ + if( pTrigger->pWhen ){ + pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0); + if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) + && db->mallocFailed==0 + ){ + iEndTrigger = sqlite3VdbeMakeLabel(v); + sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL); + } + sqlite3ExprDelete(db, pWhen); + } + + /* Code the trigger program into the sub-vdbe. */ + codeTriggerProgram(pSubParse, pTrigger->step_list, orconf); + + /* Insert an OP_Halt at the end of the sub-program. */ + if( iEndTrigger ){ + sqlite3VdbeResolveLabel(v, iEndTrigger); + } + sqlite3VdbeAddOp0(v, OP_Halt); + VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf))); + + transferParseError(pParse, pSubParse); + if( db->mallocFailed==0 ){ + pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg); + } + pProgram->nMem = pSubParse->nMem; + pProgram->nCsr = pSubParse->nTab; + pProgram->nOnce = pSubParse->nOnce; + pProgram->token = (void *)pTrigger; + pPrg->aColmask[0] = pSubParse->oldmask; + pPrg->aColmask[1] = pSubParse->newmask; + sqlite3VdbeDelete(v); + } + + assert( !pSubParse->pAinc && !pSubParse->pZombieTab ); + assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg ); + sqlite3StackFree(db, pSubParse); + + return pPrg; +} + +/* +** Return a pointer to a TriggerPrg object containing the sub-program for +** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such +** TriggerPrg object exists, a new object is allocated and populated before +** being returned. +*/ +static TriggerPrg *getRowTrigger( + Parse *pParse, /* Current parse context */ + Trigger *pTrigger, /* Trigger to code */ + Table *pTab, /* The table trigger pTrigger is attached to */ + int orconf /* ON CONFLICT algorithm. */ +){ + Parse *pRoot = sqlite3ParseToplevel(pParse); + TriggerPrg *pPrg; + + assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); + + /* It may be that this trigger has already been coded (or is in the + ** process of being coded). If this is the case, then an entry with + ** a matching TriggerPrg.pTrigger field will be present somewhere + ** in the Parse.pTriggerPrg list. Search for such an entry. */ + for(pPrg=pRoot->pTriggerPrg; + pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); + pPrg=pPrg->pNext + ); + + /* If an existing TriggerPrg could not be located, create a new one. */ + if( !pPrg ){ + pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf); + } + + return pPrg; +} + +/* +** Generate code for the trigger program associated with trigger p on +** table pTab. The reg, orconf and ignoreJump parameters passed to this +** function are the same as those described in the header function for +** sqlite3CodeRowTrigger() +*/ +void sqlite3CodeRowTriggerDirect( + Parse *pParse, /* Parse context */ + Trigger *p, /* Trigger to code */ + Table *pTab, /* The table to code triggers from */ + int reg, /* Reg array containing OLD.* and NEW.* values */ + int orconf, /* ON CONFLICT policy */ + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ +){ + Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */ + TriggerPrg *pPrg; + pPrg = getRowTrigger(pParse, p, pTab, orconf); + assert( pPrg || pParse->nErr || pParse->db->mallocFailed ); + + /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program + ** is a pointer to the sub-vdbe containing the trigger program. */ + if( pPrg ){ + int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers)); + + sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem); + sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM); + VdbeComment( + (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf))); + + /* Set the P5 operand of the OP_Program instruction to non-zero if + ** recursive invocation of this trigger program is disallowed. Recursive + ** invocation is disallowed if (a) the sub-program is really a trigger, + ** not a foreign key action, and (b) the flag to enable recursive triggers + ** is clear. */ + sqlite3VdbeChangeP5(v, (u8)bRecursive); + } +} + +/* +** This is called to code the required FOR EACH ROW triggers for an operation +** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE) +** is given by the op parameter. The tr_tm parameter determines whether the +** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then +** parameter pChanges is passed the list of columns being modified. +** +** If there are no triggers that fire at the specified time for the specified +** operation on pTab, this function is a no-op. +** +** The reg argument is the address of the first in an array of registers +** that contain the values substituted for the new.* and old.* references +** in the trigger program. If N is the number of columns in table pTab +** (a copy of pTab->nCol), then registers are populated as follows: +** +** Register Contains +** ------------------------------------------------------ +** reg+0 OLD.rowid +** reg+1 OLD.* value of left-most column of pTab +** ... ... +** reg+N OLD.* value of right-most column of pTab +** reg+N+1 NEW.rowid +** reg+N+2 OLD.* value of left-most column of pTab +** ... ... +** reg+N+N+1 NEW.* value of right-most column of pTab +** +** For ON DELETE triggers, the registers containing the NEW.* values will +** never be accessed by the trigger program, so they are not allocated or +** populated by the caller (there is no data to populate them with anyway). +** Similarly, for ON INSERT triggers the values stored in the OLD.* registers +** are never accessed, and so are not allocated by the caller. So, for an +** ON INSERT trigger, the value passed to this function as parameter reg +** is not a readable register, although registers (reg+N) through +** (reg+N+N+1) are. +** +** Parameter orconf is the default conflict resolution algorithm for the +** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump +** is the instruction that control should jump to if a trigger program +** raises an IGNORE exception. +*/ +void sqlite3CodeRowTrigger( + Parse *pParse, /* Parse context */ + Trigger *pTrigger, /* List of triggers on table pTab */ + int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */ + ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ + int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ + Table *pTab, /* The table to code triggers from */ + int reg, /* The first in an array of registers (see above) */ + int orconf, /* ON CONFLICT policy */ + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ +){ + Trigger *p; /* Used to iterate through pTrigger list */ + + assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE ); + assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER ); + assert( (op==TK_UPDATE)==(pChanges!=0) ); + + for(p=pTrigger; p; p=p->pNext){ + + /* Sanity checking: The schema for the trigger and for the table are + ** always defined. The trigger must be in the same schema as the table + ** or else it must be a TEMP trigger. */ + assert( p->pSchema!=0 ); + assert( p->pTabSchema!=0 ); + assert( p->pSchema==p->pTabSchema + || p->pSchema==pParse->db->aDb[1].pSchema ); + + /* Determine whether we should code this trigger */ + if( p->op==op + && p->tr_tm==tr_tm + && checkColumnOverlap(p->pColumns, pChanges) + ){ + sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump); + } + } +} + +/* +** Triggers may access values stored in the old.* or new.* pseudo-table. +** This function returns a 32-bit bitmask indicating which columns of the +** old.* or new.* tables actually are used by triggers. This information +** may be used by the caller, for example, to avoid having to load the entire +** old.* record into memory when executing an UPDATE or DELETE command. +** +** Bit 0 of the returned mask is set if the left-most column of the +** table may be accessed using an [old|new]. reference. Bit 1 is set if +** the second leftmost column value is required, and so on. If there +** are more than 32 columns in the table, and at least one of the columns +** with an index greater than 32 may be accessed, 0xffffffff is returned. +** +** It is not possible to determine if the old.rowid or new.rowid column is +** accessed by triggers. The caller must always assume that it is. +** +** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned +** applies to the old.* table. If 1, the new.* table. +** +** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE +** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only +** included in the returned mask if the TRIGGER_BEFORE bit is set in the +** tr_tm parameter. Similarly, values accessed by AFTER triggers are only +** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm. +*/ +u32 sqlite3TriggerColmask( + Parse *pParse, /* Parse context */ + Trigger *pTrigger, /* List of triggers on table pTab */ + ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ + int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */ + int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ + Table *pTab, /* The table to code triggers from */ + int orconf /* Default ON CONFLICT policy for trigger steps */ +){ + const int op = pChanges ? TK_UPDATE : TK_DELETE; + u32 mask = 0; + Trigger *p; + + assert( isNew==1 || isNew==0 ); + for(p=pTrigger; p; p=p->pNext){ + if( p->op==op && (tr_tm&p->tr_tm) + && checkColumnOverlap(p->pColumns,pChanges) + ){ + TriggerPrg *pPrg; + pPrg = getRowTrigger(pParse, p, pTab, orconf); + if( pPrg ){ + mask |= pPrg->aColmask[isNew]; + } + } + } + + return mask; +} + +#endif /* !defined(SQLITE_OMIT_TRIGGER) */ diff --git a/components/external/SQLite-3.8.1/src/update.c b/components/external/SQLite-3.8.1/src/update.c new file mode 100644 index 0000000000000000000000000000000000000000..0f760a460933290c8e1ae07869bd63d117dc127b --- /dev/null +++ b/components/external/SQLite-3.8.1/src/update.c @@ -0,0 +1,675 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains C code routines that are called by the parser +** to handle UPDATE statements. +*/ +#include "sqliteInt.h" + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Forward declaration */ +static void updateVirtualTable( + Parse *pParse, /* The parsing context */ + SrcList *pSrc, /* The virtual table to be modified */ + Table *pTab, /* The virtual table */ + ExprList *pChanges, /* The columns to change in the UPDATE statement */ + Expr *pRowidExpr, /* Expression used to recompute the rowid */ + int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ + Expr *pWhere, /* WHERE clause of the UPDATE statement */ + int onError /* ON CONFLICT strategy */ +); +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** The most recently coded instruction was an OP_Column to retrieve the +** i-th column of table pTab. This routine sets the P4 parameter of the +** OP_Column to the default value, if any. +** +** The default value of a column is specified by a DEFAULT clause in the +** column definition. This was either supplied by the user when the table +** was created, or added later to the table definition by an ALTER TABLE +** command. If the latter, then the row-records in the table btree on disk +** may not contain a value for the column and the default value, taken +** from the P4 parameter of the OP_Column instruction, is returned instead. +** If the former, then all row-records are guaranteed to include a value +** for the column and the P4 value is not required. +** +** Column definitions created by an ALTER TABLE command may only have +** literal default values specified: a number, null or a string. (If a more +** complicated default expression value was provided, it is evaluated +** when the ALTER TABLE is executed and one of the literal values written +** into the sqlite_master table.) +** +** Therefore, the P4 parameter is only required if the default value for +** the column is a literal number, string or null. The sqlite3ValueFromExpr() +** function is capable of transforming these types of expressions into +** sqlite3_value objects. +** +** If parameter iReg is not negative, code an OP_RealAffinity instruction +** on register iReg. This is used when an equivalent integer value is +** stored in place of an 8-byte floating point value in order to save +** space. +*/ +void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ + assert( pTab!=0 ); + if( !pTab->pSelect ){ + sqlite3_value *pValue = 0; + u8 enc = ENC(sqlite3VdbeDb(v)); + Column *pCol = &pTab->aCol[i]; + VdbeComment((v, "%s.%s", pTab->zName, pCol->zName)); + assert( inCol ); + sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, + pCol->affinity, &pValue); + if( pValue ){ + sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM); + } +#ifndef SQLITE_OMIT_FLOATING_POINT + if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){ + sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); + } +#endif + } +} + +/* +** Process an UPDATE statement. +** +** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL; +** \_______/ \________/ \______/ \________________/ +* onError pTabList pChanges pWhere +*/ +void sqlite3Update( + Parse *pParse, /* The parser context */ + SrcList *pTabList, /* The table in which we should change things */ + ExprList *pChanges, /* Things to be changed */ + Expr *pWhere, /* The WHERE clause. May be null */ + int onError /* How to handle constraint errors */ +){ + int i, j; /* Loop counters */ + Table *pTab; /* The table to be updated */ + int addr = 0; /* VDBE instruction address of the start of the loop */ + WhereInfo *pWInfo; /* Information about the WHERE clause */ + Vdbe *v; /* The virtual database engine */ + Index *pIdx; /* For looping over indices */ + int nIdx; /* Number of indices that need updating */ + int iCur; /* VDBE Cursor number of pTab */ + sqlite3 *db; /* The database structure */ + int *aRegIdx = 0; /* One register assigned to each index to be updated */ + int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the + ** an expression for the i-th column of the table. + ** aXRef[i]==-1 if the i-th column is not changed. */ + int chngRowid; /* True if the record number is being changed */ + Expr *pRowidExpr = 0; /* Expression defining the new record number */ + int openAll = 0; /* True if all indices need to be opened */ + AuthContext sContext; /* The authorization context */ + NameContext sNC; /* The name-context to resolve expressions in */ + int iDb; /* Database containing the table being updated */ + int okOnePass; /* True for one-pass algorithm without the FIFO */ + int hasFK; /* True if foreign key processing is required */ + +#ifndef SQLITE_OMIT_TRIGGER + int isView; /* True when updating a view (INSTEAD OF trigger) */ + Trigger *pTrigger; /* List of triggers on pTab, if required */ + int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ +#endif + int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */ + + /* Register Allocations */ + int regRowCount = 0; /* A count of rows changed */ + int regOldRowid; /* The old rowid */ + int regNewRowid; /* The new rowid */ + int regNew; /* Content of the NEW.* table in triggers */ + int regOld = 0; /* Content of OLD.* table in triggers */ + int regRowSet = 0; /* Rowset of rows to be updated */ + + memset(&sContext, 0, sizeof(sContext)); + db = pParse->db; + if( pParse->nErr || db->mallocFailed ){ + goto update_cleanup; + } + assert( pTabList->nSrc==1 ); + + /* Locate the table which we want to update. + */ + pTab = sqlite3SrcListLookup(pParse, pTabList); + if( pTab==0 ) goto update_cleanup; + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + + /* Figure out if we have any triggers and if the table being + ** updated is a view. + */ +#ifndef SQLITE_OMIT_TRIGGER + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask); + isView = pTab->pSelect!=0; + assert( pTrigger || tmask==0 ); +#else +# define pTrigger 0 +# define isView 0 +# define tmask 0 +#endif +#ifdef SQLITE_OMIT_VIEW +# undef isView +# define isView 0 +#endif + + if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + goto update_cleanup; + } + if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ + goto update_cleanup; + } + aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol ); + if( aXRef==0 ) goto update_cleanup; + for(i=0; inCol; i++) aXRef[i] = -1; + + /* Allocate a cursors for the main database table and for all indices. + ** The index cursors might not be used, but if they are used they + ** need to occur right after the database cursor. So go ahead and + ** allocate enough space, just in case. + */ + pTabList->a[0].iCursor = iCur = pParse->nTab++; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + pParse->nTab++; + } + + /* Initialize the name-context */ + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + + /* Resolve the column names in all the expressions of the + ** of the UPDATE statement. Also find the column index + ** for each column to be updated in the pChanges array. For each + ** column to be updated, make sure we have authorization to change + ** that column. + */ + chngRowid = 0; + for(i=0; inExpr; i++){ + if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ + goto update_cleanup; + } + for(j=0; jnCol; j++){ + if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){ + if( j==pTab->iPKey ){ + chngRowid = 1; + pRowidExpr = pChanges->a[i].pExpr; + } + aXRef[j] = i; + break; + } + } + if( j>=pTab->nCol ){ + if( sqlite3IsRowid(pChanges->a[i].zName) ){ + j = -1; + chngRowid = 1; + pRowidExpr = pChanges->a[i].pExpr; + }else{ + sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName); + pParse->checkSchema = 1; + goto update_cleanup; + } + } +#ifndef SQLITE_OMIT_AUTHORIZATION + { + int rc; + rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName, + j<0 ? "ROWID" : pTab->aCol[j].zName, + db->aDb[iDb].zName); + if( rc==SQLITE_DENY ){ + goto update_cleanup; + }else if( rc==SQLITE_IGNORE ){ + aXRef[j] = -1; + } + } +#endif + } + + hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid); + + /* Allocate memory for the array aRegIdx[]. There is one entry in the + ** array for each index associated with table being updated. Fill in + ** the value with a register number for indices that are to be used + ** and with zero for unused indices. + */ + for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} + if( nIdx>0 ){ + aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx ); + if( aRegIdx==0 ) goto update_cleanup; + } + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + int reg; + if( hasFK || chngRowid || pIdx->pPartIdxWhere ){ + reg = ++pParse->nMem; + }else{ + reg = 0; + for(i=0; inColumn; i++){ + if( aXRef[pIdx->aiColumn[i]]>=0 ){ + reg = ++pParse->nMem; + break; + } + } + } + aRegIdx[j] = reg; + } + + /* Begin generating code. */ + v = sqlite3GetVdbe(pParse); + if( v==0 ) goto update_cleanup; + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); + sqlite3BeginWriteOperation(pParse, 1, iDb); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + /* Virtual tables must be handled separately */ + if( IsVirtual(pTab) ){ + updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef, + pWhere, onError); + pWhere = 0; + pTabList = 0; + goto update_cleanup; + } +#endif + + /* Allocate required registers. */ + regRowSet = ++pParse->nMem; + regOldRowid = regNewRowid = ++pParse->nMem; + if( pTrigger || hasFK ){ + regOld = pParse->nMem + 1; + pParse->nMem += pTab->nCol; + } + if( chngRowid || pTrigger || hasFK ){ + regNewRowid = ++pParse->nMem; + } + regNew = pParse->nMem + 1; + pParse->nMem += pTab->nCol; + + /* Start the view context. */ + if( isView ){ + sqlite3AuthContextPush(pParse, &sContext, pTab->zName); + } + + /* If we are trying to update a view, realize that view into + ** a ephemeral table. + */ +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) + if( isView ){ + sqlite3MaterializeView(pParse, pTab, pWhere, iCur); + } +#endif + + /* Resolve the column names in all the expressions in the + ** WHERE clause. + */ + if( sqlite3ResolveExprNames(&sNC, pWhere) ){ + goto update_cleanup; + } + + /* Begin the database scan + */ + sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); + pWInfo = sqlite3WhereBegin( + pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0 + ); + if( pWInfo==0 ) goto update_cleanup; + okOnePass = sqlite3WhereOkOnePass(pWInfo); + + /* Remember the rowid of every item to be updated. + */ + sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid); + if( !okOnePass ){ + sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); + } + + /* End the database scan loop. + */ + sqlite3WhereEnd(pWInfo); + + /* Initialize the count of updated rows + */ + if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){ + regRowCount = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); + } + + if( !isView ){ + /* + ** Open every index that needs updating. Note that if any + ** index could potentially invoke a REPLACE conflict resolution + ** action, then we need to open all indices because we might need + ** to be deleting some records. + */ + if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); + if( onError==OE_Replace ){ + openAll = 1; + }else{ + openAll = 0; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->onError==OE_Replace ){ + openAll = 1; + break; + } + } + } + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + assert( aRegIdx ); + if( openAll || aRegIdx[i]>0 ){ + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb, + (char*)pKey, P4_KEYINFO_HANDOFF); + assert( pParse->nTab>iCur+i+1 ); + } + } + } + + /* Top of the update loop */ + if( okOnePass ){ + int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid); + addr = sqlite3VdbeAddOp0(v, OP_Goto); + sqlite3VdbeJumpHere(v, a1); + }else{ + addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid); + } + + /* Make cursor iCur point to the record that is being updated. If + ** this record does not exist for some reason (deleted by a trigger, + ** for example, then jump to the next iteration of the RowSet loop. */ + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); + + /* If the record number will change, set register regNewRowid to + ** contain the new value. If the record number is not being modified, + ** then regNewRowid is the same register as regOldRowid, which is + ** already populated. */ + assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid ); + if( chngRowid ){ + sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); + sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); + } + + /* If there are triggers on this table, populate an array of registers + ** with the required old.* column data. */ + if( hasFK || pTrigger ){ + u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0); + oldmask |= sqlite3TriggerColmask(pParse, + pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError + ); + for(i=0; inCol; i++){ + if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<nCol-1); + for(i=0; inCol; i++){ + if( i==pTab->iPKey ){ + /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/ + }else{ + j = aXRef[i]; + if( j>=0 ){ + sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i); + }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<nCol); + sqlite3TableAffinityStr(v, pTab); + sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, + TRIGGER_BEFORE, pTab, regOldRowid, onError, addr); + + /* The row-trigger may have deleted the row being updated. In this + ** case, jump to the next row. No updates or AFTER triggers are + ** required. This behavior - what happens when the row being updated + ** is deleted or renamed by a BEFORE trigger - is left undefined in the + ** documentation. + */ + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); + + /* If it did not delete it, the row-trigger may still have modified + ** some of the columns of the row being updated. Load the values for + ** all columns not modified by the update statement into their + ** registers in case this has happened. + */ + for(i=0; inCol; i++){ + if( aXRef[i]<0 && i!=pTab->iPKey ){ + sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i); + sqlite3ColumnDefault(v, pTab, i, regNew+i); + } + } + } + + if( !isView ){ + int j1; /* Address of jump instruction */ + + /* Do constraint checks. */ + sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid, + aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0); + + /* Do FK constraint checks. */ + if( hasFK ){ + sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid); + } + + /* Delete the index entries associated with the current record. */ + j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid); + sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx); + + /* If changing the record number, delete the old record. */ + if( hasFK || chngRowid ){ + sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0); + } + sqlite3VdbeJumpHere(v, j1); + + if( hasFK ){ + sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid); + } + + /* Insert the new index entries and the new record. */ + sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0); + + /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to + ** handle rows (possibly in other tables) that refer via a foreign key + ** to the row just updated. */ + if( hasFK ){ + sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid); + } + } + + /* Increment the row counter + */ + if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){ + sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); + } + + sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, + TRIGGER_AFTER, pTab, regOldRowid, onError, addr); + + /* Repeat the above with the next record to be updated, until + ** all record selected by the WHERE clause have been updated. + */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); + sqlite3VdbeJumpHere(v, addr); + + /* Close all tables */ + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + assert( aRegIdx ); + if( openAll || aRegIdx[i]>0 ){ + sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0); + } + } + sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); + + /* Update the sqlite_sequence table by storing the content of the + ** maximum rowid counter values recorded while inserting into + ** autoincrement tables. + */ + if( pParse->nested==0 && pParse->pTriggerTab==0 ){ + sqlite3AutoincrementEnd(pParse); + } + + /* + ** Return the number of rows that were changed. If this routine is + ** generating code because of a call to sqlite3NestedParse(), do not + ** invoke the callback function. + */ + if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){ + sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); + sqlite3VdbeSetNumCols(v, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC); + } + +update_cleanup: + sqlite3AuthContextPop(&sContext); + sqlite3DbFree(db, aRegIdx); + sqlite3DbFree(db, aXRef); + sqlite3SrcListDelete(db, pTabList); + sqlite3ExprListDelete(db, pChanges); + sqlite3ExprDelete(db, pWhere); + return; +} +/* Make sure "isView" and other macros defined above are undefined. Otherwise +** thely may interfere with compilation of other functions in this file +** (or in another file, if this file becomes part of the amalgamation). */ +#ifdef isView + #undef isView +#endif +#ifdef pTrigger + #undef pTrigger +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Generate code for an UPDATE of a virtual table. +** +** The strategy is that we create an ephemerial table that contains +** for each row to be changed: +** +** (A) The original rowid of that row. +** (B) The revised rowid for the row. (note1) +** (C) The content of every column in the row. +** +** Then we loop over this ephemeral table and for each row in +** the ephermeral table call VUpdate. +** +** When finished, drop the ephemeral table. +** +** (note1) Actually, if we know in advance that (A) is always the same +** as (B) we only store (A), then duplicate (A) when pulling +** it out of the ephemeral table before calling VUpdate. +*/ +static void updateVirtualTable( + Parse *pParse, /* The parsing context */ + SrcList *pSrc, /* The virtual table to be modified */ + Table *pTab, /* The virtual table */ + ExprList *pChanges, /* The columns to change in the UPDATE statement */ + Expr *pRowid, /* Expression used to recompute the rowid */ + int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ + Expr *pWhere, /* WHERE clause of the UPDATE statement */ + int onError /* ON CONFLICT strategy */ +){ + Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */ + ExprList *pEList = 0; /* The result set of the SELECT statement */ + Select *pSelect = 0; /* The SELECT statement */ + Expr *pExpr; /* Temporary expression */ + int ephemTab; /* Table holding the result of the SELECT */ + int i; /* Loop counter */ + int addr; /* Address of top of loop */ + int iReg; /* First register in set passed to OP_VUpdate */ + sqlite3 *db = pParse->db; /* Database connection */ + const char *pVTab = (const char*)sqlite3GetVTable(db, pTab); + SelectDest dest; + + /* Construct the SELECT statement that will find the new values for + ** all updated rows. + */ + pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_")); + if( pRowid ){ + pEList = sqlite3ExprListAppend(pParse, pEList, + sqlite3ExprDup(db, pRowid, 0)); + } + assert( pTab->iPKey<0 ); + for(i=0; inCol; i++){ + if( aXRef[i]>=0 ){ + pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0); + }else{ + pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName); + } + pEList = sqlite3ExprListAppend(pParse, pEList, pExpr); + } + pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0); + + /* Create the ephemeral table into which the update results will + ** be stored. + */ + assert( v ); + ephemTab = pParse->nTab++; + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0)); + sqlite3VdbeChangeP5(v, BTREE_UNORDERED); + + /* fill the ephemeral table + */ + sqlite3SelectDestInit(&dest, SRT_Table, ephemTab); + sqlite3Select(pParse, pSelect, &dest); + + /* Generate code to scan the ephemeral table and call VUpdate. */ + iReg = ++pParse->nMem; + pParse->nMem += pTab->nCol+1; + addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg); + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1); + for(i=0; inCol; i++){ + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i); + } + sqlite3VtabMakeWritable(pParse, pTab); + sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB); + sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); + sqlite3MayAbort(pParse); + sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); + sqlite3VdbeJumpHere(v, addr); + sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0); + + /* Cleanup */ + sqlite3SelectDelete(db, pSelect); +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ diff --git a/components/external/SQLite-3.8.1/src/utf.c b/components/external/SQLite-3.8.1/src/utf.c new file mode 100644 index 0000000000000000000000000000000000000000..ecb3ea03b87a3f49622ee860490171de0aab51f3 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/utf.c @@ -0,0 +1,530 @@ +/* +** 2004 April 13 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains routines used to translate between UTF-8, +** UTF-16, UTF-16BE, and UTF-16LE. +** +** Notes on UTF-8: +** +** Byte-0 Byte-1 Byte-2 Byte-3 Value +** 0xxxxxxx 00000000 00000000 0xxxxxxx +** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx +** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx +** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx +** +** +** Notes on UTF-16: (with wwww+1==uuuuu) +** +** Word-0 Word-1 Value +** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx +** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx +** +** +** BOM or Byte Order Mark: +** 0xff 0xfe little-endian utf-16 follows +** 0xfe 0xff big-endian utf-16 follows +** +*/ +#include "sqliteInt.h" +#include +#include "vdbeInt.h" + +#ifndef SQLITE_AMALGAMATION +/* +** The following constant value is used by the SQLITE_BIGENDIAN and +** SQLITE_LITTLEENDIAN macros. +*/ +const int sqlite3one = 1; +#endif /* SQLITE_AMALGAMATION */ + +/* +** This lookup table is used to help decode the first byte of +** a multi-byte UTF8 character. +*/ +static const unsigned char sqlite3Utf8Trans1[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, +}; + + +#define WRITE_UTF8(zOut, c) { \ + if( c<0x00080 ){ \ + *zOut++ = (u8)(c&0xFF); \ + } \ + else if( c<0x00800 ){ \ + *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ + else if( c<0x10000 ){ \ + *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + }else{ \ + *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ + *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ +} + +#define WRITE_UTF16LE(zOut, c) { \ + if( c<=0xFFFF ){ \ + *zOut++ = (u8)(c&0x00FF); \ + *zOut++ = (u8)((c>>8)&0x00FF); \ + }else{ \ + *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ + *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ + *zOut++ = (u8)(c&0x00FF); \ + *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ + } \ +} + +#define WRITE_UTF16BE(zOut, c) { \ + if( c<=0xFFFF ){ \ + *zOut++ = (u8)((c>>8)&0x00FF); \ + *zOut++ = (u8)(c&0x00FF); \ + }else{ \ + *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ + *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ + *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ + *zOut++ = (u8)(c&0x00FF); \ + } \ +} + +#define READ_UTF16LE(zIn, TERM, c){ \ + c = (*zIn++); \ + c += ((*zIn++)<<8); \ + if( c>=0xD800 && c<0xE000 && TERM ){ \ + int c2 = (*zIn++); \ + c2 += ((*zIn++)<<8); \ + c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ + } \ +} + +#define READ_UTF16BE(zIn, TERM, c){ \ + c = ((*zIn++)<<8); \ + c += (*zIn++); \ + if( c>=0xD800 && c<0xE000 && TERM ){ \ + int c2 = ((*zIn++)<<8); \ + c2 += (*zIn++); \ + c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ + } \ +} + +/* +** Translate a single UTF-8 character. Return the unicode value. +** +** During translation, assume that the byte that zTerm points +** is a 0x00. +** +** Write a pointer to the next unread byte back into *pzNext. +** +** Notes On Invalid UTF-8: +** +** * This routine never allows a 7-bit character (0x00 through 0x7f) to +** be encoded as a multi-byte character. Any multi-byte character that +** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. +** +** * This routine never allows a UTF16 surrogate value to be encoded. +** If a multi-byte character attempts to encode a value between +** 0xd800 and 0xe000 then it is rendered as 0xfffd. +** +** * Bytes in the range of 0x80 through 0xbf which occur as the first +** byte of a character are interpreted as single-byte characters +** and rendered as themselves even though they are technically +** invalid characters. +** +** * This routine accepts an infinite number of different UTF8 encodings +** for unicode values 0x80 and greater. It do not change over-length +** encodings to 0xfffd as some systems recommend. +*/ +#define READ_UTF8(zIn, zTerm, c) \ + c = *(zIn++); \ + if( c>=0xc0 ){ \ + c = sqlite3Utf8Trans1[c-0xc0]; \ + while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ + c = (c<<6) + (0x3f & *(zIn++)); \ + } \ + if( c<0x80 \ + || (c&0xFFFFF800)==0xD800 \ + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ + } +u32 sqlite3Utf8Read( + const unsigned char **pz /* Pointer to string from which to read char */ +){ + unsigned int c; + + /* Same as READ_UTF8() above but without the zTerm parameter. + ** For this routine, we assume the UTF8 string is always zero-terminated. + */ + c = *((*pz)++); + if( c>=0xc0 ){ + c = sqlite3Utf8Trans1[c-0xc0]; + while( (*(*pz) & 0xc0)==0x80 ){ + c = (c<<6) + (0x3f & *((*pz)++)); + } + if( c<0x80 + || (c&0xFFFFF800)==0xD800 + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } + } + return c; +} + + + + +/* +** If the TRANSLATE_TRACE macro is defined, the value of each Mem is +** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). +*/ +/* #define TRANSLATE_TRACE 1 */ + +#ifndef SQLITE_OMIT_UTF16 +/* +** This routine transforms the internal text encoding used by pMem to +** desiredEnc. It is an error if the string is already of the desired +** encoding, or if *pMem does not contain a string value. +*/ +int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){ + int len; /* Maximum length of output string in bytes */ + unsigned char *zOut; /* Output buffer */ + unsigned char *zIn; /* Input iterator */ + unsigned char *zTerm; /* End of input */ + unsigned char *z; /* Output iterator */ + unsigned int c; + + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( pMem->flags&MEM_Str ); + assert( pMem->enc!=desiredEnc ); + assert( pMem->enc!=0 ); + assert( pMem->n>=0 ); + +#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) + { + char zBuf[100]; + sqlite3VdbeMemPrettyPrint(pMem, zBuf); + fprintf(stderr, "INPUT: %s\n", zBuf); + } +#endif + + /* If the translation is between UTF-16 little and big endian, then + ** all that is required is to swap the byte order. This case is handled + ** differently from the others. + */ + if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ + u8 temp; + int rc; + rc = sqlite3VdbeMemMakeWriteable(pMem); + if( rc!=SQLITE_OK ){ + assert( rc==SQLITE_NOMEM ); + return SQLITE_NOMEM; + } + zIn = (u8*)pMem->z; + zTerm = &zIn[pMem->n&~1]; + while( zInenc = desiredEnc; + goto translate_out; + } + + /* Set len to the maximum number of bytes required in the output buffer. */ + if( desiredEnc==SQLITE_UTF8 ){ + /* When converting from UTF-16, the maximum growth results from + ** translating a 2-byte character to a 4-byte UTF-8 character. + ** A single byte is required for the output string + ** nul-terminator. + */ + pMem->n &= ~1; + len = pMem->n * 2 + 1; + }else{ + /* When converting from UTF-8 to UTF-16 the maximum growth is caused + ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 + ** character. Two bytes are required in the output buffer for the + ** nul-terminator. + */ + len = pMem->n * 2 + 2; + } + + /* Set zIn to point at the start of the input buffer and zTerm to point 1 + ** byte past the end. + ** + ** Variable zOut is set to point at the output buffer, space obtained + ** from sqlite3_malloc(). + */ + zIn = (u8*)pMem->z; + zTerm = &zIn[pMem->n]; + zOut = sqlite3DbMallocRaw(pMem->db, len); + if( !zOut ){ + return SQLITE_NOMEM; + } + z = zOut; + + if( pMem->enc==SQLITE_UTF8 ){ + if( desiredEnc==SQLITE_UTF16LE ){ + /* UTF-8 -> UTF-16 Little-endian */ + while( zIn UTF-16 Big-endian */ + while( zInn = (int)(z - zOut); + *z++ = 0; + }else{ + assert( desiredEnc==SQLITE_UTF8 ); + if( pMem->enc==SQLITE_UTF16LE ){ + /* UTF-16 Little-endian -> UTF-8 */ + while( zIn UTF-8 */ + while( zInn = (int)(z - zOut); + } + *z = 0; + assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); + + sqlite3VdbeMemRelease(pMem); + pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem); + pMem->enc = desiredEnc; + pMem->flags |= (MEM_Term|MEM_Dyn); + pMem->z = (char*)zOut; + pMem->zMalloc = pMem->z; + +translate_out: +#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) + { + char zBuf[100]; + sqlite3VdbeMemPrettyPrint(pMem, zBuf); + fprintf(stderr, "OUTPUT: %s\n", zBuf); + } +#endif + return SQLITE_OK; +} + +/* +** This routine checks for a byte-order mark at the beginning of the +** UTF-16 string stored in *pMem. If one is present, it is removed and +** the encoding of the Mem adjusted. This routine does not do any +** byte-swapping, it just sets Mem.enc appropriately. +** +** The allocation (static, dynamic etc.) and encoding of the Mem may be +** changed by this function. +*/ +int sqlite3VdbeMemHandleBom(Mem *pMem){ + int rc = SQLITE_OK; + u8 bom = 0; + + assert( pMem->n>=0 ); + if( pMem->n>1 ){ + u8 b1 = *(u8 *)pMem->z; + u8 b2 = *(((u8 *)pMem->z) + 1); + if( b1==0xFE && b2==0xFF ){ + bom = SQLITE_UTF16BE; + } + if( b1==0xFF && b2==0xFE ){ + bom = SQLITE_UTF16LE; + } + } + + if( bom ){ + rc = sqlite3VdbeMemMakeWriteable(pMem); + if( rc==SQLITE_OK ){ + pMem->n -= 2; + memmove(pMem->z, &pMem->z[2], pMem->n); + pMem->z[pMem->n] = '\0'; + pMem->z[pMem->n+1] = '\0'; + pMem->flags |= MEM_Term; + pMem->enc = bom; + } + } + return rc; +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, +** return the number of unicode characters in pZ up to (but not including) +** the first 0x00 byte. If nByte is not less than zero, return the +** number of unicode characters in the first nByte of pZ (or up to +** the first 0x00, whichever comes first). +*/ +int sqlite3Utf8CharLen(const char *zIn, int nByte){ + int r = 0; + const u8 *z = (const u8*)zIn; + const u8 *zTerm; + if( nByte>=0 ){ + zTerm = &z[nByte]; + }else{ + zTerm = (const u8*)(-1); + } + assert( z<=zTerm ); + while( *z!=0 && zmallocFailed ){ + sqlite3VdbeMemRelease(&m); + m.z = 0; + } + assert( (m.flags & MEM_Term)!=0 || db->mallocFailed ); + assert( (m.flags & MEM_Str)!=0 || db->mallocFailed ); + assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed ); + assert( m.z || db->mallocFailed ); + return m.z; +} + +/* +** zIn is a UTF-16 encoded unicode string at least nChar characters long. +** Return the number of bytes in the first nChar unicode characters +** in pZ. nChar must be non-negative. +*/ +int sqlite3Utf16ByteLen(const void *zIn, int nChar){ + int c; + unsigned char const *z = zIn; + int n = 0; + + if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){ + while( n0 && n<=4 ); + z[0] = 0; + z = zBuf; + c = sqlite3Utf8Read((const u8**)&z); + t = i; + if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; + if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; + assert( c==t ); + assert( (z-zBuf)==n ); + } + for(i=0; i<0x00110000; i++){ + if( i>=0xD800 && i<0xE000 ) continue; + z = zBuf; + WRITE_UTF16LE(z, i); + n = (int)(z-zBuf); + assert( n>0 && n<=4 ); + z[0] = 0; + z = zBuf; + READ_UTF16LE(z, 1, c); + assert( c==i ); + assert( (z-zBuf)==n ); + } + for(i=0; i<0x00110000; i++){ + if( i>=0xD800 && i<0xE000 ) continue; + z = zBuf; + WRITE_UTF16BE(z, i); + n = (int)(z-zBuf); + assert( n>0 && n<=4 ); + z[0] = 0; + z = zBuf; + READ_UTF16BE(z, 1, c); + assert( c==i ); + assert( (z-zBuf)==n ); + } +} +#endif /* SQLITE_TEST */ +#endif /* SQLITE_OMIT_UTF16 */ diff --git a/components/external/SQLite-3.8.1/src/util.c b/components/external/SQLite-3.8.1/src/util.c new file mode 100644 index 0000000000000000000000000000000000000000..50ffd98650bf862985cd453ace8830063847ebf9 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/util.c @@ -0,0 +1,1287 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Utility functions used throughout sqlite. +** +** This file contains functions for allocating memory, comparing +** strings, and stuff like that. +** +*/ +#include "sqliteInt.h" +#include +#ifdef SQLITE_HAVE_ISNAN +# include +#endif + +/* +** Routine needed to support the testcase() macro. +*/ +#ifdef SQLITE_COVERAGE_TEST +void sqlite3Coverage(int x){ + static unsigned dummy = 0; + dummy += (unsigned)x; +} +#endif + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* +** Return true if the floating point value is Not a Number (NaN). +** +** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN. +** Otherwise, we have our own implementation that works on most systems. +*/ +int sqlite3IsNaN(double x){ + int rc; /* The value return */ +#if !defined(SQLITE_HAVE_ISNAN) + /* + ** Systems that support the isnan() library function should probably + ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have + ** found that many systems do not have a working isnan() function so + ** this implementation is provided as an alternative. + ** + ** This NaN test sometimes fails if compiled on GCC with -ffast-math. + ** On the other hand, the use of -ffast-math comes with the following + ** warning: + ** + ** This option [-ffast-math] should never be turned on by any + ** -O option since it can result in incorrect output for programs + ** which depend on an exact implementation of IEEE or ISO + ** rules/specifications for math functions. + ** + ** Under MSVC, this NaN test may fail if compiled with a floating- + ** point precision mode other than /fp:precise. From the MSDN + ** documentation: + ** + ** The compiler [with /fp:precise] will properly handle comparisons + ** involving NaN. For example, x != x evaluates to true if x is NaN + ** ... + */ +#ifdef __FAST_MATH__ +# error SQLite will not work correctly with the -ffast-math option of GCC. +#endif + volatile double y = x; + volatile double z = y; + rc = (y!=z); +#else /* if defined(SQLITE_HAVE_ISNAN) */ + rc = isnan(x); +#endif /* SQLITE_HAVE_ISNAN */ + testcase( rc ); + return rc; +} +#endif /* SQLITE_OMIT_FLOATING_POINT */ + +/* +** Compute a string length that is limited to what can be stored in +** lower 30 bits of a 32-bit signed integer. +** +** The value returned will never be negative. Nor will it ever be greater +** than the actual length of the string. For very long strings (greater +** than 1GiB) the value returned might be less than the true string length. +*/ +int sqlite3Strlen30(const char *z){ + const char *z2 = z; + if( z==0 ) return 0; + while( *z2 ){ z2++; } + return 0x3fffffff & (int)(z2 - z); +} + +/* +** Set the most recent error code and error string for the sqlite +** handle "db". The error code is set to "err_code". +** +** If it is not NULL, string zFormat specifies the format of the +** error string in the style of the printf functions: The following +** format characters are allowed: +** +** %s Insert a string +** %z A string that should be freed after use +** %d Insert an integer +** %T Insert a token +** %S Insert the first element of a SrcList +** +** zFormat and any string tokens that follow it are assumed to be +** encoded in UTF-8. +** +** To clear the most recent error for sqlite handle "db", sqlite3Error +** should be called with err_code set to SQLITE_OK and zFormat set +** to NULL. +*/ +void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){ + if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){ + db->errCode = err_code; + if( zFormat ){ + char *z; + va_list ap; + va_start(ap, zFormat); + z = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC); + }else{ + sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC); + } + } +} + +/* +** Add an error message to pParse->zErrMsg and increment pParse->nErr. +** The following formatting characters are allowed: +** +** %s Insert a string +** %z A string that should be freed after use +** %d Insert an integer +** %T Insert a token +** %S Insert the first element of a SrcList +** +** This function should be used to report any error that occurs whilst +** compiling an SQL statement (i.e. within sqlite3_prepare()). The +** last thing the sqlite3_prepare() function does is copy the error +** stored by this function into the database handle using sqlite3Error(). +** Function sqlite3Error() should be used during statement execution +** (sqlite3_step() etc.). +*/ +void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ + char *zMsg; + va_list ap; + sqlite3 *db = pParse->db; + va_start(ap, zFormat); + zMsg = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); + if( db->suppressErr ){ + sqlite3DbFree(db, zMsg); + }else{ + pParse->nErr++; + sqlite3DbFree(db, pParse->zErrMsg); + pParse->zErrMsg = zMsg; + pParse->rc = SQLITE_ERROR; + } +} + +/* +** Convert an SQL-style quoted string into a normal string by removing +** the quote characters. The conversion is done in-place. If the +** input does not begin with a quote character, then this routine +** is a no-op. +** +** The input string must be zero-terminated. A new zero-terminator +** is added to the dequoted string. +** +** The return value is -1 if no dequoting occurs or the length of the +** dequoted string, exclusive of the zero terminator, if dequoting does +** occur. +** +** 2002-Feb-14: This routine is extended to remove MS-Access style +** brackets from around identifers. For example: "[a-b-c]" becomes +** "a-b-c". +*/ +int sqlite3Dequote(char *z){ + char quote; + int i, j; + if( z==0 ) return -1; + quote = z[0]; + switch( quote ){ + case '\'': break; + case '"': break; + case '`': break; /* For MySQL compatibility */ + case '[': quote = ']'; break; /* For MS SqlServer compatibility */ + default: return -1; + } + for(i=1, j=0;; i++){ + assert( z[i] ); + if( z[i]==quote ){ + if( z[i+1]==quote ){ + z[j++] = quote; + i++; + }else{ + break; + } + }else{ + z[j++] = z[i]; + } + } + z[j] = 0; + return j; +} + +/* Convenient short-hand */ +#define UpperToLower sqlite3UpperToLower + +/* +** Some systems have stricmp(). Others have strcasecmp(). Because +** there is no consistency, we will define our own. +** +** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and +** sqlite3_strnicmp() APIs allow applications and extensions to compare +** the contents of two buffers containing UTF-8 strings in a +** case-independent fashion, using the same definition of "case +** independence" that SQLite uses internally when comparing identifiers. +*/ +int sqlite3_stricmp(const char *zLeft, const char *zRight){ + register unsigned char *a, *b; + a = (unsigned char *)zLeft; + b = (unsigned char *)zRight; + while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; } + return UpperToLower[*a] - UpperToLower[*b]; +} +int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ + register unsigned char *a, *b; + a = (unsigned char *)zLeft; + b = (unsigned char *)zRight; + while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; } + return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b]; +} + +/* +** The string z[] is an text representation of a real number. +** Convert this string to a double and write it into *pResult. +** +** The string z[] is length bytes in length (bytes, not characters) and +** uses the encoding enc. The string is not necessarily zero-terminated. +** +** Return TRUE if the result is a valid real number (or integer) and FALSE +** if the string is empty or contains extraneous text. Valid numbers +** are in one of these formats: +** +** [+-]digits[E[+-]digits] +** [+-]digits.[digits][E[+-]digits] +** [+-].digits[E[+-]digits] +** +** Leading and trailing whitespace is ignored for the purpose of determining +** validity. +** +** If some prefix of the input string is a valid number, this routine +** returns FALSE but it still converts the prefix and writes the result +** into *pResult. +*/ +int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ +#ifndef SQLITE_OMIT_FLOATING_POINT + int incr; + const char *zEnd = z + length; + /* sign * significand * (10 ^ (esign * exponent)) */ + int sign = 1; /* sign of significand */ + i64 s = 0; /* significand */ + int d = 0; /* adjust exponent for shifting decimal point */ + int esign = 1; /* sign of exponent */ + int e = 0; /* exponent */ + int eValid = 1; /* True exponent is either not used or is well-formed */ + double result; + int nDigits = 0; + int nonNum = 0; + + assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); + *pResult = 0.0; /* Default return value, in case of an error */ + + if( enc==SQLITE_UTF8 ){ + incr = 1; + }else{ + int i; + incr = 2; + assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); + for(i=3-enc; i=zEnd ) return 0; + + /* get sign of significand */ + if( *z=='-' ){ + sign = -1; + z+=incr; + }else if( *z=='+' ){ + z+=incr; + } + + /* skip leading zeroes */ + while( z=zEnd ) goto do_atof_calc; + + /* if decimal point is present */ + if( *z=='.' ){ + z+=incr; + /* copy digits from after decimal to significand + ** (decrease exponent by d to shift decimal right) */ + while( z=zEnd ) goto do_atof_calc; + + /* if exponent is present */ + if( *z=='e' || *z=='E' ){ + z+=incr; + eValid = 0; + if( z>=zEnd ) goto do_atof_calc; + /* get sign of exponent */ + if( *z=='-' ){ + esign = -1; + z+=incr; + }else if( *z=='+' ){ + z+=incr; + } + /* copy digits to exponent */ + while( z0 ){ + while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10; + }else{ + while( !(s%10) && e>0 ) e--,s/=10; + } + + /* adjust the sign of significand */ + s = sign<0 ? -s : s; + + /* if exponent, scale significand as appropriate + ** and store in result. */ + if( e ){ + LONGDOUBLE_TYPE scale = 1.0; + /* attempt to handle extremely small/large numbers better */ + if( e>307 && e<342 ){ + while( e%308 ) { scale *= 1.0e+1; e -= 1; } + if( esign<0 ){ + result = s / scale; + result /= 1.0e+308; + }else{ + result = s * scale; + result *= 1.0e+308; + } + }else if( e>=342 ){ + if( esign<0 ){ + result = 0.0*s; + }else{ + result = 1e308*1e308*s; /* Infinity */ + } + }else{ + /* 1.0e+22 is the largest power of 10 than can be + ** represented exactly. */ + while( e%22 ) { scale *= 1.0e+1; e -= 1; } + while( e>0 ) { scale *= 1.0e+22; e -= 22; } + if( esign<0 ){ + result = s / scale; + }else{ + result = s * scale; + } + } + } else { + result = (double)s; + } + } + + /* store the result */ + *pResult = result; + + /* return true if number and no extra non-whitespace chracters after */ + return z>=zEnd && nDigits>0 && eValid && nonNum==0; +#else + return !sqlite3Atoi64(z, pResult, length, enc); +#endif /* SQLITE_OMIT_FLOATING_POINT */ +} + +/* +** Compare the 19-character string zNum against the text representation +** value 2^63: 9223372036854775808. Return negative, zero, or positive +** if zNum is less than, equal to, or greater than the string. +** Note that zNum must contain exactly 19 characters. +** +** Unlike memcmp() this routine is guaranteed to return the difference +** in the values of the last digit if the only difference is in the +** last digit. So, for example, +** +** compare2pow63("9223372036854775800", 1) +** +** will return -8. +*/ +static int compare2pow63(const char *zNum, int incr){ + int c = 0; + int i; + /* 012345678901234567 */ + const char *pow63 = "922337203685477580"; + for(i=0; c==0 && i<18; i++){ + c = (zNum[i*incr]-pow63[i])*10; + } + if( c==0 ){ + c = zNum[18*incr] - '8'; + testcase( c==(-1) ); + testcase( c==0 ); + testcase( c==(+1) ); + } + return c; +} + + +/* +** Convert zNum to a 64-bit signed integer. +** +** If the zNum value is representable as a 64-bit twos-complement +** integer, then write that value into *pNum and return 0. +** +** If zNum is exactly 9223372036854665808, return 2. This special +** case is broken out because while 9223372036854665808 cannot be a +** signed 64-bit integer, its negative -9223372036854665808 can be. +** +** If zNum is too big for a 64-bit integer and is not +** 9223372036854665808 or if zNum contains any non-numeric text, +** then return 1. +** +** length is the number of bytes in the string (bytes, not characters). +** The string is not necessarily zero-terminated. The encoding is +** given by enc. +*/ +int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){ + int incr; + u64 u = 0; + int neg = 0; /* assume positive */ + int i; + int c = 0; + int nonNum = 0; + const char *zStart; + const char *zEnd = zNum + length; + assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); + if( enc==SQLITE_UTF8 ){ + incr = 1; + }else{ + incr = 2; + assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); + for(i=3-enc; i='0' && c<='9'; i+=incr){ + u = u*10 + c - '0'; + } + if( u>LARGEST_INT64 ){ + *pNum = SMALLEST_INT64; + }else if( neg ){ + *pNum = -(i64)u; + }else{ + *pNum = (i64)u; + } + testcase( i==18 ); + testcase( i==19 ); + testcase( i==20 ); + if( (c!=0 && &zNum[i]19*incr || nonNum ){ + /* zNum is empty or contains non-numeric text or is longer + ** than 19 digits (thus guaranteeing that it is too large) */ + return 1; + }else if( i<19*incr ){ + /* Less than 19 digits, so we know that it fits in 64 bits */ + assert( u<=LARGEST_INT64 ); + return 0; + }else{ + /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ + c = compare2pow63(zNum, incr); + if( c<0 ){ + /* zNum is less than 9223372036854775808 so it fits */ + assert( u<=LARGEST_INT64 ); + return 0; + }else if( c>0 ){ + /* zNum is greater than 9223372036854775808 so it overflows */ + return 1; + }else{ + /* zNum is exactly 9223372036854775808. Fits if negative. The + ** special case 2 overflow if positive */ + assert( u-1==LARGEST_INT64 ); + assert( (*pNum)==SMALLEST_INT64 ); + return neg ? 0 : 2; + } + } +} + +/* +** If zNum represents an integer that will fit in 32-bits, then set +** *pValue to that integer and return true. Otherwise return false. +** +** Any non-numeric characters that following zNum are ignored. +** This is different from sqlite3Atoi64() which requires the +** input number to be zero-terminated. +*/ +int sqlite3GetInt32(const char *zNum, int *pValue){ + sqlite_int64 v = 0; + int i, c; + int neg = 0; + if( zNum[0]=='-' ){ + neg = 1; + zNum++; + }else if( zNum[0]=='+' ){ + zNum++; + } + while( zNum[0]=='0' ) zNum++; + for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){ + v = v*10 + c; + } + + /* The longest decimal representation of a 32 bit integer is 10 digits: + ** + ** 1234567890 + ** 2^31 -> 2147483648 + */ + testcase( i==10 ); + if( i>10 ){ + return 0; + } + testcase( v-neg==2147483647 ); + if( v-neg>2147483647 ){ + return 0; + } + if( neg ){ + v = -v; + } + *pValue = (int)v; + return 1; +} + +/* +** Return a 32-bit integer value extracted from a string. If the +** string is not an integer, just return 0. +*/ +int sqlite3Atoi(const char *z){ + int x = 0; + if( z ) sqlite3GetInt32(z, &x); + return x; +} + +/* +** The variable-length integer encoding is as follows: +** +** KEY: +** A = 0xxxxxxx 7 bits of data and one flag bit +** B = 1xxxxxxx 7 bits of data and one flag bit +** C = xxxxxxxx 8 bits of data +** +** 7 bits - A +** 14 bits - BA +** 21 bits - BBA +** 28 bits - BBBA +** 35 bits - BBBBA +** 42 bits - BBBBBA +** 49 bits - BBBBBBA +** 56 bits - BBBBBBBA +** 64 bits - BBBBBBBBC +*/ + +/* +** Write a 64-bit variable-length integer to memory starting at p[0]. +** The length of data write will be between 1 and 9 bytes. The number +** of bytes written is returned. +** +** A variable-length integer consists of the lower 7 bits of each byte +** for all bytes that have the 8th bit set and one byte with the 8th +** bit clear. Except, if we get to the 9th byte, it stores the full +** 8 bits and is the last byte. +*/ +int sqlite3PutVarint(unsigned char *p, u64 v){ + int i, j, n; + u8 buf[10]; + if( v & (((u64)0xff000000)<<32) ){ + p[8] = (u8)v; + v >>= 8; + for(i=7; i>=0; i--){ + p[i] = (u8)((v & 0x7f) | 0x80); + v >>= 7; + } + return 9; + } + n = 0; + do{ + buf[n++] = (u8)((v & 0x7f) | 0x80); + v >>= 7; + }while( v!=0 ); + buf[0] &= 0x7f; + assert( n<=9 ); + for(i=0, j=n-1; j>=0; j--, i++){ + p[i] = buf[j]; + } + return n; +} + +/* +** This routine is a faster version of sqlite3PutVarint() that only +** works for 32-bit positive integers and which is optimized for +** the common case of small integers. A MACRO version, putVarint32, +** is provided which inlines the single-byte case. All code should use +** the MACRO version as this function assumes the single-byte case has +** already been handled. +*/ +int sqlite3PutVarint32(unsigned char *p, u32 v){ +#ifndef putVarint32 + if( (v & ~0x7f)==0 ){ + p[0] = v; + return 1; + } +#endif + if( (v & ~0x3fff)==0 ){ + p[0] = (u8)((v>>7) | 0x80); + p[1] = (u8)(v & 0x7f); + return 2; + } + return sqlite3PutVarint(p, v); +} + +/* +** Bitmasks used by sqlite3GetVarint(). These precomputed constants +** are defined here rather than simply putting the constant expressions +** inline in order to work around bugs in the RVT compiler. +** +** SLOT_2_0 A mask for (0x7f<<14) | 0x7f +** +** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0 +*/ +#define SLOT_2_0 0x001fc07f +#define SLOT_4_2_0 0xf01fc07f + + +/* +** Read a 64-bit variable-length integer from memory starting at p[0]. +** Return the number of bytes read. The value is stored in *v. +*/ +u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ + u32 a,b,s; + + a = *p; + /* a: p0 (unmasked) */ + if (!(a&0x80)) + { + *v = a; + return 1; + } + + p++; + b = *p; + /* b: p1 (unmasked) */ + if (!(b&0x80)) + { + a &= 0x7f; + a = a<<7; + a |= b; + *v = a; + return 2; + } + + /* Verify that constants are precomputed correctly */ + assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) ); + assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) ); + + p++; + a = a<<14; + a |= *p; + /* a: p0<<14 | p2 (unmasked) */ + if (!(a&0x80)) + { + a &= SLOT_2_0; + b &= 0x7f; + b = b<<7; + a |= b; + *v = a; + return 3; + } + + /* CSE1 from below */ + a &= SLOT_2_0; + p++; + b = b<<14; + b |= *p; + /* b: p1<<14 | p3 (unmasked) */ + if (!(b&0x80)) + { + b &= SLOT_2_0; + /* moved CSE1 up */ + /* a &= (0x7f<<14)|(0x7f); */ + a = a<<7; + a |= b; + *v = a; + return 4; + } + + /* a: p0<<14 | p2 (masked) */ + /* b: p1<<14 | p3 (unmasked) */ + /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ + /* moved CSE1 up */ + /* a &= (0x7f<<14)|(0x7f); */ + b &= SLOT_2_0; + s = a; + /* s: p0<<14 | p2 (masked) */ + + p++; + a = a<<14; + a |= *p; + /* a: p0<<28 | p2<<14 | p4 (unmasked) */ + if (!(a&0x80)) + { + /* we can skip these cause they were (effectively) done above in calc'ing s */ + /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ + /* b &= (0x7f<<14)|(0x7f); */ + b = b<<7; + a |= b; + s = s>>18; + *v = ((u64)s)<<32 | a; + return 5; + } + + /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ + s = s<<7; + s |= b; + /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ + + p++; + b = b<<14; + b |= *p; + /* b: p1<<28 | p3<<14 | p5 (unmasked) */ + if (!(b&0x80)) + { + /* we can skip this cause it was (effectively) done above in calc'ing s */ + /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ + a &= SLOT_2_0; + a = a<<7; + a |= b; + s = s>>18; + *v = ((u64)s)<<32 | a; + return 6; + } + + p++; + a = a<<14; + a |= *p; + /* a: p2<<28 | p4<<14 | p6 (unmasked) */ + if (!(a&0x80)) + { + a &= SLOT_4_2_0; + b &= SLOT_2_0; + b = b<<7; + a |= b; + s = s>>11; + *v = ((u64)s)<<32 | a; + return 7; + } + + /* CSE2 from below */ + a &= SLOT_2_0; + p++; + b = b<<14; + b |= *p; + /* b: p3<<28 | p5<<14 | p7 (unmasked) */ + if (!(b&0x80)) + { + b &= SLOT_4_2_0; + /* moved CSE2 up */ + /* a &= (0x7f<<14)|(0x7f); */ + a = a<<7; + a |= b; + s = s>>4; + *v = ((u64)s)<<32 | a; + return 8; + } + + p++; + a = a<<15; + a |= *p; + /* a: p4<<29 | p6<<15 | p8 (unmasked) */ + + /* moved CSE2 up */ + /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ + b &= SLOT_2_0; + b = b<<8; + a |= b; + + s = s<<4; + b = p[-4]; + b &= 0x7f; + b = b>>3; + s |= b; + + *v = ((u64)s)<<32 | a; + + return 9; +} + +/* +** Read a 32-bit variable-length integer from memory starting at p[0]. +** Return the number of bytes read. The value is stored in *v. +** +** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned +** integer, then set *v to 0xffffffff. +** +** A MACRO version, getVarint32, is provided which inlines the +** single-byte case. All code should use the MACRO version as +** this function assumes the single-byte case has already been handled. +*/ +u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ + u32 a,b; + + /* The 1-byte case. Overwhelmingly the most common. Handled inline + ** by the getVarin32() macro */ + a = *p; + /* a: p0 (unmasked) */ +#ifndef getVarint32 + if (!(a&0x80)) + { + /* Values between 0 and 127 */ + *v = a; + return 1; + } +#endif + + /* The 2-byte case */ + p++; + b = *p; + /* b: p1 (unmasked) */ + if (!(b&0x80)) + { + /* Values between 128 and 16383 */ + a &= 0x7f; + a = a<<7; + *v = a | b; + return 2; + } + + /* The 3-byte case */ + p++; + a = a<<14; + a |= *p; + /* a: p0<<14 | p2 (unmasked) */ + if (!(a&0x80)) + { + /* Values between 16384 and 2097151 */ + a &= (0x7f<<14)|(0x7f); + b &= 0x7f; + b = b<<7; + *v = a | b; + return 3; + } + + /* A 32-bit varint is used to store size information in btrees. + ** Objects are rarely larger than 2MiB limit of a 3-byte varint. + ** A 3-byte varint is sufficient, for example, to record the size + ** of a 1048569-byte BLOB or string. + ** + ** We only unroll the first 1-, 2-, and 3- byte cases. The very + ** rare larger cases can be handled by the slower 64-bit varint + ** routine. + */ +#if 1 + { + u64 v64; + u8 n; + + p -= 2; + n = sqlite3GetVarint(p, &v64); + assert( n>3 && n<=9 ); + if( (v64 & SQLITE_MAX_U32)!=v64 ){ + *v = 0xffffffff; + }else{ + *v = (u32)v64; + } + return n; + } + +#else + /* For following code (kept for historical record only) shows an + ** unrolling for the 3- and 4-byte varint cases. This code is + ** slightly faster, but it is also larger and much harder to test. + */ + p++; + b = b<<14; + b |= *p; + /* b: p1<<14 | p3 (unmasked) */ + if (!(b&0x80)) + { + /* Values between 2097152 and 268435455 */ + b &= (0x7f<<14)|(0x7f); + a &= (0x7f<<14)|(0x7f); + a = a<<7; + *v = a | b; + return 4; + } + + p++; + a = a<<14; + a |= *p; + /* a: p0<<28 | p2<<14 | p4 (unmasked) */ + if (!(a&0x80)) + { + /* Values between 268435456 and 34359738367 */ + a &= SLOT_4_2_0; + b &= SLOT_4_2_0; + b = b<<7; + *v = a | b; + return 5; + } + + /* We can only reach this point when reading a corrupt database + ** file. In that case we are not in any hurry. Use the (relatively + ** slow) general-purpose sqlite3GetVarint() routine to extract the + ** value. */ + { + u64 v64; + u8 n; + + p -= 4; + n = sqlite3GetVarint(p, &v64); + assert( n>5 && n<=9 ); + *v = (u32)v64; + return n; + } +#endif +} + +/* +** Return the number of bytes that will be needed to store the given +** 64-bit integer. +*/ +int sqlite3VarintLen(u64 v){ + int i = 0; + do{ + i++; + v >>= 7; + }while( v!=0 && ALWAYS(i<9) ); + return i; +} + + +/* +** Read or write a four-byte big-endian integer value. +*/ +u32 sqlite3Get4byte(const u8 *p){ + return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]; +} +void sqlite3Put4byte(unsigned char *p, u32 v){ + p[0] = (u8)(v>>24); + p[1] = (u8)(v>>16); + p[2] = (u8)(v>>8); + p[3] = (u8)v; +} + + + +/* +** Translate a single byte of Hex into an integer. +** This routine only works if h really is a valid hexadecimal +** character: 0..9a..fA..F +*/ +u8 sqlite3HexToInt(int h){ + assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); +#ifdef SQLITE_ASCII + h += 9*(1&(h>>6)); +#endif +#ifdef SQLITE_EBCDIC + h += 9*(1&~(h>>4)); +#endif + return (u8)(h & 0xf); +} + +#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) +/* +** Convert a BLOB literal of the form "x'hhhhhh'" into its binary +** value. Return a pointer to its binary value. Space to hold the +** binary value has been obtained from malloc and must be freed by +** the calling routine. +*/ +void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){ + char *zBlob; + int i; + + zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1); + n--; + if( zBlob ){ + for(i=0; imagic; + if( magic!=SQLITE_MAGIC_OPEN ){ + if( sqlite3SafetyCheckSickOrOk(db) ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + logBadConnection("unopened"); + } + return 0; + }else{ + return 1; + } +} +int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ + u32 magic; + magic = db->magic; + if( magic!=SQLITE_MAGIC_SICK && + magic!=SQLITE_MAGIC_OPEN && + magic!=SQLITE_MAGIC_BUSY ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + logBadConnection("invalid"); + return 0; + }else{ + return 1; + } +} + +/* +** Attempt to add, substract, or multiply the 64-bit signed value iB against +** the other 64-bit signed integer at *pA and store the result in *pA. +** Return 0 on success. Or if the operation would have resulted in an +** overflow, leave *pA unchanged and return 1. +*/ +int sqlite3AddInt64(i64 *pA, i64 iB){ + i64 iA = *pA; + testcase( iA==0 ); testcase( iA==1 ); + testcase( iB==-1 ); testcase( iB==0 ); + if( iB>=0 ){ + testcase( iA>0 && LARGEST_INT64 - iA == iB ); + testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 ); + if( iA>0 && LARGEST_INT64 - iA < iB ) return 1; + *pA += iB; + }else{ + testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 ); + testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 ); + if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1; + *pA += iB; + } + return 0; +} +int sqlite3SubInt64(i64 *pA, i64 iB){ + testcase( iB==SMALLEST_INT64+1 ); + if( iB==SMALLEST_INT64 ){ + testcase( (*pA)==(-1) ); testcase( (*pA)==0 ); + if( (*pA)>=0 ) return 1; + *pA -= iB; + return 0; + }else{ + return sqlite3AddInt64(pA, -iB); + } +} +#define TWOPOWER32 (((i64)1)<<32) +#define TWOPOWER31 (((i64)1)<<31) +int sqlite3MulInt64(i64 *pA, i64 iB){ + i64 iA = *pA; + i64 iA1, iA0, iB1, iB0, r; + + iA1 = iA/TWOPOWER32; + iA0 = iA % TWOPOWER32; + iB1 = iB/TWOPOWER32; + iB0 = iB % TWOPOWER32; + if( iA1*iB1 != 0 ) return 1; + assert( iA1*iB0==0 || iA0*iB1==0 ); + r = iA1*iB0 + iA0*iB1; + testcase( r==(-TWOPOWER31)-1 ); + testcase( r==(-TWOPOWER31) ); + testcase( r==TWOPOWER31 ); + testcase( r==TWOPOWER31-1 ); + if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1; + r *= TWOPOWER32; + if( sqlite3AddInt64(&r, iA0*iB0) ) return 1; + *pA = r; + return 0; +} + +/* +** Compute the absolute value of a 32-bit signed integer, of possible. Or +** if the integer has a value of -2147483648, return +2147483647 +*/ +int sqlite3AbsInt32(int x){ + if( x>=0 ) return x; + if( x==(int)0x80000000 ) return 0x7fffffff; + return -x; +} + +#ifdef SQLITE_ENABLE_8_3_NAMES +/* +** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database +** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and +** if filename in z[] has a suffix (a.k.a. "extension") that is longer than +** three characters, then shorten the suffix on z[] to be the last three +** characters of the original suffix. +** +** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always +** do the suffix shortening regardless of URI parameter. +** +** Examples: +** +** test.db-journal => test.nal +** test.db-wal => test.wal +** test.db-shm => test.shm +** test.db-mj7f3319fa => test.9fa +*/ +void sqlite3FileSuffix3(const char *zBaseFilename, char *z){ +#if SQLITE_ENABLE_8_3_NAMES<2 + if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) ) +#endif + { + int i, sz; + sz = sqlite3Strlen30(z); + for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} + if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4); + } +} +#endif + +/* +** Find (an approximate) sum of two LogEst values. This computation is +** not a simple "+" operator because LogEst is stored as a logarithmic +** value. +** +*/ +LogEst sqlite3LogEstAdd(LogEst a, LogEst b){ + static const unsigned char x[] = { + 10, 10, /* 0,1 */ + 9, 9, /* 2,3 */ + 8, 8, /* 4,5 */ + 7, 7, 7, /* 6,7,8 */ + 6, 6, 6, /* 9,10,11 */ + 5, 5, 5, /* 12-14 */ + 4, 4, 4, 4, /* 15-18 */ + 3, 3, 3, 3, 3, 3, /* 19-24 */ + 2, 2, 2, 2, 2, 2, 2, /* 25-31 */ + }; + if( a>=b ){ + if( a>b+49 ) return a; + if( a>b+31 ) return a+1; + return a+x[a-b]; + }else{ + if( b>a+49 ) return b; + if( b>a+31 ) return b+1; + return b+x[b-a]; + } +} + +/* +** Convert an integer into a LogEst. In other words, compute a +** good approximatation for 10*log2(x). +*/ +LogEst sqlite3LogEst(u64 x){ + static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 }; + LogEst y = 40; + if( x<8 ){ + if( x<2 ) return 0; + while( x<8 ){ y -= 10; x <<= 1; } + }else{ + while( x>255 ){ y += 40; x >>= 4; } + while( x>15 ){ y += 10; x >>= 1; } + } + return a[x&7] + y - 10; +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Convert a double into a LogEst +** In other words, compute an approximation for 10*log2(x). +*/ +LogEst sqlite3LogEstFromDouble(double x){ + u64 a; + LogEst e; + assert( sizeof(x)==8 && sizeof(a)==8 ); + if( x<=1 ) return 0; + if( x<=2000000000 ) return sqlite3LogEst((u64)x); + memcpy(&a, &x, 8); + e = (a>>52) - 1022; + return e*10; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** Convert a LogEst into an integer. +*/ +u64 sqlite3LogEstToInt(LogEst x){ + u64 n; + if( x<10 ) return 1; + n = x%10; + x /= 10; + if( n>=5 ) n -= 2; + else if( n>=1 ) n -= 1; + if( x>=3 ) return (n+8)<<(x-3); + return (n+8)>>(3-x); +} diff --git a/components/external/SQLite-3.8.1/src/vacuum.c b/components/external/SQLite-3.8.1/src/vacuum.c new file mode 100644 index 0000000000000000000000000000000000000000..5d41d93e0dce400bfc3e5bf598dfc8cfadfc65b0 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vacuum.c @@ -0,0 +1,369 @@ +/* +** 2003 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the VACUUM command. +** +** Most of the code in this file may be omitted by defining the +** SQLITE_OMIT_VACUUM macro. +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" + +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) +/* +** Finalize a prepared statement. If there was an error, store the +** text of the error message in *pzErrMsg. Return the result code. +*/ +static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){ + int rc; + rc = sqlite3VdbeFinalize((Vdbe*)pStmt); + if( rc ){ + sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); + } + return rc; +} + +/* +** Execute zSql on database db. Return an error code. +*/ +static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ + sqlite3_stmt *pStmt; + VVA_ONLY( int rc; ) + if( !zSql ){ + return SQLITE_NOMEM; + } + if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ + sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); + return sqlite3_errcode(db); + } + VVA_ONLY( rc = ) sqlite3_step(pStmt); + assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) ); + return vacuumFinalize(db, pStmt, pzErrMsg); +} + +/* +** Execute zSql on database db. The statement returns exactly +** one column. Execute this as SQL on the same database. +*/ +static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ + sqlite3_stmt *pStmt; + int rc; + + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0)); + if( rc!=SQLITE_OK ){ + vacuumFinalize(db, pStmt, pzErrMsg); + return rc; + } + } + + return vacuumFinalize(db, pStmt, pzErrMsg); +} + +/* +** The VACUUM command is used to clean up the database, +** collapse free space, etc. It is modelled after the VACUUM command +** in PostgreSQL. The VACUUM command works as follows: +** +** (1) Create a new transient database file +** (2) Copy all content from the database being vacuumed into +** the new transient database file +** (3) Copy content from the transient database back into the +** original database. +** +** The transient database requires temporary disk space approximately +** equal to the size of the original database. The copy operation of +** step (3) requires additional temporary disk space approximately equal +** to the size of the original database for the rollback journal. +** Hence, temporary disk space that is approximately 2x the size of the +** orginal database is required. Every page of the database is written +** approximately 3 times: Once for step (2) and twice for step (3). +** Two writes per page are required in step (3) because the original +** database content must be written into the rollback journal prior to +** overwriting the database with the vacuumed content. +** +** Only 1x temporary space and only 1x writes would be required if +** the copy of step (3) were replace by deleting the original database +** and renaming the transient database as the original. But that will +** not work if other processes are attached to the original database. +** And a power loss in between deleting the original and renaming the +** transient would cause the database file to appear to be deleted +** following reboot. +*/ +void sqlite3Vacuum(Parse *pParse){ + Vdbe *v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0); + sqlite3VdbeUsesBtree(v, 0); + } + return; +} + +/* +** This routine implements the OP_Vacuum opcode of the VDBE. +*/ +int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){ + int rc = SQLITE_OK; /* Return code from service routines */ + Btree *pMain; /* The database being vacuumed */ + Btree *pTemp; /* The temporary database we vacuum into */ + char *zSql = 0; /* SQL statements */ + int saved_flags; /* Saved value of the db->flags */ + int saved_nChange; /* Saved value of db->nChange */ + int saved_nTotalChange; /* Saved value of db->nTotalChange */ + void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */ + Db *pDb = 0; /* Database to detach at end of vacuum */ + int isMemDb; /* True if vacuuming a :memory: database */ + int nRes; /* Bytes of reserved space at the end of each page */ + int nDb; /* Number of attached databases */ + + if( !db->autoCommit ){ + sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); + return SQLITE_ERROR; + } + if( db->nVdbeActive>1 ){ + sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress"); + return SQLITE_ERROR; + } + + /* Save the current value of the database flags so that it can be + ** restored before returning. Then set the writable-schema flag, and + ** disable CHECK and foreign key constraints. */ + saved_flags = db->flags; + saved_nChange = db->nChange; + saved_nTotalChange = db->nTotalChange; + saved_xTrace = db->xTrace; + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin; + db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder); + db->xTrace = 0; + + pMain = db->aDb[0].pBt; + isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain)); + + /* Attach the temporary database as 'vacuum_db'. The synchronous pragma + ** can be set to 'off' for this file, as it is not recovered if a crash + ** occurs anyway. The integrity of the database is maintained by a + ** (possibly synchronous) transaction opened on the main database before + ** sqlite3BtreeCopyFile() is called. + ** + ** An optimisation would be to use a non-journaled pager. + ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but + ** that actually made the VACUUM run slower. Very little journalling + ** actually occurs when doing a vacuum since the vacuum_db is initially + ** empty. Only the journal header is written. Apparently it takes more + ** time to parse and run the PRAGMA to turn journalling off than it does + ** to write the journal header file. + */ + nDb = db->nDb; + if( sqlite3TempInMemory(db) ){ + zSql = "ATTACH ':memory:' AS vacuum_db;"; + }else{ + zSql = "ATTACH '' AS vacuum_db;"; + } + rc = execSql(db, pzErrMsg, zSql); + if( db->nDb>nDb ){ + pDb = &db->aDb[db->nDb-1]; + assert( strcmp(pDb->zName,"vacuum_db")==0 ); + } + if( rc!=SQLITE_OK ) goto end_of_vacuum; + pTemp = db->aDb[db->nDb-1].pBt; + + /* The call to execSql() to attach the temp database has left the file + ** locked (as there was more than one active statement when the transaction + ** to read the schema was concluded. Unlock it here so that this doesn't + ** cause problems for the call to BtreeSetPageSize() below. */ + sqlite3BtreeCommit(pTemp); + + nRes = sqlite3BtreeGetReserve(pMain); + + /* A VACUUM cannot change the pagesize of an encrypted database. */ +#ifdef SQLITE_HAS_CODEC + if( db->nextPagesize ){ + extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); + int nKey; + char *zKey; + sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); + if( nKey ) db->nextPagesize = 0; + } +#endif + + rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Begin a transaction and take an exclusive lock on the main database + ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below, + ** to ensure that we do not try to change the page-size on a WAL database. + */ + rc = execSql(db, pzErrMsg, "BEGIN;"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = sqlite3BtreeBeginTrans(pMain, 2); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Do not attempt to change the page size for a WAL database */ + if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain)) + ==PAGER_JOURNALMODE_WAL ){ + db->nextPagesize = 0; + } + + if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0) + || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0)) + || NEVER(db->mallocFailed) + ){ + rc = SQLITE_NOMEM; + goto end_of_vacuum; + } + +#ifndef SQLITE_OMIT_AUTOVACUUM + sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : + sqlite3BtreeGetAutoVacuum(pMain)); +#endif + + /* Query the schema of the main database. Create a mirror schema + ** in the temporary database. + */ + rc = execExecSql(db, pzErrMsg, + "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) " + " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" + " AND rootpage>0" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, pzErrMsg, + "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)" + " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' "); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, pzErrMsg, + "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) " + " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Loop through the tables in the main database. For each, do + ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy + ** the contents to the temporary database. + */ + rc = execExecSql(db, pzErrMsg, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM main.' || quote(name) || ';'" + "FROM main.sqlite_master " + "WHERE type = 'table' AND name!='sqlite_sequence' " + " AND rootpage>0" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Copy over the sequence table + */ + rc = execExecSql(db, pzErrMsg, + "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' " + "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' " + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, pzErrMsg, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM main.' || quote(name) || ';' " + "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + + /* Copy the triggers, views, and virtual tables from the main database + ** over to the temporary database. None of these objects has any + ** associated storage, so all we have to do is copy their entries + ** from the SQLITE_MASTER table. + */ + rc = execSql(db, pzErrMsg, + "INSERT INTO vacuum_db.sqlite_master " + " SELECT type, name, tbl_name, rootpage, sql" + " FROM main.sqlite_master" + " WHERE type='view' OR type='trigger'" + " OR (type='table' AND rootpage=0)" + ); + if( rc ) goto end_of_vacuum; + + /* At this point, there is a write transaction open on both the + ** vacuum database and the main database. Assuming no error occurs, + ** both transactions are closed by this block - the main database + ** transaction by sqlite3BtreeCopyFile() and the other by an explicit + ** call to sqlite3BtreeCommit(). + */ + { + u32 meta; + int i; + + /* This array determines which meta meta values are preserved in the + ** vacuum. Even entries are the meta value number and odd entries + ** are an increment to apply to the meta value after the vacuum. + ** The increment is used to increase the schema cookie so that other + ** connections to the same database will know to reread the schema. + */ + static const unsigned char aCopy[] = { + BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */ + BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */ + BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */ + BTREE_USER_VERSION, 0, /* Preserve the user version */ + BTREE_APPLICATION_ID, 0, /* Preserve the application id */ + }; + + assert( 1==sqlite3BtreeIsInTrans(pTemp) ); + assert( 1==sqlite3BtreeIsInTrans(pMain) ); + + /* Copy Btree meta values */ + for(i=0; iflags */ + db->flags = saved_flags; + db->nChange = saved_nChange; + db->nTotalChange = saved_nTotalChange; + db->xTrace = saved_xTrace; + sqlite3BtreeSetPageSize(pMain, -1, -1, 1); + + /* Currently there is an SQL level transaction open on the vacuum + ** database. No locks are held on any other files (since the main file + ** was committed at the btree level). So it safe to end the transaction + ** by manually setting the autoCommit flag to true and detaching the + ** vacuum database. The vacuum_db journal file is deleted when the pager + ** is closed by the DETACH. + */ + db->autoCommit = 1; + + if( pDb ){ + sqlite3BtreeClose(pDb->pBt); + pDb->pBt = 0; + pDb->pSchema = 0; + } + + /* This both clears the schemas and reduces the size of the db->aDb[] + ** array. */ + sqlite3ResetAllSchemasOfConnection(db); + + return rc; +} + +#endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */ diff --git a/components/external/SQLite-3.8.1/src/vdbe.c b/components/external/SQLite-3.8.1/src/vdbe.c new file mode 100644 index 0000000000000000000000000000000000000000..c75aadb19c0cfe14ff36d3c10414e4cb74a52bb6 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vdbe.c @@ -0,0 +1,6273 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** The code in this file implements execution method of the +** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c") +** handles housekeeping details such as creating and deleting +** VDBE instances. This file is solely interested in executing +** the VDBE program. +** +** In the external interface, an "sqlite3_stmt*" is an opaque pointer +** to a VDBE. +** +** The SQL parser generates a program which is then executed by +** the VDBE to do the work of the SQL statement. VDBE programs are +** similar in form to assembly language. The program consists of +** a linear sequence of operations. Each operation has an opcode +** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4 +** is a null-terminated string. Operand P5 is an unsigned character. +** Few opcodes use all 5 operands. +** +** Computation results are stored on a set of registers numbered beginning +** with 1 and going up to Vdbe.nMem. Each register can store +** either an integer, a null-terminated string, a floating point +** number, or the SQL "NULL" value. An implicit conversion from one +** type to the other occurs as necessary. +** +** Most of the code in this file is taken up by the sqlite3VdbeExec() +** function which does the work of interpreting a VDBE program. +** But other routines are also provided to help in building up +** a program instruction by instruction. +** +** Various scripts scan this source file in order to generate HTML +** documentation, headers files, or other derived files. The formatting +** of the code in this file is, therefore, important. See other comments +** in this file for details. If in doubt, do not deviate from existing +** commenting and indentation practices when changing or adding code. +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" + +/* +** Invoke this macro on memory cells just prior to changing the +** value of the cell. This macro verifies that shallow copies are +** not misused. +*/ +#ifdef SQLITE_DEBUG +# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M) +#else +# define memAboutToChange(P,M) +#endif + +/* +** The following global variable is incremented every time a cursor +** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test +** procedures use this information to make sure that indices are +** working correctly. This variable has no function other than to +** help verify the correct operation of the library. +*/ +#ifdef SQLITE_TEST +int sqlite3_search_count = 0; +#endif + +/* +** When this global variable is positive, it gets decremented once before +** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted +** field of the sqlite3 structure is set in order to simulate an interrupt. +** +** This facility is used for testing purposes only. It does not function +** in an ordinary build. +*/ +#ifdef SQLITE_TEST +int sqlite3_interrupt_count = 0; +#endif + +/* +** The next global variable is incremented each type the OP_Sort opcode +** is executed. The test procedures use this information to make sure that +** sorting is occurring or not occurring at appropriate times. This variable +** has no function other than to help verify the correct operation of the +** library. +*/ +#ifdef SQLITE_TEST +int sqlite3_sort_count = 0; +#endif + +/* +** The next global variable records the size of the largest MEM_Blob +** or MEM_Str that has been used by a VDBE opcode. The test procedures +** use this information to make sure that the zero-blob functionality +** is working correctly. This variable has no function other than to +** help verify the correct operation of the library. +*/ +#ifdef SQLITE_TEST +int sqlite3_max_blobsize = 0; +static void updateMaxBlobsize(Mem *p){ + if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){ + sqlite3_max_blobsize = p->n; + } +} +#endif + +/* +** The next global variable is incremented each type the OP_Found opcode +** is executed. This is used to test whether or not the foreign key +** operation implemented using OP_FkIsZero is working. This variable +** has no function other than to help verify the correct operation of the +** library. +*/ +#ifdef SQLITE_TEST +int sqlite3_found_count = 0; +#endif + +/* +** Test a register to see if it exceeds the current maximum blob size. +** If it does, record the new maximum blob size. +*/ +#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST) +# define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P) +#else +# define UPDATE_MAX_BLOBSIZE(P) +#endif + +/* +** Convert the given register into a string if it isn't one +** already. Return non-zero if a malloc() fails. +*/ +#define Stringify(P, enc) \ + if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \ + { goto no_mem; } + +/* +** An ephemeral string value (signified by the MEM_Ephem flag) contains +** a pointer to a dynamically allocated string where some other entity +** is responsible for deallocating that string. Because the register +** does not control the string, it might be deleted without the register +** knowing it. +** +** This routine converts an ephemeral string into a dynamically allocated +** string that the register itself controls. In other words, it +** converts an MEM_Ephem string into an MEM_Dyn string. +*/ +#define Deephemeralize(P) \ + if( ((P)->flags&MEM_Ephem)!=0 \ + && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} + +/* Return true if the cursor was opened using the OP_OpenSorter opcode. */ +# define isSorter(x) ((x)->pSorter!=0) + +/* +** Argument pMem points at a register that will be passed to a +** user-defined function or returned to the user as the result of a query. +** This routine sets the pMem->type variable used by the sqlite3_value_*() +** routines. +*/ +void sqlite3VdbeMemStoreType(Mem *pMem){ + int flags = pMem->flags; + if( flags & MEM_Null ){ + pMem->type = SQLITE_NULL; + } + else if( flags & MEM_Int ){ + pMem->type = SQLITE_INTEGER; + } + else if( flags & MEM_Real ){ + pMem->type = SQLITE_FLOAT; + } + else if( flags & MEM_Str ){ + pMem->type = SQLITE_TEXT; + }else{ + pMem->type = SQLITE_BLOB; + } +} + +/* +** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL +** if we run out of memory. +*/ +static VdbeCursor *allocateCursor( + Vdbe *p, /* The virtual machine */ + int iCur, /* Index of the new VdbeCursor */ + int nField, /* Number of fields in the table or index */ + int iDb, /* Database the cursor belongs to, or -1 */ + int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */ +){ + /* Find the memory cell that will be used to store the blob of memory + ** required for this VdbeCursor structure. It is convenient to use a + ** vdbe memory cell to manage the memory allocation required for a + ** VdbeCursor structure for the following reasons: + ** + ** * Sometimes cursor numbers are used for a couple of different + ** purposes in a vdbe program. The different uses might require + ** different sized allocations. Memory cells provide growable + ** allocations. + ** + ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can + ** be freed lazily via the sqlite3_release_memory() API. This + ** minimizes the number of malloc calls made by the system. + ** + ** Memory cells for cursors are allocated at the top of the address + ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for + ** cursor 1 is managed by memory cell (p->nMem-1), etc. + */ + Mem *pMem = &p->aMem[p->nMem-iCur]; + + int nByte; + VdbeCursor *pCx = 0; + nByte = + ROUND8(sizeof(VdbeCursor)) + + (isBtreeCursor?sqlite3BtreeCursorSize():0) + + 2*nField*sizeof(u32); + + assert( iCurnCursor ); + if( p->apCsr[iCur] ){ + sqlite3VdbeFreeCursor(p, p->apCsr[iCur]); + p->apCsr[iCur] = 0; + } + if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){ + p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z; + memset(pCx, 0, sizeof(VdbeCursor)); + pCx->iDb = iDb; + pCx->nField = nField; + if( nField ){ + pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))]; + } + if( isBtreeCursor ){ + pCx->pCursor = (BtCursor*) + &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)]; + sqlite3BtreeCursorZero(pCx->pCursor); + } + } + return pCx; +} + +/* +** Try to convert a value into a numeric representation if we can +** do so without loss of information. In other words, if the string +** looks like a number, convert it into a number. If it does not +** look like a number, leave it alone. +*/ +static void applyNumericAffinity(Mem *pRec){ + if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){ + double rValue; + i64 iValue; + u8 enc = pRec->enc; + if( (pRec->flags&MEM_Str)==0 ) return; + if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return; + if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){ + pRec->u.i = iValue; + pRec->flags |= MEM_Int; + }else{ + pRec->r = rValue; + pRec->flags |= MEM_Real; + } + } +} + +/* +** Processing is determine by the affinity parameter: +** +** SQLITE_AFF_INTEGER: +** SQLITE_AFF_REAL: +** SQLITE_AFF_NUMERIC: +** Try to convert pRec to an integer representation or a +** floating-point representation if an integer representation +** is not possible. Note that the integer representation is +** always preferred, even if the affinity is REAL, because +** an integer representation is more space efficient on disk. +** +** SQLITE_AFF_TEXT: +** Convert pRec to a text representation. +** +** SQLITE_AFF_NONE: +** No-op. pRec is unchanged. +*/ +static void applyAffinity( + Mem *pRec, /* The value to apply affinity to */ + char affinity, /* The affinity to be applied */ + u8 enc /* Use this text encoding */ +){ + if( affinity==SQLITE_AFF_TEXT ){ + /* Only attempt the conversion to TEXT if there is an integer or real + ** representation (blob and NULL do not get converted) but no string + ** representation. + */ + if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){ + sqlite3VdbeMemStringify(pRec, enc); + } + pRec->flags &= ~(MEM_Real|MEM_Int); + }else if( affinity!=SQLITE_AFF_NONE ){ + assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL + || affinity==SQLITE_AFF_NUMERIC ); + applyNumericAffinity(pRec); + if( pRec->flags & MEM_Real ){ + sqlite3VdbeIntegerAffinity(pRec); + } + } +} + +/* +** Try to convert the type of a function argument or a result column +** into a numeric representation. Use either INTEGER or REAL whichever +** is appropriate. But only do the conversion if it is possible without +** loss of information and return the revised type of the argument. +*/ +int sqlite3_value_numeric_type(sqlite3_value *pVal){ + Mem *pMem = (Mem*)pVal; + if( pMem->type==SQLITE_TEXT ){ + applyNumericAffinity(pMem); + sqlite3VdbeMemStoreType(pMem); + } + return pMem->type; +} + +/* +** Exported version of applyAffinity(). This one works on sqlite3_value*, +** not the internal Mem* type. +*/ +void sqlite3ValueApplyAffinity( + sqlite3_value *pVal, + u8 affinity, + u8 enc +){ + applyAffinity((Mem *)pVal, affinity, enc); +} + +#ifdef SQLITE_DEBUG +/* +** Write a nice string representation of the contents of cell pMem +** into buffer zBuf, length nBuf. +*/ +void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){ + char *zCsr = zBuf; + int f = pMem->flags; + + static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"}; + + if( f&MEM_Blob ){ + int i; + char c; + if( f & MEM_Dyn ){ + c = 'z'; + assert( (f & (MEM_Static|MEM_Ephem))==0 ); + }else if( f & MEM_Static ){ + c = 't'; + assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); + }else if( f & MEM_Ephem ){ + c = 'e'; + assert( (f & (MEM_Static|MEM_Dyn))==0 ); + }else{ + c = 's'; + } + + sqlite3_snprintf(100, zCsr, "%c", c); + zCsr += sqlite3Strlen30(zCsr); + sqlite3_snprintf(100, zCsr, "%d[", pMem->n); + zCsr += sqlite3Strlen30(zCsr); + for(i=0; i<16 && in; i++){ + sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF)); + zCsr += sqlite3Strlen30(zCsr); + } + for(i=0; i<16 && in; i++){ + char z = pMem->z[i]; + if( z<32 || z>126 ) *zCsr++ = '.'; + else *zCsr++ = z; + } + + sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]); + zCsr += sqlite3Strlen30(zCsr); + if( f & MEM_Zero ){ + sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero); + zCsr += sqlite3Strlen30(zCsr); + } + *zCsr = '\0'; + }else if( f & MEM_Str ){ + int j, k; + zBuf[0] = ' '; + if( f & MEM_Dyn ){ + zBuf[1] = 'z'; + assert( (f & (MEM_Static|MEM_Ephem))==0 ); + }else if( f & MEM_Static ){ + zBuf[1] = 't'; + assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); + }else if( f & MEM_Ephem ){ + zBuf[1] = 'e'; + assert( (f & (MEM_Static|MEM_Dyn))==0 ); + }else{ + zBuf[1] = 's'; + } + k = 2; + sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n); + k += sqlite3Strlen30(&zBuf[k]); + zBuf[k++] = '['; + for(j=0; j<15 && jn; j++){ + u8 c = pMem->z[j]; + if( c>=0x20 && c<0x7f ){ + zBuf[k++] = c; + }else{ + zBuf[k++] = '.'; + } + } + zBuf[k++] = ']'; + sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]); + k += sqlite3Strlen30(&zBuf[k]); + zBuf[k++] = 0; + } +} +#endif + +#ifdef SQLITE_DEBUG +/* +** Print the value of a register for tracing purposes: +*/ +static void memTracePrint(FILE *out, Mem *p){ + if( p->flags & MEM_Invalid ){ + fprintf(out, " undefined"); + }else if( p->flags & MEM_Null ){ + fprintf(out, " NULL"); + }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ + fprintf(out, " si:%lld", p->u.i); + }else if( p->flags & MEM_Int ){ + fprintf(out, " i:%lld", p->u.i); +#ifndef SQLITE_OMIT_FLOATING_POINT + }else if( p->flags & MEM_Real ){ + fprintf(out, " r:%g", p->r); +#endif + }else if( p->flags & MEM_RowSet ){ + fprintf(out, " (rowset)"); + }else{ + char zBuf[200]; + sqlite3VdbeMemPrettyPrint(p, zBuf); + fprintf(out, " "); + fprintf(out, "%s", zBuf); + } +} +static void registerTrace(FILE *out, int iReg, Mem *p){ + fprintf(out, "REG[%d] = ", iReg); + memTracePrint(out, p); + fprintf(out, "\n"); +} +#endif + +#ifdef SQLITE_DEBUG +# define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M) +#else +# define REGISTER_TRACE(R,M) +#endif + + +#ifdef VDBE_PROFILE + +/* +** hwtime.h contains inline assembler code for implementing +** high-performance timing routines. +*/ +#include "hwtime.h" + +#endif + +/* +** The CHECK_FOR_INTERRUPT macro defined here looks to see if the +** sqlite3_interrupt() routine has been called. If it has been, then +** processing of the VDBE program is interrupted. +** +** This macro added to every instruction that does a jump in order to +** implement a loop. This test used to be on every single instruction, +** but that meant we more testing than we needed. By only testing the +** flag on jump instructions, we get a (small) speed improvement. +*/ +#define CHECK_FOR_INTERRUPT \ + if( db->u1.isInterrupted ) goto abort_due_to_interrupt; + + +#ifndef NDEBUG +/* +** This function is only called from within an assert() expression. It +** checks that the sqlite3.nTransaction variable is correctly set to +** the number of non-transaction savepoints currently in the +** linked list starting at sqlite3.pSavepoint. +** +** Usage: +** +** assert( checkSavepointCount(db) ); +*/ +static int checkSavepointCount(sqlite3 *db){ + int n = 0; + Savepoint *p; + for(p=db->pSavepoint; p; p=p->pNext) n++; + assert( n==(db->nSavepoint + db->isTransactionSavepoint) ); + return 1; +} +#endif + + +/* +** Execute as much of a VDBE program as we can then return. +** +** sqlite3VdbeMakeReady() must be called before this routine in order to +** close the program with a final OP_Halt and to set up the callbacks +** and the error message pointer. +** +** Whenever a row or result data is available, this routine will either +** invoke the result callback (if there is one) or return with +** SQLITE_ROW. +** +** If an attempt is made to open a locked database, then this routine +** will either invoke the busy callback (if there is one) or it will +** return SQLITE_BUSY. +** +** If an error occurs, an error message is written to memory obtained +** from sqlite3_malloc() and p->zErrMsg is made to point to that memory. +** The error code is stored in p->rc and this routine returns SQLITE_ERROR. +** +** If the callback ever returns non-zero, then the program exits +** immediately. There will be no error message but the p->rc field is +** set to SQLITE_ABORT and this routine will return SQLITE_ERROR. +** +** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this +** routine to return SQLITE_ERROR. +** +** Other fatal errors return SQLITE_ERROR. +** +** After this routine has finished, sqlite3VdbeFinalize() should be +** used to clean up the mess that was left behind. +*/ +int sqlite3VdbeExec( + Vdbe *p /* The VDBE */ +){ + int pc=0; /* The program counter */ + Op *aOp = p->aOp; /* Copy of p->aOp */ + Op *pOp; /* Current operation */ + int rc = SQLITE_OK; /* Value to return */ + sqlite3 *db = p->db; /* The database */ + u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */ + u8 encoding = ENC(db); /* The database encoding */ + int iCompare = 0; /* Result of last OP_Compare operation */ + unsigned nVmStep = 0; /* Number of virtual machine steps */ +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */ +#endif + Mem *aMem = p->aMem; /* Copy of p->aMem */ + Mem *pIn1 = 0; /* 1st input operand */ + Mem *pIn2 = 0; /* 2nd input operand */ + Mem *pIn3 = 0; /* 3rd input operand */ + Mem *pOut = 0; /* Output operand */ + int *aPermute = 0; /* Permutation of columns for OP_Compare */ + i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */ +#ifdef VDBE_PROFILE + u64 start; /* CPU clock count at start of opcode */ + int origPc; /* Program counter at start of opcode */ +#endif + /*** INSERT STACK UNION HERE ***/ + + assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ + sqlite3VdbeEnter(p); + if( p->rc==SQLITE_NOMEM ){ + /* This happens if a malloc() inside a call to sqlite3_column_text() or + ** sqlite3_column_text16() failed. */ + goto no_mem; + } + assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY ); + assert( p->bIsReader || p->readOnly!=0 ); + p->rc = SQLITE_OK; + p->iCurrentTime = 0; + assert( p->explain==0 ); + p->pResultSet = 0; + db->busyHandler.nBusy = 0; + CHECK_FOR_INTERRUPT; + sqlite3VdbeIOTraceSql(p); +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + if( db->xProgress ){ + assert( 0 < db->nProgressOps ); + nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP]; + if( nProgressLimit==0 ){ + nProgressLimit = db->nProgressOps; + }else{ + nProgressLimit %= (unsigned)db->nProgressOps; + } + } +#endif +#ifdef SQLITE_DEBUG + sqlite3BeginBenignMalloc(); + if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){ + int i; + printf("VDBE Program Listing:\n"); + sqlite3VdbePrintSql(p); + for(i=0; inOp; i++){ + sqlite3VdbePrintOp(stdout, i, &aOp[i]); + } + } + sqlite3EndBenignMalloc(); +#endif + for(pc=p->pc; rc==SQLITE_OK; pc++){ + assert( pc>=0 && pcnOp ); + if( db->mallocFailed ) goto no_mem; +#ifdef VDBE_PROFILE + origPc = pc; + start = sqlite3Hwtime(); +#endif + nVmStep++; + pOp = &aOp[pc]; + + /* Only allow tracing if SQLITE_DEBUG is defined. + */ +#ifdef SQLITE_DEBUG + if( p->trace ){ + if( pc==0 ){ + printf("VDBE Execution Trace:\n"); + sqlite3VdbePrintSql(p); + } + sqlite3VdbePrintOp(p->trace, pc, pOp); + } +#endif + + + /* Check to see if we need to simulate an interrupt. This only happens + ** if we have a special test build. + */ +#ifdef SQLITE_TEST + if( sqlite3_interrupt_count>0 ){ + sqlite3_interrupt_count--; + if( sqlite3_interrupt_count==0 ){ + sqlite3_interrupt(db); + } + } +#endif + + /* On any opcode with the "out2-prerelease" tag, free any + ** external allocations out of mem[p2] and set mem[p2] to be + ** an undefined integer. Opcodes will either fill in the integer + ** value or convert mem[p2] to a different type. + */ + assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] ); + if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){ + assert( pOp->p2>0 ); + assert( pOp->p2<=(p->nMem-p->nCursor) ); + pOut = &aMem[pOp->p2]; + memAboutToChange(p, pOut); + VdbeMemRelease(pOut); + pOut->flags = MEM_Int; + } + + /* Sanity checking on other operands */ +#ifdef SQLITE_DEBUG + if( (pOp->opflags & OPFLG_IN1)!=0 ){ + assert( pOp->p1>0 ); + assert( pOp->p1<=(p->nMem-p->nCursor) ); + assert( memIsValid(&aMem[pOp->p1]) ); + REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]); + } + if( (pOp->opflags & OPFLG_IN2)!=0 ){ + assert( pOp->p2>0 ); + assert( pOp->p2<=(p->nMem-p->nCursor) ); + assert( memIsValid(&aMem[pOp->p2]) ); + REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]); + } + if( (pOp->opflags & OPFLG_IN3)!=0 ){ + assert( pOp->p3>0 ); + assert( pOp->p3<=(p->nMem-p->nCursor) ); + assert( memIsValid(&aMem[pOp->p3]) ); + REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]); + } + if( (pOp->opflags & OPFLG_OUT2)!=0 ){ + assert( pOp->p2>0 ); + assert( pOp->p2<=(p->nMem-p->nCursor) ); + memAboutToChange(p, &aMem[pOp->p2]); + } + if( (pOp->opflags & OPFLG_OUT3)!=0 ){ + assert( pOp->p3>0 ); + assert( pOp->p3<=(p->nMem-p->nCursor) ); + memAboutToChange(p, &aMem[pOp->p3]); + } +#endif + + switch( pOp->opcode ){ + +/***************************************************************************** +** What follows is a massive switch statement where each case implements a +** separate instruction in the virtual machine. If we follow the usual +** indentation conventions, each case should be indented by 6 spaces. But +** that is a lot of wasted space on the left margin. So the code within +** the switch statement will break with convention and be flush-left. Another +** big comment (similar to this one) will mark the point in the code where +** we transition back to normal indentation. +** +** The formatting of each case is important. The makefile for SQLite +** generates two C files "opcodes.h" and "opcodes.c" by scanning this +** file looking for lines that begin with "case OP_". The opcodes.h files +** will be filled with #defines that give unique integer values to each +** opcode and the opcodes.c file is filled with an array of strings where +** each string is the symbolic name for the corresponding opcode. If the +** case statement is followed by a comment of the form "/# same as ... #/" +** that comment is used to determine the particular value of the opcode. +** +** Other keywords in the comment that follows each case are used to +** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[]. +** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See +** the mkopcodeh.awk script for additional information. +** +** Documentation about VDBE opcodes is generated by scanning this file +** for lines of that contain "Opcode:". That line and all subsequent +** comment lines are used in the generation of the opcode.html documentation +** file. +** +** SUMMARY: +** +** Formatting is important to scripts that scan this file. +** Do not deviate from the formatting style currently in use. +** +*****************************************************************************/ + +/* Opcode: Goto * P2 * * * +** +** An unconditional jump to address P2. +** The next instruction executed will be +** the one at index P2 from the beginning of +** the program. +*/ +case OP_Goto: { /* jump */ + pc = pOp->p2 - 1; + + /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev, + ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon + ** completion. Check to see if sqlite3_interrupt() has been called + ** or if the progress callback needs to be invoked. + ** + ** This code uses unstructured "goto" statements and does not look clean. + ** But that is not due to sloppy coding habits. The code is written this + ** way for performance, to avoid having to run the interrupt and progress + ** checks on every opcode. This helps sqlite3_step() to run about 1.5% + ** faster according to "valgrind --tool=cachegrind" */ +check_for_interrupt: + CHECK_FOR_INTERRUPT; +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + /* Call the progress callback if it is configured and the required number + ** of VDBE ops have been executed (either since this invocation of + ** sqlite3VdbeExec() or since last time the progress callback was called). + ** If the progress callback returns non-zero, exit the virtual machine with + ** a return code SQLITE_ABORT. + */ + if( db->xProgress!=0 && nVmStep>=nProgressLimit ){ + int prc; + prc = db->xProgress(db->pProgressArg); + if( prc!=0 ){ + rc = SQLITE_INTERRUPT; + goto vdbe_error_halt; + } + if( db->xProgress!=0 ){ + nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps); + } + } +#endif + + break; +} + +/* Opcode: Gosub P1 P2 * * * +** +** Write the current address onto register P1 +** and then jump to address P2. +*/ +case OP_Gosub: { /* jump */ + assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) ); + pIn1 = &aMem[pOp->p1]; + assert( (pIn1->flags & MEM_Dyn)==0 ); + memAboutToChange(p, pIn1); + pIn1->flags = MEM_Int; + pIn1->u.i = pc; + REGISTER_TRACE(pOp->p1, pIn1); + pc = pOp->p2 - 1; + break; +} + +/* Opcode: Return P1 * * * * +** +** Jump to the next instruction after the address in register P1. +*/ +case OP_Return: { /* in1 */ + pIn1 = &aMem[pOp->p1]; + assert( pIn1->flags & MEM_Int ); + pc = (int)pIn1->u.i; + break; +} + +/* Opcode: Yield P1 * * * * +** +** Swap the program counter with the value in register P1. +*/ +case OP_Yield: { /* in1 */ + int pcDest; + pIn1 = &aMem[pOp->p1]; + assert( (pIn1->flags & MEM_Dyn)==0 ); + pIn1->flags = MEM_Int; + pcDest = (int)pIn1->u.i; + pIn1->u.i = pc; + REGISTER_TRACE(pOp->p1, pIn1); + pc = pcDest; + break; +} + +/* Opcode: HaltIfNull P1 P2 P3 P4 * +** +** Check the value in register P3. If it is NULL then Halt using +** parameter P1, P2, and P4 as if this were a Halt instruction. If the +** value in register P3 is not NULL, then this routine is a no-op. +*/ +case OP_HaltIfNull: { /* in3 */ + pIn3 = &aMem[pOp->p3]; + if( (pIn3->flags & MEM_Null)==0 ) break; + /* Fall through into OP_Halt */ +} + +/* Opcode: Halt P1 P2 * P4 * +** +** Exit immediately. All open cursors, etc are closed +** automatically. +** +** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(), +** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0). +** For errors, it can be some other value. If P1!=0 then P2 will determine +** whether or not to rollback the current transaction. Do not rollback +** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort, +** then back out all changes that have occurred during this execution of the +** VDBE, but do not rollback the transaction. +** +** If P4 is not null then it is an error message string. +** +** There is an implied "Halt 0 0 0" instruction inserted at the very end of +** every program. So a jump past the last instruction of the program +** is the same as executing Halt. +*/ +case OP_Halt: { + if( pOp->p1==SQLITE_OK && p->pFrame ){ + /* Halt the sub-program. Return control to the parent frame. */ + VdbeFrame *pFrame = p->pFrame; + p->pFrame = pFrame->pParent; + p->nFrame--; + sqlite3VdbeSetChanges(db, p->nChange); + pc = sqlite3VdbeFrameRestore(pFrame); + lastRowid = db->lastRowid; + if( pOp->p2==OE_Ignore ){ + /* Instruction pc is the OP_Program that invoked the sub-program + ** currently being halted. If the p2 instruction of this OP_Halt + ** instruction is set to OE_Ignore, then the sub-program is throwing + ** an IGNORE exception. In this case jump to the address specified + ** as the p2 of the calling OP_Program. */ + pc = p->aOp[pc].p2-1; + } + aOp = p->aOp; + aMem = p->aMem; + break; + } + + p->rc = pOp->p1; + p->errorAction = (u8)pOp->p2; + p->pc = pc; + if( pOp->p4.z ){ + assert( p->rc!=SQLITE_OK ); + sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z); + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z); + }else if( p->rc ){ + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql); + } + rc = sqlite3VdbeHalt(p); + assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); + if( rc==SQLITE_BUSY ){ + p->rc = rc = SQLITE_BUSY; + }else{ + assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ); + assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 ); + rc = p->rc ? SQLITE_ERROR : SQLITE_DONE; + } + goto vdbe_return; +} + +/* Opcode: Integer P1 P2 * * * +** +** The 32-bit integer value P1 is written into register P2. +*/ +case OP_Integer: { /* out2-prerelease */ + pOut->u.i = pOp->p1; + break; +} + +/* Opcode: Int64 * P2 * P4 * +** +** P4 is a pointer to a 64-bit integer value. +** Write that value into register P2. +*/ +case OP_Int64: { /* out2-prerelease */ + assert( pOp->p4.pI64!=0 ); + pOut->u.i = *pOp->p4.pI64; + break; +} + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* Opcode: Real * P2 * P4 * +** +** P4 is a pointer to a 64-bit floating point value. +** Write that value into register P2. +*/ +case OP_Real: { /* same as TK_FLOAT, out2-prerelease */ + pOut->flags = MEM_Real; + assert( !sqlite3IsNaN(*pOp->p4.pReal) ); + pOut->r = *pOp->p4.pReal; + break; +} +#endif + +/* Opcode: String8 * P2 * P4 * +** +** P4 points to a nul terminated UTF-8 string. This opcode is transformed +** into an OP_String before it is executed for the first time. +*/ +case OP_String8: { /* same as TK_STRING, out2-prerelease */ + assert( pOp->p4.z!=0 ); + pOp->opcode = OP_String; + pOp->p1 = sqlite3Strlen30(pOp->p4.z); + +#ifndef SQLITE_OMIT_UTF16 + if( encoding!=SQLITE_UTF8 ){ + rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); + if( rc==SQLITE_TOOBIG ) goto too_big; + if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; + assert( pOut->zMalloc==pOut->z ); + assert( pOut->flags & MEM_Dyn ); + pOut->zMalloc = 0; + pOut->flags |= MEM_Static; + pOut->flags &= ~MEM_Dyn; + if( pOp->p4type==P4_DYNAMIC ){ + sqlite3DbFree(db, pOp->p4.z); + } + pOp->p4type = P4_DYNAMIC; + pOp->p4.z = pOut->z; + pOp->p1 = pOut->n; + } +#endif + if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + /* Fall through to the next case, OP_String */ +} + +/* Opcode: String P1 P2 * P4 * +** +** The string value P4 of length P1 (bytes) is stored in register P2. +*/ +case OP_String: { /* out2-prerelease */ + assert( pOp->p4.z!=0 ); + pOut->flags = MEM_Str|MEM_Static|MEM_Term; + pOut->z = pOp->p4.z; + pOut->n = pOp->p1; + pOut->enc = encoding; + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Null P1 P2 P3 * * +** +** Write a NULL into registers P2. If P3 greater than P2, then also write +** NULL into register P3 and every register in between P2 and P3. If P3 +** is less than P2 (typically P3 is zero) then only register P2 is +** set to NULL. +** +** If the P1 value is non-zero, then also set the MEM_Cleared flag so that +** NULL values will not compare equal even if SQLITE_NULLEQ is set on +** OP_Ne or OP_Eq. +*/ +case OP_Null: { /* out2-prerelease */ + int cnt; + u16 nullFlag; + cnt = pOp->p3-pOp->p2; + assert( pOp->p3<=(p->nMem-p->nCursor) ); + pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null; + while( cnt>0 ){ + pOut++; + memAboutToChange(p, pOut); + VdbeMemRelease(pOut); + pOut->flags = nullFlag; + cnt--; + } + break; +} + + +/* Opcode: Blob P1 P2 * P4 +** +** P4 points to a blob of data P1 bytes long. Store this +** blob in register P2. +*/ +case OP_Blob: { /* out2-prerelease */ + assert( pOp->p1 <= SQLITE_MAX_LENGTH ); + sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); + pOut->enc = encoding; + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Variable P1 P2 * P4 * +** +** Transfer the values of bound parameter P1 into register P2 +** +** If the parameter is named, then its name appears in P4 and P3==1. +** The P4 value is used by sqlite3_bind_parameter_name(). +*/ +case OP_Variable: { /* out2-prerelease */ + Mem *pVar; /* Value being transferred */ + + assert( pOp->p1>0 && pOp->p1<=p->nVar ); + assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] ); + pVar = &p->aVar[pOp->p1 - 1]; + if( sqlite3VdbeMemTooBig(pVar) ){ + goto too_big; + } + sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Move P1 P2 P3 * * +** +** Move the values in register P1..P1+P3 over into +** registers P2..P2+P3. Registers P1..P1+P3 are +** left holding a NULL. It is an error for register ranges +** P1..P1+P3 and P2..P2+P3 to overlap. +*/ +case OP_Move: { + char *zMalloc; /* Holding variable for allocated memory */ + int n; /* Number of registers left to copy */ + int p1; /* Register to copy from */ + int p2; /* Register to copy to */ + + n = pOp->p3 + 1; + p1 = pOp->p1; + p2 = pOp->p2; + assert( n>0 && p1>0 && p2>0 ); + assert( p1+n<=p2 || p2+n<=p1 ); + + pIn1 = &aMem[p1]; + pOut = &aMem[p2]; + while( n-- ){ + assert( pOut<=&aMem[(p->nMem-p->nCursor)] ); + assert( pIn1<=&aMem[(p->nMem-p->nCursor)] ); + assert( memIsValid(pIn1) ); + memAboutToChange(p, pOut); + zMalloc = pOut->zMalloc; + pOut->zMalloc = 0; + sqlite3VdbeMemMove(pOut, pIn1); +#ifdef SQLITE_DEBUG + if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){ + pOut->pScopyFrom += p1 - pOp->p2; + } +#endif + pIn1->zMalloc = zMalloc; + REGISTER_TRACE(p2++, pOut); + pIn1++; + pOut++; + } + break; +} + +/* Opcode: Copy P1 P2 P3 * * +** +** Make a copy of registers P1..P1+P3 into registers P2..P2+P3. +** +** This instruction makes a deep copy of the value. A duplicate +** is made of any string or blob constant. See also OP_SCopy. +*/ +case OP_Copy: { + int n; + + n = pOp->p3; + pIn1 = &aMem[pOp->p1]; + pOut = &aMem[pOp->p2]; + assert( pOut!=pIn1 ); + while( 1 ){ + sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); + Deephemeralize(pOut); +#ifdef SQLITE_DEBUG + pOut->pScopyFrom = 0; +#endif + REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut); + if( (n--)==0 ) break; + pOut++; + pIn1++; + } + break; +} + +/* Opcode: SCopy P1 P2 * * * +** +** Make a shallow copy of register P1 into register P2. +** +** This instruction makes a shallow copy of the value. If the value +** is a string or blob, then the copy is only a pointer to the +** original and hence if the original changes so will the copy. +** Worse, if the original is deallocated, the copy becomes invalid. +** Thus the program must guarantee that the original will not change +** during the lifetime of the copy. Use OP_Copy to make a complete +** copy. +*/ +case OP_SCopy: { /* in1, out2 */ + pIn1 = &aMem[pOp->p1]; + pOut = &aMem[pOp->p2]; + assert( pOut!=pIn1 ); + sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); +#ifdef SQLITE_DEBUG + if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1; +#endif + REGISTER_TRACE(pOp->p2, pOut); + break; +} + +/* Opcode: ResultRow P1 P2 * * * +** +** The registers P1 through P1+P2-1 contain a single row of +** results. This opcode causes the sqlite3_step() call to terminate +** with an SQLITE_ROW return code and it sets up the sqlite3_stmt +** structure to provide access to the top P1 values as the result +** row. +*/ +case OP_ResultRow: { + Mem *pMem; + int i; + assert( p->nResColumn==pOp->p2 ); + assert( pOp->p1>0 ); + assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 ); + + /* If this statement has violated immediate foreign key constraints, do + ** not return the number of rows modified. And do not RELEASE the statement + ** transaction. It needs to be rolled back. */ + if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){ + assert( db->flags&SQLITE_CountRows ); + assert( p->usesStmtJournal ); + break; + } + + /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then + ** DML statements invoke this opcode to return the number of rows + ** modified to the user. This is the only way that a VM that + ** opens a statement transaction may invoke this opcode. + ** + ** In case this is such a statement, close any statement transaction + ** opened by this VM before returning control to the user. This is to + ** ensure that statement-transactions are always nested, not overlapping. + ** If the open statement-transaction is not closed here, then the user + ** may step another VM that opens its own statement transaction. This + ** may lead to overlapping statement transactions. + ** + ** The statement transaction is never a top-level transaction. Hence + ** the RELEASE call below can never fail. + */ + assert( p->iStatement==0 || db->flags&SQLITE_CountRows ); + rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE); + if( NEVER(rc!=SQLITE_OK) ){ + break; + } + + /* Invalidate all ephemeral cursor row caches */ + p->cacheCtr = (p->cacheCtr + 2)|1; + + /* Make sure the results of the current row are \000 terminated + ** and have an assigned type. The results are de-ephemeralized as + ** a side effect. + */ + pMem = p->pResultSet = &aMem[pOp->p1]; + for(i=0; ip2; i++){ + assert( memIsValid(&pMem[i]) ); + Deephemeralize(&pMem[i]); + assert( (pMem[i].flags & MEM_Ephem)==0 + || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 ); + sqlite3VdbeMemNulTerminate(&pMem[i]); + sqlite3VdbeMemStoreType(&pMem[i]); + REGISTER_TRACE(pOp->p1+i, &pMem[i]); + } + if( db->mallocFailed ) goto no_mem; + + /* Return SQLITE_ROW + */ + p->pc = pc + 1; + rc = SQLITE_ROW; + goto vdbe_return; +} + +/* Opcode: Concat P1 P2 P3 * * +** +** Add the text in register P1 onto the end of the text in +** register P2 and store the result in register P3. +** If either the P1 or P2 text are NULL then store NULL in P3. +** +** P3 = P2 || P1 +** +** It is illegal for P1 and P3 to be the same register. Sometimes, +** if P3 is the same register as P2, the implementation is able +** to avoid a memcpy(). +*/ +case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ + i64 nByte; + + pIn1 = &aMem[pOp->p1]; + pIn2 = &aMem[pOp->p2]; + pOut = &aMem[pOp->p3]; + assert( pIn1!=pOut ); + if( (pIn1->flags | pIn2->flags) & MEM_Null ){ + sqlite3VdbeMemSetNull(pOut); + break; + } + if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem; + Stringify(pIn1, encoding); + Stringify(pIn2, encoding); + nByte = pIn1->n + pIn2->n; + if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + MemSetTypeFlag(pOut, MEM_Str); + if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){ + goto no_mem; + } + if( pOut!=pIn2 ){ + memcpy(pOut->z, pIn2->z, pIn2->n); + } + memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); + pOut->z[nByte] = 0; + pOut->z[nByte+1] = 0; + pOut->flags |= MEM_Term; + pOut->n = (int)nByte; + pOut->enc = encoding; + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Add P1 P2 P3 * * +** +** Add the value in register P1 to the value in register P2 +** and store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Multiply P1 P2 P3 * * +** +** +** Multiply the value in register P1 by the value in register P2 +** and store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Subtract P1 P2 P3 * * +** +** Subtract the value in register P1 from the value in register P2 +** and store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Divide P1 P2 P3 * * +** +** Divide the value in register P1 by the value in register P2 +** and store the result in register P3 (P3=P2/P1). If the value in +** register P1 is zero, then the result is NULL. If either input is +** NULL, the result is NULL. +*/ +/* Opcode: Remainder P1 P2 P3 * * +** +** Compute the remainder after integer division of the value in +** register P1 by the value in register P2 and store the result in P3. +** If the value in register P2 is zero the result is NULL. +** If either operand is NULL, the result is NULL. +*/ +case OP_Add: /* same as TK_PLUS, in1, in2, out3 */ +case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */ +case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */ +case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */ +case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ + char bIntint; /* Started out as two integer operands */ + int flags; /* Combined MEM_* flags from both inputs */ + i64 iA; /* Integer value of left operand */ + i64 iB; /* Integer value of right operand */ + double rA; /* Real value of left operand */ + double rB; /* Real value of right operand */ + + pIn1 = &aMem[pOp->p1]; + applyNumericAffinity(pIn1); + pIn2 = &aMem[pOp->p2]; + applyNumericAffinity(pIn2); + pOut = &aMem[pOp->p3]; + flags = pIn1->flags | pIn2->flags; + if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null; + if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){ + iA = pIn1->u.i; + iB = pIn2->u.i; + bIntint = 1; + switch( pOp->opcode ){ + case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break; + case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break; + case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break; + case OP_Divide: { + if( iA==0 ) goto arithmetic_result_is_null; + if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math; + iB /= iA; + break; + } + default: { + if( iA==0 ) goto arithmetic_result_is_null; + if( iA==-1 ) iA = 1; + iB %= iA; + break; + } + } + pOut->u.i = iB; + MemSetTypeFlag(pOut, MEM_Int); + }else{ + bIntint = 0; +fp_math: + rA = sqlite3VdbeRealValue(pIn1); + rB = sqlite3VdbeRealValue(pIn2); + switch( pOp->opcode ){ + case OP_Add: rB += rA; break; + case OP_Subtract: rB -= rA; break; + case OP_Multiply: rB *= rA; break; + case OP_Divide: { + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + if( rA==(double)0 ) goto arithmetic_result_is_null; + rB /= rA; + break; + } + default: { + iA = (i64)rA; + iB = (i64)rB; + if( iA==0 ) goto arithmetic_result_is_null; + if( iA==-1 ) iA = 1; + rB = (double)(iB % iA); + break; + } + } +#ifdef SQLITE_OMIT_FLOATING_POINT + pOut->u.i = rB; + MemSetTypeFlag(pOut, MEM_Int); +#else + if( sqlite3IsNaN(rB) ){ + goto arithmetic_result_is_null; + } + pOut->r = rB; + MemSetTypeFlag(pOut, MEM_Real); + if( (flags & MEM_Real)==0 && !bIntint ){ + sqlite3VdbeIntegerAffinity(pOut); + } +#endif + } + break; + +arithmetic_result_is_null: + sqlite3VdbeMemSetNull(pOut); + break; +} + +/* Opcode: CollSeq P1 * * P4 +** +** P4 is a pointer to a CollSeq struct. If the next call to a user function +** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will +** be returned. This is used by the built-in min(), max() and nullif() +** functions. +** +** If P1 is not zero, then it is a register that a subsequent min() or +** max() aggregate will set to 1 if the current row is not the minimum or +** maximum. The P1 register is initialized to 0 by this instruction. +** +** The interface used by the implementation of the aforementioned functions +** to retrieve the collation sequence set by this opcode is not available +** publicly, only to user functions defined in func.c. +*/ +case OP_CollSeq: { + assert( pOp->p4type==P4_COLLSEQ ); + if( pOp->p1 ){ + sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0); + } + break; +} + +/* Opcode: Function P1 P2 P3 P4 P5 +** +** Invoke a user function (P4 is a pointer to a Function structure that +** defines the function) with P5 arguments taken from register P2 and +** successors. The result of the function is stored in register P3. +** Register P3 must not be one of the function inputs. +** +** P1 is a 32-bit bitmask indicating whether or not each argument to the +** function was determined to be constant at compile time. If the first +** argument was constant then bit 0 of P1 is set. This is used to determine +** whether meta data associated with a user function argument using the +** sqlite3_set_auxdata() API may be safely retained until the next +** invocation of this opcode. +** +** See also: AggStep and AggFinal +*/ +case OP_Function: { + int i; + Mem *pArg; + sqlite3_context ctx; + sqlite3_value **apVal; + int n; + + n = pOp->p5; + apVal = p->apArg; + assert( apVal || n==0 ); + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + pOut = &aMem[pOp->p3]; + memAboutToChange(p, pOut); + + assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) ); + assert( pOp->p3p2 || pOp->p3>=pOp->p2+n ); + pArg = &aMem[pOp->p2]; + for(i=0; ip2+i, pArg); + } + + assert( pOp->p4type==P4_FUNCDEF ); + ctx.pFunc = pOp->p4.pFunc; + ctx.s.flags = MEM_Null; + ctx.s.db = db; + ctx.s.xDel = 0; + ctx.s.zMalloc = 0; + ctx.iOp = pc; + ctx.pVdbe = p; + + /* The output cell may already have a buffer allocated. Move + ** the pointer to ctx.s so in case the user-function can use + ** the already allocated buffer instead of allocating a new one. + */ + sqlite3VdbeMemMove(&ctx.s, pOut); + MemSetTypeFlag(&ctx.s, MEM_Null); + + ctx.fErrorOrAux = 0; + if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ + assert( pOp>aOp ); + assert( pOp[-1].p4type==P4_COLLSEQ ); + assert( pOp[-1].opcode==OP_CollSeq ); + ctx.pColl = pOp[-1].p4.pColl; + } + db->lastRowid = lastRowid; + (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */ + lastRowid = db->lastRowid; + + if( db->mallocFailed ){ + /* Even though a malloc() has failed, the implementation of the + ** user function may have called an sqlite3_result_XXX() function + ** to return a value. The following call releases any resources + ** associated with such a value. + */ + sqlite3VdbeMemRelease(&ctx.s); + goto no_mem; + } + + /* If the function returned an error, throw an exception */ + if( ctx.fErrorOrAux ){ + if( ctx.isError ){ + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s)); + rc = ctx.isError; + } + sqlite3VdbeDeleteAuxData(p, pc, pOp->p1); + } + + /* Copy the result of the function into register P3 */ + sqlite3VdbeChangeEncoding(&ctx.s, encoding); + sqlite3VdbeMemMove(pOut, &ctx.s); + if( sqlite3VdbeMemTooBig(pOut) ){ + goto too_big; + } + +#if 0 + /* The app-defined function has done something that as caused this + ** statement to expire. (Perhaps the function called sqlite3_exec() + ** with a CREATE TABLE statement.) + */ + if( p->expired ) rc = SQLITE_ABORT; +#endif + + REGISTER_TRACE(pOp->p3, pOut); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: BitAnd P1 P2 P3 * * +** +** Take the bit-wise AND of the values in register P1 and P2 and +** store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: BitOr P1 P2 P3 * * +** +** Take the bit-wise OR of the values in register P1 and P2 and +** store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: ShiftLeft P1 P2 P3 * * +** +** Shift the integer value in register P2 to the left by the +** number of bits specified by the integer in register P1. +** Store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: ShiftRight P1 P2 P3 * * +** +** Shift the integer value in register P2 to the right by the +** number of bits specified by the integer in register P1. +** Store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */ +case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */ +case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */ +case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ + i64 iA; + u64 uA; + i64 iB; + u8 op; + + pIn1 = &aMem[pOp->p1]; + pIn2 = &aMem[pOp->p2]; + pOut = &aMem[pOp->p3]; + if( (pIn1->flags | pIn2->flags) & MEM_Null ){ + sqlite3VdbeMemSetNull(pOut); + break; + } + iA = sqlite3VdbeIntValue(pIn2); + iB = sqlite3VdbeIntValue(pIn1); + op = pOp->opcode; + if( op==OP_BitAnd ){ + iA &= iB; + }else if( op==OP_BitOr ){ + iA |= iB; + }else if( iB!=0 ){ + assert( op==OP_ShiftRight || op==OP_ShiftLeft ); + + /* If shifting by a negative amount, shift in the other direction */ + if( iB<0 ){ + assert( OP_ShiftRight==OP_ShiftLeft+1 ); + op = 2*OP_ShiftLeft + 1 - op; + iB = iB>(-64) ? -iB : 64; + } + + if( iB>=64 ){ + iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1; + }else{ + memcpy(&uA, &iA, sizeof(uA)); + if( op==OP_ShiftLeft ){ + uA <<= iB; + }else{ + uA >>= iB; + /* Sign-extend on a right shift of a negative number */ + if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB); + } + memcpy(&iA, &uA, sizeof(iA)); + } + } + pOut->u.i = iA; + MemSetTypeFlag(pOut, MEM_Int); + break; +} + +/* Opcode: AddImm P1 P2 * * * +** +** Add the constant P2 to the value in register P1. +** The result is always an integer. +** +** To force any register to be an integer, just add 0. +*/ +case OP_AddImm: { /* in1 */ + pIn1 = &aMem[pOp->p1]; + memAboutToChange(p, pIn1); + sqlite3VdbeMemIntegerify(pIn1); + pIn1->u.i += pOp->p2; + break; +} + +/* Opcode: MustBeInt P1 P2 * * * +** +** Force the value in register P1 to be an integer. If the value +** in P1 is not an integer and cannot be converted into an integer +** without data loss, then jump immediately to P2, or if P2==0 +** raise an SQLITE_MISMATCH exception. +*/ +case OP_MustBeInt: { /* jump, in1 */ + pIn1 = &aMem[pOp->p1]; + applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); + if( (pIn1->flags & MEM_Int)==0 ){ + if( pOp->p2==0 ){ + rc = SQLITE_MISMATCH; + goto abort_due_to_error; + }else{ + pc = pOp->p2 - 1; + } + }else{ + MemSetTypeFlag(pIn1, MEM_Int); + } + break; +} + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* Opcode: RealAffinity P1 * * * * +** +** If register P1 holds an integer convert it to a real value. +** +** This opcode is used when extracting information from a column that +** has REAL affinity. Such column values may still be stored as +** integers, for space efficiency, but after extraction we want them +** to have only a real value. +*/ +case OP_RealAffinity: { /* in1 */ + pIn1 = &aMem[pOp->p1]; + if( pIn1->flags & MEM_Int ){ + sqlite3VdbeMemRealify(pIn1); + } + break; +} +#endif + +#ifndef SQLITE_OMIT_CAST +/* Opcode: ToText P1 * * * * +** +** Force the value in register P1 to be text. +** If the value is numeric, convert it to a string using the +** equivalent of printf(). Blob values are unchanged and +** are afterwards simply interpreted as text. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToText: { /* same as TK_TO_TEXT, in1 */ + pIn1 = &aMem[pOp->p1]; + memAboutToChange(p, pIn1); + if( pIn1->flags & MEM_Null ) break; + assert( MEM_Str==(MEM_Blob>>3) ); + pIn1->flags |= (pIn1->flags&MEM_Blob)>>3; + applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding); + rc = ExpandBlob(pIn1); + assert( pIn1->flags & MEM_Str || db->mallocFailed ); + pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero); + UPDATE_MAX_BLOBSIZE(pIn1); + break; +} + +/* Opcode: ToBlob P1 * * * * +** +** Force the value in register P1 to be a BLOB. +** If the value is numeric, convert it to a string first. +** Strings are simply reinterpreted as blobs with no change +** to the underlying data. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */ + pIn1 = &aMem[pOp->p1]; + if( pIn1->flags & MEM_Null ) break; + if( (pIn1->flags & MEM_Blob)==0 ){ + applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding); + assert( pIn1->flags & MEM_Str || db->mallocFailed ); + MemSetTypeFlag(pIn1, MEM_Blob); + }else{ + pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob); + } + UPDATE_MAX_BLOBSIZE(pIn1); + break; +} + +/* Opcode: ToNumeric P1 * * * * +** +** Force the value in register P1 to be numeric (either an +** integer or a floating-point number.) +** If the value is text or blob, try to convert it to an using the +** equivalent of atoi() or atof() and store 0 if no such conversion +** is possible. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */ + pIn1 = &aMem[pOp->p1]; + sqlite3VdbeMemNumerify(pIn1); + break; +} +#endif /* SQLITE_OMIT_CAST */ + +/* Opcode: ToInt P1 * * * * +** +** Force the value in register P1 to be an integer. If +** The value is currently a real number, drop its fractional part. +** If the value is text or blob, try to convert it to an integer using the +** equivalent of atoi() and store 0 if no such conversion is possible. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToInt: { /* same as TK_TO_INT, in1 */ + pIn1 = &aMem[pOp->p1]; + if( (pIn1->flags & MEM_Null)==0 ){ + sqlite3VdbeMemIntegerify(pIn1); + } + break; +} + +#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) +/* Opcode: ToReal P1 * * * * +** +** Force the value in register P1 to be a floating point number. +** If The value is currently an integer, convert it. +** If the value is text or blob, try to convert it to an integer using the +** equivalent of atoi() and store 0.0 if no such conversion is possible. +** +** A NULL value is not changed by this routine. It remains NULL. +*/ +case OP_ToReal: { /* same as TK_TO_REAL, in1 */ + pIn1 = &aMem[pOp->p1]; + memAboutToChange(p, pIn1); + if( (pIn1->flags & MEM_Null)==0 ){ + sqlite3VdbeMemRealify(pIn1); + } + break; +} +#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */ + +/* Opcode: Lt P1 P2 P3 P4 P5 +** +** Compare the values in register P1 and P3. If reg(P3)flags */ + u16 flags3; /* Copy of initial value of pIn3->flags */ + + pIn1 = &aMem[pOp->p1]; + pIn3 = &aMem[pOp->p3]; + flags1 = pIn1->flags; + flags3 = pIn3->flags; + if( (flags1 | flags3)&MEM_Null ){ + /* One or both operands are NULL */ + if( pOp->p5 & SQLITE_NULLEQ ){ + /* If SQLITE_NULLEQ is set (which will only happen if the operator is + ** OP_Eq or OP_Ne) then take the jump or not depending on whether + ** or not both operands are null. + */ + assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne ); + assert( (flags1 & MEM_Cleared)==0 ); + if( (flags1&MEM_Null)!=0 + && (flags3&MEM_Null)!=0 + && (flags3&MEM_Cleared)==0 + ){ + res = 0; /* Results are equal */ + }else{ + res = 1; /* Results are not equal */ + } + }else{ + /* SQLITE_NULLEQ is clear and at least one operand is NULL, + ** then the result is always NULL. + ** The jump is taken if the SQLITE_JUMPIFNULL bit is set. + */ + if( pOp->p5 & SQLITE_JUMPIFNULL ){ + pc = pOp->p2-1; + }else if( pOp->p5 & SQLITE_STOREP2 ){ + pOut = &aMem[pOp->p2]; + MemSetTypeFlag(pOut, MEM_Null); + REGISTER_TRACE(pOp->p2, pOut); + } + break; + } + }else{ + /* Neither operand is NULL. Do a comparison. */ + affinity = pOp->p5 & SQLITE_AFF_MASK; + if( affinity ){ + applyAffinity(pIn1, affinity, encoding); + applyAffinity(pIn3, affinity, encoding); + if( db->mallocFailed ) goto no_mem; + } + + assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 ); + ExpandBlob(pIn1); + ExpandBlob(pIn3); + res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); + } + switch( pOp->opcode ){ + case OP_Eq: res = res==0; break; + case OP_Ne: res = res!=0; break; + case OP_Lt: res = res<0; break; + case OP_Le: res = res<=0; break; + case OP_Gt: res = res>0; break; + default: res = res>=0; break; + } + + if( pOp->p5 & SQLITE_STOREP2 ){ + pOut = &aMem[pOp->p2]; + memAboutToChange(p, pOut); + MemSetTypeFlag(pOut, MEM_Int); + pOut->u.i = res; + REGISTER_TRACE(pOp->p2, pOut); + }else if( res ){ + pc = pOp->p2-1; + } + + /* Undo any changes made by applyAffinity() to the input registers. */ + pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (flags1&MEM_TypeMask); + pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (flags3&MEM_TypeMask); + break; +} + +/* Opcode: Permutation * * * P4 * +** +** Set the permutation used by the OP_Compare operator to be the array +** of integers in P4. +** +** The permutation is only valid until the next OP_Compare that has +** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should +** occur immediately prior to the OP_Compare. +*/ +case OP_Permutation: { + assert( pOp->p4type==P4_INTARRAY ); + assert( pOp->p4.ai ); + aPermute = pOp->p4.ai; + break; +} + +/* Opcode: Compare P1 P2 P3 P4 P5 +** +** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this +** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of +** the comparison for use by the next OP_Jump instruct. +** +** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is +** determined by the most recent OP_Permutation operator. If the +** OPFLAG_PERMUTE bit is clear, then register are compared in sequential +** order. +** +** P4 is a KeyInfo structure that defines collating sequences and sort +** orders for the comparison. The permutation applies to registers +** only. The KeyInfo elements are used sequentially. +** +** The comparison is a sort comparison, so NULLs compare equal, +** NULLs are less than numbers, numbers are less than strings, +** and strings are less than blobs. +*/ +case OP_Compare: { + int n; + int i; + int p1; + int p2; + const KeyInfo *pKeyInfo; + int idx; + CollSeq *pColl; /* Collating sequence to use on this term */ + int bRev; /* True for DESCENDING sort order */ + + if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0; + n = pOp->p3; + pKeyInfo = pOp->p4.pKeyInfo; + assert( n>0 ); + assert( pKeyInfo!=0 ); + p1 = pOp->p1; + p2 = pOp->p2; +#if SQLITE_DEBUG + if( aPermute ){ + int k, mx = 0; + for(k=0; kmx ) mx = aPermute[k]; + assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 ); + assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 ); + }else{ + assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 ); + assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 ); + } +#endif /* SQLITE_DEBUG */ + for(i=0; inField ); + pColl = pKeyInfo->aColl[i]; + bRev = pKeyInfo->aSortOrder[i]; + iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl); + if( iCompare ){ + if( bRev ) iCompare = -iCompare; + break; + } + } + aPermute = 0; + break; +} + +/* Opcode: Jump P1 P2 P3 * * +** +** Jump to the instruction at address P1, P2, or P3 depending on whether +** in the most recent OP_Compare instruction the P1 vector was less than +** equal to, or greater than the P2 vector, respectively. +*/ +case OP_Jump: { /* jump */ + if( iCompare<0 ){ + pc = pOp->p1 - 1; + }else if( iCompare==0 ){ + pc = pOp->p2 - 1; + }else{ + pc = pOp->p3 - 1; + } + break; +} + +/* Opcode: And P1 P2 P3 * * +** +** Take the logical AND of the values in registers P1 and P2 and +** write the result into register P3. +** +** If either P1 or P2 is 0 (false) then the result is 0 even if +** the other input is NULL. A NULL and true or two NULLs give +** a NULL output. +*/ +/* Opcode: Or P1 P2 P3 * * +** +** Take the logical OR of the values in register P1 and P2 and +** store the answer in register P3. +** +** If either P1 or P2 is nonzero (true) then the result is 1 (true) +** even if the other input is NULL. A NULL and false or two NULLs +** give a NULL output. +*/ +case OP_And: /* same as TK_AND, in1, in2, out3 */ +case OP_Or: { /* same as TK_OR, in1, in2, out3 */ + int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ + int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ + + pIn1 = &aMem[pOp->p1]; + if( pIn1->flags & MEM_Null ){ + v1 = 2; + }else{ + v1 = sqlite3VdbeIntValue(pIn1)!=0; + } + pIn2 = &aMem[pOp->p2]; + if( pIn2->flags & MEM_Null ){ + v2 = 2; + }else{ + v2 = sqlite3VdbeIntValue(pIn2)!=0; + } + if( pOp->opcode==OP_And ){ + static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 }; + v1 = and_logic[v1*3+v2]; + }else{ + static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 }; + v1 = or_logic[v1*3+v2]; + } + pOut = &aMem[pOp->p3]; + if( v1==2 ){ + MemSetTypeFlag(pOut, MEM_Null); + }else{ + pOut->u.i = v1; + MemSetTypeFlag(pOut, MEM_Int); + } + break; +} + +/* Opcode: Not P1 P2 * * * +** +** Interpret the value in register P1 as a boolean value. Store the +** boolean complement in register P2. If the value in register P1 is +** NULL, then a NULL is stored in P2. +*/ +case OP_Not: { /* same as TK_NOT, in1, out2 */ + pIn1 = &aMem[pOp->p1]; + pOut = &aMem[pOp->p2]; + if( pIn1->flags & MEM_Null ){ + sqlite3VdbeMemSetNull(pOut); + }else{ + sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1)); + } + break; +} + +/* Opcode: BitNot P1 P2 * * * +** +** Interpret the content of register P1 as an integer. Store the +** ones-complement of the P1 value into register P2. If P1 holds +** a NULL then store a NULL in P2. +*/ +case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ + pIn1 = &aMem[pOp->p1]; + pOut = &aMem[pOp->p2]; + if( pIn1->flags & MEM_Null ){ + sqlite3VdbeMemSetNull(pOut); + }else{ + sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1)); + } + break; +} + +/* Opcode: Once P1 P2 * * * +** +** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise, +** set the flag and fall through to the next instruction. +*/ +case OP_Once: { /* jump */ + assert( pOp->p1nOnceFlag ); + if( p->aOnceFlag[pOp->p1] ){ + pc = pOp->p2-1; + }else{ + p->aOnceFlag[pOp->p1] = 1; + } + break; +} + +/* Opcode: If P1 P2 P3 * * +** +** Jump to P2 if the value in register P1 is true. The value +** is considered true if it is numeric and non-zero. If the value +** in P1 is NULL then take the jump if P3 is non-zero. +*/ +/* Opcode: IfNot P1 P2 P3 * * +** +** Jump to P2 if the value in register P1 is False. The value +** is considered false if it has a numeric value of zero. If the value +** in P1 is NULL then take the jump if P3 is zero. +*/ +case OP_If: /* jump, in1 */ +case OP_IfNot: { /* jump, in1 */ + int c; + pIn1 = &aMem[pOp->p1]; + if( pIn1->flags & MEM_Null ){ + c = pOp->p3; + }else{ +#ifdef SQLITE_OMIT_FLOATING_POINT + c = sqlite3VdbeIntValue(pIn1)!=0; +#else + c = sqlite3VdbeRealValue(pIn1)!=0.0; +#endif + if( pOp->opcode==OP_IfNot ) c = !c; + } + if( c ){ + pc = pOp->p2-1; + } + break; +} + +/* Opcode: IsNull P1 P2 * * * +** +** Jump to P2 if the value in register P1 is NULL. +*/ +case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */ + pIn1 = &aMem[pOp->p1]; + if( (pIn1->flags & MEM_Null)!=0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: NotNull P1 P2 * * * +** +** Jump to P2 if the value in register P1 is not NULL. +*/ +case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ + pIn1 = &aMem[pOp->p1]; + if( (pIn1->flags & MEM_Null)==0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: Column P1 P2 P3 P4 P5 +** +** Interpret the data that cursor P1 points to as a structure built using +** the MakeRecord instruction. (See the MakeRecord opcode for additional +** information about the format of the data.) Extract the P2-th column +** from this record. If there are less that (P2+1) +** values in the record, extract a NULL. +** +** The value extracted is stored in register P3. +** +** If the column contains fewer than P2 fields, then extract a NULL. Or, +** if the P4 argument is a P4_MEM use the value of the P4 argument as +** the result. +** +** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor, +** then the cache of the cursor is reset prior to extracting the column. +** The first OP_Column against a pseudo-table after the value of the content +** register has changed should have this bit set. +** +** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when +** the result is guaranteed to only be used as the argument of a length() +** or typeof() function, respectively. The loading of large blobs can be +** skipped for length() and all content loading can be skipped for typeof(). +*/ +case OP_Column: { + u32 payloadSize; /* Number of bytes in the record */ + i64 payloadSize64; /* Number of bytes in the record */ + int p1; /* P1 value of the opcode */ + int p2; /* column number to retrieve */ + VdbeCursor *pC; /* The VDBE cursor */ + char *zRec; /* Pointer to complete record-data */ + BtCursor *pCrsr; /* The BTree cursor */ + u32 *aType; /* aType[i] holds the numeric type of the i-th column */ + u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */ + int nField; /* number of fields in the record */ + int len; /* The length of the serialized data for the column */ + int i; /* Loop counter */ + char *zData; /* Part of the record being decoded */ + Mem *pDest; /* Where to write the extracted value */ + Mem sMem; /* For storing the record being decoded */ + u8 *zIdx; /* Index into header */ + u8 *zEndHdr; /* Pointer to first byte after the header */ + u32 offset; /* Offset into the data */ + u32 szField; /* Number of bytes in the content of a field */ + int szHdr; /* Size of the header size field at start of record */ + int avail; /* Number of bytes of available data */ + u32 t; /* A type code from the record header */ + Mem *pReg; /* PseudoTable input register */ + + + p1 = pOp->p1; + p2 = pOp->p2; + pC = 0; + memset(&sMem, 0, sizeof(sMem)); + assert( p1nCursor ); + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + pDest = &aMem[pOp->p3]; + memAboutToChange(p, pDest); + zRec = 0; + + /* This block sets the variable payloadSize to be the total number of + ** bytes in the record. + ** + ** zRec is set to be the complete text of the record if it is available. + ** The complete record text is always available for pseudo-tables + ** If the record is stored in a cursor, the complete record text + ** might be available in the pC->aRow cache. Or it might not be. + ** If the data is unavailable, zRec is set to NULL. + ** + ** We also compute the number of columns in the record. For cursors, + ** the number of columns is stored in the VdbeCursor.nField element. + */ + pC = p->apCsr[p1]; + assert( pC!=0 ); +#ifndef SQLITE_OMIT_VIRTUALTABLE + assert( pC->pVtabCursor==0 ); +#endif + pCrsr = pC->pCursor; + if( pCrsr!=0 ){ + /* The record is stored in a B-Tree */ + rc = sqlite3VdbeCursorMoveto(pC); + if( rc ) goto abort_due_to_error; + if( pC->nullRow ){ + payloadSize = 0; + }else if( pC->cacheStatus==p->cacheCtr ){ + payloadSize = pC->payloadSize; + zRec = (char*)pC->aRow; + }else if( pC->isIndex ){ + assert( sqlite3BtreeCursorIsValid(pCrsr) ); + VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64); + assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */ + /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the + ** payload size, so it is impossible for payloadSize64 to be + ** larger than 32 bits. */ + assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 ); + payloadSize = (u32)payloadSize64; + }else{ + assert( sqlite3BtreeCursorIsValid(pCrsr) ); + VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &payloadSize); + assert( rc==SQLITE_OK ); /* DataSize() cannot fail */ + } + }else if( ALWAYS(pC->pseudoTableReg>0) ){ + pReg = &aMem[pC->pseudoTableReg]; + if( pC->multiPseudo ){ + sqlite3VdbeMemShallowCopy(pDest, pReg+p2, MEM_Ephem); + Deephemeralize(pDest); + goto op_column_out; + } + assert( pReg->flags & MEM_Blob ); + assert( memIsValid(pReg) ); + payloadSize = pReg->n; + zRec = pReg->z; + pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr; + assert( payloadSize==0 || zRec!=0 ); + }else{ + /* Consider the row to be NULL */ + payloadSize = 0; + } + + /* If payloadSize is 0, then just store a NULL. This can happen because of + ** nullRow or because of a corrupt database. */ + if( payloadSize==0 ){ + MemSetTypeFlag(pDest, MEM_Null); + goto op_column_out; + } + assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 ); + if( payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + + nField = pC->nField; + assert( p2aType; + if( pC->cacheStatus==p->cacheCtr ){ + aOffset = pC->aOffset; + }else{ + assert(aType); + avail = 0; + pC->aOffset = aOffset = &aType[nField]; + pC->payloadSize = payloadSize; + pC->cacheStatus = p->cacheCtr; + + /* Figure out how many bytes are in the header */ + if( zRec ){ + zData = zRec; + }else{ + if( pC->isIndex ){ + zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail); + }else{ + zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail); + } + /* If KeyFetch()/DataFetch() managed to get the entire payload, + ** save the payload in the pC->aRow cache. That will save us from + ** having to make additional calls to fetch the content portion of + ** the record. + */ + assert( avail>=0 ); + if( payloadSize <= (u32)avail ){ + zRec = zData; + pC->aRow = (u8*)zData; + }else{ + pC->aRow = 0; + } + } + /* The following assert is true in all cases except when + ** the database file has been corrupted externally. + ** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */ + szHdr = getVarint32((u8*)zData, offset); + + /* Make sure a corrupt database has not given us an oversize header. + ** Do this now to avoid an oversize memory allocation. + ** + ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte + ** types use so much data space that there can only be 4096 and 32 of + ** them, respectively. So the maximum header length results from a + ** 3-byte type for each of the maximum of 32768 columns plus three + ** extra bytes for the header length itself. 32768*3 + 3 = 98307. + */ + if( offset > 98307 ){ + rc = SQLITE_CORRUPT_BKPT; + goto op_column_out; + } + + /* Compute in len the number of bytes of data we need to read in order + ** to get nField type values. offset is an upper bound on this. But + ** nField might be significantly less than the true number of columns + ** in the table, and in that case, 5*nField+3 might be smaller than offset. + ** We want to minimize len in order to limit the size of the memory + ** allocation, especially if a corrupt database file has caused offset + ** to be oversized. Offset is limited to 98307 above. But 98307 might + ** still exceed Robson memory allocation limits on some configurations. + ** On systems that cannot tolerate large memory allocations, nField*5+3 + ** will likely be much smaller since nField will likely be less than + ** 20 or so. This insures that Robson memory allocation limits are + ** not exceeded even for corrupt database files. + */ + len = nField*5 + 3; + if( len > (int)offset ) len = (int)offset; + + /* The KeyFetch() or DataFetch() above are fast and will get the entire + ** record header in most cases. But they will fail to get the complete + ** record header if the record header does not fit on a single page + ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to + ** acquire the complete header text. + */ + if( !zRec && availisIndex, &sMem); + if( rc!=SQLITE_OK ){ + goto op_column_out; + } + zData = sMem.z; + } + zEndHdr = (u8 *)&zData[len]; + zIdx = (u8 *)&zData[szHdr]; + + /* Scan the header and use it to fill in the aType[] and aOffset[] + ** arrays. aType[i] will contain the type integer for the i-th + ** column and aOffset[i] will contain the offset from the beginning + ** of the record to the start of the data for the i-th column + */ + for(i=0; i zEndHdr) || (offset > payloadSize) + || (zIdx==zEndHdr && offset!=payloadSize) ){ + rc = SQLITE_CORRUPT_BKPT; + goto op_column_out; + } + } + + /* Get the column information. If aOffset[p2] is non-zero, then + ** deserialize the value from the record. If aOffset[p2] is zero, + ** then there are not enough fields in the record to satisfy the + ** request. In this case, set the value NULL or to P4 if P4 is + ** a pointer to a Mem object. + */ + if( aOffset[p2] ){ + assert( rc==SQLITE_OK ); + if( zRec ){ + /* This is the common case where the whole row fits on a single page */ + VdbeMemRelease(pDest); + sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest); + }else{ + /* This branch happens only when the row overflows onto multiple pages */ + t = aType[p2]; + if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0 + && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0) + ){ + /* Content is irrelevant for the typeof() function and for + ** the length(X) function if X is a blob. So we might as well use + ** bogus content rather than reading content from disk. NULL works + ** for text and blob and whatever is in the payloadSize64 variable + ** will work for everything else. */ + zData = t<12 ? (char*)&payloadSize64 : 0; + }else{ + len = sqlite3VdbeSerialTypeLen(t); + sqlite3VdbeMemMove(&sMem, pDest); + rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, + &sMem); + if( rc!=SQLITE_OK ){ + goto op_column_out; + } + zData = sMem.z; + } + sqlite3VdbeSerialGet((u8*)zData, t, pDest); + } + pDest->enc = encoding; + }else{ + if( pOp->p4type==P4_MEM ){ + sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static); + }else{ + MemSetTypeFlag(pDest, MEM_Null); + } + } + + /* If we dynamically allocated space to hold the data (in the + ** sqlite3VdbeMemFromBtree() call above) then transfer control of that + ** dynamically allocated space over to the pDest structure. + ** This prevents a memory copy. + */ + if( sMem.zMalloc ){ + assert( sMem.z==sMem.zMalloc ); + assert( !(pDest->flags & MEM_Dyn) ); + assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z ); + pDest->flags &= ~(MEM_Ephem|MEM_Static); + pDest->flags |= MEM_Term; + pDest->z = sMem.z; + pDest->zMalloc = sMem.zMalloc; + } + + rc = sqlite3VdbeMemMakeWriteable(pDest); + +op_column_out: + UPDATE_MAX_BLOBSIZE(pDest); + REGISTER_TRACE(pOp->p3, pDest); + break; +} + +/* Opcode: Affinity P1 P2 * P4 * +** +** Apply affinities to a range of P2 registers starting with P1. +** +** P4 is a string that is P2 characters long. The nth character of the +** string indicates the column affinity that should be used for the nth +** memory cell in the range. +*/ +case OP_Affinity: { + const char *zAffinity; /* The affinity to be applied */ + char cAff; /* A single character of affinity */ + + zAffinity = pOp->p4.z; + assert( zAffinity!=0 ); + assert( zAffinity[pOp->p2]==0 ); + pIn1 = &aMem[pOp->p1]; + while( (cAff = *(zAffinity++))!=0 ){ + assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] ); + assert( memIsValid(pIn1) ); + ExpandBlob(pIn1); + applyAffinity(pIn1, cAff, encoding); + pIn1++; + } + break; +} + +/* Opcode: MakeRecord P1 P2 P3 P4 * +** +** Convert P2 registers beginning with P1 into the [record format] +** use as a data record in a database table or as a key +** in an index. The OP_Column opcode can decode the record later. +** +** P4 may be a string that is P2 characters long. The nth character of the +** string indicates the column affinity that should be used for the nth +** field of the index key. +** +** The mapping from character to affinity is given by the SQLITE_AFF_ +** macros defined in sqliteInt.h. +** +** If P4 is NULL then all index fields have the affinity NONE. +*/ +case OP_MakeRecord: { + u8 *zNewRecord; /* A buffer to hold the data for the new record */ + Mem *pRec; /* The new record */ + u64 nData; /* Number of bytes of data space */ + int nHdr; /* Number of bytes of header space */ + i64 nByte; /* Data space required for this record */ + int nZero; /* Number of zero bytes at the end of the record */ + int nVarint; /* Number of bytes in a varint */ + u32 serial_type; /* Type field */ + Mem *pData0; /* First field to be combined into the record */ + Mem *pLast; /* Last field of the record */ + int nField; /* Number of fields in the record */ + char *zAffinity; /* The affinity string for the record */ + int file_format; /* File format to use for encoding */ + int i; /* Space used in zNewRecord[] */ + int len; /* Length of a field */ + + /* Assuming the record contains N fields, the record format looks + ** like this: + ** + ** ------------------------------------------------------------------------ + ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | + ** ------------------------------------------------------------------------ + ** + ** Data(0) is taken from register P1. Data(1) comes from register P1+1 + ** and so froth. + ** + ** Each type field is a varint representing the serial type of the + ** corresponding data element (see sqlite3VdbeSerialType()). The + ** hdr-size field is also a varint which is the offset from the beginning + ** of the record to data0. + */ + nData = 0; /* Number of bytes of data space */ + nHdr = 0; /* Number of bytes of header space */ + nZero = 0; /* Number of zero bytes at the end of the record */ + nField = pOp->p1; + zAffinity = pOp->p4.z; + assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 ); + pData0 = &aMem[nField]; + nField = pOp->p2; + pLast = &pData0[nField-1]; + file_format = p->minWriteFileFormat; + + /* Identify the output register */ + assert( pOp->p3p1 || pOp->p3>=pOp->p1+pOp->p2 ); + pOut = &aMem[pOp->p3]; + memAboutToChange(p, pOut); + + /* Loop through the elements that will make up the record to figure + ** out how much space is required for the new record. + */ + for(pRec=pData0; pRec<=pLast; pRec++){ + assert( memIsValid(pRec) ); + if( zAffinity ){ + applyAffinity(pRec, zAffinity[pRec-pData0], encoding); + } + if( pRec->flags&MEM_Zero && pRec->n>0 ){ + sqlite3VdbeMemExpandBlob(pRec); + } + serial_type = sqlite3VdbeSerialType(pRec, file_format); + len = sqlite3VdbeSerialTypeLen(serial_type); + nData += len; + nHdr += sqlite3VarintLen(serial_type); + if( pRec->flags & MEM_Zero ){ + /* Only pure zero-filled BLOBs can be input to this Opcode. + ** We do not allow blobs with a prefix and a zero-filled tail. */ + nZero += pRec->u.nZero; + }else if( len ){ + nZero = 0; + } + } + + /* Add the initial header varint and total the size */ + nHdr += nVarint = sqlite3VarintLen(nHdr); + if( nVarintdb->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + + /* Make sure the output register has a buffer large enough to store + ** the new record. The output register (pOp->p3) is not allowed to + ** be one of the input registers (because the following call to + ** sqlite3VdbeMemGrow() could clobber the value before it is used). + */ + if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){ + goto no_mem; + } + zNewRecord = (u8 *)pOut->z; + + /* Write the record */ + i = putVarint32(zNewRecord, nHdr); + for(pRec=pData0; pRec<=pLast; pRec++){ + serial_type = sqlite3VdbeSerialType(pRec, file_format); + i += putVarint32(&zNewRecord[i], serial_type); /* serial type */ + } + for(pRec=pData0; pRec<=pLast; pRec++){ /* serial data */ + i += sqlite3VdbeSerialPut(&zNewRecord[i], (int)(nByte-i), pRec,file_format); + } + assert( i==nByte ); + + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + pOut->n = (int)nByte; + pOut->flags = MEM_Blob | MEM_Dyn; + pOut->xDel = 0; + if( nZero ){ + pOut->u.nZero = nZero; + pOut->flags |= MEM_Zero; + } + pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */ + REGISTER_TRACE(pOp->p3, pOut); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Count P1 P2 * * * +** +** Store the number of entries (an integer value) in the table or index +** opened by cursor P1 in register P2 +*/ +#ifndef SQLITE_OMIT_BTREECOUNT +case OP_Count: { /* out2-prerelease */ + i64 nEntry; + BtCursor *pCrsr; + + pCrsr = p->apCsr[pOp->p1]->pCursor; + if( ALWAYS(pCrsr) ){ + rc = sqlite3BtreeCount(pCrsr, &nEntry); + }else{ + nEntry = 0; + } + pOut->u.i = nEntry; + break; +} +#endif + +/* Opcode: Savepoint P1 * * P4 * +** +** Open, release or rollback the savepoint named by parameter P4, depending +** on the value of P1. To open a new savepoint, P1==0. To release (commit) an +** existing savepoint, P1==1, or to rollback an existing savepoint P1==2. +*/ +case OP_Savepoint: { + int p1; /* Value of P1 operand */ + char *zName; /* Name of savepoint */ + int nName; + Savepoint *pNew; + Savepoint *pSavepoint; + Savepoint *pTmp; + int iSavepoint; + int ii; + + p1 = pOp->p1; + zName = pOp->p4.z; + + /* Assert that the p1 parameter is valid. Also that if there is no open + ** transaction, then there cannot be any savepoints. + */ + assert( db->pSavepoint==0 || db->autoCommit==0 ); + assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK ); + assert( db->pSavepoint || db->isTransactionSavepoint==0 ); + assert( checkSavepointCount(db) ); + assert( p->bIsReader ); + + if( p1==SAVEPOINT_BEGIN ){ + if( db->nVdbeWrite>0 ){ + /* A new savepoint cannot be created if there are active write + ** statements (i.e. open read/write incremental blob handles). + */ + sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - " + "SQL statements in progress"); + rc = SQLITE_BUSY; + }else{ + nName = sqlite3Strlen30(zName); + +#ifndef SQLITE_OMIT_VIRTUALTABLE + /* This call is Ok even if this savepoint is actually a transaction + ** savepoint (and therefore should not prompt xSavepoint()) callbacks. + ** If this is a transaction savepoint being opened, it is guaranteed + ** that the db->aVTrans[] array is empty. */ + assert( db->autoCommit==0 || db->nVTrans==0 ); + rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, + db->nStatement+db->nSavepoint); + if( rc!=SQLITE_OK ) goto abort_due_to_error; +#endif + + /* Create a new savepoint structure. */ + pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1); + if( pNew ){ + pNew->zName = (char *)&pNew[1]; + memcpy(pNew->zName, zName, nName+1); + + /* If there is no open transaction, then mark this as a special + ** "transaction savepoint". */ + if( db->autoCommit ){ + db->autoCommit = 0; + db->isTransactionSavepoint = 1; + }else{ + db->nSavepoint++; + } + + /* Link the new savepoint into the database handle's list. */ + pNew->pNext = db->pSavepoint; + db->pSavepoint = pNew; + pNew->nDeferredCons = db->nDeferredCons; + pNew->nDeferredImmCons = db->nDeferredImmCons; + } + } + }else{ + iSavepoint = 0; + + /* Find the named savepoint. If there is no such savepoint, then an + ** an error is returned to the user. */ + for( + pSavepoint = db->pSavepoint; + pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName); + pSavepoint = pSavepoint->pNext + ){ + iSavepoint++; + } + if( !pSavepoint ){ + sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName); + rc = SQLITE_ERROR; + }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){ + /* It is not possible to release (commit) a savepoint if there are + ** active write statements. + */ + sqlite3SetString(&p->zErrMsg, db, + "cannot release savepoint - SQL statements in progress" + ); + rc = SQLITE_BUSY; + }else{ + + /* Determine whether or not this is a transaction savepoint. If so, + ** and this is a RELEASE command, then the current transaction + ** is committed. + */ + int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint; + if( isTransaction && p1==SAVEPOINT_RELEASE ){ + if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ + goto vdbe_return; + } + db->autoCommit = 1; + if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ + p->pc = pc; + db->autoCommit = 0; + p->rc = rc = SQLITE_BUSY; + goto vdbe_return; + } + db->isTransactionSavepoint = 0; + rc = p->rc; + }else{ + iSavepoint = db->nSavepoint - iSavepoint - 1; + if( p1==SAVEPOINT_ROLLBACK ){ + for(ii=0; iinDb; ii++){ + sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT); + } + } + for(ii=0; iinDb; ii++){ + rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + } + if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){ + sqlite3ExpirePreparedStatements(db); + sqlite3ResetAllSchemasOfConnection(db); + db->flags = (db->flags | SQLITE_InternChanges); + } + } + + /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all + ** savepoints nested inside of the savepoint being operated on. */ + while( db->pSavepoint!=pSavepoint ){ + pTmp = db->pSavepoint; + db->pSavepoint = pTmp->pNext; + sqlite3DbFree(db, pTmp); + db->nSavepoint--; + } + + /* If it is a RELEASE, then destroy the savepoint being operated on + ** too. If it is a ROLLBACK TO, then set the number of deferred + ** constraint violations present in the database to the value stored + ** when the savepoint was created. */ + if( p1==SAVEPOINT_RELEASE ){ + assert( pSavepoint==db->pSavepoint ); + db->pSavepoint = pSavepoint->pNext; + sqlite3DbFree(db, pSavepoint); + if( !isTransaction ){ + db->nSavepoint--; + } + }else{ + db->nDeferredCons = pSavepoint->nDeferredCons; + db->nDeferredImmCons = pSavepoint->nDeferredImmCons; + } + + if( !isTransaction ){ + rc = sqlite3VtabSavepoint(db, p1, iSavepoint); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + } + } + } + + break; +} + +/* Opcode: AutoCommit P1 P2 * * * +** +** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll +** back any currently active btree transactions. If there are any active +** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if +** there are active writing VMs or active VMs that use shared cache. +** +** This instruction causes the VM to halt. +*/ +case OP_AutoCommit: { + int desiredAutoCommit; + int iRollback; + int turnOnAC; + + desiredAutoCommit = pOp->p1; + iRollback = pOp->p2; + turnOnAC = desiredAutoCommit && !db->autoCommit; + assert( desiredAutoCommit==1 || desiredAutoCommit==0 ); + assert( desiredAutoCommit==1 || iRollback==0 ); + assert( db->nVdbeActive>0 ); /* At least this one VM is active */ + assert( p->bIsReader ); + +#if 0 + if( turnOnAC && iRollback && db->nVdbeActive>1 ){ + /* If this instruction implements a ROLLBACK and other VMs are + ** still running, and a transaction is active, return an error indicating + ** that the other VMs must complete first. + */ + sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - " + "SQL statements in progress"); + rc = SQLITE_BUSY; + }else +#endif + if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){ + /* If this instruction implements a COMMIT and other VMs are writing + ** return an error indicating that the other VMs must complete first. + */ + sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - " + "SQL statements in progress"); + rc = SQLITE_BUSY; + }else if( desiredAutoCommit!=db->autoCommit ){ + if( iRollback ){ + assert( desiredAutoCommit==1 ); + sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + db->autoCommit = 1; + }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ + goto vdbe_return; + }else{ + db->autoCommit = (u8)desiredAutoCommit; + if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ + p->pc = pc; + db->autoCommit = (u8)(1-desiredAutoCommit); + p->rc = rc = SQLITE_BUSY; + goto vdbe_return; + } + } + assert( db->nStatement==0 ); + sqlite3CloseSavepoints(db); + if( p->rc==SQLITE_OK ){ + rc = SQLITE_DONE; + }else{ + rc = SQLITE_ERROR; + } + goto vdbe_return; + }else{ + sqlite3SetString(&p->zErrMsg, db, + (!desiredAutoCommit)?"cannot start a transaction within a transaction":( + (iRollback)?"cannot rollback - no transaction is active": + "cannot commit - no transaction is active")); + + rc = SQLITE_ERROR; + } + break; +} + +/* Opcode: Transaction P1 P2 * * * +** +** Begin a transaction. The transaction ends when a Commit or Rollback +** opcode is encountered. Depending on the ON CONFLICT setting, the +** transaction might also be rolled back if an error is encountered. +** +** P1 is the index of the database file on which the transaction is +** started. Index 0 is the main database file and index 1 is the +** file used for temporary tables. Indices of 2 or more are used for +** attached databases. +** +** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is +** obtained on the database file when a write-transaction is started. No +** other process can start another write transaction while this transaction is +** underway. Starting a write transaction also creates a rollback journal. A +** write transaction must be started before any changes can be made to the +** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is +** also obtained on the file. +** +** If a write-transaction is started and the Vdbe.usesStmtJournal flag is +** true (this flag is set if the Vdbe may modify more than one row and may +** throw an ABORT exception), a statement transaction may also be opened. +** More specifically, a statement transaction is opened iff the database +** connection is currently not in autocommit mode, or if there are other +** active statements. A statement transaction allows the changes made by this +** VDBE to be rolled back after an error without having to roll back the +** entire transaction. If no error is encountered, the statement transaction +** will automatically commit when the VDBE halts. +** +** If P2 is zero, then a read-lock is obtained on the database file. +*/ +case OP_Transaction: { + Btree *pBt; + + assert( p->bIsReader ); + assert( p->readOnly==0 || pOp->p2==0 ); + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){ + rc = SQLITE_READONLY; + goto abort_due_to_error; + } + pBt = db->aDb[pOp->p1].pBt; + + if( pBt ){ + rc = sqlite3BtreeBeginTrans(pBt, pOp->p2); + if( rc==SQLITE_BUSY ){ + p->pc = pc; + p->rc = rc = SQLITE_BUSY; + goto vdbe_return; + } + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + + if( pOp->p2 && p->usesStmtJournal + && (db->autoCommit==0 || db->nVdbeRead>1) + ){ + assert( sqlite3BtreeIsInTrans(pBt) ); + if( p->iStatement==0 ){ + assert( db->nStatement>=0 && db->nSavepoint>=0 ); + db->nStatement++; + p->iStatement = db->nSavepoint + db->nStatement; + } + + rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1); + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeBeginStmt(pBt, p->iStatement); + } + + /* Store the current value of the database handles deferred constraint + ** counter. If the statement transaction needs to be rolled back, + ** the value of this counter needs to be restored too. */ + p->nStmtDefCons = db->nDeferredCons; + p->nStmtDefImmCons = db->nDeferredImmCons; + } + } + break; +} + +/* Opcode: ReadCookie P1 P2 P3 * * +** +** Read cookie number P3 from database P1 and write it into register P2. +** P3==1 is the schema version. P3==2 is the database format. +** P3==3 is the recommended pager cache size, and so forth. P1==0 is +** the main database file and P1==1 is the database file used to store +** temporary tables. +** +** There must be a read-lock on the database (either a transaction +** must be started or there must be an open cursor) before +** executing this instruction. +*/ +case OP_ReadCookie: { /* out2-prerelease */ + int iMeta; + int iDb; + int iCookie; + + assert( p->bIsReader ); + iDb = pOp->p1; + iCookie = pOp->p3; + assert( pOp->p3=0 && iDbnDb ); + assert( db->aDb[iDb].pBt!=0 ); + assert( (p->btreeMask & (((yDbMask)1)<aDb[iDb].pBt, iCookie, (u32 *)&iMeta); + pOut->u.i = iMeta; + break; +} + +/* Opcode: SetCookie P1 P2 P3 * * +** +** Write the content of register P3 (interpreted as an integer) +** into cookie number P2 of database P1. P2==1 is the schema version. +** P2==2 is the database format. P2==3 is the recommended pager cache +** size, and so forth. P1==0 is the main database file and P1==1 is the +** database file used to store temporary tables. +** +** A transaction must be started before executing this opcode. +*/ +case OP_SetCookie: { /* in3 */ + Db *pDb; + assert( pOp->p2p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + assert( p->readOnly==0 ); + pDb = &db->aDb[pOp->p1]; + assert( pDb->pBt!=0 ); + assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); + pIn3 = &aMem[pOp->p3]; + sqlite3VdbeMemIntegerify(pIn3); + /* See note about index shifting on OP_ReadCookie */ + rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i); + if( pOp->p2==BTREE_SCHEMA_VERSION ){ + /* When the schema cookie changes, record the new cookie internally */ + pDb->pSchema->schema_cookie = (int)pIn3->u.i; + db->flags |= SQLITE_InternChanges; + }else if( pOp->p2==BTREE_FILE_FORMAT ){ + /* Record changes in the file format */ + pDb->pSchema->file_format = (u8)pIn3->u.i; + } + if( pOp->p1==1 ){ + /* Invalidate all prepared statements whenever the TEMP database + ** schema is changed. Ticket #1644 */ + sqlite3ExpirePreparedStatements(db); + p->expired = 0; + } + break; +} + +/* Opcode: VerifyCookie P1 P2 P3 * * +** +** Check the value of global database parameter number 0 (the +** schema version) and make sure it is equal to P2 and that the +** generation counter on the local schema parse equals P3. +** +** P1 is the database number which is 0 for the main database file +** and 1 for the file holding temporary tables and some higher number +** for auxiliary databases. +** +** The cookie changes its value whenever the database schema changes. +** This operation is used to detect when that the cookie has changed +** and that the current process needs to reread the schema. +** +** Either a transaction needs to have been started or an OP_Open needs +** to be executed (to establish a read lock) before this opcode is +** invoked. +*/ +case OP_VerifyCookie: { + int iMeta; + int iGen; + Btree *pBt; + + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); + assert( p->bIsReader ); + pBt = db->aDb[pOp->p1].pBt; + if( pBt ){ + sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta); + iGen = db->aDb[pOp->p1].pSchema->iGeneration; + }else{ + iGen = iMeta = 0; + } + if( iMeta!=pOp->p2 || iGen!=pOp->p3 ){ + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed"); + /* If the schema-cookie from the database file matches the cookie + ** stored with the in-memory representation of the schema, do + ** not reload the schema from the database file. + ** + ** If virtual-tables are in use, this is not just an optimization. + ** Often, v-tables store their data in other SQLite tables, which + ** are queried from within xNext() and other v-table methods using + ** prepared queries. If such a query is out-of-date, we do not want to + ** discard the database schema, as the user code implementing the + ** v-table would have to be ready for the sqlite3_vtab structure itself + ** to be invalidated whenever sqlite3_step() is called from within + ** a v-table method. + */ + if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){ + sqlite3ResetOneSchema(db, pOp->p1); + } + + p->expired = 1; + rc = SQLITE_SCHEMA; + } + break; +} + +/* Opcode: OpenRead P1 P2 P3 P4 P5 +** +** Open a read-only cursor for the database table whose root page is +** P2 in a database file. The database file is determined by P3. +** P3==0 means the main database, P3==1 means the database used for +** temporary tables, and P3>1 means used the corresponding attached +** database. Give the new cursor an identifier of P1. The P1 +** values need not be contiguous but all P1 values should be small integers. +** It is an error for P1 to be negative. +** +** If P5!=0 then use the content of register P2 as the root page, not +** the value of P2 itself. +** +** There will be a read lock on the database whenever there is an +** open cursor. If the database was unlocked prior to this instruction +** then a read lock is acquired as part of this instruction. A read +** lock allows other processes to read the database but prohibits +** any other process from modifying the database. The read lock is +** released when all cursors are closed. If this instruction attempts +** to get a read lock but fails, the script terminates with an +** SQLITE_BUSY error code. +** +** The P4 value may be either an integer (P4_INT32) or a pointer to +** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo +** structure, then said structure defines the content and collating +** sequence of the index being opened. Otherwise, if P4 is an integer +** value, it is set to the number of columns in the table. +** +** See also OpenWrite. +*/ +/* Opcode: OpenWrite P1 P2 P3 P4 P5 +** +** Open a read/write cursor named P1 on the table or index whose root +** page is P2. Or if P5!=0 use the content of register P2 to find the +** root page. +** +** The P4 value may be either an integer (P4_INT32) or a pointer to +** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo +** structure, then said structure defines the content and collating +** sequence of the index being opened. Otherwise, if P4 is an integer +** value, it is set to the number of columns in the table, or to the +** largest index of any column of the table that is actually used. +** +** This instruction works just like OpenRead except that it opens the cursor +** in read/write mode. For a given table, there can be one or more read-only +** cursors or a single read/write cursor but not both. +** +** See also OpenRead. +*/ +case OP_OpenRead: +case OP_OpenWrite: { + int nField; + KeyInfo *pKeyInfo; + int p2; + int iDb; + int wrFlag; + Btree *pX; + VdbeCursor *pCur; + Db *pDb; + + assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 ); + assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 ); + assert( p->bIsReader ); + assert( pOp->opcode==OP_OpenRead || p->readOnly==0 ); + + if( p->expired ){ + rc = SQLITE_ABORT; + break; + } + + nField = 0; + pKeyInfo = 0; + p2 = pOp->p2; + iDb = pOp->p3; + assert( iDb>=0 && iDbnDb ); + assert( (p->btreeMask & (((yDbMask)1)<aDb[iDb]; + pX = pDb->pBt; + assert( pX!=0 ); + if( pOp->opcode==OP_OpenWrite ){ + wrFlag = 1; + assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + if( pDb->pSchema->file_format < p->minWriteFileFormat ){ + p->minWriteFileFormat = pDb->pSchema->file_format; + } + }else{ + wrFlag = 0; + } + if( pOp->p5 & OPFLAG_P2ISREG ){ + assert( p2>0 ); + assert( p2<=(p->nMem-p->nCursor) ); + pIn2 = &aMem[p2]; + assert( memIsValid(pIn2) ); + assert( (pIn2->flags & MEM_Int)!=0 ); + sqlite3VdbeMemIntegerify(pIn2); + p2 = (int)pIn2->u.i; + /* The p2 value always comes from a prior OP_CreateTable opcode and + ** that opcode will always set the p2 value to 2 or more or else fail. + ** If there were a failure, the prepared statement would have halted + ** before reaching this instruction. */ + if( NEVER(p2<2) ) { + rc = SQLITE_CORRUPT_BKPT; + goto abort_due_to_error; + } + } + if( pOp->p4type==P4_KEYINFO ){ + pKeyInfo = pOp->p4.pKeyInfo; + pKeyInfo->enc = ENC(p->db); + nField = pKeyInfo->nField+1; + }else if( pOp->p4type==P4_INT32 ){ + nField = pOp->p4.i; + } + assert( pOp->p1>=0 ); + pCur = allocateCursor(p, pOp->p1, nField, iDb, 1); + if( pCur==0 ) goto no_mem; + pCur->nullRow = 1; + pCur->isOrdered = 1; + rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor); + pCur->pKeyInfo = pKeyInfo; + assert( OPFLAG_BULKCSR==BTREE_BULKLOAD ); + sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR)); + + /* Since it performs no memory allocation or IO, the only value that + ** sqlite3BtreeCursor() may return is SQLITE_OK. */ + assert( rc==SQLITE_OK ); + + /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of + ** SQLite used to check if the root-page flags were sane at this point + ** and report database corruption if they were not, but this check has + ** since moved into the btree layer. */ + pCur->isTable = pOp->p4type!=P4_KEYINFO; + pCur->isIndex = !pCur->isTable; + break; +} + +/* Opcode: OpenEphemeral P1 P2 * P4 P5 +** +** Open a new cursor P1 to a transient table. +** The cursor is always opened read/write even if +** the main database is read-only. The ephemeral +** table is deleted automatically when the cursor is closed. +** +** P2 is the number of columns in the ephemeral table. +** The cursor points to a BTree table if P4==0 and to a BTree index +** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure +** that defines the format of keys in the index. +** +** This opcode was once called OpenTemp. But that created +** confusion because the term "temp table", might refer either +** to a TEMP table at the SQL level, or to a table opened by +** this opcode. Then this opcode was call OpenVirtual. But +** that created confusion with the whole virtual-table idea. +** +** The P5 parameter can be a mask of the BTREE_* flags defined +** in btree.h. These flags control aspects of the operation of +** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are +** added automatically. +*/ +/* Opcode: OpenAutoindex P1 P2 * P4 * +** +** This opcode works the same as OP_OpenEphemeral. It has a +** different name to distinguish its use. Tables created using +** by this opcode will be used for automatically created transient +** indices in joins. +*/ +case OP_OpenAutoindex: +case OP_OpenEphemeral: { + VdbeCursor *pCx; + static const int vfsFlags = + SQLITE_OPEN_READWRITE | + SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | + SQLITE_OPEN_DELETEONCLOSE | + SQLITE_OPEN_TRANSIENT_DB; + + assert( pOp->p1>=0 ); + pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1); + if( pCx==0 ) goto no_mem; + pCx->nullRow = 1; + rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt, + BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags); + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeBeginTrans(pCx->pBt, 1); + } + if( rc==SQLITE_OK ){ + /* If a transient index is required, create it by calling + ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before + ** opening it. If a transient table is required, just use the + ** automatically created table with root-page 1 (an BLOB_INTKEY table). + */ + if( pOp->p4.pKeyInfo ){ + int pgno; + assert( pOp->p4type==P4_KEYINFO ); + rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5); + if( rc==SQLITE_OK ){ + assert( pgno==MASTER_ROOT+1 ); + rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, + (KeyInfo*)pOp->p4.z, pCx->pCursor); + pCx->pKeyInfo = pOp->p4.pKeyInfo; + pCx->pKeyInfo->enc = ENC(p->db); + } + pCx->isTable = 0; + }else{ + rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor); + pCx->isTable = 1; + } + } + pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); + pCx->isIndex = !pCx->isTable; + break; +} + +/* Opcode: SorterOpen P1 P2 * P4 * +** +** This opcode works like OP_OpenEphemeral except that it opens +** a transient index that is specifically designed to sort large +** tables using an external merge-sort algorithm. +*/ +case OP_SorterOpen: { + VdbeCursor *pCx; + + pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1); + if( pCx==0 ) goto no_mem; + pCx->pKeyInfo = pOp->p4.pKeyInfo; + pCx->pKeyInfo->enc = ENC(p->db); + pCx->isSorter = 1; + rc = sqlite3VdbeSorterInit(db, pCx); + break; +} + +/* Opcode: OpenPseudo P1 P2 P3 * P5 +** +** Open a new cursor that points to a fake table that contains a single +** row of data. The content of that one row in the content of memory +** register P2 when P5==0. In other words, cursor P1 becomes an alias for the +** MEM_Blob content contained in register P2. When P5==1, then the +** row is represented by P3 consecutive registers beginning with P2. +** +** A pseudo-table created by this opcode is used to hold a single +** row output from the sorter so that the row can be decomposed into +** individual columns using the OP_Column opcode. The OP_Column opcode +** is the only cursor opcode that works with a pseudo-table. +** +** P3 is the number of fields in the records that will be stored by +** the pseudo-table. +*/ +case OP_OpenPseudo: { + VdbeCursor *pCx; + + assert( pOp->p1>=0 ); + pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0); + if( pCx==0 ) goto no_mem; + pCx->nullRow = 1; + pCx->pseudoTableReg = pOp->p2; + pCx->isTable = 1; + pCx->isIndex = 0; + pCx->multiPseudo = pOp->p5; + break; +} + +/* Opcode: Close P1 * * * * +** +** Close a cursor previously opened as P1. If P1 is not +** currently open, this instruction is a no-op. +*/ +case OP_Close: { + assert( pOp->p1>=0 && pOp->p1nCursor ); + sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); + p->apCsr[pOp->p1] = 0; + break; +} + +/* Opcode: SeekGe P1 P2 P3 P4 * +** +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), +** use the value in register P3 as the key. If cursor P1 refers +** to an SQL index, then P3 is the first in an array of P4 registers +** that are used as an unpacked index key. +** +** Reposition cursor P1 so that it points to the smallest entry that +** is greater than or equal to the key value. If there are no records +** greater than or equal to the key and P2 is not zero, then jump to P2. +** +** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe +*/ +/* Opcode: SeekGt P1 P2 P3 P4 * +** +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), +** use the value in register P3 as a key. If cursor P1 refers +** to an SQL index, then P3 is the first in an array of P4 registers +** that are used as an unpacked index key. +** +** Reposition cursor P1 so that it points to the smallest entry that +** is greater than the key value. If there are no records greater than +** the key and P2 is not zero, then jump to P2. +** +** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe +*/ +/* Opcode: SeekLt P1 P2 P3 P4 * +** +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), +** use the value in register P3 as a key. If cursor P1 refers +** to an SQL index, then P3 is the first in an array of P4 registers +** that are used as an unpacked index key. +** +** Reposition cursor P1 so that it points to the largest entry that +** is less than the key value. If there are no records less than +** the key and P2 is not zero, then jump to P2. +** +** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe +*/ +/* Opcode: SeekLe P1 P2 P3 P4 * +** +** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), +** use the value in register P3 as a key. If cursor P1 refers +** to an SQL index, then P3 is the first in an array of P4 registers +** that are used as an unpacked index key. +** +** Reposition cursor P1 so that it points to the largest entry that +** is less than or equal to the key value. If there are no records +** less than or equal to the key and P2 is not zero, then jump to P2. +** +** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt +*/ +case OP_SeekLt: /* jump, in3 */ +case OP_SeekLe: /* jump, in3 */ +case OP_SeekGe: /* jump, in3 */ +case OP_SeekGt: { /* jump, in3 */ + int res; + int oc; + VdbeCursor *pC; + UnpackedRecord r; + int nField; + i64 iKey; /* The rowid we are to seek to */ + + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( pOp->p2!=0 ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->pseudoTableReg==0 ); + assert( OP_SeekLe == OP_SeekLt+1 ); + assert( OP_SeekGe == OP_SeekLt+2 ); + assert( OP_SeekGt == OP_SeekLt+3 ); + assert( pC->isOrdered ); + if( ALWAYS(pC->pCursor!=0) ){ + oc = pOp->opcode; + pC->nullRow = 0; + if( pC->isTable ){ + /* The input value in P3 might be of any type: integer, real, string, + ** blob, or NULL. But it needs to be an integer before we can do + ** the seek, so covert it. */ + pIn3 = &aMem[pOp->p3]; + applyNumericAffinity(pIn3); + iKey = sqlite3VdbeIntValue(pIn3); + pC->rowidIsValid = 0; + + /* If the P3 value could not be converted into an integer without + ** loss of information, then special processing is required... */ + if( (pIn3->flags & MEM_Int)==0 ){ + if( (pIn3->flags & MEM_Real)==0 ){ + /* If the P3 value cannot be converted into any kind of a number, + ** then the seek is not possible, so jump to P2 */ + pc = pOp->p2 - 1; + break; + } + /* If we reach this point, then the P3 value must be a floating + ** point number. */ + assert( (pIn3->flags & MEM_Real)!=0 ); + + if( iKey==SMALLEST_INT64 && (pIn3->r<(double)iKey || pIn3->r>0) ){ + /* The P3 value is too large in magnitude to be expressed as an + ** integer. */ + res = 1; + if( pIn3->r<0 ){ + if( oc>=OP_SeekGe ){ assert( oc==OP_SeekGe || oc==OP_SeekGt ); + rc = sqlite3BtreeFirst(pC->pCursor, &res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + } + }else{ + if( oc<=OP_SeekLe ){ assert( oc==OP_SeekLt || oc==OP_SeekLe ); + rc = sqlite3BtreeLast(pC->pCursor, &res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + } + } + if( res ){ + pc = pOp->p2 - 1; + } + break; + }else if( oc==OP_SeekLt || oc==OP_SeekGe ){ + /* Use the ceiling() function to convert real->int */ + if( pIn3->r > (double)iKey ) iKey++; + }else{ + /* Use the floor() function to convert real->int */ + assert( oc==OP_SeekLe || oc==OP_SeekGt ); + if( pIn3->r < (double)iKey ) iKey--; + } + } + rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + if( res==0 ){ + pC->rowidIsValid = 1; + pC->lastRowid = iKey; + } + }else{ + nField = pOp->p4.i; + assert( pOp->p4type==P4_INT32 ); + assert( nField>0 ); + r.pKeyInfo = pC->pKeyInfo; + r.nField = (u16)nField; + + /* The next line of code computes as follows, only faster: + ** if( oc==OP_SeekGt || oc==OP_SeekLe ){ + ** r.flags = UNPACKED_INCRKEY; + ** }else{ + ** r.flags = 0; + ** } + */ + r.flags = (u8)(UNPACKED_INCRKEY * (1 & (oc - OP_SeekLt))); + assert( oc!=OP_SeekGt || r.flags==UNPACKED_INCRKEY ); + assert( oc!=OP_SeekLe || r.flags==UNPACKED_INCRKEY ); + assert( oc!=OP_SeekGe || r.flags==0 ); + assert( oc!=OP_SeekLt || r.flags==0 ); + + r.aMem = &aMem[pOp->p3]; +#ifdef SQLITE_DEBUG + { int i; for(i=0; ipCursor, &r, 0, 0, &res); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + pC->rowidIsValid = 0; + } + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; +#ifdef SQLITE_TEST + sqlite3_search_count++; +#endif + if( oc>=OP_SeekGe ){ assert( oc==OP_SeekGe || oc==OP_SeekGt ); + if( res<0 || (res==0 && oc==OP_SeekGt) ){ + rc = sqlite3BtreeNext(pC->pCursor, &res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + pC->rowidIsValid = 0; + }else{ + res = 0; + } + }else{ + assert( oc==OP_SeekLt || oc==OP_SeekLe ); + if( res>0 || (res==0 && oc==OP_SeekLt) ){ + rc = sqlite3BtreePrevious(pC->pCursor, &res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + pC->rowidIsValid = 0; + }else{ + /* res might be negative because the table is empty. Check to + ** see if this is the case. + */ + res = sqlite3BtreeEof(pC->pCursor); + } + } + assert( pOp->p2>0 ); + if( res ){ + pc = pOp->p2 - 1; + } + }else{ + /* This happens when attempting to open the sqlite3_master table + ** for read access returns SQLITE_EMPTY. In this case always + ** take the jump (since there are no records in the table). + */ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: Seek P1 P2 * * * +** +** P1 is an open table cursor and P2 is a rowid integer. Arrange +** for P1 to move so that it points to the rowid given by P2. +** +** This is actually a deferred seek. Nothing actually happens until +** the cursor is used to read a record. That way, if no reads +** occur, no unnecessary I/O happens. +*/ +case OP_Seek: { /* in2 */ + VdbeCursor *pC; + + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + if( ALWAYS(pC->pCursor!=0) ){ + assert( pC->isTable ); + pC->nullRow = 0; + pIn2 = &aMem[pOp->p2]; + pC->movetoTarget = sqlite3VdbeIntValue(pIn2); + pC->rowidIsValid = 0; + pC->deferredMoveto = 1; + } + break; +} + + +/* Opcode: Found P1 P2 P3 P4 * +** +** If P4==0 then register P3 holds a blob constructed by MakeRecord. If +** P4>0 then register P3 is the first of P4 registers that form an unpacked +** record. +** +** Cursor P1 is on an index btree. If the record identified by P3 and P4 +** is a prefix of any entry in P1 then a jump is made to P2 and +** P1 is left pointing at the matching entry. +*/ +/* Opcode: NotFound P1 P2 P3 P4 * +** +** If P4==0 then register P3 holds a blob constructed by MakeRecord. If +** P4>0 then register P3 is the first of P4 registers that form an unpacked +** record. +** +** Cursor P1 is on an index btree. If the record identified by P3 and P4 +** is not the prefix of any entry in P1 then a jump is made to P2. If P1 +** does contain an entry whose prefix matches the P3/P4 record then control +** falls through to the next instruction and P1 is left pointing at the +** matching entry. +** +** See also: Found, NotExists, IsUnique +*/ +case OP_NotFound: /* jump, in3 */ +case OP_Found: { /* jump, in3 */ + int alreadyExists; + VdbeCursor *pC; + int res; + char *pFree; + UnpackedRecord *pIdxKey; + UnpackedRecord r; + char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7]; + +#ifdef SQLITE_TEST + sqlite3_found_count++; +#endif + + alreadyExists = 0; + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( pOp->p4type==P4_INT32 ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + pIn3 = &aMem[pOp->p3]; + if( ALWAYS(pC->pCursor!=0) ){ + + assert( pC->isTable==0 ); + if( pOp->p4.i>0 ){ + r.pKeyInfo = pC->pKeyInfo; + r.nField = (u16)pOp->p4.i; + r.aMem = pIn3; +#ifdef SQLITE_DEBUG + { int i; for(i=0; ipKeyInfo, aTempRec, sizeof(aTempRec), &pFree + ); + if( pIdxKey==0 ) goto no_mem; + assert( pIn3->flags & MEM_Blob ); + assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */ + sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); + pIdxKey->flags |= UNPACKED_PREFIX_MATCH; + } + rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res); + if( pOp->p4.i==0 ){ + sqlite3DbFree(db, pFree); + } + if( rc!=SQLITE_OK ){ + break; + } + alreadyExists = (res==0); + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; + } + if( pOp->opcode==OP_Found ){ + if( alreadyExists ) pc = pOp->p2 - 1; + }else{ + if( !alreadyExists ) pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: IsUnique P1 P2 P3 P4 * +** +** Cursor P1 is open on an index b-tree - that is to say, a btree which +** no data and where the key are records generated by OP_MakeRecord with +** the list field being the integer ROWID of the entry that the index +** entry refers to. +** +** The P3 register contains an integer record number. Call this record +** number R. Register P4 is the first in a set of N contiguous registers +** that make up an unpacked index key that can be used with cursor P1. +** The value of N can be inferred from the cursor. N includes the rowid +** value appended to the end of the index record. This rowid value may +** or may not be the same as R. +** +** If any of the N registers beginning with register P4 contains a NULL +** value, jump immediately to P2. +** +** Otherwise, this instruction checks if cursor P1 contains an entry +** where the first (N-1) fields match but the rowid value at the end +** of the index entry is not R. If there is no such entry, control jumps +** to instruction P2. Otherwise, the rowid of the conflicting index +** entry is copied to register P3 and control falls through to the next +** instruction. +** +** See also: NotFound, NotExists, Found +*/ +case OP_IsUnique: { /* jump, in3 */ + u16 ii; + VdbeCursor *pCx; + BtCursor *pCrsr; + u16 nField; + Mem *aMx; + UnpackedRecord r; /* B-Tree index search key */ + i64 R; /* Rowid stored in register P3 */ + + pIn3 = &aMem[pOp->p3]; + aMx = &aMem[pOp->p4.i]; + /* Assert that the values of parameters P1 and P4 are in range. */ + assert( pOp->p4type==P4_INT32 ); + assert( pOp->p4.i>0 && pOp->p4.i<=(p->nMem-p->nCursor) ); + assert( pOp->p1>=0 && pOp->p1nCursor ); + + /* Find the index cursor. */ + pCx = p->apCsr[pOp->p1]; + assert( pCx->deferredMoveto==0 ); + pCx->seekResult = 0; + pCx->cacheStatus = CACHE_STALE; + pCrsr = pCx->pCursor; + + /* If any of the values are NULL, take the jump. */ + nField = pCx->pKeyInfo->nField; + for(ii=0; iip2 - 1; + pCrsr = 0; + break; + } + } + assert( (aMx[nField].flags & MEM_Null)==0 ); + + if( pCrsr!=0 ){ + /* Populate the index search key. */ + r.pKeyInfo = pCx->pKeyInfo; + r.nField = nField + 1; + r.flags = UNPACKED_PREFIX_SEARCH; + r.aMem = aMx; +#ifdef SQLITE_DEBUG + { int i; for(i=0; iu.i; + + /* Search the B-Tree index. If no conflicting record is found, jump + ** to P2. Otherwise, copy the rowid of the conflicting record to + ** register P3 and fall through to the next instruction. */ + rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &pCx->seekResult); + if( (r.flags & UNPACKED_PREFIX_SEARCH) || r.rowid==R ){ + pc = pOp->p2 - 1; + }else{ + pIn3->u.i = r.rowid; + } + } + break; +} + +/* Opcode: NotExists P1 P2 P3 * * +** +** Use the content of register P3 as an integer key. If a record +** with that key does not exist in table of P1, then jump to P2. +** If the record does exist, then fall through. The cursor is left +** pointing to the record if it exists. +** +** The difference between this operation and NotFound is that this +** operation assumes the key is an integer and that P1 is a table whereas +** NotFound assumes key is a blob constructed from MakeRecord and +** P1 is an index. +** +** See also: Found, NotFound, IsUnique +*/ +case OP_NotExists: { /* jump, in3 */ + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + u64 iKey; + + pIn3 = &aMem[pOp->p3]; + assert( pIn3->flags & MEM_Int ); + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->isTable ); + assert( pC->pseudoTableReg==0 ); + pCrsr = pC->pCursor; + if( ALWAYS(pCrsr!=0) ){ + res = 0; + iKey = pIn3->u.i; + rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); + pC->lastRowid = pIn3->u.i; + pC->rowidIsValid = res==0 ?1:0; + pC->nullRow = 0; + pC->cacheStatus = CACHE_STALE; + pC->deferredMoveto = 0; + if( res!=0 ){ + pc = pOp->p2 - 1; + assert( pC->rowidIsValid==0 ); + } + pC->seekResult = res; + }else{ + /* This happens when an attempt to open a read cursor on the + ** sqlite_master table returns SQLITE_EMPTY. + */ + pc = pOp->p2 - 1; + assert( pC->rowidIsValid==0 ); + pC->seekResult = 0; + } + break; +} + +/* Opcode: Sequence P1 P2 * * * +** +** Find the next available sequence number for cursor P1. +** Write the sequence number into register P2. +** The sequence number on the cursor is incremented after this +** instruction. +*/ +case OP_Sequence: { /* out2-prerelease */ + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( p->apCsr[pOp->p1]!=0 ); + pOut->u.i = p->apCsr[pOp->p1]->seqCount++; + break; +} + + +/* Opcode: NewRowid P1 P2 P3 * * +** +** Get a new integer record number (a.k.a "rowid") used as the key to a table. +** The record number is not previously used as a key in the database +** table that cursor P1 points to. The new record number is written +** written to register P2. +** +** If P3>0 then P3 is a register in the root frame of this VDBE that holds +** the largest previously generated record number. No new record numbers are +** allowed to be less than this value. When this value reaches its maximum, +** an SQLITE_FULL error is generated. The P3 register is updated with the ' +** generated record number. This P3 mechanism is used to help implement the +** AUTOINCREMENT feature. +*/ +case OP_NewRowid: { /* out2-prerelease */ + i64 v; /* The new rowid */ + VdbeCursor *pC; /* Cursor of table to get the new rowid */ + int res; /* Result of an sqlite3BtreeLast() */ + int cnt; /* Counter to limit the number of searches */ + Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ + VdbeFrame *pFrame; /* Root frame of VDBE */ + + v = 0; + res = 0; + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + if( NEVER(pC->pCursor==0) ){ + /* The zero initialization above is all that is needed */ + }else{ + /* The next rowid or record number (different terms for the same + ** thing) is obtained in a two-step algorithm. + ** + ** First we attempt to find the largest existing rowid and add one + ** to that. But if the largest existing rowid is already the maximum + ** positive integer, we have to fall through to the second + ** probabilistic algorithm + ** + ** The second algorithm is to select a rowid at random and see if + ** it already exists in the table. If it does not exist, we have + ** succeeded. If the random rowid does exist, we select a new one + ** and try again, up to 100 times. + */ + assert( pC->isTable ); + +#ifdef SQLITE_32BIT_ROWID +# define MAX_ROWID 0x7fffffff +#else + /* Some compilers complain about constants of the form 0x7fffffffffffffff. + ** Others complain about 0x7ffffffffffffffffLL. The following macro seems + ** to provide the constant while making all compilers happy. + */ +# define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff ) +#endif + + if( !pC->useRandomRowid ){ + v = sqlite3BtreeGetCachedRowid(pC->pCursor); + if( v==0 ){ + rc = sqlite3BtreeLast(pC->pCursor, &res); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + if( res ){ + v = 1; /* IMP: R-61914-48074 */ + }else{ + assert( sqlite3BtreeCursorIsValid(pC->pCursor) ); + rc = sqlite3BtreeKeySize(pC->pCursor, &v); + assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */ + if( v>=MAX_ROWID ){ + pC->useRandomRowid = 1; + }else{ + v++; /* IMP: R-29538-34987 */ + } + } + } + +#ifndef SQLITE_OMIT_AUTOINCREMENT + if( pOp->p3 ){ + /* Assert that P3 is a valid memory cell. */ + assert( pOp->p3>0 ); + if( p->pFrame ){ + for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); + /* Assert that P3 is a valid memory cell. */ + assert( pOp->p3<=pFrame->nMem ); + pMem = &pFrame->aMem[pOp->p3]; + }else{ + /* Assert that P3 is a valid memory cell. */ + assert( pOp->p3<=(p->nMem-p->nCursor) ); + pMem = &aMem[pOp->p3]; + memAboutToChange(p, pMem); + } + assert( memIsValid(pMem) ); + + REGISTER_TRACE(pOp->p3, pMem); + sqlite3VdbeMemIntegerify(pMem); + assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ + if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){ + rc = SQLITE_FULL; /* IMP: R-12275-61338 */ + goto abort_due_to_error; + } + if( vu.i+1 ){ + v = pMem->u.i + 1; + } + pMem->u.i = v; + } +#endif + + sqlite3BtreeSetCachedRowid(pC->pCursor, vuseRandomRowid ){ + /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the + ** largest possible integer (9223372036854775807) then the database + ** engine starts picking positive candidate ROWIDs at random until + ** it finds one that is not previously used. */ + assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is + ** an AUTOINCREMENT table. */ + /* on the first attempt, simply do one more than previous */ + v = lastRowid; + v &= (MAX_ROWID>>1); /* ensure doesn't go negative */ + v++; /* ensure non-zero */ + cnt = 0; + while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v, + 0, &res))==SQLITE_OK) + && (res==0) + && (++cnt<100)){ + /* collision - try another random rowid */ + sqlite3_randomness(sizeof(v), &v); + if( cnt<5 ){ + /* try "small" random rowids for the initial attempts */ + v &= 0xffffff; + }else{ + v &= (MAX_ROWID>>1); /* ensure doesn't go negative */ + } + v++; /* ensure non-zero */ + } + if( rc==SQLITE_OK && res==0 ){ + rc = SQLITE_FULL; /* IMP: R-38219-53002 */ + goto abort_due_to_error; + } + assert( v>0 ); /* EV: R-40812-03570 */ + } + pC->rowidIsValid = 0; + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; + } + pOut->u.i = v; + break; +} + +/* Opcode: Insert P1 P2 P3 P4 P5 +** +** Write an entry into the table of cursor P1. A new entry is +** created if it doesn't already exist or the data for an existing +** entry is overwritten. The data is the value MEM_Blob stored in register +** number P2. The key is stored in register P3. The key must +** be a MEM_Int. +** +** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is +** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, +** then rowid is stored for subsequent return by the +** sqlite3_last_insert_rowid() function (otherwise it is unmodified). +** +** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of +** the last seek operation (OP_NotExists) was a success, then this +** operation will not attempt to find the appropriate row before doing +** the insert but will instead overwrite the row that the cursor is +** currently pointing to. Presumably, the prior OP_NotExists opcode +** has already positioned the cursor correctly. This is an optimization +** that boosts performance by avoiding redundant seeks. +** +** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an +** UPDATE operation. Otherwise (if the flag is clear) then this opcode +** is part of an INSERT operation. The difference is only important to +** the update hook. +** +** Parameter P4 may point to a string containing the table-name, or +** may be NULL. If it is not NULL, then the update-hook +** (sqlite3.xUpdateCallback) is invoked following a successful insert. +** +** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically +** allocated, then ownership of P2 is transferred to the pseudo-cursor +** and register P2 becomes ephemeral. If the cursor is changed, the +** value of register P2 will then change. Make sure this does not +** cause any problems.) +** +** This instruction only works on tables. The equivalent instruction +** for indices is OP_IdxInsert. +*/ +/* Opcode: InsertInt P1 P2 P3 P4 P5 +** +** This works exactly like OP_Insert except that the key is the +** integer value P3, not the value of the integer stored in register P3. +*/ +case OP_Insert: +case OP_InsertInt: { + Mem *pData; /* MEM cell holding data for the record to be inserted */ + Mem *pKey; /* MEM cell holding key for the record */ + i64 iKey; /* The integer ROWID or key for the record to be inserted */ + VdbeCursor *pC; /* Cursor to table into which insert is written */ + int nZero; /* Number of zero-bytes to append */ + int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ + const char *zDb; /* database name - used by the update hook */ + const char *zTbl; /* Table name - used by the opdate hook */ + int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */ + + pData = &aMem[pOp->p2]; + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( memIsValid(pData) ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->pCursor!=0 ); + assert( pC->pseudoTableReg==0 ); + assert( pC->isTable ); + REGISTER_TRACE(pOp->p2, pData); + + if( pOp->opcode==OP_Insert ){ + pKey = &aMem[pOp->p3]; + assert( pKey->flags & MEM_Int ); + assert( memIsValid(pKey) ); + REGISTER_TRACE(pOp->p3, pKey); + iKey = pKey->u.i; + }else{ + assert( pOp->opcode==OP_InsertInt ); + iKey = pOp->p3; + } + + if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; + if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey; + if( pData->flags & MEM_Null ){ + pData->z = 0; + pData->n = 0; + }else{ + assert( pData->flags & (MEM_Blob|MEM_Str) ); + } + seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0); + if( pData->flags & MEM_Zero ){ + nZero = pData->u.nZero; + }else{ + nZero = 0; + } + sqlite3BtreeSetCachedRowid(pC->pCursor, 0); + rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey, + pData->z, pData->n, nZero, + pOp->p5 & OPFLAG_APPEND, seekResult + ); + pC->rowidIsValid = 0; + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; + + /* Invoke the update-hook if required. */ + if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){ + zDb = db->aDb[pC->iDb].zName; + zTbl = pOp->p4.z; + op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT); + assert( pC->isTable ); + db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey); + assert( pC->iDb>=0 ); + } + break; +} + +/* Opcode: Delete P1 P2 * P4 * +** +** Delete the record at which the P1 cursor is currently pointing. +** +** The cursor will be left pointing at either the next or the previous +** record in the table. If it is left pointing at the next record, then +** the next Next instruction will be a no-op. Hence it is OK to delete +** a record from within an Next loop. +** +** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is +** incremented (otherwise not). +** +** P1 must not be pseudo-table. It has to be a real table with +** multiple rows. +** +** If P4 is not NULL, then it is the name of the table that P1 is +** pointing to. The update hook will be invoked, if it exists. +** If P4 is not NULL then the P1 cursor must have been positioned +** using OP_NotFound prior to invoking this opcode. +*/ +case OP_Delete: { + i64 iKey; + VdbeCursor *pC; + + iKey = 0; + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */ + + /* If the update-hook will be invoked, set iKey to the rowid of the + ** row being deleted. + */ + if( db->xUpdateCallback && pOp->p4.z ){ + assert( pC->isTable ); + assert( pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */ + iKey = pC->lastRowid; + } + + /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or + ** OP_Column on the same table without any intervening operations that + ** might move or invalidate the cursor. Hence cursor pC is always pointing + ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation + ** below is always a no-op and cannot fail. We will run it anyhow, though, + ** to guard against future changes to the code generator. + **/ + assert( pC->deferredMoveto==0 ); + rc = sqlite3VdbeCursorMoveto(pC); + if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; + + sqlite3BtreeSetCachedRowid(pC->pCursor, 0); + rc = sqlite3BtreeDelete(pC->pCursor); + pC->cacheStatus = CACHE_STALE; + + /* Invoke the update-hook if required. */ + if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){ + const char *zDb = db->aDb[pC->iDb].zName; + const char *zTbl = pOp->p4.z; + db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey); + assert( pC->iDb>=0 ); + } + if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++; + break; +} +/* Opcode: ResetCount * * * * * +** +** The value of the change counter is copied to the database handle +** change counter (returned by subsequent calls to sqlite3_changes()). +** Then the VMs internal change counter resets to 0. +** This is used by trigger programs. +*/ +case OP_ResetCount: { + sqlite3VdbeSetChanges(db, p->nChange); + p->nChange = 0; + break; +} + +/* Opcode: SorterCompare P1 P2 P3 +** +** P1 is a sorter cursor. This instruction compares the record blob in +** register P3 with the entry that the sorter cursor currently points to. +** If, excluding the rowid fields at the end, the two records are a match, +** fall through to the next instruction. Otherwise, jump to instruction P2. +*/ +case OP_SorterCompare: { + VdbeCursor *pC; + int res; + + pC = p->apCsr[pOp->p1]; + assert( isSorter(pC) ); + pIn3 = &aMem[pOp->p3]; + rc = sqlite3VdbeSorterCompare(pC, pIn3, &res); + if( res ){ + pc = pOp->p2-1; + } + break; +}; + +/* Opcode: SorterData P1 P2 * * * +** +** Write into register P2 the current sorter data for sorter cursor P1. +*/ +case OP_SorterData: { + VdbeCursor *pC; + + pOut = &aMem[pOp->p2]; + pC = p->apCsr[pOp->p1]; + assert( pC->isSorter ); + rc = sqlite3VdbeSorterRowkey(pC, pOut); + break; +} + +/* Opcode: RowData P1 P2 * * * +** +** Write into register P2 the complete row data for cursor P1. +** There is no interpretation of the data. +** It is just copied onto the P2 register exactly as +** it is found in the database file. +** +** If the P1 cursor must be pointing to a valid row (not a NULL row) +** of a real table, not a pseudo-table. +*/ +/* Opcode: RowKey P1 P2 * * * +** +** Write into register P2 the complete row key for cursor P1. +** There is no interpretation of the data. +** The key is copied onto the P3 register exactly as +** it is found in the database file. +** +** If the P1 cursor must be pointing to a valid row (not a NULL row) +** of a real table, not a pseudo-table. +*/ +case OP_RowKey: +case OP_RowData: { + VdbeCursor *pC; + BtCursor *pCrsr; + u32 n; + i64 n64; + + pOut = &aMem[pOp->p2]; + memAboutToChange(p, pOut); + + /* Note that RowKey and RowData are really exactly the same instruction */ + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC->isSorter==0 ); + assert( pC->isTable || pOp->opcode!=OP_RowData ); + assert( pC->isIndex || pOp->opcode==OP_RowData ); + assert( pC!=0 ); + assert( pC->nullRow==0 ); + assert( pC->pseudoTableReg==0 ); + assert( pC->pCursor!=0 ); + pCrsr = pC->pCursor; + assert( sqlite3BtreeCursorIsValid(pCrsr) ); + + /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or + ** OP_Rewind/Op_Next with no intervening instructions that might invalidate + ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always + ** a no-op and can never fail. But we leave it in place as a safety. + */ + assert( pC->deferredMoveto==0 ); + rc = sqlite3VdbeCursorMoveto(pC); + if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; + + if( pC->isIndex ){ + assert( !pC->isTable ); + VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64); + assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */ + if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + n = (u32)n64; + }else{ + VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n); + assert( rc==SQLITE_OK ); /* DataSize() cannot fail */ + if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + } + if( sqlite3VdbeMemGrow(pOut, n, 0) ){ + goto no_mem; + } + pOut->n = n; + MemSetTypeFlag(pOut, MEM_Blob); + if( pC->isIndex ){ + rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z); + }else{ + rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z); + } + pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */ + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Rowid P1 P2 * * * +** +** Store in register P2 an integer which is the key of the table entry that +** P1 is currently point to. +** +** P1 can be either an ordinary table or a virtual table. There used to +** be a separate OP_VRowid opcode for use with virtual tables, but this +** one opcode now works for both table types. +*/ +case OP_Rowid: { /* out2-prerelease */ + VdbeCursor *pC; + i64 v; + sqlite3_vtab *pVtab; + const sqlite3_module *pModule; + + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->pseudoTableReg==0 || pC->nullRow ); + if( pC->nullRow ){ + pOut->flags = MEM_Null; + break; + }else if( pC->deferredMoveto ){ + v = pC->movetoTarget; +#ifndef SQLITE_OMIT_VIRTUALTABLE + }else if( pC->pVtabCursor ){ + pVtab = pC->pVtabCursor->pVtab; + pModule = pVtab->pModule; + assert( pModule->xRowid ); + rc = pModule->xRowid(pC->pVtabCursor, &v); + sqlite3VtabImportErrmsg(p, pVtab); +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + }else{ + assert( pC->pCursor!=0 ); + rc = sqlite3VdbeCursorMoveto(pC); + if( rc ) goto abort_due_to_error; + if( pC->rowidIsValid ){ + v = pC->lastRowid; + }else{ + rc = sqlite3BtreeKeySize(pC->pCursor, &v); + assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */ + } + } + pOut->u.i = v; + break; +} + +/* Opcode: NullRow P1 * * * * +** +** Move the cursor P1 to a null row. Any OP_Column operations +** that occur while the cursor is on the null row will always +** write a NULL. +*/ +case OP_NullRow: { + VdbeCursor *pC; + + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + pC->nullRow = 1; + pC->rowidIsValid = 0; + assert( pC->pCursor || pC->pVtabCursor ); + if( pC->pCursor ){ + sqlite3BtreeClearCursor(pC->pCursor); + } + break; +} + +/* Opcode: Last P1 P2 * * * +** +** The next use of the Rowid or Column or Next instruction for P1 +** will refer to the last entry in the database table or index. +** If the table or index is empty and P2>0, then jump immediately to P2. +** If P2 is 0 or if the table or index is not empty, fall through +** to the following instruction. +*/ +case OP_Last: { /* jump */ + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + pCrsr = pC->pCursor; + res = 0; + if( ALWAYS(pCrsr!=0) ){ + rc = sqlite3BtreeLast(pCrsr, &res); + } + pC->nullRow = (u8)res; + pC->deferredMoveto = 0; + pC->rowidIsValid = 0; + pC->cacheStatus = CACHE_STALE; + if( pOp->p2>0 && res ){ + pc = pOp->p2 - 1; + } + break; +} + + +/* Opcode: Sort P1 P2 * * * +** +** This opcode does exactly the same thing as OP_Rewind except that +** it increments an undocumented global variable used for testing. +** +** Sorting is accomplished by writing records into a sorting index, +** then rewinding that index and playing it back from beginning to +** end. We use the OP_Sort opcode instead of OP_Rewind to do the +** rewinding so that the global variable will be incremented and +** regression tests can determine whether or not the optimizer is +** correctly optimizing out sorts. +*/ +case OP_SorterSort: /* jump */ +case OP_Sort: { /* jump */ +#ifdef SQLITE_TEST + sqlite3_sort_count++; + sqlite3_search_count--; +#endif + p->aCounter[SQLITE_STMTSTATUS_SORT]++; + /* Fall through into OP_Rewind */ +} +/* Opcode: Rewind P1 P2 * * * +** +** The next use of the Rowid or Column or Next instruction for P1 +** will refer to the first entry in the database table or index. +** If the table or index is empty and P2>0, then jump immediately to P2. +** If P2 is 0 or if the table or index is not empty, fall through +** to the following instruction. +*/ +case OP_Rewind: { /* jump */ + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->isSorter==(pOp->opcode==OP_SorterSort) ); + res = 1; + if( isSorter(pC) ){ + rc = sqlite3VdbeSorterRewind(db, pC, &res); + }else{ + pCrsr = pC->pCursor; + assert( pCrsr ); + rc = sqlite3BtreeFirst(pCrsr, &res); + pC->atFirst = res==0 ?1:0; + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; + pC->rowidIsValid = 0; + } + pC->nullRow = (u8)res; + assert( pOp->p2>0 && pOp->p2nOp ); + if( res ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: Next P1 P2 * P4 P5 +** +** Advance cursor P1 so that it points to the next key/data pair in its +** table or index. If there are no more key/value pairs then fall through +** to the following instruction. But if the cursor advance was successful, +** jump immediately to P2. +** +** The P1 cursor must be for a real table, not a pseudo-table. +** +** P4 is always of type P4_ADVANCE. The function pointer points to +** sqlite3BtreeNext(). +** +** If P5 is positive and the jump is taken, then event counter +** number P5-1 in the prepared statement is incremented. +** +** See also: Prev +*/ +/* Opcode: Prev P1 P2 * * P5 +** +** Back up cursor P1 so that it points to the previous key/data pair in its +** table or index. If there is no previous key/value pairs then fall through +** to the following instruction. But if the cursor backup was successful, +** jump immediately to P2. +** +** The P1 cursor must be for a real table, not a pseudo-table. +** +** P4 is always of type P4_ADVANCE. The function pointer points to +** sqlite3BtreePrevious(). +** +** If P5 is positive and the jump is taken, then event counter +** number P5-1 in the prepared statement is incremented. +*/ +case OP_SorterNext: /* jump */ +case OP_Prev: /* jump */ +case OP_Next: { /* jump */ + VdbeCursor *pC; + int res; + + assert( pOp->p1>=0 && pOp->p1nCursor ); + assert( pOp->p5aCounter) ); + pC = p->apCsr[pOp->p1]; + if( pC==0 ){ + break; /* See ticket #2273 */ + } + assert( pC->isSorter==(pOp->opcode==OP_SorterNext) ); + if( isSorter(pC) ){ + assert( pOp->opcode==OP_SorterNext ); + rc = sqlite3VdbeSorterNext(db, pC, &res); + }else{ + /* res = 1; // Always initialized by the xAdvance() call */ + assert( pC->deferredMoveto==0 ); + assert( pC->pCursor ); + assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext ); + assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious ); + rc = pOp->p4.xAdvance(pC->pCursor, &res); + } + pC->nullRow = (u8)res; + pC->cacheStatus = CACHE_STALE; + if( res==0 ){ + pc = pOp->p2 - 1; + p->aCounter[pOp->p5]++; +#ifdef SQLITE_TEST + sqlite3_search_count++; +#endif + } + pC->rowidIsValid = 0; + goto check_for_interrupt; +} + +/* Opcode: IdxInsert P1 P2 P3 * P5 +** +** Register P2 holds an SQL index key made using the +** MakeRecord instructions. This opcode writes that key +** into the index P1. Data for the entry is nil. +** +** P3 is a flag that provides a hint to the b-tree layer that this +** insert is likely to be an append. +** +** This instruction only works for indices. The equivalent instruction +** for tables is OP_Insert. +*/ +case OP_SorterInsert: /* in2 */ +case OP_IdxInsert: { /* in2 */ + VdbeCursor *pC; + BtCursor *pCrsr; + int nKey; + const char *zKey; + + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->isSorter==(pOp->opcode==OP_SorterInsert) ); + pIn2 = &aMem[pOp->p2]; + assert( pIn2->flags & MEM_Blob ); + pCrsr = pC->pCursor; + if( ALWAYS(pCrsr!=0) ){ + assert( pC->isTable==0 ); + rc = ExpandBlob(pIn2); + if( rc==SQLITE_OK ){ + if( isSorter(pC) ){ + rc = sqlite3VdbeSorterWrite(db, pC, pIn2); + }else{ + nKey = pIn2->n; + zKey = pIn2->z; + rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3, + ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) + ); + assert( pC->deferredMoveto==0 ); + pC->cacheStatus = CACHE_STALE; + } + } + } + break; +} + +/* Opcode: IdxDelete P1 P2 P3 * * +** +** The content of P3 registers starting at register P2 form +** an unpacked index key. This opcode removes that entry from the +** index opened by cursor P1. +*/ +case OP_IdxDelete: { + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + UnpackedRecord r; + + assert( pOp->p3>0 ); + assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 ); + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + pCrsr = pC->pCursor; + if( ALWAYS(pCrsr!=0) ){ + r.pKeyInfo = pC->pKeyInfo; + r.nField = (u16)pOp->p3; + r.flags = 0; + r.aMem = &aMem[pOp->p2]; +#ifdef SQLITE_DEBUG + { int i; for(i=0; ideferredMoveto==0 ); + pC->cacheStatus = CACHE_STALE; + } + break; +} + +/* Opcode: IdxRowid P1 P2 * * * +** +** Write into register P2 an integer which is the last entry in the record at +** the end of the index key pointed to by cursor P1. This integer should be +** the rowid of the table entry to which this index entry points. +** +** See also: Rowid, MakeRecord. +*/ +case OP_IdxRowid: { /* out2-prerelease */ + BtCursor *pCrsr; + VdbeCursor *pC; + i64 rowid; + + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + pCrsr = pC->pCursor; + pOut->flags = MEM_Null; + if( ALWAYS(pCrsr!=0) ){ + rc = sqlite3VdbeCursorMoveto(pC); + if( NEVER(rc) ) goto abort_due_to_error; + assert( pC->deferredMoveto==0 ); + assert( pC->isTable==0 ); + if( !pC->nullRow ){ + rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid); + if( rc!=SQLITE_OK ){ + goto abort_due_to_error; + } + pOut->u.i = rowid; + pOut->flags = MEM_Int; + } + } + break; +} + +/* Opcode: IdxGE P1 P2 P3 P4 P5 +** +** The P4 register values beginning with P3 form an unpacked index +** key that omits the ROWID. Compare this key value against the index +** that P1 is currently pointing to, ignoring the ROWID on the P1 index. +** +** If the P1 index entry is greater than or equal to the key value +** then jump to P2. Otherwise fall through to the next instruction. +** +** If P5 is non-zero then the key value is increased by an epsilon +** prior to the comparison. This make the opcode work like IdxGT except +** that if the key from register P3 is a prefix of the key in the cursor, +** the result is false whereas it would be true with IdxGT. +*/ +/* Opcode: IdxLT P1 P2 P3 P4 P5 +** +** The P4 register values beginning with P3 form an unpacked index +** key that omits the ROWID. Compare this key value against the index +** that P1 is currently pointing to, ignoring the ROWID on the P1 index. +** +** If the P1 index entry is less than the key value then jump to P2. +** Otherwise fall through to the next instruction. +** +** If P5 is non-zero then the key value is increased by an epsilon prior +** to the comparison. This makes the opcode work like IdxLE. +*/ +case OP_IdxLT: /* jump */ +case OP_IdxGE: { /* jump */ + VdbeCursor *pC; + int res; + UnpackedRecord r; + + assert( pOp->p1>=0 && pOp->p1nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->isOrdered ); + if( ALWAYS(pC->pCursor!=0) ){ + assert( pC->deferredMoveto==0 ); + assert( pOp->p5==0 || pOp->p5==1 ); + assert( pOp->p4type==P4_INT32 ); + r.pKeyInfo = pC->pKeyInfo; + r.nField = (u16)pOp->p4.i; + if( pOp->p5 ){ + r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH; + }else{ + r.flags = UNPACKED_PREFIX_MATCH; + } + r.aMem = &aMem[pOp->p3]; +#ifdef SQLITE_DEBUG + { int i; for(i=0; iopcode==OP_IdxLT ){ + res = -res; + }else{ + assert( pOp->opcode==OP_IdxGE ); + res++; + } + if( res>0 ){ + pc = pOp->p2 - 1 ; + } + } + break; +} + +/* Opcode: Destroy P1 P2 P3 * * +** +** Delete an entire database table or index whose root page in the database +** file is given by P1. +** +** The table being destroyed is in the main database file if P3==0. If +** P3==1 then the table to be clear is in the auxiliary database file +** that is used to store tables create using CREATE TEMPORARY TABLE. +** +** If AUTOVACUUM is enabled then it is possible that another root page +** might be moved into the newly deleted root page in order to keep all +** root pages contiguous at the beginning of the database. The former +** value of the root page that moved - its value before the move occurred - +** is stored in register P2. If no page +** movement was required (because the table being dropped was already +** the last one in the database) then a zero is stored in register P2. +** If AUTOVACUUM is disabled then a zero is stored in register P2. +** +** See also: Clear +*/ +case OP_Destroy: { /* out2-prerelease */ + int iMoved; + int iCnt; + Vdbe *pVdbe; + int iDb; + + assert( p->readOnly==0 ); +#ifndef SQLITE_OMIT_VIRTUALTABLE + iCnt = 0; + for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){ + if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader + && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 + ){ + iCnt++; + } + } +#else + iCnt = db->nVdbeRead; +#endif + pOut->flags = MEM_Null; + if( iCnt>1 ){ + rc = SQLITE_LOCKED; + p->errorAction = OE_Abort; + }else{ + iDb = pOp->p3; + assert( iCnt==1 ); + assert( (p->btreeMask & (((yDbMask)1)<aDb[iDb].pBt, pOp->p1, &iMoved); + pOut->flags = MEM_Int; + pOut->u.i = iMoved; +#ifndef SQLITE_OMIT_AUTOVACUUM + if( rc==SQLITE_OK && iMoved!=0 ){ + sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1); + /* All OP_Destroy operations occur on the same btree */ + assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 ); + resetSchemaOnFault = iDb+1; + } +#endif + } + break; +} + +/* Opcode: Clear P1 P2 P3 +** +** Delete all contents of the database table or index whose root page +** in the database file is given by P1. But, unlike Destroy, do not +** remove the table or index from the database file. +** +** The table being clear is in the main database file if P2==0. If +** P2==1 then the table to be clear is in the auxiliary database file +** that is used to store tables create using CREATE TEMPORARY TABLE. +** +** If the P3 value is non-zero, then the table referred to must be an +** intkey table (an SQL table, not an index). In this case the row change +** count is incremented by the number of rows in the table being cleared. +** If P3 is greater than zero, then the value stored in register P3 is +** also incremented by the number of rows in the table being cleared. +** +** See also: Destroy +*/ +case OP_Clear: { + int nChange; + + nChange = 0; + assert( p->readOnly==0 ); + assert( pOp->p1!=1 ); + assert( (p->btreeMask & (((yDbMask)1)<p2))!=0 ); + rc = sqlite3BtreeClearTable( + db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0) + ); + if( pOp->p3 ){ + p->nChange += nChange; + if( pOp->p3>0 ){ + assert( memIsValid(&aMem[pOp->p3]) ); + memAboutToChange(p, &aMem[pOp->p3]); + aMem[pOp->p3].u.i += nChange; + } + } + break; +} + +/* Opcode: CreateTable P1 P2 * * * +** +** Allocate a new table in the main database file if P1==0 or in the +** auxiliary database file if P1==1 or in an attached database if +** P1>1. Write the root page number of the new table into +** register P2 +** +** The difference between a table and an index is this: A table must +** have a 4-byte integer key and can have arbitrary data. An index +** has an arbitrary key but no data. +** +** See also: CreateIndex +*/ +/* Opcode: CreateIndex P1 P2 * * * +** +** Allocate a new index in the main database file if P1==0 or in the +** auxiliary database file if P1==1 or in an attached database if +** P1>1. Write the root page number of the new table into +** register P2. +** +** See documentation on OP_CreateTable for additional information. +*/ +case OP_CreateIndex: /* out2-prerelease */ +case OP_CreateTable: { /* out2-prerelease */ + int pgno; + int flags; + Db *pDb; + + pgno = 0; + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + assert( p->readOnly==0 ); + pDb = &db->aDb[pOp->p1]; + assert( pDb->pBt!=0 ); + if( pOp->opcode==OP_CreateTable ){ + /* flags = BTREE_INTKEY; */ + flags = BTREE_INTKEY; + }else{ + flags = BTREE_BLOBKEY; + } + rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags); + pOut->u.i = pgno; + break; +} + +/* Opcode: ParseSchema P1 * * P4 * +** +** Read and parse all entries from the SQLITE_MASTER table of database P1 +** that match the WHERE clause P4. +** +** This opcode invokes the parser to create a new virtual machine, +** then runs the new virtual machine. It is thus a re-entrant opcode. +*/ +case OP_ParseSchema: { + int iDb; + const char *zMaster; + char *zSql; + InitData initData; + + /* Any prepared statement that invokes this opcode will hold mutexes + ** on every btree. This is a prerequisite for invoking + ** sqlite3InitCallback(). + */ +#ifdef SQLITE_DEBUG + for(iDb=0; iDbnDb; iDb++){ + assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); + } +#endif + + iDb = pOp->p1; + assert( iDb>=0 && iDbnDb ); + assert( DbHasProperty(db, iDb, DB_SchemaLoaded) ); + /* Used to be a conditional */ { + zMaster = SCHEMA_TABLE(iDb); + initData.db = db; + initData.iDb = pOp->p1; + initData.pzErrMsg = &p->zErrMsg; + zSql = sqlite3MPrintf(db, + "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid", + db->aDb[iDb].zName, zMaster, pOp->p4.z); + if( zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + assert( db->init.busy==0 ); + db->init.busy = 1; + initData.rc = SQLITE_OK; + assert( !db->mallocFailed ); + rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); + if( rc==SQLITE_OK ) rc = initData.rc; + sqlite3DbFree(db, zSql); + db->init.busy = 0; + } + } + if( rc ) sqlite3ResetAllSchemasOfConnection(db); + if( rc==SQLITE_NOMEM ){ + goto no_mem; + } + break; +} + +#if !defined(SQLITE_OMIT_ANALYZE) +/* Opcode: LoadAnalysis P1 * * * * +** +** Read the sqlite_stat1 table for database P1 and load the content +** of that table into the internal index hash table. This will cause +** the analysis to be used when preparing all subsequent queries. +*/ +case OP_LoadAnalysis: { + assert( pOp->p1>=0 && pOp->p1nDb ); + rc = sqlite3AnalysisLoad(db, pOp->p1); + break; +} +#endif /* !defined(SQLITE_OMIT_ANALYZE) */ + +/* Opcode: DropTable P1 * * P4 * +** +** Remove the internal (in-memory) data structures that describe +** the table named P4 in database P1. This is called after a table +** is dropped in order to keep the internal representation of the +** schema consistent with what is on disk. +*/ +case OP_DropTable: { + sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); + break; +} + +/* Opcode: DropIndex P1 * * P4 * +** +** Remove the internal (in-memory) data structures that describe +** the index named P4 in database P1. This is called after an index +** is dropped in order to keep the internal representation of the +** schema consistent with what is on disk. +*/ +case OP_DropIndex: { + sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); + break; +} + +/* Opcode: DropTrigger P1 * * P4 * +** +** Remove the internal (in-memory) data structures that describe +** the trigger named P4 in database P1. This is called after a trigger +** is dropped in order to keep the internal representation of the +** schema consistent with what is on disk. +*/ +case OP_DropTrigger: { + sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); + break; +} + + +#ifndef SQLITE_OMIT_INTEGRITY_CHECK +/* Opcode: IntegrityCk P1 P2 P3 * P5 +** +** Do an analysis of the currently open database. Store in +** register P1 the text of an error message describing any problems. +** If no problems are found, store a NULL in register P1. +** +** The register P3 contains the maximum number of allowed errors. +** At most reg(P3) errors will be reported. +** In other words, the analysis stops as soon as reg(P1) errors are +** seen. Reg(P1) is updated with the number of errors remaining. +** +** The root page numbers of all tables in the database are integer +** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables +** total. +** +** If P5 is not zero, the check is done on the auxiliary database +** file, not the main database file. +** +** This opcode is used to implement the integrity_check pragma. +*/ +case OP_IntegrityCk: { + int nRoot; /* Number of tables to check. (Number of root pages.) */ + int *aRoot; /* Array of rootpage numbers for tables to be checked */ + int j; /* Loop counter */ + int nErr; /* Number of errors reported */ + char *z; /* Text of the error report */ + Mem *pnErr; /* Register keeping track of errors remaining */ + + assert( p->bIsReader ); + nRoot = pOp->p2; + assert( nRoot>0 ); + aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) ); + if( aRoot==0 ) goto no_mem; + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + pnErr = &aMem[pOp->p3]; + assert( (pnErr->flags & MEM_Int)!=0 ); + assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 ); + pIn1 = &aMem[pOp->p1]; + for(j=0; jp5nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p5))!=0 ); + z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot, + (int)pnErr->u.i, &nErr); + sqlite3DbFree(db, aRoot); + pnErr->u.i -= nErr; + sqlite3VdbeMemSetNull(pIn1); + if( nErr==0 ){ + assert( z==0 ); + }else if( z==0 ){ + goto no_mem; + }else{ + sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free); + } + UPDATE_MAX_BLOBSIZE(pIn1); + sqlite3VdbeChangeEncoding(pIn1, encoding); + break; +} +#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ + +/* Opcode: RowSetAdd P1 P2 * * * +** +** Insert the integer value held by register P2 into a boolean index +** held in register P1. +** +** An assertion fails if P2 is not an integer. +*/ +case OP_RowSetAdd: { /* in1, in2 */ + pIn1 = &aMem[pOp->p1]; + pIn2 = &aMem[pOp->p2]; + assert( (pIn2->flags & MEM_Int)!=0 ); + if( (pIn1->flags & MEM_RowSet)==0 ){ + sqlite3VdbeMemSetRowSet(pIn1); + if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; + } + sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i); + break; +} + +/* Opcode: RowSetRead P1 P2 P3 * * +** +** Extract the smallest value from boolean index P1 and put that value into +** register P3. Or, if boolean index P1 is initially empty, leave P3 +** unchanged and jump to instruction P2. +*/ +case OP_RowSetRead: { /* jump, in1, out3 */ + i64 val; + + pIn1 = &aMem[pOp->p1]; + if( (pIn1->flags & MEM_RowSet)==0 + || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0 + ){ + /* The boolean index is empty */ + sqlite3VdbeMemSetNull(pIn1); + pc = pOp->p2 - 1; + }else{ + /* A value was pulled from the index */ + sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val); + } + goto check_for_interrupt; +} + +/* Opcode: RowSetTest P1 P2 P3 P4 +** +** Register P3 is assumed to hold a 64-bit integer value. If register P1 +** contains a RowSet object and that RowSet object contains +** the value held in P3, jump to register P2. Otherwise, insert the +** integer in P3 into the RowSet and continue on to the +** next opcode. +** +** The RowSet object is optimized for the case where successive sets +** of integers, where each set contains no duplicates. Each set +** of values is identified by a unique P4 value. The first set +** must have P4==0, the final set P4=-1. P4 must be either -1 or +** non-negative. For non-negative values of P4 only the lower 4 +** bits are significant. +** +** This allows optimizations: (a) when P4==0 there is no need to test +** the rowset object for P3, as it is guaranteed not to contain it, +** (b) when P4==-1 there is no need to insert the value, as it will +** never be tested for, and (c) when a value that is part of set X is +** inserted, there is no need to search to see if the same value was +** previously inserted as part of set X (only if it was previously +** inserted as part of some other set). +*/ +case OP_RowSetTest: { /* jump, in1, in3 */ + int iSet; + int exists; + + pIn1 = &aMem[pOp->p1]; + pIn3 = &aMem[pOp->p3]; + iSet = pOp->p4.i; + assert( pIn3->flags&MEM_Int ); + + /* If there is anything other than a rowset object in memory cell P1, + ** delete it now and initialize P1 with an empty rowset + */ + if( (pIn1->flags & MEM_RowSet)==0 ){ + sqlite3VdbeMemSetRowSet(pIn1); + if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; + } + + assert( pOp->p4type==P4_INT32 ); + assert( iSet==-1 || iSet>=0 ); + if( iSet ){ + exists = sqlite3RowSetTest(pIn1->u.pRowSet, + (u8)(iSet>=0 ? iSet & 0xf : 0xff), + pIn3->u.i); + if( exists ){ + pc = pOp->p2 - 1; + break; + } + } + if( iSet>=0 ){ + sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i); + } + break; +} + + +#ifndef SQLITE_OMIT_TRIGGER + +/* Opcode: Program P1 P2 P3 P4 * +** +** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). +** +** P1 contains the address of the memory cell that contains the first memory +** cell in an array of values used as arguments to the sub-program. P2 +** contains the address to jump to if the sub-program throws an IGNORE +** exception using the RAISE() function. Register P3 contains the address +** of a memory cell in this (the parent) VM that is used to allocate the +** memory required by the sub-vdbe at runtime. +** +** P4 is a pointer to the VM containing the trigger program. +*/ +case OP_Program: { /* jump */ + int nMem; /* Number of memory registers for sub-program */ + int nByte; /* Bytes of runtime space required for sub-program */ + Mem *pRt; /* Register to allocate runtime space */ + Mem *pMem; /* Used to iterate through memory cells */ + Mem *pEnd; /* Last memory cell in new array */ + VdbeFrame *pFrame; /* New vdbe frame to execute in */ + SubProgram *pProgram; /* Sub-program to execute */ + void *t; /* Token identifying trigger */ + + pProgram = pOp->p4.pProgram; + pRt = &aMem[pOp->p3]; + assert( pProgram->nOp>0 ); + + /* If the p5 flag is clear, then recursive invocation of triggers is + ** disabled for backwards compatibility (p5 is set if this sub-program + ** is really a trigger, not a foreign key action, and the flag set + ** and cleared by the "PRAGMA recursive_triggers" command is clear). + ** + ** It is recursive invocation of triggers, at the SQL level, that is + ** disabled. In some cases a single trigger may generate more than one + ** SubProgram (if the trigger may be executed with more than one different + ** ON CONFLICT algorithm). SubProgram structures associated with a + ** single trigger all have the same value for the SubProgram.token + ** variable. */ + if( pOp->p5 ){ + t = pProgram->token; + for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent); + if( pFrame ) break; + } + + if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ + rc = SQLITE_ERROR; + sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion"); + break; + } + + /* Register pRt is used to store the memory required to save the state + ** of the current program, and the memory required at runtime to execute + ** the trigger program. If this trigger has been fired before, then pRt + ** is already allocated. Otherwise, it must be initialized. */ + if( (pRt->flags&MEM_Frame)==0 ){ + /* SubProgram.nMem is set to the number of memory cells used by the + ** program stored in SubProgram.aOp. As well as these, one memory + ** cell is required for each cursor used by the program. Set local + ** variable nMem (and later, VdbeFrame.nChildMem) to this value. + */ + nMem = pProgram->nMem + pProgram->nCsr; + nByte = ROUND8(sizeof(VdbeFrame)) + + nMem * sizeof(Mem) + + pProgram->nCsr * sizeof(VdbeCursor *) + + pProgram->nOnce * sizeof(u8); + pFrame = sqlite3DbMallocZero(db, nByte); + if( !pFrame ){ + goto no_mem; + } + sqlite3VdbeMemRelease(pRt); + pRt->flags = MEM_Frame; + pRt->u.pFrame = pFrame; + + pFrame->v = p; + pFrame->nChildMem = nMem; + pFrame->nChildCsr = pProgram->nCsr; + pFrame->pc = pc; + pFrame->aMem = p->aMem; + pFrame->nMem = p->nMem; + pFrame->apCsr = p->apCsr; + pFrame->nCursor = p->nCursor; + pFrame->aOp = p->aOp; + pFrame->nOp = p->nOp; + pFrame->token = pProgram->token; + pFrame->aOnceFlag = p->aOnceFlag; + pFrame->nOnceFlag = p->nOnceFlag; + + pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem]; + for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){ + pMem->flags = MEM_Invalid; + pMem->db = db; + } + }else{ + pFrame = pRt->u.pFrame; + assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem ); + assert( pProgram->nCsr==pFrame->nChildCsr ); + assert( pc==pFrame->pc ); + } + + p->nFrame++; + pFrame->pParent = p->pFrame; + pFrame->lastRowid = lastRowid; + pFrame->nChange = p->nChange; + p->nChange = 0; + p->pFrame = pFrame; + p->aMem = aMem = &VdbeFrameMem(pFrame)[-1]; + p->nMem = pFrame->nChildMem; + p->nCursor = (u16)pFrame->nChildCsr; + p->apCsr = (VdbeCursor **)&aMem[p->nMem+1]; + p->aOp = aOp = pProgram->aOp; + p->nOp = pProgram->nOp; + p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor]; + p->nOnceFlag = pProgram->nOnce; + pc = -1; + memset(p->aOnceFlag, 0, p->nOnceFlag); + + break; +} + +/* Opcode: Param P1 P2 * * * +** +** This opcode is only ever present in sub-programs called via the +** OP_Program instruction. Copy a value currently stored in a memory +** cell of the calling (parent) frame to cell P2 in the current frames +** address space. This is used by trigger programs to access the new.* +** and old.* values. +** +** The address of the cell in the parent frame is determined by adding +** the value of the P1 argument to the value of the P1 argument to the +** calling OP_Program instruction. +*/ +case OP_Param: { /* out2-prerelease */ + VdbeFrame *pFrame; + Mem *pIn; + pFrame = p->pFrame; + pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1]; + sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem); + break; +} + +#endif /* #ifndef SQLITE_OMIT_TRIGGER */ + +#ifndef SQLITE_OMIT_FOREIGN_KEY +/* Opcode: FkCounter P1 P2 * * * +** +** Increment a "constraint counter" by P2 (P2 may be negative or positive). +** If P1 is non-zero, the database constraint counter is incremented +** (deferred foreign key constraints). Otherwise, if P1 is zero, the +** statement counter is incremented (immediate foreign key constraints). +*/ +case OP_FkCounter: { + if( db->flags & SQLITE_DeferFKs ){ + db->nDeferredImmCons += pOp->p2; + }else if( pOp->p1 ){ + db->nDeferredCons += pOp->p2; + }else{ + p->nFkConstraint += pOp->p2; + } + break; +} + +/* Opcode: FkIfZero P1 P2 * * * +** +** This opcode tests if a foreign key constraint-counter is currently zero. +** If so, jump to instruction P2. Otherwise, fall through to the next +** instruction. +** +** If P1 is non-zero, then the jump is taken if the database constraint-counter +** is zero (the one that counts deferred constraint violations). If P1 is +** zero, the jump is taken if the statement constraint-counter is zero +** (immediate foreign key constraint violations). +*/ +case OP_FkIfZero: { /* jump */ + if( pOp->p1 ){ + if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1; + }else{ + if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1; + } + break; +} +#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ + +#ifndef SQLITE_OMIT_AUTOINCREMENT +/* Opcode: MemMax P1 P2 * * * +** +** P1 is a register in the root frame of this VM (the root frame is +** different from the current frame if this instruction is being executed +** within a sub-program). Set the value of register P1 to the maximum of +** its current value and the value in register P2. +** +** This instruction throws an error if the memory cell is not initially +** an integer. +*/ +case OP_MemMax: { /* in2 */ + Mem *pIn1; + VdbeFrame *pFrame; + if( p->pFrame ){ + for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); + pIn1 = &pFrame->aMem[pOp->p1]; + }else{ + pIn1 = &aMem[pOp->p1]; + } + assert( memIsValid(pIn1) ); + sqlite3VdbeMemIntegerify(pIn1); + pIn2 = &aMem[pOp->p2]; + sqlite3VdbeMemIntegerify(pIn2); + if( pIn1->u.iu.i){ + pIn1->u.i = pIn2->u.i; + } + break; +} +#endif /* SQLITE_OMIT_AUTOINCREMENT */ + +/* Opcode: IfPos P1 P2 * * * +** +** If the value of register P1 is 1 or greater, jump to P2. +** +** It is illegal to use this instruction on a register that does +** not contain an integer. An assertion fault will result if you try. +*/ +case OP_IfPos: { /* jump, in1 */ + pIn1 = &aMem[pOp->p1]; + assert( pIn1->flags&MEM_Int ); + if( pIn1->u.i>0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: IfNeg P1 P2 * * * +** +** If the value of register P1 is less than zero, jump to P2. +** +** It is illegal to use this instruction on a register that does +** not contain an integer. An assertion fault will result if you try. +*/ +case OP_IfNeg: { /* jump, in1 */ + pIn1 = &aMem[pOp->p1]; + assert( pIn1->flags&MEM_Int ); + if( pIn1->u.i<0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: IfZero P1 P2 P3 * * +** +** The register P1 must contain an integer. Add literal P3 to the +** value in register P1. If the result is exactly 0, jump to P2. +** +** It is illegal to use this instruction on a register that does +** not contain an integer. An assertion fault will result if you try. +*/ +case OP_IfZero: { /* jump, in1 */ + pIn1 = &aMem[pOp->p1]; + assert( pIn1->flags&MEM_Int ); + pIn1->u.i += pOp->p3; + if( pIn1->u.i==0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: AggStep * P2 P3 P4 P5 +** +** Execute the step function for an aggregate. The +** function has P5 arguments. P4 is a pointer to the FuncDef +** structure that specifies the function. Use register +** P3 as the accumulator. +** +** The P5 arguments are taken from register P2 and its +** successors. +*/ +case OP_AggStep: { + int n; + int i; + Mem *pMem; + Mem *pRec; + sqlite3_context ctx; + sqlite3_value **apVal; + + n = pOp->p5; + assert( n>=0 ); + pRec = &aMem[pOp->p2]; + apVal = p->apArg; + assert( apVal || n==0 ); + for(i=0; ip4.pFunc; + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + ctx.pMem = pMem = &aMem[pOp->p3]; + pMem->n++; + ctx.s.flags = MEM_Null; + ctx.s.z = 0; + ctx.s.zMalloc = 0; + ctx.s.xDel = 0; + ctx.s.db = db; + ctx.isError = 0; + ctx.pColl = 0; + ctx.skipFlag = 0; + if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ + assert( pOp>p->aOp ); + assert( pOp[-1].p4type==P4_COLLSEQ ); + assert( pOp[-1].opcode==OP_CollSeq ); + ctx.pColl = pOp[-1].p4.pColl; + } + (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */ + if( ctx.isError ){ + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s)); + rc = ctx.isError; + } + if( ctx.skipFlag ){ + assert( pOp[-1].opcode==OP_CollSeq ); + i = pOp[-1].p1; + if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1); + } + + sqlite3VdbeMemRelease(&ctx.s); + + break; +} + +/* Opcode: AggFinal P1 P2 * P4 * +** +** Execute the finalizer function for an aggregate. P1 is +** the memory location that is the accumulator for the aggregate. +** +** P2 is the number of arguments that the step function takes and +** P4 is a pointer to the FuncDef for this function. The P2 +** argument is not used by this opcode. It is only there to disambiguate +** functions that can take varying numbers of arguments. The +** P4 argument is only needed for the degenerate case where +** the step function was not previously called. +*/ +case OP_AggFinal: { + Mem *pMem; + assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) ); + pMem = &aMem[pOp->p1]; + assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); + rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); + if( rc ){ + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem)); + } + sqlite3VdbeChangeEncoding(pMem, encoding); + UPDATE_MAX_BLOBSIZE(pMem); + if( sqlite3VdbeMemTooBig(pMem) ){ + goto too_big; + } + break; +} + +#ifndef SQLITE_OMIT_WAL +/* Opcode: Checkpoint P1 P2 P3 * * +** +** Checkpoint database P1. This is a no-op if P1 is not currently in +** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL +** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns +** SQLITE_BUSY or not, respectively. Write the number of pages in the +** WAL after the checkpoint into mem[P3+1] and the number of pages +** in the WAL that have been checkpointed after the checkpoint +** completes into mem[P3+2]. However on an error, mem[P3+1] and +** mem[P3+2] are initialized to -1. +*/ +case OP_Checkpoint: { + int i; /* Loop counter */ + int aRes[3]; /* Results */ + Mem *pMem; /* Write results here */ + + assert( p->readOnly==0 ); + aRes[0] = 0; + aRes[1] = aRes[2] = -1; + assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE + || pOp->p2==SQLITE_CHECKPOINT_FULL + || pOp->p2==SQLITE_CHECKPOINT_RESTART + ); + rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); + if( rc==SQLITE_BUSY ){ + rc = SQLITE_OK; + aRes[0] = 1; + } + for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){ + sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]); + } + break; +}; +#endif + +#ifndef SQLITE_OMIT_PRAGMA +/* Opcode: JournalMode P1 P2 P3 * P5 +** +** Change the journal mode of database P1 to P3. P3 must be one of the +** PAGER_JOURNALMODE_XXX values. If changing between the various rollback +** modes (delete, truncate, persist, off and memory), this is a simple +** operation. No IO is required. +** +** If changing into or out of WAL mode the procedure is more complicated. +** +** Write a string containing the final journal-mode to register P2. +*/ +case OP_JournalMode: { /* out2-prerelease */ + Btree *pBt; /* Btree to change journal mode of */ + Pager *pPager; /* Pager associated with pBt */ + int eNew; /* New journal mode */ + int eOld; /* The old journal mode */ +#ifndef SQLITE_OMIT_WAL + const char *zFilename; /* Name of database file for pPager */ +#endif + + eNew = pOp->p3; + assert( eNew==PAGER_JOURNALMODE_DELETE + || eNew==PAGER_JOURNALMODE_TRUNCATE + || eNew==PAGER_JOURNALMODE_PERSIST + || eNew==PAGER_JOURNALMODE_OFF + || eNew==PAGER_JOURNALMODE_MEMORY + || eNew==PAGER_JOURNALMODE_WAL + || eNew==PAGER_JOURNALMODE_QUERY + ); + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( p->readOnly==0 ); + + pBt = db->aDb[pOp->p1].pBt; + pPager = sqlite3BtreePager(pBt); + eOld = sqlite3PagerGetJournalMode(pPager); + if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld; + if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld; + +#ifndef SQLITE_OMIT_WAL + zFilename = sqlite3PagerFilename(pPager, 1); + + /* Do not allow a transition to journal_mode=WAL for a database + ** in temporary storage or if the VFS does not support shared memory + */ + if( eNew==PAGER_JOURNALMODE_WAL + && (sqlite3Strlen30(zFilename)==0 /* Temp file */ + || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */ + ){ + eNew = eOld; + } + + if( (eNew!=eOld) + && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL) + ){ + if( !db->autoCommit || db->nVdbeRead>1 ){ + rc = SQLITE_ERROR; + sqlite3SetString(&p->zErrMsg, db, + "cannot change %s wal mode from within a transaction", + (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of") + ); + break; + }else{ + + if( eOld==PAGER_JOURNALMODE_WAL ){ + /* If leaving WAL mode, close the log file. If successful, the call + ** to PagerCloseWal() checkpoints and deletes the write-ahead-log + ** file. An EXCLUSIVE lock may still be held on the database file + ** after a successful return. + */ + rc = sqlite3PagerCloseWal(pPager); + if( rc==SQLITE_OK ){ + sqlite3PagerSetJournalMode(pPager, eNew); + } + }else if( eOld==PAGER_JOURNALMODE_MEMORY ){ + /* Cannot transition directly from MEMORY to WAL. Use mode OFF + ** as an intermediate */ + sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF); + } + + /* Open a transaction on the database file. Regardless of the journal + ** mode, this transaction always uses a rollback journal. + */ + assert( sqlite3BtreeIsInTrans(pBt)==0 ); + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1)); + } + } + } +#endif /* ifndef SQLITE_OMIT_WAL */ + + if( rc ){ + eNew = eOld; + } + eNew = sqlite3PagerSetJournalMode(pPager, eNew); + + pOut = &aMem[pOp->p2]; + pOut->flags = MEM_Str|MEM_Static|MEM_Term; + pOut->z = (char *)sqlite3JournalModename(eNew); + pOut->n = sqlite3Strlen30(pOut->z); + pOut->enc = SQLITE_UTF8; + sqlite3VdbeChangeEncoding(pOut, encoding); + break; +}; +#endif /* SQLITE_OMIT_PRAGMA */ + +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) +/* Opcode: Vacuum * * * * * +** +** Vacuum the entire database. This opcode will cause other virtual +** machines to be created and run. It may not be called from within +** a transaction. +*/ +case OP_Vacuum: { + assert( p->readOnly==0 ); + rc = sqlite3RunVacuum(&p->zErrMsg, db); + break; +} +#endif + +#if !defined(SQLITE_OMIT_AUTOVACUUM) +/* Opcode: IncrVacuum P1 P2 * * * +** +** Perform a single step of the incremental vacuum procedure on +** the P1 database. If the vacuum has finished, jump to instruction +** P2. Otherwise, fall through to the next instruction. +*/ +case OP_IncrVacuum: { /* jump */ + Btree *pBt; + + assert( pOp->p1>=0 && pOp->p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<p1))!=0 ); + assert( p->readOnly==0 ); + pBt = db->aDb[pOp->p1].pBt; + rc = sqlite3BtreeIncrVacuum(pBt); + if( rc==SQLITE_DONE ){ + pc = pOp->p2 - 1; + rc = SQLITE_OK; + } + break; +} +#endif + +/* Opcode: Expire P1 * * * * +** +** Cause precompiled statements to become expired. An expired statement +** fails with an error code of SQLITE_SCHEMA if it is ever executed +** (via sqlite3_step()). +** +** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, +** then only the currently executing statement is affected. +*/ +case OP_Expire: { + if( !pOp->p1 ){ + sqlite3ExpirePreparedStatements(db); + }else{ + p->expired = 1; + } + break; +} + +#ifndef SQLITE_OMIT_SHARED_CACHE +/* Opcode: TableLock P1 P2 P3 P4 * +** +** Obtain a lock on a particular table. This instruction is only used when +** the shared-cache feature is enabled. +** +** P1 is the index of the database in sqlite3.aDb[] of the database +** on which the lock is acquired. A readlock is obtained if P3==0 or +** a write lock if P3==1. +** +** P2 contains the root-page of the table to lock. +** +** P4 contains a pointer to the name of the table being locked. This is only +** used to generate an error message if the lock cannot be obtained. +*/ +case OP_TableLock: { + u8 isWriteLock = (u8)pOp->p3; + if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){ + int p1 = pOp->p1; + assert( p1>=0 && p1nDb ); + assert( (p->btreeMask & (((yDbMask)1)<aDb[p1].pBt, pOp->p2, isWriteLock); + if( (rc&0xFF)==SQLITE_LOCKED ){ + const char *z = pOp->p4.z; + sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z); + } + } + break; +} +#endif /* SQLITE_OMIT_SHARED_CACHE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VBegin * * * P4 * +** +** P4 may be a pointer to an sqlite3_vtab structure. If so, call the +** xBegin method for that table. +** +** Also, whether or not P4 is set, check that this is not being called from +** within a callback to a virtual table xSync() method. If it is, the error +** code will be set to SQLITE_LOCKED. +*/ +case OP_VBegin: { + VTable *pVTab; + pVTab = pOp->p4.pVtab; + rc = sqlite3VtabBegin(db, pVTab); + if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab); + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VCreate P1 * * P4 * +** +** P4 is the name of a virtual table in database P1. Call the xCreate method +** for that table. +*/ +case OP_VCreate: { + rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg); + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VDestroy P1 * * P4 * +** +** P4 is the name of a virtual table in database P1. Call the xDestroy method +** of that table. +*/ +case OP_VDestroy: { + p->inVtabMethod = 2; + rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); + p->inVtabMethod = 0; + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VOpen P1 * * P4 * +** +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. +** P1 is a cursor number. This opcode opens a cursor to the virtual +** table and stores that cursor in P1. +*/ +case OP_VOpen: { + VdbeCursor *pCur; + sqlite3_vtab_cursor *pVtabCursor; + sqlite3_vtab *pVtab; + sqlite3_module *pModule; + + assert( p->bIsReader ); + pCur = 0; + pVtabCursor = 0; + pVtab = pOp->p4.pVtab->pVtab; + pModule = (sqlite3_module *)pVtab->pModule; + assert(pVtab && pModule); + rc = pModule->xOpen(pVtab, &pVtabCursor); + sqlite3VtabImportErrmsg(p, pVtab); + if( SQLITE_OK==rc ){ + /* Initialize sqlite3_vtab_cursor base class */ + pVtabCursor->pVtab = pVtab; + + /* Initialize vdbe cursor object */ + pCur = allocateCursor(p, pOp->p1, 0, -1, 0); + if( pCur ){ + pCur->pVtabCursor = pVtabCursor; + pCur->pModule = pVtabCursor->pVtab->pModule; + }else{ + db->mallocFailed = 1; + pModule->xClose(pVtabCursor); + } + } + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VFilter P1 P2 P3 P4 * +** +** P1 is a cursor opened using VOpen. P2 is an address to jump to if +** the filtered result set is empty. +** +** P4 is either NULL or a string that was generated by the xBestIndex +** method of the module. The interpretation of the P4 string is left +** to the module implementation. +** +** This opcode invokes the xFilter method on the virtual table specified +** by P1. The integer query plan parameter to xFilter is stored in register +** P3. Register P3+1 stores the argc parameter to be passed to the +** xFilter method. Registers P3+2..P3+1+argc are the argc +** additional parameters which are passed to +** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter. +** +** A jump is made to P2 if the result set after filtering would be empty. +*/ +case OP_VFilter: { /* jump */ + int nArg; + int iQuery; + const sqlite3_module *pModule; + Mem *pQuery; + Mem *pArgc; + sqlite3_vtab_cursor *pVtabCursor; + sqlite3_vtab *pVtab; + VdbeCursor *pCur; + int res; + int i; + Mem **apArg; + + pQuery = &aMem[pOp->p3]; + pArgc = &pQuery[1]; + pCur = p->apCsr[pOp->p1]; + assert( memIsValid(pQuery) ); + REGISTER_TRACE(pOp->p3, pQuery); + assert( pCur->pVtabCursor ); + pVtabCursor = pCur->pVtabCursor; + pVtab = pVtabCursor->pVtab; + pModule = pVtab->pModule; + + /* Grab the index number and argc parameters */ + assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int ); + nArg = (int)pArgc->u.i; + iQuery = (int)pQuery->u.i; + + /* Invoke the xFilter method */ + { + res = 0; + apArg = p->apArg; + for(i = 0; iinVtabMethod = 1; + rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg); + p->inVtabMethod = 0; + sqlite3VtabImportErrmsg(p, pVtab); + if( rc==SQLITE_OK ){ + res = pModule->xEof(pVtabCursor); + } + + if( res ){ + pc = pOp->p2 - 1; + } + } + pCur->nullRow = 0; + + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VColumn P1 P2 P3 * * +** +** Store the value of the P2-th column of +** the row of the virtual-table that the +** P1 cursor is pointing to into register P3. +*/ +case OP_VColumn: { + sqlite3_vtab *pVtab; + const sqlite3_module *pModule; + Mem *pDest; + sqlite3_context sContext; + + VdbeCursor *pCur = p->apCsr[pOp->p1]; + assert( pCur->pVtabCursor ); + assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) ); + pDest = &aMem[pOp->p3]; + memAboutToChange(p, pDest); + if( pCur->nullRow ){ + sqlite3VdbeMemSetNull(pDest); + break; + } + pVtab = pCur->pVtabCursor->pVtab; + pModule = pVtab->pModule; + assert( pModule->xColumn ); + memset(&sContext, 0, sizeof(sContext)); + + /* The output cell may already have a buffer allocated. Move + ** the current contents to sContext.s so in case the user-function + ** can use the already allocated buffer instead of allocating a + ** new one. + */ + sqlite3VdbeMemMove(&sContext.s, pDest); + MemSetTypeFlag(&sContext.s, MEM_Null); + + rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2); + sqlite3VtabImportErrmsg(p, pVtab); + if( sContext.isError ){ + rc = sContext.isError; + } + + /* Copy the result of the function to the P3 register. We + ** do this regardless of whether or not an error occurred to ensure any + ** dynamic allocation in sContext.s (a Mem struct) is released. + */ + sqlite3VdbeChangeEncoding(&sContext.s, encoding); + sqlite3VdbeMemMove(pDest, &sContext.s); + REGISTER_TRACE(pOp->p3, pDest); + UPDATE_MAX_BLOBSIZE(pDest); + + if( sqlite3VdbeMemTooBig(pDest) ){ + goto too_big; + } + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VNext P1 P2 * * * +** +** Advance virtual table P1 to the next row in its result set and +** jump to instruction P2. Or, if the virtual table has reached +** the end of its result set, then fall through to the next instruction. +*/ +case OP_VNext: { /* jump */ + sqlite3_vtab *pVtab; + const sqlite3_module *pModule; + int res; + VdbeCursor *pCur; + + res = 0; + pCur = p->apCsr[pOp->p1]; + assert( pCur->pVtabCursor ); + if( pCur->nullRow ){ + break; + } + pVtab = pCur->pVtabCursor->pVtab; + pModule = pVtab->pModule; + assert( pModule->xNext ); + + /* Invoke the xNext() method of the module. There is no way for the + ** underlying implementation to return an error if one occurs during + ** xNext(). Instead, if an error occurs, true is returned (indicating that + ** data is available) and the error code returned when xColumn or + ** some other method is next invoked on the save virtual table cursor. + */ + p->inVtabMethod = 1; + rc = pModule->xNext(pCur->pVtabCursor); + p->inVtabMethod = 0; + sqlite3VtabImportErrmsg(p, pVtab); + if( rc==SQLITE_OK ){ + res = pModule->xEof(pCur->pVtabCursor); + } + + if( !res ){ + /* If there is data, jump to P2 */ + pc = pOp->p2 - 1; + } + goto check_for_interrupt; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VRename P1 * * P4 * +** +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. +** This opcode invokes the corresponding xRename method. The value +** in register P1 is passed as the zName argument to the xRename method. +*/ +case OP_VRename: { + sqlite3_vtab *pVtab; + Mem *pName; + + pVtab = pOp->p4.pVtab->pVtab; + pName = &aMem[pOp->p1]; + assert( pVtab->pModule->xRename ); + assert( memIsValid(pName) ); + assert( p->readOnly==0 ); + REGISTER_TRACE(pOp->p1, pName); + assert( pName->flags & MEM_Str ); + testcase( pName->enc==SQLITE_UTF8 ); + testcase( pName->enc==SQLITE_UTF16BE ); + testcase( pName->enc==SQLITE_UTF16LE ); + rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8); + if( rc==SQLITE_OK ){ + rc = pVtab->pModule->xRename(pVtab, pName->z); + sqlite3VtabImportErrmsg(p, pVtab); + p->expired = 0; + } + break; +} +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* Opcode: VUpdate P1 P2 P3 P4 * +** +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. +** This opcode invokes the corresponding xUpdate method. P2 values +** are contiguous memory cells starting at P3 to pass to the xUpdate +** invocation. The value in register (P3+P2-1) corresponds to the +** p2th element of the argv array passed to xUpdate. +** +** The xUpdate method will do a DELETE or an INSERT or both. +** The argv[0] element (which corresponds to memory cell P3) +** is the rowid of a row to delete. If argv[0] is NULL then no +** deletion occurs. The argv[1] element is the rowid of the new +** row. This can be NULL to have the virtual table select the new +** rowid for itself. The subsequent elements in the array are +** the values of columns in the new row. +** +** If P2==1 then no insert is performed. argv[0] is the rowid of +** a row to delete. +** +** P1 is a boolean flag. If it is set to true and the xUpdate call +** is successful, then the value returned by sqlite3_last_insert_rowid() +** is set to the value of the rowid for the row just inserted. +*/ +case OP_VUpdate: { + sqlite3_vtab *pVtab; + sqlite3_module *pModule; + int nArg; + int i; + sqlite_int64 rowid; + Mem **apArg; + Mem *pX; + + assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback + || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace + ); + assert( p->readOnly==0 ); + pVtab = pOp->p4.pVtab->pVtab; + pModule = (sqlite3_module *)pVtab->pModule; + nArg = pOp->p2; + assert( pOp->p4type==P4_VTAB ); + if( ALWAYS(pModule->xUpdate) ){ + u8 vtabOnConflict = db->vtabOnConflict; + apArg = p->apArg; + pX = &aMem[pOp->p3]; + for(i=0; ivtabOnConflict = pOp->p5; + rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid); + db->vtabOnConflict = vtabOnConflict; + sqlite3VtabImportErrmsg(p, pVtab); + if( rc==SQLITE_OK && pOp->p1 ){ + assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) ); + db->lastRowid = lastRowid = rowid; + } + if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){ + if( pOp->p5==OE_Ignore ){ + rc = SQLITE_OK; + }else{ + p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5); + } + }else{ + p->nChange++; + } + } + break; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* Opcode: Pagecount P1 P2 * * * +** +** Write the current number of pages in database P1 to memory cell P2. +*/ +case OP_Pagecount: { /* out2-prerelease */ + pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt); + break; +} +#endif + + +#ifndef SQLITE_OMIT_PAGER_PRAGMAS +/* Opcode: MaxPgcnt P1 P2 P3 * * +** +** Try to set the maximum page count for database P1 to the value in P3. +** Do not let the maximum page count fall below the current page count and +** do not change the maximum page count value if P3==0. +** +** Store the maximum page count after the change in register P2. +*/ +case OP_MaxPgcnt: { /* out2-prerelease */ + unsigned int newMax; + Btree *pBt; + + pBt = db->aDb[pOp->p1].pBt; + newMax = 0; + if( pOp->p3 ){ + newMax = sqlite3BtreeLastPage(pBt); + if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3; + } + pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax); + break; +} +#endif + + +#ifndef SQLITE_OMIT_TRACE +/* Opcode: Trace * * * P4 * +** +** If tracing is enabled (by the sqlite3_trace()) interface, then +** the UTF-8 string contained in P4 is emitted on the trace callback. +*/ +case OP_Trace: { + char *zTrace; + char *z; + + if( db->xTrace + && !p->doingRerun + && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 + ){ + z = sqlite3VdbeExpandSql(p, zTrace); + db->xTrace(db->pTraceArg, z); + sqlite3DbFree(db, z); + } +#ifdef SQLITE_DEBUG + if( (db->flags & SQLITE_SqlTrace)!=0 + && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 + ){ + sqlite3DebugPrintf("SQL-trace: %s\n", zTrace); + } +#endif /* SQLITE_DEBUG */ + break; +} +#endif + + +/* Opcode: Noop * * * * * +** +** Do nothing. This instruction is often useful as a jump +** destination. +*/ +/* +** The magic Explain opcode are only inserted when explain==2 (which +** is to say when the EXPLAIN QUERY PLAN syntax is used.) +** This opcode records information from the optimizer. It is the +** the same as a no-op. This opcodesnever appears in a real VM program. +*/ +default: { /* This is really OP_Noop and OP_Explain */ + assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain ); + break; +} + +/***************************************************************************** +** The cases of the switch statement above this line should all be indented +** by 6 spaces. But the left-most 6 spaces have been removed to improve the +** readability. From this point on down, the normal indentation rules are +** restored. +*****************************************************************************/ + } + +#ifdef VDBE_PROFILE + { + u64 elapsed = sqlite3Hwtime() - start; + pOp->cycles += elapsed; + pOp->cnt++; +#if 0 + fprintf(stdout, "%10llu ", elapsed); + sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]); +#endif + } +#endif + + /* The following code adds nothing to the actual functionality + ** of the program. It is only here for testing and debugging. + ** On the other hand, it does burn CPU cycles every time through + ** the evaluator loop. So we can leave it out when NDEBUG is defined. + */ +#ifndef NDEBUG + assert( pc>=-1 && pcnOp ); + +#ifdef SQLITE_DEBUG + if( p->trace ){ + if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc); + if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){ + registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]); + } + if( pOp->opflags & OPFLG_OUT3 ){ + registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]); + } + } +#endif /* SQLITE_DEBUG */ +#endif /* NDEBUG */ + } /* The end of the for(;;) loop the loops through opcodes */ + + /* If we reach this point, it means that execution is finished with + ** an error of some kind. + */ +vdbe_error_halt: + assert( rc ); + p->rc = rc; + testcase( sqlite3GlobalConfig.xLog!=0 ); + sqlite3_log(rc, "statement aborts at %d: [%s] %s", + pc, p->zSql, p->zErrMsg); + sqlite3VdbeHalt(p); + if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1; + rc = SQLITE_ERROR; + if( resetSchemaOnFault>0 ){ + sqlite3ResetOneSchema(db, resetSchemaOnFault-1); + } + + /* This is the only way out of this procedure. We have to + ** release the mutexes on btrees that were acquired at the + ** top. */ +vdbe_return: + db->lastRowid = lastRowid; + testcase( nVmStep>0 ); + p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep; + sqlite3VdbeLeave(p); + return rc; + + /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH + ** is encountered. + */ +too_big: + sqlite3SetString(&p->zErrMsg, db, "string or blob too big"); + rc = SQLITE_TOOBIG; + goto vdbe_error_halt; + + /* Jump to here if a malloc() fails. + */ +no_mem: + db->mallocFailed = 1; + sqlite3SetString(&p->zErrMsg, db, "out of memory"); + rc = SQLITE_NOMEM; + goto vdbe_error_halt; + + /* Jump to here for any other kind of fatal error. The "rc" variable + ** should hold the error number. + */ +abort_due_to_error: + assert( p->zErrMsg==0 ); + if( db->mallocFailed ) rc = SQLITE_NOMEM; + if( rc!=SQLITE_IOERR_NOMEM ){ + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc)); + } + goto vdbe_error_halt; + + /* Jump to here if the sqlite3_interrupt() API sets the interrupt + ** flag. + */ +abort_due_to_interrupt: + assert( db->u1.isInterrupted ); + rc = SQLITE_INTERRUPT; + p->rc = rc; + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc)); + goto vdbe_error_halt; +} diff --git a/components/external/SQLite-3.8.1/src/vdbe.h b/components/external/SQLite-3.8.1/src/vdbe.h new file mode 100644 index 0000000000000000000000000000000000000000..a6cc91544400565d79a0f0bf8d54303b48e5b0e2 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vdbe.h @@ -0,0 +1,232 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Header file for the Virtual DataBase Engine (VDBE) +** +** This header defines the interface to the virtual database engine +** or VDBE. The VDBE implements an abstract machine that runs a +** simple program to access and modify the underlying database. +*/ +#ifndef _SQLITE_VDBE_H_ +#define _SQLITE_VDBE_H_ +#include + +/* +** A single VDBE is an opaque structure named "Vdbe". Only routines +** in the source file sqliteVdbe.c are allowed to see the insides +** of this structure. +*/ +typedef struct Vdbe Vdbe; + +/* +** The names of the following types declared in vdbeInt.h are required +** for the VdbeOp definition. +*/ +typedef struct Mem Mem; +typedef struct SubProgram SubProgram; + +/* +** A single instruction of the virtual machine has an opcode +** and as many as three operands. The instruction is recorded +** as an instance of the following structure: +*/ +struct VdbeOp { + u8 opcode; /* What operation to perform */ + signed char p4type; /* One of the P4_xxx constants for p4 */ + u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */ + u8 p5; /* Fifth parameter is an unsigned character */ + int p1; /* First operand */ + int p2; /* Second parameter (often the jump destination) */ + int p3; /* The third parameter */ + union { /* fourth parameter */ + int i; /* Integer value if p4type==P4_INT32 */ + void *p; /* Generic pointer */ + char *z; /* Pointer to data for string (char array) types */ + i64 *pI64; /* Used when p4type is P4_INT64 */ + double *pReal; /* Used when p4type is P4_REAL */ + FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ + CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ + Mem *pMem; /* Used when p4type is P4_MEM */ + VTable *pVtab; /* Used when p4type is P4_VTAB */ + KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ + int *ai; /* Used when p4type is P4_INTARRAY */ + SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ + int (*xAdvance)(BtCursor *, int *); + } p4; +#ifdef SQLITE_DEBUG + char *zComment; /* Comment to improve readability */ +#endif +#ifdef VDBE_PROFILE + int cnt; /* Number of times this instruction was executed */ + u64 cycles; /* Total time spent executing this instruction */ +#endif +}; +typedef struct VdbeOp VdbeOp; + + +/* +** A sub-routine used to implement a trigger program. +*/ +struct SubProgram { + VdbeOp *aOp; /* Array of opcodes for sub-program */ + int nOp; /* Elements in aOp[] */ + int nMem; /* Number of memory cells required */ + int nCsr; /* Number of cursors required */ + int nOnce; /* Number of OP_Once instructions */ + void *token; /* id that may be used to recursive triggers */ + SubProgram *pNext; /* Next sub-program already visited */ +}; + +/* +** A smaller version of VdbeOp used for the VdbeAddOpList() function because +** it takes up less space. +*/ +struct VdbeOpList { + u8 opcode; /* What operation to perform */ + signed char p1; /* First operand */ + signed char p2; /* Second parameter (often the jump destination) */ + signed char p3; /* Third parameter */ +}; +typedef struct VdbeOpList VdbeOpList; + +/* +** Allowed values of VdbeOp.p4type +*/ +#define P4_NOTUSED 0 /* The P4 parameter is not used */ +#define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ +#define P4_STATIC (-2) /* Pointer to a static string */ +#define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ +#define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ +#define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ +#define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ +#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */ +#define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ +#define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ +#define P4_REAL (-12) /* P4 is a 64-bit floating point value */ +#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ +#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ +#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ +#define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ +#define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */ + +/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure +** is made. That copy is freed when the Vdbe is finalized. But if the +** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still +** gets freed when the Vdbe is finalized so it still should be obtained +** from a single sqliteMalloc(). But no copy is made and the calling +** function should *not* try to free the KeyInfo. +*/ +#define P4_KEYINFO_HANDOFF (-16) +#define P4_KEYINFO_STATIC (-17) + +/* +** The Vdbe.aColName array contains 5n Mem structures, where n is the +** number of columns of data returned by the statement. +*/ +#define COLNAME_NAME 0 +#define COLNAME_DECLTYPE 1 +#define COLNAME_DATABASE 2 +#define COLNAME_TABLE 3 +#define COLNAME_COLUMN 4 +#ifdef SQLITE_ENABLE_COLUMN_METADATA +# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ +#else +# ifdef SQLITE_OMIT_DECLTYPE +# define COLNAME_N 1 /* Store only the name */ +# else +# define COLNAME_N 2 /* Store the name and decltype */ +# endif +#endif + +/* +** The following macro converts a relative address in the p2 field +** of a VdbeOp structure into a negative number so that +** sqlite3VdbeAddOpList() knows that the address is relative. Calling +** the macro again restores the address. +*/ +#define ADDR(X) (-1-(X)) + +/* +** The makefile scans the vdbe.c source file and creates the "opcodes.h" +** header file that defines a number for each opcode used by the VDBE. +*/ +#include "opcodes.h" + +/* +** Prototypes for the VDBE interface. See comments on the implementation +** for a description of what each of these routines does. +*/ +Vdbe *sqlite3VdbeCreate(sqlite3*); +int sqlite3VdbeAddOp0(Vdbe*,int); +int sqlite3VdbeAddOp1(Vdbe*,int,int); +int sqlite3VdbeAddOp2(Vdbe*,int,int,int); +int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); +int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); +int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); +int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); +void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); +void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1); +void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2); +void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3); +void sqlite3VdbeChangeP5(Vdbe*, u8 P5); +void sqlite3VdbeJumpHere(Vdbe*, int addr); +void sqlite3VdbeChangeToNoop(Vdbe*, int addr); +void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); +void sqlite3VdbeUsesBtree(Vdbe*, int); +VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); +int sqlite3VdbeMakeLabel(Vdbe*); +void sqlite3VdbeRunOnlyOnce(Vdbe*); +void sqlite3VdbeDelete(Vdbe*); +void sqlite3VdbeClearObject(sqlite3*,Vdbe*); +void sqlite3VdbeMakeReady(Vdbe*,Parse*); +int sqlite3VdbeFinalize(Vdbe*); +void sqlite3VdbeResolveLabel(Vdbe*, int); +int sqlite3VdbeCurrentAddr(Vdbe*); +#ifdef SQLITE_DEBUG + int sqlite3VdbeAssertMayAbort(Vdbe *, int); + void sqlite3VdbeTrace(Vdbe*,FILE*); +#endif +void sqlite3VdbeResetStepResult(Vdbe*); +void sqlite3VdbeRewind(Vdbe*); +int sqlite3VdbeReset(Vdbe*); +void sqlite3VdbeSetNumCols(Vdbe*,int); +int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); +void sqlite3VdbeCountChanges(Vdbe*); +sqlite3 *sqlite3VdbeDb(Vdbe*); +void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); +void sqlite3VdbeSwap(Vdbe*,Vdbe*); +VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); +sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8); +void sqlite3VdbeSetVarmask(Vdbe*, int); +#ifndef SQLITE_OMIT_TRACE + char *sqlite3VdbeExpandSql(Vdbe*, const char*); +#endif + +void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); +int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); +UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **); + +#ifndef SQLITE_OMIT_TRIGGER +void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); +#endif + + +#ifndef NDEBUG + void sqlite3VdbeComment(Vdbe*, const char*, ...); +# define VdbeComment(X) sqlite3VdbeComment X + void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); +# define VdbeNoopComment(X) sqlite3VdbeNoopComment X +#else +# define VdbeComment(X) +# define VdbeNoopComment(X) +#endif + +#endif diff --git a/components/external/SQLite-3.8.1/src/vdbeInt.h b/components/external/SQLite-3.8.1/src/vdbeInt.h new file mode 100644 index 0000000000000000000000000000000000000000..3cac04016cd27ef531908a4e031ef94e71cdae1e --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vdbeInt.h @@ -0,0 +1,486 @@ +/* +** 2003 September 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for information that is private to the +** VDBE. This information used to all be at the top of the single +** source code file "vdbe.c". When that file became too big (over +** 6000 lines long) it was split up into several smaller files and +** this header information was factored out. +*/ +#ifndef _VDBEINT_H_ +#define _VDBEINT_H_ + +/* +** The maximum number of times that a statement will try to reparse +** itself before giving up and returning SQLITE_SCHEMA. +*/ +#ifndef SQLITE_MAX_SCHEMA_RETRY +# define SQLITE_MAX_SCHEMA_RETRY 50 +#endif + +/* +** SQL is translated into a sequence of instructions to be +** executed by a virtual machine. Each instruction is an instance +** of the following structure. +*/ +typedef struct VdbeOp Op; + +/* +** Boolean values +*/ +typedef unsigned char Bool; + +/* Opaque type used by code in vdbesort.c */ +typedef struct VdbeSorter VdbeSorter; + +/* Opaque type used by the explainer */ +typedef struct Explain Explain; + +/* Elements of the linked list at Vdbe.pAuxData */ +typedef struct AuxData AuxData; + +/* +** A cursor is a pointer into a single BTree within a database file. +** The cursor can seek to a BTree entry with a particular key, or +** loop over all entries of the Btree. You can also insert new BTree +** entries or retrieve the key or data from the entry that the cursor +** is currently pointing to. +** +** Every cursor that the virtual machine has open is represented by an +** instance of the following structure. +*/ +struct VdbeCursor { + BtCursor *pCursor; /* The cursor structure of the backend */ + Btree *pBt; /* Separate file holding temporary table */ + KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */ + int iDb; /* Index of cursor database in db->aDb[] (or -1) */ + int pseudoTableReg; /* Register holding pseudotable content. */ + int nField; /* Number of fields in the header */ + Bool zeroed; /* True if zeroed out and ready for reuse */ + Bool rowidIsValid; /* True if lastRowid is valid */ + Bool atFirst; /* True if pointing to first entry */ + Bool useRandomRowid; /* Generate new record numbers semi-randomly */ + Bool nullRow; /* True if pointing to a row with no data */ + Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ + Bool isTable; /* True if a table requiring integer keys */ + Bool isIndex; /* True if an index containing keys only - no data */ + Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */ + Bool isSorter; /* True if a new-style sorter */ + Bool multiPseudo; /* Multi-register pseudo-cursor */ + sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */ + const sqlite3_module *pModule; /* Module for cursor pVtabCursor */ + i64 seqCount; /* Sequence counter */ + i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ + i64 lastRowid; /* Last rowid from a Next or NextIdx operation */ + VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */ + + /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or + ** OP_IsUnique opcode on this cursor. */ + int seekResult; + + /* Cached information about the header for the data record that the + ** cursor is currently pointing to. Only valid if cacheStatus matches + ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of + ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that + ** the cache is out of date. + ** + ** aRow might point to (ephemeral) data for the current row, or it might + ** be NULL. + */ + u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ + int payloadSize; /* Total number of bytes in the record */ + u32 *aType; /* Type values for all entries in the record */ + u32 *aOffset; /* Cached offsets to the start of each columns data */ + u8 *aRow; /* Data for the current row, if all on one page */ +}; +typedef struct VdbeCursor VdbeCursor; + +/* +** When a sub-program is executed (OP_Program), a structure of this type +** is allocated to store the current value of the program counter, as +** well as the current memory cell array and various other frame specific +** values stored in the Vdbe struct. When the sub-program is finished, +** these values are copied back to the Vdbe from the VdbeFrame structure, +** restoring the state of the VM to as it was before the sub-program +** began executing. +** +** The memory for a VdbeFrame object is allocated and managed by a memory +** cell in the parent (calling) frame. When the memory cell is deleted or +** overwritten, the VdbeFrame object is not freed immediately. Instead, it +** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame +** list is deleted when the VM is reset in VdbeHalt(). The reason for doing +** this instead of deleting the VdbeFrame immediately is to avoid recursive +** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the +** child frame are released. +** +** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is +** set to NULL if the currently executing frame is the main program. +*/ +typedef struct VdbeFrame VdbeFrame; +struct VdbeFrame { + Vdbe *v; /* VM this frame belongs to */ + VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */ + Op *aOp; /* Program instructions for parent frame */ + Mem *aMem; /* Array of memory cells for parent frame */ + u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */ + VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */ + void *token; /* Copy of SubProgram.token */ + i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ + int nCursor; /* Number of entries in apCsr */ + int pc; /* Program Counter in parent (calling) frame */ + int nOp; /* Size of aOp array */ + int nMem; /* Number of entries in aMem */ + int nOnceFlag; /* Number of entries in aOnceFlag */ + int nChildMem; /* Number of memory cells for child frame */ + int nChildCsr; /* Number of cursors for child frame */ + int nChange; /* Statement changes (Vdbe.nChanges) */ +}; + +#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))]) + +/* +** A value for VdbeCursor.cacheValid that means the cache is always invalid. +*/ +#define CACHE_STALE 0 + +/* +** Internally, the vdbe manipulates nearly all SQL values as Mem +** structures. Each Mem struct may cache multiple representations (string, +** integer etc.) of the same value. +*/ +struct Mem { + sqlite3 *db; /* The associated database connection */ + char *z; /* String or BLOB value */ + double r; /* Real value */ + union { + i64 i; /* Integer value used when MEM_Int is set in flags */ + int nZero; /* Used when bit MEM_Zero is set in flags */ + FuncDef *pDef; /* Used only when flags==MEM_Agg */ + RowSet *pRowSet; /* Used only when flags==MEM_RowSet */ + VdbeFrame *pFrame; /* Used when flags==MEM_Frame */ + } u; + int n; /* Number of characters in string value, excluding '\0' */ + u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ + u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */ + u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ +#ifdef SQLITE_DEBUG + Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */ + void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */ +#endif + void (*xDel)(void *); /* If not null, call this function to delete Mem.z */ + char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */ +}; + +/* One or more of the following flags are set to indicate the validOK +** representations of the value stored in the Mem struct. +** +** If the MEM_Null flag is set, then the value is an SQL NULL value. +** No other flags may be set in this case. +** +** If the MEM_Str flag is set then Mem.z points at a string representation. +** Usually this is encoded in the same unicode encoding as the main +** database (see below for exceptions). If the MEM_Term flag is also +** set, then the string is nul terminated. The MEM_Int and MEM_Real +** flags may coexist with the MEM_Str flag. +*/ +#define MEM_Null 0x0001 /* Value is NULL */ +#define MEM_Str 0x0002 /* Value is a string */ +#define MEM_Int 0x0004 /* Value is an integer */ +#define MEM_Real 0x0008 /* Value is a real number */ +#define MEM_Blob 0x0010 /* Value is a BLOB */ +#define MEM_RowSet 0x0020 /* Value is a RowSet object */ +#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */ +#define MEM_Invalid 0x0080 /* Value is undefined */ +#define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */ +#define MEM_TypeMask 0x01ff /* Mask of type bits */ + + +/* Whenever Mem contains a valid string or blob representation, one of +** the following flags must be set to determine the memory management +** policy for Mem.z. The MEM_Term flag tells us whether or not the +** string is \000 or \u0000 terminated +*/ +#define MEM_Term 0x0200 /* String rep is nul terminated */ +#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */ +#define MEM_Static 0x0800 /* Mem.z points to a static string */ +#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */ +#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */ +#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */ +#ifdef SQLITE_OMIT_INCRBLOB + #undef MEM_Zero + #define MEM_Zero 0x0000 +#endif + +/* +** Clear any existing type flags from a Mem and replace them with f +*/ +#define MemSetTypeFlag(p, f) \ + ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f) + +/* +** Return true if a memory cell is not marked as invalid. This macro +** is for use inside assert() statements only. +*/ +#ifdef SQLITE_DEBUG +#define memIsValid(M) ((M)->flags & MEM_Invalid)==0 +#endif + +/* +** Each auxilliary data pointer stored by a user defined function +** implementation calling sqlite3_set_auxdata() is stored in an instance +** of this structure. All such structures associated with a single VM +** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed +** when the VM is halted (if not before). +*/ +struct AuxData { + int iOp; /* Instruction number of OP_Function opcode */ + int iArg; /* Index of function argument. */ + void *pAux; /* Aux data pointer */ + void (*xDelete)(void *); /* Destructor for the aux data */ + AuxData *pNext; /* Next element in list */ +}; + +/* +** The "context" argument for a installable function. A pointer to an +** instance of this structure is the first argument to the routines used +** implement the SQL functions. +** +** There is a typedef for this structure in sqlite.h. So all routines, +** even the public interface to SQLite, can use a pointer to this structure. +** But this file is the only place where the internal details of this +** structure are known. +** +** This structure is defined inside of vdbeInt.h because it uses substructures +** (Mem) which are only defined there. +*/ +struct sqlite3_context { + FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */ + Mem s; /* The return value is stored here */ + Mem *pMem; /* Memory cell used to store aggregate context */ + CollSeq *pColl; /* Collating sequence */ + Vdbe *pVdbe; /* The VM that owns this context */ + int iOp; /* Instruction number of OP_Function */ + int isError; /* Error code returned by the function. */ + u8 skipFlag; /* Skip skip accumulator loading if true */ + u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */ +}; + +/* +** An Explain object accumulates indented output which is helpful +** in describing recursive data structures. +*/ +struct Explain { + Vdbe *pVdbe; /* Attach the explanation to this Vdbe */ + StrAccum str; /* The string being accumulated */ + int nIndent; /* Number of elements in aIndent */ + u16 aIndent[100]; /* Levels of indentation */ + char zBase[100]; /* Initial space */ +}; + +/* A bitfield type for use inside of structures. Always follow with :N where +** N is the number of bits. +*/ +typedef unsigned bft; /* Bit Field Type */ + +/* +** An instance of the virtual machine. This structure contains the complete +** state of the virtual machine. +** +** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare() +** is really a pointer to an instance of this structure. +** +** The Vdbe.inVtabMethod variable is set to non-zero for the duration of +** any virtual table method invocations made by the vdbe program. It is +** set to 2 for xDestroy method calls and 1 for all other methods. This +** variable is used for two purposes: to allow xDestroy methods to execute +** "DROP TABLE" statements and to prevent some nasty side effects of +** malloc failure when SQLite is invoked recursively by a virtual table +** method function. +*/ +struct Vdbe { + sqlite3 *db; /* The database connection that owns this statement */ + Op *aOp; /* Space to hold the virtual machine's program */ + Mem *aMem; /* The memory locations */ + Mem **apArg; /* Arguments to currently executing user function */ + Mem *aColName; /* Column names to return */ + Mem *pResultSet; /* Pointer to an array of results */ + int nMem; /* Number of memory locations currently allocated */ + int nOp; /* Number of instructions in the program */ + int nOpAlloc; /* Number of slots allocated for aOp[] */ + int nLabel; /* Number of labels used */ + int *aLabel; /* Space to hold the labels */ + u16 nResColumn; /* Number of columns in one row of the result set */ + int nCursor; /* Number of slots in apCsr[] */ + u32 magic; /* Magic number for sanity checking */ + char *zErrMsg; /* Error message written here */ + Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */ + VdbeCursor **apCsr; /* One element of this array for each open cursor */ + Mem *aVar; /* Values for the OP_Variable opcode. */ + char **azVar; /* Name of variables */ + ynVar nVar; /* Number of entries in aVar[] */ + ynVar nzVar; /* Number of entries in azVar[] */ + u32 cacheCtr; /* VdbeCursor row cache generation counter */ + int pc; /* The program counter */ + int rc; /* Value to return */ + u8 errorAction; /* Recovery action to do in case of an error */ + u8 minWriteFileFormat; /* Minimum file format for writable database files */ + bft explain:2; /* True if EXPLAIN present on SQL command */ + bft inVtabMethod:2; /* See comments above */ + bft changeCntOn:1; /* True to update the change-counter */ + bft expired:1; /* True if the VM needs to be recompiled */ + bft runOnlyOnce:1; /* Automatically expire on reset */ + bft usesStmtJournal:1; /* True if uses a statement journal */ + bft readOnly:1; /* True for statements that do not write */ + bft bIsReader:1; /* True for statements that read */ + bft isPrepareV2:1; /* True if prepared with prepare_v2() */ + bft doingRerun:1; /* True if rerunning after an auto-reprepare */ + int nChange; /* Number of db changes made since last reset */ + yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */ + yDbMask lockMask; /* Subset of btreeMask that requires a lock */ + int iStatement; /* Statement number (or 0 if has not opened stmt) */ + u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */ +#ifndef SQLITE_OMIT_TRACE + i64 startTime; /* Time when query started - used for profiling */ +#endif + i64 iCurrentTime; /* Value of julianday('now') for this statement */ + i64 nFkConstraint; /* Number of imm. FK constraints this VM */ + i64 nStmtDefCons; /* Number of def. constraints when stmt started */ + i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */ + char *zSql; /* Text of the SQL statement that generated this */ + void *pFree; /* Free this when deleting the vdbe */ +#ifdef SQLITE_DEBUG + FILE *trace; /* Write an execution trace here, if not NULL */ +#endif +#ifdef SQLITE_ENABLE_TREE_EXPLAIN + Explain *pExplain; /* The explainer */ + char *zExplain; /* Explanation of data structures */ +#endif + VdbeFrame *pFrame; /* Parent frame */ + VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */ + int nFrame; /* Number of frames in pFrame list */ + u32 expmask; /* Binding to these vars invalidates VM */ + SubProgram *pProgram; /* Linked list of all sub-programs used by VM */ + int nOnceFlag; /* Size of array aOnceFlag[] */ + u8 *aOnceFlag; /* Flags for OP_Once */ + AuxData *pAuxData; /* Linked list of auxdata allocations */ +}; + +/* +** The following are allowed values for Vdbe.magic +*/ +#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */ +#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */ +#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */ +#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */ + +/* +** Function prototypes +*/ +void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); +void sqliteVdbePopStack(Vdbe*,int); +int sqlite3VdbeCursorMoveto(VdbeCursor*); +#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) +void sqlite3VdbePrintOp(FILE*, int, Op*); +#endif +u32 sqlite3VdbeSerialTypeLen(u32); +u32 sqlite3VdbeSerialType(Mem*, int); +u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int); +u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); +void sqlite3VdbeDeleteAuxData(Vdbe*, int, int); + +int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); +int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*); +int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *); +int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); +int sqlite3VdbeExec(Vdbe*); +int sqlite3VdbeList(Vdbe*); +int sqlite3VdbeHalt(Vdbe*); +int sqlite3VdbeChangeEncoding(Mem *, int); +int sqlite3VdbeMemTooBig(Mem*); +int sqlite3VdbeMemCopy(Mem*, const Mem*); +void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); +void sqlite3VdbeMemMove(Mem*, Mem*); +int sqlite3VdbeMemNulTerminate(Mem*); +int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); +void sqlite3VdbeMemSetInt64(Mem*, i64); +#ifdef SQLITE_OMIT_FLOATING_POINT +# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 +#else + void sqlite3VdbeMemSetDouble(Mem*, double); +#endif +void sqlite3VdbeMemSetNull(Mem*); +void sqlite3VdbeMemSetZeroBlob(Mem*,int); +void sqlite3VdbeMemSetRowSet(Mem*); +int sqlite3VdbeMemMakeWriteable(Mem*); +int sqlite3VdbeMemStringify(Mem*, int); +i64 sqlite3VdbeIntValue(Mem*); +int sqlite3VdbeMemIntegerify(Mem*); +double sqlite3VdbeRealValue(Mem*); +void sqlite3VdbeIntegerAffinity(Mem*); +int sqlite3VdbeMemRealify(Mem*); +int sqlite3VdbeMemNumerify(Mem*); +int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*); +void sqlite3VdbeMemRelease(Mem *p); +void sqlite3VdbeMemReleaseExternal(Mem *p); +#define VdbeMemRelease(X) \ + if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \ + sqlite3VdbeMemReleaseExternal(X); +int sqlite3VdbeMemFinalize(Mem*, FuncDef*); +const char *sqlite3OpcodeName(int); +int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve); +int sqlite3VdbeCloseStatement(Vdbe *, int); +void sqlite3VdbeFrameDelete(VdbeFrame*); +int sqlite3VdbeFrameRestore(VdbeFrame *); +void sqlite3VdbeMemStoreType(Mem *pMem); +int sqlite3VdbeTransferError(Vdbe *p); + +int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *); +void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *); +int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *); +int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *); +int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *); +int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *); +int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *); + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 + void sqlite3VdbeEnter(Vdbe*); + void sqlite3VdbeLeave(Vdbe*); +#else +# define sqlite3VdbeEnter(X) +# define sqlite3VdbeLeave(X) +#endif + +#ifdef SQLITE_DEBUG +void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*); +#endif + +#ifndef SQLITE_OMIT_FOREIGN_KEY +int sqlite3VdbeCheckFk(Vdbe *, int); +#else +# define sqlite3VdbeCheckFk(p,i) 0 +#endif + +int sqlite3VdbeMemTranslate(Mem*, u8); +#ifdef SQLITE_DEBUG + void sqlite3VdbePrintSql(Vdbe*); + void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf); +#endif +int sqlite3VdbeMemHandleBom(Mem *pMem); + +#ifndef SQLITE_OMIT_INCRBLOB + int sqlite3VdbeMemExpandBlob(Mem *); + #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0) +#else + #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK + #define ExpandBlob(P) SQLITE_OK +#endif + +#endif /* !defined(_VDBEINT_H_) */ diff --git a/components/external/SQLite-3.8.1/src/vdbeapi.c b/components/external/SQLite-3.8.1/src/vdbeapi.c new file mode 100644 index 0000000000000000000000000000000000000000..d51256217413188766279307e3a9721b9ed8e94c --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vdbeapi.c @@ -0,0 +1,1318 @@ +/* +** 2004 May 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code use to implement APIs that are part of the +** VDBE. +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** Return TRUE (non-zero) of the statement supplied as an argument needs +** to be recompiled. A statement needs to be recompiled whenever the +** execution environment changes in a way that would alter the program +** that sqlite3_prepare() generates. For example, if new functions or +** collating sequences are registered or if an authorizer function is +** added or changed. +*/ +int sqlite3_expired(sqlite3_stmt *pStmt){ + Vdbe *p = (Vdbe*)pStmt; + return p==0 || p->expired; +} +#endif + +/* +** Check on a Vdbe to make sure it has not been finalized. Log +** an error and return true if it has been finalized (or is otherwise +** invalid). Return false if it is ok. +*/ +static int vdbeSafety(Vdbe *p){ + if( p->db==0 ){ + sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement"); + return 1; + }else{ + return 0; + } +} +static int vdbeSafetyNotNull(Vdbe *p){ + if( p==0 ){ + sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement"); + return 1; + }else{ + return vdbeSafety(p); + } +} + +/* +** The following routine destroys a virtual machine that is created by +** the sqlite3_compile() routine. The integer returned is an SQLITE_ +** success/failure code that describes the result of executing the virtual +** machine. +** +** This routine sets the error code and string returned by +** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt){ + int rc; + if( pStmt==0 ){ + /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL + ** pointer is a harmless no-op. */ + rc = SQLITE_OK; + }else{ + Vdbe *v = (Vdbe*)pStmt; + sqlite3 *db = v->db; + if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT; + sqlite3_mutex_enter(db->mutex); + rc = sqlite3VdbeFinalize(v); + rc = sqlite3ApiExit(db, rc); + sqlite3LeaveMutexAndCloseZombie(db); + } + return rc; +} + +/* +** Terminate the current execution of an SQL statement and reset it +** back to its starting state so that it can be reused. A success code from +** the prior execution is returned. +** +** This routine sets the error code and string returned by +** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). +*/ +int sqlite3_reset(sqlite3_stmt *pStmt){ + int rc; + if( pStmt==0 ){ + rc = SQLITE_OK; + }else{ + Vdbe *v = (Vdbe*)pStmt; + sqlite3_mutex_enter(v->db->mutex); + rc = sqlite3VdbeReset(v); + sqlite3VdbeRewind(v); + assert( (rc & (v->db->errMask))==rc ); + rc = sqlite3ApiExit(v->db, rc); + sqlite3_mutex_leave(v->db->mutex); + } + return rc; +} + +/* +** Set all the parameters in the compiled SQL statement to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt *pStmt){ + int i; + int rc = SQLITE_OK; + Vdbe *p = (Vdbe*)pStmt; +#if SQLITE_THREADSAFE + sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex; +#endif + sqlite3_mutex_enter(mutex); + for(i=0; inVar; i++){ + sqlite3VdbeMemRelease(&p->aVar[i]); + p->aVar[i].flags = MEM_Null; + } + if( p->isPrepareV2 && p->expmask ){ + p->expired = 1; + } + sqlite3_mutex_leave(mutex); + return rc; +} + + +/**************************** sqlite3_value_ ******************************* +** The following routines extract information from a Mem or sqlite3_value +** structure. +*/ +const void *sqlite3_value_blob(sqlite3_value *pVal){ + Mem *p = (Mem*)pVal; + if( p->flags & (MEM_Blob|MEM_Str) ){ + sqlite3VdbeMemExpandBlob(p); + p->flags &= ~MEM_Str; + p->flags |= MEM_Blob; + return p->n ? p->z : 0; + }else{ + return sqlite3_value_text(pVal); + } +} +int sqlite3_value_bytes(sqlite3_value *pVal){ + return sqlite3ValueBytes(pVal, SQLITE_UTF8); +} +int sqlite3_value_bytes16(sqlite3_value *pVal){ + return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE); +} +double sqlite3_value_double(sqlite3_value *pVal){ + return sqlite3VdbeRealValue((Mem*)pVal); +} +int sqlite3_value_int(sqlite3_value *pVal){ + return (int)sqlite3VdbeIntValue((Mem*)pVal); +} +sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){ + return sqlite3VdbeIntValue((Mem*)pVal); +} +const unsigned char *sqlite3_value_text(sqlite3_value *pVal){ + return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8); +} +#ifndef SQLITE_OMIT_UTF16 +const void *sqlite3_value_text16(sqlite3_value* pVal){ + return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); +} +const void *sqlite3_value_text16be(sqlite3_value *pVal){ + return sqlite3ValueText(pVal, SQLITE_UTF16BE); +} +const void *sqlite3_value_text16le(sqlite3_value *pVal){ + return sqlite3ValueText(pVal, SQLITE_UTF16LE); +} +#endif /* SQLITE_OMIT_UTF16 */ +int sqlite3_value_type(sqlite3_value* pVal){ + return pVal->type; +} + +/**************************** sqlite3_result_ ******************************* +** The following routines are used by user-defined functions to specify +** the function result. +** +** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the +** result as a string or blob but if the string or blob is too large, it +** then sets the error code to SQLITE_TOOBIG +*/ +static void setResultStrOrError( + sqlite3_context *pCtx, /* Function context */ + const char *z, /* String pointer */ + int n, /* Bytes in string, or negative */ + u8 enc, /* Encoding of z. 0 for BLOBs */ + void (*xDel)(void*) /* Destructor function */ +){ + if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){ + sqlite3_result_error_toobig(pCtx); + } +} +void sqlite3_result_blob( + sqlite3_context *pCtx, + const void *z, + int n, + void (*xDel)(void *) +){ + assert( n>=0 ); + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, 0, xDel); +} +void sqlite3_result_double(sqlite3_context *pCtx, double rVal){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetDouble(&pCtx->s, rVal); +} +void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + pCtx->isError = SQLITE_ERROR; + pCtx->fErrorOrAux = 1; + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT); +} +#ifndef SQLITE_OMIT_UTF16 +void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + pCtx->isError = SQLITE_ERROR; + pCtx->fErrorOrAux = 1; + sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT); +} +#endif +void sqlite3_result_int(sqlite3_context *pCtx, int iVal){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal); +} +void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetInt64(&pCtx->s, iVal); +} +void sqlite3_result_null(sqlite3_context *pCtx){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetNull(&pCtx->s); +} +void sqlite3_result_text( + sqlite3_context *pCtx, + const char *z, + int n, + void (*xDel)(void *) +){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel); +} +#ifndef SQLITE_OMIT_UTF16 +void sqlite3_result_text16( + sqlite3_context *pCtx, + const void *z, + int n, + void (*xDel)(void *) +){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel); +} +void sqlite3_result_text16be( + sqlite3_context *pCtx, + const void *z, + int n, + void (*xDel)(void *) +){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel); +} +void sqlite3_result_text16le( + sqlite3_context *pCtx, + const void *z, + int n, + void (*xDel)(void *) +){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel); +} +#endif /* SQLITE_OMIT_UTF16 */ +void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemCopy(&pCtx->s, pValue); +} +void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetZeroBlob(&pCtx->s, n); +} +void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){ + pCtx->isError = errCode; + pCtx->fErrorOrAux = 1; + if( pCtx->s.flags & MEM_Null ){ + sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, + SQLITE_UTF8, SQLITE_STATIC); + } +} + +/* Force an SQLITE_TOOBIG error. */ +void sqlite3_result_error_toobig(sqlite3_context *pCtx){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + pCtx->isError = SQLITE_TOOBIG; + pCtx->fErrorOrAux = 1; + sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, + SQLITE_UTF8, SQLITE_STATIC); +} + +/* An SQLITE_NOMEM error. */ +void sqlite3_result_error_nomem(sqlite3_context *pCtx){ + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + sqlite3VdbeMemSetNull(&pCtx->s); + pCtx->isError = SQLITE_NOMEM; + pCtx->fErrorOrAux = 1; + pCtx->s.db->mallocFailed = 1; +} + +/* +** This function is called after a transaction has been committed. It +** invokes callbacks registered with sqlite3_wal_hook() as required. +*/ +static int doWalCallbacks(sqlite3 *db){ + int rc = SQLITE_OK; +#ifndef SQLITE_OMIT_WAL + int i; + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt)); + if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){ + rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry); + } + } + } +#endif + return rc; +} + +/* +** Execute the statement pStmt, either until a row of data is ready, the +** statement is completely executed or an error occurs. +** +** This routine implements the bulk of the logic behind the sqlite_step() +** API. The only thing omitted is the automatic recompile if a +** schema change has occurred. That detail is handled by the +** outer sqlite3_step() wrapper procedure. +*/ +static int sqlite3Step(Vdbe *p){ + sqlite3 *db; + int rc; + + assert(p); + if( p->magic!=VDBE_MAGIC_RUN ){ + /* We used to require that sqlite3_reset() be called before retrying + ** sqlite3_step() after any error or after SQLITE_DONE. But beginning + ** with version 3.7.0, we changed this so that sqlite3_reset() would + ** be called automatically instead of throwing the SQLITE_MISUSE error. + ** This "automatic-reset" change is not technically an incompatibility, + ** since any application that receives an SQLITE_MISUSE is broken by + ** definition. + ** + ** Nevertheless, some published applications that were originally written + ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE + ** returns, and those were broken by the automatic-reset change. As a + ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the + ** legacy behavior of returning SQLITE_MISUSE for cases where the + ** previous sqlite3_step() returned something other than a SQLITE_LOCKED + ** or SQLITE_BUSY error. + */ +#ifdef SQLITE_OMIT_AUTORESET + if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){ + sqlite3_reset((sqlite3_stmt*)p); + }else{ + return SQLITE_MISUSE_BKPT; + } +#else + sqlite3_reset((sqlite3_stmt*)p); +#endif + } + + /* Check that malloc() has not failed. If it has, return early. */ + db = p->db; + if( db->mallocFailed ){ + p->rc = SQLITE_NOMEM; + return SQLITE_NOMEM; + } + + if( p->pc<=0 && p->expired ){ + p->rc = SQLITE_SCHEMA; + rc = SQLITE_ERROR; + goto end_of_step; + } + if( p->pc<0 ){ + /* If there are no other statements currently running, then + ** reset the interrupt flag. This prevents a call to sqlite3_interrupt + ** from interrupting a statement that has not yet started. + */ + if( db->nVdbeActive==0 ){ + db->u1.isInterrupted = 0; + } + + assert( db->nVdbeWrite>0 || db->autoCommit==0 + || (db->nDeferredCons==0 && db->nDeferredImmCons==0) + ); + +#ifndef SQLITE_OMIT_TRACE + if( db->xProfile && !db->init.busy ){ + sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime); + } +#endif + + db->nVdbeActive++; + if( p->readOnly==0 ) db->nVdbeWrite++; + if( p->bIsReader ) db->nVdbeRead++; + p->pc = 0; + } +#ifndef SQLITE_OMIT_EXPLAIN + if( p->explain ){ + rc = sqlite3VdbeList(p); + }else +#endif /* SQLITE_OMIT_EXPLAIN */ + { + db->nVdbeExec++; + rc = sqlite3VdbeExec(p); + db->nVdbeExec--; + } + +#ifndef SQLITE_OMIT_TRACE + /* Invoke the profile callback if there is one + */ + if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){ + sqlite3_int64 iNow; + sqlite3OsCurrentTimeInt64(db->pVfs, &iNow); + db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000); + } +#endif + + if( rc==SQLITE_DONE ){ + assert( p->rc==SQLITE_OK ); + p->rc = doWalCallbacks(db); + if( p->rc!=SQLITE_OK ){ + rc = SQLITE_ERROR; + } + } + + db->errCode = rc; + if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){ + p->rc = SQLITE_NOMEM; + } +end_of_step: + /* At this point local variable rc holds the value that should be + ** returned if this statement was compiled using the legacy + ** sqlite3_prepare() interface. According to the docs, this can only + ** be one of the values in the first assert() below. Variable p->rc + ** contains the value that would be returned if sqlite3_finalize() + ** were called on statement p. + */ + assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR + || rc==SQLITE_BUSY || rc==SQLITE_MISUSE + ); + assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE ); + if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ + /* If this statement was prepared using sqlite3_prepare_v2(), and an + ** error has occurred, then return the error code in p->rc to the + ** caller. Set the error code in the database handle to the same value. + */ + rc = sqlite3VdbeTransferError(p); + } + return (rc&db->errMask); +} + +/* +** This is the top-level implementation of sqlite3_step(). Call +** sqlite3Step() to do most of the work. If a schema error occurs, +** call sqlite3Reprepare() and try again. +*/ +int sqlite3_step(sqlite3_stmt *pStmt){ + int rc = SQLITE_OK; /* Result from sqlite3Step() */ + int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */ + Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */ + int cnt = 0; /* Counter to prevent infinite loop of reprepares */ + sqlite3 *db; /* The database connection */ + + if( vdbeSafetyNotNull(v) ){ + return SQLITE_MISUSE_BKPT; + } + db = v->db; + sqlite3_mutex_enter(db->mutex); + v->doingRerun = 0; + while( (rc = sqlite3Step(v))==SQLITE_SCHEMA + && cnt++ < SQLITE_MAX_SCHEMA_RETRY + && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){ + sqlite3_reset(pStmt); + v->doingRerun = 1; + assert( v->expired==0 ); + } + if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){ + /* This case occurs after failing to recompile an sql statement. + ** The error message from the SQL compiler has already been loaded + ** into the database handle. This block copies the error message + ** from the database handle into the statement and sets the statement + ** program counter to 0 to ensure that when the statement is + ** finalized or reset the parser error message is available via + ** sqlite3_errmsg() and sqlite3_errcode(). + */ + const char *zErr = (const char *)sqlite3_value_text(db->pErr); + sqlite3DbFree(db, v->zErrMsg); + if( !db->mallocFailed ){ + v->zErrMsg = sqlite3DbStrDup(db, zErr); + v->rc = rc2; + } else { + v->zErrMsg = 0; + v->rc = rc = SQLITE_NOMEM; + } + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + + +/* +** Extract the user data from a sqlite3_context structure and return a +** pointer to it. +*/ +void *sqlite3_user_data(sqlite3_context *p){ + assert( p && p->pFunc ); + return p->pFunc->pUserData; +} + +/* +** Extract the user data from a sqlite3_context structure and return a +** pointer to it. +** +** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface +** returns a copy of the pointer to the database connection (the 1st +** parameter) of the sqlite3_create_function() and +** sqlite3_create_function16() routines that originally registered the +** application defined function. +*/ +sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){ + assert( p && p->pFunc ); + return p->s.db; +} + +/* +** Return the current time for a statement +*/ +sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){ + Vdbe *v = p->pVdbe; + int rc; + if( v->iCurrentTime==0 ){ + rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime); + if( rc ) v->iCurrentTime = 0; + } + return v->iCurrentTime; +} + +/* +** The following is the implementation of an SQL function that always +** fails with an error message stating that the function is used in the +** wrong context. The sqlite3_overload_function() API might construct +** SQL function that use this routine so that the functions will exist +** for name resolution but are actually overloaded by the xFindFunction +** method of virtual tables. +*/ +void sqlite3InvalidFunction( + sqlite3_context *context, /* The function calling context */ + int NotUsed, /* Number of arguments to the function */ + sqlite3_value **NotUsed2 /* Value of each argument */ +){ + const char *zName = context->pFunc->zName; + char *zErr; + UNUSED_PARAMETER2(NotUsed, NotUsed2); + zErr = sqlite3_mprintf( + "unable to use function %s in the requested context", zName); + sqlite3_result_error(context, zErr, -1); + sqlite3_free(zErr); +} + +/* +** Allocate or return the aggregate context for a user function. A new +** context is allocated on the first call. Subsequent calls return the +** same context that was returned on prior calls. +*/ +void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){ + Mem *pMem; + assert( p && p->pFunc && p->pFunc->xStep ); + assert( sqlite3_mutex_held(p->s.db->mutex) ); + pMem = p->pMem; + testcase( nByte<0 ); + if( (pMem->flags & MEM_Agg)==0 ){ + if( nByte<=0 ){ + sqlite3VdbeMemReleaseExternal(pMem); + pMem->flags = MEM_Null; + pMem->z = 0; + }else{ + sqlite3VdbeMemGrow(pMem, nByte, 0); + pMem->flags = MEM_Agg; + pMem->u.pDef = p->pFunc; + if( pMem->z ){ + memset(pMem->z, 0, nByte); + } + } + } + return (void*)pMem->z; +} + +/* +** Return the auxilary data pointer, if any, for the iArg'th argument to +** the user-function defined by pCtx. +*/ +void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){ + AuxData *pAuxData; + + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ + if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; + } + + return (pAuxData ? pAuxData->pAux : 0); +} + +/* +** Set the auxilary data pointer and delete function, for the iArg'th +** argument to the user-function defined by pCtx. Any previous value is +** deleted by calling the delete function specified when it was set. +*/ +void sqlite3_set_auxdata( + sqlite3_context *pCtx, + int iArg, + void *pAux, + void (*xDelete)(void*) +){ + AuxData *pAuxData; + Vdbe *pVdbe = pCtx->pVdbe; + + assert( sqlite3_mutex_held(pCtx->s.db->mutex) ); + if( iArg<0 ) goto failed; + + for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ + if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; + } + if( pAuxData==0 ){ + pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData)); + if( !pAuxData ) goto failed; + pAuxData->iOp = pCtx->iOp; + pAuxData->iArg = iArg; + pAuxData->pNext = pVdbe->pAuxData; + pVdbe->pAuxData = pAuxData; + if( pCtx->fErrorOrAux==0 ){ + pCtx->isError = 0; + pCtx->fErrorOrAux = 1; + } + }else if( pAuxData->xDelete ){ + pAuxData->xDelete(pAuxData->pAux); + } + + pAuxData->pAux = pAux; + pAuxData->xDelete = xDelete; + return; + +failed: + if( xDelete ){ + xDelete(pAux); + } +} + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** Return the number of times the Step function of a aggregate has been +** called. +** +** This function is deprecated. Do not use it for new code. It is +** provide only to avoid breaking legacy code. New aggregate function +** implementations should keep their own counts within their aggregate +** context. +*/ +int sqlite3_aggregate_count(sqlite3_context *p){ + assert( p && p->pMem && p->pFunc && p->pFunc->xStep ); + return p->pMem->n; +} +#endif + +/* +** Return the number of columns in the result set for the statement pStmt. +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt){ + Vdbe *pVm = (Vdbe *)pStmt; + return pVm ? pVm->nResColumn : 0; +} + +/* +** Return the number of values available from the current row of the +** currently executing statement pStmt. +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt){ + Vdbe *pVm = (Vdbe *)pStmt; + if( pVm==0 || pVm->pResultSet==0 ) return 0; + return pVm->nResColumn; +} + + +/* +** Check to see if column iCol of the given statement is valid. If +** it is, return a pointer to the Mem for the value of that column. +** If iCol is not valid, return a pointer to a Mem which has a value +** of NULL. +*/ +static Mem *columnMem(sqlite3_stmt *pStmt, int i){ + Vdbe *pVm; + Mem *pOut; + + pVm = (Vdbe *)pStmt; + if( pVm && pVm->pResultSet!=0 && inResColumn && i>=0 ){ + sqlite3_mutex_enter(pVm->db->mutex); + pOut = &pVm->pResultSet[i]; + }else{ + /* If the value passed as the second argument is out of range, return + ** a pointer to the following static Mem object which contains the + ** value SQL NULL. Even though the Mem structure contains an element + ** of type i64, on certain architectures (x86) with certain compiler + ** switches (-Os), gcc may align this Mem object on a 4-byte boundary + ** instead of an 8-byte one. This all works fine, except that when + ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s + ** that a Mem structure is located on an 8-byte boundary. To prevent + ** these assert()s from failing, when building with SQLITE_DEBUG defined + ** using gcc, we force nullMem to be 8-byte aligned using the magical + ** __attribute__((aligned(8))) macro. */ + static const Mem nullMem +#if defined(SQLITE_DEBUG) && defined(__GNUC__) + __attribute__((aligned(8))) +#endif + = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0, +#ifdef SQLITE_DEBUG + 0, 0, /* pScopyFrom, pFiller */ +#endif + 0, 0 }; + + if( pVm && ALWAYS(pVm->db) ){ + sqlite3_mutex_enter(pVm->db->mutex); + sqlite3Error(pVm->db, SQLITE_RANGE, 0); + } + pOut = (Mem*)&nullMem; + } + return pOut; +} + +/* +** This function is called after invoking an sqlite3_value_XXX function on a +** column value (i.e. a value returned by evaluating an SQL expression in the +** select list of a SELECT statement) that may cause a malloc() failure. If +** malloc() has failed, the threads mallocFailed flag is cleared and the result +** code of statement pStmt set to SQLITE_NOMEM. +** +** Specifically, this is called from within: +** +** sqlite3_column_int() +** sqlite3_column_int64() +** sqlite3_column_text() +** sqlite3_column_text16() +** sqlite3_column_real() +** sqlite3_column_bytes() +** sqlite3_column_bytes16() +** sqiite3_column_blob() +*/ +static void columnMallocFailure(sqlite3_stmt *pStmt) +{ + /* If malloc() failed during an encoding conversion within an + ** sqlite3_column_XXX API, then set the return code of the statement to + ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR + ** and _finalize() will return NOMEM. + */ + Vdbe *p = (Vdbe *)pStmt; + if( p ){ + p->rc = sqlite3ApiExit(p->db, p->rc); + sqlite3_mutex_leave(p->db->mutex); + } +} + +/**************************** sqlite3_column_ ******************************* +** The following routines are used to access elements of the current row +** in the result set. +*/ +const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){ + const void *val; + val = sqlite3_value_blob( columnMem(pStmt,i) ); + /* Even though there is no encoding conversion, value_blob() might + ** need to call malloc() to expand the result of a zeroblob() + ** expression. + */ + columnMallocFailure(pStmt); + return val; +} +int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){ + int val = sqlite3_value_bytes( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){ + int val = sqlite3_value_bytes16( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +double sqlite3_column_double(sqlite3_stmt *pStmt, int i){ + double val = sqlite3_value_double( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +int sqlite3_column_int(sqlite3_stmt *pStmt, int i){ + int val = sqlite3_value_int( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){ + sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){ + const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){ + Mem *pOut = columnMem(pStmt, i); + if( pOut->flags&MEM_Static ){ + pOut->flags &= ~MEM_Static; + pOut->flags |= MEM_Ephem; + } + columnMallocFailure(pStmt); + return (sqlite3_value *)pOut; +} +#ifndef SQLITE_OMIT_UTF16 +const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){ + const void *val = sqlite3_value_text16( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return val; +} +#endif /* SQLITE_OMIT_UTF16 */ +int sqlite3_column_type(sqlite3_stmt *pStmt, int i){ + int iType = sqlite3_value_type( columnMem(pStmt,i) ); + columnMallocFailure(pStmt); + return iType; +} + +/* +** Convert the N-th element of pStmt->pColName[] into a string using +** xFunc() then return that string. If N is out of range, return 0. +** +** There are up to 5 names for each column. useType determines which +** name is returned. Here are the names: +** +** 0 The column name as it should be displayed for output +** 1 The datatype name for the column +** 2 The name of the database that the column derives from +** 3 The name of the table that the column derives from +** 4 The name of the table column that the result column derives from +** +** If the result is not a simple column reference (if it is an expression +** or a constant) then useTypes 2, 3, and 4 return NULL. +*/ +static const void *columnName( + sqlite3_stmt *pStmt, + int N, + const void *(*xFunc)(Mem*), + int useType +){ + const void *ret = 0; + Vdbe *p = (Vdbe *)pStmt; + int n; + sqlite3 *db = p->db; + + assert( db!=0 ); + n = sqlite3_column_count(pStmt); + if( N=0 ){ + N += useType*n; + sqlite3_mutex_enter(db->mutex); + assert( db->mallocFailed==0 ); + ret = xFunc(&p->aColName[N]); + /* A malloc may have failed inside of the xFunc() call. If this + ** is the case, clear the mallocFailed flag and return NULL. + */ + if( db->mallocFailed ){ + db->mallocFailed = 0; + ret = 0; + } + sqlite3_mutex_leave(db->mutex); + } + return ret; +} + +/* +** Return the name of the Nth column of the result set returned by SQL +** statement pStmt. +*/ +const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME); +} +#ifndef SQLITE_OMIT_UTF16 +const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME); +} +#endif + +/* +** Constraint: If you have ENABLE_COLUMN_METADATA then you must +** not define OMIT_DECLTYPE. +*/ +#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA) +# error "Must not define both SQLITE_OMIT_DECLTYPE \ + and SQLITE_ENABLE_COLUMN_METADATA" +#endif + +#ifndef SQLITE_OMIT_DECLTYPE +/* +** Return the column declaration type (if applicable) of the 'i'th column +** of the result set of SQL statement pStmt. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE); +} +#ifndef SQLITE_OMIT_UTF16 +const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE); +} +#endif /* SQLITE_OMIT_UTF16 */ +#endif /* SQLITE_OMIT_DECLTYPE */ + +#ifdef SQLITE_ENABLE_COLUMN_METADATA +/* +** Return the name of the database from which a result column derives. +** NULL is returned if the result column is an expression or constant or +** anything else which is not an unabiguous reference to a database column. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE); +} +#ifndef SQLITE_OMIT_UTF16 +const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE); +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Return the name of the table from which a result column derives. +** NULL is returned if the result column is an expression or constant or +** anything else which is not an unabiguous reference to a database column. +*/ +const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE); +} +#ifndef SQLITE_OMIT_UTF16 +const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE); +} +#endif /* SQLITE_OMIT_UTF16 */ + +/* +** Return the name of the table column from which a result column derives. +** NULL is returned if the result column is an expression or constant or +** anything else which is not an unabiguous reference to a database column. +*/ +const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN); +} +#ifndef SQLITE_OMIT_UTF16 +const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){ + return columnName( + pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN); +} +#endif /* SQLITE_OMIT_UTF16 */ +#endif /* SQLITE_ENABLE_COLUMN_METADATA */ + + +/******************************* sqlite3_bind_ *************************** +** +** Routines used to attach values to wildcards in a compiled SQL statement. +*/ +/* +** Unbind the value bound to variable i in virtual machine p. This is the +** the same as binding a NULL value to the column. If the "i" parameter is +** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK. +** +** A successful evaluation of this routine acquires the mutex on p. +** the mutex is released if any kind of error occurs. +** +** The error code stored in database p->db is overwritten with the return +** value in any case. +*/ +static int vdbeUnbind(Vdbe *p, int i){ + Mem *pVar; + if( vdbeSafetyNotNull(p) ){ + return SQLITE_MISUSE_BKPT; + } + sqlite3_mutex_enter(p->db->mutex); + if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){ + sqlite3Error(p->db, SQLITE_MISUSE, 0); + sqlite3_mutex_leave(p->db->mutex); + sqlite3_log(SQLITE_MISUSE, + "bind on a busy prepared statement: [%s]", p->zSql); + return SQLITE_MISUSE_BKPT; + } + if( i<1 || i>p->nVar ){ + sqlite3Error(p->db, SQLITE_RANGE, 0); + sqlite3_mutex_leave(p->db->mutex); + return SQLITE_RANGE; + } + i--; + pVar = &p->aVar[i]; + sqlite3VdbeMemRelease(pVar); + pVar->flags = MEM_Null; + sqlite3Error(p->db, SQLITE_OK, 0); + + /* If the bit corresponding to this variable in Vdbe.expmask is set, then + ** binding a new value to this variable invalidates the current query plan. + ** + ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host + ** parameter in the WHERE clause might influence the choice of query plan + ** for a statement, then the statement will be automatically recompiled, + ** as if there had been a schema change, on the first sqlite3_step() call + ** following any change to the bindings of that parameter. + */ + if( p->isPrepareV2 && + ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff) + ){ + p->expired = 1; + } + return SQLITE_OK; +} + +/* +** Bind a text or BLOB value. +*/ +static int bindText( + sqlite3_stmt *pStmt, /* The statement to bind against */ + int i, /* Index of the parameter to bind */ + const void *zData, /* Pointer to the data to be bound */ + int nData, /* Number of bytes of data to be bound */ + void (*xDel)(void*), /* Destructor for the data */ + u8 encoding /* Encoding for the data */ +){ + Vdbe *p = (Vdbe *)pStmt; + Mem *pVar; + int rc; + + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + if( zData!=0 ){ + pVar = &p->aVar[i-1]; + rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel); + if( rc==SQLITE_OK && encoding!=0 ){ + rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db)); + } + sqlite3Error(p->db, rc, 0); + rc = sqlite3ApiExit(p->db, rc); + } + sqlite3_mutex_leave(p->db->mutex); + }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){ + xDel((void*)zData); + } + return rc; +} + + +/* +** Bind a blob value to an SQL statement variable. +*/ +int sqlite3_bind_blob( + sqlite3_stmt *pStmt, + int i, + const void *zData, + int nData, + void (*xDel)(void*) +){ + return bindText(pStmt, i, zData, nData, xDel, 0); +} +int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){ + int rc; + Vdbe *p = (Vdbe *)pStmt; + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue); + sqlite3_mutex_leave(p->db->mutex); + } + return rc; +} +int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){ + return sqlite3_bind_int64(p, i, (i64)iValue); +} +int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){ + int rc; + Vdbe *p = (Vdbe *)pStmt; + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue); + sqlite3_mutex_leave(p->db->mutex); + } + return rc; +} +int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){ + int rc; + Vdbe *p = (Vdbe*)pStmt; + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + sqlite3_mutex_leave(p->db->mutex); + } + return rc; +} +int sqlite3_bind_text( + sqlite3_stmt *pStmt, + int i, + const char *zData, + int nData, + void (*xDel)(void*) +){ + return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8); +} +#ifndef SQLITE_OMIT_UTF16 +int sqlite3_bind_text16( + sqlite3_stmt *pStmt, + int i, + const void *zData, + int nData, + void (*xDel)(void*) +){ + return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE); +} +#endif /* SQLITE_OMIT_UTF16 */ +int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){ + int rc; + switch( pValue->type ){ + case SQLITE_INTEGER: { + rc = sqlite3_bind_int64(pStmt, i, pValue->u.i); + break; + } + case SQLITE_FLOAT: { + rc = sqlite3_bind_double(pStmt, i, pValue->r); + break; + } + case SQLITE_BLOB: { + if( pValue->flags & MEM_Zero ){ + rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero); + }else{ + rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT); + } + break; + } + case SQLITE_TEXT: { + rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT, + pValue->enc); + break; + } + default: { + rc = sqlite3_bind_null(pStmt, i); + break; + } + } + return rc; +} +int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){ + int rc; + Vdbe *p = (Vdbe *)pStmt; + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n); + sqlite3_mutex_leave(p->db->mutex); + } + return rc; +} + +/* +** Return the number of wildcards that can be potentially bound to. +** This routine is added to support DBD::SQLite. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){ + Vdbe *p = (Vdbe*)pStmt; + return p ? p->nVar : 0; +} + +/* +** Return the name of a wildcard parameter. Return NULL if the index +** is out of range or if the wildcard is unnamed. +** +** The result is always UTF-8. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){ + Vdbe *p = (Vdbe*)pStmt; + if( p==0 || i<1 || i>p->nzVar ){ + return 0; + } + return p->azVar[i-1]; +} + +/* +** Given a wildcard parameter name, return the index of the variable +** with that name. If there is no variable with the given name, +** return 0. +*/ +int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){ + int i; + if( p==0 ){ + return 0; + } + if( zName ){ + for(i=0; inzVar; i++){ + const char *z = p->azVar[i]; + if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){ + return i+1; + } + } + } + return 0; +} +int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){ + return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName)); +} + +/* +** Transfer all bindings from the first statement over to the second. +*/ +int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ + Vdbe *pFrom = (Vdbe*)pFromStmt; + Vdbe *pTo = (Vdbe*)pToStmt; + int i; + assert( pTo->db==pFrom->db ); + assert( pTo->nVar==pFrom->nVar ); + sqlite3_mutex_enter(pTo->db->mutex); + for(i=0; inVar; i++){ + sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]); + } + sqlite3_mutex_leave(pTo->db->mutex); + return SQLITE_OK; +} + +#ifndef SQLITE_OMIT_DEPRECATED +/* +** Deprecated external interface. Internal/core SQLite code +** should call sqlite3TransferBindings. +** +** Is is misuse to call this routine with statements from different +** database connections. But as this is a deprecated interface, we +** will not bother to check for that condition. +** +** If the two statements contain a different number of bindings, then +** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise +** SQLITE_OK is returned. +*/ +int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ + Vdbe *pFrom = (Vdbe*)pFromStmt; + Vdbe *pTo = (Vdbe*)pToStmt; + if( pFrom->nVar!=pTo->nVar ){ + return SQLITE_ERROR; + } + if( pTo->isPrepareV2 && pTo->expmask ){ + pTo->expired = 1; + } + if( pFrom->isPrepareV2 && pFrom->expmask ){ + pFrom->expired = 1; + } + return sqlite3TransferBindings(pFromStmt, pToStmt); +} +#endif + +/* +** Return the sqlite3* database handle to which the prepared statement given +** in the argument belongs. This is the same database handle that was +** the first argument to the sqlite3_prepare() that was used to create +** the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){ + return pStmt ? ((Vdbe*)pStmt)->db : 0; +} + +/* +** Return true if the prepared statement is guaranteed to not modify the +** database. +*/ +int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){ + return pStmt ? ((Vdbe*)pStmt)->readOnly : 1; +} + +/* +** Return true if the prepared statement is in need of being reset. +*/ +int sqlite3_stmt_busy(sqlite3_stmt *pStmt){ + Vdbe *v = (Vdbe*)pStmt; + return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN; +} + +/* +** Return a pointer to the next prepared statement after pStmt associated +** with database connection pDb. If pStmt is NULL, return the first +** prepared statement for the database connection. Return NULL if there +** are no more. +*/ +sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){ + sqlite3_stmt *pNext; + sqlite3_mutex_enter(pDb->mutex); + if( pStmt==0 ){ + pNext = (sqlite3_stmt*)pDb->pVdbe; + }else{ + pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext; + } + sqlite3_mutex_leave(pDb->mutex); + return pNext; +} + +/* +** Return the value of a status counter for a prepared statement +*/ +int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){ + Vdbe *pVdbe = (Vdbe*)pStmt; + u32 v = pVdbe->aCounter[op]; + if( resetFlag ) pVdbe->aCounter[op] = 0; + return (int)v; +} diff --git a/components/external/SQLite-3.8.1/src/vdbeaux.c b/components/external/SQLite-3.8.1/src/vdbeaux.c new file mode 100644 index 0000000000000000000000000000000000000000..d2e495ea14505cac1efdacf250d56905ae5c7eb3 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vdbeaux.c @@ -0,0 +1,3322 @@ +/* +** 2003 September 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used for creating, destroying, and populating +** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior +** to version 2.8.7, all this code was combined into the vdbe.c source file. +** But that file was getting too big so this subroutines were split out. +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" + +/* +** Create a new virtual database engine. +*/ +Vdbe *sqlite3VdbeCreate(sqlite3 *db){ + Vdbe *p; + p = sqlite3DbMallocZero(db, sizeof(Vdbe) ); + if( p==0 ) return 0; + p->db = db; + if( db->pVdbe ){ + db->pVdbe->pPrev = p; + } + p->pNext = db->pVdbe; + p->pPrev = 0; + db->pVdbe = p; + p->magic = VDBE_MAGIC_INIT; + return p; +} + +/* +** Remember the SQL string for a prepared statement. +*/ +void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){ + assert( isPrepareV2==1 || isPrepareV2==0 ); + if( p==0 ) return; +#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG) + if( !isPrepareV2 ) return; +#endif + assert( p->zSql==0 ); + p->zSql = sqlite3DbStrNDup(p->db, z, n); + p->isPrepareV2 = (u8)isPrepareV2; +} + +/* +** Return the SQL associated with a prepared statement +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt){ + Vdbe *p = (Vdbe *)pStmt; + return (p && p->isPrepareV2) ? p->zSql : 0; +} + +/* +** Swap all content between two VDBE structures. +*/ +void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ + Vdbe tmp, *pTmp; + char *zTmp; + tmp = *pA; + *pA = *pB; + *pB = tmp; + pTmp = pA->pNext; + pA->pNext = pB->pNext; + pB->pNext = pTmp; + pTmp = pA->pPrev; + pA->pPrev = pB->pPrev; + pB->pPrev = pTmp; + zTmp = pA->zSql; + pA->zSql = pB->zSql; + pB->zSql = zTmp; + pB->isPrepareV2 = pA->isPrepareV2; +} + +#ifdef SQLITE_DEBUG +/* +** Turn tracing on or off +*/ +void sqlite3VdbeTrace(Vdbe *p, FILE *trace){ + p->trace = trace; +} +#endif + +/* +** Resize the Vdbe.aOp array so that it is at least one op larger than +** it was. +** +** If an out-of-memory error occurs while resizing the array, return +** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain +** unchanged (this is so that any opcodes already allocated can be +** correctly deallocated along with the rest of the Vdbe). +*/ +static int growOpArray(Vdbe *p){ + VdbeOp *pNew; + int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op))); + pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op)); + if( pNew ){ + p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op); + p->aOp = pNew; + } + return (pNew ? SQLITE_OK : SQLITE_NOMEM); +} + +/* +** Add a new instruction to the list of instructions current in the +** VDBE. Return the address of the new instruction. +** +** Parameters: +** +** p Pointer to the VDBE +** +** op The opcode for this instruction +** +** p1, p2, p3 Operands +** +** Use the sqlite3VdbeResolveLabel() function to fix an address and +** the sqlite3VdbeChangeP4() function to change the value of the P4 +** operand. +*/ +int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ + int i; + VdbeOp *pOp; + + i = p->nOp; + assert( p->magic==VDBE_MAGIC_INIT ); + assert( op>0 && op<0xff ); + if( p->nOpAlloc<=i ){ + if( growOpArray(p) ){ + return 1; + } + } + p->nOp++; + pOp = &p->aOp[i]; + pOp->opcode = (u8)op; + pOp->p5 = 0; + pOp->p1 = p1; + pOp->p2 = p2; + pOp->p3 = p3; + pOp->p4.p = 0; + pOp->p4type = P4_NOTUSED; +#ifdef SQLITE_DEBUG + pOp->zComment = 0; + if( p->db->flags & SQLITE_VdbeAddopTrace ){ + sqlite3VdbePrintOp(0, i, &p->aOp[i]); + } +#endif +#ifdef VDBE_PROFILE + pOp->cycles = 0; + pOp->cnt = 0; +#endif + return i; +} +int sqlite3VdbeAddOp0(Vdbe *p, int op){ + return sqlite3VdbeAddOp3(p, op, 0, 0, 0); +} +int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){ + return sqlite3VdbeAddOp3(p, op, p1, 0, 0); +} +int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){ + return sqlite3VdbeAddOp3(p, op, p1, p2, 0); +} + + +/* +** Add an opcode that includes the p4 value as a pointer. +*/ +int sqlite3VdbeAddOp4( + Vdbe *p, /* Add the opcode to this VM */ + int op, /* The new opcode */ + int p1, /* The P1 operand */ + int p2, /* The P2 operand */ + int p3, /* The P3 operand */ + const char *zP4, /* The P4 operand */ + int p4type /* P4 operand type */ +){ + int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); + sqlite3VdbeChangeP4(p, addr, zP4, p4type); + return addr; +} + +/* +** Add an OP_ParseSchema opcode. This routine is broken out from +** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees +** as having been used. +** +** The zWhere string must have been obtained from sqlite3_malloc(). +** This routine will take ownership of the allocated memory. +*/ +void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){ + int j; + int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0); + sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC); + for(j=0; jdb->nDb; j++) sqlite3VdbeUsesBtree(p, j); +} + +/* +** Add an opcode that includes the p4 value as an integer. +*/ +int sqlite3VdbeAddOp4Int( + Vdbe *p, /* Add the opcode to this VM */ + int op, /* The new opcode */ + int p1, /* The P1 operand */ + int p2, /* The P2 operand */ + int p3, /* The P3 operand */ + int p4 /* The P4 operand as an integer */ +){ + int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); + sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32); + return addr; +} + +/* +** Create a new symbolic label for an instruction that has yet to be +** coded. The symbolic label is really just a negative number. The +** label can be used as the P2 value of an operation. Later, when +** the label is resolved to a specific address, the VDBE will scan +** through its operation list and change all values of P2 which match +** the label into the resolved address. +** +** The VDBE knows that a P2 value is a label because labels are +** always negative and P2 values are suppose to be non-negative. +** Hence, a negative P2 value is a label that has yet to be resolved. +** +** Zero is returned if a malloc() fails. +*/ +int sqlite3VdbeMakeLabel(Vdbe *p){ + int i = p->nLabel++; + assert( p->magic==VDBE_MAGIC_INIT ); + if( (i & (i-1))==0 ){ + p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, + (i*2+1)*sizeof(p->aLabel[0])); + } + if( p->aLabel ){ + p->aLabel[i] = -1; + } + return -1-i; +} + +/* +** Resolve label "x" to be the address of the next instruction to +** be inserted. The parameter "x" must have been obtained from +** a prior call to sqlite3VdbeMakeLabel(). +*/ +void sqlite3VdbeResolveLabel(Vdbe *p, int x){ + int j = -1-x; + assert( p->magic==VDBE_MAGIC_INIT ); + assert( jnLabel ); + if( j>=0 && p->aLabel ){ + p->aLabel[j] = p->nOp; + } +} + +/* +** Mark the VDBE as one that can only be run one time. +*/ +void sqlite3VdbeRunOnlyOnce(Vdbe *p){ + p->runOnlyOnce = 1; +} + +#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */ + +/* +** The following type and function are used to iterate through all opcodes +** in a Vdbe main program and each of the sub-programs (triggers) it may +** invoke directly or indirectly. It should be used as follows: +** +** Op *pOp; +** VdbeOpIter sIter; +** +** memset(&sIter, 0, sizeof(sIter)); +** sIter.v = v; // v is of type Vdbe* +** while( (pOp = opIterNext(&sIter)) ){ +** // Do something with pOp +** } +** sqlite3DbFree(v->db, sIter.apSub); +** +*/ +typedef struct VdbeOpIter VdbeOpIter; +struct VdbeOpIter { + Vdbe *v; /* Vdbe to iterate through the opcodes of */ + SubProgram **apSub; /* Array of subprograms */ + int nSub; /* Number of entries in apSub */ + int iAddr; /* Address of next instruction to return */ + int iSub; /* 0 = main program, 1 = first sub-program etc. */ +}; +static Op *opIterNext(VdbeOpIter *p){ + Vdbe *v = p->v; + Op *pRet = 0; + Op *aOp; + int nOp; + + if( p->iSub<=p->nSub ){ + + if( p->iSub==0 ){ + aOp = v->aOp; + nOp = v->nOp; + }else{ + aOp = p->apSub[p->iSub-1]->aOp; + nOp = p->apSub[p->iSub-1]->nOp; + } + assert( p->iAddriAddr]; + p->iAddr++; + if( p->iAddr==nOp ){ + p->iSub++; + p->iAddr = 0; + } + + if( pRet->p4type==P4_SUBPROGRAM ){ + int nByte = (p->nSub+1)*sizeof(SubProgram*); + int j; + for(j=0; jnSub; j++){ + if( p->apSub[j]==pRet->p4.pProgram ) break; + } + if( j==p->nSub ){ + p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte); + if( !p->apSub ){ + pRet = 0; + }else{ + p->apSub[p->nSub++] = pRet->p4.pProgram; + } + } + } + } + + return pRet; +} + +/* +** Check if the program stored in the VM associated with pParse may +** throw an ABORT exception (causing the statement, but not entire transaction +** to be rolled back). This condition is true if the main program or any +** sub-programs contains any of the following: +** +** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort. +** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort. +** * OP_Destroy +** * OP_VUpdate +** * OP_VRename +** * OP_FkCounter with P2==0 (immediate foreign key constraint) +** +** Then check that the value of Parse.mayAbort is true if an +** ABORT may be thrown, or false otherwise. Return true if it does +** match, or false otherwise. This function is intended to be used as +** part of an assert statement in the compiler. Similar to: +** +** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) ); +*/ +int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ + int hasAbort = 0; + Op *pOp; + VdbeOpIter sIter; + memset(&sIter, 0, sizeof(sIter)); + sIter.v = v; + + while( (pOp = opIterNext(&sIter))!=0 ){ + int opcode = pOp->opcode; + if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename +#ifndef SQLITE_OMIT_FOREIGN_KEY + || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) +#endif + || ((opcode==OP_Halt || opcode==OP_HaltIfNull) + && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort)) + ){ + hasAbort = 1; + break; + } + } + sqlite3DbFree(v->db, sIter.apSub); + + /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred. + ** If malloc failed, then the while() loop above may not have iterated + ** through all opcodes and hasAbort may be set incorrectly. Return + ** true for this case to prevent the assert() in the callers frame + ** from failing. */ + return ( v->db->mallocFailed || hasAbort==mayAbort ); +} +#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */ + +/* +** Loop through the program looking for P2 values that are negative +** on jump instructions. Each such value is a label. Resolve the +** label by setting the P2 value to its correct non-zero value. +** +** This routine is called once after all opcodes have been inserted. +** +** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument +** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by +** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array. +** +** The Op.opflags field is set on all opcodes. +*/ +static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ + int i; + int nMaxArgs = *pMaxFuncArgs; + Op *pOp; + int *aLabel = p->aLabel; + p->readOnly = 1; + p->bIsReader = 0; + for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){ + u8 opcode = pOp->opcode; + + /* NOTE: Be sure to update mkopcodeh.awk when adding or removing + ** cases from this switch! */ + switch( opcode ){ + case OP_Function: + case OP_AggStep: { + if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5; + break; + } + case OP_Transaction: { + if( pOp->p2!=0 ) p->readOnly = 0; + /* fall thru */ + } + case OP_AutoCommit: + case OP_Savepoint: { + p->bIsReader = 1; + break; + } +#ifndef SQLITE_OMIT_WAL + case OP_Checkpoint: +#endif + case OP_Vacuum: + case OP_JournalMode: { + p->readOnly = 0; + p->bIsReader = 1; + break; + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + case OP_VUpdate: { + if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2; + break; + } + case OP_VFilter: { + int n; + assert( p->nOp - i >= 3 ); + assert( pOp[-1].opcode==OP_Integer ); + n = pOp[-1].p1; + if( n>nMaxArgs ) nMaxArgs = n; + break; + } +#endif + case OP_Next: + case OP_SorterNext: { + pOp->p4.xAdvance = sqlite3BtreeNext; + pOp->p4type = P4_ADVANCE; + break; + } + case OP_Prev: { + pOp->p4.xAdvance = sqlite3BtreePrevious; + pOp->p4type = P4_ADVANCE; + break; + } + } + + pOp->opflags = sqlite3OpcodeProperty[opcode]; + if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){ + assert( -1-pOp->p2nLabel ); + pOp->p2 = aLabel[-1-pOp->p2]; + } + } + sqlite3DbFree(p->db, p->aLabel); + p->aLabel = 0; + *pMaxFuncArgs = nMaxArgs; + assert( p->bIsReader!=0 || p->btreeMask==0 ); +} + +/* +** Return the address of the next instruction to be inserted. +*/ +int sqlite3VdbeCurrentAddr(Vdbe *p){ + assert( p->magic==VDBE_MAGIC_INIT ); + return p->nOp; +} + +/* +** This function returns a pointer to the array of opcodes associated with +** the Vdbe passed as the first argument. It is the callers responsibility +** to arrange for the returned array to be eventually freed using the +** vdbeFreeOpArray() function. +** +** Before returning, *pnOp is set to the number of entries in the returned +** array. Also, *pnMaxArg is set to the larger of its current value and +** the number of entries in the Vdbe.apArg[] array required to execute the +** returned program. +*/ +VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){ + VdbeOp *aOp = p->aOp; + assert( aOp && !p->db->mallocFailed ); + + /* Check that sqlite3VdbeUsesBtree() was not called on this VM */ + assert( p->btreeMask==0 ); + + resolveP2Values(p, pnMaxArg); + *pnOp = p->nOp; + p->aOp = 0; + return aOp; +} + +/* +** Add a whole list of operations to the operation stack. Return the +** address of the first operation added. +*/ +int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){ + int addr; + assert( p->magic==VDBE_MAGIC_INIT ); + if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){ + return 0; + } + addr = p->nOp; + if( ALWAYS(nOp>0) ){ + int i; + VdbeOpList const *pIn = aOp; + for(i=0; ip2; + VdbeOp *pOut = &p->aOp[i+addr]; + pOut->opcode = pIn->opcode; + pOut->p1 = pIn->p1; + if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){ + pOut->p2 = addr + ADDR(p2); + }else{ + pOut->p2 = p2; + } + pOut->p3 = pIn->p3; + pOut->p4type = P4_NOTUSED; + pOut->p4.p = 0; + pOut->p5 = 0; +#ifdef SQLITE_DEBUG + pOut->zComment = 0; + if( p->db->flags & SQLITE_VdbeAddopTrace ){ + sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]); + } +#endif + } + p->nOp += nOp; + } + return addr; +} + +/* +** Change the value of the P1 operand for a specific instruction. +** This routine is useful when a large program is loaded from a +** static array using sqlite3VdbeAddOpList but we want to make a +** few minor changes to the program. +*/ +void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){ + assert( p!=0 ); + if( ((u32)p->nOp)>addr ){ + p->aOp[addr].p1 = val; + } +} + +/* +** Change the value of the P2 operand for a specific instruction. +** This routine is useful for setting a jump destination. +*/ +void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){ + assert( p!=0 ); + if( ((u32)p->nOp)>addr ){ + p->aOp[addr].p2 = val; + } +} + +/* +** Change the value of the P3 operand for a specific instruction. +*/ +void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){ + assert( p!=0 ); + if( ((u32)p->nOp)>addr ){ + p->aOp[addr].p3 = val; + } +} + +/* +** Change the value of the P5 operand for the most recently +** added operation. +*/ +void sqlite3VdbeChangeP5(Vdbe *p, u8 val){ + assert( p!=0 ); + if( p->aOp ){ + assert( p->nOp>0 ); + p->aOp[p->nOp-1].p5 = val; + } +} + +/* +** Change the P2 operand of instruction addr so that it points to +** the address of the next instruction to be coded. +*/ +void sqlite3VdbeJumpHere(Vdbe *p, int addr){ + if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp); +} + + +/* +** If the input FuncDef structure is ephemeral, then free it. If +** the FuncDef is not ephermal, then do nothing. +*/ +static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){ + if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){ + sqlite3DbFree(db, pDef); + } +} + +static void vdbeFreeOpArray(sqlite3 *, Op *, int); + +/* +** Delete a P4 value if necessary. +*/ +static void freeP4(sqlite3 *db, int p4type, void *p4){ + if( p4 ){ + assert( db ); + switch( p4type ){ + case P4_REAL: + case P4_INT64: + case P4_DYNAMIC: + case P4_KEYINFO: + case P4_INTARRAY: + case P4_KEYINFO_HANDOFF: { + sqlite3DbFree(db, p4); + break; + } + case P4_MPRINTF: { + if( db->pnBytesFreed==0 ) sqlite3_free(p4); + break; + } + case P4_FUNCDEF: { + freeEphemeralFunction(db, (FuncDef*)p4); + break; + } + case P4_MEM: { + if( db->pnBytesFreed==0 ){ + sqlite3ValueFree((sqlite3_value*)p4); + }else{ + Mem *p = (Mem*)p4; + sqlite3DbFree(db, p->zMalloc); + sqlite3DbFree(db, p); + } + break; + } + case P4_VTAB : { + if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4); + break; + } + } + } +} + +/* +** Free the space allocated for aOp and any p4 values allocated for the +** opcodes contained within. If aOp is not NULL it is assumed to contain +** nOp entries. +*/ +static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){ + if( aOp ){ + Op *pOp; + for(pOp=aOp; pOp<&aOp[nOp]; pOp++){ + freeP4(db, pOp->p4type, pOp->p4.p); +#ifdef SQLITE_DEBUG + sqlite3DbFree(db, pOp->zComment); +#endif + } + } + sqlite3DbFree(db, aOp); +} + +/* +** Link the SubProgram object passed as the second argument into the linked +** list at Vdbe.pSubProgram. This list is used to delete all sub-program +** objects when the VM is no longer required. +*/ +void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){ + p->pNext = pVdbe->pProgram; + pVdbe->pProgram = p; +} + +/* +** Change the opcode at addr into OP_Noop +*/ +void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){ + if( p->aOp ){ + VdbeOp *pOp = &p->aOp[addr]; + sqlite3 *db = p->db; + freeP4(db, pOp->p4type, pOp->p4.p); + memset(pOp, 0, sizeof(pOp[0])); + pOp->opcode = OP_Noop; + } +} + +/* +** Change the value of the P4 operand for a specific instruction. +** This routine is useful when a large program is loaded from a +** static array using sqlite3VdbeAddOpList but we want to make a +** few minor changes to the program. +** +** If n>=0 then the P4 operand is dynamic, meaning that a copy of +** the string is made into memory obtained from sqlite3_malloc(). +** A value of n==0 means copy bytes of zP4 up to and including the +** first null byte. If n>0 then copy n+1 bytes of zP4. +** +** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure. +** A copy is made of the KeyInfo structure into memory obtained from +** sqlite3_malloc, to be freed when the Vdbe is finalized. +** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure +** stored in memory that the caller has obtained from sqlite3_malloc. The +** caller should not free the allocation, it will be freed when the Vdbe is +** finalized. +** +** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points +** to a string or structure that is guaranteed to exist for the lifetime of +** the Vdbe. In these cases we can just copy the pointer. +** +** If addr<0 then change P4 on the most recently inserted instruction. +*/ +void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ + Op *pOp; + sqlite3 *db; + assert( p!=0 ); + db = p->db; + assert( p->magic==VDBE_MAGIC_INIT ); + if( p->aOp==0 || db->mallocFailed ){ + if ( n!=P4_KEYINFO && n!=P4_VTAB ) { + freeP4(db, n, (void*)*(char**)&zP4); + } + return; + } + assert( p->nOp>0 ); + assert( addrnOp ); + if( addr<0 ){ + addr = p->nOp - 1; + } + pOp = &p->aOp[addr]; + assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 ); + freeP4(db, pOp->p4type, pOp->p4.p); + pOp->p4.p = 0; + if( n==P4_INT32 ){ + /* Note: this cast is safe, because the origin data point was an int + ** that was cast to a (const char *). */ + pOp->p4.i = SQLITE_PTR_TO_INT(zP4); + pOp->p4type = P4_INT32; + }else if( zP4==0 ){ + pOp->p4.p = 0; + pOp->p4type = P4_NOTUSED; + }else if( n==P4_KEYINFO ){ + KeyInfo *pOrig, *pNew; + + pOrig = (KeyInfo*)zP4; + pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField); + if( pNew ){ + memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0])); + memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField); + pOp->p4type = P4_KEYINFO; + }else{ + p->db->mallocFailed = 1; + pOp->p4type = P4_NOTUSED; + } + }else if( n==P4_KEYINFO_HANDOFF ){ + pOp->p4.p = (void*)zP4; + pOp->p4type = P4_KEYINFO; + }else if( n==P4_VTAB ){ + pOp->p4.p = (void*)zP4; + pOp->p4type = P4_VTAB; + sqlite3VtabLock((VTable *)zP4); + assert( ((VTable *)zP4)->db==p->db ); + }else if( n<0 ){ + pOp->p4.p = (void*)zP4; + pOp->p4type = (signed char)n; + }else{ + if( n==0 ) n = sqlite3Strlen30(zP4); + pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n); + pOp->p4type = P4_DYNAMIC; + } +} + +#ifndef NDEBUG +/* +** Change the comment on the most recently coded instruction. Or +** insert a No-op and add the comment to that new instruction. This +** makes the code easier to read during debugging. None of this happens +** in a production build. +*/ +static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){ + assert( p->nOp>0 || p->aOp==0 ); + assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed ); + if( p->nOp ){ + assert( p->aOp ); + sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment); + p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap); + } +} +void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){ + va_list ap; + if( p ){ + va_start(ap, zFormat); + vdbeVComment(p, zFormat, ap); + va_end(ap); + } +} +void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){ + va_list ap; + if( p ){ + sqlite3VdbeAddOp0(p, OP_Noop); + va_start(ap, zFormat); + vdbeVComment(p, zFormat, ap); + va_end(ap); + } +} +#endif /* NDEBUG */ + +/* +** Return the opcode for a given address. If the address is -1, then +** return the most recently inserted opcode. +** +** If a memory allocation error has occurred prior to the calling of this +** routine, then a pointer to a dummy VdbeOp will be returned. That opcode +** is readable but not writable, though it is cast to a writable value. +** The return of a dummy opcode allows the call to continue functioning +** after a OOM fault without having to check to see if the return from +** this routine is a valid pointer. But because the dummy.opcode is 0, +** dummy will never be written to. This is verified by code inspection and +** by running with Valgrind. +** +** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called +** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE, +** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as +** a new VDBE is created. So we are free to set addr to p->nOp-1 without +** having to double-check to make sure that the result is non-negative. But +** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to +** check the value of p->nOp-1 before continuing. +*/ +VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){ + /* C89 specifies that the constant "dummy" will be initialized to all + ** zeros, which is correct. MSVC generates a warning, nevertheless. */ + static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */ + assert( p->magic==VDBE_MAGIC_INIT ); + if( addr<0 ){ +#ifdef SQLITE_OMIT_TRACE + if( p->nOp==0 ) return (VdbeOp*)&dummy; +#endif + addr = p->nOp - 1; + } + assert( (addr>=0 && addrnOp) || p->db->mallocFailed ); + if( p->db->mallocFailed ){ + return (VdbeOp*)&dummy; + }else{ + return &p->aOp[addr]; + } +} + +#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \ + || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) +/* +** Compute a string that describes the P4 parameter for an opcode. +** Use zTemp for any required temporary buffer space. +*/ +static char *displayP4(Op *pOp, char *zTemp, int nTemp){ + char *zP4 = zTemp; + assert( nTemp>=20 ); + switch( pOp->p4type ){ + case P4_KEYINFO_STATIC: + case P4_KEYINFO: { + int i, j; + KeyInfo *pKeyInfo = pOp->p4.pKeyInfo; + assert( pKeyInfo->aSortOrder!=0 ); + sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField); + i = sqlite3Strlen30(zTemp); + for(j=0; jnField; j++){ + CollSeq *pColl = pKeyInfo->aColl[j]; + const char *zColl = pColl ? pColl->zName : "nil"; + int n = sqlite3Strlen30(zColl); + if( i+n>nTemp-6 ){ + memcpy(&zTemp[i],",...",4); + break; + } + zTemp[i++] = ','; + if( pKeyInfo->aSortOrder[j] ){ + zTemp[i++] = '-'; + } + memcpy(&zTemp[i], zColl, n+1); + i += n; + } + zTemp[i++] = ')'; + zTemp[i] = 0; + assert( ip4.pColl; + sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName); + break; + } + case P4_FUNCDEF: { + FuncDef *pDef = pOp->p4.pFunc; + sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg); + break; + } + case P4_INT64: { + sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64); + break; + } + case P4_INT32: { + sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i); + break; + } + case P4_REAL: { + sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal); + break; + } + case P4_MEM: { + Mem *pMem = pOp->p4.pMem; + if( pMem->flags & MEM_Str ){ + zP4 = pMem->z; + }else if( pMem->flags & MEM_Int ){ + sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i); + }else if( pMem->flags & MEM_Real ){ + sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r); + }else if( pMem->flags & MEM_Null ){ + sqlite3_snprintf(nTemp, zTemp, "NULL"); + }else{ + assert( pMem->flags & MEM_Blob ); + zP4 = "(blob)"; + } + break; + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + case P4_VTAB: { + sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab; + sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule); + break; + } +#endif + case P4_INTARRAY: { + sqlite3_snprintf(nTemp, zTemp, "intarray"); + break; + } + case P4_SUBPROGRAM: { + sqlite3_snprintf(nTemp, zTemp, "program"); + break; + } + case P4_ADVANCE: { + zTemp[0] = 0; + break; + } + default: { + zP4 = pOp->p4.z; + if( zP4==0 ){ + zP4 = zTemp; + zTemp[0] = 0; + } + } + } + assert( zP4!=0 ); + return zP4; +} +#endif + +/* +** Declare to the Vdbe that the BTree object at db->aDb[i] is used. +** +** The prepared statements need to know in advance the complete set of +** attached databases that will be use. A mask of these databases +** is maintained in p->btreeMask. The p->lockMask value is the subset of +** p->btreeMask of databases that will require a lock. +*/ +void sqlite3VdbeUsesBtree(Vdbe *p, int i){ + assert( i>=0 && idb->nDb && i<(int)sizeof(yDbMask)*8 ); + assert( i<(int)sizeof(p->btreeMask)*8 ); + p->btreeMask |= ((yDbMask)1)<db->aDb[i].pBt) ){ + p->lockMask |= ((yDbMask)1)<0 +/* +** If SQLite is compiled to support shared-cache mode and to be threadsafe, +** this routine obtains the mutex associated with each BtShared structure +** that may be accessed by the VM passed as an argument. In doing so it also +** sets the BtShared.db member of each of the BtShared structures, ensuring +** that the correct busy-handler callback is invoked if required. +** +** If SQLite is not threadsafe but does support shared-cache mode, then +** sqlite3BtreeEnter() is invoked to set the BtShared.db variables +** of all of BtShared structures accessible via the database handle +** associated with the VM. +** +** If SQLite is not threadsafe and does not support shared-cache mode, this +** function is a no-op. +** +** The p->btreeMask field is a bitmask of all btrees that the prepared +** statement p will ever use. Let N be the number of bits in p->btreeMask +** corresponding to btrees that use shared cache. Then the runtime of +** this routine is N*N. But as N is rarely more than 1, this should not +** be a problem. +*/ +void sqlite3VdbeEnter(Vdbe *p){ + int i; + yDbMask mask; + sqlite3 *db; + Db *aDb; + int nDb; + if( p->lockMask==0 ) return; /* The common case */ + db = p->db; + aDb = db->aDb; + nDb = db->nDb; + for(i=0, mask=1; ilockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){ + sqlite3BtreeEnter(aDb[i].pBt); + } + } +} +#endif + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 +/* +** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter(). +*/ +void sqlite3VdbeLeave(Vdbe *p){ + int i; + yDbMask mask; + sqlite3 *db; + Db *aDb; + int nDb; + if( p->lockMask==0 ) return; /* The common case */ + db = p->db; + aDb = db->aDb; + nDb = db->nDb; + for(i=0, mask=1; ilockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){ + sqlite3BtreeLeave(aDb[i].pBt); + } + } +} +#endif + +#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) +/* +** Print a single opcode. This routine is used for debugging only. +*/ +void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){ + char *zP4; + char zPtr[50]; + static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n"; + if( pOut==0 ) pOut = stdout; + zP4 = displayP4(pOp, zPtr, sizeof(zPtr)); + fprintf(pOut, zFormat1, pc, + sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5, +#ifdef SQLITE_DEBUG + pOp->zComment ? pOp->zComment : "" +#else + "" +#endif + ); + fflush(pOut); +} +#endif + +/* +** Release an array of N Mem elements +*/ +static void releaseMemArray(Mem *p, int N){ + if( p && N ){ + Mem *pEnd; + sqlite3 *db = p->db; + u8 malloc_failed = db->mallocFailed; + if( db->pnBytesFreed ){ + for(pEnd=&p[N]; pzMalloc); + } + return; + } + for(pEnd=&p[N]; pflags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){ + sqlite3VdbeMemRelease(p); + }else if( p->zMalloc ){ + sqlite3DbFree(db, p->zMalloc); + p->zMalloc = 0; + } + + p->flags = MEM_Invalid; + } + db->mallocFailed = malloc_failed; + } +} + +/* +** Delete a VdbeFrame object and its contents. VdbeFrame objects are +** allocated by the OP_Program opcode in sqlite3VdbeExec(). +*/ +void sqlite3VdbeFrameDelete(VdbeFrame *p){ + int i; + Mem *aMem = VdbeFrameMem(p); + VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem]; + for(i=0; inChildCsr; i++){ + sqlite3VdbeFreeCursor(p->v, apCsr[i]); + } + releaseMemArray(aMem, p->nChildMem); + sqlite3DbFree(p->v->db, p); +} + +#ifndef SQLITE_OMIT_EXPLAIN +/* +** Give a listing of the program in the virtual machine. +** +** The interface is the same as sqlite3VdbeExec(). But instead of +** running the code, it invokes the callback once for each instruction. +** This feature is used to implement "EXPLAIN". +** +** When p->explain==1, each instruction is listed. When +** p->explain==2, only OP_Explain instructions are listed and these +** are shown in a different format. p->explain==2 is used to implement +** EXPLAIN QUERY PLAN. +** +** When p->explain==1, first the main program is listed, then each of +** the trigger subprograms are listed one by one. +*/ +int sqlite3VdbeList( + Vdbe *p /* The VDBE */ +){ + int nRow; /* Stop when row count reaches this */ + int nSub = 0; /* Number of sub-vdbes seen so far */ + SubProgram **apSub = 0; /* Array of sub-vdbes */ + Mem *pSub = 0; /* Memory cell hold array of subprogs */ + sqlite3 *db = p->db; /* The database connection */ + int i; /* Loop counter */ + int rc = SQLITE_OK; /* Return code */ + Mem *pMem = &p->aMem[1]; /* First Mem of result set */ + + assert( p->explain ); + assert( p->magic==VDBE_MAGIC_RUN ); + assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM ); + + /* Even though this opcode does not use dynamic strings for + ** the result, result columns may become dynamic if the user calls + ** sqlite3_column_text16(), causing a translation to UTF-16 encoding. + */ + releaseMemArray(pMem, 8); + p->pResultSet = 0; + + if( p->rc==SQLITE_NOMEM ){ + /* This happens if a malloc() inside a call to sqlite3_column_text() or + ** sqlite3_column_text16() failed. */ + db->mallocFailed = 1; + return SQLITE_ERROR; + } + + /* When the number of output rows reaches nRow, that means the + ** listing has finished and sqlite3_step() should return SQLITE_DONE. + ** nRow is the sum of the number of rows in the main program, plus + ** the sum of the number of rows in all trigger subprograms encountered + ** so far. The nRow value will increase as new trigger subprograms are + ** encountered, but p->pc will eventually catch up to nRow. + */ + nRow = p->nOp; + if( p->explain==1 ){ + /* The first 8 memory cells are used for the result set. So we will + ** commandeer the 9th cell to use as storage for an array of pointers + ** to trigger subprograms. The VDBE is guaranteed to have at least 9 + ** cells. */ + assert( p->nMem>9 ); + pSub = &p->aMem[9]; + if( pSub->flags&MEM_Blob ){ + /* On the first call to sqlite3_step(), pSub will hold a NULL. It is + ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */ + nSub = pSub->n/sizeof(Vdbe*); + apSub = (SubProgram **)pSub->z; + } + for(i=0; inOp; + } + } + + do{ + i = p->pc++; + }while( iexplain==2 && p->aOp[i].opcode!=OP_Explain ); + if( i>=nRow ){ + p->rc = SQLITE_OK; + rc = SQLITE_DONE; + }else if( db->u1.isInterrupted ){ + p->rc = SQLITE_INTERRUPT; + rc = SQLITE_ERROR; + sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc)); + }else{ + char *z; + Op *pOp; + if( inOp ){ + /* The output line number is small enough that we are still in the + ** main program. */ + pOp = &p->aOp[i]; + }else{ + /* We are currently listing subprograms. Figure out which one and + ** pick up the appropriate opcode. */ + int j; + i -= p->nOp; + for(j=0; i>=apSub[j]->nOp; j++){ + i -= apSub[j]->nOp; + } + pOp = &apSub[j]->aOp[i]; + } + if( p->explain==1 ){ + pMem->flags = MEM_Int; + pMem->type = SQLITE_INTEGER; + pMem->u.i = i; /* Program counter */ + pMem++; + + pMem->flags = MEM_Static|MEM_Str|MEM_Term; + pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ + assert( pMem->z!=0 ); + pMem->n = sqlite3Strlen30(pMem->z); + pMem->type = SQLITE_TEXT; + pMem->enc = SQLITE_UTF8; + pMem++; + + /* When an OP_Program opcode is encounter (the only opcode that has + ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms + ** kept in p->aMem[9].z to hold the new program - assuming this subprogram + ** has not already been seen. + */ + if( pOp->p4type==P4_SUBPROGRAM ){ + int nByte = (nSub+1)*sizeof(SubProgram*); + int j; + for(j=0; jp4.pProgram ) break; + } + if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){ + apSub = (SubProgram **)pSub->z; + apSub[nSub++] = pOp->p4.pProgram; + pSub->flags |= MEM_Blob; + pSub->n = nSub*sizeof(SubProgram*); + } + } + } + + pMem->flags = MEM_Int; + pMem->u.i = pOp->p1; /* P1 */ + pMem->type = SQLITE_INTEGER; + pMem++; + + pMem->flags = MEM_Int; + pMem->u.i = pOp->p2; /* P2 */ + pMem->type = SQLITE_INTEGER; + pMem++; + + pMem->flags = MEM_Int; + pMem->u.i = pOp->p3; /* P3 */ + pMem->type = SQLITE_INTEGER; + pMem++; + + if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */ + assert( p->db->mallocFailed ); + return SQLITE_ERROR; + } + pMem->flags = MEM_Dyn|MEM_Str|MEM_Term; + z = displayP4(pOp, pMem->z, 32); + if( z!=pMem->z ){ + sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0); + }else{ + assert( pMem->z!=0 ); + pMem->n = sqlite3Strlen30(pMem->z); + pMem->enc = SQLITE_UTF8; + } + pMem->type = SQLITE_TEXT; + pMem++; + + if( p->explain==1 ){ + if( sqlite3VdbeMemGrow(pMem, 4, 0) ){ + assert( p->db->mallocFailed ); + return SQLITE_ERROR; + } + pMem->flags = MEM_Dyn|MEM_Str|MEM_Term; + pMem->n = 2; + sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */ + pMem->type = SQLITE_TEXT; + pMem->enc = SQLITE_UTF8; + pMem++; + +#ifdef SQLITE_DEBUG + if( pOp->zComment ){ + pMem->flags = MEM_Str|MEM_Term; + pMem->z = pOp->zComment; + pMem->n = sqlite3Strlen30(pMem->z); + pMem->enc = SQLITE_UTF8; + pMem->type = SQLITE_TEXT; + }else +#endif + { + pMem->flags = MEM_Null; /* Comment */ + pMem->type = SQLITE_NULL; + } + } + + p->nResColumn = 8 - 4*(p->explain-1); + p->pResultSet = &p->aMem[1]; + p->rc = SQLITE_OK; + rc = SQLITE_ROW; + } + return rc; +} +#endif /* SQLITE_OMIT_EXPLAIN */ + +#ifdef SQLITE_DEBUG +/* +** Print the SQL that was used to generate a VDBE program. +*/ +void sqlite3VdbePrintSql(Vdbe *p){ + int nOp = p->nOp; + VdbeOp *pOp; + if( nOp<1 ) return; + pOp = &p->aOp[0]; + if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){ + const char *z = pOp->p4.z; + while( sqlite3Isspace(*z) ) z++; + printf("SQL: [%s]\n", z); + } +} +#endif + +#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) +/* +** Print an IOTRACE message showing SQL content. +*/ +void sqlite3VdbeIOTraceSql(Vdbe *p){ + int nOp = p->nOp; + VdbeOp *pOp; + if( sqlite3IoTrace==0 ) return; + if( nOp<1 ) return; + pOp = &p->aOp[0]; + if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){ + int i, j; + char z[1000]; + sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z); + for(i=0; sqlite3Isspace(z[i]); i++){} + for(j=0; z[i]; i++){ + if( sqlite3Isspace(z[i]) ){ + if( z[i-1]!=' ' ){ + z[j++] = ' '; + } + }else{ + z[j++] = z[i]; + } + } + z[j] = 0; + sqlite3IoTrace("SQL %s\n", z); + } +} +#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */ + +/* +** Allocate space from a fixed size buffer and return a pointer to +** that space. If insufficient space is available, return NULL. +** +** The pBuf parameter is the initial value of a pointer which will +** receive the new memory. pBuf is normally NULL. If pBuf is not +** NULL, it means that memory space has already been allocated and that +** this routine should not allocate any new memory. When pBuf is not +** NULL simply return pBuf. Only allocate new memory space when pBuf +** is NULL. +** +** nByte is the number of bytes of space needed. +** +** *ppFrom points to available space and pEnd points to the end of the +** available space. When space is allocated, *ppFrom is advanced past +** the end of the allocated space. +** +** *pnByte is a counter of the number of bytes of space that have failed +** to allocate. If there is insufficient space in *ppFrom to satisfy the +** request, then increment *pnByte by the amount of the request. +*/ +static void *allocSpace( + void *pBuf, /* Where return pointer will be stored */ + int nByte, /* Number of bytes to allocate */ + u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */ + u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */ + int *pnByte /* If allocation cannot be made, increment *pnByte */ +){ + assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) ); + if( pBuf ) return pBuf; + nByte = ROUND8(nByte); + if( &(*ppFrom)[nByte] <= pEnd ){ + pBuf = (void*)*ppFrom; + *ppFrom += nByte; + }else{ + *pnByte += nByte; + } + return pBuf; +} + +/* +** Rewind the VDBE back to the beginning in preparation for +** running it. +*/ +void sqlite3VdbeRewind(Vdbe *p){ +#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) + int i; +#endif + assert( p!=0 ); + assert( p->magic==VDBE_MAGIC_INIT ); + + /* There should be at least one opcode. + */ + assert( p->nOp>0 ); + + /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */ + p->magic = VDBE_MAGIC_RUN; + +#ifdef SQLITE_DEBUG + for(i=1; inMem; i++){ + assert( p->aMem[i].db==p->db ); + } +#endif + p->pc = -1; + p->rc = SQLITE_OK; + p->errorAction = OE_Abort; + p->magic = VDBE_MAGIC_RUN; + p->nChange = 0; + p->cacheCtr = 1; + p->minWriteFileFormat = 255; + p->iStatement = 0; + p->nFkConstraint = 0; +#ifdef VDBE_PROFILE + for(i=0; inOp; i++){ + p->aOp[i].cnt = 0; + p->aOp[i].cycles = 0; + } +#endif +} + +/* +** Prepare a virtual machine for execution for the first time after +** creating the virtual machine. This involves things such +** as allocating stack space and initializing the program counter. +** After the VDBE has be prepped, it can be executed by one or more +** calls to sqlite3VdbeExec(). +** +** This function may be called exact once on a each virtual machine. +** After this routine is called the VM has been "packaged" and is ready +** to run. After this routine is called, futher calls to +** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects +** the Vdbe from the Parse object that helped generate it so that the +** the Vdbe becomes an independent entity and the Parse object can be +** destroyed. +** +** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back +** to its initial state after it has been run. +*/ +void sqlite3VdbeMakeReady( + Vdbe *p, /* The VDBE */ + Parse *pParse /* Parsing context */ +){ + sqlite3 *db; /* The database connection */ + int nVar; /* Number of parameters */ + int nMem; /* Number of VM memory registers */ + int nCursor; /* Number of cursors required */ + int nArg; /* Number of arguments in subprograms */ + int nOnce; /* Number of OP_Once instructions */ + int n; /* Loop counter */ + u8 *zCsr; /* Memory available for allocation */ + u8 *zEnd; /* First byte past allocated memory */ + int nByte; /* How much extra memory is needed */ + + assert( p!=0 ); + assert( p->nOp>0 ); + assert( pParse!=0 ); + assert( p->magic==VDBE_MAGIC_INIT ); + db = p->db; + assert( db->mallocFailed==0 ); + nVar = pParse->nVar; + nMem = pParse->nMem; + nCursor = pParse->nTab; + nArg = pParse->nMaxArg; + nOnce = pParse->nOnce; + if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */ + + /* For each cursor required, also allocate a memory cell. Memory + ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by + ** the vdbe program. Instead they are used to allocate space for + ** VdbeCursor/BtCursor structures. The blob of memory associated with + ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1) + ** stores the blob of memory associated with cursor 1, etc. + ** + ** See also: allocateCursor(). + */ + nMem += nCursor; + + /* Allocate space for memory registers, SQL variables, VDBE cursors and + ** an array to marshal SQL function arguments in. + */ + zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */ + zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */ + + resolveP2Values(p, &nArg); + p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort); + if( pParse->explain && nMem<10 ){ + nMem = 10; + } + memset(zCsr, 0, zEnd-zCsr); + zCsr += (zCsr - (u8*)0)&7; + assert( EIGHT_BYTE_ALIGNMENT(zCsr) ); + p->expired = 0; + + /* Memory for registers, parameters, cursor, etc, is allocated in two + ** passes. On the first pass, we try to reuse unused space at the + ** end of the opcode array. If we are unable to satisfy all memory + ** requirements by reusing the opcode array tail, then the second + ** pass will fill in the rest using a fresh allocation. + ** + ** This two-pass approach that reuses as much memory as possible from + ** the leftover space at the end of the opcode array can significantly + ** reduce the amount of memory held by a prepared statement. + */ + do { + nByte = 0; + p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte); + p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte); + p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte); + p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte); + p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*), + &zCsr, zEnd, &nByte); + p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte); + if( nByte ){ + p->pFree = sqlite3DbMallocZero(db, nByte); + } + zCsr = p->pFree; + zEnd = &zCsr[nByte]; + }while( nByte && !db->mallocFailed ); + + p->nCursor = nCursor; + p->nOnceFlag = nOnce; + if( p->aVar ){ + p->nVar = (ynVar)nVar; + for(n=0; naVar[n].flags = MEM_Null; + p->aVar[n].db = db; + } + } + if( p->azVar ){ + p->nzVar = pParse->nzVar; + memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0])); + memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0])); + } + if( p->aMem ){ + p->aMem--; /* aMem[] goes from 1..nMem */ + p->nMem = nMem; /* not from 0..nMem-1 */ + for(n=1; n<=nMem; n++){ + p->aMem[n].flags = MEM_Invalid; + p->aMem[n].db = db; + } + } + p->explain = pParse->explain; + sqlite3VdbeRewind(p); +} + +/* +** Close a VDBE cursor and release all the resources that cursor +** happens to hold. +*/ +void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){ + if( pCx==0 ){ + return; + } + sqlite3VdbeSorterClose(p->db, pCx); + if( pCx->pBt ){ + sqlite3BtreeClose(pCx->pBt); + /* The pCx->pCursor will be close automatically, if it exists, by + ** the call above. */ + }else if( pCx->pCursor ){ + sqlite3BtreeCloseCursor(pCx->pCursor); + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pCx->pVtabCursor ){ + sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor; + const sqlite3_module *pModule = pCx->pModule; + p->inVtabMethod = 1; + pModule->xClose(pVtabCursor); + p->inVtabMethod = 0; + } +#endif +} + +/* +** Copy the values stored in the VdbeFrame structure to its Vdbe. This +** is used, for example, when a trigger sub-program is halted to restore +** control to the main program. +*/ +int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){ + Vdbe *v = pFrame->v; + v->aOnceFlag = pFrame->aOnceFlag; + v->nOnceFlag = pFrame->nOnceFlag; + v->aOp = pFrame->aOp; + v->nOp = pFrame->nOp; + v->aMem = pFrame->aMem; + v->nMem = pFrame->nMem; + v->apCsr = pFrame->apCsr; + v->nCursor = pFrame->nCursor; + v->db->lastRowid = pFrame->lastRowid; + v->nChange = pFrame->nChange; + return pFrame->pc; +} + +/* +** Close all cursors. +** +** Also release any dynamic memory held by the VM in the Vdbe.aMem memory +** cell array. This is necessary as the memory cell array may contain +** pointers to VdbeFrame objects, which may in turn contain pointers to +** open cursors. +*/ +static void closeAllCursors(Vdbe *p){ + if( p->pFrame ){ + VdbeFrame *pFrame; + for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); + sqlite3VdbeFrameRestore(pFrame); + } + p->pFrame = 0; + p->nFrame = 0; + + if( p->apCsr ){ + int i; + for(i=0; inCursor; i++){ + VdbeCursor *pC = p->apCsr[i]; + if( pC ){ + sqlite3VdbeFreeCursor(p, pC); + p->apCsr[i] = 0; + } + } + } + if( p->aMem ){ + releaseMemArray(&p->aMem[1], p->nMem); + } + while( p->pDelFrame ){ + VdbeFrame *pDel = p->pDelFrame; + p->pDelFrame = pDel->pParent; + sqlite3VdbeFrameDelete(pDel); + } + + /* Delete any auxdata allocations made by the VM */ + sqlite3VdbeDeleteAuxData(p, -1, 0); + assert( p->pAuxData==0 ); +} + +/* +** Clean up the VM after execution. +** +** This routine will automatically close any cursors, lists, and/or +** sorters that were left open. It also deletes the values of +** variables in the aVar[] array. +*/ +static void Cleanup(Vdbe *p){ + sqlite3 *db = p->db; + +#ifdef SQLITE_DEBUG + /* Execute assert() statements to ensure that the Vdbe.apCsr[] and + ** Vdbe.aMem[] arrays have already been cleaned up. */ + int i; + if( p->apCsr ) for(i=0; inCursor; i++) assert( p->apCsr[i]==0 ); + if( p->aMem ){ + for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid ); + } +#endif + + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = 0; + p->pResultSet = 0; +} + +/* +** Set the number of result columns that will be returned by this SQL +** statement. This is now set at compile time, rather than during +** execution of the vdbe program so that sqlite3_column_count() can +** be called on an SQL statement before sqlite3_step(). +*/ +void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){ + Mem *pColName; + int n; + sqlite3 *db = p->db; + + releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); + sqlite3DbFree(db, p->aColName); + n = nResColumn*COLNAME_N; + p->nResColumn = (u16)nResColumn; + p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n ); + if( p->aColName==0 ) return; + while( n-- > 0 ){ + pColName->flags = MEM_Null; + pColName->db = p->db; + pColName++; + } +} + +/* +** Set the name of the idx'th column to be returned by the SQL statement. +** zName must be a pointer to a nul terminated string. +** +** This call must be made after a call to sqlite3VdbeSetNumCols(). +** +** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC +** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed +** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed. +*/ +int sqlite3VdbeSetColName( + Vdbe *p, /* Vdbe being configured */ + int idx, /* Index of column zName applies to */ + int var, /* One of the COLNAME_* constants */ + const char *zName, /* Pointer to buffer containing name */ + void (*xDel)(void*) /* Memory management strategy for zName */ +){ + int rc; + Mem *pColName; + assert( idxnResColumn ); + assert( vardb->mallocFailed ){ + assert( !zName || xDel!=SQLITE_DYNAMIC ); + return SQLITE_NOMEM; + } + assert( p->aColName!=0 ); + pColName = &(p->aColName[idx+var*p->nResColumn]); + rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel); + assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 ); + return rc; +} + +/* +** A read or write transaction may or may not be active on database handle +** db. If a transaction is active, commit it. If there is a +** write-transaction spanning more than one database file, this routine +** takes care of the master journal trickery. +*/ +static int vdbeCommit(sqlite3 *db, Vdbe *p){ + int i; + int nTrans = 0; /* Number of databases with an active write-transaction */ + int rc = SQLITE_OK; + int needXcommit = 0; + +#ifdef SQLITE_OMIT_VIRTUALTABLE + /* With this option, sqlite3VtabSync() is defined to be simply + ** SQLITE_OK so p is not used. + */ + UNUSED_PARAMETER(p); +#endif + + /* Before doing anything else, call the xSync() callback for any + ** virtual module tables written in this transaction. This has to + ** be done before determining whether a master journal file is + ** required, as an xSync() callback may add an attached database + ** to the transaction. + */ + rc = sqlite3VtabSync(db, p); + + /* This loop determines (a) if the commit hook should be invoked and + ** (b) how many database files have open write transactions, not + ** including the temp database. (b) is important because if more than + ** one database file has an open write transaction, a master journal + ** file is required for an atomic commit. + */ + for(i=0; rc==SQLITE_OK && inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( sqlite3BtreeIsInTrans(pBt) ){ + needXcommit = 1; + if( i!=1 ) nTrans++; + sqlite3BtreeEnter(pBt); + rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt)); + sqlite3BtreeLeave(pBt); + } + } + if( rc!=SQLITE_OK ){ + return rc; + } + + /* If there are any write-transactions at all, invoke the commit hook */ + if( needXcommit && db->xCommitCallback ){ + rc = db->xCommitCallback(db->pCommitArg); + if( rc ){ + return SQLITE_CONSTRAINT_COMMITHOOK; + } + } + + /* The simple case - no more than one database file (not counting the + ** TEMP database) has a transaction active. There is no need for the + ** master-journal. + ** + ** If the return value of sqlite3BtreeGetFilename() is a zero length + ** string, it means the main database is :memory: or a temp file. In + ** that case we do not support atomic multi-file commits, so use the + ** simple case then too. + */ + if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt)) + || nTrans<=1 + ){ + for(i=0; rc==SQLITE_OK && inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + rc = sqlite3BtreeCommitPhaseOne(pBt, 0); + } + } + + /* Do the commit only if all databases successfully complete phase 1. + ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an + ** IO error while deleting or truncating a journal file. It is unlikely, + ** but could happen. In this case abandon processing and return the error. + */ + for(i=0; rc==SQLITE_OK && inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + rc = sqlite3BtreeCommitPhaseTwo(pBt, 0); + } + } + if( rc==SQLITE_OK ){ + sqlite3VtabCommit(db); + } + } + + /* The complex case - There is a multi-file write-transaction active. + ** This requires a master journal file to ensure the transaction is + ** committed atomicly. + */ +#ifndef SQLITE_OMIT_DISKIO + else{ + sqlite3_vfs *pVfs = db->pVfs; + int needSync = 0; + char *zMaster = 0; /* File-name for the master journal */ + char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt); + sqlite3_file *pMaster = 0; + i64 offset = 0; + int res; + int retryCount = 0; + int nMainFile; + + /* Select a master journal file name */ + nMainFile = sqlite3Strlen30(zMainFile); + zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile); + if( zMaster==0 ) return SQLITE_NOMEM; + do { + u32 iRandom; + if( retryCount ){ + if( retryCount>100 ){ + sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster); + sqlite3OsDelete(pVfs, zMaster, 0); + break; + }else if( retryCount==1 ){ + sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster); + } + } + retryCount++; + sqlite3_randomness(sizeof(iRandom), &iRandom); + sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X", + (iRandom>>8)&0xffffff, iRandom&0xff); + /* The antipenultimate character of the master journal name must + ** be "9" to avoid name collisions when using 8+3 filenames. */ + assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' ); + sqlite3FileSuffix3(zMainFile, zMaster); + rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); + }while( rc==SQLITE_OK && res ); + if( rc==SQLITE_OK ){ + /* Open the master journal. */ + rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, + SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE| + SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0 + ); + } + if( rc!=SQLITE_OK ){ + sqlite3DbFree(db, zMaster); + return rc; + } + + /* Write the name of each database file in the transaction into the new + ** master journal file. If an error occurs at this point close + ** and delete the master journal file. All the individual journal files + ** still have 'null' as the master journal pointer, so they will roll + ** back independently if a failure occurs. + */ + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( sqlite3BtreeIsInTrans(pBt) ){ + char const *zFile = sqlite3BtreeGetJournalname(pBt); + if( zFile==0 ){ + continue; /* Ignore TEMP and :memory: databases */ + } + assert( zFile[0]!=0 ); + if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){ + needSync = 1; + } + rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset); + offset += sqlite3Strlen30(zFile)+1; + if( rc!=SQLITE_OK ){ + sqlite3OsCloseFree(pMaster); + sqlite3OsDelete(pVfs, zMaster, 0); + sqlite3DbFree(db, zMaster); + return rc; + } + } + } + + /* Sync the master journal file. If the IOCAP_SEQUENTIAL device + ** flag is set this is not required. + */ + if( needSync + && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL) + && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL)) + ){ + sqlite3OsCloseFree(pMaster); + sqlite3OsDelete(pVfs, zMaster, 0); + sqlite3DbFree(db, zMaster); + return rc; + } + + /* Sync all the db files involved in the transaction. The same call + ** sets the master journal pointer in each individual journal. If + ** an error occurs here, do not delete the master journal file. + ** + ** If the error occurs during the first call to + ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the + ** master journal file will be orphaned. But we cannot delete it, + ** in case the master journal file name was written into the journal + ** file before the failure occurred. + */ + for(i=0; rc==SQLITE_OK && inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster); + } + } + sqlite3OsCloseFree(pMaster); + assert( rc!=SQLITE_BUSY ); + if( rc!=SQLITE_OK ){ + sqlite3DbFree(db, zMaster); + return rc; + } + + /* Delete the master journal file. This commits the transaction. After + ** doing this the directory is synced again before any individual + ** transaction files are deleted. + */ + rc = sqlite3OsDelete(pVfs, zMaster, 1); + sqlite3DbFree(db, zMaster); + zMaster = 0; + if( rc ){ + return rc; + } + + /* All files and directories have already been synced, so the following + ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and + ** deleting or truncating journals. If something goes wrong while + ** this is happening we don't really care. The integrity of the + ** transaction is already guaranteed, but some stray 'cold' journals + ** may be lying around. Returning an error code won't help matters. + */ + disable_simulated_io_errors(); + sqlite3BeginBenignMalloc(); + for(i=0; inDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + sqlite3BtreeCommitPhaseTwo(pBt, 1); + } + } + sqlite3EndBenignMalloc(); + enable_simulated_io_errors(); + + sqlite3VtabCommit(db); + } +#endif + + return rc; +} + +/* +** This routine checks that the sqlite3.nVdbeActive count variable +** matches the number of vdbe's in the list sqlite3.pVdbe that are +** currently active. An assertion fails if the two counts do not match. +** This is an internal self-check only - it is not an essential processing +** step. +** +** This is a no-op if NDEBUG is defined. +*/ +#ifndef NDEBUG +static void checkActiveVdbeCnt(sqlite3 *db){ + Vdbe *p; + int cnt = 0; + int nWrite = 0; + int nRead = 0; + p = db->pVdbe; + while( p ){ + if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){ + cnt++; + if( p->readOnly==0 ) nWrite++; + if( p->bIsReader ) nRead++; + } + p = p->pNext; + } + assert( cnt==db->nVdbeActive ); + assert( nWrite==db->nVdbeWrite ); + assert( nRead==db->nVdbeRead ); +} +#else +#define checkActiveVdbeCnt(x) +#endif + +/* +** If the Vdbe passed as the first argument opened a statement-transaction, +** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or +** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement +** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the +** statement transaction is committed. +** +** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. +** Otherwise SQLITE_OK. +*/ +int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){ + sqlite3 *const db = p->db; + int rc = SQLITE_OK; + + /* If p->iStatement is greater than zero, then this Vdbe opened a + ** statement transaction that should be closed here. The only exception + ** is that an IO error may have occurred, causing an emergency rollback. + ** In this case (db->nStatement==0), and there is nothing to do. + */ + if( db->nStatement && p->iStatement ){ + int i; + const int iSavepoint = p->iStatement-1; + + assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE); + assert( db->nStatement>0 ); + assert( p->iStatement==(db->nStatement+db->nSavepoint) ); + + for(i=0; inDb; i++){ + int rc2 = SQLITE_OK; + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + if( eOp==SAVEPOINT_ROLLBACK ){ + rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint); + } + if( rc2==SQLITE_OK ){ + rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint); + } + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + db->nStatement--; + p->iStatement = 0; + + if( rc==SQLITE_OK ){ + if( eOp==SAVEPOINT_ROLLBACK ){ + rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint); + } + if( rc==SQLITE_OK ){ + rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint); + } + } + + /* If the statement transaction is being rolled back, also restore the + ** database handles deferred constraint counter to the value it had when + ** the statement transaction was opened. */ + if( eOp==SAVEPOINT_ROLLBACK ){ + db->nDeferredCons = p->nStmtDefCons; + db->nDeferredImmCons = p->nStmtDefImmCons; + } + } + return rc; +} + +/* +** This function is called when a transaction opened by the database +** handle associated with the VM passed as an argument is about to be +** committed. If there are outstanding deferred foreign key constraint +** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK. +** +** If there are outstanding FK violations and this function returns +** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY +** and write an error message to it. Then return SQLITE_ERROR. +*/ +#ifndef SQLITE_OMIT_FOREIGN_KEY +int sqlite3VdbeCheckFk(Vdbe *p, int deferred){ + sqlite3 *db = p->db; + if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) + || (!deferred && p->nFkConstraint>0) + ){ + p->rc = SQLITE_CONSTRAINT_FOREIGNKEY; + p->errorAction = OE_Abort; + sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed"); + return SQLITE_ERROR; + } + return SQLITE_OK; +} +#endif + +/* +** This routine is called the when a VDBE tries to halt. If the VDBE +** has made changes and is in autocommit mode, then commit those +** changes. If a rollback is needed, then do the rollback. +** +** This routine is the only way to move the state of a VM from +** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to +** call this on a VM that is in the SQLITE_MAGIC_HALT state. +** +** Return an error code. If the commit could not complete because of +** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it +** means the close did not happen and needs to be repeated. +*/ +int sqlite3VdbeHalt(Vdbe *p){ + int rc; /* Used to store transient return codes */ + sqlite3 *db = p->db; + + /* This function contains the logic that determines if a statement or + ** transaction will be committed or rolled back as a result of the + ** execution of this virtual machine. + ** + ** If any of the following errors occur: + ** + ** SQLITE_NOMEM + ** SQLITE_IOERR + ** SQLITE_FULL + ** SQLITE_INTERRUPT + ** + ** Then the internal cache might have been left in an inconsistent + ** state. We need to rollback the statement transaction, if there is + ** one, or the complete transaction if there is no statement transaction. + */ + + if( p->db->mallocFailed ){ + p->rc = SQLITE_NOMEM; + } + if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag); + closeAllCursors(p); + if( p->magic!=VDBE_MAGIC_RUN ){ + return SQLITE_OK; + } + checkActiveVdbeCnt(db); + + /* No commit or rollback needed if the program never started or if the + ** SQL statement does not read or write a database file. */ + if( p->pc>=0 && p->bIsReader ){ + int mrc; /* Primary error code from p->rc */ + int eStatementOp = 0; + int isSpecialError; /* Set to true if a 'special' error */ + + /* Lock all btrees used by the statement */ + sqlite3VdbeEnter(p); + + /* Check for one of the special errors */ + mrc = p->rc & 0xff; + assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */ + isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR + || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL; + if( isSpecialError ){ + /* If the query was read-only and the error code is SQLITE_INTERRUPT, + ** no rollback is necessary. Otherwise, at least a savepoint + ** transaction must be rolled back to restore the database to a + ** consistent state. + ** + ** Even if the statement is read-only, it is important to perform + ** a statement or transaction rollback operation. If the error + ** occurred while writing to the journal, sub-journal or database + ** file as part of an effort to free up cache space (see function + ** pagerStress() in pager.c), the rollback is required to restore + ** the pager to a consistent state. + */ + if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){ + if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){ + eStatementOp = SAVEPOINT_ROLLBACK; + }else{ + /* We are forced to roll back the active transaction. Before doing + ** so, abort any other statements this handle currently has active. + */ + sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + sqlite3CloseSavepoints(db); + db->autoCommit = 1; + } + } + } + + /* Check for immediate foreign key violations. */ + if( p->rc==SQLITE_OK ){ + sqlite3VdbeCheckFk(p, 0); + } + + /* If the auto-commit flag is set and this is the only active writer + ** VM, then we do either a commit or rollback of the current transaction. + ** + ** Note: This block also runs if one of the special errors handled + ** above has occurred. + */ + if( !sqlite3VtabInSync(db) + && db->autoCommit + && db->nVdbeWrite==(p->readOnly==0) + ){ + if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ + rc = sqlite3VdbeCheckFk(p, 1); + if( rc!=SQLITE_OK ){ + if( NEVER(p->readOnly) ){ + sqlite3VdbeLeave(p); + return SQLITE_ERROR; + } + rc = SQLITE_CONSTRAINT_FOREIGNKEY; + }else{ + /* The auto-commit flag is true, the vdbe program was successful + ** or hit an 'OR FAIL' constraint and there are no deferred foreign + ** key constraints to hold up the transaction. This means a commit + ** is required. */ + rc = vdbeCommit(db, p); + } + if( rc==SQLITE_BUSY && p->readOnly ){ + sqlite3VdbeLeave(p); + return SQLITE_BUSY; + }else if( rc!=SQLITE_OK ){ + p->rc = rc; + sqlite3RollbackAll(db, SQLITE_OK); + }else{ + db->nDeferredCons = 0; + db->nDeferredImmCons = 0; + db->flags &= ~SQLITE_DeferFKs; + sqlite3CommitInternalChanges(db); + } + }else{ + sqlite3RollbackAll(db, SQLITE_OK); + } + db->nStatement = 0; + }else if( eStatementOp==0 ){ + if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){ + eStatementOp = SAVEPOINT_RELEASE; + }else if( p->errorAction==OE_Abort ){ + eStatementOp = SAVEPOINT_ROLLBACK; + }else{ + sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + sqlite3CloseSavepoints(db); + db->autoCommit = 1; + } + } + + /* If eStatementOp is non-zero, then a statement transaction needs to + ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to + ** do so. If this operation returns an error, and the current statement + ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the + ** current statement error code. + */ + if( eStatementOp ){ + rc = sqlite3VdbeCloseStatement(p, eStatementOp); + if( rc ){ + if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){ + p->rc = rc; + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = 0; + } + sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + sqlite3CloseSavepoints(db); + db->autoCommit = 1; + } + } + + /* If this was an INSERT, UPDATE or DELETE and no statement transaction + ** has been rolled back, update the database connection change-counter. + */ + if( p->changeCntOn ){ + if( eStatementOp!=SAVEPOINT_ROLLBACK ){ + sqlite3VdbeSetChanges(db, p->nChange); + }else{ + sqlite3VdbeSetChanges(db, 0); + } + p->nChange = 0; + } + + /* Release the locks */ + sqlite3VdbeLeave(p); + } + + /* We have successfully halted and closed the VM. Record this fact. */ + if( p->pc>=0 ){ + db->nVdbeActive--; + if( !p->readOnly ) db->nVdbeWrite--; + if( p->bIsReader ) db->nVdbeRead--; + assert( db->nVdbeActive>=db->nVdbeRead ); + assert( db->nVdbeRead>=db->nVdbeWrite ); + assert( db->nVdbeWrite>=0 ); + } + p->magic = VDBE_MAGIC_HALT; + checkActiveVdbeCnt(db); + if( p->db->mallocFailed ){ + p->rc = SQLITE_NOMEM; + } + + /* If the auto-commit flag is set to true, then any locks that were held + ** by connection db have now been released. Call sqlite3ConnectionUnlocked() + ** to invoke any required unlock-notify callbacks. + */ + if( db->autoCommit ){ + sqlite3ConnectionUnlocked(db); + } + + assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 ); + return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK); +} + + +/* +** Each VDBE holds the result of the most recent sqlite3_step() call +** in p->rc. This routine sets that result back to SQLITE_OK. +*/ +void sqlite3VdbeResetStepResult(Vdbe *p){ + p->rc = SQLITE_OK; +} + +/* +** Copy the error code and error message belonging to the VDBE passed +** as the first argument to its database handle (so that they will be +** returned by calls to sqlite3_errcode() and sqlite3_errmsg()). +** +** This function does not clear the VDBE error code or message, just +** copies them to the database handle. +*/ +int sqlite3VdbeTransferError(Vdbe *p){ + sqlite3 *db = p->db; + int rc = p->rc; + if( p->zErrMsg ){ + u8 mallocFailed = db->mallocFailed; + sqlite3BeginBenignMalloc(); + sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); + sqlite3EndBenignMalloc(); + db->mallocFailed = mallocFailed; + db->errCode = rc; + }else{ + sqlite3Error(db, rc, 0); + } + return rc; +} + +#ifdef SQLITE_ENABLE_SQLLOG +/* +** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, +** invoke it. +*/ +static void vdbeInvokeSqllog(Vdbe *v){ + if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){ + char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql); + assert( v->db->init.busy==0 ); + if( zExpanded ){ + sqlite3GlobalConfig.xSqllog( + sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1 + ); + sqlite3DbFree(v->db, zExpanded); + } + } +} +#else +# define vdbeInvokeSqllog(x) +#endif + +/* +** Clean up a VDBE after execution but do not delete the VDBE just yet. +** Write any error messages into *pzErrMsg. Return the result code. +** +** After this routine is run, the VDBE should be ready to be executed +** again. +** +** To look at it another way, this routine resets the state of the +** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to +** VDBE_MAGIC_INIT. +*/ +int sqlite3VdbeReset(Vdbe *p){ + sqlite3 *db; + db = p->db; + + /* If the VM did not run to completion or if it encountered an + ** error, then it might not have been halted properly. So halt + ** it now. + */ + sqlite3VdbeHalt(p); + + /* If the VDBE has be run even partially, then transfer the error code + ** and error message from the VDBE into the main database structure. But + ** if the VDBE has just been set to run but has not actually executed any + ** instructions yet, leave the main database error information unchanged. + */ + if( p->pc>=0 ){ + vdbeInvokeSqllog(p); + sqlite3VdbeTransferError(p); + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = 0; + if( p->runOnlyOnce ) p->expired = 1; + }else if( p->rc && p->expired ){ + /* The expired flag was set on the VDBE before the first call + ** to sqlite3_step(). For consistency (since sqlite3_step() was + ** called), set the database error in this case as well. + */ + sqlite3Error(db, p->rc, 0); + sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = 0; + } + + /* Reclaim all memory used by the VDBE + */ + Cleanup(p); + + /* Save profiling information from this VDBE run. + */ +#ifdef VDBE_PROFILE + { + FILE *out = fopen("vdbe_profile.out", "a"); + if( out ){ + int i; + fprintf(out, "---- "); + for(i=0; inOp; i++){ + fprintf(out, "%02x", p->aOp[i].opcode); + } + fprintf(out, "\n"); + for(i=0; inOp; i++){ + fprintf(out, "%6d %10lld %8lld ", + p->aOp[i].cnt, + p->aOp[i].cycles, + p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0 + ); + sqlite3VdbePrintOp(out, i, &p->aOp[i]); + } + fclose(out); + } + } +#endif + p->iCurrentTime = 0; + p->magic = VDBE_MAGIC_INIT; + return p->rc & db->errMask; +} + +/* +** Clean up and delete a VDBE after execution. Return an integer which is +** the result code. Write any error message text into *pzErrMsg. +*/ +int sqlite3VdbeFinalize(Vdbe *p){ + int rc = SQLITE_OK; + if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){ + rc = sqlite3VdbeReset(p); + assert( (rc & p->db->errMask)==rc ); + } + sqlite3VdbeDelete(p); + return rc; +} + +/* +** If parameter iOp is less than zero, then invoke the destructor for +** all auxiliary data pointers currently cached by the VM passed as +** the first argument. +** +** Or, if iOp is greater than or equal to zero, then the destructor is +** only invoked for those auxiliary data pointers created by the user +** function invoked by the OP_Function opcode at instruction iOp of +** VM pVdbe, and only then if: +** +** * the associated function parameter is the 32nd or later (counting +** from left to right), or +** +** * the corresponding bit in argument mask is clear (where the first +** function parameter corrsponds to bit 0 etc.). +*/ +void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){ + AuxData **pp = &pVdbe->pAuxData; + while( *pp ){ + AuxData *pAux = *pp; + if( (iOp<0) + || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & ((u32)1<iArg)))) + ){ + if( pAux->xDelete ){ + pAux->xDelete(pAux->pAux); + } + *pp = pAux->pNext; + sqlite3DbFree(pVdbe->db, pAux); + }else{ + pp= &pAux->pNext; + } + } +} + +/* +** Free all memory associated with the Vdbe passed as the second argument, +** except for object itself, which is preserved. +** +** The difference between this function and sqlite3VdbeDelete() is that +** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with +** the database connection and frees the object itself. +*/ +void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){ + SubProgram *pSub, *pNext; + int i; + assert( p->db==0 || p->db==db ); + releaseMemArray(p->aVar, p->nVar); + releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); + for(pSub=p->pProgram; pSub; pSub=pNext){ + pNext = pSub->pNext; + vdbeFreeOpArray(db, pSub->aOp, pSub->nOp); + sqlite3DbFree(db, pSub); + } + for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]); + vdbeFreeOpArray(db, p->aOp, p->nOp); + sqlite3DbFree(db, p->aLabel); + sqlite3DbFree(db, p->aColName); + sqlite3DbFree(db, p->zSql); + sqlite3DbFree(db, p->pFree); +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) + sqlite3DbFree(db, p->zExplain); + sqlite3DbFree(db, p->pExplain); +#endif +} + +/* +** Delete an entire VDBE. +*/ +void sqlite3VdbeDelete(Vdbe *p){ + sqlite3 *db; + + if( NEVER(p==0) ) return; + db = p->db; + assert( sqlite3_mutex_held(db->mutex) ); + sqlite3VdbeClearObject(db, p); + if( p->pPrev ){ + p->pPrev->pNext = p->pNext; + }else{ + assert( db->pVdbe==p ); + db->pVdbe = p->pNext; + } + if( p->pNext ){ + p->pNext->pPrev = p->pPrev; + } + p->magic = VDBE_MAGIC_DEAD; + p->db = 0; + sqlite3DbFree(db, p); +} + +/* +** Make sure the cursor p is ready to read or write the row to which it +** was last positioned. Return an error code if an OOM fault or I/O error +** prevents us from positioning the cursor to its correct position. +** +** If a MoveTo operation is pending on the given cursor, then do that +** MoveTo now. If no move is pending, check to see if the row has been +** deleted out from under the cursor and if it has, mark the row as +** a NULL row. +** +** If the cursor is already pointing to the correct row and that row has +** not been deleted out from under the cursor, then this routine is a no-op. +*/ +int sqlite3VdbeCursorMoveto(VdbeCursor *p){ + if( p->deferredMoveto ){ + int res, rc; +#ifdef SQLITE_TEST + extern int sqlite3_search_count; +#endif + assert( p->isTable ); + rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res); + if( rc ) return rc; + p->lastRowid = p->movetoTarget; + if( res!=0 ) return SQLITE_CORRUPT_BKPT; + p->rowidIsValid = 1; +#ifdef SQLITE_TEST + sqlite3_search_count++; +#endif + p->deferredMoveto = 0; + p->cacheStatus = CACHE_STALE; + }else if( ALWAYS(p->pCursor) ){ + int hasMoved; + int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved); + if( rc ) return rc; + if( hasMoved ){ + p->cacheStatus = CACHE_STALE; + p->nullRow = 1; + } + } + return SQLITE_OK; +} + +/* +** The following functions: +** +** sqlite3VdbeSerialType() +** sqlite3VdbeSerialTypeLen() +** sqlite3VdbeSerialLen() +** sqlite3VdbeSerialPut() +** sqlite3VdbeSerialGet() +** +** encapsulate the code that serializes values for storage in SQLite +** data and index records. Each serialized value consists of a +** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned +** integer, stored as a varint. +** +** In an SQLite index record, the serial type is stored directly before +** the blob of data that it corresponds to. In a table record, all serial +** types are stored at the start of the record, and the blobs of data at +** the end. Hence these functions allow the caller to handle the +** serial-type and data blob separately. +** +** The following table describes the various storage classes for data: +** +** serial type bytes of data type +** -------------- --------------- --------------- +** 0 0 NULL +** 1 1 signed integer +** 2 2 signed integer +** 3 3 signed integer +** 4 4 signed integer +** 5 6 signed integer +** 6 8 signed integer +** 7 8 IEEE float +** 8 0 Integer constant 0 +** 9 0 Integer constant 1 +** 10,11 reserved for expansion +** N>=12 and even (N-12)/2 BLOB +** N>=13 and odd (N-13)/2 text +** +** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions +** of SQLite will not understand those serial types. +*/ + +/* +** Return the serial-type for the value stored in pMem. +*/ +u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){ + int flags = pMem->flags; + int n; + + if( flags&MEM_Null ){ + return 0; + } + if( flags&MEM_Int ){ + /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */ +# define MAX_6BYTE ((((i64)0x00008000)<<32)-1) + i64 i = pMem->u.i; + u64 u; + if( i<0 ){ + if( i<(-MAX_6BYTE) ) return 6; + /* Previous test prevents: u = -(-9223372036854775808) */ + u = -i; + }else{ + u = i; + } + if( u<=127 ){ + return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1; + } + if( u<=32767 ) return 2; + if( u<=8388607 ) return 3; + if( u<=2147483647 ) return 4; + if( u<=MAX_6BYTE ) return 5; + return 6; + } + if( flags&MEM_Real ){ + return 7; + } + assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) ); + n = pMem->n; + if( flags & MEM_Zero ){ + n += pMem->u.nZero; + } + assert( n>=0 ); + return ((n*2) + 12 + ((flags&MEM_Str)!=0)); +} + +/* +** Return the length of the data corresponding to the supplied serial-type. +*/ +u32 sqlite3VdbeSerialTypeLen(u32 serial_type){ + if( serial_type>=12 ){ + return (serial_type-12)/2; + }else{ + static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 }; + return aSize[serial_type]; + } +} + +/* +** If we are on an architecture with mixed-endian floating +** points (ex: ARM7) then swap the lower 4 bytes with the +** upper 4 bytes. Return the result. +** +** For most architectures, this is a no-op. +** +** (later): It is reported to me that the mixed-endian problem +** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems +** that early versions of GCC stored the two words of a 64-bit +** float in the wrong order. And that error has been propagated +** ever since. The blame is not necessarily with GCC, though. +** GCC might have just copying the problem from a prior compiler. +** I am also told that newer versions of GCC that follow a different +** ABI get the byte order right. +** +** Developers using SQLite on an ARM7 should compile and run their +** application using -DSQLITE_DEBUG=1 at least once. With DEBUG +** enabled, some asserts below will ensure that the byte order of +** floating point values is correct. +** +** (2007-08-30) Frank van Vugt has studied this problem closely +** and has send his findings to the SQLite developers. Frank +** writes that some Linux kernels offer floating point hardware +** emulation that uses only 32-bit mantissas instead of a full +** 48-bits as required by the IEEE standard. (This is the +** CONFIG_FPE_FASTFPE option.) On such systems, floating point +** byte swapping becomes very complicated. To avoid problems, +** the necessary byte swapping is carried out using a 64-bit integer +** rather than a 64-bit float. Frank assures us that the code here +** works for him. We, the developers, have no way to independently +** verify this, but Frank seems to know what he is talking about +** so we trust him. +*/ +#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT +static u64 floatSwap(u64 in){ + union { + u64 r; + u32 i[2]; + } u; + u32 t; + + u.r = in; + t = u.i[0]; + u.i[0] = u.i[1]; + u.i[1] = t; + return u.r; +} +# define swapMixedEndianFloat(X) X = floatSwap(X) +#else +# define swapMixedEndianFloat(X) +#endif + +/* +** Write the serialized data blob for the value stored in pMem into +** buf. It is assumed that the caller has allocated sufficient space. +** Return the number of bytes written. +** +** nBuf is the amount of space left in buf[]. nBuf must always be +** large enough to hold the entire field. Except, if the field is +** a blob with a zero-filled tail, then buf[] might be just the right +** size to hold everything except for the zero-filled tail. If buf[] +** is only big enough to hold the non-zero prefix, then only write that +** prefix into buf[]. But if buf[] is large enough to hold both the +** prefix and the tail then write the prefix and set the tail to all +** zeros. +** +** Return the number of bytes actually written into buf[]. The number +** of bytes in the zero-filled tail is included in the return value only +** if those bytes were zeroed in buf[]. +*/ +u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){ + u32 serial_type = sqlite3VdbeSerialType(pMem, file_format); + u32 len; + + /* Integer and Real */ + if( serial_type<=7 && serial_type>0 ){ + u64 v; + u32 i; + if( serial_type==7 ){ + assert( sizeof(v)==sizeof(pMem->r) ); + memcpy(&v, &pMem->r, sizeof(v)); + swapMixedEndianFloat(v); + }else{ + v = pMem->u.i; + } + len = i = sqlite3VdbeSerialTypeLen(serial_type); + assert( len<=(u32)nBuf ); + while( i-- ){ + buf[i] = (u8)(v&0xFF); + v >>= 8; + } + return len; + } + + /* String or blob */ + if( serial_type>=12 ){ + assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0) + == (int)sqlite3VdbeSerialTypeLen(serial_type) ); + assert( pMem->n<=nBuf ); + len = pMem->n; + memcpy(buf, pMem->z, len); + if( pMem->flags & MEM_Zero ){ + len += pMem->u.nZero; + assert( nBuf>=0 ); + if( len > (u32)nBuf ){ + len = (u32)nBuf; + } + memset(&buf[pMem->n], 0, len-pMem->n); + } + return len; + } + + /* NULL or constants 0 or 1 */ + return 0; +} + +/* +** Deserialize the data blob pointed to by buf as serial type serial_type +** and store the result in pMem. Return the number of bytes read. +*/ +u32 sqlite3VdbeSerialGet( + const unsigned char *buf, /* Buffer to deserialize from */ + u32 serial_type, /* Serial type to deserialize */ + Mem *pMem /* Memory cell to write value into */ +){ + switch( serial_type ){ + case 10: /* Reserved for future use */ + case 11: /* Reserved for future use */ + case 0: { /* NULL */ + pMem->flags = MEM_Null; + break; + } + case 1: { /* 1-byte signed integer */ + pMem->u.i = (signed char)buf[0]; + pMem->flags = MEM_Int; + return 1; + } + case 2: { /* 2-byte signed integer */ + pMem->u.i = (((signed char)buf[0])<<8) | buf[1]; + pMem->flags = MEM_Int; + return 2; + } + case 3: { /* 3-byte signed integer */ + pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2]; + pMem->flags = MEM_Int; + return 3; + } + case 4: { /* 4-byte signed integer */ + pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3]; + pMem->flags = MEM_Int; + return 4; + } + case 5: { /* 6-byte signed integer */ + u64 x = (((signed char)buf[0])<<8) | buf[1]; + u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5]; + x = (x<<32) | y; + pMem->u.i = *(i64*)&x; + pMem->flags = MEM_Int; + return 6; + } + case 6: /* 8-byte signed integer */ + case 7: { /* IEEE floating point */ + u64 x; + u32 y; +#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT) + /* Verify that integers and floating point values use the same + ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is + ** defined that 64-bit floating point values really are mixed + ** endian. + */ + static const u64 t1 = ((u64)0x3ff00000)<<32; + static const double r1 = 1.0; + u64 t2 = t1; + swapMixedEndianFloat(t2); + assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 ); +#endif + + x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3]; + y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7]; + x = (x<<32) | y; + if( serial_type==6 ){ + pMem->u.i = *(i64*)&x; + pMem->flags = MEM_Int; + }else{ + assert( sizeof(x)==8 && sizeof(pMem->r)==8 ); + swapMixedEndianFloat(x); + memcpy(&pMem->r, &x, sizeof(x)); + pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real; + } + return 8; + } + case 8: /* Integer 0 */ + case 9: { /* Integer 1 */ + pMem->u.i = serial_type-8; + pMem->flags = MEM_Int; + return 0; + } + default: { + u32 len = (serial_type-12)/2; + pMem->z = (char *)buf; + pMem->n = len; + pMem->xDel = 0; + if( serial_type&0x01 ){ + pMem->flags = MEM_Str | MEM_Ephem; + }else{ + pMem->flags = MEM_Blob | MEM_Ephem; + } + return len; + } + } + return 0; +} + +/* +** This routine is used to allocate sufficient space for an UnpackedRecord +** structure large enough to be used with sqlite3VdbeRecordUnpack() if +** the first argument is a pointer to KeyInfo structure pKeyInfo. +** +** The space is either allocated using sqlite3DbMallocRaw() or from within +** the unaligned buffer passed via the second and third arguments (presumably +** stack space). If the former, then *ppFree is set to a pointer that should +** be eventually freed by the caller using sqlite3DbFree(). Or, if the +** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL +** before returning. +** +** If an OOM error occurs, NULL is returned. +*/ +UnpackedRecord *sqlite3VdbeAllocUnpackedRecord( + KeyInfo *pKeyInfo, /* Description of the record */ + char *pSpace, /* Unaligned space available */ + int szSpace, /* Size of pSpace[] in bytes */ + char **ppFree /* OUT: Caller should free this pointer */ +){ + UnpackedRecord *p; /* Unpacked record to return */ + int nOff; /* Increment pSpace by nOff to align it */ + int nByte; /* Number of bytes required for *p */ + + /* We want to shift the pointer pSpace up such that it is 8-byte aligned. + ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift + ** it by. If pSpace is already 8-byte aligned, nOff should be zero. + */ + nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7; + nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1); + if( nByte>szSpace+nOff ){ + p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte); + *ppFree = (char *)p; + if( !p ) return 0; + }else{ + p = (UnpackedRecord*)&pSpace[nOff]; + *ppFree = 0; + } + + p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))]; + assert( pKeyInfo->aSortOrder!=0 ); + p->pKeyInfo = pKeyInfo; + p->nField = pKeyInfo->nField + 1; + return p; +} + +/* +** Given the nKey-byte encoding of a record in pKey[], populate the +** UnpackedRecord structure indicated by the fourth argument with the +** contents of the decoded record. +*/ +void sqlite3VdbeRecordUnpack( + KeyInfo *pKeyInfo, /* Information about the record format */ + int nKey, /* Size of the binary record */ + const void *pKey, /* The binary record */ + UnpackedRecord *p /* Populate this structure before returning. */ +){ + const unsigned char *aKey = (const unsigned char *)pKey; + int d; + u32 idx; /* Offset in aKey[] to read from */ + u16 u; /* Unsigned loop counter */ + u32 szHdr; + Mem *pMem = p->aMem; + + p->flags = 0; + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + idx = getVarint32(aKey, szHdr); + d = szHdr; + u = 0; + while( idxnField && d<=nKey ){ + u32 serial_type; + + idx += getVarint32(&aKey[idx], serial_type); + pMem->enc = pKeyInfo->enc; + pMem->db = pKeyInfo->db; + /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */ + pMem->zMalloc = 0; + d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem); + pMem++; + u++; + } + assert( u<=pKeyInfo->nField + 1 ); + p->nField = u; +} + +/* +** This function compares the two table rows or index records +** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero +** or positive integer if key1 is less than, equal to or +** greater than key2. The {nKey1, pKey1} key must be a blob +** created by th OP_MakeRecord opcode of the VDBE. The pPKey2 +** key must be a parsed key such as obtained from +** sqlite3VdbeParseRecord. +** +** Key1 and Key2 do not have to contain the same number of fields. +** The key with fewer fields is usually compares less than the +** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set +** and the common prefixes are equal, then key1 is less than key2. +** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are +** equal, then the keys are considered to be equal and +** the parts beyond the common prefix are ignored. +*/ +int sqlite3VdbeRecordCompare( + int nKey1, const void *pKey1, /* Left key */ + UnpackedRecord *pPKey2 /* Right key */ +){ + u32 d1; /* Offset into aKey[] of next data element */ + u32 idx1; /* Offset into aKey[] of next header element */ + u32 szHdr1; /* Number of bytes in header */ + int i = 0; + int rc = 0; + const unsigned char *aKey1 = (const unsigned char *)pKey1; + KeyInfo *pKeyInfo; + Mem mem1; + + pKeyInfo = pPKey2->pKeyInfo; + mem1.enc = pKeyInfo->enc; + mem1.db = pKeyInfo->db; + /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */ + VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */ + + /* Compilers may complain that mem1.u.i is potentially uninitialized. + ** We could initialize it, as shown here, to silence those complaints. + ** But in fact, mem1.u.i will never actually be used uninitialized, and doing + ** the unnecessary initialization has a measurable negative performance + ** impact, since this routine is a very high runner. And so, we choose + ** to ignore the compiler warnings and leave this variable uninitialized. + */ + /* mem1.u.i = 0; // not needed, here to silence compiler warning */ + + idx1 = getVarint32(aKey1, szHdr1); + d1 = szHdr1; + assert( pKeyInfo->nField+1>=pPKey2->nField ); + assert( pKeyInfo->aSortOrder!=0 ); + while( idx1nField ){ + u32 serial_type1; + + /* Read the serial types for the next element in each key. */ + idx1 += getVarint32( aKey1+idx1, serial_type1 ); + + /* Verify that there is enough key space remaining to avoid + ** a buffer overread. The "d1+serial_type1+2" subexpression will + ** always be greater than or equal to the amount of required key space. + ** Use that approximation to avoid the more expensive call to + ** sqlite3VdbeSerialTypeLen() in the common case. + */ + if( d1+serial_type1+2>(u32)nKey1 + && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 + ){ + break; + } + + /* Extract the values to be compared. + */ + d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1); + + /* Do the comparison + */ + rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]); + if( rc!=0 ){ + assert( mem1.zMalloc==0 ); /* See comment below */ + + /* Invert the result if we are using DESC sort order. */ + if( pKeyInfo->aSortOrder[i] ){ + rc = -rc; + } + + /* If the PREFIX_SEARCH flag is set and all fields except the final + ** rowid field were equal, then clear the PREFIX_SEARCH flag and set + ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1). + ** This is used by the OP_IsUnique opcode. + */ + if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){ + assert( idx1==szHdr1 && rc ); + assert( mem1.flags & MEM_Int ); + pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH; + pPKey2->rowid = mem1.u.i; + } + + return rc; + } + i++; + } + + /* No memory allocation is ever used on mem1. Prove this using + ** the following assert(). If the assert() fails, it indicates a + ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). + */ + assert( mem1.zMalloc==0 ); + + /* rc==0 here means that one of the keys ran out of fields and + ** all the fields up to that point were equal. If the UNPACKED_INCRKEY + ** flag is set, then break the tie by treating key2 as larger. + ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes + ** are considered to be equal. Otherwise, the longer key is the + ** larger. As it happens, the pPKey2 will always be the longer + ** if there is a difference. + */ + assert( rc==0 ); + if( pPKey2->flags & UNPACKED_INCRKEY ){ + rc = -1; + }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){ + /* Leave rc==0 */ + }else if( idx1m.n) ){ + goto idx_rowid_corruption; + } + + /* The last field of the index should be an integer - the ROWID. + ** Verify that the last entry really is an integer. */ + (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid); + testcase( typeRowid==1 ); + testcase( typeRowid==2 ); + testcase( typeRowid==3 ); + testcase( typeRowid==4 ); + testcase( typeRowid==5 ); + testcase( typeRowid==6 ); + testcase( typeRowid==8 ); + testcase( typeRowid==9 ); + if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){ + goto idx_rowid_corruption; + } + lenRowid = sqlite3VdbeSerialTypeLen(typeRowid); + testcase( (u32)m.n==szHdr+lenRowid ); + if( unlikely((u32)m.npCursor; + Mem m; + + assert( sqlite3BtreeCursorIsValid(pCur) ); + VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey); + assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */ + /* nCellKey will always be between 0 and 0xffffffff because of the say + ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */ + if( nCellKey<=0 || nCellKey>0x7fffffff ){ + *res = 0; + return SQLITE_CORRUPT_BKPT; + } + memset(&m, 0, sizeof(m)); + rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m); + if( rc ){ + return rc; + } + assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH ); + *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked); + sqlite3VdbeMemRelease(&m); + return SQLITE_OK; +} + +/* +** This routine sets the value to be returned by subsequent calls to +** sqlite3_changes() on the database handle 'db'. +*/ +void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){ + assert( sqlite3_mutex_held(db->mutex) ); + db->nChange = nChange; + db->nTotalChange += nChange; +} + +/* +** Set a flag in the vdbe to update the change counter when it is finalised +** or reset. +*/ +void sqlite3VdbeCountChanges(Vdbe *v){ + v->changeCntOn = 1; +} + +/* +** Mark every prepared statement associated with a database connection +** as expired. +** +** An expired statement means that recompilation of the statement is +** recommend. Statements expire when things happen that make their +** programs obsolete. Removing user-defined functions or collating +** sequences, or changing an authorization function are the types of +** things that make prepared statements obsolete. +*/ +void sqlite3ExpirePreparedStatements(sqlite3 *db){ + Vdbe *p; + for(p = db->pVdbe; p; p=p->pNext){ + p->expired = 1; + } +} + +/* +** Return the database associated with the Vdbe. +*/ +sqlite3 *sqlite3VdbeDb(Vdbe *v){ + return v->db; +} + +/* +** Return a pointer to an sqlite3_value structure containing the value bound +** parameter iVar of VM v. Except, if the value is an SQL NULL, return +** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_* +** constants) to the value before returning it. +** +** The returned value must be freed by the caller using sqlite3ValueFree(). +*/ +sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){ + assert( iVar>0 ); + if( v ){ + Mem *pMem = &v->aVar[iVar-1]; + if( 0==(pMem->flags & MEM_Null) ){ + sqlite3_value *pRet = sqlite3ValueNew(v->db); + if( pRet ){ + sqlite3VdbeMemCopy((Mem *)pRet, pMem); + sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8); + sqlite3VdbeMemStoreType((Mem *)pRet); + } + return pRet; + } + } + return 0; +} + +/* +** Configure SQL variable iVar so that binding a new value to it signals +** to sqlite3_reoptimize() that re-preparing the statement may result +** in a better query plan. +*/ +void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){ + assert( iVar>0 ); + if( iVar>32 ){ + v->expmask = 0xffffffff; + }else{ + v->expmask |= ((u32)1 << (iVar-1)); + } +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored +** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored +** in memory obtained from sqlite3DbMalloc). +*/ +void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){ + sqlite3 *db = p->db; + sqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg); + sqlite3_free(pVtab->zErrMsg); + pVtab->zErrMsg = 0; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ diff --git a/components/external/SQLite-3.8.1/src/vdbeblob.c b/components/external/SQLite-3.8.1/src/vdbeblob.c new file mode 100644 index 0000000000000000000000000000000000000000..2e8fd8ee7447e64646e3494b4c041d3a4abb0885 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vdbeblob.c @@ -0,0 +1,469 @@ +/* +** 2007 May 1 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used to implement incremental BLOB I/O. +*/ + +#include "sqliteInt.h" +#include "vdbeInt.h" + +#ifndef SQLITE_OMIT_INCRBLOB + +/* +** Valid sqlite3_blob* handles point to Incrblob structures. +*/ +typedef struct Incrblob Incrblob; +struct Incrblob { + int flags; /* Copy of "flags" passed to sqlite3_blob_open() */ + int nByte; /* Size of open blob, in bytes */ + int iOffset; /* Byte offset of blob in cursor data */ + int iCol; /* Table column this handle is open on */ + BtCursor *pCsr; /* Cursor pointing at blob row */ + sqlite3_stmt *pStmt; /* Statement holding cursor open */ + sqlite3 *db; /* The associated database */ +}; + + +/* +** This function is used by both blob_open() and blob_reopen(). It seeks +** the b-tree cursor associated with blob handle p to point to row iRow. +** If successful, SQLITE_OK is returned and subsequent calls to +** sqlite3_blob_read() or sqlite3_blob_write() access the specified row. +** +** If an error occurs, or if the specified row does not exist or does not +** contain a value of type TEXT or BLOB in the column nominated when the +** blob handle was opened, then an error code is returned and *pzErr may +** be set to point to a buffer containing an error message. It is the +** responsibility of the caller to free the error message buffer using +** sqlite3DbFree(). +** +** If an error does occur, then the b-tree cursor is closed. All subsequent +** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will +** immediately return SQLITE_ABORT. +*/ +static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){ + int rc; /* Error code */ + char *zErr = 0; /* Error message */ + Vdbe *v = (Vdbe *)p->pStmt; + + /* Set the value of the SQL statements only variable to integer iRow. + ** This is done directly instead of using sqlite3_bind_int64() to avoid + ** triggering asserts related to mutexes. + */ + assert( v->aVar[0].flags&MEM_Int ); + v->aVar[0].u.i = iRow; + + rc = sqlite3_step(p->pStmt); + if( rc==SQLITE_ROW ){ + u32 type = v->apCsr[0]->aType[p->iCol]; + if( type<12 ){ + zErr = sqlite3MPrintf(p->db, "cannot open value of type %s", + type==0?"null": type==7?"real": "integer" + ); + rc = SQLITE_ERROR; + sqlite3_finalize(p->pStmt); + p->pStmt = 0; + }else{ + p->iOffset = v->apCsr[0]->aOffset[p->iCol]; + p->nByte = sqlite3VdbeSerialTypeLen(type); + p->pCsr = v->apCsr[0]->pCursor; + sqlite3BtreeEnterCursor(p->pCsr); + sqlite3BtreeCacheOverflow(p->pCsr); + sqlite3BtreeLeaveCursor(p->pCsr); + } + } + + if( rc==SQLITE_ROW ){ + rc = SQLITE_OK; + }else if( p->pStmt ){ + rc = sqlite3_finalize(p->pStmt); + p->pStmt = 0; + if( rc==SQLITE_OK ){ + zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow); + rc = SQLITE_ERROR; + }else{ + zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db)); + } + } + + assert( rc!=SQLITE_OK || zErr==0 ); + assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE ); + + *pzErr = zErr; + return rc; +} + +/* +** Open a blob handle. +*/ +int sqlite3_blob_open( + sqlite3* db, /* The database connection */ + const char *zDb, /* The attached database containing the blob */ + const char *zTable, /* The table containing the blob */ + const char *zColumn, /* The column containing the blob */ + sqlite_int64 iRow, /* The row containing the glob */ + int flags, /* True -> read/write access, false -> read-only */ + sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */ +){ + int nAttempt = 0; + int iCol; /* Index of zColumn in row-record */ + + /* This VDBE program seeks a btree cursor to the identified + ** db/table/row entry. The reason for using a vdbe program instead + ** of writing code to use the b-tree layer directly is that the + ** vdbe program will take advantage of the various transaction, + ** locking and error handling infrastructure built into the vdbe. + ** + ** After seeking the cursor, the vdbe executes an OP_ResultRow. + ** Code external to the Vdbe then "borrows" the b-tree cursor and + ** uses it to implement the blob_read(), blob_write() and + ** blob_bytes() functions. + ** + ** The sqlite3_blob_close() function finalizes the vdbe program, + ** which closes the b-tree cursor and (possibly) commits the + ** transaction. + */ + static const VdbeOpList openBlob[] = { + {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */ + {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */ + {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */ + + /* One of the following two instructions is replaced by an OP_Noop. */ + {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */ + {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */ + + {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */ + {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */ + {OP_Column, 0, 0, 1}, /* 7 */ + {OP_ResultRow, 1, 0, 0}, /* 8 */ + {OP_Goto, 0, 5, 0}, /* 9 */ + {OP_Close, 0, 0, 0}, /* 10 */ + {OP_Halt, 0, 0, 0}, /* 11 */ + }; + + int rc = SQLITE_OK; + char *zErr = 0; + Table *pTab; + Parse *pParse = 0; + Incrblob *pBlob = 0; + + flags = !!flags; /* flags = (flags ? 1 : 0); */ + *ppBlob = 0; + + sqlite3_mutex_enter(db->mutex); + + pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob)); + if( !pBlob ) goto blob_open_out; + pParse = sqlite3StackAllocRaw(db, sizeof(*pParse)); + if( !pParse ) goto blob_open_out; + + do { + memset(pParse, 0, sizeof(Parse)); + pParse->db = db; + sqlite3DbFree(db, zErr); + zErr = 0; + + sqlite3BtreeEnterAll(db); + pTab = sqlite3LocateTable(pParse, 0, zTable, zDb); + if( pTab && IsVirtual(pTab) ){ + pTab = 0; + sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable); + } +#ifndef SQLITE_OMIT_VIEW + if( pTab && pTab->pSelect ){ + pTab = 0; + sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable); + } +#endif + if( !pTab ){ + if( pParse->zErrMsg ){ + sqlite3DbFree(db, zErr); + zErr = pParse->zErrMsg; + pParse->zErrMsg = 0; + } + rc = SQLITE_ERROR; + sqlite3BtreeLeaveAll(db); + goto blob_open_out; + } + + /* Now search pTab for the exact column. */ + for(iCol=0; iColnCol; iCol++) { + if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){ + break; + } + } + if( iCol==pTab->nCol ){ + sqlite3DbFree(db, zErr); + zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn); + rc = SQLITE_ERROR; + sqlite3BtreeLeaveAll(db); + goto blob_open_out; + } + + /* If the value is being opened for writing, check that the + ** column is not indexed, and that it is not part of a foreign key. + ** It is against the rules to open a column to which either of these + ** descriptions applies for writing. */ + if( flags ){ + const char *zFault = 0; + Index *pIdx; +#ifndef SQLITE_OMIT_FOREIGN_KEY + if( db->flags&SQLITE_ForeignKeys ){ + /* Check that the column is not part of an FK child key definition. It + ** is not necessary to check if it is part of a parent key, as parent + ** key columns must be indexed. The check below will pick up this + ** case. */ + FKey *pFKey; + for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ + int j; + for(j=0; jnCol; j++){ + if( pFKey->aCol[j].iFrom==iCol ){ + zFault = "foreign key"; + } + } + } + } +#endif + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + int j; + for(j=0; jnColumn; j++){ + if( pIdx->aiColumn[j]==iCol ){ + zFault = "indexed"; + } + } + } + if( zFault ){ + sqlite3DbFree(db, zErr); + zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault); + rc = SQLITE_ERROR; + sqlite3BtreeLeaveAll(db); + goto blob_open_out; + } + } + + pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db); + assert( pBlob->pStmt || db->mallocFailed ); + if( pBlob->pStmt ){ + Vdbe *v = (Vdbe *)pBlob->pStmt; + int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + + sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob); + + + /* Configure the OP_Transaction */ + sqlite3VdbeChangeP1(v, 0, iDb); + sqlite3VdbeChangeP2(v, 0, flags); + + /* Configure the OP_VerifyCookie */ + sqlite3VdbeChangeP1(v, 1, iDb); + sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie); + sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration); + + /* Make sure a mutex is held on the table to be accessed */ + sqlite3VdbeUsesBtree(v, iDb); + + /* Configure the OP_TableLock instruction */ +#ifdef SQLITE_OMIT_SHARED_CACHE + sqlite3VdbeChangeToNoop(v, 2); +#else + sqlite3VdbeChangeP1(v, 2, iDb); + sqlite3VdbeChangeP2(v, 2, pTab->tnum); + sqlite3VdbeChangeP3(v, 2, flags); + sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT); +#endif + + /* Remove either the OP_OpenWrite or OpenRead. Set the P2 + ** parameter of the other to pTab->tnum. */ + sqlite3VdbeChangeToNoop(v, 4 - flags); + sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum); + sqlite3VdbeChangeP3(v, 3 + flags, iDb); + + /* Configure the number of columns. Configure the cursor to + ** think that the table has one more column than it really + ** does. An OP_Column to retrieve this imaginary column will + ** always return an SQL NULL. This is useful because it means + ** we can invoke OP_Column to fill in the vdbe cursors type + ** and offset cache without causing any IO. + */ + sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32); + sqlite3VdbeChangeP2(v, 7, pTab->nCol); + if( !db->mallocFailed ){ + pParse->nVar = 1; + pParse->nMem = 1; + pParse->nTab = 1; + sqlite3VdbeMakeReady(v, pParse); + } + } + + pBlob->flags = flags; + pBlob->iCol = iCol; + pBlob->db = db; + sqlite3BtreeLeaveAll(db); + if( db->mallocFailed ){ + goto blob_open_out; + } + sqlite3_bind_int64(pBlob->pStmt, 1, iRow); + rc = blobSeekToRow(pBlob, iRow, &zErr); + } while( (++nAttempt)mallocFailed==0 ){ + *ppBlob = (sqlite3_blob *)pBlob; + }else{ + if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt); + sqlite3DbFree(db, pBlob); + } + sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr); + sqlite3DbFree(db, zErr); + sqlite3StackFree(db, pParse); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Close a blob handle that was previously created using +** sqlite3_blob_open(). +*/ +int sqlite3_blob_close(sqlite3_blob *pBlob){ + Incrblob *p = (Incrblob *)pBlob; + int rc; + sqlite3 *db; + + if( p ){ + db = p->db; + sqlite3_mutex_enter(db->mutex); + rc = sqlite3_finalize(p->pStmt); + sqlite3DbFree(db, p); + sqlite3_mutex_leave(db->mutex); + }else{ + rc = SQLITE_OK; + } + return rc; +} + +/* +** Perform a read or write operation on a blob +*/ +static int blobReadWrite( + sqlite3_blob *pBlob, + void *z, + int n, + int iOffset, + int (*xCall)(BtCursor*, u32, u32, void*) +){ + int rc; + Incrblob *p = (Incrblob *)pBlob; + Vdbe *v; + sqlite3 *db; + + if( p==0 ) return SQLITE_MISUSE_BKPT; + db = p->db; + sqlite3_mutex_enter(db->mutex); + v = (Vdbe*)p->pStmt; + + if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){ + /* Request is out of range. Return a transient error. */ + rc = SQLITE_ERROR; + sqlite3Error(db, SQLITE_ERROR, 0); + }else if( v==0 ){ + /* If there is no statement handle, then the blob-handle has + ** already been invalidated. Return SQLITE_ABORT in this case. + */ + rc = SQLITE_ABORT; + }else{ + /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is + ** returned, clean-up the statement handle. + */ + assert( db == v->db ); + sqlite3BtreeEnterCursor(p->pCsr); + rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); + sqlite3BtreeLeaveCursor(p->pCsr); + if( rc==SQLITE_ABORT ){ + sqlite3VdbeFinalize(v); + p->pStmt = 0; + }else{ + db->errCode = rc; + v->rc = rc; + } + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** Read data from a blob handle. +*/ +int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){ + return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData); +} + +/* +** Write data to a blob handle. +*/ +int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){ + return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData); +} + +/* +** Query a blob handle for the size of the data. +** +** The Incrblob.nByte field is fixed for the lifetime of the Incrblob +** so no mutex is required for access. +*/ +int sqlite3_blob_bytes(sqlite3_blob *pBlob){ + Incrblob *p = (Incrblob *)pBlob; + return (p && p->pStmt) ? p->nByte : 0; +} + +/* +** Move an existing blob handle to point to a different row of the same +** database table. +** +** If an error occurs, or if the specified row does not exist or does not +** contain a blob or text value, then an error code is returned and the +** database handle error code and message set. If this happens, then all +** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) +** immediately return SQLITE_ABORT. +*/ +int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){ + int rc; + Incrblob *p = (Incrblob *)pBlob; + sqlite3 *db; + + if( p==0 ) return SQLITE_MISUSE_BKPT; + db = p->db; + sqlite3_mutex_enter(db->mutex); + + if( p->pStmt==0 ){ + /* If there is no statement handle, then the blob-handle has + ** already been invalidated. Return SQLITE_ABORT in this case. + */ + rc = SQLITE_ABORT; + }else{ + char *zErr; + rc = blobSeekToRow(p, iRow, &zErr); + if( rc!=SQLITE_OK ){ + sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr); + sqlite3DbFree(db, zErr); + } + assert( rc!=SQLITE_SCHEMA ); + } + + rc = sqlite3ApiExit(db, rc); + assert( rc==SQLITE_OK || p->pStmt==0 ); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#endif /* #ifndef SQLITE_OMIT_INCRBLOB */ diff --git a/components/external/SQLite-3.8.1/src/vdbemem.c b/components/external/SQLite-3.8.1/src/vdbemem.c new file mode 100644 index 0000000000000000000000000000000000000000..b549c4a31ac74cd536dcbbed2904dc1955db6977 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vdbemem.c @@ -0,0 +1,1413 @@ +/* +** 2004 May 26 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code use to manipulate "Mem" structure. A "Mem" +** stores a single value in the VDBE. Mem is an opaque structure visible +** only within the VDBE. Interface routines refer to a Mem using the +** name sqlite_value +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" + +/* +** If pMem is an object with a valid string representation, this routine +** ensures the internal encoding for the string representation is +** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE. +** +** If pMem is not a string object, or the encoding of the string +** representation is already stored using the requested encoding, then this +** routine is a no-op. +** +** SQLITE_OK is returned if the conversion is successful (or not required). +** SQLITE_NOMEM may be returned if a malloc() fails during conversion +** between formats. +*/ +int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){ +#ifndef SQLITE_OMIT_UTF16 + int rc; +#endif + assert( (pMem->flags&MEM_RowSet)==0 ); + assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE + || desiredEnc==SQLITE_UTF16BE ); + if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){ + return SQLITE_OK; + } + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); +#ifdef SQLITE_OMIT_UTF16 + return SQLITE_ERROR; +#else + + /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned, + ** then the encoding of the value may not have changed. + */ + rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc); + assert(rc==SQLITE_OK || rc==SQLITE_NOMEM); + assert(rc==SQLITE_OK || pMem->enc!=desiredEnc); + assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc); + return rc; +#endif +} + +/* +** Make sure pMem->z points to a writable allocation of at least +** n bytes. +** +** If the third argument passed to this function is true, then memory +** cell pMem must contain a string or blob. In this case the content is +** preserved. Otherwise, if the third parameter to this function is false, +** any current string or blob value may be discarded. +** +** This function sets the MEM_Dyn flag and clears any xDel callback. +** It also clears MEM_Ephem and MEM_Static. If the preserve flag is +** not set, Mem.n is zeroed. +*/ +int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){ + assert( 1 >= + ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) + + (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + + ((pMem->flags&MEM_Ephem) ? 1 : 0) + + ((pMem->flags&MEM_Static) ? 1 : 0) + ); + assert( (pMem->flags&MEM_RowSet)==0 ); + + /* If the preserve flag is set to true, then the memory cell must already + ** contain a valid string or blob value. */ + assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) ); + + if( n<32 ) n = 32; + if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)z==pMem->zMalloc ){ + pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n); + preserve = 0; + }else{ + sqlite3DbFree(pMem->db, pMem->zMalloc); + pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n); + } + } + + if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){ + memcpy(pMem->zMalloc, pMem->z, pMem->n); + } + if( pMem->flags&MEM_Dyn && pMem->xDel ){ + assert( pMem->xDel!=SQLITE_DYNAMIC ); + pMem->xDel((void *)(pMem->z)); + } + + pMem->z = pMem->zMalloc; + if( pMem->z==0 ){ + pMem->flags = MEM_Null; + }else{ + pMem->flags &= ~(MEM_Ephem|MEM_Static); + } + pMem->xDel = 0; + return (pMem->z ? SQLITE_OK : SQLITE_NOMEM); +} + +/* +** Make the given Mem object MEM_Dyn. In other words, make it so +** that any TEXT or BLOB content is stored in memory obtained from +** malloc(). In this way, we know that the memory is safe to be +** overwritten or altered. +** +** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails. +*/ +int sqlite3VdbeMemMakeWriteable(Mem *pMem){ + int f; + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( (pMem->flags&MEM_RowSet)==0 ); + ExpandBlob(pMem); + f = pMem->flags; + if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){ + if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){ + return SQLITE_NOMEM; + } + pMem->z[pMem->n] = 0; + pMem->z[pMem->n+1] = 0; + pMem->flags |= MEM_Term; +#ifdef SQLITE_DEBUG + pMem->pScopyFrom = 0; +#endif + } + + return SQLITE_OK; +} + +/* +** If the given Mem* has a zero-filled tail, turn it into an ordinary +** blob stored in dynamically allocated space. +*/ +#ifndef SQLITE_OMIT_INCRBLOB +int sqlite3VdbeMemExpandBlob(Mem *pMem){ + if( pMem->flags & MEM_Zero ){ + int nByte; + assert( pMem->flags&MEM_Blob ); + assert( (pMem->flags&MEM_RowSet)==0 ); + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + + /* Set nByte to the number of bytes required to store the expanded blob. */ + nByte = pMem->n + pMem->u.nZero; + if( nByte<=0 ){ + nByte = 1; + } + if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){ + return SQLITE_NOMEM; + } + + memset(&pMem->z[pMem->n], 0, pMem->u.nZero); + pMem->n += pMem->u.nZero; + pMem->flags &= ~(MEM_Zero|MEM_Term); + } + return SQLITE_OK; +} +#endif + + +/* +** Make sure the given Mem is \u0000 terminated. +*/ +int sqlite3VdbeMemNulTerminate(Mem *pMem){ + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){ + return SQLITE_OK; /* Nothing to do */ + } + if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){ + return SQLITE_NOMEM; + } + pMem->z[pMem->n] = 0; + pMem->z[pMem->n+1] = 0; + pMem->flags |= MEM_Term; + return SQLITE_OK; +} + +/* +** Add MEM_Str to the set of representations for the given Mem. Numbers +** are converted using sqlite3_snprintf(). Converting a BLOB to a string +** is a no-op. +** +** Existing representations MEM_Int and MEM_Real are *not* invalidated. +** +** A MEM_Null value will never be passed to this function. This function is +** used for converting values to text for returning to the user (i.e. via +** sqlite3_value_text()), or for ensuring that values to be used as btree +** keys are strings. In the former case a NULL pointer is returned the +** user and the later is an internal programming error. +*/ +int sqlite3VdbeMemStringify(Mem *pMem, int enc){ + int rc = SQLITE_OK; + int fg = pMem->flags; + const int nByte = 32; + + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( !(fg&MEM_Zero) ); + assert( !(fg&(MEM_Str|MEM_Blob)) ); + assert( fg&(MEM_Int|MEM_Real) ); + assert( (pMem->flags&MEM_RowSet)==0 ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + + + if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){ + return SQLITE_NOMEM; + } + + /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8 + ** string representation of the value. Then, if the required encoding + ** is UTF-16le or UTF-16be do a translation. + ** + ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16. + */ + if( fg & MEM_Int ){ + sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i); + }else{ + assert( fg & MEM_Real ); + sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r); + } + pMem->n = sqlite3Strlen30(pMem->z); + pMem->enc = SQLITE_UTF8; + pMem->flags |= MEM_Str|MEM_Term; + sqlite3VdbeChangeEncoding(pMem, enc); + return rc; +} + +/* +** Memory cell pMem contains the context of an aggregate function. +** This routine calls the finalize method for that function. The +** result of the aggregate is stored back into pMem. +** +** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK +** otherwise. +*/ +int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){ + int rc = SQLITE_OK; + if( ALWAYS(pFunc && pFunc->xFinalize) ){ + sqlite3_context ctx; + assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef ); + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + memset(&ctx, 0, sizeof(ctx)); + ctx.s.flags = MEM_Null; + ctx.s.db = pMem->db; + ctx.pMem = pMem; + ctx.pFunc = pFunc; + pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */ + assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel ); + sqlite3DbFree(pMem->db, pMem->zMalloc); + memcpy(pMem, &ctx.s, sizeof(ctx.s)); + rc = ctx.isError; + } + return rc; +} + +/* +** If the memory cell contains a string value that must be freed by +** invoking an external callback, free it now. Calling this function +** does not free any Mem.zMalloc buffer. +*/ +void sqlite3VdbeMemReleaseExternal(Mem *p){ + assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) ); + if( p->flags&MEM_Agg ){ + sqlite3VdbeMemFinalize(p, p->u.pDef); + assert( (p->flags & MEM_Agg)==0 ); + sqlite3VdbeMemRelease(p); + }else if( p->flags&MEM_Dyn && p->xDel ){ + assert( (p->flags&MEM_RowSet)==0 ); + assert( p->xDel!=SQLITE_DYNAMIC ); + p->xDel((void *)p->z); + p->xDel = 0; + }else if( p->flags&MEM_RowSet ){ + sqlite3RowSetClear(p->u.pRowSet); + }else if( p->flags&MEM_Frame ){ + sqlite3VdbeMemSetNull(p); + } +} + +/* +** Release any memory held by the Mem. This may leave the Mem in an +** inconsistent state, for example with (Mem.z==0) and +** (Mem.type==SQLITE_TEXT). +*/ +void sqlite3VdbeMemRelease(Mem *p){ + VdbeMemRelease(p); + sqlite3DbFree(p->db, p->zMalloc); + p->z = 0; + p->zMalloc = 0; + p->xDel = 0; +} + +/* +** Convert a 64-bit IEEE double into a 64-bit signed integer. +** If the double is too large, return 0x8000000000000000. +** +** Most systems appear to do this simply by assigning +** variables and without the extra range tests. But +** there are reports that windows throws an expection +** if the floating point value is out of range. (See ticket #2880.) +** Because we do not completely understand the problem, we will +** take the conservative approach and always do range tests +** before attempting the conversion. +*/ +static i64 doubleToInt64(double r){ +#ifdef SQLITE_OMIT_FLOATING_POINT + /* When floating-point is omitted, double and int64 are the same thing */ + return r; +#else + /* + ** Many compilers we encounter do not define constants for the + ** minimum and maximum 64-bit integers, or they define them + ** inconsistently. And many do not understand the "LL" notation. + ** So we define our own static constants here using nothing + ** larger than a 32-bit integer constant. + */ + static const i64 maxInt = LARGEST_INT64; + static const i64 minInt = SMALLEST_INT64; + + if( r<(double)minInt ){ + return minInt; + }else if( r>(double)maxInt ){ + /* minInt is correct here - not maxInt. It turns out that assigning + ** a very large positive number to an integer results in a very large + ** negative integer. This makes no sense, but it is what x86 hardware + ** does so for compatibility we will do the same in software. */ + return minInt; + }else{ + return (i64)r; + } +#endif +} + +/* +** Return some kind of integer value which is the best we can do +** at representing the value that *pMem describes as an integer. +** If pMem is an integer, then the value is exact. If pMem is +** a floating-point then the value returned is the integer part. +** If pMem is a string or blob, then we make an attempt to convert +** it into a integer and return that. If pMem represents an +** an SQL-NULL value, return 0. +** +** If pMem represents a string value, its encoding might be changed. +*/ +i64 sqlite3VdbeIntValue(Mem *pMem){ + int flags; + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + flags = pMem->flags; + if( flags & MEM_Int ){ + return pMem->u.i; + }else if( flags & MEM_Real ){ + return doubleToInt64(pMem->r); + }else if( flags & (MEM_Str|MEM_Blob) ){ + i64 value = 0; + assert( pMem->z || pMem->n==0 ); + testcase( pMem->z==0 ); + sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc); + return value; + }else{ + return 0; + } +} + +/* +** Return the best representation of pMem that we can get into a +** double. If pMem is already a double or an integer, return its +** value. If it is a string or blob, try to convert it to a double. +** If it is a NULL, return 0.0. +*/ +double sqlite3VdbeRealValue(Mem *pMem){ + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + if( pMem->flags & MEM_Real ){ + return pMem->r; + }else if( pMem->flags & MEM_Int ){ + return (double)pMem->u.i; + }else if( pMem->flags & (MEM_Str|MEM_Blob) ){ + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + double val = (double)0; + sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc); + return val; + }else{ + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + return (double)0; + } +} + +/* +** The MEM structure is already a MEM_Real. Try to also make it a +** MEM_Int if we can. +*/ +void sqlite3VdbeIntegerAffinity(Mem *pMem){ + assert( pMem->flags & MEM_Real ); + assert( (pMem->flags & MEM_RowSet)==0 ); + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + + pMem->u.i = doubleToInt64(pMem->r); + + /* Only mark the value as an integer if + ** + ** (1) the round-trip conversion real->int->real is a no-op, and + ** (2) The integer is neither the largest nor the smallest + ** possible integer (ticket #3922) + ** + ** The second and third terms in the following conditional enforces + ** the second condition under the assumption that addition overflow causes + ** values to wrap around. On x86 hardware, the third term is always + ** true and could be omitted. But we leave it in because other + ** architectures might behave differently. + */ + if( pMem->r==(double)pMem->u.i + && pMem->u.i>SMALLEST_INT64 +#if defined(__i486__) || defined(__x86_64__) + && ALWAYS(pMem->u.iu.iflags |= MEM_Int; + } +} + +/* +** Convert pMem to type integer. Invalidate any prior representations. +*/ +int sqlite3VdbeMemIntegerify(Mem *pMem){ + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( (pMem->flags & MEM_RowSet)==0 ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + + pMem->u.i = sqlite3VdbeIntValue(pMem); + MemSetTypeFlag(pMem, MEM_Int); + return SQLITE_OK; +} + +/* +** Convert pMem so that it is of type MEM_Real. +** Invalidate any prior representations. +*/ +int sqlite3VdbeMemRealify(Mem *pMem){ + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( EIGHT_BYTE_ALIGNMENT(pMem) ); + + pMem->r = sqlite3VdbeRealValue(pMem); + MemSetTypeFlag(pMem, MEM_Real); + return SQLITE_OK; +} + +/* +** Convert pMem so that it has types MEM_Real or MEM_Int or both. +** Invalidate any prior representations. +** +** Every effort is made to force the conversion, even if the input +** is a string that does not look completely like a number. Convert +** as much of the string as we can and ignore the rest. +*/ +int sqlite3VdbeMemNumerify(Mem *pMem){ + if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){ + assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){ + MemSetTypeFlag(pMem, MEM_Int); + }else{ + pMem->r = sqlite3VdbeRealValue(pMem); + MemSetTypeFlag(pMem, MEM_Real); + sqlite3VdbeIntegerAffinity(pMem); + } + } + assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 ); + pMem->flags &= ~(MEM_Str|MEM_Blob); + return SQLITE_OK; +} + +/* +** Delete any previous value and set the value stored in *pMem to NULL. +*/ +void sqlite3VdbeMemSetNull(Mem *pMem){ + if( pMem->flags & MEM_Frame ){ + VdbeFrame *pFrame = pMem->u.pFrame; + pFrame->pParent = pFrame->v->pDelFrame; + pFrame->v->pDelFrame = pFrame; + } + if( pMem->flags & MEM_RowSet ){ + sqlite3RowSetClear(pMem->u.pRowSet); + } + MemSetTypeFlag(pMem, MEM_Null); + pMem->type = SQLITE_NULL; +} + +/* +** Delete any previous value and set the value to be a BLOB of length +** n containing all zeros. +*/ +void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){ + sqlite3VdbeMemRelease(pMem); + pMem->flags = MEM_Blob|MEM_Zero; + pMem->type = SQLITE_BLOB; + pMem->n = 0; + if( n<0 ) n = 0; + pMem->u.nZero = n; + pMem->enc = SQLITE_UTF8; + +#ifdef SQLITE_OMIT_INCRBLOB + sqlite3VdbeMemGrow(pMem, n, 0); + if( pMem->z ){ + pMem->n = n; + memset(pMem->z, 0, n); + } +#endif +} + +/* +** Delete any previous value and set the value stored in *pMem to val, +** manifest type INTEGER. +*/ +void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ + sqlite3VdbeMemRelease(pMem); + pMem->u.i = val; + pMem->flags = MEM_Int; + pMem->type = SQLITE_INTEGER; +} + +#ifndef SQLITE_OMIT_FLOATING_POINT +/* +** Delete any previous value and set the value stored in *pMem to val, +** manifest type REAL. +*/ +void sqlite3VdbeMemSetDouble(Mem *pMem, double val){ + if( sqlite3IsNaN(val) ){ + sqlite3VdbeMemSetNull(pMem); + }else{ + sqlite3VdbeMemRelease(pMem); + pMem->r = val; + pMem->flags = MEM_Real; + pMem->type = SQLITE_FLOAT; + } +} +#endif + +/* +** Delete any previous value and set the value of pMem to be an +** empty boolean index. +*/ +void sqlite3VdbeMemSetRowSet(Mem *pMem){ + sqlite3 *db = pMem->db; + assert( db!=0 ); + assert( (pMem->flags & MEM_RowSet)==0 ); + sqlite3VdbeMemRelease(pMem); + pMem->zMalloc = sqlite3DbMallocRaw(db, 64); + if( db->mallocFailed ){ + pMem->flags = MEM_Null; + }else{ + assert( pMem->zMalloc ); + pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, + sqlite3DbMallocSize(db, pMem->zMalloc)); + assert( pMem->u.pRowSet!=0 ); + pMem->flags = MEM_RowSet; + } +} + +/* +** Return true if the Mem object contains a TEXT or BLOB that is +** too large - whose size exceeds SQLITE_MAX_LENGTH. +*/ +int sqlite3VdbeMemTooBig(Mem *p){ + assert( p->db!=0 ); + if( p->flags & (MEM_Str|MEM_Blob) ){ + int n = p->n; + if( p->flags & MEM_Zero ){ + n += p->u.nZero; + } + return n>p->db->aLimit[SQLITE_LIMIT_LENGTH]; + } + return 0; +} + +#ifdef SQLITE_DEBUG +/* +** This routine prepares a memory cell for modication by breaking +** its link to a shallow copy and by marking any current shallow +** copies of this cell as invalid. +** +** This is used for testing and debugging only - to make sure shallow +** copies are not misused. +*/ +void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ + int i; + Mem *pX; + for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){ + if( pX->pScopyFrom==pMem ){ + pX->flags |= MEM_Invalid; + pX->pScopyFrom = 0; + } + } + pMem->pScopyFrom = 0; +} +#endif /* SQLITE_DEBUG */ + +/* +** Size of struct Mem not including the Mem.zMalloc member. +*/ +#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc)) + +/* +** Make an shallow copy of pFrom into pTo. Prior contents of +** pTo are freed. The pFrom->z field is not duplicated. If +** pFrom->z is used, then pTo->z points to the same thing as pFrom->z +** and flags gets srcType (either MEM_Ephem or MEM_Static). +*/ +void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){ + assert( (pFrom->flags & MEM_RowSet)==0 ); + VdbeMemRelease(pTo); + memcpy(pTo, pFrom, MEMCELLSIZE); + pTo->xDel = 0; + if( (pFrom->flags&MEM_Static)==0 ){ + pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem); + assert( srcType==MEM_Ephem || srcType==MEM_Static ); + pTo->flags |= srcType; + } +} + +/* +** Make a full copy of pFrom into pTo. Prior contents of pTo are +** freed before the copy is made. +*/ +int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ + int rc = SQLITE_OK; + + assert( (pFrom->flags & MEM_RowSet)==0 ); + VdbeMemRelease(pTo); + memcpy(pTo, pFrom, MEMCELLSIZE); + pTo->flags &= ~MEM_Dyn; + + if( pTo->flags&(MEM_Str|MEM_Blob) ){ + if( 0==(pFrom->flags&MEM_Static) ){ + pTo->flags |= MEM_Ephem; + rc = sqlite3VdbeMemMakeWriteable(pTo); + } + } + + return rc; +} + +/* +** Transfer the contents of pFrom to pTo. Any existing value in pTo is +** freed. If pFrom contains ephemeral data, a copy is made. +** +** pFrom contains an SQL NULL when this routine returns. +*/ +void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ + assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) ); + assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) ); + assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db ); + + sqlite3VdbeMemRelease(pTo); + memcpy(pTo, pFrom, sizeof(Mem)); + pFrom->flags = MEM_Null; + pFrom->xDel = 0; + pFrom->zMalloc = 0; +} + +/* +** Change the value of a Mem to be a string or a BLOB. +** +** The memory management strategy depends on the value of the xDel +** parameter. If the value passed is SQLITE_TRANSIENT, then the +** string is copied into a (possibly existing) buffer managed by the +** Mem structure. Otherwise, any existing buffer is freed and the +** pointer copied. +** +** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH +** size limit) then no memory allocation occurs. If the string can be +** stored without allocating memory, then it is. If a memory allocation +** is required to store the string, then value of pMem is unchanged. In +** either case, SQLITE_TOOBIG is returned. +*/ +int sqlite3VdbeMemSetStr( + Mem *pMem, /* Memory cell to set to string value */ + const char *z, /* String pointer */ + int n, /* Bytes in string, or negative */ + u8 enc, /* Encoding of z. 0 for BLOBs */ + void (*xDel)(void*) /* Destructor function */ +){ + int nByte = n; /* New value for pMem->n */ + int iLimit; /* Maximum allowed string or blob size */ + u16 flags = 0; /* New value for pMem->flags */ + + assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( (pMem->flags & MEM_RowSet)==0 ); + + /* If z is a NULL pointer, set pMem to contain an SQL NULL. */ + if( !z ){ + sqlite3VdbeMemSetNull(pMem); + return SQLITE_OK; + } + + if( pMem->db ){ + iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH]; + }else{ + iLimit = SQLITE_MAX_LENGTH; + } + flags = (enc==0?MEM_Blob:MEM_Str); + if( nByte<0 ){ + assert( enc!=0 ); + if( enc==SQLITE_UTF8 ){ + for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){} + }else{ + for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){} + } + flags |= MEM_Term; + } + + /* The following block sets the new values of Mem.z and Mem.xDel. It + ** also sets a flag in local variable "flags" to indicate the memory + ** management (one of MEM_Dyn or MEM_Static). + */ + if( xDel==SQLITE_TRANSIENT ){ + int nAlloc = nByte; + if( flags&MEM_Term ){ + nAlloc += (enc==SQLITE_UTF8?1:2); + } + if( nByte>iLimit ){ + return SQLITE_TOOBIG; + } + if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){ + return SQLITE_NOMEM; + } + memcpy(pMem->z, z, nAlloc); + }else if( xDel==SQLITE_DYNAMIC ){ + sqlite3VdbeMemRelease(pMem); + pMem->zMalloc = pMem->z = (char *)z; + pMem->xDel = 0; + }else{ + sqlite3VdbeMemRelease(pMem); + pMem->z = (char *)z; + pMem->xDel = xDel; + flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn); + } + + pMem->n = nByte; + pMem->flags = flags; + pMem->enc = (enc==0 ? SQLITE_UTF8 : enc); + pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT); + +#ifndef SQLITE_OMIT_UTF16 + if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){ + return SQLITE_NOMEM; + } +#endif + + if( nByte>iLimit ){ + return SQLITE_TOOBIG; + } + + return SQLITE_OK; +} + +/* +** Compare the values contained by the two memory cells, returning +** negative, zero or positive if pMem1 is less than, equal to, or greater +** than pMem2. Sorting order is NULL's first, followed by numbers (integers +** and reals) sorted numerically, followed by text ordered by the collating +** sequence pColl and finally blob's ordered by memcmp(). +** +** Two NULL values are considered equal by this function. +*/ +int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){ + int rc; + int f1, f2; + int combined_flags; + + f1 = pMem1->flags; + f2 = pMem2->flags; + combined_flags = f1|f2; + assert( (combined_flags & MEM_RowSet)==0 ); + + /* If one value is NULL, it is less than the other. If both values + ** are NULL, return 0. + */ + if( combined_flags&MEM_Null ){ + return (f2&MEM_Null) - (f1&MEM_Null); + } + + /* If one value is a number and the other is not, the number is less. + ** If both are numbers, compare as reals if one is a real, or as integers + ** if both values are integers. + */ + if( combined_flags&(MEM_Int|MEM_Real) ){ + double r1, r2; + if( (f1 & f2 & MEM_Int)!=0 ){ + if( pMem1->u.i < pMem2->u.i ) return -1; + if( pMem1->u.i > pMem2->u.i ) return 1; + return 0; + } + if( (f1&MEM_Real)!=0 ){ + r1 = pMem1->r; + }else if( (f1&MEM_Int)!=0 ){ + r1 = (double)pMem1->u.i; + }else{ + return 1; + } + if( (f2&MEM_Real)!=0 ){ + r2 = pMem2->r; + }else if( (f2&MEM_Int)!=0 ){ + r2 = (double)pMem2->u.i; + }else{ + return -1; + } + if( r1r2 ) return 1; + return 0; + } + + /* If one value is a string and the other is a blob, the string is less. + ** If both are strings, compare using the collating functions. + */ + if( combined_flags&MEM_Str ){ + if( (f1 & MEM_Str)==0 ){ + return 1; + } + if( (f2 & MEM_Str)==0 ){ + return -1; + } + + assert( pMem1->enc==pMem2->enc ); + assert( pMem1->enc==SQLITE_UTF8 || + pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE ); + + /* The collation sequence must be defined at this point, even if + ** the user deletes the collation sequence after the vdbe program is + ** compiled (this was not always the case). + */ + assert( !pColl || pColl->xCmp ); + + if( pColl ){ + if( pMem1->enc==pColl->enc ){ + /* The strings are already in the correct encoding. Call the + ** comparison function directly */ + return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z); + }else{ + const void *v1, *v2; + int n1, n2; + Mem c1; + Mem c2; + memset(&c1, 0, sizeof(c1)); + memset(&c2, 0, sizeof(c2)); + sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem); + sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem); + v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc); + n1 = v1==0 ? 0 : c1.n; + v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc); + n2 = v2==0 ? 0 : c2.n; + rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2); + sqlite3VdbeMemRelease(&c1); + sqlite3VdbeMemRelease(&c2); + return rc; + } + } + /* If a NULL pointer was passed as the collate function, fall through + ** to the blob case and use memcmp(). */ + } + + /* Both values must be blobs. Compare using memcmp(). */ + rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n); + if( rc==0 ){ + rc = pMem1->n - pMem2->n; + } + return rc; +} + +/* +** Move data out of a btree key or data field and into a Mem structure. +** The data or key is taken from the entry that pCur is currently pointing +** to. offset and amt determine what portion of the data or key to retrieve. +** key is true to get the key or false to get data. The result is written +** into the pMem element. +** +** The pMem structure is assumed to be uninitialized. Any prior content +** is overwritten without being freed. +** +** If this routine fails for any reason (malloc returns NULL or unable +** to read from the disk) then the pMem is left in an inconsistent state. +*/ +int sqlite3VdbeMemFromBtree( + BtCursor *pCur, /* Cursor pointing at record to retrieve. */ + int offset, /* Offset from the start of data to return bytes from. */ + int amt, /* Number of bytes to return. */ + int key, /* If true, retrieve from the btree key, not data. */ + Mem *pMem /* OUT: Return data in this Mem structure. */ +){ + char *zData; /* Data from the btree layer */ + int available = 0; /* Number of bytes available on the local btree page */ + int rc = SQLITE_OK; /* Return code */ + + assert( sqlite3BtreeCursorIsValid(pCur) ); + + /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() + ** that both the BtShared and database handle mutexes are held. */ + assert( (pMem->flags & MEM_RowSet)==0 ); + if( key ){ + zData = (char *)sqlite3BtreeKeyFetch(pCur, &available); + }else{ + zData = (char *)sqlite3BtreeDataFetch(pCur, &available); + } + assert( zData!=0 ); + + if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){ + sqlite3VdbeMemRelease(pMem); + pMem->z = &zData[offset]; + pMem->flags = MEM_Blob|MEM_Ephem; + }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){ + pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term; + pMem->enc = 0; + pMem->type = SQLITE_BLOB; + if( key ){ + rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z); + }else{ + rc = sqlite3BtreeData(pCur, offset, amt, pMem->z); + } + pMem->z[amt] = 0; + pMem->z[amt+1] = 0; + if( rc!=SQLITE_OK ){ + sqlite3VdbeMemRelease(pMem); + } + } + pMem->n = amt; + + return rc; +} + +/* This function is only available internally, it is not part of the +** external API. It works in a similar way to sqlite3_value_text(), +** except the data returned is in the encoding specified by the second +** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or +** SQLITE_UTF8. +** +** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED. +** If that is the case, then the result must be aligned on an even byte +** boundary. +*/ +const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){ + if( !pVal ) return 0; + + assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); + assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); + assert( (pVal->flags & MEM_RowSet)==0 ); + + if( pVal->flags&MEM_Null ){ + return 0; + } + assert( (MEM_Blob>>3) == MEM_Str ); + pVal->flags |= (pVal->flags & MEM_Blob)>>3; + ExpandBlob(pVal); + if( pVal->flags&MEM_Str ){ + sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED); + if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){ + assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 ); + if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){ + return 0; + } + } + sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */ + }else{ + assert( (pVal->flags&MEM_Blob)==0 ); + sqlite3VdbeMemStringify(pVal, enc); + assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) ); + } + assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0 + || pVal->db->mallocFailed ); + if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){ + return pVal->z; + }else{ + return 0; + } +} + +/* +** Create a new sqlite3_value object. +*/ +sqlite3_value *sqlite3ValueNew(sqlite3 *db){ + Mem *p = sqlite3DbMallocZero(db, sizeof(*p)); + if( p ){ + p->flags = MEM_Null; + p->type = SQLITE_NULL; + p->db = db; + } + return p; +} + +/* +** Context object passed by sqlite3Stat4ProbeSetValue() through to +** valueNew(). See comments above valueNew() for details. +*/ +struct ValueNewStat4Ctx { + Parse *pParse; + Index *pIdx; + UnpackedRecord **ppRec; + int iVal; +}; + +/* +** Allocate and return a pointer to a new sqlite3_value object. If +** the second argument to this function is NULL, the object is allocated +** by calling sqlite3ValueNew(). +** +** Otherwise, if the second argument is non-zero, then this function is +** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not +** already been allocated, allocate the UnpackedRecord structure that +** that function will return to its caller here. Then return a pointer +** an sqlite3_value within the UnpackedRecord.a[] array. +*/ +static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( p ){ + UnpackedRecord *pRec = p->ppRec[0]; + + if( pRec==0 ){ + Index *pIdx = p->pIdx; /* Index being probed */ + int nByte; /* Bytes of space to allocate */ + int i; /* Counter variable */ + int nCol = pIdx->nColumn+1; /* Number of index columns including rowid */ + + nByte = sizeof(Mem) * nCol + sizeof(UnpackedRecord); + pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte); + if( pRec ){ + pRec->pKeyInfo = sqlite3IndexKeyinfo(p->pParse, pIdx); + if( pRec->pKeyInfo ){ + assert( pRec->pKeyInfo->nField+1==nCol ); + pRec->pKeyInfo->enc = ENC(db); + pRec->flags = UNPACKED_PREFIX_MATCH; + pRec->aMem = (Mem *)&pRec[1]; + for(i=0; iaMem[i].flags = MEM_Null; + pRec->aMem[i].type = SQLITE_NULL; + pRec->aMem[i].db = db; + } + }else{ + sqlite3DbFree(db, pRec); + pRec = 0; + } + } + if( pRec==0 ) return 0; + p->ppRec[0] = pRec; + } + + pRec->nField = p->iVal+1; + return &pRec->aMem[p->iVal]; + } +#else + UNUSED_PARAMETER(p); +#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */ + return sqlite3ValueNew(db); +} + +/* +** Extract a value from the supplied expression in the manner described +** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object +** using valueNew(). +** +** If pCtx is NULL and an error occurs after the sqlite3_value object +** has been allocated, it is freed before returning. Or, if pCtx is not +** NULL, it is assumed that the caller will free any allocated object +** in all cases. +*/ +static int valueFromExpr( + sqlite3 *db, /* The database connection */ + Expr *pExpr, /* The expression to evaluate */ + u8 enc, /* Encoding to use */ + u8 affinity, /* Affinity to use */ + sqlite3_value **ppVal, /* Write the new value here */ + struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */ +){ + int op; + char *zVal = 0; + sqlite3_value *pVal = 0; + int negInt = 1; + const char *zNeg = ""; + int rc = SQLITE_OK; + + if( !pExpr ){ + *ppVal = 0; + return SQLITE_OK; + } + op = pExpr->op; + + /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT4. + ** The ifdef here is to enable us to achieve 100% branch test coverage even + ** when SQLITE_ENABLE_STAT4 is omitted. + */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( op==TK_REGISTER ) op = pExpr->op2; +#else + if( NEVER(op==TK_REGISTER) ) op = pExpr->op2; +#endif + + /* Handle negative integers in a single step. This is needed in the + ** case when the value is -9223372036854775808. + */ + if( op==TK_UMINUS + && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){ + pExpr = pExpr->pLeft; + op = pExpr->op; + negInt = -1; + zNeg = "-"; + } + + if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){ + pVal = valueNew(db, pCtx); + if( pVal==0 ) goto no_mem; + if( ExprHasProperty(pExpr, EP_IntValue) ){ + sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt); + }else{ + zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken); + if( zVal==0 ) goto no_mem; + sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC); + if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT; + } + if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){ + sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8); + }else{ + sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8); + } + if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str; + if( enc!=SQLITE_UTF8 ){ + rc = sqlite3VdbeChangeEncoding(pVal, enc); + } + }else if( op==TK_UMINUS ) { + /* This branch happens for multiple negative signs. Ex: -(-5) */ + if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) + && pVal!=0 + ){ + sqlite3VdbeMemNumerify(pVal); + if( pVal->u.i==SMALLEST_INT64 ){ + pVal->flags &= MEM_Int; + pVal->flags |= MEM_Real; + pVal->r = (double)LARGEST_INT64; + }else{ + pVal->u.i = -pVal->u.i; + } + pVal->r = -pVal->r; + sqlite3ValueApplyAffinity(pVal, affinity, enc); + } + }else if( op==TK_NULL ){ + pVal = valueNew(db, pCtx); + if( pVal==0 ) goto no_mem; + } +#ifndef SQLITE_OMIT_BLOB_LITERAL + else if( op==TK_BLOB ){ + int nVal; + assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); + assert( pExpr->u.zToken[1]=='\'' ); + pVal = valueNew(db, pCtx); + if( !pVal ) goto no_mem; + zVal = &pExpr->u.zToken[2]; + nVal = sqlite3Strlen30(zVal)-1; + assert( zVal[nVal]=='\'' ); + sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2, + 0, SQLITE_DYNAMIC); + } +#endif + + if( pVal ){ + sqlite3VdbeMemStoreType(pVal); + } + *ppVal = pVal; + return rc; + +no_mem: + db->mallocFailed = 1; + sqlite3DbFree(db, zVal); + assert( *ppVal==0 ); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( pCtx==0 ) sqlite3ValueFree(pVal); +#else + assert( pCtx==0 ); sqlite3ValueFree(pVal); +#endif + return SQLITE_NOMEM; +} + +/* +** Create a new sqlite3_value object, containing the value of pExpr. +** +** This only works for very simple expressions that consist of one constant +** token (i.e. "5", "5.1", "'a string'"). If the expression can +** be converted directly into a value, then the value is allocated and +** a pointer written to *ppVal. The caller is responsible for deallocating +** the value by passing it to sqlite3ValueFree() later on. If the expression +** cannot be converted to a value, then *ppVal is set to NULL. +*/ +int sqlite3ValueFromExpr( + sqlite3 *db, /* The database connection */ + Expr *pExpr, /* The expression to evaluate */ + u8 enc, /* Encoding to use */ + u8 affinity, /* Affinity to use */ + sqlite3_value **ppVal /* Write the new value here */ +){ + return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0); +} + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** The implementation of the sqlite_record() function. This function accepts +** a single argument of any type. The return value is a formatted database +** record (a blob) containing the argument value. +** +** This is used to convert the value stored in the 'sample' column of the +** sqlite_stat3 table to the record format SQLite uses internally. +*/ +static void recordFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const int file_format = 1; + int iSerial; /* Serial type */ + int nSerial; /* Bytes of space for iSerial as varint */ + int nVal; /* Bytes of space required for argv[0] */ + int nRet; + sqlite3 *db; + u8 *aRet; + + UNUSED_PARAMETER( argc ); + iSerial = sqlite3VdbeSerialType(argv[0], file_format); + nSerial = sqlite3VarintLen(iSerial); + nVal = sqlite3VdbeSerialTypeLen(iSerial); + db = sqlite3_context_db_handle(context); + + nRet = 1 + nSerial + nVal; + aRet = sqlite3DbMallocRaw(db, nRet); + if( aRet==0 ){ + sqlite3_result_error_nomem(context); + }else{ + aRet[0] = nSerial+1; + sqlite3PutVarint(&aRet[1], iSerial); + sqlite3VdbeSerialPut(&aRet[1+nSerial], nVal, argv[0], file_format); + sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT); + sqlite3DbFree(db, aRet); + } +} + +/* +** Register built-in functions used to help read ANALYZE data. +*/ +void sqlite3AnalyzeFunctions(void){ + static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = { + FUNCTION(sqlite_record, 1, 0, 0, recordFunc), + }; + int i; + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs); + for(i=0; idb; + + + struct ValueNewStat4Ctx alloc; + alloc.pParse = pParse; + alloc.pIdx = pIdx; + alloc.ppRec = ppRec; + alloc.iVal = iVal; + + /* Skip over any TK_COLLATE nodes */ + pExpr = sqlite3ExprSkipCollate(pExpr); + + if( !pExpr ){ + pVal = valueNew(db, &alloc); + if( pVal ){ + sqlite3VdbeMemSetNull((Mem*)pVal); + *pbOk = 1; + } + }else if( pExpr->op==TK_VARIABLE + || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE) + ){ + Vdbe *v; + int iBindVar = pExpr->iColumn; + sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar); + if( (v = pParse->pReprepare)!=0 ){ + pVal = valueNew(db, &alloc); + if( pVal ){ + rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]); + if( rc==SQLITE_OK ){ + sqlite3ValueApplyAffinity(pVal, affinity, ENC(db)); + } + pVal->db = pParse->db; + *pbOk = 1; + sqlite3VdbeMemStoreType((Mem*)pVal); + } + }else{ + *pbOk = 0; + } + }else{ + rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc); + *pbOk = (pVal!=0); + } + + assert( pVal==0 || pVal->db==db ); + return rc; +} + +/* +** Unless it is NULL, the argument must be an UnpackedRecord object returned +** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes +** the object. +*/ +void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){ + if( pRec ){ + int i; + int nCol = pRec->pKeyInfo->nField+1; + Mem *aMem = pRec->aMem; + sqlite3 *db = aMem[0].db; + for(i=0; ipKeyInfo); + sqlite3DbFree(db, pRec); + } +} +#endif /* ifdef SQLITE_ENABLE_STAT4 */ + +/* +** Change the string value of an sqlite3_value object +*/ +void sqlite3ValueSetStr( + sqlite3_value *v, /* Value to be set */ + int n, /* Length of string z */ + const void *z, /* Text of the new string */ + u8 enc, /* Encoding to use */ + void (*xDel)(void*) /* Destructor for the string */ +){ + if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel); +} + +/* +** Free an sqlite3_value object +*/ +void sqlite3ValueFree(sqlite3_value *v){ + if( !v ) return; + sqlite3VdbeMemRelease((Mem *)v); + sqlite3DbFree(((Mem*)v)->db, v); +} + +/* +** Return the number of bytes in the sqlite3_value object assuming +** that it uses the encoding "enc" +*/ +int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){ + Mem *p = (Mem*)pVal; + if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){ + if( p->flags & MEM_Zero ){ + return p->n + p->u.nZero; + }else{ + return p->n; + } + } + return 0; +} diff --git a/components/external/SQLite-3.8.1/src/vdbesort.c b/components/external/SQLite-3.8.1/src/vdbesort.c new file mode 100644 index 0000000000000000000000000000000000000000..c8709bdafd8e4e18e4e2658661b100b81a2105ab --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vdbesort.c @@ -0,0 +1,1038 @@ +/* +** 2011 July 9 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code for the VdbeSorter object, used in concert with +** a VdbeCursor to sort large numbers of keys (as may be required, for +** example, by CREATE INDEX statements on tables too large to fit in main +** memory). +*/ + +#include "sqliteInt.h" +#include "vdbeInt.h" + + +typedef struct VdbeSorterIter VdbeSorterIter; +typedef struct SorterRecord SorterRecord; +typedef struct FileWriter FileWriter; + +/* +** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES: +** +** As keys are added to the sorter, they are written to disk in a series +** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly +** the same as the cache-size allowed for temporary databases. In order +** to allow the caller to extract keys from the sorter in sorted order, +** all PMAs currently stored on disk must be merged together. This comment +** describes the data structure used to do so. The structure supports +** merging any number of arrays in a single pass with no redundant comparison +** operations. +** +** The aIter[] array contains an iterator for each of the PMAs being merged. +** An aIter[] iterator either points to a valid key or else is at EOF. For +** the purposes of the paragraphs below, we assume that the array is actually +** N elements in size, where N is the smallest power of 2 greater to or equal +** to the number of iterators being merged. The extra aIter[] elements are +** treated as if they are empty (always at EOF). +** +** The aTree[] array is also N elements in size. The value of N is stored in +** the VdbeSorter.nTree variable. +** +** The final (N/2) elements of aTree[] contain the results of comparing +** pairs of iterator keys together. Element i contains the result of +** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the +** aTree element is set to the index of it. +** +** For the purposes of this comparison, EOF is considered greater than any +** other key value. If the keys are equal (only possible with two EOF +** values), it doesn't matter which index is stored. +** +** The (N/4) elements of aTree[] that precede the final (N/2) described +** above contains the index of the smallest of each block of 4 iterators. +** And so on. So that aTree[1] contains the index of the iterator that +** currently points to the smallest key value. aTree[0] is unused. +** +** Example: +** +** aIter[0] -> Banana +** aIter[1] -> Feijoa +** aIter[2] -> Elderberry +** aIter[3] -> Currant +** aIter[4] -> Grapefruit +** aIter[5] -> Apple +** aIter[6] -> Durian +** aIter[7] -> EOF +** +** aTree[] = { X, 5 0, 5 0, 3, 5, 6 } +** +** The current element is "Apple" (the value of the key indicated by +** iterator 5). When the Next() operation is invoked, iterator 5 will +** be advanced to the next key in its segment. Say the next key is +** "Eggplant": +** +** aIter[5] -> Eggplant +** +** The contents of aTree[] are updated first by comparing the new iterator +** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator +** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree. +** The value of iterator 6 - "Durian" - is now smaller than that of iterator +** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (BananaaAlloc); + sqlite3DbFree(db, pIter->aBuffer); + memset(pIter, 0, sizeof(VdbeSorterIter)); +} + +/* +** Read nByte bytes of data from the stream of data iterated by object p. +** If successful, set *ppOut to point to a buffer containing the data +** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite +** error code. +** +** The buffer indicated by *ppOut may only be considered valid until the +** next call to this function. +*/ +static int vdbeSorterIterRead( + sqlite3 *db, /* Database handle (for malloc) */ + VdbeSorterIter *p, /* Iterator */ + int nByte, /* Bytes of data to read */ + u8 **ppOut /* OUT: Pointer to buffer containing data */ +){ + int iBuf; /* Offset within buffer to read from */ + int nAvail; /* Bytes of data available in buffer */ + assert( p->aBuffer ); + + /* If there is no more data to be read from the buffer, read the next + ** p->nBuffer bytes of data from the file into it. Or, if there are less + ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */ + iBuf = p->iReadOff % p->nBuffer; + if( iBuf==0 ){ + int nRead; /* Bytes to read from disk */ + int rc; /* sqlite3OsRead() return code */ + + /* Determine how many bytes of data to read. */ + if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){ + nRead = p->nBuffer; + }else{ + nRead = (int)(p->iEof - p->iReadOff); + } + assert( nRead>0 ); + + /* Read data from the file. Return early if an error occurs. */ + rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff); + assert( rc!=SQLITE_IOERR_SHORT_READ ); + if( rc!=SQLITE_OK ) return rc; + } + nAvail = p->nBuffer - iBuf; + + if( nByte<=nAvail ){ + /* The requested data is available in the in-memory buffer. In this + ** case there is no need to make a copy of the data, just return a + ** pointer into the buffer to the caller. */ + *ppOut = &p->aBuffer[iBuf]; + p->iReadOff += nByte; + }else{ + /* The requested data is not all available in the in-memory buffer. + ** In this case, allocate space at p->aAlloc[] to copy the requested + ** range into. Then return a copy of pointer p->aAlloc to the caller. */ + int nRem; /* Bytes remaining to copy */ + + /* Extend the p->aAlloc[] allocation if required. */ + if( p->nAllocnAlloc*2; + while( nByte>nNew ) nNew = nNew*2; + p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew); + if( !p->aAlloc ) return SQLITE_NOMEM; + p->nAlloc = nNew; + } + + /* Copy as much data as is available in the buffer into the start of + ** p->aAlloc[]. */ + memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail); + p->iReadOff += nAvail; + nRem = nByte - nAvail; + + /* The following loop copies up to p->nBuffer bytes per iteration into + ** the p->aAlloc[] buffer. */ + while( nRem>0 ){ + int rc; /* vdbeSorterIterRead() return code */ + int nCopy; /* Number of bytes to copy */ + u8 *aNext; /* Pointer to buffer to copy data from */ + + nCopy = nRem; + if( nRem>p->nBuffer ) nCopy = p->nBuffer; + rc = vdbeSorterIterRead(db, p, nCopy, &aNext); + if( rc!=SQLITE_OK ) return rc; + assert( aNext!=p->aAlloc ); + memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy); + nRem -= nCopy; + } + + *ppOut = p->aAlloc; + } + + return SQLITE_OK; +} + +/* +** Read a varint from the stream of data accessed by p. Set *pnOut to +** the value read. +*/ +static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){ + int iBuf; + + iBuf = p->iReadOff % p->nBuffer; + if( iBuf && (p->nBuffer-iBuf)>=9 ){ + p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut); + }else{ + u8 aVarint[16], *a; + int i = 0, rc; + do{ + rc = vdbeSorterIterRead(db, p, 1, &a); + if( rc ) return rc; + aVarint[(i++)&0xf] = a[0]; + }while( (a[0]&0x80)!=0 ); + sqlite3GetVarint(aVarint, pnOut); + } + + return SQLITE_OK; +} + + +/* +** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if +** no error occurs, or an SQLite error code if one does. +*/ +static int vdbeSorterIterNext( + sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */ + VdbeSorterIter *pIter /* Iterator to advance */ +){ + int rc; /* Return Code */ + u64 nRec = 0; /* Size of record in bytes */ + + if( pIter->iReadOff>=pIter->iEof ){ + /* This is an EOF condition */ + vdbeSorterIterZero(db, pIter); + return SQLITE_OK; + } + + rc = vdbeSorterIterVarint(db, pIter, &nRec); + if( rc==SQLITE_OK ){ + pIter->nKey = (int)nRec; + rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey); + } + + return rc; +} + +/* +** Initialize iterator pIter to scan through the PMA stored in file pFile +** starting at offset iStart and ending at offset iEof-1. This function +** leaves the iterator pointing to the first key in the PMA (or EOF if the +** PMA is empty). +*/ +static int vdbeSorterIterInit( + sqlite3 *db, /* Database handle */ + const VdbeSorter *pSorter, /* Sorter object */ + i64 iStart, /* Start offset in pFile */ + VdbeSorterIter *pIter, /* Iterator to populate */ + i64 *pnByte /* IN/OUT: Increment this value by PMA size */ +){ + int rc = SQLITE_OK; + int nBuf; + + nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt); + + assert( pSorter->iWriteOff>iStart ); + assert( pIter->aAlloc==0 ); + assert( pIter->aBuffer==0 ); + pIter->pFile = pSorter->pTemp1; + pIter->iReadOff = iStart; + pIter->nAlloc = 128; + pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc); + pIter->nBuffer = nBuf; + pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf); + + if( !pIter->aBuffer ){ + rc = SQLITE_NOMEM; + }else{ + int iBuf; + + iBuf = iStart % nBuf; + if( iBuf ){ + int nRead = nBuf - iBuf; + if( (iStart + nRead) > pSorter->iWriteOff ){ + nRead = (int)(pSorter->iWriteOff - iStart); + } + rc = sqlite3OsRead( + pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart + ); + assert( rc!=SQLITE_IOERR_SHORT_READ ); + } + + if( rc==SQLITE_OK ){ + u64 nByte; /* Size of PMA in bytes */ + pIter->iEof = pSorter->iWriteOff; + rc = vdbeSorterIterVarint(db, pIter, &nByte); + pIter->iEof = pIter->iReadOff + nByte; + *pnByte += nByte; + } + } + + if( rc==SQLITE_OK ){ + rc = vdbeSorterIterNext(db, pIter); + } + return rc; +} + + +/* +** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, +** size nKey2 bytes). Argument pKeyInfo supplies the collation functions +** used by the comparison. If an error occurs, return an SQLite error code. +** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive +** value, depending on whether key1 is smaller, equal to or larger than key2. +** +** If the bOmitRowid argument is non-zero, assume both keys end in a rowid +** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid +** is true and key1 contains even a single NULL value, it is considered to +** be less than key2. Even if key2 also contains NULL values. +** +** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace +** has been allocated and contains an unpacked record that is used as key2. +*/ +static void vdbeSorterCompare( + const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */ + int bOmitRowid, /* Ignore rowid field at end of keys */ + const void *pKey1, int nKey1, /* Left side of comparison */ + const void *pKey2, int nKey2, /* Right side of comparison */ + int *pRes /* OUT: Result of comparison */ +){ + KeyInfo *pKeyInfo = pCsr->pKeyInfo; + VdbeSorter *pSorter = pCsr->pSorter; + UnpackedRecord *r2 = pSorter->pUnpacked; + int i; + + if( pKey2 ){ + sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2); + } + + if( bOmitRowid ){ + r2->nField = pKeyInfo->nField; + assert( r2->nField>0 ); + for(i=0; inField; i++){ + if( r2->aMem[i].flags & MEM_Null ){ + *pRes = -1; + return; + } + } + r2->flags |= UNPACKED_PREFIX_MATCH; + } + + *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2); +} + +/* +** This function is called to compare two iterator keys when merging +** multiple b-tree segments. Parameter iOut is the index of the aTree[] +** value to recalculate. +*/ +static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){ + VdbeSorter *pSorter = pCsr->pSorter; + int i1; + int i2; + int iRes; + VdbeSorterIter *p1; + VdbeSorterIter *p2; + + assert( iOutnTree && iOut>0 ); + + if( iOut>=(pSorter->nTree/2) ){ + i1 = (iOut - pSorter->nTree/2) * 2; + i2 = i1 + 1; + }else{ + i1 = pSorter->aTree[iOut*2]; + i2 = pSorter->aTree[iOut*2+1]; + } + + p1 = &pSorter->aIter[i1]; + p2 = &pSorter->aIter[i2]; + + if( p1->pFile==0 ){ + iRes = i2; + }else if( p2->pFile==0 ){ + iRes = i1; + }else{ + int res; + assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */ + vdbeSorterCompare( + pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res + ); + if( res<=0 ){ + iRes = i1; + }else{ + iRes = i2; + } + } + + pSorter->aTree[iOut] = iRes; + return SQLITE_OK; +} + +/* +** Initialize the temporary index cursor just opened as a sorter cursor. +*/ +int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){ + int pgsz; /* Page size of main database */ + int mxCache; /* Cache size */ + VdbeSorter *pSorter; /* The new sorter */ + char *d; /* Dummy */ + + assert( pCsr->pKeyInfo && pCsr->pBt==0 ); + pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter)); + if( pSorter==0 ){ + return SQLITE_NOMEM; + } + + pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d); + if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM; + assert( pSorter->pUnpacked==(UnpackedRecord *)d ); + + if( !sqlite3TempInMemory(db) ){ + pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt); + pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz; + mxCache = db->aDb[0].pSchema->cache_size; + if( mxCachemxPmaSize = mxCache * pgsz; + } + + return SQLITE_OK; +} + +/* +** Free the list of sorted records starting at pRecord. +*/ +static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){ + SorterRecord *p; + SorterRecord *pNext; + for(p=pRecord; p; p=pNext){ + pNext = p->pNext; + sqlite3DbFree(db, p); + } +} + +/* +** Free any cursor components allocated by sqlite3VdbeSorterXXX routines. +*/ +void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){ + VdbeSorter *pSorter = pCsr->pSorter; + if( pSorter ){ + if( pSorter->aIter ){ + int i; + for(i=0; inTree; i++){ + vdbeSorterIterZero(db, &pSorter->aIter[i]); + } + sqlite3DbFree(db, pSorter->aIter); + } + if( pSorter->pTemp1 ){ + sqlite3OsCloseFree(pSorter->pTemp1); + } + vdbeSorterRecordFree(db, pSorter->pRecord); + sqlite3DbFree(db, pSorter->pUnpacked); + sqlite3DbFree(db, pSorter); + pCsr->pSorter = 0; + } +} + +/* +** Allocate space for a file-handle and open a temporary file. If successful, +** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK. +** Otherwise, set *ppFile to 0 and return an SQLite error code. +*/ +static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){ + int dummy; + return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile, + SQLITE_OPEN_TEMP_JOURNAL | + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy + ); +} + +/* +** Merge the two sorted lists p1 and p2 into a single list. +** Set *ppOut to the head of the new list. +*/ +static void vdbeSorterMerge( + const VdbeCursor *pCsr, /* For pKeyInfo */ + SorterRecord *p1, /* First list to merge */ + SorterRecord *p2, /* Second list to merge */ + SorterRecord **ppOut /* OUT: Head of merged list */ +){ + SorterRecord *pFinal = 0; + SorterRecord **pp = &pFinal; + void *pVal2 = p2 ? p2->pVal : 0; + + while( p1 && p2 ){ + int res; + vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res); + if( res<=0 ){ + *pp = p1; + pp = &p1->pNext; + p1 = p1->pNext; + pVal2 = 0; + }else{ + *pp = p2; + pp = &p2->pNext; + p2 = p2->pNext; + if( p2==0 ) break; + pVal2 = p2->pVal; + } + } + *pp = p1 ? p1 : p2; + *ppOut = pFinal; +} + +/* +** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK +** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error +** occurs. +*/ +static int vdbeSorterSort(const VdbeCursor *pCsr){ + int i; + SorterRecord **aSlot; + SorterRecord *p; + VdbeSorter *pSorter = pCsr->pSorter; + + aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *)); + if( !aSlot ){ + return SQLITE_NOMEM; + } + + p = pSorter->pRecord; + while( p ){ + SorterRecord *pNext = p->pNext; + p->pNext = 0; + for(i=0; aSlot[i]; i++){ + vdbeSorterMerge(pCsr, p, aSlot[i], &p); + aSlot[i] = 0; + } + aSlot[i] = p; + p = pNext; + } + + p = 0; + for(i=0; i<64; i++){ + vdbeSorterMerge(pCsr, p, aSlot[i], &p); + } + pSorter->pRecord = p; + + sqlite3_free(aSlot); + return SQLITE_OK; +} + +/* +** Initialize a file-writer object. +*/ +static void fileWriterInit( + sqlite3 *db, /* Database (for malloc) */ + sqlite3_file *pFile, /* File to write to */ + FileWriter *p, /* Object to populate */ + i64 iStart /* Offset of pFile to begin writing at */ +){ + int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt); + + memset(p, 0, sizeof(FileWriter)); + p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf); + if( !p->aBuffer ){ + p->eFWErr = SQLITE_NOMEM; + }else{ + p->iBufEnd = p->iBufStart = (iStart % nBuf); + p->iWriteOff = iStart - p->iBufStart; + p->nBuffer = nBuf; + p->pFile = pFile; + } +} + +/* +** Write nData bytes of data to the file-write object. Return SQLITE_OK +** if successful, or an SQLite error code if an error occurs. +*/ +static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){ + int nRem = nData; + while( nRem>0 && p->eFWErr==0 ){ + int nCopy = nRem; + if( nCopy>(p->nBuffer - p->iBufEnd) ){ + nCopy = p->nBuffer - p->iBufEnd; + } + + memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy); + p->iBufEnd += nCopy; + if( p->iBufEnd==p->nBuffer ){ + p->eFWErr = sqlite3OsWrite(p->pFile, + &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, + p->iWriteOff + p->iBufStart + ); + p->iBufStart = p->iBufEnd = 0; + p->iWriteOff += p->nBuffer; + } + assert( p->iBufEndnBuffer ); + + nRem -= nCopy; + } +} + +/* +** Flush any buffered data to disk and clean up the file-writer object. +** The results of using the file-writer after this call are undefined. +** Return SQLITE_OK if flushing the buffered data succeeds or is not +** required. Otherwise, return an SQLite error code. +** +** Before returning, set *piEof to the offset immediately following the +** last byte written to the file. +*/ +static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){ + int rc; + if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){ + p->eFWErr = sqlite3OsWrite(p->pFile, + &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, + p->iWriteOff + p->iBufStart + ); + } + *piEof = (p->iWriteOff + p->iBufEnd); + sqlite3DbFree(db, p->aBuffer); + rc = p->eFWErr; + memset(p, 0, sizeof(FileWriter)); + return rc; +} + +/* +** Write value iVal encoded as a varint to the file-write object. Return +** SQLITE_OK if successful, or an SQLite error code if an error occurs. +*/ +static void fileWriterWriteVarint(FileWriter *p, u64 iVal){ + int nByte; + u8 aByte[10]; + nByte = sqlite3PutVarint(aByte, iVal); + fileWriterWrite(p, aByte, nByte); +} + +/* +** Write the current contents of the in-memory linked-list to a PMA. Return +** SQLITE_OK if successful, or an SQLite error code otherwise. +** +** The format of a PMA is: +** +** * A varint. This varint contains the total number of bytes of content +** in the PMA (not including the varint itself). +** +** * One or more records packed end-to-end in order of ascending keys. +** Each record consists of a varint followed by a blob of data (the +** key). The varint is the number of bytes in the blob of data. +*/ +static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){ + int rc = SQLITE_OK; /* Return code */ + VdbeSorter *pSorter = pCsr->pSorter; + FileWriter writer; + + memset(&writer, 0, sizeof(FileWriter)); + + if( pSorter->nInMemory==0 ){ + assert( pSorter->pRecord==0 ); + return rc; + } + + rc = vdbeSorterSort(pCsr); + + /* If the first temporary PMA file has not been opened, open it now. */ + if( rc==SQLITE_OK && pSorter->pTemp1==0 ){ + rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1); + assert( rc!=SQLITE_OK || pSorter->pTemp1 ); + assert( pSorter->iWriteOff==0 ); + assert( pSorter->nPMA==0 ); + } + + if( rc==SQLITE_OK ){ + SorterRecord *p; + SorterRecord *pNext = 0; + + fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff); + pSorter->nPMA++; + fileWriterWriteVarint(&writer, pSorter->nInMemory); + for(p=pSorter->pRecord; p; p=pNext){ + pNext = p->pNext; + fileWriterWriteVarint(&writer, p->nVal); + fileWriterWrite(&writer, p->pVal, p->nVal); + sqlite3DbFree(db, p); + } + pSorter->pRecord = p; + rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff); + } + + return rc; +} + +/* +** Add a record to the sorter. +*/ +int sqlite3VdbeSorterWrite( + sqlite3 *db, /* Database handle */ + const VdbeCursor *pCsr, /* Sorter cursor */ + Mem *pVal /* Memory cell containing record */ +){ + VdbeSorter *pSorter = pCsr->pSorter; + int rc = SQLITE_OK; /* Return Code */ + SorterRecord *pNew; /* New list element */ + + assert( pSorter ); + pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n; + + pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord)); + if( pNew==0 ){ + rc = SQLITE_NOMEM; + }else{ + pNew->pVal = (void *)&pNew[1]; + memcpy(pNew->pVal, pVal->z, pVal->n); + pNew->nVal = pVal->n; + pNew->pNext = pSorter->pRecord; + pSorter->pRecord = pNew; + } + + /* See if the contents of the sorter should now be written out. They + ** are written out when either of the following are true: + ** + ** * The total memory allocated for the in-memory list is greater + ** than (page-size * cache-size), or + ** + ** * The total memory allocated for the in-memory list is greater + ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true. + */ + if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && ( + (pSorter->nInMemory>pSorter->mxPmaSize) + || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull()) + )){ +#ifdef SQLITE_DEBUG + i64 nExpect = pSorter->iWriteOff + + sqlite3VarintLen(pSorter->nInMemory) + + pSorter->nInMemory; +#endif + rc = vdbeSorterListToPMA(db, pCsr); + pSorter->nInMemory = 0; + assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) ); + } + + return rc; +} + +/* +** Helper function for sqlite3VdbeSorterRewind(). +*/ +static int vdbeSorterInitMerge( + sqlite3 *db, /* Database handle */ + const VdbeCursor *pCsr, /* Cursor handle for this sorter */ + i64 *pnByte /* Sum of bytes in all opened PMAs */ +){ + VdbeSorter *pSorter = pCsr->pSorter; + int rc = SQLITE_OK; /* Return code */ + int i; /* Used to iterator through aIter[] */ + i64 nByte = 0; /* Total bytes in all opened PMAs */ + + /* Initialize the iterators. */ + for(i=0; iaIter[i]; + rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte); + pSorter->iReadOff = pIter->iEof; + assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff ); + if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break; + } + + /* Initialize the aTree[] array. */ + for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){ + rc = vdbeSorterDoCompare(pCsr, i); + } + + *pnByte = nByte; + return rc; +} + +/* +** Once the sorter has been populated, this function is called to prepare +** for iterating through its contents in sorted order. +*/ +int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){ + VdbeSorter *pSorter = pCsr->pSorter; + int rc; /* Return code */ + sqlite3_file *pTemp2 = 0; /* Second temp file to use */ + i64 iWrite2 = 0; /* Write offset for pTemp2 */ + int nIter; /* Number of iterators used */ + int nByte; /* Bytes of space required for aIter/aTree */ + int N = 2; /* Power of 2 >= nIter */ + + assert( pSorter ); + + /* If no data has been written to disk, then do not do so now. Instead, + ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly + ** from the in-memory list. */ + if( pSorter->nPMA==0 ){ + *pbEof = !pSorter->pRecord; + assert( pSorter->aTree==0 ); + return vdbeSorterSort(pCsr); + } + + /* Write the current in-memory list to a PMA. */ + rc = vdbeSorterListToPMA(db, pCsr); + if( rc!=SQLITE_OK ) return rc; + + /* Allocate space for aIter[] and aTree[]. */ + nIter = pSorter->nPMA; + if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT; + assert( nIter>0 ); + while( NaIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte); + if( !pSorter->aIter ) return SQLITE_NOMEM; + pSorter->aTree = (int *)&pSorter->aIter[N]; + pSorter->nTree = N; + + do { + int iNew; /* Index of new, merged, PMA */ + + for(iNew=0; + rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNTnPMA; + iNew++ + ){ + int rc2; /* Return code from fileWriterFinish() */ + FileWriter writer; /* Object used to write to disk */ + i64 nWrite; /* Number of bytes in new PMA */ + + memset(&writer, 0, sizeof(FileWriter)); + + /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1, + ** initialize an iterator for each of them and break out of the loop. + ** These iterators will be incrementally merged as the VDBE layer calls + ** sqlite3VdbeSorterNext(). + ** + ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs, + ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs + ** are merged into a single PMA that is written to file pTemp2. + */ + rc = vdbeSorterInitMerge(db, pCsr, &nWrite); + assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile ); + if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){ + break; + } + + /* Open the second temp file, if it is not already open. */ + if( pTemp2==0 ){ + assert( iWrite2==0 ); + rc = vdbeSorterOpenTempFile(db, &pTemp2); + } + + if( rc==SQLITE_OK ){ + int bEof = 0; + fileWriterInit(db, pTemp2, &writer, iWrite2); + fileWriterWriteVarint(&writer, nWrite); + while( rc==SQLITE_OK && bEof==0 ){ + VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ]; + assert( pIter->pFile ); + + fileWriterWriteVarint(&writer, pIter->nKey); + fileWriterWrite(&writer, pIter->aKey, pIter->nKey); + rc = sqlite3VdbeSorterNext(db, pCsr, &bEof); + } + rc2 = fileWriterFinish(db, &writer, &iWrite2); + if( rc==SQLITE_OK ) rc = rc2; + } + } + + if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){ + break; + }else{ + sqlite3_file *pTmp = pSorter->pTemp1; + pSorter->nPMA = iNew; + pSorter->pTemp1 = pTemp2; + pTemp2 = pTmp; + pSorter->iWriteOff = iWrite2; + pSorter->iReadOff = 0; + iWrite2 = 0; + } + }while( rc==SQLITE_OK ); + + if( pTemp2 ){ + sqlite3OsCloseFree(pTemp2); + } + *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0); + return rc; +} + +/* +** Advance to the next element in the sorter. +*/ +int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){ + VdbeSorter *pSorter = pCsr->pSorter; + int rc; /* Return code */ + + if( pSorter->aTree ){ + int iPrev = pSorter->aTree[1];/* Index of iterator to advance */ + int i; /* Index of aTree[] to recalculate */ + + rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]); + for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){ + rc = vdbeSorterDoCompare(pCsr, i); + } + + *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0); + }else{ + SorterRecord *pFree = pSorter->pRecord; + pSorter->pRecord = pFree->pNext; + pFree->pNext = 0; + vdbeSorterRecordFree(db, pFree); + *pbEof = !pSorter->pRecord; + rc = SQLITE_OK; + } + return rc; +} + +/* +** Return a pointer to a buffer owned by the sorter that contains the +** current key. +*/ +static void *vdbeSorterRowkey( + const VdbeSorter *pSorter, /* Sorter object */ + int *pnKey /* OUT: Size of current key in bytes */ +){ + void *pKey; + if( pSorter->aTree ){ + VdbeSorterIter *pIter; + pIter = &pSorter->aIter[ pSorter->aTree[1] ]; + *pnKey = pIter->nKey; + pKey = pIter->aKey; + }else{ + *pnKey = pSorter->pRecord->nVal; + pKey = pSorter->pRecord->pVal; + } + return pKey; +} + +/* +** Copy the current sorter key into the memory cell pOut. +*/ +int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ + VdbeSorter *pSorter = pCsr->pSorter; + void *pKey; int nKey; /* Sorter key to copy into pOut */ + + pKey = vdbeSorterRowkey(pSorter, &nKey); + if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){ + return SQLITE_NOMEM; + } + pOut->n = nKey; + MemSetTypeFlag(pOut, MEM_Blob); + memcpy(pOut->z, pKey, nKey); + + return SQLITE_OK; +} + +/* +** Compare the key in memory cell pVal with the key that the sorter cursor +** passed as the first argument currently points to. For the purposes of +** the comparison, ignore the rowid field at the end of each record. +** +** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM). +** Otherwise, set *pRes to a negative, zero or positive value if the +** key in pVal is smaller than, equal to or larger than the current sorter +** key. +*/ +int sqlite3VdbeSorterCompare( + const VdbeCursor *pCsr, /* Sorter cursor */ + Mem *pVal, /* Value to compare to current sorter key */ + int *pRes /* OUT: Result of comparison */ +){ + VdbeSorter *pSorter = pCsr->pSorter; + void *pKey; int nKey; /* Sorter key to compare pVal with */ + + pKey = vdbeSorterRowkey(pSorter, &nKey); + vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes); + return SQLITE_OK; +} diff --git a/components/external/SQLite-3.8.1/src/vdbetrace.c b/components/external/SQLite-3.8.1/src/vdbetrace.c new file mode 100644 index 0000000000000000000000000000000000000000..0a767261f07adcfa4f6bc2e8ef54bd6f39a3ea8f --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vdbetrace.c @@ -0,0 +1,295 @@ +/* +** 2009 November 25 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains code used to insert the values of host parameters +** (aka "wildcards") into the SQL text output by sqlite3_trace(). +** +** The Vdbe parse-tree explainer is also found here. +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" + +#ifndef SQLITE_OMIT_TRACE + +/* +** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of +** bytes in this text up to but excluding the first character in +** a host parameter. If the text contains no host parameters, return +** the total number of bytes in the text. +*/ +static int findNextHostParameter(const char *zSql, int *pnToken){ + int tokenType; + int nTotal = 0; + int n; + + *pnToken = 0; + while( zSql[0] ){ + n = sqlite3GetToken((u8*)zSql, &tokenType); + assert( n>0 && tokenType!=TK_ILLEGAL ); + if( tokenType==TK_VARIABLE ){ + *pnToken = n; + break; + } + nTotal += n; + zSql += n; + } + return nTotal; +} + +/* +** This function returns a pointer to a nul-terminated string in memory +** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the +** string contains a copy of zRawSql but with host parameters expanded to +** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, +** then the returned string holds a copy of zRawSql with "-- " prepended +** to each line of text. +** +** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then +** then long strings and blobs are truncated to that many bytes. This +** can be used to prevent unreasonably large trace strings when dealing +** with large (multi-megabyte) strings and blobs. +** +** The calling function is responsible for making sure the memory returned +** is eventually freed. +** +** ALGORITHM: Scan the input string looking for host parameters in any of +** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within +** string literals, quoted identifier names, and comments. For text forms, +** the host parameter index is found by scanning the perpared +** statement for the corresponding OP_Variable opcode. Once the host +** parameter index is known, locate the value in p->aVar[]. Then render +** the value as a literal in place of the host parameter name. +*/ +char *sqlite3VdbeExpandSql( + Vdbe *p, /* The prepared statement being evaluated */ + const char *zRawSql /* Raw text of the SQL statement */ +){ + sqlite3 *db; /* The database connection */ + int idx = 0; /* Index of a host parameter */ + int nextIndex = 1; /* Index of next ? host parameter */ + int n; /* Length of a token prefix */ + int nToken; /* Length of the parameter token */ + int i; /* Loop counter */ + Mem *pVar; /* Value of a host parameter */ + StrAccum out; /* Accumulate the output here */ + char zBase[100]; /* Initial working space */ + + db = p->db; + sqlite3StrAccumInit(&out, zBase, sizeof(zBase), + db->aLimit[SQLITE_LIMIT_LENGTH]); + out.db = db; + if( db->nVdbeExec>1 ){ + while( *zRawSql ){ + const char *zStart = zRawSql; + while( *(zRawSql++)!='\n' && *zRawSql ); + sqlite3StrAccumAppend(&out, "-- ", 3); + sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart)); + } + }else{ + while( zRawSql[0] ){ + n = findNextHostParameter(zRawSql, &nToken); + assert( n>0 ); + sqlite3StrAccumAppend(&out, zRawSql, n); + zRawSql += n; + assert( zRawSql[0] || nToken==0 ); + if( nToken==0 ) break; + if( zRawSql[0]=='?' ){ + if( nToken>1 ){ + assert( sqlite3Isdigit(zRawSql[1]) ); + sqlite3GetInt32(&zRawSql[1], &idx); + }else{ + idx = nextIndex; + } + }else{ + assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' ); + testcase( zRawSql[0]==':' ); + testcase( zRawSql[0]=='$' ); + testcase( zRawSql[0]=='@' ); + idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken); + assert( idx>0 ); + } + zRawSql += nToken; + nextIndex = idx + 1; + assert( idx>0 && idx<=p->nVar ); + pVar = &p->aVar[idx-1]; + if( pVar->flags & MEM_Null ){ + sqlite3StrAccumAppend(&out, "NULL", 4); + }else if( pVar->flags & MEM_Int ){ + sqlite3XPrintf(&out, "%lld", pVar->u.i); + }else if( pVar->flags & MEM_Real ){ + sqlite3XPrintf(&out, "%!.15g", pVar->r); + }else if( pVar->flags & MEM_Str ){ + int nOut; /* Number of bytes of the string text to include in output */ +#ifndef SQLITE_OMIT_UTF16 + u8 enc = ENC(db); + Mem utf8; + if( enc!=SQLITE_UTF8 ){ + memset(&utf8, 0, sizeof(utf8)); + utf8.db = db; + sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC); + sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8); + pVar = &utf8; + } +#endif + nOut = pVar->n; +#ifdef SQLITE_TRACE_SIZE_LIMIT + if( nOut>SQLITE_TRACE_SIZE_LIMIT ){ + nOut = SQLITE_TRACE_SIZE_LIMIT; + while( nOutn && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; } + } +#endif + sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z); +#ifdef SQLITE_TRACE_SIZE_LIMIT + if( nOutn ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); +#endif +#ifndef SQLITE_OMIT_UTF16 + if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8); +#endif + }else if( pVar->flags & MEM_Zero ){ + sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero); + }else{ + int nOut; /* Number of bytes of the blob to include in output */ + assert( pVar->flags & MEM_Blob ); + sqlite3StrAccumAppend(&out, "x'", 2); + nOut = pVar->n; +#ifdef SQLITE_TRACE_SIZE_LIMIT + if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT; +#endif + for(i=0; iz[i]&0xff); + } + sqlite3StrAccumAppend(&out, "'", 1); +#ifdef SQLITE_TRACE_SIZE_LIMIT + if( nOutn ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); +#endif + } + } + } + return sqlite3StrAccumFinish(&out); +} + +#endif /* #ifndef SQLITE_OMIT_TRACE */ + +/***************************************************************************** +** The following code implements the data-structure explaining logic +** for the Vdbe. +*/ + +#if defined(SQLITE_ENABLE_TREE_EXPLAIN) + +/* +** Allocate a new Explain object +*/ +void sqlite3ExplainBegin(Vdbe *pVdbe){ + if( pVdbe ){ + Explain *p; + sqlite3BeginBenignMalloc(); + p = (Explain *)sqlite3MallocZero( sizeof(Explain) ); + if( p ){ + p->pVdbe = pVdbe; + sqlite3_free(pVdbe->pExplain); + pVdbe->pExplain = p; + sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase), + SQLITE_MAX_LENGTH); + p->str.useMalloc = 2; + }else{ + sqlite3EndBenignMalloc(); + } + } +} + +/* +** Return true if the Explain ends with a new-line. +*/ +static int endsWithNL(Explain *p){ + return p && p->str.zText && p->str.nChar + && p->str.zText[p->str.nChar-1]=='\n'; +} + +/* +** Append text to the indentation +*/ +void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){ + Explain *p; + if( pVdbe && (p = pVdbe->pExplain)!=0 ){ + va_list ap; + if( p->nIndent && endsWithNL(p) ){ + int n = p->nIndent; + if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent); + sqlite3AppendSpace(&p->str, p->aIndent[n-1]); + } + va_start(ap, zFormat); + sqlite3VXPrintf(&p->str, 1, zFormat, ap); + va_end(ap); + } +} + +/* +** Append a '\n' if there is not already one. +*/ +void sqlite3ExplainNL(Vdbe *pVdbe){ + Explain *p; + if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){ + sqlite3StrAccumAppend(&p->str, "\n", 1); + } +} + +/* +** Push a new indentation level. Subsequent lines will be indented +** so that they begin at the current cursor position. +*/ +void sqlite3ExplainPush(Vdbe *pVdbe){ + Explain *p; + if( pVdbe && (p = pVdbe->pExplain)!=0 ){ + if( p->str.zText && p->nIndentaIndent) ){ + const char *z = p->str.zText; + int i = p->str.nChar-1; + int x; + while( i>=0 && z[i]!='\n' ){ i--; } + x = (p->str.nChar - 1) - i; + if( p->nIndent && xaIndent[p->nIndent-1] ){ + x = p->aIndent[p->nIndent-1]; + } + p->aIndent[p->nIndent] = x; + } + p->nIndent++; + } +} + +/* +** Pop the indentation stack by one level. +*/ +void sqlite3ExplainPop(Vdbe *p){ + if( p && p->pExplain ) p->pExplain->nIndent--; +} + +/* +** Free the indentation structure +*/ +void sqlite3ExplainFinish(Vdbe *pVdbe){ + if( pVdbe && pVdbe->pExplain ){ + sqlite3_free(pVdbe->zExplain); + sqlite3ExplainNL(pVdbe); + pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str); + sqlite3_free(pVdbe->pExplain); + pVdbe->pExplain = 0; + sqlite3EndBenignMalloc(); + } +} + +/* +** Return the explanation of a virtual machine. +*/ +const char *sqlite3VdbeExplanation(Vdbe *pVdbe){ + return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0; +} +#endif /* defined(SQLITE_DEBUG) */ diff --git a/components/external/SQLite-3.8.1/src/vtab.c b/components/external/SQLite-3.8.1/src/vtab.c new file mode 100644 index 0000000000000000000000000000000000000000..195aa68b25b16a885ed1734bf1a265e122d262eb --- /dev/null +++ b/components/external/SQLite-3.8.1/src/vtab.c @@ -0,0 +1,1096 @@ +/* +** 2006 June 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to help implement virtual tables. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE +#include "sqliteInt.h" + +/* +** Before a virtual table xCreate() or xConnect() method is invoked, the +** sqlite3.pVtabCtx member variable is set to point to an instance of +** this struct allocated on the stack. It is used by the implementation of +** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which +** are invoked only from within xCreate and xConnect methods. +*/ +struct VtabCtx { + VTable *pVTable; /* The virtual table being constructed */ + Table *pTab; /* The Table object to which the virtual table belongs */ +}; + +/* +** The actual function that does the work of creating a new module. +** This function implements the sqlite3_create_module() and +** sqlite3_create_module_v2() interfaces. +*/ +static int createModule( + sqlite3 *db, /* Database in which module is registered */ + const char *zName, /* Name assigned to this module */ + const sqlite3_module *pModule, /* The definition of the module */ + void *pAux, /* Context pointer for xCreate/xConnect */ + void (*xDestroy)(void *) /* Module destructor function */ +){ + int rc = SQLITE_OK; + int nName; + + sqlite3_mutex_enter(db->mutex); + nName = sqlite3Strlen30(zName); + if( sqlite3HashFind(&db->aModule, zName, nName) ){ + rc = SQLITE_MISUSE_BKPT; + }else{ + Module *pMod; + pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1); + if( pMod ){ + Module *pDel; + char *zCopy = (char *)(&pMod[1]); + memcpy(zCopy, zName, nName+1); + pMod->zName = zCopy; + pMod->pModule = pModule; + pMod->pAux = pAux; + pMod->xDestroy = xDestroy; + pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod); + assert( pDel==0 || pDel==pMod ); + if( pDel ){ + db->mallocFailed = 1; + sqlite3DbFree(db, pDel); + } + } + } + rc = sqlite3ApiExit(db, rc); + if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux); + + sqlite3_mutex_leave(db->mutex); + return rc; +} + + +/* +** External API function used to create a new virtual-table module. +*/ +int sqlite3_create_module( + sqlite3 *db, /* Database in which module is registered */ + const char *zName, /* Name assigned to this module */ + const sqlite3_module *pModule, /* The definition of the module */ + void *pAux /* Context pointer for xCreate/xConnect */ +){ + return createModule(db, zName, pModule, pAux, 0); +} + +/* +** External API function used to create a new virtual-table module. +*/ +int sqlite3_create_module_v2( + sqlite3 *db, /* Database in which module is registered */ + const char *zName, /* Name assigned to this module */ + const sqlite3_module *pModule, /* The definition of the module */ + void *pAux, /* Context pointer for xCreate/xConnect */ + void (*xDestroy)(void *) /* Module destructor function */ +){ + return createModule(db, zName, pModule, pAux, xDestroy); +} + +/* +** Lock the virtual table so that it cannot be disconnected. +** Locks nest. Every lock should have a corresponding unlock. +** If an unlock is omitted, resources leaks will occur. +** +** If a disconnect is attempted while a virtual table is locked, +** the disconnect is deferred until all locks have been removed. +*/ +void sqlite3VtabLock(VTable *pVTab){ + pVTab->nRef++; +} + + +/* +** pTab is a pointer to a Table structure representing a virtual-table. +** Return a pointer to the VTable object used by connection db to access +** this virtual-table, if one has been created, or NULL otherwise. +*/ +VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){ + VTable *pVtab; + assert( IsVirtual(pTab) ); + for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext); + return pVtab; +} + +/* +** Decrement the ref-count on a virtual table object. When the ref-count +** reaches zero, call the xDisconnect() method to delete the object. +*/ +void sqlite3VtabUnlock(VTable *pVTab){ + sqlite3 *db = pVTab->db; + + assert( db ); + assert( pVTab->nRef>0 ); + assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE ); + + pVTab->nRef--; + if( pVTab->nRef==0 ){ + sqlite3_vtab *p = pVTab->pVtab; + if( p ){ + p->pModule->xDisconnect(p); + } + sqlite3DbFree(db, pVTab); + } +} + +/* +** Table p is a virtual table. This function moves all elements in the +** p->pVTable list to the sqlite3.pDisconnect lists of their associated +** database connections to be disconnected at the next opportunity. +** Except, if argument db is not NULL, then the entry associated with +** connection db is left in the p->pVTable list. +*/ +static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){ + VTable *pRet = 0; + VTable *pVTable = p->pVTable; + p->pVTable = 0; + + /* Assert that the mutex (if any) associated with the BtShared database + ** that contains table p is held by the caller. See header comments + ** above function sqlite3VtabUnlockList() for an explanation of why + ** this makes it safe to access the sqlite3.pDisconnect list of any + ** database connection that may have an entry in the p->pVTable list. + */ + assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); + + while( pVTable ){ + sqlite3 *db2 = pVTable->db; + VTable *pNext = pVTable->pNext; + assert( db2 ); + if( db2==db ){ + pRet = pVTable; + p->pVTable = pRet; + pRet->pNext = 0; + }else{ + pVTable->pNext = db2->pDisconnect; + db2->pDisconnect = pVTable; + } + pVTable = pNext; + } + + assert( !db || pRet ); + return pRet; +} + +/* +** Table *p is a virtual table. This function removes the VTable object +** for table *p associated with database connection db from the linked +** list in p->pVTab. It also decrements the VTable ref count. This is +** used when closing database connection db to free all of its VTable +** objects without disturbing the rest of the Schema object (which may +** be being used by other shared-cache connections). +*/ +void sqlite3VtabDisconnect(sqlite3 *db, Table *p){ + VTable **ppVTab; + + assert( IsVirtual(p) ); + assert( sqlite3BtreeHoldsAllMutexes(db) ); + assert( sqlite3_mutex_held(db->mutex) ); + + for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){ + if( (*ppVTab)->db==db ){ + VTable *pVTab = *ppVTab; + *ppVTab = pVTab->pNext; + sqlite3VtabUnlock(pVTab); + break; + } + } +} + + +/* +** Disconnect all the virtual table objects in the sqlite3.pDisconnect list. +** +** This function may only be called when the mutexes associated with all +** shared b-tree databases opened using connection db are held by the +** caller. This is done to protect the sqlite3.pDisconnect list. The +** sqlite3.pDisconnect list is accessed only as follows: +** +** 1) By this function. In this case, all BtShared mutexes and the mutex +** associated with the database handle itself must be held. +** +** 2) By function vtabDisconnectAll(), when it adds a VTable entry to +** the sqlite3.pDisconnect list. In this case either the BtShared mutex +** associated with the database the virtual table is stored in is held +** or, if the virtual table is stored in a non-sharable database, then +** the database handle mutex is held. +** +** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously +** by multiple threads. It is thread-safe. +*/ +void sqlite3VtabUnlockList(sqlite3 *db){ + VTable *p = db->pDisconnect; + db->pDisconnect = 0; + + assert( sqlite3BtreeHoldsAllMutexes(db) ); + assert( sqlite3_mutex_held(db->mutex) ); + + if( p ){ + sqlite3ExpirePreparedStatements(db); + do { + VTable *pNext = p->pNext; + sqlite3VtabUnlock(p); + p = pNext; + }while( p ); + } +} + +/* +** Clear any and all virtual-table information from the Table record. +** This routine is called, for example, just before deleting the Table +** record. +** +** Since it is a virtual-table, the Table structure contains a pointer +** to the head of a linked list of VTable structures. Each VTable +** structure is associated with a single sqlite3* user of the schema. +** The reference count of the VTable structure associated with database +** connection db is decremented immediately (which may lead to the +** structure being xDisconnected and free). Any other VTable structures +** in the list are moved to the sqlite3.pDisconnect list of the associated +** database connection. +*/ +void sqlite3VtabClear(sqlite3 *db, Table *p){ + if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p); + if( p->azModuleArg ){ + int i; + for(i=0; inModuleArg; i++){ + if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]); + } + sqlite3DbFree(db, p->azModuleArg); + } +} + +/* +** Add a new module argument to pTable->azModuleArg[]. +** The string is not copied - the pointer is stored. The +** string will be freed automatically when the table is +** deleted. +*/ +static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){ + int i = pTable->nModuleArg++; + int nBytes = sizeof(char *)*(1+pTable->nModuleArg); + char **azModuleArg; + azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes); + if( azModuleArg==0 ){ + int j; + for(j=0; jazModuleArg[j]); + } + sqlite3DbFree(db, zArg); + sqlite3DbFree(db, pTable->azModuleArg); + pTable->nModuleArg = 0; + }else{ + azModuleArg[i] = zArg; + azModuleArg[i+1] = 0; + } + pTable->azModuleArg = azModuleArg; +} + +/* +** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE +** statement. The module name has been parsed, but the optional list +** of parameters that follow the module name are still pending. +*/ +void sqlite3VtabBeginParse( + Parse *pParse, /* Parsing context */ + Token *pName1, /* Name of new table, or database name */ + Token *pName2, /* Name of new table or NULL */ + Token *pModuleName, /* Name of the module for the virtual table */ + int ifNotExists /* No error if the table already exists */ +){ + int iDb; /* The database the table is being created in */ + Table *pTable; /* The new virtual table */ + sqlite3 *db; /* Database connection */ + + sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists); + pTable = pParse->pNewTable; + if( pTable==0 ) return; + assert( 0==pTable->pIndex ); + + db = pParse->db; + iDb = sqlite3SchemaToIndex(db, pTable->pSchema); + assert( iDb>=0 ); + + pTable->tabFlags |= TF_Virtual; + pTable->nModuleArg = 0; + addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName)); + addModuleArgument(db, pTable, 0); + addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName)); + pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z); + +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Creating a virtual table invokes the authorization callback twice. + ** The first invocation, to obtain permission to INSERT a row into the + ** sqlite_master table, has already been made by sqlite3StartTable(). + ** The second call, to obtain permission to create the table, is made now. + */ + if( pTable->azModuleArg ){ + sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, + pTable->azModuleArg[0], pParse->db->aDb[iDb].zName); + } +#endif +} + +/* +** This routine takes the module argument that has been accumulating +** in pParse->zArg[] and appends it to the list of arguments on the +** virtual table currently under construction in pParse->pTable. +*/ +static void addArgumentToVtab(Parse *pParse){ + if( pParse->sArg.z && pParse->pNewTable ){ + const char *z = (const char*)pParse->sArg.z; + int n = pParse->sArg.n; + sqlite3 *db = pParse->db; + addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); + } +} + +/* +** The parser calls this routine after the CREATE VIRTUAL TABLE statement +** has been completely parsed. +*/ +void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ + Table *pTab = pParse->pNewTable; /* The table being constructed */ + sqlite3 *db = pParse->db; /* The database connection */ + + if( pTab==0 ) return; + addArgumentToVtab(pParse); + pParse->sArg.z = 0; + if( pTab->nModuleArg<1 ) return; + + /* If the CREATE VIRTUAL TABLE statement is being entered for the + ** first time (in other words if the virtual table is actually being + ** created now instead of just being read out of sqlite_master) then + ** do additional initialization work and store the statement text + ** in the sqlite_master table. + */ + if( !db->init.busy ){ + char *zStmt; + char *zWhere; + int iDb; + Vdbe *v; + + /* Compute the complete text of the CREATE VIRTUAL TABLE statement */ + if( pEnd ){ + pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n; + } + zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken); + + /* A slot for the record has already been allocated in the + ** SQLITE_MASTER table. We just need to update that slot with all + ** the information we've collected. + ** + ** The VM register number pParse->regRowid holds the rowid of an + ** entry in the sqlite_master table tht was created for this vtab + ** by sqlite3StartTable(). + */ + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + sqlite3NestedParse(pParse, + "UPDATE %Q.%s " + "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " + "WHERE rowid=#%d", + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), + pTab->zName, + pTab->zName, + zStmt, + pParse->regRowid + ); + sqlite3DbFree(db, zStmt); + v = sqlite3GetVdbe(pParse); + sqlite3ChangeCookie(pParse, iDb); + + sqlite3VdbeAddOp2(v, OP_Expire, 0, 0); + zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName); + sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); + sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, + pTab->zName, sqlite3Strlen30(pTab->zName) + 1); + } + + /* If we are rereading the sqlite_master table create the in-memory + ** record of the table. The xConnect() method is not called until + ** the first time the virtual table is used in an SQL statement. This + ** allows a schema that contains virtual tables to be loaded before + ** the required virtual table implementations are registered. */ + else { + Table *pOld; + Schema *pSchema = pTab->pSchema; + const char *zName = pTab->zName; + int nName = sqlite3Strlen30(zName); + assert( sqlite3SchemaMutexHeld(db, 0, pSchema) ); + pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab); + if( pOld ){ + db->mallocFailed = 1; + assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */ + return; + } + pParse->pNewTable = 0; + } +} + +/* +** The parser calls this routine when it sees the first token +** of an argument to the module name in a CREATE VIRTUAL TABLE statement. +*/ +void sqlite3VtabArgInit(Parse *pParse){ + addArgumentToVtab(pParse); + pParse->sArg.z = 0; + pParse->sArg.n = 0; +} + +/* +** The parser calls this routine for each token after the first token +** in an argument to the module name in a CREATE VIRTUAL TABLE statement. +*/ +void sqlite3VtabArgExtend(Parse *pParse, Token *p){ + Token *pArg = &pParse->sArg; + if( pArg->z==0 ){ + pArg->z = p->z; + pArg->n = p->n; + }else{ + assert(pArg->z < p->z); + pArg->n = (int)(&p->z[p->n] - pArg->z); + } +} + +/* +** Invoke a virtual table constructor (either xCreate or xConnect). The +** pointer to the function to invoke is passed as the fourth parameter +** to this procedure. +*/ +static int vtabCallConstructor( + sqlite3 *db, + Table *pTab, + Module *pMod, + int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**), + char **pzErr +){ + VtabCtx sCtx, *pPriorCtx; + VTable *pVTable; + int rc; + const char *const*azArg = (const char *const*)pTab->azModuleArg; + int nArg = pTab->nModuleArg; + char *zErr = 0; + char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName); + int iDb; + + if( !zModuleName ){ + return SQLITE_NOMEM; + } + + pVTable = sqlite3DbMallocZero(db, sizeof(VTable)); + if( !pVTable ){ + sqlite3DbFree(db, zModuleName); + return SQLITE_NOMEM; + } + pVTable->db = db; + pVTable->pMod = pMod; + + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + pTab->azModuleArg[1] = db->aDb[iDb].zName; + + /* Invoke the virtual table constructor */ + assert( &db->pVtabCtx ); + assert( xConstruct ); + sCtx.pTab = pTab; + sCtx.pVTable = pVTable; + pPriorCtx = db->pVtabCtx; + db->pVtabCtx = &sCtx; + rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr); + db->pVtabCtx = pPriorCtx; + if( rc==SQLITE_NOMEM ) db->mallocFailed = 1; + + if( SQLITE_OK!=rc ){ + if( zErr==0 ){ + *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName); + }else { + *pzErr = sqlite3MPrintf(db, "%s", zErr); + sqlite3_free(zErr); + } + sqlite3DbFree(db, pVTable); + }else if( ALWAYS(pVTable->pVtab) ){ + /* Justification of ALWAYS(): A correct vtab constructor must allocate + ** the sqlite3_vtab object if successful. */ + pVTable->pVtab->pModule = pMod->pModule; + pVTable->nRef = 1; + if( sCtx.pTab ){ + const char *zFormat = "vtable constructor did not declare schema: %s"; + *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName); + sqlite3VtabUnlock(pVTable); + rc = SQLITE_ERROR; + }else{ + int iCol; + /* If everything went according to plan, link the new VTable structure + ** into the linked list headed by pTab->pVTable. Then loop through the + ** columns of the table to see if any of them contain the token "hidden". + ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from + ** the type string. */ + pVTable->pNext = pTab->pVTable; + pTab->pVTable = pVTable; + + for(iCol=0; iColnCol; iCol++){ + char *zType = pTab->aCol[iCol].zType; + int nType; + int i = 0; + if( !zType ) continue; + nType = sqlite3Strlen30(zType); + if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){ + for(i=0; i0 ){ + assert(zType[i-1]==' '); + zType[i-1] = '\0'; + } + pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN; + } + } + } + } + + sqlite3DbFree(db, zModuleName); + return rc; +} + +/* +** This function is invoked by the parser to call the xConnect() method +** of the virtual table pTab. If an error occurs, an error code is returned +** and an error left in pParse. +** +** This call is a no-op if table pTab is not a virtual table. +*/ +int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){ + sqlite3 *db = pParse->db; + const char *zMod; + Module *pMod; + int rc; + + assert( pTab ); + if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){ + return SQLITE_OK; + } + + /* Locate the required virtual table module */ + zMod = pTab->azModuleArg[0]; + pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod)); + + if( !pMod ){ + const char *zModule = pTab->azModuleArg[0]; + sqlite3ErrorMsg(pParse, "no such module: %s", zModule); + rc = SQLITE_ERROR; + }else{ + char *zErr = 0; + rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr); + if( rc!=SQLITE_OK ){ + sqlite3ErrorMsg(pParse, "%s", zErr); + } + sqlite3DbFree(db, zErr); + } + + return rc; +} +/* +** Grow the db->aVTrans[] array so that there is room for at least one +** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise. +*/ +static int growVTrans(sqlite3 *db){ + const int ARRAY_INCR = 5; + + /* Grow the sqlite3.aVTrans array if required */ + if( (db->nVTrans%ARRAY_INCR)==0 ){ + VTable **aVTrans; + int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR); + aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes); + if( !aVTrans ){ + return SQLITE_NOMEM; + } + memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR); + db->aVTrans = aVTrans; + } + + return SQLITE_OK; +} + +/* +** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should +** have already been reserved using growVTrans(). +*/ +static void addToVTrans(sqlite3 *db, VTable *pVTab){ + /* Add pVtab to the end of sqlite3.aVTrans */ + db->aVTrans[db->nVTrans++] = pVTab; + sqlite3VtabLock(pVTab); +} + +/* +** This function is invoked by the vdbe to call the xCreate method +** of the virtual table named zTab in database iDb. +** +** If an error occurs, *pzErr is set to point an an English language +** description of the error and an SQLITE_XXX error code is returned. +** In this case the caller must call sqlite3DbFree(db, ) on *pzErr. +*/ +int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){ + int rc = SQLITE_OK; + Table *pTab; + Module *pMod; + const char *zMod; + + pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName); + assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable ); + + /* Locate the required virtual table module */ + zMod = pTab->azModuleArg[0]; + pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod)); + + /* If the module has been registered and includes a Create method, + ** invoke it now. If the module has not been registered, return an + ** error. Otherwise, do nothing. + */ + if( !pMod ){ + *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod); + rc = SQLITE_ERROR; + }else{ + rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr); + } + + /* Justification of ALWAYS(): The xConstructor method is required to + ** create a valid sqlite3_vtab if it returns SQLITE_OK. */ + if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){ + rc = growVTrans(db); + if( rc==SQLITE_OK ){ + addToVTrans(db, sqlite3GetVTable(db, pTab)); + } + } + + return rc; +} + +/* +** This function is used to set the schema of a virtual table. It is only +** valid to call this function from within the xCreate() or xConnect() of a +** virtual table module. +*/ +int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){ + Parse *pParse; + + int rc = SQLITE_OK; + Table *pTab; + char *zErr = 0; + + sqlite3_mutex_enter(db->mutex); + if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){ + sqlite3Error(db, SQLITE_MISUSE, 0); + sqlite3_mutex_leave(db->mutex); + return SQLITE_MISUSE_BKPT; + } + assert( (pTab->tabFlags & TF_Virtual)!=0 ); + + pParse = sqlite3StackAllocZero(db, sizeof(*pParse)); + if( pParse==0 ){ + rc = SQLITE_NOMEM; + }else{ + pParse->declareVtab = 1; + pParse->db = db; + pParse->nQueryLoop = 1; + + if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) + && pParse->pNewTable + && !db->mallocFailed + && !pParse->pNewTable->pSelect + && (pParse->pNewTable->tabFlags & TF_Virtual)==0 + ){ + if( !pTab->aCol ){ + pTab->aCol = pParse->pNewTable->aCol; + pTab->nCol = pParse->pNewTable->nCol; + pParse->pNewTable->nCol = 0; + pParse->pNewTable->aCol = 0; + } + db->pVtabCtx->pTab = 0; + }else{ + sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr); + sqlite3DbFree(db, zErr); + rc = SQLITE_ERROR; + } + pParse->declareVtab = 0; + + if( pParse->pVdbe ){ + sqlite3VdbeFinalize(pParse->pVdbe); + } + sqlite3DeleteTable(db, pParse->pNewTable); + sqlite3StackFree(db, pParse); + } + + assert( (rc&0xff)==rc ); + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** This function is invoked by the vdbe to call the xDestroy method +** of the virtual table named zTab in database iDb. This occurs +** when a DROP TABLE is mentioned. +** +** This call is a no-op if zTab is not a virtual table. +*/ +int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){ + int rc = SQLITE_OK; + Table *pTab; + + pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName); + if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){ + VTable *p = vtabDisconnectAll(db, pTab); + + assert( rc==SQLITE_OK ); + rc = p->pMod->pModule->xDestroy(p->pVtab); + + /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */ + if( rc==SQLITE_OK ){ + assert( pTab->pVTable==p && p->pNext==0 ); + p->pVtab = 0; + pTab->pVTable = 0; + sqlite3VtabUnlock(p); + } + } + + return rc; +} + +/* +** This function invokes either the xRollback or xCommit method +** of each of the virtual tables in the sqlite3.aVTrans array. The method +** called is identified by the second argument, "offset", which is +** the offset of the method to call in the sqlite3_module structure. +** +** The array is cleared after invoking the callbacks. +*/ +static void callFinaliser(sqlite3 *db, int offset){ + int i; + if( db->aVTrans ){ + for(i=0; inVTrans; i++){ + VTable *pVTab = db->aVTrans[i]; + sqlite3_vtab *p = pVTab->pVtab; + if( p ){ + int (*x)(sqlite3_vtab *); + x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset); + if( x ) x(p); + } + pVTab->iSavepoint = 0; + sqlite3VtabUnlock(pVTab); + } + sqlite3DbFree(db, db->aVTrans); + db->nVTrans = 0; + db->aVTrans = 0; + } +} + +/* +** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans +** array. Return the error code for the first error that occurs, or +** SQLITE_OK if all xSync operations are successful. +** +** If an error message is available, leave it in p->zErrMsg. +*/ +int sqlite3VtabSync(sqlite3 *db, Vdbe *p){ + int i; + int rc = SQLITE_OK; + VTable **aVTrans = db->aVTrans; + + db->aVTrans = 0; + for(i=0; rc==SQLITE_OK && inVTrans; i++){ + int (*x)(sqlite3_vtab *); + sqlite3_vtab *pVtab = aVTrans[i]->pVtab; + if( pVtab && (x = pVtab->pModule->xSync)!=0 ){ + rc = x(pVtab); + sqlite3VtabImportErrmsg(p, pVtab); + } + } + db->aVTrans = aVTrans; + return rc; +} + +/* +** Invoke the xRollback method of all virtual tables in the +** sqlite3.aVTrans array. Then clear the array itself. +*/ +int sqlite3VtabRollback(sqlite3 *db){ + callFinaliser(db, offsetof(sqlite3_module,xRollback)); + return SQLITE_OK; +} + +/* +** Invoke the xCommit method of all virtual tables in the +** sqlite3.aVTrans array. Then clear the array itself. +*/ +int sqlite3VtabCommit(sqlite3 *db){ + callFinaliser(db, offsetof(sqlite3_module,xCommit)); + return SQLITE_OK; +} + +/* +** If the virtual table pVtab supports the transaction interface +** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is +** not currently open, invoke the xBegin method now. +** +** If the xBegin call is successful, place the sqlite3_vtab pointer +** in the sqlite3.aVTrans array. +*/ +int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){ + int rc = SQLITE_OK; + const sqlite3_module *pModule; + + /* Special case: If db->aVTrans is NULL and db->nVTrans is greater + ** than zero, then this function is being called from within a + ** virtual module xSync() callback. It is illegal to write to + ** virtual module tables in this case, so return SQLITE_LOCKED. + */ + if( sqlite3VtabInSync(db) ){ + return SQLITE_LOCKED; + } + if( !pVTab ){ + return SQLITE_OK; + } + pModule = pVTab->pVtab->pModule; + + if( pModule->xBegin ){ + int i; + + /* If pVtab is already in the aVTrans array, return early */ + for(i=0; inVTrans; i++){ + if( db->aVTrans[i]==pVTab ){ + return SQLITE_OK; + } + } + + /* Invoke the xBegin method. If successful, add the vtab to the + ** sqlite3.aVTrans[] array. */ + rc = growVTrans(db); + if( rc==SQLITE_OK ){ + rc = pModule->xBegin(pVTab->pVtab); + if( rc==SQLITE_OK ){ + addToVTrans(db, pVTab); + } + } + } + return rc; +} + +/* +** Invoke either the xSavepoint, xRollbackTo or xRelease method of all +** virtual tables that currently have an open transaction. Pass iSavepoint +** as the second argument to the virtual table method invoked. +** +** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is +** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is +** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with +** an open transaction is invoked. +** +** If any virtual table method returns an error code other than SQLITE_OK, +** processing is abandoned and the error returned to the caller of this +** function immediately. If all calls to virtual table methods are successful, +** SQLITE_OK is returned. +*/ +int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){ + int rc = SQLITE_OK; + + assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN ); + assert( iSavepoint>=0 ); + if( db->aVTrans ){ + int i; + for(i=0; rc==SQLITE_OK && inVTrans; i++){ + VTable *pVTab = db->aVTrans[i]; + const sqlite3_module *pMod = pVTab->pMod->pModule; + if( pVTab->pVtab && pMod->iVersion>=2 ){ + int (*xMethod)(sqlite3_vtab *, int); + switch( op ){ + case SAVEPOINT_BEGIN: + xMethod = pMod->xSavepoint; + pVTab->iSavepoint = iSavepoint+1; + break; + case SAVEPOINT_ROLLBACK: + xMethod = pMod->xRollbackTo; + break; + default: + xMethod = pMod->xRelease; + break; + } + if( xMethod && pVTab->iSavepoint>iSavepoint ){ + rc = xMethod(pVTab->pVtab, iSavepoint); + } + } + } + } + return rc; +} + +/* +** The first parameter (pDef) is a function implementation. The +** second parameter (pExpr) is the first argument to this function. +** If pExpr is a column in a virtual table, then let the virtual +** table implementation have an opportunity to overload the function. +** +** This routine is used to allow virtual table implementations to +** overload MATCH, LIKE, GLOB, and REGEXP operators. +** +** Return either the pDef argument (indicating no change) or a +** new FuncDef structure that is marked as ephemeral using the +** SQLITE_FUNC_EPHEM flag. +*/ +FuncDef *sqlite3VtabOverloadFunction( + sqlite3 *db, /* Database connection for reporting malloc problems */ + FuncDef *pDef, /* Function to possibly overload */ + int nArg, /* Number of arguments to the function */ + Expr *pExpr /* First argument to the function */ +){ + Table *pTab; + sqlite3_vtab *pVtab; + sqlite3_module *pMod; + void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0; + void *pArg = 0; + FuncDef *pNew; + int rc = 0; + char *zLowerName; + unsigned char *z; + + + /* Check to see the left operand is a column in a virtual table */ + if( NEVER(pExpr==0) ) return pDef; + if( pExpr->op!=TK_COLUMN ) return pDef; + pTab = pExpr->pTab; + if( NEVER(pTab==0) ) return pDef; + if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef; + pVtab = sqlite3GetVTable(db, pTab)->pVtab; + assert( pVtab!=0 ); + assert( pVtab->pModule!=0 ); + pMod = (sqlite3_module *)pVtab->pModule; + if( pMod->xFindFunction==0 ) return pDef; + + /* Call the xFindFunction method on the virtual table implementation + ** to see if the implementation wants to overload this function + */ + zLowerName = sqlite3DbStrDup(db, pDef->zName); + if( zLowerName ){ + for(z=(unsigned char*)zLowerName; *z; z++){ + *z = sqlite3UpperToLower[*z]; + } + rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg); + sqlite3DbFree(db, zLowerName); + } + if( rc==0 ){ + return pDef; + } + + /* Create a new ephemeral function definition for the overloaded + ** function */ + pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + + sqlite3Strlen30(pDef->zName) + 1); + if( pNew==0 ){ + return pDef; + } + *pNew = *pDef; + pNew->zName = (char *)&pNew[1]; + memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1); + pNew->xFunc = xFunc; + pNew->pUserData = pArg; + pNew->funcFlags |= SQLITE_FUNC_EPHEM; + return pNew; +} + +/* +** Make sure virtual table pTab is contained in the pParse->apVirtualLock[] +** array so that an OP_VBegin will get generated for it. Add pTab to the +** array if it is missing. If pTab is already in the array, this routine +** is a no-op. +*/ +void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + int i, n; + Table **apVtabLock; + + assert( IsVirtual(pTab) ); + for(i=0; inVtabLock; i++){ + if( pTab==pToplevel->apVtabLock[i] ) return; + } + n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]); + apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n); + if( apVtabLock ){ + pToplevel->apVtabLock = apVtabLock; + pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab; + }else{ + pToplevel->db->mallocFailed = 1; + } +} + +/* +** Return the ON CONFLICT resolution mode in effect for the virtual +** table update operation currently in progress. +** +** The results of this routine are undefined unless it is called from +** within an xUpdate method. +*/ +int sqlite3_vtab_on_conflict(sqlite3 *db){ + static const unsigned char aMap[] = { + SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE + }; + assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 ); + assert( OE_Ignore==4 && OE_Replace==5 ); + assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 ); + return (int)aMap[db->vtabOnConflict-1]; +} + +/* +** Call from within the xCreate() or xConnect() methods to provide +** the SQLite core with additional information about the behavior +** of the virtual table being implemented. +*/ +int sqlite3_vtab_config(sqlite3 *db, int op, ...){ + va_list ap; + int rc = SQLITE_OK; + + sqlite3_mutex_enter(db->mutex); + + va_start(ap, op); + switch( op ){ + case SQLITE_VTAB_CONSTRAINT_SUPPORT: { + VtabCtx *p = db->pVtabCtx; + if( !p ){ + rc = SQLITE_MISUSE_BKPT; + }else{ + assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 ); + p->pVTable->bConstraint = (u8)va_arg(ap, int); + } + break; + } + default: + rc = SQLITE_MISUSE_BKPT; + break; + } + va_end(ap); + + if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0); + sqlite3_mutex_leave(db->mutex); + return rc; +} + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ diff --git a/components/external/SQLite-3.8.1/src/wal.c b/components/external/SQLite-3.8.1/src/wal.c new file mode 100644 index 0000000000000000000000000000000000000000..f41392064811473e6259081cea4d3a419ab5ed1c --- /dev/null +++ b/components/external/SQLite-3.8.1/src/wal.c @@ -0,0 +1,3094 @@ +/* +** 2010 February 1 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the implementation of a write-ahead log (WAL) used in +** "journal_mode=WAL" mode. +** +** WRITE-AHEAD LOG (WAL) FILE FORMAT +** +** A WAL file consists of a header followed by zero or more "frames". +** Each frame records the revised content of a single page from the +** database file. All changes to the database are recorded by writing +** frames into the WAL. Transactions commit when a frame is written that +** contains a commit marker. A single WAL can and usually does record +** multiple transactions. Periodically, the content of the WAL is +** transferred back into the database file in an operation called a +** "checkpoint". +** +** A single WAL file can be used multiple times. In other words, the +** WAL can fill up with frames and then be checkpointed and then new +** frames can overwrite the old ones. A WAL always grows from beginning +** toward the end. Checksums and counters attached to each frame are +** used to determine which frames within the WAL are valid and which +** are leftovers from prior checkpoints. +** +** The WAL header is 32 bytes in size and consists of the following eight +** big-endian 32-bit unsigned integer values: +** +** 0: Magic number. 0x377f0682 or 0x377f0683 +** 4: File format version. Currently 3007000 +** 8: Database page size. Example: 1024 +** 12: Checkpoint sequence number +** 16: Salt-1, random integer incremented with each checkpoint +** 20: Salt-2, a different random integer changing with each ckpt +** 24: Checksum-1 (first part of checksum for first 24 bytes of header). +** 28: Checksum-2 (second part of checksum for first 24 bytes of header). +** +** Immediately following the wal-header are zero or more frames. Each +** frame consists of a 24-byte frame-header followed by a bytes +** of page data. The frame-header is six big-endian 32-bit unsigned +** integer values, as follows: +** +** 0: Page number. +** 4: For commit records, the size of the database image in pages +** after the commit. For all other records, zero. +** 8: Salt-1 (copied from the header) +** 12: Salt-2 (copied from the header) +** 16: Checksum-1. +** 20: Checksum-2. +** +** A frame is considered valid if and only if the following conditions are +** true: +** +** (1) The salt-1 and salt-2 values in the frame-header match +** salt values in the wal-header +** +** (2) The checksum values in the final 8 bytes of the frame-header +** exactly match the checksum computed consecutively on the +** WAL header and the first 8 bytes and the content of all frames +** up to and including the current frame. +** +** The checksum is computed using 32-bit big-endian integers if the +** magic number in the first 4 bytes of the WAL is 0x377f0683 and it +** is computed using little-endian if the magic number is 0x377f0682. +** The checksum values are always stored in the frame header in a +** big-endian format regardless of which byte order is used to compute +** the checksum. The checksum is computed by interpreting the input as +** an even number of unsigned 32-bit integers: x[0] through x[N]. The +** algorithm used for the checksum is as follows: +** +** for i from 0 to n-1 step 2: +** s0 += x[i] + s1; +** s1 += x[i+1] + s0; +** endfor +** +** Note that s0 and s1 are both weighted checksums using fibonacci weights +** in reverse order (the largest fibonacci weight occurs on the first element +** of the sequence being summed.) The s1 value spans all 32-bit +** terms of the sequence whereas s0 omits the final term. +** +** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the +** WAL is transferred into the database, then the database is VFS.xSync-ed. +** The VFS.xSync operations serve as write barriers - all writes launched +** before the xSync must complete before any write that launches after the +** xSync begins. +** +** After each checkpoint, the salt-1 value is incremented and the salt-2 +** value is randomized. This prevents old and new frames in the WAL from +** being considered valid at the same time and being checkpointing together +** following a crash. +** +** READER ALGORITHM +** +** To read a page from the database (call it page number P), a reader +** first checks the WAL to see if it contains page P. If so, then the +** last valid instance of page P that is a followed by a commit frame +** or is a commit frame itself becomes the value read. If the WAL +** contains no copies of page P that are valid and which are a commit +** frame or are followed by a commit frame, then page P is read from +** the database file. +** +** To start a read transaction, the reader records the index of the last +** valid frame in the WAL. The reader uses this recorded "mxFrame" value +** for all subsequent read operations. New transactions can be appended +** to the WAL, but as long as the reader uses its original mxFrame value +** and ignores the newly appended content, it will see a consistent snapshot +** of the database from a single point in time. This technique allows +** multiple concurrent readers to view different versions of the database +** content simultaneously. +** +** The reader algorithm in the previous paragraphs works correctly, but +** because frames for page P can appear anywhere within the WAL, the +** reader has to scan the entire WAL looking for page P frames. If the +** WAL is large (multiple megabytes is typical) that scan can be slow, +** and read performance suffers. To overcome this problem, a separate +** data structure called the wal-index is maintained to expedite the +** search for frames of a particular page. +** +** WAL-INDEX FORMAT +** +** Conceptually, the wal-index is shared memory, though VFS implementations +** might choose to implement the wal-index using a mmapped file. Because +** the wal-index is shared memory, SQLite does not support journal_mode=WAL +** on a network filesystem. All users of the database must be able to +** share memory. +** +** The wal-index is transient. After a crash, the wal-index can (and should +** be) reconstructed from the original WAL file. In fact, the VFS is required +** to either truncate or zero the header of the wal-index when the last +** connection to it closes. Because the wal-index is transient, it can +** use an architecture-specific format; it does not have to be cross-platform. +** Hence, unlike the database and WAL file formats which store all values +** as big endian, the wal-index can store multi-byte values in the native +** byte order of the host computer. +** +** The purpose of the wal-index is to answer this question quickly: Given +** a page number P and a maximum frame index M, return the index of the +** last frame in the wal before frame M for page P in the WAL, or return +** NULL if there are no frames for page P in the WAL prior to M. +** +** The wal-index consists of a header region, followed by an one or +** more index blocks. +** +** The wal-index header contains the total number of frames within the WAL +** in the mxFrame field. +** +** Each index block except for the first contains information on +** HASHTABLE_NPAGE frames. The first index block contains information on +** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and +** HASHTABLE_NPAGE are selected so that together the wal-index header and +** first index block are the same size as all other index blocks in the +** wal-index. +** +** Each index block contains two sections, a page-mapping that contains the +** database page number associated with each wal frame, and a hash-table +** that allows readers to query an index block for a specific page number. +** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE +** for the first index block) 32-bit page numbers. The first entry in the +** first index-block contains the database page number corresponding to the +** first frame in the WAL file. The first entry in the second index block +** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in +** the log, and so on. +** +** The last index block in a wal-index usually contains less than the full +** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers, +** depending on the contents of the WAL file. This does not change the +** allocated size of the page-mapping array - the page-mapping array merely +** contains unused entries. +** +** Even without using the hash table, the last frame for page P +** can be found by scanning the page-mapping sections of each index block +** starting with the last index block and moving toward the first, and +** within each index block, starting at the end and moving toward the +** beginning. The first entry that equals P corresponds to the frame +** holding the content for that page. +** +** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers. +** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the +** hash table for each page number in the mapping section, so the hash +** table is never more than half full. The expected number of collisions +** prior to finding a match is 1. Each entry of the hash table is an +** 1-based index of an entry in the mapping section of the same +** index block. Let K be the 1-based index of the largest entry in +** the mapping section. (For index blocks other than the last, K will +** always be exactly HASHTABLE_NPAGE (4096) and for the last index block +** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table +** contain a value of 0. +** +** To look for page P in the hash table, first compute a hash iKey on +** P as follows: +** +** iKey = (P * 383) % HASHTABLE_NSLOT +** +** Then start scanning entries of the hash table, starting with iKey +** (wrapping around to the beginning when the end of the hash table is +** reached) until an unused hash slot is found. Let the first unused slot +** be at index iUnused. (iUnused might be less than iKey if there was +** wrap-around.) Because the hash table is never more than half full, +** the search is guaranteed to eventually hit an unused entry. Let +** iMax be the value between iKey and iUnused, closest to iUnused, +** where aHash[iMax]==P. If there is no iMax entry (if there exists +** no hash slot such that aHash[i]==p) then page P is not in the +** current index block. Otherwise the iMax-th mapping entry of the +** current index block corresponds to the last entry that references +** page P. +** +** A hash search begins with the last index block and moves toward the +** first index block, looking for entries corresponding to page P. On +** average, only two or three slots in each index block need to be +** examined in order to either find the last entry for page P, or to +** establish that no such entry exists in the block. Each index block +** holds over 4000 entries. So two or three index blocks are sufficient +** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10 +** comparisons (on average) suffice to either locate a frame in the +** WAL or to establish that the frame does not exist in the WAL. This +** is much faster than scanning the entire 10MB WAL. +** +** Note that entries are added in order of increasing K. Hence, one +** reader might be using some value K0 and a second reader that started +** at a later time (after additional transactions were added to the WAL +** and to the wal-index) might be using a different value K1, where K1>K0. +** Both readers can use the same hash table and mapping section to get +** the correct result. There may be entries in the hash table with +** K>K0 but to the first reader, those entries will appear to be unused +** slots in the hash table and so the first reader will get an answer as +** if no values greater than K0 had ever been inserted into the hash table +** in the first place - which is what reader one wants. Meanwhile, the +** second reader using K1 will see additional values that were inserted +** later, which is exactly what reader two wants. +** +** When a rollback occurs, the value of K is decreased. Hash table entries +** that correspond to frames greater than the new K value are removed +** from the hash table at this point. +*/ +#ifndef SQLITE_OMIT_WAL + +#include "wal.h" + +/* +** Trace output macros +*/ +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) +int sqlite3WalTrace = 0; +# define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X +#else +# define WALTRACE(X) +#endif + +/* +** The maximum (and only) versions of the wal and wal-index formats +** that may be interpreted by this version of SQLite. +** +** If a client begins recovering a WAL file and finds that (a) the checksum +** values in the wal-header are correct and (b) the version field is not +** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN. +** +** Similarly, if a client successfully reads a wal-index header (i.e. the +** checksum test is successful) and finds that the version field is not +** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite +** returns SQLITE_CANTOPEN. +*/ +#define WAL_MAX_VERSION 3007000 +#define WALINDEX_MAX_VERSION 3007000 + +/* +** Indices of various locking bytes. WAL_NREADER is the number +** of available reader locks and should be at least 3. +*/ +#define WAL_WRITE_LOCK 0 +#define WAL_ALL_BUT_WRITE 1 +#define WAL_CKPT_LOCK 1 +#define WAL_RECOVER_LOCK 2 +#define WAL_READ_LOCK(I) (3+(I)) +#define WAL_NREADER (SQLITE_SHM_NLOCK-3) + + +/* Object declarations */ +typedef struct WalIndexHdr WalIndexHdr; +typedef struct WalIterator WalIterator; +typedef struct WalCkptInfo WalCkptInfo; + + +/* +** The following object holds a copy of the wal-index header content. +** +** The actual header in the wal-index consists of two copies of this +** object. +** +** The szPage value can be any power of 2 between 512 and 32768, inclusive. +** Or it can be 1 to represent a 65536-byte page. The latter case was +** added in 3.7.1 when support for 64K pages was added. +*/ +struct WalIndexHdr { + u32 iVersion; /* Wal-index version */ + u32 unused; /* Unused (padding) field */ + u32 iChange; /* Counter incremented each transaction */ + u8 isInit; /* 1 when initialized */ + u8 bigEndCksum; /* True if checksums in WAL are big-endian */ + u16 szPage; /* Database page size in bytes. 1==64K */ + u32 mxFrame; /* Index of last valid frame in the WAL */ + u32 nPage; /* Size of database in pages */ + u32 aFrameCksum[2]; /* Checksum of last frame in log */ + u32 aSalt[2]; /* Two salt values copied from WAL header */ + u32 aCksum[2]; /* Checksum over all prior fields */ +}; + +/* +** A copy of the following object occurs in the wal-index immediately +** following the second copy of the WalIndexHdr. This object stores +** information used by checkpoint. +** +** nBackfill is the number of frames in the WAL that have been written +** back into the database. (We call the act of moving content from WAL to +** database "backfilling".) The nBackfill number is never greater than +** WalIndexHdr.mxFrame. nBackfill can only be increased by threads +** holding the WAL_CKPT_LOCK lock (which includes a recovery thread). +** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from +** mxFrame back to zero when the WAL is reset. +** +** There is one entry in aReadMark[] for each reader lock. If a reader +** holds read-lock K, then the value in aReadMark[K] is no greater than +** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff) +** for any aReadMark[] means that entry is unused. aReadMark[0] is +** a special case; its value is never used and it exists as a place-holder +** to avoid having to offset aReadMark[] indexs by one. Readers holding +** WAL_READ_LOCK(0) always ignore the entire WAL and read all content +** directly from the database. +** +** The value of aReadMark[K] may only be changed by a thread that +** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of +** aReadMark[K] cannot changed while there is a reader is using that mark +** since the reader will be holding a shared lock on WAL_READ_LOCK(K). +** +** The checkpointer may only transfer frames from WAL to database where +** the frame numbers are less than or equal to every aReadMark[] that is +** in use (that is, every aReadMark[j] for which there is a corresponding +** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the +** largest value and will increase an unused aReadMark[] to mxFrame if there +** is not already an aReadMark[] equal to mxFrame. The exception to the +** previous sentence is when nBackfill equals mxFrame (meaning that everything +** in the WAL has been backfilled into the database) then new readers +** will choose aReadMark[0] which has value 0 and hence such reader will +** get all their all content directly from the database file and ignore +** the WAL. +** +** Writers normally append new frames to the end of the WAL. However, +** if nBackfill equals mxFrame (meaning that all WAL content has been +** written back into the database) and if no readers are using the WAL +** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then +** the writer will first "reset" the WAL back to the beginning and start +** writing new content beginning at frame 1. +** +** We assume that 32-bit loads are atomic and so no locks are needed in +** order to read from any aReadMark[] entries. +*/ +struct WalCkptInfo { + u32 nBackfill; /* Number of WAL frames backfilled into DB */ + u32 aReadMark[WAL_NREADER]; /* Reader marks */ +}; +#define READMARK_NOT_USED 0xffffffff + + +/* A block of WALINDEX_LOCK_RESERVED bytes beginning at +** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems +** only support mandatory file-locks, we do not read or write data +** from the region of the file on which locks are applied. +*/ +#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo)) +#define WALINDEX_LOCK_RESERVED 16 +#define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED) + +/* Size of header before each frame in wal */ +#define WAL_FRAME_HDRSIZE 24 + +/* Size of write ahead log header, including checksum. */ +/* #define WAL_HDRSIZE 24 */ +#define WAL_HDRSIZE 32 + +/* WAL magic value. Either this value, or the same value with the least +** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit +** big-endian format in the first 4 bytes of a WAL file. +** +** If the LSB is set, then the checksums for each frame within the WAL +** file are calculated by treating all data as an array of 32-bit +** big-endian words. Otherwise, they are calculated by interpreting +** all data as 32-bit little-endian words. +*/ +#define WAL_MAGIC 0x377f0682 + +/* +** Return the offset of frame iFrame in the write-ahead log file, +** assuming a database page size of szPage bytes. The offset returned +** is to the start of the write-ahead log frame-header. +*/ +#define walFrameOffset(iFrame, szPage) ( \ + WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \ +) + +/* +** An open write-ahead log file is represented by an instance of the +** following object. +*/ +struct Wal { + sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */ + sqlite3_file *pDbFd; /* File handle for the database file */ + sqlite3_file *pWalFd; /* File handle for WAL file */ + u32 iCallback; /* Value to pass to log callback (or 0) */ + i64 mxWalSize; /* Truncate WAL to this size upon reset */ + int nWiData; /* Size of array apWiData */ + int szFirstBlock; /* Size of first block written to WAL file */ + volatile u32 **apWiData; /* Pointer to wal-index content in memory */ + u32 szPage; /* Database page size */ + i16 readLock; /* Which read lock is being held. -1 for none */ + u8 syncFlags; /* Flags to use to sync header writes */ + u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */ + u8 writeLock; /* True if in a write transaction */ + u8 ckptLock; /* True if holding a checkpoint lock */ + u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */ + u8 truncateOnCommit; /* True to truncate WAL file on commit */ + u8 syncHeader; /* Fsync the WAL header if true */ + u8 padToSectorBoundary; /* Pad transactions out to the next sector */ + WalIndexHdr hdr; /* Wal-index header for current transaction */ + const char *zWalName; /* Name of WAL file */ + u32 nCkpt; /* Checkpoint sequence counter in the wal-header */ +#ifdef SQLITE_DEBUG + u8 lockError; /* True if a locking error has occurred */ +#endif +}; + +/* +** Candidate values for Wal.exclusiveMode. +*/ +#define WAL_NORMAL_MODE 0 +#define WAL_EXCLUSIVE_MODE 1 +#define WAL_HEAPMEMORY_MODE 2 + +/* +** Possible values for WAL.readOnly +*/ +#define WAL_RDWR 0 /* Normal read/write connection */ +#define WAL_RDONLY 1 /* The WAL file is readonly */ +#define WAL_SHM_RDONLY 2 /* The SHM file is readonly */ + +/* +** Each page of the wal-index mapping contains a hash-table made up of +** an array of HASHTABLE_NSLOT elements of the following type. +*/ +typedef u16 ht_slot; + +/* +** This structure is used to implement an iterator that loops through +** all frames in the WAL in database page order. Where two or more frames +** correspond to the same database page, the iterator visits only the +** frame most recently written to the WAL (in other words, the frame with +** the largest index). +** +** The internals of this structure are only accessed by: +** +** walIteratorInit() - Create a new iterator, +** walIteratorNext() - Step an iterator, +** walIteratorFree() - Free an iterator. +** +** This functionality is used by the checkpoint code (see walCheckpoint()). +*/ +struct WalIterator { + int iPrior; /* Last result returned from the iterator */ + int nSegment; /* Number of entries in aSegment[] */ + struct WalSegment { + int iNext; /* Next slot in aIndex[] not yet returned */ + ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */ + u32 *aPgno; /* Array of page numbers. */ + int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */ + int iZero; /* Frame number associated with aPgno[0] */ + } aSegment[1]; /* One for every 32KB page in the wal-index */ +}; + +/* +** Define the parameters of the hash tables in the wal-index file. There +** is a hash-table following every HASHTABLE_NPAGE page numbers in the +** wal-index. +** +** Changing any of these constants will alter the wal-index format and +** create incompatibilities. +*/ +#define HASHTABLE_NPAGE 4096 /* Must be power of 2 */ +#define HASHTABLE_HASH_1 383 /* Should be prime */ +#define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */ + +/* +** The block of page numbers associated with the first hash-table in a +** wal-index is smaller than usual. This is so that there is a complete +** hash-table on each aligned 32KB page of the wal-index. +*/ +#define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32))) + +/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */ +#define WALINDEX_PGSZ ( \ + sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \ +) + +/* +** Obtain a pointer to the iPage'th page of the wal-index. The wal-index +** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are +** numbered from zero. +** +** If this call is successful, *ppPage is set to point to the wal-index +** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs, +** then an SQLite error code is returned and *ppPage is set to 0. +*/ +static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){ + int rc = SQLITE_OK; + + /* Enlarge the pWal->apWiData[] array if required */ + if( pWal->nWiData<=iPage ){ + int nByte = sizeof(u32*)*(iPage+1); + volatile u32 **apNew; + apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte); + if( !apNew ){ + *ppPage = 0; + return SQLITE_NOMEM; + } + memset((void*)&apNew[pWal->nWiData], 0, + sizeof(u32*)*(iPage+1-pWal->nWiData)); + pWal->apWiData = apNew; + pWal->nWiData = iPage+1; + } + + /* Request a pointer to the required page from the VFS */ + if( pWal->apWiData[iPage]==0 ){ + if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ + pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ); + if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM; + }else{ + rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, + pWal->writeLock, (void volatile **)&pWal->apWiData[iPage] + ); + if( rc==SQLITE_READONLY ){ + pWal->readOnly |= WAL_SHM_RDONLY; + rc = SQLITE_OK; + } + } + } + + *ppPage = pWal->apWiData[iPage]; + assert( iPage==0 || *ppPage || rc!=SQLITE_OK ); + return rc; +} + +/* +** Return a pointer to the WalCkptInfo structure in the wal-index. +*/ +static volatile WalCkptInfo *walCkptInfo(Wal *pWal){ + assert( pWal->nWiData>0 && pWal->apWiData[0] ); + return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]); +} + +/* +** Return a pointer to the WalIndexHdr structure in the wal-index. +*/ +static volatile WalIndexHdr *walIndexHdr(Wal *pWal){ + assert( pWal->nWiData>0 && pWal->apWiData[0] ); + return (volatile WalIndexHdr*)pWal->apWiData[0]; +} + +/* +** The argument to this macro must be of type u32. On a little-endian +** architecture, it returns the u32 value that results from interpreting +** the 4 bytes as a big-endian value. On a big-endian architecture, it +** returns the value that would be produced by intepreting the 4 bytes +** of the input value as a little-endian integer. +*/ +#define BYTESWAP32(x) ( \ + (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \ + + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \ +) + +/* +** Generate or extend an 8 byte checksum based on the data in +** array aByte[] and the initial values of aIn[0] and aIn[1] (or +** initial values of 0 and 0 if aIn==NULL). +** +** The checksum is written back into aOut[] before returning. +** +** nByte must be a positive multiple of 8. +*/ +static void walChecksumBytes( + int nativeCksum, /* True for native byte-order, false for non-native */ + u8 *a, /* Content to be checksummed */ + int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */ + const u32 *aIn, /* Initial checksum value input */ + u32 *aOut /* OUT: Final checksum value output */ +){ + u32 s1, s2; + u32 *aData = (u32 *)a; + u32 *aEnd = (u32 *)&a[nByte]; + + if( aIn ){ + s1 = aIn[0]; + s2 = aIn[1]; + }else{ + s1 = s2 = 0; + } + + assert( nByte>=8 ); + assert( (nByte&0x00000007)==0 ); + + if( nativeCksum ){ + do { + s1 += *aData++ + s2; + s2 += *aData++ + s1; + }while( aDataexclusiveMode!=WAL_HEAPMEMORY_MODE ){ + sqlite3OsShmBarrier(pWal->pDbFd); + } +} + +/* +** Write the header information in pWal->hdr into the wal-index. +** +** The checksum on pWal->hdr is updated before it is written. +*/ +static void walIndexWriteHdr(Wal *pWal){ + volatile WalIndexHdr *aHdr = walIndexHdr(pWal); + const int nCksum = offsetof(WalIndexHdr, aCksum); + + assert( pWal->writeLock ); + pWal->hdr.isInit = 1; + pWal->hdr.iVersion = WALINDEX_MAX_VERSION; + walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum); + memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr)); + walShmBarrier(pWal); + memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr)); +} + +/* +** This function encodes a single frame header and writes it to a buffer +** supplied by the caller. A frame-header is made up of a series of +** 4-byte big-endian integers, as follows: +** +** 0: Page number. +** 4: For commit records, the size of the database image in pages +** after the commit. For all other records, zero. +** 8: Salt-1 (copied from the wal-header) +** 12: Salt-2 (copied from the wal-header) +** 16: Checksum-1. +** 20: Checksum-2. +*/ +static void walEncodeFrame( + Wal *pWal, /* The write-ahead log */ + u32 iPage, /* Database page number for frame */ + u32 nTruncate, /* New db size (or 0 for non-commit frames) */ + u8 *aData, /* Pointer to page data */ + u8 *aFrame /* OUT: Write encoded frame here */ +){ + int nativeCksum; /* True for native byte-order checksums */ + u32 *aCksum = pWal->hdr.aFrameCksum; + assert( WAL_FRAME_HDRSIZE==24 ); + sqlite3Put4byte(&aFrame[0], iPage); + sqlite3Put4byte(&aFrame[4], nTruncate); + memcpy(&aFrame[8], pWal->hdr.aSalt, 8); + + nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); + walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); + walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); + + sqlite3Put4byte(&aFrame[16], aCksum[0]); + sqlite3Put4byte(&aFrame[20], aCksum[1]); +} + +/* +** Check to see if the frame with header in aFrame[] and content +** in aData[] is valid. If it is a valid frame, fill *piPage and +** *pnTruncate and return true. Return if the frame is not valid. +*/ +static int walDecodeFrame( + Wal *pWal, /* The write-ahead log */ + u32 *piPage, /* OUT: Database page number for frame */ + u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */ + u8 *aData, /* Pointer to page data (for checksum) */ + u8 *aFrame /* Frame data */ +){ + int nativeCksum; /* True for native byte-order checksums */ + u32 *aCksum = pWal->hdr.aFrameCksum; + u32 pgno; /* Page number of the frame */ + assert( WAL_FRAME_HDRSIZE==24 ); + + /* A frame is only valid if the salt values in the frame-header + ** match the salt values in the wal-header. + */ + if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){ + return 0; + } + + /* A frame is only valid if the page number is creater than zero. + */ + pgno = sqlite3Get4byte(&aFrame[0]); + if( pgno==0 ){ + return 0; + } + + /* A frame is only valid if a checksum of the WAL header, + ** all prior frams, the first 16 bytes of this frame-header, + ** and the frame-data matches the checksum in the last 8 + ** bytes of this frame-header. + */ + nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); + walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); + walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); + if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) + || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) + ){ + /* Checksum failed. */ + return 0; + } + + /* If we reach this point, the frame is valid. Return the page number + ** and the new database size. + */ + *piPage = pgno; + *pnTruncate = sqlite3Get4byte(&aFrame[4]); + return 1; +} + + +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) +/* +** Names of locks. This routine is used to provide debugging output and is not +** a part of an ordinary build. +*/ +static const char *walLockName(int lockIdx){ + if( lockIdx==WAL_WRITE_LOCK ){ + return "WRITE-LOCK"; + }else if( lockIdx==WAL_CKPT_LOCK ){ + return "CKPT-LOCK"; + }else if( lockIdx==WAL_RECOVER_LOCK ){ + return "RECOVER-LOCK"; + }else{ + static char zName[15]; + sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]", + lockIdx-WAL_READ_LOCK(0)); + return zName; + } +} +#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ + + +/* +** Set or release locks on the WAL. Locks are either shared or exclusive. +** A lock cannot be moved directly between shared and exclusive - it must go +** through the unlocked state first. +** +** In locking_mode=EXCLUSIVE, all of these routines become no-ops. +*/ +static int walLockShared(Wal *pWal, int lockIdx){ + int rc; + if( pWal->exclusiveMode ) return SQLITE_OK; + rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, + SQLITE_SHM_LOCK | SQLITE_SHM_SHARED); + WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal, + walLockName(lockIdx), rc ? "failed" : "ok")); + VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); ) + return rc; +} +static void walUnlockShared(Wal *pWal, int lockIdx){ + if( pWal->exclusiveMode ) return; + (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, + SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED); + WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx))); +} +static int walLockExclusive(Wal *pWal, int lockIdx, int n){ + int rc; + if( pWal->exclusiveMode ) return SQLITE_OK; + rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, + SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE); + WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal, + walLockName(lockIdx), n, rc ? "failed" : "ok")); + VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); ) + return rc; +} +static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){ + if( pWal->exclusiveMode ) return; + (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, + SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE); + WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal, + walLockName(lockIdx), n)); +} + +/* +** Compute a hash on a page number. The resulting hash value must land +** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances +** the hash to the next value in the event of a collision. +*/ +static int walHash(u32 iPage){ + assert( iPage>0 ); + assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 ); + return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1); +} +static int walNextHash(int iPriorHash){ + return (iPriorHash+1)&(HASHTABLE_NSLOT-1); +} + +/* +** Return pointers to the hash table and page number array stored on +** page iHash of the wal-index. The wal-index is broken into 32KB pages +** numbered starting from 0. +** +** Set output variable *paHash to point to the start of the hash table +** in the wal-index file. Set *piZero to one less than the frame +** number of the first frame indexed by this hash table. If a +** slot in the hash table is set to N, it refers to frame number +** (*piZero+N) in the log. +** +** Finally, set *paPgno so that *paPgno[1] is the page number of the +** first frame indexed by the hash table, frame (*piZero+1). +*/ +static int walHashGet( + Wal *pWal, /* WAL handle */ + int iHash, /* Find the iHash'th table */ + volatile ht_slot **paHash, /* OUT: Pointer to hash index */ + volatile u32 **paPgno, /* OUT: Pointer to page number array */ + u32 *piZero /* OUT: Frame associated with *paPgno[0] */ +){ + int rc; /* Return code */ + volatile u32 *aPgno; + + rc = walIndexPage(pWal, iHash, &aPgno); + assert( rc==SQLITE_OK || iHash>0 ); + + if( rc==SQLITE_OK ){ + u32 iZero; + volatile ht_slot *aHash; + + aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE]; + if( iHash==0 ){ + aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)]; + iZero = 0; + }else{ + iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE; + } + + *paPgno = &aPgno[-1]; + *paHash = aHash; + *piZero = iZero; + } + return rc; +} + +/* +** Return the number of the wal-index page that contains the hash-table +** and page-number array that contain entries corresponding to WAL frame +** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages +** are numbered starting from 0. +*/ +static int walFramePage(u32 iFrame){ + int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE; + assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE) + && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE) + && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)) + && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE) + && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE)) + ); + return iHash; +} + +/* +** Return the page number associated with frame iFrame in this WAL. +*/ +static u32 walFramePgno(Wal *pWal, u32 iFrame){ + int iHash = walFramePage(iFrame); + if( iHash==0 ){ + return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1]; + } + return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE]; +} + +/* +** Remove entries from the hash table that point to WAL slots greater +** than pWal->hdr.mxFrame. +** +** This function is called whenever pWal->hdr.mxFrame is decreased due +** to a rollback or savepoint. +** +** At most only the hash table containing pWal->hdr.mxFrame needs to be +** updated. Any later hash tables will be automatically cleared when +** pWal->hdr.mxFrame advances to the point where those hash tables are +** actually needed. +*/ +static void walCleanupHash(Wal *pWal){ + volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */ + volatile u32 *aPgno = 0; /* Page number array for hash table */ + u32 iZero = 0; /* frame == (aHash[x]+iZero) */ + int iLimit = 0; /* Zero values greater than this */ + int nByte; /* Number of bytes to zero in aPgno[] */ + int i; /* Used to iterate through aHash[] */ + + assert( pWal->writeLock ); + testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 ); + testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE ); + testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 ); + + if( pWal->hdr.mxFrame==0 ) return; + + /* Obtain pointers to the hash-table and page-number array containing + ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed + ** that the page said hash-table and array reside on is already mapped. + */ + assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) ); + assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] ); + walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero); + + /* Zero all hash-table entries that correspond to frame numbers greater + ** than pWal->hdr.mxFrame. + */ + iLimit = pWal->hdr.mxFrame - iZero; + assert( iLimit>0 ); + for(i=0; iiLimit ){ + aHash[i] = 0; + } + } + + /* Zero the entries in the aPgno array that correspond to frames with + ** frame numbers greater than pWal->hdr.mxFrame. + */ + nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]); + memset((void *)&aPgno[iLimit+1], 0, nByte); + +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT + /* Verify that the every entry in the mapping region is still reachable + ** via the hash table even after the cleanup. + */ + if( iLimit ){ + int i; /* Loop counter */ + int iKey; /* Hash key */ + for(i=1; i<=iLimit; i++){ + for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){ + if( aHash[iKey]==i ) break; + } + assert( aHash[iKey]==i ); + } + } +#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ +} + + +/* +** Set an entry in the wal-index that will map database page number +** pPage into WAL frame iFrame. +*/ +static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ + int rc; /* Return code */ + u32 iZero = 0; /* One less than frame number of aPgno[1] */ + volatile u32 *aPgno = 0; /* Page number array */ + volatile ht_slot *aHash = 0; /* Hash table */ + + rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero); + + /* Assuming the wal-index file was successfully mapped, populate the + ** page number array and hash table entry. + */ + if( rc==SQLITE_OK ){ + int iKey; /* Hash table key */ + int idx; /* Value to write to hash-table slot */ + int nCollide; /* Number of hash collisions */ + + idx = iFrame - iZero; + assert( idx <= HASHTABLE_NSLOT/2 + 1 ); + + /* If this is the first entry to be added to this hash-table, zero the + ** entire hash table and aPgno[] array before proceding. + */ + if( idx==1 ){ + int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]); + memset((void*)&aPgno[1], 0, nByte); + } + + /* If the entry in aPgno[] is already set, then the previous writer + ** must have exited unexpectedly in the middle of a transaction (after + ** writing one or more dirty pages to the WAL to free up memory). + ** Remove the remnants of that writers uncommitted transaction from + ** the hash-table before writing any new entries. + */ + if( aPgno[idx] ){ + walCleanupHash(pWal); + assert( !aPgno[idx] ); + } + + /* Write the aPgno[] array entry and the hash-table slot. */ + nCollide = idx; + for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){ + if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT; + } + aPgno[idx] = iPage; + aHash[iKey] = (ht_slot)idx; + +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT + /* Verify that the number of entries in the hash table exactly equals + ** the number of entries in the mapping region. + */ + { + int i; /* Loop counter */ + int nEntry = 0; /* Number of entries in the hash table */ + for(i=0; ickptLock==1 || pWal->ckptLock==0 ); + assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 ); + assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE ); + assert( pWal->writeLock ); + iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock; + nLock = SQLITE_SHM_NLOCK - iLock; + rc = walLockExclusive(pWal, iLock, nLock); + if( rc ){ + return rc; + } + WALTRACE(("WAL%p: recovery begin...\n", pWal)); + + memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); + + rc = sqlite3OsFileSize(pWal->pWalFd, &nSize); + if( rc!=SQLITE_OK ){ + goto recovery_error; + } + + if( nSize>WAL_HDRSIZE ){ + u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */ + u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */ + int szFrame; /* Number of bytes in buffer aFrame[] */ + u8 *aData; /* Pointer to data part of aFrame buffer */ + int iFrame; /* Index of last frame read */ + i64 iOffset; /* Next offset to read from log file */ + int szPage; /* Page size according to the log */ + u32 magic; /* Magic value read from WAL header */ + u32 version; /* Magic value read from WAL header */ + int isValid; /* True if this frame is valid */ + + /* Read in the WAL header. */ + rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0); + if( rc!=SQLITE_OK ){ + goto recovery_error; + } + + /* If the database page size is not a power of two, or is greater than + ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid + ** data. Similarly, if the 'magic' value is invalid, ignore the whole + ** WAL file. + */ + magic = sqlite3Get4byte(&aBuf[0]); + szPage = sqlite3Get4byte(&aBuf[8]); + if( (magic&0xFFFFFFFE)!=WAL_MAGIC + || szPage&(szPage-1) + || szPage>SQLITE_MAX_PAGE_SIZE + || szPage<512 + ){ + goto finished; + } + pWal->hdr.bigEndCksum = (u8)(magic&0x00000001); + pWal->szPage = szPage; + pWal->nCkpt = sqlite3Get4byte(&aBuf[12]); + memcpy(&pWal->hdr.aSalt, &aBuf[16], 8); + + /* Verify that the WAL header checksum is correct */ + walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, + aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum + ); + if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24]) + || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28]) + ){ + goto finished; + } + + /* Verify that the version number on the WAL format is one that + ** are able to understand */ + version = sqlite3Get4byte(&aBuf[4]); + if( version!=WAL_MAX_VERSION ){ + rc = SQLITE_CANTOPEN_BKPT; + goto finished; + } + + /* Malloc a buffer to read frames into. */ + szFrame = szPage + WAL_FRAME_HDRSIZE; + aFrame = (u8 *)sqlite3_malloc(szFrame); + if( !aFrame ){ + rc = SQLITE_NOMEM; + goto recovery_error; + } + aData = &aFrame[WAL_FRAME_HDRSIZE]; + + /* Read all frames from the log file. */ + iFrame = 0; + for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){ + u32 pgno; /* Database page number for frame */ + u32 nTruncate; /* dbsize field from frame header */ + + /* Read and decode the next log frame. */ + iFrame++; + rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); + if( rc!=SQLITE_OK ) break; + isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame); + if( !isValid ) break; + rc = walIndexAppend(pWal, iFrame, pgno); + if( rc!=SQLITE_OK ) break; + + /* If nTruncate is non-zero, this is a commit record. */ + if( nTruncate ){ + pWal->hdr.mxFrame = iFrame; + pWal->hdr.nPage = nTruncate; + pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); + testcase( szPage<=32768 ); + testcase( szPage>=65536 ); + aFrameCksum[0] = pWal->hdr.aFrameCksum[0]; + aFrameCksum[1] = pWal->hdr.aFrameCksum[1]; + } + } + + sqlite3_free(aFrame); + } + +finished: + if( rc==SQLITE_OK ){ + volatile WalCkptInfo *pInfo; + int i; + pWal->hdr.aFrameCksum[0] = aFrameCksum[0]; + pWal->hdr.aFrameCksum[1] = aFrameCksum[1]; + walIndexWriteHdr(pWal); + + /* Reset the checkpoint-header. This is safe because this thread is + ** currently holding locks that exclude all other readers, writers and + ** checkpointers. + */ + pInfo = walCkptInfo(pWal); + pInfo->nBackfill = 0; + pInfo->aReadMark[0] = 0; + for(i=1; iaReadMark[i] = READMARK_NOT_USED; + if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame; + + /* If more than one frame was recovered from the log file, report an + ** event via sqlite3_log(). This is to help with identifying performance + ** problems caused by applications routinely shutting down without + ** checkpointing the log file. + */ + if( pWal->hdr.nPage ){ + sqlite3_log(SQLITE_NOTICE_RECOVER_WAL, + "recovered %d frames from WAL file %s", + pWal->hdr.mxFrame, pWal->zWalName + ); + } + } + +recovery_error: + WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok")); + walUnlockExclusive(pWal, iLock, nLock); + return rc; +} + +/* +** Close an open wal-index. +*/ +static void walIndexClose(Wal *pWal, int isDelete){ + if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ + int i; + for(i=0; inWiData; i++){ + sqlite3_free((void *)pWal->apWiData[i]); + pWal->apWiData[i] = 0; + } + }else{ + sqlite3OsShmUnmap(pWal->pDbFd, isDelete); + } +} + +/* +** Open a connection to the WAL file zWalName. The database file must +** already be opened on connection pDbFd. The buffer that zWalName points +** to must remain valid for the lifetime of the returned Wal* handle. +** +** A SHARED lock should be held on the database file when this function +** is called. The purpose of this SHARED lock is to prevent any other +** client from unlinking the WAL or wal-index file. If another process +** were to do this just after this client opened one of these files, the +** system would be badly broken. +** +** If the log file is successfully opened, SQLITE_OK is returned and +** *ppWal is set to point to a new WAL handle. If an error occurs, +** an SQLite error code is returned and *ppWal is left unmodified. +*/ +int sqlite3WalOpen( + sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */ + sqlite3_file *pDbFd, /* The open database file */ + const char *zWalName, /* Name of the WAL file */ + int bNoShm, /* True to run in heap-memory mode */ + i64 mxWalSize, /* Truncate WAL to this size on reset */ + Wal **ppWal /* OUT: Allocated Wal handle */ +){ + int rc; /* Return Code */ + Wal *pRet; /* Object to allocate and return */ + int flags; /* Flags passed to OsOpen() */ + + assert( zWalName && zWalName[0] ); + assert( pDbFd ); + + /* In the amalgamation, the os_unix.c and os_win.c source files come before + ** this source file. Verify that the #defines of the locking byte offsets + ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value. + */ +#ifdef WIN_SHM_BASE + assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET ); +#endif +#ifdef UNIX_SHM_BASE + assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET ); +#endif + + + /* Allocate an instance of struct Wal to return. */ + *ppWal = 0; + pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile); + if( !pRet ){ + return SQLITE_NOMEM; + } + + pRet->pVfs = pVfs; + pRet->pWalFd = (sqlite3_file *)&pRet[1]; + pRet->pDbFd = pDbFd; + pRet->readLock = -1; + pRet->mxWalSize = mxWalSize; + pRet->zWalName = zWalName; + pRet->syncHeader = 1; + pRet->padToSectorBoundary = 1; + pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE); + + /* Open file handle on the write-ahead log file. */ + flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL); + rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags); + if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){ + pRet->readOnly = WAL_RDONLY; + } + + if( rc!=SQLITE_OK ){ + walIndexClose(pRet, 0); + sqlite3OsClose(pRet->pWalFd); + sqlite3_free(pRet); + }else{ + int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd); + if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; } + if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){ + pRet->padToSectorBoundary = 0; + } + *ppWal = pRet; + WALTRACE(("WAL%d: opened\n", pRet)); + } + return rc; +} + +/* +** Change the size to which the WAL file is trucated on each reset. +*/ +void sqlite3WalLimit(Wal *pWal, i64 iLimit){ + if( pWal ) pWal->mxWalSize = iLimit; +} + +/* +** Find the smallest page number out of all pages held in the WAL that +** has not been returned by any prior invocation of this method on the +** same WalIterator object. Write into *piFrame the frame index where +** that page was last written into the WAL. Write into *piPage the page +** number. +** +** Return 0 on success. If there are no pages in the WAL with a page +** number larger than *piPage, then return 1. +*/ +static int walIteratorNext( + WalIterator *p, /* Iterator */ + u32 *piPage, /* OUT: The page number of the next page */ + u32 *piFrame /* OUT: Wal frame index of next page */ +){ + u32 iMin; /* Result pgno must be greater than iMin */ + u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */ + int i; /* For looping through segments */ + + iMin = p->iPrior; + assert( iMin<0xffffffff ); + for(i=p->nSegment-1; i>=0; i--){ + struct WalSegment *pSegment = &p->aSegment[i]; + while( pSegment->iNextnEntry ){ + u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]]; + if( iPg>iMin ){ + if( iPgiZero + pSegment->aIndex[pSegment->iNext]; + } + break; + } + pSegment->iNext++; + } + } + + *piPage = p->iPrior = iRet; + return (iRet==0xFFFFFFFF); +} + +/* +** This function merges two sorted lists into a single sorted list. +** +** aLeft[] and aRight[] are arrays of indices. The sort key is +** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following +** is guaranteed for all J0 && nRight>0 ); + while( iRight=nRight || aContent[aLeft[iLeft]]=nLeft || aContent[aLeft[iLeft]]>dbpage ); + assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage ); + } + + *paRight = aLeft; + *pnRight = iOut; + memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut); +} + +/* +** Sort the elements in list aList using aContent[] as the sort key. +** Remove elements with duplicate keys, preferring to keep the +** larger aList[] values. +** +** The aList[] entries are indices into aContent[]. The values in +** aList[] are to be sorted so that for all J0 ); + assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) ); + + for(iList=0; iListaList && p->nList<=(1<aList==&aList[iList&~((2<aList, p->nList, &aMerge, &nMerge, aBuffer); + } + aSub[iSub].aList = aMerge; + aSub[iSub].nList = nMerge; + } + + for(iSub++; iSubnList<=(1<aList==&aList[nList&~((2<aList, p->nList, &aMerge, &nMerge, aBuffer); + } + } + assert( aMerge==aList ); + *pnList = nMerge; + +#ifdef SQLITE_DEBUG + { + int i; + for(i=1; i<*pnList; i++){ + assert( aContent[aList[i]] > aContent[aList[i-1]] ); + } + } +#endif +} + +/* +** Free an iterator allocated by walIteratorInit(). +*/ +static void walIteratorFree(WalIterator *p){ + sqlite3ScratchFree(p); +} + +/* +** Construct a WalInterator object that can be used to loop over all +** pages in the WAL in ascending order. The caller must hold the checkpoint +** lock. +** +** On success, make *pp point to the newly allocated WalInterator object +** return SQLITE_OK. Otherwise, return an error code. If this routine +** returns an error, the value of *pp is undefined. +** +** The calling routine should invoke walIteratorFree() to destroy the +** WalIterator object when it has finished with it. +*/ +static int walIteratorInit(Wal *pWal, WalIterator **pp){ + WalIterator *p; /* Return value */ + int nSegment; /* Number of segments to merge */ + u32 iLast; /* Last frame in log */ + int nByte; /* Number of bytes to allocate */ + int i; /* Iterator variable */ + ht_slot *aTmp; /* Temp space used by merge-sort */ + int rc = SQLITE_OK; /* Return Code */ + + /* This routine only runs while holding the checkpoint lock. And + ** it only runs if there is actually content in the log (mxFrame>0). + */ + assert( pWal->ckptLock && pWal->hdr.mxFrame>0 ); + iLast = pWal->hdr.mxFrame; + + /* Allocate space for the WalIterator object. */ + nSegment = walFramePage(iLast) + 1; + nByte = sizeof(WalIterator) + + (nSegment-1)*sizeof(struct WalSegment) + + iLast*sizeof(ht_slot); + p = (WalIterator *)sqlite3ScratchMalloc(nByte); + if( !p ){ + return SQLITE_NOMEM; + } + memset(p, 0, nByte); + p->nSegment = nSegment; + + /* Allocate temporary space used by the merge-sort routine. This block + ** of memory will be freed before this function returns. + */ + aTmp = (ht_slot *)sqlite3ScratchMalloc( + sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast) + ); + if( !aTmp ){ + rc = SQLITE_NOMEM; + } + + for(i=0; rc==SQLITE_OK && iaSegment[p->nSegment])[iZero]; + iZero++; + + for(j=0; jaSegment[i].iZero = iZero; + p->aSegment[i].nEntry = nEntry; + p->aSegment[i].aIndex = aIndex; + p->aSegment[i].aPgno = (u32 *)aPgno; + } + } + sqlite3ScratchFree(aTmp); + + if( rc!=SQLITE_OK ){ + walIteratorFree(p); + } + *pp = p; + return rc; +} + +/* +** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and +** n. If the attempt fails and parameter xBusy is not NULL, then it is a +** busy-handler function. Invoke it and retry the lock until either the +** lock is successfully obtained or the busy-handler returns 0. +*/ +static int walBusyLock( + Wal *pWal, /* WAL connection */ + int (*xBusy)(void*), /* Function to call when busy */ + void *pBusyArg, /* Context argument for xBusyHandler */ + int lockIdx, /* Offset of first byte to lock */ + int n /* Number of bytes to lock */ +){ + int rc; + do { + rc = walLockExclusive(pWal, lockIdx, n); + }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) ); + return rc; +} + +/* +** The cache of the wal-index header must be valid to call this function. +** Return the page-size in bytes used by the database. +*/ +static int walPagesize(Wal *pWal){ + return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); +} + +/* +** Copy as much content as we can from the WAL back into the database file +** in response to an sqlite3_wal_checkpoint() request or the equivalent. +** +** The amount of information copies from WAL to database might be limited +** by active readers. This routine will never overwrite a database page +** that a concurrent reader might be using. +** +** All I/O barrier operations (a.k.a fsyncs) occur in this routine when +** SQLite is in WAL-mode in synchronous=NORMAL. That means that if +** checkpoints are always run by a background thread or background +** process, foreground threads will never block on a lengthy fsync call. +** +** Fsync is called on the WAL before writing content out of the WAL and +** into the database. This ensures that if the new content is persistent +** in the WAL and can be recovered following a power-loss or hard reset. +** +** Fsync is also called on the database file if (and only if) the entire +** WAL content is copied into the database file. This second fsync makes +** it safe to delete the WAL since the new content will persist in the +** database file. +** +** This routine uses and updates the nBackfill field of the wal-index header. +** This is the only routine tha will increase the value of nBackfill. +** (A WAL reset or recovery will revert nBackfill to zero, but not increase +** its value.) +** +** The caller must be holding sufficient locks to ensure that no other +** checkpoint is running (in any other thread or process) at the same +** time. +*/ +static int walCheckpoint( + Wal *pWal, /* Wal connection */ + int eMode, /* One of PASSIVE, FULL or RESTART */ + int (*xBusyCall)(void*), /* Function to call when busy */ + void *pBusyArg, /* Context argument for xBusyHandler */ + int sync_flags, /* Flags for OsSync() (or 0) */ + u8 *zBuf /* Temporary buffer to use */ +){ + int rc; /* Return code */ + int szPage; /* Database page-size */ + WalIterator *pIter = 0; /* Wal iterator context */ + u32 iDbpage = 0; /* Next database page to write */ + u32 iFrame = 0; /* Wal frame containing data for iDbpage */ + u32 mxSafeFrame; /* Max frame that can be backfilled */ + u32 mxPage; /* Max database page to write */ + int i; /* Loop counter */ + volatile WalCkptInfo *pInfo; /* The checkpoint status information */ + int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */ + + szPage = walPagesize(pWal); + testcase( szPage<=32768 ); + testcase( szPage>=65536 ); + pInfo = walCkptInfo(pWal); + if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK; + + /* Allocate the iterator */ + rc = walIteratorInit(pWal, &pIter); + if( rc!=SQLITE_OK ){ + return rc; + } + assert( pIter ); + + if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall; + + /* Compute in mxSafeFrame the index of the last frame of the WAL that is + ** safe to write into the database. Frames beyond mxSafeFrame might + ** overwrite database pages that are in use by active readers and thus + ** cannot be backfilled from the WAL. + */ + mxSafeFrame = pWal->hdr.mxFrame; + mxPage = pWal->hdr.nPage; + for(i=1; iaReadMark[i]; + if( mxSafeFrame>y ){ + assert( y<=pWal->hdr.mxFrame ); + rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1); + if( rc==SQLITE_OK ){ + pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED); + walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); + }else if( rc==SQLITE_BUSY ){ + mxSafeFrame = y; + xBusy = 0; + }else{ + goto walcheckpoint_out; + } + } + } + + if( pInfo->nBackfillnBackfill; + + /* Sync the WAL to disk */ + if( sync_flags ){ + rc = sqlite3OsSync(pWal->pWalFd, sync_flags); + } + + /* If the database may grow as a result of this checkpoint, hint + ** about the eventual size of the db file to the VFS layer. + */ + if( rc==SQLITE_OK ){ + i64 nReq = ((i64)mxPage * szPage); + rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); + if( rc==SQLITE_OK && nSizepDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq); + } + } + + + /* Iterate through the contents of the WAL, copying data to the db file. */ + while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){ + i64 iOffset; + assert( walFramePgno(pWal, iFrame)==iDbpage ); + if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue; + iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE; + /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */ + rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); + if( rc!=SQLITE_OK ) break; + iOffset = (iDbpage-1)*(i64)szPage; + testcase( IS_BIG_INT(iOffset) ); + rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); + if( rc!=SQLITE_OK ) break; + } + + /* If work was actually accomplished... */ + if( rc==SQLITE_OK ){ + if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){ + i64 szDb = pWal->hdr.nPage*(i64)szPage; + testcase( IS_BIG_INT(szDb) ); + rc = sqlite3OsTruncate(pWal->pDbFd, szDb); + if( rc==SQLITE_OK && sync_flags ){ + rc = sqlite3OsSync(pWal->pDbFd, sync_flags); + } + } + if( rc==SQLITE_OK ){ + pInfo->nBackfill = mxSafeFrame; + } + } + + /* Release the reader lock held while backfilling */ + walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1); + } + + if( rc==SQLITE_BUSY ){ + /* Reset the return code so as not to report a checkpoint failure + ** just because there are active readers. */ + rc = SQLITE_OK; + } + + /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal + ** file has been copied into the database file, then block until all + ** readers have finished using the wal file. This ensures that the next + ** process to write to the database restarts the wal file. + */ + if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){ + assert( pWal->writeLock ); + if( pInfo->nBackfillhdr.mxFrame ){ + rc = SQLITE_BUSY; + }else if( eMode==SQLITE_CHECKPOINT_RESTART ){ + assert( mxSafeFrame==pWal->hdr.mxFrame ); + rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1); + if( rc==SQLITE_OK ){ + walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); + } + } + } + + walcheckpoint_out: + walIteratorFree(pIter); + return rc; +} + +/* +** If the WAL file is currently larger than nMax bytes in size, truncate +** it to exactly nMax bytes. If an error occurs while doing so, ignore it. +*/ +static void walLimitSize(Wal *pWal, i64 nMax){ + i64 sz; + int rx; + sqlite3BeginBenignMalloc(); + rx = sqlite3OsFileSize(pWal->pWalFd, &sz); + if( rx==SQLITE_OK && (sz > nMax ) ){ + rx = sqlite3OsTruncate(pWal->pWalFd, nMax); + } + sqlite3EndBenignMalloc(); + if( rx ){ + sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName); + } +} + +/* +** Close a connection to a log file. +*/ +int sqlite3WalClose( + Wal *pWal, /* Wal to close */ + int sync_flags, /* Flags to pass to OsSync() (or 0) */ + int nBuf, + u8 *zBuf /* Buffer of at least nBuf bytes */ +){ + int rc = SQLITE_OK; + if( pWal ){ + int isDelete = 0; /* True to unlink wal and wal-index files */ + + /* If an EXCLUSIVE lock can be obtained on the database file (using the + ** ordinary, rollback-mode locking methods, this guarantees that the + ** connection associated with this log file is the only connection to + ** the database. In this case checkpoint the database and unlink both + ** the wal and wal-index files. + ** + ** The EXCLUSIVE lock is not released before returning. + */ + rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE); + if( rc==SQLITE_OK ){ + if( pWal->exclusiveMode==WAL_NORMAL_MODE ){ + pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; + } + rc = sqlite3WalCheckpoint( + pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0 + ); + if( rc==SQLITE_OK ){ + int bPersist = -1; + sqlite3OsFileControlHint( + pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist + ); + if( bPersist!=1 ){ + /* Try to delete the WAL file if the checkpoint completed and + ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal + ** mode (!bPersist) */ + isDelete = 1; + }else if( pWal->mxWalSize>=0 ){ + /* Try to truncate the WAL file to zero bytes if the checkpoint + ** completed and fsynced (rc==SQLITE_OK) and we are in persistent + ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a + ** non-negative value (pWal->mxWalSize>=0). Note that we truncate + ** to zero bytes as truncating to the journal_size_limit might + ** leave a corrupt WAL file on disk. */ + walLimitSize(pWal, 0); + } + } + } + + walIndexClose(pWal, isDelete); + sqlite3OsClose(pWal->pWalFd); + if( isDelete ){ + sqlite3BeginBenignMalloc(); + sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0); + sqlite3EndBenignMalloc(); + } + WALTRACE(("WAL%p: closed\n", pWal)); + sqlite3_free((void *)pWal->apWiData); + sqlite3_free(pWal); + } + return rc; +} + +/* +** Try to read the wal-index header. Return 0 on success and 1 if +** there is a problem. +** +** The wal-index is in shared memory. Another thread or process might +** be writing the header at the same time this procedure is trying to +** read it, which might result in inconsistency. A dirty read is detected +** by verifying that both copies of the header are the same and also by +** a checksum on the header. +** +** If and only if the read is consistent and the header is different from +** pWal->hdr, then pWal->hdr is updated to the content of the new header +** and *pChanged is set to 1. +** +** If the checksum cannot be verified return non-zero. If the header +** is read successfully and the checksum verified, return zero. +*/ +static int walIndexTryHdr(Wal *pWal, int *pChanged){ + u32 aCksum[2]; /* Checksum on the header content */ + WalIndexHdr h1, h2; /* Two copies of the header content */ + WalIndexHdr volatile *aHdr; /* Header in shared memory */ + + /* The first page of the wal-index must be mapped at this point. */ + assert( pWal->nWiData>0 && pWal->apWiData[0] ); + + /* Read the header. This might happen concurrently with a write to the + ** same area of shared memory on a different CPU in a SMP, + ** meaning it is possible that an inconsistent snapshot is read + ** from the file. If this happens, return non-zero. + ** + ** There are two copies of the header at the beginning of the wal-index. + ** When reading, read [0] first then [1]. Writes are in the reverse order. + ** Memory barriers are used to prevent the compiler or the hardware from + ** reordering the reads and writes. + */ + aHdr = walIndexHdr(pWal); + memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); + walShmBarrier(pWal); + memcpy(&h2, (void *)&aHdr[1], sizeof(h2)); + + if( memcmp(&h1, &h2, sizeof(h1))!=0 ){ + return 1; /* Dirty read */ + } + if( h1.isInit==0 ){ + return 1; /* Malformed header - probably all zeros */ + } + walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum); + if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){ + return 1; /* Checksum does not match */ + } + + if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){ + *pChanged = 1; + memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr)); + pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); + testcase( pWal->szPage<=32768 ); + testcase( pWal->szPage>=65536 ); + } + + /* The header was successfully read. Return zero. */ + return 0; +} + +/* +** Read the wal-index header from the wal-index and into pWal->hdr. +** If the wal-header appears to be corrupt, try to reconstruct the +** wal-index from the WAL before returning. +** +** Set *pChanged to 1 if the wal-index header value in pWal->hdr is +** changed by this opertion. If pWal->hdr is unchanged, set *pChanged +** to 0. +** +** If the wal-index header is successfully read, return SQLITE_OK. +** Otherwise an SQLite error code. +*/ +static int walIndexReadHdr(Wal *pWal, int *pChanged){ + int rc; /* Return code */ + int badHdr; /* True if a header read failed */ + volatile u32 *page0; /* Chunk of wal-index containing header */ + + /* Ensure that page 0 of the wal-index (the page that contains the + ** wal-index header) is mapped. Return early if an error occurs here. + */ + assert( pChanged ); + rc = walIndexPage(pWal, 0, &page0); + if( rc!=SQLITE_OK ){ + return rc; + }; + assert( page0 || pWal->writeLock==0 ); + + /* If the first page of the wal-index has been mapped, try to read the + ** wal-index header immediately, without holding any lock. This usually + ** works, but may fail if the wal-index header is corrupt or currently + ** being modified by another thread or process. + */ + badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1); + + /* If the first attempt failed, it might have been due to a race + ** with a writer. So get a WRITE lock and try again. + */ + assert( badHdr==0 || pWal->writeLock==0 ); + if( badHdr ){ + if( pWal->readOnly & WAL_SHM_RDONLY ){ + if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){ + walUnlockShared(pWal, WAL_WRITE_LOCK); + rc = SQLITE_READONLY_RECOVERY; + } + }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){ + pWal->writeLock = 1; + if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){ + badHdr = walIndexTryHdr(pWal, pChanged); + if( badHdr ){ + /* If the wal-index header is still malformed even while holding + ** a WRITE lock, it can only mean that the header is corrupted and + ** needs to be reconstructed. So run recovery to do exactly that. + */ + rc = walIndexRecover(pWal); + *pChanged = 1; + } + } + pWal->writeLock = 0; + walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); + } + } + + /* If the header is read successfully, check the version number to make + ** sure the wal-index was not constructed with some future format that + ** this version of SQLite cannot understand. + */ + if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){ + rc = SQLITE_CANTOPEN_BKPT; + } + + return rc; +} + +/* +** This is the value that walTryBeginRead returns when it needs to +** be retried. +*/ +#define WAL_RETRY (-1) + +/* +** Attempt to start a read transaction. This might fail due to a race or +** other transient condition. When that happens, it returns WAL_RETRY to +** indicate to the caller that it is safe to retry immediately. +** +** On success return SQLITE_OK. On a permanent failure (such an +** I/O error or an SQLITE_BUSY because another process is running +** recovery) return a positive error code. +** +** The useWal parameter is true to force the use of the WAL and disable +** the case where the WAL is bypassed because it has been completely +** checkpointed. If useWal==0 then this routine calls walIndexReadHdr() +** to make a copy of the wal-index header into pWal->hdr. If the +** wal-index header has changed, *pChanged is set to 1 (as an indication +** to the caller that the local paget cache is obsolete and needs to be +** flushed.) When useWal==1, the wal-index header is assumed to already +** be loaded and the pChanged parameter is unused. +** +** The caller must set the cnt parameter to the number of prior calls to +** this routine during the current read attempt that returned WAL_RETRY. +** This routine will start taking more aggressive measures to clear the +** race conditions after multiple WAL_RETRY returns, and after an excessive +** number of errors will ultimately return SQLITE_PROTOCOL. The +** SQLITE_PROTOCOL return indicates that some other process has gone rogue +** and is not honoring the locking protocol. There is a vanishingly small +** chance that SQLITE_PROTOCOL could be returned because of a run of really +** bad luck when there is lots of contention for the wal-index, but that +** possibility is so small that it can be safely neglected, we believe. +** +** On success, this routine obtains a read lock on +** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is +** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1) +** that means the Wal does not hold any read lock. The reader must not +** access any database page that is modified by a WAL frame up to and +** including frame number aReadMark[pWal->readLock]. The reader will +** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0 +** Or if pWal->readLock==0, then the reader will ignore the WAL +** completely and get all content directly from the database file. +** If the useWal parameter is 1 then the WAL will never be ignored and +** this routine will always set pWal->readLock>0 on success. +** When the read transaction is completed, the caller must release the +** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1. +** +** This routine uses the nBackfill and aReadMark[] fields of the header +** to select a particular WAL_READ_LOCK() that strives to let the +** checkpoint process do as much work as possible. This routine might +** update values of the aReadMark[] array in the header, but if it does +** so it takes care to hold an exclusive lock on the corresponding +** WAL_READ_LOCK() while changing values. +*/ +static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ + volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */ + u32 mxReadMark; /* Largest aReadMark[] value */ + int mxI; /* Index of largest aReadMark[] value */ + int i; /* Loop counter */ + int rc = SQLITE_OK; /* Return code */ + + assert( pWal->readLock<0 ); /* Not currently locked */ + + /* Take steps to avoid spinning forever if there is a protocol error. + ** + ** Circumstances that cause a RETRY should only last for the briefest + ** instances of time. No I/O or other system calls are done while the + ** locks are held, so the locks should not be held for very long. But + ** if we are unlucky, another process that is holding a lock might get + ** paged out or take a page-fault that is time-consuming to resolve, + ** during the few nanoseconds that it is holding the lock. In that case, + ** it might take longer than normal for the lock to free. + ** + ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few + ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this + ** is more of a scheduler yield than an actual delay. But on the 10th + ** an subsequent retries, the delays start becoming longer and longer, + ** so that on the 100th (and last) RETRY we delay for 21 milliseconds. + ** The total delay time before giving up is less than 1 second. + */ + if( cnt>5 ){ + int nDelay = 1; /* Pause time in microseconds */ + if( cnt>100 ){ + VVA_ONLY( pWal->lockError = 1; ) + return SQLITE_PROTOCOL; + } + if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */ + sqlite3OsSleep(pWal->pVfs, nDelay); + } + + if( !useWal ){ + rc = walIndexReadHdr(pWal, pChanged); + if( rc==SQLITE_BUSY ){ + /* If there is not a recovery running in another thread or process + ** then convert BUSY errors to WAL_RETRY. If recovery is known to + ** be running, convert BUSY to BUSY_RECOVERY. There is a race here + ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY + ** would be technically correct. But the race is benign since with + ** WAL_RETRY this routine will be called again and will probably be + ** right on the second iteration. + */ + if( pWal->apWiData[0]==0 ){ + /* This branch is taken when the xShmMap() method returns SQLITE_BUSY. + ** We assume this is a transient condition, so return WAL_RETRY. The + ** xShmMap() implementation used by the default unix and win32 VFS + ** modules may return SQLITE_BUSY due to a race condition in the + ** code that determines whether or not the shared-memory region + ** must be zeroed before the requested page is returned. + */ + rc = WAL_RETRY; + }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){ + walUnlockShared(pWal, WAL_RECOVER_LOCK); + rc = WAL_RETRY; + }else if( rc==SQLITE_BUSY ){ + rc = SQLITE_BUSY_RECOVERY; + } + } + if( rc!=SQLITE_OK ){ + return rc; + } + } + + pInfo = walCkptInfo(pWal); + if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){ + /* The WAL has been completely backfilled (or it is empty). + ** and can be safely ignored. + */ + rc = walLockShared(pWal, WAL_READ_LOCK(0)); + walShmBarrier(pWal); + if( rc==SQLITE_OK ){ + if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){ + /* It is not safe to allow the reader to continue here if frames + ** may have been appended to the log before READ_LOCK(0) was obtained. + ** When holding READ_LOCK(0), the reader ignores the entire log file, + ** which implies that the database file contains a trustworthy + ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from + ** happening, this is usually correct. + ** + ** However, if frames have been appended to the log (or if the log + ** is wrapped and written for that matter) before the READ_LOCK(0) + ** is obtained, that is not necessarily true. A checkpointer may + ** have started to backfill the appended frames but crashed before + ** it finished. Leaving a corrupt image in the database file. + */ + walUnlockShared(pWal, WAL_READ_LOCK(0)); + return WAL_RETRY; + } + pWal->readLock = 0; + return SQLITE_OK; + }else if( rc!=SQLITE_BUSY ){ + return rc; + } + } + + /* If we get this far, it means that the reader will want to use + ** the WAL to get at content from recent commits. The job now is + ** to select one of the aReadMark[] entries that is closest to + ** but not exceeding pWal->hdr.mxFrame and lock that entry. + */ + mxReadMark = 0; + mxI = 0; + for(i=1; iaReadMark[i]; + if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){ + assert( thisMark!=READMARK_NOT_USED ); + mxReadMark = thisMark; + mxI = i; + } + } + /* There was once an "if" here. The extra "{" is to preserve indentation. */ + { + if( (pWal->readOnly & WAL_SHM_RDONLY)==0 + && (mxReadMarkhdr.mxFrame || mxI==0) + ){ + for(i=1; iaReadMark[i] = pWal->hdr.mxFrame; + mxI = i; + walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); + break; + }else if( rc!=SQLITE_BUSY ){ + return rc; + } + } + } + if( mxI==0 ){ + assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 ); + return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK; + } + + rc = walLockShared(pWal, WAL_READ_LOCK(mxI)); + if( rc ){ + return rc==SQLITE_BUSY ? WAL_RETRY : rc; + } + /* Now that the read-lock has been obtained, check that neither the + ** value in the aReadMark[] array or the contents of the wal-index + ** header have changed. + ** + ** It is necessary to check that the wal-index header did not change + ** between the time it was read and when the shared-lock was obtained + ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility + ** that the log file may have been wrapped by a writer, or that frames + ** that occur later in the log than pWal->hdr.mxFrame may have been + ** copied into the database by a checkpointer. If either of these things + ** happened, then reading the database with the current value of + ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry + ** instead. + ** + ** This does not guarantee that the copy of the wal-index header is up to + ** date before proceeding. That would not be possible without somehow + ** blocking writers. It only guarantees that a dangerous checkpoint or + ** log-wrap (either of which would require an exclusive lock on + ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid. + */ + walShmBarrier(pWal); + if( pInfo->aReadMark[mxI]!=mxReadMark + || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) + ){ + walUnlockShared(pWal, WAL_READ_LOCK(mxI)); + return WAL_RETRY; + }else{ + assert( mxReadMark<=pWal->hdr.mxFrame ); + pWal->readLock = (i16)mxI; + } + } + return rc; +} + +/* +** Begin a read transaction on the database. +** +** This routine used to be called sqlite3OpenSnapshot() and with good reason: +** it takes a snapshot of the state of the WAL and wal-index for the current +** instant in time. The current thread will continue to use this snapshot. +** Other threads might append new content to the WAL and wal-index but +** that extra content is ignored by the current thread. +** +** If the database contents have changes since the previous read +** transaction, then *pChanged is set to 1 before returning. The +** Pager layer will use this to know that is cache is stale and +** needs to be flushed. +*/ +int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ + int rc; /* Return code */ + int cnt = 0; /* Number of TryBeginRead attempts */ + + do{ + rc = walTryBeginRead(pWal, pChanged, 0, ++cnt); + }while( rc==WAL_RETRY ); + testcase( (rc&0xff)==SQLITE_BUSY ); + testcase( (rc&0xff)==SQLITE_IOERR ); + testcase( rc==SQLITE_PROTOCOL ); + testcase( rc==SQLITE_OK ); + return rc; +} + +/* +** Finish with a read transaction. All this does is release the +** read-lock. +*/ +void sqlite3WalEndReadTransaction(Wal *pWal){ + sqlite3WalEndWriteTransaction(pWal); + if( pWal->readLock>=0 ){ + walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); + pWal->readLock = -1; + } +} + +/* +** Search the wal file for page pgno. If found, set *piRead to the frame that +** contains the page. Otherwise, if pgno is not in the wal file, set *piRead +** to zero. +** +** Return SQLITE_OK if successful, or an error code if an error occurs. If an +** error does occur, the final value of *piRead is undefined. +*/ +int sqlite3WalFindFrame( + Wal *pWal, /* WAL handle */ + Pgno pgno, /* Database page number to read data for */ + u32 *piRead /* OUT: Frame number (or zero) */ +){ + u32 iRead = 0; /* If !=0, WAL frame to return data from */ + u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */ + int iHash; /* Used to loop through N hash tables */ + + /* This routine is only be called from within a read transaction. */ + assert( pWal->readLock>=0 || pWal->lockError ); + + /* If the "last page" field of the wal-index header snapshot is 0, then + ** no data will be read from the wal under any circumstances. Return early + ** in this case as an optimization. Likewise, if pWal->readLock==0, + ** then the WAL is ignored by the reader so return early, as if the + ** WAL were empty. + */ + if( iLast==0 || pWal->readLock==0 ){ + *piRead = 0; + return SQLITE_OK; + } + + /* Search the hash table or tables for an entry matching page number + ** pgno. Each iteration of the following for() loop searches one + ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames). + ** + ** This code might run concurrently to the code in walIndexAppend() + ** that adds entries to the wal-index (and possibly to this hash + ** table). This means the value just read from the hash + ** slot (aHash[iKey]) may have been added before or after the + ** current read transaction was opened. Values added after the + ** read transaction was opened may have been written incorrectly - + ** i.e. these slots may contain garbage data. However, we assume + ** that any slots written before the current read transaction was + ** opened remain unmodified. + ** + ** For the reasons above, the if(...) condition featured in the inner + ** loop of the following block is more stringent that would be required + ** if we had exclusive access to the hash-table: + ** + ** (aPgno[iFrame]==pgno): + ** This condition filters out normal hash-table collisions. + ** + ** (iFrame<=iLast): + ** This condition filters out entries that were added to the hash + ** table after the current read-transaction had started. + */ + for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){ + volatile ht_slot *aHash; /* Pointer to hash table */ + volatile u32 *aPgno; /* Pointer to array of page numbers */ + u32 iZero; /* Frame number corresponding to aPgno[0] */ + int iKey; /* Hash slot index */ + int nCollide; /* Number of hash collisions remaining */ + int rc; /* Error code */ + + rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero); + if( rc!=SQLITE_OK ){ + return rc; + } + nCollide = HASHTABLE_NSLOT; + for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){ + u32 iFrame = aHash[iKey] + iZero; + if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){ + /* assert( iFrame>iRead ); -- not true if there is corruption */ + iRead = iFrame; + } + if( (nCollide--)==0 ){ + return SQLITE_CORRUPT_BKPT; + } + } + } + +#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT + /* If expensive assert() statements are available, do a linear search + ** of the wal-index file content. Make sure the results agree with the + ** result obtained using the hash indexes above. */ + { + u32 iRead2 = 0; + u32 iTest; + for(iTest=iLast; iTest>0; iTest--){ + if( walFramePgno(pWal, iTest)==pgno ){ + iRead2 = iTest; + break; + } + } + assert( iRead==iRead2 ); + } +#endif + + *piRead = iRead; + return SQLITE_OK; +} + +/* +** Read the contents of frame iRead from the wal file into buffer pOut +** (which is nOut bytes in size). Return SQLITE_OK if successful, or an +** error code otherwise. +*/ +int sqlite3WalReadFrame( + Wal *pWal, /* WAL handle */ + u32 iRead, /* Frame to read */ + int nOut, /* Size of buffer pOut in bytes */ + u8 *pOut /* Buffer to write page data to */ +){ + int sz; + i64 iOffset; + sz = pWal->hdr.szPage; + sz = (sz&0xfe00) + ((sz&0x0001)<<16); + testcase( sz<=32768 ); + testcase( sz>=65536 ); + iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE; + /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */ + return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset); +} + +/* +** Return the size of the database in pages (or zero, if unknown). +*/ +Pgno sqlite3WalDbsize(Wal *pWal){ + if( pWal && ALWAYS(pWal->readLock>=0) ){ + return pWal->hdr.nPage; + } + return 0; +} + + +/* +** This function starts a write transaction on the WAL. +** +** A read transaction must have already been started by a prior call +** to sqlite3WalBeginReadTransaction(). +** +** If another thread or process has written into the database since +** the read transaction was started, then it is not possible for this +** thread to write as doing so would cause a fork. So this routine +** returns SQLITE_BUSY in that case and no write transaction is started. +** +** There can only be a single writer active at a time. +*/ +int sqlite3WalBeginWriteTransaction(Wal *pWal){ + int rc; + + /* Cannot start a write transaction without first holding a read + ** transaction. */ + assert( pWal->readLock>=0 ); + + if( pWal->readOnly ){ + return SQLITE_READONLY; + } + + /* Only one writer allowed at a time. Get the write lock. Return + ** SQLITE_BUSY if unable. + */ + rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1); + if( rc ){ + return rc; + } + pWal->writeLock = 1; + + /* If another connection has written to the database file since the + ** time the read transaction on this connection was started, then + ** the write is disallowed. + */ + if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){ + walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); + pWal->writeLock = 0; + rc = SQLITE_BUSY_SNAPSHOT; + } + + return rc; +} + +/* +** End a write transaction. The commit has already been done. This +** routine merely releases the lock. +*/ +int sqlite3WalEndWriteTransaction(Wal *pWal){ + if( pWal->writeLock ){ + walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); + pWal->writeLock = 0; + pWal->truncateOnCommit = 0; + } + return SQLITE_OK; +} + +/* +** If any data has been written (but not committed) to the log file, this +** function moves the write-pointer back to the start of the transaction. +** +** Additionally, the callback function is invoked for each frame written +** to the WAL since the start of the transaction. If the callback returns +** other than SQLITE_OK, it is not invoked again and the error code is +** returned to the caller. +** +** Otherwise, if the callback function does not return an error, this +** function returns SQLITE_OK. +*/ +int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){ + int rc = SQLITE_OK; + if( ALWAYS(pWal->writeLock) ){ + Pgno iMax = pWal->hdr.mxFrame; + Pgno iFrame; + + /* Restore the clients cache of the wal-index header to the state it + ** was in before the client began writing to the database. + */ + memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr)); + + for(iFrame=pWal->hdr.mxFrame+1; + ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; + iFrame++ + ){ + /* This call cannot fail. Unless the page for which the page number + ** is passed as the second argument is (a) in the cache and + ** (b) has an outstanding reference, then xUndo is either a no-op + ** (if (a) is false) or simply expels the page from the cache (if (b) + ** is false). + ** + ** If the upper layer is doing a rollback, it is guaranteed that there + ** are no outstanding references to any page other than page 1. And + ** page 1 is never written to the log until the transaction is + ** committed. As a result, the call to xUndo may not fail. + */ + assert( walFramePgno(pWal, iFrame)!=1 ); + rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame)); + } + if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal); + } + assert( rc==SQLITE_OK ); + return rc; +} + +/* +** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 +** values. This function populates the array with values required to +** "rollback" the write position of the WAL handle back to the current +** point in the event of a savepoint rollback (via WalSavepointUndo()). +*/ +void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){ + assert( pWal->writeLock ); + aWalData[0] = pWal->hdr.mxFrame; + aWalData[1] = pWal->hdr.aFrameCksum[0]; + aWalData[2] = pWal->hdr.aFrameCksum[1]; + aWalData[3] = pWal->nCkpt; +} + +/* +** Move the write position of the WAL back to the point identified by +** the values in the aWalData[] array. aWalData must point to an array +** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated +** by a call to WalSavepoint(). +*/ +int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ + int rc = SQLITE_OK; + + assert( pWal->writeLock ); + assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame ); + + if( aWalData[3]!=pWal->nCkpt ){ + /* This savepoint was opened immediately after the write-transaction + ** was started. Right after that, the writer decided to wrap around + ** to the start of the log. Update the savepoint values to match. + */ + aWalData[0] = 0; + aWalData[3] = pWal->nCkpt; + } + + if( aWalData[0]hdr.mxFrame ){ + pWal->hdr.mxFrame = aWalData[0]; + pWal->hdr.aFrameCksum[0] = aWalData[1]; + pWal->hdr.aFrameCksum[1] = aWalData[2]; + walCleanupHash(pWal); + } + + return rc; +} + + +/* +** This function is called just before writing a set of frames to the log +** file (see sqlite3WalFrames()). It checks to see if, instead of appending +** to the current log file, it is possible to overwrite the start of the +** existing log file with the new frames (i.e. "reset" the log). If so, +** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left +** unchanged. +** +** SQLITE_OK is returned if no error is encountered (regardless of whether +** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned +** if an error occurs. +*/ +static int walRestartLog(Wal *pWal){ + int rc = SQLITE_OK; + int cnt; + + if( pWal->readLock==0 ){ + volatile WalCkptInfo *pInfo = walCkptInfo(pWal); + assert( pInfo->nBackfill==pWal->hdr.mxFrame ); + if( pInfo->nBackfill>0 ){ + u32 salt1; + sqlite3_randomness(4, &salt1); + rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); + if( rc==SQLITE_OK ){ + /* If all readers are using WAL_READ_LOCK(0) (in other words if no + ** readers are currently using the WAL), then the transactions + ** frames will overwrite the start of the existing log. Update the + ** wal-index header to reflect this. + ** + ** In theory it would be Ok to update the cache of the header only + ** at this point. But updating the actual wal-index header is also + ** safe and means there is no special case for sqlite3WalUndo() + ** to handle if this transaction is rolled back. + */ + int i; /* Loop counter */ + u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */ + + pWal->nCkpt++; + pWal->hdr.mxFrame = 0; + sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0])); + aSalt[1] = salt1; + walIndexWriteHdr(pWal); + pInfo->nBackfill = 0; + pInfo->aReadMark[1] = 0; + for(i=2; iaReadMark[i] = READMARK_NOT_USED; + assert( pInfo->aReadMark[0]==0 ); + walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); + }else if( rc!=SQLITE_BUSY ){ + return rc; + } + } + walUnlockShared(pWal, WAL_READ_LOCK(0)); + pWal->readLock = -1; + cnt = 0; + do{ + int notUsed; + rc = walTryBeginRead(pWal, ¬Used, 1, ++cnt); + }while( rc==WAL_RETRY ); + assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */ + testcase( (rc&0xff)==SQLITE_IOERR ); + testcase( rc==SQLITE_PROTOCOL ); + testcase( rc==SQLITE_OK ); + } + return rc; +} + +/* +** Information about the current state of the WAL file and where +** the next fsync should occur - passed from sqlite3WalFrames() into +** walWriteToLog(). +*/ +typedef struct WalWriter { + Wal *pWal; /* The complete WAL information */ + sqlite3_file *pFd; /* The WAL file to which we write */ + sqlite3_int64 iSyncPoint; /* Fsync at this offset */ + int syncFlags; /* Flags for the fsync */ + int szPage; /* Size of one page */ +} WalWriter; + +/* +** Write iAmt bytes of content into the WAL file beginning at iOffset. +** Do a sync when crossing the p->iSyncPoint boundary. +** +** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt, +** first write the part before iSyncPoint, then sync, then write the +** rest. +*/ +static int walWriteToLog( + WalWriter *p, /* WAL to write to */ + void *pContent, /* Content to be written */ + int iAmt, /* Number of bytes to write */ + sqlite3_int64 iOffset /* Start writing at this offset */ +){ + int rc; + if( iOffsetiSyncPoint && iOffset+iAmt>=p->iSyncPoint ){ + int iFirstAmt = (int)(p->iSyncPoint - iOffset); + rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset); + if( rc ) return rc; + iOffset += iFirstAmt; + iAmt -= iFirstAmt; + pContent = (void*)(iFirstAmt + (char*)pContent); + assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) ); + rc = sqlite3OsSync(p->pFd, p->syncFlags); + if( iAmt==0 || rc ) return rc; + } + rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset); + return rc; +} + +/* +** Write out a single frame of the WAL +*/ +static int walWriteOneFrame( + WalWriter *p, /* Where to write the frame */ + PgHdr *pPage, /* The page of the frame to be written */ + int nTruncate, /* The commit flag. Usually 0. >0 for commit */ + sqlite3_int64 iOffset /* Byte offset at which to write */ +){ + int rc; /* Result code from subfunctions */ + void *pData; /* Data actually written */ + u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */ +#if defined(SQLITE_HAS_CODEC) + if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM; +#else + pData = pPage->pData; +#endif + walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame); + rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset); + if( rc ) return rc; + /* Write the page data */ + rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame)); + return rc; +} + +/* +** Write a set of frames to the log. The caller must hold the write-lock +** on the log file (obtained using sqlite3WalBeginWriteTransaction()). +*/ +int sqlite3WalFrames( + Wal *pWal, /* Wal handle to write to */ + int szPage, /* Database page-size in bytes */ + PgHdr *pList, /* List of dirty pages to write */ + Pgno nTruncate, /* Database size after this commit */ + int isCommit, /* True if this is a commit */ + int sync_flags /* Flags to pass to OsSync() (or 0) */ +){ + int rc; /* Used to catch return codes */ + u32 iFrame; /* Next frame address */ + PgHdr *p; /* Iterator to run through pList with. */ + PgHdr *pLast = 0; /* Last frame in list */ + int nExtra = 0; /* Number of extra copies of last page */ + int szFrame; /* The size of a single frame */ + i64 iOffset; /* Next byte to write in WAL file */ + WalWriter w; /* The writer */ + + assert( pList ); + assert( pWal->writeLock ); + + /* If this frame set completes a transaction, then nTruncate>0. If + ** nTruncate==0 then this frame set does not complete the transaction. */ + assert( (isCommit!=0)==(nTruncate!=0) ); + +#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) + { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){} + WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n", + pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill")); + } +#endif + + /* See if it is possible to write these frames into the start of the + ** log file, instead of appending to it at pWal->hdr.mxFrame. + */ + if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){ + return rc; + } + + /* If this is the first frame written into the log, write the WAL + ** header to the start of the WAL file. See comments at the top of + ** this source file for a description of the WAL header format. + */ + iFrame = pWal->hdr.mxFrame; + if( iFrame==0 ){ + u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */ + u32 aCksum[2]; /* Checksum for wal-header */ + + sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN)); + sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION); + sqlite3Put4byte(&aWalHdr[8], szPage); + sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt); + if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt); + memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8); + walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum); + sqlite3Put4byte(&aWalHdr[24], aCksum[0]); + sqlite3Put4byte(&aWalHdr[28], aCksum[1]); + + pWal->szPage = szPage; + pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN; + pWal->hdr.aFrameCksum[0] = aCksum[0]; + pWal->hdr.aFrameCksum[1] = aCksum[1]; + pWal->truncateOnCommit = 1; + + rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0); + WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok")); + if( rc!=SQLITE_OK ){ + return rc; + } + + /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless + ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise + ** an out-of-order write following a WAL restart could result in + ** database corruption. See the ticket: + ** + ** http://localhost:591/sqlite/info/ff5be73dee + */ + if( pWal->syncHeader && sync_flags ){ + rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK); + if( rc ) return rc; + } + } + assert( (int)pWal->szPage==szPage ); + + /* Setup information needed to write frames into the WAL */ + w.pWal = pWal; + w.pFd = pWal->pWalFd; + w.iSyncPoint = 0; + w.syncFlags = sync_flags; + w.szPage = szPage; + iOffset = walFrameOffset(iFrame+1, szPage); + szFrame = szPage + WAL_FRAME_HDRSIZE; + + /* Write all frames into the log file exactly once */ + for(p=pList; p; p=p->pDirty){ + int nDbSize; /* 0 normally. Positive == commit flag */ + iFrame++; + assert( iOffset==walFrameOffset(iFrame, szPage) ); + nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0; + rc = walWriteOneFrame(&w, p, nDbSize, iOffset); + if( rc ) return rc; + pLast = p; + iOffset += szFrame; + } + + /* If this is the end of a transaction, then we might need to pad + ** the transaction and/or sync the WAL file. + ** + ** Padding and syncing only occur if this set of frames complete a + ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL + ** or synchonous==OFF, then no padding or syncing are needed. + ** + ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not + ** needed and only the sync is done. If padding is needed, then the + ** final frame is repeated (with its commit mark) until the next sector + ** boundary is crossed. Only the part of the WAL prior to the last + ** sector boundary is synced; the part of the last frame that extends + ** past the sector boundary is written after the sync. + */ + if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){ + if( pWal->padToSectorBoundary ){ + int sectorSize = sqlite3SectorSize(pWal->pWalFd); + w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize; + while( iOffsettruncateOnCommit && pWal->mxWalSize>=0 ){ + i64 sz = pWal->mxWalSize; + if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){ + sz = walFrameOffset(iFrame+nExtra+1, szPage); + } + walLimitSize(pWal, sz); + pWal->truncateOnCommit = 0; + } + + /* Append data to the wal-index. It is not necessary to lock the + ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index + ** guarantees that there are no other writers, and no data that may + ** be in use by existing readers is being overwritten. + */ + iFrame = pWal->hdr.mxFrame; + for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){ + iFrame++; + rc = walIndexAppend(pWal, iFrame, p->pgno); + } + while( rc==SQLITE_OK && nExtra>0 ){ + iFrame++; + nExtra--; + rc = walIndexAppend(pWal, iFrame, pLast->pgno); + } + + if( rc==SQLITE_OK ){ + /* Update the private copy of the header. */ + pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); + testcase( szPage<=32768 ); + testcase( szPage>=65536 ); + pWal->hdr.mxFrame = iFrame; + if( isCommit ){ + pWal->hdr.iChange++; + pWal->hdr.nPage = nTruncate; + } + /* If this is a commit, update the wal-index header too. */ + if( isCommit ){ + walIndexWriteHdr(pWal); + pWal->iCallback = iFrame; + } + } + + WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok")); + return rc; +} + +/* +** This routine is called to implement sqlite3_wal_checkpoint() and +** related interfaces. +** +** Obtain a CHECKPOINT lock and then backfill as much information as +** we can from WAL into the database. +** +** If parameter xBusy is not NULL, it is a pointer to a busy-handler +** callback. In this case this function runs a blocking checkpoint. +*/ +int sqlite3WalCheckpoint( + Wal *pWal, /* Wal connection */ + int eMode, /* PASSIVE, FULL or RESTART */ + int (*xBusy)(void*), /* Function to call when busy */ + void *pBusyArg, /* Context argument for xBusyHandler */ + int sync_flags, /* Flags to sync db file with (or 0) */ + int nBuf, /* Size of temporary buffer */ + u8 *zBuf, /* Temporary buffer to use */ + int *pnLog, /* OUT: Number of frames in WAL */ + int *pnCkpt /* OUT: Number of backfilled frames in WAL */ +){ + int rc; /* Return code */ + int isChanged = 0; /* True if a new wal-index header is loaded */ + int eMode2 = eMode; /* Mode to pass to walCheckpoint() */ + + assert( pWal->ckptLock==0 ); + assert( pWal->writeLock==0 ); + + if( pWal->readOnly ) return SQLITE_READONLY; + WALTRACE(("WAL%p: checkpoint begins\n", pWal)); + rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); + if( rc ){ + /* Usually this is SQLITE_BUSY meaning that another thread or process + ** is already running a checkpoint, or maybe a recovery. But it might + ** also be SQLITE_IOERR. */ + return rc; + } + pWal->ckptLock = 1; + + /* If this is a blocking-checkpoint, then obtain the write-lock as well + ** to prevent any writers from running while the checkpoint is underway. + ** This has to be done before the call to walIndexReadHdr() below. + ** + ** If the writer lock cannot be obtained, then a passive checkpoint is + ** run instead. Since the checkpointer is not holding the writer lock, + ** there is no point in blocking waiting for any readers. Assuming no + ** other error occurs, this function will return SQLITE_BUSY to the caller. + */ + if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){ + rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1); + if( rc==SQLITE_OK ){ + pWal->writeLock = 1; + }else if( rc==SQLITE_BUSY ){ + eMode2 = SQLITE_CHECKPOINT_PASSIVE; + rc = SQLITE_OK; + } + } + + /* Read the wal-index header. */ + if( rc==SQLITE_OK ){ + rc = walIndexReadHdr(pWal, &isChanged); + if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){ + sqlite3OsUnfetch(pWal->pDbFd, 0, 0); + } + } + + /* Copy data from the log to the database file. */ + if( rc==SQLITE_OK ){ + if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf); + } + + /* If no error occurred, set the output variables. */ + if( rc==SQLITE_OK || rc==SQLITE_BUSY ){ + if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame; + if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill); + } + } + + if( isChanged ){ + /* If a new wal-index header was loaded before the checkpoint was + ** performed, then the pager-cache associated with pWal is now + ** out of date. So zero the cached wal-index header to ensure that + ** next time the pager opens a snapshot on this database it knows that + ** the cache needs to be reset. + */ + memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); + } + + /* Release the locks. */ + sqlite3WalEndWriteTransaction(pWal); + walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); + pWal->ckptLock = 0; + WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok")); + return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc); +} + +/* Return the value to pass to a sqlite3_wal_hook callback, the +** number of frames in the WAL at the point of the last commit since +** sqlite3WalCallback() was called. If no commits have occurred since +** the last call, then return 0. +*/ +int sqlite3WalCallback(Wal *pWal){ + u32 ret = 0; + if( pWal ){ + ret = pWal->iCallback; + pWal->iCallback = 0; + } + return (int)ret; +} + +/* +** This function is called to change the WAL subsystem into or out +** of locking_mode=EXCLUSIVE. +** +** If op is zero, then attempt to change from locking_mode=EXCLUSIVE +** into locking_mode=NORMAL. This means that we must acquire a lock +** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL +** or if the acquisition of the lock fails, then return 0. If the +** transition out of exclusive-mode is successful, return 1. This +** operation must occur while the pager is still holding the exclusive +** lock on the main database file. +** +** If op is one, then change from locking_mode=NORMAL into +** locking_mode=EXCLUSIVE. This means that the pWal->readLock must +** be released. Return 1 if the transition is made and 0 if the +** WAL is already in exclusive-locking mode - meaning that this +** routine is a no-op. The pager must already hold the exclusive lock +** on the main database file before invoking this operation. +** +** If op is negative, then do a dry-run of the op==1 case but do +** not actually change anything. The pager uses this to see if it +** should acquire the database exclusive lock prior to invoking +** the op==1 case. +*/ +int sqlite3WalExclusiveMode(Wal *pWal, int op){ + int rc; + assert( pWal->writeLock==0 ); + assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 ); + + /* pWal->readLock is usually set, but might be -1 if there was a + ** prior error while attempting to acquire are read-lock. This cannot + ** happen if the connection is actually in exclusive mode (as no xShmLock + ** locks are taken in this case). Nor should the pager attempt to + ** upgrade to exclusive-mode following such an error. + */ + assert( pWal->readLock>=0 || pWal->lockError ); + assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) ); + + if( op==0 ){ + if( pWal->exclusiveMode ){ + pWal->exclusiveMode = 0; + if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){ + pWal->exclusiveMode = 1; + } + rc = pWal->exclusiveMode==0; + }else{ + /* Already in locking_mode=NORMAL */ + rc = 0; + } + }else if( op>0 ){ + assert( pWal->exclusiveMode==0 ); + assert( pWal->readLock>=0 ); + walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); + pWal->exclusiveMode = 1; + rc = 1; + }else{ + rc = pWal->exclusiveMode==0; + } + return rc; +} + +/* +** Return true if the argument is non-NULL and the WAL module is using +** heap-memory for the wal-index. Otherwise, if the argument is NULL or the +** WAL module is using shared-memory, return false. +*/ +int sqlite3WalHeapMemory(Wal *pWal){ + return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ); +} + +#ifdef SQLITE_ENABLE_ZIPVFS +/* +** If the argument is not NULL, it points to a Wal object that holds a +** read-lock. This function returns the database page-size if it is known, +** or zero if it is not (or if pWal is NULL). +*/ +int sqlite3WalFramesize(Wal *pWal){ + assert( pWal==0 || pWal->readLock>=0 ); + return (pWal ? pWal->szPage : 0); +} +#endif + +#endif /* #ifndef SQLITE_OMIT_WAL */ diff --git a/components/external/SQLite-3.8.1/src/wal.h b/components/external/SQLite-3.8.1/src/wal.h new file mode 100644 index 0000000000000000000000000000000000000000..092546354b34c0ab3d20056a7f8a8a52e4d0b5f5 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/wal.h @@ -0,0 +1,137 @@ +/* +** 2010 February 1 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface to the write-ahead logging +** system. Refer to the comments below and the header comment attached to +** the implementation of each function in log.c for further details. +*/ + +#ifndef _WAL_H_ +#define _WAL_H_ + +#include "sqliteInt.h" + +/* Additional values that can be added to the sync_flags argument of +** sqlite3WalFrames(): +*/ +#define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */ +#define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */ + +#ifdef SQLITE_OMIT_WAL +# define sqlite3WalOpen(x,y,z) 0 +# define sqlite3WalLimit(x,y) +# define sqlite3WalClose(w,x,y,z) 0 +# define sqlite3WalBeginReadTransaction(y,z) 0 +# define sqlite3WalEndReadTransaction(z) +# define sqlite3WalDbsize(y) 0 +# define sqlite3WalBeginWriteTransaction(y) 0 +# define sqlite3WalEndWriteTransaction(x) 0 +# define sqlite3WalUndo(x,y,z) 0 +# define sqlite3WalSavepoint(y,z) +# define sqlite3WalSavepointUndo(y,z) 0 +# define sqlite3WalFrames(u,v,w,x,y,z) 0 +# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0 +# define sqlite3WalCallback(z) 0 +# define sqlite3WalExclusiveMode(y,z) 0 +# define sqlite3WalHeapMemory(z) 0 +# define sqlite3WalFramesize(z) 0 +# define sqlite3WalFindFrame(x,y,z) 0 +#else + +#define WAL_SAVEPOINT_NDATA 4 + +/* Connection to a write-ahead log (WAL) file. +** There is one object of this type for each pager. +*/ +typedef struct Wal Wal; + +/* Open and close a connection to a write-ahead log. */ +int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**); +int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *); + +/* Set the limiting size of a WAL file. */ +void sqlite3WalLimit(Wal*, i64); + +/* Used by readers to open (lock) and close (unlock) a snapshot. A +** snapshot is like a read-transaction. It is the state of the database +** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and +** preserves the current state even if the other threads or processes +** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the +** transaction and releases the lock. +*/ +int sqlite3WalBeginReadTransaction(Wal *pWal, int *); +void sqlite3WalEndReadTransaction(Wal *pWal); + +/* Read a page from the write-ahead log, if it is present. */ +int sqlite3WalFindFrame(Wal *, Pgno, u32 *); +int sqlite3WalReadFrame(Wal *, u32, int, u8 *); + +/* If the WAL is not empty, return the size of the database. */ +Pgno sqlite3WalDbsize(Wal *pWal); + +/* Obtain or release the WRITER lock. */ +int sqlite3WalBeginWriteTransaction(Wal *pWal); +int sqlite3WalEndWriteTransaction(Wal *pWal); + +/* Undo any frames written (but not committed) to the log */ +int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx); + +/* Return an integer that records the current (uncommitted) write +** position in the WAL */ +void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData); + +/* Move the write position of the WAL back to iFrame. Called in +** response to a ROLLBACK TO command. */ +int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData); + +/* Write a frame or frames to the log. */ +int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int); + +/* Copy pages from the log to the database file */ +int sqlite3WalCheckpoint( + Wal *pWal, /* Write-ahead log connection */ + int eMode, /* One of PASSIVE, FULL and RESTART */ + int (*xBusy)(void*), /* Function to call when busy */ + void *pBusyArg, /* Context argument for xBusyHandler */ + int sync_flags, /* Flags to sync db file with (or 0) */ + int nBuf, /* Size of buffer nBuf */ + u8 *zBuf, /* Temporary buffer to use */ + int *pnLog, /* OUT: Number of frames in WAL */ + int *pnCkpt /* OUT: Number of backfilled frames in WAL */ +); + +/* Return the value to pass to a sqlite3_wal_hook callback, the +** number of frames in the WAL at the point of the last commit since +** sqlite3WalCallback() was called. If no commits have occurred since +** the last call, then return 0. +*/ +int sqlite3WalCallback(Wal *pWal); + +/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released) +** by the pager layer on the database file. +*/ +int sqlite3WalExclusiveMode(Wal *pWal, int op); + +/* Return true if the argument is non-NULL and the WAL module is using +** heap-memory for the wal-index. Otherwise, if the argument is NULL or the +** WAL module is using shared-memory, return false. +*/ +int sqlite3WalHeapMemory(Wal *pWal); + +#ifdef SQLITE_ENABLE_ZIPVFS +/* If the WAL file is not empty, return the number of bytes of content +** stored in each frame (i.e. the db page-size when the WAL was created). +*/ +int sqlite3WalFramesize(Wal *pWal); +#endif + +#endif /* ifndef SQLITE_OMIT_WAL */ +#endif /* _WAL_H_ */ diff --git a/components/external/SQLite-3.8.1/src/walker.c b/components/external/SQLite-3.8.1/src/walker.c new file mode 100644 index 0000000000000000000000000000000000000000..cde34ad78031a3a7a265cdc7ad73a82120d38535 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/walker.c @@ -0,0 +1,153 @@ +/* +** 2008 August 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains routines used for walking the parser tree for +** an SQL statement. +*/ +#include "sqliteInt.h" +#include +#include + + +/* +** Walk an expression tree. Invoke the callback once for each node +** of the expression, while decending. (In other words, the callback +** is invoked before visiting children.) +** +** The return value from the callback should be one of the WRC_* +** constants to specify how to proceed with the walk. +** +** WRC_Continue Continue descending down the tree. +** +** WRC_Prune Do not descend into child nodes. But allow +** the walk to continue with sibling nodes. +** +** WRC_Abort Do no more callbacks. Unwind the stack and +** return the top-level walk call. +** +** The return value from this routine is WRC_Abort to abandon the tree walk +** and WRC_Continue to continue. +*/ +int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){ + int rc; + if( pExpr==0 ) return WRC_Continue; + testcase( ExprHasProperty(pExpr, EP_TokenOnly) ); + testcase( ExprHasProperty(pExpr, EP_Reduced) ); + rc = pWalker->xExprCallback(pWalker, pExpr); + if( rc==WRC_Continue + && !ExprHasProperty(pExpr,EP_TokenOnly) ){ + if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort; + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort; + }else{ + if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort; + } + } + return rc & WRC_Abort; +} + +/* +** Call sqlite3WalkExpr() for every expression in list p or until +** an abort request is seen. +*/ +int sqlite3WalkExprList(Walker *pWalker, ExprList *p){ + int i; + struct ExprList_item *pItem; + if( p ){ + for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){ + if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort; + } + } + return WRC_Continue; +} + +/* +** Walk all expressions associated with SELECT statement p. Do +** not invoke the SELECT callback on p, but do (of course) invoke +** any expr callbacks and SELECT callbacks that come from subqueries. +** Return WRC_Abort or WRC_Continue. +*/ +int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){ + if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort; + if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort; + if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort; + if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort; + return WRC_Continue; +} + +/* +** Walk the parse trees associated with all subqueries in the +** FROM clause of SELECT statement p. Do not invoke the select +** callback on p, but do invoke it on each FROM clause subquery +** and on any subqueries further down in the tree. Return +** WRC_Abort or WRC_Continue; +*/ +int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){ + SrcList *pSrc; + int i; + struct SrcList_item *pItem; + + pSrc = p->pSrc; + if( ALWAYS(pSrc) ){ + for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ + if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){ + return WRC_Abort; + } + } + } + return WRC_Continue; +} + +/* +** Call sqlite3WalkExpr() for every expression in Select statement p. +** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and +** on the compound select chain, p->pPrior. Invoke the xSelectCallback() +** either before or after the walk of expressions and FROM clause, depending +** on whether pWalker->bSelectDepthFirst is false or true, respectively. +** +** Return WRC_Continue under normal conditions. Return WRC_Abort if +** there is an abort request. +** +** If the Walker does not have an xSelectCallback() then this routine +** is a no-op returning WRC_Continue. +*/ +int sqlite3WalkSelect(Walker *pWalker, Select *p){ + int rc; + if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue; + rc = WRC_Continue; + pWalker->walkerDepth++; + while( p ){ + if( !pWalker->bSelectDepthFirst ){ + rc = pWalker->xSelectCallback(pWalker, p); + if( rc ) break; + } + if( sqlite3WalkSelectExpr(pWalker, p) + || sqlite3WalkSelectFrom(pWalker, p) + ){ + pWalker->walkerDepth--; + return WRC_Abort; + } + if( pWalker->bSelectDepthFirst ){ + rc = pWalker->xSelectCallback(pWalker, p); + /* Depth-first search is currently only used for + ** selectAddSubqueryTypeInfo() and that routine always returns + ** WRC_Continue (0). So the following branch is never taken. */ + if( NEVER(rc) ) break; + } + p = p->pPrior; + } + pWalker->walkerDepth--; + return rc & WRC_Abort; +} diff --git a/components/external/SQLite-3.8.1/src/where.c b/components/external/SQLite-3.8.1/src/where.c new file mode 100644 index 0000000000000000000000000000000000000000..d89ce65137ad29a449f34d1dc9d7a210d7a765b2 --- /dev/null +++ b/components/external/SQLite-3.8.1/src/where.c @@ -0,0 +1,6144 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This module contains C code that generates VDBE code used to process +** the WHERE clause of SQL statements. This module is responsible for +** generating the code that loops through a table looking for applicable +** rows. Indices are selected and used to speed the search when doing +** so is applicable. Because this module is responsible for selecting +** indices, you might also think of this module as the "query optimizer". +*/ +#include "sqliteInt.h" + + +/* +** Trace output macros +*/ +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) +/***/ int sqlite3WhereTrace = 0; +#endif +#if defined(SQLITE_DEBUG) \ + && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE)) +# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X +# define WHERETRACE_ENABLED 1 +#else +# define WHERETRACE(K,X) +#endif + +/* Forward references +*/ +typedef struct WhereClause WhereClause; +typedef struct WhereMaskSet WhereMaskSet; +typedef struct WhereOrInfo WhereOrInfo; +typedef struct WhereAndInfo WhereAndInfo; +typedef struct WhereLevel WhereLevel; +typedef struct WhereLoop WhereLoop; +typedef struct WherePath WherePath; +typedef struct WhereTerm WhereTerm; +typedef struct WhereLoopBuilder WhereLoopBuilder; +typedef struct WhereScan WhereScan; +typedef struct WhereOrCost WhereOrCost; +typedef struct WhereOrSet WhereOrSet; + +/* +** This object contains information needed to implement a single nested +** loop in WHERE clause. +** +** Contrast this object with WhereLoop. This object describes the +** implementation of the loop. WhereLoop describes the algorithm. +** This object contains a pointer to the WhereLoop algorithm as one of +** its elements. +** +** The WhereInfo object contains a single instance of this object for +** each term in the FROM clause (which is to say, for each of the +** nested loops as implemented). The order of WhereLevel objects determines +** the loop nested order, with WhereInfo.a[0] being the outer loop and +** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop. +*/ +struct WhereLevel { + int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */ + int iTabCur; /* The VDBE cursor used to access the table */ + int iIdxCur; /* The VDBE cursor used to access pIdx */ + int addrBrk; /* Jump here to break out of the loop */ + int addrNxt; /* Jump here to start the next IN combination */ + int addrCont; /* Jump here to continue with the next loop cycle */ + int addrFirst; /* First instruction of interior of the loop */ + int addrBody; /* Beginning of the body of this loop */ + u8 iFrom; /* Which entry in the FROM clause */ + u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */ + int p1, p2; /* Operands of the opcode used to ends the loop */ + union { /* Information that depends on pWLoop->wsFlags */ + struct { + int nIn; /* Number of entries in aInLoop[] */ + struct InLoop { + int iCur; /* The VDBE cursor used by this IN operator */ + int addrInTop; /* Top of the IN loop */ + u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */ + } *aInLoop; /* Information about each nested IN operator */ + } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */ + Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */ + } u; + struct WhereLoop *pWLoop; /* The selected WhereLoop object */ + Bitmask notReady; /* FROM entries not usable at this level */ +}; + +/* +** Each instance of this object represents an algorithm for evaluating one +** term of a join. Every term of the FROM clause will have at least +** one corresponding WhereLoop object (unless INDEXED BY constraints +** prevent a query solution - which is an error) and many terms of the +** FROM clause will have multiple WhereLoop objects, each describing a +** potential way of implementing that FROM-clause term, together with +** dependencies and cost estimates for using the chosen algorithm. +** +** Query planning consists of building up a collection of these WhereLoop +** objects, then computing a particular sequence of WhereLoop objects, with +** one WhereLoop object per FROM clause term, that satisfy all dependencies +** and that minimize the overall cost. +*/ +struct WhereLoop { + Bitmask prereq; /* Bitmask of other loops that must run first */ + Bitmask maskSelf; /* Bitmask identifying table iTab */ +#ifdef SQLITE_DEBUG + char cId; /* Symbolic ID of this loop for debugging use */ +#endif + u8 iTab; /* Position in FROM clause of table for this loop */ + u8 iSortIdx; /* Sorting index number. 0==None */ + LogEst rSetup; /* One-time setup cost (ex: create transient index) */ + LogEst rRun; /* Cost of running each loop */ + LogEst nOut; /* Estimated number of output rows */ + union { + struct { /* Information for internal btree tables */ + int nEq; /* Number of equality constraints */ + Index *pIndex; /* Index used, or NULL */ + } btree; + struct { /* Information for virtual tables */ + int idxNum; /* Index number */ + u8 needFree; /* True if sqlite3_free(idxStr) is needed */ + u8 isOrdered; /* True if satisfies ORDER BY */ + u16 omitMask; /* Terms that may be omitted */ + char *idxStr; /* Index identifier string */ + } vtab; + } u; + u32 wsFlags; /* WHERE_* flags describing the plan */ + u16 nLTerm; /* Number of entries in aLTerm[] */ + /**** whereLoopXfer() copies fields above ***********************/ +# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot) + u16 nLSlot; /* Number of slots allocated for aLTerm[] */ + WhereTerm **aLTerm; /* WhereTerms used */ + WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */ + WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */ +}; + +/* This object holds the prerequisites and the cost of running a +** subquery on one operand of an OR operator in the WHERE clause. +** See WhereOrSet for additional information +*/ +struct WhereOrCost { + Bitmask prereq; /* Prerequisites */ + LogEst rRun; /* Cost of running this subquery */ + LogEst nOut; /* Number of outputs for this subquery */ +}; + +/* The WhereOrSet object holds a set of possible WhereOrCosts that +** correspond to the subquery(s) of OR-clause processing. Only the +** best N_OR_COST elements are retained. +*/ +#define N_OR_COST 3 +struct WhereOrSet { + u16 n; /* Number of valid a[] entries */ + WhereOrCost a[N_OR_COST]; /* Set of best costs */ +}; + + +/* Forward declaration of methods */ +static int whereLoopResize(sqlite3*, WhereLoop*, int); + +/* +** Each instance of this object holds a sequence of WhereLoop objects +** that implement some or all of a query plan. +** +** Think of each WhereLoop object as a node in a graph with arcs +** showing dependencies and costs for travelling between nodes. (That is +** not a completely accurate description because WhereLoop costs are a +** vector, not a scalar, and because dependencies are many-to-one, not +** one-to-one as are graph nodes. But it is a useful visualization aid.) +** Then a WherePath object is a path through the graph that visits some +** or all of the WhereLoop objects once. +** +** The "solver" works by creating the N best WherePath objects of length +** 1. Then using those as a basis to compute the N best WherePath objects +** of length 2. And so forth until the length of WherePaths equals the +** number of nodes in the FROM clause. The best (lowest cost) WherePath +** at the end is the choosen query plan. +*/ +struct WherePath { + Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */ + Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */ + LogEst nRow; /* Estimated number of rows generated by this path */ + LogEst rCost; /* Total cost of this path */ + u8 isOrdered; /* True if this path satisfies ORDER BY */ + u8 isOrderedValid; /* True if the isOrdered field is valid */ + WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */ +}; + +/* +** The query generator uses an array of instances of this structure to +** help it analyze the subexpressions of the WHERE clause. Each WHERE +** clause subexpression is separated from the others by AND operators, +** usually, or sometimes subexpressions separated by OR. +** +** All WhereTerms are collected into a single WhereClause structure. +** The following identity holds: +** +** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm +** +** When a term is of the form: +** +** X +** +** where X is a column name and is one of certain operators, +** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the +** cursor number and column number for X. WhereTerm.eOperator records +** the using a bitmask encoding defined by WO_xxx below. The +** use of a bitmask encoding for the operator allows us to search +** quickly for terms that match any of several different operators. +** +** A WhereTerm might also be two or more subterms connected by OR: +** +** (t1.X ) OR (t1.Y ) OR .... +** +** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR +** and the WhereTerm.u.pOrInfo field points to auxiliary information that +** is collected about the OR clause. +** +** If a term in the WHERE clause does not match either of the two previous +** categories, then eOperator==0. The WhereTerm.pExpr field is still set +** to the original subexpression content and wtFlags is set up appropriately +** but no other fields in the WhereTerm object are meaningful. +** +** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers, +** but they do so indirectly. A single WhereMaskSet structure translates +** cursor number into bits and the translated bit is stored in the prereq +** fields. The translation is used in order to maximize the number of +** bits that will fit in a Bitmask. The VDBE cursor numbers might be +** spread out over the non-negative integers. For example, the cursor +** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet +** translates these sparse cursor numbers into consecutive integers +** beginning with 0 in order to make the best possible use of the available +** bits in the Bitmask. So, in the example above, the cursor numbers +** would be mapped into integers 0 through 7. +** +** The number of terms in a join is limited by the number of bits +** in prereqRight and prereqAll. The default is 64 bits, hence SQLite +** is only able to process joins with 64 or fewer tables. +*/ +struct WhereTerm { + Expr *pExpr; /* Pointer to the subexpression that is this term */ + int iParent; /* Disable pWC->a[iParent] when this term disabled */ + int leftCursor; /* Cursor number of X in "X " */ + union { + int leftColumn; /* Column number of X in "X " */ + WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */ + WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */ + } u; + LogEst truthProb; /* Probability of truth for this expression */ + u16 eOperator; /* A WO_xx value describing */ + u8 wtFlags; /* TERM_xxx bit flags. See below */ + u8 nChild; /* Number of children that must disable us */ + WhereClause *pWC; /* The clause this term is part of */ + Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */ + Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */ +}; + +/* +** Allowed values of WhereTerm.wtFlags +*/ +#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */ +#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */ +#define TERM_CODED 0x04 /* This term is already coded */ +#define TERM_COPIED 0x08 /* Has a child */ +#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */ +#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */ +#define TERM_OR_OK 0x40 /* Used during OR-clause processing */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */ +#else +# define TERM_VNULL 0x00 /* Disabled if not using stat3 */ +#endif + +/* +** An instance of the WhereScan object is used as an iterator for locating +** terms in the WHERE clause that are useful to the query planner. +*/ +struct WhereScan { + WhereClause *pOrigWC; /* Original, innermost WhereClause */ + WhereClause *pWC; /* WhereClause currently being scanned */ + char *zCollName; /* Required collating sequence, if not NULL */ + char idxaff; /* Must match this affinity, if zCollName!=NULL */ + unsigned char nEquiv; /* Number of entries in aEquiv[] */ + unsigned char iEquiv; /* Next unused slot in aEquiv[] */ + u32 opMask; /* Acceptable operators */ + int k; /* Resume scanning at this->pWC->a[this->k] */ + int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */ +}; + +/* +** An instance of the following structure holds all information about a +** WHERE clause. Mostly this is a container for one or more WhereTerms. +** +** Explanation of pOuter: For a WHERE clause of the form +** +** a AND ((b AND c) OR (d AND e)) AND f +** +** There are separate WhereClause objects for the whole clause and for +** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the +** subclauses points to the WhereClause object for the whole clause. +*/ +struct WhereClause { + WhereInfo *pWInfo; /* WHERE clause processing context */ + WhereClause *pOuter; /* Outer conjunction */ + u8 op; /* Split operator. TK_AND or TK_OR */ + int nTerm; /* Number of terms */ + int nSlot; /* Number of entries in a[] */ + WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */ +#if defined(SQLITE_SMALL_STACK) + WhereTerm aStatic[1]; /* Initial static space for a[] */ +#else + WhereTerm aStatic[8]; /* Initial static space for a[] */ +#endif +}; + +/* +** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to +** a dynamically allocated instance of the following structure. +*/ +struct WhereOrInfo { + WhereClause wc; /* Decomposition into subterms */ + Bitmask indexable; /* Bitmask of all indexable tables in the clause */ +}; + +/* +** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to +** a dynamically allocated instance of the following structure. +*/ +struct WhereAndInfo { + WhereClause wc; /* The subexpression broken out */ +}; + +/* +** An instance of the following structure keeps track of a mapping +** between VDBE cursor numbers and bits of the bitmasks in WhereTerm. +** +** The VDBE cursor numbers are small integers contained in +** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE +** clause, the cursor numbers might not begin with 0 and they might +** contain gaps in the numbering sequence. But we want to make maximum +** use of the bits in our bitmasks. This structure provides a mapping +** from the sparse cursor numbers into consecutive integers beginning +** with 0. +** +** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask +** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<3, 5->1, 8->2, 29->0, +** 57->5, 73->4. Or one of 719 other combinations might be used. It +** does not really matter. What is important is that sparse cursor +** numbers all get mapped into bit numbers that begin with 0 and contain +** no gaps. +*/ +struct WhereMaskSet { + int n; /* Number of assigned cursor values */ + int ix[BMS]; /* Cursor assigned to each bit */ +}; + +/* +** This object is a convenience wrapper holding all information needed +** to construct WhereLoop objects for a particular query. +*/ +struct WhereLoopBuilder { + WhereInfo *pWInfo; /* Information about this WHERE */ + WhereClause *pWC; /* WHERE clause terms */ + ExprList *pOrderBy; /* ORDER BY clause */ + WhereLoop *pNew; /* Template WhereLoop */ + WhereOrSet *pOrSet; /* Record best loops here, if not NULL */ +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + UnpackedRecord *pRec; /* Probe for stat4 (if required) */ + int nRecValid; /* Number of valid fields currently in pRec */ +#endif +}; + +/* +** The WHERE clause processing routine has two halves. The +** first part does the start of the WHERE loop and the second +** half does the tail of the WHERE loop. An instance of +** this structure is returned by the first half and passed +** into the second half to give some continuity. +** +** An instance of this object holds the complete state of the query +** planner. +*/ +struct WhereInfo { + Parse *pParse; /* Parsing and code generating context */ + SrcList *pTabList; /* List of tables in the join */ + ExprList *pOrderBy; /* The ORDER BY clause or NULL */ + ExprList *pResultSet; /* Result set. DISTINCT operates on these */ + WhereLoop *pLoops; /* List of all WhereLoop objects */ + Bitmask revMask; /* Mask of ORDER BY terms that need reversing */ + LogEst nRowOut; /* Estimated number of output rows */ + u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */ + u8 bOBSat; /* ORDER BY satisfied by indices */ + u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */ + u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */ + u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */ + u8 nLevel; /* Number of nested loop */ + int iTop; /* The very beginning of the WHERE loop */ + int iContinue; /* Jump here to continue with next record */ + int iBreak; /* Jump here to break out of the loop */ + int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */ + WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */ + WhereClause sWC; /* Decomposition of the WHERE clause */ + WhereLevel a[1]; /* Information about each nest loop in WHERE */ +}; + +/* +** Bitmasks for the operators on WhereTerm objects. These are all +** operators that are of interest to the query planner. An +** OR-ed combination of these values can be used when searching for +** particular WhereTerms within a WhereClause. +*/ +#define WO_IN 0x001 +#define WO_EQ 0x002 +#define WO_LT (WO_EQ<<(TK_LT-TK_EQ)) +#define WO_LE (WO_EQ<<(TK_LE-TK_EQ)) +#define WO_GT (WO_EQ<<(TK_GT-TK_EQ)) +#define WO_GE (WO_EQ<<(TK_GE-TK_EQ)) +#define WO_MATCH 0x040 +#define WO_ISNULL 0x080 +#define WO_OR 0x100 /* Two or more OR-connected terms */ +#define WO_AND 0x200 /* Two or more AND-connected terms */ +#define WO_EQUIV 0x400 /* Of the form A==B, both columns */ +#define WO_NOOP 0x800 /* This term does not restrict search space */ + +#define WO_ALL 0xfff /* Mask of all possible WO_* values */ +#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */ + +/* +** These are definitions of bits in the WhereLoop.wsFlags field. +** The particular combination of bits in each WhereLoop help to +** determine the algorithm that WhereLoop represents. +*/ +#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */ +#define WHERE_COLUMN_RANGE 0x00000002 /* xEXPR */ +#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */ +#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */ +#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */ +#define WHERE_TOP_LIMIT 0x00000010 /* xEXPR or x>=EXPR constraint */ +#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and xnRowOut); +} + +/* +** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this +** WHERE clause returns outputs for DISTINCT processing. +*/ +int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ + return pWInfo->eDistinct; +} + +/* +** Return TRUE if the WHERE clause returns rows in ORDER BY order. +** Return FALSE if the output needs to be sorted. +*/ +int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ + return pWInfo->bOBSat!=0; +} + +/* +** Return the VDBE address or label to jump to in order to continue +** immediately with the next row of a WHERE clause. +*/ +int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ + return pWInfo->iContinue; +} + +/* +** Return the VDBE address or label to jump to in order to break +** out of a WHERE loop. +*/ +int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ + return pWInfo->iBreak; +} + +/* +** Return TRUE if an UPDATE or DELETE statement can operate directly on +** the rowids returned by a WHERE clause. Return FALSE if doing an +** UPDATE or DELETE might change subsequent WHERE clause results. +*/ +int sqlite3WhereOkOnePass(WhereInfo *pWInfo){ + return pWInfo->okOnePass; +} + +/* +** Move the content of pSrc into pDest +*/ +static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ + pDest->n = pSrc->n; + memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); +} + +/* +** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet. +** +** The new entry might overwrite an existing entry, or it might be +** appended, or it might be discarded. Do whatever is the right thing +** so that pSet keeps the N_OR_COST best entries seen so far. +*/ +static int whereOrInsert( + WhereOrSet *pSet, /* The WhereOrSet to be updated */ + Bitmask prereq, /* Prerequisites of the new entry */ + LogEst rRun, /* Run-cost of the new entry */ + LogEst nOut /* Number of outputs for the new entry */ +){ + u16 i; + WhereOrCost *p; + for(i=pSet->n, p=pSet->a; i>0; i--, p++){ + if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){ + goto whereOrInsert_done; + } + if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){ + return 0; + } + } + if( pSet->na[pSet->n++]; + p->nOut = nOut; + }else{ + p = pSet->a; + for(i=1; in; i++){ + if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i; + } + if( p->rRun<=rRun ) return 0; + } +whereOrInsert_done: + p->prereq = prereq; + p->rRun = rRun; + if( p->nOut>nOut ) p->nOut = nOut; + return 1; +} + +/* +** Initialize a preallocated WhereClause structure. +*/ +static void whereClauseInit( + WhereClause *pWC, /* The WhereClause to be initialized */ + WhereInfo *pWInfo /* The WHERE processing context */ +){ + pWC->pWInfo = pWInfo; + pWC->pOuter = 0; + pWC->nTerm = 0; + pWC->nSlot = ArraySize(pWC->aStatic); + pWC->a = pWC->aStatic; +} + +/* Forward reference */ +static void whereClauseClear(WhereClause*); + +/* +** Deallocate all memory associated with a WhereOrInfo object. +*/ +static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ + whereClauseClear(&p->wc); + sqlite3DbFree(db, p); +} + +/* +** Deallocate all memory associated with a WhereAndInfo object. +*/ +static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ + whereClauseClear(&p->wc); + sqlite3DbFree(db, p); +} + +/* +** Deallocate a WhereClause structure. The WhereClause structure +** itself is not freed. This routine is the inverse of whereClauseInit(). +*/ +static void whereClauseClear(WhereClause *pWC){ + int i; + WhereTerm *a; + sqlite3 *db = pWC->pWInfo->pParse->db; + for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ + if( a->wtFlags & TERM_DYNAMIC ){ + sqlite3ExprDelete(db, a->pExpr); + } + if( a->wtFlags & TERM_ORINFO ){ + whereOrInfoDelete(db, a->u.pOrInfo); + }else if( a->wtFlags & TERM_ANDINFO ){ + whereAndInfoDelete(db, a->u.pAndInfo); + } + } + if( pWC->a!=pWC->aStatic ){ + sqlite3DbFree(db, pWC->a); + } +} + +/* +** Add a single new WhereTerm entry to the WhereClause object pWC. +** The new WhereTerm object is constructed from Expr p and with wtFlags. +** The index in pWC->a[] of the new WhereTerm is returned on success. +** 0 is returned if the new WhereTerm could not be added due to a memory +** allocation error. The memory allocation failure will be recorded in +** the db->mallocFailed flag so that higher-level functions can detect it. +** +** This routine will increase the size of the pWC->a[] array as necessary. +** +** If the wtFlags argument includes TERM_DYNAMIC, then responsibility +** for freeing the expression p is assumed by the WhereClause object pWC. +** This is true even if this routine fails to allocate a new WhereTerm. +** +** WARNING: This routine might reallocate the space used to store +** WhereTerms. All pointers to WhereTerms should be invalidated after +** calling this routine. Such pointers may be reinitialized by referencing +** the pWC->a[] array. +*/ +static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){ + WhereTerm *pTerm; + int idx; + testcase( wtFlags & TERM_VIRTUAL ); + if( pWC->nTerm>=pWC->nSlot ){ + WhereTerm *pOld = pWC->a; + sqlite3 *db = pWC->pWInfo->pParse->db; + pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); + if( pWC->a==0 ){ + if( wtFlags & TERM_DYNAMIC ){ + sqlite3ExprDelete(db, p); + } + pWC->a = pOld; + return 0; + } + memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); + if( pOld!=pWC->aStatic ){ + sqlite3DbFree(db, pOld); + } + pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); + } + pTerm = &pWC->a[idx = pWC->nTerm++]; + if( p && ExprHasProperty(p, EP_Unlikely) ){ + pTerm->truthProb = sqlite3LogEst(p->iTable) - 99; + }else{ + pTerm->truthProb = -1; + } + pTerm->pExpr = sqlite3ExprSkipCollate(p); + pTerm->wtFlags = wtFlags; + pTerm->pWC = pWC; + pTerm->iParent = -1; + return idx; +} + +/* +** This routine identifies subexpressions in the WHERE clause where +** each subexpression is separated by the AND operator or some other +** operator specified in the op parameter. The WhereClause structure +** is filled with pointers to subexpressions. For example: +** +** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) +** \________/ \_______________/ \________________/ +** slot[0] slot[1] slot[2] +** +** The original WHERE clause in pExpr is unaltered. All this routine +** does is make slot[] entries point to substructure within pExpr. +** +** In the previous sentence and in the diagram, "slot[]" refers to +** the WhereClause.a[] array. The slot[] array grows as needed to contain +** all terms of the WHERE clause. +*/ +static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ + pWC->op = op; + if( pExpr==0 ) return; + if( pExpr->op!=op ){ + whereClauseInsert(pWC, pExpr, 0); + }else{ + whereSplit(pWC, pExpr->pLeft, op); + whereSplit(pWC, pExpr->pRight, op); + } +} + +/* +** Initialize a WhereMaskSet object +*/ +#define initMaskSet(P) (P)->n=0 + +/* +** Return the bitmask for the given cursor number. Return 0 if +** iCursor is not in the set. +*/ +static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){ + int i; + assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); + for(i=0; in; i++){ + if( pMaskSet->ix[i]==iCursor ){ + return MASKBIT(i); + } + } + return 0; +} + +/* +** Create a new mask for cursor iCursor. +** +** There is one cursor per table in the FROM clause. The number of +** tables in the FROM clause is limited by a test early in the +** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] +** array will never overflow. +*/ +static void createMask(WhereMaskSet *pMaskSet, int iCursor){ + assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); + pMaskSet->ix[pMaskSet->n++] = iCursor; +} + +/* +** These routines walk (recursively) an expression tree and generate +** a bitmask indicating which tables are used in that expression +** tree. +*/ +static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*); +static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*); +static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){ + Bitmask mask = 0; + if( p==0 ) return 0; + if( p->op==TK_COLUMN ){ + mask = getMask(pMaskSet, p->iTable); + return mask; + } + mask = exprTableUsage(pMaskSet, p->pRight); + mask |= exprTableUsage(pMaskSet, p->pLeft); + if( ExprHasProperty(p, EP_xIsSelect) ){ + mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect); + }else{ + mask |= exprListTableUsage(pMaskSet, p->x.pList); + } + return mask; +} +static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){ + int i; + Bitmask mask = 0; + if( pList ){ + for(i=0; inExpr; i++){ + mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr); + } + } + return mask; +} +static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){ + Bitmask mask = 0; + while( pS ){ + SrcList *pSrc = pS->pSrc; + mask |= exprListTableUsage(pMaskSet, pS->pEList); + mask |= exprListTableUsage(pMaskSet, pS->pGroupBy); + mask |= exprListTableUsage(pMaskSet, pS->pOrderBy); + mask |= exprTableUsage(pMaskSet, pS->pWhere); + mask |= exprTableUsage(pMaskSet, pS->pHaving); + if( ALWAYS(pSrc!=0) ){ + int i; + for(i=0; inSrc; i++){ + mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect); + mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn); + } + } + pS = pS->pPrior; + } + return mask; +} + +/* +** Return TRUE if the given operator is one of the operators that is +** allowed for an indexable WHERE clause term. The allowed operators are +** "=", "<", ">", "<=", ">=", "IN", and "IS NULL" +*/ +static int allowedOp(int op){ + assert( TK_GT>TK_EQ && TK_GTTK_EQ && TK_LTTK_EQ && TK_LE=TK_EQ && op<=TK_GE) || op==TK_ISNULL; +} + +/* +** Swap two objects of type TYPE. +*/ +#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} + +/* +** Commute a comparison operator. Expressions of the form "X op Y" +** are converted into "Y op X". +** +** If left/right precedence rules come into play when determining the +** collating sequence, then COLLATE operators are adjusted to ensure +** that the collating sequence does not change. For example: +** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on +** the left hand side of a comparison overrides any collation sequence +** attached to the right. For the same reason the EP_Collate flag +** is not commuted. +*/ +static void exprCommute(Parse *pParse, Expr *pExpr){ + u16 expRight = (pExpr->pRight->flags & EP_Collate); + u16 expLeft = (pExpr->pLeft->flags & EP_Collate); + assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN ); + if( expRight==expLeft ){ + /* Either X and Y both have COLLATE operator or neither do */ + if( expRight ){ + /* Both X and Y have COLLATE operators. Make sure X is always + ** used by clearing the EP_Collate flag from Y. */ + pExpr->pRight->flags &= ~EP_Collate; + }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){ + /* Neither X nor Y have COLLATE operators, but X has a non-default + ** collating sequence. So add the EP_Collate marker on X to cause + ** it to be searched first. */ + pExpr->pLeft->flags |= EP_Collate; + } + } + SWAP(Expr*,pExpr->pRight,pExpr->pLeft); + if( pExpr->op>=TK_GT ){ + assert( TK_LT==TK_GT+2 ); + assert( TK_GE==TK_LE+2 ); + assert( TK_GT>TK_EQ ); + assert( TK_GTop>=TK_GT && pExpr->op<=TK_GE ); + pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; + } +} + +/* +** Translate from TK_xx operator to WO_xx bitmask. +*/ +static u16 operatorMask(int op){ + u16 c; + assert( allowedOp(op) ); + if( op==TK_IN ){ + c = WO_IN; + }else if( op==TK_ISNULL ){ + c = WO_ISNULL; + }else{ + assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff ); + c = (u16)(WO_EQ<<(op-TK_EQ)); + } + assert( op!=TK_ISNULL || c==WO_ISNULL ); + assert( op!=TK_IN || c==WO_IN ); + assert( op!=TK_EQ || c==WO_EQ ); + assert( op!=TK_LT || c==WO_LT ); + assert( op!=TK_LE || c==WO_LE ); + assert( op!=TK_GT || c==WO_GT ); + assert( op!=TK_GE || c==WO_GE ); + return c; +} + +/* +** Advance to the next WhereTerm that matches according to the criteria +** established when the pScan object was initialized by whereScanInit(). +** Return NULL if there are no more matching WhereTerms. +*/ +static WhereTerm *whereScanNext(WhereScan *pScan){ + int iCur; /* The cursor on the LHS of the term */ + int iColumn; /* The column on the LHS of the term. -1 for IPK */ + Expr *pX; /* An expression being tested */ + WhereClause *pWC; /* Shorthand for pScan->pWC */ + WhereTerm *pTerm; /* The term being tested */ + int k = pScan->k; /* Where to start scanning */ + + while( pScan->iEquiv<=pScan->nEquiv ){ + iCur = pScan->aEquiv[pScan->iEquiv-2]; + iColumn = pScan->aEquiv[pScan->iEquiv-1]; + while( (pWC = pScan->pWC)!=0 ){ + for(pTerm=pWC->a+k; knTerm; k++, pTerm++){ + if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){ + if( (pTerm->eOperator & WO_EQUIV)!=0 + && pScan->nEquivaEquiv) + ){ + int j; + pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight); + assert( pX->op==TK_COLUMN ); + for(j=0; jnEquiv; j+=2){ + if( pScan->aEquiv[j]==pX->iTable + && pScan->aEquiv[j+1]==pX->iColumn ){ + break; + } + } + if( j==pScan->nEquiv ){ + pScan->aEquiv[j] = pX->iTable; + pScan->aEquiv[j+1] = pX->iColumn; + pScan->nEquiv += 2; + } + } + if( (pTerm->eOperator & pScan->opMask)!=0 ){ + /* Verify the affinity and collating sequence match */ + if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ + CollSeq *pColl; + Parse *pParse = pWC->pWInfo->pParse; + pX = pTerm->pExpr; + if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ + continue; + } + assert(pX->pLeft); + pColl = sqlite3BinaryCompareCollSeq(pParse, + pX->pLeft, pX->pRight); + if( pColl==0 ) pColl = pParse->db->pDfltColl; + if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ + continue; + } + } + if( (pTerm->eOperator & WO_EQ)!=0 + && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN + && pX->iTable==pScan->aEquiv[0] + && pX->iColumn==pScan->aEquiv[1] + ){ + continue; + } + pScan->k = k+1; + return pTerm; + } + } + } + pScan->pWC = pScan->pWC->pOuter; + k = 0; + } + pScan->pWC = pScan->pOrigWC; + k = 0; + pScan->iEquiv += 2; + } + return 0; +} + +/* +** Initialize a WHERE clause scanner object. Return a pointer to the +** first match. Return NULL if there are no matches. +** +** The scanner will be searching the WHERE clause pWC. It will look +** for terms of the form "X " where X is column iColumn of table +** iCur. The must be one of the operators described by opMask. +** +** If the search is for X and the WHERE clause contains terms of the +** form X=Y then this routine might also return terms of the form +** "Y ". The number of levels of transitivity is limited, +** but is enough to handle most commonly occurring SQL statements. +** +** If X is not the INTEGER PRIMARY KEY then X must be compatible with +** index pIdx. +*/ +static WhereTerm *whereScanInit( + WhereScan *pScan, /* The WhereScan object being initialized */ + WhereClause *pWC, /* The WHERE clause to be scanned */ + int iCur, /* Cursor to scan for */ + int iColumn, /* Column to scan for */ + u32 opMask, /* Operator(s) to scan for */ + Index *pIdx /* Must be compatible with this index */ +){ + int j; + + /* memset(pScan, 0, sizeof(*pScan)); */ + pScan->pOrigWC = pWC; + pScan->pWC = pWC; + if( pIdx && iColumn>=0 ){ + pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; + for(j=0; pIdx->aiColumn[j]!=iColumn; j++){ + if( NEVER(j>=pIdx->nColumn) ) return 0; + } + pScan->zCollName = pIdx->azColl[j]; + }else{ + pScan->idxaff = 0; + pScan->zCollName = 0; + } + pScan->opMask = opMask; + pScan->k = 0; + pScan->aEquiv[0] = iCur; + pScan->aEquiv[1] = iColumn; + pScan->nEquiv = 2; + pScan->iEquiv = 2; + return whereScanNext(pScan); +} + +/* +** Search for a term in the WHERE clause that is of the form "X " +** where X is a reference to the iColumn of table iCur and is one of +** the WO_xx operator codes specified by the op parameter. +** Return a pointer to the term. Return 0 if not found. +** +** The term returned might by Y= if there is another constraint in +** the WHERE clause that specifies that X=Y. Any such constraints will be +** identified by the WO_EQUIV bit in the pTerm->eOperator field. The +** aEquiv[] array holds X and all its equivalents, with each SQL variable +** taking up two slots in aEquiv[]. The first slot is for the cursor number +** and the second is for the column number. There are 22 slots in aEquiv[] +** so that means we can look for X plus up to 10 other equivalent values. +** Hence a search for X will return if X=A1 and A1=A2 and A2=A3 +** and ... and A9=A10 and A10=. +** +** If there are multiple terms in the WHERE clause of the form "X " +** then try for the one with no dependencies on - in other words where +** is a constant expression of some kind. Only return entries of +** the form "X Y" where Y is a column in another table if no terms of +** the form "X " exist. If no terms with a constant RHS +** exist, try to return a term that does not use WO_EQUIV. +*/ +static WhereTerm *findTerm( + WhereClause *pWC, /* The WHERE clause to be searched */ + int iCur, /* Cursor number of LHS */ + int iColumn, /* Column number of LHS */ + Bitmask notReady, /* RHS must not overlap with this mask */ + u32 op, /* Mask of WO_xx values describing operator */ + Index *pIdx /* Must be compatible with this index, if not NULL */ +){ + WhereTerm *pResult = 0; + WhereTerm *p; + WhereScan scan; + + p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx); + while( p ){ + if( (p->prereqRight & notReady)==0 ){ + if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){ + return p; + } + if( pResult==0 ) pResult = p; + } + p = whereScanNext(&scan); + } + return pResult; +} + +/* Forward reference */ +static void exprAnalyze(SrcList*, WhereClause*, int); + +/* +** Call exprAnalyze on all terms in a WHERE clause. +*/ +static void exprAnalyzeAll( + SrcList *pTabList, /* the FROM clause */ + WhereClause *pWC /* the WHERE clause to be analyzed */ +){ + int i; + for(i=pWC->nTerm-1; i>=0; i--){ + exprAnalyze(pTabList, pWC, i); + } +} + +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION +/* +** Check to see if the given expression is a LIKE or GLOB operator that +** can be optimized using inequality constraints. Return TRUE if it is +** so and false if not. +** +** In order for the operator to be optimizible, the RHS must be a string +** literal that does not begin with a wildcard. +*/ +static int isLikeOrGlob( + Parse *pParse, /* Parsing and code generating context */ + Expr *pExpr, /* Test this expression */ + Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */ + int *pisComplete, /* True if the only wildcard is % in the last character */ + int *pnoCase /* True if uppercase is equivalent to lowercase */ +){ + const char *z = 0; /* String on RHS of LIKE operator */ + Expr *pRight, *pLeft; /* Right and left size of LIKE operator */ + ExprList *pList; /* List of operands to the LIKE operator */ + int c; /* One character in z[] */ + int cnt; /* Number of non-wildcard prefix characters */ + char wc[3]; /* Wildcard characters */ + sqlite3 *db = pParse->db; /* Database connection */ + sqlite3_value *pVal = 0; + int op; /* Opcode of pRight */ + + if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){ + return 0; + } +#ifdef SQLITE_EBCDIC + if( *pnoCase ) return 0; +#endif + pList = pExpr->x.pList; + pLeft = pList->a[1].pExpr; + if( pLeft->op!=TK_COLUMN + || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT + || IsVirtual(pLeft->pTab) + ){ + /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must + ** be the name of an indexed column with TEXT affinity. */ + return 0; + } + assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */ + + pRight = pList->a[0].pExpr; + op = pRight->op; + if( op==TK_REGISTER ){ + op = pRight->op2; + } + if( op==TK_VARIABLE ){ + Vdbe *pReprepare = pParse->pReprepare; + int iCol = pRight->iColumn; + pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE); + if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ + z = (char *)sqlite3_value_text(pVal); + } + sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); + assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); + }else if( op==TK_STRING ){ + z = pRight->u.zToken; + } + if( z ){ + cnt = 0; + while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ + cnt++; + } + if( cnt!=0 && 255!=(u8)z[cnt-1] ){ + Expr *pPrefix; + *pisComplete = c==wc[0] && z[cnt+1]==0; + pPrefix = sqlite3Expr(db, TK_STRING, z); + if( pPrefix ) pPrefix->u.zToken[cnt] = 0; + *ppPrefix = pPrefix; + if( op==TK_VARIABLE ){ + Vdbe *v = pParse->pVdbe; + sqlite3VdbeSetVarmask(v, pRight->iColumn); + if( *pisComplete && pRight->u.zToken[1] ){ + /* If the rhs of the LIKE expression is a variable, and the current + ** value of the variable means there is no need to invoke the LIKE + ** function, then no OP_Variable will be added to the program. + ** This causes problems for the sqlite3_bind_parameter_name() + ** API. To workaround them, add a dummy OP_Variable here. + */ + int r1 = sqlite3GetTempReg(pParse); + sqlite3ExprCodeTarget(pParse, pRight, r1); + sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0); + sqlite3ReleaseTempReg(pParse, r1); + } + } + }else{ + z = 0; + } + } + + sqlite3ValueFree(pVal); + return (z!=0); +} +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ + + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Check to see if the given expression is of the form +** +** column MATCH expr +** +** If it is then return TRUE. If not, return FALSE. +*/ +static int isMatchOfColumn( + Expr *pExpr /* Test this expression */ +){ + ExprList *pList; + + if( pExpr->op!=TK_FUNCTION ){ + return 0; + } + if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){ + return 0; + } + pList = pExpr->x.pList; + if( pList->nExpr!=2 ){ + return 0; + } + if( pList->a[1].pExpr->op != TK_COLUMN ){ + return 0; + } + return 1; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** If the pBase expression originated in the ON or USING clause of +** a join, then transfer the appropriate markings over to derived. +*/ +static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ + if( pDerived ){ + pDerived->flags |= pBase->flags & EP_FromJoin; + pDerived->iRightJoinTable = pBase->iRightJoinTable; + } +} + +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) +/* +** Analyze a term that consists of two or more OR-connected +** subterms. So in: +** +** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13) +** ^^^^^^^^^^^^^^^^^^^^ +** +** This routine analyzes terms such as the middle term in the above example. +** A WhereOrTerm object is computed and attached to the term under +** analysis, regardless of the outcome of the analysis. Hence: +** +** WhereTerm.wtFlags |= TERM_ORINFO +** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object +** +** The term being analyzed must have two or more of OR-connected subterms. +** A single subterm might be a set of AND-connected sub-subterms. +** Examples of terms under analysis: +** +** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5 +** (B) x=expr1 OR expr2=x OR x=expr3 +** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15) +** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*') +** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6) +** +** CASE 1: +** +** If all subterms are of the form T.C=expr for some single column of C and +** a single table T (as shown in example B above) then create a new virtual +** term that is an equivalent IN expression. In other words, if the term +** being analyzed is: +** +** x = expr1 OR expr2 = x OR x = expr3 +** +** then create a new virtual term like this: +** +** x IN (expr1,expr2,expr3) +** +** CASE 2: +** +** If all subterms are indexable by a single table T, then set +** +** WhereTerm.eOperator = WO_OR +** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T +** +** A subterm is "indexable" if it is of the form +** "T.C " where C is any column of table T and +** is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN". +** A subterm is also indexable if it is an AND of two or more +** subsubterms at least one of which is indexable. Indexable AND +** subterms have their eOperator set to WO_AND and they have +** u.pAndInfo set to a dynamically allocated WhereAndTerm object. +** +** From another point of view, "indexable" means that the subterm could +** potentially be used with an index if an appropriate index exists. +** This analysis does not consider whether or not the index exists; that +** is decided elsewhere. This analysis only looks at whether subterms +** appropriate for indexing exist. +** +** All examples A through E above satisfy case 2. But if a term +** also statisfies case 1 (such as B) we know that the optimizer will +** always prefer case 1, so in that case we pretend that case 2 is not +** satisfied. +** +** It might be the case that multiple tables are indexable. For example, +** (E) above is indexable on tables P, Q, and R. +** +** Terms that satisfy case 2 are candidates for lookup by using +** separate indices to find rowids for each subterm and composing +** the union of all rowids using a RowSet object. This is similar +** to "bitmap indices" in other database engines. +** +** OTHERWISE: +** +** If neither case 1 nor case 2 apply, then leave the eOperator set to +** zero. This term is not useful for search. +*/ +static void exprAnalyzeOrTerm( + SrcList *pSrc, /* the FROM clause */ + WhereClause *pWC, /* the complete WHERE clause */ + int idxTerm /* Index of the OR-term to be analyzed */ +){ + WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ + Parse *pParse = pWInfo->pParse; /* Parser context */ + sqlite3 *db = pParse->db; /* Database connection */ + WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ + Expr *pExpr = pTerm->pExpr; /* The expression of the term */ + int i; /* Loop counters */ + WhereClause *pOrWc; /* Breakup of pTerm into subterms */ + WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */ + WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */ + Bitmask chngToIN; /* Tables that might satisfy case 1 */ + Bitmask indexable; /* Tables that are indexable, satisfying case 2 */ + + /* + ** Break the OR clause into its separate subterms. The subterms are + ** stored in a WhereClause structure containing within the WhereOrInfo + ** object that is attached to the original OR clause term. + */ + assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); + assert( pExpr->op==TK_OR ); + pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); + if( pOrInfo==0 ) return; + pTerm->wtFlags |= TERM_ORINFO; + pOrWc = &pOrInfo->wc; + whereClauseInit(pOrWc, pWInfo); + whereSplit(pOrWc, pExpr, TK_OR); + exprAnalyzeAll(pSrc, pOrWc); + if( db->mallocFailed ) return; + assert( pOrWc->nTerm>=2 ); + + /* + ** Compute the set of tables that might satisfy cases 1 or 2. + */ + indexable = ~(Bitmask)0; + chngToIN = ~(Bitmask)0; + for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){ + if( (pOrTerm->eOperator & WO_SINGLE)==0 ){ + WhereAndInfo *pAndInfo; + assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); + chngToIN = 0; + pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo)); + if( pAndInfo ){ + WhereClause *pAndWC; + WhereTerm *pAndTerm; + int j; + Bitmask b = 0; + pOrTerm->u.pAndInfo = pAndInfo; + pOrTerm->wtFlags |= TERM_ANDINFO; + pOrTerm->eOperator = WO_AND; + pAndWC = &pAndInfo->wc; + whereClauseInit(pAndWC, pWC->pWInfo); + whereSplit(pAndWC, pOrTerm->pExpr, TK_AND); + exprAnalyzeAll(pSrc, pAndWC); + pAndWC->pOuter = pWC; + testcase( db->mallocFailed ); + if( !db->mallocFailed ){ + for(j=0, pAndTerm=pAndWC->a; jnTerm; j++, pAndTerm++){ + assert( pAndTerm->pExpr ); + if( allowedOp(pAndTerm->pExpr->op) ){ + b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); + } + } + } + indexable &= b; + } + }else if( pOrTerm->wtFlags & TERM_COPIED ){ + /* Skip this term for now. We revisit it when we process the + ** corresponding TERM_VIRTUAL term */ + }else{ + Bitmask b; + b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); + if( pOrTerm->wtFlags & TERM_VIRTUAL ){ + WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; + b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor); + } + indexable &= b; + if( (pOrTerm->eOperator & WO_EQ)==0 ){ + chngToIN = 0; + }else{ + chngToIN &= b; + } + } + } + + /* + ** Record the set of tables that satisfy case 2. The set might be + ** empty. + */ + pOrInfo->indexable = indexable; + pTerm->eOperator = indexable==0 ? 0 : WO_OR; + + /* + ** chngToIN holds a set of tables that *might* satisfy case 1. But + ** we have to do some additional checking to see if case 1 really + ** is satisfied. + ** + ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means + ** that there is no possibility of transforming the OR clause into an + ** IN operator because one or more terms in the OR clause contain + ** something other than == on a column in the single table. The 1-bit + ** case means that every term of the OR clause is of the form + ** "table.column=expr" for some single table. The one bit that is set + ** will correspond to the common table. We still need to check to make + ** sure the same column is used on all terms. The 2-bit case is when + ** the all terms are of the form "table1.column=table2.column". It + ** might be possible to form an IN operator with either table1.column + ** or table2.column as the LHS if either is common to every term of + ** the OR clause. + ** + ** Note that terms of the form "table.column1=table.column2" (the + ** same table on both sizes of the ==) cannot be optimized. + */ + if( chngToIN ){ + int okToChngToIN = 0; /* True if the conversion to IN is valid */ + int iColumn = -1; /* Column index on lhs of IN operator */ + int iCursor = -1; /* Table cursor common to all terms */ + int j = 0; /* Loop counter */ + + /* Search for a table and column that appears on one side or the + ** other of the == operator in every subterm. That table and column + ** will be recorded in iCursor and iColumn. There might not be any + ** such table and column. Set okToChngToIN if an appropriate table + ** and column is found but leave okToChngToIN false if not found. + */ + for(j=0; j<2 && !okToChngToIN; j++){ + pOrTerm = pOrWc->a; + for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ + assert( pOrTerm->eOperator & WO_EQ ); + pOrTerm->wtFlags &= ~TERM_OR_OK; + if( pOrTerm->leftCursor==iCursor ){ + /* This is the 2-bit case and we are on the second iteration and + ** current term is from the first iteration. So skip this term. */ + assert( j==1 ); + continue; + } + if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){ + /* This term must be of the form t1.a==t2.b where t2 is in the + ** chngToIN set but t1 is not. This term will be either preceeded + ** or follwed by an inverted copy (t2.b==t1.a). Skip this term + ** and use its inversion. */ + testcase( pOrTerm->wtFlags & TERM_COPIED ); + testcase( pOrTerm->wtFlags & TERM_VIRTUAL ); + assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) ); + continue; + } + iColumn = pOrTerm->u.leftColumn; + iCursor = pOrTerm->leftCursor; + break; + } + if( i<0 ){ + /* No candidate table+column was found. This can only occur + ** on the second iteration */ + assert( j==1 ); + assert( IsPowerOfTwo(chngToIN) ); + assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) ); + break; + } + testcase( j==1 ); + + /* We have found a candidate table and column. Check to see if that + ** table and column is common to every term in the OR clause */ + okToChngToIN = 1; + for(; i>=0 && okToChngToIN; i--, pOrTerm++){ + assert( pOrTerm->eOperator & WO_EQ ); + if( pOrTerm->leftCursor!=iCursor ){ + pOrTerm->wtFlags &= ~TERM_OR_OK; + }else if( pOrTerm->u.leftColumn!=iColumn ){ + okToChngToIN = 0; + }else{ + int affLeft, affRight; + /* If the right-hand side is also a column, then the affinities + ** of both right and left sides must be such that no type + ** conversions are required on the right. (Ticket #2249) + */ + affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); + affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); + if( affRight!=0 && affRight!=affLeft ){ + okToChngToIN = 0; + }else{ + pOrTerm->wtFlags |= TERM_OR_OK; + } + } + } + } + + /* At this point, okToChngToIN is true if original pTerm satisfies + ** case 1. In that case, construct a new virtual term that is + ** pTerm converted into an IN operator. + */ + if( okToChngToIN ){ + Expr *pDup; /* A transient duplicate expression */ + ExprList *pList = 0; /* The RHS of the IN operator */ + Expr *pLeft = 0; /* The LHS of the IN operator */ + Expr *pNew; /* The complete IN operator */ + + for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ + if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue; + assert( pOrTerm->eOperator & WO_EQ ); + assert( pOrTerm->leftCursor==iCursor ); + assert( pOrTerm->u.leftColumn==iColumn ); + pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); + pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); + pLeft = pOrTerm->pExpr->pLeft; + } + assert( pLeft!=0 ); + pDup = sqlite3ExprDup(db, pLeft, 0); + pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0); + if( pNew ){ + int idxNew; + transferJoinMarkings(pNew, pExpr); + assert( !ExprHasProperty(pNew, EP_xIsSelect) ); + pNew->x.pList = pList; + idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew==0 ); + exprAnalyze(pSrc, pWC, idxNew); + pTerm = &pWC->a[idxTerm]; + pWC->a[idxNew].iParent = idxTerm; + pTerm->nChild = 1; + }else{ + sqlite3ExprListDelete(db, pList); + } + pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */ + } + } +} +#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ + +/* +** The input to this routine is an WhereTerm structure with only the +** "pExpr" field filled in. The job of this routine is to analyze the +** subexpression and populate all the other fields of the WhereTerm +** structure. +** +** If the expression is of the form " X" it gets commuted +** to the standard form of "X ". +** +** If the expression is of the form "X Y" where both X and Y are +** columns, then the original expression is unchanged and a new virtual +** term of the form "Y X" is added to the WHERE clause and +** analyzed separately. The original term is marked with TERM_COPIED +** and the new term is marked with TERM_DYNAMIC (because it's pExpr +** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it +** is a commuted copy of a prior term.) The original term has nChild=1 +** and the copy has idxParent set to the index of the original term. +*/ +static void exprAnalyze( + SrcList *pSrc, /* the FROM clause */ + WhereClause *pWC, /* the WHERE clause */ + int idxTerm /* Index of the term to be analyzed */ +){ + WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ + WhereTerm *pTerm; /* The term to be analyzed */ + WhereMaskSet *pMaskSet; /* Set of table index masks */ + Expr *pExpr; /* The expression to be analyzed */ + Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */ + Bitmask prereqAll; /* Prerequesites of pExpr */ + Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */ + Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */ + int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */ + int noCase = 0; /* LIKE/GLOB distinguishes case */ + int op; /* Top-level operator. pExpr->op */ + Parse *pParse = pWInfo->pParse; /* Parsing context */ + sqlite3 *db = pParse->db; /* Database connection */ + + if( db->mallocFailed ){ + return; + } + pTerm = &pWC->a[idxTerm]; + pMaskSet = &pWInfo->sMaskSet; + pExpr = pTerm->pExpr; + assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); + prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft); + op = pExpr->op; + if( op==TK_IN ){ + assert( pExpr->pRight==0 ); + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect); + }else{ + pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList); + } + }else if( op==TK_ISNULL ){ + pTerm->prereqRight = 0; + }else{ + pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight); + } + prereqAll = exprTableUsage(pMaskSet, pExpr); + if( ExprHasProperty(pExpr, EP_FromJoin) ){ + Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable); + prereqAll |= x; + extraRight = x-1; /* ON clause terms may not be used with an index + ** on left table of a LEFT JOIN. Ticket #3015 */ + } + pTerm->prereqAll = prereqAll; + pTerm->leftCursor = -1; + pTerm->iParent = -1; + pTerm->eOperator = 0; + if( allowedOp(op) ){ + Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); + Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); + u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; + if( pLeft->op==TK_COLUMN ){ + pTerm->leftCursor = pLeft->iTable; + pTerm->u.leftColumn = pLeft->iColumn; + pTerm->eOperator = operatorMask(op) & opMask; + } + if( pRight && pRight->op==TK_COLUMN ){ + WhereTerm *pNew; + Expr *pDup; + u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */ + if( pTerm->leftCursor>=0 ){ + int idxNew; + pDup = sqlite3ExprDup(db, pExpr, 0); + if( db->mallocFailed ){ + sqlite3ExprDelete(db, pDup); + return; + } + idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); + if( idxNew==0 ) return; + pNew = &pWC->a[idxNew]; + pNew->iParent = idxTerm; + pTerm = &pWC->a[idxTerm]; + pTerm->nChild = 1; + pTerm->wtFlags |= TERM_COPIED; + if( pExpr->op==TK_EQ + && !ExprHasProperty(pExpr, EP_FromJoin) + && OptimizationEnabled(db, SQLITE_Transitive) + ){ + pTerm->eOperator |= WO_EQUIV; + eExtraOp = WO_EQUIV; + } + }else{ + pDup = pExpr; + pNew = pTerm; + } + exprCommute(pParse, pDup); + pLeft = sqlite3ExprSkipCollate(pDup->pLeft); + pNew->leftCursor = pLeft->iTable; + pNew->u.leftColumn = pLeft->iColumn; + testcase( (prereqLeft | extraRight) != prereqLeft ); + pNew->prereqRight = prereqLeft | extraRight; + pNew->prereqAll = prereqAll; + pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask; + } + } + +#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION + /* If a term is the BETWEEN operator, create two new virtual terms + ** that define the range that the BETWEEN implements. For example: + ** + ** a BETWEEN b AND c + ** + ** is converted into: + ** + ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c) + ** + ** The two new terms are added onto the end of the WhereClause object. + ** The new terms are "dynamic" and are children of the original BETWEEN + ** term. That means that if the BETWEEN term is coded, the children are + ** skipped. Or, if the children are satisfied by an index, the original + ** BETWEEN term is skipped. + */ + else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){ + ExprList *pList = pExpr->x.pList; + int i; + static const u8 ops[] = {TK_GE, TK_LE}; + assert( pList!=0 ); + assert( pList->nExpr==2 ); + for(i=0; i<2; i++){ + Expr *pNewExpr; + int idxNew; + pNewExpr = sqlite3PExpr(pParse, ops[i], + sqlite3ExprDup(db, pExpr->pLeft, 0), + sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0); + transferJoinMarkings(pNewExpr, pExpr); + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew==0 ); + exprAnalyze(pSrc, pWC, idxNew); + pTerm = &pWC->a[idxTerm]; + pWC->a[idxNew].iParent = idxTerm; + } + pTerm->nChild = 2; + } +#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ + +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) + /* Analyze a term that is composed of two or more subterms connected by + ** an OR operator. + */ + else if( pExpr->op==TK_OR ){ + assert( pWC->op==TK_AND ); + exprAnalyzeOrTerm(pSrc, pWC, idxTerm); + pTerm = &pWC->a[idxTerm]; + } +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */ + +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION + /* Add constraints to reduce the search space on a LIKE or GLOB + ** operator. + ** + ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints + ** + ** x>='abc' AND x<'abd' AND x LIKE 'abc%' + ** + ** The last character of the prefix "abc" is incremented to form the + ** termination condition "abd". + */ + if( pWC->op==TK_AND + && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase) + ){ + Expr *pLeft; /* LHS of LIKE/GLOB operator */ + Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */ + Expr *pNewExpr1; + Expr *pNewExpr2; + int idxNew1; + int idxNew2; + Token sCollSeqName; /* Name of collating sequence */ + + pLeft = pExpr->x.pList->a[1].pExpr; + pStr2 = sqlite3ExprDup(db, pStr1, 0); + if( !db->mallocFailed ){ + u8 c, *pC; /* Last character before the first wildcard */ + pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; + c = *pC; + if( noCase ){ + /* The point is to increment the last character before the first + ** wildcard. But if we increment '@', that will push it into the + ** alphabetic range where case conversions will mess up the + ** inequality. To avoid this, make sure to also run the full + ** LIKE on all candidate expressions by clearing the isComplete flag + */ + if( c=='A'-1 ) isComplete = 0; + c = sqlite3UpperToLower[c]; + } + *pC = c + 1; + } + sCollSeqName.z = noCase ? "NOCASE" : "BINARY"; + sCollSeqName.n = 6; + pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); + pNewExpr1 = sqlite3PExpr(pParse, TK_GE, + sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName), + pStr1, 0); + transferJoinMarkings(pNewExpr1, pExpr); + idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew1==0 ); + exprAnalyze(pSrc, pWC, idxNew1); + pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); + pNewExpr2 = sqlite3PExpr(pParse, TK_LT, + sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName), + pStr2, 0); + transferJoinMarkings(pNewExpr2, pExpr); + idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew2==0 ); + exprAnalyze(pSrc, pWC, idxNew2); + pTerm = &pWC->a[idxTerm]; + if( isComplete ){ + pWC->a[idxNew1].iParent = idxTerm; + pWC->a[idxNew2].iParent = idxTerm; + pTerm->nChild = 2; + } + } +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE + /* Add a WO_MATCH auxiliary term to the constraint set if the + ** current expression is of the form: column MATCH expr. + ** This information is used by the xBestIndex methods of + ** virtual tables. The native query optimizer does not attempt + ** to do anything with MATCH functions. + */ + if( isMatchOfColumn(pExpr) ){ + int idxNew; + Expr *pRight, *pLeft; + WhereTerm *pNewTerm; + Bitmask prereqColumn, prereqExpr; + + pRight = pExpr->x.pList->a[0].pExpr; + pLeft = pExpr->x.pList->a[1].pExpr; + prereqExpr = exprTableUsage(pMaskSet, pRight); + prereqColumn = exprTableUsage(pMaskSet, pLeft); + if( (prereqExpr & prereqColumn)==0 ){ + Expr *pNewExpr; + pNewExpr = sqlite3PExpr(pParse, TK_MATCH, + 0, sqlite3ExprDup(db, pRight, 0), 0); + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew==0 ); + pNewTerm = &pWC->a[idxNew]; + pNewTerm->prereqRight = prereqExpr; + pNewTerm->leftCursor = pLeft->iTable; + pNewTerm->u.leftColumn = pLeft->iColumn; + pNewTerm->eOperator = WO_MATCH; + pNewTerm->iParent = idxTerm; + pTerm = &pWC->a[idxTerm]; + pTerm->nChild = 1; + pTerm->wtFlags |= TERM_COPIED; + pNewTerm->prereqAll = pTerm->prereqAll; + } + } +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + /* When sqlite_stat3 histogram data is available an operator of the + ** form "x IS NOT NULL" can sometimes be evaluated more efficiently + ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a + ** virtual term of that form. + ** + ** Note that the virtual term must be tagged with TERM_VNULL. This + ** TERM_VNULL tag will suppress the not-null check at the beginning + ** of the loop. Without the TERM_VNULL flag, the not-null check at + ** the start of the loop will prevent any results from being returned. + */ + if( pExpr->op==TK_NOTNULL + && pExpr->pLeft->op==TK_COLUMN + && pExpr->pLeft->iColumn>=0 + && OptimizationEnabled(db, SQLITE_Stat3) + ){ + Expr *pNewExpr; + Expr *pLeft = pExpr->pLeft; + int idxNew; + WhereTerm *pNewTerm; + + pNewExpr = sqlite3PExpr(pParse, TK_GT, + sqlite3ExprDup(db, pLeft, 0), + sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0); + + idxNew = whereClauseInsert(pWC, pNewExpr, + TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL); + if( idxNew ){ + pNewTerm = &pWC->a[idxNew]; + pNewTerm->prereqRight = 0; + pNewTerm->leftCursor = pLeft->iTable; + pNewTerm->u.leftColumn = pLeft->iColumn; + pNewTerm->eOperator = WO_GT; + pNewTerm->iParent = idxTerm; + pTerm = &pWC->a[idxTerm]; + pTerm->nChild = 1; + pTerm->wtFlags |= TERM_COPIED; + pNewTerm->prereqAll = pTerm->prereqAll; + } + } +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + + /* Prevent ON clause terms of a LEFT JOIN from being used to drive + ** an index for tables to the left of the join. + */ + pTerm->prereqRight |= extraRight; +} + +/* +** This function searches pList for a entry that matches the iCol-th column +** of index pIdx. +** +** If such an expression is found, its index in pList->a[] is returned. If +** no expression is found, -1 is returned. +*/ +static int findIndexCol( + Parse *pParse, /* Parse context */ + ExprList *pList, /* Expression list to search */ + int iBase, /* Cursor for table associated with pIdx */ + Index *pIdx, /* Index to match column of */ + int iCol /* Column of index to match */ +){ + int i; + const char *zColl = pIdx->azColl[iCol]; + + for(i=0; inExpr; i++){ + Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr); + if( p->op==TK_COLUMN + && p->iColumn==pIdx->aiColumn[iCol] + && p->iTable==iBase + ){ + CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr); + if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){ + return i; + } + } + } + + return -1; +} + +/* +** Return true if the DISTINCT expression-list passed as the third argument +** is redundant. +** +** A DISTINCT list is redundant if the database contains some subset of +** columns that are unique and non-null. +*/ +static int isDistinctRedundant( + Parse *pParse, /* Parsing context */ + SrcList *pTabList, /* The FROM clause */ + WhereClause *pWC, /* The WHERE clause */ + ExprList *pDistinct /* The result set that needs to be DISTINCT */ +){ + Table *pTab; + Index *pIdx; + int i; + int iBase; + + /* If there is more than one table or sub-select in the FROM clause of + ** this query, then it will not be possible to show that the DISTINCT + ** clause is redundant. */ + if( pTabList->nSrc!=1 ) return 0; + iBase = pTabList->a[0].iCursor; + pTab = pTabList->a[0].pTab; + + /* If any of the expressions is an IPK column on table iBase, then return + ** true. Note: The (p->iTable==iBase) part of this test may be false if the + ** current SELECT is a correlated sub-query. + */ + for(i=0; inExpr; i++){ + Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr); + if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1; + } + + /* Loop through all indices on the table, checking each to see if it makes + ** the DISTINCT qualifier redundant. It does so if: + ** + ** 1. The index is itself UNIQUE, and + ** + ** 2. All of the columns in the index are either part of the pDistinct + ** list, or else the WHERE clause contains a term of the form "col=X", + ** where X is a constant value. The collation sequences of the + ** comparison and select-list expressions must match those of the index. + ** + ** 3. All of those index columns for which the WHERE clause does not + ** contain a "col=X" term are subject to a NOT NULL constraint. + */ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->onError==OE_None ) continue; + for(i=0; inColumn; i++){ + int iCol = pIdx->aiColumn[i]; + if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){ + int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i); + if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){ + break; + } + } + } + if( i==pIdx->nColumn ){ + /* This index implies that the DISTINCT qualifier is redundant. */ + return 1; + } + } + + return 0; +} + + +/* +** Estimate the logarithm of the input value to base 2. +*/ +static LogEst estLog(LogEst N){ + LogEst x = sqlite3LogEst(N); + return x>33 ? x - 33 : 0; +} + +/* +** Two routines for printing the content of an sqlite3_index_info +** structure. Used for testing and debugging only. If neither +** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines +** are no-ops. +*/ +#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) +static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ + int i; + if( !sqlite3WhereTrace ) return; + for(i=0; inConstraint; i++){ + sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", + i, + p->aConstraint[i].iColumn, + p->aConstraint[i].iTermOffset, + p->aConstraint[i].op, + p->aConstraint[i].usable); + } + for(i=0; inOrderBy; i++){ + sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", + i, + p->aOrderBy[i].iColumn, + p->aOrderBy[i].desc); + } +} +static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ + int i; + if( !sqlite3WhereTrace ) return; + for(i=0; inConstraint; i++){ + sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", + i, + p->aConstraintUsage[i].argvIndex, + p->aConstraintUsage[i].omit); + } + sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); + sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); + sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); + sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); +} +#else +#define TRACE_IDX_INPUTS(A) +#define TRACE_IDX_OUTPUTS(A) +#endif + +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX +/* +** Return TRUE if the WHERE clause term pTerm is of a form where it +** could be used with an index to access pSrc, assuming an appropriate +** index existed. +*/ +static int termCanDriveIndex( + WhereTerm *pTerm, /* WHERE clause term to check */ + struct SrcList_item *pSrc, /* Table we are trying to access */ + Bitmask notReady /* Tables in outer loops of the join */ +){ + char aff; + if( pTerm->leftCursor!=pSrc->iCursor ) return 0; + if( (pTerm->eOperator & WO_EQ)==0 ) return 0; + if( (pTerm->prereqRight & notReady)!=0 ) return 0; + if( pTerm->u.leftColumn<0 ) return 0; + aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity; + if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; + return 1; +} +#endif + + +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX +/* +** Generate code to construct the Index object for an automatic index +** and to set up the WhereLevel object pLevel so that the code generator +** makes use of the automatic index. +*/ +static void constructAutomaticIndex( + Parse *pParse, /* The parsing context */ + WhereClause *pWC, /* The WHERE clause */ + struct SrcList_item *pSrc, /* The FROM clause term to get the next index */ + Bitmask notReady, /* Mask of cursors that are not available */ + WhereLevel *pLevel /* Write new index here */ +){ + int nColumn; /* Number of columns in the constructed index */ + WhereTerm *pTerm; /* A single term of the WHERE clause */ + WhereTerm *pWCEnd; /* End of pWC->a[] */ + int nByte; /* Byte of memory needed for pIdx */ + Index *pIdx; /* Object describing the transient index */ + Vdbe *v; /* Prepared statement under construction */ + int addrInit; /* Address of the initialization bypass jump */ + Table *pTable; /* The table being indexed */ + KeyInfo *pKeyinfo; /* Key information for the index */ + int addrTop; /* Top of the index fill loop */ + int regRecord; /* Register holding an index record */ + int n; /* Column counter */ + int i; /* Loop counter */ + int mxBitCol; /* Maximum column in pSrc->colUsed */ + CollSeq *pColl; /* Collating sequence to on a column */ + WhereLoop *pLoop; /* The Loop object */ + Bitmask idxCols; /* Bitmap of columns used for indexing */ + Bitmask extraCols; /* Bitmap of additional columns */ + u8 sentWarning = 0; /* True if a warnning has been issued */ + + /* Generate code to skip over the creation and initialization of the + ** transient index on 2nd and subsequent iterations of the loop. */ + v = pParse->pVdbe; + assert( v!=0 ); + addrInit = sqlite3CodeOnce(pParse); + + /* Count the number of columns that will be added to the index + ** and used to match WHERE clause constraints */ + nColumn = 0; + pTable = pSrc->pTab; + pWCEnd = &pWC->a[pWC->nTerm]; + pLoop = pLevel->pWLoop; + idxCols = 0; + for(pTerm=pWC->a; pTermu.leftColumn; + Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); + testcase( iCol==BMS ); + testcase( iCol==BMS-1 ); + if( !sentWarning ){ + sqlite3_log(SQLITE_WARNING_AUTOINDEX, + "automatic index on %s(%s)", pTable->zName, + pTable->aCol[iCol].zName); + sentWarning = 1; + } + if( (idxCols & cMask)==0 ){ + if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return; + pLoop->aLTerm[nColumn++] = pTerm; + idxCols |= cMask; + } + } + } + assert( nColumn>0 ); + pLoop->u.btree.nEq = pLoop->nLTerm = nColumn; + pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED + | WHERE_AUTO_INDEX; + + /* Count the number of additional columns needed to create a + ** covering index. A "covering index" is an index that contains all + ** columns that are needed by the query. With a covering index, the + ** original table never needs to be accessed. Automatic indices must + ** be a covering index because the index will not be updated if the + ** original table changes and the index and table cannot both be used + ** if they go out of sync. + */ + extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); + mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol; + testcase( pTable->nCol==BMS-1 ); + testcase( pTable->nCol==BMS-2 ); + for(i=0; icolUsed & MASKBIT(BMS-1) ){ + nColumn += pTable->nCol - BMS + 1; + } + pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY; + + /* Construct the Index object to describe this index */ + nByte = sizeof(Index); + nByte += nColumn*sizeof(int); /* Index.aiColumn */ + nByte += nColumn*sizeof(char*); /* Index.azColl */ + nByte += nColumn; /* Index.aSortOrder */ + pIdx = sqlite3DbMallocZero(pParse->db, nByte); + if( pIdx==0 ) return; + pLoop->u.btree.pIndex = pIdx; + pIdx->azColl = (char**)&pIdx[1]; + pIdx->aiColumn = (int*)&pIdx->azColl[nColumn]; + pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn]; + pIdx->zName = "auto-index"; + pIdx->nColumn = nColumn; + pIdx->pTable = pTable; + n = 0; + idxCols = 0; + for(pTerm=pWC->a; pTermu.leftColumn; + Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); + testcase( iCol==BMS-1 ); + testcase( iCol==BMS ); + if( (idxCols & cMask)==0 ){ + Expr *pX = pTerm->pExpr; + idxCols |= cMask; + pIdx->aiColumn[n] = pTerm->u.leftColumn; + pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); + pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY"; + n++; + } + } + } + assert( (u32)n==pLoop->u.btree.nEq ); + + /* Add additional columns needed to make the automatic index into + ** a covering index */ + for(i=0; iaiColumn[n] = i; + pIdx->azColl[n] = "BINARY"; + n++; + } + } + if( pSrc->colUsed & MASKBIT(BMS-1) ){ + for(i=BMS-1; inCol; i++){ + pIdx->aiColumn[n] = i; + pIdx->azColl[n] = "BINARY"; + n++; + } + } + assert( n==nColumn ); + + /* Create the automatic index */ + pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx); + assert( pLevel->iIdxCur>=0 ); + pLevel->iIdxCur = pParse->nTab++; + sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0, + (char*)pKeyinfo, P4_KEYINFO_HANDOFF); + VdbeComment((v, "for %s", pTable->zName)); + + /* Fill the automatic index with content */ + addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); + regRecord = sqlite3GetTempReg(pParse); + sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0); + sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); + sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); + sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); + sqlite3VdbeJumpHere(v, addrTop); + sqlite3ReleaseTempReg(pParse, regRecord); + + /* Jump here when skipping the initialization */ + sqlite3VdbeJumpHere(v, addrInit); +} +#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Allocate and populate an sqlite3_index_info structure. It is the +** responsibility of the caller to eventually release the structure +** by passing the pointer returned by this function to sqlite3_free(). +*/ +static sqlite3_index_info *allocateIndexInfo( + Parse *pParse, + WhereClause *pWC, + struct SrcList_item *pSrc, + ExprList *pOrderBy +){ + int i, j; + int nTerm; + struct sqlite3_index_constraint *pIdxCons; + struct sqlite3_index_orderby *pIdxOrderBy; + struct sqlite3_index_constraint_usage *pUsage; + WhereTerm *pTerm; + int nOrderBy; + sqlite3_index_info *pIdxInfo; + + /* Count the number of possible WHERE clause constraints referring + ** to this virtual table */ + for(i=nTerm=0, pTerm=pWC->a; inTerm; i++, pTerm++){ + if( pTerm->leftCursor != pSrc->iCursor ) continue; + assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); + testcase( pTerm->eOperator & WO_IN ); + testcase( pTerm->eOperator & WO_ISNULL ); + if( pTerm->eOperator & (WO_ISNULL) ) continue; + if( pTerm->wtFlags & TERM_VNULL ) continue; + nTerm++; + } + + /* If the ORDER BY clause contains only columns in the current + ** virtual table then allocate space for the aOrderBy part of + ** the sqlite3_index_info structure. + */ + nOrderBy = 0; + if( pOrderBy ){ + int n = pOrderBy->nExpr; + for(i=0; ia[i].pExpr; + if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; + } + if( i==n){ + nOrderBy = n; + } + } + + /* Allocate the sqlite3_index_info structure + */ + pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) + + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm + + sizeof(*pIdxOrderBy)*nOrderBy ); + if( pIdxInfo==0 ){ + sqlite3ErrorMsg(pParse, "out of memory"); + return 0; + } + + /* Initialize the structure. The sqlite3_index_info structure contains + ** many fields that are declared "const" to prevent xBestIndex from + ** changing them. We have to do some funky casting in order to + ** initialize those fields. + */ + pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1]; + pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; + pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; + *(int*)&pIdxInfo->nConstraint = nTerm; + *(int*)&pIdxInfo->nOrderBy = nOrderBy; + *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; + *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; + *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = + pUsage; + + for(i=j=0, pTerm=pWC->a; inTerm; i++, pTerm++){ + u8 op; + if( pTerm->leftCursor != pSrc->iCursor ) continue; + assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); + testcase( pTerm->eOperator & WO_IN ); + testcase( pTerm->eOperator & WO_ISNULL ); + if( pTerm->eOperator & (WO_ISNULL) ) continue; + if( pTerm->wtFlags & TERM_VNULL ) continue; + pIdxCons[j].iColumn = pTerm->u.leftColumn; + pIdxCons[j].iTermOffset = i; + op = (u8)pTerm->eOperator & WO_ALL; + if( op==WO_IN ) op = WO_EQ; + pIdxCons[j].op = op; + /* The direct assignment in the previous line is possible only because + ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The + ** following asserts verify this fact. */ + assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); + assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); + assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); + assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); + assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); + assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); + assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) ); + j++; + } + for(i=0; ia[i].pExpr; + pIdxOrderBy[i].iColumn = pExpr->iColumn; + pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder; + } + + return pIdxInfo; +} + +/* +** The table object reference passed as the second argument to this function +** must represent a virtual table. This function invokes the xBestIndex() +** method of the virtual table with the sqlite3_index_info object that +** comes in as the 3rd argument to this function. +** +** If an error occurs, pParse is populated with an error message and a +** non-zero value is returned. Otherwise, 0 is returned and the output +** part of the sqlite3_index_info structure is left populated. +** +** Whether or not an error is returned, it is the responsibility of the +** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates +** that this is required. +*/ +static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ + sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; + int i; + int rc; + + TRACE_IDX_INPUTS(p); + rc = pVtab->pModule->xBestIndex(pVtab, p); + TRACE_IDX_OUTPUTS(p); + + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM ){ + pParse->db->mallocFailed = 1; + }else if( !pVtab->zErrMsg ){ + sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); + }else{ + sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); + } + } + sqlite3_free(pVtab->zErrMsg); + pVtab->zErrMsg = 0; + + for(i=0; inConstraint; i++){ + if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ + sqlite3ErrorMsg(pParse, + "table %s: xBestIndex returned an invalid plan", pTab->zName); + } + } + + return pParse->nErr; +} +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ + + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Estimate the location of a particular key among all keys in an +** index. Store the results in aStat as follows: +** +** aStat[0] Est. number of rows less than pVal +** aStat[1] Est. number of rows equal to pVal +** +** Return SQLITE_OK on success. +*/ +static void whereKeyStats( + Parse *pParse, /* Database connection */ + Index *pIdx, /* Index to consider domain of */ + UnpackedRecord *pRec, /* Vector of values to consider */ + int roundUp, /* Round up if true. Round down if false */ + tRowcnt *aStat /* OUT: stats written here */ +){ + IndexSample *aSample = pIdx->aSample; + int iCol; /* Index of required stats in anEq[] etc. */ + int iMin = 0; /* Smallest sample not yet tested */ + int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */ + int iTest; /* Next sample to test */ + int res; /* Result of comparison operation */ + +#ifndef SQLITE_DEBUG + UNUSED_PARAMETER( pParse ); +#endif + assert( pRec!=0 || pParse->db->mallocFailed ); + if( pRec==0 ) return; + iCol = pRec->nField - 1; + assert( pIdx->nSample>0 ); + assert( pRec->nField>0 && iColnSampleCol ); + do{ + iTest = (iMin+i)/2; + res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec); + if( res<0 ){ + iMin = iTest+1; + }else{ + i = iTest; + } + }while( res && iMinnSample ); + assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) + || pParse->db->mallocFailed ); + }else{ + /* Otherwise, pRec must be smaller than sample $i and larger than + ** sample ($i-1). */ + assert( i==pIdx->nSample + || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 + || pParse->db->mallocFailed ); + assert( i==0 + || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 + || pParse->db->mallocFailed ); + } +#endif /* ifdef SQLITE_DEBUG */ + + /* At this point, aSample[i] is the first sample that is greater than + ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less + ** than pVal. If aSample[i]==pVal, then res==0. + */ + if( res==0 ){ + aStat[0] = aSample[i].anLt[iCol]; + aStat[1] = aSample[i].anEq[iCol]; + }else{ + tRowcnt iLower, iUpper, iGap; + if( i==0 ){ + iLower = 0; + iUpper = aSample[0].anLt[iCol]; + }else{ + iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol]; + iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol]; + } + aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1); + if( iLower>=iUpper ){ + iGap = 0; + }else{ + iGap = iUpper - iLower; + } + if( roundUp ){ + iGap = (iGap*2)/3; + }else{ + iGap = iGap/3; + } + aStat[0] = iLower + iGap; + } +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +/* +** This function is used to estimate the number of rows that will be visited +** by scanning an index for a range of values. The range may have an upper +** bound, a lower bound, or both. The WHERE clause terms that set the upper +** and lower bounds are represented by pLower and pUpper respectively. For +** example, assuming that index p is on t1(a): +** +** ... FROM t1 WHERE a > ? AND a < ? ... +** |_____| |_____| +** | | +** pLower pUpper +** +** If either of the upper or lower bound is not present, then NULL is passed in +** place of the corresponding WhereTerm. +** +** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index +** column subject to the range constraint. Or, equivalently, the number of +** equality constraints optimized by the proposed index scan. For example, +** assuming index p is on t1(a, b), and the SQL query is: +** +** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... +** +** then nEq is set to 1 (as the range restricted column, b, is the second +** left-most column of the index). Or, if the query is: +** +** ... FROM t1 WHERE a > ? AND a < ? ... +** +** then nEq is set to 0. +** +** When this function is called, *pnOut is set to the sqlite3LogEst() of the +** number of rows that the index scan is expected to visit without +** considering the range constraints. If nEq is 0, this is the number of +** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) +** to account for the range contraints pLower and pUpper. +** +** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be +** used, each range inequality reduces the search space by a factor of 4. +** Hence a pair of constraints (x>? AND x123" Might be NULL */ + WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ + WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ +){ + int rc = SQLITE_OK; + int nOut = pLoop->nOut; + LogEst nNew; + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + Index *p = pLoop->u.btree.pIndex; + int nEq = pLoop->u.btree.nEq; + + if( p->nSample>0 + && nEq==pBuilder->nRecValid + && nEqnSampleCol + && OptimizationEnabled(pParse->db, SQLITE_Stat3) + ){ + UnpackedRecord *pRec = pBuilder->pRec; + tRowcnt a[2]; + u8 aff; + + /* Variable iLower will be set to the estimate of the number of rows in + ** the index that are less than the lower bound of the range query. The + ** lower bound being the concatenation of $P and $L, where $P is the + ** key-prefix formed by the nEq values matched against the nEq left-most + ** columns of the index, and $L is the value in pLower. + ** + ** Or, if pLower is NULL or $L cannot be extracted from it (because it + ** is not a simple variable or literal value), the lower bound of the + ** range is $P. Due to a quirk in the way whereKeyStats() works, even + ** if $L is available, whereKeyStats() is called for both ($P) and + ** ($P:$L) and the larger of the two returned values used. + ** + ** Similarly, iUpper is to be set to the estimate of the number of rows + ** less than the upper bound of the range query. Where the upper bound + ** is either ($P) or ($P:$U). Again, even if $U is available, both values + ** of iUpper are requested of whereKeyStats() and the smaller used. + */ + tRowcnt iLower; + tRowcnt iUpper; + + if( nEq==p->nColumn ){ + aff = SQLITE_AFF_INTEGER; + }else{ + aff = p->pTable->aCol[p->aiColumn[nEq]].affinity; + } + /* Determine iLower and iUpper using ($P) only. */ + if( nEq==0 ){ + iLower = 0; + iUpper = p->aiRowEst[0]; + }else{ + /* Note: this call could be optimized away - since the same values must + ** have been requested when testing key $P in whereEqualScanEst(). */ + whereKeyStats(pParse, p, pRec, 0, a); + iLower = a[0]; + iUpper = a[0] + a[1]; + } + + /* If possible, improve on the iLower estimate using ($P:$L). */ + if( pLower ){ + int bOk; /* True if value is extracted from pExpr */ + Expr *pExpr = pLower->pExpr->pRight; + assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 ); + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); + if( rc==SQLITE_OK && bOk ){ + tRowcnt iNew; + whereKeyStats(pParse, p, pRec, 0, a); + iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0); + if( iNew>iLower ) iLower = iNew; + nOut--; + } + } + + /* If possible, improve on the iUpper estimate using ($P:$U). */ + if( pUpper ){ + int bOk; /* True if value is extracted from pExpr */ + Expr *pExpr = pUpper->pExpr->pRight; + assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); + if( rc==SQLITE_OK && bOk ){ + tRowcnt iNew; + whereKeyStats(pParse, p, pRec, 1, a); + iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0); + if( iNewpRec = pRec; + if( rc==SQLITE_OK ){ + if( iUpper>iLower ){ + nNew = sqlite3LogEst(iUpper - iLower); + }else{ + nNew = 10; assert( 10==sqlite3LogEst(2) ); + } + if( nNewnOut = (LogEst)nOut; + WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n", + (u32)iLower, (u32)iUpper, nOut)); + return SQLITE_OK; + } + } +#else + UNUSED_PARAMETER(pParse); + UNUSED_PARAMETER(pBuilder); +#endif + assert( pLower || pUpper ); + /* TUNING: Each inequality constraint reduces the search space 4-fold. + ** A BETWEEN operator, therefore, reduces the search space 16-fold */ + nNew = nOut; + if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){ + nNew -= 20; assert( 20==sqlite3LogEst(4) ); + nOut--; + } + if( pUpper ){ + nNew -= 20; assert( 20==sqlite3LogEst(4) ); + nOut--; + } + if( nNew<10 ) nNew = 10; + if( nNewnOut = (LogEst)nOut; + return rc; +} + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Estimate the number of rows that will be returned based on +** an equality constraint x=VALUE and where that VALUE occurs in +** the histogram data. This only works when x is the left-most +** column of an index and sqlite_stat3 histogram data is available +** for that index. When pExpr==NULL that means the constraint is +** "x IS NULL" instead of "x=VALUE". +** +** Write the estimated row count into *pnRow and return SQLITE_OK. +** If unable to make an estimate, leave *pnRow unchanged and return +** non-zero. +** +** This routine can fail if it is unable to load a collating sequence +** required for string comparison, or if unable to allocate memory +** for a UTF conversion required for comparison. The error is stored +** in the pParse structure. +*/ +static int whereEqualScanEst( + Parse *pParse, /* Parsing & code generating context */ + WhereLoopBuilder *pBuilder, + Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */ + tRowcnt *pnRow /* Write the revised row estimate here */ +){ + Index *p = pBuilder->pNew->u.btree.pIndex; + int nEq = pBuilder->pNew->u.btree.nEq; + UnpackedRecord *pRec = pBuilder->pRec; + u8 aff; /* Column affinity */ + int rc; /* Subfunction return code */ + tRowcnt a[2]; /* Statistics */ + int bOk; + + assert( nEq>=1 ); + assert( nEq<=(p->nColumn+1) ); + assert( p->aSample!=0 ); + assert( p->nSample>0 ); + assert( pBuilder->nRecValidnRecValid<(nEq-1) ){ + return SQLITE_NOTFOUND; + } + + /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() + ** below would return the same value. */ + if( nEq>p->nColumn ){ + *pnRow = 1; + return SQLITE_OK; + } + + aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity; + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk); + pBuilder->pRec = pRec; + if( rc!=SQLITE_OK ) return rc; + if( bOk==0 ) return SQLITE_NOTFOUND; + pBuilder->nRecValid = nEq; + + whereKeyStats(pParse, p, pRec, 0, a); + WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1])); + *pnRow = a[1]; + + return rc; +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +/* +** Estimate the number of rows that will be returned based on +** an IN constraint where the right-hand side of the IN operator +** is a list of values. Example: +** +** WHERE x IN (1,2,3,4) +** +** Write the estimated row count into *pnRow and return SQLITE_OK. +** If unable to make an estimate, leave *pnRow unchanged and return +** non-zero. +** +** This routine can fail if it is unable to load a collating sequence +** required for string comparison, or if unable to allocate memory +** for a UTF conversion required for comparison. The error is stored +** in the pParse structure. +*/ +static int whereInScanEst( + Parse *pParse, /* Parsing & code generating context */ + WhereLoopBuilder *pBuilder, + ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */ + tRowcnt *pnRow /* Write the revised row estimate here */ +){ + Index *p = pBuilder->pNew->u.btree.pIndex; + int nRecValid = pBuilder->nRecValid; + int rc = SQLITE_OK; /* Subfunction return code */ + tRowcnt nEst; /* Number of rows for a single term */ + tRowcnt nRowEst = 0; /* New estimate of the number of rows */ + int i; /* Loop counter */ + + assert( p->aSample!=0 ); + for(i=0; rc==SQLITE_OK && inExpr; i++){ + nEst = p->aiRowEst[0]; + rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst); + nRowEst += nEst; + pBuilder->nRecValid = nRecValid; + } + + if( rc==SQLITE_OK ){ + if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0]; + *pnRow = nRowEst; + WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst)); + } + assert( pBuilder->nRecValid==nRecValid ); + return rc; +} +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ + +/* +** Disable a term in the WHERE clause. Except, do not disable the term +** if it controls a LEFT OUTER JOIN and it did not originate in the ON +** or USING clause of that join. +** +** Consider the term t2.z='ok' in the following queries: +** +** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' +** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' +** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' +** +** The t2.z='ok' is disabled in the in (2) because it originates +** in the ON clause. The term is disabled in (3) because it is not part +** of a LEFT OUTER JOIN. In (1), the term is not disabled. +** +** Disabling a term causes that term to not be tested in the inner loop +** of the join. Disabling is an optimization. When terms are satisfied +** by indices, we disable them to prevent redundant tests in the inner +** loop. We would get the correct results if nothing were ever disabled, +** but joins might run a little slower. The trick is to disable as much +** as we can without disabling too much. If we disabled in (1), we'd get +** the wrong answer. See ticket #813. +*/ +static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ + if( pTerm + && (pTerm->wtFlags & TERM_CODED)==0 + && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) + && (pLevel->notReady & pTerm->prereqAll)==0 + ){ + pTerm->wtFlags |= TERM_CODED; + if( pTerm->iParent>=0 ){ + WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent]; + if( (--pOther->nChild)==0 ){ + disableTerm(pLevel, pOther); + } + } + } +} + +/* +** Code an OP_Affinity opcode to apply the column affinity string zAff +** to the n registers starting at base. +** +** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the +** beginning and end of zAff are ignored. If all entries in zAff are +** SQLITE_AFF_NONE, then no code gets generated. +** +** This routine makes its own copy of zAff so that the caller is free +** to modify zAff after this routine returns. +*/ +static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ + Vdbe *v = pParse->pVdbe; + if( zAff==0 ){ + assert( pParse->db->mallocFailed ); + return; + } + assert( v!=0 ); + + /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning + ** and end of the affinity string. + */ + while( n>0 && zAff[0]==SQLITE_AFF_NONE ){ + n--; + base++; + zAff++; + } + while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){ + n--; + } + + /* Code the OP_Affinity opcode if there is anything left to do. */ + if( n>0 ){ + sqlite3VdbeAddOp2(v, OP_Affinity, base, n); + sqlite3VdbeChangeP4(v, -1, zAff, n); + sqlite3ExprCacheAffinityChange(pParse, base, n); + } +} + + +/* +** Generate code for a single equality term of the WHERE clause. An equality +** term can be either X=expr or X IN (...). pTerm is the term to be +** coded. +** +** The current value for the constraint is left in register iReg. +** +** For a constraint of the form X=expr, the expression is evaluated and its +** result is left on the stack. For constraints of the form X IN (...) +** this routine sets up a loop that will iterate over all values of X. +*/ +static int codeEqualityTerm( + Parse *pParse, /* The parsing context */ + WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ + WhereLevel *pLevel, /* The level of the FROM clause we are working on */ + int iEq, /* Index of the equality term within this level */ + int bRev, /* True for reverse-order IN operations */ + int iTarget /* Attempt to leave results in this register */ +){ + Expr *pX = pTerm->pExpr; + Vdbe *v = pParse->pVdbe; + int iReg; /* Register holding results */ + + assert( iTarget>0 ); + if( pX->op==TK_EQ ){ + iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); + }else if( pX->op==TK_ISNULL ){ + iReg = iTarget; + sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); +#ifndef SQLITE_OMIT_SUBQUERY + }else{ + int eType; + int iTab; + struct InLoop *pIn; + WhereLoop *pLoop = pLevel->pWLoop; + + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 + && pLoop->u.btree.pIndex!=0 + && pLoop->u.btree.pIndex->aSortOrder[iEq] + ){ + testcase( iEq==0 ); + testcase( bRev ); + bRev = !bRev; + } + assert( pX->op==TK_IN ); + iReg = iTarget; + eType = sqlite3FindInIndex(pParse, pX, 0); + if( eType==IN_INDEX_INDEX_DESC ){ + testcase( bRev ); + bRev = !bRev; + } + iTab = pX->iTable; + sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); + assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); + pLoop->wsFlags |= WHERE_IN_ABLE; + if( pLevel->u.in.nIn==0 ){ + pLevel->addrNxt = sqlite3VdbeMakeLabel(v); + } + pLevel->u.in.nIn++; + pLevel->u.in.aInLoop = + sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, + sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); + pIn = pLevel->u.in.aInLoop; + if( pIn ){ + pIn += pLevel->u.in.nIn - 1; + pIn->iCur = iTab; + if( eType==IN_INDEX_ROWID ){ + pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg); + }else{ + pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg); + } + pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next; + sqlite3VdbeAddOp1(v, OP_IsNull, iReg); + }else{ + pLevel->u.in.nIn = 0; + } +#endif + } + disableTerm(pLevel, pTerm); + return iReg; +} + +/* +** Generate code that will evaluate all == and IN constraints for an +** index. +** +** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). +** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 +** The index has as many as three equality constraints, but in this +** example, the third "c" value is an inequality. So only two +** constraints are coded. This routine will generate code to evaluate +** a==5 and b IN (1,2,3). The current values for a and b will be stored +** in consecutive registers and the index of the first register is returned. +** +** In the example above nEq==2. But this subroutine works for any value +** of nEq including 0. If nEq==0, this routine is nearly a no-op. +** The only thing it does is allocate the pLevel->iMem memory cell and +** compute the affinity string. +** +** This routine always allocates at least one memory cell and returns +** the index of that memory cell. The code that +** calls this routine will use that memory cell to store the termination +** key value of the loop. If one or more IN operators appear, then +** this routine allocates an additional nEq memory cells for internal +** use. +** +** Before returning, *pzAff is set to point to a buffer containing a +** copy of the column affinity string of the index allocated using +** sqlite3DbMalloc(). Except, entries in the copy of the string associated +** with equality constraints that use NONE affinity are set to +** SQLITE_AFF_NONE. This is to deal with SQL such as the following: +** +** CREATE TABLE t1(a TEXT PRIMARY KEY, b); +** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; +** +** In the example above, the index on t1(a) has TEXT affinity. But since +** the right hand side of the equality constraint (t2.b) has NONE affinity, +** no conversion should be attempted before using a t2.b value as part of +** a key to search the index. Hence the first byte in the returned affinity +** string in this example would be set to SQLITE_AFF_NONE. +*/ +static int codeAllEqualityTerms( + Parse *pParse, /* Parsing context */ + WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ + int bRev, /* Reverse the order of IN operators */ + int nExtraReg, /* Number of extra registers to allocate */ + char **pzAff /* OUT: Set to point to affinity string */ +){ + int nEq; /* The number of == or IN constraints to code */ + Vdbe *v = pParse->pVdbe; /* The vm under construction */ + Index *pIdx; /* The index being used for this loop */ + WhereTerm *pTerm; /* A single constraint term */ + WhereLoop *pLoop; /* The WhereLoop object */ + int j; /* Loop counter */ + int regBase; /* Base register */ + int nReg; /* Number of registers to allocate */ + char *zAff; /* Affinity string to return */ + + /* This module is only called on query plans that use an index. */ + pLoop = pLevel->pWLoop; + assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); + nEq = pLoop->u.btree.nEq; + pIdx = pLoop->u.btree.pIndex; + assert( pIdx!=0 ); + + /* Figure out how many memory cells we will need then allocate them. + */ + regBase = pParse->nMem + 1; + nReg = pLoop->u.btree.nEq + nExtraReg; + pParse->nMem += nReg; + + zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx)); + if( !zAff ){ + pParse->db->mallocFailed = 1; + } + + /* Evaluate the equality constraints + */ + assert( zAff==0 || (int)strlen(zAff)>=nEq ); + for(j=0; jaLTerm[j]; + assert( pTerm!=0 ); + /* The following true for indices with redundant columns. + ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ + testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); + testcase( pTerm->wtFlags & TERM_VIRTUAL ); + r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); + if( r1!=regBase+j ){ + if( nReg==1 ){ + sqlite3ReleaseTempReg(pParse, regBase); + regBase = r1; + }else{ + sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); + } + } + testcase( pTerm->eOperator & WO_ISNULL ); + testcase( pTerm->eOperator & WO_IN ); + if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ + Expr *pRight = pTerm->pExpr->pRight; + sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk); + if( zAff ){ + if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){ + zAff[j] = SQLITE_AFF_NONE; + } + if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ + zAff[j] = SQLITE_AFF_NONE; + } + } + } + } + *pzAff = zAff; + return regBase; +} + +#ifndef SQLITE_OMIT_EXPLAIN +/* +** This routine is a helper for explainIndexRange() below +** +** pStr holds the text of an expression that we are building up one term +** at a time. This routine adds a new term to the end of the expression. +** Terms are separated by AND so add the "AND" text for second and subsequent +** terms only. +*/ +static void explainAppendTerm( + StrAccum *pStr, /* The text expression being built */ + int iTerm, /* Index of this term. First is zero */ + const char *zColumn, /* Name of the column */ + const char *zOp /* Name of the operator */ +){ + if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5); + sqlite3StrAccumAppend(pStr, zColumn, -1); + sqlite3StrAccumAppend(pStr, zOp, 1); + sqlite3StrAccumAppend(pStr, "?", 1); +} + +/* +** Argument pLevel describes a strategy for scanning table pTab. This +** function returns a pointer to a string buffer containing a description +** of the subset of table rows scanned by the strategy in the form of an +** SQL expression. Or, if all rows are scanned, NULL is returned. +** +** For example, if the query: +** +** SELECT * FROM t1 WHERE a=1 AND b>2; +** +** is run and there is an index on (a, b), then this function returns a +** string similar to: +** +** "a=? AND b>?" +** +** The returned pointer points to memory obtained from sqlite3DbMalloc(). +** It is the responsibility of the caller to free the buffer when it is +** no longer required. +*/ +static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){ + Index *pIndex = pLoop->u.btree.pIndex; + int nEq = pLoop->u.btree.nEq; + int i, j; + Column *aCol = pTab->aCol; + int *aiColumn = pIndex->aiColumn; + StrAccum txt; + + if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){ + return 0; + } + sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH); + txt.db = db; + sqlite3StrAccumAppend(&txt, " (", 2); + for(i=0; inColumn ) ? "rowid" : aCol[aiColumn[i]].zName; + explainAppendTerm(&txt, i, z, "="); + } + + j = i; + if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ + char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName; + explainAppendTerm(&txt, i++, z, ">"); + } + if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ + char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName; + explainAppendTerm(&txt, i, z, "<"); + } + sqlite3StrAccumAppend(&txt, ")", 1); + return sqlite3StrAccumFinish(&txt); +} + +/* +** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN +** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single +** record is added to the output to describe the table scan strategy in +** pLevel. +*/ +static void explainOneScan( + Parse *pParse, /* Parse context */ + SrcList *pTabList, /* Table list this loop refers to */ + WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ + int iLevel, /* Value for "level" column of output */ + int iFrom, /* Value for "from" column of output */ + u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ +){ + if( pParse->explain==2 ){ + struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; + Vdbe *v = pParse->pVdbe; /* VM being constructed */ + sqlite3 *db = pParse->db; /* Database handle */ + char *zMsg; /* Text to add to EQP output */ + int iId = pParse->iSelectId; /* Select id (left-most output column) */ + int isSearch; /* True for a SEARCH. False for SCAN. */ + WhereLoop *pLoop; /* The controlling WhereLoop object */ + u32 flags; /* Flags that describe this loop */ + + pLoop = pLevel->pWLoop; + flags = pLoop->wsFlags; + if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return; + + isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 + || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) + || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); + + zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN"); + if( pItem->pSelect ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId); + }else{ + zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName); + } + + if( pItem->zAlias ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias); + } + if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 + && ALWAYS(pLoop->u.btree.pIndex!=0) + ){ + char *zWhere = explainIndexRange(db, pLoop, pItem->pTab); + zMsg = sqlite3MAppendf(db, zMsg, + ((flags & WHERE_AUTO_INDEX) ? + "%s USING AUTOMATIC %sINDEX%.0s%s" : + "%s USING %sINDEX %s%s"), + zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""), + pLoop->u.btree.pIndex->zName, zWhere); + sqlite3DbFree(db, zWhere); + }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg); + + if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg); + }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid?)", zMsg); + }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){ + zMsg = sqlite3MAppendf(db, zMsg, "%s (rowidu.vtab.idxNum, pLoop->u.vtab.idxStr); + } +#endif + zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg); + sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC); + } +} +#else +# define explainOneScan(u,v,w,x,y,z) +#endif /* SQLITE_OMIT_EXPLAIN */ + + +/* +** Generate code for the start of the iLevel-th loop in the WHERE clause +** implementation described by pWInfo. +*/ +static Bitmask codeOneLoopStart( + WhereInfo *pWInfo, /* Complete information about the WHERE clause */ + int iLevel, /* Which level of pWInfo->a[] should be coded */ + Bitmask notReady /* Which tables are currently available */ +){ + int j, k; /* Loop counters */ + int iCur; /* The VDBE cursor for the table */ + int addrNxt; /* Where to jump to continue with the next IN case */ + int omitTable; /* True if we use the index only */ + int bRev; /* True if we need to scan in reverse order */ + WhereLevel *pLevel; /* The where level to be coded */ + WhereLoop *pLoop; /* The WhereLoop object being coded */ + WhereClause *pWC; /* Decomposition of the entire WHERE clause */ + WhereTerm *pTerm; /* A WHERE clause term */ + Parse *pParse; /* Parsing context */ + sqlite3 *db; /* Database connection */ + Vdbe *v; /* The prepared stmt under constructions */ + struct SrcList_item *pTabItem; /* FROM clause term being coded */ + int addrBrk; /* Jump here to break out of the loop */ + int addrCont; /* Jump here to continue with next cycle */ + int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ + int iReleaseReg = 0; /* Temp register to free before returning */ + + pParse = pWInfo->pParse; + v = pParse->pVdbe; + pWC = &pWInfo->sWC; + db = pParse->db; + pLevel = &pWInfo->a[iLevel]; + pLoop = pLevel->pWLoop; + pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; + iCur = pTabItem->iCursor; + pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur); + bRev = (pWInfo->revMask>>iLevel)&1; + omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 + && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0; + VdbeNoopComment((v, "Begin Join Loop %d", iLevel)); + + /* Create labels for the "break" and "continue" instructions + ** for the current loop. Jump to addrBrk to break out of a loop. + ** Jump to cont to go immediately to the next iteration of the + ** loop. + ** + ** When there is an IN operator, we also have a "addrNxt" label that + ** means to continue with the next IN value combination. When + ** there are no IN operators in the constraints, the "addrNxt" label + ** is the same as "addrBrk". + */ + addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); + addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); + + /* If this is the right table of a LEFT OUTER JOIN, allocate and + ** initialize a memory cell that records if this table matches any + ** row of the left table of the join. + */ + if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){ + pLevel->iLeftJoin = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); + VdbeComment((v, "init LEFT JOIN no-match flag")); + } + + /* Special case of a FROM clause subquery implemented as a co-routine */ + if( pTabItem->viaCoroutine ){ + int regYield = pTabItem->regReturn; + sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield); + pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield); + VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName)); + sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk); + pLevel->op = OP_Goto; + }else + +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ + /* Case 1: The table is a virtual-table. Use the VFilter and VNext + ** to access the data. + */ + int iReg; /* P3 Value for OP_VFilter */ + int addrNotFound; + int nConstraint = pLoop->nLTerm; + + sqlite3ExprCachePush(pParse); + iReg = sqlite3GetTempRange(pParse, nConstraint+2); + addrNotFound = pLevel->addrBrk; + for(j=0; jaLTerm[j]; + if( pTerm==0 ) continue; + if( pTerm->eOperator & WO_IN ){ + codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); + addrNotFound = pLevel->addrNxt; + }else{ + sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget); + } + } + sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); + sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); + sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, + pLoop->u.vtab.idxStr, + pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC); + pLoop->u.vtab.needFree = 0; + for(j=0; ju.vtab.omitMask>>j)&1 ){ + disableTerm(pLevel, pLoop->aLTerm[j]); + } + } + pLevel->op = OP_VNext; + pLevel->p1 = iCur; + pLevel->p2 = sqlite3VdbeCurrentAddr(v); + sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); + sqlite3ExprCachePop(pParse, 1); + }else +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + + if( (pLoop->wsFlags & WHERE_IPK)!=0 + && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 + ){ + /* Case 2: We can directly reference a single row using an + ** equality comparison against the ROWID field. Or + ** we reference multiple rows using a "rowid IN (...)" + ** construct. + */ + assert( pLoop->u.btree.nEq==1 ); + iReleaseReg = sqlite3GetTempReg(pParse); + pTerm = pLoop->aLTerm[0]; + assert( pTerm!=0 ); + assert( pTerm->pExpr!=0 ); + assert( omitTable==0 ); + testcase( pTerm->wtFlags & TERM_VIRTUAL ); + iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); + addrNxt = pLevel->addrNxt; + sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg); + sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); + sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); + VdbeComment((v, "pk")); + pLevel->op = OP_Noop; + }else if( (pLoop->wsFlags & WHERE_IPK)!=0 + && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 + ){ + /* Case 3: We have an inequality comparison against the ROWID field. + */ + int testOp = OP_Noop; + int start; + int memEndValue = 0; + WhereTerm *pStart, *pEnd; + + assert( omitTable==0 ); + j = 0; + pStart = pEnd = 0; + if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; + if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; + assert( pStart!=0 || pEnd!=0 ); + if( bRev ){ + pTerm = pStart; + pStart = pEnd; + pEnd = pTerm; + } + if( pStart ){ + Expr *pX; /* The expression that defines the start bound */ + int r1, rTemp; /* Registers for holding the start boundary */ + + /* The following constant maps TK_xx codes into corresponding + ** seek opcodes. It depends on a particular ordering of TK_xx + */ + const u8 aMoveOp[] = { + /* TK_GT */ OP_SeekGt, + /* TK_LE */ OP_SeekLe, + /* TK_LT */ OP_SeekLt, + /* TK_GE */ OP_SeekGe + }; + assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ + assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ + assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ + + assert( (pStart->wtFlags & TERM_VNULL)==0 ); + testcase( pStart->wtFlags & TERM_VIRTUAL ); + pX = pStart->pExpr; + assert( pX!=0 ); + testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ + r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); + sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1); + VdbeComment((v, "pk")); + sqlite3ExprCacheAffinityChange(pParse, r1, 1); + sqlite3ReleaseTempReg(pParse, rTemp); + disableTerm(pLevel, pStart); + }else{ + sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); + } + if( pEnd ){ + Expr *pX; + pX = pEnd->pExpr; + assert( pX!=0 ); + assert( (pEnd->wtFlags & TERM_VNULL)==0 ); + testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ + testcase( pEnd->wtFlags & TERM_VIRTUAL ); + memEndValue = ++pParse->nMem; + sqlite3ExprCode(pParse, pX->pRight, memEndValue); + if( pX->op==TK_LT || pX->op==TK_GT ){ + testOp = bRev ? OP_Le : OP_Ge; + }else{ + testOp = bRev ? OP_Lt : OP_Gt; + } + disableTerm(pLevel, pEnd); + } + start = sqlite3VdbeCurrentAddr(v); + pLevel->op = bRev ? OP_Prev : OP_Next; + pLevel->p1 = iCur; + pLevel->p2 = start; + assert( pLevel->p5==0 ); + if( testOp!=OP_Noop ){ + iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); + sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); + sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); + sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); + } + }else if( pLoop->wsFlags & WHERE_INDEXED ){ + /* Case 4: A scan using an index. + ** + ** The WHERE clause may contain zero or more equality + ** terms ("==" or "IN" operators) that refer to the N + ** left-most columns of the index. It may also contain + ** inequality constraints (>, <, >= or <=) on the indexed + ** column that immediately follows the N equalities. Only + ** the right-most column can be an inequality - the rest must + ** use the "==" and "IN" operators. For example, if the + ** index is on (x,y,z), then the following clauses are all + ** optimized: + ** + ** x=5 + ** x=5 AND y=10 + ** x=5 AND y<10 + ** x=5 AND y>5 AND y<10 + ** x=5 AND y=5 AND z<=10 + ** + ** The z<10 term of the following cannot be used, only + ** the x=5 term: + ** + ** x=5 AND z<10 + ** + ** N may be zero if there are inequality constraints. + ** If there are no inequality constraints, then N is at + ** least one. + ** + ** This case is also used when there are no WHERE clause + ** constraints but an index is selected anyway, in order + ** to force the output order to conform to an ORDER BY. + */ + static const u8 aStartOp[] = { + 0, + 0, + OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ + OP_Last, /* 3: (!start_constraints && startEq && bRev) */ + OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */ + OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */ + OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */ + OP_SeekLe /* 7: (start_constraints && startEq && bRev) */ + }; + static const u8 aEndOp[] = { + OP_Noop, /* 0: (!end_constraints) */ + OP_IdxGE, /* 1: (end_constraints && !bRev) */ + OP_IdxLT /* 2: (end_constraints && bRev) */ + }; + int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ + int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */ + int regBase; /* Base register holding constraint values */ + int r1; /* Temp register */ + WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ + WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ + int startEq; /* True if range start uses ==, >= or <= */ + int endEq; /* True if range end uses ==, >= or <= */ + int start_constraints; /* Start of range is constrained */ + int nConstraint; /* Number of constraint terms */ + Index *pIdx; /* The index we will be using */ + int iIdxCur; /* The VDBE cursor for the index */ + int nExtraReg = 0; /* Number of extra registers needed */ + int op; /* Instruction opcode */ + char *zStartAff; /* Affinity for start of range constraint */ + char *zEndAff; /* Affinity for end of range constraint */ + + pIdx = pLoop->u.btree.pIndex; + iIdxCur = pLevel->iIdxCur; + + /* If this loop satisfies a sort order (pOrderBy) request that + ** was passed to this function to implement a "SELECT min(x) ..." + ** query, then the caller will only allow the loop to run for + ** a single iteration. This means that the first row returned + ** should not have a NULL value stored in 'x'. If column 'x' is + ** the first one after the nEq equality constraints in the index, + ** this requires some special handling. + */ + if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 + && (pWInfo->bOBSat!=0) + && (pIdx->nColumn>nEq) + ){ + /* assert( pOrderBy->nExpr==1 ); */ + /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */ + isMinQuery = 1; + nExtraReg = 1; + } + + /* Find any inequality constraint terms for the start and end + ** of the range. + */ + j = nEq; + if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ + pRangeStart = pLoop->aLTerm[j++]; + nExtraReg = 1; + } + if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ + pRangeEnd = pLoop->aLTerm[j++]; + nExtraReg = 1; + } + + /* Generate code to evaluate all constraint terms using == or IN + ** and store the values of those terms in an array of registers + ** starting at regBase. + */ + regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); + zEndAff = sqlite3DbStrDup(db, zStartAff); + addrNxt = pLevel->addrNxt; + + /* If we are doing a reverse order scan on an ascending index, or + ** a forward order scan on a descending index, interchange the + ** start and end terms (pRangeStart and pRangeEnd). + */ + if( (nEqnColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) + || (bRev && pIdx->nColumn==nEq) + ){ + SWAP(WhereTerm *, pRangeEnd, pRangeStart); + } + + testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); + testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); + testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); + testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); + startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); + endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); + start_constraints = pRangeStart || nEq>0; + + /* Seek the index cursor to the start of the range. */ + nConstraint = nEq; + if( pRangeStart ){ + Expr *pRight = pRangeStart->pExpr->pRight; + sqlite3ExprCode(pParse, pRight, regBase+nEq); + if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){ + sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt); + } + if( zStartAff ){ + if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){ + /* Since the comparison is to be performed with no conversions + ** applied to the operands, set the affinity to apply to pRight to + ** SQLITE_AFF_NONE. */ + zStartAff[nEq] = SQLITE_AFF_NONE; + } + if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){ + zStartAff[nEq] = SQLITE_AFF_NONE; + } + } + nConstraint++; + testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); + }else if( isMinQuery ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); + nConstraint++; + startEq = 0; + start_constraints = 1; + } + codeApplyAffinity(pParse, regBase, nConstraint, zStartAff); + op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; + assert( op!=0 ); + testcase( op==OP_Rewind ); + testcase( op==OP_Last ); + testcase( op==OP_SeekGt ); + testcase( op==OP_SeekGe ); + testcase( op==OP_SeekLe ); + testcase( op==OP_SeekLt ); + sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); + + /* Load the value for the inequality constraint at the end of the + ** range (if any). + */ + nConstraint = nEq; + if( pRangeEnd ){ + Expr *pRight = pRangeEnd->pExpr->pRight; + sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); + sqlite3ExprCode(pParse, pRight, regBase+nEq); + if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){ + sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt); + } + if( zEndAff ){ + if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){ + /* Since the comparison is to be performed with no conversions + ** applied to the operands, set the affinity to apply to pRight to + ** SQLITE_AFF_NONE. */ + zEndAff[nEq] = SQLITE_AFF_NONE; + } + if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){ + zEndAff[nEq] = SQLITE_AFF_NONE; + } + } + codeApplyAffinity(pParse, regBase, nEq+1, zEndAff); + nConstraint++; + testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); + } + sqlite3DbFree(db, zStartAff); + sqlite3DbFree(db, zEndAff); + + /* Top of the loop body */ + pLevel->p2 = sqlite3VdbeCurrentAddr(v); + + /* Check if the index cursor is past the end of the range. */ + op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)]; + testcase( op==OP_Noop ); + testcase( op==OP_IdxGE ); + testcase( op==OP_IdxLT ); + if( op!=OP_Noop ){ + sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); + sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0); + } + + /* If there are inequality constraints, check that the value + ** of the table column that the inequality contrains is not NULL. + ** If it is, jump to the next iteration of the loop. + */ + r1 = sqlite3GetTempReg(pParse); + testcase( pLoop->wsFlags & WHERE_BTM_LIMIT ); + testcase( pLoop->wsFlags & WHERE_TOP_LIMIT ); + if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){ + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1); + sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont); + } + sqlite3ReleaseTempReg(pParse, r1); + + /* Seek the table cursor, if required */ + disableTerm(pLevel, pRangeStart); + disableTerm(pLevel, pRangeEnd); + if( !omitTable ){ + iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); + sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); + sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */ + } + + /* Record the instruction used to terminate the loop. Disable + ** WHERE clause terms made redundant by the index range scan. + */ + if( pLoop->wsFlags & WHERE_ONEROW ){ + pLevel->op = OP_Noop; + }else if( bRev ){ + pLevel->op = OP_Prev; + }else{ + pLevel->op = OP_Next; + } + pLevel->p1 = iIdxCur; + if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ + pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; + }else{ + assert( pLevel->p5==0 ); + } + }else + +#ifndef SQLITE_OMIT_OR_OPTIMIZATION + if( pLoop->wsFlags & WHERE_MULTI_OR ){ + /* Case 5: Two or more separately indexed terms connected by OR + ** + ** Example: + ** + ** CREATE TABLE t1(a,b,c,d); + ** CREATE INDEX i1 ON t1(a); + ** CREATE INDEX i2 ON t1(b); + ** CREATE INDEX i3 ON t1(c); + ** + ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) + ** + ** In the example, there are three indexed terms connected by OR. + ** The top of the loop looks like this: + ** + ** Null 1 # Zero the rowset in reg 1 + ** + ** Then, for each indexed term, the following. The arguments to + ** RowSetTest are such that the rowid of the current row is inserted + ** into the RowSet. If it is already present, control skips the + ** Gosub opcode and jumps straight to the code generated by WhereEnd(). + ** + ** sqlite3WhereBegin() + ** RowSetTest # Insert rowid into rowset + ** Gosub 2 A + ** sqlite3WhereEnd() + ** + ** Following the above, code to terminate the loop. Label A, the target + ** of the Gosub above, jumps to the instruction right after the Goto. + ** + ** Null 1 # Zero the rowset in reg 1 + ** Goto B # The loop is finished. + ** + ** A: # Return data, whatever. + ** + ** Return 2 # Jump back to the Gosub + ** + ** B: + ** + */ + WhereClause *pOrWc; /* The OR-clause broken out into subterms */ + SrcList *pOrTab; /* Shortened table list or OR-clause generation */ + Index *pCov = 0; /* Potential covering index (or NULL) */ + int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ + + int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ + int regRowset = 0; /* Register for RowSet object */ + int regRowid = 0; /* Register holding rowid */ + int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ + int iRetInit; /* Address of regReturn init */ + int untestedTerms = 0; /* Some terms not completely tested */ + int ii; /* Loop counter */ + Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ + + pTerm = pLoop->aLTerm[0]; + assert( pTerm!=0 ); + assert( pTerm->eOperator & WO_OR ); + assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); + pOrWc = &pTerm->u.pOrInfo->wc; + pLevel->op = OP_Return; + pLevel->p1 = regReturn; + + /* Set up a new SrcList in pOrTab containing the table being scanned + ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. + ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). + */ + if( pWInfo->nLevel>1 ){ + int nNotReady; /* The number of notReady tables */ + struct SrcList_item *origSrc; /* Original list of tables */ + nNotReady = pWInfo->nLevel - iLevel - 1; + pOrTab = sqlite3StackAllocRaw(db, + sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); + if( pOrTab==0 ) return notReady; + pOrTab->nAlloc = (u8)(nNotReady + 1); + pOrTab->nSrc = pOrTab->nAlloc; + memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); + origSrc = pWInfo->pTabList->a; + for(k=1; k<=nNotReady; k++){ + memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); + } + }else{ + pOrTab = pWInfo->pTabList; + } + + /* Initialize the rowset register to contain NULL. An SQL NULL is + ** equivalent to an empty rowset. + ** + ** Also initialize regReturn to contain the address of the instruction + ** immediately following the OP_Return at the bottom of the loop. This + ** is required in a few obscure LEFT JOIN cases where control jumps + ** over the top of the loop into the body of it. In this case the + ** correct response for the end-of-loop code (the OP_Return) is to + ** fall through to the next instruction, just as an OP_Next does if + ** called on an uninitialized cursor. + */ + if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ + regRowset = ++pParse->nMem; + regRowid = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); + } + iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); + + /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y + ** Then for every term xN, evaluate as the subexpression: xN AND z + ** That way, terms in y that are factored into the disjunction will + ** be picked up by the recursive calls to sqlite3WhereBegin() below. + ** + ** Actually, each subexpression is converted to "xN AND w" where w is + ** the "interesting" terms of z - terms that did not originate in the + ** ON or USING clause of a LEFT JOIN, and terms that are usable as + ** indices. + ** + ** This optimization also only applies if the (x1 OR x2 OR ...) term + ** is not contained in the ON clause of a LEFT JOIN. + ** See ticket http://www.sqlite.org/src/info/f2369304e4 + */ + if( pWC->nTerm>1 ){ + int iTerm; + for(iTerm=0; iTermnTerm; iTerm++){ + Expr *pExpr = pWC->a[iTerm].pExpr; + if( &pWC->a[iTerm] == pTerm ) continue; + if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; + if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue; + if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; + pExpr = sqlite3ExprDup(db, pExpr, 0); + pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); + } + if( pAndExpr ){ + pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0); + } + } + + for(ii=0; iinTerm; ii++){ + WhereTerm *pOrTerm = &pOrWc->a[ii]; + if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ + WhereInfo *pSubWInfo; /* Info for single OR-term scan */ + Expr *pOrExpr = pOrTerm->pExpr; + if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ + pAndExpr->pLeft = pOrExpr; + pOrExpr = pAndExpr; + } + /* Loop through table entries that match term pOrTerm. */ + pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, + WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY | + WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur); + assert( pSubWInfo || pParse->nErr || db->mallocFailed ); + if( pSubWInfo ){ + WhereLoop *pSubLoop; + explainOneScan( + pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 + ); + if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ + int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); + int r; + r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, + regRowid, 0); + sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, + sqlite3VdbeCurrentAddr(v)+2, r, iSet); + } + sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); + + /* The pSubWInfo->untestedTerms flag means that this OR term + ** contained one or more AND term from a notReady table. The + ** terms from the notReady table could not be tested and will + ** need to be tested later. + */ + if( pSubWInfo->untestedTerms ) untestedTerms = 1; + + /* If all of the OR-connected terms are optimized using the same + ** index, and the index is opened using the same cursor number + ** by each call to sqlite3WhereBegin() made by this loop, it may + ** be possible to use that index as a covering index. + ** + ** If the call to sqlite3WhereBegin() above resulted in a scan that + ** uses an index, and this is either the first OR-connected term + ** processed or the index is the same as that used by all previous + ** terms, set pCov to the candidate covering index. Otherwise, set + ** pCov to NULL to indicate that no candidate covering index will + ** be available. + */ + pSubLoop = pSubWInfo->a[0].pWLoop; + assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); + if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 + && (ii==0 || pSubLoop->u.btree.pIndex==pCov) + ){ + assert( pSubWInfo->a[0].iIdxCur==iCovCur ); + pCov = pSubLoop->u.btree.pIndex; + }else{ + pCov = 0; + } + + /* Finish the loop through table entries that match term pOrTerm. */ + sqlite3WhereEnd(pSubWInfo); + } + } + } + pLevel->u.pCovidx = pCov; + if( pCov ) pLevel->iIdxCur = iCovCur; + if( pAndExpr ){ + pAndExpr->pLeft = 0; + sqlite3ExprDelete(db, pAndExpr); + } + sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); + sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk); + sqlite3VdbeResolveLabel(v, iLoopBody); + + if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); + if( !untestedTerms ) disableTerm(pLevel, pTerm); + }else +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */ + + { + /* Case 6: There is no usable index. We must do a complete + ** scan of the entire table. + */ + static const u8 aStep[] = { OP_Next, OP_Prev }; + static const u8 aStart[] = { OP_Rewind, OP_Last }; + assert( bRev==0 || bRev==1 ); + pLevel->op = aStep[bRev]; + pLevel->p1 = iCur; + pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); + pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; + } + + /* Insert code to test every subexpression that can be completely + ** computed using the current set of tables. + */ + for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ + Expr *pE; + testcase( pTerm->wtFlags & TERM_VIRTUAL ); + testcase( pTerm->wtFlags & TERM_CODED ); + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; + if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ + testcase( pWInfo->untestedTerms==0 + && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ); + pWInfo->untestedTerms = 1; + continue; + } + pE = pTerm->pExpr; + assert( pE!=0 ); + if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ + continue; + } + sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); + pTerm->wtFlags |= TERM_CODED; + } + + /* Insert code to test for implied constraints based on transitivity + ** of the "==" operator. + ** + ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" + ** and we are coding the t1 loop and the t2 loop has not yet coded, + ** then we cannot use the "t1.a=t2.b" constraint, but we can code + ** the implied "t1.a=123" constraint. + */ + for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ + Expr *pE, *pEAlt; + WhereTerm *pAlt; + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; + if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue; + if( pTerm->leftCursor!=iCur ) continue; + if( pLevel->iLeftJoin ) continue; + pE = pTerm->pExpr; + assert( !ExprHasProperty(pE, EP_FromJoin) ); + assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); + pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0); + if( pAlt==0 ) continue; + if( pAlt->wtFlags & (TERM_CODED) ) continue; + testcase( pAlt->eOperator & WO_EQ ); + testcase( pAlt->eOperator & WO_IN ); + VdbeNoopComment((v, "begin transitive constraint")); + pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt)); + if( pEAlt ){ + *pEAlt = *pAlt->pExpr; + pEAlt->pLeft = pE->pLeft; + sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL); + sqlite3StackFree(db, pEAlt); + } + } + + /* For a LEFT OUTER JOIN, generate code that will record the fact that + ** at least one row of the right table has matched the left table. + */ + if( pLevel->iLeftJoin ){ + pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); + VdbeComment((v, "record LEFT JOIN hit")); + sqlite3ExprCacheClear(pParse); + for(pTerm=pWC->a, j=0; jnTerm; j++, pTerm++){ + testcase( pTerm->wtFlags & TERM_VIRTUAL ); + testcase( pTerm->wtFlags & TERM_CODED ); + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; + if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ + assert( pWInfo->untestedTerms ); + continue; + } + assert( pTerm->pExpr ); + sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); + pTerm->wtFlags |= TERM_CODED; + } + } + sqlite3ReleaseTempReg(pParse, iReleaseReg); + + return pLevel->notReady; +} + +#ifdef WHERETRACE_ENABLED +/* +** Print a WhereLoop object for debugging purposes +*/ +static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){ + int nb = 1+(pTabList->nSrc+7)/8; + struct SrcList_item *pItem = pTabList->a + p->iTab; + Table *pTab = pItem->pTab; + sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, + p->iTab, nb, p->maskSelf, nb, p->prereq); + sqlite3DebugPrintf(" %12s", + pItem->zAlias ? pItem->zAlias : pTab->zName); + if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ + if( p->u.btree.pIndex ){ + const char *zName = p->u.btree.pIndex->zName; + if( zName==0 ) zName = "ipk"; + if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ + int i = sqlite3Strlen30(zName) - 1; + while( zName[i]!='_' ) i--; + zName += i; + } + sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); + }else{ + sqlite3DebugPrintf("%20s",""); + } + }else{ + char *z; + if( p->u.vtab.idxStr ){ + z = sqlite3_mprintf("(%d,\"%s\",%x)", + p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); + }else{ + z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); + } + sqlite3DebugPrintf(" %-19s", z); + sqlite3_free(z); + } + sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm); + sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); +} +#endif + +/* +** Convert bulk memory into a valid WhereLoop that can be passed +** to whereLoopClear harmlessly. +*/ +static void whereLoopInit(WhereLoop *p){ + p->aLTerm = p->aLTermSpace; + p->nLTerm = 0; + p->nLSlot = ArraySize(p->aLTermSpace); + p->wsFlags = 0; +} + +/* +** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. +*/ +static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ + if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ + if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ + sqlite3_free(p->u.vtab.idxStr); + p->u.vtab.needFree = 0; + p->u.vtab.idxStr = 0; + }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ + sqlite3DbFree(db, p->u.btree.pIndex->zColAff); + sqlite3DbFree(db, p->u.btree.pIndex); + p->u.btree.pIndex = 0; + } + } +} + +/* +** Deallocate internal memory used by a WhereLoop object +*/ +static void whereLoopClear(sqlite3 *db, WhereLoop *p){ + if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); + whereLoopClearUnion(db, p); + whereLoopInit(p); +} + +/* +** Increase the memory allocation for pLoop->aLTerm[] to be at least n. +*/ +static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ + WhereTerm **paNew; + if( p->nLSlot>=n ) return SQLITE_OK; + n = (n+7)&~7; + paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n); + if( paNew==0 ) return SQLITE_NOMEM; + memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); + if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); + p->aLTerm = paNew; + p->nLSlot = n; + return SQLITE_OK; +} + +/* +** Transfer content from the second pLoop into the first. +*/ +static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ + whereLoopClearUnion(db, pTo); + if( whereLoopResize(db, pTo, pFrom->nLTerm) ){ + memset(&pTo->u, 0, sizeof(pTo->u)); + return SQLITE_NOMEM; + } + memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); + memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); + if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ + pFrom->u.vtab.needFree = 0; + }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ + pFrom->u.btree.pIndex = 0; + } + return SQLITE_OK; +} + +/* +** Delete a WhereLoop object +*/ +static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ + whereLoopClear(db, p); + sqlite3DbFree(db, p); +} + +/* +** Free a WhereInfo structure +*/ +static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ + if( ALWAYS(pWInfo) ){ + whereClauseClear(&pWInfo->sWC); + while( pWInfo->pLoops ){ + WhereLoop *p = pWInfo->pLoops; + pWInfo->pLoops = p->pNextLoop; + whereLoopDelete(db, p); + } + sqlite3DbFree(db, pWInfo); + } +} + +/* +** Insert or replace a WhereLoop entry using the template supplied. +** +** An existing WhereLoop entry might be overwritten if the new template +** is better and has fewer dependencies. Or the template will be ignored +** and no insert will occur if an existing WhereLoop is faster and has +** fewer dependencies than the template. Otherwise a new WhereLoop is +** added based on the template. +** +** If pBuilder->pOrSet is not NULL then we only care about only the +** prerequisites and rRun and nOut costs of the N best loops. That +** information is gathered in the pBuilder->pOrSet object. This special +** processing mode is used only for OR clause processing. +** +** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we +** still might overwrite similar loops with the new template if the +** template is better. Loops may be overwritten if the following +** conditions are met: +** +** (1) They have the same iTab. +** (2) They have the same iSortIdx. +** (3) The template has same or fewer dependencies than the current loop +** (4) The template has the same or lower cost than the current loop +** (5) The template uses more terms of the same index but has no additional +** dependencies +*/ +static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ + WhereLoop **ppPrev, *p, *pNext = 0; + WhereInfo *pWInfo = pBuilder->pWInfo; + sqlite3 *db = pWInfo->pParse->db; + + /* If pBuilder->pOrSet is defined, then only keep track of the costs + ** and prereqs. + */ + if( pBuilder->pOrSet!=0 ){ +#if WHERETRACE_ENABLED + u16 n = pBuilder->pOrSet->n; + int x = +#endif + whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, + pTemplate->nOut); +#if WHERETRACE_ENABLED + if( sqlite3WhereTrace & 0x8 ){ + sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); + whereLoopPrint(pTemplate, pWInfo->pTabList); + } +#endif + return SQLITE_OK; + } + + /* Search for an existing WhereLoop to overwrite, or which takes + ** priority over pTemplate. + */ + for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){ + if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){ + /* If either the iTab or iSortIdx values for two WhereLoop are different + ** then those WhereLoops need to be considered separately. Neither is + ** a candidate to replace the other. */ + continue; + } + /* In the current implementation, the rSetup value is either zero + ** or the cost of building an automatic index (NlogN) and the NlogN + ** is the same for compatible WhereLoops. */ + assert( p->rSetup==0 || pTemplate->rSetup==0 + || p->rSetup==pTemplate->rSetup ); + + /* whereLoopAddBtree() always generates and inserts the automatic index + ** case first. Hence compatible candidate WhereLoops never have a larger + ** rSetup. Call this SETUP-INVARIANT */ + assert( p->rSetup>=pTemplate->rSetup ); + + if( (p->prereq & pTemplate->prereq)==p->prereq + && p->rSetup<=pTemplate->rSetup + && p->rRun<=pTemplate->rRun + && p->nOut<=pTemplate->nOut + ){ + /* This branch taken when p is equal or better than pTemplate in + ** all of (1) dependencies (2) setup-cost, (3) run-cost, and + ** (4) number of output rows. */ + assert( p->rSetup==pTemplate->rSetup ); + if( p->prereq==pTemplate->prereq + && p->nLTermnLTerm + && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0 + && (p->u.btree.pIndex==pTemplate->u.btree.pIndex + || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm) + ){ + /* Overwrite an existing WhereLoop with an similar one that uses + ** more terms of the index */ + pNext = p->pNextLoop; + break; + }else{ + /* pTemplate is not helpful. + ** Return without changing or adding anything */ + goto whereLoopInsert_noop; + } + } + if( (p->prereq & pTemplate->prereq)==pTemplate->prereq + && p->rRun>=pTemplate->rRun + && p->nOut>=pTemplate->nOut + ){ + /* Overwrite an existing WhereLoop with a better one: one that is + ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost + ** or (4) number of output rows, and is no worse in any of those + ** categories. */ + assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */ + pNext = p->pNextLoop; + break; + } + } + + /* If we reach this point it means that either p[] should be overwritten + ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new + ** WhereLoop and insert it. + */ +#if WHERETRACE_ENABLED + if( sqlite3WhereTrace & 0x8 ){ + if( p!=0 ){ + sqlite3DebugPrintf("ins-del: "); + whereLoopPrint(p, pWInfo->pTabList); + } + sqlite3DebugPrintf("ins-new: "); + whereLoopPrint(pTemplate, pWInfo->pTabList); + } +#endif + if( p==0 ){ + p = sqlite3DbMallocRaw(db, sizeof(WhereLoop)); + if( p==0 ) return SQLITE_NOMEM; + whereLoopInit(p); + } + whereLoopXfer(db, p, pTemplate); + p->pNextLoop = pNext; + *ppPrev = p; + if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ + Index *pIndex = p->u.btree.pIndex; + if( pIndex && pIndex->tnum==0 ){ + p->u.btree.pIndex = 0; + } + } + return SQLITE_OK; + + /* Jump here if the insert is a no-op */ +whereLoopInsert_noop: +#if WHERETRACE_ENABLED + if( sqlite3WhereTrace & 0x8 ){ + sqlite3DebugPrintf("ins-noop: "); + whereLoopPrint(pTemplate, pWInfo->pTabList); + } +#endif + return SQLITE_OK; +} + +/* +** Adjust the WhereLoop.nOut value downward to account for terms of the +** WHERE clause that reference the loop but which are not used by an +** index. +** +** In the current implementation, the first extra WHERE clause term reduces +** the number of output rows by a factor of 10 and each additional term +** reduces the number of output rows by sqrt(2). +*/ +static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){ + WhereTerm *pTerm, *pX; + Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); + int i, j; + + if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){ + return; + } + for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ + if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; + if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; + if( (pTerm->prereqAll & notAllowed)!=0 ) continue; + for(j=pLoop->nLTerm-1; j>=0; j--){ + pX = pLoop->aLTerm[j]; + if( pX==pTerm ) break; + if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; + } + if( j<0 ) pLoop->nOut += pTerm->truthProb; + } +} + +/* +** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex. +** Try to match one more. +** +** If pProbe->tnum==0, that means pIndex is a fake index used for the +** INTEGER PRIMARY KEY. +*/ +static int whereLoopAddBtreeIndex( + WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ + struct SrcList_item *pSrc, /* FROM clause term being analyzed */ + Index *pProbe, /* An index on pSrc */ + LogEst nInMul /* log(Number of iterations due to IN) */ +){ + WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ + Parse *pParse = pWInfo->pParse; /* Parsing context */ + sqlite3 *db = pParse->db; /* Database connection malloc context */ + WhereLoop *pNew; /* Template WhereLoop under construction */ + WhereTerm *pTerm; /* A WhereTerm under consideration */ + int opMask; /* Valid operators for constraints */ + WhereScan scan; /* Iterator for WHERE terms */ + Bitmask saved_prereq; /* Original value of pNew->prereq */ + u16 saved_nLTerm; /* Original value of pNew->nLTerm */ + int saved_nEq; /* Original value of pNew->u.btree.nEq */ + u32 saved_wsFlags; /* Original value of pNew->wsFlags */ + LogEst saved_nOut; /* Original value of pNew->nOut */ + int iCol; /* Index of the column in the table */ + int rc = SQLITE_OK; /* Return code */ + LogEst nRowEst; /* Estimated index selectivity */ + LogEst rLogSize; /* Logarithm of table size */ + WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ + + pNew = pBuilder->pNew; + if( db->mallocFailed ) return SQLITE_NOMEM; + + assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); + assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); + if( pNew->wsFlags & WHERE_BTM_LIMIT ){ + opMask = WO_LT|WO_LE; + }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){ + opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE; + }else{ + opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE; + } + if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); + + assert( pNew->u.btree.nEq<=pProbe->nColumn ); + if( pNew->u.btree.nEq < pProbe->nColumn ){ + iCol = pProbe->aiColumn[pNew->u.btree.nEq]; + nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]); + if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1; + }else{ + iCol = -1; + nRowEst = 0; + } + pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol, + opMask, pProbe); + saved_nEq = pNew->u.btree.nEq; + saved_nLTerm = pNew->nLTerm; + saved_wsFlags = pNew->wsFlags; + saved_prereq = pNew->prereq; + saved_nOut = pNew->nOut; + pNew->rSetup = 0; + rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0])); + for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ + int nIn = 0; +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + int nRecValid = pBuilder->nRecValid; +#endif + if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) + && (iCol<0 || pSrc->pTab->aCol[iCol].notNull) + ){ + continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ + } + if( pTerm->prereqRight & pNew->maskSelf ) continue; + + assert( pNew->nOut==saved_nOut ); + + pNew->wsFlags = saved_wsFlags; + pNew->u.btree.nEq = saved_nEq; + pNew->nLTerm = saved_nLTerm; + if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ + pNew->aLTerm[pNew->nLTerm++] = pTerm; + pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; + pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */ + if( pTerm->eOperator & WO_IN ){ + Expr *pExpr = pTerm->pExpr; + pNew->wsFlags |= WHERE_COLUMN_IN; + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ + nIn = 46; assert( 46==sqlite3LogEst(25) ); + }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ + /* "x IN (value, value, ...)" */ + nIn = sqlite3LogEst(pExpr->x.pList->nExpr); + } + pNew->rRun += nIn; + pNew->u.btree.nEq++; + pNew->nOut = nRowEst + nInMul + nIn; + }else if( pTerm->eOperator & (WO_EQ) ){ + assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0 + || nInMul==0 ); + pNew->wsFlags |= WHERE_COLUMN_EQ; + if( iCol<0 + || (pProbe->onError!=OE_None && nInMul==0 + && pNew->u.btree.nEq==pProbe->nColumn-1) + ){ + assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 ); + pNew->wsFlags |= WHERE_ONEROW; + } + pNew->u.btree.nEq++; + pNew->nOut = nRowEst + nInMul; + }else if( pTerm->eOperator & (WO_ISNULL) ){ + pNew->wsFlags |= WHERE_COLUMN_NULL; + pNew->u.btree.nEq++; + /* TUNING: IS NULL selects 2 rows */ + nIn = 10; assert( 10==sqlite3LogEst(2) ); + pNew->nOut = nRowEst + nInMul + nIn; + }else if( pTerm->eOperator & (WO_GT|WO_GE) ){ + testcase( pTerm->eOperator & WO_GT ); + testcase( pTerm->eOperator & WO_GE ); + pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; + pBtm = pTerm; + pTop = 0; + }else{ + assert( pTerm->eOperator & (WO_LT|WO_LE) ); + testcase( pTerm->eOperator & WO_LT ); + testcase( pTerm->eOperator & WO_LE ); + pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; + pTop = pTerm; + pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? + pNew->aLTerm[pNew->nLTerm-2] : 0; + } + if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ + /* Adjust nOut and rRun for STAT3 range values */ + assert( pNew->nOut==saved_nOut ); + whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); + } +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + if( nInMul==0 + && pProbe->nSample + && pNew->u.btree.nEq<=pProbe->nSampleCol + && OptimizationEnabled(db, SQLITE_Stat3) + ){ + Expr *pExpr = pTerm->pExpr; + tRowcnt nOut = 0; + if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){ + testcase( pTerm->eOperator & WO_EQ ); + testcase( pTerm->eOperator & WO_ISNULL ); + rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); + }else if( (pTerm->eOperator & WO_IN) + && !ExprHasProperty(pExpr, EP_xIsSelect) ){ + rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); + } + assert( nOut==0 || rc==SQLITE_OK ); + if( nOut ){ + pNew->nOut = sqlite3LogEst(nOut); + if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; + } + } +#endif + if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){ + /* Each row involves a step of the index, then a binary search of + ** the main table */ + pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10); + } + /* Step cost for each output row */ + pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut); + whereLoopOutputAdjust(pBuilder->pWC, pNew); + rc = whereLoopInsert(pBuilder, pNew); + if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 + && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0)) + ){ + whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); + } + pNew->nOut = saved_nOut; +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + pBuilder->nRecValid = nRecValid; +#endif + } + pNew->prereq = saved_prereq; + pNew->u.btree.nEq = saved_nEq; + pNew->wsFlags = saved_wsFlags; + pNew->nOut = saved_nOut; + pNew->nLTerm = saved_nLTerm; + return rc; +} + +/* +** Return True if it is possible that pIndex might be useful in +** implementing the ORDER BY clause in pBuilder. +** +** Return False if pBuilder does not contain an ORDER BY clause or +** if there is no way for pIndex to be useful in implementing that +** ORDER BY clause. +*/ +static int indexMightHelpWithOrderBy( + WhereLoopBuilder *pBuilder, + Index *pIndex, + int iCursor +){ + ExprList *pOB; + int ii, jj; + + if( pIndex->bUnordered ) return 0; + if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; + for(ii=0; iinExpr; ii++){ + Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr); + if( pExpr->op!=TK_COLUMN ) return 0; + if( pExpr->iTable==iCursor ){ + for(jj=0; jjnColumn; jj++){ + if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; + } + } + } + return 0; +} + +/* +** Return a bitmask where 1s indicate that the corresponding column of +** the table is used by an index. Only the first 63 columns are considered. +*/ +static Bitmask columnsInIndex(Index *pIdx){ + Bitmask m = 0; + int j; + for(j=pIdx->nColumn-1; j>=0; j--){ + int x = pIdx->aiColumn[j]; + assert( x>=0 ); + testcase( x==BMS-1 ); + testcase( x==BMS-2 ); + if( xa; inTerm; i++, pTerm++){ + if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1; + } + return 0; +} + +/* +** Add all WhereLoop objects for a single table of the join where the table +** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be +** a b-tree table, not a virtual table. +*/ +static int whereLoopAddBtree( + WhereLoopBuilder *pBuilder, /* WHERE clause information */ + Bitmask mExtra /* Extra prerequesites for using this table */ +){ + WhereInfo *pWInfo; /* WHERE analysis context */ + Index *pProbe; /* An index we are evaluating */ + Index sPk; /* A fake index object for the primary key */ + tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */ + int aiColumnPk = -1; /* The aColumn[] value for the sPk index */ + SrcList *pTabList; /* The FROM clause */ + struct SrcList_item *pSrc; /* The FROM clause btree term to add */ + WhereLoop *pNew; /* Template WhereLoop object */ + int rc = SQLITE_OK; /* Return code */ + int iSortIdx = 1; /* Index number */ + int b; /* A boolean value */ + LogEst rSize; /* number of rows in the table */ + LogEst rLogSize; /* Logarithm of the number of rows in the table */ + WhereClause *pWC; /* The parsed WHERE clause */ + Table *pTab; /* Table being queried */ + + pNew = pBuilder->pNew; + pWInfo = pBuilder->pWInfo; + pTabList = pWInfo->pTabList; + pSrc = pTabList->a + pNew->iTab; + pTab = pSrc->pTab; + pWC = pBuilder->pWC; + assert( !IsVirtual(pSrc->pTab) ); + + if( pSrc->pIndex ){ + /* An INDEXED BY clause specifies a particular index to use */ + pProbe = pSrc->pIndex; + }else{ + /* There is no INDEXED BY clause. Create a fake Index object in local + ** variable sPk to represent the rowid primary key index. Make this + ** fake index the first in a chain of Index objects with all of the real + ** indices to follow */ + Index *pFirst; /* First of real indices on the table */ + memset(&sPk, 0, sizeof(Index)); + sPk.nColumn = 1; + sPk.aiColumn = &aiColumnPk; + sPk.aiRowEst = aiRowEstPk; + sPk.onError = OE_Replace; + sPk.pTable = pTab; + aiRowEstPk[0] = pTab->nRowEst; + aiRowEstPk[1] = 1; + pFirst = pSrc->pTab->pIndex; + if( pSrc->notIndexed==0 ){ + /* The real indices of the table are only considered if the + ** NOT INDEXED qualifier is omitted from the FROM clause */ + sPk.pNext = pFirst; + } + pProbe = &sPk; + } + rSize = sqlite3LogEst(pTab->nRowEst); + rLogSize = estLog(rSize); + +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX + /* Automatic indexes */ + if( !pBuilder->pOrSet + && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 + && pSrc->pIndex==0 + && !pSrc->viaCoroutine + && !pSrc->notIndexed + && !pSrc->isCorrelated + ){ + /* Generate auto-index WhereLoops */ + WhereTerm *pTerm; + WhereTerm *pWCEnd = pWC->a + pWC->nTerm; + for(pTerm=pWC->a; rc==SQLITE_OK && pTermprereqRight & pNew->maskSelf ) continue; + if( termCanDriveIndex(pTerm, pSrc, 0) ){ + pNew->u.btree.nEq = 1; + pNew->u.btree.pIndex = 0; + pNew->nLTerm = 1; + pNew->aLTerm[0] = pTerm; + /* TUNING: One-time cost for computing the automatic index is + ** approximately 7*N*log2(N) where N is the number of rows in + ** the table being indexed. */ + pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) ); + /* TUNING: Each index lookup yields 20 rows in the table. This + ** is more than the usual guess of 10 rows, since we have no way + ** of knowning how selective the index will ultimately be. It would + ** not be unreasonable to make this value much larger. */ + pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); + pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); + pNew->wsFlags = WHERE_AUTO_INDEX; + pNew->prereq = mExtra | pTerm->prereqRight; + rc = whereLoopInsert(pBuilder, pNew); + } + } + } +#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ + + /* Loop over all indices + */ + for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ + if( pProbe->pPartIdxWhere!=0 + && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){ + continue; /* Partial index inappropriate for this query */ + } + pNew->u.btree.nEq = 0; + pNew->nLTerm = 0; + pNew->iSortIdx = 0; + pNew->rSetup = 0; + pNew->prereq = mExtra; + pNew->nOut = rSize; + pNew->u.btree.pIndex = pProbe; + b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); + /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ + assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); + if( pProbe->tnum<=0 ){ + /* Integer primary key index */ + pNew->wsFlags = WHERE_IPK; + + /* Full table scan */ + pNew->iSortIdx = b ? iSortIdx : 0; + /* TUNING: Cost of full table scan is 3*(N + log2(N)). + ** + The extra 3 factor is to encourage the use of indexed lookups + ** over full scans. FIXME */ + pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16; + whereLoopOutputAdjust(pWC, pNew); + rc = whereLoopInsert(pBuilder, pNew); + pNew->nOut = rSize; + if( rc ) break; + }else{ + Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe); + pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; + + /* Full scan via index */ + if( b + || ( m==0 + && pProbe->bUnordered==0 + && pProbe->szIdxRowszTabRow + && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 + && sqlite3GlobalConfig.bUseCis + && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) + ) + ){ + pNew->iSortIdx = b ? iSortIdx : 0; + if( m==0 ){ + /* TUNING: Cost of a covering index scan is K*(N + log2(N)). + ** + The extra factor K of between 1.1 and 3.0 that depends + ** on the relative sizes of the table and the index. K + ** is smaller for smaller indices, thus favoring them. + */ + pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 + + (15*pProbe->szIdxRow)/pTab->szTabRow; + }else{ + assert( b!=0 ); + /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N) + ** which we will simplify to just N*log2(N) */ + pNew->rRun = rSize + rLogSize; + } + whereLoopOutputAdjust(pWC, pNew); + rc = whereLoopInsert(pBuilder, pNew); + pNew->nOut = rSize; + if( rc ) break; + } + } + + rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + sqlite3Stat4ProbeFree(pBuilder->pRec); + pBuilder->nRecValid = 0; + pBuilder->pRec = 0; +#endif + + /* If there was an INDEXED BY clause, then only that one index is + ** considered. */ + if( pSrc->pIndex ) break; + } + return rc; +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Add all WhereLoop objects for a table of the join identified by +** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table. +*/ +static int whereLoopAddVirtual( + WhereLoopBuilder *pBuilder /* WHERE clause information */ +){ + WhereInfo *pWInfo; /* WHERE analysis context */ + Parse *pParse; /* The parsing context */ + WhereClause *pWC; /* The WHERE clause */ + struct SrcList_item *pSrc; /* The FROM clause term to search */ + Table *pTab; + sqlite3 *db; + sqlite3_index_info *pIdxInfo; + struct sqlite3_index_constraint *pIdxCons; + struct sqlite3_index_constraint_usage *pUsage; + WhereTerm *pTerm; + int i, j; + int iTerm, mxTerm; + int nConstraint; + int seenIn = 0; /* True if an IN operator is seen */ + int seenVar = 0; /* True if a non-constant constraint is seen */ + int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */ + WhereLoop *pNew; + int rc = SQLITE_OK; + + pWInfo = pBuilder->pWInfo; + pParse = pWInfo->pParse; + db = pParse->db; + pWC = pBuilder->pWC; + pNew = pBuilder->pNew; + pSrc = &pWInfo->pTabList->a[pNew->iTab]; + pTab = pSrc->pTab; + assert( IsVirtual(pTab) ); + pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy); + if( pIdxInfo==0 ) return SQLITE_NOMEM; + pNew->prereq = 0; + pNew->rSetup = 0; + pNew->wsFlags = WHERE_VIRTUALTABLE; + pNew->nLTerm = 0; + pNew->u.vtab.needFree = 0; + pUsage = pIdxInfo->aConstraintUsage; + nConstraint = pIdxInfo->nConstraint; + if( whereLoopResize(db, pNew, nConstraint) ){ + sqlite3DbFree(db, pIdxInfo); + return SQLITE_NOMEM; + } + + for(iPhase=0; iPhase<=3; iPhase++){ + if( !seenIn && (iPhase&1)!=0 ){ + iPhase++; + if( iPhase>3 ) break; + } + if( !seenVar && iPhase>1 ) break; + pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pIdxCons++){ + j = pIdxCons->iTermOffset; + pTerm = &pWC->a[j]; + switch( iPhase ){ + case 0: /* Constants without IN operator */ + pIdxCons->usable = 0; + if( (pTerm->eOperator & WO_IN)!=0 ){ + seenIn = 1; + } + if( pTerm->prereqRight!=0 ){ + seenVar = 1; + }else if( (pTerm->eOperator & WO_IN)==0 ){ + pIdxCons->usable = 1; + } + break; + case 1: /* Constants with IN operators */ + assert( seenIn ); + pIdxCons->usable = (pTerm->prereqRight==0); + break; + case 2: /* Variables without IN */ + assert( seenVar ); + pIdxCons->usable = (pTerm->eOperator & WO_IN)==0; + break; + default: /* Variables with IN */ + assert( seenVar && seenIn ); + pIdxCons->usable = 1; + break; + } + } + memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint); + if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); + pIdxInfo->idxStr = 0; + pIdxInfo->idxNum = 0; + pIdxInfo->needToFreeIdxStr = 0; + pIdxInfo->orderByConsumed = 0; + pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; + rc = vtabBestIndex(pParse, pTab, pIdxInfo); + if( rc ) goto whereLoopAddVtab_exit; + pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; + pNew->prereq = 0; + mxTerm = -1; + assert( pNew->nLSlot>=nConstraint ); + for(i=0; iaLTerm[i] = 0; + pNew->u.vtab.omitMask = 0; + for(i=0; i=0 ){ + j = pIdxCons->iTermOffset; + if( iTerm>=nConstraint + || j<0 + || j>=pWC->nTerm + || pNew->aLTerm[iTerm]!=0 + ){ + rc = SQLITE_ERROR; + sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName); + goto whereLoopAddVtab_exit; + } + testcase( iTerm==nConstraint-1 ); + testcase( j==0 ); + testcase( j==pWC->nTerm-1 ); + pTerm = &pWC->a[j]; + pNew->prereq |= pTerm->prereqRight; + assert( iTermnLSlot ); + pNew->aLTerm[iTerm] = pTerm; + if( iTerm>mxTerm ) mxTerm = iTerm; + testcase( iTerm==15 ); + testcase( iTerm==16 ); + if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<eOperator & WO_IN)!=0 ){ + if( pUsage[i].omit==0 ){ + /* Do not attempt to use an IN constraint if the virtual table + ** says that the equivalent EQ constraint cannot be safely omitted. + ** If we do attempt to use such a constraint, some rows might be + ** repeated in the output. */ + break; + } + /* A virtual table that is constrained by an IN clause may not + ** consume the ORDER BY clause because (1) the order of IN terms + ** is not necessarily related to the order of output terms and + ** (2) Multiple outputs from a single IN value will not merge + ** together. */ + pIdxInfo->orderByConsumed = 0; + } + } + } + if( i>=nConstraint ){ + pNew->nLTerm = mxTerm+1; + assert( pNew->nLTerm<=pNew->nLSlot ); + pNew->u.vtab.idxNum = pIdxInfo->idxNum; + pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; + pIdxInfo->needToFreeIdxStr = 0; + pNew->u.vtab.idxStr = pIdxInfo->idxStr; + pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0) + && pIdxInfo->orderByConsumed); + pNew->rSetup = 0; + pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); + /* TUNING: Every virtual table query returns 25 rows */ + pNew->nOut = 46; assert( 46==sqlite3LogEst(25) ); + whereLoopInsert(pBuilder, pNew); + if( pNew->u.vtab.needFree ){ + sqlite3_free(pNew->u.vtab.idxStr); + pNew->u.vtab.needFree = 0; + } + } + } + +whereLoopAddVtab_exit: + if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); + sqlite3DbFree(db, pIdxInfo); + return rc; +} +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/* +** Add WhereLoop entries to handle OR terms. This works for either +** btrees or virtual tables. +*/ +static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){ + WhereInfo *pWInfo = pBuilder->pWInfo; + WhereClause *pWC; + WhereLoop *pNew; + WhereTerm *pTerm, *pWCEnd; + int rc = SQLITE_OK; + int iCur; + WhereClause tempWC; + WhereLoopBuilder sSubBuild; + WhereOrSet sSum, sCur, sPrev; + struct SrcList_item *pItem; + + pWC = pBuilder->pWC; + if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK; + pWCEnd = pWC->a + pWC->nTerm; + pNew = pBuilder->pNew; + memset(&sSum, 0, sizeof(sSum)); + pItem = pWInfo->pTabList->a + pNew->iTab; + iCur = pItem->iCursor; + + for(pTerm=pWC->a; pTermeOperator & WO_OR)!=0 + && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 + ){ + WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; + WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; + WhereTerm *pOrTerm; + int once = 1; + int i, j; + + sSubBuild = *pBuilder; + sSubBuild.pOrderBy = 0; + sSubBuild.pOrSet = &sCur; + + for(pOrTerm=pOrWC->a; pOrTermeOperator & WO_AND)!=0 ){ + sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc; + }else if( pOrTerm->leftCursor==iCur ){ + tempWC.pWInfo = pWC->pWInfo; + tempWC.pOuter = pWC; + tempWC.op = TK_AND; + tempWC.nTerm = 1; + tempWC.a = pOrTerm; + sSubBuild.pWC = &tempWC; + }else{ + continue; + } + sCur.n = 0; +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pItem->pTab) ){ + rc = whereLoopAddVirtual(&sSubBuild); + for(i=0; inLTerm = 1; + pNew->aLTerm[0] = pTerm; + pNew->wsFlags = WHERE_MULTI_OR; + pNew->rSetup = 0; + pNew->iSortIdx = 0; + memset(&pNew->u, 0, sizeof(pNew->u)); + for(i=0; rc==SQLITE_OK && irRun = sSum.a[i].rRun + 18; + pNew->nOut = sSum.a[i].nOut; + pNew->prereq = sSum.a[i].prereq; + rc = whereLoopInsert(pBuilder, pNew); + } + } + } + return rc; +} + +/* +** Add all WhereLoop objects for all tables +*/ +static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ + WhereInfo *pWInfo = pBuilder->pWInfo; + Bitmask mExtra = 0; + Bitmask mPrior = 0; + int iTab; + SrcList *pTabList = pWInfo->pTabList; + struct SrcList_item *pItem; + sqlite3 *db = pWInfo->pParse->db; + int nTabList = pWInfo->nLevel; + int rc = SQLITE_OK; + u8 priorJoinType = 0; + WhereLoop *pNew; + + /* Loop over the tables in the join, from left to right */ + pNew = pBuilder->pNew; + whereLoopInit(pNew); + for(iTab=0, pItem=pTabList->a; iTabiTab = iTab; + pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor); + if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){ + mExtra = mPrior; + } + priorJoinType = pItem->jointype; + if( IsVirtual(pItem->pTab) ){ + rc = whereLoopAddVirtual(pBuilder); + }else{ + rc = whereLoopAddBtree(pBuilder, mExtra); + } + if( rc==SQLITE_OK ){ + rc = whereLoopAddOr(pBuilder, mExtra); + } + mPrior |= pNew->maskSelf; + if( rc || db->mallocFailed ) break; + } + whereLoopClear(db, pNew); + return rc; +} + +/* +** Examine a WherePath (with the addition of the extra WhereLoop of the 5th +** parameters) to see if it outputs rows in the requested ORDER BY +** (or GROUP BY) without requiring a separate sort operation. Return: +** +** 0: ORDER BY is not satisfied. Sorting required +** 1: ORDER BY is satisfied. Omit sorting +** -1: Unknown at this time +** +** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as +** strict. With GROUP BY and DISTINCT the only requirement is that +** equivalent rows appear immediately adjacent to one another. GROUP BY +** and DISTINT do not require rows to appear in any particular order as long +** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT +** the pOrderBy terms can be matched in any order. With ORDER BY, the +** pOrderBy terms must be matched in strict left-to-right order. +*/ +static int wherePathSatisfiesOrderBy( + WhereInfo *pWInfo, /* The WHERE clause */ + ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */ + WherePath *pPath, /* The WherePath to check */ + u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */ + u16 nLoop, /* Number of entries in pPath->aLoop[] */ + WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */ + Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */ +){ + u8 revSet; /* True if rev is known */ + u8 rev; /* Composite sort order */ + u8 revIdx; /* Index sort order */ + u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */ + u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */ + u8 isMatch; /* iColumn matches a term of the ORDER BY clause */ + u16 nColumn; /* Number of columns in pIndex */ + u16 nOrderBy; /* Number terms in the ORDER BY clause */ + int iLoop; /* Index of WhereLoop in pPath being processed */ + int i, j; /* Loop counters */ + int iCur; /* Cursor number for current WhereLoop */ + int iColumn; /* A column number within table iCur */ + WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */ + WhereTerm *pTerm; /* A single term of the WHERE clause */ + Expr *pOBExpr; /* An expression from the ORDER BY clause */ + CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ + Index *pIndex; /* The index associated with pLoop */ + sqlite3 *db = pWInfo->pParse->db; /* Database connection */ + Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ + Bitmask obDone; /* Mask of all ORDER BY terms */ + Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ + Bitmask ready; /* Mask of inner loops */ + + /* + ** We say the WhereLoop is "one-row" if it generates no more than one + ** row of output. A WhereLoop is one-row if all of the following are true: + ** (a) All index columns match with WHERE_COLUMN_EQ. + ** (b) The index is unique + ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row. + ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags. + ** + ** We say the WhereLoop is "order-distinct" if the set of columns from + ** that WhereLoop that are in the ORDER BY clause are different for every + ** row of the WhereLoop. Every one-row WhereLoop is automatically + ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause + ** is not order-distinct. To be order-distinct is not quite the same as being + ** UNIQUE since a UNIQUE column or index can have multiple rows that + ** are NULL and NULL values are equivalent for the purpose of order-distinct. + ** To be order-distinct, the columns must be UNIQUE and NOT NULL. + ** + ** The rowid for a table is always UNIQUE and NOT NULL so whenever the + ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is + ** automatically order-distinct. + */ + + assert( pOrderBy!=0 ); + + /* Sortability of virtual tables is determined by the xBestIndex method + ** of the virtual table itself */ + if( pLast->wsFlags & WHERE_VIRTUALTABLE ){ + testcase( nLoop>0 ); /* True when outer loops are one-row and match + ** no ORDER BY terms */ + return pLast->u.vtab.isOrdered; + } + if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0; + + nOrderBy = pOrderBy->nExpr; + testcase( nOrderBy==BMS-1 ); + if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */ + isOrderDistinct = 1; + obDone = MASKBIT(nOrderBy)-1; + orderDistinctMask = 0; + ready = 0; + for(iLoop=0; isOrderDistinct && obSat0 ) ready |= pLoop->maskSelf; + pLoop = iLoopaLoop[iLoop] : pLast; + assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); + iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; + + /* Mark off any ORDER BY term X that is a column in the table of + ** the current loop for which there is term in the WHERE + ** clause of the form X IS NULL or X=? that reference only outer + ** loops. + */ + for(i=0; ia[i].pExpr); + if( pOBExpr->op!=TK_COLUMN ) continue; + if( pOBExpr->iTable!=iCur ) continue; + pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, + ~ready, WO_EQ|WO_ISNULL, 0); + if( pTerm==0 ) continue; + if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){ + const char *z1, *z2; + pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); + if( !pColl ) pColl = db->pDfltColl; + z1 = pColl->zName; + pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr); + if( !pColl ) pColl = db->pDfltColl; + z2 = pColl->zName; + if( sqlite3StrICmp(z1, z2)!=0 ) continue; + } + obSat |= MASKBIT(i); + } + + if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ + if( pLoop->wsFlags & WHERE_IPK ){ + pIndex = 0; + nColumn = 0; + }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ + return 0; + }else{ + nColumn = pIndex->nColumn; + isOrderDistinct = pIndex->onError!=OE_None; + } + + /* Loop through all columns of the index and deal with the ones + ** that are not constrained by == or IN. + */ + rev = revSet = 0; + distinctColumns = 0; + for(j=0; j<=nColumn; j++){ + u8 bOnce; /* True to run the ORDER BY search loop */ + + /* Skip over == and IS NULL terms */ + if( ju.btree.nEq + && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0 + ){ + if( i & WO_ISNULL ){ + testcase( isOrderDistinct ); + isOrderDistinct = 0; + } + continue; + } + + /* Get the column number in the table (iColumn) and sort order + ** (revIdx) for the j-th column of the index. + */ + if( jaiColumn[j]; + revIdx = pIndex->aSortOrder[j]; + if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; + }else{ + /* The ROWID column at the end */ + assert( j==nColumn ); + iColumn = -1; + revIdx = 0; + } + + /* An unconstrained column that might be NULL means that this + ** WhereLoop is not well-ordered + */ + if( isOrderDistinct + && iColumn>=0 + && j>=pLoop->u.btree.nEq + && pIndex->pTable->aCol[iColumn].notNull==0 + ){ + isOrderDistinct = 0; + } + + /* Find the ORDER BY term that corresponds to the j-th column + ** of the index and and mark that ORDER BY term off + */ + bOnce = 1; + isMatch = 0; + for(i=0; bOnce && ia[i].pExpr); + testcase( wctrlFlags & WHERE_GROUPBY ); + testcase( wctrlFlags & WHERE_DISTINCTBY ); + if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; + if( pOBExpr->op!=TK_COLUMN ) continue; + if( pOBExpr->iTable!=iCur ) continue; + if( pOBExpr->iColumn!=iColumn ) continue; + if( iColumn>=0 ){ + pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); + if( !pColl ) pColl = db->pDfltColl; + if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; + } + isMatch = 1; + break; + } + if( isMatch ){ + if( iColumn<0 ){ + testcase( distinctColumns==0 ); + distinctColumns = 1; + } + obSat |= MASKBIT(i); + if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){ + /* Make sure the sort order is compatible in an ORDER BY clause. + ** Sort order is irrelevant for a GROUP BY clause. */ + if( revSet ){ + if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0; + }else{ + rev = revIdx ^ pOrderBy->a[i].sortOrder; + if( rev ) *pRevMask |= MASKBIT(iLoop); + revSet = 1; + } + } + }else{ + /* No match found */ + if( j==0 || jmaskSelf; + for(i=0; ia[i].pExpr; + if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){ + obSat |= MASKBIT(i); + } + } + } + } /* End the loop over all WhereLoops from outer-most down to inner-most */ + if( obSat==obDone ) return 1; + if( !isOrderDistinct ) return 0; + return -1; +} + +#ifdef WHERETRACE_ENABLED +/* For debugging use only: */ +static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){ + static char zName[65]; + int i; + for(i=0; iaLoop[i]->cId; } + if( pLast ) zName[i++] = pLast->cId; + zName[i] = 0; + return zName; +} +#endif + + +/* +** Given the list of WhereLoop objects at pWInfo->pLoops, this routine +** attempts to find the lowest cost path that visits each WhereLoop +** once. This path is then loaded into the pWInfo->a[].pWLoop fields. +** +** Assume that the total number of output rows that will need to be sorted +** will be nRowEst (in the 10*log2 representation). Or, ignore sorting +** costs if nRowEst==0. +** +** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation +** error occurs. +*/ +static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ + int mxChoice; /* Maximum number of simultaneous paths tracked */ + int nLoop; /* Number of terms in the join */ + Parse *pParse; /* Parsing context */ + sqlite3 *db; /* The database connection */ + int iLoop; /* Loop counter over the terms of the join */ + int ii, jj; /* Loop counters */ + int mxI = 0; /* Index of next entry to replace */ + LogEst rCost; /* Cost of a path */ + LogEst nOut; /* Number of outputs */ + LogEst mxCost = 0; /* Maximum cost of a set of paths */ + LogEst mxOut = 0; /* Maximum nOut value on the set of paths */ + LogEst rSortCost; /* Cost to do a sort */ + int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ + WherePath *aFrom; /* All nFrom paths at the previous level */ + WherePath *aTo; /* The nTo best paths at the current level */ + WherePath *pFrom; /* An element of aFrom[] that we are working on */ + WherePath *pTo; /* An element of aTo[] that we are working on */ + WhereLoop *pWLoop; /* One of the WhereLoop objects */ + WhereLoop **pX; /* Used to divy up the pSpace memory */ + char *pSpace; /* Temporary memory used by this routine */ + + pParse = pWInfo->pParse; + db = pParse->db; + nLoop = pWInfo->nLevel; + /* TUNING: For simple queries, only the best path is tracked. + ** For 2-way joins, the 5 best paths are followed. + ** For joins of 3 or more tables, track the 10 best paths */ + mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10); + assert( nLoop<=pWInfo->pTabList->nSrc ); + WHERETRACE(0x002, ("---- begin solver\n")); + + /* Allocate and initialize space for aTo and aFrom */ + ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; + pSpace = sqlite3DbMallocRaw(db, ii); + if( pSpace==0 ) return SQLITE_NOMEM; + aTo = (WherePath*)pSpace; + aFrom = aTo+mxChoice; + memset(aFrom, 0, sizeof(aFrom[0])); + pX = (WhereLoop**)(aFrom+mxChoice); + for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){ + pFrom->aLoop = pX; + } + + /* Seed the search with a single WherePath containing zero WhereLoops. + ** + ** TUNING: Do not let the number of iterations go above 25. If the cost + ** of computing an automatic index is not paid back within the first 25 + ** rows, then do not use the automatic index. */ + aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) ); + nFrom = 1; + + /* Precompute the cost of sorting the final result set, if the caller + ** to sqlite3WhereBegin() was concerned about sorting */ + rSortCost = 0; + if( pWInfo->pOrderBy==0 || nRowEst==0 ){ + aFrom[0].isOrderedValid = 1; + }else{ + /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the + ** number of output rows. The 48 is the expected size of a row to sort. + ** FIXME: compute a better estimate of the 48 multiplier based on the + ** result set expressions. */ + rSortCost = nRowEst + estLog(nRowEst); + WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost)); + } + + /* Compute successively longer WherePaths using the previous generation + ** of WherePaths as the basis for the next. Keep track of the mxChoice + ** best paths at each generation */ + for(iLoop=0; iLooppLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ + Bitmask maskNew; + Bitmask revMask = 0; + u8 isOrderedValid = pFrom->isOrderedValid; + u8 isOrdered = pFrom->isOrdered; + if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; + if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; + /* At this point, pWLoop is a candidate to be the next loop. + ** Compute its cost */ + rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); + rCost = sqlite3LogEstAdd(rCost, pFrom->rCost); + nOut = pFrom->nRow + pWLoop->nOut; + maskNew = pFrom->maskLoop | pWLoop->maskSelf; + if( !isOrderedValid ){ + switch( wherePathSatisfiesOrderBy(pWInfo, + pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags, + iLoop, pWLoop, &revMask) ){ + case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */ + isOrdered = 1; + isOrderedValid = 1; + break; + case 0: /* No. pFrom+pWLoop will require a separate sort */ + isOrdered = 0; + isOrderedValid = 1; + rCost = sqlite3LogEstAdd(rCost, rSortCost); + break; + default: /* Cannot tell yet. Try again on the next iteration */ + break; + } + }else{ + revMask = pFrom->revLoop; + } + /* Check to see if pWLoop should be added to the mxChoice best so far */ + for(jj=0, pTo=aTo; jjmaskLoop==maskNew + && pTo->isOrderedValid==isOrderedValid + && ((pTo->rCost<=rCost && pTo->nRow<=nOut) || + (pTo->rCost>=rCost && pTo->nRow>=nOut)) + ){ + testcase( jj==nTo-1 ); + break; + } + } + if( jj>=nTo ){ + if( nTo>=mxChoice && rCost>=mxCost ){ +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace&0x4 ){ + sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?'); + } +#endif + continue; + } + /* Add a new Path to the aTo[] set */ + if( nTorCost<=rCost && pTo->nRow<=nOut ){ +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace&0x4 ){ + sqlite3DebugPrintf( + "Skip %s cost=%-3d,%3d order=%c", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?'); + sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n", + wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, + pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?'); + } +#endif + testcase( pTo->rCost==rCost ); + continue; + } + testcase( pTo->rCost==rCost+1 ); + /* A new and better score for a previously created equivalent path */ +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace&0x4 ){ + sqlite3DebugPrintf( + "Update %s cost=%-3d,%3d order=%c", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?'); + sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n", + wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, + pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?'); + } +#endif + } + /* pWLoop is a winner. Add it to the set of best so far */ + pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf; + pTo->revLoop = revMask; + pTo->nRow = nOut; + pTo->rCost = rCost; + pTo->isOrderedValid = isOrderedValid; + pTo->isOrdered = isOrdered; + memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); + pTo->aLoop[iLoop] = pWLoop; + if( nTo>=mxChoice ){ + mxI = 0; + mxCost = aTo[0].rCost; + mxOut = aTo[0].nRow; + for(jj=1, pTo=&aTo[1]; jjrCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){ + mxCost = pTo->rCost; + mxOut = pTo->nRow; + mxI = jj; + } + } + } + } + } + +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace>=2 ){ + sqlite3DebugPrintf("---- after round %d ----\n", iLoop); + for(ii=0, pTo=aTo; iirCost, pTo->nRow, + pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?'); + if( pTo->isOrderedValid && pTo->isOrdered ){ + sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); + }else{ + sqlite3DebugPrintf("\n"); + } + } + } +#endif + + /* Swap the roles of aFrom and aTo for the next generation */ + pFrom = aTo; + aTo = aFrom; + aFrom = pFrom; + nFrom = nTo; + } + + if( nFrom==0 ){ + sqlite3ErrorMsg(pParse, "no query solution"); + sqlite3DbFree(db, pSpace); + return SQLITE_ERROR; + } + + /* Find the lowest cost path. pFrom will be left pointing to that path */ + pFrom = aFrom; + for(ii=1; iirCost>aFrom[ii].rCost ) pFrom = &aFrom[ii]; + } + assert( pWInfo->nLevel==nLoop ); + /* Load the lowest cost path into pWInfo */ + for(iLoop=0; iLoopa + iLoop; + pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop]; + pLevel->iFrom = pWLoop->iTab; + pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor; + } + if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 + && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0 + && pWInfo->eDistinct==WHERE_DISTINCT_NOOP + && nRowEst + ){ + Bitmask notUsed; + int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom, + WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used); + if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; + } + if( pFrom->isOrdered ){ + if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ + pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; + }else{ + pWInfo->bOBSat = 1; + pWInfo->revMask = pFrom->revLoop; + } + } + pWInfo->nRowOut = pFrom->nRow; + + /* Free temporary memory and return success */ + sqlite3DbFree(db, pSpace); + return SQLITE_OK; +} + +/* +** Most queries use only a single table (they are not joins) and have +** simple == constraints against indexed fields. This routine attempts +** to plan those simple cases using much less ceremony than the +** general-purpose query planner, and thereby yield faster sqlite3_prepare() +** times for the common case. +** +** Return non-zero on success, if this query can be handled by this +** no-frills query planner. Return zero if this query needs the +** general-purpose query planner. +*/ +static int whereShortCut(WhereLoopBuilder *pBuilder){ + WhereInfo *pWInfo; + struct SrcList_item *pItem; + WhereClause *pWC; + WhereTerm *pTerm; + WhereLoop *pLoop; + int iCur; + int j; + Table *pTab; + Index *pIdx; + + pWInfo = pBuilder->pWInfo; + if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0; + assert( pWInfo->pTabList->nSrc>=1 ); + pItem = pWInfo->pTabList->a; + pTab = pItem->pTab; + if( IsVirtual(pTab) ) return 0; + if( pItem->zIndex ) return 0; + iCur = pItem->iCursor; + pWC = &pWInfo->sWC; + pLoop = pBuilder->pNew; + pLoop->wsFlags = 0; + pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0); + if( pTerm ){ + pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; + pLoop->aLTerm[0] = pTerm; + pLoop->nLTerm = 1; + pLoop->u.btree.nEq = 1; + /* TUNING: Cost of a rowid lookup is 10 */ + pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ + }else{ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + assert( pLoop->aLTermSpace==pLoop->aLTerm ); + assert( ArraySize(pLoop->aLTermSpace)==4 ); + if( pIdx->onError==OE_None + || pIdx->pPartIdxWhere!=0 + || pIdx->nColumn>ArraySize(pLoop->aLTermSpace) + ) continue; + for(j=0; jnColumn; j++){ + pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx); + if( pTerm==0 ) break; + pLoop->aLTerm[j] = pTerm; + } + if( j!=pIdx->nColumn ) continue; + pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; + if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ + pLoop->wsFlags |= WHERE_IDX_ONLY; + } + pLoop->nLTerm = j; + pLoop->u.btree.nEq = j; + pLoop->u.btree.pIndex = pIdx; + /* TUNING: Cost of a unique index lookup is 15 */ + pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ + break; + } + } + if( pLoop->wsFlags ){ + pLoop->nOut = (LogEst)1; + pWInfo->a[0].pWLoop = pLoop; + pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur); + pWInfo->a[0].iTabCur = iCur; + pWInfo->nRowOut = 1; + if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1; + if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ + pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; + } +#ifdef SQLITE_DEBUG + pLoop->cId = '0'; +#endif + return 1; + } + return 0; +} + +/* +** Generate the beginning of the loop used for WHERE clause processing. +** The return value is a pointer to an opaque structure that contains +** information needed to terminate the loop. Later, the calling routine +** should invoke sqlite3WhereEnd() with the return value of this function +** in order to complete the WHERE clause processing. +** +** If an error occurs, this routine returns NULL. +** +** The basic idea is to do a nested loop, one loop for each table in +** the FROM clause of a select. (INSERT and UPDATE statements are the +** same as a SELECT with only a single table in the FROM clause.) For +** example, if the SQL is this: +** +** SELECT * FROM t1, t2, t3 WHERE ...; +** +** Then the code generated is conceptually like the following: +** +** foreach row1 in t1 do \ Code generated +** foreach row2 in t2 do |-- by sqlite3WhereBegin() +** foreach row3 in t3 do / +** ... +** end \ Code generated +** end |-- by sqlite3WhereEnd() +** end / +** +** Note that the loops might not be nested in the order in which they +** appear in the FROM clause if a different order is better able to make +** use of indices. Note also that when the IN operator appears in +** the WHERE clause, it might result in additional nested loops for +** scanning through all values on the right-hand side of the IN. +** +** There are Btree cursors associated with each table. t1 uses cursor +** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. +** And so forth. This routine generates code to open those VDBE cursors +** and sqlite3WhereEnd() generates the code to close them. +** +** The code that sqlite3WhereBegin() generates leaves the cursors named +** in pTabList pointing at their appropriate entries. The [...] code +** can use OP_Column and OP_Rowid opcodes on these cursors to extract +** data from the various tables of the loop. +** +** If the WHERE clause is empty, the foreach loops must each scan their +** entire tables. Thus a three-way join is an O(N^3) operation. But if +** the tables have indices and there are terms in the WHERE clause that +** refer to those indices, a complete table scan can be avoided and the +** code will run much faster. Most of the work of this routine is checking +** to see if there are indices that can be used to speed up the loop. +** +** Terms of the WHERE clause are also used to limit which rows actually +** make it to the "..." in the middle of the loop. After each "foreach", +** terms of the WHERE clause that use only terms in that loop and outer +** loops are evaluated and if false a jump is made around all subsequent +** inner loops (or around the "..." if the test occurs within the inner- +** most loop) +** +** OUTER JOINS +** +** An outer join of tables t1 and t2 is conceptally coded as follows: +** +** foreach row1 in t1 do +** flag = 0 +** foreach row2 in t2 do +** start: +** ... +** flag = 1 +** end +** if flag==0 then +** move the row2 cursor to a null row +** goto start +** fi +** end +** +** ORDER BY CLAUSE PROCESSING +** +** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause +** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement +** if there is one. If there is no ORDER BY clause or if this routine +** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. +*/ +WhereInfo *sqlite3WhereBegin( + Parse *pParse, /* The parser context */ + SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ + Expr *pWhere, /* The WHERE clause */ + ExprList *pOrderBy, /* An ORDER BY clause, or NULL */ + ExprList *pResultSet, /* Result set of the query */ + u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */ + int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */ +){ + int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ + int nTabList; /* Number of elements in pTabList */ + WhereInfo *pWInfo; /* Will become the return value of this function */ + Vdbe *v = pParse->pVdbe; /* The virtual database engine */ + Bitmask notReady; /* Cursors that are not yet positioned */ + WhereLoopBuilder sWLB; /* The WhereLoop builder */ + WhereMaskSet *pMaskSet; /* The expression mask set */ + WhereLevel *pLevel; /* A single level in pWInfo->a[] */ + WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ + int ii; /* Loop counter */ + sqlite3 *db; /* Database connection */ + int rc; /* Return code */ + + + /* Variable initialization */ + db = pParse->db; + memset(&sWLB, 0, sizeof(sWLB)); + sWLB.pOrderBy = pOrderBy; + + /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via + ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ + if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ + wctrlFlags &= ~WHERE_WANT_DISTINCT; + } + + /* The number of tables in the FROM clause is limited by the number of + ** bits in a Bitmask + */ + testcase( pTabList->nSrc==BMS ); + if( pTabList->nSrc>BMS ){ + sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); + return 0; + } + + /* This function normally generates a nested loop for all tables in + ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should + ** only generate code for the first table in pTabList and assume that + ** any cursors associated with subsequent tables are uninitialized. + */ + nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc; + + /* Allocate and initialize the WhereInfo structure that will become the + ** return value. A single allocation is used to store the WhereInfo + ** struct, the contents of WhereInfo.a[], the WhereClause structure + ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte + ** field (type Bitmask) it must be aligned on an 8-byte boundary on + ** some architectures. Hence the ROUND8() below. + */ + nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); + pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop)); + if( db->mallocFailed ){ + sqlite3DbFree(db, pWInfo); + pWInfo = 0; + goto whereBeginError; + } + pWInfo->nLevel = nTabList; + pWInfo->pParse = pParse; + pWInfo->pTabList = pTabList; + pWInfo->pOrderBy = pOrderBy; + pWInfo->pResultSet = pResultSet; + pWInfo->iBreak = sqlite3VdbeMakeLabel(v); + pWInfo->wctrlFlags = wctrlFlags; + pWInfo->savedNQueryLoop = pParse->nQueryLoop; + pMaskSet = &pWInfo->sMaskSet; + sWLB.pWInfo = pWInfo; + sWLB.pWC = &pWInfo->sWC; + sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); + assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); + whereLoopInit(sWLB.pNew); +#ifdef SQLITE_DEBUG + sWLB.pNew->cId = '*'; +#endif + + /* Split the WHERE clause into separate subexpressions where each + ** subexpression is separated by an AND operator. + */ + initMaskSet(pMaskSet); + whereClauseInit(&pWInfo->sWC, pWInfo); + sqlite3ExprCodeConstants(pParse, pWhere); + whereSplit(&pWInfo->sWC, pWhere, TK_AND); + sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */ + + /* Special case: a WHERE clause that is constant. Evaluate the + ** expression and either jump over all of the code or fall thru. + */ + if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){ + sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL); + pWhere = 0; + } + + /* Special case: No FROM clause + */ + if( nTabList==0 ){ + if( pOrderBy ) pWInfo->bOBSat = 1; + if( wctrlFlags & WHERE_WANT_DISTINCT ){ + pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; + } + } + + /* Assign a bit from the bitmask to every term in the FROM clause. + ** + ** When assigning bitmask values to FROM clause cursors, it must be + ** the case that if X is the bitmask for the N-th FROM clause term then + ** the bitmask for all FROM clause terms to the left of the N-th term + ** is (X-1). An expression from the ON clause of a LEFT JOIN can use + ** its Expr.iRightJoinTable value to find the bitmask of the right table + ** of the join. Subtracting one from the right table bitmask gives a + ** bitmask for all tables to the left of the join. Knowing the bitmask + ** for all tables to the left of a left join is important. Ticket #3015. + ** + ** Note that bitmasks are created for all pTabList->nSrc tables in + ** pTabList, not just the first nTabList tables. nTabList is normally + ** equal to pTabList->nSrc but might be shortened to 1 if the + ** WHERE_ONETABLE_ONLY flag is set. + */ + for(ii=0; iinSrc; ii++){ + createMask(pMaskSet, pTabList->a[ii].iCursor); + } +#ifndef NDEBUG + { + Bitmask toTheLeft = 0; + for(ii=0; iinSrc; ii++){ + Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor); + assert( (m-1)==toTheLeft ); + toTheLeft |= m; + } + } +#endif + + /* Analyze all of the subexpressions. Note that exprAnalyze() might + ** add new virtual terms onto the end of the WHERE clause. We do not + ** want to analyze these virtual terms, so start analyzing at the end + ** and work forward so that the added virtual terms are never processed. + */ + exprAnalyzeAll(pTabList, &pWInfo->sWC); + if( db->mallocFailed ){ + goto whereBeginError; + } + + /* If the ORDER BY (or GROUP BY) clause contains references to general + ** expressions, then we won't be able to satisfy it using indices, so + ** go ahead and disable it now. + */ + if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){ + for(ii=0; iinExpr; ii++){ + Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr); + if( pExpr->op!=TK_COLUMN ){ + pWInfo->pOrderBy = pOrderBy = 0; + break; + }else if( pExpr->iColumn<0 ){ + break; + } + } + } + + if( wctrlFlags & WHERE_WANT_DISTINCT ){ + if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){ + /* The DISTINCT marking is pointless. Ignore it. */ + pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; + }else if( pOrderBy==0 ){ + /* Try to ORDER BY the result set to make distinct processing easier */ + pWInfo->wctrlFlags |= WHERE_DISTINCTBY; + pWInfo->pOrderBy = pResultSet; + } + } + + /* Construct the WhereLoop objects */ + WHERETRACE(0xffff,("*** Optimizer Start ***\n")); + if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ + rc = whereLoopAddAll(&sWLB); + if( rc ) goto whereBeginError; + + /* Display all of the WhereLoop objects if wheretrace is enabled */ +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace ){ + WhereLoop *p; + int i; + static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" + "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; + for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ + p->cId = zLabel[i%sizeof(zLabel)]; + whereLoopPrint(p, pTabList); + } + } +#endif + + wherePathSolver(pWInfo, 0); + if( db->mallocFailed ) goto whereBeginError; + if( pWInfo->pOrderBy ){ + wherePathSolver(pWInfo, pWInfo->nRowOut+1); + if( db->mallocFailed ) goto whereBeginError; + } + } + if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ + pWInfo->revMask = (Bitmask)(-1); + } + if( pParse->nErr || NEVER(db->mallocFailed) ){ + goto whereBeginError; + } +#ifdef WHERETRACE_ENABLED + if( sqlite3WhereTrace ){ + int ii; + sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); + if( pWInfo->bOBSat ){ + sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask); + } + switch( pWInfo->eDistinct ){ + case WHERE_DISTINCT_UNIQUE: { + sqlite3DebugPrintf(" DISTINCT=unique"); + break; + } + case WHERE_DISTINCT_ORDERED: { + sqlite3DebugPrintf(" DISTINCT=ordered"); + break; + } + case WHERE_DISTINCT_UNORDERED: { + sqlite3DebugPrintf(" DISTINCT=unordered"); + break; + } + } + sqlite3DebugPrintf("\n"); + for(ii=0; iinLevel; ii++){ + whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList); + } + } +#endif + /* Attempt to omit tables from the join that do not effect the result */ + if( pWInfo->nLevel>=2 + && pResultSet!=0 + && OptimizationEnabled(db, SQLITE_OmitNoopJoin) + ){ + Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet); + if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy); + while( pWInfo->nLevel>=2 ){ + WhereTerm *pTerm, *pEnd; + pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop; + if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break; + if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 + && (pLoop->wsFlags & WHERE_ONEROW)==0 + ){ + break; + } + if( (tabUsed & pLoop->maskSelf)!=0 ) break; + pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; + for(pTerm=sWLB.pWC->a; pTermprereqAll & pLoop->maskSelf)!=0 + && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) + ){ + break; + } + } + if( pTerm drop loop %c not used\n", pLoop->cId)); + pWInfo->nLevel--; + nTabList--; + } + } + WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); + pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; + + /* If the caller is an UPDATE or DELETE statement that is requesting + ** to use a one-pass algorithm, determine if this is appropriate. + ** The one-pass algorithm only works if the WHERE clause constrains + ** the statement to update a single row. + */ + assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); + if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 + && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){ + pWInfo->okOnePass = 1; + pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY; + } + + /* Open all tables in the pTabList and any indices selected for + ** searching those tables. + */ + notReady = ~(Bitmask)0; + for(ii=0, pLevel=pWInfo->a; iia[pLevel->iFrom]; + pTab = pTabItem->pTab; + iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + pLoop = pLevel->pWLoop; + if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ + /* Do nothing */ + }else +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ + const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); + int iCur = pTabItem->iCursor; + sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); + }else if( IsVirtual(pTab) ){ + /* noop */ + }else +#endif + if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 + && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){ + int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead; + sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); + testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 ); + testcase( !pWInfo->okOnePass && pTab->nCol==BMS ); + if( !pWInfo->okOnePass && pTab->nColcolUsed; + int n = 0; + for(; b; b=b>>1, n++){} + sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, + SQLITE_INT_TO_PTR(n), P4_INT32); + assert( n<=pTab->nCol ); + } + }else{ + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + } + if( pLoop->wsFlags & WHERE_INDEXED ){ + Index *pIx = pLoop->u.btree.pIndex; + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx); + /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */ + int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++; + assert( pIx->pSchema==pTab->pSchema ); + assert( iIndexCur>=0 ); + sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb, + (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIx->zName)); + } + sqlite3CodeVerifySchema(pParse, iDb); + notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor); + } + pWInfo->iTop = sqlite3VdbeCurrentAddr(v); + if( db->mallocFailed ) goto whereBeginError; + + /* Generate the code to do the search. Each iteration of the for + ** loop below generates code for a single nested loop of the VM + ** program. + */ + notReady = ~(Bitmask)0; + for(ii=0; iia[ii]; +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX + if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){ + constructAutomaticIndex(pParse, &pWInfo->sWC, + &pTabList->a[pLevel->iFrom], notReady, pLevel); + if( db->mallocFailed ) goto whereBeginError; + } +#endif + explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags); + pLevel->addrBody = sqlite3VdbeCurrentAddr(v); + notReady = codeOneLoopStart(pWInfo, ii, notReady); + pWInfo->iContinue = pLevel->addrCont; + } + + /* Done. */ + return pWInfo; + + /* Jump here if malloc fails */ +whereBeginError: + if( pWInfo ){ + pParse->nQueryLoop = pWInfo->savedNQueryLoop; + whereInfoFree(db, pWInfo); + } + return 0; +} + +/* +** Generate the end of the WHERE loop. See comments on +** sqlite3WhereBegin() for additional information. +*/ +void sqlite3WhereEnd(WhereInfo *pWInfo){ + Parse *pParse = pWInfo->pParse; + Vdbe *v = pParse->pVdbe; + int i; + WhereLevel *pLevel; + WhereLoop *pLoop; + SrcList *pTabList = pWInfo->pTabList; + sqlite3 *db = pParse->db; + + /* Generate loop termination code. + */ + sqlite3ExprCacheClear(pParse); + for(i=pWInfo->nLevel-1; i>=0; i--){ + pLevel = &pWInfo->a[i]; + pLoop = pLevel->pWLoop; + sqlite3VdbeResolveLabel(v, pLevel->addrCont); + if( pLevel->op!=OP_Noop ){ + sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2); + sqlite3VdbeChangeP5(v, pLevel->p5); + } + if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ + struct InLoop *pIn; + int j; + sqlite3VdbeResolveLabel(v, pLevel->addrNxt); + for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ + sqlite3VdbeJumpHere(v, pIn->addrInTop+1); + sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); + sqlite3VdbeJumpHere(v, pIn->addrInTop-1); + } + sqlite3DbFree(db, pLevel->u.in.aInLoop); + } + sqlite3VdbeResolveLabel(v, pLevel->addrBrk); + if( pLevel->iLeftJoin ){ + int addr; + addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); + assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 + || (pLoop->wsFlags & WHERE_INDEXED)!=0 ); + if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){ + sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); + } + if( pLoop->wsFlags & WHERE_INDEXED ){ + sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); + } + if( pLevel->op==OP_Return ){ + sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); + }else{ + sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst); + } + sqlite3VdbeJumpHere(v, addr); + } + } + + /* The "break" point is here, just past the end of the outer loop. + ** Set it. + */ + sqlite3VdbeResolveLabel(v, pWInfo->iBreak); + + /* Close all of the cursors that were opened by sqlite3WhereBegin. + */ + assert( pWInfo->nLevel<=pTabList->nSrc ); + for(i=0, pLevel=pWInfo->a; inLevel; i++, pLevel++){ + Index *pIdx = 0; + struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; + Table *pTab = pTabItem->pTab; + assert( pTab!=0 ); + pLoop = pLevel->pWLoop; + if( (pTab->tabFlags & TF_Ephemeral)==0 + && pTab->pSelect==0 + && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 + ){ + int ws = pLoop->wsFlags; + if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){ + sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); + } + if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){ + sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); + } + } + + /* If this scan uses an index, make VDBE code substitutions to read data + ** from the index instead of from the table where possible. In some cases + ** this optimization prevents the table from ever being read, which can + ** yield a significant performance boost. + ** + ** Calls to the code generator in between sqlite3WhereBegin and + ** sqlite3WhereEnd will have created code that references the table + ** directly. This loop scans all that code looking for opcodes + ** that reference the table and converts them into opcodes that + ** reference the index. + */ + if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ + pIdx = pLoop->u.btree.pIndex; + }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ + pIdx = pLevel->u.pCovidx; + } + if( pIdx && !db->mallocFailed ){ + int k, j, last; + VdbeOp *pOp; + + last = sqlite3VdbeCurrentAddr(v); + k = pLevel->addrBody; + pOp = sqlite3VdbeGetOp(v, k); + for(; kp1!=pLevel->iTabCur ) continue; + if( pOp->opcode==OP_Column ){ + for(j=0; jnColumn; j++){ + if( pOp->p2==pIdx->aiColumn[j] ){ + pOp->p2 = j; + pOp->p1 = pLevel->iIdxCur; + break; + } + } + assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || jnColumn ); + }else if( pOp->opcode==OP_Rowid ){ + pOp->p1 = pLevel->iIdxCur; + pOp->opcode = OP_IdxRowid; + } + } + } + } + + /* Final cleanup + */ + pParse->nQueryLoop = pWInfo->savedNQueryLoop; + whereInfoFree(db, pWInfo); + return; +} diff --git a/components/external/SQLite-3.8.1/test/8_3_names.test b/components/external/SQLite-3.8.1/test/8_3_names.test new file mode 100644 index 0000000000000000000000000000000000000000..1d63f5dcc96ceeccdcd7d1fa4fbdd6f75eee9268 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/8_3_names.test @@ -0,0 +1,197 @@ +# 2011 May 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test cases for the SQLITE_ENABLE_8_3_NAMES feature that forces all +# filename extensions to be limited to 3 characters. Some embedded +# systems need this to work around microsoft FAT patents, but this +# feature should be disabled on most deployments. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !8_3_names { + finish_test + return +} + +db close +sqlite3_shutdown +sqlite3_config_uri 1 + +do_test 8_3_names-1.0 { + forcedelete test.db test.nal test.db-journal + sqlite3 db test.db + db eval { + PRAGMA cache_size=10; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(20000)); + BEGIN; + DELETE FROM t1; + INSERT INTO t1 VALUES(randomblob(15000)); + } + file exists test.db-journal +} 1 +do_test 8_3_names-1.1 { + file exists test.nal +} 0 +do_test 8_3_names-1.2 { + db eval { + ROLLBACK; + SELECT length(x) FROM t1 + } +} 20000 + +db close +do_test 8_3_names-2.0 { + forcedelete test.db test.nal test.db-journal + sqlite3 db file:./test.db?8_3_names=1 + db eval { + PRAGMA cache_size=10; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(20000)); + BEGIN; + DELETE FROM t1; + INSERT INTO t1 VALUES(randomblob(15000)); + } + file exists test.db-journal +} 0 +do_test 8_3_names-2.1 { + file exists test.nal +} 1 +forcedelete test2.db test2.nal test2.db-journal +copy_file test.db test2.db +copy_file test.nal test2.nal +do_test 8_3_names-2.2 { + db eval { + COMMIT; + SELECT length(x) FROM t1 + } +} 15000 +do_test 8_3_names-2.3 { + sqlite3 db2 file:./test2.db?8_3_names=1 + db2 eval { + PRAGMA integrity_check; + SELECT length(x) FROM t1; + } +} {ok 20000} + +db close +do_test 8_3_names-3.0 { + forcedelete test.db test.nal test.db-journal + sqlite3 db file:./test.db?8_3_names=0 + db eval { + PRAGMA cache_size=10; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(20000)); + BEGIN; + DELETE FROM t1; + INSERT INTO t1 VALUES(randomblob(15000)); + } + file exists test.db-journal +} 1 +do_test 8_3_names-3.1 { + file exists test.nal +} 0 +forcedelete test2.db test2.nal test2.db-journal +copy_file test.db test2.db +copy_file test.db-journal test2.db-journal +do_test 8_3_names-3.2 { + db eval { + COMMIT; + SELECT length(x) FROM t1 + } +} 15000 +do_test 8_3_names-3.3 { + sqlite3 db2 file:./test2.db?8_3_names=0 + db2 eval { + PRAGMA integrity_check; + SELECT length(x) FROM t1; + } +} {ok 20000} + +########################################################################## +# Master journals. +# +db close +forcedelete test.db test2.db +do_test 8_3_names-4.0 { + sqlite3 db file:./test.db?8_3_names=1 + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + ATTACH 'file:./test2.db?8_3_names=1' AS db2; + CREATE TABLE db2.t2(y); + INSERT INTO t2 VALUES(2); + BEGIN; + INSERT INTO t1 VALUES(3); + INSERT INTO t2 VALUES(4); + COMMIT; + SELECT * FROM t1, t2 ORDER BY x, y + } +} {1 2 1 4 3 2 3 4} + + +########################################################################## +# WAL mode. +# +ifcapable !wal { + finish_test + return +} +db close +forcedelete test.db +do_test 8_3_names-5.0 { + sqlite3 db file:./test.db?8_3_names=1 + load_static_extension db wholenumber + db eval { + PRAGMA journal_mode=WAL; + CREATE TABLE t1(x); + CREATE VIRTUAL TABLE nums USING wholenumber; + INSERT INTO t1 SELECT value FROM nums WHERE value BETWEEN 1 AND 1000; + BEGIN; + UPDATE t1 SET x=x*2; + } + sqlite3 db2 file:./test.db?8_3_names=1 + load_static_extension db2 wholenumber + db2 eval { + BEGIN; + SELECT sum(x) FROM t1; + } +} {500500} + +do_test 8_3_names-5.1 { + file exists test.db-wal +} 0 +do_test 8_3_names-5.2 { + file exists test.wal +} 1 +do_test 8_3_names-5.3 { + file exists test.db-shm +} 0 +do_test 8_3_names-5.4 { + file exists test.shm +} 1 + + +do_test 8_3_names-5.5 { + db eval { + COMMIT; + SELECT sum(x) FROM t1; + } +} {1001000} +do_test 8_3_names-5.6 { + db2 eval { + SELECT sum(x) FROM t1; + } +} {500500} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/aggerror.test b/components/external/SQLite-3.8.1/test/aggerror.test new file mode 100644 index 0000000000000000000000000000000000000000..f95d8b220a8d663d2028444abe04094858d28288 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/aggerror.test @@ -0,0 +1,78 @@ +# 2006 January 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for calling sqlite3_result_error() +# from within an aggregate function implementation. +# +# $Id: aggerror.test,v 1.3 2006/05/03 23:34:06 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +# Add the x_count aggregate function to the database handle. +# x_count will error out if its input is 40 or 41 or if its +# final results is 42. Make sure that such errors are handled +# appropriately. +# +do_test aggerror-1.1 { + set DB [sqlite3_connection_pointer db] + sqlite3_create_aggregate $DB + execsql { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 SELECT a+2 FROM t1; + INSERT INTO t1 SELECT a+4 FROM t1; + INSERT INTO t1 SELECT a+8 FROM t1; + INSERT INTO t1 SELECT a+16 FROM t1; + INSERT INTO t1 SELECT a+32 FROM t1 ORDER BY a LIMIT 7; + SELECT x_count(*) FROM t1; + } +} {39} +do_test aggerror-1.2 { + execsql { + INSERT INTO t1 VALUES(40); + SELECT x_count(*) FROM t1; + } +} {40} +do_test aggerror-1.3 { + catchsql { + SELECT x_count(a) FROM t1; + } +} {1 {value of 40 handed to x_count}} +ifcapable utf16 { + do_test aggerror-1.4 { + execsql { + UPDATE t1 SET a=41 WHERE a=40 + } + catchsql { + SELECT x_count(a) FROM t1; + } + } {1 abc} +} +do_test aggerror-1.5 { + execsql { + SELECT x_count(*) FROM t1 + } +} 40 +do_test aggerror-1.6 { + execsql { + INSERT INTO t1 VALUES(40); + INSERT INTO t1 VALUES(42); + } + catchsql { + SELECT x_count(*) FROM t1; + } +} {1 {x_count totals to 42}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/aggnested.test b/components/external/SQLite-3.8.1/test/aggnested.test new file mode 100644 index 0000000000000000000000000000000000000000..6e2fd6554b2a64f1ad11a4360d7d5526219a54dc --- /dev/null +++ b/components/external/SQLite-3.8.1/test/aggnested.test @@ -0,0 +1,231 @@ +# 2012 August 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for processing aggregate queries with +# subqueries in which the subqueries hold the aggregate functions +# or in which the subqueries are themselves aggregate queries +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test aggnested-1.1 { + db eval { + CREATE TABLE t1(a1 INTEGER); + INSERT INTO t1 VALUES(1), (2), (3); + CREATE TABLE t2(b1 INTEGER); + INSERT INTO t2 VALUES(4), (5); + SELECT (SELECT group_concat(a1,'x') FROM t2) FROM t1; + } +} {1x2x3} +do_test aggnested-1.2 { + db eval { + SELECT + (SELECT group_concat(a1,'x') || '-' || group_concat(b1,'y') FROM t2) + FROM t1; + } +} {1x2x3-4y5} +do_test aggnested-1.3 { + db eval { + SELECT (SELECT group_concat(b1,a1) FROM t2) FROM t1; + } +} {415 425 435} +do_test aggnested-1.4 { + db eval { + SELECT (SELECT group_concat(a1,b1) FROM t2) FROM t1; + } +} {151 252 353} + + +# This test case is a copy of the one in +# http://www.mail-archive.com/sqlite-users@sqlite.org/msg70787.html +# +do_test aggnested-2.0 { + sqlite3 db2 :memory: + db2 eval { + CREATE TABLE t1 (A1 INTEGER NOT NULL,A2 INTEGER NOT NULL,A3 INTEGER NOT + NULL,A4 INTEGER NOT NULL,PRIMARY KEY(A1)); + REPLACE INTO t1 VALUES(1,11,111,1111); + REPLACE INTO t1 VALUES(2,22,222,2222); + REPLACE INTO t1 VALUES(3,33,333,3333); + CREATE TABLE t2 (B1 INTEGER NOT NULL,B2 INTEGER NOT NULL,B3 INTEGER NOT + NULL,B4 INTEGER NOT NULL,PRIMARY KEY(B1)); + REPLACE INTO t2 VALUES(1,88,888,8888); + REPLACE INTO t2 VALUES(2,99,999,9999); + SELECT (SELECT GROUP_CONCAT(CASE WHEN a1=1 THEN'A' ELSE 'B' END) FROM t2), + t1.* + FROM t1; + } +} {A,B,B 3 33 333 3333} +db2 close + +##################### Test cases for ticket [bfbf38e5e9956ac69f] ############ +# +# This first test case is the original problem report: +do_test aggnested-3.0 { + db eval { + CREATE TABLE AAA ( + aaa_id INTEGER PRIMARY KEY AUTOINCREMENT + ); + CREATE TABLE RRR ( + rrr_id INTEGER PRIMARY KEY AUTOINCREMENT, + rrr_date INTEGER NOT NULL, + rrr_aaa INTEGER + ); + CREATE TABLE TTT ( + ttt_id INTEGER PRIMARY KEY AUTOINCREMENT, + target_aaa INTEGER NOT NULL, + source_aaa INTEGER NOT NULL + ); + insert into AAA (aaa_id) values (2); + insert into TTT (ttt_id, target_aaa, source_aaa) + values (4469, 2, 2); + insert into TTT (ttt_id, target_aaa, source_aaa) + values (4476, 2, 1); + insert into RRR (rrr_id, rrr_date, rrr_aaa) + values (0, 0, NULL); + insert into RRR (rrr_id, rrr_date, rrr_aaa) + values (2, 4312, 2); + SELECT i.aaa_id, + (SELECT sum(CASE WHEN (t.source_aaa == i.aaa_id) THEN 1 ELSE 0 END) + FROM TTT t + ) AS segfault + FROM + (SELECT curr.rrr_aaa as aaa_id + FROM RRR curr + -- you also can comment out the next line + -- it causes segfault to happen after one row is outputted + INNER JOIN AAA a ON (curr.rrr_aaa = aaa_id) + LEFT JOIN RRR r ON (r.rrr_id <> 0 AND r.rrr_date < curr.rrr_date) + GROUP BY curr.rrr_id + HAVING r.rrr_date IS NULL + ) i; + } +} {2 1} + +# Further variants of the test case, as found in the ticket +# +do_test aggnested-3.1 { + db eval { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1 ( + id1 INTEGER PRIMARY KEY AUTOINCREMENT, + value1 INTEGER + ); + INSERT INTO t1 VALUES(4469,2),(4476,1); + CREATE TABLE t2 ( + id2 INTEGER PRIMARY KEY AUTOINCREMENT, + value2 INTEGER + ); + INSERT INTO t2 VALUES(0,1),(2,2); + SELECT + (SELECT sum(value2==xyz) FROM t2) + FROM + (SELECT curr.value1 as xyz + FROM t1 AS curr LEFT JOIN t1 AS other + GROUP BY curr.id1); + } +} {1 1} +do_test aggnested-3.2 { + db eval { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1 ( + id1 INTEGER, + value1 INTEGER, + x1 INTEGER + ); + INSERT INTO t1 VALUES(4469,2,98),(4469,1,99),(4469,3,97); + CREATE TABLE t2 ( + value2 INTEGER + ); + INSERT INTO t2 VALUES(1); + SELECT + (SELECT sum(value2==xyz) FROM t2) + FROM + (SELECT value1 as xyz, max(x1) AS pqr + FROM t1 + GROUP BY id1); + } +} {0} +do_test aggnested-3.3 { + db eval { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(id1, value1); + INSERT INTO t1 VALUES(4469,2),(4469,1); + CREATE TABLE t2 (value2); + INSERT INTO t2 VALUES(1); + SELECT (SELECT sum(value2=value1) FROM t2), max(value1) + FROM t1 + GROUP BY id1; + } +} {0 2} + +# A batch of queries all doing approximately the same operation involving +# two nested aggregate queries. +# +do_test aggnested-3.11 { + db eval { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(id1, value1); + INSERT INTO t1 VALUES(4469,12),(4469,11),(4470,34); + CREATE INDEX t1id1 ON t1(id1); + CREATE TABLE t2 (value2); + INSERT INTO t2 VALUES(12),(34),(34); + INSERT INTO t2 SELECT value2 FROM t2; + + SELECT max(value1), (SELECT count(*) FROM t2 WHERE value2=max(value1)) + FROM t1 + GROUP BY id1; + } +} {12 2 34 4} +do_test aggnested-3.12 { + db eval { + SELECT max(value1), (SELECT count(*) FROM t2 WHERE value2=value1) + FROM t1 + GROUP BY id1; + } +} {12 2 34 4} +do_test aggnested-3.13 { + db eval { + SELECT value1, (SELECT sum(value2=value1) FROM t2) + FROM t1; + } +} {12 2 11 0 34 4} +do_test aggnested-3.14 { + db eval { + SELECT value1, (SELECT sum(value2=value1) FROM t2) + FROM t1 + WHERE value1 IN (SELECT max(value1) FROM t1 GROUP BY id1); + } +} {12 2 34 4} +do_test aggnested-3.15 { + # FIXME: If case 3.16 works, then this case really ought to work too... + catchsql { + SELECT max(value1), (SELECT sum(value2=max(value1)) FROM t2) + FROM t1 + GROUP BY id1; + } +} {1 {misuse of aggregate function max()}} +do_test aggnested-3.16 { + db eval { + SELECT max(value1), (SELECT sum(value2=value1) FROM t2) + FROM t1 + GROUP BY id1; + } +} {12 2 34 4} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/alias.test b/components/external/SQLite-3.8.1/test/alias.test new file mode 100644 index 0000000000000000000000000000000000000000..290798974b74c2e680d4af75c8e122f6f22ade89 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/alias.test @@ -0,0 +1,140 @@ +# 2008 August 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this script is correct code generation of aliased result-set +# values. See ticket #3343. +# +# $Id: alias.test,v 1.3 2009/04/23 13:22:44 drh Exp $ +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Aliases are currently evaluated twice. We might try to change this +# in the future. But not now. +return + +# A procedure to return a sequence of increasing integers. +# +namespace eval ::seq { + variable counter 0 + proc value {args} { + variable counter + incr counter + return $counter + } + proc reset {} { + variable counter + set counter 0 + } +} + + +do_test alias-1.1 { + db function sequence ::seq::value + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(9); + INSERT INTO t1 VALUES(8); + INSERT INTO t1 VALUES(7); + SELECT x, sequence() FROM t1; + } +} {9 1 8 2 7 3} +do_test alias-1.2 { + ::seq::reset + db eval { + SELECT x, sequence() AS y FROM t1 WHERE y>0 + } +} {9 1 8 2 7 3} +do_test alias-1.3 { + ::seq::reset + db eval { + SELECT x, sequence() AS y FROM t1 WHERE y>0 AND y<99 + } +} {9 1 8 2 7 3} +do_test alias-1.4 { + ::seq::reset + db eval { + SELECT x, sequence() AS y FROM t1 WHERE y>0 AND y<99 AND y!=55 + } +} {9 1 8 2 7 3} +do_test alias-1.5 { + ::seq::reset + db eval { + SELECT x, sequence() AS y FROM t1 + WHERE y>0 AND y<99 AND y!=55 AND y NOT IN (56,57,58) + AND y NOT LIKE 'abc%' AND y%10==2 + } +} {8 2} +do_test alias-1.6 { + ::seq::reset + db eval { + SELECT x, sequence() AS y FROM t1 WHERE y BETWEEN 0 AND 99 + } +} {9 1 8 2 7 3} +#do_test alias-1.7 { +# ::seq::reset +# db eval { +# SELECT x, sequence() AS y FROM t1 WHERE y IN (55,66,3) +# } +#} {7 3} +do_test alias-1.8 { + ::seq::reset + db eval { + SELECT x, 1-sequence() AS y FROM t1 ORDER BY y + } +} {7 -2 8 -1 9 0} +do_test alias-1.9 { + ::seq::reset + db eval { + SELECT x, sequence() AS y FROM t1 ORDER BY -y + } +} {7 3 8 2 9 1} +do_test alias-1.10 { + ::seq::reset + db eval { + SELECT x, sequence() AS y FROM t1 ORDER BY x%2, y + } +} {8 2 9 1 7 3} + +unset -nocomplain random_int_list +set random_int_list [db eval { + SELECT random()&2147483647 AS r FROM t1, t1, t1, t1 ORDER BY r +}] +do_test alias-1.11 { + lsort -integer $::random_int_list +} $random_int_list + + +do_test alias-2.1 { + db eval { + SELECT 4 UNION SELECT 1 ORDER BY 1 + } +} {1 4} +do_test alias-2.2 { + db eval { + SELECT 4 UNION SELECT 1 UNION SELECT 9 ORDER BY 1 + } +} {1 4 9} + +if 0 { + # Aliases in the GROUP BY clause cause the expression to be evaluated + # twice in the current implementation. This might change in the future. + # + do_test alias-3.1 { + ::seq::reset + db eval { + SELECT sequence(*) AS y, count(*) AS z FROM t1 GROUP BY y ORDER BY z, y + } + } {1 1 2 1 3 1} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/all.test b/components/external/SQLite-3.8.1/test/all.test new file mode 100644 index 0000000000000000000000000000000000000000..f6e722f2dfaa0360333611b0378793ba4099dfc9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/all.test @@ -0,0 +1,50 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs all tests. +# + +set testdir [file dirname $argv0] +source $testdir/permutations.test + +run_test_suite full + +run_test_suite no_optimization +run_test_suite memsubsys1 +run_test_suite memsubsys2 +run_test_suite singlethread +run_test_suite multithread +run_test_suite onefile +run_test_suite utf16 +run_test_suite exclusive +run_test_suite persistent_journal +run_test_suite persistent_journal_error +run_test_suite no_journal +run_test_suite no_journal_error +run_test_suite autovacuum_ioerr +run_test_suite no_mutex_try +run_test_suite fullmutex +run_test_suite journaltest +run_test_suite inmemory_journal +run_test_suite pcache0 +run_test_suite pcache10 +run_test_suite pcache50 +run_test_suite pcache90 +run_test_suite pcache100 +run_test_suite prepare +run_test_suite mmap + +if {$::tcl_platform(platform)=="unix"} { + ifcapable !default_autovacuum { + run_test_suite autovacuum_crash + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/alter.test b/components/external/SQLite-3.8.1/test/alter.test new file mode 100644 index 0000000000000000000000000000000000000000..1ccea22624ba99f9dd78abd12b7fa189b3aba0e4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/alter.test @@ -0,0 +1,864 @@ +# 2004 November 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the ALTER TABLE statement. +# +# $Id: alter.test,v 1.32 2009/03/24 15:08:10 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_OMIT_ALTERTABLE is defined, omit this file. +ifcapable !altertable { + finish_test + return +} + +#---------------------------------------------------------------------- +# Test organization: +# +# alter-1.1.* - alter-1.7.*: Basic tests of ALTER TABLE, including tables +# with implicit and explicit indices. These tests came from an earlier +# fork of SQLite that also supported ALTER TABLE. +# alter-1.8.*: Tests for ALTER TABLE when the table resides in an +# attached database. +# alter-1.9.*: Tests for ALTER TABLE when their is whitespace between the +# table name and left parenthesis token. i.e: +# "CREATE TABLE abc (a, b, c);" +# alter-2.*: Test error conditions and messages. +# alter-3.*: Test ALTER TABLE on tables that have TRIGGERs attached to them. +# alter-4.*: Test ALTER TABLE on tables that have AUTOINCREMENT fields. +# ... +# alter-12.*: Test ALTER TABLE on views. +# + +# Create some tables to rename. Be sure to include some TEMP tables +# and some tables with odd names. +# +do_test alter-1.1 { + ifcapable tempdb { + set ::temp TEMP + } else { + set ::temp {} + } + execsql [subst -nocommands { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + CREATE TABLE [t1'x1](c UNIQUE, b PRIMARY KEY); + INSERT INTO [t1'x1] VALUES(3,4); + CREATE INDEX t1i1 ON T1(B); + CREATE INDEX t1i2 ON t1(a,b); + CREATE INDEX i3 ON [t1'x1](b,c); + CREATE $::temp TABLE "temp table"(e,f,g UNIQUE); + CREATE INDEX i2 ON [temp table](f); + INSERT INTO [temp table] VALUES(5,6,7); + }] + execsql { + SELECT 't1', * FROM t1; + SELECT 't1''x1', * FROM "t1'x1"; + SELECT * FROM [temp table]; + } +} {t1 1 2 t1'x1 3 4 5 6 7} +do_test alter-1.2 { + execsql [subst { + CREATE $::temp TABLE objlist(type, name, tbl_name); + INSERT INTO objlist SELECT type, name, tbl_name + FROM sqlite_master WHERE NAME!='objlist'; + }] + ifcapable tempdb { + execsql { + INSERT INTO objlist SELECT type, name, tbl_name + FROM sqlite_temp_master WHERE NAME!='objlist'; + } + } + + execsql { + SELECT type, name, tbl_name FROM objlist ORDER BY tbl_name, type desc, name; + } +} [list \ + table t1 t1 \ + index t1i1 t1 \ + index t1i2 t1 \ + table t1'x1 t1'x1 \ + index i3 t1'x1 \ + index {sqlite_autoindex_t1'x1_1} t1'x1 \ + index {sqlite_autoindex_t1'x1_2} t1'x1 \ + table {temp table} {temp table} \ + index i2 {temp table} \ + index {sqlite_autoindex_temp table_1} {temp table} \ + ] + +# Make some changes +# +integrity_check alter-1.3.0 +do_test alter-1.3 { + execsql { + ALTER TABLE [T1] RENAME to [-t1-]; + ALTER TABLE "t1'x1" RENAME TO T2; + ALTER TABLE [temp table] RENAME to TempTab; + } +} {} +integrity_check alter-1.3.1 +do_test alter-1.4 { + execsql { + SELECT 't1', * FROM [-t1-]; + SELECT 't2', * FROM t2; + SELECT * FROM temptab; + } +} {t1 1 2 t2 3 4 5 6 7} +do_test alter-1.5 { + execsql { + DELETE FROM objlist; + INSERT INTO objlist SELECT type, name, tbl_name + FROM sqlite_master WHERE NAME!='objlist'; + } + catchsql { + INSERT INTO objlist SELECT type, name, tbl_name + FROM sqlite_temp_master WHERE NAME!='objlist'; + } + execsql { + SELECT type, name, tbl_name FROM objlist ORDER BY tbl_name, type desc, name; + } +} [list \ + table -t1- -t1- \ + index t1i1 -t1- \ + index t1i2 -t1- \ + table T2 T2 \ + index i3 T2 \ + index {sqlite_autoindex_T2_1} T2 \ + index {sqlite_autoindex_T2_2} T2 \ + table {TempTab} {TempTab} \ + index i2 {TempTab} \ + index {sqlite_autoindex_TempTab_1} {TempTab} \ + ] + +# Make sure the changes persist after restarting the database. +# (The TEMP table will not persist, of course.) +# +ifcapable tempdb { + do_test alter-1.6 { + db close + sqlite3 db test.db + set DB [sqlite3_connection_pointer db] + execsql { + CREATE TEMP TABLE objlist(type, name, tbl_name); + INSERT INTO objlist SELECT type, name, tbl_name FROM sqlite_master; + INSERT INTO objlist + SELECT type, name, tbl_name FROM sqlite_temp_master + WHERE NAME!='objlist'; + SELECT type, name, tbl_name FROM objlist + ORDER BY tbl_name, type desc, name; + } + } [list \ + table -t1- -t1- \ + index t1i1 -t1- \ + index t1i2 -t1- \ + table T2 T2 \ + index i3 T2 \ + index {sqlite_autoindex_T2_1} T2 \ + index {sqlite_autoindex_T2_2} T2 \ + ] +} else { + execsql { + DROP TABLE TempTab; + } +} + +# Create bogus application-defined functions for functions used +# internally by ALTER TABLE, to ensure that ALTER TABLE falls back +# to the built-in functions. +# +proc failing_app_func {args} {error "bad function"} +do_test alter-1.7-prep { + db func substr failing_app_func + db func like failing_app_func + db func sqlite_rename_table failing_app_func + db func sqlite_rename_trigger failing_app_func + db func sqlite_rename_parent failing_app_func + catchsql {SELECT substr(name,1,3) FROM sqlite_master} +} {1 {bad function}} + +# Make sure the ALTER TABLE statements work with the +# non-callback API +# +do_test alter-1.7 { + stepsql $DB { + ALTER TABLE [-t1-] RENAME to [*t1*]; + ALTER TABLE T2 RENAME TO []; + } + execsql { + DELETE FROM objlist; + INSERT INTO objlist SELECT type, name, tbl_name + FROM sqlite_master WHERE NAME!='objlist'; + } + catchsql { + INSERT INTO objlist SELECT type, name, tbl_name + FROM sqlite_temp_master WHERE NAME!='objlist'; + } + execsql { + SELECT type, name, tbl_name FROM objlist ORDER BY tbl_name, type desc, name; + } +} [list \ + table *t1* *t1* \ + index t1i1 *t1* \ + index t1i2 *t1* \ + table \ + index i3 \ + index {sqlite_autoindex__1} \ + index {sqlite_autoindex__2} \ + ] + +# Check that ALTER TABLE works on attached databases. +# +ifcapable attach { + do_test alter-1.8.1 { + forcedelete test2.db + forcedelete test2.db-journal + execsql { + ATTACH 'test2.db' AS aux; + } + } {} + do_test alter-1.8.2 { + execsql { + CREATE TABLE t4(a PRIMARY KEY, b, c); + CREATE TABLE aux.t4(a PRIMARY KEY, b, c); + CREATE INDEX i4 ON t4(b); + CREATE INDEX aux.i4 ON t4(b); + } + } {} + do_test alter-1.8.3 { + execsql { + INSERT INTO t4 VALUES('main', 'main', 'main'); + INSERT INTO aux.t4 VALUES('aux', 'aux', 'aux'); + SELECT * FROM t4 WHERE a = 'main'; + } + } {main main main} + do_test alter-1.8.4 { + execsql { + ALTER TABLE t4 RENAME TO t5; + SELECT * FROM t4 WHERE a = 'aux'; + } + } {aux aux aux} + do_test alter-1.8.5 { + execsql { + SELECT * FROM t5; + } + } {main main main} + do_test alter-1.8.6 { + execsql { + SELECT * FROM t5 WHERE b = 'main'; + } + } {main main main} + do_test alter-1.8.7 { + execsql { + ALTER TABLE aux.t4 RENAME TO t5; + SELECT * FROM aux.t5 WHERE b = 'aux'; + } + } {aux aux aux} +} + +do_test alter-1.9.1 { + execsql { + CREATE TABLE tbl1 (a, b, c); + INSERT INTO tbl1 VALUES(1, 2, 3); + } +} {} +do_test alter-1.9.2 { + execsql { + SELECT * FROM tbl1; + } +} {1 2 3} +do_test alter-1.9.3 { + execsql { + ALTER TABLE tbl1 RENAME TO tbl2; + SELECT * FROM tbl2; + } +} {1 2 3} +do_test alter-1.9.4 { + execsql { + DROP TABLE tbl2; + } +} {} + +# Test error messages +# +do_test alter-2.1 { + catchsql { + ALTER TABLE none RENAME TO hi; + } +} {1 {no such table: none}} +do_test alter-2.2 { + execsql { + CREATE TABLE t3(p,q,r); + } + catchsql { + ALTER TABLE [] RENAME TO t3; + } +} {1 {there is already another table or index with this name: t3}} +do_test alter-2.3 { + catchsql { + ALTER TABLE [] RENAME TO i3; + } +} {1 {there is already another table or index with this name: i3}} +do_test alter-2.4 { + catchsql { + ALTER TABLE SqLiTe_master RENAME TO master; + } +} {1 {table sqlite_master may not be altered}} +do_test alter-2.5 { + catchsql { + ALTER TABLE t3 RENAME TO sqlite_t3; + } +} {1 {object name reserved for internal use: sqlite_t3}} +do_test alter-2.6 { + catchsql { + ALTER TABLE t3 ADD COLUMN (ALTER TABLE t3 ADD COLUMN); + } +} {1 {near "(": syntax error}} + +# If this compilation does not include triggers, omit the alter-3.* tests. +ifcapable trigger { + +#----------------------------------------------------------------------- +# Tests alter-3.* test ALTER TABLE on tables that have triggers. +# +# alter-3.1.*: ALTER TABLE with triggers. +# alter-3.2.*: Test that the ON keyword cannot be used as a database, +# table or column name unquoted. This is done because part of the +# ALTER TABLE code (specifically the implementation of SQL function +# "sqlite_alter_trigger") will break in this case. +# alter-3.3.*: ALTER TABLE with TEMP triggers (todo). +# + +# An SQL user-function for triggers to fire, so that we know they +# are working. +proc trigfunc {args} { + set ::TRIGGER $args +} +db func trigfunc trigfunc + +do_test alter-3.1.0 { + execsql { + CREATE TABLE t6(a, b, c); + -- Different case for the table name in the trigger. + CREATE TRIGGER trig1 AFTER INSERT ON T6 BEGIN + SELECT trigfunc('trig1', new.a, new.b, new.c); + END; + } +} {} +do_test alter-3.1.1 { + execsql { + INSERT INTO t6 VALUES(1, 2, 3); + } + set ::TRIGGER +} {trig1 1 2 3} +do_test alter-3.1.2 { + execsql { + ALTER TABLE t6 RENAME TO t7; + INSERT INTO t7 VALUES(4, 5, 6); + } + set ::TRIGGER +} {trig1 4 5 6} +do_test alter-3.1.3 { + execsql { + DROP TRIGGER trig1; + } +} {} +do_test alter-3.1.4 { + execsql { + CREATE TRIGGER trig2 AFTER INSERT ON main.t7 BEGIN + SELECT trigfunc('trig2', new.a, new.b, new.c); + END; + INSERT INTO t7 VALUES(1, 2, 3); + } + set ::TRIGGER +} {trig2 1 2 3} +do_test alter-3.1.5 { + execsql { + ALTER TABLE t7 RENAME TO t8; + INSERT INTO t8 VALUES(4, 5, 6); + } + set ::TRIGGER +} {trig2 4 5 6} +do_test alter-3.1.6 { + execsql { + DROP TRIGGER trig2; + } +} {} +do_test alter-3.1.7 { + execsql { + CREATE TRIGGER trig3 AFTER INSERT ON main.'t8'BEGIN + SELECT trigfunc('trig3', new.a, new.b, new.c); + END; + INSERT INTO t8 VALUES(1, 2, 3); + } + set ::TRIGGER +} {trig3 1 2 3} +do_test alter-3.1.8 { + execsql { + ALTER TABLE t8 RENAME TO t9; + INSERT INTO t9 VALUES(4, 5, 6); + } + set ::TRIGGER +} {trig3 4 5 6} + +# Make sure "ON" cannot be used as a database, table or column name without +# quoting. Otherwise the sqlite_alter_trigger() function might not work. +forcedelete test3.db +forcedelete test3.db-journal +ifcapable attach { + do_test alter-3.2.1 { + catchsql { + ATTACH 'test3.db' AS ON; + } + } {1 {near "ON": syntax error}} + do_test alter-3.2.2 { + catchsql { + ATTACH 'test3.db' AS 'ON'; + } + } {0 {}} + do_test alter-3.2.3 { + catchsql { + CREATE TABLE ON.t1(a, b, c); + } + } {1 {near "ON": syntax error}} + do_test alter-3.2.4 { + catchsql { + CREATE TABLE 'ON'.t1(a, b, c); + } + } {0 {}} + do_test alter-3.2.4 { + catchsql { + CREATE TABLE 'ON'.ON(a, b, c); + } + } {1 {near "ON": syntax error}} + do_test alter-3.2.5 { + catchsql { + CREATE TABLE 'ON'.'ON'(a, b, c); + } + } {0 {}} +} +do_test alter-3.2.6 { + catchsql { + CREATE TABLE t10(a, ON, c); + } +} {1 {near "ON": syntax error}} +do_test alter-3.2.7 { + catchsql { + CREATE TABLE t10(a, 'ON', c); + } +} {0 {}} +do_test alter-3.2.8 { + catchsql { + CREATE TRIGGER trig4 AFTER INSERT ON ON BEGIN SELECT 1; END; + } +} {1 {near "ON": syntax error}} +ifcapable attach { + do_test alter-3.2.9 { + catchsql { + CREATE TRIGGER 'on'.trig4 AFTER INSERT ON 'ON' BEGIN SELECT 1; END; + } + } {0 {}} +} +do_test alter-3.2.10 { + execsql { + DROP TABLE t10; + } +} {} + +do_test alter-3.3.1 { + execsql [subst { + CREATE TABLE tbl1(a, b, c); + CREATE $::temp TRIGGER trig1 AFTER INSERT ON tbl1 BEGIN + SELECT trigfunc('trig1', new.a, new.b, new.c); + END; + }] +} {} +do_test alter-3.3.2 { + execsql { + INSERT INTO tbl1 VALUES('a', 'b', 'c'); + } + set ::TRIGGER +} {trig1 a b c} +do_test alter-3.3.3 { + execsql { + ALTER TABLE tbl1 RENAME TO tbl2; + INSERT INTO tbl2 VALUES('d', 'e', 'f'); + } + set ::TRIGGER +} {trig1 d e f} +do_test alter-3.3.4 { + execsql [subst { + CREATE $::temp TRIGGER trig2 AFTER UPDATE ON tbl2 BEGIN + SELECT trigfunc('trig2', new.a, new.b, new.c); + END; + }] +} {} +do_test alter-3.3.5 { + execsql { + ALTER TABLE tbl2 RENAME TO tbl3; + INSERT INTO tbl3 VALUES('g', 'h', 'i'); + } + set ::TRIGGER +} {trig1 g h i} +do_test alter-3.3.6 { + execsql { + UPDATE tbl3 SET a = 'G' where a = 'g'; + } + set ::TRIGGER +} {trig2 G h i} +do_test alter-3.3.7 { + execsql { + DROP TABLE tbl3; + } +} {} +ifcapable tempdb { + do_test alter-3.3.8 { + execsql { + SELECT * FROM sqlite_temp_master WHERE type = 'trigger'; + } + } {} +} + +} ;# ifcapable trigger + +# If the build does not include AUTOINCREMENT fields, omit alter-4.*. +ifcapable autoinc { + +do_test alter-4.1 { + execsql { + CREATE TABLE tbl1(a INTEGER PRIMARY KEY AUTOINCREMENT); + INSERT INTO tbl1 VALUES(10); + } +} {} +do_test alter-4.2 { + execsql { + INSERT INTO tbl1 VALUES(NULL); + SELECT a FROM tbl1; + } +} {10 11} +do_test alter-4.3 { + execsql { + ALTER TABLE tbl1 RENAME TO tbl2; + DELETE FROM tbl2; + INSERT INTO tbl2 VALUES(NULL); + SELECT a FROM tbl2; + } +} {12} +do_test alter-4.4 { + execsql { + DROP TABLE tbl2; + } +} {} + +} ;# ifcapable autoinc + +# Test that it is Ok to execute an ALTER TABLE immediately after +# opening a database. +do_test alter-5.1 { + execsql { + CREATE TABLE tbl1(a, b, c); + INSERT INTO tbl1 VALUES('x', 'y', 'z'); + } +} {} +do_test alter-5.2 { + sqlite3 db2 test.db + execsql { + ALTER TABLE tbl1 RENAME TO tbl2; + SELECT * FROM tbl2; + } db2 +} {x y z} +do_test alter-5.3 { + db2 close +} {} + +foreach tblname [execsql { + SELECT name FROM sqlite_master + WHERE type='table' AND name NOT GLOB 'sqlite*' +}] { + execsql "DROP TABLE \"$tblname\"" +} + +set ::tbl_name "abc\uABCDdef" +do_test alter-6.1 { + string length $::tbl_name +} {7} +do_test alter-6.2 { + execsql " + CREATE TABLE ${tbl_name}(a, b, c); + " + set ::oid [execsql {SELECT max(oid) FROM sqlite_master}] + execsql " + SELECT sql FROM sqlite_master WHERE oid = $::oid; + " +} "{CREATE TABLE ${::tbl_name}(a, b, c)}" +execsql " + SELECT * FROM ${::tbl_name} +" +set ::tbl_name2 "abcXdef" +do_test alter-6.3 { + execsql " + ALTER TABLE $::tbl_name RENAME TO $::tbl_name2 + " + execsql " + SELECT sql FROM sqlite_master WHERE oid = $::oid + " +} "{CREATE TABLE \"${::tbl_name2}\"(a, b, c)}" +do_test alter-6.4 { + execsql " + ALTER TABLE $::tbl_name2 RENAME TO $::tbl_name + " + execsql " + SELECT sql FROM sqlite_master WHERE oid = $::oid + " +} "{CREATE TABLE \"${::tbl_name}\"(a, b, c)}" +set ::col_name ghi\1234\jkl +do_test alter-6.5 { + execsql " + ALTER TABLE $::tbl_name ADD COLUMN $::col_name VARCHAR + " + execsql " + SELECT sql FROM sqlite_master WHERE oid = $::oid + " +} "{CREATE TABLE \"${::tbl_name}\"(a, b, c, $::col_name VARCHAR)}" +set ::col_name2 B\3421\A +do_test alter-6.6 { + db close + sqlite3 db test.db + execsql " + ALTER TABLE $::tbl_name ADD COLUMN $::col_name2 + " + execsql " + SELECT sql FROM sqlite_master WHERE oid = $::oid + " +} "{CREATE TABLE \"${::tbl_name}\"(a, b, c, $::col_name VARCHAR, $::col_name2)}" +do_test alter-6.7 { + execsql " + INSERT INTO ${::tbl_name} VALUES(1, 2, 3, 4, 5); + SELECT $::col_name, $::col_name2 FROM $::tbl_name; + " +} {4 5} + +# Ticket #1665: Make sure ALTER TABLE ADD COLUMN works on a table +# that includes a COLLATE clause. +# +do_realnum_test alter-7.1 { + execsql { + CREATE TABLE t1(a TEXT COLLATE BINARY); + ALTER TABLE t1 ADD COLUMN b INTEGER COLLATE NOCASE; + INSERT INTO t1 VALUES(1,'-2'); + INSERT INTO t1 VALUES(5.4e-08,'5.4e-08'); + SELECT typeof(a), a, typeof(b), b FROM t1; + } +} {text 1 integer -2 text 5.4e-08 real 5.4e-08} + +# Make sure that when a column is added by ALTER TABLE ADD COLUMN and has +# a default value that the default value is used by aggregate functions. +# +do_test alter-8.1 { + execsql { + CREATE TABLE t2(a INTEGER); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(2); + ALTER TABLE t2 ADD COLUMN b INTEGER DEFAULT 9; + SELECT sum(b) FROM t2; + } +} {27} +do_test alter-8.2 { + execsql { + SELECT a, sum(b) FROM t2 GROUP BY a; + } +} {1 18 2 9} + +#-------------------------------------------------------------------------- +# alter-9.X - Special test: Make sure the sqlite_rename_trigger() and +# rename_table() functions do not crash when handed bad input. +# +ifcapable trigger { + do_test alter-9.1 { + execsql {SELECT SQLITE_RENAME_TRIGGER(0,0)} + } {{}} +} +do_test alter-9.2 { + execsql { + SELECT SQLITE_RENAME_TABLE(0,0); + SELECT SQLITE_RENAME_TABLE(10,20); + SELECT SQLITE_RENAME_TABLE('foo', 'foo'); + } +} {{} {} {}} + +#------------------------------------------------------------------------ +# alter-10.X - Make sure ALTER TABLE works with multi-byte UTF-8 characters +# in the names. +# +do_test alter-10.1 { + execsql "CREATE TABLE xyz(x UNIQUE)" + execsql "ALTER TABLE xyz RENAME TO xyz\u1234abc" + execsql {SELECT name FROM sqlite_master WHERE name GLOB 'xyz*'} +} [list xyz\u1234abc] +do_test alter-10.2 { + execsql {SELECT name FROM sqlite_master WHERE name GLOB 'sqlite_autoindex*'} +} [list sqlite_autoindex_xyz\u1234abc_1] +do_test alter-10.3 { + execsql "ALTER TABLE xyz\u1234abc RENAME TO xyzabc" + execsql {SELECT name FROM sqlite_master WHERE name GLOB 'xyz*'} +} [list xyzabc] +do_test alter-10.4 { + execsql {SELECT name FROM sqlite_master WHERE name GLOB 'sqlite_autoindex*'} +} [list sqlite_autoindex_xyzabc_1] + +do_test alter-11.1 { + sqlite3_exec db {CREATE TABLE t11(%c6%c6)} + execsql { + ALTER TABLE t11 ADD COLUMN abc; + } + catchsql { + ALTER TABLE t11 ADD COLUMN abc; + } +} {1 {duplicate column name: abc}} +set isutf16 [regexp 16 [db one {PRAGMA encoding}]] +if {!$isutf16} { + do_test alter-11.2 { + execsql {INSERT INTO t11 VALUES(1,2)} + sqlite3_exec db {SELECT %c6%c6 AS xyz, abc FROM t11} + } {0 {xyz abc 1 2}} +} +do_test alter-11.3 { + sqlite3_exec db {CREATE TABLE t11b("%81%82%83" text)} + execsql { + ALTER TABLE t11b ADD COLUMN abc; + } + catchsql { + ALTER TABLE t11b ADD COLUMN abc; + } +} {1 {duplicate column name: abc}} +if {!$isutf16} { + do_test alter-11.4 { + execsql {INSERT INTO t11b VALUES(3,4)} + sqlite3_exec db {SELECT %81%82%83 AS xyz, abc FROM t11b} + } {0 {xyz abc 3 4}} + do_test alter-11.5 { + sqlite3_exec db {SELECT [%81%82%83] AS xyz, abc FROM t11b} + } {0 {xyz abc 3 4}} + do_test alter-11.6 { + sqlite3_exec db {SELECT "%81%82%83" AS xyz, abc FROM t11b} + } {0 {xyz abc 3 4}} +} +do_test alter-11.7 { + sqlite3_exec db {CREATE TABLE t11c(%81%82%83 text)} + execsql { + ALTER TABLE t11c ADD COLUMN abc; + } + catchsql { + ALTER TABLE t11c ADD COLUMN abc; + } +} {1 {duplicate column name: abc}} +if {!$isutf16} { + do_test alter-11.8 { + execsql {INSERT INTO t11c VALUES(5,6)} + sqlite3_exec db {SELECT %81%82%83 AS xyz, abc FROM t11c} + } {0 {xyz abc 5 6}} + do_test alter-11.9 { + sqlite3_exec db {SELECT [%81%82%83] AS xyz, abc FROM t11c} + } {0 {xyz abc 5 6}} + do_test alter-11.10 { + sqlite3_exec db {SELECT "%81%82%83" AS xyz, abc FROM t11c} + } {0 {xyz abc 5 6}} +} + +do_test alter-12.1 { + execsql { + CREATE TABLE t12(a, b, c); + CREATE VIEW v1 AS SELECT * FROM t12; + } +} {} +do_test alter-12.2 { + catchsql { + ALTER TABLE v1 RENAME TO v2; + } +} {1 {view v1 may not be altered}} +do_test alter-12.3 { + execsql { SELECT * FROM v1; } +} {} +do_test alter-12.4 { + db close + sqlite3 db test.db + execsql { SELECT * FROM v1; } +} {} +do_test alter-12.5 { + catchsql { + ALTER TABLE v1 ADD COLUMN new_column; + } +} {1 {Cannot add a column to a view}} + +# Ticket #3102: +# Verify that comments do not interfere with the table rename +# algorithm. +# +do_test alter-13.1 { + execsql { + CREATE TABLE /* hi */ t3102a(x); + CREATE TABLE t3102b -- comment + (y); + CREATE INDEX t3102c ON t3102a(x); + SELECT name FROM sqlite_master WHERE name GLOB 't3102*' ORDER BY 1; + } +} {t3102a t3102b t3102c} +do_test alter-13.2 { + execsql { + ALTER TABLE t3102a RENAME TO t3102a_rename; + SELECT name FROM sqlite_master WHERE name GLOB 't3102*' ORDER BY 1; + } +} {t3102a_rename t3102b t3102c} +do_test alter-13.3 { + execsql { + ALTER TABLE t3102b RENAME TO t3102b_rename; + SELECT name FROM sqlite_master WHERE name GLOB 't3102*' ORDER BY 1; + } +} {t3102a_rename t3102b_rename t3102c} + +# Ticket #3651 +do_test alter-14.1 { + catchsql { + CREATE TABLE t3651(a UNIQUE); + ALTER TABLE t3651 ADD COLUMN b UNIQUE; + } +} {1 {Cannot add a UNIQUE column}} +do_test alter-14.2 { + catchsql { + ALTER TABLE t3651 ADD COLUMN b PRIMARY KEY; + } +} {1 {Cannot add a PRIMARY KEY column}} + + +#------------------------------------------------------------------------- +# Test that it is not possible to use ALTER TABLE on any system table. +# +set system_table_list {1 sqlite_master} +catchsql ANALYZE +ifcapable analyze { lappend system_table_list 2 sqlite_stat1 } +ifcapable stat3 { lappend system_table_list 3 sqlite_stat3 } +ifcapable stat4 { lappend system_table_list 4 sqlite_stat4 } + +foreach {tn tbl} $system_table_list { + do_test alter-15.$tn.1 { + catchsql "ALTER TABLE $tbl RENAME TO xyz" + } [list 1 "table $tbl may not be altered"] + + do_test alter-15.$tn.2 { + catchsql "ALTER TABLE $tbl ADD COLUMN xyz" + } [list 1 "table $tbl may not be altered"] +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/alter2.test b/components/external/SQLite-3.8.1/test/alter2.test new file mode 100644 index 0000000000000000000000000000000000000000..14be637f970ffd3a6a6875420a2196faf3e05a71 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/alter2.test @@ -0,0 +1,468 @@ +# 2005 February 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing that SQLite can handle a subtle +# file format change that may be used in the future to implement +# "ALTER TABLE ... ADD COLUMN". +# +# $Id: alter2.test,v 1.14 2009/04/07 14:14:22 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# We have to have pragmas in order to do this test +ifcapable {!pragma} return + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts. See proc [set_file_format]. +# +do_not_use_codec + +# The file format change affects the way row-records stored in tables (but +# not indices) are interpreted. Before version 3.1.3, a row-record for a +# table with N columns was guaranteed to contain exactly N fields. As +# of version 3.1.3, the record may contain up to N fields. In this case +# the M fields that are present are the values for the left-most M +# columns. The (N-M) rightmost columns contain NULL. +# +# If any records in the database contain less fields than their table +# has columns, then the file-format meta value should be set to (at least) 2. +# + +# This procedure sets the value of the file-format in file 'test.db' +# to $newval. Also, the schema cookie is incremented. +# +proc set_file_format {newval} { + hexio_write test.db 44 [hexio_render_int32 $newval] + set schemacookie [hexio_get_int [hexio_read test.db 40 4]] + incr schemacookie + hexio_write test.db 40 [hexio_render_int32 $schemacookie] + return {} +} + +# This procedure returns the value of the file-format in file 'test.db'. +# +proc get_file_format {{fname test.db}} { + return [hexio_get_int [hexio_read $fname 44 4]] +} + +# This procedure sets the SQL statement stored for table $tbl in the +# sqlite_master table of file 'test.db' to $sql. Also set the file format +# to the supplied value. This is 2 if the added column has a default that is +# NULL, or 3 otherwise. +# +proc alter_table {tbl sql {file_format 2}} { + sqlite3 dbat test.db + set s [string map {' ''} $sql] + set t [string map {' ''} $tbl] + dbat eval [subst { + PRAGMA writable_schema = 1; + UPDATE sqlite_master SET sql = '$s' WHERE name = '$t' AND type = 'table'; + PRAGMA writable_schema = 0; + }] + dbat close + set_file_format 2 +} + +# Create bogus application-defined functions for functions used +# internally by ALTER TABLE, to ensure that ALTER TABLE falls back +# to the built-in functions. +# +proc failing_app_func {args} {error "bad function"} +do_test alter2-1.0 { + db func substr failing_app_func + db func like failing_app_func + db func sqlite_rename_table failing_app_func + db func sqlite_rename_trigger failing_app_func + db func sqlite_rename_parent failing_app_func + catchsql {SELECT substr('abcdefg',1,3)} +} {1 {bad function}} + + +#----------------------------------------------------------------------- +# Some basic tests to make sure short rows are handled. +# +do_test alter2-1.1 { + execsql { + CREATE TABLE abc(a, b); + INSERT INTO abc VALUES(1, 2); + INSERT INTO abc VALUES(3, 4); + INSERT INTO abc VALUES(5, 6); + } +} {} +do_test alter2-1.2 { + # ALTER TABLE abc ADD COLUMN c; + alter_table abc {CREATE TABLE abc(a, b, c);} +} {} +do_test alter2-1.3 { + execsql { + SELECT * FROM abc; + } +} {1 2 {} 3 4 {} 5 6 {}} +do_test alter2-1.4 { + execsql { + UPDATE abc SET c = 10 WHERE a = 1; + SELECT * FROM abc; + } +} {1 2 10 3 4 {} 5 6 {}} +do_test alter2-1.5 { + execsql { + CREATE INDEX abc_i ON abc(c); + } +} {} +do_test alter2-1.6 { + execsql { + SELECT c FROM abc ORDER BY c; + } +} {{} {} 10} +do_test alter2-1.7 { + execsql { + SELECT * FROM abc WHERE c = 10; + } +} {1 2 10} +do_test alter2-1.8 { + execsql { + SELECT sum(a), c FROM abc GROUP BY c; + } +} {8 {} 1 10} +do_test alter2-1.9 { + # ALTER TABLE abc ADD COLUMN d; + alter_table abc {CREATE TABLE abc(a, b, c, d);} + if {[permutation] == "prepare"} { db cache flush } + execsql { SELECT * FROM abc; } + execsql { + UPDATE abc SET d = 11 WHERE c IS NULL AND a<4; + SELECT * FROM abc; + } +} {1 2 10 {} 3 4 {} 11 5 6 {} {}} +do_test alter2-1.10 { + execsql { + SELECT typeof(d) FROM abc; + } +} {null integer null} +do_test alter2-1.99 { + execsql { + DROP TABLE abc; + } +} {} + +#----------------------------------------------------------------------- +# Test that views work when the underlying table structure is changed. +# +ifcapable view { + do_test alter2-2.1 { + execsql { + CREATE TABLE abc2(a, b, c); + INSERT INTO abc2 VALUES(1, 2, 10); + INSERT INTO abc2 VALUES(3, 4, NULL); + INSERT INTO abc2 VALUES(5, 6, NULL); + CREATE VIEW abc2_v AS SELECT * FROM abc2; + SELECT * FROM abc2_v; + } + } {1 2 10 3 4 {} 5 6 {}} + do_test alter2-2.2 { + # ALTER TABLE abc ADD COLUMN d; + alter_table abc2 {CREATE TABLE abc2(a, b, c, d);} + execsql { + SELECT * FROM abc2_v; + } + } {1 2 10 {} 3 4 {} {} 5 6 {} {}} + do_test alter2-2.3 { + execsql { + DROP TABLE abc2; + DROP VIEW abc2_v; + } + } {} +} + +#----------------------------------------------------------------------- +# Test that triggers work when a short row is copied to the old.* +# trigger pseudo-table. +# +ifcapable trigger { + do_test alter2-3.1 { + execsql { + CREATE TABLE abc3(a, b); + CREATE TABLE blog(o, n); + CREATE TRIGGER abc3_t AFTER UPDATE OF b ON abc3 BEGIN + INSERT INTO blog VALUES(old.b, new.b); + END; + } + } {} + do_test alter2-3.2 { + execsql { + INSERT INTO abc3 VALUES(1, 4); + UPDATE abc3 SET b = 2 WHERE b = 4; + SELECT * FROM blog; + } + } {4 2} + do_test alter2-3.3 { + execsql { + INSERT INTO abc3 VALUES(3, 4); + INSERT INTO abc3 VALUES(5, 6); + } + alter_table abc3 {CREATE TABLE abc3(a, b, c);} + execsql { + SELECT * FROM abc3; + } + } {1 2 {} 3 4 {} 5 6 {}} + do_test alter2-3.4 { + execsql { + UPDATE abc3 SET b = b*2 WHERE a<4; + SELECT * FROM abc3; + } + } {1 4 {} 3 8 {} 5 6 {}} + do_test alter2-3.5 { + execsql { + SELECT * FROM blog; + } + } {4 2 2 4 4 8} + + do_test alter2-3.6 { + execsql { + CREATE TABLE clog(o, n); + CREATE TRIGGER abc3_t2 AFTER UPDATE OF c ON abc3 BEGIN + INSERT INTO clog VALUES(old.c, new.c); + END; + UPDATE abc3 SET c = a*2; + SELECT * FROM clog; + } + } {{} 2 {} 6 {} 10} +} else { + execsql { CREATE TABLE abc3(a, b); } +} + +#--------------------------------------------------------------------- +# Check that an error occurs if the database is upgraded to a file +# format that SQLite does not support (in this case 5). Note: The +# file format is checked each time the schema is read, so changing the +# file format requires incrementing the schema cookie. +# +do_test alter2-4.1 { + db close + set_file_format 5 + catch { sqlite3 db test.db } + set {} {} +} {} +do_test alter2-4.2 { + # We have to run two queries here because the Tcl interface uses + # sqlite3_prepare_v2(). In this case, the first query encounters an + # SQLITE_SCHEMA error. Then, when trying to recompile the statement, the + # "unsupported file format" error is encountered. So the error code + # returned is SQLITE_SCHEMA, not SQLITE_ERROR as required by the following + # test case. + # + # When the query is attempted a second time, the same error message is + # returned but the error code is SQLITE_ERROR, because the unsupported + # file format was detected during a call to sqlite3_prepare(), not + # sqlite3_step(). + # + catchsql { SELECT * FROM sqlite_master; } + catchsql { SELECT * FROM sqlite_master; } +} {1 {unsupported file format}} +do_test alter2-4.3 { + sqlite3_errcode db +} {SQLITE_ERROR} +do_test alter2-4.4 { + set ::DB [sqlite3_connection_pointer db] + catchsql { + SELECT * FROM sqlite_master; + } +} {1 {unsupported file format}} +do_test alter2-4.5 { + sqlite3_errcode db +} {SQLITE_ERROR} + +#--------------------------------------------------------------------- +# Check that executing VACUUM on a file with file-format version 2 +# resets the file format to 1. +# +set default_file_format [expr $SQLITE_DEFAULT_FILE_FORMAT==4 ? 4 : 1] +ifcapable vacuum { + do_test alter2-5.1 { + set_file_format 2 + db close + sqlite3 db test.db + execsql {SELECT 1 FROM sqlite_master LIMIT 1;} + get_file_format + } {2} + do_test alter2-5.2 { + execsql { VACUUM } + } {} + do_test alter2-5.3 { + get_file_format + } $default_file_format +} + +#--------------------------------------------------------------------- +# Test that when a database with file-format 2 is opened, new +# databases are still created with file-format 1. +# +do_test alter2-6.1 { + db close + set_file_format 2 + sqlite3 db test.db + get_file_format +} {2} +ifcapable attach { + do_test alter2-6.2 { + forcedelete test2.db-journal + forcedelete test2.db + execsql { + ATTACH 'test2.db' AS aux; + CREATE TABLE aux.t1(a, b); + } + get_file_format test2.db + } $default_file_format +} +do_test alter2-6.3 { + execsql { + CREATE TABLE t1(a, b); + } + get_file_format +} {2} + +#--------------------------------------------------------------------- +# Test that types and values for columns added with default values +# other than NULL work with SELECT statements. +# +do_test alter2-7.1 { + execsql { + DROP TABLE t1; + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + SELECT * FROM t1; + } +} {1 2 3 4} +do_test alter2-7.2 { + set sql {CREATE TABLE t1(a, b DEFAULT '123', c INTEGER DEFAULT '123')} + alter_table t1 $sql 3 + execsql { + SELECT * FROM t1 LIMIT 1; + } +} {1 123 123} +do_test alter2-7.3 { + execsql { + SELECT a, typeof(a), b, typeof(b), c, typeof(c) FROM t1 LIMIT 1; + } +} {1 integer 123 text 123 integer} +do_test alter2-7.4 { + execsql { + SELECT a, typeof(a), b, typeof(b), c, typeof(c) FROM t1 LIMIT 1; + } +} {1 integer 123 text 123 integer} +do_test alter2-7.5 { + set sql {CREATE TABLE t1(a, b DEFAULT -123.0, c VARCHAR(10) default 5)} + alter_table t1 $sql 3 + execsql { + SELECT a, typeof(a), b, typeof(b), c, typeof(c) FROM t1 LIMIT 1; + } +} {1 integer -123 integer 5 text} + +#----------------------------------------------------------------------- +# Test that UPDATE trigger tables work with default values, and that when +# a row is updated the default values are correctly transfered to the +# new row. +# +ifcapable trigger { +db function set_val {set ::val} + do_test alter2-8.1 { + execsql { + CREATE TRIGGER trig1 BEFORE UPDATE ON t1 BEGIN + SELECT set_val( + old.b||' '||typeof(old.b)||' '||old.c||' '||typeof(old.c)||' '|| + new.b||' '||typeof(new.b)||' '||new.c||' '||typeof(new.c) + ); + END; + } + list + } {} +} +do_test alter2-8.2 { + execsql { + UPDATE t1 SET c = 10 WHERE a = 1; + SELECT a, typeof(a), b, typeof(b), c, typeof(c) FROM t1 LIMIT 1; + } +} {1 integer -123 integer 10 text} +ifcapable trigger { + do_test alter2-8.3 { + set ::val + } {-123 integer 5 text -123 integer 10 text} +} + +#----------------------------------------------------------------------- +# Test that DELETE trigger tables work with default values, and that when +# a row is updated the default values are correctly transfered to the +# new row. +# +ifcapable trigger { + do_test alter2-9.1 { + execsql { + CREATE TRIGGER trig2 BEFORE DELETE ON t1 BEGIN + SELECT set_val( + old.b||' '||typeof(old.b)||' '||old.c||' '||typeof(old.c) + ); + END; + } + list + } {} + do_test alter2-9.2 { + execsql { + DELETE FROM t1 WHERE a = 2; + } + set ::val + } {-123 integer 5 text} +} + +#----------------------------------------------------------------------- +# Test creating an index on a column added with a default value. +# +ifcapable bloblit { + do_test alter2-10.1 { + execsql { + CREATE TABLE t2(a); + INSERT INTO t2 VALUES('a'); + INSERT INTO t2 VALUES('b'); + INSERT INTO t2 VALUES('c'); + INSERT INTO t2 VALUES('d'); + } + alter_table t2 {CREATE TABLE t2(a, b DEFAULT X'ABCD', c DEFAULT NULL);} 3 + catchsql { + SELECT * FROM sqlite_master; + } + execsql { + SELECT quote(a), quote(b), quote(c) FROM t2 LIMIT 1; + } + } {'a' X'ABCD' NULL} + do_test alter2-10.2 { + execsql { + CREATE INDEX i1 ON t2(b); + SELECT a FROM t2 WHERE b = X'ABCD'; + } + } {a b c d} + do_test alter2-10.3 { + execsql { + DELETE FROM t2 WHERE a = 'c'; + SELECT a FROM t2 WHERE b = X'ABCD'; + } + } {a b d} + do_test alter2-10.4 { + execsql { + SELECT count(b) FROM t2 WHERE b = X'ABCD'; + } + } {3} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/alter3.test b/components/external/SQLite-3.8.1/test/alter3.test new file mode 100644 index 0000000000000000000000000000000000000000..28d293e24bca55bc4c81b5c5308f99e337981261 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/alter3.test @@ -0,0 +1,397 @@ +# 2005 February 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing that SQLite can handle a subtle +# file format change that may be used in the future to implement +# "ALTER TABLE ... ADD COLUMN". +# +# $Id: alter3.test,v 1.11 2008/03/19 00:21:31 drh Exp $ +# + +set testdir [file dirname $argv0] + +source $testdir/tester.tcl + +# If SQLITE_OMIT_ALTERTABLE is defined, omit this file. +ifcapable !altertable { + finish_test + return +} + +# Determine if there is a codec available on this test. +# +if {[catch {sqlite3 -has-codec} r] || $r} { + set has_codec 1 +} else { + set has_codec 0 +} + + +# Test Organisation: +# ------------------ +# +# alter3-1.*: Test that ALTER TABLE correctly modifies the CREATE TABLE sql. +# alter3-2.*: Test error messages. +# alter3-3.*: Test adding columns with default value NULL. +# alter3-4.*: Test adding columns with default values other than NULL. +# alter3-5.*: Test adding columns to tables in ATTACHed databases. +# alter3-6.*: Test that temp triggers are not accidentally dropped. +# alter3-7.*: Test that VACUUM resets the file-format. +# + +# This procedure returns the value of the file-format in file 'test.db'. +# +proc get_file_format {{fname test.db}} { + return [hexio_get_int [hexio_read $fname 44 4]] +} + +do_test alter3-1.1 { + execsql { + PRAGMA legacy_file_format=ON; + CREATE TABLE abc(a, b, c); + SELECT sql FROM sqlite_master; + } +} {{CREATE TABLE abc(a, b, c)}} +do_test alter3-1.2 { + execsql {ALTER TABLE abc ADD d INTEGER;} + execsql { + SELECT sql FROM sqlite_master; + } +} {{CREATE TABLE abc(a, b, c, d INTEGER)}} +do_test alter3-1.3 { + execsql {ALTER TABLE abc ADD e} + execsql { + SELECT sql FROM sqlite_master; + } +} {{CREATE TABLE abc(a, b, c, d INTEGER, e)}} +do_test alter3-1.4 { + execsql { + CREATE TABLE main.t1(a, b); + ALTER TABLE t1 ADD c; + SELECT sql FROM sqlite_master WHERE tbl_name = 't1'; + } +} {{CREATE TABLE t1(a, b, c)}} +do_test alter3-1.5 { + execsql { + ALTER TABLE t1 ADD d CHECK (a>d); + SELECT sql FROM sqlite_master WHERE tbl_name = 't1'; + } +} {{CREATE TABLE t1(a, b, c, d CHECK (a>d))}} +ifcapable foreignkey { + do_test alter3-1.6 { + execsql { + CREATE TABLE t2(a, b, UNIQUE(a, b)); + ALTER TABLE t2 ADD c REFERENCES t1(c) ; + SELECT sql FROM sqlite_master WHERE tbl_name = 't2' AND type = 'table'; + } + } {{CREATE TABLE t2(a, b, c REFERENCES t1(c), UNIQUE(a, b))}} +} +do_test alter3-1.7 { + execsql { + CREATE TABLE t3(a, b, UNIQUE(a, b)); + ALTER TABLE t3 ADD COLUMN c VARCHAR(10, 20); + SELECT sql FROM sqlite_master WHERE tbl_name = 't3' AND type = 'table'; + } +} {{CREATE TABLE t3(a, b, c VARCHAR(10, 20), UNIQUE(a, b))}} +do_test alter3-1.99 { + catchsql { + # May not exist if foriegn-keys are omitted at compile time. + DROP TABLE t2; + } + execsql { + DROP TABLE abc; + DROP TABLE t1; + DROP TABLE t3; + } +} {} + +do_test alter3-2.1 { + execsql { + CREATE TABLE t1(a, b); + } + catchsql { + ALTER TABLE t1 ADD c PRIMARY KEY; + } +} {1 {Cannot add a PRIMARY KEY column}} +do_test alter3-2.2 { + catchsql { + ALTER TABLE t1 ADD c UNIQUE + } +} {1 {Cannot add a UNIQUE column}} +do_test alter3-2.3 { + catchsql { + ALTER TABLE t1 ADD b VARCHAR(10) + } +} {1 {duplicate column name: b}} +do_test alter3-2.3 { + catchsql { + ALTER TABLE t1 ADD c NOT NULL; + } +} {1 {Cannot add a NOT NULL column with default value NULL}} +do_test alter3-2.4 { + catchsql { + ALTER TABLE t1 ADD c NOT NULL DEFAULT 10; + } +} {0 {}} +ifcapable view { + do_test alter3-2.5 { + execsql { + CREATE VIEW v1 AS SELECT * FROM t1; + } + catchsql { + alter table v1 add column d; + } + } {1 {Cannot add a column to a view}} +} +do_test alter3-2.6 { + catchsql { + alter table t1 add column d DEFAULT CURRENT_TIME; + } +} {1 {Cannot add a column with non-constant default}} +do_test alter3-2.99 { + execsql { + DROP TABLE t1; + } +} {} + +do_test alter3-3.1 { + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 100); + INSERT INTO t1 VALUES(2, 300); + SELECT * FROM t1; + } +} {1 100 2 300} +do_test alter3-3.1 { + execsql { + PRAGMA schema_version = 10; + } +} {} +do_test alter3-3.2 { + execsql { + ALTER TABLE t1 ADD c; + SELECT * FROM t1; + } +} {1 100 {} 2 300 {}} +if {!$has_codec} { + do_test alter3-3.3 { + get_file_format + } {3} +} +ifcapable schema_version { + do_test alter3-3.4 { + execsql { + PRAGMA schema_version; + } + } {11} +} + +do_test alter3-4.1 { + db close + forcedelete test.db + set ::DB [sqlite3 db test.db] + execsql { + PRAGMA legacy_file_format=ON; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 100); + INSERT INTO t1 VALUES(2, 300); + SELECT * FROM t1; + } +} {1 100 2 300} +do_test alter3-4.1 { + execsql { + PRAGMA schema_version = 20; + } +} {} +do_test alter3-4.2 { + execsql { + ALTER TABLE t1 ADD c DEFAULT 'hello world'; + SELECT * FROM t1; + } +} {1 100 {hello world} 2 300 {hello world}} +if {!$has_codec} { + do_test alter3-4.3 { + get_file_format + } {3} +} +ifcapable schema_version { + do_test alter3-4.4 { + execsql { + PRAGMA schema_version; + } + } {21} +} +do_test alter3-4.99 { + execsql { + DROP TABLE t1; + } +} {} + +ifcapable attach { + do_test alter3-5.1 { + forcedelete test2.db + forcedelete test2.db-journal + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + ATTACH 'test2.db' AS aux; + CREATE TABLE aux.t1 AS SELECT * FROM t1; + PRAGMA aux.schema_version = 30; + SELECT sql FROM aux.sqlite_master; + } + } {{CREATE TABLE t1(a,b)}} + do_test alter3-5.2 { + execsql { + ALTER TABLE aux.t1 ADD COLUMN c VARCHAR(128); + SELECT sql FROM aux.sqlite_master; + } + } {{CREATE TABLE t1(a,b, c VARCHAR(128))}} + do_test alter3-5.3 { + execsql { + SELECT * FROM aux.t1; + } + } {1 one {} 2 two {}} + ifcapable schema_version { + do_test alter3-5.4 { + execsql { + PRAGMA aux.schema_version; + } + } {31} + } + if {!$has_codec} { + do_test alter3-5.5 { + list [get_file_format test2.db] [get_file_format] + } {2 3} + } + do_test alter3-5.6 { + execsql { + ALTER TABLE aux.t1 ADD COLUMN d DEFAULT 1000; + SELECT sql FROM aux.sqlite_master; + } + } {{CREATE TABLE t1(a,b, c VARCHAR(128), d DEFAULT 1000)}} + do_test alter3-5.7 { + execsql { + SELECT * FROM aux.t1; + } + } {1 one {} 1000 2 two {} 1000} + ifcapable schema_version { + do_test alter3-5.8 { + execsql { + PRAGMA aux.schema_version; + } + } {32} + } + do_test alter3-5.9 { + execsql { + SELECT * FROM t1; + } + } {1 one 2 two} + do_test alter3-5.99 { + execsql { + DROP TABLE aux.t1; + DROP TABLE t1; + } + } {} +} + +#---------------------------------------------------------------- +# Test that the table schema is correctly reloaded when a column +# is added to a table. +# +ifcapable trigger&&tempdb { + do_test alter3-6.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE TABLE log(trig, a, b); + + CREATE TRIGGER t1_a AFTER INSERT ON t1 BEGIN + INSERT INTO log VALUES('a', new.a, new.b); + END; + CREATE TEMP TRIGGER t1_b AFTER INSERT ON t1 BEGIN + INSERT INTO log VALUES('b', new.a, new.b); + END; + + INSERT INTO t1 VALUES(1, 2); + SELECT * FROM log; + } + } {b 1 2 a 1 2} + do_test alter3-6.2 { + execsql { + ALTER TABLE t1 ADD COLUMN c DEFAULT 'c'; + INSERT INTO t1(a, b) VALUES(3, 4); + SELECT * FROM log; + } + } {b 1 2 a 1 2 b 3 4 a 3 4} +} + +if {!$has_codec} { + ifcapable vacuum { + do_test alter3-7.1 { + execsql { + VACUUM; + } + get_file_format + } {1} + do_test alter3-7.2 { + execsql { + CREATE TABLE abc(a, b, c); + ALTER TABLE abc ADD d DEFAULT NULL; + } + get_file_format + } {2} + do_test alter3-7.3 { + execsql { + ALTER TABLE abc ADD e DEFAULT 10; + } + get_file_format + } {3} + do_test alter3-7.4 { + execsql { + ALTER TABLE abc ADD f DEFAULT NULL; + } + get_file_format + } {3} + do_test alter3-7.5 { + execsql { + VACUUM; + } + get_file_format + } {1} + } +} + +# Ticket #1183 - Make sure adding columns to large tables does not cause +# memory corruption (as was the case before this bug was fixed). +do_test alter3-8.1 { + execsql { + CREATE TABLE t4(c1); + } +} {} +set ::sql "" +do_test alter3-8.2 { + set cols c1 + for {set i 2} {$i < 100} {incr i} { + execsql " + ALTER TABLE t4 ADD c$i + " + lappend cols c$i + } + set ::sql "CREATE TABLE t4([join $cols {, }])" + list +} {} +do_test alter3-8.2 { + execsql { + SELECT sql FROM sqlite_master WHERE name = 't4'; + } +} [list $::sql] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/alter4.test b/components/external/SQLite-3.8.1/test/alter4.test new file mode 100644 index 0000000000000000000000000000000000000000..59704fed4c693a80451d344470fc9567cf0cc0ee --- /dev/null +++ b/components/external/SQLite-3.8.1/test/alter4.test @@ -0,0 +1,337 @@ +# 2009 February 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing that SQLite can handle a subtle +# file format change that may be used in the future to implement +# "ALTER TABLE ... ADD COLUMN". +# +# $Id: alter4.test,v 1.1 2009/02/02 18:03:22 drh Exp $ +# + +set testdir [file dirname $argv0] + +source $testdir/tester.tcl + +# If SQLITE_OMIT_ALTERTABLE is defined, omit this file. +ifcapable !altertable { + finish_test + return +} + + +# Test Organisation: +# ------------------ +# +# alter4-1.*: Test that ALTER TABLE correctly modifies the CREATE TABLE sql. +# alter4-2.*: Test error messages. +# alter4-3.*: Test adding columns with default value NULL. +# alter4-4.*: Test adding columns with default values other than NULL. +# alter4-5.*: Test adding columns to tables in ATTACHed databases. +# alter4-6.*: Test that temp triggers are not accidentally dropped. +# alter4-7.*: Test that VACUUM resets the file-format. +# + +do_test alter4-1.1 { + execsql { + CREATE TEMP TABLE abc(a, b, c); + SELECT sql FROM sqlite_temp_master; + } +} {{CREATE TABLE abc(a, b, c)}} +do_test alter4-1.2 { + execsql {ALTER TABLE abc ADD d INTEGER;} + execsql { + SELECT sql FROM sqlite_temp_master; + } +} {{CREATE TABLE abc(a, b, c, d INTEGER)}} +do_test alter4-1.3 { + execsql {ALTER TABLE abc ADD e} + execsql { + SELECT sql FROM sqlite_temp_master; + } +} {{CREATE TABLE abc(a, b, c, d INTEGER, e)}} +do_test alter4-1.4 { + execsql { + CREATE TABLE temp.t1(a, b); + ALTER TABLE t1 ADD c; + SELECT sql FROM sqlite_temp_master WHERE tbl_name = 't1'; + } +} {{CREATE TABLE t1(a, b, c)}} +do_test alter4-1.5 { + execsql { + ALTER TABLE t1 ADD d CHECK (a>d); + SELECT sql FROM sqlite_temp_master WHERE tbl_name = 't1'; + } +} {{CREATE TABLE t1(a, b, c, d CHECK (a>d))}} +ifcapable foreignkey { + do_test alter4-1.6 { + execsql { + CREATE TEMP TABLE t2(a, b, UNIQUE(a, b)); + ALTER TABLE t2 ADD c REFERENCES t1(c) ; + SELECT sql FROM sqlite_temp_master + WHERE tbl_name = 't2' AND type = 'table'; + } + } {{CREATE TABLE t2(a, b, c REFERENCES t1(c), UNIQUE(a, b))}} +} +do_test alter4-1.7 { + execsql { + CREATE TEMPORARY TABLE t3(a, b, UNIQUE(a, b)); + ALTER TABLE t3 ADD COLUMN c VARCHAR(10, 20); + SELECT sql FROM sqlite_temp_master + WHERE tbl_name = 't3' AND type = 'table'; + } +} {{CREATE TABLE t3(a, b, c VARCHAR(10, 20), UNIQUE(a, b))}} +do_test alter4-1.99 { + catchsql { + # May not exist if foriegn-keys are omitted at compile time. + DROP TABLE t2; + } + execsql { + DROP TABLE abc; + DROP TABLE t1; + DROP TABLE t3; + } +} {} + +do_test alter4-2.1 { + execsql { + CREATE TABLE temp.t1(a, b); + } + catchsql { + ALTER TABLE t1 ADD c PRIMARY KEY; + } +} {1 {Cannot add a PRIMARY KEY column}} +do_test alter4-2.2 { + catchsql { + ALTER TABLE t1 ADD c UNIQUE + } +} {1 {Cannot add a UNIQUE column}} +do_test alter4-2.3 { + catchsql { + ALTER TABLE t1 ADD b VARCHAR(10) + } +} {1 {duplicate column name: b}} +do_test alter4-2.3 { + catchsql { + ALTER TABLE t1 ADD c NOT NULL; + } +} {1 {Cannot add a NOT NULL column with default value NULL}} +do_test alter4-2.4 { + catchsql { + ALTER TABLE t1 ADD c NOT NULL DEFAULT 10; + } +} {0 {}} +ifcapable view { + do_test alter4-2.5 { + execsql { + CREATE TEMPORARY VIEW v1 AS SELECT * FROM t1; + } + catchsql { + alter table v1 add column d; + } + } {1 {Cannot add a column to a view}} +} +do_test alter4-2.6 { + catchsql { + alter table t1 add column d DEFAULT CURRENT_TIME; + } +} {1 {Cannot add a column with non-constant default}} +do_test alter4-2.7 { + catchsql { + alter table t1 add column d default (-+1); + } +} {1 {Cannot add a column with non-constant default}} +do_test alter4-2.99 { + execsql { + DROP TABLE t1; + } +} {} + +do_test alter4-3.1 { + execsql { + CREATE TEMP TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 100); + INSERT INTO t1 VALUES(2, 300); + SELECT * FROM t1; + } +} {1 100 2 300} +do_test alter4-3.1 { + execsql { + PRAGMA schema_version = 10; + } +} {} +do_test alter4-3.2 { + execsql { + ALTER TABLE t1 ADD c; + SELECT * FROM t1; + } +} {1 100 {} 2 300 {}} +ifcapable schema_version { + do_test alter4-3.4 { + execsql { + PRAGMA schema_version; + } + } {10} +} + +do_test alter4-4.1 { + db close + forcedelete test.db + set ::DB [sqlite3 db test.db] + execsql { + CREATE TEMP TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 100); + INSERT INTO t1 VALUES(2, 300); + SELECT * FROM t1; + } +} {1 100 2 300} +do_test alter4-4.1 { + execsql { + PRAGMA schema_version = 20; + } +} {} +do_test alter4-4.2 { + execsql { + ALTER TABLE t1 ADD c DEFAULT 'hello world'; + SELECT * FROM t1; + } +} {1 100 {hello world} 2 300 {hello world}} +ifcapable schema_version { + do_test alter4-4.4 { + execsql { + PRAGMA schema_version; + } + } {20} +} +do_test alter4-4.99 { + execsql { + DROP TABLE t1; + } +} {} + +ifcapable attach { + do_test alter4-5.1 { + forcedelete test2.db + forcedelete test2.db-journal + execsql { + CREATE TEMP TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + ATTACH 'test2.db' AS aux; + CREATE TABLE aux.t1 AS SELECT * FROM t1; + PRAGMA aux.schema_version = 30; + SELECT sql FROM aux.sqlite_master; + } + } {{CREATE TABLE t1(a,b)}} + do_test alter4-5.2 { + execsql { + ALTER TABLE aux.t1 ADD COLUMN c VARCHAR(128); + SELECT sql FROM aux.sqlite_master; + } + } {{CREATE TABLE t1(a,b, c VARCHAR(128))}} + do_test alter4-5.3 { + execsql { + SELECT * FROM aux.t1; + } + } {1 one {} 2 two {}} + ifcapable schema_version { + do_test alter4-5.4 { + execsql { + PRAGMA aux.schema_version; + } + } {31} + } + do_test alter4-5.6 { + execsql { + ALTER TABLE aux.t1 ADD COLUMN d DEFAULT 1000; + SELECT sql FROM aux.sqlite_master; + } + } {{CREATE TABLE t1(a,b, c VARCHAR(128), d DEFAULT 1000)}} + do_test alter4-5.7 { + execsql { + SELECT * FROM aux.t1; + } + } {1 one {} 1000 2 two {} 1000} + ifcapable schema_version { + do_test alter4-5.8 { + execsql { + PRAGMA aux.schema_version; + } + } {32} + } + do_test alter4-5.9 { + execsql { + SELECT * FROM t1; + } + } {1 one 2 two} + do_test alter4-5.99 { + execsql { + DROP TABLE aux.t1; + DROP TABLE t1; + } + } {} +} + +#---------------------------------------------------------------- +# Test that the table schema is correctly reloaded when a column +# is added to a table. +# +ifcapable trigger&&tempdb { + do_test alter4-6.1 { + execsql { + CREATE TEMP TABLE t1(a, b); + CREATE TEMP TABLE log(trig, a, b); + + CREATE TRIGGER t1_a AFTER INSERT ON t1 BEGIN + INSERT INTO log VALUES('a', new.a, new.b); + END; + CREATE TEMP TRIGGER t1_b AFTER INSERT ON t1 BEGIN + INSERT INTO log VALUES('b', new.a, new.b); + END; + + INSERT INTO t1 VALUES(1, 2); + SELECT * FROM log; + } + } {b 1 2 a 1 2} + do_test alter4-6.2 { + execsql { + ALTER TABLE t1 ADD COLUMN c DEFAULT 'c'; + INSERT INTO t1(a, b) VALUES(3, 4); + SELECT * FROM log; + } + } {b 1 2 a 1 2 b 3 4 a 3 4} +} + +# Ticket #1183 - Make sure adding columns to large tables does not cause +# memory corruption (as was the case before this bug was fixed). +do_test alter4-8.1 { + execsql { + CREATE TEMP TABLE t4(c1); + } +} {} +set ::sql "" +do_test alter4-8.2 { + set cols c1 + for {set i 2} {$i < 100} {incr i} { + execsql " + ALTER TABLE t4 ADD c$i + " + lappend cols c$i + } + set ::sql "CREATE TABLE t4([join $cols {, }])" + list +} {} +do_test alter4-8.2 { + execsql { + SELECT sql FROM sqlite_temp_master WHERE name = 't4'; + } +} [list $::sql] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/altermalloc.test b/components/external/SQLite-3.8.1/test/altermalloc.test new file mode 100644 index 0000000000000000000000000000000000000000..a35e7d5a345ca00707ad9a8bea90dc9d7f237bac --- /dev/null +++ b/components/external/SQLite-3.8.1/test/altermalloc.test @@ -0,0 +1,71 @@ +# 2005 September 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the ALTER TABLE statement and +# specifically out-of-memory conditions within that command. +# +# $Id: altermalloc.test,v 1.10 2008/10/30 17:21:13 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_OMIT_ALTERTABLE is defined, omit this file. +ifcapable !altertable||!memdebug { + finish_test + return +} + +source $testdir/malloc_common.tcl + +do_malloc_test altermalloc-1 -tclprep { + db close +} -tclbody { + if {[catch {sqlite3 db test.db}]} { + error "out of memory" + } + sqlite3_db_config_lookaside db 0 0 0 + sqlite3_extended_result_codes db 1 +} -sqlbody { + CREATE TABLE t1(a int); + ALTER TABLE t1 ADD COLUMN b INTEGER DEFAULT NULL; + ALTER TABLE t1 ADD COLUMN c TEXT DEFAULT 'default-text'; + ALTER TABLE t1 RENAME TO t2; + ALTER TABLE t2 ADD COLUMN d BLOB DEFAULT X'ABCD'; +} + +# Test malloc() failure on an ALTER TABLE on a virtual table. +# +ifcapable vtab { + do_malloc_test altermalloc-vtab -tclprep { + sqlite3 db2 test.db + sqlite3_db_config_lookaside db2 0 0 0 + sqlite3_extended_result_codes db2 1 + register_echo_module [sqlite3_connection_pointer db2] + db2 eval { + CREATE TABLE t1(a, b VARCHAR, c INTEGER); + CREATE VIRTUAL TABLE t1echo USING echo(t1); + } + db2 close + + register_echo_module [sqlite3_connection_pointer db] + } -tclbody { + set rc [catch {db eval { ALTER TABLE t1echo RENAME TO t1_echo }} msg] + if {$msg eq "vtable constructor failed: t1echo"} { + set msg "out of memory" + } + if {$rc} { + error $msg + } + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/amatch1.test b/components/external/SQLite-3.8.1/test/amatch1.test new file mode 100644 index 0000000000000000000000000000000000000000..cc0f77af107688e3fa1e6ae906b58f71e8dd11c1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/amatch1.test @@ -0,0 +1,117 @@ +# 2013-09-30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for "approximate_match" virtual +# table that is in the "amatch.c" extension. +# +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS4 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Create the fts_kjv_genesis procedure which fills and FTS3/4 table with +# the complete text of the Book of Genesis. +# +source $testdir/genesis.tcl + + + +do_test amatch1-1.0 { + db eval { + CREATE VIRTUAL TABLE t1 USING fts4(words); --, tokenize porter); + } + fts_kjv_genesis + db eval { + INSERT INTO t1(t1) VALUES('optimize'); + CREATE VIRTUAL TABLE temp.t1aux USING fts4aux(main, t1); + SELECT term FROM t1aux WHERE col=0 ORDER BY 1 LIMIT 5 + } +} {a abated abel abelmizraim abidah} +do_test amatch1-1.1 { + db eval { + SELECT term FROM t1aux WHERE term>'b' AND col=0 ORDER BY 1 LIMIT 5 + } +} {baalhanan babel back backward bad} +do_test amatch1-1.2 { + db eval { + SELECT term FROM t1aux WHERE term>'b' AND col=0 LIMIT 5 + } +} {baalhanan babel back backward bad} + +# Load the amatch extension +load_static_extension db amatch + +do_execsql_test amatch1-2.0 { + CREATE TABLE costs(iLang, cFrom, cTo, Cost); + INSERT INTO costs VALUES(0, '', '?', 100); + INSERT INTO costs VALUES(0, '?', '', 100); + INSERT INTO costs VALUES(0, '?', '?', 150); + CREATE TABLE vocab(w TEXT UNIQUE); + INSERT OR IGNORE INTO vocab SELECT term FROM t1aux; + CREATE VIRTUAL TABLE t2 USING approximate_match( + vocabulary_table=t1aux, + vocabulary_word=term, + edit_distances=costs + ); + CREATE VIRTUAL TABLE t3 USING approximate_match( + vocabulary_table=vocab, + vocabulary_word=w, + edit_distances=costs + ); + CREATE VIRTUAL TABLE t4 USING approximate_match( + vocabulary_table=vtemp, + vocabulary_word=w, + edit_distances=costs + ); +} {} +puts "Query against fts4aux: [time { + do_execsql_test amatch1-2.1 { + SELECT word, distance FROM t2 + WHERE word MATCH 'josxph' AND distance<300; + } {joseph 150}} 1]" +puts "Query against ordinary table: [time { + do_execsql_test amatch1-2.2 { + SELECT word, distance FROM t3 + WHERE word MATCH 'josxph' AND distance<300; + } {joseph 150}} 1]" +puts "Temp table initialized from fts4aux: [time { + do_execsql_test amatch1-2.3a { + CREATE TEMP TABLE vtemp(w TEXT UNIQUE); + INSERT OR IGNORE INTO vtemp SELECT term FROM t1aux; + } {}} 1]" +puts "Query against temp table: [time { + do_execsql_test amatch1-2.3b { + SELECT word, distance FROM t4 + WHERE word MATCH 'josxph' AND distance<300; + } {joseph 150}} 1]" +do_execsql_test amatch1-2.11 { + SELECT word, distance FROM t2 + WHERE word MATCH 'joxxph' AND distance<=300; +} {joseph 300} +do_execsql_test amatch1-2.12 { + SELECT word, distance FROM t3 + WHERE word MATCH 'joxxph' AND distance<=300; +} {joseph 300} +do_execsql_test amatch1-2.21 { + SELECT word, distance FROM t2 + WHERE word MATCH 'joxxph' AND distance<300; +} {} +do_execsql_test amatch1-2.22 { + SELECT word, distance FROM t3 + WHERE word MATCH 'joxxph' AND distance<300; +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/analyze.test b/components/external/SQLite-3.8.1/test/analyze.test new file mode 100644 index 0000000000000000000000000000000000000000..c44508426396de42b8b877156a7687e5aa497d3d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/analyze.test @@ -0,0 +1,364 @@ +# 2005 July 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# This file implements tests for the ANALYZE command. +# +# $Id: analyze.test,v 1.9 2008/08/11 18:44:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# There is nothing to test if ANALYZE is disable for this build. +# +ifcapable {!analyze} { + finish_test + return +} + +# Basic sanity checks. +# +do_test analyze-1.1 { + catchsql { + ANALYZE no_such_table + } +} {1 {no such table: no_such_table}} +do_test analyze-1.2 { + execsql { + SELECT count(*) FROM sqlite_master WHERE name='sqlite_stat1' + } +} {0} +do_test analyze-1.3 { + catchsql { + ANALYZE no_such_db.no_such_table + } +} {1 {unknown database no_such_db}} +do_test analyze-1.4 { + execsql { + SELECT count(*) FROM sqlite_master WHERE name='sqlite_stat1' + } +} {0} +do_test analyze-1.5.1 { + catchsql { + ANALYZE + } +} {0 {}} +do_test analyze-1.5.2 { + catchsql { + PRAGMA empty_result_callbacks=1; + ANALYZE + } +} {0 {}} +do_test analyze-1.6 { + execsql { + SELECT count(*) FROM sqlite_master WHERE name='sqlite_stat1' + } +} {1} +do_test analyze-1.6.2 { + catchsql { + CREATE INDEX stat1idx ON sqlite_stat1(idx); + } +} {1 {table sqlite_stat1 may not be indexed}} +do_test analyze-1.6.3 { + catchsql { + CREATE INDEX main.stat1idx ON SQLite_stat1(idx); + } +} {1 {table sqlite_stat1 may not be indexed}} +do_test analyze-1.7 { + execsql { + SELECT * FROM sqlite_stat1 WHERE idx NOT NULL + } +} {} +do_test analyze-1.8 { + catchsql { + ANALYZE main + } +} {0 {}} +do_test analyze-1.9 { + execsql { + SELECT * FROM sqlite_stat1 WHERE idx NOT NULL + } +} {} +do_test analyze-1.10 { + catchsql { + CREATE TABLE t1(a,b); + ANALYZE main.t1; + } +} {0 {}} +do_test analyze-1.11 { + execsql { + SELECT * FROM sqlite_stat1 + } +} {} +do_test analyze-1.12 { + catchsql { + ANALYZE t1; + } +} {0 {}} +do_test analyze-1.13 { + execsql { + SELECT * FROM sqlite_stat1 + } +} {} + +# Create some indices that can be analyzed. But do not yet add +# data. Without data in the tables, no analysis is done. +# +do_test analyze-2.1 { + execsql { + CREATE INDEX t1i1 ON t1(a); + ANALYZE main.t1; + SELECT * FROM sqlite_stat1 ORDER BY idx; + } +} {} +do_test analyze-2.2 { + execsql { + CREATE INDEX t1i2 ON t1(b); + ANALYZE t1; + SELECT * FROM sqlite_stat1 ORDER BY idx; + } +} {} +do_test analyze-2.3 { + execsql { + CREATE INDEX t1i3 ON t1(a,b); + ANALYZE main; + SELECT * FROM sqlite_stat1 ORDER BY idx; + } +} {} + +# Start adding data to the table. Verify that the analysis +# is done correctly. +# +do_test analyze-3.1 { + execsql { + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(1,3); + ANALYZE main.t1; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t1i1 {2 2} t1i2 {2 1} t1i3 {2 2 1}} +do_test analyze-3.2 { + execsql { + INSERT INTO t1 VALUES(1,4); + INSERT INTO t1 VALUES(1,5); + ANALYZE t1; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t1i1 {4 4} t1i2 {4 1} t1i3 {4 4 1}} +do_test analyze-3.3 { + execsql { + INSERT INTO t1 VALUES(2,5); + ANALYZE main; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1}} +do_test analyze-3.4 { + execsql { + CREATE TABLE t2 AS SELECT * FROM t1; + CREATE INDEX t2i1 ON t2(a); + CREATE INDEX t2i2 ON t2(b); + CREATE INDEX t2i3 ON t2(a,b); + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1} t2i1 {5 3} t2i2 {5 2} t2i3 {5 3 1}} +do_test analyze-3.5 { + execsql { + DROP INDEX t2i3; + ANALYZE t1; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1} t2i1 {5 3} t2i2 {5 2}} +do_test analyze-3.6 { + execsql { + ANALYZE t2; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1} t2i1 {5 3} t2i2 {5 2}} +do_test analyze-3.7 { + execsql { + DROP INDEX t2i2; + ANALYZE t2; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t1i1 {5 3} t1i2 {5 2} t1i3 {5 3 1} t2i1 {5 3}} +do_test analyze-3.8 { + execsql { + CREATE TABLE t3 AS SELECT a, b, rowid AS c, 'hi' AS d FROM t1; + CREATE INDEX t3i1 ON t3(a); + CREATE INDEX t3i2 ON t3(a,b,c,d); + CREATE INDEX t3i3 ON t3(d,b,c,a); + DROP TABLE t1; + DROP TABLE t2; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {} +do_test analyze-3.9 { + execsql { + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1}} + +do_test analyze-3.10 { + execsql { + CREATE TABLE [silly " name](a, b, c); + CREATE INDEX 'foolish '' name' ON [silly " name](a, b); + CREATE INDEX 'another foolish '' name' ON [silly " name](c); + INSERT INTO [silly " name] VALUES(1, 2, 3); + INSERT INTO [silly " name] VALUES(4, 5, 6); + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {{another foolish ' name} {2 1} {foolish ' name} {2 1 1} t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1}} +do_test analyze-3.11 { + execsql { + DROP INDEX "foolish ' name"; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {{another foolish ' name} {2 1} t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1}} +do_test analyze-3.11 { + execsql { + DROP TABLE "silly "" name"; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1}} + +# Try corrupting the sqlite_stat1 table and make sure the +# database is still able to function. +# +do_test analyze-4.0 { + sqlite3 db2 test.db + db2 eval { + CREATE TABLE t4(x,y,z); + CREATE INDEX t4i1 ON t4(x); + CREATE INDEX t4i2 ON t4(y); + INSERT INTO t4 SELECT a,b,c FROM t3; + } + db2 close + db close + sqlite3 db test.db + execsql { + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + } +} {t3i1 {5 3} t3i2 {5 3 1 1 1} t3i3 {5 5 2 1 1} t4i1 {5 3} t4i2 {5 2}} +do_test analyze-4.1 { + execsql { + PRAGMA writable_schema=on; + INSERT INTO sqlite_stat1 VALUES(null,null,null); + PRAGMA writable_schema=off; + } + db close + sqlite3 db test.db + execsql { + SELECT * FROM t4 WHERE x=1234; + } +} {} +do_test analyze-4.2 { + execsql { + PRAGMA writable_schema=on; + DELETE FROM sqlite_stat1; + INSERT INTO sqlite_stat1 VALUES('t4','t4i1','nonsense'); + INSERT INTO sqlite_stat1 VALUES('t4','t4i2','120897349817238741092873198273409187234918720394817209384710928374109827172901827349871928741910'); + PRAGMA writable_schema=off; + } + db close + sqlite3 db test.db + execsql { + SELECT * FROM t4 WHERE x=1234; + } +} {} +do_test analyze-4.3 { + execsql { + INSERT INTO sqlite_stat1 VALUES('t4','xyzzy','0 1 2 3'); + } + db close + sqlite3 db test.db + execsql { + SELECT * FROM t4 WHERE x=1234; + } +} {} + +# Verify that DROP TABLE and DROP INDEX remove entries from the +# sqlite_stat1, sqlite_stat3 and sqlite_stat4 tables. +# +do_test analyze-5.0 { + execsql { + DELETE FROM t3; + DELETE FROM t4; + INSERT INTO t3 VALUES(1,2,3,4); + INSERT INTO t3 VALUES(5,6,7,8); + INSERT INTO t3 SELECT a+8, b+8, c+8, d+8 FROM t3; + INSERT INTO t3 SELECT a+16, b+16, c+16, d+16 FROM t3; + INSERT INTO t3 SELECT a+32, b+32, c+32, d+32 FROM t3; + INSERT INTO t3 SELECT a+64, b+64, c+64, d+64 FROM t3; + INSERT INTO t4 SELECT a, b, c FROM t3; + ANALYZE; + SELECT DISTINCT idx FROM sqlite_stat1 ORDER BY 1; + SELECT DISTINCT tbl FROM sqlite_stat1 ORDER BY 1; + } +} {t3i1 t3i2 t3i3 t4i1 t4i2 t3 t4} +ifcapable stat4||stat3 { + ifcapable stat4 {set stat sqlite_stat4} else {set stat sqlite_stat3} + do_test analyze-5.1 { + execsql " + SELECT DISTINCT idx FROM $stat ORDER BY 1; + SELECT DISTINCT tbl FROM $stat ORDER BY 1; + " + } {t3i1 t3i2 t3i3 t4i1 t4i2 t3 t4} +} +do_test analyze-5.2 { + execsql { + DROP INDEX t3i2; + SELECT DISTINCT idx FROM sqlite_stat1 ORDER BY 1; + SELECT DISTINCT tbl FROM sqlite_stat1 ORDER BY 1; + } +} {t3i1 t3i3 t4i1 t4i2 t3 t4} +ifcapable stat4||stat3 { + do_test analyze-5.3 { + execsql " + SELECT DISTINCT idx FROM $stat ORDER BY 1; + SELECT DISTINCT tbl FROM $stat ORDER BY 1; + " + } {t3i1 t3i3 t4i1 t4i2 t3 t4} +} +do_test analyze-5.4 { + execsql { + DROP TABLE t3; + SELECT DISTINCT idx FROM sqlite_stat1 ORDER BY 1; + SELECT DISTINCT tbl FROM sqlite_stat1 ORDER BY 1; + } +} {t4i1 t4i2 t4} +ifcapable stat4||stat3 { + do_test analyze-5.5 { + execsql " + SELECT DISTINCT idx FROM $stat ORDER BY 1; + SELECT DISTINCT tbl FROM $stat ORDER BY 1; + " + } {t4i1 t4i2 t4} +} + +# This test corrupts the database file so it must be the last test +# in the series. +# +do_test analyze-99.1 { + execsql { + PRAGMA writable_schema=on; + UPDATE sqlite_master SET sql='nonsense' WHERE name='sqlite_stat1'; + } + db close + catch { sqlite3 db test.db } + catchsql { + ANALYZE + } +} {1 {malformed database schema (sqlite_stat1) - near "nonsense": syntax error}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/analyze3.test b/components/external/SQLite-3.8.1/test/analyze3.test new file mode 100644 index 0000000000000000000000000000000000000000..fb26303ee3f2a3e76d9281720ae0cff1e00b736d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/analyze3.test @@ -0,0 +1,647 @@ +# 2009 August 06 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. This file +# implements tests for range and LIKE constraints that use bound variables +# instead of literal constant arguments. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !stat4&&!stat3 { + finish_test + return +} + +#---------------------------------------------------------------------- +# Test Organization: +# +# analyze3-1.*: Test that the values of bound parameters are considered +# in the same way as constants when planning queries that +# use range constraints. +# +# analyze3-2.*: Test that the values of bound parameters are considered +# in the same way as constants when planning queries that +# use LIKE expressions in the WHERE clause. +# +# analyze3-3.*: Test that binding to a variable does not invalidate the +# query plan when there is no way in which replanning the +# query may produce a superior outcome. +# +# analyze3-4.*: Test that SQL or authorization callback errors occuring +# within sqlite3Reprepare() are handled correctly. +# +# analyze3-5.*: Check that the query plans of applicable statements are +# invalidated if the values of SQL parameter are modified +# using the clear_bindings() or transfer_bindings() APIs. +# +# analyze3-6.*: Test that the problem fixed by commit [127a5b776d] is fixed. +# + +proc getvar {varname} { uplevel #0 set $varname } +db function var getvar + +proc eqp {sql {db db}} { + uplevel execsql [list "EXPLAIN QUERY PLAN $sql"] $db +} + +proc sf_execsql {sql {db db}} { + set ::sqlite_search_count 0 + set r [uplevel [list execsql $sql $db]] + + concat $::sqlite_search_count [$db status step] $r +} + +#------------------------------------------------------------------------- +# +# analyze3-1.1.1: +# Create a table with two columns. Populate the first column (affinity +# INTEGER) with integer values from 100 to 1100. Create an index on this +# column. ANALYZE the table. +# +# analyze3-1.1.2 - 3.1.3 +# Show that there are two possible plans for querying the table with +# a range constraint on the indexed column - "full table scan" or "use +# the index". When the range is specified using literal values, SQLite +# is able to pick the best plan based on the samples in sqlite_stat3. +# +# analyze3-1.1.4 - 3.1.9 +# Show that using SQL variables produces the same results as using +# literal values to constrain the range scan. +# +# These tests also check that the compiler code considers column +# affinities when estimating the number of rows scanned by the "use +# index strategy". +# +do_test analyze3-1.1.1 { + execsql { + BEGIN; + CREATE TABLE t1(x INTEGER, y); + CREATE INDEX i1 ON t1(x); + } + for {set i 0} {$i < 1000} {incr i} { + execsql { INSERT INTO t1 VALUES($i+100, $i) } + } + execsql { + COMMIT; + ANALYZE; + } + + ifcapable stat4 { + execsql { SELECT count(*)>0 FROM sqlite_stat4; } + } else { + execsql { SELECT count(*)>0 FROM sqlite_stat3; } + } +} {1} + +do_eqp_test analyze3-1.1.2 { + SELECT sum(y) FROM t1 WHERE x>200 AND x<300 +} {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (x>? AND x0 AND x<1100 +} {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (x>? AND x200 AND x<300 } +} {199 0 14850} +do_test analyze3-1.1.5 { + set l [string range "200" 0 end] + set u [string range "300" 0 end] + sf_execsql { SELECT sum(y) FROM t1 WHERE x>$l AND x<$u } +} {199 0 14850} +do_test analyze3-1.1.6 { + set l [expr int(200)] + set u [expr int(300)] + sf_execsql { SELECT sum(y) FROM t1 WHERE x>$l AND x<$u } +} {199 0 14850} +do_test analyze3-1.1.7 { + sf_execsql { SELECT sum(y) FROM t1 WHERE x>0 AND x<1100 } +} {2000 0 499500} +do_test analyze3-1.1.8 { + set l [string range "0" 0 end] + set u [string range "1100" 0 end] + sf_execsql { SELECT sum(y) FROM t1 WHERE x>$l AND x<$u } +} {2000 0 499500} +do_test analyze3-1.1.9 { + set l [expr int(0)] + set u [expr int(1100)] + sf_execsql { SELECT sum(y) FROM t1 WHERE x>$l AND x<$u } +} {2000 0 499500} + + +# The following tests are similar to the block above. The difference is +# that the indexed column has TEXT affinity in this case. In the tests +# above the affinity is INTEGER. +# +do_test analyze3-1.2.1 { + execsql { + BEGIN; + CREATE TABLE t2(x TEXT, y); + INSERT INTO t2 SELECT * FROM t1; + CREATE INDEX i2 ON t2(x); + COMMIT; + ANALYZE; + } +} {} +do_eqp_test analyze3-1.2.2 { + SELECT sum(y) FROM t2 WHERE x>1 AND x<2 +} {0 0 0 {SEARCH TABLE t2 USING INDEX i2 (x>? AND x0 AND x<99 +} {0 0 0 {SEARCH TABLE t2 USING INDEX i2 (x>? AND x12 AND x<20 } +} {161 0 4760} +do_test analyze3-1.2.5 { + set l [string range "12" 0 end] + set u [string range "20" 0 end] + sf_execsql {SELECT typeof($l), typeof($u), sum(y) FROM t2 WHERE x>$l AND x<$u} +} {161 0 text text 4760} +do_test analyze3-1.2.6 { + set l [expr int(12)] + set u [expr int(20)] + sf_execsql {SELECT typeof($l), typeof($u), sum(y) FROM t2 WHERE x>$l AND x<$u} +} {161 0 integer integer 4760} +do_test analyze3-1.2.7 { + sf_execsql { SELECT sum(y) FROM t2 WHERE x>0 AND x<99 } +} {1981 0 490555} +do_test analyze3-1.2.8 { + set l [string range "0" 0 end] + set u [string range "99" 0 end] + sf_execsql {SELECT typeof($l), typeof($u), sum(y) FROM t2 WHERE x>$l AND x<$u} +} {1981 0 text text 490555} +do_test analyze3-1.2.9 { + set l [expr int(0)] + set u [expr int(99)] + sf_execsql {SELECT typeof($l), typeof($u), sum(y) FROM t2 WHERE x>$l AND x<$u} +} {1981 0 integer integer 490555} + +# Same tests a third time. This time, column x has INTEGER affinity and +# is not the leftmost column of the table. This triggered a bug causing +# SQLite to use sub-optimal query plans in 3.6.18 and earlier. +# +do_test analyze3-1.3.1 { + execsql { + BEGIN; + CREATE TABLE t3(y TEXT, x INTEGER); + INSERT INTO t3 SELECT y, x FROM t1; + CREATE INDEX i3 ON t3(x); + COMMIT; + ANALYZE; + } +} {} +do_eqp_test analyze3-1.3.2 { + SELECT sum(y) FROM t3 WHERE x>200 AND x<300 +} {0 0 0 {SEARCH TABLE t3 USING INDEX i3 (x>? AND x0 AND x<1100 +} {0 0 0 {SEARCH TABLE t3 USING INDEX i3 (x>? AND x200 AND x<300 } +} {199 0 14850} +do_test analyze3-1.3.5 { + set l [string range "200" 0 end] + set u [string range "300" 0 end] + sf_execsql { SELECT sum(y) FROM t3 WHERE x>$l AND x<$u } +} {199 0 14850} +do_test analyze3-1.3.6 { + set l [expr int(200)] + set u [expr int(300)] + sf_execsql { SELECT sum(y) FROM t3 WHERE x>$l AND x<$u } +} {199 0 14850} +do_test analyze3-1.3.7 { + sf_execsql { SELECT sum(y) FROM t3 WHERE x>0 AND x<1100 } +} {2000 0 499500} +do_test analyze3-1.3.8 { + set l [string range "0" 0 end] + set u [string range "1100" 0 end] + sf_execsql { SELECT sum(y) FROM t3 WHERE x>$l AND x<$u } +} {2000 0 499500} +do_test analyze3-1.3.9 { + set l [expr int(0)] + set u [expr int(1100)] + sf_execsql { SELECT sum(y) FROM t3 WHERE x>$l AND x<$u } +} {2000 0 499500} + +#------------------------------------------------------------------------- +# Test that the values of bound SQL variables may be used for the LIKE +# optimization. +# +drop_all_tables +do_test analyze3-2.1 { + execsql { + PRAGMA case_sensitive_like=off; + BEGIN; + CREATE TABLE t1(a, b TEXT COLLATE nocase); + CREATE INDEX i1 ON t1(b); + } + for {set i 0} {$i < 1000} {incr i} { + set t "" + append t [lindex {a b c d e f g h i j} [expr $i/100]] + append t [lindex {a b c d e f g h i j} [expr ($i/10)%10]] + append t [lindex {a b c d e f g h i j} [expr ($i%10)]] + execsql { INSERT INTO t1 VALUES($i, $t) } + } + execsql COMMIT +} {} +do_eqp_test analyze3-2.2 { + SELECT count(a) FROM t1 WHERE b LIKE 'a%' +} {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (b>? AND b?" -1 dummy] + sqlite3_expired $S +} {0} +do_test analyze3-3.2.2 { + sqlite3_bind_text $S 1 "abc" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.2.4 { + sqlite3_finalize $S +} {SQLITE_OK} + +do_test analyze3-3.2.5 { + set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE b=?" -1 dummy] + sqlite3_expired $S +} {0} +do_test analyze3-3.2.6 { + sqlite3_bind_text $S 1 "abc" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.2.7 { + sqlite3_finalize $S +} {SQLITE_OK} + +do_test analyze3-3.4.1 { + set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE a=? AND b>?" -1 dummy] + sqlite3_expired $S +} {0} +do_test analyze3-3.4.2 { + sqlite3_bind_text $S 1 "abc" 3 + sqlite3_expired $S +} {0} +do_test analyze3-3.4.3 { + sqlite3_bind_text $S 2 "def" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.4.4 { + sqlite3_bind_text $S 2 "ghi" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.4.5 { + sqlite3_expired $S +} {1} +do_test analyze3-3.4.6 { + sqlite3_finalize $S +} {SQLITE_OK} + +do_test analyze3-3.5.1 { + set S [sqlite3_prepare_v2 db { + SELECT * FROM t1 WHERE a IN ( + ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, + ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, + ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30, ?31 + ) AND b>?32; + } -1 dummy] + sqlite3_expired $S +} {0} +do_test analyze3-3.5.2 { + sqlite3_bind_text $S 31 "abc" 3 + sqlite3_expired $S +} {0} +do_test analyze3-3.5.3 { + sqlite3_bind_text $S 32 "def" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.5.5 { + sqlite3_finalize $S +} {SQLITE_OK} + +do_test analyze3-3.6.1 { + set S [sqlite3_prepare_v2 db { + SELECT * FROM t1 WHERE a IN ( + ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, + ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, + ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30, ?31, ?32 + ) AND b>?33; + } -1 dummy] + sqlite3_expired $S +} {0} +do_test analyze3-3.6.2 { + sqlite3_bind_text $S 32 "abc" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.6.3 { + sqlite3_bind_text $S 33 "def" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.6.5 { + sqlite3_finalize $S +} {SQLITE_OK} + +do_test analyze3-3.7.1 { + set S [sqlite3_prepare_v2 db { + SELECT * FROM t1 WHERE a IN ( + ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?33, + ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, + ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30, ?31, ?32 + ) AND b>?10; + } -1 dummy] + sqlite3_expired $S +} {0} +do_test analyze3-3.7.2 { + sqlite3_bind_text $S 32 "abc" 3 + sqlite3_expired $S +} {0} +do_test analyze3-3.7.3 { + sqlite3_bind_text $S 33 "def" 3 + sqlite3_expired $S +} {0} +do_test analyze3-3.7.4 { + sqlite3_bind_text $S 10 "def" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.7.6 { + sqlite3_finalize $S +} {SQLITE_OK} + +do_test analyze3-3.8.1 { + execsql { + CREATE TABLE t4(x, y TEXT COLLATE NOCASE); + CREATE INDEX i4 ON t4(y); + } +} {} +do_test analyze3-3.8.2 { + set S [sqlite3_prepare_v2 db { + SELECT * FROM t4 WHERE x != ? AND y LIKE ? + } -1 dummy] + sqlite3_expired $S +} {0} +do_test analyze3-3.8.3 { + sqlite3_bind_text $S 1 "abc" 3 + sqlite3_expired $S +} {0} +do_test analyze3-3.8.4 { + sqlite3_bind_text $S 2 "def" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.8.7 { + sqlite3_bind_text $S 2 "ghi%" 4 + sqlite3_expired $S +} {1} +do_test analyze3-3.8.8 { + sqlite3_expired $S +} {1} +do_test analyze3-3.8.9 { + sqlite3_bind_text $S 2 "ghi%def" 7 + sqlite3_expired $S +} {1} +do_test analyze3-3.8.10 { + sqlite3_expired $S +} {1} +do_test analyze3-3.8.11 { + sqlite3_bind_text $S 2 "%ab" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.8.12 { + sqlite3_expired $S +} {1} +do_test analyze3-3.8.12 { + sqlite3_bind_text $S 2 "%de" 3 + sqlite3_expired $S +} {1} +do_test analyze3-3.8.13 { + sqlite3_expired $S +} {1} +do_test analyze3-3.8.14 { + sqlite3_finalize $S +} {SQLITE_OK} + +#------------------------------------------------------------------------- +# These tests check that errors encountered while repreparing an SQL +# statement within sqlite3Reprepare() are handled correctly. +# + +# Check a schema error. +# +do_test analyze3-4.1.1 { + set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE a=? AND b>?" -1 dummy] + sqlite3_step $S +} {SQLITE_DONE} +do_test analyze3-4.1.2 { + sqlite3_reset $S + sqlite3_bind_text $S 2 "abc" 3 + execsql { DROP TABLE t1 } + sqlite3_step $S +} {SQLITE_ERROR} +do_test analyze3-4.1.3 { + sqlite3_finalize $S +} {SQLITE_ERROR} + +# Check an authorization error. +# +do_test analyze3-4.2.1 { + execsql { + BEGIN; + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(b); + } + for {set i 0} {$i < 100} {incr i} { + execsql { INSERT INTO t1 VALUES($i, $i, $i) } + } + execsql COMMIT + execsql ANALYZE + set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE a=? AND b>?" -1 dummy] + sqlite3_step $S +} {SQLITE_DONE} +db auth auth +proc auth {args} { + if {[lindex $args 0] == "SQLITE_READ"} {return SQLITE_DENY} + return SQLITE_OK +} +do_test analyze3-4.2.2 { + sqlite3_reset $S + sqlite3_bind_text $S 2 "abc" 3 + sqlite3_step $S +} {SQLITE_AUTH} +do_test analyze3-4.2.4 { + sqlite3_finalize $S +} {SQLITE_AUTH} + +# Check the effect of an authorization error that occurs in a re-prepare +# performed by sqlite3_step() is the same as one that occurs within +# sqlite3Reprepare(). +# +do_test analyze3-4.3.1 { + db auth {} + set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE a=? AND b>?" -1 dummy] + execsql { CREATE TABLE t2(d, e, f) } + db auth auth + sqlite3_step $S +} {SQLITE_AUTH} +do_test analyze3-4.3.2 { + sqlite3_finalize $S +} {SQLITE_AUTH} +db auth {} + +#------------------------------------------------------------------------- +# Test that modifying bound variables using the clear_bindings() or +# transfer_bindings() APIs works. +# +# analyze3-5.1.*: sqlite3_clear_bindings() +# analyze3-5.2.*: sqlite3_transfer_bindings() +# +do_test analyze3-5.1.1 { + drop_all_tables + execsql { + CREATE TABLE t1(x TEXT COLLATE NOCASE); + CREATE INDEX i1 ON t1(x); + INSERT INTO t1 VALUES('aaa'); + INSERT INTO t1 VALUES('abb'); + INSERT INTO t1 VALUES('acc'); + INSERT INTO t1 VALUES('baa'); + INSERT INTO t1 VALUES('bbb'); + INSERT INTO t1 VALUES('bcc'); + } + + set S [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE x LIKE ?" -1 dummy] + sqlite3_bind_text $S 1 "a%" 2 + set R [list] + while { "SQLITE_ROW" == [sqlite3_step $S] } { + lappend R [sqlite3_column_text $S 0] + } + concat [sqlite3_reset $S] $R +} {SQLITE_OK aaa abb acc} +do_test analyze3-5.1.2 { + sqlite3_clear_bindings $S + set R [list] + while { "SQLITE_ROW" == [sqlite3_step $S] } { + lappend R [sqlite3_column_text $S 0] + } + concat [sqlite3_reset $S] $R +} {SQLITE_OK} +do_test analyze3-5.1.3 { + sqlite3_finalize $S +} {SQLITE_OK} + +do_test analyze3-5.1.1 { + set S1 [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE x LIKE ?" -1 dummy] + sqlite3_bind_text $S1 1 "b%" 2 + set R [list] + while { "SQLITE_ROW" == [sqlite3_step $S1] } { + lappend R [sqlite3_column_text $S1 0] + } + concat [sqlite3_reset $S1] $R +} {SQLITE_OK baa bbb bcc} + +do_test analyze3-5.1.2 { + set S2 [sqlite3_prepare_v2 db "SELECT * FROM t1 WHERE x = ?" -1 dummy] + sqlite3_bind_text $S2 1 "a%" 2 + sqlite3_transfer_bindings $S2 $S1 + set R [list] + while { "SQLITE_ROW" == [sqlite3_step $S1] } { + lappend R [sqlite3_column_text $S1 0] + } + concat [sqlite3_reset $S1] $R +} {SQLITE_OK aaa abb acc} +do_test analyze3-5.1.3 { + sqlite3_finalize $S2 + sqlite3_finalize $S1 +} {SQLITE_OK} + +#------------------------------------------------------------------------- + +do_test analyze3-6.1 { + execsql { DROP TABLE IF EXISTS t1 } + execsql BEGIN + execsql { CREATE TABLE t1(a, b, c) } + for {set i 0} {$i < 1000} {incr i} { + execsql "INSERT INTO t1 VALUES([expr $i/100], 'x', [expr $i/10])" + } + execsql { + CREATE INDEX i1 ON t1(a, b); + CREATE INDEX i2 ON t1(c); + } + execsql COMMIT + execsql ANALYZE +} {} + +do_eqp_test analyze3-6-3 { + SELECT * FROM t1 WHERE a = 5 AND c = 13; +} {0 0 0 {SEARCH TABLE t1 USING INDEX i2 (c=?)}} + +do_eqp_test analyze3-6-2 { + SELECT * FROM t1 WHERE a = 5 AND b > 'w' AND c = 13; +} {0 0 0 {SEARCH TABLE t1 USING INDEX i2 (c=?)}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/analyze4.test b/components/external/SQLite-3.8.1/test/analyze4.test new file mode 100644 index 0000000000000000000000000000000000000000..974ed89a867cec68f48158c76ca6ce528d047d62 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/analyze4.test @@ -0,0 +1,111 @@ +# 2011 January 04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. This file +# implements tests for ANALYZE to verify that multiple rows containing +# a NULL value count as distinct rows for the purposes of analyze +# statistics. +# +# Also include test cases for collating sequences on indices. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test analyze4-1.0 { + db eval { + CREATE TABLE t1(a,b); + CREATE INDEX t1a ON t1(a); + CREATE INDEX t1b ON t1(b); + INSERT INTO t1 VALUES(1,NULL); + INSERT INTO t1 SELECT a+1, b FROM t1; + INSERT INTO t1 SELECT a+2, b FROM t1; + INSERT INTO t1 SELECT a+4, b FROM t1; + INSERT INTO t1 SELECT a+8, b FROM t1; + INSERT INTO t1 SELECT a+16, b FROM t1; + INSERT INTO t1 SELECT a+32, b FROM t1; + INSERT INTO t1 SELECT a+64, b FROM t1; + ANALYZE; + } + + # Should choose the t1a index since it is more specific than t1b. + db eval {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=5 AND b IS NULL} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} + +# Verify that the t1b index shows that it does not narrow down the +# search any at all. +# +do_test analyze4-1.1 { + db eval { + SELECT idx, stat FROM sqlite_stat1 WHERE tbl='t1' ORDER BY idx; + } +} {t1a {128 1} t1b {128 128}} + +# Change half of the b values from NULL to a constant. Verify +# that the number of rows selected in stat1 is half the total +# number of rows. +# +do_test analyze4-1.2 { + db eval { + UPDATE t1 SET b='x' WHERE a%2; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 WHERE tbl='t1' ORDER BY idx; + } +} {t1a {128 1} t1b {128 64}} + +# Change the t1.b values all back to NULL. Add columns t1.c and t1.d. +# Create a multi-column indices using t1.b and verify that ANALYZE +# processes them correctly. +# +do_test analyze4-1.3 { + db eval { + UPDATE t1 SET b=NULL; + ALTER TABLE t1 ADD COLUMN c; + ALTER TABLE t1 ADD COLUMN d; + UPDATE t1 SET c=a/4, d=a/2; + CREATE INDEX t1bcd ON t1(b,c,d); + CREATE INDEX t1cdb ON t1(c,d,b); + CREATE INDEX t1cbd ON t1(c,b,d); + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 WHERE tbl='t1' ORDER BY idx; + } +} {t1a {128 1} t1b {128 128} t1bcd {128 128 4 2} t1cbd {128 4 4 2} t1cdb {128 4 2 2}} + +# Verify that collating sequences are taken into account when computing +# ANALYZE statistics. +# +do_test analyze4-2.0 { + db eval { + CREATE TABLE t2( + x INTEGER PRIMARY KEY, + a TEXT COLLATE nocase, + b TEXT COLLATE rtrim, + c TEXT COLLATE binary + ); + CREATE INDEX t2a ON t2(a); + CREATE INDEX t2b ON t2(b); + CREATE INDEX t2c ON t2(c); + CREATE INDEX t2c2 ON t2(c COLLATE nocase); + CREATE INDEX t2c3 ON t2(c COLLATE rtrim); + INSERT INTO t2 VALUES(1, 'abc', 'abc', 'abc'); + INSERT INTO t2 VALUES(2, 'abC', 'abC', 'abC'); + INSERT INTO t2 VALUES(3, 'abc ', 'abc ', 'abc '); + INSERT INTO t2 VALUES(4, 'abC ', 'abC ', 'abC '); + INSERT INTO t2 VALUES(5, 'aBc', 'aBc', 'aBc'); + INSERT INTO t2 VALUES(6, 'aBC', 'aBC', 'aBC'); + INSERT INTO t2 VALUES(7, 'aBc ', 'aBc ', 'aBc '); + INSERT INTO t2 VALUES(8, 'aBC ', 'aBC ', 'aBC '); + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 WHERE tbl='t2' ORDER BY idx; + } +} {t2a {8 4} t2b {8 2} t2c {8 1} t2c2 {8 4} t2c3 {8 2}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/analyze5.test b/components/external/SQLite-3.8.1/test/analyze5.test new file mode 100644 index 0000000000000000000000000000000000000000..ac175c07b5953b74a3541a398b34ad2005994fda --- /dev/null +++ b/components/external/SQLite-3.8.1/test/analyze5.test @@ -0,0 +1,265 @@ +# 2011 January 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests for SQLite library. The focus of the tests +# in this file is the use of the sqlite_stat4 histogram data on tables +# with many repeated values and only a few distinct values. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !stat4&&!stat3 { + finish_test + return +} + +set testprefix analyze5 + +proc eqp {sql {db db}} { + uplevel execsql [list "EXPLAIN QUERY PLAN $sql"] $db +} + +proc alpha {blob} { + set ret "" + foreach c [split $blob {}] { + if {[string is alpha $c]} {append ret $c} + } + return $ret +} +db func alpha alpha + +db func lindex lindex + +unset -nocomplain i t u v w x y z +do_test analyze5-1.0 { + db eval {CREATE TABLE t1(t,u,v TEXT COLLATE nocase,w,x,y,z)} + for {set i 0} {$i < 1000} {incr i} { + set y [expr {$i>=25 && $i<=50}] + set z [expr {($i>=400) + ($i>=700) + ($i>=875)}] + set x $z + set w $z + set t [expr {$z+0.5}] + switch $z { + 0 {set u "alpha"; unset x} + 1 {set u "bravo"} + 2 {set u "charlie"} + 3 {set u "delta"; unset w} + } + if {$i%2} {set v $u} {set v [string toupper $u]} + db eval {INSERT INTO t1 VALUES($t,$u,$v,$w,$x,$y,$z)} + } + db eval { + CREATE INDEX t1t ON t1(t); -- 0.5, 1.5, 2.5, and 3.5 + CREATE INDEX t1u ON t1(u); -- text + CREATE INDEX t1v ON t1(v); -- mixed case text + CREATE INDEX t1w ON t1(w); -- integers 0, 1, 2 and a few NULLs + CREATE INDEX t1x ON t1(x); -- integers 1, 2, 3 and many NULLs + CREATE INDEX t1y ON t1(y); -- integers 0 and very few 1s + CREATE INDEX t1z ON t1(z); -- integers 0, 1, 2, and 3 + ANALYZE; + } + ifcapable stat4 { + db eval { + SELECT DISTINCT lindex(test_decode(sample),0) + FROM sqlite_stat4 WHERE idx='t1u' ORDER BY nlt; + } + } else { + db eval { + SELECT sample FROM sqlite_stat3 WHERE idx='t1u' ORDER BY nlt; + } + } +} {alpha bravo charlie delta} + +do_test analyze5-1.1 { + ifcapable stat4 { + db eval { + SELECT DISTINCT lower(lindex(test_decode(sample), 0)) + FROM sqlite_stat4 WHERE idx='t1v' ORDER BY 1 + } + } else { + db eval { + SELECT lower(sample) FROM sqlite_stat3 WHERE idx='t1v' ORDER BY 1 + } + } +} {alpha bravo charlie delta} +ifcapable stat4 { + do_test analyze5-1.2 { + db eval {SELECT idx, count(*) FROM sqlite_stat4 GROUP BY 1 ORDER BY 1} + } {t1t 8 t1u 8 t1v 8 t1w 8 t1x 8 t1y 9 t1z 8} +} else { + do_test analyze5-1.2 { + db eval {SELECT idx, count(*) FROM sqlite_stat3 GROUP BY 1 ORDER BY 1} + } {t1t 4 t1u 4 t1v 4 t1w 4 t1x 4 t1y 2 t1z 4} +} + +# Verify that range queries generate the correct row count estimates +# +foreach {testid where index rows} { + 1 {z>=0 AND z<=0} t1z 400 + 2 {z>=1 AND z<=1} t1z 300 + 3 {z>=2 AND z<=2} t1z 175 + 4 {z>=3 AND z<=3} t1z 125 + 5 {z>=4 AND z<=4} t1z 1 + 6 {z>=-1 AND z<=-1} t1z 1 + 7 {z>1 AND z<3} t1z 175 + 8 {z>0 AND z<100} t1z 600 + 9 {z>=1 AND z<100} t1z 600 + 10 {z>1 AND z<100} t1z 300 + 11 {z>=2 AND z<100} t1z 300 + 12 {z>2 AND z<100} t1z 125 + 13 {z>=3 AND z<100} t1z 125 + 14 {z>3 AND z<100} t1z 1 + 15 {z>=4 AND z<100} t1z 1 + 16 {z>=-100 AND z<=-1} t1z 1 + 17 {z>=-100 AND z<=0} t1z 400 + 18 {z>=-100 AND z<0} t1z 1 + 19 {z>=-100 AND z<=1} t1z 700 + 20 {z>=-100 AND z<2} t1z 700 + 21 {z>=-100 AND z<=2} t1z 875 + 22 {z>=-100 AND z<3} t1z 875 + + 31 {z>=0.0 AND z<=0.0} t1z 400 + 32 {z>=1.0 AND z<=1.0} t1z 300 + 33 {z>=2.0 AND z<=2.0} t1z 175 + 34 {z>=3.0 AND z<=3.0} t1z 125 + 35 {z>=4.0 AND z<=4.0} t1z 1 + 36 {z>=-1.0 AND z<=-1.0} t1z 1 + 37 {z>1.5 AND z<3.0} t1z 174 + 38 {z>0.5 AND z<100} t1z 599 + 39 {z>=1.0 AND z<100} t1z 600 + 40 {z>1.5 AND z<100} t1z 299 + 41 {z>=2.0 AND z<100} t1z 300 + 42 {z>2.1 AND z<100} t1z 124 + 43 {z>=3.0 AND z<100} t1z 125 + 44 {z>3.2 AND z<100} t1z 1 + 45 {z>=4.0 AND z<100} t1z 1 + 46 {z>=-100 AND z<=-1.0} t1z 1 + 47 {z>=-100 AND z<=0.0} t1z 400 + 48 {z>=-100 AND z<0.0} t1z 1 + 49 {z>=-100 AND z<=1.0} t1z 700 + 50 {z>=-100 AND z<2.0} t1z 700 + 51 {z>=-100 AND z<=2.0} t1z 875 + 52 {z>=-100 AND z<3.0} t1z 875 + + 101 {z=-1} t1z 1 + 102 {z=0} t1z 400 + 103 {z=1} t1z 300 + 104 {z=2} t1z 175 + 105 {z=3} t1z 125 + 106 {z=4} t1z 1 + 107 {z=-10.0} t1z 1 + 108 {z=0.0} t1z 400 + 109 {z=1.0} t1z 300 + 110 {z=2.0} t1z 175 + 111 {z=3.0} t1z 125 + 112 {z=4.0} t1z 1 + 113 {z=1.5} t1z 1 + 114 {z=2.5} t1z 1 + + 201 {z IN (-1)} t1z 1 + 202 {z IN (0)} t1z 400 + 203 {z IN (1)} t1z 300 + 204 {z IN (2)} t1z 175 + 205 {z IN (3)} t1z 125 + 206 {z IN (4)} t1z 1 + 207 {z IN (0.5)} t1z 1 + 208 {z IN (0,1)} t1z 700 + 209 {z IN (0,1,2)} t1z 875 + 210 {z IN (0,1,2,3)} {} 100 + 211 {z IN (0,1,2,3,4,5)} {} 100 + 212 {z IN (1,2)} t1z 475 + 213 {z IN (2,3)} t1z 300 + 214 {z=3 OR z=2} t1z 300 + 215 {z IN (-1,3)} t1z 126 + 216 {z=-1 OR z=3} t1z 126 + + 300 {y=0} t1y 974 + 301 {y=1} t1y 26 + 302 {y=0.1} t1y 1 + + 400 {x IS NULL} t1x 400 + +} { + # Verify that the expected index is used with the expected row count + # No longer valid due to an EXPLAIN QUERY PLAN output format change + # do_test analyze5-1.${testid}a { + # set x [lindex [eqp "SELECT * FROM t1 WHERE $where"] 3] + # set idx {} + # regexp {INDEX (t1.) } $x all idx + # regexp {~([0-9]+) rows} $x all nrow + # list $idx $nrow + # } [list $index $rows] + + # Verify that the same result is achieved regardless of whether or not + # the index is used + do_test analyze5-1.${testid}b { + set w2 [string map {y +y z +z} $where] + set a1 [db eval "SELECT rowid FROM t1 NOT INDEXED WHERE $w2\ + ORDER BY +rowid"] + set a2 [db eval "SELECT rowid FROM t1 WHERE $where ORDER BY +rowid"] + if {$a1==$a2} { + set res ok + } else { + set res "a1=\[$a1\] a2=\[$a2\]" + } + set res + } {ok} +} + +# Increase the number of NULLs in column x +# +db eval { + UPDATE t1 SET x=NULL; + UPDATE t1 SET x=rowid + WHERE rowid IN (SELECT rowid FROM t1 ORDER BY random() LIMIT 5); + ANALYZE; +} + +# Verify that range queries generate the correct row count estimates +# +foreach {testid where index rows} { + 500 {x IS NULL AND u='charlie'} t1u 17 + 501 {x=1 AND u='charlie'} t1x 1 + 502 {x IS NULL} t1x 995 + 503 {x=1} t1x 1 + 504 {x IS NOT NULL} t1x 2 + 505 {+x IS NOT NULL} {} 500 + 506 {upper(x) IS NOT NULL} {} 500 + +} { + # Verify that the expected index is used with the expected row count + # No longer valid due to an EXPLAIN QUERY PLAN format change + # do_test analyze5-1.${testid}a { + # set x [lindex [eqp "SELECT * FROM t1 WHERE $where"] 3] + # set idx {} + # regexp {INDEX (t1.) } $x all idx + # regexp {~([0-9]+) rows} $x all nrow + # list $idx $nrow + # } [list $index $rows] + + # Verify that the same result is achieved regardless of whether or not + # the index is used + do_test analyze5-1.${testid}b { + set w2 [string map {y +y z +z} $where] + set a1 [db eval "SELECT rowid FROM t1 NOT INDEXED WHERE $w2\ + ORDER BY +rowid"] + set a2 [db eval "SELECT rowid FROM t1 WHERE $where ORDER BY +rowid"] + if {$a1==$a2} { + set res ok + } else { + set res "a1=\[$a1\] a2=\[$a2\]" + } + set res + } {ok} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/analyze6.test b/components/external/SQLite-3.8.1/test/analyze6.test new file mode 100644 index 0000000000000000000000000000000000000000..f77f05324acb75d039b7a472274f8e3878c595bf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/analyze6.test @@ -0,0 +1,122 @@ +# 2011 March 3 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests for SQLite library. The focus of the tests +# in this file a corner-case query planner optimization involving the +# join order of two tables of different sizes. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !stat4&&!stat3 { + finish_test + return +} + +set testprefix analyze6 + +proc eqp {sql {db db}} { + uplevel execsql [list "EXPLAIN QUERY PLAN $sql"] $db +} + +do_test analyze6-1.0 { + db eval { + CREATE TABLE cat(x INT, yz TEXT); + CREATE UNIQUE INDEX catx ON cat(x); + /* Give cat 16 unique integers */ + INSERT INTO cat(x) VALUES(1); + INSERT INTO cat(x) VALUES(2); + INSERT INTO cat(x) SELECT x+2 FROM cat; + INSERT INTO cat(x) SELECT x+4 FROM cat; + INSERT INTO cat(x) SELECT x+8 FROM cat; + + CREATE TABLE ev(y INT); + CREATE INDEX evy ON ev(y); + /* ev will hold 32 copies of 16 integers found in cat */ + INSERT INTO ev SELECT x FROM cat; + INSERT INTO ev SELECT x FROM cat; + INSERT INTO ev SELECT y FROM ev; + INSERT INTO ev SELECT y FROM ev; + INSERT INTO ev SELECT y FROM ev; + INSERT INTO ev SELECT y FROM ev; + ANALYZE; + SELECT count(*) FROM cat; + SELECT count(*) FROM ev; + } +} {16 512} + +# The lowest cost plan is to scan CAT and for each integer there, do a single +# lookup of the first corresponding entry in EV then read off the equal values +# in EV. (Prior to the 2011-03-04 enhancement to where.c, this query would +# have used EV for the outer loop instead of CAT - which was about 3x slower.) +# +do_test analyze6-1.1 { + eqp {SELECT count(*) FROM ev, cat WHERE x=y} +} {0 0 1 {SCAN TABLE cat USING COVERING INDEX catx} 0 1 0 {SEARCH TABLE ev USING COVERING INDEX evy (y=?)}} + +# The same plan is chosen regardless of the order of the tables in the +# FROM clause. +# +do_test analyze6-1.2 { + eqp {SELECT count(*) FROM cat, ev WHERE x=y} +} {0 0 0 {SCAN TABLE cat USING COVERING INDEX catx} 0 1 1 {SEARCH TABLE ev USING COVERING INDEX evy (y=?)}} + + +# Ticket [83ea97620bd3101645138b7b0e71c12c5498fe3d] 2011-03-30 +# If ANALYZE is run on an empty table, make sure indices are used +# on the table. +# +do_test analyze6-2.1 { + execsql { + CREATE TABLE t201(x INTEGER PRIMARY KEY, y UNIQUE, z); + CREATE INDEX t201z ON t201(z); + ANALYZE; + } + eqp {SELECT * FROM t201 WHERE z=5} +} {0 0 0 {SEARCH TABLE t201 USING INDEX t201z (z=?)}} +do_test analyze6-2.2 { + eqp {SELECT * FROM t201 WHERE y=5} +} {0 0 0 {SEARCH TABLE t201 USING INDEX sqlite_autoindex_t201_1 (y=?)}} +do_test analyze6-2.3 { + eqp {SELECT * FROM t201 WHERE x=5} +} {0 0 0 {SEARCH TABLE t201 USING INTEGER PRIMARY KEY (rowid=?)}} +do_test analyze6-2.4 { + execsql { + INSERT INTO t201 VALUES(1,2,3); + ANALYZE t201; + } + eqp {SELECT * FROM t201 WHERE z=5} +} {0 0 0 {SEARCH TABLE t201 USING INDEX t201z (z=?)}} +do_test analyze6-2.5 { + eqp {SELECT * FROM t201 WHERE y=5} +} {0 0 0 {SEARCH TABLE t201 USING INDEX sqlite_autoindex_t201_1 (y=?)}} +do_test analyze6-2.6 { + eqp {SELECT * FROM t201 WHERE x=5} +} {0 0 0 {SEARCH TABLE t201 USING INTEGER PRIMARY KEY (rowid=?)}} +do_test analyze6-2.7 { + execsql { + INSERT INTO t201 VALUES(4,5,7); + INSERT INTO t201 SELECT x+100, y+100, z+100 FROM t201; + INSERT INTO t201 SELECT x+200, y+200, z+200 FROM t201; + INSERT INTO t201 SELECT x+400, y+400, z+400 FROM t201; + ANALYZE t201; + } + eqp {SELECT * FROM t201 WHERE z=5} +} {0 0 0 {SEARCH TABLE t201 USING INDEX t201z (z=?)}} +do_test analyze6-2.8 { + eqp {SELECT * FROM t201 WHERE y=5} +} {0 0 0 {SEARCH TABLE t201 USING INDEX sqlite_autoindex_t201_1 (y=?)}} +do_test analyze6-2.9 { + eqp {SELECT * FROM t201 WHERE x=5} +} {0 0 0 {SEARCH TABLE t201 USING INTEGER PRIMARY KEY (rowid=?)}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/analyze7.test b/components/external/SQLite-3.8.1/test/analyze7.test new file mode 100644 index 0000000000000000000000000000000000000000..76664546a5ff4cc13e79b57629033b902f078e4a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/analyze7.test @@ -0,0 +1,114 @@ +# 2011 April 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# This file implements tests for the ANALYZE command when an idnex +# name is given as the argument. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# There is nothing to test if ANALYZE is disable for this build. +# +ifcapable {!analyze||!vtab} { + finish_test + return +} + +# Generate some test data +# +do_test analyze7-1.0 { + load_static_extension db wholenumber + execsql { + CREATE TABLE t1(a,b,c,d); + CREATE INDEX t1a ON t1(a); + CREATE INDEX t1b ON t1(b); + CREATE INDEX t1cd ON t1(c,d); + CREATE VIRTUAL TABLE nums USING wholenumber; + INSERT INTO t1 SELECT value, value, value/100, value FROM nums + WHERE value BETWEEN 1 AND 256; + EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=123; + } +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} +do_test analyze7-1.1 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE b=123;} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b=?)}} +do_test analyze7-1.2 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE c=2;} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1cd (c=?)}} + +# Run an analyze on one of the three indices. Verify that this +# effects the row-count estimate on the one query that uses that +# one index. +# +do_test analyze7-2.0 { + execsql {ANALYZE t1a;} + db cache flush + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=123;} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} +do_test analyze7-2.1 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE b=123;} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b=?)}} +do_test analyze7-2.2 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE c=2;} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1cd (c=?)}} + +# Verify that since the query planner now things that t1a is more +# selective than t1b, it prefers to use t1a. +# +do_test analyze7-2.3 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=123 AND b=123} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} + +# Run an analysis on another of the three indices. Verify that this +# new analysis works and does not disrupt the previous analysis. +# +do_test analyze7-3.0 { + execsql {ANALYZE t1cd;} + db cache flush; + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=123;} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} +do_test analyze7-3.1 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE b=123;} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b=?)}} +do_test analyze7-3.2.1 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE c=?;} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1cd (c=?)}} +ifcapable stat4||stat3 { + # If ENABLE_STAT4 is defined, SQLite comes up with a different estimated + # row count for (c=2) than it does for (c=?). + do_test analyze7-3.2.2 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE c=2;} + } {0 0 0 {SEARCH TABLE t1 USING INDEX t1cd (c=?)}} +} else { + # If ENABLE_STAT4 is not defined, the expected row count for (c=2) is the + # same as that for (c=?). + do_test analyze7-3.2.3 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE c=2;} + } {0 0 0 {SEARCH TABLE t1 USING INDEX t1cd (c=?)}} +} +do_test analyze7-3.3 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=123 AND b=123} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} + +ifcapable {!stat4 && !stat3} { + do_test analyze7-3.4 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE c=123 AND b=123} + } {0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b=?)}} + do_test analyze7-3.5 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=123 AND c=123} + } {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} +} +do_test analyze7-3.6 { + execsql {EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE c=123 AND d=123 AND b=123} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1cd (c=? AND d=?)}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/analyze8.test b/components/external/SQLite-3.8.1/test/analyze8.test new file mode 100644 index 0000000000000000000000000000000000000000..4384c39676fc683a526626fbdd545b2082818494 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/analyze8.test @@ -0,0 +1,115 @@ +# 2011 August 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests for SQLite library. The focus of the tests +# in this file is testing the capabilities of sqlite_stat3. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !stat4&&!stat3 { + finish_test + return +} + +set testprefix analyze8 + +proc eqp {sql {db db}} { + uplevel execsql [list "EXPLAIN QUERY PLAN $sql"] $db +} + +# Scenario: +# +# Two indices. One has mostly singleton entries, but for a few +# values there are hundreds of entries. The other has 10-20 +# entries per value. +# +# Verify that the query planner chooses the first index for the singleton +# entries and the second index for the others. +# +do_test 1.0 { + db eval { + CREATE TABLE t1(a,b,c,d); + CREATE INDEX t1a ON t1(a); + CREATE INDEX t1b ON t1(b); + CREATE INDEX t1c ON t1(c); + } + for {set i 0} {$i<1000} {incr i} { + if {$i%2==0} {set a $i} {set a [expr {($i%8)*100}]} + set b [expr {$i/10}] + set c [expr {$i/8}] + set c [expr {$c*$c*$c}] + db eval {INSERT INTO t1 VALUES($a,$b,$c,$i)} + } + db eval {ANALYZE} +} {} + +# The a==100 comparison is expensive because there are many rows +# with a==100. And so for those cases, choose the t1b index. +# +# Buf ro a==99 and a==101, there are far fewer rows so choose +# the t1a index. +# +do_test 1.1 { + eqp {SELECT * FROM t1 WHERE a=100 AND b=55} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b=?)}} +do_test 1.2 { + eqp {SELECT * FROM t1 WHERE a=99 AND b=55} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} +do_test 1.3 { + eqp {SELECT * FROM t1 WHERE a=101 AND b=55} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} +do_test 1.4 { + eqp {SELECT * FROM t1 WHERE a=100 AND b=56} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b=?)}} +do_test 1.5 { + eqp {SELECT * FROM t1 WHERE a=99 AND b=56} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} +do_test 1.6 { + eqp {SELECT * FROM t1 WHERE a=101 AND b=56} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1a (a=?)}} +do_test 2.1 { + eqp {SELECT * FROM t1 WHERE a=100 AND b BETWEEN 50 AND 54} +} {0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b>? AND b? AND b? AND c? AND c90} { set a $i } else { set a NULL } + set b [expr $i % 5] + execsql "INSERT INTO t3 VALUES($a, $b)" + } + execsql ANALYZE +} {} +do_eqp_test 10.1.3 { + SELECT * FROM t3 WHERE a IS NULL AND b = 2 +} {/t3 USING INDEX t3b/} +do_eqp_test 10.1.4 { + SELECT * FROM t3 WHERE a IS NOT NULL AND b = 2 +} {/t3 USING INDEX t3a/} + +do_execsql_test 10.2.1 { + DROP TABLE IF EXISTS t3; + CREATE TABLE t3(x, a, b); + CREATE INDEX t3a ON t3(x, a); + CREATE INDEX t3b ON t3(x, b); +} +do_test 10.2.2 { + for {set i 1} {$i < 100} {incr i} { + if {$i>90} { set a $i } else { set a NULL } + set b [expr $i % 5] + execsql "INSERT INTO t3 VALUES('xyz', $a, $b)" + } + execsql ANALYZE +} {} +do_eqp_test 10.2.3 { + SELECT * FROM t3 WHERE x = 'xyz' AND a IS NULL AND b = 2 +} {/t3 USING INDEX t3b/} +do_eqp_test 10.2.4 { + SELECT * FROM t3 WHERE x = 'xyz' AND a IS NOT NULL AND b = 2 +} {/t3 USING INDEX t3a/} + +#------------------------------------------------------------------------- +# Check that stat4 data is used correctly with non-default collation +# sequences. +# +foreach {tn schema} { + 1 { + CREATE TABLE t4(a COLLATE nocase, b); + CREATE INDEX t4a ON t4(a); + CREATE INDEX t4b ON t4(b); + } + 2 { + CREATE TABLE t4(a, b); + CREATE INDEX t4a ON t4(a COLLATE nocase); + CREATE INDEX t4b ON t4(b); + } +} { + drop_all_tables + do_test 11.$tn.1 { execsql $schema } {} + + do_test 11.$tn.2 { + for {set i 0} {$i < 100} {incr i} { + if { ($i % 10)==0 } { set a ABC } else { set a DEF } + set b [expr $i % 5] + execsql { INSERT INTO t4 VALUES($a, $b) } + } + execsql ANALYZE + } {} + + do_eqp_test 11.$tn.3 { + SELECT * FROM t4 WHERE a = 'def' AND b = 3; + } {/t4 USING INDEX t4b/} + + if {$tn==1} { + set sql "SELECT * FROM t4 WHERE a = 'abc' AND b = 3;" + do_eqp_test 11.$tn.4 $sql {/t4 USING INDEX t4a/} + } else { + + set sql "SELECT * FROM t4 WHERE a = 'abc' COLLATE nocase AND b = 3;" + do_eqp_test 11.$tn.5 $sql {/t4 USING INDEX t4a/} + + set sql "SELECT * FROM t4 WHERE a COLLATE nocase = 'abc' AND b = 3;" + do_eqp_test 11.$tn.6 $sql {/t4 USING INDEX t4a/} + } +} + +foreach {tn schema} { + 1 { + CREATE TABLE t4(x, a COLLATE nocase, b); + CREATE INDEX t4a ON t4(x, a); + CREATE INDEX t4b ON t4(x, b); + } + 2 { + CREATE TABLE t4(x, a, b); + CREATE INDEX t4a ON t4(x, a COLLATE nocase); + CREATE INDEX t4b ON t4(x, b); + } +} { + drop_all_tables + do_test 12.$tn.1 { execsql $schema } {} + + do_test 12.$tn.2 { + for {set i 0} {$i < 100} {incr i} { + if { ($i % 10)==0 } { set a ABC } else { set a DEF } + set b [expr $i % 5] + execsql { INSERT INTO t4 VALUES(X'abcdef', $a, $b) } + } + execsql ANALYZE + } {} + + do_eqp_test 12.$tn.3 { + SELECT * FROM t4 WHERE x=X'abcdef' AND a = 'def' AND b = 3; + } {/t4 USING INDEX t4b/} + + if {$tn==1} { + set sql "SELECT * FROM t4 WHERE x=X'abcdef' AND a = 'abc' AND b = 3;" + do_eqp_test 12.$tn.4 $sql {/t4 USING INDEX t4a/} + } else { + set sql { + SELECT * FROM t4 WHERE x=X'abcdef' AND a = 'abc' COLLATE nocase AND b = 3 + } + do_eqp_test 12.$tn.5 $sql {/t4 USING INDEX t4a/} + set sql { + SELECT * FROM t4 WHERE x=X'abcdef' AND a COLLATE nocase = 'abc' AND b = 3 + } + do_eqp_test 12.$tn.6 $sql {/t4 USING INDEX t4a/} + } +} + +#------------------------------------------------------------------------- +# Check that affinities are taken into account when using stat4 data to +# estimate the number of rows scanned by a rowid constraint. +# +drop_all_tables +do_test 13.1 { + execsql { + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b, c); + } + for {set i 0} {$i<100} {incr i} { + if {$i %2} {set a abc} else {set a def} + execsql { INSERT INTO t1(rowid, a, b, c) VALUES($i, $a, $i, $i) } + } + execsql ANALYZE +} {} +do_eqp_test 13.2.1 { + SELECT * FROM t1 WHERE a='abc' AND rowid<15 AND b<20 +} {/SEARCH TABLE t1 USING INDEX i1/} +do_eqp_test 13.2.2 { + SELECT * FROM t1 WHERE a='abc' AND rowid<'15' AND b<20 +} {/SEARCH TABLE t1 USING INDEX i1/} +do_eqp_test 13.3.1 { + SELECT * FROM t1 WHERE a='abc' AND rowid<100 AND b<20 +} {/SEARCH TABLE t1 USING INDEX i2/} +do_eqp_test 13.3.2 { + SELECT * FROM t1 WHERE a='abc' AND rowid<'100' AND b<20 +} {/SEARCH TABLE t1 USING INDEX i2/} + +#------------------------------------------------------------------------- +# Check also that affinities are taken into account when using stat4 data +# to estimate the number of rows scanned by any other constraint on a +# column other than the leftmost. +# +drop_all_tables +do_test 14.1 { + execsql { CREATE TABLE t1(a, b INTEGER, c) } + for {set i 0} {$i<100} {incr i} { + set c [expr $i % 3] + execsql { INSERT INTO t1 VALUES('ott', $i, $c) } + } + execsql { + CREATE INDEX i1 ON t1(a, b); + CREATE INDEX i2 ON t1(c); + ANALYZE; + } +} {} +do_eqp_test 13.2.1 { + SELECT * FROM t1 WHERE a='ott' AND b<10 AND c=1 +} {/SEARCH TABLE t1 USING INDEX i1/} +do_eqp_test 13.2.2 { + SELECT * FROM t1 WHERE a='ott' AND b<'10' AND c=1 +} {/SEARCH TABLE t1 USING INDEX i1/} + +#------------------------------------------------------------------------- +# By default, 16 non-periodic samples are collected for the stat4 table. +# The following tests attempt to verify that the most common keys are +# being collected. +# +proc check_stat4 {tn} { + db eval ANALYZE + db eval {SELECT a, b, c, d FROM t1} { + incr k($a) + incr k([list $a $b]) + incr k([list $a $b $c]) + if { [info exists k([list $a $b $c $d])]==0 } { incr nRow } + incr k([list $a $b $c $d]) + } + + set L [list] + foreach key [array names k] { + lappend L [list $k($key) $key] + } + + set nSample $nRow + if {$nSample>16} {set nSample 16} + + set nThreshold [lindex [lsort -decr -integer -index 0 $L] [expr $nSample-1] 0] + foreach key [array names k] { + if {$k($key)>$nThreshold} { + set expect($key) 1 + } + if {$k($key)==$nThreshold} { + set possible($key) 1 + } + } + + + set nPossible [expr $nSample - [llength [array names expect]]] + + #puts "EXPECT: [array names expect]" + #puts "POSSIBLE($nPossible/[array size possible]): [array names possible]" + #puts "HAVE: [db eval {SELECT test_decode(sample) FROM sqlite_stat4 WHERE idx='i1'}]" + + db eval {SELECT test_decode(sample) AS s FROM sqlite_stat4 WHERE idx='i1'} { + set seen 0 + for {set i 0} {$i<4} {incr i} { + unset -nocomplain expect([lrange $s 0 $i]) + if {[info exists possible([lrange $s 0 $i])]} { + set seen 1 + unset -nocomplain possible([lrange $s 0 $i]) + } + } + if {$seen} {incr nPossible -1} + } + if {$nPossible<0} {set nPossible 0} + + set res [list [llength [array names expect]] $nPossible] + uplevel [list do_test $tn [list set {} $res] {0 0}] +} + +drop_all_tables +do_test 14.1.1 { + execsql { + CREATE TABLE t1(a,b,c,d); + CREATE INDEX i1 ON t1(a,b,c,d); + } + for {set i 0} {$i < 160} {incr i} { + execsql { INSERT INTO t1 VALUES($i,$i,$i,$i) } + if {($i % 10)==0} { execsql { INSERT INTO t1 VALUES($i,$i,$i,$i) } } + } +} {} +check_stat4 14.1.2 + +do_test 14.2.1 { + execsql { DELETE FROM t1 } + for {set i 0} {$i < 1600} {incr i} { + execsql { INSERT INTO t1 VALUES($i/10,$i/17,$i/27,$i/37) } + } +} {} +check_stat4 14.2.2 + +do_test 14.3.1 { + for {set i 0} {$i < 10} {incr i} { + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + execsql { INSERT INTO t1 VALUES($i*50,$i*50,$i*50,$i*50) } + } +} {} +check_stat4 14.3.2 + +do_test 14.4.1 { + execsql {DELETE FROM t1} + for {set i 1} {$i < 160} {incr i} { + set b [expr $i % 10] + if {$b==0 || $b==2} {set b 1} + execsql { INSERT INTO t1 VALUES($i/10,$b,$i,$i) } + } +} {} +check_stat4 14.4.2 +db func lrange lrange +db func lindex lindex +do_execsql_test 14.4.3 { + SELECT lrange(test_decode(sample), 0, 1) AS s FROM sqlite_stat4 + WHERE lindex(s, 1)=='1' ORDER BY rowid +} { + {0 1} {1 1} {2 1} {3 1} + {4 1} {5 1} {6 1} {7 1} + {8 1} {9 1} {10 1} {11 1} + {12 1} {13 1} {14 1} {15 1} +} + +#------------------------------------------------------------------------- +# Test that nothing untoward happens if the stat4 table contains entries +# for indexes that do not exist. Or NULL values in the idx column. +# Or NULL values in any of the other columns. +# +drop_all_tables +do_execsql_test 15.1 { + CREATE TABLE x1(a, b, UNIQUE(a, b)); + INSERT INTO x1 VALUES(1, 2); + INSERT INTO x1 VALUES(3, 4); + INSERT INTO x1 VALUES(5, 6); + ANALYZE; + INSERT INTO sqlite_stat4 VALUES(NULL, NULL, NULL, NULL, NULL, NULL); +} +db close +sqlite3 db test.db +do_execsql_test 15.2 { SELECT * FROM x1 } {1 2 3 4 5 6} + +do_execsql_test 15.3 { + INSERT INTO sqlite_stat4 VALUES(42, 42, 42, 42, 42, 42); +} +db close +sqlite3 db test.db +do_execsql_test 15.4 { SELECT * FROM x1 } {1 2 3 4 5 6} + +do_execsql_test 15.5 { + UPDATE sqlite_stat1 SET stat = NULL; +} +db close +sqlite3 db test.db +do_execsql_test 15.6 { SELECT * FROM x1 } {1 2 3 4 5 6} + +do_execsql_test 15.7 { + ANALYZE; + UPDATE sqlite_stat1 SET tbl = 'no such tbl'; +} +db close +sqlite3 db test.db +do_execsql_test 15.8 { SELECT * FROM x1 } {1 2 3 4 5 6} + +do_execsql_test 15.9 { + ANALYZE; + UPDATE sqlite_stat4 SET neq = NULL, nlt=NULL, ndlt=NULL; +} +db close +sqlite3 db test.db +do_execsql_test 15.10 { SELECT * FROM x1 } {1 2 3 4 5 6} + +# This is just for coverage.... +do_execsql_test 15.11 { + ANALYZE; + UPDATE sqlite_stat1 SET stat = stat || ' unordered'; +} +db close +sqlite3 db test.db +do_execsql_test 15.12 { SELECT * FROM x1 } {1 2 3 4 5 6} + +#------------------------------------------------------------------------- +# Test that allocations used for sqlite_stat4 samples are included in +# the quantity returned by SQLITE_DBSTATUS_SCHEMA_USED. +# +set one [string repeat x 1000] +set two [string repeat x 2000] +do_test 16.1 { + reset_db + execsql { + CREATE TABLE t1(a, UNIQUE(a)); + INSERT INTO t1 VALUES($one); + ANALYZE; + } + set nByte [lindex [sqlite3_db_status db SCHEMA_USED 0] 1] + + reset_db + execsql { + CREATE TABLE t1(a, UNIQUE(a)); + INSERT INTO t1 VALUES($two); + ANALYZE; + } + set nByte2 [lindex [sqlite3_db_status db SCHEMA_USED 0] 1] + + expr {$nByte2 > $nByte+900 && $nByte2 < $nByte+1050} +} {1} + +#------------------------------------------------------------------------- +# Test that stat4 data may be used with partial indexes. +# +do_test 17.1 { + reset_db + execsql { + CREATE TABLE t1(a, b, c, d); + CREATE INDEX i1 ON t1(a, b) WHERE d IS NOT NULL; + INSERT INTO t1 VALUES(-1, -1, -1, NULL); + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + } + + for {set i 0} {$i < 32} {incr i} { + if {$i<8} {set b 0} else { set b $i } + execsql { INSERT INTO t1 VALUES($i%2, $b, $i/2, 'abc') } + } + execsql {ANALYZE main.t1} +} {} + +do_catchsql_test 17.1.2 { + ANALYZE temp.t1; +} {1 {no such table: temp.t1}} + +do_eqp_test 17.2 { + SELECT * FROM t1 WHERE d IS NOT NULL AND a=0 AND b=10 AND c=10; +} {/USING INDEX i1/} +do_eqp_test 17.3 { + SELECT * FROM t1 WHERE d IS NOT NULL AND a=0 AND b=0 AND c=10; +} {/USING INDEX i1/} + +do_execsql_test 17.4 { + CREATE INDEX i2 ON t1(c, d); + ANALYZE main.i2; +} +do_eqp_test 17.5 { + SELECT * FROM t1 WHERE d IS NOT NULL AND a=0 AND b=10 AND c=10; +} {/USING INDEX i1/} +do_eqp_test 17.6 { + SELECT * FROM t1 WHERE d IS NOT NULL AND a=0 AND b=0 AND c=10; +} {/USING INDEX i2/} + +#------------------------------------------------------------------------- +# +do_test 18.1 { + reset_db + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + } + for {set i 0} {$i < 9} {incr i} { + execsql { + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + } + } + execsql ANALYZE + execsql { SELECT count(*) FROM sqlite_stat4 } +} {9} + +#------------------------------------------------------------------------- +# For coverage. +# +ifcapable view { + do_test 19.1 { + reset_db + execsql { + CREATE TABLE t1(x, y); + CREATE INDEX i1 ON t1(x, y); + CREATE VIEW v1 AS SELECT * FROM t1; + ANALYZE; + } + } {} +} +ifcapable auth { + proc authproc {op args} { + if {$op == "SQLITE_ANALYZE"} { return "SQLITE_DENY" } + return "SQLITE_OK" + } + do_test 19.2 { + reset_db + db auth authproc + execsql { + CREATE TABLE t1(x, y); + CREATE VIEW v1 AS SELECT * FROM t1; + } + catchsql ANALYZE + } {1 {not authorized}} +} + +#------------------------------------------------------------------------- +# +reset_db +proc r {args} { expr rand() } +db func r r +db func lrange lrange +do_test 20.1 { + execsql { + CREATE TABLE t1(a,b,c,d); + CREATE INDEX i1 ON t1(a,b,c,d); + } + for {set i 0} {$i < 16} {incr i} { + execsql { + INSERT INTO t1 VALUES($i, r(), r(), r()); + INSERT INTO t1 VALUES($i, $i, r(), r()); + INSERT INTO t1 VALUES($i, $i, $i, r()); + INSERT INTO t1 VALUES($i, $i, $i, $i); + INSERT INTO t1 VALUES($i, $i, $i, $i); + INSERT INTO t1 VALUES($i, $i, $i, r()); + INSERT INTO t1 VALUES($i, $i, r(), r()); + INSERT INTO t1 VALUES($i, r(), r(), r()); + } + } +} {} +do_execsql_test 20.2 { ANALYZE } +for {set i 0} {$i<16} {incr i} { + set val "$i $i $i $i" + do_execsql_test 20.3.$i { + SELECT count(*) FROM sqlite_stat4 + WHERE lrange(test_decode(sample), 0, 3)=$val + } {1} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/analyzeA.test b/components/external/SQLite-3.8.1/test/analyzeA.test new file mode 100644 index 0000000000000000000000000000000000000000..d9ca2c0f3bafe7c519bacae52f4e447aa1fd3670 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/analyzeA.test @@ -0,0 +1,167 @@ +# 2013 August 3 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains automated tests used to verify that the current build +# (which must be either ENABLE_STAT3 or ENABLE_STAT4) works with both stat3 +# and stat4 data. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix analyzeA + +ifcapable !stat4&&!stat3 { + finish_test + return +} + +# Populate the stat3 table according to the current contents of the db +# +proc populate_stat3 {{bDropTable 1}} { + # Open a second connection on database "test.db" and run ANALYZE. If this + # is an ENABLE_STAT3 build, this is all that is required to create and + # populate the sqlite_stat3 table. + # + sqlite3 db2 test.db + execsql { ANALYZE } + + # Now, if this is an ENABLE_STAT4 build, create and populate the + # sqlite_stat3 table based on the stat4 data gathered by the ANALYZE + # above. Then drop the sqlite_stat4 table. + # + ifcapable stat4 { + db2 func lindex lindex + execsql { + PRAGMA writable_schema = on; + CREATE TABLE sqlite_stat3(tbl,idx,neq,nlt,ndlt,sample); + INSERT INTO sqlite_stat3 + SELECT DISTINCT tbl, idx, + lindex(neq,0), lindex(nlt,0), lindex(ndlt,0), test_extract(sample, 0) + FROM sqlite_stat4; + } db2 + if {$bDropTable} { execsql {DROP TABLE sqlite_stat4} db2 } + execsql { PRAGMA writable_schema = off } + } + + # Modify the database schema cookie to ensure that the other connection + # reloads the schema. + # + execsql { + CREATE TABLE obscure_tbl_nm(x); + DROP TABLE obscure_tbl_nm; + } db2 + db2 close +} + +# Populate the stat4 table according to the current contents of the db +# +proc populate_stat4 {{bDropTable 1}} { + sqlite3 db2 test.db + execsql { ANALYZE } + + ifcapable stat3 { + execsql { + PRAGMA writable_schema = on; + CREATE TABLE sqlite_stat4(tbl,idx,neq,nlt,ndlt,sample); + INSERT INTO sqlite_stat4 + SELECT tbl, idx, neq, nlt, ndlt, sqlite_record(sample) + FROM sqlite_stat3; + } db2 + if {$bDropTable} { execsql {DROP TABLE sqlite_stat3} db2 } + execsql { PRAGMA writable_schema = off } + } + + # Modify the database schema cookie to ensure that the other connection + # reloads the schema. + # + execsql { + CREATE TABLE obscure_tbl_nm(x); + DROP TABLE obscure_tbl_nm; + } db2 + db2 close +} + +# Populate the stat4 table according to the current contents of the db. +# Leave deceptive data in the stat3 table. This data should be ignored +# in favour of that from the stat4 table. +# +proc populate_both {} { + ifcapable stat4 { populate_stat3 0 } + ifcapable stat3 { populate_stat4 0 } + + sqlite3 db2 test.db + execsql { + PRAGMA writable_schema = on; + UPDATE sqlite_stat3 SET idx = + CASE idx WHEN 't1b' THEN 't1c' ELSE 't1b' + END; + PRAGMA writable_schema = off; + CREATE TABLE obscure_tbl_nm(x); + DROP TABLE obscure_tbl_nm; + } db2 + db2 close +} + +foreach {tn analyze_cmd} { + 1 populate_stat4 + 2 populate_stat3 + 3 populate_both +} { + reset_db + do_test 1.$tn.1 { + execsql { CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c) } + for {set i 0} {$i < 100} {incr i} { + set c [expr int(pow(1.1,$i)/100)] + set b [expr 125 - int(pow(1.1,99-$i))/100] + execsql {INSERT INTO t1 VALUES($i, $b, $c)} + } + } {} + + execsql { CREATE INDEX t1b ON t1(b) } + execsql { CREATE INDEX t1c ON t1(c) } + $analyze_cmd + + do_execsql_test 1.$tn.2.1 { SELECT count(*) FROM t1 WHERE b=31 } 1 + do_execsql_test 1.$tn.2.2 { SELECT count(*) FROM t1 WHERE c=0 } 49 + do_execsql_test 1.$tn.2.3 { SELECT count(*) FROM t1 WHERE b=125 } 49 + do_execsql_test 1.$tn.2.4 { SELECT count(*) FROM t1 WHERE c=16 } 1 + + do_eqp_test 1.$tn.2.5 { + SELECT * FROM t1 WHERE b = 31 AND c = 0; + } {0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b=?)}} + do_eqp_test 1.$tn.2.6 { + SELECT * FROM t1 WHERE b = 125 AND c = 16; + } {0 0 0 {SEARCH TABLE t1 USING INDEX t1c (c=?)}} + + do_execsql_test 1.$tn.3.1 { + SELECT count(*) FROM t1 WHERE b BETWEEN 0 AND 50 + } {6} + do_execsql_test 1.$tn.3.2 { + SELECT count(*) FROM t1 WHERE c BETWEEN 0 AND 50 + } {90} + do_execsql_test 1.$tn.3.3 { + SELECT count(*) FROM t1 WHERE b BETWEEN 75 AND 125 + } {90} + do_execsql_test 1.$tn.3.4 { + SELECT count(*) FROM t1 WHERE c BETWEEN 75 AND 125 + } {6} + + do_eqp_test 1.$tn.3.5 { + SELECT * FROM t1 WHERE b BETWEEN 0 AND 50 AND c BETWEEN 0 AND 50 + } {0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b>? AND b? AND c90} { set a $i } else { set a NULL } + set b [expr $i % 5] + execsql "INSERT INTO t3 VALUES($a, $b)" + } + execsql ANALYZE +} {} +do_eqp_test 10.1.3 { + SELECT * FROM t3 WHERE a IS NULL AND b = 2 +} {/t3 USING INDEX t3b/} +do_eqp_test 10.1.4 { + SELECT * FROM t3 WHERE a IS NOT NULL AND b = 2 +} {/t3 USING INDEX t3a/} + +#------------------------------------------------------------------------- +# Check that stat3 data is used correctly with non-default collation +# sequences. +# +foreach {tn schema} { + 1 { + CREATE TABLE t4(a COLLATE nocase, b); + CREATE INDEX t4a ON t4(a); + CREATE INDEX t4b ON t4(b); + } + 2 { + CREATE TABLE t4(a, b); + CREATE INDEX t4a ON t4(a COLLATE nocase); + CREATE INDEX t4b ON t4(b); + } +} { + drop_all_tables + do_test 11.$tn.1 { execsql $schema } {} + + do_test 11.$tn.2 { + for {set i 0} {$i < 100} {incr i} { + if { ($i % 10)==0 } { set a ABC } else { set a DEF } + set b [expr $i % 5] + execsql { INSERT INTO t4 VALUES($a, $b) } + } + execsql ANALYZE + } {} + + do_eqp_test 11.$tn.3 { + SELECT * FROM t4 WHERE a = 'def' AND b = 3; + } {/t4 USING INDEX t4b/} + + if {$tn==1} { + set sql "SELECT * FROM t4 WHERE a = 'abc' AND b = 3;" + do_eqp_test 11.$tn.4 $sql {/t4 USING INDEX t4a/} + } else { + + set sql "SELECT * FROM t4 WHERE a = 'abc' COLLATE nocase AND b = 3;" + do_eqp_test 11.$tn.5 $sql {/t4 USING INDEX t4a/} + + set sql "SELECT * FROM t4 WHERE a COLLATE nocase = 'abc' AND b = 3;" + do_eqp_test 11.$tn.6 $sql {/t4 USING INDEX t4a/} + } +} + +#------------------------------------------------------------------------- +# Test that nothing untoward happens if the stat3 table contains entries +# for indexes that do not exist. Or NULL values in the idx column. +# Or NULL values in any of the other columns. +# +drop_all_tables +do_execsql_test 15.1 { + CREATE TABLE x1(a, b, UNIQUE(a, b)); + INSERT INTO x1 VALUES(1, 2); + INSERT INTO x1 VALUES(3, 4); + INSERT INTO x1 VALUES(5, 6); + ANALYZE; + INSERT INTO sqlite_stat3 VALUES(NULL, NULL, NULL, NULL, NULL, NULL); +} +db close +sqlite3 db test.db +do_execsql_test 15.2 { SELECT * FROM x1 } {1 2 3 4 5 6} + +do_execsql_test 15.3 { + INSERT INTO sqlite_stat3 VALUES(42, 42, 42, 42, 42, 42); +} +db close +sqlite3 db test.db +do_execsql_test 15.4 { SELECT * FROM x1 } {1 2 3 4 5 6} + +do_execsql_test 15.5 { + UPDATE sqlite_stat1 SET stat = NULL; +} +db close +sqlite3 db test.db +do_execsql_test 15.6 { SELECT * FROM x1 } {1 2 3 4 5 6} + +do_execsql_test 15.7 { + ANALYZE; + UPDATE sqlite_stat1 SET tbl = 'no such tbl'; +} +db close +sqlite3 db test.db +do_execsql_test 15.8 { SELECT * FROM x1 } {1 2 3 4 5 6} + +do_execsql_test 15.9 { + ANALYZE; + UPDATE sqlite_stat3 SET neq = NULL, nlt=NULL, ndlt=NULL; +} +db close +sqlite3 db test.db +do_execsql_test 15.10 { SELECT * FROM x1 } {1 2 3 4 5 6} + +# This is just for coverage.... +do_execsql_test 15.11 { + ANALYZE; + UPDATE sqlite_stat1 SET stat = stat || ' unordered'; +} +db close +sqlite3 db test.db +do_execsql_test 15.12 { SELECT * FROM x1 } {1 2 3 4 5 6} + +#------------------------------------------------------------------------- +# Test that allocations used for sqlite_stat3 samples are included in +# the quantity returned by SQLITE_DBSTATUS_SCHEMA_USED. +# +set one [string repeat x 1000] +set two [string repeat x 2000] +do_test 16.1 { + reset_db + execsql { + CREATE TABLE t1(a, UNIQUE(a)); + INSERT INTO t1 VALUES($one); + ANALYZE; + } + set nByte [lindex [sqlite3_db_status db SCHEMA_USED 0] 1] + + reset_db + execsql { + CREATE TABLE t1(a, UNIQUE(a)); + INSERT INTO t1 VALUES($two); + ANALYZE; + } + set nByte2 [lindex [sqlite3_db_status db SCHEMA_USED 0] 1] + + expr {$nByte2 > $nByte+950 && $nByte2 < $nByte+1050} +} {1} + +#------------------------------------------------------------------------- +# Test that stat3 data may be used with partial indexes. +# +do_test 17.1 { + reset_db + execsql { + CREATE TABLE t1(a, b, c, d); + CREATE INDEX i1 ON t1(a, b) WHERE d IS NOT NULL; + INSERT INTO t1 VALUES(-1, -1, -1, NULL); + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + INSERT INTO t1 SELECT 2*a,2*b,2*c,d FROM t1; + } + + for {set i 0} {$i < 32} {incr i} { + execsql { INSERT INTO t1 VALUES($i%2, $b, $i/2, 'abc') } + } + execsql {ANALYZE main.t1} +} {} + +do_catchsql_test 17.1.2 { + ANALYZE temp.t1; +} {1 {no such table: temp.t1}} + +do_eqp_test 17.2 { + SELECT * FROM t1 WHERE d IS NOT NULL AND a=0; +} {/USING INDEX i1/} +do_eqp_test 17.3 { + SELECT * FROM t1 WHERE d IS NOT NULL AND a=0; +} {/USING INDEX i1/} + +do_execsql_test 17.4 { + CREATE INDEX i2 ON t1(c) WHERE d IS NOT NULL; + ANALYZE main.i2; +} +do_eqp_test 17.5 { + SELECT * FROM t1 WHERE d IS NOT NULL AND a=0; +} {/USING INDEX i1/} +do_eqp_test 17.6 { + SELECT * FROM t1 WHERE d IS NOT NULL AND a=0 AND b=0 AND c=10; +} {/USING INDEX i2/} + +#------------------------------------------------------------------------- +# +do_test 18.1 { + reset_db + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + } + for {set i 0} {$i < 9} {incr i} { + execsql { + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + INSERT INTO t1 VALUES($i, 0); + } + } + execsql ANALYZE + execsql { SELECT count(*) FROM sqlite_stat3 } +} {9} + +#------------------------------------------------------------------------- +# For coverage. +# +ifcapable view { + do_test 19.1 { + reset_db + execsql { + CREATE TABLE t1(x, y); + CREATE INDEX i1 ON t1(x, y); + CREATE VIEW v1 AS SELECT * FROM t1; + ANALYZE; + } + } {} +} +ifcapable auth { + proc authproc {op args} { + if {$op == "SQLITE_ANALYZE"} { return "SQLITE_DENY" } + return "SQLITE_OK" + } + do_test 19.2 { + reset_db + db auth authproc + execsql { + CREATE TABLE t1(x, y); + CREATE VIEW v1 AS SELECT * FROM t1; + } + catchsql ANALYZE + } {1 {not authorized}} +} + +#------------------------------------------------------------------------- +# +reset_db +proc r {args} { expr rand() } +db func r r +db func lrange lrange +do_test 20.1 { + execsql { + CREATE TABLE t1(a,b,c,d); + CREATE INDEX i1 ON t1(a,b,c,d); + } + for {set i 0} {$i < 16} {incr i} { + execsql { + INSERT INTO t1 VALUES($i, r(), r(), r()); + INSERT INTO t1 VALUES($i, $i, r(), r()); + INSERT INTO t1 VALUES($i, $i, $i, r()); + INSERT INTO t1 VALUES($i, $i, $i, $i); + INSERT INTO t1 VALUES($i, $i, $i, $i); + INSERT INTO t1 VALUES($i, $i, $i, r()); + INSERT INTO t1 VALUES($i, $i, r(), r()); + INSERT INTO t1 VALUES($i, r(), r(), r()); + } + } +} {} +do_execsql_test 20.2 { ANALYZE } +for {set i 0} {$i<16} {incr i} { + set val $i + do_execsql_test 20.3.$i { + SELECT count(*) FROM sqlite_stat3 WHERE sample=$val + } {1} +} + +finish_test + diff --git a/components/external/SQLite-3.8.1/test/async.test b/components/external/SQLite-3.8.1/test/async.test new file mode 100644 index 0000000000000000000000000000000000000000..e1bc08642e50a2fc409b3ecdab14aa74b88ab1b1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/async.test @@ -0,0 +1,90 @@ +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs all tests. +# +# $Id: async.test,v 1.21 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +if {[info commands sqlite3async_initialize] eq ""} { + # The async logic is not built into this system + finish_test + return +} + +rename finish_test async_really_finish_test +proc finish_test {} { + catch {db close} + catch {db2 close} + catch {db3 close} +} +if {[info exists G(isquick)]} { set ASYNC_SAVE_ISQUICK $G(isquick) } +set G(isquick) 1 + +set ASYNC_INCLUDE { + insert.test + insert2.test + insert3.test + lock.test + lock2.test + lock3.test + select1.test + select2.test + select3.test + select4.test + trans.test +} + +# Enable asynchronous IO. +sqlite3async_initialize "" 1 + +# This proc flushes the contents of the async-IO queue through to the +# underlying VFS. A couple of the test scripts identified in $ASYNC_INCLUDE +# above contain lines like "catch flush_async_queue" in places where +# this is required for the tests to work in async mode. +# +proc flush_async_queue {} { + sqlite3async_control halt idle + sqlite3async_start + sqlite3async_wait + sqlite3async_control halt never +} + +rename do_test async_really_do_test +proc do_test {name args} { + uplevel async_really_do_test async_io-$name $args + flush_async_queue +} + +foreach testfile [lsort -dictionary [glob $testdir/*.test]] { + set tail [file tail $testfile] + if {[lsearch -exact $ASYNC_INCLUDE $tail]<0} continue + source $testfile + + # Make sure everything is flushed through. This is because [source]ing + # the next test file will delete the database file on disk (using + # [delete_file]). If the asynchronous backend still has the file + # open, it will become confused. + # + flush_async_queue +} + +# Flush the write-queue and disable asynchronous IO. This should ensure +# all allocated memory is cleaned up. +set sqlite3async_trace 1 +flush_async_queue +sqlite3async_shutdown +set sqlite3async_trace 0 + +rename do_test {} +rename async_really_do_test do_test +rename finish_test {} +rename async_really_finish_test finish_test + +if {[info exists ASYNC_SAVE_ISQUICK]} { set G(isquick) $ASYNC_SAVE_ISQUICK } +finish_test diff --git a/components/external/SQLite-3.8.1/test/async2.test b/components/external/SQLite-3.8.1/test/async2.test new file mode 100644 index 0000000000000000000000000000000000000000..7994a7219d748d124f4455005e890eb458f6ae49 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/async2.test @@ -0,0 +1,126 @@ +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: async2.test,v 1.12 2009/04/25 08:39:15 danielk1977 Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +if { + [info commands sqlite3async_initialize]=="" || + [info command sqlite3_memdebug_fail]=="" +} { + # The async logic is not built into this system + puts "Skipping async2 tests: not compiled with required features" + finish_test + return +} + +# Enable asynchronous IO. + +set setup_script { + CREATE TABLE counter(c); + INSERT INTO counter(c) VALUES (1); +} + +set sql_script { + BEGIN; + UPDATE counter SET c = 2; + CREATE TABLE t1(a PRIMARY KEY, b, c); + CREATE TABLE t2(a PRIMARY KEY, b, c); + COMMIT; + + BEGIN; + UPDATE counter SET c = 3; + INSERT INTO t1 VALUES('abcdefghij', 'four', 'score'); + INSERT INTO t2 VALUES('klmnopqrst', 'and', 'seven'); + COMMIT; + + UPDATE counter SET c = 'FIN'; +} + +db close + +foreach err [list ioerr malloc-transient malloc-persistent] { + set ::go 10 + for {set n 1} {$::go} {incr n} { + set ::sqlite_io_error_pending 0 + sqlite3_memdebug_fail -1 + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql $::setup_script + db close + + sqlite3async_initialize "" 1 + sqlite3 db test.db + sqlite3_db_config_lookaside db 0 0 0 + + switch -- $err { + ioerr { set ::sqlite_io_error_pending $n } + malloc-persistent { sqlite3_memdebug_fail $n -repeat 1 } + malloc-transient { sqlite3_memdebug_fail $n -repeat 0 } + } + + catchsql $::sql_script + db close + + sqlite3async_control halt idle + sqlite3async_start + sqlite3async_wait + sqlite3async_control halt never + sqlite3async_shutdown + + set ::sqlite_io_error_pending 0 + sqlite3_memdebug_fail -1 + + sqlite3 db test.db + set c [db one {SELECT c FROM counter LIMIT 1}] + switch -- $c { + 1 { + do_test async-$err-1.1.$n { + execsql { + SELECT name FROM sqlite_master; + } + } {counter} + } + 2 { + do_test async-$err-1.2.$n.1 { + execsql { + SELECT * FROM t1; + } + } {} + do_test async-$err-1.2.$n.2 { + execsql { + SELECT * FROM t2; + } + } {} + } + 3 { + do_test async-$err-1.3.$n.1 { + execsql { + SELECT * FROM t1; + } + } {abcdefghij four score} + do_test async-$err-1.3.$n.2 { + execsql { + SELECT * FROM t2; + } + } {klmnopqrst and seven} + } + FIN { + incr ::go -1 + } + } + + db close + } +} + +catch {db close} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/async3.test b/components/external/SQLite-3.8.1/test/async3.test new file mode 100644 index 0000000000000000000000000000000000000000..9336b660589e986a335eb54b6edac2f077c99306 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/async3.test @@ -0,0 +1,76 @@ +# 2007 September 5 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing the code in test_async.c. +# Specifically, it tests that the xFullPathname() method of +# of the asynchronous vfs works correctly. +# +# $Id: async3.test,v 1.5 2009/04/25 08:39:15 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +if { [info commands sqlite3async_initialize]=="" } { + # The async logic is not built into this system + puts "Skipping async3 tests: not compiled with required features" + finish_test + return +} + +db close +sqlite3async_initialize "" 1 +#set sqlite3async_trace 1 +sqlite3async_start + +set paths { + chocolate/banana/vanilla/file.db + chocolate//banana/vanilla/file.db + chocolate/./banana//vanilla/file.db + chocolate/banana/./vanilla/file.db + chocolate/banana/../banana/vanilla/file.db + chocolate/banana/./vanilla/extra_bit/../file.db +} + +do_test async3-1.0 { + file mkdir [file join chocolate banana vanilla] + forcedelete chocolate/banana/vanilla/file.db + forcedelete chocolate/banana/vanilla/file.db-journal +} {} + +do_test async3-1.1 { + sqlite3 db chocolate/banana/vanilla/file.db + execsql { + CREATE TABLE abc(a, b, c); + BEGIN; + INSERT INTO abc VALUES(1, 2, 3); + } +} {} + +set N 2 +foreach p $paths { + sqlite3 db2 $p + do_test async3-1.$N.1 { + execsql {SELECT * FROM abc} db2 + } {} + do_test async3-1.$N.2 { + catchsql {INSERT INTO abc VALUES(4, 5, 6)} db2 + } {1 {database is locked}} + db2 close + incr N +} + +db close + +sqlite3async_control halt idle +sqlite3async_wait +sqlite3async_control halt never +sqlite3async_shutdown +finish_test diff --git a/components/external/SQLite-3.8.1/test/async4.test b/components/external/SQLite-3.8.1/test/async4.test new file mode 100644 index 0000000000000000000000000000000000000000..92a820173ea281de71e2baecbbb181d46a01a0b2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/async4.test @@ -0,0 +1,168 @@ +# 2009 April 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: async4.test,v 1.4 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# These tests only work for Tcl version 8.5 and later on Windows (for now) +# +if {$tcl_platform(platform)=="windows"} { + scan $::tcl_version %f vx + if {$vx<8.5} { + finish_test + return + } +} + +if {[info commands sqlite3async_initialize] eq ""} { + # The async logic is not built into this system + finish_test + return +} +db close + +# Test layout: +# +# async4.1.*: Test the lockfiles parameter. +# async4.2.*: Test the delay parameter. + +do_test async4.1.1 { + sqlite3async_initialize {} 0 + sqlite3async_control lockfiles +} {1} +do_test async4.1.2 { + sqlite3async_control lockfiles false +} {0} +do_test async4.1.3 { + sqlite3async_control lockfiles +} {0} +do_test async4.1.4 { + sqlite3async_control lockfiles true +} {1} + +do_test async4.1.5 { + sqlite3 db test.db -vfs sqlite3async + execsql { CREATE TABLE t1(a, b, c) } +} {} +do_test async4.1.6 { + list [file exists test.db] [file size test.db] +} {1 0} +do_test async4.1.7 { + sqlite3 db2 test.db + catchsql { CREATE TABLE t2(a, b, c) } db2 +} {1 {database is locked}} +do_test async4.1.8 { + sqlite3async_control halt idle + sqlite3async_start + sqlite3async_wait +} {} +do_test async4.1.9 { + catchsql { CREATE TABLE t2(a, b, c) } db2 +} {0 {}} +do_test async4.1.10 { + list [catch {sqlite3async_control lockfiles false} msg] $msg +} {1 SQLITE_MISUSE} +do_test async4.1.11 { + db close + list [catch {sqlite3async_control lockfiles false} msg] $msg +} {1 SQLITE_MISUSE} +do_test async4.1.12 { + sqlite3async_start + sqlite3async_wait + sqlite3async_control lockfiles false +} {0} +do_test async4.1.13 { + sqlite3 db test.db -vfs sqlite3async + execsql { CREATE TABLE t3(a, b, c) } db +} {} +do_test async4.1.14 { + execsql { + CREATE INDEX i1 ON t2(a); + CREATE INDEX i2 ON t1(a); + } db2 +} {} +do_test async4.1.15 { + sqlite3async_start + sqlite3async_wait + hexio_write test.db 28 00000000 + execsql { pragma integrity_check } db2 +} {{*** in database main *** +Page 5 is never used}} +do_test async4.1.16 { + db close + db2 close + sqlite3async_start + sqlite3async_wait +} {} +do_test async4.1.17 { + sqlite3async_control lockfiles true +} {1} + +do_test async4.2.1 { + sqlite3async_control delay +} {0} +do_test async4.2.2 { + sqlite3async_control delay 23 +} {23} +do_test async4.2.3 { + sqlite3async_control delay +} {23} +do_test async4.2.4 { + sqlite3async_control delay 0 +} {0} +do_test async4.2.5 { + sqlite3 db test.db -vfs sqlite3async + + execsql { CREATE TABLE t4(a, b) } + set T1 [lindex [time { + sqlite3async_start + sqlite3async_wait + }] 0] + + sqlite3async_control delay 100 + execsql { CREATE TABLE t5(a, b) } + set T2 [lindex [time { + sqlite3async_start + sqlite3async_wait + }] 0] + + expr {($T1+1000000) < $T2} +} {1} + +do_test async4.2.6 { + sqlite3async_control delay 0 + execsql { CREATE TABLE t6(a, b) } + set T1 [lindex [time { + sqlite3async_start + sqlite3async_wait + }] 0] + + expr {($T1+1000000) < $T2} +} {1} + +do_test async4.2.7 { + list [catch { sqlite3async_control delay -1 } msg] $msg +} {1 SQLITE_MISUSE} + +do_test async4.2.8 { + db close + sqlite3async_start + sqlite3async_wait +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/async5.test b/components/external/SQLite-3.8.1/test/async5.test new file mode 100644 index 0000000000000000000000000000000000000000..abac11f7504f6be3fad8b3dbf199829e9af2df78 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/async5.test @@ -0,0 +1,68 @@ +# 2009 July 19 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file tests that asynchronous IO is compatible with multi-file +# transactions. +# +# $Id: async5.test,v 1.1 2009/07/18 11:52:04 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +if {[info commands sqlite3async_initialize] eq ""} { + # The async logic is not built into this system + finish_test + return +} + +db close +forcedelete test2.db +sqlite3async_initialize "" 1 +sqlite3async_control halt never +sqlite3 db test.db + +do_test async5-1.1 { + execsql { + ATTACH 'test2.db' AS next; + CREATE TABLE main.t1(a, b); + CREATE TABLE next.t2(a, b); + BEGIN; + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t2 VALUES(3, 4); + COMMIT; + } +} {} +do_test async5-1.2 { + execsql { SELECT * FROM t1 } +} {1 2} +do_test async5-1.3 { + execsql { SELECT * FROM t2 } +} {3 4} +do_test async5-1.4 { + execsql { + BEGIN; + INSERT INTO t1 VALUES('a', 'b'); + INSERT INTO t2 VALUES('c', 'd'); + COMMIT; + } +} {} +do_test async5-1.5 { + execsql { SELECT * FROM t1 } +} {1 2 a b} +do_test async5-1.6 { + execsql { SELECT * FROM t2 } +} {3 4 c d} + +db close + +sqlite3async_control halt idle +sqlite3async_start +sqlite3async_wait +sqlite3async_control halt never +sqlite3async_shutdown +set sqlite3async_trace 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/atof1.test b/components/external/SQLite-3.8.1/test/atof1.test new file mode 100644 index 0000000000000000000000000000000000000000..76eb4273b969041ec9233701c32d68dc10d6dfaa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/atof1.test @@ -0,0 +1,60 @@ +# 2012 June 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests of the sqlite3AtoF() function. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +if {![info exists __GNUC__]} { + finish_test + return +} + +expr srand(1) +for {set i 1} {$i<20000} {incr i} { + set pow [expr {int((rand()-0.5)*100)}] + set x [expr {pow((rand()-0.5)*2*rand(),$pow)}] + set xf [format %.32e $x] + + # Verify that text->real conversions get exactly same ieee754 floating- + # point value in SQLite as they do in TCL. + # + do_test atof1-1.$i.1 { + set y [db eval "SELECT $xf=\$x"] + if {!$y} { + puts -nonewline \173[db eval "SELECT real2hex($xf), real2hex(\$x)"]\175 + db eval "SELECT $xf+0.0 AS a, \$x AS b" { + puts [format "\n%.60e\n%.60e\n%.60e" $x $a $b] + } + } + set y + } {1} + + # Verify that round-trip real->text->real conversions using the quote() + # function preserve the bits of the numeric value exactly. + # + do_test atof1-1.$i.2 { + set y [db eval {SELECT $x=CAST(quote($x) AS real)}] + if {!$y} { + db eval {SELECT real2hex($x) a, real2hex(CAST(quote($x) AS real)) b} {} + puts "\nIN: $a $xf" + puts [format {QUOTE: %16s %s} {} [db eval {SELECT quote($x)}]] + db eval {SELECT CAST(quote($x) AS real) c} {} + puts "OUT: $b [format %.32e $c]" + } + set y + } {1} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/attach.test b/components/external/SQLite-3.8.1/test/attach.test new file mode 100644 index 0000000000000000000000000000000000000000..be5f9881c31833e2da37256dfb19f2c66f3c8c9f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/attach.test @@ -0,0 +1,862 @@ +# 2003 April 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is testing the ATTACH and DETACH commands +# and related functionality. +# +# $Id: attach.test,v 1.52 2009/05/29 14:39:08 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !attach { + finish_test + return +} + +for {set i 2} {$i<=15} {incr i} { + forcedelete test$i.db + forcedelete test$i.db-journal +} + +do_test attach-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + SELECT * FROM t1; + } +} {1 2 3 4} +do_test attach-1.2 { + sqlite3 db2 test2.db + execsql { + CREATE TABLE t2(x,y); + INSERT INTO t2 VALUES(1,'x'); + INSERT INTO t2 VALUES(2,'y'); + SELECT * FROM t2; + } db2 +} {1 x 2 y} +do_test attach-1.3 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + SELECT * FROM two.t2; + } +} {1 x 2 y} + +# Tests for the sqlite3_db_filename interface +# +do_test attach-1.3.1 { + file tail [sqlite3_db_filename db main] +} {test.db} +do_test attach-1.3.2 { + file tail [sqlite3_db_filename db MAIN] +} {test.db} +do_test attach-1.3.3 { + file tail [sqlite3_db_filename db temp] +} {} +do_test attach-1.3.4 { + file tail [sqlite3_db_filename db two] +} {test2.db} +do_test attach-1.3.5 { + file tail [sqlite3_db_filename db three] +} {} + +do_test attach-1.4 { + execsql { + SELECT * FROM t2; + } +} {1 x 2 y} +do_test attach-1.5 { + execsql { + DETACH DATABASE two; + SELECT * FROM t1; + } +} {1 2 3 4} +do_test attach-1.6 { + catchsql { + SELECT * FROM t2; + } +} {1 {no such table: t2}} +do_test attach-1.7 { + catchsql { + SELECT * FROM two.t2; + } +} {1 {no such table: two.t2}} +do_test attach-1.8 { + catchsql { + ATTACH DATABASE 'test3.db' AS three; + } +} {0 {}} +do_test attach-1.9 { + catchsql { + SELECT * FROM three.sqlite_master; + } +} {0 {}} +do_test attach-1.10 { + catchsql { + DETACH DATABASE [three]; + } +} {0 {}} +do_test attach-1.11 { + execsql { + ATTACH 'test.db' AS db2; + ATTACH 'test.db' AS db3; + ATTACH 'test.db' AS db4; + ATTACH 'test.db' AS db5; + ATTACH 'test.db' AS db6; + ATTACH 'test.db' AS db7; + ATTACH 'test.db' AS db8; + ATTACH 'test.db' AS db9; + } +} {} +proc db_list {db} { + set list {} + foreach {idx name file} [execsql {PRAGMA database_list} $db] { + lappend list $idx $name + } + return $list +} +ifcapable schema_pragmas { +do_test attach-1.11b { + db_list db +} {0 main 2 db2 3 db3 4 db4 5 db5 6 db6 7 db7 8 db8 9 db9} +} ;# ifcapable schema_pragmas +do_test attach-1.12 { + catchsql { + ATTACH 'test.db' as db2; + } +} {1 {database db2 is already in use}} +do_test attach-1.12.2 { + db errorcode +} {1} +do_test attach-1.13 { + catchsql { + ATTACH 'test.db' as db5; + } +} {1 {database db5 is already in use}} +do_test attach-1.14 { + catchsql { + ATTACH 'test.db' as db9; + } +} {1 {database db9 is already in use}} +do_test attach-1.15 { + catchsql { + ATTACH 'test.db' as main; + } +} {1 {database main is already in use}} +ifcapable tempdb { + do_test attach-1.16 { + catchsql { + ATTACH 'test.db' as temp; + } + } {1 {database temp is already in use}} +} +do_test attach-1.17 { + catchsql { + ATTACH 'test.db' as MAIN; + } +} {1 {database MAIN is already in use}} +do_test attach-1.18 { + catchsql { + ATTACH 'test.db' as db10; + ATTACH 'test.db' as db11; + } +} {0 {}} +if {$SQLITE_MAX_ATTACHED==10} { + do_test attach-1.19 { + catchsql { + ATTACH 'test.db' as db12; + } + } {1 {too many attached databases - max 10}} + do_test attach-1.19.1 { + db errorcode + } {1} +} +do_test attach-1.20.1 { + execsql { + DETACH db5; + } +} {} +ifcapable schema_pragmas { +do_test attach-1.20.2 { + db_list db +} {0 main 2 db2 3 db3 4 db4 5 db6 6 db7 7 db8 8 db9 9 db10 10 db11} +} ;# ifcapable schema_pragmas +integrity_check attach-1.20.3 +ifcapable tempdb { + execsql {select * from sqlite_temp_master} +} +do_test attach-1.21 { + catchsql { + ATTACH 'test.db' as db12; + } +} {0 {}} +if {$SQLITE_MAX_ATTACHED==10} { + do_test attach-1.22 { + catchsql { + ATTACH 'test.db' as db13; + } + } {1 {too many attached databases - max 10}} + do_test attach-1.22.1 { + db errorcode + } {1} +} +do_test attach-1.23 { + catchsql { + DETACH "db14"; + } +} {1 {no such database: db14}} +do_test attach-1.24 { + catchsql { + DETACH db12; + } +} {0 {}} +do_test attach-1.25 { + catchsql { + DETACH db12; + } +} {1 {no such database: db12}} +do_test attach-1.26 { + catchsql { + DETACH main; + } +} {1 {cannot detach database main}} + +ifcapable tempdb { + do_test attach-1.27 { + catchsql { + DETACH Temp; + } + } {1 {cannot detach database Temp}} +} else { + do_test attach-1.27 { + catchsql { + DETACH Temp; + } + } {1 {no such database: Temp}} +} + +do_test attach-1.28 { + catchsql { + DETACH db11; + DETACH db10; + DETACH db9; + DETACH db8; + DETACH db7; + DETACH db6; + DETACH db4; + DETACH db3; + DETACH db2; + } +} {0 {}} +ifcapable schema_pragmas { + ifcapable tempdb { + do_test attach-1.29 { + db_list db + } {0 main 1 temp} + } else { + do_test attach-1.29 { + db_list db + } {0 main} + } +} ;# ifcapable schema_pragmas + +ifcapable {trigger} { # Only do the following tests if triggers are enabled +do_test attach-2.1 { + execsql { + CREATE TABLE tx(x1,x2,y1,y2); + CREATE TRIGGER r1 AFTER UPDATE ON t2 FOR EACH ROW BEGIN + INSERT INTO tx(x1,x2,y1,y2) VALUES(OLD.x,NEW.x,OLD.y,NEW.y); + END; + SELECT * FROM tx; + } db2; +} {} +do_test attach-2.2 { + execsql { + UPDATE t2 SET x=x+10; + SELECT * FROM tx; + } db2; +} {1 11 x x 2 12 y y} +do_test attach-2.3 { + execsql { + CREATE TABLE tx(x1,x2,y1,y2); + SELECT * FROM tx; + } +} {} +do_test attach-2.4 { + execsql { + ATTACH 'test2.db' AS db2; + } +} {} +do_test attach-2.5 { + execsql { + UPDATE db2.t2 SET x=x+10; + SELECT * FROM db2.tx; + } +} {1 11 x x 2 12 y y 11 21 x x 12 22 y y} +do_test attach-2.6 { + execsql { + SELECT * FROM main.tx; + } +} {} +do_test attach-2.7 { + execsql { + SELECT type, name, tbl_name FROM db2.sqlite_master; + } +} {table t2 t2 table tx tx trigger r1 t2} + +ifcapable schema_pragmas&&tempdb { + do_test attach-2.8 { + db_list db + } {0 main 1 temp 2 db2} +} ;# ifcapable schema_pragmas&&tempdb +ifcapable schema_pragmas&&!tempdb { + do_test attach-2.8 { + db_list db + } {0 main 2 db2} +} ;# ifcapable schema_pragmas&&!tempdb + +do_test attach-2.9 { + execsql { + CREATE INDEX i2 ON t2(x); + SELECT * FROM t2 WHERE x>5; + } db2 +} {21 x 22 y} +do_test attach-2.10 { + execsql { + SELECT type, name, tbl_name FROM sqlite_master; + } db2 +} {table t2 t2 table tx tx trigger r1 t2 index i2 t2} +#do_test attach-2.11 { +# catchsql { +# SELECT * FROM t2 WHERE x>5; +# } +#} {1 {database schema has changed}} +ifcapable schema_pragmas { + ifcapable tempdb { + do_test attach-2.12 { + db_list db + } {0 main 1 temp 2 db2} + } else { + do_test attach-2.12 { + db_list db + } {0 main 2 db2} + } +} ;# ifcapable schema_pragmas +do_test attach-2.13 { + catchsql { + SELECT * FROM t2 WHERE x>5; + } +} {0 {21 x 22 y}} +do_test attach-2.14 { + execsql { + SELECT type, name, tbl_name FROM sqlite_master; + } +} {table t1 t1 table tx tx} +do_test attach-2.15 { + execsql { + SELECT type, name, tbl_name FROM db2.sqlite_master; + } +} {table t2 t2 table tx tx trigger r1 t2 index i2 t2} +do_test attach-2.16 { + db close + sqlite3 db test.db + execsql { + ATTACH 'test2.db' AS db2; + SELECT type, name, tbl_name FROM db2.sqlite_master; + } +} {table t2 t2 table tx tx trigger r1 t2 index i2 t2} +} ;# End of ifcapable {trigger} + +do_test attach-3.1 { + db close + db2 close + sqlite3 db test.db + sqlite3 db2 test2.db + execsql { + SELECT * FROM t1 + } +} {1 2 3 4} + +# If we are testing a version of the code that lacks trigger support, +# adjust the database contents so that they are the same if triggers +# had been enabled. +ifcapable {!trigger} { + db2 eval { + DELETE FROM t2; + INSERT INTO t2 VALUES(21, 'x'); + INSERT INTO t2 VALUES(22, 'y'); + CREATE TABLE tx(x1,x2,y1,y2); + INSERT INTO tx VALUES(1, 11, 'x', 'x'); + INSERT INTO tx VALUES(2, 12, 'y', 'y'); + INSERT INTO tx VALUES(11, 21, 'x', 'x'); + INSERT INTO tx VALUES(12, 22, 'y', 'y'); + CREATE INDEX i2 ON t2(x); + } +} + +do_test attach-3.2 { + catchsql { + SELECT * FROM t2 + } +} {1 {no such table: t2}} +do_test attach-3.3 { + catchsql { + ATTACH DATABASE 'test2.db' AS db2; + SELECT * FROM t2 + } +} {0 {21 x 22 y}} + +# Even though 'db' has started a transaction, it should not yet have +# a lock on test2.db so 'db2' should be readable. +do_test attach-3.4 { + execsql BEGIN + catchsql { + SELECT * FROM t2; + } db2; +} {0 {21 x 22 y}} + +# Reading from test2.db from db within a transaction should not +# prevent test2.db from being read by db2. +do_test attach-3.5 { + execsql {SELECT * FROM t2} + catchsql { + SELECT * FROM t2; + } db2; +} {0 {21 x 22 y}} + +# Making a change to test2.db through db causes test2.db to get +# a reserved lock. It should still be accessible through db2. +do_test attach-3.6 { + execsql { + UPDATE t2 SET x=x+1 WHERE x=50; + } + catchsql { + SELECT * FROM t2; + } db2; +} {0 {21 x 22 y}} + +do_test attach-3.7 { + execsql ROLLBACK + execsql {SELECT * FROM t2} db2 +} {21 x 22 y} + +# Start transactions on both db and db2. Once again, just because +# we make a change to test2.db using db2, only a RESERVED lock is +# obtained, so test2.db should still be readable using db. +# +do_test attach-3.8 { + execsql BEGIN + execsql BEGIN db2 + execsql {UPDATE t2 SET x=0 WHERE 0} db2 + catchsql {SELECT * FROM t2} +} {0 {21 x 22 y}} + +# It is also still accessible from db2. +do_test attach-3.9 { + catchsql {SELECT * FROM t2} db2 +} {0 {21 x 22 y}} + +do_test attach-3.10 { + execsql {SELECT * FROM t1} +} {1 2 3 4} + +do_test attach-3.11 { + catchsql {UPDATE t1 SET a=a+1} +} {0 {}} +do_test attach-3.12 { + execsql {SELECT * FROM t1} +} {2 2 4 4} + +# db2 has a RESERVED lock on test2.db, so db cannot write to any tables +# in test2.db. +do_test attach-3.13 { + catchsql {UPDATE t2 SET x=x+1 WHERE x=50} +} {1 {database is locked}} + +# Change for version 3. Transaction is no longer rolled back +# for a locked database. +execsql {ROLLBACK} + +# db is able to reread its schema because db2 still only holds a +# reserved lock. +do_test attach-3.14 { + catchsql {SELECT * FROM t1} +} {0 {1 2 3 4}} +do_test attach-3.15 { + execsql COMMIT db2 + execsql {SELECT * FROM t1} +} {1 2 3 4} + +# Ticket #323 +do_test attach-4.1 { + execsql {DETACH db2} + db2 close + sqlite3 db2 test2.db + execsql { + CREATE TABLE t3(x,y); + CREATE UNIQUE INDEX t3i1 ON t3(x); + INSERT INTO t3 VALUES(1,2); + SELECT * FROM t3; + } db2; +} {1 2} +do_test attach-4.2 { + execsql { + CREATE TABLE t3(a,b); + CREATE UNIQUE INDEX t3i1b ON t3(a); + INSERT INTO t3 VALUES(9,10); + SELECT * FROM t3; + } +} {9 10} +do_test attach-4.3 { + execsql { + ATTACH DATABASE 'test2.db' AS db2; + SELECT * FROM db2.t3; + } +} {1 2} +do_test attach-4.4 { + execsql { + SELECT * FROM main.t3; + } +} {9 10} +do_test attach-4.5 { + execsql { + INSERT INTO db2.t3 VALUES(9,10); + SELECT * FROM db2.t3; + } +} {1 2 9 10} +execsql { + DETACH db2; +} +ifcapable {trigger} { + do_test attach-4.6 { + execsql { + CREATE TABLE t4(x); + CREATE TRIGGER t3r3 AFTER INSERT ON t3 BEGIN + INSERT INTO t4 VALUES('db2.' || NEW.x); + END; + INSERT INTO t3 VALUES(6,7); + SELECT * FROM t4; + } db2 + } {db2.6} + do_test attach-4.7 { + execsql { + CREATE TABLE t4(y); + CREATE TRIGGER t3r3 AFTER INSERT ON t3 BEGIN + INSERT INTO t4 VALUES('main.' || NEW.a); + END; + INSERT INTO main.t3 VALUES(11,12); + SELECT * FROM main.t4; + } + } {main.11} +} +ifcapable {!trigger} { + # When we do not have trigger support, set up the table like they + # would have been had triggers been there. The tests that follow need + # this setup. + execsql { + CREATE TABLE t4(x); + INSERT INTO t3 VALUES(6,7); + INSERT INTO t4 VALUES('db2.6'); + INSERT INTO t4 VALUES('db2.13'); + } db2 + execsql { + CREATE TABLE t4(y); + INSERT INTO main.t3 VALUES(11,12); + INSERT INTO t4 VALUES('main.11'); + } +} + + +# This one is tricky. On the UNION ALL select, we have to make sure +# the schema for both main and db2 is valid before starting to execute +# the first query of the UNION ALL. If we wait to test the validity of +# the schema for main until after the first query has run, that test will +# fail and the query will abort but we will have already output some +# results. When the query is retried, the results will be repeated. +# +ifcapable compound { +do_test attach-4.8 { + execsql { + ATTACH DATABASE 'test2.db' AS db2; + INSERT INTO db2.t3 VALUES(13,14); + SELECT * FROM db2.t4 UNION ALL SELECT * FROM main.t4; + } +} {db2.6 db2.13 main.11} + +do_test attach-4.9 { + ifcapable {!trigger} {execsql {INSERT INTO main.t4 VALUES('main.15')}} + execsql { + INSERT INTO main.t3 VALUES(15,16); + SELECT * FROM db2.t4 UNION ALL SELECT * FROM main.t4; + } +} {db2.6 db2.13 main.11 main.15} +} ;# ifcapable compound + +ifcapable !compound { + ifcapable {!trigger} {execsql {INSERT INTO main.t4 VALUES('main.15')}} + execsql { + ATTACH DATABASE 'test2.db' AS db2; + INSERT INTO db2.t3 VALUES(13,14); + INSERT INTO main.t3 VALUES(15,16); + } +} ;# ifcapable !compound + +ifcapable view { +do_test attach-4.10 { + execsql { + DETACH DATABASE db2; + } + execsql { + CREATE VIEW v3 AS SELECT x*100+y FROM t3; + SELECT * FROM v3; + } db2 +} {102 910 607 1314} +do_test attach-4.11 { + execsql { + CREATE VIEW v3 AS SELECT a*100+b FROM t3; + SELECT * FROM v3; + } +} {910 1112 1516} +do_test attach-4.12 { + execsql { + ATTACH DATABASE 'test2.db' AS db2; + SELECT * FROM db2.v3; + } +} {102 910 607 1314} +do_test attach-4.13 { + execsql { + SELECT * FROM main.v3; + } +} {910 1112 1516} +} ;# ifcapable view + +# Tests for the sqliteFix...() routines in attach.c +# +ifcapable {trigger} { +do_test attach-5.1 { + db close + sqlite3 db test.db + db2 close + forcedelete test2.db + sqlite3 db2 test2.db + catchsql { + ATTACH DATABASE 'test.db' AS orig; + CREATE TRIGGER r1 AFTER INSERT ON orig.t1 BEGIN + SELECT 'no-op'; + END; + } db2 +} {1 {trigger r1 cannot reference objects in database orig}} +do_test attach-5.2 { + catchsql { + CREATE TABLE t5(x,y); + CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN + SELECT 'no-op'; + END; + } db2 +} {0 {}} +do_test attach-5.3 { + catchsql { + DROP TRIGGER r5; + CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN + SELECT 'no-op' FROM orig.t1; + END; + } db2 +} {1 {trigger r5 cannot reference objects in database orig}} +ifcapable tempdb { + do_test attach-5.4 { + catchsql { + CREATE TEMP TABLE t6(p,q,r); + CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN + SELECT 'no-op' FROM temp.t6; + END; + } db2 + } {1 {trigger r5 cannot reference objects in database temp}} +} +ifcapable subquery { + do_test attach-5.5 { + catchsql { + CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN + SELECT 'no-op' || (SELECT * FROM temp.t6); + END; + } db2 + } {1 {trigger r5 cannot reference objects in database temp}} + do_test attach-5.6 { + catchsql { + CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN + SELECT 'no-op' FROM t1 WHERE x<(SELECT min(x) FROM temp.t6); + END; + } db2 + } {1 {trigger r5 cannot reference objects in database temp}} + do_test attach-5.7 { + catchsql { + CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN + SELECT 'no-op' FROM t1 GROUP BY 1 HAVING x<(SELECT min(x) FROM temp.t6); + END; + } db2 + } {1 {trigger r5 cannot reference objects in database temp}} + do_test attach-5.7 { + catchsql { + CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN + SELECT max(1,x,(SELECT min(x) FROM temp.t6)) FROM t1; + END; + } db2 + } {1 {trigger r5 cannot reference objects in database temp}} + do_test attach-5.8 { + catchsql { + CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN + INSERT INTO t1 VALUES((SELECT min(x) FROM temp.t6),5); + END; + } db2 + } {1 {trigger r5 cannot reference objects in database temp}} + do_test attach-5.9 { + catchsql { + CREATE TRIGGER r5 AFTER INSERT ON t5 BEGIN + DELETE FROM t1 WHERE x<(SELECT min(x) FROM temp.t6); + END; + } db2 + } {1 {trigger r5 cannot reference objects in database temp}} +} ;# endif subquery +} ;# endif trigger + +# Check to make sure we get a sensible error if unable to open +# the file that we are trying to attach. +# +do_test attach-6.1 { + catchsql { + ATTACH DATABASE 'no-such-file' AS nosuch; + } +} {0 {}} +if {$tcl_platform(platform)=="unix"} { + do_test attach-6.2 { + sqlite3 dbx cannot-read + dbx eval {CREATE TABLE t1(a,b,c)} + dbx close + file attributes cannot-read -permission 0000 + if {[file writable cannot-read]} { + puts "\n**** Tests do not work when run as root ****" + forcedelete cannot-read + exit 1 + } + catchsql { + ATTACH DATABASE 'cannot-read' AS noread; + } + } {1 {unable to open database: cannot-read}} + do_test attach-6.2.2 { + db errorcode + } {14} + forcedelete cannot-read +} + +# Check the error message if we try to access a database that has +# not been attached. +do_test attach-6.3 { + catchsql { + CREATE TABLE no_such_db.t1(a, b, c); + } +} {1 {unknown database no_such_db}} +for {set i 2} {$i<=15} {incr i} { + catch {db$i close} +} +db close +forcedelete test2.db +forcedelete no-such-file + +ifcapable subquery { + do_test attach-7.1 { + forcedelete test.db test.db-journal + sqlite3 db test.db + catchsql { + DETACH RAISE ( IGNORE ) IN ( SELECT "AAAAAA" . * ORDER BY + REGISTER LIMIT "AAAAAA" . "AAAAAA" OFFSET RAISE ( IGNORE ) NOT NULL ) + } + } {1 {no such table: AAAAAA}} +} + +# Create a malformed file (a file that is not a valid database) +# and try to attach it +# +do_test attach-8.1 { + set fd [open test2.db w] + puts $fd "This file is not a valid SQLite database" + close $fd + catchsql { + ATTACH 'test2.db' AS t2; + } +} {1 {file is encrypted or is not a database}} +do_test attach-8.2 { + db errorcode +} {26} +forcedelete test2.db +do_test attach-8.3 { + sqlite3 db2 test2.db + db2 eval {CREATE TABLE t1(x); BEGIN EXCLUSIVE} + catchsql { + ATTACH 'test2.db' AS t2; + } +} {1 {database is locked}} +do_test attach-8.4 { + db errorcode +} {5} +db2 close +forcedelete test2.db + +# Test that it is possible to attach the same database more than +# once when not in shared-cache mode. That this is not possible in +# shared-cache mode is tested in shared7.test. +do_test attach-9.1 { + forcedelete test4.db + execsql { + ATTACH 'test4.db' AS aux1; + CREATE TABLE aux1.t1(a, b); + INSERT INTO aux1.t1 VALUES(1, 2); + ATTACH 'test4.db' AS aux2; + SELECT * FROM aux2.t1; + } +} {1 2} +do_test attach-9.2 { + catchsql { + BEGIN; + INSERT INTO aux1.t1 VALUES(3, 4); + INSERT INTO aux2.t1 VALUES(5, 6); + } +} {1 {database is locked}} +do_test attach-9.3 { + execsql { + COMMIT; + SELECT * FROM aux2.t1; + } +} {1 2 3 4} + +# Ticket [abe728bbc311d81334dae9762f0db87c07a98f79]. +# Multi-database commit on an attached TEMP database. +# +do_test attach-10.1 { + execsql { + ATTACH '' AS noname; + ATTACH ':memory:' AS inmem; + BEGIN; + CREATE TABLE noname.noname(x); + CREATE TABLE inmem.inmem(y); + CREATE TABLE main.main(z); + COMMIT; + SELECT name FROM noname.sqlite_master; + SELECT name FROM inmem.sqlite_master; + } +} {noname inmem} +do_test attach-10.2 { + lrange [execsql { + PRAGMA database_list; + }] 9 end +} {4 noname {} 5 inmem {}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/attach2.test b/components/external/SQLite-3.8.1/test/attach2.test new file mode 100644 index 0000000000000000000000000000000000000000..f8705685419e6ede6afa710d211619c8106846c8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/attach2.test @@ -0,0 +1,397 @@ +# 2003 July 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is testing the ATTACH and DETACH commands +# and related functionality. +# +# $Id: attach2.test,v 1.38 2007/12/13 21:54:11 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !attach { + finish_test + return +} + +# Ticket #354 +# +# Databases test.db and test2.db contain identical schemas. Make +# sure we can attach test2.db from test.db. +# +do_test attach2-1.1 { + db eval { + CREATE TABLE t1(a,b); + CREATE INDEX x1 ON t1(a); + } + forcedelete test2.db + forcedelete test2.db-journal + sqlite3 db2 test2.db + db2 eval { + CREATE TABLE t1(a,b); + CREATE INDEX x1 ON t1(a); + } + catchsql { + ATTACH 'test2.db' AS t2; + } +} {0 {}} + +# Ticket #514 +# +proc db_list {db} { + set list {} + foreach {idx name file} [execsql {PRAGMA database_list} $db] { + lappend list $idx $name + } + return $list +} +db eval {DETACH t2} +do_test attach2-2.1 { + # lock test2.db then try to attach it. This is no longer an error because + # db2 just RESERVES the database. It does not obtain a write-lock until + # we COMMIT. + db2 eval {BEGIN} + db2 eval {UPDATE t1 SET a = 0 WHERE 0} + catchsql { + ATTACH 'test2.db' AS t2; + } +} {0 {}} +ifcapable schema_pragmas { +do_test attach2-2.2 { + # make sure test2.db did get attached. + db_list db +} {0 main 2 t2} +} ;# ifcapable schema_pragmas +db2 eval {COMMIT} + +do_test attach2-2.5 { + # Make sure we can read test2.db from db + catchsql { + SELECT name FROM t2.sqlite_master; + } +} {0 {t1 x1}} +do_test attach2-2.6 { + # lock test2.db and try to read from it. This should still work because + # the lock is only a RESERVED lock which does not prevent reading. + # + db2 eval BEGIN + db2 eval {UPDATE t1 SET a = 0 WHERE 0} + catchsql { + SELECT name FROM t2.sqlite_master; + } +} {0 {t1 x1}} +do_test attach2-2.7 { + # but we can still read from test1.db even though test2.db is locked. + catchsql { + SELECT name FROM main.sqlite_master; + } +} {0 {t1 x1}} +do_test attach2-2.8 { + # start a transaction on test.db even though test2.db is locked. + catchsql { + BEGIN; + INSERT INTO t1 VALUES(8,9); + } +} {0 {}} +do_test attach2-2.9 { + execsql { + SELECT * FROM t1 + } +} {8 9} +do_test attach2-2.10 { + # now try to write to test2.db. the write should fail + catchsql { + INSERT INTO t2.t1 VALUES(1,2); + } +} {1 {database is locked}} +do_test attach2-2.11 { + # when the write failed in the previous test, the transaction should + # have rolled back. + # + # Update for version 3: A transaction is no longer rolled back if a + # database is found to be busy. + execsql {rollback} + db2 eval ROLLBACK + execsql { + SELECT * FROM t1 + } +} {} +do_test attach2-2.12 { + catchsql { + COMMIT + } +} {1 {cannot commit - no transaction is active}} + +# Ticket #574: Make sure it works using the non-callback API +# +do_test attach2-3.1 { + set DB [sqlite3_connection_pointer db] + set rc [catch {sqlite3_prepare $DB "ATTACH 'test2.db' AS t2" -1 TAIL} VM] + if {$rc} {lappend rc $VM} + sqlite3_step $VM + sqlite3_finalize $VM + set rc +} {0} +do_test attach2-3.2 { + set rc [catch {sqlite3_prepare $DB "DETACH t2" -1 TAIL} VM] + if {$rc} {lappend rc $VM} + sqlite3_step $VM + sqlite3_finalize $VM + set rc +} {0} + +db close +for {set i 2} {$i<=15} {incr i} { + catch {db$i close} +} + +# A procedure to verify the status of locks on a database. +# +proc lock_status {testnum db expected_result} { + # If the database was compiled with OMIT_TEMPDB set, then + # the lock_status list will not contain an entry for the temp + # db. But the test code doesn't know this, so its easiest + # to filter it out of the $expected_result list here. + ifcapable !tempdb { + set expected_result [concat \ + [lrange $expected_result 0 1] \ + [lrange $expected_result 4 end] \ + ] + } + do_test attach2-$testnum [subst { + $db cache flush ;# The lock_status pragma should not be cached + execsql {PRAGMA lock_status} $db + }] $expected_result +} +set sqlite_os_trace 0 + +# Tests attach2-4.* test that read-locks work correctly with attached +# databases. +do_test attach2-4.1 { + sqlite3 db test.db + sqlite3 db2 test.db + execsql {ATTACH 'test2.db' as file2} + execsql {ATTACH 'test2.db' as file2} db2 +} {} + +lock_status 4.1.1 db {main unlocked temp closed file2 unlocked} +lock_status 4.1.2 db2 {main unlocked temp closed file2 unlocked} + +do_test attach2-4.2 { + # Handle 'db' read-locks test.db + execsql {BEGIN} + execsql {SELECT * FROM t1} + # Lock status: + # db - shared(main) + # db2 - +} {} + +lock_status 4.2.1 db {main shared temp closed file2 unlocked} +lock_status 4.2.2 db2 {main unlocked temp closed file2 unlocked} + +do_test attach2-4.3 { + # The read lock held by db does not prevent db2 from reading test.db + execsql {SELECT * FROM t1} db2 +} {} + +lock_status 4.3.1 db {main shared temp closed file2 unlocked} +lock_status 4.3.2 db2 {main unlocked temp closed file2 unlocked} + +do_test attach2-4.4 { + # db is holding a read lock on test.db, so we should not be able + # to commit a write to test.db from db2 + catchsql { + INSERT INTO t1 VALUES(1, 2) + } db2 +} {1 {database is locked}} + +lock_status 4.4.1 db {main shared temp closed file2 unlocked} +lock_status 4.4.2 db2 {main unlocked temp closed file2 unlocked} + +# We have to make sure that the cache_size and the soft_heap_limit +# are large enough to hold the entire change in memory. If either +# is set too small, then changes will spill to the database, forcing +# a reserved lock to promote to exclusive. That will mess up our +# test results. + +set soft_limit [sqlite3_soft_heap_limit 0] + + +do_test attach2-4.5 { + # Handle 'db2' reserves file2. + execsql {BEGIN} db2 + execsql {INSERT INTO file2.t1 VALUES(1, 2)} db2 + # Lock status: + # db - shared(main) + # db2 - reserved(file2) +} {} + +lock_status 4.5.1 db {main shared temp closed file2 unlocked} +lock_status 4.5.2 db2 {main unlocked temp closed file2 reserved} + +do_test attach2-4.6.1 { + # Reads are allowed against a reserved database. + catchsql { + SELECT * FROM file2.t1; + } + # Lock status: + # db - shared(main), shared(file2) + # db2 - reserved(file2) +} {0 {}} + +lock_status 4.6.1.1 db {main shared temp closed file2 shared} +lock_status 4.6.1.2 db2 {main unlocked temp closed file2 reserved} + +do_test attach2-4.6.2 { + # Writes against a reserved database are not allowed. + catchsql { + UPDATE file2.t1 SET a=0; + } +} {1 {database is locked}} + +lock_status 4.6.2.1 db {main shared temp closed file2 shared} +lock_status 4.6.2.2 db2 {main unlocked temp closed file2 reserved} + +do_test attach2-4.7 { + # Ensure handle 'db' retains the lock on the main file after + # failing to obtain a write-lock on file2. + catchsql { + INSERT INTO t1 VALUES(1, 2) + } db2 +} {0 {}} + +lock_status 4.7.1 db {main shared temp closed file2 shared} +lock_status 4.7.2 db2 {main reserved temp closed file2 reserved} + +do_test attach2-4.8 { + # We should still be able to read test.db from db2 + execsql {SELECT * FROM t1} db2 +} {1 2} + +lock_status 4.8.1 db {main shared temp closed file2 shared} +lock_status 4.8.2 db2 {main reserved temp closed file2 reserved} + +do_test attach2-4.9 { + # Try to upgrade the handle 'db' lock. + catchsql { + INSERT INTO t1 VALUES(1, 2) + } +} {1 {database is locked}} + +lock_status 4.9.1 db {main shared temp closed file2 shared} +lock_status 4.9.2 db2 {main reserved temp closed file2 reserved} + +do_test attach2-4.10 { + # We cannot commit db2 while db is holding a read-lock + catchsql {COMMIT} db2 +} {1 {database is locked}} + +lock_status 4.10.1 db {main shared temp closed file2 shared} +lock_status 4.10.2 db2 {main pending temp closed file2 reserved} + +set sqlite_os_trace 0 +do_test attach2-4.11 { + # db is able to commit. + catchsql {COMMIT} +} {0 {}} + +lock_status 4.11.1 db {main unlocked temp closed file2 unlocked} +lock_status 4.11.2 db2 {main pending temp closed file2 reserved} + +do_test attach2-4.12 { + # Now we can commit db2 + catchsql {COMMIT} db2 +} {0 {}} + +lock_status 4.12.1 db {main unlocked temp closed file2 unlocked} +lock_status 4.12.2 db2 {main unlocked temp closed file2 unlocked} + +do_test attach2-4.13 { + execsql {SELECT * FROM file2.t1} +} {1 2} +do_test attach2-4.14 { + execsql {INSERT INTO t1 VALUES(1, 2)} +} {} +do_test attach2-4.15 { + execsql {SELECT * FROM t1} db2 +} {1 2 1 2} + +db close +db2 close +forcedelete test2.db +sqlite3_soft_heap_limit $soft_limit + +# These tests - attach2-5.* - check that the master journal file is deleted +# correctly when a multi-file transaction is committed or rolled back. +# +# Update: It's not actually created if a rollback occurs, so that test +# doesn't really prove too much. +foreach f [glob test.db*] {forcedelete $f} +do_test attach2-5.1 { + sqlite3 db test.db + execsql { + ATTACH 'test.db2' AS aux; + } +} {} +do_test attach2-5.2 { + execsql { + BEGIN; + CREATE TABLE tbl(a, b, c); + CREATE TABLE aux.tbl(a, b, c); + COMMIT; + } +} {} +do_test attach2-5.3 { + lsort [glob test.db*] +} {test.db test.db2} +do_test attach2-5.4 { + execsql { + BEGIN; + DROP TABLE aux.tbl; + DROP TABLE tbl; + ROLLBACK; + } +} {} +do_test attach2-5.5 { + lsort [glob test.db*] +} {test.db test.db2} + +# Check that a database cannot be ATTACHed or DETACHed during a transaction. +do_test attach2-6.1 { + execsql { + BEGIN; + } +} {} +do_test attach2-6.2 { + catchsql { + ATTACH 'test3.db' as aux2; + } +} {1 {cannot ATTACH database within transaction}} + +# EVIDENCE-OF: R-59740-55581 This statement will fail if SQLite is in +# the middle of a transaction. +# +do_test attach2-6.3 { + catchsql { + DETACH aux; + } +} {1 {cannot DETACH database within transaction}} +do_test attach2-6.4 { + execsql { + COMMIT; + DETACH aux; + } +} {} + +db close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/attach3.test b/components/external/SQLite-3.8.1/test/attach3.test new file mode 100644 index 0000000000000000000000000000000000000000..f861425346e71b053ecd8508f6a701cce9709cbd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/attach3.test @@ -0,0 +1,354 @@ +# 2003 July 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is testing the ATTACH and DETACH commands +# and schema changes to attached databases. +# +# $Id: attach3.test,v 1.18 2007/10/09 08:29:32 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !attach { + finish_test + return +} + +# The tests in this file were written before SQLite supported recursive +# trigger invocation, and some tests depend on that to pass. So disable +# recursive triggers for this file. +catchsql { pragma recursive_triggers = off } + +# Create tables t1 and t2 in the main database +execsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); +} + +# Create tables t1 and t2 in database file test2.db +forcedelete test2.db +forcedelete test2.db-journal +sqlite3 db2 test2.db +execsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); +} db2 +db2 close + +# Create a table in the auxilary database. +do_test attach3-1.1 { + execsql { + ATTACH 'test2.db' AS aux; + } +} {} +do_test attach3-1.2 { + execsql { + CREATE TABLE aux.t3(e, f); + } +} {} +do_test attach3-1.3 { + execsql { + SELECT * FROM sqlite_master WHERE name = 't3'; + } +} {} +do_test attach3-1.4 { + execsql { + SELECT * FROM aux.sqlite_master WHERE name = 't3'; + } +} "table t3 t3 [expr $AUTOVACUUM?5:4] {CREATE TABLE t3(e, f)}" +do_test attach3-1.5 { + execsql { + INSERT INTO t3 VALUES(1, 2); + SELECT * FROM t3; + } +} {1 2} + +# Create an index on the auxilary database table. +do_test attach3-2.1 { + execsql { + CREATE INDEX aux.i1 on t3(e); + } +} {} +do_test attach3-2.2 { + execsql { + SELECT * FROM sqlite_master WHERE name = 'i1'; + } +} {} +do_test attach3-2.3 { + execsql { + SELECT * FROM aux.sqlite_master WHERE name = 'i1'; + } +} "index i1 t3 [expr $AUTOVACUUM?6:5] {CREATE INDEX i1 on t3(e)}" + +# Drop the index on the aux database table. +do_test attach3-3.1 { + execsql { + DROP INDEX aux.i1; + SELECT * FROM aux.sqlite_master WHERE name = 'i1'; + } +} {} +do_test attach3-3.2 { + execsql { + CREATE INDEX aux.i1 on t3(e); + SELECT * FROM aux.sqlite_master WHERE name = 'i1'; + } +} "index i1 t3 [expr $AUTOVACUUM?6:5] {CREATE INDEX i1 on t3(e)}" +do_test attach3-3.3 { + execsql { + DROP INDEX i1; + SELECT * FROM aux.sqlite_master WHERE name = 'i1'; + } +} {} + +# Drop tables t1 and t2 in the auxilary database. +do_test attach3-4.1 { + execsql { + DROP TABLE aux.t1; + SELECT name FROM aux.sqlite_master; + } +} {t2 t3} +do_test attach3-4.2 { + # This will drop main.t2 + execsql { + DROP TABLE t2; + SELECT name FROM aux.sqlite_master; + } +} {t2 t3} +do_test attach3-4.3 { + execsql { + DROP TABLE t2; + SELECT name FROM aux.sqlite_master; + } +} {t3} + +# Create a view in the auxilary database. +ifcapable view { +do_test attach3-5.1 { + execsql { + CREATE VIEW aux.v1 AS SELECT * FROM t3; + } +} {} +do_test attach3-5.2 { + execsql { + SELECT * FROM aux.sqlite_master WHERE name = 'v1'; + } +} {view v1 v1 0 {CREATE VIEW v1 AS SELECT * FROM t3}} +do_test attach3-5.3 { + execsql { + INSERT INTO aux.t3 VALUES('hello', 'world'); + SELECT * FROM v1; + } +} {1 2 hello world} + +# Drop the view +do_test attach3-6.1 { + execsql { + DROP VIEW aux.v1; + } +} {} +do_test attach3-6.2 { + execsql { + SELECT * FROM aux.sqlite_master WHERE name = 'v1'; + } +} {} +} ;# ifcapable view + +ifcapable {trigger} { +# Create a trigger in the auxilary database. +do_test attach3-7.1 { + execsql { + CREATE TRIGGER aux.tr1 AFTER INSERT ON t3 BEGIN + INSERT INTO t3 VALUES(new.e*2, new.f*2); + END; + } +} {} +do_test attach3-7.2 { + execsql { + DELETE FROM t3; + INSERT INTO t3 VALUES(10, 20); + SELECT * FROM t3; + } +} {10 20 20 40} +do_test attach3-5.3 { + execsql { + SELECT * FROM aux.sqlite_master WHERE name = 'tr1'; + } +} {trigger tr1 t3 0 {CREATE TRIGGER tr1 AFTER INSERT ON t3 BEGIN + INSERT INTO t3 VALUES(new.e*2, new.f*2); + END}} + +# Drop the trigger +do_test attach3-8.1 { + execsql { + DROP TRIGGER aux.tr1; + } +} {} +do_test attach3-8.2 { + execsql { + SELECT * FROM aux.sqlite_master WHERE name = 'tr1'; + } +} {} + +ifcapable tempdb { + # Try to trick SQLite into dropping the wrong temp trigger. + do_test attach3-9.0 { + execsql { + CREATE TABLE main.t4(a, b, c); + CREATE TABLE aux.t4(a, b, c); + CREATE TEMP TRIGGER tst_trigger BEFORE INSERT ON aux.t4 BEGIN + SELECT 'hello world'; + END; + SELECT count(*) FROM sqlite_temp_master; + } + } {1} + do_test attach3-9.1 { + execsql { + DROP TABLE main.t4; + SELECT count(*) FROM sqlite_temp_master; + } + } {1} + do_test attach3-9.2 { + execsql { + DROP TABLE aux.t4; + SELECT count(*) FROM sqlite_temp_master; + } + } {0} +} +} ;# endif trigger + +# Make sure the aux.sqlite_master table is read-only +do_test attach3-10.0 { + catchsql { + INSERT INTO aux.sqlite_master VALUES(1, 2, 3, 4, 5); + } +} {1 {table sqlite_master may not be modified}} + +# Failure to attach leaves us in a workable state. +# Ticket #811 +# +do_test attach3-11.0 { + catchsql { + ATTACH DATABASE '/nodir/nofile.x' AS notadb; + } +} {1 {unable to open database: /nodir/nofile.x}} +do_test attach3-11.1 { + catchsql { + ATTACH DATABASE ':memory:' AS notadb; + } +} {0 {}} +do_test attach3-11.2 { + catchsql { + DETACH DATABASE notadb; + } +} {0 {}} + +# Return a list of attached databases +# +proc db_list {} { + set x [execsql { + PRAGMA database_list; + }] + set y {} + foreach {n id file} $x {lappend y $id} + return $y +} + +ifcapable schema_pragmas&&tempdb { + +ifcapable !trigger { + execsql {create temp table dummy(dummy)} +} + +# Ticket #1825 +# +do_test attach3-12.1 { + db_list +} {main temp aux} +do_test attach3-12.2 { + execsql { + ATTACH DATABASE ? AS ? + } + db_list +} {main temp aux {}} +do_test attach3-12.3 { + execsql { + DETACH aux + } + db_list +} {main temp {}} +do_test attach3-12.4 { + execsql { + DETACH ? + } + db_list +} {main temp} +do_test attach3-12.5 { + execsql { + ATTACH DATABASE '' AS '' + } + db_list +} {main temp {}} +do_test attach3-12.6 { + execsql { + DETACH '' + } + db_list +} {main temp} +do_test attach3-12.7 { + execsql { + ATTACH DATABASE '' AS ? + } + db_list +} {main temp {}} +do_test attach3-12.8 { + execsql { + DETACH '' + } + db_list +} {main temp} +do_test attach3-12.9 { + execsql { + ATTACH DATABASE '' AS NULL + } + db_list +} {main temp {}} +do_test attach3-12.10 { +breakpoint + execsql { + DETACH ? + } + db_list +} {main temp} +do_test attach3-12.11 { + catchsql { + DETACH NULL + } +} {1 {no such database: }} +do_test attach3-12.12 { + catchsql { + ATTACH null AS null; + ATTACH '' AS ''; + } +} {1 {database is already in use}} +do_test attach3-12.13 { + db_list +} {main temp {}} +do_test attach3-12.14 { + execsql { + DETACH ''; + } + db_list +} {main temp} + +} ;# ifcapable pragma + +finish_test diff --git a/components/external/SQLite-3.8.1/test/attach4.test b/components/external/SQLite-3.8.1/test/attach4.test new file mode 100644 index 0000000000000000000000000000000000000000..77dd7e41154f4a0523ddd110fb50b26b4a8c65b9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/attach4.test @@ -0,0 +1,118 @@ +# 200 July 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is attaching many database files to a single +# connection. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set testprefix attach4 + +ifcapable !attach { + finish_test + return +} + +puts "Testing with SQLITE_MAX_ATTACHED=$SQLITE_MAX_ATTACHED" + +set files {main test.db} +for {set ii 0} {$ii < $SQLITE_MAX_ATTACHED} {incr ii} { + lappend files aux$ii "test.db$ii" +} + +do_test 1.1 { + sqlite3_limit db SQLITE_LIMIT_ATTACHED -1 +} $SQLITE_MAX_ATTACHED + +do_test 1.2.1 { + db close + foreach {name f} $files { forcedelete $f } + sqlite3 db test.db + + foreach {name f} $files { + if {$name == "main"} continue + execsql "ATTACH '$f' AS $name" + } + + db eval {PRAGMA database_list} { + lappend L $name [file tail $file] + } + set L +} $files + +do_catchsql_test 1.2.2 { + ATTACH 'x.db' AS next; +} [list 1 "too many attached databases - max $SQLITE_MAX_ATTACHED"] + +do_test 1.3 { + execsql BEGIN; + foreach {name f} $files { + execsql "CREATE TABLE $name.tbl(x)" + execsql "INSERT INTO $name.tbl VALUES('$f')" + } + execsql COMMIT; +} {} + +do_test 1.4 { + set L [list] + foreach {name f} $files { + lappend L $name [execsql "SELECT x FROM $name.tbl"] + } + set L +} $files + +set L [list] +set S "" +foreach {name f} $files { + if {[permutation] == "journaltest"} { + set mode delete + } else { + set mode wal + } + ifcapable !wal { set mode delete } + lappend L $mode + append S " + PRAGMA $name.journal_mode = WAL; + UPDATE $name.tbl SET x = '$name'; + " +} +do_execsql_test 1.5 $S $L + +do_test 1.6 { + set L [list] + foreach {name f} $files { + lappend L [execsql "SELECT x FROM $name.tbl"] $f + } + set L +} $files + +do_test 1.7 { + execsql BEGIN; + foreach {name f} $files { + execsql "UPDATE $name.tbl SET x = '$f'" + } + execsql COMMIT; +} {} + +do_test 1.8 { + set L [list] + foreach {name f} $files { + lappend L $name [execsql "SELECT x FROM $name.tbl"] + } + set L +} $files + +db close +foreach {name f} $files { forcedelete $f } + +finish_test diff --git a/components/external/SQLite-3.8.1/test/attachmalloc.test b/components/external/SQLite-3.8.1/test/attachmalloc.test new file mode 100644 index 0000000000000000000000000000000000000000..7fee1e1b2a9ddaf536095d6e5de8e64647fdeef8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/attachmalloc.test @@ -0,0 +1,77 @@ +# 2005 September 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the ATTACH statement and +# specifically out-of-memory conditions within that command. +# +# $Id: attachmalloc.test,v 1.10 2008/10/22 10:45:38 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !memdebug||!attach { + finish_test + return +} + +source $testdir/malloc_common.tcl + +do_malloc_test attachmalloc-1 -tclprep { + catch { db close } + for {set i 2} {$i<=4} {incr i} { + catch { db$i close } + forcedelete test$i.db + forcedelete test$i.db-journal + } +} -tclbody { + if {[catch {sqlite3 db test.db}]} { + error "out of memory" + } + sqlite3_db_config_lookaside db 0 0 0 + sqlite3_extended_result_codes db 1 +} -sqlbody { + ATTACH 'test2.db' AS two; + CREATE TABLE two.t1(x); + ATTACH 'test3.db' AS three; + CREATE TABLE three.t1(x); + ATTACH 'test4.db' AS four; + CREATE TABLE four.t1(x); +} + +do_malloc_test attachmalloc-2 -tclprep { + forcedelete test2.db + forcedelete test2.db-journal + sqlite3 db2 test2.db + db2 eval { + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(a, b); + } + db2 close +} -sqlbody { + CREATE TABLE t1(d, e, f); + ATTACH 'test2.db' AS db1; +} + +set enable_shared_cache [sqlite3_enable_shared_cache 1] +sqlite3 dbaux test3.db +dbaux eval {SELECT * FROM sqlite_master} +do_malloc_test attachmalloc-3 -sqlbody { + SELECT * FROM sqlite_master; + ATTACH 'test3.db' AS three; +} -cleanup { + db eval { DETACH three } +} +dbaux close +sqlite3_enable_shared_cache $enable_shared_cache + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/auth.test b/components/external/SQLite-3.8.1/test/auth.test new file mode 100644 index 0000000000000000000000000000000000000000..5e91b33eaa879d25c7109d5cb6d16274d3ba6574 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/auth.test @@ -0,0 +1,2403 @@ +# 2003 April 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is testing the sqlite3_set_authorizer() API +# and related functionality. +# +# $Id: auth.test,v 1.46 2009/07/02 18:40:35 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# disable this test if the SQLITE_OMIT_AUTHORIZATION macro is +# defined during compilation. +if {[catch {db auth {}} msg]} { + finish_test + return +} + +rename proc proc_real +proc_real proc {name arguments script} { + proc_real $name $arguments $script + if {$name=="auth"} { + db authorizer ::auth + } +} + +do_test auth-1.1.1 { + db close + set ::DB [sqlite3 db test.db] + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + db authorizer ::auth + catchsql {CREATE TABLE t1(a,b,c)} +} {1 {not authorized}} +do_test auth-1.1.2 { + db errorcode +} {23} +do_test auth-1.1.3 { + db authorizer +} {::auth} +do_test auth-1.1.4 { + # Ticket #896. + catchsql { + SELECT x; + } +} {1 {no such column: x}} +do_test auth-1.2 { + execsql {SELECT name FROM sqlite_master} +} {} +do_test auth-1.3.1 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE TABLE t1(a,b,c)} +} {1 {not authorized}} +do_test auth-1.3.2 { + db errorcode +} {23} +do_test auth-1.3.3 { + set ::authargs +} {t1 {} main {}} +do_test auth-1.4 { + execsql {SELECT name FROM sqlite_master} +} {} + +ifcapable tempdb { + do_test auth-1.5 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE TEMP TABLE t1(a,b,c)} + } {1 {not authorized}} + do_test auth-1.6 { + execsql {SELECT name FROM sqlite_temp_master} + } {} + do_test auth-1.7.1 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE TEMP TABLE t1(a,b,c)} + } {1 {not authorized}} + do_test auth-1.7.2 { + set ::authargs + } {t1 {} temp {}} + do_test auth-1.8 { + execsql {SELECT name FROM sqlite_temp_master} + } {} +} + +do_test auth-1.9 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE TABLE t1(a,b,c)} +} {0 {}} +do_test auth-1.10 { + execsql {SELECT name FROM sqlite_master} +} {} +do_test auth-1.11 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE TABLE t1(a,b,c)} +} {0 {}} +do_test auth-1.12 { + execsql {SELECT name FROM sqlite_master} +} {} + +ifcapable tempdb { + do_test auth-1.13 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE TEMP TABLE t1(a,b,c)} + } {0 {}} + do_test auth-1.14 { + execsql {SELECT name FROM sqlite_temp_master} + } {} + do_test auth-1.15 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE TEMP TABLE t1(a,b,c)} + } {0 {}} + do_test auth-1.16 { + execsql {SELECT name FROM sqlite_temp_master} + } {} + + do_test auth-1.17 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE TEMP TABLE t1(a,b,c)} + } {0 {}} + do_test auth-1.18 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} +} + +do_test auth-1.19.1 { + set ::authargs {} + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE TABLE t2(a,b,c)} +} {0 {}} +do_test auth-1.19.2 { + set ::authargs +} {} +do_test auth-1.20 { + execsql {SELECT name FROM sqlite_master} +} {t2} + +do_test auth-1.21.1 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TABLE t2} +} {1 {not authorized}} +do_test auth-1.21.2 { + set ::authargs +} {t2 {} main {}} +do_test auth-1.22 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.23.1 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TABLE t2} +} {0 {}} +do_test auth-1.23.2 { + set ::authargs +} {t2 {} main {}} +do_test auth-1.24 { + execsql {SELECT name FROM sqlite_master} +} {t2} + +ifcapable tempdb { + do_test auth-1.25 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TABLE t1} + } {1 {not authorized}} + do_test auth-1.26 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} + do_test auth-1.27 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TABLE t1} + } {0 {}} + do_test auth-1.28 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} +} + +do_test auth-1.29 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="t2"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {INSERT INTO t2 VALUES(1,2,3)} +} {1 {not authorized}} +do_test auth-1.30 { + execsql {SELECT * FROM t2} +} {} +do_test auth-1.31 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="t2"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {INSERT INTO t2 VALUES(1,2,3)} +} {0 {}} +do_test auth-1.32 { + execsql {SELECT * FROM t2} +} {} +do_test auth-1.33 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="t1"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {INSERT INTO t2 VALUES(1,2,3)} +} {0 {}} +do_test auth-1.34 { + execsql {SELECT * FROM t2} +} {1 2 3} + +do_test auth-1.35.1 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2} +} {1 {access to t2.b is prohibited}} +ifcapable attach { + do_test auth-1.35.2 { + execsql {ATTACH DATABASE 'test.db' AS two} + catchsql {SELECT * FROM two.t2} + } {1 {access to two.t2.b is prohibited}} + execsql {DETACH DATABASE two} +} +do_test auth-1.36 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2} +} {0 {1 {} 3}} +do_test auth-1.37 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2 WHERE b=2} +} {0 {}} +do_test auth-1.38 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="a"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2 WHERE b=2} +} {0 {{} 2 3}} +do_test auth-1.39 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2 WHERE b IS NULL} +} {0 {1 {} 3}} +do_test auth-1.40 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="b"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {SELECT a,c FROM t2 WHERE b IS NULL} +} {1 {access to t2.b is prohibited}} + +do_test auth-1.41 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_UPDATE" && $arg1=="t2" && $arg2=="b"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {UPDATE t2 SET a=11} +} {0 {}} +do_test auth-1.42 { + execsql {SELECT * FROM t2} +} {11 2 3} +do_test auth-1.43 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_UPDATE" && $arg1=="t2" && $arg2=="b"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {UPDATE t2 SET b=22, c=33} +} {1 {not authorized}} +do_test auth-1.44 { + execsql {SELECT * FROM t2} +} {11 2 3} +do_test auth-1.45 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_UPDATE" && $arg1=="t2" && $arg2=="b"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {UPDATE t2 SET b=22, c=33} +} {0 {}} +do_test auth-1.46 { + execsql {SELECT * FROM t2} +} {11 2 33} + +do_test auth-1.47 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="t2"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DELETE FROM t2 WHERE a=11} +} {1 {not authorized}} +do_test auth-1.48 { + execsql {SELECT * FROM t2} +} {11 2 33} +do_test auth-1.49 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="t2"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DELETE FROM t2 WHERE a=11} +} {0 {}} +do_test auth-1.50 { + execsql {SELECT * FROM t2} +} {} +do_test auth-1.50.2 { + execsql {INSERT INTO t2 VALUES(11, 2, 33)} +} {} + +do_test auth-1.51 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_SELECT"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2} +} {1 {not authorized}} +do_test auth-1.52 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_SELECT"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2} +} {0 {}} +do_test auth-1.53 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_SELECT"} { + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2} +} {0 {11 2 33}} + +# Update for version 3: There used to be a handful of test here that +# tested the authorisation callback with the COPY command. The following +# test makes the same database modifications as they used to. +do_test auth-1.54 { + execsql {INSERT INTO t2 VALUES(7, 8, 9);} +} {} +do_test auth-1.55 { + execsql {SELECT * FROM t2} +} {11 2 33 7 8 9} + +do_test auth-1.63 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TABLE t2} +} {1 {not authorized}} +do_test auth-1.64 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.65 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="t2"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TABLE t2} +} {1 {not authorized}} +do_test auth-1.66 { + execsql {SELECT name FROM sqlite_master} +} {t2} + +ifcapable tempdb { + do_test auth-1.67 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TABLE t1} + } {1 {not authorized}} + do_test auth-1.68 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} + do_test auth-1.69 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="t1"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TABLE t1} + } {1 {not authorized}} + do_test auth-1.70 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} +} + +do_test auth-1.71 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TABLE t2} +} {0 {}} +do_test auth-1.72 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.73 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="t2"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TABLE t2} +} {0 {}} +do_test auth-1.74 { + execsql {SELECT name FROM sqlite_master} +} {t2} + +ifcapable tempdb { + do_test auth-1.75 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TABLE t1} + } {0 {}} + do_test auth-1.76 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} + do_test auth-1.77 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="t1"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TABLE t1} + } {0 {}} + do_test auth-1.78 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} +} + +# Test cases auth-1.79 to auth-1.124 test creating and dropping views. +# Omit these if the library was compiled with views omitted. +ifcapable view { +do_test auth-1.79 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE VIEW v1 AS SELECT a+1,b+1 FROM t2} +} {1 {not authorized}} +do_test auth-1.80 { + set ::authargs +} {v1 {} main {}} +do_test auth-1.81 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.82 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE VIEW v1 AS SELECT a+1,b+1 FROM t2} +} {0 {}} +do_test auth-1.83 { + set ::authargs +} {v1 {} main {}} +do_test auth-1.84 { + execsql {SELECT name FROM sqlite_master} +} {t2} + +ifcapable tempdb { + do_test auth-1.85 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE TEMPORARY VIEW v1 AS SELECT a+1,b+1 FROM t2} + } {1 {not authorized}} + do_test auth-1.86 { + set ::authargs + } {v1 {} temp {}} + do_test auth-1.87 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} + do_test auth-1.88 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE TEMPORARY VIEW v1 AS SELECT a+1,b+1 FROM t2} + } {0 {}} + do_test auth-1.89 { + set ::authargs + } {v1 {} temp {}} + do_test auth-1.90 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} +} + +do_test auth-1.91 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE VIEW v1 AS SELECT a+1,b+1 FROM t2} +} {1 {not authorized}} +do_test auth-1.92 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.93 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE VIEW v1 AS SELECT a+1,b+1 FROM t2} +} {0 {}} +do_test auth-1.94 { + execsql {SELECT name FROM sqlite_master} +} {t2} + +ifcapable tempdb { + do_test auth-1.95 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE TEMPORARY VIEW v1 AS SELECT a+1,b+1 FROM t2} + } {1 {not authorized}} + do_test auth-1.96 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} + do_test auth-1.97 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE TEMPORARY VIEW v1 AS SELECT a+1,b+1 FROM t2} + } {0 {}} + do_test auth-1.98 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} +} + +do_test auth-1.99 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + CREATE VIEW v2 AS SELECT a+1,b+1 FROM t2; + DROP VIEW v2 + } +} {1 {not authorized}} +do_test auth-1.100 { + execsql {SELECT name FROM sqlite_master} +} {t2 v2} +do_test auth-1.101 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP VIEW v2} +} {1 {not authorized}} +do_test auth-1.102 { + set ::authargs +} {v2 {} main {}} +do_test auth-1.103 { + execsql {SELECT name FROM sqlite_master} +} {t2 v2} +do_test auth-1.104 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP VIEW v2} +} {0 {}} +do_test auth-1.105 { + execsql {SELECT name FROM sqlite_master} +} {t2 v2} +do_test auth-1.106 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP VIEW v2} +} {0 {}} +do_test auth-1.107 { + set ::authargs +} {v2 {} main {}} +do_test auth-1.108 { + execsql {SELECT name FROM sqlite_master} +} {t2 v2} +do_test auth-1.109 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {DROP VIEW v2} +} {0 {}} +do_test auth-1.110 { + set ::authargs +} {v2 {} main {}} +do_test auth-1.111 { + execsql {SELECT name FROM sqlite_master} +} {t2} + + +ifcapable tempdb { + do_test auth-1.112 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + CREATE TEMP VIEW v1 AS SELECT a+1,b+1 FROM t1; + DROP VIEW v1 + } + } {1 {not authorized}} + do_test auth-1.113 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1 v1} + do_test auth-1.114 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP VIEW v1} + } {1 {not authorized}} + do_test auth-1.115 { + set ::authargs + } {v1 {} temp {}} + do_test auth-1.116 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1 v1} + do_test auth-1.117 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP VIEW v1} + } {0 {}} + do_test auth-1.118 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1 v1} + do_test auth-1.119 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP VIEW v1} + } {0 {}} + do_test auth-1.120 { + set ::authargs + } {v1 {} temp {}} + do_test auth-1.121 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1 v1} + do_test auth-1.122 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_VIEW"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {DROP VIEW v1} + } {0 {}} + do_test auth-1.123 { + set ::authargs + } {v1 {} temp {}} + do_test auth-1.124 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} +} +} ;# ifcapable view + +# Test cases auth-1.125 to auth-1.176 test creating and dropping triggers. +# Omit these if the library was compiled with triggers omitted. +# +ifcapable trigger&&tempdb { +do_test auth-1.125 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + CREATE TRIGGER r2 DELETE on t2 BEGIN + SELECT NULL; + END; + } +} {1 {not authorized}} +do_test auth-1.126 { + set ::authargs +} {r2 t2 main {}} +do_test auth-1.127 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.128 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + CREATE TRIGGER r2 DELETE on t2 BEGIN + SELECT NULL; + END; + } +} {1 {not authorized}} +do_test auth-1.129 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.130 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql { + CREATE TRIGGER r2 DELETE on t2 BEGIN + SELECT NULL; + END; + } +} {0 {}} +do_test auth-1.131 { + set ::authargs +} {r2 t2 main {}} +do_test auth-1.132 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.133 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql { + CREATE TRIGGER r2 DELETE on t2 BEGIN + SELECT NULL; + END; + } +} {0 {}} +do_test auth-1.134 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.135 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql { + CREATE TABLE tx(id); + CREATE TRIGGER r2 AFTER INSERT ON t2 BEGIN + INSERT INTO tx VALUES(NEW.rowid); + END; + } +} {0 {}} +do_test auth-1.136.1 { + set ::authargs +} {r2 t2 main {}} +do_test auth-1.136.2 { + execsql { + SELECT name FROM sqlite_master WHERE type='trigger' + } +} {r2} +do_test auth-1.136.3 { + proc auth {code arg1 arg2 arg3 arg4} { + lappend ::authargs $code $arg1 $arg2 $arg3 $arg4 + return SQLITE_OK + } + set ::authargs {} + execsql { + INSERT INTO t2 VALUES(1,2,3); + } + set ::authargs +} {SQLITE_INSERT t2 {} main {} SQLITE_INSERT tx {} main r2 SQLITE_READ t2 ROWID main r2} +do_test auth-1.136.4 { + execsql { + SELECT * FROM tx; + } +} {3} +do_test auth-1.137 { + execsql {SELECT name FROM sqlite_master} +} {t2 tx r2} +do_test auth-1.138 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + CREATE TRIGGER r1 DELETE on t1 BEGIN + SELECT NULL; + END; + } +} {1 {not authorized}} +do_test auth-1.139 { + set ::authargs +} {r1 t1 temp {}} +do_test auth-1.140 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1} +do_test auth-1.141 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + CREATE TRIGGER r1 DELETE on t1 BEGIN + SELECT NULL; + END; + } +} {1 {not authorized}} +do_test auth-1.142 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1} +do_test auth-1.143 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql { + CREATE TRIGGER r1 DELETE on t1 BEGIN + SELECT NULL; + END; + } +} {0 {}} +do_test auth-1.144 { + set ::authargs +} {r1 t1 temp {}} +do_test auth-1.145 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1} +do_test auth-1.146 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql { + CREATE TRIGGER r1 DELETE on t1 BEGIN + SELECT NULL; + END; + } +} {0 {}} +do_test auth-1.147 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1} +do_test auth-1.148 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql { + CREATE TRIGGER r1 DELETE on t1 BEGIN + SELECT NULL; + END; + } +} {0 {}} +do_test auth-1.149 { + set ::authargs +} {r1 t1 temp {}} +do_test auth-1.150 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1 r1} + +do_test auth-1.151 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r2} +} {1 {not authorized}} +do_test auth-1.152 { + execsql {SELECT name FROM sqlite_master} +} {t2 tx r2} +do_test auth-1.153 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r2} +} {1 {not authorized}} +do_test auth-1.154 { + set ::authargs +} {r2 t2 main {}} +do_test auth-1.155 { + execsql {SELECT name FROM sqlite_master} +} {t2 tx r2} +do_test auth-1.156 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r2} +} {0 {}} +do_test auth-1.157 { + execsql {SELECT name FROM sqlite_master} +} {t2 tx r2} +do_test auth-1.158 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r2} +} {0 {}} +do_test auth-1.159 { + set ::authargs +} {r2 t2 main {}} +do_test auth-1.160 { + execsql {SELECT name FROM sqlite_master} +} {t2 tx r2} +do_test auth-1.161 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r2} +} {0 {}} +do_test auth-1.162 { + set ::authargs +} {r2 t2 main {}} +do_test auth-1.163 { + execsql { + DROP TABLE tx; + DELETE FROM t2 WHERE a=1 AND b=2 AND c=3; + SELECT name FROM sqlite_master; + } +} {t2} + +do_test auth-1.164 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r1} +} {1 {not authorized}} +do_test auth-1.165 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1 r1} +do_test auth-1.166 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r1} +} {1 {not authorized}} +do_test auth-1.167 { + set ::authargs +} {r1 t1 temp {}} +do_test auth-1.168 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1 r1} +do_test auth-1.169 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r1} +} {0 {}} +do_test auth-1.170 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1 r1} +do_test auth-1.171 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r1} +} {0 {}} +do_test auth-1.172 { + set ::authargs +} {r1 t1 temp {}} +do_test auth-1.173 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1 r1} +do_test auth-1.174 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_TRIGGER"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {DROP TRIGGER r1} +} {0 {}} +do_test auth-1.175 { + set ::authargs +} {r1 t1 temp {}} +do_test auth-1.176 { + execsql {SELECT name FROM sqlite_temp_master} +} {t1} +} ;# ifcapable trigger + +do_test auth-1.177 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE INDEX i2 ON t2(a)} +} {1 {not authorized}} +do_test auth-1.178 { + set ::authargs +} {i2 t2 main {}} +do_test auth-1.179 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.180 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE INDEX i2 ON t2(a)} +} {1 {not authorized}} +do_test auth-1.181 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.182 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE INDEX i2 ON t2(b)} +} {0 {}} +do_test auth-1.183 { + set ::authargs +} {i2 t2 main {}} +do_test auth-1.184 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.185 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE INDEX i2 ON t2(b)} +} {0 {}} +do_test auth-1.186 { + execsql {SELECT name FROM sqlite_master} +} {t2} +do_test auth-1.187 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {CREATE INDEX i2 ON t2(a)} +} {0 {}} +do_test auth-1.188 { + set ::authargs +} {i2 t2 main {}} +do_test auth-1.189 { + execsql {SELECT name FROM sqlite_master} +} {t2 i2} + +ifcapable tempdb { + do_test auth-1.190 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE INDEX i1 ON t1(a)} + } {1 {not authorized}} + do_test auth-1.191 { + set ::authargs + } {i1 t1 temp {}} + do_test auth-1.192 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} + do_test auth-1.193 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {CREATE INDEX i1 ON t1(b)} + } {1 {not authorized}} + do_test auth-1.194 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} + do_test auth-1.195 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE INDEX i1 ON t1(b)} + } {0 {}} + do_test auth-1.196 { + set ::authargs + } {i1 t1 temp {}} + do_test auth-1.197 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} + do_test auth-1.198 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_INSERT" && $arg1=="sqlite_temp_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {CREATE INDEX i1 ON t1(c)} + } {0 {}} + do_test auth-1.199 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} + do_test auth-1.200 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_CREATE_TEMP_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {CREATE INDEX i1 ON t1(a)} + } {0 {}} + do_test auth-1.201 { + set ::authargs + } {i1 t1 temp {}} + do_test auth-1.202 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1 i1} +} + +do_test auth-1.203 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP INDEX i2} +} {1 {not authorized}} +do_test auth-1.204 { + execsql {SELECT name FROM sqlite_master} +} {t2 i2} +do_test auth-1.205 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP INDEX i2} +} {1 {not authorized}} +do_test auth-1.206 { + set ::authargs +} {i2 t2 main {}} +do_test auth-1.207 { + execsql {SELECT name FROM sqlite_master} +} {t2 i2} +do_test auth-1.208 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP INDEX i2} +} {0 {}} +do_test auth-1.209 { + execsql {SELECT name FROM sqlite_master} +} {t2 i2} +do_test auth-1.210 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP INDEX i2} +} {0 {}} +do_test auth-1.211 { + set ::authargs +} {i2 t2 main {}} +do_test auth-1.212 { + execsql {SELECT name FROM sqlite_master} +} {t2 i2} +do_test auth-1.213 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {DROP INDEX i2} +} {0 {}} +do_test auth-1.214 { + set ::authargs +} {i2 t2 main {}} +do_test auth-1.215 { + execsql {SELECT name FROM sqlite_master} +} {t2} + +ifcapable tempdb { + do_test auth-1.216 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} { + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP INDEX i1} + } {1 {not authorized}} + do_test auth-1.217 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1 i1} + do_test auth-1.218 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {DROP INDEX i1} + } {1 {not authorized}} + do_test auth-1.219 { + set ::authargs + } {i1 t1 temp {}} + do_test auth-1.220 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1 i1} + do_test auth-1.221 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE" && $arg1=="sqlite_temp_master"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP INDEX i1} + } {0 {}} + do_test auth-1.222 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1 i1} + do_test auth-1.223 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {DROP INDEX i1} + } {0 {}} + do_test auth-1.224 { + set ::authargs + } {i1 t1 temp {}} + do_test auth-1.225 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1 i1} + do_test auth-1.226 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DROP_TEMP_INDEX"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {DROP INDEX i1} + } {0 {}} + do_test auth-1.227 { + set ::authargs + } {i1 t1 temp {}} + do_test auth-1.228 { + execsql {SELECT name FROM sqlite_temp_master} + } {t1} +} + +do_test auth-1.229 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_PRAGMA"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {PRAGMA full_column_names=on} +} {1 {not authorized}} +do_test auth-1.230 { + set ::authargs +} {full_column_names on {} {}} +do_test auth-1.231 { + execsql2 {SELECT a FROM t2} +} {a 11 a 7} +do_test auth-1.232 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_PRAGMA"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {PRAGMA full_column_names=on} +} {0 {}} +do_test auth-1.233 { + set ::authargs +} {full_column_names on {} {}} +do_test auth-1.234 { + execsql2 {SELECT a FROM t2} +} {a 11 a 7} +do_test auth-1.235 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_PRAGMA"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {PRAGMA full_column_names=on} +} {0 {}} +do_test auth-1.236 { + execsql2 {SELECT a FROM t2} +} {t2.a 11 t2.a 7} +do_test auth-1.237 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_PRAGMA"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql {PRAGMA full_column_names=OFF} +} {0 {}} +do_test auth-1.238 { + set ::authargs +} {full_column_names OFF {} {}} +do_test auth-1.239 { + execsql2 {SELECT a FROM t2} +} {a 11 a 7} + +do_test auth-1.240 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_TRANSACTION"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {BEGIN} +} {1 {not authorized}} +do_test auth-1.241 { + set ::authargs +} {BEGIN {} {} {}} +do_test auth-1.242 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_TRANSACTION" && $arg1!="BEGIN"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql {BEGIN; INSERT INTO t2 VALUES(44,55,66); COMMIT} +} {1 {not authorized}} +do_test auth-1.243 { + set ::authargs +} {COMMIT {} {} {}} +do_test auth-1.244 { + execsql {SELECT * FROM t2} +} {11 2 33 7 8 9 44 55 66} +do_test auth-1.245 { + catchsql {ROLLBACK} +} {1 {not authorized}} +do_test auth-1.246 { + set ::authargs +} {ROLLBACK {} {} {}} +do_test auth-1.247 { + catchsql {END TRANSACTION} +} {1 {not authorized}} +do_test auth-1.248 { + set ::authargs +} {COMMIT {} {} {}} +do_test auth-1.249 { + db authorizer {} + catchsql {ROLLBACK} +} {0 {}} +do_test auth-1.250 { + execsql {SELECT * FROM t2} +} {11 2 33 7 8 9} + +# ticket #340 - authorization for ATTACH and DETACH. +# +ifcapable attach { + do_test auth-1.251 { + db authorizer ::auth + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ATTACH"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + } + return SQLITE_OK + } + catchsql { + ATTACH DATABASE ':memory:' AS test1 + } + } {0 {}} + do_test auth-1.252a { + set ::authargs + } {:memory: {} {} {}} + do_test auth-1.252b { + db eval {DETACH test1} + set ::attachfilename :memory: + db eval {ATTACH $::attachfilename AS test1} + set ::authargs + } {{} {} {} {}} + do_test auth-1.252c { + db eval {DETACH test1} + db eval {ATTACH ':mem' || 'ory:' AS test1} + set ::authargs + } {{} {} {} {}} + do_test auth-1.253 { + catchsql {DETACH DATABASE test1} + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ATTACH"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + ATTACH DATABASE ':memory:' AS test1; + } + } {1 {not authorized}} + do_test auth-1.254 { + lindex [execsql {PRAGMA database_list}] 7 + } {} + do_test auth-1.255 { + catchsql {DETACH DATABASE test1} + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ATTACH"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql { + ATTACH DATABASE ':memory:' AS test1; + } + } {0 {}} + do_test auth-1.256 { + lindex [execsql {PRAGMA database_list}] 7 + } {} + do_test auth-1.257 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DETACH"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + execsql {ATTACH DATABASE ':memory:' AS test1} + catchsql { + DETACH DATABASE test1; + } + } {0 {}} + do_test auth-1.258 { + lindex [execsql {PRAGMA database_list}] 7 + } {} + do_test auth-1.259 { + execsql {ATTACH DATABASE ':memory:' AS test1} + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DETACH"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql { + DETACH DATABASE test1; + } + } {0 {}} + ifcapable tempdb { + ifcapable schema_pragmas { + do_test auth-1.260 { + lindex [execsql {PRAGMA database_list}] 7 + } {test1} + } ;# ifcapable schema_pragmas + do_test auth-1.261 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DETACH"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + DETACH DATABASE test1; + } + } {1 {not authorized}} + ifcapable schema_pragmas { + do_test auth-1.262 { + lindex [execsql {PRAGMA database_list}] 7 + } {test1} + } ;# ifcapable schema_pragmas + db authorizer {} + execsql {DETACH DATABASE test1} + db authorizer ::auth + + # Authorization for ALTER TABLE. These tests are omitted if the library + # was built without ALTER TABLE support. + ifcapable altertable { + + do_test auth-1.263 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ALTER_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql { + ALTER TABLE t1 RENAME TO t1x + } + } {0 {}} + do_test auth-1.264 { + execsql {SELECT name FROM sqlite_temp_master WHERE type='table'} + } {t1x} + do_test auth-1.265 { + set authargs + } {temp t1 {} {}} + do_test auth-1.266 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ALTER_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql { + ALTER TABLE t1x RENAME TO t1 + } + } {0 {}} + do_test auth-1.267 { + execsql {SELECT name FROM sqlite_temp_master WHERE type='table'} + } {t1x} + do_test auth-1.268 { + set authargs + } {temp t1x {} {}} + do_test auth-1.269 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ALTER_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + ALTER TABLE t1x RENAME TO t1 + } + } {1 {not authorized}} + do_test auth-1.270 { + execsql {SELECT name FROM sqlite_temp_master WHERE type='table'} + } {t1x} + + do_test auth-1.271 { + set authargs + } {temp t1x {} {}} + } ;# ifcapable altertable + + } else { + db authorizer {} + db eval { + DETACH DATABASE test1; + } + } +} + +ifcapable altertable { +db authorizer {} +catchsql {ALTER TABLE t1x RENAME TO t1} +db authorizer ::auth +do_test auth-1.272 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ALTER_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql { + ALTER TABLE t2 RENAME TO t2x + } +} {0 {}} +do_test auth-1.273 { + execsql {SELECT name FROM sqlite_master WHERE type='table'} +} {t2x} +do_test auth-1.274 { + set authargs +} {main t2 {} {}} +do_test auth-1.275 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ALTER_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql { + ALTER TABLE t2x RENAME TO t2 + } +} {0 {}} +do_test auth-1.276 { + execsql {SELECT name FROM sqlite_master WHERE type='table'} +} {t2x} +do_test auth-1.277 { + set authargs +} {main t2x {} {}} +do_test auth-1.278 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ALTER_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + ALTER TABLE t2x RENAME TO t2 + } +} {1 {not authorized}} +do_test auth-1.279 { + execsql {SELECT name FROM sqlite_master WHERE type='table'} +} {t2x} +do_test auth-1.280 { + set authargs +} {main t2x {} {}} +db authorizer {} +catchsql {ALTER TABLE t2x RENAME TO t2} + +} ;# ifcapable altertable + +# Test the authorization callbacks for the REINDEX command. +ifcapable reindex { + +proc auth {code args} { + if {$code=="SQLITE_REINDEX"} { + set ::authargs [concat $::authargs $args] + } + return SQLITE_OK +} +db authorizer auth +do_test auth-1.281 { + execsql { + CREATE TABLE t3(a PRIMARY KEY, b, c); + CREATE INDEX t3_idx1 ON t3(c COLLATE BINARY); + CREATE INDEX t3_idx2 ON t3(b COLLATE NOCASE); + } +} {} +do_test auth-1.282 { + set ::authargs {} + execsql { + REINDEX t3_idx1; + } + set ::authargs +} {t3_idx1 {} main {}} +do_test auth-1.283 { + set ::authargs {} + execsql { + REINDEX BINARY; + } + set ::authargs +} {t3_idx1 {} main {} sqlite_autoindex_t3_1 {} main {}} +do_test auth-1.284 { + set ::authargs {} + execsql { + REINDEX NOCASE; + } + set ::authargs +} {t3_idx2 {} main {}} +do_test auth-1.285 { + set ::authargs {} + execsql { + REINDEX t3; + } + set ::authargs +} {t3_idx2 {} main {} t3_idx1 {} main {} sqlite_autoindex_t3_1 {} main {}} +do_test auth-1.286 { + execsql { + DROP TABLE t3; + } +} {} +ifcapable tempdb { + do_test auth-1.287 { + execsql { + CREATE TEMP TABLE t3(a PRIMARY KEY, b, c); + CREATE INDEX t3_idx1 ON t3(c COLLATE BINARY); + CREATE INDEX t3_idx2 ON t3(b COLLATE NOCASE); + } + } {} + do_test auth-1.288 { + set ::authargs {} + execsql { + REINDEX temp.t3_idx1; + } + set ::authargs + } {t3_idx1 {} temp {}} + do_test auth-1.289 { + set ::authargs {} + execsql { + REINDEX BINARY; + } + set ::authargs + } {t3_idx1 {} temp {} sqlite_autoindex_t3_1 {} temp {}} + do_test auth-1.290 { + set ::authargs {} + execsql { + REINDEX NOCASE; + } + set ::authargs + } {t3_idx2 {} temp {}} + do_test auth-1.291 { + set ::authargs {} + execsql { + REINDEX temp.t3; + } + set ::authargs + } {t3_idx2 {} temp {} t3_idx1 {} temp {} sqlite_autoindex_t3_1 {} temp {}} + proc auth {code args} { + if {$code=="SQLITE_REINDEX"} { + set ::authargs [concat $::authargs $args] + return SQLITE_DENY + } + return SQLITE_OK + } + do_test auth-1.292 { + set ::authargs {} + catchsql { + REINDEX temp.t3; + } + } {1 {not authorized}} + do_test auth-1.293 { + execsql { + DROP TABLE t3; + } + } {} +} + +} ;# ifcapable reindex + +ifcapable analyze { + proc auth {code args} { + if {$code=="SQLITE_ANALYZE"} { + set ::authargs [concat $::authargs $args] + } + return SQLITE_OK + } + do_test auth-1.294 { + set ::authargs {} + execsql { + CREATE TABLE t4(a,b,c); + CREATE INDEX t4i1 ON t4(a); + CREATE INDEX t4i2 ON t4(b,a,c); + INSERT INTO t4 VALUES(1,2,3); + ANALYZE; + } + set ::authargs + } {t4 {} main {} t2 {} main {}} + do_test auth-1.295 { + execsql { + SELECT count(*) FROM sqlite_stat1; + } + } 3 + proc auth {code args} { + if {$code=="SQLITE_ANALYZE"} { + set ::authargs [concat $::authargs $args] + return SQLITE_DENY + } + return SQLITE_OK + } + do_test auth-1.296 { + set ::authargs {} + catchsql { + ANALYZE; + } + } {1 {not authorized}} + do_test auth-1.297 { + execsql { + SELECT count(*) FROM sqlite_stat1; + } + } 3 +} ;# ifcapable analyze + + +# Authorization for ALTER TABLE ADD COLUMN. +# These tests are omitted if the library +# was built without ALTER TABLE support. +ifcapable {altertable} { + do_test auth-1.300 { + execsql {CREATE TABLE t5(x)} + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ALTER_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_OK + } + return SQLITE_OK + } + catchsql { + ALTER TABLE t5 ADD COLUMN new_col_1; + } + } {0 {}} + do_test auth-1.301 { + set x [execsql {SELECT sql FROM sqlite_master WHERE name='t5'}] + regexp new_col_1 $x + } {1} + do_test auth-1.302 { + set authargs + } {main t5 {} {}} + do_test auth-1.303 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ALTER_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql { + ALTER TABLE t5 ADD COLUMN new_col_2; + } + } {0 {}} + do_test auth-1.304 { + set x [execsql {SELECT sql FROM sqlite_master WHERE name='t5'}] + regexp new_col_2 $x + } {0} + do_test auth-1.305 { + set authargs + } {main t5 {} {}} + do_test auth-1.306 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_ALTER_TABLE"} { + set ::authargs [list $arg1 $arg2 $arg3 $arg4] + return SQLITE_DENY + } + return SQLITE_OK + } + catchsql { + ALTER TABLE t5 ADD COLUMN new_col_3 + } + } {1 {not authorized}} + do_test auth-1.307 { + set x [execsql {SELECT sql FROM sqlite_temp_master WHERE type='t5'}] + regexp new_col_3 $x + } {0} + + do_test auth-1.308 { + set authargs + } {main t5 {} {}} + execsql {DROP TABLE t5} +} ;# ifcapable altertable + +do_test auth-2.1 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t3" && $arg2=="x"} { + return SQLITE_DENY + } + return SQLITE_OK + } + db authorizer ::auth + execsql {CREATE TABLE t3(x INTEGER PRIMARY KEY, y, z)} + catchsql {SELECT * FROM t3} +} {1 {access to t3.x is prohibited}} +do_test auth-2.1 { + catchsql {SELECT y,z FROM t3} +} {0 {}} +do_test auth-2.2 { + catchsql {SELECT ROWID,y,z FROM t3} +} {1 {access to t3.x is prohibited}} +do_test auth-2.3 { + catchsql {SELECT OID,y,z FROM t3} +} {1 {access to t3.x is prohibited}} +do_test auth-2.4 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t3" && $arg2=="x"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + execsql {INSERT INTO t3 VALUES(44,55,66)} + catchsql {SELECT * FROM t3} +} {0 {{} 55 66}} +do_test auth-2.5 { + catchsql {SELECT rowid,y,z FROM t3} +} {0 {{} 55 66}} +do_test auth-2.6 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t3" && $arg2=="ROWID"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {SELECT * FROM t3} +} {0 {44 55 66}} +do_test auth-2.7 { + catchsql {SELECT ROWID,y,z FROM t3} +} {0 {44 55 66}} +do_test auth-2.8 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="ROWID"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {SELECT ROWID,b,c FROM t2} +} {0 {{} 2 33 {} 8 9}} +do_test auth-2.9.1 { + # We have to flush the cache here in case the Tcl interface tries to + # reuse a statement compiled with sqlite3_prepare_v2(). In this case, + # the first error encountered is an SQLITE_SCHEMA error. Then, when + # trying to recompile the statement, the authorization error is encountered. + # If we do not flush the cache, the correct error message is returned, but + # the error code is SQLITE_SCHEMA, not SQLITE_ERROR as required by the test + # case after this one. + # + db cache flush + + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="ROWID"} { + return bogus + } + return SQLITE_OK + } + catchsql {SELECT ROWID,b,c FROM t2} +} {1 {authorizer malfunction}} +do_test auth-2.9.2 { + db errorcode +} {1} +do_test auth-2.10 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_SELECT"} { + return bogus + } + return SQLITE_OK + } + catchsql {SELECT ROWID,b,c FROM t2} +} {1 {authorizer malfunction}} +do_test auth-2.11.1 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg2=="a"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2, t3} +} {0 {{} 2 33 44 55 66 {} 8 9 44 55 66}} +do_test auth-2.11.2 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg2=="x"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + catchsql {SELECT * FROM t2, t3} +} {0 {11 2 33 {} 55 66 7 8 9 {} 55 66}} + +# Make sure the OLD and NEW pseudo-tables of a trigger get authorized. +# +ifcapable trigger { + do_test auth-3.1 { + proc auth {code arg1 arg2 arg3 arg4} { + return SQLITE_OK + } + execsql { + CREATE TABLE tx(a1,a2,b1,b2,c1,c2); + CREATE TRIGGER r1 AFTER UPDATE ON t2 FOR EACH ROW BEGIN + INSERT INTO tx VALUES(OLD.a,NEW.a,OLD.b,NEW.b,OLD.c,NEW.c); + END; + UPDATE t2 SET a=a+1; + SELECT * FROM tx; + } + } {11 12 2 2 33 33 7 8 8 8 9 9} + do_test auth-3.2 { + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_READ" && $arg1=="t2" && $arg2=="c"} { + return SQLITE_IGNORE + } + return SQLITE_OK + } + execsql { + DELETE FROM tx; + UPDATE t2 SET a=a+100; + SELECT * FROM tx; + } + } {12 112 2 2 {} {} 8 108 8 8 {} {}} +} ;# ifcapable trigger + +# Make sure the names of views and triggers are passed on on arg4. +# +ifcapable trigger { +do_test auth-4.1 { + proc auth {code arg1 arg2 arg3 arg4} { + lappend ::authargs $code $arg1 $arg2 $arg3 $arg4 + return SQLITE_OK + } + set authargs {} + execsql { + UPDATE t2 SET a=a+1; + } + set authargs +} [list \ + SQLITE_READ t2 a main {} \ + SQLITE_UPDATE t2 a main {} \ + SQLITE_INSERT tx {} main r1 \ + SQLITE_READ t2 a main r1 \ + SQLITE_READ t2 a main r1 \ + SQLITE_READ t2 b main r1 \ + SQLITE_READ t2 b main r1 \ + SQLITE_READ t2 c main r1 \ + SQLITE_READ t2 c main r1] +} + +ifcapable {view && trigger} { +do_test auth-4.2 { + execsql { + CREATE VIEW v1 AS SELECT a+b AS x FROM t2; + CREATE TABLE v1chng(x1,x2); + CREATE TRIGGER r2 INSTEAD OF UPDATE ON v1 BEGIN + INSERT INTO v1chng VALUES(OLD.x,NEW.x); + END; + SELECT * FROM v1; + } +} {115 117} +do_test auth-4.3 { + set authargs {} + execsql { + UPDATE v1 SET x=1 WHERE x=117 + } + set authargs +} [list \ + SQLITE_UPDATE v1 x main {} \ + SQLITE_SELECT {} {} {} v1 \ + SQLITE_READ t2 a main v1 \ + SQLITE_READ t2 b main v1 \ + SQLITE_READ v1 x main v1 \ + SQLITE_READ v1 x main v1 \ + SQLITE_SELECT {} {} {} v1 \ + SQLITE_READ v1 x main v1 \ + SQLITE_INSERT v1chng {} main r2 \ + SQLITE_READ v1 x main r2 \ + SQLITE_READ v1 x main r2 \ +] + +do_test auth-4.4 { + execsql { + CREATE TRIGGER r3 INSTEAD OF DELETE ON v1 BEGIN + INSERT INTO v1chng VALUES(OLD.x,NULL); + END; + SELECT * FROM v1; + } +} {115 117} +do_test auth-4.5 { + set authargs {} + execsql { + DELETE FROM v1 WHERE x=117 + } + set authargs +} [list \ + SQLITE_DELETE v1 {} main {} \ + SQLITE_SELECT {} {} {} v1 \ + SQLITE_READ t2 a main v1 \ + SQLITE_READ t2 b main v1 \ + SQLITE_READ v1 x main v1 \ + SQLITE_READ v1 x main v1 \ + SQLITE_SELECT {} {} {} v1 \ + SQLITE_READ v1 x main v1 \ + SQLITE_INSERT v1chng {} main r3 \ + SQLITE_READ v1 x main r3 \ +] + +} ;# ifcapable view && trigger + +# Ticket #1338: Make sure authentication works in the presence of an AS +# clause. +# +do_test auth-5.1 { + proc auth {code arg1 arg2 arg3 arg4} { + return SQLITE_OK + } + execsql { + SELECT count(a) AS cnt FROM t4 ORDER BY cnt + } +} {1} + +# Ticket #1607 +# +ifcapable compound&&subquery { + ifcapable trigger { + execsql { + DROP TABLE tx; + } + ifcapable view { + execsql { + DROP TABLE v1chng; + } + } + } + ifcapable stat4 { + set stat4 "sqlite_stat4 " + } else { + ifcapable stat3 { + set stat4 "sqlite_stat3 " + } else { + set stat4 "" + } + } + do_test auth-5.2 { + execsql { + SELECT name FROM ( + SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) + WHERE type='table' + ORDER BY name + } + } "sqlite_stat1 ${stat4}t1 t2 t3 t4" +} + +# Ticket #3944 +# +ifcapable trigger { + do_test auth-5.3.1 { + execsql { + CREATE TABLE t5 ( x ); + CREATE TRIGGER t5_tr1 AFTER INSERT ON t5 BEGIN + UPDATE t5 SET x = 1 WHERE NEW.x = 0; + END; + } + } {} + set ::authargs [list] + proc auth {args} { + eval lappend ::authargs $args + return SQLITE_OK + } + do_test auth-5.3.2 { + execsql { INSERT INTO t5 (x) values(0) } + set ::authargs + } [list SQLITE_INSERT t5 {} main {} \ + SQLITE_UPDATE t5 x main t5_tr1 \ + SQLITE_READ t5 x main t5_tr1 \ + ] + do_test auth-5.3.2 { + execsql { SELECT * FROM t5 } + } {1} +} + +# Ticket [0eb70d77cb05bb22720]: Invalid pointer passsed to the authorizer +# callback when updating a ROWID. +# +do_test auth-6.1 { + execsql { + CREATE TABLE t6(a,b,c,d,e,f,g,h); + INSERT INTO t6 VALUES(1,2,3,4,5,6,7,8); + } +} {} +set ::authargs [list] +proc auth {args} { + eval lappend ::authargs $args + return SQLITE_OK +} +do_test auth-6.2 { + execsql {UPDATE t6 SET rowID=rowID+100} + set ::authargs +} [list SQLITE_READ t6 ROWID main {} \ + SQLITE_UPDATE t6 ROWID main {} \ +] +do_test auth-6.3 { + execsql {SELECT rowid, * FROM t6} +} {101 1 2 3 4 5 6 7 8} + +rename proc {} +rename proc_real proc + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/auth2.test b/components/external/SQLite-3.8.1/test/auth2.test new file mode 100644 index 0000000000000000000000000000000000000000..9343fd6f71d71fec7de5b2dcc5d83ec60f58198b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/auth2.test @@ -0,0 +1,170 @@ +# 2006 Aug 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is testing the sqlite3_set_authorizer() API +# and related functionality. +# +# $Id: auth2.test,v 1.3 2008/07/02 13:13:53 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# disable this test if the SQLITE_OMIT_AUTHORIZATION macro is +# defined during compilation. +if {[catch {db auth {}} msg]} { + finish_test + return +} + +do_test auth2-1.1 { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(1,2,3); + } + set ::flist {} + proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_FUNCTION"} { + lappend ::flist $arg2 + if {$arg2=="max"} { + return SQLITE_DENY + } elseif {$arg2=="min"} { + return SQLITE_IGNORE + } else { + return SQLITE_OK + } + } + return SQLITE_OK + } + db authorizer ::auth + catchsql {SELECT max(a,b,c) FROM t1} +} {1 {not authorized to use function: max}} +do_test auth2-1.2 { + set ::flist +} max +do_test auth2-1.3 { + set ::flist {} + catchsql {SELECT min(a,b,c) FROM t1} +} {0 {{}}} +do_test auth2-1.4 { + set ::flist +} min +do_test auth2-1.5 { + set ::flist {} + catchsql {SELECT coalesce(min(a,b,c),999) FROM t1} +} {0 999} +do_test auth2-1.6 { + set ::flist +} {coalesce min} +do_test auth2-1.7 { + set ::flist {} + catchsql {SELECT coalesce(a,b,c) FROM t1} +} {0 1} +do_test auth2-1.8 { + set ::flist +} coalesce + +# Make sure the authorizer is not called when parsing the schema +# and when computing the result set of a view. +# +db close +sqlite3 db test.db +sqlite3 db2 test.db +proc auth {args} { + global authargs + append authargs $args\n + return SQLITE_OK +} +db auth auth +do_test auth2-2.1 { + set ::authargs {} + db eval { + CREATE TABLE t2(x,y,z); + } + set ::authargs +} {SQLITE_INSERT sqlite_master {} main {} +SQLITE_CREATE_TABLE t2 {} main {} +SQLITE_UPDATE sqlite_master type main {} +SQLITE_UPDATE sqlite_master name main {} +SQLITE_UPDATE sqlite_master tbl_name main {} +SQLITE_UPDATE sqlite_master rootpage main {} +SQLITE_UPDATE sqlite_master sql main {} +SQLITE_READ sqlite_master ROWID main {} +SQLITE_READ sqlite_master name main {} +SQLITE_READ sqlite_master rootpage main {} +SQLITE_READ sqlite_master sql main {} +SQLITE_READ sqlite_master tbl_name main {} +SQLITE_READ sqlite_master ROWID main {} +} +do_test auth2-2.2 { + set ::authargs {} + db eval { + CREATE VIEW v2 AS SELECT x+y AS a, y+z AS b from t2; + } + set ::authargs +} {SQLITE_INSERT sqlite_master {} main {} +SQLITE_CREATE_VIEW v2 {} main {} +SQLITE_UPDATE sqlite_master type main {} +SQLITE_UPDATE sqlite_master name main {} +SQLITE_UPDATE sqlite_master tbl_name main {} +SQLITE_UPDATE sqlite_master rootpage main {} +SQLITE_UPDATE sqlite_master sql main {} +SQLITE_READ sqlite_master ROWID main {} +SQLITE_READ sqlite_master name main {} +SQLITE_READ sqlite_master rootpage main {} +SQLITE_READ sqlite_master sql main {} +SQLITE_READ sqlite_master tbl_name main {} +SQLITE_READ sqlite_master ROWID main {} +} +do_test auth2-2.3 { + set ::authargs {} + db eval { + SELECT a, b FROM v2; + } + set ::authargs +} {SQLITE_SELECT {} {} {} {} +SQLITE_READ t2 x main v2 +SQLITE_READ t2 y main v2 +SQLITE_READ t2 y main v2 +SQLITE_READ t2 z main v2 +SQLITE_READ v2 a main {} +SQLITE_READ v2 b main {} +SQLITE_SELECT {} {} {} v2 +} +do_test auth2-2.4 { + db2 eval { + CREATE TABLE t3(p,q,r); + } + set ::authargs {} + db eval { + SELECT b, a FROM v2; + } + set ::authargs +} {SQLITE_SELECT {} {} {} {} +SQLITE_READ t2 x main v2 +SQLITE_READ t2 y main v2 +SQLITE_READ t2 y main v2 +SQLITE_READ t2 z main v2 +SQLITE_READ v2 b main {} +SQLITE_READ v2 a main {} +SQLITE_SELECT {} {} {} v2 +SQLITE_SELECT {} {} {} {} +SQLITE_READ t2 x main v2 +SQLITE_READ t2 y main v2 +SQLITE_READ t2 y main v2 +SQLITE_READ t2 z main v2 +SQLITE_READ v2 b main {} +SQLITE_READ v2 a main {} +SQLITE_SELECT {} {} {} v2 +} +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/auth3.test b/components/external/SQLite-3.8.1/test/auth3.test new file mode 100644 index 0000000000000000000000000000000000000000..21e2b3b65da5cef3bec9ec5e7b0467b64fc21f52 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/auth3.test @@ -0,0 +1,111 @@ +# 2008 October 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test that the truncate optimization is disabled if the SQLITE_DELETE +# authorization callback returns SQLITE_IGNORE. +# +# $Id: auth3.test,v 1.2 2009/05/04 01:58:31 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# disable this test if the SQLITE_OMIT_AUTHORIZATION macro is +# defined during compilation. +if {[catch {db auth {}} msg]} { + finish_test + return +} + +# Disable the statement cache for these tests. +# +db cache size 0 + +db authorizer ::auth +proc auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_DELETE"} { + return $::authcode + } + return SQLITE_OK +} + +#-------------------------------------------------------------------------- +# The following tests - auth3-1.* - test that return values of SQLITE_DENY, +# SQLITE_IGNORE, SQLITE_OK and are correctly handled when returned +# by an SQLITE_DELETE authorization callback triggered by a +# "DELETE FROM " statement. +# +do_test auth3-1.1 { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + } +} {} +do_test auth3.1.2 { + set ::authcode SQLITE_DENY + catchsql { DELETE FROM t1 } +} {1 {not authorized}} +do_test auth3.1.3 { + set ::authcode SQLITE_INVALID + catchsql { DELETE FROM t1 } +} {1 {authorizer malfunction}} +do_test auth3.1.4 { + execsql { SELECT * FROM t1 } +} {1 2 3 4 5 6} +do_test auth3-1.5 { + set ::authcode SQLITE_IGNORE + execsql { + DELETE FROM t1; + SELECT * FROM t1; + } +} {} +do_test auth3-1.6 { + set ::authcode SQLITE_OK + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + DELETE FROM t1; + SELECT * FROM t1; + } +} {} + +#-------------------------------------------------------------------------- +# These tests - auth3-2.* - test that returning SQLITE_IGNORE really does +# disable the truncate optimization. +# +do_test auth3-2.1 { + set ::authcode SQLITE_OK + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + } + set sqlite_search_count 0 + execsql { + DELETE FROM t1; + } + set sqlite_search_count +} {0} + +do_test auth3-2.2 { + set ::authcode SQLITE_IGNORE + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + } + set sqlite_search_count 0 + execsql { + DELETE FROM t1; + } + set sqlite_search_count +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/autoinc.test b/components/external/SQLite-3.8.1/test/autoinc.test new file mode 100644 index 0000000000000000000000000000000000000000..98f6919b0366bae06663486a148a0ef195f9d747 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/autoinc.test @@ -0,0 +1,668 @@ +# 2004 November 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the AUTOINCREMENT features. +# +# $Id: autoinc.test,v 1.14 2009/06/23 20:28:54 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If the library is not compiled with autoincrement support then +# skip all tests in this file. +# +ifcapable {!autoinc} { + finish_test + return +} + +sqlite3_db_config_lookaside db 0 0 0 + +# The database is initially empty. +# +do_test autoinc-1.1 { + execsql { + SELECT name FROM sqlite_master WHERE type='table'; + } +} {} + +# Add a table with the AUTOINCREMENT feature. Verify that the +# SQLITE_SEQUENCE table gets created. +# +do_test autoinc-1.2 { + execsql { + CREATE TABLE t1(x INTEGER PRIMARY KEY AUTOINCREMENT, y); + SELECT name FROM sqlite_master WHERE type='table'; + } +} {t1 sqlite_sequence} + +# The SQLITE_SEQUENCE table is initially empty +# +do_test autoinc-1.3 { + execsql { + SELECT * FROM sqlite_sequence; + } +} {} +do_test autoinc-1.3.1 { + catchsql { + CREATE INDEX seqidx ON sqlite_sequence(name) + } +} {1 {table sqlite_sequence may not be indexed}} + +# Close and reopen the database. Verify that everything is still there. +# +do_test autoinc-1.4 { + db close + sqlite3 db test.db + execsql { + SELECT * FROM sqlite_sequence; + } +} {} + +# We are not allowed to drop the sqlite_sequence table. +# +do_test autoinc-1.5 { + catchsql {DROP TABLE sqlite_sequence} +} {1 {table sqlite_sequence may not be dropped}} +do_test autoinc-1.6 { + execsql {SELECT name FROM sqlite_master WHERE type='table'} +} {t1 sqlite_sequence} + +# Insert an entries into the t1 table and make sure the largest key +# is always recorded in the sqlite_sequence table. +# +do_test autoinc-2.1 { + execsql { + SELECT * FROM sqlite_sequence + } +} {} +do_test autoinc-2.2 { + execsql { + INSERT INTO t1 VALUES(12,34); + SELECT * FROM sqlite_sequence; + } +} {t1 12} +do_test autoinc-2.3 { + execsql { + INSERT INTO t1 VALUES(1,23); + SELECT * FROM sqlite_sequence; + } +} {t1 12} +do_test autoinc-2.4 { + execsql { + INSERT INTO t1 VALUES(123,456); + SELECT * FROM sqlite_sequence; + } +} {t1 123} +do_test autoinc-2.5 { + execsql { + INSERT INTO t1 VALUES(NULL,567); + SELECT * FROM sqlite_sequence; + } +} {t1 124} +do_test autoinc-2.6 { + execsql { + DELETE FROM t1 WHERE y=567; + SELECT * FROM sqlite_sequence; + } +} {t1 124} +do_test autoinc-2.7 { + execsql { + INSERT INTO t1 VALUES(NULL,567); + SELECT * FROM sqlite_sequence; + } +} {t1 125} +do_test autoinc-2.8 { + execsql { + DELETE FROM t1; + SELECT * FROM sqlite_sequence; + } +} {t1 125} +do_test autoinc-2.9 { + execsql { + INSERT INTO t1 VALUES(12,34); + SELECT * FROM sqlite_sequence; + } +} {t1 125} +do_test autoinc-2.10 { + execsql { + INSERT INTO t1 VALUES(125,456); + SELECT * FROM sqlite_sequence; + } +} {t1 125} +do_test autoinc-2.11 { + execsql { + INSERT INTO t1 VALUES(-1234567,-1); + SELECT * FROM sqlite_sequence; + } +} {t1 125} +do_test autoinc-2.12 { + execsql { + INSERT INTO t1 VALUES(234,5678); + SELECT * FROM sqlite_sequence; + } +} {t1 234} +do_test autoinc-2.13 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(NULL,1); + SELECT * FROM sqlite_sequence; + } +} {t1 235} +do_test autoinc-2.14 { + execsql { + SELECT * FROM t1; + } +} {235 1} + +# Manually change the autoincrement values in sqlite_sequence. +# +do_test autoinc-2.20 { + execsql { + UPDATE sqlite_sequence SET seq=1234 WHERE name='t1'; + INSERT INTO t1 VALUES(NULL,2); + SELECT * FROM t1; + } +} {235 1 1235 2} +do_test autoinc-2.21 { + execsql { + SELECT * FROM sqlite_sequence; + } +} {t1 1235} +do_test autoinc-2.22 { + execsql { + UPDATE sqlite_sequence SET seq=NULL WHERE name='t1'; + INSERT INTO t1 VALUES(NULL,3); + SELECT * FROM t1; + } +} {235 1 1235 2 1236 3} +do_test autoinc-2.23 { + execsql { + SELECT * FROM sqlite_sequence; + } +} {t1 1236} +do_test autoinc-2.24 { + execsql { + UPDATE sqlite_sequence SET seq='a-string' WHERE name='t1'; + INSERT INTO t1 VALUES(NULL,4); + SELECT * FROM t1; + } +} {235 1 1235 2 1236 3 1237 4} +do_test autoinc-2.25 { + execsql { + SELECT * FROM sqlite_sequence; + } +} {t1 1237} +do_test autoinc-2.26 { + execsql { + DELETE FROM sqlite_sequence WHERE name='t1'; + INSERT INTO t1 VALUES(NULL,5); + SELECT * FROM t1; + } +} {235 1 1235 2 1236 3 1237 4 1238 5} +do_test autoinc-2.27 { + execsql { + SELECT * FROM sqlite_sequence; + } +} {t1 1238} +do_test autoinc-2.28 { + execsql { + UPDATE sqlite_sequence SET seq='12345678901234567890' + WHERE name='t1'; + INSERT INTO t1 VALUES(NULL,6); + SELECT * FROM t1; + } +} {235 1 1235 2 1236 3 1237 4 1238 5 1239 6} +do_test autoinc-2.29 { + execsql { + SELECT * FROM sqlite_sequence; + } +} {t1 1239} + +# Test multi-row inserts +# +do_test autoinc-2.50 { + execsql { + DELETE FROM t1 WHERE y>=3; + INSERT INTO t1 SELECT NULL, y+2 FROM t1; + SELECT * FROM t1; + } +} {235 1 1235 2 1240 3 1241 4} +do_test autoinc-2.51 { + execsql { + SELECT * FROM sqlite_sequence + } +} {t1 1241} + +ifcapable tempdb { + do_test autoinc-2.52 { + execsql { + CREATE TEMP TABLE t2 AS SELECT y FROM t1; + } + execsql { + INSERT INTO t1 SELECT NULL, y+4 FROM t2; + SELECT * FROM t1; + } + } {235 1 1235 2 1240 3 1241 4 1242 5 1243 6 1244 7 1245 8} + do_test autoinc-2.53 { + execsql { + SELECT * FROM sqlite_sequence + } + } {t1 1245} + do_test autoinc-2.54 { + execsql { + DELETE FROM t1; + INSERT INTO t1 SELECT NULL, y FROM t2; + SELECT * FROM t1; + } + } {1246 1 1247 2 1248 3 1249 4} + do_test autoinc-2.55 { + execsql { + SELECT * FROM sqlite_sequence + } + } {t1 1249} +} + +# Create multiple AUTOINCREMENT tables. Make sure all sequences are +# tracked separately and do not interfere with one another. +# +do_test autoinc-2.70 { + catchsql { + DROP TABLE t2; + } + execsql { + CREATE TABLE t2(d, e INTEGER PRIMARY KEY AUTOINCREMENT, f); + INSERT INTO t2(d) VALUES(1); + SELECT * FROM sqlite_sequence; + } +} [ifcapable tempdb {list t1 1249 t2 1} else {list t1 1241 t2 1}] +do_test autoinc-2.71 { + execsql { + INSERT INTO t2(d) VALUES(2); + SELECT * FROM sqlite_sequence; + } +} [ifcapable tempdb {list t1 1249 t2 2} else {list t1 1241 t2 2}] +do_test autoinc-2.72 { + execsql { + INSERT INTO t1(x) VALUES(10000); + SELECT * FROM sqlite_sequence; + } +} {t1 10000 t2 2} +do_test autoinc-2.73 { + execsql { + CREATE TABLE t3(g INTEGER PRIMARY KEY AUTOINCREMENT, h); + INSERT INTO t3(h) VALUES(1); + SELECT * FROM sqlite_sequence; + } +} {t1 10000 t2 2 t3 1} +do_test autoinc-2.74 { + execsql { + INSERT INTO t2(d,e) VALUES(3,100); + SELECT * FROM sqlite_sequence; + } +} {t1 10000 t2 100 t3 1} + + +# When a table with an AUTOINCREMENT is deleted, the corresponding entry +# in the SQLITE_SEQUENCE table should also be deleted. But the SQLITE_SEQUENCE +# table itself should remain behind. +# +do_test autoinc-3.1 { + execsql {SELECT name FROM sqlite_sequence} +} {t1 t2 t3} +do_test autoinc-3.2 { + execsql { + DROP TABLE t1; + SELECT name FROM sqlite_sequence; + } +} {t2 t3} +do_test autoinc-3.3 { + execsql { + DROP TABLE t3; + SELECT name FROM sqlite_sequence; + } +} {t2} +do_test autoinc-3.4 { + execsql { + DROP TABLE t2; + SELECT name FROM sqlite_sequence; + } +} {} + +# AUTOINCREMENT on TEMP tables. +# +ifcapable tempdb { + do_test autoinc-4.1 { + execsql { + SELECT 1, name FROM sqlite_master WHERE type='table'; + SELECT 2, name FROM sqlite_temp_master WHERE type='table'; + } + } {1 sqlite_sequence} + do_test autoinc-4.2 { + execsql { + CREATE TABLE t1(x INTEGER PRIMARY KEY AUTOINCREMENT, y); + CREATE TEMP TABLE t3(a INTEGER PRIMARY KEY AUTOINCREMENT, b); + SELECT 1, name FROM sqlite_master WHERE type='table'; + SELECT 2, name FROM sqlite_temp_master WHERE type='table'; + } + } {1 sqlite_sequence 1 t1 2 t3 2 sqlite_sequence} + do_test autoinc-4.3 { + execsql { + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + } + } {} + do_test autoinc-4.4 { + execsql { + INSERT INTO t1 VALUES(10,1); + INSERT INTO t3 VALUES(20,2); + INSERT INTO t1 VALUES(NULL,3); + INSERT INTO t3 VALUES(NULL,4); + } + } {} + + ifcapable compound { + do_test autoinc-4.4.1 { + execsql { + SELECT * FROM t1 UNION ALL SELECT * FROM t3; + } + } {10 1 11 3 20 2 21 4} + } ;# ifcapable compound + + do_test autoinc-4.5 { + execsql { + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + } + } {1 t1 11 2 t3 21} + do_test autoinc-4.6 { + execsql { + INSERT INTO t1 SELECT * FROM t3; + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + } + } {1 t1 21 2 t3 21} + do_test autoinc-4.7 { + execsql { + INSERT INTO t3 SELECT x+100, y FROM t1; + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + } + } {1 t1 21 2 t3 121} + do_test autoinc-4.8 { + execsql { + DROP TABLE t3; + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + } + } {1 t1 21} + do_test autoinc-4.9 { + execsql { + CREATE TEMP TABLE t2(p INTEGER PRIMARY KEY AUTOINCREMENT, q); + INSERT INTO t2 SELECT * FROM t1; + DROP TABLE t1; + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + } + } {2 t2 21} + do_test autoinc-4.10 { + execsql { + DROP TABLE t2; + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + } + } {} +} + +# Make sure AUTOINCREMENT works on ATTACH-ed tables. +# +ifcapable tempdb&&attach { + do_test autoinc-5.1 { + forcedelete test2.db + forcedelete test2.db-journal + sqlite3 db2 test2.db + execsql { + CREATE TABLE t4(m INTEGER PRIMARY KEY AUTOINCREMENT, n); + CREATE TABLE t5(o, p INTEGER PRIMARY KEY AUTOINCREMENT); + } db2; + execsql { + ATTACH 'test2.db' as aux; + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + SELECT 3, * FROM aux.sqlite_sequence; + } + } {} + do_test autoinc-5.2 { + execsql { + INSERT INTO t4 VALUES(NULL,1); + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + SELECT 3, * FROM aux.sqlite_sequence; + } + } {3 t4 1} + do_test autoinc-5.3 { + execsql { + INSERT INTO t5 VALUES(100,200); + SELECT * FROM sqlite_sequence + } db2 + } {t4 1 t5 200} + do_test autoinc-5.4 { + execsql { + SELECT 1, * FROM main.sqlite_sequence; + SELECT 2, * FROM temp.sqlite_sequence; + SELECT 3, * FROM aux.sqlite_sequence; + } + } {3 t4 1 3 t5 200} +} + +# Requirement REQ00310: Make sure an insert fails if the sequence is +# already at its maximum value. +# +ifcapable {rowid32} { + do_test autoinc-6.1 { + execsql { + CREATE TABLE t6(v INTEGER PRIMARY KEY AUTOINCREMENT, w); + INSERT INTO t6 VALUES(2147483647,1); + SELECT seq FROM main.sqlite_sequence WHERE name='t6'; + } + } 2147483647 +} +ifcapable {!rowid32} { + do_test autoinc-6.1 { + execsql { + CREATE TABLE t6(v INTEGER PRIMARY KEY AUTOINCREMENT, w); + INSERT INTO t6 VALUES(9223372036854775807,1); + SELECT seq FROM main.sqlite_sequence WHERE name='t6'; + } + } 9223372036854775807 +} +do_test autoinc-6.2 { + catchsql { + INSERT INTO t6 VALUES(NULL,1); + } +} {1 {database or disk is full}} + +# Allow the AUTOINCREMENT keyword inside the parentheses +# on a separate PRIMARY KEY designation. +# +do_test autoinc-7.1 { + execsql { + CREATE TABLE t7(x INTEGER, y REAL, PRIMARY KEY(x AUTOINCREMENT)); + INSERT INTO t7(y) VALUES(123); + INSERT INTO t7(y) VALUES(234); + DELETE FROM t7; + INSERT INTO t7(y) VALUES(345); + SELECT * FROM t7; + } +} {3 345.0} + +# Test that if the AUTOINCREMENT is applied to a non integer primary key +# the error message is sensible. +do_test autoinc-7.2 { + catchsql { + CREATE TABLE t8(x TEXT PRIMARY KEY AUTOINCREMENT); + } +} {1 {AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY}} + + +# Ticket #1283. Make sure that preparing but never running a statement +# that creates the sqlite_sequence table does not mess up the database. +# +do_test autoinc-8.1 { + catch {db2 close} + catch {db close} + forcedelete test.db + sqlite3 db test.db + set DB [sqlite3_connection_pointer db] + set STMT [sqlite3_prepare $DB { + CREATE TABLE t1( + x INTEGER PRIMARY KEY AUTOINCREMENT + ) + } -1 TAIL] + sqlite3_finalize $STMT + set STMT [sqlite3_prepare $DB { + CREATE TABLE t1( + x INTEGER PRIMARY KEY AUTOINCREMENT + ) + } -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql { + INSERT INTO t1 VALUES(NULL); + SELECT * FROM t1; + } +} {1} + +# Ticket #3148 +# Make sure the sqlite_sequence table is not damaged when doing +# an empty insert - an INSERT INTO ... SELECT ... where the SELECT +# clause returns an empty set. +# +do_test autoinc-9.1 { + db eval { + CREATE TABLE t2(x INTEGER PRIMARY KEY AUTOINCREMENT, y); + INSERT INTO t2 VALUES(NULL, 1); + CREATE TABLE t3(a INTEGER PRIMARY KEY AUTOINCREMENT, b); + INSERT INTO t3 SELECT * FROM t2 WHERE y>1; + + SELECT * FROM sqlite_sequence WHERE name='t3'; + } +} {t3 0} + +ifcapable trigger { + catchsql { pragma recursive_triggers = off } + + # Ticket #3928. Make sure that triggers to not make extra slots in + # the SQLITE_SEQUENCE table. + # + do_test autoinc-3928.1 { + db eval { + CREATE TABLE t3928(a INTEGER PRIMARY KEY AUTOINCREMENT, b); + CREATE TRIGGER t3928r1 BEFORE INSERT ON t3928 BEGIN + INSERT INTO t3928(b) VALUES('before1'); + INSERT INTO t3928(b) VALUES('before2'); + END; + CREATE TRIGGER t3928r2 AFTER INSERT ON t3928 BEGIN + INSERT INTO t3928(b) VALUES('after1'); + INSERT INTO t3928(b) VALUES('after2'); + END; + INSERT INTO t3928(b) VALUES('test'); + SELECT * FROM t3928 ORDER BY a; + } + } {1 before1 2 after1 3 after2 4 before2 5 after1 6 after2 7 test 8 before1 9 before2 10 after1 11 before1 12 before2 13 after2} + do_test autoinc-3928.2 { + db eval { + SELECT * FROM sqlite_sequence WHERE name='t3928' + } + } {t3928 13} + + do_test autoinc-3928.3 { + db eval { + DROP TRIGGER t3928r1; + DROP TRIGGER t3928r2; + CREATE TRIGGER t3928r3 BEFORE UPDATE ON t3928 + WHEN typeof(new.b)=='integer' BEGIN + INSERT INTO t3928(b) VALUES('before-int-' || new.b); + END; + CREATE TRIGGER t3928r4 AFTER UPDATE ON t3928 + WHEN typeof(new.b)=='integer' BEGIN + INSERT INTO t3928(b) VALUES('after-int-' || new.b); + END; + DELETE FROM t3928 WHERE a!=1; + UPDATE t3928 SET b=456 WHERE a=1; + SELECT * FROM t3928 ORDER BY a; + } + } {1 456 14 before-int-456 15 after-int-456} + do_test autoinc-3928.4 { + db eval { + SELECT * FROM sqlite_sequence WHERE name='t3928' + } + } {t3928 15} + + do_test autoinc-3928.5 { + db eval { + CREATE TABLE t3928b(x); + INSERT INTO t3928b VALUES(100); + INSERT INTO t3928b VALUES(200); + INSERT INTO t3928b VALUES(300); + DELETE FROM t3928; + CREATE TABLE t3928c(y INTEGER PRIMARY KEY AUTOINCREMENT, z); + CREATE TRIGGER t3928br1 BEFORE DELETE ON t3928b BEGIN + INSERT INTO t3928(b) VALUES('before-del-'||old.x); + INSERT INTO t3928c(z) VALUES('before-del-'||old.x); + END; + CREATE TRIGGER t3928br2 AFTER DELETE ON t3928b BEGIN + INSERT INTO t3928(b) VALUES('after-del-'||old.x); + INSERT INTO t3928c(z) VALUES('after-del-'||old.x); + END; + DELETE FROM t3928b; + SELECT * FROM t3928 ORDER BY a; + } + } {16 before-del-100 17 after-del-100 18 before-del-200 19 after-del-200 20 before-del-300 21 after-del-300} + do_test autoinc-3928.6 { + db eval { + SELECT * FROM t3928c ORDER BY y; + } + } {1 before-del-100 2 after-del-100 3 before-del-200 4 after-del-200 5 before-del-300 6 after-del-300} + do_test autoinc-3928.7 { + db eval { + SELECT * FROM sqlite_sequence WHERE name LIKE 't3928%' ORDER BY name; + } + } {t3928 21 t3928c 6} + + # Ticket [a696379c1f0886615541a48b35bd8181a80e88f8] + do_test autoinc-a69637.1 { + db eval { + CREATE TABLE ta69637_1(x INTEGER PRIMARY KEY AUTOINCREMENT, y); + CREATE TABLE ta69637_2(z); + CREATE TRIGGER ra69637_1 AFTER INSERT ON ta69637_2 BEGIN + INSERT INTO ta69637_1(y) VALUES(new.z+1); + END; + INSERT INTO ta69637_2 VALUES(123); + SELECT * FROM ta69637_1; + } + } {1 124} + do_test autoinc-a69637.2 { + db eval { + CREATE VIEW va69637_2 AS SELECT * FROM ta69637_2; + CREATE TRIGGER ra69637_2 INSTEAD OF INSERT ON va69637_2 BEGIN + INSERT INTO ta69637_1(y) VALUES(new.z+10000); + END; + INSERT INTO va69637_2 VALUES(123); + SELECT * FROM ta69637_1; + } + } {1 124 2 10123} +} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/autoindex1.test b/components/external/SQLite-3.8.1/test/autoindex1.test new file mode 100644 index 0000000000000000000000000000000000000000..0e5032b9b929bf7f844058576dfeabc923bfe214 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/autoindex1.test @@ -0,0 +1,414 @@ +# 2010 April 07 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing automatic index creation logic. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If the library is not compiled with automatic index support then +# skip all tests in this file. +# +ifcapable {!autoindex} { + finish_test + return +} + +# Setup for logging +db close +sqlite3_shutdown +test_sqlite3_log [list lappend ::log] +set ::log [list] +sqlite3 db test.db + + +# With automatic index turned off, we do a full scan of the T2 table +do_test autoindex1-100 { + db eval { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,11); + INSERT INTO t1 VALUES(2,22); + INSERT INTO t1 SELECT a+2, b+22 FROM t1; + INSERT INTO t1 SELECT a+4, b+44 FROM t1; + CREATE TABLE t2(c,d); + INSERT INTO t2 SELECT a, 900+b FROM t1; + } + db eval { + PRAGMA automatic_index=OFF; + SELECT b, d FROM t1 JOIN t2 ON a=c ORDER BY b; + } +} {11 911 22 922 33 933 44 944 55 955 66 966 77 977 88 988} +do_test autoindex1-101 { + db status step +} {63} +do_test autoindex1-102 { + db status autoindex +} {0} + +# With autoindex turned on, we build an index once and then use that index +# to find T2 values. +do_test autoindex1-110 { + db eval { + PRAGMA automatic_index=ON; + SELECT b, d FROM t1 JOIN t2 ON a=c ORDER BY b; + } +} {11 911 22 922 33 933 44 944 55 955 66 966 77 977 88 988} +do_test autoindex1-111 { + db status step +} {7} +do_test autoindex1-112 { + db status autoindex +} {7} +do_test autoindex1-113 { + set ::log +} {SQLITE_WARNING_AUTOINDEX {automatic index on t2(c)}} + +db close +sqlite3_shutdown +test_sqlite3_log +sqlite3_initialize +sqlite3 db test.db + +# The same test as above, but this time the T2 query is a subquery rather +# than a join. +do_test autoindex1-200 { + db eval { + PRAGMA automatic_index=OFF; + SELECT b, (SELECT d FROM t2 WHERE c=a) FROM t1; + } +} {11 911 22 922 33 933 44 944 55 955 66 966 77 977 88 988} +do_test autoindex1-201 { + db status step +} {35} +do_test autoindex1-202 { + db status autoindex +} {0} +do_test autoindex1-210 { + db eval { + PRAGMA automatic_index=ON; + ANALYZE; + UPDATE sqlite_stat1 SET stat='10000' WHERE tbl='t1'; + ANALYZE sqlite_master; + SELECT b, (SELECT d FROM t2 WHERE c=a) FROM t1; + } +} {11 911 22 922 33 933 44 944 55 955 66 966 77 977 88 988} +do_test autoindex1-211 { + db status step +} {7} +do_test autoindex1-212 { + db status autoindex +} {7} + + +# Modify the second table of the join while the join is in progress +# +do_execsql_test autoindex1-299 { + UPDATE sqlite_stat1 SET stat='10000' WHERE tbl='t2'; + ANALYZE sqlite_master; + EXPLAIN QUERY PLAN + SELECT b, d FROM t1 CROSS JOIN t2 ON (c=a); +} {/AUTOMATIC COVERING INDEX/} +do_test autoindex1-300 { + set r {} + db eval {SELECT b, d FROM t1 CROSS JOIN t2 ON (c=a)} { + lappend r $b $d + db eval {UPDATE t2 SET d=d+1} + } + set r +} {11 911 22 922 33 933 44 944 55 955 66 966 77 977 88 988} +do_test autoindex1-310 { + db eval {SELECT d FROM t2 ORDER BY d} +} {919 930 941 952 963 974 985 996} + +# The next test does a 10-way join on unindexed tables. Without +# automatic indices, the join will take a long time to complete. +# With automatic indices, it should only take about a second. +# +do_test autoindex1-400 { + db eval { + CREATE TABLE t4(a, b); + INSERT INTO t4 VALUES(1,2); + INSERT INTO t4 VALUES(2,3); + } + for {set n 2} {$n<4096} {set n [expr {$n+$n}]} { + db eval {INSERT INTO t4 SELECT a+$n, b+$n FROM t4} + } + db eval { + SELECT count(*) FROM t4; + } +} {4096} +do_test autoindex1-401 { + db eval { + SELECT count(*) + FROM t4 AS x1 + JOIN t4 AS x2 ON x2.a=x1.b + JOIN t4 AS x3 ON x3.a=x2.b + JOIN t4 AS x4 ON x4.a=x3.b + JOIN t4 AS x5 ON x5.a=x4.b + JOIN t4 AS x6 ON x6.a=x5.b + JOIN t4 AS x7 ON x7.a=x6.b + JOIN t4 AS x8 ON x8.a=x7.b + JOIN t4 AS x9 ON x9.a=x8.b + JOIN t4 AS x10 ON x10.a=x9.b; + } +} {4087} + +# Ticket [8011086c85c6c404014c947fcf3eb9f42b184a0d] from 2010-07-08 +# Make sure automatic indices are not created for the RHS of an IN expression +# that is not a correlated subquery. +# +do_execsql_test autoindex1-500 { + CREATE TABLE t501(a INTEGER PRIMARY KEY, b); + CREATE TABLE t502(x INTEGER PRIMARY KEY, y); + INSERT INTO sqlite_stat1(tbl,idx,stat) VALUES('t501',null,'1000000'); + INSERT INTO sqlite_stat1(tbl,idx,stat) VALUES('t502',null,'1000'); + ANALYZE sqlite_master; + EXPLAIN QUERY PLAN + SELECT b FROM t501 + WHERE t501.a IN (SELECT x FROM t502 WHERE y=?); +} { + 0 0 0 {SEARCH TABLE t501 USING INTEGER PRIMARY KEY (rowid=?)} + 0 0 0 {EXECUTE LIST SUBQUERY 1} + 1 0 0 {SCAN TABLE t502} +} +do_execsql_test autoindex1-501 { + EXPLAIN QUERY PLAN + SELECT b FROM t501 + WHERE t501.a IN (SELECT x FROM t502 WHERE y=t501.b); +} { + 0 0 0 {SCAN TABLE t501} + 0 0 0 {EXECUTE CORRELATED LIST SUBQUERY 1} + 1 0 0 {SEARCH TABLE t502 USING AUTOMATIC COVERING INDEX (y=?)} +} +do_execsql_test autoindex1-502 { + EXPLAIN QUERY PLAN + SELECT b FROM t501 + WHERE t501.a=123 + AND t501.a IN (SELECT x FROM t502 WHERE y=t501.b); +} { + 0 0 0 {SEARCH TABLE t501 USING INTEGER PRIMARY KEY (rowid=?)} + 0 0 0 {EXECUTE CORRELATED LIST SUBQUERY 1} + 1 0 0 {SCAN TABLE t502} +} + + +# The following code checks a performance regression reported on the +# mailing list on 2010-10-19. The problem is that the nRowEst field +# of ephermeral tables was not being initialized correctly and so no +# automatic index was being created for the emphemeral table when it was +# used as part of a join. +# +do_execsql_test autoindex1-600 { + CREATE TABLE flock_owner( + owner_rec_id INTEGER CONSTRAINT flock_owner_key PRIMARY KEY, + flock_no VARCHAR(6) NOT NULL REFERENCES flock (flock_no), + owner_person_id INTEGER NOT NULL REFERENCES person (person_id), + owner_change_date TEXT, last_changed TEXT NOT NULL, + CONSTRAINT fo_owner_date UNIQUE (flock_no, owner_change_date) + ); + CREATE TABLE sheep ( + Sheep_No char(7) NOT NULL, + Date_of_Birth char(8), + Sort_DoB text, + Flock_Book_Vol char(2), + Breeder_No char(6), + Breeder_Person integer, + Originating_Flock char(6), + Registering_Flock char(6), + Tag_Prefix char(9), + Tag_No char(15), + Sort_Tag_No integer, + Breeders_Temp_Tag char(15), + Sex char(1), + Sheep_Name char(32), + Sire_No char(7), + Dam_No char(7), + Register_Code char(1), + Colour char(48), + Colour_Code char(2), + Pattern_Code char(8), + Horns char(1), + Litter_Size char(1), + Coeff_of_Inbreeding real, + Date_of_Registration text, + Date_Last_Changed text, + UNIQUE(Sheep_No)); + CREATE INDEX fo_flock_no_index + ON flock_owner (flock_no); + CREATE INDEX fo_owner_change_date_index + ON flock_owner (owner_change_date); + CREATE INDEX fo_owner_person_id_index + ON flock_owner (owner_person_id); + CREATE INDEX sheep_org_flock_index + ON sheep (originating_flock); + CREATE INDEX sheep_reg_flock_index + ON sheep (registering_flock); + EXPLAIN QUERY PLAN + SELECT x.sheep_no, x.registering_flock, x.date_of_registration + FROM sheep x LEFT JOIN + (SELECT s.sheep_no, prev.flock_no, prev.owner_person_id, + s.date_of_registration, prev.owner_change_date + FROM sheep s JOIN flock_owner prev ON s.registering_flock = + prev.flock_no + AND (prev.owner_change_date <= s.date_of_registration || ' 00:00:00') + WHERE NOT EXISTS + (SELECT 'x' FROM flock_owner later + WHERE prev.flock_no = later.flock_no + AND later.owner_change_date > prev.owner_change_date + AND later.owner_change_date <= s.date_of_registration||' 00:00:00') + ) y ON x.sheep_no = y.sheep_no + WHERE y.sheep_no IS NULL + ORDER BY x.registering_flock; +} { + 1 0 0 {SCAN TABLE sheep AS s} + 1 1 1 {SEARCH TABLE flock_owner AS prev USING INDEX sqlite_autoindex_flock_owner_1 (flock_no=? AND owner_change_date? AND owner_change_date= $pending_byte_page} { + lappend root_page_list $i +} +do_test autovacuum-2.4.5 { + for {set i 11} {$i<=530} {incr i} { + execsql "CREATE TABLE av$i (x)" + } + execsql { + SELECT rootpage FROM sqlite_master ORDER by rootpage + } +} $root_page_list + +# Just for fun, delete all those tables and see if the database is 1 page. +do_test autovacuum-2.4.6 { + execsql COMMIT; + file_pages +} [expr 561 + (($i >= $pending_byte_page)?1:0)] +integrity_check autovacuum-2.4.6 +do_test autovacuum-2.4.7 { + execsql BEGIN + for {set i 3} {$i<=530} {incr i} { + execsql "DROP TABLE av$i" + } + execsql COMMIT + file_pages +} 1 + +# Create some tables with indices to drop. +do_test autovacuum-2.5.1 { + execsql { + CREATE TABLE av1(a PRIMARY KEY, b, c); + INSERT INTO av1 VALUES('av1 a', 'av1 b', 'av1 c'); + + CREATE TABLE av2(a PRIMARY KEY, b, c); + CREATE INDEX av2_i1 ON av2(b); + CREATE INDEX av2_i2 ON av2(c); + INSERT INTO av2 VALUES('av2 a', 'av2 b', 'av2 c'); + + CREATE TABLE av3(a PRIMARY KEY, b, c); + CREATE INDEX av3_i1 ON av3(b); + INSERT INTO av3 VALUES('av3 a', 'av3 b', 'av3 c'); + + CREATE TABLE av4(a, b, c); + CREATE INDEX av4_i1 ON av4(a); + CREATE INDEX av4_i2 ON av4(b); + CREATE INDEX av4_i3 ON av4(c); + CREATE INDEX av4_i4 ON av4(a, b, c); + INSERT INTO av4 VALUES('av4 a', 'av4 b', 'av4 c'); + } +} {} + +do_test autovacuum-2.5.2 { + execsql { + SELECT name, rootpage FROM sqlite_master; + } +} [list av1 3 sqlite_autoindex_av1_1 4 \ + av2 5 sqlite_autoindex_av2_1 6 av2_i1 7 av2_i2 8 \ + av3 9 sqlite_autoindex_av3_1 10 av3_i1 11 \ + av4 12 av4_i1 13 av4_i2 14 av4_i3 15 av4_i4 16 \ +] + +# The following 4 tests are SELECT queries that use the indices created. +# If the root-pages in the internal schema are not updated correctly when +# a table or indice is moved, these queries will fail. They are repeated +# after each table is dropped (i.e. as test cases 2.5.*.[1..4]). +do_test autovacuum-2.5.2.1 { + execsql { + SELECT * FROM av1 WHERE a = 'av1 a'; + } +} {{av1 a} {av1 b} {av1 c}} +do_test autovacuum-2.5.2.2 { + execsql { + SELECT * FROM av2 WHERE a = 'av2 a' AND b = 'av2 b' AND c = 'av2 c' + } +} {{av2 a} {av2 b} {av2 c}} +do_test autovacuum-2.5.2.3 { + execsql { + SELECT * FROM av3 WHERE a = 'av3 a' AND b = 'av3 b'; + } +} {{av3 a} {av3 b} {av3 c}} +do_test autovacuum-2.5.2.4 { + execsql { + SELECT * FROM av4 WHERE a = 'av4 a' AND b = 'av4 b' AND c = 'av4 c'; + } +} {{av4 a} {av4 b} {av4 c}} + +# Drop table av3. Indices av4_i2, av4_i3 and av4_i4 are moved to fill the two +# root pages vacated. The operation proceeds as: +# Step 1: Delete av3_i1 (root-page 11). Move root-page of av4_i4 to page 11. +# Step 2: Delete av3 (root-page 10). Move root-page of av4_i3 to page 10. +# Step 3: Delete sqlite_autoindex_av1_3 (root-page 9). Move av4_i2 to page 9. +do_test autovacuum-2.5.3 { + execsql { + DROP TABLE av3; + SELECT name, rootpage FROM sqlite_master; + } +} [list av1 3 sqlite_autoindex_av1_1 4 \ + av2 5 sqlite_autoindex_av2_1 6 av2_i1 7 av2_i2 8 \ + av4 12 av4_i1 13 av4_i2 9 av4_i3 10 av4_i4 11 \ +] +do_test autovacuum-2.5.3.1 { + execsql { + SELECT * FROM av1 WHERE a = 'av1 a'; + } +} {{av1 a} {av1 b} {av1 c}} +do_test autovacuum-2.5.3.2 { + execsql { + SELECT * FROM av2 WHERE a = 'av2 a' AND b = 'av2 b' AND c = 'av2 c' + } +} {{av2 a} {av2 b} {av2 c}} +do_test autovacuum-2.5.3.3 { + execsql { + SELECT * FROM av4 WHERE a = 'av4 a' AND b = 'av4 b' AND c = 'av4 c'; + } +} {{av4 a} {av4 b} {av4 c}} + +# Drop table av1: +# Step 1: Delete av1 (root page 4). Root-page of av4_i1 fills the gap. +# Step 2: Delete sqlite_autoindex_av1_1 (root page 3). Move av4 to the gap. +do_test autovacuum-2.5.4 { + execsql { + DROP TABLE av1; + SELECT name, rootpage FROM sqlite_master; + } +} [list av2 5 sqlite_autoindex_av2_1 6 av2_i1 7 av2_i2 8 \ + av4 3 av4_i1 4 av4_i2 9 av4_i3 10 av4_i4 11 \ +] +do_test autovacuum-2.5.4.2 { + execsql { + SELECT * FROM av2 WHERE a = 'av2 a' AND b = 'av2 b' AND c = 'av2 c' + } +} {{av2 a} {av2 b} {av2 c}} +do_test autovacuum-2.5.4.4 { + execsql { + SELECT * FROM av4 WHERE a = 'av4 a' AND b = 'av4 b' AND c = 'av4 c'; + } +} {{av4 a} {av4 b} {av4 c}} + +# Drop table av4: +# Step 1: Delete av4_i4. +# Step 2: Delete av4_i3. +# Step 3: Delete av4_i2. +# Step 4: Delete av4_i1. av2_i2 replaces it. +# Step 5: Delete av4. av2_i1 replaces it. +do_test autovacuum-2.5.5 { + execsql { + DROP TABLE av4; + SELECT name, rootpage FROM sqlite_master; + } +} [list av2 5 sqlite_autoindex_av2_1 6 av2_i1 3 av2_i2 4] +do_test autovacuum-2.5.5.2 { + execsql { + SELECT * FROM av2 WHERE a = 'av2 a' AND b = 'av2 b' AND c = 'av2 c' + } +} {{av2 a} {av2 b} {av2 c}} + +#-------------------------------------------------------------------------- +# Test cases autovacuum-3.* test the operation of the "PRAGMA auto_vacuum" +# command. +# +do_test autovacuum-3.1 { + execsql { + PRAGMA auto_vacuum; + } +} {1} +do_test autovacuum-3.2 { + db close + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum; + } +} {1} +do_test autovacuum-3.3 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA auto_vacuum; + } +} {1} + +do_test autovacuum-3.4 { + db close + forcedelete test.db + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum; + } +} $AUTOVACUUM +do_test autovacuum-3.5 { + execsql { + CREATE TABLE av1(x); + PRAGMA auto_vacuum; + } +} $AUTOVACUUM +do_test autovacuum-3.6 { + execsql { + PRAGMA auto_vacuum = 1; + PRAGMA auto_vacuum; + } +} [expr $AUTOVACUUM ? 1 : 0] +do_test autovacuum-3.7 { + execsql { + DROP TABLE av1; + } + file_pages +} [expr $AUTOVACUUM?1:2] + + +#----------------------------------------------------------------------- +# Test that if a statement transaction around a CREATE INDEX statement is +# rolled back no corruption occurs. +# +do_test autovacuum-4.0 { + # The last round of tests may have left the db in non-autovacuum mode. + # Reset everything just in case. + # + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum = 1; + PRAGMA auto_vacuum; + } +} {1} +do_test autovacuum-4.1 { + execsql { + CREATE TABLE av1(a, b); + BEGIN; + } + for {set i 0} {$i<100} {incr i} { + execsql "INSERT INTO av1 VALUES($i, '[string repeat X 200]');" + } + execsql "INSERT INTO av1 VALUES(99, '[string repeat X 200]');" + execsql { + SELECT sum(a) FROM av1; + } +} {5049} +do_test autovacuum-4.2 { + catchsql { + CREATE UNIQUE INDEX av1_i ON av1(a); + } +} {1 {indexed columns are not unique}} +do_test autovacuum-4.3 { + execsql { + SELECT sum(a) FROM av1; + } +} {5049} +do_test autovacuum-4.4 { + execsql { + COMMIT; + } +} {} + +ifcapable integrityck { + +# Ticket #1727 +do_test autovacuum-5.1 { + db close + sqlite3 db :memory: + db eval { + PRAGMA auto_vacuum=1; + CREATE TABLE t1(a); + CREATE TABLE t2(a); + DROP TABLE t1; + PRAGMA integrity_check; + } +} ok + +} + +# Ticket #1728. +# +# In autovacuum mode, when tables or indices are deleted, the rootpage +# values in the symbol table have to be updated. There was a bug in this +# logic so that if an index/table was moved twice, the second move might +# not occur. This would leave the internal symbol table in an inconsistent +# state causing subsequent statements to fail. +# +# The problem is difficult to reproduce. The sequence of statements in +# the following test are carefully designed make it occur and thus to +# verify that this very obscure bug has been resolved. +# +ifcapable integrityck&&memorydb { + +do_test autovacuum-6.1 { + db close + sqlite3 db :memory: + db eval { + PRAGMA auto_vacuum=1; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a); + CREATE TABLE t2(a); + CREATE INDEX i2 ON t2(a); + CREATE TABLE t3(a); + CREATE INDEX i3 ON t2(a); + CREATE INDEX x ON t1(b); + DROP TABLE t3; + PRAGMA integrity_check; + DROP TABLE t2; + PRAGMA integrity_check; + DROP TABLE t1; + PRAGMA integrity_check; + } +} {ok ok ok} + +} + +#--------------------------------------------------------------------- +# Test cases autovacuum-7.X test the case where a page must be moved +# and the destination location collides with at least one other +# entry in the page hash-table (internal to the pager.c module. +# +do_test autovacuum-7.1 { + db close + forcedelete test.db + forcedelete test.db-journal + sqlite3 db test.db + + execsql { + PRAGMA auto_vacuum=1; + CREATE TABLE t1(a, b, PRIMARY KEY(a, b)); + INSERT INTO t1 VALUES(randstr(400,400),randstr(400,400)); + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2 + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 4 + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 8 + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 16 + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 32 + } + + expr {[file size test.db] / 1024} +} {73} + +do_test autovacuum-7.2 { + execsql { + CREATE TABLE t2(a, b, PRIMARY KEY(a, b)); + INSERT INTO t2 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2 + CREATE TABLE t3(a, b, PRIMARY KEY(a, b)); + INSERT INTO t3 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2 + CREATE TABLE t4(a, b, PRIMARY KEY(a, b)); + INSERT INTO t4 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2 + CREATE TABLE t5(a, b, PRIMARY KEY(a, b)); + INSERT INTO t5 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2 + } + expr {[file size test.db] / 1024} +} {354} + +do_test autovacuum-7.3 { + db close + sqlite3 db test.db + execsql { + BEGIN; + DELETE FROM t4; + COMMIT; + SELECT count(*) FROM t1; + } + expr {[file size test.db] / 1024} +} {286} + +#------------------------------------------------------------------------ +# Additional tests. +# +# Try to determine the autovacuum setting for a database that is locked. +# +do_test autovacuum-8.1 { + db close + sqlite3 db test.db + sqlite3 db2 test.db + db eval {PRAGMA auto_vacuum} +} {1} +if {[permutation] == ""} { + do_test autovacuum-8.2 { + db eval {BEGIN EXCLUSIVE} + catchsql {PRAGMA auto_vacuum} db2 + } {1 {database is locked}} + catch {db2 close} + catch {db eval {COMMIT}} +} + +do_test autovacuum-9.1 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + DROP TABLE t4; + DROP TABLE t5; + PRAGMA page_count; + } +} {1} +do_test autovacuum-9.2 { + file size test.db +} 1024 +do_test autovacuum-9.3 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(NULL, randstr(50,50)); + } + for {set ii 0} {$ii < 10} {incr ii} { + db eval { INSERT INTO t1 SELECT NULL, randstr(50,50) FROM t1 } + } + file size test.db +} $::sqlite_pending_byte +do_test autovacuum-9.4 { + execsql { INSERT INTO t1 SELECT NULL, randstr(50,50) FROM t1 } +} {} +do_test autovacuum-9.5 { + execsql { DELETE FROM t1 WHERE rowid > (SELECT max(a)/2 FROM t1) } + file size test.db +} $::sqlite_pending_byte + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/autovacuum_ioerr2.test b/components/external/SQLite-3.8.1/test/autovacuum_ioerr2.test new file mode 100644 index 0000000000000000000000000000000000000000..891d00eb06bce225482c4f49a8d573edffa27bcf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/autovacuum_ioerr2.test @@ -0,0 +1,132 @@ +# 2001 October 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing for correct handling of I/O errors +# such as writes failing because the disk is full. +# +# The tests in this file use special facilities that are only +# available in the SQLite test fixture. +# +# $Id: autovacuum_ioerr2.test,v 1.7 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If this build of the library does not support auto-vacuum, omit this +# whole file. +ifcapable {!autovacuum} { + finish_test + return +} + +do_ioerr_test autovacuum-ioerr2-1 -sqlprep { + PRAGMA auto_vacuum = 1; + CREATE TABLE abc(a); + INSERT INTO abc VALUES(randstr(1500,1500)); +} -sqlbody { + CREATE TABLE abc2(a); + BEGIN; + DELETE FROM abc; + INSERT INTO abc VALUES(randstr(1500,1500)); + CREATE TABLE abc3(a); + COMMIT; +} + +do_ioerr_test autovacuum-ioerr2-2 -tclprep { + execsql { + PRAGMA auto_vacuum = 1; + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE abc(a); + INSERT INTO abc VALUES(randstr(1100,1100)); -- Page 4 is overflow + INSERT INTO abc VALUES(randstr(1100,1100)); -- Page 5 is overflow + } + for {set i 0} {$i<150} {incr i} { + execsql { + INSERT INTO abc VALUES(randstr(100,100)); + } + } + execsql COMMIT +} -sqlbody { + BEGIN; + DELETE FROM abc WHERE length(a)>100; + UPDATE abc SET a = randstr(90,90); + CREATE TABLE abc3(a); + COMMIT; +} + +do_ioerr_test autovacuum-ioerr2-3 -sqlprep { + PRAGMA auto_vacuum = 1; + CREATE TABLE abc(a); + CREATE TABLE abc2(b); +} -sqlbody { + BEGIN; + INSERT INTO abc2 VALUES(10); + DROP TABLE abc; + COMMIT; + DROP TABLE abc2; +} + +forcedelete backup.db +ifcapable subquery { + do_ioerr_test autovacuum-ioerr2-4 -tclprep { + if {![file exists backup.db]} { + sqlite3 dbb backup.db + execsql { + PRAGMA auto_vacuum = 1; + BEGIN; + CREATE TABLE abc(a); + INSERT INTO abc VALUES(randstr(1100,1100)); -- Page 4 is overflow + INSERT INTO abc VALUES(randstr(1100,1100)); -- Page 5 is overflow + } dbb + for {set i 0} {$i<2500} {incr i} { + execsql { + INSERT INTO abc VALUES(randstr(100,100)); + } dbb + } + execsql { + COMMIT; + PRAGMA cache_size = 10; + } dbb + dbb close + } + db close + forcedelete test.db + forcedelete test.db-journal + forcecopy backup.db test.db + set ::DB [sqlite3 db test.db] + execsql { + PRAGMA cache_size = 10; + } + } -sqlbody { + BEGIN; + DELETE FROM abc WHERE oid < 3; + UPDATE abc SET a = randstr(100,100) WHERE oid > 2300; + UPDATE abc SET a = randstr(1100,1100) WHERE oid = + (select max(oid) from abc); + COMMIT; + } +} + +do_ioerr_test autovacuum-ioerr2-1 -sqlprep { + PRAGMA auto_vacuum = 1; + CREATE TABLE abc(a); + INSERT INTO abc VALUES(randstr(1500,1500)); +} -sqlbody { + CREATE TABLE abc2(a); + BEGIN; + DELETE FROM abc; + INSERT INTO abc VALUES(randstr(1500,1500)); + CREATE TABLE abc3(a); + COMMIT; +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/avtrans.test b/components/external/SQLite-3.8.1/test/avtrans.test new file mode 100644 index 0000000000000000000000000000000000000000..17a28606491ea7d6898caf44e961d16fb4ba2e17 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/avtrans.test @@ -0,0 +1,926 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. This +# file is a copy of "trans.test" modified to run under autovacuum mode. +# the point is to stress the autovacuum logic and try to get it to fail. +# +# $Id: avtrans.test,v 1.6 2007/09/12 17:01:45 danielk1977 Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +# Create several tables to work with. +# +do_test avtrans-1.0 { + execsql { PRAGMA auto_vacuum=ON } + wal_set_journal_mode + execsql { + CREATE TABLE one(a int PRIMARY KEY, b text); + INSERT INTO one VALUES(1,'one'); + INSERT INTO one VALUES(2,'two'); + INSERT INTO one VALUES(3,'three'); + SELECT b FROM one ORDER BY a; + } +} {one two three} +do_test avtrans-1.1 { + execsql { + CREATE TABLE two(a int PRIMARY KEY, b text); + INSERT INTO two VALUES(1,'I'); + INSERT INTO two VALUES(5,'V'); + INSERT INTO two VALUES(10,'X'); + SELECT b FROM two ORDER BY a; + } +} {I V X} +do_test avtrans-1.9 { + sqlite3 altdb test.db + execsql {SELECT b FROM one ORDER BY a} altdb +} {one two three} +do_test avtrans-1.10 { + execsql {SELECT b FROM two ORDER BY a} altdb +} {I V X} +integrity_check avtrans-1.11 +wal_check_journal_mode avtrans-1.12 + +# Basic transactions +# +do_test avtrans-2.1 { + set v [catch {execsql {BEGIN}} msg] + lappend v $msg +} {0 {}} +do_test avtrans-2.2 { + set v [catch {execsql {END}} msg] + lappend v $msg +} {0 {}} +do_test avtrans-2.3 { + set v [catch {execsql {BEGIN TRANSACTION}} msg] + lappend v $msg +} {0 {}} +do_test avtrans-2.4 { + set v [catch {execsql {COMMIT TRANSACTION}} msg] + lappend v $msg +} {0 {}} +do_test avtrans-2.5 { + set v [catch {execsql {BEGIN TRANSACTION 'foo'}} msg] + lappend v $msg +} {0 {}} +do_test avtrans-2.6 { + set v [catch {execsql {ROLLBACK TRANSACTION 'foo'}} msg] + lappend v $msg +} {0 {}} +do_test avtrans-2.10 { + execsql { + BEGIN; + SELECT a FROM one ORDER BY a; + SELECT a FROM two ORDER BY a; + END; + } +} {1 2 3 1 5 10} +integrity_check avtrans-2.11 +wal_check_journal_mode avtrans-2.12 + +# Check the locking behavior +# +sqlite3_soft_heap_limit 0 +do_test avtrans-3.1 { + execsql { + BEGIN; + UPDATE one SET a = 0 WHERE 0; + SELECT a FROM one ORDER BY a; + } +} {1 2 3} +do_test avtrans-3.2 { + catchsql { + SELECT a FROM two ORDER BY a; + } altdb +} {0 {1 5 10}} +do_test avtrans-3.3 { + catchsql { + SELECT a FROM one ORDER BY a; + } altdb +} {0 {1 2 3}} +do_test avtrans-3.4 { + catchsql { + INSERT INTO one VALUES(4,'four'); + } +} {0 {}} +do_test avtrans-3.5 { + catchsql { + SELECT a FROM two ORDER BY a; + } altdb +} {0 {1 5 10}} +do_test avtrans-3.6 { + catchsql { + SELECT a FROM one ORDER BY a; + } altdb +} {0 {1 2 3}} +do_test avtrans-3.7 { + catchsql { + INSERT INTO two VALUES(4,'IV'); + } +} {0 {}} +do_test avtrans-3.8 { + catchsql { + SELECT a FROM two ORDER BY a; + } altdb +} {0 {1 5 10}} +do_test avtrans-3.9 { + catchsql { + SELECT a FROM one ORDER BY a; + } altdb +} {0 {1 2 3}} +do_test avtrans-3.10 { + execsql {END TRANSACTION} +} {} +do_test avtrans-3.11 { + set v [catch {execsql { + SELECT a FROM two ORDER BY a; + } altdb} msg] + lappend v $msg +} {0 {1 4 5 10}} +do_test avtrans-3.12 { + set v [catch {execsql { + SELECT a FROM one ORDER BY a; + } altdb} msg] + lappend v $msg +} {0 {1 2 3 4}} +do_test avtrans-3.13 { + set v [catch {execsql { + SELECT a FROM two ORDER BY a; + } db} msg] + lappend v $msg +} {0 {1 4 5 10}} +do_test avtrans-3.14 { + set v [catch {execsql { + SELECT a FROM one ORDER BY a; + } db} msg] + lappend v $msg +} {0 {1 2 3 4}} +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) +integrity_check avtrans-3.15 + +do_test avtrans-4.1 { + set v [catch {execsql { + COMMIT; + } db} msg] + lappend v $msg +} {1 {cannot commit - no transaction is active}} +do_test avtrans-4.2 { + set v [catch {execsql { + ROLLBACK; + } db} msg] + lappend v $msg +} {1 {cannot rollback - no transaction is active}} +do_test avtrans-4.3 { + catchsql { + BEGIN TRANSACTION; + UPDATE two SET a = 0 WHERE 0; + SELECT a FROM two ORDER BY a; + } db +} {0 {1 4 5 10}} +do_test avtrans-4.4 { + catchsql { + SELECT a FROM two ORDER BY a; + } altdb +} {0 {1 4 5 10}} +do_test avtrans-4.5 { + catchsql { + SELECT a FROM one ORDER BY a; + } altdb +} {0 {1 2 3 4}} +do_test avtrans-4.6 { + catchsql { + BEGIN TRANSACTION; + SELECT a FROM one ORDER BY a; + } db +} {1 {cannot start a transaction within a transaction}} +do_test avtrans-4.7 { + catchsql { + SELECT a FROM two ORDER BY a; + } altdb +} {0 {1 4 5 10}} +do_test avtrans-4.8 { + catchsql { + SELECT a FROM one ORDER BY a; + } altdb +} {0 {1 2 3 4}} +do_test avtrans-4.9 { + set v [catch {execsql { + END TRANSACTION; + SELECT a FROM two ORDER BY a; + } db} msg] + lappend v $msg +} {0 {1 4 5 10}} +do_test avtrans-4.10 { + set v [catch {execsql { + SELECT a FROM two ORDER BY a; + } altdb} msg] + lappend v $msg +} {0 {1 4 5 10}} +do_test avtrans-4.11 { + set v [catch {execsql { + SELECT a FROM one ORDER BY a; + } altdb} msg] + lappend v $msg +} {0 {1 2 3 4}} +integrity_check avtrans-4.12 +do_test avtrans-4.98 { + altdb close + execsql { + DROP TABLE one; + DROP TABLE two; + } +} {} +integrity_check avtrans-4.99 + +# Check out the commit/rollback behavior of the database +# +do_test avtrans-5.1 { + execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name} +} {} +do_test avtrans-5.2 { + execsql {BEGIN TRANSACTION} + execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name} +} {} +do_test avtrans-5.3 { + execsql {CREATE TABLE one(a text, b int)} + execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name} +} {one} +do_test avtrans-5.4 { + execsql {SELECT a,b FROM one ORDER BY b} +} {} +do_test avtrans-5.5 { + execsql {INSERT INTO one(a,b) VALUES('hello', 1)} + execsql {SELECT a,b FROM one ORDER BY b} +} {hello 1} +do_test avtrans-5.6 { + execsql {ROLLBACK} + execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name} +} {} +do_test avtrans-5.7 { + set v [catch { + execsql {SELECT a,b FROM one ORDER BY b} + } msg] + lappend v $msg +} {1 {no such table: one}} + +# Test commits and rollbacks of table CREATE TABLEs, CREATE INDEXs +# DROP TABLEs and DROP INDEXs +# +do_test avtrans-5.8 { + execsql { + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name + } +} {} +do_test avtrans-5.9 { + execsql { + BEGIN TRANSACTION; + CREATE TABLE t1(a int, b int, c int); + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {t1} +do_test avtrans-5.10 { + execsql { + CREATE INDEX i1 ON t1(a); + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {i1 t1} +do_test avtrans-5.11 { + execsql { + COMMIT; + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {i1 t1} +do_test avtrans-5.12 { + execsql { + BEGIN TRANSACTION; + CREATE TABLE t2(a int, b int, c int); + CREATE INDEX i2a ON t2(a); + CREATE INDEX i2b ON t2(b); + DROP TABLE t1; + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {i2a i2b t2} +do_test avtrans-5.13 { + execsql { + ROLLBACK; + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {i1 t1} +do_test avtrans-5.14 { + execsql { + BEGIN TRANSACTION; + DROP INDEX i1; + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {t1} +do_test avtrans-5.15 { + execsql { + ROLLBACK; + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {i1 t1} +do_test avtrans-5.16 { + execsql { + BEGIN TRANSACTION; + DROP INDEX i1; + CREATE TABLE t2(x int, y int, z int); + CREATE INDEX i2x ON t2(x); + CREATE INDEX i2y ON t2(y); + INSERT INTO t2 VALUES(1,2,3); + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {i2x i2y t1 t2} +do_test avtrans-5.17 { + execsql { + COMMIT; + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {i2x i2y t1 t2} +do_test avtrans-5.18 { + execsql { + SELECT * FROM t2; + } +} {1 2 3} +do_test avtrans-5.19 { + execsql { + SELECT x FROM t2 WHERE y=2; + } +} {1} +do_test avtrans-5.20 { + execsql { + BEGIN TRANSACTION; + DROP TABLE t1; + DROP TABLE t2; + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {} +do_test avtrans-5.21 { + set r [catch {execsql { + SELECT * FROM t2 + }} msg] + lappend r $msg +} {1 {no such table: t2}} +do_test avtrans-5.22 { + execsql { + ROLLBACK; + SELECT name fROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name; + } +} {i2x i2y t1 t2} +do_test avtrans-5.23 { + execsql { + SELECT * FROM t2; + } +} {1 2 3} +integrity_check avtrans-5.23 + + +# Try to DROP and CREATE tables and indices with the same name +# within a transaction. Make sure ROLLBACK works. +# +do_test avtrans-6.1 { + execsql2 { + INSERT INTO t1 VALUES(1,2,3); + BEGIN TRANSACTION; + DROP TABLE t1; + CREATE TABLE t1(p,q,r); + ROLLBACK; + SELECT * FROM t1; + } +} {a 1 b 2 c 3} +do_test avtrans-6.2 { + execsql2 { + INSERT INTO t1 VALUES(1,2,3); + BEGIN TRANSACTION; + DROP TABLE t1; + CREATE TABLE t1(p,q,r); + COMMIT; + SELECT * FROM t1; + } +} {} +do_test avtrans-6.3 { + execsql2 { + INSERT INTO t1 VALUES(1,2,3); + SELECT * FROM t1; + } +} {p 1 q 2 r 3} +do_test avtrans-6.4 { + execsql2 { + BEGIN TRANSACTION; + DROP TABLE t1; + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(4,5,6); + SELECT * FROM t1; + DROP TABLE t1; + } +} {a 4 b 5 c 6} +do_test avtrans-6.5 { + execsql2 { + ROLLBACK; + SELECT * FROM t1; + } +} {p 1 q 2 r 3} +do_test avtrans-6.6 { + execsql2 { + BEGIN TRANSACTION; + DROP TABLE t1; + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(4,5,6); + SELECT * FROM t1; + DROP TABLE t1; + } +} {a 4 b 5 c 6} +do_test avtrans-6.7 { + catchsql { + COMMIT; + SELECT * FROM t1; + } +} {1 {no such table: t1}} + +# Repeat on a table with an automatically generated index. +# +do_test avtrans-6.10 { + execsql2 { + CREATE TABLE t1(a unique,b,c); + INSERT INTO t1 VALUES(1,2,3); + BEGIN TRANSACTION; + DROP TABLE t1; + CREATE TABLE t1(p unique,q,r); + ROLLBACK; + SELECT * FROM t1; + } +} {a 1 b 2 c 3} +do_test avtrans-6.11 { + execsql2 { + BEGIN TRANSACTION; + DROP TABLE t1; + CREATE TABLE t1(p unique,q,r); + COMMIT; + SELECT * FROM t1; + } +} {} +do_test avtrans-6.12 { + execsql2 { + INSERT INTO t1 VALUES(1,2,3); + SELECT * FROM t1; + } +} {p 1 q 2 r 3} +do_test avtrans-6.13 { + execsql2 { + BEGIN TRANSACTION; + DROP TABLE t1; + CREATE TABLE t1(a unique,b,c); + INSERT INTO t1 VALUES(4,5,6); + SELECT * FROM t1; + DROP TABLE t1; + } +} {a 4 b 5 c 6} +do_test avtrans-6.14 { + execsql2 { + ROLLBACK; + SELECT * FROM t1; + } +} {p 1 q 2 r 3} +do_test avtrans-6.15 { + execsql2 { + BEGIN TRANSACTION; + DROP TABLE t1; + CREATE TABLE t1(a unique,b,c); + INSERT INTO t1 VALUES(4,5,6); + SELECT * FROM t1; + DROP TABLE t1; + } +} {a 4 b 5 c 6} +do_test avtrans-6.16 { + catchsql { + COMMIT; + SELECT * FROM t1; + } +} {1 {no such table: t1}} + +do_test avtrans-6.20 { + execsql { + CREATE TABLE t1(a integer primary key,b,c); + INSERT INTO t1 VALUES(1,-2,-3); + INSERT INTO t1 VALUES(4,-5,-6); + SELECT * FROM t1; + } +} {1 -2 -3 4 -5 -6} +do_test avtrans-6.21 { + execsql { + CREATE INDEX i1 ON t1(b); + SELECT * FROM t1 WHERE b<1; + } +} {4 -5 -6 1 -2 -3} +do_test avtrans-6.22 { + execsql { + BEGIN TRANSACTION; + DROP INDEX i1; + SELECT * FROM t1 WHERE b<1; + ROLLBACK; + } +} {1 -2 -3 4 -5 -6} +do_test avtrans-6.23 { + execsql { + SELECT * FROM t1 WHERE b<1; + } +} {4 -5 -6 1 -2 -3} +do_test avtrans-6.24 { + execsql { + BEGIN TRANSACTION; + DROP TABLE t1; + ROLLBACK; + SELECT * FROM t1 WHERE b<1; + } +} {4 -5 -6 1 -2 -3} + +do_test avtrans-6.25 { + execsql { + BEGIN TRANSACTION; + DROP INDEX i1; + CREATE INDEX i1 ON t1(c); + SELECT * FROM t1 WHERE b<1; + } +} {1 -2 -3 4 -5 -6} +do_test avtrans-6.26 { + execsql { + SELECT * FROM t1 WHERE c<1; + } +} {4 -5 -6 1 -2 -3} +do_test avtrans-6.27 { + execsql { + ROLLBACK; + SELECT * FROM t1 WHERE b<1; + } +} {4 -5 -6 1 -2 -3} +do_test avtrans-6.28 { + execsql { + SELECT * FROM t1 WHERE c<1; + } +} {1 -2 -3 4 -5 -6} + +# The following repeats steps 6.20 through 6.28, but puts a "unique" +# constraint the first field of the table in order to generate an +# automatic index. +# +do_test avtrans-6.30 { + execsql { + BEGIN TRANSACTION; + DROP TABLE t1; + CREATE TABLE t1(a int unique,b,c); + COMMIT; + INSERT INTO t1 VALUES(1,-2,-3); + INSERT INTO t1 VALUES(4,-5,-6); + SELECT * FROM t1 ORDER BY a; + } +} {1 -2 -3 4 -5 -6} +do_test avtrans-6.31 { + execsql { + CREATE INDEX i1 ON t1(b); + SELECT * FROM t1 WHERE b<1; + } +} {4 -5 -6 1 -2 -3} +do_test avtrans-6.32 { + execsql { + BEGIN TRANSACTION; + DROP INDEX i1; + SELECT * FROM t1 WHERE b<1; + ROLLBACK; + } +} {1 -2 -3 4 -5 -6} +do_test avtrans-6.33 { + execsql { + SELECT * FROM t1 WHERE b<1; + } +} {4 -5 -6 1 -2 -3} +do_test avtrans-6.34 { + execsql { + BEGIN TRANSACTION; + DROP TABLE t1; + ROLLBACK; + SELECT * FROM t1 WHERE b<1; + } +} {4 -5 -6 1 -2 -3} + +do_test avtrans-6.35 { + execsql { + BEGIN TRANSACTION; + DROP INDEX i1; + CREATE INDEX i1 ON t1(c); + SELECT * FROM t1 WHERE b<1; + } +} {1 -2 -3 4 -5 -6} +do_test avtrans-6.36 { + execsql { + SELECT * FROM t1 WHERE c<1; + } +} {4 -5 -6 1 -2 -3} +do_test avtrans-6.37 { + execsql { + DROP INDEX i1; + SELECT * FROM t1 WHERE c<1; + } +} {1 -2 -3 4 -5 -6} +do_test avtrans-6.38 { + execsql { + ROLLBACK; + SELECT * FROM t1 WHERE b<1; + } +} {4 -5 -6 1 -2 -3} +do_test avtrans-6.39 { + execsql { + SELECT * FROM t1 WHERE c<1; + } +} {1 -2 -3 4 -5 -6} +integrity_check avtrans-6.40 + +ifcapable !floatingpoint { + finish_test + return +} + +# Test to make sure rollback restores the database back to its original +# state. +# +do_test avtrans-7.1 { + execsql {BEGIN} + for {set i 0} {$i<1000} {incr i} { + set r1 [expr {rand()}] + set r2 [expr {rand()}] + set r3 [expr {rand()}] + execsql "INSERT INTO t2 VALUES($r1,$r2,$r3)" + } + execsql {COMMIT} + set ::checksum [execsql {SELECT md5sum(x,y,z) FROM t2}] + set ::checksum2 [ + execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master} + ] + execsql {SELECT count(*) FROM t2} +} {1001} +do_test avtrans-7.2 { + execsql {SELECT md5sum(x,y,z) FROM t2} +} $checksum +do_test avtrans-7.2.1 { + execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master} +} $checksum2 +do_test avtrans-7.3 { + execsql { + BEGIN; + DELETE FROM t2; + ROLLBACK; + SELECT md5sum(x,y,z) FROM t2; + } +} $checksum +do_test avtrans-7.4 { + execsql { + BEGIN; + INSERT INTO t2 SELECT * FROM t2; + ROLLBACK; + SELECT md5sum(x,y,z) FROM t2; + } +} $checksum +do_test avtrans-7.5 { + execsql { + BEGIN; + DELETE FROM t2; + ROLLBACK; + SELECT md5sum(x,y,z) FROM t2; + } +} $checksum +do_test avtrans-7.6 { + execsql { + BEGIN; + INSERT INTO t2 SELECT * FROM t2; + ROLLBACK; + SELECT md5sum(x,y,z) FROM t2; + } +} $checksum +do_test avtrans-7.7 { + execsql { + BEGIN; + CREATE TABLE t3 AS SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t3; + ROLLBACK; + SELECT md5sum(x,y,z) FROM t2; + } +} $checksum +do_test avtrans-7.8 { + execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master} +} $checksum2 +ifcapable tempdb { + do_test avtrans-7.9 { + execsql { + BEGIN; + CREATE TEMP TABLE t3 AS SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t3; + ROLLBACK; + SELECT md5sum(x,y,z) FROM t2; + } + } $checksum +} +do_test avtrans-7.10 { + execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master} +} $checksum2 +ifcapable tempdb { + do_test avtrans-7.11 { + execsql { + BEGIN; + CREATE TEMP TABLE t3 AS SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t3; + DROP INDEX i2x; + DROP INDEX i2y; + CREATE INDEX i3a ON t3(x); + ROLLBACK; + SELECT md5sum(x,y,z) FROM t2; + } + } $checksum +} +do_test avtrans-7.12 { + execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master} +} $checksum2 +ifcapable tempdb { + do_test avtrans-7.13 { + execsql { + BEGIN; + DROP TABLE t2; + ROLLBACK; + SELECT md5sum(x,y,z) FROM t2; + } + } $checksum +} +do_test avtrans-7.14 { + execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master} +} $checksum2 +integrity_check avtrans-7.15 + +# Arrange for another process to begin modifying the database but abort +# and die in the middle of the modification. Then have this process read +# the database. This process should detect the journal file and roll it +# back. Verify that this happens correctly. +# +set fd [open test.tcl w] +puts $fd { + sqlite3 db test.db + db eval { + PRAGMA default_cache_size=20; + BEGIN; + CREATE TABLE t3 AS SELECT * FROM t2; + DELETE FROM t2; + } + sqlite_abort +} +close $fd +do_test avtrans-8.1 { + catch {exec [info nameofexec] test.tcl} + execsql {SELECT md5sum(x,y,z) FROM t2} +} $checksum +do_test avtrans-8.2 { + execsql {SELECT md5sum(type,name,tbl_name,rootpage,sql) FROM sqlite_master} +} $checksum2 +integrity_check avtrans-8.3 + +# In the following sequence of tests, compute the MD5 sum of the content +# of a table, make lots of modifications to that table, then do a rollback. +# Verify that after the rollback, the MD5 checksum is unchanged. +# +do_test avtrans-9.1 { + execsql { + PRAGMA default_cache_size=10; + } + db close + sqlite3 db test.db + execsql { + BEGIN; + CREATE TABLE t3(x TEXT); + INSERT INTO t3 VALUES(randstr(10,400)); + INSERT INTO t3 VALUES(randstr(10,400)); + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + COMMIT; + SELECT count(*) FROM t3; + } +} {1024} + +# The following procedure computes a "signature" for table "t3". If +# T3 changes in any way, the signature should change. +# +# This is used to test ROLLBACK. We gather a signature for t3, then +# make lots of changes to t3, then rollback and take another signature. +# The two signatures should be the same. +# +proc signature {} { + return [db eval {SELECT count(*), md5sum(x) FROM t3}] +} + +# Repeat the following group of tests 20 times for quick testing and +# 40 times for full testing. Each iteration of the test makes table +# t3 a little larger, and thus takes a little longer, so doing 40 tests +# is more than 2.0 times slower than doing 20 tests. Considerably more. +# +if {[info exists G(isquick)]} { + set limit 20 +} else { + set limit 40 +} + +# Do rollbacks. Make sure the signature does not change. +# +for {set i 2} {$i<=$limit} {incr i} { + set ::sig [signature] + set cnt [lindex $::sig 0] + if {$i%2==0} { + execsql {PRAGMA fullfsync=ON} + } else { + execsql {PRAGMA fullfsync=OFF} + } + set sqlite_sync_count 0 + set sqlite_fullsync_count 0 + do_test avtrans-9.$i.1-$cnt { + execsql { + BEGIN; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + ROLLBACK; + } + signature + } $sig + do_test avtrans-9.$i.2-$cnt { + execsql { + BEGIN; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + ROLLBACK; + } + signature + } $sig + if {$i<$limit} { + do_test avtrans-9.$i.3-$cnt { + execsql { + INSERT INTO t3 SELECT randstr(10,400) FROM t3 WHERE random()%10==0; + } + } {} + if {$tcl_platform(platform)=="unix"} { + do_test avtrans-9.$i.4-$cnt { + expr {$sqlite_sync_count>0} + } 1 + ifcapable pager_pragmas { + do_test avtrans-9.$i.5-$cnt { + expr {$sqlite_fullsync_count>0} + } [expr {$i%2==0}] + } else { + do_test avtrans-9.$i.5-$cnt { + expr {$sqlite_fullsync_count==0} + } {1} + } + } + wal_check_journal_mode avtrans-9.$i-6.$cnt + } + set ::pager_old_format 0 +} +integrity_check avtrans-10.1 +wal_check_journal_mode avtrans-10.2 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/backcompat.test b/components/external/SQLite-3.8.1/test/backcompat.test new file mode 100644 index 0000000000000000000000000000000000000000..dd40fed23a9dcefbe9c1927cc948f013c6594084 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/backcompat.test @@ -0,0 +1,427 @@ +# 2010 August 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that the current version of SQLite +# is capable of reading and writing databases created by previous +# versions, and vice-versa. +# +# To use this test, old versions of the testfixture process should be +# copied into the working directory alongside the new version. The old +# versions should be named "testfixtureXXX" (or testfixtureXXX.exe on +# windows), where XXX can be any string. +# +# This test file uses the tcl code for controlling a second testfixture +# process located in lock_common.tcl. See the commments in lock_common.tcl +# for documentation of the available commands. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl +source $testdir/bc_common.tcl +db close + +if {"" == [bc_find_binaries backcompat.test]} { + finish_test + return +} + +proc do_backcompat_test {rv bin1 bin2 script} { + + forcedelete test.db + + if {$bin1 != ""} { set ::bc_chan1 [launch_testfixture $bin1] } + set ::bc_chan2 [launch_testfixture $bin2] + + if { $rv } { + proc code2 {tcl} { uplevel #0 $tcl } + if {$bin1 != ""} { proc code2 {tcl} { testfixture $::bc_chan1 $tcl } } + proc code1 {tcl} { testfixture $::bc_chan2 $tcl } + } else { + proc code1 {tcl} { uplevel #0 $tcl } + if {$bin1 != ""} { proc code1 {tcl} { testfixture $::bc_chan1 $tcl } } + proc code2 {tcl} { testfixture $::bc_chan2 $tcl } + } + + proc sql1 sql { code1 [list db eval $sql] } + proc sql2 sql { code2 [list db eval $sql] } + + code1 { sqlite3 db test.db } + code2 { sqlite3 db test.db } + + uplevel $script + + catch { code1 { db close } } + catch { code2 { db close } } + catch { close $::bc_chan2 } + catch { close $::bc_chan1 } +} + +array set ::incompatible [list] +proc do_allbackcompat_test {script} { + + foreach bin $::BC(binaries) { + set nErr [set_test_counter errors] + foreach dir {0 1} { + + set bintag [string map {testfixture {}} $bin] + set bintag [string map {\.exe {}} $bintag] + if {$bintag == ""} {set bintag self} + set ::bcname ".$bintag.$dir." + + rename do_test _do_test + proc do_test {nm sql res} { + set nm [regsub {\.} $nm $::bcname] + uplevel [list _do_test $nm $sql $res] + } + + do_backcompat_test $dir {} $bin $script + + rename do_test {} + rename _do_test do_test + } + if { $nErr < [set_test_counter errors] } { + set ::incompatible([get_version $bin]) 1 + } + } +} + +proc read_file {zFile} { + set zData {} + if {[file exists $zFile]} { + set fd [open $zFile] + fconfigure $fd -translation binary -encoding binary + + if {[file size $zFile]<=$::sqlite_pending_byte || $zFile != "test.db"} { + set zData [read $fd] + } else { + set zData [read $fd $::sqlite_pending_byte] + append zData [string repeat x 512] + seek $fd [expr $::sqlite_pending_byte+512] start + append zData [read $fd] + } + + close $fd + } + return $zData +} +proc write_file {zFile zData} { + set fd [open $zFile w] + fconfigure $fd -translation binary -encoding binary + puts -nonewline $fd $zData + close $fd +} +proc read_file_system {} { + set ret [list] + foreach f {test.db test.db-journal test.db-wal} { lappend ret [read_file $f] } + set ret +} +proc write_file_system {data} { + foreach f {test.db test.db-journal test.db-wal} d $data { + if {[string length $d] == 0} { + forcedelete $f + } else { + write_file $f $d + } + } +} + +#------------------------------------------------------------------------- +# Actual tests begin here. +# +# This first block of tests checks to see that the same database and +# journal files can be used by old and new versions. WAL and wal-index +# files are tested separately below. +# +do_allbackcompat_test { + + # Test that database files are backwards compatible. + # + do_test backcompat-1.1.1 { sql1 { + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + INSERT INTO t1 VALUES('abc', 'def'); + } } {} + do_test backcompat-1.1.2 { sql2 { SELECT * FROM t1; } } {abc def} + do_test backcompat-1.1.3 { sql2 { INSERT INTO t1 VALUES('ghi', 'jkl'); } } {} + do_test backcompat-1.1.4 { sql1 { SELECT * FROM t1; } } {abc def ghi jkl} + do_test backcompat-1.1.5 { sql1 { PRAGMA integrity_check } } {ok} + do_test backcompat-1.1.6 { sql2 { PRAGMA integrity_check } } {ok} + + # Test that one version can roll back a hot-journal file left in the + # file-system by the other version. + # + # Each test case is named "backcompat-1.X...", where X is either 0 or + # 1. If it is 0, then the current version creates a journal file that + # the old versions try to read. Otherwise, if X is 1, then the old version + # creates the journal file and we try to read it with the current version. + # + do_test backcompat-1.2.1 { sql1 { + PRAGMA cache_size = 10; + BEGIN; + INSERT INTO t1 VALUES(randomblob(400), randomblob(400)); + INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1; + INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1; + INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1; + INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1; + COMMIT; + } } {} + set cksum1 [sql1 {SELECT md5sum(a), md5sum(b) FROM t1}] + set cksum2 [sql2 {SELECT md5sum(a), md5sum(b) FROM t1}] + do_test backcompat-1.2.2 [list string compare $cksum1 $cksum2] 0 + + do_test backcompat-1.2.3 { sql1 { + BEGIN; + UPDATE t1 SET a = randomblob(500); + } } {} + set data [read_file_system] + + do_test backcompat-1.2.4 { sql1 { COMMIT } } {} + + set same [expr {[sql2 {SELECT md5sum(a), md5sum(b) FROM t1}] == $cksum2}] + do_test backcompat-1.2.5 [list set {} $same] 0 + + code1 { db close } + code2 { db close } + write_file_system $data + code1 { sqlite3 db test.db } + code2 { sqlite3 db test.db } + + set same [expr {[sql2 {SELECT md5sum(a), md5sum(b) FROM t1}] == $cksum2}] + do_test backcompat-1.2.6 [list set {} $same] 1 + + do_test backcompat-1.2.7 { sql1 { PRAGMA integrity_check } } {ok} + do_test backcompat-1.2.8 { sql2 { PRAGMA integrity_check } } {ok} +} +foreach k [lsort [array names ::incompatible]] { + puts "ERROR: Detected journal incompatibility with version $k" +} +unset ::incompatible + + +#------------------------------------------------------------------------- +# Test that WAL and wal-index files may be shared between different +# SQLite versions. +# +do_allbackcompat_test { + if {[code1 {sqlite3 -version}] >= "3.7.0" + && [code1 {set ::sqlite_options(wal)}] + && [code2 {sqlite3 -version}] >= "3.7.0" + && [code2 {set ::sqlite_options(wal)}] + } { + + do_test backcompat-2.1.1 { sql1 { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + INSERT INTO t1 VALUES('I', 1); + INSERT INTO t1 VALUES('II', 2); + INSERT INTO t1 VALUES('III', 3); + SELECT * FROM t1; + } } {wal I 1 II 2 III 3} + do_test backcompat-2.1.2 { sql2 { + SELECT * FROM t1; + } } {I 1 II 2 III 3} + + set data [read_file_system] + code1 {db close} + code2 {db close} + write_file_system $data + code1 {sqlite3 db test.db} + code2 {sqlite3 db test.db} + + # The WAL file now in the file-system was created by the [code1] + # process. Check that the [code2] process can recover the log. + # + do_test backcompat-2.1.3 { sql2 { + SELECT * FROM t1; + } } {I 1 II 2 III 3} + do_test backcompat-2.1.4 { sql1 { + SELECT * FROM t1; + } } {I 1 II 2 III 3} + } +} + +#------------------------------------------------------------------------- +# Test that FTS3 tables may be read/written by different versions of +# SQLite. +# +ifcapable fts3 { + set contents { + CREATE VIRTUAL TABLE t1 USING fts3(a, b); + } + foreach {num doc} { + one "jk zm jk eczkjblu urvysbnykk sk gnl jk ttvgf hmjf" + two "jk bnhc jjrxpjkb mjpavjuhw fibokdry igju jk zm zm xh" + three "wxe ogttbykvt uhzq xr iaf zf urvysbnykk aayxpmve oacaxgjoo mjpavjuhw" + four "gazrt jk ephknonq myjp uenvbm wuvajhwqz jk zm xnxhf nvfasfh" + five "zm aayxpmve csjqxhgj xnxhf xr jk aayxpmve xnxhf zm zm" + six "sokcyf zm ogyavjvv jk zm fibokdry zm jk igju igju" + seven "vgsld bvgimjik xuprtlyle jk akmikrqyt jk aayxpmve hkfoudzftq ddjj" + eight "zm uhzq ovkyevlgv zk uenvbm csjqxhgj jk vgsld pgybs jk" + nine "zm agmckuiu zexh fibokdry jk uhzq bu tugflixoex xnxhf sk" + } { + append contents "INSERT INTO t1 VALUES('$num', '$doc');" + } + do_allbackcompat_test { + if {[code1 {set ::sqlite_options(fts3)}] + && [code2 {set ::sqlite_options(fts3)}] + } { + + do_test backcompat-3.1 { sql1 $contents } {} + + foreach {n q} { + 1 "SELECT * FROM t1 ORDER BY a, b" + 2 "SELECT rowid FROM t1 WHERE a MATCH 'five'" + 3 "SELECT * FROM t1 WHERE a MATCH 'five'" + 4 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'jk'" + 5 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'tug* OR eight'" + } { + do_test backcompat-3.2 [list sql1 $q] [sql2 $q] + } + + do_test backcompat-3.3 { sql1 { + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + } } {} + + foreach {n q} { + 1 "SELECT * FROM t1 ORDER BY a, b" + 2 "SELECT rowid FROM t1 WHERE a MATCH 'five'" + 3 "SELECT * FROM t1 WHERE a MATCH 'five'" + 4 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'jk'" + 5 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'tug* OR eight'" + } { + do_test backcompat-3.4 [list sql1 $q] [sql2 $q] + } + + set alphabet "a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4" + for {set i 0} {$i < 900} {incr i} { + set term "[lindex $alphabet [expr $i/30]][lindex $alphabet [expr $i%30]] " + sql1 "INSERT INTO t1 VALUES($i, '[string repeat $term 14]')" + } + + foreach {n q} { + 1 "SELECT * FROM t1 ORDER BY a, b" + 2 "SELECT rowid FROM t1 WHERE a MATCH 'five'" + 3 "SELECT * FROM t1 WHERE a MATCH 'five'" + 4 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'jk'" + 5 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'tug* OR eight'" + + 6 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'aa'" + 7 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH '44'" + 8 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'a*'" + } { + do_test backcompat-3.5 [list sql1 $q] [sql2 $q] + } + + do_test backcompat-3.6 { + sql1 "SELECT optimize(t1) FROM t1 LIMIT 1" + } {{Index optimized}} + + foreach {n q} { + 1 "SELECT * FROM t1 ORDER BY a, b" + 2 "SELECT rowid FROM t1 WHERE a MATCH 'five'" + 3 "SELECT * FROM t1 WHERE a MATCH 'five'" + 4 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'jk'" + 5 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'tug* OR eight'" + + 6 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'aa'" + 7 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH '44'" + 8 "SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'a*'" + } { + do_test backcompat-3.7 [list sql1 $q] [sql2 $q] + } + } + } +} + +#------------------------------------------------------------------------- +# Test that Rtree tables may be read/written by different versions of +# SQLite. +# +ifcapable rtree { + set contents { + CREATE VIRTUAL TABLE t1 USING rtree(id, x1, x2, y1, y2); + } + foreach {id x1 x2 y1 y2} { + 1 -47.64 43.87 33.86 34.42 2 -21.51 17.32 2.05 31.04 + 3 -43.67 -38.33 -19.79 3.43 4 32.41 35.16 9.12 19.82 + 5 33.28 34.87 14.78 28.26 6 49.31 116.59 -9.87 75.09 + 7 -14.93 34.51 -17.64 64.09 8 -43.05 23.43 -1.19 69.44 + 9 44.79 133.56 28.09 80.30 10 -2.66 81.47 -41.38 -10.46 + 11 -42.89 -3.54 15.76 71.63 12 -3.50 84.96 -11.64 64.95 + 13 -45.69 26.25 11.14 55.06 14 -44.09 11.23 17.52 44.45 + 15 36.23 133.49 -19.38 53.67 16 -17.89 81.54 14.64 50.61 + 17 -41.97 -24.04 -39.43 28.95 18 -5.85 7.76 -6.38 47.02 + 19 18.82 27.10 42.82 100.09 20 39.17 113.45 26.14 73.47 + 21 22.31 103.17 49.92 106.05 22 -43.06 40.38 -1.75 76.08 + 23 2.43 57.27 -14.19 -3.83 24 -47.57 -4.35 8.93 100.06 + 25 -37.47 49.14 -29.11 8.81 26 -7.86 75.72 49.34 107.42 + 27 1.53 45.49 20.36 49.74 28 -48.48 32.54 28.81 54.45 + 29 2.67 39.77 -4.05 13.67 30 4.11 62.88 -47.44 -5.72 + 31 -21.47 51.75 37.25 116.09 32 45.59 111.37 -6.43 43.64 + 33 35.23 48.29 23.54 113.33 34 16.61 68.35 -14.69 65.97 + 35 13.98 16.60 48.66 102.87 36 19.74 23.84 31.15 77.27 + 37 -27.61 24.43 7.96 94.91 38 -34.77 12.05 -22.60 -6.29 + 39 -25.83 8.71 -13.48 -12.53 40 -17.11 -1.01 18.06 67.89 + 41 14.13 71.72 -3.78 39.25 42 23.75 76.00 -16.30 8.23 + 43 -39.15 28.63 38.12 125.88 44 48.62 86.09 36.49 102.95 + 45 -31.39 -21.98 2.52 89.78 46 5.65 56.04 15.94 89.10 + 47 18.28 95.81 46.46 143.08 48 30.93 102.82 -20.08 37.36 + 49 -20.78 -3.48 -5.58 35.46 50 49.85 90.58 -24.48 46.29 + } { + if {$x1 >= $x2 || $y1 >= $y2} { error "$x1 $x2 $y1 $y2" } + append contents "INSERT INTO t1 VALUES($id, $x1, $x2, $y1, $y2);" + } + set queries { + 1 "SELECT id FROM t1 WHERE x1>10 AND x2<44" + 2 "SELECT id FROM t1 WHERE y1<100" + 3 "SELECT id FROM t1 WHERE y1<100 AND x1>0" + 4 "SELECT id FROM t1 WHERE y1>10 AND x1>0 AND x2<50 AND y2<550" + } + do_allbackcompat_test { + if {[code1 {set ::sqlite_options(fts3)}] + && [code2 {set ::sqlite_options(fts3)}] + } { + + do_test backcompat-4.1 { sql1 $contents } {} + + foreach {n q} $::queries { + do_test backcompat-4.2.$n [list sql1 $q] [sql2 $q] + } + + do_test backcompat-4.3 { sql1 { + INSERT INTO t1 SELECT id+100, x1+10.0, x2+10.0, y1-10.0, y2-10.0 FROM t1; + } } {} + + foreach {n q} $::queries { + do_test backcompat-4.4.$n [list sql1 $q] [sql2 $q] + } + + do_test backcompat-4.5 { sql2 { + INSERT INTO t1 SELECT id+200, x1+20.0, x2+20.0, y1-20.0, y2-20.0 FROM t1; + } } {} + + foreach {n q} $::queries { + do_test backcompat-4.6.$n [list sql1 $q] [sql2 $q] + } + + } + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/backup.test b/components/external/SQLite-3.8.1/test/backup.test new file mode 100644 index 0000000000000000000000000000000000000000..444619c68c41b4fe6a1a9b156df11d9075993fa6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/backup.test @@ -0,0 +1,972 @@ +# 2009 January 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the sqlite3_backup_XXX API. +# +# $Id: backup.test,v 1.11 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_not_use_codec + +#--------------------------------------------------------------------- +# Test organization: +# +# backup-1.*: Warm-body tests. +# +# backup-2.*: Test backup under various conditions. To and from in-memory +# databases. To and from empty/populated databases. etc. +# +# backup-3.*: Verify that the locking-page (pending byte page) is handled. +# +# backup-4.*: Test various error conditions. +# +# backup-5.*: Test the source database being modified during a backup. +# +# backup-6.*: Test the backup_remaining() and backup_pagecount() APIs. +# +# backup-7.*: Test SQLITE_BUSY and SQLITE_LOCKED errors. +# +# backup-8.*: Test multiple simultaneous backup operations. +# +# backup-9.*: Test that passing a negative argument to backup_step() is +# interpreted as "copy the whole file". +# +# backup-10.*: Test writing the source database mid backup. +# + +proc data_checksum {db file} { $db one "SELECT md5sum(a, b) FROM ${file}.t1" } +proc test_contents {name db1 file1 db2 file2} { + $db2 eval {select * from sqlite_master} + $db1 eval {select * from sqlite_master} + set checksum [data_checksum $db2 $file2] + uplevel [list do_test $name [list data_checksum $db1 $file1] $checksum] +} + +do_test backup-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 VALUES(2, randstr(1000,1000)); + INSERT INTO t1 VALUES(3, randstr(1000,1000)); + INSERT INTO t1 VALUES(4, randstr(1000,1000)); + INSERT INTO t1 VALUES(5, randstr(1000,1000)); + COMMIT; + } +} {} + +# Sanity check to verify that the [test_contents] proc works. +# +test_contents backup-1.2 db main db main + +# Check that it is possible to create and finish backup operations. +# +do_test backup-1.3.1 { + delete_file test2.db + sqlite3 db2 test2.db + sqlite3_backup B db2 main db main +} {B} +do_test backup-1.3.2 { + B finish +} {SQLITE_OK} +do_test backup-1.3.3 { + info commands B +} {} + +# Simplest backup operation. Backup test.db to test2.db. test2.db is +# initially empty. test.db uses the default page size. +# +do_test backup-1.4.1 { + sqlite3_backup B db2 main db main +} {B} +do_test backup-1.4.2 { + B step 200 +} {SQLITE_DONE} +do_test backup-1.4.3 { + B finish +} {SQLITE_OK} +do_test backup-1.4.4 { + info commands B +} {} +test_contents backup-1.4.5 db2 main db main +db close +db2 close +# +# End of backup-1.* tests. +#--------------------------------------------------------------------- + + +#--------------------------------------------------------------------- +# The following tests, backup-2.*, are based on the following procedure: +# +# 1) Populate the source database. +# 2) Populate the destination database. +# 3) Run the backup to completion. (backup-2.*.1) +# 4) Integrity check the destination db. (backup-2.*.2) +# 5) Check that the contents of the destination db is the same as that +# of the source db. (backup-2.*.3) +# +# The test is run with all possible combinations of the following +# input parameters, except that if the destination is an in-memory +# database, the only page size tested is 1024 bytes (the same as the +# source page-size). +# +# * Source database is an in-memory database, OR +# * Source database is a file-backed database. +# +# * Target database is an in-memory database, OR +# * Target database is a file-backed database. +# +# * Destination database is a main file, OR +# * Destination database is an attached file, OR +# * Destination database is a temp database. +# +# * Target database is empty (zero bytes), OR +# * Target database is larger than the source, OR +# * Target database is smaller than the source. +# +# * Target database page-size is the same as the source, OR +# * Target database page-size is larger than the source, OR +# * Target database page-size is smaller than the source. +# +# * Each call to step copies a single page, OR +# * A single call to step copies the entire source database. +# +set iTest 1 +foreach zSrcFile {test.db :memory:} { +foreach zDestFile {test2.db :memory:} { +foreach zOpenScript [list { + sqlite3 db $zSrcFile + sqlite3 db2 $zSrcFile + db2 eval "ATTACH '$zDestFile' AS bak" + set db_dest db2 + set file_dest bak +} { + sqlite3 db $zSrcFile + sqlite3 db2 $zDestFile + set db_dest db2 + set file_dest main +} { + sqlite3 db $zSrcFile + sqlite3 db2 $zDestFile + set db_dest db2 + set file_dest temp +}] { +foreach rows_dest {0 3 10} { +foreach pgsz_dest {512 1024 2048} { +foreach nPagePerStep {1 200} { + + # Open the databases. + catch { delete_file test.db } + catch { delete_file test2.db } + eval $zOpenScript + + # Set to true if copying to an in-memory destination. Copying to an + # in-memory destination is only possible if the initial destination + # page size is the same as the source page size (in this case 1024 bytes). + # + set isMemDest [expr { + $zDestFile eq ":memory:" || $file_dest eq "temp" && $TEMP_STORE>=2 + }] + + if { $isMemDest==0 || $pgsz_dest == 1024 } { + if 0 { + puts -nonewline "Test $iTest: src=$zSrcFile dest=$zDestFile" + puts -nonewline " (as $db_dest.$file_dest)" + puts -nonewline " rows_dest=$rows_dest pgsz_dest=$pgsz_dest" + puts "" + } + + # Set up the content of the source database. + execsql { + PRAGMA page_size = 1024; + BEGIN; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 VALUES(2, randstr(1000,1000)); + INSERT INTO t1 VALUES(3, randstr(1000,1000)); + INSERT INTO t1 VALUES(4, randstr(1000,1000)); + INSERT INTO t1 VALUES(5, randstr(1000,1000)); + COMMIT; + } + + + + # Set up the content of the target database. + execsql "PRAGMA ${file_dest}.page_size = ${pgsz_dest}" $db_dest + if {$rows_dest != 0} { + execsql " + BEGIN; + CREATE TABLE ${file_dest}.t1(a, b); + CREATE INDEX ${file_dest}.i1 ON t1(a, b); + " $db_dest + for {set ii 0} {$ii < $rows_dest} {incr ii} { + execsql " + INSERT INTO ${file_dest}.t1 VALUES(1, randstr(1000,1000)) + " $db_dest + } + } + + # Backup the source database. + do_test backup-2.$iTest.1 { + sqlite3_backup B $db_dest $file_dest db main + while {[B step $nPagePerStep]=="SQLITE_OK"} {} + B finish + } {SQLITE_OK} + + # Run integrity check on the backup. + do_test backup-2.$iTest.2 { + execsql "PRAGMA ${file_dest}.integrity_check" $db_dest + } {ok} + + test_contents backup-2.$iTest.3 db main $db_dest $file_dest + + } + + db close + catch {db2 close} + incr iTest + +} } } } } } +# +# End of backup-2.* tests. +#--------------------------------------------------------------------- + +#--------------------------------------------------------------------- +# These tests, backup-3.*, ensure that nothing goes wrong if either +# the source or destination database are large enough to include the +# the locking-page (the page that contains the range of bytes that +# the locks are applied to). These tests assume that the pending +# byte is at offset 0x00010000 (64KB offset), as set by tester.tcl, +# not at the 1GB offset as it usually is. +# +# The test procedure is as follows (same procedure as used for +# the backup-2.* tests): +# +# 1) Populate the source database. +# 2) Populate the destination database. +# 3) Run the backup to completion. (backup-3.*.1) +# 4) Integrity check the destination db. (backup-3.*.2) +# 5) Check that the contents of the destination db is the same as that +# of the source db. (backup-3.*.3) +# +# The test procedure is run with the following parameters varied: +# +# * Source database includes pending-byte page. +# * Source database does not include pending-byte page. +# +# * Target database includes pending-byte page. +# * Target database does not include pending-byte page. +# +# * Target database page-size is the same as the source, OR +# * Target database page-size is larger than the source, OR +# * Target database page-size is smaller than the source. +# +set iTest 1 +foreach nSrcPg {10 64 65 66 100} { +foreach nDestRow {10 100} { +foreach nDestPgsz {512 1024 2048 4096} { + + catch { delete_file test.db } + catch { delete_file test2.db } + sqlite3 db test.db + sqlite3 db2 test2.db + + # Set up the content of the two databases. + # + execsql { PRAGMA page_size = 1024 } + execsql "PRAGMA page_size = $nDestPgsz" db2 + foreach db {db db2} { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + COMMIT; + } $db + } + while {[file size test.db]/1024 < $nSrcPg} { + execsql { INSERT INTO t1 VALUES($ii, randstr(200,200)) } + } + + for {set ii 0} {$ii < $nDestRow} {incr ii} { + execsql { INSERT INTO t1 VALUES($ii, randstr(1000,1000)) } db2 + } + + # Backup the source database. + do_test backup-3.$iTest.1 { + sqlite3_backup B db main db2 main + while {[B step 10]=="SQLITE_OK"} {} + B finish + } {SQLITE_OK} + + # Run integrity check on the backup. + do_test backup-3.$iTest.2 { + execsql "PRAGMA integrity_check" db2 + } {ok} + + test_contents backup-3.$iTest.3 db main db2 main + + db close + db2 close + incr iTest +} +} +} + +#-------------------------------------------------------------------- +do_test backup-3.$iTest.1 { + catch { forcedelete test.db } + catch { forcedelete test2.db } + sqlite3 db test.db + set iTab 1 + + db eval { PRAGMA page_size = 512 } + while {[file size test.db] <= $::sqlite_pending_byte} { + db eval "CREATE TABLE t${iTab}(a, b, c)" + incr iTab + } + + sqlite3 db2 test2.db + db2 eval { PRAGMA page_size = 4096 } + while {[file size test2.db] < $::sqlite_pending_byte} { + db2 eval "CREATE TABLE t${iTab}(a, b, c)" + incr iTab + } + + sqlite3_backup B db2 main db main + B step -1 +} {SQLITE_DONE} + +do_test backup-3.$iTest.2 { + B finish +} {SQLITE_OK} + +# +# End of backup-3.* tests. +#--------------------------------------------------------------------- + + +#--------------------------------------------------------------------- +# The following tests, backup-4.*, test various error conditions: +# +# backup-4.1.*: Test invalid database names. +# +# backup-4.2.*: Test that the source database cannot be detached while +# a backup is in progress. +# +# backup-4.3.*: Test that the source database handle cannot be closed +# while a backup is in progress. +# +# backup-4.4.*: Test an attempt to specify the same handle for the +# source and destination databases. +# +# backup-4.5.*: Test that an in-memory destination with a different +# page-size to the source database is an error. +# +sqlite3 db test.db +sqlite3 db2 test2.db + +do_test backup-4.1.1 { + catch { sqlite3_backup B db aux db2 main } +} {1} +do_test backup-4.1.2 { + sqlite3_errmsg db +} {unknown database aux} +do_test backup-4.1.3 { + catch { sqlite3_backup B db main db2 aux } +} {1} +do_test backup-4.1.4 { + sqlite3_errmsg db +} {unknown database aux} + +do_test backup-4.2.1 { + catch { forcedelete test3.db } + catch { forcedelete test4.db } + execsql { + ATTACH 'test3.db' AS aux1; + CREATE TABLE aux1.t1(a, b); + } + execsql { + ATTACH 'test4.db' AS aux2; + CREATE TABLE aux2.t2(a, b); + } db2 + sqlite3_backup B db aux1 db2 aux2 +} {B} +do_test backup-4.2.2 { + catchsql { DETACH aux2 } db2 +} {1 {database aux2 is locked}} +do_test backup-4.2.3 { + B step 50 +} {SQLITE_DONE} +do_test backup-4.2.4 { + B finish +} {SQLITE_OK} + +do_test backup-4.3.1 { + sqlite3_backup B db aux1 db2 aux2 +} {B} +do_test backup-4.3.2 { + db2 cache flush + sqlite3_close db2 +} {SQLITE_BUSY} +do_test backup-4.3.3 { + sqlite3_errmsg db2 +} {unable to close due to unfinalized statements or unfinished backups} +do_test backup-4.3.4 { + B step 50 +} {SQLITE_DONE} +do_test backup-4.3.5 { + B finish +} {SQLITE_OK} + +do_test backup-4.4.1 { + set rc [catch {sqlite3_backup B db main db aux1}] + list $rc [sqlite3_errcode db] [sqlite3_errmsg db] +} {1 SQLITE_ERROR {source and destination must be distinct}} +db close +db2 close + +do_test backup-4.5.1 { + catch { forcedelete test.db } + sqlite3 db test.db + sqlite3 db2 :memory: + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } + execsql { + PRAGMA page_size = 4096; + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES(3, 4); + } db2 + sqlite3_backup B db2 main db main +} {B} +do_test backup-4.5.2 { + B step 5000 +} {SQLITE_READONLY} +do_test backup-4.5.3 { + B finish +} {SQLITE_READONLY} + +db close +db2 close +# +# End of backup-4.* tests. +#--------------------------------------------------------------------- + +#--------------------------------------------------------------------- +# The following tests, backup-5.*, test that the backup works properly +# when the source database is modified during the backup. Test cases +# are organized as follows: +# +# backup-5.x.1.*: Nothing special. Modify the database mid-backup. +# +# backup-5.x.2.*: Modify the database mid-backup so that one or more +# pages are written out due to cache stress. Then +# rollback the transaction. +# +# backup-5.x.3.*: Database is vacuumed. +# +# backup-5.x.4.*: Database is vacuumed and the page-size modified. +# +# backup-5.x.5.*: Database is shrunk via incr-vacuum. +# +# Each test is run three times, in the following configurations: +# +# 1) Backing up file-to-file. The writer writes via an external pager. +# 2) Backing up file-to-file. The writer writes via the same pager as +# is used by the backup operation. +# 3) Backing up memory-to-file. +# +set iTest 0 +forcedelete bak.db-wal +foreach {writer file} {db test.db db3 test.db db :memory:} { + incr iTest + catch { delete_file bak.db } + sqlite3 db2 bak.db + catch { delete_file $file } + sqlite3 db $file + sqlite3 db3 $file + + do_test backup-5.$iTest.1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 VALUES(2, randstr(1000,1000)); + INSERT INTO t1 VALUES(3, randstr(1000,1000)); + INSERT INTO t1 VALUES(4, randstr(1000,1000)); + INSERT INTO t1 VALUES(5, randstr(1000,1000)); + COMMIT; + } + expr {[execsql {PRAGMA page_count}] > 10} + } {1} + do_test backup-5.$iTest.1.2 { + sqlite3_backup B db2 main db main + B step 5 + } {SQLITE_OK} + do_test backup-5.$iTest.1.3 { + execsql { UPDATE t1 SET a = a + 1 } $writer + B step 50 + } {SQLITE_DONE} + do_test backup-5.$iTest.1.4 { + B finish + } {SQLITE_OK} + integrity_check backup-5.$iTest.1.5 db2 + test_contents backup-5.$iTest.1.6 db main db2 main + + do_test backup-5.$iTest.2.1 { + execsql { + PRAGMA cache_size = 10; + BEGIN; + INSERT INTO t1 SELECT '', randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT '', randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT '', randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT '', randstr(1000,1000) FROM t1; + COMMIT; + } + } {} + do_test backup-5.$iTest.2.2 { + sqlite3_backup B db2 main db main + B step 50 + } {SQLITE_OK} + do_test backup-5.$iTest.2.3 { + execsql { + BEGIN; + UPDATE t1 SET a = a + 1; + ROLLBACK; + } $writer + B step 5000 + } {SQLITE_DONE} + do_test backup-5.$iTest.2.4 { + B finish + } {SQLITE_OK} + integrity_check backup-5.$iTest.2.5 db2 + test_contents backup-5.$iTest.2.6 db main db2 main + + do_test backup-5.$iTest.3.1 { + execsql { UPDATE t1 SET b = randstr(1000,1000) } + } {} + do_test backup-5.$iTest.3.2 { + sqlite3_backup B db2 main db main + B step 50 + } {SQLITE_OK} + do_test backup-5.$iTest.3.3 { + execsql { VACUUM } $writer + B step 5000 + } {SQLITE_DONE} + do_test backup-5.$iTest.3.4 { + B finish + } {SQLITE_OK} + integrity_check backup-5.$iTest.3.5 db2 + test_contents backup-5.$iTest.3.6 db main db2 main + + do_test backup-5.$iTest.4.1 { + execsql { UPDATE t1 SET b = randstr(1000,1000) } + } {} + do_test backup-5.$iTest.4.2 { + sqlite3_backup B db2 main db main + B step 50 + } {SQLITE_OK} + do_test backup-5.$iTest.4.3 { + execsql { + PRAGMA page_size = 2048; + VACUUM; + } $writer + B step 5000 + } {SQLITE_DONE} + do_test backup-5.$iTest.4.4 { + B finish + } {SQLITE_OK} + integrity_check backup-5.$iTest.4.5 db2 + test_contents backup-5.$iTest.4.6 db main db2 main + + catch {db close} + catch {db2 close} + catch {db3 close} + catch { delete_file bak.db } + sqlite3 db2 bak.db + catch { delete_file $file } + sqlite3 db $file + sqlite3 db3 $file + do_test backup-5.$iTest.5.1 { + execsql { + PRAGMA auto_vacuum = incremental; + BEGIN; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 VALUES(2, randstr(1000,1000)); + INSERT INTO t1 VALUES(3, randstr(1000,1000)); + INSERT INTO t1 VALUES(4, randstr(1000,1000)); + INSERT INTO t1 VALUES(5, randstr(1000,1000)); + COMMIT; + } + } {} + do_test backup-5.$iTest.5.2 { + sqlite3_backup B db2 main db main + B step 8 + } {SQLITE_OK} + do_test backup-5.$iTest.5.3 { + execsql { + DELETE FROM t1; + PRAGMA incremental_vacuum; + } $writer + B step 50 + } {SQLITE_DONE} + do_test backup-5.$iTest.5.4 { + B finish + } {SQLITE_OK} + integrity_check backup-5.$iTest.5.5 db2 + test_contents backup-5.$iTest.5.6 db main db2 main + catch {db close} + catch {db2 close} + catch {db3 close} +} +# +# End of backup-5.* tests. +#--------------------------------------------------------------------- + +#--------------------------------------------------------------------- +# Test the sqlite3_backup_remaining() and backup_pagecount() APIs. +# +do_test backup-6.1 { + catch { forcedelete test.db } + catch { forcedelete test2.db } + sqlite3 db test.db + sqlite3 db2 test2.db + execsql { + BEGIN; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 VALUES(2, randstr(1000,1000)); + INSERT INTO t1 VALUES(3, randstr(1000,1000)); + INSERT INTO t1 VALUES(4, randstr(1000,1000)); + INSERT INTO t1 VALUES(5, randstr(1000,1000)); + COMMIT; + } +} {} +do_test backup-6.2 { + set nTotal [expr {[file size test.db]/1024}] + sqlite3_backup B db2 main db main + B step 1 +} {SQLITE_OK} +do_test backup-6.3 { + B pagecount +} $nTotal +do_test backup-6.4 { + B remaining +} [expr $nTotal-1] +do_test backup-6.5 { + B step 5 + list [B remaining] [B pagecount] +} [list [expr $nTotal-6] $nTotal] +do_test backup-6.6 { + execsql { CREATE TABLE t2(a PRIMARY KEY, b) } + B step 1 + list [B remaining] [B pagecount] +} [list [expr $nTotal-5] [expr $nTotal+2]] + +do_test backup-6.X { + B finish +} {SQLITE_OK} + +catch {db close} +catch {db2 close} + +#--------------------------------------------------------------------- +# Test cases backup-7.* test that SQLITE_BUSY and SQLITE_LOCKED errors +# are returned correctly: +# +# backup-7.1.*: Source database is externally locked (return SQLITE_BUSY). +# +# backup-7.2.*: Attempt to step the backup process while a +# write-transaction is underway on the source pager (return +# SQLITE_LOCKED). +# +# backup-7.3.*: Destination database is externally locked (return SQLITE_BUSY). +# +do_test backup-7.0 { + catch { forcedelete test.db } + catch { forcedelete test2.db } + sqlite3 db2 test2.db + sqlite3 db test.db + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 SELECT a+ 1, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+ 2, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+ 4, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+ 8, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+16, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+32, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+64, randstr(1000,1000) FROM t1; + } +} {} + +do_test backup-7.1.1 { + sqlite3_backup B db2 main db main + B step 5 +} {SQLITE_OK} +do_test backup-7.1.2 { + sqlite3 db3 test.db + execsql { BEGIN EXCLUSIVE } db3 + B step 5 +} {SQLITE_BUSY} +do_test backup-7.1.3 { + execsql { ROLLBACK } db3 + B step 5 +} {SQLITE_OK} +do_test backup-7.2.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(1, 4); + } +} {} +do_test backup-7.2.2 { + B step 5000 +} {SQLITE_BUSY} +do_test backup-7.2.3 { + execsql { ROLLBACK } + B step 5000 +} {SQLITE_DONE} +do_test backup-7.2.4 { + B finish +} {SQLITE_OK} +test_contents backup-7.2.5 db main db2 main +integrity_check backup-7.3.6 db2 + +do_test backup-7.3.1 { + db2 close + db3 close + forcedelete test2.db + sqlite3 db2 test2.db + sqlite3 db3 test2.db + + sqlite3_backup B db2 main db main + execsql { BEGIN ; CREATE TABLE t2(a, b); } db3 + + B step 5 +} {SQLITE_BUSY} +do_test backup-7.3.2 { + execsql { COMMIT } db3 + B step 5000 +} {SQLITE_DONE} +do_test backup-7.3.3 { + B finish +} {SQLITE_OK} +test_contents backup-7.3.4 db main db2 main +integrity_check backup-7.3.5 db2 +catch { db2 close } +catch { db3 close } + +#----------------------------------------------------------------------- +# The following tests, backup-8.*, test attaching multiple backup +# processes to the same source database. Also, reading from the source +# database while a read transaction is active. +# +# These tests reuse the database "test.db" left over from backup-7.*. +# +do_test backup-8.1 { + catch { forcedelete test2.db } + catch { forcedelete test3.db } + sqlite3 db2 test2.db + sqlite3 db3 test3.db + + sqlite3_backup B2 db2 main db main + sqlite3_backup B3 db3 main db main + list [B2 finish] [B3 finish] +} {SQLITE_OK SQLITE_OK} +do_test backup-8.2 { + sqlite3_backup B3 db3 main db main + sqlite3_backup B2 db2 main db main + list [B2 finish] [B3 finish] +} {SQLITE_OK SQLITE_OK} +do_test backup-8.3 { + sqlite3_backup B2 db2 main db main + sqlite3_backup B3 db3 main db main + B2 step 5 +} {SQLITE_OK} +do_test backup-8.4 { + execsql { + BEGIN; + SELECT * FROM sqlite_master; + } + B3 step 5 +} {SQLITE_OK} +do_test backup-8.5 { + list [B3 step 5000] [B3 finish] +} {SQLITE_DONE SQLITE_OK} +do_test backup-8.6 { + list [B2 step 5000] [B2 finish] +} {SQLITE_DONE SQLITE_OK} +test_contents backup-8.7 db main db2 main +test_contents backup-8.8 db main db3 main +do_test backup-8.9 { + execsql { PRAGMA lock_status } +} {main shared temp closed} +do_test backup-8.10 { + execsql COMMIT +} {} +catch { db2 close } +catch { db3 close } + +#----------------------------------------------------------------------- +# The following tests, backup-9.*, test that: +# +# * Passing 0 as an argument to sqlite3_backup_step() means no pages +# are backed up (backup-9.1.*), and +# * Passing a negative value as an argument to sqlite3_backup_step() means +# all pages are backed up (backup-9.2.*). +# +# These tests reuse the database "test.db" left over from backup-7.*. +# +do_test backup-9.1.1 { + sqlite3 db2 test2.db + sqlite3_backup B db2 main db main + B step 1 +} {SQLITE_OK} +do_test backup-9.1.2 { + set nRemaining [B remaining] + expr {$nRemaining>100} +} {1} +do_test backup-9.1.3 { + B step 0 +} {SQLITE_OK} +do_test backup-9.1.4 { + B remaining +} $nRemaining + +do_test backup-9.2.1 { + B step -1 +} {SQLITE_DONE} +do_test backup-9.2.2 { + B remaining +} {0} +do_test backup-9.2.3 { + B finish +} {SQLITE_OK} +catch {db2 close} + +ifcapable memorymanage { + db close + forcedelete test.db + forcedelete bak.db + + sqlite3 db test.db + sqlite3 db2 test.db + sqlite3 db3 bak.db + + do_test backup-10.1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 VALUES(2, randstr(1000,1000)); + INSERT INTO t1 VALUES(3, randstr(1000,1000)); + INSERT INTO t1 VALUES(4, randstr(1000,1000)); + INSERT INTO t1 VALUES(5, randstr(1000,1000)); + CREATE INDEX i1 ON t1(a, b); + COMMIT; + } + } {} + do_test backup-10.1.2 { + sqlite3_backup B db3 main db2 main + B step 5 + } {SQLITE_OK} + do_test backup-10.1.3 { + execsql { + UPDATE t1 SET b = randstr(500,500); + } + } {} + sqlite3_release_memory [expr 1024*1024] + do_test backup-10.1.3 { + B step 50 + } {SQLITE_DONE} + do_test backup-10.1.4 { + B finish + } {SQLITE_OK} + do_test backup-10.1.5 { + execsql { PRAGMA integrity_check } db3 + } {ok} + + db2 close + db3 close +} + + +#----------------------------------------------------------------------- +# Test that if the database is written to via the same database handle being +# used as the source by a backup operation: +# +# 10.1.*: If the db is in-memory, the backup is restarted. +# 10.2.*: If the db is a file, the backup is not restarted. +# +db close +forcedelete test.db test.db-journal +foreach {tn file rc} { + 1 test.db SQLITE_DONE + 2 :memory: SQLITE_OK +} { + do_test backup-10.$tn.1 { + sqlite3 db $file + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b BLOB); + BEGIN; + INSERT INTO t1 VALUES(NULL, randomblob(200)); + INSERT INTO t1 SELECT NULL, randomblob(200) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(200) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(200) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(200) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(200) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(200) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(200) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(200) FROM t1; + COMMIT; + SELECT count(*) FROM t1; + } + } {256} + + do_test backup-10.$tn.2 { + set pgs [execsql {pragma page_count}] + expr {$pgs > 50 && $pgs < 75} + } {1} + + do_test backup-10.$tn.3 { + forcedelete bak.db bak.db-journal + sqlite3 db2 bak.db + sqlite3_backup B db2 main db main + B step 50 + } {SQLITE_OK} + + do_test backup-10.$tn.4 { + execsql { UPDATE t1 SET b = randomblob(200) WHERE a IN (1, 250) } + } {} + + do_test backup-10.$tn.5 { + B step 50 + } $rc + + do_test backup-10.$tn.6 { + B finish + } {SQLITE_OK} + + db2 close +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/backup2.test b/components/external/SQLite-3.8.1/test/backup2.test new file mode 100644 index 0000000000000000000000000000000000000000..989319923a9a517f6854123c2cc3489c12ad1b9f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/backup2.test @@ -0,0 +1,186 @@ +# 2009 February 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the "backup" and "restore" methods +# of the TCL interface - methods which are based on the +# sqlite3_backup_XXX API. +# +# $Id: backup2.test,v 1.4 2009/04/07 14:14:23 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_not_use_codec + +ifcapable !trigger||!view { finish_test ; return } + +# Fill a database with test data. +# +do_test backup2-1 { + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randstr(8000,8000)); + INSERT INTO t1 VALUES(randstr(8000,8000)); + INSERT INTO t1 VALUES(randstr(8000,8000)); + INSERT INTO t1 VALUES(randstr(8000,8000)); + INSERT INTO t1 VALUES(randstr(8000,8000)); + CREATE VIEW v1 AS SELECT substr(x,10,10) FROM t1; + CREATE TABLE t2(a,b); + INSERT INTO t2 VALUES(1,2); + INSERT INTO t2 VALUES(2,4); + INSERT INTO t2 SELECT a+2, (a+2)*2 FROM t2; + INSERT INTO t2 SELECT a+4, (a+4)*2 FROM t2; + INSERT INTO t2 SELECT a+8, (a+8)*2 FROM t2; + INSERT INTO t2 SELECT a+16, (a+16)*2 FROM t2; + INSERT INTO t2 SELECT a+32, (a+32)*2 FROM t2; + INSERT INTO t2 SELECT a+64, (a+64)*2 FROM t2; + INSERT INTO t2 SELECT a+128, (a+128)*2 FROM t2; + CREATE INDEX t2i1 ON t2(a,b); + CREATE TRIGGER r1 AFTER INSERT ON t2 BEGIN + SELECT 'hello'; + END; + ANALYZE; + PRAGMA integrity_check; + } +} {ok} + +# Remember a check-sum on the database file. +# +unset -nocomplain cksum +set cksum [dbcksum db main] + +# Make a backup of the test data. Verify that the backup copy +# is identical to the original. +# +do_test backup2-2 { + forcedelete bu1.db + db backup bu1.db + sqlite3 db2 bu1.db + dbcksum db2 main +} $cksum + +# Delete the original. Restore from backup. Verify the content is +# unchanged. +# +do_test backup2-3.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + db2 eval {BEGIN EXCLUSIVE} + set rc [catch {db restore bu1.db} res] + lappend rc $res + db2 eval {ROLLBACK} + set rc +} {1 {restore failed: source database busy}} +do_test backup2-3.2 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + db restore bu1.db + dbcksum db main +} $cksum + +# Use alternative databases - other than "main". +# +do_test backup2-4 { + db restore temp bu1.db + dbcksum db temp +} $cksum +do_test backup2-5 { + db2 close + forcedelete bu1.db bu2.db + db backup temp bu2.db + sqlite3 db2 bu2.db + dbcksum db2 main +} $cksum + +# Try to backup to a readonly file. +# +do_test backup2-6 { + db2 close + catch {file attributes bu2.db -permissions r--------} + catch {file attributes bu2.db -readonly 1} + set rc [catch {db backup temp bu2.db} res] + lappend rc $res +} {1 {backup failed: attempt to write a readonly database}} + +# Try to backup to something that is not a database file. +# +do_test backup2-7 { + catch {file attributes bu2.db -readonly 0} + catch {file attributes bu2.db -permissions rw-------} + set out [open bu2.db w] + puts $out "This is not a valid database file" + close $out + set rc [catch {db backup temp bu2.db} res] + lappend rc $res +} {1 {backup failed: file is encrypted or is not a database}} + +# Try to backup database that does not exist +# +do_test backup2-8 { + forcedelete bu1.db + set rc [catch {db backup aux1 bu1.db} res] + lappend rc $res +} {1 {backup failed: unknown database aux1}} + +# Invalid syntax on the backup method +# +do_test backup2-9 { + set rc [catch {db backup} res] + lappend rc $res +} {1 {wrong # args: should be "db backup ?DATABASE? FILENAME"}} + +# Try to restore from an unreadable file. +# +if {$tcl_platform(platform)=="windows"} { + set msg {cannot open source database: unable to open database file} +} elseif {$tcl_platform(os)=="OpenBSD"} { + set msg {restore failed: file is encrypted or is not a database} +} else { + set msg {cannot open source database: disk I/O error} +} +do_test backup2-10 { + forcedelete bu3.db + file mkdir bu3.db + set rc [catch {db restore temp bu3.db} res] + lappend rc $res +} [list 1 $msg] + +# Try to restore from something that is not a database file. +# +do_test backup2-11 { + set rc [catch {db restore temp bu2.db} res] + lappend rc $res +} {1 {restore failed: file is encrypted or is not a database}} + +# Try to restore a database that does not exist +# +do_test backup2-12 { + set rc [catch {db restore aux1 bu2.db} res] + lappend rc $res +} {1 {restore failed: unknown database aux1}} +do_test backup2-13 { + forcedelete bu4.db + set rc [catch {db restore bu4.db} res] + lappend rc $res +} {1 {cannot open source database: unable to open database file}} + +# Invalid syntax on the restore method +# +do_test backup2-14 { + set rc [catch {db restore} res] + lappend rc $res +} {1 {wrong # args: should be "db restore ?DATABASE? FILENAME"}} + +forcedelete bu1.db bu2.db bu3.db bu4.db + +finish_test diff --git a/components/external/SQLite-3.8.1/test/backup4.test b/components/external/SQLite-3.8.1/test/backup4.test new file mode 100644 index 0000000000000000000000000000000000000000..417df80e552d502728dc719e0e72d6ea3c01cadb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/backup4.test @@ -0,0 +1,103 @@ +# 2012 October 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The tests in this file verify that if an empty database (zero bytes in +# size) is used as the source of a backup operation, the final destination +# database is one page in size. +# +# The destination must consist of at least one page as truncating a +# database file to zero bytes is equivalent to resetting the database +# schema cookie and change counter. Doing that could cause other clients +# to become confused and continue using out-of-date cache data. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix backup4 + +#------------------------------------------------------------------------- +# At one point this test was failing because [db] was using an out of +# date schema in test case 1.2. +# +do_execsql_test 1.0 { + CREATE TABLE t1(x, y, UNIQUE(x, y)); + INSERT INTO t1 VALUES('one', 'two'); + SELECT * FROM t1 WHERE x='one'; + PRAGMA integrity_check; +} {one two ok} + +do_test 1.1 { + sqlite3 db1 :memory: + db1 backup test.db + sqlite3 db1 test.db + db1 eval { + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES('one', 'two'); + } + db1 close +} {} + +do_execsql_test 1.2 { + SELECT * FROM t1 WHERE x='one'; + PRAGMA integrity_check; +} {one two ok} + +db close +forcedelete test.db +forcedelete test.db2 +sqlite3 db test.db + +#------------------------------------------------------------------------- +# Test that if the source is zero bytes, the destination database +# consists of a single page only. +# +do_execsql_test 2.1 { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); +} +do_test 2.2 { file size test.db } [expr $AUTOVACUUM ? 4096 : 3072] + +do_test 2.3 { + sqlite3 db1 test.db2 + db1 backup test.db + db1 close + file size test.db +} {1024} + +do_test 2.4 { file size test.db2 } 0 + +db close +forcedelete test.db +forcedelete test.db2 +sqlite3 db test.db + +#------------------------------------------------------------------------- +# Test that if the destination has a page-size larger than the implicit +# page-size of the source, the final destination database still consists +# of a single page. +# +do_execsql_test 3.1 { + PRAGMA page_size = 4096; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); +} +do_test 3.2 { file size test.db } [expr $AUTOVACUUM ? 16384 : 12288] + +do_test 3.3 { + sqlite3 db1 test.db2 + db1 backup test.db + db1 close + file size test.db +} {1024} + +do_test 3.4 { file size test.db2 } 0 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/backup_ioerr.test b/components/external/SQLite-3.8.1/test/backup_ioerr.test new file mode 100644 index 0000000000000000000000000000000000000000..ca3fd3240d778d1b6fd19b59a66ffcf7a66b9f78 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/backup_ioerr.test @@ -0,0 +1,286 @@ +# 2009 January 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the handling of IO errors by the +# sqlite3_backup_XXX APIs. +# +# $Id: backup_ioerr.test,v 1.3 2009/04/10 18:41:01 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc data_checksum {db file} { + $db one "SELECT md5sum(a, b) FROM ${file}.t1" +} +proc test_contents {name db1 file1 db2 file2} { + $db2 eval {select * from sqlite_master} + $db1 eval {select * from sqlite_master} + set checksum [data_checksum $db2 $file2] + uplevel [list do_test $name [list data_checksum $db1 $file1] $checksum] +} + +#-------------------------------------------------------------------- +# This proc creates a database of approximately 290 pages. Depending +# on whether or not auto-vacuum is configured. Test cases backup_ioerr-1.* +# verify nothing more than this assumption. +# +proc populate_database {db {xtra_large 0}} { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 SELECT a+ 1, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+ 2, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+ 4, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+ 8, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+16, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+32, randstr(1000,1000) FROM t1; + CREATE INDEX i1 ON t1(b); + COMMIT; + } $db + if {$xtra_large} { + execsql { INSERT INTO t1 SELECT a+64, randstr(1000,1000) FROM t1 } $db + } +} +do_test backup_ioerr-1.1 { + populate_database db + set nPage [expr {[file size test.db] / 1024}] + expr {$nPage>130 && $nPage<160} +} {1} +do_test backup_ioerr-1.2 { + expr {[file size test.db] > $sqlite_pending_byte} +} {1} +do_test backup_ioerr-1.3 { + db close + forcedelete test.db +} {} + +# Turn off IO error simulation. +# +proc clear_ioerr_simulation {} { + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_hardhit 0 + set ::sqlite_io_error_pending 0 + set ::sqlite_io_error_persist 0 +} + +#-------------------------------------------------------------------- +# The following procedure runs with SQLite's IO error simulation +# enabled. +# +# 1) Start with a reasonably sized database. One that includes the +# pending-byte (locking) page. +# +# 2) Open a backup process. Set the cache-size for the destination +# database to 10 pages only. +# +# 3) Step the backup process N times to partially backup the database +# file. If an IO error is reported, then the backup process is +# concluded with a call to backup_finish(). +# +# If an IO error occurs, verify that: +# +# * the call to backup_step() returns an SQLITE_IOERR_XXX error code. +# +# * after the failed call to backup_step() but before the call to +# backup_finish() the destination database handle error code and +# error message remain unchanged. +# +# * the call to backup_finish() returns an SQLITE_IOERR_XXX error code. +# +# * following the call to backup_finish(), the destination database +# handle has been populated with an error code and error message. +# +# 4) Write to the database via the source database connection. Check +# that: +# +# * If an IO error occurs while writing the source database, the +# write operation should report an IO error. The backup should +# proceed as normal. +# +# * If an IO error occurs while updating the backup, the write +# operation should proceed normally. The error should be reported +# from the next call to backup_step() (in step 5 of this test +# procedure). +# +# 5) Step the backup process to finish the backup. If an IO error is +# reported, then the backup process is concluded with a call to +# backup_finish(). +# +# Test that if an IO error occurs, or if one occurred while updating +# the backup database during step 4, then the conditions listed +# under step 3 are all true. +# +# 6) Finish the backup process. +# +# * If the backup succeeds (backup_finish() returns SQLITE_OK), then +# the contents of the backup database should match that of the +# source database. +# +# * If the backup fails (backup_finish() returns other than SQLITE_OK), +# then the contents of the backup database should be as they were +# before the operation was started. +# +# The following factors are varied: +# +# * Destination database is initially larger than the source database, OR +# * Destination database is initially smaller than the source database. +# +# * IO errors are transient, OR +# * IO errors are persistent. +# +# * Destination page-size is smaller than the source. +# * Destination page-size is the same as the source. +# * Destination page-size is larger than the source. +# + +set iTest 1 +foreach bPersist {0 1} { +foreach iDestPagesize {512 1024 4096} { +foreach zSetupBak [list "" {populate_database ddb 1}] { + + incr iTest + set bStop 0 +for {set iError 1} {$bStop == 0} {incr iError} { + # Disable IO error simulation. + clear_ioerr_simulation + + catch { ddb close } + catch { sdb close } + catch { forcedelete test.db } + catch { forcedelete bak.db } + + # Open the source and destination databases. + sqlite3 sdb test.db + sqlite3 ddb bak.db + + # Step 1: Populate the source and destination databases. + populate_database sdb + ddb eval "PRAGMA page_size = $iDestPagesize" + ddb eval "PRAGMA cache_size = 10" + eval $zSetupBak + + # Step 2: Open the backup process. + sqlite3_backup B ddb main sdb main + + # Enable IO error simulation. + set ::sqlite_io_error_pending $iError + set ::sqlite_io_error_persist $bPersist + + # Step 3: Partially backup the database. If an IO error occurs, check + # a few things then skip to the next iteration of the loop. + # + set rc [B step 100] + if {$::sqlite_io_error_hardhit} { + + do_test backup_ioerr-$iTest.$iError.1 { + string match SQLITE_IOERR* $rc + } {1} + do_test backup_ioerr-$iTest.$iError.2 { + list [sqlite3_errcode ddb] [sqlite3_errmsg ddb] + } {SQLITE_OK {not an error}} + + set rc [B finish] + do_test backup_ioerr-$iTest.$iError.3 { + string match SQLITE_IOERR* $rc + } {1} + + do_test backup_ioerr-$iTest.$iError.4 { + sqlite3_errmsg ddb + } {disk I/O error} + + clear_ioerr_simulation + sqlite3 ddb bak.db + integrity_check backup_ioerr-$iTest.$iError.5 ddb + + continue + } + + # No IO error was encountered during step 3. Check that backup_step() + # returned SQLITE_OK before proceding. + do_test backup_ioerr-$iTest.$iError.6 { + expr {$rc eq "SQLITE_OK"} + } {1} + + # Step 4: Write to the source database. + set rc [catchsql { UPDATE t1 SET b = randstr(1000,1000) WHERE a < 50 } sdb] + + if {[lindex $rc 0] && $::sqlite_io_error_persist==0} { + # The IO error occurred while updating the source database. In this + # case the backup should be able to continue. + set rc [B step 5000] + if { $rc != "SQLITE_IOERR_UNLOCK" } { + do_test backup_ioerr-$iTest.$iError.7 { + list [B step 5000] [B finish] + } {SQLITE_DONE SQLITE_OK} + + clear_ioerr_simulation + test_contents backup_ioerr-$iTest.$iError.8 ddb main sdb main + integrity_check backup_ioerr-$iTest.$iError.9 ddb + } else { + do_test backup_ioerr-$iTest.$iError.10 { + B finish + } {SQLITE_IOERR_UNLOCK} + } + + clear_ioerr_simulation + sqlite3 ddb bak.db + integrity_check backup_ioerr-$iTest.$iError.11 ddb + + continue + } + + # Step 5: Finish the backup operation. If an IO error occurs, check that + # it is reported correctly and skip to the next iteration of the loop. + # + set rc [B step 5000] + if {$rc != "SQLITE_DONE"} { + do_test backup_ioerr-$iTest.$iError.12 { + string match SQLITE_IOERR* $rc + } {1} + do_test backup_ioerr-$iTest.$iError.13 { + list [sqlite3_errcode ddb] [sqlite3_errmsg ddb] + } {SQLITE_OK {not an error}} + + set rc [B finish] + do_test backup_ioerr-$iTest.$iError.14 { + string match SQLITE_IOERR* $rc + } {1} + do_test backup_ioerr-$iTest.$iError.15 { + sqlite3_errmsg ddb + } {disk I/O error} + + clear_ioerr_simulation + sqlite3 ddb bak.db + integrity_check backup_ioerr-$iTest.$iError.16 ddb + + continue + } + + # The backup was successfully completed. + # + do_test backup_ioerr-$iTest.$iError.17 { + list [set rc] [B finish] + } {SQLITE_DONE SQLITE_OK} + + clear_ioerr_simulation + sqlite3 sdb test.db + sqlite3 ddb bak.db + + test_contents backup_ioerr-$iTest.$iError.18 ddb main sdb main + integrity_check backup_ioerr-$iTest.$iError.19 ddb + + set bStop [expr $::sqlite_io_error_pending<=0] +}}}} + +catch { sdb close } +catch { ddb close } +finish_test diff --git a/components/external/SQLite-3.8.1/test/backup_malloc.test b/components/external/SQLite-3.8.1/test/backup_malloc.test new file mode 100644 index 0000000000000000000000000000000000000000..f556861fb199845123dd1a0562cacf24cb183039 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/backup_malloc.test @@ -0,0 +1,87 @@ +# 2009 January 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the handling of OOM errors by the +# sqlite3_backup_XXX APIs. +# +# $Id: backup_malloc.test,v 1.2 2009/02/04 22:46:47 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +source $testdir/malloc_common.tcl + +do_malloc_test backup_malloc-1 -tclprep { + execsql { + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 SELECT a+ 1, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+ 2, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+ 4, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+ 8, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+16, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+32, randstr(1000,1000) FROM t1; + INSERT INTO t1 SELECT a+64, randstr(1000,1000) FROM t1; + CREATE INDEX i1 ON t1(b); + COMMIT; + } + sqlite3 db2 test2.db + execsql { PRAGMA cache_size = 10 } db2 +} -tclbody { + + # Create a backup object. + # + set rc [catch {sqlite3_backup B db2 main db main}] + if {$rc && [sqlite3_errcode db2] == "SQLITE_NOMEM"} { + error "out of memory" + } + + # Run the backup process some. + # + set rc [B step 50] + if {$rc == "SQLITE_NOMEM" || $rc == "SQLITE_IOERR_NOMEM"} { + error "out of memory" + } + + # Update the database. + # + execsql { UPDATE t1 SET a = a + 1 } + + # Finish doing the backup. + # + set rc [B step 5000] + if {$rc == "SQLITE_NOMEM" || $rc == "SQLITE_IOERR_NOMEM"} { + error "out of memory" + } + + # Finalize the backup. + B finish +} -cleanup { + catch { B finish } + catch { db2 close } +} + +do_malloc_test backup_malloc-2 -tclprep { + sqlite3 db2 test2.db +} -tclbody { + set rc [catch {sqlite3_backup B db2 temp db main}] + set errcode [sqlite3_errcode db2] + if {$rc && ($errcode == "SQLITE_NOMEM" || $errcode == "SQLITE_IOERR_NOMEM")} { + error "out of memory" + } +} -cleanup { + catch { B finish } + db2 close +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/badutf.test b/components/external/SQLite-3.8.1/test/badutf.test new file mode 100644 index 0000000000000000000000000000000000000000..d09c933c1810dbd55486fef6b4e92d53522ac0a0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/badutf.test @@ -0,0 +1,143 @@ +# 2007 May 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file checks to make sure SQLite is able to gracefully +# handle malformed UTF-8. +# +# $Id: badutf.test,v 1.2 2007/09/12 17:01:45 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test badutf-1.1 { + db eval {PRAGMA encoding=UTF8} + sqlite3_exec db {SELECT hex('%80') AS x} +} {0 {x 80}} +do_test badutf-1.2 { + sqlite3_exec db {SELECT hex('%81') AS x} +} {0 {x 81}} +do_test badutf-1.3 { + sqlite3_exec db {SELECT hex('%bf') AS x} +} {0 {x BF}} +do_test badutf-1.4 { + sqlite3_exec db {SELECT hex('%c0') AS x} +} {0 {x C0}} +do_test badutf-1.5 { + sqlite3_exec db {SELECT hex('%e0') AS x} +} {0 {x E0}} +do_test badutf-1.6 { + sqlite3_exec db {SELECT hex('%f0') AS x} +} {0 {x F0}} +do_test badutf-1.7 { + sqlite3_exec db {SELECT hex('%ff') AS x} +} {0 {x FF}} + +sqlite3 db2 {} +ifcapable utf16 { + do_test badutf-1.10 { + db2 eval {PRAGMA encoding=UTF16be} + sqlite3_exec db2 {SELECT hex('%80') AS x} + } {0 {x 0080}} + do_test badutf-1.11 { + sqlite3_exec db2 {SELECT hex('%81') AS x} + } {0 {x 0081}} + do_test badutf-1.12 { + sqlite3_exec db2 {SELECT hex('%bf') AS x} + } {0 {x 00BF}} + do_test badutf-1.13 { + sqlite3_exec db2 {SELECT hex('%c0') AS x} + } {0 {x FFFD}} + do_test badutf-1.14 { + sqlite3_exec db2 {SELECT hex('%c1') AS x} + } {0 {x FFFD}} + do_test badutf-1.15 { + sqlite3_exec db2 {SELECT hex('%c0%bf') AS x} + } {0 {x FFFD}} + do_test badutf-1.16 { + sqlite3_exec db2 {SELECT hex('%c1%bf') AS x} + } {0 {x FFFD}} + do_test badutf-1.17 { + sqlite3_exec db2 {SELECT hex('%c3%bf') AS x} + } {0 {x 00FF}} + do_test badutf-1.18 { + sqlite3_exec db2 {SELECT hex('%e0') AS x} + } {0 {x FFFD}} + do_test badutf-1.19 { + sqlite3_exec db2 {SELECT hex('%f0') AS x} + } {0 {x FFFD}} + do_test badutf-1.20 { + sqlite3_exec db2 {SELECT hex('%ff') AS x} + } {0 {x FFFD}} +} + + +ifcapable bloblit { + do_test badutf-2.1 { + sqlite3_exec db {SELECT '%80'=CAST(x'80' AS text) AS x} + } {0 {x 1}} + do_test badutf-2.2 { + sqlite3_exec db {SELECT CAST('%80' AS blob)=x'80' AS x} + } {0 {x 1}} +} + +do_test badutf-3.1 { + sqlite3_exec db {SELECT length('%80') AS x} +} {0 {x 1}} +do_test badutf-3.2 { + sqlite3_exec db {SELECT length('%61%62%63') AS x} +} {0 {x 3}} +do_test badutf-3.3 { + sqlite3_exec db {SELECT length('%7f%80%81') AS x} +} {0 {x 3}} +do_test badutf-3.4 { + sqlite3_exec db {SELECT length('%61%c0') AS x} +} {0 {x 2}} +do_test badutf-3.5 { + sqlite3_exec db {SELECT length('%61%c0%80%80%80%80%80%80%80%80%80%80') AS x} +} {0 {x 2}} +do_test badutf-3.6 { + sqlite3_exec db {SELECT length('%c0%80%80%80%80%80%80%80%80%80%80') AS x} +} {0 {x 1}} +do_test badutf-3.7 { + sqlite3_exec db {SELECT length('%80%80%80%80%80%80%80%80%80%80') AS x} +} {0 {x 10}} +do_test badutf-3.8 { + sqlite3_exec db {SELECT length('%80%80%80%80%80%f0%80%80%80%80') AS x} +} {0 {x 6}} +do_test badutf-3.9 { + sqlite3_exec db {SELECT length('%80%80%80%80%80%f0%80%80%80%ff') AS x} +} {0 {x 7}} + +do_test badutf-4.1 { + sqlite3_exec db {SELECT hex(trim('%80%80%80%f0%80%80%80%ff','%80%ff')) AS x} +} {0 {x F0}} +do_test badutf-4.2 { + sqlite3_exec db {SELECT hex(ltrim('%80%80%80%f0%80%80%80%ff','%80%ff')) AS x} +} {0 {x F0808080FF}} +do_test badutf-4.3 { + sqlite3_exec db {SELECT hex(rtrim('%80%80%80%f0%80%80%80%ff','%80%ff')) AS x} +} {0 {x 808080F0}} +do_test badutf-4.4 { + sqlite3_exec db {SELECT hex(trim('%80%80%80%f0%80%80%80%ff','%ff%80')) AS x} +} {0 {x 808080F0808080FF}} +do_test badutf-4.5 { + sqlite3_exec db {SELECT hex(trim('%ff%80%80%f0%80%80%80%ff','%ff%80')) AS x} +} {0 {x 80F0808080FF}} +do_test badutf-4.6 { + sqlite3_exec db {SELECT hex(trim('%ff%80%f0%80%80%80%ff','%ff%80')) AS x} +} {0 {x F0808080FF}} +do_test badutf-4.7 { + sqlite3_exec db {SELECT hex(trim('%ff%80%f0%80%80%80%ff','%ff%80%80')) AS x} +} {0 {x FF80F0808080FF}} + +db2 close +finish_test diff --git a/components/external/SQLite-3.8.1/test/badutf2.test b/components/external/SQLite-3.8.1/test/badutf2.test new file mode 100644 index 0000000000000000000000000000000000000000..36b40fb95c7427ca20d03a54ee7743ba88d4483a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/badutf2.test @@ -0,0 +1,121 @@ +# 2011 March 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file checks to make sure SQLite is able to gracEFully +# handle malformed UTF-8. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc utf8_to_ustr2 {s} { + set r "" + foreach i [split $s ""] { + scan $i %c c + append r [format \\u%04.4X $c] + } + set r +} + +proc utf8_to_hstr {in} { + regsub -all -- {(..)} $in {%[format "%s" \1]} out + subst $out +} + +proc utf8_to_xstr {in} { + regsub -all -- {(..)} $in {\\\\x[format "%s" \1]} out + subst $out +} + +proc utf8_to_ustr {in} { + regsub -all -- {(..)} $in {\\\\u[format "%04.4X" 0x\1]} out + subst $out +} + +do_test badutf2-1.0 { + db close + forcedelete test.db + sqlite3 db test.db + db eval "PRAGMA encoding = 'UTF-8'" +} {} + +do_test badutf2-4.0 { + set S [sqlite3_prepare_v2 db "SELECT ?" -1 dummy] + sqlite3_expired $S +} {0} + +foreach { i len uval xstr ustr u2u } { +1 1 00 \x00 {} {} +2 1 01 \x01 "\\u0001" 01 +3 1 3F \x3F "\\u003F" 3F +4 1 7F \x7F "\\u007F" 7F +5 1 80 \x80 "\\u0080" C280 +6 1 C3BF \xFF "\\u00FF" C3BF +7 3 EFBFBD \xEF\xBF\xBD "\\uFFFD" {} +} { + + set hstr [ utf8_to_hstr $uval ] + + ifcapable bloblit { + if {$hstr != "%00"} { + do_test badutf2-2.1.$i { + set sql "SELECT '$hstr'=CAST(x'$uval' AS text) AS x;" + set res [ sqlite3_exec db $sql ] + lindex [ lindex $res 1] 1 + } {1} + do_test badutf2-2.2.$i { + set sql "SELECT CAST('$hstr' AS blob)=x'$uval' AS x;" + set res [ sqlite3_exec db $sql ] + lindex [ lindex $res 1] 1 + } {1} + } + do_test badutf2-2.3.$i { + set sql "SELECT hex(CAST(x'$uval' AS text)) AS x;" + set res [ sqlite3_exec db $sql ] + lindex [ lindex $res 1] 1 + } $uval + do_test badutf2-2.4.$i { + set sql "SELECT hex(CAST(x'$uval' AS text)) AS x;" + set res [ sqlite3_exec db $sql ] + lindex [ lindex $res 1] 1 + } $uval + } + + if {$hstr != "%00"} { + do_test badutf2-3.1.$i { + set sql "SELECT hex('$hstr') AS x;" + set res [ sqlite3_exec db $sql ] + lindex [ lindex $res 1] 1 + } $uval + } + + do_test badutf2-4.1.$i { + sqlite3_reset $S + sqlite3_bind_text $S 1 $xstr $len + sqlite3_step $S + utf8_to_ustr2 [ sqlite3_column_text $S 0 ] + } $ustr + + ifcapable debug { + do_test badutf2-5.1.$i { + utf8_to_utf8 $uval + } $u2u + } + +} + +do_test badutf2-4.2 { + sqlite3_finalize $S +} {SQLITE_OK} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/bc_common.tcl b/components/external/SQLite-3.8.1/test/bc_common.tcl new file mode 100644 index 0000000000000000000000000000000000000000..eb9b6db9d3536ef9bbbe7d4eb7e03d2042967c3b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/bc_common.tcl @@ -0,0 +1,72 @@ + + + +proc bc_find_binaries {zCaption} { + # Search for binaries to test against. Any executable files that match + # our naming convention are assumed to be testfixture binaries to test + # against. + # + set binaries [list] + set pattern "[file tail [info nameofexec]]?*" + if {$::tcl_platform(platform)=="windows"} { + set pattern [string map {\.exe {}} $pattern] + } + foreach file [glob -nocomplain $pattern] { + if {[file executable $file] && [file isfile $file]} {lappend binaries $file} + } + + if {[llength $binaries]==0} { + puts "WARNING: No historical binaries to test against." + puts "WARNING: Omitting backwards-compatibility tests" + } + + foreach bin $binaries { + puts -nonewline "Testing against $bin - " + flush stdout + puts "version [get_version $bin]" + } + + set ::BC(binaries) $binaries + return $binaries +} + +proc get_version {binary} { + set chan [launch_testfixture $binary] + set v [testfixture $chan { sqlite3 -version }] + close $chan + set v +} + +proc do_bc_test {bin script} { + + forcedelete test.db + set ::bc_chan [launch_testfixture $bin] + + proc code1 {tcl} { uplevel #0 $tcl } + proc code2 {tcl} { testfixture $::bc_chan $tcl } + proc sql1 sql { code1 [list db eval $sql] } + proc sql2 sql { code2 [list db eval $sql] } + + code1 { sqlite3 db test.db } + code2 { sqlite3 db test.db } + + set bintag [string map {testfixture {}} $bin] + set bintag [string map {\.exe {}} $bintag] + if {$bintag == ""} {set bintag self} + set saved_prefix $::testprefix + append ::testprefix ".$bintag" + + uplevel $script + + set ::testprefix $saved_prefix + + catch { code1 { db close } } + catch { code2 { db close } } + catch { close $::bc_chan } +} + +proc do_all_bc_test {script} { + foreach bin $::BC(binaries) { + uplevel [list do_bc_test $bin $script] + } +} diff --git a/components/external/SQLite-3.8.1/test/between.test b/components/external/SQLite-3.8.1/test/between.test new file mode 100644 index 0000000000000000000000000000000000000000..df4c67995c46dc945de8b5ab820a83198891c20c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/between.test @@ -0,0 +1,123 @@ +# 2005 July 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the use of indices in WHERE clauses +# when the WHERE clause contains the BETWEEN operator. +# +# $Id: between.test,v 1.2 2006/01/17 09:35:02 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build some test data +# +do_test between-1.0 { + execsql { + BEGIN; + CREATE TABLE t1(w int, x int, y int, z int); + } + for {set i 1} {$i<=100} {incr i} { + set w $i + set x [expr {int(log($i)/log(2))}] + set y [expr {$i*$i + 2*$i + 1}] + set z [expr {$x+$y}] + ifcapable tclvar { + # Random unplanned test of the $varname variable syntax. + execsql {INSERT INTO t1 VALUES($::w,$::x,$::y,$::z)} + } else { + # If the $varname syntax is not available, use the regular variable + # declaration syntax. + execsql {INSERT INTO t1 VALUES(:w,:x,:y,:z)} + } + } + execsql { + CREATE UNIQUE INDEX i1w ON t1(w); + CREATE INDEX i1xy ON t1(x,y); + CREATE INDEX i1zyx ON t1(z,y,x); + COMMIT; + } +} {} + +# This procedure executes the SQL. Then it appends to the result the +# "sort" or "nosort" keyword depending on whether or not any sorting +# is done. Then it appends the names of the table and index used. +# +proc queryplan {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + if {$::sqlite_sort_count} {set x sort} {set x nosort} + lappend data $x + set eqp [execsql "EXPLAIN QUERY PLAN $sql"] + # puts eqp=$eqp + foreach {a b c x} $eqp { + if {[regexp { TABLE (\w+ AS )?(\w+) USING.* INDEX (\w+)\y} \ + $x all as tab idx]} { + lappend data $tab $idx + } elseif {[regexp { TABLE (\w+ AS )?(\w+)\y} $x all as tab]} { + lappend data $tab * + } + } + return $data +} + +do_test between-1.1.1 { + queryplan { + SELECT * FROM t1 WHERE w BETWEEN 5 AND 6 ORDER BY +w + } +} {5 2 36 38 6 2 49 51 sort t1 i1w} +do_test between-1.1.2 { + queryplan { + SELECT * FROM t1 WHERE +w BETWEEN 5 AND 6 ORDER BY +w + } +} {5 2 36 38 6 2 49 51 sort t1 *} +do_test between-1.2.1 { + queryplan { + SELECT * FROM t1 WHERE w BETWEEN 5 AND 65-y ORDER BY +w + } +} {5 2 36 38 6 2 49 51 sort t1 i1w} +do_test between-1.2.2 { + queryplan { + SELECT * FROM t1 WHERE +w BETWEEN 5 AND 65-y ORDER BY +w + } +} {5 2 36 38 6 2 49 51 sort t1 *} +do_test between-1.3.1 { + queryplan { + SELECT * FROM t1 WHERE w BETWEEN 41-y AND 6 ORDER BY +w + } +} {5 2 36 38 6 2 49 51 sort t1 i1w} +do_test between-1.3.2 { + queryplan { + SELECT * FROM t1 WHERE +w BETWEEN 41-y AND 6 ORDER BY +w + } +} {5 2 36 38 6 2 49 51 sort t1 *} +do_test between-1.4 { + queryplan { + SELECT * FROM t1 WHERE w BETWEEN 41-y AND 65-y ORDER BY +w + } +} {5 2 36 38 6 2 49 51 sort t1 *} +do_test between-1.5.1 { + queryplan { + SELECT * FROM t1 WHERE 26 BETWEEN y AND z ORDER BY +w + } +} {4 2 25 27 sort t1 i1zyx} +do_test between-1.5.2 { + queryplan { + SELECT * FROM t1 WHERE 26 BETWEEN +y AND z ORDER BY +w + } +} {4 2 25 27 sort t1 i1zyx} +do_test between-1.5.3 { + queryplan { + SELECT * FROM t1 WHERE 26 BETWEEN y AND +z ORDER BY +w + } +} {4 2 25 27 sort t1 *} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/bigfile.test b/components/external/SQLite-3.8.1/test/bigfile.test new file mode 100644 index 0000000000000000000000000000000000000000..31c632322c726b085a543fde874aeaa63b3cb472 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/bigfile.test @@ -0,0 +1,203 @@ +# 2002 November 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the ability of SQLite to handle database +# files larger than 4GB. +# +# $Id: bigfile.test,v 1.12 2009/03/05 04:27:08 shane Exp $ +# + +if {[file exists skip-big-file]} return +if {$tcl_platform(os)=="Darwin"} return + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for this file, as the database is manipulated using +# external methods (the [fake_big_file] and [hexio_write] commands). +# +do_not_use_codec + +# If SQLITE_DISABLE_LFS is defined, omit this file. +ifcapable !lfs { + finish_test + return +} + +# These tests only work for Tcl version 8.4 and later. Prior to 8.4, +# Tcl was unable to handle large files. +# +scan $::tcl_version %f vx +if {$vx<8.4} return + +# Mac OS X does not handle large files efficiently. So skip this test +# on that platform. +if {$tcl_platform(os)=="Darwin"} return + +# This is the md5 checksum of all the data in table t1 as created +# by the first test. We will use this number to make sure that data +# never changes. +# +set MAGIC_SUM {593f1efcfdbe698c28b4b1b693f7e4cf} + +do_test bigfile-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('abcdefghijklmnopqrstuvwxyz'); + INSERT INTO t1 SELECT rowid || ' ' || x FROM t1; + INSERT INTO t1 SELECT rowid || ' ' || x FROM t1; + INSERT INTO t1 SELECT rowid || ' ' || x FROM t1; + INSERT INTO t1 SELECT rowid || ' ' || x FROM t1; + INSERT INTO t1 SELECT rowid || ' ' || x FROM t1; + INSERT INTO t1 SELECT rowid || ' ' || x FROM t1; + INSERT INTO t1 SELECT rowid || ' ' || x FROM t1; + COMMIT; + } + execsql { + SELECT md5sum(x) FROM t1; + } +} $::MAGIC_SUM + +# Try to create a large file - a file that is larger than 2^32 bytes. +# If this fails, it means that the system being tested does not support +# large files. So skip all of the remaining tests in this file. +# +db close +if {[catch {fake_big_file 4096 [get_pwd]/test.db} msg]} { + puts "**** Unable to create a file larger than 4096 MB. *****" + finish_test + return +} +hexio_write test.db 28 00000000 + +do_test bigfile-1.2 { + sqlite3 db test.db + execsql { + SELECT md5sum(x) FROM t1; + } +} $::MAGIC_SUM + +# The previous test may fail on some systems because they are unable +# to handle large files. If that is so, then skip all of the following +# tests. We will know the above test failed because the "db" command +# does not exist. +# +if {[llength [info command db]]<=0} { + puts "**** Large file support appears to be broken. *****" + finish_test + return +} + +do_test bigfile-1.3 { + execsql { + CREATE TABLE t2 AS SELECT * FROM t1; + SELECT md5sum(x) FROM t2; + } +} $::MAGIC_SUM +do_test bigfile-1.4 { + db close + sqlite3 db test.db + execsql { + SELECT md5sum(x) FROM t1; + } +} $::MAGIC_SUM + +db close +if {[catch {fake_big_file 8192 [get_pwd]/test.db}]} { + puts "**** Unable to create a file larger than 8192 MB. *****" + finish_test + return +} +hexio_write test.db 28 00000000 + +do_test bigfile-1.5 { + sqlite3 db test.db + execsql { + SELECT md5sum(x) FROM t1; + } +} $::MAGIC_SUM +do_test bigfile-1.6 { + sqlite3 db test.db + execsql { + SELECT md5sum(x) FROM t2; + } +} $::MAGIC_SUM +do_test bigfile-1.7 { + execsql { + CREATE TABLE t3 AS SELECT * FROM t1; + SELECT md5sum(x) FROM t3; + } +} $::MAGIC_SUM +do_test bigfile-1.8 { + db close + sqlite3 db test.db + execsql { + SELECT md5sum(x) FROM t1; + } +} $::MAGIC_SUM +do_test bigfile-1.9 { + execsql { + SELECT md5sum(x) FROM t2; + } +} $::MAGIC_SUM + +db close +if {[catch {fake_big_file 16384 [get_pwd]/test.db}]} { + puts "**** Unable to create a file larger than 16384 MB. *****" + finish_test + return +} +hexio_write test.db 28 00000000 + +do_test bigfile-1.10 { + sqlite3 db test.db + execsql { + SELECT md5sum(x) FROM t1; + } +} $::MAGIC_SUM +do_test bigfile-1.11 { + sqlite3 db test.db + execsql { + SELECT md5sum(x) FROM t2; + } +} $::MAGIC_SUM +do_test bigfile-1.12 { + sqlite3 db test.db + execsql { + SELECT md5sum(x) FROM t3; + } +} $::MAGIC_SUM +do_test bigfile-1.13 { + execsql { + CREATE TABLE t4 AS SELECT * FROM t1; + SELECT md5sum(x) FROM t4; + } +} $::MAGIC_SUM +do_test bigfile-1.14 { + db close + sqlite3 db test.db + execsql { + SELECT md5sum(x) FROM t1; + } +} $::MAGIC_SUM +do_test bigfile-1.15 { + execsql { + SELECT md5sum(x) FROM t2; + } +} $::MAGIC_SUM +do_test bigfile-1.16 { + execsql { + SELECT md5sum(x) FROM t3; + } +} $::MAGIC_SUM + +finish_test diff --git a/components/external/SQLite-3.8.1/test/bigfile2.test b/components/external/SQLite-3.8.1/test/bigfile2.test new file mode 100644 index 0000000000000000000000000000000000000000..de3b14b558ede33b77d9423002fd9ba9ea8bfcdf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/bigfile2.test @@ -0,0 +1,62 @@ +# 2011 December 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the ability of SQLite to handle database +# files larger than 4GB. +# + +if {[file exists skip-big-file]} return +if {$tcl_platform(os)=="Darwin"} return + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix bigfile2 + +# Create a small database. +# +do_execsql_test 1.1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); +} + +# Pad the file out to 4GB in size. Then clear the file-size field in the +# db header. This will cause SQLite to assume that the first 4GB of pages +# are actually in use and new pages will be appended to the file. +# +db close +if {[catch {fake_big_file 4096 [get_pwd]/test.db} msg]} { + puts "**** Unable to create a file larger than 4096 MB. *****" + finish_test + return +} +hexio_write test.db 28 00000000 + +do_test 1.2 { + file size test.db +} [expr 14 + 4096 * (1<<20)] + +# Now insert a large row. The overflow pages will be located past the 4GB +# boundary. Then, after opening and closing the database, test that the row +# can be read back in. +# +set str [string repeat k 30000] +do_test 1.3 { + sqlite3 db test.db + execsql { INSERT INTO t1 VALUES(3, $str) } + db close + sqlite3 db test.db + db one { SELECT b FROM t1 WHERE a = 3 } +} $str + +db close +delete_file test.db + +finish_test diff --git a/components/external/SQLite-3.8.1/test/bigrow.test b/components/external/SQLite-3.8.1/test/bigrow.test new file mode 100644 index 0000000000000000000000000000000000000000..fa59c3625240a582a1d38e3826d895264e68c7ef --- /dev/null +++ b/components/external/SQLite-3.8.1/test/bigrow.test @@ -0,0 +1,223 @@ +# 2001 September 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is stressing the library by putting large amounts +# of data in a single row of a table. +# +# $Id: bigrow.test,v 1.5 2004/08/07 23:54:48 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Make a big string that we can use for test data +# +do_test bigrow-1.0 { + set ::bigstr {} + for {set i 1} {$i<=9999} {incr i} { + set sep [string index "abcdefghijklmnopqrstuvwxyz" [expr {$i%26}]] + append ::bigstr "$sep [format %04d $i] " + } + string length $::bigstr +} {69993} + +# Make a table into which we can insert some but records. +# +do_test bigrow-1.1 { + execsql { + CREATE TABLE t1(a text, b text, c text); + SELECT name FROM sqlite_master + WHERE type='table' OR type='index' + ORDER BY name + } +} {t1} + +do_test bigrow-1.2 { + set ::big1 [string range $::bigstr 0 65519] + set sql "INSERT INTO t1 VALUES('abc'," + append sql "'$::big1', 'xyz');" + execsql $sql + execsql {SELECT a, c FROM t1} +} {abc xyz} +do_test bigrow-1.3 { + execsql {SELECT b FROM t1} +} [list $::big1] +do_test bigrow-1.4 { + set ::big2 [string range $::bigstr 0 65520] + set sql "INSERT INTO t1 VALUES('abc2'," + append sql "'$::big2', 'xyz2');" + set r [catch {execsql $sql} msg] + lappend r $msg +} {0 {}} +do_test bigrow-1.4.1 { + execsql {SELECT b FROM t1 ORDER BY c} +} [list $::big1 $::big2] +do_test bigrow-1.4.2 { + execsql {SELECT c FROM t1 ORDER BY c} +} {xyz xyz2} +do_test bigrow-1.4.3 { + execsql {DELETE FROM t1 WHERE a='abc2'} + execsql {SELECT c FROM t1} +} {xyz} + +do_test bigrow-1.5 { + execsql { + UPDATE t1 SET a=b, b=a; + SELECT b,c FROM t1 + } +} {abc xyz} +do_test bigrow-1.6 { + execsql { + SELECT * FROM t1 + } +} [list $::big1 abc xyz] +do_test bigrow-1.7 { + execsql { + INSERT INTO t1 VALUES('1','2','3'); + INSERT INTO t1 VALUES('A','B','C'); + SELECT b FROM t1 WHERE a=='1'; + } +} {2} +do_test bigrow-1.8 { + execsql "SELECT b FROM t1 WHERE a=='$::big1'" +} {abc} +do_test bigrow-1.9 { + execsql "SELECT b FROM t1 WHERE a!='$::big1' ORDER BY a" +} {2 B} + +# Try doing some indexing on big columns +# +do_test bigrow-2.1 { + execsql { + CREATE INDEX i1 ON t1(a) + } + execsql "SELECT b FROM t1 WHERE a=='$::big1'" +} {abc} +do_test bigrow-2.2 { + execsql { + UPDATE t1 SET a=b, b=a + } + execsql "SELECT b FROM t1 WHERE a=='abc'" +} [list $::big1] +do_test bigrow-2.3 { + execsql { + UPDATE t1 SET a=b, b=a + } + execsql "SELECT b FROM t1 WHERE a=='$::big1'" +} {abc} +catch {unset ::bigstr} +catch {unset ::big1} +catch {unset ::big2} + +# Mosts of the tests above were created back when rows were limited in +# size to 64K. Now rows can be much bigger. Test that logic. Also +# make sure things work correctly at the transition boundries between +# row sizes of 256 to 257 bytes and from 65536 to 65537 bytes. +# +# We begin by testing the 256..257 transition. +# +do_test bigrow-3.1 { + execsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c) VALUES('one','abcdefghijklmnopqrstuvwxyz0123','hi'); + } + execsql {SELECT a,length(b),c FROM t1} +} {one 30 hi} +do_test bigrow-3.2 { + execsql { + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + } + execsql {SELECT a,length(b),c FROM t1} +} {one 240 hi} +for {set i 1} {$i<10} {incr i} { + do_test bigrow-3.3.$i { + execsql "UPDATE t1 SET b=b||'$i'" + execsql {SELECT a,length(b),c FROM t1} + } "one [expr {240+$i}] hi" +} + +# Now test the 65536..65537 row-size transition. +# +do_test bigrow-4.1 { + execsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c) VALUES('one','abcdefghijklmnopqrstuvwxyz0123','hi'); + } + execsql {SELECT a,length(b),c FROM t1} +} {one 30 hi} +do_test bigrow-4.2 { + execsql { + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + } + execsql {SELECT a,length(b),c FROM t1} +} {one 122880 hi} +do_test bigrow-4.3 { + execsql { + UPDATE t1 SET b=substr(b,1,65515) + } + execsql {SELECT a,length(b),c FROM t1} +} {one 65515 hi} +for {set i 1} {$i<10} {incr i} { + do_test bigrow-4.4.$i { + execsql "UPDATE t1 SET b=b||'$i'" + execsql {SELECT a,length(b),c FROM t1} + } "one [expr {65515+$i}] hi" +} + +# Check to make sure the library recovers safely if a row contains +# too much data. +# +do_test bigrow-5.1 { + execsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c) VALUES('one','abcdefghijklmnopqrstuvwxyz0123','hi'); + } + execsql {SELECT a,length(b),c FROM t1} +} {one 30 hi} +set i 1 +for {set sz 60} {$sz<1048560} {incr sz $sz} { + do_test bigrow-5.2.$i { + execsql { + UPDATE t1 SET b=b||b; + SELECT a,length(b),c FROM t1; + } + } "one $sz hi" + incr i +} +do_test bigrow-5.3 { + catchsql {UPDATE t1 SET b=b||b} +} {0 {}} +do_test bigrow-5.4 { + execsql {SELECT length(b) FROM t1} +} 1966080 +do_test bigrow-5.5 { + catchsql {UPDATE t1 SET b=b||b} +} {0 {}} +do_test bigrow-5.6 { + execsql {SELECT length(b) FROM t1} +} 3932160 +do_test bigrow-5.99 { + execsql {DROP TABLE t1} +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/bind.test b/components/external/SQLite-3.8.1/test/bind.test new file mode 100644 index 0000000000000000000000000000000000000000..34f3155b95253a3f9b740f2ffa2c9fbdd276edee --- /dev/null +++ b/components/external/SQLite-3.8.1/test/bind.test @@ -0,0 +1,758 @@ +# 2003 September 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the sqlite_bind API. +# +# $Id: bind.test,v 1.48 2009/07/22 07:27:57 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc sqlite_step {stmt N VALS COLS} { + upvar VALS vals + upvar COLS cols + set vals [list] + set cols [list] + + set rc [sqlite3_step $stmt] + for {set i 0} {$i < [sqlite3_column_count $stmt]} {incr i} { + lappend cols [sqlite3_column_name $stmt $i] + } + for {set i 0} {$i < [sqlite3_data_count $stmt]} {incr i} { + lappend vals [sqlite3_column_text $stmt $i] + } + + return $rc +} + +do_test bind-1.1 { + set DB [sqlite3_connection_pointer db] + execsql {CREATE TABLE t1(a,b,c);} + set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES(:1,?,:abc)} -1 TAIL] + set TAIL +} {} +do_test bind-1.1.1 { + sqlite3_bind_parameter_count $VM +} 3 +do_test bind-1.1.2 { + sqlite3_bind_parameter_name $VM 1 +} {:1} +do_test bind-1.1.3 { + sqlite3_bind_parameter_name $VM 2 +} {} +do_test bind-1.1.4 { + sqlite3_bind_parameter_name $VM 3 +} {:abc} +do_test bind-1.2 { + sqlite_step $VM N VALUES COLNAMES +} {SQLITE_DONE} +do_test bind-1.3 { + execsql {SELECT rowid, * FROM t1} +} {1 {} {} {}} +do_test bind-1.4 { + sqlite3_reset $VM + sqlite_bind $VM 1 {test value 1} normal + sqlite_step $VM N VALUES COLNAMES +} SQLITE_DONE +do_test bind-1.5 { + execsql {SELECT rowid, * FROM t1} +} {1 {} {} {} 2 {test value 1} {} {}} +do_test bind-1.6 { + sqlite3_reset $VM + sqlite_bind $VM 3 {'test value 2'} normal + sqlite_step $VM N VALUES COLNAMES +} SQLITE_DONE +do_test bind-1.7 { + execsql {SELECT rowid, * FROM t1} +} {1 {} {} {} 2 {test value 1} {} {} 3 {test value 1} {} {'test value 2'}} +do_test bind-1.8 { + sqlite3_reset $VM + set sqlite_static_bind_value 123 + sqlite_bind $VM 1 {} static + sqlite_bind $VM 2 {abcdefg} normal + sqlite_bind $VM 3 {} null + execsql {DELETE FROM t1} + sqlite_step $VM N VALUES COLNAMES + execsql {SELECT rowid, * FROM t1} +} {1 123 abcdefg {}} +do_test bind-1.9 { + sqlite3_reset $VM + sqlite_bind $VM 1 {456} normal + sqlite_step $VM N VALUES COLNAMES + execsql {SELECT rowid, * FROM t1} +} {1 123 abcdefg {} 2 456 abcdefg {}} + +do_test bind-1.10 { + set rc [catch { + sqlite3_prepare db {INSERT INTO t1 VALUES($abc:123,?,:abc)} -1 TAIL + } msg] + lappend rc $msg +} {1 {(1) near ":123": syntax error}} +do_test bind-1.11 { + set rc [catch { + sqlite3_prepare db {INSERT INTO t1 VALUES(@abc:xyz,?,:abc)} -1 TAIL + } msg] + lappend rc $msg +} {1 {(1) near ":xyz": syntax error}} + +do_test bind-1.99 { + sqlite3_finalize $VM +} SQLITE_OK + +# Prepare the statement in different ways depending on whether or not +# the $var processing is compiled into the library. +# +ifcapable {tclvar} { + do_test bind-2.1 { + execsql { + DELETE FROM t1; + } + set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES($one,$::two,$x(-z-))}\ + -1 TX] + set TX + } {} + set v1 {$one} + set v2 {$::two} + set v3 {$x(-z-)} +} +ifcapable {!tclvar} { + do_test bind-2.1 { + execsql { + DELETE FROM t1; + } + set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES(:one,:two,:_)} -1 TX] + set TX + } {} + set v1 {:one} + set v2 {:two} + set v3 {:_} +} + +do_test bind-2.1.1 { + sqlite3_bind_parameter_count $VM +} 3 +do_test bind-2.1.2 { + sqlite3_bind_parameter_name $VM 1 +} $v1 +do_test bind-2.1.3 { + sqlite3_bind_parameter_name $VM 2 +} $v2 +do_test bind-2.1.4 { + sqlite3_bind_parameter_name $VM 3 +} $v3 +do_test bind-2.1.5 { + sqlite3_bind_parameter_index $VM $v1 +} 1 +do_test bind-2.1.6 { + sqlite3_bind_parameter_index $VM $v2 +} 2 +do_test bind-2.1.7 { + sqlite3_bind_parameter_index $VM $v3 +} 3 +do_test bind-2.1.8 { + sqlite3_bind_parameter_index $VM {:hi} +} 0 + +# 32 bit Integers +do_test bind-2.2 { + sqlite3_bind_int $VM 1 123 + sqlite3_bind_int $VM 2 456 + sqlite3_bind_int $VM 3 789 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + execsql {SELECT rowid, * FROM t1} +} {1 123 456 789} +do_test bind-2.3 { + sqlite3_bind_int $VM 2 -2000000000 + sqlite3_bind_int $VM 3 2000000000 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + execsql {SELECT rowid, * FROM t1} +} {1 123 456 789 2 123 -2000000000 2000000000} +do_test bind-2.4 { + execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1} +} {integer integer integer integer integer integer} +do_test bind-2.5 { + execsql { + DELETE FROM t1; + } +} {} + +# 64 bit Integers +do_test bind-3.1 { + sqlite3_bind_int64 $VM 1 32 + sqlite3_bind_int64 $VM 2 -2000000000000 + sqlite3_bind_int64 $VM 3 2000000000000 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + execsql {SELECT rowid, * FROM t1} +} {1 32 -2000000000000 2000000000000} +do_test bind-3.2 { + execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1} +} {integer integer integer} +do_test bind-3.3 { + execsql { + DELETE FROM t1; + } +} {} + +# Doubles +do_test bind-4.1 { + sqlite3_bind_double $VM 1 1234.1234 + sqlite3_bind_double $VM 2 0.00001 + sqlite3_bind_double $VM 3 123456789 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + set x [execsql {SELECT rowid, * FROM t1}] + regsub {1e-005} $x {1e-05} y + set y +} {1 1234.1234 1e-05 123456789.0} +do_test bind-4.2 { + execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1} +} {real real real} +do_test bind-4.3 { + execsql { + DELETE FROM t1; + } +} {} +do_test bind-4.4 { + sqlite3_bind_double $VM 1 NaN + sqlite3_bind_double $VM 2 1e300 + sqlite3_bind_double $VM 3 -1e-300 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + set x [execsql {SELECT rowid, * FROM t1}] + regsub {1e-005} $x {1e-05} y + set y +} {1 {} 1e+300 -1e-300} +do_test bind-4.5 { + execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1} +} {null real real} +do_test bind-4.6 { + execsql { + DELETE FROM t1; + } +} {} + +# NULL +do_test bind-5.1 { + sqlite3_bind_null $VM 1 + sqlite3_bind_null $VM 2 + sqlite3_bind_null $VM 3 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + execsql {SELECT rowid, * FROM t1} +} {1 {} {} {}} +do_test bind-5.2 { + execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1} +} {null null null} +do_test bind-5.3 { + execsql { + DELETE FROM t1; + } +} {} + +# UTF-8 text +do_test bind-6.1 { + sqlite3_bind_text $VM 1 hellothere 5 + sqlite3_bind_text $VM 2 ".." 1 + sqlite3_bind_text $VM 3 world\000 -1 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + execsql {SELECT rowid, * FROM t1} +} {1 hello . world} +do_test bind-6.2 { + execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1} +} {text text text} +do_test bind-6.3 { + execsql { + DELETE FROM t1; + } +} {} + +# Make sure zeros in a string work. +# +do_test bind-6.4 { + db eval {DELETE FROM t1} + sqlite3_bind_text $VM 1 hello\000there\000 12 + sqlite3_bind_text $VM 2 hello\000there\000 11 + sqlite3_bind_text $VM 3 hello\000there\000 -1 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + execsql {SELECT * FROM t1} +} {hello hello hello} +set enc [db eval {PRAGMA encoding}] +if {$enc=="UTF-8" || $enc==""} { + do_test bind-6.5 { + execsql {SELECT hex(a), hex(b), hex(c) FROM t1} + } {68656C6C6F00746865726500 68656C6C6F007468657265 68656C6C6F} +} elseif {$enc=="UTF-16le"} { + do_test bind-6.5 { + execsql {SELECT hex(a), hex(b), hex(c) FROM t1} + } {680065006C006C006F000000740068006500720065000000 680065006C006C006F00000074006800650072006500 680065006C006C006F00} +} elseif {$enc=="UTF-16be"} { + do_test bind-6.5 { + execsql {SELECT hex(a), hex(b), hex(c) FROM t1} + } {00680065006C006C006F0000007400680065007200650000 00680065006C006C006F000000740068006500720065 00680065006C006C006F} +} else { + do_test bind-6.5 { + set "Unknown database encoding: $::enc" + } {} +} +do_test bind-6.6 { + execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1} +} {text text text} +do_test bind-6.7 { + execsql { + DELETE FROM t1; + } +} {} + +# UTF-16 text +ifcapable {utf16} { + do_test bind-7.1 { + sqlite3_bind_text16 $VM 1 [encoding convertto unicode hellothere] 10 + sqlite3_bind_text16 $VM 2 [encoding convertto unicode ""] 0 + sqlite3_bind_text16 $VM 3 [encoding convertto unicode world] 10 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + execsql {SELECT rowid, * FROM t1} + } {1 hello {} world} + do_test bind-7.2 { + execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1} + } {text text text} + do_test bind-7.3 { + db eval {DELETE FROM t1} + sqlite3_bind_text16 $VM 1 [encoding convertto unicode hi\000yall\000] 16 + sqlite3_bind_text16 $VM 2 [encoding convertto unicode hi\000yall\000] 14 + sqlite3_bind_text16 $VM 3 [encoding convertto unicode hi\000yall\000] -1 + sqlite_step $VM N VALUES COLNAMES + sqlite3_reset $VM + execsql {SELECT * FROM t1} + } {hi hi hi} + if {$enc=="UTF-8"} { + do_test bind-7.4 { + execsql {SELECT hex(a), hex(b), hex(c) FROM t1} + } {68690079616C6C00 68690079616C6C 6869} + } elseif {$enc=="UTF-16le"} { + do_test bind-7.4 { + execsql {SELECT hex(a), hex(b), hex(c) FROM t1} + } {680069000000790061006C006C000000 680069000000790061006C006C00 68006900} + } elseif {$enc=="UTF-16be"} { + do_test bind-7.4 { + execsql {SELECT hex(a), hex(b), hex(c) FROM t1} + } {00680069000000790061006C006C0000 00680069000000790061006C006C 00680069} + } + do_test bind-7.5 { + execsql {SELECT typeof(a), typeof(b), typeof(c) FROM t1} + } {text text text} +} +do_test bind-7.99 { + execsql {DELETE FROM t1;} +} {} + +# Test that the 'out of range' error works. +do_test bind-8.1 { + catch { sqlite3_bind_null $VM 0 } +} {1} +do_test bind-8.2 { + sqlite3_errmsg $DB +} {bind or column index out of range} +ifcapable {utf16} { + do_test bind-8.3 { + encoding convertfrom unicode [sqlite3_errmsg16 $DB] + } {bind or column index out of range} +} +do_test bind-8.4 { + sqlite3_bind_null $VM 1 + sqlite3_errmsg $DB +} {not an error} +do_test bind-8.5 { + catch { sqlite3_bind_null $VM 4 } +} {1} +do_test bind-8.6 { + sqlite3_errmsg $DB +} {bind or column index out of range} +ifcapable {utf16} { + do_test bind-8.7 { + encoding convertfrom unicode [sqlite3_errmsg16 $DB] + } {bind or column index out of range} +} + +do_test bind-8.8 { + catch { sqlite3_bind_blob $VM 0 "abc" 3 } +} {1} +do_test bind-8.9 { + catch { sqlite3_bind_blob $VM 4 "abc" 3 } +} {1} +do_test bind-8.10 { + catch { sqlite3_bind_text $VM 0 "abc" 3 } +} {1} +ifcapable {utf16} { + do_test bind-8.11 { + catch { sqlite3_bind_text16 $VM 4 "abc" 2 } + } {1} +} +do_test bind-8.12 { + catch { sqlite3_bind_int $VM 0 5 } +} {1} +do_test bind-8.13 { + catch { sqlite3_bind_int $VM 4 5 } +} {1} +do_test bind-8.14 { + catch { sqlite3_bind_double $VM 0 5.0 } +} {1} +do_test bind-8.15 { + catch { sqlite3_bind_double $VM 4 6.0 } +} {1} + +do_test bind-8.99 { + sqlite3_finalize $VM +} SQLITE_OK + +set iMaxVar $SQLITE_MAX_VARIABLE_NUMBER +set zError "(1) variable number must be between ?1 and ?$iMaxVar" +do_test bind-9.1 { + execsql { + CREATE TABLE t2(a,b,c,d,e,f); + } + set rc [catch { + sqlite3_prepare $DB { + INSERT INTO t2(a) VALUES(?0) + } -1 TAIL + } msg] + lappend rc $msg +} [list 1 $zError] +do_test bind-9.2 { + set rc [catch { + sqlite3_prepare $DB "INSERT INTO t2(a) VALUES(?[expr $iMaxVar+1])" -1 TAIL + } msg] + lappend rc $msg +} [list 1 $zError] +do_test bind-9.3.1 { + set VM [ + sqlite3_prepare $DB " + INSERT INTO t2(a,b) VALUES(?1,?$iMaxVar) + " -1 TAIL + ] + sqlite3_bind_parameter_count $VM +} $iMaxVar +catch {sqlite3_finalize $VM} +do_test bind-9.3.2 { + set VM [ + sqlite3_prepare $DB " + INSERT INTO t2(a,b) VALUES(?2,?[expr $iMaxVar - 1]) + " -1 TAIL + ] + sqlite3_bind_parameter_count $VM +} [expr {$iMaxVar - 1}] +catch {sqlite3_finalize $VM} +do_test bind-9.4 { + set VM [ + sqlite3_prepare $DB " + INSERT INTO t2(a,b,c,d) VALUES(?1,?[expr $iMaxVar - 2],?,?) + " -1 TAIL + ] + sqlite3_bind_parameter_count $VM +} $iMaxVar +do_test bind-9.5 { + sqlite3_bind_int $VM 1 1 + sqlite3_bind_int $VM [expr $iMaxVar - 2] 999 + sqlite3_bind_int $VM [expr $iMaxVar - 1] 1000 + sqlite3_bind_int $VM $iMaxVar 1001 + sqlite3_step $VM +} SQLITE_DONE +do_test bind-9.6 { + sqlite3_finalize $VM +} SQLITE_OK +do_test bind-9.7 { + execsql {SELECT * FROM t2} +} {1 999 1000 1001 {} {}} + +ifcapable {tclvar} { + do_test bind-10.1 { + set VM [ + sqlite3_prepare $DB { + INSERT INTO t2(a,b,c,d,e,f) VALUES(:abc,$abc,:abc,$ab,$abc,:abc) + } -1 TAIL + ] + sqlite3_bind_parameter_count $VM + } 3 + set v1 {$abc} + set v2 {$ab} +} +ifcapable {!tclvar} { + do_test bind-10.1 { + set VM [ + sqlite3_prepare $DB { + INSERT INTO t2(a,b,c,d,e,f) VALUES(:abc,:xyz,:abc,:xy,:xyz,:abc) + } -1 TAIL + ] + sqlite3_bind_parameter_count $VM + } 3 + set v1 {:xyz} + set v2 {:xy} +} +do_test bind-10.2 { + sqlite3_bind_parameter_index $VM :abc +} 1 +do_test bind-10.3 { + sqlite3_bind_parameter_index $VM $v1 +} 2 +do_test bind-10.4 { + sqlite3_bind_parameter_index $VM $v2 +} 3 +do_test bind-10.5 { + sqlite3_bind_parameter_name $VM 1 +} :abc +do_test bind-10.6 { + sqlite3_bind_parameter_name $VM 2 +} $v1 +do_test bind-10.7 { + sqlite3_bind_parameter_name $VM 3 +} $v2 +do_test bind-10.7.1 { + sqlite3_bind_parameter_name 0 1 ;# Ignore if VM is NULL +} {} +do_test bind-10.7.2 { + sqlite3_bind_parameter_name $VM 0 ;# Ignore if index too small +} {} +do_test bind-10.7.3 { + sqlite3_bind_parameter_name $VM 4 ;# Ignore if index is too big +} {} +do_test bind-10.8 { + sqlite3_bind_int $VM 1 1 + sqlite3_bind_int $VM 2 2 + sqlite3_bind_int $VM 3 3 + sqlite3_step $VM +} SQLITE_DONE +do_test bind-10.8.1 { + # Binding attempts after program start should fail + set rc [catch { + sqlite3_bind_int $VM 1 1 + } msg] + lappend rc $msg +} {1 {}} +do_test bind-10.9 { + sqlite3_finalize $VM +} SQLITE_OK +do_test bind-10.10 { + execsql {SELECT * FROM t2} +} {1 999 1000 1001 {} {} 1 2 1 3 2 1} + +# Ticket #918 +# +do_test bind-10.11 { + # catch {sqlite3_finalize $VM} + set VM [ + sqlite3_prepare $DB { + INSERT INTO t2(a,b,c,d,e,f) VALUES(:abc,?,?4,:pqr,:abc,?4) + } -1 TAIL + ] + sqlite3_bind_parameter_count $VM +} 5 +do_test bind-10.11.1 { + sqlite3_bind_parameter_index 0 :xyz ;# ignore NULL VM arguments +} 0 +do_test bind-10.12 { + sqlite3_bind_parameter_index $VM :xyz +} 0 +do_test bind-10.13 { + sqlite3_bind_parameter_index $VM {} +} 0 +do_test bind-10.14 { + sqlite3_bind_parameter_index $VM :pqr +} 5 +do_test bind-10.15 { + sqlite3_bind_parameter_index $VM ?4 +} 4 +do_test bind-10.16 { + sqlite3_bind_parameter_name $VM 1 +} :abc +do_test bind-10.17 { + sqlite3_bind_parameter_name $VM 2 +} {} +do_test bind-10.18 { + sqlite3_bind_parameter_name $VM 3 +} {} +do_test bind-10.19 { + sqlite3_bind_parameter_name $VM 4 +} {?4} +do_test bind-10.20 { + sqlite3_bind_parameter_name $VM 5 +} :pqr +catch {sqlite3_finalize $VM} + +# Make sure we catch an unterminated "(" in a Tcl-style variable name +# +ifcapable tclvar { + do_test bind-11.1 { + catchsql {SELECT * FROM sqlite_master WHERE name=$abc(123 and sql NOT NULL;} + } {1 {unrecognized token: "$abc(123"}} +} + +if {[execsql {pragma encoding}]=="UTF-8"} { + # Test the ability to bind text that contains embedded '\000' characters. + # Make sure we can recover the entire input string. + # + do_test bind-12.1 { + execsql { + CREATE TABLE t3(x BLOB); + } + set VM [sqlite3_prepare $DB {INSERT INTO t3 VALUES(?)} -1 TAIL] + sqlite_bind $VM 1 not-used blob10 + sqlite3_step $VM + sqlite3_finalize $VM + execsql { + SELECT typeof(x), length(x), quote(x), + length(cast(x AS BLOB)), quote(cast(x AS BLOB)) FROM t3 + } + } {text 3 'abc' 10 X'6162630078797A007071'} + do_test bind-12.2 { + sqlite3_create_function $DB + execsql { + SELECT quote(cast(x_coalesce(x) AS blob)) FROM t3 + } + } {X'6162630078797A007071'} +} + +# Test the operation of sqlite3_clear_bindings +# +do_test bind-13.1 { + set VM [sqlite3_prepare $DB {SELECT ?,?,?} -1 TAIL] + sqlite3_step $VM + list [sqlite3_column_type $VM 0] [sqlite3_column_type $VM 1] \ + [sqlite3_column_type $VM 2] +} {NULL NULL NULL} +do_test bind-13.2 { + sqlite3_reset $VM + sqlite3_bind_int $VM 1 1 + sqlite3_bind_int $VM 2 2 + sqlite3_bind_int $VM 3 3 + sqlite3_step $VM + list [sqlite3_column_type $VM 0] [sqlite3_column_type $VM 1] \ + [sqlite3_column_type $VM 2] +} {INTEGER INTEGER INTEGER} +do_test bind-13.3 { + sqlite3_reset $VM + sqlite3_step $VM + list [sqlite3_column_type $VM 0] [sqlite3_column_type $VM 1] \ + [sqlite3_column_type $VM 2] +} {INTEGER INTEGER INTEGER} +do_test bind-13.4 { + sqlite3_reset $VM + sqlite3_clear_bindings $VM + sqlite3_step $VM + list [sqlite3_column_type $VM 0] [sqlite3_column_type $VM 1] \ + [sqlite3_column_type $VM 2] +} {NULL NULL NULL} +sqlite3_finalize $VM + +#-------------------------------------------------------------------- +# These tests attempt to reproduce bug #3463. +# +proc param_names {db zSql} { + set ret [list] + set VM [sqlite3_prepare db $zSql -1 TAIL] + for {set ii 1} {$ii <= [sqlite3_bind_parameter_count $VM]} {incr ii} { + lappend ret [sqlite3_bind_parameter_name $VM $ii] + } + sqlite3_finalize $VM + set ret +} + +do_test bind-14.1 { + param_names db { SELECT @a, @b } +} {@a @b} +do_test bind-14.2 { + param_names db { SELECT NULL FROM (SELECT NULL) WHERE @a = @b } +} {@a @b} +do_test bind-14.3 { + param_names db { SELECT @a FROM (SELECT NULL) WHERE 1 = @b } +} {@a @b} +do_test bind-14.4 { + param_names db { SELECT @a, @b FROM (SELECT NULL) } +} {@a @b} + +#-------------------------------------------------------------------------- +# Tests of the OP_Variable opcode where P3>1 +# +do_test bind-15.1 { + db eval {CREATE TABLE t4(a,b,c,d,e,f,g,h);} + set VM [sqlite3_prepare db { + INSERT INTO t4(a,b,c,d,f,g,h,e) VALUES(?,?,?,?,?,?,?,?) + } -1 TAIL] + sqlite3_bind_int $VM 1 1 + sqlite3_bind_int $VM 2 2 + sqlite3_bind_int $VM 3 3 + sqlite3_bind_int $VM 4 4 + sqlite3_bind_int $VM 5 5 + sqlite3_bind_int $VM 6 6 + sqlite3_bind_int $VM 7 7 + sqlite3_bind_int $VM 8 8 + sqlite3_step $VM + sqlite3_finalize $VM + db eval {SELECT * FROM t4} +} {1 2 3 4 8 5 6 7} +do_test bind-15.2 { + db eval {DELETE FROM t4} + set VM [sqlite3_prepare db { + INSERT INTO t4(a,b,c,d,e,f,g,h) VALUES(?,?,?,?,?,?,?,?) + } -1 TAIL] + sqlite3_bind_int $VM 1 1 + sqlite3_bind_int $VM 2 2 + sqlite3_bind_int $VM 3 3 + sqlite3_bind_int $VM 4 4 + sqlite3_bind_int $VM 5 5 + sqlite3_bind_int $VM 6 6 + sqlite3_bind_int $VM 7 7 + sqlite3_bind_int $VM 8 8 + sqlite3_step $VM + sqlite3_finalize $VM + db eval {SELECT * FROM t4} +} {1 2 3 4 5 6 7 8} +do_test bind-15.3 { + db eval {DELETE FROM t4} + set VM [sqlite3_prepare db { + INSERT INTO t4(h,g,f,e,d,c,b,a) VALUES(?,?,?,?,?,?,?,?) + } -1 TAIL] + sqlite3_bind_int $VM 1 1 + sqlite3_bind_int $VM 2 2 + sqlite3_bind_int $VM 3 3 + sqlite3_bind_int $VM 4 4 + sqlite3_bind_int $VM 5 5 + sqlite3_bind_int $VM 6 6 + sqlite3_bind_int $VM 7 7 + sqlite3_bind_int $VM 8 8 + sqlite3_step $VM + sqlite3_finalize $VM + db eval {SELECT * FROM t4} +} {8 7 6 5 4 3 2 1} +do_test bind-15.4 { + db eval {DELETE FROM t4} + set VM [sqlite3_prepare db { + INSERT INTO t4(a,b,c,d,e,f,g,h) VALUES(?,?,?,?4,?,?6,?,?) + } -1 TAIL] + sqlite3_bind_int $VM 1 1 + sqlite3_bind_int $VM 2 2 + sqlite3_bind_int $VM 3 3 + sqlite3_bind_int $VM 4 4 + sqlite3_bind_int $VM 5 5 + sqlite3_bind_int $VM 6 6 + sqlite3_bind_int $VM 7 7 + sqlite3_bind_int $VM 8 8 + sqlite3_step $VM + sqlite3_finalize $VM + db eval {SELECT * FROM t4} +} {1 2 3 4 5 6 7 8} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/bindxfer.test b/components/external/SQLite-3.8.1/test/bindxfer.test new file mode 100644 index 0000000000000000000000000000000000000000..393aab96d4e4132fab75f01d91fa3badf72db7af --- /dev/null +++ b/components/external/SQLite-3.8.1/test/bindxfer.test @@ -0,0 +1,76 @@ +# 2005 April 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the sqlite_transfer_bindings() API. +# +# $Id: bindxfer.test,v 1.9 2009/04/17 11:56:28 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc sqlite_step {stmt VALS COLS} { + upvar #0 $VALS vals + upvar #0 $COLS cols + set vals [list] + set cols [list] + + set rc [sqlite3_step $stmt] + for {set i 0} {$i < [sqlite3_column_count $stmt]} {incr i} { + lappend cols [sqlite3_column_name $stmt $i] + } + for {set i 0} {$i < [sqlite3_data_count $stmt]} {incr i} { + lappend vals [sqlite3_column_text $stmt $i] + } + + return $rc +} + +do_test bindxfer-1.1 { + set DB [sqlite3_connection_pointer db] + execsql {CREATE TABLE t1(a,b,c);} + set VM1 [sqlite3_prepare $DB {SELECT ?, ?, ?} -1 TAIL] + set TAIL +} {} +do_test bindxfer-1.2 { + sqlite3_bind_parameter_count $VM1 +} 3 +do_test bindxfer-1.3 { + set VM2 [sqlite3_prepare $DB {SELECT ?, ?, ?} -1 TAIL] + set TAIL +} {} +do_test bindxfer-1.4 { + sqlite3_bind_parameter_count $VM2 +} 3 +ifcapable deprecated { + do_test bindxfer-1.5 { + sqlite_bind $VM1 1 one normal + set sqlite_static_bind_value two + sqlite_bind $VM1 2 {} static + sqlite_bind $VM1 3 {} null + sqlite3_transfer_bindings $VM1 $VM2 + sqlite_step $VM1 VALUES COLNAMES + } SQLITE_ROW + do_test bindxfer-1.6 { + set VALUES + } {{} {} {}} + do_test bindxfer-1.7 { + sqlite_step $VM2 VALUES COLNAMES + } SQLITE_ROW + do_test bindxfer-1.8 { + set VALUES + } {one two {}} +} +catch {sqlite3_finalize $VM1} +catch {sqlite3_finalize $VM2} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/bitvec.test b/components/external/SQLite-3.8.1/test/bitvec.test new file mode 100644 index 0000000000000000000000000000000000000000..d27f9274563ef435e6dd14dd64e028e50dcf7ceb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/bitvec.test @@ -0,0 +1,195 @@ +# 2008 February 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Unit testing of the Bitvec object. +# +# $Id: bitvec.test,v 1.4 2009/04/01 23:49:04 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# The built-in test logic must be operational in order for +# this test to work. +ifcapable !builtin_test { + finish_test + return +} + +# Test that sqlite3BitvecBuiltinTest correctly reports errors +# that are deliberately introduced. +# +do_test bitvec-1.0.1 { + sqlite3BitvecBuiltinTest 400 {5 1 1 1 0} +} 1 +do_test bitvec-1.0.2 { + sqlite3BitvecBuiltinTest 400 {5 1 234 1 0} +} 234 + +# Run test cases that set every bit in vectors of various sizes. +# for larger cases, this should cycle the bit vector representation +# from hashing into subbitmaps. The subbitmaps should start as +# hashes then change to either subbitmaps or linear maps, depending +# on their size. +# +do_test bitvec-1.1 { + sqlite3BitvecBuiltinTest 400 {1 400 1 1 0} +} 0 +do_test bitvec-1.2 { + sqlite3BitvecBuiltinTest 4000 {1 4000 1 1 0} +} 0 +do_test bitvec-1.3 { + sqlite3BitvecBuiltinTest 40000 {1 40000 1 1 0} +} 0 +do_test bitvec-1.4 { + sqlite3BitvecBuiltinTest 400000 {1 400000 1 1 0} +} 0 + +# By specifying a larger increments, we spread the load around. +# +do_test bitvec-1.5 { + sqlite3BitvecBuiltinTest 400 {1 400 1 7 0} +} 0 +do_test bitvec-1.6 { + sqlite3BitvecBuiltinTest 4000 {1 4000 1 7 0} +} 0 +do_test bitvec-1.7 { + sqlite3BitvecBuiltinTest 40000 {1 40000 1 7 0} +} 0 +do_test bitvec-1.8 { + sqlite3BitvecBuiltinTest 400000 {1 400000 1 7 0} +} 0 + +# First fill up the bitmap with ones, then go through and +# clear all the bits. This will stress the clearing mechanism. +# +do_test bitvec-1.9 { + sqlite3BitvecBuiltinTest 400 {1 400 1 1 2 400 1 1 0} +} 0 +do_test bitvec-1.10 { + sqlite3BitvecBuiltinTest 4000 {1 4000 1 1 2 4000 1 1 0} +} 0 +do_test bitvec-1.11 { + sqlite3BitvecBuiltinTest 40000 {1 40000 1 1 2 40000 1 1 0} +} 0 +do_test bitvec-1.12 { + sqlite3BitvecBuiltinTest 400000 {1 400000 1 1 2 400000 1 1 0} +} 0 + +do_test bitvec-1.13 { + sqlite3BitvecBuiltinTest 400 {1 400 1 1 2 400 1 7 0} +} 0 +do_test bitvec-1.15 { + sqlite3BitvecBuiltinTest 4000 {1 4000 1 1 2 4000 1 7 0} +} 0 +do_test bitvec-1.16 { + sqlite3BitvecBuiltinTest 40000 {1 40000 1 1 2 40000 1 77 0} +} 0 +do_test bitvec-1.17 { + sqlite3BitvecBuiltinTest 400000 {1 400000 1 1 2 400000 1 777 0} +} 0 + +do_test bitvec-1.18 { + sqlite3BitvecBuiltinTest 400000 {1 5000 100000 1 2 400000 1 37 0} +} 0 + +# Attempt to induce hash collisions. +# +unset -nocomplain start +unset -nocomplain incr +foreach start {1 2 3 4 5 6 7 8} { + foreach incr {124 125} { + do_test bitvec-1.20.$start.$incr { + set prog [list 1 60 $::start $::incr 2 5000 1 1 0] + sqlite3BitvecBuiltinTest 5000 $prog + } 0 + } +} + +do_test bitvec-1.30.big_and_slow { + sqlite3BitvecBuiltinTest 17000000 {1 17000000 1 1 2 17000000 1 1 0} +} 0 + + +# Test setting and clearing a random subset of bits. +# +do_test bitvec-2.1 { + sqlite3BitvecBuiltinTest 4000 {3 2000 4 2000 0} +} 0 +do_test bitvec-2.2 { + sqlite3BitvecBuiltinTest 4000 {3 1000 4 1000 3 1000 4 1000 3 1000 4 1000 + 3 1000 4 1000 3 1000 4 1000 3 1000 4 1000 0} +} 0 +do_test bitvec-2.3 { + sqlite3BitvecBuiltinTest 400000 {3 10 0} +} 0 +do_test bitvec-2.4 { + sqlite3BitvecBuiltinTest 4000 {3 10 2 4000 1 1 0} +} 0 +do_test bitvec-2.5 { + sqlite3BitvecBuiltinTest 5000 {3 20 2 5000 1 1 0} +} 0 +do_test bitvec-2.6 { + sqlite3BitvecBuiltinTest 50000 {3 60 2 50000 1 1 0} +} 0 +do_test bitvec-2.7 { + sqlite3BitvecBuiltinTest 5000 { + 1 25 121 125 + 1 50 121 125 + 2 25 121 125 + 0 + } +} 0 + +# This procedure runs sqlite3BitvecBuiltinTest with argments "n" and +# "program". But it also causes a malloc error to occur after the +# "failcnt"-th malloc. The result should be "0" if no malloc failure +# occurs or "-1" if there is a malloc failure. +# +proc bitvec_malloc_test {label failcnt n program} { + do_test $label [subst { + sqlite3_memdebug_fail $failcnt + set x \[sqlite3BitvecBuiltinTest $n [list $program]\] + set nFail \[sqlite3_memdebug_fail -1\] + if {\$nFail==0} { + set ::go 0 + set x -1 + } + set x + }] -1 +} + +# Make sure malloc failures are handled sanily. +# +unset -nocomplain n +unset -nocomplain go +set go 1 +save_prng_state +for {set n 0} {$go} {incr n} { + restore_prng_state + bitvec_malloc_test bitvec-3.1.$n $n 5000 { + 3 60 2 5000 1 1 3 60 2 5000 1 1 3 60 2 5000 1 1 0 + } +} +set go 1 +for {set n 0} {$go} {incr n} { + restore_prng_state + bitvec_malloc_test bitvec-3.2.$n $n 5000 { + 3 600 2 5000 1 1 3 600 2 5000 1 1 3 600 2 5000 1 1 0 + } +} +set go 1 +for {set n 1} {$go} {incr n} { + bitvec_malloc_test bitvec-3.3.$n $n 50000 {1 50000 1 1 0} +} + +finish_test +return diff --git a/components/external/SQLite-3.8.1/test/blob.test b/components/external/SQLite-3.8.1/test/blob.test new file mode 100644 index 0000000000000000000000000000000000000000..b1aae381a9f16b5c1688a812f6725a795f14ed98 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/blob.test @@ -0,0 +1,147 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# $Id: blob.test,v 1.8 2009/04/28 18:00:27 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!bloblit} { + finish_test + return +} + +proc bin_to_hex {blob} { + set bytes {} + binary scan $blob \c* bytes + set bytes2 [list] + foreach b $bytes {lappend bytes2 [format %02X [expr $b & 0xFF]]} + join $bytes2 {} +} + +# Simplest possible case. Specify a blob literal +do_test blob-1.0 { + set blob [execsql {SELECT X'01020304';}] + bin_to_hex [lindex $blob 0] +} {01020304} +do_test blob-1.1 { + set blob [execsql {SELECT x'ABCDEF';}] + bin_to_hex [lindex $blob 0] +} {ABCDEF} +do_test blob-1.2 { + set blob [execsql {SELECT x'';}] + bin_to_hex [lindex $blob 0] +} {} +do_test blob-1.3 { + set blob [execsql {SELECT x'abcdEF12';}] + bin_to_hex [lindex $blob 0] +} {ABCDEF12} +do_test blob-1.3.2 { + set blob [execsql {SELECT x'0123456789abcdefABCDEF';}] + bin_to_hex [lindex $blob 0] +} {0123456789ABCDEFABCDEF} + +# Try some syntax errors in blob literals. +do_test blob-1.4 { + catchsql {SELECT X'01020k304', 100} +} {1 {unrecognized token: "X'01020k304'"}} +do_test blob-1.5 { + catchsql {SELECT X'01020, 100} +} {1 {unrecognized token: "X'01020, 100"}} +do_test blob-1.6 { + catchsql {SELECT X'01020 100'} +} {1 {unrecognized token: "X'01020 100'"}} +do_test blob-1.7 { + catchsql {SELECT X'01001'} +} {1 {unrecognized token: "X'01001'"}} +do_test blob-1.8 { + catchsql {SELECT x'012/45'} +} {1 {unrecognized token: "x'012/45'"}} +do_test blob-1.9 { + catchsql {SELECT x'012:45'} +} {1 {unrecognized token: "x'012:45'"}} +do_test blob-1.10 { + catchsql {SELECT x'012@45'} +} {1 {unrecognized token: "x'012@45'"}} +do_test blob-1.11 { + catchsql {SELECT x'012G45'} +} {1 {unrecognized token: "x'012G45'"}} +do_test blob-1.12 { + catchsql {SELECT x'012`45'} +} {1 {unrecognized token: "x'012`45'"}} +do_test blob-1.13 { + catchsql {SELECT x'012g45'} +} {1 {unrecognized token: "x'012g45'"}} + + +# Insert a blob into a table and retrieve it. +do_test blob-2.0 { + execsql { + CREATE TABLE t1(a BLOB, b BLOB); + INSERT INTO t1 VALUES(X'123456', x'7890ab'); + INSERT INTO t1 VALUES(X'CDEF12', x'345678'); + } + set blobs [execsql {SELECT * FROM t1}] + set blobs2 [list] + foreach b $blobs {lappend blobs2 [bin_to_hex $b]} + set blobs2 +} {123456 7890AB CDEF12 345678} + +# An index on a blob column +do_test blob-2.1 { + execsql { + CREATE INDEX i1 ON t1(a); + } + set blobs [execsql {SELECT * FROM t1}] + set blobs2 [list] + foreach b $blobs {lappend blobs2 [bin_to_hex $b]} + set blobs2 +} {123456 7890AB CDEF12 345678} +do_test blob-2.2 { + set blobs [execsql {SELECT * FROM t1 where a = X'123456'}] + set blobs2 [list] + foreach b $blobs {lappend blobs2 [bin_to_hex $b]} + set blobs2 +} {123456 7890AB} +do_test blob-2.3 { + set blobs [execsql {SELECT * FROM t1 where a = X'CDEF12'}] + set blobs2 [list] + foreach b $blobs {lappend blobs2 [bin_to_hex $b]} + set blobs2 +} {CDEF12 345678} +do_test blob-2.4 { + set blobs [execsql {SELECT * FROM t1 where a = X'CD12'}] + set blobs2 [list] + foreach b $blobs {lappend blobs2 [bin_to_hex $b]} + set blobs2 +} {} + +# Try to bind a blob value to a prepared statement. +do_test blob-3.0 { + sqlite3 db2 test.db + set DB [sqlite3_connection_pointer db2] + set STMT [sqlite3_prepare $DB "DELETE FROM t1 WHERE a = ?" -1 DUMMY] + sqlite3_bind_blob $STMT 1 "\x12\x34\x56" 3 + sqlite3_step $STMT +} {SQLITE_DONE} +do_test blob-3.1 { + sqlite3_finalize $STMT + db2 close +} {} +do_test blob-3.2 { + set blobs [execsql {SELECT * FROM t1}] + set blobs2 [list] + foreach b $blobs {lappend blobs2 [bin_to_hex $b]} + set blobs2 +} {CDEF12 345678} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/boundary1.tcl b/components/external/SQLite-3.8.1/test/boundary1.tcl new file mode 100644 index 0000000000000000000000000000000000000000..3896b50463844ecf2bdb2110990e40fe0aa60e14 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/boundary1.tcl @@ -0,0 +1,289 @@ +puts {# 2008 December 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is automatically generated from a separate TCL script. +# This file seeks to exercise integer boundary values. +# +# $Id: boundary1.tcl,v 1.3 2009/01/02 15:45:48 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Many of the boundary tests depend on a working 64-bit implementation. +if {![working_64bit_int]} { finish_test; return } +} + +expr srand(0) + +# Generate interesting boundary numbers +# +foreach x { + 0 + 1 + 0x7f + 0x7fff + 0x7fffff + 0x7fffffff + 0x7fffffffff + 0x7fffffffffff + 0x7fffffffffffff + 0x7fffffffffffffff +} { + set x [expr {wide($x)}] + set boundarynum($x) 1 + set boundarynum([expr {$x+1}]) 1 + set boundarynum([expr {-($x+1)}]) 1 + set boundarynum([expr {-($x+2)}]) 1 + set boundarynum([expr {$x+$x+1}]) 1 + set boundarynum([expr {$x+$x+2}]) 1 +} +set x [expr {wide(127)}] +for {set i 1} {$i<=9} {incr i} { + set boundarynum($x) 1 + set boundarynum([expr {$x+1}]) 1 + set x [expr {wide($x*128 + 127)}] +} + +# Scramble the $inlist into a random order. +# +proc scramble {inlist} { + set y {} + foreach x $inlist { + lappend y [list [expr {rand()}] $x] + } + set y [lsort $y] + set outlist {} + foreach x $y { + lappend outlist [lindex $x 1] + } + return $outlist +} + +# A simple selection sort. Not trying to be efficient. +# +proc sort {inlist} { + set outlist {} + set mn [lindex $inlist 0] + foreach x $inlist { + if {$x<$mn} {set mn $x} + } + set outlist $mn + set mx $mn + while {1} { + set valid 0 + foreach x $inlist { + if {$x>$mx && (!$valid || $mn>$x)} { + set mn $x + set valid 1 + } + } + if {!$valid} break + lappend outlist $mn + set mx $mn + } + return $outlist +} + +# Reverse the order of a list +# +proc reverse {inlist} { + set i [llength $inlist] + set outlist {} + for {incr i -1} {$i>=0} {incr i -1} { + lappend outlist [lindex $inlist $i] + } + return $outlist +} + +set nums1 [scramble [array names boundarynum]] +set nums2 [scramble [array names boundarynum]] + +set tname boundary1 +puts "do_test $tname-1.1 \173" +puts " db eval \173" +puts " CREATE TABLE t1(a,x);" +set a 0 +foreach r $nums1 { + incr a + set t1ra($r) $a + set t1ar($a) $r + set x [format %08x%08x [expr {wide($r)>>32}] $r] + set t1rx($r) $x + set t1xr($x) $r + puts " INSERT INTO t1(oid,a,x) VALUES($r,$a,'$x');" +} +puts " CREATE INDEX t1i1 ON t1(a);" +puts " CREATE INDEX t1i2 ON t1(x);" +puts " \175" +puts "\175 {}" + +puts "do_test $tname-1.2 \173" +puts " db eval \173" +puts " SELECT count(*) FROM t1" +puts " \175" +puts "\175 {64}" + +set nums3 $nums2 +lappend nums3 9.22337303685477580800e+18 +lappend nums3 -9.22337303685477580800e+18 + +set i 0 +foreach r $nums3 { + incr i + + if {abs($r)<9.22337203685477580800e+18} { + set x $t1rx($r) + set a $t1ra($r) + set r5 $r.5 + set r0 $r.0 + puts "do_test $tname-2.$i.1 \173" + puts " db eval \173" + puts " SELECT * FROM t1 WHERE rowid=$r" + puts " \175" + puts "\175 {$a $x}" + puts "do_test $tname-2.$i.2 \173" + puts " db eval \173" + puts " SELECT rowid, a FROM t1 WHERE x='$x'" + puts " \175" + puts "\175 {$r $a}" + puts "do_test $tname-2.$i.3 \173" + puts " db eval \173" + puts " SELECT rowid, x FROM t1 WHERE a=$a" + puts " \175" + puts "\175 {$r $x}" + } + + foreach op {> >= < <=} subno {gt ge lt le} { + + ################################################################ 2.x.y.1 + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r" { + lappend rset $rx + lappend aset $t1ra($rx) + } + } + puts "do_test $tname-2.$i.$subno.1 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE rowid $op $r ORDER BY a" + puts " \175" + puts "\175 {[sort $aset]}" + + ################################################################ 2.x.y.2 + puts "do_test $tname-2.$i.$subno.2 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE rowid $op $r ORDER BY a DESC" + puts " \175" + puts "\175 {[reverse [sort $aset]]}" + + ################################################################ 2.x.y.3 + set aset {} + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.3 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE rowid $op $r ORDER BY rowid" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.4 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.4 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE rowid $op $r ORDER BY rowid DESC" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.5 + set aset {} + set xset {} + foreach rx $rset { + lappend xset $t1rx($rx) + } + foreach x [sort $xset] { + set rx $t1xr($x) + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.5 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE rowid $op $r ORDER BY x" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.10 + if {abs($r)>9223372036854775808 || [string length $r5]>15} continue + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r0" { + lappend rset $rx + } + } + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.10 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE rowid $op $r0 ORDER BY rowid" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.11 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.11 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE rowid $op $r0 ORDER BY rowid DESC" + puts " \175" + puts "\175 {$aset}" + + + ################################################################ 2.x.y.12 + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r5" { + lappend rset $rx + } + } + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.12 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE rowid $op $r5 ORDER BY rowid" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.13 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.13 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE rowid $op $r5 ORDER BY rowid DESC" + puts " \175" + puts "\175 {$aset}" + } + +} + + +puts {finish_test} diff --git a/components/external/SQLite-3.8.1/test/boundary1.test b/components/external/SQLite-3.8.1/test/boundary1.test new file mode 100644 index 0000000000000000000000000000000000000000..0e2458c15e31c440d0f22e7d3e99497db81e6e59 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/boundary1.test @@ -0,0 +1,7645 @@ +# 2008 December 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is automatically generated from a separate TCL script. +# This file seeks to exercise integer boundary values. +# +# $Id: boundary1.test,v 1.2 2009/01/02 15:45:48 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Many of the boundary tests depend on a working 64-bit implementation. +if {![working_64bit_int]} { finish_test; return } + +do_test boundary1-1.1 { + db eval { + CREATE TABLE t1(a,x); + INSERT INTO t1(oid,a,x) VALUES(-8388609,1,'ffffffffff7fffff'); + INSERT INTO t1(oid,a,x) VALUES(-36028797018963969,2,'ff7fffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(9223372036854775807,3,'7fffffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(127,4,'000000000000007f'); + INSERT INTO t1(oid,a,x) VALUES(3,5,'0000000000000003'); + INSERT INTO t1(oid,a,x) VALUES(16777216,6,'0000000001000000'); + INSERT INTO t1(oid,a,x) VALUES(4398046511103,7,'000003ffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(16383,8,'0000000000003fff'); + INSERT INTO t1(oid,a,x) VALUES(16777215,9,'0000000000ffffff'); + INSERT INTO t1(oid,a,x) VALUES(281474976710655,10,'0000ffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-2147483648,11,'ffffffff80000000'); + INSERT INTO t1(oid,a,x) VALUES(268435455,12,'000000000fffffff'); + INSERT INTO t1(oid,a,x) VALUES(562949953421311,13,'0001ffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(4294967295,14,'00000000ffffffff'); + INSERT INTO t1(oid,a,x) VALUES(2097151,15,'00000000001fffff'); + INSERT INTO t1(oid,a,x) VALUES(16384,16,'0000000000004000'); + INSERT INTO t1(oid,a,x) VALUES(72057594037927935,17,'00ffffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(8388607,18,'00000000007fffff'); + INSERT INTO t1(oid,a,x) VALUES(1099511627776,19,'0000010000000000'); + INSERT INTO t1(oid,a,x) VALUES(2147483647,20,'000000007fffffff'); + INSERT INTO t1(oid,a,x) VALUES(-140737488355329,21,'ffff7fffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(34359738368,22,'0000000800000000'); + INSERT INTO t1(oid,a,x) VALUES(32767,23,'0000000000007fff'); + INSERT INTO t1(oid,a,x) VALUES(8388608,24,'0000000000800000'); + INSERT INTO t1(oid,a,x) VALUES(140737488355327,25,'00007fffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(281474976710656,26,'0001000000000000'); + INSERT INTO t1(oid,a,x) VALUES(36028797018963967,27,'007fffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(72057594037927936,28,'0100000000000000'); + INSERT INTO t1(oid,a,x) VALUES(-32769,29,'ffffffffffff7fff'); + INSERT INTO t1(oid,a,x) VALUES(255,30,'00000000000000ff'); + INSERT INTO t1(oid,a,x) VALUES(4,31,'0000000000000004'); + INSERT INTO t1(oid,a,x) VALUES(-32768,32,'ffffffffffff8000'); + INSERT INTO t1(oid,a,x) VALUES(-2,33,'fffffffffffffffe'); + INSERT INTO t1(oid,a,x) VALUES(140737488355328,34,'0000800000000000'); + INSERT INTO t1(oid,a,x) VALUES(549755813888,35,'0000008000000000'); + INSERT INTO t1(oid,a,x) VALUES(4294967296,36,'0000000100000000'); + INSERT INTO t1(oid,a,x) VALUES(-8388608,37,'ffffffffff800000'); + INSERT INTO t1(oid,a,x) VALUES(-1,38,'ffffffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(34359738367,39,'00000007ffffffff'); + INSERT INTO t1(oid,a,x) VALUES(268435456,40,'0000000010000000'); + INSERT INTO t1(oid,a,x) VALUES(2,41,'0000000000000002'); + INSERT INTO t1(oid,a,x) VALUES(2097152,42,'0000000000200000'); + INSERT INTO t1(oid,a,x) VALUES(562949953421312,43,'0002000000000000'); + INSERT INTO t1(oid,a,x) VALUES(-140737488355328,44,'ffff800000000000'); + INSERT INTO t1(oid,a,x) VALUES(36028797018963968,45,'0080000000000000'); + INSERT INTO t1(oid,a,x) VALUES(549755813887,46,'0000007fffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-2147483649,47,'ffffffff7fffffff'); + INSERT INTO t1(oid,a,x) VALUES(65535,48,'000000000000ffff'); + INSERT INTO t1(oid,a,x) VALUES(128,49,'0000000000000080'); + INSERT INTO t1(oid,a,x) VALUES(32768,50,'0000000000008000'); + INSERT INTO t1(oid,a,x) VALUES(2147483648,51,'0000000080000000'); + INSERT INTO t1(oid,a,x) VALUES(-3,52,'fffffffffffffffd'); + INSERT INTO t1(oid,a,x) VALUES(-128,53,'ffffffffffffff80'); + INSERT INTO t1(oid,a,x) VALUES(-129,54,'ffffffffffffff7f'); + INSERT INTO t1(oid,a,x) VALUES(-9223372036854775808,55,'8000000000000000'); + INSERT INTO t1(oid,a,x) VALUES(4398046511104,56,'0000040000000000'); + INSERT INTO t1(oid,a,x) VALUES(1099511627775,57,'000000ffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-549755813889,58,'ffffff7fffffffff'); + INSERT INTO t1(oid,a,x) VALUES(0,59,'0000000000000000'); + INSERT INTO t1(oid,a,x) VALUES(1,60,'0000000000000001'); + INSERT INTO t1(oid,a,x) VALUES(256,61,'0000000000000100'); + INSERT INTO t1(oid,a,x) VALUES(65536,62,'0000000000010000'); + INSERT INTO t1(oid,a,x) VALUES(-549755813888,63,'ffffff8000000000'); + INSERT INTO t1(oid,a,x) VALUES(-36028797018963968,64,'ff80000000000000'); + CREATE INDEX t1i1 ON t1(a); + CREATE INDEX t1i2 ON t1(x); + } +} {} +do_test boundary1-1.2 { + db eval { + SELECT count(*) FROM t1 + } +} {64} +do_test boundary1-2.1.1 { + db eval { + SELECT * FROM t1 WHERE rowid=72057594037927935 + } +} {17 00ffffffffffffff} +do_test boundary1-2.1.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='00ffffffffffffff' + } +} {72057594037927935 17} +do_test boundary1-2.1.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=17 + } +} {72057594037927935 00ffffffffffffff} +do_test boundary1-2.1.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY a + } +} {3 28} +do_test boundary1-2.1.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY a DESC + } +} {28 3} +do_test boundary1-2.1.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY rowid + } +} {28 3} +do_test boundary1-2.1.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY rowid DESC + } +} {3 28} +do_test boundary1-2.1.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927935 ORDER BY x + } +} {28 3} +do_test boundary1-2.1.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY a + } +} {3 17 28} +do_test boundary1-2.1.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY a DESC + } +} {28 17 3} +do_test boundary1-2.1.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY rowid + } +} {17 28 3} +do_test boundary1-2.1.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY rowid DESC + } +} {3 28 17} +do_test boundary1-2.1.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927935 ORDER BY x + } +} {17 28 3} +do_test boundary1-2.1.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.1.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.1.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45} +do_test boundary1-2.1.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY rowid DESC + } +} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.1.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927935 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.1.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.1.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.1.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17} +do_test boundary1-2.1.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY rowid DESC + } +} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.1.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927935 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.2.1 { + db eval { + SELECT * FROM t1 WHERE rowid=16384 + } +} {16 0000000000004000} +do_test boundary1-2.2.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000004000' + } +} {16384 16} +do_test boundary1-2.2.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=16 + } +} {16384 0000000000004000} +do_test boundary1-2.2.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 16384 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary1-2.2.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 16384 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.2.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 16384 ORDER BY rowid + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.2.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 16384 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary1-2.2.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 16384 ORDER BY x + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.2.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary1-2.2.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.2.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY rowid + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.2.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary1-2.2.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16384 ORDER BY x + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.2.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 16384 ORDER BY a + } +} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.2.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 16384 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1} +do_test boundary1-2.2.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 16384 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary1-2.2.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 16384 ORDER BY rowid DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.2.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 16384 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.2.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY a + } +} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.2.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1} +do_test boundary1-2.2.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary1-2.2.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY rowid DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.2.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16384 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.3.1 { + db eval { + SELECT * FROM t1 WHERE rowid=4294967296 + } +} {36 0000000100000000} +do_test boundary1-2.3.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000100000000' + } +} {4294967296 36} +do_test boundary1-2.3.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=36 + } +} {4294967296 0000000100000000} +do_test boundary1-2.3.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57} +do_test boundary1-2.3.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY a DESC + } +} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary1-2.3.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY rowid + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.3.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary1-2.3.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967296 ORDER BY x + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.3.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary1-2.3.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary1-2.3.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY rowid + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.3.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary1-2.3.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967296 ORDER BY x + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.3.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.3.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.3.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary1-2.3.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY rowid DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.3.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967296 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.3.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.3.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.3.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary1-2.3.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY rowid DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.3.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967296 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.4.1 { + db eval { + SELECT * FROM t1 WHERE rowid=16777216 + } +} {6 0000000001000000} +do_test boundary1-2.4.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000001000000' + } +} {16777216 6} +do_test boundary1-2.4.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=6 + } +} {16777216 0000000001000000} +do_test boundary1-2.4.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY a + } +} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.4.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3} +do_test boundary1-2.4.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY rowid + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.4.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary1-2.4.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777216 ORDER BY x + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.4.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY a + } +} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.4.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3} +do_test boundary1-2.4.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY rowid + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.4.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary1-2.4.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777216 ORDER BY x + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.4.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY a + } +} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.4.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1} +do_test boundary1-2.4.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary1-2.4.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY rowid DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.4.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777216 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.4.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY a + } +} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.4.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1} +do_test boundary1-2.4.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary1-2.4.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY rowid DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.4.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777216 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.5.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-32769 + } +} {29 ffffffffffff7fff} +do_test boundary1-2.5.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffffffffff7fff' + } +} {-32769 29} +do_test boundary1-2.5.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=29 + } +} {-32769 ffffffffffff7fff} +do_test boundary1-2.5.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -32769 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.5.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -32769 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.5.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -32769 ORDER BY rowid + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.5.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -32769 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary1-2.5.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -32769 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38} +do_test boundary1-2.5.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.5.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.5.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY rowid + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.5.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary1-2.5.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32769 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38} +do_test boundary1-2.5.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -32769 ORDER BY a + } +} {1 2 11 21 37 44 47 55 58 63 64} +do_test boundary1-2.5.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -32769 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 21 11 2 1} +do_test boundary1-2.5.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -32769 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary1-2.5.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -32769 ORDER BY rowid DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.5.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -32769 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary1-2.5.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY a + } +} {1 2 11 21 29 37 44 47 55 58 63 64} +do_test boundary1-2.5.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 29 21 11 2 1} +do_test boundary1-2.5.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary1-2.5.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY rowid DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.5.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32769 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary1-2.6.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-140737488355329 + } +} {21 ffff7fffffffffff} +do_test boundary1-2.6.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffff7fffffffffff' + } +} {-140737488355329 21} +do_test boundary1-2.6.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=21 + } +} {-140737488355329 ffff7fffffffffff} +do_test boundary1-2.6.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary1-2.6.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.6.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY rowid + } +} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.6.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44} +do_test boundary1-2.6.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355329 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.6.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary1-2.6.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.6.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY rowid + } +} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.6.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21} +do_test boundary1-2.6.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355329 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.6.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY a + } +} {2 55 64} +do_test boundary1-2.6.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY a DESC + } +} {64 55 2} +do_test boundary1-2.6.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY rowid + } +} {55 2 64} +do_test boundary1-2.6.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY rowid DESC + } +} {64 2 55} +do_test boundary1-2.6.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355329 ORDER BY x + } +} {55 2 64} +do_test boundary1-2.6.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY a + } +} {2 21 55 64} +do_test boundary1-2.6.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY a DESC + } +} {64 55 21 2} +do_test boundary1-2.6.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY rowid + } +} {55 2 64 21} +do_test boundary1-2.6.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY rowid DESC + } +} {21 64 2 55} +do_test boundary1-2.6.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355329 ORDER BY x + } +} {55 2 64 21} +do_test boundary1-2.7.1 { + db eval { + SELECT * FROM t1 WHERE rowid=2 + } +} {41 0000000000000002} +do_test boundary1-2.7.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000000002' + } +} {2 41} +do_test boundary1-2.7.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=41 + } +} {2 0000000000000002} +do_test boundary1-2.7.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.7.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 2 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.7.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 2 ORDER BY rowid + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.7.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 2 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary1-2.7.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 2 ORDER BY x + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.7.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.7.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.7.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2 ORDER BY rowid + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.7.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary1-2.7.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2 ORDER BY x + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.7.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 2 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.7.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 2 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary1-2.7.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 2 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary1-2.7.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 2 ORDER BY rowid DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.7.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 2 ORDER BY x + } +} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.7.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.7.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1} +do_test boundary1-2.7.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary1-2.7.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2 ORDER BY rowid DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.7.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2 ORDER BY x + } +} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.8.1 { + db eval { + SELECT * FROM t1 WHERE rowid=4 + } +} {31 0000000000000004} +do_test boundary1-2.8.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000000004' + } +} {4 31} +do_test boundary1-2.8.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=31 + } +} {4 0000000000000004} +do_test boundary1-2.8.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 4 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.8.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 4 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary1-2.8.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 4 ORDER BY rowid + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.8.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 4 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary1-2.8.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 4 ORDER BY x + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.8.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.8.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary1-2.8.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4 ORDER BY rowid + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.8.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary1-2.8.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4 ORDER BY x + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.8.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 4 ORDER BY a + } +} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.8.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 4 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1} +do_test boundary1-2.8.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 4 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary1-2.8.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 4 ORDER BY rowid DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.8.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 4 ORDER BY x + } +} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.8.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4 ORDER BY a + } +} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.8.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1} +do_test boundary1-2.8.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary1-2.8.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4 ORDER BY rowid DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.8.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4 ORDER BY x + } +} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.9.1 { + db eval { + SELECT * FROM t1 WHERE rowid=562949953421311 + } +} {13 0001ffffffffffff} +do_test boundary1-2.9.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0001ffffffffffff' + } +} {562949953421311 13} +do_test boundary1-2.9.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=13 + } +} {562949953421311 0001ffffffffffff} +do_test boundary1-2.9.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY a + } +} {3 17 27 28 43 45} +do_test boundary1-2.9.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY a DESC + } +} {45 43 28 27 17 3} +do_test boundary1-2.9.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY rowid + } +} {43 27 45 17 28 3} +do_test boundary1-2.9.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY rowid DESC + } +} {3 28 17 45 27 43} +do_test boundary1-2.9.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421311 ORDER BY x + } +} {43 27 45 17 28 3} +do_test boundary1-2.9.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY a + } +} {3 13 17 27 28 43 45} +do_test boundary1-2.9.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY a DESC + } +} {45 43 28 27 17 13 3} +do_test boundary1-2.9.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY rowid + } +} {13 43 27 45 17 28 3} +do_test boundary1-2.9.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13} +do_test boundary1-2.9.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421311 ORDER BY x + } +} {13 43 27 45 17 28 3} +do_test boundary1-2.9.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.9.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.9.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26} +do_test boundary1-2.9.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY rowid DESC + } +} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.9.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421311 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.9.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.9.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.9.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13} +do_test boundary1-2.9.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY rowid DESC + } +} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.9.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421311 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.10.1 { + db eval { + SELECT * FROM t1 WHERE rowid=256 + } +} {61 0000000000000100} +do_test boundary1-2.10.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000000100' + } +} {256 61} +do_test boundary1-2.10.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=61 + } +} {256 0000000000000100} +do_test boundary1-2.10.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 256 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary1-2.10.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 256 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary1-2.10.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 256 ORDER BY rowid + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.10.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 256 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary1-2.10.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 256 ORDER BY x + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.10.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 256 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary1-2.10.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 256 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary1-2.10.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 256 ORDER BY rowid + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.10.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 256 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary1-2.10.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 256 ORDER BY x + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.10.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 256 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.10.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 256 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary1-2.10.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 256 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary1-2.10.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 256 ORDER BY rowid DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.10.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 256 ORDER BY x + } +} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.10.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 256 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.10.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 256 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary1-2.10.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 256 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary1-2.10.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 256 ORDER BY rowid DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.10.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 256 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.11.1 { + db eval { + SELECT * FROM t1 WHERE rowid=34359738368 + } +} {22 0000000800000000} +do_test boundary1-2.11.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000800000000' + } +} {34359738368 22} +do_test boundary1-2.11.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=22 + } +} {34359738368 0000000800000000} +do_test boundary1-2.11.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary1-2.11.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary1-2.11.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY rowid + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.11.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary1-2.11.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738368 ORDER BY x + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.11.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary1-2.11.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary1-2.11.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY rowid + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.11.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary1-2.11.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738368 ORDER BY x + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.11.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.11.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.11.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary1-2.11.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY rowid DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.11.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738368 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.11.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.11.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.11.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary1-2.11.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY rowid DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.11.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738368 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.12.1 { + db eval { + SELECT * FROM t1 WHERE rowid=65536 + } +} {62 0000000000010000} +do_test boundary1-2.12.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000010000' + } +} {65536 62} +do_test boundary1-2.12.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=62 + } +} {65536 0000000000010000} +do_test boundary1-2.12.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 65536 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary1-2.12.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 65536 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.12.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 65536 ORDER BY rowid + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.12.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 65536 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary1-2.12.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 65536 ORDER BY x + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.12.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62} +do_test boundary1-2.12.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY a DESC + } +} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.12.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY rowid + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.12.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary1-2.12.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65536 ORDER BY x + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.12.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 65536 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.12.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 65536 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary1-2.12.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 65536 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary1-2.12.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 65536 ORDER BY rowid DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.12.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 65536 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.12.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.12.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary1-2.12.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary1-2.12.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY rowid DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.12.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65536 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.13.1 { + db eval { + SELECT * FROM t1 WHERE rowid=268435456 + } +} {40 0000000010000000} +do_test boundary1-2.13.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000010000000' + } +} {268435456 40} +do_test boundary1-2.13.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=40 + } +} {268435456 0000000010000000} +do_test boundary1-2.13.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary1-2.13.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary1-2.13.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY rowid + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.13.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary1-2.13.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435456 ORDER BY x + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.13.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.13.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary1-2.13.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY rowid + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.13.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary1-2.13.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435456 ORDER BY x + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.13.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.13.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.13.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary1-2.13.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY rowid DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.13.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435456 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.13.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.13.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.13.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary1-2.13.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY rowid DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.13.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435456 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.14.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-140737488355328 + } +} {44 ffff800000000000} +do_test boundary1-2.14.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffff800000000000' + } +} {-140737488355328 44} +do_test boundary1-2.14.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=44 + } +} {-140737488355328 ffff800000000000} +do_test boundary1-2.14.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary1-2.14.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.14.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY rowid + } +} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.14.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58} +do_test boundary1-2.14.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.14.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary1-2.14.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.14.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY rowid + } +} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.14.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44} +do_test boundary1-2.14.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.14.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY a + } +} {2 21 55 64} +do_test boundary1-2.14.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY a DESC + } +} {64 55 21 2} +do_test boundary1-2.14.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY rowid + } +} {55 2 64 21} +do_test boundary1-2.14.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY rowid DESC + } +} {21 64 2 55} +do_test boundary1-2.14.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -140737488355328 ORDER BY x + } +} {55 2 64 21} +do_test boundary1-2.14.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY a + } +} {2 21 44 55 64} +do_test boundary1-2.14.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY a DESC + } +} {64 55 44 21 2} +do_test boundary1-2.14.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY rowid + } +} {55 2 64 21 44} +do_test boundary1-2.14.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY rowid DESC + } +} {44 21 64 2 55} +do_test boundary1-2.14.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -140737488355328 ORDER BY x + } +} {55 2 64 21 44} +do_test boundary1-2.15.1 { + db eval { + SELECT * FROM t1 WHERE rowid=1099511627776 + } +} {19 0000010000000000} +do_test boundary1-2.15.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000010000000000' + } +} {1099511627776 19} +do_test boundary1-2.15.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=19 + } +} {1099511627776 0000010000000000} +do_test boundary1-2.15.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY a + } +} {3 7 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary1-2.15.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 7 3} +do_test boundary1-2.15.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY rowid + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.15.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary1-2.15.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627776 ORDER BY x + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.15.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56} +do_test boundary1-2.15.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary1-2.15.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY rowid + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.15.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary1-2.15.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627776 ORDER BY x + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.15.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary1-2.15.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.15.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary1-2.15.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY rowid DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.15.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627776 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.15.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary1-2.15.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.15.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary1-2.15.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY rowid DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.15.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627776 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.16.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY a + } +} {} +do_test boundary1-2.16.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY a DESC + } +} {} +do_test boundary1-2.16.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY rowid + } +} {} +do_test boundary1-2.16.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY rowid DESC + } +} {} +do_test boundary1-2.16.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 9223372036854775807 ORDER BY x + } +} {} +do_test boundary1-2.16.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY a + } +} {3} +do_test boundary1-2.16.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY a DESC + } +} {3} +do_test boundary1-2.16.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY rowid + } +} {3} +do_test boundary1-2.16.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY rowid DESC + } +} {3} +do_test boundary1-2.16.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9223372036854775807 ORDER BY x + } +} {3} +do_test boundary1-2.16.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.16.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.16.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28} +do_test boundary1-2.16.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY rowid DESC + } +} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.16.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 9223372036854775807 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.16.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.16.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary1-2.16.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.16.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.16.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9223372036854775807 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.17.1 { + db eval { + SELECT * FROM t1 WHERE rowid=32768 + } +} {50 0000000000008000} +do_test boundary1-2.17.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000008000' + } +} {32768 50} +do_test boundary1-2.17.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=50 + } +} {32768 0000000000008000} +do_test boundary1-2.17.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 32768 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62} +do_test boundary1-2.17.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 32768 ORDER BY a DESC + } +} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.17.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 32768 ORDER BY rowid + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.17.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 32768 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary1-2.17.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 32768 ORDER BY x + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.17.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary1-2.17.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.17.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY rowid + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.17.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary1-2.17.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32768 ORDER BY x + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.17.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 32768 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.17.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 32768 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary1-2.17.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 32768 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary1-2.17.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 32768 ORDER BY rowid DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.17.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.17.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.17.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary1-2.17.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary1-2.17.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY rowid DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.17.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.18.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-36028797018963968 + } +} {64 ff80000000000000} +do_test boundary1-2.18.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ff80000000000000' + } +} {-36028797018963968 64} +do_test boundary1-2.18.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=64 + } +} {-36028797018963968 ff80000000000000} +do_test boundary1-2.18.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary1-2.18.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.18.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY rowid + } +} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.18.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21} +do_test boundary1-2.18.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.18.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.18.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.18.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY rowid + } +} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.18.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64} +do_test boundary1-2.18.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.18.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY a + } +} {2 55} +do_test boundary1-2.18.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY a DESC + } +} {55 2} +do_test boundary1-2.18.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY rowid + } +} {55 2} +do_test boundary1-2.18.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY rowid DESC + } +} {2 55} +do_test boundary1-2.18.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963968 ORDER BY x + } +} {55 2} +do_test boundary1-2.18.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY a + } +} {2 55 64} +do_test boundary1-2.18.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY a DESC + } +} {64 55 2} +do_test boundary1-2.18.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY rowid + } +} {55 2 64} +do_test boundary1-2.18.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY rowid DESC + } +} {64 2 55} +do_test boundary1-2.18.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963968 ORDER BY x + } +} {55 2 64} +do_test boundary1-2.19.1 { + db eval { + SELECT * FROM t1 WHERE rowid=65535 + } +} {48 000000000000ffff} +do_test boundary1-2.19.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='000000000000ffff' + } +} {65535 48} +do_test boundary1-2.19.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=48 + } +} {65535 000000000000ffff} +do_test boundary1-2.19.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 65535 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62} +do_test boundary1-2.19.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 65535 ORDER BY a DESC + } +} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.19.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 65535 ORDER BY rowid + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.19.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 65535 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary1-2.19.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 65535 ORDER BY x + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.19.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62} +do_test boundary1-2.19.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY a DESC + } +} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.19.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY rowid + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.19.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary1-2.19.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 65535 ORDER BY x + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.19.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 65535 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.19.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 65535 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary1-2.19.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 65535 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary1-2.19.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 65535 ORDER BY rowid DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.19.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 65535 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.19.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.19.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary1-2.19.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary1-2.19.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY rowid DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.19.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 65535 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.20.1 { + db eval { + SELECT * FROM t1 WHERE rowid=4294967295 + } +} {14 00000000ffffffff} +do_test boundary1-2.20.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='00000000ffffffff' + } +} {4294967295 14} +do_test boundary1-2.20.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=14 + } +} {4294967295 00000000ffffffff} +do_test boundary1-2.20.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary1-2.20.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary1-2.20.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY rowid + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.20.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary1-2.20.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 4294967295 ORDER BY x + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.20.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary1-2.20.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary1-2.20.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY rowid + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.20.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary1-2.20.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4294967295 ORDER BY x + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.20.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.20.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.20.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary1-2.20.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY rowid DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.20.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 4294967295 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.20.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.20.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.20.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary1-2.20.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY rowid DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.20.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4294967295 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.21.1 { + db eval { + SELECT * FROM t1 WHERE rowid=1099511627775 + } +} {57 000000ffffffffff} +do_test boundary1-2.21.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='000000ffffffffff' + } +} {1099511627775 57} +do_test boundary1-2.21.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=57 + } +} {1099511627775 000000ffffffffff} +do_test boundary1-2.21.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56} +do_test boundary1-2.21.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary1-2.21.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY rowid + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.21.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary1-2.21.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 1099511627775 ORDER BY x + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.21.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57} +do_test boundary1-2.21.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY a DESC + } +} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary1-2.21.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY rowid + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.21.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary1-2.21.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1099511627775 ORDER BY x + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.21.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.21.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.21.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary1-2.21.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY rowid DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.21.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 1099511627775 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.21.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary1-2.21.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.21.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary1-2.21.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY rowid DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.21.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1099511627775 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.22.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-8388608 + } +} {37 ffffffffff800000} +do_test boundary1-2.22.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffffffff800000' + } +} {-8388608 37} +do_test boundary1-2.22.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=37 + } +} {-8388608 ffffffffff800000} +do_test boundary1-2.22.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.22.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.22.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY rowid + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.22.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary1-2.22.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38} +do_test boundary1-2.22.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.22.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.22.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY rowid + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.22.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary1-2.22.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38} +do_test boundary1-2.22.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY a + } +} {1 2 11 21 44 47 55 58 63 64} +do_test boundary1-2.22.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2 1} +do_test boundary1-2.22.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary1-2.22.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY rowid DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.22.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388608 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary1-2.22.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY a + } +} {1 2 11 21 37 44 47 55 58 63 64} +do_test boundary1-2.22.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 21 11 2 1} +do_test boundary1-2.22.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary1-2.22.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY rowid DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.22.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388608 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary1-2.23.1 { + db eval { + SELECT * FROM t1 WHERE rowid=549755813888 + } +} {35 0000008000000000} +do_test boundary1-2.23.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000008000000000' + } +} {549755813888 35} +do_test boundary1-2.23.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=35 + } +} {549755813888 0000008000000000} +do_test boundary1-2.23.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57} +do_test boundary1-2.23.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY a DESC + } +} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary1-2.23.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY rowid + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.23.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary1-2.23.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813888 ORDER BY x + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.23.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57} +do_test boundary1-2.23.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY a DESC + } +} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary1-2.23.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY rowid + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.23.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary1-2.23.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813888 ORDER BY x + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.23.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.23.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.23.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary1-2.23.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY rowid DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.23.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.23.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.23.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.23.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary1-2.23.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY rowid DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.23.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.24.1 { + db eval { + SELECT * FROM t1 WHERE rowid=8388607 + } +} {18 00000000007fffff} +do_test boundary1-2.24.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='00000000007fffff' + } +} {8388607 18} +do_test boundary1-2.24.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=18 + } +} {8388607 00000000007fffff} +do_test boundary1-2.24.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.24.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary1-2.24.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY rowid + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.24.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary1-2.24.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388607 ORDER BY x + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.24.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.24.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary1-2.24.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY rowid + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.24.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary1-2.24.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388607 ORDER BY x + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.24.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.24.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary1-2.24.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary1-2.24.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY rowid DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.24.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388607 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.24.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.24.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary1-2.24.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary1-2.24.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY rowid DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.24.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388607 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.25.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-3 + } +} {52 fffffffffffffffd} +do_test boundary1-2.25.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='fffffffffffffffd' + } +} {-3 52} +do_test boundary1-2.25.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=52 + } +} {-3 fffffffffffffffd} +do_test boundary1-2.25.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -3 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary1-2.25.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -3 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.25.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -3 ORDER BY rowid + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.25.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -3 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary1-2.25.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -3 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38} +do_test boundary1-2.25.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -3 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62} +do_test boundary1-2.25.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -3 ORDER BY a DESC + } +} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.25.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -3 ORDER BY rowid + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.25.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -3 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary1-2.25.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -3 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38} +do_test boundary1-2.25.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -3 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64} +do_test boundary1-2.25.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -3 ORDER BY a DESC + } +} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1} +do_test boundary1-2.25.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -3 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary1-2.25.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -3 ORDER BY rowid DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.25.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -3 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary1-2.25.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -3 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64} +do_test boundary1-2.25.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -3 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1} +do_test boundary1-2.25.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -3 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary1-2.25.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -3 ORDER BY rowid DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.25.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -3 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary1-2.26.1 { + db eval { + SELECT * FROM t1 WHERE rowid=0 + } +} {59 0000000000000000} +do_test boundary1-2.26.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000000000' + } +} {0 59} +do_test boundary1-2.26.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=59 + } +} {0 0000000000000000} +do_test boundary1-2.26.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 0 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62} +do_test boundary1-2.26.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 0 ORDER BY a DESC + } +} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.26.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 0 ORDER BY rowid + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.26.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 0 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary1-2.26.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 0 ORDER BY x + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.26.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 0 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary1-2.26.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 0 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.26.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 0 ORDER BY rowid + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.26.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 0 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary1-2.26.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 0 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.26.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 0 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64} +do_test boundary1-2.26.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 0 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary1-2.26.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 0 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.26.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 0 ORDER BY rowid DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.26.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 0 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.26.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 0 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64} +do_test boundary1-2.26.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 0 ORDER BY a DESC + } +} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary1-2.26.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 0 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary1-2.26.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 0 ORDER BY rowid DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.26.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 0 ORDER BY x + } +} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.27.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-1 + } +} {38 ffffffffffffffff} +do_test boundary1-2.27.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffffffffffffff' + } +} {-1 38} +do_test boundary1-2.27.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=38 + } +} {-1 ffffffffffffffff} +do_test boundary1-2.27.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary1-2.27.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -1 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.27.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -1 ORDER BY rowid + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.27.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -1 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary1-2.27.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -1 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.27.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary1-2.27.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -1 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.27.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -1 ORDER BY rowid + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.27.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -1 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary1-2.27.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -1 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38} +do_test boundary1-2.27.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64} +do_test boundary1-2.27.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -1 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1} +do_test boundary1-2.27.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -1 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary1-2.27.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -1 ORDER BY rowid DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.27.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -1 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary1-2.27.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64} +do_test boundary1-2.27.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -1 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary1-2.27.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -1 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.27.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -1 ORDER BY rowid DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.27.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -1 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.28.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-2 + } +} {33 fffffffffffffffe} +do_test boundary1-2.28.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='fffffffffffffffe' + } +} {-2 33} +do_test boundary1-2.28.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=33 + } +} {-2 fffffffffffffffe} +do_test boundary1-2.28.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary1-2.28.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -2 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.28.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -2 ORDER BY rowid + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.28.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -2 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary1-2.28.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -2 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38} +do_test boundary1-2.28.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary1-2.28.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.28.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2 ORDER BY rowid + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.28.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary1-2.28.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38} +do_test boundary1-2.28.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -2 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64} +do_test boundary1-2.28.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -2 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1} +do_test boundary1-2.28.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -2 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary1-2.28.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -2 ORDER BY rowid DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.28.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -2 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary1-2.28.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2 ORDER BY a + } +} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64} +do_test boundary1-2.28.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1} +do_test boundary1-2.28.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary1-2.28.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2 ORDER BY rowid DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.28.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary1-2.29.1 { + db eval { + SELECT * FROM t1 WHERE rowid=2097152 + } +} {42 0000000000200000} +do_test boundary1-2.29.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000200000' + } +} {2097152 42} +do_test boundary1-2.29.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=42 + } +} {2097152 0000000000200000} +do_test boundary1-2.29.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.29.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary1-2.29.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY rowid + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.29.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary1-2.29.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097152 ORDER BY x + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.29.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary1-2.29.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary1-2.29.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY rowid + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.29.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary1-2.29.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097152 ORDER BY x + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.29.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.29.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary1-2.29.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary1-2.29.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY rowid DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.29.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097152 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.29.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.29.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary1-2.29.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary1-2.29.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY rowid DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.29.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097152 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.30.1 { + db eval { + SELECT * FROM t1 WHERE rowid=128 + } +} {49 0000000000000080} +do_test boundary1-2.30.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000000080' + } +} {128 49} +do_test boundary1-2.30.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=49 + } +} {128 0000000000000080} +do_test boundary1-2.30.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 128 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary1-2.30.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 128 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary1-2.30.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 128 ORDER BY rowid + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.30.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 128 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary1-2.30.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 128 ORDER BY x + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.30.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 128 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.30.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 128 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary1-2.30.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 128 ORDER BY rowid + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.30.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 128 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary1-2.30.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 128 ORDER BY x + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.30.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 128 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.30.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 128 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary1-2.30.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 128 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary1-2.30.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 128 ORDER BY rowid DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.30.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 128 ORDER BY x + } +} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.30.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 128 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.30.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 128 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary1-2.30.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 128 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary1-2.30.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 128 ORDER BY rowid DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.30.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 128 ORDER BY x + } +} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.31.1 { + db eval { + SELECT * FROM t1 WHERE rowid=255 + } +} {30 00000000000000ff} +do_test boundary1-2.31.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='00000000000000ff' + } +} {255 30} +do_test boundary1-2.31.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=30 + } +} {255 00000000000000ff} +do_test boundary1-2.31.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 255 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary1-2.31.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 255 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary1-2.31.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 255 ORDER BY rowid + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.31.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 255 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary1-2.31.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 255 ORDER BY x + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.31.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 255 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary1-2.31.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 255 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary1-2.31.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 255 ORDER BY rowid + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.31.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 255 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary1-2.31.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 255 ORDER BY x + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.31.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 255 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.31.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 255 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary1-2.31.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 255 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary1-2.31.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 255 ORDER BY rowid DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.31.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 255 ORDER BY x + } +} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.31.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 255 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.31.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 255 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary1-2.31.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 255 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary1-2.31.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 255 ORDER BY rowid DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.31.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 255 ORDER BY x + } +} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.32.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-2147483648 + } +} {11 ffffffff80000000} +do_test boundary1-2.32.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffffff80000000' + } +} {-2147483648 11} +do_test boundary1-2.32.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=11 + } +} {-2147483648 ffffffff80000000} +do_test boundary1-2.32.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.32.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.32.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY rowid + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.32.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary1-2.32.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.32.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.32.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.32.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY rowid + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.32.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary1-2.32.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.32.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY a + } +} {2 21 44 47 55 58 63 64} +do_test boundary1-2.32.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 2} +do_test boundary1-2.32.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47} +do_test boundary1-2.32.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY rowid DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary1-2.32.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483648 ORDER BY x + } +} {55 2 64 21 44 58 63 47} +do_test boundary1-2.32.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY a + } +} {2 11 21 44 47 55 58 63 64} +do_test boundary1-2.32.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2} +do_test boundary1-2.32.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary1-2.32.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY rowid DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary1-2.32.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483648 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary1-2.33.1 { + db eval { + SELECT * FROM t1 WHERE rowid=34359738367 + } +} {39 00000007ffffffff} +do_test boundary1-2.33.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='00000007ffffffff' + } +} {34359738367 39} +do_test boundary1-2.33.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=39 + } +} {34359738367 00000007ffffffff} +do_test boundary1-2.33.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary1-2.33.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary1-2.33.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY rowid + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.33.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary1-2.33.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 34359738367 ORDER BY x + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.33.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57} +do_test boundary1-2.33.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY a DESC + } +} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary1-2.33.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY rowid + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.33.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary1-2.33.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 34359738367 ORDER BY x + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.33.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.33.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.33.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary1-2.33.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY rowid DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.33.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 34359738367 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.33.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.33.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.33.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary1-2.33.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY rowid DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.33.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 34359738367 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.34.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-549755813889 + } +} {58 ffffff7fffffffff} +do_test boundary1-2.34.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffff7fffffffff' + } +} {-549755813889 58} +do_test boundary1-2.34.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=58 + } +} {-549755813889 ffffff7fffffffff} +do_test boundary1-2.34.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63} +do_test boundary1-2.34.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY a DESC + } +} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.34.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY rowid + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.34.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary1-2.34.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813889 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.34.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary1-2.34.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.34.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY rowid + } +} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.34.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58} +do_test boundary1-2.34.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813889 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.34.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY a + } +} {2 21 44 55 64} +do_test boundary1-2.34.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY a DESC + } +} {64 55 44 21 2} +do_test boundary1-2.34.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY rowid + } +} {55 2 64 21 44} +do_test boundary1-2.34.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY rowid DESC + } +} {44 21 64 2 55} +do_test boundary1-2.34.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813889 ORDER BY x + } +} {55 2 64 21 44} +do_test boundary1-2.34.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY a + } +} {2 21 44 55 58 64} +do_test boundary1-2.34.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY a DESC + } +} {64 58 55 44 21 2} +do_test boundary1-2.34.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY rowid + } +} {55 2 64 21 44 58} +do_test boundary1-2.34.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY rowid DESC + } +} {58 44 21 64 2 55} +do_test boundary1-2.34.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813889 ORDER BY x + } +} {55 2 64 21 44 58} +do_test boundary1-2.35.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-32768 + } +} {32 ffffffffffff8000} +do_test boundary1-2.35.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffffffffff8000' + } +} {-32768 32} +do_test boundary1-2.35.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=32 + } +} {-32768 ffffffffffff8000} +do_test boundary1-2.35.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -32768 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.35.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -32768 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.35.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -32768 ORDER BY rowid + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.35.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -32768 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary1-2.35.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38} +do_test boundary1-2.35.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.35.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.35.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY rowid + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.35.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary1-2.35.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38} +do_test boundary1-2.35.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -32768 ORDER BY a + } +} {1 2 11 21 29 37 44 47 55 58 63 64} +do_test boundary1-2.35.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -32768 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 29 21 11 2 1} +do_test boundary1-2.35.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -32768 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary1-2.35.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -32768 ORDER BY rowid DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.35.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -32768 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary1-2.35.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 55 58 63 64} +do_test boundary1-2.35.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 32 29 21 11 2 1} +do_test boundary1-2.35.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary1-2.35.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY rowid DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.35.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -32768 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary1-2.36.1 { + db eval { + SELECT * FROM t1 WHERE rowid=2147483647 + } +} {20 000000007fffffff} +do_test boundary1-2.36.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='000000007fffffff' + } +} {2147483647 20} +do_test boundary1-2.36.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=20 + } +} {2147483647 000000007fffffff} +do_test boundary1-2.36.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary1-2.36.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary1-2.36.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY rowid + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.36.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary1-2.36.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483647 ORDER BY x + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.36.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary1-2.36.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary1-2.36.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY rowid + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.36.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary1-2.36.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483647 ORDER BY x + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.36.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.36.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.36.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary1-2.36.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY rowid DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.36.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483647 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.36.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.36.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.36.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary1-2.36.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY rowid DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.36.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483647 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.37.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-129 + } +} {54 ffffffffffffff7f} +do_test boundary1-2.37.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffffffffffff7f' + } +} {-129 54} +do_test boundary1-2.37.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=54 + } +} {-129 ffffffffffffff7f} +do_test boundary1-2.37.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -129 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62} +do_test boundary1-2.37.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -129 ORDER BY a DESC + } +} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.37.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -129 ORDER BY rowid + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.37.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -129 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary1-2.37.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -129 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38} +do_test boundary1-2.37.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -129 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.37.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -129 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.37.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -129 ORDER BY rowid + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.37.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -129 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary1-2.37.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -129 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38} +do_test boundary1-2.37.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -129 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 55 58 63 64} +do_test boundary1-2.37.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -129 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 32 29 21 11 2 1} +do_test boundary1-2.37.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -129 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary1-2.37.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -129 ORDER BY rowid DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.37.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -129 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary1-2.37.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -129 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 54 55 58 63 64} +do_test boundary1-2.37.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -129 ORDER BY a DESC + } +} {64 63 58 55 54 47 44 37 32 29 21 11 2 1} +do_test boundary1-2.37.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -129 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary1-2.37.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -129 ORDER BY rowid DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.37.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -129 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary1-2.38.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-128 + } +} {53 ffffffffffffff80} +do_test boundary1-2.38.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffffffffffff80' + } +} {-128 53} +do_test boundary1-2.38.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=53 + } +} {-128 ffffffffffffff80} +do_test boundary1-2.38.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -128 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62} +do_test boundary1-2.38.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -128 ORDER BY a DESC + } +} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.38.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -128 ORDER BY rowid + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.38.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -128 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary1-2.38.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -128 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38} +do_test boundary1-2.38.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -128 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62} +do_test boundary1-2.38.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -128 ORDER BY a DESC + } +} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.38.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -128 ORDER BY rowid + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.38.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -128 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary1-2.38.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -128 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38} +do_test boundary1-2.38.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -128 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 54 55 58 63 64} +do_test boundary1-2.38.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -128 ORDER BY a DESC + } +} {64 63 58 55 54 47 44 37 32 29 21 11 2 1} +do_test boundary1-2.38.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -128 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary1-2.38.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -128 ORDER BY rowid DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.38.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -128 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary1-2.38.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -128 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64} +do_test boundary1-2.38.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -128 ORDER BY a DESC + } +} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1} +do_test boundary1-2.38.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -128 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary1-2.38.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -128 ORDER BY rowid DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.38.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -128 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary1-2.39.1 { + db eval { + SELECT * FROM t1 WHERE rowid=72057594037927936 + } +} {28 0100000000000000} +do_test boundary1-2.39.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0100000000000000' + } +} {72057594037927936 28} +do_test boundary1-2.39.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=28 + } +} {72057594037927936 0100000000000000} +do_test boundary1-2.39.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY a + } +} {3} +do_test boundary1-2.39.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY a DESC + } +} {3} +do_test boundary1-2.39.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY rowid + } +} {3} +do_test boundary1-2.39.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY rowid DESC + } +} {3} +do_test boundary1-2.39.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 72057594037927936 ORDER BY x + } +} {3} +do_test boundary1-2.39.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY a + } +} {3 28} +do_test boundary1-2.39.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY a DESC + } +} {28 3} +do_test boundary1-2.39.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY rowid + } +} {28 3} +do_test boundary1-2.39.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY rowid DESC + } +} {3 28} +do_test boundary1-2.39.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 72057594037927936 ORDER BY x + } +} {28 3} +do_test boundary1-2.39.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.39.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.39.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17} +do_test boundary1-2.39.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY rowid DESC + } +} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.39.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 72057594037927936 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.39.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.39.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.39.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28} +do_test boundary1-2.39.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY rowid DESC + } +} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.39.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 72057594037927936 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.40.1 { + db eval { + SELECT * FROM t1 WHERE rowid=2147483648 + } +} {51 0000000080000000} +do_test boundary1-2.40.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000080000000' + } +} {2147483648 51} +do_test boundary1-2.40.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=51 + } +} {2147483648 0000000080000000} +do_test boundary1-2.40.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary1-2.40.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary1-2.40.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY rowid + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.40.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary1-2.40.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 2147483648 ORDER BY x + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.40.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary1-2.40.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary1-2.40.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY rowid + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.40.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary1-2.40.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2147483648 ORDER BY x + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.40.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.40.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.40.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary1-2.40.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY rowid DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.40.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.40.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.40.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.40.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary1-2.40.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY rowid DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.40.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.41.1 { + db eval { + SELECT * FROM t1 WHERE rowid=549755813887 + } +} {46 0000007fffffffff} +do_test boundary1-2.41.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000007fffffffff' + } +} {549755813887 46} +do_test boundary1-2.41.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=46 + } +} {549755813887 0000007fffffffff} +do_test boundary1-2.41.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57} +do_test boundary1-2.41.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY a DESC + } +} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary1-2.41.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY rowid + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.41.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary1-2.41.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 549755813887 ORDER BY x + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.41.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary1-2.41.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary1-2.41.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY rowid + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.41.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary1-2.41.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 549755813887 ORDER BY x + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.41.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.41.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.41.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary1-2.41.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY rowid DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.41.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 549755813887 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.41.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.41.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.41.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary1-2.41.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY rowid DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.41.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 549755813887 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.42.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-549755813888 + } +} {63 ffffff8000000000} +do_test boundary1-2.42.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffff8000000000' + } +} {-549755813888 63} +do_test boundary1-2.42.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=63 + } +} {-549755813888 ffffff8000000000} +do_test boundary1-2.42.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.42.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.42.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY rowid + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.42.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary1-2.42.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.42.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63} +do_test boundary1-2.42.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY a DESC + } +} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.42.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY rowid + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.42.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary1-2.42.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.42.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY a + } +} {2 21 44 55 58 64} +do_test boundary1-2.42.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY a DESC + } +} {64 58 55 44 21 2} +do_test boundary1-2.42.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY rowid + } +} {55 2 64 21 44 58} +do_test boundary1-2.42.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY rowid DESC + } +} {58 44 21 64 2 55} +do_test boundary1-2.42.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -549755813888 ORDER BY x + } +} {55 2 64 21 44 58} +do_test boundary1-2.42.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY a + } +} {2 21 44 55 58 63 64} +do_test boundary1-2.42.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY a DESC + } +} {64 63 58 55 44 21 2} +do_test boundary1-2.42.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY rowid + } +} {55 2 64 21 44 58 63} +do_test boundary1-2.42.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY rowid DESC + } +} {63 58 44 21 64 2 55} +do_test boundary1-2.42.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -549755813888 ORDER BY x + } +} {55 2 64 21 44 58 63} +do_test boundary1-2.43.1 { + db eval { + SELECT * FROM t1 WHERE rowid=281474976710655 + } +} {10 0000ffffffffffff} +do_test boundary1-2.43.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000ffffffffffff' + } +} {281474976710655 10} +do_test boundary1-2.43.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=10 + } +} {281474976710655 0000ffffffffffff} +do_test boundary1-2.43.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY a + } +} {3 13 17 26 27 28 43 45} +do_test boundary1-2.43.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 3} +do_test boundary1-2.43.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY rowid + } +} {26 13 43 27 45 17 28 3} +do_test boundary1-2.43.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26} +do_test boundary1-2.43.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710655 ORDER BY x + } +} {26 13 43 27 45 17 28 3} +do_test boundary1-2.43.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY a + } +} {3 10 13 17 26 27 28 43 45} +do_test boundary1-2.43.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 10 3} +do_test boundary1-2.43.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY rowid + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary1-2.43.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10} +do_test boundary1-2.43.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710655 ORDER BY x + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary1-2.43.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.43.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary1-2.43.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34} +do_test boundary1-2.43.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY rowid DESC + } +} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.43.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710655 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.43.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.43.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.43.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10} +do_test boundary1-2.43.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY rowid DESC + } +} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.43.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710655 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.44.1 { + db eval { + SELECT * FROM t1 WHERE rowid=4398046511103 + } +} {7 000003ffffffffff} +do_test boundary1-2.44.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='000003ffffffffff' + } +} {4398046511103 7} +do_test boundary1-2.44.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=7 + } +} {4398046511103 000003ffffffffff} +do_test boundary1-2.44.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary1-2.44.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 3} +do_test boundary1-2.44.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY rowid + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.44.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary1-2.44.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511103 ORDER BY x + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.44.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY a + } +} {3 7 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary1-2.44.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 7 3} +do_test boundary1-2.44.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY rowid + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.44.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary1-2.44.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511103 ORDER BY x + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.44.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary1-2.44.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.44.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary1-2.44.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY rowid DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.44.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511103 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.44.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary1-2.44.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary1-2.44.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary1-2.44.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY rowid DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.44.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511103 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.45.1 { + db eval { + SELECT * FROM t1 WHERE rowid=268435455 + } +} {12 000000000fffffff} +do_test boundary1-2.45.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='000000000fffffff' + } +} {268435455 12} +do_test boundary1-2.45.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=12 + } +} {268435455 000000000fffffff} +do_test boundary1-2.45.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.45.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary1-2.45.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY rowid + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.45.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary1-2.45.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 268435455 ORDER BY x + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.45.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY a + } +} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.45.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3} +do_test boundary1-2.45.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY rowid + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.45.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary1-2.45.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 268435455 ORDER BY x + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.45.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY a + } +} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.45.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1} +do_test boundary1-2.45.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary1-2.45.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY rowid DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.45.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 268435455 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.45.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.45.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary1-2.45.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary1-2.45.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY rowid DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.45.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 268435455 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.46.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-9223372036854775808 + } +} {55 8000000000000000} +do_test boundary1-2.46.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='8000000000000000' + } +} {-9223372036854775808 55} +do_test boundary1-2.46.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=55 + } +} {-9223372036854775808 8000000000000000} +do_test boundary1-2.46.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.46.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary1-2.46.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY rowid + } +} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.46.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2} +do_test boundary1-2.46.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -9223372036854775808 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.46.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.46.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary1-2.46.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.46.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.46.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9223372036854775808 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.46.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY a + } +} {} +do_test boundary1-2.46.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY a DESC + } +} {} +do_test boundary1-2.46.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY rowid + } +} {} +do_test boundary1-2.46.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY rowid DESC + } +} {} +do_test boundary1-2.46.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -9223372036854775808 ORDER BY x + } +} {} +do_test boundary1-2.46.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY a + } +} {55} +do_test boundary1-2.46.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY a DESC + } +} {55} +do_test boundary1-2.46.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY rowid + } +} {55} +do_test boundary1-2.46.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY rowid DESC + } +} {55} +do_test boundary1-2.46.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9223372036854775808 ORDER BY x + } +} {55} +do_test boundary1-2.47.1 { + db eval { + SELECT * FROM t1 WHERE rowid=562949953421312 + } +} {43 0002000000000000} +do_test boundary1-2.47.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0002000000000000' + } +} {562949953421312 43} +do_test boundary1-2.47.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=43 + } +} {562949953421312 0002000000000000} +do_test boundary1-2.47.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY a + } +} {3 17 27 28 45} +do_test boundary1-2.47.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY a DESC + } +} {45 28 27 17 3} +do_test boundary1-2.47.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY rowid + } +} {27 45 17 28 3} +do_test boundary1-2.47.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY rowid DESC + } +} {3 28 17 45 27} +do_test boundary1-2.47.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 562949953421312 ORDER BY x + } +} {27 45 17 28 3} +do_test boundary1-2.47.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY a + } +} {3 17 27 28 43 45} +do_test boundary1-2.47.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY a DESC + } +} {45 43 28 27 17 3} +do_test boundary1-2.47.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY rowid + } +} {43 27 45 17 28 3} +do_test boundary1-2.47.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY rowid DESC + } +} {3 28 17 45 27 43} +do_test boundary1-2.47.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 562949953421312 ORDER BY x + } +} {43 27 45 17 28 3} +do_test boundary1-2.47.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.47.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.47.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13} +do_test boundary1-2.47.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY rowid DESC + } +} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.47.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 562949953421312 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.47.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.47.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.47.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43} +do_test boundary1-2.47.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY rowid DESC + } +} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.47.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 562949953421312 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.48.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-8388609 + } +} {1 ffffffffff7fffff} +do_test boundary1-2.48.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffffffff7fffff' + } +} {-8388609 1} +do_test boundary1-2.48.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=1 + } +} {-8388609 ffffffffff7fffff} +do_test boundary1-2.48.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.48.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.48.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY rowid + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.48.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary1-2.48.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -8388609 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38} +do_test boundary1-2.48.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.48.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.48.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY rowid + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.48.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary1-2.48.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -8388609 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.48.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY a + } +} {2 11 21 44 47 55 58 63 64} +do_test boundary1-2.48.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2} +do_test boundary1-2.48.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary1-2.48.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY rowid DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary1-2.48.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -8388609 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary1-2.48.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY a + } +} {1 2 11 21 44 47 55 58 63 64} +do_test boundary1-2.48.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2 1} +do_test boundary1-2.48.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary1-2.48.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY rowid DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.48.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -8388609 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary1-2.49.1 { + db eval { + SELECT * FROM t1 WHERE rowid=16777215 + } +} {9 0000000000ffffff} +do_test boundary1-2.49.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000ffffff' + } +} {16777215 9} +do_test boundary1-2.49.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=9 + } +} {16777215 0000000000ffffff} +do_test boundary1-2.49.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY a + } +} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.49.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3} +do_test boundary1-2.49.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY rowid + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.49.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary1-2.49.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 16777215 ORDER BY x + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.49.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.49.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary1-2.49.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY rowid + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.49.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary1-2.49.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16777215 ORDER BY x + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.49.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.49.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary1-2.49.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary1-2.49.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY rowid DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.49.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 16777215 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.49.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY a + } +} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.49.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1} +do_test boundary1-2.49.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary1-2.49.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY rowid DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.49.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16777215 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.50.1 { + db eval { + SELECT * FROM t1 WHERE rowid=8388608 + } +} {24 0000000000800000} +do_test boundary1-2.50.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000800000' + } +} {8388608 24} +do_test boundary1-2.50.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=24 + } +} {8388608 0000000000800000} +do_test boundary1-2.50.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.50.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary1-2.50.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY rowid + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.50.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary1-2.50.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 8388608 ORDER BY x + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.50.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary1-2.50.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary1-2.50.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY rowid + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.50.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary1-2.50.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 8388608 ORDER BY x + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.50.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.50.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary1-2.50.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary1-2.50.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY rowid DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.50.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.50.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.50.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary1-2.50.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary1-2.50.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY rowid DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.50.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.51.1 { + db eval { + SELECT * FROM t1 WHERE rowid=16383 + } +} {8 0000000000003fff} +do_test boundary1-2.51.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000003fff' + } +} {16383 8} +do_test boundary1-2.51.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=8 + } +} {16383 0000000000003fff} +do_test boundary1-2.51.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 16383 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary1-2.51.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 16383 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.51.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 16383 ORDER BY rowid + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.51.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 16383 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary1-2.51.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 16383 ORDER BY x + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.51.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary1-2.51.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary1-2.51.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY rowid + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.51.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary1-2.51.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 16383 ORDER BY x + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.51.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 16383 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.51.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 16383 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary1-2.51.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 16383 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary1-2.51.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 16383 ORDER BY rowid DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.51.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 16383 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.51.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY a + } +} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.51.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1} +do_test boundary1-2.51.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary1-2.51.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY rowid DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.51.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 16383 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.52.1 { + db eval { + SELECT * FROM t1 WHERE rowid=140737488355328 + } +} {34 0000800000000000} +do_test boundary1-2.52.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000800000000000' + } +} {140737488355328 34} +do_test boundary1-2.52.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=34 + } +} {140737488355328 0000800000000000} +do_test boundary1-2.52.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY a + } +} {3 10 13 17 26 27 28 43 45} +do_test boundary1-2.52.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 10 3} +do_test boundary1-2.52.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY rowid + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary1-2.52.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10} +do_test boundary1-2.52.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355328 ORDER BY x + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary1-2.52.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY a + } +} {3 10 13 17 26 27 28 34 43 45} +do_test boundary1-2.52.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY a DESC + } +} {45 43 34 28 27 26 17 13 10 3} +do_test boundary1-2.52.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY rowid + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.52.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34} +do_test boundary1-2.52.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355328 ORDER BY x + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.52.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.52.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary1-2.52.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25} +do_test boundary1-2.52.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY rowid DESC + } +} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.52.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.52.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.52.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary1-2.52.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34} +do_test boundary1-2.52.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY rowid DESC + } +} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.52.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.53.1 { + db eval { + SELECT * FROM t1 WHERE rowid=2097151 + } +} {15 00000000001fffff} +do_test boundary1-2.53.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='00000000001fffff' + } +} {2097151 15} +do_test boundary1-2.53.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=15 + } +} {2097151 00000000001fffff} +do_test boundary1-2.53.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary1-2.53.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary1-2.53.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY rowid + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.53.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary1-2.53.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 2097151 ORDER BY x + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.53.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary1-2.53.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.53.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY rowid + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.53.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary1-2.53.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 2097151 ORDER BY x + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.53.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.53.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary1-2.53.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary1-2.53.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY rowid DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.53.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 2097151 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.53.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary1-2.53.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary1-2.53.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary1-2.53.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY rowid DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.53.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 2097151 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.54.1 { + db eval { + SELECT * FROM t1 WHERE rowid=140737488355327 + } +} {25 00007fffffffffff} +do_test boundary1-2.54.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='00007fffffffffff' + } +} {140737488355327 25} +do_test boundary1-2.54.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=25 + } +} {140737488355327 00007fffffffffff} +do_test boundary1-2.54.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY a + } +} {3 10 13 17 26 27 28 34 43 45} +do_test boundary1-2.54.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY a DESC + } +} {45 43 34 28 27 26 17 13 10 3} +do_test boundary1-2.54.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY rowid + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.54.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34} +do_test boundary1-2.54.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 140737488355327 ORDER BY x + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.54.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45} +do_test boundary1-2.54.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY a DESC + } +} {45 43 34 28 27 26 25 17 13 10 3} +do_test boundary1-2.54.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY rowid + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.54.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25} +do_test boundary1-2.54.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 140737488355327 ORDER BY x + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.54.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.54.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary1-2.54.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56} +do_test boundary1-2.54.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY rowid DESC + } +} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.54.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 140737488355327 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.54.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.54.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary1-2.54.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25} +do_test boundary1-2.54.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY rowid DESC + } +} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.54.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 140737488355327 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.55.1 { + db eval { + SELECT * FROM t1 WHERE rowid=281474976710656 + } +} {26 0001000000000000} +do_test boundary1-2.55.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0001000000000000' + } +} {281474976710656 26} +do_test boundary1-2.55.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=26 + } +} {281474976710656 0001000000000000} +do_test boundary1-2.55.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY a + } +} {3 13 17 27 28 43 45} +do_test boundary1-2.55.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY a DESC + } +} {45 43 28 27 17 13 3} +do_test boundary1-2.55.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY rowid + } +} {13 43 27 45 17 28 3} +do_test boundary1-2.55.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13} +do_test boundary1-2.55.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 281474976710656 ORDER BY x + } +} {13 43 27 45 17 28 3} +do_test boundary1-2.55.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY a + } +} {3 13 17 26 27 28 43 45} +do_test boundary1-2.55.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 3} +do_test boundary1-2.55.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY rowid + } +} {26 13 43 27 45 17 28 3} +do_test boundary1-2.55.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26} +do_test boundary1-2.55.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 281474976710656 ORDER BY x + } +} {26 13 43 27 45 17 28 3} +do_test boundary1-2.55.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.55.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.55.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10} +do_test boundary1-2.55.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY rowid DESC + } +} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.55.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 281474976710656 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.55.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.55.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.55.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26} +do_test boundary1-2.55.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY rowid DESC + } +} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.55.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 281474976710656 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.56.1 { + db eval { + SELECT * FROM t1 WHERE rowid=32767 + } +} {23 0000000000007fff} +do_test boundary1-2.56.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000007fff' + } +} {32767 23} +do_test boundary1-2.56.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=23 + } +} {32767 0000000000007fff} +do_test boundary1-2.56.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 32767 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary1-2.56.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 32767 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.56.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 32767 ORDER BY rowid + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.56.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 32767 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary1-2.56.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 32767 ORDER BY x + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.56.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary1-2.56.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary1-2.56.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY rowid + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.56.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary1-2.56.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 32767 ORDER BY x + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.56.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 32767 ORDER BY a + } +} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.56.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 32767 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1} +do_test boundary1-2.56.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 32767 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary1-2.56.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 32767 ORDER BY rowid DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.56.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 32767 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.56.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary1-2.56.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary1-2.56.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary1-2.56.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY rowid DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.56.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 32767 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.57.1 { + db eval { + SELECT * FROM t1 WHERE rowid=127 + } +} {4 000000000000007f} +do_test boundary1-2.57.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='000000000000007f' + } +} {127 4} +do_test boundary1-2.57.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=4 + } +} {127 000000000000007f} +do_test boundary1-2.57.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 127 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.57.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 127 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary1-2.57.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 127 ORDER BY rowid + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.57.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 127 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary1-2.57.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 127 ORDER BY x + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.57.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 127 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.57.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 127 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary1-2.57.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 127 ORDER BY rowid + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.57.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 127 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary1-2.57.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 127 ORDER BY x + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.57.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 127 ORDER BY a + } +} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.57.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 127 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1} +do_test boundary1-2.57.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 127 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary1-2.57.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 127 ORDER BY rowid DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.57.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 127 ORDER BY x + } +} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.57.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 127 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.57.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 127 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary1-2.57.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 127 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary1-2.57.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 127 ORDER BY rowid DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.57.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 127 ORDER BY x + } +} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.58.1 { + db eval { + SELECT * FROM t1 WHERE rowid=36028797018963967 + } +} {27 007fffffffffffff} +do_test boundary1-2.58.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='007fffffffffffff' + } +} {36028797018963967 27} +do_test boundary1-2.58.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=27 + } +} {36028797018963967 007fffffffffffff} +do_test boundary1-2.58.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY a + } +} {3 17 28 45} +do_test boundary1-2.58.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY a DESC + } +} {45 28 17 3} +do_test boundary1-2.58.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY rowid + } +} {45 17 28 3} +do_test boundary1-2.58.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY rowid DESC + } +} {3 28 17 45} +do_test boundary1-2.58.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY x + } +} {45 17 28 3} +do_test boundary1-2.58.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY a + } +} {3 17 27 28 45} +do_test boundary1-2.58.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY a DESC + } +} {45 28 27 17 3} +do_test boundary1-2.58.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY rowid + } +} {27 45 17 28 3} +do_test boundary1-2.58.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY rowid DESC + } +} {3 28 17 45 27} +do_test boundary1-2.58.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY x + } +} {27 45 17 28 3} +do_test boundary1-2.58.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.58.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.58.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43} +do_test boundary1-2.58.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY rowid DESC + } +} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.58.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.58.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.58.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.58.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27} +do_test boundary1-2.58.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY rowid DESC + } +} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.58.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.59.1 { + db eval { + SELECT * FROM t1 WHERE rowid=4398046511104 + } +} {56 0000040000000000} +do_test boundary1-2.59.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000040000000000' + } +} {4398046511104 56} +do_test boundary1-2.59.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=56 + } +} {4398046511104 0000040000000000} +do_test boundary1-2.59.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45} +do_test boundary1-2.59.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY a DESC + } +} {45 43 34 28 27 26 25 17 13 10 3} +do_test boundary1-2.59.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY rowid + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.59.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25} +do_test boundary1-2.59.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY x + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.59.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary1-2.59.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 3} +do_test boundary1-2.59.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY rowid + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.59.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary1-2.59.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY x + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.59.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary1-2.59.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary1-2.59.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary1-2.59.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY rowid DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.59.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.59.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.59.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary1-2.59.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56} +do_test boundary1-2.59.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY rowid DESC + } +} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.59.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.60.1 { + db eval { + SELECT * FROM t1 WHERE rowid=1 + } +} {60 0000000000000001} +do_test boundary1-2.60.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000000001' + } +} {1 60} +do_test boundary1-2.60.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=60 + } +} {1 0000000000000001} +do_test boundary1-2.60.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.60.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 1 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.60.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 1 ORDER BY rowid + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.60.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 1 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary1-2.60.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 1 ORDER BY x + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.60.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62} +do_test boundary1-2.60.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1 ORDER BY a DESC + } +} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.60.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1 ORDER BY rowid + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.60.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary1-2.60.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 1 ORDER BY x + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.60.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64} +do_test boundary1-2.60.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 1 ORDER BY a DESC + } +} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary1-2.60.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 1 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary1-2.60.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 1 ORDER BY rowid DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.60.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 1 ORDER BY x + } +} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.60.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.60.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary1-2.60.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary1-2.60.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1 ORDER BY rowid DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.60.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 1 ORDER BY x + } +} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.61.1 { + db eval { + SELECT * FROM t1 WHERE rowid=36028797018963968 + } +} {45 0080000000000000} +do_test boundary1-2.61.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0080000000000000' + } +} {36028797018963968 45} +do_test boundary1-2.61.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=45 + } +} {36028797018963968 0080000000000000} +do_test boundary1-2.61.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY a + } +} {3 17 28} +do_test boundary1-2.61.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY a DESC + } +} {28 17 3} +do_test boundary1-2.61.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY rowid + } +} {17 28 3} +do_test boundary1-2.61.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY rowid DESC + } +} {3 28 17} +do_test boundary1-2.61.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY x + } +} {17 28 3} +do_test boundary1-2.61.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY a + } +} {3 17 28 45} +do_test boundary1-2.61.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY a DESC + } +} {45 28 17 3} +do_test boundary1-2.61.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY rowid + } +} {45 17 28 3} +do_test boundary1-2.61.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY rowid DESC + } +} {3 28 17 45} +do_test boundary1-2.61.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY x + } +} {45 17 28 3} +do_test boundary1-2.61.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.61.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.61.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27} +do_test boundary1-2.61.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY rowid DESC + } +} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.61.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.61.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.61.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary1-2.61.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45} +do_test boundary1-2.61.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY rowid DESC + } +} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.61.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.62.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-2147483649 + } +} {47 ffffffff7fffffff} +do_test boundary1-2.62.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ffffffff7fffffff' + } +} {-2147483649 47} +do_test boundary1-2.62.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=47 + } +} {-2147483649 ffffffff7fffffff} +do_test boundary1-2.62.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.62.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.62.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY rowid + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.62.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary1-2.62.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -2147483649 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.62.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary1-2.62.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.62.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY rowid + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.62.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary1-2.62.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -2147483649 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.62.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY a + } +} {2 21 44 55 58 63 64} +do_test boundary1-2.62.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY a DESC + } +} {64 63 58 55 44 21 2} +do_test boundary1-2.62.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY rowid + } +} {55 2 64 21 44 58 63} +do_test boundary1-2.62.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY rowid DESC + } +} {63 58 44 21 64 2 55} +do_test boundary1-2.62.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -2147483649 ORDER BY x + } +} {55 2 64 21 44 58 63} +do_test boundary1-2.62.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY a + } +} {2 21 44 47 55 58 63 64} +do_test boundary1-2.62.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 2} +do_test boundary1-2.62.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47} +do_test boundary1-2.62.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY rowid DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary1-2.62.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -2147483649 ORDER BY x + } +} {55 2 64 21 44 58 63 47} +do_test boundary1-2.63.1 { + db eval { + SELECT * FROM t1 WHERE rowid=-36028797018963969 + } +} {2 ff7fffffffffffff} +do_test boundary1-2.63.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='ff7fffffffffffff' + } +} {-36028797018963969 2} +do_test boundary1-2.63.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=2 + } +} {-36028797018963969 ff7fffffffffffff} +do_test boundary1-2.63.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.63.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary1-2.63.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY rowid + } +} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.63.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64} +do_test boundary1-2.63.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -36028797018963969 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.63.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.63.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary1-2.63.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY rowid + } +} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.63.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2} +do_test boundary1-2.63.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -36028797018963969 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.63.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY a + } +} {55} +do_test boundary1-2.63.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY a DESC + } +} {55} +do_test boundary1-2.63.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY rowid + } +} {55} +do_test boundary1-2.63.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY rowid DESC + } +} {55} +do_test boundary1-2.63.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -36028797018963969 ORDER BY x + } +} {55} +do_test boundary1-2.63.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY a + } +} {2 55} +do_test boundary1-2.63.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY a DESC + } +} {55 2} +do_test boundary1-2.63.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY rowid + } +} {55 2} +do_test boundary1-2.63.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY rowid DESC + } +} {2 55} +do_test boundary1-2.63.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -36028797018963969 ORDER BY x + } +} {55 2} +do_test boundary1-2.64.1 { + db eval { + SELECT * FROM t1 WHERE rowid=3 + } +} {5 0000000000000003} +do_test boundary1-2.64.2 { + db eval { + SELECT rowid, a FROM t1 WHERE x='0000000000000003' + } +} {3 5} +do_test boundary1-2.64.3 { + db eval { + SELECT rowid, x FROM t1 WHERE a=5 + } +} {3 0000000000000003} +do_test boundary1-2.64.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 3 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.64.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 3 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary1-2.64.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 3 ORDER BY rowid + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.64.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 3 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary1-2.64.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 3 ORDER BY x + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.64.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 3 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary1-2.64.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 3 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary1-2.64.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 3 ORDER BY rowid + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.64.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 3 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary1-2.64.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 3 ORDER BY x + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.64.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 3 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.64.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 3 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1} +do_test boundary1-2.64.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 3 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary1-2.64.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 3 ORDER BY rowid DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.64.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 3 ORDER BY x + } +} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.64.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 3 ORDER BY a + } +} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary1-2.64.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 3 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1} +do_test boundary1-2.64.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 3 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary1-2.64.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 3 ORDER BY rowid DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.64.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 3 ORDER BY x + } +} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.65.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary1-2.65.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary1-2.65.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY rowid + } +} {} +do_test boundary1-2.65.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY rowid DESC + } +} {} +do_test boundary1-2.65.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > 9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary1-2.65.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary1-2.65.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary1-2.65.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY rowid + } +} {} +do_test boundary1-2.65.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY rowid DESC + } +} {} +do_test boundary1-2.65.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= 9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary1-2.65.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.65.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary1-2.65.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.65.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.65.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < 9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.65.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.65.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary1-2.65.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.65.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.65.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= 9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.66.gt.1 { + db eval { + SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.66.gt.2 { + db eval { + SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary1-2.66.gt.3 { + db eval { + SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.66.gt.4 { + db eval { + SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.66.gt.5 { + db eval { + SELECT a FROM t1 WHERE rowid > -9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.66.ge.1 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary1-2.66.ge.2 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary1-2.66.ge.3 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary1-2.66.ge.4 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary1-2.66.ge.5 { + db eval { + SELECT a FROM t1 WHERE rowid >= -9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary1-2.66.lt.1 { + db eval { + SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary1-2.66.lt.2 { + db eval { + SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary1-2.66.lt.3 { + db eval { + SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY rowid + } +} {} +do_test boundary1-2.66.lt.4 { + db eval { + SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY rowid DESC + } +} {} +do_test boundary1-2.66.lt.5 { + db eval { + SELECT a FROM t1 WHERE rowid < -9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary1-2.66.le.1 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary1-2.66.le.2 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary1-2.66.le.3 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY rowid + } +} {} +do_test boundary1-2.66.le.4 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY rowid DESC + } +} {} +do_test boundary1-2.66.le.5 { + db eval { + SELECT a FROM t1 WHERE rowid <= -9.22337303685477580800e+18 ORDER BY x + } +} {} +finish_test diff --git a/components/external/SQLite-3.8.1/test/boundary2.tcl b/components/external/SQLite-3.8.1/test/boundary2.tcl new file mode 100644 index 0000000000000000000000000000000000000000..b141166072d9174f9cc05232724ecc5253c1e64c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/boundary2.tcl @@ -0,0 +1,445 @@ +puts {# 2008 December 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is automatically generated from a separate TCL script. +# This file seeks to exercise integer boundary values. +# +# $Id: boundary2.tcl,v 1.3 2009/01/02 15:45:48 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Many of the boundary tests depend on a working 64-bit implementation. +if {![working_64bit_int]} { finish_test; return } +} + +expr srand(0) + +# Generate interesting boundary numbers +# +foreach x { + 0 + 1 + 0x7f + 0x7fff + 0x7fffff + 0x7fffffff + 0x7fffffffff + 0x7fffffffffff + 0x7fffffffffffff + 0x7fffffffffffffff +} { + set x [expr {wide($x)}] + set boundarynum($x) 1 + set boundarynum([expr {$x+1}]) 1 + set boundarynum([expr {-($x+1)}]) 1 + set boundarynum([expr {-($x+2)}]) 1 + set boundarynum([expr {$x+$x+1}]) 1 + set boundarynum([expr {$x+$x+2}]) 1 +} +set x [expr {wide(127)}] +for {set i 1} {$i<=9} {incr i} { + set boundarynum($x) 1 + set boundarynum([expr {$x+1}]) 1 + set x [expr {wide($x*128 + 127)}] +} + +# Scramble the $inlist into a random order. +# +proc scramble {inlist} { + set y {} + foreach x $inlist { + lappend y [list [expr {rand()}] $x] + } + set y [lsort $y] + set outlist {} + foreach x $y { + lappend outlist [lindex $x 1] + } + return $outlist +} + +# A simple selection sort. Not trying to be efficient. +# +proc sort {inlist} { + set outlist {} + set mn [lindex $inlist 0] + foreach x $inlist { + if {$x<$mn} {set mn $x} + } + set outlist $mn + set mx $mn + while {1} { + set valid 0 + foreach x $inlist { + if {$x>$mx && (!$valid || $mn>$x)} { + set mn $x + set valid 1 + } + } + if {!$valid} break + lappend outlist $mn + set mx $mn + } + return $outlist +} + +# Reverse the order of a list +# +proc reverse {inlist} { + set i [llength $inlist] + set outlist {} + for {incr i -1} {$i>=0} {incr i -1} { + lappend outlist [lindex $inlist $i] + } + return $outlist +} + +set nums1 [scramble [array names boundarynum]] +set nums2 [scramble [array names boundarynum]] + +set tname boundary2 +puts "do_test $tname-1.1 \173" +puts " db eval \173" +puts " CREATE TABLE t1(r INTEGER, a INTEGER, x TEXT);" +set a 0 +foreach r $nums1 { + incr a + set t1ra($r) $a + set t1ar($a) $r + set x [format %08x%08x [expr {wide($r)>>32}] $r] + set t1rx($r) $x + set t1xr($x) $r + puts " INSERT INTO t1 VALUES($r,$a,'$x');" +} +puts " CREATE INDEX t1i1 ON t1(r);" +puts " CREATE INDEX t1i2 ON t1(a);" +puts " CREATE INDEX t1i3 ON t1(x);" +puts " \175" +puts "\175 {}" + +puts "do_test $tname-1.2 \173" +puts " db eval \173" +puts " SELECT count(*) FROM t1" +puts " \175" +puts "\175 {64}" + +set nums3 $nums2 +lappend nums3 9.22337303685477580800e+18 +lappend nums3 -9.22337303685477580800e+18 + +set i 0 +foreach r $nums3 { + incr i + + if {abs($r)<9.22337203685477580800e+18} { + set x $t1rx($r) + set a $t1ra($r) + set r5 $r.5 + set r0 $r.0 + puts "do_test $tname-2.$i.1 \173" + puts " db eval \173" + puts " SELECT * FROM t1 WHERE r=$r" + puts " \175" + puts "\175 {$r $a $x}" + puts "do_test $tname-2.$i.2 \173" + puts " db eval \173" + puts " SELECT r, a FROM t1 WHERE x='$x'" + puts " \175" + puts "\175 {$r $a}" + puts "do_test $tname-2.$i.3 \173" + puts " db eval \173" + puts " SELECT r, x FROM t1 WHERE a=$a" + puts " \175" + puts "\175 {$r $x}" + } + + foreach op {> >= < <=} subno {gt ge lt le} { + + ################################################################ 2.x.y.1 + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r" { + lappend rset $rx + lappend aset $t1ra($rx) + } + } + puts "do_test $tname-2.$i.$subno.1 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY a" + puts " \175" + puts "\175 {[sort $aset]}" + + ################################################################ 2.x.y.2 + puts "do_test $tname-2.$i.$subno.2 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY a DESC" + puts " \175" + puts "\175 {[reverse [sort $aset]]}" + + ################################################################ 2.x.y.3 + set aset {} + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.3 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY r" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.4 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.4 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY r DESC" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.5 + set aset {} + set xset {} + foreach rx $rset { + lappend xset $t1rx($rx) + } + foreach x [sort $xset] { + set rx $t1xr($x) + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.5 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY x" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.10 + if {abs($r)>9223372036854775808 || [string length $r5]>15} continue + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r0" { + lappend rset $rx + } + } + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.10 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r0 ORDER BY r" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.11 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.11 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r0 ORDER BY r DESC" + puts " \175" + puts "\175 {$aset}" + + + ################################################################ 2.x.y.12 + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r5" { + lappend rset $rx + } + } + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.12 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r5 ORDER BY r" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.13 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.13 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r5 ORDER BY r DESC" + puts " \175" + puts "\175 {$aset}" + } +} + +puts "do_test $tname-3.1 \173" +puts " db eval \173" +puts " DROP INDEX t1i1;" +puts " DROP INDEX t1i2;" +puts " DROP INDEX t1i3;" +puts " \175" +puts "\175 {}" + +set i 0 +foreach r $nums3 { + incr i + + if {abs($r)<9.22337203685477580800e+18} { + set x $t1rx($r) + set a $t1ra($r) + set r5 $r.5 + set r0 $r.0 + puts "do_test $tname-4.$i.1 \173" + puts " db eval \173" + puts " SELECT * FROM t1 WHERE r=$r" + puts " \175" + puts "\175 {$r $a $x}" + puts "do_test $tname-4.$i.2 \173" + puts " db eval \173" + puts " SELECT r, a FROM t1 WHERE x='$x'" + puts " \175" + puts "\175 {$r $a}" + puts "do_test $tname-4.$i.3 \173" + puts " db eval \173" + puts " SELECT r, x FROM t1 WHERE a=$a" + puts " \175" + puts "\175 {$r $x}" + } + + foreach op {> >= < <=} subno {gt ge lt le} { + + ################################################################ 2.x.y.1 + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r" { + lappend rset $rx + lappend aset $t1ra($rx) + } + } + puts "do_test $tname-4.$i.$subno.1 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY a" + puts " \175" + puts "\175 {[sort $aset]}" + + ################################################################ 2.x.y.2 + puts "do_test $tname-4.$i.$subno.2 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY a DESC" + puts " \175" + puts "\175 {[reverse [sort $aset]]}" + + ################################################################ 2.x.y.3 + set aset {} + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-4.$i.$subno.3 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY r" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.4 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-4.$i.$subno.4 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY r DESC" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.5 + set aset {} + set xset {} + foreach rx $rset { + lappend xset $t1rx($rx) + } + foreach x [sort $xset] { + set rx $t1xr($x) + lappend aset $t1ra($rx) + } + puts "do_test $tname-4.$i.$subno.5 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r ORDER BY x" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.10 + if {abs($r)>9223372036854775808 || [string length $r5]>15} continue + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r0" { + lappend rset $rx + } + } + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-4.$i.$subno.10 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r0 ORDER BY r" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.11 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-4.$i.$subno.11 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r0 ORDER BY r DESC" + puts " \175" + puts "\175 {$aset}" + + + ################################################################ 2.x.y.12 + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r5" { + lappend rset $rx + } + } + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-4.$i.$subno.12 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r5 ORDER BY r" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.13 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-4.$i.$subno.13 \173" + puts " db eval \173" + puts " SELECT a FROM t1 WHERE r $op $r5 ORDER BY r DESC" + puts " \175" + puts "\175 {$aset}" + } +} + + +puts {finish_test} diff --git a/components/external/SQLite-3.8.1/test/boundary2.test b/components/external/SQLite-3.8.1/test/boundary2.test new file mode 100644 index 0000000000000000000000000000000000000000..15a824dc5d60f868e5286bcb046bbfcdf5db906a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/boundary2.test @@ -0,0 +1,15198 @@ +# 2008 December 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is automatically generated from a separate TCL script. +# This file seeks to exercise integer boundary values. +# +# $Id: boundary2.test,v 1.2 2009/01/02 15:45:48 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Many of the boundary tests depend on a working 64-bit implementation. +if {![working_64bit_int]} { finish_test; return } + +do_test boundary2-1.1 { + db eval { + CREATE TABLE t1(r INTEGER, a INTEGER, x TEXT); + INSERT INTO t1 VALUES(-8388609,1,'ffffffffff7fffff'); + INSERT INTO t1 VALUES(-36028797018963969,2,'ff7fffffffffffff'); + INSERT INTO t1 VALUES(9223372036854775807,3,'7fffffffffffffff'); + INSERT INTO t1 VALUES(127,4,'000000000000007f'); + INSERT INTO t1 VALUES(3,5,'0000000000000003'); + INSERT INTO t1 VALUES(16777216,6,'0000000001000000'); + INSERT INTO t1 VALUES(4398046511103,7,'000003ffffffffff'); + INSERT INTO t1 VALUES(16383,8,'0000000000003fff'); + INSERT INTO t1 VALUES(16777215,9,'0000000000ffffff'); + INSERT INTO t1 VALUES(281474976710655,10,'0000ffffffffffff'); + INSERT INTO t1 VALUES(-2147483648,11,'ffffffff80000000'); + INSERT INTO t1 VALUES(268435455,12,'000000000fffffff'); + INSERT INTO t1 VALUES(562949953421311,13,'0001ffffffffffff'); + INSERT INTO t1 VALUES(4294967295,14,'00000000ffffffff'); + INSERT INTO t1 VALUES(2097151,15,'00000000001fffff'); + INSERT INTO t1 VALUES(16384,16,'0000000000004000'); + INSERT INTO t1 VALUES(72057594037927935,17,'00ffffffffffffff'); + INSERT INTO t1 VALUES(8388607,18,'00000000007fffff'); + INSERT INTO t1 VALUES(1099511627776,19,'0000010000000000'); + INSERT INTO t1 VALUES(2147483647,20,'000000007fffffff'); + INSERT INTO t1 VALUES(-140737488355329,21,'ffff7fffffffffff'); + INSERT INTO t1 VALUES(34359738368,22,'0000000800000000'); + INSERT INTO t1 VALUES(32767,23,'0000000000007fff'); + INSERT INTO t1 VALUES(8388608,24,'0000000000800000'); + INSERT INTO t1 VALUES(140737488355327,25,'00007fffffffffff'); + INSERT INTO t1 VALUES(281474976710656,26,'0001000000000000'); + INSERT INTO t1 VALUES(36028797018963967,27,'007fffffffffffff'); + INSERT INTO t1 VALUES(72057594037927936,28,'0100000000000000'); + INSERT INTO t1 VALUES(-32769,29,'ffffffffffff7fff'); + INSERT INTO t1 VALUES(255,30,'00000000000000ff'); + INSERT INTO t1 VALUES(4,31,'0000000000000004'); + INSERT INTO t1 VALUES(-32768,32,'ffffffffffff8000'); + INSERT INTO t1 VALUES(-2,33,'fffffffffffffffe'); + INSERT INTO t1 VALUES(140737488355328,34,'0000800000000000'); + INSERT INTO t1 VALUES(549755813888,35,'0000008000000000'); + INSERT INTO t1 VALUES(4294967296,36,'0000000100000000'); + INSERT INTO t1 VALUES(-8388608,37,'ffffffffff800000'); + INSERT INTO t1 VALUES(-1,38,'ffffffffffffffff'); + INSERT INTO t1 VALUES(34359738367,39,'00000007ffffffff'); + INSERT INTO t1 VALUES(268435456,40,'0000000010000000'); + INSERT INTO t1 VALUES(2,41,'0000000000000002'); + INSERT INTO t1 VALUES(2097152,42,'0000000000200000'); + INSERT INTO t1 VALUES(562949953421312,43,'0002000000000000'); + INSERT INTO t1 VALUES(-140737488355328,44,'ffff800000000000'); + INSERT INTO t1 VALUES(36028797018963968,45,'0080000000000000'); + INSERT INTO t1 VALUES(549755813887,46,'0000007fffffffff'); + INSERT INTO t1 VALUES(-2147483649,47,'ffffffff7fffffff'); + INSERT INTO t1 VALUES(65535,48,'000000000000ffff'); + INSERT INTO t1 VALUES(128,49,'0000000000000080'); + INSERT INTO t1 VALUES(32768,50,'0000000000008000'); + INSERT INTO t1 VALUES(2147483648,51,'0000000080000000'); + INSERT INTO t1 VALUES(-3,52,'fffffffffffffffd'); + INSERT INTO t1 VALUES(-128,53,'ffffffffffffff80'); + INSERT INTO t1 VALUES(-129,54,'ffffffffffffff7f'); + INSERT INTO t1 VALUES(-9223372036854775808,55,'8000000000000000'); + INSERT INTO t1 VALUES(4398046511104,56,'0000040000000000'); + INSERT INTO t1 VALUES(1099511627775,57,'000000ffffffffff'); + INSERT INTO t1 VALUES(-549755813889,58,'ffffff7fffffffff'); + INSERT INTO t1 VALUES(0,59,'0000000000000000'); + INSERT INTO t1 VALUES(1,60,'0000000000000001'); + INSERT INTO t1 VALUES(256,61,'0000000000000100'); + INSERT INTO t1 VALUES(65536,62,'0000000000010000'); + INSERT INTO t1 VALUES(-549755813888,63,'ffffff8000000000'); + INSERT INTO t1 VALUES(-36028797018963968,64,'ff80000000000000'); + CREATE INDEX t1i1 ON t1(r); + CREATE INDEX t1i2 ON t1(a); + CREATE INDEX t1i3 ON t1(x); + } +} {} +do_test boundary2-1.2 { + db eval { + SELECT count(*) FROM t1 + } +} {64} +do_test boundary2-2.1.1 { + db eval { + SELECT * FROM t1 WHERE r=72057594037927935 + } +} {72057594037927935 17 00ffffffffffffff} +do_test boundary2-2.1.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00ffffffffffffff' + } +} {72057594037927935 17} +do_test boundary2-2.1.3 { + db eval { + SELECT r, x FROM t1 WHERE a=17 + } +} {72057594037927935 00ffffffffffffff} +do_test boundary2-2.1.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY a + } +} {3 28} +do_test boundary2-2.1.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY a DESC + } +} {28 3} +do_test boundary2-2.1.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY r + } +} {28 3} +do_test boundary2-2.1.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY r DESC + } +} {3 28} +do_test boundary2-2.1.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY x + } +} {28 3} +do_test boundary2-2.1.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY a + } +} {3 17 28} +do_test boundary2-2.1.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY a DESC + } +} {28 17 3} +do_test boundary2-2.1.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY r + } +} {17 28 3} +do_test boundary2-2.1.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY r DESC + } +} {3 28 17} +do_test boundary2-2.1.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY x + } +} {17 28 3} +do_test boundary2-2.1.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.1.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.1.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45} +do_test boundary2-2.1.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY r DESC + } +} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.1.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.1.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.1.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.1.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17} +do_test boundary2-2.1.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY r DESC + } +} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.1.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.2.1 { + db eval { + SELECT * FROM t1 WHERE r=16384 + } +} {16384 16 0000000000004000} +do_test boundary2-2.2.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000004000' + } +} {16384 16} +do_test boundary2-2.2.3 { + db eval { + SELECT r, x FROM t1 WHERE a=16 + } +} {16384 0000000000004000} +do_test boundary2-2.2.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-2.2.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.2.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY r + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.2.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary2-2.2.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY x + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.2.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-2.2.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.2.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY r + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.2.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary2-2.2.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY x + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.2.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY a + } +} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.2.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1} +do_test boundary2-2.2.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary2-2.2.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY r DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.2.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.2.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY a + } +} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.2.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1} +do_test boundary2-2.2.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary2-2.2.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY r DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.2.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.3.1 { + db eval { + SELECT * FROM t1 WHERE r=4294967296 + } +} {4294967296 36 0000000100000000} +do_test boundary2-2.3.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000100000000' + } +} {4294967296 36} +do_test boundary2-2.3.3 { + db eval { + SELECT r, x FROM t1 WHERE a=36 + } +} {4294967296 0000000100000000} +do_test boundary2-2.3.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57} +do_test boundary2-2.3.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY a DESC + } +} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-2.3.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY r + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.3.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary2-2.3.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY x + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.3.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary2-2.3.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-2.3.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY r + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.3.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary2-2.3.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY x + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.3.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.3.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.3.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary2-2.3.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY r DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.3.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.3.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.3.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.3.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary2-2.3.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY r DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.3.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.4.1 { + db eval { + SELECT * FROM t1 WHERE r=16777216 + } +} {16777216 6 0000000001000000} +do_test boundary2-2.4.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000001000000' + } +} {16777216 6} +do_test boundary2-2.4.3 { + db eval { + SELECT r, x FROM t1 WHERE a=6 + } +} {16777216 0000000001000000} +do_test boundary2-2.4.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY a + } +} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.4.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3} +do_test boundary2-2.4.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY r + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.4.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary2-2.4.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY x + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.4.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY a + } +} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.4.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3} +do_test boundary2-2.4.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY r + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.4.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary2-2.4.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY x + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.4.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY a + } +} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.4.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1} +do_test boundary2-2.4.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary2-2.4.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY r DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.4.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.4.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY a + } +} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.4.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1} +do_test boundary2-2.4.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary2-2.4.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY r DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.4.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.5.1 { + db eval { + SELECT * FROM t1 WHERE r=-32769 + } +} {-32769 29 ffffffffffff7fff} +do_test boundary2-2.5.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffff7fff' + } +} {-32769 29} +do_test boundary2-2.5.3 { + db eval { + SELECT r, x FROM t1 WHERE a=29 + } +} {-32769 ffffffffffff7fff} +do_test boundary2-2.5.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.5.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.5.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY r + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.5.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary2-2.5.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38} +do_test boundary2-2.5.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.5.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.5.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY r + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.5.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary2-2.5.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38} +do_test boundary2-2.5.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY a + } +} {1 2 11 21 37 44 47 55 58 63 64} +do_test boundary2-2.5.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 21 11 2 1} +do_test boundary2-2.5.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary2-2.5.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY r DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.5.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary2-2.5.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY a + } +} {1 2 11 21 29 37 44 47 55 58 63 64} +do_test boundary2-2.5.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 29 21 11 2 1} +do_test boundary2-2.5.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary2-2.5.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY r DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.5.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary2-2.6.1 { + db eval { + SELECT * FROM t1 WHERE r=-140737488355329 + } +} {-140737488355329 21 ffff7fffffffffff} +do_test boundary2-2.6.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffff7fffffffffff' + } +} {-140737488355329 21} +do_test boundary2-2.6.3 { + db eval { + SELECT r, x FROM t1 WHERE a=21 + } +} {-140737488355329 ffff7fffffffffff} +do_test boundary2-2.6.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-2.6.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.6.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY r + } +} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.6.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44} +do_test boundary2-2.6.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.6.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-2.6.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.6.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY r + } +} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.6.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21} +do_test boundary2-2.6.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.6.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY a + } +} {2 55 64} +do_test boundary2-2.6.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY a DESC + } +} {64 55 2} +do_test boundary2-2.6.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY r + } +} {55 2 64} +do_test boundary2-2.6.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY r DESC + } +} {64 2 55} +do_test boundary2-2.6.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY x + } +} {55 2 64} +do_test boundary2-2.6.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY a + } +} {2 21 55 64} +do_test boundary2-2.6.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY a DESC + } +} {64 55 21 2} +do_test boundary2-2.6.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY r + } +} {55 2 64 21} +do_test boundary2-2.6.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY r DESC + } +} {21 64 2 55} +do_test boundary2-2.6.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY x + } +} {55 2 64 21} +do_test boundary2-2.7.1 { + db eval { + SELECT * FROM t1 WHERE r=2 + } +} {2 41 0000000000000002} +do_test boundary2-2.7.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000002' + } +} {2 41} +do_test boundary2-2.7.3 { + db eval { + SELECT r, x FROM t1 WHERE a=41 + } +} {2 0000000000000002} +do_test boundary2-2.7.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.7.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.7.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY r + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.7.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary2-2.7.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY x + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.7.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.7.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.7.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY r + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.7.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary2-2.7.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY x + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.7.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.7.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-2.7.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary2-2.7.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY r DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.7.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY x + } +} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.7.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.7.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1} +do_test boundary2-2.7.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary2-2.7.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY r DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.7.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY x + } +} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.8.1 { + db eval { + SELECT * FROM t1 WHERE r=4 + } +} {4 31 0000000000000004} +do_test boundary2-2.8.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000004' + } +} {4 31} +do_test boundary2-2.8.3 { + db eval { + SELECT r, x FROM t1 WHERE a=31 + } +} {4 0000000000000004} +do_test boundary2-2.8.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.8.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary2-2.8.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY r + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.8.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary2-2.8.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY x + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.8.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.8.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary2-2.8.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY r + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.8.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary2-2.8.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY x + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.8.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY a + } +} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.8.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1} +do_test boundary2-2.8.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary2-2.8.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY r DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.8.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY x + } +} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.8.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY a + } +} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.8.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1} +do_test boundary2-2.8.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary2-2.8.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY r DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.8.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY x + } +} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.9.1 { + db eval { + SELECT * FROM t1 WHERE r=562949953421311 + } +} {562949953421311 13 0001ffffffffffff} +do_test boundary2-2.9.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0001ffffffffffff' + } +} {562949953421311 13} +do_test boundary2-2.9.3 { + db eval { + SELECT r, x FROM t1 WHERE a=13 + } +} {562949953421311 0001ffffffffffff} +do_test boundary2-2.9.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY a + } +} {3 17 27 28 43 45} +do_test boundary2-2.9.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY a DESC + } +} {45 43 28 27 17 3} +do_test boundary2-2.9.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY r + } +} {43 27 45 17 28 3} +do_test boundary2-2.9.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY r DESC + } +} {3 28 17 45 27 43} +do_test boundary2-2.9.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY x + } +} {43 27 45 17 28 3} +do_test boundary2-2.9.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY a + } +} {3 13 17 27 28 43 45} +do_test boundary2-2.9.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY a DESC + } +} {45 43 28 27 17 13 3} +do_test boundary2-2.9.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY r + } +} {13 43 27 45 17 28 3} +do_test boundary2-2.9.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY r DESC + } +} {3 28 17 45 27 43 13} +do_test boundary2-2.9.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY x + } +} {13 43 27 45 17 28 3} +do_test boundary2-2.9.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.9.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.9.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26} +do_test boundary2-2.9.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY r DESC + } +} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.9.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.9.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.9.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.9.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13} +do_test boundary2-2.9.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY r DESC + } +} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.9.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.10.1 { + db eval { + SELECT * FROM t1 WHERE r=256 + } +} {256 61 0000000000000100} +do_test boundary2-2.10.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000100' + } +} {256 61} +do_test boundary2-2.10.3 { + db eval { + SELECT r, x FROM t1 WHERE a=61 + } +} {256 0000000000000100} +do_test boundary2-2.10.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-2.10.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-2.10.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY r + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.10.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary2-2.10.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY x + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.10.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary2-2.10.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-2.10.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY r + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.10.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary2-2.10.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY x + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.10.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.10.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary2-2.10.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary2-2.10.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY r DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.10.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY x + } +} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.10.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.10.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary2-2.10.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary2-2.10.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY r DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.10.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.11.1 { + db eval { + SELECT * FROM t1 WHERE r=34359738368 + } +} {34359738368 22 0000000800000000} +do_test boundary2-2.11.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000800000000' + } +} {34359738368 22} +do_test boundary2-2.11.3 { + db eval { + SELECT r, x FROM t1 WHERE a=22 + } +} {34359738368 0000000800000000} +do_test boundary2-2.11.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary2-2.11.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-2.11.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY r + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.11.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary2-2.11.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY x + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.11.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary2-2.11.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-2.11.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY r + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.11.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary2-2.11.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY x + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.11.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.11.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.11.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary2-2.11.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY r DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.11.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.11.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.11.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.11.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary2-2.11.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY r DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.11.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.12.1 { + db eval { + SELECT * FROM t1 WHERE r=65536 + } +} {65536 62 0000000000010000} +do_test boundary2-2.12.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000010000' + } +} {65536 62} +do_test boundary2-2.12.3 { + db eval { + SELECT r, x FROM t1 WHERE a=62 + } +} {65536 0000000000010000} +do_test boundary2-2.12.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary2-2.12.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.12.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY r + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.12.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary2-2.12.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY x + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.12.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62} +do_test boundary2-2.12.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY a DESC + } +} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.12.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY r + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.12.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary2-2.12.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY x + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.12.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.12.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-2.12.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary2-2.12.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY r DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.12.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.12.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.12.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-2.12.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary2-2.12.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY r DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.12.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.13.1 { + db eval { + SELECT * FROM t1 WHERE r=268435456 + } +} {268435456 40 0000000010000000} +do_test boundary2-2.13.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000010000000' + } +} {268435456 40} +do_test boundary2-2.13.3 { + db eval { + SELECT r, x FROM t1 WHERE a=40 + } +} {268435456 0000000010000000} +do_test boundary2-2.13.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary2-2.13.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary2-2.13.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY r + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.13.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary2-2.13.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY x + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.13.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.13.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary2-2.13.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY r + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.13.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary2-2.13.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY x + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.13.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.13.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.13.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary2-2.13.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY r DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.13.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.13.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.13.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.13.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary2-2.13.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY r DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.13.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.14.1 { + db eval { + SELECT * FROM t1 WHERE r=-140737488355328 + } +} {-140737488355328 44 ffff800000000000} +do_test boundary2-2.14.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffff800000000000' + } +} {-140737488355328 44} +do_test boundary2-2.14.3 { + db eval { + SELECT r, x FROM t1 WHERE a=44 + } +} {-140737488355328 ffff800000000000} +do_test boundary2-2.14.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-2.14.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.14.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY r + } +} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.14.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58} +do_test boundary2-2.14.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.14.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-2.14.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.14.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY r + } +} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.14.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44} +do_test boundary2-2.14.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.14.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY a + } +} {2 21 55 64} +do_test boundary2-2.14.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY a DESC + } +} {64 55 21 2} +do_test boundary2-2.14.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY r + } +} {55 2 64 21} +do_test boundary2-2.14.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY r DESC + } +} {21 64 2 55} +do_test boundary2-2.14.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY x + } +} {55 2 64 21} +do_test boundary2-2.14.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY a + } +} {2 21 44 55 64} +do_test boundary2-2.14.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY a DESC + } +} {64 55 44 21 2} +do_test boundary2-2.14.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY r + } +} {55 2 64 21 44} +do_test boundary2-2.14.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY r DESC + } +} {44 21 64 2 55} +do_test boundary2-2.14.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY x + } +} {55 2 64 21 44} +do_test boundary2-2.15.1 { + db eval { + SELECT * FROM t1 WHERE r=1099511627776 + } +} {1099511627776 19 0000010000000000} +do_test boundary2-2.15.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000010000000000' + } +} {1099511627776 19} +do_test boundary2-2.15.3 { + db eval { + SELECT r, x FROM t1 WHERE a=19 + } +} {1099511627776 0000010000000000} +do_test boundary2-2.15.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY a + } +} {3 7 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary2-2.15.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 7 3} +do_test boundary2-2.15.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY r + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.15.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary2-2.15.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY x + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.15.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56} +do_test boundary2-2.15.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-2.15.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY r + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.15.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary2-2.15.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY x + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.15.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-2.15.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.15.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary2-2.15.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY r DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.15.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.15.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-2.15.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.15.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary2-2.15.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY r DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.15.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.16.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY a + } +} {} +do_test boundary2-2.16.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY a DESC + } +} {} +do_test boundary2-2.16.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY r + } +} {} +do_test boundary2-2.16.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY r DESC + } +} {} +do_test boundary2-2.16.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY x + } +} {} +do_test boundary2-2.16.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY a + } +} {3} +do_test boundary2-2.16.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY a DESC + } +} {3} +do_test boundary2-2.16.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY r + } +} {3} +do_test boundary2-2.16.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY r DESC + } +} {3} +do_test boundary2-2.16.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY x + } +} {3} +do_test boundary2-2.16.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.16.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.16.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28} +do_test boundary2-2.16.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY r DESC + } +} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.16.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.16.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.16.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-2.16.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.16.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.16.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.17.1 { + db eval { + SELECT * FROM t1 WHERE r=32768 + } +} {32768 50 0000000000008000} +do_test boundary2-2.17.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000008000' + } +} {32768 50} +do_test boundary2-2.17.3 { + db eval { + SELECT r, x FROM t1 WHERE a=50 + } +} {32768 0000000000008000} +do_test boundary2-2.17.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62} +do_test boundary2-2.17.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY a DESC + } +} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.17.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY r + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.17.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary2-2.17.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY x + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.17.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-2.17.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.17.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY r + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.17.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary2-2.17.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY x + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.17.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.17.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-2.17.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary2-2.17.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY r DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.17.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.17.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.17.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-2.17.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary2-2.17.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY r DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.17.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.18.1 { + db eval { + SELECT * FROM t1 WHERE r=-36028797018963968 + } +} {-36028797018963968 64 ff80000000000000} +do_test boundary2-2.18.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ff80000000000000' + } +} {-36028797018963968 64} +do_test boundary2-2.18.3 { + db eval { + SELECT r, x FROM t1 WHERE a=64 + } +} {-36028797018963968 ff80000000000000} +do_test boundary2-2.18.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-2.18.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.18.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY r + } +} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.18.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21} +do_test boundary2-2.18.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.18.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.18.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.18.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY r + } +} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.18.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64} +do_test boundary2-2.18.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.18.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY a + } +} {2 55} +do_test boundary2-2.18.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY a DESC + } +} {55 2} +do_test boundary2-2.18.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY r + } +} {55 2} +do_test boundary2-2.18.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY r DESC + } +} {2 55} +do_test boundary2-2.18.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY x + } +} {55 2} +do_test boundary2-2.18.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY a + } +} {2 55 64} +do_test boundary2-2.18.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY a DESC + } +} {64 55 2} +do_test boundary2-2.18.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY r + } +} {55 2 64} +do_test boundary2-2.18.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY r DESC + } +} {64 2 55} +do_test boundary2-2.18.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY x + } +} {55 2 64} +do_test boundary2-2.19.1 { + db eval { + SELECT * FROM t1 WHERE r=65535 + } +} {65535 48 000000000000ffff} +do_test boundary2-2.19.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000000000ffff' + } +} {65535 48} +do_test boundary2-2.19.3 { + db eval { + SELECT r, x FROM t1 WHERE a=48 + } +} {65535 000000000000ffff} +do_test boundary2-2.19.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62} +do_test boundary2-2.19.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY a DESC + } +} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.19.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY r + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.19.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary2-2.19.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY x + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.19.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62} +do_test boundary2-2.19.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY a DESC + } +} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.19.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY r + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.19.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary2-2.19.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY x + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.19.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.19.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-2.19.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary2-2.19.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY r DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.19.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.19.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.19.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-2.19.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary2-2.19.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY r DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.19.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.20.1 { + db eval { + SELECT * FROM t1 WHERE r=4294967295 + } +} {4294967295 14 00000000ffffffff} +do_test boundary2-2.20.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000000ffffffff' + } +} {4294967295 14} +do_test boundary2-2.20.3 { + db eval { + SELECT r, x FROM t1 WHERE a=14 + } +} {4294967295 00000000ffffffff} +do_test boundary2-2.20.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary2-2.20.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-2.20.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY r + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.20.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary2-2.20.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY x + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.20.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary2-2.20.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary2-2.20.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY r + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.20.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary2-2.20.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY x + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.20.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.20.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.20.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary2-2.20.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY r DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.20.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.20.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.20.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.20.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary2-2.20.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY r DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.20.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.21.1 { + db eval { + SELECT * FROM t1 WHERE r=1099511627775 + } +} {1099511627775 57 000000ffffffffff} +do_test boundary2-2.21.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000ffffffffff' + } +} {1099511627775 57} +do_test boundary2-2.21.3 { + db eval { + SELECT r, x FROM t1 WHERE a=57 + } +} {1099511627775 000000ffffffffff} +do_test boundary2-2.21.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56} +do_test boundary2-2.21.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-2.21.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY r + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.21.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary2-2.21.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY x + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.21.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57} +do_test boundary2-2.21.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY a DESC + } +} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-2.21.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY r + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.21.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary2-2.21.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY x + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.21.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.21.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.21.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary2-2.21.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY r DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.21.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.21.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-2.21.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.21.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary2-2.21.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY r DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.21.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.22.1 { + db eval { + SELECT * FROM t1 WHERE r=-8388608 + } +} {-8388608 37 ffffffffff800000} +do_test boundary2-2.22.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffff800000' + } +} {-8388608 37} +do_test boundary2-2.22.3 { + db eval { + SELECT r, x FROM t1 WHERE a=37 + } +} {-8388608 ffffffffff800000} +do_test boundary2-2.22.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.22.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.22.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY r + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.22.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary2-2.22.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38} +do_test boundary2-2.22.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.22.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.22.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY r + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.22.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary2-2.22.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38} +do_test boundary2-2.22.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY a + } +} {1 2 11 21 44 47 55 58 63 64} +do_test boundary2-2.22.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2 1} +do_test boundary2-2.22.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary2-2.22.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY r DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.22.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary2-2.22.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY a + } +} {1 2 11 21 37 44 47 55 58 63 64} +do_test boundary2-2.22.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 21 11 2 1} +do_test boundary2-2.22.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary2-2.22.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY r DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.22.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary2-2.23.1 { + db eval { + SELECT * FROM t1 WHERE r=549755813888 + } +} {549755813888 35 0000008000000000} +do_test boundary2-2.23.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000008000000000' + } +} {549755813888 35} +do_test boundary2-2.23.3 { + db eval { + SELECT r, x FROM t1 WHERE a=35 + } +} {549755813888 0000008000000000} +do_test boundary2-2.23.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57} +do_test boundary2-2.23.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY a DESC + } +} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-2.23.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY r + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.23.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary2-2.23.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY x + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.23.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57} +do_test boundary2-2.23.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY a DESC + } +} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-2.23.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY r + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.23.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary2-2.23.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY x + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.23.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.23.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.23.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary2-2.23.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY r DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.23.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.23.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.23.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.23.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary2-2.23.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY r DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.23.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.24.1 { + db eval { + SELECT * FROM t1 WHERE r=8388607 + } +} {8388607 18 00000000007fffff} +do_test boundary2-2.24.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000000007fffff' + } +} {8388607 18} +do_test boundary2-2.24.3 { + db eval { + SELECT r, x FROM t1 WHERE a=18 + } +} {8388607 00000000007fffff} +do_test boundary2-2.24.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.24.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary2-2.24.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY r + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.24.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary2-2.24.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY x + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.24.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.24.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary2-2.24.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY r + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.24.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary2-2.24.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY x + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.24.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.24.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary2-2.24.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary2-2.24.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY r DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.24.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.24.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.24.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary2-2.24.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary2-2.24.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY r DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.24.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.25.1 { + db eval { + SELECT * FROM t1 WHERE r=-3 + } +} {-3 52 fffffffffffffffd} +do_test boundary2-2.25.2 { + db eval { + SELECT r, a FROM t1 WHERE x='fffffffffffffffd' + } +} {-3 52} +do_test boundary2-2.25.3 { + db eval { + SELECT r, x FROM t1 WHERE a=52 + } +} {-3 fffffffffffffffd} +do_test boundary2-2.25.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-2.25.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.25.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY r + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.25.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary2-2.25.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38} +do_test boundary2-2.25.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62} +do_test boundary2-2.25.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY a DESC + } +} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.25.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY r + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.25.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary2-2.25.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38} +do_test boundary2-2.25.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64} +do_test boundary2-2.25.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY a DESC + } +} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1} +do_test boundary2-2.25.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary2-2.25.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY r DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.25.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary2-2.25.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64} +do_test boundary2-2.25.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1} +do_test boundary2-2.25.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary2-2.25.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY r DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.25.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary2-2.26.1 { + db eval { + SELECT * FROM t1 WHERE r=0 + } +} {0 59 0000000000000000} +do_test boundary2-2.26.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000000' + } +} {0 59} +do_test boundary2-2.26.3 { + db eval { + SELECT r, x FROM t1 WHERE a=59 + } +} {0 0000000000000000} +do_test boundary2-2.26.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62} +do_test boundary2-2.26.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY a DESC + } +} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.26.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY r + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.26.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary2-2.26.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY x + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.26.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-2.26.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.26.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY r + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.26.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary2-2.26.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.26.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64} +do_test boundary2-2.26.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-2.26.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.26.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY r DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.26.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.26.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64} +do_test boundary2-2.26.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY a DESC + } +} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-2.26.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary2-2.26.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY r DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.26.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY x + } +} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.27.1 { + db eval { + SELECT * FROM t1 WHERE r=-1 + } +} {-1 38 ffffffffffffffff} +do_test boundary2-2.27.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffffffff' + } +} {-1 38} +do_test boundary2-2.27.3 { + db eval { + SELECT r, x FROM t1 WHERE a=38 + } +} {-1 ffffffffffffffff} +do_test boundary2-2.27.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-2.27.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.27.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY r + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.27.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary2-2.27.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.27.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-2.27.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.27.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY r + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.27.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary2-2.27.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38} +do_test boundary2-2.27.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64} +do_test boundary2-2.27.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1} +do_test boundary2-2.27.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary2-2.27.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY r DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.27.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary2-2.27.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64} +do_test boundary2-2.27.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-2.27.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.27.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY r DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.27.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.28.1 { + db eval { + SELECT * FROM t1 WHERE r=-2 + } +} {-2 33 fffffffffffffffe} +do_test boundary2-2.28.2 { + db eval { + SELECT r, a FROM t1 WHERE x='fffffffffffffffe' + } +} {-2 33} +do_test boundary2-2.28.3 { + db eval { + SELECT r, x FROM t1 WHERE a=33 + } +} {-2 fffffffffffffffe} +do_test boundary2-2.28.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-2.28.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.28.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY r + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.28.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary2-2.28.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38} +do_test boundary2-2.28.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-2.28.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.28.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY r + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.28.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary2-2.28.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38} +do_test boundary2-2.28.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64} +do_test boundary2-2.28.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1} +do_test boundary2-2.28.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary2-2.28.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY r DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.28.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary2-2.28.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY a + } +} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64} +do_test boundary2-2.28.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1} +do_test boundary2-2.28.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary2-2.28.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY r DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.28.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary2-2.29.1 { + db eval { + SELECT * FROM t1 WHERE r=2097152 + } +} {2097152 42 0000000000200000} +do_test boundary2-2.29.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000200000' + } +} {2097152 42} +do_test boundary2-2.29.3 { + db eval { + SELECT r, x FROM t1 WHERE a=42 + } +} {2097152 0000000000200000} +do_test boundary2-2.29.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.29.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary2-2.29.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY r + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.29.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary2-2.29.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY x + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.29.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary2-2.29.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary2-2.29.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY r + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.29.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary2-2.29.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY x + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.29.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.29.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary2-2.29.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary2-2.29.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY r DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.29.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.29.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.29.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary2-2.29.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary2-2.29.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY r DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.29.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.30.1 { + db eval { + SELECT * FROM t1 WHERE r=128 + } +} {128 49 0000000000000080} +do_test boundary2-2.30.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000080' + } +} {128 49} +do_test boundary2-2.30.3 { + db eval { + SELECT r, x FROM t1 WHERE a=49 + } +} {128 0000000000000080} +do_test boundary2-2.30.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary2-2.30.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-2.30.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY r + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.30.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary2-2.30.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY x + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.30.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.30.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-2.30.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY r + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.30.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary2-2.30.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY x + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.30.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.30.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary2-2.30.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary2-2.30.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY r DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.30.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY x + } +} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.30.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.30.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary2-2.30.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary2-2.30.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY r DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.30.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY x + } +} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.31.1 { + db eval { + SELECT * FROM t1 WHERE r=255 + } +} {255 30 00000000000000ff} +do_test boundary2-2.31.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000000000000ff' + } +} {255 30} +do_test boundary2-2.31.3 { + db eval { + SELECT r, x FROM t1 WHERE a=30 + } +} {255 00000000000000ff} +do_test boundary2-2.31.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary2-2.31.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-2.31.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY r + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.31.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary2-2.31.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY x + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.31.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary2-2.31.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-2.31.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY r + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.31.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary2-2.31.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY x + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.31.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.31.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary2-2.31.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary2-2.31.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY r DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.31.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY x + } +} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.31.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.31.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary2-2.31.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary2-2.31.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY r DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.31.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY x + } +} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.32.1 { + db eval { + SELECT * FROM t1 WHERE r=-2147483648 + } +} {-2147483648 11 ffffffff80000000} +do_test boundary2-2.32.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffff80000000' + } +} {-2147483648 11} +do_test boundary2-2.32.3 { + db eval { + SELECT r, x FROM t1 WHERE a=11 + } +} {-2147483648 ffffffff80000000} +do_test boundary2-2.32.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.32.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.32.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY r + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.32.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary2-2.32.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.32.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.32.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.32.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY r + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.32.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary2-2.32.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.32.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY a + } +} {2 21 44 47 55 58 63 64} +do_test boundary2-2.32.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 2} +do_test boundary2-2.32.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY r + } +} {55 2 64 21 44 58 63 47} +do_test boundary2-2.32.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY r DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary2-2.32.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY x + } +} {55 2 64 21 44 58 63 47} +do_test boundary2-2.32.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY a + } +} {2 11 21 44 47 55 58 63 64} +do_test boundary2-2.32.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2} +do_test boundary2-2.32.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary2-2.32.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY r DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary2-2.32.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary2-2.33.1 { + db eval { + SELECT * FROM t1 WHERE r=34359738367 + } +} {34359738367 39 00000007ffffffff} +do_test boundary2-2.33.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000007ffffffff' + } +} {34359738367 39} +do_test boundary2-2.33.3 { + db eval { + SELECT r, x FROM t1 WHERE a=39 + } +} {34359738367 00000007ffffffff} +do_test boundary2-2.33.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary2-2.33.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-2.33.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY r + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.33.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary2-2.33.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY x + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.33.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57} +do_test boundary2-2.33.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY a DESC + } +} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-2.33.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY r + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.33.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary2-2.33.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY x + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.33.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.33.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.33.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary2-2.33.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY r DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.33.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.33.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.33.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.33.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary2-2.33.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY r DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.33.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.34.1 { + db eval { + SELECT * FROM t1 WHERE r=-549755813889 + } +} {-549755813889 58 ffffff7fffffffff} +do_test boundary2-2.34.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffff7fffffffff' + } +} {-549755813889 58} +do_test boundary2-2.34.3 { + db eval { + SELECT r, x FROM t1 WHERE a=58 + } +} {-549755813889 ffffff7fffffffff} +do_test boundary2-2.34.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63} +do_test boundary2-2.34.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY a DESC + } +} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.34.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY r + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.34.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary2-2.34.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.34.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-2.34.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.34.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY r + } +} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.34.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58} +do_test boundary2-2.34.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.34.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY a + } +} {2 21 44 55 64} +do_test boundary2-2.34.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY a DESC + } +} {64 55 44 21 2} +do_test boundary2-2.34.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY r + } +} {55 2 64 21 44} +do_test boundary2-2.34.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY r DESC + } +} {44 21 64 2 55} +do_test boundary2-2.34.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY x + } +} {55 2 64 21 44} +do_test boundary2-2.34.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY a + } +} {2 21 44 55 58 64} +do_test boundary2-2.34.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY a DESC + } +} {64 58 55 44 21 2} +do_test boundary2-2.34.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY r + } +} {55 2 64 21 44 58} +do_test boundary2-2.34.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY r DESC + } +} {58 44 21 64 2 55} +do_test boundary2-2.34.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY x + } +} {55 2 64 21 44 58} +do_test boundary2-2.35.1 { + db eval { + SELECT * FROM t1 WHERE r=-32768 + } +} {-32768 32 ffffffffffff8000} +do_test boundary2-2.35.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffff8000' + } +} {-32768 32} +do_test boundary2-2.35.3 { + db eval { + SELECT r, x FROM t1 WHERE a=32 + } +} {-32768 ffffffffffff8000} +do_test boundary2-2.35.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.35.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.35.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY r + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.35.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary2-2.35.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38} +do_test boundary2-2.35.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.35.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.35.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY r + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.35.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary2-2.35.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38} +do_test boundary2-2.35.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY a + } +} {1 2 11 21 29 37 44 47 55 58 63 64} +do_test boundary2-2.35.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 29 21 11 2 1} +do_test boundary2-2.35.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary2-2.35.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY r DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.35.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary2-2.35.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 55 58 63 64} +do_test boundary2-2.35.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 32 29 21 11 2 1} +do_test boundary2-2.35.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary2-2.35.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY r DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.35.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary2-2.36.1 { + db eval { + SELECT * FROM t1 WHERE r=2147483647 + } +} {2147483647 20 000000007fffffff} +do_test boundary2-2.36.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000007fffffff' + } +} {2147483647 20} +do_test boundary2-2.36.3 { + db eval { + SELECT r, x FROM t1 WHERE a=20 + } +} {2147483647 000000007fffffff} +do_test boundary2-2.36.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary2-2.36.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary2-2.36.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY r + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.36.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary2-2.36.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY x + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.36.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary2-2.36.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary2-2.36.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY r + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.36.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary2-2.36.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY x + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.36.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.36.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.36.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary2-2.36.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY r DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.36.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.36.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.36.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.36.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary2-2.36.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY r DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.36.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.37.1 { + db eval { + SELECT * FROM t1 WHERE r=-129 + } +} {-129 54 ffffffffffffff7f} +do_test boundary2-2.37.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffffff7f' + } +} {-129 54} +do_test boundary2-2.37.3 { + db eval { + SELECT r, x FROM t1 WHERE a=54 + } +} {-129 ffffffffffffff7f} +do_test boundary2-2.37.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62} +do_test boundary2-2.37.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY a DESC + } +} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.37.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY r + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.37.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary2-2.37.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38} +do_test boundary2-2.37.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.37.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.37.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY r + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.37.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary2-2.37.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38} +do_test boundary2-2.37.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 55 58 63 64} +do_test boundary2-2.37.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 32 29 21 11 2 1} +do_test boundary2-2.37.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary2-2.37.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY r DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.37.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary2-2.37.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 54 55 58 63 64} +do_test boundary2-2.37.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY a DESC + } +} {64 63 58 55 54 47 44 37 32 29 21 11 2 1} +do_test boundary2-2.37.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary2-2.37.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY r DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.37.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary2-2.38.1 { + db eval { + SELECT * FROM t1 WHERE r=-128 + } +} {-128 53 ffffffffffffff80} +do_test boundary2-2.38.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffffff80' + } +} {-128 53} +do_test boundary2-2.38.3 { + db eval { + SELECT r, x FROM t1 WHERE a=53 + } +} {-128 ffffffffffffff80} +do_test boundary2-2.38.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62} +do_test boundary2-2.38.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY a DESC + } +} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.38.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY r + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.38.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary2-2.38.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38} +do_test boundary2-2.38.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62} +do_test boundary2-2.38.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY a DESC + } +} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.38.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY r + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.38.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary2-2.38.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38} +do_test boundary2-2.38.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 54 55 58 63 64} +do_test boundary2-2.38.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY a DESC + } +} {64 63 58 55 54 47 44 37 32 29 21 11 2 1} +do_test boundary2-2.38.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary2-2.38.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY r DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.38.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary2-2.38.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64} +do_test boundary2-2.38.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY a DESC + } +} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1} +do_test boundary2-2.38.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary2-2.38.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY r DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.38.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary2-2.39.1 { + db eval { + SELECT * FROM t1 WHERE r=72057594037927936 + } +} {72057594037927936 28 0100000000000000} +do_test boundary2-2.39.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0100000000000000' + } +} {72057594037927936 28} +do_test boundary2-2.39.3 { + db eval { + SELECT r, x FROM t1 WHERE a=28 + } +} {72057594037927936 0100000000000000} +do_test boundary2-2.39.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY a + } +} {3} +do_test boundary2-2.39.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY a DESC + } +} {3} +do_test boundary2-2.39.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY r + } +} {3} +do_test boundary2-2.39.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY r DESC + } +} {3} +do_test boundary2-2.39.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY x + } +} {3} +do_test boundary2-2.39.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY a + } +} {3 28} +do_test boundary2-2.39.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY a DESC + } +} {28 3} +do_test boundary2-2.39.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY r + } +} {28 3} +do_test boundary2-2.39.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY r DESC + } +} {3 28} +do_test boundary2-2.39.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY x + } +} {28 3} +do_test boundary2-2.39.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.39.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.39.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17} +do_test boundary2-2.39.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY r DESC + } +} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.39.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.39.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.39.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.39.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28} +do_test boundary2-2.39.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY r DESC + } +} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.39.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.40.1 { + db eval { + SELECT * FROM t1 WHERE r=2147483648 + } +} {2147483648 51 0000000080000000} +do_test boundary2-2.40.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000080000000' + } +} {2147483648 51} +do_test boundary2-2.40.3 { + db eval { + SELECT r, x FROM t1 WHERE a=51 + } +} {2147483648 0000000080000000} +do_test boundary2-2.40.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary2-2.40.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary2-2.40.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY r + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.40.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary2-2.40.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY x + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.40.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary2-2.40.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary2-2.40.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY r + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.40.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary2-2.40.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY x + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.40.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.40.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.40.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary2-2.40.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY r DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.40.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.40.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.40.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.40.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary2-2.40.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY r DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.40.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.41.1 { + db eval { + SELECT * FROM t1 WHERE r=549755813887 + } +} {549755813887 46 0000007fffffffff} +do_test boundary2-2.41.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000007fffffffff' + } +} {549755813887 46} +do_test boundary2-2.41.3 { + db eval { + SELECT r, x FROM t1 WHERE a=46 + } +} {549755813887 0000007fffffffff} +do_test boundary2-2.41.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57} +do_test boundary2-2.41.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY a DESC + } +} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-2.41.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY r + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.41.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary2-2.41.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY x + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.41.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary2-2.41.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-2.41.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY r + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.41.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary2-2.41.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY x + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.41.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.41.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.41.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary2-2.41.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY r DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.41.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.41.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.41.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.41.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary2-2.41.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY r DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.41.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.42.1 { + db eval { + SELECT * FROM t1 WHERE r=-549755813888 + } +} {-549755813888 63 ffffff8000000000} +do_test boundary2-2.42.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffff8000000000' + } +} {-549755813888 63} +do_test boundary2-2.42.3 { + db eval { + SELECT r, x FROM t1 WHERE a=63 + } +} {-549755813888 ffffff8000000000} +do_test boundary2-2.42.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.42.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.42.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY r + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.42.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary2-2.42.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.42.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63} +do_test boundary2-2.42.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY a DESC + } +} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.42.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY r + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.42.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary2-2.42.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.42.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY a + } +} {2 21 44 55 58 64} +do_test boundary2-2.42.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY a DESC + } +} {64 58 55 44 21 2} +do_test boundary2-2.42.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY r + } +} {55 2 64 21 44 58} +do_test boundary2-2.42.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY r DESC + } +} {58 44 21 64 2 55} +do_test boundary2-2.42.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY x + } +} {55 2 64 21 44 58} +do_test boundary2-2.42.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY a + } +} {2 21 44 55 58 63 64} +do_test boundary2-2.42.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY a DESC + } +} {64 63 58 55 44 21 2} +do_test boundary2-2.42.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY r + } +} {55 2 64 21 44 58 63} +do_test boundary2-2.42.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY r DESC + } +} {63 58 44 21 64 2 55} +do_test boundary2-2.42.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY x + } +} {55 2 64 21 44 58 63} +do_test boundary2-2.43.1 { + db eval { + SELECT * FROM t1 WHERE r=281474976710655 + } +} {281474976710655 10 0000ffffffffffff} +do_test boundary2-2.43.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000ffffffffffff' + } +} {281474976710655 10} +do_test boundary2-2.43.3 { + db eval { + SELECT r, x FROM t1 WHERE a=10 + } +} {281474976710655 0000ffffffffffff} +do_test boundary2-2.43.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY a + } +} {3 13 17 26 27 28 43 45} +do_test boundary2-2.43.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 3} +do_test boundary2-2.43.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY r + } +} {26 13 43 27 45 17 28 3} +do_test boundary2-2.43.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26} +do_test boundary2-2.43.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY x + } +} {26 13 43 27 45 17 28 3} +do_test boundary2-2.43.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY a + } +} {3 10 13 17 26 27 28 43 45} +do_test boundary2-2.43.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 10 3} +do_test boundary2-2.43.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY r + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary2-2.43.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10} +do_test boundary2-2.43.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY x + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary2-2.43.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.43.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-2.43.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34} +do_test boundary2-2.43.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY r DESC + } +} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.43.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.43.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.43.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.43.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10} +do_test boundary2-2.43.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY r DESC + } +} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.43.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.44.1 { + db eval { + SELECT * FROM t1 WHERE r=4398046511103 + } +} {4398046511103 7 000003ffffffffff} +do_test boundary2-2.44.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000003ffffffffff' + } +} {4398046511103 7} +do_test boundary2-2.44.3 { + db eval { + SELECT r, x FROM t1 WHERE a=7 + } +} {4398046511103 000003ffffffffff} +do_test boundary2-2.44.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary2-2.44.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 3} +do_test boundary2-2.44.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY r + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.44.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary2-2.44.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY x + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.44.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY a + } +} {3 7 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary2-2.44.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 7 3} +do_test boundary2-2.44.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY r + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.44.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary2-2.44.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY x + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.44.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-2.44.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.44.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary2-2.44.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY r DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.44.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.44.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-2.44.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-2.44.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary2-2.44.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY r DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.44.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.45.1 { + db eval { + SELECT * FROM t1 WHERE r=268435455 + } +} {268435455 12 000000000fffffff} +do_test boundary2-2.45.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000000fffffff' + } +} {268435455 12} +do_test boundary2-2.45.3 { + db eval { + SELECT r, x FROM t1 WHERE a=12 + } +} {268435455 000000000fffffff} +do_test boundary2-2.45.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.45.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary2-2.45.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY r + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.45.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary2-2.45.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY x + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.45.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY a + } +} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.45.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3} +do_test boundary2-2.45.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY r + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.45.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary2-2.45.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY x + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.45.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY a + } +} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.45.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1} +do_test boundary2-2.45.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary2-2.45.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY r DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.45.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.45.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.45.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-2.45.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary2-2.45.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY r DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.45.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.46.1 { + db eval { + SELECT * FROM t1 WHERE r=-9223372036854775808 + } +} {-9223372036854775808 55 8000000000000000} +do_test boundary2-2.46.2 { + db eval { + SELECT r, a FROM t1 WHERE x='8000000000000000' + } +} {-9223372036854775808 55} +do_test boundary2-2.46.3 { + db eval { + SELECT r, x FROM t1 WHERE a=55 + } +} {-9223372036854775808 8000000000000000} +do_test boundary2-2.46.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.46.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-2.46.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY r + } +} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.46.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2} +do_test boundary2-2.46.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.46.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.46.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-2.46.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.46.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.46.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.46.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY a + } +} {} +do_test boundary2-2.46.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY a DESC + } +} {} +do_test boundary2-2.46.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY r + } +} {} +do_test boundary2-2.46.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY r DESC + } +} {} +do_test boundary2-2.46.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY x + } +} {} +do_test boundary2-2.46.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY a + } +} {55} +do_test boundary2-2.46.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY a DESC + } +} {55} +do_test boundary2-2.46.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY r + } +} {55} +do_test boundary2-2.46.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY r DESC + } +} {55} +do_test boundary2-2.46.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY x + } +} {55} +do_test boundary2-2.47.1 { + db eval { + SELECT * FROM t1 WHERE r=562949953421312 + } +} {562949953421312 43 0002000000000000} +do_test boundary2-2.47.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0002000000000000' + } +} {562949953421312 43} +do_test boundary2-2.47.3 { + db eval { + SELECT r, x FROM t1 WHERE a=43 + } +} {562949953421312 0002000000000000} +do_test boundary2-2.47.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY a + } +} {3 17 27 28 45} +do_test boundary2-2.47.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY a DESC + } +} {45 28 27 17 3} +do_test boundary2-2.47.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY r + } +} {27 45 17 28 3} +do_test boundary2-2.47.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY r DESC + } +} {3 28 17 45 27} +do_test boundary2-2.47.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY x + } +} {27 45 17 28 3} +do_test boundary2-2.47.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY a + } +} {3 17 27 28 43 45} +do_test boundary2-2.47.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY a DESC + } +} {45 43 28 27 17 3} +do_test boundary2-2.47.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY r + } +} {43 27 45 17 28 3} +do_test boundary2-2.47.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY r DESC + } +} {3 28 17 45 27 43} +do_test boundary2-2.47.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY x + } +} {43 27 45 17 28 3} +do_test boundary2-2.47.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.47.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.47.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13} +do_test boundary2-2.47.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY r DESC + } +} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.47.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.47.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.47.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.47.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43} +do_test boundary2-2.47.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY r DESC + } +} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.47.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.48.1 { + db eval { + SELECT * FROM t1 WHERE r=-8388609 + } +} {-8388609 1 ffffffffff7fffff} +do_test boundary2-2.48.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffff7fffff' + } +} {-8388609 1} +do_test boundary2-2.48.3 { + db eval { + SELECT r, x FROM t1 WHERE a=1 + } +} {-8388609 ffffffffff7fffff} +do_test boundary2-2.48.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.48.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.48.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY r + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.48.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary2-2.48.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38} +do_test boundary2-2.48.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.48.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.48.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY r + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.48.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary2-2.48.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.48.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY a + } +} {2 11 21 44 47 55 58 63 64} +do_test boundary2-2.48.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2} +do_test boundary2-2.48.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary2-2.48.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY r DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary2-2.48.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary2-2.48.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY a + } +} {1 2 11 21 44 47 55 58 63 64} +do_test boundary2-2.48.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2 1} +do_test boundary2-2.48.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary2-2.48.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY r DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.48.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary2-2.49.1 { + db eval { + SELECT * FROM t1 WHERE r=16777215 + } +} {16777215 9 0000000000ffffff} +do_test boundary2-2.49.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000ffffff' + } +} {16777215 9} +do_test boundary2-2.49.3 { + db eval { + SELECT r, x FROM t1 WHERE a=9 + } +} {16777215 0000000000ffffff} +do_test boundary2-2.49.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY a + } +} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.49.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3} +do_test boundary2-2.49.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY r + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.49.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary2-2.49.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY x + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.49.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.49.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary2-2.49.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY r + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.49.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary2-2.49.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY x + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.49.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.49.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary2-2.49.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary2-2.49.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY r DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.49.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.49.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY a + } +} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.49.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1} +do_test boundary2-2.49.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary2-2.49.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY r DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.49.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.50.1 { + db eval { + SELECT * FROM t1 WHERE r=8388608 + } +} {8388608 24 0000000000800000} +do_test boundary2-2.50.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000800000' + } +} {8388608 24} +do_test boundary2-2.50.3 { + db eval { + SELECT r, x FROM t1 WHERE a=24 + } +} {8388608 0000000000800000} +do_test boundary2-2.50.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.50.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary2-2.50.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY r + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.50.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary2-2.50.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY x + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.50.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-2.50.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary2-2.50.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY r + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.50.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary2-2.50.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY x + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.50.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.50.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary2-2.50.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary2-2.50.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY r DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.50.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.50.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.50.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary2-2.50.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary2-2.50.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY r DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.50.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.51.1 { + db eval { + SELECT * FROM t1 WHERE r=16383 + } +} {16383 8 0000000000003fff} +do_test boundary2-2.51.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000003fff' + } +} {16383 8} +do_test boundary2-2.51.3 { + db eval { + SELECT r, x FROM t1 WHERE a=8 + } +} {16383 0000000000003fff} +do_test boundary2-2.51.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-2.51.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.51.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY r + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.51.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary2-2.51.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY x + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.51.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-2.51.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-2.51.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY r + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.51.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary2-2.51.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY x + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.51.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.51.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary2-2.51.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary2-2.51.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY r DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.51.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.51.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY a + } +} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.51.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1} +do_test boundary2-2.51.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary2-2.51.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY r DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.51.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.52.1 { + db eval { + SELECT * FROM t1 WHERE r=140737488355328 + } +} {140737488355328 34 0000800000000000} +do_test boundary2-2.52.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000800000000000' + } +} {140737488355328 34} +do_test boundary2-2.52.3 { + db eval { + SELECT r, x FROM t1 WHERE a=34 + } +} {140737488355328 0000800000000000} +do_test boundary2-2.52.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY a + } +} {3 10 13 17 26 27 28 43 45} +do_test boundary2-2.52.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 10 3} +do_test boundary2-2.52.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY r + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary2-2.52.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10} +do_test boundary2-2.52.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY x + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary2-2.52.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY a + } +} {3 10 13 17 26 27 28 34 43 45} +do_test boundary2-2.52.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY a DESC + } +} {45 43 34 28 27 26 17 13 10 3} +do_test boundary2-2.52.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY r + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.52.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34} +do_test boundary2-2.52.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY x + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.52.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.52.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-2.52.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25} +do_test boundary2-2.52.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY r DESC + } +} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.52.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.52.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.52.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-2.52.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34} +do_test boundary2-2.52.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY r DESC + } +} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.52.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.53.1 { + db eval { + SELECT * FROM t1 WHERE r=2097151 + } +} {2097151 15 00000000001fffff} +do_test boundary2-2.53.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000000001fffff' + } +} {2097151 15} +do_test boundary2-2.53.3 { + db eval { + SELECT r, x FROM t1 WHERE a=15 + } +} {2097151 00000000001fffff} +do_test boundary2-2.53.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary2-2.53.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary2-2.53.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY r + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.53.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary2-2.53.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY x + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.53.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary2-2.53.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.53.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY r + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.53.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary2-2.53.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY x + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.53.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.53.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-2.53.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary2-2.53.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY r DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.53.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.53.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-2.53.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary2-2.53.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary2-2.53.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY r DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.53.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.54.1 { + db eval { + SELECT * FROM t1 WHERE r=140737488355327 + } +} {140737488355327 25 00007fffffffffff} +do_test boundary2-2.54.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00007fffffffffff' + } +} {140737488355327 25} +do_test boundary2-2.54.3 { + db eval { + SELECT r, x FROM t1 WHERE a=25 + } +} {140737488355327 00007fffffffffff} +do_test boundary2-2.54.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY a + } +} {3 10 13 17 26 27 28 34 43 45} +do_test boundary2-2.54.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY a DESC + } +} {45 43 34 28 27 26 17 13 10 3} +do_test boundary2-2.54.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY r + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.54.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34} +do_test boundary2-2.54.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY x + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.54.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45} +do_test boundary2-2.54.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY a DESC + } +} {45 43 34 28 27 26 25 17 13 10 3} +do_test boundary2-2.54.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY r + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.54.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25} +do_test boundary2-2.54.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY x + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.54.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.54.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-2.54.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56} +do_test boundary2-2.54.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY r DESC + } +} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.54.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.54.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.54.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-2.54.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25} +do_test boundary2-2.54.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY r DESC + } +} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.54.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.55.1 { + db eval { + SELECT * FROM t1 WHERE r=281474976710656 + } +} {281474976710656 26 0001000000000000} +do_test boundary2-2.55.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0001000000000000' + } +} {281474976710656 26} +do_test boundary2-2.55.3 { + db eval { + SELECT r, x FROM t1 WHERE a=26 + } +} {281474976710656 0001000000000000} +do_test boundary2-2.55.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY a + } +} {3 13 17 27 28 43 45} +do_test boundary2-2.55.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY a DESC + } +} {45 43 28 27 17 13 3} +do_test boundary2-2.55.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY r + } +} {13 43 27 45 17 28 3} +do_test boundary2-2.55.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY r DESC + } +} {3 28 17 45 27 43 13} +do_test boundary2-2.55.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY x + } +} {13 43 27 45 17 28 3} +do_test boundary2-2.55.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY a + } +} {3 13 17 26 27 28 43 45} +do_test boundary2-2.55.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 3} +do_test boundary2-2.55.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY r + } +} {26 13 43 27 45 17 28 3} +do_test boundary2-2.55.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26} +do_test boundary2-2.55.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY x + } +} {26 13 43 27 45 17 28 3} +do_test boundary2-2.55.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.55.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.55.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10} +do_test boundary2-2.55.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY r DESC + } +} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.55.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.55.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.55.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.55.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26} +do_test boundary2-2.55.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY r DESC + } +} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.55.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.56.1 { + db eval { + SELECT * FROM t1 WHERE r=32767 + } +} {32767 23 0000000000007fff} +do_test boundary2-2.56.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000007fff' + } +} {32767 23} +do_test boundary2-2.56.3 { + db eval { + SELECT r, x FROM t1 WHERE a=23 + } +} {32767 0000000000007fff} +do_test boundary2-2.56.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-2.56.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.56.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY r + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.56.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary2-2.56.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY x + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.56.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-2.56.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-2.56.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY r + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.56.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary2-2.56.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY x + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.56.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY a + } +} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.56.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1} +do_test boundary2-2.56.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary2-2.56.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY r DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.56.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.56.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-2.56.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-2.56.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary2-2.56.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY r DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.56.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.57.1 { + db eval { + SELECT * FROM t1 WHERE r=127 + } +} {127 4 000000000000007f} +do_test boundary2-2.57.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000000000007f' + } +} {127 4} +do_test boundary2-2.57.3 { + db eval { + SELECT r, x FROM t1 WHERE a=4 + } +} {127 000000000000007f} +do_test boundary2-2.57.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.57.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-2.57.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY r + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.57.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary2-2.57.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY x + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.57.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.57.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary2-2.57.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY r + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.57.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary2-2.57.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY x + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.57.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY a + } +} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.57.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1} +do_test boundary2-2.57.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary2-2.57.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY r DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.57.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY x + } +} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.57.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.57.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary2-2.57.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary2-2.57.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY r DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.57.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY x + } +} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.58.1 { + db eval { + SELECT * FROM t1 WHERE r=36028797018963967 + } +} {36028797018963967 27 007fffffffffffff} +do_test boundary2-2.58.2 { + db eval { + SELECT r, a FROM t1 WHERE x='007fffffffffffff' + } +} {36028797018963967 27} +do_test boundary2-2.58.3 { + db eval { + SELECT r, x FROM t1 WHERE a=27 + } +} {36028797018963967 007fffffffffffff} +do_test boundary2-2.58.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY a + } +} {3 17 28 45} +do_test boundary2-2.58.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY a DESC + } +} {45 28 17 3} +do_test boundary2-2.58.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY r + } +} {45 17 28 3} +do_test boundary2-2.58.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY r DESC + } +} {3 28 17 45} +do_test boundary2-2.58.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY x + } +} {45 17 28 3} +do_test boundary2-2.58.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY a + } +} {3 17 27 28 45} +do_test boundary2-2.58.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY a DESC + } +} {45 28 27 17 3} +do_test boundary2-2.58.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY r + } +} {27 45 17 28 3} +do_test boundary2-2.58.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY r DESC + } +} {3 28 17 45 27} +do_test boundary2-2.58.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY x + } +} {27 45 17 28 3} +do_test boundary2-2.58.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.58.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.58.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43} +do_test boundary2-2.58.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY r DESC + } +} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.58.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.58.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.58.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.58.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27} +do_test boundary2-2.58.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY r DESC + } +} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.58.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.59.1 { + db eval { + SELECT * FROM t1 WHERE r=4398046511104 + } +} {4398046511104 56 0000040000000000} +do_test boundary2-2.59.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000040000000000' + } +} {4398046511104 56} +do_test boundary2-2.59.3 { + db eval { + SELECT r, x FROM t1 WHERE a=56 + } +} {4398046511104 0000040000000000} +do_test boundary2-2.59.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45} +do_test boundary2-2.59.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY a DESC + } +} {45 43 34 28 27 26 25 17 13 10 3} +do_test boundary2-2.59.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY r + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.59.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25} +do_test boundary2-2.59.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY x + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.59.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary2-2.59.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 3} +do_test boundary2-2.59.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY r + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.59.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary2-2.59.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY x + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.59.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-2.59.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-2.59.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary2-2.59.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY r DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.59.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.59.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.59.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-2.59.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56} +do_test boundary2-2.59.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY r DESC + } +} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.59.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.60.1 { + db eval { + SELECT * FROM t1 WHERE r=1 + } +} {1 60 0000000000000001} +do_test boundary2-2.60.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000001' + } +} {1 60} +do_test boundary2-2.60.3 { + db eval { + SELECT r, x FROM t1 WHERE a=60 + } +} {1 0000000000000001} +do_test boundary2-2.60.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.60.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.60.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY r + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.60.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary2-2.60.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY x + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.60.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62} +do_test boundary2-2.60.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY a DESC + } +} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.60.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY r + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.60.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary2-2.60.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY x + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.60.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64} +do_test boundary2-2.60.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY a DESC + } +} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-2.60.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary2-2.60.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY r DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.60.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY x + } +} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.60.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.60.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-2.60.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary2-2.60.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY r DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.60.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY x + } +} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.61.1 { + db eval { + SELECT * FROM t1 WHERE r=36028797018963968 + } +} {36028797018963968 45 0080000000000000} +do_test boundary2-2.61.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0080000000000000' + } +} {36028797018963968 45} +do_test boundary2-2.61.3 { + db eval { + SELECT r, x FROM t1 WHERE a=45 + } +} {36028797018963968 0080000000000000} +do_test boundary2-2.61.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY a + } +} {3 17 28} +do_test boundary2-2.61.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY a DESC + } +} {28 17 3} +do_test boundary2-2.61.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY r + } +} {17 28 3} +do_test boundary2-2.61.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY r DESC + } +} {3 28 17} +do_test boundary2-2.61.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY x + } +} {17 28 3} +do_test boundary2-2.61.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY a + } +} {3 17 28 45} +do_test boundary2-2.61.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY a DESC + } +} {45 28 17 3} +do_test boundary2-2.61.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY r + } +} {45 17 28 3} +do_test boundary2-2.61.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY r DESC + } +} {3 28 17 45} +do_test boundary2-2.61.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY x + } +} {45 17 28 3} +do_test boundary2-2.61.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.61.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.61.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27} +do_test boundary2-2.61.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY r DESC + } +} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.61.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.61.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.61.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-2.61.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45} +do_test boundary2-2.61.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY r DESC + } +} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.61.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.62.1 { + db eval { + SELECT * FROM t1 WHERE r=-2147483649 + } +} {-2147483649 47 ffffffff7fffffff} +do_test boundary2-2.62.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffff7fffffff' + } +} {-2147483649 47} +do_test boundary2-2.62.3 { + db eval { + SELECT r, x FROM t1 WHERE a=47 + } +} {-2147483649 ffffffff7fffffff} +do_test boundary2-2.62.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.62.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.62.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY r + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.62.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary2-2.62.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.62.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-2.62.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.62.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY r + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.62.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary2-2.62.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.62.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY a + } +} {2 21 44 55 58 63 64} +do_test boundary2-2.62.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY a DESC + } +} {64 63 58 55 44 21 2} +do_test boundary2-2.62.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY r + } +} {55 2 64 21 44 58 63} +do_test boundary2-2.62.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY r DESC + } +} {63 58 44 21 64 2 55} +do_test boundary2-2.62.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY x + } +} {55 2 64 21 44 58 63} +do_test boundary2-2.62.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY a + } +} {2 21 44 47 55 58 63 64} +do_test boundary2-2.62.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 2} +do_test boundary2-2.62.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY r + } +} {55 2 64 21 44 58 63 47} +do_test boundary2-2.62.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY r DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary2-2.62.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY x + } +} {55 2 64 21 44 58 63 47} +do_test boundary2-2.63.1 { + db eval { + SELECT * FROM t1 WHERE r=-36028797018963969 + } +} {-36028797018963969 2 ff7fffffffffffff} +do_test boundary2-2.63.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ff7fffffffffffff' + } +} {-36028797018963969 2} +do_test boundary2-2.63.3 { + db eval { + SELECT r, x FROM t1 WHERE a=2 + } +} {-36028797018963969 ff7fffffffffffff} +do_test boundary2-2.63.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.63.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-2.63.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY r + } +} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.63.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64} +do_test boundary2-2.63.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.63.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.63.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-2.63.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY r + } +} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.63.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2} +do_test boundary2-2.63.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.63.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY a + } +} {55} +do_test boundary2-2.63.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY a DESC + } +} {55} +do_test boundary2-2.63.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY r + } +} {55} +do_test boundary2-2.63.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY r DESC + } +} {55} +do_test boundary2-2.63.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY x + } +} {55} +do_test boundary2-2.63.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY a + } +} {2 55} +do_test boundary2-2.63.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY a DESC + } +} {55 2} +do_test boundary2-2.63.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY r + } +} {55 2} +do_test boundary2-2.63.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY r DESC + } +} {2 55} +do_test boundary2-2.63.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY x + } +} {55 2} +do_test boundary2-2.64.1 { + db eval { + SELECT * FROM t1 WHERE r=3 + } +} {3 5 0000000000000003} +do_test boundary2-2.64.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000003' + } +} {3 5} +do_test boundary2-2.64.3 { + db eval { + SELECT r, x FROM t1 WHERE a=5 + } +} {3 0000000000000003} +do_test boundary2-2.64.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.64.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary2-2.64.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY r + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.64.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary2-2.64.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY x + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.64.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-2.64.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-2.64.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY r + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.64.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary2-2.64.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY x + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.64.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.64.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1} +do_test boundary2-2.64.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary2-2.64.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY r DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.64.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY x + } +} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.64.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY a + } +} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-2.64.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1} +do_test boundary2-2.64.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary2-2.64.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY r DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.64.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY x + } +} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.65.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary2-2.65.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary2-2.65.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY r + } +} {} +do_test boundary2-2.65.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY r DESC + } +} {} +do_test boundary2-2.65.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary2-2.65.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary2-2.65.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary2-2.65.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY r + } +} {} +do_test boundary2-2.65.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY r DESC + } +} {} +do_test boundary2-2.65.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary2-2.65.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.65.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-2.65.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.65.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.65.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.65.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.65.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-2.65.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.65.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.65.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.66.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.66.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-2.66.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.66.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.66.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.66.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-2.66.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-2.66.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-2.66.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-2.66.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-2.66.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary2-2.66.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary2-2.66.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY r + } +} {} +do_test boundary2-2.66.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY r DESC + } +} {} +do_test boundary2-2.66.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary2-2.66.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary2-2.66.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary2-2.66.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY r + } +} {} +do_test boundary2-2.66.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY r DESC + } +} {} +do_test boundary2-2.66.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary2-3.1 { + db eval { + DROP INDEX t1i1; + DROP INDEX t1i2; + DROP INDEX t1i3; + } +} {} +do_test boundary2-4.1.1 { + db eval { + SELECT * FROM t1 WHERE r=72057594037927935 + } +} {72057594037927935 17 00ffffffffffffff} +do_test boundary2-4.1.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00ffffffffffffff' + } +} {72057594037927935 17} +do_test boundary2-4.1.3 { + db eval { + SELECT r, x FROM t1 WHERE a=17 + } +} {72057594037927935 00ffffffffffffff} +do_test boundary2-4.1.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY a + } +} {3 28} +do_test boundary2-4.1.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY a DESC + } +} {28 3} +do_test boundary2-4.1.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY r + } +} {28 3} +do_test boundary2-4.1.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY r DESC + } +} {3 28} +do_test boundary2-4.1.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927935 ORDER BY x + } +} {28 3} +do_test boundary2-4.1.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY a + } +} {3 17 28} +do_test boundary2-4.1.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY a DESC + } +} {28 17 3} +do_test boundary2-4.1.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY r + } +} {17 28 3} +do_test boundary2-4.1.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY r DESC + } +} {3 28 17} +do_test boundary2-4.1.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927935 ORDER BY x + } +} {17 28 3} +do_test boundary2-4.1.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.1.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.1.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45} +do_test boundary2-4.1.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY r DESC + } +} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.1.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927935 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.1.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.1.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.1.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17} +do_test boundary2-4.1.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY r DESC + } +} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.1.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927935 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.2.1 { + db eval { + SELECT * FROM t1 WHERE r=16384 + } +} {16384 16 0000000000004000} +do_test boundary2-4.2.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000004000' + } +} {16384 16} +do_test boundary2-4.2.3 { + db eval { + SELECT r, x FROM t1 WHERE a=16 + } +} {16384 0000000000004000} +do_test boundary2-4.2.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-4.2.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.2.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY r + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.2.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary2-4.2.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 16384 ORDER BY x + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.2.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-4.2.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.2.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY r + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.2.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary2-4.2.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 16384 ORDER BY x + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.2.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY a + } +} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.2.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1} +do_test boundary2-4.2.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary2-4.2.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY r DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.2.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 16384 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.2.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY a + } +} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.2.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1} +do_test boundary2-4.2.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary2-4.2.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY r DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.2.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 16384 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.3.1 { + db eval { + SELECT * FROM t1 WHERE r=4294967296 + } +} {4294967296 36 0000000100000000} +do_test boundary2-4.3.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000100000000' + } +} {4294967296 36} +do_test boundary2-4.3.3 { + db eval { + SELECT r, x FROM t1 WHERE a=36 + } +} {4294967296 0000000100000000} +do_test boundary2-4.3.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57} +do_test boundary2-4.3.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY a DESC + } +} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-4.3.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY r + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.3.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary2-4.3.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4294967296 ORDER BY x + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.3.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary2-4.3.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-4.3.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY r + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.3.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary2-4.3.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967296 ORDER BY x + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.3.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.3.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.3.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary2-4.3.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY r DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.3.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4294967296 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.3.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.3.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.3.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary2-4.3.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY r DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.3.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967296 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.4.1 { + db eval { + SELECT * FROM t1 WHERE r=16777216 + } +} {16777216 6 0000000001000000} +do_test boundary2-4.4.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000001000000' + } +} {16777216 6} +do_test boundary2-4.4.3 { + db eval { + SELECT r, x FROM t1 WHERE a=6 + } +} {16777216 0000000001000000} +do_test boundary2-4.4.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY a + } +} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.4.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3} +do_test boundary2-4.4.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY r + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.4.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary2-4.4.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 16777216 ORDER BY x + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.4.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY a + } +} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.4.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3} +do_test boundary2-4.4.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY r + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.4.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary2-4.4.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 16777216 ORDER BY x + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.4.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY a + } +} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.4.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1} +do_test boundary2-4.4.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary2-4.4.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY r DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.4.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 16777216 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.4.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY a + } +} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.4.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1} +do_test boundary2-4.4.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary2-4.4.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY r DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.4.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 16777216 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.5.1 { + db eval { + SELECT * FROM t1 WHERE r=-32769 + } +} {-32769 29 ffffffffffff7fff} +do_test boundary2-4.5.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffff7fff' + } +} {-32769 29} +do_test boundary2-4.5.3 { + db eval { + SELECT r, x FROM t1 WHERE a=29 + } +} {-32769 ffffffffffff7fff} +do_test boundary2-4.5.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.5.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.5.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY r + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.5.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary2-4.5.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -32769 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38} +do_test boundary2-4.5.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.5.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.5.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY r + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.5.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary2-4.5.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -32769 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38} +do_test boundary2-4.5.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY a + } +} {1 2 11 21 37 44 47 55 58 63 64} +do_test boundary2-4.5.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 21 11 2 1} +do_test boundary2-4.5.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary2-4.5.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY r DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.5.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -32769 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary2-4.5.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY a + } +} {1 2 11 21 29 37 44 47 55 58 63 64} +do_test boundary2-4.5.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 29 21 11 2 1} +do_test boundary2-4.5.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary2-4.5.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY r DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.5.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -32769 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary2-4.6.1 { + db eval { + SELECT * FROM t1 WHERE r=-140737488355329 + } +} {-140737488355329 21 ffff7fffffffffff} +do_test boundary2-4.6.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffff7fffffffffff' + } +} {-140737488355329 21} +do_test boundary2-4.6.3 { + db eval { + SELECT r, x FROM t1 WHERE a=21 + } +} {-140737488355329 ffff7fffffffffff} +do_test boundary2-4.6.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-4.6.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.6.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY r + } +} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.6.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44} +do_test boundary2-4.6.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355329 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.6.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-4.6.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.6.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY r + } +} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.6.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21} +do_test boundary2-4.6.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355329 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.6.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY a + } +} {2 55 64} +do_test boundary2-4.6.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY a DESC + } +} {64 55 2} +do_test boundary2-4.6.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY r + } +} {55 2 64} +do_test boundary2-4.6.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY r DESC + } +} {64 2 55} +do_test boundary2-4.6.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355329 ORDER BY x + } +} {55 2 64} +do_test boundary2-4.6.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY a + } +} {2 21 55 64} +do_test boundary2-4.6.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY a DESC + } +} {64 55 21 2} +do_test boundary2-4.6.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY r + } +} {55 2 64 21} +do_test boundary2-4.6.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY r DESC + } +} {21 64 2 55} +do_test boundary2-4.6.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355329 ORDER BY x + } +} {55 2 64 21} +do_test boundary2-4.7.1 { + db eval { + SELECT * FROM t1 WHERE r=2 + } +} {2 41 0000000000000002} +do_test boundary2-4.7.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000002' + } +} {2 41} +do_test boundary2-4.7.3 { + db eval { + SELECT r, x FROM t1 WHERE a=41 + } +} {2 0000000000000002} +do_test boundary2-4.7.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.7.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.7.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY r + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.7.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary2-4.7.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2 ORDER BY x + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.7.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.7.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.7.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY r + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.7.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary2-4.7.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2 ORDER BY x + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.7.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.7.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-4.7.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary2-4.7.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY r DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.7.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2 ORDER BY x + } +} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.7.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.7.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1} +do_test boundary2-4.7.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary2-4.7.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY r DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.7.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2 ORDER BY x + } +} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.8.1 { + db eval { + SELECT * FROM t1 WHERE r=4 + } +} {4 31 0000000000000004} +do_test boundary2-4.8.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000004' + } +} {4 31} +do_test boundary2-4.8.3 { + db eval { + SELECT r, x FROM t1 WHERE a=31 + } +} {4 0000000000000004} +do_test boundary2-4.8.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.8.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary2-4.8.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY r + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.8.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary2-4.8.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4 ORDER BY x + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.8.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.8.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary2-4.8.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY r + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.8.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary2-4.8.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4 ORDER BY x + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.8.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY a + } +} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.8.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1} +do_test boundary2-4.8.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary2-4.8.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY r DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.8.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4 ORDER BY x + } +} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.8.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY a + } +} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.8.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1} +do_test boundary2-4.8.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary2-4.8.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY r DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.8.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4 ORDER BY x + } +} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.9.1 { + db eval { + SELECT * FROM t1 WHERE r=562949953421311 + } +} {562949953421311 13 0001ffffffffffff} +do_test boundary2-4.9.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0001ffffffffffff' + } +} {562949953421311 13} +do_test boundary2-4.9.3 { + db eval { + SELECT r, x FROM t1 WHERE a=13 + } +} {562949953421311 0001ffffffffffff} +do_test boundary2-4.9.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY a + } +} {3 17 27 28 43 45} +do_test boundary2-4.9.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY a DESC + } +} {45 43 28 27 17 3} +do_test boundary2-4.9.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY r + } +} {43 27 45 17 28 3} +do_test boundary2-4.9.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY r DESC + } +} {3 28 17 45 27 43} +do_test boundary2-4.9.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421311 ORDER BY x + } +} {43 27 45 17 28 3} +do_test boundary2-4.9.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY a + } +} {3 13 17 27 28 43 45} +do_test boundary2-4.9.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY a DESC + } +} {45 43 28 27 17 13 3} +do_test boundary2-4.9.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY r + } +} {13 43 27 45 17 28 3} +do_test boundary2-4.9.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY r DESC + } +} {3 28 17 45 27 43 13} +do_test boundary2-4.9.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421311 ORDER BY x + } +} {13 43 27 45 17 28 3} +do_test boundary2-4.9.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.9.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.9.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26} +do_test boundary2-4.9.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY r DESC + } +} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.9.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421311 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.9.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.9.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.9.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13} +do_test boundary2-4.9.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY r DESC + } +} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.9.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421311 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.10.1 { + db eval { + SELECT * FROM t1 WHERE r=256 + } +} {256 61 0000000000000100} +do_test boundary2-4.10.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000100' + } +} {256 61} +do_test boundary2-4.10.3 { + db eval { + SELECT r, x FROM t1 WHERE a=61 + } +} {256 0000000000000100} +do_test boundary2-4.10.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-4.10.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-4.10.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY r + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.10.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary2-4.10.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 256 ORDER BY x + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.10.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary2-4.10.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-4.10.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY r + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.10.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary2-4.10.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 256 ORDER BY x + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.10.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.10.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary2-4.10.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary2-4.10.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY r DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.10.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 256 ORDER BY x + } +} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.10.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.10.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary2-4.10.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary2-4.10.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY r DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.10.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 256 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.11.1 { + db eval { + SELECT * FROM t1 WHERE r=34359738368 + } +} {34359738368 22 0000000800000000} +do_test boundary2-4.11.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000800000000' + } +} {34359738368 22} +do_test boundary2-4.11.3 { + db eval { + SELECT r, x FROM t1 WHERE a=22 + } +} {34359738368 0000000800000000} +do_test boundary2-4.11.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary2-4.11.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-4.11.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY r + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.11.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary2-4.11.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 34359738368 ORDER BY x + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.11.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary2-4.11.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-4.11.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY r + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.11.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary2-4.11.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738368 ORDER BY x + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.11.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.11.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.11.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary2-4.11.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY r DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.11.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 34359738368 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.11.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.11.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.11.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary2-4.11.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY r DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.11.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738368 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.12.1 { + db eval { + SELECT * FROM t1 WHERE r=65536 + } +} {65536 62 0000000000010000} +do_test boundary2-4.12.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000010000' + } +} {65536 62} +do_test boundary2-4.12.3 { + db eval { + SELECT r, x FROM t1 WHERE a=62 + } +} {65536 0000000000010000} +do_test boundary2-4.12.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary2-4.12.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.12.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY r + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.12.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary2-4.12.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 65536 ORDER BY x + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.12.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62} +do_test boundary2-4.12.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY a DESC + } +} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.12.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY r + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.12.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary2-4.12.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 65536 ORDER BY x + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.12.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.12.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-4.12.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary2-4.12.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY r DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.12.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 65536 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.12.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.12.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-4.12.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary2-4.12.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY r DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.12.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 65536 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.13.1 { + db eval { + SELECT * FROM t1 WHERE r=268435456 + } +} {268435456 40 0000000010000000} +do_test boundary2-4.13.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000010000000' + } +} {268435456 40} +do_test boundary2-4.13.3 { + db eval { + SELECT r, x FROM t1 WHERE a=40 + } +} {268435456 0000000010000000} +do_test boundary2-4.13.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary2-4.13.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary2-4.13.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY r + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.13.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary2-4.13.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 268435456 ORDER BY x + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.13.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.13.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary2-4.13.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY r + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.13.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary2-4.13.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 268435456 ORDER BY x + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.13.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.13.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.13.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary2-4.13.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY r DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.13.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 268435456 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.13.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.13.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.13.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary2-4.13.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY r DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.13.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 268435456 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.14.1 { + db eval { + SELECT * FROM t1 WHERE r=-140737488355328 + } +} {-140737488355328 44 ffff800000000000} +do_test boundary2-4.14.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffff800000000000' + } +} {-140737488355328 44} +do_test boundary2-4.14.3 { + db eval { + SELECT r, x FROM t1 WHERE a=44 + } +} {-140737488355328 ffff800000000000} +do_test boundary2-4.14.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-4.14.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.14.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY r + } +} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.14.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58} +do_test boundary2-4.14.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.14.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-4.14.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.14.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY r + } +} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.14.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44} +do_test boundary2-4.14.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.14.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY a + } +} {2 21 55 64} +do_test boundary2-4.14.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY a DESC + } +} {64 55 21 2} +do_test boundary2-4.14.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY r + } +} {55 2 64 21} +do_test boundary2-4.14.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY r DESC + } +} {21 64 2 55} +do_test boundary2-4.14.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -140737488355328 ORDER BY x + } +} {55 2 64 21} +do_test boundary2-4.14.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY a + } +} {2 21 44 55 64} +do_test boundary2-4.14.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY a DESC + } +} {64 55 44 21 2} +do_test boundary2-4.14.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY r + } +} {55 2 64 21 44} +do_test boundary2-4.14.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY r DESC + } +} {44 21 64 2 55} +do_test boundary2-4.14.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -140737488355328 ORDER BY x + } +} {55 2 64 21 44} +do_test boundary2-4.15.1 { + db eval { + SELECT * FROM t1 WHERE r=1099511627776 + } +} {1099511627776 19 0000010000000000} +do_test boundary2-4.15.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000010000000000' + } +} {1099511627776 19} +do_test boundary2-4.15.3 { + db eval { + SELECT r, x FROM t1 WHERE a=19 + } +} {1099511627776 0000010000000000} +do_test boundary2-4.15.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY a + } +} {3 7 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary2-4.15.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 7 3} +do_test boundary2-4.15.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY r + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.15.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary2-4.15.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627776 ORDER BY x + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.15.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56} +do_test boundary2-4.15.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-4.15.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY r + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.15.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary2-4.15.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627776 ORDER BY x + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.15.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-4.15.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.15.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary2-4.15.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY r DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.15.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627776 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.15.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-4.15.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.15.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary2-4.15.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY r DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.15.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627776 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.16.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY a + } +} {} +do_test boundary2-4.16.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY a DESC + } +} {} +do_test boundary2-4.16.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY r + } +} {} +do_test boundary2-4.16.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY r DESC + } +} {} +do_test boundary2-4.16.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 9223372036854775807 ORDER BY x + } +} {} +do_test boundary2-4.16.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY a + } +} {3} +do_test boundary2-4.16.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY a DESC + } +} {3} +do_test boundary2-4.16.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY r + } +} {3} +do_test boundary2-4.16.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY r DESC + } +} {3} +do_test boundary2-4.16.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 9223372036854775807 ORDER BY x + } +} {3} +do_test boundary2-4.16.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.16.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.16.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28} +do_test boundary2-4.16.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY r DESC + } +} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.16.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 9223372036854775807 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.16.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.16.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-4.16.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.16.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.16.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 9223372036854775807 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.17.1 { + db eval { + SELECT * FROM t1 WHERE r=32768 + } +} {32768 50 0000000000008000} +do_test boundary2-4.17.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000008000' + } +} {32768 50} +do_test boundary2-4.17.3 { + db eval { + SELECT r, x FROM t1 WHERE a=50 + } +} {32768 0000000000008000} +do_test boundary2-4.17.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62} +do_test boundary2-4.17.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY a DESC + } +} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.17.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY r + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.17.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary2-4.17.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 32768 ORDER BY x + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.17.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-4.17.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.17.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY r + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.17.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary2-4.17.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 32768 ORDER BY x + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.17.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.17.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-4.17.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary2-4.17.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY r DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.17.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.17.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.17.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-4.17.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary2-4.17.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY r DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.17.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.18.1 { + db eval { + SELECT * FROM t1 WHERE r=-36028797018963968 + } +} {-36028797018963968 64 ff80000000000000} +do_test boundary2-4.18.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ff80000000000000' + } +} {-36028797018963968 64} +do_test boundary2-4.18.3 { + db eval { + SELECT r, x FROM t1 WHERE a=64 + } +} {-36028797018963968 ff80000000000000} +do_test boundary2-4.18.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-4.18.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.18.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY r + } +} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.18.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21} +do_test boundary2-4.18.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.18.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.18.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.18.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY r + } +} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.18.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64} +do_test boundary2-4.18.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.18.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY a + } +} {2 55} +do_test boundary2-4.18.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY a DESC + } +} {55 2} +do_test boundary2-4.18.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY r + } +} {55 2} +do_test boundary2-4.18.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY r DESC + } +} {2 55} +do_test boundary2-4.18.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963968 ORDER BY x + } +} {55 2} +do_test boundary2-4.18.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY a + } +} {2 55 64} +do_test boundary2-4.18.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY a DESC + } +} {64 55 2} +do_test boundary2-4.18.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY r + } +} {55 2 64} +do_test boundary2-4.18.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY r DESC + } +} {64 2 55} +do_test boundary2-4.18.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963968 ORDER BY x + } +} {55 2 64} +do_test boundary2-4.19.1 { + db eval { + SELECT * FROM t1 WHERE r=65535 + } +} {65535 48 000000000000ffff} +do_test boundary2-4.19.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000000000ffff' + } +} {65535 48} +do_test boundary2-4.19.3 { + db eval { + SELECT r, x FROM t1 WHERE a=48 + } +} {65535 000000000000ffff} +do_test boundary2-4.19.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62} +do_test boundary2-4.19.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY a DESC + } +} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.19.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY r + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.19.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary2-4.19.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 65535 ORDER BY x + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.19.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62} +do_test boundary2-4.19.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY a DESC + } +} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.19.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY r + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.19.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary2-4.19.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 65535 ORDER BY x + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.19.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.19.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-4.19.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary2-4.19.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY r DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.19.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 65535 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.19.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.19.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-4.19.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary2-4.19.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY r DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.19.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 65535 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.20.1 { + db eval { + SELECT * FROM t1 WHERE r=4294967295 + } +} {4294967295 14 00000000ffffffff} +do_test boundary2-4.20.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000000ffffffff' + } +} {4294967295 14} +do_test boundary2-4.20.3 { + db eval { + SELECT r, x FROM t1 WHERE a=14 + } +} {4294967295 00000000ffffffff} +do_test boundary2-4.20.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary2-4.20.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-4.20.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY r + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.20.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary2-4.20.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4294967295 ORDER BY x + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.20.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary2-4.20.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary2-4.20.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY r + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.20.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary2-4.20.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4294967295 ORDER BY x + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.20.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.20.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.20.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary2-4.20.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY r DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.20.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4294967295 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.20.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.20.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.20.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary2-4.20.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY r DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.20.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4294967295 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.21.1 { + db eval { + SELECT * FROM t1 WHERE r=1099511627775 + } +} {1099511627775 57 000000ffffffffff} +do_test boundary2-4.21.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000ffffffffff' + } +} {1099511627775 57} +do_test boundary2-4.21.3 { + db eval { + SELECT r, x FROM t1 WHERE a=57 + } +} {1099511627775 000000ffffffffff} +do_test boundary2-4.21.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56} +do_test boundary2-4.21.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-4.21.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY r + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.21.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary2-4.21.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 1099511627775 ORDER BY x + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.21.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57} +do_test boundary2-4.21.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY a DESC + } +} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-4.21.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY r + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.21.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary2-4.21.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 1099511627775 ORDER BY x + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.21.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.21.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.21.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary2-4.21.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY r DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.21.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 1099511627775 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.21.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-4.21.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.21.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary2-4.21.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY r DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.21.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 1099511627775 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.22.1 { + db eval { + SELECT * FROM t1 WHERE r=-8388608 + } +} {-8388608 37 ffffffffff800000} +do_test boundary2-4.22.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffff800000' + } +} {-8388608 37} +do_test boundary2-4.22.3 { + db eval { + SELECT r, x FROM t1 WHERE a=37 + } +} {-8388608 ffffffffff800000} +do_test boundary2-4.22.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.22.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.22.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY r + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.22.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary2-4.22.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38} +do_test boundary2-4.22.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.22.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.22.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY r + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.22.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary2-4.22.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38} +do_test boundary2-4.22.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY a + } +} {1 2 11 21 44 47 55 58 63 64} +do_test boundary2-4.22.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2 1} +do_test boundary2-4.22.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary2-4.22.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY r DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.22.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -8388608 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary2-4.22.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY a + } +} {1 2 11 21 37 44 47 55 58 63 64} +do_test boundary2-4.22.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 21 11 2 1} +do_test boundary2-4.22.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary2-4.22.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY r DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.22.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -8388608 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary2-4.23.1 { + db eval { + SELECT * FROM t1 WHERE r=549755813888 + } +} {549755813888 35 0000008000000000} +do_test boundary2-4.23.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000008000000000' + } +} {549755813888 35} +do_test boundary2-4.23.3 { + db eval { + SELECT r, x FROM t1 WHERE a=35 + } +} {549755813888 0000008000000000} +do_test boundary2-4.23.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57} +do_test boundary2-4.23.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY a DESC + } +} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-4.23.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY r + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.23.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary2-4.23.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 549755813888 ORDER BY x + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.23.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57} +do_test boundary2-4.23.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY a DESC + } +} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-4.23.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY r + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.23.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary2-4.23.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813888 ORDER BY x + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.23.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.23.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.23.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary2-4.23.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY r DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.23.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.23.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.23.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.23.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary2-4.23.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY r DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.23.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.24.1 { + db eval { + SELECT * FROM t1 WHERE r=8388607 + } +} {8388607 18 00000000007fffff} +do_test boundary2-4.24.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000000007fffff' + } +} {8388607 18} +do_test boundary2-4.24.3 { + db eval { + SELECT r, x FROM t1 WHERE a=18 + } +} {8388607 00000000007fffff} +do_test boundary2-4.24.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.24.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary2-4.24.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY r + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.24.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary2-4.24.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 8388607 ORDER BY x + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.24.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.24.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary2-4.24.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY r + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.24.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary2-4.24.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 8388607 ORDER BY x + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.24.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.24.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary2-4.24.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary2-4.24.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY r DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.24.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 8388607 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.24.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.24.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary2-4.24.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary2-4.24.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY r DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.24.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 8388607 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.25.1 { + db eval { + SELECT * FROM t1 WHERE r=-3 + } +} {-3 52 fffffffffffffffd} +do_test boundary2-4.25.2 { + db eval { + SELECT r, a FROM t1 WHERE x='fffffffffffffffd' + } +} {-3 52} +do_test boundary2-4.25.3 { + db eval { + SELECT r, x FROM t1 WHERE a=52 + } +} {-3 fffffffffffffffd} +do_test boundary2-4.25.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-4.25.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.25.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY r + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.25.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary2-4.25.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -3 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38} +do_test boundary2-4.25.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62} +do_test boundary2-4.25.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY a DESC + } +} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.25.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY r + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.25.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary2-4.25.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -3 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38} +do_test boundary2-4.25.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64} +do_test boundary2-4.25.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY a DESC + } +} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1} +do_test boundary2-4.25.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary2-4.25.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY r DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.25.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -3 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary2-4.25.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64} +do_test boundary2-4.25.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1} +do_test boundary2-4.25.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary2-4.25.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY r DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.25.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -3 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary2-4.26.1 { + db eval { + SELECT * FROM t1 WHERE r=0 + } +} {0 59 0000000000000000} +do_test boundary2-4.26.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000000' + } +} {0 59} +do_test boundary2-4.26.3 { + db eval { + SELECT r, x FROM t1 WHERE a=59 + } +} {0 0000000000000000} +do_test boundary2-4.26.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62} +do_test boundary2-4.26.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY a DESC + } +} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.26.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY r + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.26.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary2-4.26.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 0 ORDER BY x + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.26.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-4.26.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.26.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY r + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.26.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary2-4.26.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 0 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.26.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64} +do_test boundary2-4.26.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-4.26.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.26.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY r DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.26.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 0 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.26.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64} +do_test boundary2-4.26.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY a DESC + } +} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-4.26.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary2-4.26.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY r DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.26.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 0 ORDER BY x + } +} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.27.1 { + db eval { + SELECT * FROM t1 WHERE r=-1 + } +} {-1 38 ffffffffffffffff} +do_test boundary2-4.27.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffffffff' + } +} {-1 38} +do_test boundary2-4.27.3 { + db eval { + SELECT r, x FROM t1 WHERE a=38 + } +} {-1 ffffffffffffffff} +do_test boundary2-4.27.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-4.27.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.27.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY r + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.27.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary2-4.27.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -1 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.27.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-4.27.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.27.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY r + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.27.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary2-4.27.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -1 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38} +do_test boundary2-4.27.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64} +do_test boundary2-4.27.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1} +do_test boundary2-4.27.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary2-4.27.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY r DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.27.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -1 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary2-4.27.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64} +do_test boundary2-4.27.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-4.27.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.27.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY r DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.27.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -1 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.28.1 { + db eval { + SELECT * FROM t1 WHERE r=-2 + } +} {-2 33 fffffffffffffffe} +do_test boundary2-4.28.2 { + db eval { + SELECT r, a FROM t1 WHERE x='fffffffffffffffe' + } +} {-2 33} +do_test boundary2-4.28.3 { + db eval { + SELECT r, x FROM t1 WHERE a=33 + } +} {-2 fffffffffffffffe} +do_test boundary2-4.28.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-4.28.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.28.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY r + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.28.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary2-4.28.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -2 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38} +do_test boundary2-4.28.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary2-4.28.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.28.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY r + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.28.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary2-4.28.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -2 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38} +do_test boundary2-4.28.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64} +do_test boundary2-4.28.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1} +do_test boundary2-4.28.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary2-4.28.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY r DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.28.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -2 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary2-4.28.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY a + } +} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64} +do_test boundary2-4.28.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY a DESC + } +} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1} +do_test boundary2-4.28.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary2-4.28.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY r DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.28.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -2 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary2-4.29.1 { + db eval { + SELECT * FROM t1 WHERE r=2097152 + } +} {2097152 42 0000000000200000} +do_test boundary2-4.29.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000200000' + } +} {2097152 42} +do_test boundary2-4.29.3 { + db eval { + SELECT r, x FROM t1 WHERE a=42 + } +} {2097152 0000000000200000} +do_test boundary2-4.29.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.29.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary2-4.29.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY r + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.29.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary2-4.29.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2097152 ORDER BY x + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.29.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary2-4.29.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary2-4.29.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY r + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.29.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary2-4.29.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2097152 ORDER BY x + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.29.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.29.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary2-4.29.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary2-4.29.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY r DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.29.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2097152 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.29.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.29.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary2-4.29.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary2-4.29.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY r DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.29.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2097152 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.30.1 { + db eval { + SELECT * FROM t1 WHERE r=128 + } +} {128 49 0000000000000080} +do_test boundary2-4.30.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000080' + } +} {128 49} +do_test boundary2-4.30.3 { + db eval { + SELECT r, x FROM t1 WHERE a=49 + } +} {128 0000000000000080} +do_test boundary2-4.30.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary2-4.30.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-4.30.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY r + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.30.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary2-4.30.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 128 ORDER BY x + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.30.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.30.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-4.30.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY r + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.30.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary2-4.30.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 128 ORDER BY x + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.30.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.30.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary2-4.30.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary2-4.30.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY r DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.30.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 128 ORDER BY x + } +} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.30.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.30.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary2-4.30.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary2-4.30.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY r DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.30.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 128 ORDER BY x + } +} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.31.1 { + db eval { + SELECT * FROM t1 WHERE r=255 + } +} {255 30 00000000000000ff} +do_test boundary2-4.31.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000000000000ff' + } +} {255 30} +do_test boundary2-4.31.3 { + db eval { + SELECT r, x FROM t1 WHERE a=30 + } +} {255 00000000000000ff} +do_test boundary2-4.31.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary2-4.31.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-4.31.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY r + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.31.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary2-4.31.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 255 ORDER BY x + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.31.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary2-4.31.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-4.31.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY r + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.31.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary2-4.31.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 255 ORDER BY x + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.31.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.31.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary2-4.31.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary2-4.31.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY r DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.31.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 255 ORDER BY x + } +} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.31.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.31.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary2-4.31.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary2-4.31.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY r DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.31.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 255 ORDER BY x + } +} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.32.1 { + db eval { + SELECT * FROM t1 WHERE r=-2147483648 + } +} {-2147483648 11 ffffffff80000000} +do_test boundary2-4.32.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffff80000000' + } +} {-2147483648 11} +do_test boundary2-4.32.3 { + db eval { + SELECT r, x FROM t1 WHERE a=11 + } +} {-2147483648 ffffffff80000000} +do_test boundary2-4.32.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.32.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.32.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY r + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.32.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary2-4.32.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.32.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.32.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.32.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY r + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.32.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary2-4.32.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.32.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY a + } +} {2 21 44 47 55 58 63 64} +do_test boundary2-4.32.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 2} +do_test boundary2-4.32.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY r + } +} {55 2 64 21 44 58 63 47} +do_test boundary2-4.32.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY r DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary2-4.32.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -2147483648 ORDER BY x + } +} {55 2 64 21 44 58 63 47} +do_test boundary2-4.32.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY a + } +} {2 11 21 44 47 55 58 63 64} +do_test boundary2-4.32.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2} +do_test boundary2-4.32.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary2-4.32.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY r DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary2-4.32.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483648 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary2-4.33.1 { + db eval { + SELECT * FROM t1 WHERE r=34359738367 + } +} {34359738367 39 00000007ffffffff} +do_test boundary2-4.33.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000007ffffffff' + } +} {34359738367 39} +do_test boundary2-4.33.3 { + db eval { + SELECT r, x FROM t1 WHERE a=39 + } +} {34359738367 00000007ffffffff} +do_test boundary2-4.33.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary2-4.33.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-4.33.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY r + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.33.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary2-4.33.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 34359738367 ORDER BY x + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.33.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57} +do_test boundary2-4.33.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY a DESC + } +} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary2-4.33.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY r + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.33.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary2-4.33.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 34359738367 ORDER BY x + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.33.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.33.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.33.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary2-4.33.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY r DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.33.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 34359738367 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.33.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.33.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.33.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary2-4.33.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY r DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.33.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 34359738367 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.34.1 { + db eval { + SELECT * FROM t1 WHERE r=-549755813889 + } +} {-549755813889 58 ffffff7fffffffff} +do_test boundary2-4.34.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffff7fffffffff' + } +} {-549755813889 58} +do_test boundary2-4.34.3 { + db eval { + SELECT r, x FROM t1 WHERE a=58 + } +} {-549755813889 ffffff7fffffffff} +do_test boundary2-4.34.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63} +do_test boundary2-4.34.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY a DESC + } +} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.34.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY r + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.34.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary2-4.34.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -549755813889 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.34.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary2-4.34.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.34.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY r + } +} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.34.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58} +do_test boundary2-4.34.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813889 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.34.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY a + } +} {2 21 44 55 64} +do_test boundary2-4.34.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY a DESC + } +} {64 55 44 21 2} +do_test boundary2-4.34.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY r + } +} {55 2 64 21 44} +do_test boundary2-4.34.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY r DESC + } +} {44 21 64 2 55} +do_test boundary2-4.34.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -549755813889 ORDER BY x + } +} {55 2 64 21 44} +do_test boundary2-4.34.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY a + } +} {2 21 44 55 58 64} +do_test boundary2-4.34.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY a DESC + } +} {64 58 55 44 21 2} +do_test boundary2-4.34.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY r + } +} {55 2 64 21 44 58} +do_test boundary2-4.34.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY r DESC + } +} {58 44 21 64 2 55} +do_test boundary2-4.34.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813889 ORDER BY x + } +} {55 2 64 21 44 58} +do_test boundary2-4.35.1 { + db eval { + SELECT * FROM t1 WHERE r=-32768 + } +} {-32768 32 ffffffffffff8000} +do_test boundary2-4.35.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffff8000' + } +} {-32768 32} +do_test boundary2-4.35.3 { + db eval { + SELECT r, x FROM t1 WHERE a=32 + } +} {-32768 ffffffffffff8000} +do_test boundary2-4.35.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.35.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.35.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY r + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.35.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary2-4.35.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38} +do_test boundary2-4.35.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.35.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.35.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY r + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.35.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary2-4.35.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -32768 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38} +do_test boundary2-4.35.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY a + } +} {1 2 11 21 29 37 44 47 55 58 63 64} +do_test boundary2-4.35.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 29 21 11 2 1} +do_test boundary2-4.35.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary2-4.35.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY r DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.35.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -32768 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary2-4.35.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 55 58 63 64} +do_test boundary2-4.35.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 32 29 21 11 2 1} +do_test boundary2-4.35.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary2-4.35.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY r DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.35.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -32768 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary2-4.36.1 { + db eval { + SELECT * FROM t1 WHERE r=2147483647 + } +} {2147483647 20 000000007fffffff} +do_test boundary2-4.36.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000007fffffff' + } +} {2147483647 20} +do_test boundary2-4.36.3 { + db eval { + SELECT r, x FROM t1 WHERE a=20 + } +} {2147483647 000000007fffffff} +do_test boundary2-4.36.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary2-4.36.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary2-4.36.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY r + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.36.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary2-4.36.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2147483647 ORDER BY x + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.36.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary2-4.36.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary2-4.36.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY r + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.36.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary2-4.36.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483647 ORDER BY x + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.36.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.36.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.36.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary2-4.36.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY r DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.36.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2147483647 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.36.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.36.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.36.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary2-4.36.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY r DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.36.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483647 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.37.1 { + db eval { + SELECT * FROM t1 WHERE r=-129 + } +} {-129 54 ffffffffffffff7f} +do_test boundary2-4.37.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffffff7f' + } +} {-129 54} +do_test boundary2-4.37.3 { + db eval { + SELECT r, x FROM t1 WHERE a=54 + } +} {-129 ffffffffffffff7f} +do_test boundary2-4.37.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62} +do_test boundary2-4.37.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY a DESC + } +} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.37.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY r + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.37.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary2-4.37.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -129 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38} +do_test boundary2-4.37.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.37.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.37.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY r + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.37.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary2-4.37.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -129 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38} +do_test boundary2-4.37.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 55 58 63 64} +do_test boundary2-4.37.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY a DESC + } +} {64 63 58 55 47 44 37 32 29 21 11 2 1} +do_test boundary2-4.37.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary2-4.37.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY r DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.37.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -129 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary2-4.37.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 54 55 58 63 64} +do_test boundary2-4.37.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY a DESC + } +} {64 63 58 55 54 47 44 37 32 29 21 11 2 1} +do_test boundary2-4.37.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary2-4.37.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY r DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.37.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -129 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary2-4.38.1 { + db eval { + SELECT * FROM t1 WHERE r=-128 + } +} {-128 53 ffffffffffffff80} +do_test boundary2-4.38.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffffffff80' + } +} {-128 53} +do_test boundary2-4.38.3 { + db eval { + SELECT r, x FROM t1 WHERE a=53 + } +} {-128 ffffffffffffff80} +do_test boundary2-4.38.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62} +do_test boundary2-4.38.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY a DESC + } +} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.38.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY r + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.38.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary2-4.38.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -128 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38} +do_test boundary2-4.38.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62} +do_test boundary2-4.38.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY a DESC + } +} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.38.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY r + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.38.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary2-4.38.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -128 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38} +do_test boundary2-4.38.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 54 55 58 63 64} +do_test boundary2-4.38.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY a DESC + } +} {64 63 58 55 54 47 44 37 32 29 21 11 2 1} +do_test boundary2-4.38.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary2-4.38.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY r DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.38.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -128 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary2-4.38.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY a + } +} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64} +do_test boundary2-4.38.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY a DESC + } +} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1} +do_test boundary2-4.38.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary2-4.38.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY r DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.38.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -128 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary2-4.39.1 { + db eval { + SELECT * FROM t1 WHERE r=72057594037927936 + } +} {72057594037927936 28 0100000000000000} +do_test boundary2-4.39.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0100000000000000' + } +} {72057594037927936 28} +do_test boundary2-4.39.3 { + db eval { + SELECT r, x FROM t1 WHERE a=28 + } +} {72057594037927936 0100000000000000} +do_test boundary2-4.39.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY a + } +} {3} +do_test boundary2-4.39.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY a DESC + } +} {3} +do_test boundary2-4.39.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY r + } +} {3} +do_test boundary2-4.39.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY r DESC + } +} {3} +do_test boundary2-4.39.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 72057594037927936 ORDER BY x + } +} {3} +do_test boundary2-4.39.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY a + } +} {3 28} +do_test boundary2-4.39.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY a DESC + } +} {28 3} +do_test boundary2-4.39.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY r + } +} {28 3} +do_test boundary2-4.39.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY r DESC + } +} {3 28} +do_test boundary2-4.39.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 72057594037927936 ORDER BY x + } +} {28 3} +do_test boundary2-4.39.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.39.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.39.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17} +do_test boundary2-4.39.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY r DESC + } +} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.39.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 72057594037927936 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.39.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.39.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.39.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28} +do_test boundary2-4.39.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY r DESC + } +} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.39.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 72057594037927936 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.40.1 { + db eval { + SELECT * FROM t1 WHERE r=2147483648 + } +} {2147483648 51 0000000080000000} +do_test boundary2-4.40.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000080000000' + } +} {2147483648 51} +do_test boundary2-4.40.3 { + db eval { + SELECT r, x FROM t1 WHERE a=51 + } +} {2147483648 0000000080000000} +do_test boundary2-4.40.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary2-4.40.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary2-4.40.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY r + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.40.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary2-4.40.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2147483648 ORDER BY x + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.40.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary2-4.40.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary2-4.40.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY r + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.40.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary2-4.40.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2147483648 ORDER BY x + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.40.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.40.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.40.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary2-4.40.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY r DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.40.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.40.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.40.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.40.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary2-4.40.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY r DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.40.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2147483648 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.41.1 { + db eval { + SELECT * FROM t1 WHERE r=549755813887 + } +} {549755813887 46 0000007fffffffff} +do_test boundary2-4.41.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000007fffffffff' + } +} {549755813887 46} +do_test boundary2-4.41.3 { + db eval { + SELECT r, x FROM t1 WHERE a=46 + } +} {549755813887 0000007fffffffff} +do_test boundary2-4.41.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57} +do_test boundary2-4.41.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY a DESC + } +} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-4.41.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY r + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.41.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary2-4.41.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 549755813887 ORDER BY x + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.41.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary2-4.41.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary2-4.41.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY r + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.41.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary2-4.41.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 549755813887 ORDER BY x + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.41.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.41.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.41.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary2-4.41.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY r DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.41.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 549755813887 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.41.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.41.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.41.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary2-4.41.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY r DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.41.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 549755813887 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.42.1 { + db eval { + SELECT * FROM t1 WHERE r=-549755813888 + } +} {-549755813888 63 ffffff8000000000} +do_test boundary2-4.42.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffff8000000000' + } +} {-549755813888 63} +do_test boundary2-4.42.3 { + db eval { + SELECT r, x FROM t1 WHERE a=63 + } +} {-549755813888 ffffff8000000000} +do_test boundary2-4.42.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.42.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.42.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY r + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.42.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary2-4.42.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.42.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63} +do_test boundary2-4.42.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY a DESC + } +} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.42.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY r + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.42.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary2-4.42.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -549755813888 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.42.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY a + } +} {2 21 44 55 58 64} +do_test boundary2-4.42.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY a DESC + } +} {64 58 55 44 21 2} +do_test boundary2-4.42.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY r + } +} {55 2 64 21 44 58} +do_test boundary2-4.42.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY r DESC + } +} {58 44 21 64 2 55} +do_test boundary2-4.42.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -549755813888 ORDER BY x + } +} {55 2 64 21 44 58} +do_test boundary2-4.42.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY a + } +} {2 21 44 55 58 63 64} +do_test boundary2-4.42.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY a DESC + } +} {64 63 58 55 44 21 2} +do_test boundary2-4.42.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY r + } +} {55 2 64 21 44 58 63} +do_test boundary2-4.42.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY r DESC + } +} {63 58 44 21 64 2 55} +do_test boundary2-4.42.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -549755813888 ORDER BY x + } +} {55 2 64 21 44 58 63} +do_test boundary2-4.43.1 { + db eval { + SELECT * FROM t1 WHERE r=281474976710655 + } +} {281474976710655 10 0000ffffffffffff} +do_test boundary2-4.43.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000ffffffffffff' + } +} {281474976710655 10} +do_test boundary2-4.43.3 { + db eval { + SELECT r, x FROM t1 WHERE a=10 + } +} {281474976710655 0000ffffffffffff} +do_test boundary2-4.43.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY a + } +} {3 13 17 26 27 28 43 45} +do_test boundary2-4.43.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 3} +do_test boundary2-4.43.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY r + } +} {26 13 43 27 45 17 28 3} +do_test boundary2-4.43.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26} +do_test boundary2-4.43.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710655 ORDER BY x + } +} {26 13 43 27 45 17 28 3} +do_test boundary2-4.43.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY a + } +} {3 10 13 17 26 27 28 43 45} +do_test boundary2-4.43.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 10 3} +do_test boundary2-4.43.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY r + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary2-4.43.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10} +do_test boundary2-4.43.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710655 ORDER BY x + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary2-4.43.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.43.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-4.43.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34} +do_test boundary2-4.43.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY r DESC + } +} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.43.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710655 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.43.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.43.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.43.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10} +do_test boundary2-4.43.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY r DESC + } +} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.43.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710655 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.44.1 { + db eval { + SELECT * FROM t1 WHERE r=4398046511103 + } +} {4398046511103 7 000003ffffffffff} +do_test boundary2-4.44.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000003ffffffffff' + } +} {4398046511103 7} +do_test boundary2-4.44.3 { + db eval { + SELECT r, x FROM t1 WHERE a=7 + } +} {4398046511103 000003ffffffffff} +do_test boundary2-4.44.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary2-4.44.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 3} +do_test boundary2-4.44.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY r + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.44.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary2-4.44.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511103 ORDER BY x + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.44.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY a + } +} {3 7 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary2-4.44.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 7 3} +do_test boundary2-4.44.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY r + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.44.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary2-4.44.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511103 ORDER BY x + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.44.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-4.44.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.44.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary2-4.44.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY r DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.44.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511103 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.44.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-4.44.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-4.44.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary2-4.44.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY r DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.44.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511103 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.45.1 { + db eval { + SELECT * FROM t1 WHERE r=268435455 + } +} {268435455 12 000000000fffffff} +do_test boundary2-4.45.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000000fffffff' + } +} {268435455 12} +do_test boundary2-4.45.3 { + db eval { + SELECT r, x FROM t1 WHERE a=12 + } +} {268435455 000000000fffffff} +do_test boundary2-4.45.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.45.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary2-4.45.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY r + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.45.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary2-4.45.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 268435455 ORDER BY x + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.45.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY a + } +} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.45.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3} +do_test boundary2-4.45.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY r + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.45.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary2-4.45.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 268435455 ORDER BY x + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.45.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY a + } +} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.45.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1} +do_test boundary2-4.45.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary2-4.45.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY r DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.45.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 268435455 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.45.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.45.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary2-4.45.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary2-4.45.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY r DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.45.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 268435455 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.46.1 { + db eval { + SELECT * FROM t1 WHERE r=-9223372036854775808 + } +} {-9223372036854775808 55 8000000000000000} +do_test boundary2-4.46.2 { + db eval { + SELECT r, a FROM t1 WHERE x='8000000000000000' + } +} {-9223372036854775808 55} +do_test boundary2-4.46.3 { + db eval { + SELECT r, x FROM t1 WHERE a=55 + } +} {-9223372036854775808 8000000000000000} +do_test boundary2-4.46.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.46.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-4.46.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY r + } +} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.46.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2} +do_test boundary2-4.46.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -9223372036854775808 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.46.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.46.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-4.46.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.46.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.46.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -9223372036854775808 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.46.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY a + } +} {} +do_test boundary2-4.46.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY a DESC + } +} {} +do_test boundary2-4.46.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY r + } +} {} +do_test boundary2-4.46.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY r DESC + } +} {} +do_test boundary2-4.46.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -9223372036854775808 ORDER BY x + } +} {} +do_test boundary2-4.46.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY a + } +} {55} +do_test boundary2-4.46.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY a DESC + } +} {55} +do_test boundary2-4.46.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY r + } +} {55} +do_test boundary2-4.46.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY r DESC + } +} {55} +do_test boundary2-4.46.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -9223372036854775808 ORDER BY x + } +} {55} +do_test boundary2-4.47.1 { + db eval { + SELECT * FROM t1 WHERE r=562949953421312 + } +} {562949953421312 43 0002000000000000} +do_test boundary2-4.47.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0002000000000000' + } +} {562949953421312 43} +do_test boundary2-4.47.3 { + db eval { + SELECT r, x FROM t1 WHERE a=43 + } +} {562949953421312 0002000000000000} +do_test boundary2-4.47.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY a + } +} {3 17 27 28 45} +do_test boundary2-4.47.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY a DESC + } +} {45 28 27 17 3} +do_test boundary2-4.47.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY r + } +} {27 45 17 28 3} +do_test boundary2-4.47.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY r DESC + } +} {3 28 17 45 27} +do_test boundary2-4.47.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 562949953421312 ORDER BY x + } +} {27 45 17 28 3} +do_test boundary2-4.47.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY a + } +} {3 17 27 28 43 45} +do_test boundary2-4.47.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY a DESC + } +} {45 43 28 27 17 3} +do_test boundary2-4.47.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY r + } +} {43 27 45 17 28 3} +do_test boundary2-4.47.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY r DESC + } +} {3 28 17 45 27 43} +do_test boundary2-4.47.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 562949953421312 ORDER BY x + } +} {43 27 45 17 28 3} +do_test boundary2-4.47.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.47.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.47.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13} +do_test boundary2-4.47.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY r DESC + } +} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.47.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 562949953421312 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.47.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.47.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.47.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43} +do_test boundary2-4.47.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY r DESC + } +} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.47.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 562949953421312 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.48.1 { + db eval { + SELECT * FROM t1 WHERE r=-8388609 + } +} {-8388609 1 ffffffffff7fffff} +do_test boundary2-4.48.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffffff7fffff' + } +} {-8388609 1} +do_test boundary2-4.48.3 { + db eval { + SELECT r, x FROM t1 WHERE a=1 + } +} {-8388609 ffffffffff7fffff} +do_test boundary2-4.48.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.48.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.48.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY r + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.48.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary2-4.48.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -8388609 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38} +do_test boundary2-4.48.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.48.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.48.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY r + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.48.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary2-4.48.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -8388609 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.48.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY a + } +} {2 11 21 44 47 55 58 63 64} +do_test boundary2-4.48.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2} +do_test boundary2-4.48.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary2-4.48.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY r DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary2-4.48.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -8388609 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary2-4.48.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY a + } +} {1 2 11 21 44 47 55 58 63 64} +do_test boundary2-4.48.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 11 2 1} +do_test boundary2-4.48.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary2-4.48.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY r DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.48.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -8388609 ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary2-4.49.1 { + db eval { + SELECT * FROM t1 WHERE r=16777215 + } +} {16777215 9 0000000000ffffff} +do_test boundary2-4.49.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000ffffff' + } +} {16777215 9} +do_test boundary2-4.49.3 { + db eval { + SELECT r, x FROM t1 WHERE a=9 + } +} {16777215 0000000000ffffff} +do_test boundary2-4.49.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY a + } +} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.49.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3} +do_test boundary2-4.49.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY r + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.49.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary2-4.49.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 16777215 ORDER BY x + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.49.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.49.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary2-4.49.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY r + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.49.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary2-4.49.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 16777215 ORDER BY x + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.49.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.49.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary2-4.49.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary2-4.49.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY r DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.49.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 16777215 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.49.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY a + } +} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.49.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1} +do_test boundary2-4.49.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary2-4.49.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY r DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.49.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 16777215 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.50.1 { + db eval { + SELECT * FROM t1 WHERE r=8388608 + } +} {8388608 24 0000000000800000} +do_test boundary2-4.50.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000800000' + } +} {8388608 24} +do_test boundary2-4.50.3 { + db eval { + SELECT r, x FROM t1 WHERE a=24 + } +} {8388608 0000000000800000} +do_test boundary2-4.50.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.50.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary2-4.50.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY r + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.50.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary2-4.50.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 8388608 ORDER BY x + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.50.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary2-4.50.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary2-4.50.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY r + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.50.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary2-4.50.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 8388608 ORDER BY x + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.50.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.50.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary2-4.50.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary2-4.50.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY r DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.50.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.50.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY a + } +} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.50.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary2-4.50.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary2-4.50.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY r DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.50.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 8388608 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.51.1 { + db eval { + SELECT * FROM t1 WHERE r=16383 + } +} {16383 8 0000000000003fff} +do_test boundary2-4.51.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000003fff' + } +} {16383 8} +do_test boundary2-4.51.3 { + db eval { + SELECT r, x FROM t1 WHERE a=8 + } +} {16383 0000000000003fff} +do_test boundary2-4.51.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-4.51.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.51.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY r + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.51.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary2-4.51.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 16383 ORDER BY x + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.51.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-4.51.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-4.51.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY r + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.51.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary2-4.51.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 16383 ORDER BY x + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.51.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.51.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary2-4.51.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary2-4.51.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY r DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.51.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 16383 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.51.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY a + } +} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.51.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1} +do_test boundary2-4.51.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary2-4.51.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY r DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.51.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 16383 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.52.1 { + db eval { + SELECT * FROM t1 WHERE r=140737488355328 + } +} {140737488355328 34 0000800000000000} +do_test boundary2-4.52.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000800000000000' + } +} {140737488355328 34} +do_test boundary2-4.52.3 { + db eval { + SELECT r, x FROM t1 WHERE a=34 + } +} {140737488355328 0000800000000000} +do_test boundary2-4.52.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY a + } +} {3 10 13 17 26 27 28 43 45} +do_test boundary2-4.52.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 10 3} +do_test boundary2-4.52.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY r + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary2-4.52.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10} +do_test boundary2-4.52.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355328 ORDER BY x + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary2-4.52.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY a + } +} {3 10 13 17 26 27 28 34 43 45} +do_test boundary2-4.52.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY a DESC + } +} {45 43 34 28 27 26 17 13 10 3} +do_test boundary2-4.52.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY r + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.52.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34} +do_test boundary2-4.52.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355328 ORDER BY x + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.52.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.52.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-4.52.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25} +do_test boundary2-4.52.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY r DESC + } +} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.52.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.52.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.52.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-4.52.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34} +do_test boundary2-4.52.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY r DESC + } +} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.52.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355328 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.53.1 { + db eval { + SELECT * FROM t1 WHERE r=2097151 + } +} {2097151 15 00000000001fffff} +do_test boundary2-4.53.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00000000001fffff' + } +} {2097151 15} +do_test boundary2-4.53.3 { + db eval { + SELECT r, x FROM t1 WHERE a=15 + } +} {2097151 00000000001fffff} +do_test boundary2-4.53.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary2-4.53.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary2-4.53.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY r + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.53.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary2-4.53.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 2097151 ORDER BY x + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.53.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary2-4.53.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.53.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY r + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.53.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary2-4.53.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 2097151 ORDER BY x + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.53.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.53.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-4.53.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary2-4.53.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY r DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.53.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 2097151 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.53.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary2-4.53.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary2-4.53.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary2-4.53.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY r DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.53.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 2097151 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.54.1 { + db eval { + SELECT * FROM t1 WHERE r=140737488355327 + } +} {140737488355327 25 00007fffffffffff} +do_test boundary2-4.54.2 { + db eval { + SELECT r, a FROM t1 WHERE x='00007fffffffffff' + } +} {140737488355327 25} +do_test boundary2-4.54.3 { + db eval { + SELECT r, x FROM t1 WHERE a=25 + } +} {140737488355327 00007fffffffffff} +do_test boundary2-4.54.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY a + } +} {3 10 13 17 26 27 28 34 43 45} +do_test boundary2-4.54.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY a DESC + } +} {45 43 34 28 27 26 17 13 10 3} +do_test boundary2-4.54.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY r + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.54.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34} +do_test boundary2-4.54.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 140737488355327 ORDER BY x + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.54.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45} +do_test boundary2-4.54.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY a DESC + } +} {45 43 34 28 27 26 25 17 13 10 3} +do_test boundary2-4.54.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY r + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.54.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25} +do_test boundary2-4.54.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 140737488355327 ORDER BY x + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.54.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.54.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-4.54.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56} +do_test boundary2-4.54.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY r DESC + } +} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.54.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 140737488355327 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.54.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.54.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-4.54.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25} +do_test boundary2-4.54.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY r DESC + } +} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.54.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 140737488355327 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.55.1 { + db eval { + SELECT * FROM t1 WHERE r=281474976710656 + } +} {281474976710656 26 0001000000000000} +do_test boundary2-4.55.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0001000000000000' + } +} {281474976710656 26} +do_test boundary2-4.55.3 { + db eval { + SELECT r, x FROM t1 WHERE a=26 + } +} {281474976710656 0001000000000000} +do_test boundary2-4.55.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY a + } +} {3 13 17 27 28 43 45} +do_test boundary2-4.55.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY a DESC + } +} {45 43 28 27 17 13 3} +do_test boundary2-4.55.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY r + } +} {13 43 27 45 17 28 3} +do_test boundary2-4.55.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY r DESC + } +} {3 28 17 45 27 43 13} +do_test boundary2-4.55.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 281474976710656 ORDER BY x + } +} {13 43 27 45 17 28 3} +do_test boundary2-4.55.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY a + } +} {3 13 17 26 27 28 43 45} +do_test boundary2-4.55.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY a DESC + } +} {45 43 28 27 26 17 13 3} +do_test boundary2-4.55.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY r + } +} {26 13 43 27 45 17 28 3} +do_test boundary2-4.55.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26} +do_test boundary2-4.55.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 281474976710656 ORDER BY x + } +} {26 13 43 27 45 17 28 3} +do_test boundary2-4.55.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.55.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.55.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10} +do_test boundary2-4.55.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY r DESC + } +} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.55.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 281474976710656 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.55.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.55.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.55.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26} +do_test boundary2-4.55.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY r DESC + } +} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.55.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 281474976710656 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.56.1 { + db eval { + SELECT * FROM t1 WHERE r=32767 + } +} {32767 23 0000000000007fff} +do_test boundary2-4.56.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000007fff' + } +} {32767 23} +do_test boundary2-4.56.3 { + db eval { + SELECT r, x FROM t1 WHERE a=23 + } +} {32767 0000000000007fff} +do_test boundary2-4.56.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-4.56.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.56.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY r + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.56.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary2-4.56.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 32767 ORDER BY x + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.56.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary2-4.56.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary2-4.56.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY r + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.56.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary2-4.56.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 32767 ORDER BY x + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.56.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY a + } +} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.56.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1} +do_test boundary2-4.56.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary2-4.56.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY r DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.56.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 32767 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.56.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary2-4.56.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary2-4.56.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary2-4.56.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY r DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.56.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 32767 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.57.1 { + db eval { + SELECT * FROM t1 WHERE r=127 + } +} {127 4 000000000000007f} +do_test boundary2-4.57.2 { + db eval { + SELECT r, a FROM t1 WHERE x='000000000000007f' + } +} {127 4} +do_test boundary2-4.57.3 { + db eval { + SELECT r, x FROM t1 WHERE a=4 + } +} {127 000000000000007f} +do_test boundary2-4.57.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.57.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary2-4.57.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY r + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.57.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary2-4.57.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 127 ORDER BY x + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.57.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.57.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary2-4.57.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY r + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.57.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary2-4.57.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 127 ORDER BY x + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.57.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY a + } +} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.57.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1} +do_test boundary2-4.57.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary2-4.57.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY r DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.57.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 127 ORDER BY x + } +} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.57.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.57.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary2-4.57.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary2-4.57.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY r DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.57.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 127 ORDER BY x + } +} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.58.1 { + db eval { + SELECT * FROM t1 WHERE r=36028797018963967 + } +} {36028797018963967 27 007fffffffffffff} +do_test boundary2-4.58.2 { + db eval { + SELECT r, a FROM t1 WHERE x='007fffffffffffff' + } +} {36028797018963967 27} +do_test boundary2-4.58.3 { + db eval { + SELECT r, x FROM t1 WHERE a=27 + } +} {36028797018963967 007fffffffffffff} +do_test boundary2-4.58.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY a + } +} {3 17 28 45} +do_test boundary2-4.58.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY a DESC + } +} {45 28 17 3} +do_test boundary2-4.58.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY r + } +} {45 17 28 3} +do_test boundary2-4.58.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY r DESC + } +} {3 28 17 45} +do_test boundary2-4.58.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963967 ORDER BY x + } +} {45 17 28 3} +do_test boundary2-4.58.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY a + } +} {3 17 27 28 45} +do_test boundary2-4.58.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY a DESC + } +} {45 28 27 17 3} +do_test boundary2-4.58.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY r + } +} {27 45 17 28 3} +do_test boundary2-4.58.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY r DESC + } +} {3 28 17 45 27} +do_test boundary2-4.58.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963967 ORDER BY x + } +} {27 45 17 28 3} +do_test boundary2-4.58.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.58.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.58.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43} +do_test boundary2-4.58.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY r DESC + } +} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.58.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963967 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.58.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.58.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.58.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27} +do_test boundary2-4.58.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY r DESC + } +} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.58.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963967 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.59.1 { + db eval { + SELECT * FROM t1 WHERE r=4398046511104 + } +} {4398046511104 56 0000040000000000} +do_test boundary2-4.59.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000040000000000' + } +} {4398046511104 56} +do_test boundary2-4.59.3 { + db eval { + SELECT r, x FROM t1 WHERE a=56 + } +} {4398046511104 0000040000000000} +do_test boundary2-4.59.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45} +do_test boundary2-4.59.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY a DESC + } +} {45 43 34 28 27 26 25 17 13 10 3} +do_test boundary2-4.59.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY r + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.59.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25} +do_test boundary2-4.59.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 4398046511104 ORDER BY x + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.59.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY a + } +} {3 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary2-4.59.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 3} +do_test boundary2-4.59.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY r + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.59.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary2-4.59.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 4398046511104 ORDER BY x + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.59.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary2-4.59.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-4.59.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary2-4.59.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY r DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.59.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 4398046511104 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.59.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.59.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary2-4.59.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56} +do_test boundary2-4.59.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY r DESC + } +} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.59.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 4398046511104 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.60.1 { + db eval { + SELECT * FROM t1 WHERE r=1 + } +} {1 60 0000000000000001} +do_test boundary2-4.60.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000001' + } +} {1 60} +do_test boundary2-4.60.3 { + db eval { + SELECT r, x FROM t1 WHERE a=60 + } +} {1 0000000000000001} +do_test boundary2-4.60.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.60.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.60.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY r + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.60.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary2-4.60.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 1 ORDER BY x + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.60.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62} +do_test boundary2-4.60.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY a DESC + } +} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.60.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY r + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.60.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary2-4.60.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 1 ORDER BY x + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.60.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64} +do_test boundary2-4.60.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY a DESC + } +} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-4.60.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary2-4.60.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY r DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.60.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 1 ORDER BY x + } +} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.60.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.60.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary2-4.60.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary2-4.60.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY r DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.60.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 1 ORDER BY x + } +} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.61.1 { + db eval { + SELECT * FROM t1 WHERE r=36028797018963968 + } +} {36028797018963968 45 0080000000000000} +do_test boundary2-4.61.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0080000000000000' + } +} {36028797018963968 45} +do_test boundary2-4.61.3 { + db eval { + SELECT r, x FROM t1 WHERE a=45 + } +} {36028797018963968 0080000000000000} +do_test boundary2-4.61.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY a + } +} {3 17 28} +do_test boundary2-4.61.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY a DESC + } +} {28 17 3} +do_test boundary2-4.61.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY r + } +} {17 28 3} +do_test boundary2-4.61.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY r DESC + } +} {3 28 17} +do_test boundary2-4.61.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 36028797018963968 ORDER BY x + } +} {17 28 3} +do_test boundary2-4.61.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY a + } +} {3 17 28 45} +do_test boundary2-4.61.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY a DESC + } +} {45 28 17 3} +do_test boundary2-4.61.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY r + } +} {45 17 28 3} +do_test boundary2-4.61.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY r DESC + } +} {3 28 17 45} +do_test boundary2-4.61.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 36028797018963968 ORDER BY x + } +} {45 17 28 3} +do_test boundary2-4.61.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.61.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.61.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27} +do_test boundary2-4.61.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY r DESC + } +} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.61.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.61.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.61.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary2-4.61.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45} +do_test boundary2-4.61.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY r DESC + } +} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.61.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 36028797018963968 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.62.1 { + db eval { + SELECT * FROM t1 WHERE r=-2147483649 + } +} {-2147483649 47 ffffffff7fffffff} +do_test boundary2-4.62.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ffffffff7fffffff' + } +} {-2147483649 47} +do_test boundary2-4.62.3 { + db eval { + SELECT r, x FROM t1 WHERE a=47 + } +} {-2147483649 ffffffff7fffffff} +do_test boundary2-4.62.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.62.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.62.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY r + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.62.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary2-4.62.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -2147483649 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.62.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary2-4.62.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.62.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY r + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.62.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary2-4.62.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -2147483649 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.62.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY a + } +} {2 21 44 55 58 63 64} +do_test boundary2-4.62.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY a DESC + } +} {64 63 58 55 44 21 2} +do_test boundary2-4.62.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY r + } +} {55 2 64 21 44 58 63} +do_test boundary2-4.62.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY r DESC + } +} {63 58 44 21 64 2 55} +do_test boundary2-4.62.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -2147483649 ORDER BY x + } +} {55 2 64 21 44 58 63} +do_test boundary2-4.62.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY a + } +} {2 21 44 47 55 58 63 64} +do_test boundary2-4.62.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY a DESC + } +} {64 63 58 55 47 44 21 2} +do_test boundary2-4.62.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY r + } +} {55 2 64 21 44 58 63 47} +do_test boundary2-4.62.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY r DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary2-4.62.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -2147483649 ORDER BY x + } +} {55 2 64 21 44 58 63 47} +do_test boundary2-4.63.1 { + db eval { + SELECT * FROM t1 WHERE r=-36028797018963969 + } +} {-36028797018963969 2 ff7fffffffffffff} +do_test boundary2-4.63.2 { + db eval { + SELECT r, a FROM t1 WHERE x='ff7fffffffffffff' + } +} {-36028797018963969 2} +do_test boundary2-4.63.3 { + db eval { + SELECT r, x FROM t1 WHERE a=2 + } +} {-36028797018963969 ff7fffffffffffff} +do_test boundary2-4.63.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.63.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary2-4.63.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY r + } +} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.63.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64} +do_test boundary2-4.63.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -36028797018963969 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.63.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.63.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-4.63.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY r + } +} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.63.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2} +do_test boundary2-4.63.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -36028797018963969 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.63.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY a + } +} {55} +do_test boundary2-4.63.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY a DESC + } +} {55} +do_test boundary2-4.63.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY r + } +} {55} +do_test boundary2-4.63.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY r DESC + } +} {55} +do_test boundary2-4.63.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -36028797018963969 ORDER BY x + } +} {55} +do_test boundary2-4.63.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY a + } +} {2 55} +do_test boundary2-4.63.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY a DESC + } +} {55 2} +do_test boundary2-4.63.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY r + } +} {55 2} +do_test boundary2-4.63.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY r DESC + } +} {2 55} +do_test boundary2-4.63.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -36028797018963969 ORDER BY x + } +} {55 2} +do_test boundary2-4.64.1 { + db eval { + SELECT * FROM t1 WHERE r=3 + } +} {3 5 0000000000000003} +do_test boundary2-4.64.2 { + db eval { + SELECT r, a FROM t1 WHERE x='0000000000000003' + } +} {3 5} +do_test boundary2-4.64.3 { + db eval { + SELECT r, x FROM t1 WHERE a=5 + } +} {3 0000000000000003} +do_test boundary2-4.64.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.64.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary2-4.64.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY r + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.64.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary2-4.64.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 3 ORDER BY x + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.64.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary2-4.64.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary2-4.64.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY r + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.64.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary2-4.64.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 3 ORDER BY x + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.64.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY a + } +} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.64.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1} +do_test boundary2-4.64.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary2-4.64.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY r DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.64.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 3 ORDER BY x + } +} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.64.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY a + } +} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary2-4.64.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1} +do_test boundary2-4.64.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary2-4.64.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY r DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.64.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 3 ORDER BY x + } +} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.65.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary2-4.65.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary2-4.65.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY r + } +} {} +do_test boundary2-4.65.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY r DESC + } +} {} +do_test boundary2-4.65.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > 9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary2-4.65.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary2-4.65.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary2-4.65.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY r + } +} {} +do_test boundary2-4.65.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY r DESC + } +} {} +do_test boundary2-4.65.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= 9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary2-4.65.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.65.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-4.65.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.65.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.65.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < 9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.65.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.65.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-4.65.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.65.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.65.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= 9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.66.gt.1 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.66.gt.2 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-4.66.gt.3 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.66.gt.4 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.66.gt.5 { + db eval { + SELECT a FROM t1 WHERE r > -9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.66.ge.1 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary2-4.66.ge.2 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary2-4.66.ge.3 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY r + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary2-4.66.ge.4 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY r DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary2-4.66.ge.5 { + db eval { + SELECT a FROM t1 WHERE r >= -9.22337303685477580800e+18 ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary2-4.66.lt.1 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary2-4.66.lt.2 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary2-4.66.lt.3 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY r + } +} {} +do_test boundary2-4.66.lt.4 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY r DESC + } +} {} +do_test boundary2-4.66.lt.5 { + db eval { + SELECT a FROM t1 WHERE r < -9.22337303685477580800e+18 ORDER BY x + } +} {} +do_test boundary2-4.66.le.1 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY a + } +} {} +do_test boundary2-4.66.le.2 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY a DESC + } +} {} +do_test boundary2-4.66.le.3 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY r + } +} {} +do_test boundary2-4.66.le.4 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY r DESC + } +} {} +do_test boundary2-4.66.le.5 { + db eval { + SELECT a FROM t1 WHERE r <= -9.22337303685477580800e+18 ORDER BY x + } +} {} +finish_test diff --git a/components/external/SQLite-3.8.1/test/boundary3.tcl b/components/external/SQLite-3.8.1/test/boundary3.tcl new file mode 100644 index 0000000000000000000000000000000000000000..5fc26d6113f087f50cf783244c41764417173a23 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/boundary3.tcl @@ -0,0 +1,289 @@ +puts {# 2008 December 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is automatically generated from a separate TCL script. +# This file seeks to exercise integer boundary values. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Many of the boundary tests depend on a working 64-bit implementation. +if {![working_64bit_int]} { finish_test; return } +} + +expr srand(0) + +# Generate interesting boundary numbers +# +foreach x { + 0 + 1 + 0x7f + 0x7fff + 0x7fffff + 0x7fffffff + 0x7fffffffff + 0x7fffffffffff + 0x7fffffffffffff + 0x7fffffffffffffff +} { + set x [expr {wide($x)}] + set boundarynum($x) 1 + set boundarynum([expr {wide($x+1)}]) 1 + set boundarynum([expr {wide(-($x+1))}]) 1 + set boundarynum([expr {wide(-($x+2))}]) 1 + set boundarynum([expr {wide($x+$x+1)}]) 1 + set boundarynum([expr {wide($x+$x+2)}]) 1 +} +set x [expr {wide(127)}] +for {set i 1} {$i<=9} {incr i} { + set boundarynum($x) 1 + set boundarynum([expr {wide($x+1)}]) 1 + set x [expr {wide($x*128 + 127)}] +} + +# Scramble the $inlist into a random order. +# +proc scramble {inlist} { + set y {} + foreach x $inlist { + lappend y [list [expr {rand()}] $x] + } + set y [lsort $y] + set outlist {} + foreach x $y { + lappend outlist [lindex $x 1] + } + return $outlist +} + +# A simple selection sort. Not trying to be efficient. +# +proc sort {inlist} { + set outlist {} + set mn [lindex $inlist 0] + foreach x $inlist { + if {$x<$mn} {set mn $x} + } + set outlist $mn + set mx $mn + while {1} { + set valid 0 + foreach x $inlist { + if {$x>$mx && (!$valid || $mn>$x)} { + set mn $x + set valid 1 + } + } + if {!$valid} break + lappend outlist $mn + set mx $mn + } + return $outlist +} + +# Reverse the order of a list +# +proc reverse {inlist} { + set i [llength $inlist] + set outlist {} + for {incr i -1} {$i>=0} {incr i -1} { + lappend outlist [lindex $inlist $i] + } + return $outlist +} + +set nums1 [scramble [array names boundarynum]] +set nums2 [scramble [array names boundarynum]] + +set tname boundary3 +puts "do_test $tname-1.1 \173" +puts " db eval \173" +puts " CREATE TABLE t1(a,x);" +set a 0 +foreach r $nums1 { + incr a + set t1ra($r) $a + set t1ar($a) $r + set x [format %016x [expr {wide($r)}]] + set t1rx($r) $x + set t1xr($x) $r + puts " INSERT INTO t1(oid,a,x) VALUES($r,$a,'$x');" +} +puts " CREATE INDEX t1i1 ON t1(a);" +puts " CREATE INDEX t1i2 ON t1(x);" +puts " \175" +puts "\175 {}" + +puts "do_test $tname-1.2 \173" +puts " db eval \173" +puts " SELECT count(*) FROM t1" +puts " \175" +puts "\175 {64}" + +puts "do_test $tname-1.3 \173" +puts " db eval \173" +puts " CREATE TABLE t2(r,a);" +puts " INSERT INTO t2 SELECT rowid, a FROM t1;" +puts " CREATE INDEX t2i1 ON t2(r);" +puts " CREATE INDEX t2i2 ON t2(a);" +puts " INSERT INTO t2 VALUES(9.22337303685477580800e+18,65);" +set t1ra(9.22337303685477580800e+18) 65 +set t1ar(65) 9.22337303685477580800e+18) +puts " INSERT INTO t2 VALUES(-9.22337303685477580800e+18,66);" +set t1ra(-9.22337303685477580800e+18) 66 +set t1ar(66) -9.22337303685477580800e+18) +puts " SELECT count(*) FROM t2;" +puts " \175" +puts "\175 {66}" + +set nums3 $nums2 +lappend nums3 9.22337303685477580800e+18 +lappend nums3 -9.22337303685477580800e+18 + +set i 0 +foreach r $nums3 { + incr i + + set r5 $r.5 + set r0 $r.0 + if {abs($r)<0x7FFFFFFFFFFFFFFF || $r==-9223372036854775808} { + set x $t1rx($r) + set a $t1ra($r) + puts "do_test $tname-2.$i.1 \173" + puts " db eval \173" + puts " SELECT t1.* FROM t1, t2 WHERE t1.rowid=$r AND t2.a=t1.a" + puts " \175" + puts "\175 {$a $x}" + puts "do_test $tname-2.$i.2 \173" + puts " db eval \173" + puts " SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='$x'" + puts " \175" + puts "\175 {$r $a}" + puts "do_test $tname-2.$i.3 \173" + puts " db eval \173" + puts " SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=$a" + puts " \175" + puts "\175 {$r $x}" + } + + foreach op {> >= < <=} subno {gt ge lt le} { + + ################################################################ 2.x.y.1 + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r" { + lappend rset $rx + lappend aset $t1ra($rx) + } + } + puts "do_test $tname-2.$i.$subno.1 \173" + puts " db eval \173" + puts " SELECT t2.a FROM t1 JOIN t2 USING(a)" + puts " WHERE t1.rowid $op $r ORDER BY t2.a" + puts " \175" + puts "\175 {[sort $aset]}" + + ################################################################ 2.x.y.2 + puts "do_test $tname-2.$i.$subno.2 \173" + puts " db eval \173" + puts " SELECT t2.a FROM t2 NATURAL JOIN t1" + puts " WHERE t1.rowid $op $r ORDER BY t1.a DESC" + puts " \175" + puts "\175 {[reverse [sort $aset]]}" + + + ################################################################ 2.x.y.3 + set ax $t1ra($r) + set aset {} + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.3 \173" + puts " db eval \173" + puts " SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op t2.r" + puts " WHERE t2.a=$ax" + puts " ORDER BY t1.rowid" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.4 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.4 \173" + puts " db eval \173" + puts " SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op t2.r" + puts " WHERE t2.a=$ax" + puts " ORDER BY t1.rowid DESC" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.5 + set aset {} + set xset {} + foreach rx $rset { + lappend xset $t1rx($rx) + } + foreach x [sort $xset] { + set rx $t1xr($x) + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.5 \173" + puts " db eval \173" + puts " SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op t2.r" + puts " WHERE t2.a=$ax" + puts " ORDER BY x" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.10 + if {[string length $r5]>15} continue + set rset {} + set aset {} + foreach rx $nums2 { + if "\$rx $op \$r0" { + lappend rset $rx + } + } + foreach rx [sort $rset] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.10 \173" + puts " db eval \173" + puts " SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op CAST(t2.r AS real)" + puts " WHERE t2.a=$ax" + puts " ORDER BY t1.rowid" + puts " \175" + puts "\175 {$aset}" + + ################################################################ 2.x.y.11 + set aset {} + foreach rx [reverse [sort $rset]] { + lappend aset $t1ra($rx) + } + puts "do_test $tname-2.$i.$subno.11 \173" + puts " db eval \173" + puts " SELECT t1.a FROM t1 JOIN t2 ON t1.rowid $op CAST(t2.r AS real)" + puts " WHERE t2.a=$ax" + puts " ORDER BY t1.rowid DESC" + puts " \175" + puts "\175 {$aset}" + } + +} + + +puts {finish_test} diff --git a/components/external/SQLite-3.8.1/test/boundary3.test b/components/external/SQLite-3.8.1/test/boundary3.test new file mode 100644 index 0000000000000000000000000000000000000000..dbe9abfa0a9fb7fc28987dae9b4ca9724c2860ec --- /dev/null +++ b/components/external/SQLite-3.8.1/test/boundary3.test @@ -0,0 +1,12456 @@ +# 2008 December 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is automatically generated from a separate TCL script. +# This file seeks to exercise integer boundary values. +# +# $Id: boundary3.test,v 1.2 2009/01/02 15:45:48 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Many of the boundary tests depend on a working 64-bit implementation. +if {![working_64bit_int]} { finish_test; return } + +do_test boundary3-1.1 { + db eval { + CREATE TABLE t1(a,x); + INSERT INTO t1(oid,a,x) VALUES(-8388609,1,'ffffffffff7fffff'); + INSERT INTO t1(oid,a,x) VALUES(-36028797018963969,2,'ff7fffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(9223372036854775807,3,'7fffffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(127,4,'000000000000007f'); + INSERT INTO t1(oid,a,x) VALUES(3,5,'0000000000000003'); + INSERT INTO t1(oid,a,x) VALUES(16777216,6,'0000000001000000'); + INSERT INTO t1(oid,a,x) VALUES(4398046511103,7,'000003ffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(16383,8,'0000000000003fff'); + INSERT INTO t1(oid,a,x) VALUES(16777215,9,'0000000000ffffff'); + INSERT INTO t1(oid,a,x) VALUES(281474976710655,10,'0000ffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-2147483648,11,'ffffffff80000000'); + INSERT INTO t1(oid,a,x) VALUES(268435455,12,'000000000fffffff'); + INSERT INTO t1(oid,a,x) VALUES(562949953421311,13,'0001ffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(4294967295,14,'00000000ffffffff'); + INSERT INTO t1(oid,a,x) VALUES(2097151,15,'00000000001fffff'); + INSERT INTO t1(oid,a,x) VALUES(16384,16,'0000000000004000'); + INSERT INTO t1(oid,a,x) VALUES(72057594037927935,17,'00ffffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(8388607,18,'00000000007fffff'); + INSERT INTO t1(oid,a,x) VALUES(1099511627776,19,'0000010000000000'); + INSERT INTO t1(oid,a,x) VALUES(2147483647,20,'000000007fffffff'); + INSERT INTO t1(oid,a,x) VALUES(-140737488355329,21,'ffff7fffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(34359738368,22,'0000000800000000'); + INSERT INTO t1(oid,a,x) VALUES(32767,23,'0000000000007fff'); + INSERT INTO t1(oid,a,x) VALUES(8388608,24,'0000000000800000'); + INSERT INTO t1(oid,a,x) VALUES(140737488355327,25,'00007fffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(281474976710656,26,'0001000000000000'); + INSERT INTO t1(oid,a,x) VALUES(36028797018963967,27,'007fffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(72057594037927936,28,'0100000000000000'); + INSERT INTO t1(oid,a,x) VALUES(-32769,29,'ffffffffffff7fff'); + INSERT INTO t1(oid,a,x) VALUES(255,30,'00000000000000ff'); + INSERT INTO t1(oid,a,x) VALUES(4,31,'0000000000000004'); + INSERT INTO t1(oid,a,x) VALUES(-32768,32,'ffffffffffff8000'); + INSERT INTO t1(oid,a,x) VALUES(-2,33,'fffffffffffffffe'); + INSERT INTO t1(oid,a,x) VALUES(140737488355328,34,'0000800000000000'); + INSERT INTO t1(oid,a,x) VALUES(549755813888,35,'0000008000000000'); + INSERT INTO t1(oid,a,x) VALUES(4294967296,36,'0000000100000000'); + INSERT INTO t1(oid,a,x) VALUES(-8388608,37,'ffffffffff800000'); + INSERT INTO t1(oid,a,x) VALUES(-1,38,'ffffffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(34359738367,39,'00000007ffffffff'); + INSERT INTO t1(oid,a,x) VALUES(268435456,40,'0000000010000000'); + INSERT INTO t1(oid,a,x) VALUES(2,41,'0000000000000002'); + INSERT INTO t1(oid,a,x) VALUES(2097152,42,'0000000000200000'); + INSERT INTO t1(oid,a,x) VALUES(562949953421312,43,'0002000000000000'); + INSERT INTO t1(oid,a,x) VALUES(-140737488355328,44,'ffff800000000000'); + INSERT INTO t1(oid,a,x) VALUES(36028797018963968,45,'0080000000000000'); + INSERT INTO t1(oid,a,x) VALUES(549755813887,46,'0000007fffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-2147483649,47,'ffffffff7fffffff'); + INSERT INTO t1(oid,a,x) VALUES(65535,48,'000000000000ffff'); + INSERT INTO t1(oid,a,x) VALUES(128,49,'0000000000000080'); + INSERT INTO t1(oid,a,x) VALUES(32768,50,'0000000000008000'); + INSERT INTO t1(oid,a,x) VALUES(2147483648,51,'0000000080000000'); + INSERT INTO t1(oid,a,x) VALUES(-3,52,'fffffffffffffffd'); + INSERT INTO t1(oid,a,x) VALUES(-128,53,'ffffffffffffff80'); + INSERT INTO t1(oid,a,x) VALUES(-129,54,'ffffffffffffff7f'); + INSERT INTO t1(oid,a,x) VALUES(-9223372036854775808,55,'8000000000000000'); + INSERT INTO t1(oid,a,x) VALUES(4398046511104,56,'0000040000000000'); + INSERT INTO t1(oid,a,x) VALUES(1099511627775,57,'000000ffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-549755813889,58,'ffffff7fffffffff'); + INSERT INTO t1(oid,a,x) VALUES(0,59,'0000000000000000'); + INSERT INTO t1(oid,a,x) VALUES(1,60,'0000000000000001'); + INSERT INTO t1(oid,a,x) VALUES(256,61,'0000000000000100'); + INSERT INTO t1(oid,a,x) VALUES(65536,62,'0000000000010000'); + INSERT INTO t1(oid,a,x) VALUES(-549755813888,63,'ffffff8000000000'); + INSERT INTO t1(oid,a,x) VALUES(-36028797018963968,64,'ff80000000000000'); + CREATE INDEX t1i1 ON t1(a); + CREATE INDEX t1i2 ON t1(x); + } +} {} +do_test boundary3-1.2 { + db eval { + SELECT count(*) FROM t1 + } +} {64} +do_test boundary3-1.3 { + db eval { + CREATE TABLE t2(r,a); + INSERT INTO t2 SELECT rowid, a FROM t1; + CREATE INDEX t2i1 ON t2(r); + CREATE INDEX t2i2 ON t2(a); + INSERT INTO t2 VALUES(9.22337303685477580800e+18,65); + INSERT INTO t2 VALUES(-9.22337303685477580800e+18,66); + SELECT count(*) FROM t2; + } +} {66} +do_test boundary3-2.1.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=72057594037927935 AND t2.a=t1.a + } +} {17 00ffffffffffffff} +do_test boundary3-2.1.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='00ffffffffffffff' + } +} {72057594037927935 17} +do_test boundary3-2.1.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=17 + } +} {72057594037927935 00ffffffffffffff} +do_test boundary3-2.1.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 72057594037927935 ORDER BY t2.a + } +} {3 28} +do_test boundary3-2.1.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 72057594037927935 ORDER BY t1.a DESC + } +} {28 3} +do_test boundary3-2.1.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=17 + ORDER BY t1.rowid + } +} {28 3} +do_test boundary3-2.1.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=17 + ORDER BY t1.rowid DESC + } +} {3 28} +do_test boundary3-2.1.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=17 + ORDER BY x + } +} {28 3} +do_test boundary3-2.1.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 72057594037927935 ORDER BY t2.a + } +} {3 17 28} +do_test boundary3-2.1.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 72057594037927935 ORDER BY t1.a DESC + } +} {28 17 3} +do_test boundary3-2.1.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=17 + ORDER BY t1.rowid + } +} {17 28 3} +do_test boundary3-2.1.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=17 + ORDER BY t1.rowid DESC + } +} {3 28 17} +do_test boundary3-2.1.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=17 + ORDER BY x + } +} {17 28 3} +do_test boundary3-2.1.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 72057594037927935 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.1.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 72057594037927935 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.1.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=17 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45} +do_test boundary3-2.1.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=17 + ORDER BY t1.rowid DESC + } +} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.1.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=17 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.1.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 72057594037927935 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.1.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 72057594037927935 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.1.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=17 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17} +do_test boundary3-2.1.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=17 + ORDER BY t1.rowid DESC + } +} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.1.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=17 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.2.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=16384 AND t2.a=t1.a + } +} {16 0000000000004000} +do_test boundary3-2.2.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000004000' + } +} {16384 16} +do_test boundary3-2.2.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=16 + } +} {16384 0000000000004000} +do_test boundary3-2.2.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 16384 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary3-2.2.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 16384 ORDER BY t1.a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.2.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=16 + ORDER BY t1.rowid + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.2.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=16 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary3-2.2.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=16 + ORDER BY x + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.2.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=16 + ORDER BY t1.rowid + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.2.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=16 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary3-2.2.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 16384 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary3-2.2.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 16384 ORDER BY t1.a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.2.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=16 + ORDER BY t1.rowid + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.2.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=16 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary3-2.2.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=16 + ORDER BY x + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.2.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=16 + ORDER BY t1.rowid + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.2.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=16 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary3-2.2.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 16384 ORDER BY t2.a + } +} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.2.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 16384 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1} +do_test boundary3-2.2.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=16 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary3-2.2.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=16 + ORDER BY t1.rowid DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.2.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=16 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.2.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=16 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary3-2.2.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=16 + ORDER BY t1.rowid DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.2.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 16384 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.2.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 16384 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1} +do_test boundary3-2.2.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=16 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary3-2.2.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=16 + ORDER BY t1.rowid DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.2.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=16 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.2.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=16 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary3-2.2.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=16 + ORDER BY t1.rowid DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.3.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=4294967296 AND t2.a=t1.a + } +} {36 0000000100000000} +do_test boundary3-2.3.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000100000000' + } +} {4294967296 36} +do_test boundary3-2.3.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=36 + } +} {4294967296 0000000100000000} +do_test boundary3-2.3.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 4294967296 ORDER BY t2.a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57} +do_test boundary3-2.3.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 4294967296 ORDER BY t1.a DESC + } +} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary3-2.3.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=36 + ORDER BY t1.rowid + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.3.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=36 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary3-2.3.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=36 + ORDER BY x + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.3.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=36 + ORDER BY t1.rowid + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.3.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=36 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary3-2.3.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 4294967296 ORDER BY t2.a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary3-2.3.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 4294967296 ORDER BY t1.a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary3-2.3.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=36 + ORDER BY t1.rowid + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.3.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=36 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary3-2.3.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=36 + ORDER BY x + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.3.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=36 + ORDER BY t1.rowid + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.3.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=36 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary3-2.3.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 4294967296 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.3.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 4294967296 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.3.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=36 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary3-2.3.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=36 + ORDER BY t1.rowid DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.3.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=36 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.3.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=36 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary3-2.3.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=36 + ORDER BY t1.rowid DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.3.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 4294967296 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.3.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 4294967296 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.3.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=36 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary3-2.3.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=36 + ORDER BY t1.rowid DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.3.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=36 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.3.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=36 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary3-2.3.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=36 + ORDER BY t1.rowid DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.4.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=16777216 AND t2.a=t1.a + } +} {6 0000000001000000} +do_test boundary3-2.4.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000001000000' + } +} {16777216 6} +do_test boundary3-2.4.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=6 + } +} {16777216 0000000001000000} +do_test boundary3-2.4.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 16777216 ORDER BY t2.a + } +} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.4.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 16777216 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3} +do_test boundary3-2.4.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=6 + ORDER BY t1.rowid + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.4.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=6 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary3-2.4.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=6 + ORDER BY x + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.4.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=6 + ORDER BY t1.rowid + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.4.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=6 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary3-2.4.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 16777216 ORDER BY t2.a + } +} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.4.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 16777216 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3} +do_test boundary3-2.4.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=6 + ORDER BY t1.rowid + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.4.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=6 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary3-2.4.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=6 + ORDER BY x + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.4.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=6 + ORDER BY t1.rowid + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.4.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=6 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary3-2.4.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 16777216 ORDER BY t2.a + } +} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.4.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 16777216 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1} +do_test boundary3-2.4.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=6 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary3-2.4.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=6 + ORDER BY t1.rowid DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.4.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=6 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.4.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=6 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary3-2.4.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=6 + ORDER BY t1.rowid DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.4.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 16777216 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.4.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 16777216 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1} +do_test boundary3-2.4.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=6 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary3-2.4.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=6 + ORDER BY t1.rowid DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.4.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=6 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.4.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=6 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary3-2.4.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=6 + ORDER BY t1.rowid DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.5.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-32769 AND t2.a=t1.a + } +} {29 ffffffffffff7fff} +do_test boundary3-2.5.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffffffffff7fff' + } +} {-32769 29} +do_test boundary3-2.5.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=29 + } +} {-32769 ffffffffffff7fff} +do_test boundary3-2.5.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -32769 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.5.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -32769 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.5.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=29 + ORDER BY t1.rowid + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.5.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=29 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary3-2.5.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=29 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38} +do_test boundary3-2.5.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=29 + ORDER BY t1.rowid + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.5.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=29 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary3-2.5.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -32769 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.5.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -32769 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.5.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=29 + ORDER BY t1.rowid + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.5.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=29 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary3-2.5.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=29 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38} +do_test boundary3-2.5.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=29 + ORDER BY t1.rowid + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.5.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=29 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary3-2.5.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -32769 ORDER BY t2.a + } +} {1 2 11 21 37 44 47 55 58 63 64} +do_test boundary3-2.5.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -32769 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 37 21 11 2 1} +do_test boundary3-2.5.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=29 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary3-2.5.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=29 + ORDER BY t1.rowid DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.5.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=29 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary3-2.5.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=29 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary3-2.5.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=29 + ORDER BY t1.rowid DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.5.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -32769 ORDER BY t2.a + } +} {1 2 11 21 29 37 44 47 55 58 63 64} +do_test boundary3-2.5.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -32769 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 37 29 21 11 2 1} +do_test boundary3-2.5.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=29 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary3-2.5.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=29 + ORDER BY t1.rowid DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.5.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=29 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary3-2.5.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=29 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary3-2.5.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=29 + ORDER BY t1.rowid DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.6.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-140737488355329 AND t2.a=t1.a + } +} {21 ffff7fffffffffff} +do_test boundary3-2.6.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffff7fffffffffff' + } +} {-140737488355329 21} +do_test boundary3-2.6.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=21 + } +} {-140737488355329 ffff7fffffffffff} +do_test boundary3-2.6.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -140737488355329 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary3-2.6.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -140737488355329 ORDER BY t1.a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.6.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=21 + ORDER BY t1.rowid + } +} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.6.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=21 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44} +do_test boundary3-2.6.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=21 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.6.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -140737488355329 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary3-2.6.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -140737488355329 ORDER BY t1.a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.6.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=21 + ORDER BY t1.rowid + } +} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.6.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=21 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21} +do_test boundary3-2.6.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=21 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.6.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -140737488355329 ORDER BY t2.a + } +} {2 55 64} +do_test boundary3-2.6.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -140737488355329 ORDER BY t1.a DESC + } +} {64 55 2} +do_test boundary3-2.6.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=21 + ORDER BY t1.rowid + } +} {55 2 64} +do_test boundary3-2.6.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=21 + ORDER BY t1.rowid DESC + } +} {64 2 55} +do_test boundary3-2.6.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=21 + ORDER BY x + } +} {55 2 64} +do_test boundary3-2.6.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -140737488355329 ORDER BY t2.a + } +} {2 21 55 64} +do_test boundary3-2.6.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -140737488355329 ORDER BY t1.a DESC + } +} {64 55 21 2} +do_test boundary3-2.6.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=21 + ORDER BY t1.rowid + } +} {55 2 64 21} +do_test boundary3-2.6.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=21 + ORDER BY t1.rowid DESC + } +} {21 64 2 55} +do_test boundary3-2.6.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=21 + ORDER BY x + } +} {55 2 64 21} +do_test boundary3-2.7.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=2 AND t2.a=t1.a + } +} {41 0000000000000002} +do_test boundary3-2.7.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000000002' + } +} {2 41} +do_test boundary3-2.7.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=41 + } +} {2 0000000000000002} +do_test boundary3-2.7.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 2 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.7.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 2 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.7.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=41 + ORDER BY t1.rowid + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.7.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=41 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary3-2.7.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=41 + ORDER BY x + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.7.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=41 + ORDER BY t1.rowid + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.7.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=41 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary3-2.7.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 2 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.7.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 2 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.7.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=41 + ORDER BY t1.rowid + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.7.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=41 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary3-2.7.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=41 + ORDER BY x + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.7.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=41 + ORDER BY t1.rowid + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.7.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=41 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary3-2.7.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 2 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.7.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 2 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary3-2.7.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=41 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary3-2.7.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=41 + ORDER BY t1.rowid DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.7.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=41 + ORDER BY x + } +} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.7.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=41 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary3-2.7.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=41 + ORDER BY t1.rowid DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.7.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 2 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.7.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 2 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1} +do_test boundary3-2.7.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=41 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary3-2.7.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=41 + ORDER BY t1.rowid DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.7.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=41 + ORDER BY x + } +} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.7.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=41 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary3-2.7.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=41 + ORDER BY t1.rowid DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.8.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=4 AND t2.a=t1.a + } +} {31 0000000000000004} +do_test boundary3-2.8.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000000004' + } +} {4 31} +do_test boundary3-2.8.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=31 + } +} {4 0000000000000004} +do_test boundary3-2.8.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 4 ORDER BY t2.a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.8.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 4 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary3-2.8.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=31 + ORDER BY t1.rowid + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.8.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=31 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary3-2.8.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=31 + ORDER BY x + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.8.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=31 + ORDER BY t1.rowid + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.8.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=31 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary3-2.8.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 4 ORDER BY t2.a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.8.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 4 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary3-2.8.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=31 + ORDER BY t1.rowid + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.8.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=31 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary3-2.8.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=31 + ORDER BY x + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.8.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=31 + ORDER BY t1.rowid + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.8.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=31 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary3-2.8.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 4 ORDER BY t2.a + } +} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.8.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 4 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1} +do_test boundary3-2.8.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=31 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary3-2.8.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=31 + ORDER BY t1.rowid DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.8.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=31 + ORDER BY x + } +} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.8.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=31 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary3-2.8.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=31 + ORDER BY t1.rowid DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.8.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 4 ORDER BY t2.a + } +} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.8.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 4 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1} +do_test boundary3-2.8.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=31 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary3-2.8.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=31 + ORDER BY t1.rowid DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.8.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=31 + ORDER BY x + } +} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.8.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=31 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary3-2.8.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=31 + ORDER BY t1.rowid DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.9.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=562949953421311 AND t2.a=t1.a + } +} {13 0001ffffffffffff} +do_test boundary3-2.9.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0001ffffffffffff' + } +} {562949953421311 13} +do_test boundary3-2.9.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=13 + } +} {562949953421311 0001ffffffffffff} +do_test boundary3-2.9.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 562949953421311 ORDER BY t2.a + } +} {3 17 27 28 43 45} +do_test boundary3-2.9.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 562949953421311 ORDER BY t1.a DESC + } +} {45 43 28 27 17 3} +do_test boundary3-2.9.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=13 + ORDER BY t1.rowid + } +} {43 27 45 17 28 3} +do_test boundary3-2.9.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=13 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43} +do_test boundary3-2.9.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=13 + ORDER BY x + } +} {43 27 45 17 28 3} +do_test boundary3-2.9.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 562949953421311 ORDER BY t2.a + } +} {3 13 17 27 28 43 45} +do_test boundary3-2.9.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 562949953421311 ORDER BY t1.a DESC + } +} {45 43 28 27 17 13 3} +do_test boundary3-2.9.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=13 + ORDER BY t1.rowid + } +} {13 43 27 45 17 28 3} +do_test boundary3-2.9.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=13 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13} +do_test boundary3-2.9.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=13 + ORDER BY x + } +} {13 43 27 45 17 28 3} +do_test boundary3-2.9.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 562949953421311 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.9.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 562949953421311 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.9.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=13 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26} +do_test boundary3-2.9.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=13 + ORDER BY t1.rowid DESC + } +} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.9.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=13 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.9.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 562949953421311 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.9.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 562949953421311 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.9.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=13 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13} +do_test boundary3-2.9.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=13 + ORDER BY t1.rowid DESC + } +} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.9.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=13 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.10.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=256 AND t2.a=t1.a + } +} {61 0000000000000100} +do_test boundary3-2.10.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000000100' + } +} {256 61} +do_test boundary3-2.10.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=61 + } +} {256 0000000000000100} +do_test boundary3-2.10.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 256 ORDER BY t2.a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary3-2.10.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 256 ORDER BY t1.a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary3-2.10.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=61 + ORDER BY t1.rowid + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.10.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=61 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary3-2.10.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=61 + ORDER BY x + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.10.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=61 + ORDER BY t1.rowid + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.10.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=61 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary3-2.10.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 256 ORDER BY t2.a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary3-2.10.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 256 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary3-2.10.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=61 + ORDER BY t1.rowid + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.10.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=61 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary3-2.10.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=61 + ORDER BY x + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.10.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=61 + ORDER BY t1.rowid + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.10.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=61 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary3-2.10.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 256 ORDER BY t2.a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.10.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 256 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary3-2.10.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=61 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary3-2.10.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=61 + ORDER BY t1.rowid DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.10.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=61 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.10.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=61 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary3-2.10.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=61 + ORDER BY t1.rowid DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.10.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 256 ORDER BY t2.a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.10.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 256 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary3-2.10.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=61 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary3-2.10.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=61 + ORDER BY t1.rowid DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.10.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=61 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.10.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=61 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary3-2.10.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=61 + ORDER BY t1.rowid DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.11.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=34359738368 AND t2.a=t1.a + } +} {22 0000000800000000} +do_test boundary3-2.11.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000800000000' + } +} {34359738368 22} +do_test boundary3-2.11.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=22 + } +} {34359738368 0000000800000000} +do_test boundary3-2.11.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 34359738368 ORDER BY t2.a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary3-2.11.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 34359738368 ORDER BY t1.a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary3-2.11.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=22 + ORDER BY t1.rowid + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.11.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=22 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary3-2.11.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=22 + ORDER BY x + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.11.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=22 + ORDER BY t1.rowid + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.11.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=22 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary3-2.11.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 34359738368 ORDER BY t2.a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary3-2.11.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 34359738368 ORDER BY t1.a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary3-2.11.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=22 + ORDER BY t1.rowid + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.11.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=22 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary3-2.11.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=22 + ORDER BY x + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.11.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=22 + ORDER BY t1.rowid + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.11.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=22 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary3-2.11.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 34359738368 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.11.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 34359738368 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.11.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=22 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary3-2.11.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=22 + ORDER BY t1.rowid DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.11.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=22 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.11.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=22 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary3-2.11.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=22 + ORDER BY t1.rowid DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.11.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 34359738368 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.11.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 34359738368 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.11.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=22 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary3-2.11.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=22 + ORDER BY t1.rowid DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.11.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=22 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.11.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=22 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary3-2.11.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=22 + ORDER BY t1.rowid DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.12.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=65536 AND t2.a=t1.a + } +} {62 0000000000010000} +do_test boundary3-2.12.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000010000' + } +} {65536 62} +do_test boundary3-2.12.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=62 + } +} {65536 0000000000010000} +do_test boundary3-2.12.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 65536 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary3-2.12.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 65536 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.12.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=62 + ORDER BY t1.rowid + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.12.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=62 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary3-2.12.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=62 + ORDER BY x + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.12.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=62 + ORDER BY t1.rowid + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.12.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=62 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary3-2.12.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 65536 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62} +do_test boundary3-2.12.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 65536 ORDER BY t1.a DESC + } +} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.12.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=62 + ORDER BY t1.rowid + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.12.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=62 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary3-2.12.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=62 + ORDER BY x + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.12.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=62 + ORDER BY t1.rowid + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.12.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=62 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary3-2.12.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 65536 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.12.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 65536 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary3-2.12.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=62 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary3-2.12.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=62 + ORDER BY t1.rowid DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.12.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=62 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.12.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=62 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary3-2.12.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=62 + ORDER BY t1.rowid DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.12.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 65536 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.12.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 65536 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary3-2.12.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=62 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary3-2.12.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=62 + ORDER BY t1.rowid DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.12.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=62 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.12.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=62 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary3-2.12.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=62 + ORDER BY t1.rowid DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.13.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=268435456 AND t2.a=t1.a + } +} {40 0000000010000000} +do_test boundary3-2.13.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000010000000' + } +} {268435456 40} +do_test boundary3-2.13.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=40 + } +} {268435456 0000000010000000} +do_test boundary3-2.13.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 268435456 ORDER BY t2.a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary3-2.13.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 268435456 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary3-2.13.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=40 + ORDER BY t1.rowid + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.13.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=40 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary3-2.13.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=40 + ORDER BY x + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.13.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=40 + ORDER BY t1.rowid + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.13.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=40 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary3-2.13.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 268435456 ORDER BY t2.a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.13.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 268435456 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary3-2.13.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=40 + ORDER BY t1.rowid + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.13.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=40 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary3-2.13.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=40 + ORDER BY x + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.13.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=40 + ORDER BY t1.rowid + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.13.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=40 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary3-2.13.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 268435456 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.13.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 268435456 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.13.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=40 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary3-2.13.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=40 + ORDER BY t1.rowid DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.13.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=40 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.13.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=40 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary3-2.13.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=40 + ORDER BY t1.rowid DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.13.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 268435456 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.13.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 268435456 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.13.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=40 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary3-2.13.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=40 + ORDER BY t1.rowid DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.13.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=40 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.13.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=40 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary3-2.13.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=40 + ORDER BY t1.rowid DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.14.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-140737488355328 AND t2.a=t1.a + } +} {44 ffff800000000000} +do_test boundary3-2.14.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffff800000000000' + } +} {-140737488355328 44} +do_test boundary3-2.14.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=44 + } +} {-140737488355328 ffff800000000000} +do_test boundary3-2.14.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -140737488355328 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary3-2.14.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -140737488355328 ORDER BY t1.a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.14.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=44 + ORDER BY t1.rowid + } +} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.14.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=44 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58} +do_test boundary3-2.14.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=44 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.14.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -140737488355328 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary3-2.14.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -140737488355328 ORDER BY t1.a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.14.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=44 + ORDER BY t1.rowid + } +} {44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.14.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=44 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44} +do_test boundary3-2.14.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=44 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.14.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -140737488355328 ORDER BY t2.a + } +} {2 21 55 64} +do_test boundary3-2.14.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -140737488355328 ORDER BY t1.a DESC + } +} {64 55 21 2} +do_test boundary3-2.14.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=44 + ORDER BY t1.rowid + } +} {55 2 64 21} +do_test boundary3-2.14.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=44 + ORDER BY t1.rowid DESC + } +} {21 64 2 55} +do_test boundary3-2.14.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=44 + ORDER BY x + } +} {55 2 64 21} +do_test boundary3-2.14.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -140737488355328 ORDER BY t2.a + } +} {2 21 44 55 64} +do_test boundary3-2.14.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -140737488355328 ORDER BY t1.a DESC + } +} {64 55 44 21 2} +do_test boundary3-2.14.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=44 + ORDER BY t1.rowid + } +} {55 2 64 21 44} +do_test boundary3-2.14.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=44 + ORDER BY t1.rowid DESC + } +} {44 21 64 2 55} +do_test boundary3-2.14.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=44 + ORDER BY x + } +} {55 2 64 21 44} +do_test boundary3-2.15.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=1099511627776 AND t2.a=t1.a + } +} {19 0000010000000000} +do_test boundary3-2.15.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000010000000000' + } +} {1099511627776 19} +do_test boundary3-2.15.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=19 + } +} {1099511627776 0000010000000000} +do_test boundary3-2.15.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 1099511627776 ORDER BY t2.a + } +} {3 7 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary3-2.15.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 1099511627776 ORDER BY t1.a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 7 3} +do_test boundary3-2.15.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=19 + ORDER BY t1.rowid + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.15.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=19 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary3-2.15.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=19 + ORDER BY x + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.15.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=19 + ORDER BY t1.rowid + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.15.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=19 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary3-2.15.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 1099511627776 ORDER BY t2.a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56} +do_test boundary3-2.15.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 1099511627776 ORDER BY t1.a DESC + } +} {56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary3-2.15.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=19 + ORDER BY t1.rowid + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.15.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=19 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary3-2.15.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=19 + ORDER BY x + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.15.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=19 + ORDER BY t1.rowid + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.15.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=19 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary3-2.15.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 1099511627776 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary3-2.15.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 1099511627776 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.15.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=19 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary3-2.15.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=19 + ORDER BY t1.rowid DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.15.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=19 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.15.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=19 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary3-2.15.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=19 + ORDER BY t1.rowid DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.15.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 1099511627776 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary3-2.15.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 1099511627776 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.15.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=19 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary3-2.15.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=19 + ORDER BY t1.rowid DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.15.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=19 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.15.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=19 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary3-2.15.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=19 + ORDER BY t1.rowid DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.16.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 9223372036854775807 ORDER BY t2.a + } +} {} +do_test boundary3-2.16.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 9223372036854775807 ORDER BY t1.a DESC + } +} {} +do_test boundary3-2.16.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=3 + ORDER BY t1.rowid + } +} {} +do_test boundary3-2.16.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=3 + ORDER BY t1.rowid DESC + } +} {} +do_test boundary3-2.16.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=3 + ORDER BY x + } +} {} +do_test boundary3-2.16.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 9223372036854775807 ORDER BY t2.a + } +} {3} +do_test boundary3-2.16.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 9223372036854775807 ORDER BY t1.a DESC + } +} {3} +do_test boundary3-2.16.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=3 + ORDER BY t1.rowid + } +} {3} +do_test boundary3-2.16.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=3 + ORDER BY t1.rowid DESC + } +} {3} +do_test boundary3-2.16.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=3 + ORDER BY x + } +} {3} +do_test boundary3-2.16.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 9223372036854775807 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.16.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 9223372036854775807 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.16.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=3 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28} +do_test boundary3-2.16.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=3 + ORDER BY t1.rowid DESC + } +} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.16.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=3 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.16.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 9223372036854775807 ORDER BY t2.a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.16.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 9223372036854775807 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary3-2.16.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=3 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.16.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=3 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.16.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=3 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.17.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=32768 AND t2.a=t1.a + } +} {50 0000000000008000} +do_test boundary3-2.17.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000008000' + } +} {32768 50} +do_test boundary3-2.17.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=50 + } +} {32768 0000000000008000} +do_test boundary3-2.17.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 32768 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62} +do_test boundary3-2.17.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 32768 ORDER BY t1.a DESC + } +} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.17.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=50 + ORDER BY t1.rowid + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.17.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=50 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary3-2.17.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=50 + ORDER BY x + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.17.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=50 + ORDER BY t1.rowid + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.17.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=50 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary3-2.17.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 32768 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary3-2.17.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 32768 ORDER BY t1.a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.17.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=50 + ORDER BY t1.rowid + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.17.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=50 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary3-2.17.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=50 + ORDER BY x + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.17.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=50 + ORDER BY t1.rowid + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.17.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=50 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary3-2.17.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 32768 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.17.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 32768 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary3-2.17.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=50 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary3-2.17.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=50 + ORDER BY t1.rowid DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.17.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=50 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.17.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=50 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary3-2.17.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=50 + ORDER BY t1.rowid DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.17.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 32768 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.17.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 32768 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary3-2.17.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=50 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary3-2.17.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=50 + ORDER BY t1.rowid DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.17.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=50 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.17.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=50 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary3-2.17.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=50 + ORDER BY t1.rowid DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.18.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-36028797018963968 AND t2.a=t1.a + } +} {64 ff80000000000000} +do_test boundary3-2.18.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ff80000000000000' + } +} {-36028797018963968 64} +do_test boundary3-2.18.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=64 + } +} {-36028797018963968 ff80000000000000} +do_test boundary3-2.18.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -36028797018963968 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary3-2.18.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -36028797018963968 ORDER BY t1.a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.18.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=64 + ORDER BY t1.rowid + } +} {21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.18.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=64 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21} +do_test boundary3-2.18.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=64 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.18.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -36028797018963968 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.18.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -36028797018963968 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.18.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=64 + ORDER BY t1.rowid + } +} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.18.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=64 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64} +do_test boundary3-2.18.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=64 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.18.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -36028797018963968 ORDER BY t2.a + } +} {2 55} +do_test boundary3-2.18.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -36028797018963968 ORDER BY t1.a DESC + } +} {55 2} +do_test boundary3-2.18.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=64 + ORDER BY t1.rowid + } +} {55 2} +do_test boundary3-2.18.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=64 + ORDER BY t1.rowid DESC + } +} {2 55} +do_test boundary3-2.18.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=64 + ORDER BY x + } +} {55 2} +do_test boundary3-2.18.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -36028797018963968 ORDER BY t2.a + } +} {2 55 64} +do_test boundary3-2.18.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -36028797018963968 ORDER BY t1.a DESC + } +} {64 55 2} +do_test boundary3-2.18.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=64 + ORDER BY t1.rowid + } +} {55 2 64} +do_test boundary3-2.18.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=64 + ORDER BY t1.rowid DESC + } +} {64 2 55} +do_test boundary3-2.18.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=64 + ORDER BY x + } +} {55 2 64} +do_test boundary3-2.19.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=65535 AND t2.a=t1.a + } +} {48 000000000000ffff} +do_test boundary3-2.19.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='000000000000ffff' + } +} {65535 48} +do_test boundary3-2.19.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=48 + } +} {65535 000000000000ffff} +do_test boundary3-2.19.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 65535 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57 62} +do_test boundary3-2.19.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 65535 ORDER BY t1.a DESC + } +} {62 57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.19.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=48 + ORDER BY t1.rowid + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.19.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=48 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary3-2.19.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=48 + ORDER BY x + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.19.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=48 + ORDER BY t1.rowid + } +} {62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.19.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=48 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62} +do_test boundary3-2.19.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 65535 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 51 56 57 62} +do_test boundary3-2.19.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 65535 ORDER BY t1.a DESC + } +} {62 57 56 51 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.19.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=48 + ORDER BY t1.rowid + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.19.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=48 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary3-2.19.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=48 + ORDER BY x + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.19.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=48 + ORDER BY t1.rowid + } +} {48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.19.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=48 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48} +do_test boundary3-2.19.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 65535 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.19.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 65535 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary3-2.19.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=48 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary3-2.19.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=48 + ORDER BY t1.rowid DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.19.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=48 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.19.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=48 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50} +do_test boundary3-2.19.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=48 + ORDER BY t1.rowid DESC + } +} {50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.19.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 65535 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.19.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 65535 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary3-2.19.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=48 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary3-2.19.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=48 + ORDER BY t1.rowid DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.19.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=48 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.19.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=48 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48} +do_test boundary3-2.19.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=48 + ORDER BY t1.rowid DESC + } +} {48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.20.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=4294967295 AND t2.a=t1.a + } +} {14 00000000ffffffff} +do_test boundary3-2.20.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='00000000ffffffff' + } +} {4294967295 14} +do_test boundary3-2.20.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=14 + } +} {4294967295 00000000ffffffff} +do_test boundary3-2.20.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 4294967295 ORDER BY t2.a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary3-2.20.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 4294967295 ORDER BY t1.a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary3-2.20.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=14 + ORDER BY t1.rowid + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.20.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=14 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary3-2.20.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=14 + ORDER BY x + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.20.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=14 + ORDER BY t1.rowid + } +} {36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.20.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=14 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36} +do_test boundary3-2.20.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 4294967295 ORDER BY t2.a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary3-2.20.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 4294967295 ORDER BY t1.a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary3-2.20.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=14 + ORDER BY t1.rowid + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.20.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=14 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary3-2.20.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=14 + ORDER BY x + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.20.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=14 + ORDER BY t1.rowid + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.20.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=14 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary3-2.20.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 4294967295 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.20.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 4294967295 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.20.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=14 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary3-2.20.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=14 + ORDER BY t1.rowid DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.20.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=14 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.20.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=14 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary3-2.20.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=14 + ORDER BY t1.rowid DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.20.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 4294967295 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.20.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 4294967295 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.20.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=14 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary3-2.20.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=14 + ORDER BY t1.rowid DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.20.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=14 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.20.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=14 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14} +do_test boundary3-2.20.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=14 + ORDER BY t1.rowid DESC + } +} {14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.21.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=1099511627775 AND t2.a=t1.a + } +} {57 000000ffffffffff} +do_test boundary3-2.21.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='000000ffffffffff' + } +} {1099511627775 57} +do_test boundary3-2.21.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=57 + } +} {1099511627775 000000ffffffffff} +do_test boundary3-2.21.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 1099511627775 ORDER BY t2.a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56} +do_test boundary3-2.21.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 1099511627775 ORDER BY t1.a DESC + } +} {56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary3-2.21.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=57 + ORDER BY t1.rowid + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.21.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=57 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary3-2.21.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=57 + ORDER BY x + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.21.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=57 + ORDER BY t1.rowid + } +} {19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.21.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=57 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19} +do_test boundary3-2.21.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 1099511627775 ORDER BY t2.a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57} +do_test boundary3-2.21.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 1099511627775 ORDER BY t1.a DESC + } +} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary3-2.21.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=57 + ORDER BY t1.rowid + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.21.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=57 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary3-2.21.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=57 + ORDER BY x + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.21.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=57 + ORDER BY t1.rowid + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.21.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=57 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary3-2.21.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 1099511627775 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.21.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 1099511627775 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.21.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=57 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary3-2.21.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=57 + ORDER BY t1.rowid DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.21.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=57 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.21.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=57 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary3-2.21.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=57 + ORDER BY t1.rowid DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.21.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 1099511627775 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary3-2.21.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 1099511627775 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.21.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=57 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary3-2.21.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=57 + ORDER BY t1.rowid DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.21.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=57 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.21.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=57 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57} +do_test boundary3-2.21.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=57 + ORDER BY t1.rowid DESC + } +} {57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.22.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-8388608 AND t2.a=t1.a + } +} {37 ffffffffff800000} +do_test boundary3-2.22.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffffffff800000' + } +} {-8388608 37} +do_test boundary3-2.22.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=37 + } +} {-8388608 ffffffffff800000} +do_test boundary3-2.22.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -8388608 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.22.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -8388608 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.22.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=37 + ORDER BY t1.rowid + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.22.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=37 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary3-2.22.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=37 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 29 32 54 53 52 33 38} +do_test boundary3-2.22.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=37 + ORDER BY t1.rowid + } +} {29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.22.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=37 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29} +do_test boundary3-2.22.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -8388608 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.22.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -8388608 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.22.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=37 + ORDER BY t1.rowid + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.22.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=37 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary3-2.22.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=37 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38} +do_test boundary3-2.22.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=37 + ORDER BY t1.rowid + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.22.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=37 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary3-2.22.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -8388608 ORDER BY t2.a + } +} {1 2 11 21 44 47 55 58 63 64} +do_test boundary3-2.22.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -8388608 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 21 11 2 1} +do_test boundary3-2.22.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=37 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary3-2.22.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=37 + ORDER BY t1.rowid DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.22.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=37 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary3-2.22.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=37 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary3-2.22.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=37 + ORDER BY t1.rowid DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.22.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -8388608 ORDER BY t2.a + } +} {1 2 11 21 37 44 47 55 58 63 64} +do_test boundary3-2.22.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -8388608 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 37 21 11 2 1} +do_test boundary3-2.22.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=37 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary3-2.22.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=37 + ORDER BY t1.rowid DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.22.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=37 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary3-2.22.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=37 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37} +do_test boundary3-2.22.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=37 + ORDER BY t1.rowid DESC + } +} {37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.23.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=549755813888 AND t2.a=t1.a + } +} {35 0000008000000000} +do_test boundary3-2.23.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000008000000000' + } +} {549755813888 35} +do_test boundary3-2.23.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=35 + } +} {549755813888 0000008000000000} +do_test boundary3-2.23.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 549755813888 ORDER BY t2.a + } +} {3 7 10 13 17 19 25 26 27 28 34 43 45 56 57} +do_test boundary3-2.23.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 549755813888 ORDER BY t1.a DESC + } +} {57 56 45 43 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary3-2.23.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=35 + ORDER BY t1.rowid + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.23.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=35 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary3-2.23.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=35 + ORDER BY x + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.23.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=35 + ORDER BY t1.rowid + } +} {57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.23.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=35 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57} +do_test boundary3-2.23.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 549755813888 ORDER BY t2.a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57} +do_test boundary3-2.23.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 549755813888 ORDER BY t1.a DESC + } +} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary3-2.23.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=35 + ORDER BY t1.rowid + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.23.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=35 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary3-2.23.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=35 + ORDER BY x + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.23.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=35 + ORDER BY t1.rowid + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.23.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=35 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary3-2.23.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 549755813888 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.23.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 549755813888 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.23.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=35 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary3-2.23.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=35 + ORDER BY t1.rowid DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.23.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=35 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.23.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=35 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary3-2.23.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=35 + ORDER BY t1.rowid DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.23.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 549755813888 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.23.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 549755813888 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.23.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=35 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary3-2.23.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=35 + ORDER BY t1.rowid DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.23.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=35 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.23.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=35 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35} +do_test boundary3-2.23.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=35 + ORDER BY t1.rowid DESC + } +} {35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.24.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=8388607 AND t2.a=t1.a + } +} {18 00000000007fffff} +do_test boundary3-2.24.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='00000000007fffff' + } +} {8388607 18} +do_test boundary3-2.24.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=18 + } +} {8388607 00000000007fffff} +do_test boundary3-2.24.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 8388607 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.24.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 8388607 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary3-2.24.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=18 + ORDER BY t1.rowid + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.24.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=18 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary3-2.24.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=18 + ORDER BY x + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.24.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=18 + ORDER BY t1.rowid + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.24.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=18 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary3-2.24.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 8388607 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.24.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 8388607 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary3-2.24.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=18 + ORDER BY t1.rowid + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.24.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=18 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary3-2.24.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=18 + ORDER BY x + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.24.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=18 + ORDER BY t1.rowid + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.24.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=18 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary3-2.24.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 8388607 ORDER BY t2.a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.24.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 8388607 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary3-2.24.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=18 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary3-2.24.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=18 + ORDER BY t1.rowid DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.24.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=18 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.24.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=18 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary3-2.24.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=18 + ORDER BY t1.rowid DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.24.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 8388607 ORDER BY t2.a + } +} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.24.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 8388607 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary3-2.24.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=18 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary3-2.24.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=18 + ORDER BY t1.rowid DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.24.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=18 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.24.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=18 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary3-2.24.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=18 + ORDER BY t1.rowid DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.25.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-3 AND t2.a=t1.a + } +} {52 fffffffffffffffd} +do_test boundary3-2.25.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='fffffffffffffffd' + } +} {-3 52} +do_test boundary3-2.25.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=52 + } +} {-3 fffffffffffffffd} +do_test boundary3-2.25.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -3 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary3-2.25.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -3 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.25.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=52 + ORDER BY t1.rowid + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.25.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=52 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary3-2.25.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=52 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38} +do_test boundary3-2.25.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=52 + ORDER BY t1.rowid + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.25.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=52 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary3-2.25.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -3 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62} +do_test boundary3-2.25.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -3 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.25.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=52 + ORDER BY t1.rowid + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.25.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=52 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary3-2.25.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=52 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38} +do_test boundary3-2.25.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=52 + ORDER BY t1.rowid + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.25.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=52 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary3-2.25.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -3 ORDER BY t2.a + } +} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64} +do_test boundary3-2.25.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -3 ORDER BY t1.a DESC + } +} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1} +do_test boundary3-2.25.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=52 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary3-2.25.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=52 + ORDER BY t1.rowid DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.25.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=52 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary3-2.25.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=52 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary3-2.25.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=52 + ORDER BY t1.rowid DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.25.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -3 ORDER BY t2.a + } +} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64} +do_test boundary3-2.25.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -3 ORDER BY t1.a DESC + } +} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1} +do_test boundary3-2.25.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=52 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary3-2.25.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=52 + ORDER BY t1.rowid DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.25.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=52 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary3-2.25.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=52 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary3-2.25.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=52 + ORDER BY t1.rowid DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.26.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=0 AND t2.a=t1.a + } +} {59 0000000000000000} +do_test boundary3-2.26.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000000000' + } +} {0 59} +do_test boundary3-2.26.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=59 + } +} {0 0000000000000000} +do_test boundary3-2.26.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 0 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62} +do_test boundary3-2.26.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 0 ORDER BY t1.a DESC + } +} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.26.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=59 + ORDER BY t1.rowid + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.26.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=59 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary3-2.26.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=59 + ORDER BY x + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.26.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=59 + ORDER BY t1.rowid + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.26.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=59 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary3-2.26.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 0 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary3-2.26.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 0 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.26.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=59 + ORDER BY t1.rowid + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.26.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=59 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary3-2.26.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=59 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.26.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=59 + ORDER BY t1.rowid + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.26.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=59 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary3-2.26.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 0 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64} +do_test boundary3-2.26.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 0 ORDER BY t1.a DESC + } +} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary3-2.26.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=59 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.26.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=59 + ORDER BY t1.rowid DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.26.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=59 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.26.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=59 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.26.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=59 + ORDER BY t1.rowid DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.26.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 0 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64} +do_test boundary3-2.26.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 0 ORDER BY t1.a DESC + } +} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary3-2.26.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=59 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary3-2.26.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=59 + ORDER BY t1.rowid DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.26.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=59 + ORDER BY x + } +} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.26.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=59 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary3-2.26.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=59 + ORDER BY t1.rowid DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.27.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-1 AND t2.a=t1.a + } +} {38 ffffffffffffffff} +do_test boundary3-2.27.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffffffffffffff' + } +} {-1 38} +do_test boundary3-2.27.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=38 + } +} {-1 ffffffffffffffff} +do_test boundary3-2.27.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -1 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary3-2.27.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -1 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.27.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=38 + ORDER BY t1.rowid + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.27.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=38 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary3-2.27.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=38 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.27.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=38 + ORDER BY t1.rowid + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.27.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=38 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59} +do_test boundary3-2.27.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -1 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary3-2.27.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -1 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.27.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=38 + ORDER BY t1.rowid + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.27.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=38 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary3-2.27.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=38 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38} +do_test boundary3-2.27.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=38 + ORDER BY t1.rowid + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.27.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=38 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary3-2.27.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -1 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64} +do_test boundary3-2.27.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -1 ORDER BY t1.a DESC + } +} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1} +do_test boundary3-2.27.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=38 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary3-2.27.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=38 + ORDER BY t1.rowid DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.27.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=38 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary3-2.27.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=38 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary3-2.27.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=38 + ORDER BY t1.rowid DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.27.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -1 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 63 64} +do_test boundary3-2.27.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -1 ORDER BY t1.a DESC + } +} {64 63 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary3-2.27.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=38 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.27.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=38 + ORDER BY t1.rowid DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.27.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=38 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.27.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=38 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.27.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=38 + ORDER BY t1.rowid DESC + } +} {38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.28.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-2 AND t2.a=t1.a + } +} {33 fffffffffffffffe} +do_test boundary3-2.28.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='fffffffffffffffe' + } +} {-2 33} +do_test boundary3-2.28.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=33 + } +} {-2 fffffffffffffffe} +do_test boundary3-2.28.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -2 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary3-2.28.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -2 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.28.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=33 + ORDER BY t1.rowid + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.28.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=33 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary3-2.28.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=33 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 38} +do_test boundary3-2.28.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=33 + ORDER BY t1.rowid + } +} {38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.28.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=33 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38} +do_test boundary3-2.28.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -2 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 56 57 59 60 61 62} +do_test boundary3-2.28.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -2 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.28.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=33 + ORDER BY t1.rowid + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.28.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=33 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary3-2.28.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=33 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 33 38} +do_test boundary3-2.28.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=33 + ORDER BY t1.rowid + } +} {33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.28.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=33 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33} +do_test boundary3-2.28.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -2 ORDER BY t2.a + } +} {1 2 11 21 29 32 37 44 47 52 53 54 55 58 63 64} +do_test boundary3-2.28.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -2 ORDER BY t1.a DESC + } +} {64 63 58 55 54 53 52 47 44 37 32 29 21 11 2 1} +do_test boundary3-2.28.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=33 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary3-2.28.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=33 + ORDER BY t1.rowid DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.28.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=33 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary3-2.28.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=33 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52} +do_test boundary3-2.28.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=33 + ORDER BY t1.rowid DESC + } +} {52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.28.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -2 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 44 47 52 53 54 55 58 63 64} +do_test boundary3-2.28.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -2 ORDER BY t1.a DESC + } +} {64 63 58 55 54 53 52 47 44 37 33 32 29 21 11 2 1} +do_test boundary3-2.28.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=33 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary3-2.28.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=33 + ORDER BY t1.rowid DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.28.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=33 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary3-2.28.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=33 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33} +do_test boundary3-2.28.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=33 + ORDER BY t1.rowid DESC + } +} {33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.29.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=2097152 AND t2.a=t1.a + } +} {42 0000000000200000} +do_test boundary3-2.29.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000200000' + } +} {2097152 42} +do_test boundary3-2.29.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=42 + } +} {2097152 0000000000200000} +do_test boundary3-2.29.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 2097152 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.29.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 2097152 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary3-2.29.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=42 + ORDER BY t1.rowid + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.29.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=42 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary3-2.29.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=42 + ORDER BY x + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.29.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=42 + ORDER BY t1.rowid + } +} {18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.29.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=42 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18} +do_test boundary3-2.29.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 2097152 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary3-2.29.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 2097152 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary3-2.29.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=42 + ORDER BY t1.rowid + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.29.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=42 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary3-2.29.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=42 + ORDER BY x + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.29.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=42 + ORDER BY t1.rowid + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.29.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=42 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary3-2.29.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 2097152 ORDER BY t2.a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.29.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 2097152 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary3-2.29.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=42 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary3-2.29.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=42 + ORDER BY t1.rowid DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.29.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=42 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.29.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=42 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary3-2.29.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=42 + ORDER BY t1.rowid DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.29.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 2097152 ORDER BY t2.a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.29.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 2097152 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary3-2.29.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=42 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary3-2.29.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=42 + ORDER BY t1.rowid DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.29.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=42 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.29.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=42 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42} +do_test boundary3-2.29.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=42 + ORDER BY t1.rowid DESC + } +} {42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.30.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=128 AND t2.a=t1.a + } +} {49 0000000000000080} +do_test boundary3-2.30.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000000080' + } +} {128 49} +do_test boundary3-2.30.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=49 + } +} {128 0000000000000080} +do_test boundary3-2.30.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 128 ORDER BY t2.a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary3-2.30.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 128 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary3-2.30.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=49 + ORDER BY t1.rowid + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.30.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=49 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary3-2.30.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=49 + ORDER BY x + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.30.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=49 + ORDER BY t1.rowid + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.30.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=49 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary3-2.30.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 128 ORDER BY t2.a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.30.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 128 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary3-2.30.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=49 + ORDER BY t1.rowid + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.30.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=49 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary3-2.30.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=49 + ORDER BY x + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.30.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=49 + ORDER BY t1.rowid + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.30.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=49 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary3-2.30.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 128 ORDER BY t2.a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.30.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 128 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary3-2.30.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=49 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary3-2.30.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=49 + ORDER BY t1.rowid DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.30.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=49 + ORDER BY x + } +} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.30.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=49 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary3-2.30.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=49 + ORDER BY t1.rowid DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.30.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 128 ORDER BY t2.a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.30.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 128 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary3-2.30.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=49 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary3-2.30.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=49 + ORDER BY t1.rowid DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.30.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=49 + ORDER BY x + } +} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.30.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=49 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary3-2.30.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=49 + ORDER BY t1.rowid DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.31.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=255 AND t2.a=t1.a + } +} {30 00000000000000ff} +do_test boundary3-2.31.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='00000000000000ff' + } +} {255 30} +do_test boundary3-2.31.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=30 + } +} {255 00000000000000ff} +do_test boundary3-2.31.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 255 ORDER BY t2.a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary3-2.31.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 255 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary3-2.31.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=30 + ORDER BY t1.rowid + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.31.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=30 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary3-2.31.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=30 + ORDER BY x + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.31.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=30 + ORDER BY t1.rowid + } +} {61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.31.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=30 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61} +do_test boundary3-2.31.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 255 ORDER BY t2.a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 50 51 56 57 61 62} +do_test boundary3-2.31.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 255 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary3-2.31.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=30 + ORDER BY t1.rowid + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.31.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=30 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary3-2.31.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=30 + ORDER BY x + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.31.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=30 + ORDER BY t1.rowid + } +} {30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.31.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=30 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30} +do_test boundary3-2.31.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 255 ORDER BY t2.a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.31.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 255 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary3-2.31.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=30 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary3-2.31.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=30 + ORDER BY t1.rowid DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.31.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=30 + ORDER BY x + } +} {59 60 41 5 31 4 49 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.31.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=30 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49} +do_test boundary3-2.31.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=30 + ORDER BY t1.rowid DESC + } +} {49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.31.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 255 ORDER BY t2.a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.31.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 255 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary3-2.31.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=30 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary3-2.31.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=30 + ORDER BY t1.rowid DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.31.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=30 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.31.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=30 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30} +do_test boundary3-2.31.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=30 + ORDER BY t1.rowid DESC + } +} {30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.32.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-2147483648 AND t2.a=t1.a + } +} {11 ffffffff80000000} +do_test boundary3-2.32.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffffff80000000' + } +} {-2147483648 11} +do_test boundary3-2.32.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=11 + } +} {-2147483648 ffffffff80000000} +do_test boundary3-2.32.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -2147483648 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.32.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -2147483648 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.32.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=11 + ORDER BY t1.rowid + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.32.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=11 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary3-2.32.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=11 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.32.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=11 + ORDER BY t1.rowid + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.32.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=11 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary3-2.32.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -2147483648 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.32.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -2147483648 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.32.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=11 + ORDER BY t1.rowid + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.32.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=11 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary3-2.32.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=11 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.32.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=11 + ORDER BY t1.rowid + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.32.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=11 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary3-2.32.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -2147483648 ORDER BY t2.a + } +} {2 21 44 47 55 58 63 64} +do_test boundary3-2.32.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -2147483648 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 21 2} +do_test boundary3-2.32.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=11 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47} +do_test boundary3-2.32.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=11 + ORDER BY t1.rowid DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary3-2.32.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=11 + ORDER BY x + } +} {55 2 64 21 44 58 63 47} +do_test boundary3-2.32.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=11 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47} +do_test boundary3-2.32.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=11 + ORDER BY t1.rowid DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary3-2.32.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -2147483648 ORDER BY t2.a + } +} {2 11 21 44 47 55 58 63 64} +do_test boundary3-2.32.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -2147483648 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 21 11 2} +do_test boundary3-2.32.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=11 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary3-2.32.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=11 + ORDER BY t1.rowid DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary3-2.32.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=11 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary3-2.32.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=11 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary3-2.32.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=11 + ORDER BY t1.rowid DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary3-2.33.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=34359738367 AND t2.a=t1.a + } +} {39 00000007ffffffff} +do_test boundary3-2.33.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='00000007ffffffff' + } +} {34359738367 39} +do_test boundary3-2.33.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=39 + } +} {34359738367 00000007ffffffff} +do_test boundary3-2.33.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 34359738367 ORDER BY t2.a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary3-2.33.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 34359738367 ORDER BY t1.a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary3-2.33.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=39 + ORDER BY t1.rowid + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.33.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=39 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary3-2.33.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=39 + ORDER BY x + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.33.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=39 + ORDER BY t1.rowid + } +} {22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.33.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=39 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22} +do_test boundary3-2.33.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 34359738367 ORDER BY t2.a + } +} {3 7 10 13 17 19 22 25 26 27 28 34 35 39 43 45 46 56 57} +do_test boundary3-2.33.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 34359738367 ORDER BY t1.a DESC + } +} {57 56 46 45 43 39 35 34 28 27 26 25 22 19 17 13 10 7 3} +do_test boundary3-2.33.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=39 + ORDER BY t1.rowid + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.33.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=39 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary3-2.33.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=39 + ORDER BY x + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.33.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=39 + ORDER BY t1.rowid + } +} {39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.33.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=39 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39} +do_test boundary3-2.33.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 34359738367 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.33.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 34359738367 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.33.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=39 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary3-2.33.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=39 + ORDER BY t1.rowid DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.33.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=39 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.33.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=39 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36} +do_test boundary3-2.33.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=39 + ORDER BY t1.rowid DESC + } +} {36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.33.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 34359738367 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.33.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 34359738367 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.33.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=39 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary3-2.33.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=39 + ORDER BY t1.rowid DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.33.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=39 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.33.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=39 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39} +do_test boundary3-2.33.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=39 + ORDER BY t1.rowid DESC + } +} {39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.34.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-549755813889 AND t2.a=t1.a + } +} {58 ffffff7fffffffff} +do_test boundary3-2.34.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffff7fffffffff' + } +} {-549755813889 58} +do_test boundary3-2.34.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=58 + } +} {-549755813889 ffffff7fffffffff} +do_test boundary3-2.34.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -549755813889 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63} +do_test boundary3-2.34.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -549755813889 ORDER BY t1.a DESC + } +} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.34.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=58 + ORDER BY t1.rowid + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.34.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=58 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary3-2.34.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=58 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.34.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=58 + ORDER BY t1.rowid + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.34.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=58 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary3-2.34.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -549755813889 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63} +do_test boundary3-2.34.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -549755813889 ORDER BY t1.a DESC + } +} {63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.34.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=58 + ORDER BY t1.rowid + } +} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.34.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=58 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58} +do_test boundary3-2.34.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=58 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.34.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=58 + ORDER BY t1.rowid + } +} {58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.34.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=58 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58} +do_test boundary3-2.34.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -549755813889 ORDER BY t2.a + } +} {2 21 44 55 64} +do_test boundary3-2.34.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -549755813889 ORDER BY t1.a DESC + } +} {64 55 44 21 2} +do_test boundary3-2.34.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=58 + ORDER BY t1.rowid + } +} {55 2 64 21 44} +do_test boundary3-2.34.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=58 + ORDER BY t1.rowid DESC + } +} {44 21 64 2 55} +do_test boundary3-2.34.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=58 + ORDER BY x + } +} {55 2 64 21 44} +do_test boundary3-2.34.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=58 + ORDER BY t1.rowid + } +} {55 2 64 21 44} +do_test boundary3-2.34.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=58 + ORDER BY t1.rowid DESC + } +} {44 21 64 2 55} +do_test boundary3-2.34.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -549755813889 ORDER BY t2.a + } +} {2 21 44 55 58 64} +do_test boundary3-2.34.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -549755813889 ORDER BY t1.a DESC + } +} {64 58 55 44 21 2} +do_test boundary3-2.34.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=58 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58} +do_test boundary3-2.34.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=58 + ORDER BY t1.rowid DESC + } +} {58 44 21 64 2 55} +do_test boundary3-2.34.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=58 + ORDER BY x + } +} {55 2 64 21 44 58} +do_test boundary3-2.34.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=58 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58} +do_test boundary3-2.34.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=58 + ORDER BY t1.rowid DESC + } +} {58 44 21 64 2 55} +do_test boundary3-2.35.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-32768 AND t2.a=t1.a + } +} {32 ffffffffffff8000} +do_test boundary3-2.35.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffffffffff8000' + } +} {-32768 32} +do_test boundary3-2.35.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=32 + } +} {-32768 ffffffffffff8000} +do_test boundary3-2.35.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -32768 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.35.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -32768 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.35.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=32 + ORDER BY t1.rowid + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.35.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=32 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary3-2.35.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=32 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38} +do_test boundary3-2.35.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=32 + ORDER BY t1.rowid + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.35.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=32 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary3-2.35.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -32768 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 32 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.35.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -32768 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 32 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.35.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=32 + ORDER BY t1.rowid + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.35.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=32 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary3-2.35.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=32 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 32 54 53 52 33 38} +do_test boundary3-2.35.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=32 + ORDER BY t1.rowid + } +} {32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.35.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=32 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32} +do_test boundary3-2.35.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -32768 ORDER BY t2.a + } +} {1 2 11 21 29 37 44 47 55 58 63 64} +do_test boundary3-2.35.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -32768 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 37 29 21 11 2 1} +do_test boundary3-2.35.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=32 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary3-2.35.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=32 + ORDER BY t1.rowid DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.35.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=32 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary3-2.35.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=32 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29} +do_test boundary3-2.35.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=32 + ORDER BY t1.rowid DESC + } +} {29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.35.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -32768 ORDER BY t2.a + } +} {1 2 11 21 29 32 37 44 47 55 58 63 64} +do_test boundary3-2.35.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -32768 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 37 32 29 21 11 2 1} +do_test boundary3-2.35.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=32 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary3-2.35.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=32 + ORDER BY t1.rowid DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.35.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=32 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary3-2.35.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=32 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary3-2.35.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=32 + ORDER BY t1.rowid DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.36.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=2147483647 AND t2.a=t1.a + } +} {20 000000007fffffff} +do_test boundary3-2.36.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='000000007fffffff' + } +} {2147483647 20} +do_test boundary3-2.36.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=20 + } +} {2147483647 000000007fffffff} +do_test boundary3-2.36.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 2147483647 ORDER BY t2.a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary3-2.36.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 2147483647 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary3-2.36.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=20 + ORDER BY t1.rowid + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.36.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=20 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary3-2.36.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=20 + ORDER BY x + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.36.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=20 + ORDER BY t1.rowid + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.36.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=20 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary3-2.36.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 2147483647 ORDER BY t2.a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary3-2.36.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 2147483647 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary3-2.36.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=20 + ORDER BY t1.rowid + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.36.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=20 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary3-2.36.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=20 + ORDER BY x + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.36.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=20 + ORDER BY t1.rowid + } +} {20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.36.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=20 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20} +do_test boundary3-2.36.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 2147483647 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.36.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 2147483647 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.36.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=20 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary3-2.36.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=20 + ORDER BY t1.rowid DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.36.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=20 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.36.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=20 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40} +do_test boundary3-2.36.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=20 + ORDER BY t1.rowid DESC + } +} {40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.36.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 2147483647 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.36.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 2147483647 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.36.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=20 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary3-2.36.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=20 + ORDER BY t1.rowid DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.36.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=20 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.36.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=20 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary3-2.36.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=20 + ORDER BY t1.rowid DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.37.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-129 AND t2.a=t1.a + } +} {54 ffffffffffffff7f} +do_test boundary3-2.37.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffffffffffff7f' + } +} {-129 54} +do_test boundary3-2.37.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=54 + } +} {-129 ffffffffffffff7f} +do_test boundary3-2.37.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -129 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62} +do_test boundary3-2.37.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -129 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.37.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=54 + ORDER BY t1.rowid + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.37.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=54 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary3-2.37.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=54 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38} +do_test boundary3-2.37.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=54 + ORDER BY t1.rowid + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.37.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=54 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary3-2.37.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -129 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.37.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -129 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.37.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=54 + ORDER BY t1.rowid + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.37.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=54 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary3-2.37.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=54 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 54 53 52 33 38} +do_test boundary3-2.37.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=54 + ORDER BY t1.rowid + } +} {54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.37.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=54 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54} +do_test boundary3-2.37.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -129 ORDER BY t2.a + } +} {1 2 11 21 29 32 37 44 47 55 58 63 64} +do_test boundary3-2.37.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -129 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 37 32 29 21 11 2 1} +do_test boundary3-2.37.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=54 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary3-2.37.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=54 + ORDER BY t1.rowid DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.37.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=54 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary3-2.37.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=54 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32} +do_test boundary3-2.37.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=54 + ORDER BY t1.rowid DESC + } +} {32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.37.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -129 ORDER BY t2.a + } +} {1 2 11 21 29 32 37 44 47 54 55 58 63 64} +do_test boundary3-2.37.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -129 ORDER BY t1.a DESC + } +} {64 63 58 55 54 47 44 37 32 29 21 11 2 1} +do_test boundary3-2.37.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=54 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary3-2.37.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=54 + ORDER BY t1.rowid DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.37.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=54 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary3-2.37.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=54 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary3-2.37.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=54 + ORDER BY t1.rowid DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.38.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-128 AND t2.a=t1.a + } +} {53 ffffffffffffff80} +do_test boundary3-2.38.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffffffffffff80' + } +} {-128 53} +do_test boundary3-2.38.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=53 + } +} {-128 ffffffffffffff80} +do_test boundary3-2.38.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -128 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 56 57 59 60 61 62} +do_test boundary3-2.38.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -128 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.38.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=53 + ORDER BY t1.rowid + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.38.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=53 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary3-2.38.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=53 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 52 33 38} +do_test boundary3-2.38.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=53 + ORDER BY t1.rowid + } +} {52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.38.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=53 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52} +do_test boundary3-2.38.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -128 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 33 34 35 36 38 39 40 41 42 43 45 46 48 49 50 51 52 53 56 57 59 60 61 62} +do_test boundary3-2.38.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -128 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 53 52 51 50 49 48 46 45 43 42 41 40 39 38 36 35 34 33 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.38.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=53 + ORDER BY t1.rowid + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.38.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=53 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary3-2.38.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=53 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 53 52 33 38} +do_test boundary3-2.38.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=53 + ORDER BY t1.rowid + } +} {53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.38.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=53 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53} +do_test boundary3-2.38.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -128 ORDER BY t2.a + } +} {1 2 11 21 29 32 37 44 47 54 55 58 63 64} +do_test boundary3-2.38.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -128 ORDER BY t1.a DESC + } +} {64 63 58 55 54 47 44 37 32 29 21 11 2 1} +do_test boundary3-2.38.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=53 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary3-2.38.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=53 + ORDER BY t1.rowid DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.38.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=53 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary3-2.38.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=53 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54} +do_test boundary3-2.38.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=53 + ORDER BY t1.rowid DESC + } +} {54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.38.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -128 ORDER BY t2.a + } +} {1 2 11 21 29 32 37 44 47 53 54 55 58 63 64} +do_test boundary3-2.38.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -128 ORDER BY t1.a DESC + } +} {64 63 58 55 54 53 47 44 37 32 29 21 11 2 1} +do_test boundary3-2.38.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=53 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary3-2.38.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=53 + ORDER BY t1.rowid DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.38.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=53 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary3-2.38.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=53 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53} +do_test boundary3-2.38.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=53 + ORDER BY t1.rowid DESC + } +} {53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.39.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=72057594037927936 AND t2.a=t1.a + } +} {28 0100000000000000} +do_test boundary3-2.39.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0100000000000000' + } +} {72057594037927936 28} +do_test boundary3-2.39.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=28 + } +} {72057594037927936 0100000000000000} +do_test boundary3-2.39.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 72057594037927936 ORDER BY t2.a + } +} {3} +do_test boundary3-2.39.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 72057594037927936 ORDER BY t1.a DESC + } +} {3} +do_test boundary3-2.39.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=28 + ORDER BY t1.rowid + } +} {3} +do_test boundary3-2.39.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=28 + ORDER BY t1.rowid DESC + } +} {3} +do_test boundary3-2.39.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=28 + ORDER BY x + } +} {3} +do_test boundary3-2.39.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 72057594037927936 ORDER BY t2.a + } +} {3 28} +do_test boundary3-2.39.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 72057594037927936 ORDER BY t1.a DESC + } +} {28 3} +do_test boundary3-2.39.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=28 + ORDER BY t1.rowid + } +} {28 3} +do_test boundary3-2.39.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=28 + ORDER BY t1.rowid DESC + } +} {3 28} +do_test boundary3-2.39.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=28 + ORDER BY x + } +} {28 3} +do_test boundary3-2.39.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 72057594037927936 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.39.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 72057594037927936 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.39.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=28 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17} +do_test boundary3-2.39.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=28 + ORDER BY t1.rowid DESC + } +} {17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.39.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=28 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.39.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 72057594037927936 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.39.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 72057594037927936 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.39.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=28 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28} +do_test boundary3-2.39.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=28 + ORDER BY t1.rowid DESC + } +} {28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.39.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=28 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.40.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=2147483648 AND t2.a=t1.a + } +} {51 0000000080000000} +do_test boundary3-2.40.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000080000000' + } +} {2147483648 51} +do_test boundary3-2.40.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=51 + } +} {2147483648 0000000080000000} +do_test boundary3-2.40.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 2147483648 ORDER BY t2.a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 56 57} +do_test boundary3-2.40.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 2147483648 ORDER BY t1.a DESC + } +} {57 56 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary3-2.40.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=51 + ORDER BY t1.rowid + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.40.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=51 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary3-2.40.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=51 + ORDER BY x + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.40.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=51 + ORDER BY t1.rowid + } +} {14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.40.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=51 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14} +do_test boundary3-2.40.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 2147483648 ORDER BY t2.a + } +} {3 7 10 13 14 17 19 22 25 26 27 28 34 35 36 39 43 45 46 51 56 57} +do_test boundary3-2.40.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 2147483648 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 39 36 35 34 28 27 26 25 22 19 17 14 13 10 7 3} +do_test boundary3-2.40.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=51 + ORDER BY t1.rowid + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.40.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=51 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary3-2.40.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=51 + ORDER BY x + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.40.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=51 + ORDER BY t1.rowid + } +} {51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.40.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=51 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51} +do_test boundary3-2.40.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 2147483648 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.40.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 2147483648 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.40.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=51 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary3-2.40.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=51 + ORDER BY t1.rowid DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.40.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=51 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.40.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=51 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20} +do_test boundary3-2.40.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=51 + ORDER BY t1.rowid DESC + } +} {20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.40.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 2147483648 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 20 21 23 24 29 30 31 32 33 37 38 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.40.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 2147483648 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 38 37 33 32 31 30 29 24 23 21 20 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.40.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=51 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary3-2.40.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=51 + ORDER BY t1.rowid DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.40.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=51 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.40.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=51 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51} +do_test boundary3-2.40.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=51 + ORDER BY t1.rowid DESC + } +} {51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.41.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=549755813887 AND t2.a=t1.a + } +} {46 0000007fffffffff} +do_test boundary3-2.41.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000007fffffffff' + } +} {549755813887 46} +do_test boundary3-2.41.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=46 + } +} {549755813887 0000007fffffffff} +do_test boundary3-2.41.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 549755813887 ORDER BY t2.a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 56 57} +do_test boundary3-2.41.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 549755813887 ORDER BY t1.a DESC + } +} {57 56 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary3-2.41.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=46 + ORDER BY t1.rowid + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.41.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=46 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary3-2.41.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=46 + ORDER BY x + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.41.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=46 + ORDER BY t1.rowid + } +} {35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.41.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=46 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35} +do_test boundary3-2.41.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 549755813887 ORDER BY t2.a + } +} {3 7 10 13 17 19 25 26 27 28 34 35 43 45 46 56 57} +do_test boundary3-2.41.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 549755813887 ORDER BY t1.a DESC + } +} {57 56 46 45 43 35 34 28 27 26 25 19 17 13 10 7 3} +do_test boundary3-2.41.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=46 + ORDER BY t1.rowid + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.41.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=46 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary3-2.41.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=46 + ORDER BY x + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.41.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=46 + ORDER BY t1.rowid + } +} {46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.41.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=46 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46} +do_test boundary3-2.41.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 549755813887 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.41.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 549755813887 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.41.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=46 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary3-2.41.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=46 + ORDER BY t1.rowid DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.41.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=46 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.41.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=46 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22} +do_test boundary3-2.41.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=46 + ORDER BY t1.rowid DESC + } +} {22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.41.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 549755813887 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 20 21 22 23 24 29 30 31 32 33 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.41.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 549755813887 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 33 32 31 30 29 24 23 22 21 20 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.41.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=46 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary3-2.41.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=46 + ORDER BY t1.rowid DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.41.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=46 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.41.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=46 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46} +do_test boundary3-2.41.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=46 + ORDER BY t1.rowid DESC + } +} {46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.42.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-549755813888 AND t2.a=t1.a + } +} {63 ffffff8000000000} +do_test boundary3-2.42.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffff8000000000' + } +} {-549755813888 63} +do_test boundary3-2.42.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=63 + } +} {-549755813888 ffffff8000000000} +do_test boundary3-2.42.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -549755813888 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.42.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -549755813888 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.42.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=63 + ORDER BY t1.rowid + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.42.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=63 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary3-2.42.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=63 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.42.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=63 + ORDER BY t1.rowid + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.42.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=63 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary3-2.42.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -549755813888 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62 63} +do_test boundary3-2.42.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -549755813888 ORDER BY t1.a DESC + } +} {63 62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.42.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=63 + ORDER BY t1.rowid + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.42.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=63 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary3-2.42.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=63 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.42.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=63 + ORDER BY t1.rowid + } +} {63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.42.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=63 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63} +do_test boundary3-2.42.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -549755813888 ORDER BY t2.a + } +} {2 21 44 55 58 64} +do_test boundary3-2.42.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -549755813888 ORDER BY t1.a DESC + } +} {64 58 55 44 21 2} +do_test boundary3-2.42.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=63 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58} +do_test boundary3-2.42.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=63 + ORDER BY t1.rowid DESC + } +} {58 44 21 64 2 55} +do_test boundary3-2.42.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=63 + ORDER BY x + } +} {55 2 64 21 44 58} +do_test boundary3-2.42.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=63 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58} +do_test boundary3-2.42.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=63 + ORDER BY t1.rowid DESC + } +} {58 44 21 64 2 55} +do_test boundary3-2.42.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -549755813888 ORDER BY t2.a + } +} {2 21 44 55 58 63 64} +do_test boundary3-2.42.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -549755813888 ORDER BY t1.a DESC + } +} {64 63 58 55 44 21 2} +do_test boundary3-2.42.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=63 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63} +do_test boundary3-2.42.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=63 + ORDER BY t1.rowid DESC + } +} {63 58 44 21 64 2 55} +do_test boundary3-2.42.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=63 + ORDER BY x + } +} {55 2 64 21 44 58 63} +do_test boundary3-2.42.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=63 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63} +do_test boundary3-2.42.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=63 + ORDER BY t1.rowid DESC + } +} {63 58 44 21 64 2 55} +do_test boundary3-2.43.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=281474976710655 AND t2.a=t1.a + } +} {10 0000ffffffffffff} +do_test boundary3-2.43.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000ffffffffffff' + } +} {281474976710655 10} +do_test boundary3-2.43.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=10 + } +} {281474976710655 0000ffffffffffff} +do_test boundary3-2.43.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 281474976710655 ORDER BY t2.a + } +} {3 13 17 26 27 28 43 45} +do_test boundary3-2.43.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 281474976710655 ORDER BY t1.a DESC + } +} {45 43 28 27 26 17 13 3} +do_test boundary3-2.43.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=10 + ORDER BY t1.rowid + } +} {26 13 43 27 45 17 28 3} +do_test boundary3-2.43.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=10 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26} +do_test boundary3-2.43.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=10 + ORDER BY x + } +} {26 13 43 27 45 17 28 3} +do_test boundary3-2.43.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 281474976710655 ORDER BY t2.a + } +} {3 10 13 17 26 27 28 43 45} +do_test boundary3-2.43.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 281474976710655 ORDER BY t1.a DESC + } +} {45 43 28 27 26 17 13 10 3} +do_test boundary3-2.43.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=10 + ORDER BY t1.rowid + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary3-2.43.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=10 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10} +do_test boundary3-2.43.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=10 + ORDER BY x + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary3-2.43.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 281474976710655 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.43.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 281474976710655 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary3-2.43.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=10 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34} +do_test boundary3-2.43.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=10 + ORDER BY t1.rowid DESC + } +} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.43.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=10 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.43.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 281474976710655 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.43.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 281474976710655 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.43.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=10 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10} +do_test boundary3-2.43.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=10 + ORDER BY t1.rowid DESC + } +} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.43.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=10 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.44.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=4398046511103 AND t2.a=t1.a + } +} {7 000003ffffffffff} +do_test boundary3-2.44.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='000003ffffffffff' + } +} {4398046511103 7} +do_test boundary3-2.44.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=7 + } +} {4398046511103 000003ffffffffff} +do_test boundary3-2.44.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 4398046511103 ORDER BY t2.a + } +} {3 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary3-2.44.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 4398046511103 ORDER BY t1.a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 3} +do_test boundary3-2.44.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=7 + ORDER BY t1.rowid + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.44.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=7 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary3-2.44.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=7 + ORDER BY x + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.44.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=7 + ORDER BY t1.rowid + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.44.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=7 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary3-2.44.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 4398046511103 ORDER BY t2.a + } +} {3 7 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary3-2.44.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 4398046511103 ORDER BY t1.a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 7 3} +do_test boundary3-2.44.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=7 + ORDER BY t1.rowid + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.44.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=7 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary3-2.44.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=7 + ORDER BY x + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.44.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=7 + ORDER BY t1.rowid + } +} {7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.44.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=7 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7} +do_test boundary3-2.44.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 4398046511103 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary3-2.44.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 4398046511103 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.44.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=7 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary3-2.44.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=7 + ORDER BY t1.rowid DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.44.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=7 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.44.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=7 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19} +do_test boundary3-2.44.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=7 + ORDER BY t1.rowid DESC + } +} {19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.44.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 4398046511103 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary3-2.44.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 4398046511103 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary3-2.44.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=7 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary3-2.44.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=7 + ORDER BY t1.rowid DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.44.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=7 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.44.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=7 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary3-2.44.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=7 + ORDER BY t1.rowid DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.45.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=268435455 AND t2.a=t1.a + } +} {12 000000000fffffff} +do_test boundary3-2.45.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='000000000fffffff' + } +} {268435455 12} +do_test boundary3-2.45.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=12 + } +} {268435455 000000000fffffff} +do_test boundary3-2.45.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 268435455 ORDER BY t2.a + } +} {3 7 10 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.45.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 268435455 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 10 7 3} +do_test boundary3-2.45.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=12 + ORDER BY t1.rowid + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.45.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=12 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary3-2.45.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=12 + ORDER BY x + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.45.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=12 + ORDER BY t1.rowid + } +} {40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.45.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=12 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40} +do_test boundary3-2.45.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 268435455 ORDER BY t2.a + } +} {3 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.45.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 268435455 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 3} +do_test boundary3-2.45.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=12 + ORDER BY t1.rowid + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.45.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=12 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary3-2.45.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=12 + ORDER BY x + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.45.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=12 + ORDER BY t1.rowid + } +} {12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.45.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=12 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12} +do_test boundary3-2.45.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 268435455 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.45.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 268435455 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 6 5 4 2 1} +do_test boundary3-2.45.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=12 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary3-2.45.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=12 + ORDER BY t1.rowid DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.45.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=12 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.45.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=12 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6} +do_test boundary3-2.45.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=12 + ORDER BY t1.rowid DESC + } +} {6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.45.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 268435455 ORDER BY t2.a + } +} {1 2 4 5 6 8 9 11 12 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.45.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 268435455 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 12 11 9 8 6 5 4 2 1} +do_test boundary3-2.45.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=12 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary3-2.45.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=12 + ORDER BY t1.rowid DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.45.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=12 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.45.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=12 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12} +do_test boundary3-2.45.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=12 + ORDER BY t1.rowid DESC + } +} {12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.46.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-9223372036854775808 AND t2.a=t1.a + } +} {55 8000000000000000} +do_test boundary3-2.46.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='8000000000000000' + } +} {-9223372036854775808 55} +do_test boundary3-2.46.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=55 + } +} {-9223372036854775808 8000000000000000} +do_test boundary3-2.46.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -9223372036854775808 ORDER BY t2.a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.46.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -9223372036854775808 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary3-2.46.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=55 + ORDER BY t1.rowid + } +} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.46.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=55 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2} +do_test boundary3-2.46.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=55 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.46.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -9223372036854775808 ORDER BY t2.a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.46.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -9223372036854775808 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary3-2.46.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=55 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.46.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=55 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.46.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=55 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.46.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -9223372036854775808 ORDER BY t2.a + } +} {} +do_test boundary3-2.46.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -9223372036854775808 ORDER BY t1.a DESC + } +} {} +do_test boundary3-2.46.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=55 + ORDER BY t1.rowid + } +} {} +do_test boundary3-2.46.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=55 + ORDER BY t1.rowid DESC + } +} {} +do_test boundary3-2.46.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=55 + ORDER BY x + } +} {} +do_test boundary3-2.46.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -9223372036854775808 ORDER BY t2.a + } +} {55} +do_test boundary3-2.46.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -9223372036854775808 ORDER BY t1.a DESC + } +} {55} +do_test boundary3-2.46.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=55 + ORDER BY t1.rowid + } +} {55} +do_test boundary3-2.46.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=55 + ORDER BY t1.rowid DESC + } +} {55} +do_test boundary3-2.46.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=55 + ORDER BY x + } +} {55} +do_test boundary3-2.47.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=562949953421312 AND t2.a=t1.a + } +} {43 0002000000000000} +do_test boundary3-2.47.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0002000000000000' + } +} {562949953421312 43} +do_test boundary3-2.47.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=43 + } +} {562949953421312 0002000000000000} +do_test boundary3-2.47.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 562949953421312 ORDER BY t2.a + } +} {3 17 27 28 45} +do_test boundary3-2.47.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 562949953421312 ORDER BY t1.a DESC + } +} {45 28 27 17 3} +do_test boundary3-2.47.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=43 + ORDER BY t1.rowid + } +} {27 45 17 28 3} +do_test boundary3-2.47.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=43 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27} +do_test boundary3-2.47.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=43 + ORDER BY x + } +} {27 45 17 28 3} +do_test boundary3-2.47.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 562949953421312 ORDER BY t2.a + } +} {3 17 27 28 43 45} +do_test boundary3-2.47.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 562949953421312 ORDER BY t1.a DESC + } +} {45 43 28 27 17 3} +do_test boundary3-2.47.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=43 + ORDER BY t1.rowid + } +} {43 27 45 17 28 3} +do_test boundary3-2.47.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=43 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43} +do_test boundary3-2.47.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=43 + ORDER BY x + } +} {43 27 45 17 28 3} +do_test boundary3-2.47.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 562949953421312 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.47.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 562949953421312 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.47.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=43 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13} +do_test boundary3-2.47.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=43 + ORDER BY t1.rowid DESC + } +} {13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.47.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=43 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.47.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 562949953421312 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.47.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 562949953421312 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.47.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=43 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43} +do_test boundary3-2.47.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=43 + ORDER BY t1.rowid DESC + } +} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.47.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=43 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.48.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-8388609 AND t2.a=t1.a + } +} {1 ffffffffff7fffff} +do_test boundary3-2.48.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffffffff7fffff' + } +} {-8388609 1} +do_test boundary3-2.48.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=1 + } +} {-8388609 ffffffffff7fffff} +do_test boundary3-2.48.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -8388609 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.48.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -8388609 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.48.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=1 + ORDER BY t1.rowid + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.48.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=1 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary3-2.48.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=1 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 37 29 32 54 53 52 33 38} +do_test boundary3-2.48.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=1 + ORDER BY t1.rowid + } +} {37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.48.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=1 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37} +do_test boundary3-2.48.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -8388609 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.48.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -8388609 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.48.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=1 + ORDER BY t1.rowid + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.48.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=1 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary3-2.48.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=1 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.48.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=1 + ORDER BY t1.rowid + } +} {1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.48.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=1 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1} +do_test boundary3-2.48.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -8388609 ORDER BY t2.a + } +} {2 11 21 44 47 55 58 63 64} +do_test boundary3-2.48.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -8388609 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 21 11 2} +do_test boundary3-2.48.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=1 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary3-2.48.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=1 + ORDER BY t1.rowid DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary3-2.48.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=1 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary3-2.48.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=1 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11} +do_test boundary3-2.48.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=1 + ORDER BY t1.rowid DESC + } +} {11 47 63 58 44 21 64 2 55} +do_test boundary3-2.48.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -8388609 ORDER BY t2.a + } +} {1 2 11 21 44 47 55 58 63 64} +do_test boundary3-2.48.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -8388609 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 21 11 2 1} +do_test boundary3-2.48.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=1 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary3-2.48.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=1 + ORDER BY t1.rowid DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.48.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=1 + ORDER BY x + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary3-2.48.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=1 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1} +do_test boundary3-2.48.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=1 + ORDER BY t1.rowid DESC + } +} {1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.49.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=16777215 AND t2.a=t1.a + } +} {9 0000000000ffffff} +do_test boundary3-2.49.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000ffffff' + } +} {16777215 9} +do_test boundary3-2.49.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=9 + } +} {16777215 0000000000ffffff} +do_test boundary3-2.49.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 16777215 ORDER BY t2.a + } +} {3 6 7 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.49.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 16777215 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 7 6 3} +do_test boundary3-2.49.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=9 + ORDER BY t1.rowid + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.49.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=9 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary3-2.49.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=9 + ORDER BY x + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.49.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=9 + ORDER BY t1.rowid + } +} {6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.49.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=9 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6} +do_test boundary3-2.49.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 16777215 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.49.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 16777215 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary3-2.49.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=9 + ORDER BY t1.rowid + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.49.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=9 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary3-2.49.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=9 + ORDER BY x + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.49.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=9 + ORDER BY t1.rowid + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.49.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=9 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary3-2.49.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 16777215 ORDER BY t2.a + } +} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.49.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 16777215 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary3-2.49.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=9 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary3-2.49.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=9 + ORDER BY t1.rowid DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.49.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=9 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.49.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=9 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary3-2.49.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=9 + ORDER BY t1.rowid DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.49.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 16777215 ORDER BY t2.a + } +} {1 2 4 5 8 9 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.49.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 16777215 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 9 8 5 4 2 1} +do_test boundary3-2.49.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=9 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary3-2.49.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=9 + ORDER BY t1.rowid DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.49.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=9 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.49.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=9 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9} +do_test boundary3-2.49.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=9 + ORDER BY t1.rowid DESC + } +} {9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.50.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=8388608 AND t2.a=t1.a + } +} {24 0000000000800000} +do_test boundary3-2.50.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000800000' + } +} {8388608 24} +do_test boundary3-2.50.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=24 + } +} {8388608 0000000000800000} +do_test boundary3-2.50.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 8388608 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.50.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 8388608 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary3-2.50.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=24 + ORDER BY t1.rowid + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.50.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=24 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary3-2.50.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=24 + ORDER BY x + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.50.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=24 + ORDER BY t1.rowid + } +} {9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.50.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=24 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9} +do_test boundary3-2.50.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 8388608 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 17 19 20 22 24 25 26 27 28 34 35 36 39 40 43 45 46 51 56 57} +do_test boundary3-2.50.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 8388608 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 40 39 36 35 34 28 27 26 25 24 22 20 19 17 14 13 12 10 9 7 6 3} +do_test boundary3-2.50.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=24 + ORDER BY t1.rowid + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.50.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=24 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary3-2.50.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=24 + ORDER BY x + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.50.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=24 + ORDER BY t1.rowid + } +} {24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.50.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=24 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24} +do_test boundary3-2.50.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 8388608 ORDER BY t2.a + } +} {1 2 4 5 8 11 15 16 18 21 23 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.50.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 8388608 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary3-2.50.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=24 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary3-2.50.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=24 + ORDER BY t1.rowid DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.50.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=24 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.50.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=24 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18} +do_test boundary3-2.50.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=24 + ORDER BY t1.rowid DESC + } +} {18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.50.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 8388608 ORDER BY t2.a + } +} {1 2 4 5 8 11 15 16 18 21 23 24 29 30 31 32 33 37 38 41 42 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.50.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 8388608 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 42 41 38 37 33 32 31 30 29 24 23 21 18 16 15 11 8 5 4 2 1} +do_test boundary3-2.50.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=24 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary3-2.50.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=24 + ORDER BY t1.rowid DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.50.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=24 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.50.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=24 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24} +do_test boundary3-2.50.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=24 + ORDER BY t1.rowid DESC + } +} {24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.51.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=16383 AND t2.a=t1.a + } +} {8 0000000000003fff} +do_test boundary3-2.51.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000003fff' + } +} {16383 8} +do_test boundary3-2.51.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=8 + } +} {16383 0000000000003fff} +do_test boundary3-2.51.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 16383 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary3-2.51.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 16383 ORDER BY t1.a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.51.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=8 + ORDER BY t1.rowid + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.51.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=8 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary3-2.51.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=8 + ORDER BY x + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.51.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=8 + ORDER BY t1.rowid + } +} {16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.51.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=8 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16} +do_test boundary3-2.51.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 16383 ORDER BY t2.a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary3-2.51.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 16383 ORDER BY t1.a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary3-2.51.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=8 + ORDER BY t1.rowid + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.51.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=8 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary3-2.51.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=8 + ORDER BY x + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.51.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=8 + ORDER BY t1.rowid + } +} {8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.51.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=8 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8} +do_test boundary3-2.51.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 16383 ORDER BY t2.a + } +} {1 2 4 5 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.51.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 16383 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 5 4 2 1} +do_test boundary3-2.51.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=8 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary3-2.51.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=8 + ORDER BY t1.rowid DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.51.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=8 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.51.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=8 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61} +do_test boundary3-2.51.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=8 + ORDER BY t1.rowid DESC + } +} {61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.51.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 16383 ORDER BY t2.a + } +} {1 2 4 5 8 11 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.51.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 16383 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 11 8 5 4 2 1} +do_test boundary3-2.51.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=8 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary3-2.51.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=8 + ORDER BY t1.rowid DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.51.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=8 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.51.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=8 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8} +do_test boundary3-2.51.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=8 + ORDER BY t1.rowid DESC + } +} {8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.52.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=140737488355328 AND t2.a=t1.a + } +} {34 0000800000000000} +do_test boundary3-2.52.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000800000000000' + } +} {140737488355328 34} +do_test boundary3-2.52.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=34 + } +} {140737488355328 0000800000000000} +do_test boundary3-2.52.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 140737488355328 ORDER BY t2.a + } +} {3 10 13 17 26 27 28 43 45} +do_test boundary3-2.52.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 140737488355328 ORDER BY t1.a DESC + } +} {45 43 28 27 26 17 13 10 3} +do_test boundary3-2.52.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=34 + ORDER BY t1.rowid + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary3-2.52.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=34 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10} +do_test boundary3-2.52.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=34 + ORDER BY x + } +} {10 26 13 43 27 45 17 28 3} +do_test boundary3-2.52.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 140737488355328 ORDER BY t2.a + } +} {3 10 13 17 26 27 28 34 43 45} +do_test boundary3-2.52.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 140737488355328 ORDER BY t1.a DESC + } +} {45 43 34 28 27 26 17 13 10 3} +do_test boundary3-2.52.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=34 + ORDER BY t1.rowid + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.52.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=34 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34} +do_test boundary3-2.52.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=34 + ORDER BY x + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.52.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 140737488355328 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.52.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 140737488355328 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary3-2.52.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=34 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25} +do_test boundary3-2.52.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=34 + ORDER BY t1.rowid DESC + } +} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.52.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=34 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.52.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 140737488355328 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.52.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 140737488355328 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary3-2.52.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=34 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34} +do_test boundary3-2.52.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=34 + ORDER BY t1.rowid DESC + } +} {34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.52.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=34 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.53.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=2097151 AND t2.a=t1.a + } +} {15 00000000001fffff} +do_test boundary3-2.53.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='00000000001fffff' + } +} {2097151 15} +do_test boundary3-2.53.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=15 + } +} {2097151 00000000001fffff} +do_test boundary3-2.53.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 2097151 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary3-2.53.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 2097151 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 14 13 12 10 9 7 6 3} +do_test boundary3-2.53.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=15 + ORDER BY t1.rowid + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.53.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=15 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary3-2.53.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=15 + ORDER BY x + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.53.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=15 + ORDER BY t1.rowid + } +} {42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.53.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=15 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42} +do_test boundary3-2.53.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 2097151 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 51 56 57} +do_test boundary3-2.53.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 2097151 ORDER BY t1.a DESC + } +} {57 56 51 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.53.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=15 + ORDER BY t1.rowid + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.53.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=15 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary3-2.53.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=15 + ORDER BY x + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.53.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=15 + ORDER BY t1.rowid + } +} {15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.53.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=15 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15} +do_test boundary3-2.53.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 2097151 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.53.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 2097151 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary3-2.53.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=15 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary3-2.53.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=15 + ORDER BY t1.rowid DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.53.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=15 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.53.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=15 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62} +do_test boundary3-2.53.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=15 + ORDER BY t1.rowid DESC + } +} {62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.53.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 2097151 ORDER BY t2.a + } +} {1 2 4 5 8 11 15 16 21 23 29 30 31 32 33 37 38 41 44 47 48 49 50 52 53 54 55 58 59 60 61 62 63 64} +do_test boundary3-2.53.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 2097151 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 55 54 53 52 50 49 48 47 44 41 38 37 33 32 31 30 29 23 21 16 15 11 8 5 4 2 1} +do_test boundary3-2.53.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=15 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary3-2.53.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=15 + ORDER BY t1.rowid DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.53.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=15 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.53.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=15 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15} +do_test boundary3-2.53.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=15 + ORDER BY t1.rowid DESC + } +} {15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.54.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=140737488355327 AND t2.a=t1.a + } +} {25 00007fffffffffff} +do_test boundary3-2.54.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='00007fffffffffff' + } +} {140737488355327 25} +do_test boundary3-2.54.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=25 + } +} {140737488355327 00007fffffffffff} +do_test boundary3-2.54.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 140737488355327 ORDER BY t2.a + } +} {3 10 13 17 26 27 28 34 43 45} +do_test boundary3-2.54.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 140737488355327 ORDER BY t1.a DESC + } +} {45 43 34 28 27 26 17 13 10 3} +do_test boundary3-2.54.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=25 + ORDER BY t1.rowid + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.54.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=25 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34} +do_test boundary3-2.54.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=25 + ORDER BY x + } +} {34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.54.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 140737488355327 ORDER BY t2.a + } +} {3 10 13 17 25 26 27 28 34 43 45} +do_test boundary3-2.54.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 140737488355327 ORDER BY t1.a DESC + } +} {45 43 34 28 27 26 25 17 13 10 3} +do_test boundary3-2.54.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=25 + ORDER BY t1.rowid + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.54.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=25 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25} +do_test boundary3-2.54.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=25 + ORDER BY x + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.54.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 140737488355327 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.54.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 140737488355327 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary3-2.54.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=25 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56} +do_test boundary3-2.54.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=25 + ORDER BY t1.rowid DESC + } +} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.54.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=25 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.54.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 140737488355327 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.54.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 140737488355327 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary3-2.54.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=25 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25} +do_test boundary3-2.54.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=25 + ORDER BY t1.rowid DESC + } +} {25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.54.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=25 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.55.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=281474976710656 AND t2.a=t1.a + } +} {26 0001000000000000} +do_test boundary3-2.55.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0001000000000000' + } +} {281474976710656 26} +do_test boundary3-2.55.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=26 + } +} {281474976710656 0001000000000000} +do_test boundary3-2.55.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 281474976710656 ORDER BY t2.a + } +} {3 13 17 27 28 43 45} +do_test boundary3-2.55.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 281474976710656 ORDER BY t1.a DESC + } +} {45 43 28 27 17 13 3} +do_test boundary3-2.55.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=26 + ORDER BY t1.rowid + } +} {13 43 27 45 17 28 3} +do_test boundary3-2.55.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=26 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13} +do_test boundary3-2.55.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=26 + ORDER BY x + } +} {13 43 27 45 17 28 3} +do_test boundary3-2.55.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 281474976710656 ORDER BY t2.a + } +} {3 13 17 26 27 28 43 45} +do_test boundary3-2.55.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 281474976710656 ORDER BY t1.a DESC + } +} {45 43 28 27 26 17 13 3} +do_test boundary3-2.55.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=26 + ORDER BY t1.rowid + } +} {26 13 43 27 45 17 28 3} +do_test boundary3-2.55.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=26 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26} +do_test boundary3-2.55.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=26 + ORDER BY x + } +} {26 13 43 27 45 17 28 3} +do_test boundary3-2.55.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 281474976710656 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.55.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 281474976710656 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.55.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=26 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10} +do_test boundary3-2.55.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=26 + ORDER BY t1.rowid DESC + } +} {10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.55.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=26 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.55.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 281474976710656 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.55.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 281474976710656 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.55.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=26 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26} +do_test boundary3-2.55.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=26 + ORDER BY t1.rowid DESC + } +} {26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.55.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=26 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.56.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=32767 AND t2.a=t1.a + } +} {23 0000000000007fff} +do_test boundary3-2.56.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000007fff' + } +} {32767 23} +do_test boundary3-2.56.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=23 + } +} {32767 0000000000007fff} +do_test boundary3-2.56.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 32767 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary3-2.56.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 32767 ORDER BY t1.a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.56.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=23 + ORDER BY t1.rowid + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.56.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=23 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary3-2.56.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=23 + ORDER BY x + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.56.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=23 + ORDER BY t1.rowid + } +} {50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.56.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=23 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50} +do_test boundary3-2.56.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 32767 ORDER BY t2.a + } +} {3 6 7 9 10 12 13 14 15 17 18 19 20 22 23 24 25 26 27 28 34 35 36 39 40 42 43 45 46 48 50 51 56 57 62} +do_test boundary3-2.56.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 32767 ORDER BY t1.a DESC + } +} {62 57 56 51 50 48 46 45 43 42 40 39 36 35 34 28 27 26 25 24 23 22 20 19 18 17 15 14 13 12 10 9 7 6 3} +do_test boundary3-2.56.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=23 + ORDER BY t1.rowid + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.56.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=23 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary3-2.56.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=23 + ORDER BY x + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.56.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=23 + ORDER BY t1.rowid + } +} {23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.56.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=23 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23} +do_test boundary3-2.56.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 32767 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.56.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 32767 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 21 16 11 8 5 4 2 1} +do_test boundary3-2.56.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=23 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary3-2.56.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=23 + ORDER BY t1.rowid DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.56.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=23 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.56.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=23 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16} +do_test boundary3-2.56.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=23 + ORDER BY t1.rowid DESC + } +} {16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.56.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 32767 ORDER BY t2.a + } +} {1 2 4 5 8 11 16 21 23 29 30 31 32 33 37 38 41 44 47 49 52 53 54 55 58 59 60 61 63 64} +do_test boundary3-2.56.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 32767 ORDER BY t1.a DESC + } +} {64 63 61 60 59 58 55 54 53 52 49 47 44 41 38 37 33 32 31 30 29 23 21 16 11 8 5 4 2 1} +do_test boundary3-2.56.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=23 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary3-2.56.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=23 + ORDER BY t1.rowid DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.56.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=23 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.56.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=23 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23} +do_test boundary3-2.56.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=23 + ORDER BY t1.rowid DESC + } +} {23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.57.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=127 AND t2.a=t1.a + } +} {4 000000000000007f} +do_test boundary3-2.57.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='000000000000007f' + } +} {127 4} +do_test boundary3-2.57.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=4 + } +} {127 000000000000007f} +do_test boundary3-2.57.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 127 ORDER BY t2.a + } +} {3 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.57.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 127 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 3} +do_test boundary3-2.57.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=4 + ORDER BY t1.rowid + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.57.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=4 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary3-2.57.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=4 + ORDER BY x + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.57.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=4 + ORDER BY t1.rowid + } +} {49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.57.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=4 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49} +do_test boundary3-2.57.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 127 ORDER BY t2.a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.57.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 127 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary3-2.57.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=4 + ORDER BY t1.rowid + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.57.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=4 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary3-2.57.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=4 + ORDER BY x + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.57.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=4 + ORDER BY t1.rowid + } +} {4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.57.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=4 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4} +do_test boundary3-2.57.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 127 ORDER BY t2.a + } +} {1 2 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.57.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 127 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 2 1} +do_test boundary3-2.57.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=4 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary3-2.57.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=4 + ORDER BY t1.rowid DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.57.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=4 + ORDER BY x + } +} {59 60 41 5 31 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.57.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=4 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31} +do_test boundary3-2.57.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=4 + ORDER BY t1.rowid DESC + } +} {31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.57.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 127 ORDER BY t2.a + } +} {1 2 4 5 11 21 29 31 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.57.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 127 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 31 29 21 11 5 4 2 1} +do_test boundary3-2.57.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=4 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary3-2.57.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=4 + ORDER BY t1.rowid DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.57.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=4 + ORDER BY x + } +} {59 60 41 5 31 4 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.57.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=4 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4} +do_test boundary3-2.57.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=4 + ORDER BY t1.rowid DESC + } +} {4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.58.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=36028797018963967 AND t2.a=t1.a + } +} {27 007fffffffffffff} +do_test boundary3-2.58.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='007fffffffffffff' + } +} {36028797018963967 27} +do_test boundary3-2.58.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=27 + } +} {36028797018963967 007fffffffffffff} +do_test boundary3-2.58.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 36028797018963967 ORDER BY t2.a + } +} {3 17 28 45} +do_test boundary3-2.58.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 36028797018963967 ORDER BY t1.a DESC + } +} {45 28 17 3} +do_test boundary3-2.58.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=27 + ORDER BY t1.rowid + } +} {45 17 28 3} +do_test boundary3-2.58.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=27 + ORDER BY t1.rowid DESC + } +} {3 28 17 45} +do_test boundary3-2.58.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=27 + ORDER BY x + } +} {45 17 28 3} +do_test boundary3-2.58.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 36028797018963967 ORDER BY t2.a + } +} {3 17 27 28 45} +do_test boundary3-2.58.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 36028797018963967 ORDER BY t1.a DESC + } +} {45 28 27 17 3} +do_test boundary3-2.58.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=27 + ORDER BY t1.rowid + } +} {27 45 17 28 3} +do_test boundary3-2.58.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=27 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27} +do_test boundary3-2.58.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=27 + ORDER BY x + } +} {27 45 17 28 3} +do_test boundary3-2.58.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 36028797018963967 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.58.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 36028797018963967 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.58.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=27 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43} +do_test boundary3-2.58.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=27 + ORDER BY t1.rowid DESC + } +} {43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.58.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=27 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.58.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 36028797018963967 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.58.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 36028797018963967 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.58.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=27 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27} +do_test boundary3-2.58.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=27 + ORDER BY t1.rowid DESC + } +} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.58.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=27 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.59.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=4398046511104 AND t2.a=t1.a + } +} {56 0000040000000000} +do_test boundary3-2.59.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000040000000000' + } +} {4398046511104 56} +do_test boundary3-2.59.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=56 + } +} {4398046511104 0000040000000000} +do_test boundary3-2.59.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 4398046511104 ORDER BY t2.a + } +} {3 10 13 17 25 26 27 28 34 43 45} +do_test boundary3-2.59.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 4398046511104 ORDER BY t1.a DESC + } +} {45 43 34 28 27 26 25 17 13 10 3} +do_test boundary3-2.59.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=56 + ORDER BY t1.rowid + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.59.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=56 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25} +do_test boundary3-2.59.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=56 + ORDER BY x + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.59.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=56 + ORDER BY t1.rowid + } +} {25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.59.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=56 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25} +do_test boundary3-2.59.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 4398046511104 ORDER BY t2.a + } +} {3 10 13 17 25 26 27 28 34 43 45 56} +do_test boundary3-2.59.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 4398046511104 ORDER BY t1.a DESC + } +} {56 45 43 34 28 27 26 25 17 13 10 3} +do_test boundary3-2.59.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=56 + ORDER BY t1.rowid + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.59.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=56 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary3-2.59.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=56 + ORDER BY x + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.59.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=56 + ORDER BY t1.rowid + } +} {56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.59.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=56 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56} +do_test boundary3-2.59.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 4398046511104 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 62 63 64} +do_test boundary3-2.59.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 4398046511104 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary3-2.59.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=56 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary3-2.59.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=56 + ORDER BY t1.rowid DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.59.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=56 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.59.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=56 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7} +do_test boundary3-2.59.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=56 + ORDER BY t1.rowid DESC + } +} {7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.59.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 4398046511104 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 11 12 14 15 16 18 19 20 21 22 23 24 29 30 31 32 33 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.59.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 4398046511104 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 42 41 40 39 38 37 36 35 33 32 31 30 29 24 23 22 21 20 19 18 16 15 14 12 11 9 8 7 6 5 4 2 1} +do_test boundary3-2.59.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=56 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56} +do_test boundary3-2.59.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=56 + ORDER BY t1.rowid DESC + } +} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.59.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=56 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.59.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=56 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56} +do_test boundary3-2.59.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=56 + ORDER BY t1.rowid DESC + } +} {56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.60.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=1 AND t2.a=t1.a + } +} {60 0000000000000001} +do_test boundary3-2.60.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000000001' + } +} {1 60} +do_test boundary3-2.60.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=60 + } +} {1 0000000000000001} +do_test boundary3-2.60.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 1 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.60.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 1 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.60.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=60 + ORDER BY t1.rowid + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.60.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=60 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary3-2.60.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=60 + ORDER BY x + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.60.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=60 + ORDER BY t1.rowid + } +} {41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.60.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=60 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41} +do_test boundary3-2.60.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 1 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 41 42 43 45 46 48 49 50 51 56 57 60 61 62} +do_test boundary3-2.60.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 1 ORDER BY t1.a DESC + } +} {62 61 60 57 56 51 50 49 48 46 45 43 42 41 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.60.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=60 + ORDER BY t1.rowid + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.60.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=60 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary3-2.60.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=60 + ORDER BY x + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.60.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=60 + ORDER BY t1.rowid + } +} {60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.60.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=60 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60} +do_test boundary3-2.60.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 1 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 63 64} +do_test boundary3-2.60.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 1 ORDER BY t1.a DESC + } +} {64 63 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary3-2.60.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=60 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary3-2.60.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=60 + ORDER BY t1.rowid DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.60.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=60 + ORDER BY x + } +} {59 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.60.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=60 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59} +do_test boundary3-2.60.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=60 + ORDER BY t1.rowid DESC + } +} {59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.60.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 1 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 38 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.60.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 1 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 38 37 33 32 29 21 11 2 1} +do_test boundary3-2.60.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=60 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary3-2.60.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=60 + ORDER BY t1.rowid DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.60.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=60 + ORDER BY x + } +} {59 60 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.60.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=60 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60} +do_test boundary3-2.60.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=60 + ORDER BY t1.rowid DESC + } +} {60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.61.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=36028797018963968 AND t2.a=t1.a + } +} {45 0080000000000000} +do_test boundary3-2.61.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0080000000000000' + } +} {36028797018963968 45} +do_test boundary3-2.61.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=45 + } +} {36028797018963968 0080000000000000} +do_test boundary3-2.61.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 36028797018963968 ORDER BY t2.a + } +} {3 17 28} +do_test boundary3-2.61.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 36028797018963968 ORDER BY t1.a DESC + } +} {28 17 3} +do_test boundary3-2.61.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=45 + ORDER BY t1.rowid + } +} {17 28 3} +do_test boundary3-2.61.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=45 + ORDER BY t1.rowid DESC + } +} {3 28 17} +do_test boundary3-2.61.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=45 + ORDER BY x + } +} {17 28 3} +do_test boundary3-2.61.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 36028797018963968 ORDER BY t2.a + } +} {3 17 28 45} +do_test boundary3-2.61.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 36028797018963968 ORDER BY t1.a DESC + } +} {45 28 17 3} +do_test boundary3-2.61.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=45 + ORDER BY t1.rowid + } +} {45 17 28 3} +do_test boundary3-2.61.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=45 + ORDER BY t1.rowid DESC + } +} {3 28 17 45} +do_test boundary3-2.61.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=45 + ORDER BY x + } +} {45 17 28 3} +do_test boundary3-2.61.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 36028797018963968 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.61.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 36028797018963968 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.61.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=45 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27} +do_test boundary3-2.61.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=45 + ORDER BY t1.rowid DESC + } +} {27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.61.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=45 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.61.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 36028797018963968 ORDER BY t2.a + } +} {1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.61.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 36028797018963968 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 27 26 25 24 23 22 21 20 19 18 16 15 14 13 12 11 10 9 8 7 6 5 4 2 1} +do_test boundary3-2.61.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=45 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45} +do_test boundary3-2.61.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=45 + ORDER BY t1.rowid DESC + } +} {45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.61.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=45 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.62.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-2147483649 AND t2.a=t1.a + } +} {47 ffffffff7fffffff} +do_test boundary3-2.62.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ffffffff7fffffff' + } +} {-2147483649 47} +do_test boundary3-2.62.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=47 + } +} {-2147483649 ffffffff7fffffff} +do_test boundary3-2.62.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -2147483649 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.62.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -2147483649 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.62.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=47 + ORDER BY t1.rowid + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.62.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=47 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary3-2.62.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=47 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.62.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=47 + ORDER BY t1.rowid + } +} {11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.62.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=47 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11} +do_test boundary3-2.62.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -2147483649 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 59 60 61 62} +do_test boundary3-2.62.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -2147483649 ORDER BY t1.a DESC + } +} {62 61 60 59 57 56 54 53 52 51 50 49 48 47 46 45 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.62.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=47 + ORDER BY t1.rowid + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.62.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=47 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary3-2.62.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=47 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.62.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=47 + ORDER BY t1.rowid + } +} {47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.62.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=47 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47} +do_test boundary3-2.62.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -2147483649 ORDER BY t2.a + } +} {2 21 44 55 58 63 64} +do_test boundary3-2.62.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -2147483649 ORDER BY t1.a DESC + } +} {64 63 58 55 44 21 2} +do_test boundary3-2.62.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=47 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63} +do_test boundary3-2.62.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=47 + ORDER BY t1.rowid DESC + } +} {63 58 44 21 64 2 55} +do_test boundary3-2.62.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=47 + ORDER BY x + } +} {55 2 64 21 44 58 63} +do_test boundary3-2.62.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=47 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63} +do_test boundary3-2.62.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=47 + ORDER BY t1.rowid DESC + } +} {63 58 44 21 64 2 55} +do_test boundary3-2.62.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -2147483649 ORDER BY t2.a + } +} {2 21 44 47 55 58 63 64} +do_test boundary3-2.62.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -2147483649 ORDER BY t1.a DESC + } +} {64 63 58 55 47 44 21 2} +do_test boundary3-2.62.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=47 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47} +do_test boundary3-2.62.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=47 + ORDER BY t1.rowid DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary3-2.62.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=47 + ORDER BY x + } +} {55 2 64 21 44 58 63 47} +do_test boundary3-2.62.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=47 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47} +do_test boundary3-2.62.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=47 + ORDER BY t1.rowid DESC + } +} {47 63 58 44 21 64 2 55} +do_test boundary3-2.63.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=-36028797018963969 AND t2.a=t1.a + } +} {2 ff7fffffffffffff} +do_test boundary3-2.63.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='ff7fffffffffffff' + } +} {-36028797018963969 2} +do_test boundary3-2.63.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=2 + } +} {-36028797018963969 ff7fffffffffffff} +do_test boundary3-2.63.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -36028797018963969 ORDER BY t2.a + } +} {1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.63.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -36028797018963969 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1} +do_test boundary3-2.63.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=2 + ORDER BY t1.rowid + } +} {64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.63.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=2 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64} +do_test boundary3-2.63.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=2 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.63.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -36028797018963969 ORDER BY t2.a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.63.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -36028797018963969 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary3-2.63.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=2 + ORDER BY t1.rowid + } +} {2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.63.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=2 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2} +do_test boundary3-2.63.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=2 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.63.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -36028797018963969 ORDER BY t2.a + } +} {55} +do_test boundary3-2.63.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -36028797018963969 ORDER BY t1.a DESC + } +} {55} +do_test boundary3-2.63.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=2 + ORDER BY t1.rowid + } +} {55} +do_test boundary3-2.63.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=2 + ORDER BY t1.rowid DESC + } +} {55} +do_test boundary3-2.63.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=2 + ORDER BY x + } +} {55} +do_test boundary3-2.63.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -36028797018963969 ORDER BY t2.a + } +} {2 55} +do_test boundary3-2.63.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -36028797018963969 ORDER BY t1.a DESC + } +} {55 2} +do_test boundary3-2.63.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=2 + ORDER BY t1.rowid + } +} {55 2} +do_test boundary3-2.63.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=2 + ORDER BY t1.rowid DESC + } +} {2 55} +do_test boundary3-2.63.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=2 + ORDER BY x + } +} {55 2} +do_test boundary3-2.64.1 { + db eval { + SELECT t1.* FROM t1, t2 WHERE t1.rowid=3 AND t2.a=t1.a + } +} {5 0000000000000003} +do_test boundary3-2.64.2 { + db eval { + SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0000000000000003' + } +} {3 5} +do_test boundary3-2.64.3 { + db eval { + SELECT t1.rowid, x FROM t1 JOIN t2 ON t2.r=t1.rowid WHERE t2.a=5 + } +} {3 0000000000000003} +do_test boundary3-2.64.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 3 ORDER BY t2.a + } +} {3 4 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.64.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 3 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 4 3} +do_test boundary3-2.64.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=5 + ORDER BY t1.rowid + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.64.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=5 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary3-2.64.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=5 + ORDER BY x + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.64.gt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=5 + ORDER BY t1.rowid + } +} {31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.64.gt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > CAST(t2.r AS real) + WHERE t2.a=5 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31} +do_test boundary3-2.64.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 3 ORDER BY t2.a + } +} {3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 30 31 34 35 36 39 40 42 43 45 46 48 49 50 51 56 57 61 62} +do_test boundary3-2.64.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 3 ORDER BY t1.a DESC + } +} {62 61 57 56 51 50 49 48 46 45 43 42 40 39 36 35 34 31 30 28 27 26 25 24 23 22 20 19 18 17 16 15 14 13 12 10 9 8 7 6 5 4 3} +do_test boundary3-2.64.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=5 + ORDER BY t1.rowid + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.64.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=5 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary3-2.64.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=5 + ORDER BY x + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.64.ge.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=5 + ORDER BY t1.rowid + } +} {5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.64.ge.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= CAST(t2.r AS real) + WHERE t2.a=5 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5} +do_test boundary3-2.64.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 3 ORDER BY t2.a + } +} {1 2 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.64.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 3 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 2 1} +do_test boundary3-2.64.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=5 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary3-2.64.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=5 + ORDER BY t1.rowid DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.64.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=5 + ORDER BY x + } +} {59 60 41 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.64.lt.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=5 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41} +do_test boundary3-2.64.lt.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < CAST(t2.r AS real) + WHERE t2.a=5 + ORDER BY t1.rowid DESC + } +} {41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.64.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 3 ORDER BY t2.a + } +} {1 2 5 11 21 29 32 33 37 38 41 44 47 52 53 54 55 58 59 60 63 64} +do_test boundary3-2.64.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 3 ORDER BY t1.a DESC + } +} {64 63 60 59 58 55 54 53 52 47 44 41 38 37 33 32 29 21 11 5 2 1} +do_test boundary3-2.64.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=5 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary3-2.64.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=5 + ORDER BY t1.rowid DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.64.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=5 + ORDER BY x + } +} {59 60 41 5 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.64.le.10 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=5 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5} +do_test boundary3-2.64.le.11 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= CAST(t2.r AS real) + WHERE t2.a=5 + ORDER BY t1.rowid DESC + } +} {5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.65.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > 9.22337303685477580800e+18 ORDER BY t2.a + } +} {} +do_test boundary3-2.65.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > 9.22337303685477580800e+18 ORDER BY t1.a DESC + } +} {} +do_test boundary3-2.65.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=65 + ORDER BY t1.rowid + } +} {} +do_test boundary3-2.65.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=65 + ORDER BY t1.rowid DESC + } +} {} +do_test boundary3-2.65.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=65 + ORDER BY x + } +} {} +do_test boundary3-2.65.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= 9.22337303685477580800e+18 ORDER BY t2.a + } +} {} +do_test boundary3-2.65.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= 9.22337303685477580800e+18 ORDER BY t1.a DESC + } +} {} +do_test boundary3-2.65.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=65 + ORDER BY t1.rowid + } +} {} +do_test boundary3-2.65.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=65 + ORDER BY t1.rowid DESC + } +} {} +do_test boundary3-2.65.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=65 + ORDER BY x + } +} {} +do_test boundary3-2.65.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < 9.22337303685477580800e+18 ORDER BY t2.a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.65.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < 9.22337303685477580800e+18 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary3-2.65.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=65 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.65.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=65 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.65.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=65 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.65.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= 9.22337303685477580800e+18 ORDER BY t2.a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.65.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= 9.22337303685477580800e+18 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary3-2.65.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=65 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.65.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=65 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.65.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=65 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.66.gt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid > -9.22337303685477580800e+18 ORDER BY t2.a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.66.gt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid > -9.22337303685477580800e+18 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary3-2.66.gt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=66 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.66.gt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=66 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.66.gt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid > t2.r + WHERE t2.a=66 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.66.ge.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid >= -9.22337303685477580800e+18 ORDER BY t2.a + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64} +do_test boundary3-2.66.ge.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid >= -9.22337303685477580800e+18 ORDER BY t1.a DESC + } +} {64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1} +do_test boundary3-2.66.ge.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=66 + ORDER BY t1.rowid + } +} {55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38 59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3} +do_test boundary3-2.66.ge.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=66 + ORDER BY t1.rowid DESC + } +} {3 28 17 45 27 43 13 26 10 34 25 56 7 19 57 35 46 22 39 36 14 51 20 40 12 6 9 24 18 42 15 62 48 50 23 16 8 61 30 49 4 31 5 41 60 59 38 33 52 53 54 32 29 37 1 11 47 63 58 44 21 64 2 55} +do_test boundary3-2.66.ge.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid >= t2.r + WHERE t2.a=66 + ORDER BY x + } +} {59 60 41 5 31 4 49 30 61 8 16 23 50 48 62 15 42 18 24 9 6 12 40 20 51 14 36 39 22 46 35 57 19 7 56 25 34 10 26 13 43 27 45 17 28 3 55 2 64 21 44 58 63 47 11 1 37 29 32 54 53 52 33 38} +do_test boundary3-2.66.lt.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid < -9.22337303685477580800e+18 ORDER BY t2.a + } +} {} +do_test boundary3-2.66.lt.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid < -9.22337303685477580800e+18 ORDER BY t1.a DESC + } +} {} +do_test boundary3-2.66.lt.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=66 + ORDER BY t1.rowid + } +} {} +do_test boundary3-2.66.lt.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=66 + ORDER BY t1.rowid DESC + } +} {} +do_test boundary3-2.66.lt.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid < t2.r + WHERE t2.a=66 + ORDER BY x + } +} {} +do_test boundary3-2.66.le.1 { + db eval { + SELECT t2.a FROM t1 JOIN t2 USING(a) + WHERE t1.rowid <= -9.22337303685477580800e+18 ORDER BY t2.a + } +} {} +do_test boundary3-2.66.le.2 { + db eval { + SELECT t2.a FROM t2 NATURAL JOIN t1 + WHERE t1.rowid <= -9.22337303685477580800e+18 ORDER BY t1.a DESC + } +} {} +do_test boundary3-2.66.le.3 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=66 + ORDER BY t1.rowid + } +} {} +do_test boundary3-2.66.le.4 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=66 + ORDER BY t1.rowid DESC + } +} {} +do_test boundary3-2.66.le.5 { + db eval { + SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r + WHERE t2.a=66 + ORDER BY x + } +} {} +finish_test diff --git a/components/external/SQLite-3.8.1/test/boundary4.tcl b/components/external/SQLite-3.8.1/test/boundary4.tcl new file mode 100644 index 0000000000000000000000000000000000000000..20f5c9680fb8a7d781187a0ac874a86125c83644 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/boundary4.tcl @@ -0,0 +1,340 @@ +puts {# 2008 December 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is automatically generated from a separate TCL script. +# This file seeks to exercise integer boundary values. +# +# $Id: boundary4.tcl,v 1.3 2009/01/02 15:45:48 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Many of the boundary tests depend on a working 64-bit implementation. +if {![working_64bit_int]} { finish_test; return } +ifcapable !altertable { finish_test; return } +} + +expr srand(0) + +# Generate interesting boundary numbers +# +foreach x { + 0x7f + 0x7fff + 0x7fffff + 0x7fffffff + 0x7fffffffff + 0x7fffffffffff + 0x7fffffffffffff + 0x7fffffffffffffff +} { + set x [expr {wide($x)}] + set boundarynum($x) 1 + set boundarynum([expr {$x+1}]) 1 + set boundarynum([expr {-($x+1)}]) 1 + set boundarynum([expr {-($x+2)}]) 1 + set boundarynum([expr {$x+$x+1}]) 1 + set boundarynum([expr {$x+$x+2}]) 1 +} +set x [expr {wide(127)}] +for {set i 127} {$i<=9} {incr i} { + set boundarynum($x) 1 + set boundarynum([expr {$x+1}]) 1 + set x [expr {wide($x*128 + 127)}] +} + +# Scramble the $inlist into a random order. +# +proc scramble {inlist} { + set y {} + foreach x $inlist { + lappend y [list [expr {rand()}] $x] + } + set y [lsort $y] + set outlist {} + foreach x $y { + lappend outlist [lindex $x 1] + } + return $outlist +} + +# A simple selection sort. Not trying to be efficient. +# +proc sort {inlist} { + set outlist {} + set mn [lindex $inlist 0] + foreach x $inlist { + if {$x<$mn} {set mn $x} + } + set outlist $mn + set mx $mn + while {1} { + set valid 0 + foreach x $inlist { + if {$x>$mx && (!$valid || $mn>$x)} { + set mn $x + set valid 1 + } + } + if {!$valid} break + lappend outlist $mn + set mx $mn + } + return $outlist +} + +# Reverse the order of a list +# +proc reverse {inlist} { + set i [llength $inlist] + set outlist {} + for {incr i -1} {$i>=0} {incr i -1} { + lappend outlist [lindex $inlist $i] + } + return $outlist +} + +set nums1 [scramble [array names boundarynum]] +set nums2 [scramble [array names boundarynum]] + +set tname boundary4 +puts "do_test $tname-1.1 \173" +puts " db eval \173" +puts " CREATE TABLE t1(a,x);" +set a 0 +set all_rowid {} +set all_a {} +set all_x {} +foreach r $nums1 { + incr a + set t1ra($r) $a + set t1ar($a) $r + set x [format %08x%08x [expr {wide($r)>>32}] $r] + set t1rx($r) $x + set t1xr($x) $r + puts " INSERT INTO t1(oid,a,x) VALUES($r,$a,'$x');" + lappend all_rowid $r + lappend all_a $a + lappend all_x $x +} +puts " CREATE INDEX t1i1 ON t1(a);" +puts " CREATE INDEX t1i2 ON t1(x);" +puts " \175" +puts "\175 {}" + +puts "do_test $tname-1.2 \173" +puts " db eval \173" +puts " SELECT count(*) FROM t1" +puts " \175" +puts "\175 {[llength $nums1]}" + +proc maketest {tnum sql answer} { + puts "do_test $::tname-$tnum \173" + puts " db eval \173" + puts " $sql" + puts " \175" + puts "\175 {$answer}" +} + +set ans {} +foreach r [sort $all_rowid] { + lappend ans $r $t1ra($r) $t1rx($r) +} +maketest 1.3 {SELECT rowid, a, x FROM t1 ORDER BY +rowid} $ans +maketest 1.4 {SELECT rowid, a, x FROM t1 ORDER BY rowid} $ans + +set ans {} +foreach r [reverse [sort $all_rowid]] { + lappend ans $r $t1ra($r) $t1rx($r) +} +maketest 1.5 {SELECT rowid, a, x FROM t1 ORDER BY +rowid DESC} $ans +maketest 1.6 {SELECT rowid, a, x FROM t1 ORDER BY rowid DESC} $ans + +set ans {} +foreach a [sort $all_a] { + set r $t1ar($a) + lappend ans $r $a $t1rx($r) +} +maketest 1.7 {SELECT rowid, a, x FROM t1 ORDER BY +a} $ans +maketest 1.8 {SELECT rowid, a, x FROM t1 ORDER BY a} $ans + +set ans {} +foreach a [reverse [sort $all_a]] { + set r $t1ar($a) + lappend ans $r $a $t1rx($r) +} +maketest 1.9 {SELECT rowid, a, x FROM t1 ORDER BY +a DESC} $ans +maketest 1.10 {SELECT rowid, a, x FROM t1 ORDER BY a DESC} $ans + +set ans {} +foreach x [sort $all_x] { + set r $t1xr($x) + lappend ans $r $t1ra($r) $x +} +maketest 1.11 {SELECT rowid, a, x FROM t1 ORDER BY +x} $ans +maketest 1.12 {SELECT rowid, a, x FROM t1 ORDER BY x} $ans + +set ans {} +foreach x [reverse [sort $all_x]] { + set r $t1xr($x) + lappend ans $r $t1ra($r) $x +} +maketest 1.13 {SELECT rowid, a, x FROM t1 ORDER BY +x DESC} $ans +maketest 1.14 {SELECT rowid, a, x FROM t1 ORDER BY x DESC} $ans + +maketest 2.1 {UPDATE t1 SET rowid=a, a=rowid} {} + +set ans {} +foreach r [sort $all_rowid] { + lappend ans $r $t1ra($r) $t1rx($r) +} +maketest 2.3 {SELECT a, rowid, x FROM t1 ORDER BY +a} $ans +maketest 2.4 {SELECT a, rowid, x FROM t1 ORDER BY a} $ans + +set ans {} +foreach r [reverse [sort $all_rowid]] { + lappend ans $r $t1ra($r) $t1rx($r) +} +maketest 2.5 {SELECT a, rowid, x FROM t1 ORDER BY +a DESC} $ans +maketest 2.6 {SELECT a, rowid, x FROM t1 ORDER BY a DESC} $ans + +set ans {} +foreach a [sort $all_a] { + set r $t1ar($a) + lappend ans $r $a $t1rx($r) +} +maketest 2.7 {SELECT a, rowid, x FROM t1 ORDER BY +rowid} $ans +maketest 2.8 {SELECT a, rowid, x FROM t1 ORDER BY rowid} $ans + +set ans {} +foreach a [reverse [sort $all_a]] { + set r $t1ar($a) + lappend ans $r $a $t1rx($r) +} +maketest 2.9 {SELECT a, rowid, x FROM t1 ORDER BY +rowid DESC} $ans +maketest 2.10 {SELECT a, rowid, x FROM t1 ORDER BY rowid DESC} $ans + +set ans {} +foreach x [sort $all_x] { + set r $t1xr($x) + lappend ans $r $t1ra($r) $x +} +maketest 2.11 {SELECT a, rowid, x FROM t1 ORDER BY +x} $ans +maketest 2.12 {SELECT a, rowid, x FROM t1 ORDER BY x} $ans + +set ans {} +foreach x [reverse [sort $all_x]] { + set r $t1xr($x) + lappend ans $r $t1ra($r) $x +} +maketest 2.13 {SELECT a, rowid, x FROM t1 ORDER BY +x DESC} $ans +maketest 2.14 {SELECT a, rowid, x FROM t1 ORDER BY x DESC} $ans + +maketest 3.1 {UPDATE t1 SET rowid=a, a=rowid} {} +maketest 3.2 {ALTER TABLE t1 ADD COLUMN z; UPDATE t1 SET z=zeroblob(600)} {} + +set ans {} +foreach r [sort $all_rowid] { + lappend ans $r $t1ra($r) $t1rx($r) +} +maketest 3.3 {SELECT rowid, a, x FROM t1 ORDER BY +rowid} $ans +maketest 3.4 {SELECT rowid, a, x FROM t1 ORDER BY rowid} $ans + +set ans {} +foreach r [reverse [sort $all_rowid]] { + lappend ans $r $t1ra($r) $t1rx($r) +} +maketest 3.5 {SELECT rowid, a, x FROM t1 ORDER BY +rowid DESC} $ans +maketest 3.6 {SELECT rowid, a, x FROM t1 ORDER BY rowid DESC} $ans + +set ans {} +foreach a [sort $all_a] { + set r $t1ar($a) + lappend ans $r $a $t1rx($r) +} +maketest 3.7 {SELECT rowid, a, x FROM t1 ORDER BY +a} $ans +maketest 3.8 {SELECT rowid, a, x FROM t1 ORDER BY a} $ans + +set ans {} +foreach a [reverse [sort $all_a]] { + set r $t1ar($a) + lappend ans $r $a $t1rx($r) +} +maketest 3.9 {SELECT rowid, a, x FROM t1 ORDER BY +a DESC} $ans +maketest 3.10 {SELECT rowid, a, x FROM t1 ORDER BY a DESC} $ans + +set ans {} +foreach x [sort $all_x] { + set r $t1xr($x) + lappend ans $r $t1ra($r) $x +} +maketest 3.11 {SELECT rowid, a, x FROM t1 ORDER BY +x} $ans +maketest 3.12 {SELECT rowid, a, x FROM t1 ORDER BY x} $ans + +set ans {} +foreach x [reverse [sort $all_x]] { + set r $t1xr($x) + lappend ans $r $t1ra($r) $x +} +maketest 3.13 {SELECT rowid, a, x FROM t1 ORDER BY +x DESC} $ans +maketest 3.14 {SELECT rowid, a, x FROM t1 ORDER BY x DESC} $ans + + +maketest 4.1 {UPDATE t1 SET rowid=a, a=rowid, x=z, z=x} {} + +set ans {} +foreach r [sort $all_rowid] { + lappend ans $r $t1ra($r) $t1rx($r) +} +maketest 4.3 {SELECT a, rowid, z FROM t1 ORDER BY +a} $ans +maketest 4.4 {SELECT a, rowid, z FROM t1 ORDER BY a} $ans + +set ans {} +foreach r [reverse [sort $all_rowid]] { + lappend ans $r $t1ra($r) $t1rx($r) +} +maketest 4.5 {SELECT a, rowid, z FROM t1 ORDER BY +a DESC} $ans +maketest 4.6 {SELECT a, rowid, z FROM t1 ORDER BY a DESC} $ans + +set ans {} +foreach a [sort $all_a] { + set r $t1ar($a) + lappend ans $r $a $t1rx($r) +} +maketest 4.7 {SELECT a, rowid, z FROM t1 ORDER BY +rowid} $ans +maketest 4.8 {SELECT a, rowid, z FROM t1 ORDER BY rowid} $ans + +set ans {} +foreach a [reverse [sort $all_a]] { + set r $t1ar($a) + lappend ans $r $a $t1rx($r) +} +maketest 4.9 {SELECT a, rowid, z FROM t1 ORDER BY +rowid DESC} $ans +maketest 4.10 {SELECT a, rowid, z FROM t1 ORDER BY rowid DESC} $ans + +set ans {} +foreach x [sort $all_x] { + set r $t1xr($x) + lappend ans $r $t1ra($r) $x +} +maketest 4.11 {SELECT a, rowid, z FROM t1 ORDER BY +z} $ans +maketest 4.12 {SELECT a, rowid, z FROM t1 ORDER BY z} $ans + +set ans {} +foreach x [reverse [sort $all_x]] { + set r $t1xr($x) + lappend ans $r $t1ra($r) $x +} +maketest 4.13 {SELECT a, rowid, z FROM t1 ORDER BY +z DESC} $ans +maketest 4.14 {SELECT a, rowid, z FROM t1 ORDER BY z DESC} $ans + +puts {finish_test} diff --git a/components/external/SQLite-3.8.1/test/boundary4.test b/components/external/SQLite-3.8.1/test/boundary4.test new file mode 100644 index 0000000000000000000000000000000000000000..b77ac3acf0bc91870acefdd1eb46fe327394f76d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/boundary4.test @@ -0,0 +1,343 @@ +# 2008 December 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is automatically generated from a separate TCL script. +# This file seeks to exercise integer boundary values. +# +# $Id: boundary4.test,v 1.2 2009/01/02 15:45:48 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Many of the boundary tests depend on a working 64-bit implementation. +if {![working_64bit_int]} { finish_test; return } +ifcapable !altertable { finish_test; return } + +do_test boundary4-1.1 { + db eval { + CREATE TABLE t1(a,x); + INSERT INTO t1(oid,a,x) VALUES(549755813887,1,'0000007fffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-8388608,2,'ffffffffff800000'); + INSERT INTO t1(oid,a,x) VALUES(0,3,'0000000000000000'); + INSERT INTO t1(oid,a,x) VALUES(-129,4,'ffffffffffffff7f'); + INSERT INTO t1(oid,a,x) VALUES(8388608,5,'0000000000800000'); + INSERT INTO t1(oid,a,x) VALUES(65535,6,'000000000000ffff'); + INSERT INTO t1(oid,a,x) VALUES(8388607,7,'00000000007fffff'); + INSERT INTO t1(oid,a,x) VALUES(1099511627776,8,'0000010000000000'); + INSERT INTO t1(oid,a,x) VALUES(16777215,9,'0000000000ffffff'); + INSERT INTO t1(oid,a,x) VALUES(32767,10,'0000000000007fff'); + INSERT INTO t1(oid,a,x) VALUES(4294967296,11,'0000000100000000'); + INSERT INTO t1(oid,a,x) VALUES(-549755813888,12,'ffffff8000000000'); + INSERT INTO t1(oid,a,x) VALUES(-140737488355328,13,'ffff800000000000'); + INSERT INTO t1(oid,a,x) VALUES(256,14,'0000000000000100'); + INSERT INTO t1(oid,a,x) VALUES(16777216,15,'0000000001000000'); + INSERT INTO t1(oid,a,x) VALUES(72057594037927936,16,'0100000000000000'); + INSERT INTO t1(oid,a,x) VALUES(-1,17,'ffffffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(9223372036854775807,18,'7fffffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(281474976710655,19,'0000ffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(1099511627775,20,'000000ffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-8388609,21,'ffffffffff7fffff'); + INSERT INTO t1(oid,a,x) VALUES(32768,22,'0000000000008000'); + INSERT INTO t1(oid,a,x) VALUES(36028797018963968,23,'0080000000000000'); + INSERT INTO t1(oid,a,x) VALUES(-32769,24,'ffffffffffff7fff'); + INSERT INTO t1(oid,a,x) VALUES(127,25,'000000000000007f'); + INSERT INTO t1(oid,a,x) VALUES(-9223372036854775808,26,'8000000000000000'); + INSERT INTO t1(oid,a,x) VALUES(72057594037927935,27,'00ffffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-549755813889,28,'ffffff7fffffffff'); + INSERT INTO t1(oid,a,x) VALUES(255,29,'00000000000000ff'); + INSERT INTO t1(oid,a,x) VALUES(-36028797018963969,30,'ff7fffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-2147483648,31,'ffffffff80000000'); + INSERT INTO t1(oid,a,x) VALUES(281474976710656,32,'0001000000000000'); + INSERT INTO t1(oid,a,x) VALUES(65536,33,'0000000000010000'); + INSERT INTO t1(oid,a,x) VALUES(140737488355328,34,'0000800000000000'); + INSERT INTO t1(oid,a,x) VALUES(549755813888,35,'0000008000000000'); + INSERT INTO t1(oid,a,x) VALUES(2147483648,36,'0000000080000000'); + INSERT INTO t1(oid,a,x) VALUES(4294967295,37,'00000000ffffffff'); + INSERT INTO t1(oid,a,x) VALUES(140737488355327,38,'00007fffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-2147483649,39,'ffffffff7fffffff'); + INSERT INTO t1(oid,a,x) VALUES(36028797018963967,40,'007fffffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(128,41,'0000000000000080'); + INSERT INTO t1(oid,a,x) VALUES(-32768,42,'ffffffffffff8000'); + INSERT INTO t1(oid,a,x) VALUES(-36028797018963968,43,'ff80000000000000'); + INSERT INTO t1(oid,a,x) VALUES(-140737488355329,44,'ffff7fffffffffff'); + INSERT INTO t1(oid,a,x) VALUES(-128,45,'ffffffffffffff80'); + INSERT INTO t1(oid,a,x) VALUES(2147483647,46,'000000007fffffff'); + CREATE INDEX t1i1 ON t1(a); + CREATE INDEX t1i2 ON t1(x); + } +} {} +do_test boundary4-1.2 { + db eval { + SELECT count(*) FROM t1 + } +} {46} +do_test boundary4-1.3 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +rowid + } +} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff} +do_test boundary4-1.4 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY rowid + } +} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff} +do_test boundary4-1.5 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +rowid DESC + } +} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000} +do_test boundary4-1.6 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY rowid DESC + } +} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000} +do_test boundary4-1.7 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +a + } +} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff} +do_test boundary4-1.8 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY a + } +} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff} +do_test boundary4-1.9 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +a DESC + } +} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff} +do_test boundary4-1.10 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY a DESC + } +} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff} +do_test boundary4-1.11 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +x + } +} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff} +do_test boundary4-1.12 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY x + } +} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff} +do_test boundary4-1.13 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +x DESC + } +} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000} +do_test boundary4-1.14 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY x DESC + } +} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000} +do_test boundary4-2.1 { + db eval { + UPDATE t1 SET rowid=a, a=rowid + } +} {} +do_test boundary4-2.3 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY +a + } +} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff} +do_test boundary4-2.4 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY a + } +} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff} +do_test boundary4-2.5 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY +a DESC + } +} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000} +do_test boundary4-2.6 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY a DESC + } +} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000} +do_test boundary4-2.7 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY +rowid + } +} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff} +do_test boundary4-2.8 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY rowid + } +} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff} +do_test boundary4-2.9 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY +rowid DESC + } +} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff} +do_test boundary4-2.10 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY rowid DESC + } +} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff} +do_test boundary4-2.11 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY +x + } +} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff} +do_test boundary4-2.12 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY x + } +} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff} +do_test boundary4-2.13 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY +x DESC + } +} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000} +do_test boundary4-2.14 { + db eval { + SELECT a, rowid, x FROM t1 ORDER BY x DESC + } +} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000} +do_test boundary4-3.1 { + db eval { + UPDATE t1 SET rowid=a, a=rowid + } +} {} +do_test boundary4-3.2 { + db eval { + ALTER TABLE t1 ADD COLUMN z; UPDATE t1 SET z=zeroblob(600) + } +} {} +do_test boundary4-3.3 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +rowid + } +} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff} +do_test boundary4-3.4 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY rowid + } +} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff} +do_test boundary4-3.5 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +rowid DESC + } +} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000} +do_test boundary4-3.6 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY rowid DESC + } +} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000} +do_test boundary4-3.7 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +a + } +} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff} +do_test boundary4-3.8 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY a + } +} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff} +do_test boundary4-3.9 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +a DESC + } +} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff} +do_test boundary4-3.10 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY a DESC + } +} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff} +do_test boundary4-3.11 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +x + } +} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff} +do_test boundary4-3.12 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY x + } +} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff} +do_test boundary4-3.13 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY +x DESC + } +} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000} +do_test boundary4-3.14 { + db eval { + SELECT rowid, a, x FROM t1 ORDER BY x DESC + } +} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000} +do_test boundary4-4.1 { + db eval { + UPDATE t1 SET rowid=a, a=rowid, x=z, z=x + } +} {} +do_test boundary4-4.3 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY +a + } +} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff} +do_test boundary4-4.4 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY a + } +} {-9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff 0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff} +do_test boundary4-4.5 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY +a DESC + } +} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000} +do_test boundary4-4.6 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY a DESC + } +} {9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000 -1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000} +do_test boundary4-4.7 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY +rowid + } +} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff} +do_test boundary4-4.8 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY rowid + } +} {549755813887 1 0000007fffffffff -8388608 2 ffffffffff800000 0 3 0000000000000000 -129 4 ffffffffffffff7f 8388608 5 0000000000800000 65535 6 000000000000ffff 8388607 7 00000000007fffff 1099511627776 8 0000010000000000 16777215 9 0000000000ffffff 32767 10 0000000000007fff 4294967296 11 0000000100000000 -549755813888 12 ffffff8000000000 -140737488355328 13 ffff800000000000 256 14 0000000000000100 16777216 15 0000000001000000 72057594037927936 16 0100000000000000 -1 17 ffffffffffffffff 9223372036854775807 18 7fffffffffffffff 281474976710655 19 0000ffffffffffff 1099511627775 20 000000ffffffffff -8388609 21 ffffffffff7fffff 32768 22 0000000000008000 36028797018963968 23 0080000000000000 -32769 24 ffffffffffff7fff 127 25 000000000000007f -9223372036854775808 26 8000000000000000 72057594037927935 27 00ffffffffffffff -549755813889 28 ffffff7fffffffff 255 29 00000000000000ff -36028797018963969 30 ff7fffffffffffff -2147483648 31 ffffffff80000000 281474976710656 32 0001000000000000 65536 33 0000000000010000 140737488355328 34 0000800000000000 549755813888 35 0000008000000000 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 140737488355327 38 00007fffffffffff -2147483649 39 ffffffff7fffffff 36028797018963967 40 007fffffffffffff 128 41 0000000000000080 -32768 42 ffffffffffff8000 -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -128 45 ffffffffffffff80 2147483647 46 000000007fffffff} +do_test boundary4-4.9 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY +rowid DESC + } +} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff} +do_test boundary4-4.10 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY rowid DESC + } +} {2147483647 46 000000007fffffff -128 45 ffffffffffffff80 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -32768 42 ffffffffffff8000 128 41 0000000000000080 36028797018963967 40 007fffffffffffff -2147483649 39 ffffffff7fffffff 140737488355327 38 00007fffffffffff 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 549755813888 35 0000008000000000 140737488355328 34 0000800000000000 65536 33 0000000000010000 281474976710656 32 0001000000000000 -2147483648 31 ffffffff80000000 -36028797018963969 30 ff7fffffffffffff 255 29 00000000000000ff -549755813889 28 ffffff7fffffffff 72057594037927935 27 00ffffffffffffff -9223372036854775808 26 8000000000000000 127 25 000000000000007f -32769 24 ffffffffffff7fff 36028797018963968 23 0080000000000000 32768 22 0000000000008000 -8388609 21 ffffffffff7fffff 1099511627775 20 000000ffffffffff 281474976710655 19 0000ffffffffffff 9223372036854775807 18 7fffffffffffffff -1 17 ffffffffffffffff 72057594037927936 16 0100000000000000 16777216 15 0000000001000000 256 14 0000000000000100 -140737488355328 13 ffff800000000000 -549755813888 12 ffffff8000000000 4294967296 11 0000000100000000 32767 10 0000000000007fff 16777215 9 0000000000ffffff 1099511627776 8 0000010000000000 8388607 7 00000000007fffff 65535 6 000000000000ffff 8388608 5 0000000000800000 -129 4 ffffffffffffff7f 0 3 0000000000000000 -8388608 2 ffffffffff800000 549755813887 1 0000007fffffffff} +do_test boundary4-4.11 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY +z + } +} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff} +do_test boundary4-4.12 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY z + } +} {0 3 0000000000000000 127 25 000000000000007f 128 41 0000000000000080 255 29 00000000000000ff 256 14 0000000000000100 32767 10 0000000000007fff 32768 22 0000000000008000 65535 6 000000000000ffff 65536 33 0000000000010000 8388607 7 00000000007fffff 8388608 5 0000000000800000 16777215 9 0000000000ffffff 16777216 15 0000000001000000 2147483647 46 000000007fffffff 2147483648 36 0000000080000000 4294967295 37 00000000ffffffff 4294967296 11 0000000100000000 549755813887 1 0000007fffffffff 549755813888 35 0000008000000000 1099511627775 20 000000ffffffffff 1099511627776 8 0000010000000000 140737488355327 38 00007fffffffffff 140737488355328 34 0000800000000000 281474976710655 19 0000ffffffffffff 281474976710656 32 0001000000000000 36028797018963967 40 007fffffffffffff 36028797018963968 23 0080000000000000 72057594037927935 27 00ffffffffffffff 72057594037927936 16 0100000000000000 9223372036854775807 18 7fffffffffffffff -9223372036854775808 26 8000000000000000 -36028797018963969 30 ff7fffffffffffff -36028797018963968 43 ff80000000000000 -140737488355329 44 ffff7fffffffffff -140737488355328 13 ffff800000000000 -549755813889 28 ffffff7fffffffff -549755813888 12 ffffff8000000000 -2147483649 39 ffffffff7fffffff -2147483648 31 ffffffff80000000 -8388609 21 ffffffffff7fffff -8388608 2 ffffffffff800000 -32769 24 ffffffffffff7fff -32768 42 ffffffffffff8000 -129 4 ffffffffffffff7f -128 45 ffffffffffffff80 -1 17 ffffffffffffffff} +do_test boundary4-4.13 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY +z DESC + } +} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000} +do_test boundary4-4.14 { + db eval { + SELECT a, rowid, z FROM t1 ORDER BY z DESC + } +} {-1 17 ffffffffffffffff -128 45 ffffffffffffff80 -129 4 ffffffffffffff7f -32768 42 ffffffffffff8000 -32769 24 ffffffffffff7fff -8388608 2 ffffffffff800000 -8388609 21 ffffffffff7fffff -2147483648 31 ffffffff80000000 -2147483649 39 ffffffff7fffffff -549755813888 12 ffffff8000000000 -549755813889 28 ffffff7fffffffff -140737488355328 13 ffff800000000000 -140737488355329 44 ffff7fffffffffff -36028797018963968 43 ff80000000000000 -36028797018963969 30 ff7fffffffffffff -9223372036854775808 26 8000000000000000 9223372036854775807 18 7fffffffffffffff 72057594037927936 16 0100000000000000 72057594037927935 27 00ffffffffffffff 36028797018963968 23 0080000000000000 36028797018963967 40 007fffffffffffff 281474976710656 32 0001000000000000 281474976710655 19 0000ffffffffffff 140737488355328 34 0000800000000000 140737488355327 38 00007fffffffffff 1099511627776 8 0000010000000000 1099511627775 20 000000ffffffffff 549755813888 35 0000008000000000 549755813887 1 0000007fffffffff 4294967296 11 0000000100000000 4294967295 37 00000000ffffffff 2147483648 36 0000000080000000 2147483647 46 000000007fffffff 16777216 15 0000000001000000 16777215 9 0000000000ffffff 8388608 5 0000000000800000 8388607 7 00000000007fffff 65536 33 0000000000010000 65535 6 000000000000ffff 32768 22 0000000000008000 32767 10 0000000000007fff 256 14 0000000000000100 255 29 00000000000000ff 128 41 0000000000000080 127 25 000000000000007f 0 3 0000000000000000} +finish_test diff --git a/components/external/SQLite-3.8.1/test/btreefault.test b/components/external/SQLite-3.8.1/test/btreefault.test new file mode 100644 index 0000000000000000000000000000000000000000..61104c5a79ada72c12a3bdf3b5ffaa33dfc0774f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/btreefault.test @@ -0,0 +1,57 @@ +# 2013 April 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains fault injection tests designed to test the btree.c +# module. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +set testprefix btreefault + +# This test will not work with an in-memory journal, as the database will +# become corrupt if an error is injected into a transaction after it starts +# writing data out to the db file. +if {[permutation]=="inmemory_journal"} { + finish_test + return +} + +do_test 1-pre1 { + execsql { + PRAGMA auto_vacuum = incremental; + PRAGMA journal_mode = DELETE; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(randomblob(1000), randomblob(100)); + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + DELETE FROM t1 WHERE rowid%2; + } + faultsim_save_and_close +} {} + +do_faultsim_test 1 -prep { + faultsim_restore_and_reopen + set ::STMT [sqlite3_prepare db "SELECT * FROM t1 ORDER BY a" -1 DUMMY] + sqlite3_step $::STMT + sqlite3_step $::STMT +} -body { + execsql { PRAGMA incremental_vacuum = 10 } +} -test { + sqlite3_finalize $::STMT + faultsim_test_result {0 {}} + faultsim_integrity_check +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/busy.test b/components/external/SQLite-3.8.1/test/busy.test new file mode 100644 index 0000000000000000000000000000000000000000..585f764547717a4f1b1b70240844b28b20f990d2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/busy.test @@ -0,0 +1,61 @@ +# 2005 july 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file test the busy handler +# +# $Id: busy.test,v 1.3 2008/03/15 02:09:22 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test busy-1.1 { + sqlite3 db2 test.db + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + SELECT * FROM t1 + } +} 1 +proc busy x { + lappend ::busyargs $x + if {$x>2} {return 1} + return 0 +} +set busyargs {} +do_test busy-1.2 { + db busy busy + db2 eval {BEGIN EXCLUSIVE} + catchsql {BEGIN IMMEDIATE} +} {1 {database is locked}} +do_test busy-1.3 { + set busyargs +} {0 1 2 3} +do_test busy-1.4 { + set busyargs {} + catchsql {BEGIN IMMEDIATE} + set busyargs +} {0 1 2 3} + +do_test busy-2.1 { + db2 eval {COMMIT} + db eval {BEGIN; INSERT INTO t1 VALUES(5)} + db2 eval {BEGIN; SELECT * FROM t1} + set busyargs {} + catchsql COMMIT +} {1 {database is locked}} +do_test busy-2.2 { + set busyargs +} {0 1 2 3} + + +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/cache.test b/components/external/SQLite-3.8.1/test/cache.test new file mode 100644 index 0000000000000000000000000000000000000000..ffc25c460e73be51b91c24021df5d531cc8881fe --- /dev/null +++ b/components/external/SQLite-3.8.1/test/cache.test @@ -0,0 +1,140 @@ +# 2007 March 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: cache.test,v 1.4 2007/08/22 02:56:44 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !pager_pragmas||!compound { + finish_test + return +} +sqlite3_soft_heap_limit 0 + +proc pager_cache_size {db} { + set bt [btree_from_db $db] + db_enter $db + array set stats [btree_pager_stats $bt] + db_leave $db + return $stats(page) +} + +if {[permutation] == ""} { + do_test cache-1.1 { pager_cache_size db } {0} +} + +do_test cache-1.2 { + execsql { + PRAGMA auto_vacuum=OFF; + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(1, 2, 3); + } + pager_cache_size db +} {2} + +# At one point, repeatedly locking and unlocking the cache was causing +# a resource leak of one page per repetition. The page wasn't actually +# leaked, but would not be reused until the pager-cache was full (i.e. +# 2000 pages by default). +# +# This tests that once the pager-cache is initialized, it can be locked +# and unlocked repeatedly without internally allocating any new pages. +# +set cache_size [pager_cache_size db] +for {set ii 0} {$ii < 10} {incr ii} { + do_test cache-1.3.$ii { + execsql {SELECT * FROM abc} + pager_cache_size db + } $::cache_size +} + +#------------------------------------------------------------------------- +# This block of tests checks that it is possible to set the cache_size of a +# database to a small (< 10) value. More specifically: +# +# cache-2.1.*: Test that "PRAGMA cache_size" appears to work with small +# values. +# cache-2.2.*: Test that "PRAGMA main.cache_size" appears to work with +# small values. +# cache-2.3.*: Test cache_size=1 correctly spills/flushes the cache. +# cache-2.4.*: Test cache_size=0 correctly spills/flushes the cache. +# +# +db_delete_and_reopen +do_execsql_test cache-2.0 { + PRAGMA auto_vacuum=OFF; + PRAGMA journal_mode=DELETE; + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); + INSERT INTO t1 VALUES('x', 'y'); + INSERT INTO t2 VALUES('i', 'j'); +} {delete} + +for {set i 0} {$i < 20} {incr i} { + do_execsql_test cache-2.1.$i.1 "PRAGMA cache_size = $i" + do_execsql_test cache-2.1.$i.2 "PRAGMA cache_size" $i + do_execsql_test cache-2.1.$i.3 "SELECT * FROM t1" {x y} + do_execsql_test cache-2.1.$i.4 "PRAGMA cache_size" $i +} +for {set i 0} {$i < 20} {incr i} { + do_execsql_test cache-2.2.$i.1 "PRAGMA main.cache_size = $i" + do_execsql_test cache-2.2.$i.2 "PRAGMA main.cache_size" $i + do_execsql_test cache-2.2.$i.3 "SELECT * FROM t1" {x y} + do_execsql_test cache-2.2.$i.4 "PRAGMA main.cache_size" $i +} + +# Tests for cache_size = 1. +# +do_execsql_test cache-2.3.1 { + PRAGMA cache_size = 1; + BEGIN; + INSERT INTO t1 VALUES(1, 2); + PRAGMA lock_status; +} {main reserved temp closed} +do_test cache-2.3.2 { pager_cache_size db } 2 +do_execsql_test cache-2.3.3 { + INSERT INTO t2 VALUES(1, 2); + PRAGMA lock_status; +} {main exclusive temp closed} +do_test cache-2.3.4 { pager_cache_size db } 2 +do_execsql_test cache-2.3.5 COMMIT +do_test cache-2.3.6 { pager_cache_size db } 1 + +do_execsql_test cache-2.3.7 { + SELECT * FROM t1 UNION SELECT * FROM t2; +} {1 2 i j x y} +do_test cache-2.3.8 { pager_cache_size db } 1 + +# Tests for cache_size = 0. +# +do_execsql_test cache-2.4.1 { + PRAGMA cache_size = 0; + BEGIN; + INSERT INTO t1 VALUES(1, 2); + PRAGMA lock_status; +} {main reserved temp closed} +do_test cache-2.4.2 { pager_cache_size db } 2 +do_execsql_test cache-2.4.3 { + INSERT INTO t2 VALUES(1, 2); + PRAGMA lock_status; +} {main exclusive temp closed} +do_test cache-2.4.4 { pager_cache_size db } 2 +do_execsql_test cache-2.4.5 COMMIT + +do_test cache-2.4.6 { pager_cache_size db } 0 +do_execsql_test cache-2.4.7 { + SELECT * FROM t1 UNION SELECT * FROM t2; +} {1 2 i j x y} +do_test cache-2.4.8 { pager_cache_size db } 0 + +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) +finish_test diff --git a/components/external/SQLite-3.8.1/test/capi2.test b/components/external/SQLite-3.8.1/test/capi2.test new file mode 100644 index 0000000000000000000000000000000000000000..20ee3401bf477ef0430aed4fdbc278e48eb08ae0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/capi2.test @@ -0,0 +1,803 @@ +# 2003 January 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the callback-free C/C++ API. +# +# $Id: capi2.test,v 1.37 2008/12/30 17:55:00 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Return the text values from the current row pointed at by STMT as a list. +proc get_row_values {STMT} { + set VALUES [list] + for {set i 0} {$i < [sqlite3_data_count $STMT]} {incr i} { + lappend VALUES [sqlite3_column_text $STMT $i] + } + return $VALUES +} + +# Return the column names followed by declaration types for the result set +# of the SQL statement STMT. +# +# i.e. for: +# CREATE TABLE abc(a text, b integer); +# SELECT * FROM abc; +# +# The result is {a b text integer} +proc get_column_names {STMT} { + set VALUES [list] + for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} { + lappend VALUES [sqlite3_column_name $STMT $i] + } + for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} { + lappend VALUES [sqlite3_column_decltype $STMT $i] + } + return $VALUES +} + +# Check basic functionality +# +do_test capi2-1.1 { + set DB [sqlite3_connection_pointer db] + execsql {CREATE TABLE t1(a,b,c)} + set VM [sqlite3_prepare $DB {SELECT name, rowid FROM sqlite_master} -1 TAIL] + set TAIL +} {} +do_test capi2-1.2 { + sqlite3_step $VM +} {SQLITE_ROW} +do_test capi2-1.3 { + sqlite3_data_count $VM +} {2} +do_test capi2-1.4 { + get_row_values $VM +} {t1 1} +do_test capi2-1.5 { + get_column_names $VM +} {name rowid text INTEGER} +do_test capi2-1.6 { + sqlite3_step $VM +} {SQLITE_DONE} +do_test capi2-1.7 { + list [sqlite3_column_count $VM] [get_row_values $VM] [get_column_names $VM] +} {2 {} {name rowid text INTEGER}} + +# This used to be SQLITE_MISUSE. But now we automatically reset prepared +# statements. +ifcapable autoreset { + do_test capi2-1.8 { + sqlite3_step $VM + } {SQLITE_ROW} +} else { + do_test capi2-1.8 { + sqlite3_step $VM + } {SQLITE_MISUSE} +} + +# Update: In v2, once SQLITE_MISUSE is returned the statement handle cannot +# be interrogated for more information. However in v3, since the column +# count, names and types are determined at compile time, these are still +# accessible after an SQLITE_MISUSE error. +do_test capi2-1.9 { + sqlite3_reset $VM + list [sqlite3_column_count $VM] [get_row_values $VM] [get_column_names $VM] +} {2 {} {name rowid text INTEGER}} +do_test capi2-1.10 { + sqlite3_data_count $VM +} {0} + +do_test capi2-1.11 { + sqlite3_finalize $VM +} {SQLITE_OK} + +# Check to make sure that the "tail" of a multi-statement SQL script +# is returned by sqlite3_prepare. +# +do_test capi2-2.1 { + set SQL { + SELECT name, rowid FROM sqlite_master; + SELECT name, rowid FROM sqlite_master WHERE 0; + -- A comment at the end + } + set VM [sqlite3_prepare $DB $SQL -1 SQL] + set SQL +} { + SELECT name, rowid FROM sqlite_master WHERE 0; + -- A comment at the end + } +do_test capi2-2.2 { + set r [sqlite3_step $VM] + lappend r [sqlite3_column_count $VM] \ + [get_row_values $VM] \ + [get_column_names $VM] +} {SQLITE_ROW 2 {t1 1} {name rowid text INTEGER}} +do_test capi2-2.3 { + set r [sqlite3_step $VM] + lappend r [sqlite3_column_count $VM] \ + [get_row_values $VM] \ + [get_column_names $VM] +} {SQLITE_DONE 2 {} {name rowid text INTEGER}} +do_test capi2-2.4 { + sqlite3_finalize $VM +} {SQLITE_OK} +do_test capi2-2.5 { + set VM [sqlite3_prepare $DB $SQL -1 SQL] + set SQL +} { + -- A comment at the end + } +do_test capi2-2.6 { + set r [sqlite3_step $VM] + lappend r [sqlite3_column_count $VM] \ + [get_row_values $VM] \ + [get_column_names $VM] +} {SQLITE_DONE 2 {} {name rowid text INTEGER}} +do_test capi2-2.7 { + sqlite3_finalize $VM +} {SQLITE_OK} +do_test capi2-2.8 { + set VM [sqlite3_prepare $DB $SQL -1 SQL] + list $SQL $VM +} {{} {}} + +# Check the error handling. +# +do_test capi2-3.1 { + set rc [catch { + sqlite3_prepare $DB {select bogus from sqlite_master} -1 TAIL + } msg] + lappend rc $msg $TAIL +} {1 {(1) no such column: bogus} {}} +do_test capi2-3.2 { + set rc [catch { + sqlite3_prepare $DB {select bogus from } -1 TAIL + } msg] + lappend rc $msg $TAIL +} {1 {(1) near " ": syntax error} {}} +do_test capi2-3.3 { + set rc [catch { + sqlite3_prepare $DB {;;;;select bogus from sqlite_master} -1 TAIL + } msg] + lappend rc $msg $TAIL +} {1 {(1) no such column: bogus} {}} +do_test capi2-3.4 { + set rc [catch { + sqlite3_prepare $DB {select bogus from sqlite_master;x;} -1 TAIL + } msg] + lappend rc $msg $TAIL +} {1 {(1) no such column: bogus} {x;}} +do_test capi2-3.5 { + set rc [catch { + sqlite3_prepare $DB {select bogus from sqlite_master;;;x;} -1 TAIL + } msg] + lappend rc $msg $TAIL +} {1 {(1) no such column: bogus} {;;x;}} +do_test capi2-3.6 { + set rc [catch { + sqlite3_prepare $DB {select 5/0} -1 TAIL + } VM] + lappend rc $TAIL +} {0 {}} +do_test capi2-3.7 { + list [sqlite3_step $VM] \ + [sqlite3_column_count $VM] \ + [get_row_values $VM] \ + [get_column_names $VM] +} {SQLITE_ROW 1 {{}} {5/0 {}}} +do_test capi2-3.8 { + sqlite3_finalize $VM +} {SQLITE_OK} +do_test capi2-3.9 { + execsql {CREATE UNIQUE INDEX i1 ON t1(a)} + set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES(1,2,3)} -1 TAIL] + set TAIL +} {} +do_test capi2-3.9b {db changes} {0} +do_test capi2-3.10 { + list [sqlite3_step $VM] \ + [sqlite3_column_count $VM] \ + [get_row_values $VM] \ + [get_column_names $VM] +} {SQLITE_DONE 0 {} {}} + +# Update for v3 - the change has not actually happened until the query is +# finalized. Is this going to cause trouble for anyone? Lee Nelson maybe? +# (Later:) The change now happens just before SQLITE_DONE is returned. +do_test capi2-3.10b {db changes} {1} +do_test capi2-3.11 { + sqlite3_finalize $VM +} {SQLITE_OK} +do_test capi2-3.11b {db changes} {1} +#do_test capi2-3.12-misuse { +# sqlite3_finalize $VM +#} {SQLITE_MISUSE} +do_test capi2-3.13 { + set VM [sqlite3_prepare $DB {INSERT INTO t1 VALUES(1,3,4)} -1 TAIL] + list [sqlite3_step $VM] \ + [sqlite3_column_count $VM] \ + [get_row_values $VM] \ + [get_column_names $VM] +} {SQLITE_ERROR 0 {} {}} + +# Update for v3: Preparing a statement does not affect the change counter. +# (Test result changes from 0 to 1). (Later:) change counter updates occur +# when sqlite3_step returns, not at finalize time. +do_test capi2-3.13b {db changes} {0} + +do_test capi2-3.14 { + list [sqlite3_finalize $VM] [sqlite3_errmsg $DB] \ + [sqlite3_extended_errcode $DB] +} {SQLITE_CONSTRAINT {column a is not unique} SQLITE_CONSTRAINT_UNIQUE} +do_test capi2-3.15 { + set VM [sqlite3_prepare $DB {CREATE TABLE t2(a NOT NULL, b)} -1 TAIL] + set TAIL +} {} +do_test capi2-3.16 { + list [sqlite3_step $VM] \ + [sqlite3_column_count $VM] \ + [get_row_values $VM] \ + [get_column_names $VM] +} {SQLITE_DONE 0 {} {}} +do_test capi2-3.17 { + list [sqlite3_finalize $VM] [sqlite3_errmsg $DB] +} {SQLITE_OK {not an error}} +do_test capi2-3.18 { + set VM [sqlite3_prepare $DB {INSERT INTO t2 VALUES(NULL,2)} -1 TAIL] + list [sqlite3_step $VM] \ + [sqlite3_column_count $VM] \ + [get_row_values $VM] \ + [get_column_names $VM] +} {SQLITE_ERROR 0 {} {}} +do_test capi2-3.19 { + list [sqlite3_finalize $VM] [sqlite3_errmsg $DB] \ + [sqlite3_extended_errcode $DB] +} {SQLITE_CONSTRAINT {t2.a may not be NULL} SQLITE_CONSTRAINT_NOTNULL} + +do_test capi2-3.20 { + execsql { + CREATE TABLE a1(message_id, name , UNIQUE(message_id, name) ); + INSERT INTO a1 VALUES(1, 1); + } +} {} +do_test capi2-3.21 { + set VM [sqlite3_prepare $DB {INSERT INTO a1 VALUES(1, 1)} -1 TAIL] + sqlite3_step $VM +} {SQLITE_ERROR} +do_test capi2-3.22 { + sqlite3_errcode $DB +} {SQLITE_ERROR} +do_test capi2-3.23 { + sqlite3_finalize $VM +} {SQLITE_CONSTRAINT} +do_test capi2-3.24 { + list [sqlite3_errcode $DB] [sqlite3_extended_errcode $DB] +} {SQLITE_CONSTRAINT SQLITE_CONSTRAINT_UNIQUE} + +# Two or more virtual machines exists at the same time. +# +do_test capi2-4.1 { + set VM1 [sqlite3_prepare $DB {INSERT INTO t2 VALUES(1,2)} -1 TAIL] + set TAIL +} {} +do_test capi2-4.2 { + set VM2 [sqlite3_prepare $DB {INSERT INTO t2 VALUES(2,3)} -1 TAIL] + set TAIL +} {} +do_test capi2-4.3 { + set VM3 [sqlite3_prepare $DB {INSERT INTO t2 VALUES(3,4)} -1 TAIL] + set TAIL +} {} +do_test capi2-4.4 { + list [sqlite3_step $VM2] \ + [sqlite3_column_count $VM2] \ + [get_row_values $VM2] \ + [get_column_names $VM2] +} {SQLITE_DONE 0 {} {}} +do_test capi2-4.5 { + execsql {SELECT * FROM t2 ORDER BY a} +} {2 3} +do_test capi2-4.6 { + sqlite3_finalize $VM2 +} {SQLITE_OK} +do_test capi2-4.7 { + list [sqlite3_step $VM3] \ + [sqlite3_column_count $VM3] \ + [get_row_values $VM3] \ + [get_column_names $VM3] +} {SQLITE_DONE 0 {} {}} +do_test capi2-4.8 { + execsql {SELECT * FROM t2 ORDER BY a} +} {2 3 3 4} +do_test capi2-4.9 { + sqlite3_finalize $VM3 +} {SQLITE_OK} +do_test capi2-4.10 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_DONE 0 {} {}} +do_test capi2-4.11 { + execsql {SELECT * FROM t2 ORDER BY a} +} {1 2 2 3 3 4} +do_test capi2-4.12 { + sqlite3_finalize $VM1 +} {SQLITE_OK} + +# Interleaved SELECTs +# +do_test capi2-5.1 { + set VM1 [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL] + set VM2 [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL] + set VM3 [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL] + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 2 {2 3} {a b {} {}}} +do_test capi2-5.2 { + list [sqlite3_step $VM2] \ + [sqlite3_column_count $VM2] \ + [get_row_values $VM2] \ + [get_column_names $VM2] +} {SQLITE_ROW 2 {2 3} {a b {} {}}} +do_test capi2-5.3 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 2 {3 4} {a b {} {}}} +do_test capi2-5.4 { + list [sqlite3_step $VM3] \ + [sqlite3_column_count $VM3] \ + [get_row_values $VM3] \ + [get_column_names $VM3] +} {SQLITE_ROW 2 {2 3} {a b {} {}}} +do_test capi2-5.5 { + list [sqlite3_step $VM3] \ + [sqlite3_column_count $VM3] \ + [get_row_values $VM3] \ + [get_column_names $VM3] +} {SQLITE_ROW 2 {3 4} {a b {} {}}} +do_test capi2-5.6 { + list [sqlite3_step $VM3] \ + [sqlite3_column_count $VM3] \ + [get_row_values $VM3] \ + [get_column_names $VM3] +} {SQLITE_ROW 2 {1 2} {a b {} {}}} +do_test capi2-5.7 { + list [sqlite3_step $VM3] \ + [sqlite3_column_count $VM3] \ + [get_row_values $VM3] \ + [get_column_names $VM3] +} {SQLITE_DONE 2 {} {a b {} {}}} +do_test capi2-5.8 { + sqlite3_finalize $VM3 +} {SQLITE_OK} +do_test capi2-5.9 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 2 {1 2} {a b {} {}}} +do_test capi2-5.10 { + sqlite3_finalize $VM1 +} {SQLITE_OK} +do_test capi2-5.11 { + list [sqlite3_step $VM2] \ + [sqlite3_column_count $VM2] \ + [get_row_values $VM2] \ + [get_column_names $VM2] +} {SQLITE_ROW 2 {3 4} {a b {} {}}} +do_test capi2-5.12 { + list [sqlite3_step $VM2] \ + [sqlite3_column_count $VM2] \ + [get_row_values $VM2] \ + [get_column_names $VM2] +} {SQLITE_ROW 2 {1 2} {a b {} {}}} +do_test capi2-5.11 { + sqlite3_finalize $VM2 +} {SQLITE_OK} + +# Check for proper SQLITE_BUSY returns. +# +do_test capi2-6.1 { + execsql { + BEGIN; + CREATE TABLE t3(x counter); + INSERT INTO t3 VALUES(1); + INSERT INTO t3 VALUES(2); + INSERT INTO t3 SELECT x+2 FROM t3; + INSERT INTO t3 SELECT x+4 FROM t3; + INSERT INTO t3 SELECT x+8 FROM t3; + COMMIT; + } + set VM1 [sqlite3_prepare $DB {SELECT * FROM t3} -1 TAIL] + sqlite3 db2 test.db + execsql {BEGIN} db2 +} {} +# Update for v3: BEGIN doesn't write-lock the database. It is quite +# difficult to get v3 to write-lock the database, which causes a few +# problems for test scripts. +# +# do_test capi2-6.2 { +# list [sqlite3_step $VM1] \ +# [sqlite3_column_count $VM1] \ +# [get_row_values $VM1] \ +# [get_column_names $VM1] +# } {SQLITE_BUSY 0 {} {}} +do_test capi2-6.3 { + execsql {COMMIT} db2 +} {} +do_test capi2-6.4 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 1 {x counter}} +do_test capi2-6.5 { + catchsql {INSERT INTO t3 VALUES(10);} db2 +} {1 {database is locked}} +do_test capi2-6.6 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 2 {x counter}} +do_test capi2-6.7 { + execsql {SELECT * FROM t2} db2 +} {2 3 3 4 1 2} +do_test capi2-6.8 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 3 {x counter}} +do_test capi2-6.9 { + execsql {SELECT * FROM t2} +} {2 3 3 4 1 2} +do_test capi2-6.10 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 4 {x counter}} +do_test capi2-6.11 { + execsql {BEGIN} +} {} +do_test capi2-6.12 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 5 {x counter}} + +# A read no longer blocks a write in the same connection. +#do_test capi2-6.13 { +# catchsql {UPDATE t3 SET x=x+1} +#} {1 {database table is locked}} + +do_test capi2-6.14 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 6 {x counter}} +do_test capi2-6.15 { + execsql {SELECT * FROM t1} +} {1 2 3} +do_test capi2-6.16 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 7 {x counter}} +do_test capi2-6.17 { + catchsql {UPDATE t1 SET b=b+1} +} {0 {}} +do_test capi2-6.18 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 8 {x counter}} +do_test capi2-6.19 { + execsql {SELECT * FROM t1} +} {1 3 3} +do_test capi2-6.20 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 9 {x counter}} +#do_test capi2-6.21 { +# execsql {ROLLBACK; SELECT * FROM t1} +#} {1 2 3} +do_test capi2-6.22 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 10 {x counter}} +#do_test capi2-6.23 { +# execsql {BEGIN TRANSACTION;} +#} {} +do_test capi2-6.24 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 11 {x counter}} +do_test capi2-6.25 { + execsql { + INSERT INTO t1 VALUES(2,3,4); + SELECT * FROM t1; + } +} {1 3 3 2 3 4} +do_test capi2-6.26 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 12 {x counter}} +do_test capi2-6.27 { + catchsql { + INSERT INTO t1 VALUES(2,4,5); + SELECT * FROM t1; + } +} {1 {column a is not unique}} +do_test capi2-6.28 { + list [sqlite3_step $VM1] \ + [sqlite3_column_count $VM1] \ + [get_row_values $VM1] \ + [get_column_names $VM1] +} {SQLITE_ROW 1 13 {x counter}} +do_test capi2-6.99 { + sqlite3_finalize $VM1 +} {SQLITE_OK} +catchsql {ROLLBACK} + +do_test capi2-7.1 { + stepsql $DB { + SELECT * FROM t1 + } +} {0 1 2 3} +do_test capi2-7.2 { + stepsql $DB { + PRAGMA count_changes=on + } +} {0} +do_test capi2-7.3 { + stepsql $DB { + UPDATE t1 SET a=a+10; + } +} {0 1} +do_test capi2-7.4 { + stepsql $DB { + INSERT INTO t1 SELECT a+1,b+1,c+1 FROM t1; + } +} {0 1} +do_test capi2-7.4b {sqlite3_changes $DB} {1} +do_test capi2-7.5 { + stepsql $DB { + UPDATE t1 SET a=a+10; + } +} {0 2} +do_test capi2-7.5b {sqlite3_changes $DB} {2} +do_test capi2-7.6 { + stepsql $DB { + SELECT * FROM t1; + } +} {0 21 2 3 22 3 4} +do_test capi2-7.7 { + stepsql $DB { + INSERT INTO t1 SELECT a+2,b+2,c+2 FROM t1; + } +} {0 2} +do_test capi2-7.8 { + sqlite3_changes $DB +} {2} +do_test capi2-7.9 { + stepsql $DB { + SELECT * FROM t1; + } +} {0 21 2 3 22 3 4 23 4 5 24 5 6} +do_test capi2-7.10 { + stepsql $DB { + UPDATE t1 SET a=a-20; + SELECT * FROM t1; + } +} {0 4 1 2 3 2 3 4 3 4 5 4 5 6} + +# Update for version 3: A SELECT statement no longer resets the change +# counter (Test result changes from 0 to 4). +do_test capi2-7.11 { + sqlite3_changes $DB +} {4} +do_test capi2-7.11a { + execsql {SELECT count(*) FROM t1} +} {4} + +ifcapable {explain} { + do_test capi2-7.12 { + set x [stepsql $DB {EXPLAIN SELECT * FROM t1}] + lindex $x 0 + } {0} +} + +# Ticket #261 - make sure we can finalize before the end of a query. +# +do_test capi2-8.1 { + set VM1 [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL] + sqlite3_finalize $VM1 +} {SQLITE_OK} + +# Tickets #384 and #385 - make sure the TAIL argument to sqlite3_prepare +# and all of the return pointers in sqlite_step can be null. +# +do_test capi2-9.1 { + set VM1 [sqlite3_prepare $DB {SELECT * FROM t2} -1 DUMMY] + sqlite3_step $VM1 + sqlite3_finalize $VM1 +} {SQLITE_OK} + +# Test that passing a NULL pointer to sqlite3_finalize() or sqlite3_reset +# does not cause an error. +do_test capi2-10.1 { + sqlite3_finalize 0 +} {SQLITE_OK} +do_test capi2-10.2 { + sqlite3_reset 0 +} {SQLITE_OK} + +#--------------------------------------------------------------------------- +# The following tests - capi2-11.* - test the "column origin" APIs. +# +# sqlite3_column_origin_name() +# sqlite3_column_database_name() +# sqlite3_column_table_name() +# + +ifcapable columnmetadata { + +# This proc uses the database handle $::DB to compile the SQL statement passed +# as a parameter. The return value of this procedure is a list with one +# element for each column returned by the compiled statement. Each element of +# this list is itself a list of length three, consisting of the origin +# database, table and column for the corresponding returned column. +proc check_origins {sql} { + set ret [list] + set ::STMT [sqlite3_prepare $::DB $sql -1 dummy] + for {set i 0} {$i < [sqlite3_column_count $::STMT]} {incr i} { + lappend ret [list \ + [sqlite3_column_database_name $::STMT $i] \ + [sqlite3_column_table_name $::STMT $i] \ + [sqlite3_column_origin_name $::STMT $i] \ + ] + } + sqlite3_finalize $::STMT + return $ret +} +do_test capi2-11.1 { + execsql { + CREATE TABLE tab1(col1, col2); + } +} {} +do_test capi2-11.2 { + check_origins {SELECT col2, col1 FROM tab1} +} [list {main tab1 col2} {main tab1 col1}] +do_test capi2-11.3 { + check_origins {SELECT col2 AS hello, col1 AS world FROM tab1} +} [list {main tab1 col2} {main tab1 col1}] + +ifcapable subquery { + do_test capi2-11.4 { + check_origins {SELECT b, a FROM (SELECT col1 AS a, col2 AS b FROM tab1)} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-11.5 { + check_origins {SELECT (SELECT col2 FROM tab1), (SELECT col1 FROM tab1)} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-11.6 { + check_origins {SELECT (SELECT col2), (SELECT col1) FROM tab1} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-11.7 { + check_origins {SELECT * FROM tab1} + } [list {main tab1 col1} {main tab1 col2}] + do_test capi2-11.8 { + check_origins {SELECT * FROM (SELECT * FROM tab1)} + } [list {main tab1 col1} {main tab1 col2}] +} + +ifcapable view&&subquery { + do_test capi2-12.1 { + execsql { + CREATE VIEW view1 AS SELECT * FROM tab1; + } + } {} + do_test capi2-12.2 { + check_origins {SELECT col2, col1 FROM view1} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-12.3 { + check_origins {SELECT col2 AS hello, col1 AS world FROM view1} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-12.4 { + check_origins {SELECT b, a FROM (SELECT col1 AS a, col2 AS b FROM view1)} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-12.5 { + check_origins {SELECT (SELECT col2 FROM view1), (SELECT col1 FROM view1)} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-12.6 { + check_origins {SELECT (SELECT col2), (SELECT col1) FROM view1} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-12.7 { + check_origins {SELECT * FROM view1} + } [list {main tab1 col1} {main tab1 col2}] + do_test capi2-12.8 { + check_origins {select * from (select * from view1)} + } [list {main tab1 col1} {main tab1 col2}] + do_test capi2-12.9 { + check_origins {select * from (select * from (select * from view1))} + } [list {main tab1 col1} {main tab1 col2}] + do_test capi2-12.10 { + db close + sqlite3 db test.db + set ::DB [sqlite3_connection_pointer db] + check_origins {select * from (select * from (select * from view1))} + } [list {main tab1 col1} {main tab1 col2}] + + # This view will thwart the flattening optimization. + do_test capi2-13.1 { + execsql { + CREATE VIEW view2 AS SELECT * FROM tab1 limit 10 offset 10; + } + } {} + do_test capi2-13.2 { + check_origins {SELECT col2, col1 FROM view2} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-13.3 { + check_origins {SELECT col2 AS hello, col1 AS world FROM view2} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-13.4 { + check_origins {SELECT b, a FROM (SELECT col1 AS a, col2 AS b FROM view2)} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-13.5 { + check_origins {SELECT (SELECT col2 FROM view2), (SELECT col1 FROM view2)} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-13.6 { + check_origins {SELECT (SELECT col2), (SELECT col1) FROM view2} + } [list {main tab1 col2} {main tab1 col1}] + do_test capi2-13.7 { + check_origins {SELECT * FROM view2} + } [list {main tab1 col1} {main tab1 col2}] + do_test capi2-13.8 { + check_origins {select * from (select * from view2)} + } [list {main tab1 col1} {main tab1 col2}] + do_test capi2-13.9 { + check_origins {select * from (select * from (select * from view2))} + } [list {main tab1 col1} {main tab1 col2}] + do_test capi2-13.10 { + db close + sqlite3 db test.db + set ::DB [sqlite3_connection_pointer db] + check_origins {select * from (select * from (select * from view2))} + } [list {main tab1 col1} {main tab1 col2}] + do_test capi2-13.11 { + check_origins {select * from (select * from tab1 limit 10 offset 10)} + } [list {main tab1 col1} {main tab1 col2}] +} + + +} ;# ifcapable columnmetadata + +db2 close +finish_test diff --git a/components/external/SQLite-3.8.1/test/capi3.test b/components/external/SQLite-3.8.1/test/capi3.test new file mode 100644 index 0000000000000000000000000000000000000000..9d7434d25d2247f8ebf6af66c4dcd4c3d0ef6363 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/capi3.test @@ -0,0 +1,1229 @@ +# 2003 January 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the callback-free C/C++ API. +# +# $Id: capi3.test,v 1.70 2009/01/09 02:49:32 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Return the UTF-16 representation of the supplied UTF-8 string $str. +# If $nt is true, append two 0x00 bytes as a nul terminator. +proc utf16 {str {nt 1}} { + set r [encoding convertto unicode $str] + if {$nt} { + append r "\x00\x00" + } + return $r +} + +# Return the UTF-8 representation of the supplied UTF-16 string $str. +proc utf8 {str} { + # If $str ends in two 0x00 0x00 bytes, knock these off before + # converting to UTF-8 using TCL. + binary scan $str \c* vals + if {[lindex $vals end]==0 && [lindex $vals end-1]==0} { + set str [binary format \c* [lrange $vals 0 end-2]] + } + + set r [encoding convertfrom unicode $str] + return $r +} + +# These tests complement those in capi2.test. They are organized +# as follows: +# +# capi3-1.*: Test sqlite3_prepare +# capi3-2.*: Test sqlite3_prepare16 +# capi3-3.*: Test sqlite3_open +# capi3-4.*: Test sqlite3_open16 +# capi3-5.*: Test the various sqlite3_result_* APIs +# capi3-6.*: Test that sqlite3_close fails if there are outstanding VMs. +# + +set DB [sqlite3_connection_pointer db] + +do_test capi3-1.0 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3-1.1 { + set STMT [sqlite3_prepare $DB {SELECT name FROM sqlite_master} -1 TAIL] + sqlite3_finalize $STMT + set TAIL +} {} +do_test capi3-1.2.1 { + sqlite3_errcode $DB +} {SQLITE_OK} +do_test capi3-1.2.2 { + sqlite3_extended_errcode $DB +} {SQLITE_OK} +do_test capi3-1.3 { + sqlite3_errmsg $DB +} {not an error} +do_test capi3-1.4 { + set sql {SELECT name FROM sqlite_master;SELECT 10} + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_finalize $STMT + set TAIL +} {SELECT 10} +do_test capi3-1.5 { + set sql {SELECT name FROM sqlite_master;SELECT 10} + set STMT [sqlite3_prepare $DB $sql [string length $sql] TAIL] + sqlite3_finalize $STMT + set TAIL +} {SELECT 10} +do_test capi3-1.6 { + set sql {SELECT name FROM sqlite_master;SELECT 10} + set STMT [sqlite3_prepare $DB $sql [expr [string length $sql]+1] TAIL] + sqlite3_finalize $STMT + set TAIL +} {SELECT 10} + +do_test capi3-1.7 { + set sql {SELECT namex FROM sqlite_master} + catch { + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + } +} {1} +do_test capi3-1.8.1 { + sqlite3_errcode $DB +} {SQLITE_ERROR} +do_test capi3-1.8.2 { + sqlite3_extended_errcode $DB +} {SQLITE_ERROR} +do_test capi3-1.9 { + sqlite3_errmsg $DB +} {no such column: namex} + +ifcapable {utf16} { + do_test capi3-2.1 { + set sql16 [utf16 {SELECT name FROM sqlite_master}] + set STMT [sqlite3_prepare16 $DB $sql16 -1 ::TAIL] + sqlite3_finalize $STMT + utf8 $::TAIL + } {} + do_test capi3-2.2 { + set sql [utf16 {SELECT name FROM sqlite_master;SELECT 10}] + set STMT [sqlite3_prepare16 $DB $sql -1 TAIL] + sqlite3_finalize $STMT + utf8 $TAIL + } {SELECT 10} + do_test capi3-2.3 { + set sql [utf16 {SELECT namex FROM sqlite_master}] + catch { + set STMT [sqlite3_prepare16 $DB $sql -1] + } + } {1} + do_test capi3-2.4.1 { + sqlite3_errcode $DB + } {SQLITE_ERROR} + do_test capi3-2.4.2 { + sqlite3_extended_errcode $DB + } {SQLITE_ERROR} + do_test capi3-2.5 { + sqlite3_errmsg $DB + } {no such column: namex} + + ifcapable schema_pragmas { + do_test capi3-2.6 { + execsql {CREATE TABLE tablename(x)} + set sql16 [utf16 {PRAGMA table_info("TableName"); --excess text}] + set STMT [sqlite3_prepare16 $DB $sql16 -1] + sqlite3_step $STMT + } SQLITE_ROW + do_test capi3-2.7 { + sqlite3_step $STMT + } SQLITE_DONE + do_test capi3-2.8 { + sqlite3_finalize $STMT + } SQLITE_OK + } + +} ;# endif utf16 + +# rename sqlite3_open sqlite3_open_old +# proc sqlite3_open {fname options} {sqlite3_open_new $fname $options} + +do_test capi3-3.1 { + set db2 [sqlite3_open test.db {}] + sqlite3_errcode $db2 +} {SQLITE_OK} +# FIX ME: Should test the db handle works. +do_test capi3-3.2 { + sqlite3_close $db2 +} {SQLITE_OK} +do_test capi3-3.3 { + catch { + set db2 [sqlite3_open /bogus/path/test.db {}] + } + sqlite3_extended_errcode $db2 +} {SQLITE_CANTOPEN} +do_test capi3-3.4 { + sqlite3_errmsg $db2 +} {unable to open database file} +do_test capi3-3.5 { + sqlite3_close $db2 +} {SQLITE_OK} +do_test capi3-3.6.1-misuse { + sqlite3_close $db2 +} {SQLITE_MISUSE} +do_test capi3-3.6.2-misuse { + sqlite3_errmsg $db2 +} {library routine called out of sequence} +ifcapable {utf16} { + do_test capi3-3.6.3-misuse { + utf8 [sqlite3_errmsg16 $db2] + } {library routine called out of sequence} +} + +do_test capi3-3.7 { + set db2 [sqlite3_open] + sqlite3_errcode $db2 +} {SQLITE_OK} +do_test capi3-3.8 { + sqlite3_close $db2 +} {SQLITE_OK} + +# rename sqlite3_open "" +# rename sqlite3_open_old sqlite3_open + +ifcapable {utf16} { +do_test capi3-4.1 { + set db2 [sqlite3_open16 [utf16 test.db] {}] + sqlite3_errcode $db2 +} {SQLITE_OK} +# FIX ME: Should test the db handle works. +do_test capi3-4.2 { + sqlite3_close $db2 +} {SQLITE_OK} +do_test capi3-4.3 { + catch { + set db2 [sqlite3_open16 [utf16 /bogus/path/test.db] {}] + } + sqlite3_errcode $db2 +} {SQLITE_CANTOPEN} +do_test capi3-4.4 { + utf8 [sqlite3_errmsg16 $db2] +} {unable to open database file} +do_test capi3-4.5 { + sqlite3_close $db2 +} {SQLITE_OK} +} ;# utf16 + +# This proc is used to test the following API calls: +# +# sqlite3_column_count +# sqlite3_column_name +# sqlite3_column_name16 +# sqlite3_column_decltype +# sqlite3_column_decltype16 +# +# $STMT is a compiled SQL statement. $test is a prefix +# to use for test names within this proc. $names is a list +# of the column names that should be returned by $STMT. +# $decltypes is a list of column declaration types for $STMT. +# +# Example: +# +# set STMT [sqlite3_prepare "SELECT 1, 2, 2;" -1 DUMMY] +# check_header test1.1 {1 2 3} {"" "" ""} +# +proc check_header {STMT test names decltypes} { + + # Use the return value of sqlite3_column_count() to build + # a list of column indexes. i.e. If sqlite3_column_count + # is 3, build the list {0 1 2}. + set ::idxlist [list] + set ::numcols [sqlite3_column_count $STMT] + for {set i 0} {$i < $::numcols} {incr i} {lappend ::idxlist $i} + + # Column names in UTF-8 + do_test $test.1 { + set cnamelist [list] + foreach i $idxlist {lappend cnamelist [sqlite3_column_name $STMT $i]} + set cnamelist + } $names + + # Column names in UTF-16 + ifcapable {utf16} { + do_test $test.2 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_name16 $STMT $i]] + } + set cnamelist + } $names + } + + # Column names in UTF-8 + do_test $test.3 { + set cnamelist [list] + foreach i $idxlist {lappend cnamelist [sqlite3_column_name $STMT $i]} + set cnamelist + } $names + + # Column names in UTF-16 + ifcapable {utf16} { + do_test $test.4 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_name16 $STMT $i]] + } + set cnamelist + } $names + } + + # Column names in UTF-8 + do_test $test.5 { + set cnamelist [list] + foreach i $idxlist {lappend cnamelist [sqlite3_column_decltype $STMT $i]} + set cnamelist + } $decltypes + + # Column declaration types in UTF-16 + ifcapable {utf16} { + do_test $test.6 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_decltype16 $STMT $i]] + } + set cnamelist + } $decltypes + } + + + # Test some out of range conditions: + ifcapable {utf16} { + do_test $test.7 { + list \ + [sqlite3_column_name $STMT -1] \ + [sqlite3_column_name16 $STMT -1] \ + [sqlite3_column_decltype $STMT -1] \ + [sqlite3_column_decltype16 $STMT -1] \ + [sqlite3_column_name $STMT $numcols] \ + [sqlite3_column_name16 $STMT $numcols] \ + [sqlite3_column_decltype $STMT $numcols] \ + [sqlite3_column_decltype16 $STMT $numcols] + } {{} {} {} {} {} {} {} {}} + } +} + +# This proc is used to test the following API calls: +# +# sqlite3_column_origin_name +# sqlite3_column_origin_name16 +# sqlite3_column_table_name +# sqlite3_column_table_name16 +# sqlite3_column_database_name +# sqlite3_column_database_name16 +# +# $STMT is a compiled SQL statement. $test is a prefix +# to use for test names within this proc. $names is a list +# of the column names that should be returned by $STMT. +# $decltypes is a list of column declaration types for $STMT. +# +# Example: +# +# set STMT [sqlite3_prepare "SELECT 1, 2, 2;" -1 DUMMY] +# check_header test1.1 {1 2 3} {"" "" ""} +# +proc check_origin_header {STMT test dbs tables cols} { + # If sqlite3_column_origin_name() and friends are not compiled into + # this build, this proc is a no-op. + ifcapable columnmetadata { + # Use the return value of sqlite3_column_count() to build + # a list of column indexes. i.e. If sqlite3_column_count + # is 3, build the list {0 1 2}. + set ::idxlist [list] + set ::numcols [sqlite3_column_count $STMT] + for {set i 0} {$i < $::numcols} {incr i} {lappend ::idxlist $i} + + # Database names in UTF-8 + do_test $test.8 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [sqlite3_column_database_name $STMT $i] + } + set cnamelist + } $dbs + + # Database names in UTF-16 + ifcapable {utf16} { + do_test $test.9 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_database_name16 $STMT $i]] + } + set cnamelist + } $dbs + } + + # Table names in UTF-8 + do_test $test.10 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [sqlite3_column_table_name $STMT $i] + } + set cnamelist + } $tables + + # Table names in UTF-16 + ifcapable {utf16} { + do_test $test.11 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_table_name16 $STMT $i]] + } + set cnamelist + } $tables + } + + # Origin names in UTF-8 + do_test $test.12 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [sqlite3_column_origin_name $STMT $i] + } + set cnamelist + } $cols + + # Origin declaration types in UTF-16 + ifcapable {utf16} { + do_test $test.13 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_origin_name16 $STMT $i]] + } + set cnamelist + } $cols + } + } +} + +# This proc is used to test the following APIs: +# +# sqlite3_data_count +# sqlite3_column_type +# sqlite3_column_int +# sqlite3_column_text +# sqlite3_column_text16 +# sqlite3_column_double +# +# $STMT is a compiled SQL statement for which the previous call +# to sqlite3_step returned SQLITE_ROW. $test is a prefix to use +# for test names within this proc. $types is a list of the +# manifest types for the current row. $ints, $doubles and $strings +# are lists of the integer, real and string representations of +# the values in the current row. +# +# Example: +# +# set STMT [sqlite3_prepare "SELECT 'hello', 1.1, NULL" -1 DUMMY] +# sqlite3_step $STMT +# check_data test1.2 {TEXT REAL NULL} {0 1 0} {0 1.1 0} {hello 1.1 {}} +# +proc check_data {STMT test types ints doubles strings} { + + # Use the return value of sqlite3_column_count() to build + # a list of column indexes. i.e. If sqlite3_column_count + # is 3, build the list {0 1 2}. + set ::idxlist [list] + set numcols [sqlite3_data_count $STMT] + for {set i 0} {$i < $numcols} {incr i} {lappend ::idxlist $i} + +# types +do_test $test.1 { + set types [list] + foreach i $idxlist {lappend types [sqlite3_column_type $STMT $i]} + set types +} $types + +# Integers +do_test $test.2 { + set ints [list] + foreach i $idxlist {lappend ints [sqlite3_column_int64 $STMT $i]} + set ints +} $ints + +# bytes +set lens [list] +foreach i $::idxlist { + lappend lens [string length [lindex $strings $i]] +} +do_test $test.3 { + set bytes [list] + set lens [list] + foreach i $idxlist { + lappend bytes [sqlite3_column_bytes $STMT $i] + } + set bytes +} $lens + +# bytes16 +ifcapable {utf16} { + set lens [list] + foreach i $::idxlist { + lappend lens [expr 2 * [string length [lindex $strings $i]]] + } + do_test $test.4 { + set bytes [list] + set lens [list] + foreach i $idxlist { + lappend bytes [sqlite3_column_bytes16 $STMT $i] + } + set bytes + } $lens +} + +# Blob +do_test $test.5 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_blob $STMT $i]} + set utf8 +} $strings + +# UTF-8 +do_test $test.6 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_text $STMT $i]} + set utf8 +} $strings + +# Floats +do_test $test.7 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_double $STMT $i]} + set utf8 +} $doubles + +# UTF-16 +ifcapable {utf16} { + do_test $test.8 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [utf8 [sqlite3_column_text16 $STMT $i]]} + set utf8 + } $strings +} + +# Integers +do_test $test.9 { + set ints [list] + foreach i $idxlist {lappend ints [sqlite3_column_int $STMT $i]} + set ints +} $ints + +# Floats +do_test $test.10 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_double $STMT $i]} + set utf8 +} $doubles + +# UTF-8 +do_test $test.11 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_text $STMT $i]} + set utf8 +} $strings + +# Types +do_test $test.12 { + set types [list] + foreach i $idxlist {lappend types [sqlite3_column_type $STMT $i]} + set types +} $types + +# Test that an out of range request returns the equivalent of NULL +do_test $test.13 { + sqlite3_column_int $STMT -1 +} {0} +do_test $test.13 { + sqlite3_column_text $STMT -1 +} {} + +} + +ifcapable !floatingpoint { + finish_test + return +} + +do_test capi3-5.0 { + execsql { + CREATE TABLE t1(a VARINT, b BLOB, c VARCHAR(16)); + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES('one', 'two', NULL); + INSERT INTO t1 VALUES(1.2, 1.3, 1.4); + } + set sql "SELECT * FROM t1" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_column_count $STMT +} 3 + +check_header $STMT capi3-5.1 {a b c} {VARINT BLOB VARCHAR(16)} +check_origin_header $STMT capi3-5.1 {main main main} {t1 t1 t1} {a b c} +do_test capi3-5.2 { + sqlite3_step $STMT +} SQLITE_ROW + +check_header $STMT capi3-5.3 {a b c} {VARINT BLOB VARCHAR(16)} +check_origin_header $STMT capi3-5.3 {main main main} {t1 t1 t1} {a b c} +check_data $STMT capi3-5.4 {INTEGER INTEGER TEXT} {1 2 3} {1.0 2.0 3.0} {1 2 3} + +do_test capi3-5.5 { + sqlite3_step $STMT +} SQLITE_ROW + +check_header $STMT capi3-5.6 {a b c} {VARINT BLOB VARCHAR(16)} +check_origin_header $STMT capi3-5.6 {main main main} {t1 t1 t1} {a b c} +check_data $STMT capi3-5.7 {TEXT TEXT NULL} {0 0 0} {0.0 0.0 0.0} {one two {}} + +do_test capi3-5.8 { + sqlite3_step $STMT +} SQLITE_ROW + +check_header $STMT capi3-5.9 {a b c} {VARINT BLOB VARCHAR(16)} +check_origin_header $STMT capi3-5.9 {main main main} {t1 t1 t1} {a b c} +check_data $STMT capi3-5.10 {FLOAT FLOAT TEXT} {1 1 1} {1.2 1.3 1.4} {1.2 1.3 1.4} + +do_test capi3-5.11 { + sqlite3_step $STMT +} SQLITE_DONE + +do_test capi3-5.12 { + sqlite3_finalize $STMT +} SQLITE_OK + +do_test capi3-5.20 { + set sql "SELECT a, sum(b), max(c) FROM t1 GROUP BY a" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_column_count $STMT +} 3 + +check_header $STMT capi3-5.21 {a sum(b) max(c)} {VARINT {} {}} +check_origin_header $STMT capi3-5.22 {main {} {}} {t1 {} {}} {a {} {}} +do_test capi3-5.23 { + sqlite3_finalize $STMT +} SQLITE_OK + +do_test capi3-5.30 { + set sql "SELECT a AS x, sum(b) AS y, max(c) AS z FROM t1 AS m GROUP BY x" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_column_count $STMT +} 3 + +check_header $STMT capi3-5.31 {x y z} {VARINT {} {}} +check_origin_header $STMT capi3-5.32 {main {} {}} {t1 {} {}} {a {} {}} +do_test capi3-5.33 { + sqlite3_finalize $STMT +} SQLITE_OK + + +set ::ENC [execsql {pragma encoding}] +db close + +do_test capi3-6.0 { + sqlite3 db test.db + set DB [sqlite3_connection_pointer db] + if {[sqlite3 -has-codec]==0} { sqlite3_key $DB xyzzy } + set sql {SELECT a FROM t1 order by rowid} + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + expr 0 +} {0} +do_test capi3-6.1 { + db cache flush + sqlite3_close $DB +} {SQLITE_BUSY} + +# 6.2 and 6.3 used to return SQLITE_ERROR and SQLITE_SCHEMA, respectively. +# But since attempting to close a connection no longer resets the internal +# schema and expires all statements, this is no longer the case. +do_test capi3-6.2 { + sqlite3_step $STMT +} {SQLITE_ROW} +#check_data $STMT capi3-6.3 {INTEGER} {1} {1.0} {1} +do_test capi3-6.3 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +do_test capi3-6.4-misuse { + db cache flush + sqlite3_close $DB +} {SQLITE_OK} +db close + +# This procedure sets the value of the file-format in file 'test.db' +# to $newval. Also, the schema cookie is incremented. +# +proc set_file_format {newval} { + hexio_write test.db 44 [hexio_render_int32 $newval] + set schemacookie [hexio_get_int [hexio_read test.db 40 4]] + incr schemacookie + hexio_write test.db 40 [hexio_render_int32 $schemacookie] + return {} +} + +# This procedure returns the value of the file-format in file 'test.db'. +# +proc get_file_format {{fname test.db}} { + return [hexio_get_int [hexio_read $fname 44 4]] +} + +if {![sqlite3 -has-codec]} { + # Test what happens when the library encounters a newer file format. + do_test capi3-7.1 { + set_file_format 5 + } {} + do_test capi3-7.2 { + catch { sqlite3 db test.db } + catchsql { + SELECT * FROM sqlite_master; + } + } {1 {unsupported file format}} + db close +} + +if {![sqlite3 -has-codec]} { + # Now test that the library correctly handles bogus entries in the + # sqlite_master table (schema corruption). + do_test capi3-8.1 { + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + CREATE TABLE t1(a); + } + db close + } {} + do_test capi3-8.2 { + sqlite3 db test.db + execsql { + PRAGMA writable_schema=ON; + INSERT INTO sqlite_master VALUES(NULL,NULL,NULL,NULL,NULL); + } + db close + } {} + do_test capi3-8.3 { + catch { sqlite3 db test.db } + catchsql { + SELECT * FROM sqlite_master; + } + } {1 {malformed database schema (?)}} + do_test capi3-8.4 { + # Build a 5-field row record. The first field is a string 'table', and + # subsequent fields are all NULL. + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + CREATE TABLE t1(a); + PRAGMA writable_schema=ON; + INSERT INTO sqlite_master VALUES('table',NULL,NULL,NULL,NULL); + } + db close + } {}; + do_test capi3-8.5 { + catch { sqlite3 db test.db } + catchsql { + SELECT * FROM sqlite_master; + } + } {1 {malformed database schema (?)}} + db close +} +forcedelete test.db +forcedelete test.db-journal + + +# Test the english language string equivalents for sqlite error codes +set code2english [list \ +SQLITE_OK {not an error} \ +SQLITE_ERROR {SQL logic error or missing database} \ +SQLITE_PERM {access permission denied} \ +SQLITE_ABORT {callback requested query abort} \ +SQLITE_BUSY {database is locked} \ +SQLITE_LOCKED {database table is locked} \ +SQLITE_NOMEM {out of memory} \ +SQLITE_READONLY {attempt to write a readonly database} \ +SQLITE_INTERRUPT {interrupted} \ +SQLITE_IOERR {disk I/O error} \ +SQLITE_CORRUPT {database disk image is malformed} \ +SQLITE_FULL {database or disk is full} \ +SQLITE_CANTOPEN {unable to open database file} \ +SQLITE_EMPTY {table contains no data} \ +SQLITE_SCHEMA {database schema has changed} \ +SQLITE_CONSTRAINT {constraint failed} \ +SQLITE_MISMATCH {datatype mismatch} \ +SQLITE_MISUSE {library routine called out of sequence} \ +SQLITE_NOLFS {large file support is disabled} \ +SQLITE_AUTH {authorization denied} \ +SQLITE_FORMAT {auxiliary database format error} \ +SQLITE_RANGE {bind or column index out of range} \ +SQLITE_NOTADB {file is encrypted or is not a database} \ +unknownerror {unknown error} \ +] + +set test_number 1 +foreach {code english} $code2english { + do_test capi3-9.$test_number "sqlite3_test_errstr $code" $english + incr test_number +} + +# Test the error message when a "real" out of memory occurs. +if { [permutation] != "nofaultsim" } { +ifcapable memdebug { + do_test capi3-10-1 { + sqlite3 db test.db + set DB [sqlite3_connection_pointer db] + sqlite3_memdebug_fail 1 + catchsql { + select * from sqlite_master; + } + } {1 {out of memory}} + do_test capi3-10-2 { + sqlite3_errmsg $::DB + } {out of memory} + ifcapable {utf16} { + do_test capi3-10-3 { + utf8 [sqlite3_errmsg16 $::DB] + } {out of memory} + } + db close + sqlite3_memdebug_fail -1 + do_test capi3-10-4 { + sqlite3 db test.db + set DB [sqlite3_connection_pointer db] + sqlite3_memdebug_fail 1 + catchsql { + select * from sqlite_master where rowid>5; + } + } {1 {out of memory}} + do_test capi3-10-5 { + sqlite3_errmsg $::DB + } {out of memory} + ifcapable {utf16} { + do_test capi3-10-6 { + utf8 [sqlite3_errmsg16 $::DB] + } {out of memory} + } + db close + sqlite3_memdebug_fail -1 +} +} + +# The following tests - capi3-11.* - test that a COMMIT or ROLLBACK +# statement issued while there are still outstanding VMs that are part of +# the transaction fails. +sqlite3 db test.db +set DB [sqlite3_connection_pointer db] +sqlite_register_test_function $DB func +do_test capi3-11.1 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 'int'); + INSERT INTO t1 VALUES(2, 'notatype'); + } +} {} +do_test capi3-11.1.1 { + sqlite3_get_autocommit $DB +} 0 +do_test capi3-11.2 { + set STMT [sqlite3_prepare $DB "SELECT func(b, a) FROM t1" -1 TAIL] + sqlite3_step $STMT +} {SQLITE_ROW} + +# As of 3.6.5 a COMMIT is OK during while a query is still running - +# as long as it is a read-only query and not an incremental BLOB write. +# +do_test capi3-11.3.1 { + catchsql { + COMMIT; + } +} {0 {}} +do_test capi3-11.3.2 { + sqlite3_extended_errcode $DB +} {SQLITE_OK} +do_test capi3-11.3.3 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3-11.3.4 { + db eval {PRAGMA lock_status} +} {main shared temp closed} + +do_test capi3-11.4 { + sqlite3_step $STMT +} {SQLITE_ERROR} +do_test capi3-11.5 { + sqlite3_finalize $STMT +} {SQLITE_ERROR} +do_test capi3-11.6 { + catchsql { + SELECT * FROM t1; + } +} {0 {1 int 2 notatype}} +do_test capi3-11.7 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3-11.8 { + execsql { + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(2); + BEGIN; + INSERT INTO t2 VALUES(3); + } +} {} +do_test capi3-11.8.1 { + sqlite3_get_autocommit $DB +} 0 +do_test capi3-11.9 { + set STMT [sqlite3_prepare $DB "SELECT a FROM t2" -1 TAIL] + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3-11.9.1 { + sqlite3_get_autocommit $DB +} 0 +do_test capi3-11.9.2 { + catchsql { + ROLLBACK; + } +} {0 {}} +do_test capi3-11.9.3 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3-11.10 { + sqlite3_step $STMT +} {SQLITE_ERROR} +ifcapable !autoreset { + # If SQLITE_OMIT_AUTORESET is defined, then the statement must be + # reset() before it can be passed to step() again. + do_test capi3-11.11a { sqlite3_step $STMT } {SQLITE_MISUSE} + do_test capi3-11.11b { sqlite3_reset $STMT } {SQLITE_ABORT} +} +do_test capi3-11.11 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3-11.12 { + sqlite3_step $STMT + sqlite3_step $STMT +} {SQLITE_DONE} +do_test capi3-11.13 { + sqlite3_finalize $STMT +} {SQLITE_OK} +do_test capi3-11.14 { + execsql { + SELECT a FROM t2; + } +} {1 2} +do_test capi3-11.14.1 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3-11.15 { + catchsql { + ROLLBACK; + } +} {1 {cannot rollback - no transaction is active}} +do_test capi3-11.15.1 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3-11.16 { + execsql { + SELECT a FROM t2; + } +} {1 2} + +# Sanity check on the definition of 'outstanding VM'. This means any VM +# that has had sqlite3_step() called more recently than sqlite3_finalize() or +# sqlite3_reset(). So a VM that has just been prepared or reset does not +# count as an active VM. +do_test capi3-11.17 { + execsql { + BEGIN; + } +} {} +do_test capi3-11.18 { + set STMT [sqlite3_prepare $DB "SELECT a FROM t1" -1 TAIL] + catchsql { + COMMIT; + } +} {0 {}} +do_test capi3-11.19 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3-11.20 { + catchsql { + BEGIN; + COMMIT; + } +} {0 {}} +do_test capi3-11.20 { + sqlite3_reset $STMT + catchsql { + COMMIT; + } +} {1 {cannot commit - no transaction is active}} +do_test capi3-11.21 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +# The following tests - capi3-12.* - check that its Ok to start a +# transaction while other VMs are active, and that its Ok to execute +# atomic updates in the same situation +# +do_test capi3-12.1 { + set STMT [sqlite3_prepare $DB "SELECT a FROM t2" -1 TAIL] + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3-12.2 { + catchsql { + INSERT INTO t1 VALUES(3, NULL); + } +} {0 {}} +do_test capi3-12.3 { + catchsql { + INSERT INTO t2 VALUES(4); + } +} {0 {}} +do_test capi3-12.4 { + catchsql { + BEGIN; + INSERT INTO t1 VALUES(4, NULL); + } +} {0 {}} +do_test capi3-12.5 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3-12.5.1 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3-12.6 { + sqlite3_step $STMT +} {SQLITE_DONE} +do_test capi3-12.7 { + sqlite3_finalize $STMT +} {SQLITE_OK} +do_test capi3-12.8 { + execsql { + COMMIT; + SELECT a FROM t1; + } +} {1 2 3 4} + +# Test cases capi3-13.* test the sqlite3_clear_bindings() and +# sqlite3_sleep APIs. +# +if {[llength [info commands sqlite3_clear_bindings]]>0} { + do_test capi3-13.1 { + execsql { + DELETE FROM t1; + } + set STMT [sqlite3_prepare $DB "INSERT INTO t1 VALUES(?, ?)" -1 TAIL] + sqlite3_step $STMT + } {SQLITE_DONE} + do_test capi3-13.2 { + sqlite3_reset $STMT + sqlite3_bind_text $STMT 1 hello 5 + sqlite3_bind_text $STMT 2 world 5 + sqlite3_step $STMT + } {SQLITE_DONE} + do_test capi3-13.3 { + sqlite3_reset $STMT + sqlite3_clear_bindings $STMT + sqlite3_step $STMT + } {SQLITE_DONE} + do_test capi3-13-4 { + sqlite3_finalize $STMT + execsql { + SELECT * FROM t1; + } + } {{} {} hello world {} {}} +} +if {[llength [info commands sqlite3_sleep]]>0} { + do_test capi3-13-5 { + set ms [sqlite3_sleep 80] + expr {$ms==80 || $ms==1000} + } {1} +} + +# Ticket #1219: Make sure binding APIs can handle a NULL pointer. +# +do_test capi3-14.1-misuse { + set rc [catch {sqlite3_bind_text 0 1 hello 5} msg] + lappend rc $msg +} {1 SQLITE_MISUSE} + +# Ticket #1650: Honor the nBytes parameter to sqlite3_prepare. +# +do_test capi3-15.1 { + set sql {SELECT * FROM t2} + set nbytes [string length $sql] + append sql { WHERE a==1} + set STMT [sqlite3_prepare $DB $sql $nbytes TAIL] + sqlite3_step $STMT + sqlite3_column_int $STMT 0 +} {1} +do_test capi3-15.2 { + sqlite3_step $STMT + sqlite3_column_int $STMT 0 +} {2} +do_test capi3-15.3 { + sqlite3_finalize $STMT +} {SQLITE_OK} +do_test capi3-15.4 { + # 123456789 1234567 + set sql {SELECT 1234567890} + set STMT [sqlite3_prepare $DB $sql 8 TAIL] + sqlite3_step $STMT + set v1 [sqlite3_column_int $STMT 0] + sqlite3_finalize $STMT + set v1 +} {1} +do_test capi3-15.5 { + # 123456789 1234567 + set sql {SELECT 1234567890} + set STMT [sqlite3_prepare $DB $sql 9 TAIL] + sqlite3_step $STMT + set v1 [sqlite3_column_int $STMT 0] + sqlite3_finalize $STMT + set v1 +} {12} +do_test capi3-15.6 { + # 123456789 1234567 + set sql {SELECT 1234567890} + set STMT [sqlite3_prepare $DB $sql 12 TAIL] + sqlite3_step $STMT + set v1 [sqlite3_column_int $STMT 0] + sqlite3_finalize $STMT + set v1 +} {12345} +do_test capi3-15.7 { + # 123456789 1234567 + set sql {SELECT 12.34567890} + set STMT [sqlite3_prepare $DB $sql 12 TAIL] + sqlite3_step $STMT + set v1 [sqlite3_column_double $STMT 0] + sqlite3_finalize $STMT + set v1 +} {12.34} +do_test capi3-15.8 { + # 123456789 1234567 + set sql {SELECT 12.34567890} + set STMT [sqlite3_prepare $DB $sql 14 TAIL] + sqlite3_step $STMT + set v1 [sqlite3_column_double $STMT 0] + sqlite3_finalize $STMT + set v1 +} {12.3456} + +# Make sure code is always generated even if an IF EXISTS or +# IF NOT EXISTS clause is present that the table does not or +# does exists. That way we will always have a prepared statement +# to expire when the schema changes. +# +do_test capi3-16.1 { + set sql {DROP TABLE IF EXISTS t3} + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_finalize $STMT + expr {$STMT!=""} +} {1} +do_test capi3-16.2 { + set sql {CREATE TABLE IF NOT EXISTS t1(x,y)} + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_finalize $STMT + expr {$STMT!=""} +} {1} + +# But still we do not generate code if there is no SQL +# +do_test capi3-16.3 { + set STMT [sqlite3_prepare $DB {} -1 TAIL] + sqlite3_finalize $STMT + expr {$STMT==""} +} {1} +do_test capi3-16.4 { + set STMT [sqlite3_prepare $DB {;} -1 TAIL] + sqlite3_finalize $STMT + expr {$STMT==""} +} {1} + +# Ticket #2426: Misuse of sqlite3_column_* by calling it after +# a sqlite3_reset should be harmless. +# +do_test capi3-17.1 { + set STMT [sqlite3_prepare $DB {SELECT * FROM t2} -1 TAIL] + sqlite3_step $STMT + sqlite3_column_int $STMT 0 +} {1} +do_test capi3-17.2 { + sqlite3_reset $STMT + sqlite3_column_int $STMT 0 +} {0} +do_test capi3-17.3 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +# Verify that sqlite3_step() fails with an SQLITE_SCHEMA error +# when the statement is prepared with sqlite3_prepare() (not +# sqlite3_prepare_v2()) and the schema has changed. +# +do_test capi3-18.1 { + set STMT [sqlite3_prepare db {SELECT * FROM t2} -1 TAIL] + sqlite3 db2 test.db + db2 eval {CREATE TABLE t3(x)} + db2 close + sqlite3_step $STMT +} {SQLITE_ERROR} +do_test capi3-18.2 { + sqlite3_reset $STMT + sqlite3_errcode db +} {SQLITE_SCHEMA} +do_test capi3-18.3 { + sqlite3_errmsg db +} {database schema has changed} +# The error persist on retry when sqlite3_prepare() has been used. +do_test capi3-18.4 { + sqlite3_step $STMT +} {SQLITE_ERROR} +do_test capi3-18.5 { + sqlite3_reset $STMT + sqlite3_errcode db +} {SQLITE_SCHEMA} +do_test capi3-18.6 { + sqlite3_errmsg db +} {database schema has changed} +sqlite3_finalize $STMT + +# Ticket #3134. Prepare a statement with an nBytes parameter of 0. +# Make sure this works correctly and does not reference memory out of +# range. +# +do_test capi3-19.1 { + sqlite3_prepare_tkt3134 db +} {} + +# Tests of the interface when no VFS is registered. +# +if {![info exists tester_do_binarylog]} { + db close + vfs_unregister_all + do_test capi3-20.1 { + sqlite3_sleep 100 + } {0} + vfs_reregister_all +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/capi3b.test b/components/external/SQLite-3.8.1/test/capi3b.test new file mode 100644 index 0000000000000000000000000000000000000000..72bbbaf65678938bcfb9fe072c55f675f00db2b8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/capi3b.test @@ -0,0 +1,145 @@ +# 2004 September 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the callback-free C/C++ API and in +# particular the behavior of sqlite3_step() when trying to commit +# with lock contention. +# +# $Id: capi3b.test,v 1.4 2007/08/10 19:46:14 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +# These tests depend on the pager holding changes in cache +# until it is time to commit. But that won't happen if the +# soft-heap-limit is set too low. So disable the soft heap limit +# for the duration of this test. +# +sqlite3_soft_heap_limit 0 + + +set DB [sqlite3_connection_pointer db] +sqlite3 db2 test.db +set DB2 [sqlite3_connection_pointer db2] + +# Create some data in the database +# +do_test capi3b-1.1 { + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + SELECT * FROM t1 + } +} {1 2} + +# Make sure the second database connection can see the data +# +do_test capi3b-1.2 { + execsql { + SELECT * FROM t1 + } db2 +} {1 2} + +# First database connection acquires a shared lock +# +do_test capi3b-1.3 { + execsql { + BEGIN; + SELECT * FROM t1; + } +} {1 2} + +# Second database connection tries to write. The sqlite3_step() +# function returns SQLITE_BUSY because it cannot commit. +# +do_test capi3b-1.4 { + set VM [sqlite3_prepare $DB2 {INSERT INTO t1 VALUES(3)} -1 TAIL] + sqlite3_step $VM +} SQLITE_BUSY + +# The sqlite3_step call can be repeated multiple times. +# +do_test capi3b-1.5.1 { + sqlite3_step $VM +} SQLITE_BUSY +do_test capi3b-1.5.2 { + sqlite3_step $VM +} SQLITE_BUSY + +# The first connection closes its transaction. This allows the second +# connections sqlite3_step to succeed. +# +do_test capi3b-1.6 { + execsql COMMIT + sqlite3_step $VM +} SQLITE_DONE +do_test capi3b-1.7 { + sqlite3_finalize $VM +} SQLITE_OK +do_test capi3b-1.8 { + execsql {SELECT * FROM t1} db2 +} {1 2 3} +do_test capi3b-1.9 { + execsql {SELECT * FROM t1} +} {1 2 3} + +# Start doing a SELECT with one connection. This gets a SHARED lock. +# Then do an INSERT with the other connection. The INSERT should +# not be able to complete until the SELECT finishes. +# +do_test capi3b-2.1 { + set VM1 [sqlite3_prepare $DB {SELECT * FROM t1} -1 TAIL] + sqlite3_step $VM1 +} SQLITE_ROW +do_test capi3b-2.2 { + sqlite3_column_text $VM1 0 +} 1 +do_test capi3b-2.3 { + set VM2 [sqlite3_prepare $DB2 {INSERT INTO t1 VALUES(4)} -1 TAIL] + sqlite3_step $VM2 +} SQLITE_BUSY +do_test capi3b-2.4 { + sqlite3_step $VM1 +} SQLITE_ROW +do_test capi3b-2.5 { + sqlite3_column_text $VM1 0 +} 2 +do_test capi3b-2.6 { + sqlite3_step $VM2 +} SQLITE_BUSY +do_test capi3b-2.7 { + sqlite3_step $VM1 +} SQLITE_ROW +do_test capi3b-2.8 { + sqlite3_column_text $VM1 0 +} 3 +do_test capi3b-2.9 { + sqlite3_step $VM2 +} SQLITE_BUSY +do_test capi3b-2.10 { + sqlite3_step $VM1 +} SQLITE_DONE +do_test capi3b-2.11 { + sqlite3_step $VM2 +} SQLITE_DONE +do_test capi3b-2.12 { + sqlite3_finalize $VM1 + sqlite3_finalize $VM2 + execsql {SELECT * FROM t1} +} {1 2 3 4} + +catch {db2 close} + +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) +finish_test diff --git a/components/external/SQLite-3.8.1/test/capi3c.test b/components/external/SQLite-3.8.1/test/capi3c.test new file mode 100644 index 0000000000000000000000000000000000000000..14545c0a68ddb42bc83286ccd1967072dc1965a3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/capi3c.test @@ -0,0 +1,1372 @@ +# 2006 November 08 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This is a copy of the capi3.test file that has been adapted to +# test the new sqlite3_prepare_v2 interface. +# +# $Id: capi3c.test,v 1.23 2009/07/22 07:27:57 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Return the UTF-16 representation of the supplied UTF-8 string $str. +# If $nt is true, append two 0x00 bytes as a nul terminator. +proc utf16 {str {nt 1}} { + set r [encoding convertto unicode $str] + if {$nt} { + append r "\x00\x00" + } + return $r +} + +# Return the UTF-8 representation of the supplied UTF-16 string $str. +proc utf8 {str} { + # If $str ends in two 0x00 0x00 bytes, knock these off before + # converting to UTF-8 using TCL. + binary scan $str \c* vals + if {[lindex $vals end]==0 && [lindex $vals end-1]==0} { + set str [binary format \c* [lrange $vals 0 end-2]] + } + + set r [encoding convertfrom unicode $str] + return $r +} + +# These tests complement those in capi2.test. They are organized +# as follows: +# +# capi3c-1.*: Test sqlite3_prepare_v2 +# capi3c-2.*: Test sqlite3_prepare16_v2 +# capi3c-3.*: Test sqlite3_open +# capi3c-4.*: Test sqlite3_open16 +# capi3c-5.*: Test the various sqlite3_result_* APIs +# capi3c-6.*: Test that sqlite3_close fails if there are outstanding VMs. +# + +set DB [sqlite3_connection_pointer db] + +do_test capi3c-1.0 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3c-1.1 { + set STMT [sqlite3_prepare_v2 $DB {SELECT name FROM sqlite_master} -1 TAIL] + sqlite3_finalize $STMT + set TAIL +} {} +do_test capi3c-1.2.1 { + sqlite3_errcode $DB +} {SQLITE_OK} +do_test capi3c-1.2.2 { + sqlite3_extended_errcode $DB +} {SQLITE_OK} +do_test capi3c-1.3 { + sqlite3_errmsg $DB +} {not an error} +do_test capi3c-1.4 { + set sql {SELECT name FROM sqlite_master;SELECT 10} + set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL] + sqlite3_finalize $STMT + set TAIL +} {SELECT 10} +do_test capi3c-1.5 { + set sql {SELECT namex FROM sqlite_master} + catch { + set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL] + } +} {1} +do_test capi3c-1.6.1 { + sqlite3_errcode $DB +} {SQLITE_ERROR} +do_test capi3c-1.6.2 { + sqlite3_extended_errcode $DB +} {SQLITE_ERROR} +do_test capi3c-1.7 { + sqlite3_errmsg $DB +} {no such column: namex} + + +ifcapable {utf16} { + do_test capi3c-2.1 { + set sql16 [utf16 {SELECT name FROM sqlite_master}] + set STMT [sqlite3_prepare16_v2 $DB $sql16 -1 ::TAIL] + sqlite3_finalize $STMT + utf8 $::TAIL + } {} + do_test capi3c-2.2 { + set sql [utf16 {SELECT name FROM sqlite_master;SELECT 10}] + set STMT [sqlite3_prepare16_v2 $DB $sql -1 TAIL] + sqlite3_finalize $STMT + utf8 $TAIL + } {SELECT 10} + do_test capi3c-2.3 { + set sql [utf16 {SELECT namex FROM sqlite_master}] + catch { + set STMT [sqlite3_prepare16_v2 $DB $sql -1 TAIL] + } + } {1} + do_test capi3c-2.4.1 { + sqlite3_errcode $DB + } {SQLITE_ERROR} + do_test capi3c-2.4.2 { + sqlite3_extended_errcode $DB + } {SQLITE_ERROR} + do_test capi3c-2.5 { + sqlite3_errmsg $DB + } {no such column: namex} + + ifcapable schema_pragmas { + do_test capi3c-2.6 { + execsql {CREATE TABLE tablename(x)} + set sql16 [utf16 {PRAGMA table_info("TableName")}] + set STMT [sqlite3_prepare16_v2 $DB $sql16 -1 TAIL] + sqlite3_step $STMT + } SQLITE_ROW + do_test capi3c-2.7 { + sqlite3_step $STMT + } SQLITE_DONE + do_test capi3c-2.8 { + sqlite3_finalize $STMT + } SQLITE_OK + } + +} ;# endif utf16 + +# rename sqlite3_open sqlite3_open_old +# proc sqlite3_open {fname options} {sqlite3_open_new $fname $options} + +do_test capi3c-3.1 { + set db2 [sqlite3_open test.db {}] + sqlite3_errcode $db2 +} {SQLITE_OK} +# FIX ME: Should test the db handle works. +do_test capi3c-3.2 { + sqlite3_close $db2 +} {SQLITE_OK} +do_test capi3c-3.3 { + catch { + set db2 [sqlite3_open /bogus/path/test.db {}] + } + sqlite3_errcode $db2 +} {SQLITE_CANTOPEN} +do_test capi3c-3.4 { + sqlite3_errmsg $db2 +} {unable to open database file} +do_test capi3c-3.5 { + sqlite3_close $db2 +} {SQLITE_OK} +do_test capi3c-3.6.1-misuse { + sqlite3_close $db2 +} {SQLITE_MISUSE} +do_test capi3c-3.6.2-misuse { + sqlite3_errmsg $db2 +} {library routine called out of sequence} +ifcapable {utf16} { + do_test capi3c-3.6.3-misuse { + utf8 [sqlite3_errmsg16 $db2] + } {library routine called out of sequence} +} + +# rename sqlite3_open "" +# rename sqlite3_open_old sqlite3_open + +ifcapable {utf16} { +do_test capi3c-4.1 { + set db2 [sqlite3_open16 [utf16 test.db] {}] + sqlite3_errcode $db2 +} {SQLITE_OK} +# FIX ME: Should test the db handle works. +do_test capi3c-4.2 { + sqlite3_close $db2 +} {SQLITE_OK} +do_test capi3c-4.3 { + catch { + set db2 [sqlite3_open16 [utf16 /bogus/path/test.db] {}] + } + sqlite3_errcode $db2 +} {SQLITE_CANTOPEN} +do_test capi3c-4.4 { + utf8 [sqlite3_errmsg16 $db2] +} {unable to open database file} +do_test capi3c-4.5 { + sqlite3_close $db2 +} {SQLITE_OK} +} ;# utf16 + +# This proc is used to test the following API calls: +# +# sqlite3_column_count +# sqlite3_column_name +# sqlite3_column_name16 +# sqlite3_column_decltype +# sqlite3_column_decltype16 +# +# $STMT is a compiled SQL statement. $test is a prefix +# to use for test names within this proc. $names is a list +# of the column names that should be returned by $STMT. +# $decltypes is a list of column declaration types for $STMT. +# +# Example: +# +# set STMT [sqlite3_prepare_v2 "SELECT 1, 2, 2;" -1 DUMMY] +# check_header test1.1 {1 2 3} {"" "" ""} +# +proc check_header {STMT test names decltypes} { + + # Use the return value of sqlite3_column_count() to build + # a list of column indexes. i.e. If sqlite3_column_count + # is 3, build the list {0 1 2}. + set ::idxlist [list] + set ::numcols [sqlite3_column_count $STMT] + for {set i 0} {$i < $::numcols} {incr i} {lappend ::idxlist $i} + + # Column names in UTF-8 + do_test $test.1 { + set cnamelist [list] + foreach i $idxlist {lappend cnamelist [sqlite3_column_name $STMT $i]} + set cnamelist + } $names + + # Column names in UTF-16 + ifcapable {utf16} { + do_test $test.2 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_name16 $STMT $i]] + } + set cnamelist + } $names + } + + # Column names in UTF-8 + do_test $test.3 { + set cnamelist [list] + foreach i $idxlist {lappend cnamelist [sqlite3_column_name $STMT $i]} + set cnamelist + } $names + + # Column names in UTF-16 + ifcapable {utf16} { + do_test $test.4 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_name16 $STMT $i]] + } + set cnamelist + } $names + } + + # Column names in UTF-8 + do_test $test.5 { + set cnamelist [list] + foreach i $idxlist {lappend cnamelist [sqlite3_column_decltype $STMT $i]} + set cnamelist + } $decltypes + + # Column declaration types in UTF-16 + ifcapable {utf16} { + do_test $test.6 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_decltype16 $STMT $i]] + } + set cnamelist + } $decltypes + } + + + # Test some out of range conditions: + ifcapable {utf16} { + do_test $test.7 { + list \ + [sqlite3_column_name $STMT -1] \ + [sqlite3_column_name16 $STMT -1] \ + [sqlite3_column_decltype $STMT -1] \ + [sqlite3_column_decltype16 $STMT -1] \ + [sqlite3_column_name $STMT $numcols] \ + [sqlite3_column_name16 $STMT $numcols] \ + [sqlite3_column_decltype $STMT $numcols] \ + [sqlite3_column_decltype16 $STMT $numcols] + } {{} {} {} {} {} {} {} {}} + } +} + +# This proc is used to test the following API calls: +# +# sqlite3_column_origin_name +# sqlite3_column_origin_name16 +# sqlite3_column_table_name +# sqlite3_column_table_name16 +# sqlite3_column_database_name +# sqlite3_column_database_name16 +# +# $STMT is a compiled SQL statement. $test is a prefix +# to use for test names within this proc. $names is a list +# of the column names that should be returned by $STMT. +# $decltypes is a list of column declaration types for $STMT. +# +# Example: +# +# set STMT [sqlite3_prepare_v2 "SELECT 1, 2, 2;" -1 DUMMY] +# check_header test1.1 {1 2 3} {"" "" ""} +# +proc check_origin_header {STMT test dbs tables cols} { + # If sqlite3_column_origin_name() and friends are not compiled into + # this build, this proc is a no-op. +ifcapable columnmetadata { + + # Use the return value of sqlite3_column_count() to build + # a list of column indexes. i.e. If sqlite3_column_count + # is 3, build the list {0 1 2}. + set ::idxlist [list] + set ::numcols [sqlite3_column_count $STMT] + for {set i 0} {$i < $::numcols} {incr i} {lappend ::idxlist $i} + + # Database names in UTF-8 + do_test $test.8 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [sqlite3_column_database_name $STMT $i] + } + set cnamelist + } $dbs + + # Database names in UTF-16 + ifcapable {utf16} { + do_test $test.9 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_database_name16 $STMT $i]] + } + set cnamelist + } $dbs + } + + # Table names in UTF-8 + do_test $test.10 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [sqlite3_column_table_name $STMT $i] + } + set cnamelist + } $tables + + # Table names in UTF-16 + ifcapable {utf16} { + do_test $test.11 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_table_name16 $STMT $i]] + } + set cnamelist + } $tables + } + + # Origin names in UTF-8 + do_test $test.12 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [sqlite3_column_origin_name $STMT $i] + } + set cnamelist + } $cols + + # Origin declaration types in UTF-16 + ifcapable {utf16} { + do_test $test.13 { + set cnamelist [list] + foreach i $idxlist { + lappend cnamelist [utf8 [sqlite3_column_origin_name16 $STMT $i]] + } + set cnamelist + } $cols + } + } +} + +# This proc is used to test the following APIs: +# +# sqlite3_data_count +# sqlite3_column_type +# sqlite3_column_int +# sqlite3_column_text +# sqlite3_column_text16 +# sqlite3_column_double +# +# $STMT is a compiled SQL statement for which the previous call +# to sqlite3_step returned SQLITE_ROW. $test is a prefix to use +# for test names within this proc. $types is a list of the +# manifest types for the current row. $ints, $doubles and $strings +# are lists of the integer, real and string representations of +# the values in the current row. +# +# Example: +# +# set STMT [sqlite3_prepare_v2 "SELECT 'hello', 1.1, NULL" -1 DUMMY] +# sqlite3_step $STMT +# check_data test1.2 {TEXT REAL NULL} {0 1 0} {0 1.1 0} {hello 1.1 {}} +# +proc check_data {STMT test types ints doubles strings} { + + # Use the return value of sqlite3_column_count() to build + # a list of column indexes. i.e. If sqlite3_column_count + # is 3, build the list {0 1 2}. + set ::idxlist [list] + set numcols [sqlite3_data_count $STMT] + for {set i 0} {$i < $numcols} {incr i} {lappend ::idxlist $i} + +# types +do_test $test.1 { + set types [list] + foreach i $idxlist {lappend types [sqlite3_column_type $STMT $i]} + set types +} $types + +# Integers +do_test $test.2 { + set ints [list] + foreach i $idxlist {lappend ints [sqlite3_column_int64 $STMT $i]} + set ints +} $ints + +# bytes +set lens [list] +foreach i $::idxlist { + lappend lens [string length [lindex $strings $i]] +} +do_test $test.3 { + set bytes [list] + set lens [list] + foreach i $idxlist { + lappend bytes [sqlite3_column_bytes $STMT $i] + } + set bytes +} $lens + +# bytes16 +ifcapable {utf16} { + set lens [list] + foreach i $::idxlist { + lappend lens [expr 2 * [string length [lindex $strings $i]]] + } + do_test $test.4 { + set bytes [list] + set lens [list] + foreach i $idxlist { + lappend bytes [sqlite3_column_bytes16 $STMT $i] + } + set bytes + } $lens +} + +# Blob +do_test $test.5 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_blob $STMT $i]} + set utf8 +} $strings + +# UTF-8 +do_test $test.6 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_text $STMT $i]} + set utf8 +} $strings + +# Floats +do_test $test.7 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_double $STMT $i]} + set utf8 +} $doubles + +# UTF-16 +ifcapable {utf16} { + do_test $test.8 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [utf8 [sqlite3_column_text16 $STMT $i]]} + set utf8 + } $strings +} + +# Integers +do_test $test.9 { + set ints [list] + foreach i $idxlist {lappend ints [sqlite3_column_int $STMT $i]} + set ints +} $ints + +# Floats +do_test $test.10 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_double $STMT $i]} + set utf8 +} $doubles + +# UTF-8 +do_test $test.11 { + set utf8 [list] + foreach i $idxlist {lappend utf8 [sqlite3_column_text $STMT $i]} + set utf8 +} $strings + +# Types +do_test $test.12 { + set types [list] + foreach i $idxlist {lappend types [sqlite3_column_type $STMT $i]} + set types +} $types + +# Test that an out of range request returns the equivalent of NULL +do_test $test.13 { + sqlite3_column_int $STMT -1 +} {0} +do_test $test.13 { + sqlite3_column_text $STMT -1 +} {} + +} + +ifcapable !floatingpoint { + finish_test + return +} + +do_test capi3c-5.0 { + execsql { + CREATE TABLE t1(a VARINT, b BLOB, c VARCHAR(16)); + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES('one', 'two', NULL); + INSERT INTO t1 VALUES(1.2, 1.3, 1.4); + } + set sql "SELECT * FROM t1" + set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL] + sqlite3_column_count $STMT +} 3 + +check_header $STMT capi3c-5.1 {a b c} {VARINT BLOB VARCHAR(16)} +check_origin_header $STMT capi3c-5.1 {main main main} {t1 t1 t1} {a b c} +do_test capi3c-5.2 { + sqlite3_step $STMT +} SQLITE_ROW + +check_header $STMT capi3c-5.3 {a b c} {VARINT BLOB VARCHAR(16)} +check_origin_header $STMT capi3c-5.3 {main main main} {t1 t1 t1} {a b c} +check_data $STMT capi3c-5.4 {INTEGER INTEGER TEXT} {1 2 3} {1.0 2.0 3.0} {1 2 3} + +do_test capi3c-5.5 { + sqlite3_step $STMT +} SQLITE_ROW + +check_header $STMT capi3c-5.6 {a b c} {VARINT BLOB VARCHAR(16)} +check_origin_header $STMT capi3c-5.6 {main main main} {t1 t1 t1} {a b c} +check_data $STMT capi3c-5.7 {TEXT TEXT NULL} {0 0 0} {0.0 0.0 0.0} {one two {}} + +do_test capi3c-5.8 { + sqlite3_step $STMT +} SQLITE_ROW + +check_header $STMT capi3c-5.9 {a b c} {VARINT BLOB VARCHAR(16)} +check_origin_header $STMT capi3c-5.9 {main main main} {t1 t1 t1} {a b c} +check_data $STMT capi3c-5.10 {FLOAT FLOAT TEXT} {1 1 1} {1.2 1.3 1.4} {1.2 1.3 1.4} + +do_test capi3c-5.11 { + sqlite3_step $STMT +} SQLITE_DONE + +do_test capi3c-5.12 { + sqlite3_finalize $STMT +} SQLITE_OK + +do_test capi3c-5.20 { + set sql "SELECT a, sum(b), max(c) FROM t1 GROUP BY a" + set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL] + sqlite3_column_count $STMT +} 3 + +check_header $STMT capi3c-5.21 {a sum(b) max(c)} {VARINT {} {}} +check_origin_header $STMT capi3c-5.22 {main {} {}} {t1 {} {}} {a {} {}} +do_test capi3c-5.23 { + sqlite3_finalize $STMT +} SQLITE_OK + + +set ::ENC [execsql {pragma encoding}] +db close + +do_test capi3c-6.0 { + sqlite3 db test.db + set DB [sqlite3_connection_pointer db] + if {[sqlite3 -has-codec]==0} { sqlite3_key $DB xyzzy } + set sql {SELECT a FROM t1 order by rowid} + set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL] + expr 0 +} {0} +do_test capi3c-6.1 { + db cache flush + sqlite3_close $DB +} {SQLITE_BUSY} +do_test capi3c-6.2 { + sqlite3_step $STMT +} {SQLITE_ROW} +check_data $STMT capi3c-6.3 {INTEGER} {1} {1.0} {1} +do_test capi3c-6.3 { + sqlite3_finalize $STMT +} {SQLITE_OK} +do_test capi3c-6.4 { + db cache flush + sqlite3_close $DB +} {SQLITE_OK} +do_test capi3c-6.99-misuse { + db close +} {} + +# This procedure sets the value of the file-format in file 'test.db' +# to $newval. Also, the schema cookie is incremented. +# +proc set_file_format {newval} { + hexio_write test.db 44 [hexio_render_int32 $newval] + set schemacookie [hexio_get_int [hexio_read test.db 40 4]] + incr schemacookie + hexio_write test.db 40 [hexio_render_int32 $schemacookie] + return {} +} + +# This procedure returns the value of the file-format in file 'test.db'. +# +proc get_file_format {{fname test.db}} { + return [hexio_get_int [hexio_read $fname 44 4]] +} + +if {![sqlite3 -has-codec]} { + # Test what happens when the library encounters a newer file format. + do_test capi3c-7.1 { + set_file_format 5 + } {} + do_test capi3c-7.2 { + catch { sqlite3 db test.db } + catchsql { + SELECT * FROM sqlite_master; + } + } {1 {unsupported file format}} + db close +} + +if {![sqlite3 -has-codec]} { + # Now test that the library correctly handles bogus entries in the + # sqlite_master table (schema corruption). + do_test capi3c-8.1 { + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + CREATE TABLE t1(a); + } + db close + } {} + do_test capi3c-8.2 { + sqlite3 db test.db + execsql { + PRAGMA writable_schema=ON; + INSERT INTO sqlite_master VALUES(NULL,NULL,NULL,NULL,NULL); + } + db close + } {} + do_test capi3c-8.3 { + catch { sqlite3 db test.db } + catchsql { + SELECT * FROM sqlite_master; + } + } {1 {malformed database schema (?)}} + do_test capi3c-8.4 { + # Build a 5-field row record. The first field is a string 'table', and + # subsequent fields are all NULL. + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + CREATE TABLE t1(a); + PRAGMA writable_schema=ON; + INSERT INTO sqlite_master VALUES('table',NULL,NULL,NULL,NULL); + } + db close + } {}; + do_test capi3c-8.5 { + catch { sqlite3 db test.db } + catchsql { + SELECT * FROM sqlite_master; + } + } {1 {malformed database schema (?)}} + db close +} +forcedelete test.db +forcedelete test.db-journal + + +# Test the english language string equivalents for sqlite error codes +set code2english [list \ +SQLITE_OK {not an error} \ +SQLITE_ERROR {SQL logic error or missing database} \ +SQLITE_PERM {access permission denied} \ +SQLITE_ABORT {callback requested query abort} \ +SQLITE_BUSY {database is locked} \ +SQLITE_LOCKED {database table is locked} \ +SQLITE_NOMEM {out of memory} \ +SQLITE_READONLY {attempt to write a readonly database} \ +SQLITE_INTERRUPT {interrupted} \ +SQLITE_IOERR {disk I/O error} \ +SQLITE_CORRUPT {database disk image is malformed} \ +SQLITE_FULL {database or disk is full} \ +SQLITE_CANTOPEN {unable to open database file} \ +SQLITE_EMPTY {table contains no data} \ +SQLITE_SCHEMA {database schema has changed} \ +SQLITE_CONSTRAINT {constraint failed} \ +SQLITE_MISMATCH {datatype mismatch} \ +SQLITE_MISUSE {library routine called out of sequence} \ +SQLITE_NOLFS {large file support is disabled} \ +SQLITE_AUTH {authorization denied} \ +SQLITE_FORMAT {auxiliary database format error} \ +SQLITE_RANGE {bind or column index out of range} \ +SQLITE_NOTADB {file is encrypted or is not a database} \ +unknownerror {unknown error} \ +] + +set test_number 1 +foreach {code english} $code2english { + do_test capi3c-9.$test_number "sqlite3_test_errstr $code" $english + incr test_number +} + +# Test the error message when a "real" out of memory occurs. +if { [permutation] != "nofaultsim" } { +ifcapable memdebug { + do_test capi3c-10-1 { + sqlite3 db test.db + set DB [sqlite3_connection_pointer db] + sqlite3_memdebug_fail 0 + catchsql { + select * from sqlite_master; + } + } {1 {out of memory}} + do_test capi3c-10-2 { + sqlite3_errmsg $::DB + } {out of memory} + ifcapable {utf16} { + do_test capi3c-10-3 { + utf8 [sqlite3_errmsg16 $::DB] + } {out of memory} + } + db close + sqlite3_memdebug_fail -1 +} +} + +# The following tests - capi3c-11.* - test that a COMMIT or ROLLBACK +# statement issued while there are still outstanding VMs that are part of +# the transaction fails. +sqlite3 db test.db +set DB [sqlite3_connection_pointer db] +sqlite_register_test_function $DB func +do_test capi3c-11.1 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 'int'); + INSERT INTO t1 VALUES(2, 'notatype'); + } +} {} +do_test capi3c-11.1.1 { + sqlite3_get_autocommit $DB +} 0 +do_test capi3c-11.2 { + set STMT [sqlite3_prepare_v2 $DB "SELECT func(b, a) FROM t1" -1 TAIL] + sqlite3_step $STMT +} {SQLITE_ROW} + +# As of 3.6.5 a COMMIT is OK during while a query is still running - +# as long as it is a read-only query and not an incremental BLOB write. +# +do_test capi3-11.3.1 { + catchsql { + COMMIT; + } +} {0 {}} +do_test capi3-11.3.2 { + sqlite3_extended_errcode $DB +} {SQLITE_OK} +do_test capi3-11.3.3 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3-11.3.4 { + db eval {PRAGMA lock_status} +} {main shared temp closed} + +do_test capi3c-11.4 { + sqlite3_step $STMT +} {SQLITE_ERROR} +do_test capi3c-11.5 { + sqlite3_finalize $STMT +} {SQLITE_ERROR} +do_test capi3c-11.6 { + catchsql { + SELECT * FROM t1; + } +} {0 {1 int 2 notatype}} +do_test capi3c-11.7 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3c-11.8 { + execsql { + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(2); + BEGIN; + INSERT INTO t2 VALUES(3); + } +} {} +do_test capi3c-11.8.1 { + sqlite3_get_autocommit $DB +} 0 +do_test capi3c-11.9 { + set STMT [sqlite3_prepare_v2 $DB "SELECT a FROM t2" -1 TAIL] + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3c-11.9.1 { + sqlite3_get_autocommit $DB +} 0 +do_test capi3c-11.9.2 { + catchsql { + ROLLBACK; + } +} {0 {}} +do_test capi3c-11.9.3 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3c-11.10 { + sqlite3_step $STMT +} {SQLITE_ABORT} +ifcapable !autoreset { + # If SQLITE_OMIT_AUTORESET is defined, then the statement must be + # reset() before it can be passed to step() again. + do_test capi3-11.11a { sqlite3_step $STMT } {SQLITE_MISUSE} + do_test capi3-11.11b { sqlite3_reset $STMT } {SQLITE_ABORT} +} +do_test capi3c-11.11 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3c-11.12 { + sqlite3_step $STMT + sqlite3_step $STMT +} {SQLITE_DONE} +do_test capi3c-11.13 { + sqlite3_finalize $STMT +} {SQLITE_OK} +do_test capi3c-11.14 { + execsql { + SELECT a FROM t2; + } +} {1 2} +do_test capi3c-11.14.1 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3c-11.15 { + catchsql { + ROLLBACK; + } +} {1 {cannot rollback - no transaction is active}} +do_test capi3c-11.15.1 { + sqlite3_get_autocommit $DB +} 1 +do_test capi3c-11.16 { + execsql { + SELECT a FROM t2; + } +} {1 2} + +# Sanity check on the definition of 'outstanding VM'. This means any VM +# that has had sqlite3_step() called more recently than sqlite3_finalize() or +# sqlite3_reset(). So a VM that has just been prepared or reset does not +# count as an active VM. +do_test capi3c-11.17 { + execsql { + BEGIN; + } +} {} +do_test capi3c-11.18 { + set STMT [sqlite3_prepare_v2 $DB "SELECT a FROM t1" -1 TAIL] + catchsql { + COMMIT; + } +} {0 {}} +do_test capi3c-11.19 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3c-11.20 { + catchsql { + BEGIN; + COMMIT; + } +} {0 {}} +do_test capi3c-11.20 { + sqlite3_reset $STMT + catchsql { + COMMIT; + } +} {1 {cannot commit - no transaction is active}} +do_test capi3c-11.21 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +# The following tests - capi3c-12.* - check that its Ok to start a +# transaction while other VMs are active, and that its Ok to execute +# atomic updates in the same situation +# +do_test capi3c-12.1 { + set STMT [sqlite3_prepare_v2 $DB "SELECT a FROM t2" -1 TAIL] + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3c-12.2 { + catchsql { + INSERT INTO t1 VALUES(3, NULL); + } +} {0 {}} +do_test capi3c-12.3 { + catchsql { + INSERT INTO t2 VALUES(4); + } +} {0 {}} +do_test capi3c-12.4 { + catchsql { + BEGIN; + INSERT INTO t1 VALUES(4, NULL); + } +} {0 {}} +do_test capi3c-12.5 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3c-12.5.1 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test capi3c-12.6 { + sqlite3_step $STMT +} {SQLITE_DONE} +do_test capi3c-12.7 { + sqlite3_finalize $STMT +} {SQLITE_OK} +do_test capi3c-12.8 { + execsql { + COMMIT; + SELECT a FROM t1; + } +} {1 2 3 4} + +# Test cases capi3c-13.* test the sqlite3_clear_bindings() and +# sqlite3_sleep APIs. +# +if {[llength [info commands sqlite3_clear_bindings]]>0} { + do_test capi3c-13.1 { + execsql { + DELETE FROM t1; + } + set STMT [sqlite3_prepare_v2 $DB "INSERT INTO t1 VALUES(?, ?)" -1 TAIL] + sqlite3_step $STMT + } {SQLITE_DONE} + do_test capi3c-13.2 { + sqlite3_reset $STMT + sqlite3_bind_text $STMT 1 hello 5 + sqlite3_bind_text $STMT 2 world 5 + sqlite3_step $STMT + } {SQLITE_DONE} + do_test capi3c-13.3 { + sqlite3_reset $STMT + sqlite3_clear_bindings $STMT + sqlite3_step $STMT + } {SQLITE_DONE} + do_test capi3c-13-4 { + sqlite3_finalize $STMT + execsql { + SELECT * FROM t1; + } + } {{} {} hello world {} {}} +} +if {[llength [info commands sqlite3_sleep]]>0} { + do_test capi3c-13-5 { + set ms [sqlite3_sleep 80] + expr {$ms==80 || $ms==1000} + } {1} +} + +# Ticket #1219: Make sure binding APIs can handle a NULL pointer. +# +do_test capi3c-14.1 { + set rc [catch {sqlite3_bind_text 0 1 hello 5} msg] + lappend rc $msg +} {1 SQLITE_MISUSE} + +# Ticket #1650: Honor the nBytes parameter to sqlite3_prepare. +# +do_test capi3c-15.1 { + set sql {SELECT * FROM t2} + set nbytes [string length $sql] + append sql { WHERE a==1} + set STMT [sqlite3_prepare_v2 $DB $sql $nbytes TAIL] + sqlite3_step $STMT + sqlite3_column_int $STMT 0 +} {1} +do_test capi3c-15.2 { + sqlite3_step $STMT + sqlite3_column_int $STMT 0 +} {2} +do_test capi3c-15.3 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +# Make sure code is always generated even if an IF EXISTS or +# IF NOT EXISTS clause is present that the table does not or +# does exists. That way we will always have a prepared statement +# to expire when the schema changes. +# +do_test capi3c-16.1 { + set sql {DROP TABLE IF EXISTS t3} + set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL] + sqlite3_finalize $STMT + expr {$STMT!=""} +} {1} +do_test capi3c-16.2 { + set sql {CREATE TABLE IF NOT EXISTS t1(x,y)} + set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL] + sqlite3_finalize $STMT + expr {$STMT!=""} +} {1} + +# But still we do not generate code if there is no SQL +# +do_test capi3c-16.3 { + set STMT [sqlite3_prepare_v2 $DB {} -1 TAIL] + sqlite3_finalize $STMT + expr {$STMT==""} +} {1} +do_test capi3c-16.4 { + set STMT [sqlite3_prepare_v2 $DB {;} -1 TAIL] + sqlite3_finalize $STMT + expr {$STMT==""} +} {1} + +# Ticket #2154. +# +do_test capi3c-17.1 { + set STMT [sqlite3_prepare_v2 $DB {SELECT max(a) FROM t2} -1 TAIL] + sqlite3_step $STMT +} SQLITE_ROW +do_test capi3c-17.2 { + sqlite3_column_int $STMT 0 +} 4 +do_test capi3c-17.3 { + sqlite3_step $STMT +} SQLITE_DONE +do_test capi3c-17.4 { + sqlite3_reset $STMT + db eval {CREATE INDEX i2 ON t2(a)} + sqlite3_step $STMT +} SQLITE_ROW +do_test capi3c-17.5 { + sqlite3_column_int $STMT 0 +} 4 +do_test capi3c-17.6 { + sqlite3_step $STMT +} SQLITE_DONE +do_test capi3c-17.7 { + sqlite3_reset $STMT + db eval {DROP INDEX i2} + sqlite3_step $STMT +} SQLITE_ROW +do_test capi3c-17.8 { + sqlite3_column_int $STMT 0 +} 4 +do_test capi3c-17.9 { + sqlite3_step $STMT +} SQLITE_DONE +do_test capi3c-17.10 { + sqlite3_finalize $STMT + set STMT [sqlite3_prepare_v2 $DB {SELECT b FROM t1 WHERE a=?} -1 TAIL] + sqlite3_bind_int $STMT 1 2 + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,'one'); + INSERT INTO t1 VALUES(2,'two'); + INSERT INTO t1 VALUES(3,'three'); + INSERT INTO t1 VALUES(4,'four'); + } + sqlite3_step $STMT +} SQLITE_ROW +do_test capi3c-17.11 { + sqlite3_column_text $STMT 0 +} two +do_test capi3c-17.12 { + sqlite3_step $STMT +} SQLITE_DONE +do_test capi3c-17.13 { + sqlite3_reset $STMT + db eval {CREATE INDEX i1 ON t1(a)} + sqlite3_step $STMT +} SQLITE_ROW +do_test capi3c-17.14 { + sqlite3_column_text $STMT 0 +} two +do_test capi3c-17.15 { + sqlite3_step $STMT +} SQLITE_DONE +do_test capi3c-17.16 { + sqlite3_reset $STMT + db eval {DROP INDEX i1} + sqlite3_step $STMT +} SQLITE_ROW +do_test capi3c-17.17 { + sqlite3_column_text $STMT 0 +} two +do_test capi3c-17.18 { + sqlite3_step $STMT +} SQLITE_DONE +do_test capi3c-17.99 { + sqlite3_finalize $STMT +} SQLITE_OK + +# On the mailing list it has been reported that finalizing after +# an SQLITE_BUSY return leads to a segfault. Here we test that case. +# +do_test capi3c-18.1 { + sqlite3 db2 test.db + set STMT [sqlite3_prepare_v2 $DB {SELECT max(a) FROM t1} -1 TAIL] + sqlite3_step $STMT +} SQLITE_ROW +do_test capi3c-18.2 { + sqlite3_column_int $STMT 0 +} 4 +do_test capi3c-18.3 { + sqlite3_reset $STMT + db2 eval {BEGIN EXCLUSIVE} + sqlite3_step $STMT +} SQLITE_BUSY +do_test capi3c-18.4 { + sqlite3_finalize $STMT +} SQLITE_BUSY +do_test capi3c-18.5 { + db2 eval {COMMIT} + db2 close +} {} + +# Ticket #2158. The sqlite3_step() will still return SQLITE_SCHEMA +# if the database schema changes in a way that makes the statement +# no longer valid. +# +do_test capi3c-19.1 { + db eval { + CREATE TABLE t3(x,y); + INSERT INTO t3 VALUES(1,2); + } + set STMT [sqlite3_prepare_v2 $DB {SELECT * FROM t3} -1 TAIL] + sqlite3_step $STMT +} SQLITE_ROW +do_test capi3c-19.2 { + sqlite3_column_int $STMT 0 +} 1 +do_test capi3c-19.3 { + sqlite3_step $STMT +} SQLITE_DONE +do_test capi3c-19.4 { + sqlite3_reset $STMT + db eval {DROP TABLE t3} + sqlite3_step $STMT +} SQLITE_ERROR +do_test capi3c-19.4.1 { + sqlite3_errmsg $DB +} {no such table: t3} +ifcapable deprecated { + do_test capi3c-19.4.2 { + sqlite3_expired $STMT + } 1 +} +do_test capi3c-19.4.3 { + sqlite3_errmsg $DB +} {no such table: t3} +ifcapable deprecated { + do_test capi3c-19.4.4 { + sqlite3_expired 0 + } 1 +} +do_test capi3c-19.5 { + sqlite3_reset $STMT + db eval { + CREATE TABLE t3(x,y); + INSERT INTO t3 VALUES(1,2); + } + sqlite3_step $STMT +} SQLITE_ROW +ifcapable deprecated { + do_test capi3c-19.5.2 { + sqlite3_expired $STMT + } 0 +} +do_test capi3c-19.6 { + sqlite3_column_int $STMT 1 +} 2 +do_test capi3c-19.99 { + sqlite3_finalize $STMT +} SQLITE_OK + +# Make sure a change in a separate database connection does not +# cause an SQLITE_SCHEMA return. +# +do_test capi3c-20.1 { + set STMT [sqlite3_prepare_v2 $DB {SELECT * FROM t3} -1 TAIL] + sqlite3 db2 test.db + db2 eval {CREATE TABLE t4(x)} + sqlite3_step $STMT +} SQLITE_ROW +do_test capi3c-20.2 { + sqlite3_column_int $STMT 1 +} 2 +do_test capi3c-20.3 { + sqlite3_step $STMT +} SQLITE_DONE +do_test capi3c-20.4 { + db2 close + sqlite3_finalize $STMT +} SQLITE_OK + +# Test that sqlite3_step() sets the database error code correctly. +# See ticket #2497. +# +ifcapable progress { + do_test capi3c-21.1 { + set STMT [sqlite3_prepare_v2 $DB {SELECT * FROM t3} -1 TAIL] + db progress 5 "expr 1" + sqlite3_step $STMT + } {SQLITE_INTERRUPT} + do_test capi3c-21.2 { + sqlite3_extended_errcode $DB + } {SQLITE_INTERRUPT} + do_test capi3c-21.3 { + sqlite3_finalize $STMT + } {SQLITE_INTERRUPT} + do_test capi3c-21.4 { + set STMT [sqlite3_prepare $DB {SELECT * FROM t3} -1 TAIL] + db progress 5 "expr 1" + sqlite3_step $STMT + } {SQLITE_ERROR} + do_test capi3c-21.5 { + sqlite3_errcode $DB + } {SQLITE_ERROR} + do_test capi3c-21.6 { + sqlite3_finalize $STMT + } {SQLITE_INTERRUPT} + do_test capi3c-21.7 { + sqlite3_errcode $DB + } {SQLITE_INTERRUPT} + do_test capi3c-21.8 { + sqlite3_extended_errcode $DB + } {SQLITE_INTERRUPT} +} + +# Make sure sqlite3_result_error_code() returns the correct error code. +# See ticket #2940 +# +do_test capi3c-22.1 { + db progress 0 {} + set STMT [sqlite3_prepare_v2 db {SELECT test_error('the message',3)} -1 TAIL] + sqlite3_step $STMT +} {SQLITE_PERM} +sqlite3_finalize $STMT +do_test capi3c-22.2 { + set STMT [sqlite3_prepare_v2 db {SELECT test_error('the message',4)} -1 TAIL] + sqlite3_step $STMT +} {SQLITE_ABORT} +sqlite3_finalize $STMT +do_test capi3c-22.3 { + set STMT [sqlite3_prepare_v2 db {SELECT test_error('the message',16)} -1 TAIL] + sqlite3_step $STMT +} {SQLITE_EMPTY} +sqlite3_finalize $STMT + +# For a multi-column result set where the same table column is repeated +# in multiple columns of the output, verify that doing a UTF-8 to UTF-16 +# conversion (or vice versa) on one column does not change the value of +# the second. +# +ifcapable utf16 { + do_test capi3c-23.1 { + set STMT [sqlite3_prepare_v2 db {SELECT b,b,b,b FROM t1} -1 TAIL] + sqlite3_step $STMT + } {SQLITE_ROW} + do_test capi3c-23.2 { + sqlite3_column_text16 $STMT 0 + sqlite3_column_text $STMT 1 + } {one} + do_test capi3c-23.3 { + sqlite3_column_text16 $STMT 2 + sqlite3_column_text $STMT 3 + } {one} + sqlite3_finalize $STMT + do_test capi3c-23.4 { + set STMT [sqlite3_prepare_v2 db {SELECT b||'x',b,b,b FROM t1} -1 TAIL] + sqlite3_step $STMT + } {SQLITE_ROW} + do_test capi3c-23.5 { + sqlite3_column_text16 $STMT 0 + sqlite3_column_text $STMT 1 + } {one} + do_test capi3c-23.6 { + sqlite3_column_text16 $STMT 2 + sqlite3_column_text $STMT 3 + } {one} + sqlite3_finalize $STMT +} + +# Test decltype on some SELECT statements that contain sub-selects. +# +proc decltype {zSql} { + set ret [list] + set STMT [sqlite3_prepare_v2 db $zSql -1 TAIL] + for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} { + lappend ret [sqlite3_column_decltype $STMT $i] + } + sqlite3_finalize $STMT + return $ret +} +do_test capi3c-24.1 { + execsql { CREATE TABLE t5(a INTEGER, b STRING, c DATETIME) } + decltype {SELECT * FROM t5} +} {INTEGER STRING DATETIME} +do_test capi3c-24.2 { + decltype {SELECT (SELECT c) FROM t5} +} {DATETIME} +do_test capi3c-24.3 { + decltype {SELECT (SELECT * FROM (SELECT c)) FROM t5} +} {DATETIME} +do_test capi3c-24.4 { + decltype {SELECT * FROM (SELECT * FROM t5 ORDER BY c LIMIT 1) ORDER BY b} +} {INTEGER STRING DATETIME} +do_test capi3c-24.5 { + decltype { + SELECT (SELECT x FROM (SELECT c AS x)) + FROM (SELECT * FROM t5 ORDER BY c LIMIT 1) ORDER BY b + } +} {DATETIME} +do_test capi3c-24.3 { + decltype {SELECT (SELECT x FROM (SELECT t5.a AS x)) FROM t5} +} {INTEGER} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/capi3d.test b/components/external/SQLite-3.8.1/test/capi3d.test new file mode 100644 index 0000000000000000000000000000000000000000..ed3765b05194193cc78d4df24facaa1bd2409975 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/capi3d.test @@ -0,0 +1,147 @@ +# 2008 June 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is devoted to testing the sqlite3_next_stmt and +# sqlite3_stmt_readonly and sqlite3_stmt_busy interfaces. +# +# $Id: capi3d.test,v 1.2 2008/07/14 15:11:20 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create N prepared statements against database connection db +# and return a list of all the generated prepared statements. +# +proc make_prepared_statements {N} { + set plist {} + for {set i 0} {$i<$N} {incr i} { + set sql "SELECT $i FROM sqlite_master WHERE name LIKE '%$i%'" + if {rand()<0.33} { + set s [sqlite3_prepare_v2 db $sql -1 notused] + } else { + ifcapable utf16 { + if {rand()<0.5} { + set sql [encoding convertto unicode $sql]\x00\x00 + set s [sqlite3_prepare16 db $sql -1 notused] + } else { + set s [sqlite3_prepare db $sql -1 notused] + } + } + ifcapable !utf16 { + set s [sqlite3_prepare db $sql -1 notused] + } + } + lappend plist $s + } + return $plist +} + + +# Scramble the $inlist into a random order. +# +proc scramble {inlist} { + set y {} + foreach x $inlist { + lappend y [list [expr {rand()}] $x] + } + set y [lsort $y] + set outlist {} + foreach x $y { + lappend outlist [lindex $x 1] + } + return $outlist +} + +# Database initially has no prepared statements. +# +do_test capi3d-1.1 { + db cache flush + sqlite3_next_stmt db 0 +} {} + +# Run the following tests for between 1 and 100 prepared statements. +# +for {set i 1} {$i<=100} {incr i} { + set stmtlist [make_prepared_statements $i] + do_test capi3d-1.2.$i.1 { + set p [sqlite3_next_stmt db 0] + set x {} + while {$p!=""} { + lappend x $p + set p [sqlite3_next_stmt db $p] + } + lsort $x + } [lsort $stmtlist] + do_test capi3-1.2.$i.2 { + foreach p [scramble $::stmtlist] { + sqlite3_finalize $p + } + sqlite3_next_stmt db 0 + } {} +} + +# Tests for the is-read-only interface. +# +proc test_is_readonly {testname sql truth} { + do_test $testname [format { + set DB [sqlite3_connection_pointer db] + set STMT [sqlite3_prepare $DB {%s} -1 TAIL] + set rc [sqlite3_stmt_readonly $STMT] + sqlite3_finalize $STMT + set rc + } $sql] $truth +} + +test_is_readonly capi3d-2.1 {SELECT * FROM sqlite_master} 1 +test_is_readonly capi3d-2.2 {CREATE TABLE t1(x)} 0 +db eval {CREATE TABLE t1(x)} +test_is_readonly capi3d-2.3 {INSERT INTO t1 VALUES(5)} 0 +test_is_readonly capi3d-2.4 {UPDATE t1 SET x=x+1 WHERE x<0} 0 +test_is_readonly capi3d-2.5 {SELECT * FROM t1} 1 +ifcapable wal { + test_is_readonly capi3d-2.6 {PRAGMA journal_mode=WAL} 0 + test_is_readonly capi3d-2.7 {PRAGMA wal_checkpoint} 0 +} +test_is_readonly capi3d-2.8 {PRAGMA application_id=1234} 0 +test_is_readonly capi3d-2.9 {VACUUM} 0 +test_is_readonly capi3d-2.10 {PRAGMA integrity_check} 1 +do_test capi3-2.99 { + sqlite3_stmt_readonly 0 +} 1 + +# Tests for sqlite3_stmt_busy +# +do_test capi3d-3.1 { + db eval {INSERT INTO t1 VALUES(6); INSERT INTO t1 VALUES(7);} + set STMT [sqlite3_prepare db {SELECT * FROM t1} -1 TAIL] + sqlite3_stmt_busy $STMT +} {0} +do_test capi3d-3.2 { + sqlite3_step $STMT + sqlite3_stmt_busy $STMT +} {1} +do_test capi3d-3.3 { + sqlite3_step $STMT + sqlite3_stmt_busy $STMT +} {1} +do_test capi3d-3.4 { + sqlite3_reset $STMT + sqlite3_stmt_busy $STMT +} {0} + +do_test capi3d-3.99 { + sqlite3_finalize $STMT + sqlite3_stmt_busy 0 +} {0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/capi3e.test b/components/external/SQLite-3.8.1/test/capi3e.test new file mode 100644 index 0000000000000000000000000000000000000000..d7ab8d0bd4f96e95ac8c5c6d0a4918f558ed5392 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/capi3e.test @@ -0,0 +1,122 @@ +# 2010 Novemeber 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the callback-free C/C++ API. +# +# $Id: capi3e.test,v 1.70 2009/01/09 02:49:32 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Make sure the system encoding is utf-8. Otherwise, if the system encoding +# is other than utf-8, [file isfile $x] may not refer to the same file +# as [sqlite3 db $x]. +encoding system utf-8 + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Return the UTF-16 representation of the supplied UTF-8 string $str. +# If $nt is true, append two 0x00 bytes as a nul terminator. +proc utf16 {str {nt 1}} { + set r [encoding convertto unicode $str] + if {$nt} { + append r "\x00\x00" + } + return $r +} + +# Return the UTF-8 representation of the supplied UTF-16 string $str. +proc utf8 {str} { + # If $str ends in two 0x00 0x00 bytes, knock these off before + # converting to UTF-8 using TCL. + binary scan $str \c* vals + if {[lindex $vals end]==0 && [lindex $vals end-1]==0} { + set str [binary format \c* [lrange $vals 0 end-2]] + } + + set r [encoding convertfrom unicode $str] + return $r +} + +# These tests complement those in capi2.test. They are organized +# as follows: +# +# capi3e-1.*: Test sqlite3_open with various UTF8 filenames +# capi3e-2.*: Test sqlite3_open16 with various UTF8 filenames +# capi3e-3.*: Test ATTACH with various UTF8 filenames + +db close + +# here's the list of file names we're testing +set names {t 1 t. 1. t.d 1.d t-1 1-1 t.db ä.db ë.db ö.db ü.db ÿ.db} + +set i 0 +foreach name $names { + incr i + do_test capi3e-1.1.$i { + set db2 [sqlite3_open $name {}] + sqlite3_errcode $db2 + } {SQLITE_OK} + do_test capi3e-1.2.$i { + sqlite3_close $db2 + } {SQLITE_OK} + do_test capi3e-1.3.$i { + file isfile $name + } {1} +} + +ifcapable {utf16} { + set i 0 + foreach name $names { + incr i + do_test capi3e-2.1.$i { + set db2 [sqlite3_open16 [utf16 $name] {}] + sqlite3_errcode $db2 + } {SQLITE_OK} + do_test capi3e-2.2.$i { + sqlite3_close $db2 + } {SQLITE_OK} + do_test capi3e-2.3.$i { + file isfile $name + } {1} + } +} + +ifcapable attach { + do_test capi3e-3.1 { + sqlite3 db2 base.db + } {} + set i 0 + foreach name $names { + incr i + do_test capi3e-3.2.$i { + db2 eval "ATTACH DATABASE '$name' AS db$i;" + } {} + do_test capi3e-3.3.$i { + db2 eval "DETACH DATABASE db$i;" + } {} + } + do_test capi3e-3.4 { + db2 close + } {} +} + +# clean up +forcedelete base.db +foreach name $names { + forcedelete $name +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/cast.test b/components/external/SQLite-3.8.1/test/cast.test new file mode 100644 index 0000000000000000000000000000000000000000..f47f4bb2bf3fce09682d5231f814a90086139708 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/cast.test @@ -0,0 +1,346 @@ +# 2005 June 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the CAST operator. +# +# $Id: cast.test,v 1.10 2008/11/06 15:33:04 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Only run these tests if the build includes the CAST operator +ifcapable !cast { + finish_test + return +} + +# Tests for the CAST( AS blob), CAST( AS text) and CAST( AS numeric) built-ins +# +ifcapable bloblit { + do_test cast-1.1 { + execsql {SELECT x'616263'} + } abc + do_test cast-1.2 { + execsql {SELECT typeof(x'616263')} + } blob + do_test cast-1.3 { + execsql {SELECT CAST(x'616263' AS text)} + } abc + do_test cast-1.4 { + execsql {SELECT typeof(CAST(x'616263' AS text))} + } text + do_test cast-1.5 { + execsql {SELECT CAST(x'616263' AS numeric)} + } 0 + do_test cast-1.6 { + execsql {SELECT typeof(CAST(x'616263' AS numeric))} + } integer + do_test cast-1.7 { + execsql {SELECT CAST(x'616263' AS blob)} + } abc + do_test cast-1.8 { + execsql {SELECT typeof(CAST(x'616263' AS blob))} + } blob + do_test cast-1.9 { + execsql {SELECT CAST(x'616263' AS integer)} + } 0 + do_test cast-1.10 { + execsql {SELECT typeof(CAST(x'616263' AS integer))} + } integer +} +do_test cast-1.11 { + execsql {SELECT null} +} {{}} +do_test cast-1.12 { + execsql {SELECT typeof(NULL)} +} null +do_test cast-1.13 { + execsql {SELECT CAST(NULL AS text)} +} {{}} +do_test cast-1.14 { + execsql {SELECT typeof(CAST(NULL AS text))} +} null +do_test cast-1.15 { + execsql {SELECT CAST(NULL AS numeric)} +} {{}} +do_test cast-1.16 { + execsql {SELECT typeof(CAST(NULL AS numeric))} +} null +do_test cast-1.17 { + execsql {SELECT CAST(NULL AS blob)} +} {{}} +do_test cast-1.18 { + execsql {SELECT typeof(CAST(NULL AS blob))} +} null +do_test cast-1.19 { + execsql {SELECT CAST(NULL AS integer)} +} {{}} +do_test cast-1.20 { + execsql {SELECT typeof(CAST(NULL AS integer))} +} null +do_test cast-1.21 { + execsql {SELECT 123} +} {123} +do_test cast-1.22 { + execsql {SELECT typeof(123)} +} integer +do_test cast-1.23 { + execsql {SELECT CAST(123 AS text)} +} {123} +do_test cast-1.24 { + execsql {SELECT typeof(CAST(123 AS text))} +} text +do_test cast-1.25 { + execsql {SELECT CAST(123 AS numeric)} +} 123 +do_test cast-1.26 { + execsql {SELECT typeof(CAST(123 AS numeric))} +} integer +do_test cast-1.27 { + execsql {SELECT CAST(123 AS blob)} +} {123} +do_test cast-1.28 { + execsql {SELECT typeof(CAST(123 AS blob))} +} blob +do_test cast-1.29 { + execsql {SELECT CAST(123 AS integer)} +} {123} +do_test cast-1.30 { + execsql {SELECT typeof(CAST(123 AS integer))} +} integer +do_test cast-1.31 { + execsql {SELECT 123.456} +} {123.456} +do_test cast-1.32 { + execsql {SELECT typeof(123.456)} +} real +do_test cast-1.33 { + execsql {SELECT CAST(123.456 AS text)} +} {123.456} +do_test cast-1.34 { + execsql {SELECT typeof(CAST(123.456 AS text))} +} text +do_test cast-1.35 { + execsql {SELECT CAST(123.456 AS numeric)} +} 123.456 +do_test cast-1.36 { + execsql {SELECT typeof(CAST(123.456 AS numeric))} +} real +do_test cast-1.37 { + execsql {SELECT CAST(123.456 AS blob)} +} {123.456} +do_test cast-1.38 { + execsql {SELECT typeof(CAST(123.456 AS blob))} +} blob +do_test cast-1.39 { + execsql {SELECT CAST(123.456 AS integer)} +} {123} +do_test cast-1.38 { + execsql {SELECT typeof(CAST(123.456 AS integer))} +} integer +do_test cast-1.41 { + execsql {SELECT '123abc'} +} {123abc} +do_test cast-1.42 { + execsql {SELECT typeof('123abc')} +} text +do_test cast-1.43 { + execsql {SELECT CAST('123abc' AS text)} +} {123abc} +do_test cast-1.44 { + execsql {SELECT typeof(CAST('123abc' AS text))} +} text +do_test cast-1.45 { + execsql {SELECT CAST('123abc' AS numeric)} +} 123 +do_test cast-1.46 { + execsql {SELECT typeof(CAST('123abc' AS numeric))} +} integer +do_test cast-1.47 { + execsql {SELECT CAST('123abc' AS blob)} +} {123abc} +do_test cast-1.48 { + execsql {SELECT typeof(CAST('123abc' AS blob))} +} blob +do_test cast-1.49 { + execsql {SELECT CAST('123abc' AS integer)} +} 123 +do_test cast-1.50 { + execsql {SELECT typeof(CAST('123abc' AS integer))} +} integer +do_test cast-1.51 { + execsql {SELECT CAST('123.5abc' AS numeric)} +} 123.5 +do_test cast-1.53 { + execsql {SELECT CAST('123.5abc' AS integer)} +} 123 + +do_test case-1.60 { + execsql {SELECT CAST(null AS REAL)} +} {{}} +do_test case-1.61 { + execsql {SELECT typeof(CAST(null AS REAL))} +} {null} +do_test case-1.62 { + execsql {SELECT CAST(1 AS REAL)} +} {1.0} +do_test case-1.63 { + execsql {SELECT typeof(CAST(1 AS REAL))} +} {real} +do_test case-1.64 { + execsql {SELECT CAST('1' AS REAL)} +} {1.0} +do_test case-1.65 { + execsql {SELECT typeof(CAST('1' AS REAL))} +} {real} +do_test case-1.66 { + execsql {SELECT CAST('abc' AS REAL)} +} {0.0} +do_test case-1.67 { + execsql {SELECT typeof(CAST('abc' AS REAL))} +} {real} +do_test case-1.68 { + execsql {SELECT CAST(x'31' AS REAL)} +} {1.0} +do_test case-1.69 { + execsql {SELECT typeof(CAST(x'31' AS REAL))} +} {real} + + +# Ticket #1662. Ignore leading spaces in numbers when casting. +# +do_test cast-2.1 { + execsql {SELECT CAST(' 123' AS integer)} +} 123 +do_test cast-2.2 { + execsql {SELECT CAST(' -123.456' AS real)} +} -123.456 + +# ticket #2364. Use full percision integers if possible when casting +# to numeric. Do not fallback to real (and the corresponding 48-bit +# mantissa) unless absolutely necessary. +# +do_test cast-3.1 { + execsql {SELECT CAST(9223372036854774800 AS integer)} +} 9223372036854774800 +do_test cast-3.2 { + execsql {SELECT CAST(9223372036854774800 AS numeric)} +} 9223372036854774800 +do_realnum_test cast-3.3 { + execsql {SELECT CAST(9223372036854774800 AS real)} +} 9.22337203685477e+18 +do_test cast-3.4 { + execsql {SELECT CAST(CAST(9223372036854774800 AS real) AS integer)} +} 9223372036854774784 +do_test cast-3.5 { + execsql {SELECT CAST(-9223372036854774800 AS integer)} +} -9223372036854774800 +do_test cast-3.6 { + execsql {SELECT CAST(-9223372036854774800 AS numeric)} +} -9223372036854774800 +do_realnum_test cast-3.7 { + execsql {SELECT CAST(-9223372036854774800 AS real)} +} -9.22337203685477e+18 +do_test cast-3.8 { + execsql {SELECT CAST(CAST(-9223372036854774800 AS real) AS integer)} +} -9223372036854774784 +do_test cast-3.11 { + execsql {SELECT CAST('9223372036854774800' AS integer)} +} 9223372036854774800 +do_test cast-3.12 { + execsql {SELECT CAST('9223372036854774800' AS numeric)} +} 9223372036854774800 +do_realnum_test cast-3.13 { + execsql {SELECT CAST('9223372036854774800' AS real)} +} 9.22337203685477e+18 +ifcapable long_double { + do_test cast-3.14 { + execsql {SELECT CAST(CAST('9223372036854774800' AS real) AS integer)} + } 9223372036854774784 +} +do_test cast-3.15 { + execsql {SELECT CAST('-9223372036854774800' AS integer)} +} -9223372036854774800 +do_test cast-3.16 { + execsql {SELECT CAST('-9223372036854774800' AS numeric)} +} -9223372036854774800 +do_realnum_test cast-3.17 { + execsql {SELECT CAST('-9223372036854774800' AS real)} +} -9.22337203685477e+18 +ifcapable long_double { + do_test cast-3.18 { + execsql {SELECT CAST(CAST('-9223372036854774800' AS real) AS integer)} + } -9223372036854774784 +} +if {[db eval {PRAGMA encoding}]=="UTF-8"} { + do_test cast-3.21 { + execsql {SELECT CAST(x'39323233333732303336383534373734383030' AS integer)} + } 9223372036854774800 + do_test cast-3.22 { + execsql {SELECT CAST(x'39323233333732303336383534373734383030' AS numeric)} + } 9223372036854774800 + do_realnum_test cast-3.23 { + execsql {SELECT CAST(x'39323233333732303336383534373734383030' AS real)} + } 9.22337203685477e+18 + ifcapable long_double { + do_test cast-3.24 { + execsql { + SELECT CAST(CAST(x'39323233333732303336383534373734383030' AS real) + AS integer) + } + } 9223372036854774784 + } +} +do_test case-3.31 { + execsql {SELECT CAST(NULL AS numeric)} +} {{}} + +# Test to see if it is possible to trick SQLite into reading past +# the end of a blob when converting it to a number. +do_test cast-3.32.1 { + set blob "1234567890" + set DB [sqlite3_connection_pointer db] + set ::STMT [sqlite3_prepare $DB {SELECT CAST(? AS real)} -1 TAIL] + sqlite3_bind_blob -static $::STMT 1 $blob 5 + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test cast-3.32.2 { + sqlite3_column_int $::STMT 0 +} {12345} +do_test cast-3.32.3 { + sqlite3_finalize $::STMT +} {SQLITE_OK} + + +do_test cast-4.1 { + db eval { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES('abc'); + SELECT a, CAST(a AS integer) FROM t1; + } +} {abc 0} +do_test cast-4.2 { + db eval { + SELECT CAST(a AS integer), a FROM t1; + } +} {0 abc} +do_test cast-4.3 { + db eval { + SELECT a, CAST(a AS integer), a FROM t1; + } +} {abc 0 abc} +do_test cast-4.4 { + db eval { + SELECT CAST(a AS integer), a, CAST(a AS real), a FROM t1; + } +} {0 abc 0.0 abc} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/check.test b/components/external/SQLite-3.8.1/test/check.test new file mode 100644 index 0000000000000000000000000000000000000000..f7ebc2cb4ca53238b810ab1036a21d7d4415e95a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/check.test @@ -0,0 +1,461 @@ +# 2005 November 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing CHECK constraints +# +# $Id: check.test,v 1.13 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix check + +# Only run these tests if the build includes support for CHECK constraints +ifcapable !check { + finish_test + return +} + +do_test check-1.1 { + execsql { + CREATE TABLE t1( + x INTEGER CHECK( x<5 ), + y REAL CHECK( y>x ) + ); + } +} {} +do_test check-1.2 { + execsql { + INSERT INTO t1 VALUES(3,4); + SELECT * FROM t1; + } +} {3 4.0} +do_test check-1.3 { + catchsql { + INSERT INTO t1 VALUES(6,7); + } +} {1 {constraint failed}} +do_test check-1.4 { + execsql { + SELECT * FROM t1; + } +} {3 4.0} +do_test check-1.5 { + catchsql { + INSERT INTO t1 VALUES(4,3); + } +} {1 {constraint failed}} +do_test check-1.6 { + execsql { + SELECT * FROM t1; + } +} {3 4.0} +do_test check-1.7 { + catchsql { + INSERT INTO t1 VALUES(NULL,6); + } +} {0 {}} +do_test check-1.8 { + execsql { + SELECT * FROM t1; + } +} {3 4.0 {} 6.0} +do_test check-1.9 { + catchsql { + INSERT INTO t1 VALUES(2,NULL); + } +} {0 {}} +do_test check-1.10 { + execsql { + SELECT * FROM t1; + } +} {3 4.0 {} 6.0 2 {}} +do_test check-1.11 { + execsql { + DELETE FROM t1 WHERE x IS NULL OR x!=3; + UPDATE t1 SET x=2 WHERE x==3; + SELECT * FROM t1; + } +} {2 4.0} +do_test check-1.12 { + catchsql { + UPDATE t1 SET x=7 WHERE x==2 + } +} {1 {constraint failed}} +do_test check-1.13 { + execsql { + SELECT * FROM t1; + } +} {2 4.0} +do_test check-1.14 { + catchsql { + UPDATE t1 SET x=5 WHERE x==2 + } +} {1 {constraint failed}} +do_test check-1.15 { + execsql { + SELECT * FROM t1; + } +} {2 4.0} +do_test check-1.16 { + catchsql { + UPDATE t1 SET x=4, y=11 WHERE x==2 + } +} {0 {}} +do_test check-1.17 { + execsql { + SELECT * FROM t1; + } +} {4 11.0} + +do_test check-2.1 { + execsql { + CREATE TABLE t2( + x INTEGER CONSTRAINT one CHECK( typeof(coalesce(x,0))=="integer" ), + y REAL CONSTRAINT two CHECK( typeof(coalesce(y,0.1))=='real' ), + z TEXT CONSTRAINT three CHECK( typeof(coalesce(z,''))=='text' ) + ); + } +} {} +do_test check-2.2 { + execsql { + INSERT INTO t2 VALUES(1,2.2,'three'); + SELECT * FROM t2; + } +} {1 2.2 three} +db close +sqlite3 db test.db +do_test check-2.3 { + execsql { + INSERT INTO t2 VALUES(NULL, NULL, NULL); + SELECT * FROM t2; + } +} {1 2.2 three {} {} {}} +do_test check-2.4 { + catchsql { + INSERT INTO t2 VALUES(1.1, NULL, NULL); + } +} {1 {constraint one failed}} +do_test check-2.5 { + catchsql { + INSERT INTO t2 VALUES(NULL, 5, NULL); + } +} {1 {constraint two failed}} +do_test check-2.6 { + catchsql { + INSERT INTO t2 VALUES(NULL, NULL, 3.14159); + } +} {1 {constraint three failed}} + +# Undocumented behavior: The CONSTRAINT name clause can follow a constraint. +# Such a clause is ignored. But the parser must accept it for backwards +# compatibility. +# +do_test check-2.10 { + execsql { + CREATE TABLE t2b( + x INTEGER CHECK( typeof(coalesce(x,0))=='integer' ) CONSTRAINT one, + y TEXT PRIMARY KEY constraint two, + z INTEGER, + UNIQUE(x,z) constraint three + ); + } +} {} +do_test check-2.11 { + catchsql { + INSERT INTO t2b VALUES('xyzzy','hi',5); + } +} {1 {constraint failed}} +do_test check-2.12 { + execsql { + CREATE TABLE t2c( + x INTEGER CONSTRAINT x_one CONSTRAINT x_two + CHECK( typeof(coalesce(x,0))=='integer' ) + CONSTRAINT x_two CONSTRAINT x_three, + y INTEGER, z INTEGER, + CONSTRAINT u_one UNIQUE(x,y,z) CONSTRAINT u_two + ); + } +} {} +do_test check-2.13 { + catchsql { + INSERT INTO t2c VALUES('xyzzy',7,8); + } +} {1 {constraint x_two failed}} +do_test check-2.cleanup { + execsql { + DROP TABLE IF EXISTS t2b; + DROP TABLE IF EXISTS t2c; + } +} {} + +ifcapable subquery { + do_test check-3.1 { + catchsql { + CREATE TABLE t3( + x, y, z, + CHECK( x<(SELECT min(x) FROM t1) ) + ); + } + } {1 {subqueries prohibited in CHECK constraints}} +} + +do_test check-3.2 { + execsql { + SELECT name FROM sqlite_master ORDER BY name + } +} {t1 t2} +do_test check-3.3 { + catchsql { + CREATE TABLE t3( + x, y, z, + CHECK( q0 )); + CREATE TABLE t811(b, CHECK( xyzzy.t811.b BETWEEN 5 AND 10 )); +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/close.test b/components/external/SQLite-3.8.1/test/close.test new file mode 100644 index 0000000000000000000000000000000000000000..d5d6391ae5e58be31e669f29d753cc1d970004e5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/close.test @@ -0,0 +1,78 @@ +# 2013 May 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test some specific circumstances to do with shared cache mode. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix close + +do_execsql_test 1.0 { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('one'); + INSERT INTO t1 VALUES('two'); + INSERT INTO t1 VALUES('three'); +} +db close + +do_test 1.1 { + set DB [sqlite3_open test.db] + sqlite3_close_v2 $DB +} {SQLITE_OK} + +do_test 1.2.1 { + set DB [sqlite3_open test.db] + set STMT [sqlite3_prepare $DB "SELECT * FROM t1" -1 dummy] + sqlite3_close_v2 $DB +} {SQLITE_OK} +do_test 1.2.2 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +do_test 1.3.1 { + set DB [sqlite3_open test.db] + set STMT [sqlite3_prepare $DB "SELECT * FROM t1" -1 dummy] + sqlite3_step $STMT + sqlite3_close_v2 $DB +} {SQLITE_OK} + +do_test 1.3.2 { + sqlite3_column_text $STMT 0 +} {one} + +do_test 1.3.3 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +do_test 1.4.1 { + set DB [sqlite3_open test.db] + set STMT [sqlite3_prepare $DB "SELECT * FROM t1" -1 dummy] + sqlite3_step $STMT + sqlite3_close_v2 $DB +} {SQLITE_OK} + +do_test 1.4.2 { + list [sqlite3_step $STMT] [sqlite3_column_text $STMT 0] +} {SQLITE_ROW two} + +do_test 1.4.3 { + list [catch { + sqlite3_prepare $DB "SELECT * FROM sqlite_master" -1 dummy + } msg] $msg +} {1 {(21) library routine called out of sequence}} + +do_test 1.4.4 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/closure01.test b/components/external/SQLite-3.8.1/test/closure01.test new file mode 100644 index 0000000000000000000000000000000000000000..5dac87a0ce28446a818858daab515af3a150949c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/closure01.test @@ -0,0 +1,226 @@ +# 2013-04-25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test cases for transitive_closure virtual table. + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix closure01 + +ifcapable !vtab { finish_test ; return } + +load_static_extension db closure + +do_execsql_test 1.0 { + BEGIN; + CREATE TABLE t1(x INTEGER PRIMARY KEY, y INTEGER); + CREATE INDEX t1y ON t1(y); + INSERT INTO t1(x) VALUES(1),(2); + INSERT INTO t1(x) SELECT x+2 FROM t1; + INSERT INTO t1(x) SELECT x+4 FROM t1; + INSERT INTO t1(x) SELECT x+8 FROM t1; + INSERT INTO t1(x) SELECT x+16 FROM t1; + INSERT INTO t1(x) SELECT x+32 FROM t1; + INSERT INTO t1(x) SELECT x+64 FROM t1; + INSERT INTO t1(x) SELECT x+128 FROM t1; + INSERT INTO t1(x) SELECT x+256 FROM t1; + INSERT INTO t1(x) SELECT x+512 FROM t1; + INSERT INTO t1(x) SELECT x+1024 FROM t1; + INSERT INTO t1(x) SELECT x+2048 FROM t1; + INSERT INTO t1(x) SELECT x+4096 FROM t1; + INSERT INTO t1(x) SELECT x+8192 FROM t1; + INSERT INTO t1(x) SELECT x+16384 FROM t1; + INSERT INTO t1(x) SELECT x+32768 FROM t1; + INSERT INTO t1(x) SELECT x+65536 FROM t1; + UPDATE t1 SET y=x/2 WHERE x>1; + COMMIT; + CREATE VIRTUAL TABLE cx + USING transitive_closure(tablename=t1, idcolumn=x, parentcolumn=y); +} {} + +# The entire table +do_execsql_test 1.1 { + SELECT count(*), depth FROM cx WHERE root=1 GROUP BY depth ORDER BY 1; +} {/1 0 1 17 2 1 4 2 8 3 16 4 .* 65536 16/} + +# descendents of 32768 +do_execsql_test 1.2 { + SELECT * FROM cx WHERE root=32768 ORDER BY id; +} {32768 0 65536 1 65537 1 131072 2} + +# descendents of 16384 +do_execsql_test 1.3 { + SELECT * FROM cx WHERE root=16384 AND depth<=2 ORDER BY id; +} {16384 0 32768 1 32769 1 65536 2 65537 2 65538 2 65539 2} + +# children of 16384 +do_execsql_test 1.4 { + SELECT id, depth, root, tablename, idcolumn, parentcolumn FROM cx + WHERE root=16384 + AND depth=1 + ORDER BY id; +} {32768 1 {} t1 x y 32769 1 {} t1 x y} + +# great-grandparent of 16384 +do_execsql_test 1.5 { + SELECT id, depth, root, tablename, idcolumn, parentcolumn FROM cx + WHERE root=16384 + AND depth=3 + AND idcolumn='Y' + AND parentcolumn='X'; +} {2048 3 {} t1 Y X} + +# depth<5 +do_execsql_test 1.6 { + SELECT count(*), depth FROM cx WHERE root=1 AND depth<5 + GROUP BY depth ORDER BY 1; +} {1 0 2 1 4 2 8 3 16 4} + +# depth<=5 +do_execsql_test 1.7 { + SELECT count(*), depth FROM cx WHERE root=1 AND depth<=5 + GROUP BY depth ORDER BY 1; +} {1 0 2 1 4 2 8 3 16 4 32 5} + +# depth==5 +do_execsql_test 1.8 { + SELECT count(*), depth FROM cx WHERE root=1 AND depth=5 + GROUP BY depth ORDER BY 1; +} {32 5} + +# depth BETWEEN 3 AND 5 +do_execsql_test 1.9 { + SELECT count(*), depth FROM cx WHERE root=1 AND depth BETWEEN 3 AND 5 + GROUP BY depth ORDER BY 1; +} {8 3 16 4 32 5} + +# depth==5 with min() and max() +do_execsql_test 1.10 { + SELECT count(*), min(id), max(id) FROM cx WHERE root=1 AND depth=5; +} {32 32 63} + +# Create a much smaller table t2 with only 32 elements +db eval { + CREATE TABLE t2(x INTEGER PRIMARY KEY, y INTEGER); + INSERT INTO t2 SELECT x, y FROM t1 WHERE x<32; + CREATE INDEX t2y ON t2(y); + CREATE VIRTUAL TABLE c2 + USING transitive_closure(tablename=t2, idcolumn=x, parentcolumn=y); +} + +# t2 full-table +do_execsql_test 2.1 { + SELECT count(*), min(id), max(id) FROM c2 WHERE root=1; +} {31 1 31} +# t2 root=10 +do_execsql_test 2.2 { + SELECT id FROM c2 WHERE root=10; +} {10 20 21} +# t2 root=11 +do_execsql_test 2.3 { + SELECT id FROM c2 WHERE root=12; +} {12 24 25} +# t2 root IN [10,12] +do_execsql_test 2.4 { + SELECT id FROM c2 WHERE root IN (10,12) ORDER BY id; +} {10 12 20 21 24 25} +# t2 root IN [10,12] (sorted) +do_execsql_test 2.5 { + SELECT id FROM c2 WHERE root IN (10,12) ORDER BY +id; +} {10 12 20 21 24 25} + +# t2 c2up from 20 +do_execsql_test 3.0 { + CREATE VIRTUAL TABLE c2up USING transitive_closure( + tablename = t2, + idcolumn = y, + parentcolumn = x + ); + SELECT id FROM c2up WHERE root=20; +} {1 2 5 10 20} + +# cx as c2up +do_execsql_test 3.1 { + SELECT id FROM cx + WHERE root=20 + AND tablename='t2' + AND idcolumn='y' + AND parentcolumn='x'; +} {1 2 5 10 20} + +# t2 first cousins of 20 +do_execsql_test 3.2 { + SELECT DISTINCT id FROM c2 + WHERE root IN (SELECT id FROM c2up + WHERE root=20 AND depth<=2) + ORDER BY id; +} {5 10 11 20 21 22 23} + +# t2 first cousins of 20 +do_execsql_test 3.3 { + SELECT id FROM c2 + WHERE root=(SELECT id FROM c2up + WHERE root=20 AND depth=2) + AND depth=2 + EXCEPT + SELECT id FROM c2 + WHERE root=(SELECT id FROM c2up + WHERE root=20 AND depth=1) + AND depth<=1 + ORDER BY id; +} {22 23} + +# missing tablename. +do_test 4.1 { + catchsql { + SELECT id FROM cx + WHERE root=20 + AND tablename='t3' + AND idcolumn='y' + AND parentcolumn='x'; + } +} {1 {no such table: t3}} + +# missing idcolumn +do_test 4.2 { + catchsql { + SELECT id FROM cx + WHERE root=20 + AND tablename='t2' + AND idcolumn='xyz' + AND parentcolumn='x'; + } +} {1 {no such column: t2.xyz}} + +# missing parentcolumn +do_test 4.3 { + catchsql { + SELECT id FROM cx + WHERE root=20 + AND tablename='t2' + AND idcolumn='x' + AND parentcolumn='pqr'; + } +} {1 {no such column: t2.pqr}} + +# generic closure +do_execsql_test 5.1 { + CREATE VIRTUAL TABLE temp.closure USING transitive_closure; + SELECT id FROM closure + WHERE root=1 + AND depth=3 + AND tablename='t1' + AND idcolumn='x' + AND parentcolumn='y' + ORDER BY id; +} {8 9 10 11 12 13 14 15} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/coalesce.test b/components/external/SQLite-3.8.1/test/coalesce.test new file mode 100644 index 0000000000000000000000000000000000000000..af4ea8dfa9b8f78af133743ee0505b58081fa52b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/coalesce.test @@ -0,0 +1,84 @@ +# 2009 November 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# Additional test cases for the COALESCE() and IFNULL() functions. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +do_test coalesce-1.0 { + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, d); + INSERT INTO t1 VALUES(1, null, null, null); + INSERT INTO t1 VALUES(2, 2, 99, 99); + INSERT INTO t1 VALUES(3, null, 3, 99); + INSERT INTO t1 VALUES(4, null, null, 4); + INSERT INTO t1 VALUES(5, null, null, null); + INSERT INTO t1 VALUES(6, 22, 99, 99); + INSERT INTO t1 VALUES(7, null, 33, 99); + INSERT INTO t1 VALUES(8, null, null, 44); + + SELECT coalesce(b,c,d) FROM t1 ORDER BY a; + } +} {{} 2 3 4 {} 22 33 44} +do_test coalesce-1.1 { + db eval { + SELECT coalesce(d+c+b,d+c,d) FROM t1 ORDER BY a; + } +} {{} 200 102 4 {} 220 132 44} +do_test coalesce-1.2 { + db eval { + SELECT ifnull(d+c+b,ifnull(d+c,d)) FROM t1 ORDER BY a; + } +} {{} 200 102 4 {} 220 132 44} +do_test coalesce-1.3 { + db eval { + SELECT ifnull(ifnull(d+c+b,d+c),d) FROM t1 ORDER BY a; + } +} {{} 200 102 4 {} 220 132 44} +do_test coalesce-1.4 { + db eval { + SELECT ifnull(ifnull(b,c),d) FROM t1 ORDER BY a; + } +} {{} 2 3 4 {} 22 33 44} +do_test coalesce-1.5 { + db eval { + SELECT ifnull(b,ifnull(c,d)) FROM t1 ORDER BY a; + } +} {{} 2 3 4 {} 22 33 44} +do_test coalesce-1.6 { + db eval { + SELECT coalesce(b,NOT b,-b,abs(b),lower(b),length(b),min(b,5),b*123,c) + FROM t1 ORDER BY a; + } +} {{} 2 3 {} {} 22 33 {}} +do_test coalesce-1.7 { + db eval { + SELECT ifnull(nullif(a,4),99) + FROM t1 ORDER BY a; + } +} {1 2 3 99 5 6 7 8} +do_test coalesce-1.8 { + db eval { +pragma vdbe_listing=on; + SELECT coalesce( + CASE WHEN b=2 THEN 123 END, + CASE WHEN b=3 THEN 234 END, + CASE WHEN c=3 THEN 345 WHEN c=33 THEN 456 END, + d + ) + FROM t1 ORDER BY a; + } +} {{} 123 345 4 {} 99 456 44} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collate1.test b/components/external/SQLite-3.8.1/test/collate1.test new file mode 100644 index 0000000000000000000000000000000000000000..e9ac93aa304756763903776d402e71fdd8631fc2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collate1.test @@ -0,0 +1,337 @@ +# +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is page cache subsystem. +# +# $Id: collate1.test,v 1.5 2007/02/01 23:02:46 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# +# Tests are roughly organised as follows: +# +# collate1-1.* - Single-field ORDER BY with an explicit COLLATE clause. +# collate1-2.* - Multi-field ORDER BY with an explicit COLLATE clause. +# collate1-3.* - ORDER BY using a default collation type. Also that an +# explict collate type overrides a default collate type. +# collate1-4.* - ORDER BY using a data type. +# + +# +# Collation type 'HEX'. If an argument can be interpreted as a hexadecimal +# number, then it is converted to one before the comparison is performed. +# Numbers are less than other strings. If neither argument is a number, +# [string compare] is used. +# +db collate HEX hex_collate +proc hex_collate {lhs rhs} { + set lhs_ishex [regexp {^(0x|)[1234567890abcdefABCDEF]+$} $lhs] + set rhs_ishex [regexp {^(0x|)[1234567890abcdefABCDEF]+$} $rhs] + if {$lhs_ishex && $rhs_ishex} { + set lhsx [scan $lhs %x] + set rhsx [scan $rhs %x] + if {$lhs < $rhs} {return -1} + if {$lhs == $rhs} {return 0} + if {$lhs > $rhs} {return 1} + } + if {$lhs_ishex} { + return -1; + } + if {$rhs_ishex} { + return 1; + } + return [string compare $lhs $rhs] +} +db function hex {format 0x%X} + +# Mimic the SQLite 2 collation type NUMERIC. +db collate numeric numeric_collate +proc numeric_collate {lhs rhs} { + if {$lhs == $rhs} {return 0} + return [expr ($lhs>$rhs)?1:-1] +} + +do_test collate1-1.0 { + execsql { + CREATE TABLE collate1t1(c1, c2); + INSERT INTO collate1t1 VALUES(45, hex(45)); + INSERT INTO collate1t1 VALUES(NULL, NULL); + INSERT INTO collate1t1 VALUES(281, hex(281)); + } +} {} +do_test collate1-1.1 { + execsql { + SELECT c2 FROM collate1t1 ORDER BY 1; + } +} {{} 0x119 0x2D} +do_test collate1-1.2 { +breakpoint + execsql { + SELECT c2 FROM collate1t1 ORDER BY 1 COLLATE hex; + } +} {{} 0x2D 0x119} +do_test collate1-1.3 { + execsql { + SELECT c2 FROM collate1t1 ORDER BY 1 COLLATE hex DESC; + } +} {0x119 0x2D {}} +do_test collate1-1.4 { + execsql { + SELECT c2 FROM collate1t1 ORDER BY 1 COLLATE hex ASC; + } +} {{} 0x2D 0x119} +do_test collate1-1.5 { + execsql { + SELECT c2 COLLATE hex FROM collate1t1 ORDER BY 1 + } +} {{} 0x2D 0x119} +do_test collate1-1.6 { + execsql { + SELECT c2 COLLATE hex FROM collate1t1 ORDER BY 1 ASC + } +} {{} 0x2D 0x119} +do_test collate1-1.7 { + execsql { + SELECT c2 COLLATE hex FROM collate1t1 ORDER BY 1 DESC + } +} {0x119 0x2D {}} +do_test collate1-1.99 { + execsql { + DROP TABLE collate1t1; + } +} {} + +do_test collate1-2.0 { + execsql { + CREATE TABLE collate1t1(c1, c2); + INSERT INTO collate1t1 VALUES('5', '0x11'); + INSERT INTO collate1t1 VALUES('5', '0xA'); + INSERT INTO collate1t1 VALUES(NULL, NULL); + INSERT INTO collate1t1 VALUES('7', '0xA'); + INSERT INTO collate1t1 VALUES('11', '0x11'); + INSERT INTO collate1t1 VALUES('11', '0x101'); + } +} {} +do_test collate1-2.2 { + execsql { + SELECT c1, c2 FROM collate1t1 ORDER BY 1 COLLATE numeric, 2 COLLATE hex; + } +} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101} +do_test collate1-2.3 { + execsql { + SELECT c1, c2 FROM collate1t1 ORDER BY 1 COLLATE binary, 2 COLLATE hex; + } +} {{} {} 11 0x11 11 0x101 5 0xA 5 0x11 7 0xA} +do_test collate1-2.4 { + execsql { + SELECT c1, c2 FROM collate1t1 ORDER BY 1 COLLATE binary DESC, 2 COLLATE hex; + } +} {7 0xA 5 0xA 5 0x11 11 0x11 11 0x101 {} {}} +do_test collate1-2.5 { + execsql { + SELECT c1, c2 FROM collate1t1 + ORDER BY 1 COLLATE binary DESC, 2 COLLATE hex DESC; + } +} {7 0xA 5 0x11 5 0xA 11 0x101 11 0x11 {} {}} +do_test collate1-2.6 { + execsql { + SELECT c1, c2 FROM collate1t1 + ORDER BY 1 COLLATE binary ASC, 2 COLLATE hex ASC; + } +} {{} {} 11 0x11 11 0x101 5 0xA 5 0x11 7 0xA} +do_test collate1-2.12.1 { + execsql { + SELECT c1 COLLATE numeric, c2 FROM collate1t1 + ORDER BY 1, 2 COLLATE hex; + } +} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101} +do_test collate1-2.12.2 { + execsql { + SELECT c1 COLLATE hex, c2 FROM collate1t1 + ORDER BY 1 COLLATE numeric, 2 COLLATE hex; + } +} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101} +do_test collate1-2.12.3 { + execsql { + SELECT c1, c2 COLLATE hex FROM collate1t1 + ORDER BY 1 COLLATE numeric, 2; + } +} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101} +do_test collate1-2.12.4 { + execsql { + SELECT c1 COLLATE numeric, c2 COLLATE hex + FROM collate1t1 + ORDER BY 1, 2; + } +} {{} {} 5 0xA 5 0x11 7 0xA 11 0x11 11 0x101} +do_test collate1-2.13 { + execsql { + SELECT c1 COLLATE binary, c2 COLLATE hex + FROM collate1t1 + ORDER BY 1, 2; + } +} {{} {} 11 0x11 11 0x101 5 0xA 5 0x11 7 0xA} +do_test collate1-2.14 { + execsql { + SELECT c1, c2 + FROM collate1t1 ORDER BY 1 COLLATE binary DESC, 2 COLLATE hex; + } +} {7 0xA 5 0xA 5 0x11 11 0x11 11 0x101 {} {}} +do_test collate1-2.15 { + execsql { + SELECT c1 COLLATE binary, c2 COLLATE hex + FROM collate1t1 + ORDER BY 1 DESC, 2 DESC; + } +} {7 0xA 5 0x11 5 0xA 11 0x101 11 0x11 {} {}} +do_test collate1-2.16 { + execsql { + SELECT c1 COLLATE hex, c2 COLLATE binary + FROM collate1t1 + ORDER BY 1 COLLATE binary ASC, 2 COLLATE hex ASC; + } +} {{} {} 11 0x11 11 0x101 5 0xA 5 0x11 7 0xA} +do_test collate1-2.99 { + execsql { + DROP TABLE collate1t1; + } +} {} + +# +# These tests ensure that the default collation type for a column is used +# by an ORDER BY clause correctly. The focus is all the different ways +# the column can be referenced. i.e. a, collate2t1.a, main.collate2t1.a etc. +# +do_test collate1-3.0 { + execsql { + CREATE TABLE collate1t1(a COLLATE hex, b); + INSERT INTO collate1t1 VALUES( '0x5', 5 ); + INSERT INTO collate1t1 VALUES( '1', 1 ); + INSERT INTO collate1t1 VALUES( '0x45', 69 ); + INSERT INTO collate1t1 VALUES( NULL, NULL ); + SELECT * FROM collate1t1 ORDER BY a; + } +} {{} {} 1 1 0x5 5 0x45 69} + +do_test collate1-3.1 { + execsql { + SELECT * FROM collate1t1 ORDER BY 1; + } +} {{} {} 1 1 0x5 5 0x45 69} +do_test collate1-3.2 { + execsql { + SELECT * FROM collate1t1 ORDER BY collate1t1.a; + } +} {{} {} 1 1 0x5 5 0x45 69} +do_test collate1-3.3 { + execsql { + SELECT * FROM collate1t1 ORDER BY main.collate1t1.a; + } +} {{} {} 1 1 0x5 5 0x45 69} +do_test collate1-3.4 { + execsql { + SELECT a as c1, b as c2 FROM collate1t1 ORDER BY c1; + } +} {{} {} 1 1 0x5 5 0x45 69} +do_test collate1-3.5 { + execsql { + SELECT a as c1, b as c2 FROM collate1t1 ORDER BY c1 COLLATE binary; + } +} {{} {} 0x45 69 0x5 5 1 1} +do_test collate1-3.5.1 { + execsql { + SELECT a COLLATE binary as c1, b as c2 + FROM collate1t1 ORDER BY c1; + } +} {{} {} 0x45 69 0x5 5 1 1} +do_test collate1-3.6 { + execsql { + DROP TABLE collate1t1; + } +} {} + +# Update for SQLite version 3. The collate1-4.* test cases were written +# before manifest types were introduced. The following test cases still +# work, due to the 'affinity' mechanism, but they don't prove anything +# about collation sequences. +# +do_test collate1-4.0 { + execsql { + CREATE TABLE collate1t1(c1 numeric, c2 text); + INSERT INTO collate1t1 VALUES(1, 1); + INSERT INTO collate1t1 VALUES(12, 12); + INSERT INTO collate1t1 VALUES(NULL, NULL); + INSERT INTO collate1t1 VALUES(101, 101); + } +} {} +do_test collate1-4.1 { + execsql { + SELECT c1 FROM collate1t1 ORDER BY 1; + } +} {{} 1 12 101} +do_test collate1-4.2 { + execsql { + SELECT c2 FROM collate1t1 ORDER BY 1; + } +} {{} 1 101 12} +do_test collate1-4.3 { + execsql { + SELECT c2+0 FROM collate1t1 ORDER BY 1; + } +} {{} 1 12 101} +do_test collate1-4.4 { + execsql { + SELECT c1||'' FROM collate1t1 ORDER BY 1; + } +} {{} 1 101 12} +do_test collate1-4.4.1 { + execsql { + SELECT (c1||'') COLLATE numeric FROM collate1t1 ORDER BY 1; + } +} {{} 1 12 101} +do_test collate1-4.5 { + execsql { + DROP TABLE collate1t1; + } +} {} + +# A problem reported on the mailing list: A CREATE TABLE statement +# is allowed to have two or more COLLATE clauses on the same column. +# That probably ought to be an error, but we allow it for backwards +# compatibility. Just make sure it works and doesn't leak memory. +# +do_test collate1-5.1 { + execsql { + CREATE TABLE c5( + id INTEGER PRIMARY KEY, + a TEXT COLLATE binary COLLATE nocase COLLATE rtrim, + b TEXT COLLATE nocase COLLATE binary, + c TEXT COLLATE rtrim COLLATE binary COLLATE rtrim COLLATE nocase + ); + INSERT INTO c5 VALUES(1, 'abc','abc','abc'); + INSERT INTO c5 VALUES(2, 'abc ','ABC','ABC'); + SELECT id FROM c5 WHERE a='abc' ORDER BY id; + } +} {1 2} +do_test collate1-5.2 { + execsql { + SELECT id FROM c5 WHERE b='abc' ORDER BY id; + } +} {1} +do_test collate1-5.3 { + execsql { + SELECT id FROM c5 WHERE c='abc' ORDER BY id; + } +} {1 2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collate2.test b/components/external/SQLite-3.8.1/test/collate2.test new file mode 100644 index 0000000000000000000000000000000000000000..d5aadb4eb56811f03cc4df480c1186f642c7bdd0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collate2.test @@ -0,0 +1,724 @@ +# +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is page cache subsystem. +# +# $Id: collate2.test,v 1.6 2008/08/20 16:35:10 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set ::testprefix collate2 + +# +# Tests are organised as follows: +# +# collate2-1.* WHERE expressions (sqliteExprIfTrue). +# collate2-2.* WHERE NOT expressions (sqliteExprIfFalse). +# collate2-3.* SELECT expressions (sqliteExprCode). +# collate2-4.* Precedence of collation/data types in binary comparisons +# collate2-5.* JOIN syntax. +# + +# Create a collation type BACKWARDS for use in testing. This collation type +# is similar to the built-in TEXT collation type except the order of +# characters in each string is reversed before the comparison is performed. +db collate BACKWARDS backwards_collate +proc backwards_collate {a b} { + set ra {}; + set rb {} + foreach c [split $a {}] { set ra $c$ra } + foreach c [split $b {}] { set rb $c$rb } + return [string compare $ra $rb] +} + +# The following values are used in these tests: +# NULL aa ab ba bb aA aB bA bB Aa Ab Ba Bb AA AB BA BB +# +# The collation orders for each of the tested collation types are: +# +# BINARY: NULL AA AB Aa Ab BA BB Ba Bb aA aB aa ab bA bB ba bb +# NOCASE: NULL aa aA Aa AA ab aB Ab AB ba bA Ba BA bb bB Bb BB +# BACKWARDS: NULL AA BA aA bA AB BB aB bB Aa Ba aa ba Ab Bb ab bb +# +# These tests verify that the default collation type for a column is used +# for comparison operators (<, >, <=, >=, =) involving that column and +# an expression that is not a column with a default collation type. +# +# The collation sequences BINARY and NOCASE are built-in, the BACKWARDS +# collation sequence is implemented by the TCL proc backwards_collate +# above. +# +do_test collate2-1.0 { + execsql { + CREATE TABLE collate2t1( + a COLLATE BINARY, + b COLLATE NOCASE, + c COLLATE BACKWARDS + ); + INSERT INTO collate2t1 VALUES( NULL, NULL, NULL ); + + INSERT INTO collate2t1 VALUES( 'aa', 'aa', 'aa' ); + INSERT INTO collate2t1 VALUES( 'ab', 'ab', 'ab' ); + INSERT INTO collate2t1 VALUES( 'ba', 'ba', 'ba' ); + INSERT INTO collate2t1 VALUES( 'bb', 'bb', 'bb' ); + + INSERT INTO collate2t1 VALUES( 'aA', 'aA', 'aA' ); + INSERT INTO collate2t1 VALUES( 'aB', 'aB', 'aB' ); + INSERT INTO collate2t1 VALUES( 'bA', 'bA', 'bA' ); + INSERT INTO collate2t1 VALUES( 'bB', 'bB', 'bB' ); + + INSERT INTO collate2t1 VALUES( 'Aa', 'Aa', 'Aa' ); + INSERT INTO collate2t1 VALUES( 'Ab', 'Ab', 'Ab' ); + INSERT INTO collate2t1 VALUES( 'Ba', 'Ba', 'Ba' ); + INSERT INTO collate2t1 VALUES( 'Bb', 'Bb', 'Bb' ); + + INSERT INTO collate2t1 VALUES( 'AA', 'AA', 'AA' ); + INSERT INTO collate2t1 VALUES( 'AB', 'AB', 'AB' ); + INSERT INTO collate2t1 VALUES( 'BA', 'BA', 'BA' ); + INSERT INTO collate2t1 VALUES( 'BB', 'BB', 'BB' ); + } + if {[info exists collate_test_use_index]} { + execsql { + CREATE INDEX collate2t1_i1 ON collate2t1(a); + CREATE INDEX collate2t1_i2 ON collate2t1(b); + CREATE INDEX collate2t1_i3 ON collate2t1(c); + } + } +} {} +do_test collate2-1.1 { + execsql { + SELECT a FROM collate2t1 WHERE a > 'aa' ORDER BY 1; + } +} {ab bA bB ba bb} +do_test collate2-1.1.1 { + execsql { + SELECT a FROM collate2t1 WHERE a COLLATE binary > 'aa' ORDER BY 1; + } +} {ab bA bB ba bb} +do_test collate2-1.1.2 { + execsql { + SELECT a FROM collate2t1 WHERE b COLLATE binary > 'aa' ORDER BY 1; + } +} {ab bA bB ba bb} +do_test collate2-1.1.3 { + execsql { + SELECT a FROM collate2t1 WHERE c COLLATE binary > 'aa' ORDER BY 1; + } +} {ab bA bB ba bb} +do_test collate2-1.2 { + execsql { + SELECT b FROM collate2t1 WHERE b > 'aa' ORDER BY 1, oid; + } +} {ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.2.1 { + execsql { + SELECT b FROM collate2t1 WHERE a COLLATE nocase > 'aa' + ORDER BY 1, oid; + } +} {ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.2.2 { + execsql { + SELECT b FROM collate2t1 WHERE b COLLATE nocase > 'aa' + ORDER BY 1, oid; + } +} {ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.2.3 { + execsql { + SELECT b FROM collate2t1 WHERE c COLLATE nocase > 'aa' + ORDER BY 1, oid; + } +} {ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.2.4 { + execsql { + SELECT b FROM collate2t1 WHERE b > 'aa' ORDER BY +b; + } +} {ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.2.5 { + execsql { + SELECT b FROM collate2t1 WHERE a COLLATE nocase > 'aa' ORDER BY +b; + } +} {ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.2.6 { + execsql { + SELECT b FROM collate2t1 WHERE b COLLATE nocase > 'aa' ORDER BY +b; + } +} {ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.2.7 { + execsql { + SELECT b FROM collate2t1 WHERE c COLLATE nocase > 'aa' ORDER BY +b; + } +} {ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.3 { + execsql { + SELECT c FROM collate2t1 WHERE c > 'aa' ORDER BY 1; + } +} {ba Ab Bb ab bb} +do_test collate2-1.3.1 { + execsql { + SELECT c FROM collate2t1 WHERE a COLLATE backwards > 'aa' + ORDER BY 1; + } +} {ba Ab Bb ab bb} +do_test collate2-1.3.2 { + execsql { + SELECT c FROM collate2t1 WHERE b COLLATE backwards > 'aa' + ORDER BY 1; + } +} {ba Ab Bb ab bb} +do_test collate2-1.3.3 { + execsql { + SELECT c FROM collate2t1 WHERE c COLLATE backwards > 'aa' + ORDER BY 1; + } +} {ba Ab Bb ab bb} +do_test collate2-1.4 { + execsql { + SELECT a FROM collate2t1 WHERE a < 'aa' ORDER BY 1; + } +} {AA AB Aa Ab BA BB Ba Bb aA aB} +do_test collate2-1.5 { + execsql { + SELECT b FROM collate2t1 WHERE b < 'aa' ORDER BY 1, oid; + } +} {} +do_test collate2-1.5.1 { + execsql { + SELECT b FROM collate2t1 WHERE b < 'aa' ORDER BY +b; + } +} {} +do_test collate2-1.6 { + execsql { + SELECT c FROM collate2t1 WHERE c < 'aa' ORDER BY 1; + } +} {AA BA aA bA AB BB aB bB Aa Ba} +do_test collate2-1.7 { + execsql { + SELECT a FROM collate2t1 WHERE a = 'aa'; + } +} {aa} +do_test collate2-1.8 { + execsql { + SELECT b FROM collate2t1 WHERE b = 'aa' ORDER BY oid; + } +} {aa aA Aa AA} +do_test collate2-1.9 { + execsql { + SELECT c FROM collate2t1 WHERE c = 'aa'; + } +} {aa} +do_test collate2-1.10 { + execsql { + SELECT a FROM collate2t1 WHERE a >= 'aa' ORDER BY 1; + } +} {aa ab bA bB ba bb} +do_test collate2-1.11 { + execsql { + SELECT b FROM collate2t1 WHERE b >= 'aa' ORDER BY 1, oid; + } +} {aa aA Aa AA ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.12 { + execsql { + SELECT c FROM collate2t1 WHERE c >= 'aa' ORDER BY 1; + } +} {aa ba Ab Bb ab bb} +do_test collate2-1.13 { + execsql { + SELECT a FROM collate2t1 WHERE a <= 'aa' ORDER BY 1; + } +} {AA AB Aa Ab BA BB Ba Bb aA aB aa} +do_test collate2-1.14 { + execsql { + SELECT b FROM collate2t1 WHERE b <= 'aa' ORDER BY 1, oid; + } +} {aa aA Aa AA} +do_test collate2-1.15 { + execsql { + SELECT c FROM collate2t1 WHERE c <= 'aa' ORDER BY 1; + } +} {AA BA aA bA AB BB aB bB Aa Ba aa} +do_test collate2-1.16 { + execsql { + SELECT a FROM collate2t1 WHERE a BETWEEN 'Aa' AND 'Bb' ORDER BY 1; + } +} {Aa Ab BA BB Ba Bb} +do_test collate2-1.17 { + execsql { + SELECT b FROM collate2t1 WHERE b BETWEEN 'Aa' AND 'Bb' ORDER BY 1, oid; + } +} {aa aA Aa AA ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.17.1 { + execsql { + SELECT b FROM collate2t1 WHERE b BETWEEN 'Aa' AND 'Bb' ORDER BY +b; + } +} {aa aA Aa AA ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-1.18 { + execsql { + SELECT c FROM collate2t1 WHERE c BETWEEN 'Aa' AND 'Bb' ORDER BY 1; + } +} {Aa Ba aa ba Ab Bb} +do_test collate2-1.19 { + execsql { + SELECT a FROM collate2t1 WHERE + CASE a WHEN 'aa' THEN 1 ELSE 0 END + ORDER BY 1, oid; + } +} {aa} +do_test collate2-1.20 { + execsql { + SELECT b FROM collate2t1 WHERE + CASE b WHEN 'aa' THEN 1 ELSE 0 END + ORDER BY 1, oid; + } +} {aa aA Aa AA} +do_test collate2-1.21 { + execsql { + SELECT c FROM collate2t1 WHERE + CASE c WHEN 'aa' THEN 1 ELSE 0 END + ORDER BY 1, oid; + } +} {aa} + +ifcapable subquery { + do_test collate2-1.22 { + execsql { + SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb') ORDER BY 1, oid; + } + } {aa bb} + do_test collate2-1.23 { + execsql { + SELECT b FROM collate2t1 WHERE b IN ('aa', 'bb') ORDER BY 1, oid; + } + } {aa aA Aa AA bb bB Bb BB} + do_test collate2-1.24 { + execsql { + SELECT c FROM collate2t1 WHERE c IN ('aa', 'bb') ORDER BY 1, oid; + } + } {aa bb} + do_test collate2-1.25 { + execsql { + SELECT a FROM collate2t1 + WHERE a IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')); + } + } {aa bb} + do_test collate2-1.26 { + execsql { + SELECT b FROM collate2t1 + WHERE b IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')); + } + } {aa bb aA bB Aa Bb AA BB} + do_test collate2-1.27 { + execsql { + SELECT c FROM collate2t1 + WHERE c IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')); + } + } {aa bb} +} ;# ifcapable subquery + +do_test collate2-2.1 { + execsql { + SELECT a FROM collate2t1 WHERE NOT a > 'aa' ORDER BY 1; + } +} {AA AB Aa Ab BA BB Ba Bb aA aB aa} +do_test collate2-2.2 { + execsql { + SELECT b FROM collate2t1 WHERE NOT b > 'aa' ORDER BY 1, oid; + } +} {aa aA Aa AA} +do_test collate2-2.3 { + execsql { + SELECT c FROM collate2t1 WHERE NOT c > 'aa' ORDER BY 1; + } +} {AA BA aA bA AB BB aB bB Aa Ba aa} +do_test collate2-2.4 { + execsql { + SELECT a FROM collate2t1 WHERE NOT a < 'aa' ORDER BY 1; + } +} {aa ab bA bB ba bb} +do_test collate2-2.5 { + execsql { + SELECT b FROM collate2t1 WHERE NOT b < 'aa' ORDER BY 1, oid; + } +} {aa aA Aa AA ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-2.6 { + execsql { + SELECT c FROM collate2t1 WHERE NOT c < 'aa' ORDER BY 1; + } +} {aa ba Ab Bb ab bb} +do_test collate2-2.7 { + execsql { + SELECT a FROM collate2t1 WHERE NOT a = 'aa'; + } +} {ab ba bb aA aB bA bB Aa Ab Ba Bb AA AB BA BB} +do_test collate2-2.8 { + execsql { + SELECT b FROM collate2t1 WHERE NOT b = 'aa'; + } +} {ab ba bb aB bA bB Ab Ba Bb AB BA BB} +do_test collate2-2.9 { + execsql { + SELECT c FROM collate2t1 WHERE NOT c = 'aa'; + } +} {ab ba bb aA aB bA bB Aa Ab Ba Bb AA AB BA BB} +do_test collate2-2.10 { + execsql { + SELECT a FROM collate2t1 WHERE NOT a >= 'aa' ORDER BY 1; + } +} {AA AB Aa Ab BA BB Ba Bb aA aB} +do_test collate2-2.11 { + execsql { + SELECT b FROM collate2t1 WHERE NOT b >= 'aa' ORDER BY 1, oid; + } +} {} +do_test collate2-2.12 { + execsql { + SELECT c FROM collate2t1 WHERE NOT c >= 'aa' ORDER BY 1; + } +} {AA BA aA bA AB BB aB bB Aa Ba} +do_test collate2-2.13 { + execsql { + SELECT a FROM collate2t1 WHERE NOT a <= 'aa' ORDER BY 1; + } +} {ab bA bB ba bb} +do_test collate2-2.14 { + execsql { + SELECT b FROM collate2t1 WHERE NOT b <= 'aa' ORDER BY 1, oid; + } +} {ab aB Ab AB ba bA Ba BA bb bB Bb BB} +do_test collate2-2.15 { + execsql { + SELECT c FROM collate2t1 WHERE NOT c <= 'aa' ORDER BY 1; + } +} {ba Ab Bb ab bb} +do_test collate2-2.16 { + execsql { + SELECT a FROM collate2t1 WHERE a NOT BETWEEN 'Aa' AND 'Bb' ORDER BY 1; + } +} {AA AB aA aB aa ab bA bB ba bb} +do_test collate2-2.17 { + execsql { + SELECT b FROM collate2t1 WHERE b NOT BETWEEN 'Aa' AND 'Bb' ORDER BY 1, oid; + } +} {} +do_test collate2-2.18 { + execsql { + SELECT c FROM collate2t1 WHERE c NOT BETWEEN 'Aa' AND 'Bb' ORDER BY 1; + } +} {AA BA aA bA AB BB aB bB ab bb} +do_test collate2-2.19 { + execsql { + SELECT a FROM collate2t1 WHERE NOT CASE a WHEN 'aa' THEN 1 ELSE 0 END; + } +} {{} ab ba bb aA aB bA bB Aa Ab Ba Bb AA AB BA BB} +do_test collate2-2.20 { + execsql { + SELECT b FROM collate2t1 WHERE NOT CASE b WHEN 'aa' THEN 1 ELSE 0 END; + } +} {{} ab ba bb aB bA bB Ab Ba Bb AB BA BB} +do_test collate2-2.21 { + execsql { + SELECT c FROM collate2t1 WHERE NOT CASE c WHEN 'aa' THEN 1 ELSE 0 END; + } +} {{} ab ba bb aA aB bA bB Aa Ab Ba Bb AA AB BA BB} + +ifcapable subquery { + do_test collate2-2.22 { + execsql { + SELECT a FROM collate2t1 WHERE NOT a IN ('aa', 'bb'); + } + } {ab ba aA aB bA bB Aa Ab Ba Bb AA AB BA BB} + do_test collate2-2.23 { + execsql { + SELECT b FROM collate2t1 WHERE NOT b IN ('aa', 'bb'); + } + } {ab ba aB bA Ab Ba AB BA} + do_test collate2-2.24 { + execsql { + SELECT c FROM collate2t1 WHERE NOT c IN ('aa', 'bb'); + } + } {ab ba aA aB bA bB Aa Ab Ba Bb AA AB BA BB} + do_test collate2-2.25 { + execsql { + SELECT a FROM collate2t1 + WHERE NOT a IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')); + } + } {ab ba aA aB bA bB Aa Ab Ba Bb AA AB BA BB} + do_test collate2-2.26 { + execsql { + SELECT b FROM collate2t1 + WHERE NOT b IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')); + } + } {ab ba aB bA Ab Ba AB BA} + do_test collate2-2.27 { + execsql { + SELECT c FROM collate2t1 + WHERE NOT c IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')); + } + } {ab ba aA aB bA bB Aa Ab Ba Bb AA AB BA BB} +} + +do_test collate2-3.1 { + execsql { + SELECT a > 'aa' FROM collate2t1; + } +} {{} 0 1 1 1 0 0 1 1 0 0 0 0 0 0 0 0} +do_test collate2-3.2 { + execsql { + SELECT b > 'aa' FROM collate2t1; + } +} {{} 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1} +do_test collate2-3.3 { + execsql { + SELECT c > 'aa' FROM collate2t1; + } +} {{} 0 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0} +do_test collate2-3.4 { + execsql { + SELECT a < 'aa' FROM collate2t1; + } +} {{} 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1} +do_test collate2-3.5 { + execsql { + SELECT b < 'aa' FROM collate2t1; + } +} {{} 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} +do_test collate2-3.6 { + execsql { + SELECT c < 'aa' FROM collate2t1; + } +} {{} 0 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1} +do_test collate2-3.7 { + execsql { + SELECT a = 'aa' FROM collate2t1; + } +} {{} 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} +do_test collate2-3.8 { + execsql { + SELECT b = 'aa' FROM collate2t1; + } +} {{} 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0} +do_test collate2-3.9 { + execsql { + SELECT c = 'aa' FROM collate2t1; + } +} {{} 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} +do_test collate2-3.10 { + execsql { + SELECT a <= 'aa' FROM collate2t1; + } +} {{} 1 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1} +do_test collate2-3.11 { + execsql { + SELECT b <= 'aa' FROM collate2t1; + } +} {{} 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0} +do_test collate2-3.12 { + execsql { + SELECT c <= 'aa' FROM collate2t1; + } +} {{} 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1} +do_test collate2-3.13 { + execsql { + SELECT a >= 'aa' FROM collate2t1; + } +} {{} 1 1 1 1 0 0 1 1 0 0 0 0 0 0 0 0} +do_test collate2-3.14 { + execsql { + SELECT b >= 'aa' FROM collate2t1; + } +} {{} 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1} +do_test collate2-3.15 { + execsql { + SELECT c >= 'aa' FROM collate2t1; + } +} {{} 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0} +do_test collate2-3.16 { + execsql { + SELECT a BETWEEN 'Aa' AND 'Bb' FROM collate2t1; + } +} {{} 0 0 0 0 0 0 0 0 1 1 1 1 0 0 1 1} +do_test collate2-3.17 { + execsql { + SELECT b BETWEEN 'Aa' AND 'Bb' FROM collate2t1; + } +} {{} 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1} +do_test collate2-3.18 { + execsql { + SELECT c BETWEEN 'Aa' AND 'Bb' FROM collate2t1; + } +} {{} 1 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0} +do_test collate2-3.19 { + execsql { + SELECT CASE a WHEN 'aa' THEN 1 ELSE 0 END FROM collate2t1; + } +} {0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} +do_test collate2-3.20 { + execsql { + SELECT CASE b WHEN 'aa' THEN 1 ELSE 0 END FROM collate2t1; + } +} {0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0} +do_test collate2-3.21 { + execsql { + SELECT CASE c WHEN 'aa' THEN 1 ELSE 0 END FROM collate2t1; + } +} {0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0} + +ifcapable subquery { + do_test collate2-3.22 { + execsql { + SELECT a IN ('aa', 'bb') FROM collate2t1; + } + } {{} 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0} + do_test collate2-3.23 { + execsql { + SELECT b IN ('aa', 'bb') FROM collate2t1; + } + } {{} 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1} + do_test collate2-3.24 { + execsql { + SELECT c IN ('aa', 'bb') FROM collate2t1; + } + } {{} 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0} + do_test collate2-3.25 { + execsql { + SELECT a IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')) + FROM collate2t1; + } + } {{} 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0} + do_test collate2-3.26 { + execsql { + SELECT b IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')) + FROM collate2t1; + } + } {{} 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1} + do_test collate2-3.27 { + execsql { + SELECT c IN (SELECT a FROM collate2t1 WHERE a IN ('aa', 'bb')) + FROM collate2t1; + } + } {{} 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0} +} + +do_test collate2-4.0 { + execsql { + CREATE TABLE collate2t2(b COLLATE binary); + CREATE TABLE collate2t3(b text); + INSERT INTO collate2t2 VALUES('aa'); + INSERT INTO collate2t3 VALUES('aa'); + } +} {} + +# Test that when both sides of a binary comparison operator have +# default collation types, the collate type for the leftmost term +# is used. +do_test collate2-4.1 { + execsql { + SELECT collate2t1.a FROM collate2t1, collate2t2 + WHERE collate2t1.b = collate2t2.b; + } +} {aa aA Aa AA} +do_test collate2-4.2 { + execsql { + SELECT collate2t1.a FROM collate2t1, collate2t2 + WHERE collate2t2.b = collate2t1.b; + } +} {aa} + +# Test that when one side has a default collation type and the other +# does not, the collation type is used. +do_test collate2-4.3 { + execsql { + SELECT collate2t1.a FROM collate2t1, collate2t3 + WHERE collate2t1.b = collate2t3.b||'' + ORDER BY +collate2t1.a DESC; + } +} {aa aA Aa AA} +do_test collate2-4.4 { + execsql { + SELECT collate2t1.a FROM collate2t1, collate2t3 + WHERE collate2t3.b||'' = collate2t1.b + ORDER BY +collate2t1.a DESC; + } +} {aa aA Aa AA} + +do_test collate2-4.5 { + execsql { + DROP TABLE collate2t3; + } +} {} + +# +# Test that the default collation types are used when the JOIN syntax +# is used in place of a WHERE clause. +# +# SQLite transforms the JOIN syntax into a WHERE clause internally, so +# the focus of these tests is to ensure that the table on the left-hand-side +# of the join determines the collation type used. +# +do_test collate2-5.0 { + execsql { + SELECT collate2t1.b FROM collate2t1 JOIN collate2t2 USING (b); + } +} {aa aA Aa AA} +do_test collate2-5.1 { + execsql { + SELECT collate2t1.b FROM collate2t2 JOIN collate2t1 USING (b); + } +} {aa} +do_test collate2-5.2 { + execsql { + SELECT collate2t1.b FROM collate2t1 NATURAL JOIN collate2t2; + } +} {aa aA Aa AA} +do_test collate2-5.3 { + execsql { + SELECT collate2t1.b FROM collate2t2 NATURAL JOIN collate2t1; + } +} {aa} +do_test collate2-5.4 { + execsql { + SELECT collate2t2.b FROM collate2t1 LEFT OUTER JOIN collate2t2 USING (b) order by collate2t1.oid; + } +} {{} aa {} {} {} aa {} {} {} aa {} {} {} aa {} {} {}} +do_test collate2-5.5 { + execsql { + SELECT collate2t1.b, collate2t2.b FROM collate2t2 LEFT OUTER JOIN collate2t1 USING (b); + } +} {aa aa} + +do_execsql_test 6.1 { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('b'); + INSERT INTO t1 VALUES('B'); +} +do_execsql_test 6.2 { + SELECT * FROM t1 WHERE x COLLATE nocase BETWEEN 'a' AND 'c'; +} {b B} +do_execsql_test 6.3 { + SELECT * FROM t1 WHERE x BETWEEN 'a' COLLATE nocase AND 'c' COLLATE nocase; +} {b B} +do_execsql_test 6.4 { + SELECT * FROM t1 + WHERE x COLLATE nocase BETWEEN 'a' COLLATE nocase AND 'c' COLLATE nocase; +} {b B} +do_execsql_test 6.5 { + SELECT * FROM t1 WHERE +x COLLATE nocase BETWEEN 'a' AND 'c'; +} {b B} +do_execsql_test 6.6 { + SELECT * FROM t1 WHERE +x BETWEEN 'a' COLLATE nocase AND 'c' COLLATE nocase; +} {b B} +do_execsql_test 6.7 { + SELECT * FROM t1 + WHERE +x COLLATE nocase BETWEEN 'a' COLLATE nocase AND 'c' COLLATE nocase; +} {b B} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collate3.test b/components/external/SQLite-3.8.1/test/collate3.test new file mode 100644 index 0000000000000000000000000000000000000000..2c051cb9a74fbdca4b60cdebace083de0cc4d090 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collate3.test @@ -0,0 +1,526 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is page cache subsystem. +# +# $Id: collate3.test,v 1.13 2008/08/20 16:35:10 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# +# Tests are organised as follows: +# +# collate3.1.* - Errors related to unknown collation sequences. +# collate3.2.* - Errors related to undefined collation sequences. +# collate3.3.* - Writing to a table that has an index with an undefined c.s. +# collate3.4.* - Misc errors. +# collate3.5.* - Collation factory. +# + +# +# These tests ensure that when a user executes a statement with an +# unknown collation sequence an error is returned. +# +do_test collate3-1.0 { + execsql { + CREATE TABLE collate3t1(c1); + } +} {} +do_test collate3-1.1 { + catchsql { + SELECT * FROM collate3t1 ORDER BY 1 collate garbage; + } +} {1 {no such collation sequence: garbage}} +do_test collate3-1.2 { + catchsql { + CREATE TABLE collate3t2(c1 collate garbage); + } +} {1 {no such collation sequence: garbage}} +do_test collate3-1.3 { + catchsql { + CREATE INDEX collate3i1 ON collate3t1(c1 COLLATE garbage); + } +} {1 {no such collation sequence: garbage}} + +execsql { + DROP TABLE collate3t1; +} + +proc caseless {a b} { string compare -nocase $a $b } +do_test collate3-1.4 { + db collate caseless caseless + execsql { + CREATE TABLE t1(a COLLATE caseless); + INSERT INTO t1 VALUES('Abc2'); + INSERT INTO t1 VALUES('abc1'); + INSERT INTO t1 VALUES('aBc3'); + } + execsql { SELECT * FROM t1 ORDER BY a } +} {abc1 Abc2 aBc3} + +do_test collate3-1.5 { + db close + sqlite3 db test.db + catchsql { SELECT * FROM t1 ORDER BY a } +} {1 {no such collation sequence: caseless}} + +do_test collate3-1.6.1 { + db collate caseless caseless + execsql { CREATE INDEX i1 ON t1(a) } + execsql { SELECT * FROM t1 ORDER BY a } +} {abc1 Abc2 aBc3} + +do_test collate3-1.6.2 { + db close + sqlite3 db test.db + catchsql { SELECT * FROM t1 ORDER BY a } +} {1 {no such collation sequence: caseless}} + +do_test collate3-1.6.3 { + db close + sqlite3 db test.db + catchsql { PRAGMA integrity_check } +} {1 {no such collation sequence: caseless}} + +do_test collate3-1.6.4 { + db close + sqlite3 db test.db + catchsql { REINDEX } +} {1 {no such collation sequence: caseless}} + +do_test collate3-1.7.1 { + db collate caseless caseless + execsql { + DROP TABLE t1; + CREATE TABLE t1(a); + CREATE INDEX i1 ON t1(a COLLATE caseless); + INSERT INTO t1 VALUES('Abc2'); + INSERT INTO t1 VALUES('abc1'); + INSERT INTO t1 VALUES('aBc3'); + SELECT * FROM t1 ORDER BY a COLLATE caseless; + } +} {abc1 Abc2 aBc3} + +do_test collate3-1.7.2 { + db close + sqlite3 db test.db + catchsql { SELECT * FROM t1 ORDER BY a COLLATE caseless} +} {1 {no such collation sequence: caseless}} + +do_test collate3-1.7.4 { + db close + sqlite3 db test.db + catchsql { REINDEX } +} {1 {no such collation sequence: caseless}} + +do_test collate3-1.7.3 { + db close + sqlite3 db test.db + catchsql { PRAGMA integrity_check } +} {1 {no such collation sequence: caseless}} + +do_test collate3-1.7.4 { + db close + sqlite3 db test.db + catchsql { REINDEX } +} {1 {no such collation sequence: caseless}} + +do_test collate3-1.7.5 { + db close + sqlite3 db test.db + db collate caseless caseless + catchsql { PRAGMA integrity_check } +} {0 ok} + +proc needed {nm} { db collate caseless caseless } +do_test collate3-1.7.6 { + db close + sqlite3 db test.db + db collation_needed needed + catchsql { PRAGMA integrity_check } +} {0 ok} + +do_test collate3-1.8 { + execsql { DROP TABLE t1 } +} {} + +# +# Create a table with a default collation sequence, then close +# and re-open the database without re-registering the collation +# sequence. Then make sure the library stops us from using +# the collation sequence in: +# * an explicitly collated ORDER BY +# * an ORDER BY that uses the default collation sequence +# * an expression (=) +# * a CREATE TABLE statement +# * a CREATE INDEX statement that uses a default collation sequence +# * a GROUP BY that uses the default collation sequence +# * a SELECT DISTINCT that uses the default collation sequence +# * Compound SELECTs that uses the default collation sequence +# * An ORDER BY on a compound SELECT with an explicit ORDER BY. +# +do_test collate3-2.0 { + db collate string_compare {string compare} + execsql { + CREATE TABLE collate3t1(c1 COLLATE string_compare, c2); + } + db close + sqlite3 db test.db + expr 0 +} 0 +do_test collate3-2.1 { + catchsql { + SELECT * FROM collate3t1 ORDER BY 1 COLLATE string_compare; + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-2.2 { + catchsql { + SELECT * FROM collate3t1 ORDER BY c1; + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-2.3 { + catchsql { + SELECT * FROM collate3t1 WHERE c1 = 'xxx'; + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-2.4 { + catchsql { + CREATE TABLE collate3t2(c1 COLLATE string_compare); + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-2.5 { + catchsql { + CREATE INDEX collate3t1_i1 ON collate3t1(c1); + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-2.6 { + catchsql { + SELECT * FROM collate3t1; + } +} {0 {}} +do_test collate3-2.7.1 { + catchsql { + SELECT count(*) FROM collate3t1 GROUP BY c1; + } +} {1 {no such collation sequence: string_compare}} +# do_test collate3-2.7.2 { +# catchsql { +# SELECT * FROM collate3t1 GROUP BY c1; +# } +# } {1 {GROUP BY may only be used on aggregate queries}} +do_test collate3-2.7.2 { + catchsql { + SELECT * FROM collate3t1 GROUP BY c1; + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-2.8 { + catchsql { + SELECT DISTINCT c1 FROM collate3t1; + } +} {1 {no such collation sequence: string_compare}} + +ifcapable compound { + do_test collate3-2.9 { + catchsql { + SELECT c1 FROM collate3t1 UNION SELECT c1 FROM collate3t1; + } + } {1 {no such collation sequence: string_compare}} + do_test collate3-2.10 { + catchsql { + SELECT c1 FROM collate3t1 EXCEPT SELECT c1 FROM collate3t1; + } + } {1 {no such collation sequence: string_compare}} + do_test collate3-2.11 { + catchsql { + SELECT c1 FROM collate3t1 INTERSECT SELECT c1 FROM collate3t1; + } + } {1 {no such collation sequence: string_compare}} + do_test collate3-2.12 { + catchsql { + SELECT c1 FROM collate3t1 UNION ALL SELECT c1 FROM collate3t1; + } + } {0 {}} + do_test collate3-2.13 { + catchsql { + SELECT 10 UNION ALL SELECT 20 ORDER BY 1 COLLATE string_compare; + } + } {1 {no such collation sequence: string_compare}} + do_test collate3-2.14 { + catchsql { + SELECT 10 INTERSECT SELECT 20 ORDER BY 1 COLLATE string_compare; + } + } {1 {no such collation sequence: string_compare}} + do_test collate3-2.15 { + catchsql { + SELECT 10 EXCEPT SELECT 20 ORDER BY 1 COLLATE string_compare; + } + } {1 {no such collation sequence: string_compare}} + do_test collate3-2.16 { + catchsql { + SELECT 10 UNION SELECT 20 ORDER BY 1 COLLATE string_compare; + } + } {1 {no such collation sequence: string_compare}} + do_test collate3-2.17 { + catchsql { + SELECT c1 FROM collate3t1 UNION ALL SELECT c1 FROM collate3t1 ORDER BY 1; + } + } {1 {no such collation sequence: string_compare}} +} ;# ifcapable compound + +# +# Create an index that uses a collation sequence then close and +# re-open the database without re-registering the collation +# sequence. Then check that for the table with the index +# * An INSERT fails, +# * An UPDATE on the column with the index fails, +# * An UPDATE on a different column succeeds. +# * A DELETE with a WHERE clause fails +# * A DELETE without a WHERE clause succeeds +# +# Also, ensure that the restrictions tested by collate3-2.* still +# apply after the index has been created. +# +do_test collate3-3.0 { + db collate string_compare {string compare} + execsql { + CREATE INDEX collate3t1_i1 ON collate3t1(c1); + INSERT INTO collate3t1 VALUES('xxx', 'yyy'); + } + db close + sqlite3 db test.db + expr 0 +} 0 +db eval {select * from collate3t1} +do_test collate3-3.1 { + catchsql { + INSERT INTO collate3t1 VALUES('xxx', 0); + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-3.2 { + catchsql { + UPDATE collate3t1 SET c1 = 'xxx'; + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-3.3 { + catchsql { + UPDATE collate3t1 SET c2 = 'xxx'; + } +} {0 {}} +do_test collate3-3.4 { + catchsql { + DELETE FROM collate3t1 WHERE 1; + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-3.5 { + catchsql { + SELECT * FROM collate3t1; + } +} {0 {xxx xxx}} +do_test collate3-3.6 { + catchsql { + DELETE FROM collate3t1; + } +} {0 {}} +ifcapable {integrityck} { + do_test collate3-3.8 { + catchsql { + PRAGMA integrity_check + } + } {1 {no such collation sequence: string_compare}} +} +do_test collate3-3.9 { + catchsql { + SELECT * FROM collate3t1; + } +} {0 {}} +do_test collate3-3.10 { + catchsql { + SELECT * FROM collate3t1 ORDER BY 1 COLLATE string_compare; + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-3.11 { + catchsql { + SELECT * FROM collate3t1 ORDER BY c1; + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-3.12 { + catchsql { + SELECT * FROM collate3t1 WHERE c1 = 'xxx'; + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-3.13 { + catchsql { + CREATE TABLE collate3t2(c1 COLLATE string_compare); + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-3.14 { + catchsql { + CREATE INDEX collate3t1_i2 ON collate3t1(c1); + } +} {1 {no such collation sequence: string_compare}} +do_test collate3-3.15 { + execsql { + DROP TABLE collate3t1; + } +} {} + +# Check we can create an index that uses an explicit collation +# sequence and then close and re-open the database. +do_test collate3-4.6 { + db collate user_defined "string compare" + execsql { + CREATE TABLE collate3t1(a, b); + INSERT INTO collate3t1 VALUES('hello', NULL); + CREATE INDEX collate3i1 ON collate3t1(a COLLATE user_defined); + } +} {} +do_test collate3-4.7 { + db close + sqlite3 db test.db + catchsql { + SELECT * FROM collate3t1 ORDER BY a COLLATE user_defined; + } +} {1 {no such collation sequence: user_defined}} +do_test collate3-4.8.1 { + db collate user_defined "string compare" + catchsql { + SELECT * FROM collate3t1 ORDER BY a COLLATE user_defined; + } +} {0 {hello {}}} +do_test collate3-4.8.2 { + db close + lindex [catch { + sqlite3 db test.db + }] 0 +} {0} +do_test collate3-4.8.3 { + execsql { + DROP TABLE collate3t1; + } +} {} + +# Compare strings as numbers. +proc numeric_compare {lhs rhs} { + if {$rhs > $lhs} { + set res -1 + } else { + set res [expr ($lhs > $rhs)?1:0] + } + return $res +} + +# Check we can create a view that uses an explicit collation +# sequence and then close and re-open the database. +ifcapable view { +do_test collate3-4.9 { + db collate user_defined numeric_compare + execsql { + CREATE TABLE collate3t1(a, b); + INSERT INTO collate3t1 VALUES('2', NULL); + INSERT INTO collate3t1 VALUES('101', NULL); + INSERT INTO collate3t1 VALUES('12', NULL); + CREATE VIEW collate3v1 AS SELECT * FROM collate3t1 + ORDER BY 1 COLLATE user_defined; + SELECT * FROM collate3v1; + } +} {2 {} 12 {} 101 {}} +do_test collate3-4.10 { + db close + sqlite3 db test.db + catchsql { + SELECT * FROM collate3v1; + } +} {1 {no such collation sequence: user_defined}} +do_test collate3-4.11 { + db collate user_defined numeric_compare + catchsql { + SELECT * FROM collate3v1; + } +} {0 {2 {} 12 {} 101 {}}} +do_test collate3-4.12 { + execsql { + DROP TABLE collate3t1; + } +} {} +} ;# ifcapable view + +# +# Test the collation factory. In the code, the "no such collation sequence" +# message is only generated in two places. So these tests just test that +# the collation factory can be called once from each of those points. +# +do_test collate3-5.0 { + catchsql { + CREATE TABLE collate3t1(a); + INSERT INTO collate3t1 VALUES(10); + SELECT a FROM collate3t1 ORDER BY 1 COLLATE unk; + } +} {1 {no such collation sequence: unk}} +do_test collate3-5.1 { + set ::cfact_cnt 0 + proc cfact {nm} { + db collate $nm {string compare} + incr ::cfact_cnt + } + db collation_needed cfact +} {} +do_test collate3-5.2 { + catchsql { + SELECT a FROM collate3t1 ORDER BY 1 COLLATE unk; + } +} {0 10} +do_test collate3-5.3 { + set ::cfact_cnt +} {1} +do_test collate3-5.4 { + catchsql { + SELECT a FROM collate3t1 ORDER BY 1 COLLATE unk; + } +} {0 10} +do_test collate3-5.5 { + set ::cfact_cnt +} {1} +do_test collate3-5.6 { + catchsql { + SELECT a FROM collate3t1 ORDER BY 1 COLLATE unk; + } +} {0 10} +do_test collate3-5.7 { + execsql { + DROP TABLE collate3t1; + CREATE TABLE collate3t1(a COLLATE unk); + } + db close + sqlite3 db test.db + catchsql { + SELECT a FROM collate3t1 ORDER BY 1; + } +} {1 {no such collation sequence: unk}} +do_test collate3-5.8 { + set ::cfact_cnt 0 + proc cfact {nm} { + db collate $nm {string compare} + incr ::cfact_cnt + } + db collation_needed cfact + catchsql { + SELECT a FROM collate3t1 ORDER BY 1; + } +} {0 {}} + +do_test collate3-5.9 { + execsql { + DROP TABLE collate3t1; + } +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collate4.test b/components/external/SQLite-3.8.1/test/collate4.test new file mode 100644 index 0000000000000000000000000000000000000000..5ae1e7b930ee74fdf7ad6d77b384b434d29a0859 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collate4.test @@ -0,0 +1,704 @@ +# +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is page cache subsystem. +# +# $Id: collate4.test,v 1.9 2008/01/05 17:39:30 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +db collate TEXT text_collate +proc text_collate {a b} { + return [string compare $a $b] +} + +# Do an SQL statement. Append the search count to the end of the result. +# +proc count sql { + set ::sqlite_search_count 0 + return [concat [execsql $sql] $::sqlite_search_count] +} + +# This procedure executes the SQL. Then it checks the generated program +# for the SQL and appends a "nosort" to the result if the program contains the +# SortCallback opcode. If the program does not contain the SortCallback +# opcode it appends "sort" +# +proc cksort {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + if {$::sqlite_sort_count} {set x sort} {set x nosort} + lappend data $x + return $data +} + +# +# Test cases are organized roughly as follows: +# +# collate4-1.* ORDER BY. +# collate4-2.* WHERE clauses. +# collate4-3.* constraints (primary key, unique). +# collate4-4.* simple min() or max() queries. +# collate4-5.* REINDEX command +# collate4-6.* INTEGER PRIMARY KEY indices. +# + +# +# These tests - collate4-1.* - check that indices are correctly +# selected or not selected to implement ORDER BY clauses when +# user defined collation sequences are involved. +# +# Because these tests also exercise all the different ways indices +# can be created, they also serve to verify that indices are correctly +# initialized with user-defined collation sequences when they are +# created. +# +# Tests named collate4-1.1.* use indices with a single column. Tests +# collate4-1.2.* use indices with two columns. +# +do_test collate4-1.1.0 { + execsql { + CREATE TABLE collate4t1(a COLLATE NOCASE, b COLLATE TEXT); + INSERT INTO collate4t1 VALUES( 'a', 'a' ); + INSERT INTO collate4t1 VALUES( 'b', 'b' ); + INSERT INTO collate4t1 VALUES( NULL, NULL ); + INSERT INTO collate4t1 VALUES( 'B', 'B' ); + INSERT INTO collate4t1 VALUES( 'A', 'A' ); + CREATE INDEX collate4i1 ON collate4t1(a); + CREATE INDEX collate4i2 ON collate4t1(b); + } +} {} +do_test collate4-1.1.1 { + cksort {SELECT a FROM collate4t1 ORDER BY a} +} {{} a A b B nosort} +do_test collate4-1.1.2 { + cksort {SELECT a FROM collate4t1 ORDER BY a COLLATE NOCASE} +} {{} a A b B nosort} +do_test collate4-1.1.3 { + cksort {SELECT a FROM collate4t1 ORDER BY a COLLATE TEXT} +} {{} A B a b sort} +do_test collate4-1.1.4 { + cksort {SELECT b FROM collate4t1 ORDER BY b} +} {{} A B a b nosort} +do_test collate4-1.1.5 { + cksort {SELECT b FROM collate4t1 ORDER BY b COLLATE TEXT} +} {{} A B a b nosort} +do_test collate4-1.1.6 { + cksort {SELECT b FROM collate4t1 ORDER BY b COLLATE NOCASE, rowid} +} {{} a A b B sort} + +do_test collate4-1.1.7 { + execsql { + CREATE TABLE collate4t2( + a PRIMARY KEY COLLATE NOCASE, + b UNIQUE COLLATE TEXT + ); + INSERT INTO collate4t2 VALUES( 'a', 'a' ); + INSERT INTO collate4t2 VALUES( NULL, NULL ); + INSERT INTO collate4t2 VALUES( 'B', 'B' ); + } +} {} +do_test collate4-1.1.8 { + cksort {SELECT a FROM collate4t2 ORDER BY a} +} {{} a B nosort} +do_test collate4-1.1.9 { + cksort {SELECT a FROM collate4t2 ORDER BY a COLLATE NOCASE} +} {{} a B nosort} +do_test collate4-1.1.10 { + cksort {SELECT a FROM collate4t2 ORDER BY a COLLATE TEXT} +} {{} B a sort} +do_test collate4-1.1.11 { + cksort {SELECT b FROM collate4t2 ORDER BY b} +} {{} B a nosort} +do_test collate4-1.1.12 { + cksort {SELECT b FROM collate4t2 ORDER BY b COLLATE TEXT} +} {{} B a nosort} +do_test collate4-1.1.13 { + cksort {SELECT b FROM collate4t2 ORDER BY b COLLATE NOCASE} +} {{} a B sort} + +do_test collate4-1.1.14 { + execsql { + CREATE TABLE collate4t3( + b COLLATE TEXT, + a COLLATE NOCASE, + UNIQUE(a), PRIMARY KEY(b) + ); + INSERT INTO collate4t3 VALUES( 'a', 'a' ); + INSERT INTO collate4t3 VALUES( NULL, NULL ); + INSERT INTO collate4t3 VALUES( 'B', 'B' ); + } +} {} +do_test collate4-1.1.15 { + cksort {SELECT a FROM collate4t3 ORDER BY a} +} {{} a B nosort} +do_test collate4-1.1.16 { + cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE NOCASE} +} {{} a B nosort} +do_test collate4-1.1.17 { + cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE TEXT} +} {{} B a sort} +do_test collate4-1.1.18 { + cksort {SELECT b FROM collate4t3 ORDER BY b} +} {{} B a nosort} +do_test collate4-1.1.19 { + cksort {SELECT b FROM collate4t3 ORDER BY b COLLATE TEXT} +} {{} B a nosort} +do_test collate4-1.1.20 { + cksort {SELECT b FROM collate4t3 ORDER BY b COLLATE NOCASE} +} {{} a B sort} + +do_test collate4-1.1.21 { + execsql { + CREATE TABLE collate4t4(a COLLATE NOCASE, b COLLATE TEXT); + INSERT INTO collate4t4 VALUES( 'a', 'a' ); + INSERT INTO collate4t4 VALUES( 'b', 'b' ); + INSERT INTO collate4t4 VALUES( NULL, NULL ); + INSERT INTO collate4t4 VALUES( 'B', 'B' ); + INSERT INTO collate4t4 VALUES( 'A', 'A' ); + CREATE INDEX collate4i3 ON collate4t4(a COLLATE TEXT); + CREATE INDEX collate4i4 ON collate4t4(b COLLATE NOCASE); + } +} {} +do_test collate4-1.1.22 { + cksort {SELECT a FROM collate4t4 ORDER BY a, rowid} +} {{} a A b B sort} +do_test collate4-1.1.23 { + cksort {SELECT a FROM collate4t4 ORDER BY a COLLATE NOCASE, rowid} +} {{} a A b B sort} +do_test collate4-1.1.24 { + cksort {SELECT a FROM collate4t4 ORDER BY a COLLATE TEXT, rowid} +} {{} A B a b nosort} +do_test collate4-1.1.25 { + cksort {SELECT b FROM collate4t4 ORDER BY b} +} {{} A B a b sort} +do_test collate4-1.1.26 { + cksort {SELECT b FROM collate4t4 ORDER BY b COLLATE TEXT} +} {{} A B a b sort} +do_test collate4-1.1.27 { + cksort {SELECT b FROM collate4t4 ORDER BY b COLLATE NOCASE} +} {{} a A b B nosort} + +do_test collate4-1.1.30 { + execsql { + DROP TABLE collate4t1; + DROP TABLE collate4t2; + DROP TABLE collate4t3; + DROP TABLE collate4t4; + } +} {} + +do_test collate4-1.2.0 { + execsql { + CREATE TABLE collate4t1(a COLLATE NOCASE, b COLLATE TEXT); + INSERT INTO collate4t1 VALUES( 'a', 'a' ); + INSERT INTO collate4t1 VALUES( 'b', 'b' ); + INSERT INTO collate4t1 VALUES( NULL, NULL ); + INSERT INTO collate4t1 VALUES( 'B', 'B' ); + INSERT INTO collate4t1 VALUES( 'A', 'A' ); + CREATE INDEX collate4i1 ON collate4t1(a, b); + } +} {} +do_test collate4-1.2.1 { + cksort {SELECT a FROM collate4t1 ORDER BY a} +} {{} A a B b nosort} +do_test collate4-1.2.2 { + cksort {SELECT a FROM collate4t1 ORDER BY a COLLATE nocase} +} {{} A a B b nosort} +do_test collate4-1.2.3 { + cksort {SELECT a FROM collate4t1 ORDER BY a COLLATE text} +} {{} A B a b sort} +do_test collate4-1.2.4 { + cksort {SELECT a FROM collate4t1 ORDER BY a, b} +} {{} A a B b nosort} +do_test collate4-1.2.5 { + cksort {SELECT a FROM collate4t1 ORDER BY a, b COLLATE nocase, rowid} +} {{} a A b B sort} +do_test collate4-1.2.6 { + cksort {SELECT a FROM collate4t1 ORDER BY a, b COLLATE text} +} {{} A a B b nosort} + +do_test collate4-1.2.7 { + execsql { + CREATE TABLE collate4t2( + a COLLATE NOCASE, + b COLLATE TEXT, + PRIMARY KEY(a, b) + ); + INSERT INTO collate4t2 VALUES( 'a', 'a' ); + INSERT INTO collate4t2 VALUES( NULL, NULL ); + INSERT INTO collate4t2 VALUES( 'B', 'B' ); + } +} {} +do_test collate4-1.2.8 { + cksort {SELECT a FROM collate4t2 ORDER BY a} +} {{} a B nosort} +do_test collate4-1.2.9 { + cksort {SELECT a FROM collate4t2 ORDER BY a COLLATE nocase} +} {{} a B nosort} +do_test collate4-1.2.10 { + cksort {SELECT a FROM collate4t2 ORDER BY a COLLATE text} +} {{} B a sort} +do_test collate4-1.2.11 { + cksort {SELECT a FROM collate4t2 ORDER BY a, b} +} {{} a B nosort} +do_test collate4-1.2.12 { + cksort {SELECT a FROM collate4t2 ORDER BY a, b COLLATE nocase} +} {{} a B sort} +do_test collate4-1.2.13 { + cksort {SELECT a FROM collate4t2 ORDER BY a, b COLLATE text} +} {{} a B nosort} + +do_test collate4-1.2.14 { + execsql { + CREATE TABLE collate4t3(a COLLATE NOCASE, b COLLATE TEXT); + INSERT INTO collate4t3 VALUES( 'a', 'a' ); + INSERT INTO collate4t3 VALUES( 'b', 'b' ); + INSERT INTO collate4t3 VALUES( NULL, NULL ); + INSERT INTO collate4t3 VALUES( 'B', 'B' ); + INSERT INTO collate4t3 VALUES( 'A', 'A' ); + CREATE INDEX collate4i2 ON collate4t3(a COLLATE TEXT, b COLLATE NOCASE); + } +} {} +do_test collate4-1.2.15 { + cksort {SELECT a FROM collate4t3 ORDER BY a, rowid} +} {{} a A b B sort} +do_test collate4-1.2.16 { + cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE nocase, rowid} +} {{} a A b B sort} +do_test collate4-1.2.17 { + cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text} +} {{} A B a b nosort} +do_test collate4-1.2.18 { + cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text, b} +} {{} A B a b sort} +do_test collate4-1.2.19 { + cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text, b COLLATE nocase} +} {{} A B a b nosort} +do_test collate4-1.2.20 { + cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text, b COLLATE text} +} {{} A B a b sort} +do_test collate4-1.2.21 { + cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text DESC} +} {b a B A {} nosort} +do_test collate4-1.2.22 { + cksort {SELECT a FROM collate4t3 ORDER BY a COLLATE text DESC, b} +} {b a B A {} sort} +do_test collate4-1.2.23 { + cksort {SELECT a FROM collate4t3 + ORDER BY a COLLATE text DESC, b COLLATE nocase} +} {b a B A {} sort} +do_test collate4-1.2.24 { + cksort {SELECT a FROM collate4t3 + ORDER BY a COLLATE text DESC, b COLLATE nocase DESC} +} {b a B A {} nosort} + +do_test collate4-1.2.25 { + execsql { + DROP TABLE collate4t1; + DROP TABLE collate4t2; + DROP TABLE collate4t3; + } +} {} + +# +# These tests - collate4-2.* - check that indices are correctly +# selected or not selected to implement WHERE clauses when user +# defined collation sequences are involved. +# +# Indices may optimise WHERE clauses using <, >, <=, >=, = or IN +# operators. +# +do_test collate4-2.1.0 { + execsql { + PRAGMA automatic_index=OFF; + CREATE TABLE collate4t1(a COLLATE NOCASE); + CREATE TABLE collate4t2(b COLLATE TEXT); + + INSERT INTO collate4t1 VALUES('a'); + INSERT INTO collate4t1 VALUES('A'); + INSERT INTO collate4t1 VALUES('b'); + INSERT INTO collate4t1 VALUES('B'); + INSERT INTO collate4t1 VALUES('c'); + INSERT INTO collate4t1 VALUES('C'); + INSERT INTO collate4t1 VALUES('d'); + INSERT INTO collate4t1 VALUES('D'); + INSERT INTO collate4t1 VALUES('e'); + INSERT INTO collate4t1 VALUES('D'); + + INSERT INTO collate4t2 VALUES('A'); + INSERT INTO collate4t2 VALUES('Z'); + } +} {} +do_test collate4-2.1.1 { + count { + SELECT * FROM collate4t2, collate4t1 WHERE a = b; + } +} {A a A A 19} +do_test collate4-2.1.2 { + execsql { + CREATE INDEX collate4i1 ON collate4t1(a); + } + count { + SELECT * FROM collate4t2, collate4t1 WHERE a = b; + } +} {A a A A 5} +do_test collate4-2.1.3 { + count { + SELECT * FROM collate4t2, collate4t1 WHERE b = a; + } +} {A A 19} +do_test collate4-2.1.4 { + execsql { + DROP INDEX collate4i1; + CREATE INDEX collate4i1 ON collate4t1(a COLLATE TEXT); + } + count { + SELECT * FROM collate4t2, collate4t1 WHERE a = b + ORDER BY collate4t2.rowid, collate4t1.rowid + } +} {A a A A 19} +do_test collate4-2.1.5 { + count { + SELECT * FROM collate4t2, collate4t1 WHERE b = a; + } +} {A A 4} +ifcapable subquery { + do_test collate4-2.1.6 { + count { + SELECT a FROM collate4t1 WHERE a IN (SELECT * FROM collate4t2) + ORDER BY rowid + } + } {a A 10} + do_test collate4-2.1.7 { + execsql { + DROP INDEX collate4i1; + CREATE INDEX collate4i1 ON collate4t1(a); + } + count { + SELECT a FROM collate4t1 WHERE a IN (SELECT * FROM collate4t2) + ORDER BY rowid + } + } {a A 6} + do_test collate4-2.1.8 { + count { + SELECT a FROM collate4t1 WHERE a IN ('z', 'a'); + } + } {a A 5} + do_test collate4-2.1.9 { + execsql { + DROP INDEX collate4i1; + CREATE INDEX collate4i1 ON collate4t1(a COLLATE TEXT); + } + count { + SELECT a FROM collate4t1 WHERE a IN ('z', 'a') ORDER BY rowid; + } + } {a A 9} +} +do_test collate4-2.1.10 { + execsql { + DROP TABLE collate4t1; + DROP TABLE collate4t2; + } +} {} + +do_test collate4-2.2.0 { + execsql { + CREATE TABLE collate4t1(a COLLATE nocase, b COLLATE text, c); + CREATE TABLE collate4t2(a COLLATE nocase, b COLLATE text, c COLLATE TEXT); + + INSERT INTO collate4t1 VALUES('0', '0', '0'); + INSERT INTO collate4t1 VALUES('0', '0', '1'); + INSERT INTO collate4t1 VALUES('0', '1', '0'); + INSERT INTO collate4t1 VALUES('0', '1', '1'); + INSERT INTO collate4t1 VALUES('1', '0', '0'); + INSERT INTO collate4t1 VALUES('1', '0', '1'); + INSERT INTO collate4t1 VALUES('1', '1', '0'); + INSERT INTO collate4t1 VALUES('1', '1', '1'); + insert into collate4t2 SELECT * FROM collate4t1; + } +} {} +do_test collate4-2.2.1 { + count { + SELECT * FROM collate4t2 NOT INDEXED NATURAL JOIN collate4t1 NOT INDEXED; + } +} {0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 63} +do_test collate4-2.2.1b { + execsql { + CREATE INDEX collate4i1 ON collate4t1(a, b, c); + } + count { + SELECT * FROM collate4t2 NATURAL JOIN collate4t1; + } +} {0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 29} +do_test collate4-2.2.2 { + execsql { + DROP INDEX collate4i1; + CREATE INDEX collate4i1 ON collate4t1(a, b, c COLLATE text); + } + count { + SELECT * FROM collate4t2 NATURAL JOIN collate4t1; + } +} {0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 22} + +do_test collate4-2.2.10 { + execsql { + DROP TABLE collate4t1; + DROP TABLE collate4t2; + } +} {} + +# +# These tests - collate4-3.* verify that indices that implement +# UNIQUE and PRIMARY KEY constraints operate correctly with user +# defined collation sequences. +# +do_test collate4-3.0 { + execsql { + CREATE TABLE collate4t1(a PRIMARY KEY COLLATE NOCASE); + } +} {} +do_test collate4-3.1 { + catchsql { + INSERT INTO collate4t1 VALUES('abc'); + INSERT INTO collate4t1 VALUES('ABC'); + } +} {1 {column a is not unique}} +do_test collate4-3.2 { + execsql { + SELECT * FROM collate4t1; + } +} {abc} +do_test collate4-3.3 { + catchsql { + INSERT INTO collate4t1 SELECT upper(a) FROM collate4t1; + } +} {1 {column a is not unique}} +do_test collate4-3.4 { + catchsql { + INSERT INTO collate4t1 VALUES(1); + UPDATE collate4t1 SET a = 'abc'; + } +} {1 {column a is not unique}} +do_test collate4-3.5 { + execsql { + DROP TABLE collate4t1; + CREATE TABLE collate4t1(a COLLATE NOCASE UNIQUE); + } +} {} +do_test collate4-3.6 { + catchsql { + INSERT INTO collate4t1 VALUES('abc'); + INSERT INTO collate4t1 VALUES('ABC'); + } +} {1 {column a is not unique}} +do_test collate4-3.7 { + execsql { + SELECT * FROM collate4t1; + } +} {abc} +do_test collate4-3.8 { + catchsql { + INSERT INTO collate4t1 SELECT upper(a) FROM collate4t1; + } +} {1 {column a is not unique}} +do_test collate4-3.9 { + catchsql { + INSERT INTO collate4t1 VALUES(1); + UPDATE collate4t1 SET a = 'abc'; + } +} {1 {column a is not unique}} +do_test collate4-3.10 { + execsql { + DROP TABLE collate4t1; + CREATE TABLE collate4t1(a); + CREATE UNIQUE INDEX collate4i1 ON collate4t1(a COLLATE NOCASE); + } +} {} +do_test collate4-3.11 { + catchsql { + INSERT INTO collate4t1 VALUES('abc'); + INSERT INTO collate4t1 VALUES('ABC'); + } +} {1 {column a is not unique}} +do_test collate4-3.12 { + execsql { + SELECT * FROM collate4t1; + } +} {abc} +do_test collate4-3.13 { + catchsql { + INSERT INTO collate4t1 SELECT upper(a) FROM collate4t1; + } +} {1 {column a is not unique}} +do_test collate4-3.14 { + catchsql { + INSERT INTO collate4t1 VALUES(1); + UPDATE collate4t1 SET a = 'abc'; + } +} {1 {column a is not unique}} + +do_test collate4-3.15 { + execsql { + DROP TABLE collate4t1; + } +} {} + +# Mimic the SQLite 2 collation type NUMERIC. +db collate numeric numeric_collate +proc numeric_collate {lhs rhs} { + if {$lhs == $rhs} {return 0} + return [expr ($lhs>$rhs)?1:-1] +} + +# +# These tests - collate4-4.* check that min() and max() only ever +# use indices constructed with built-in collation type numeric. +# +# CHANGED: min() and max() now use the collation type. If there +# is an indice that can be used, it is used. +# +do_test collate4-4.0 { + execsql { + CREATE TABLE collate4t1(a COLLATE TEXT); + INSERT INTO collate4t1 VALUES('2'); + INSERT INTO collate4t1 VALUES('10'); + INSERT INTO collate4t1 VALUES('20'); + INSERT INTO collate4t1 VALUES('104'); + } +} {} +do_test collate4-4.1 { + count { + SELECT max(a) FROM collate4t1 + } +} {20 3} +do_test collate4-4.2 { + count { + SELECT min(a) FROM collate4t1 + } +} {10 3} +do_test collate4-4.3 { + # Test that the index with collation type TEXT is used. + execsql { + CREATE INDEX collate4i1 ON collate4t1(a); + } + count { + SELECT min(a) FROM collate4t1; + } +} {10 1} +do_test collate4-4.4 { + count { + SELECT max(a) FROM collate4t1; + } +} {20 0} +do_test collate4-4.5 { + # Test that the index with collation type NUMERIC is not used. + execsql { + DROP INDEX collate4i1; + CREATE INDEX collate4i1 ON collate4t1(a COLLATE NUMERIC); + } + count { + SELECT min(a) FROM collate4t1; + } +} {10 3} +do_test collate4-4.6 { + count { + SELECT max(a) FROM collate4t1; + } +} {20 3} +do_test collate4-4.7 { + execsql { + DROP TABLE collate4t1; + } +} {} + +# Also test the scalar min() and max() functions. +# +do_test collate4-4.8 { + execsql { + CREATE TABLE collate4t1(a COLLATE TEXT, b COLLATE NUMERIC); + INSERT INTO collate4t1 VALUES('11', '101'); + INSERT INTO collate4t1 VALUES('101', '11') + } +} {} +do_test collate4-4.9 { + execsql { + SELECT max(a, b) FROM collate4t1; + } +} {11 11} +do_test collate4-4.10 { + execsql { + SELECT max(b, a) FROM collate4t1; + } +} {101 101} +do_test collate4-4.11 { + execsql { + SELECT max(a, '101') FROM collate4t1; + } +} {11 101} +do_test collate4-4.12 { + execsql { + SELECT max('101', a) FROM collate4t1; + } +} {11 101} +do_test collate4-4.13 { + execsql { + SELECT max(b, '101') FROM collate4t1; + } +} {101 101} +do_test collate4-4.14 { + execsql { + SELECT max('101', b) FROM collate4t1; + } +} {101 101} + +do_test collate4-4.15 { + execsql { + DROP TABLE collate4t1; + } +} {} + +# +# These tests - collate4.6.* - ensure that implict INTEGER PRIMARY KEY +# indices do not confuse collation sequences. +# +# These indices are never used for sorting in SQLite. And you can't +# create another index on an INTEGER PRIMARY KEY column, so we don't have +# to test that. +# (Revised 2004-Nov-22): The ROWID can be used for sorting now. +# +do_test collate4-6.0 { + execsql { + CREATE TABLE collate4t1(a INTEGER PRIMARY KEY); + INSERT INTO collate4t1 VALUES(101); + INSERT INTO collate4t1 VALUES(10); + INSERT INTO collate4t1 VALUES(15); + } +} {} +do_test collate4-6.1 { + cksort { + SELECT * FROM collate4t1 ORDER BY 1; + } +} {10 15 101 nosort} +do_test collate4-6.2 { + cksort { + SELECT * FROM collate4t1 ORDER BY oid; + } +} {10 15 101 nosort} +do_test collate4-6.3 { + cksort { + SELECT * FROM collate4t1 ORDER BY oid||'' COLLATE TEXT; + } +} {10 101 15 sort} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collate5.test b/components/external/SQLite-3.8.1/test/collate5.test new file mode 100644 index 0000000000000000000000000000000000000000..5f8697ea51ee34c39ee7028cac52c0d4893efe5b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collate5.test @@ -0,0 +1,292 @@ +# +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this file is testing DISTINCT, UNION, INTERSECT and EXCEPT +# SELECT statements that use user-defined collation sequences. Also +# GROUP BY clauses that use user-defined collation sequences. +# +# $Id: collate5.test,v 1.7 2008/09/16 11:58:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +# +# Tests are organised as follows: +# collate5-1.* - DISTINCT +# collate5-2.* - Compound SELECT +# collate5-3.* - ORDER BY on compound SELECT +# collate5-4.* - GROUP BY + +# Create the collation sequence 'TEXT', purely for asthetic reasons. The +# test cases in this script could just as easily use BINARY. +db collate TEXT [list string compare] + +# Mimic the SQLite 2 collation type NUMERIC. +db collate numeric numeric_collate +proc numeric_collate {lhs rhs} { + if {$lhs == $rhs} {return 0} + return [expr ($lhs>$rhs)?1:-1] +} + +# +# These tests - collate5-1.* - focus on the DISTINCT keyword. +# +do_test collate5-1.0 { + execsql { + CREATE TABLE collate5t1(a COLLATE nocase, b COLLATE text); + + INSERT INTO collate5t1 VALUES('a', 'apple'); + INSERT INTO collate5t1 VALUES('A', 'Apple'); + INSERT INTO collate5t1 VALUES('b', 'banana'); + INSERT INTO collate5t1 VALUES('B', 'banana'); + INSERT INTO collate5t1 VALUES('n', NULL); + INSERT INTO collate5t1 VALUES('N', NULL); + } +} {} +do_test collate5-1.1 { + execsql { + SELECT DISTINCT a FROM collate5t1; + } +} {a b n} +do_test collate5-1.2 { + execsql { + SELECT DISTINCT b FROM collate5t1; + } +} {apple Apple banana {}} +do_test collate5-1.3 { + execsql { + SELECT DISTINCT a, b FROM collate5t1; + } +} {a apple A Apple b banana n {}} + +# Ticket #3376 +# +do_test collate5-1.11 { + execsql { + CREATE TABLE tkt3376(a COLLATE nocase PRIMARY KEY); + INSERT INTO tkt3376 VALUES('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'); + INSERT INTO tkt3376 VALUES('ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789'); + SELECT DISTINCT a FROM tkt3376; + } +} {abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789ABXYZ012234567890123456789} +do_test collate5-1.12 { + sqlite3 db2 :memory: + db2 eval { + PRAGMA encoding=UTF16le; + CREATE TABLE tkt3376(a COLLATE nocase PRIMARY KEY); + INSERT INTO tkt3376 VALUES('abc'); + INSERT INTO tkt3376 VALUES('ABX'); + SELECT DISTINCT a FROM tkt3376; + } +} {abc ABX} +catch {db2 close} + +# The remainder of this file tests compound SELECT statements. +# Omit it if the library is compiled such that they are omitted. +# +ifcapable !compound { + finish_test + return +} + +# +# Tests named collate5-2.* focus on UNION, EXCEPT and INTERSECT +# queries that use user-defined collation sequences. +# +# collate5-2.1.* - UNION +# collate5-2.2.* - INTERSECT +# collate5-2.3.* - EXCEPT +# +do_test collate5-2.0 { + execsql { + CREATE TABLE collate5t2(a COLLATE text, b COLLATE nocase); + + INSERT INTO collate5t2 VALUES('a', 'apple'); + INSERT INTO collate5t2 VALUES('A', 'apple'); + INSERT INTO collate5t2 VALUES('b', 'banana'); + INSERT INTO collate5t2 VALUES('B', 'Banana'); + } +} {} + +do_test collate5-2.1.1 { + execsql { + SELECT a FROM collate5t1 UNION select a FROM collate5t2; + } +} {A B N} +do_test collate5-2.1.2 { + execsql { + SELECT a FROM collate5t2 UNION select a FROM collate5t1; + } +} {A B N a b n} +do_test collate5-2.1.3 { + execsql { + SELECT a, b FROM collate5t1 UNION select a, b FROM collate5t2; + } +} {A Apple A apple B Banana b banana N {}} +do_test collate5-2.1.4 { + execsql { + SELECT a, b FROM collate5t2 UNION select a, b FROM collate5t1; + } +} {A Apple B banana N {} a apple b banana n {}} + +do_test collate5-2.2.1 { + execsql { + SELECT a FROM collate5t1 EXCEPT select a FROM collate5t2; + } +} {N} +do_test collate5-2.2.2 { + execsql { + SELECT a FROM collate5t2 EXCEPT select a FROM collate5t1 WHERE a != 'a'; + } +} {A a} +do_test collate5-2.2.3 { + execsql { + SELECT a, b FROM collate5t1 EXCEPT select a, b FROM collate5t2; + } +} {A Apple N {}} +do_test collate5-2.2.4 { + execsql { + SELECT a, b FROM collate5t2 EXCEPT select a, b FROM collate5t1 + where a != 'a'; + } +} {A apple a apple} + +do_test collate5-2.3.1 { + execsql { + SELECT a FROM collate5t1 INTERSECT select a FROM collate5t2; + } +} {A B} +do_test collate5-2.3.2 { + execsql { + SELECT a FROM collate5t2 INTERSECT select a FROM collate5t1 WHERE a != 'a'; + } +} {B b} +do_test collate5-2.3.3 { + execsql { + SELECT a, b FROM collate5t1 INTERSECT select a, b FROM collate5t2; + } +} {a apple B banana} +do_test collate5-2.3.4 { + execsql { + SELECT a, b FROM collate5t2 INTERSECT select a, b FROM collate5t1; + } +} {A apple B Banana a apple b banana} + +# +# This test ensures performs a UNION operation with a bunch of different +# length records. The goal is to test that the logic that compares records +# for the compound SELECT operators works with record lengths that lie +# either side of the troublesome 256 and 65536 byte marks. +# +set ::lens [list \ + 0 1 2 3 4 5 6 7 8 9 \ + 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 \ + 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 \ + 65520 65521 65522 65523 65524 65525 65526 65527 65528 65529 65530 \ + 65531 65532 65533 65534 65535 65536 65537 65538 65539 65540 65541 \ + 65542 65543 65544 65545 65546 65547 65548 65549 65550 65551 ] +do_test collate5-2.4.0 { + execsql { + BEGIN; + CREATE TABLE collate5t3(a, b); + } + foreach ii $::lens { + execsql "INSERT INTO collate5t3 VALUES($ii, '[string repeat a $ii]');" + } + expr [llength [execsql { + COMMIT; + SELECT * FROM collate5t3 UNION SELECT * FROM collate5t3; + }]] / 2 +} [llength $::lens] +do_test collate5-2.4.1 { + execsql {DROP TABLE collate5t3;} +} {} +unset ::lens + +# +# These tests - collate5-3.* - focus on compound SELECT queries that +# feature ORDER BY clauses. +# +do_test collate5-3.0 { + execsql { + SELECT a FROM collate5t1 UNION ALL SELECT a FROM collate5t2 ORDER BY 1; + } +} {/[aA] [aA] [aA] [aA] [bB] [bB] [bB] [bB] [nN] [nN]/} +do_test collate5-3.1 { + execsql { + SELECT a FROM collate5t2 UNION ALL SELECT a FROM collate5t1 ORDER BY 1; + } +} {A A B B N a a b b n} +do_test collate5-3.2 { + execsql { + SELECT a FROM collate5t1 UNION ALL SELECT a FROM collate5t2 + ORDER BY 1 COLLATE TEXT; + } +} {A A B B N a a b b n} + +do_test collate5-3.3 { + execsql { + CREATE TABLE collate5t_cn(a COLLATE NUMERIC); + CREATE TABLE collate5t_ct(a COLLATE TEXT); + INSERT INTO collate5t_cn VALUES('1'); + INSERT INTO collate5t_cn VALUES('11'); + INSERT INTO collate5t_cn VALUES('101'); + INSERT INTO collate5t_ct SELECT * FROM collate5t_cn; + } +} {} +do_test collate5-3.4 { + execsql { + SELECT a FROM collate5t_cn INTERSECT SELECT a FROM collate5t_ct ORDER BY 1; + } +} {1 11 101} +do_test collate5-3.5 { + execsql { + SELECT a FROM collate5t_ct INTERSECT SELECT a FROM collate5t_cn ORDER BY 1; + } +} {1 101 11} + +do_test collate5-3.20 { + execsql { + DROP TABLE collate5t_cn; + DROP TABLE collate5t_ct; + DROP TABLE collate5t1; + DROP TABLE collate5t2; + } +} {} + +do_test collate5-4.0 { + execsql { + CREATE TABLE collate5t1(a COLLATE NOCASE, b COLLATE NUMERIC); + INSERT INTO collate5t1 VALUES('a', '1'); + INSERT INTO collate5t1 VALUES('A', '1.0'); + INSERT INTO collate5t1 VALUES('b', '2'); + INSERT INTO collate5t1 VALUES('B', '3'); + } +} {} +do_test collate5-4.1 { + string tolower [execsql { + SELECT a, count(*) FROM collate5t1 GROUP BY a; + }] +} {a 2 b 2} +do_test collate5-4.2 { + execsql { + SELECT a, b, count(*) FROM collate5t1 GROUP BY a, b ORDER BY a, b; + } +} {/[aA] 1(.0)? 2 [bB] 2 1 [bB] 3 1/} +do_test collate5-4.3 { + execsql { + DROP TABLE collate5t1; + } +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collate6.test b/components/external/SQLite-3.8.1/test/collate6.test new file mode 100644 index 0000000000000000000000000000000000000000..d238639a5d3771f9fc607018becaefdefcbb34f5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collate6.test @@ -0,0 +1,153 @@ +# +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is collation sequences in concert with triggers. +# +# $Id: collate6.test,v 1.4 2007/07/30 14:40:48 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# There are no tests in this file that will work without +# trigger support. +# +ifcapable {!trigger} { + finish_test + return +} + +# Create a case-insensitive collation type NOCASE for use in testing. +# Normally, capital letters are less than their lower-case counterparts. +db collate NOCASE nocase_collate +proc nocase_collate {a b} { + return [string compare -nocase $a $b] +} + +# +# Tests are organized as follows: +# collate6-1.* - triggers. +# + +do_test collate6-1.0 { + execsql { + CREATE TABLE collate6log(a, b); + CREATE TABLE collate6tab(a COLLATE NOCASE, b COLLATE BINARY); + } +} {} + +# Test that the default collation sequence applies to new.* references +# in WHEN clauses. +do_test collate6-1.1 { + execsql { + CREATE TRIGGER collate6trig BEFORE INSERT ON collate6tab + WHEN new.a = 'a' BEGIN + INSERT INTO collate6log VALUES(new.a, new.b); + END; + } +} {} +do_test collate6-1.2 { + execsql { + INSERT INTO collate6tab VALUES('a', 'b'); + SELECT * FROM collate6log; + } +} {a b} +do_test collate6-1.3 { + execsql { + INSERT INTO collate6tab VALUES('A', 'B'); + SELECT * FROM collate6log; + } +} {a b A B} +do_test collate6-1.4 { + execsql { + DROP TRIGGER collate6trig; + DELETE FROM collate6log; + } +} {} + +# Test that the default collation sequence applies to new.* references +# in the body of triggers. +do_test collate6-1.5 { + execsql { + CREATE TRIGGER collate6trig BEFORE INSERT ON collate6tab BEGIN + INSERT INTO collate6log VALUES(new.a='a', new.b='b'); + END; + } +} {} +do_test collate6-1.6 { + execsql { + INSERT INTO collate6tab VALUES('a', 'b'); + SELECT * FROM collate6log; + } +} {1 1} +do_test collate6-1.7 { + execsql { + INSERT INTO collate6tab VALUES('A', 'B'); + SELECT * FROM collate6log; + } +} {1 1 1 0} +do_test collate6-1.8 { + execsql { + DROP TRIGGER collate6trig; + DELETE FROM collate6log; + } +} {} + +do_test collate6-1.9 { + execsql { + DROP TABLE collate6tab; + } +} {} + +# Test that an explicit collation sequence overrides an implicit +# one attached to a 'new' reference. +# +do_test collate6-2.1 { + execsql { + CREATE TABLE abc(a COLLATE binary, b, c); + CREATE TABLE def(a, b, c); + CREATE TRIGGER abc_t1 AFTER INSERT ON abc BEGIN + INSERT INTO def SELECT * FROM abc WHERE a < new.a COLLATE nocase; + END + } +} {} +do_test collate6-2.2 { + execsql { + INSERT INTO abc VALUES('One', 'Two', 'Three'); + INSERT INTO abc VALUES('one', 'two', 'three'); + SELECT * FROM def; + } +} {} +do_test collate6-2.3 { + execsql { + UPDATE abc SET a = 'four' WHERE a = 'one'; + CREATE TRIGGER abc_t2 AFTER UPDATE ON abc BEGIN + INSERT INTO def SELECT * FROM abc WHERE a < new.a COLLATE nocase; + END; + SELECT * FROM def; + } +} {} + +# At one point the 6-3.2 (but not 6-3.1) was causing an assert() to fail. +# +do_test collate6-3.1 { + execsql { + SELECT 1 FROM sqlite_master WHERE name COLLATE nocase = 'hello'; + } +} {} +do_test collate6-3.2 { + execsql { + SELECT 1 FROM sqlite_master WHERE 'hello' = name COLLATE nocase; + } +} {} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collate7.test b/components/external/SQLite-3.8.1/test/collate7.test new file mode 100644 index 0000000000000000000000000000000000000000..da97491ece19d099f11cab4be31ea1de7e952912 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collate7.test @@ -0,0 +1,72 @@ +# +# 2007 May 7 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is the experimental sqlite3_create_collation_v2() +# API. +# +# $Id: collate7.test,v 1.2 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set ::caseless_del 0 +proc caseless_cmp {zLeft zRight} { + string compare -nocase $zLeft $zRight +} + +do_test collate7-1.1 { + set cmd [list incr ::caseless_del] + sqlite3_create_collation_v2 db CASELESS caseless_cmp $cmd + set ::caseless_del +} {0} +do_test collate7-1.2 { + sqlite_delete_collation db CASELESS + set ::caseless_del +} {1} +do_test collate7-1.3 { + catchsql { + CREATE TABLE abc(a COLLATE CASELESS, b, c); + } +} {1 {no such collation sequence: CASELESS}} +do_test collate7-1.4 { + sqlite3_create_collation_v2 db CASELESS caseless_cmp {incr ::caseless_del} + db close + set ::caseless_del +} {2} + +do_test collate7-2.1 { + forcedelete test.db test.db-journal + sqlite3 db test.db + sqlite3_create_collation_v2 db CASELESS caseless_cmp {incr ::caseless_del} + execsql { + PRAGMA encoding='utf-16'; + CREATE TABLE abc16(a COLLATE CASELESS, b, c); + } db + set ::caseless_del +} {2} +do_test collate7-2.2 { + execsql { + SELECT * FROM abc16 WHERE a < 'abc'; + } + set ::caseless_del +} {2} +do_test collate7-2.3 { + sqlite_delete_collation db CASELESS + set ::caseless_del +} {3} +do_test collate7-2.4 { + catchsql { + SELECT * FROM abc16 WHERE a < 'abc'; + } +} {1 {no such collation sequence: CASELESS}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collate8.test b/components/external/SQLite-3.8.1/test/collate8.test new file mode 100644 index 0000000000000000000000000000000000000000..60a89162dddd6a569273b1430ab19a40dc5e60e8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collate8.test @@ -0,0 +1,125 @@ +# +# 2007 June 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is making sure collations pass through the +# unary + operator. +# +# $Id: collate8.test,v 1.2 2008/08/25 12:14:09 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test collate8-1.1 { + execsql { + CREATE TABLE t1(a TEXT COLLATE nocase); + INSERT INTO t1 VALUES('aaa'); + INSERT INTO t1 VALUES('BBB'); + INSERT INTO t1 VALUES('ccc'); + INSERT INTO t1 VALUES('DDD'); + SELECT a FROM t1 ORDER BY a; + } +} {aaa BBB ccc DDD} +do_test collate8-1.2 { + execsql { + SELECT rowid FROM t1 WHERE a<'ccc' ORDER BY 1 + } +} {1 2} +do_test collate8-1.3 { + execsql { + SELECT rowid FROM t1 WHERE a<'ccc' COLLATE binary ORDER BY 1 + } +} {1 2 4} +do_test collate8-1.4 { + execsql { + SELECT rowid FROM t1 WHERE +a<'ccc' ORDER BY 1 + } +} {1 2} +do_test collate8-1.5 { + execsql { + SELECT a FROM t1 ORDER BY +a + } +} {aaa BBB ccc DDD} +do_test collate8-1.11 { + execsql { + SELECT a AS x FROM t1 ORDER BY "x"; + } +} {aaa BBB ccc DDD} +do_test collate8-1.12 { + execsql { + SELECT a AS x FROM t1 WHERE x<'ccc' ORDER BY 1 + } +} {aaa BBB} +do_test collate8-1.13 { + execsql { + SELECT a AS x FROM t1 WHERE x<'ccc' COLLATE binary ORDER BY [x] + } +} {aaa BBB DDD} +do_test collate8-1.14 { + execsql { + SELECT a AS x FROM t1 WHERE +x<'ccc' ORDER BY 1 + } +} {aaa BBB} +do_test collate8-1.15 { + execsql { + SELECT a AS x FROM t1 ORDER BY +x + } +} {aaa BBB ccc DDD} + + +# When a result-set column is aliased into a WHERE clause, make sure the +# collating sequence logic works correctly. +# +do_test collate8-2.1 { + execsql { + CREATE TABLE t2(a); + INSERT INTO t2 VALUES('abc'); + INSERT INTO t2 VALUES('ABC'); + SELECT a AS x FROM t2 WHERE x='abc'; + } +} {abc} +do_test collate8-2.2 { + execsql { + SELECT a AS x FROM t2 WHERE x='abc' COLLATE nocase; + } +} {abc ABC} +do_test collate8-2.3 { + execsql { + SELECT a AS x FROM t2 WHERE (x COLLATE nocase)='abc'; + } +} {abc ABC} +do_test collate8-2.4 { + execsql { + SELECT a COLLATE nocase AS x FROM t2 WHERE x='abc'; + } +} {abc ABC} +do_test collate8-2.5 { + execsql { + SELECT a COLLATE nocase AS x FROM t2 WHERE (x COLLATE binary)='abc'; + } +} {abc} +do_test collate8-2.6 { + execsql { + SELECT a COLLATE nocase AS x FROM t2 WHERE x='abc' COLLATE binary; + } +} {abc ABC} +do_test collate8-2.7 { + execsql { + SELECT * FROM t2 WHERE (a COLLATE nocase)='abc' COLLATE binary; + } +} {abc ABC} +do_test collate8-2.8 { + execsql { + SELECT a COLLATE nocase AS x FROM t2 WHERE 'abc'=x COLLATE binary; + } +} {abc} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collate9.test b/components/external/SQLite-3.8.1/test/collate9.test new file mode 100644 index 0000000000000000000000000000000000000000..5a07773a1ce2fbf999c29b290ac52badb43bed87 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collate9.test @@ -0,0 +1,178 @@ +# +# 2007 November 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is making sure that the names of collation +# sequences may be quoted using double quotes in SQL statements. +# +# $Id: collate9.test,v 1.2 2008/07/10 00:32:42 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc reverse_sort {lhs rhs} { + return [string compare $rhs $lhs] +} +db collate "reverse sort" reverse_sort + +# This procedure executes the SQL. Then it checks to see if the OP_Sort +# opcode was executed. If an OP_Sort did occur, then "sort" is appended +# to the result. If no OP_Sort happened, then "nosort" is appended. +# +# This procedure is used to check to make sure sorting is or is not +# occurring as expected. +# +proc cksort {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + if {$::sqlite_sort_count} {set x sort} {set x nosort} + lappend data $x + return $data +} + +# Test plan: +# +# collate9-1.* - Test collation sequences attached to table columns +# collate9-2.* - Test collation sequences attached to expressions +# collate9-3.* - Test collation sequences attached to an index +# collate9-4.* - Test collation sequences as an argument to REINDEX +# + +do_test collate9-1.1 { + execsql { + CREATE TABLE xy(x COLLATE "reverse sort", y COLLATE binary); + INSERT INTO xy VALUES('one', 'one'); + INSERT INTO xy VALUES('two', 'two'); + INSERT INTO xy VALUES('three', 'three'); + } +} {} +do_test collate9-1.2 { + execsql { + SELECT x FROM xy ORDER BY x + } +} {two three one} +do_test collate9-1.3 { + execsql { + SELECT y FROM xy ORDER BY y + } +} {one three two} +do_test collate9-1.4 { + cksort { + SELECT x FROM xy ORDER BY x + } +} {two three one sort} +do_test collate9-1.5 { + execsql { + CREATE INDEX xy_i ON xy(x) + } +} {} +do_test collate9-1.6 { + cksort { + SELECT x FROM xy ORDER BY x + } +} {two three one nosort} + +do_test collate9-2.1 { + execsql { + SELECT x, x < 'seven' FROM xy ORDER BY x + } +} {two 1 three 1 one 0} +do_test collate9-2.2 { + execsql { + SELECT y, y < 'seven' FROM xy ORDER BY x + } +} {two 0 three 0 one 1} +do_test collate9-2.3 { + execsql { + SELECT y, y COLLATE "reverse sort" < 'seven' FROM xy ORDER BY x + } +} {two 1 three 1 one 0} +do_test collate9-2.4 { + execsql { + SELECT y FROM xy ORDER BY y + } +} {one three two} +do_test collate9-2.5 { + execsql { + SELECT y FROM xy ORDER BY y COLLATE "reverse sort" + } +} {two three one} +do_test collate9-2.6 { + execsql { + SELECT y COLLATE "reverse sort" AS aaa FROM xy ORDER BY aaa + } +} {two three one} + +do_test collate9-3.1 { + execsql { + CREATE INDEX xy_i2 ON xy(y COLLATE "reverse sort"); + } +} {} +do_test collate9-3.2 { + cksort { + SELECT y FROM xy ORDER BY y + } +} {one three two sort} +do_test collate9-3.3 { + cksort { + SELECT y FROM xy ORDER BY y COLLATE "reverse sort" + } +} {two three one nosort} +do_test collate9-3.4 { + cksort { + SELECT y AS aaa FROM xy ORDER BY aaa + } +} {one three two sort} +do_test collate9-3.5 { + cksort { + SELECT y COLLATE "reverse sort" AS aaa FROM xy ORDER BY aaa + } +} {two three one nosort} + +ifcapable reindex { + do_test collate9-4.1 { + execsql { + REINDEX "reverse sort" + } + } {} + + # Modify the "reverse sort" collation so that it now sorts in the same + # order as binary. + proc reverse_sort {lhs rhs} { + return [string compare $lhs $rhs] + } + + # The integrity check should now fail because the indexes created using + # "reverse sort" are no longer in sync with the collation sequence + # implementation. + do_test collate9-4.2 { + expr {"ok" eq [execsql { PRAGMA integrity_check }]} + } {0} + + do_test collate9-4.3 { + execsql { + REINDEX "reverse sort" + } + } {} + + # Integrity check should now pass. + do_test collate9-4.4 { + expr {"ok" eq [execsql { PRAGMA integrity_check }]} + } {1} + + do_test collate9-4.5 { + cksort { + SELECT x FROM xy ORDER BY x COLLATE "reverse sort" + } + } {one three two nosort} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/collateA.test b/components/external/SQLite-3.8.1/test/collateA.test new file mode 100644 index 0000000000000000000000000000000000000000..3f7ebd9242fa7bfcc1270af3d5cb31051bcf464d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/collateA.test @@ -0,0 +1,217 @@ +# +# 2008 January 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is the built-in RTRIM collating +# API. +# +# $Id: collateA.test,v 1.3 2008/04/15 04:02:41 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test collateA-1.1 { + execsql { + CREATE TABLE t1( + a INTEGER PRIMARY KEY, + b TEXT COLLATE BINARY, + c TEXT COLLATE RTRIM + ); + INSERT INTO t1 VALUES(1, 'abcde','abcde'); + INSERT INTO t1 VALUES(2, 'xyzzy ','xyzzy '); + INSERT INTO t1 VALUES(3, 'xyzzy ','xyzzy '); + INSERT INTO t1 VALUES(4, 'xyzzy ','xyzzy '); + INSERT INTO t1 VALUES(5, ' ', ' '); + INSERT INTO t1 VALUES(6, '', ''); + SELECT count(*) FROM t1; + } +} {6} +do_test collateA-1.2 { + execsql {SELECT a FROM t1 WHERE b='abcde '} +} {} +do_test collateA-1.3 { + execsql {SELECT a FROM t1 WHERE c='abcde '} +} {1} +do_test collateA-1.4 { + execsql {SELECT a FROM t1 WHERE b='xyzzy'} +} {} +do_test collateA-1.5 { + execsql {SELECT a FROM t1 WHERE c='xyzzy'} +} {2 3 4} +do_test collateA-1.6 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-1.7 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-1.8 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-1.9 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-1.10 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-1.11 { + execsql {SELECT 'abc123'='abc123 ' COLLATE RTRIM;} +} {1} +do_test collateA-1.12 { + execsql {SELECT 'abc123 '='abc123' COLLATE RTRIM;} +} {1} +do_test collateA-1.13 { + execsql {SELECT ' '='' COLLATE RTRIM, ' '='' COLLATE BINARY, ' '=''} +} {1 0 0} +do_test collateA-1.14 { + execsql {SELECT ''=' ' COLLATE RTRIM, ''=' ' COLLATE BINARY, ''=' '} +} {1 0 0} +do_test collateA-1.15 { + execsql {SELECT ' '=' ' COLLATE RTRIM, ' '=' '} +} {1 0} +do_test collateA-1.16 { + execsql {SELECT ''<>' ' COLLATE RTRIM, ''<>' ' COLLATE BINARY, ''<>' '} +} {0 1 1} +do_test collateA-1.17 { + execsql {SELECT a FROM t1 WHERE c='xyzz'} +} {} +do_test collateA-1.18 { + execsql {SELECT a FROM t1 WHERE c='xyzzyy '} +} {} +do_test collateA-1.19 { + execsql {SELECT a FROM t1 WHERE c='xyzz '} +} {} +do_test collateA-1.20 { + execsql {SELECT a FROM t1 WHERE c='abcd '} +} {} +do_test collateA-1.21 { + execsql {SELECT a FROM t1 WHERE c='abcd'} +} {} +do_test collateA-1.22 { + execsql {SELECT a FROM t1 WHERE c='abc'} +} {} +do_test collateA-1.23 { + execsql {SELECT a FROM t1 WHERE c='abcdef '} +} {} +do_test collateA-1.24 { + execsql {SELECT a FROM t1 WHERE c=''} +} {5 6} +do_test collateA-1.25 { + execsql {SELECT a FROM t1 WHERE c=' '} +} {5 6} +do_test collateA-1.26 { + execsql {SELECT a FROM t1 WHERE c=' '} +} {5 6} + + +do_test collateA-2.1 { + execsql { + CREATE INDEX i1b ON t1(b); + CREATE INDEX i1c ON t1(c); + PRAGMA integrity_check; + } +} {ok} +do_test collateA-2.2 { + execsql {SELECT a FROM t1 WHERE b='abcde '} +} {} +do_test collateA-2.3 { + execsql {SELECT a FROM t1 WHERE c='abcde '} +} {1} +do_test collateA-2.4 { + execsql {SELECT a FROM t1 WHERE b='xyzzy'} +} {} +do_test collateA-2.5 { + execsql {SELECT a FROM t1 WHERE c='xyzzy'} +} {2 3 4} +do_test collateA-2.6 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-2.7 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-2.8 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-2.9 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-2.10 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-2.17 { + execsql {SELECT a FROM t1 WHERE c='xyzz'} +} {} +do_test collateA-2.18 { + execsql {SELECT a FROM t1 WHERE c='xyzzyy '} +} {} +do_test collateA-2.19 { + execsql {SELECT a FROM t1 WHERE c='xyzz '} +} {} +do_test collateA-2.20 { + execsql {SELECT a FROM t1 WHERE c='abcd '} +} {} +do_test collateA-2.21 { + execsql {SELECT a FROM t1 WHERE c='abcd'} +} {} +do_test collateA-2.22 { + execsql {SELECT a FROM t1 WHERE c='abc'} +} {} +do_test collateA-2.23 { + execsql {SELECT a FROM t1 WHERE c='abcdef '} +} {} +do_test collateA-2.24 { + execsql {SELECT a FROM t1 WHERE c=''} +} {5 6} +do_test collateA-2.25 { + execsql {SELECT a FROM t1 WHERE c=' '} +} {5 6} +do_test collateA-2.26 { + execsql {SELECT a FROM t1 WHERE c=' '} +} {5 6} + + +do_test collateA-3.1 { + db close + sqlite3 db test.db + execsql { + REINDEX; + PRAGMA integrity_check; + } +} {ok} +do_test collateA-3.2 { + execsql {SELECT a FROM t1 WHERE b='abcde '} +} {} +do_test collateA-3.3 { + execsql {SELECT a FROM t1 WHERE c='abcde '} +} {1} +do_test collateA-3.4 { + execsql {SELECT a FROM t1 WHERE b='xyzzy'} +} {} +do_test collateA-3.5 { + execsql {SELECT a FROM t1 WHERE c='xyzzy'} +} {2 3 4} +do_test collateA-3.6 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-3.7 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-3.8 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-3.9 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} +do_test collateA-3.10 { + execsql {SELECT a FROM t1 WHERE c='xyzzy '} +} {2 3 4} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/colmeta.test b/components/external/SQLite-3.8.1/test/colmeta.test new file mode 100644 index 0000000000000000000000000000000000000000..3939f8228acb917ffb2e383fd3d9a7b9cf88366c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/colmeta.test @@ -0,0 +1,94 @@ +# +# 2006 February 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is the sqlite3_table_column_metadata() API. +# +# $Id: colmeta.test,v 1.4 2008/01/23 12:52:41 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !columnmetadata { + finish_test + return +} + +# Set up a schema in the main and temp test databases. +do_test colmeta-0 { + execsql { + CREATE TABLE abc(a, b, c); + CREATE TABLE abc2(a PRIMARY KEY COLLATE NOCASE, b VARCHAR(32), c); + CREATE TABLE abc3(a NOT NULL, b INTEGER PRIMARY KEY, c); + } + ifcapable autoinc { + execsql { + CREATE TABLE abc4(a, b INTEGER PRIMARY KEY AUTOINCREMENT, c); + } + } + ifcapable view { + execsql { + CREATE VIEW v1 AS SELECT * FROM abc2; + } + } +} {} + + +# Return values are of the form: +# +# { } +# +set tests { + 1 {main abc a} {0 {{} BINARY 0 0 0}} + 2 {{} abc a} {0 {{} BINARY 0 0 0}} + 3 {{} abc2 b} {0 {VARCHAR(32) BINARY 0 0 0}} + 4 {main abc2 b} {0 {VARCHAR(32) BINARY 0 0 0}} + 5 {{} abc2 a} {0 {{} NOCASE 0 1 0}} + 6 {{} abc3 a} {0 {{} BINARY 1 0 0}} + 7 {{} abc3 b} {0 {INTEGER BINARY 0 1 0}} + 13 {main abc rowid} {0 {INTEGER BINARY 0 1 0}} + 14 {main abc3 rowid} {0 {INTEGER BINARY 0 1 0}} + 16 {main abc d} {1 {no such table column: abc.d}} +} +ifcapable view { + set tests [concat $tests { + 8 {{} abc4 b} {0 {INTEGER BINARY 0 1 1}} + 15 {main abc4 rowid} {0 {INTEGER BINARY 0 1 1}} + }] +} +ifcapable view { + set tests [concat $tests { + 9 {{} v1 a} {1 {no such table column: v1.a}} + 10 {main v1 b} {1 {no such table column: v1.b}} + 11 {main v1 badname} {1 {no such table column: v1.badname}} + 12 {main v1 rowid} {1 {no such table column: v1.rowid}} + }] +} + +foreach {tn params results} $tests { + set ::DB [sqlite3_connection_pointer db] + + set tstbody [concat sqlite3_table_column_metadata $::DB $params] + do_test colmeta-$tn.1 { + list [catch $tstbody msg] [set msg] + } $results + + db close + sqlite3 db test.db + + set ::DB [sqlite3_connection_pointer db] + set tstbody [concat sqlite3_table_column_metadata $::DB $params] + do_test colmeta-$tn.2 { + list [catch $tstbody msg] [set msg] + } $results +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/colname.test b/components/external/SQLite-3.8.1/test/colname.test new file mode 100644 index 0000000000000000000000000000000000000000..e16304d4a98ea67c353cc82d403857781bb819f7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/colname.test @@ -0,0 +1,329 @@ +# 2008 July 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# The focus of this file is testing how SQLite generates the names +# of columns in a result set. +# +# $Id: colname.test,v 1.7 2009/06/02 15:47:38 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Rules (applied in order): +# +# (1) If there is an AS clause, use it. +# +# (2) A non-trival expression (not a table column name) then the name is +# a copy of the expression text. +# +# (3) If short_column_names=ON, then just the abbreviated column name without +# the table name. +# +# (4) When short_column_names=OFF and full_column_names=OFF then +# use case (2) for simple queries and case (5) for joins. +# +# (5) When short_column_names=OFF and full_column_names=ON then +# use the form: TABLE.COLUMN +# + + +# Verify the default settings for short_column_name and full_column_name +# +do_test colname-1.1 { + db eval {PRAGMA short_column_names} +} {1} +do_test colname-1.2 { + db eval {PRAGMA full_column_names} +} {0} + +# Tests for then short=ON and full=any +# +do_test colname-2.1 { + db eval { + CREATE TABLE tabc(a,b,c); + INSERT INTO tabc VALUES(1,2,3); + CREATE TABLE txyz(x,y,z); + INSERT INTO txyz VALUES(4,5,6); + CREATE TABLE tboth(a,b,c,x,y,z); + INSERT INTO tboth VALUES(11,12,13,14,15,16); + CREATE VIEW v1 AS SELECT tabC.a, txyZ.x, * + FROM tabc, txyz ORDER BY 1 LIMIT 1; + CREATE VIEW v2 AS SELECT tabC.a, txyZ.x, tboTh.a, tbotH.x, * + FROM tabc, txyz, tboth ORDER BY 1 LIMIT 1; + } + execsql2 { + SELECT * FROM tabc; + } +} {a 1 b 2 c 3} +do_test colname-2.2 { + execsql2 { + SELECT Tabc.a, tAbc.b, taBc.c, * FROM tabc + } +} {a 1 b 2 c 3 a 1 b 2 c 3} +do_test colname-2.3 { + execsql2 { + SELECT +tabc.a, -tabc.b, tabc.c, * FROM tabc + } +} {+tabc.a 1 -tabc.b -2 c 3 a 1 b 2 c 3} +do_test colname-2.4 { + execsql2 { + SELECT +tabc.a AS AAA, -tabc.b AS BBB, tabc.c CCC, * FROM tabc + } +} {AAA 1 BBB -2 CCC 3 a 1 b 2 c 3} +do_test colname-2.5 { + execsql2 { + SELECT tabc.a, txyz.x, * FROM tabc, txyz; + } +} {a 1 x 4 a 1 b 2 c 3 x 4 y 5 z 6} +do_test colname-2.6 { + execsql2 { + SELECT tabc.a, txyz.x, tabc.*, txyz.* FROM tabc, txyz; + } +} {a 1 x 4 a 1 b 2 c 3 x 4 y 5 z 6} +do_test colname-2.7 { + execsql2 { + SELECT tabc.a, txyz.x, tboth.a, tboth.x, * FROM tabc, txyz, tboth; + } +} {a 11 x 14 a 11 x 14 a 11 b 12 c 13 x 14 y 15 z 16 a 11 b 12 c 13 x 14 y 15 z 16} +do_test colname-2.8 { + execsql2 { + SELECT * FROM v1 ORDER BY 2; + } +} {a 1 x 4 a:1 1 b 2 c 3 x:1 4 y 5 z 6} +do_test colname-2.9 { + execsql2 { + SELECT * FROM v2 ORDER BY 2; + } +} {a 1 x 4 a:1 11 x:1 14 a:2 1 b 2 c 3 x:2 4 y 5 z 6 a:3 11 b:1 12 c:1 13 x:3 14 y:1 15 z:1 16} + + +# Tests for short=OFF and full=OFF +# +do_test colname-3.1 { + db eval { + PRAGMA short_column_names=OFF; + PRAGMA full_column_names=OFF; + CREATE VIEW v3 AS SELECT tabC.a, txyZ.x, * + FROM tabc, txyz ORDER BY 1 LIMIT 1; + CREATE VIEW v4 AS SELECT tabC.a, txyZ.x, tboTh.a, tbotH.x, * + FROM tabc, txyz, tboth ORDER BY 1 LIMIT 1; + } + execsql2 { + SELECT * FROM tabc; + } +} {a 1 b 2 c 3} +do_test colname-3.2 { + execsql2 { + SELECT Tabc.a, tAbc.b, taBc.c FROM tabc + } +} {Tabc.a 1 tAbc.b 2 taBc.c 3} +do_test colname-3.3 { + execsql2 { + SELECT +tabc.a, -tabc.b, tabc.c FROM tabc + } +} {+tabc.a 1 -tabc.b -2 tabc.c 3} +do_test colname-3.4 { + execsql2 { + SELECT +tabc.a AS AAA, -tabc.b AS BBB, tabc.c CCC FROM tabc + } +} {AAA 1 BBB -2 CCC 3} +do_test colname-3.5 { + execsql2 { + SELECT Tabc.a, Txyz.x, * FROM tabc, txyz; + } +} {Tabc.a 1 Txyz.x 4 a 1 b 2 c 3 x 4 y 5 z 6} +do_test colname-3.6 { + execsql2 { + SELECT tabc.*, txyz.* FROM tabc, txyz; + } +} {a 1 b 2 c 3 x 4 y 5 z 6} +do_test colname-3.7 { + execsql2 { + SELECT * FROM tabc, txyz, tboth; + } +} {a 11 b 12 c 13 x 14 y 15 z 16 a 11 b 12 c 13 x 14 y 15 z 16} +do_test colname-3.8 { + execsql2 { + SELECT v1.a, * FROM v1 ORDER BY 2; + } +} {v1.a 1 a 1 x 4 a:1 1 b 2 c 3 x:1 4 y 5 z 6} +do_test colname-3.9 { + execsql2 { + SELECT * FROM v2 ORDER BY 2; + } +} {a 1 x 4 a:1 11 x:1 14 a:2 1 b 2 c 3 x:2 4 y 5 z 6 a:3 11 b:1 12 c:1 13 x:3 14 y:1 15 z:1 16} +do_test colname-3.10 { + execsql2 { + SELECT * FROM v3 ORDER BY 2; + } +} {a 1 x 4 a:1 1 b 2 c 3 x:1 4 y 5 z 6} +do_test colname-3.11 { + execsql2 { + SELECT * FROM v4 ORDER BY 2; + } +} {a 1 x 4 a:1 11 x:1 14 a:2 1 b 2 c 3 x:2 4 y 5 z 6 a:3 11 b:1 12 c:1 13 x:3 14 y:1 15 z:1 16} + +# Test for short=OFF and full=ON +# +do_test colname-4.1 { + db eval { + PRAGMA short_column_names=OFF; + PRAGMA full_column_names=ON; + CREATE VIEW v5 AS SELECT tabC.a, txyZ.x, * + FROM tabc, txyz ORDER BY 1 LIMIT 1; + CREATE VIEW v6 AS SELECT tabC.a, txyZ.x, tboTh.a, tbotH.x, * + FROM tabc, txyz, tboth ORDER BY 1 LIMIT 1; + } + execsql2 { + SELECT * FROM tabc; + } +} {tabc.a 1 tabc.b 2 tabc.c 3} +do_test colname-4.2 { + execsql2 { + SELECT Tabc.a, tAbc.b, taBc.c FROM tabc + } +} {tabc.a 1 tabc.b 2 tabc.c 3} +do_test colname-4.3 { + execsql2 { + SELECT +tabc.a, -tabc.b, tabc.c FROM tabc + } +} {+tabc.a 1 -tabc.b -2 tabc.c 3} +do_test colname-4.4 { + execsql2 { + SELECT +tabc.a AS AAA, -tabc.b AS BBB, tabc.c CCC FROM tabc + } +} {AAA 1 BBB -2 CCC 3} +do_test colname-4.5 { + execsql2 { + SELECT Tabc.a, Txyz.x, * FROM tabc, txyz; + } +} {tabc.a 1 txyz.x 4 tabc.a 1 tabc.b 2 tabc.c 3 txyz.x 4 txyz.y 5 txyz.z 6} +do_test colname-4.6 { + execsql2 { + SELECT tabc.*, txyz.* FROM tabc, txyz; + } +} {tabc.a 1 tabc.b 2 tabc.c 3 txyz.x 4 txyz.y 5 txyz.z 6} +do_test colname-4.7 { + execsql2 { + SELECT * FROM tabc, txyz, tboth; + } +} {tabc.a 1 tabc.b 2 tabc.c 3 txyz.x 4 txyz.y 5 txyz.z 6 tboth.a 11 tboth.b 12 tboth.c 13 tboth.x 14 tboth.y 15 tboth.z 16} +do_test colname-4.8 { + execsql2 { + SELECT * FROM v1 ORDER BY 2; + } +} {v1.a 1 v1.x 4 v1.a:1 1 v1.b 2 v1.c 3 v1.x:1 4 v1.y 5 v1.z 6} +do_test colname-4.9 { + execsql2 { + SELECT * FROM v2 ORDER BY 2; + } +} {v2.a 1 v2.x 4 v2.a:1 11 v2.x:1 14 v2.a:2 1 v2.b 2 v2.c 3 v2.x:2 4 v2.y 5 v2.z 6 v2.a:3 11 v2.b:1 12 v2.c:1 13 v2.x:3 14 v2.y:1 15 v2.z:1 16} +do_test colname-4.10 { + execsql2 { + SELECT * FROM v3 ORDER BY 2; + } +} {v3.a 1 v3.x 4 v3.a:1 1 v3.b 2 v3.c 3 v3.x:1 4 v3.y 5 v3.z 6} +do_test colname-4.11 { + execsql2 { + SELECT * FROM v4 ORDER BY 2; + } +} {v4.a 1 v4.x 4 v4.a:1 11 v4.x:1 14 v4.a:2 1 v4.b 2 v4.c 3 v4.x:2 4 v4.y 5 v4.z 6 v4.a:3 11 v4.b:1 12 v4.c:1 13 v4.x:3 14 v4.y:1 15 v4.z:1 16} +do_test colname-4.12 { + execsql2 { + SELECT * FROM v5 ORDER BY 2; + } +} {v5.a 1 v5.x 4 v5.a:1 1 v5.b 2 v5.c 3 v5.x:1 4 v5.y 5 v5.z 6} +do_test colname-4.13 { + execsql2 { + SELECT * FROM v6 ORDER BY 2; + } +} {v6.a 1 v6.x 4 v6.a:1 11 v6.x:1 14 v6.a:2 1 v6.b 2 v6.c 3 v6.x:2 4 v6.y 5 v6.z 6 v6.a:3 11 v6.b:1 12 v6.c:1 13 v6.x:3 14 v6.y:1 15 v6.z:1 16} + +# ticket #3229 +do_test colname-5.1 { + lreplace [db eval { + SELECT x.* FROM sqlite_master X LIMIT 1; + }] 3 3 x +} {table tabc tabc x {CREATE TABLE tabc(a,b,c)}} + +# ticket #3370, #3371, #3372 +# +do_test colname-6.1 { + db close + sqlite3 db test.db + db eval { + CREATE TABLE t6(a, ['a'], ["a"], "[a]", [`a`]); + INSERT INTO t6 VALUES(1,2,3,4,5); + } + execsql2 {SELECT * FROM t6} +} {a 1 'a' 2 {"a"} 3 {[a]} 4 `a` 5} +do_test colname-6.2 { + execsql2 {SELECT ['a'], [`a`], "[a]", [a], ["a"] FROM t6} +} {'a' 2 `a` 5 {[a]} 4 a 1 {"a"} 3} +do_test colname-6.3 { + execsql2 {SELECT "'a'", "`a`", "[a]", "a", """a""" FROM t6} +} {'a' 2 `a` 5 {[a]} 4 a 1 {"a"} 3} +do_test colname-6.4 { + execsql2 {SELECT `'a'`, ```a```, `[a]`, `a`, `"a"` FROM t6} +} {'a' 2 `a` 5 {[a]} 4 a 1 {"a"} 3} +do_test colname-6.11 { + execsql2 {SELECT a, max(a) AS m FROM t6} +} {a 1 m 1} +do_test colname-6.12 { + execsql2 {SELECT `a`, max(a) AS m FROM t6} +} {a 1 m 1} +do_test colname-6.13 { + execsql2 {SELECT "a", max(a) AS m FROM t6} +} {a 1 m 1} +do_test colname-6.14 { + execsql2 {SELECT [a], max(a) AS m FROM t6} +} {a 1 m 1} +do_test colname-6.15 { + execsql2 {SELECT t6.a, max(a) AS m FROM t6} +} {a 1 m 1} +do_test colname-6.16 { + execsql2 {SELECT ['a'], max(['a']) AS m FROM t6} +} {'a' 2 m 2} +do_test colname-6.17 { + execsql2 {SELECT ["a"], max(["a"]) AS m FROM t6} +} {{"a"} 3 m 3} +do_test colname-6.18 { + execsql2 {SELECT "[a]", max("[a]") AS m FROM t6} +} {{[a]} 4 m 4} +do_test colname-6.19 { + execsql2 {SELECT "`a`", max([`a`]) AS m FROM t6} +} {`a` 5 m 5} + + +# Ticket #3429 +# We cannot find anything wrong, but it never hurts to add another +# test case. +# +do_test colname-7.1 { + db eval { + CREATE TABLE t7(x INTEGER PRIMARY KEY, y); + INSERT INTO t7 VALUES(1,2); + } + execsql2 {SELECT rowid, * FROM t7} +} {x 1 x 1 y 2} + +# Tickets #3893 and #3984. (Same problem; independently reported) +# +do_test colname-8.1 { + db eval { + CREATE TABLE "t3893"("x"); + INSERT INTO t3893 VALUES(123); + SELECT "y"."x" FROM (SELECT "x" FROM "t3893") AS "y"; + } +} {123} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/conflict.test b/components/external/SQLite-3.8.1/test/conflict.test new file mode 100644 index 0000000000000000000000000000000000000000..65769596074f825f1cf1f3ba6f80363fb0592663 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/conflict.test @@ -0,0 +1,818 @@ +# 2002 January 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the conflict resolution extension +# to SQLite. +# +# $Id: conflict.test,v 1.32 2009/04/30 09:10:38 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !conflict { + finish_test + return +} + +# Create tables for the first group of tests. +# +do_test conflict-1.0 { + execsql { + CREATE TABLE t1(a, b, c, UNIQUE(a,b)); + CREATE TABLE t2(x); + SELECT c FROM t1 ORDER BY c; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# t3 Number of temporary files created by this test +# +foreach {i cmd t0 t1 t2 t3} { + 1 INSERT 1 {} 1 0 + 2 {INSERT OR IGNORE} 0 3 1 0 + 3 {INSERT OR REPLACE} 0 4 1 0 + 4 REPLACE 0 4 1 0 + 5 {INSERT OR FAIL} 1 {} 1 0 + 6 {INSERT OR ABORT} 1 {} 1 0 + 7 {INSERT OR ROLLBACK} 1 {} {} 0 +} { + do_test conflict-1.$i { + set ::sqlite_opentemp_count 0 + set r0 [catch {execsql [subst { + DELETE FROM t1; + DELETE FROM t2; + INSERT INTO t1 VALUES(1,2,3); + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,4); + }]} r1] + catch {execsql {COMMIT}} + if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + set r3 $::sqlite_opentemp_count + list $r0 $r1 $r2 $r3 + } [list $t0 $t1 $t2 $t3] +} + +# Create tables for the first group of tests. +# +do_test conflict-2.0 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(a,b)); + CREATE TABLE t2(x); + SELECT c FROM t1 ORDER BY c; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# +foreach {i cmd t0 t1 t2} { + 1 INSERT 1 {} 1 + 2 {INSERT OR IGNORE} 0 3 1 + 3 {INSERT OR REPLACE} 0 4 1 + 4 REPLACE 0 4 1 + 5 {INSERT OR FAIL} 1 {} 1 + 6 {INSERT OR ABORT} 1 {} 1 + 7 {INSERT OR ROLLBACK} 1 {} {} +} { + do_test conflict-2.$i { + set r0 [catch {execsql [subst { + DELETE FROM t1; + DELETE FROM t2; + INSERT INTO t1 VALUES(1,2,3); + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,4); + }]} r1] + catch {execsql {COMMIT}} + if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +# Create tables for the first group of tests. +# +do_test conflict-3.0 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + CREATE TABLE t1(a, b, c INTEGER, PRIMARY KEY(c), UNIQUE(a,b)); + CREATE TABLE t2(x); + SELECT c FROM t1 ORDER BY c; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# +foreach {i cmd t0 t1 t2} { + 1 INSERT 1 {} 1 + 2 {INSERT OR IGNORE} 0 3 1 + 3 {INSERT OR REPLACE} 0 4 1 + 4 REPLACE 0 4 1 + 5 {INSERT OR FAIL} 1 {} 1 + 6 {INSERT OR ABORT} 1 {} 1 + 7 {INSERT OR ROLLBACK} 1 {} {} +} { + do_test conflict-3.$i { + set r0 [catch {execsql [subst { + DELETE FROM t1; + DELETE FROM t2; + INSERT INTO t1 VALUES(1,2,3); + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,4); + }]} r1] + catch {execsql {COMMIT}} + if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +do_test conflict-4.0 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(x); + SELECT x FROM t2; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# conf1 The conflict resolution algorithm on the UNIQUE constraint +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# +foreach {i conf1 cmd t0 t1 t2} { + 1 {} INSERT 1 {} 1 + 2 REPLACE INSERT 0 4 1 + 3 IGNORE INSERT 0 3 1 + 4 FAIL INSERT 1 {} 1 + 5 ABORT INSERT 1 {} 1 + 6 ROLLBACK INSERT 1 {} {} + 7 REPLACE {INSERT OR IGNORE} 0 3 1 + 8 IGNORE {INSERT OR REPLACE} 0 4 1 + 9 FAIL {INSERT OR IGNORE} 0 3 1 + 10 ABORT {INSERT OR REPLACE} 0 4 1 + 11 ROLLBACK {INSERT OR IGNORE } 0 3 1 +} { + do_test conflict-4.$i { + if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"} + set r0 [catch {execsql [subst { + DROP TABLE t1; + CREATE TABLE t1(a,b,c,UNIQUE(a,b) $conf1); + DELETE FROM t2; + INSERT INTO t1 VALUES(1,2,3); + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,4); + }]} r1] + catch {execsql {COMMIT}} + if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +do_test conflict-5.0 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(x); + SELECT x FROM t2; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# conf1 The conflict resolution algorithm on the NOT NULL constraint +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# +foreach {i conf1 cmd t0 t1 t2} { + 1 {} INSERT 1 {} 1 + 2 REPLACE INSERT 0 5 1 + 3 IGNORE INSERT 0 {} 1 + 4 FAIL INSERT 1 {} 1 + 5 ABORT INSERT 1 {} 1 + 6 ROLLBACK INSERT 1 {} {} + 7 REPLACE {INSERT OR IGNORE} 0 {} 1 + 8 IGNORE {INSERT OR REPLACE} 0 5 1 + 9 FAIL {INSERT OR IGNORE} 0 {} 1 + 10 ABORT {INSERT OR REPLACE} 0 5 1 + 11 ROLLBACK {INSERT OR IGNORE} 0 {} 1 + 12 {} {INSERT OR IGNORE} 0 {} 1 + 13 {} {INSERT OR REPLACE} 0 5 1 + 14 {} {INSERT OR FAIL} 1 {} 1 + 15 {} {INSERT OR ABORT} 1 {} 1 + 16 {} {INSERT OR ROLLBACK} 1 {} {} +} { + if {$t0} {set t1 {t1.c may not be NULL}} + do_test conflict-5.$i { + if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"} + set r0 [catch {execsql [subst { + DROP TABLE t1; + CREATE TABLE t1(a,b,c NOT NULL $conf1 DEFAULT 5); + DELETE FROM t2; + BEGIN; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,NULL); + }]} r1] + catch {execsql {COMMIT}} + if {!$r0} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +do_test conflict-6.0 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(a,b,c); + INSERT INTO t2 VALUES(1,2,1); + INSERT INTO t2 VALUES(2,3,2); + INSERT INTO t2 VALUES(3,4,1); + INSERT INTO t2 VALUES(4,5,4); + SELECT c FROM t2 ORDER BY b; + CREATE TABLE t3(x); + INSERT INTO t3 VALUES(1); + } +} {1 2 1 4} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# conf1 The conflict resolution algorithm on the UNIQUE constraint +# cmd An UPDATE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "b" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t3 +# t3 Number of temporary files for tables +# t4 Number of temporary files for statement journals +# +# Update: Since temporary table files are now opened lazily, and none +# of the following tests use large quantities of data, t3 is always 0. +# +foreach {i conf1 cmd t0 t1 t2 t3 t4} { + 1 {} UPDATE 1 {6 7 8 9} 1 0 1 + 2 REPLACE UPDATE 0 {7 6 9} 1 0 0 + 3 IGNORE UPDATE 0 {6 7 3 9} 1 0 0 + 4 FAIL UPDATE 1 {6 7 3 4} 1 0 0 + 5 ABORT UPDATE 1 {1 2 3 4} 1 0 1 + 6 ROLLBACK UPDATE 1 {1 2 3 4} 0 0 0 + 7 REPLACE {UPDATE OR IGNORE} 0 {6 7 3 9} 1 0 0 + 8 IGNORE {UPDATE OR REPLACE} 0 {7 6 9} 1 0 0 + 9 FAIL {UPDATE OR IGNORE} 0 {6 7 3 9} 1 0 0 + 10 ABORT {UPDATE OR REPLACE} 0 {7 6 9} 1 0 0 + 11 ROLLBACK {UPDATE OR IGNORE} 0 {6 7 3 9} 1 0 0 + 12 {} {UPDATE OR IGNORE} 0 {6 7 3 9} 1 0 0 + 13 {} {UPDATE OR REPLACE} 0 {7 6 9} 1 0 0 + 14 {} {UPDATE OR FAIL} 1 {6 7 3 4} 1 0 0 + 15 {} {UPDATE OR ABORT} 1 {1 2 3 4} 1 0 1 + 16 {} {UPDATE OR ROLLBACK} 1 {1 2 3 4} 0 0 0 +} { + if {$t0} {set t1 {column a is not unique}} + if {[info exists TEMP_STORE] && $TEMP_STORE==3} { + set t3 0 + } else { + set t3 [expr {$t3+$t4}] + } + do_test conflict-6.$i { + db close + sqlite3 db test.db + if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"} + execsql {pragma temp_store=file} + set ::sqlite_opentemp_count 0 + set r0 [catch {execsql [subst { + DROP TABLE t1; + CREATE TABLE t1(a,b,c, UNIQUE(a) $conf1); + INSERT INTO t1 SELECT * FROM t2; + UPDATE t3 SET x=0; + BEGIN; + $cmd t3 SET x=1; + $cmd t1 SET b=b*2; + $cmd t1 SET a=c+5; + }]} r1] + catch {execsql {COMMIT}} + if {!$r0} {set r1 [execsql {SELECT a FROM t1 ORDER BY b}]} + set r2 [execsql {SELECT x FROM t3}] + list $r0 $r1 $r2 $::sqlite_opentemp_count + } [list $t0 $t1 $t2 $t3] +} + +# Test to make sure a lot of IGNOREs don't cause a stack overflow +# +do_test conflict-7.1 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + CREATE TABLE t1(a unique, b); + } + for {set i 1} {$i<=50} {incr i} { + execsql "INSERT into t1 values($i,[expr {$i+1}]);" + } + execsql { + SELECT count(*), min(a), max(b) FROM t1; + } +} {50 1 51} +do_test conflict-7.2 { + execsql { + PRAGMA count_changes=on; + UPDATE OR IGNORE t1 SET a=1000; + } +} {1} +do_test conflict-7.2.1 { + db changes +} {1} +do_test conflict-7.3 { + execsql { + SELECT b FROM t1 WHERE a=1000; + } +} {2} +do_test conflict-7.4 { + execsql { + SELECT count(*) FROM t1; + } +} {50} +do_test conflict-7.5 { + execsql { + PRAGMA count_changes=on; + UPDATE OR REPLACE t1 SET a=1001; + } +} {50} +do_test conflict-7.5.1 { + db changes +} {50} +do_test conflict-7.6 { + execsql { + SELECT b FROM t1 WHERE a=1001; + } +} {51} +do_test conflict-7.7 { + execsql { + SELECT count(*) FROM t1; + } +} {1} + +# Update for version 3: A SELECT statement no longer resets the change +# counter (Test result changes from 0 to 50). +do_test conflict-7.7.1 { + db changes +} {50} + +# Make sure the row count is right for rows that are ignored on +# an insert. +# +do_test conflict-8.1 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2); + } + execsql { + INSERT OR IGNORE INTO t1 VALUES(2,3); + } +} {1} +do_test conflict-8.1.1 { + db changes +} {1} +do_test conflict-8.2 { + execsql { + INSERT OR IGNORE INTO t1 VALUES(2,4); + } +} {0} +do_test conflict-8.2.1 { + db changes +} {0} +do_test conflict-8.3 { + execsql { + INSERT OR REPLACE INTO t1 VALUES(2,4); + } +} {1} +do_test conflict-8.3.1 { + db changes +} {1} +do_test conflict-8.4 { + execsql { + INSERT OR IGNORE INTO t1 SELECT * FROM t1; + } +} {0} +do_test conflict-8.4.1 { + db changes +} {0} +do_test conflict-8.5 { + execsql { + INSERT OR IGNORE INTO t1 SELECT a+2,b+2 FROM t1; + } +} {2} +do_test conflict-8.5.1 { + db changes +} {2} +do_test conflict-8.6 { + execsql { + INSERT OR IGNORE INTO t1 SELECT a+3,b+3 FROM t1; + } +} {3} +do_test conflict-8.6.1 { + db changes +} {3} + +integrity_check conflict-8.99 + +do_test conflict-9.1 { + execsql { + PRAGMA count_changes=0; + CREATE TABLE t2( + a INTEGER UNIQUE ON CONFLICT IGNORE, + b INTEGER UNIQUE ON CONFLICT FAIL, + c INTEGER UNIQUE ON CONFLICT REPLACE, + d INTEGER UNIQUE ON CONFLICT ABORT, + e INTEGER UNIQUE ON CONFLICT ROLLBACK + ); + CREATE TABLE t3(x); + INSERT INTO t3 VALUES(1); + SELECT * FROM t3; + } +} {1} +do_test conflict-9.2 { + catchsql { + INSERT INTO t2 VALUES(1,1,1,1,1); + INSERT INTO t2 VALUES(2,2,2,2,2); + SELECT * FROM t2; + } +} {0 {1 1 1 1 1 2 2 2 2 2}} +do_test conflict-9.3 { + catchsql { + INSERT INTO t2 VALUES(1,3,3,3,3); + SELECT * FROM t2; + } +} {0 {1 1 1 1 1 2 2 2 2 2}} +do_test conflict-9.4 { + catchsql { + UPDATE t2 SET a=a+1 WHERE a=1; + SELECT * FROM t2; + } +} {0 {1 1 1 1 1 2 2 2 2 2}} +do_test conflict-9.5 { + catchsql { + INSERT INTO t2 VALUES(3,1,3,3,3); + SELECT * FROM t2; + } +} {1 {column b is not unique}} +do_test conflict-9.6 { + catchsql { + UPDATE t2 SET b=b+1 WHERE b=1; + SELECT * FROM t2; + } +} {1 {column b is not unique}} +do_test conflict-9.7 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + INSERT INTO t2 VALUES(3,1,3,3,3); + SELECT * FROM t2; + } +} {1 {column b is not unique}} +do_test conflict-9.8 { + execsql {COMMIT} + execsql {SELECT * FROM t3} +} {2} +do_test conflict-9.9 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + UPDATE t2 SET b=b+1 WHERE b=1; + SELECT * FROM t2; + } +} {1 {column b is not unique}} +do_test conflict-9.10 { + execsql {COMMIT} + execsql {SELECT * FROM t3} +} {3} +do_test conflict-9.11 { + catchsql { + INSERT INTO t2 VALUES(3,3,3,1,3); + SELECT * FROM t2; + } +} {1 {column d is not unique}} +do_test conflict-9.12 { + catchsql { + UPDATE t2 SET d=d+1 WHERE d=1; + SELECT * FROM t2; + } +} {1 {column d is not unique}} +do_test conflict-9.13 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + INSERT INTO t2 VALUES(3,3,3,1,3); + SELECT * FROM t2; + } +} {1 {column d is not unique}} +do_test conflict-9.14 { + execsql {COMMIT} + execsql {SELECT * FROM t3} +} {4} +do_test conflict-9.15 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + UPDATE t2 SET d=d+1 WHERE d=1; + SELECT * FROM t2; + } +} {1 {column d is not unique}} +do_test conflict-9.16 { + execsql {COMMIT} + execsql {SELECT * FROM t3} +} {5} +do_test conflict-9.17 { + catchsql { + INSERT INTO t2 VALUES(3,3,3,3,1); + SELECT * FROM t2; + } +} {1 {column e is not unique}} +do_test conflict-9.18 { + catchsql { + UPDATE t2 SET e=e+1 WHERE e=1; + SELECT * FROM t2; + } +} {1 {column e is not unique}} +do_test conflict-9.19 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + INSERT INTO t2 VALUES(3,3,3,3,1); + SELECT * FROM t2; + } +} {1 {column e is not unique}} +verify_ex_errcode conflict-9.21b SQLITE_CONSTRAINT_UNIQUE +do_test conflict-9.20 { + catch {execsql {COMMIT}} + execsql {SELECT * FROM t3} +} {5} +do_test conflict-9.21 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + UPDATE t2 SET e=e+1 WHERE e=1; + SELECT * FROM t2; + } +} {1 {column e is not unique}} +verify_ex_errcode conflict-9.21b SQLITE_CONSTRAINT_UNIQUE +do_test conflict-9.22 { + catch {execsql {COMMIT}} + execsql {SELECT * FROM t3} +} {5} +do_test conflict-9.23 { + catchsql { + INSERT INTO t2 VALUES(3,3,1,3,3); + SELECT * FROM t2; + } +} {0 {2 2 2 2 2 3 3 1 3 3}} +do_test conflict-9.24 { + catchsql { + UPDATE t2 SET c=c-1 WHERE c=2; + SELECT * FROM t2; + } +} {0 {2 2 1 2 2}} +do_test conflict-9.25 { + catchsql { + BEGIN; + UPDATE t3 SET x=x+1; + INSERT INTO t2 VALUES(3,3,1,3,3); + SELECT * FROM t2; + } +} {0 {3 3 1 3 3}} +do_test conflict-9.26 { + catch {execsql {COMMIT}} + execsql {SELECT * FROM t3} +} {6} + +do_test conflict-10.1 { + catchsql { + DELETE FROM t1; + BEGIN; + INSERT OR ROLLBACK INTO t1 VALUES(1,2); + INSERT OR ROLLBACK INTO t1 VALUES(1,3); + COMMIT; + } + execsql {SELECT * FROM t1} +} {} +do_test conflict-10.2 { + catchsql { + CREATE TABLE t4(x); + CREATE UNIQUE INDEX t4x ON t4(x); + BEGIN; + INSERT OR ROLLBACK INTO t4 VALUES(1); + INSERT OR ROLLBACK INTO t4 VALUES(1); + COMMIT; + } + execsql {SELECT * FROM t4} +} {} + +# Ticket #1171. Make sure statement rollbacks do not +# damage the database. +# +do_test conflict-11.1 { + execsql { + -- Create a database object (pages 2, 3 of the file) + BEGIN; + CREATE TABLE abc(a UNIQUE, b, c); + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, 6); + INSERT INTO abc VALUES(7, 8, 9); + COMMIT; + } + + + # Set a small cache size so that changes will spill into + # the database file. + execsql { + PRAGMA cache_size = 10; + } + + # Make lots of changes. Because of the small cache, some + # (most?) of these changes will spill into the disk file. + # In other words, some of the changes will not be held in + # cache. + # + execsql { + BEGIN; + -- Make sure the pager is in EXCLUSIVE state. + CREATE TABLE def(d, e, f); + INSERT INTO def VALUES + ('xxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzz'); + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + DELETE FROM abc WHERE a = 4; + } + + # Execute a statement that does a statement rollback due to + # a constraint failure. + # + catchsql { + INSERT INTO abc SELECT 10, 20, 30 FROM def; + } + + # Rollback the database. Verify that the state of the ABC table + # is unchanged from the beginning of the transaction. In other words, + # make sure the DELETE on table ABC that occurred within the transaction + # had no effect. + # + execsql { + ROLLBACK; + SELECT * FROM abc; + } +} {1 2 3 4 5 6 7 8 9} +integrity_check conflict-11.2 + +# Repeat test conflict-11.1 but this time commit. +# +do_test conflict-11.3 { + execsql { + BEGIN; + -- Make sure the pager is in EXCLUSIVE state. + UPDATE abc SET a=a+1; + CREATE TABLE def(d, e, f); + INSERT INTO def VALUES + ('xxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzz'); + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + DELETE FROM abc WHERE a = 4; + } + catchsql { + INSERT INTO abc SELECT 10, 20, 30 FROM def; + } + execsql { + ROLLBACK; + SELECT * FROM abc; + } +} {1 2 3 4 5 6 7 8 9} +# Repeat test conflict-11.1 but this time commit. +# +do_test conflict-11.5 { + execsql { + BEGIN; + -- Make sure the pager is in EXCLUSIVE state. + CREATE TABLE def(d, e, f); + INSERT INTO def VALUES + ('xxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzz'); + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + INSERT INTO def SELECT * FROM def; + DELETE FROM abc WHERE a = 4; + } + catchsql { + INSERT INTO abc SELECT 10, 20, 30 FROM def; + } + execsql { + COMMIT; + SELECT * FROM abc; + } +} {1 2 3 7 8 9} +integrity_check conflict-11.6 + +# Make sure UPDATE OR REPLACE works on tables that have only +# an INTEGER PRIMARY KEY. +# +do_test conflict-12.1 { + execsql { + CREATE TABLE t5(a INTEGER PRIMARY KEY, b text); + INSERT INTO t5 VALUES(1,'one'); + INSERT INTO t5 VALUES(2,'two'); + SELECT * FROM t5 + } +} {1 one 2 two} +do_test conflict-12.2 { + execsql { + UPDATE OR IGNORE t5 SET a=a+1 WHERE a=1; + SELECT * FROM t5; + } +} {1 one 2 two} +do_test conflict-12.3 { + catchsql { + UPDATE t5 SET a=a+1 WHERE a=1; + } +} {1 {PRIMARY KEY must be unique}} +verify_ex_errcode conflict-12.3b SQLITE_CONSTRAINT_PRIMARYKEY +do_test conflict-12.4 { + execsql { + UPDATE OR REPLACE t5 SET a=a+1 WHERE a=1; + SELECT * FROM t5; + } +} {2 one} + + +# Ticket [c38baa3d969eab7946dc50ba9d9b4f0057a19437] +# REPLACE works like ABORT on a CHECK constraint. +# +do_test conflict-13.1 { + execsql { + CREATE TABLE t13(a CHECK(a!=2)); + BEGIN; + REPLACE INTO t13 VALUES(1); + } + catchsql { + REPLACE INTO t13 VALUES(2); + } +} {1 {constraint failed}} +verify_ex_errcode conflict-13.1b SQLITE_CONSTRAINT_CHECK +do_test conflict-13.2 { + execsql { + REPLACE INTO t13 VALUES(3); + COMMIT; + SELECT * FROM t13; + } +} {1 3} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/contrib01.test b/components/external/SQLite-3.8.1/test/contrib01.test new file mode 100644 index 0000000000000000000000000000000000000000..43ea47c3e464f57721f97c34e9d8baf18b264002 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/contrib01.test @@ -0,0 +1,90 @@ +# 2013-06-05 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file contains test cases that were contributed on the sqlite-users +# mailing list on 2013-06-05 by Mi Chen at mi.chen@echostar.com. +# +# At the time it was contributed, this test failed on trunk, but +# worked on the NGQP. + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build some test data +# +do_test contrib01-1.0 { + db eval { + CREATE TABLE T1 (B INTEGER NOT NULL, + C INTEGER NOT NULL, + D INTEGER NOT NULL, + E INTEGER NOT NULL, + F INTEGER NOT NULL, + G INTEGER NOT NULL, + H INTEGER NOT NULL, + PRIMARY KEY (B, C, D)); + + CREATE TABLE T2 (A INTEGER NOT NULL, + B INTEGER NOT NULL, + C INTEGER NOT NULL, + PRIMARY KEY (A, B, C)); + + INSERT INTO T2(A, B, C) VALUES(702118,16183,15527); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15560); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15561); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15563); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15564); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15566); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15567); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15569); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15612); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15613); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15638); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15681); + INSERT INTO T2(A, B, C) VALUES(702118,16183,15682); + + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15527,6,0,5,5,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15560,6,0,5,2,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15561,6,0,5,2,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15563,6,0,5,2,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15564,6,0,5,2,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15566,6,0,5,2,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15567,6,0,5,2,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15569,6,0,5,2,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15612,6,0,5,5,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15613,6,0,5,2,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15638,6,0,5,2,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15681,6,0,5,5,0); + INSERT INTO T1(B, C, D, E, F, G, H) VALUES(16183,15682,6,0,5,2,0); + } +} {} +do_test contrib01-1.1 { + db eval { + SELECT T2.A, T2.B, T1.D, T1.E, T1.F, T1.G, T1.H, MAX(T1.C), '^' + FROM T1, T2 + WHERE T1.B = T2.B + AND T1.C = T2.C + GROUP BY T2.A, T2.B, T1.D, T1.E, T1.F, T1.G, T1.H + ORDER BY +max(t1.c); + } +} {702118 16183 6 0 5 5 0 15681 ^ 702118 16183 6 0 5 2 0 15682 ^} +do_test contrib01-1.2 { + db eval { + SELECT T2.A, T2.B, T1.D, T1.E, T1.F, T1.G, T1.H, MAX(T1.C), '^' + FROM T1, T2 + WHERE T1.B = T2.B + AND T1.C = T2.C + GROUP BY T2.A, T2.B, T1.F, T1.D, T1.E, T1.G, T1.H + ORDER BY +max(t1.c); + } +} {702118 16183 6 0 5 5 0 15681 ^ 702118 16183 6 0 5 2 0 15682 ^} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corrupt.test b/components/external/SQLite-3.8.1/test/corrupt.test new file mode 100644 index 0000000000000000000000000000000000000000..09f3c5bd7c0f9a00f0f270636f5e9e2f5e717f75 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corrupt.test @@ -0,0 +1,344 @@ +# 2004 August 30 {} +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. +# +# $Id: corrupt.test,v 1.12 2009/07/13 09:41:45 danielk1977 Exp $ + +catch {forcedelete test.db test.db-journal test.bu} + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Construct a large database for testing. +# +do_test corrupt-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randstr(100,100)); + INSERT INTO t1 VALUES(randstr(90,90)); + INSERT INTO t1 VALUES(randstr(80,80)); + INSERT INTO t1 SELECT x || randstr(5,5) FROM t1; + INSERT INTO t1 SELECT x || randstr(6,6) FROM t1; + INSERT INTO t1 SELECT x || randstr(7,7) FROM t1; + INSERT INTO t1 SELECT x || randstr(8,8) FROM t1; + INSERT INTO t1 VALUES(randstr(3000,3000)); + INSERT INTO t1 SELECT x || randstr(9,9) FROM t1; + INSERT INTO t1 SELECT x || randstr(10,10) FROM t1; + INSERT INTO t1 SELECT x || randstr(11,11) FROM t1; + INSERT INTO t1 SELECT x || randstr(12,12) FROM t1; + CREATE INDEX t1i1 ON t1(x); + CREATE TABLE t2 AS SELECT * FROM t1; + DELETE FROM t2 WHERE rowid%5!=0; + COMMIT; + } +} {} +integrity_check corrupt-1.2 + +# Setup for the tests. Make a backup copy of the good database in test.bu. +# Create a string of garbage data that is 256 bytes long. +# +forcecopy test.db test.bu +set fsize [file size test.db] +set junk "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" +while {[string length $junk]<256} {append junk $junk} +set junk [string range $junk 0 255] + +# Go through the database and write garbage data into each 256 segment +# of the file. Then do various operations on the file to make sure that +# the database engine can recover gracefully from the corruption. +# +for {set i [expr {1*256}]} {$i<$fsize-256} {incr i 256} { + set tn [expr {$i/256}] + db close + forcecopy test.bu test.db + set fd [open test.db r+] + fconfigure $fd -translation binary + seek $fd $i + puts -nonewline $fd $junk + close $fd + do_test corrupt-2.$tn.1 { + sqlite3 db test.db + catchsql {SELECT count(*) FROM sqlite_master} + set x {} + } {} + do_test corrupt-2.$tn.2 { + catchsql {SELECT count(*) FROM t1} + set x {} + } {} + do_test corrupt-2.$tn.3 { + catchsql {SELECT count(*) FROM t1 WHERE x>'abcdef'} + set x {} + } {} + do_test corrupt-2.$tn.4 { + catchsql {SELECT count(*) FROM t2} + set x {} + } {} + do_test corrupt-2.$tn.5 { + catchsql {CREATE TABLE t3 AS SELECT * FROM t1} + set x {} + } {} + do_test corrupt-2.$tn.6 { + catchsql {DROP TABLE t1} + set x {} + } {} + do_test corrupt-2.$tn.7 { + catchsql {PRAGMA integrity_check} + set x {} + } {} + + # Check that no page references were leaked. + do_test corrupt-2.$tn.8 { + set bt [btree_from_db db] + db_enter db + array set stats [btree_pager_stats $bt] + db_leave db + set stats(ref) + } {0} +} + +#------------------------------------------------------------------------ +# For these tests, swap the rootpage entries of t1 (a table) and t1i1 (an +# index on t1) in sqlite_master. Then perform a few different queries +# and make sure this is detected as corruption. +# +do_test corrupt-3.1 { + db close + forcecopy test.bu test.db + sqlite3 db test.db + list +} {} +do_test corrupt-3.2 { + set t1_r [execsql {SELECT rootpage FROM sqlite_master WHERE name = 't1i1'}] + set t1i1_r [execsql {SELECT rootpage FROM sqlite_master WHERE name = 't1'}] + set cookie [expr [execsql {PRAGMA schema_version}] + 1] + execsql " + PRAGMA writable_schema = 1; + UPDATE sqlite_master SET rootpage = $t1_r WHERE name = 't1'; + UPDATE sqlite_master SET rootpage = $t1i1_r WHERE name = 't1i1'; + PRAGMA writable_schema = 0; + PRAGMA schema_version = $cookie; + " +} {} + +# This one tests the case caught by code in checkin [2313]. +do_test corrupt-3.3 { + db close + sqlite3 db test.db + catchsql { + INSERT INTO t1 VALUES('abc'); + } +} {1 {database disk image is malformed}} +do_test corrupt-3.4 { + db close + sqlite3 db test.db + catchsql { + SELECT * FROM t1; + } +} {1 {database disk image is malformed}} +do_test corrupt-3.5 { + db close + sqlite3 db test.db + catchsql { + SELECT * FROM t1 WHERE oid = 10; + } +} {1 {database disk image is malformed}} +do_test corrupt-3.6 { + db close + sqlite3 db test.db + catchsql { + SELECT * FROM t1 WHERE x = 'abcde'; + } +} {1 {database disk image is malformed}} + +do_test corrupt-4.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT); + } + for {set i 0} {$i < 10} {incr i} { + set text [string repeat $i 220] + execsql { INSERT INTO t1 VALUES($i, $text) } + } + execsql { CREATE INDEX i1 ON t1(b) } +} {} +do_test corrupt-4.2 { + set iRoot [db one {SELECT rootpage FROM sqlite_master WHERE name = 'i1'}] + set iOffset [hexio_get_int [hexio_read test.db [expr 12+($iRoot-1)*1024] 2]] + set data [hexio_render_int32 [expr $iRoot - 1]] + hexio_write test.db [expr ($iRoot-1)*1024 + $iOffset] $data + db close + sqlite3 db test.db + + # The following DELETE statement attempts to delete a cell stored on the + # root page of index i1. After this cell is deleted it must be replaced + # by a cell retrieved from the child page (a leaf) of the deleted cell. + # This will fail, as the block modified the database image so that the + # child page of the deleted cell is from a table (intkey) b-tree, not an + # index b-tree as expected. At one point this was causing an assert() + # to fail. + catchsql { DELETE FROM t1 WHERE rowid = 3 } +} {1 {database disk image is malformed}} + +do_test corrupt-5.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + + execsql { PRAGMA page_size = 1024 } + set ct "CREATE TABLE t1(c0 " + set i 0 + while {[string length $ct] < 950} { append ct ", c[incr i]" } + append ct ")" + execsql $ct +} {} + +do_test corrupt-5.2 { + db close + hexio_write test.db 108 00000000 + sqlite3 db test.db + catchsql { SELECT * FROM sqlite_master } +} {1 {database disk image is malformed}} + +# At one point, the specific corruption caused by this test case was +# causing a buffer overwrite. Although a crash was never demonstrated, +# running this testcase under valgrind revealed the problem. +do_test corrupt-6.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; CREATE TABLE t1(x); + } + + # The root page of t1 is 1024 bytes in size. The header is 8 bytes, and + # each of the cells inserted by the following INSERT statements consume + # 16 bytes (including the 2 byte cell-offset array entry). So the page + # can contain up to 63 cells. + for {set i 0} {$i < 63} {incr i} { + execsql { INSERT INTO t1 VALUES( randomblob(10) ) } + } + + # Free the cell stored right at the end of the page (at offset pgsz-14). + execsql { DELETE FROM t1 WHERE rowid=1 } + set rootpage [db one {SELECT rootpage FROM sqlite_master WHERE name = 't1'}] + db close + + set offset [expr ($rootpage * 1024)-14+2] + hexio_write test.db $offset 00FF + sqlite3 db test.db + + catchsql { INSERT INTO t1 VALUES( randomblob(10) ) } +} {1 {database disk image is malformed}} + +ifcapable oversize_cell_check { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; CREATE TABLE t1(x); + } + + do_test corrupt-7.1 { + for {set i 0} {$i < 39} {incr i} { + execsql { + INSERT INTO t1 VALUES(X'000100020003000400050006000700080009000A'); + } + } + } {} + db close + + # Corrupt the root page of table t1 so that the first offset in the + # cell-offset array points to the data for the SQL blob associated with + # record (rowid=10). The root page still passes the checks in btreeInitPage(), + # because the start of said blob looks like the start of a legitimate + # page cell. + # + # Test case cc-2 overwrites the blob so that it no longer looks like a + # real cell. But, by the time it is overwritten, btreeInitPage() has already + # initialized the root page, so no corruption is detected. + # + # Test case cc-3 inserts an extra record into t1, forcing balance-deeper + # to run. After copying the contents of the root page to the new child, + # btreeInitPage() is called on the child. This time, it detects corruption + # (because the start of the blob associated with the (rowid=10) record + # no longer looks like a real cell). At one point the code assumed that + # detecting corruption was not possible at that point, and an assert() failed. + # + set fd [open test.db r+] + fconfigure $fd -translation binary -encoding binary + seek $fd [expr 1024+8] + puts -nonewline $fd "\x03\x14" + close $fd + + sqlite3 db test.db + do_test corrupt-7.2 { + execsql { + UPDATE t1 SET x = X'870400020003000400050006000700080009000A' + WHERE rowid = 10; + } + } {} + do_test corrupt-7.3 { + catchsql { + INSERT INTO t1 VALUES(X'000100020003000400050006000700080009000A'); + } + } {1 {database disk image is malformed}} +} + +db close +forcedelete test.db test.db-journal +do_test corrupt-8.1 { + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + PRAGMA secure_delete = on; + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(x INTEGER PRIMARY KEY, y); + INSERT INTO t1 VALUES(5, randomblob(1900)); + } + + hexio_write test.db 2044 [hexio_render_int32 2] + hexio_write test.db 24 [hexio_render_int32 45] + + catchsql { INSERT OR REPLACE INTO t1 VALUES(5, randomblob(1900)) } +} {1 {database disk image is malformed}} + +db close +forcedelete test.db test.db-journal +do_test corrupt-8.2 { + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + PRAGMA secure_delete = on; + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(x INTEGER PRIMARY KEY, y); + INSERT INTO t1 VALUES(5, randomblob(900)); + INSERT INTO t1 VALUES(6, randomblob(900)); + } + + hexio_write test.db 2047 FF + hexio_write test.db 24 [hexio_render_int32 45] + + catchsql { INSERT INTO t1 VALUES(4, randomblob(1900)) } +} {1 {database disk image is malformed}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corrupt2.test b/components/external/SQLite-3.8.1/test/corrupt2.test new file mode 100644 index 0000000000000000000000000000000000000000..744a76ed04ac9b125177211e2e91850d0766137c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corrupt2.test @@ -0,0 +1,558 @@ +# 2004 August 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. +# +# $Id: corrupt2.test,v 1.20 2009/04/06 17:50:03 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +set presql "" +catch { set presql "$::G(perm:presql);" } +unset -nocomplain ::G(perm:presql) + +# The following tests - corrupt2-1.* - create some databases corrupted in +# specific ways and ensure that SQLite detects them as corrupt. +# +do_test corrupt2-1.1 { + execsql { + PRAGMA auto_vacuum=0; + PRAGMA page_size=1024; + CREATE TABLE abc(a, b, c); + } +} {} + +do_test corrupt2-1.2 { + + # Corrupt the 16 byte magic string at the start of the file + forcedelete corrupt.db + forcedelete corrupt.db-journal + forcecopy test.db corrupt.db + set f [open corrupt.db RDWR] + seek $f 8 start + puts $f blah + close $f + + sqlite3 db2 corrupt.db + catchsql " + $::presql + SELECT * FROM sqlite_master; + " db2 +} {1 {file is encrypted or is not a database}} + +do_test corrupt2-1.3 { + db2 close + + # Corrupt the page-size (bytes 16 and 17 of page 1). + forcedelete corrupt.db + forcedelete corrupt.db-journal + forcecopy test.db corrupt.db + set f [open corrupt.db RDWR] + fconfigure $f -encoding binary + seek $f 16 start + puts -nonewline $f "\x00\xFF" + close $f + + sqlite3 db2 corrupt.db + catchsql " + $::presql + SELECT * FROM sqlite_master; + " db2 +} {1 {file is encrypted or is not a database}} + +do_test corrupt2-1.4 { + db2 close + + # Corrupt the free-block list on page 1. + forcedelete corrupt.db + forcedelete corrupt.db-journal + forcecopy test.db corrupt.db + set f [open corrupt.db RDWR] + fconfigure $f -encoding binary + seek $f 101 start + puts -nonewline $f "\xFF\xFF" + close $f + + sqlite3 db2 corrupt.db + catchsql " + $::presql + SELECT * FROM sqlite_master; + " db2 +} {1 {database disk image is malformed}} + +do_test corrupt2-1.5 { + db2 close + + # Corrupt the free-block list on page 1. + forcedelete corrupt.db + forcedelete corrupt.db-journal + forcecopy test.db corrupt.db + set f [open corrupt.db RDWR] + fconfigure $f -encoding binary + seek $f 101 start + puts -nonewline $f "\x00\xC8" + seek $f 200 start + puts -nonewline $f "\x00\x00" + puts -nonewline $f "\x10\x00" + close $f + + sqlite3 db2 corrupt.db + catchsql " + $::presql + SELECT * FROM sqlite_master; + " db2 +} {1 {database disk image is malformed}} +db2 close + +# Corrupt a database by having 2 indices of the same name: +do_test corrupt2-2.1 { + + forcedelete corrupt.db + forcedelete corrupt.db-journal + forcecopy test.db corrupt.db + + sqlite3 db2 corrupt.db + execsql " + $::presql + CREATE INDEX a1 ON abc(a); + CREATE INDEX a2 ON abc(b); + PRAGMA writable_schema = 1; + UPDATE sqlite_master + SET name = 'a3', sql = 'CREATE INDEX a3' || substr(sql, 16, 10000) + WHERE type = 'index'; + PRAGMA writable_schema = 0; + " db2 + + db2 close + sqlite3 db2 corrupt.db + catchsql " + $::presql + SELECT * FROM sqlite_master; + " db2 +} {1 {malformed database schema (a3) - index a3 already exists}} + +db2 close + +do_test corrupt2-3.1 { + forcedelete corrupt.db + forcedelete corrupt.db-journal + sqlite3 db2 corrupt.db + + execsql " + $::presql + PRAGMA auto_vacuum = 1; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(a, b, c); + INSERT INTO t2 VALUES(randomblob(100), randomblob(100), randomblob(100)); + INSERT INTO t2 SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t2; + " db2 + + db2 close + + # On the root page of table t2 (page 4), set one of the child page-numbers + # to 0. This corruption will be detected when SQLite attempts to update + # the pointer-map after moving the content of page 4 to page 3 as part + # of the DROP TABLE operation below. + # + set fd [open corrupt.db r+] + fconfigure $fd -encoding binary -translation binary + seek $fd [expr 1024*3 + 12] + set zCelloffset [read $fd 2] + binary scan $zCelloffset S iCelloffset + seek $fd [expr 1024*3 + $iCelloffset] + puts -nonewline $fd "\00\00\00\00" + close $fd + + sqlite3 db2 corrupt.db + catchsql " + $::presql + DROP TABLE t1; + " db2 +} {1 {database disk image is malformed}} + +do_test corrupt2-4.1 { + catchsql { + SELECT * FROM t2; + } db2 +} {1 {database disk image is malformed}} + +db2 close + +unset -nocomplain result +do_test corrupt2-5.1 { + forcedelete corrupt.db + forcedelete corrupt.db-journal + sqlite3 db2 corrupt.db + + execsql " + $::presql + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(a, b, c); + INSERT INTO t2 VALUES(randomblob(100), randomblob(100), randomblob(100)); + INSERT INTO t2 SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t2; + INSERT INTO t1 SELECT * FROM t2; + " db2 + + db2 close + + # This block links a page from table t2 into the t1 table structure. + # + set fd [open corrupt.db r+] + fconfigure $fd -encoding binary -translation binary + seek $fd [expr 1024 + 12] + set zCelloffset [read $fd 2] + binary scan $zCelloffset S iCelloffset + seek $fd [expr 1024 + $iCelloffset] + set zChildPage [read $fd 4] + seek $fd [expr 2*1024 + 12] + set zCelloffset [read $fd 2] + binary scan $zCelloffset S iCelloffset + seek $fd [expr 2*1024 + $iCelloffset] + puts -nonewline $fd $zChildPage + close $fd + + sqlite3 db2 corrupt.db + db2 eval $::presql + db2 eval {SELECT rowid FROM t1} { + set result [db2 eval {pragma integrity_check}] + break + } + set result +} {{*** in database main *** +On tree page 2 cell 0: 2nd reference to page 10 +On tree page 2 cell 1: Child page depth differs +Page 4 is never used}} + +db2 close + +proc corruption_test {args} { + set A(-corrupt) {} + set A(-sqlprep) {} + set A(-tclprep) {} + array set A $args + + catch {db close} + forcedelete corrupt.db + forcedelete corrupt.db-journal + + sqlite3 db corrupt.db + db eval $::presql + eval $A(-tclprep) + db eval $A(-sqlprep) + db close + + eval $A(-corrupt) + + sqlite3 db corrupt.db + eval $A(-test) +} + +ifcapable autovacuum { + # The tests within this block - corrupt2-6.* - aim to test corruption + # detection within an incremental-vacuum. When an incremental-vacuum + # step is executed, the last non-free page of the database file is + # moved into a free space in the body of the file. After doing so, + # the page reference in the parent page must be updated to refer + # to the new location. These tests test the outcome of corrupting + # that page reference before performing the incremental vacuum. + # + + # The last page in the database page is the second page + # in an overflow chain. + # + corruption_test -sqlprep { + PRAGMA auto_vacuum = incremental; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, randomblob(2500)); + INSERT INTO t1 VALUES(2, randomblob(2500)); + DELETE FROM t1 WHERE a = 1; + } -corrupt { + hexio_write corrupt.db [expr 1024*5] 00000008 + } -test { + do_test corrupt2-6.1 { + catchsql " $::presql pragma incremental_vacuum = 1 " + } {1 {database disk image is malformed}} + } + + # The last page in the database page is a non-root b-tree page. + # + corruption_test -sqlprep { + PRAGMA auto_vacuum = incremental; + PRAGMA page_size = 1024; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, randomblob(2500)); + INSERT INTO t1 VALUES(2, randomblob(50)); + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; + DELETE FROM t1 WHERE a = 1; + } -corrupt { + hexio_write corrupt.db [expr 1024*2 + 8] 00000009 + } -test { + do_test corrupt2-6.2 { + catchsql " $::presql pragma incremental_vacuum = 1 " + } {1 {database disk image is malformed}} + } + + # Set up a pointer-map entry so that the last page of the database + # file appears to be a b-tree root page. This should be detected + # as corruption. + # + corruption_test -sqlprep { + PRAGMA auto_vacuum = incremental; + PRAGMA page_size = 1024; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, randomblob(2500)); + INSERT INTO t1 VALUES(2, randomblob(2500)); + INSERT INTO t1 VALUES(3, randomblob(2500)); + DELETE FROM t1 WHERE a = 1; + } -corrupt { + set nPage [expr [file size corrupt.db] / 1024] + hexio_write corrupt.db [expr 1024 + ($nPage-3)*5] 010000000 + } -test { + do_test corrupt2-6.3 { + catchsql " $::presql pragma incremental_vacuum = 1 " + } {1 {database disk image is malformed}} + } + + corruption_test -sqlprep { + PRAGMA auto_vacuum = 1; + PRAGMA page_size = 1024; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, randomblob(2500)); + DELETE FROM t1 WHERE a = 1; + } -corrupt { + set nAppend [expr 1024*207 - [file size corrupt.db]] + set fd [open corrupt.db r+] + seek $fd 0 end + puts -nonewline $fd [string repeat x $nAppend] + close $fd + hexio_write corrupt.db 28 00000000 + } -test { + do_test corrupt2-6.4 { + catchsql " + $::presql + BEGIN EXCLUSIVE; + COMMIT; + " + } {1 {database disk image is malformed}} + } +} + + +set sqlprep { + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 1024; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + CREATE INDEX i1 ON t1(b); + INSERT INTO t1 VALUES(1, randomblob(50)); + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; + INSERT INTO t1 SELECT NULL, randomblob(50) FROM t1; +} + +corruption_test -sqlprep $sqlprep -corrupt { + # Set the page-flags of one of the leaf pages of the index B-Tree to + # 0x0D (interpreted by SQLite as "leaf page of a table B-Tree"). + # + set fd [open corrupt.db r+] + fconfigure $fd -translation binary -encoding binary + seek $fd [expr 1024*2 + 8] + set zRightChild [read $fd 4] + binary scan $zRightChild I iRightChild + seek $fd [expr 1024*($iRightChild-1)] + puts -nonewline $fd "\x0D" + close $fd +} -test { + do_test corrupt2-7.1 { + catchsql " $::presql SELECT b FROM t1 ORDER BY b ASC " + } {1 {database disk image is malformed}} +} + +corruption_test -sqlprep $sqlprep -corrupt { + # Mess up the page-header of one of the leaf pages of the index B-Tree. + # The corruption is detected as part of an OP_Prev opcode. + # + set fd [open corrupt.db r+] + fconfigure $fd -translation binary -encoding binary + seek $fd [expr 1024*2 + 12] + set zCellOffset [read $fd 2] + binary scan $zCellOffset S iCellOffset + seek $fd [expr 1024*2 + $iCellOffset] + set zChild [read $fd 4] + binary scan $zChild I iChild + seek $fd [expr 1024*($iChild-1)+3] + puts -nonewline $fd "\xFFFF" + close $fd +} -test { + do_test corrupt2-7.1 { + catchsql " $::presql SELECT b FROM t1 ORDER BY b DESC " + } {1 {database disk image is malformed}} +} + +corruption_test -sqlprep $sqlprep -corrupt { + # Set the page-flags of one of the leaf pages of the table B-Tree to + # 0x0A (interpreted by SQLite as "leaf page of an index B-Tree"). + # + set fd [open corrupt.db r+] + fconfigure $fd -translation binary -encoding binary + seek $fd [expr 1024*1 + 8] + set zRightChild [read $fd 4] + binary scan $zRightChild I iRightChild + seek $fd [expr 1024*($iRightChild-1)] + puts -nonewline $fd "\x0A" + close $fd +} -test { + do_test corrupt2-8.1 { + catchsql " $::presql SELECT * FROM t1 WHERE rowid=1000 " + } {1 {database disk image is malformed}} +} + +corruption_test -sqlprep { + CREATE TABLE t1(a, b, c); CREATE TABLE t8(a, b, c); CREATE TABLE tE(a, b, c); + CREATE TABLE t2(a, b, c); CREATE TABLE t9(a, b, c); CREATE TABLE tF(a, b, c); + CREATE TABLE t3(a, b, c); CREATE TABLE tA(a, b, c); CREATE TABLE tG(a, b, c); + CREATE TABLE t4(a, b, c); CREATE TABLE tB(a, b, c); CREATE TABLE tH(a, b, c); + CREATE TABLE t5(a, b, c); CREATE TABLE tC(a, b, c); CREATE TABLE tI(a, b, c); + CREATE TABLE t6(a, b, c); CREATE TABLE tD(a, b, c); CREATE TABLE tJ(a, b, c); + CREATE TABLE x1(a, b, c); CREATE TABLE x8(a, b, c); CREATE TABLE xE(a, b, c); + CREATE TABLE x2(a, b, c); CREATE TABLE x9(a, b, c); CREATE TABLE xF(a, b, c); + CREATE TABLE x3(a, b, c); CREATE TABLE xA(a, b, c); CREATE TABLE xG(a, b, c); + CREATE TABLE x4(a, b, c); CREATE TABLE xB(a, b, c); CREATE TABLE xH(a, b, c); + CREATE TABLE x5(a, b, c); CREATE TABLE xC(a, b, c); CREATE TABLE xI(a, b, c); + CREATE TABLE x6(a, b, c); CREATE TABLE xD(a, b, c); CREATE TABLE xJ(a, b, c); +} -corrupt { + set fd [open corrupt.db r+] + fconfigure $fd -translation binary -encoding binary + seek $fd 108 + set zRightChild [read $fd 4] + binary scan $zRightChild I iRightChild + seek $fd [expr 1024*($iRightChild-1)+3] + puts -nonewline $fd "\x00\x00" + close $fd +} -test { + do_test corrupt2-9.1 { + catchsql " $::presql SELECT sql FROM sqlite_master " + } {1 {database disk image is malformed}} +} + +corruption_test -sqlprep { + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(a, b, c); + PRAGMA writable_schema = 1; + UPDATE sqlite_master SET rootpage = NULL WHERE name = 't2'; +} -test { + do_test corrupt2-10.1 { + catchsql " $::presql SELECT * FROM t2 " + } {1 {malformed database schema (t2)}} + do_test corrupt2-10.2 { + sqlite3_errcode db + } {SQLITE_CORRUPT} +} + +corruption_test -sqlprep { + PRAGMA auto_vacuum = incremental; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + CREATE TABLE t2(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, randstr(100,100)); + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t2 SELECT * FROM t1; + DELETE FROM t1; +} -corrupt { + set offset [expr [file size corrupt.db] - 1024] + hexio_write corrupt.db $offset FF + hexio_write corrupt.db 24 12345678 +} -test { + do_test corrupt2-11.1 { + catchsql " $::presql PRAGMA incremental_vacuum " + } {1 {database disk image is malformed}} +} +corruption_test -sqlprep { + PRAGMA auto_vacuum = incremental; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + CREATE TABLE t2(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, randstr(100,100)); + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t1 SELECT NULL, randstr(100,100) FROM t1; + INSERT INTO t2 SELECT * FROM t1; + DELETE FROM t1; +} -corrupt { + set pgno [expr [file size corrupt.db] / 1024] + hexio_write corrupt.db [expr 1024+5*($pgno-3)] 03 + hexio_write corrupt.db 24 12345678 +} -test { + do_test corrupt2-12.1 { + catchsql " $::presql PRAGMA incremental_vacuum " + } {1 {database disk image is malformed}} +} + +ifcapable autovacuum { + # It is not possible for the last page in a database file to be the + # pending-byte page (AKA the locking page). This test verifies that if + # an attempt is made to commit a transaction to such an auto-vacuum + # database SQLITE_CORRUPT is returned. + # + corruption_test -tclprep { + db eval { + PRAGMA auto_vacuum = full; + PRAGMA page_size = 1024; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(NULL, randstr(50,50)); + } + for {set ii 0} {$ii < 10} {incr ii} { + db eval " $::presql INSERT INTO t1 SELECT NULL, randstr(50,50) FROM t1 " + } + } -corrupt { + do_test corrupt2-13.1 { + file size corrupt.db + } $::sqlite_pending_byte + hexio_write corrupt.db [expr $::sqlite_pending_byte+1023] 00 + hexio_write corrupt.db 28 00000000 + } -test { + do_test corrupt2-13.2 { + file size corrupt.db + } [expr $::sqlite_pending_byte + 1024] + do_test corrupt2-13.3 { + catchsql { DELETE FROM t1 WHERE rowid < 30; } + } {1 {database disk image is malformed}} + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corrupt3.test b/components/external/SQLite-3.8.1/test/corrupt3.test new file mode 100644 index 0000000000000000000000000000000000000000..a3827227b7f4346a21fd9650e0f4fe6cf209e3ec --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corrupt3.test @@ -0,0 +1,114 @@ +# 2007 April 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. +# +# $Id: corrupt3.test,v 1.2 2007/04/06 21:42:22 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# We must have the page_size pragma for these tests to work. +# +ifcapable !pager_pragmas||direct_read { + finish_test + return +} + +# Create a database with an overflow page. +# +do_test corrupt3-1.1 { + set bigstring [string repeat 0123456789 200] + execsql { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size=1024; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES($bigstring); + } + file size test.db +} [expr {1024*3}] + +# Verify that the file format is as we expect. The page size +# should be 1024 bytes. The only record should have a single +# overflow page. The overflow page is page 3. The pointer to +# the overflow page is on the last 4 bytes of page 2. +# +do_test corrupt3-1.2 { + hexio_get_int [hexio_read test.db 16 2] +} 1024 ;# The page size is 1024 +do_test corrupt3-1.3 { + hexio_get_int [hexio_read test.db 20 1] +} 0 ;# Unused bytes per page is 0 +do_test corrupt3-1.4 { + hexio_get_int [hexio_read test.db 2044 4] +} 3 ;# Overflow page is 3 +do_test corrupt3-1.5 { + hexio_get_int [hexio_read test.db 2048 4] +} 0 ;# First chained overflow is 0 + +integrity_check corrupt3-1.6 + +# Make the overflow chain loop back on itself. See if the +# corruption is detected. (Actually, the last pointer in +# an overflow chain is ignored, so this is not an error.) +# +do_test corrupt3-1.7 { + db close + hexio_write test.db 2048 [hexio_render_int32 3] + sqlite3 db test.db + catchsql { + SELECT x FROM t1 + } +} [list 0 $bigstring] +integrity_check corrupt3-1.8 + +# Change the pointer for the first page of the overflow +# change to be a non-existant page. +# +do_test corrupt3-1.9 { + db close + hexio_write test.db 2044 [hexio_render_int32 4] + sqlite3 db test.db + catchsql { + SELECT substr(x,1,10) FROM t1 + } +} [list 0 0123456789] +do_test corrupt3-1.10 { + catchsql { + PRAGMA integrity_check + } +} {0 {{*** in database main *** +On tree page 2 cell 0: invalid page number 4 +Page 3 is never used}}} +do_test corrupt3-1.11 { + db close + hexio_write test.db 2044 [hexio_render_int32 0] + sqlite3 db test.db + catchsql { + SELECT substr(x,1,10) FROM t1 + } +} [list 1 {database disk image is malformed}] +do_test corrupt3-1.12 { + catchsql { + PRAGMA integrity_check + } +} {0 {{*** in database main *** +On tree page 2 cell 0: 1 of 1 pages missing from overflow list starting at 0 +Page 3 is never used}}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corrupt4.test b/components/external/SQLite-3.8.1/test/corrupt4.test new file mode 100644 index 0000000000000000000000000000000000000000..19061134f6563b0315f02016158f6523b69acc1b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corrupt4.test @@ -0,0 +1,79 @@ +# 2007 Sept 7 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. +# +# $Id: corrupt4.test,v 1.1 2007/09/07 14:32:07 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# We must have the page_size pragma for these tests to work. +# +ifcapable !pager_pragmas { + finish_test + return +} + +# Create a database with a freelist containing at least two pages. +# +do_test corrupt4-1.1 { + set bigstring [string repeat 0123456789 200] + execsql { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size=1024; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES($bigstring); + CREATE TABLE t2(y); + INSERT INTO t2 VALUES(1); + DROP TABLE t1; + } + file size test.db +} [expr {1024*4}] + +# Verify that there are two pages on the freelist. +# +do_test corrupt4-1.2 { + execsql {PRAGMA freelist_count} +} {2} + +# Get the page number for the trunk of the freelist. +# +set trunkpgno [hexio_get_int [hexio_read test.db 32 4]] +set baseaddr [expr {($trunkpgno-1)*1024}] + +# Verify that the trunk of the freelist has exactly one +# leaf. +# +do_test corrupt4-1.3 { + hexio_get_int [hexio_read test.db [expr {$::baseaddr+4}] 4] +} {1} + +# Insert a negative number as the number of leaves on the trunk. +# Then try to add a new element to the freelist. +# +do_test corrupt4-1.4 { + hexio_write test.db [expr {$::baseaddr+4}] [hexio_render_int32 -100000000] + db close + sqlite3 db test.db + catchsql { + DROP TABLE t2 + } +} {1 {database disk image is malformed}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corrupt5.test b/components/external/SQLite-3.8.1/test/corrupt5.test new file mode 100644 index 0000000000000000000000000000000000000000..dca06e5fec25fbba22a229e39c61268fb848a958 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corrupt5.test @@ -0,0 +1,45 @@ +# 2008 Jan 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. Checks for +# malformed schema. +# +# $Id: corrupt5.test,v 1.3 2009/06/04 02:47:04 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# We must have the page_size pragma for these tests to work. +# +ifcapable !pager_pragmas { + finish_test + return +} + +# Create a database with a freelist containing at least two pages. +# +do_test corrupt5-1.1 { + execsql { + CREATE TABLE t1(a,b,c); + CREATE INDEX i1 ON t1(a,b); + PRAGMA writable_schema=ON; + UPDATE sqlite_master SET name=NULL, sql=NULL WHERE name='i1'; + } + db close + sqlite3 db test.db + catchsql { + SELECT * FROM t1 + } +} {1 {malformed database schema (?)}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corrupt6.test b/components/external/SQLite-3.8.1/test/corrupt6.test new file mode 100644 index 0000000000000000000000000000000000000000..c0dcedf3d9f66d5157861197571de2aaa4357135 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corrupt6.test @@ -0,0 +1,256 @@ +# 2008 May 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. It specifically focuses +# on corrupt SerialTypeLen values. +# +# $Id: corrupt6.test,v 1.2 2008/05/19 15:37:10 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# We must have the page_size pragma for these tests to work. +# +ifcapable !pager_pragmas { + finish_test + return +} + +# Create a simple, small database. +# +do_test corrupt6-1.1 { + execsql { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size=1024; + CREATE TABLE t1(x); + INSERT INTO t1(x) VALUES('varint32-01234567890123456789012345678901234567890123456789'); + INSERT INTO t1(x) VALUES('varint32-01234567890123456789012345678901234567890123456789'); + } + file size test.db +} [expr {1024*2}] + +# Verify that the file format is as we expect. The page size +# should be 1024 bytes. +# +do_test corrupt6-1.2 { + hexio_get_int [hexio_read test.db 16 2] +} 1024 ;# The page size is 1024 +do_test corrupt6-1.3 { + hexio_get_int [hexio_read test.db 20 1] +} 0 ;# Unused bytes per page is 0 + +integrity_check corrupt6-1.4 + +# Verify SerialTypeLen for first field of two records as we expect. +# SerialTypeLen = (len*2+12) = 60*2+12 = 132 +do_test corrupt6-1.5.1 { + hexio_read test.db 1923 2 +} 8103 ;# First text field size is 81 03 == 131 +do_test corrupt6-1.5.2 { + hexio_read test.db 1987 2 +} 8103 ;# Second text field size is 81 03 == 131 + +# Verify simple query results as expected. +do_test corrupt6-1.6 { + db close + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 0 {varint32 varint32} ] +integrity_check corrupt6-1.7 + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Increase SerialTypeLen by 2. +do_test corrupt6-1.8.1 { + db close + hexio_write test.db 1923 8105 + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Decrease SerialTypeLen by 2. +do_test corrupt6-1.8.2 { + db close + hexio_write test.db 1923 8101 + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Put value of record 1 / field 1 SerialTypeLen back. +do_test corrupt6-1.8.3 { + db close + hexio_write test.db 1923 8103 + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 0 {varint32 varint32} ] +integrity_check corrupt6-1.8.4 + +# Adjust value of record 2 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Increase SerialTypeLen by 2. +do_test corrupt6-1.9.1 { + db close + hexio_write test.db 1987 8105 + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 2 / field 2 SerialTypeLen and see if the +# corruption is detected. +# Decrease SerialTypeLen by 2. +do_test corrupt6-1.9.2 { + db close + hexio_write test.db 1987 8101 + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Put value of record 1 / field 2 SerialTypeLen back. +do_test corrupt6-1.9.3 { + db close + hexio_write test.db 1987 8103 + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 0 {varint32 varint32} ] +integrity_check corrupt6-1.9.4 + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Set SerialTypeLen to FF 7F (2 bytes) +do_test corrupt6-1.10.1 { + db close + hexio_write test.db 1923 FF7F + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Set SerialTypeLen to FF FF 7F (3 bytes) +do_test corrupt6-1.10.2 { + db close + hexio_write test.db 1923 FFFF7F + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Set SerialTypeLen to FF FF FF 7F (4 bytes) +do_test corrupt6-1.10.3 { + db close + hexio_write test.db 1923 FFFFFF7F + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Set SerialTypeLen to FF FF FF FF 7F (5 bytes) +do_test corrupt6-1.10.4 { + db close + hexio_write test.db 1923 FFFFFFFF7F + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Set SerialTypeLen to FF FF FF FF FF 7F (6 bytes, and overflows). +do_test corrupt6-1.10.5 { + db close + hexio_write test.db 1923 FFFFFFFFFF7F + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Set SerialTypeLen to FF FF FF FF FF FF 7F (7 bytes, and overflows). +do_test corrupt6-1.10.6 { + db close + hexio_write test.db 1923 FFFFFFFFFFFF7F + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Set SerialTypeLen to FF FF FF FF FF FF FF 7F (8 bytes, and overflows). +do_test corrupt6-1.10.7 { + db close + hexio_write test.db 1923 FFFFFFFFFFFFFF7F + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Set SerialTypeLen to FF FF FF FF FF FF FF FF 7F (9 bytes, and overflows). +do_test corrupt6-1.10.8 { + db close + hexio_write test.db 1923 FFFFFFFFFFFFFFFF7F + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +# Adjust value of record 1 / field 1 SerialTypeLen and see if the +# corruption is detected. +# Set SerialTypeLen to FFFF FF FF FF FF FF FF FF 7F (10 bytes, and overflows). +do_test corrupt6-1.10.9 { + db close + hexio_write test.db 1923 FFFFFFFFFFFFFFFFFF7F + sqlite3 db test.db + catchsql { + SELECT substr(x,1,8) FROM t1 + } +} [list 1 {database disk image is malformed}] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corrupt7.test b/components/external/SQLite-3.8.1/test/corrupt7.test new file mode 100644 index 0000000000000000000000000000000000000000..ad566560f7ff811e9979eba0f2e8149034d1468c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corrupt7.test @@ -0,0 +1,130 @@ +# 2008 June 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. It specifically focuses +# on corrupt cell offsets in a btree page. +# +# $Id: corrupt7.test,v 1.8 2009/08/10 10:18:08 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# We must have the page_size pragma for these tests to work. +# +ifcapable !pager_pragmas { + finish_test + return +} + +# Create a simple, small database. +# +do_test corrupt7-1.1 { + execsql { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size=1024; + CREATE TABLE t1(x); + INSERT INTO t1(x) VALUES(1); + INSERT INTO t1(x) VALUES(2); + INSERT INTO t1(x) SELECT x+2 FROM t1; + INSERT INTO t1(x) SELECT x+4 FROM t1; + INSERT INTO t1(x) SELECT x+8 FROM t1; + } + file size test.db +} [expr {1024*2}] + +# Verify that the file format is as we expect. The page size +# should be 1024 bytes. +# +do_test corrupt7-1.2 { + hexio_get_int [hexio_read test.db 16 2] +} 1024 ;# The page size is 1024 +do_test corrupt7-1.3 { + hexio_get_int [hexio_read test.db 20 1] +} 0 ;# Unused bytes per page is 0 + +integrity_check corrupt7-1.4 + +# Deliberately corrupt some of the cell offsets in the btree page +# on page 2 of the database. +# +# The error message is different depending on whether or not the +# SQLITE_ENABLE_OVERSIZE_CELL_CHECK compile-time option is engaged. +# +ifcapable oversize_cell_check { + do_test corrupt7-2.1 { + db close + hexio_write test.db 1062 FF + sqlite3 db test.db + db eval {PRAGMA integrity_check(1)} + } {{*** in database main *** +Page 2: btreeInitPage() returns error code 11}} + do_test corrupt7-2.2 { + db close + hexio_write test.db 1062 04 + sqlite3 db test.db + db eval {PRAGMA integrity_check(1)} + } {{*** in database main *** +Page 2: btreeInitPage() returns error code 11}} +} else { + do_test corrupt7-2.1 { + db close + hexio_write test.db 1062 FF + sqlite3 db test.db + db eval {PRAGMA integrity_check(1)} + } {{*** in database main *** +Corruption detected in cell 15 on page 2}} + do_test corrupt7-2.2 { + db close + hexio_write test.db 1062 04 + sqlite3 db test.db + db eval {PRAGMA integrity_check(1)} + } {{*** in database main *** +On tree page 2 cell 15: Rowid 0 out of order (previous was 15)}} +} + +# The code path that was causing the buffer overrun that this test +# case was checking for was removed. +# +#do_test corrupt7-3.1 { +# execsql { +# DROP TABLE t1; +# CREATE TABLE t1(a, b); +# INSERT INTO t1 VALUES(1, 'one'); +# INSERT INTO t1 VALUES(100, 'one hundred'); +# INSERT INTO t1 VALUES(100000, 'one hundred thousand'); +# CREATE INDEX i1 ON t1(b); +# } +# db close +# +# # Locate the 3rd cell in the index. +# set cell_offset [hexio_get_int [hexio_read test.db [expr 1024*2 + 12] 2]] +# incr cell_offset [expr 1024*2] +# incr cell_offset 1 +# +# # This write corrupts the "header-size" field of the database record +# # stored in the index cell. At one point this was causing sqlite to +# # reference invalid memory. +# hexio_write test.db $cell_offset FFFF7F +# +# sqlite3 db test.db +# catchsql { +# SELECT b FROM t1 WHERE b > 'o' AND b < 'p'; +# } +#} {1 {database disk image is malformed}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corrupt8.test b/components/external/SQLite-3.8.1/test/corrupt8.test new file mode 100644 index 0000000000000000000000000000000000000000..012beb562e40e15db4b6c68a31328e8d7dae8262 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corrupt8.test @@ -0,0 +1,104 @@ +# 2008 July 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. It specifically focuses +# on corrupt pointer map pages. +# +# $Id: corrupt8.test,v 1.2 2008/07/11 03:34:10 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# We must have the page_size pragma for these tests to work. +# +ifcapable !pager_pragmas||!autovacuum { + finish_test + return +} + +# Create a database to work with. +# +do_test corrupt8-1.1 { + execsql { + PRAGMA auto_vacuum=1; + PRAGMA page_size=1024; + CREATE TABLE t1(x); + INSERT INTO t1(x) VALUES(1); + INSERT INTO t1(x) VALUES(2); + INSERT INTO t1(x) SELECT x+2 FROM t1; + INSERT INTO t1(x) SELECT x+4 FROM t1; + INSERT INTO t1(x) SELECT x+8 FROM t1; + INSERT INTO t1(x) SELECT x+16 FROM t1; + INSERT INTO t1(x) SELECT x+32 FROM t1; + INSERT INTO t1(x) SELECT x+64 FROM t1; + INSERT INTO t1(x) SELECT x+128 FROM t1; + INSERT INTO t1(x) SELECT x+256 FROM t1; + CREATE TABLE t2(a,b); + INSERT INTO t2 SELECT x, x*x FROM t1; + } + expr {[file size test.db]>1024*12} +} {1} +integrity_check corrupt8-1.2 + +# Loop through each ptrmap entry. Corrupt the entry and make sure the +# corruption is detected by the integrity_check. +# +for {set i 1024} {$i<2048} {incr i 5} { + set oldval [hexio_read test.db $i 1] + if {$oldval==0} break + hexio_write test.db $i 00 + do_test corrupt8-2.$i.0 { + db close + sqlite3 db test.db + set x [db eval {PRAGMA integrity_check}] + expr {$x!="ok"} + } {1} + for {set k 1} {$k<=5} {incr k} { + if {$k==$oldval} continue + hexio_write test.db $i 0$k + do_test corrupt8-2.$i.$k { + db close + sqlite3 db test.db + set x [db eval {PRAGMA integrity_check}] + expr {$x!="ok"} + } {1} + } + hexio_write test.db $i 06 + do_test corrupt8-2.$i.6 { + db close + sqlite3 db test.db + set x [db eval {PRAGMA integrity_check}] + expr {$x!="ok"} + } {1} + hexio_write test.db $i $oldval + if {$oldval>2} { + set i2 [expr {$i+1+$i%4}] + set oldval [hexio_read test.db $i2 1] + hexio_write test.db $i2 [format %02x [expr {($oldval+1)&0xff}]] + do_test corrupt8-2.$i.7 { + db close + sqlite3 db test.db + set x [db eval {PRAGMA integrity_check}] + expr {$x!="ok"} + } {1} + hexio_write test.db $i2 $oldval + } +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corrupt9.test b/components/external/SQLite-3.8.1/test/corrupt9.test new file mode 100644 index 0000000000000000000000000000000000000000..f199452f958a207efb77002f739d0b66fd00a940 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corrupt9.test @@ -0,0 +1,136 @@ +# 2008 July 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. It specifically focuses +# on corruption in the form of duplicate entries on the freelist. +# +# $Id: corrupt9.test,v 1.3 2009/06/04 02:47:04 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# We must have the page_size pragma for these tests to work. +# +ifcapable !pager_pragmas { + finish_test + return +} + +# Return the offset to the first (trunk) page of the freelist. Return +# zero of the freelist is empty. +# +proc freelist_trunk_offset {filename} { + if {[hexio_read $filename 36 4]==0} {return 0} + set pgno [hexio_get_int [hexio_read $filename 32 4]] + return [expr {($pgno-1)*[hexio_get_int [hexio_read $filename 16 2]]}] +} + +# This procedure looks at the first trunk page of the freelist and +# corrupts that page by overwriting up to N entries with duplicates +# of the first entry. +# +proc corrupt_freelist {filename N} { + set offset [freelist_trunk_offset $filename] + if {$offset==0} {error "Freelist is empty"} + set cnt [hexio_get_int [hexio_read $filename [expr {$offset+4}] 4]] + set pgno [hexio_read $filename [expr {$offset+8}] 4] + for {set i 12} {$N>0 && $i<8+4*$cnt} {incr i 4; incr N -1} { + hexio_write $filename [expr {$offset+$i}] $pgno + } +} + +# Create a database to work with. Make sure there are plenty of +# entries on the freelist. +# +do_test corrupt9-1.1 { + execsql { + PRAGMA auto_vacuum=NONE; + PRAGMA page_size=1024; + CREATE TABLE t1(x); + INSERT INTO t1(x) VALUES(1); + INSERT INTO t1(x) VALUES(2); + INSERT INTO t1(x) SELECT x+2 FROM t1; + INSERT INTO t1(x) SELECT x+4 FROM t1; + INSERT INTO t1(x) SELECT x+8 FROM t1; + INSERT INTO t1(x) SELECT x+16 FROM t1; + INSERT INTO t1(x) SELECT x+32 FROM t1; + INSERT INTO t1(x) SELECT x+64 FROM t1; + INSERT INTO t1(x) SELECT x+128 FROM t1; + INSERT INTO t1(x) SELECT x+256 FROM t1; + CREATE TABLE t2(a,b); + INSERT INTO t2 SELECT x, x*x FROM t1; + CREATE INDEX i1 ON t1(x); + CREATE INDEX i2 ON t2(b,a); + DROP INDEX i2; + } + expr {[file size test.db]>1024*24} +} {1} +integrity_check corrupt9-1.2 + +# Corrupt the freelist by adding duplicate entries to the freelist. +# Make sure the corruption is detected. +# +db close +forcecopy test.db test.db-template + +corrupt_freelist test.db 1 +sqlite3 db test.db +do_test corrupt9-2.1 { + set x [db eval {PRAGMA integrity_check}] + expr {$x!="ok"} +} {1} +do_test corrupt9-2.2 { + catchsql { + CREATE INDEX i2 ON t2(b,a); + REINDEX; + } +} {1 {database disk image is malformed}} + + +db close +forcecopy test.db-template test.db +corrupt_freelist test.db 2 +sqlite3 db test.db +do_test corrupt9-3.1 { + set x [db eval {PRAGMA integrity_check}] + expr {$x!="ok"} +} {1} +do_test corrupt9-3.2 { + catchsql { + CREATE INDEX i2 ON t2(b,a); + REINDEX; + } +} {1 {database disk image is malformed}} + +db close +forcecopy test.db-template test.db +corrupt_freelist test.db 3 +sqlite3 db test.db +do_test corrupt9-4.1 { + set x [db eval {PRAGMA integrity_check}] + expr {$x!="ok"} +} {1} +do_test corrupt9-4.2 { + catchsql { + CREATE INDEX i2 ON t2(b,a); + REINDEX; + } +} {1 {database disk image is malformed}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corruptA.test b/components/external/SQLite-3.8.1/test/corruptA.test new file mode 100644 index 0000000000000000000000000000000000000000..8b76d3a201f74e53c2e66e90d29213e892bd98ba --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corruptA.test @@ -0,0 +1,79 @@ +# 2008 July 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. It specifically focuses +# on corrupt database headers. +# +# $Id: corruptA.test,v 1.1 2008/07/11 16:39:23 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + + +# Create a database to work with. +# +do_test corruptA-1.1 { + execsql { + CREATE TABLE t1(x); + INSERT INTO t1(x) VALUES(1); + } + expr {[file size test.db]>=1024} +} {1} +integrity_check corruptA-1.2 + +# Corrupt the file header in various ways and make sure the corruption +# is detected when opening the database file. +# +db close +forcecopy test.db test.db-template + +set unreadable_version 02 +ifcapable wal { set unreadable_version 03 } +do_test corruptA-2.1 { + forcecopy test.db-template test.db + hexio_write test.db 19 $unreadable_version ;# the read format number + sqlite3 db test.db + catchsql {SELECT * FROM t1} +} {1 {file is encrypted or is not a database}} + +do_test corruptA-2.2 { + db close + forcecopy test.db-template test.db + hexio_write test.db 21 41 ;# max embedded payload fraction + sqlite3 db test.db + catchsql {SELECT * FROM t1} +} {1 {file is encrypted or is not a database}} + +do_test corruptA-2.3 { + db close + forcecopy test.db-template test.db + hexio_write test.db 22 1f ;# min embedded payload fraction + sqlite3 db test.db + catchsql {SELECT * FROM t1} +} {1 {file is encrypted or is not a database}} + +do_test corruptA-2.4 { + db close + forcecopy test.db-template test.db + hexio_write test.db 23 21 ;# min leaf payload fraction + sqlite3 db test.db + catchsql {SELECT * FROM t1} +} {1 {file is encrypted or is not a database}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corruptB.test b/components/external/SQLite-3.8.1/test/corruptB.test new file mode 100644 index 0000000000000000000000000000000000000000..0ff2d6e9e03046b8b97953733af87afab3f4bb90 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corruptB.test @@ -0,0 +1,189 @@ +# 2008 Sep 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. It specifically focuses +# on loops in the B-Tree structure. A loop is formed in a B-Tree structure +# when there exists a page that is both an a descendent or ancestor of +# itself. +# +# Also test that an SQLITE_CORRUPT error is returned if a B-Tree page +# contains a (corrupt) reference to a page greater than the configured +# maximum page number. +# +# $Id: corruptB.test,v 1.4 2009/07/21 19:25:24 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + + +do_test corruptB-1.1 { + execsql { + PRAGMA auto_vacuum = 1; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(200)); + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + } + expr {[file size test.db] > (1024*9)} +} {1} +integrity_check corruptB-1.2 + +forcecopy test.db bak.db + +# Set the right-child of a B-Tree rootpage to refer to the root-page itself. +# +do_test corruptB-1.3.1 { + set ::root [execsql {SELECT rootpage FROM sqlite_master}] + set ::offset [expr {($::root-1)*1024}] + hexio_write test.db [expr $offset+8] [hexio_render_int32 $::root] +} {4} +do_test corruptB-1.3.2 { + sqlite3 db test.db + catchsql { SELECT * FROM t1 } +} {1 {database disk image is malformed}} + +# Set the left-child of a cell in a B-Tree rootpage to refer to the +# root-page itself. +# +do_test corruptB-1.4.1 { + db close + forcecopy bak.db test.db + set cell_offset [hexio_get_int [hexio_read test.db [expr $offset+12] 2]] + hexio_write test.db [expr $offset+$cell_offset] [hexio_render_int32 $::root] +} {4} +do_test corruptB-1.4.2 { + sqlite3 db test.db + catchsql { SELECT * FROM t1 } +} {1 {database disk image is malformed}} + +# Now grow the table B-Tree so that it is more than 2 levels high. +# +do_test corruptB-1.5.1 { + db close + forcecopy bak.db test.db + sqlite3 db test.db + execsql { + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + } +} {} + +forcecopy test.db bak.db + +# Set the right-child pointer of the right-child of the root page to point +# back to the root page. +# +do_test corruptB-1.6.1 { + db close + set iRightChild [hexio_get_int [hexio_read test.db [expr $offset+8] 4]] + set c_offset [expr ($iRightChild-1)*1024] + hexio_write test.db [expr $c_offset+8] [hexio_render_int32 $::root] +} {4} +do_test corruptB-1.6.2 { + sqlite3 db test.db + catchsql { SELECT * FROM t1 } +} {1 {database disk image is malformed}} + +# Set the left-child pointer of a cell of the right-child of the root page to +# point back to the root page. +# +do_test corruptB-1.7.1 { + db close + forcecopy bak.db test.db + set cell_offset [hexio_get_int [hexio_read test.db [expr $c_offset+12] 2]] + hexio_write test.db [expr $c_offset+$cell_offset] [hexio_render_int32 $::root] +} {4} +do_test corruptB-1.7.2 { + sqlite3 db test.db + catchsql { SELECT * FROM t1 } +} {1 {database disk image is malformed}} + +do_test corruptB-1.8.1 { + db close + set cell_offset [hexio_get_int [hexio_read test.db [expr $offset+12] 2]] + set iLeftChild [ + hexio_get_int [hexio_read test.db [expr $offset+$cell_offset] 4] + ] + set c_offset [expr ($iLeftChild-1)*1024] + hexio_write test.db [expr $c_offset+8] [hexio_render_int32 $::root] +} {4} +do_test corruptB-1.8.2 { + sqlite3 db test.db + catchsql { SELECT * FROM t1 } +} {1 {database disk image is malformed}} + +# Set the left-child pointer of a cell of the right-child of the root page to +# point back to the root page. +# +do_test corruptB-1.9.1 { + db close + forcecopy bak.db test.db + set cell_offset [hexio_get_int [hexio_read test.db [expr $c_offset+12] 2]] + hexio_write test.db [expr $c_offset+$cell_offset] [hexio_render_int32 $::root] +} {4} +do_test corruptB-1.9.2 { + sqlite3 db test.db + catchsql { SELECT * FROM t1 } +} {1 {database disk image is malformed}} + +#--------------------------------------------------------------------------- + +do_test corruptB-2.1.1 { + db close + forcecopy bak.db test.db + hexio_write test.db [expr $offset+8] [hexio_render_int32 0x6FFFFFFF] +} {4} +do_test corruptB-2.1.2 { + sqlite3 db test.db + catchsql { SELECT * FROM t1 } +} {1 {database disk image is malformed}} + +#--------------------------------------------------------------------------- + +# Corrupt the header-size field of a database record. +# +do_test corruptB-3.1.1 { + db close + forcecopy bak.db test.db + sqlite3 db test.db + set v [string repeat abcdefghij 200] + execsql { + CREATE TABLE t2(a); + INSERT INTO t2 VALUES($v); + } + set t2_root [execsql {SELECT rootpage FROM sqlite_master WHERE name = 't2'}] + set iPage [expr ($t2_root-1)*1024] + set iCellarray [expr $iPage + 8] + set iRecord [hexio_get_int [hexio_read test.db $iCellarray 2]] + db close + hexio_write test.db [expr $iPage+$iRecord+3] FF00 +} {2} +do_test corruptB-3.1.2 { + sqlite3 db test.db + catchsql { SELECT * FROM t2 } +} {1 {database disk image is malformed}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corruptC.test b/components/external/SQLite-3.8.1/test/corruptC.test new file mode 100644 index 0000000000000000000000000000000000000000..34e81a1be81f1bdec9ab4480937494ac237b36ce --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corruptC.test @@ -0,0 +1,407 @@ +# 2004 August 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. It creates a base +# data base file, then tests that single byte corruptions in +# increasingly larger quantities are handled gracefully. +# +# $Id: corruptC.test,v 1.14 2009/07/11 06:55:34 danielk1977 Exp $ + +catch {forcedelete test.db test.db-journal test.bu} + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Construct a compact, dense database for testing. +# +do_test corruptC-1.1 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA legacy_file_format=1; + BEGIN; + CREATE TABLE t1(x,y); + INSERT INTO t1 VALUES(1,1); + INSERT OR IGNORE INTO t1 SELECT x*2,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*3,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*5,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*7,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*11,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*13,y FROM t1; + CREATE INDEX t1i1 ON t1(x); + CREATE TABLE t2 AS SELECT x,2 as y FROM t1 WHERE rowid%5!=0; + COMMIT; + } +} {} + +ifcapable {integrityck} { + integrity_check corruptC-1.2 +} + +# Generate random integer +# +proc random {range} { + return [expr {round(rand()*$range)}] +} + +# Setup for the tests. Make a backup copy of the good database in test.bu. +# +db close +forcecopy test.db test.bu +sqlite3 db test.db +set fsize [file size test.db] + +# Set a quasi-random random seed. +if {[info exists ::G(issoak)]} { + # If we are doing SOAK tests, we want a different + # random seed for each run. Ideally we would like + # to use [clock clicks] or something like that here. + set qseed [file mtime test.db] +} else { + # If we are not doing soak tests, + # make it repeatable. + set qseed 0 +} +expr srand($qseed) + +# +# First test some specific corruption tests found from earlier runs +# with specific seeds. +# + +# test that a corrupt content offset size is handled (seed 5577) +do_test corruptC-2.1 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 2053 [format %02x 0x04] + + sqlite3 db test.db + catchsql {PRAGMA integrity_check} +} {1 {database disk image is malformed}} + +# test that a corrupt content offset size is handled (seed 5649) +do_test corruptC-2.2 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 27 [format %02x 0x08] + hexio_write test.db 233 [format %02x 0x6a] + hexio_write test.db 328 [format %02x 0x67] + hexio_write test.db 750 [format %02x 0x1f] + hexio_write test.db 1132 [format %02x 0x52] + hexio_write test.db 1133 [format %02x 0x84] + hexio_write test.db 1220 [format %02x 0x01] + hexio_write test.db 3688 [format %02x 0xc1] + hexio_write test.db 3714 [format %02x 0x58] + hexio_write test.db 3746 [format %02x 0x9a] + + sqlite3 db test.db + catchsql {UPDATE t1 SET y=1} +} {1 {database disk image is malformed}} + +# test that a corrupt free cell size is handled (seed 13329) +do_test corruptC-2.3 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 1094 [format %02x 0x76] + + sqlite3 db test.db + catchsql {UPDATE t1 SET y=1} +} {1 {database disk image is malformed}} + +# test that a corrupt free cell size is handled (seed 169571) +do_test corruptC-2.4 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 3119 [format %02x 0xdf] + + sqlite3 db test.db + catchsql {UPDATE t2 SET y='abcdef-uvwxyz'} +} {1 {database disk image is malformed}} + +# test that a corrupt free cell size is handled (seed 169571) +do_test corruptC-2.5 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 3119 [format %02x 0xdf] + hexio_write test.db 4073 [format %02x 0xbf] + + sqlite3 db test.db + catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;} + catchsql {PRAGMA integrity_check} +} {0 {{*** in database main *** +Page 4: btreeInitPage() returns error code 11}}} + +# {0 {{*** in database main *** +# Corruption detected in cell 710 on page 4 +# Multiple uses for byte 661 of page 4 +# Fragmented space is 249 byte reported as 21 on page 4}}} + +# test that a corrupt free cell size is handled (seed 169595) +do_test corruptC-2.6 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 619 [format %02x 0xe2] + hexio_write test.db 3150 [format %02x 0xa8] + + sqlite3 db test.db + catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;} +} {1 {database disk image is malformed}} + +# corruption (seed 178692) +do_test corruptC-2.7 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 3074 [format %02x 0xa0] + + sqlite3 db test.db + catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;} +} {1 {database disk image is malformed}} + +# corruption (seed 179069) +do_test corruptC-2.8 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 1393 [format %02x 0x7d] + hexio_write test.db 84 [format %02x 0x19] + hexio_write test.db 3287 [format %02x 0x3b] + hexio_write test.db 2564 [format %02x 0xed] + hexio_write test.db 2139 [format %02x 0x55] + + sqlite3 db test.db + catchsql {BEGIN; DELETE FROM t1 WHERE x>13; ROLLBACK;} +} {1 {database disk image is malformed}} + +# corruption (seed 170434) +do_test corruptC-2.9 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 2095 [format %02x 0xd6] + + sqlite3 db test.db + catchsql {BEGIN; DELETE FROM t1 WHERE x>13; ROLLBACK;} +} {1 {database disk image is malformed}} + +# corruption (seed 186504) +do_test corruptC-2.10 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 3130 [format %02x 0x02] + + sqlite3 db test.db + catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;} +} {1 {database disk image is malformed}} + +# corruption (seed 1589) +do_test corruptC-2.11 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 55 [format %02x 0xa7] + + sqlite3 db test.db + catchsql {BEGIN; CREATE TABLE t3 AS SELECT x,3 as y FROM t2 WHERE rowid%5!=0; ROLLBACK;} +} {1 {database disk image is malformed}} + +# corruption (seed 14166) +do_test corruptC-2.12 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 974 [format %02x 0x2e] + + sqlite3 db test.db + catchsql {SELECT count(*) FROM sqlite_master;} +} {1 {malformed database schema (t1i1) - corrupt database}} + +# corruption (seed 218803) +do_test corruptC-2.13 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 102 [format %02x 0x12] + + sqlite3 db test.db + catchsql {BEGIN; CREATE TABLE t3 AS SELECT x,3 as y FROM t2 WHERE rowid%5!=0; ROLLBACK;} +} {1 {database disk image is malformed}} + +do_test corruptC-2.14 { + db close + forcecopy test.bu test.db + + sqlite3 db test.db + set blob [string repeat abcdefghij 10000] + execsql { INSERT INTO t1 VALUES (1, $blob) } + + sqlite3 db test.db + set filesize [file size test.db] + hexio_write test.db [expr $filesize-2048] 00000001 + catchsql {DELETE FROM t1 WHERE rowid = (SELECT max(rowid) FROM t1)} +} {1 {database disk image is malformed}} + +# At one point this particular corrupt database was causing a buffer +# overread. Which caused a crash in a run of all.test once. +# +do_test corruptC-2.15 { + db close + forcecopy test.bu test.db + hexio_write test.db 986 b9 + sqlite3 db test.db + catchsql {SELECT count(*) FROM sqlite_master;} +} {1 {malformed database schema (t1i1) - no such table: main.t1}} + +# +# Now test for a series of quasi-random seeds. +# We loop over the entire file size and touch +# each byte at least once. +for {set tn 0} {$tn<$fsize} {incr tn 1} { + + # setup for test + db close + forcecopy test.bu test.db + sqlite3 db test.db + + # Seek to a random location in the file, and write a random single byte + # value. Then do various operations on the file to make sure that + # the database engine can handle the corruption gracefully. + # + set last 0 + for {set i 1} {$i<=512 && !$last} {incr i 1} { + + db close + if {$i==1} { + # on the first corrupt value, use location $tn + # this ensures that we touch each location in the + # file at least once. + set roffset $tn + } else { + # insert random byte at random location + set roffset [random $fsize] + } + set rbyte [format %02x [random 255]] + + # You can uncomment the following to have it trace + # exactly how it's corrupting the file. This is + # useful for generating the "seed specific" tests + # above. + # set rline "$roffset $rbyte" + # puts stdout $rline + + hexio_write test.db $roffset $rbyte + sqlite3 db test.db + + # do a few random operations to make sure that if + # they error, they error gracefully instead of crashing. + do_test corruptC-3.$tn.($qseed).$i.1 { + catchsql {SELECT count(*) FROM sqlite_master} + set x {} + } {} + do_test corruptC-3.$tn.($qseed).$i.2 { + catchsql {SELECT count(*) FROM t1} + set x {} + } {} + do_test corruptC-3.$tn.($qseed).$i.3 { + catchsql {SELECT count(*) FROM t1 WHERE x>13} + set x {} + } {} + do_test corruptC-3.$tn.($qseed).$i.4 { + catchsql {SELECT count(*) FROM t2} + set x {} + } {} + do_test corruptC-3.$tn.($qseed).$i.5 { + catchsql {SELECT count(*) FROM t2 WHERE x<13} + set x {} + } {} + do_test corruptC-3.$tn.($qseed).$i.6 { + catchsql {BEGIN; UPDATE t1 SET y=1; ROLLBACK;} + set x {} + } {} + do_test corruptC-3.$tn.($qseed).$i.7 { + catchsql {BEGIN; UPDATE t2 SET y='abcdef-uvwxyz'; ROLLBACK;} + set x {} + } {} + do_test corruptC-3.$tn.($qseed).$i.8 { + catchsql {BEGIN; DELETE FROM t1 WHERE x>13; ROLLBACK;} + set x {} + } {} + do_test corruptC-3.$tn.($qseed).$i.9 { + catchsql {BEGIN; DELETE FROM t2 WHERE x<13; ROLLBACK;} + set x {} + } {} + do_test corruptC-3.$tn.($qseed).$i.10 { + catchsql {BEGIN; CREATE TABLE t3 AS SELECT x,3 as y FROM t2 WHERE rowid%5!=0; ROLLBACK;} + set x {} + } {} + + # check the integrity of the database. + # once the corruption is detected, we can stop. + ifcapable {integrityck} { + set res [ catchsql {PRAGMA integrity_check} ] + set ans [lindex $res 1] + if { [ string compare $ans "ok" ] != 0 } { + set last -1 + } + } + # if we are not capable of doing an integrity check, + # stop after corrupting 5 bytes. + ifcapable {!integrityck} { + if { $i > 5 } { + set last -1 + } + } + + # Check that no page references were leaked. + # TBD: need to figure out why this doesn't work + # work with ROLLBACKs... + if {0} { + do_test corruptC-3.$tn.($qseed).$i.11 { + set bt [btree_from_db db] + db_enter db + array set stats [btree_pager_stats $bt] + db_leave db + set stats(ref) + } {0} + } + } + # end for i + +} +# end for tn + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corruptD.test b/components/external/SQLite-3.8.1/test/corruptD.test new file mode 100644 index 0000000000000000000000000000000000000000..2423cd428e4d277f730a323657e0ac2904d362b2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corruptD.test @@ -0,0 +1,140 @@ +# 2009 June 3 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: corruptD.test,v 1.2 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +#-------------------------------------------------------------------------- +# OVERVIEW +# +# This test file attempts to verify that SQLite does not read past the +# end of any in-memory buffers as a result of corrupted database page +# images. Usually this happens because a field within a database page +# that contains an offset to some other structure within the same page +# is set to too large a value. A database page contains the following +# such fields: +# +# 1. The page header field that contains the offset to the first +# free block of space. +# +# 2. The first two bytes of all but the last free block on the free-block +# list (the offset to the next free block). +# +# 3. The page header field containing the number of cells on the page +# (implicitly defines the offset to the final element in the cell offset +# array, which could potentially be off the end of the page). +# +# 4. The page header field containing the offset to the start of the cell +# content area. +# +# 5. The contents of the cell offset array. +# +# 6. The first few bytes of each cell determine the size of the cell +# stored within the page, and hence the offset to the final byte of +# the cell. +# +# If any of the above fields are set to too large a value, then a buffer +# overread may occur. This test script creates and operates on various +# strategically corrupted database files to attempt to provoke such buffer +# overreads. +# +# Very often, a buffer overread passes unnoticed, particularly in workstation +# environments. For this reason, this test script should be run using valgrind +# (or similar) in order to verify that no overreads occur. +# +# TEST PLAN +# +# Test cases corruptD-1.* are white-box tests. They attempt to corrupt +# one of the above fields, then exercise each part of the code in btree.c +# that uses said field. +# +# Offset variables 1, 2, 3 and 4 are all checked to make sure they +# will not result in buffer overruns as part of page initialization in +# sqlite3BtreeInitPage(). Offsets 5 and 6 cannot be tested as part of +# page initialization, as trying to do so causes a performance hit. +# + +do_test corruptD-1.0 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + } + for {set ii 1} {$ii < 50} {incr ii} { + execsql { INSERT INTO t1 VALUES($ii, $ii * $ii) } + } + execsql { + DELETE FROM t1 WHERE a = 10; + DELETE FROM t1 WHERE a = 20; + DELETE FROM t1 WHERE a = 30; + DELETE FROM t1 WHERE a = 40; + } + forcecopy test.db test.bu +} {} + +proc incr_change_counter {} { + hexio_write test.db 24 [ + hexio_render_int32 [expr [hexio_get_int [hexio_read test.db 24 4]] + 1] + ] +} + +proc restore_file {} { + db close + forcecopy test.bu test.db + sqlite3 db test.db +} + +#------------------------------------------------------------------------- +# The following tests, corruptD-1.1.*, focus on the page header field +# containing the offset of the first free block in a page. +# +do_test corruptD-1.1.1 { + incr_change_counter + hexio_write test.db [expr 1024+1] FFFF + catchsql { SELECT * FROM t1 ORDER BY rowid } +} {1 {database disk image is malformed}} +do_test corruptD-1.1.2 { + incr_change_counter + hexio_write test.db [expr 1024+1] [hexio_render_int32 1021] + catchsql { SELECT * FROM t1 ORDER BY rowid } +} {1 {database disk image is malformed}} + +#------------------------------------------------------------------------- +# The following tests, corruptD-1.2.*, focus on the offsets contained +# in the first 2 byte of each free-block on the free-list. +# +do_test corruptD-1.2.1 { + restore_file +} {} +do_test corruptD-1.2.2 { +} {} + +#------------------------------------------------------------------------- +# The following tests, corruptD-1.4.*, ... +# + + +#------------------------------------------------------------------------- +# The following tests, corruptD-1.5.*, focus on the offsets contained +# in the cell offset array. +# +# defragmentPage +# + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corruptE.test b/components/external/SQLite-3.8.1/test/corruptE.test new file mode 100644 index 0000000000000000000000000000000000000000..48292ab2e90b644b4d4c1aa6433de8affcdc7268 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corruptE.test @@ -0,0 +1,175 @@ +# 2010 February 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite does not crash or +# segfault if it sees a corrupt database file. It specifcally +# focuses on rowid order corruption. +# +# $Id: corruptE.test,v 1.14 2009/07/11 06:55:34 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Do not run the tests in this file if ENABLE_OVERSIZE_CELL_CHECK is on. +# +ifcapable oversize_cell_check { + finish_test + return +} + +# Construct a compact, dense database for testing. +# +do_test corruptE-1.1 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA legacy_file_format=1; + BEGIN; + CREATE TABLE t1(x,y); + INSERT INTO t1 VALUES(1,1); + INSERT OR IGNORE INTO t1 SELECT x*2,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*3,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*5,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*7,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*11,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*13,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*17,y FROM t1; + INSERT OR IGNORE INTO t1 SELECT x*19,y FROM t1; + CREATE INDEX t1i1 ON t1(x); + CREATE TABLE t2 AS SELECT x,2 as y FROM t1 WHERE rowid%5!=0 ORDER BY rowid; + COMMIT; + } +} {} + +ifcapable {integrityck} { + integrity_check corruptE-1.2 +} + +# Setup for the tests. Make a backup copy of the good database in test.bu. +# +db close +forcecopy test.db test.bu +sqlite3 db test.db +set fsize [file size test.db] + + +do_test corruptE-2.1 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 2041 [format %02x 0x2e] + + sqlite3 db test.db + + set res [ catchsql {PRAGMA integrity_check} ] + set ans [lindex $res 1] + + list [regexp {out of order.*previous was} $ans] \ + [regexp {out of order.*max larger than parent max} $ans] +} {1 1} + +do_test corruptE-2.2 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 2047 [format %02x 0x84] + + sqlite3 db test.db + + set res [ catchsql {PRAGMA integrity_check} ] + set ans [lindex $res 1] + + list [regexp {out of order.*previous was} $ans] \ + [regexp {out of order.*min less than parent min} $ans] +} {1 1} + +do_test corruptE-2.3 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 7420 [format %02x 0xa8] + hexio_write test.db 10459 [format %02x 0x8d] + + sqlite3 db test.db + + set res [ catchsql {PRAGMA integrity_check} ] + set ans [lindex $res 1] + + list [regexp {out of order.*max larger than parent min} $ans] +} {1} + +do_test corruptE-2.4 { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db 10233 [format %02x 0xd0] + + sqlite3 db test.db + + set res [ catchsql {PRAGMA integrity_check} ] + set ans [lindex $res 1] + + list [regexp {out of order.*min less than parent max} $ans] +} {1} + + +set tests [list {10233 0xd0} \ + {941 0x42} \ + {1028 0x53} \ + {2041 0xd0} \ + {2042 0x1f} \ + {2047 0xaa} \ + {2263 0x29} \ + {2274 0x75} \ + {3267 0xf2} \ + {4104 0x2c} \ + {5113 0x36} \ + {10233 0x84} \ + {10234 0x74} \ + {10239 0x41} \ + {10453 0x11} \ + {11273 0x28} \ + {11455 0x11} \ + {11461 0xe6} \ + {12281 0x99} \ + {12296 0x9e} \ + {12297 0xd7} \ + {13303 0x53} ] + +set tc 1 +foreach test $tests { + do_test corruptE-3.$tc { + db close + forcecopy test.bu test.db + + # insert corrupt byte(s) + hexio_write test.db [lindex $test 0] [format %02x [lindex $test 1]] + + sqlite3 db test.db + + set res [ catchsql {PRAGMA integrity_check} ] + set ans [lindex $res 1] + + list [regexp {out of order} $ans] + } {1} + incr tc 1 +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corruptF.test b/components/external/SQLite-3.8.1/test/corruptF.test new file mode 100644 index 0000000000000000000000000000000000000000..64c6eb890bdb4fa0770e2305b233853f290bf3b2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corruptF.test @@ -0,0 +1,149 @@ +# 2012 January 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix corruptF + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +proc str {i} { format %08d $i } + +# Create a 6 page database containing a single table - t1. Table t1 +# consists of page 2 (the root page) and pages 5 and 6 (leaf pages). +# Database pages 3 and 4 are on the free list. +# +proc create_test_db {} { + catch { db close } + forcedelete test.db + sqlite3 db test.db + db func str str + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 1024; + CREATE TABLE t1(x); /* root page = 2 */ + CREATE TABLE t2(x); /* root page = 3 */ + CREATE TABLE t3(x); /* root page = 4 */ + + INSERT INTO t1 VALUES(str(1)); + INSERT INTO t1 SELECT str(rowid+1) FROM t1; + INSERT INTO t1 SELECT str(rowid+2) FROM t1; + INSERT INTO t1 SELECT str(rowid+4) FROM t1; + INSERT INTO t1 SELECT str(rowid+8) FROM t1; + INSERT INTO t1 SELECT str(rowid+16) FROM t1; + INSERT INTO t1 SELECT str(rowid+32) FROM t1; + INSERT INTO t1 SELECT str(rowid+64) FROM t1; + DROP TABLE t2; + DROP TABLE t3; + } + db close +} + +do_test 1.1 { create_test_db } {} + +# Check the db is as we expect. 6 pages in total, with 3 and 4 on the free +# list. Page 3 is the free list trunk and page 4 is a leaf. +# +do_test 1.2 { file size test.db } [expr 6*1024] +do_test 1.3 { hexio_read test.db 32 4 } 00000003 +do_test 1.4 { hexio_read test.db [expr 2*1024] 12 } 000000000000000100000004 + +# Change the free-list entry to page 6 and reopen the db file. +do_test 1.5 { + hexio_write test.db [expr 2*1024 + 8] 00000006 + sqlite3 db test.db +} {} + +# Now create a new table in the database file. The root of the new table +# is page 6, which is also the right-most leaf page in table t1. +# +do_execsql_test 1.6 { + CREATE TABLE t4(x); + SELECT * FROM sqlite_master; +} { + table t1 t1 2 {CREATE TABLE t1(x)} + table t4 t4 6 {CREATE TABLE t4(x)} +} + +# At one point this was causing an assert to fail. +# +# This statement opens a cursor on table t1 and does a full table scan. As +# each row is visited, it is copied into table t4. There is no temporary +# table. +# +# When the t1 cursor reaches page 6 (which is both the right-most leaf of +# t1 and the root of t4), it continues to iterate through the keys within +# it (which at this point are keys that have been inserted into t4). And +# for each row visited, another row is inserted into page 6 - it being the +# root page of t4. Eventually, page 6 becomes full and the height of the +# b-tree for table t4 increased. From the point of view of the t1 cursor, +# this unexpectedly reduces the number of keys on page 6 in the middle of +# its iteration, which causes an assert() to fail. +# +db_save_and_close +if 1 { +for {set i 0} {$i < 128} {incr i} { + db_restore_and_reopen + do_test 1.7.$i { + set res [ + catchsql { INSERT INTO t4 SELECT x FROM t1 WHERE rowid>$i } + ] + if {$res == "0 {}" || $res == "1 {database disk image is malformed}"} { + set res "" + } + set res + } {} +} +} + +do_test 2.1 { create_test_db } {} +do_test 2.2 { file size test.db } [expr 6*1024] +do_test 2.3 { hexio_read test.db 32 4 } 00000003 +do_test 2.4 { hexio_read test.db [expr 2*1024] 12 } 000000000000000100000004 + +# Change the free-list entry to page 5 and reopen the db file. +do_test 2.5 { + hexio_write test.db [expr 2*1024 + 8] 00000005 + sqlite3 db test.db +} {} + +# Now create a new table in the database file. The root of the new table +# is page 5, which is also the right-most leaf page in table t1. +# +do_execsql_test 2.6 { + CREATE TABLE t4(x); + SELECT * FROM sqlite_master; +} { + table t1 t1 2 {CREATE TABLE t1(x)} + table t4 t4 5 {CREATE TABLE t4(x)} +} + +db_save_and_close +for {set i 127} {$i >= 0} {incr i -1} { + db_restore_and_reopen + do_test 2.7.$i { + set res [ + catchsql { + INSERT INTO t4 SELECT x FROM t1 WHERE rowid<$i ORDER BY rowid DESC + } + ] + if {$res == "0 {}" || $res == "1 {database disk image is malformed}"} { + set res "" + } + set res + } {} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/corruptG.test b/components/external/SQLite-3.8.1/test/corruptG.test new file mode 100644 index 0000000000000000000000000000000000000000..c34911195c808afa07cef07f9b6799e613f20dc5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/corruptG.test @@ -0,0 +1,77 @@ +# 2013-08-01 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix corruptG + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Create a simple database with a single entry. Then corrupt the +# header-size varint on the index payload so that it maps into a +# negative number. Try to use the database. +# + +do_execsql_test 1.1 { + PRAGMA page_size=512; + CREATE TABLE t1(a,b,c); + INSERT INTO t1(rowid,a,b,c) VALUES(52,'abc','xyz','123'); + CREATE INDEX t1abc ON t1(a,b,c); +} + +set idxroot [db one {SELECT rootpage FROM sqlite_master WHERE name = 't1abc'}] + +# Corrupt the file +db close +hexio_write test.db [expr {$idxroot*512 - 15}] 888080807f +sqlite3 db test.db + +# Try to use the file. +do_test 1.2 { + catchsql { + SELECT c FROM t1 WHERE a>'abc'; + } +} {0 {}} +do_test 1.3 { + catchsql { + PRAGMA integrity_check + } +} {0 ok} +do_test 1.4 { + catchsql { + SELECT c FROM t1 ORDER BY a; + } +} {1 {database disk image is malformed}} + +# Corrupt the same file in a slightly different way. Make the record header +# sane, but corrupt one of the serial_type value to indicate a huge payload +# such that the payload begins in allocated space but overflows the buffer. +# +db close +hexio_write test.db [expr {$idxroot*512-15}] 0513ff7f01 +sqlite3 db test.db + +do_test 2.1 { + catchsql { + SELECT rowid FROM t1 WHERE a='abc' and b='xyz123456789XYZ'; + } + # The following test result is brittle. The point above is to try to + # force a buffer overread by a corrupt database file. If we get an + # incorrect answer from a corrupt database file, that is OK. If the + # result below changes, that just means that "undefined behavior" has + # changed. +} {0 52} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/count.test b/components/external/SQLite-3.8.1/test/count.test new file mode 100644 index 0000000000000000000000000000000000000000..fbdd13b6ba55202760ddc0c8fdd70d6d34f868b0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/count.test @@ -0,0 +1,192 @@ +# 2009 February 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing "SELECT count(*)" statements. +# +# $Id: count.test,v 1.6 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Test plan: +# +# count-0.*: Make sure count(*) works on an empty database. (Ticket #3774) +# +# count-1.*: Test that the OP_Count instruction appears to work on both +# tables and indexes. Test both when they contain 0 entries, +# when all entries are on the root page, and when the b-tree +# forms a structure 2 and 3 levels deep. +# +# count-2.*: Test that +# +# + +do_test count-0.1 { + db eval { + SELECT count(*) FROM sqlite_master; + } +} {0} + +set iTest 0 +foreach zIndex [list { + /* no-op */ +} { + CREATE INDEX i1 ON t1(a); +}] { + incr iTest + do_test count-1.$iTest.1 { + execsql { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(a, b); + } + execsql $zIndex + execsql { SELECT count(*) FROM t1 } + } {0} + + do_test count-1.$iTest.2 { + execsql { + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + SELECT count(*) FROM t1; + } + } {2} + + do_test count-1.$iTest.3 { + execsql { + INSERT INTO t1 SELECT * FROM t1; -- 4 + INSERT INTO t1 SELECT * FROM t1; -- 8 + INSERT INTO t1 SELECT * FROM t1; -- 16 + INSERT INTO t1 SELECT * FROM t1; -- 32 + INSERT INTO t1 SELECT * FROM t1; -- 64 + INSERT INTO t1 SELECT * FROM t1; -- 128 + INSERT INTO t1 SELECT * FROM t1; -- 256 + SELECT count(*) FROM t1; + } + } {256} + + do_test count-1.$iTest.4 { + execsql { + INSERT INTO t1 SELECT * FROM t1; -- 512 + INSERT INTO t1 SELECT * FROM t1; -- 1024 + INSERT INTO t1 SELECT * FROM t1; -- 2048 + INSERT INTO t1 SELECT * FROM t1; -- 4096 + SELECT count(*) FROM t1; + } + } {4096} + + do_test count-1.$iTest.5 { + execsql { + BEGIN; + INSERT INTO t1 SELECT * FROM t1; -- 8192 + INSERT INTO t1 SELECT * FROM t1; -- 16384 + INSERT INTO t1 SELECT * FROM t1; -- 32768 + INSERT INTO t1 SELECT * FROM t1; -- 65536 + COMMIT; + SELECT count(*) FROM t1; + } + } {65536} +} + +proc uses_op_count {sql} { + if {[lsearch [execsql "EXPLAIN $sql"] Count]>=0} { + return 1; + } + return 0 +} + +do_test count-2.1 { + execsql { + CREATE TABLE t2(a, b); + } + uses_op_count {SELECT count(*) FROM t2} +} {1} +do_test count-2.2 { + catchsql {SELECT count(DISTINCT *) FROM t2} +} {1 {near "*": syntax error}} +do_test count-2.3 { + uses_op_count {SELECT count(DISTINCT a) FROM t2} +} {0} +do_test count-2.4 { + uses_op_count {SELECT count(a) FROM t2} +} {0} +do_test count-2.5 { + uses_op_count {SELECT count() FROM t2} +} {1} +do_test count-2.6 { + catchsql {SELECT count(DISTINCT) FROM t2} +} {1 {DISTINCT aggregates must have exactly one argument}} +do_test count-2.7 { + uses_op_count {SELECT count(*)+1 FROM t2} +} {0} +do_test count-2.8 { + uses_op_count {SELECT count(*) FROM t2 WHERE a IS NOT NULL} +} {0} +do_test count-2.9 { + catchsql {SELECT count(*) FROM t2 HAVING count(*)>1} +} {1 {a GROUP BY clause is required before HAVING}} +do_test count-2.10 { + uses_op_count {SELECT count(*) FROM (SELECT 1)} +} {0} +do_test count-2.11 { + execsql { CREATE VIEW v1 AS SELECT 1 AS a } + uses_op_count {SELECT count(*) FROM v1} +} {0} +do_test count-2.12 { + uses_op_count {SELECT count(*), max(a) FROM t2} +} {0} +do_test count-2.13 { + uses_op_count {SELECT count(*) FROM t1, t2} +} {0} + +ifcapable vtab { + register_echo_module [sqlite3_connection_pointer db] + do_test count-2.14 { + execsql { CREATE VIRTUAL TABLE techo USING echo(t1); } + uses_op_count {SELECT count(*) FROM techo} + } {0} +} + +do_test count-3.1 { + execsql { + CREATE TABLE t3(a, b); + SELECT a FROM (SELECT count(*) AS a FROM t3) WHERE a==0; + } +} {0} +do_test count-3.2 { + execsql { + SELECT a FROM (SELECT count(*) AS a FROM t3) WHERE a==1; + } +} {} + +do_test count-4.1 { + execsql { + CREATE TABLE t4(a, b); + INSERT INTO t4 VALUES('a', 'b'); + CREATE INDEX t4i1 ON t4(b, a); + SELECT count(*) FROM t4; + } +} {1} +do_test count-4.2 { + execsql { + CREATE INDEX t4i2 ON t4(b); + SELECT count(*) FROM t4; + } +} {1} +do_test count-4.3 { + execsql { + DROP INDEX t4i1; + CREATE INDEX t4i1 ON t4(b, a); + SELECT count(*) FROM t4; + } +} {1} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/coveridxscan.test b/components/external/SQLite-3.8.1/test/coveridxscan.test new file mode 100644 index 0000000000000000000000000000000000000000..7b3c0b0be9942aa898a9dd483797ded8c12948e6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/coveridxscan.test @@ -0,0 +1,93 @@ +# 2012 September 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests for the optimization which attempts to use a covering index +# for a full-table scan (under the theory that the index will be smaller +# and require less I/O and hence will run faster.) +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set testprefix coveridxscan + +do_test 1.1 { + db eval { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(5,4,3), (4,8,2), (3,2,1); + CREATE INDEX t1ab ON t1(a,b); + CREATE INDEX t1b ON t1(b); + SELECT a FROM t1; + } + # covering index used for the scan, hence values are increasing +} {3 4 5} + +do_test 1.2 { + db eval { + SELECT a, c FROM t1; + } + # There is no covering index, hence the values are in rowid order +} {5 3 4 2 3 1} + +do_test 1.3 { + db eval { + SELECT b FROM t1; + } + # Choice of two indices: use the one with fewest columns +} {2 4 8} + +do_test 2.1 { + optimization_control db cover-idx-scan 0 + db eval {SELECT a FROM t1} + # With the optimization turned off, output in rowid order +} {5 4 3} +do_test 2.2 { + db eval {SELECT a, c FROM t1} +} {5 3 4 2 3 1} +do_test 2.3 { + db eval {SELECT b FROM t1} +} {4 8 2} + +db close +sqlite3_shutdown +sqlite3_config_cis 0 +sqlite3 db test.db + +do_test 3.1 { + db eval {SELECT a FROM t1} + # With the optimization configured off, output in rowid order +} {5 4 3} +do_test 3.2 { + db eval {SELECT a, c FROM t1} +} {5 3 4 2 3 1} +do_test 3.3 { + db eval {SELECT b FROM t1} +} {4 8 2} + +db close +sqlite3_shutdown +sqlite3_config_cis 1 +sqlite3 db test.db + +# The CIS optimization is enabled again. Covering indices are once again +# used for all table scans. +do_test 4.1 { + db eval {SELECT a FROM t1} +} {3 4 5} +do_test 4.2 { + db eval {SELECT a, c FROM t1} +} {5 3 4 2 3 1} +do_test 4.3 { + db eval {SELECT b FROM t1} +} {2 4 8} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/crash.test b/components/external/SQLite-3.8.1/test/crash.test new file mode 100644 index 0000000000000000000000000000000000000000..c1901daec6ca24dc0740c220c45d900fd787f145 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/crash.test @@ -0,0 +1,411 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# The focus of this file is testing the ability of the database to +# uses its rollback journal to recover intact (no database corruption) +# from a power failure during the middle of a COMMIT. The OS interface +# modules are overloaded using the modified I/O routines found in test6.c. +# These routines allow us to simulate the kind of file damage that +# occurs after a power failure. +# +# $Id: crash.test,v 1.27 2008/01/08 15:18:52 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !crashtest { + finish_test + return +} + +set repeats 100 +#set repeats 10 + +# The following procedure computes a "signature" for table "abc". If +# abc changes in any way, the signature should change. +proc signature {} { + return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}] +} +proc signature2 {} { + return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc2}] +} + +#-------------------------------------------------------------------------- +# Simple crash test: +# +# crash-1.1: Create a database with a table with two rows. +# crash-1.2: Run a 'DELETE FROM abc WHERE a = 1' that crashes during +# the first journal-sync. +# crash-1.3: Ensure the database is in the same state as after crash-1.1. +# crash-1.4: Run a 'DELETE FROM abc WHERE a = 1' that crashes during +# the first database-sync. +# crash-1.5: Ensure the database is in the same state as after crash-1.1. +# crash-1.6: Run a 'DELETE FROM abc WHERE a = 1' that crashes during +# the second journal-sync. +# crash-1.7: Ensure the database is in the same state as after crash-1.1. +# +# Tests 1.8 through 1.11 test for crashes on the third journal sync and +# second database sync. Neither of these is required in such a small test +# case, so these tests are just to verify that the test infrastructure +# operates as expected. +# +do_test crash-1.1 { + execsql { + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, 6); + } + set ::sig [signature] + expr 0 +} {0} +for {set i 0} {$i<10} {incr i} { + set seed [expr {int(abs(rand()*10000))}] + do_test crash-1.2.$i { + crashsql -delay 1 -file test.db-journal -seed $seed { + DELETE FROM abc WHERE a = 1; + } + } {1 {child process exited abnormally}} + do_test crash-1.3.$i { + signature + } $::sig +} +do_test crash-1.4 { + crashsql -delay 1 -file test.db { + DELETE FROM abc WHERE a = 1; + } +} {1 {child process exited abnormally}} +do_test crash-1.5 { + signature +} $::sig +do_test crash-1.6 { + crashsql -delay 2 -file test.db-journal { + DELETE FROM abc WHERE a = 1; + } +} {1 {child process exited abnormally}} +do_test crash-1.7 { + catchsql { + SELECT * FROM abc; + } +} {0 {1 2 3 4 5 6}} + +do_test crash-1.8 { + crashsql -delay 3 -file test.db-journal { + DELETE FROM abc WHERE a = 1; + } +} {0 {}} +do_test crash-1.9 { + catchsql { + SELECT * FROM abc; + } +} {0 {4 5 6}} +do_test crash-1.10 { + crashsql -delay 2 -file test.db { + DELETE FROM abc WHERE a = 4; + } +} {0 {}} +do_test crash-1.11 { + catchsql { + SELECT * FROM abc; + } +} {0 {}} + +#-------------------------------------------------------------------------- +# The following tests test recovery when both the database file and the +# journal file contain corrupt data. This can happen after pages are +# written to the database file before a transaction is committed due to +# cache-pressure. +# +# crash-2.1: Insert 18 pages of data into the database. +# crash-2.2: Check the database file size looks ok. +# crash-2.3: Delete 15 or so pages (with a 10 page page-cache), then crash. +# crash-2.4: Ensure the database is in the same state as after crash-2.1. +# +# Test cases crash-2.5 and crash-2.6 check that the database is OK if the +# crash occurs during the main database file sync. But this isn't really +# different from the crash-1.* cases. +# +do_test crash-2.1 { + execsql { BEGIN } + for {set n 0} {$n < 1000} {incr n} { + execsql "INSERT INTO abc VALUES($n, [expr 2*$n], [expr 3*$n])" + } + execsql { COMMIT } + set ::sig [signature] + execsql { SELECT sum(a), sum(b), sum(c) from abc } +} {499500 999000 1498500} +do_test crash-2.2 { + expr ([file size test.db] / 1024)>16 +} {1} +do_test crash-2.3 { + crashsql -delay 2 -file test.db-journal { + DELETE FROM abc WHERE a < 800; + } +} {1 {child process exited abnormally}} +do_test crash-2.4 { + signature +} $sig +do_test crash-2.5 { + crashsql -delay 1 -file test.db { + DELETE FROM abc WHERE a<800; + } +} {1 {child process exited abnormally}} +do_test crash-2.6 { + signature +} $sig + +#-------------------------------------------------------------------------- +# The crash-3.* test cases are essentially the same test as test case +# crash-2.*, but with a more complicated data set. +# +# The test is repeated a few times with different seeds for the random +# number generator in the crashing executable. Because there is no way to +# seed the random number generator directly, some SQL is added to the test +# case to 'use up' a different quantity random numbers before the test SQL +# is executed. +# + +# Make sure the file is much bigger than the pager-cache (10 pages). This +# ensures that cache-spills happen regularly. +do_test crash-3.0 { + execsql { + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + } + expr ([file size test.db] / 1024) > 450 +} {1} +for {set i 1} {$i < $repeats} {incr i} { + set sig [signature] + do_test crash-3.$i.1 { + set seed [expr {int(abs(rand()*10000))}] + crashsql -delay [expr $i%5 + 1] -file test.db-journal -seed $seed " + BEGIN; + SELECT random() FROM abc LIMIT $i; + INSERT INTO abc VALUES(randstr(10,10), 0, 0); + DELETE FROM abc WHERE random()%10!=0; + COMMIT; + " + } {1 {child process exited abnormally}} + do_test crash-3.$i.2 { + signature + } $sig +} + +#-------------------------------------------------------------------------- +# The following test cases - crash-4.* - test the correct recovery of the +# database when a crash occurs during a multi-file transaction. +# +# crash-4.1.*: Test recovery when crash occurs during sync() of the +# main database journal file. +# crash-4.2.*: Test recovery when crash occurs during sync() of an +# attached database journal file. +# crash-4.3.*: Test recovery when crash occurs during sync() of the master +# journal file. +# +ifcapable attach { + do_test crash-4.0 { + forcedelete test2.db + forcedelete test2.db-journal + execsql { + ATTACH 'test2.db' AS aux; + PRAGMA aux.default_cache_size = 10; + CREATE TABLE aux.abc2 AS SELECT 2*a as a, 2*b as b, 2*c as c FROM abc; + } + expr ([file size test2.db] / 1024) > 450 + } {1} + + set fin 0 + for {set i 1} {$i<$repeats} {incr i} { + set seed [expr {int(abs(rand()*10000))}] + set sig [signature] + set sig2 [signature2] + do_test crash-4.1.$i.1 { + set c [crashsql -delay $i -file test.db-journal -seed $::seed " + ATTACH 'test2.db' AS aux; + BEGIN; + SELECT randstr($i,$i) FROM abc LIMIT $i; + INSERT INTO abc VALUES(randstr(10,10), 0, 0); + DELETE FROM abc WHERE random()%10!=0; + INSERT INTO abc2 VALUES(randstr(10,10), 0, 0); + DELETE FROM abc2 WHERE random()%10!=0; + COMMIT; + "] + if { $c == {0 {}} } { + set ::fin 1 + set c {1 {child process exited abnormally}} + } + set c + } {1 {child process exited abnormally}} + if {$::fin} break + do_test crash-4.1.$i.2 { + signature + } $sig + do_test crash-4.1.$i.3 { + signature2 + } $sig2 + } + set i 0 + set fin 0 + while {[incr i]} { + set seed [expr {int(abs(rand()*10000))}] + set sig [signature] + set sig2 [signature2] + set ::fin 0 + do_test crash-4.2.$i.1 { + set c [crashsql -delay $i -file test2.db-journal -seed $::seed " + ATTACH 'test2.db' AS aux; + BEGIN; + SELECT randstr($i,$i) FROM abc LIMIT $i; + INSERT INTO abc VALUES(randstr(10,10), 0, 0); + DELETE FROM abc WHERE random()%10!=0; + INSERT INTO abc2 VALUES(randstr(10,10), 0, 0); + DELETE FROM abc2 WHERE random()%10!=0; + COMMIT; + "] + if { $c == {0 {}} } { + set ::fin 1 + set c {1 {child process exited abnormally}} + } + set c + } {1 {child process exited abnormally}} + if { $::fin } break + do_test crash-4.2.$i.2 { + signature + } $sig + do_test crash-4.2.$i.3 { + signature2 + } $sig2 + } + for {set i 1} {$i < 5} {incr i} { + set sig [signature] + set sig2 [signature2] + do_test crash-4.3.$i.1 { + crashsql -delay 1 -file test.db-mj* " + ATTACH 'test2.db' AS aux; + BEGIN; + SELECT random() FROM abc LIMIT $i; + INSERT INTO abc VALUES(randstr(10,10), 0, 0); + DELETE FROM abc WHERE random()%10!=0; + INSERT INTO abc2 VALUES(randstr(10,10), 0, 0); + DELETE FROM abc2 WHERE random()%10!=0; + COMMIT; + " + } {1 {child process exited abnormally}} + do_test crash-4.3.$i.2 { + signature + } $sig + do_test crash-4.3.$i.3 { + signature2 + } $sig2 + } +} + +#-------------------------------------------------------------------------- +# The following test cases - crash-5.* - exposes a bug that existed in the +# sqlite3pager_movepage() API used by auto-vacuum databases. +# database when a crash occurs during a multi-file transaction. See comments +# in test crash-5.3 for details. +# +db close +forcedelete test.db +sqlite3 db test.db +do_test crash-5.1 { + execsql { + CREATE TABLE abc(a, b, c); -- Root page 3 + INSERT INTO abc VALUES(randstr(1500,1500), 0, 0); -- Overflow page 4 + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + } +} {} +do_test crash-5.2 { + expr [file size test.db] / 1024 +} [expr [string match [execsql {pragma auto_vacuum}] 1] ? 11 : 10] +set sig [signature] +do_test crash-5.3 { +# The SQL below is used to expose a bug that existed in +# sqlite3pager_movepage() during development of the auto-vacuum feature. It +# functions as follows: +# +# 1: Begin a transaction. +# 2: Put page 4 on the free-list (was the overflow page for the row deleted). +# 3: Write data to page 4 (it becomes the overflow page for the row inserted). +# The old page 4 data has been written to the journal file, but the +# journal file has not been sync()hronized. +# 4: Create a table, which calls sqlite3pager_movepage() to move page 4 +# to the end of the database (page 12) to make room for the new root-page. +# 5: Put pressure on the pager-cache. This results in page 4 being written +# to the database file to make space in the cache to load a new page. The +# bug was that page 4 was written to the database file before the journal +# is sync()hronized. +# 6: Commit. A crash occurs during the sync of the journal file. +# +# End result: Before the bug was fixed, data has been written to page 4 of the +# database file and the journal file does not contain trustworthy rollback +# data for this page. +# + crashsql -delay 1 -file test.db-journal { + BEGIN; -- 1 + DELETE FROM abc WHERE oid = 1; -- 2 + INSERT INTO abc VALUES(randstr(1500,1500), 0, 0); -- 3 + CREATE TABLE abc2(a, b, c); -- 4 + SELECT * FROM abc; -- 5 + COMMIT; -- 6 + } +} {1 {child process exited abnormally}} +integrity_check crash-5.4 +do_test crash-5.5 { + signature +} $sig + +#-------------------------------------------------------------------------- +# The following test cases - crash-6.* - test that a DROP TABLE operation +# is correctly rolled back in the event of a crash while the database file +# is being written. This is mainly to test that all pages are written to the +# journal file before truncation in an auto-vacuum database. +# +do_test crash-6.1 { + crashsql -delay 1 -file test.db { + DROP TABLE abc; + } +} {1 {child process exited abnormally}} +do_test crash-6.2 { + signature +} $sig + +#-------------------------------------------------------------------------- +# These test cases test the case where the master journal file name is +# corrupted slightly so that the corruption has to be detected by the +# checksum. +do_test crash-7.1 { + crashsql -delay 1 -file test.db { + ATTACH 'test2.db' AS aux; + BEGIN; + INSERT INTO abc VALUES(randstr(1500,1500), 0, 0); + INSERT INTO abc2 VALUES(randstr(1500,1500), 0, 0); + COMMIT; + } + + # Change the checksum value for the master journal name. + set f [open test.db-journal a] + fconfigure $f -encoding binary + seek $f [expr [file size test.db-journal] - 12] + puts -nonewline $f "\00\00\00\00" + close $f +} {} +do_test crash-7.2 { + signature +} $sig + +finish_test diff --git a/components/external/SQLite-3.8.1/test/crash2.test b/components/external/SQLite-3.8.1/test/crash2.test new file mode 100644 index 0000000000000000000000000000000000000000..c74f6c2ffa27c0461deab93f502c15f10808a9fa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/crash2.test @@ -0,0 +1,133 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# The focus of this file is testing the ability of the database to +# uses its rollback journal to recover intact (no database corruption) +# from a power failure during the middle of a COMMIT. Even more +# specifically, the tests in this file verify this functionality +# for storage mediums with various sector sizes. +# +# $Id: crash2.test,v 1.6 2008/08/25 07:12:29 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !crashtest { + finish_test + return +} + +db close + +# This test is designed to check that the crash-test infrastructure +# can create files that do not consist of an integer number of +# simulated disk blocks (i.e. 3KB file using 2KB disk blocks). +# +do_test crash2-1.1 { + crashsql -delay 500 -file test.db -blocksize 2048 { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size=1024; + BEGIN; + CREATE TABLE abc AS SELECT 1 AS a, 2 AS b, 3 AS c; + CREATE TABLE def AS SELECT 1 AS d, 2 AS e, 3 AS f; + COMMIT; + } + file size test.db +} {3072} + +for {set ii 0} {$ii < 5} {incr ii} { + + # Simple test using the database created above: Create a new + # table so that page 1 and page 4 are modified. Using a + # block-size of 2048 and page-size of 1024, this means + # pages 2 and 3 must also be saved in the journal to avoid + # risking corruption. + # + # The loop is so that this test can be run with a couple + # of different seeds for the random number generator. + # + do_test crash2-1.2.$ii { + crashsql -file test.db -blocksize 2048 [subst { + [string repeat {SELECT random();} $ii] + CREATE TABLE hij(h, i, j); + }] + sqlite3 db test.db + db eval {PRAGMA integrity_check} + } {ok} +} + +proc signature {} { + return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}] +} + +# Test case for crashing during journal sync with simulated +# sector-size values from 1024 to 8192. +# +do_test crash2-2.0 { + execsql BEGIN + for {set n 0} {$n < 1000} {incr n} { + execsql "INSERT INTO abc VALUES($n, [expr 2*$n], [expr 3*$n])" + } + execsql { + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + } + execsql COMMIT + expr ([file size test.db] / 1024) > 450 +} {1} +for {set i 1} {$i < 30} {incr i} { + set sig [signature] + set sector [expr 1024 * 1<<($i%4)] + db close + do_test crash2-2.$i.1 { + crashsql -blocksize $sector -delay [expr $i%5 + 1] -file test.db-journal " + PRAGMA temp_store = memory; + BEGIN; + SELECT random() FROM abc LIMIT $i; + INSERT INTO abc SELECT randstr(10,10), 0, 0 FROM abc WHERE random()%2==0; + DELETE FROM abc WHERE random()%2!=0; + COMMIT; + " + } {1 {child process exited abnormally}} + do_test crash2-2.$i.2 { + sqlite3 db test.db + signature + } $sig +} + + +# Test case for crashing during database sync with simulated +# sector-size values from 1024 to 8192. +# +for {set i 1} {$i < 10} {incr i} { + set sig [signature] + set sector [expr 1024 * 1<<($i%4)] + db close + do_test crash2-3.$i.1 { + crashsql -blocksize $sector -file test.db " + BEGIN; + SELECT random() FROM abc LIMIT $i; + INSERT INTO abc SELECT randstr(10,10), 0, 0 FROM abc WHERE random()%2==0; + DELETE FROM abc WHERE random()%2!=0; + COMMIT; + " + } {1 {child process exited abnormally}} + do_test crash2-3.$i.2 { + sqlite3 db test.db + signature + } $sig +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/crash3.test b/components/external/SQLite-3.8.1/test/crash3.test new file mode 100644 index 0000000000000000000000000000000000000000..7958af992ed76aa9053824cd64e801a85e534c9f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/crash3.test @@ -0,0 +1,190 @@ +# 2007 August 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests that verify that SQLite can correctly rollback +# databases after crashes when using the special IO modes triggered +# by device IOCAP flags. +# +# $Id: crash3.test,v 1.4 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !crashtest { + finish_test + return +} + +proc do_test2 {name tcl res1 res2} { + set script [subst -nocommands { + do_test $name { + set res1 {$res1} + set res2 {$res2} + set res [eval {$tcl}] + if {[set res] eq [set res1] || [set res] eq [set res2]} { + set res "{[set res1]} or {[set res2]}" + } + set res + } {{$res1} or {$res2}} + }] + uplevel $script +} + +# This block tests crash-recovery when the IOCAP_ATOMIC flags is set. +# +# Each iteration of the following loop sets up the database to contain +# the following schema and data: +# +# CREATE TABLE abc(a, b, c); +# INSERT INTO abc VALUES(1, 2, 3); +# +# Then execute the SQL statement, scheduling a crash for part-way through +# the first sync() of either the database file or the journal file (often +# the journal file is not required - meaning no crash occurs). +# +# After the crash (or absence of a crash), open the database and +# verify that: +# +# * The integrity check passes, and +# * The contents of table abc is either {1 2 3} or the value specified +# to the right of the SQL statement below. +# +# The procedure is repeated 10 times for each SQL statement. Five times +# with the crash scheduled for midway through the first journal sync (if +# any), and five times with the crash midway through the database sync. +# +set tn 1 +foreach {sql res2} [list \ + {INSERT INTO abc VALUES(4, 5, 6)} {1 2 3 4 5 6} \ + {DELETE FROM abc} {} \ + {INSERT INTO abc SELECT * FROM abc} {1 2 3 1 2 3} \ + {UPDATE abc SET a = 2} {2 2 3} \ + {INSERT INTO abc VALUES(4, 5, randstr(1000,1000))} {n/a} \ + {CREATE TABLE def(d, e, f)} {n/a} \ +] { + for {set ii 0} {$ii < 10} {incr ii} { + + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + do_test crash3-1.$tn.1 { + execsql { + PRAGMA page_size = 1024; + BEGIN; + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(1, 2, 3); + COMMIT; + } + } {} + db close + + set crashfile test.db + if {($ii%2)==0} { append crashfile -journal } + set rand "SELECT randstr($tn,$tn);" + do_test crash3-1.$tn.2 [subst { + crashsql -file $crashfile -char atomic {$rand $sql} + sqlite3 db test.db + execsql { PRAGMA integrity_check; } + }] {ok} + + do_test2 crash3-1.$tn.3 { + execsql { SELECT * FROM abc } + } {1 2 3} $res2 + + incr tn + } +} + +# This block tests both the IOCAP_SEQUENTIAL and IOCAP_SAFE_APPEND flags. +# +db close +forcedelete test.db test.db-journal +sqlite3 db test.db +do_test crash3-2.0 { + execsql { + BEGIN; + CREATE TABLE abc(a PRIMARY KEY, b, c); + CREATE TABLE def(d PRIMARY KEY, e, f); + PRAGMA default_cache_size = 10; + INSERT INTO abc VALUES(randstr(10,1000),randstr(10,1000),randstr(10,1000)); + INSERT INTO abc + SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc; + INSERT INTO abc + SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc; + INSERT INTO abc + SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc; + INSERT INTO abc + SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc; + INSERT INTO abc + SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc; + INSERT INTO abc + SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) FROM abc; + COMMIT; + } +} {} + +set tn 1 +foreach {::crashfile ::delay ::char} { + test.db 1 sequential + test.db 1 safe_append + test.db-journal 1 sequential + test.db-journal 1 safe_append + test.db-journal 2 safe_append + test.db-journal 2 sequential + test.db-journal 3 sequential + test.db-journal 3 safe_append +} { + for {set ii 0} {$ii < 100} {incr ii} { + set ::SQL [subst { + SELECT randstr($ii,$ii+10); + BEGIN; + DELETE FROM abc WHERE random()%5; + INSERT INTO abc + SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) + FROM abc + WHERE (random()%5)==0; + DELETE FROM def WHERE random()%5; + INSERT INTO def + SELECT randstr(10,1000),randstr(10,1000),randstr(10,1000) + FROM def + WHERE (random()%5)==0; + COMMIT; + }] + + do_test crash3-2.$tn.$ii { + crashsql -file $::crashfile -delay $::delay -char $::char $::SQL + db close + sqlite3 db test.db + execsql {PRAGMA integrity_check} + } {ok} + } + incr tn +} + +# The following block tests an interaction between IOCAP_ATOMIC and +# IOCAP_SEQUENTIAL. At one point, if both flags were set, small +# journal files that contained only a single page, but were required +# for some other reason (i.e. nTrunk) were not being written to +# disk. +# +for {set ii 0} {$ii < 10} {incr ii} { + db close + forcedelete test.db test.db-journal + crashsql -file test.db -char {sequential atomic} { + CREATE TABLE abc(a, b, c); + } + sqlite3 db test.db + do_test crash3-3.$ii { + execsql {PRAGMA integrity_check} + } {ok} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/crash4.test b/components/external/SQLite-3.8.1/test/crash4.test new file mode 100644 index 0000000000000000000000000000000000000000..f68caecdef3eeb4252907264201666a8ccd83388 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/crash4.test @@ -0,0 +1,102 @@ +# 2008 January 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains additional tests to verify that SQLite database +# file survive a power loss or OS crash. +# +# $Id: crash4.test,v 1.3 2008/01/16 17:46:38 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !crashtest { + finish_test + return +} + + +# A sequence of SQL commands: +# +set sql_cmd_list { + {CREATE TABLE a(id INTEGER, name CHAR(50))} + {INSERT INTO a(id,name) VALUES(1,'one')} + {INSERT INTO a(id,name) VALUES(2,'two')} + {INSERT INTO a(id,name) VALUES(3,'three')} + {INSERT INTO a(id,name) VALUES(4,'four')} + {INSERT INTO a(id,name) VALUES(5,'five')} + {INSERT INTO a(id,name) VALUES(6,'six')} + {INSERT INTO a(id,name) VALUES(7,'seven')} + {INSERT INTO a(id,name) VALUES(8,'eight')} + {INSERT INTO a(id,name) VALUES(9,'nine')} + {INSERT INTO a(id,name) VALUES(10,'ten')} + {UPDATE A SET name='new text for row 3' WHERE id=3} +} + +# Assume that a database is created by evaluating the SQL statements +# in $sql_cmd_list. Compute a set of checksums that capture the state +# of the database after each statement. Also include a checksum for +# the state of the database prior to any of these statements. +# +set crash4_cksum_set {} +lappend crash4_cksum_set [allcksum db] +foreach cmd $sql_cmd_list { + db eval $cmd + lappend crash4_cksum_set [allcksum db] +} + +# Run the sequence of SQL statements shown above repeatedly. +# Close and reopen the database right before the UPDATE statement. +# On each repetition, introduce database corruption typical of +# what might be seen in a power loss or OS crash. +# +# Slowly increase the delay before the crash, repeating the test +# over and over. Stop testing when the entire sequence of SQL +# statements runs to completing without hitting the crash. +# +for {set cnt 1; set fin 0} {!$fin} {incr cnt} { + db close + forcedelete test.db test.db-journal + do_test crash4-1.$cnt.1 { + set seed [expr {int(abs(rand()*10000))}] + set delay [expr {int($cnt/50)+1}] + set file [expr {($cnt&1)?"test.db":"test.db-journal"}] + set c [crashsql -delay $delay -file $file -seed $seed -tclbody { + db eval {CREATE TABLE a(id INTEGER, name CHAR(50))} + db eval {INSERT INTO a(id,name) VALUES(1,'one')} + db eval {INSERT INTO a(id,name) VALUES(2,'two')} + db eval {INSERT INTO a(id,name) VALUES(3,'three')} + db eval {INSERT INTO a(id,name) VALUES(4,'four')} + db eval {INSERT INTO a(id,name) VALUES(5,'five')} + db eval {INSERT INTO a(id,name) VALUES(6,'six')} + db eval {INSERT INTO a(id,name) VALUES(7,'seven')} + db eval {INSERT INTO a(id,name) VALUES(8,'eight')} + db eval {INSERT INTO a(id,name) VALUES(9,'nine')} + db eval {INSERT INTO a(id,name) VALUES(10,'ten')} + db close + sqlite3 db test.db + db eval {UPDATE A SET name='new text for row 3' WHERE id=3} + db close + } {}] + if {$c==[list 0 {}]} { + set ::fin 1 + set c [list 1 {child process exited abnormally}] + } + set c + } {1 {child process exited abnormally}} + sqlite3 db test.db + integrity_check crash4-1.$cnt.2 + do_test crash4-1.$cnt.3 { + set x [lsearch $::crash4_cksum_set [allcksum db]] + expr {$x>=0} + } {1} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/crash5.test b/components/external/SQLite-3.8.1/test/crash5.test new file mode 100644 index 0000000000000000000000000000000000000000..83d1647a84696d0a45b530efde4d08640b63b568 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/crash5.test @@ -0,0 +1,110 @@ + +# 2007 Aug 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests aspects of recovery from a malloc() failure +# in a CREATE INDEX statement. +# +# $Id: crash5.test,v 1.3 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Only run these tests if memory debugging is turned on. +# +ifcapable !memdebug||!crashtest||!memorymanage { + puts "Skipping crash5 tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + +db close + +for {set ii 0} {$ii < 10} {incr ii} { + for {set jj 50} {$jj < 100} {incr jj} { + + # Set up the database so that it is an auto-vacuum database + # containing a single table (root page 3) with a single row. + # The row has an overflow page (page 4). + forcedelete test.db test.db-journal + sqlite3 db test.db + set c [string repeat 3 1500] + db eval { + pragma auto_vacuum = 1; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES('1111111111', '2222222222', $c); + } + db close + + do_test crash5-$ii.$jj.1 { + crashsql -delay 1 -file test.db-journal -seed $ii -tclbody [join [list \ + [list set iFail $jj] { + sqlite3_crashparams 0 [file join [get_pwd] test.db-journal] + + # Begin a transaction and evaluate a "CREATE INDEX" statement + # with the iFail'th malloc() set to fail. This operation will + # have to move the current contents of page 4 (the overflow + # page) to make room for the new root page. The bug is that + # if malloc() fails at a particular point in sqlite3PagerMovepage(), + # sqlite mistakenly thinks that the page being moved (page 4) has + # been safely synced into the journal. If the page is written + # to later in the transaction, it may be written out to the database + # before the relevant part of the journal has been synced. + # + db eval BEGIN + sqlite3_memdebug_fail $iFail -repeat 0 + catch {db eval { CREATE UNIQUE INDEX i1 ON t1(a); }} msg + # puts "$n $msg ac=[sqlite3_get_autocommit db]" + + # If the transaction is still active (it may not be if the malloc() + # failure occurred in the OS layer), write to the database. Make sure + # page 4 is among those written. + # + if {![sqlite3_get_autocommit db]} { + db eval { + DELETE FROM t1; -- This will put page 4 on the free list. + INSERT INTO t1 VALUES('111111111', '2222222222', '33333333'); + INSERT INTO t1 SELECT * FROM t1; -- 2 + INSERT INTO t1 SELECT * FROM t1; -- 4 + INSERT INTO t1 SELECT * FROM t1; -- 8 + INSERT INTO t1 SELECT * FROM t1; -- 16 + INSERT INTO t1 SELECT * FROM t1; -- 32 + INSERT INTO t1 SELECT * FROM t1 WHERE rowid%2; -- 48 + } + } + + # If the right malloc() failed during the 'CREATE INDEX' above and + # the transaction was not rolled back, then the sqlite cache now + # has a dirty page 4 that it incorrectly believes is already safely + # in the synced part of the journal file. When + # sqlite3_release_memory() is called sqlite tries to free memory + # by writing page 4 out to the db file. If it crashes later on, + # before syncing the journal... Corruption! + # + sqlite3_crashparams 1 [file join [get_pwd] test.db-journal] + sqlite3_release_memory 8092 + }]] {} + expr 1 + } {1} + + sqlite3 db test.db + do_test crash5-$ii.$jj.2 { + db eval {pragma integrity_check} + } {ok} + do_test crash5-$ii.$jj.3 { + db eval {SELECT * FROM t1} + } [list 1111111111 2222222222 $::c] + db close + } +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/crash6.test b/components/external/SQLite-3.8.1/test/crash6.test new file mode 100644 index 0000000000000000000000000000000000000000..69c19464b3f4ad55318cd98280f24322b6492557 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/crash6.test @@ -0,0 +1,118 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file tests that rollback journals for databases that use a +# page-size other than the default page-size can be rolled back Ok. +# +# $Id: crash6.test,v 1.2 2008/04/14 15:27:19 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !crashtest { + finish_test + return +} + +for {set ii 0} {$ii < 10} {incr ii} { + catch {db close} + forcedelete test.db test.db-journal + crashsql -delay 2 -file test.db { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size=4096; + BEGIN; + CREATE TABLE abc AS SELECT 1 AS a, 2 AS b, 3 AS c; + COMMIT; + BEGIN; + CREATE TABLE def AS SELECT 1 AS d, 2 AS e, 3 AS f; + COMMIT; + } + sqlite3 db test.db + integrity_check crash6-1.$ii +} + +for {set ii 0} {$ii < 10} {incr ii} { + catch {db close} + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size=2048; + BEGIN; + CREATE TABLE abc AS SELECT 1 AS a, 2 AS b, 3 AS c; + COMMIT; + } + db close + crashsql -delay 1 -file test.db { + INSERT INTO abc VALUES(5, 6, 7); + } + sqlite3 db test.db + integrity_check crash6-2.$ii +} + +proc signature {} { + return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}] +} + +# Test case for crashing during database sync with page-size values +# from 1024 to 8192. +# +for {set ii 0} {$ii < 30} {incr ii} { + db close + forcedelete test.db + sqlite3 db test.db + + set pagesize [expr 1024 << ($ii % 4)] + if {$pagesize>$::SQLITE_MAX_PAGE_SIZE} { + set pagesize $::SQLITE_MAX_PAGE_SIZE + } + do_test crash6-3.$ii.0 { + execsql "pragma page_size = $pagesize" + execsql "pragma page_size" + } $pagesize + + do_test crash6-3.$ii.1 { + + execsql BEGIN + execsql {CREATE TABLE abc(a, b, c)} + for {set n 0} {$n < 1000} {incr n} { + execsql "INSERT INTO abc VALUES($n, [expr 2*$n], [expr 3*$n])" + } + execsql { + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + } + execsql COMMIT + expr ([file size test.db] / 1024) > 450 + } {1} + + set sig [signature] + db close + + do_test crash6-3.$ii.2 { + crashsql -file test.db " + BEGIN; + SELECT random() FROM abc LIMIT $ii; + INSERT INTO abc SELECT randstr(10,10), 0, 0 FROM abc WHERE random()%2==0; + DELETE FROM abc WHERE random()%2!=0; + COMMIT; + " + } {1 {child process exited abnormally}} + + do_test crash6-3.$ii.3 { + sqlite3 db test.db + signature + } $sig +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/crash7.test b/components/external/SQLite-3.8.1/test/crash7.test new file mode 100644 index 0000000000000000000000000000000000000000..482999cbfd9575921d5e6f5336f04e3143db101d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/crash7.test @@ -0,0 +1,116 @@ +# 2008 March 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: crash7.test,v 1.1 2008/04/03 14:36:26 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix crash7 + +ifcapable !crashtest { + finish_test + return +} + +proc signature {} { + return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}] +} + +foreach f [list test.db test.db-journal] { + for {set ii 1} {$ii < 64} {incr ii} { + db close + delete_file test.db + sqlite3 db test.db + + set from_size [expr 1024 << ($ii&3)] + set to_size [expr 1024 << (($ii>>2)&3)] + + execsql " + PRAGMA page_size = $from_size; + BEGIN; + CREATE TABLE abc(a PRIMARY KEY, b, c); + INSERT INTO abc VALUES(randomblob(100), randomblob(200), randomblob(1000)); + INSERT INTO abc + SELECT randomblob(1000), randomblob(200), randomblob(100) + FROM abc; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc WHERE [expr $ii&16]; + INSERT INTO abc + SELECT randomblob(25), randomblob(45), randomblob(9456) + FROM abc WHERE [expr $ii&32]; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc WHERE [expr $ii&8]; + INSERT INTO abc + SELECT randomblob(25), randomblob(45), randomblob(9456) + FROM abc WHERE [expr $ii&4]; + COMMIT; + " + + set sig [signature] + db close + + do_test crash7-1.$ii.crash { + crashsql -file $f " + PRAGMA page_size = $to_size; + VACUUM; + " + } {1 {child process exited abnormally}} + + sqlite3 db test.db + integrity_check crash7-1.$ii.integrity + } +} + +db close +forcedelete test.db +sqlite3 db test.db +do_execsql_test 2.0 { + CREATE TABLE t1(a, b, UNIQUE(a, b)); + INSERT INTO t1 VALUES(randomblob(100), randomblob(100)); + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(100) FROM t1; + DELETE FROM t1 WHERE rowid%2; +} +db_save_and_close + +for {set i 0} {$i < 20} {incr i} { + db_restore_and_reopen + do_test 2.[expr $i+1].1 { + crashsql -file test.db -seed $i {VACUUM} + } {1 {child process exited abnormally}} + do_execsql_test 2.[expr $i+1].2 { PRAGMA integrity_check } {ok} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/crash8.test b/components/external/SQLite-3.8.1/test/crash8.test new file mode 100644 index 0000000000000000000000000000000000000000..8bc258651a3d1f58cd53f2b9887a21e1b51458a8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/crash8.test @@ -0,0 +1,402 @@ +# 2009 January 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test verifies a couple of specific potential data corruption +# scenarios involving crashes or power failures. +# +# Later: Also, some other specific scenarios required for coverage +# testing that do not lead to corruption. +# +# $Id: crash8.test,v 1.4 2009/01/11 00:44:48 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !crashtest { + finish_test + return +} + +do_test crash8-1.1 { + execsql { + PRAGMA auto_vacuum=OFF; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 VALUES(2, randstr(1000,1000)); + INSERT INTO t1 VALUES(3, randstr(1000,1000)); + INSERT INTO t1 VALUES(4, randstr(1000,1000)); + INSERT INTO t1 VALUES(5, randstr(1000,1000)); + INSERT INTO t1 VALUES(6, randstr(1000,1000)); + CREATE TABLE t2(a, b); + CREATE TABLE t3(a, b); + CREATE TABLE t4(a, b); + CREATE TABLE t5(a, b); + CREATE TABLE t6(a, b); + CREATE TABLE t7(a, b); + CREATE TABLE t8(a, b); + CREATE TABLE t9(a, b); + CREATE TABLE t10(a, b); + PRAGMA integrity_check + } +} {ok} + + +# Potential corruption scenario 1. A second process opens the database +# and modifies a large portion of it. It then opens a second transaction +# and modifies a small part of the database, but crashes before it commits +# the transaction. +# +# When the first process accessed the database again, it was rolling back +# the aborted transaction, but was not purging its in-memory cache (which +# was loaded before the second process made its first, successful, +# modification). Producing an inconsistent cache. +# +do_test crash8-1.2 { + crashsql -delay 2 -file test.db { + PRAGMA cache_size = 10; + UPDATE t1 SET b = randstr(1000,1000); + INSERT INTO t9 VALUES(1, 2); + } +} {1 {child process exited abnormally}} +do_test crash8-1.3 { + execsql {PRAGMA integrity_check} +} {ok} + +# Potential corruption scenario 2. The second process, operating in +# persistent-journal mode, makes a large change to the database file +# with a small in-memory cache. Such that more than one journal-header +# was written to the file. It then opens a second transaction and makes +# a smaller change that requires only a single journal-header to be +# written to the journal file. The second change is such that the +# journal content written to the persistent journal file exactly overwrites +# the first journal-header and set of subsequent records written by the +# first, successful, change. The second process crashes before it can +# commit its second change. +# +# When the first process accessed the database again, it was rolling back +# the second aborted transaction, then continuing to rollback the second +# and subsequent journal-headers written by the first, successful, change. +# Database corruption. +# +do_test crash8.2.1 { + crashsql -delay 2 -file test.db { + PRAGMA journal_mode = persist; + PRAGMA cache_size = 10; + UPDATE t1 SET b = randstr(1000,1000); + PRAGMA cache_size = 100; + BEGIN; + INSERT INTO t2 VALUES('a', 'b'); + INSERT INTO t3 VALUES('a', 'b'); + INSERT INTO t4 VALUES('a', 'b'); + INSERT INTO t5 VALUES('a', 'b'); + INSERT INTO t6 VALUES('a', 'b'); + INSERT INTO t7 VALUES('a', 'b'); + INSERT INTO t8 VALUES('a', 'b'); + INSERT INTO t9 VALUES('a', 'b'); + INSERT INTO t10 VALUES('a', 'b'); + COMMIT; + } +} {1 {child process exited abnormally}} + +do_test crash8-2.3 { + execsql {PRAGMA integrity_check} +} {ok} + +proc read_file {zFile} { + set fd [open $zFile] + fconfigure $fd -translation binary + set zData [read $fd] + close $fd + return $zData +} +proc write_file {zFile zData} { + set fd [open $zFile w] + fconfigure $fd -translation binary + puts -nonewline $fd $zData + close $fd +} + +# The following tests check that SQLite will not roll back a hot-journal +# file if the sector-size field in the first journal file header is +# suspect. Definition of suspect: +# +# a) Not a power of 2, or (crash8-3.5) +# b) Greater than 0x01000000 (16MB), or (crash8-3.6) +# c) Less than 512. (crash8-3.7) +# +# Also test that SQLite will not rollback a hot-journal file with a +# suspect page-size. In this case "suspect" means: +# +# a) Not a power of 2, or +# b) Less than 512, or +# c) Greater than SQLITE_MAX_PAGE_SIZE +# +do_test crash8-3.1 { + list [file exists test.db-joural] [file exists test.db] +} {0 1} +do_test crash8-3.2 { + execsql { + PRAGMA synchronous = off; + BEGIN; + DELETE FROM t1; + SELECT count(*) FROM t1; + } +} {0} +do_test crash8-3.3 { + set zJournal [read_file test.db-journal] + execsql { + COMMIT; + SELECT count(*) FROM t1; + } +} {0} +do_test crash8-3.4 { + binary scan [string range $zJournal 20 23] I nSector + set nSector +} {512} + +do_test crash8-3.5 { + set zJournal2 [string replace $zJournal 20 23 [binary format I 513]] + write_file test.db-journal $zJournal2 + + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check + } +} {0 ok} +do_test crash8-3.6 { + set zJournal2 [string replace $zJournal 20 23 [binary format I 0x2000000]] + write_file test.db-journal $zJournal2 + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check + } +} {0 ok} +do_test crash8-3.7 { + set zJournal2 [string replace $zJournal 20 23 [binary format I 256]] + write_file test.db-journal $zJournal2 + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check + } +} {0 ok} + +do_test crash8-3.8 { + set zJournal2 [string replace $zJournal 24 27 [binary format I 513]] + write_file test.db-journal $zJournal2 + + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check + } +} {0 ok} +do_test crash8-3.9 { + set big [expr $SQLITE_MAX_PAGE_SIZE * 2] + set zJournal2 [string replace $zJournal 24 27 [binary format I $big]] + write_file test.db-journal $zJournal2 + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check + } +} {0 ok} +do_test crash8-3.10 { + set zJournal2 [string replace $zJournal 24 27 [binary format I 256]] + write_file test.db-journal $zJournal2 + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check + } +} {0 ok} + +do_test crash8-3.11 { + set fd [open test.db-journal w] + fconfigure $fd -translation binary + puts -nonewline $fd $zJournal + close $fd + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check + } +} {6 ok} + + +# If a connection running in persistent-journal mode is part of a +# multi-file transaction, it must ensure that the master-journal name +# appended to the journal file contents during the commit is located +# at the end of the physical journal file. If there was already a +# large journal file allocated at the start of the transaction, this +# may mean truncating the file so that the master journal name really +# is at the physical end of the file. +# +# This block of tests test that SQLite correctly truncates such +# journal files, and that the results behave correctly if a hot-journal +# rollback occurs. +# +ifcapable pragma { + reset_db + forcedelete test2.db + + do_test crash8-4.1 { + execsql { + PRAGMA journal_mode = persist; + CREATE TABLE ab(a, b); + INSERT INTO ab VALUES(0, 'abc'); + INSERT INTO ab VALUES(1, NULL); + INSERT INTO ab VALUES(2, NULL); + INSERT INTO ab VALUES(3, NULL); + INSERT INTO ab VALUES(4, NULL); + INSERT INTO ab VALUES(5, NULL); + INSERT INTO ab VALUES(6, NULL); + UPDATE ab SET b = randstr(1000,1000); + ATTACH 'test2.db' AS aux; + PRAGMA aux.journal_mode = persist; + CREATE TABLE aux.ab(a, b); + INSERT INTO aux.ab SELECT * FROM main.ab; + + UPDATE aux.ab SET b = randstr(1000,1000) WHERE a>=1; + UPDATE ab SET b = randstr(1000,1000) WHERE a>=1; + } + list [file exists test.db-journal] [file exists test2.db-journal] + } {1 1} + + do_test crash8-4.2 { + execsql { + BEGIN; + UPDATE aux.ab SET b = 'def' WHERE a = 0; + UPDATE main.ab SET b = 'def' WHERE a = 0; + COMMIT; + } + } {} + + do_test crash8-4.3 { + execsql { + UPDATE aux.ab SET b = randstr(1000,1000) WHERE a>=1; + UPDATE ab SET b = randstr(1000,1000) WHERE a>=1; + } + } {} + + set contents_main [db eval {SELECT b FROM main.ab WHERE a = 1}] + set contents_aux [db eval {SELECT b FROM aux.ab WHERE a = 1}] + + do_test crash8-4.4 { + crashsql -file test2.db -delay 1 { + ATTACH 'test2.db' AS aux; + BEGIN; + UPDATE aux.ab SET b = 'ghi' WHERE a = 0; + UPDATE main.ab SET b = 'ghi' WHERE a = 0; + COMMIT; + } + } {1 {child process exited abnormally}} + + do_test crash8-4.5 { + list [file exists test.db-journal] [file exists test2.db-journal] + } {1 1} + + do_test crash8-4.6 { + execsql { + SELECT b FROM main.ab WHERE a = 0; + SELECT b FROM aux.ab WHERE a = 0; + } + } {def def} + + do_test crash8-4.7 { + crashsql -file test2.db -delay 1 { + ATTACH 'test2.db' AS aux; + BEGIN; + UPDATE aux.ab SET b = 'jkl' WHERE a = 0; + UPDATE main.ab SET b = 'jkl' WHERE a = 0; + COMMIT; + } + } {1 {child process exited abnormally}} + + do_test crash8-4.8 { + set fd [open test.db-journal] + fconfigure $fd -translation binary + seek $fd -16 end + binary scan [read $fd 4] I len + + seek $fd [expr {-1 * ($len + 16)}] end + set zMasterJournal [read $fd $len] + close $fd + + file exists $zMasterJournal + } {1} + + do_test crash8-4.9 { + execsql { SELECT b FROM aux.ab WHERE a = 0 } + } {def} + + do_test crash8-4.10 { + delete_file $zMasterJournal + execsql { SELECT b FROM main.ab WHERE a = 0 } + } {jkl} +} + +for {set i 1} {$i < 10} {incr i} { + catch { db close } + forcedelete test.db test.db-journal + sqlite3 db test.db + do_test crash8-5.$i.1 { + execsql { + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 64 rows */ + } + crashsql -file test.db -delay [expr ($::i%2) + 1] { + PRAGMA cache_size = 10; + BEGIN; + UPDATE t1 SET x = randomblob(900); + ROLLBACK; + INSERT INTO t1 VALUES(randomblob(900)); + } + execsql { PRAGMA integrity_check } + } {ok} + + catch { db close } + forcedelete test.db test.db-journal + sqlite3 db test.db + do_test crash8-5.$i.2 { + execsql { + PRAGMA cache_size = 10; + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 64 rows */ + BEGIN; + UPDATE t1 SET x = randomblob(900); + } + forcedelete testX.db testX.db-journal testX.db-wal + forcecopy test.db testX.db + forcecopy test.db-journal testX.db-journal + db close + + crashsql -file test.db -delay [expr ($::i%2) + 1] { + SELECT * FROM sqlite_master; + INSERT INTO t1 VALUES(randomblob(900)); + } + + sqlite3 db2 testX.db + execsql { PRAGMA integrity_check } db2 + } {ok} +} +catch {db2 close} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/crashtest1.c b/components/external/SQLite-3.8.1/test/crashtest1.c new file mode 100644 index 0000000000000000000000000000000000000000..1f7035d18ea78d137272a6d76edbe1909549c414 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/crashtest1.c @@ -0,0 +1,96 @@ +/* +** This program tests the ability of SQLite database to recover from a crash. +** This program runs under Unix only, but the results are applicable to all +** systems. +** +** The main process first constructs a test database, then starts creating +** subprocesses that write to that database. Each subprocess is killed off, +** without a chance to clean up its database connection, after a random +** delay. This killing of the subprocesses simulates a crash or power +** failure. The next subprocess to open the database should rollback +** whatever operation was in process at the time of the simulated crash. +** +** If any problems are encountered, an error is reported and the test stops. +** If no problems are seen after a large number of tests, we assume that +** the rollback mechanism is working. +*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include "sqlite.h" + +static void do_some_sql(int parent){ + char *zErr; + int rc = SQLITE_OK; + sqlite *db; + int cnt = 0; + static char zBig[] = + "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + if( access("./test.db-journal",0)==0 ){ + /*printf("pid %d: journal exists. rollback will be required\n",getpid());*/ unlink("test.db-saved"); + system("cp test.db test.db-saved"); + unlink("test.db-journal-saved"); + system("cp test.db-journal test.db-journal-saved"); + } + db = sqlite_open("./test.db", 0, &zErr); + if( db==0 ){ + printf("ERROR: %s\n", zErr); + if( strcmp(zErr,"database disk image is malformed")==0 ){ + kill(parent, SIGKILL); + } + exit(1); + } + srand(getpid()); + while( rc==SQLITE_OK ){ + cnt++; + rc = sqlite_exec_printf(db, + "INSERT INTO t1 VALUES(%d,'%d%s')", 0, 0, &zErr, + rand(), rand(), zBig); + } + if( rc!=SQLITE_OK ){ + printf("ERROR #%d: %s\n", rc, zErr); + if( rc==SQLITE_CORRUPT ){ + kill(parent, SIGKILL); + } + } + printf("pid %d: cnt=%d\n", getpid(), cnt); +} + + +int main(int argc, char **argv){ + int i; + sqlite *db; + char *zErr; + int status; + int parent = getpid(); + + unlink("test.db"); + unlink("test.db-journal"); + db = sqlite_open("test.db", 0, &zErr); + if( db==0 ){ + printf("Cannot initialize: %s\n", zErr); + return 1; + } + sqlite_exec(db, "CREATE TABLE t1(a,b)", 0, 0, 0); + sqlite_close(db); + for(i=0; i<10000; i++){ + int pid = fork(); + if( pid==0 ){ + sched_yield(); + do_some_sql(parent); + return 0; + } + printf("test %d, pid=%d\n", i, pid); + usleep(rand()%10000 + 1000); + kill(pid, SIGKILL); + waitpid(pid, &status, 0); + } + return 0; +} diff --git a/components/external/SQLite-3.8.1/test/createtab.test b/components/external/SQLite-3.8.1/test/createtab.test new file mode 100644 index 0000000000000000000000000000000000000000..01e0b6122ec45ebf70263658481075fc8833a098 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/createtab.test @@ -0,0 +1,146 @@ +# 2007 May 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that it is OK to create new tables +# and indices while creating existing tables and indices. +# +# $Id: createtab.test,v 1.3 2007/09/12 17:01:45 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable autovacuum { + set upperBound 2 +} else { + set upperBound 0 +} + +# Run these tests for all possible values of autovacuum. +# +for {set av 0} {$av<=$upperBound} {incr av} { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + + # Create a table that spans multiple pages. It is important + # that part of the database be in pages beyond the root page. + # + do_test createtab-$av.1 { + execsql "PRAGMA auto_vacuum=$av" + execsql { + PRAGMA page_size=1024; + CREATE TABLE t1(x INTEGER PRIMARY KEY, y); + INSERT INTO t1 VALUES(1, hex(randomblob(200))); + INSERT INTO t1 VALUES(2, hex(randomblob(200))); + INSERT INTO t1 VALUES(3, hex(randomblob(200))); + INSERT INTO t1 VALUES(4, hex(randomblob(200))); + SELECT count(*) FROM t1; + } + } {4} + + set isUtf16 0 + ifcapable utf16 { + set isUtf16 [expr {[execsql {PRAGMA encoding}] != "UTF-8"}] + } + + do_test createtab-$av.2 { + file size test.db + } [expr {1024*(4+($av!=0)+(${isUtf16}*2))}] + + # Start reading the table + # + do_test createtab-$av.3 { + set STMT [sqlite3_prepare db {SELECT x FROM t1} -1 TAIL] + sqlite3_step $STMT + } {SQLITE_ROW} + do_test createtab-$av.4 { + sqlite3_column_int $STMT 0 + } {1} + + # While still reading the table, create a new table. + # + do_test createtab-$av.5 { + execsql { + CREATE TABLE t2(a,b); + INSERT INTO t2 VALUES(1,2); + SELECT * FROM t2; + } + } {1 2} + + # Continue reading the original table. + # + do_test createtab-$av.6 { + sqlite3_column_int $STMT 0 + } {1} + do_test createtab-$av.7 { + sqlite3_step $STMT + } {SQLITE_ROW} + do_test createtab-$av.8 { + sqlite3_column_int $STMT 0 + } {2} + + # Do another cycle of creating a new database table while contining + # to read the original table. + # + do_test createtab-$av.11 { + execsql { + CREATE TABLE t3(a,b); + INSERT INTO t3 VALUES(4,5); + SELECT * FROM t3; + } + } {4 5} + do_test createtab-$av.12 { + sqlite3_column_int $STMT 0 + } {2} + do_test createtab-$av.13 { + sqlite3_step $STMT + } {SQLITE_ROW} + do_test createtab-$av.14 { + sqlite3_column_int $STMT 0 + } {3} + + # One more cycle. + # + do_test createtab-$av.21 { + execsql { + CREATE TABLE t4(a,b); + INSERT INTO t4 VALUES('abc','xyz'); + SELECT * FROM t4; + } + } {abc xyz} + do_test createtab-$av.22 { + sqlite3_column_int $STMT 0 + } {3} + do_test createtab-$av.23 { + sqlite3_step $STMT + } {SQLITE_ROW} + do_test createtab-$av.24 { + sqlite3_column_int $STMT 0 + } {4} + + # Finish reading. Do an integrity check on the database. + # + do_test createtab-$av.30 { + sqlite3_step $STMT + } {SQLITE_DONE} + do_test createtab-$av.31 { + sqlite3_finalize $STMT + } {SQLITE_OK} + do_test createtab-$av.32 { + execsql { + SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1 + } + } {t1 t2 t3 t4} + integrity_check createtab-$av.40 + +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/cse.test b/components/external/SQLite-3.8.1/test/cse.test new file mode 100644 index 0000000000000000000000000000000000000000..57cdef5acc2c27edc7510b1c62e3d97a1fb25ea8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/cse.test @@ -0,0 +1,160 @@ +# 2008 April 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test cases designed to exercise and verify the logic for +# factoring constant expressions out of loops and for +# common subexpression eliminations. +# +# $Id: cse.test,v 1.6 2008/08/04 03:51:24 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test cse-1.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, d, e, f); + INSERT INTO t1 VALUES(1,11,12,13,14,15); + INSERT INTO t1 VALUES(2,21,22,23,24,25); + } + execsql { + SELECT b, -b, ~b, NOT b, NOT NOT b, b-b, b+b, b*b, b/b, b FROM t1 + } +} {11 -11 -12 0 1 0 22 121 1 11 21 -21 -22 0 1 0 42 441 1 21} +do_test cse-1.2 { + execsql { + SELECT b, b%b, b==b, b!=b, b49} {set r [expr {99-$r}]} + lappend colset a$j a$r + lappend answer $j $r + } + set sql "SELECT [join $colset ,] FROM t2" + do_test cse-2.2.$i { + # explain $::sql + execsql $::sql + } $answer +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/ctime.test b/components/external/SQLite-3.8.1/test/ctime.test new file mode 100644 index 0000000000000000000000000000000000000000..e4cb156168be57f9208e8bba8f247cbd740dac6d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/ctime.test @@ -0,0 +1,227 @@ +# 2009 February 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the compile time diagnostic +# functions. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Test organization: +# +# ctime-1.*: Test pragma support. +# ctime-2.*: Test function support. +# + +ifcapable !pragma||!compileoption_diags { + finish_test + return +} + +##################### +# ctime-1.*: Test pragma support. + +do_test ctime-1.1.1 { + catchsql { + PRAGMA compile_options(); + } +} {1 {near ")": syntax error}} +do_test ctime-1.1.2 { + catchsql { + PRAGMA compile_options(NULL); + } +} {1 {near "NULL": syntax error}} +do_test ctime-1.1.3 { + catchsql { + PRAGMA compile_options *; + } +} {1 {near "*": syntax error}} + +do_test ctime-1.2.1 { + set ans [ catchsql { + PRAGMA compile_options; + } ] + list [ lindex $ans 0 ] +} {0} +# the results should be in sorted order already +do_test ctime-1.2.2 { + set ans [ catchsql { + PRAGMA compile_options; + } ] + list [ lindex $ans 0 ] [ expr { [lsort [lindex $ans 1]]==[lindex $ans 1] } ] +} {0 1} + +# SQLITE_THREADSAFE should pretty much always be defined +# one way or the other, and it must have a value of 0 or 1. +do_test ctime-1.4.1 { + catchsql { + SELECT sqlite_compileoption_used('SQLITE_THREADSAFE'); + } +} {0 1} +do_test ctime-1.4.2 { + catchsql { + SELECT sqlite_compileoption_used('THREADSAFE'); + } +} {0 1} +do_test ctime-1.4.3 { + catchsql { + SELECT sqlite_compileoption_used("THREADSAFE"); + } +} {0 1} + +do_test ctime-1.5 { + set ans1 [ catchsql { + SELECT sqlite_compileoption_used('THREADSAFE=0'); + } ] + set ans2 [ catchsql { + SELECT sqlite_compileoption_used('THREADSAFE=1'); + } ] + set ans3 [ catchsql { + SELECT sqlite_compileoption_used('THREADSAFE=2'); + } ] + lsort [ list $ans1 $ans2 $ans3 ] +} {{0 0} {0 0} {0 1}} + +do_test ctime-1.6 { + execsql { + SELECT sqlite_compileoption_used('THREADSAFE='); + } +} {0} + +do_test ctime-1.7.1 { + execsql { + SELECT sqlite_compileoption_used('SQLITE_OMIT_COMPILEOPTION_DIAGS'); + } +} {0} +do_test ctime-1.7.2 { + execsql { + SELECT sqlite_compileoption_used('OMIT_COMPILEOPTION_DIAGS'); + } +} {0} + +##################### +# ctime-2.*: Test function support. + +do_test ctime-2.1.1 { + catchsql { + SELECT sqlite_compileoption_used(); + } +} {1 {wrong number of arguments to function sqlite_compileoption_used()}} +do_test ctime-2.1.2 { + catchsql { + SELECT sqlite_compileoption_used(NULL); + } +} {0 {{}}} +do_test ctime-2.1.3 { + catchsql { + SELECT sqlite_compileoption_used(""); + } +} {0 0} +do_test ctime-2.1.4 { + catchsql { + SELECT sqlite_compileoption_used(''); + } +} {0 0} +do_test ctime-2.1.5 { + catchsql { + SELECT sqlite_compileoption_used(foo); + } +} {1 {no such column: foo}} +do_test ctime-2.1.6 { + catchsql { + SELECT sqlite_compileoption_used('THREADSAFE', 0); + } +} {1 {wrong number of arguments to function sqlite_compileoption_used()}} +do_test ctime-2.1.7 { + catchsql { + SELECT sqlite_compileoption_used(0); + } +} {0 0} +do_test ctime-2.1.8 { + catchsql { + SELECT sqlite_compileoption_used('0'); + } +} {0 0} +do_test ctime-2.1.9 { + catchsql { + SELECT sqlite_compileoption_used(1.0); + } +} {0 0} + +do_test ctime-2.2.1 { + catchsql { + SELECT sqlite_compileoption_get(); + } +} {1 {wrong number of arguments to function sqlite_compileoption_get()}} +do_test ctime-2.2.2 { + catchsql { + SELECT sqlite_compileoption_get(0, 0); + } +} {1 {wrong number of arguments to function sqlite_compileoption_get()}} + +# This assumes there is at least 1 compile time option +# (see SQLITE_THREADSAFE above). +do_test ctime-2.3 { + catchsql { + SELECT sqlite_compileoption_used(sqlite_compileoption_get(0)); + } +} {0 1} + +# This assumes there is at least 1 compile time option +# (see SQLITE_THREADSAFE above). +do_test ctime-2.4 { + set ans [ catchsql { + SELECT sqlite_compileoption_get(0); + } ] + list [lindex $ans 0] +} {0} + +# Get the list of defines using the pragma, +# then try querying each one with the functions. +set ans [ catchsql { + PRAGMA compile_options; +} ] +set opts [ lindex $ans 1 ] +set tc 1 +foreach opt $opts { + do_test ctime-2.5.$tc { + set N [ expr {$tc-1} ] + set ans1 [ catchsql { + SELECT sqlite_compileoption_get($N); + } ] + set ans2 [ catchsql { + SELECT sqlite_compileoption_used($opt); + } ] + list [ lindex $ans1 0 ] [ expr { [lindex $ans1 1]==$opt } ] \ + [ expr { $ans2 } ] + } {0 1 {0 1}} + incr tc 1 +} +# test 1 past array bounds +do_test ctime-2.5.$tc { + set N [ expr {$tc-1} ] + set ans [ catchsql { + SELECT sqlite_compileoption_get($N); + } ] +} {0 {{}}} +incr tc 1 +# test 1 before array bounds (N=-1) +do_test ctime-2.5.$tc { + set N -1 + set ans [ catchsql { + SELECT sqlite_compileoption_get($N); + } ] +} {0 {{}}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/date.test b/components/external/SQLite-3.8.1/test/date.test new file mode 100644 index 0000000000000000000000000000000000000000..b1d1c677c1c17dba6432e31bf12e221cf4aaf051 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/date.test @@ -0,0 +1,554 @@ +# 2003 October 31 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing date and time functions. +# +# $Id: date.test,v 1.34 2009/04/16 12:58:03 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Skip this whole file if date and time functions are omitted +# at compile-time +# +ifcapable {!datetime} { + finish_test + return +} + +proc datetest {tnum expr result} { + do_test date-$tnum [subst { + execsql "SELECT coalesce($expr,'NULL')" + }] [list $result] +} +set tcl_precision 15 +datetest 1.1 julianday('2000-01-01') 2451544.5 +datetest 1.2 julianday('1970-01-01') 2440587.5 +datetest 1.3 julianday('1910-04-20') 2418781.5 +datetest 1.4 julianday('1986-02-09') 2446470.5 +datetest 1.5 julianday('12:00:00') 2451545.0 +datetest 1.6 {julianday('2000-01-01 12:00:00')} 2451545.0 +datetest 1.7 {julianday('2000-01-01 12:00')} 2451545.0 +datetest 1.8 julianday('bogus') NULL +datetest 1.9 julianday('1999-12-31') 2451543.5 +datetest 1.10 julianday('1999-12-32') NULL +datetest 1.11 julianday('1999-13-01') NULL +datetest 1.12 julianday('2003-02-31') 2452701.5 +datetest 1.13 julianday('2003-03-03') 2452701.5 +datetest 1.14 julianday('+2000-01-01') NULL +datetest 1.15 julianday('200-01-01') NULL +datetest 1.16 julianday('2000-1-01') NULL +datetest 1.17 julianday('2000-01-1') NULL +datetest 1.18.1 {julianday('2000-01-01 12:00:00')} 2451545.0 +datetest 1.18.2 {julianday('2000-01-01T12:00:00')} 2451545.0 +datetest 1.18.3 {julianday('2000-01-01 T12:00:00')} 2451545.0 +datetest 1.18.4 {julianday('2000-01-01T 12:00:00')} 2451545.0 +datetest 1.18.4 {julianday('2000-01-01 T 12:00:00')} 2451545.0 +datetest 1.19 {julianday('2000-01-01 12:00:00.1')} 2451545.00000116 +datetest 1.20 {julianday('2000-01-01 12:00:00.01')} 2451545.00000012 +datetest 1.21 {julianday('2000-01-01 12:00:00.001')} 2451545.00000001 +datetest 1.22 {julianday('2000-01-01 12:00:00.')} NULL +datetest 1.23 julianday(12345.6) 12345.6 +datetest 1.23b julianday('12345.6') 12345.6 +datetest 1.24 {julianday('2001-01-01 12:00:00 bogus')} NULL +datetest 1.25 {julianday('2001-01-01 bogus')} NULL +datetest 1.26 {julianday('2001-01-01 12:60:00')} NULL +datetest 1.27 {julianday('2001-01-01 12:59:60')} NULL +datetest 1.28 {julianday('2001-00-01')} NULL +datetest 1.29 {julianday('2001-01-00')} NULL + +datetest 2.1 datetime(0,'unixepoch') {1970-01-01 00:00:00} +datetest 2.1b datetime(0,'unixepoc') NULL +datetest 2.1c datetime(0,'unixepochx') NULL +datetest 2.1d datetime('2003-10-22','unixepoch') NULL +datetest 2.2 datetime(946684800,'unixepoch') {2000-01-01 00:00:00} +datetest 2.2b datetime('946684800','unixepoch') {2000-01-01 00:00:00} +for {set i 0} {$i<1000} {incr i} { + set sql [format {strftime('%%H:%%M:%%f',1237962480.%03d,'unixepoch')} $i] + set res [format {06:28:00.%03d} $i] + datetest 2.2c-$i $sql $res +} +datetest 2.3 {date('2003-10-22','weekday 0')} 2003-10-26 +datetest 2.4 {date('2003-10-22','weekday 1')} 2003-10-27 +datetest 2.4a {date('2003-10-22','weekday 1')} 2003-10-27 +datetest 2.4b {date('2003-10-22','weekday 1x')} NULL +datetest 2.4c {date('2003-10-22','weekday -1')} NULL +datetest 2.4d {date('2003-10-22','weakday 1x')} NULL +datetest 2.4e {date('2003-10-22','weekday ')} NULL +datetest 2.5 {date('2003-10-22','weekday 2')} 2003-10-28 +datetest 2.6 {date('2003-10-22','weekday 3')} 2003-10-22 +datetest 2.7 {date('2003-10-22','weekday 4')} 2003-10-23 +datetest 2.8 {date('2003-10-22','weekday 5')} 2003-10-24 +datetest 2.9 {date('2003-10-22','weekday 6')} 2003-10-25 +datetest 2.10 {date('2003-10-22','weekday 7')} NULL +datetest 2.11 {date('2003-10-22','weekday 5.5')} NULL +datetest 2.12 {datetime('2003-10-22 12:34','weekday 0')} {2003-10-26 12:34:00} +datetest 2.13 {datetime('2003-10-22 12:34','start of month')} \ + {2003-10-01 00:00:00} +datetest 2.14 {datetime('2003-10-22 12:34','start of year')} \ + {2003-01-01 00:00:00} +datetest 2.15 {datetime('2003-10-22 12:34','start of day')} \ + {2003-10-22 00:00:00} +datetest 2.15a {datetime('2003-10-22 12:34','start of')} NULL +datetest 2.15b {datetime('2003-10-22 12:34','start of bogus')} NULL +datetest 2.16 time('12:34:56.43') 12:34:56 +datetest 2.17 {datetime('2003-10-22 12:34','1 day')} {2003-10-23 12:34:00} +datetest 2.18 {datetime('2003-10-22 12:34','+1 day')} {2003-10-23 12:34:00} +datetest 2.19 {datetime('2003-10-22 12:34','+1.25 day')} {2003-10-23 18:34:00} +datetest 2.20 {datetime('2003-10-22 12:34','-1.0 day')} {2003-10-21 12:34:00} +datetest 2.21 {datetime('2003-10-22 12:34','1 month')} {2003-11-22 12:34:00} +datetest 2.22 {datetime('2003-10-22 12:34','11 month')} {2004-09-22 12:34:00} +datetest 2.23 {datetime('2003-10-22 12:34','-13 month')} {2002-09-22 12:34:00} +datetest 2.24 {datetime('2003-10-22 12:34','1.5 months')} {2003-12-07 12:34:00} +datetest 2.25 {datetime('2003-10-22 12:34','-5 years')} {1998-10-22 12:34:00} +datetest 2.26 {datetime('2003-10-22 12:34','+10.5 minutes')} \ + {2003-10-22 12:44:30} +datetest 2.27 {datetime('2003-10-22 12:34','-1.25 hours')} \ + {2003-10-22 11:19:00} +datetest 2.28 {datetime('2003-10-22 12:34','11.25 seconds')} \ + {2003-10-22 12:34:11} +datetest 2.29 {datetime('2003-10-22 12:24','+5 bogus')} NULL +datetest 2.30 {datetime('2003-10-22 12:24','+++')} NULL +datetest 2.31 {datetime('2003-10-22 12:24','+12.3e4 femtoseconds')} NULL +datetest 2.32 {datetime('2003-10-22 12:24','+12.3e4 uS')} NULL +datetest 2.33 {datetime('2003-10-22 12:24','+1 abc')} NULL +datetest 2.34 {datetime('2003-10-22 12:24','+1 abcd')} NULL +datetest 2.35 {datetime('2003-10-22 12:24','+1 abcde')} NULL +datetest 2.36 {datetime('2003-10-22 12:24','+1 abcdef')} NULL +datetest 2.37 {datetime('2003-10-22 12:24','+1 abcdefg')} NULL +datetest 2.38 {datetime('2003-10-22 12:24','+1 abcdefgh')} NULL +datetest 2.39 {datetime('2003-10-22 12:24','+1 abcdefghi')} NULL +set sqlite_current_time 1199243045 +datetest 2.40 {datetime()} {2008-01-02 03:04:05} +set sqlite_current_time 0 +datetest 2.41 {datetime('2003-10-22 12:24','23 seconds')} {2003-10-22 12:24:23} +datetest 2.42 {datetime('2003-10-22 12:24','345 second')} {2003-10-22 12:29:45} +datetest 2.43 {datetime('2003-10-22 12:24','4 second')} {2003-10-22 12:24:04} +datetest 2.44 {datetime('2003-10-22 12:24','56 second')} {2003-10-22 12:24:56} +datetest 2.45 {datetime('2003-10-22 12:24','60 second')} {2003-10-22 12:25:00} +datetest 2.46 {datetime('2003-10-22 12:24','70 second')} {2003-10-22 12:25:10} +datetest 2.47 {datetime('2003-10-22 12:24','8.6 seconds')} {2003-10-22 12:24:08} +datetest 2.48 {datetime('2003-10-22 12:24','9.4 second')} {2003-10-22 12:24:09} +datetest 2.49 {datetime('2003-10-22 12:24','0000 second')} {2003-10-22 12:24:00} +datetest 2.50 {datetime('2003-10-22 12:24','0001 second')} {2003-10-22 12:24:01} +datetest 2.51 {datetime('2003-10-22 12:24','nonsense')} NULL + +datetest 3.1 {strftime('%d','2003-10-31 12:34:56.432')} 31 +datetest 3.2.1 {strftime('pre%fpost','2003-10-31 12:34:56.432')} pre56.432post +datetest 3.2.2 {strftime('%f','2003-10-31 12:34:59.9999999')} 59.999 +datetest 3.3 {strftime('%H','2003-10-31 12:34:56.432')} 12 +datetest 3.4 {strftime('%j','2003-10-31 12:34:56.432')} 304 +datetest 3.5 {strftime('%J','2003-10-31 12:34:56.432')} 2452944.024264259 +datetest 3.6 {strftime('%m','2003-10-31 12:34:56.432')} 10 +datetest 3.7 {strftime('%M','2003-10-31 12:34:56.432')} 34 +datetest 3.8.1 {strftime('%s','2003-10-31 12:34:56.432')} 1067603696 +datetest 3.8.2 {strftime('%s','2038-01-19 03:14:07')} 2147483647 +datetest 3.8.3 {strftime('%s','2038-01-19 03:14:08')} 2147483648 +datetest 3.8.4 {strftime('%s','2201-04-09 12:00:00')} 7298164800 +datetest 3.8.5 {strftime('%s','9999-12-31 23:59:59')} 253402300799 +datetest 3.8.6 {strftime('%s','1969-12-31 23:59:59')} -1 +datetest 3.8.7 {strftime('%s','1901-12-13 20:45:52')} -2147483648 +datetest 3.8.8 {strftime('%s','1901-12-13 20:45:51')} -2147483649 +datetest 3.8.9 {strftime('%s','1776-07-04 00:00:00')} -6106060800 +datetest 3.9 {strftime('%S','2003-10-31 12:34:56.432')} 56 +datetest 3.10 {strftime('%w','2003-10-31 12:34:56.432')} 5 +datetest 3.11.1 {strftime('%W','2003-10-31 12:34:56.432')} 43 +datetest 3.11.2 {strftime('%W','2004-01-01')} 00 +datetest 3.11.3 {strftime('%W','2004-01-02')} 00 +datetest 3.11.4 {strftime('%W','2004-01-03')} 00 +datetest 3.11.5 {strftime('abc%Wxyz','2004-01-04')} abc00xyz +datetest 3.11.6 {strftime('%W','2004-01-05')} 01 +datetest 3.11.7 {strftime('%W','2004-01-06')} 01 +datetest 3.11.8 {strftime('%W','2004-01-07')} 01 +datetest 3.11.9 {strftime('%W','2004-01-08')} 01 +datetest 3.11.10 {strftime('%W','2004-01-09')} 01 +datetest 3.11.11 {strftime('%W','2004-07-18')} 28 +datetest 3.11.12 {strftime('%W','2004-12-31')} 52 +datetest 3.11.13 {strftime('%W','2007-12-31')} 53 +datetest 3.11.14 {strftime('%W','2007-01-01')} 01 +datetest 3.11.15 {strftime('%W %j',2454109.04140970)} {02 008} +datetest 3.11.16 {strftime('%W %j',2454109.04140971)} {02 008} +datetest 3.11.17 {strftime('%W %j',2454109.04140972)} {02 008} +datetest 3.11.18 {strftime('%W %j',2454109.04140973)} {02 008} +datetest 3.11.19 {strftime('%W %j',2454109.04140974)} {02 008} +datetest 3.11.20 {strftime('%W %j',2454109.04140975)} {02 008} +datetest 3.11.21 {strftime('%W %j',2454109.04140976)} {02 008} +datetest 3.11.22 {strftime('%W %j',2454109.04140977)} {02 008} +datetest 3.11.23 {strftime('%W %j',2454109.04140978)} {02 008} +datetest 3.11.24 {strftime('%W %j',2454109.04140979)} {02 008} +datetest 3.11.25 {strftime('%W %j',2454109.04140980)} {02 008} +datetest 3.11.99 {strftime('%W %j','2454109.04140970')} {02 008} +datetest 3.12 {strftime('%Y','2003-10-31 12:34:56.432')} 2003 +datetest 3.13 {strftime('%%','2003-10-31 12:34:56.432')} % +datetest 3.14 {strftime('%_','2003-10-31 12:34:56.432')} NULL +datetest 3.15 {strftime('%Y-%m-%d','2003-10-31')} 2003-10-31 +proc repeat {n txt} { + set x {} + while {$n>0} { + append x $txt + incr n -1 + } + return $x +} +datetest 3.16 "strftime('[repeat 200 %Y]','2003-10-31')" [repeat 200 2003] +datetest 3.17 "strftime('[repeat 200 abc%m123]','2003-10-31')" \ + [repeat 200 abc10123] + +foreach c {a b c e g h i k l n o p q r t v x y z + A B C D E F G I K L N O P Q R T U V Z + 0 1 2 3 4 5 6 6 7 9 _} { + datetest 3.18.$c "strftime('%$c','2003-10-31')" NULL +} + +# Ticket #2276. Make sure leading zeros are inserted where appropriate. +# +datetest 3.20 \ + {strftime('%d/%f/%H/%W/%j/%m/%M/%S/%Y','0421-01-02 03:04:05.006')} \ + 02/05.006/03/00/002/01/04/05/0421 + +set sqlite_current_time 1157124367 +datetest 4.1 {date('now')} {2006-09-01} +set sqlite_current_time 0 + +datetest 5.1 {datetime('1994-04-16 14:00:00 +05:00')} {1994-04-16 09:00:00} +datetest 5.2 {datetime('1994-04-16 14:00:00 -05:15')} {1994-04-16 19:15:00} +datetest 5.3 {datetime('1994-04-16 05:00:00 +08:30')} {1994-04-15 20:30:00} +datetest 5.4 {datetime('1994-04-16 14:00:00 -11:55')} {1994-04-17 01:55:00} +datetest 5.5 {datetime('1994-04-16 14:00:00 -11:60')} NULL +datetest 5.6 {datetime('1994-04-16 14:00:00 -11:55 ')} {1994-04-17 01:55:00} +datetest 5.7 {datetime('1994-04-16 14:00:00 -11:55 x')} NULL +datetest 5.8 {datetime('1994-04-16T14:00:00Z')} {1994-04-16 14:00:00} +datetest 5.9 {datetime('1994-04-16 14:00:00z')} {1994-04-16 14:00:00} +datetest 5.10 {datetime('1994-04-16 14:00:00 Z')} {1994-04-16 14:00:00} +datetest 5.11 {datetime('1994-04-16 14:00:00z ')} {1994-04-16 14:00:00} +datetest 5.12 {datetime('1994-04-16 14:00:00 z ')} {1994-04-16 14:00:00} +datetest 5.13 {datetime('1994-04-16 14:00:00Zulu')} NULL +datetest 5.14 {datetime('1994-04-16 14:00:00Z +05:00')} NULL +datetest 5.15 {datetime('1994-04-16 14:00:00 +05:00 Z')} NULL + +# localtime->utc and utc->localtime conversions. These tests only work +# if the localtime is in the US Eastern Time (the time in Charlotte, NC +# and in New York.) +# +# On non-Vista Windows platform, '2006-03-31' is treated incorrectly as being +# in DST giving a 4 hour offset instead of 5. In 2007, DST was extended to +# start three weeks earlier (second Sunday in March) and end one week +# later (first Sunday in November). Older Windows systems apply this +# new rule incorrectly to dates prior to 2007. +# +# It might be argued that this is masking a problem on non-Vista Windows +# platform. A ticket has already been opened for this issue +# (http://www.sqlite.org/cvstrac/tktview?tn=2322). This is just to prevent +# more confusion/reports of the issue. +# + +# $tzoffset_old should be 5 if DST is working correctly. +set tzoffset_old [db one { + SELECT CAST(24*(julianday('2006-03-31') - + julianday('2006-03-31','localtime'))+0.5 + AS INT) +}] + +# $tzoffset_new should be 4 if DST is working correctly. +set tzoffset_new [db one { + SELECT CAST(24*(julianday('2007-03-31') - + julianday('2007-03-31','localtime'))+0.5 + AS INT) +}] + +# Warn about possibly broken Windows DST implementations. +if {$::tcl_platform(platform)=="windows" && $tzoffset_new==4 && $tzoffset_old==4} { + puts "******************************************************************" + puts "N.B.: The DST support provided by your current O/S seems to be" + puts "suspect in that it is reporting incorrect DST values for dates" + puts "prior to 2007. This is the known case for most (all?) non-Vista" + puts "Windows versions. Please see ticket #2322 for more information." + puts "******************************************************************" +} + +if {$tzoffset_new==4} { + datetest 6.1 {datetime('2000-10-29 05:59:00','localtime')}\ + {2000-10-29 01:59:00} + datetest 6.1.1 {datetime('2006-10-29 05:59:00','localtime')}\ + {2006-10-29 01:59:00} + datetest 6.1.2 {datetime('2007-11-04 05:59:00','localtime')}\ + {2007-11-04 01:59:00} + + # If the new and old DST rules seem to be working correctly... + if {$tzoffset_new==4 && $tzoffset_old==5} { + datetest 6.2 {datetime('2000-10-29 06:00:00','localtime')}\ + {2000-10-29 01:00:00} + datetest 6.2.1 {datetime('2006-10-29 06:00:00','localtime')}\ + {2006-10-29 01:00:00} + } + datetest 6.2.2 {datetime('2007-11-04 06:00:00','localtime')}\ + {2007-11-04 01:00:00} + + # If the new and old DST rules seem to be working correctly... + if {$tzoffset_new==4 && $tzoffset_old==5} { + datetest 6.3 {datetime('2000-04-02 06:59:00','localtime')}\ + {2000-04-02 01:59:00} + datetest 6.3.1 {datetime('2006-04-02 06:59:00','localtime')}\ + {2006-04-02 01:59:00} + } + datetest 6.3.2 {datetime('2007-03-11 07:00:00','localtime')}\ + {2007-03-11 03:00:00} + + datetest 6.4 {datetime('2000-04-02 07:00:00','localtime')}\ + {2000-04-02 03:00:00} + datetest 6.4.1 {datetime('2006-04-02 07:00:00','localtime')}\ + {2006-04-02 03:00:00} + datetest 6.4.2 {datetime('2007-03-11 07:00:00','localtime')}\ + {2007-03-11 03:00:00} + + datetest 6.5 {datetime('2000-10-29 01:59:00','utc')} {2000-10-29 05:59:00} + datetest 6.5.1 {datetime('2006-10-29 01:59:00','utc')} {2006-10-29 05:59:00} + datetest 6.5.2 {datetime('2007-11-04 01:59:00','utc')} {2007-11-04 05:59:00} + + # If the new and old DST rules seem to be working correctly... + if {$tzoffset_new==4 && $tzoffset_old==5} { + datetest 6.6 {datetime('2000-10-29 02:00:00','utc')} {2000-10-29 07:00:00} + datetest 6.6.1 {datetime('2006-10-29 02:00:00','utc')} {2006-10-29 07:00:00} + } + datetest 6.6.2 {datetime('2007-11-04 02:00:00','utc')} {2007-11-04 07:00:00} + + # If the new and old DST rules seem to be working correctly... + if {$tzoffset_new==4 && $tzoffset_old==5} { + datetest 6.7 {datetime('2000-04-02 01:59:00','utc')} {2000-04-02 06:59:00} + datetest 6.7.1 {datetime('2006-04-02 01:59:00','utc')} {2006-04-02 06:59:00} + } + datetest 6.7.2 {datetime('2007-03-11 01:59:00','utc')} {2007-03-11 06:59:00} + + datetest 6.8 {datetime('2000-04-02 02:00:00','utc')} {2000-04-02 06:00:00} + datetest 6.8.1 {datetime('2006-04-02 02:00:00','utc')} {2006-04-02 06:00:00} + datetest 6.8.2 {datetime('2007-03-11 02:00:00','utc')} {2007-03-11 06:00:00} + + datetest 6.10 {datetime('2000-01-01 12:00:00','localtime')} \ + {2000-01-01 07:00:00} + datetest 6.11 {datetime('1969-01-01 12:00:00','localtime')} \ + {1969-01-01 07:00:00} + datetest 6.12 {datetime('2039-01-01 12:00:00','localtime')} \ + {2039-01-01 07:00:00} + datetest 6.13 {datetime('2000-07-01 12:00:00','localtime')} \ + {2000-07-01 08:00:00} + datetest 6.14 {datetime('1969-07-01 12:00:00','localtime')} \ + {1969-07-01 07:00:00} + datetest 6.15 {datetime('2039-07-01 12:00:00','localtime')} \ + {2039-07-01 07:00:00} + set sqlite_current_time \ + [db eval {SELECT strftime('%s','2000-07-01 12:34:56')}] + datetest 6.16 {datetime('now','localtime')} {2000-07-01 08:34:56} + datetest 6.17 {datetime('now','localtimex')} NULL + datetest 6.18 {datetime('now','localtim')} NULL + set sqlite_current_time 0 +} + +# These two are a bit of a scam. They are added to ensure that 100% of +# the date.c file is covered by testing, even when the time-zone +# is not -0400 (the condition for running of the block of tests above). +# +datetest 6.19 {datetime('2039-07-01 12:00:00','localtime',null)} NULL +datetest 6.20 {datetime('2039-07-01 12:00:00','utc',null)} NULL + +# Date-time functions that contain NULL arguments return a NULL +# result. +# +datetest 7.1 {datetime(null)} NULL +datetest 7.2 {datetime('now',null)} NULL +datetest 7.3 {datetime('now','localtime',null)} NULL +datetest 7.4 {time(null)} NULL +datetest 7.5 {time('now',null)} NULL +datetest 7.6 {time('now','localtime',null)} NULL +datetest 7.7 {date(null)} NULL +datetest 7.8 {date('now',null)} NULL +datetest 7.9 {date('now','localtime',null)} NULL +datetest 7.10 {julianday(null)} NULL +datetest 7.11 {julianday('now',null)} NULL +datetest 7.12 {julianday('now','localtime',null)} NULL +datetest 7.13 {strftime(null,'now')} NULL +datetest 7.14 {strftime('%s',null)} NULL +datetest 7.15 {strftime('%s','now',null)} NULL +datetest 7.16 {strftime('%s','now','localtime',null)} NULL + +# Test modifiers when the date begins as a julian day number - to +# make sure the HH:MM:SS is preserved. Ticket #551. +# +set sqlite_current_time [db eval {SELECT strftime('%s','2003-10-22 12:34:00')}] +datetest 8.1 {datetime('now','weekday 0')} {2003-10-26 12:34:00} +datetest 8.2 {datetime('now','weekday 1')} {2003-10-27 12:34:00} +datetest 8.3 {datetime('now','weekday 2')} {2003-10-28 12:34:00} +datetest 8.4 {datetime('now','weekday 3')} {2003-10-22 12:34:00} +datetest 8.5 {datetime('now','start of month')} {2003-10-01 00:00:00} +datetest 8.6 {datetime('now','start of year')} {2003-01-01 00:00:00} +datetest 8.7 {datetime('now','start of day')} {2003-10-22 00:00:00} +datetest 8.8 {datetime('now','1 day')} {2003-10-23 12:34:00} +datetest 8.9 {datetime('now','+1 day')} {2003-10-23 12:34:00} +datetest 8.10 {datetime('now','+1.25 day')} {2003-10-23 18:34:00} +datetest 8.11 {datetime('now','-1.0 day')} {2003-10-21 12:34:00} +datetest 8.12 {datetime('now','1 month')} {2003-11-22 12:34:00} +datetest 8.13 {datetime('now','11 month')} {2004-09-22 12:34:00} +datetest 8.14 {datetime('now','-13 month')} {2002-09-22 12:34:00} +datetest 8.15 {datetime('now','1.5 months')} {2003-12-07 12:34:00} +datetest 8.16 {datetime('now','-5 years')} {1998-10-22 12:34:00} +datetest 8.17 {datetime('now','+10.5 minutes')} {2003-10-22 12:44:30} +datetest 8.18 {datetime('now','-1.25 hours')} {2003-10-22 11:19:00} +datetest 8.19 {datetime('now','11.25 seconds')} {2003-10-22 12:34:11} +datetest 8.90 {datetime('now','abcdefghijklmnopqrstuvwyxzABCDEFGHIJLMNOP')} NULL +set sqlite_current_time 0 + +# Negative years work. Example: '-4713-11-26' is JD 1.5. +# +datetest 9.1 {julianday('-4713-11-24 12:00:00')} {0.0} +datetest 9.2 {julianday(datetime(5))} {5.0} +datetest 9.3 {julianday(datetime(10))} {10.0} +datetest 9.4 {julianday(datetime(100))} {100.0} +datetest 9.5 {julianday(datetime(1000))} {1000.0} +datetest 9.6 {julianday(datetime(10000))} {10000.0} +datetest 9.7 {julianday(datetime(100000))} {100000.0} + +# datetime() with just an HH:MM:SS correctly inserts the date 2000-01-01. +# +datetest 10.1 {datetime('01:02:03')} {2000-01-01 01:02:03} +datetest 10.2 {date('01:02:03')} {2000-01-01} +datetest 10.3 {strftime('%Y-%m-%d %H:%M','01:02:03')} {2000-01-01 01:02} + +# Test the new HH:MM:SS modifier +# +datetest 11.1 {datetime('2004-02-28 20:00:00', '-01:20:30')} \ + {2004-02-28 18:39:30} +datetest 11.2 {datetime('2004-02-28 20:00:00', '+12:30:00')} \ + {2004-02-29 08:30:00} +datetest 11.3 {datetime('2004-02-28 20:00:00', '+12:30')} \ + {2004-02-29 08:30:00} +datetest 11.4 {datetime('2004-02-28 20:00:00', '12:30')} \ + {2004-02-29 08:30:00} +datetest 11.5 {datetime('2004-02-28 20:00:00', '-12:00')} \ + {2004-02-28 08:00:00} +datetest 11.6 {datetime('2004-02-28 20:00:00', '-12:01')} \ + {2004-02-28 07:59:00} +datetest 11.7 {datetime('2004-02-28 20:00:00', '-11:59')} \ + {2004-02-28 08:01:00} +datetest 11.8 {datetime('2004-02-28 20:00:00', '11:59')} \ + {2004-02-29 07:59:00} +datetest 11.9 {datetime('2004-02-28 20:00:00', '12:01')} \ + {2004-02-29 08:01:00} +datetest 11.10 {datetime('2004-02-28 20:00:00', '12:60')} NULL + +# Ticket #1964 +datetest 12.1 {datetime('2005-09-01')} {2005-09-01 00:00:00} +datetest 12.2 {datetime('2005-09-01','+0 hours')} {2005-09-01 00:00:00} + +# Ticket #1991 +do_test date-13.1 { + execsql { + SELECT strftime('%Y-%m-%d %H:%M:%f', julianday('2006-09-24T10:50:26.047')) + } +} {{2006-09-24 10:50:26.047}} + +# Ticket #2153 +datetest 13.2 {strftime('%Y-%m-%d %H:%M:%S', '2007-01-01 12:34:59.6')} \ + {2007-01-01 12:34:59} +datetest 13.3 {strftime('%Y-%m-%d %H:%M:%f', '2007-01-01 12:34:59.6')} \ + {2007-01-01 12:34:59.600} +datetest 13.4 {strftime('%Y-%m-%d %H:%M:%S', '2007-01-01 12:59:59.6')} \ + {2007-01-01 12:59:59} +datetest 13.5 {strftime('%Y-%m-%d %H:%M:%f', '2007-01-01 12:59:59.6')} \ + {2007-01-01 12:59:59.600} +datetest 13.6 {strftime('%Y-%m-%d %H:%M:%S', '2007-01-01 23:59:59.6')} \ + {2007-01-01 23:59:59} +datetest 13.7 {strftime('%Y-%m-%d %H:%M:%f', '2007-01-01 23:59:59.6')} \ + {2007-01-01 23:59:59.600} + +# Ticket #3618 +datetest 13.11 {julianday(2454832.5,'-1 day')} {2454831.5} +datetest 13.12 {julianday(2454832.5,'+1 day')} {2454833.5} +datetest 13.13 {julianday(2454832.5,'-1.5 day')} {2454831.0} +datetest 13.14 {julianday(2454832.5,'+1.5 day')} {2454834.0} +datetest 13.15 {julianday(2454832.5,'-3 hours')} {2454832.375} +datetest 13.16 {julianday(2454832.5,'+3 hours')} {2454832.625} +datetest 13.17 {julianday(2454832.5,'-45 minutes')} {2454832.46875} +datetest 13.18 {julianday(2454832.5,'+45 minutes')} {2454832.53125} +datetest 13.19 {julianday(2454832.5,'-675 seconds')} {2454832.4921875} +datetest 13.20 {julianday(2454832.5,'+675 seconds')} {2454832.5078125} +datetest 13.21 {julianday(2454832.5,'-1.5 months')} {2454786.5} +datetest 13.22 {julianday(2454832.5,'+1.5 months')} {2454878.5} +datetest 13.23 {julianday(2454832.5,'-1.5 years')} {2454284.0} +datetest 13.24 {julianday(2454832.5,'+1.5 years')} {2455380.0} + +datetest 13.30 {date('2000-01-01','+1.5 years')} {2001-07-02} +datetest 13.31 {date('2001-01-01','+1.5 years')} {2002-07-02} +datetest 13.32 {date('2002-01-01','+1.5 years')} {2003-07-02} +datetest 13.33 {date('2002-01-01','-1.5 years')} {2000-07-02} +datetest 13.34 {date('2001-01-01','-1.5 years')} {1999-07-02} + +# Test for issues reported by BareFeet (list.sql at tandb.com.au) +# on mailing list on 2008-06-12. +# +# Put a floating point number in the database so that we can manipulate +# raw bits using the hexio interface. +# +if {0==[sqlite3 -has-codec]} { + do_test date-14.1 { + execsql { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size = 1024; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1.1); + } + db close + hexio_write test.db 2040 4142ba32bffffff9 + sqlite3 db test.db + db eval {SELECT * FROM t1} + } {2454629.5} + + # Changing the least significant byte of the floating point value between + # 00 and FF should always generate a time of either 23:59:59 or 00:00:00, + # never 24:00:00 + # + for {set i 0} {$i<=255} {incr i} { + db close + hexio_write test.db 2047 [format %02x $i] + sqlite3 db test.db + do_test date-14.2.$i { + set date [db one {SELECT datetime(x) FROM t1}] + expr {$date eq "2008-06-12 00:00:00" || $date eq "2008-06-11 23:59:59"} + } {1} + } +} + +# Verify that multiple calls to date functions with 'now' return the +# same answer. +# +# EVIDENCE-OF: R-34818-13664 The 'now' argument to date and time +# functions always returns exactly the same value for multiple +# invocations within the same sqlite3_step() call. +# +proc sleeper {} {after 100} +do_test date-15.1 { + db func sleeper sleeper + db eval { + SELECT c - a FROM (SELECT julianday('now') AS a, + sleeper(), julianday('now') AS c); + } +} {0.0} +do_test date-15.2 { + db eval { + SELECT a==b FROM (SELECT current_timestamp AS a, + sleeper(), current_timestamp AS b); + } +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/dbstatus.test b/components/external/SQLite-3.8.1/test/dbstatus.test new file mode 100644 index 0000000000000000000000000000000000000000..c22fe15d4370911c7bc955cbe435d6597b5eaca7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/dbstatus.test @@ -0,0 +1,374 @@ +# 2010 March 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests for the sqlite3_db_status() function +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +# Memory statistics must be enabled for this test. +db close +sqlite3_shutdown +sqlite3_config_memstatus 1 +sqlite3_initialize +sqlite3 db test.db + + +# Make sure sqlite3_db_config() and sqlite3_db_status are working. +# +unset -nocomplain PAGESZ +unset -nocomplain BASESZ +do_test dbstatus-1.1 { + db close + sqlite3 db :memory: + db eval { + CREATE TABLE t1(x); + } + set sz1 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_CACHE_USED 0] 1] + db eval { + CREATE TABLE t2(y); + } + set sz2 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_CACHE_USED 0] 1] + set ::PAGESZ [expr {$sz2-$sz1}] + set ::BASESZ [expr {$sz1-$::PAGESZ}] + expr {$::PAGESZ>1024 && $::PAGESZ<1300} +} {1} +do_test dbstatus-1.2 { + db eval { + INSERT INTO t1 VALUES(zeroblob(9000)); + } + lindex [sqlite3_db_status db SQLITE_DBSTATUS_CACHE_USED 0] 1 +} [expr {$BASESZ + 10*$PAGESZ}] + + +proc lookaside {db} { + expr { $::lookaside_buffer_size * + [lindex [sqlite3_db_status $db SQLITE_DBSTATUS_LOOKASIDE_USED 0] 1] + } +} + +ifcapable stat4||stat3 { + set STAT3 1 +} else { + set STAT3 0 +} + +ifcapable malloc_usable_size { + finish_test + return +} + +#--------------------------------------------------------------------------- +# Run the dbstatus-2 and dbstatus-3 tests with several of different +# lookaside buffer sizes. +# +foreach ::lookaside_buffer_size {0 64 120} { + + # Do not run any of these tests if there is SQL configured to run + # as part of the [sqlite3] command. This prevents the script from + # configuring the size of the lookaside buffer after [sqlite3] has + # returned. + if {[presql] != ""} break + + #------------------------------------------------------------------------- + # Tests for SQLITE_DBSTATUS_SCHEMA_USED. + # + # Each test in the following block works as follows. Each test uses a + # different database schema. + # + # 1. Open a connection to an empty database. Disable statement caching. + # + # 2. Execute the SQL to create the database schema. Measure the total + # heap and lookaside memory allocated by SQLite, and the memory + # allocated for the database schema according to sqlite3_db_status(). + # + # 3. Drop all tables in the database schema. Measure the total memory + # and the schema memory again. + # + # 4. Repeat step 2. + # + # 5. Repeat step 3. + # + # Then test that: + # + # a) The difference in schema memory quantities in steps 2 and 3 is the + # same as the difference in total memory in steps 2 and 3. + # + # b) Step 4 reports the same amount of schema and total memory used as + # in step 2. + # + # c) Step 5 reports the same amount of schema and total memory used as + # in step 3. + # + foreach {tn schema} { + 1 { CREATE TABLE t1(a, b) } + 2 { CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1, c UNIQUE) } + 3 { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + } + 4 { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); + CREATE TRIGGER AFTER INSERT ON t1 BEGIN + INSERT INTO t2 VALUES(new.a, new.b); + SELECT * FROM t1, t2 WHERE a=c AND b=d GROUP BY b HAVING a>5 ORDER BY a; + END; + } + 5 { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); + CREATE VIEW v1 AS SELECT * FROM t1 UNION SELECT * FROM t2; + } + 6y { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(a,b); + CREATE INDEX i3 ON t1(b,b); + INSERT INTO t1 VALUES(randomblob(20), randomblob(25)); + INSERT INTO t1 SELECT randomblob(20), randomblob(25) FROM t1; + INSERT INTO t1 SELECT randomblob(20), randomblob(25) FROM t1; + INSERT INTO t1 SELECT randomblob(20), randomblob(25) FROM t1; + ANALYZE; + } + 7 { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); + CREATE VIEW v1 AS + SELECT * FROM t1 + UNION + SELECT * FROM t2 + UNION ALL + SELECT c||b, d||a FROM t2 LEFT OUTER JOIN t1 GROUP BY c, d + ORDER BY 1, 2 + ; + CREATE TRIGGER tr1 INSTEAD OF INSERT ON v1 BEGIN + SELECT * FROM v1; + UPDATE t1 SET a=5, b=(SELECT c FROM t2); + END; + SELECT * FROM v1; + } + 8x { + CREATE TABLE t1(a, b, UNIQUE(a, b)); + CREATE VIRTUAL TABLE t2 USING echo(t1); + } + } { + set tn "$::lookaside_buffer_size-$tn" + + # Step 1. + db close + forcedelete test.db + sqlite3 db test.db + sqlite3_db_config_lookaside db 0 $::lookaside_buffer_size 500 + db cache size 0 + + catch { register_echo_module db } + ifcapable !vtab { if {[string match *x $tn]} continue } + + # Step 2. + execsql $schema + set nAlloc1 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + incr nAlloc1 [lookaside db] + set nSchema1 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_SCHEMA_USED 0] 1] + + # Step 3. + drop_all_tables + set nAlloc2 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + incr nAlloc2 [lookaside db] + set nSchema2 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_SCHEMA_USED 0] 1] + + # Step 4. + execsql $schema + set nAlloc3 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + incr nAlloc3 [lookaside db] + set nSchema3 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_SCHEMA_USED 0] 1] + + # Step 5. + drop_all_tables + set nAlloc4 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + incr nAlloc4 [lookaside db] + set nSchema4 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_SCHEMA_USED 0] 1] + set nFree [expr {$nAlloc1-$nAlloc2}] + + # Tests for which the test name ends in an "x" report slightly less + # memory than is actually freed when all schema items are finalized. + # This is because memory allocated by virtual table implementations + # for any reason is not counted as "schema memory". + # + # Additionally, in auto-vacuum mode, dropping tables and indexes causes + # the page-cache to shrink. So the amount of memory freed is always + # much greater than just that reported by DBSTATUS_SCHEMA_USED in this + # case. + # + # Some of the memory used for sqlite_stat4 is unaccounted for by + # dbstatus. + # + # Finally, on osx the estimate of memory used by the schema may be + # slightly low. + # + if {[string match *x $tn] || $AUTOVACUUM + || ([string match *y $tn] && $STAT3) + || ($::tcl_platform(os) == "Darwin") + } { + do_test dbstatus-2.$tn.ax { expr {($nSchema1-$nSchema2)<=$nFree} } 1 + } else { + do_test dbstatus-2.$tn.a { expr {$nSchema1-$nSchema2} } $nFree + } + + do_test dbstatus-2.$tn.b { list $nAlloc1 $nSchema1 } "$nAlloc3 $nSchema3" + do_test dbstatus-2.$tn.c { list $nAlloc2 $nSchema2 } "$nAlloc4 $nSchema4" + } + + #------------------------------------------------------------------------- + # Tests for SQLITE_DBSTATUS_STMT_USED. + # + # Each test in the following block works as follows. Each test uses a + # different database schema. + # + # 1. Open a connection to an empty database. Initialized the database + # schema. + # + # 2. Prepare a bunch of SQL statements. Measure the total heap and + # lookaside memory allocated by SQLite, and the memory allocated + # for the prepared statements according to sqlite3_db_status(). + # + # 3. Finalize all prepared statements Measure the total memory + # and the prepared statement memory again. + # + # 4. Repeat step 2. + # + # 5. Repeat step 3. + # + # Then test that: + # + # a) The difference in schema memory quantities in steps 2 and 3 is the + # same as the difference in total memory in steps 2 and 3. + # + # b) Step 4 reports the same amount of schema and total memory used as + # in step 2. + # + # c) Step 5 reports the same amount of schema and total memory used as + # in step 3. + # + foreach {tn schema statements} { + 1 { CREATE TABLE t1(a, b) } { + SELECT * FROM t1; + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 SELECT * FROM t1; + UPDATE t1 SET a=5; + DELETE FROM t1; + } + 2 { + PRAGMA recursive_triggers = 1; + CREATE TABLE t1(a, b); + CREATE TRIGGER tr1 AFTER INSERT ON t1 WHEN (new.a>0) BEGIN + INSERT INTO t1 VALUES(new.a-1, new.b); + END; + } { + INSERT INTO t1 VALUES(5, 'x'); + } + 3 { + PRAGMA recursive_triggers = 1; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + CREATE TRIGGER tr1 AFTER INSERT ON t1 WHEN (new.a>0) BEGIN + INSERT INTO t2 VALUES(new.a-1, new.b); + END; + CREATE TRIGGER tr2 AFTER INSERT ON t1 WHEN (new.a>0) BEGIN + INSERT INTO t1 VALUES(new.a-1, new.b); + END; + } { + INSERT INTO t1 VALUES(10, 'x'); + } + 4 { + CREATE TABLE t1(a, b); + } { + SELECT count(*) FROM t1 WHERE upper(a)='ABC'; + } + 5x { + CREATE TABLE t1(a, b UNIQUE); + CREATE VIRTUAL TABLE t2 USING echo(t1); + } { + SELECT count(*) FROM t2; + SELECT * FROM t2 WHERE b>5; + SELECT * FROM t2 WHERE b='abcdefg'; + } + } { + set tn "$::lookaside_buffer_size-$tn" + + # Step 1. + db close + forcedelete test.db + sqlite3 db test.db + sqlite3_db_config_lookaside db 0 $::lookaside_buffer_size 500 + db cache size 1000 + + catch { register_echo_module db } + ifcapable !vtab { if {[string match *x $tn]} continue } + + execsql $schema + db cache flush + + # Step 2. + execsql $statements + set nAlloc1 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + incr nAlloc1 [lookaside db] + set nStmt1 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_STMT_USED 0] 1] + execsql $statements + + # Step 3. + db cache flush + set nAlloc2 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + incr nAlloc2 [lookaside db] + set nStmt2 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_STMT_USED 0] 1] + + # Step 3. + execsql $statements + set nAlloc3 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + incr nAlloc3 [lookaside db] + set nStmt3 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_STMT_USED 0] 1] + execsql $statements + + # Step 4. + db cache flush + set nAlloc4 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + incr nAlloc4 [lookaside db] + set nStmt4 [lindex [sqlite3_db_status db SQLITE_DBSTATUS_STMT_USED 0] 1] + + set nFree [expr {$nAlloc1-$nAlloc2}] + + do_test dbstatus-3.$tn.a { expr $nStmt2 } {0} + + # Tests for which the test name ends in an "x" report slightly less + # memory than is actually freed when all statements are finalized. + # This is because a small amount of memory allocated by a virtual table + # implementation using sqlite3_mprintf() is technically considered + # external and so is not counted as "statement memory". + # +#puts "$nStmt1 $nFree" + if {[string match *x $tn]} { + do_test dbstatus-3.$tn.bx { expr $nStmt1<=$nFree } {1} + } else { + do_test dbstatus-3.$tn.b { expr $nStmt1==$nFree } {1} + } + + do_test dbstatus-3.$tn.c { list $nAlloc1 $nStmt1 } [list $nAlloc3 $nStmt3] + do_test dbstatus-3.$tn.d { list $nAlloc2 $nStmt2 } [list $nAlloc4 $nStmt4] + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/dbstatus2.test b/components/external/SQLite-3.8.1/test/dbstatus2.test new file mode 100644 index 0000000000000000000000000000000000000000..2541a1a82312ed4035e1c78af7f475cf06ebab1b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/dbstatus2.test @@ -0,0 +1,102 @@ +# 2011 September 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests for the sqlite3_db_status() function +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set ::testprefix dbstatus2 + +do_execsql_test 1.0 { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, randomblob(600)); + INSERT INTO t1 VALUES(2, randomblob(600)); + INSERT INTO t1 VALUES(3, randomblob(600)); +} + +proc db_hit_miss {db {reset 0}} { + set nHit [sqlite3_db_status $db CACHE_HIT $reset] + set nMiss [sqlite3_db_status $db CACHE_MISS $reset] + list $nHit $nMiss +} + +proc db_write {db {reset 0}} { + sqlite3_db_status $db CACHE_WRITE $reset +} + +do_test 1.1 { + db close + sqlite3 db test.db + execsql { PRAGMA mmap_size = 0 } + expr {[file size test.db] / 1024} +} 6 + +do_test 1.2 { + execsql { SELECT b FROM t1 WHERE a=2 } + db_hit_miss db +} {{0 2 0} {0 4 0}} + +do_test 1.3 { + execsql { SELECT b FROM t1 WHERE a=2 } + db_hit_miss db +} {{0 6 0} {0 4 0}} + +do_test 1.4 { + execsql { SELECT b FROM t1 WHERE a=2 } + db_hit_miss db +} {{0 10 0} {0 4 0}} + +do_test 1.5 { + db_hit_miss db 1 +} {{0 10 0} {0 4 0}} + +do_test 1.6 { + db_hit_miss db 0 +} {{0 0 0} {0 0 0}} + +do_test 1.7 { + set fd [db incrblob main t1 b 1] + fconfigure $fd -translation binary + set len [string length [read $fd]] + close $fd + set len +} 600 +do_test 1.8 { sqlite3_db_status db CACHE_HIT 0 } {0 2 0} +do_test 1.9 { sqlite3_db_status db CACHE_MISS 0 } {0 1 0} + +do_test 2.1 { db_write db } {0 0 0} +do_test 2.2 { + execsql { INSERT INTO t1 VALUES(4, randomblob(600)) } + db_write db +} {0 4 0} +do_test 2.3 { db_write db 1 } {0 4 0} +do_test 2.4 { db_write db 0 } {0 0 0} +do_test 2.5 { db_write db 1 } {0 0 0} + +ifcapable wal { + do_test 2.6 { + execsql { PRAGMA journal_mode = WAL } + db_write db 1 + } {0 1 0} +} +do_test 2.7 { + execsql { INSERT INTO t1 VALUES(5, randomblob(600)) } + db_write db +} {0 4 0} +do_test 2.8 { db_write db 1 } {0 4 0} +do_test 2.9 { db_write db 0 } {0 0 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/default.test b/components/external/SQLite-3.8.1/test/default.test new file mode 100644 index 0000000000000000000000000000000000000000..95a4ee039cc84591c42fa6f7f72a741ec5866bbd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/default.test @@ -0,0 +1,67 @@ +# 2005 August 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this file is testing corner cases of the DEFAULT syntax +# on table definitions. +# +# $Id: default.test,v 1.3 2009/02/19 14:39:25 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable bloblit { + do_test default-1.1 { + execsql { + CREATE TABLE t1( + a INTEGER, + b BLOB DEFAULT x'6869' + ); + INSERT INTO t1(a) VALUES(1); + SELECT * from t1; + } + } {1 hi} +} +do_test default-1.2 { + execsql { + CREATE TABLE t2( + x INTEGER, + y INTEGER DEFAULT NULL + ); + INSERT INTO t2(x) VALUES(1); + SELECT * FROM t2; + } +} {1 {}} +do_test default-1.3 { + catchsql { + CREATE TABLE t3( + x INTEGER, + y INTEGER DEFAULT (max(x,5)) + ) + } +} {1 {default value of column [y] is not constant}} + +ifcapable pragma { + do_test default-2.1 { + execsql { + CREATE TABLE t4(c DEFAULT 'abc'); + PRAGMA table_info(t4); + } + } {0 c {} 0 'abc' 0} + do_test default-2.2 { + execsql { + INSERT INTO t4 DEFAULT VALUES; + PRAGMA table_info(t4); + } + } {0 c {} 0 'abc' 0} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/delete.test b/components/external/SQLite-3.8.1/test/delete.test new file mode 100644 index 0000000000000000000000000000000000000000..47d357811b69211fdbe328c1265a004c0be95740 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/delete.test @@ -0,0 +1,394 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the DELETE FROM statement. +# +# $Id: delete.test,v 1.26 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Try to delete from a non-existant table. +# +do_test delete-1.1 { + set v [catch {execsql {DELETE FROM test1}} msg] + lappend v $msg +} {1 {no such table: test1}} + +# Try to delete from sqlite_master +# +do_test delete-2.1 { + set v [catch {execsql {DELETE FROM sqlite_master}} msg] + lappend v $msg +} {1 {table sqlite_master may not be modified}} + +# Delete selected entries from a table with and without an index. +# +do_test delete-3.1.1 { + execsql {CREATE TABLE table1(f1 int, f2 int)} + execsql {INSERT INTO table1 VALUES(1,2)} + execsql {INSERT INTO table1 VALUES(2,4)} + execsql {INSERT INTO table1 VALUES(3,8)} + execsql {INSERT INTO table1 VALUES(4,16)} + execsql {SELECT * FROM table1 ORDER BY f1} +} {1 2 2 4 3 8 4 16} +do_test delete-3.1.2 { + execsql {DELETE FROM table1 WHERE f1=3} +} {} +do_test delete-3.1.3 { + execsql {SELECT * FROM table1 ORDER BY f1} +} {1 2 2 4 4 16} +do_test delete-3.1.4 { + execsql {CREATE INDEX index1 ON table1(f1)} + execsql {PRAGMA count_changes=on} + ifcapable explain { + execsql {EXPLAIN DELETE FROM table1 WHERE f1=3} + } + execsql {DELETE FROM 'table1' WHERE f1=3} +} {0} +do_test delete-3.1.5 { + execsql {SELECT * FROM table1 ORDER BY f1} +} {1 2 2 4 4 16} +do_test delete-3.1.6.1 { + execsql {DELETE FROM table1 WHERE f1=2} +} {1} +do_test delete-3.1.6.2 { + db changes +} 1 +do_test delete-3.1.7 { + execsql {SELECT * FROM table1 ORDER BY f1} +} {1 2 4 16} +integrity_check delete-3.2 + + +# Semantic errors in the WHERE clause +# +do_test delete-4.1 { + execsql {CREATE TABLE table2(f1 int, f2 int)} + set v [catch {execsql {DELETE FROM table2 WHERE f3=5}} msg] + lappend v $msg +} {1 {no such column: f3}} + +do_test delete-4.2 { + set v [catch {execsql {DELETE FROM table2 WHERE xyzzy(f1+4)}} msg] + lappend v $msg +} {1 {no such function: xyzzy}} +integrity_check delete-4.3 + +# Lots of deletes +# +do_test delete-5.1.1 { + execsql {DELETE FROM table1} +} {2} +do_test delete-5.1.2 { + execsql {SELECT count(*) FROM table1} +} {0} +do_test delete-5.2.1 { + execsql {BEGIN TRANSACTION} + for {set i 1} {$i<=200} {incr i} { + execsql "INSERT INTO table1 VALUES($i,[expr {$i*$i}])" + } + execsql {COMMIT} + execsql {SELECT count(*) FROM table1} +} {200} +do_test delete-5.2.2 { + execsql {DELETE FROM table1} +} {200} +do_test delete-5.2.3 { + execsql {BEGIN TRANSACTION} + for {set i 1} {$i<=200} {incr i} { + execsql "INSERT INTO table1 VALUES($i,[expr {$i*$i}])" + } + execsql {COMMIT} + execsql {SELECT count(*) FROM table1} +} {200} +do_test delete-5.2.4 { + execsql {PRAGMA count_changes=off} + execsql {DELETE FROM table1} +} {} +do_test delete-5.2.5 { + execsql {SELECT count(*) FROM table1} +} {0} +do_test delete-5.2.6 { + execsql {BEGIN TRANSACTION} + for {set i 1} {$i<=200} {incr i} { + execsql "INSERT INTO table1 VALUES($i,[expr {$i*$i}])" + } + execsql {COMMIT} + execsql {SELECT count(*) FROM table1} +} {200} +do_test delete-5.3 { + for {set i 1} {$i<=200} {incr i 4} { + execsql "DELETE FROM table1 WHERE f1==$i" + } + execsql {SELECT count(*) FROM table1} +} {150} +do_test delete-5.4.1 { + execsql "DELETE FROM table1 WHERE f1>50" + db changes +} [db one {SELECT count(*) FROM table1 WHERE f1>50}] +do_test delete-5.4.2 { + execsql {SELECT count(*) FROM table1} +} {37} +do_test delete-5.5 { + for {set i 1} {$i<=70} {incr i 3} { + execsql "DELETE FROM table1 WHERE f1==$i" + } + execsql {SELECT f1 FROM table1 ORDER BY f1} +} {2 3 6 8 11 12 14 15 18 20 23 24 26 27 30 32 35 36 38 39 42 44 47 48 50} +do_test delete-5.6 { + for {set i 1} {$i<40} {incr i} { + execsql "DELETE FROM table1 WHERE f1==$i" + } + execsql {SELECT f1 FROM table1 ORDER BY f1} +} {42 44 47 48 50} +do_test delete-5.7 { + execsql "DELETE FROM table1 WHERE f1!=48" + execsql {SELECT f1 FROM table1 ORDER BY f1} +} {48} +integrity_check delete-5.8 + + +# Delete large quantities of data. We want to test the List overflow +# mechanism in the vdbe. +# +do_test delete-6.1 { + execsql {BEGIN; DELETE FROM table1} + for {set i 1} {$i<=3000} {incr i} { + execsql "INSERT INTO table1 VALUES($i,[expr {$i*$i}])" + } + execsql {DELETE FROM table2} + for {set i 1} {$i<=3000} {incr i} { + execsql "INSERT INTO table2 VALUES($i,[expr {$i*$i}])" + } + execsql {COMMIT} + execsql {SELECT count(*) FROM table1} +} {3000} +do_test delete-6.2 { + execsql {SELECT count(*) FROM table2} +} {3000} +do_test delete-6.3 { + execsql {SELECT f1 FROM table1 WHERE f1<10 ORDER BY f1} +} {1 2 3 4 5 6 7 8 9} +do_test delete-6.4 { + execsql {SELECT f1 FROM table2 WHERE f1<10 ORDER BY f1} +} {1 2 3 4 5 6 7 8 9} +do_test delete-6.5.1 { + execsql {DELETE FROM table1 WHERE f1>7} + db changes +} {2993} +do_test delete-6.5.2 { + execsql {SELECT f1 FROM table1 ORDER BY f1} +} {1 2 3 4 5 6 7} +do_test delete-6.6 { + execsql {DELETE FROM table2 WHERE f1>7} + execsql {SELECT f1 FROM table2 ORDER BY f1} +} {1 2 3 4 5 6 7} +do_test delete-6.7 { + execsql {DELETE FROM table1} + execsql {SELECT f1 FROM table1} +} {} +do_test delete-6.8 { + execsql {INSERT INTO table1 VALUES(2,3)} + execsql {SELECT f1 FROM table1} +} {2} +do_test delete-6.9 { + execsql {DELETE FROM table2} + execsql {SELECT f1 FROM table2} +} {} +do_test delete-6.10 { + execsql {INSERT INTO table2 VALUES(2,3)} + execsql {SELECT f1 FROM table2} +} {2} +integrity_check delete-6.11 + +do_test delete-7.1 { + execsql { + CREATE TABLE t3(a); + INSERT INTO t3 VALUES(1); + INSERT INTO t3 SELECT a+1 FROM t3; + INSERT INTO t3 SELECT a+2 FROM t3; + SELECT * FROM t3; + } +} {1 2 3 4} +ifcapable {trigger} { + do_test delete-7.2 { + execsql { + CREATE TABLE cnt(del); + INSERT INTO cnt VALUES(0); + CREATE TRIGGER r1 AFTER DELETE ON t3 FOR EACH ROW BEGIN + UPDATE cnt SET del=del+1; + END; + DELETE FROM t3 WHERE a<2; + SELECT * FROM t3; + } + } {2 3 4} + do_test delete-7.3 { + execsql { + SELECT * FROM cnt; + } + } {1} + do_test delete-7.4 { + execsql { + DELETE FROM t3; + SELECT * FROM t3; + } + } {} + do_test delete-7.5 { + execsql { + SELECT * FROM cnt; + } + } {4} + do_test delete-7.6 { + execsql { + INSERT INTO t3 VALUES(1); + INSERT INTO t3 SELECT a+1 FROM t3; + INSERT INTO t3 SELECT a+2 FROM t3; + CREATE TABLE t4 AS SELECT * FROM t3; + PRAGMA count_changes=ON; + DELETE FROM t3; + DELETE FROM t4; + } + } {4 4} +} ;# endif trigger +ifcapable {!trigger} { + execsql {DELETE FROM t3} +} +integrity_check delete-7.7 + +# Make sure error messages are consistent when attempting to delete +# from a read-only database. Ticket #304. +# +do_test delete-8.0 { + execsql { + PRAGMA count_changes=OFF; + INSERT INTO t3 VALUES(123); + SELECT * FROM t3; + } +} {123} +db close +catch {forcedelete test.db-journal} +catch {file attributes test.db -permissions 0444} +catch {file attributes test.db -readonly 1} +sqlite3 db test.db +set ::DB [sqlite3_connection_pointer db] +do_test delete-8.1 { + catchsql { + DELETE FROM t3; + } +} {1 {attempt to write a readonly database}} +do_test delete-8.2 { + execsql {SELECT * FROM t3} +} {123} +do_test delete-8.3 { + catchsql { + DELETE FROM t3 WHERE 1; + } +} {1 {attempt to write a readonly database}} +do_test delete-8.4 { + execsql {SELECT * FROM t3} +} {123} + +# Update for v3: In v2 the DELETE statement would succeed because no +# database writes actually occur. Version 3 refuses to open a transaction +# on a read-only file, so the statement fails. +do_test delete-8.5 { + catchsql { + DELETE FROM t3 WHERE a<100; + } +# v2 result: {0 {}} +} {1 {attempt to write a readonly database}} +do_test delete-8.6 { + execsql {SELECT * FROM t3} +} {123} +integrity_check delete-8.7 + +# Need to do the following for tcl 8.5 on mac. On that configuration, the +# -readonly flag is taken so seriously that a subsequent [forcedelete] +# (required before the next test file can be executed) will fail. +# +catch {file attributes test.db -readonly 0} +db close +forcedelete test.db test.db-journal + +# The following tests verify that SQLite correctly handles the case +# where an index B-Tree is being scanned, the rowid column being read +# from each index entry and another statement deletes some rows from +# the index B-Tree. At one point this (obscure) scenario was causing +# SQLite to return spurious SQLITE_CORRUPT errors and arguably incorrect +# query results. +# +do_test delete-9.1 { + sqlite3 db test.db + execsql { + CREATE TABLE t5(a, b); + CREATE TABLE t6(c, d); + INSERT INTO t5 VALUES(1, 2); + INSERT INTO t5 VALUES(3, 4); + INSERT INTO t5 VALUES(5, 6); + INSERT INTO t6 VALUES('a', 'b'); + INSERT INTO t6 VALUES('c', 'd'); + CREATE INDEX i5 ON t5(a); + CREATE INDEX i6 ON t6(c); + } +} {} +do_test delete-9.2 { + set res [list] + db eval { SELECT t5.rowid AS r, c, d FROM t5, t6 ORDER BY a } { + if {$r==2} { db eval { DELETE FROM t5 } } + lappend res $r $c $d + } + set res +} {1 a b 1 c d 2 a b {} c d} +do_test delete-9.3 { + execsql { + INSERT INTO t5 VALUES(1, 2); + INSERT INTO t5 VALUES(3, 4); + INSERT INTO t5 VALUES(5, 6); + } + set res [list] + db eval { SELECT t5.rowid AS r, c, d FROM t5, t6 ORDER BY a } { + if {$r==2} { db eval { DELETE FROM t5 WHERE rowid = 2 } } + lappend res $r $c $d + } + set res +} {1 a b 1 c d 2 a b {} c d 3 a b 3 c d} +do_test delete-9.4 { + execsql { + DELETE FROM t5; + INSERT INTO t5 VALUES(1, 2); + INSERT INTO t5 VALUES(3, 4); + INSERT INTO t5 VALUES(5, 6); + } + set res [list] + db eval { SELECT t5.rowid AS r, c, d FROM t5, t6 ORDER BY a } { + if {$r==2} { db eval { DELETE FROM t5 WHERE rowid = 1 } } + lappend res $r $c $d + } + set res +} {1 a b 1 c d 2 a b 2 c d 3 a b 3 c d} +do_test delete-9.5 { + execsql { + DELETE FROM t5; + INSERT INTO t5 VALUES(1, 2); + INSERT INTO t5 VALUES(3, 4); + INSERT INTO t5 VALUES(5, 6); + } + set res [list] + db eval { SELECT t5.rowid AS r, c, d FROM t5, t6 ORDER BY a } { + if {$r==2} { db eval { DELETE FROM t5 WHERE rowid = 3 } } + lappend res $r $c $d + } + set res +} {1 a b 1 c d 2 a b 2 c d} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/delete2.test b/components/external/SQLite-3.8.1/test/delete2.test new file mode 100644 index 0000000000000000000000000000000000000000..1668a3a9ae05c82ece49e3d0642531731c5f9135 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/delete2.test @@ -0,0 +1,119 @@ +# 2003 September 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is a test to replicate the bug reported by +# ticket #842. +# +# Ticket #842 was a database corruption problem caused by a DELETE that +# removed an index entry by not the main table entry. To recreate the +# problem do this: +# +# (1) Create a table with an index. Insert some data into that table. +# (2) Start a query on the table but do not complete the query. +# (3) Try to delete a single entry from the table. +# +# Step 3 will fail because there is still a read cursor on the table. +# But the database is corrupted by the DELETE. It turns out that the +# index entry was deleted first, before the table entry. And the index +# delete worked. Thus an entry was deleted from the index but not from +# the table. +# +# The solution to the problem was to detect that the table is locked +# before the index entry is deleted. +# +# $Id: delete2.test,v 1.8 2008/07/08 15:59:52 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table that has an index. +# +do_test delete2-1.1 { + set DB [sqlite3_connection_pointer db] + execsql { + CREATE TABLE q(s string, id string, constraint pk_q primary key(id)); + BEGIN; + INSERT INTO q(s,id) VALUES('hello','id.1'); + INSERT INTO q(s,id) VALUES('goodbye','id.2'); + INSERT INTO q(s,id) VALUES('again','id.3'); + END; + SELECT * FROM q; + } +} {hello id.1 goodbye id.2 again id.3} +do_test delete2-1.2 { + execsql { + SELECT * FROM q WHERE id='id.1'; + } +} {hello id.1} +integrity_check delete2-1.3 + +# Start a query on the table. The query should not use the index. +# Do not complete the query, thus leaving the table locked. +# +do_test delete2-1.4 { + set STMT [sqlite3_prepare $DB {SELECT * FROM q} -1 TAIL] + sqlite3_step $STMT +} SQLITE_ROW +integrity_check delete2-1.5 + +# Try to delete a row from the table while a read is in process. +# As of 2006-08-16, this is allowed. (It used to fail with SQLITE_LOCKED.) +# +do_test delete2-1.6 { + catchsql { + DELETE FROM q WHERE rowid=1 + } +} {0 {}} +integrity_check delete2-1.7 +do_test delete2-1.8 { + execsql { + SELECT * FROM q; + } +} {goodbye id.2 again id.3} + +# Finalize the query, thus clearing the lock on the table. Then +# retry the delete. The delete should work this time. +# +do_test delete2-1.9 { + sqlite3_finalize $STMT + catchsql { + DELETE FROM q WHERE rowid=1 + } +} {0 {}} +integrity_check delete2-1.10 +do_test delete2-1.11 { + execsql { + SELECT * FROM q; + } +} {goodbye id.2 again id.3} + +do_test delete2-2.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t2 VALUES(3, 4); + INSERT INTO t2 VALUES(5, 6); + } +} {} +do_test delete2-2.2 { + set res [list] + db eval { + SELECT CASE WHEN c = 5 THEN b ELSE NULL END AS b, c, d FROM t1, t2 + } { + db eval {DELETE FROM t1} + lappend res $b $c $d + } + set res +} {{} 3 4 {} 5 6} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/delete3.test b/components/external/SQLite-3.8.1/test/delete3.test new file mode 100644 index 0000000000000000000000000000000000000000..a31f6ec39e49eed7fb0b2445822466457c696774 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/delete3.test @@ -0,0 +1,57 @@ +# 2005 August 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is a test of the DELETE command where a +# large number of rows are deleted. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table that contains a large number of rows. +# +do_test delete3-1.1 { + execsql { + CREATE TABLE t1(x integer primary key); + BEGIN; + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 SELECT x+2 FROM t1; + INSERT INTO t1 SELECT x+4 FROM t1; + INSERT INTO t1 SELECT x+8 FROM t1; + INSERT INTO t1 SELECT x+16 FROM t1; + INSERT INTO t1 SELECT x+32 FROM t1; + INSERT INTO t1 SELECT x+64 FROM t1; + INSERT INTO t1 SELECT x+128 FROM t1; + INSERT INTO t1 SELECT x+256 FROM t1; + INSERT INTO t1 SELECT x+512 FROM t1; + INSERT INTO t1 SELECT x+1024 FROM t1; + INSERT INTO t1 SELECT x+2048 FROM t1; + INSERT INTO t1 SELECT x+4096 FROM t1; + INSERT INTO t1 SELECT x+8192 FROM t1; + INSERT INTO t1 SELECT x+16384 FROM t1; + INSERT INTO t1 SELECT x+32768 FROM t1; + INSERT INTO t1 SELECT x+65536 FROM t1; + INSERT INTO t1 SELECT x+131072 FROM t1; + INSERT INTO t1 SELECT x+262144 FROM t1; + COMMIT; + SELECT count(*) FROM t1; + } +} {524288} +do_test delete3-1.2 { + execsql { + DELETE FROM t1 WHERE x%2==0; + SELECT count(*) FROM t1; + } +} {262144} +integrity_check delete3-1.3 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/descidx1.test b/components/external/SQLite-3.8.1/test/descidx1.test new file mode 100644 index 0000000000000000000000000000000000000000..a223664ff32e31c46f0076bd15bf532a0317a95f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/descidx1.test @@ -0,0 +1,364 @@ +# 2005 December 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is descending indices. +# +# $Id: descidx1.test,v 1.10 2008/03/19 00:21:31 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +db eval {PRAGMA legacy_file_format=OFF} + +# This procedure sets the value of the file-format in file 'test.db' +# to $newval. Also, the schema cookie is incremented. +# +proc set_file_format {newval} { + hexio_write test.db 44 [hexio_render_int32 $newval] + set schemacookie [hexio_get_int [hexio_read test.db 40 4]] + incr schemacookie + hexio_write test.db 40 [hexio_render_int32 $schemacookie] + return {} +} + +# This procedure returns the value of the file-format in file 'test.db'. +# +proc get_file_format {{fname test.db}} { + return [hexio_get_int [hexio_read $fname 44 4]] +} + + +# Verify that the file format starts as 4. +# +do_test descidx1-1.1 { + execsql { + CREATE TABLE t1(a,b); + CREATE INDEX i1 ON t1(b ASC); + } + get_file_format +} {4} +do_test descidx1-1.2 { + execsql { + CREATE INDEX i2 ON t1(a DESC); + } + get_file_format +} {4} + +# Put some information in the table and verify that the descending +# index actually works. +# +do_test descidx1-2.1 { + execsql { + INSERT INTO t1 VALUES(1,1); + INSERT INTO t1 VALUES(2,2); + INSERT INTO t1 SELECT a+2, a+2 FROM t1; + INSERT INTO t1 SELECT a+4, a+4 FROM t1; + SELECT b FROM t1 WHERE a>3 AND a<7; + } +} {6 5 4} +do_test descidx1-2.2 { + execsql { + SELECT a FROM t1 WHERE b>3 AND b<7; + } +} {4 5 6} +do_test descidx1-2.3 { + execsql { + SELECT b FROM t1 WHERE a>=3 AND a<7; + } +} {6 5 4 3} +do_test descidx1-2.4 { + execsql { + SELECT b FROM t1 WHERE a>3 AND a<=7; + } +} {7 6 5 4} +do_test descidx1-2.5 { + execsql { + SELECT b FROM t1 WHERE a>=3 AND a<=7; + } +} {7 6 5 4 3} +do_test descidx1-2.6 { + execsql { + SELECT a FROM t1 WHERE b>=3 AND b<=7; + } +} {3 4 5 6 7} + +# This procedure executes the SQL. Then it checks to see if the OP_Sort +# opcode was executed. If an OP_Sort did occur, then "sort" is appended +# to the result. If no OP_Sort happened, then "nosort" is appended. +# +# This procedure is used to check to make sure sorting is or is not +# occurring as expected. +# +proc cksort {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + if {$::sqlite_sort_count} {set x sort} {set x nosort} + lappend data $x + return $data +} + +# Test sorting using a descending index. +# +do_test descidx1-3.1 { + cksort {SELECT a FROM t1 ORDER BY a} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx1-3.2 { + cksort {SELECT a FROM t1 ORDER BY a ASC} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx1-3.3 { + cksort {SELECT a FROM t1 ORDER BY a DESC} +} {8 7 6 5 4 3 2 1 nosort} +do_test descidx1-3.4 { + cksort {SELECT b FROM t1 ORDER BY a} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx1-3.5 { + cksort {SELECT b FROM t1 ORDER BY a ASC} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx1-3.6 { + cksort {SELECT b FROM t1 ORDER BY a DESC} +} {8 7 6 5 4 3 2 1 nosort} +do_test descidx1-3.7 { + cksort {SELECT a FROM t1 ORDER BY b} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx1-3.8 { + cksort {SELECT a FROM t1 ORDER BY b ASC} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx1-3.9 { + cksort {SELECT a FROM t1 ORDER BY b DESC} +} {8 7 6 5 4 3 2 1 nosort} +do_test descidx1-3.10 { + cksort {SELECT b FROM t1 ORDER BY b} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx1-3.11 { + cksort {SELECT b FROM t1 ORDER BY b ASC} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx1-3.12 { + cksort {SELECT b FROM t1 ORDER BY b DESC} +} {8 7 6 5 4 3 2 1 nosort} + +do_test descidx1-3.21 { + cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a} +} {4 5 6 7 nosort} +do_test descidx1-3.22 { + cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a ASC} +} {4 5 6 7 nosort} +do_test descidx1-3.23 { + cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a DESC} +} {7 6 5 4 nosort} +do_test descidx1-3.24 { + cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a} +} {4 5 6 7 nosort} +do_test descidx1-3.25 { + cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a ASC} +} {4 5 6 7 nosort} +do_test descidx1-3.26 { + cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a DESC} +} {7 6 5 4 nosort} + +# Create a table with indices that are descending on some terms and +# ascending on others. +# +ifcapable bloblit { + do_test descidx1-4.1 { + execsql { + CREATE TABLE t2(a INT, b TEXT, c BLOB, d REAL); + CREATE INDEX i3 ON t2(a ASC, b DESC, c ASC); + CREATE INDEX i4 ON t2(b DESC, a ASC, d DESC); + INSERT INTO t2 VALUES(1,'one',x'31',1.0); + INSERT INTO t2 VALUES(2,'two',x'3232',2.0); + INSERT INTO t2 VALUES(3,'three',x'333333',3.0); + INSERT INTO t2 VALUES(4,'four',x'34343434',4.0); + INSERT INTO t2 VALUES(5,'five',x'3535353535',5.0); + INSERT INTO t2 VALUES(6,'six',x'363636363636',6.0); + INSERT INTO t2 VALUES(2,'two',x'323232',2.1); + INSERT INTO t2 VALUES(2,'zwei',x'3232',2.2); + INSERT INTO t2 VALUES(2,NULL,NULL,2.3); + SELECT count(*) FROM t2; + } + } {9} + do_test descidx1-4.2 { + execsql { + SELECT d FROM t2 ORDER BY a; + } + } {1.0 2.2 2.0 2.1 2.3 3.0 4.0 5.0 6.0} + do_test descidx1-4.3 { + execsql { + SELECT d FROM t2 WHERE a>=2 ORDER BY a; + } + } {2.2 2.0 2.1 2.3 3.0 4.0 5.0 6.0} + do_test descidx1-4.4 { + execsql { + SELECT d FROM t2 WHERE a>2 ORDER BY a; + } + } {3.0 4.0 5.0 6.0} + do_test descidx1-4.5 { + execsql { + SELECT d FROM t2 WHERE a=2 AND b>'two'; + } + } {2.2} + do_test descidx1-4.6 { + execsql { + SELECT d FROM t2 WHERE a=2 AND b>='two'; + } + } {2.2 2.0 2.1} + do_test descidx1-4.7 { + execsql { + SELECT d FROM t2 WHERE a=2 AND b<'two'; + } + } {} + do_test descidx1-4.8 { + execsql { + SELECT d FROM t2 WHERE a=2 AND b<='two'; + } + } {2.0 2.1} +} + +do_test descidx1-5.1 { + execsql { + CREATE TABLE t3(a,b,c,d); + CREATE INDEX t3i1 ON t3(a DESC, b ASC, c DESC, d ASC); + INSERT INTO t3 VALUES(0,0,0,0); + INSERT INTO t3 VALUES(0,0,0,1); + INSERT INTO t3 VALUES(0,0,1,0); + INSERT INTO t3 VALUES(0,0,1,1); + INSERT INTO t3 VALUES(0,1,0,0); + INSERT INTO t3 VALUES(0,1,0,1); + INSERT INTO t3 VALUES(0,1,1,0); + INSERT INTO t3 VALUES(0,1,1,1); + INSERT INTO t3 VALUES(1,0,0,0); + INSERT INTO t3 VALUES(1,0,0,1); + INSERT INTO t3 VALUES(1,0,1,0); + INSERT INTO t3 VALUES(1,0,1,1); + INSERT INTO t3 VALUES(1,1,0,0); + INSERT INTO t3 VALUES(1,1,0,1); + INSERT INTO t3 VALUES(1,1,1,0); + INSERT INTO t3 VALUES(1,1,1,1); + SELECT count(*) FROM t3; + } +} {16} +do_test descidx1-5.2 { + cksort { + SELECT a||b||c||d FROM t3 ORDER BY a,b,c,d; + } +} {0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 sort} +do_test descidx1-5.3 { + cksort { + SELECT a||b||c||d FROM t3 ORDER BY a DESC, b ASC, c DESC, d ASC; + } +} {1010 1011 1000 1001 1110 1111 1100 1101 0010 0011 0000 0001 0110 0111 0100 0101 nosort} +do_test descidx1-5.4 { + cksort { + SELECT a||b||c||d FROM t3 ORDER BY a ASC, b DESC, c ASC, d DESC; + } +} {0101 0100 0111 0110 0001 0000 0011 0010 1101 1100 1111 1110 1001 1000 1011 1010 nosort} +do_test descidx1-5.5 { + cksort { + SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a DESC, b ASC, c DESC + } +} {101 100 111 110 001 000 011 010 nosort} +do_test descidx1-5.6 { + cksort { + SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a ASC, b DESC, c ASC + } +} {010 011 000 001 110 111 100 101 nosort} +do_test descidx1-5.7 { + cksort { + SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a ASC, b DESC, c DESC + } +} {011 010 001 000 111 110 101 100 sort} +do_test descidx1-5.8 { + cksort { + SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a ASC, b ASC, c ASC + } +} {000 001 010 011 100 101 110 111 sort} +do_test descidx1-5.9 { + cksort { + SELECT a||b||c FROM t3 WHERE d=0 ORDER BY a DESC, b DESC, c ASC + } +} {110 111 100 101 010 011 000 001 sort} + +# Test the legacy_file_format pragma here because we have access to +# the get_file_format command. +# +ifcapable legacyformat { + do_test descidx1-6.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql {PRAGMA legacy_file_format} + } {1} +} else { + do_test descidx1-6.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql {PRAGMA legacy_file_format} + } {0} +} +do_test descidx1-6.2 { + execsql {PRAGMA legacy_file_format=YES} + execsql {PRAGMA legacy_file_format} +} {1} +do_test descidx1-6.3 { + execsql { + CREATE TABLE t1(a,b,c); + } + get_file_format +} {1} +ifcapable vacuum { + # Verify that the file format is preserved across a vacuum. + do_test descidx1-6.3.1 { + execsql {VACUUM} + get_file_format + } {1} +} +do_test descidx1-6.4 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql {PRAGMA legacy_file_format=NO} + execsql {PRAGMA legacy_file_format} +} {0} +do_test descidx1-6.5 { + execsql { + CREATE TABLE t1(a,b,c); + CREATE INDEX i1 ON t1(a ASC, b DESC, c ASC); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(1,1,0); + INSERT INTO t1 VALUES(1,2,1); + INSERT INTO t1 VALUES(1,3,4); + } + get_file_format +} {4} +ifcapable vacuum { + # Verify that the file format is preserved across a vacuum. + do_test descidx1-6.6 { + execsql {VACUUM} + get_file_format + } {4} + do_test descidx1-6.7 { + execsql { + PRAGMA legacy_file_format=ON; + VACUUM; + } + get_file_format + } {4} +} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/descidx2.test b/components/external/SQLite-3.8.1/test/descidx2.test new file mode 100644 index 0000000000000000000000000000000000000000..fdc3eb079477c8593e0f61e06f69842dd4b59f9b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/descidx2.test @@ -0,0 +1,185 @@ +# 2005 December 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is descending indices. +# +# $Id: descidx2.test,v 1.5 2008/03/19 00:21:31 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + + +db eval {PRAGMA legacy_file_format=OFF} + +# This procedure sets the value of the file-format in file 'test.db' +# to $newval. Also, the schema cookie is incremented. +# +proc set_file_format {newval} { + hexio_write test.db 44 [hexio_render_int32 $newval] + set schemacookie [hexio_get_int [hexio_read test.db 40 4]] + incr schemacookie + hexio_write test.db 40 [hexio_render_int32 $schemacookie] + return {} +} + +# This procedure returns the value of the file-format in file 'test.db'. +# +proc get_file_format {{fname test.db}} { + return [hexio_get_int [hexio_read $fname 44 4]] +} + + +# Verify that the file format starts as 4 +# +do_test descidx2-1.1 { + execsql { + CREATE TABLE t1(a,b); + CREATE INDEX i1 ON t1(b ASC); + } + get_file_format +} {4} +do_test descidx2-1.2 { + execsql { + CREATE INDEX i2 ON t1(a DESC); + } + get_file_format +} {4} + +# Before adding any information to the database, set the file format +# back to three. Then close and reopen the database. With the file +# format set to three, SQLite should ignore the DESC argument on the +# index. +# +do_test descidx2-2.0 { + set_file_format 3 + db close + sqlite3 db test.db + get_file_format +} {3} + +# Put some information in the table and verify that the DESC +# on the index is ignored. +# +do_test descidx2-2.1 { + execsql { + INSERT INTO t1 VALUES(1,1); + INSERT INTO t1 VALUES(2,2); + INSERT INTO t1 SELECT a+2, a+2 FROM t1; + INSERT INTO t1 SELECT a+4, a+4 FROM t1; + SELECT b FROM t1 WHERE a>3 AND a<7; + } +} {4 5 6} +do_test descidx2-2.2 { + execsql { + SELECT a FROM t1 WHERE b>3 AND b<7; + } +} {4 5 6} +do_test descidx2-2.3 { + execsql { + SELECT b FROM t1 WHERE a>=3 AND a<7; + } +} {3 4 5 6} +do_test descidx2-2.4 { + execsql { + SELECT b FROM t1 WHERE a>3 AND a<=7; + } +} {4 5 6 7} +do_test descidx2-2.5 { + execsql { + SELECT b FROM t1 WHERE a>=3 AND a<=7; + } +} {3 4 5 6 7} +do_test descidx2-2.6 { + execsql { + SELECT a FROM t1 WHERE b>=3 AND b<=7; + } +} {3 4 5 6 7} + +# This procedure executes the SQL. Then it checks to see if the OP_Sort +# opcode was executed. If an OP_Sort did occur, then "sort" is appended +# to the result. If no OP_Sort happened, then "nosort" is appended. +# +# This procedure is used to check to make sure sorting is or is not +# occurring as expected. +# +proc cksort {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + if {$::sqlite_sort_count} {set x sort} {set x nosort} + lappend data $x + return $data +} + +# Test sorting using a descending index. +# +do_test descidx2-3.1 { + cksort {SELECT a FROM t1 ORDER BY a} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx2-3.2 { + cksort {SELECT a FROM t1 ORDER BY a ASC} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx2-3.3 { + cksort {SELECT a FROM t1 ORDER BY a DESC} +} {8 7 6 5 4 3 2 1 nosort} +do_test descidx2-3.4 { + cksort {SELECT b FROM t1 ORDER BY a} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx2-3.5 { + cksort {SELECT b FROM t1 ORDER BY a ASC} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx2-3.6 { + cksort {SELECT b FROM t1 ORDER BY a DESC} +} {8 7 6 5 4 3 2 1 nosort} +do_test descidx2-3.7 { + cksort {SELECT a FROM t1 ORDER BY b} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx2-3.8 { + cksort {SELECT a FROM t1 ORDER BY b ASC} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx2-3.9 { + cksort {SELECT a FROM t1 ORDER BY b DESC} +} {8 7 6 5 4 3 2 1 nosort} +do_test descidx2-3.10 { + cksort {SELECT b FROM t1 ORDER BY b} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx2-3.11 { + cksort {SELECT b FROM t1 ORDER BY b ASC} +} {1 2 3 4 5 6 7 8 nosort} +do_test descidx2-3.12 { + cksort {SELECT b FROM t1 ORDER BY b DESC} +} {8 7 6 5 4 3 2 1 nosort} + +do_test descidx2-3.21 { + cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a} +} {4 5 6 7 nosort} +do_test descidx2-3.22 { + cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a ASC} +} {4 5 6 7 nosort} +do_test descidx2-3.23 { + cksort {SELECT a FROM t1 WHERE a>3 AND a<8 ORDER BY a DESC} +} {7 6 5 4 nosort} +do_test descidx2-3.24 { + cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a} +} {4 5 6 7 nosort} +do_test descidx2-3.25 { + cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a ASC} +} {4 5 6 7 nosort} +do_test descidx2-3.26 { + cksort {SELECT b FROM t1 WHERE a>3 AND a<8 ORDER BY a DESC} +} {7 6 5 4 nosort} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/descidx3.test b/components/external/SQLite-3.8.1/test/descidx3.test new file mode 100644 index 0000000000000000000000000000000000000000..c375acc705fbffe8161cd21a9a7c1cf5e2968238 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/descidx3.test @@ -0,0 +1,154 @@ +# 2006 January 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is descending indices. +# +# $Id: descidx3.test,v 1.6 2008/03/19 00:21:31 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +ifcapable !bloblit { + finish_test + return +} +db eval {PRAGMA legacy_file_format=OFF} + +# This procedure sets the value of the file-format in file 'test.db' +# to $newval. Also, the schema cookie is incremented. +# +proc set_file_format {newval} { + hexio_write test.db 44 [hexio_render_int32 $newval] + set schemacookie [hexio_get_int [hexio_read test.db 40 4]] + incr schemacookie + hexio_write test.db 40 [hexio_render_int32 $schemacookie] + return {} +} + +# This procedure returns the value of the file-format in file 'test.db'. +# +proc get_file_format {{fname test.db}} { + return [hexio_get_int [hexio_read $fname 44 4]] +} + +# Verify that the file format starts as 4. +# +do_test descidx3-1.1 { + execsql { + CREATE TABLE t1(i INTEGER PRIMARY KEY,a,b,c,d); + CREATE INDEX t1i1 ON t1(a DESC, b ASC, c DESC); + CREATE INDEX t1i2 ON t1(b DESC, c ASC, d DESC); + } + get_file_format +} {4} + +# Put some information in the table and verify that the descending +# index actually works. +# +do_test descidx3-2.1 { + execsql { + INSERT INTO t1 VALUES(1, NULL, NULL, NULL, NULL); + INSERT INTO t1 VALUES(2, 2, 2, 2, 2); + INSERT INTO t1 VALUES(3, 3, 3, 3, 3); + INSERT INTO t1 VALUES(4, 2.5, 2.5, 2.5, 2.5); + INSERT INTO t1 VALUES(5, -5, -5, -5, -5); + INSERT INTO t1 VALUES(6, 'six', 'six', 'six', 'six'); + INSERT INTO t1 VALUES(7, x'77', x'77', x'77', x'77'); + INSERT INTO t1 VALUES(8, 'eight', 'eight', 'eight', 'eight'); + INSERT INTO t1 VALUES(9, x'7979', x'7979', x'7979', x'7979'); + SELECT count(*) FROM t1; + } +} 9 +do_test descidx3-2.2 { + execsql { + SELECT i FROM t1 ORDER BY a; + } +} {1 5 2 4 3 8 6 7 9} +do_test descidx3-2.3 { + execsql { + SELECT i FROM t1 ORDER BY a DESC; + } +} {9 7 6 8 3 4 2 5 1} + +# The "natural" order for the index is decreasing +do_test descidx3-2.4 { + execsql { + SELECT i FROM t1 WHERE a<=x'7979'; + } +} {9 7 6 8 3 4 2 5} +do_test descidx3-2.5 { + execsql { + SELECT i FROM t1 WHERE a>-99; + } +} {9 7 6 8 3 4 2 5} + +# Even when all values of t1.a are the same, sorting by A returns +# the rows in reverse order because this the natural order of the +# index. +# +do_test descidx3-3.1 { + execsql { + UPDATE t1 SET a=1; + SELECT i FROM t1 ORDER BY a; + } +} {9 7 6 8 3 4 2 5 1} +do_test descidx3-3.2 { + execsql { + SELECT i FROM t1 WHERE a=1 AND b>0 AND b<'zzz' + } +} {2 4 3 8 6} +do_test descidx3-3.3 { + execsql { + SELECT i FROM t1 WHERE b>0 AND b<'zzz' + } +} {6 8 3 4 2} +do_test descidx3-3.4 { + execsql { + SELECT i FROM t1 WHERE a=1 AND b>-9999 AND b-9999 AND b0 AND b<'zzz'; + }] + } {2 3 4 6 8} + do_test descidx3-4.2 { + execsql { + UPDATE t1 SET a=1; + SELECT i FROM t1 WHERE a IN (1,2) AND b>0 AND b<'zzz'; + } + } {2 4 3 8 6} + do_test descidx3-4.3 { + execsql { + UPDATE t1 SET b=2; + SELECT i FROM t1 WHERE a IN (1,2) AND b>0 AND b<'zzz'; + } + } {9 7 6 8 3 4 2 5 1} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/diskfull.test b/components/external/SQLite-3.8.1/test/diskfull.test new file mode 100644 index 0000000000000000000000000000000000000000..391dfb4fcf440f7515f1dbb1f3f812737408f561 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/diskfull.test @@ -0,0 +1,115 @@ +# 2001 October 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing for correct handling of disk full +# errors. +# +# $Id: diskfull.test,v 1.8 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set sqlite_io_error_persist 0 +set sqlite_io_error_hit 0 +set sqlite_io_error_pending 0 +do_test diskfull-1.1 { + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randstr(1000,1000)); + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + CREATE INDEX t1i1 ON t1(x); + CREATE TABLE t2 AS SELECT x AS a, x AS b FROM t1; + CREATE INDEX t2i1 ON t2(b); + } +} {} +set sqlite_diskfull_pending 0 +integrity_check diskfull-1.2 +do_test diskfull-1.3 { + set sqlite_diskfull_pending 1 + catchsql { + INSERT INTO t1 SELECT * FROM t1; + } +} {1 {database or disk is full}} +set sqlite_diskfull_pending 0 +integrity_check diskfull-1.4 +do_test diskfull-1.5 { + set sqlite_diskfull_pending 1 + catchsql { + DELETE FROM t1; + } +} {1 {database or disk is full}} +set sqlite_diskfull_pending 0 +set sqlite_io_error_hit 0 +integrity_check diskfull-1.6 + +proc do_diskfull_test {prefix sql} { + set ::go 1 + set ::sql $sql + set ::i 1 + while {$::go} { + incr ::i + do_test ${prefix}.$::i.1 { + set ::sqlite_diskfull_pending $::i + set ::sqlite_diskfull 0 + set r [catchsql $::sql] + if {!$::sqlite_diskfull} { + set r {1 {database or disk is full}} + set ::go 0 + } + if {$r=="1 {disk I/O error}"} { + set r {1 {database or disk is full}} + } + set r + } {1 {database or disk is full}} + set ::sqlite_diskfull_pending 0 + db close + sqlite3 db test.db + integrity_check ${prefix}.$::i.2 + } +} + +do_diskfull_test diskfull-2 VACUUM + +# db close +# forcedelete test.db +# forcedelete test.db-journal +# sqlite3 db test.db +# +# do_test diskfull-3.1 { +# execsql { +# PRAGMA default_cache_size = 10; +# CREATE TABLE t3(a, b, UNIQUE(a, b)); +# INSERT INTO t3 VALUES( randstr(100, 100), randstr(100, 100) ); +# INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; +# INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; +# INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; +# INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; +# INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; +# INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; +# INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; +# UPDATE t3 +# SET b = (SELECT a FROM t3 WHERE rowid = (SELECT max(rowid)-1 FROM t3)) +# WHERE rowid = (SELECT max(rowid) FROM t3); +# PRAGMA cache_size; +# } +# } {10} +# +# do_diskfull_test diskfull-3.2 { +# BEGIN; +# INSERT INTO t3 VALUES( randstr(100, 100), randstr(100, 100) ); +# UPDATE t3 SET a = b; +# COMMIT; +# } + +finish_test diff --git a/components/external/SQLite-3.8.1/test/distinct.test b/components/external/SQLite-3.8.1/test/distinct.test new file mode 100644 index 0000000000000000000000000000000000000000..2b006d3e61cf57dd223e459e7109acdd0e0da451 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/distinct.test @@ -0,0 +1,200 @@ +# 2011 July 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is the DISTINCT modifier. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +set testprefix distinct + + +proc is_distinct_noop {sql} { + set sql1 $sql + set sql2 [string map {DISTINCT ""} $sql] + + set program1 [list] + set program2 [list] + db eval "EXPLAIN $sql1" { + if {$opcode != "Noop"} { lappend program1 $opcode } + } + db eval "EXPLAIN $sql2" { + if {$opcode != "Noop"} { lappend program2 $opcode } + } + + return [expr {$program1==$program2}] +} + +proc do_distinct_noop_test {tn sql} { + uplevel [list do_test $tn [list is_distinct_noop $sql] 1] +} +proc do_distinct_not_noop_test {tn sql} { + uplevel [list do_test $tn [list is_distinct_noop $sql] 0] +} + +proc do_temptables_test {tn sql temptables} { + uplevel [list do_test $tn [subst -novar { + set ret "" + db eval "EXPLAIN [set sql]" { + if {$opcode == "OpenEphemeral" || $opcode == "SorterOpen"} { + if {$p5 != "08" && $p5!="00"} { error "p5 = $p5" } + if {$p5 == "08"} { + lappend ret hash + } else { + lappend ret btree + } + } + } + set ret + }] $temptables] +} + + +#------------------------------------------------------------------------- +# The following tests - distinct-1.* - check that the planner correctly +# detects cases where a UNIQUE index means that a DISTINCT clause is +# redundant. Currently the planner only detects such cases when there +# is a single table in the FROM clause. +# +do_execsql_test 1.0 { + CREATE TABLE t1(a, b, c, d); + CREATE UNIQUE INDEX i1 ON t1(b, c); + CREATE UNIQUE INDEX i2 ON t1(d COLLATE nocase); + + CREATE TABLE t2(x INTEGER PRIMARY KEY, y); + + CREATE TABLE t3(c1 PRIMARY KEY NOT NULL, c2 NOT NULL); + CREATE INDEX i3 ON t3(c2); + + CREATE TABLE t4(a, b NOT NULL, c NOT NULL, d NOT NULL); + CREATE UNIQUE INDEX t4i1 ON t4(b, c); + CREATE UNIQUE INDEX t4i2 ON t4(d COLLATE nocase); +} +foreach {tn noop sql} { + + 1.1 0 "SELECT DISTINCT b, c FROM t1" + 1.2 1 "SELECT DISTINCT b, c FROM t4" + 2.1 0 "SELECT DISTINCT c FROM t1 WHERE b = ?" + 2.2 1 "SELECT DISTINCT c FROM t4 WHERE b = ?" + 3 1 "SELECT DISTINCT rowid FROM t1" + 4 1 "SELECT DISTINCT rowid, a FROM t1" + 5 1 "SELECT DISTINCT x FROM t2" + 6 1 "SELECT DISTINCT * FROM t2" + 7 1 "SELECT DISTINCT * FROM (SELECT * FROM t2)" + + 8.1 0 "SELECT DISTINCT * FROM t1" + 8.2 1 "SELECT DISTINCT * FROM t4" + + 8 0 "SELECT DISTINCT a, b FROM t1" + + 9 0 "SELECT DISTINCT c FROM t1 WHERE b IN (1,2)" + 10 0 "SELECT DISTINCT c FROM t1" + 11 0 "SELECT DISTINCT b FROM t1" + + 12.1 0 "SELECT DISTINCT a, d FROM t1" + 12.2 0 "SELECT DISTINCT a, d FROM t4" + 13.1 0 "SELECT DISTINCT a, b, c COLLATE nocase FROM t1" + 13.2 0 "SELECT DISTINCT a, b, c COLLATE nocase FROM t4" + 14.1 0 "SELECT DISTINCT a, d COLLATE nocase FROM t1" + 14.2 1 "SELECT DISTINCT a, d COLLATE nocase FROM t4" + + 15 0 "SELECT DISTINCT a, d COLLATE binary FROM t1" + 16.1 0 "SELECT DISTINCT a, b, c COLLATE binary FROM t1" + 16.2 1 "SELECT DISTINCT a, b, c COLLATE binary FROM t4" + + 16 0 "SELECT DISTINCT t1.rowid FROM t1, t2" + 17 0 { /* Technically, it would be possible to detect that DISTINCT + ** is a no-op in cases like the following. But SQLite does not + ** do so. */ + SELECT DISTINCT t1.rowid FROM t1, t2 WHERE t1.rowid=t2.rowid } + + 18 1 "SELECT DISTINCT c1, c2 FROM t3" + 19 1 "SELECT DISTINCT c1 FROM t3" + 20 1 "SELECT DISTINCT * FROM t3" + 21 0 "SELECT DISTINCT c2 FROM t3" + + 22 0 "SELECT DISTINCT * FROM (SELECT 1, 2, 3 UNION SELECT 4, 5, 6)" + 23 1 "SELECT DISTINCT rowid FROM (SELECT 1, 2, 3 UNION SELECT 4, 5, 6)" + + 24 0 "SELECT DISTINCT rowid/2 FROM t1" + 25 1 "SELECT DISTINCT rowid/2, rowid FROM t1" + 26.1 0 "SELECT DISTINCT rowid/2, b FROM t1 WHERE c = ?" + 26.2 1 "SELECT DISTINCT rowid/2, b FROM t4 WHERE c = ?" +} { + if {$noop} { + do_distinct_noop_test 1.$tn $sql + } else { + do_distinct_not_noop_test 1.$tn $sql + } +} + +#------------------------------------------------------------------------- +# The following tests - distinct-2.* - test cases where an index is +# used to deliver results in order of the DISTINCT expressions. +# +drop_all_tables +do_execsql_test 2.0 { + CREATE TABLE t1(a, b, c); + + CREATE INDEX i1 ON t1(a, b); + CREATE INDEX i2 ON t1(b COLLATE nocase, c COLLATE nocase); + + INSERT INTO t1 VALUES('a', 'b', 'c'); + INSERT INTO t1 VALUES('A', 'B', 'C'); + INSERT INTO t1 VALUES('a', 'b', 'c'); + INSERT INTO t1 VALUES('A', 'B', 'C'); +} + +foreach {tn sql temptables res} { + 1 "a, b FROM t1" {} {A B a b} + 2 "b, a FROM t1" {} {B A b a} + 3 "a, b, c FROM t1" {hash} {a b c A B C} + 4 "a, b, c FROM t1 ORDER BY a, b, c" {btree} {A B C a b c} + 5 "b FROM t1 WHERE a = 'a'" {} {b} + 6 "b FROM t1 ORDER BY +b COLLATE binary" {btree hash} {B b} + 7 "a FROM t1" {} {A a} + 8 "b COLLATE nocase FROM t1" {} {b} + 9 "b COLLATE nocase FROM t1 ORDER BY b COLLATE nocase" {} {b} +} { + do_execsql_test 2.$tn.1 "SELECT DISTINCT $sql" $res + do_temptables_test 2.$tn.2 "SELECT DISTINCT $sql" $temptables +} + +do_execsql_test 2.A { + SELECT (SELECT DISTINCT o.a FROM t1 AS i) FROM t1 AS o ORDER BY rowid; +} {a A a A} + +do_test 3.0 { + db eval { + CREATE TABLE t3(a INTEGER, b INTEGER, c, UNIQUE(a,b)); + INSERT INTO t3 VALUES + (null, null, 1), + (null, null, 2), + (null, 3, 4), + (null, 3, 5), + (6, null, 7), + (6, null, 8); + SELECT DISTINCT a, b FROM t3 ORDER BY +a, +b; + } +} {{} {} {} 3 6 {}} +do_test 3.1 { + regexp {OpenEphemeral} [db eval { + EXPLAIN SELECT DISTINCT a, b FROM t3 ORDER BY +a, +b; + }] +} {0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/distinctagg.test b/components/external/SQLite-3.8.1/test/distinctagg.test new file mode 100644 index 0000000000000000000000000000000000000000..9b5dc2167822661d99de6b155aa979f3379f379a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/distinctagg.test @@ -0,0 +1,62 @@ +# 2005 September 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is the DISTINCT modifier on aggregate functions. +# +# $Id: distinctagg.test,v 1.3 2009/02/09 13:19:28 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test distinctagg-1.1 { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(1,3,4); + INSERT INTO t1 VALUES(1,3,5); + SELECT count(distinct a), + count(distinct b), + count(distinct c), + count(all a) FROM t1; + } +} {1 2 3 3} +do_test distinctagg-1.2 { + execsql { + SELECT b, count(distinct c) FROM t1 GROUP BY b ORDER BY b + } +} {2 1 3 2} +do_test distinctagg-1.3 { + execsql { + INSERT INTO t1 SELECT a+1, b+3, c+5 FROM t1; + INSERT INTO t1 SELECT a+2, b+6, c+10 FROM t1; + INSERT INTO t1 SELECT a+4, b+12, c+20 FROM t1; + SELECT count(*), count(distinct a), count(distinct b) FROM t1 + } +} {24 8 16} +do_test distinctagg-1.4 { + execsql { + SELECT a, count(distinct c) FROM t1 GROUP BY a ORDER BY a + } +} {1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3} + +do_test distinctagg-2.1 { + catchsql { + SELECT count(distinct) FROM t1; + } +} {1 {DISTINCT aggregates must have exactly one argument}} +do_test distinctagg-2.2 { + catchsql { + SELECT group_concat(distinct a,b) FROM t1; + } +} {1 {DISTINCT aggregates must have exactly one argument}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_createtable.test b/components/external/SQLite-3.8.1/test/e_createtable.test new file mode 100644 index 0000000000000000000000000000000000000000..b231cee8047a633a360244d2805da0a1072e134f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_createtable.test @@ -0,0 +1,1922 @@ +# 2010 September 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_createtable.html document are correct. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set ::testprefix e_createtable + +# Test organization: +# +# e_createtable-0.*: Test that the syntax diagrams are correct. +# +# e_createtable-1.*: Test statements related to table and database names, +# the TEMP and TEMPORARY keywords, and the IF NOT EXISTS clause. +# +# e_createtable-2.*: Test "CREATE TABLE AS" statements. +# + +proc do_createtable_tests {nm args} { + uplevel do_select_tests [list e_createtable-$nm] $args +} + + +#------------------------------------------------------------------------- +# This command returns a serialized tcl array mapping from the name of +# each attached database to a list of tables in that database. For example, +# if the database schema is created with: +# +# CREATE TABLE t1(x); +# CREATE TEMP TABLE t2(x); +# CREATE TEMP TABLE t3(x); +# +# Then this command returns "main t1 temp {t2 t3}". +# +proc table_list {} { + set res [list] + db eval { pragma database_list } a { + set dbname $a(name) + set master $a(name).sqlite_master + if {$dbname == "temp"} { set master sqlite_temp_master } + lappend res $dbname [ + db eval "SELECT DISTINCT tbl_name FROM $master ORDER BY tbl_name" + ] + } + set res +} + + +do_createtable_tests 0.1.1 -repair { + drop_all_tables +} { + 1 "CREATE TABLE t1(c1 one)" {} + 2 "CREATE TABLE t1(c1 one two)" {} + 3 "CREATE TABLE t1(c1 one two three)" {} + 4 "CREATE TABLE t1(c1 one two three four)" {} + 5 "CREATE TABLE t1(c1 one two three four(14))" {} + 6 "CREATE TABLE t1(c1 one two three four(14, 22))" {} + 7 "CREATE TABLE t1(c1 var(+14, -22.3))" {} + 8 "CREATE TABLE t1(c1 var(1.0e10))" {} +} +do_createtable_tests 0.1.2 -error { + near "%s": syntax error +} { + 1 "CREATE TABLE t1(c1 one(number))" {number} +} + + +# syntax diagram column-constraint +# +do_createtable_tests 0.2.1 -repair { + drop_all_tables + execsql { CREATE TABLE t2(x PRIMARY KEY) } +} { + 1.1 "CREATE TABLE t1(c1 text PRIMARY KEY)" {} + 1.2 "CREATE TABLE t1(c1 text PRIMARY KEY ASC)" {} + 1.3 "CREATE TABLE t1(c1 text PRIMARY KEY DESC)" {} + 1.4 "CREATE TABLE t1(c1 text CONSTRAINT cons PRIMARY KEY DESC)" {} + + 2.1 "CREATE TABLE t1(c1 text NOT NULL)" {} + 2.2 "CREATE TABLE t1(c1 text CONSTRAINT nm NOT NULL)" {} + 2.3 "CREATE TABLE t1(c1 text NULL)" {} + 2.4 "CREATE TABLE t1(c1 text CONSTRAINT nm NULL)" {} + + 3.1 "CREATE TABLE t1(c1 text UNIQUE)" {} + 3.2 "CREATE TABLE t1(c1 text CONSTRAINT un UNIQUE)" {} + + 4.1 "CREATE TABLE t1(c1 text CHECK(c1!=0))" {} + 4.2 "CREATE TABLE t1(c1 text CONSTRAINT chk CHECK(c1!=0))" {} + + 5.1 "CREATE TABLE t1(c1 text DEFAULT 1)" {} + 5.2 "CREATE TABLE t1(c1 text DEFAULT -1)" {} + 5.3 "CREATE TABLE t1(c1 text DEFAULT +1)" {} + 5.4 "CREATE TABLE t1(c1 text DEFAULT -45.8e22)" {} + 5.5 "CREATE TABLE t1(c1 text DEFAULT (1+1))" {} + 5.6 "CREATE TABLE t1(c1 text CONSTRAINT \"1 2\" DEFAULT (1+1))" {} + + 6.1 "CREATE TABLE t1(c1 text COLLATE nocase)" {} + 6.2 "CREATE TABLE t1(c1 text CONSTRAINT 'a x' COLLATE nocase)" {} + + 7.1 "CREATE TABLE t1(c1 REFERENCES t2)" {} + 7.2 "CREATE TABLE t1(c1 CONSTRAINT abc REFERENCES t2)" {} + + 8.1 { + CREATE TABLE t1(c1 + PRIMARY KEY NOT NULL UNIQUE CHECK(c1 IS 'ten') DEFAULT 123 REFERENCES t1 + ); + } {} + 8.2 { + CREATE TABLE t1(c1 + REFERENCES t1 DEFAULT 123 CHECK(c1 IS 'ten') UNIQUE NOT NULL PRIMARY KEY + ); + } {} +} + +# -- syntax diagram table-constraint +# +do_createtable_tests 0.3.1 -repair { + drop_all_tables + execsql { CREATE TABLE t2(x PRIMARY KEY) } +} { + 1.1 "CREATE TABLE t1(c1, c2, PRIMARY KEY(c1))" {} + 1.2 "CREATE TABLE t1(c1, c2, PRIMARY KEY(c1, c2))" {} + 1.3 "CREATE TABLE t1(c1, c2, PRIMARY KEY(c1, c2) ON CONFLICT IGNORE)" {} + + 2.1 "CREATE TABLE t1(c1, c2, UNIQUE(c1))" {} + 2.2 "CREATE TABLE t1(c1, c2, UNIQUE(c1, c2))" {} + 2.3 "CREATE TABLE t1(c1, c2, UNIQUE(c1, c2) ON CONFLICT IGNORE)" {} + + 3.1 "CREATE TABLE t1(c1, c2, CHECK(c1 IS NOT c2))" {} + + 4.1 "CREATE TABLE t1(c1, c2, FOREIGN KEY(c1) REFERENCES t2)" {} +} + +# -- syntax diagram column-def +# +do_createtable_tests 0.4.1 -repair { + drop_all_tables +} { + 1 {CREATE TABLE t1( + col1, + col2 TEXT, + col3 INTEGER UNIQUE, + col4 VARCHAR(10, 10) PRIMARY KEY, + "name with spaces" REFERENCES t1 + ); + } {} +} + +# -- syntax diagram create-table-stmt +# +do_createtable_tests 0.5.1 -repair { + drop_all_tables + execsql { CREATE TABLE t2(a, b, c) } +} { + 1 "CREATE TABLE t1(a, b, c)" {} + 2 "CREATE TEMP TABLE t1(a, b, c)" {} + 3 "CREATE TEMPORARY TABLE t1(a, b, c)" {} + 4 "CREATE TABLE IF NOT EXISTS t1(a, b, c)" {} + 5 "CREATE TEMP TABLE IF NOT EXISTS t1(a, b, c)" {} + 6 "CREATE TEMPORARY TABLE IF NOT EXISTS t1(a, b, c)" {} + + 7 "CREATE TABLE main.t1(a, b, c)" {} + 8 "CREATE TEMP TABLE temp.t1(a, b, c)" {} + 9 "CREATE TEMPORARY TABLE temp.t1(a, b, c)" {} + 10 "CREATE TABLE IF NOT EXISTS main.t1(a, b, c)" {} + 11 "CREATE TEMP TABLE IF NOT EXISTS temp.t1(a, b, c)" {} + 12 "CREATE TEMPORARY TABLE IF NOT EXISTS temp.t1(a, b, c)" {} + + 13 "CREATE TABLE t1 AS SELECT * FROM t2" {} + 14 "CREATE TEMP TABLE t1 AS SELECT c, b, a FROM t2" {} + 15 "CREATE TABLE t1 AS SELECT count(*), max(b), min(a) FROM t2" {} +} + +# +# 1: Explicit parent-key columns. +# 2: Implicit child-key columns. +# +# 1: MATCH FULL +# 2: MATCH PARTIAL +# 3: MATCH SIMPLE +# 4: MATCH STICK +# 5: +# +# 1: ON DELETE SET NULL +# 2: ON DELETE SET DEFAULT +# 3: ON DELETE CASCADE +# 4: ON DELETE RESTRICT +# 5: ON DELETE NO ACTION +# 6: +# +# 1: ON UPDATE SET NULL +# 2: ON UPDATE SET DEFAULT +# 3: ON UPDATE CASCADE +# 4: ON UPDATE RESTRICT +# 5: ON UPDATE NO ACTION +# 6: +# +# 1: NOT DEFERRABLE INITIALLY DEFERRED +# 2: NOT DEFERRABLE INITIALLY IMMEDIATE +# 3: NOT DEFERRABLE +# 4: DEFERRABLE INITIALLY DEFERRED +# 5: DEFERRABLE INITIALLY IMMEDIATE +# 6: DEFERRABLE +# 7: +# +do_createtable_tests 0.6.1 -repair { + drop_all_tables + execsql { CREATE TABLE t2(x PRIMARY KEY, y) } + execsql { CREATE TABLE t3(i, j, UNIQUE(i, j) ) } +} { + 11146 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH FULL + ON DELETE SET NULL ON UPDATE RESTRICT DEFERRABLE + )} {} + 11412 { CREATE TABLE t1(a + REFERENCES t2(x) + ON DELETE RESTRICT ON UPDATE SET NULL MATCH FULL + NOT DEFERRABLE INITIALLY IMMEDIATE + )} {} + 12135 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH PARTIAL + ON DELETE SET NULL ON UPDATE CASCADE DEFERRABLE INITIALLY IMMEDIATE + )} {} + 12427 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH PARTIAL + ON DELETE RESTRICT ON UPDATE SET DEFAULT + )} {} + 12446 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH PARTIAL + ON DELETE RESTRICT ON UPDATE RESTRICT DEFERRABLE + )} {} + 12522 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH PARTIAL + ON DELETE NO ACTION ON UPDATE SET DEFAULT NOT DEFERRABLE INITIALLY IMMEDIATE + )} {} + 13133 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH SIMPLE + ON DELETE SET NULL ON UPDATE CASCADE NOT DEFERRABLE + )} {} + 13216 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH SIMPLE + ON DELETE SET DEFAULT ON UPDATE SET NULL DEFERRABLE + )} {} + 13263 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH SIMPLE + ON DELETE SET DEFAULT NOT DEFERRABLE + )} {} + 13421 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH SIMPLE + ON DELETE RESTRICT ON UPDATE SET DEFAULT NOT DEFERRABLE INITIALLY DEFERRED + )} {} + 13432 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH SIMPLE + ON DELETE RESTRICT ON UPDATE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE + )} {} + 13523 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH SIMPLE + ON DELETE NO ACTION ON UPDATE SET DEFAULT NOT DEFERRABLE + )} {} + 14336 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH STICK + ON DELETE CASCADE ON UPDATE CASCADE DEFERRABLE + )} {} + 14611 { CREATE TABLE t1(a + REFERENCES t2(x) MATCH STICK + ON UPDATE SET NULL NOT DEFERRABLE INITIALLY DEFERRED + )} {} + 15155 { CREATE TABLE t1(a + REFERENCES t2(x) + ON DELETE SET NULL ON UPDATE NO ACTION DEFERRABLE INITIALLY IMMEDIATE + )} {} + 15453 { CREATE TABLE t1(a + REFERENCES t2(x) ON DELETE RESTRICT ON UPDATE NO ACTION NOT DEFERRABLE + )} {} + 15661 { CREATE TABLE t1(a + REFERENCES t2(x) NOT DEFERRABLE INITIALLY DEFERRED + )} {} + 21115 { CREATE TABLE t1(a + REFERENCES t2 MATCH FULL + ON DELETE SET NULL ON UPDATE SET NULL DEFERRABLE INITIALLY IMMEDIATE + )} {} + 21123 { CREATE TABLE t1(a + REFERENCES t2 MATCH FULL + ON DELETE SET NULL ON UPDATE SET DEFAULT NOT DEFERRABLE + )} {} + 21217 { CREATE TABLE t1(a + REFERENCES t2 MATCH FULL ON DELETE SET DEFAULT ON UPDATE SET NULL + )} {} + 21362 { CREATE TABLE t1(a + REFERENCES t2 MATCH FULL + ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE + )} {} + 22143 { CREATE TABLE t1(a + REFERENCES t2 MATCH PARTIAL + ON DELETE SET NULL ON UPDATE RESTRICT NOT DEFERRABLE + )} {} + 22156 { CREATE TABLE t1(a + REFERENCES t2 MATCH PARTIAL + ON DELETE SET NULL ON UPDATE NO ACTION DEFERRABLE + )} {} + 22327 { CREATE TABLE t1(a + REFERENCES t2 MATCH PARTIAL ON DELETE CASCADE ON UPDATE SET DEFAULT + )} {} + 22663 { CREATE TABLE t1(a + REFERENCES t2 MATCH PARTIAL NOT DEFERRABLE + )} {} + 23236 { CREATE TABLE t1(a + REFERENCES t2 MATCH SIMPLE + ON DELETE SET DEFAULT ON UPDATE CASCADE DEFERRABLE + )} {} + 24155 { CREATE TABLE t1(a + REFERENCES t2 MATCH STICK + ON DELETE SET NULL ON UPDATE NO ACTION DEFERRABLE INITIALLY IMMEDIATE + )} {} + 24522 { CREATE TABLE t1(a + REFERENCES t2 MATCH STICK + ON DELETE NO ACTION ON UPDATE SET DEFAULT NOT DEFERRABLE INITIALLY IMMEDIATE + )} {} + 24625 { CREATE TABLE t1(a + REFERENCES t2 MATCH STICK + ON UPDATE SET DEFAULT DEFERRABLE INITIALLY IMMEDIATE + )} {} + 25454 { CREATE TABLE t1(a + REFERENCES t2 + ON DELETE RESTRICT ON UPDATE NO ACTION DEFERRABLE INITIALLY DEFERRED + )} {} +} + +#------------------------------------------------------------------------- +# Test cases e_createtable-1.* - test statements related to table and +# database names, the TEMP and TEMPORARY keywords, and the IF NOT EXISTS +# clause. +# +drop_all_tables +forcedelete test.db2 test.db3 + +do_execsql_test e_createtable-1.0 { + ATTACH 'test.db2' AS auxa; + ATTACH 'test.db3' AS auxb; +} {} + +# EVIDENCE-OF: R-17899-04554 Table names that begin with "sqlite_" are +# reserved for internal use. It is an error to attempt to create a table +# with a name that starts with "sqlite_". +# +do_createtable_tests 1.1.1 -error { + object name reserved for internal use: %s +} { + 1 "CREATE TABLE sqlite_abc(a, b, c)" sqlite_abc + 2 "CREATE TABLE temp.sqlite_helloworld(x)" sqlite_helloworld + 3 {CREATE TABLE auxa."sqlite__"(x, y)} sqlite__ + 4 {CREATE TABLE auxb."sqlite_"(z)} sqlite_ + 5 {CREATE TABLE "SQLITE_TBL"(z)} SQLITE_TBL +} +do_createtable_tests 1.1.2 { + 1 "CREATE TABLE sqlit_abc(a, b, c)" {} + 2 "CREATE TABLE temp.sqlitehelloworld(x)" {} + 3 {CREATE TABLE auxa."sqlite"(x, y)} {} + 4 {CREATE TABLE auxb."sqlite-"(z)} {} + 5 {CREATE TABLE "SQLITE-TBL"(z)} {} +} + + +# EVIDENCE-OF: R-10195-31023 If a is specified, it +# must be either "main", "temp", or the name of an attached database. +# +# EVIDENCE-OF: R-39822-07822 In this case the new table is created in +# the named database. +# +# Test cases 1.2.* test the first of the two requirements above. The +# second is verified by cases 1.3.*. +# +do_createtable_tests 1.2.1 -error { + unknown database %s +} { + 1 "CREATE TABLE george.t1(a, b)" george + 2 "CREATE TABLE _.t1(a, b)" _ +} +do_createtable_tests 1.2.2 { + 1 "CREATE TABLE main.abc(a, b, c)" {} + 2 "CREATE TABLE temp.helloworld(x)" {} + 3 {CREATE TABLE auxa."t 1"(x, y)} {} + 4 {CREATE TABLE auxb.xyz(z)} {} +} +drop_all_tables +do_createtable_tests 1.3 -tclquery { + unset -nocomplain X + array set X [table_list] + list $X(main) $X(temp) $X(auxa) $X(auxb) +} { + 1 "CREATE TABLE main.abc(a, b, c)" {abc {} {} {}} + 2 "CREATE TABLE main.t1(a, b, c)" {{abc t1} {} {} {}} + 3 "CREATE TABLE temp.tmp(a, b, c)" {{abc t1} tmp {} {}} + 4 "CREATE TABLE auxb.tbl(x, y)" {{abc t1} tmp {} tbl} + 5 "CREATE TABLE auxb.t1(k, v)" {{abc t1} tmp {} {t1 tbl}} + 6 "CREATE TABLE auxa.next(c, d)" {{abc t1} tmp next {t1 tbl}} +} + +# EVIDENCE-OF: R-18895-27365 If the "TEMP" or "TEMPORARY" keyword occurs +# between the "CREATE" and "TABLE" then the new table is created in the +# temp database. +# +drop_all_tables +do_createtable_tests 1.4 -tclquery { + unset -nocomplain X + array set X [table_list] + list $X(main) $X(temp) $X(auxa) $X(auxb) +} { + 1 "CREATE TEMP TABLE t1(a, b)" {{} t1 {} {}} + 2 "CREATE TEMPORARY TABLE t2(a, b)" {{} {t1 t2} {} {}} +} + +# EVIDENCE-OF: R-49439-47561 It is an error to specify both a +# and the TEMP or TEMPORARY keyword, unless the +# is "temp". +# +drop_all_tables +do_createtable_tests 1.5.1 -error { + temporary table name must be unqualified +} { + 1 "CREATE TEMP TABLE main.t1(a, b)" {} + 2 "CREATE TEMPORARY TABLE auxa.t2(a, b)" {} + 3 "CREATE TEMP TABLE auxb.t3(a, b)" {} + 4 "CREATE TEMPORARY TABLE main.xxx(x)" {} +} +drop_all_tables +do_createtable_tests 1.5.2 -tclquery { + unset -nocomplain X + array set X [table_list] + list $X(main) $X(temp) $X(auxa) $X(auxb) +} { + 1 "CREATE TEMP TABLE temp.t1(a, b)" {{} t1 {} {}} + 2 "CREATE TEMPORARY TABLE temp.t2(a, b)" {{} {t1 t2} {} {}} + 3 "CREATE TEMP TABLE TEMP.t3(a, b)" {{} {t1 t2 t3} {} {}} + 4 "CREATE TEMPORARY TABLE TEMP.xxx(x)" {{} {t1 t2 t3 xxx} {} {}} +} + +# EVIDENCE-OF: R-00917-09393 If no database name is specified and the +# TEMP keyword is not present then the table is created in the main +# database. +# +drop_all_tables +do_createtable_tests 1.6 -tclquery { + unset -nocomplain X + array set X [table_list] + list $X(main) $X(temp) $X(auxa) $X(auxb) +} { + 1 "CREATE TABLE t1(a, b)" {t1 {} {} {}} + 2 "CREATE TABLE t2(a, b)" {{t1 t2} {} {} {}} + 3 "CREATE TABLE t3(a, b)" {{t1 t2 t3} {} {} {}} + 4 "CREATE TABLE xxx(x)" {{t1 t2 t3 xxx} {} {} {}} +} + +drop_all_tables +do_execsql_test e_createtable-1.7.0 { + CREATE TABLE t1(x, y); + CREATE INDEX i1 ON t1(x); + CREATE VIEW v1 AS SELECT * FROM t1; + + CREATE TABLE auxa.tbl1(x, y); + CREATE INDEX auxa.idx1 ON tbl1(x); + CREATE VIEW auxa.view1 AS SELECT * FROM tbl1; +} {} + +# EVIDENCE-OF: R-01232-54838 It is usually an error to attempt to create +# a new table in a database that already contains a table, index or view +# of the same name. +# +# Test cases 1.7.1.* verify that creating a table in a database with a +# table/index/view of the same name does fail. 1.7.2.* tests that creating +# a table with the same name as a table/index/view in a different database +# is Ok. +# +do_createtable_tests 1.7.1 -error { %s } { + 1 "CREATE TABLE t1(a, b)" {{table t1 already exists}} + 2 "CREATE TABLE i1(a, b)" {{there is already an index named i1}} + 3 "CREATE TABLE v1(a, b)" {{table v1 already exists}} + 4 "CREATE TABLE auxa.tbl1(a, b)" {{table tbl1 already exists}} + 5 "CREATE TABLE auxa.idx1(a, b)" {{there is already an index named idx1}} + 6 "CREATE TABLE auxa.view1(a, b)" {{table view1 already exists}} +} +do_createtable_tests 1.7.2 { + 1 "CREATE TABLE auxa.t1(a, b)" {} + 2 "CREATE TABLE auxa.i1(a, b)" {} + 3 "CREATE TABLE auxa.v1(a, b)" {} + 4 "CREATE TABLE tbl1(a, b)" {} + 5 "CREATE TABLE idx1(a, b)" {} + 6 "CREATE TABLE view1(a, b)" {} +} + +# EVIDENCE-OF: R-33917-24086 However, if the "IF NOT EXISTS" clause is +# specified as part of the CREATE TABLE statement and a table or view of +# the same name already exists, the CREATE TABLE command simply has no +# effect (and no error message is returned). +# +drop_all_tables +do_execsql_test e_createtable-1.8.0 { + CREATE TABLE t1(x, y); + CREATE INDEX i1 ON t1(x); + CREATE VIEW v1 AS SELECT * FROM t1; + CREATE TABLE auxa.tbl1(x, y); + CREATE INDEX auxa.idx1 ON tbl1(x); + CREATE VIEW auxa.view1 AS SELECT * FROM tbl1; +} {} +do_createtable_tests 1.8 { + 1 "CREATE TABLE IF NOT EXISTS t1(a, b)" {} + 2 "CREATE TABLE IF NOT EXISTS auxa.tbl1(a, b)" {} + 3 "CREATE TABLE IF NOT EXISTS v1(a, b)" {} + 4 "CREATE TABLE IF NOT EXISTS auxa.view1(a, b)" {} +} + +# EVIDENCE-OF: R-16465-40078 An error is still returned if the table +# cannot be created because of an existing index, even if the "IF NOT +# EXISTS" clause is specified. +# +do_createtable_tests 1.9 -error { %s } { + 1 "CREATE TABLE IF NOT EXISTS i1(a, b)" + {{there is already an index named i1}} + 2 "CREATE TABLE IF NOT EXISTS auxa.idx1(a, b)" + {{there is already an index named idx1}} +} + +# EVIDENCE-OF: R-05513-33819 It is not an error to create a table that +# has the same name as an existing trigger. +# +drop_all_tables +do_execsql_test e_createtable-1.10.0 { + CREATE TABLE t1(x, y); + CREATE TABLE auxb.t2(x, y); + + CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN + SELECT 1; + END; + CREATE TRIGGER auxb.tr2 AFTER INSERT ON t2 BEGIN + SELECT 1; + END; +} {} +do_createtable_tests 1.10 { + 1 "CREATE TABLE tr1(a, b)" {} + 2 "CREATE TABLE tr2(a, b)" {} + 3 "CREATE TABLE auxb.tr1(a, b)" {} + 4 "CREATE TABLE auxb.tr2(a, b)" {} +} + +# EVIDENCE-OF: R-22283-14179 Tables are removed using the DROP TABLE +# statement. +# +drop_all_tables +do_execsql_test e_createtable-1.11.0 { + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + CREATE TABLE auxa.t3(a, b); + CREATE TABLE auxa.t4(a, b); +} {} + +do_execsql_test e_createtable-1.11.1.1 { + SELECT * FROM t1; + SELECT * FROM t2; + SELECT * FROM t3; + SELECT * FROM t4; +} {} +do_execsql_test e_createtable-1.11.1.2 { DROP TABLE t1 } {} +do_catchsql_test e_createtable-1.11.1.3 { + SELECT * FROM t1 +} {1 {no such table: t1}} +do_execsql_test e_createtable-1.11.1.4 { DROP TABLE t3 } {} +do_catchsql_test e_createtable-1.11.1.5 { + SELECT * FROM t3 +} {1 {no such table: t3}} + +do_execsql_test e_createtable-1.11.2.1 { + SELECT name FROM sqlite_master; + SELECT name FROM auxa.sqlite_master; +} {t2 t4} +do_execsql_test e_createtable-1.11.2.2 { DROP TABLE t2 } {} +do_execsql_test e_createtable-1.11.2.3 { DROP TABLE t4 } {} +do_execsql_test e_createtable-1.11.2.4 { + SELECT name FROM sqlite_master; + SELECT name FROM auxa.sqlite_master; +} {} + +#------------------------------------------------------------------------- +# Test cases e_createtable-2.* - test statements related to the CREATE +# TABLE AS ... SELECT statement. +# + +# Three Tcl commands: +# +# select_column_names SQL +# The argument must be a SELECT statement. Return a list of the names +# of the columns of the result-set that would be returned by executing +# the SELECT. +# +# table_column_names TBL +# The argument must be a table name. Return a list of column names, from +# left to right, for the table. +# +# table_column_decltypes TBL +# The argument must be a table name. Return a list of column declared +# types, from left to right, for the table. +# +proc sci {select cmd} { + set res [list] + set STMT [sqlite3_prepare_v2 db $select -1 dummy] + for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} { + lappend res [$cmd $STMT $i] + } + sqlite3_finalize $STMT + set res +} +proc tci {tbl cmd} { sci "SELECT * FROM $tbl" $cmd } +proc select_column_names {sql} { sci $sql sqlite3_column_name } +proc table_column_names {tbl} { tci $tbl sqlite3_column_name } +proc table_column_decltypes {tbl} { tci $tbl sqlite3_column_decltype } + +# Create a database schema. This schema is used by tests 2.1.* through 2.3.*. +# +drop_all_tables +do_execsql_test e_createtable-2.0 { + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(d, e, f); + CREATE TABLE t3(g BIGINT, h VARCHAR(10)); + CREATE TABLE t4(i BLOB, j ANYOLDATA); + CREATE TABLE t5(k FLOAT, l INTEGER); + CREATE TABLE t6(m DEFAULT 10, n DEFAULT 5, PRIMARY KEY(m, n)); + CREATE TABLE t7(x INTEGER PRIMARY KEY); + CREATE TABLE t8(o COLLATE nocase DEFAULT 'abc'); + CREATE TABLE t9(p NOT NULL, q DOUBLE CHECK (q!=0), r STRING UNIQUE); +} {} + +# EVIDENCE-OF: R-64828-59568 The table has the same number of columns as +# the rows returned by the SELECT statement. The name of each column is +# the same as the name of the corresponding column in the result set of +# the SELECT statement. +# +do_createtable_tests 2.1 -tclquery { + table_column_names x1 +} -repair { + catchsql { DROP TABLE x1 } +} { + 1 "CREATE TABLE x1 AS SELECT * FROM t1" {a b c} + 2 "CREATE TABLE x1 AS SELECT c, b, a FROM t1" {c b a} + 3 "CREATE TABLE x1 AS SELECT * FROM t1, t2" {a b c d e f} + 4 "CREATE TABLE x1 AS SELECT count(*) FROM t1" {count(*)} + 5 "CREATE TABLE x1 AS SELECT count(a) AS a, max(b) FROM t1" {a max(b)} +} + +# EVIDENCE-OF: R-37111-22855 The declared type of each column is +# determined by the expression affinity of the corresponding expression +# in the result set of the SELECT statement, as follows: Expression +# Affinity Column Declared Type TEXT "TEXT" NUMERIC "NUM" INTEGER "INT" +# REAL "REAL" NONE "" (empty string) +# +do_createtable_tests 2.2 -tclquery { + table_column_decltypes x1 +} -repair { + catchsql { DROP TABLE x1 } +} { + 1 "CREATE TABLE x1 AS SELECT a FROM t1" {""} + 2 "CREATE TABLE x1 AS SELECT * FROM t3" {INT TEXT} + 3 "CREATE TABLE x1 AS SELECT * FROM t4" {"" NUM} + 4 "CREATE TABLE x1 AS SELECT * FROM t5" {REAL INT} +} + +# EVIDENCE-OF: R-16667-09772 A table created using CREATE TABLE AS has +# no PRIMARY KEY and no constraints of any kind. The default value of +# each column is NULL. The default collation sequence for each column of +# the new table is BINARY. +# +# The following tests create tables based on SELECT statements that read +# from tables that have primary keys, constraints and explicit default +# collation sequences. None of this is transfered to the definition of +# the new table as stored in the sqlite_master table. +# +# Tests 2.3.2.* show that the default value of each column is NULL. +# +do_createtable_tests 2.3.1 -query { + SELECT sql FROM sqlite_master ORDER BY rowid DESC LIMIT 1 +} { + 1 "CREATE TABLE x1 AS SELECT * FROM t6" {{CREATE TABLE x1(m,n)}} + 2 "CREATE TABLE x2 AS SELECT * FROM t7" {{CREATE TABLE x2(x INT)}} + 3 "CREATE TABLE x3 AS SELECT * FROM t8" {{CREATE TABLE x3(o)}} + 4 "CREATE TABLE x4 AS SELECT * FROM t9" {{CREATE TABLE x4(p,q REAL,r NUM)}} +} +do_execsql_test e_createtable-2.3.2.1 { + INSERT INTO x1 DEFAULT VALUES; + INSERT INTO x2 DEFAULT VALUES; + INSERT INTO x3 DEFAULT VALUES; + INSERT INTO x4 DEFAULT VALUES; +} {} +db nullvalue null +do_execsql_test e_createtable-2.3.2.2 { SELECT * FROM x1 } {null null} +do_execsql_test e_createtable-2.3.2.3 { SELECT * FROM x2 } {null} +do_execsql_test e_createtable-2.3.2.4 { SELECT * FROM x3 } {null} +do_execsql_test e_createtable-2.3.2.5 { SELECT * FROM x4 } {null null null} +db nullvalue {} + +drop_all_tables +do_execsql_test e_createtable-2.4.0 { + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES('i', 'one'); + INSERT INTO t1 VALUES('ii', 'two'); + INSERT INTO t1 VALUES('iii', 'three'); +} {} + +# EVIDENCE-OF: R-24153-28352 Tables created using CREATE TABLE AS are +# initially populated with the rows of data returned by the SELECT +# statement. +# +# EVIDENCE-OF: R-08224-30249 Rows are assigned contiguously ascending +# rowid values, starting with 1, in the order that they are returned by +# the SELECT statement. +# +# Each test case below is specified as the name of a table to create +# using "CREATE TABLE ... AS SELECT ..." and a SELECT statement to use in +# creating it. The table is created. +# +# Test cases 2.4.*.1 check that after it has been created, the data in the +# table is the same as the data returned by the SELECT statement executed as +# a standalone command, verifying the first testable statement above. +# +# Test cases 2.4.*.2 check that the rowids were allocated contiguously +# as required by the second testable statement above. That the rowids +# from the contiguous block were allocated to rows in the order rows are +# returned by the SELECT statement is verified by 2.4.*.1. +# +# EVIDENCE-OF: R-32365-09043 A "CREATE TABLE ... AS SELECT" statement +# creates and populates a database table based on the results of a +# SELECT statement. +# +# The above is also considered to be tested by the following. It is +# clear that tables are being created and populated by the command in +# question. +# +foreach {tn tbl select} { + 1 x1 "SELECT * FROM t1" + 2 x2 "SELECT * FROM t1 ORDER BY x DESC" + 3 x3 "SELECT * FROM t1 ORDER BY x ASC" +} { + # Create the table using a "CREATE TABLE ... AS SELECT ..." command. + execsql [subst {CREATE TABLE $tbl AS $select}] + + # Check that the rows inserted into the table, sorted in ascending rowid + # order, match those returned by executing the SELECT statement as a + # standalone command. + do_execsql_test e_createtable-2.4.$tn.1 [subst { + SELECT * FROM $tbl ORDER BY rowid; + }] [execsql $select] + + # Check that the rowids in the new table are a contiguous block starting + # with rowid 1. Note that this will fail if SELECT statement $select + # returns 0 rows (as max(rowid) will be NULL). + do_execsql_test e_createtable-2.4.$tn.2 [subst { + SELECT min(rowid), count(rowid)==max(rowid) FROM $tbl + }] {1 1} +} + +#-------------------------------------------------------------------------- +# Test cases for column defintions in CREATE TABLE statements that do not +# use a SELECT statement. Not including data constraints. In other words, +# tests for the specification of: +# +# * declared types, +# * default values, and +# * default collation sequences. +# + +# EVIDENCE-OF: R-27219-49057 Unlike most SQL databases, SQLite does not +# restrict the type of data that may be inserted into a column based on +# the columns declared type. +# +# Test this by creating a few tables with varied declared types, then +# inserting various different types of values into them. +# +drop_all_tables +do_execsql_test e_createtable-3.1.0 { + CREATE TABLE t1(x VARCHAR(10), y INTEGER, z DOUBLE); + CREATE TABLE t2(a DATETIME, b STRING, c REAL); + CREATE TABLE t3(o, t); +} {} + +# value type -> declared column type +# ---------------------------------- +# integer -> VARCHAR(10) +# string -> INTEGER +# blob -> DOUBLE +# +do_execsql_test e_createtable-3.1.1 { + INSERT INTO t1 VALUES(14, 'quite a lengthy string', X'555655'); + SELECT * FROM t1; +} {14 {quite a lengthy string} UVU} + +# string -> DATETIME +# integer -> STRING +# time -> REAL +# +do_execsql_test e_createtable-3.1.2 { + INSERT INTO t2 VALUES('not a datetime', 13, '12:41:59'); + SELECT * FROM t2; +} {{not a datetime} 13 12:41:59} + +# EVIDENCE-OF: R-10565-09557 The declared type of a column is used to +# determine the affinity of the column only. +# +# Affinities are tested in more detail elsewhere (see document +# datatype3.html). Here, just test that affinity transformations +# consistent with the expected affinity of each column (based on +# the declared type) appear to take place. +# +# Affinities of t1 (test cases 3.2.1.*): TEXT, INTEGER, REAL +# Affinities of t2 (test cases 3.2.2.*): NUMERIC, NUMERIC, REAL +# Affinities of t3 (test cases 3.2.3.*): NONE, NONE +# +do_execsql_test e_createtable-3.2.0 { DELETE FROM t1; DELETE FROM t2; } {} + +do_createtable_tests 3.2.1 -query { + SELECT quote(x), quote(y), quote(z) FROM t1 ORDER BY rowid DESC LIMIT 1; +} { + 1 "INSERT INTO t1 VALUES(15, '22.0', '14')" {'15' 22 14.0} + 2 "INSERT INTO t1 VALUES(22.0, 22.0, 22.0)" {'22.0' 22 22.0} +} +do_createtable_tests 3.2.2 -query { + SELECT quote(a), quote(b), quote(c) FROM t2 ORDER BY rowid DESC LIMIT 1; +} { + 1 "INSERT INTO t2 VALUES(15, '22.0', '14')" {15 22 14.0} + 2 "INSERT INTO t2 VALUES(22.0, 22.0, 22.0)" {22 22 22.0} +} +do_createtable_tests 3.2.3 -query { + SELECT quote(o), quote(t) FROM t3 ORDER BY rowid DESC LIMIT 1; +} { + 1 "INSERT INTO t3 VALUES('15', '22.0')" {'15' '22.0'} + 2 "INSERT INTO t3 VALUES(15, 22.0)" {15 22.0} +} + +# EVIDENCE-OF: R-42316-09582 If there is no explicit DEFAULT clause +# attached to a column definition, then the default value of the column +# is NULL. +# +# None of the columns in table t1 have an explicit DEFAULT clause. +# So testing that the default value of all columns in table t1 is +# NULL serves to verify the above. +# +do_createtable_tests 3.2.3 -query { + SELECT quote(x), quote(y), quote(z) FROM t1 +} -repair { + execsql { DELETE FROM t1 } +} { + 1 "INSERT INTO t1(x, y) VALUES('abc', 'xyz')" {'abc' 'xyz' NULL} + 2 "INSERT INTO t1(x, z) VALUES('abc', 'xyz')" {'abc' NULL 'xyz'} + 3 "INSERT INTO t1 DEFAULT VALUES" {NULL NULL NULL} +} + +# EVIDENCE-OF: R-62940-43005 An explicit DEFAULT clause may specify that +# the default value is NULL, a string constant, a blob constant, a +# signed-number, or any constant expression enclosed in parentheses. An +# explicit default value may also be one of the special case-independent +# keywords CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP. +# +do_execsql_test e_createtable-3.3.1 { + CREATE TABLE t4( + a DEFAULT NULL, + b DEFAULT 'string constant', + c DEFAULT X'424C4F42', + d DEFAULT 1, + e DEFAULT -1, + f DEFAULT 3.14, + g DEFAULT -3.14, + h DEFAULT ( substr('abcd', 0, 2) || 'cd' ), + i DEFAULT CURRENT_TIME, + j DEFAULT CURRENT_DATE, + k DEFAULT CURRENT_TIMESTAMP + ); +} {} + +# EVIDENCE-OF: R-10288-43169 For the purposes of the DEFAULT clause, an +# expression is considered constant provided that it does not contain +# any sub-queries or string constants enclosed in double quotes. +# +do_createtable_tests 3.4.1 -error { + default value of column [x] is not constant +} { + 1 {CREATE TABLE t5(x DEFAULT ( (SELECT 1) ))} {} + 2 {CREATE TABLE t5(x DEFAULT ( "abc" ))} {} + 3 {CREATE TABLE t5(x DEFAULT ( 1 IN (SELECT 1) ))} {} + 4 {CREATE TABLE t5(x DEFAULT ( EXISTS (SELECT 1) ))} {} +} +do_createtable_tests 3.4.2 -repair { + catchsql { DROP TABLE t5 } +} { + 1 {CREATE TABLE t5(x DEFAULT ( 'abc' ))} {} + 2 {CREATE TABLE t5(x DEFAULT ( 1 IN (1, 2, 3) ))} {} +} + +# EVIDENCE-OF: R-18814-23501 Each time a row is inserted into the table +# by an INSERT statement that does not provide explicit values for all +# table columns the values stored in the new row are determined by their +# default values +# +# Verify this with some assert statements for which all, some and no +# columns lack explicit values. +# +set sqlite_current_time 1000000000 +do_createtable_tests 3.5 -query { + SELECT quote(a), quote(b), quote(c), quote(d), quote(e), quote(f), + quote(g), quote(h), quote(i), quote(j), quote(k) + FROM t4 ORDER BY rowid DESC LIMIT 1; +} { + 1 "INSERT INTO t4 DEFAULT VALUES" { + NULL {'string constant'} X'424C4F42' 1 -1 3.14 -3.14 + 'acd' '01:46:40' '2001-09-09' {'2001-09-09 01:46:40'} + } + + 2 "INSERT INTO t4(a, b, c) VALUES(1, 2, 3)" { + 1 2 3 1 -1 3.14 -3.14 'acd' '01:46:40' '2001-09-09' {'2001-09-09 01:46:40'} + } + + 3 "INSERT INTO t4(k, j, i) VALUES(1, 2, 3)" { + NULL {'string constant'} X'424C4F42' 1 -1 3.14 -3.14 'acd' 3 2 1 + } + + 4 "INSERT INTO t4(a,b,c,d,e,f,g,h,i,j,k) VALUES(1,2,3,4,5,6,7,8,9,10,11)" { + 1 2 3 4 5 6 7 8 9 10 11 + } +} + +# EVIDENCE-OF: R-12572-62501 If the default value of the column is a +# constant NULL, text, blob or signed-number value, then that value is +# used directly in the new row. +# +do_execsql_test e_createtable-3.6.1 { + CREATE TABLE t5( + a DEFAULT NULL, + b DEFAULT 'text value', + c DEFAULT X'424C4F42', + d DEFAULT -45678.6, + e DEFAULT 394507 + ); +} {} +do_execsql_test e_createtable-3.6.2 { + INSERT INTO t5 DEFAULT VALUES; + SELECT quote(a), quote(b), quote(c), quote(d), quote(e) FROM t5; +} {NULL {'text value'} X'424C4F42' -45678.6 394507} + +# EVIDENCE-OF: R-60616-50251 If the default value of a column is an +# expression in parentheses, then the expression is evaluated once for +# each row inserted and the results used in the new row. +# +# Test case 3.6.4 demonstrates that the expression is evaluated +# separately for each row if the INSERT is an "INSERT INTO ... SELECT ..." +# command. +# +set ::nextint 0 +proc nextint {} { incr ::nextint } +db func nextint nextint + +do_execsql_test e_createtable-3.7.1 { + CREATE TABLE t6(a DEFAULT ( nextint() ), b DEFAULT ( nextint() )); +} {} +do_execsql_test e_createtable-3.7.2 { + INSERT INTO t6 DEFAULT VALUES; + SELECT quote(a), quote(b) FROM t6; +} {1 2} +do_execsql_test e_createtable-3.7.3 { + INSERT INTO t6(a) VALUES('X'); + SELECT quote(a), quote(b) FROM t6; +} {1 2 'X' 3} +do_execsql_test e_createtable-3.7.4 { + INSERT INTO t6(a) SELECT a FROM t6; + SELECT quote(a), quote(b) FROM t6; +} {1 2 'X' 3 1 4 'X' 5} + +# EVIDENCE-OF: R-15363-55230 If the default value of a column is +# CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP, then the value used +# in the new row is a text representation of the current UTC date and/or +# time. +# +# This is difficult to test literally without knowing what time the +# user will run the tests. Instead, we test that the three cases +# above set the value to the current date and/or time according to +# the xCurrentTime() method of the VFS. Which is usually the same +# as UTC. In this case, however, we instrument it to always return +# a time equivalent to "2001-09-09 01:46:40 UTC". +# +set sqlite_current_time 1000000000 +do_execsql_test e_createtable-3.8.1 { + CREATE TABLE t7( + a DEFAULT CURRENT_TIME, + b DEFAULT CURRENT_DATE, + c DEFAULT CURRENT_TIMESTAMP + ); +} {} +do_execsql_test e_createtable-3.8.2 { + INSERT INTO t7 DEFAULT VALUES; + SELECT quote(a), quote(b), quote(c) FROM t7; +} {'01:46:40' '2001-09-09' {'2001-09-09 01:46:40'}} + + +# EVIDENCE-OF: R-62327-53843 For CURRENT_TIME, the format of the value +# is "HH:MM:SS". +# +# EVIDENCE-OF: R-03775-43471 For CURRENT_DATE, "YYYY-MM-DD". +# +# EVIDENCE-OF: R-07677-44926 The format for CURRENT_TIMESTAMP is +# "YYYY-MM-DD HH:MM:SS". +# +# The three above are demonstrated by tests 1, 2 and 3 below. +# Respectively. +# +do_createtable_tests 3.8.3 -query { + SELECT a, b, c FROM t7 ORDER BY rowid DESC LIMIT 1; +} { + 1 "INSERT INTO t7(b, c) VALUES('x', 'y')" {01:46:40 x y} + 2 "INSERT INTO t7(c, a) VALUES('x', 'y')" {y 2001-09-09 x} + 3 "INSERT INTO t7(a, b) VALUES('x', 'y')" {x y {2001-09-09 01:46:40}} +} + +# EVIDENCE-OF: R-55061-47754 The COLLATE clause specifies the name of a +# collating sequence to use as the default collation sequence for the +# column. +# +# EVIDENCE-OF: R-40275-54363 If no COLLATE clause is specified, the +# default collation sequence is BINARY. +# +do_execsql_test e_createtable-3-9.1 { + CREATE TABLE t8(a COLLATE nocase, b COLLATE rtrim, c COLLATE binary, d); + INSERT INTO t8 VALUES('abc', 'abc', 'abc', 'abc'); + INSERT INTO t8 VALUES('abc ', 'abc ', 'abc ', 'abc '); + INSERT INTO t8 VALUES('ABC ', 'ABC ', 'ABC ', 'ABC '); + INSERT INTO t8 VALUES('ABC', 'ABC', 'ABC', 'ABC'); +} {} +do_createtable_tests 3.9 { + 2 "SELECT a FROM t8 ORDER BY a, rowid" {abc ABC {abc } {ABC }} + 3 "SELECT b FROM t8 ORDER BY b, rowid" {{ABC } ABC abc {abc }} + 4 "SELECT c FROM t8 ORDER BY c, rowid" {ABC {ABC } abc {abc }} + 5 "SELECT d FROM t8 ORDER BY d, rowid" {ABC {ABC } abc {abc }} +} + +# EVIDENCE-OF: R-25473-20557 The number of columns in a table is limited +# by the SQLITE_MAX_COLUMN compile-time parameter. +# +proc columns {n} { + set res [list] + for {set i 0} {$i < $n} {incr i} { lappend res "c$i" } + join $res ", " +} +do_execsql_test e_createtable-3.10.1 [subst { + CREATE TABLE t9([columns $::SQLITE_MAX_COLUMN]); +}] {} +do_catchsql_test e_createtable-3.10.2 [subst { + CREATE TABLE t10([columns [expr $::SQLITE_MAX_COLUMN+1]]); +}] {1 {too many columns on t10}} + +# EVIDENCE-OF: R-27775-64721 Both of these limits can be lowered at +# runtime using the sqlite3_limit() C/C++ interface. +# +# A 30,000 byte blob consumes 30,003 bytes of record space. A record +# that contains 3 such blobs consumes (30,000*3)+1 bytes of space. Tests +# 3.11.4 and 3.11.5, which verify that SQLITE_MAX_LENGTH may be lowered +# at runtime, are based on this calculation. +# +sqlite3_limit db SQLITE_LIMIT_COLUMN 500 +do_execsql_test e_createtable-3.11.1 [subst { + CREATE TABLE t10([columns 500]); +}] {} +do_catchsql_test e_createtable-3.11.2 [subst { + CREATE TABLE t11([columns 501]); +}] {1 {too many columns on t11}} + +# Check that it is not possible to raise the column limit above its +# default compile time value. +# +sqlite3_limit db SQLITE_LIMIT_COLUMN [expr $::SQLITE_MAX_COLUMN+2] +do_catchsql_test e_createtable-3.11.3 [subst { + CREATE TABLE t11([columns [expr $::SQLITE_MAX_COLUMN+1]]); +}] {1 {too many columns on t11}} + +sqlite3_limit db SQLITE_LIMIT_LENGTH 90010 +do_execsql_test e_createtable-3.11.4 { + CREATE TABLE t12(a, b, c); + INSERT INTO t12 VALUES(randomblob(30000),randomblob(30000),randomblob(30000)); +} {} +do_catchsql_test e_createtable-3.11.5 { + INSERT INTO t12 VALUES(randomblob(30001),randomblob(30000),randomblob(30000)); +} {1 {string or blob too big}} + +#------------------------------------------------------------------------- +# Tests for statements regarding constraints (PRIMARY KEY, UNIQUE, NOT +# NULL and CHECK constraints). +# + +# EVIDENCE-OF: R-52382-54248 Each table in SQLite may have at most one +# PRIMARY KEY. +# +# EVIDENCE-OF: R-18080-47271 If there is more than one PRIMARY KEY +# clause in a single CREATE TABLE statement, it is an error. +# +# To test the two above, show that zero primary keys is Ok, one primary +# key is Ok, and two or more primary keys is an error. +# +drop_all_tables +do_createtable_tests 4.1.1 { + 1 "CREATE TABLE t1(a, b, c)" {} + 2 "CREATE TABLE t2(a PRIMARY KEY, b, c)" {} + 3 "CREATE TABLE t3(a, b, c, PRIMARY KEY(a))" {} + 4 "CREATE TABLE t4(a, b, c, PRIMARY KEY(c,b,a))" {} +} +do_createtable_tests 4.1.2 -error { + table "t5" has more than one primary key +} { + 1 "CREATE TABLE t5(a PRIMARY KEY, b PRIMARY KEY, c)" {} + 2 "CREATE TABLE t5(a, b PRIMARY KEY, c, PRIMARY KEY(a))" {} + 3 "CREATE TABLE t5(a INTEGER PRIMARY KEY, b PRIMARY KEY, c)" {} + 4 "CREATE TABLE t5(a INTEGER PRIMARY KEY, b, c, PRIMARY KEY(b, c))" {} + 5 "CREATE TABLE t5(a PRIMARY KEY, b, c, PRIMARY KEY(a))" {} + 6 "CREATE TABLE t5(a INTEGER PRIMARY KEY, b, c, PRIMARY KEY(a))" {} +} + +proc table_pk {tbl} { + set pk [list] + db eval "pragma table_info($tbl)" a { + if {$a(pk)} { lappend pk $a(name) } + } + set pk +} + +# EVIDENCE-OF: R-41411-18837 If the keywords PRIMARY KEY are added to a +# column definition, then the primary key for the table consists of that +# single column. +# +# The above is tested by 4.2.1.* +# +# EVIDENCE-OF: R-31775-48204 Or, if a PRIMARY KEY clause is specified as +# a table-constraint, then the primary key of the table consists of the +# list of columns specified as part of the PRIMARY KEY clause. +# +# The above is tested by 4.2.2.* +# +do_createtable_tests 4.2 -repair { + catchsql { DROP TABLE t5 } +} -tclquery { + table_pk t5 +} { + 1.1 "CREATE TABLE t5(a, b INTEGER PRIMARY KEY, c)" {b} + 1.2 "CREATE TABLE t5(a PRIMARY KEY, b, c)" {a} + + 2.1 "CREATE TABLE t5(a, b, c, PRIMARY KEY(a))" {a} + 2.2 "CREATE TABLE t5(a, b, c, PRIMARY KEY(c,b,a))" {a b c} + 2.3 "CREATE TABLE t5(a, b INTEGER PRIMARY KEY, c)" {b} +} + +# EVIDENCE-OF: R-33986-09410 Each row in a table with a primary key must +# feature a unique combination of values in its primary key columns. +# +# EVIDENCE-OF: R-39102-06737 If an INSERT or UPDATE statement attempts +# to modify the table content so that two or more rows feature identical +# primary key values, it is a constraint violation. +# +drop_all_tables +do_execsql_test 4.3.0 { + CREATE TABLE t1(x PRIMARY KEY, y); + INSERT INTO t1 VALUES(0, 'zero'); + INSERT INTO t1 VALUES(45.5, 'one'); + INSERT INTO t1 VALUES('brambles', 'two'); + INSERT INTO t1 VALUES(X'ABCDEF', 'three'); + + CREATE TABLE t2(x, y, PRIMARY KEY(x, y)); + INSERT INTO t2 VALUES(0, 'zero'); + INSERT INTO t2 VALUES(45.5, 'one'); + INSERT INTO t2 VALUES('brambles', 'two'); + INSERT INTO t2 VALUES(X'ABCDEF', 'three'); +} {} + +do_createtable_tests 4.3.1 -error { %s not unique } { + 1 "INSERT INTO t1 VALUES(0, 0)" {"column x is"} + 2 "INSERT INTO t1 VALUES(45.5, 'abc')" {"column x is"} + 3 "INSERT INTO t1 VALUES(0.0, 'abc')" {"column x is"} + 4 "INSERT INTO t1 VALUES('brambles', 'abc')" {"column x is"} + 5 "INSERT INTO t1 VALUES(X'ABCDEF', 'abc')" {"column x is"} + + 6 "INSERT INTO t2 VALUES(0, 'zero')" {"columns x, y are"} + 7 "INSERT INTO t2 VALUES(45.5, 'one')" {"columns x, y are"} + 8 "INSERT INTO t2 VALUES(0.0, 'zero')" {"columns x, y are"} + 9 "INSERT INTO t2 VALUES('brambles', 'two')" {"columns x, y are"} + 10 "INSERT INTO t2 VALUES(X'ABCDEF', 'three')" {"columns x, y are"} +} +do_createtable_tests 4.3.2 { + 1 "INSERT INTO t1 VALUES(-1, 0)" {} + 2 "INSERT INTO t1 VALUES(45.2, 'abc')" {} + 3 "INSERT INTO t1 VALUES(0.01, 'abc')" {} + 4 "INSERT INTO t1 VALUES('bramble', 'abc')" {} + 5 "INSERT INTO t1 VALUES(X'ABCDEE', 'abc')" {} + + 6 "INSERT INTO t2 VALUES(0, 0)" {} + 7 "INSERT INTO t2 VALUES(45.5, 'abc')" {} + 8 "INSERT INTO t2 VALUES(0.0, 'abc')" {} + 9 "INSERT INTO t2 VALUES('brambles', 'abc')" {} + 10 "INSERT INTO t2 VALUES(X'ABCDEF', 'abc')" {} +} +do_createtable_tests 4.3.3 -error { %s not unique } { + 1 "UPDATE t1 SET x=0 WHERE y='two'" {"column x is"} + 2 "UPDATE t1 SET x='brambles' WHERE y='three'" {"column x is"} + 3 "UPDATE t1 SET x=45.5 WHERE y='zero'" {"column x is"} + 4 "UPDATE t1 SET x=X'ABCDEF' WHERE y='one'" {"column x is"} + 5 "UPDATE t1 SET x=0.0 WHERE y='three'" {"column x is"} + + 6 "UPDATE t2 SET x=0, y='zero' WHERE y='two'" {"columns x, y are"} + 7 "UPDATE t2 SET x='brambles', y='two' WHERE y='three'" + {"columns x, y are"} + 8 "UPDATE t2 SET x=45.5, y='one' WHERE y='zero'" {"columns x, y are"} + 9 "UPDATE t2 SET x=X'ABCDEF', y='three' WHERE y='one'" + {"columns x, y are"} + 10 "UPDATE t2 SET x=0.0, y='zero' WHERE y='three'" + {"columns x, y are"} +} + + +# EVIDENCE-OF: R-52572-02078 For the purposes of determining the +# uniqueness of primary key values, NULL values are considered distinct +# from all other values, including other NULLs. +# +do_createtable_tests 4.4 { + 1 "INSERT INTO t1 VALUES(NULL, 0)" {} + 2 "INSERT INTO t1 VALUES(NULL, 0)" {} + 3 "INSERT INTO t1 VALUES(NULL, 0)" {} + + 4 "INSERT INTO t2 VALUES(NULL, 'zero')" {} + 5 "INSERT INTO t2 VALUES(NULL, 'one')" {} + 6 "INSERT INTO t2 VALUES(NULL, 'two')" {} + 7 "INSERT INTO t2 VALUES(NULL, 'three')" {} + + 8 "INSERT INTO t2 VALUES(0, NULL)" {} + 9 "INSERT INTO t2 VALUES(45.5, NULL)" {} + 10 "INSERT INTO t2 VALUES(0.0, NULL)" {} + 11 "INSERT INTO t2 VALUES('brambles', NULL)" {} + 12 "INSERT INTO t2 VALUES(X'ABCDEF', NULL)" {} + + 13 "INSERT INTO t2 VALUES(NULL, NULL)" {} + 14 "INSERT INTO t2 VALUES(NULL, NULL)" {} +} + +# EVIDENCE-OF: R-61866-38053 Unless the column is an INTEGER PRIMARY KEY +# SQLite allows NULL values in a PRIMARY KEY column. +# +# If the column is an integer primary key, attempting to insert a NULL +# into the column triggers the auto-increment behavior. Attempting +# to use UPDATE to set an ipk column to a NULL value is an error. +# +do_createtable_tests 4.5.1 { + 1 "SELECT count(*) FROM t1 WHERE x IS NULL" 3 + 2 "SELECT count(*) FROM t2 WHERE x IS NULL" 6 + 3 "SELECT count(*) FROM t2 WHERE y IS NULL" 7 + 4 "SELECT count(*) FROM t2 WHERE x IS NULL AND y IS NULL" 2 +} +do_execsql_test 4.5.2 { + CREATE TABLE t3(s, u INTEGER PRIMARY KEY, v); + INSERT INTO t3 VALUES(1, NULL, 2); + INSERT INTO t3 VALUES('x', NULL, 'y'); + SELECT u FROM t3; +} {1 2} +do_catchsql_test 4.5.3 { + INSERT INTO t3 VALUES(2, 5, 3); + UPDATE t3 SET u = NULL WHERE s = 2; +} {1 {datatype mismatch}} + +# EVIDENCE-OF: R-00227-21080 A UNIQUE constraint is similar to a PRIMARY +# KEY constraint, except that a single table may have any number of +# UNIQUE constraints. +# +drop_all_tables +do_createtable_tests 4.6 { + 1 "CREATE TABLE t1(a UNIQUE, b UNIQUE)" {} + 2 "CREATE TABLE t2(a UNIQUE, b, c, UNIQUE(c, b))" {} + 3 "CREATE TABLE t3(a, b, c, UNIQUE(a), UNIQUE(b), UNIQUE(c))" {} + 4 "CREATE TABLE t4(a, b, c, UNIQUE(a, b, c))" {} +} + +# EVIDENCE-OF: R-55240-58877 For each UNIQUE constraint on the table, +# each row must feature a unique combination of values in the columns +# identified by the UNIQUE constraint. +# +# EVIDENCE-OF: R-47733-51480 If an INSERT or UPDATE statement attempts +# to modify the table content so that two or more rows feature identical +# values in a set of columns that are subject to a UNIQUE constraint, it +# is a constraint violation. +# +do_execsql_test 4.7.0 { + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(4.3, 5.5); + INSERT INTO t1 VALUES('reveal', 'variableness'); + INSERT INTO t1 VALUES(X'123456', X'654321'); + + INSERT INTO t4 VALUES('xyx', 1, 1); + INSERT INTO t4 VALUES('xyx', 2, 1); + INSERT INTO t4 VALUES('uvw', 1, 1); +} +do_createtable_tests 4.7.1 -error { %s not unique } { + 1 "INSERT INTO t1 VALUES(1, 'one')" {{column a is}} + 2 "INSERT INTO t1 VALUES(4.3, 'two')" {{column a is}} + 3 "INSERT INTO t1 VALUES('reveal', 'three')" {{column a is}} + 4 "INSERT INTO t1 VALUES(X'123456', 'four')" {{column a is}} + + 5 "UPDATE t1 SET a = 1 WHERE rowid=2" {{column a is}} + 6 "UPDATE t1 SET a = 4.3 WHERE rowid=3" {{column a is}} + 7 "UPDATE t1 SET a = 'reveal' WHERE rowid=4" {{column a is}} + 8 "UPDATE t1 SET a = X'123456' WHERE rowid=1" {{column a is}} + + 9 "INSERT INTO t4 VALUES('xyx', 1, 1)" {{columns a, b, c are}} + 10 "INSERT INTO t4 VALUES('xyx', 2, 1)" {{columns a, b, c are}} + 11 "INSERT INTO t4 VALUES('uvw', 1, 1)" {{columns a, b, c are}} + + 12 "UPDATE t4 SET a='xyx' WHERE rowid=3" {{columns a, b, c are}} + 13 "UPDATE t4 SET b=1 WHERE rowid=2" {{columns a, b, c are}} + 14 "UPDATE t4 SET a=0, b=0, c=0" {{columns a, b, c are}} +} + +# EVIDENCE-OF: R-21289-11559 As with PRIMARY KEY constraints, for the +# purposes of UNIQUE constraints NULL values are considered distinct +# from all other values (including other NULLs). +# +do_createtable_tests 4.8 { + 1 "INSERT INTO t1 VALUES(NULL, NULL)" {} + 2 "INSERT INTO t1 VALUES(NULL, NULL)" {} + 3 "UPDATE t1 SET a = NULL" {} + 4 "UPDATE t1 SET b = NULL" {} + + 5 "INSERT INTO t4 VALUES(NULL, NULL, NULL)" {} + 6 "INSERT INTO t4 VALUES(NULL, NULL, NULL)" {} + 7 "UPDATE t4 SET a = NULL" {} + 8 "UPDATE t4 SET b = NULL" {} + 9 "UPDATE t4 SET c = NULL" {} +} + +# EVIDENCE-OF: R-26983-26377 INTEGER PRIMARY KEY columns aside, both +# UNIQUE and PRIMARY KEY constraints are implemented by creating an +# index in the database (in the same way as a "CREATE UNIQUE INDEX" +# statement would). +do_createtable_tests 4.9 -repair drop_all_tables -query { + SELECT count(*) FROM sqlite_master WHERE type='index' +} { + 1 "CREATE TABLE t1(a TEXT PRIMARY KEY, b)" 1 + 2 "CREATE TABLE t1(a INTEGER PRIMARY KEY, b)" 0 + 3 "CREATE TABLE t1(a TEXT UNIQUE, b)" 1 + 4 "CREATE TABLE t1(a PRIMARY KEY, b TEXT UNIQUE)" 2 + 5 "CREATE TABLE t1(a PRIMARY KEY, b, c, UNIQUE(c, b))" 2 +} + +# EVIDENCE-OF: R-02252-33116 Such an index is used like any other index +# in the database to optimize queries. +# +do_execsql_test 4.10.0 { + CREATE TABLE t1(a, b PRIMARY KEY); + CREATE TABLE t2(a, b, c, UNIQUE(b, c)); +} +do_createtable_tests 4.10 { + 1 "EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE b = 5" + {0 0 0 {SEARCH TABLE t1 USING INDEX sqlite_autoindex_t1_1 (b=?)}} + + 2 "EXPLAIN QUERY PLAN SELECT * FROM t2 ORDER BY b, c" + {0 0 0 {SCAN TABLE t2 USING INDEX sqlite_autoindex_t2_1}} + + 3 "EXPLAIN QUERY PLAN SELECT * FROM t2 WHERE b=10 AND c>10" + {0 0 0 {SEARCH TABLE t2 USING INDEX sqlite_autoindex_t2_1 (b=? AND c>?)}} +} + +# EVIDENCE-OF: R-45493-35653 A CHECK constraint may be attached to a +# column definition or specified as a table constraint. In practice it +# makes no difference. +# +# All the tests that deal with CHECK constraints below (4.11.* and +# 4.12.*) are run once for a table with the check constraint attached +# to a column definition, and once with a table where the check +# condition is specified as a table constraint. +# +# EVIDENCE-OF: R-55435-14303 Each time a new row is inserted into the +# table or an existing row is updated, the expression associated with +# each CHECK constraint is evaluated and cast to a NUMERIC value in the +# same way as a CAST expression. If the result is zero (integer value 0 +# or real value 0.0), then a constraint violation has occurred. +# +drop_all_tables +do_execsql_test 4.11 { + CREATE TABLE x1(a TEXT, b INTEGER CHECK( b>0 )); + CREATE TABLE t1(a TEXT, b INTEGER, CHECK( b>0 )); + INSERT INTO x1 VALUES('x', 'xx'); + INSERT INTO x1 VALUES('y', 'yy'); + INSERT INTO t1 SELECT * FROM x1; + + CREATE TABLE x2(a CHECK( a||b ), b); + CREATE TABLE t2(a, b, CHECK( a||b )); + INSERT INTO x2 VALUES(1, 'xx'); + INSERT INTO x2 VALUES(1, 'yy'); + INSERT INTO t2 SELECT * FROM x2; +} + +do_createtable_tests 4.11 -error {constraint failed} { + 1a "INSERT INTO x1 VALUES('one', 0)" {} + 1b "INSERT INTO t1 VALUES('one', -4.0)" {} + + 2a "INSERT INTO x2 VALUES('abc', 1)" {} + 2b "INSERT INTO t2 VALUES('abc', 1)" {} + + 3a "INSERT INTO x2 VALUES(0, 'abc')" {} + 3b "INSERT INTO t2 VALUES(0, 'abc')" {} + + 4a "UPDATE t1 SET b=-1 WHERE rowid=1" {} + 4b "UPDATE x1 SET b=-1 WHERE rowid=1" {} + + 4a "UPDATE x2 SET a='' WHERE rowid=1" {} + 4b "UPDATE t2 SET a='' WHERE rowid=1" {} +} + +# EVIDENCE-OF: R-34109-39108 If the CHECK expression evaluates to NULL, +# or any other non-zero value, it is not a constraint violation. +# +do_createtable_tests 4.12 { + 1a "INSERT INTO x1 VALUES('one', NULL)" {} + 1b "INSERT INTO t1 VALUES('one', NULL)" {} + + 2a "INSERT INTO x1 VALUES('one', 2)" {} + 2b "INSERT INTO t1 VALUES('one', 2)" {} + + 3a "INSERT INTO x2 VALUES(1, 'abc')" {} + 3b "INSERT INTO t2 VALUES(1, 'abc')" {} +} + +# EVIDENCE-OF: R-02060-64547 A NOT NULL constraint may only be attached +# to a column definition, not specified as a table constraint. +# +drop_all_tables +do_createtable_tests 4.13.1 { + 1 "CREATE TABLE t1(a NOT NULL, b)" {} + 2 "CREATE TABLE t2(a PRIMARY KEY NOT NULL, b)" {} + 3 "CREATE TABLE t3(a NOT NULL, b NOT NULL, c NOT NULL UNIQUE)" {} +} +do_createtable_tests 4.13.2 -error { + near "NOT": syntax error +} { + 1 "CREATE TABLE t4(a, b, NOT NULL(a))" {} + 2 "CREATE TABLE t4(a PRIMARY KEY, b, NOT NULL(a))" {} + 3 "CREATE TABLE t4(a, b, c UNIQUE, NOT NULL(a, b, c))" {} +} + +# EVIDENCE-OF: R-31795-57643 a NOT NULL constraint dictates that the +# associated column may not contain a NULL value. Attempting to set the +# column value to NULL when inserting a new row or updating an existing +# one causes a constraint violation. +# +# These tests use the tables created by 4.13. +# +do_execsql_test 4.14.0 { + INSERT INTO t1 VALUES('x', 'y'); + INSERT INTO t1 VALUES('z', NULL); + + INSERT INTO t2 VALUES('x', 'y'); + INSERT INTO t2 VALUES('z', NULL); + + INSERT INTO t3 VALUES('x', 'y', 'z'); + INSERT INTO t3 VALUES(1, 2, 3); +} +do_createtable_tests 4.14 -error { + %s may not be NULL +} { + 1 "INSERT INTO t1 VALUES(NULL, 'a')" {t1.a} + 2 "INSERT INTO t2 VALUES(NULL, 'b')" {t2.a} + 3 "INSERT INTO t3 VALUES('c', 'd', NULL)" {t3.c} + 4 "INSERT INTO t3 VALUES('e', NULL, 'f')" {t3.b} + 5 "INSERT INTO t3 VALUES(NULL, 'g', 'h')" {t3.a} +} + +# EVIDENCE-OF: R-42511-39459 PRIMARY KEY, UNIQUE and NOT NULL +# constraints may be explicitly assigned a default conflict resolution +# algorithm by including a conflict-clause in their definitions. +# +# Conflict clauses: ABORT, ROLLBACK, IGNORE, FAIL, REPLACE +# +# Test cases 4.15.*, 4.16.* and 4.17.* focus on PRIMARY KEY, NOT NULL +# and UNIQUE constraints, respectively. +# +drop_all_tables +do_execsql_test 4.15.0 { + CREATE TABLE t1_ab(a PRIMARY KEY ON CONFLICT ABORT, b); + CREATE TABLE t1_ro(a PRIMARY KEY ON CONFLICT ROLLBACK, b); + CREATE TABLE t1_ig(a PRIMARY KEY ON CONFLICT IGNORE, b); + CREATE TABLE t1_fa(a PRIMARY KEY ON CONFLICT FAIL, b); + CREATE TABLE t1_re(a PRIMARY KEY ON CONFLICT REPLACE, b); + CREATE TABLE t1_xx(a PRIMARY KEY, b); + + INSERT INTO t1_ab VALUES(1, 'one'); + INSERT INTO t1_ab VALUES(2, 'two'); + INSERT INTO t1_ro SELECT * FROM t1_ab; + INSERT INTO t1_ig SELECT * FROM t1_ab; + INSERT INTO t1_fa SELECT * FROM t1_ab; + INSERT INTO t1_re SELECT * FROM t1_ab; + INSERT INTO t1_xx SELECT * FROM t1_ab; + + CREATE TABLE t2_ab(a, b NOT NULL ON CONFLICT ABORT); + CREATE TABLE t2_ro(a, b NOT NULL ON CONFLICT ROLLBACK); + CREATE TABLE t2_ig(a, b NOT NULL ON CONFLICT IGNORE); + CREATE TABLE t2_fa(a, b NOT NULL ON CONFLICT FAIL); + CREATE TABLE t2_re(a, b NOT NULL ON CONFLICT REPLACE); + CREATE TABLE t2_xx(a, b NOT NULL); + + INSERT INTO t2_ab VALUES(1, 'one'); + INSERT INTO t2_ab VALUES(2, 'two'); + INSERT INTO t2_ro SELECT * FROM t2_ab; + INSERT INTO t2_ig SELECT * FROM t2_ab; + INSERT INTO t2_fa SELECT * FROM t2_ab; + INSERT INTO t2_re SELECT * FROM t2_ab; + INSERT INTO t2_xx SELECT * FROM t2_ab; + + CREATE TABLE t3_ab(a, b, UNIQUE(a, b) ON CONFLICT ABORT); + CREATE TABLE t3_ro(a, b, UNIQUE(a, b) ON CONFLICT ROLLBACK); + CREATE TABLE t3_ig(a, b, UNIQUE(a, b) ON CONFLICT IGNORE); + CREATE TABLE t3_fa(a, b, UNIQUE(a, b) ON CONFLICT FAIL); + CREATE TABLE t3_re(a, b, UNIQUE(a, b) ON CONFLICT REPLACE); + CREATE TABLE t3_xx(a, b, UNIQUE(a, b)); + + INSERT INTO t3_ab VALUES(1, 'one'); + INSERT INTO t3_ab VALUES(2, 'two'); + INSERT INTO t3_ro SELECT * FROM t3_ab; + INSERT INTO t3_ig SELECT * FROM t3_ab; + INSERT INTO t3_fa SELECT * FROM t3_ab; + INSERT INTO t3_re SELECT * FROM t3_ab; + INSERT INTO t3_xx SELECT * FROM t3_ab; +} + +foreach {tn tbl res ac data} { + 1 t1_ab {1 {column a is not unique}} 0 {1 one 2 two 3 three} + 2 t1_ro {1 {column a is not unique}} 1 {1 one 2 two} + 3 t1_fa {1 {column a is not unique}} 0 {1 one 2 two 3 three 4 string} + 4 t1_ig {0 {}} 0 {1 one 2 two 3 three 4 string 6 string} + 5 t1_re {0 {}} 0 {1 one 2 two 4 string 3 string 6 string} + 6 t1_xx {1 {column a is not unique}} 0 {1 one 2 two 3 three} +} { + catchsql COMMIT + do_execsql_test 4.15.$tn.1 "BEGIN; INSERT INTO $tbl VALUES(3, 'three')" + + do_catchsql_test 4.15.$tn.2 " + INSERT INTO $tbl SELECT ((a%2)*a+3), 'string' FROM $tbl; + " $res + + do_test e_createtable-4.15.$tn.3 { sqlite3_get_autocommit db } $ac + do_execsql_test 4.15.$tn.4 "SELECT * FROM $tbl" $data +} +foreach {tn tbl res ac data} { + 1 t2_ab {1 {t2_ab.b may not be NULL}} 0 {1 one 2 two 3 three} + 2 t2_ro {1 {t2_ro.b may not be NULL}} 1 {1 one 2 two} + 3 t2_fa {1 {t2_fa.b may not be NULL}} 0 {1 one 2 two 3 three 4 xx} + 4 t2_ig {0 {}} 0 {1 one 2 two 3 three 4 xx 6 xx} + 5 t2_re {1 {t2_re.b may not be NULL}} 0 {1 one 2 two 3 three} + 6 t2_xx {1 {t2_xx.b may not be NULL}} 0 {1 one 2 two 3 three} +} { + catchsql COMMIT + do_execsql_test 4.16.$tn.1 "BEGIN; INSERT INTO $tbl VALUES(3, 'three')" + + do_catchsql_test 4.16.$tn.2 " + INSERT INTO $tbl SELECT a+3, CASE a WHEN 2 THEN NULL ELSE 'xx' END FROM $tbl + " $res + + do_test e_createtable-4.16.$tn.3 { sqlite3_get_autocommit db } $ac + do_execsql_test 4.16.$tn.4 "SELECT * FROM $tbl" $data +} +foreach {tn tbl res ac data} { + 1 t3_ab {1 {columns a, b are not unique}} 0 {1 one 2 two 3 three} + 2 t3_ro {1 {columns a, b are not unique}} 1 {1 one 2 two} + 3 t3_fa {1 {columns a, b are not unique}} 0 {1 one 2 two 3 three 4 three} + 4 t3_ig {0 {}} 0 {1 one 2 two 3 three 4 three 6 three} + 5 t3_re {0 {}} 0 {1 one 2 two 4 three 3 three 6 three} + 6 t3_xx {1 {columns a, b are not unique}} 0 {1 one 2 two 3 three} +} { + catchsql COMMIT + do_execsql_test 4.17.$tn.1 "BEGIN; INSERT INTO $tbl VALUES(3, 'three')" + + do_catchsql_test 4.17.$tn.2 " + INSERT INTO $tbl SELECT ((a%2)*a+3), 'three' FROM $tbl + " $res + + do_test e_createtable-4.17.$tn.3 { sqlite3_get_autocommit db } $ac + do_execsql_test 4.17.$tn.4 "SELECT * FROM $tbl ORDER BY rowid" $data +} +catchsql COMMIT + +# EVIDENCE-OF: R-12645-39772 Or, if a constraint definition does not +# include a conflict-clause or it is a CHECK constraint, the default +# conflict resolution algorithm is ABORT. +# +# The first half of the above is tested along with explicit ON +# CONFLICT clauses above (specifically, the tests involving t1_xx, t2_xx +# and t3_xx). The following just tests that the default conflict +# handling for CHECK constraints is ABORT. +# +do_execsql_test 4.18.1 { + CREATE TABLE t4(a, b CHECK (b!=10)); + INSERT INTO t4 VALUES(1, 2); + INSERT INTO t4 VALUES(3, 4); +} +do_execsql_test 4.18.2 { BEGIN; INSERT INTO t4 VALUES(5, 6) } +do_catchsql_test 4.18.3 { + INSERT INTO t4 SELECT a+4, b+4 FROM t4 +} {1 {constraint failed}} +do_test e_createtable-4.18.4 { sqlite3_get_autocommit db } 0 +do_execsql_test 4.18.5 { SELECT * FROM t4 } {1 2 3 4 5 6} + +# EVIDENCE-OF: R-19114-56113 Different constraints within the same table +# may have different default conflict resolution algorithms. +# +do_execsql_test 4.19.0 { + CREATE TABLE t5(a NOT NULL ON CONFLICT IGNORE, b NOT NULL ON CONFLICT ABORT); +} +do_catchsql_test 4.19.1 { INSERT INTO t5 VALUES(NULL, 'not null') } {0 {}} +do_execsql_test 4.19.2 { SELECT * FROM t5 } {} +do_catchsql_test 4.19.3 { INSERT INTO t5 VALUES('not null', NULL) } \ + {1 {t5.b may not be NULL}} +do_execsql_test 4.19.4 { SELECT * FROM t5 } {} + +#------------------------------------------------------------------------ +# Tests for INTEGER PRIMARY KEY and rowid related statements. +# + +# EVIDENCE-OF: R-52584-04009 The rowid value can be accessed using one +# of the special case-independent names "rowid", "oid", or "_rowid_" in +# place of a column name. +# +drop_all_tables +do_execsql_test 5.1.0 { + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES('one', 'first'); + INSERT INTO t1 VALUES('two', 'second'); + INSERT INTO t1 VALUES('three', 'third'); +} +do_createtable_tests 5.1 { + 1 "SELECT rowid FROM t1" {1 2 3} + 2 "SELECT oid FROM t1" {1 2 3} + 3 "SELECT _rowid_ FROM t1" {1 2 3} + 4 "SELECT ROWID FROM t1" {1 2 3} + 5 "SELECT OID FROM t1" {1 2 3} + 6 "SELECT _ROWID_ FROM t1" {1 2 3} + 7 "SELECT RoWiD FROM t1" {1 2 3} + 8 "SELECT OiD FROM t1" {1 2 3} + 9 "SELECT _RoWiD_ FROM t1" {1 2 3} +} + +# EVIDENCE-OF: R-26501-17306 If a table contains a user defined column +# named "rowid", "oid" or "_rowid_", then that name always refers the +# explicitly declared column and cannot be used to retrieve the integer +# rowid value. +# +do_execsql_test 5.2.0 { + CREATE TABLE t2(oid, b); + CREATE TABLE t3(a, _rowid_); + CREATE TABLE t4(a, b, rowid); + + INSERT INTO t2 VALUES('one', 'two'); + INSERT INTO t2 VALUES('three', 'four'); + + INSERT INTO t3 VALUES('five', 'six'); + INSERT INTO t3 VALUES('seven', 'eight'); + + INSERT INTO t4 VALUES('nine', 'ten', 'eleven'); + INSERT INTO t4 VALUES('twelve', 'thirteen', 'fourteen'); +} +do_createtable_tests 5.2 { + 1 "SELECT oid, rowid, _rowid_ FROM t2" {one 1 1 three 2 2} + 2 "SELECT oid, rowid, _rowid_ FROM t3" {1 1 six 2 2 eight} + 3 "SELECT oid, rowid, _rowid_ FROM t4" {1 eleven 1 2 fourteen 2} +} + + +# Argument $tbl is the name of a table in the database. Argument $col is +# the name of one of the tables columns. Return 1 if $col is an alias for +# the rowid, or 0 otherwise. +# +proc is_integer_primary_key {tbl col} { + lindex [db eval [subst { + DELETE FROM $tbl; + INSERT INTO $tbl ($col) VALUES(0); + SELECT (rowid==$col) FROM $tbl; + DELETE FROM $tbl; + }]] 0 +} + +# EVIDENCE-OF: R-53738-31673 With one exception, if a table has a +# primary key that consists of a single column, and the declared type of +# that column is "INTEGER" in any mixture of upper and lower case, then +# the column becomes an alias for the rowid. +# +# EVIDENCE-OF: R-45951-08347 if the declaration of a column with +# declared type "INTEGER" includes an "PRIMARY KEY DESC" clause, it does +# not become an alias for the rowid and is not classified as an integer +# primary key. +# +do_createtable_tests 5.3 -tclquery { + is_integer_primary_key t5 pk +} -repair { + catchsql { DROP TABLE t5 } +} { + 1 "CREATE TABLE t5(pk integer primary key)" 1 + 2 "CREATE TABLE t5(pk integer, primary key(pk))" 1 + 3 "CREATE TABLE t5(pk integer, v integer, primary key(pk))" 1 + 4 "CREATE TABLE t5(pk integer, v integer, primary key(pk, v))" 0 + 5 "CREATE TABLE t5(pk int, v integer, primary key(pk, v))" 0 + 6 "CREATE TABLE t5(pk int, v integer, primary key(pk))" 0 + 7 "CREATE TABLE t5(pk int primary key, v integer)" 0 + 8 "CREATE TABLE t5(pk inTEger primary key)" 1 + 9 "CREATE TABLE t5(pk inteGEr, primary key(pk))" 1 + 10 "CREATE TABLE t5(pk INTEGER, v integer, primary key(pk))" 1 +} + +# EVIDENCE-OF: R-41444-49665 Other integer type names like "INT" or +# "BIGINT" or "SHORT INTEGER" or "UNSIGNED INTEGER" causes the primary +# key column to behave as an ordinary table column with integer affinity +# and a unique index, not as an alias for the rowid. +# +do_execsql_test 5.4.1 { + CREATE TABLE t6(pk INT primary key); + CREATE TABLE t7(pk BIGINT primary key); + CREATE TABLE t8(pk SHORT INTEGER primary key); + CREATE TABLE t9(pk UNSIGNED INTEGER primary key); +} +do_test e_createtable-5.4.2.1 { is_integer_primary_key t6 pk } 0 +do_test e_createtable-5.4.2.2 { is_integer_primary_key t7 pk } 0 +do_test e_createtable-5.4.2.3 { is_integer_primary_key t8 pk } 0 +do_test e_createtable-5.4.2.4 { is_integer_primary_key t9 pk } 0 + +do_execsql_test 5.4.3 { + INSERT INTO t6 VALUES('2.0'); + INSERT INTO t7 VALUES('2.0'); + INSERT INTO t8 VALUES('2.0'); + INSERT INTO t9 VALUES('2.0'); + SELECT typeof(pk), pk FROM t6; + SELECT typeof(pk), pk FROM t7; + SELECT typeof(pk), pk FROM t8; + SELECT typeof(pk), pk FROM t9; +} {integer 2 integer 2 integer 2 integer 2} + +do_catchsql_test 5.4.4.1 { + INSERT INTO t6 VALUES(2) +} {1 {column pk is not unique}} +do_catchsql_test 5.4.4.2 { + INSERT INTO t7 VALUES(2) +} {1 {column pk is not unique}} +do_catchsql_test 5.4.4.3 { + INSERT INTO t8 VALUES(2) +} {1 {column pk is not unique}} +do_catchsql_test 5.4.4.4 { + INSERT INTO t9 VALUES(2) +} {1 {column pk is not unique}} + +# EVIDENCE-OF: R-56094-57830 the following three table declarations all +# cause the column "x" to be an alias for the rowid (an integer primary +# key): CREATE TABLE t(x INTEGER PRIMARY KEY ASC, y, z); CREATE TABLE +# t(x INTEGER, y, z, PRIMARY KEY(x ASC)); CREATE TABLE t(x INTEGER, y, +# z, PRIMARY KEY(x DESC)); +# +# EVIDENCE-OF: R-20149-25884 the following declaration does not result +# in "x" being an alias for the rowid: CREATE TABLE t(x INTEGER PRIMARY +# KEY DESC, y, z); +# +do_createtable_tests 5 -tclquery { + is_integer_primary_key t x +} -repair { + catchsql { DROP TABLE t } +} { + 5.1 "CREATE TABLE t(x INTEGER PRIMARY KEY ASC, y, z)" 1 + 5.2 "CREATE TABLE t(x INTEGER, y, z, PRIMARY KEY(x ASC))" 1 + 5.3 "CREATE TABLE t(x INTEGER, y, z, PRIMARY KEY(x DESC))" 1 + 6.1 "CREATE TABLE t(x INTEGER PRIMARY KEY DESC, y, z)" 0 +} + +# EVIDENCE-OF: R-03733-29734 Rowid values may be modified using an +# UPDATE statement in the same way as any other column value can, either +# using one of the built-in aliases ("rowid", "oid" or "_rowid_") or by +# using an alias created by an integer primary key. +# +do_execsql_test 5.7.0 { + CREATE TABLE t10(a, b); + INSERT INTO t10 VALUES('ten', 10); + + CREATE TABLE t11(a, b INTEGER PRIMARY KEY); + INSERT INTO t11 VALUES('ten', 10); +} +do_createtable_tests 5.7.1 -query { + SELECT rowid, _rowid_, oid FROM t10; +} { + 1 "UPDATE t10 SET rowid = 5" {5 5 5} + 2 "UPDATE t10 SET _rowid_ = 6" {6 6 6} + 3 "UPDATE t10 SET oid = 7" {7 7 7} +} +do_createtable_tests 5.7.2 -query { + SELECT rowid, _rowid_, oid, b FROM t11; +} { + 1 "UPDATE t11 SET rowid = 5" {5 5 5 5} + 2 "UPDATE t11 SET _rowid_ = 6" {6 6 6 6} + 3 "UPDATE t11 SET oid = 7" {7 7 7 7} + 4 "UPDATE t11 SET b = 8" {8 8 8 8} +} + +# EVIDENCE-OF: R-58706-14229 Similarly, an INSERT statement may provide +# a value to use as the rowid for each row inserted. +# +do_createtable_tests 5.8.1 -query { + SELECT rowid, _rowid_, oid FROM t10; +} -repair { + execsql { DELETE FROM t10 } +} { + 1 "INSERT INTO t10(oid) VALUES(15)" {15 15 15} + 2 "INSERT INTO t10(rowid) VALUES(16)" {16 16 16} + 3 "INSERT INTO t10(_rowid_) VALUES(17)" {17 17 17} + 4 "INSERT INTO t10(a, b, oid) VALUES(1,2,3)" {3 3 3} +} +do_createtable_tests 5.8.2 -query { + SELECT rowid, _rowid_, oid, b FROM t11; +} -repair { + execsql { DELETE FROM t11 } +} { + 1 "INSERT INTO t11(oid) VALUES(15)" {15 15 15 15} + 2 "INSERT INTO t11(rowid) VALUES(16)" {16 16 16 16} + 3 "INSERT INTO t11(_rowid_) VALUES(17)" {17 17 17 17} + 4 "INSERT INTO t11(a, b) VALUES(1,2)" {2 2 2 2} +} + +# EVIDENCE-OF: R-32326-44592 Unlike normal SQLite columns, an integer +# primary key or rowid column must contain integer values. Integer +# primary key or rowid columns are not able to hold floating point +# values, strings, BLOBs, or NULLs. +# +# This is considered by the tests for the following 3 statements, +# which show that: +# +# 1. Attempts to UPDATE a rowid column to a non-integer value fail, +# 2. Attempts to INSERT a real, string or blob value into a rowid +# column fail, and +# 3. Attempting to INSERT a NULL value into a rowid column causes the +# system to automatically select an integer value to use. +# + + +# EVIDENCE-OF: R-64224-62578 If an UPDATE statement attempts to set an +# integer primary key or rowid column to a NULL or blob value, or to a +# string or real value that cannot be losslessly converted to an +# integer, a "datatype mismatch" error occurs and the statement is +# aborted. +# +drop_all_tables +do_execsql_test 5.9.0 { + CREATE TABLE t12(x INTEGER PRIMARY KEY, y); + INSERT INTO t12 VALUES(5, 'five'); +} +do_createtable_tests 5.9.1 -query { SELECT typeof(x), x FROM t12 } { + 1 "UPDATE t12 SET x = 4" {integer 4} + 2 "UPDATE t12 SET x = 10.0" {integer 10} + 3 "UPDATE t12 SET x = '12.0'" {integer 12} + 4 "UPDATE t12 SET x = '-15.0'" {integer -15} +} +do_createtable_tests 5.9.2 -error { + datatype mismatch +} { + 1 "UPDATE t12 SET x = 4.1" {} + 2 "UPDATE t12 SET x = 'hello'" {} + 3 "UPDATE t12 SET x = NULL" {} + 4 "UPDATE t12 SET x = X'ABCD'" {} + 5 "UPDATE t12 SET x = X'3900'" {} + 6 "UPDATE t12 SET x = X'39'" {} +} + +# EVIDENCE-OF: R-05734-13629 If an INSERT statement attempts to insert a +# blob value, or a string or real value that cannot be losslessly +# converted to an integer into an integer primary key or rowid column, a +# "datatype mismatch" error occurs and the statement is aborted. +# +do_execsql_test 5.10.0 { DELETE FROM t12 } +do_createtable_tests 5.10.1 -error { + datatype mismatch +} { + 1 "INSERT INTO t12(x) VALUES(4.1)" {} + 2 "INSERT INTO t12(x) VALUES('hello')" {} + 3 "INSERT INTO t12(x) VALUES(X'ABCD')" {} + 4 "INSERT INTO t12(x) VALUES(X'3900')" {} + 5 "INSERT INTO t12(x) VALUES(X'39')" {} +} +do_createtable_tests 5.10.2 -query { + SELECT typeof(x), x FROM t12 +} -repair { + execsql { DELETE FROM t12 } +} { + 1 "INSERT INTO t12(x) VALUES(4)" {integer 4} + 2 "INSERT INTO t12(x) VALUES(10.0)" {integer 10} + 3 "INSERT INTO t12(x) VALUES('12.0')" {integer 12} + 4 "INSERT INTO t12(x) VALUES('4e3')" {integer 4000} + 5 "INSERT INTO t12(x) VALUES('-14.0')" {integer -14} +} + +# EVIDENCE-OF: R-07986-46024 If an INSERT statement attempts to insert a +# NULL value into a rowid or integer primary key column, the system +# chooses an integer value to use as the rowid automatically. +# +do_execsql_test 5.11.0 { DELETE FROM t12 } +do_createtable_tests 5.11 -query { + SELECT typeof(x), x FROM t12 WHERE y IS (SELECT max(y) FROM t12) +} { + 1 "INSERT INTO t12 DEFAULT VALUES" {integer 1} + 2 "INSERT INTO t12(y) VALUES(5)" {integer 2} + 3 "INSERT INTO t12(x,y) VALUES(NULL, 10)" {integer 3} + 4 "INSERT INTO t12(x,y) SELECT NULL, 15 FROM t12" + {integer 4 integer 5 integer 6} + 5 "INSERT INTO t12(y) SELECT 20 FROM t12 LIMIT 3" + {integer 7 integer 8 integer 9} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_delete.test b/components/external/SQLite-3.8.1/test/e_delete.test new file mode 100644 index 0000000000000000000000000000000000000000..b857cf147feffd116448ebfe74ae9659e9c1dd78 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_delete.test @@ -0,0 +1,474 @@ +# 2010 September 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_delete.html document are correct. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +proc do_delete_tests {args} { + uplevel do_select_tests $args +} + +do_execsql_test e_delete-0.0 { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a); +} {} + +# -- syntax diagram delete-stmt +# -- syntax diagram qualified-table-name +# +do_delete_tests e_delete-0.1 { + 1 "DELETE FROM t1" {} + 2 "DELETE FROM t1 INDEXED BY i1" {} + 3 "DELETE FROM t1 NOT INDEXED" {} + 4 "DELETE FROM main.t1" {} + 5 "DELETE FROM main.t1 INDEXED BY i1" {} + 6 "DELETE FROM main.t1 NOT INDEXED" {} + 7 "DELETE FROM t1 WHERE a>2" {} + 8 "DELETE FROM t1 INDEXED BY i1 WHERE a>2" {} + 9 "DELETE FROM t1 NOT INDEXED WHERE a>2" {} + 10 "DELETE FROM main.t1 WHERE a>2" {} + 11 "DELETE FROM main.t1 INDEXED BY i1 WHERE a>2" {} + 12 "DELETE FROM main.t1 NOT INDEXED WHERE a>2" {} +} + +# EVIDENCE-OF: R-20205-17349 If the WHERE clause is not present, all +# records in the table are deleted. +# +drop_all_tables +do_test e_delete-1.0 { + db transaction { + foreach t {t1 t2 t3 t4 t5 t6} { + execsql [string map [list %T% $t] { + CREATE TABLE %T%(x, y); + INSERT INTO %T% VALUES(1, 'one'); + INSERT INTO %T% VALUES(2, 'two'); + INSERT INTO %T% VALUES(3, 'three'); + INSERT INTO %T% VALUES(4, 'four'); + INSERT INTO %T% VALUES(5, 'five'); + }] + } + } +} {} +do_delete_tests e_delete-1.1 { + 1 "DELETE FROM t1 ; SELECT * FROM t1" {} + 2 "DELETE FROM main.t2 ; SELECT * FROM t2" {} +} + +# EVIDENCE-OF: R-30203-16177 If a WHERE clause is supplied, then only +# those rows for which the result of evaluating the WHERE clause as a +# boolean expression is true are deleted. +# +do_delete_tests e_delete-1.2 { + 1 "DELETE FROM t3 WHERE 1 ; SELECT x FROM t3" {} + 2 "DELETE FROM main.t4 WHERE 0 ; SELECT x FROM t4" {1 2 3 4 5} + 3 "DELETE FROM t4 WHERE 0.0 ; SELECT x FROM t4" {1 2 3 4 5} + 4 "DELETE FROM t4 WHERE NULL ; SELECT x FROM t4" {1 2 3 4 5} + 5 "DELETE FROM t4 WHERE y!='two'; SELECT x FROM t4" {2} + 6 "DELETE FROM t4 WHERE y='two' ; SELECT x FROM t4" {} + 7 "DELETE FROM t5 WHERE x=(SELECT max(x) FROM t5);SELECT x FROM t5" {1 2 3 4} + 8 "DELETE FROM t5 WHERE (SELECT max(x) FROM t4) ;SELECT x FROM t5" {1 2 3 4} + 9 "DELETE FROM t5 WHERE (SELECT max(x) FROM t6) ;SELECT x FROM t5" {} + 10 "DELETE FROM t6 WHERE y>'seven' ; SELECT y FROM t6" {one four five} +} + + +#------------------------------------------------------------------------- +# Tests for restrictions on DELETE statements that appear within trigger +# programs. +# +forcedelete test.db2 +forcedelete test.db3 +do_execsql_test e_delete-2.0 { + ATTACH 'test.db2' AS aux; + ATTACH 'test.db3' AS aux2; + + CREATE TABLE temp.t7(a, b); INSERT INTO temp.t7 VALUES(1, 2); + CREATE TABLE main.t7(a, b); INSERT INTO main.t7 VALUES(3, 4); + CREATE TABLE aux.t7(a, b); INSERT INTO aux.t7 VALUES(5, 6); + CREATE TABLE aux2.t7(a, b); INSERT INTO aux2.t7 VALUES(7, 8); + + CREATE TABLE main.t8(a, b); INSERT INTO main.t8 VALUES(1, 2); + CREATE TABLE aux.t8(a, b); INSERT INTO aux.t8 VALUES(3, 4); + CREATE TABLE aux2.t8(a, b); INSERT INTO aux2.t8 VALUES(5, 6); + + CREATE TABLE aux.t9(a, b); INSERT INTO aux.t9 VALUES(1, 2); + CREATE TABLE aux2.t9(a, b); INSERT INTO aux2.t9 VALUES(3, 4); + + CREATE TABLE aux2.t10(a, b); INSERT INTO aux2.t10 VALUES(1, 2); +} {} + + +# EVIDENCE-OF: R-09681-58560 The table-name specified as part of a +# DELETE statement within a trigger body must be unqualified. +# +# EVIDENCE-OF: R-36771-43788 In other words, the database-name. prefix +# on the table name is not allowed within triggers. +# +do_delete_tests e_delete-2.1 -error { + qualified table names are not allowed on INSERT, UPDATE, and DELETE statements within triggers +} { + 1 { + CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN + DELETE FROM main.t2; + END; + } {} + + 2 { + CREATE TRIGGER tr1 BEFORE UPDATE ON t2 BEGIN + DELETE FROM temp.t7 WHERE a=new.a; + END; + } {} + + 3 { + CREATE TRIGGER tr1 AFTER UPDATE ON t8 BEGIN + DELETE FROM aux2.t8 WHERE b!=a; + END; + } {} +} + +# EVIDENCE-OF: R-28818-63526 If the table to which the trigger is +# attached is not in the temp database, then DELETE statements within +# the trigger body must operate on tables within the same database as +# it. +# +# This is tested in two parts. First, check that if a table of the +# specified name does not exist, an error is raised. Secondly, test +# that if tables with the specified name exist in multiple databases, +# the local database table is used. +# +do_delete_tests e_delete-2.2.1 -error { no such table: %s } { + 1 { + CREATE TRIGGER main.tr1 AFTER INSERT ON main.t7 BEGIN + DELETE FROM t9; + END; + INSERT INTO main.t7 VALUES(1, 2); + } {main.t9} + + 2 { + CREATE TRIGGER aux.tr2 BEFORE UPDATE ON t9 BEGIN + DELETE FROM t10; + END; + UPDATE t9 SET a=1; + } {aux.t10} +} +do_execsql_test e_delete-2.2.X { + DROP TRIGGER main.tr1; + DROP TRIGGER aux.tr2; +} {} + +do_delete_tests e_delete-2.2.2 { + 1 { + CREATE TRIGGER aux.tr1 AFTER INSERT ON t8 BEGIN + DELETE FROM t9; + END; + INSERT INTO aux.t8 VALUES(1, 2); + + SELECT count(*) FROM aux.t9 + UNION ALL + SELECT count(*) FROM aux2.t9; + } {0 1} + + 2 { + CREATE TRIGGER main.tr1 AFTER INSERT ON t8 BEGIN + DELETE FROM t7; + END; + INSERT INTO main.t8 VALUES(1, 2); + + SELECT count(*) FROM temp.t7 + UNION ALL + SELECT count(*) FROM main.t7 + UNION ALL + SELECT count(*) FROM aux.t7 + UNION ALL + SELECT count(*) FROM aux2.t7; + } {1 0 1 1} +} + +# EVIDENCE-OF: R-31567-38587 If the table to which the trigger is +# attached is in the TEMP database, then the unqualified name of the +# table being deleted is resolved in the same way as it is for a +# top-level statement (by searching first the TEMP database, then the +# main database, then any other databases in the order they were +# attached). +# +do_execsql_test e_delete-2.3.0 { + DROP TRIGGER aux.tr1; + DROP TRIGGER main.tr1; + DELETE FROM main.t8 WHERE oid>1; + DELETE FROM aux.t8 WHERE oid>1; + INSERT INTO aux.t9 VALUES(1, 2); + INSERT INTO main.t7 VALUES(3, 4); +} {} +do_execsql_test e_delete-2.3.1 { + SELECT count(*) FROM temp.t7 UNION ALL SELECT count(*) FROM main.t7 UNION ALL + SELECT count(*) FROM aux.t7 UNION ALL SELECT count(*) FROM aux2.t7; + + SELECT count(*) FROM main.t8 UNION ALL SELECT count(*) FROM aux.t8 + UNION ALL SELECT count(*) FROM aux2.t8; + + SELECT count(*) FROM aux.t9 UNION ALL SELECT count(*) FROM aux2.t9; + + SELECT count(*) FROM aux2.t10; +} {1 1 1 1 1 1 1 1 1 1} +do_execsql_test e_delete-2.3.2 { + CREATE TRIGGER temp.tr1 AFTER INSERT ON t7 BEGIN + DELETE FROM t7; + DELETE FROM t8; + DELETE FROM t9; + DELETE FROM t10; + END; + INSERT INTO temp.t7 VALUES('hello', 'world'); +} {} +do_execsql_test e_delete-2.3.3 { + SELECT count(*) FROM temp.t7 UNION ALL SELECT count(*) FROM main.t7 UNION ALL + SELECT count(*) FROM aux.t7 UNION ALL SELECT count(*) FROM aux2.t7; + + SELECT count(*) FROM main.t8 UNION ALL SELECT count(*) FROM aux.t8 + UNION ALL SELECT count(*) FROM aux2.t8; + + SELECT count(*) FROM aux.t9 UNION ALL SELECT count(*) FROM aux2.t9; + + SELECT count(*) FROM aux2.t10; +} {0 1 1 1 0 1 1 0 1 0} + +# EVIDENCE-OF: R-28691-49464 The INDEXED BY and NOT INDEXED clauses are +# not allowed on DELETE statements within triggers. +# +do_execsql_test e_delete-2.4.0 { + CREATE INDEX i8 ON t8(a, b); +} {} +do_delete_tests e_delete-2.4 -error { + the %s %s clause is not allowed on UPDATE or DELETE statements within triggers +} { + 1 { + CREATE TRIGGER tr3 AFTER INSERT ON t8 BEGIN + DELETE FROM t8 INDEXED BY i8 WHERE a=5; + END; + } {INDEXED BY} + 2 { + CREATE TRIGGER tr3 AFTER INSERT ON t8 BEGIN + DELETE FROM t8 NOT INDEXED WHERE a=5; + END; + } {NOT INDEXED} +} + +ifcapable update_delete_limit { + +# EVIDENCE-OF: R-64942-06615 The LIMIT and ORDER BY clauses (described +# below) are unsupported for DELETE statements within triggers. +# +do_delete_tests e_delete-2.5 -error { near "%s": syntax error } { + 1 { + CREATE TRIGGER tr3 AFTER INSERT ON t8 BEGIN + DELETE FROM t8 LIMIT 10; + END; + } {LIMIT} + 2 { + CREATE TRIGGER tr3 AFTER INSERT ON t8 BEGIN + DELETE FROM t8 ORDER BY a LIMIT 5; + END; + } {ORDER} +} + +# EVIDENCE-OF: R-40026-10531 If SQLite is compiled with the +# SQLITE_ENABLE_UPDATE_DELETE_LIMIT compile-time option, then the syntax +# of the DELETE statement is extended by the addition of optional ORDER +# BY and LIMIT clauses: +# +# -- syntax diagram delete-stmt-limited +# +do_delete_tests e_delete-3.1 { + 1 "DELETE FROM t1 LIMIT 5" {} + 2 "DELETE FROM t1 LIMIT 5-1 OFFSET 2+2" {} + 3 "DELETE FROM t1 LIMIT 2+2, 16/4" {} + 4 "DELETE FROM t1 ORDER BY x LIMIT 5" {} + 5 "DELETE FROM t1 ORDER BY x LIMIT 5-1 OFFSET 2+2" {} + 6 "DELETE FROM t1 ORDER BY x LIMIT 2+2, 16/4" {} + 7 "DELETE FROM t1 WHERE x>2 LIMIT 5" {} + 8 "DELETE FROM t1 WHERE x>2 LIMIT 5-1 OFFSET 2+2" {} + 9 "DELETE FROM t1 WHERE x>2 LIMIT 2+2, 16/4" {} + 10 "DELETE FROM t1 WHERE x>2 ORDER BY x LIMIT 5" {} + 11 "DELETE FROM t1 WHERE x>2 ORDER BY x LIMIT 5-1 OFFSET 2+2" {} + 12 "DELETE FROM t1 WHERE x>2 ORDER BY x LIMIT 2+2, 16/4" {} +} + +drop_all_tables +proc rebuild_t1 {} { + catchsql { DROP TABLE t1 } + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t1 VALUES(3, 'three'); + INSERT INTO t1 VALUES(4, 'four'); + INSERT INTO t1 VALUES(5, 'five'); + } +} + +# EVIDENCE-OF: R-44062-08550 If a DELETE statement has a LIMIT clause, +# the maximum number of rows that will be deleted is found by evaluating +# the accompanying expression and casting it to an integer value. +# +rebuild_t1 +do_delete_tests e_delete-3.2 -repair rebuild_t1 -query { + SELECT a FROM t1 +} { + 1 "DELETE FROM t1 LIMIT 3" {4 5} + 2 "DELETE FROM t1 LIMIT 1+1" {3 4 5} + 3 "DELETE FROM t1 LIMIT '4'" {5} + 4 "DELETE FROM t1 LIMIT '1.0'" {2 3 4 5} +} + +# EVIDENCE-OF: R-02661-56399 If the result of the evaluating the LIMIT +# clause cannot be losslessly converted to an integer value, it is an +# error. +# +do_delete_tests e_delete-3.3 -error { datatype mismatch } { + 1 "DELETE FROM t1 LIMIT 'abc'" {} + 2 "DELETE FROM t1 LIMIT NULL" {} + 3 "DELETE FROM t1 LIMIT X'ABCD'" {} + 4 "DELETE FROM t1 LIMIT 1.2" {} +} + +# EVIDENCE-OF: R-00598-03741 A negative LIMIT value is interpreted as +# "no limit". +# +do_delete_tests e_delete-3.4 -repair rebuild_t1 -query { + SELECT a FROM t1 +} { + 1 "DELETE FROM t1 LIMIT -1" {} + 2 "DELETE FROM t1 LIMIT 2-4" {} + 3 "DELETE FROM t1 LIMIT -4.0" {} + 4 "DELETE FROM t1 LIMIT 5*-1" {} +} + +# EVIDENCE-OF: R-26377-49195 If the DELETE statement also has an OFFSET +# clause, then it is similarly evaluated and cast to an integer value. +# Again, it is an error if the value cannot be losslessly converted to +# an integer. +# +do_delete_tests e_delete-3.5 -error { datatype mismatch } { + 1 "DELETE FROM t1 LIMIT 1 OFFSET 'abc'" {} + 2 "DELETE FROM t1 LIMIT 1 OFFSET NULL" {} + 3 "DELETE FROM t1 LIMIT 1 OFFSET X'ABCD'" {} + 4 "DELETE FROM t1 LIMIT 1 OFFSET 1.2" {} + 5 "DELETE FROM t1 LIMIT 'abc', 1" {} + 6 "DELETE FROM t1 LIMIT NULL, 1" {} + 7 "DELETE FROM t1 LIMIT X'ABCD', 1" {} + 8 "DELETE FROM t1 LIMIT 1.2, 1" {} +} + + +# EVIDENCE-OF: R-64004-53814 If there is no OFFSET clause, or the +# calculated integer value is negative, the effective OFFSET value is +# zero. +# +do_delete_tests e_delete-3.6 -repair rebuild_t1 -query { + SELECT a FROM t1 +} { + 1a "DELETE FROM t1 LIMIT 3 OFFSET 0" {4 5} + 1b "DELETE FROM t1 LIMIT 3" {4 5} + 1c "DELETE FROM t1 LIMIT 3 OFFSET -1" {4 5} + 2a "DELETE FROM t1 LIMIT 1+1 OFFSET 0" {3 4 5} + 2b "DELETE FROM t1 LIMIT 1+1" {3 4 5} + 2c "DELETE FROM t1 LIMIT 1+1 OFFSET 2-5" {3 4 5} + 3a "DELETE FROM t1 LIMIT '4' OFFSET 0" {5} + 3b "DELETE FROM t1 LIMIT '4'" {5} + 3c "DELETE FROM t1 LIMIT '4' OFFSET -1.0" {5} + 4a "DELETE FROM t1 LIMIT '1.0' OFFSET 0" {2 3 4 5} + 4b "DELETE FROM t1 LIMIT '1.0'" {2 3 4 5} + 4c "DELETE FROM t1 LIMIT '1.0' OFFSET -11" {2 3 4 5} +} + +# EVIDENCE-OF: R-48141-52334 If the DELETE statement has an ORDER BY +# clause, then all rows that would be deleted in the absence of the +# LIMIT clause are sorted according to the ORDER BY. The first M rows, +# where M is the value found by evaluating the OFFSET clause expression, +# are skipped, and the following N, where N is the value of the LIMIT +# expression, are deleted. +# +do_delete_tests e_delete-3.7 -repair rebuild_t1 -query { + SELECT a FROM t1 +} { + 1 "DELETE FROM t1 ORDER BY b LIMIT 2" {1 2 3} + 2 "DELETE FROM t1 ORDER BY length(b), a LIMIT 3" {3 5} + 3 "DELETE FROM t1 ORDER BY a DESC LIMIT 1 OFFSET 0" {1 2 3 4} + 4 "DELETE FROM t1 ORDER BY a DESC LIMIT 1 OFFSET 1" {1 2 3 5} + 5 "DELETE FROM t1 ORDER BY a DESC LIMIT 1 OFFSET 2" {1 2 4 5} +} + +# EVIDENCE-OF: R-64535-08414 If there are less than N rows remaining +# after taking the OFFSET clause into account, or if the LIMIT clause +# evaluated to a negative value, then all remaining rows are deleted. +# +do_delete_tests e_delete-3.8 -repair rebuild_t1 -query { + SELECT a FROM t1 +} { + 1 "DELETE FROM t1 ORDER BY a ASC LIMIT 10" {} + 2 "DELETE FROM t1 ORDER BY a ASC LIMIT -1" {} + 3 "DELETE FROM t1 ORDER BY a ASC LIMIT 4 OFFSET 2" {1 2} +} + +# EVIDENCE-OF: R-37284-06965 If the DELETE statement has no ORDER BY +# clause, then all rows that would be deleted in the absence of the +# LIMIT clause are assembled in an arbitrary order before applying the +# LIMIT and OFFSET clauses to determine the subset that are actually +# deleted. +# +# In practice, the "arbitrary order" is rowid order. +# +do_delete_tests e_delete-3.9 -repair rebuild_t1 -query { + SELECT a FROM t1 +} { + 1 "DELETE FROM t1 LIMIT 2" {3 4 5} + 2 "DELETE FROM t1 LIMIT 3" {4 5} + 3 "DELETE FROM t1 LIMIT 1 OFFSET 0" {2 3 4 5} + 4 "DELETE FROM t1 LIMIT 1 OFFSET 1" {1 3 4 5} + 5 "DELETE FROM t1 LIMIT 1 OFFSET 2" {1 2 4 5} +} + + +# EVIDENCE-OF: R-07548-13422 The ORDER BY clause on a DELETE statement +# is used only to determine which rows fall within the LIMIT. The order +# in which rows are deleted is arbitrary and is not influenced by the +# ORDER BY clause. +# +# In practice, rows are always deleted in rowid order. +# +do_delete_tests e_delete-3.10 -repair { + rebuild_t1 + catchsql { DROP TABLE t1log } + execsql { + CREATE TABLE t1log(x); + CREATE TRIGGER tr1 AFTER DELETE ON t1 BEGIN + INSERT INTO t1log VALUES(old.a); + END; + } +} -query { + SELECT x FROM t1log +} { + 1 "DELETE FROM t1 ORDER BY a DESC LIMIT 2" {4 5} + 2 "DELETE FROM t1 ORDER BY a DESC LIMIT -1" {1 2 3 4 5} + 3 "DELETE FROM t1 ORDER BY a ASC LIMIT 2" {1 2} + 4 "DELETE FROM t1 ORDER BY a ASC LIMIT -1" {1 2 3 4 5} +} + +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_droptrigger.test b/components/external/SQLite-3.8.1/test/e_droptrigger.test new file mode 100644 index 0000000000000000000000000000000000000000..84dfe7279a4a23fb9953947c920c7c23d0a5e6c2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_droptrigger.test @@ -0,0 +1,218 @@ +# 2010 November 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_droptrigger.html document are correct. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix e_droptrigger + +ifcapable !trigger { finish_test ; return } + +proc do_droptrigger_tests {nm args} { + uplevel do_select_tests [list e_createtable-$nm] $args +} + +proc list_all_triggers {{db db}} { + set res [list] + $db eval { PRAGMA database_list } { + if {$name == "temp"} { + set tbl sqlite_temp_master + } else { + set tbl "$name.sqlite_master" + } + lappend res {*}[ + db eval "SELECT '$name.' || name FROM $tbl WHERE type = 'trigger'" + ] + } + set res +} + + +proc droptrigger_reopen_db {{event INSERT}} { + db close + forcedelete test.db test.db2 + sqlite3 db test.db + + set ::triggers_fired [list] + proc r {x} { lappend ::triggers_fired $x } + db func r r + + db eval " + ATTACH 'test.db2' AS aux; + + CREATE TEMP TABLE t1(a, b); + INSERT INTO t1 VALUES('a', 'b'); + CREATE TRIGGER tr1 AFTER $event ON t1 BEGIN SELECT r('temp.tr1') ; END; + + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES('a', 'b'); + CREATE TRIGGER tr1 BEFORE $event ON t2 BEGIN SELECT r('main.tr1') ; END; + CREATE TRIGGER tr2 AFTER $event ON t2 BEGIN SELECT r('main.tr2') ; END; + + CREATE TABLE aux.t3(a, b); + INSERT INTO t3 VALUES('a', 'b'); + CREATE TRIGGER aux.tr1 BEFORE $event ON t3 BEGIN SELECT r('aux.tr1') ; END; + CREATE TRIGGER aux.tr2 AFTER $event ON t3 BEGIN SELECT r('aux.tr2') ; END; + CREATE TRIGGER aux.tr3 AFTER $event ON t3 BEGIN SELECT r('aux.tr3') ; END; + " +} + + +# -- syntax diagram drop-trigger-stmt +# +do_droptrigger_tests 1.1 -repair { + droptrigger_reopen_db +} -tclquery { + list_all_triggers +} { + 1 "DROP TRIGGER main.tr1" + {main.tr2 temp.tr1 aux.tr1 aux.tr2 aux.tr3} + 2 "DROP TRIGGER IF EXISTS main.tr1" + {main.tr2 temp.tr1 aux.tr1 aux.tr2 aux.tr3} + 3 "DROP TRIGGER tr1" + {main.tr1 main.tr2 aux.tr1 aux.tr2 aux.tr3} + 4 "DROP TRIGGER IF EXISTS tr1" + {main.tr1 main.tr2 aux.tr1 aux.tr2 aux.tr3} + + 5 "DROP TRIGGER aux.tr1" + {main.tr1 main.tr2 temp.tr1 aux.tr2 aux.tr3} + 6 "DROP TRIGGER IF EXISTS aux.tr1" + {main.tr1 main.tr2 temp.tr1 aux.tr2 aux.tr3} + + 7 "DROP TRIGGER IF EXISTS aux.xxx" + {main.tr1 main.tr2 temp.tr1 aux.tr1 aux.tr2 aux.tr3} + 8 "DROP TRIGGER IF EXISTS aux.xxx" + {main.tr1 main.tr2 temp.tr1 aux.tr1 aux.tr2 aux.tr3} +} + +# EVIDENCE-OF: R-61172-15671 The DROP TRIGGER statement removes a +# trigger created by the CREATE TRIGGER statement. +# +foreach {tn tbl droptrigger before after} { + 1 t1 "DROP TRIGGER tr1" {temp.tr1} {} + 2 t2 "DROP TRIGGER tr1" {main.tr1 main.tr2} {main.tr1 main.tr2} + 3 t3 "DROP TRIGGER tr1" {aux.tr1 aux.tr3 aux.tr2} {aux.tr1 aux.tr3 aux.tr2} + + 4 t1 "DROP TRIGGER tr2" {temp.tr1} {temp.tr1} + 5 t2 "DROP TRIGGER tr2" {main.tr1 main.tr2} {main.tr1} + 6 t3 "DROP TRIGGER tr2" {aux.tr1 aux.tr3 aux.tr2} {aux.tr1 aux.tr3 aux.tr2} + + 7 t1 "DROP TRIGGER tr3" {temp.tr1} {temp.tr1} + 8 t2 "DROP TRIGGER tr3" {main.tr1 main.tr2} {main.tr1 main.tr2} + 9 t3 "DROP TRIGGER tr3" {aux.tr1 aux.tr3 aux.tr2} {aux.tr1 aux.tr2} +} { + + do_test 2.$tn.1 { + droptrigger_reopen_db + execsql " INSERT INTO $tbl VALUES('1', '2') " + set ::triggers_fired + } $before + + do_test 2.$tn.2 { + droptrigger_reopen_db + execsql $droptrigger + execsql " INSERT INTO $tbl VALUES('1', '2') " + set ::triggers_fired + } $after +} + +# EVIDENCE-OF: R-50239-29811 Once removed, the trigger definition is no +# longer present in the sqlite_master (or sqlite_temp_master) table and +# is not fired by any subsequent INSERT, UPDATE or DELETE statements. +# +# Test cases e_droptrigger-1.* test the first part of this statement +# (that dropped triggers do not appear in the schema table), and tests +# droptrigger-2.* test that dropped triggers are not fired by INSERT +# statements. The following tests verify that they are not fired by +# UPDATE or DELETE statements. +# +foreach {tn tbl droptrigger before after} { + 1 t1 "DROP TRIGGER tr1" {temp.tr1} {} + 2 t2 "DROP TRIGGER tr1" {main.tr1 main.tr2} {main.tr1 main.tr2} + 3 t3 "DROP TRIGGER tr1" {aux.tr1 aux.tr3 aux.tr2} {aux.tr1 aux.tr3 aux.tr2} + + 4 t1 "DROP TRIGGER tr2" {temp.tr1} {temp.tr1} + 5 t2 "DROP TRIGGER tr2" {main.tr1 main.tr2} {main.tr1} + 6 t3 "DROP TRIGGER tr2" {aux.tr1 aux.tr3 aux.tr2} {aux.tr1 aux.tr3 aux.tr2} + + 7 t1 "DROP TRIGGER tr3" {temp.tr1} {temp.tr1} + 8 t2 "DROP TRIGGER tr3" {main.tr1 main.tr2} {main.tr1 main.tr2} + 9 t3 "DROP TRIGGER tr3" {aux.tr1 aux.tr3 aux.tr2} {aux.tr1 aux.tr2} +} { + + do_test 3.1.$tn.1 { + droptrigger_reopen_db UPDATE + execsql "UPDATE $tbl SET a = 'abc'" + set ::triggers_fired + } $before + + do_test 3.1.$tn.2 { + droptrigger_reopen_db UPDATE + execsql $droptrigger + execsql "UPDATE $tbl SET a = 'abc'" + set ::triggers_fired + } $after +} +foreach {tn tbl droptrigger before after} { + 1 t1 "DROP TRIGGER tr1" {temp.tr1} {} + 2 t2 "DROP TRIGGER tr1" {main.tr1 main.tr2} {main.tr1 main.tr2} + 3 t3 "DROP TRIGGER tr1" {aux.tr1 aux.tr3 aux.tr2} {aux.tr1 aux.tr3 aux.tr2} + + 4 t1 "DROP TRIGGER tr2" {temp.tr1} {temp.tr1} + 5 t2 "DROP TRIGGER tr2" {main.tr1 main.tr2} {main.tr1} + 6 t3 "DROP TRIGGER tr2" {aux.tr1 aux.tr3 aux.tr2} {aux.tr1 aux.tr3 aux.tr2} + + 7 t1 "DROP TRIGGER tr3" {temp.tr1} {temp.tr1} + 8 t2 "DROP TRIGGER tr3" {main.tr1 main.tr2} {main.tr1 main.tr2} + 9 t3 "DROP TRIGGER tr3" {aux.tr1 aux.tr3 aux.tr2} {aux.tr1 aux.tr2} +} { + + do_test 3.2.$tn.1 { + droptrigger_reopen_db DELETE + execsql "DELETE FROM $tbl" + set ::triggers_fired + } $before + + do_test 3.2.$tn.2 { + droptrigger_reopen_db DELETE + execsql $droptrigger + execsql "DELETE FROM $tbl" + set ::triggers_fired + } $after +} + +# EVIDENCE-OF: R-37808-62273 Note that triggers are automatically +# dropped when the associated table is dropped. +# +do_test 4.1 { + droptrigger_reopen_db + list_all_triggers +} {main.tr1 main.tr2 temp.tr1 aux.tr1 aux.tr2 aux.tr3} +do_test 4.2 { + droptrigger_reopen_db + execsql "DROP TABLE t1" + list_all_triggers +} {main.tr1 main.tr2 aux.tr1 aux.tr2 aux.tr3} +do_test 4.3 { + droptrigger_reopen_db + execsql "DROP TABLE t1" + list_all_triggers +} {main.tr1 main.tr2 aux.tr1 aux.tr2 aux.tr3} +do_test 4.4 { + droptrigger_reopen_db + execsql "DROP TABLE t1" + list_all_triggers +} {main.tr1 main.tr2 aux.tr1 aux.tr2 aux.tr3} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_dropview.test b/components/external/SQLite-3.8.1/test/e_dropview.test new file mode 100644 index 0000000000000000000000000000000000000000..143dce2907d1ffc1338f65b9cfbc5205653d4fe2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_dropview.test @@ -0,0 +1,192 @@ +# 2010 November 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_dropview.html document are correct. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix e_dropview + +proc dropview_reopen_db {} { + db close + forcedelete test.db test.db2 + sqlite3 db test.db + + db eval { + ATTACH 'test.db2' AS aux; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('a main', 'b main'); + CREATE VIEW v1 AS SELECT * FROM t1; + CREATE VIEW v2 AS SELECT * FROM t1; + + CREATE TEMP TABLE t1(a, b); + INSERT INTO temp.t1 VALUES('a temp', 'b temp'); + CREATE VIEW temp.v1 AS SELECT * FROM t1; + + CREATE TABLE aux.t1(a, b); + INSERT INTO aux.t1 VALUES('a aux', 'b aux'); + CREATE VIEW aux.v1 AS SELECT * FROM t1; + CREATE VIEW aux.v2 AS SELECT * FROM t1; + CREATE VIEW aux.v3 AS SELECT * FROM t1; + } +} + +proc list_all_views {{db db}} { + set res [list] + $db eval { PRAGMA database_list } { + set tbl "$name.sqlite_master" + if {$name == "temp"} { set tbl sqlite_temp_master } + + set sql "SELECT '$name.' || name FROM $tbl WHERE type = 'view'" + lappend res {*}[$db eval $sql] + } + set res +} + +proc list_all_data {{db db}} { + set res [list] + $db eval { PRAGMA database_list } { + set tbl "$name.sqlite_master" + if {$name == "temp"} { set tbl sqlite_temp_master } + + db eval "SELECT '$name.' || name AS x FROM $tbl WHERE type = 'table'" { + lappend res [list $x [db eval "SELECT * FROM $x"]] + } + } + set res +} + +proc do_dropview_tests {nm args} { + uplevel do_select_tests $nm $args +} + +# -- syntax diagram drop-view-stmt +# +# All paths in the syntax diagram for DROP VIEW are tested by tests 1.*. +# +do_dropview_tests 1 -repair { + dropview_reopen_db +} -tclquery { + list_all_views +} { + 1 "DROP VIEW v1" {main.v1 main.v2 aux.v1 aux.v2 aux.v3} + 2 "DROP VIEW v2" {main.v1 temp.v1 aux.v1 aux.v2 aux.v3} + 3 "DROP VIEW main.v1" {main.v2 temp.v1 aux.v1 aux.v2 aux.v3} + 4 "DROP VIEW main.v2" {main.v1 temp.v1 aux.v1 aux.v2 aux.v3} + 5 "DROP VIEW IF EXISTS v1" {main.v1 main.v2 aux.v1 aux.v2 aux.v3} + 6 "DROP VIEW IF EXISTS v2" {main.v1 temp.v1 aux.v1 aux.v2 aux.v3} + 7 "DROP VIEW IF EXISTS main.v1" {main.v2 temp.v1 aux.v1 aux.v2 aux.v3} + 8 "DROP VIEW IF EXISTS main.v2" {main.v1 temp.v1 aux.v1 aux.v2 aux.v3} +} + +# EVIDENCE-OF: R-27002-52307 The DROP VIEW statement removes a view +# created by the CREATE VIEW statement. +# +dropview_reopen_db +do_execsql_test 2.1 { + CREATE VIEW "new view" AS SELECT * FROM t1 AS x, t1 AS y; + SELECT * FROM "new view"; +} {{a main} {b main} {a main} {b main}} +do_execsql_test 2.2 {; + SELECT * FROM sqlite_master WHERE name = 'new view'; +} { + view {new view} {new view} 0 + {CREATE VIEW "new view" AS SELECT * FROM t1 AS x, t1 AS y} +} +do_execsql_test 2.3 { + DROP VIEW "new view"; + SELECT * FROM sqlite_master WHERE name = 'new view'; +} {} +do_catchsql_test 2.4 { + SELECT * FROM "new view" +} {1 {no such table: new view}} + +# EVIDENCE-OF: R-00359-41639 The view definition is removed from the +# database schema, but no actual data in the underlying base tables is +# modified. +# +# For each view in the database, check that it can be queried. Then drop +# it. Check that it can no longer be queried and is no longer listed +# in any schema table. Then check that the contents of the db tables have +# not changed +# +set databasedata [list_all_data] + +do_execsql_test 3.1.0 { SELECT * FROM temp.v1 } {{a temp} {b temp}} +do_execsql_test 3.1.1 { DROP VIEW temp.v1 } {} +do_catchsql_test 3.1.2 { SELECT * FROM temp.v1 } {1 {no such table: temp.v1}} +do_test 3.1.3 { list_all_views } {main.v1 main.v2 aux.v1 aux.v2 aux.v3} +do_test 3.1.4 { list_all_data } $databasedata + +do_execsql_test 3.2.0 { SELECT * FROM v1 } {{a main} {b main}} +do_execsql_test 3.2.1 { DROP VIEW v1 } {} +do_catchsql_test 3.2.2 { SELECT * FROM main.v1 } {1 {no such table: main.v1}} +do_test 3.2.3 { list_all_views } {main.v2 aux.v1 aux.v2 aux.v3} +do_test 3.2.4 { list_all_data } $databasedata + +do_execsql_test 3.3.0 { SELECT * FROM v2 } {{a main} {b main}} +do_execsql_test 3.3.1 { DROP VIEW v2 } {} +do_catchsql_test 3.3.2 { SELECT * FROM main.v2 } {1 {no such table: main.v2}} +do_test 3.3.3 { list_all_views } {aux.v1 aux.v2 aux.v3} +do_test 3.3.4 { list_all_data } $databasedata + +do_execsql_test 3.4.0 { SELECT * FROM v1 } {{a aux} {b aux}} +do_execsql_test 3.4.1 { DROP VIEW v1 } {} +do_catchsql_test 3.4.2 { SELECT * FROM v1 } {1 {no such table: v1}} +do_test 3.4.3 { list_all_views } {aux.v2 aux.v3} +do_test 3.4.4 { list_all_data } $databasedata + +do_execsql_test 3.4.0 { SELECT * FROM aux.v2 } {{a aux} {b aux}} +do_execsql_test 3.4.1 { DROP VIEW aux.v2 } {} +do_catchsql_test 3.4.2 { SELECT * FROM aux.v2 } {1 {no such table: aux.v2}} +do_test 3.4.3 { list_all_views } {aux.v3} +do_test 3.4.4 { list_all_data } $databasedata + +do_execsql_test 3.5.0 { SELECT * FROM v3 } {{a aux} {b aux}} +do_execsql_test 3.5.1 { DROP VIEW v3 } {} +do_catchsql_test 3.5.2 { SELECT * FROM v3 } {1 {no such table: v3}} +do_test 3.5.3 { list_all_views } {} +do_test 3.5.4 { list_all_data } $databasedata + +# EVIDENCE-OF: R-25558-37487 If the specified view cannot be found and +# the IF EXISTS clause is not present, it is an error. +# +do_dropview_tests 4 -repair { + dropview_reopen_db +} -errorformat { + no such view: %s +} { + 1 "DROP VIEW xx" xx + 2 "DROP VIEW main.xx" main.xx + 3 "DROP VIEW temp.v2" temp.v2 +} + +# EVIDENCE-OF: R-07490-32536 If the specified view cannot be found and +# an IF EXISTS clause is present in the DROP VIEW statement, then the +# statement is a no-op. +# +do_dropview_tests 5 -repair { + dropview_reopen_db +} -tclquery { + list_all_views + expr {[list_all_views] == "main.v1 main.v2 temp.v1 aux.v1 aux.v2 aux.v3"} +} { + 1 "DROP VIEW IF EXISTS xx" 1 + 2 "DROP VIEW IF EXISTS main.xx" 1 + 3 "DROP VIEW IF EXISTS temp.v2" 1 +} + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_expr.test b/components/external/SQLite-3.8.1/test/e_expr.test new file mode 100644 index 0000000000000000000000000000000000000000..f0705757ac14ce1aed4b0c9498e202b5280d5210 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_expr.test @@ -0,0 +1,1851 @@ +# 2010 July 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_expr.html document are correct. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +ifcapable !compound { + finish_test + return +} + +proc do_expr_test {tn expr type value} { + uplevel do_execsql_test $tn [list "SELECT typeof($expr), $expr"] [ + list [list $type $value] + ] +} + +proc do_qexpr_test {tn expr value} { + uplevel do_execsql_test $tn [list "SELECT quote($expr)"] [list $value] +} + +# Set up three global variables: +# +# ::opname An array mapping from SQL operator to an easy to parse +# name. The names are used as part of test case names. +# +# ::opprec An array mapping from SQL operator to a numeric +# precedence value. Operators that group more tightly +# have lower numeric precedences. +# +# ::oplist A list of all SQL operators supported by SQLite. +# +foreach {op opn} { + || cat * mul / div % mod + add + - sub << lshift >> rshift & bitand | bitor + < less <= lesseq > more >= moreeq = eq1 + == eq2 <> ne1 != ne2 IS is LIKE like + GLOB glob AND and OR or MATCH match REGEXP regexp + {IS NOT} isnt +} { + set ::opname($op) $opn +} +set oplist [list] +foreach {prec opl} { + 1 || + 2 {* / %} + 3 {+ -} + 4 {<< >> & |} + 5 {< <= > >=} + 6 {= == != <> IS {IS NOT} LIKE GLOB MATCH REGEXP} + 7 AND + 8 OR +} { + foreach op $opl { + set ::opprec($op) $prec + lappend oplist $op + } +} + + +# Hook in definitions of MATCH and REGEX. The following implementations +# cause MATCH and REGEX to behave similarly to the == operator. +# +proc matchfunc {a b} { return [expr {$a==$b}] } +proc regexfunc {a b} { return [expr {$a==$b}] } +db func match -argcount 2 matchfunc +db func regexp -argcount 2 regexfunc + +#------------------------------------------------------------------------- +# Test cases e_expr-1.* attempt to verify that all binary operators listed +# in the documentation exist and that the relative precedences of the +# operators are also as the documentation suggests. +# +# EVIDENCE-OF: R-15514-65163 SQLite understands the following binary +# operators, in order from highest to lowest precedence: || * / % + - +# << >> & | < <= > >= = == != <> IS IS +# NOT IN LIKE GLOB MATCH REGEXP AND OR +# +# EVIDENCE-OF: R-38759-38789 Operators IS and IS NOT have the same +# precedence as =. +# + +unset -nocomplain untested +foreach op1 $oplist { + foreach op2 $oplist { + set untested($op1,$op2) 1 + foreach {tn A B C} { + 1 22 45 66 + 2 0 0 0 + 3 0 0 1 + 4 0 1 0 + 5 0 1 1 + 6 1 0 0 + 7 1 0 1 + 8 1 1 0 + 9 1 1 1 + 10 5 6 1 + 11 1 5 6 + 12 1 5 5 + 13 5 5 1 + + 14 5 2 1 + 15 1 4 1 + 16 -1 0 1 + 17 0 1 -1 + + } { + set testname "e_expr-1.$opname($op1).$opname($op2).$tn" + + # If $op2 groups more tightly than $op1, then the result + # of executing $sql1 whould be the same as executing $sql3. + # If $op1 groups more tightly, or if $op1 and $op2 have + # the same precedence, then executing $sql1 should return + # the same value as $sql2. + # + set sql1 "SELECT $A $op1 $B $op2 $C" + set sql2 "SELECT ($A $op1 $B) $op2 $C" + set sql3 "SELECT $A $op1 ($B $op2 $C)" + + set a2 [db one $sql2] + set a3 [db one $sql3] + + do_execsql_test $testname $sql1 [list [ + if {$opprec($op2) < $opprec($op1)} {set a3} {set a2} + ]] + if {$a2 != $a3} { unset -nocomplain untested($op1,$op2) } + } + } +} + +foreach op {* AND OR + || & |} { unset untested($op,$op) } +unset untested(+,-) ;# Since (a+b)-c == a+(b-c) +unset untested(*,<<) ;# Since (a*b)< work as the not-equals operator. +# +# EVIDENCE-OF: R-03679-60639 Equals can be either = or ==. +# +# EVIDENCE-OF: R-30082-38996 The non-equals operator can be either != or +# <>. +# +foreach {tn literal different} { + 1 'helloworld' '12345' + 2 22 23 + 3 'xyz' X'78797A' + 4 X'78797A00' 'xyz' +} { + do_execsql_test e_expr-4.$tn " + SELECT $literal = $literal, $literal == $literal, + $literal = $different, $literal == $different, + $literal = NULL, $literal == NULL, + $literal != $literal, $literal <> $literal, + $literal != $different, $literal <> $different, + $literal != NULL, $literal != NULL + + " {1 1 0 0 {} {} 0 0 1 1 {} {}} +} + +#------------------------------------------------------------------------- +# Test the || operator. +# +# EVIDENCE-OF: R-44409-62641 The || operator is "concatenate" - it joins +# together the two strings of its operands. +# +foreach {tn a b} { + 1 'helloworld' '12345' + 2 22 23 +} { + set as [db one "SELECT $a"] + set bs [db one "SELECT $b"] + + do_execsql_test e_expr-5.$tn "SELECT $a || $b" [list "${as}${bs}"] +} + +#------------------------------------------------------------------------- +# Test the % operator. +# +# EVIDENCE-OF: R-08914-63790 The operator % outputs the value of its +# left operand modulo its right operand. +# +do_execsql_test e_expr-6.1 {SELECT 72%5} {2} +do_execsql_test e_expr-6.2 {SELECT 72%-5} {2} +do_execsql_test e_expr-6.3 {SELECT -72%-5} {-2} +do_execsql_test e_expr-6.4 {SELECT -72%5} {-2} + +#------------------------------------------------------------------------- +# Test that the results of all binary operators are either numeric or +# NULL, except for the || operator, which may evaluate to either a text +# value or NULL. +# +# EVIDENCE-OF: R-20665-17792 The result of any binary operator is either +# a numeric value or NULL, except for the || concatenation operator +# which always evaluates to either NULL or a text value. +# +set literals { + 1 'abc' 2 'hexadecimal' 3 '' + 4 123 5 -123 6 0 + 7 123.4 8 0.0 9 -123.4 + 10 X'ABCDEF' 11 X'' 12 X'0000' + 13 NULL +} +foreach op $oplist { + foreach {n1 rhs} $literals { + foreach {n2 lhs} $literals { + + set t [db one " SELECT typeof($lhs $op $rhs) "] + do_test e_expr-7.$opname($op).$n1.$n2 { + expr { + ($op=="||" && ($t == "text" || $t == "null")) + || ($op!="||" && ($t == "integer" || $t == "real" || $t == "null")) + } + } 1 + + }} +} + +#------------------------------------------------------------------------- +# Test the IS and IS NOT operators. +# +# EVIDENCE-OF: R-24731-45773 The IS and IS NOT operators work like = and +# != except when one or both of the operands are NULL. +# +# EVIDENCE-OF: R-06325-15315 In this case, if both operands are NULL, +# then the IS operator evaluates to 1 (true) and the IS NOT operator +# evaluates to 0 (false). +# +# EVIDENCE-OF: R-19812-36779 If one operand is NULL and the other is +# not, then the IS operator evaluates to 0 (false) and the IS NOT +# operator is 1 (true). +# +# EVIDENCE-OF: R-61975-13410 It is not possible for an IS or IS NOT +# expression to evaluate to NULL. +# +do_execsql_test e_expr-8.1.1 { SELECT NULL IS NULL } {1} +do_execsql_test e_expr-8.1.2 { SELECT 'ab' IS NULL } {0} +do_execsql_test e_expr-8.1.3 { SELECT NULL IS 'ab' } {0} +do_execsql_test e_expr-8.1.4 { SELECT 'ab' IS 'ab' } {1} +do_execsql_test e_expr-8.1.5 { SELECT NULL == NULL } {{}} +do_execsql_test e_expr-8.1.6 { SELECT 'ab' == NULL } {{}} +do_execsql_test e_expr-8.1.7 { SELECT NULL == 'ab' } {{}} +do_execsql_test e_expr-8.1.8 { SELECT 'ab' == 'ab' } {1} +do_execsql_test e_expr-8.1.9 { SELECT NULL IS NOT NULL } {0} +do_execsql_test e_expr-8.1.10 { SELECT 'ab' IS NOT NULL } {1} +do_execsql_test e_expr-8.1.11 { SELECT NULL IS NOT 'ab' } {1} +do_execsql_test e_expr-8.1.12 { SELECT 'ab' IS NOT 'ab' } {0} +do_execsql_test e_expr-8.1.13 { SELECT NULL != NULL } {{}} +do_execsql_test e_expr-8.1.14 { SELECT 'ab' != NULL } {{}} +do_execsql_test e_expr-8.1.15 { SELECT NULL != 'ab' } {{}} +do_execsql_test e_expr-8.1.16 { SELECT 'ab' != 'ab' } {0} + +foreach {n1 rhs} $literals { + foreach {n2 lhs} $literals { + if {$rhs!="NULL" && $lhs!="NULL"} { + set eq [execsql "SELECT $lhs = $rhs, $lhs != $rhs"] + } else { + set eq [list [expr {$lhs=="NULL" && $rhs=="NULL"}] \ + [expr {$lhs!="NULL" || $rhs!="NULL"}] + ] + } + set test e_expr-8.2.$n1.$n2 + do_execsql_test $test.1 "SELECT $lhs IS $rhs, $lhs IS NOT $rhs" $eq + do_execsql_test $test.2 " + SELECT ($lhs IS $rhs) IS NULL, ($lhs IS NOT $rhs) IS NULL + " {0 0} + } +} + +#------------------------------------------------------------------------- +# Run some tests on the COLLATE "unary postfix operator". +# +# This collation sequence reverses both arguments before using +# [string compare] to compare them. For example, when comparing the +# strings 'one' and 'four', return the result of: +# +# string compare eno ruof +# +proc reverse_str {zStr} { + set out "" + foreach c [split $zStr {}] { set out "${c}${out}" } + set out +} +proc reverse_collate {zLeft zRight} { + string compare [reverse_str $zLeft] [reverse_str $zRight] +} +db collate reverse reverse_collate + +# EVIDENCE-OF: R-59577-33471 The COLLATE operator is a unary postfix +# operator that assigns a collating sequence to an expression. +# +# EVIDENCE-OF: R-36231-30731 The COLLATE operator has a higher +# precedence (binds more tightly) than any binary operator and any unary +# prefix operator except "~". +# +do_execsql_test e_expr-9.1 { SELECT 'abcd' < 'bbbb' COLLATE reverse } 0 +do_execsql_test e_expr-9.2 { SELECT ('abcd' < 'bbbb') COLLATE reverse } 1 +do_execsql_test e_expr-9.3 { SELECT 'abcd' <= 'bbbb' COLLATE reverse } 0 +do_execsql_test e_expr-9.4 { SELECT ('abcd' <= 'bbbb') COLLATE reverse } 1 + +do_execsql_test e_expr-9.5 { SELECT 'abcd' > 'bbbb' COLLATE reverse } 1 +do_execsql_test e_expr-9.6 { SELECT ('abcd' > 'bbbb') COLLATE reverse } 0 +do_execsql_test e_expr-9.7 { SELECT 'abcd' >= 'bbbb' COLLATE reverse } 1 +do_execsql_test e_expr-9.8 { SELECT ('abcd' >= 'bbbb') COLLATE reverse } 0 + +do_execsql_test e_expr-9.10 { SELECT 'abcd' = 'ABCD' COLLATE nocase } 1 +do_execsql_test e_expr-9.11 { SELECT ('abcd' = 'ABCD') COLLATE nocase } 0 +do_execsql_test e_expr-9.12 { SELECT 'abcd' == 'ABCD' COLLATE nocase } 1 +do_execsql_test e_expr-9.13 { SELECT ('abcd' == 'ABCD') COLLATE nocase } 0 +do_execsql_test e_expr-9.14 { SELECT 'abcd' IS 'ABCD' COLLATE nocase } 1 +do_execsql_test e_expr-9.15 { SELECT ('abcd' IS 'ABCD') COLLATE nocase } 0 + +do_execsql_test e_expr-9.16 { SELECT 'abcd' != 'ABCD' COLLATE nocase } 0 +do_execsql_test e_expr-9.17 { SELECT ('abcd' != 'ABCD') COLLATE nocase } 1 +do_execsql_test e_expr-9.18 { SELECT 'abcd' <> 'ABCD' COLLATE nocase } 0 +do_execsql_test e_expr-9.19 { SELECT ('abcd' <> 'ABCD') COLLATE nocase } 1 +do_execsql_test e_expr-9.20 { SELECT 'abcd' IS NOT 'ABCD' COLLATE nocase } 0 +do_execsql_test e_expr-9.21 { SELECT ('abcd' IS NOT 'ABCD') COLLATE nocase } 1 + +do_execsql_test e_expr-9.22 { + SELECT 'bbb' BETWEEN 'AAA' AND 'CCC' COLLATE nocase +} 1 +do_execsql_test e_expr-9.23 { + SELECT ('bbb' BETWEEN 'AAA' AND 'CCC') COLLATE nocase +} 0 + +# EVIDENCE-OF: R-58731-25439 The collating sequence set by the COLLATE +# operator overrides the collating sequence determined by the COLLATE +# clause in a table column definition. +# +do_execsql_test e_expr-9.24 { + CREATE TABLE t24(a COLLATE NOCASE, b); + INSERT INTO t24 VALUES('aaa', 1); + INSERT INTO t24 VALUES('bbb', 2); + INSERT INTO t24 VALUES('ccc', 3); +} {} +do_execsql_test e_expr-9.25 { SELECT 'BBB' = a FROM t24 } {0 1 0} +do_execsql_test e_expr-9.25 { SELECT a = 'BBB' FROM t24 } {0 1 0} +do_execsql_test e_expr-9.25 { SELECT 'BBB' = a COLLATE binary FROM t24 } {0 0 0} +do_execsql_test e_expr-9.25 { SELECT a COLLATE binary = 'BBB' FROM t24 } {0 0 0} + +#------------------------------------------------------------------------- +# Test statements related to literal values. +# +# EVIDENCE-OF: R-31536-32008 Literal values may be integers, floating +# point numbers, strings, BLOBs, or NULLs. +# +do_execsql_test e_expr-10.1.1 { SELECT typeof(5) } {integer} +do_execsql_test e_expr-10.1.2 { SELECT typeof(5.1) } {real} +do_execsql_test e_expr-10.1.3 { SELECT typeof('5.1') } {text} +do_execsql_test e_expr-10.1.4 { SELECT typeof(X'ABCD') } {blob} +do_execsql_test e_expr-10.1.5 { SELECT typeof(NULL) } {null} + +# "Scientific notation is supported for point literal values." +# +do_execsql_test e_expr-10.2.1 { SELECT typeof(3.4e-02) } {real} +do_execsql_test e_expr-10.2.2 { SELECT typeof(3e+5) } {real} +do_execsql_test e_expr-10.2.3 { SELECT 3.4e-02 } {0.034} +do_execsql_test e_expr-10.2.4 { SELECT 3e+4 } {30000.0} + +# EVIDENCE-OF: R-35229-17830 A string constant is formed by enclosing +# the string in single quotes ('). +# +# EVIDENCE-OF: R-07100-06606 A single quote within the string can be +# encoded by putting two single quotes in a row - as in Pascal. +# +do_execsql_test e_expr-10.3.1 { SELECT 'is not' } {{is not}} +do_execsql_test e_expr-10.3.2 { SELECT typeof('is not') } {text} +do_execsql_test e_expr-10.3.3 { SELECT 'isn''t' } {isn't} +do_execsql_test e_expr-10.3.4 { SELECT typeof('isn''t') } {text} + +# EVIDENCE-OF: R-09593-03321 BLOB literals are string literals +# containing hexadecimal data and preceded by a single "x" or "X" +# character. +# +# EVIDENCE-OF: R-39344-59787 For example: X'53514C697465' +# +do_execsql_test e_expr-10.4.1 { SELECT typeof(X'0123456789ABCDEF') } blob +do_execsql_test e_expr-10.4.2 { SELECT typeof(x'0123456789ABCDEF') } blob +do_execsql_test e_expr-10.4.3 { SELECT typeof(X'0123456789abcdef') } blob +do_execsql_test e_expr-10.4.4 { SELECT typeof(x'0123456789abcdef') } blob +do_execsql_test e_expr-10.4.5 { SELECT typeof(X'53514C697465') } blob + +# EVIDENCE-OF: R-23914-51476 A literal value can also be the token +# "NULL". +# +do_execsql_test e_expr-10.5.1 { SELECT NULL } {{}} +do_execsql_test e_expr-10.5.2 { SELECT typeof(NULL) } {null} + +#------------------------------------------------------------------------- +# Test statements related to bound parameters +# + +proc parameter_test {tn sql params result} { + set stmt [sqlite3_prepare_v2 db $sql -1] + + foreach {number name} $params { + set nm [sqlite3_bind_parameter_name $stmt $number] + do_test $tn.name.$number [list set {} $nm] $name + sqlite3_bind_int $stmt $number [expr -1 * $number] + } + + sqlite3_step $stmt + + set res [list] + for {set i 0} {$i < [sqlite3_column_count $stmt]} {incr i} { + lappend res [sqlite3_column_text $stmt $i] + } + + set rc [sqlite3_finalize $stmt] + do_test $tn.rc [list set {} $rc] SQLITE_OK + do_test $tn.res [list set {} $res] $result +} + +# EVIDENCE-OF: R-33509-39458 A question mark followed by a number NNN +# holds a spot for the NNN-th parameter. NNN must be between 1 and +# SQLITE_MAX_VARIABLE_NUMBER. +# +set mvn $SQLITE_MAX_VARIABLE_NUMBER +parameter_test e_expr-11.1 " + SELECT ?1, ?123, ?$SQLITE_MAX_VARIABLE_NUMBER, ?123, ?4 +" "1 ?1 123 ?123 $mvn ?$mvn 4 ?4" "-1 -123 -$mvn -123 -4" + +set errmsg "variable number must be between ?1 and ?$SQLITE_MAX_VARIABLE_NUMBER" +foreach {tn param_number} [list \ + 2 0 \ + 3 [expr $SQLITE_MAX_VARIABLE_NUMBER+1] \ + 4 [expr $SQLITE_MAX_VARIABLE_NUMBER+2] \ + 5 12345678903456789034567890234567890 \ + 6 2147483648 \ + 7 2147483649 \ + 8 4294967296 \ + 9 4294967297 \ + 10 9223372036854775808 \ + 11 9223372036854775809 \ + 12 18446744073709551616 \ + 13 18446744073709551617 \ +] { + do_catchsql_test e_expr-11.1.$tn "SELECT ?$param_number" [list 1 $errmsg] +} + +# EVIDENCE-OF: R-33670-36097 A question mark that is not followed by a +# number creates a parameter with a number one greater than the largest +# parameter number already assigned. +# +# EVIDENCE-OF: R-42938-07030 If this means the parameter number is +# greater than SQLITE_MAX_VARIABLE_NUMBER, it is an error. +# +parameter_test e_expr-11.2.1 "SELECT ?" {1 {}} -1 +parameter_test e_expr-11.2.2 "SELECT ?, ?" {1 {} 2 {}} {-1 -2} +parameter_test e_expr-11.2.3 "SELECT ?5, ?" {5 ?5 6 {}} {-5 -6} +parameter_test e_expr-11.2.4 "SELECT ?, ?5" {1 {} 5 ?5} {-1 -5} +parameter_test e_expr-11.2.5 "SELECT ?, ?456, ?" { + 1 {} 456 ?456 457 {} +} {-1 -456 -457} +parameter_test e_expr-11.2.5 "SELECT ?, ?456, ?4, ?" { + 1 {} 456 ?456 4 ?4 457 {} +} {-1 -456 -4 -457} +foreach {tn sql} [list \ + 1 "SELECT ?$mvn, ?" \ + 2 "SELECT ?[expr $mvn-5], ?, ?, ?, ?, ?, ?" \ + 3 "SELECT ?[expr $mvn], ?5, ?6, ?" \ +] { + do_catchsql_test e_expr-11.3.$tn $sql [list 1 {too many SQL variables}] +} + +# EVIDENCE-OF: R-11620-22743 A colon followed by an identifier name +# holds a spot for a named parameter with the name :AAAA. +# +# Identifiers in SQLite consist of alphanumeric, '_' and '$' characters, +# and any UTF characters with codepoints larger than 127 (non-ASCII +# characters). +# +parameter_test e_expr-11.2.1 {SELECT :AAAA} {1 :AAAA} -1 +parameter_test e_expr-11.2.2 {SELECT :123} {1 :123} -1 +parameter_test e_expr-11.2.3 {SELECT :__} {1 :__} -1 +parameter_test e_expr-11.2.4 {SELECT :_$_} {1 :_$_} -1 +parameter_test e_expr-11.2.5 " + SELECT :\u0e40\u0e2d\u0e28\u0e02\u0e39\u0e40\u0e2d\u0e25 +" "1 :\u0e40\u0e2d\u0e28\u0e02\u0e39\u0e40\u0e2d\u0e25" -1 +parameter_test e_expr-11.2.6 "SELECT :\u0080" "1 :\u0080" -1 + +# EVIDENCE-OF: R-49783-61279 An "at" sign works exactly like a colon, +# except that the name of the parameter created is @AAAA. +# +parameter_test e_expr-11.3.1 {SELECT @AAAA} {1 @AAAA} -1 +parameter_test e_expr-11.3.2 {SELECT @123} {1 @123} -1 +parameter_test e_expr-11.3.3 {SELECT @__} {1 @__} -1 +parameter_test e_expr-11.3.4 {SELECT @_$_} {1 @_$_} -1 +parameter_test e_expr-11.3.5 " + SELECT @\u0e40\u0e2d\u0e28\u0e02\u0e39\u0e40\u0e2d\u0e25 +" "1 @\u0e40\u0e2d\u0e28\u0e02\u0e39\u0e40\u0e2d\u0e25" -1 +parameter_test e_expr-11.3.6 "SELECT @\u0080" "1 @\u0080" -1 + +# EVIDENCE-OF: R-62610-51329 A dollar-sign followed by an identifier +# name also holds a spot for a named parameter with the name $AAAA. +# +# EVIDENCE-OF: R-55025-21042 The identifier name in this case can +# include one or more occurrences of "::" and a suffix enclosed in +# "(...)" containing any text at all. +# +# Note: Looks like an identifier cannot consist entirely of "::" +# characters or just a suffix. Also, the other named variable characters +# (: and @) work the same way internally. Why not just document it that way? +# +parameter_test e_expr-11.4.1 {SELECT $AAAA} {1 $AAAA} -1 +parameter_test e_expr-11.4.2 {SELECT $123} {1 $123} -1 +parameter_test e_expr-11.4.3 {SELECT $__} {1 $__} -1 +parameter_test e_expr-11.4.4 {SELECT $_$_} {1 $_$_} -1 +parameter_test e_expr-11.4.5 " + SELECT \$\u0e40\u0e2d\u0e28\u0e02\u0e39\u0e40\u0e2d\u0e25 +" "1 \$\u0e40\u0e2d\u0e28\u0e02\u0e39\u0e40\u0e2d\u0e25" -1 +parameter_test e_expr-11.4.6 "SELECT \$\u0080" "1 \$\u0080" -1 + +parameter_test e_expr-11.5.1 {SELECT $::::a(++--++)} {1 $::::a(++--++)} -1 +parameter_test e_expr-11.5.2 {SELECT $::a()} {1 $::a()} -1 +parameter_test e_expr-11.5.3 {SELECT $::1(::#$)} {1 $::1(::#$)} -1 + +# EVIDENCE-OF: R-11370-04520 Named parameters are also numbered. The +# number assigned is one greater than the largest parameter number +# already assigned. +# +# EVIDENCE-OF: R-42620-22184 If this means the parameter would be +# assigned a number greater than SQLITE_MAX_VARIABLE_NUMBER, it is an +# error. +# +parameter_test e_expr-11.6.1 "SELECT ?, @abc" {1 {} 2 @abc} {-1 -2} +parameter_test e_expr-11.6.2 "SELECT ?123, :a1" {123 ?123 124 :a1} {-123 -124} +parameter_test e_expr-11.6.3 {SELECT $a, ?8, ?, $b, ?2, $c} { + 1 $a 8 ?8 9 {} 10 $b 2 ?2 11 $c +} {-1 -8 -9 -10 -2 -11} +foreach {tn sql} [list \ + 1 "SELECT ?$mvn, \$::a" \ + 2 "SELECT ?$mvn, ?4, @a1" \ + 3 "SELECT ?[expr $mvn-2], :bag, @123, \$x" \ +] { + do_catchsql_test e_expr-11.7.$tn $sql [list 1 {too many SQL variables}] +} + +# EVIDENCE-OF: R-14068-49671 Parameters that are not assigned values +# using sqlite3_bind() are treated as NULL. +# +do_test e_expr-11.7.1 { + set stmt [sqlite3_prepare_v2 db { SELECT ?, :a, @b, $d } -1] + sqlite3_step $stmt + + list [sqlite3_column_type $stmt 0] \ + [sqlite3_column_type $stmt 1] \ + [sqlite3_column_type $stmt 2] \ + [sqlite3_column_type $stmt 3] +} {NULL NULL NULL NULL} +do_test e_expr-11.7.1 { sqlite3_finalize $stmt } SQLITE_OK + +#------------------------------------------------------------------------- +# "Test" the syntax diagrams in lang_expr.html. +# +# -- syntax diagram signed-number +# +do_execsql_test e_expr-12.1.1 { SELECT 0, +0, -0 } {0 0 0} +do_execsql_test e_expr-12.1.2 { SELECT 1, +1, -1 } {1 1 -1} +do_execsql_test e_expr-12.1.3 { SELECT 2, +2, -2 } {2 2 -2} +do_execsql_test e_expr-12.1.4 { + SELECT 1.4, +1.4, -1.4 +} {1.4 1.4 -1.4} +do_execsql_test e_expr-12.1.5 { + SELECT 1.5e+5, +1.5e+5, -1.5e+5 +} {150000.0 150000.0 -150000.0} +do_execsql_test e_expr-12.1.6 { + SELECT 0.0001, +0.0001, -0.0001 +} {0.0001 0.0001 -0.0001} + +# -- syntax diagram literal-value +# +set sqlite_current_time 1 +do_execsql_test e_expr-12.2.1 {SELECT 123} {123} +do_execsql_test e_expr-12.2.2 {SELECT 123.4e05} {12340000.0} +do_execsql_test e_expr-12.2.3 {SELECT 'abcde'} {abcde} +do_execsql_test e_expr-12.2.4 {SELECT X'414243'} {ABC} +do_execsql_test e_expr-12.2.5 {SELECT NULL} {{}} +do_execsql_test e_expr-12.2.6 {SELECT CURRENT_TIME} {00:00:01} +do_execsql_test e_expr-12.2.7 {SELECT CURRENT_DATE} {1970-01-01} +do_execsql_test e_expr-12.2.8 {SELECT CURRENT_TIMESTAMP} {{1970-01-01 00:00:01}} +set sqlite_current_time 0 + +# -- syntax diagram expr +# +forcedelete test.db2 +execsql { + ATTACH 'test.db2' AS dbname; + CREATE TABLE dbname.tblname(cname); +} + +proc glob {args} {return 1} +db function glob glob +db function match glob +db function regexp glob + +foreach {tn expr} { + 1 123 + 2 123.4e05 + 3 'abcde' + 4 X'414243' + 5 NULL + 6 CURRENT_TIME + 7 CURRENT_DATE + 8 CURRENT_TIMESTAMP + + 9 ? + 10 ?123 + 11 @hello + 12 :world + 13 $tcl + 14 $tcl(array) + + 15 cname + 16 tblname.cname + 17 dbname.tblname.cname + + 18 "+ EXPR" + 19 "- EXPR" + 20 "NOT EXPR" + 21 "~ EXPR" + + 22 "EXPR1 || EXPR2" + 23 "EXPR1 * EXPR2" + 24 "EXPR1 / EXPR2" + 25 "EXPR1 % EXPR2" + 26 "EXPR1 + EXPR2" + 27 "EXPR1 - EXPR2" + 28 "EXPR1 << EXPR2" + 29 "EXPR1 >> EXPR2" + 30 "EXPR1 & EXPR2" + 31 "EXPR1 | EXPR2" + 32 "EXPR1 < EXPR2" + 33 "EXPR1 <= EXPR2" + 34 "EXPR1 > EXPR2" + 35 "EXPR1 >= EXPR2" + 36 "EXPR1 = EXPR2" + 37 "EXPR1 == EXPR2" + 38 "EXPR1 != EXPR2" + 39 "EXPR1 <> EXPR2" + 40 "EXPR1 IS EXPR2" + 41 "EXPR1 IS NOT EXPR2" + 42 "EXPR1 AND EXPR2" + 43 "EXPR1 OR EXPR2" + + 44 "count(*)" + 45 "count(DISTINCT EXPR)" + 46 "substr(EXPR, 10, 20)" + 47 "changes()" + + 48 "( EXPR )" + + 49 "CAST ( EXPR AS integer )" + 50 "CAST ( EXPR AS 'abcd' )" + 51 "CAST ( EXPR AS 'ab$ $cd' )" + + 52 "EXPR COLLATE nocase" + 53 "EXPR COLLATE binary" + + 54 "EXPR1 LIKE EXPR2" + 55 "EXPR1 LIKE EXPR2 ESCAPE EXPR" + 56 "EXPR1 GLOB EXPR2" + 57 "EXPR1 GLOB EXPR2 ESCAPE EXPR" + 58 "EXPR1 REGEXP EXPR2" + 59 "EXPR1 REGEXP EXPR2 ESCAPE EXPR" + 60 "EXPR1 MATCH EXPR2" + 61 "EXPR1 MATCH EXPR2 ESCAPE EXPR" + 62 "EXPR1 NOT LIKE EXPR2" + 63 "EXPR1 NOT LIKE EXPR2 ESCAPE EXPR" + 64 "EXPR1 NOT GLOB EXPR2" + 65 "EXPR1 NOT GLOB EXPR2 ESCAPE EXPR" + 66 "EXPR1 NOT REGEXP EXPR2" + 67 "EXPR1 NOT REGEXP EXPR2 ESCAPE EXPR" + 68 "EXPR1 NOT MATCH EXPR2" + 69 "EXPR1 NOT MATCH EXPR2 ESCAPE EXPR" + + 70 "EXPR ISNULL" + 71 "EXPR NOTNULL" + 72 "EXPR NOT NULL" + + 73 "EXPR1 IS EXPR2" + 74 "EXPR1 IS NOT EXPR2" + + 75 "EXPR NOT BETWEEN EXPR1 AND EXPR2" + 76 "EXPR BETWEEN EXPR1 AND EXPR2" + + 77 "EXPR NOT IN (SELECT cname FROM tblname)" + 78 "EXPR NOT IN (1)" + 79 "EXPR NOT IN (1, 2, 3)" + 80 "EXPR NOT IN tblname" + 81 "EXPR NOT IN dbname.tblname" + 82 "EXPR IN (SELECT cname FROM tblname)" + 83 "EXPR IN (1)" + 84 "EXPR IN (1, 2, 3)" + 85 "EXPR IN tblname" + 86 "EXPR IN dbname.tblname" + + 87 "EXISTS (SELECT cname FROM tblname)" + 88 "NOT EXISTS (SELECT cname FROM tblname)" + + 89 "CASE EXPR WHEN EXPR1 THEN EXPR2 ELSE EXPR END" + 90 "CASE EXPR WHEN EXPR1 THEN EXPR2 END" + 91 "CASE EXPR WHEN EXPR1 THEN EXPR2 WHEN EXPR THEN EXPR1 ELSE EXPR2 END" + 92 "CASE EXPR WHEN EXPR1 THEN EXPR2 WHEN EXPR THEN EXPR1 END" + 93 "CASE WHEN EXPR1 THEN EXPR2 ELSE EXPR END" + 94 "CASE WHEN EXPR1 THEN EXPR2 END" + 95 "CASE WHEN EXPR1 THEN EXPR2 WHEN EXPR THEN EXPR1 ELSE EXPR2 END" + 96 "CASE WHEN EXPR1 THEN EXPR2 WHEN EXPR THEN EXPR1 END" +} { + + # If the expression string being parsed contains "EXPR2", then replace + # string "EXPR1" and "EXPR2" with arbitrary SQL expressions. If it + # contains "EXPR", then replace EXPR with an arbitrary SQL expression. + # + set elist [list $expr] + if {[string match *EXPR2* $expr]} { + set elist [list] + foreach {e1 e2} { cname "34+22" } { + lappend elist [string map [list EXPR1 $e1 EXPR2 $e2] $expr] + } + } + if {[string match *EXPR* $expr]} { + set elist2 [list] + foreach el $elist { + foreach e { cname "34+22" } { + lappend elist2 [string map [list EXPR $e] $el] + } + } + set elist $elist2 + } + + set x 0 + foreach e $elist { + incr x + do_test e_expr-12.3.$tn.$x { + set rc [catch { execsql "SELECT $e FROM tblname" } msg] + } {0} + } +} + +# -- syntax diagram raise-function +# +foreach {tn raiseexpr} { + 1 "RAISE(IGNORE)" + 2 "RAISE(ROLLBACK, 'error message')" + 3 "RAISE(ABORT, 'error message')" + 4 "RAISE(FAIL, 'error message')" +} { + do_execsql_test e_expr-12.4.$tn " + CREATE TRIGGER dbname.tr$tn BEFORE DELETE ON tblname BEGIN + SELECT $raiseexpr ; + END; + " {} +} + +#------------------------------------------------------------------------- +# Test the statements related to the BETWEEN operator. +# +# EVIDENCE-OF: R-40079-54503 The BETWEEN operator is logically +# equivalent to a pair of comparisons. "x BETWEEN y AND z" is equivalent +# to "x>=y AND x<=z" except that with BETWEEN, the x expression is +# only evaluated once. +# +db func x x +proc x {} { incr ::xcount ; return [expr $::x] } +foreach {tn x expr res nEval} { + 1 10 "x() >= 5 AND x() <= 15" 1 2 + 2 10 "x() BETWEEN 5 AND 15" 1 1 + + 3 5 "x() >= 5 AND x() <= 5" 1 2 + 4 5 "x() BETWEEN 5 AND 5" 1 1 +} { + do_test e_expr-13.1.$tn { + set ::xcount 0 + set a [execsql "SELECT $expr"] + list $::xcount $a + } [list $nEval $res] +} + +# EVIDENCE-OF: R-05155-34454 The precedence of the BETWEEN operator is +# the same as the precedence as operators == and != and LIKE and groups +# left to right. +# +# Therefore, BETWEEN groups more tightly than operator "AND", but less +# so than "<". +# +do_execsql_test e_expr-13.2.1 { SELECT 1 == 10 BETWEEN 0 AND 2 } 1 +do_execsql_test e_expr-13.2.2 { SELECT (1 == 10) BETWEEN 0 AND 2 } 1 +do_execsql_test e_expr-13.2.3 { SELECT 1 == (10 BETWEEN 0 AND 2) } 0 +do_execsql_test e_expr-13.2.4 { SELECT 6 BETWEEN 4 AND 8 == 1 } 1 +do_execsql_test e_expr-13.2.5 { SELECT (6 BETWEEN 4 AND 8) == 1 } 1 +do_execsql_test e_expr-13.2.6 { SELECT 6 BETWEEN 4 AND (8 == 1) } 0 + +do_execsql_test e_expr-13.2.7 { SELECT 5 BETWEEN 0 AND 0 != 1 } 1 +do_execsql_test e_expr-13.2.8 { SELECT (5 BETWEEN 0 AND 0) != 1 } 1 +do_execsql_test e_expr-13.2.9 { SELECT 5 BETWEEN 0 AND (0 != 1) } 0 +do_execsql_test e_expr-13.2.10 { SELECT 1 != 0 BETWEEN 0 AND 2 } 1 +do_execsql_test e_expr-13.2.11 { SELECT (1 != 0) BETWEEN 0 AND 2 } 1 +do_execsql_test e_expr-13.2.12 { SELECT 1 != (0 BETWEEN 0 AND 2) } 0 + +do_execsql_test e_expr-13.2.13 { SELECT 1 LIKE 10 BETWEEN 0 AND 2 } 1 +do_execsql_test e_expr-13.2.14 { SELECT (1 LIKE 10) BETWEEN 0 AND 2 } 1 +do_execsql_test e_expr-13.2.15 { SELECT 1 LIKE (10 BETWEEN 0 AND 2) } 0 +do_execsql_test e_expr-13.2.16 { SELECT 6 BETWEEN 4 AND 8 LIKE 1 } 1 +do_execsql_test e_expr-13.2.17 { SELECT (6 BETWEEN 4 AND 8) LIKE 1 } 1 +do_execsql_test e_expr-13.2.18 { SELECT 6 BETWEEN 4 AND (8 LIKE 1) } 0 + +do_execsql_test e_expr-13.2.19 { SELECT 0 AND 0 BETWEEN 0 AND 1 } 0 +do_execsql_test e_expr-13.2.20 { SELECT 0 AND (0 BETWEEN 0 AND 1) } 0 +do_execsql_test e_expr-13.2.21 { SELECT (0 AND 0) BETWEEN 0 AND 1 } 1 +do_execsql_test e_expr-13.2.22 { SELECT 0 BETWEEN -1 AND 1 AND 0 } 0 +do_execsql_test e_expr-13.2.23 { SELECT (0 BETWEEN -1 AND 1) AND 0 } 0 +do_execsql_test e_expr-13.2.24 { SELECT 0 BETWEEN -1 AND (1 AND 0) } 1 + +do_execsql_test e_expr-13.2.25 { SELECT 2 < 3 BETWEEN 0 AND 1 } 1 +do_execsql_test e_expr-13.2.26 { SELECT (2 < 3) BETWEEN 0 AND 1 } 1 +do_execsql_test e_expr-13.2.27 { SELECT 2 < (3 BETWEEN 0 AND 1) } 0 +do_execsql_test e_expr-13.2.28 { SELECT 2 BETWEEN 1 AND 2 < 3 } 0 +do_execsql_test e_expr-13.2.29 { SELECT 2 BETWEEN 1 AND (2 < 3) } 0 +do_execsql_test e_expr-13.2.30 { SELECT (2 BETWEEN 1 AND 2) < 3 } 1 + +#------------------------------------------------------------------------- +# Test the statements related to the LIKE and GLOB operators. +# +# EVIDENCE-OF: R-16584-60189 The LIKE operator does a pattern matching +# comparison. +# +# EVIDENCE-OF: R-11295-04657 The operand to the right of the LIKE +# operator contains the pattern and the left hand operand contains the +# string to match against the pattern. +# +do_execsql_test e_expr-14.1.1 { SELECT 'abc%' LIKE 'abcde' } 0 +do_execsql_test e_expr-14.1.2 { SELECT 'abcde' LIKE 'abc%' } 1 + +# EVIDENCE-OF: R-55406-38524 A percent symbol ("%") in the LIKE pattern +# matches any sequence of zero or more characters in the string. +# +do_execsql_test e_expr-14.2.1 { SELECT 'abde' LIKE 'ab%de' } 1 +do_execsql_test e_expr-14.2.2 { SELECT 'abXde' LIKE 'ab%de' } 1 +do_execsql_test e_expr-14.2.3 { SELECT 'abABCde' LIKE 'ab%de' } 1 + +# EVIDENCE-OF: R-30433-25443 An underscore ("_") in the LIKE pattern +# matches any single character in the string. +# +do_execsql_test e_expr-14.3.1 { SELECT 'abde' LIKE 'ab_de' } 0 +do_execsql_test e_expr-14.3.2 { SELECT 'abXde' LIKE 'ab_de' } 1 +do_execsql_test e_expr-14.3.3 { SELECT 'abABCde' LIKE 'ab_de' } 0 + +# EVIDENCE-OF: R-59007-20454 Any other character matches itself or its +# lower/upper case equivalent (i.e. case-insensitive matching). +# +do_execsql_test e_expr-14.4.1 { SELECT 'abc' LIKE 'aBc' } 1 +do_execsql_test e_expr-14.4.2 { SELECT 'aBc' LIKE 'aBc' } 1 +do_execsql_test e_expr-14.4.3 { SELECT 'ac' LIKE 'aBc' } 0 + +# EVIDENCE-OF: R-23648-58527 SQLite only understands upper/lower case +# for ASCII characters by default. +# +# EVIDENCE-OF: R-04532-11527 The LIKE operator is case sensitive by +# default for unicode characters that are beyond the ASCII range. +# +# EVIDENCE-OF: R-44381-11669 the expression +# 'a' LIKE 'A' is TRUE but +# 'æ' LIKE 'Æ' is FALSE. +# +# The restriction to ASCII characters does not apply if the ICU +# library is compiled in. When ICU is enabled SQLite does not act +# as it does "by default". +# +do_execsql_test e_expr-14.5.1 { SELECT 'A' LIKE 'a' } 1 +ifcapable !icu { + do_execsql_test e_expr-14.5.2 "SELECT '\u00c6' LIKE '\u00e6'" 0 +} + +# EVIDENCE-OF: R-56683-13731 If the optional ESCAPE clause is present, +# then the expression following the ESCAPE keyword must evaluate to a +# string consisting of a single character. +# +do_catchsql_test e_expr-14.6.1 { + SELECT 'A' LIKE 'a' ESCAPE '12' +} {1 {ESCAPE expression must be a single character}} +do_catchsql_test e_expr-14.6.2 { + SELECT 'A' LIKE 'a' ESCAPE '' +} {1 {ESCAPE expression must be a single character}} +do_catchsql_test e_expr-14.6.3 { SELECT 'A' LIKE 'a' ESCAPE 'x' } {0 1} +do_catchsql_test e_expr-14.6.4 "SELECT 'A' LIKE 'a' ESCAPE '\u00e6'" {0 1} + +# EVIDENCE-OF: R-02045-23762 This character may be used in the LIKE +# pattern to include literal percent or underscore characters. +# +# EVIDENCE-OF: R-13345-31830 The escape character followed by a percent +# symbol (%), underscore (_), or a second instance of the escape +# character itself matches a literal percent symbol, underscore, or a +# single escape character, respectively. +# +do_execsql_test e_expr-14.7.1 { SELECT 'abc%' LIKE 'abcX%' ESCAPE 'X' } 1 +do_execsql_test e_expr-14.7.2 { SELECT 'abc5' LIKE 'abcX%' ESCAPE 'X' } 0 +do_execsql_test e_expr-14.7.3 { SELECT 'abc' LIKE 'abcX%' ESCAPE 'X' } 0 +do_execsql_test e_expr-14.7.4 { SELECT 'abcX%' LIKE 'abcX%' ESCAPE 'X' } 0 +do_execsql_test e_expr-14.7.5 { SELECT 'abc%%' LIKE 'abcX%' ESCAPE 'X' } 0 + +do_execsql_test e_expr-14.7.6 { SELECT 'abc_' LIKE 'abcX_' ESCAPE 'X' } 1 +do_execsql_test e_expr-14.7.7 { SELECT 'abc5' LIKE 'abcX_' ESCAPE 'X' } 0 +do_execsql_test e_expr-14.7.8 { SELECT 'abc' LIKE 'abcX_' ESCAPE 'X' } 0 +do_execsql_test e_expr-14.7.9 { SELECT 'abcX_' LIKE 'abcX_' ESCAPE 'X' } 0 +do_execsql_test e_expr-14.7.10 { SELECT 'abc__' LIKE 'abcX_' ESCAPE 'X' } 0 + +do_execsql_test e_expr-14.7.11 { SELECT 'abcX' LIKE 'abcXX' ESCAPE 'X' } 1 +do_execsql_test e_expr-14.7.12 { SELECT 'abc5' LIKE 'abcXX' ESCAPE 'X' } 0 +do_execsql_test e_expr-14.7.13 { SELECT 'abc' LIKE 'abcXX' ESCAPE 'X' } 0 +do_execsql_test e_expr-14.7.14 { SELECT 'abcXX' LIKE 'abcXX' ESCAPE 'X' } 0 + +# EVIDENCE-OF: R-51359-17496 The infix LIKE operator is implemented by +# calling the application-defined SQL functions like(Y,X) or like(Y,X,Z). +# +proc likefunc {args} { + eval lappend ::likeargs $args + return 1 +} +db func like -argcount 2 likefunc +db func like -argcount 3 likefunc +set ::likeargs [list] +do_execsql_test e_expr-15.1.1 { SELECT 'abc' LIKE 'def' } 1 +do_test e_expr-15.1.2 { set likeargs } {def abc} +set ::likeargs [list] +do_execsql_test e_expr-15.1.3 { SELECT 'abc' LIKE 'def' ESCAPE 'X' } 1 +do_test e_expr-15.1.4 { set likeargs } {def abc X} +db close +sqlite3 db test.db + +# EVIDENCE-OF: R-22868-25880 The LIKE operator can be made case +# sensitive using the case_sensitive_like pragma. +# +do_execsql_test e_expr-16.1.1 { SELECT 'abcxyz' LIKE 'ABC%' } 1 +do_execsql_test e_expr-16.1.2 { PRAGMA case_sensitive_like = 1 } {} +do_execsql_test e_expr-16.1.3 { SELECT 'abcxyz' LIKE 'ABC%' } 0 +do_execsql_test e_expr-16.1.4 { SELECT 'ABCxyz' LIKE 'ABC%' } 1 +do_execsql_test e_expr-16.1.5 { PRAGMA case_sensitive_like = 0 } {} +do_execsql_test e_expr-16.1.6 { SELECT 'abcxyz' LIKE 'ABC%' } 1 +do_execsql_test e_expr-16.1.7 { SELECT 'ABCxyz' LIKE 'ABC%' } 1 + +# EVIDENCE-OF: R-52087-12043 The GLOB operator is similar to LIKE but +# uses the Unix file globbing syntax for its wildcards. +# +# EVIDENCE-OF: R-09813-17279 Also, GLOB is case sensitive, unlike LIKE. +# +do_execsql_test e_expr-17.1.1 { SELECT 'abcxyz' GLOB 'abc%' } 0 +do_execsql_test e_expr-17.1.2 { SELECT 'abcxyz' GLOB 'abc*' } 1 +do_execsql_test e_expr-17.1.3 { SELECT 'abcxyz' GLOB 'abc___' } 0 +do_execsql_test e_expr-17.1.4 { SELECT 'abcxyz' GLOB 'abc???' } 1 + +do_execsql_test e_expr-17.1.5 { SELECT 'abcxyz' GLOB 'abc*' } 1 +do_execsql_test e_expr-17.1.6 { SELECT 'ABCxyz' GLOB 'abc*' } 0 +do_execsql_test e_expr-17.1.7 { SELECT 'abcxyz' GLOB 'ABC*' } 0 + +# EVIDENCE-OF: R-39616-20555 Both GLOB and LIKE may be preceded by the +# NOT keyword to invert the sense of the test. +# +do_execsql_test e_expr-17.2.1 { SELECT 'abcxyz' NOT GLOB 'ABC*' } 1 +do_execsql_test e_expr-17.2.2 { SELECT 'abcxyz' NOT GLOB 'abc*' } 0 +do_execsql_test e_expr-17.2.3 { SELECT 'abcxyz' NOT LIKE 'ABC%' } 0 +do_execsql_test e_expr-17.2.4 { SELECT 'abcxyz' NOT LIKE 'abc%' } 0 +do_execsql_test e_expr-17.2.5 { SELECT 'abdxyz' NOT LIKE 'abc%' } 1 + +db nullvalue null +do_execsql_test e_expr-17.2.6 { SELECT 'abcxyz' NOT GLOB NULL } null +do_execsql_test e_expr-17.2.7 { SELECT 'abcxyz' NOT LIKE NULL } null +do_execsql_test e_expr-17.2.8 { SELECT NULL NOT GLOB 'abc*' } null +do_execsql_test e_expr-17.2.9 { SELECT NULL NOT LIKE 'ABC%' } null +db nullvalue {} + +# EVIDENCE-OF: R-39414-35489 The infix GLOB operator is implemented by +# calling the function glob(Y,X) and can be modified by overriding that +# function. +proc globfunc {args} { + eval lappend ::globargs $args + return 1 +} +db func glob -argcount 2 globfunc +set ::globargs [list] +do_execsql_test e_expr-17.3.1 { SELECT 'abc' GLOB 'def' } 1 +do_test e_expr-17.3.2 { set globargs } {def abc} +set ::globargs [list] +do_execsql_test e_expr-17.3.3 { SELECT 'X' NOT GLOB 'Y' } 0 +do_test e_expr-17.3.4 { set globargs } {Y X} +sqlite3 db test.db + +# EVIDENCE-OF: R-41650-20872 No regexp() user function is defined by +# default and so use of the REGEXP operator will normally result in an +# error message. +# +# There is a regexp function if ICU is enabled though. +# +ifcapable !icu { + do_catchsql_test e_expr-18.1.1 { + SELECT regexp('abc', 'def') + } {1 {no such function: regexp}} + do_catchsql_test e_expr-18.1.2 { + SELECT 'abc' REGEXP 'def' + } {1 {no such function: REGEXP}} +} + +# EVIDENCE-OF: R-33693-50180 The REGEXP operator is a special syntax for +# the regexp() user function. +# +# EVIDENCE-OF: R-57289-13578 If a application-defined SQL function named +# "regexp" is added at run-time, that function will be called in order +# to implement the REGEXP operator. +# +proc regexpfunc {args} { + eval lappend ::regexpargs $args + return 1 +} +db func regexp -argcount 2 regexpfunc +set ::regexpargs [list] +do_execsql_test e_expr-18.2.1 { SELECT 'abc' REGEXP 'def' } 1 +do_test e_expr-18.2.2 { set regexpargs } {def abc} +set ::regexpargs [list] +do_execsql_test e_expr-18.2.3 { SELECT 'X' NOT REGEXP 'Y' } 0 +do_test e_expr-18.2.4 { set regexpargs } {Y X} +sqlite3 db test.db + +# EVIDENCE-OF: R-42037-37826 The default match() function implementation +# raises an exception and is not really useful for anything. +# +do_catchsql_test e_expr-19.1.1 { + SELECT 'abc' MATCH 'def' +} {1 {unable to use function MATCH in the requested context}} +do_catchsql_test e_expr-19.1.2 { + SELECT match('abc', 'def') +} {1 {unable to use function MATCH in the requested context}} + +# EVIDENCE-OF: R-37916-47407 The MATCH operator is a special syntax for +# the match() application-defined function. +# +# EVIDENCE-OF: R-06021-09373 But extensions can override the match() +# function with more helpful logic. +# +proc matchfunc {args} { + eval lappend ::matchargs $args + return 1 +} +db func match -argcount 2 matchfunc +set ::matchargs [list] +do_execsql_test e_expr-19.2.1 { SELECT 'abc' MATCH 'def' } 1 +do_test e_expr-19.2.2 { set matchargs } {def abc} +set ::matchargs [list] +do_execsql_test e_expr-19.2.3 { SELECT 'X' NOT MATCH 'Y' } 0 +do_test e_expr-19.2.4 { set matchargs } {Y X} +sqlite3 db test.db + +#------------------------------------------------------------------------- +# Test cases for the testable statements related to the CASE expression. +# +# EVIDENCE-OF: R-15199-61389 There are two basic forms of the CASE +# expression: those with a base expression and those without. +# +do_execsql_test e_expr-20.1 { + SELECT CASE WHEN 1 THEN 'true' WHEN 0 THEN 'false' ELSE 'else' END; +} {true} +do_execsql_test e_expr-20.2 { + SELECT CASE 0 WHEN 1 THEN 'true' WHEN 0 THEN 'false' ELSE 'else' END; +} {false} + +proc var {nm} { + lappend ::varlist $nm + return [set "::$nm"] +} +db func var var + +# EVIDENCE-OF: R-30638-59954 In a CASE without a base expression, each +# WHEN expression is evaluated and the result treated as a boolean, +# starting with the leftmost and continuing to the right. +# +foreach {a b c} {0 0 0} break +set varlist [list] +do_execsql_test e_expr-21.1.1 { + SELECT CASE WHEN var('a') THEN 'A' + WHEN var('b') THEN 'B' + WHEN var('c') THEN 'C' END +} {{}} +do_test e_expr-21.1.2 { set varlist } {a b c} +set varlist [list] +do_execsql_test e_expr-21.1.3 { + SELECT CASE WHEN var('c') THEN 'C' + WHEN var('b') THEN 'B' + WHEN var('a') THEN 'A' + ELSE 'no result' + END +} {{no result}} +do_test e_expr-21.1.4 { set varlist } {c b a} + +# EVIDENCE-OF: R-39009-25596 The result of the CASE expression is the +# evaluation of the THEN expression that corresponds to the first WHEN +# expression that evaluates to true. +# +foreach {a b c} {0 1 0} break +do_execsql_test e_expr-21.2.1 { + SELECT CASE WHEN var('a') THEN 'A' + WHEN var('b') THEN 'B' + WHEN var('c') THEN 'C' + ELSE 'no result' + END +} {B} +foreach {a b c} {0 1 1} break +do_execsql_test e_expr-21.2.2 { + SELECT CASE WHEN var('a') THEN 'A' + WHEN var('b') THEN 'B' + WHEN var('c') THEN 'C' + ELSE 'no result' + END +} {B} +foreach {a b c} {0 0 1} break +do_execsql_test e_expr-21.2.3 { + SELECT CASE WHEN var('a') THEN 'A' + WHEN var('b') THEN 'B' + WHEN var('c') THEN 'C' + ELSE 'no result' + END +} {C} + +# EVIDENCE-OF: R-24227-04807 Or, if none of the WHEN expressions +# evaluate to true, the result of evaluating the ELSE expression, if +# any. +# +foreach {a b c} {0 0 0} break +do_execsql_test e_expr-21.3.1 { + SELECT CASE WHEN var('a') THEN 'A' + WHEN var('b') THEN 'B' + WHEN var('c') THEN 'C' + ELSE 'no result' + END +} {{no result}} + +# EVIDENCE-OF: R-14168-07579 If there is no ELSE expression and none of +# the WHEN expressions are true, then the overall result is NULL. +# +db nullvalue null +do_execsql_test e_expr-21.3.2 { + SELECT CASE WHEN var('a') THEN 'A' + WHEN var('b') THEN 'B' + WHEN var('c') THEN 'C' + END +} {null} +db nullvalue {} + +# EVIDENCE-OF: R-13943-13592 A NULL result is considered untrue when +# evaluating WHEN terms. +# +do_execsql_test e_expr-21.4.1 { + SELECT CASE WHEN NULL THEN 'A' WHEN 1 THEN 'B' END +} {B} +do_execsql_test e_expr-21.4.2 { + SELECT CASE WHEN 0 THEN 'A' WHEN NULL THEN 'B' ELSE 'C' END +} {C} + +# EVIDENCE-OF: R-38620-19499 In a CASE with a base expression, the base +# expression is evaluated just once and the result is compared against +# the evaluation of each WHEN expression from left to right. +# +# Note: This test case tests the "evaluated just once" part of the above +# statement. Tests associated with the next two statements test that the +# comparisons take place. +# +foreach {a b c} [list [expr 3] [expr 4] [expr 5]] break +set ::varlist [list] +do_execsql_test e_expr-22.1.1 { + SELECT CASE var('a') WHEN 1 THEN 'A' WHEN 2 THEN 'B' WHEN 3 THEN 'C' END +} {C} +do_test e_expr-22.1.2 { set ::varlist } {a} + +# EVIDENCE-OF: R-07667-49537 The result of the CASE expression is the +# evaluation of the THEN expression that corresponds to the first WHEN +# expression for which the comparison is true. +# +do_execsql_test e_expr-22.2.1 { + SELECT CASE 23 WHEN 1 THEN 'A' WHEN 23 THEN 'B' WHEN 23 THEN 'C' END +} {B} +do_execsql_test e_expr-22.2.2 { + SELECT CASE 1 WHEN 1 THEN 'A' WHEN 23 THEN 'B' WHEN 23 THEN 'C' END +} {A} + +# EVIDENCE-OF: R-47543-32145 Or, if none of the WHEN expressions +# evaluate to a value equal to the base expression, the result of +# evaluating the ELSE expression, if any. +# +do_execsql_test e_expr-22.3.1 { + SELECT CASE 24 WHEN 1 THEN 'A' WHEN 23 THEN 'B' WHEN 23 THEN 'C' ELSE 'D' END +} {D} + +# EVIDENCE-OF: R-54721-48557 If there is no ELSE expression and none of +# the WHEN expressions produce a result equal to the base expression, +# the overall result is NULL. +# +do_execsql_test e_expr-22.4.1 { + SELECT CASE 24 WHEN 1 THEN 'A' WHEN 23 THEN 'B' WHEN 23 THEN 'C' END +} {{}} +db nullvalue null +do_execsql_test e_expr-22.4.2 { + SELECT CASE 24 WHEN 1 THEN 'A' WHEN 23 THEN 'B' WHEN 23 THEN 'C' END +} {null} +db nullvalue {} + +# EVIDENCE-OF: R-11479-62774 When comparing a base expression against a +# WHEN expression, the same collating sequence, affinity, and +# NULL-handling rules apply as if the base expression and WHEN +# expression are respectively the left- and right-hand operands of an = +# operator. +# +proc rev {str} { + set ret "" + set chars [split $str] + for {set i [expr [llength $chars]-1]} {$i>=0} {incr i -1} { + append ret [lindex $chars $i] + } + set ret +} +proc reverse {lhs rhs} { + string compare [rev $lhs] [rev $rhs] +} +db collate reverse reverse +do_execsql_test e_expr-23.1.1 { + CREATE TABLE t1( + a TEXT COLLATE NOCASE, + b COLLATE REVERSE, + c INTEGER, + d BLOB + ); + INSERT INTO t1 VALUES('abc', 'cba', 55, 34.5); +} {} +do_execsql_test e_expr-23.1.2 { + SELECT CASE a WHEN 'xyz' THEN 'A' WHEN 'AbC' THEN 'B' END FROM t1 +} {B} +do_execsql_test e_expr-23.1.3 { + SELECT CASE 'AbC' WHEN 'abc' THEN 'A' WHEN a THEN 'B' END FROM t1 +} {B} +do_execsql_test e_expr-23.1.4 { + SELECT CASE a WHEN b THEN 'A' ELSE 'B' END FROM t1 +} {B} +do_execsql_test e_expr-23.1.5 { + SELECT CASE b WHEN a THEN 'A' ELSE 'B' END FROM t1 +} {B} +do_execsql_test e_expr-23.1.6 { + SELECT CASE 55 WHEN '55' THEN 'A' ELSE 'B' END +} {B} +do_execsql_test e_expr-23.1.7 { + SELECT CASE c WHEN '55' THEN 'A' ELSE 'B' END FROM t1 +} {A} +do_execsql_test e_expr-23.1.8 { + SELECT CASE '34.5' WHEN d THEN 'A' ELSE 'B' END FROM t1 +} {B} +do_execsql_test e_expr-23.1.9 { + SELECT CASE NULL WHEN NULL THEN 'A' ELSE 'B' END +} {B} + +# EVIDENCE-OF: R-37304-39405 If the base expression is NULL then the +# result of the CASE is always the result of evaluating the ELSE +# expression if it exists, or NULL if it does not. +# +do_execsql_test e_expr-24.1.1 { + SELECT CASE NULL WHEN 'abc' THEN 'A' WHEN 'def' THEN 'B' END; +} {{}} +do_execsql_test e_expr-24.1.2 { + SELECT CASE NULL WHEN 'abc' THEN 'A' WHEN 'def' THEN 'B' ELSE 'C' END; +} {C} + +# EVIDENCE-OF: R-56280-17369 Both forms of the CASE expression use lazy, +# or short-circuit, evaluation. +# +set varlist [list] +foreach {a b c} {0 1 0} break +do_execsql_test e_expr-25.1.1 { + SELECT CASE WHEN var('a') THEN 'A' + WHEN var('b') THEN 'B' + WHEN var('c') THEN 'C' + END +} {B} +do_test e_expr-25.1.2 { set ::varlist } {a b} +set varlist [list] +do_execsql_test e_expr-25.1.3 { + SELECT CASE '0' WHEN var('a') THEN 'A' + WHEN var('b') THEN 'B' + WHEN var('c') THEN 'C' + END +} {A} +do_test e_expr-25.1.4 { set ::varlist } {a} + +# EVIDENCE-OF: R-34773-62253 The only difference between the following +# two CASE expressions is that the x expression is evaluated exactly +# once in the first example but might be evaluated multiple times in the +# second: CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END CASE WHEN +# x=w1 THEN r1 WHEN x=w2 THEN r2 ELSE r3 END +# +proc ceval {x} { + incr ::evalcount + return $x +} +db func ceval ceval +set ::evalcount 0 + +do_execsql_test e_expr-26.1.1 { + CREATE TABLE t2(x, w1, r1, w2, r2, r3); + INSERT INTO t2 VALUES(1, 1, 'R1', 2, 'R2', 'R3'); + INSERT INTO t2 VALUES(2, 1, 'R1', 2, 'R2', 'R3'); + INSERT INTO t2 VALUES(3, 1, 'R1', 2, 'R2', 'R3'); +} {} +do_execsql_test e_expr-26.1.2 { + SELECT CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END FROM t2 +} {R1 R2 R3} +do_execsql_test e_expr-26.1.3 { + SELECT CASE WHEN x=w1 THEN r1 WHEN x=w2 THEN r2 ELSE r3 END FROM t2 +} {R1 R2 R3} + +do_execsql_test e_expr-26.1.4 { + SELECT CASE ceval(x) WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END FROM t2 +} {R1 R2 R3} +do_test e_expr-26.1.5 { set ::evalcount } {3} +set ::evalcount 0 +do_execsql_test e_expr-26.1.6 { + SELECT CASE + WHEN ceval(x)=w1 THEN r1 + WHEN ceval(x)=w2 THEN r2 + ELSE r3 END + FROM t2 +} {R1 R2 R3} +do_test e_expr-26.1.6 { set ::evalcount } {5} + + +#------------------------------------------------------------------------- +# Test statements related to CAST expressions. +# +# EVIDENCE-OF: R-65079-31758 Application of a CAST expression is +# different to application of a column affinity, as with a CAST +# expression the storage class conversion is forced even if it is lossy +# and irrreversible. +# +do_execsql_test e_expr-27.1.1 { + CREATE TABLE t3(a TEXT, b REAL, c INTEGER); + INSERT INTO t3 VALUES(X'555655', '1.23abc', 4.5); + SELECT typeof(a), a, typeof(b), b, typeof(c), c FROM t3; +} {blob UVU text 1.23abc real 4.5} +do_execsql_test e_expr-27.1.2 { + SELECT + typeof(CAST(X'555655' as TEXT)), CAST(X'555655' as TEXT), + typeof(CAST('1.23abc' as REAL)), CAST('1.23abc' as REAL), + typeof(CAST(4.5 as INTEGER)), CAST(4.5 as INTEGER) +} {text UVU real 1.23 integer 4} + +# EVIDENCE-OF: R-27225-65050 If the value of is NULL, then +# the result of the CAST expression is also NULL. +# +do_expr_test e_expr-27.2.1 { CAST(NULL AS integer) } null {} +do_expr_test e_expr-27.2.2 { CAST(NULL AS text) } null {} +do_expr_test e_expr-27.2.3 { CAST(NULL AS blob) } null {} +do_expr_test e_expr-27.2.4 { CAST(NULL AS number) } null {} + +# EVIDENCE-OF: R-31076-23575 Casting a value to a with +# no affinity causes the value to be converted into a BLOB. +# +do_expr_test e_expr-27.3.1 { CAST('abc' AS blob) } blob abc +do_expr_test e_expr-27.3.2 { CAST('def' AS shobblob_x) } blob def +do_expr_test e_expr-27.3.3 { CAST('ghi' AS abbLOb10) } blob ghi + +# EVIDENCE-OF: R-22956-37754 Casting to a BLOB consists of first casting +# the value to TEXT in the encoding of the database connection, then +# interpreting the resulting byte sequence as a BLOB instead of as TEXT. +# +do_qexpr_test e_expr-27.4.1 { CAST('ghi' AS blob) } X'676869' +do_qexpr_test e_expr-27.4.2 { CAST(456 AS blob) } X'343536' +do_qexpr_test e_expr-27.4.3 { CAST(1.78 AS blob) } X'312E3738' +rename db db2 +sqlite3 db :memory: +ifcapable {utf16} { +db eval { PRAGMA encoding = 'utf-16le' } +do_qexpr_test e_expr-27.4.4 { CAST('ghi' AS blob) } X'670068006900' +do_qexpr_test e_expr-27.4.5 { CAST(456 AS blob) } X'340035003600' +do_qexpr_test e_expr-27.4.6 { CAST(1.78 AS blob) } X'31002E0037003800' +} +db close +sqlite3 db :memory: +db eval { PRAGMA encoding = 'utf-16be' } +ifcapable {utf16} { +do_qexpr_test e_expr-27.4.7 { CAST('ghi' AS blob) } X'006700680069' +do_qexpr_test e_expr-27.4.8 { CAST(456 AS blob) } X'003400350036' +do_qexpr_test e_expr-27.4.9 { CAST(1.78 AS blob) } X'0031002E00370038' +} +db close +rename db2 db + +# EVIDENCE-OF: R-04207-37981 To cast a BLOB value to TEXT, the sequence +# of bytes that make up the BLOB is interpreted as text encoded using +# the database encoding. +# +do_expr_test e_expr-28.1.1 { CAST (X'676869' AS text) } text ghi +do_expr_test e_expr-28.1.2 { CAST (X'670068006900' AS text) } text g +rename db db2 +sqlite3 db :memory: +db eval { PRAGMA encoding = 'utf-16le' } +ifcapable {utf16} { +do_expr_test e_expr-28.1.3 { CAST (X'676869' AS text) == 'ghi' } integer 0 +do_expr_test e_expr-28.1.4 { CAST (X'670068006900' AS text) } text ghi +} +db close +rename db2 db + +# EVIDENCE-OF: R-22235-47006 Casting an INTEGER or REAL value into TEXT +# renders the value as if via sqlite3_snprintf() except that the +# resulting TEXT uses the encoding of the database connection. +# +do_expr_test e_expr-28.2.1 { CAST (1 AS text) } text 1 +do_expr_test e_expr-28.2.2 { CAST (45 AS text) } text 45 +do_expr_test e_expr-28.2.3 { CAST (-45 AS text) } text -45 +do_expr_test e_expr-28.2.4 { CAST (8.8 AS text) } text 8.8 +do_expr_test e_expr-28.2.5 { CAST (2.3e+5 AS text) } text 230000.0 +do_expr_test e_expr-28.2.6 { CAST (-2.3e-5 AS text) } text -2.3e-05 +do_expr_test e_expr-28.2.7 { CAST (0.0 AS text) } text 0.0 +do_expr_test e_expr-28.2.7 { CAST (0 AS text) } text 0 + +# EVIDENCE-OF: R-26346-36443 When casting a BLOB value to a REAL, the +# value is first converted to TEXT. +# +do_expr_test e_expr-29.1.1 { CAST (X'312E3233' AS REAL) } real 1.23 +do_expr_test e_expr-29.1.2 { CAST (X'3233302E30' AS REAL) } real 230.0 +do_expr_test e_expr-29.1.3 { CAST (X'2D392E3837' AS REAL) } real -9.87 +do_expr_test e_expr-29.1.4 { CAST (X'302E30303031' AS REAL) } real 0.0001 +rename db db2 +sqlite3 db :memory: +ifcapable {utf16} { +db eval { PRAGMA encoding = 'utf-16le' } +do_expr_test e_expr-29.1.5 { + CAST (X'31002E0032003300' AS REAL) } real 1.23 +do_expr_test e_expr-29.1.6 { + CAST (X'3200330030002E003000' AS REAL) } real 230.0 +do_expr_test e_expr-29.1.7 { + CAST (X'2D0039002E0038003700' AS REAL) } real -9.87 +do_expr_test e_expr-29.1.8 { + CAST (X'30002E003000300030003100' AS REAL) } real 0.0001 +} +db close +rename db2 db + +# EVIDENCE-OF: R-54898-34554 When casting a TEXT value to REAL, the +# longest possible prefix of the value that can be interpreted as a real +# number is extracted from the TEXT value and the remainder ignored. +# +do_expr_test e_expr-29.2.1 { CAST('1.23abcd' AS REAL) } real 1.23 +do_expr_test e_expr-29.2.2 { CAST('1.45.23abcd' AS REAL) } real 1.45 +do_expr_test e_expr-29.2.3 { CAST('-2.12e-01ABC' AS REAL) } real -0.212 +do_expr_test e_expr-29.2.4 { CAST('1 2 3 4' AS REAL) } real 1.0 + +# EVIDENCE-OF: R-11321-47427 Any leading spaces in the TEXT value are +# ignored when converging from TEXT to REAL. +# +do_expr_test e_expr-29.3.1 { CAST(' 1.23abcd' AS REAL) } real 1.23 +do_expr_test e_expr-29.3.2 { CAST(' 1.45.23abcd' AS REAL) } real 1.45 +do_expr_test e_expr-29.3.3 { CAST(' -2.12e-01ABC' AS REAL) } real -0.212 +do_expr_test e_expr-29.3.4 { CAST(' 1 2 3 4' AS REAL) } real 1.0 + +# EVIDENCE-OF: R-22662-28218 If there is no prefix that can be +# interpreted as a real number, the result of the conversion is 0.0. +# +do_expr_test e_expr-29.4.1 { CAST('' AS REAL) } real 0.0 +do_expr_test e_expr-29.4.2 { CAST('not a number' AS REAL) } real 0.0 +do_expr_test e_expr-29.4.3 { CAST('XXI' AS REAL) } real 0.0 + +# EVIDENCE-OF: R-21829-14563 When casting a BLOB value to INTEGER, the +# value is first converted to TEXT. +# +do_expr_test e_expr-30.1.1 { CAST(X'313233' AS INTEGER) } integer 123 +do_expr_test e_expr-30.1.2 { CAST(X'2D363738' AS INTEGER) } integer -678 +do_expr_test e_expr-30.1.3 { + CAST(X'31303030303030' AS INTEGER) +} integer 1000000 +do_expr_test e_expr-30.1.4 { + CAST(X'2D31313235383939393036383432363234' AS INTEGER) +} integer -1125899906842624 + +rename db db2 +sqlite3 db :memory: +ifcapable {utf16} { +execsql { PRAGMA encoding = 'utf-16be' } +do_expr_test e_expr-30.1.5 { CAST(X'003100320033' AS INTEGER) } integer 123 +do_expr_test e_expr-30.1.6 { CAST(X'002D003600370038' AS INTEGER) } integer -678 +do_expr_test e_expr-30.1.7 { + CAST(X'0031003000300030003000300030' AS INTEGER) +} integer 1000000 +do_expr_test e_expr-30.1.8 { + CAST(X'002D0031003100320035003800390039003900300036003800340032003600320034' AS INTEGER) +} integer -1125899906842624 +} +db close +rename db2 db + +# EVIDENCE-OF: R-47612-45842 When casting a TEXT value to INTEGER, the +# longest possible prefix of the value that can be interpreted as an +# integer number is extracted from the TEXT value and the remainder +# ignored. +# +do_expr_test e_expr-30.2.1 { CAST('123abcd' AS INT) } integer 123 +do_expr_test e_expr-30.2.2 { CAST('14523abcd' AS INT) } integer 14523 +do_expr_test e_expr-30.2.3 { CAST('-2.12e-01ABC' AS INT) } integer -2 +do_expr_test e_expr-30.2.4 { CAST('1 2 3 4' AS INT) } integer 1 + +# EVIDENCE-OF: R-34400-33772 Any leading spaces in the TEXT value when +# converting from TEXT to INTEGER are ignored. +# +do_expr_test e_expr-30.3.1 { CAST(' 123abcd' AS INT) } integer 123 +do_expr_test e_expr-30.3.2 { CAST(' 14523abcd' AS INT) } integer 14523 +do_expr_test e_expr-30.3.3 { CAST(' -2.12e-01ABC' AS INT) } integer -2 +do_expr_test e_expr-30.3.4 { CAST(' 1 2 3 4' AS INT) } integer 1 + +# EVIDENCE-OF: R-43164-44276 If there is no prefix that can be +# interpreted as an integer number, the result of the conversion is 0. +# +do_expr_test e_expr-30.4.1 { CAST('' AS INTEGER) } integer 0 +do_expr_test e_expr-30.4.2 { CAST('not a number' AS INTEGER) } integer 0 +do_expr_test e_expr-30.4.3 { CAST('XXI' AS INTEGER) } integer 0 + +# EVIDENCE-OF: R-00741-38776 A cast of a REAL value into an INTEGER will +# truncate the fractional part of the REAL. +# +do_expr_test e_expr-31.1.1 { CAST(3.14159 AS INTEGER) } integer 3 +do_expr_test e_expr-31.1.2 { CAST(1.99999 AS INTEGER) } integer 1 +do_expr_test e_expr-31.1.3 { CAST(-1.99999 AS INTEGER) } integer -1 +do_expr_test e_expr-31.1.4 { CAST(-0.99999 AS INTEGER) } integer 0 + +# EVIDENCE-OF: R-49503-28105 If a REAL is too large to be represented as +# an INTEGER then the result of the cast is the largest negative +# integer: -9223372036854775808. +# +do_expr_test e_expr-31.2.1 { CAST(2e+50 AS INT) } integer -9223372036854775808 +do_expr_test e_expr-31.2.2 { CAST(-2e+50 AS INT) } integer -9223372036854775808 +do_expr_test e_expr-31.2.3 { + CAST(-9223372036854775809.0 AS INT) +} integer -9223372036854775808 +do_expr_test e_expr-31.2.4 { + CAST(9223372036854775809.0 AS INT) +} integer -9223372036854775808 + + +# EVIDENCE-OF: R-09295-61337 Casting a TEXT or BLOB value into NUMERIC +# first does a forced conversion into REAL but then further converts the +# result into INTEGER if and only if the conversion from REAL to INTEGER +# is lossless and reversible. +# +do_expr_test e_expr-32.1.1 { CAST('45' AS NUMERIC) } integer 45 +do_expr_test e_expr-32.1.2 { CAST('45.0' AS NUMERIC) } integer 45 +do_expr_test e_expr-32.1.3 { CAST('45.2' AS NUMERIC) } real 45.2 +do_expr_test e_expr-32.1.4 { CAST('11abc' AS NUMERIC) } integer 11 +do_expr_test e_expr-32.1.5 { CAST('11.1abc' AS NUMERIC) } real 11.1 + +# EVIDENCE-OF: R-30347-18702 Casting a REAL or INTEGER value to NUMERIC +# is a no-op, even if a real value could be losslessly converted to an +# integer. +# +do_expr_test e_expr-32.2.1 { CAST(13.0 AS NUMERIC) } real 13.0 +do_expr_test e_expr-32.2.2 { CAST(13.5 AS NUMERIC) } real 13.5 + +do_expr_test e_expr-32.2.3 { + CAST(-9223372036854775808 AS NUMERIC) +} integer -9223372036854775808 +do_expr_test e_expr-32.2.4 { + CAST(9223372036854775807 AS NUMERIC) +} integer 9223372036854775807 + +# EVIDENCE-OF: R-64550-29191 Note that the result from casting any +# non-BLOB value into a BLOB and the result from casting any BLOB value +# into a non-BLOB value may be different depending on whether the +# database encoding is UTF-8, UTF-16be, or UTF-16le. +# +ifcapable {utf16} { +sqlite3 db1 :memory: ; db1 eval { PRAGMA encoding = 'utf-8' } +sqlite3 db2 :memory: ; db2 eval { PRAGMA encoding = 'utf-16le' } +sqlite3 db3 :memory: ; db3 eval { PRAGMA encoding = 'utf-16be' } +foreach {tn castexpr differs} { + 1 { CAST(123 AS BLOB) } 1 + 2 { CAST('' AS BLOB) } 0 + 3 { CAST('abcd' AS BLOB) } 1 + + 4 { CAST(X'abcd' AS TEXT) } 1 + 5 { CAST(X'' AS TEXT) } 0 +} { + set r1 [db1 eval "SELECT typeof($castexpr), quote($castexpr)"] + set r2 [db2 eval "SELECT typeof($castexpr), quote($castexpr)"] + set r3 [db3 eval "SELECT typeof($castexpr), quote($castexpr)"] + + if {$differs} { + set res [expr {$r1!=$r2 && $r2!=$r3}] + } else { + set res [expr {$r1==$r2 && $r2==$r3}] + } + + do_test e_expr-33.1.$tn {set res} 1 +} +db1 close +db2 close +db3 close +} + +#------------------------------------------------------------------------- +# Test statements related to the EXISTS and NOT EXISTS operators. +# +catch { db close } +forcedelete test.db +sqlite3 db test.db + +do_execsql_test e_expr-34.1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(NULL, 2); + INSERT INTO t1 VALUES(1, NULL); + INSERT INTO t1 VALUES(NULL, NULL); +} {} + +# EVIDENCE-OF: R-25588-27181 The EXISTS operator always evaluates to one +# of the integer values 0 and 1. +# +# This statement is not tested by itself. Instead, all e_expr-34.* tests +# following this point explicitly test that specific invocations of EXISTS +# return either integer 0 or integer 1. +# + +# EVIDENCE-OF: R-58553-63740 If executing the SELECT statement specified +# as the right-hand operand of the EXISTS operator would return one or +# more rows, then the EXISTS operator evaluates to 1. +# +foreach {tn expr} { + 1 { EXISTS ( SELECT a FROM t1 ) } + 2 { EXISTS ( SELECT b FROM t1 ) } + 3 { EXISTS ( SELECT 24 ) } + 4 { EXISTS ( SELECT NULL ) } + 5 { EXISTS ( SELECT a FROM t1 WHERE a IS NULL ) } +} { + do_expr_test e_expr-34.2.$tn $expr integer 1 +} + +# EVIDENCE-OF: R-19673-40972 If executing the SELECT would return no +# rows at all, then the EXISTS operator evaluates to 0. +# +foreach {tn expr} { + 1 { EXISTS ( SELECT a FROM t1 WHERE 0) } + 2 { EXISTS ( SELECT b FROM t1 WHERE a = 5) } + 3 { EXISTS ( SELECT 24 WHERE 0) } + 4 { EXISTS ( SELECT NULL WHERE 1=2) } +} { + do_expr_test e_expr-34.3.$tn $expr integer 0 +} + +# EVIDENCE-OF: R-35109-49139 The number of columns in each row returned +# by the SELECT statement (if any) and the specific values returned have +# no effect on the results of the EXISTS operator. +# +foreach {tn expr res} { + 1 { EXISTS ( SELECT * FROM t1 ) } 1 + 2 { EXISTS ( SELECT *, *, * FROM t1 ) } 1 + 3 { EXISTS ( SELECT 24, 25 ) } 1 + 4 { EXISTS ( SELECT NULL, NULL, NULL ) } 1 + 5 { EXISTS ( SELECT a,b,a||b FROM t1 WHERE a IS NULL ) } 1 + + 6 { EXISTS ( SELECT a, a FROM t1 WHERE 0) } 0 + 7 { EXISTS ( SELECT b, b, a FROM t1 WHERE a = 5) } 0 + 8 { EXISTS ( SELECT 24, 46, 89 WHERE 0) } 0 + 9 { EXISTS ( SELECT NULL, NULL WHERE 1=2) } 0 +} { + do_expr_test e_expr-34.4.$tn $expr integer $res +} + +# EVIDENCE-OF: R-10645-12439 In particular, rows containing NULL values +# are not handled any differently from rows without NULL values. +# +foreach {tn e1 e2} { + 1 { EXISTS (SELECT 'not null') } { EXISTS (SELECT NULL) } + 2 { EXISTS (SELECT NULL FROM t1) } { EXISTS (SELECT 'bread' FROM t1) } +} { + set res [db one "SELECT $e1"] + do_expr_test e_expr-34.5.${tn}a $e1 integer $res + do_expr_test e_expr-34.5.${tn}b $e2 integer $res +} + +#------------------------------------------------------------------------- +# Test statements related to scalar sub-queries. +# + +catch { db close } +forcedelete test.db +sqlite3 db test.db +do_test e_expr-35.0 { + execsql { + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES('one', 'two'); + INSERT INTO t2 VALUES('three', NULL); + INSERT INTO t2 VALUES(4, 5.0); + } +} {} + +# EVIDENCE-OF: R-00980-39256 A SELECT statement enclosed in parentheses +# may appear as a scalar quantity. +# +# EVIDENCE-OF: R-56294-03966 All types of SELECT statement, including +# aggregate and compound SELECT queries (queries with keywords like +# UNION or EXCEPT) are allowed as scalar subqueries. +# +do_expr_test e_expr-35.1.1 { (SELECT 35) } integer 35 +do_expr_test e_expr-35.1.2 { (SELECT NULL) } null {} + +do_expr_test e_expr-35.1.3 { (SELECT count(*) FROM t2) } integer 3 +do_expr_test e_expr-35.1.4 { (SELECT 4 FROM t2) } integer 4 + +do_expr_test e_expr-35.1.5 { + (SELECT b FROM t2 UNION SELECT a+1 FROM t2) +} null {} +do_expr_test e_expr-35.1.6 { + (SELECT a FROM t2 UNION SELECT COALESCE(b, 55) FROM t2 ORDER BY 1) +} integer 4 + +# EVIDENCE-OF: R-46899-53765 A SELECT used as a scalar quantity must +# return a result set with a single column. +# +# The following block tests that errors are returned in a bunch of cases +# where a subquery returns more than one column. +# +set M {only a single result allowed for a SELECT that is part of an expression} +foreach {tn sql} { + 1 { SELECT (SELECT * FROM t2 UNION SELECT a+1, b+1 FROM t2) } + 2 { SELECT (SELECT * FROM t2 UNION SELECT a+1, b+1 FROM t2 ORDER BY 1) } + 3 { SELECT (SELECT 1, 2) } + 4 { SELECT (SELECT NULL, NULL, NULL) } + 5 { SELECT (SELECT * FROM t2) } + 6 { SELECT (SELECT * FROM (SELECT 1, 2, 3)) } +} { + do_catchsql_test e_expr-35.2.$tn $sql [list 1 $M] +} + +# EVIDENCE-OF: R-35764-28041 The result of the expression is the value +# of the only column in the first row returned by the SELECT statement. +# +# EVIDENCE-OF: R-41898-06686 If the SELECT yields more than one result +# row, all rows after the first are ignored. +# +do_execsql_test e_expr-36.3.1 { + CREATE TABLE t4(x, y); + INSERT INTO t4 VALUES(1, 'one'); + INSERT INTO t4 VALUES(2, 'two'); + INSERT INTO t4 VALUES(3, 'three'); +} {} + +foreach {tn expr restype resval} { + 2 { ( SELECT x FROM t4 ORDER BY x ) } integer 1 + 3 { ( SELECT x FROM t4 ORDER BY y ) } integer 1 + 4 { ( SELECT x FROM t4 ORDER BY x DESC ) } integer 3 + 5 { ( SELECT x FROM t4 ORDER BY y DESC ) } integer 2 + 6 { ( SELECT y FROM t4 ORDER BY y DESC ) } text two + + 7 { ( SELECT sum(x) FROM t4 ) } integer 6 + 8 { ( SELECT group_concat(y,'') FROM t4 ) } text onetwothree + 9 { ( SELECT max(x) FROM t4 WHERE y LIKE '___') } integer 2 + +} { + do_expr_test e_expr-36.3.$tn $expr $restype $resval +} + +# EVIDENCE-OF: R-25492-41572 If the SELECT yields no rows, then the +# value of the expression is NULL. +# +foreach {tn expr} { + 1 { ( SELECT x FROM t4 WHERE x>3 ORDER BY x ) } + 2 { ( SELECT x FROM t4 WHERE y<'one' ORDER BY y ) } +} { + do_expr_test e_expr-36.4.$tn $expr null {} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_fkey.test b/components/external/SQLite-3.8.1/test/e_fkey.test new file mode 100644 index 0000000000000000000000000000000000000000..976ed16325e8e6f4281505219a52c2abac7f7c1a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_fkey.test @@ -0,0 +1,3015 @@ +# 2009 October 7 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify the "testable statements" in the +# foreignkeys.in document. +# +# The tests in this file are arranged to mirror the structure of +# foreignkey.in, with one exception: The statements in section 2, which +# deals with enabling/disabling foreign key support, is tested first, +# before section 1. This is because some statements in section 2 deal +# with builds that do not include complete foreign key support (because +# either SQLITE_OMIT_TRIGGER or SQLITE_OMIT_FOREIGN_KEY was defined +# at build time). +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc eqp {sql {db db}} { uplevel execsql [list "EXPLAIN QUERY PLAN $sql"] $db } + +########################################################################### +### SECTION 2: Enabling Foreign Key Support +########################################################################### + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-33710-56344 In order to use foreign key constraints in +# SQLite, the library must be compiled with neither +# SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER defined. +# +ifcapable trigger&&foreignkey { + do_test e_fkey-1 { + execsql { + PRAGMA foreign_keys = ON; + CREATE TABLE p(i PRIMARY KEY); + CREATE TABLE c(j REFERENCES p ON UPDATE CASCADE); + INSERT INTO p VALUES('hello'); + INSERT INTO c VALUES('hello'); + UPDATE p SET i = 'world'; + SELECT * FROM c; + } + } {world} +} + +#------------------------------------------------------------------------- +# Test the effects of defining OMIT_TRIGGER but not OMIT_FOREIGN_KEY. +# +# EVIDENCE-OF: R-44697-61543 If SQLITE_OMIT_TRIGGER is defined but +# SQLITE_OMIT_FOREIGN_KEY is not, then SQLite behaves as it did prior to +# version 3.6.19 - foreign key definitions are parsed and may be queried +# using PRAGMA foreign_key_list, but foreign key constraints are not +# enforced. +# +# Specifically, test that "PRAGMA foreign_keys" is a no-op in this case. +# When using the pragma to query the current setting, 0 rows are returned. +# +# EVIDENCE-OF: R-22567-44039 The PRAGMA foreign_keys command is a no-op +# in this configuration. +# +# EVIDENCE-OF: R-41784-13339 Tip: If the command "PRAGMA foreign_keys" +# returns no data instead of a single row containing "0" or "1", then +# the version of SQLite you are using does not support foreign keys +# (either because it is older than 3.6.19 or because it was compiled +# with SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER defined). +# +reset_db +ifcapable !trigger&&foreignkey { + do_test e_fkey-2.1 { + execsql { + PRAGMA foreign_keys = ON; + CREATE TABLE p(i PRIMARY KEY); + CREATE TABLE c(j REFERENCES p ON UPDATE CASCADE); + INSERT INTO p VALUES('hello'); + INSERT INTO c VALUES('hello'); + UPDATE p SET i = 'world'; + SELECT * FROM c; + } + } {hello} + do_test e_fkey-2.2 { + execsql { PRAGMA foreign_key_list(c) } + } {0 0 p j {} CASCADE {NO ACTION} NONE} + do_test e_fkey-2.3 { + execsql { PRAGMA foreign_keys } + } {} +} + + +#------------------------------------------------------------------------- +# Test the effects of defining OMIT_FOREIGN_KEY. +# +# EVIDENCE-OF: R-58428-36660 If OMIT_FOREIGN_KEY is defined, then +# foreign key definitions cannot even be parsed (attempting to specify a +# foreign key definition is a syntax error). +# +# Specifically, test that foreign key constraints cannot even be parsed +# in such a build. +# +reset_db +ifcapable !foreignkey { + do_test e_fkey-3.1 { + execsql { CREATE TABLE p(i PRIMARY KEY) } + catchsql { CREATE TABLE c(j REFERENCES p ON UPDATE CASCADE) } + } {1 {near "ON": syntax error}} + do_test e_fkey-3.2 { + # This is allowed, as in this build, "REFERENCES" is not a keyword. + # The declared datatype of column j is "REFERENCES p". + execsql { CREATE TABLE c(j REFERENCES p) } + } {} + do_test e_fkey-3.3 { + execsql { PRAGMA table_info(c) } + } {0 j {REFERENCES p} 0 {} 0} + do_test e_fkey-3.4 { + execsql { PRAGMA foreign_key_list(c) } + } {} + do_test e_fkey-3.5 { + execsql { PRAGMA foreign_keys } + } {} +} + +ifcapable !foreignkey||!trigger { finish_test ; return } +reset_db + + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-07280-60510 Assuming the library is compiled with +# foreign key constraints enabled, it must still be enabled by the +# application at runtime, using the PRAGMA foreign_keys command. +# +# This also tests that foreign key constraints are disabled by default. +# +# EVIDENCE-OF: R-59578-04990 Foreign key constraints are disabled by +# default (for backwards compatibility), so must be enabled separately +# for each database connection separately. +# +drop_all_tables +do_test e_fkey-4.1 { + execsql { + CREATE TABLE p(i PRIMARY KEY); + CREATE TABLE c(j REFERENCES p ON UPDATE CASCADE); + INSERT INTO p VALUES('hello'); + INSERT INTO c VALUES('hello'); + UPDATE p SET i = 'world'; + SELECT * FROM c; + } +} {hello} +do_test e_fkey-4.2 { + execsql { + DELETE FROM c; + DELETE FROM p; + PRAGMA foreign_keys = ON; + INSERT INTO p VALUES('hello'); + INSERT INTO c VALUES('hello'); + UPDATE p SET i = 'world'; + SELECT * FROM c; + } +} {world} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-15278-54456 The application can can also use a PRAGMA +# foreign_keys statement to determine if foreign keys are currently +# enabled. +# +# This also tests the example code in section 2 of foreignkeys.in. +# +# EVIDENCE-OF: R-11255-19907 +# +reset_db +do_test e_fkey-5.1 { + execsql { PRAGMA foreign_keys } +} {0} +do_test e_fkey-5.2 { + execsql { + PRAGMA foreign_keys = ON; + PRAGMA foreign_keys; + } +} {1} +do_test e_fkey-5.3 { + execsql { + PRAGMA foreign_keys = OFF; + PRAGMA foreign_keys; + } +} {0} + +#------------------------------------------------------------------------- +# Test that it is not possible to enable or disable foreign key support +# while not in auto-commit mode. +# +# EVIDENCE-OF: R-46649-58537 It is not possible to enable or disable +# foreign key constraints in the middle of a multi-statement transaction +# (when SQLite is not in autocommit mode). Attempting to do so does not +# return an error; it simply has no effect. +# +reset_db +do_test e_fkey-6.1 { + execsql { + PRAGMA foreign_keys = ON; + CREATE TABLE t1(a UNIQUE, b); + CREATE TABLE t2(c, d REFERENCES t1(a)); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t2 VALUES(2, 1); + BEGIN; + PRAGMA foreign_keys = OFF; + } + catchsql { + DELETE FROM t1 + } +} {1 {foreign key constraint failed}} +do_test e_fkey-6.2 { + execsql { PRAGMA foreign_keys } +} {1} +do_test e_fkey-6.3 { + execsql { + COMMIT; + PRAGMA foreign_keys = OFF; + BEGIN; + PRAGMA foreign_keys = ON; + DELETE FROM t1; + PRAGMA foreign_keys; + } +} {0} +do_test e_fkey-6.4 { + execsql COMMIT +} {} + +########################################################################### +### SECTION 1: Introduction to Foreign Key Constraints +########################################################################### +execsql "PRAGMA foreign_keys = ON" + +#------------------------------------------------------------------------- +# Verify that the syntax in the first example in section 1 is valid. +# +# EVIDENCE-OF: R-04042-24825 To do so, a foreign key definition may be +# added by modifying the declaration of the track table to the +# following: CREATE TABLE track( trackid INTEGER, trackname TEXT, +# trackartist INTEGER, FOREIGN KEY(trackartist) REFERENCES +# artist(artistid) ); +# +do_test e_fkey-7.1 { + execsql { + CREATE TABLE artist( + artistid INTEGER PRIMARY KEY, + artistname TEXT + ); + CREATE TABLE track( + trackid INTEGER, + trackname TEXT, + trackartist INTEGER, + FOREIGN KEY(trackartist) REFERENCES artist(artistid) + ); + } +} {} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-61362-32087 Attempting to insert a row into the track +# table that does not correspond to any row in the artist table will +# fail, +# +do_test e_fkey-8.1 { + catchsql { INSERT INTO track VALUES(1, 'track 1', 1) } +} {1 {foreign key constraint failed}} +do_test e_fkey-8.2 { + execsql { INSERT INTO artist VALUES(2, 'artist 1') } + catchsql { INSERT INTO track VALUES(1, 'track 1', 1) } +} {1 {foreign key constraint failed}} +do_test e_fkey-8.2 { + execsql { INSERT INTO track VALUES(1, 'track 1', 2) } +} {} + +#------------------------------------------------------------------------- +# Attempting to delete a row from the 'artist' table while there are +# dependent rows in the track table also fails. +# +# EVIDENCE-OF: R-24401-52400 as will attempting to delete a row from the +# artist table when there exist dependent rows in the track table +# +do_test e_fkey-9.1 { + catchsql { DELETE FROM artist WHERE artistid = 2 } +} {1 {foreign key constraint failed}} +do_test e_fkey-9.2 { + execsql { + DELETE FROM track WHERE trackartist = 2; + DELETE FROM artist WHERE artistid = 2; + } +} {} + +#------------------------------------------------------------------------- +# If the foreign key column (trackartist) in table 'track' is set to NULL, +# there is no requirement for a matching row in the 'artist' table. +# +# EVIDENCE-OF: R-23980-48859 There is one exception: if the foreign key +# column in the track table is NULL, then no corresponding entry in the +# artist table is required. +# +do_test e_fkey-10.1 { + execsql { + INSERT INTO track VALUES(1, 'track 1', NULL); + INSERT INTO track VALUES(2, 'track 2', NULL); + } +} {} +do_test e_fkey-10.2 { + execsql { SELECT * FROM artist } +} {} +do_test e_fkey-10.3 { + # Setting the trackid to a non-NULL value fails, of course. + catchsql { UPDATE track SET trackartist = 5 WHERE trackid = 1 } +} {1 {foreign key constraint failed}} +do_test e_fkey-10.4 { + execsql { + INSERT INTO artist VALUES(5, 'artist 5'); + UPDATE track SET trackartist = 5 WHERE trackid = 1; + } + catchsql { DELETE FROM artist WHERE artistid = 5} +} {1 {foreign key constraint failed}} +do_test e_fkey-10.5 { + execsql { + UPDATE track SET trackartist = NULL WHERE trackid = 1; + DELETE FROM artist WHERE artistid = 5; + } +} {} + +#------------------------------------------------------------------------- +# Test that the following is true fo all rows in the track table: +# +# trackartist IS NULL OR +# EXISTS(SELECT 1 FROM artist WHERE artistid=trackartist) +# +# EVIDENCE-OF: R-52486-21352 Expressed in SQL, this means that for every +# row in the track table, the following expression evaluates to true: +# trackartist IS NULL OR EXISTS(SELECT 1 FROM artist WHERE +# artistid=trackartist) + +# This procedure executes a test case to check that statement +# R-52486-21352 is true after executing the SQL statement passed. +# as the second argument. +proc test_r52486_21352 {tn sql} { + set res [catchsql $sql] + set results { + {0 {}} + {1 {PRIMARY KEY must be unique}} + {1 {foreign key constraint failed}} + } + if {[lsearch $results $res]<0} { + error $res + } + + do_test e_fkey-11.$tn { + execsql { + SELECT count(*) FROM track WHERE NOT ( + trackartist IS NULL OR + EXISTS(SELECT 1 FROM artist WHERE artistid=trackartist) + ) + } + } {0} +} + +# Execute a series of random INSERT, UPDATE and DELETE operations +# (some of which may fail due to FK or PK constraint violations) on +# the two tables in the example schema. Test that R-52486-21352 +# is true after executing each operation. +# +set Template { + {INSERT INTO track VALUES($t, 'track $t', $a)} + {DELETE FROM track WHERE trackid = $t} + {UPDATE track SET trackartist = $a WHERE trackid = $t} + {INSERT INTO artist VALUES($a, 'artist $a')} + {DELETE FROM artist WHERE artistid = $a} + {UPDATE artist SET artistid = $a2 WHERE artistid = $a} +} +for {set i 0} {$i < 500} {incr i} { + set a [expr int(rand()*10)] + set a2 [expr int(rand()*10)] + set t [expr int(rand()*50)] + set sql [subst [lindex $Template [expr int(rand()*6)]]] + + test_r52486_21352 $i $sql +} + +#------------------------------------------------------------------------- +# Check that a NOT NULL constraint can be added to the example schema +# to prohibit NULL child keys from being inserted. +# +# EVIDENCE-OF: R-42412-59321 Tip: If the application requires a stricter +# relationship between artist and track, where NULL values are not +# permitted in the trackartist column, simply add the appropriate "NOT +# NULL" constraint to the schema. +# +drop_all_tables +do_test e_fkey-12.1 { + execsql { + CREATE TABLE artist( + artistid INTEGER PRIMARY KEY, + artistname TEXT + ); + CREATE TABLE track( + trackid INTEGER, + trackname TEXT, + trackartist INTEGER NOT NULL, + FOREIGN KEY(trackartist) REFERENCES artist(artistid) + ); + } +} {} +do_test e_fkey-12.2 { + catchsql { INSERT INTO track VALUES(14, 'Mr. Bojangles', NULL) } +} {1 {track.trackartist may not be NULL}} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-16127-35442 +# +# Test an example from foreignkeys.html. +# +drop_all_tables +do_test e_fkey-13.1 { + execsql { + CREATE TABLE artist( + artistid INTEGER PRIMARY KEY, + artistname TEXT + ); + CREATE TABLE track( + trackid INTEGER, + trackname TEXT, + trackartist INTEGER, + FOREIGN KEY(trackartist) REFERENCES artist(artistid) + ); + INSERT INTO artist VALUES(1, 'Dean Martin'); + INSERT INTO artist VALUES(2, 'Frank Sinatra'); + INSERT INTO track VALUES(11, 'That''s Amore', 1); + INSERT INTO track VALUES(12, 'Christmas Blues', 1); + INSERT INTO track VALUES(13, 'My Way', 2); + } +} {} +do_test e_fkey-13.2 { + catchsql { INSERT INTO track VALUES(14, 'Mr. Bojangles', 3) } +} {1 {foreign key constraint failed}} +do_test e_fkey-13.3 { + execsql { INSERT INTO track VALUES(14, 'Mr. Bojangles', NULL) } +} {} +do_test e_fkey-13.4 { + catchsql { + UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles'; + } +} {1 {foreign key constraint failed}} +do_test e_fkey-13.5 { + execsql { + INSERT INTO artist VALUES(3, 'Sammy Davis Jr.'); + UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles'; + INSERT INTO track VALUES(15, 'Boogie Woogie', 3); + } +} {} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-15958-50233 +# +# Test the second example from the first section of foreignkeys.html. +# +do_test e_fkey-14.1 { + catchsql { + DELETE FROM artist WHERE artistname = 'Frank Sinatra'; + } +} {1 {foreign key constraint failed}} +do_test e_fkey-14.2 { + execsql { + DELETE FROM track WHERE trackname = 'My Way'; + DELETE FROM artist WHERE artistname = 'Frank Sinatra'; + } +} {} +do_test e_fkey-14.3 { + catchsql { + UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin'; + } +} {1 {foreign key constraint failed}} +do_test e_fkey-14.4 { + execsql { + DELETE FROM track WHERE trackname IN('That''s Amore', 'Christmas Blues'); + UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin'; + } +} {} + + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-56032-24923 The foreign key constraint is satisfied if +# for each row in the child table either one or more of the child key +# columns are NULL, or there exists a row in the parent table for which +# each parent key column contains a value equal to the value in its +# associated child key column. +# +# Test also that the usual comparison rules are used when testing if there +# is a matching row in the parent table of a foreign key constraint. +# +# EVIDENCE-OF: R-57765-12380 In the above paragraph, the term "equal" +# means equal when values are compared using the rules specified here. +# +drop_all_tables +do_test e_fkey-15.1 { + execsql { + CREATE TABLE par(p PRIMARY KEY); + CREATE TABLE chi(c REFERENCES par); + + INSERT INTO par VALUES(1); + INSERT INTO par VALUES('1'); + INSERT INTO par VALUES(X'31'); + SELECT typeof(p) FROM par; + } +} {integer text blob} + +proc test_efkey_45 {tn isError sql} { + do_test e_fkey-15.$tn.1 " + catchsql {$sql} + " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] + + do_test e_fkey-15.$tn.2 { + execsql { + SELECT * FROM chi WHERE c IS NOT NULL AND c NOT IN (SELECT p FROM par) + } + } {} +} + +test_efkey_45 1 0 "INSERT INTO chi VALUES(1)" +test_efkey_45 2 1 "INSERT INTO chi VALUES('1.0')" +test_efkey_45 3 0 "INSERT INTO chi VALUES('1')" +test_efkey_45 4 1 "DELETE FROM par WHERE p = '1'" +test_efkey_45 5 0 "DELETE FROM chi WHERE c = '1'" +test_efkey_45 6 0 "DELETE FROM par WHERE p = '1'" +test_efkey_45 7 1 "INSERT INTO chi VALUES('1')" +test_efkey_45 8 0 "INSERT INTO chi VALUES(X'31')" +test_efkey_45 9 1 "INSERT INTO chi VALUES(X'32')" + +#------------------------------------------------------------------------- +# Specifically, test that when comparing child and parent key values the +# default collation sequence of the parent key column is used. +# +# EVIDENCE-OF: R-15796-47513 When comparing text values, the collating +# sequence associated with the parent key column is always used. +# +drop_all_tables +do_test e_fkey-16.1 { + execsql { + CREATE TABLE t1(a COLLATE nocase PRIMARY KEY); + CREATE TABLE t2(b REFERENCES t1); + } +} {} +do_test e_fkey-16.2 { + execsql { + INSERT INTO t1 VALUES('oNe'); + INSERT INTO t2 VALUES('one'); + INSERT INTO t2 VALUES('ONE'); + UPDATE t2 SET b = 'OnE'; + UPDATE t1 SET a = 'ONE'; + } +} {} +do_test e_fkey-16.3 { + catchsql { UPDATE t2 SET b = 'two' WHERE rowid = 1 } +} {1 {foreign key constraint failed}} +do_test e_fkey-16.4 { + catchsql { DELETE FROM t1 WHERE rowid = 1 } +} {1 {foreign key constraint failed}} + +#------------------------------------------------------------------------- +# Specifically, test that when comparing child and parent key values the +# affinity of the parent key column is applied to the child key value +# before the comparison takes place. +# +# EVIDENCE-OF: R-04240-13860 When comparing values, if the parent key +# column has an affinity, then that affinity is applied to the child key +# value before the comparison is performed. +# +drop_all_tables +do_test e_fkey-17.1 { + execsql { + CREATE TABLE t1(a NUMERIC PRIMARY KEY); + CREATE TABLE t2(b TEXT REFERENCES t1); + } +} {} +do_test e_fkey-17.2 { + execsql { + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES('three'); + INSERT INTO t2 VALUES('2.0'); + SELECT b, typeof(b) FROM t2; + } +} {2.0 text} +do_test e_fkey-17.3 { + execsql { SELECT typeof(a) FROM t1 } +} {integer integer text} +do_test e_fkey-17.4 { + catchsql { DELETE FROM t1 WHERE rowid = 2 } +} {1 {foreign key constraint failed}} + +########################################################################### +### SECTION 3: Required and Suggested Database Indexes +########################################################################### + +#------------------------------------------------------------------------- +# A parent key must be either a PRIMARY KEY, subject to a UNIQUE +# constraint, or have a UNIQUE index created on it. +# +# EVIDENCE-OF: R-13435-26311 Usually, the parent key of a foreign key +# constraint is the primary key of the parent table. If they are not the +# primary key, then the parent key columns must be collectively subject +# to a UNIQUE constraint or have a UNIQUE index. +# +# Also test that if a parent key is not subject to a PRIMARY KEY or UNIQUE +# constraint, but does have a UNIQUE index created on it, then the UNIQUE index +# must use the default collation sequences associated with the parent key +# columns. +# +# EVIDENCE-OF: R-00376-39212 If the parent key columns have a UNIQUE +# index, then that index must use the collation sequences that are +# specified in the CREATE TABLE statement for the parent table. +# +drop_all_tables +do_test e_fkey-18.1 { + execsql { + CREATE TABLE t2(a REFERENCES t1(x)); + } +} {} +proc test_efkey_57 {tn isError sql} { + catchsql { DROP TABLE t1 } + execsql $sql + do_test e_fkey-18.$tn { + catchsql { INSERT INTO t2 VALUES(NULL) } + } [lindex {{0 {}} {/1 {foreign key mismatch - ".*" referencing ".*"}/}} \ + $isError] +} +test_efkey_57 2 0 { CREATE TABLE t1(x PRIMARY KEY) } +test_efkey_57 3 0 { CREATE TABLE t1(x UNIQUE) } +test_efkey_57 4 0 { CREATE TABLE t1(x); CREATE UNIQUE INDEX t1i ON t1(x) } +test_efkey_57 5 1 { + CREATE TABLE t1(x); + CREATE UNIQUE INDEX t1i ON t1(x COLLATE nocase); +} +test_efkey_57 6 1 { CREATE TABLE t1(x) } +test_efkey_57 7 1 { CREATE TABLE t1(x, y, PRIMARY KEY(x, y)) } +test_efkey_57 8 1 { CREATE TABLE t1(x, y, UNIQUE(x, y)) } +test_efkey_57 9 1 { + CREATE TABLE t1(x, y); + CREATE UNIQUE INDEX t1i ON t1(x, y); +} + + +#------------------------------------------------------------------------- +# This block tests an example in foreignkeys.html. Several testable +# statements refer to this example, as follows +# +# EVIDENCE-OF: R-27484-01467 +# +# FK Constraints on child1, child2 and child3 are Ok. +# +# Problem with FK on child4: +# +# EVIDENCE-OF: R-51039-44840 The foreign key declared as part of table +# child4 is an error because even though the parent key column is +# indexed, the index is not UNIQUE. +# +# Problem with FK on child5: +# +# EVIDENCE-OF: R-01060-48788 The foreign key for table child5 is an +# error because even though the parent key column has a unique index, +# the index uses a different collating sequence. +# +# Problem with FK on child6 and child7: +# +# EVIDENCE-OF: R-63088-37469 Tables child6 and child7 are incorrect +# because while both have UNIQUE indices on their parent keys, the keys +# are not an exact match to the columns of a single UNIQUE index. +# +drop_all_tables +do_test e_fkey-19.1 { + execsql { + CREATE TABLE parent(a PRIMARY KEY, b UNIQUE, c, d, e, f); + CREATE UNIQUE INDEX i1 ON parent(c, d); + CREATE INDEX i2 ON parent(e); + CREATE UNIQUE INDEX i3 ON parent(f COLLATE nocase); + + CREATE TABLE child1(f, g REFERENCES parent(a)); -- Ok + CREATE TABLE child2(h, i REFERENCES parent(b)); -- Ok + CREATE TABLE child3(j, k, FOREIGN KEY(j, k) REFERENCES parent(c, d)); -- Ok + CREATE TABLE child4(l, m REFERENCES parent(e)); -- Err + CREATE TABLE child5(n, o REFERENCES parent(f)); -- Err + CREATE TABLE child6(p, q, FOREIGN KEY(p,q) REFERENCES parent(b, c)); -- Err + CREATE TABLE child7(r REFERENCES parent(c)); -- Err + } +} {} +do_test e_fkey-19.2 { + execsql { + INSERT INTO parent VALUES(1, 2, 3, 4, 5, 6); + INSERT INTO child1 VALUES('xxx', 1); + INSERT INTO child2 VALUES('xxx', 2); + INSERT INTO child3 VALUES(3, 4); + } +} {} +do_test e_fkey-19.2 { + catchsql { INSERT INTO child4 VALUES('xxx', 5) } +} {1 {foreign key mismatch - "child4" referencing "parent"}} +do_test e_fkey-19.3 { + catchsql { INSERT INTO child5 VALUES('xxx', 6) } +} {1 {foreign key mismatch - "child5" referencing "parent"}} +do_test e_fkey-19.4 { + catchsql { INSERT INTO child6 VALUES(2, 3) } +} {1 {foreign key mismatch - "child6" referencing "parent"}} +do_test e_fkey-19.5 { + catchsql { INSERT INTO child7 VALUES(3) } +} {1 {foreign key mismatch - "child7" referencing "parent"}} + +#------------------------------------------------------------------------- +# Test errors in the database schema that are detected while preparing +# DML statements. The error text for these messages always matches +# either "foreign key mismatch" or "no such table*" (using [string match]). +# +# EVIDENCE-OF: R-45488-08504 If the database schema contains foreign key +# errors that require looking at more than one table definition to +# identify, then those errors are not detected when the tables are +# created. +# +# EVIDENCE-OF: R-48391-38472 Instead, such errors prevent the +# application from preparing SQL statements that modify the content of +# the child or parent tables in ways that use the foreign keys. +# +# EVIDENCE-OF: R-03108-63659 The English language error message for +# foreign key DML errors is usually "foreign key mismatch" but can also +# be "no such table" if the parent table does not exist. +# +# EVIDENCE-OF: R-60781-26576 Foreign key DML errors are may be reported +# if: The parent table does not exist, or The parent key columns named +# in the foreign key constraint do not exist, or The parent key columns +# named in the foreign key constraint are not the primary key of the +# parent table and are not subject to a unique constraint using +# collating sequence specified in the CREATE TABLE, or The child table +# references the primary key of the parent without specifying the +# primary key columns and the number of primary key columns in the +# parent do not match the number of child key columns. +# +do_test e_fkey-20.1 { + execsql { + CREATE TABLE c1(c REFERENCES nosuchtable, d); + + CREATE TABLE p2(a, b, UNIQUE(a, b)); + CREATE TABLE c2(c, d, FOREIGN KEY(c, d) REFERENCES p2(a, x)); + + CREATE TABLE p3(a PRIMARY KEY, b); + CREATE TABLE c3(c REFERENCES p3(b), d); + + CREATE TABLE p4(a PRIMARY KEY, b); + CREATE UNIQUE INDEX p4i ON p4(b COLLATE nocase); + CREATE TABLE c4(c REFERENCES p4(b), d); + + CREATE TABLE p5(a PRIMARY KEY, b COLLATE nocase); + CREATE UNIQUE INDEX p5i ON p5(b COLLATE binary); + CREATE TABLE c5(c REFERENCES p5(b), d); + + CREATE TABLE p6(a PRIMARY KEY, b); + CREATE TABLE c6(c, d, FOREIGN KEY(c, d) REFERENCES p6); + + CREATE TABLE p7(a, b, PRIMARY KEY(a, b)); + CREATE TABLE c7(c, d REFERENCES p7); + } +} {} + +foreach {tn tbl ptbl err} { + 2 c1 {} "no such table: main.nosuchtable" + 3 c2 p2 "foreign key mismatch - \"c2\" referencing \"p2\"" + 4 c3 p3 "foreign key mismatch - \"c3\" referencing \"p3\"" + 5 c4 p4 "foreign key mismatch - \"c4\" referencing \"p4\"" + 6 c5 p5 "foreign key mismatch - \"c5\" referencing \"p5\"" + 7 c6 p6 "foreign key mismatch - \"c6\" referencing \"p6\"" + 8 c7 p7 "foreign key mismatch - \"c7\" referencing \"p7\"" +} { + do_test e_fkey-20.$tn.1 { + catchsql "INSERT INTO $tbl VALUES('a', 'b')" + } [list 1 $err] + do_test e_fkey-20.$tn.2 { + catchsql "UPDATE $tbl SET c = ?, d = ?" + } [list 1 $err] + do_test e_fkey-20.$tn.3 { + catchsql "INSERT INTO $tbl SELECT ?, ?" + } [list 1 $err] + + if {$ptbl ne ""} { + do_test e_fkey-20.$tn.4 { + catchsql "DELETE FROM $ptbl" + } [list 1 $err] + do_test e_fkey-20.$tn.5 { + catchsql "UPDATE $ptbl SET a = ?, b = ?" + } [list 1 $err] + do_test e_fkey-20.$tn.6 { + catchsql "INSERT INTO $ptbl SELECT ?, ?" + } [list 1 $err] + } +} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-19353-43643 +# +# Test the example of foreign key mismatch errors caused by implicitly +# mapping a child key to the primary key of the parent table when the +# child key consists of a different number of columns to that primary key. +# +drop_all_tables +do_test e_fkey-21.1 { + execsql { + CREATE TABLE parent2(a, b, PRIMARY KEY(a,b)); + + CREATE TABLE child8(x, y, FOREIGN KEY(x,y) REFERENCES parent2); -- Ok + CREATE TABLE child9(x REFERENCES parent2); -- Err + CREATE TABLE child10(x,y,z, FOREIGN KEY(x,y,z) REFERENCES parent2); -- Err + } +} {} +do_test e_fkey-21.2 { + execsql { + INSERT INTO parent2 VALUES('I', 'II'); + INSERT INTO child8 VALUES('I', 'II'); + } +} {} +do_test e_fkey-21.3 { + catchsql { INSERT INTO child9 VALUES('I') } +} {1 {foreign key mismatch - "child9" referencing "parent2"}} +do_test e_fkey-21.4 { + catchsql { INSERT INTO child9 VALUES('II') } +} {1 {foreign key mismatch - "child9" referencing "parent2"}} +do_test e_fkey-21.5 { + catchsql { INSERT INTO child9 VALUES(NULL) } +} {1 {foreign key mismatch - "child9" referencing "parent2"}} +do_test e_fkey-21.6 { + catchsql { INSERT INTO child10 VALUES('I', 'II', 'III') } +} {1 {foreign key mismatch - "child10" referencing "parent2"}} +do_test e_fkey-21.7 { + catchsql { INSERT INTO child10 VALUES(1, 2, 3) } +} {1 {foreign key mismatch - "child10" referencing "parent2"}} +do_test e_fkey-21.8 { + catchsql { INSERT INTO child10 VALUES(NULL, NULL, NULL) } +} {1 {foreign key mismatch - "child10" referencing "parent2"}} + +#------------------------------------------------------------------------- +# Test errors that are reported when creating the child table. +# Specifically: +# +# * different number of child and parent key columns, and +# * child columns that do not exist. +# +# EVIDENCE-OF: R-23682-59820 By contrast, if foreign key errors can be +# recognized simply by looking at the definition of the child table and +# without having to consult the parent table definition, then the CREATE +# TABLE statement for the child table fails. +# +# These errors are reported whether or not FK support is enabled. +# +# EVIDENCE-OF: R-33883-28833 Foreign key DDL errors are reported +# regardless of whether or not foreign key constraints are enabled when +# the table is created. +# +drop_all_tables +foreach fk [list OFF ON] { + execsql "PRAGMA foreign_keys = $fk" + set i 0 + foreach {sql error} { + "CREATE TABLE child1(a, b, FOREIGN KEY(a, b) REFERENCES p(c))" + {number of columns in foreign key does not match the number of columns in the referenced table} + "CREATE TABLE child2(a, b, FOREIGN KEY(a, b) REFERENCES p(c, d, e))" + {number of columns in foreign key does not match the number of columns in the referenced table} + "CREATE TABLE child2(a, b, FOREIGN KEY(a, c) REFERENCES p(c, d))" + {unknown column "c" in foreign key definition} + "CREATE TABLE child2(a, b, FOREIGN KEY(c, b) REFERENCES p(c, d))" + {unknown column "c" in foreign key definition} + } { + do_test e_fkey-22.$fk.[incr i] { + catchsql $sql + } [list 1 $error] + } +} + +#------------------------------------------------------------------------- +# Test that a REFERENCING clause that does not specify parent key columns +# implicitly maps to the primary key of the parent table. +# +# EVIDENCE-OF: R-43879-08025 Attaching a "REFERENCES " +# clause to a column definition creates a foreign +# key constraint that maps the column to the primary key of +# . +# +do_test e_fkey-23.1 { + execsql { + CREATE TABLE p1(a, b, PRIMARY KEY(a, b)); + CREATE TABLE p2(a, b PRIMARY KEY); + CREATE TABLE c1(c, d, FOREIGN KEY(c, d) REFERENCES p1); + CREATE TABLE c2(a, b REFERENCES p2); + } +} {} +proc test_efkey_60 {tn isError sql} { + do_test e_fkey-23.$tn " + catchsql {$sql} + " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] +} + +test_efkey_60 2 1 "INSERT INTO c1 VALUES(239, 231)" +test_efkey_60 3 0 "INSERT INTO p1 VALUES(239, 231)" +test_efkey_60 4 0 "INSERT INTO c1 VALUES(239, 231)" +test_efkey_60 5 1 "INSERT INTO c2 VALUES(239, 231)" +test_efkey_60 6 0 "INSERT INTO p2 VALUES(239, 231)" +test_efkey_60 7 0 "INSERT INTO c2 VALUES(239, 231)" + +#------------------------------------------------------------------------- +# Test that an index on on the child key columns of an FK constraint +# is optional. +# +# EVIDENCE-OF: R-15417-28014 Indices are not required for child key +# columns +# +# Also test that if an index is created on the child key columns, it does +# not make a difference whether or not it is a UNIQUE index. +# +# EVIDENCE-OF: R-15741-50893 The child key index does not have to be +# (and usually will not be) a UNIQUE index. +# +drop_all_tables +do_test e_fkey-24.1 { + execsql { + CREATE TABLE parent(x, y, UNIQUE(y, x)); + CREATE TABLE c1(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y)); + CREATE TABLE c2(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y)); + CREATE TABLE c3(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y)); + CREATE INDEX c2i ON c2(a, b); + CREATE UNIQUE INDEX c3i ON c2(b, a); + } +} {} +proc test_efkey_61 {tn isError sql} { + do_test e_fkey-24.$tn " + catchsql {$sql} + " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] +} +foreach {tn c} [list 2 c1 3 c2 4 c3] { + test_efkey_61 $tn.1 1 "INSERT INTO $c VALUES(1, 2)" + test_efkey_61 $tn.2 0 "INSERT INTO parent VALUES(1, 2)" + test_efkey_61 $tn.3 0 "INSERT INTO $c VALUES(1, 2)" + + execsql "DELETE FROM $c ; DELETE FROM parent" +} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-00279-52283 +# +# Test an example showing that when a row is deleted from the parent +# table, the child table is queried for orphaned rows as follows: +# +# SELECT rowid FROM track WHERE trackartist = ? +# +# EVIDENCE-OF: R-23302-30956 If this SELECT returns any rows at all, +# then SQLite concludes that deleting the row from the parent table +# would violate the foreign key constraint and returns an error. +# +do_test e_fkey-25.1 { + execsql { + CREATE TABLE artist( + artistid INTEGER PRIMARY KEY, + artistname TEXT + ); + CREATE TABLE track( + trackid INTEGER, + trackname TEXT, + trackartist INTEGER, + FOREIGN KEY(trackartist) REFERENCES artist(artistid) + ); + } +} {} +do_execsql_test e_fkey-25.2 { + PRAGMA foreign_keys = OFF; + EXPLAIN QUERY PLAN DELETE FROM artist WHERE 1; + EXPLAIN QUERY PLAN SELECT rowid FROM track WHERE trackartist = ?; +} { + 0 0 0 {SCAN TABLE artist} + 0 0 0 {SCAN TABLE track} +} +do_execsql_test e_fkey-25.3 { + PRAGMA foreign_keys = ON; + EXPLAIN QUERY PLAN DELETE FROM artist WHERE 1; +} { + 0 0 0 {SCAN TABLE artist} + 0 0 0 {SCAN TABLE track} +} +do_test e_fkey-25.4 { + execsql { + INSERT INTO artist VALUES(5, 'artist 5'); + INSERT INTO artist VALUES(6, 'artist 6'); + INSERT INTO artist VALUES(7, 'artist 7'); + INSERT INTO track VALUES(1, 'track 1', 5); + INSERT INTO track VALUES(2, 'track 2', 6); + } +} {} + +do_test e_fkey-25.5 { + concat \ + [execsql { SELECT rowid FROM track WHERE trackartist = 5 }] \ + [catchsql { DELETE FROM artist WHERE artistid = 5 }] +} {1 1 {foreign key constraint failed}} + +do_test e_fkey-25.6 { + concat \ + [execsql { SELECT rowid FROM track WHERE trackartist = 7 }] \ + [catchsql { DELETE FROM artist WHERE artistid = 7 }] +} {0 {}} + +do_test e_fkey-25.7 { + concat \ + [execsql { SELECT rowid FROM track WHERE trackartist = 6 }] \ + [catchsql { DELETE FROM artist WHERE artistid = 6 }] +} {2 1 {foreign key constraint failed}} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-47936-10044 Or, more generally: +# SELECT rowid FROM WHERE = :parent_key_value +# +# Test that when a row is deleted from the parent table of an FK +# constraint, the child table is queried for orphaned rows. The +# query is equivalent to: +# +# SELECT rowid FROM WHERE = :parent_key_value +# +# Also test that when a row is inserted into the parent table, or when the +# parent key values of an existing row are modified, a query equivalent +# to the following is planned. In some cases it is not executed, but it +# is always planned. +# +# SELECT rowid FROM WHERE = :parent_key_value +# +# EVIDENCE-OF: R-61616-46700 Similar queries may be run if the content +# of the parent key is modified or a new row is inserted into the parent +# table. +# +# +drop_all_tables +do_test e_fkey-26.1 { + execsql { CREATE TABLE parent(x, y, UNIQUE(y, x)) } +} {} +foreach {tn sql} { + 2 { + CREATE TABLE child(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y)) + } + 3 { + CREATE TABLE child(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y)); + CREATE INDEX childi ON child(a, b); + } + 4 { + CREATE TABLE child(a, b, FOREIGN KEY(a, b) REFERENCES parent(x, y)); + CREATE UNIQUE INDEX childi ON child(b, a); + } +} { + execsql $sql + + execsql {PRAGMA foreign_keys = OFF} + set delete [concat \ + [eqp "DELETE FROM parent WHERE 1"] \ + [eqp "SELECT rowid FROM child WHERE a = ? AND b = ?"] + ] + set update [concat \ + [eqp "UPDATE parent SET x=?, y=?"] \ + [eqp "SELECT rowid FROM child WHERE a = ? AND b = ?"] \ + [eqp "SELECT rowid FROM child WHERE a = ? AND b = ?"] + ] + execsql {PRAGMA foreign_keys = ON} + + do_test e_fkey-26.$tn.1 { eqp "DELETE FROM parent WHERE 1" } $delete + do_test e_fkey-26.$tn.2 { eqp "UPDATE parent set x=?, y=?" } $update + + execsql {DROP TABLE child} +} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-14553-34013 +# +# Test the example schema at the end of section 3. Also test that is +# is "efficient". In this case "efficient" means that foreign key +# related operations on the parent table do not provoke linear scans. +# +drop_all_tables +do_test e_fkey-27.1 { + execsql { + CREATE TABLE artist( + artistid INTEGER PRIMARY KEY, + artistname TEXT + ); + CREATE TABLE track( + trackid INTEGER, + trackname TEXT, + trackartist INTEGER REFERENCES artist + ); + CREATE INDEX trackindex ON track(trackartist); + } +} {} +do_test e_fkey-27.2 { + eqp { INSERT INTO artist VALUES(?, ?) } +} {} +do_execsql_test e_fkey-27.3 { + EXPLAIN QUERY PLAN UPDATE artist SET artistid = ?, artistname = ? +} { + 0 0 0 {SCAN TABLE artist} + 0 0 0 {SEARCH TABLE track USING COVERING INDEX trackindex (trackartist=?)} + 0 0 0 {SEARCH TABLE track USING COVERING INDEX trackindex (trackartist=?)} +} +do_execsql_test e_fkey-27.4 { + EXPLAIN QUERY PLAN DELETE FROM artist +} { + 0 0 0 {SCAN TABLE artist} + 0 0 0 {SEARCH TABLE track USING COVERING INDEX trackindex (trackartist=?)} +} + + +########################################################################### +### SECTION 4.1: Composite Foreign Key Constraints +########################################################################### + +#------------------------------------------------------------------------- +# Check that parent and child keys must have the same number of columns. +# +# EVIDENCE-OF: R-41062-34431 Parent and child keys must have the same +# cardinality. +# +foreach {tn sql err} { + 1 "CREATE TABLE c(jj REFERENCES p(x, y))" + {foreign key on jj should reference only one column of table p} + + 2 "CREATE TABLE c(jj REFERENCES p())" {near ")": syntax error} + + 3 "CREATE TABLE c(jj, FOREIGN KEY(jj) REFERENCES p(x, y))" + {number of columns in foreign key does not match the number of columns in the referenced table} + + 4 "CREATE TABLE c(jj, FOREIGN KEY(jj) REFERENCES p())" + {near ")": syntax error} + + 5 "CREATE TABLE c(ii, jj, FOREIGN KEY(jj, ii) REFERENCES p())" + {near ")": syntax error} + + 6 "CREATE TABLE c(ii, jj, FOREIGN KEY(jj, ii) REFERENCES p(x))" + {number of columns in foreign key does not match the number of columns in the referenced table} + + 7 "CREATE TABLE c(ii, jj, FOREIGN KEY(jj, ii) REFERENCES p(x,y,z))" + {number of columns in foreign key does not match the number of columns in the referenced table} +} { + drop_all_tables + do_test e_fkey-28.$tn [list catchsql $sql] [list 1 $err] +} +do_test e_fkey-28.8 { + drop_all_tables + execsql { + CREATE TABLE p(x PRIMARY KEY); + CREATE TABLE c(a, b, FOREIGN KEY(a,b) REFERENCES p); + } + catchsql {DELETE FROM p} +} {1 {foreign key mismatch - "c" referencing "p"}} +do_test e_fkey-28.9 { + drop_all_tables + execsql { + CREATE TABLE p(x, y, PRIMARY KEY(x,y)); + CREATE TABLE c(a REFERENCES p); + } + catchsql {DELETE FROM p} +} {1 {foreign key mismatch - "c" referencing "p"}} + + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-24676-09859 +# +# Test the example schema in the "Composite Foreign Key Constraints" +# section. +# +do_test e_fkey-29.1 { + execsql { + CREATE TABLE album( + albumartist TEXT, + albumname TEXT, + albumcover BINARY, + PRIMARY KEY(albumartist, albumname) + ); + CREATE TABLE song( + songid INTEGER, + songartist TEXT, + songalbum TEXT, + songname TEXT, + FOREIGN KEY(songartist, songalbum) REFERENCES album(albumartist,albumname) + ); + } +} {} + +do_test e_fkey-29.2 { + execsql { + INSERT INTO album VALUES('Elvis Presley', 'Elvis'' Christmas Album', NULL); + INSERT INTO song VALUES( + 1, 'Elvis Presley', 'Elvis'' Christmas Album', 'Here Comes Santa Clause' + ); + } +} {} +do_test e_fkey-29.3 { + catchsql { + INSERT INTO song VALUES(2, 'Elvis Presley', 'Elvis Is Back!', 'Fever'); + } +} {1 {foreign key constraint failed}} + + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-33626-48418 In SQLite, if any of the child key columns +# (in this case songartist and songalbum) are NULL, then there is no +# requirement for a corresponding row in the parent table. +# +do_test e_fkey-30.1 { + execsql { + INSERT INTO song VALUES(2, 'Elvis Presley', NULL, 'Fever'); + INSERT INTO song VALUES(3, NULL, 'Elvis Is Back', 'Soldier Boy'); + } +} {} + +########################################################################### +### SECTION 4.2: Deferred Foreign Key Constraints +########################################################################### + +#------------------------------------------------------------------------- +# Test that if a statement violates an immediate FK constraint, and the +# database does not satisfy the FK constraint once all effects of the +# statement have been applied, an error is reported and the effects of +# the statement rolled back. +# +# EVIDENCE-OF: R-09323-30470 If a statement modifies the contents of the +# database so that an immediate foreign key constraint is in violation +# at the conclusion the statement, an exception is thrown and the +# effects of the statement are reverted. +# +drop_all_tables +do_test e_fkey-31.1 { + execsql { + CREATE TABLE king(a, b, PRIMARY KEY(a)); + CREATE TABLE prince(c REFERENCES king, d); + } +} {} + +do_test e_fkey-31.2 { + # Execute a statement that violates the immediate FK constraint. + catchsql { INSERT INTO prince VALUES(1, 2) } +} {1 {foreign key constraint failed}} + +do_test e_fkey-31.3 { + # This time, use a trigger to fix the constraint violation before the + # statement has finished executing. Then execute the same statement as + # in the previous test case. This time, no error. + execsql { + CREATE TRIGGER kt AFTER INSERT ON prince WHEN + NOT EXISTS (SELECT a FROM king WHERE a = new.c) + BEGIN + INSERT INTO king VALUES(new.c, NULL); + END + } + execsql { INSERT INTO prince VALUES(1, 2) } +} {} + +# Test that operating inside a transaction makes no difference to +# immediate constraint violation handling. +do_test e_fkey-31.4 { + execsql { + BEGIN; + INSERT INTO prince VALUES(2, 3); + DROP TRIGGER kt; + } + catchsql { INSERT INTO prince VALUES(3, 4) } +} {1 {foreign key constraint failed}} +do_test e_fkey-31.5 { + execsql { + COMMIT; + SELECT * FROM king; + } +} {1 {} 2 {}} + +#------------------------------------------------------------------------- +# Test that if a deferred constraint is violated within a transaction, +# nothing happens immediately and the database is allowed to persist +# in a state that does not satisfy the FK constraint. However attempts +# to COMMIT the transaction fail until the FK constraint is satisfied. +# +# EVIDENCE-OF: R-49178-21358 By contrast, if a statement modifies the +# contents of the database such that a deferred foreign key constraint +# is violated, the violation is not reported immediately. +# +# EVIDENCE-OF: R-39692-12488 Deferred foreign key constraints are not +# checked until the transaction tries to COMMIT. +# +# EVIDENCE-OF: R-55147-47664 For as long as the user has an open +# transaction, the database is allowed to exist in a state that violates +# any number of deferred foreign key constraints. +# +# EVIDENCE-OF: R-29604-30395 However, COMMIT will fail as long as +# foreign key constraints remain in violation. +# +proc test_efkey_34 {tn isError sql} { + do_test e_fkey-32.$tn " + catchsql {$sql} + " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] +} +drop_all_tables + +test_efkey_34 1 0 { + CREATE TABLE ll(k PRIMARY KEY); + CREATE TABLE kk(c REFERENCES ll DEFERRABLE INITIALLY DEFERRED); +} +test_efkey_34 2 0 "BEGIN" +test_efkey_34 3 0 "INSERT INTO kk VALUES(5)" +test_efkey_34 4 0 "INSERT INTO kk VALUES(10)" +test_efkey_34 5 1 "COMMIT" +test_efkey_34 6 0 "INSERT INTO ll VALUES(10)" +test_efkey_34 7 1 "COMMIT" +test_efkey_34 8 0 "INSERT INTO ll VALUES(5)" +test_efkey_34 9 0 "COMMIT" + +#------------------------------------------------------------------------- +# When not running inside a transaction, a deferred constraint is similar +# to an immediate constraint (violations are reported immediately). +# +# EVIDENCE-OF: R-56844-61705 If the current statement is not inside an +# explicit transaction (a BEGIN/COMMIT/ROLLBACK block), then an implicit +# transaction is committed as soon as the statement has finished +# executing. In this case deferred constraints behave the same as +# immediate constraints. +# +drop_all_tables +proc test_efkey_35 {tn isError sql} { + do_test e_fkey-33.$tn " + catchsql {$sql} + " [lindex {{0 {}} {1 {foreign key constraint failed}}} $isError] +} +do_test e_fkey-33.1 { + execsql { + CREATE TABLE parent(x, y); + CREATE UNIQUE INDEX pi ON parent(x, y); + CREATE TABLE child(a, b, + FOREIGN KEY(a, b) REFERENCES parent(x, y) DEFERRABLE INITIALLY DEFERRED + ); + } +} {} +test_efkey_35 2 1 "INSERT INTO child VALUES('x', 'y')" +test_efkey_35 3 0 "INSERT INTO parent VALUES('x', 'y')" +test_efkey_35 4 0 "INSERT INTO child VALUES('x', 'y')" + + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-12782-61841 +# +# Test that an FK constraint is made deferred by adding the following +# to the definition: +# +# DEFERRABLE INITIALLY DEFERRED +# +# EVIDENCE-OF: R-09005-28791 +# +# Also test that adding any of the following to a foreign key definition +# makes the constraint IMMEDIATE: +# +# NOT DEFERRABLE INITIALLY DEFERRED +# NOT DEFERRABLE INITIALLY IMMEDIATE +# NOT DEFERRABLE +# DEFERRABLE INITIALLY IMMEDIATE +# DEFERRABLE +# +# Foreign keys are IMMEDIATE by default (if there is no DEFERRABLE or NOT +# DEFERRABLE clause). +# +# EVIDENCE-OF: R-35290-16460 Foreign key constraints are immediate by +# default. +# +# EVIDENCE-OF: R-30323-21917 Each foreign key constraint in SQLite is +# classified as either immediate or deferred. +# +drop_all_tables +do_test e_fkey-34.1 { + execsql { + CREATE TABLE parent(x, y, z, PRIMARY KEY(x,y,z)); + CREATE TABLE c1(a, b, c, + FOREIGN KEY(a, b, c) REFERENCES parent NOT DEFERRABLE INITIALLY DEFERRED + ); + CREATE TABLE c2(a, b, c, + FOREIGN KEY(a, b, c) REFERENCES parent NOT DEFERRABLE INITIALLY IMMEDIATE + ); + CREATE TABLE c3(a, b, c, + FOREIGN KEY(a, b, c) REFERENCES parent NOT DEFERRABLE + ); + CREATE TABLE c4(a, b, c, + FOREIGN KEY(a, b, c) REFERENCES parent DEFERRABLE INITIALLY IMMEDIATE + ); + CREATE TABLE c5(a, b, c, + FOREIGN KEY(a, b, c) REFERENCES parent DEFERRABLE + ); + CREATE TABLE c6(a, b, c, FOREIGN KEY(a, b, c) REFERENCES parent); + + -- This FK constraint is the only deferrable one. + CREATE TABLE c7(a, b, c, + FOREIGN KEY(a, b, c) REFERENCES parent DEFERRABLE INITIALLY DEFERRED + ); + + INSERT INTO parent VALUES('a', 'b', 'c'); + INSERT INTO parent VALUES('d', 'e', 'f'); + INSERT INTO parent VALUES('g', 'h', 'i'); + INSERT INTO parent VALUES('j', 'k', 'l'); + INSERT INTO parent VALUES('m', 'n', 'o'); + INSERT INTO parent VALUES('p', 'q', 'r'); + INSERT INTO parent VALUES('s', 't', 'u'); + + INSERT INTO c1 VALUES('a', 'b', 'c'); + INSERT INTO c2 VALUES('d', 'e', 'f'); + INSERT INTO c3 VALUES('g', 'h', 'i'); + INSERT INTO c4 VALUES('j', 'k', 'l'); + INSERT INTO c5 VALUES('m', 'n', 'o'); + INSERT INTO c6 VALUES('p', 'q', 'r'); + INSERT INTO c7 VALUES('s', 't', 'u'); + } +} {} + +proc test_efkey_29 {tn sql isError} { + do_test e_fkey-34.$tn "catchsql {$sql}" [ + lindex {{0 {}} {1 {foreign key constraint failed}}} $isError + ] +} +test_efkey_29 2 "BEGIN" 0 +test_efkey_29 3 "DELETE FROM parent WHERE x = 'a'" 1 +test_efkey_29 4 "DELETE FROM parent WHERE x = 'd'" 1 +test_efkey_29 5 "DELETE FROM parent WHERE x = 'g'" 1 +test_efkey_29 6 "DELETE FROM parent WHERE x = 'j'" 1 +test_efkey_29 7 "DELETE FROM parent WHERE x = 'm'" 1 +test_efkey_29 8 "DELETE FROM parent WHERE x = 'p'" 1 +test_efkey_29 9 "DELETE FROM parent WHERE x = 's'" 0 +test_efkey_29 10 "COMMIT" 1 +test_efkey_29 11 "ROLLBACK" 0 + +test_efkey_29 9 "BEGIN" 0 +test_efkey_29 10 "UPDATE parent SET z = 'z' WHERE z = 'c'" 1 +test_efkey_29 11 "UPDATE parent SET z = 'z' WHERE z = 'f'" 1 +test_efkey_29 12 "UPDATE parent SET z = 'z' WHERE z = 'i'" 1 +test_efkey_29 13 "UPDATE parent SET z = 'z' WHERE z = 'l'" 1 +test_efkey_29 14 "UPDATE parent SET z = 'z' WHERE z = 'o'" 1 +test_efkey_29 15 "UPDATE parent SET z = 'z' WHERE z = 'r'" 1 +test_efkey_29 16 "UPDATE parent SET z = 'z' WHERE z = 'u'" 0 +test_efkey_29 17 "COMMIT" 1 +test_efkey_29 18 "ROLLBACK" 0 + +test_efkey_29 17 "BEGIN" 0 +test_efkey_29 18 "INSERT INTO c1 VALUES(1, 2, 3)" 1 +test_efkey_29 19 "INSERT INTO c2 VALUES(1, 2, 3)" 1 +test_efkey_29 20 "INSERT INTO c3 VALUES(1, 2, 3)" 1 +test_efkey_29 21 "INSERT INTO c4 VALUES(1, 2, 3)" 1 +test_efkey_29 22 "INSERT INTO c5 VALUES(1, 2, 3)" 1 +test_efkey_29 22 "INSERT INTO c6 VALUES(1, 2, 3)" 1 +test_efkey_29 22 "INSERT INTO c7 VALUES(1, 2, 3)" 0 +test_efkey_29 23 "COMMIT" 1 +test_efkey_29 24 "INSERT INTO parent VALUES(1, 2, 3)" 0 +test_efkey_29 25 "COMMIT" 0 + +test_efkey_29 26 "BEGIN" 0 +test_efkey_29 27 "UPDATE c1 SET a = 10" 1 +test_efkey_29 28 "UPDATE c2 SET a = 10" 1 +test_efkey_29 29 "UPDATE c3 SET a = 10" 1 +test_efkey_29 30 "UPDATE c4 SET a = 10" 1 +test_efkey_29 31 "UPDATE c5 SET a = 10" 1 +test_efkey_29 31 "UPDATE c6 SET a = 10" 1 +test_efkey_29 31 "UPDATE c7 SET a = 10" 0 +test_efkey_29 32 "COMMIT" 1 +test_efkey_29 33 "ROLLBACK" 0 + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-24499-57071 +# +# Test an example from foreignkeys.html dealing with a deferred foreign +# key constraint. +# +do_test e_fkey-35.1 { + drop_all_tables + execsql { + CREATE TABLE artist( + artistid INTEGER PRIMARY KEY, + artistname TEXT + ); + CREATE TABLE track( + trackid INTEGER, + trackname TEXT, + trackartist INTEGER REFERENCES artist(artistid) DEFERRABLE INITIALLY DEFERRED + ); + } +} {} +do_test e_fkey-35.2 { + execsql { + BEGIN; + INSERT INTO track VALUES(1, 'White Christmas', 5); + } + catchsql COMMIT +} {1 {foreign key constraint failed}} +do_test e_fkey-35.3 { + execsql { + INSERT INTO artist VALUES(5, 'Bing Crosby'); + COMMIT; + } +} {} + +#------------------------------------------------------------------------- +# Verify that a nested savepoint may be released without satisfying +# deferred foreign key constraints. +# +# EVIDENCE-OF: R-07223-48323 A nested savepoint transaction may be +# RELEASEd while the database is in a state that does not satisfy a +# deferred foreign key constraint. +# +drop_all_tables +do_test e_fkey-36.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, + b REFERENCES t1 DEFERRABLE INITIALLY DEFERRED + ); + INSERT INTO t1 VALUES(1, 1); + INSERT INTO t1 VALUES(2, 2); + INSERT INTO t1 VALUES(3, 3); + } +} {} +do_test e_fkey-36.2 { + execsql { + BEGIN; + SAVEPOINT one; + INSERT INTO t1 VALUES(4, 5); + RELEASE one; + } +} {} +do_test e_fkey-36.3 { + catchsql COMMIT +} {1 {foreign key constraint failed}} +do_test e_fkey-36.4 { + execsql { + UPDATE t1 SET a = 5 WHERE a = 4; + COMMIT; + } +} {} + + +#------------------------------------------------------------------------- +# Check that a transaction savepoint (an outermost savepoint opened when +# the database was in auto-commit mode) cannot be released without +# satisfying deferred foreign key constraints. It may be rolled back. +# +# EVIDENCE-OF: R-44295-13823 A transaction savepoint (a non-nested +# savepoint that was opened while there was not currently an open +# transaction), on the other hand, is subject to the same restrictions +# as a COMMIT - attempting to RELEASE it while the database is in such a +# state will fail. +# +do_test e_fkey-37.1 { + execsql { + SAVEPOINT one; + SAVEPOINT two; + INSERT INTO t1 VALUES(6, 7); + RELEASE two; + } +} {} +do_test e_fkey-37.2 { + catchsql {RELEASE one} +} {1 {foreign key constraint failed}} +do_test e_fkey-37.3 { + execsql { + UPDATE t1 SET a = 7 WHERE a = 6; + RELEASE one; + } +} {} +do_test e_fkey-37.4 { + execsql { + SAVEPOINT one; + SAVEPOINT two; + INSERT INTO t1 VALUES(9, 10); + RELEASE two; + } +} {} +do_test e_fkey-37.5 { + catchsql {RELEASE one} +} {1 {foreign key constraint failed}} +do_test e_fkey-37.6 { + execsql {ROLLBACK TO one ; RELEASE one} +} {} + +#------------------------------------------------------------------------- +# Test that if a COMMIT operation fails due to deferred foreign key +# constraints, any nested savepoints remain open. +# +# EVIDENCE-OF: R-37736-42616 If a COMMIT statement (or the RELEASE of a +# transaction SAVEPOINT) fails because the database is currently in a +# state that violates a deferred foreign key constraint and there are +# currently nested savepoints, the nested savepoints remain open. +# +do_test e_fkey-38.1 { + execsql { + DELETE FROM t1 WHERE a>3; + SELECT * FROM t1; + } +} {1 1 2 2 3 3} +do_test e_fkey-38.2 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(4, 4); + SAVEPOINT one; + INSERT INTO t1 VALUES(5, 6); + SELECT * FROM t1; + } +} {1 1 2 2 3 3 4 4 5 6} +do_test e_fkey-38.3 { + catchsql COMMIT +} {1 {foreign key constraint failed}} +do_test e_fkey-38.4 { + execsql { + ROLLBACK TO one; + COMMIT; + SELECT * FROM t1; + } +} {1 1 2 2 3 3 4 4} + +do_test e_fkey-38.5 { + execsql { + SAVEPOINT a; + INSERT INTO t1 VALUES(5, 5); + SAVEPOINT b; + INSERT INTO t1 VALUES(6, 7); + SAVEPOINT c; + INSERT INTO t1 VALUES(7, 8); + } +} {} +do_test e_fkey-38.6 { + catchsql {RELEASE a} +} {1 {foreign key constraint failed}} +do_test e_fkey-38.7 { + execsql {ROLLBACK TO c} + catchsql {RELEASE a} +} {1 {foreign key constraint failed}} +do_test e_fkey-38.8 { + execsql { + ROLLBACK TO b; + RELEASE a; + SELECT * FROM t1; + } +} {1 1 2 2 3 3 4 4 5 5} + +########################################################################### +### SECTION 4.3: ON DELETE and ON UPDATE Actions +########################################################################### + +#------------------------------------------------------------------------- +# Test that configured ON DELETE and ON UPDATE actions take place when +# deleting or modifying rows of the parent table, respectively. +# +# EVIDENCE-OF: R-48270-44282 Foreign key ON DELETE and ON UPDATE clauses +# are used to configure actions that take place when deleting rows from +# the parent table (ON DELETE), or modifying the parent key values of +# existing rows (ON UPDATE). +# +# Test that a single FK constraint may have different actions configured +# for ON DELETE and ON UPDATE. +# +# EVIDENCE-OF: R-48124-63225 A single foreign key constraint may have +# different actions configured for ON DELETE and ON UPDATE. +# +do_test e_fkey-39.1 { + execsql { + CREATE TABLE p(a, b PRIMARY KEY, c); + CREATE TABLE c1(d, e, f DEFAULT 'k0' REFERENCES p + ON UPDATE SET DEFAULT + ON DELETE SET NULL + ); + + INSERT INTO p VALUES(0, 'k0', ''); + INSERT INTO p VALUES(1, 'k1', 'I'); + INSERT INTO p VALUES(2, 'k2', 'II'); + INSERT INTO p VALUES(3, 'k3', 'III'); + + INSERT INTO c1 VALUES(1, 'xx', 'k1'); + INSERT INTO c1 VALUES(2, 'xx', 'k2'); + INSERT INTO c1 VALUES(3, 'xx', 'k3'); + } +} {} +do_test e_fkey-39.2 { + execsql { + UPDATE p SET b = 'k4' WHERE a = 1; + SELECT * FROM c1; + } +} {1 xx k0 2 xx k2 3 xx k3} +do_test e_fkey-39.3 { + execsql { + DELETE FROM p WHERE a = 2; + SELECT * FROM c1; + } +} {1 xx k0 2 xx {} 3 xx k3} +do_test e_fkey-39.4 { + execsql { + CREATE UNIQUE INDEX pi ON p(c); + REPLACE INTO p VALUES(5, 'k5', 'III'); + SELECT * FROM c1; + } +} {1 xx k0 2 xx {} 3 xx {}} + +#------------------------------------------------------------------------- +# Each foreign key in the system has an ON UPDATE and ON DELETE action, +# either "NO ACTION", "RESTRICT", "SET NULL", "SET DEFAULT" or "CASCADE". +# +# EVIDENCE-OF: R-33326-45252 The ON DELETE and ON UPDATE action +# associated with each foreign key in an SQLite database is one of "NO +# ACTION", "RESTRICT", "SET NULL", "SET DEFAULT" or "CASCADE". +# +# If none is specified explicitly, "NO ACTION" is the default. +# +# EVIDENCE-OF: R-19803-45884 If an action is not explicitly specified, +# it defaults to "NO ACTION". +# +drop_all_tables +do_test e_fkey-40.1 { + execsql { + CREATE TABLE parent(x PRIMARY KEY, y); + CREATE TABLE child1(a, + b REFERENCES parent ON UPDATE NO ACTION ON DELETE RESTRICT + ); + CREATE TABLE child2(a, + b REFERENCES parent ON UPDATE RESTRICT ON DELETE SET NULL + ); + CREATE TABLE child3(a, + b REFERENCES parent ON UPDATE SET NULL ON DELETE SET DEFAULT + ); + CREATE TABLE child4(a, + b REFERENCES parent ON UPDATE SET DEFAULT ON DELETE CASCADE + ); + + -- Create some foreign keys that use the default action - "NO ACTION" + CREATE TABLE child5(a, b REFERENCES parent ON UPDATE CASCADE); + CREATE TABLE child6(a, b REFERENCES parent ON DELETE RESTRICT); + CREATE TABLE child7(a, b REFERENCES parent ON DELETE NO ACTION); + CREATE TABLE child8(a, b REFERENCES parent ON UPDATE NO ACTION); + } +} {} + +foreach {tn zTab lRes} { + 2 child1 {0 0 parent b {} {NO ACTION} RESTRICT NONE} + 3 child2 {0 0 parent b {} RESTRICT {SET NULL} NONE} + 4 child3 {0 0 parent b {} {SET NULL} {SET DEFAULT} NONE} + 5 child4 {0 0 parent b {} {SET DEFAULT} CASCADE NONE} + 6 child5 {0 0 parent b {} CASCADE {NO ACTION} NONE} + 7 child6 {0 0 parent b {} {NO ACTION} RESTRICT NONE} + 8 child7 {0 0 parent b {} {NO ACTION} {NO ACTION} NONE} + 9 child8 {0 0 parent b {} {NO ACTION} {NO ACTION} NONE} +} { + do_test e_fkey-40.$tn { execsql "PRAGMA foreign_key_list($zTab)" } $lRes +} + +#------------------------------------------------------------------------- +# Test that "NO ACTION" means that nothing happens to a child row when +# it's parent row is updated or deleted. +# +# EVIDENCE-OF: R-19971-54976 Configuring "NO ACTION" means just that: +# when a parent key is modified or deleted from the database, no special +# action is taken. +# +drop_all_tables +do_test e_fkey-41.1 { + execsql { + CREATE TABLE parent(p1, p2, PRIMARY KEY(p1, p2)); + CREATE TABLE child(c1, c2, + FOREIGN KEY(c1, c2) REFERENCES parent + ON UPDATE NO ACTION + ON DELETE NO ACTION + DEFERRABLE INITIALLY DEFERRED + ); + INSERT INTO parent VALUES('j', 'k'); + INSERT INTO parent VALUES('l', 'm'); + INSERT INTO child VALUES('j', 'k'); + INSERT INTO child VALUES('l', 'm'); + } +} {} +do_test e_fkey-41.2 { + execsql { + BEGIN; + UPDATE parent SET p1='k' WHERE p1='j'; + DELETE FROM parent WHERE p1='l'; + SELECT * FROM child; + } +} {j k l m} +do_test e_fkey-41.3 { + catchsql COMMIT +} {1 {foreign key constraint failed}} +do_test e_fkey-41.4 { + execsql ROLLBACK +} {} + +#------------------------------------------------------------------------- +# Test that "RESTRICT" means the application is prohibited from deleting +# or updating a parent table row when there exists one or more child keys +# mapped to it. +# +# EVIDENCE-OF: R-04272-38653 The "RESTRICT" action means that the +# application is prohibited from deleting (for ON DELETE RESTRICT) or +# modifying (for ON UPDATE RESTRICT) a parent key when there exists one +# or more child keys mapped to it. +# +drop_all_tables +do_test e_fkey-41.1 { + execsql { + CREATE TABLE parent(p1, p2); + CREATE UNIQUE INDEX parent_i ON parent(p1, p2); + CREATE TABLE child1(c1, c2, + FOREIGN KEY(c2, c1) REFERENCES parent(p1, p2) ON DELETE RESTRICT + ); + CREATE TABLE child2(c1, c2, + FOREIGN KEY(c2, c1) REFERENCES parent(p1, p2) ON UPDATE RESTRICT + ); + } +} {} +do_test e_fkey-41.2 { + execsql { + INSERT INTO parent VALUES('a', 'b'); + INSERT INTO parent VALUES('c', 'd'); + INSERT INTO child1 VALUES('b', 'a'); + INSERT INTO child2 VALUES('d', 'c'); + } +} {} +do_test e_fkey-41.3 { + catchsql { DELETE FROM parent WHERE p1 = 'a' } +} {1 {foreign key constraint failed}} +do_test e_fkey-41.4 { + catchsql { UPDATE parent SET p2 = 'e' WHERE p1 = 'c' } +} {1 {foreign key constraint failed}} + +#------------------------------------------------------------------------- +# Test that RESTRICT is slightly different from NO ACTION for IMMEDIATE +# constraints, in that it is enforced immediately, not at the end of the +# statement. +# +# EVIDENCE-OF: R-37997-42187 The difference between the effect of a +# RESTRICT action and normal foreign key constraint enforcement is that +# the RESTRICT action processing happens as soon as the field is updated +# - not at the end of the current statement as it would with an +# immediate constraint, or at the end of the current transaction as it +# would with a deferred constraint. +# +drop_all_tables +do_test e_fkey-42.1 { + execsql { + CREATE TABLE parent(x PRIMARY KEY); + CREATE TABLE child1(c REFERENCES parent ON UPDATE RESTRICT); + CREATE TABLE child2(c REFERENCES parent ON UPDATE NO ACTION); + + INSERT INTO parent VALUES('key1'); + INSERT INTO parent VALUES('key2'); + INSERT INTO child1 VALUES('key1'); + INSERT INTO child2 VALUES('key2'); + + CREATE TRIGGER parent_t AFTER UPDATE ON parent BEGIN + UPDATE child1 set c = new.x WHERE c = old.x; + UPDATE child2 set c = new.x WHERE c = old.x; + END; + } +} {} +do_test e_fkey-42.2 { + catchsql { UPDATE parent SET x = 'key one' WHERE x = 'key1' } +} {1 {foreign key constraint failed}} +do_test e_fkey-42.3 { + execsql { + UPDATE parent SET x = 'key two' WHERE x = 'key2'; + SELECT * FROM child2; + } +} {{key two}} + +drop_all_tables +do_test e_fkey-42.4 { + execsql { + CREATE TABLE parent(x PRIMARY KEY); + CREATE TABLE child1(c REFERENCES parent ON DELETE RESTRICT); + CREATE TABLE child2(c REFERENCES parent ON DELETE NO ACTION); + + INSERT INTO parent VALUES('key1'); + INSERT INTO parent VALUES('key2'); + INSERT INTO child1 VALUES('key1'); + INSERT INTO child2 VALUES('key2'); + + CREATE TRIGGER parent_t AFTER DELETE ON parent BEGIN + UPDATE child1 SET c = NULL WHERE c = old.x; + UPDATE child2 SET c = NULL WHERE c = old.x; + END; + } +} {} +do_test e_fkey-42.5 { + catchsql { DELETE FROM parent WHERE x = 'key1' } +} {1 {foreign key constraint failed}} +do_test e_fkey-42.6 { + execsql { + DELETE FROM parent WHERE x = 'key2'; + SELECT * FROM child2; + } +} {{}} + +drop_all_tables +do_test e_fkey-42.7 { + execsql { + CREATE TABLE parent(x PRIMARY KEY); + CREATE TABLE child1(c REFERENCES parent ON DELETE RESTRICT); + CREATE TABLE child2(c REFERENCES parent ON DELETE NO ACTION); + + INSERT INTO parent VALUES('key1'); + INSERT INTO parent VALUES('key2'); + INSERT INTO child1 VALUES('key1'); + INSERT INTO child2 VALUES('key2'); + } +} {} +do_test e_fkey-42.8 { + catchsql { REPLACE INTO parent VALUES('key1') } +} {1 {foreign key constraint failed}} +do_test e_fkey-42.9 { + execsql { + REPLACE INTO parent VALUES('key2'); + SELECT * FROM child2; + } +} {key2} + +#------------------------------------------------------------------------- +# Test that RESTRICT is enforced immediately, even for a DEFERRED constraint. +# +# EVIDENCE-OF: R-24179-60523 Even if the foreign key constraint it is +# attached to is deferred, configuring a RESTRICT action causes SQLite +# to return an error immediately if a parent key with dependent child +# keys is deleted or modified. +# +drop_all_tables +do_test e_fkey-43.1 { + execsql { + CREATE TABLE parent(x PRIMARY KEY); + CREATE TABLE child1(c REFERENCES parent ON UPDATE RESTRICT + DEFERRABLE INITIALLY DEFERRED + ); + CREATE TABLE child2(c REFERENCES parent ON UPDATE NO ACTION + DEFERRABLE INITIALLY DEFERRED + ); + + INSERT INTO parent VALUES('key1'); + INSERT INTO parent VALUES('key2'); + INSERT INTO child1 VALUES('key1'); + INSERT INTO child2 VALUES('key2'); + BEGIN; + } +} {} +do_test e_fkey-43.2 { + catchsql { UPDATE parent SET x = 'key one' WHERE x = 'key1' } +} {1 {foreign key constraint failed}} +do_test e_fkey-43.3 { + execsql { UPDATE parent SET x = 'key two' WHERE x = 'key2' } +} {} +do_test e_fkey-43.4 { + catchsql COMMIT +} {1 {foreign key constraint failed}} +do_test e_fkey-43.5 { + execsql { + UPDATE child2 SET c = 'key two'; + COMMIT; + } +} {} + +drop_all_tables +do_test e_fkey-43.6 { + execsql { + CREATE TABLE parent(x PRIMARY KEY); + CREATE TABLE child1(c REFERENCES parent ON DELETE RESTRICT + DEFERRABLE INITIALLY DEFERRED + ); + CREATE TABLE child2(c REFERENCES parent ON DELETE NO ACTION + DEFERRABLE INITIALLY DEFERRED + ); + + INSERT INTO parent VALUES('key1'); + INSERT INTO parent VALUES('key2'); + INSERT INTO child1 VALUES('key1'); + INSERT INTO child2 VALUES('key2'); + BEGIN; + } +} {} +do_test e_fkey-43.7 { + catchsql { DELETE FROM parent WHERE x = 'key1' } +} {1 {foreign key constraint failed}} +do_test e_fkey-43.8 { + execsql { DELETE FROM parent WHERE x = 'key2' } +} {} +do_test e_fkey-43.9 { + catchsql COMMIT +} {1 {foreign key constraint failed}} +do_test e_fkey-43.10 { + execsql { + UPDATE child2 SET c = NULL; + COMMIT; + } +} {} + +#------------------------------------------------------------------------- +# Test SET NULL actions. +# +# EVIDENCE-OF: R-03353-05327 If the configured action is "SET NULL", +# then when a parent key is deleted (for ON DELETE SET NULL) or modified +# (for ON UPDATE SET NULL), the child key columns of all rows in the +# child table that mapped to the parent key are set to contain SQL NULL +# values. +# +drop_all_tables +do_test e_fkey-44.1 { + execsql { + CREATE TABLE pA(x PRIMARY KEY); + CREATE TABLE cA(c REFERENCES pA ON DELETE SET NULL); + CREATE TABLE cB(c REFERENCES pA ON UPDATE SET NULL); + + INSERT INTO pA VALUES(X'ABCD'); + INSERT INTO pA VALUES(X'1234'); + INSERT INTO cA VALUES(X'ABCD'); + INSERT INTO cB VALUES(X'1234'); + } +} {} +do_test e_fkey-44.2 { + execsql { + DELETE FROM pA WHERE rowid = 1; + SELECT quote(x) FROM pA; + } +} {X'1234'} +do_test e_fkey-44.3 { + execsql { + SELECT quote(c) FROM cA; + } +} {NULL} +do_test e_fkey-44.4 { + execsql { + UPDATE pA SET x = X'8765' WHERE rowid = 2; + SELECT quote(x) FROM pA; + } +} {X'8765'} +do_test e_fkey-44.5 { + execsql { SELECT quote(c) FROM cB } +} {NULL} + +#------------------------------------------------------------------------- +# Test SET DEFAULT actions. +# +# EVIDENCE-OF: R-43054-54832 The "SET DEFAULT" actions are similar to +# "SET NULL", except that each of the child key columns is set to +# contain the columns default value instead of NULL. +# +drop_all_tables +do_test e_fkey-45.1 { + execsql { + CREATE TABLE pA(x PRIMARY KEY); + CREATE TABLE cA(c DEFAULT X'0000' REFERENCES pA ON DELETE SET DEFAULT); + CREATE TABLE cB(c DEFAULT X'9999' REFERENCES pA ON UPDATE SET DEFAULT); + + INSERT INTO pA(rowid, x) VALUES(1, X'0000'); + INSERT INTO pA(rowid, x) VALUES(2, X'9999'); + INSERT INTO pA(rowid, x) VALUES(3, X'ABCD'); + INSERT INTO pA(rowid, x) VALUES(4, X'1234'); + + INSERT INTO cA VALUES(X'ABCD'); + INSERT INTO cB VALUES(X'1234'); + } +} {} +do_test e_fkey-45.2 { + execsql { + DELETE FROM pA WHERE rowid = 3; + SELECT quote(x) FROM pA ORDER BY rowid; + } +} {X'0000' X'9999' X'1234'} +do_test e_fkey-45.3 { + execsql { SELECT quote(c) FROM cA } +} {X'0000'} +do_test e_fkey-45.4 { + execsql { + UPDATE pA SET x = X'8765' WHERE rowid = 4; + SELECT quote(x) FROM pA ORDER BY rowid; + } +} {X'0000' X'9999' X'8765'} +do_test e_fkey-45.5 { + execsql { SELECT quote(c) FROM cB } +} {X'9999'} + +#------------------------------------------------------------------------- +# Test ON DELETE CASCADE actions. +# +# EVIDENCE-OF: R-61376-57267 A "CASCADE" action propagates the delete or +# update operation on the parent key to each dependent child key. +# +# EVIDENCE-OF: R-61809-62207 For an "ON DELETE CASCADE" action, this +# means that each row in the child table that was associated with the +# deleted parent row is also deleted. +# +drop_all_tables +do_test e_fkey-46.1 { + execsql { + CREATE TABLE p1(a, b UNIQUE); + CREATE TABLE c1(c REFERENCES p1(b) ON DELETE CASCADE, d); + INSERT INTO p1 VALUES(NULL, NULL); + INSERT INTO p1 VALUES(4, 4); + INSERT INTO p1 VALUES(5, 5); + INSERT INTO c1 VALUES(NULL, NULL); + INSERT INTO c1 VALUES(4, 4); + INSERT INTO c1 VALUES(5, 5); + SELECT count(*) FROM c1; + } +} {3} +do_test e_fkey-46.2 { + execsql { + DELETE FROM p1 WHERE a = 4; + SELECT d, c FROM c1; + } +} {{} {} 5 5} +do_test e_fkey-46.3 { + execsql { + DELETE FROM p1; + SELECT d, c FROM c1; + } +} {{} {}} +do_test e_fkey-46.4 { + execsql { SELECT * FROM p1 } +} {} + + +#------------------------------------------------------------------------- +# Test ON UPDATE CASCADE actions. +# +# EVIDENCE-OF: R-13877-64542 For an "ON UPDATE CASCADE" action, it means +# that the values stored in each dependent child key are modified to +# match the new parent key values. +# +# EVIDENCE-OF: R-61376-57267 A "CASCADE" action propagates the delete or +# update operation on the parent key to each dependent child key. +# +drop_all_tables +do_test e_fkey-47.1 { + execsql { + CREATE TABLE p1(a, b UNIQUE); + CREATE TABLE c1(c REFERENCES p1(b) ON UPDATE CASCADE, d); + INSERT INTO p1 VALUES(NULL, NULL); + INSERT INTO p1 VALUES(4, 4); + INSERT INTO p1 VALUES(5, 5); + INSERT INTO c1 VALUES(NULL, NULL); + INSERT INTO c1 VALUES(4, 4); + INSERT INTO c1 VALUES(5, 5); + SELECT count(*) FROM c1; + } +} {3} +do_test e_fkey-47.2 { + execsql { + UPDATE p1 SET b = 10 WHERE b = 5; + SELECT d, c FROM c1; + } +} {{} {} 4 4 5 10} +do_test e_fkey-47.3 { + execsql { + UPDATE p1 SET b = 11 WHERE b = 4; + SELECT d, c FROM c1; + } +} {{} {} 4 11 5 10} +do_test e_fkey-47.4 { + execsql { + UPDATE p1 SET b = 6 WHERE b IS NULL; + SELECT d, c FROM c1; + } +} {{} {} 4 11 5 10} +do_test e_fkey-46.5 { + execsql { SELECT * FROM p1 } +} {{} 6 4 11 5 10} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-65058-57158 +# +# Test an example from the "ON DELETE and ON UPDATE Actions" section +# of foreignkeys.html. +# +drop_all_tables +do_test e_fkey-48.1 { + execsql { + CREATE TABLE artist( + artistid INTEGER PRIMARY KEY, + artistname TEXT + ); + CREATE TABLE track( + trackid INTEGER, + trackname TEXT, + trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE + ); + + INSERT INTO artist VALUES(1, 'Dean Martin'); + INSERT INTO artist VALUES(2, 'Frank Sinatra'); + INSERT INTO track VALUES(11, 'That''s Amore', 1); + INSERT INTO track VALUES(12, 'Christmas Blues', 1); + INSERT INTO track VALUES(13, 'My Way', 2); + } +} {} +do_test e_fkey-48.2 { + execsql { + UPDATE artist SET artistid = 100 WHERE artistname = 'Dean Martin'; + } +} {} +do_test e_fkey-48.3 { + execsql { SELECT * FROM artist } +} {2 {Frank Sinatra} 100 {Dean Martin}} +do_test e_fkey-48.4 { + execsql { SELECT * FROM track } +} {11 {That's Amore} 100 12 {Christmas Blues} 100 13 {My Way} 2} + + +#------------------------------------------------------------------------- +# Verify that adding an FK action does not absolve the user of the +# requirement not to violate the foreign key constraint. +# +# EVIDENCE-OF: R-53968-51642 Configuring an ON UPDATE or ON DELETE +# action does not mean that the foreign key constraint does not need to +# be satisfied. +# +drop_all_tables +do_test e_fkey-49.1 { + execsql { + CREATE TABLE parent(a COLLATE nocase, b, c, PRIMARY KEY(c, a)); + CREATE TABLE child(d DEFAULT 'a', e, f DEFAULT 'c', + FOREIGN KEY(f, d) REFERENCES parent ON UPDATE SET DEFAULT + ); + + INSERT INTO parent VALUES('A', 'b', 'c'); + INSERT INTO parent VALUES('ONE', 'two', 'three'); + INSERT INTO child VALUES('one', 'two', 'three'); + } +} {} +do_test e_fkey-49.2 { + execsql { + BEGIN; + UPDATE parent SET a = '' WHERE a = 'oNe'; + SELECT * FROM child; + } +} {a two c} +do_test e_fkey-49.3 { + execsql { + ROLLBACK; + DELETE FROM parent WHERE a = 'A'; + SELECT * FROM parent; + } +} {ONE two three} +do_test e_fkey-49.4 { + catchsql { UPDATE parent SET a = '' WHERE a = 'oNe' } +} {1 {foreign key constraint failed}} + + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-11856-19836 +# +# Test an example from the "ON DELETE and ON UPDATE Actions" section +# of foreignkeys.html. This example shows that adding an "ON DELETE DEFAULT" +# clause does not abrogate the need to satisfy the foreign key constraint +# (R-28220-46694). +# +# EVIDENCE-OF: R-28220-46694 For example, if an "ON DELETE SET DEFAULT" +# action is configured, but there is no row in the parent table that +# corresponds to the default values of the child key columns, deleting a +# parent key while dependent child keys exist still causes a foreign key +# violation. +# +drop_all_tables +do_test e_fkey-50.1 { + execsql { + CREATE TABLE artist( + artistid INTEGER PRIMARY KEY, + artistname TEXT + ); + CREATE TABLE track( + trackid INTEGER, + trackname TEXT, + trackartist INTEGER DEFAULT 0 REFERENCES artist(artistid) ON DELETE SET DEFAULT + ); + INSERT INTO artist VALUES(3, 'Sammy Davis Jr.'); + INSERT INTO track VALUES(14, 'Mr. Bojangles', 3); + } +} {} +do_test e_fkey-50.2 { + catchsql { DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.' } +} {1 {foreign key constraint failed}} +do_test e_fkey-50.3 { + execsql { + INSERT INTO artist VALUES(0, 'Unknown Artist'); + DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.'; + } +} {} +do_test e_fkey-50.4 { + execsql { SELECT * FROM artist } +} {0 {Unknown Artist}} +do_test e_fkey-50.5 { + execsql { SELECT * FROM track } +} {14 {Mr. Bojangles} 0} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-09564-22170 +# +# Check that the order of steps in an UPDATE or DELETE on a parent +# table is as follows: +# +# 1. Execute applicable BEFORE trigger programs, +# 2. Check local (non foreign key) constraints, +# 3. Update or delete the row in the parent table, +# 4. Perform any required foreign key actions, +# 5. Execute applicable AFTER trigger programs. +# +drop_all_tables +do_test e_fkey-51.1 { + proc maxparent {args} { db one {SELECT max(x) FROM parent} } + db func maxparent maxparent + + execsql { + CREATE TABLE parent(x PRIMARY KEY); + + CREATE TRIGGER bu BEFORE UPDATE ON parent BEGIN + INSERT INTO parent VALUES(new.x-old.x); + END; + CREATE TABLE child( + a DEFAULT (maxparent()) REFERENCES parent ON UPDATE SET DEFAULT + ); + CREATE TRIGGER au AFTER UPDATE ON parent BEGIN + INSERT INTO parent VALUES(new.x+old.x); + END; + + INSERT INTO parent VALUES(1); + INSERT INTO child VALUES(1); + } +} {} +do_test e_fkey-51.2 { + execsql { + UPDATE parent SET x = 22; + SELECT * FROM parent ORDER BY rowid; SELECT 'xxx' ; SELECT a FROM child; + } +} {22 21 23 xxx 22} +do_test e_fkey-51.3 { + execsql { + DELETE FROM child; + DELETE FROM parent; + INSERT INTO parent VALUES(-1); + INSERT INTO child VALUES(-1); + UPDATE parent SET x = 22; + SELECT * FROM parent ORDER BY rowid; SELECT 'xxx' ; SELECT a FROM child; + } +} {22 23 21 xxx 23} + + +#------------------------------------------------------------------------- +# Verify that ON UPDATE actions only actually take place if the parent key +# is set to a new value that is distinct from the old value. The default +# collation sequence and affinity are used to determine if the new value +# is 'distinct' from the old or not. +# +# EVIDENCE-OF: R-27383-10246 An ON UPDATE action is only taken if the +# values of the parent key are modified so that the new parent key +# values are not equal to the old. +# +drop_all_tables +do_test e_fkey-52.1 { + execsql { + CREATE TABLE zeus(a INTEGER COLLATE NOCASE, b, PRIMARY KEY(a, b)); + CREATE TABLE apollo(c, d, + FOREIGN KEY(c, d) REFERENCES zeus ON UPDATE CASCADE + ); + INSERT INTO zeus VALUES('abc', 'xyz'); + INSERT INTO apollo VALUES('ABC', 'xyz'); + } + execsql { + UPDATE zeus SET a = 'aBc'; + SELECT * FROM apollo; + } +} {ABC xyz} +do_test e_fkey-52.2 { + execsql { + UPDATE zeus SET a = 1, b = 1; + SELECT * FROM apollo; + } +} {1 1} +do_test e_fkey-52.3 { + execsql { + UPDATE zeus SET a = 1, b = 1; + SELECT typeof(c), c, typeof(d), d FROM apollo; + } +} {integer 1 integer 1} +do_test e_fkey-52.4 { + execsql { + UPDATE zeus SET a = '1'; + SELECT typeof(c), c, typeof(d), d FROM apollo; + } +} {integer 1 integer 1} +do_test e_fkey-52.5 { + execsql { + UPDATE zeus SET b = '1'; + SELECT typeof(c), c, typeof(d), d FROM apollo; + } +} {integer 1 text 1} +do_test e_fkey-52.6 { + execsql { + UPDATE zeus SET b = NULL; + SELECT typeof(c), c, typeof(d), d FROM apollo; + } +} {integer 1 null {}} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-35129-58141 +# +# Test an example from the "ON DELETE and ON UPDATE Actions" section +# of foreignkeys.html. This example demonstrates that ON UPDATE actions +# only take place if at least one parent key column is set to a value +# that is distinct from its previous value. +# +drop_all_tables +do_test e_fkey-53.1 { + execsql { + CREATE TABLE parent(x PRIMARY KEY); + CREATE TABLE child(y REFERENCES parent ON UPDATE SET NULL); + INSERT INTO parent VALUES('key'); + INSERT INTO child VALUES('key'); + } +} {} +do_test e_fkey-53.2 { + execsql { + UPDATE parent SET x = 'key'; + SELECT IFNULL(y, 'null') FROM child; + } +} {key} +do_test e_fkey-53.3 { + execsql { + UPDATE parent SET x = 'key2'; + SELECT IFNULL(y, 'null') FROM child; + } +} {null} + +########################################################################### +### SECTION 5: CREATE, ALTER and DROP TABLE commands +########################################################################### + +#------------------------------------------------------------------------- +# Test that parent keys are not checked when tables are created. +# +# EVIDENCE-OF: R-36018-21755 The parent key definitions of foreign key +# constraints are not checked when a table is created. +# +# EVIDENCE-OF: R-25384-39337 There is nothing stopping the user from +# creating a foreign key definition that refers to a parent table that +# does not exist, or to parent key columns that do not exist or are not +# collectively bound by a PRIMARY KEY or UNIQUE constraint. +# +# Child keys are checked to ensure all component columns exist. If parent +# key columns are explicitly specified, SQLite checks to make sure there +# are the same number of columns in the child and parent keys. (TODO: This +# is tested but does not correspond to any testable statement.) +# +# Also test that the above statements are true regardless of whether or not +# foreign keys are enabled: "A CREATE TABLE command operates the same whether +# or not foreign key constraints are enabled." +# +# EVIDENCE-OF: R-08908-23439 A CREATE TABLE command operates the same +# whether or not foreign key constraints are enabled. +# +foreach {tn zCreateTbl lRes} { + 1 "CREATE TABLE t1(a, b REFERENCES t1)" {0 {}} + 2 "CREATE TABLE t1(a, b REFERENCES t2)" {0 {}} + 3 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t1)" {0 {}} + 4 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t2)" {0 {}} + 5 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t2)" {0 {}} + 6 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t2(n,d))" {0 {}} + 7 "CREATE TABLE t1(a, b, FOREIGN KEY(a,b) REFERENCES t1(a,b))" {0 {}} + + A "CREATE TABLE t1(a, b, FOREIGN KEY(c,b) REFERENCES t2)" + {1 {unknown column "c" in foreign key definition}} + B "CREATE TABLE t1(a, b, FOREIGN KEY(c,b) REFERENCES t2(d))" + {1 {number of columns in foreign key does not match the number of columns in the referenced table}} +} { + do_test e_fkey-54.$tn.off { + drop_all_tables + execsql {PRAGMA foreign_keys = OFF} + catchsql $zCreateTbl + } $lRes + do_test e_fkey-54.$tn.on { + drop_all_tables + execsql {PRAGMA foreign_keys = ON} + catchsql $zCreateTbl + } $lRes +} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-47952-62498 It is not possible to use the "ALTER TABLE +# ... ADD COLUMN" syntax to add a column that includes a REFERENCES +# clause, unless the default value of the new column is NULL. Attempting +# to do so returns an error. +# +proc test_efkey_6 {tn zAlter isError} { + drop_all_tables + + do_test e_fkey-56.$tn.1 " + execsql { CREATE TABLE tbl(a, b) } + [list catchsql $zAlter] + " [lindex {{0 {}} {1 {Cannot add a REFERENCES column with non-NULL default value}}} $isError] + +} + +test_efkey_6 1 "ALTER TABLE tbl ADD COLUMN c REFERENCES xx" 0 +test_efkey_6 2 "ALTER TABLE tbl ADD COLUMN c DEFAULT NULL REFERENCES xx" 0 +test_efkey_6 3 "ALTER TABLE tbl ADD COLUMN c DEFAULT 0 REFERENCES xx" 1 + +#------------------------------------------------------------------------- +# Test that ALTER TABLE adjusts REFERENCES clauses when the parent table +# is RENAMED. +# +# EVIDENCE-OF: R-47080-02069 If an "ALTER TABLE ... RENAME TO" command +# is used to rename a table that is the parent table of one or more +# foreign key constraints, the definitions of the foreign key +# constraints are modified to refer to the parent table by its new name +# +# Test that these adjustments are visible in the sqlite_master table. +# +# EVIDENCE-OF: R-63827-54774 The text of the child CREATE TABLE +# statement or statements stored in the sqlite_master table are modified +# to reflect the new parent table name. +# +do_test e_fkey-56.1 { + drop_all_tables + execsql { + CREATE TABLE 'p 1 "parent one"'(a REFERENCES 'p 1 "parent one"', b, PRIMARY KEY(b)); + + CREATE TABLE c1(c, d REFERENCES 'p 1 "parent one"' ON UPDATE CASCADE); + CREATE TABLE c2(e, f, FOREIGN KEY(f) REFERENCES 'p 1 "parent one"' ON UPDATE CASCADE); + CREATE TABLE c3(e, 'f col 2', FOREIGN KEY('f col 2') REFERENCES 'p 1 "parent one"' ON UPDATE CASCADE); + + INSERT INTO 'p 1 "parent one"' VALUES(1, 1); + INSERT INTO c1 VALUES(1, 1); + INSERT INTO c2 VALUES(1, 1); + INSERT INTO c3 VALUES(1, 1); + + -- CREATE TABLE q(a, b, PRIMARY KEY(b)); + } +} {} +do_test e_fkey-56.2 { + execsql { ALTER TABLE 'p 1 "parent one"' RENAME TO p } +} {} +do_test e_fkey-56.3 { + execsql { + UPDATE p SET a = 'xxx', b = 'xxx'; + SELECT * FROM p; + SELECT * FROM c1; + SELECT * FROM c2; + SELECT * FROM c3; + } +} {xxx xxx 1 xxx 1 xxx 1 xxx} +do_test e_fkey-56.4 { + execsql { SELECT sql FROM sqlite_master WHERE type = 'table'} +} [list \ + {CREATE TABLE "p"(a REFERENCES "p", b, PRIMARY KEY(b))} \ + {CREATE TABLE c1(c, d REFERENCES "p" ON UPDATE CASCADE)} \ + {CREATE TABLE c2(e, f, FOREIGN KEY(f) REFERENCES "p" ON UPDATE CASCADE)} \ + {CREATE TABLE c3(e, 'f col 2', FOREIGN KEY('f col 2') REFERENCES "p" ON UPDATE CASCADE)} \ +] + +#------------------------------------------------------------------------- +# Check that a DROP TABLE does an implicit DELETE FROM. Which does not +# cause any triggers to fire, but does fire foreign key actions. +# +# EVIDENCE-OF: R-14208-23986 If foreign key constraints are enabled when +# it is prepared, the DROP TABLE command performs an implicit DELETE to +# remove all rows from the table before dropping it. +# +# EVIDENCE-OF: R-11078-03945 The implicit DELETE does not cause any SQL +# triggers to fire, but may invoke foreign key actions or constraint +# violations. +# +do_test e_fkey-57.1 { + drop_all_tables + execsql { + CREATE TABLE p(a, b, PRIMARY KEY(a, b)); + + CREATE TABLE c1(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE SET NULL); + CREATE TABLE c2(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE SET DEFAULT); + CREATE TABLE c3(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE CASCADE); + CREATE TABLE c4(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE RESTRICT); + CREATE TABLE c5(c, d, FOREIGN KEY(c, d) REFERENCES p ON DELETE NO ACTION); + + CREATE TABLE c6(c, d, + FOREIGN KEY(c, d) REFERENCES p ON DELETE RESTRICT + DEFERRABLE INITIALLY DEFERRED + ); + CREATE TABLE c7(c, d, + FOREIGN KEY(c, d) REFERENCES p ON DELETE NO ACTION + DEFERRABLE INITIALLY DEFERRED + ); + + CREATE TABLE log(msg); + CREATE TRIGGER tt AFTER DELETE ON p BEGIN + INSERT INTO log VALUES('delete ' || old.rowid); + END; + } +} {} + +do_test e_fkey-57.2 { + execsql { + INSERT INTO p VALUES('a', 'b'); + INSERT INTO c1 VALUES('a', 'b'); + INSERT INTO c2 VALUES('a', 'b'); + INSERT INTO c3 VALUES('a', 'b'); + BEGIN; + DROP TABLE p; + SELECT * FROM c1; + } +} {{} {}} +do_test e_fkey-57.3 { + execsql { SELECT * FROM c2 } +} {{} {}} +do_test e_fkey-57.4 { + execsql { SELECT * FROM c3 } +} {} +do_test e_fkey-57.5 { + execsql { SELECT * FROM log } +} {} +do_test e_fkey-57.6 { + execsql ROLLBACK +} {} +do_test e_fkey-57.7 { + execsql { + BEGIN; + DELETE FROM p; + SELECT * FROM log; + ROLLBACK; + } +} {{delete 1}} + +#------------------------------------------------------------------------- +# If an IMMEDIATE foreign key fails as a result of a DROP TABLE, the +# DROP TABLE command fails. +# +# EVIDENCE-OF: R-32768-47925 If an immediate foreign key constraint is +# violated, the DROP TABLE statement fails and the table is not dropped. +# +do_test e_fkey-58.1 { + execsql { + DELETE FROM c1; + DELETE FROM c2; + DELETE FROM c3; + } + execsql { INSERT INTO c5 VALUES('a', 'b') } + catchsql { DROP TABLE p } +} {1 {foreign key constraint failed}} +do_test e_fkey-58.2 { + execsql { SELECT * FROM p } +} {a b} +do_test e_fkey-58.3 { + catchsql { + BEGIN; + DROP TABLE p; + } +} {1 {foreign key constraint failed}} +do_test e_fkey-58.4 { + execsql { + SELECT * FROM p; + SELECT * FROM c5; + ROLLBACK; + } +} {a b a b} + +#------------------------------------------------------------------------- +# If a DEFERRED foreign key fails as a result of a DROP TABLE, attempting +# to commit the transaction fails unless the violation is fixed. +# +# EVIDENCE-OF: R-05903-08460 If a deferred foreign key constraint is +# violated, then an error is reported when the user attempts to commit +# the transaction if the foreign key constraint violations still exist +# at that point. +# +do_test e_fkey-59.1 { + execsql { + DELETE FROM c1 ; DELETE FROM c2 ; DELETE FROM c3 ; + DELETE FROM c4 ; DELETE FROM c5 ; DELETE FROM c6 ; + DELETE FROM c7 + } +} {} +do_test e_fkey-59.2 { + execsql { INSERT INTO c7 VALUES('a', 'b') } + execsql { + BEGIN; + DROP TABLE p; + } +} {} +do_test e_fkey-59.3 { + catchsql COMMIT +} {1 {foreign key constraint failed}} +do_test e_fkey-59.4 { + execsql { CREATE TABLE p(a, b, PRIMARY KEY(a, b)) } + catchsql COMMIT +} {1 {foreign key constraint failed}} +do_test e_fkey-59.5 { + execsql { INSERT INTO p VALUES('a', 'b') } + execsql COMMIT +} {} + +#------------------------------------------------------------------------- +# Any "foreign key mismatch" errors encountered while running an implicit +# "DELETE FROM tbl" are ignored. +# +# EVIDENCE-OF: R-57242-37005 Any "foreign key mismatch" errors +# encountered as part of an implicit DELETE are ignored. +# +drop_all_tables +do_test e_fkey-60.1 { + execsql { + PRAGMA foreign_keys = OFF; + + CREATE TABLE p(a PRIMARY KEY, b REFERENCES nosuchtable); + CREATE TABLE c1(c, d, FOREIGN KEY(c, d) REFERENCES a); + CREATE TABLE c2(c REFERENCES p(b), d); + CREATE TABLE c3(c REFERENCES p ON DELETE SET NULL, d); + + INSERT INTO p VALUES(1, 2); + INSERT INTO c1 VALUES(1, 2); + INSERT INTO c2 VALUES(1, 2); + INSERT INTO c3 VALUES(1, 2); + } +} {} +do_test e_fkey-60.2 { + execsql { PRAGMA foreign_keys = ON } + catchsql { DELETE FROM p } +} {1 {no such table: main.nosuchtable}} +do_test e_fkey-60.3 { + execsql { + BEGIN; + DROP TABLE p; + SELECT * FROM c3; + ROLLBACK; + } +} {{} 2} +do_test e_fkey-60.4 { + execsql { CREATE TABLE nosuchtable(x PRIMARY KEY) } + catchsql { DELETE FROM p } +} {1 {foreign key mismatch - "c2" referencing "p"}} +do_test e_fkey-60.5 { + execsql { DROP TABLE c1 } + catchsql { DELETE FROM p } +} {1 {foreign key mismatch - "c2" referencing "p"}} +do_test e_fkey-60.6 { + execsql { DROP TABLE c2 } + execsql { DELETE FROM p } +} {} + +#------------------------------------------------------------------------- +# Test that the special behaviors of ALTER and DROP TABLE are only +# activated when foreign keys are enabled. Special behaviors are: +# +# 1. ADD COLUMN not allowing a REFERENCES clause with a non-NULL +# default value. +# 2. Modifying foreign key definitions when a parent table is RENAMEd. +# 3. Running an implicit DELETE FROM command as part of DROP TABLE. +# +# EVIDENCE-OF: R-54142-41346 The properties of the DROP TABLE and ALTER +# TABLE commands described above only apply if foreign keys are enabled. +# +do_test e_fkey-61.1.1 { + drop_all_tables + execsql { CREATE TABLE t1(a, b) } + catchsql { ALTER TABLE t1 ADD COLUMN c DEFAULT 'xxx' REFERENCES t2 } +} {1 {Cannot add a REFERENCES column with non-NULL default value}} +do_test e_fkey-61.1.2 { + execsql { PRAGMA foreign_keys = OFF } + execsql { ALTER TABLE t1 ADD COLUMN c DEFAULT 'xxx' REFERENCES t2 } + execsql { SELECT sql FROM sqlite_master WHERE name = 't1' } +} {{CREATE TABLE t1(a, b, c DEFAULT 'xxx' REFERENCES t2)}} +do_test e_fkey-61.1.3 { + execsql { PRAGMA foreign_keys = ON } +} {} + +do_test e_fkey-61.2.1 { + drop_all_tables + execsql { + CREATE TABLE p(a UNIQUE); + CREATE TABLE c(b REFERENCES p(a)); + BEGIN; + ALTER TABLE p RENAME TO parent; + SELECT sql FROM sqlite_master WHERE name = 'c'; + ROLLBACK; + } +} {{CREATE TABLE c(b REFERENCES "parent"(a))}} +do_test e_fkey-61.2.2 { + execsql { + PRAGMA foreign_keys = OFF; + ALTER TABLE p RENAME TO parent; + SELECT sql FROM sqlite_master WHERE name = 'c'; + } +} {{CREATE TABLE c(b REFERENCES p(a))}} +do_test e_fkey-61.2.3 { + execsql { PRAGMA foreign_keys = ON } +} {} + +do_test e_fkey-61.3.1 { + drop_all_tables + execsql { + CREATE TABLE p(a UNIQUE); + CREATE TABLE c(b REFERENCES p(a) ON DELETE SET NULL); + INSERT INTO p VALUES('x'); + INSERT INTO c VALUES('x'); + BEGIN; + DROP TABLE p; + SELECT * FROM c; + ROLLBACK; + } +} {{}} +do_test e_fkey-61.3.2 { + execsql { + PRAGMA foreign_keys = OFF; + DROP TABLE p; + SELECT * FROM c; + } +} {x} +do_test e_fkey-61.3.3 { + execsql { PRAGMA foreign_keys = ON } +} {} + +########################################################################### +### SECTION 6: Limits and Unsupported Features +########################################################################### + +#------------------------------------------------------------------------- +# Test that MATCH clauses are parsed, but SQLite treats every foreign key +# constraint as if it were "MATCH SIMPLE". +# +# EVIDENCE-OF: R-24728-13230 SQLite parses MATCH clauses (i.e. does not +# report a syntax error if you specify one), but does not enforce them. +# +# EVIDENCE-OF: R-24450-46174 All foreign key constraints in SQLite are +# handled as if MATCH SIMPLE were specified. +# +foreach zMatch [list SIMPLE PARTIAL FULL Simple parTIAL FuLL ] { + drop_all_tables + do_test e_fkey-62.$zMatch.1 { + execsql " + CREATE TABLE p(a, b, c, PRIMARY KEY(b, c)); + CREATE TABLE c(d, e, f, FOREIGN KEY(e, f) REFERENCES p MATCH $zMatch); + " + } {} + do_test e_fkey-62.$zMatch.2 { + execsql { INSERT INTO p VALUES(1, 2, 3) } + + # MATCH SIMPLE behavior: Allow any child key that contains one or more + # NULL value to be inserted. Non-NULL values do not have to map to any + # parent key values, so long as at least one field of the child key is + # NULL. + execsql { INSERT INTO c VALUES('w', 2, 3) } + execsql { INSERT INTO c VALUES('x', 'x', NULL) } + execsql { INSERT INTO c VALUES('y', NULL, 'x') } + execsql { INSERT INTO c VALUES('z', NULL, NULL) } + + # Check that the FK is enforced properly if there are no NULL values + # in the child key columns. + catchsql { INSERT INTO c VALUES('a', 2, 4) } + } {1 {foreign key constraint failed}} +} + +#------------------------------------------------------------------------- +# Test that SQLite does not support the SET CONSTRAINT statement. And +# that it is possible to create both immediate and deferred constraints. +# +# EVIDENCE-OF: R-21599-16038 In SQLite, a foreign key constraint is +# permanently marked as deferred or immediate when it is created. +# +drop_all_tables +do_test e_fkey-62.1 { + catchsql { SET CONSTRAINTS ALL IMMEDIATE } +} {1 {near "SET": syntax error}} +do_test e_fkey-62.2 { + catchsql { SET CONSTRAINTS ALL DEFERRED } +} {1 {near "SET": syntax error}} + +do_test e_fkey-62.3 { + execsql { + CREATE TABLE p(a, b, PRIMARY KEY(a, b)); + CREATE TABLE cd(c, d, + FOREIGN KEY(c, d) REFERENCES p DEFERRABLE INITIALLY DEFERRED); + CREATE TABLE ci(c, d, + FOREIGN KEY(c, d) REFERENCES p DEFERRABLE INITIALLY IMMEDIATE); + BEGIN; + } +} {} +do_test e_fkey-62.4 { + catchsql { INSERT INTO ci VALUES('x', 'y') } +} {1 {foreign key constraint failed}} +do_test e_fkey-62.5 { + catchsql { INSERT INTO cd VALUES('x', 'y') } +} {0 {}} +do_test e_fkey-62.6 { + catchsql { COMMIT } +} {1 {foreign key constraint failed}} +do_test e_fkey-62.7 { + execsql { + DELETE FROM cd; + COMMIT; + } +} {} + +#------------------------------------------------------------------------- +# Test that the maximum recursion depth of foreign key action programs is +# governed by the SQLITE_MAX_TRIGGER_DEPTH and SQLITE_LIMIT_TRIGGER_DEPTH +# settings. +# +# EVIDENCE-OF: R-42264-30503 The SQLITE_MAX_TRIGGER_DEPTH and +# SQLITE_LIMIT_TRIGGER_DEPTH settings determine the maximum allowable +# depth of trigger program recursion. For the purposes of these limits, +# foreign key actions are considered trigger programs. +# +proc test_on_delete_recursion {limit} { + drop_all_tables + execsql { + BEGIN; + CREATE TABLE t0(a PRIMARY KEY, b); + INSERT INTO t0 VALUES('x0', NULL); + } + for {set i 1} {$i <= $limit} {incr i} { + execsql " + CREATE TABLE t$i ( + a PRIMARY KEY, b REFERENCES t[expr $i-1] ON DELETE CASCADE + ); + INSERT INTO t$i VALUES('x$i', 'x[expr $i-1]'); + " + } + execsql COMMIT + catchsql " + DELETE FROM t0; + SELECT count(*) FROM t$limit; + " +} +proc test_on_update_recursion {limit} { + drop_all_tables + execsql { + BEGIN; + CREATE TABLE t0(a PRIMARY KEY); + INSERT INTO t0 VALUES('xxx'); + } + for {set i 1} {$i <= $limit} {incr i} { + set j [expr $i-1] + + execsql " + CREATE TABLE t$i (a PRIMARY KEY REFERENCES t$j ON UPDATE CASCADE); + INSERT INTO t$i VALUES('xxx'); + " + } + execsql COMMIT + catchsql " + UPDATE t0 SET a = 'yyy'; + SELECT NOT (a='yyy') FROM t$limit; + " +} + +do_test e_fkey-63.1.1 { + test_on_delete_recursion $SQLITE_MAX_TRIGGER_DEPTH +} {0 0} +do_test e_fkey-63.1.2 { + test_on_delete_recursion [expr $SQLITE_MAX_TRIGGER_DEPTH+1] +} {1 {too many levels of trigger recursion}} +do_test e_fkey-63.1.3 { + sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 5 + test_on_delete_recursion 5 +} {0 0} +do_test e_fkey-63.1.4 { + test_on_delete_recursion 6 +} {1 {too many levels of trigger recursion}} +do_test e_fkey-63.1.5 { + sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 1000000 +} {5} +do_test e_fkey-63.2.1 { + test_on_update_recursion $SQLITE_MAX_TRIGGER_DEPTH +} {0 0} +do_test e_fkey-63.2.2 { + test_on_update_recursion [expr $SQLITE_MAX_TRIGGER_DEPTH+1] +} {1 {too many levels of trigger recursion}} +do_test e_fkey-63.2.3 { + sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 5 + test_on_update_recursion 5 +} {0 0} +do_test e_fkey-63.2.4 { + test_on_update_recursion 6 +} {1 {too many levels of trigger recursion}} +do_test e_fkey-63.2.5 { + sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 1000000 +} {5} + +#------------------------------------------------------------------------- +# The setting of the recursive_triggers pragma does not affect foreign +# key actions. +# +# EVIDENCE-OF: R-51769-32730 The PRAGMA recursive_triggers setting does +# not not affect the operation of foreign key actions. +# +foreach recursive_triggers_setting [list 0 1 ON OFF] { + drop_all_tables + execsql "PRAGMA recursive_triggers = $recursive_triggers_setting" + + do_test e_fkey-64.$recursive_triggers_setting.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1 ON DELETE CASCADE); + INSERT INTO t1 VALUES(1, NULL); + INSERT INTO t1 VALUES(2, 1); + INSERT INTO t1 VALUES(3, 2); + INSERT INTO t1 VALUES(4, 3); + INSERT INTO t1 VALUES(5, 4); + SELECT count(*) FROM t1; + } + } {5} + do_test e_fkey-64.$recursive_triggers_setting.2 { + execsql { SELECT count(*) FROM t1 WHERE a = 1 } + } {1} + do_test e_fkey-64.$recursive_triggers_setting.3 { + execsql { + DELETE FROM t1 WHERE a = 1; + SELECT count(*) FROM t1; + } + } {0} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_fts3.test b/components/external/SQLite-3.8.1/test/e_fts3.test new file mode 100644 index 0000000000000000000000000000000000000000..2a580ca313424ca9fc8bf09ed7b6e30846e027ba --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_fts3.test @@ -0,0 +1,706 @@ +# 2009 November 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify the "testable statements" in the +# fts3.in document. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If this build does not include FTS3, skip the tests in this file. +# +ifcapable !fts3 { finish_test ; return } +source $testdir/fts3_common.tcl +source $testdir/malloc_common.tcl + +# Procs used to make the tests in this file easier to read. +# +proc ddl_test {tn ddl} { + uplevel [list do_write_test e_fts3-$tn sqlite_master $ddl] +} +proc write_test {tn tbl sql} { + uplevel [list do_write_test e_fts3-$tn $tbl $sql] +} +proc read_test {tn sql result} { + uplevel [list do_select_test e_fts3-$tn $sql $result] +} +proc error_test {tn sql result} { + uplevel [list do_error_test e_fts3-$tn $sql $result] +} + + +#------------------------------------------------------------------------- +# The body of the following [foreach] block contains test cases to verify +# that the example code in fts3.html works as expected. The tests run three +# times, with different values for DO_MALLOC_TEST. +# +# DO_MALLOC_TEST=0: Run tests with no OOM errors. +# DO_MALLOC_TEST=1: Run tests with transient OOM errors. +# DO_MALLOC_TEST=2: Run tests with persistent OOM errors. +# +foreach {DO_MALLOC_TEST enc} { + 0 utf-8 + 1 utf-8 + 2 utf-8 + 1 utf-16 +} { + +#if {$DO_MALLOC_TEST} break + +# Reset the database and database connection. If this iteration of the +# [foreach] loop is testing with OOM errors, disable the lookaside buffer. +# +db close +forcedelete test.db test.db-journal +sqlite3 db test.db +if {$DO_MALLOC_TEST} { sqlite3_db_config_lookaside db 0 0 0 } +db eval "PRAGMA encoding = '$enc'" + +proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r +} +db func mit mit + +########################################################################## +# Test the example CREATE VIRTUAL TABLE statements in section 1.1 +# of fts3.in. +# +ddl_test 1.1.1.1 {CREATE VIRTUAL TABLE data USING fts3()} +read_test 1.1.1.2 {PRAGMA table_info(data)} {0 content {} 0 {} 0} + +ddl_test 1.1.2.1 { + CREATE VIRTUAL TABLE pages USING fts3(title, keywords, body) +} +read_test 1.1.2.2 { + PRAGMA table_info(pages) +} {0 title {} 0 {} 0 1 keywords {} 0 {} 0 2 body {} 0 {} 0} + +ddl_test 1.1.3.1 { + CREATE VIRTUAL TABLE mail USING fts3( + subject VARCHAR(256) NOT NULL, + body TEXT CHECK(length(body)<10240) + ) +} +read_test 1.1.3.2 { + PRAGMA table_info(mail) +} {0 subject {} 0 {} 0 1 body {} 0 {} 0} + +# A very large string. Used to test if the constraint on column "body" of +# table "mail" is enforced (it should not be - FTS3 tables do not support +# constraints). +set largetext [string repeat "the quick brown fox " 5000] +write_test 1.1.3.3 mail_content { INSERT INTO mail VALUES(NULL, $largetext) } +read_test 1.1.3.4 { + SELECT subject IS NULL, length(body) FROM mail +} [list 1 100000] + +ddl_test 1.1.4.1 { + CREATE VIRTUAL TABLE papers USING fts3(author, document, tokenize=porter) +} +read_test 1.1.4.2 { + PRAGMA table_info(papers) +} {0 author {} 0 {} 0 1 document {} 0 {} 0} + +ddl_test 1.1.5.1 { + CREATE VIRTUAL TABLE simpledata USING fts3(tokenize=simple) +} +read_test 1.1.5.2 { + PRAGMA table_info(simpledata) +} {0 content {} 0 {} 0} + +ifcapable icu { + ddl_test 1.1.6.1 { + CREATE VIRTUAL TABLE names USING fts3(a, b, tokenize=icu en_AU) + } + read_test 1.1.6.2 { + PRAGMA table_info(names) + } {0 a {} 0 {} 0 1 b {} 0 {} 0} +} + +ddl_test 1.1.7.1 {DROP TABLE data} +ddl_test 1.1.7.2 {DROP TABLE pages} +ddl_test 1.1.7.3 {DROP TABLE mail} +ddl_test 1.1.7.4 {DROP TABLE papers} +ddl_test 1.1.7.5 {DROP TABLE simpledata} +read_test 1.1.7.6 {SELECT * FROM sqlite_master} {} + +# The following is not one of the examples in section 1.1. It tests +# specifying an FTS3 table with no module arguments using a slightly +# different syntax. +ddl_test 1.1.8.1 {CREATE VIRTUAL TABLE data USING fts3;} +read_test 1.1.8.2 {PRAGMA table_info(data)} {0 content {} 0 {} 0} +ddl_test 1.1.8.3 {DROP TABLE data} + +########################################################################## +# Test the examples in section 1.2 (populating fts3 tables) +# +ddl_test 1.2.1.1 { + CREATE VIRTUAL TABLE pages USING fts3(title, body); +} +write_test 1.2.1.2 pages_content { + INSERT INTO pages(docid, title, body) + VALUES(53, 'Home Page', 'SQLite is a software...'); +} +read_test 1.2.1.3 { + SELECT docid, * FROM pages +} {53 {Home Page} {SQLite is a software...}} + +write_test 1.2.1.4 pages_content { + INSERT INTO pages(title, body) + VALUES('Download', 'All SQLite source code...'); +} +read_test 1.2.1.5 { + SELECT docid, * FROM pages +} {53 {Home Page} {SQLite is a software...} 54 Download {All SQLite source code...}} + +write_test 1.2.1.6 pages_content { + UPDATE pages SET title = 'Download SQLite' WHERE rowid = 54 +} +read_test 1.2.1.7 { + SELECT docid, * FROM pages +} {53 {Home Page} {SQLite is a software...} 54 {Download SQLite} {All SQLite source code...}} + +write_test 1.2.1.8 pages_content { DELETE FROM pages } +read_test 1.2.1.9 { SELECT docid, * FROM pages } {} + +do_error_test fts3-1.2.1.10 { + INSERT INTO pages(rowid, docid, title, body) VALUES(1, 2, 'A title', 'A document body'); +} {SQL logic error or missing database} + +# Test the optimize() function example: +ddl_test 1.2.2.1 { CREATE VIRTUAL TABLE docs USING fts3 } +write_test 1.2.2.2 docs_content { + INSERT INTO docs VALUES('Others translate the first clause as'); +} +write_test 1.2.2.3 docs_content { + INSERT INTO docs VALUES('"which is for Solomon," meaning that'); +} +write_test 1.2.2.4 docs_content { + INSERT INTO docs VALUES('the book is dedicated to Solomon.'); +} +read_test 1.2.2.5 { SELECT count(*) FROM docs_segdir } {3} +write_test 1.2.2.6 docs_segdir { + INSERT INTO docs(docs) VALUES('optimize'); +} +read_test 1.2.2.7 { SELECT count(*) FROM docs_segdir } {1} +ddl_test 1.2.2.8 { DROP TABLE docs } + +########################################################################## +# Test the examples in section 1.3 (querying FTS3 tables) +# +ddl_test 1.3.1.1 { CREATE VIRTUAL TABLE mail USING fts3(subject, body) } +read_test 1.3.1.2 { + SELECT * FROM mail WHERE rowid = 15; -- Fast. Rowid lookup. + SELECT * FROM mail WHERE body MATCH 'sqlite'; -- Fast. Full-text query. + SELECT * FROM mail WHERE mail MATCH 'search'; -- Fast. Full-text query. + SELECT * FROM mail WHERE rowid BETWEEN 15 AND 20; -- Slow. Linear scan. + SELECT * FROM mail WHERE subject = 'database'; -- Slow. Linear scan. + SELECT * FROM mail WHERE subject MATCH 'database'; -- Fast. Full-text query. +} {} +ddl_test 1.3.1.3 { DROP TABLE mail } + +ddl_test 1.3.2.1 { CREATE VIRTUAL TABLE mail USING fts3(subject, body) } + +write_test 1.3.2.2 mail_content { + INSERT INTO mail(docid, subject, body) + VALUES(1, 'software feedback', 'found it too slow') +} +write_test 1.3.2.3 mail_content { + INSERT INTO mail(docid, subject, body) + VALUES(2, 'software feedback', 'no feedback') +} +write_test 1.3.2.4 mail_content { + INSERT INTO mail(docid, subject, body) + VALUES(3, 'slow lunch order', 'was a software problem') +} +read_test 1.3.2.5 { + SELECT * FROM mail WHERE subject MATCH 'software' +} {{software feedback} {found it too slow} {software feedback} {no feedback}} +read_test 1.3.2.6 { + SELECT * FROM mail WHERE body MATCH 'feedback' +} {{software feedback} {no feedback}} +read_test 1.3.2.7 { + SELECT * FROM mail WHERE mail MATCH 'software' +} {{software feedback} {found it too slow} {software feedback} {no feedback} {slow lunch order} {was a software problem}} +read_test 1.3.2.7 { + SELECT * FROM mail WHERE mail MATCH 'slow' +} {{software feedback} {found it too slow} {slow lunch order} {was a software problem}} +ddl_test 1.3.2.8 { DROP TABLE mail } + +ddl_test 1.3.3.1 { CREATE VIRTUAL TABLE docs USING fts3(content) } +read_test 1.3.3.2 { SELECT * FROM docs WHERE docs MATCH 'sqlite' } {} +read_test 1.3.3.3 { SELECT * FROM docs WHERE docs.docs MATCH 'sqlite' } {} +read_test 1.3.3.4 { SELECT * FROM docs WHERE main.docs.docs MATCH 'sqlite' } {} +do_error_test e_fts3-1.3.3.5 { + SELECT * FROM docs WHERE main.docs MATCH 'sqlite' +} {no such column: main.docs} +ddl_test 1.3.2.8 { DROP TABLE docs } + +########################################################################## +# Test the examples in section 3 (full-text index queries). +# +ddl_test 1.4.1.1 { CREATE VIRTUAL TABLE docs USING fts3(title, body) } +unset -nocomplain R +foreach {tn title body} { + 2 "linux driver" "a device" + 3 "driver" "linguistic trick" + 4 "problems" "linux problems" + 5 "linux" "big problems" + 6 "linux driver" "a device driver problem" + 7 "good times" "applications for linux" + 8 "not so good" "linux applications" + 9 "alternative" "linoleum appliances" + 10 "no L I N" "to be seen" +} { + write_test 1.4.1.$tn docs_content { INSERT INTO docs VALUES($title,$body) } + set R($tn) [list $title $body] +} + +read_test 1.4.1.11 { + SELECT * FROM docs WHERE docs MATCH 'linux' +} [concat $R(2) $R(4) $R(5) $R(6) $R(7) $R(8)] +read_test 1.4.1.12 { + SELECT * FROM docs WHERE docs MATCH 'lin*' +} [concat $R(2) $R(3) $R(4) $R(5) $R(6) $R(7) $R(8) $R(9)] +read_test 1.4.1.13 { + SELECT * FROM docs WHERE docs MATCH 'title:linux problems' +} [concat $R(5)] +read_test 1.4.1.14 { + SELECT * FROM docs WHERE body MATCH 'title:linux driver' +} [concat $R(6)] +read_test 1.4.1.15 { + SELECT * FROM docs WHERE docs MATCH '"linux applications"' +} [concat $R(8)] +read_test 1.4.1.16 { + SELECT * FROM docs WHERE docs MATCH '"lin* app*"' +} [concat $R(8) $R(9)] +ddl_test 1.4.1.17 { DROP TABLE docs } +unset R + +ddl_test 1.4.2.1 { CREATE VIRTUAL TABLE docs USING fts3() } +write_test 1.4.2.2 docs_content { + INSERT INTO docs VALUES( + 'SQLite is an ACID compliant embedded relational database management system') +} +foreach {tn query hit} { +3 {SELECT * FROM docs WHERE docs MATCH 'sqlite NEAR database'} 1 +4 {SELECT * FROM docs WHERE docs MATCH 'database NEAR/6 sqlite'} 1 +5 {SELECT * FROM docs WHERE docs MATCH 'database NEAR/5 sqlite'} 0 +6 {SELECT * FROM docs WHERE docs MATCH 'database NEAR/2 "ACID compliant"'} 1 +7 {SELECT * FROM docs WHERE docs MATCH '"ACID compliant" NEAR/2 sqlite'} 1 +8 {SELECT * FROM docs WHERE docs MATCH 'sqlite NEAR/2 acid NEAR/2 relational'} 1 +9 {SELECT * FROM docs WHERE docs MATCH 'acid NEAR/2 sqlite NEAR/2 relational'} 0 +} { + set res [db eval {SELECT * FROM docs WHERE $hit}] + read_test 1.4.2.$tn $query $res +} +ddl_test 1.4.2.10 { DROP TABLE docs } + +########################################################################## +# Test the example in section 3.1 (set operators with enhanced syntax). +# +set sqlite_fts3_enable_parentheses 1 +ddl_test 1.5.1.1 { CREATE VIRTUAL TABLE docs USING fts3() } +foreach {tn docid content} { + 2 1 "a database is a software system" + 3 2 "sqlite is a software system" + 4 3 "sqlite is a database" +} { + set R($docid) $content + write_test 1.5.1.$tn docs_content { + INSERT INTO docs(docid, content) VALUES($docid, $content) + } +} +read_test 1.5.1.4 { + SELECT * FROM docs WHERE docs MATCH 'sqlite AND database' +} [list $R(3)] +read_test 1.5.1.5 { + SELECT * FROM docs WHERE docs MATCH 'database sqlite' +} [list $R(3)] +read_test 1.5.1.6 { + SELECT * FROM docs WHERE docs MATCH 'sqlite OR database' +} [list $R(1) $R(2) $R(3)] +read_test 1.5.1.7 { + SELECT * FROM docs WHERE docs MATCH 'database NOT sqlite' +} [list $R(1)] +read_test 1.5.1.8 { + SELECT * FROM docs WHERE docs MATCH 'database and sqlite' +} {} + +write_test 1.5.2.1 docs_content { + INSERT INTO docs + SELECT 'sqlite is also a library' UNION ALL + SELECT 'library software' +} +read_test 1.5.2.2 { + SELECT docid FROM docs WHERE docs MATCH 'sqlite AND database OR library' +} {3 4 5} +read_test 1.5.2.3 { + SELECT docid FROM docs WHERE docs MATCH 'sqlite AND database' + UNION + SELECT docid FROM docs WHERE docs MATCH 'library' +} {3 4 5} +write_test 1.5.2.4 docs_content { + INSERT INTO docs + SELECT 'the sqlite library runs on linux' UNION ALL + SELECT 'as does the sqlite database (on linux)' UNION ALL + SELECT 'the sqlite database is accessed by the sqlite library' +} +read_test 1.5.2.2 { + SELECT docid FROM docs + WHERE docs MATCH '("sqlite database" OR "sqlite library") AND linux'; +} {6 7} +read_test 1.5.2.3 { + SELECT docid FROM docs WHERE docs MATCH 'linux' + INTERSECT + SELECT docid FROM ( + SELECT docid FROM docs WHERE docs MATCH '"sqlite library"' + UNION + SELECT docid FROM docs WHERE docs MATCH '"sqlite database"' + ); +} {6 7} + +########################################################################## +# Test the examples in section 3.2 (set operators with standard syntax). +# These tests reuse the table populated by the block above. +# +set sqlite_fts3_enable_parentheses 0 +read_test 1.6.1.1 { + SELECT * FROM docs WHERE docs MATCH 'sqlite -database' +} {{sqlite is a software system} {sqlite is also a library} {the sqlite library runs on linux}} +read_test 1.6.1.2 { + SELECT * FROM docs WHERE docs MATCH 'sqlite OR database library' +} {{sqlite is also a library} {the sqlite library runs on linux} {the sqlite database is accessed by the sqlite library}} + +set sqlite_fts3_enable_parentheses 1 +read_test 1.6.1.3 { + SELECT * FROM docs WHERE docs MATCH 'sqlite OR database library' +} {{sqlite is a software system} {sqlite is a database} {sqlite is also a library} {the sqlite library runs on linux} {as does the sqlite database (on linux)} {the sqlite database is accessed by the sqlite library}} +read_test 1.6.1.4 { + SELECT * FROM docs WHERE docs MATCH '(sqlite OR database) library' +} {{sqlite is also a library} {the sqlite library runs on linux} {the sqlite database is accessed by the sqlite library}} +set sqlite_fts3_enable_parentheses 0 +ddl_test 1.6.1.5 { DROP TABLE docs } + +########################################################################## +# Test the examples in section 4 (auxillary functions). +# +ddl_test 1.7.1.1 { CREATE VIRTUAL TABLE mail USING fts3(subject, body) } + +write_test 1.7.1.2 mail_content { + INSERT INTO mail VALUES( + 'hello world', 'This message is a hello world message.'); +} +write_test 1.7.1.3 mail_content { + INSERT INTO mail VALUES( + 'urgent: serious', 'This mail is seen as a more serious mail'); +} + +read_test 1.7.1.4 { + SELECT offsets(mail) FROM mail WHERE mail MATCH 'world'; +} {{0 0 6 5 1 0 24 5}} +read_test 1.7.1.5 { + SELECT offsets(mail) FROM mail WHERE mail MATCH 'message' +} {{1 0 5 7 1 0 30 7}} +read_test 1.7.1.6 { + SELECT offsets(mail) FROM mail WHERE mail MATCH '"serious mail"' +} {{1 0 28 7 1 1 36 4}} + +ddl_test 1.7.2.1 { CREATE VIRTUAL TABLE text USING fts3() } + +write_test 1.7.2.2 text_content { + INSERT INTO text VALUES(' + During 30 Nov-1 Dec, 2-3oC drops. Cool in the upper portion, minimum temperature 14-16oC and cool elsewhere, minimum temperature 17-20oC. Cold to very cold on mountaintops, minimum temperature 6-12oC. Northeasterly winds 15-30 km/hr. After that, temperature increases. Northeasterly winds 15-30 km/hr. + '); +} + +read_test 1.7.2.3 { + SELECT snippet(text) FROM text WHERE text MATCH 'cold' +} {{...cool elsewhere, minimum temperature 17-20oC. Cold to very cold on mountaintops, minimum temperature 6...}} + +read_test 1.7.2.4 { + SELECT snippet(text, '[', ']', '...') FROM text WHERE text MATCH '"min* tem*"' +} {{...the upper portion, [minimum] [temperature] 14-16oC and cool elsewhere, [minimum] [temperature] 17-20oC. Cold...}} + +ddl_test 1.7.3.1 { DROP TABLE IF EXISTS t1 } +ddl_test 1.7.3.2 { CREATE VIRTUAL TABLE t1 USING fts3(a, b) } +write_test 1.7.3.3 t1_content { + INSERT INTO t1 VALUES( + 'transaction default models default', 'Non transaction reads'); +} +write_test 1.7.3.4 t1_content { + INSERT INTO t1 VALUES('the default transaction', 'these semantics present'); +} +write_test 1.7.3.5 t1_content { + INSERT INTO t1 VALUES('single request', 'default data'); +} +read_test 1.7.3.6 { + SELECT mit(matchinfo(t1)) FROM t1 + WHERE t1 MATCH 'default transaction "these semantics"'; +} {{3 2 1 3 2 0 1 1 1 2 2 0 1 1 0 0 0 1 1 1}} + +########################################################################## +# Test the example in section 5 (custom tokenizers). +# +ddl_test 1.8.1.1 { CREATE VIRTUAL TABLE simple USING fts3(tokenize=simple) } +write_test 1.8.1.2 simple_content { + INSERT INTO simple VALUES('Right now they''re very frustrated') +} +read_test 1.8.1.3 {SELECT docid FROM simple WHERE simple MATCH 'Frustrated'} {1} +read_test 1.8.1.4 {SELECT docid FROM simple WHERE simple MATCH 'Frustration'} {} + +ddl_test 1.8.2.1 { CREATE VIRTUAL TABLE porter USING fts3(tokenize=porter) } +write_test 1.8.2.2 porter_content { + INSERT INTO porter VALUES('Right now they''re very frustrated') +} +read_test 1.8.2.4 { + SELECT docid FROM porter WHERE porter MATCH 'Frustration' +} {1} + +} +# End of tests of example code in fts3.html +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Test that errors in the arguments passed to the snippet and offsets +# functions are handled correctly. +# +set DO_MALLOC_TEST 0 +ddl_test 2.1.0 { DROP TABLE IF EXISTS t1 } +ddl_test 2.1.1 { CREATE VIRTUAL TABLE t1 USING fts3(a, b) } +write_test 2.1.2 t1_content { + INSERT INTO t1 VALUES('one two three', x'A1B2C3D4E5F6'); +} +error_test 2.1.3 { + SELECT offsets(a) FROM t1 WHERE a MATCH 'one' +} {illegal first argument to offsets} +error_test 2.1.4 { + SELECT offsets(b) FROM t1 WHERE a MATCH 'one' +} {illegal first argument to offsets} +error_test 2.1.5 { + SELECT optimize(a) FROM t1 LIMIT 1 +} {illegal first argument to optimize} +error_test 2.1.6 { + SELECT snippet(a) FROM t1 WHERE a MATCH 'one' +} {illegal first argument to snippet} +error_test 2.1.7 { + SELECT snippet() FROM t1 WHERE a MATCH 'one' +} {unable to use function snippet in the requested context} +error_test 2.1.8 { + SELECT snippet(a, b, 'A', 'B', 'C', 'D', 'E') FROM t1 WHERE a MATCH 'one' +} {wrong number of arguments to function snippet()} +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Test the effect of an OOM error while installing the FTS3 module (i.e. +# opening a database handle). This case was not tested by the OOM testing +# of the document examples above. +# +do_malloc_test e_fts3-3 -tclbody { + if {[catch {sqlite3 db test.db}]} { error "out of memory" } +} +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Verify the return values of the optimize() function. If no error occurs, +# the returned value should be "Index optimized" if the data structure +# was modified, or "Index already optimal" if it were not. +# +set DO_MALLOC_TEST 0 +ddl_test 4.1 { CREATE VIRTUAL TABLE t4 USING fts3(a, b) } +write_test 4.2 t4_content { + INSERT INTO t4 VALUES('In Xanadu', 'did Kubla Khan'); +} +write_test 4.3 t4_content { + INSERT INTO t4 VALUES('a stately pleasure', 'dome decree'); +} +do_test e_fts3-4.4 { + execsql { SELECT optimize(t4) FROM t4 LIMIT 1 } +} {{Index optimized}} +do_test e_fts3-4.5 { + execsql { SELECT optimize(t4) FROM t4 LIMIT 1 } +} {{Index already optimal}} +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Test that the snippet function appears to work correctly with 1, 2, 3 +# or 4 arguments passed to it. +# +set DO_MALLOC_TEST 0 +ddl_test 5.1 { CREATE VIRTUAL TABLE t5 USING fts3(x) } +write_test 5.2 t5_content { + INSERT INTO t5 VALUES('In Xanadu did Kubla Khan A stately pleasure-dome decree Where Alph, the sacred river, ran Through caverns measureless to man Down to a sunless sea. So twice five miles of fertile ground With walls and towers were girdled round : And there were gardens bright with sinuous rills, Where blossomed many an incense-bearing tree ; And here were forests ancient as the hills, Enfolding sunny spots of greenery.'); +} +read_test 5.3 { + SELECT snippet(t5) FROM t5 WHERE t5 MATCH 'miles' +} {{...to a sunless sea. So twice five miles of fertile ground With walls and towers...}} +read_test 5.4 { + SELECT snippet(t5, '') FROM t5 WHERE t5 MATCH 'miles' +} {{...to a sunless sea. So twice five miles
    of fertile ground With walls and towers...}} +read_test 5.5 { + SELECT snippet(t5, '', '') FROM t5 WHERE t5 MATCH 'miles' +} {{...to a sunless sea. So twice five miles of fertile ground With walls and towers...}} +read_test 5.6 { + SELECT snippet(t5, '', '', 'XXX') FROM t5 WHERE t5 MATCH 'miles' +} {{XXXto a sunless sea. So twice five miles of fertile ground With walls and towersXXX}} +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Test that an empty MATCH expression returns an empty result set. As +# does passing a NULL value as a MATCH expression. +# +set DO_MALLOC_TEST 0 +ddl_test 6.1 { CREATE VIRTUAL TABLE t6 USING fts3(x) } +write_test 6.2 t5_content { INSERT INTO t6 VALUES('a'); } +write_test 6.3 t5_content { INSERT INTO t6 VALUES('b'); } +write_test 6.4 t5_content { INSERT INTO t6 VALUES('c'); } +read_test 6.5 { SELECT * FROM t6 WHERE t6 MATCH '' } {} +read_test 6.6 { SELECT * FROM t6 WHERE x MATCH '' } {} +read_test 6.7 { SELECT * FROM t6 WHERE t6 MATCH NULL } {} +read_test 6.8 { SELECT * FROM t6 WHERE x MATCH NULL } {} +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Test a few facets of the FTS3 xFilter() callback implementation: +# +# 1. That the sqlite3_index_constraint.usable flag is respected. +# +# 2. That it is an error to use the "docid" or "rowid" column of +# an FTS3 table as the LHS of a MATCH operator. +# +# 3. That it is an error to AND together two MATCH expressions in +# that refer to a single FTS3 table in a WHERE clause. +# +# +set DO_MALLOC_TEST 0 +ddl_test 7.1.1 { CREATE VIRTUAL TABLE t7 USING fts3(a) } +ddl_test 7.1.2 { CREATE VIRTUAL TABLE t8 USING fts3(b) } +write_test 7.1.3 t7_content { INSERT INTO t7(docid, a) VALUES(4,'number four') } +write_test 7.1.4 t7_content { INSERT INTO t7(docid, a) VALUES(5,'number five') } +write_test 7.1.5 t8_content { INSERT INTO t8(docid, b) VALUES(4,'letter D') } +write_test 7.1.6 t8_content { INSERT INTO t8(docid, b) VALUES(5,'letter E') } +read_test 7.1.7 { + SELECT a || ':' || b FROM t7 JOIN t8 USING(docid) +} {{number four:letter D} {number five:letter E}} + +error_test 7.2.1 { + SELECT * FROM t7 WHERE docid MATCH 'number' +} {unable to use function MATCH in the requested context} +error_test 7.2.2 { + SELECT * FROM t7 WHERE rowid MATCH 'number' +} {unable to use function MATCH in the requested context} + +error_test 7.3.1 { + SELECT * FROM t7 WHERE a MATCH 'number' AND a MATCH 'four' +} {unable to use function MATCH in the requested context} +error_test 7.3.2 { + SELECT * FROM t7, t8 WHERE a MATCH 'number' AND a MATCH 'four' +} {unable to use function MATCH in the requested context} +error_test 7.3.3 { + SELECT * FROM t7, t8 WHERE b MATCH 'letter' AND b MATCH 'd' +} {unable to use function MATCH in the requested context} +read_test 7.3.4 { + SELECT * FROM t7, t8 WHERE a MATCH 'number' AND b MATCH 'letter' +} {{number four} {letter D} {number four} {letter E} {number five} {letter D} {number five} {letter E}} +read_test 7.3.5 { + SELECT * FROM t7 WHERE a MATCH 'number' AND docid = 4 +} {{number four}} + +#------------------------------------------------------------------------- +# Test the quoting of FTS3 table column names. Names may be quoted using +# any of "", '', ``` or []. +# +set DO_MALLOC_TEST 0 +ddl_test 8.1.1 { CREATE VIRTUAL TABLE t9a USING fts3("c1", [c2]) } +ddl_test 8.1.2 { CREATE VIRTUAL TABLE t9b USING fts3('c1', `c2`) } +read_test 8.1.3 { PRAGMA table_info(t9a) } {0 c1 {} 0 {} 0 1 c2 {} 0 {} 0} +read_test 8.1.4 { PRAGMA table_info(t9b) } {0 c1 {} 0 {} 0 1 c2 {} 0 {} 0} +ddl_test 8.2.1 { CREATE VIRTUAL TABLE t9c USING fts3("c""1", 'c''2') } +read_test 8.2.2 { PRAGMA table_info(t9c) } {0 c\"1 {} 0 {} 0 1 c'2 {} 0 {} 0} +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Test that FTS3 tables can be renamed using the ALTER RENAME command. +# OOM errors are tested during ALTER RENAME commands also. +# +foreach DO_MALLOC_TEST {0 1 2} { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + if {$DO_MALLOC_TEST} { sqlite3_db_config_lookaside db 0 0 0 } + + ddl_test 9.1.1 { CREATE VIRTUAL TABLE t10 USING fts3(x) } + write_test 9.1.2 t10_content { INSERT INTO t10 VALUES('fts3 tables') } + write_test 9.1.3 t10_content { INSERT INTO t10 VALUES('are renameable') } + + read_test 9.1.4 { + SELECT * FROM t10 WHERE t10 MATCH 'table*' + } {{fts3 tables}} + read_test 9.1.5 { + SELECT * FROM t10 WHERE x MATCH 'rename*' + } {{are renameable}} + + ddl_test 9.1.6 { ALTER TABLE t10 RENAME TO t11 } + + read_test 9.1.7 { + SELECT * FROM t11 WHERE t11 MATCH 'table*' + } {{fts3 tables}} + read_test 9.1.8 { + SELECT * FROM t11 WHERE x MATCH 'rename*' + } {{are renameable}} +} +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Test a couple of cases involving corrupt data structures: +# +# 1) A case where a document referenced by the full-text index is +# not present in the %_content table. +# +# 2) A badly formatted b-tree segment node. +# +set DO_MALLOC_TEST 0 +ddl_test 10.1.1 { CREATE VIRTUAL TABLE ta USING fts3 } +write_test 10.1.2 ta_content { + INSERT INTO ta VALUES('During a summer vacation in 1790') } +write_test 10.1.3 ta_content { + INSERT INTO ta VALUES('Wordsworth went on a walking tour') } +write_test 10.1.4 ta_content { DELETE FROM ta_content WHERE rowid = 2 } +read_test 10.1.5 { + SELECT * FROM ta WHERE ta MATCH 'summer' +} {{During a summer vacation in 1790}} +error_test 10.1.6 { + SELECT * FROM ta WHERE ta MATCH 'walking' +} {database disk image is malformed} + +write_test 10.2.1 ta_content { DELETE FROM ta } +write_test 10.2.2 ta_content { + INSERT INTO ta VALUES('debate demonstrated the rising difficulty') } +write_test 10.2.3 ta_content { + INSERT INTO ta VALUES('Google released its browser beta') } + +set blob [db one {SELECT root FROM ta_segdir WHERE rowid = 2}] +binary scan $blob "a6 a3 a*" start middle end +set middle "\x0E\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x06\x06" +set blob [binary format "a6 a* a*" $start $middle $end] +write_test 10.2.4 ta_segdir { + UPDATE ta_segdir SET root = $blob WHERE rowid = 2 +} +error_test 10.2.5 { + SELECT * FROM ta WHERE ta MATCH 'beta' +} {database disk image is malformed} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_insert.test b/components/external/SQLite-3.8.1/test/e_insert.test new file mode 100644 index 0000000000000000000000000000000000000000..d95273e93b54c5e858914a1705e65937576d2005 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_insert.test @@ -0,0 +1,430 @@ +# 2010 September 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The majority of this file implements tests to verify that the "testable +# statements" in the lang_insert.html document are correct. +# +# Also, it contains tests to verify the statements in (the very short) +# lang_replace.html. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +# Organization of tests: +# +# e_insert-0.*: Test the syntax diagram. +# +# e_insert-1.*: Test statements of the form "INSERT ... VALUES(...)". +# +# e_insert-2.*: Test statements of the form "INSERT ... SELECT ...". +# +# e_insert-3.*: Test statements of the form "INSERT ... DEFAULT VALUES". +# +# e_insert-4.*: Test statements regarding the conflict clause. +# +# e_insert-5.*: Test that the qualified table name and "DEFAULT VALUES" +# syntaxes do not work in trigger bodies. +# + +do_execsql_test e_insert-0.0 { + CREATE TABLE a1(a, b); + CREATE TABLE a2(a, b, c DEFAULT 'xyz'); + CREATE TABLE a3(x DEFAULT 1.0, y DEFAULT 'string', z); + CREATE TABLE a4(c UNIQUE, d); +} {} + +proc do_insert_tests {args} { + uplevel do_select_tests $args +} + +# -- syntax diagram insert-stmt +# +do_insert_tests e_insert-0 { + 1 "INSERT INTO a1 DEFAULT VALUES" {} + 2 "INSERT INTO main.a1 DEFAULT VALUES" {} + 3 "INSERT OR ROLLBACK INTO main.a1 DEFAULT VALUES" {} + 4 "INSERT OR ROLLBACK INTO a1 DEFAULT VALUES" {} + 5 "INSERT OR ABORT INTO main.a1 DEFAULT VALUES" {} + 6 "INSERT OR ABORT INTO a1 DEFAULT VALUES" {} + 7 "INSERT OR REPLACE INTO main.a1 DEFAULT VALUES" {} + 8 "INSERT OR REPLACE INTO a1 DEFAULT VALUES" {} + 9 "INSERT OR FAIL INTO main.a1 DEFAULT VALUES" {} + 10 "INSERT OR FAIL INTO a1 DEFAULT VALUES" {} + 11 "INSERT OR FAIL INTO main.a1 DEFAULT VALUES" {} + 12 "INSERT OR IGNORE INTO a1 DEFAULT VALUES" {} + 13 "REPLACE INTO a1 DEFAULT VALUES" {} + 14 "REPLACE INTO main.a1 DEFAULT VALUES" {} + 15 "INSERT INTO a1 VALUES(1, 2)" {} + 16 "INSERT INTO main.a1 VALUES(1, 2)" {} + 17 "INSERT OR ROLLBACK INTO main.a1 VALUES(1, 2)" {} + 18 "INSERT OR ROLLBACK INTO a1 VALUES(1, 2)" {} + 19 "INSERT OR ABORT INTO main.a1 VALUES(1, 2)" {} + 20 "INSERT OR ABORT INTO a1 VALUES(1, 2)" {} + 21 "INSERT OR REPLACE INTO main.a1 VALUES(1, 2)" {} + 22 "INSERT OR REPLACE INTO a1 VALUES(1, 2)" {} + 23 "INSERT OR FAIL INTO main.a1 VALUES(1, 2)" {} + 24 "INSERT OR FAIL INTO a1 VALUES(1, 2)" {} + 25 "INSERT OR FAIL INTO main.a1 VALUES(1, 2)" {} + 26 "INSERT OR IGNORE INTO a1 VALUES(1, 2)" {} + 27 "REPLACE INTO a1 VALUES(1, 2)" {} + 28 "REPLACE INTO main.a1 VALUES(1, 2)" {} + 29 "INSERT INTO a1 (b, a) VALUES(1, 2)" {} + 30 "INSERT INTO main.a1 (b, a) VALUES(1, 2)" {} + 31 "INSERT OR ROLLBACK INTO main.a1 (b, a) VALUES(1, 2)" {} + 32 "INSERT OR ROLLBACK INTO a1 (b, a) VALUES(1, 2)" {} + 33 "INSERT OR ABORT INTO main.a1 (b, a) VALUES(1, 2)" {} + 34 "INSERT OR ABORT INTO a1 (b, a) VALUES(1, 2)" {} + 35 "INSERT OR REPLACE INTO main.a1 (b, a) VALUES(1, 2)" {} + 36 "INSERT OR REPLACE INTO a1 (b, a) VALUES(1, 2)" {} + 37 "INSERT OR FAIL INTO main.a1 (b, a) VALUES(1, 2)" {} + 38 "INSERT OR FAIL INTO a1 (b, a) VALUES(1, 2)" {} + 39 "INSERT OR FAIL INTO main.a1 (b, a) VALUES(1, 2)" {} + 40 "INSERT OR IGNORE INTO a1 (b, a) VALUES(1, 2)" {} + 41 "REPLACE INTO a1 (b, a) VALUES(1, 2)" {} + 42 "REPLACE INTO main.a1 (b, a) VALUES(1, 2)" {} + 43 "INSERT INTO a1 SELECT c, b FROM a2" {} + 44 "INSERT INTO main.a1 SELECT c, b FROM a2" {} + 45 "INSERT OR ROLLBACK INTO main.a1 SELECT c, b FROM a2" {} + 46 "INSERT OR ROLLBACK INTO a1 SELECT c, b FROM a2" {} + 47 "INSERT OR ABORT INTO main.a1 SELECT c, b FROM a2" {} + 48 "INSERT OR ABORT INTO a1 SELECT c, b FROM a2" {} + 49 "INSERT OR REPLACE INTO main.a1 SELECT c, b FROM a2" {} + 50 "INSERT OR REPLACE INTO a1 SELECT c, b FROM a2" {} + 51 "INSERT OR FAIL INTO main.a1 SELECT c, b FROM a2" {} + 52 "INSERT OR FAIL INTO a1 SELECT c, b FROM a2" {} + 53 "INSERT OR FAIL INTO main.a1 SELECT c, b FROM a2" {} + 54 "INSERT OR IGNORE INTO a1 SELECT c, b FROM a2" {} + 55 "REPLACE INTO a1 SELECT c, b FROM a2" {} + 56 "REPLACE INTO main.a1 SELECT c, b FROM a2" {} + 57 "INSERT INTO a1 (b, a) SELECT c, b FROM a2" {} + 58 "INSERT INTO main.a1 (b, a) SELECT c, b FROM a2" {} + 59 "INSERT OR ROLLBACK INTO main.a1 (b, a) SELECT c, b FROM a2" {} + 60 "INSERT OR ROLLBACK INTO a1 (b, a) SELECT c, b FROM a2" {} + 61 "INSERT OR ABORT INTO main.a1 (b, a) SELECT c, b FROM a2" {} + 62 "INSERT OR ABORT INTO a1 (b, a) SELECT c, b FROM a2" {} + 63 "INSERT OR REPLACE INTO main.a1 (b, a) SELECT c, b FROM a2" {} + 64 "INSERT OR REPLACE INTO a1 (b, a) SELECT c, b FROM a2" {} + 65 "INSERT OR FAIL INTO main.a1 (b, a) SELECT c, b FROM a2" {} + 66 "INSERT OR FAIL INTO a1 (b, a) SELECT c, b FROM a2" {} + 67 "INSERT OR FAIL INTO main.a1 (b, a) SELECT c, b FROM a2" {} + 68 "INSERT OR IGNORE INTO a1 (b, a) SELECT c, b FROM a2" {} + 69 "REPLACE INTO a1 (b, a) SELECT c, b FROM a2" {} + 70 "REPLACE INTO main.a1 (b, a) SELECT c, b FROM a2" {} + 71 "INSERT INTO a1 (b, a) VALUES(1, 2),(3,4)" {} + 72 "INSERT INTO main.a1 (b, a) VALUES(1, 2),(3,4)" {} + 73 "INSERT OR ROLLBACK INTO main.a1 (b, a) VALUES(1, 2),(3,4)" {} + 74 "INSERT OR ROLLBACK INTO a1 (b, a) VALUES(1, 2),(3,4)" {} + 75 "INSERT OR ABORT INTO main.a1 (b, a) VALUES(1, 2),(3,4)" {} + 76 "INSERT OR ABORT INTO a1 (b, a) VALUES(1, 2),(3,4)" {} + 77 "INSERT OR REPLACE INTO main.a1 (b, a) VALUES(1, 2),(3,4)" {} + 78 "INSERT OR REPLACE INTO a1 (b, a) VALUES(1, 2),(3,4)" {} + 79 "INSERT OR FAIL INTO main.a1 (b, a) VALUES(1, 2),(3,4)" {} + 80 "INSERT OR FAIL INTO a1 (b, a) VALUES(1, 2),(3,4)" {} + 81 "INSERT OR FAIL INTO main.a1 (b, a) VALUES(1, 2),(3,4)" {} + 82 "INSERT OR IGNORE INTO a1 (b, a) VALUES(1, 2),(3,4)" {} + 83 "REPLACE INTO a1 (b, a) VALUES(1, 2),(3,4)" {} + 84 "REPLACE INTO main.a1 (b, a) VALUES(1, 2),(3,4)" {} +} + +delete_all_data + +# EVIDENCE-OF: R-21490-41092 The first form (with the "VALUES" keyword) +# creates one or more new rows in an existing table. +# +do_insert_tests e_insert-1.1 { + 0 "SELECT count(*) FROM a2" {0} + + 1a "INSERT INTO a2 VALUES(1, 2, 3)" {} + 1b "SELECT count(*) FROM a2" {1} + + 2a "INSERT INTO a2(a, b) VALUES(1, 2)" {} + 2b "SELECT count(*) FROM a2" {2} + + 3a "INSERT INTO a2(a) VALUES(3),(4)" {} + 3b "SELECT count(*) FROM a2" {4} +} + +# EVIDENCE-OF: R-53616-44976 If no column-list is specified then the +# number of values inserted into each row must be the same as the number +# of columns in the table. +# +# A test in the block above verifies that if the VALUES list has the +# correct number of columns (for table a2, 3 columns) works. So these +# tests just show that other values cause an error. +# +do_insert_tests e_insert-1.2 -error { + table %s has %d columns but %d values were supplied +} { + 1 "INSERT INTO a2 VALUES(1)" {a2 3 1} + 2 "INSERT INTO a2 VALUES(1,2)" {a2 3 2} + 3 "INSERT INTO a2 VALUES(1,2,3,4)" {a2 3 4} + 4 "INSERT INTO a2 VALUES(1,2,3,4,5)" {a2 3 5} +} + +# EVIDENCE-OF: R-34231-22576 In this case the result of evaluating the +# left-most expression in each term of the VALUES list is inserted into +# the left-most column of the each new row, and forth for each +# subsequent expression. +# +delete_all_data +do_insert_tests e_insert-1.3 { + 1a "INSERT INTO a2 VALUES(1, 2, 3)" {} + 1b "SELECT * FROM a2 WHERE oid=last_insert_rowid()" {1 2 3} + + 2a "INSERT INTO a2 VALUES('abc', NULL, 3*3+1)" {} + 2b "SELECT * FROM a2 WHERE oid=last_insert_rowid()" {abc {} 10} + + 3a "INSERT INTO a2 VALUES((SELECT count(*) FROM a2), 'x', 'y')" {} + 3b "SELECT * FROM a2 WHERE oid=last_insert_rowid()" {2 x y} +} + +# EVIDENCE-OF: R-09234-17933 If a column-list is specified, then the +# number of values in each term of the VALUE list must match the number +# of specified columns. +# +do_insert_tests e_insert-1.4 -error { + %d values for %d columns +} { + 1 "INSERT INTO a2(a, b, c) VALUES(1)" {1 3} + 2 "INSERT INTO a2(a, b, c) VALUES(1,2)" {2 3} + 3 "INSERT INTO a2(a, b, c) VALUES(1,2,3,4)" {4 3} + 4 "INSERT INTO a2(a, b, c) VALUES(1,2,3,4,5)" {5 3} + + 5 "INSERT INTO a2(c, a) VALUES(1)" {1 2} + 6 "INSERT INTO a2(c, a) VALUES(1,2,3)" {3 2} + 7 "INSERT INTO a2(c, a) VALUES(1,2,3,4)" {4 2} + 8 "INSERT INTO a2(c, a) VALUES(1,2,3,4,5)" {5 2} +} + +# EVIDENCE-OF: R-07016-26442 Each of the named columns of the new row is +# populated with the results of evaluating the corresponding VALUES +# expression. +# +# EVIDENCE-OF: R-12183-43719 Table columns that do not appear in the +# column list are populated with the default column value (specified as +# part of the CREATE TABLE statement), or with NULL if no default value +# is specified. +# +delete_all_data +do_insert_tests e_insert-1.5 { + 1a "INSERT INTO a2(b, c) VALUES('b', 'c')" {} + 1b "SELECT * FROM a2" {{} b c} + + 2a "INSERT INTO a2(a, b) VALUES('a', 'b')" {} + 2b "SELECT * FROM a2" {{} b c a b xyz} +} + +# EVIDENCE-OF: R-52173-30215 A new entry is inserted into the table for +# each row of data returned by executing the SELECT statement. +# +delete_all_data +do_insert_tests e_insert-2.1 { + 0 "SELECT count(*) FROM a1" {0} + + 1a "SELECT count(*) FROM (SELECT 1, 2)" {1} + 1b "INSERT INTO a1 SELECT 1, 2" {} + 1c "SELECT count(*) FROM a1" {1} + + 2a "SELECT count(*) FROM (SELECT b, a FROM a1)" {1} + 2b "INSERT INTO a1 SELECT b, a FROM a1" {} + 2c "SELECT count(*) FROM a1" {2} + + 3a "SELECT count(*) FROM (SELECT b, a FROM a1)" {2} + 3b "INSERT INTO a1 SELECT b, a FROM a1" {} + 3c "SELECT count(*) FROM a1" {4} + + 4a "SELECT count(*) FROM (SELECT b, a FROM a1)" {4} + 4b "INSERT INTO a1 SELECT b, a FROM a1" {} + 4c "SELECT count(*) FROM a1" {8} + + 4a "SELECT count(*) FROM (SELECT min(b), min(a) FROM a1)" {1} + 4b "INSERT INTO a1 SELECT min(b), min(a) FROM a1" {} + 4c "SELECT count(*) FROM a1" {9} +} + + +# EVIDENCE-OF: R-63614-47421 If a column-list is specified, the number +# of columns in the result of the SELECT must be the same as the number +# of items in the column-list. +# +do_insert_tests e_insert-2.2 -error { + %d values for %d columns +} { + 1 "INSERT INTO a3(x, y) SELECT a, b, c FROM a2" {3 2} + 2 "INSERT INTO a3(x, y) SELECT * FROM a2" {3 2} + 3 "INSERT INTO a3(x, y) SELECT * FROM a2 CROSS JOIN a1" {5 2} + 4 "INSERT INTO a3(x, y) SELECT * FROM a2 NATURAL JOIN a1" {3 2} + 5 "INSERT INTO a3(x, y) SELECT a2.a FROM a2,a1" {1 2} + + 6 "INSERT INTO a3(z) SELECT a, b, c FROM a2" {3 1} + 7 "INSERT INTO a3(z) SELECT * FROM a2" {3 1} + 8 "INSERT INTO a3(z) SELECT * FROM a2 CROSS JOIN a1" {5 1} + 9 "INSERT INTO a3(z) SELECT * FROM a2 NATURAL JOIN a1" {3 1} + 10 "INSERT INTO a3(z) SELECT a1.* FROM a2,a1" {2 1} +} + +# EVIDENCE-OF: R-58951-07798 Otherwise, if no column-list is specified, +# the number of columns in the result of the SELECT must be the same as +# the number of columns in the table. +# +do_insert_tests e_insert-2.3 -error { + table %s has %d columns but %d values were supplied +} { + 1 "INSERT INTO a1 SELECT a, b, c FROM a2" {a1 2 3} + 2 "INSERT INTO a1 SELECT * FROM a2" {a1 2 3} + 3 "INSERT INTO a1 SELECT * FROM a2 CROSS JOIN a1" {a1 2 5} + 4 "INSERT INTO a1 SELECT * FROM a2 NATURAL JOIN a1" {a1 2 3} + 5 "INSERT INTO a1 SELECT a2.a FROM a2,a1" {a1 2 1} +} + +# EVIDENCE-OF: R-31074-37730 Any SELECT statement, including compound +# SELECTs and SELECT statements with ORDER BY and/or LIMIT clauses, may +# be used in an INSERT statement of this form. +# +delete_all_data +do_execsql_test e_insert-2.3.0 { + INSERT INTO a1 VALUES('x', 'y'); +} {} +do_insert_tests e_insert-2.3 { + 1 "INSERT INTO a1 SELECT a,b FROM a1 UNION SELECT b,a FROM a1 ORDER BY 1" {} + 2 "INSERT INTO a1(b, a) SELECT * FROM a1 LIMIT 1" {} + 3 "INSERT INTO a1 SELECT 'a'||a, 'b'||b FROM a1 LIMIT 2 OFFSET 1" {} + 4 "INSERT INTO a1 SELECT * FROM a1 ORDER BY b, a" {} + S "SELECT * FROM a1" { + x y + x y y x + y x + ax by ay bx + ay bx ax by y x y x x y x y + } +} + +# EVIDENCE-OF: R-25149-22012 The INSERT ... DEFAULT VALUES statement +# inserts a single new row into the named table. +# +delete_all_data +do_insert_tests e_insert-3.1 { + 1 "SELECT count(*) FROM a3" {0} + 2a "INSERT INTO a3 DEFAULT VALUES" {} + 2b "SELECT count(*) FROM a3" {1} +} + +# EVIDENCE-OF: R-18927-01951 Each column of the new row is populated +# with its default value, or with a NULL if no default value is +# specified as part of the column definition in the CREATE TABLE +# statement. +# +delete_all_data +do_insert_tests e_insert-3.2 { + 1.1 "INSERT INTO a3 DEFAULT VALUES" {} + 1.2 "SELECT * FROM a3" {1.0 string {}} + + 2.1 "INSERT INTO a3 DEFAULT VALUES" {} + 2.2 "SELECT * FROM a3" {1.0 string {} 1.0 string {}} + + 3.1 "INSERT INTO a2 DEFAULT VALUES" {} + 3.2 "SELECT * FROM a2" {{} {} xyz} + + 4.1 "INSERT INTO a2 DEFAULT VALUES" {} + 4.2 "SELECT * FROM a2" {{} {} xyz {} {} xyz} + + 5.1 "INSERT INTO a1 DEFAULT VALUES" {} + 5.2 "SELECT * FROM a1" {{} {}} + + 6.1 "INSERT INTO a1 DEFAULT VALUES" {} + 6.2 "SELECT * FROM a1" {{} {} {} {}} +} + +# EVIDENCE-OF: R-46928-50290 The optional conflict-clause allows the +# specification of an alternative constraint conflict resolution +# algorithm to use during this one INSERT command. +# +# EVIDENCE-OF: R-23110-47146 the parser allows the use of the single +# keyword REPLACE as an alias for "INSERT OR REPLACE". +# +# The two requirements above are tested by e_select-4.1.* and +# e_select-4.2.*, respectively. +# +# EVIDENCE-OF: R-03421-22330 The REPLACE command is an alias for the +# "INSERT OR REPLACE" variant of the INSERT command. +# +# This is a dup of R-23110-47146. Therefore it is also verified +# by e_select-4.2.*. This requirement is the only one from +# lang_replace.html. +# +do_execsql_test e_insert-4.1.0 { + INSERT INTO a4 VALUES(1, 'a'); + INSERT INTO a4 VALUES(2, 'a'); + INSERT INTO a4 VALUES(3, 'a'); +} {} +foreach {tn sql error ac data } { + 1.1 "INSERT INTO a4 VALUES(2,'b')" {column c is not unique} 1 {1 a 2 a 3 a} + 1.2 "INSERT OR REPLACE INTO a4 VALUES(2, 'b')" {} 1 {1 a 3 a 2 b} + 1.3 "INSERT OR IGNORE INTO a4 VALUES(3, 'c')" {} 1 {1 a 3 a 2 b} + 1.4 "BEGIN" {} 0 {1 a 3 a 2 b} + 1.5 "INSERT INTO a4 VALUES(1, 'd')" {column c is not unique} 0 {1 a 3 a 2 b} + 1.6 "INSERT OR ABORT INTO a4 VALUES(1, 'd')" + {column c is not unique} 0 {1 a 3 a 2 b} + 1.7 "INSERT OR ROLLBACK INTO a4 VALUES(1, 'd')" + {column c is not unique} 1 {1 a 3 a 2 b} + 1.8 "INSERT INTO a4 SELECT 4, 'e' UNION ALL SELECT 3, 'e'" + {column c is not unique} 1 {1 a 3 a 2 b} + 1.9 "INSERT OR FAIL INTO a4 SELECT 4, 'e' UNION ALL SELECT 3, 'e'" + {column c is not unique} 1 {1 a 3 a 2 b 4 e} + + 2.1 "INSERT INTO a4 VALUES(2,'f')" + {column c is not unique} 1 {1 a 3 a 2 b 4 e} + 2.2 "REPLACE INTO a4 VALUES(2, 'f')" {} 1 {1 a 3 a 4 e 2 f} +} { + do_catchsql_test e_insert-4.1.$tn.1 $sql [list [expr {$error!=""}] $error] + do_execsql_test e_insert-4.1.$tn.2 {SELECT * FROM a4} [list {*}$data] + do_test e_insert-4.1.$tn.3 {sqlite3_get_autocommit db} $ac +} + +# EVIDENCE-OF: R-64196-02418 The optional "database-name." prefix on the +# table-name is support for top-level INSERT statements only. +# +# EVIDENCE-OF: R-05731-00924 The table name must be unqualified for +# INSERT statements that occur within CREATE TRIGGER statements. +# +set err {1 {qualified table names are not allowed on INSERT, UPDATE, and DELETE statements within triggers}} + +do_catchsql_test e_insert-5.1.1 { + CREATE TRIGGER AFTER UPDATE ON a1 BEGIN + INSERT INTO main.a4 VALUES(new.a, new.b); + END; +} $err +do_catchsql_test e_insert-5.1.2 { + CREATE TEMP TABLE IF NOT EXISTS tmptable(a, b); + CREATE TRIGGER AFTER DELETE ON a3 BEGIN + INSERT INTO temp.tmptable VALUES(1, 2); + END; +} $err + +# EVIDENCE-OF: R-15888-36326 Similarly, the "DEFAULT VALUES" form of the +# INSERT statement is supported for top-level INSERT statements only and +# not for INSERT statements within triggers. +# +do_catchsql_test e_insert-5.2.1 { + CREATE TRIGGER AFTER UPDATE ON a1 BEGIN + INSERT INTO a4 DEFAULT VALUES; + END; +} {1 {near "DEFAULT": syntax error}} + + +delete_all_data + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_reindex.test b/components/external/SQLite-3.8.1/test/e_reindex.test new file mode 100644 index 0000000000000000000000000000000000000000..c1eae0646cfc28ef939db0321461e140f8133751 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_reindex.test @@ -0,0 +1,294 @@ +# 2010 September 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_reindex.html document are correct. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc do_reindex_tests {args} { + uplevel do_select_tests $args +} + +do_execsql_test e_reindex-0.0 { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + CREATE INDEX i2 ON t1(b, a); +} {} + +# -- syntax diagram reindex-stmt +# +do_reindex_tests e_reindex-0.1 { + 1 "REINDEX" {} + 2 "REINDEX nocase" {} + 3 "REINDEX binary" {} + 4 "REINDEX t1" {} + 5 "REINDEX main.t1" {} + 6 "REINDEX i1" {} + 7 "REINDEX main.i1" {} +} + +# EVIDENCE-OF: R-52173-44778 The REINDEX command is used to delete and +# recreate indices from scratch. +# +# Test this by corrupting some database indexes, running REINDEX, and +# observing that the corruption is gone. +# +do_execsql_test e_reindex-1.1 { + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t1 VALUES(5, 6); + PRAGMA writable_schema = 1; + UPDATE sqlite_master SET sql = '-- ' || sql WHERE type = 'index'; +} {} + +db close +sqlite3 db test.db +do_execsql_test e_reindex-1.2 { + DELETE FROM t1 WHERE a = 3; + INSERT INTO t1 VALUES(7, 8); + INSERT INTO t1 VALUES(9, 10); + PRAGMA writable_schema = 1; + UPDATE sqlite_master SET sql = substr(sql, 4) WHERE type = 'index'; +} {} + +db close +sqlite3 db test.db +do_execsql_test e_reindex-1.3 { + PRAGMA integrity_check; +} [list \ + {rowid 4 missing from index i2} \ + {rowid 4 missing from index i1} \ + {rowid 5 missing from index i2} \ + {rowid 5 missing from index i1} \ + {wrong # of entries in index i2} \ + {wrong # of entries in index i1} +] + +do_execsql_test e_reindex-1.4 { + REINDEX; + PRAGMA integrity_check; +} {ok} + +#------------------------------------------------------------------------- +# The remaining tests in this file focus on testing that the REINDEX +# command reindexes the correct subset of the indexes in the database. +# They all use the following dataset. +# +db close +forcedelete test.db2 +forcedelete test.db +sqlite3 db test.db + +proc sort_by_length {lhs rhs} { + set res [expr {[string length $lhs] - [string length $rhs]}] + if {$res!=0} {return $res} + return [string compare $lhs $rhs] +} +array set V {one 1 two 2 three 3 four 4 five 5 six 6 seven 7 eight 8} +proc sort_by_value {lhs rhs} { + global V + set res [expr {$V($lhs) - $V($rhs)}] + if {$res!=0} {return $res} + return [string compare $lhs $rhs] +} + +db collate collA sort_by_length +db collate collB sort_by_value + +set BY(length) {one six two five four eight seven three} +set BY(value) {one two three four five six seven eight} + +do_execsql_test e_reindex-2.0 { + ATTACH 'test.db2' AS aux; + + CREATE TABLE t1(x); + CREATE INDEX i1_a ON t1(x COLLATE collA); + CREATE INDEX i1_b ON t1(x COLLATE collB); + INSERT INTO t1 VALUES('one'); + INSERT INTO t1 VALUES('two'); + INSERT INTO t1 VALUES('three'); + INSERT INTO t1 VALUES('four'); + INSERT INTO t1 VALUES('five'); + INSERT INTO t1 VALUES('six'); + INSERT INTO t1 VALUES('seven'); + INSERT INTO t1 VALUES('eight'); + + CREATE TABLE t2(x); + CREATE INDEX i2_a ON t2(x COLLATE collA); + CREATE INDEX i2_b ON t2(x COLLATE collB); + INSERT INTO t2 SELECT x FROM t1; + + CREATE TABLE aux.t1(x); + CREATE INDEX aux.i1_a ON t1(x COLLATE collA); + CREATE INDEX aux.i1_b ON t1(x COLLATE collB); + INSERT INTO aux.t1 SELECT x FROM main.t1; + +} {} + +proc test_index {tn tbl collation expected} { + set sql "SELECT x FROM $tbl ORDER BY x COLLATE $collation" + uplevel do_execsql_test e_reindex-2.$tn [list $sql] [list $::BY($expected)] +} + +proc set_collations {a b} { + db collate collA "sort_by_$a" + db collate collB "sort_by_$b" +} + +test_index 1.1 t1 collA length +test_index 1.2 t1 collB value +test_index 1.3 t2 collA length +test_index 1.4 t2 collB value +test_index 1.5 aux.t1 collA length +test_index 1.6 aux.t1 collB value + + +# EVIDENCE-OF: R-47362-07898 If the REINDEX keyword is not followed by a +# collation-sequence or database object identifier, then all indices in +# all attached databases are rebuilt. +# +set_collations value length +do_execsql_test e_reindex-2.2.1 "REINDEX" {} +test_index 2.2 t1 collA value +test_index 2.3 t1 collB length +test_index 2.4 t2 collA value +test_index 2.5 t2 collB length +test_index 2.6 aux.t1 collA value +test_index 2.7 aux.t1 collB length + +# EVIDENCE-OF: R-45878-07697 If the REINDEX keyword is followed by a +# collation-sequence name, then all indices in all attached databases +# that use the named collation sequences are recreated. +# +set_collations length value +do_execsql_test e_reindex-2.3.1 "REINDEX collA" {} +test_index 3.2 t1 collA length +test_index 3.3 t1 collB length +test_index 3.4 t2 collA length +test_index 3.5 t2 collB length +test_index 3.6 aux.t1 collA length +test_index 3.7 aux.t1 collB length +do_execsql_test e_reindex-2.3.8 "REINDEX collB" {} +test_index 3.9 t1 collA length +test_index 3.10 t1 collB value +test_index 3.11 t2 collA length +test_index 3.12 t2 collB value +test_index 3.13 aux.t1 collA length +test_index 3.14 aux.t1 collB value + +# EVIDENCE-OF: R-49616-30196 Or, if the argument attached to the REINDEX +# identifies a specific database table, then all indices attached to the +# database table are rebuilt. +# +set_collations value length +do_execsql_test e_reindex-2.4.1 "REINDEX t1" {} +test_index 4.2 t1 collA value +test_index 4.3 t1 collB length +test_index 4.4 t2 collA length +test_index 4.5 t2 collB value +test_index 4.6 aux.t1 collA length +test_index 4.7 aux.t1 collB value +do_execsql_test e_reindex-2.4.8 "REINDEX aux.t1" {} +test_index 4.9 t1 collA value +test_index 4.10 t1 collB length +test_index 4.11 t2 collA length +test_index 4.12 t2 collB value +test_index 4.13 aux.t1 collA value +test_index 4.14 aux.t1 collB length +do_execsql_test e_reindex-2.4.15 "REINDEX t2" {} +test_index 4.16 t1 collA value +test_index 4.17 t1 collB length +test_index 4.18 t2 collA value +test_index 4.19 t2 collB length +test_index 4.20 aux.t1 collA value +test_index 4.21 aux.t1 collB length + +# EVIDENCE-OF: R-58823-28748 If it identifies a specific database index, +# then just that index is recreated. +# +set_collations length value +do_execsql_test e_reindex-2.5.1 "REINDEX i1_a" {} +test_index 5.2 t1 collA length +test_index 5.3 t1 collB length +test_index 5.4 t2 collA value +test_index 5.5 t2 collB length +test_index 5.6 aux.t1 collA value +test_index 5.7 aux.t1 collB length +do_execsql_test e_reindex-2.5.8 "REINDEX i2_b" {} +test_index 5.9 t1 collA length +test_index 5.10 t1 collB length +test_index 5.11 t2 collA value +test_index 5.12 t2 collB value +test_index 5.13 aux.t1 collA value +test_index 5.14 aux.t1 collB length +do_execsql_test e_reindex-2.5.15 "REINDEX aux.i1_b" {} +test_index 5.16 t1 collA length +test_index 5.17 t1 collB length +test_index 5.18 t2 collA value +test_index 5.19 t2 collB value +test_index 5.20 aux.t1 collA value +test_index 5.21 aux.t1 collB value +do_execsql_test e_reindex-2.5.22 "REINDEX i1_b" {} +test_index 5.23 t1 collA length +test_index 5.24 t1 collB value +test_index 5.25 t2 collA value +test_index 5.26 t2 collB value +test_index 5.27 aux.t1 collA value +test_index 5.28 aux.t1 collB value +do_execsql_test e_reindex-2.5.29 "REINDEX i2_a" {} +test_index 5.30 t1 collA length +test_index 5.31 t1 collB value +test_index 5.32 t2 collA length +test_index 5.33 t2 collB value +test_index 5.34 aux.t1 collA value +test_index 5.35 aux.t1 collB value +do_execsql_test e_reindex-2.5.36 "REINDEX aux.i1_a" {} +test_index 5.37 t1 collA length +test_index 5.38 t1 collB value +test_index 5.39 t2 collA length +test_index 5.40 t2 collB value +test_index 5.41 aux.t1 collA length +test_index 5.42 aux.t1 collB value + +# EVIDENCE-OF: R-15639-02023 If no database-name is specified and there +# exists both a table or index and a collation sequence of the specified +# name, SQLite interprets this as a request to rebuild the indices that +# use the named collation sequence. +# +set_collations value length +do_execsql_test e_reindex-2.6.0 { + CREATE TABLE collA(x); + CREATE INDEX icolla_a ON collA(x COLLATE collA); + CREATE INDEX icolla_b ON collA(x COLLATE collB); + + INSERT INTO collA SELECT x FROM t1; +} {} + +test_index 6.1 collA collA value +test_index 6.2 collA collB length + +set_collations length value +do_execsql_test e_reindex-2.6.3 "REINDEX collA" {} +test_index 6.4 collA collA length +test_index 6.5 collA collB length +do_execsql_test e_reindex-2.6.3 "REINDEX main.collA" {} +test_index 6.4 collA collA length +test_index 6.5 collA collB value + +set_collations value length +do_execsql_test e_reindex-2.6.6 "REINDEX main.collA" {} +test_index 6.7 collA collA value +test_index 6.8 collA collB length + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_resolve.test b/components/external/SQLite-3.8.1/test/e_resolve.test new file mode 100644 index 0000000000000000000000000000000000000000..512fcf2748e01da18443ae06dc0f1b86c94cb104 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_resolve.test @@ -0,0 +1,135 @@ +# 2010 November 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_naming.html document are correct. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix e_resolve + +# An example database schema for testing name resolution: +# +set schema { + ATTACH 'test.db2' AS at1; + ATTACH 'test.db3' AS at2; + + CREATE TABLE temp.n1(x, y); INSERT INTO temp.n1 VALUES('temp', 'n1'); + CREATE TRIGGER temp.n3 AFTER INSERT ON n1 BEGIN SELECT 1; END; + CREATE INDEX temp.n4 ON n1(x, y); + + CREATE TABLE main.n1(x, y); INSERT INTO main.n1 VALUES('main', 'n1'); + CREATE TABLE main.n2(x, y); INSERT INTO main.n2 VALUES('main', 'n2'); + CREATE INDEX main.n3 ON n2(y, x); + CREATE TRIGGER main.n4 BEFORE INSERT ON n2 BEGIN SELECT 1; END; + + CREATE TABLE at1.n1(x, y); INSERT INTO at1.n1 VALUES('at1', 'n1'); + CREATE TABLE at1.n2(x, y); INSERT INTO at1.n2 VALUES('at1', 'n2'); + CREATE TABLE at1.n3(x, y); INSERT INTO at1.n3 VALUES('at1', 'n3'); + + CREATE TABLE at2.n1(x, y); INSERT INTO at2.n1 VALUES('at2', 'n1'); + CREATE TABLE at2.n2(x, y); INSERT INTO at2.n2 VALUES('at2', 'n2'); + CREATE TABLE at2.n3(x, y); INSERT INTO at2.n3 VALUES('at2', 'n3'); + CREATE TABLE at2.n4(x, y); INSERT INTO at2.n4 VALUES('at2', 'n4'); + CREATE TRIGGER at2.n4 BEFORE INSERT ON n4 BEGIN SELECT 1; END; +} + +proc resolve_reopen_db {} { + db close + forcedelete test.db test.db2 test.db3 + sqlite3 db test.db + db eval $::schema +} + + + +# EVIDENCE-OF: R-33528-20612 If no database is specified as part of the +# object reference, then SQLite searches the main, temp and all attached +# databases for an object with a matching name. The temp database is +# searched first, followed by the main database, followed all attached +# databases in the order that they were attached. The reference resolves +# to the first match found. +# +resolve_reopen_db +do_execsql_test 1.1 { SELECT * FROM n1 } {temp n1} +do_execsql_test 1.2 { SELECT * FROM n2 } {main n2} +do_execsql_test 1.3 { SELECT * FROM n3 } {at1 n3} +do_execsql_test 1.4 { SELECT * FROM n4 } {at2 n4} + +# EVIDENCE-OF: R-54577-28142 If a database name is specified as part of +# an object reference, it must be either "main", or "temp" or the name +# of an attached database. +# +# Or else it is a "no such table: xxx" error. +# +resolve_reopen_db +do_execsql_test 2.1.1 { SELECT * FROM main.n1 } {main n1} +do_execsql_test 2.1.2 { SELECT * FROM temp.n1 } {temp n1} +do_execsql_test 2.1.3 { SELECT * FROM at1.n1 } {at1 n1} +do_execsql_test 2.1.4 { SELECT * FROM at2.n1 } {at2 n1} + +do_catchsql_test 2.2 { SELECT * FROM xxx.n1 } {1 {no such table: xxx.n1}} + +# EVIDENCE-OF: R-26223-47623 Like other SQL identifiers, database names +# are case-insensitive. +# +resolve_reopen_db +do_execsql_test 3.1 { SELECT * FROM MAIN.n1 } {main n1} +do_execsql_test 3.2 { SELECT * FROM tEmP.n1 } {temp n1} +do_execsql_test 3.3 { SELECT * FROM aT1.n1 } {at1 n1} +do_execsql_test 3.4 { SELECT * FROM At2.n1 } {at2 n1} + +# EVIDENCE-OF: R-15639-28392 If a database name is specified, then only +# the named database is searched for the named object. +# +do_catchsql_test 4.1 { SELECT * FROM temp.n2 } {1 {no such table: temp.n2}} +do_catchsql_test 4.2 { SELECT * FROM main.n2 } {0 {main n2}} +do_catchsql_test 4.3 { SELECT * FROM at1.n2 } {0 {at1 n2}} +do_catchsql_test 4.4 { SELECT * FROM at2.n2 } {0 {at2 n2}} + +# EVIDENCE-OF: R-08951-19801 When searching database schemas for a named +# object, objects of types that cannot be used in the context of the +# reference are always ignored. +# +# In this case, "types that cannot be used" are triggers and indexes. +# The temp and main databases both contain triggers and indexes named +# "n3" and "n4". Database "at2" contains a trigger called "n4". And yet: +# +do_execsql_test 5.1 { SELECT * FROM n3 } {at1 n3} +do_execsql_test 5.2 { SELECT * FROM n4 } {at2 n4} + +#------------------------------------------------------------------------- +# EVIDENCE-OF: R-37286-42536 +# +db close +forcedelete test.db file.db +sqlite3 db test.db +do_execsql_test 6.1 { + ATTACH 'file.db' AS aux; + CREATE TABLE t1(x, y); + CREATE TEMP TABLE t1(x, y); + CREATE TABLE aux.t1(x, y); +} + +do_execsql_test 6.2.0 { DROP TABLE t1 } +do_catchsql_test 6.2.1 { SELECT * FROM temp.t1 } {1 {no such table: temp.t1}} +do_catchsql_test 6.2.2 { SELECT * FROM main.t1 } {0 {}} +do_catchsql_test 6.2.3 { SELECT * FROM aux.t1 } {0 {}} + +do_execsql_test 6.3.0 { DROP TABLE t1 } +do_catchsql_test 6.3.1 { SELECT * FROM main.t1 } {1 {no such table: main.t1}} +do_catchsql_test 6.3.3 { SELECT * FROM aux.t1 } {0 {}} + +do_execsql_test 6.4.0 { DROP TABLE t1 } +do_catchsql_test 6.4.1 { SELECT * FROM aux.t1 } {1 {no such table: aux.t1}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_select.test b/components/external/SQLite-3.8.1/test/e_select.test new file mode 100644 index 0000000000000000000000000000000000000000..61646a2a3131fad33547cc0e5b47a2fe3b8656fb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_select.test @@ -0,0 +1,2167 @@ +# 2010 July 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_select.html document are correct. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_execsql_test e_select-1.0 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('a', 'one'); + INSERT INTO t1 VALUES('b', 'two'); + INSERT INTO t1 VALUES('c', 'three'); + + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES('a', 'I'); + INSERT INTO t2 VALUES('b', 'II'); + INSERT INTO t2 VALUES('c', 'III'); + + CREATE TABLE t3(a, c); + INSERT INTO t3 VALUES('a', 1); + INSERT INTO t3 VALUES('b', 2); + + CREATE TABLE t4(a, c); + INSERT INTO t4 VALUES('a', NULL); + INSERT INTO t4 VALUES('b', 2); +} {} +set t1_cross_t2 [list \ + a one a I a one b II \ + a one c III b two a I \ + b two b II b two c III \ + c three a I c three b II \ + c three c III \ +] +set t1_cross_t1 [list \ + a one a one a one b two \ + a one c three b two a one \ + b two b two b two c three \ + c three a one c three b two \ + c three c three \ +] + + +# This proc is a specialized version of [do_execsql_test]. +# +# The second argument to this proc must be a SELECT statement that +# features a cross join of some time. Instead of the usual ",", +# "CROSS JOIN" or "INNER JOIN" join-op, the string %JOIN% must be +# substituted. +# +# This test runs the SELECT three times - once with: +# +# * s/%JOIN%/,/ +# * s/%JOIN%/JOIN/ +# * s/%JOIN%/INNER JOIN/ +# * s/%JOIN%/CROSS JOIN/ +# +# and checks that each time the results of the SELECT are $res. +# +proc do_join_test {tn select res} { + foreach {tn2 joinop} [list 1 , 2 "CROSS JOIN" 3 "INNER JOIN"] { + set S [string map [list %JOIN% $joinop] $select] + uplevel do_execsql_test $tn.$tn2 [list $S] [list $res] + } +} + +#------------------------------------------------------------------------- +# The following tests check that all paths on the syntax diagrams on +# the lang_select.html page may be taken. +# +# -- syntax diagram join-constraint +# +do_join_test e_select-0.1.1 { + SELECT count(*) FROM t1 %JOIN% t2 ON (t1.a=t2.a) +} {3} +do_join_test e_select-0.1.2 { + SELECT count(*) FROM t1 %JOIN% t2 USING (a) +} {3} +do_join_test e_select-0.1.3 { + SELECT count(*) FROM t1 %JOIN% t2 +} {9} +do_catchsql_test e_select-0.1.4 { + SELECT count(*) FROM t1, t2 ON (t1.a=t2.a) USING (a) +} {1 {cannot have both ON and USING clauses in the same join}} +do_catchsql_test e_select-0.1.5 { + SELECT count(*) FROM t1, t2 USING (a) ON (t1.a=t2.a) +} {1 {near "ON": syntax error}} + +# -- syntax diagram select-core +# +# 0: SELECT ... +# 1: SELECT DISTINCT ... +# 2: SELECT ALL ... +# +# 0: No FROM clause +# 1: Has FROM clause +# +# 0: No WHERE clause +# 1: Has WHERE clause +# +# 0: No GROUP BY clause +# 1: Has GROUP BY clause +# 2: Has GROUP BY and HAVING clauses +# +do_select_tests e_select-0.2 { + 0000.1 "SELECT 1, 2, 3 " {1 2 3} + 1000.1 "SELECT DISTINCT 1, 2, 3 " {1 2 3} + 2000.1 "SELECT ALL 1, 2, 3 " {1 2 3} + + 0100.1 "SELECT a, b, a||b FROM t1 " { + a one aone b two btwo c three cthree + } + 1100.1 "SELECT DISTINCT a, b, a||b FROM t1 " { + a one aone b two btwo c three cthree + } + 1200.1 "SELECT ALL a, b, a||b FROM t1 " { + a one aone b two btwo c three cthree + } + + 0010.1 "SELECT 1, 2, 3 WHERE 1 " {1 2 3} + 0010.2 "SELECT 1, 2, 3 WHERE 0 " {} + 0010.3 "SELECT 1, 2, 3 WHERE NULL " {} + + 1010.1 "SELECT DISTINCT 1, 2, 3 WHERE 1 " {1 2 3} + + 2010.1 "SELECT ALL 1, 2, 3 WHERE 1 " {1 2 3} + + 0110.1 "SELECT a, b, a||b FROM t1 WHERE a!='x' " { + a one aone b two btwo c three cthree + } + 0110.2 "SELECT a, b, a||b FROM t1 WHERE a=='x'" {} + + 1110.1 "SELECT DISTINCT a, b, a||b FROM t1 WHERE a!='x' " { + a one aone b two btwo c three cthree + } + + 2110.0 "SELECT ALL a, b, a||b FROM t1 WHERE a=='x'" {} + + 0001.1 "SELECT 1, 2, 3 GROUP BY 2" {1 2 3} + 0002.1 "SELECT 1, 2, 3 GROUP BY 2 HAVING count(*)=1" {1 2 3} + 0002.2 "SELECT 1, 2, 3 GROUP BY 2 HAVING count(*)>1" {} + + 1001.1 "SELECT DISTINCT 1, 2, 3 GROUP BY 2" {1 2 3} + 1002.1 "SELECT DISTINCT 1, 2, 3 GROUP BY 2 HAVING count(*)=1" {1 2 3} + 1002.2 "SELECT DISTINCT 1, 2, 3 GROUP BY 2 HAVING count(*)>1" {} + + 2001.1 "SELECT ALL 1, 2, 3 GROUP BY 2" {1 2 3} + 2002.1 "SELECT ALL 1, 2, 3 GROUP BY 2 HAVING count(*)=1" {1 2 3} + 2002.2 "SELECT ALL 1, 2, 3 GROUP BY 2 HAVING count(*)>1" {} + + 0101.1 "SELECT count(*), max(a) FROM t1 GROUP BY b" {1 a 1 c 1 b} + 0102.1 "SELECT count(*), max(a) FROM t1 GROUP BY b HAVING count(*)=1" { + 1 a 1 c 1 b + } + 0102.2 "SELECT count(*), max(a) FROM t1 GROUP BY b HAVING count(*)=2" { } + + 1101.1 "SELECT DISTINCT count(*), max(a) FROM t1 GROUP BY b" {1 a 1 c 1 b} + 1102.1 "SELECT DISTINCT count(*), max(a) FROM t1 + GROUP BY b HAVING count(*)=1" { + 1 a 1 c 1 b + } + 1102.2 "SELECT DISTINCT count(*), max(a) FROM t1 + GROUP BY b HAVING count(*)=2" { + } + + 2101.1 "SELECT ALL count(*), max(a) FROM t1 GROUP BY b" {1 a 1 c 1 b} + 2102.1 "SELECT ALL count(*), max(a) FROM t1 + GROUP BY b HAVING count(*)=1" { + 1 a 1 c 1 b + } + 2102.2 "SELECT ALL count(*), max(a) FROM t1 + GROUP BY b HAVING count(*)=2" { + } + + 0011.1 "SELECT 1, 2, 3 WHERE 1 GROUP BY 2" {1 2 3} + 0012.1 "SELECT 1, 2, 3 WHERE 0 GROUP BY 2 HAVING count(*)=1" {} + 0012.2 "SELECT 1, 2, 3 WHERE 0 GROUP BY 2 HAVING count(*)>1" {} + + 1011.1 "SELECT DISTINCT 1, 2, 3 WHERE 0 GROUP BY 2" {} + 1012.1 "SELECT DISTINCT 1, 2, 3 WHERE 1 GROUP BY 2 HAVING count(*)=1" + {1 2 3} + 1012.2 "SELECT DISTINCT 1, 2, 3 WHERE NULL GROUP BY 2 HAVING count(*)>1" {} + + 2011.1 "SELECT ALL 1, 2, 3 WHERE 1 GROUP BY 2" {1 2 3} + 2012.1 "SELECT ALL 1, 2, 3 WHERE 0 GROUP BY 2 HAVING count(*)=1" {} + 2012.2 "SELECT ALL 1, 2, 3 WHERE 'abc' GROUP BY 2 HAVING count(*)>1" {} + + 0111.1 "SELECT count(*), max(a) FROM t1 WHERE a='a' GROUP BY b" {1 a} + 0112.1 "SELECT count(*), max(a) FROM t1 + WHERE a='c' GROUP BY b HAVING count(*)=1" {1 c} + 0112.2 "SELECT count(*), max(a) FROM t1 + WHERE 0 GROUP BY b HAVING count(*)=2" { } + 1111.1 "SELECT DISTINCT count(*), max(a) FROM t1 WHERE a<'c' GROUP BY b" + {1 a 1 b} + 1112.1 "SELECT DISTINCT count(*), max(a) FROM t1 WHERE a>'a' + GROUP BY b HAVING count(*)=1" { + 1 c 1 b + } + 1112.2 "SELECT DISTINCT count(*), max(a) FROM t1 WHERE 0 + GROUP BY b HAVING count(*)=2" { + } + + 2111.1 "SELECT ALL count(*), max(a) FROM t1 WHERE b>'one' GROUP BY b" + {1 c 1 b} + 2112.1 "SELECT ALL count(*), max(a) FROM t1 WHERE a!='b' + GROUP BY b HAVING count(*)=1" { + 1 a 1 c + } + 2112.2 "SELECT ALL count(*), max(a) FROM t1 + WHERE 0 GROUP BY b HAVING count(*)=2" { } +} + + +# -- syntax diagram result-column +# +do_select_tests e_select-0.3 { + 1 "SELECT * FROM t1" {a one b two c three} + 2 "SELECT t1.* FROM t1" {a one b two c three} + 3 "SELECT 'x'||a||'x' FROM t1" {xax xbx xcx} + 4 "SELECT 'x'||a||'x' alias FROM t1" {xax xbx xcx} + 5 "SELECT 'x'||a||'x' AS alias FROM t1" {xax xbx xcx} +} + +# -- syntax diagram join-source +# +# -- syntax diagram join-op +# +do_select_tests e_select-0.4 { + 1 "SELECT t1.rowid FROM t1" {1 2 3} + 2 "SELECT t1.rowid FROM t1,t2" {1 1 1 2 2 2 3 3 3} + 3 "SELECT t1.rowid FROM t1,t2,t3" {1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3} + + 4 "SELECT t1.rowid FROM t1" {1 2 3} + 5 "SELECT t1.rowid FROM t1 JOIN t2" {1 1 1 2 2 2 3 3 3} + 6 "SELECT t1.rowid FROM t1 JOIN t2 JOIN t3" + {1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3} + + 7 "SELECT t1.rowid FROM t1 NATURAL JOIN t3" {1 2} + 8 "SELECT t1.rowid FROM t1 NATURAL LEFT OUTER JOIN t3" {1 2 3} + 9 "SELECT t1.rowid FROM t1 NATURAL LEFT JOIN t3" {1 2 3} + 10 "SELECT t1.rowid FROM t1 NATURAL INNER JOIN t3" {1 2} + 11 "SELECT t1.rowid FROM t1 NATURAL CROSS JOIN t3" {1 2} + + 12 "SELECT t1.rowid FROM t1 JOIN t3" {1 1 2 2 3 3} + 13 "SELECT t1.rowid FROM t1 LEFT OUTER JOIN t3" {1 1 2 2 3 3} + 14 "SELECT t1.rowid FROM t1 LEFT JOIN t3" {1 1 2 2 3 3} + 15 "SELECT t1.rowid FROM t1 INNER JOIN t3" {1 1 2 2 3 3} + 16 "SELECT t1.rowid FROM t1 CROSS JOIN t3" {1 1 2 2 3 3} +} + +# -- syntax diagram compound-operator +# +do_select_tests e_select-0.5 { + 1 "SELECT rowid FROM t1 UNION ALL SELECT rowid+2 FROM t4" {1 2 3 3 4} + 2 "SELECT rowid FROM t1 UNION SELECT rowid+2 FROM t4" {1 2 3 4} + 3 "SELECT rowid FROM t1 INTERSECT SELECT rowid+2 FROM t4" {3} + 4 "SELECT rowid FROM t1 EXCEPT SELECT rowid+2 FROM t4" {1 2} +} + +# -- syntax diagram ordering-term +# +do_select_tests e_select-0.6 { + 1 "SELECT b||a FROM t1 ORDER BY b||a" {onea threec twob} + 2 "SELECT b||a FROM t1 ORDER BY (b||a) COLLATE nocase" {onea threec twob} + 3 "SELECT b||a FROM t1 ORDER BY (b||a) ASC" {onea threec twob} + 4 "SELECT b||a FROM t1 ORDER BY (b||a) DESC" {twob threec onea} +} + +# -- syntax diagram select-stmt +# +do_select_tests e_select-0.7 { + 1 "SELECT * FROM t1" {a one b two c three} + 2 "SELECT * FROM t1 ORDER BY b" {a one c three b two} + 3 "SELECT * FROM t1 ORDER BY b, a" {a one c three b two} + + 4 "SELECT * FROM t1 LIMIT 10" {a one b two c three} + 5 "SELECT * FROM t1 LIMIT 10 OFFSET 5" {} + 6 "SELECT * FROM t1 LIMIT 10, 5" {} + + 7 "SELECT * FROM t1 ORDER BY a LIMIT 10" {a one b two c three} + 8 "SELECT * FROM t1 ORDER BY b LIMIT 10 OFFSET 5" {} + 9 "SELECT * FROM t1 ORDER BY a,b LIMIT 10, 5" {} + + 10 "SELECT * FROM t1 UNION SELECT b, a FROM t1" + {a one b two c three one a three c two b} + 11 "SELECT * FROM t1 UNION SELECT b, a FROM t1 ORDER BY b" + {one a two b three c a one c three b two} + 12 "SELECT * FROM t1 UNION SELECT b, a FROM t1 ORDER BY b, a" + {one a two b three c a one c three b two} + 13 "SELECT * FROM t1 UNION SELECT b, a FROM t1 LIMIT 10" + {a one b two c three one a three c two b} + 14 "SELECT * FROM t1 UNION SELECT b, a FROM t1 LIMIT 10 OFFSET 5" + {two b} + 15 "SELECT * FROM t1 UNION SELECT b, a FROM t1 LIMIT 10, 5" + {} + 16 "SELECT * FROM t1 UNION SELECT b, a FROM t1 ORDER BY a LIMIT 10" + {a one b two c three one a three c two b} + 17 "SELECT * FROM t1 UNION SELECT b, a FROM t1 ORDER BY b LIMIT 10 OFFSET 5" + {b two} + 18 "SELECT * FROM t1 UNION SELECT b, a FROM t1 ORDER BY a,b LIMIT 10, 5" + {} +} + +#------------------------------------------------------------------------- +# The following tests focus on FROM clause (join) processing. +# + +# EVIDENCE-OF: R-16074-54196 If the FROM clause is omitted from a simple +# SELECT statement, then the input data is implicitly a single row zero +# columns wide +# +do_select_tests e_select-1.1 { + 1 "SELECT 'abc'" {abc} + 2 "SELECT 'abc' WHERE NULL" {} + 3 "SELECT NULL" {{}} + 4 "SELECT count(*)" {1} + 5 "SELECT count(*) WHERE 0" {0} + 6 "SELECT count(*) WHERE 1" {1} +} + +# EVIDENCE-OF: R-48114-33255 If there is only a single table in the +# join-source following the FROM clause, then the input data used by the +# SELECT statement is the contents of the named table. +# +# The results of the SELECT queries suggest that they are operating on the +# contents of the table 'xx'. +# +do_execsql_test e_select-1.2.0 { + CREATE TABLE xx(x, y); + INSERT INTO xx VALUES('IiJlsIPepMuAhU', X'10B00B897A15BAA02E3F98DCE8F2'); + INSERT INTO xx VALUES(NULL, -16.87); + INSERT INTO xx VALUES(-17.89, 'linguistically'); +} {} +do_select_tests e_select-1.2 { + 1 "SELECT quote(x), quote(y) FROM xx" { + 'IiJlsIPepMuAhU' X'10B00B897A15BAA02E3F98DCE8F2' + NULL -16.87 + -17.89 'linguistically' + } + + 2 "SELECT count(*), count(x), count(y) FROM xx" {3 2 3} + 3 "SELECT sum(x), sum(y) FROM xx" {-17.89 -16.87} +} + +# EVIDENCE-OF: R-23593-12456 If there is more than one table specified +# as part of the join-source following the FROM keyword, then the +# contents of each named table are joined into a single dataset for the +# simple SELECT statement to operate on. +# +# There are more detailed tests for subsequent requirements that add +# more detail to this idea. We just add a single test that shows that +# data is coming from each of the three tables following the FROM clause +# here to show that the statement, vague as it is, is not incorrect. +# +do_select_tests e_select-1.3 { + 1 "SELECT * FROM t1, t2, t3" { + a one a I a 1 a one a I b 2 a one b II a 1 + a one b II b 2 a one c III a 1 a one c III b 2 + b two a I a 1 b two a I b 2 b two b II a 1 + b two b II b 2 b two c III a 1 b two c III b 2 + c three a I a 1 c three a I b 2 c three b II a 1 + c three b II b 2 c three c III a 1 c three c III b 2 + } +} + +# +# The following block of tests - e_select-1.4.* - test that the description +# of cartesian joins in the SELECT documentation is consistent with SQLite. +# In doing so, we test the following three requirements as a side-effect: +# +# EVIDENCE-OF: R-46122-14930 If the join-op is "CROSS JOIN", "INNER +# JOIN", "JOIN" or a comma (",") and there is no ON or USING clause, +# then the result of the join is simply the cartesian product of the +# left and right-hand datasets. +# +# The tests are built on this assertion. Really, they test that the output +# of a CROSS JOIN, JOIN, INNER JOIN or "," join matches the expected result +# of calculating the cartesian product of the left and right-hand datasets. +# +# EVIDENCE-OF: R-46256-57243 There is no difference between the "INNER +# JOIN", "JOIN" and "," join operators. +# +# EVIDENCE-OF: R-25071-21202 The "CROSS JOIN" join operator produces the +# same result as the "INNER JOIN", "JOIN" and "," operators +# +# All tests are run 4 times, with the only difference in each run being +# which of the 4 equivalent cartesian product join operators are used. +# Since the output data is the same in all cases, we consider that this +# qualifies as testing the two statements above. +# +do_execsql_test e_select-1.4.0 { + CREATE TABLE x1(a, b); + CREATE TABLE x2(c, d, e); + CREATE TABLE x3(f, g, h, i); + + -- x1: 3 rows, 2 columns + INSERT INTO x1 VALUES(24, 'converging'); + INSERT INTO x1 VALUES(NULL, X'CB71'); + INSERT INTO x1 VALUES('blonds', 'proprietary'); + + -- x2: 2 rows, 3 columns + INSERT INTO x2 VALUES(-60.06, NULL, NULL); + INSERT INTO x2 VALUES(-58, NULL, 1.21); + + -- x3: 5 rows, 4 columns + INSERT INTO x3 VALUES(-39.24, NULL, 'encompass', -1); + INSERT INTO x3 VALUES('presenting', 51, 'reformation', 'dignified'); + INSERT INTO x3 VALUES('conducting', -87.24, 37.56, NULL); + INSERT INTO x3 VALUES('coldest', -96, 'dramatists', 82.3); + INSERT INTO x3 VALUES('alerting', NULL, -93.79, NULL); +} {} + +# EVIDENCE-OF: R-59089-25828 The columns of the cartesian product +# dataset are, in order, all the columns of the left-hand dataset +# followed by all the columns of the right-hand dataset. +# +do_join_test e_select-1.4.1.1 { + SELECT * FROM x1 %JOIN% x2 LIMIT 1 +} [concat {24 converging} {-60.06 {} {}}] + +do_join_test e_select-1.4.1.2 { + SELECT * FROM x2 %JOIN% x1 LIMIT 1 +} [concat {-60.06 {} {}} {24 converging}] + +do_join_test e_select-1.4.1.3 { + SELECT * FROM x3 %JOIN% x2 LIMIT 1 +} [concat {-39.24 {} encompass -1} {-60.06 {} {}}] + +do_join_test e_select-1.4.1.4 { + SELECT * FROM x2 %JOIN% x3 LIMIT 1 +} [concat {-60.06 {} {}} {-39.24 {} encompass -1}] + +# EVIDENCE-OF: R-44414-54710 There is a row in the cartesian product +# dataset formed by combining each unique combination of a row from the +# left-hand and right-hand datasets. +# +do_join_test e_select-1.4.2.1 { + SELECT * FROM x2 %JOIN% x3 ORDER BY +c, +f +} [list -60.06 {} {} -39.24 {} encompass -1 \ + -60.06 {} {} alerting {} -93.79 {} \ + -60.06 {} {} coldest -96 dramatists 82.3 \ + -60.06 {} {} conducting -87.24 37.56 {} \ + -60.06 {} {} presenting 51 reformation dignified \ + -58 {} 1.21 -39.24 {} encompass -1 \ + -58 {} 1.21 alerting {} -93.79 {} \ + -58 {} 1.21 coldest -96 dramatists 82.3 \ + -58 {} 1.21 conducting -87.24 37.56 {} \ + -58 {} 1.21 presenting 51 reformation dignified \ +] +# TODO: Come back and add a few more like the above. + +# EVIDENCE-OF: R-20659-43267 In other words, if the left-hand dataset +# consists of Nlhs rows of Mlhs columns, and the right-hand dataset of +# Nrhs rows of Mrhs columns, then the cartesian product is a dataset of +# Nlhs.Nrhs rows, each containing Mlhs+Mrhs columns. +# +# x1, x2 (Nlhs=3, Nrhs=2) (Mlhs=2, Mrhs=3) +do_join_test e_select-1.4.3.1 { + SELECT count(*) FROM x1 %JOIN% x2 +} [expr 3*2] +do_test e_select-1.4.3.2 { + expr {[llength [execsql {SELECT * FROM x1, x2}]] / 6} +} [expr 2+3] + +# x2, x3 (Nlhs=2, Nrhs=5) (Mlhs=3, Mrhs=4) +do_join_test e_select-1.4.3.3 { + SELECT count(*) FROM x2 %JOIN% x3 +} [expr 2*5] +do_test e_select-1.4.3.4 { + expr {[llength [execsql {SELECT * FROM x2 JOIN x3}]] / 10} +} [expr 3+4] + +# x3, x1 (Nlhs=5, Nrhs=3) (Mlhs=4, Mrhs=2) +do_join_test e_select-1.4.3.5 { + SELECT count(*) FROM x3 %JOIN% x1 +} [expr 5*3] +do_test e_select-1.4.3.6 { + expr {[llength [execsql {SELECT * FROM x3 CROSS JOIN x1}]] / 15} +} [expr 4+2] + +# x3, x3 (Nlhs=5, Nrhs=5) (Mlhs=4, Mrhs=4) +do_join_test e_select-1.4.3.7 { + SELECT count(*) FROM x3 %JOIN% x3 +} [expr 5*5] +do_test e_select-1.4.3.8 { + expr {[llength [execsql {SELECT * FROM x3 INNER JOIN x3 AS x4}]] / 25} +} [expr 4+4] + +# Some extra cartesian product tests using tables t1 and t2. +# +do_execsql_test e_select-1.4.4.1 { SELECT * FROM t1, t2 } $t1_cross_t2 +do_execsql_test e_select-1.4.4.2 { SELECT * FROM t1 AS x, t1 AS y} $t1_cross_t1 + +do_select_tests e_select-1.4.5 [list \ + 1 { SELECT * FROM t1 CROSS JOIN t2 } $t1_cross_t2 \ + 2 { SELECT * FROM t1 AS y CROSS JOIN t1 AS x } $t1_cross_t1 \ + 3 { SELECT * FROM t1 INNER JOIN t2 } $t1_cross_t2 \ + 4 { SELECT * FROM t1 AS y INNER JOIN t1 AS x } $t1_cross_t1 \ +] + + +# EVIDENCE-OF: R-22775-56496 If there is an ON clause specified, then +# the ON expression is evaluated for each row of the cartesian product +# as a boolean expression. All rows for which the expression evaluates +# to false are excluded from the dataset. +# +foreach {tn select res} [list \ + 1 { SELECT * FROM t1 %JOIN% t2 ON (1) } $t1_cross_t2 \ + 2 { SELECT * FROM t1 %JOIN% t2 ON (0) } [list] \ + 3 { SELECT * FROM t1 %JOIN% t2 ON (NULL) } [list] \ + 4 { SELECT * FROM t1 %JOIN% t2 ON ('abc') } [list] \ + 5 { SELECT * FROM t1 %JOIN% t2 ON ('1ab') } $t1_cross_t2 \ + 6 { SELECT * FROM t1 %JOIN% t2 ON (0.9) } $t1_cross_t2 \ + 7 { SELECT * FROM t1 %JOIN% t2 ON ('0.9') } $t1_cross_t2 \ + 8 { SELECT * FROM t1 %JOIN% t2 ON (0.0) } [list] \ + \ + 9 { SELECT t1.b, t2.b FROM t1 %JOIN% t2 ON (t1.a = t2.a) } \ + {one I two II three III} \ + 10 { SELECT t1.b, t2.b FROM t1 %JOIN% t2 ON (t1.a = 'a') } \ + {one I one II one III} \ + 11 { SELECT t1.b, t2.b + FROM t1 %JOIN% t2 ON (CASE WHEN t1.a = 'a' THEN NULL ELSE 1 END) } \ + {two I two II two III three I three II three III} \ +] { + do_join_test e_select-1.3.$tn $select $res +} + +# EVIDENCE-OF: R-63358-54862 If there is a USING clause specified as +# part of the join-constraint, then each of the column names specified +# must exist in the datasets to both the left and right of the join-op. +# +do_select_tests e_select-1.4 -error { + cannot join using column %s - column not present in both tables +} { + 1 { SELECT * FROM t1, t3 USING (b) } "b" + 2 { SELECT * FROM t3, t1 USING (c) } "c" + 3 { SELECT * FROM t3, (SELECT a AS b, b AS c FROM t1) USING (a) } "a" +} + +# EVIDENCE-OF: R-55987-04584 For each pair of namesake columns, the +# expression "lhs.X = rhs.X" is evaluated for each row of the cartesian +# product as a boolean expression. All rows for which one or more of the +# expressions evaluates to false are excluded from the result set. +# +do_select_tests e_select-1.5 { + 1 { SELECT * FROM t1, t3 USING (a) } {a one 1 b two 2} + 2 { SELECT * FROM t3, t4 USING (a,c) } {b 2} +} + +# EVIDENCE-OF: R-54046-48600 When comparing values as a result of a +# USING clause, the normal rules for handling affinities, collation +# sequences and NULL values in comparisons apply. +# +# EVIDENCE-OF: R-35466-18578 The column from the dataset on the +# left-hand side of the join operator is considered to be on the +# left-hand side of the comparison operator (=) for the purposes of +# collation sequence and affinity precedence. +# +do_execsql_test e_select-1.6.0 { + CREATE TABLE t5(a COLLATE nocase, b COLLATE binary); + INSERT INTO t5 VALUES('AA', 'cc'); + INSERT INTO t5 VALUES('BB', 'dd'); + INSERT INTO t5 VALUES(NULL, NULL); + CREATE TABLE t6(a COLLATE binary, b COLLATE nocase); + INSERT INTO t6 VALUES('aa', 'cc'); + INSERT INTO t6 VALUES('bb', 'DD'); + INSERT INTO t6 VALUES(NULL, NULL); +} {} +foreach {tn select res} { + 1 { SELECT * FROM t5 %JOIN% t6 USING (a) } {AA cc cc BB dd DD} + 2 { SELECT * FROM t6 %JOIN% t5 USING (a) } {} + 3 { SELECT * FROM (SELECT a COLLATE nocase, b FROM t6) %JOIN% t5 USING (a) } + {aa cc cc bb DD dd} + 4 { SELECT * FROM t5 %JOIN% t6 USING (a,b) } {AA cc} + 5 { SELECT * FROM t6 %JOIN% t5 USING (a,b) } {} +} { + do_join_test e_select-1.6.$tn $select $res +} + +# EVIDENCE-OF: R-57047-10461 For each pair of columns identified by a +# USING clause, the column from the right-hand dataset is omitted from +# the joined dataset. +# +# EVIDENCE-OF: R-56132-15700 This is the only difference between a USING +# clause and its equivalent ON constraint. +# +foreach {tn select res} { + 1a { SELECT * FROM t1 %JOIN% t2 USING (a) } + {a one I b two II c three III} + 1b { SELECT * FROM t1 %JOIN% t2 ON (t1.a=t2.a) } + {a one a I b two b II c three c III} + + 2a { SELECT * FROM t3 %JOIN% t4 USING (a) } + {a 1 {} b 2 2} + 2b { SELECT * FROM t3 %JOIN% t4 ON (t3.a=t4.a) } + {a 1 a {} b 2 b 2} + + 3a { SELECT * FROM t3 %JOIN% t4 USING (a,c) } {b 2} + 3b { SELECT * FROM t3 %JOIN% t4 ON (t3.a=t4.a AND t3.c=t4.c) } {b 2 b 2} + + 4a { SELECT * FROM (SELECT a COLLATE nocase, b FROM t6) AS x + %JOIN% t5 USING (a) } + {aa cc cc bb DD dd} + 4b { SELECT * FROM (SELECT a COLLATE nocase, b FROM t6) AS x + %JOIN% t5 ON (x.a=t5.a) } + {aa cc AA cc bb DD BB dd} +} { + do_join_test e_select-1.7.$tn $select $res +} + +# EVIDENCE-OF: R-41434-12448 If the join-op is a "LEFT JOIN" or "LEFT +# OUTER JOIN", then after the ON or USING filtering clauses have been +# applied, an extra row is added to the output for each row in the +# original left-hand input dataset that corresponds to no rows at all in +# the composite dataset (if any). +# +do_execsql_test e_select-1.8.0 { + CREATE TABLE t7(a, b, c); + CREATE TABLE t8(a, d, e); + + INSERT INTO t7 VALUES('x', 'ex', 24); + INSERT INTO t7 VALUES('y', 'why', 25); + + INSERT INTO t8 VALUES('x', 'abc', 24); + INSERT INTO t8 VALUES('z', 'ghi', 26); +} {} + +do_select_tests e_select-1.8 { + 1a "SELECT count(*) FROM t7 JOIN t8 ON (t7.a=t8.a)" {1} + 1b "SELECT count(*) FROM t7 LEFT JOIN t8 ON (t7.a=t8.a)" {2} + 2a "SELECT count(*) FROM t7 JOIN t8 USING (a)" {1} + 2b "SELECT count(*) FROM t7 LEFT JOIN t8 USING (a)" {2} +} + + +# EVIDENCE-OF: R-15607-52988 The added rows contain NULL values in the +# columns that would normally contain values copied from the right-hand +# input dataset. +# +do_select_tests e_select-1.9 { + 1a "SELECT * FROM t7 JOIN t8 ON (t7.a=t8.a)" {x ex 24 x abc 24} + 1b "SELECT * FROM t7 LEFT JOIN t8 ON (t7.a=t8.a)" + {x ex 24 x abc 24 y why 25 {} {} {}} + 2a "SELECT * FROM t7 JOIN t8 USING (a)" {x ex 24 abc 24} + 2b "SELECT * FROM t7 LEFT JOIN t8 USING (a)" {x ex 24 abc 24 y why 25 {} {}} +} + +# EVIDENCE-OF: R-01809-52134 If the NATURAL keyword is added to any of +# the join-ops, then an implicit USING clause is added to the +# join-constraints. The implicit USING clause contains each of the +# column names that appear in both the left and right-hand input +# datasets. +# +do_select_tests e_select-1-10 { + 1a "SELECT * FROM t7 JOIN t8 USING (a)" {x ex 24 abc 24} + 1b "SELECT * FROM t7 NATURAL JOIN t8" {x ex 24 abc 24} + + 2a "SELECT * FROM t8 JOIN t7 USING (a)" {x abc 24 ex 24} + 2b "SELECT * FROM t8 NATURAL JOIN t7" {x abc 24 ex 24} + + 3a "SELECT * FROM t7 LEFT JOIN t8 USING (a)" {x ex 24 abc 24 y why 25 {} {}} + 3b "SELECT * FROM t7 NATURAL LEFT JOIN t8" {x ex 24 abc 24 y why 25 {} {}} + + 4a "SELECT * FROM t8 LEFT JOIN t7 USING (a)" {x abc 24 ex 24 z ghi 26 {} {}} + 4b "SELECT * FROM t8 NATURAL LEFT JOIN t7" {x abc 24 ex 24 z ghi 26 {} {}} + + 5a "SELECT * FROM t3 JOIN t4 USING (a,c)" {b 2} + 5b "SELECT * FROM t3 NATURAL JOIN t4" {b 2} + + 6a "SELECT * FROM t3 LEFT JOIN t4 USING (a,c)" {a 1 b 2} + 6b "SELECT * FROM t3 NATURAL LEFT JOIN t4" {a 1 b 2} +} + +# EVIDENCE-OF: R-49566-01570 If the left and right-hand input datasets +# feature no common column names, then the NATURAL keyword has no effect +# on the results of the join. +# +do_execsql_test e_select-1.11.0 { + CREATE TABLE t10(x, y); + INSERT INTO t10 VALUES(1, 'true'); + INSERT INTO t10 VALUES(0, 'false'); +} {} +do_select_tests e_select-1-11 { + 1a "SELECT a, x FROM t1 CROSS JOIN t10" {a 1 a 0 b 1 b 0 c 1 c 0} + 1b "SELECT a, x FROM t1 NATURAL CROSS JOIN t10" {a 1 a 0 b 1 b 0 c 1 c 0} +} + +# EVIDENCE-OF: R-39625-59133 A USING or ON clause may not be added to a +# join that specifies the NATURAL keyword. +# +foreach {tn sql} { + 1 {SELECT * FROM t1 NATURAL LEFT JOIN t2 USING (a)} + 2 {SELECT * FROM t1 NATURAL LEFT JOIN t2 ON (t1.a=t2.a)} + 3 {SELECT * FROM t1 NATURAL LEFT JOIN t2 ON (45)} +} { + do_catchsql_test e_select-1.12.$tn " + $sql + " {1 {a NATURAL join may not have an ON or USING clause}} +} + +#------------------------------------------------------------------------- +# The next block of tests - e_select-3.* - concentrate on verifying +# statements made regarding WHERE clause processing. +# +drop_all_tables +do_execsql_test e_select-3.0 { + CREATE TABLE x1(k, x, y, z); + INSERT INTO x1 VALUES(1, 'relinquished', 'aphasia', 78.43); + INSERT INTO x1 VALUES(2, X'A8E8D66F', X'07CF', -81); + INSERT INTO x1 VALUES(3, -22, -27.57, NULL); + INSERT INTO x1 VALUES(4, NULL, 'bygone', 'picky'); + INSERT INTO x1 VALUES(5, NULL, 96.28, NULL); + INSERT INTO x1 VALUES(6, 0, 1, 2); + + CREATE TABLE x2(k, x, y2); + INSERT INTO x2 VALUES(1, 50, X'B82838'); + INSERT INTO x2 VALUES(5, 84.79, 65.88); + INSERT INTO x2 VALUES(3, -22, X'0E1BE452A393'); + INSERT INTO x2 VALUES(7, 'mistrusted', 'standardized'); +} {} + +# EVIDENCE-OF: R-06999-14330 If a WHERE clause is specified, the WHERE +# expression is evaluated for each row in the input data as a boolean +# expression. All rows for which the WHERE clause expression evaluates +# to false are excluded from the dataset before continuing. +# +do_execsql_test e_select-3.1.1 { SELECT k FROM x1 WHERE x } {3} +do_execsql_test e_select-3.1.2 { SELECT k FROM x1 WHERE y } {3 5 6} +do_execsql_test e_select-3.1.3 { SELECT k FROM x1 WHERE z } {1 2 6} +do_execsql_test e_select-3.1.4 { SELECT k FROM x1 WHERE '1'||z } {1 2 4 6} +do_execsql_test e_select-3.1.5 { SELECT k FROM x1 WHERE x IS NULL } {4 5} +do_execsql_test e_select-3.1.6 { SELECT k FROM x1 WHERE z - 78.43 } {2 4 6} + +do_execsql_test e_select-3.2.1a { + SELECT k FROM x1 LEFT JOIN x2 USING(k) +} {1 2 3 4 5 6} +do_execsql_test e_select-3.2.1b { + SELECT k FROM x1 LEFT JOIN x2 USING(k) WHERE x2.k +} {1 3 5} +do_execsql_test e_select-3.2.2 { + SELECT k FROM x1 LEFT JOIN x2 USING(k) WHERE x2.k IS NULL +} {2 4 6} + +do_execsql_test e_select-3.2.3 { + SELECT k FROM x1 NATURAL JOIN x2 WHERE x2.k +} {3} +do_execsql_test e_select-3.2.4 { + SELECT k FROM x1 NATURAL JOIN x2 WHERE x2.k-3 +} {} + +#------------------------------------------------------------------------- +# Tests below this point are focused on verifying the testable statements +# related to caculating the result rows of a simple SELECT statement. +# + +drop_all_tables +do_execsql_test e_select-4.0 { + CREATE TABLE z1(a, b, c); + CREATE TABLE z2(d, e); + CREATE TABLE z3(a, b); + + INSERT INTO z1 VALUES(51.65, -59.58, 'belfries'); + INSERT INTO z1 VALUES(-5, NULL, 75); + INSERT INTO z1 VALUES(-2.2, -23.18, 'suiters'); + INSERT INTO z1 VALUES(NULL, 67, 'quartets'); + INSERT INTO z1 VALUES(-1.04, -32.3, 'aspen'); + INSERT INTO z1 VALUES(63, 'born', -26); + + INSERT INTO z2 VALUES(NULL, 21); + INSERT INTO z2 VALUES(36, 6); + + INSERT INTO z3 VALUES('subsistence', 'gauze'); + INSERT INTO z3 VALUES(49.17, -67); +} {} + +# EVIDENCE-OF: R-36327-17224 If a result expression is the special +# expression "*" then all columns in the input data are substituted for +# that one expression. +# +# EVIDENCE-OF: R-43693-30522 If the expression is the alias of a table +# or subquery in the FROM clause followed by ".*" then all columns from +# the named table or subquery are substituted for the single expression. +# +do_select_tests e_select-4.1 { + 1 "SELECT * FROM z1 LIMIT 1" {51.65 -59.58 belfries} + 2 "SELECT * FROM z1,z2 LIMIT 1" {51.65 -59.58 belfries {} 21} + 3 "SELECT z1.* FROM z1,z2 LIMIT 1" {51.65 -59.58 belfries} + 4 "SELECT z2.* FROM z1,z2 LIMIT 1" {{} 21} + 5 "SELECT z2.*, z1.* FROM z1,z2 LIMIT 1" {{} 21 51.65 -59.58 belfries} + + 6 "SELECT count(*), * FROM z1" {6 63 born -26} + 7 "SELECT max(a), * FROM z1" {63 63 born -26} + 8 "SELECT *, min(a) FROM z1" {-5 {} 75 -5} + + 9 "SELECT *,* FROM z1,z2 LIMIT 1" { + 51.65 -59.58 belfries {} 21 51.65 -59.58 belfries {} 21 + } + 10 "SELECT z1.*,z1.* FROM z2,z1 LIMIT 1" { + 51.65 -59.58 belfries 51.65 -59.58 belfries + } +} + +# EVIDENCE-OF: R-61869-22578 It is an error to use a "*" or "alias.*" +# expression in any context other than than a result expression list. +# +# EVIDENCE-OF: R-44324-41166 It is also an error to use a "*" or +# "alias.*" expression in a simple SELECT query that does not have a +# FROM clause. +# +foreach {tn select err} { + 1.1 "SELECT a, b, c FROM z1 WHERE *" {near "*": syntax error} + 1.2 "SELECT a, b, c FROM z1 GROUP BY *" {near "*": syntax error} + 1.3 "SELECT 1 + * FROM z1" {near "*": syntax error} + 1.4 "SELECT * + 1 FROM z1" {near "+": syntax error} + + 2.1 "SELECT *" {no tables specified} + 2.2 "SELECT * WHERE 1" {no tables specified} + 2.3 "SELECT * WHERE 0" {no tables specified} + 2.4 "SELECT count(*), *" {no tables specified} +} { + do_catchsql_test e_select-4.2.$tn $select [list 1 $err] +} + +# EVIDENCE-OF: R-08669-22397 The number of columns in the rows returned +# by a simple SELECT statement is equal to the number of expressions in +# the result expression list after substitution of * and alias.* +# expressions. +# +foreach {tn select nCol} { + 1 "SELECT * FROM z1" 3 + 2 "SELECT * FROM z1 NATURAL JOIN z3" 3 + 3 "SELECT z1.* FROM z1 NATURAL JOIN z3" 3 + 4 "SELECT z3.* FROM z1 NATURAL JOIN z3" 2 + 5 "SELECT z1.*, z3.* FROM z1 NATURAL JOIN z3" 5 + 6 "SELECT 1, 2, z1.* FROM z1" 5 + 7 "SELECT a, *, b, c FROM z1" 6 +} { + set ::stmt [sqlite3_prepare_v2 db $select -1 DUMMY] + do_test e_select-4.3.$tn { sqlite3_column_count $::stmt } $nCol + sqlite3_finalize $::stmt +} + + + +# In lang_select.html, a non-aggregate query is defined as any simple SELECT +# that has no GROUP BY clause and no aggregate expressions in the result +# expression list. Other queries are aggregate queries. Test cases +# e_select-4.4.* through e_select-4.12.*, inclusive, which test the part of +# simple SELECT that is different for aggregate and non-aggregate queries +# verify (in a way) that these definitions are consistent: +# +# EVIDENCE-OF: R-20637-43463 A simple SELECT statement is an aggregate +# query if it contains either a GROUP BY clause or one or more aggregate +# functions in the result-set. +# +# EVIDENCE-OF: R-23155-55597 Otherwise, if a simple SELECT contains no +# aggregate functions or a GROUP BY clause, it is a non-aggregate query. +# + +# EVIDENCE-OF: R-44050-47362 If the SELECT statement is a non-aggregate +# query, then each expression in the result expression list is evaluated +# for each row in the dataset filtered by the WHERE clause. +# +do_select_tests e_select-4.4 { + 1 "SELECT a, b FROM z1" + {51.65 -59.58 -5 {} -2.2 -23.18 {} 67 -1.04 -32.3 63 born} + + 2 "SELECT a IS NULL, b+1, * FROM z1" { + 0 -58.58 51.65 -59.58 belfries + 0 {} -5 {} 75 + 0 -22.18 -2.2 -23.18 suiters + 1 68 {} 67 quartets + 0 -31.3 -1.04 -32.3 aspen + 0 1 63 born -26 + } + + 3 "SELECT 32*32, d||e FROM z2" {1024 {} 1024 366} +} + + +# Test cases e_select-4.5.* and e_select-4.6.* together show that: +# +# EVIDENCE-OF: R-51988-01124 The single row of result-set data created +# by evaluating the aggregate and non-aggregate expressions in the +# result-set forms the result of an aggregate query without a GROUP BY +# clause. +# + +# EVIDENCE-OF: R-57629-25253 If the SELECT statement is an aggregate +# query without a GROUP BY clause, then each aggregate expression in the +# result-set is evaluated once across the entire dataset. +# +do_select_tests e_select-4.5 { + 1 "SELECT count(a), max(a), count(b), max(b) FROM z1" {5 63 5 born} + 2 "SELECT count(*), max(1)" {1 1} + + 3 "SELECT sum(b+1) FROM z1 NATURAL LEFT JOIN z3" {-43.06} + 4 "SELECT sum(b+2) FROM z1 NATURAL LEFT JOIN z3" {-38.06} + 5 "SELECT sum(b IS NOT NULL) FROM z1 NATURAL LEFT JOIN z3" {5} +} + +# EVIDENCE-OF: R-26684-40576 Each non-aggregate expression in the +# result-set is evaluated once for an arbitrarily selected row of the +# dataset. +# +# EVIDENCE-OF: R-27994-60376 The same arbitrarily selected row is used +# for each non-aggregate expression. +# +# Note: The results of many of the queries in this block of tests are +# technically undefined, as the documentation does not specify which row +# SQLite will arbitrarily select to use for the evaluation of the +# non-aggregate expressions. +# +drop_all_tables +do_execsql_test e_select-4.6.0 { + CREATE TABLE a1(one PRIMARY KEY, two); + INSERT INTO a1 VALUES(1, 1); + INSERT INTO a1 VALUES(2, 3); + INSERT INTO a1 VALUES(3, 6); + INSERT INTO a1 VALUES(4, 10); + + CREATE TABLE a2(one PRIMARY KEY, three); + INSERT INTO a2 VALUES(1, 1); + INSERT INTO a2 VALUES(3, 2); + INSERT INTO a2 VALUES(6, 3); + INSERT INTO a2 VALUES(10, 4); +} {} +do_select_tests e_select-4.6 { + 1 "SELECT one, two, count(*) FROM a1" {4 10 4} + 2 "SELECT one, two, count(*) FROM a1 WHERE one<3" {2 3 2} + 3 "SELECT one, two, count(*) FROM a1 WHERE one>3" {4 10 1} + 4 "SELECT *, count(*) FROM a1 JOIN a2" {4 10 10 4 16} + 5 "SELECT *, sum(three) FROM a1 NATURAL JOIN a2" {3 6 2 3} + 6 "SELECT *, sum(three) FROM a1 NATURAL JOIN a2" {3 6 2 3} + 7 "SELECT group_concat(three, ''), a1.* FROM a1 NATURAL JOIN a2" {12 3 6} +} + +# EVIDENCE-OF: R-04486-07266 Or, if the dataset contains zero rows, then +# each non-aggregate expression is evaluated against a row consisting +# entirely of NULL values. +# +do_select_tests e_select-4.7 { + 1 "SELECT one, two, count(*) FROM a1 WHERE 0" {{} {} 0} + 2 "SELECT sum(two), * FROM a1, a2 WHERE three>5" {{} {} {} {} {}} + 3 "SELECT max(one) IS NULL, one IS NULL, two IS NULL FROM a1 WHERE two=7" { + 1 1 1 + } +} + +# EVIDENCE-OF: R-64138-28774 An aggregate query without a GROUP BY +# clause always returns exactly one row of data, even if there are zero +# rows of input data. +# +foreach {tn select} { + 8.1 "SELECT count(*) FROM a1" + 8.2 "SELECT count(*) FROM a1 WHERE 0" + 8.3 "SELECT count(*) FROM a1 WHERE 1" + 8.4 "SELECT max(a1.one)+min(two), a1.one, two, * FROM a1, a2 WHERE 1" + 8.5 "SELECT max(a1.one)+min(two), a1.one, two, * FROM a1, a2 WHERE 0" +} { + # Set $nRow to the number of rows returned by $select: + set ::stmt [sqlite3_prepare_v2 db $select -1 DUMMY] + set nRow 0 + while {"SQLITE_ROW" == [sqlite3_step $::stmt]} { incr nRow } + set rc [sqlite3_finalize $::stmt] + + # Test that $nRow==1 and that statement execution was successful + # (rc==SQLITE_OK). + do_test e_select-4.$tn [list list $rc $nRow] {SQLITE_OK 1} +} + +drop_all_tables +do_execsql_test e_select-4.9.0 { + CREATE TABLE b1(one PRIMARY KEY, two); + INSERT INTO b1 VALUES(1, 'o'); + INSERT INTO b1 VALUES(4, 'f'); + INSERT INTO b1 VALUES(3, 't'); + INSERT INTO b1 VALUES(2, 't'); + INSERT INTO b1 VALUES(5, 'f'); + INSERT INTO b1 VALUES(7, 's'); + INSERT INTO b1 VALUES(6, 's'); + + CREATE TABLE b2(x, y); + INSERT INTO b2 VALUES(NULL, 0); + INSERT INTO b2 VALUES(NULL, 1); + INSERT INTO b2 VALUES('xyz', 2); + INSERT INTO b2 VALUES('abc', 3); + INSERT INTO b2 VALUES('xyz', 4); + + CREATE TABLE b3(a COLLATE nocase, b COLLATE binary); + INSERT INTO b3 VALUES('abc', 'abc'); + INSERT INTO b3 VALUES('aBC', 'aBC'); + INSERT INTO b3 VALUES('Def', 'Def'); + INSERT INTO b3 VALUES('dEF', 'dEF'); +} {} + +# EVIDENCE-OF: R-57754-57109 If the SELECT statement is an aggregate +# query with a GROUP BY clause, then each of the expressions specified +# as part of the GROUP BY clause is evaluated for each row of the +# dataset. Each row is then assigned to a "group" based on the results; +# rows for which the results of evaluating the GROUP BY expressions are +# the same are assigned to the same group. +# +# These tests also show that the following is not untrue: +# +# EVIDENCE-OF: R-25883-55063 The expressions in the GROUP BY clause do +# not have to be expressions that appear in the result. +# +do_select_tests e_select-4.9 { + 1 "SELECT group_concat(one), two FROM b1 GROUP BY two" { + /#,# f 1 o #,# s #,# t/ + } + 2 "SELECT group_concat(one), sum(one) FROM b1 GROUP BY (one>4)" { + 1,2,3,4 10 5,6,7 18 + } + 3 "SELECT group_concat(one) FROM b1 GROUP BY (two>'o'), one%2" { + 4 1,5 2,6 3,7 + } + 4 "SELECT group_concat(one) FROM b1 GROUP BY (one==2 OR two=='o')" { + 4,3,5,7,6 1,2 + } +} + +# EVIDENCE-OF: R-14926-50129 For the purposes of grouping rows, NULL +# values are considered equal. +# +do_select_tests e_select-4.10 { + 1 "SELECT group_concat(y) FROM b2 GROUP BY x" {/#,# 3 #,#/} + 2 "SELECT count(*) FROM b2 GROUP BY CASE WHEN y<4 THEN NULL ELSE 0 END" {4 1} +} + +# EVIDENCE-OF: R-10470-30318 The usual rules for selecting a collation +# sequence with which to compare text values apply when evaluating +# expressions in a GROUP BY clause. +# +do_select_tests e_select-4.11 { + 1 "SELECT count(*) FROM b3 GROUP BY b" {1 1 1 1} + 2 "SELECT count(*) FROM b3 GROUP BY a" {2 2} + 3 "SELECT count(*) FROM b3 GROUP BY +b" {1 1 1 1} + 4 "SELECT count(*) FROM b3 GROUP BY +a" {2 2} + 5 "SELECT count(*) FROM b3 GROUP BY b||''" {1 1 1 1} + 6 "SELECT count(*) FROM b3 GROUP BY a||''" {1 1 1 1} +} + +# EVIDENCE-OF: R-63573-50730 The expressions in a GROUP BY clause may +# not be aggregate expressions. +# +foreach {tn select} { + 12.1 "SELECT * FROM b3 GROUP BY count(*)" + 12.2 "SELECT max(a) FROM b3 GROUP BY max(b)" + 12.3 "SELECT group_concat(a) FROM b3 GROUP BY a, max(b)" +} { + set res {1 {aggregate functions are not allowed in the GROUP BY clause}} + do_catchsql_test e_select-4.$tn $select $res +} + +# EVIDENCE-OF: R-31537-00101 If a HAVING clause is specified, it is +# evaluated once for each group of rows as a boolean expression. If the +# result of evaluating the HAVING clause is false, the group is +# discarded. +# +# This requirement is tested by all e_select-4.13.* tests. +# +# EVIDENCE-OF: R-04132-09474 If the HAVING clause is an aggregate +# expression, it is evaluated across all rows in the group. +# +# Tested by e_select-4.13.1.* +# +# EVIDENCE-OF: R-28262-47447 If a HAVING clause is a non-aggregate +# expression, it is evaluated with respect to an arbitrarily selected +# row from the group. +# +# Tested by e_select-4.13.2.* +# +# Tests in this block also show that this is not untrue: +# +# EVIDENCE-OF: R-55403-13450 The HAVING expression may refer to values, +# even aggregate functions, that are not in the result. +# +do_execsql_test e_select-4.13.0 { + CREATE TABLE c1(up, down); + INSERT INTO c1 VALUES('x', 1); + INSERT INTO c1 VALUES('x', 2); + INSERT INTO c1 VALUES('x', 4); + INSERT INTO c1 VALUES('x', 8); + INSERT INTO c1 VALUES('y', 16); + INSERT INTO c1 VALUES('y', 32); + + CREATE TABLE c2(i, j); + INSERT INTO c2 VALUES(1, 0); + INSERT INTO c2 VALUES(2, 1); + INSERT INTO c2 VALUES(3, 3); + INSERT INTO c2 VALUES(4, 6); + INSERT INTO c2 VALUES(5, 10); + INSERT INTO c2 VALUES(6, 15); + INSERT INTO c2 VALUES(7, 21); + INSERT INTO c2 VALUES(8, 28); + INSERT INTO c2 VALUES(9, 36); + + CREATE TABLE c3(i PRIMARY KEY, k TEXT); + INSERT INTO c3 VALUES(1, 'hydrogen'); + INSERT INTO c3 VALUES(2, 'helium'); + INSERT INTO c3 VALUES(3, 'lithium'); + INSERT INTO c3 VALUES(4, 'beryllium'); + INSERT INTO c3 VALUES(5, 'boron'); + INSERT INTO c3 VALUES(94, 'plutonium'); +} {} + +do_select_tests e_select-4.13 { + 1.1 "SELECT up FROM c1 GROUP BY up HAVING count(*)>3" {x} + 1.2 "SELECT up FROM c1 GROUP BY up HAVING sum(down)>16" {y} + 1.3 "SELECT up FROM c1 GROUP BY up HAVING sum(down)<16" {x} + 1.4 "SELECT up||down FROM c1 GROUP BY (down<5) HAVING max(down)<10" {x4} + + 2.1 "SELECT up FROM c1 GROUP BY up HAVING down>10" {y} + 2.2 "SELECT up FROM c1 GROUP BY up HAVING up='y'" {y} + + 2.3 "SELECT i, j FROM c2 GROUP BY i>4 HAVING i>6" {9 36} +} + +# EVIDENCE-OF: R-23927-54081 Each expression in the result-set is then +# evaluated once for each group of rows. +# +# EVIDENCE-OF: R-53735-47017 If the expression is an aggregate +# expression, it is evaluated across all rows in the group. +# +do_select_tests e_select-4.15 { + 1 "SELECT sum(down) FROM c1 GROUP BY up" {15 48} + 2 "SELECT sum(j), max(j) FROM c2 GROUP BY (i%3)" {54 36 27 21 39 28} + 3 "SELECT sum(j), max(j) FROM c2 GROUP BY (j%2)" {80 36 40 21} + 4 "SELECT 1+sum(j), max(j)+1 FROM c2 GROUP BY (j%2)" {81 37 41 22} + 5 "SELECT count(*), round(avg(i),2) FROM c1, c2 ON (i=down) GROUP BY j%2" + {3 4.33 1 2.0} +} + +# EVIDENCE-OF: R-62913-19830 Otherwise, it is evaluated against a single +# arbitrarily chosen row from within the group. +# +# EVIDENCE-OF: R-53924-08809 If there is more than one non-aggregate +# expression in the result-set, then all such expressions are evaluated +# for the same row. +# +do_select_tests e_select-4.15 { + 1 "SELECT i, j FROM c2 GROUP BY i%2" {8 28 9 36} + 2 "SELECT i, j FROM c2 GROUP BY i%2 HAVING j<30" {8 28} + 3 "SELECT i, j FROM c2 GROUP BY i%2 HAVING j>30" {9 36} + 4 "SELECT i, j FROM c2 GROUP BY i%2 HAVING j>30" {9 36} + 5 "SELECT count(*), i, k FROM c2 NATURAL JOIN c3 GROUP BY substr(k, 1, 1)" + {2 5 boron 2 2 helium 1 3 lithium} +} + +# EVIDENCE-OF: R-19334-12811 Each group of input dataset rows +# contributes a single row to the set of result rows. +# +# EVIDENCE-OF: R-02223-49279 Subject to filtering associated with the +# DISTINCT keyword, the number of rows returned by an aggregate query +# with a GROUP BY clause is the same as the number of groups of rows +# produced by applying the GROUP BY and HAVING clauses to the filtered +# input dataset. +# +do_select_tests e_select.4.16 -count { + 1 "SELECT i, j FROM c2 GROUP BY i%2" 2 + 2 "SELECT i, j FROM c2 GROUP BY i" 9 + 3 "SELECT i, j FROM c2 GROUP BY i HAVING i<5" 4 +} + +#------------------------------------------------------------------------- +# The following tests attempt to verify statements made regarding the ALL +# and DISTINCT keywords. +# +drop_all_tables +do_execsql_test e_select-5.1.0 { + CREATE TABLE h1(a, b); + INSERT INTO h1 VALUES(1, 'one'); + INSERT INTO h1 VALUES(1, 'I'); + INSERT INTO h1 VALUES(1, 'i'); + INSERT INTO h1 VALUES(4, 'four'); + INSERT INTO h1 VALUES(4, 'IV'); + INSERT INTO h1 VALUES(4, 'iv'); + + CREATE TABLE h2(x COLLATE nocase); + INSERT INTO h2 VALUES('One'); + INSERT INTO h2 VALUES('Two'); + INSERT INTO h2 VALUES('Three'); + INSERT INTO h2 VALUES('Four'); + INSERT INTO h2 VALUES('one'); + INSERT INTO h2 VALUES('two'); + INSERT INTO h2 VALUES('three'); + INSERT INTO h2 VALUES('four'); + + CREATE TABLE h3(c, d); + INSERT INTO h3 VALUES(1, NULL); + INSERT INTO h3 VALUES(2, NULL); + INSERT INTO h3 VALUES(3, NULL); + INSERT INTO h3 VALUES(4, '2'); + INSERT INTO h3 VALUES(5, NULL); + INSERT INTO h3 VALUES(6, '2,3'); + INSERT INTO h3 VALUES(7, NULL); + INSERT INTO h3 VALUES(8, '2,4'); + INSERT INTO h3 VALUES(9, '3'); +} {} + +# EVIDENCE-OF: R-60770-10612 One of the ALL or DISTINCT keywords may +# follow the SELECT keyword in a simple SELECT statement. +# +do_select_tests e_select-5.1 { + 1 "SELECT ALL a FROM h1" {1 1 1 4 4 4} + 2 "SELECT DISTINCT a FROM h1" {1 4} +} + +# EVIDENCE-OF: R-08861-34280 If the simple SELECT is a SELECT ALL, then +# the entire set of result rows are returned by the SELECT. +# +# EVIDENCE-OF: R-01256-01950 If neither ALL or DISTINCT are present, +# then the behavior is as if ALL were specified. +# +# EVIDENCE-OF: R-14442-41305 If the simple SELECT is a SELECT DISTINCT, +# then duplicate rows are removed from the set of result rows before it +# is returned. +# +# The three testable statements above are tested by e_select-5.2.*, +# 5.3.* and 5.4.* respectively. +# +do_select_tests e_select-5 { + 3.1 "SELECT ALL x FROM h2" {One Two Three Four one two three four} + 3.2 "SELECT ALL x FROM h1, h2 ON (x=b)" {One one Four four} + + 3.1 "SELECT x FROM h2" {One Two Three Four one two three four} + 3.2 "SELECT x FROM h1, h2 ON (x=b)" {One one Four four} + + 4.1 "SELECT DISTINCT x FROM h2" {One Two Three Four} + 4.2 "SELECT DISTINCT x FROM h1, h2 ON (x=b)" {One Four} +} + +# EVIDENCE-OF: R-02054-15343 For the purposes of detecting duplicate +# rows, two NULL values are considered to be equal. +# +do_select_tests e_select-5.5 { + 1 "SELECT DISTINCT d FROM h3" {{} 2 2,3 2,4 3} +} + +# EVIDENCE-OF: R-58359-52112 The normal rules for selecting a collation +# sequence to compare text values with apply. +# +do_select_tests e_select-5.6 { + 1 "SELECT DISTINCT b FROM h1" {one I i four IV iv} + 2 "SELECT DISTINCT b COLLATE nocase FROM h1" {one I four IV} + 3 "SELECT DISTINCT x FROM h2" {One Two Three Four} + 4 "SELECT DISTINCT x COLLATE binary FROM h2" { + One Two Three Four one two three four + } +} + +#------------------------------------------------------------------------- +# The following tests - e_select-7.* - test that statements made to do +# with compound SELECT statements are correct. +# + +# EVIDENCE-OF: R-39368-64333 In a compound SELECT, all the constituent +# SELECTs must return the same number of result columns. +# +# All the other tests in this section use compound SELECTs created +# using component SELECTs that do return the same number of columns. +# So the tests here just show that it is an error to attempt otherwise. +# +drop_all_tables +do_execsql_test e_select-7.1.0 { + CREATE TABLE j1(a, b, c); + CREATE TABLE j2(e, f); + CREATE TABLE j3(g); +} {} +do_select_tests e_select-7.1 -error { + SELECTs to the left and right of %s do not have the same number of result columns +} { + 1 "SELECT a, b FROM j1 UNION ALL SELECT g FROM j3" {{UNION ALL}} + 2 "SELECT * FROM j1 UNION ALL SELECT * FROM j3" {{UNION ALL}} + 3 "SELECT a, b FROM j1 UNION ALL SELECT g FROM j3" {{UNION ALL}} + 4 "SELECT a, b FROM j1 UNION ALL SELECT * FROM j3,j2" {{UNION ALL}} + 5 "SELECT * FROM j3,j2 UNION ALL SELECT a, b FROM j1" {{UNION ALL}} + + 6 "SELECT a, b FROM j1 UNION SELECT g FROM j3" {UNION} + 7 "SELECT * FROM j1 UNION SELECT * FROM j3" {UNION} + 8 "SELECT a, b FROM j1 UNION SELECT g FROM j3" {UNION} + 9 "SELECT a, b FROM j1 UNION SELECT * FROM j3,j2" {UNION} + 10 "SELECT * FROM j3,j2 UNION SELECT a, b FROM j1" {UNION} + + 11 "SELECT a, b FROM j1 INTERSECT SELECT g FROM j3" {INTERSECT} + 12 "SELECT * FROM j1 INTERSECT SELECT * FROM j3" {INTERSECT} + 13 "SELECT a, b FROM j1 INTERSECT SELECT g FROM j3" {INTERSECT} + 14 "SELECT a, b FROM j1 INTERSECT SELECT * FROM j3,j2" {INTERSECT} + 15 "SELECT * FROM j3,j2 INTERSECT SELECT a, b FROM j1" {INTERSECT} + + 16 "SELECT a, b FROM j1 EXCEPT SELECT g FROM j3" {EXCEPT} + 17 "SELECT * FROM j1 EXCEPT SELECT * FROM j3" {EXCEPT} + 18 "SELECT a, b FROM j1 EXCEPT SELECT g FROM j3" {EXCEPT} + 19 "SELECT a, b FROM j1 EXCEPT SELECT * FROM j3,j2" {EXCEPT} + 20 "SELECT * FROM j3,j2 EXCEPT SELECT a, b FROM j1" {EXCEPT} +} + +# EVIDENCE-OF: R-01450-11152 As the components of a compound SELECT must +# be simple SELECT statements, they may not contain ORDER BY or LIMIT +# clauses. +# +foreach {tn select op1 op2} { + 1 "SELECT * FROM j1 ORDER BY a UNION ALL SELECT * FROM j2,j3" + {ORDER BY} {UNION ALL} + 2 "SELECT count(*) FROM j1 ORDER BY 1 UNION ALL SELECT max(e) FROM j2" + {ORDER BY} {UNION ALL} + 3 "SELECT count(*), * FROM j1 ORDER BY 1,2,3 UNION ALL SELECT *,* FROM j2" + {ORDER BY} {UNION ALL} + 4 "SELECT * FROM j1 LIMIT 10 UNION ALL SELECT * FROM j2,j3" + LIMIT {UNION ALL} + 5 "SELECT * FROM j1 LIMIT 10 OFFSET 5 UNION ALL SELECT * FROM j2,j3" + LIMIT {UNION ALL} + 6 "SELECT a FROM j1 LIMIT (SELECT e FROM j2) UNION ALL SELECT g FROM j2,j3" + LIMIT {UNION ALL} + + 7 "SELECT * FROM j1 ORDER BY a UNION SELECT * FROM j2,j3" + {ORDER BY} {UNION} + 8 "SELECT count(*) FROM j1 ORDER BY 1 UNION SELECT max(e) FROM j2" + {ORDER BY} {UNION} + 9 "SELECT count(*), * FROM j1 ORDER BY 1,2,3 UNION SELECT *,* FROM j2" + {ORDER BY} {UNION} + 10 "SELECT * FROM j1 LIMIT 10 UNION SELECT * FROM j2,j3" + LIMIT {UNION} + 11 "SELECT * FROM j1 LIMIT 10 OFFSET 5 UNION SELECT * FROM j2,j3" + LIMIT {UNION} + 12 "SELECT a FROM j1 LIMIT (SELECT e FROM j2) UNION SELECT g FROM j2,j3" + LIMIT {UNION} + + 13 "SELECT * FROM j1 ORDER BY a EXCEPT SELECT * FROM j2,j3" + {ORDER BY} {EXCEPT} + 14 "SELECT count(*) FROM j1 ORDER BY 1 EXCEPT SELECT max(e) FROM j2" + {ORDER BY} {EXCEPT} + 15 "SELECT count(*), * FROM j1 ORDER BY 1,2,3 EXCEPT SELECT *,* FROM j2" + {ORDER BY} {EXCEPT} + 16 "SELECT * FROM j1 LIMIT 10 EXCEPT SELECT * FROM j2,j3" + LIMIT {EXCEPT} + 17 "SELECT * FROM j1 LIMIT 10 OFFSET 5 EXCEPT SELECT * FROM j2,j3" + LIMIT {EXCEPT} + 18 "SELECT a FROM j1 LIMIT (SELECT e FROM j2) EXCEPT SELECT g FROM j2,j3" + LIMIT {EXCEPT} + + 19 "SELECT * FROM j1 ORDER BY a INTERSECT SELECT * FROM j2,j3" + {ORDER BY} {INTERSECT} + 20 "SELECT count(*) FROM j1 ORDER BY 1 INTERSECT SELECT max(e) FROM j2" + {ORDER BY} {INTERSECT} + 21 "SELECT count(*), * FROM j1 ORDER BY 1,2,3 INTERSECT SELECT *,* FROM j2" + {ORDER BY} {INTERSECT} + 22 "SELECT * FROM j1 LIMIT 10 INTERSECT SELECT * FROM j2,j3" + LIMIT {INTERSECT} + 23 "SELECT * FROM j1 LIMIT 10 OFFSET 5 INTERSECT SELECT * FROM j2,j3" + LIMIT {INTERSECT} + 24 "SELECT a FROM j1 LIMIT (SELECT e FROM j2) INTERSECT SELECT g FROM j2,j3" + LIMIT {INTERSECT} +} { + set err "$op1 clause should come after $op2 not before" + do_catchsql_test e_select-7.2.$tn $select [list 1 $err] +} + +# EVIDENCE-OF: R-22874-32655 ORDER BY and LIMIT clauses may only occur +# at the end of the entire compound SELECT. +# +foreach {tn select} { + 1 "SELECT * FROM j1 UNION ALL SELECT * FROM j2,j3 ORDER BY a" + 2 "SELECT count(*) FROM j1 UNION ALL SELECT max(e) FROM j2 ORDER BY 1" + 3 "SELECT count(*), * FROM j1 UNION ALL SELECT *,* FROM j2 ORDER BY 1,2,3" + 4 "SELECT * FROM j1 UNION ALL SELECT * FROM j2,j3 LIMIT 10" + 5 "SELECT * FROM j1 UNION ALL SELECT * FROM j2,j3 LIMIT 10 OFFSET 5" + 6 "SELECT a FROM j1 UNION ALL SELECT g FROM j2,j3 LIMIT (SELECT 10)" + + 7 "SELECT * FROM j1 UNION SELECT * FROM j2,j3 ORDER BY a" + 8 "SELECT count(*) FROM j1 UNION SELECT max(e) FROM j2 ORDER BY 1" + 9 "SELECT count(*), * FROM j1 UNION SELECT *,* FROM j2 ORDER BY 1,2,3" + 10 "SELECT * FROM j1 UNION SELECT * FROM j2,j3 LIMIT 10" + 11 "SELECT * FROM j1 UNION SELECT * FROM j2,j3 LIMIT 10 OFFSET 5" + 12 "SELECT a FROM j1 UNION SELECT g FROM j2,j3 LIMIT (SELECT 10)" + + 13 "SELECT * FROM j1 EXCEPT SELECT * FROM j2,j3 ORDER BY a" + 14 "SELECT count(*) FROM j1 EXCEPT SELECT max(e) FROM j2 ORDER BY 1" + 15 "SELECT count(*), * FROM j1 EXCEPT SELECT *,* FROM j2 ORDER BY 1,2,3" + 16 "SELECT * FROM j1 EXCEPT SELECT * FROM j2,j3 LIMIT 10" + 17 "SELECT * FROM j1 EXCEPT SELECT * FROM j2,j3 LIMIT 10 OFFSET 5" + 18 "SELECT a FROM j1 EXCEPT SELECT g FROM j2,j3 LIMIT (SELECT 10)" + + 19 "SELECT * FROM j1 INTERSECT SELECT * FROM j2,j3 ORDER BY a" + 20 "SELECT count(*) FROM j1 INTERSECT SELECT max(e) FROM j2 ORDER BY 1" + 21 "SELECT count(*), * FROM j1 INTERSECT SELECT *,* FROM j2 ORDER BY 1,2,3" + 22 "SELECT * FROM j1 INTERSECT SELECT * FROM j2,j3 LIMIT 10" + 23 "SELECT * FROM j1 INTERSECT SELECT * FROM j2,j3 LIMIT 10 OFFSET 5" + 24 "SELECT a FROM j1 INTERSECT SELECT g FROM j2,j3 LIMIT (SELECT 10)" +} { + do_test e_select-7.3.$tn { catch {execsql $select} msg } 0 +} + +# EVIDENCE-OF: R-08531-36543 A compound SELECT created using UNION ALL +# operator returns all the rows from the SELECT to the left of the UNION +# ALL operator, and all the rows from the SELECT to the right of it. +# +drop_all_tables +do_execsql_test e_select-7.4.0 { + CREATE TABLE q1(a TEXT, b INTEGER, c); + CREATE TABLE q2(d NUMBER, e BLOB); + CREATE TABLE q3(f REAL, g); + + INSERT INTO q1 VALUES(16, -87.66, NULL); + INSERT INTO q1 VALUES('legible', 94, -42.47); + INSERT INTO q1 VALUES('beauty', 36, NULL); + + INSERT INTO q2 VALUES('legible', 1); + INSERT INTO q2 VALUES('beauty', 2); + INSERT INTO q2 VALUES(-65.91, 4); + INSERT INTO q2 VALUES('emanating', -16.56); + + INSERT INTO q3 VALUES('beauty', 2); + INSERT INTO q3 VALUES('beauty', 2); +} {} +do_select_tests e_select-7.4 { + 1 {SELECT a FROM q1 UNION ALL SELECT d FROM q2} + {16 legible beauty legible beauty -65.91 emanating} + + 2 {SELECT * FROM q1 WHERE a=16 UNION ALL SELECT 'x', * FROM q2 WHERE oid=1} + {16 -87.66 {} x legible 1} + + 3 {SELECT count(*) FROM q1 UNION ALL SELECT min(e) FROM q2} + {3 -16.56} + + 4 {SELECT * FROM q2 UNION ALL SELECT * FROM q3} + {legible 1 beauty 2 -65.91 4 emanating -16.56 beauty 2 beauty 2} +} + +# EVIDENCE-OF: R-20560-39162 The UNION operator works the same way as +# UNION ALL, except that duplicate rows are removed from the final +# result set. +# +do_select_tests e_select-7.5 { + 1 {SELECT a FROM q1 UNION SELECT d FROM q2} + {-65.91 16 beauty emanating legible} + + 2 {SELECT * FROM q1 WHERE a=16 UNION SELECT 'x', * FROM q2 WHERE oid=1} + {16 -87.66 {} x legible 1} + + 3 {SELECT count(*) FROM q1 UNION SELECT min(e) FROM q2} + {-16.56 3} + + 4 {SELECT * FROM q2 UNION SELECT * FROM q3} + {-65.91 4 beauty 2 emanating -16.56 legible 1} +} + +# EVIDENCE-OF: R-45764-31737 The INTERSECT operator returns the +# intersection of the results of the left and right SELECTs. +# +do_select_tests e_select-7.6 { + 1 {SELECT a FROM q1 INTERSECT SELECT d FROM q2} {beauty legible} + 2 {SELECT * FROM q2 INTERSECT SELECT * FROM q3} {beauty 2} +} + +# EVIDENCE-OF: R-25787-28949 The EXCEPT operator returns the subset of +# rows returned by the left SELECT that are not also returned by the +# right-hand SELECT. +# +do_select_tests e_select-7.7 { + 1 {SELECT a FROM q1 EXCEPT SELECT d FROM q2} {16} + + 2 {SELECT * FROM q2 EXCEPT SELECT * FROM q3} + {-65.91 4 emanating -16.56 legible 1} +} + +# EVIDENCE-OF: R-40729-56447 Duplicate rows are removed from the results +# of INTERSECT and EXCEPT operators before the result set is returned. +# +do_select_tests e_select-7.8 { + 0 {SELECT * FROM q3} {beauty 2 beauty 2} + + 1 {SELECT * FROM q3 INTERSECT SELECT * FROM q3} {beauty 2} + 2 {SELECT * FROM q3 EXCEPT SELECT a,b FROM q1} {beauty 2} +} + +# EVIDENCE-OF: R-46765-43362 For the purposes of determining duplicate +# rows for the results of compound SELECT operators, NULL values are +# considered equal to other NULL values and distinct from all non-NULL +# values. +# +db nullvalue null +do_select_tests e_select-7.9 { + 1 {SELECT NULL UNION ALL SELECT NULL} {null null} + 2 {SELECT NULL UNION SELECT NULL} {null} + 3 {SELECT NULL INTERSECT SELECT NULL} {null} + 4 {SELECT NULL EXCEPT SELECT NULL} {} + + 5 {SELECT NULL UNION ALL SELECT 'ab'} {null ab} + 6 {SELECT NULL UNION SELECT 'ab'} {null ab} + 7 {SELECT NULL INTERSECT SELECT 'ab'} {} + 8 {SELECT NULL EXCEPT SELECT 'ab'} {null} + + 9 {SELECT NULL UNION ALL SELECT 0} {null 0} + 10 {SELECT NULL UNION SELECT 0} {null 0} + 11 {SELECT NULL INTERSECT SELECT 0} {} + 12 {SELECT NULL EXCEPT SELECT 0} {null} + + 13 {SELECT c FROM q1 UNION ALL SELECT g FROM q3} {null -42.47 null 2 2} + 14 {SELECT c FROM q1 UNION SELECT g FROM q3} {null -42.47 2} + 15 {SELECT c FROM q1 INTERSECT SELECT g FROM q3} {} + 16 {SELECT c FROM q1 EXCEPT SELECT g FROM q3} {null -42.47} +} +db nullvalue {} + +# EVIDENCE-OF: R-51232-50224 The collation sequence used to compare two +# text values is determined as if the columns of the left and right-hand +# SELECT statements were the left and right-hand operands of the equals +# (=) operator, except that greater precedence is not assigned to a +# collation sequence specified with the postfix COLLATE operator. +# +drop_all_tables +do_execsql_test e_select-7.10.0 { + CREATE TABLE y1(a COLLATE nocase, b COLLATE binary, c); + INSERT INTO y1 VALUES('Abc', 'abc', 'aBC'); +} {} +do_select_tests e_select-7.10 { + 1 {SELECT 'abc' UNION SELECT 'ABC'} {ABC abc} + 2 {SELECT 'abc' COLLATE nocase UNION SELECT 'ABC'} {ABC} + 3 {SELECT 'abc' UNION SELECT 'ABC' COLLATE nocase} {ABC} + 4 {SELECT 'abc' COLLATE binary UNION SELECT 'ABC' COLLATE nocase} {ABC abc} + 5 {SELECT 'abc' COLLATE nocase UNION SELECT 'ABC' COLLATE binary} {ABC} + + 6 {SELECT a FROM y1 UNION SELECT b FROM y1} {abc} + 7 {SELECT b FROM y1 UNION SELECT a FROM y1} {Abc abc} + 8 {SELECT a FROM y1 UNION SELECT c FROM y1} {aBC} + + 9 {SELECT a FROM y1 UNION SELECT c COLLATE binary FROM y1} {aBC} +} + +# EVIDENCE-OF: R-32706-07403 No affinity transformations are applied to +# any values when comparing rows as part of a compound SELECT. +# +drop_all_tables +do_execsql_test e_select-7.10.0 { + CREATE TABLE w1(a TEXT, b NUMBER); + CREATE TABLE w2(a, b TEXT); + + INSERT INTO w1 VALUES('1', 4.1); + INSERT INTO w2 VALUES(1, 4.1); +} {} + +do_select_tests e_select-7.11 { + 1 { SELECT a FROM w1 UNION SELECT a FROM w2 } {1 1} + 2 { SELECT a FROM w2 UNION SELECT a FROM w1 } {1 1} + 3 { SELECT b FROM w1 UNION SELECT b FROM w2 } {4.1 4.1} + 4 { SELECT b FROM w2 UNION SELECT b FROM w1 } {4.1 4.1} + + 5 { SELECT a FROM w1 INTERSECT SELECT a FROM w2 } {} + 6 { SELECT a FROM w2 INTERSECT SELECT a FROM w1 } {} + 7 { SELECT b FROM w1 INTERSECT SELECT b FROM w2 } {} + 8 { SELECT b FROM w2 INTERSECT SELECT b FROM w1 } {} + + 9 { SELECT a FROM w1 EXCEPT SELECT a FROM w2 } {1} + 10 { SELECT a FROM w2 EXCEPT SELECT a FROM w1 } {1} + 11 { SELECT b FROM w1 EXCEPT SELECT b FROM w2 } {4.1} + 12 { SELECT b FROM w2 EXCEPT SELECT b FROM w1 } {4.1} +} + + +# EVIDENCE-OF: R-32562-20566 When three or more simple SELECTs are +# connected into a compound SELECT, they group from left to right. In +# other words, if "A", "B" and "C" are all simple SELECT statements, (A +# op B op C) is processed as ((A op B) op C). +# +# e_select-7.12.1: Precedence of UNION vs. INTERSECT +# e_select-7.12.2: Precedence of UNION vs. UNION ALL +# e_select-7.12.3: Precedence of UNION vs. EXCEPT +# e_select-7.12.4: Precedence of INTERSECT vs. UNION ALL +# e_select-7.12.5: Precedence of INTERSECT vs. EXCEPT +# e_select-7.12.6: Precedence of UNION ALL vs. EXCEPT +# e_select-7.12.7: Check that "a EXCEPT b EXCEPT c" is processed as +# "(a EXCEPT b) EXCEPT c". +# +# The INTERSECT and EXCEPT operations are mutually commutative. So +# the e_select-7.12.5 test cases do not prove very much. +# +drop_all_tables +do_execsql_test e_select-7.12.0 { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); +} {} +foreach {tn select res} { + 1a "(1,2) INTERSECT (1) UNION (3)" {1 3} + 1b "(3) UNION (1,2) INTERSECT (1)" {1} + + 2a "(1,2) UNION (3) UNION ALL (1)" {1 2 3 1} + 2b "(1) UNION ALL (3) UNION (1,2)" {1 2 3} + + 3a "(1,2) UNION (3) EXCEPT (1)" {2 3} + 3b "(1,2) EXCEPT (3) UNION (1)" {1 2} + + 4a "(1,2) INTERSECT (1) UNION ALL (3)" {1 3} + 4b "(3) UNION (1,2) INTERSECT (1)" {1} + + 5a "(1,2) INTERSECT (2) EXCEPT (2)" {} + 5b "(2,3) EXCEPT (2) INTERSECT (2)" {} + + 6a "(2) UNION ALL (2) EXCEPT (2)" {} + 6b "(2) EXCEPT (2) UNION ALL (2)" {2} + + 7 "(2,3) EXCEPT (2) EXCEPT (3)" {} +} { + set select [string map {( {SELECT x FROM t1 WHERE x IN (}} $select] + do_execsql_test e_select-7.12.$tn $select [list {*}$res] +} + + +#------------------------------------------------------------------------- +# ORDER BY clauses +# + +drop_all_tables +do_execsql_test e_select-8.1.0 { + CREATE TABLE d1(x, y, z); + + INSERT INTO d1 VALUES(1, 2, 3); + INSERT INTO d1 VALUES(2, 5, -1); + INSERT INTO d1 VALUES(1, 2, 8); + INSERT INTO d1 VALUES(1, 2, 7); + INSERT INTO d1 VALUES(2, 4, 93); + INSERT INTO d1 VALUES(1, 2, -20); + INSERT INTO d1 VALUES(1, 4, 93); + INSERT INTO d1 VALUES(1, 5, -1); + + CREATE TABLE d2(a, b); + INSERT INTO d2 VALUES('gently', 'failings'); + INSERT INTO d2 VALUES('commercials', 'bathrobe'); + INSERT INTO d2 VALUES('iterate', 'sexton'); + INSERT INTO d2 VALUES('babied', 'charitableness'); + INSERT INTO d2 VALUES('solemnness', 'annexed'); + INSERT INTO d2 VALUES('rejoicing', 'liabilities'); + INSERT INTO d2 VALUES('pragmatist', 'guarded'); + INSERT INTO d2 VALUES('barked', 'interrupted'); + INSERT INTO d2 VALUES('reemphasizes', 'reply'); + INSERT INTO d2 VALUES('lad', 'relenting'); +} {} + +# EVIDENCE-OF: R-44988-41064 Rows are first sorted based on the results +# of evaluating the left-most expression in the ORDER BY list, then ties +# are broken by evaluating the second left-most expression and so on. +# +do_select_tests e_select-8.1 { + 1 "SELECT * FROM d1 ORDER BY x, y, z" { + 1 2 -20 1 2 3 1 2 7 1 2 8 + 1 4 93 1 5 -1 2 4 93 2 5 -1 + } +} + +# EVIDENCE-OF: R-06617-54588 Each ORDER BY expression may be optionally +# followed by one of the keywords ASC (smaller values are returned +# first) or DESC (larger values are returned first). +# +# Test cases e_select-8.2.* test the above. +# +# EVIDENCE-OF: R-18705-33393 If neither ASC or DESC are specified, rows +# are sorted in ascending (smaller values first) order by default. +# +# Test cases e_select-8.3.* test the above. All 8.3 test cases are +# copies of 8.2 test cases with the explicit "ASC" removed. +# +do_select_tests e_select-8 { + 2.1 "SELECT * FROM d1 ORDER BY x ASC, y ASC, z ASC" { + 1 2 -20 1 2 3 1 2 7 1 2 8 + 1 4 93 1 5 -1 2 4 93 2 5 -1 + } + 2.2 "SELECT * FROM d1 ORDER BY x DESC, y DESC, z DESC" { + 2 5 -1 2 4 93 1 5 -1 1 4 93 + 1 2 8 1 2 7 1 2 3 1 2 -20 + } + 2.3 "SELECT * FROM d1 ORDER BY x DESC, y ASC, z DESC" { + 2 4 93 2 5 -1 1 2 8 1 2 7 + 1 2 3 1 2 -20 1 4 93 1 5 -1 + } + 2.4 "SELECT * FROM d1 ORDER BY x DESC, y ASC, z ASC" { + 2 4 93 2 5 -1 1 2 -20 1 2 3 + 1 2 7 1 2 8 1 4 93 1 5 -1 + } + + 3.1 "SELECT * FROM d1 ORDER BY x, y, z" { + 1 2 -20 1 2 3 1 2 7 1 2 8 + 1 4 93 1 5 -1 2 4 93 2 5 -1 + } + 3.3 "SELECT * FROM d1 ORDER BY x DESC, y, z DESC" { + 2 4 93 2 5 -1 1 2 8 1 2 7 + 1 2 3 1 2 -20 1 4 93 1 5 -1 + } + 3.4 "SELECT * FROM d1 ORDER BY x DESC, y, z" { + 2 4 93 2 5 -1 1 2 -20 1 2 3 + 1 2 7 1 2 8 1 4 93 1 5 -1 + } +} + +# EVIDENCE-OF: R-29779-04281 If the ORDER BY expression is a constant +# integer K then the expression is considered an alias for the K-th +# column of the result set (columns are numbered from left to right +# starting with 1). +# +do_select_tests e_select-8.4 { + 1 "SELECT * FROM d1 ORDER BY 1 ASC, 2 ASC, 3 ASC" { + 1 2 -20 1 2 3 1 2 7 1 2 8 + 1 4 93 1 5 -1 2 4 93 2 5 -1 + } + 2 "SELECT * FROM d1 ORDER BY 1 DESC, 2 DESC, 3 DESC" { + 2 5 -1 2 4 93 1 5 -1 1 4 93 + 1 2 8 1 2 7 1 2 3 1 2 -20 + } + 3 "SELECT * FROM d1 ORDER BY 1 DESC, 2 ASC, 3 DESC" { + 2 4 93 2 5 -1 1 2 8 1 2 7 + 1 2 3 1 2 -20 1 4 93 1 5 -1 + } + 4 "SELECT * FROM d1 ORDER BY 1 DESC, 2 ASC, 3 ASC" { + 2 4 93 2 5 -1 1 2 -20 1 2 3 + 1 2 7 1 2 8 1 4 93 1 5 -1 + } + 5 "SELECT * FROM d1 ORDER BY 1, 2, 3" { + 1 2 -20 1 2 3 1 2 7 1 2 8 + 1 4 93 1 5 -1 2 4 93 2 5 -1 + } + 6 "SELECT * FROM d1 ORDER BY 1 DESC, 2, 3 DESC" { + 2 4 93 2 5 -1 1 2 8 1 2 7 + 1 2 3 1 2 -20 1 4 93 1 5 -1 + } + 7 "SELECT * FROM d1 ORDER BY 1 DESC, 2, 3" { + 2 4 93 2 5 -1 1 2 -20 1 2 3 + 1 2 7 1 2 8 1 4 93 1 5 -1 + } + 8 "SELECT z, x FROM d1 ORDER BY 2" { + /# 1 # 1 # 1 # 1 + # 1 # 1 # 2 # 2/ + } + 9 "SELECT z, x FROM d1 ORDER BY 1" { + /-20 1 -1 # -1 # 3 1 + 7 1 8 1 93 # 93 #/ + } +} + +# EVIDENCE-OF: R-63286-51977 If the ORDER BY expression is an identifier +# that corresponds to the alias of one of the output columns, then the +# expression is considered an alias for that column. +# +do_select_tests e_select-8.5 { + 1 "SELECT z+1 AS abc FROM d1 ORDER BY abc" { + -19 0 0 4 8 9 94 94 + } + 2 "SELECT z+1 AS abc FROM d1 ORDER BY abc DESC" { + 94 94 9 8 4 0 0 -19 + } + 3 "SELECT z AS x, x AS z FROM d1 ORDER BY z" { + /# 1 # 1 # 1 # 1 # 1 # 1 # 2 # 2/ + } + 4 "SELECT z AS x, x AS z FROM d1 ORDER BY x" { + /-20 1 -1 # -1 # 3 1 7 1 8 1 93 # 93 #/ + } +} + +# EVIDENCE-OF: R-65068-27207 Otherwise, if the ORDER BY expression is +# any other expression, it is evaluated and the returned value used to +# order the output rows. +# +# EVIDENCE-OF: R-03421-57988 If the SELECT statement is a simple SELECT, +# then an ORDER BY may contain any arbitrary expressions. +# +do_select_tests e_select-8.6 { + 1 "SELECT * FROM d1 ORDER BY x+y+z" { + 1 2 -20 1 5 -1 1 2 3 2 5 -1 + 1 2 7 1 2 8 1 4 93 2 4 93 + } + 2 "SELECT * FROM d1 ORDER BY x*z" { + 1 2 -20 2 5 -1 1 5 -1 1 2 3 + 1 2 7 1 2 8 1 4 93 2 4 93 + } + 3 "SELECT * FROM d1 ORDER BY y*z" { + 1 2 -20 2 5 -1 1 5 -1 1 2 3 + 1 2 7 1 2 8 2 4 93 1 4 93 + } +} + +# EVIDENCE-OF: R-28853-08147 However, if the SELECT is a compound +# SELECT, then ORDER BY expressions that are not aliases to output +# columns must be exactly the same as an expression used as an output +# column. +# +do_select_tests e_select-8.7.1 -error { + %s ORDER BY term does not match any column in the result set +} { + 1 "SELECT x FROM d1 UNION ALL SELECT a FROM d2 ORDER BY x*z" 1st + 2 "SELECT x,z FROM d1 UNION ALL SELECT a,b FROM d2 ORDER BY x, x/z" 2nd +} + +do_select_tests e_select-8.7.2 { + 1 "SELECT x*z FROM d1 UNION ALL SELECT a FROM d2 ORDER BY x*z" { + -20 -2 -1 3 7 8 93 186 babied barked commercials gently + iterate lad pragmatist reemphasizes rejoicing solemnness + } + 2 "SELECT x, x/z FROM d1 UNION ALL SELECT a,b FROM d2 ORDER BY x, x/z" { + 1 -1 1 0 1 0 1 0 1 0 1 0 2 -2 2 0 + babied charitableness barked interrupted commercials bathrobe gently + failings iterate sexton lad relenting pragmatist guarded reemphasizes reply + rejoicing liabilities solemnness annexed + } +} + +do_execsql_test e_select-8.8.0 { + CREATE TABLE d3(a); + INSERT INTO d3 VALUES('text'); + INSERT INTO d3 VALUES(14.1); + INSERT INTO d3 VALUES(13); + INSERT INTO d3 VALUES(X'78787878'); + INSERT INTO d3 VALUES(15); + INSERT INTO d3 VALUES(12.9); + INSERT INTO d3 VALUES(null); + + CREATE TABLE d4(x COLLATE nocase); + INSERT INTO d4 VALUES('abc'); + INSERT INTO d4 VALUES('ghi'); + INSERT INTO d4 VALUES('DEF'); + INSERT INTO d4 VALUES('JKL'); +} {} + +# EVIDENCE-OF: R-10883-17697 For the purposes of sorting rows, values +# are compared in the same way as for comparison expressions. +# +# The following tests verify that values of different types are sorted +# correctly, and that mixed real and integer values are compared properly. +# +do_execsql_test e_select-8.8.1 { + SELECT a FROM d3 ORDER BY a +} {{} 12.9 13 14.1 15 text xxxx} +do_execsql_test e_select-8.8.2 { + SELECT a FROM d3 ORDER BY a DESC +} {xxxx text 15 14.1 13 12.9 {}} + + +# EVIDENCE-OF: R-64199-22471 If the ORDER BY expression is assigned a +# collation sequence using the postfix COLLATE operator, then the +# specified collation sequence is used. +# +do_execsql_test e_select-8.9.1 { + SELECT x FROM d4 ORDER BY 1 COLLATE binary +} {DEF JKL abc ghi} +do_execsql_test e_select-8.9.2 { + SELECT x COLLATE binary FROM d4 ORDER BY 1 COLLATE nocase +} {abc DEF ghi JKL} + +# EVIDENCE-OF: R-09398-26102 Otherwise, if the ORDER BY expression is +# an alias to an expression that has been assigned a collation sequence +# using the postfix COLLATE operator, then the collation sequence +# assigned to the aliased expression is used. +# +# In the test 8.10.2, the only result-column expression has no alias. So the +# ORDER BY expression is not a reference to it and therefore does not inherit +# the collation sequence. In test 8.10.3, "x" is the alias (as well as the +# column name), so the ORDER BY expression is interpreted as an alias and the +# collation sequence attached to the result column is used for sorting. +# +do_execsql_test e_select-8.10.1 { + SELECT x COLLATE binary FROM d4 ORDER BY 1 +} {DEF JKL abc ghi} +do_execsql_test e_select-8.10.2 { + SELECT x COLLATE binary FROM d4 ORDER BY x +} {abc DEF ghi JKL} +do_execsql_test e_select-8.10.3 { + SELECT x COLLATE binary AS x FROM d4 ORDER BY x +} {DEF JKL abc ghi} + +# EVIDENCE-OF: R-27301-09658 Otherwise, if the ORDER BY expression is a +# column or an alias of an expression that is a column, then the default +# collation sequence for the column is used. +# +do_execsql_test e_select-8.11.1 { + SELECT x AS y FROM d4 ORDER BY y +} {abc DEF ghi JKL} +do_execsql_test e_select-8.11.2 { + SELECT x||'' FROM d4 ORDER BY x +} {abc DEF ghi JKL} + +# EVIDENCE-OF: R-49925-55905 Otherwise, the BINARY collation sequence is +# used. +# +do_execsql_test e_select-8.12.1 { + SELECT x FROM d4 ORDER BY x||'' +} {DEF JKL abc ghi} + +# EVIDENCE-OF: R-44130-32593 If an ORDER BY expression is not an integer +# alias, then SQLite searches the left-most SELECT in the compound for a +# result column that matches either the second or third rules above. If +# a match is found, the search stops and the expression is handled as an +# alias for the result column that it has been matched against. +# Otherwise, the next SELECT to the right is tried, and so on. +# +do_execsql_test e_select-8.13.0 { + CREATE TABLE d5(a, b); + CREATE TABLE d6(c, d); + CREATE TABLE d7(e, f); + + INSERT INTO d5 VALUES(1, 'f'); + INSERT INTO d6 VALUES(2, 'e'); + INSERT INTO d7 VALUES(3, 'd'); + INSERT INTO d5 VALUES(4, 'c'); + INSERT INTO d6 VALUES(5, 'b'); + INSERT INTO d7 VALUES(6, 'a'); + + CREATE TABLE d8(x COLLATE nocase); + CREATE TABLE d9(y COLLATE nocase); + + INSERT INTO d8 VALUES('a'); + INSERT INTO d9 VALUES('B'); + INSERT INTO d8 VALUES('c'); + INSERT INTO d9 VALUES('D'); +} {} +do_select_tests e_select-8.13 { + 1 { SELECT a FROM d5 UNION ALL SELECT c FROM d6 UNION ALL SELECT e FROM d7 + ORDER BY a + } {1 2 3 4 5 6} + 2 { SELECT a FROM d5 UNION ALL SELECT c FROM d6 UNION ALL SELECT e FROM d7 + ORDER BY c + } {1 2 3 4 5 6} + 3 { SELECT a FROM d5 UNION ALL SELECT c FROM d6 UNION ALL SELECT e FROM d7 + ORDER BY e + } {1 2 3 4 5 6} + 4 { SELECT a FROM d5 UNION ALL SELECT c FROM d6 UNION ALL SELECT e FROM d7 + ORDER BY 1 + } {1 2 3 4 5 6} + + 5 { SELECT a, b FROM d5 UNION ALL SELECT b, a FROM d5 ORDER BY b } + {f 1 c 4 4 c 1 f} + 6 { SELECT a, b FROM d5 UNION ALL SELECT b, a FROM d5 ORDER BY 2 } + {f 1 c 4 4 c 1 f} + + 7 { SELECT a, b FROM d5 UNION ALL SELECT b, a FROM d5 ORDER BY a } + {1 f 4 c c 4 f 1} + 8 { SELECT a, b FROM d5 UNION ALL SELECT b, a FROM d5 ORDER BY 1 } + {1 f 4 c c 4 f 1} + + 9 { SELECT a, b FROM d5 UNION ALL SELECT b, a+1 FROM d5 ORDER BY a+1 } + {f 2 c 5 4 c 1 f} + 10 { SELECT a, b FROM d5 UNION ALL SELECT b, a+1 FROM d5 ORDER BY 2 } + {f 2 c 5 4 c 1 f} + + 11 { SELECT a+1, b FROM d5 UNION ALL SELECT b, a+1 FROM d5 ORDER BY a+1 } + {2 f 5 c c 5 f 2} + 12 { SELECT a+1, b FROM d5 UNION ALL SELECT b, a+1 FROM d5 ORDER BY 1 } + {2 f 5 c c 5 f 2} +} + +# EVIDENCE-OF: R-39265-04070 If no matching expression can be found in +# the result columns of any constituent SELECT, it is an error. +# +do_select_tests e_select-8.14 -error { + %s ORDER BY term does not match any column in the result set +} { + 1 { SELECT a FROM d5 UNION SELECT c FROM d6 ORDER BY a+1 } 1st + 2 { SELECT a FROM d5 UNION SELECT c FROM d6 ORDER BY a, a+1 } 2nd + 3 { SELECT * FROM d5 INTERSECT SELECT * FROM d6 ORDER BY 'hello' } 1st + 4 { SELECT * FROM d5 INTERSECT SELECT * FROM d6 ORDER BY blah } 1st + 5 { SELECT * FROM d5 INTERSECT SELECT * FROM d6 ORDER BY c,d,c+d } 3rd + 6 { SELECT * FROM d5 EXCEPT SELECT * FROM d7 ORDER BY 1,2,b,a/b } 4th +} + +# EVIDENCE-OF: R-03407-11483 Each term of the ORDER BY clause is +# processed separately and may be matched against result columns from +# different SELECT statements in the compound. +# +do_select_tests e_select-8.15 { + 1 { SELECT a, b FROM d5 UNION ALL SELECT c-1, d FROM d6 ORDER BY a, d } + {1 e 1 f 4 b 4 c} + 2 { SELECT a, b FROM d5 UNION ALL SELECT c-1, d FROM d6 ORDER BY c-1, b } + {1 e 1 f 4 b 4 c} + 3 { SELECT a, b FROM d5 UNION ALL SELECT c-1, d FROM d6 ORDER BY 1, 2 } + {1 e 1 f 4 b 4 c} +} + + +#------------------------------------------------------------------------- +# Tests related to statements made about the LIMIT/OFFSET clause. +# +do_execsql_test e_select-9.0 { + CREATE TABLE f1(a, b); + INSERT INTO f1 VALUES(26, 'z'); + INSERT INTO f1 VALUES(25, 'y'); + INSERT INTO f1 VALUES(24, 'x'); + INSERT INTO f1 VALUES(23, 'w'); + INSERT INTO f1 VALUES(22, 'v'); + INSERT INTO f1 VALUES(21, 'u'); + INSERT INTO f1 VALUES(20, 't'); + INSERT INTO f1 VALUES(19, 's'); + INSERT INTO f1 VALUES(18, 'r'); + INSERT INTO f1 VALUES(17, 'q'); + INSERT INTO f1 VALUES(16, 'p'); + INSERT INTO f1 VALUES(15, 'o'); + INSERT INTO f1 VALUES(14, 'n'); + INSERT INTO f1 VALUES(13, 'm'); + INSERT INTO f1 VALUES(12, 'l'); + INSERT INTO f1 VALUES(11, 'k'); + INSERT INTO f1 VALUES(10, 'j'); + INSERT INTO f1 VALUES(9, 'i'); + INSERT INTO f1 VALUES(8, 'h'); + INSERT INTO f1 VALUES(7, 'g'); + INSERT INTO f1 VALUES(6, 'f'); + INSERT INTO f1 VALUES(5, 'e'); + INSERT INTO f1 VALUES(4, 'd'); + INSERT INTO f1 VALUES(3, 'c'); + INSERT INTO f1 VALUES(2, 'b'); + INSERT INTO f1 VALUES(1, 'a'); +} {} + +# EVIDENCE-OF: R-30481-56627 Any scalar expression may be used in the +# LIMIT clause, so long as it evaluates to an integer or a value that +# can be losslessly converted to an integer. +# +do_select_tests e_select-9.1 { + 1 { SELECT b FROM f1 ORDER BY a LIMIT 5 } {a b c d e} + 2 { SELECT b FROM f1 ORDER BY a LIMIT 2+3 } {a b c d e} + 3 { SELECT b FROM f1 ORDER BY a LIMIT (SELECT a FROM f1 WHERE b = 'e') } + {a b c d e} + 4 { SELECT b FROM f1 ORDER BY a LIMIT 5.0 } {a b c d e} + 5 { SELECT b FROM f1 ORDER BY a LIMIT '5' } {a b c d e} +} + +# EVIDENCE-OF: R-46155-47219 If the expression evaluates to a NULL value +# or any other value that cannot be losslessly converted to an integer, +# an error is returned. +# + +do_select_tests e_select-9.2 -error "datatype mismatch" { + 1 { SELECT b FROM f1 ORDER BY a LIMIT 'hello' } {} + 2 { SELECT b FROM f1 ORDER BY a LIMIT NULL } {} + 3 { SELECT b FROM f1 ORDER BY a LIMIT X'ABCD' } {} + 4 { SELECT b FROM f1 ORDER BY a LIMIT 5.1 } {} + 5 { SELECT b FROM f1 ORDER BY a LIMIT (SELECT group_concat(b) FROM f1) } {} +} + +# EVIDENCE-OF: R-03014-26414 If the LIMIT expression evaluates to a +# negative value, then there is no upper bound on the number of rows +# returned. +# +do_select_tests e_select-9.4 { + 1 { SELECT b FROM f1 ORDER BY a LIMIT -1 } + {a b c d e f g h i j k l m n o p q r s t u v w x y z} + 2 { SELECT b FROM f1 ORDER BY a LIMIT length('abc')-100 } + {a b c d e f g h i j k l m n o p q r s t u v w x y z} + 3 { SELECT b FROM f1 ORDER BY a LIMIT (SELECT count(*) FROM f1)/2 - 14 } + {a b c d e f g h i j k l m n o p q r s t u v w x y z} +} + +# EVIDENCE-OF: R-33750-29536 Otherwise, the SELECT returns the first N +# rows of its result set only, where N is the value that the LIMIT +# expression evaluates to. +# +do_select_tests e_select-9.5 { + 1 { SELECT b FROM f1 ORDER BY a LIMIT 0 } {} + 2 { SELECT b FROM f1 ORDER BY a DESC LIMIT 4 } {z y x w} + 3 { SELECT b FROM f1 ORDER BY a DESC LIMIT 8 } {z y x w v u t s} + 4 { SELECT b FROM f1 ORDER BY a DESC LIMIT '12.0' } {z y x w v u t s r q p o} +} + +# EVIDENCE-OF: R-54935-19057 Or, if the SELECT statement would return +# less than N rows without a LIMIT clause, then the entire result set is +# returned. +# +do_select_tests e_select-9.6 { + 1 { SELECT b FROM f1 WHERE a>21 ORDER BY a LIMIT 10 } {v w x y z} + 2 { SELECT count(*) FROM f1 GROUP BY a/5 ORDER BY 1 LIMIT 10 } {2 4 5 5 5 5} +} + + +# EVIDENCE-OF: R-24188-24349 The expression attached to the optional +# OFFSET clause that may follow a LIMIT clause must also evaluate to an +# integer, or a value that can be losslessly converted to an integer. +# +foreach {tn select} { + 1 { SELECT b FROM f1 ORDER BY a LIMIT 2 OFFSET 'hello' } + 2 { SELECT b FROM f1 ORDER BY a LIMIT 2 OFFSET NULL } + 3 { SELECT b FROM f1 ORDER BY a LIMIT 2 OFFSET X'ABCD' } + 4 { SELECT b FROM f1 ORDER BY a LIMIT 2 OFFSET 5.1 } + 5 { SELECT b FROM f1 ORDER BY a + LIMIT 2 OFFSET (SELECT group_concat(b) FROM f1) + } +} { + do_catchsql_test e_select-9.7.$tn $select {1 {datatype mismatch}} +} + +# EVIDENCE-OF: R-20467-43422 If an expression has an OFFSET clause, then +# the first M rows are omitted from the result set returned by the +# SELECT statement and the next N rows are returned, where M and N are +# the values that the OFFSET and LIMIT clauses evaluate to, +# respectively. +# +do_select_tests e_select-9.8 { + 1 { SELECT b FROM f1 ORDER BY a LIMIT 10 OFFSET 5} {f g h i j k l m n o} + 2 { SELECT b FROM f1 ORDER BY a LIMIT 2+3 OFFSET 10} {k l m n o} + 3 { SELECT b FROM f1 ORDER BY a + LIMIT (SELECT a FROM f1 WHERE b='j') + OFFSET (SELECT a FROM f1 WHERE b='b') + } {c d e f g h i j k l} + 4 { SELECT b FROM f1 ORDER BY a LIMIT '5' OFFSET 3.0 } {d e f g h} + 5 { SELECT b FROM f1 ORDER BY a LIMIT '5' OFFSET 0 } {a b c d e} + 6 { SELECT b FROM f1 ORDER BY a LIMIT 0 OFFSET 10 } {} + 7 { SELECT b FROM f1 ORDER BY a LIMIT 3 OFFSET '1'||'5' } {p q r} +} + +# EVIDENCE-OF: R-34648-44875 Or, if the SELECT would return less than +# M+N rows if it did not have a LIMIT clause, then the first M rows are +# skipped and the remaining rows (if any) are returned. +# +do_select_tests e_select-9.9 { + 1 { SELECT b FROM f1 ORDER BY a LIMIT 10 OFFSET 20} {u v w x y z} + 2 { SELECT a FROM f1 ORDER BY a DESC LIMIT 100 OFFSET 18+4} {4 3 2 1} +} + + +# EVIDENCE-OF: R-23293-62447 If the OFFSET clause evaluates to a +# negative value, the results are the same as if it had evaluated to +# zero. +# +do_select_tests e_select-9.10 { + 1 { SELECT b FROM f1 ORDER BY a LIMIT 5 OFFSET -1 } {a b c d e} + 2 { SELECT b FROM f1 ORDER BY a LIMIT 5 OFFSET -500 } {a b c d e} + 3 { SELECT b FROM f1 ORDER BY a LIMIT 5 OFFSET 0 } {a b c d e} +} + +# EVIDENCE-OF: R-19509-40356 Instead of a separate OFFSET clause, the +# LIMIT clause may specify two scalar expressions separated by a comma. +# +# EVIDENCE-OF: R-33788-46243 In this case, the first expression is used +# as the OFFSET expression and the second as the LIMIT expression. +# +do_select_tests e_select-9.11 { + 1 { SELECT b FROM f1 ORDER BY a LIMIT 5, 10 } {f g h i j k l m n o} + 2 { SELECT b FROM f1 ORDER BY a LIMIT 10, 2+3 } {k l m n o} + 3 { SELECT b FROM f1 ORDER BY a + LIMIT (SELECT a FROM f1 WHERE b='b'), (SELECT a FROM f1 WHERE b='j') + } {c d e f g h i j k l} + 4 { SELECT b FROM f1 ORDER BY a LIMIT 3.0, '5' } {d e f g h} + 5 { SELECT b FROM f1 ORDER BY a LIMIT 0, '5' } {a b c d e} + 6 { SELECT b FROM f1 ORDER BY a LIMIT 10, 0 } {} + 7 { SELECT b FROM f1 ORDER BY a LIMIT '1'||'5', 3 } {p q r} + + 8 { SELECT b FROM f1 ORDER BY a LIMIT 20, 10 } {u v w x y z} + 9 { SELECT a FROM f1 ORDER BY a DESC LIMIT 18+4, 100 } {4 3 2 1} + + 10 { SELECT b FROM f1 ORDER BY a LIMIT -1, 5 } {a b c d e} + 11 { SELECT b FROM f1 ORDER BY a LIMIT -500, 5 } {a b c d e} + 12 { SELECT b FROM f1 ORDER BY a LIMIT 0, 5 } {a b c d e} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_select2.test b/components/external/SQLite-3.8.1/test/e_select2.test new file mode 100644 index 0000000000000000000000000000000000000000..a2a32a0503a864c6b2ac3b6921fa4621c01a3316 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_select2.test @@ -0,0 +1,580 @@ +# 2010 September 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_select.html document are correct. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +#------------------------------------------------------------------------- +# te_* commands: +# +# +# te_read_sql DB SELECT-STATEMENT +# te_read_tbl DB TABLENAME +# +# These two commands are used to read a dataset from the database. A dataset +# consists of N rows of M named columns of values each, where each value has a +# type (null, integer, real, text or blob) and a value within the types domain. +# The tcl format for a "dataset" is a list of two elements: +# +# * A list of the column names. +# * A list of data rows. Each row is itself a list, where each element is +# the contents of a column of the row. Each of these is a list of two +# elements, the type name and the actual value. +# +# For example, the contents of table [t1] as a dataset is: +# +# CREATE TABLE t1(a, b); +# INSERT INTO t1 VALUES('abc', NULL); +# INSERT INTO t1 VALUES(43.1, 22); +# +# {a b} {{{TEXT abc} {NULL {}}} {{REAL 43.1} {INTEGER 22}}} +# +# The [te_read_tbl] command returns a dataset read from a table. The +# [te_read_sql] returns the dataset that results from executing a SELECT +# command. +# +# +# te_tbljoin ?SWITCHES? LHS-TABLE RHS-TABLE +# te_join ?SWITCHES? LHS-DATASET RHS-DATASET +# +# This command joins the two datasets and returns the resulting dataset. If +# there are no switches specified, then the results is the cartesian product +# of the two inputs. The [te_tbljoin] command reads the left and right-hand +# datasets from the specified tables. The [te_join] command is passed the +# datasets directly. +# +# Optional switches are as follows: +# +# -on SCRIPT +# -using COLUMN-LIST +# -left +# +# The -on option specifies a tcl script that is executed for each row in the +# cartesian product of the two datasets. The script has 4 arguments appended +# to it, in the following order: +# +# * The list of column-names from the left-hand dataset. +# * A single row from the left-hand dataset (one "data row" list as +# described above. +# * The list of column-names from the right-hand dataset. +# * A single row from the right-hand dataset. +# +# The script must return a boolean value - true if the combination of rows +# should be included in the output dataset, or false otherwise. +# +# The -using option specifies a list of the columns from the right-hand +# dataset that should be omitted from the output dataset. +# +# If the -left option is present, the join is done LEFT JOIN style. +# Specifically, an extra row is inserted if after the -on script is run there +# exist rows in the left-hand dataset that have no corresponding rows in +# the output. See the implementation for more specific comments. +# +# +# te_equals ?SWITCHES? COLNAME1 COLNAME2 <-on script args> +# +# The only supported switch is "-nocase". If it is present, then text values +# are compared in a case-independent fashion. Otherwise, they are compared +# as if using the SQLite BINARY collation sequence. +# +# +# te_and ONSCRIPT1 ONSCRIPT2... +# +# + + +# +# te_read_tbl DB TABLENAME +# te_read_sql DB SELECT-STATEMENT +# +# These two procs are used to extract datasets from the database, either +# by reading the contents of a named table (te_read_tbl), or by executing +# a SELECT statement (t3_read_sql). +# +# See the comment above, describing "te_* commands", for details of the +# return values. +# +proc te_read_tbl {db tbl} { + te_read_sql $db "SELECT * FROM '$tbl'" +} +proc te_read_sql {db sql} { + set S [sqlite3_prepare_v2 $db $sql -1 DUMMY] + + set cols [list] + for {set i 0} {$i < [sqlite3_column_count $S]} {incr i} { + lappend cols [sqlite3_column_name $S $i] + } + + set rows [list] + while {[sqlite3_step $S] == "SQLITE_ROW"} { + set r [list] + for {set i 0} {$i < [sqlite3_column_count $S]} {incr i} { + lappend r [list [sqlite3_column_type $S $i] [sqlite3_column_text $S $i]] + } + lappend rows $r + } + sqlite3_finalize $S + + return [list $cols $rows] +} + +#------- +# Usage: te_join ... +# +# Where a join-spec is an optional list of arguments as follows: +# +# ?-left? +# ?-using colname-list? +# ?-on on-expr-proc? +# +proc te_join {data1 data2 args} { + + set testproc "" + set usinglist [list] + set isleft 0 + for {set i 0} {$i < [llength $args]} {incr i} { + set a [lindex $args $i] + switch -- $a { + -on { set testproc [lindex $args [incr i]] } + -using { set usinglist [lindex $args [incr i]] } + -left { set isleft 1 } + default { + error "Unknown argument: $a" + } + } + } + + set c1 [lindex $data1 0] + set c2 [lindex $data2 0] + set omitlist [list] + set nullrowlist [list] + set cret $c1 + + set cidx 0 + foreach col $c2 { + set idx [lsearch $usinglist $col] + if {$idx>=0} {lappend omitlist $cidx} + if {$idx<0} { + lappend nullrowlist {NULL {}} + lappend cret $col + } + incr cidx + } + set omitlist [lsort -integer -decreasing $omitlist] + + + set rret [list] + foreach r1 [lindex $data1 1] { + set one 0 + foreach r2 [lindex $data2 1] { + set ok 1 + if {$testproc != ""} { + set ok [eval $testproc [list $c1 $r1 $c2 $r2]] + } + if {$ok} { + set one 1 + foreach idx $omitlist {set r2 [lreplace $r2 $idx $idx]} + lappend rret [concat $r1 $r2] + } + } + + if {$isleft && $one==0} { + lappend rret [concat $r1 $nullrowlist] + } + } + + list $cret $rret +} + +proc te_tbljoin {db t1 t2 args} { + te_join [te_read_tbl $db $t1] [te_read_tbl $db $t2] {*}$args +} + +proc te_apply_affinity {affinity typevar valvar} { + upvar $typevar type + upvar $valvar val + + switch -- $affinity { + integer { + if {[string is double $val]} { set type REAL } + if {[string is wideinteger $val]} { set type INTEGER } + if {$type == "REAL" && int($val)==$val} { + set type INTEGER + set val [expr {int($val)}] + } + } + text { + set type TEXT + } + none { } + + default { error "invalid affinity: $affinity" } + } +} + +#---------- +# te_equals ?SWITCHES? c1 c2 cols1 row1 cols2 row2 +# +proc te_equals {args} { + + if {[llength $args]<6} {error "invalid arguments to te_equals"} + foreach {c1 c2 cols1 row1 cols2 row2} [lrange $args end-5 end] break + + set nocase 0 + set affinity none + + for {set i 0} {$i < ([llength $args]-6)} {incr i} { + set a [lindex $args $i] + switch -- $a { + -nocase { + set nocase 1 + } + -affinity { + set affinity [string tolower [lindex $args [incr i]]] + } + default { + error "invalid arguments to te_equals" + } + } + } + + set idx2 [if {[string is integer $c2]} { set c2 } else { lsearch $cols2 $c2 }] + set idx1 [if {[string is integer $c1]} { set c1 } else { lsearch $cols1 $c1 }] + + set t1 [lindex $row1 $idx1 0] + set t2 [lindex $row2 $idx2 0] + set v1 [lindex $row1 $idx1 1] + set v2 [lindex $row2 $idx2 1] + + te_apply_affinity $affinity t1 v1 + te_apply_affinity $affinity t2 v2 + + if {$t1 == "NULL" || $t2 == "NULL"} { return 0 } + if {$nocase && $t1 == "TEXT"} { set v1 [string tolower $v1] } + if {$nocase && $t2 == "TEXT"} { set v2 [string tolower $v2] } + + + set res [expr {$t1 == $t2 && [string equal $v1 $v2]}] + return $res +} + +proc te_false {args} { return 0 } +proc te_true {args} { return 1 } + +proc te_and {args} { + foreach a [lrange $args 0 end-4] { + set res [eval $a [lrange $args end-3 end]] + if {$res == 0} {return 0} + } + return 1 +} + + +proc te_dataset_eq {testname got expected} { + uplevel #0 [list do_test $testname [list set {} $got] $expected] +} +proc te_dataset_eq_unordered {testname got expected} { + lset got 1 [lsort [lindex $got 1]] + lset expected 1 [lsort [lindex $expected 1]] + te_dataset_eq $testname $got $expected +} + +proc te_dataset_ne {testname got unexpected} { + uplevel #0 [list do_test $testname [list string equal $got $unexpected] 0] +} +proc te_dataset_ne_unordered {testname got unexpected} { + lset got 1 [lsort [lindex $got 1]] + lset unexpected 1 [lsort [lindex $unexpected 1]] + te_dataset_ne $testname $got $unexpected +} + + +#------------------------------------------------------------------------- +# +proc test_join {tn sqljoin tbljoinargs} { + set sql [te_read_sql db "SELECT * FROM $sqljoin"] + set te [te_tbljoin db {*}$tbljoinargs] + te_dataset_eq_unordered $tn $sql $te +} + +drop_all_tables +do_execsql_test e_select-2.0 { + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + CREATE TABLE t3(b COLLATE nocase); + + INSERT INTO t1 VALUES(2, 'B'); + INSERT INTO t1 VALUES(1, 'A'); + INSERT INTO t1 VALUES(4, 'D'); + INSERT INTO t1 VALUES(NULL, NULL); + INSERT INTO t1 VALUES(3, NULL); + + INSERT INTO t2 VALUES(1, 'A'); + INSERT INTO t2 VALUES(2, NULL); + INSERT INTO t2 VALUES(5, 'E'); + INSERT INTO t2 VALUES(NULL, NULL); + INSERT INTO t2 VALUES(3, 'C'); + + INSERT INTO t3 VALUES('a'); + INSERT INTO t3 VALUES('c'); + INSERT INTO t3 VALUES('b'); +} {} + +foreach {tn indexes} { + e_select-2.1.1 { } + e_select-2.1.2 { CREATE INDEX i1 ON t1(a) } + e_select-2.1.3 { CREATE INDEX i1 ON t2(a) } + e_select-2.1.4 { CREATE INDEX i1 ON t3(b) } +} { + + catchsql { DROP INDEX i1 } + catchsql { DROP INDEX i2 } + catchsql { DROP INDEX i3 } + execsql $indexes + + # EVIDENCE-OF: R-46122-14930 If the join-op is "CROSS JOIN", "INNER + # JOIN", "JOIN" or a comma (",") and there is no ON or USING clause, + # then the result of the join is simply the cartesian product of the + # left and right-hand datasets. + # + # EVIDENCE-OF: R-46256-57243 There is no difference between the "INNER + # JOIN", "JOIN" and "," join operators. + # + # EVIDENCE-OF: R-25071-21202 The "CROSS JOIN" join operator produces the + # same result as the "INNER JOIN", "JOIN" and "," operators + # + test_join $tn.1.1 "t1, t2" {t1 t2} + test_join $tn.1.2 "t1 INNER JOIN t2" {t1 t2} + test_join $tn.1.3 "t1 CROSS JOIN t2" {t1 t2} + test_join $tn.1.4 "t1 JOIN t2" {t1 t2} + test_join $tn.1.5 "t2, t3" {t2 t3} + test_join $tn.1.6 "t2 INNER JOIN t3" {t2 t3} + test_join $tn.1.7 "t2 CROSS JOIN t3" {t2 t3} + test_join $tn.1.8 "t2 JOIN t3" {t2 t3} + test_join $tn.1.9 "t2, t2 AS x" {t2 t2} + test_join $tn.1.10 "t2 INNER JOIN t2 AS x" {t2 t2} + test_join $tn.1.11 "t2 CROSS JOIN t2 AS x" {t2 t2} + test_join $tn.1.12 "t2 JOIN t2 AS x" {t2 t2} + + # EVIDENCE-OF: R-22775-56496 If there is an ON clause specified, then + # the ON expression is evaluated for each row of the cartesian product + # as a boolean expression. All rows for which the expression evaluates + # to false are excluded from the dataset. + # + test_join $tn.2.1 "t1, t2 ON (t1.a=t2.a)" {t1 t2 -on {te_equals a a}} + test_join $tn.2.2 "t2, t1 ON (t1.a=t2.a)" {t2 t1 -on {te_equals a a}} + test_join $tn.2.3 "t2, t1 ON (1)" {t2 t1 -on te_true} + test_join $tn.2.4 "t2, t1 ON (NULL)" {t2 t1 -on te_false} + test_join $tn.2.5 "t2, t1 ON (1.1-1.1)" {t2 t1 -on te_false} + test_join $tn.2.6 "t1, t2 ON (1.1-1.0)" {t1 t2 -on te_true} + + + test_join $tn.3 "t1 LEFT JOIN t2 ON (t1.a=t2.a)" {t1 t2 -left -on {te_equals a a}} + test_join $tn.4 "t1 LEFT JOIN t2 USING (a)" { + t1 t2 -left -using a -on {te_equals a a} + } + test_join $tn.5 "t1 CROSS JOIN t2 USING(b, a)" { + t1 t2 -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.6 "t1 NATURAL JOIN t2" { + t1 t2 -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.7 "t1 NATURAL INNER JOIN t2" { + t1 t2 -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.8 "t1 NATURAL CROSS JOIN t2" { + t1 t2 -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.9 "t1 NATURAL INNER JOIN t2" { + t1 t2 -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.10 "t1 NATURAL LEFT JOIN t2" { + t1 t2 -left -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.11 "t1 NATURAL LEFT OUTER JOIN t2" { + t1 t2 -left -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.12 "t2 NATURAL JOIN t1" { + t2 t1 -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.13 "t2 NATURAL INNER JOIN t1" { + t2 t1 -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.14 "t2 NATURAL CROSS JOIN t1" { + t2 t1 -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.15 "t2 NATURAL INNER JOIN t1" { + t2 t1 -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.16 "t2 NATURAL LEFT JOIN t1" { + t2 t1 -left -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.17 "t2 NATURAL LEFT OUTER JOIN t1" { + t2 t1 -left -using {a b} -on {te_and {te_equals a a} {te_equals b b}} + } + test_join $tn.18 "t1 LEFT JOIN t2 USING (b)" { + t1 t2 -left -using b -on {te_equals b b} + } + test_join $tn.19 "t1 JOIN t3 USING(b)" {t1 t3 -using b -on {te_equals b b}} + test_join $tn.20 "t3 JOIN t1 USING(b)" { + t3 t1 -using b -on {te_equals -nocase b b} + } + test_join $tn.21 "t1 NATURAL JOIN t3" { + t1 t3 -using b -on {te_equals b b} + } + test_join $tn.22 "t3 NATURAL JOIN t1" { + t3 t1 -using b -on {te_equals -nocase b b} + } + test_join $tn.23 "t1 NATURAL LEFT JOIN t3" { + t1 t3 -left -using b -on {te_equals b b} + } + test_join $tn.24 "t3 NATURAL LEFT JOIN t1" { + t3 t1 -left -using b -on {te_equals -nocase b b} + } + test_join $tn.25 "t1 LEFT JOIN t3 ON (t3.b=t1.b)" { + t1 t3 -left -on {te_equals -nocase b b} + } + test_join $tn.26 "t1 LEFT JOIN t3 ON (t1.b=t3.b)" { + t1 t3 -left -on {te_equals b b} + } + test_join $tn.27 "t1 JOIN t3 ON (t1.b=t3.b)" { t1 t3 -on {te_equals b b} } + + # EVIDENCE-OF: R-28760-53843 When more than two tables are joined + # together as part of a FROM clause, the join operations are processed + # in order from left to right. In other words, the FROM clause (A + # join-op-1 B join-op-2 C) is computed as ((A join-op-1 B) join-op-2 C). + # + # Tests 28a and 28b show that the statement above is true for this case. + # Test 28c shows that if the parenthesis force a different order of + # evaluation the result is different. Test 28d verifies that the result + # of the query with the parenthesis forcing a different order of evaluation + # is as calculated by the [te_*] procs. + # + set t3_natural_left_join_t2 [ + te_tbljoin db t3 t2 -left -using {b} -on {te_equals -nocase b b} + ] + set t1 [te_read_tbl db t1] + te_dataset_eq_unordered $tn.28a [ + te_read_sql db "SELECT * FROM t3 NATURAL LEFT JOIN t2 NATURAL JOIN t1" + ] [te_join $t3_natural_left_join_t2 $t1 \ + -using {a b} -on {te_and {te_equals a a} {te_equals -nocase b b}} \ + ] + + te_dataset_eq_unordered $tn.28b [ + te_read_sql db "SELECT * FROM (t3 NATURAL LEFT JOIN t2) NATURAL JOIN t1" + ] [te_join $t3_natural_left_join_t2 $t1 \ + -using {a b} -on {te_and {te_equals a a} {te_equals -nocase b b}} \ + ] + + te_dataset_ne_unordered $tn.28c [ + te_read_sql db "SELECT * FROM (t3 NATURAL LEFT JOIN t2) NATURAL JOIN t1" + ] [ + te_read_sql db "SELECT * FROM t3 NATURAL LEFT JOIN (t2 NATURAL JOIN t1)" + ] + + set t2_natural_join_t1 [te_tbljoin db t2 t1 -using {a b} \ + -using {a b} -on {te_and {te_equals a a} {te_equals -nocase b b}} \ + ] + set t3 [te_read_tbl db t3] + te_dataset_eq_unordered $tn.28d [ + te_read_sql db "SELECT * FROM t3 NATURAL LEFT JOIN (t2 NATURAL JOIN t1)" + ] [te_join $t3 $t2_natural_join_t1 \ + -left -using {b} -on {te_equals -nocase b b} \ + ] +} + +do_execsql_test e_select-2.2.0 { + CREATE TABLE t4(x TEXT COLLATE nocase); + CREATE TABLE t5(y INTEGER, z TEXT COLLATE binary); + + INSERT INTO t4 VALUES('2.0'); + INSERT INTO t4 VALUES('TWO'); + INSERT INTO t5 VALUES(2, 'two'); +} {} + +# EVIDENCE-OF: R-55824-40976 A sub-select specified in the join-source +# following the FROM clause in a simple SELECT statement is handled as +# if it was a table containing the data returned by executing the +# sub-select statement. +# +# EVIDENCE-OF: R-42612-06757 Each column of the sub-select dataset +# inherits the collation sequence and affinity of the corresponding +# expression in the sub-select statement. +# +foreach {tn subselect select spec} { + 1 "SELECT * FROM t2" "SELECT * FROM t1 JOIN %ss%" + {t1 %ss%} + + 2 "SELECT * FROM t2" "SELECT * FROM t1 JOIN %ss% AS x ON (t1.a=x.a)" + {t1 %ss% -on {te_equals 0 0}} + + 3 "SELECT * FROM t2" "SELECT * FROM %ss% AS x JOIN t1 ON (t1.a=x.a)" + {%ss% t1 -on {te_equals 0 0}} + + 4 "SELECT * FROM t1, t2" "SELECT * FROM %ss% AS x JOIN t3" + {%ss% t3} + + 5 "SELECT * FROM t1, t2" "SELECT * FROM %ss% NATURAL JOIN t3" + {%ss% t3 -using b -on {te_equals 1 0}} + + 6 "SELECT * FROM t1, t2" "SELECT * FROM t3 NATURAL JOIN %ss%" + {t3 %ss% -using b -on {te_equals -nocase 0 1}} + + 7 "SELECT * FROM t1, t2" "SELECT * FROM t3 NATURAL LEFT JOIN %ss%" + {t3 %ss% -left -using b -on {te_equals -nocase 0 1}} + + 8 "SELECT count(*) AS y FROM t4" "SELECT * FROM t5, %ss% USING (y)" + {t5 %ss% -using y -on {te_equals -affinity text 0 0}} + + 9 "SELECT count(*) AS y FROM t4" "SELECT * FROM %ss%, t5 USING (y)" + {%ss% t5 -using y -on {te_equals -affinity text 0 0}} + + 10 "SELECT x AS y FROM t4" "SELECT * FROM %ss% JOIN t5 USING (y)" + {%ss% t5 -using y -on {te_equals -nocase -affinity integer 0 0}} + + 11 "SELECT x AS y FROM t4" "SELECT * FROM t5 JOIN %ss% USING (y)" + {t5 %ss% -using y -on {te_equals -nocase -affinity integer 0 0}} + + 12 "SELECT y AS x FROM t5" "SELECT * FROM %ss% JOIN t4 USING (x)" + {%ss% t4 -using x -on {te_equals -nocase -affinity integer 0 0}} + + 13 "SELECT y AS x FROM t5" "SELECT * FROM t4 JOIN %ss% USING (x)" + {t4 %ss% -using x -on {te_equals -nocase -affinity integer 0 0}} + + 14 "SELECT +y AS x FROM t5" "SELECT * FROM %ss% JOIN t4 USING (x)" + {%ss% t4 -using x -on {te_equals -nocase -affinity text 0 0}} + + 15 "SELECT +y AS x FROM t5" "SELECT * FROM t4 JOIN %ss% USING (x)" + {t4 %ss% -using x -on {te_equals -nocase -affinity text 0 0}} +} { + + # Create a temporary table named %ss% containing the data returned by + # the sub-select. Then have the [te_tbljoin] proc use this table to + # compute the expected results of the $select query. Drop the temporary + # table before continuing. + # + execsql "CREATE TEMP TABLE '%ss%' AS $subselect" + set te [eval te_tbljoin db $spec] + execsql "DROP TABLE '%ss%'" + + # Check that the actual data returned by the $select query is the same + # as the expected data calculated using [te_tbljoin] above. + # + te_dataset_eq_unordered e_select-2.2.1.$tn [ + te_read_sql db [string map [list %ss% "($subselect)"] $select] + ] $te +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_update.test b/components/external/SQLite-3.8.1/test/e_update.test new file mode 100644 index 0000000000000000000000000000000000000000..159e0676f59c5fe5807d3c1a25f2b788e8fab396 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_update.test @@ -0,0 +1,605 @@ +# 2010 September 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_update.html document are correct. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +#-------------------- +# Test organization: +# +# e_update-1.*: Test statements describing the workings of UPDATE statements. +# +# e_update-2.*: Test the restrictions on the UPDATE statement syntax that +# can be used within triggers. +# +# e_update-3.*: Test the special LIMIT/OFFSET and ORDER BY clauses that can +# be used with UPDATE when SQLite is compiled with +# SQLITE_ENABLE_UPDATE_DELETE_LIMIT. +# + +forcedelete test.db2 + +do_execsql_test e_update-0.0 { + ATTACH 'test.db2' AS aux; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b, c); + CREATE TABLE t3(a, b UNIQUE); + CREATE TABLE t6(x, y); + CREATE INDEX i1 ON t1(a); + + CREATE TEMP TABLE t4(x, y); + CREATE TEMP TABLE t6(x, y); + + CREATE TABLE aux.t1(a, b); + CREATE TABLE aux.t5(a, b); +} {} + +proc do_update_tests {args} { + uplevel do_select_tests $args +} + +# -- syntax diagram update-stmt +# +do_update_tests e_update-0 { + 1 "UPDATE t1 SET a=10" {} + 2 "UPDATE t1 SET a=10, b=5" {} + 3 "UPDATE t1 SET a=10 WHERE b=5" {} + 4 "UPDATE t1 SET b=5,a=10 WHERE 1" {} + 5 "UPDATE main.t1 SET a=10" {} + 6 "UPDATE main.t1 SET a=10, b=5" {} + 7 "UPDATE main.t1 SET a=10 WHERE b=5" {} + 9 "UPDATE OR ROLLBACK t1 SET a=10" {} + 10 "UPDATE OR ROLLBACK t1 SET a=10, b=5" {} + 11 "UPDATE OR ROLLBACK t1 SET a=10 WHERE b=5" {} + 12 "UPDATE OR ROLLBACK t1 SET b=5,a=10 WHERE 1" {} + 13 "UPDATE OR ROLLBACK main.t1 SET a=10" {} + 14 "UPDATE OR ROLLBACK main.t1 SET a=10, b=5" {} + 15 "UPDATE OR ROLLBACK main.t1 SET a=10 WHERE b=5" {} + 16 "UPDATE OR ROLLBACK main.t1 SET b=5,a=10 WHERE 1" {} + 17 "UPDATE OR ABORT t1 SET a=10" {} + 18 "UPDATE OR ABORT t1 SET a=10, b=5" {} + 19 "UPDATE OR ABORT t1 SET a=10 WHERE b=5" {} + 20 "UPDATE OR ABORT t1 SET b=5,a=10 WHERE 1" {} + 21 "UPDATE OR ABORT main.t1 SET a=10" {} + 22 "UPDATE OR ABORT main.t1 SET a=10, b=5" {} + 23 "UPDATE OR ABORT main.t1 SET a=10 WHERE b=5" {} + 24 "UPDATE OR ABORT main.t1 SET b=5,a=10 WHERE 1" {} + 25 "UPDATE OR REPLACE t1 SET a=10" {} + 26 "UPDATE OR REPLACE t1 SET a=10, b=5" {} + 27 "UPDATE OR REPLACE t1 SET a=10 WHERE b=5" {} + 28 "UPDATE OR REPLACE t1 SET b=5,a=10 WHERE 1" {} + 29 "UPDATE OR REPLACE main.t1 SET a=10" {} + 30 "UPDATE OR REPLACE main.t1 SET a=10, b=5" {} + 31 "UPDATE OR REPLACE main.t1 SET a=10 WHERE b=5" {} + 32 "UPDATE OR REPLACE main.t1 SET b=5,a=10 WHERE 1" {} + 33 "UPDATE OR FAIL t1 SET a=10" {} + 34 "UPDATE OR FAIL t1 SET a=10, b=5" {} + 35 "UPDATE OR FAIL t1 SET a=10 WHERE b=5" {} + 36 "UPDATE OR FAIL t1 SET b=5,a=10 WHERE 1" {} + 37 "UPDATE OR FAIL main.t1 SET a=10" {} + 38 "UPDATE OR FAIL main.t1 SET a=10, b=5" {} + 39 "UPDATE OR FAIL main.t1 SET a=10 WHERE b=5" {} + 40 "UPDATE OR FAIL main.t1 SET b=5,a=10 WHERE 1" {} + 41 "UPDATE OR IGNORE t1 SET a=10" {} + 42 "UPDATE OR IGNORE t1 SET a=10, b=5" {} + 43 "UPDATE OR IGNORE t1 SET a=10 WHERE b=5" {} + 44 "UPDATE OR IGNORE t1 SET b=5,a=10 WHERE 1" {} + 45 "UPDATE OR IGNORE main.t1 SET a=10" {} + 46 "UPDATE OR IGNORE main.t1 SET a=10, b=5" {} + 47 "UPDATE OR IGNORE main.t1 SET a=10 WHERE b=5" {} + 48 "UPDATE OR IGNORE main.t1 SET b=5,a=10 WHERE 1" {} +} + +# EVIDENCE-OF: R-38515-45264 An UPDATE statement is used to modify a +# subset of the values stored in zero or more rows of the database table +# identified by the qualified-table-name specified as part of the UPDATE +# statement. +# +# Test cases e_update-1.1.1.* test the "identified by the +# qualified-table-name" part of the statement above. Tests +# e_update-1.1.2.* show that the "zero or more rows" part is +# accurate. +# +do_execsql_test e_update-1.1.0 { + INSERT INTO main.t1 VALUES(1, 'i'); + INSERT INTO main.t1 VALUES(2, 'ii'); + INSERT INTO main.t1 VALUES(3, 'iii'); + + INSERT INTO aux.t1 VALUES(1, 'I'); + INSERT INTO aux.t1 VALUES(2, 'II'); + INSERT INTO aux.t1 VALUES(3, 'III'); +} {} +do_update_tests e_update-1.1 { + 1.1 "UPDATE t1 SET a = a+1; SELECT * FROM t1" {2 i 3 ii 4 iii} + 1.2 "UPDATE main.t1 SET a = a+1; SELECT * FROM main.t1" {3 i 4 ii 5 iii} + 1.3 "UPDATE aux.t1 SET a = a+1; SELECT * FROM aux.t1" {2 I 3 II 4 III} + + 2.1 "UPDATE t1 SET a = a+1 WHERE a = 1; SELECT * FROM t1" {3 i 4 ii 5 iii} + 2.2 "UPDATE t1 SET a = a+1 WHERE a = 4; SELECT * FROM t1" {3 i 5 ii 5 iii} +} + +# EVIDENCE-OF: R-55869-30521 If the UPDATE statement does not have a +# WHERE clause, all rows in the table are modified by the UPDATE. +# +do_execsql_test e_update-1.2.0 { + DELETE FROM main.t1; + INSERT INTO main.t1 VALUES(1, 'i'); + INSERT INTO main.t1 VALUES(2, 'ii'); + INSERT INTO main.t1 VALUES(3, 'iii'); +} {} +do_update_tests e_update-1.2 { + 1 "UPDATE t1 SET b = 'roman' ; SELECT * FROM t1" + {1 roman 2 roman 3 roman} + + 2 "UPDATE t1 SET a = 'greek' ; SELECT * FROM t1" + {greek roman greek roman greek roman} +} + +# EVIDENCE-OF: R-42117-40023 Otherwise, the UPDATE affects only those +# rows for which the result of evaluating the WHERE clause expression as +# a boolean expression is true. +# +do_execsql_test e_update-1.3.0 { + DELETE FROM main.t1; + INSERT INTO main.t1 VALUES(NULL, ''); + INSERT INTO main.t1 VALUES(1, 'i'); + INSERT INTO main.t1 VALUES(2, 'ii'); + INSERT INTO main.t1 VALUES(3, 'iii'); +} {} +do_update_tests e_update-1.3 { + 1 "UPDATE t1 SET b = 'roman' WHERE a<2 ; SELECT * FROM t1" + {{} {} 1 roman 2 ii 3 iii} + + 2 "UPDATE t1 SET b = 'egyptian' WHERE (a-3)/10.0 ; SELECT * FROM t1" + {{} {} 1 egyptian 2 egyptian 3 iii} + + 3 "UPDATE t1 SET b = 'macedonian' WHERE a; SELECT * FROM t1" + {{} {} 1 macedonian 2 macedonian 3 macedonian} + + 4 "UPDATE t1 SET b = 'lithuanian' WHERE a IS NULL; SELECT * FROM t1" + {{} lithuanian 1 macedonian 2 macedonian 3 macedonian} +} + +# EVIDENCE-OF: R-58129-20729 It is not an error if the WHERE clause does +# not evaluate to true for any row in the table - this just means that +# the UPDATE statement affects zero rows. +# +do_execsql_test e_update-1.4.0 { + DELETE FROM main.t1; + INSERT INTO main.t1 VALUES(NULL, ''); + INSERT INTO main.t1 VALUES(1, 'i'); + INSERT INTO main.t1 VALUES(2, 'ii'); + INSERT INTO main.t1 VALUES(3, 'iii'); +} {} +do_update_tests e_update-1.4 -query { + SELECT * FROM t1 +} { + 1 "UPDATE t1 SET b = 'burmese' WHERE a=5" {{} {} 1 i 2 ii 3 iii} + + 2 "UPDATE t1 SET b = 'burmese' WHERE length(b)<1 AND a IS NOT NULL" + {{} {} 1 i 2 ii 3 iii} + + 3 "UPDATE t1 SET b = 'burmese' WHERE 0" {{} {} 1 i 2 ii 3 iii} + + 4 "UPDATE t1 SET b = 'burmese' WHERE (SELECT a FROM t1 WHERE rowid=1)" + {{} {} 1 i 2 ii 3 iii} +} + +# EVIDENCE-OF: R-40598-36595 For each affected row, the named columns +# are set to the values found by evaluating the corresponding scalar +# expressions. +# +# EVIDENCE-OF: R-40472-60438 Columns that do not appear in the list of +# assignments are left unmodified. +# +do_execsql_test e_update-1.5.0 { + INSERT INTO t2(rowid, a, b, c) VALUES(1, 3, 1, 4); + INSERT INTO t2(rowid, a, b, c) VALUES(2, 1, 5, 9); + INSERT INTO t2(rowid, a, b, c) VALUES(3, 2, 6, 5); +} {} +do_update_tests e_update-1.5 -query { + SELECT * FROM t2 +} { + 1 "UPDATE t2 SET c = 1+1 WHERE a=2" + {3 1 4 1 5 9 2 6 2} + + 2 "UPDATE t2 SET b = 4/2, c=CAST((0.4*5) AS INTEGER) WHERE a<3" + {3 1 4 1 2 2 2 2 2} + + 3 "UPDATE t2 SET a = 1" + {1 1 4 1 2 2 1 2 2} + + 4 "UPDATE t2 SET b = (SELECT count(*)+2 FROM t2), c = 24/3+1 WHERE rowid=2" + {1 1 4 1 5 9 1 2 2} + + 5 "UPDATE t2 SET a = 3 WHERE c = 4" + {3 1 4 1 5 9 1 2 2} + + 6 "UPDATE t2 SET a = b WHERE rowid>2" + {3 1 4 1 5 9 2 2 2} + + 6 "UPDATE t2 SET b=6, c=5 WHERE a=b AND b=c" + {3 1 4 1 5 9 2 6 5} +} + +# EVIDENCE-OF: R-34751-18293 If a single column-name appears more than +# once in the list of assignment expressions, all but the rightmost +# occurrence is ignored. +# +do_update_tests e_update-1.6 -query { + SELECT * FROM t2 +} { + 1 "UPDATE t2 SET c=5, c=6, c=7 WHERE rowid=1" {3 1 7 1 5 9 2 6 5} + 2 "UPDATE t2 SET c=7, c=6, c=5 WHERE rowid=1" {3 1 5 1 5 9 2 6 5} + 3 "UPDATE t2 SET c=5, b=6, c=7 WHERE rowid=1" {3 6 7 1 5 9 2 6 5} +} + +# EVIDENCE-OF: R-36239-04077 The scalar expressions may refer to columns +# of the row being updated. +# +# EVIDENCE-OF: R-04558-24451 In this case all scalar expressions are +# evaluated before any assignments are made. +# +do_execsql_test e_update-1.7.0 { + DELETE FROM t2; + INSERT INTO t2(rowid, a, b, c) VALUES(1, 3, 1, 4); + INSERT INTO t2(rowid, a, b, c) VALUES(2, 1, 5, 9); + INSERT INTO t2(rowid, a, b, c) VALUES(3, 2, 6, 5); +} {} +do_update_tests e_update-1.7 -query { + SELECT * FROM t2 +} { + 1 "UPDATE t2 SET a=b+c" {5 1 4 14 5 9 11 6 5} + 2 "UPDATE t2 SET a=b, b=a" {1 5 4 5 14 9 6 11 5} + 3 "UPDATE t2 SET a=c||c, c=NULL" {44 5 {} 99 14 {} 55 11 {}} +} + +# EVIDENCE-OF: R-12619-24112 The optional conflict-clause allows the +# user to nominate a specific constraint conflict resolution algorithm +# to use during this one UPDATE command. +# +do_execsql_test e_update-1.8.0 { + DELETE FROM t3; + INSERT INTO t3 VALUES(1, 'one'); + INSERT INTO t3 VALUES(2, 'two'); + INSERT INTO t3 VALUES(3, 'three'); + INSERT INTO t3 VALUES(4, 'four'); +} {} +foreach {tn sql error ac data } { + 1 "UPDATE t3 SET b='one' WHERE a=3" + {column b is not unique} 1 {1 one 2 two 3 three 4 four} + + 2 "UPDATE OR REPLACE t3 SET b='one' WHERE a=3" + {} 1 {2 two 3 one 4 four} + + 3 "UPDATE OR FAIL t3 SET b='three'" + {column b is not unique} 1 {2 three 3 one 4 four} + + 4 "UPDATE OR IGNORE t3 SET b='three' WHERE a=3" + {} 1 {2 three 3 one 4 four} + + 5 "UPDATE OR ABORT t3 SET b='three' WHERE a=3" + {column b is not unique} 1 {2 three 3 one 4 four} + + 6 "BEGIN" {} 0 {2 three 3 one 4 four} + + 7 "UPDATE t3 SET b='three' WHERE a=3" + {column b is not unique} 0 {2 three 3 one 4 four} + + 8 "UPDATE OR ABORT t3 SET b='three' WHERE a=3" + {column b is not unique} 0 {2 three 3 one 4 four} + + 9 "UPDATE OR FAIL t3 SET b='two'" + {column b is not unique} 0 {2 two 3 one 4 four} + + 10 "UPDATE OR IGNORE t3 SET b='four' WHERE a=3" + {} 0 {2 two 3 one 4 four} + + 11 "UPDATE OR REPLACE t3 SET b='four' WHERE a=3" + {} 0 {2 two 3 four} + + 12 "UPDATE OR ROLLBACK t3 SET b='four'" + {column b is not unique} 1 {2 three 3 one 4 four} +} { + do_catchsql_test e_update-1.8.$tn.1 $sql [list [expr {$error!=""}] $error] + do_execsql_test e_update-1.8.$tn.2 {SELECT * FROM t3} [list {*}$data] + do_test e_update-1.8.$tn.3 {sqlite3_get_autocommit db} $ac +} + + + +# EVIDENCE-OF: R-12123-54095 The table-name specified as part of an +# UPDATE statement within a trigger body must be unqualified. +# +# EVIDENCE-OF: R-09690-36749 In other words, the database-name. prefix +# on the table name of the UPDATE is not allowed within triggers. +# +do_update_tests e_update-2.1 -error { + qualified table names are not allowed on INSERT, UPDATE, and DELETE statements within triggers +} { + 1 { + CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN + UPDATE main.t2 SET a=1, b=2, c=3; + END; + } {} + + 2 { + CREATE TRIGGER tr1 BEFORE UPDATE ON t2 BEGIN + UPDATE aux.t1 SET a=1, b=2; + END; + } {} + + 3 { + CREATE TRIGGER tr1 AFTER DELETE ON t4 BEGIN + UPDATE main.t1 SET a=1, b=2; + END; + } {} +} + +# EVIDENCE-OF: R-06085-13761 Unless the table to which the trigger is +# attached is in the TEMP database, the table being updated by the +# trigger program must reside in the same database as it. +# +do_update_tests e_update-2.2 -error { + no such table: %s +} { + 1 { + CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN + UPDATE t4 SET x=x+1; + END; + INSERT INTO t1 VALUES(1, 2); + } "main.t4" + + 2 { + CREATE TRIGGER aux.tr1 AFTER INSERT ON t5 BEGIN + UPDATE t4 SET x=x+1; + END; + INSERT INTO t5 VALUES(1, 2); + } "aux.t4" +} +do_execsql_test e_update-2.2.X { + DROP TRIGGER tr1; + DROP TRIGGER aux.tr1; +} {} + +# EVIDENCE-OF: R-29512-54644 If the table to which the trigger is +# attached is in the TEMP database, then the unqualified name of the +# table being updated is resolved in the same way as it is for a +# top-level statement (by searching first the TEMP database, then the +# main database, then any other databases in the order they were +# attached). +# +do_execsql_test e_update-2.3.0 { + SELECT 'main', tbl_name FROM main.sqlite_master WHERE type = 'table'; + SELECT 'temp', tbl_name FROM sqlite_temp_master WHERE type = 'table'; + SELECT 'aux', tbl_name FROM aux.sqlite_master WHERE type = 'table'; +} [list {*}{ + main t1 + main t2 + main t3 + main t6 + temp t4 + temp t6 + aux t1 + aux t5 +}] +do_execsql_test e_update-2.3.1 { + DELETE FROM main.t6; + DELETE FROM temp.t6; + INSERT INTO main.t6 VALUES(1, 2); + INSERT INTO temp.t6 VALUES(1, 2); + + CREATE TRIGGER temp.tr1 AFTER INSERT ON t4 BEGIN + UPDATE t6 SET x=x+1; + END; + + INSERT INTO t4 VALUES(1, 2); + SELECT * FROM main.t6; + SELECT * FROM temp.t6; +} {1 2 2 2} +do_execsql_test e_update-2.3.2 { + DELETE FROM main.t1; + DELETE FROM aux.t1; + INSERT INTO main.t1 VALUES(1, 2); + INSERT INTO aux.t1 VALUES(1, 2); + + CREATE TRIGGER temp.tr2 AFTER DELETE ON t4 BEGIN + UPDATE t1 SET a=a+1; + END; + + DELETE FROM t4; + SELECT * FROM main.t1; + SELECT * FROM aux.t1; +} {2 2 1 2} +do_execsql_test e_update-2.3.3 { + DELETE FROM aux.t5; + INSERT INTO aux.t5 VALUES(1, 2); + + INSERT INTO t4 VALUES('x', 'y'); + CREATE TRIGGER temp.tr3 AFTER UPDATE ON t4 BEGIN + UPDATE t5 SET a=a+1; + END; + + UPDATE t4 SET x=10; + SELECT * FROM aux.t5; +} {2 2} + +# EVIDENCE-OF: R-19619-42762 The INDEXED BY and NOT INDEXED clauses are +# not allowed on UPDATE statements within triggers. +# +do_update_tests e_update-2.4 -error { + the %s %s clause is not allowed on UPDATE or DELETE statements within triggers +} { + 1 { + CREATE TRIGGER tr1 AFTER INSERT ON t2 BEGIN + UPDATE t1 INDEXED BY i1 SET a=a+1; + END; + } {INDEXED BY} + + 2 { + CREATE TRIGGER tr1 AFTER INSERT ON t2 BEGIN + UPDATE t1 NOT INDEXED SET a=a+1; + END; + } {NOT INDEXED} +} + +ifcapable update_delete_limit { + +# EVIDENCE-OF: R-57359-59558 The LIMIT and ORDER BY clauses for UPDATE +# are unsupported within triggers, regardless of the compilation options +# used to build SQLite. +# +do_update_tests e_update-2.5 -error { + near "%s": syntax error +} { + 1 { + CREATE TRIGGER tr1 AFTER INSERT ON t2 BEGIN + UPDATE t1 SET a=a+1 LIMIT 10; + END; + } {LIMIT} + + 2 { + CREATE TRIGGER tr1 AFTER INSERT ON t2 BEGIN + UPDATE t1 SET a=a+1 ORDER BY a LIMIT 10; + END; + } {ORDER} + + 3 { + CREATE TRIGGER tr1 AFTER INSERT ON t2 BEGIN + UPDATE t1 SET a=a+1 ORDER BY a LIMIT 10 OFFSET 2; + END; + } {ORDER} + + 4 { + CREATE TRIGGER tr1 AFTER INSERT ON t2 BEGIN + UPDATE t1 SET a=a+1 LIMIT 10 OFFSET 2; + END; + } {LIMIT} +} + +# EVIDENCE-OF: R-59581-44104 If SQLite is built with the +# SQLITE_ENABLE_UPDATE_DELETE_LIMIT compile-time option then the syntax +# of the UPDATE statement is extended with optional ORDER BY and LIMIT +# clauses +# +# -- syntax diagram update-stmt-limited +# +do_update_tests e_update-3.0 { + 1 "UPDATE t1 SET a=b LIMIT 5" {} + 2 "UPDATE t1 SET a=b LIMIT 5-1 OFFSET 2+2" {} + 3 "UPDATE t1 SET a=b LIMIT 2+2, 16/4" {} + 4 "UPDATE t1 SET a=b ORDER BY a LIMIT 5" {} + 5 "UPDATE t1 SET a=b ORDER BY a LIMIT 5-1 OFFSET 2+2" {} + 6 "UPDATE t1 SET a=b ORDER BY a LIMIT 2+2, 16/4" {} + 7 "UPDATE t1 SET a=b WHERE a>2 LIMIT 5" {} + 8 "UPDATE t1 SET a=b WHERE a>2 LIMIT 5-1 OFFSET 2+2" {} + 9 "UPDATE t1 SET a=b WHERE a>2 LIMIT 2+2, 16/4" {} + 10 "UPDATE t1 SET a=b WHERE a>2 ORDER BY a LIMIT 5" {} + 11 "UPDATE t1 SET a=b WHERE a>2 ORDER BY a LIMIT 5-1 OFFSET 2+2" {} + 12 "UPDATE t1 SET a=b WHERE a>2 ORDER BY a LIMIT 2+2, 16/4" {} +} + +do_execsql_test e_update-3.1.0 { + CREATE TABLE t7(q, r, s); + INSERT INTO t7 VALUES(1, 'one', 'X'); + INSERT INTO t7 VALUES(2, 'two', 'X'); + INSERT INTO t7 VALUES(3, 'three', 'X'); + INSERT INTO t7 VALUES(4, 'four', 'X'); + INSERT INTO t7 VALUES(5, 'five', 'X'); + INSERT INTO t7 VALUES(6, 'six', 'X'); + INSERT INTO t7 VALUES(7, 'seven', 'X'); + INSERT INTO t7 VALUES(8, 'eight', 'X'); + INSERT INTO t7 VALUES(9, 'nine', 'X'); + INSERT INTO t7 VALUES(10, 'ten', 'X'); +} {} + +# EVIDENCE-OF: R-58862-44169 If an UPDATE statement has a LIMIT clause, +# the maximum number of rows that will be updated is found by evaluating +# the accompanying expression and casting it to an integer value. +# +do_update_tests e_update-3.1 -query { SELECT s FROM t7 } { + 1 "UPDATE t7 SET s = q LIMIT 5" {1 2 3 4 5 X X X X X} + 2 "UPDATE t7 SET s = r WHERE q>2 LIMIT 4" {1 2 three four five six X X X X} + 3 "UPDATE t7 SET s = q LIMIT 0" {1 2 three four five six X X X X} +} + +# EVIDENCE-OF: R-63582-45120 A negative value is interpreted as "no limit". +# +do_update_tests e_update-3.2 -query { SELECT s FROM t7 } { + 1 "UPDATE t7 SET s = q LIMIT -1" {1 2 3 4 5 6 7 8 9 10} + 2 "UPDATE t7 SET s = r WHERE q>4 LIMIT -1" + {1 2 3 4 five six seven eight nine ten} + 3 "UPDATE t7 SET s = 'X' LIMIT -1" {X X X X X X X X X X} +} + +# EVIDENCE-OF: R-18628-11938 If the LIMIT expression evaluates to +# non-negative value N and the UPDATE statement has an ORDER BY clause, +# then all rows that would be updated in the absence of the LIMIT clause +# are sorted according to the ORDER BY and the first N updated. +# +do_update_tests e_update-3.3 -query { SELECT s FROM t7 } { + 1 "UPDATE t7 SET s = q ORDER BY r LIMIT 3" {X X X 4 5 X X 8 X X} + 2 "UPDATE t7 SET s = r ORDER BY r DESC LIMIT 2" {X two three 4 5 X X 8 X X} + 3 "UPDATE t7 SET s = q ORDER BY q DESC LIMIT 5" {X two three 4 5 6 7 8 9 10} + + X "UPDATE t7 SET s = 'X'" {X X X X X X X X X X} +} + +# EVIDENCE-OF: R-30955-38324 If the UPDATE statement also has an OFFSET +# clause, then it is similarly evaluated and cast to an integer value. +# If the OFFSET expression evaluates to a non-negative value M, then the +# first M rows are skipped and the following N rows updated instead. +# +do_update_tests e_update-3.3 -query { SELECT s FROM t7 } { + 1 "UPDATE t7 SET s = q ORDER BY q LIMIT 3 OFFSET 2" {X X 3 4 5 X X X X X} + 2 "UPDATE t7 SET s = q ORDER BY q DESC LIMIT 2, 3 " {X X 3 4 5 6 7 8 X X} + + X "UPDATE t7 SET s = 'X'" {X X X X X X X X X X} +} + +# EVIDENCE-OF: R-19486-35828 If the UPDATE statement has no ORDER BY +# clause, then all rows that would be updated in the absence of the +# LIMIT clause are assembled in an arbitrary order before applying the +# LIMIT and OFFSET clauses to determine which are actually updated. +# +# In practice, "arbitrary order" is rowid order. This is also tested +# by e_update-3.2.* above. +# +do_update_tests e_update-3.4 -query { SELECT s FROM t7 } { + 1 "UPDATE t7 SET s = q LIMIT 4, 2" {X X X X 5 6 X X X X} + 2 "UPDATE t7 SET s = q LIMIT 2 OFFSET 7" {X X X X 5 6 X 8 9 X} +} + +# EVIDENCE-OF: R-10927-26133 The ORDER BY clause on an UPDATE statement +# is used only to determine which rows fall within the LIMIT. The order +# in which rows are modified is arbitrary and is not influenced by the +# ORDER BY clause. +# +do_execsql_test e_update-3.5.0 { + CREATE TABLE t8(x); + CREATE TRIGGER tr7 BEFORE UPDATE ON t7 BEGIN + INSERT INTO t8 VALUES(old.q); + END; +} {} +do_update_tests e_update-3.5 -query { SELECT x FROM t8 ; DELETE FROM t8 } { + 1 "UPDATE t7 SET s = q ORDER BY r LIMIT -1" {1 2 3 4 5 6 7 8 9 10} + 2 "UPDATE t7 SET s = q ORDER BY r ASC LIMIT -1" {1 2 3 4 5 6 7 8 9 10} + 3 "UPDATE t7 SET s = q ORDER BY r DESC LIMIT -1" {1 2 3 4 5 6 7 8 9 10} + 4 "UPDATE t7 SET s = q ORDER BY q DESC LIMIT 5" {6 7 8 9 10} +} + + +} ;# ifcapable update_delete_limit + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_uri.test b/components/external/SQLite-3.8.1/test/e_uri.test new file mode 100644 index 0000000000000000000000000000000000000000..a8865cad28fc7cc3a1b74a1021c7a55b2e0e03f9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_uri.test @@ -0,0 +1,457 @@ +# 2011 May 06 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix e_uri + +db close + +proc parse_uri {uri} { + testvfs tvfs2 + testvfs tvfs + tvfs filter xOpen + tvfs script parse_uri_open_cb + + set ::uri_open [list] + set DB [sqlite3_open_v2 $uri { + SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE SQLITE_OPEN_WAL + } tvfs] + sqlite3_close $DB + tvfs delete + tvfs2 delete + + set ::uri_open +} +proc parse_uri_open_cb {method file arglist} { + set ::uri_open [list $file $arglist] +} + +proc open_uri_error {uri} { + set flags {SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE SQLITE_OPEN_WAL} + set DB [sqlite3_open_v2 $uri $flags ""] + set e [sqlite3_errmsg $DB] + sqlite3_close $DB + set e +} + +# EVIDENCE-OF: R-35840-33204 If URI filename interpretation is enabled, +# and the filename argument begins with "file:", then the filename is +# interpreted as a URI. +# +# EVIDENCE-OF: R-24124-56960 URI filename interpretation is enabled if +# the SQLITE_OPEN_URI flag is set in the fourth argument to +# sqlite3_open_v2(), or if it has been enabled globally using the +# SQLITE_CONFIG_URI option with the sqlite3_config() method or by the +# SQLITE_USE_URI compile-time option. +# +if {$tcl_platform(platform) == "unix"} { + set flags [list SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE] + + # Tests with SQLITE_CONFIG_URI configured to false. URI intepretation is + # only enabled if the SQLITE_OPEN_URI flag is specified. + sqlite3_shutdown + sqlite3_config_uri 0 + do_test 1.1 { + forcedelete file:test.db test.db + set DB [sqlite3_open_v2 file:test.db [concat $flags SQLITE_OPEN_URI] ""] + list [file exists file:test.db] [file exists test.db] + } {0 1} + do_test 1.2 { + forcedelete file:test.db2 test.db2 + set STMT [sqlite3_prepare $DB "ATTACH 'file:test.db2' AS aux" -1 dummy] + sqlite3_step $STMT + sqlite3_finalize $STMT + list [file exists file:test.db2] [file exists test.db2] + } {0 1} + sqlite3_close $DB + do_test 1.3 { + forcedelete file:test.db test.db + set DB [sqlite3_open_v2 file:test.db [concat $flags] ""] + list [file exists file:test.db] [file exists test.db] + } {1 0} + do_test 1.4 { + forcedelete file:test.db2 test.db2 + set STMT [sqlite3_prepare $DB "ATTACH 'file:test.db2' AS aux" -1 dummy] + sqlite3_step $STMT + sqlite3_finalize $STMT + list [file exists file:test.db2] [file exists test.db2] + } {1 0} + sqlite3_close $DB + + # Tests with SQLITE_CONFIG_URI configured to true. URI intepretation is + # enabled with or without SQLITE_OPEN_URI. + # + sqlite3_shutdown + sqlite3_config_uri 1 + do_test 1.5 { + forcedelete file:test.db test.db + set DB [sqlite3_open_v2 file:test.db [concat $flags SQLITE_OPEN_URI] ""] + list [file exists file:test.db] [file exists test.db] + } {0 1} + do_test 1.6 { + forcedelete file:test.db2 test.db2 + set STMT [sqlite3_prepare $DB "ATTACH 'file:test.db2' AS aux" -1 dummy] + sqlite3_step $STMT + sqlite3_finalize $STMT + list [file exists file:test.db2] [file exists test.db2] + } {0 1} + sqlite3_close $DB + do_test 1.7 { + forcedelete file:test.db test.db + set DB [sqlite3_open_v2 file:test.db [concat $flags] ""] + list [file exists file:test.db] [file exists test.db] + } {0 1} + do_test 1.8 { + forcedelete file:test.db2 test.db2 + set STMT [sqlite3_prepare $DB "ATTACH 'file:test.db2' AS aux" -1 dummy] + sqlite3_step $STMT + sqlite3_finalize $STMT + list [file exists file:test.db2] [file exists test.db2] + } {0 1} + sqlite3_close $DB +} + +# ensure uri processing enabled for the rest of the tests +sqlite3_shutdown +sqlite3_config_uri 1 + +# EVIDENCE-OF: R-17482-00398 If the authority is not an empty string or +# "localhost", an error is returned to the caller. +# +if {$tcl_platform(platform) == "unix"} { + set flags [list SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE SQLITE_OPEN_URI] + foreach {tn uri error} " + 1 {file://localhost[test_pwd /]test.db} {not an error} + 2 {file://[test_pwd /]test.db} {not an error} + 3 {file://x[test_pwd /]test.db} {invalid uri authority: x} + 4 {file://invalid[test_pwd /]test.db} {invalid uri authority: invalid} + " { + do_test 2.$tn { + set DB [sqlite3_open_v2 $uri $flags ""] + set e [sqlite3_errmsg $DB] + sqlite3_close $DB + set e + } $error + } +} + +# EVIDENCE-OF: R-45981-25528 The fragment component of a URI, if +# present, is ignored. +# +# It is difficult to test that something is ignored correctly. So these tests +# just show that adding a fragment does not interfere with the pathname or +# parameters passed through to the VFS xOpen() methods. +# +foreach {tn uri parse} " + 1 {file:test.db#abc} {[test_pwd / {}]test.db {}} + 2 {file:test.db?a=b#abc} {[test_pwd / {}]test.db {a b}} + 3 {file:test.db?a=b#?c=d} {[test_pwd / {}]test.db {a b}} +" { + do_filepath_test 3.$tn { parse_uri $uri } $parse +} + +# EVIDENCE-OF: R-62557-09390 SQLite uses the path component of the URI +# as the name of the disk file which contains the database. +# +# EVIDENCE-OF: R-28659-11035 If the path begins with a '/' character, +# then it is interpreted as an absolute path. +# +# EVIDENCE-OF: R-46234-61323 If the path does not begin with a '/' +# (meaning that the authority section is omitted from the URI) then the +# path is interpreted as a relative path. +# +foreach {tn uri parse} " + 1 {file:test.db} {[test_pwd / {}]test.db {}} + 2 {file:/test.db} {/test.db {}} + 3 {file:///test.db} {/test.db {}} + 4 {file://localhost/test.db} {/test.db {}} + 5 {file:/a/b/c/test.db} {/a/b/c/test.db {}} +" { + do_filepath_test 4.$tn { parse_uri $uri } $parse +} + +# EVIDENCE-OF: R-01612-30877 The "vfs" parameter may be used to specify +# the name of a VFS object that provides the operating system interface +# that should be used to access the database file on disk. +# +# The above is tested by cases 1.* below. +# +# EVIDENCE-OF: R-52293-58497 If this option is set to an empty string +# the default VFS object is used. +# +# The above is tested by cases 2.* below. +# +# EVIDENCE-OF: R-31855-18665 If sqlite3_open_v2() is used and the vfs +# option is present, then the VFS specified by the option takes +# precedence over the value passed as the fourth parameter to +# sqlite3_open_v2(). +# +# The above is tested by cases 3.* below. +# +proc vfs_open_cb {name args} { + set ::vfs $name +} +foreach {name default} {vfs1 0 vfs2 0 vfs3 1} { + testvfs $name -default $default + $name filter xOpen + $name script [list vfs_open_cb $name] +} +foreach {tn uri defvfs vfs} { + 1.1 "file:test.db?vfs=vfs1" "" vfs1 + 1.2 "file:test.db?vfs=vfs2" "" vfs2 + + 2.1 "file:test.db" vfs1 vfs1 + 2.2 "file:test.db?vfs=" vfs1 vfs3 + + 3.1 "file:test.db?vfs=vfs1" vfs2 vfs1 + 3.2 "file:test.db?vfs=vfs2" vfs1 vfs2 + 3.3 "file:test.db?xvfs=vfs1" vfs2 vfs2 + 3.4 "file:test.db?xvfs=vfs2" vfs1 vfs1 +} { + do_test 5.$tn { + set flags [list SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE SQLITE_OPEN_URI] + sqlite3_close [ + sqlite3_open_v2 $uri $flags $defvfs + ] + set ::vfs + } $vfs +} +vfs1 delete +vfs2 delete +vfs3 delete + +# EVIDENCE-OF: R-48365-36308 Specifying an unknown VFS is an error. +# +set flags [list SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE SQLITE_OPEN_URI] +do_test 6.1 { + set DB [sqlite3_open_v2 file:test.db?vfs=nosuchvfs $flags ""] + set errmsg [sqlite3_errmsg $DB] + sqlite3_close $DB + set errmsg +} {no such vfs: nosuchvfs} + + +# EVIDENCE-OF: R-44013-13102 The mode parameter may be set to either +# "ro", "rw", "rwc", or "memory". Attempting to set it to any other +# value is an error +# +sqlite3 db test.db +db close +foreach {tn uri error} " + 1 {file:test.db?mode=ro} {not an error} + 2 {file:test.db?mode=rw} {not an error} + 3 {file:test.db?mode=rwc} {not an error} + 4 {file:test.db?mode=Ro} {no such access mode: Ro} + 5 {file:test.db?mode=Rw} {no such access mode: Rw} + 6 {file:test.db?mode=Rwc} {no such access mode: Rwc} + 7 {file:test.db?mode=memory} {not an error} + 8 {file:test.db?mode=MEMORY} {no such access mode: MEMORY} +" { + do_test 7.$tn { open_uri_error $uri } $error +} + + +# EVIDENCE-OF: R-43036-46756 If "ro" is specified, then the database is +# opened for read-only access, just as if the SQLITE_OPEN_READONLY flag +# had been set in the third argument to sqlite3_open_v2(). +# +# EVIDENCE-OF: R-40137-26050 If the mode option is set to "rw", then the +# database is opened for read-write (but not create) access, as if +# SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had been set. +# +# EVIDENCE-OF: R-26845-32976 Value "rwc" is equivalent to setting both +# SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. +# +foreach {tn uri read write create} { + 1 {file:test.db?mode=ro} 1 0 0 + 2 {file:test.db?mode=rw} 1 1 0 + 3 {file:test.db?mode=rwc} 1 1 1 +} { + set RES(c,0) {1 {unable to open database file}} + set RES(c,1) {0 {}} + set RES(w,0) {1 {attempt to write a readonly database}} + set RES(w,1) {0 {}} + set RES(r,0) {1 {this never happens}} + set RES(r,1) {0 {a b}} + + # Test CREATE access: + forcedelete test.db + do_test 8.$tn.c { list [catch { sqlite3 db $uri } msg] $msg } $RES(c,$create) + catch { db close } + + sqlite3 db test.db + db eval { CREATE TABLE t1(a, b) ; INSERT INTO t1 VALUES('a', 'b') ;} + db close + + # Test READ access: + do_test 8.$tn.r { + sqlite3 db $uri + catchsql { SELECT * FROM t1 } + } $RES(r,$read) + + # Test WRITE access: + do_test 8.$tn.w { + sqlite3 db $uri + catchsql { INSERT INTO t1 VALUES(1, 2) } + } $RES(w,$write) + + catch {db close} +} + +# EVIDENCE-OF: R-20590-08726 It is an error to specify a value for the +# mode parameter that is less restrictive than that specified by the +# flags passed in the third parameter to sqlite3_open_v2(). +# +forcedelete test.db +sqlite3 db test.db +db close +foreach {tn uri flags error} { + 1 {file:test.db?mode=ro} ro {not an error} + 2 {file:test.db?mode=ro} rw {not an error} + 3 {file:test.db?mode=ro} rwc {not an error} + + 4 {file:test.db?mode=rw} ro {access mode not allowed: rw} + 5 {file:test.db?mode=rw} rw {not an error} + 6 {file:test.db?mode=rw} rwc {not an error} + + 7 {file:test.db?mode=rwc} ro {access mode not allowed: rwc} + 8 {file:test.db?mode=rwc} rw {access mode not allowed: rwc} + 9 {file:test.db?mode=rwc} rwc {not an error} +} { + set f(ro) [list SQLITE_OPEN_READONLY SQLITE_OPEN_URI] + set f(rw) [list SQLITE_OPEN_READWRITE SQLITE_OPEN_URI] + set f(rwc) [list SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE SQLITE_OPEN_URI] + + set DB [sqlite3_open_v2 $uri $f($flags) ""] + set e [sqlite3_errmsg $DB] + sqlite3_close $DB + + do_test 9.$tn { set e } $error +} + +# EVIDENCE-OF: R-23182-54295 The cache parameter may be set to either +# "shared" or "private". +sqlite3 db test.db +db close +foreach {tn uri error} " + 1 {file:test.db?cache=private} {not an error} + 2 {file:test.db?cache=shared} {not an error} + 3 {file:test.db?cache=yes} {no such cache mode: yes} + 4 {file:test.db?cache=} {no such cache mode: } +" { + do_test 10.$tn { open_uri_error $uri } $error +} + +# EVIDENCE-OF: R-23027-03515 Setting it to "shared" is equivalent to +# setting the SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed +# to sqlite3_open_v2(). +# +# EVIDENCE-OF: R-49793-28525 Setting the cache parameter to "private" is +# equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. +# +# EVIDENCE-OF: R-31773-41793 If sqlite3_open_v2() is used and the +# "cache" parameter is present in a URI filename, its value overrides +# any behavior requested by setting SQLITE_OPEN_PRIVATECACHE or +# SQLITE_OPEN_SHAREDCACHE flag. +# +set orig [sqlite3_enable_shared_cache] +foreach {tn uri flags shared_default isshared} { + 1.1 "file:test.db" "" 0 0 + 1.2 "file:test.db" "" 1 1 + 1.3 "file:test.db" private 0 0 + 1.4 "file:test.db" private 1 0 + 1.5 "file:test.db" shared 0 1 + 1.6 "file:test.db" shared 1 1 + + 2.1 "file:test.db?cache=private" "" 0 0 + 2.2 "file:test.db?cache=private" "" 1 0 + 2.3 "file:test.db?cache=private" private 0 0 + 2.4 "file:test.db?cache=private" private 1 0 + 2.5 "file:test.db?cache=private" shared 0 0 + 2.6 "file:test.db?cache=private" shared 1 0 + + 3.1 "file:test.db?cache=shared" "" 0 1 + 3.2 "file:test.db?cache=shared" "" 1 1 + 3.3 "file:test.db?cache=shared" private 0 1 + 3.4 "file:test.db?cache=shared" private 1 1 + 3.5 "file:test.db?cache=shared" shared 0 1 + 3.6 "file:test.db?cache=shared" shared 1 1 +} { + forcedelete test.db + sqlite3_enable_shared_cache 1 + sqlite3 db test.db + sqlite3_enable_shared_cache 0 + + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('ok'); + } + + unset -nocomplain f + set f() {SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE SQLITE_OPEN_URI} + set f(shared) [concat $f() SQLITE_OPEN_SHAREDCACHE] + set f(private) [concat $f() SQLITE_OPEN_PRIVATECACHE] + + sqlite3_enable_shared_cache $shared_default + set DB [sqlite3_open_v2 $uri $f($flags) ""] + + set STMT [sqlite3_prepare $DB "SELECT * FROM t1" -1 dummy] + + db eval { + BEGIN; + INSERT INTO t1 VALUES('ko'); + } + + sqlite3_step $STMT + sqlite3_finalize $STMT + + set RES(0) {not an error} + set RES(1) {database table is locked: t1} + + do_test 11.$tn { sqlite3_errmsg $DB } $RES($isshared) + + sqlite3_close $DB + db close +} +sqlite3_enable_shared_cache $orig + +# EVIDENCE-OF: R-63472-46769 Specifying an unknown parameter in the +# query component of a URI is not an error. +# +do_filepath_test 12.1 { + parse_uri file://localhost/test.db?an=unknown¶meter=is&ok= +} {/test.db {an unknown parameter is ok {}}} +do_filepath_test 12.2 { + parse_uri file://localhost/test.db?an&unknown¶meter&is&ok +} {/test.db {an {} unknown {} parameter {} is {} ok {}}} + +# EVIDENCE-OF: R-27458-04043 URI hexadecimal escape sequences (%HH) are +# supported within the path and query components of a URI. +# +# EVIDENCE-OF: R-52765-50368 Before the path or query components of a +# URI filename are interpreted, they are encoded using UTF-8 and all +# hexadecimal escape sequences replaced by a single byte containing the +# corresponding octet. +# +# The second of the two statements above is tested by creating a +# multi-byte utf-8 character using a sequence of %HH escapes. +# +foreach {tn uri parse} " + 1 {file:/test.%64%62} {/test.db {}} + 2 {file:/test.db?%68%65%6c%6c%6f=%77%6f%72%6c%64} {/test.db {hello world}} + 3 {file:/%C3%BF.db} {/\xFF.db {}} +" { + do_filepath_test 13.$tn { parse_uri $uri } $parse +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/e_vacuum.test b/components/external/SQLite-3.8.1/test/e_vacuum.test new file mode 100644 index 0000000000000000000000000000000000000000..99b31aaca427dcd47d88ac040ace7a229733e52c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/e_vacuum.test @@ -0,0 +1,303 @@ +# 2010 September 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that the "testable statements" in +# the lang_vacuum.html document are correct. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +sqlite3_test_control_pending_byte 0x1000000 + +proc create_db {{sql ""}} { + catch { db close } + forcedelete test.db + sqlite3 db test.db + + db transaction { + execsql { PRAGMA page_size = 1024; } + execsql $sql + execsql { + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + INSERT INTO t1 VALUES(1, randomblob(400)); + INSERT INTO t1 SELECT a+1, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+2, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+4, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+8, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+16, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+32, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+64, randomblob(400) FROM t1; + + CREATE TABLE t2(a PRIMARY KEY, b UNIQUE); + INSERT INTO t2 SELECT * FROM t1; + } + } + + return [expr {[file size test.db] / 1024}] +} + +# This proc returns the number of contiguous blocks of pages that make up +# the table or index named by the only argument. For example, if the table +# occupies database pages 3, 4, 8 and 9, then this command returns 2 (there +# are 2 fragments - one consisting of pages 3 and 4, the other of fragments +# 8 and 9). +# +proc fragment_count {name} { + execsql { CREATE VIRTUAL TABLE temp.stat USING dbstat } + set nFrag 1 + db eval {SELECT pageno FROM stat WHERE name = 't1' ORDER BY pageno} { + if {[info exists prevpageno] && $prevpageno != $pageno-1} { + incr nFrag + } + set prevpageno $pageno + } + execsql { DROP TABLE temp.stat } + set nFrag +} + + +# -- syntax diagram vacuum-stmt +# +do_execsql_test e_vacuum-0.1 { VACUUM } {} + +# EVIDENCE-OF: R-51469-36013 Unless SQLite is running in +# "auto_vacuum=FULL" mode, when a large amount of data is deleted from +# the database file it leaves behind empty space, or "free" database +# pages. +# +# EVIDENCE-OF: R-60541-63059 Running VACUUM to rebuild the database +# reclaims this space and reduces the size of the database file. +# +foreach {tn avmode sz} { + 1 none 7 + 2 full 8 + 3 incremental 8 +} { + set nPage [create_db "PRAGMA auto_vacuum = $avmode"] + + do_execsql_test e_vacuum-1.1.$tn.1 { + DELETE FROM t1; + DELETE FROM t2; + } {} + + if {$avmode == "full"} { + # This branch tests the "unless ... auto_vacuum=FULL" in the requirement + # above. If auto_vacuum is set to FULL, then no empty space is left in + # the database file. + do_execsql_test e_vacuum-1.1.$tn.2 {PRAGMA freelist_count} 0 + } else { + set freelist [expr {$nPage - $sz}] + if {$avmode == "incremental"} { + # The page size is 1024 bytes. Therefore, assuming the database contains + # somewhere between 207 and 411 pages (it does), there are 2 pointer-map + # pages. + incr freelist -2 + } + do_execsql_test e_vacuum-1.1.$tn.3 {PRAGMA freelist_count} $freelist + do_execsql_test e_vacuum-1.1.$tn.4 {VACUUM} {} + } + + do_test e_vacuum-1.1.$tn.5 { expr {[file size test.db] / 1024} } $sz +} + +# EVIDENCE-OF: R-50943-18433 Frequent inserts, updates, and deletes can +# cause the database file to become fragmented - where data for a single +# table or index is scattered around the database file. +# +# EVIDENCE-OF: R-05791-54928 Running VACUUM ensures that each table and +# index is largely stored contiguously within the database file. +# +# e_vacuum-1.2.1 - Perform many INSERT, UPDATE and DELETE ops on table t1. +# e_vacuum-1.2.2 - Verify that t1 and its indexes are now quite fragmented. +# e_vacuum-1.2.3 - Run VACUUM. +# e_vacuum-1.2.4 - Verify that t1 and its indexes are now much +# less fragmented. +# +ifcapable vtab&&compound { + create_db + register_dbstat_vtab db + do_execsql_test e_vacuum-1.2.1 { + DELETE FROM t1 WHERE a%2; + INSERT INTO t1 SELECT b, a FROM t2 WHERE a%2; + UPDATE t1 SET b=randomblob(600) WHERE (a%2)==0; + } {} + + do_test e_vacuum-1.2.2.1 { expr [fragment_count t1]>100 } 1 + do_test e_vacuum-1.2.2.2 { expr [fragment_count sqlite_autoindex_t1_1]>100 } 1 + do_test e_vacuum-1.2.2.3 { expr [fragment_count sqlite_autoindex_t1_2]>100 } 1 + + do_execsql_test e_vacuum-1.2.3 { VACUUM } {} + + # In practice, the tables and indexes each end up stored as two fragments - + # one containing the root page and another containing all other pages. + # + do_test e_vacuum-1.2.4.1 { fragment_count t1 } 2 + do_test e_vacuum-1.2.4.2 { fragment_count sqlite_autoindex_t1_1 } 2 + do_test e_vacuum-1.2.4.3 { fragment_count sqlite_autoindex_t1_2 } 2 +} + +# EVIDENCE-OF: R-20474-44465 Normally, the database page_size and +# whether or not the database supports auto_vacuum must be configured +# before the database file is actually created. +# +do_test e_vacuum-1.3.1.1 { + create_db "PRAGMA page_size = 1024 ; PRAGMA auto_vacuum = FULL" + execsql { PRAGMA page_size ; PRAGMA auto_vacuum } +} {1024 1} +do_test e_vacuum-1.3.1.2 { + execsql { PRAGMA page_size = 2048 } + execsql { PRAGMA auto_vacuum = NONE } + execsql { PRAGMA page_size ; PRAGMA auto_vacuum } +} {1024 1} + +# EVIDENCE-OF: R-08570-19916 However, when not in write-ahead log mode, +# the page_size and/or auto_vacuum properties of an existing database +# may be changed by using the page_size and/or pragma auto_vacuum +# pragmas and then immediately VACUUMing the database. +# +do_test e_vacuum-1.3.2.1 { + execsql { PRAGMA journal_mode = delete } + execsql { PRAGMA page_size = 2048 } + execsql { PRAGMA auto_vacuum = NONE } + execsql VACUUM + execsql { PRAGMA page_size ; PRAGMA auto_vacuum } +} {2048 0} + +# EVIDENCE-OF: R-48521-51450 When in write-ahead log mode, only the +# auto_vacuum support property can be changed using VACUUM. +# +ifcapable wal { +do_test e_vacuum-1.3.3.1 { + execsql { PRAGMA journal_mode = wal } + execsql { PRAGMA page_size ; PRAGMA auto_vacuum } +} {2048 0} +do_test e_vacuum-1.3.3.2 { + execsql { PRAGMA page_size = 1024 } + execsql { PRAGMA auto_vacuum = FULL } + execsql VACUUM + execsql { PRAGMA page_size ; PRAGMA auto_vacuum } +} {2048 1} +} + +# EVIDENCE-OF: R-38001-03952 VACUUM only works on the main database. It +# is not possible to VACUUM an attached database file. +forcedelete test.db2 +create_db { PRAGMA auto_vacuum = NONE } +do_execsql_test e_vacuum-2.1.1 { + ATTACH 'test.db2' AS aux; + PRAGMA aux.page_size = 1024; + CREATE TABLE aux.t3 AS SELECT * FROM t1; + DELETE FROM t3; +} {} +set original_size [file size test.db2] + +# Try everything we can think of to get the aux database vacuumed: +do_execsql_test e_vacuum-2.1.3 { VACUUM } {} +do_execsql_test e_vacuum-2.1.4 { VACUUM aux } {} +do_execsql_test e_vacuum-2.1.5 { VACUUM 'test.db2' } {} + +# Despite our efforts, space in the aux database has not been reclaimed: +do_test e_vacuum-2.1.6 { expr {[file size test.db2]==$::original_size} } 1 + +# EVIDENCE-OF: R-17495-17419 The VACUUM command may change the ROWIDs of +# entries in any tables that do not have an explicit INTEGER PRIMARY +# KEY. +# +# Tests e_vacuum-3.1.1 - 3.1.2 demonstrate that rowids can change when +# a database is VACUUMed. Tests e_vacuum-3.1.3 - 3.1.4 show that adding +# an INTEGER PRIMARY KEY column to a table stops this from happening. +# +do_execsql_test e_vacuum-3.1.1 { + CREATE TABLE t4(x); + INSERT INTO t4(x) VALUES('x'); + INSERT INTO t4(x) VALUES('y'); + INSERT INTO t4(x) VALUES('z'); + DELETE FROM t4 WHERE x = 'y'; + SELECT rowid, x FROM t4; +} {1 x 3 z} +do_execsql_test e_vacuum-3.1.2 { + VACUUM; + SELECT rowid, x FROM t4; +} {1 x 2 z} + +do_execsql_test e_vacuum-3.1.3 { + CREATE TABLE t5(x, y INTEGER PRIMARY KEY); + INSERT INTO t5(x) VALUES('x'); + INSERT INTO t5(x) VALUES('y'); + INSERT INTO t5(x) VALUES('z'); + DELETE FROM t5 WHERE x = 'y'; + SELECT rowid, x FROM t5; +} {1 x 3 z} +do_execsql_test e_vacuum-3.1.4 { + VACUUM; + SELECT rowid, x FROM t5; +} {1 x 3 z} + +# EVIDENCE-OF: R-49563-33883 A VACUUM will fail if there is an open +# transaction, or if there are one or more active SQL statements when it +# is run. +# +do_execsql_test e_vacuum-3.2.1.1 { BEGIN } {} +do_catchsql_test e_vacuum-3.2.1.2 { + VACUUM +} {1 {cannot VACUUM from within a transaction}} +do_execsql_test e_vacuum-3.2.1.3 { COMMIT } {} +do_execsql_test e_vacuum-3.2.1.4 { VACUUM } {} +do_execsql_test e_vacuum-3.2.1.5 { SAVEPOINT x } {} +do_catchsql_test e_vacuum-3.2.1.6 { + VACUUM +} {1 {cannot VACUUM from within a transaction}} +do_execsql_test e_vacuum-3.2.1.7 { COMMIT } {} +do_execsql_test e_vacuum-3.2.1.8 { VACUUM } {} + +create_db +do_test e_vacuum-3.2.2.1 { + set res "" + db eval { SELECT a FROM t1 } { + if {$a == 10} { set res [catchsql VACUUM] } + } + set res +} {1 {cannot VACUUM - SQL statements in progress}} + + +# EVIDENCE-OF: R-38735-12540 As of SQLite version 3.1, an alternative to +# using the VACUUM command to reclaim space after data has been deleted +# is auto-vacuum mode, enabled using the auto_vacuum pragma. +# +do_test e_vacuum-3.3.1 { + create_db { PRAGMA auto_vacuum = FULL } + execsql { PRAGMA auto_vacuum } +} {1} + +# EVIDENCE-OF: R-64844-34873 When auto_vacuum is enabled for a database +# free pages may be reclaimed after deleting data, causing the file to +# shrink, without rebuilding the entire database using VACUUM. +# +do_test e_vacuum-3.3.2.1 { + create_db { PRAGMA auto_vacuum = FULL } + execsql { + DELETE FROM t1; + DELETE FROM t2; + } + expr {[file size test.db] / 1024} +} {8} +do_test e_vacuum-3.3.2.2 { + create_db { PRAGMA auto_vacuum = INCREMENTAL } + execsql { + DELETE FROM t1; + DELETE FROM t2; + PRAGMA incremental_vacuum; + } + expr {[file size test.db] / 1024} +} {8} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/enc.test b/components/external/SQLite-3.8.1/test/enc.test new file mode 100644 index 0000000000000000000000000000000000000000..5c24bbb7f65f634365a5c0b4c49c3289b752811c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/enc.test @@ -0,0 +1,172 @@ +# 2002 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus of +# this file is testing the SQLite routines used for converting between the +# various suported unicode encodings (UTF-8, UTF-16, UTF-16le and +# UTF-16be). +# +# $Id: enc.test,v 1.7 2007/05/23 16:23:09 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Skip this test if the build does not support multiple encodings. +# +ifcapable {!utf16} { + finish_test + return +} + +proc do_bincmp_test {testname got expect} { + binary scan $expect \c* expectvals + binary scan $got \c* gotvals + do_test $testname [list set dummy $gotvals] $expectvals +} + +# $utf16 is a UTF-16 encoded string. Swap each pair of bytes around +# to change the byte-order of the string. +proc swap_byte_order {utf16} { + binary scan $utf16 \c* ints + + foreach {a b} $ints { + lappend ints2 $b + lappend ints2 $a + } + + return [binary format \c* $ints2] +} + +# +# Test that the SQLite routines for converting between UTF encodings +# produce the same results as their TCL counterparts. +# +# $testname is the prefix to be used for the test names. +# $str is a string to use for testing (encoded in UTF-8, as normal for TCL). +# +# The test procedure is: +# 1. Convert the string from UTF-8 to UTF-16le and check that the TCL and +# SQLite routines produce the same results. +# +# 2. Convert the string from UTF-8 to UTF-16be and check that the TCL and +# SQLite routines produce the same results. +# +# 3. Use the SQLite routines to convert the native machine order UTF-16 +# representation back to the original UTF-8. Check that the result +# matches the original representation. +# +# 4. Add a byte-order mark to each of the UTF-16 representations and +# check that the SQLite routines can convert them back to UTF-8. For +# byte-order mark info, refer to section 3.10 of the unicode standard. +# +# 5. Take the byte-order marked UTF-16 strings from step 4 and ensure +# that SQLite can convert them both to native byte order UTF-16 +# strings, sans BOM. +# +# Coverage: +# +# sqlite_utf8to16be (step 2) +# sqlite_utf8to16le (step 1) +# sqlite_utf16to8 (steps 3, 4) +# sqlite_utf16to16le (step 5) +# sqlite_utf16to16be (step 5) +# +proc test_conversion {testname str} { + + # Step 1. + set utf16le_sqlite3 [test_translate $str UTF8 UTF16LE] + set utf16le_tcl [encoding convertto unicode $str] + append utf16le_tcl "\x00\x00" + if { $::tcl_platform(byteOrder)!="littleEndian" } { + set utf16le_tcl [swap_byte_order $utf16le_tcl] + } + do_bincmp_test $testname.1 $utf16le_sqlite3 $utf16le_tcl + set utf16le $utf16le_tcl + + # Step 2. + set utf16be_sqlite3 [test_translate $str UTF8 UTF16BE] + set utf16be_tcl [encoding convertto unicode $str] + append utf16be_tcl "\x00\x00" + if { $::tcl_platform(byteOrder)=="littleEndian" } { + set utf16be_tcl [swap_byte_order $utf16be_tcl] + } + do_bincmp_test $testname.2 $utf16be_sqlite3 $utf16be_tcl + set utf16be $utf16be_tcl + + # Step 3. + if { $::tcl_platform(byteOrder)=="littleEndian" } { + set utf16 $utf16le + } else { + set utf16 $utf16be + } + set utf8_sqlite3 [test_translate $utf16 UTF16 UTF8] + do_bincmp_test $testname.3 $utf8_sqlite3 [binarize $str] + + # Step 4 (little endian). + append utf16le_bom "\xFF\xFE" $utf16le + set utf8_sqlite3 [test_translate $utf16le_bom UTF16 UTF8 1] + do_bincmp_test $testname.4.le $utf8_sqlite3 [binarize $str] + + # Step 4 (big endian). + append utf16be_bom "\xFE\xFF" $utf16be + set utf8_sqlite3 [test_translate $utf16be_bom UTF16 UTF8] + do_bincmp_test $testname.4.be $utf8_sqlite3 [binarize $str] + + # Step 5 (little endian to little endian). + set utf16_sqlite3 [test_translate $utf16le_bom UTF16LE UTF16LE] + do_bincmp_test $testname.5.le.le $utf16_sqlite3 $utf16le + + # Step 5 (big endian to big endian). + set utf16_sqlite3 [test_translate $utf16be_bom UTF16 UTF16BE] + do_bincmp_test $testname.5.be.be $utf16_sqlite3 $utf16be + + # Step 5 (big endian to little endian). + set utf16_sqlite3 [test_translate $utf16be_bom UTF16 UTF16LE] + do_bincmp_test $testname.5.be.le $utf16_sqlite3 $utf16le + + # Step 5 (little endian to big endian). + set utf16_sqlite3 [test_translate $utf16le_bom UTF16 UTF16BE] + do_bincmp_test $testname.5.le.be $utf16_sqlite3 $utf16be +} + +translate_selftest + +test_conversion enc-1 "hello world" +test_conversion enc-2 "sqlite" +test_conversion enc-3 "" +test_conversion enc-X "\u0100" +test_conversion enc-4 "\u1234" +test_conversion enc-5 "\u4321abc" +test_conversion enc-6 "\u4321\u1234" +test_conversion enc-7 [string repeat "abcde\u00EF\u00EE\uFFFCabc" 100] +test_conversion enc-8 [string repeat "\u007E\u007F\u0080\u0081" 100] +test_conversion enc-9 [string repeat "\u07FE\u07FF\u0800\u0801\uFFF0" 100] +test_conversion enc-10 [string repeat "\uE000" 100] + +proc test_collate {enc zLeft zRight} { + return [string compare $zLeft $zRight] +} +add_test_collate $::DB 0 0 1 +do_test enc-11.1 { + execsql { + CREATE TABLE ab(a COLLATE test_collate, b); + INSERT INTO ab VALUES(CAST (X'C388' AS TEXT), X'888800'); + INSERT INTO ab VALUES(CAST (X'C0808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808388' AS TEXT), X'888800'); + CREATE INDEX ab_i ON ab(a, b); + } +} {} +do_test enc-11.2 { + set cp200 "\u00C8" + execsql { + SELECT count(*) FROM ab WHERE a = $::cp200; + } +} {2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/enc2.test b/components/external/SQLite-3.8.1/test/enc2.test new file mode 100644 index 0000000000000000000000000000000000000000..3eb3aa27c364151f9772ad2120bda6fa3d704f0f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/enc2.test @@ -0,0 +1,555 @@ +# 2002 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus of +# this file is testing the SQLite routines used for converting between the +# various suported unicode encodings (UTF-8, UTF-16, UTF-16le and +# UTF-16be). +# +# $Id: enc2.test,v 1.29 2007/10/09 08:29:32 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If UTF16 support is disabled, ignore the tests in this file +# +ifcapable {!utf16} { + finish_test + return +} + +# The rough organisation of tests in this file is: +# +# enc2.1.*: Simple tests with a UTF-8 db. +# enc2.2.*: Simple tests with a UTF-16LE db. +# enc2.3.*: Simple tests with a UTF-16BE db. +# enc2.4.*: Test that attached databases must have the same text encoding +# as the main database. +# enc2.5.*: Test the behavior of the library when a collation sequence is +# not available for the most desirable text encoding. +# enc2.6.*: Similar test for user functions. +# enc2.7.*: Test that the VerifyCookie opcode protects against assuming the +# wrong text encoding for the database. +# enc2.8.*: Test sqlite3_complete16() +# + +db close + +# Return the UTF-8 representation of the supplied UTF-16 string $str. +proc utf8 {str} { + # If $str ends in two 0x00 0x00 bytes, knock these off before + # converting to UTF-8 using TCL. + binary scan $str \c* vals + if {[lindex $vals end]==0 && [lindex $vals end-1]==0} { + set str [binary format \c* [lrange $vals 0 end-2]] + } + + set r [encoding convertfrom unicode $str] + return $r +} + +# +# This proc contains all the tests in this file. It is run +# three times. Each time the file 'test.db' contains a database +# with the following contents: +set dbcontents { + CREATE TABLE t1(a PRIMARY KEY, b, c); + INSERT INTO t1 VALUES('one', 'I', 1); +} +# This proc tests that we can open and manipulate the test.db +# database, and that it is possible to retreive values in +# various text encodings. +# +proc run_test_script {t enc} { + +# Open the database and pull out a (the) row. +do_test $t.1 { + sqlite3 db test.db; set DB [sqlite3_connection_pointer db] + execsql {SELECT * FROM t1} +} {one I 1} + +# Insert some data +do_test $t.2 { + execsql {INSERT INTO t1 VALUES('two', 'II', 2);} + execsql {SELECT * FROM t1} +} {one I 1 two II 2} + +# Insert some data +do_test $t.3 { + execsql { + INSERT INTO t1 VALUES('three','III',3); + INSERT INTO t1 VALUES('four','IV',4); + INSERT INTO t1 VALUES('five','V',5); + } + execsql {SELECT * FROM t1} +} {one I 1 two II 2 three III 3 four IV 4 five V 5} + +# Use the index +do_test $t.4 { + execsql { + SELECT * FROM t1 WHERE a = 'one'; + } +} {one I 1} +do_test $t.5 { + execsql { + SELECT * FROM t1 WHERE a = 'four'; + } +} {four IV 4} +ifcapable subquery { + do_test $t.6 { + execsql { + SELECT * FROM t1 WHERE a IN ('one', 'two'); + } + } {one I 1 two II 2} +} + +# Now check that we can retrieve data in both UTF-16 and UTF-8 +do_test $t.7 { + set STMT [sqlite3_prepare $DB "SELECT a FROM t1 WHERE c>3;" -1 TAIL] + sqlite3_step $STMT + sqlite3_column_text $STMT 0 +} {four} + +do_test $t.8 { + sqlite3_step $STMT + utf8 [sqlite3_column_text16 $STMT 0] +} {five} + +do_test $t.9 { + sqlite3_finalize $STMT +} SQLITE_OK + +ifcapable vacuum { + execsql VACUUM +} + +do_test $t.10 { + db eval {PRAGMA encoding} +} $enc + +} + +# The three unicode encodings understood by SQLite. +set encodings [list UTF-8 UTF-16le UTF-16be] + +set sqlite_os_trace 0 +set i 1 +foreach enc $encodings { + forcedelete test.db + sqlite3 db test.db + db eval "PRAGMA encoding = \"$enc\"" + execsql $dbcontents + do_test enc2-$i.0.1 { + db eval {PRAGMA encoding} + } $enc + do_test enc2-$i.0.2 { + db eval {PRAGMA encoding=UTF8} + db eval {PRAGMA encoding} + } $enc + do_test enc2-$i.0.3 { + db eval {PRAGMA encoding=UTF16le} + db eval {PRAGMA encoding} + } $enc + do_test enc2-$i.0.4 { + db eval {PRAGMA encoding=UTF16be} + db eval {PRAGMA encoding} + } $enc + + db close + run_test_script enc2-$i $enc + db close + incr i +} + +# Test that it is an error to try to attach a database with a different +# encoding to the main database. +ifcapable attach { + do_test enc2-4.1 { + forcedelete test.db + sqlite3 db test.db + db eval "PRAGMA encoding = 'UTF-8'" + db eval "CREATE TABLE abc(a, b, c);" + } {} + do_test enc2-4.2 { + forcedelete test2.db + sqlite3 db2 test2.db + db2 eval "PRAGMA encoding = 'UTF-16'" + db2 eval "CREATE TABLE abc(a, b, c);" + } {} + do_test enc2-4.3 { + catchsql { + ATTACH 'test2.db' as aux; + } + } {1 {attached databases must use the same text encoding as main database}} + db2 close + db close +} + +# The following tests - enc2-5.* - test that SQLite selects the correct +# collation sequence when more than one is available. + +set ::values [list one two three four five] +set ::test_collate_enc INVALID +proc test_collate {enc lhs rhs} { + set ::test_collate_enc $enc + set l [lsearch -exact $::values $lhs] + set r [lsearch -exact $::values $rhs] + set res [expr $l - $r] + # puts "enc=$enc lhs=$lhs/$l rhs=$rhs/$r res=$res" + return $res +} + +forcedelete test.db +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +do_test enc2-5.0 { + execsql { + CREATE TABLE t5(a); + INSERT INTO t5 VALUES('one'); + INSERT INTO t5 VALUES('two'); + INSERT INTO t5 VALUES('five'); + INSERT INTO t5 VALUES('three'); + INSERT INTO t5 VALUES('four'); + } +} {} +do_test enc2-5.1 { + add_test_collate $DB 1 1 1 + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate;}] + lappend res $::test_collate_enc +} {one two three four five UTF-8} +do_test enc2-5.2 { + add_test_collate $DB 0 1 0 + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}] + lappend res $::test_collate_enc +} {one two three four five UTF-16LE} +do_test enc2-5.3 { + add_test_collate $DB 0 0 1 + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}] + lappend res $::test_collate_enc +} {one two three four five UTF-16BE} + +db close +forcedelete test.db +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +execsql {pragma encoding = 'UTF-16LE'} +do_test enc2-5.4 { + execsql { + CREATE TABLE t5(a); + INSERT INTO t5 VALUES('one'); + INSERT INTO t5 VALUES('two'); + INSERT INTO t5 VALUES('five'); + INSERT INTO t5 VALUES('three'); + INSERT INTO t5 VALUES('four'); + } +} {} +do_test enc2-5.5 { + add_test_collate $DB 1 1 1 + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}] + lappend res $::test_collate_enc +} {one two three four five UTF-16LE} +do_test enc2-5.6 { + add_test_collate $DB 1 0 1 + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}] + lappend res $::test_collate_enc +} {one two three four five UTF-16BE} +do_test enc2-5.7 { + add_test_collate $DB 1 0 0 + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}] + lappend res $::test_collate_enc +} {one two three four five UTF-8} + +db close +forcedelete test.db +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +execsql {pragma encoding = 'UTF-16BE'} +do_test enc2-5.8 { + execsql { + CREATE TABLE t5(a); + INSERT INTO t5 VALUES('one'); + INSERT INTO t5 VALUES('two'); + INSERT INTO t5 VALUES('five'); + INSERT INTO t5 VALUES('three'); + INSERT INTO t5 VALUES('four'); + } +} {} +do_test enc2-5.9 { + add_test_collate $DB 1 1 1 + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}] + lappend res $::test_collate_enc +} {one two three four five UTF-16BE} +do_test enc2-5.10 { + add_test_collate $DB 1 1 0 + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}] + lappend res $::test_collate_enc +} {one two three four five UTF-16LE} +do_test enc2-5.11 { + add_test_collate $DB 1 0 0 + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate}] + lappend res $::test_collate_enc +} {one two three four five UTF-8} + +# Also test that a UTF-16 collation factory works. +do_test enc2-5-12 { + add_test_collate $DB 0 0 0 + catchsql { + SELECT * FROM t5 ORDER BY 1 COLLATE test_collate + } +} {1 {no such collation sequence: test_collate}} +do_test enc2-5.13 { + add_test_collate_needed $DB + set res [execsql {SELECT * FROM t5 ORDER BY 1 COLLATE test_collate; }] + lappend res $::test_collate_enc +} {one two three four five UTF-16BE} +do_test enc2-5.14 { + set ::sqlite_last_needed_collation +} test_collate + +db close +forcedelete test.db + +do_test enc2-5.15 { + sqlite3 db test.db; set ::DB [sqlite3_connection_pointer db] + add_test_collate_needed $::DB + set ::sqlite_last_needed_collation +} {} +do_test enc2-5.16 { + execsql {CREATE TABLE t1(a varchar collate test_collate);} +} {} +do_test enc2-5.17 { + set ::sqlite_last_needed_collation +} {test_collate} + +# The following tests - enc2-6.* - test that SQLite selects the correct +# user function when more than one is available. + +proc test_function {enc arg} { + return "$enc $arg" +} + +db close +forcedelete test.db +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +execsql {pragma encoding = 'UTF-8'} +do_test enc2-6.0 { + execsql { + CREATE TABLE t5(a); + INSERT INTO t5 VALUES('one'); + } +} {} +do_test enc2-6.1 { + add_test_function $DB 1 1 1 + execsql { + SELECT test_function('sqlite') + } +} {{UTF-8 sqlite}} +db close +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +do_test enc2-6.2 { + add_test_function $DB 0 1 0 + execsql { + SELECT test_function('sqlite') + } +} {{UTF-16LE sqlite}} +db close +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +do_test enc2-6.3 { + add_test_function $DB 0 0 1 + execsql { + SELECT test_function('sqlite') + } +} {{UTF-16BE sqlite}} + +db close +forcedelete test.db +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +execsql {pragma encoding = 'UTF-16LE'} +do_test enc2-6.3 { + execsql { + CREATE TABLE t5(a); + INSERT INTO t5 VALUES('sqlite'); + } +} {} +do_test enc2-6.4 { + add_test_function $DB 1 1 1 + execsql { + SELECT test_function('sqlite') + } +} {{UTF-16LE sqlite}} +db close +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +do_test enc2-6.5 { + add_test_function $DB 0 1 0 + execsql { + SELECT test_function('sqlite') + } +} {{UTF-16LE sqlite}} +db close +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +do_test enc2-6.6 { + add_test_function $DB 0 0 1 + execsql { + SELECT test_function('sqlite') + } +} {{UTF-16BE sqlite}} + +db close +forcedelete test.db +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +execsql {pragma encoding = 'UTF-16BE'} +do_test enc2-6.7 { + execsql { + CREATE TABLE t5(a); + INSERT INTO t5 VALUES('sqlite'); + } +} {} +do_test enc2-6.8 { + add_test_function $DB 1 1 1 + execsql { + SELECT test_function('sqlite') + } +} {{UTF-16BE sqlite}} +db close +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +do_test enc2-6.9 { + add_test_function $DB 0 1 0 + execsql { + SELECT test_function('sqlite') + } +} {{UTF-16LE sqlite}} +db close +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +do_test enc2-6.10 { + add_test_function $DB 0 0 1 + execsql { + SELECT test_function('sqlite') + } +} {{UTF-16BE sqlite}} + + +db close +forcedelete test.db + +# The following tests - enc2-7.* - function as follows: +# +# 1: Open an empty database file assuming UTF-16 encoding. +# 2: Open the same database with a different handle assuming UTF-8. Create +# a table using this handle. +# 3: Read the sqlite_master table from the first handle. +# 4: Ensure the first handle recognises the database encoding is UTF-8. +# +do_test enc2-7.1 { + sqlite3 db test.db + execsql { + PRAGMA encoding = 'UTF-16'; + SELECT * FROM sqlite_master; + } +} {} +do_test enc2-7.2 { + set enc [execsql { + PRAGMA encoding; + }] + string range $enc 0 end-2 ;# Chop off the "le" or "be" +} {UTF-16} +do_test enc2-7.3 { + sqlite3 db2 test.db + execsql { + PRAGMA encoding = 'UTF-8'; + CREATE TABLE abc(a, b, c); + } db2 +} {} +do_test enc2-7.4 { + execsql { + SELECT * FROM sqlite_master; + } +} "table abc abc [expr $AUTOVACUUM?3:2] {CREATE TABLE abc(a, b, c)}" +do_test enc2-7.5 { + execsql { + PRAGMA encoding; + } +} {UTF-8} + +db close +db2 close + +proc utf16 {utf8} { + set utf16 [encoding convertto unicode $utf8] + append utf16 "\x00\x00" + return $utf16 +} +ifcapable {complete} { + do_test enc2-8.1 { + sqlite3_complete16 [utf16 "SELECT * FROM t1;"] + } {1} + do_test enc2-8.2 { + sqlite3_complete16 [utf16 "SELECT * FROM"] + } {0} +} + +# Test that the encoding of an empty database may still be set after the +# (empty) schema has been initialized. +forcedelete test.db +do_test enc2-9.1 { + sqlite3 db test.db + execsql { + PRAGMA encoding = 'UTF-8'; + PRAGMA encoding; + } +} {UTF-8} +do_test enc2-9.2 { + sqlite3 db test.db + execsql { + PRAGMA encoding = 'UTF-16le'; + PRAGMA encoding; + } +} {UTF-16le} +do_test enc2-9.3 { + sqlite3 db test.db + execsql { + SELECT * FROM sqlite_master; + PRAGMA encoding = 'UTF-8'; + PRAGMA encoding; + } +} {UTF-8} +do_test enc2-9.4 { + sqlite3 db test.db + execsql { + PRAGMA encoding = 'UTF-16le'; + CREATE TABLE abc(a, b, c); + PRAGMA encoding; + } +} {UTF-16le} +do_test enc2-9.5 { + sqlite3 db test.db + execsql { + PRAGMA encoding = 'UTF-8'; + PRAGMA encoding; + } +} {UTF-16le} + +# Ticket #1987. +# Disallow encoding changes once the encoding has been set. +# +do_test enc2-10.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + db eval { + PRAGMA encoding=UTF16; + CREATE TABLE t1(a); + PRAGMA encoding=UTF8; + CREATE TABLE t2(b); + } + db close + sqlite3 db test.db + db eval { + SELECT name FROM sqlite_master + } +} {t1 t2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/enc3.test b/components/external/SQLite-3.8.1/test/enc3.test new file mode 100644 index 0000000000000000000000000000000000000000..1d8a258165217c370934fbc04063803fa9827892 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/enc3.test @@ -0,0 +1,107 @@ +# 2002 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# The focus of this file is testing of the proper handling of conversions +# to the native text representation. +# +# $Id: enc3.test,v 1.8 2008/01/22 01:48:09 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {utf16} { + do_test enc3-1.1 { + execsql { + PRAGMA encoding=utf16le; + PRAGMA encoding; + } + } {UTF-16le} +} +do_test enc3-1.2 { + execsql { + CREATE TABLE t1(x,y); + INSERT INTO t1 VALUES('abc''123',5); + SELECT * FROM t1 + } +} {abc'123 5} +do_test enc3-1.3 { + execsql { + SELECT quote(x) || ' ' || quote(y) FROM t1 + } +} {{'abc''123' 5}} +ifcapable {bloblit} { + do_test enc3-1.4 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(x'616263646566',NULL); + SELECT * FROM t1 + } + } {abcdef {}} + do_test enc3-1.5 { + execsql { + SELECT quote(x) || ' ' || quote(y) FROM t1 + } + } {{X'616263646566' NULL}} +} +ifcapable {bloblit && utf16} { + do_test enc3-2.1 { + execsql { + PRAGMA encoding + } + } {UTF-16le} + do_test enc3-2.2 { + execsql { + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(x'61006200630064006500'); + SELECT CAST(a AS text) FROM t2 WHERE a LIKE 'abc%'; + } + } {abcde} + do_test enc3-2.3 { + execsql { + SELECT CAST(x'61006200630064006500' AS text); + } + } {abcde} + do_test enc3-2.4 { + execsql { + SELECT rowid FROM t2 WHERE a LIKE x'610062002500'; + } + } {1} +} + +# Try to attach a database with a different encoding. +# +ifcapable {utf16 && shared_cache} { + db close + forcedelete test8.db test8.db-journal + set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + sqlite3 dbaux test8.db + sqlite3 db test.db + db eval {SELECT 1 FROM sqlite_master LIMIT 1} + do_test enc3-3.1 { + dbaux eval { + PRAGMA encoding='utf8'; + CREATE TABLE t1(x); + PRAGMA encoding + } + } {UTF-8} + do_test enc3-3.2 { + catchsql { + ATTACH 'test.db' AS utf16; + SELECT 1 FROM utf16.sqlite_master LIMIT 1; + } dbaux + } {1 {attached databases must use the same text encoding as main database}} + dbaux close + forcedelete test8.db test8.db-journal + sqlite3_enable_shared_cache $::enable_shared_cache +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/enc4.test b/components/external/SQLite-3.8.1/test/enc4.test new file mode 100644 index 0000000000000000000000000000000000000000..94869b6fb75050b9f23fdf7966eefda3cbe1207a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/enc4.test @@ -0,0 +1,137 @@ +# 2010 Sept 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus of +# this file is testing the SQLite routines used for converting between the +# various suported unicode encodings (UTF-8, UTF-16, UTF-16le and +# UTF-16be). +# +# $Id: enc4.test,v 1.0 2010/09/29 08:29:32 shaneh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If UTF16 support is disabled, ignore the tests in this file +# +ifcapable {!utf16} { + finish_test + return +} + +db close + +# The three unicode encodings understood by SQLite. +set encodings [list UTF-8 UTF-16le UTF-16be] + +# initial value to use in SELECT +set inits [list 1 1.0 1. 1e0] + +# vals +set vals [list\ +"922337203685477580792233720368547758079223372036854775807"\ +"100000000000000000000000000000000000000000000000000000000"\ +"1.0000000000000000000000000000000000000000000000000000000"\ +] + +set i 1 +foreach enc $encodings { + + forcedelete test.db + sqlite3 db test.db + db eval "PRAGMA encoding = \"$enc\"" + + do_test enc4-$i.1 { + db eval {PRAGMA encoding} + } $enc + + set j 1 + foreach init $inits { + + do_test enc4-$i.$j.2 { + set S [sqlite3_prepare_v2 db "SELECT $init+?" -1 dummy] + sqlite3_expired $S + } {0} + + set k 1 + foreach val $vals { + for {set x 1} {$x<16} {incr x} { + set part [expr $init + [string range $val 0 [expr $x-1]]] + + do_realnum_test enc4-$i.$j.$k.3.$x { + sqlite3_reset $S + sqlite3_bind_text $S 1 $val $x + sqlite3_step $S + sqlite3_column_text $S 0 + } [list $part] + + do_realnum_test enc4-$i.$j.$k.4.$x { + sqlite3_reset $S + sqlite3_bind_text16 $S 1 [encoding convertto unicode $val] [expr $x*2] + sqlite3_step $S + sqlite3_column_text $S 0 + } [list $part] + } + + incr k + } + + do_test enc4-$i.$j.5 { + sqlite3_finalize $S + } {SQLITE_OK} + + incr j + } + + db close + incr i +} + +forcedelete test.db +sqlite3 db test.db + +do_test enc4-4.1 { + db eval "select 1+1." +} {2.0} + +do_test enc4-4.2.1 { + set S [sqlite3_prepare_v2 db "SELECT 1+1." -1 dummy] + sqlite3_step $S + sqlite3_column_text $S 0 +} {2.0} + +do_test enc4-4.2.2 { + sqlite3_finalize $S +} {SQLITE_OK} + +do_test enc4-4.3.1 { + set S [sqlite3_prepare_v2 db "SELECT 1+?" -1 dummy] + sqlite3_bind_text $S 1 "1." 2 + sqlite3_step $S + sqlite3_column_text $S 0 +} {2.0} + +do_test enc4-4.3.2 { + sqlite3_finalize $S +} {SQLITE_OK} + +do_test enc4-4.4.1 { + set S [sqlite3_prepare_v2 db "SELECT 1+?" -1 dummy] + sqlite3_bind_text $S 1 "1.0" 2 + sqlite3_step $S + sqlite3_column_text $S 0 +} {2.0} + +do_test enc4-4.4.2 { + sqlite3_finalize $S +} {SQLITE_OK} + +db close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/eqp.test b/components/external/SQLite-3.8.1/test/eqp.test new file mode 100644 index 0000000000000000000000000000000000000000..610ebdc5ca1eb708d42b451b20cd63afcf8021a2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/eqp.test @@ -0,0 +1,602 @@ +# 2010 November 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +set testprefix eqp + +#------------------------------------------------------------------------- +# +# eqp-1.*: Assorted tests. +# eqp-2.*: Tests for single select statements. +# eqp-3.*: Select statements that execute sub-selects. +# eqp-4.*: Compound select statements. +# ... +# eqp-7.*: "SELECT count(*) FROM tbl" statements (VDBE code OP_Count). +# + +proc det {args} { uplevel do_eqp_test $args } + +do_execsql_test 1.1 { + CREATE TABLE t1(a INT, b INT, ex TEXT); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); + CREATE TABLE t2(a INT, b INT, ex TEXT); + CREATE TABLE t3(a INT, b INT, ex TEXT); +} + +do_eqp_test 1.2 { + SELECT * FROM t2, t1 WHERE t1.a=1 OR t1.b=2; +} { + 0 0 1 {SEARCH TABLE t1 USING INDEX i1 (a=?)} + 0 0 1 {SEARCH TABLE t1 USING INDEX i2 (b=?)} + 0 1 0 {SCAN TABLE t2} +} +do_eqp_test 1.3 { + SELECT * FROM t2 CROSS JOIN t1 WHERE t1.a=1 OR t1.b=2; +} { + 0 0 0 {SCAN TABLE t2} + 0 1 1 {SEARCH TABLE t1 USING INDEX i1 (a=?)} + 0 1 1 {SEARCH TABLE t1 USING INDEX i2 (b=?)} +} +do_eqp_test 1.3 { + SELECT a FROM t1 ORDER BY a +} { + 0 0 0 {SCAN TABLE t1 USING COVERING INDEX i1} +} +do_eqp_test 1.4 { + SELECT a FROM t1 ORDER BY +a +} { + 0 0 0 {SCAN TABLE t1 USING COVERING INDEX i1} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} +do_eqp_test 1.5 { + SELECT a FROM t1 WHERE a=4 +} { + 0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i1 (a=?)} +} +do_eqp_test 1.6 { + SELECT DISTINCT count(*) FROM t3 GROUP BY a; +} { + 0 0 0 {SCAN TABLE t3} + 0 0 0 {USE TEMP B-TREE FOR GROUP BY} + 0 0 0 {USE TEMP B-TREE FOR DISTINCT} +} + +do_eqp_test 1.7 { + SELECT * FROM t3 JOIN (SELECT 1) +} { + 0 0 1 {SCAN SUBQUERY 1} + 0 1 0 {SCAN TABLE t3} +} +do_eqp_test 1.8 { + SELECT * FROM t3 JOIN (SELECT 1 UNION SELECT 2) +} { + 1 0 0 {COMPOUND SUBQUERIES 2 AND 3 USING TEMP B-TREE (UNION)} + 0 0 1 {SCAN SUBQUERY 1} + 0 1 0 {SCAN TABLE t3} +} +do_eqp_test 1.9 { + SELECT * FROM t3 JOIN (SELECT 1 EXCEPT SELECT a FROM t3 LIMIT 17) +} { + 3 0 0 {SCAN TABLE t3} + 1 0 0 {COMPOUND SUBQUERIES 2 AND 3 USING TEMP B-TREE (EXCEPT)} + 0 0 1 {SCAN SUBQUERY 1} + 0 1 0 {SCAN TABLE t3} +} +do_eqp_test 1.10 { + SELECT * FROM t3 JOIN (SELECT 1 INTERSECT SELECT a FROM t3 LIMIT 17) +} { + 3 0 0 {SCAN TABLE t3} + 1 0 0 {COMPOUND SUBQUERIES 2 AND 3 USING TEMP B-TREE (INTERSECT)} + 0 0 1 {SCAN SUBQUERY 1} + 0 1 0 {SCAN TABLE t3} +} + +do_eqp_test 1.11 { + SELECT * FROM t3 JOIN (SELECT 1 UNION ALL SELECT a FROM t3 LIMIT 17) +} { + 3 0 0 {SCAN TABLE t3} + 1 0 0 {COMPOUND SUBQUERIES 2 AND 3 (UNION ALL)} + 0 0 1 {SCAN SUBQUERY 1} + 0 1 0 {SCAN TABLE t3} +} + +#------------------------------------------------------------------------- +# Test cases eqp-2.* - tests for single select statements. +# +drop_all_tables +do_execsql_test 2.1 { + CREATE TABLE t1(x INT, y INT, ex TEXT); + + CREATE TABLE t2(x INT, y INT, ex TEXT); + CREATE INDEX t2i1 ON t2(x); +} + +det 2.2.1 "SELECT DISTINCT min(x), max(x) FROM t1 GROUP BY x ORDER BY 1" { + 0 0 0 {SCAN TABLE t1} + 0 0 0 {USE TEMP B-TREE FOR GROUP BY} + 0 0 0 {USE TEMP B-TREE FOR DISTINCT} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} +det 2.2.2 "SELECT DISTINCT min(x), max(x) FROM t2 GROUP BY x ORDER BY 1" { + 0 0 0 {SCAN TABLE t2 USING COVERING INDEX t2i1} + 0 0 0 {USE TEMP B-TREE FOR DISTINCT} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} +det 2.2.3 "SELECT DISTINCT * FROM t1" { + 0 0 0 {SCAN TABLE t1} + 0 0 0 {USE TEMP B-TREE FOR DISTINCT} +} +det 2.2.4 "SELECT DISTINCT * FROM t1, t2" { + 0 0 0 {SCAN TABLE t1} + 0 1 1 {SCAN TABLE t2} + 0 0 0 {USE TEMP B-TREE FOR DISTINCT} +} +det 2.2.5 "SELECT DISTINCT * FROM t1, t2 ORDER BY t1.x" { + 0 0 0 {SCAN TABLE t1} + 0 1 1 {SCAN TABLE t2} + 0 0 0 {USE TEMP B-TREE FOR DISTINCT} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} +det 2.2.6 "SELECT DISTINCT t2.x FROM t1, t2 ORDER BY t2.x" { + 0 0 1 {SCAN TABLE t2 USING COVERING INDEX t2i1} + 0 1 0 {SCAN TABLE t1} +} + +det 2.3.1 "SELECT max(x) FROM t2" { + 0 0 0 {SEARCH TABLE t2 USING COVERING INDEX t2i1} +} +det 2.3.2 "SELECT min(x) FROM t2" { + 0 0 0 {SEARCH TABLE t2 USING COVERING INDEX t2i1} +} +det 2.3.3 "SELECT min(x), max(x) FROM t2" { + 0 0 0 {SCAN TABLE t2 USING COVERING INDEX t2i1} +} + +det 2.4.1 "SELECT * FROM t1 WHERE rowid=?" { + 0 0 0 {SEARCH TABLE t1 USING INTEGER PRIMARY KEY (rowid=?)} +} + + + +#------------------------------------------------------------------------- +# Test cases eqp-3.* - tests for select statements that use sub-selects. +# +do_eqp_test 3.1.1 { + SELECT (SELECT x FROM t1 AS sub) FROM t1; +} { + 0 0 0 {SCAN TABLE t1} + 0 0 0 {EXECUTE SCALAR SUBQUERY 1} + 1 0 0 {SCAN TABLE t1 AS sub} +} +do_eqp_test 3.1.2 { + SELECT * FROM t1 WHERE (SELECT x FROM t1 AS sub); +} { + 0 0 0 {SCAN TABLE t1} + 0 0 0 {EXECUTE SCALAR SUBQUERY 1} + 1 0 0 {SCAN TABLE t1 AS sub} +} +do_eqp_test 3.1.3 { + SELECT * FROM t1 WHERE (SELECT x FROM t1 AS sub ORDER BY y); +} { + 0 0 0 {SCAN TABLE t1} + 0 0 0 {EXECUTE SCALAR SUBQUERY 1} + 1 0 0 {SCAN TABLE t1 AS sub} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} +} +do_eqp_test 3.1.4 { + SELECT * FROM t1 WHERE (SELECT x FROM t2 ORDER BY x); +} { + 0 0 0 {SCAN TABLE t1} + 0 0 0 {EXECUTE SCALAR SUBQUERY 1} + 1 0 0 {SCAN TABLE t2 USING COVERING INDEX t2i1} +} + +det 3.2.1 { + SELECT * FROM (SELECT * FROM t1 ORDER BY x LIMIT 10) ORDER BY y LIMIT 5 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {SCAN SUBQUERY 1} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} +det 3.2.2 { + SELECT * FROM + (SELECT * FROM t1 ORDER BY x LIMIT 10) AS x1, + (SELECT * FROM t2 ORDER BY x LIMIT 10) AS x2 + ORDER BY x2.y LIMIT 5 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 2 0 0 {SCAN TABLE t2 USING INDEX t2i1} + 0 0 0 {SCAN SUBQUERY 1 AS x1} + 0 1 1 {SCAN SUBQUERY 2 AS x2} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} + +det 3.3.1 { + SELECT * FROM t1 WHERE y IN (SELECT y FROM t2) +} { + 0 0 0 {SCAN TABLE t1} + 0 0 0 {EXECUTE LIST SUBQUERY 1} + 1 0 0 {SCAN TABLE t2} +} +det 3.3.2 { + SELECT * FROM t1 WHERE y IN (SELECT y FROM t2 WHERE t1.x!=t2.x) +} { + 0 0 0 {SCAN TABLE t1} + 0 0 0 {EXECUTE CORRELATED LIST SUBQUERY 1} + 1 0 0 {SCAN TABLE t2} +} +det 3.3.3 { + SELECT * FROM t1 WHERE EXISTS (SELECT y FROM t2 WHERE t1.x!=t2.x) +} { + 0 0 0 {SCAN TABLE t1} + 0 0 0 {EXECUTE CORRELATED SCALAR SUBQUERY 1} + 1 0 0 {SCAN TABLE t2} +} + +#------------------------------------------------------------------------- +# Test cases eqp-4.* - tests for composite select statements. +# +do_eqp_test 4.1.1 { + SELECT * FROM t1 UNION ALL SELECT * FROM t2 +} { + 1 0 0 {SCAN TABLE t1} + 2 0 0 {SCAN TABLE t2} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (UNION ALL)} +} +do_eqp_test 4.1.2 { + SELECT * FROM t1 UNION ALL SELECT * FROM t2 ORDER BY 2 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 2 0 0 {SCAN TABLE t2} + 2 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (UNION ALL)} +} +do_eqp_test 4.1.3 { + SELECT * FROM t1 UNION SELECT * FROM t2 ORDER BY 2 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 2 0 0 {SCAN TABLE t2} + 2 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (UNION)} +} +do_eqp_test 4.1.4 { + SELECT * FROM t1 INTERSECT SELECT * FROM t2 ORDER BY 2 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 2 0 0 {SCAN TABLE t2} + 2 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (INTERSECT)} +} +do_eqp_test 4.1.5 { + SELECT * FROM t1 EXCEPT SELECT * FROM t2 ORDER BY 2 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 2 0 0 {SCAN TABLE t2} + 2 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (EXCEPT)} +} + +do_eqp_test 4.2.2 { + SELECT * FROM t1 UNION ALL SELECT * FROM t2 ORDER BY 1 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 2 0 0 {SCAN TABLE t2 USING INDEX t2i1} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (UNION ALL)} +} +do_eqp_test 4.2.3 { + SELECT * FROM t1 UNION SELECT * FROM t2 ORDER BY 1 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 2 0 0 {SCAN TABLE t2} + 2 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (UNION)} +} +do_eqp_test 4.2.4 { + SELECT * FROM t1 INTERSECT SELECT * FROM t2 ORDER BY 1 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 2 0 0 {SCAN TABLE t2} + 2 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (INTERSECT)} +} +do_eqp_test 4.2.5 { + SELECT * FROM t1 EXCEPT SELECT * FROM t2 ORDER BY 1 +} { + 1 0 0 {SCAN TABLE t1} + 1 0 0 {USE TEMP B-TREE FOR ORDER BY} + 2 0 0 {SCAN TABLE t2} + 2 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (EXCEPT)} +} + +do_eqp_test 4.3.1 { + SELECT x FROM t1 UNION SELECT x FROM t2 +} { + 1 0 0 {SCAN TABLE t1} + 2 0 0 {SCAN TABLE t2 USING COVERING INDEX t2i1} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 USING TEMP B-TREE (UNION)} +} + +do_eqp_test 4.3.2 { + SELECT x FROM t1 UNION SELECT x FROM t2 UNION SELECT x FROM t1 +} { + 2 0 0 {SCAN TABLE t1} + 3 0 0 {SCAN TABLE t2 USING COVERING INDEX t2i1} + 1 0 0 {COMPOUND SUBQUERIES 2 AND 3 USING TEMP B-TREE (UNION)} + 4 0 0 {SCAN TABLE t1} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 4 USING TEMP B-TREE (UNION)} +} +do_eqp_test 4.3.3 { + SELECT x FROM t1 UNION SELECT x FROM t2 UNION SELECT x FROM t1 ORDER BY 1 +} { + 2 0 0 {SCAN TABLE t1} + 2 0 0 {USE TEMP B-TREE FOR ORDER BY} + 3 0 0 {SCAN TABLE t2 USING COVERING INDEX t2i1} + 1 0 0 {COMPOUND SUBQUERIES 2 AND 3 (UNION)} + 4 0 0 {SCAN TABLE t1} + 4 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 4 (UNION)} +} + +#------------------------------------------------------------------------- +# This next block of tests verifies that the examples on the +# lang_explain.html page are correct. +# +drop_all_tables + +# EVIDENCE-OF: R-47779-47605 sqlite> EXPLAIN QUERY PLAN SELECT a, b +# FROM t1 WHERE a=1; +# 0|0|0|SCAN TABLE t1 +# +do_execsql_test 5.1.0 { CREATE TABLE t1(a INT, b INT, ex TEXT) } +det 5.1.1 "SELECT a, b FROM t1 WHERE a=1" { + 0 0 0 {SCAN TABLE t1} +} + +# EVIDENCE-OF: R-55852-17599 sqlite> CREATE INDEX i1 ON t1(a); +# sqlite> EXPLAIN QUERY PLAN SELECT a, b FROM t1 WHERE a=1; +# 0|0|0|SEARCH TABLE t1 USING INDEX i1 +# +do_execsql_test 5.2.0 { CREATE INDEX i1 ON t1(a) } +det 5.2.1 "SELECT a, b FROM t1 WHERE a=1" { + 0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)} +} + +# EVIDENCE-OF: R-21179-11011 sqlite> CREATE INDEX i2 ON t1(a, b); +# sqlite> EXPLAIN QUERY PLAN SELECT a, b FROM t1 WHERE a=1; +# 0|0|0|SEARCH TABLE t1 USING COVERING INDEX i2 (a=?) +# +do_execsql_test 5.3.0 { CREATE INDEX i2 ON t1(a, b) } +det 5.3.1 "SELECT a, b FROM t1 WHERE a=1" { + 0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=?)} +} + +# EVIDENCE-OF: R-09991-48941 sqlite> EXPLAIN QUERY PLAN +# SELECT t1.*, t2.* FROM t1, t2 WHERE t1.a=1 AND t1.b>2; +# 0|0|0|SEARCH TABLE t1 USING COVERING INDEX i2 (a=? AND b>?) +# 0|1|1|SCAN TABLE t2 +# +do_execsql_test 5.4.0 {CREATE TABLE t2(c INT, d INT, ex TEXT)} +det 5.4.1 "SELECT t1.a, t2.c FROM t1, t2 WHERE t1.a=1 AND t1.b>2" { + 0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=? AND b>?)} + 0 1 1 {SCAN TABLE t2} +} + +# EVIDENCE-OF: R-33626-61085 sqlite> EXPLAIN QUERY PLAN +# SELECT t1.*, t2.* FROM t2, t1 WHERE t1.a=1 AND t1.b>2; +# 0|0|1|SEARCH TABLE t1 USING COVERING INDEX i2 (a=? AND b>?) +# 0|1|0|SCAN TABLE t2 +# +det 5.5 "SELECT t1.a, t2.c FROM t2, t1 WHERE t1.a=1 AND t1.b>2" { + 0 0 1 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=? AND b>?)} + 0 1 0 {SCAN TABLE t2} +} + +# EVIDENCE-OF: R-04002-25654 sqlite> CREATE INDEX i3 ON t1(b); +# sqlite> EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=1 OR b=2; +# 0|0|0|SEARCH TABLE t1 USING COVERING INDEX i2 (a=?) +# 0|0|0|SEARCH TABLE t1 USING INDEX i3 (b=?) +# +do_execsql_test 5.5.0 {CREATE INDEX i3 ON t1(b)} +det 5.6.1 "SELECT a, b FROM t1 WHERE a=1 OR b=2" { + 0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=?)} + 0 0 0 {SEARCH TABLE t1 USING INDEX i3 (b=?)} +} + +# EVIDENCE-OF: R-24577-38891 sqlite> EXPLAIN QUERY PLAN +# SELECT c, d FROM t2 ORDER BY c; +# 0|0|0|SCAN TABLE t2 +# 0|0|0|USE TEMP B-TREE FOR ORDER BY +# +det 5.7 "SELECT c, d FROM t2 ORDER BY c" { + 0 0 0 {SCAN TABLE t2} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} + +# EVIDENCE-OF: R-58157-12355 sqlite> CREATE INDEX i4 ON t2(c); +# sqlite> EXPLAIN QUERY PLAN SELECT c, d FROM t2 ORDER BY c; +# 0|0|0|SCAN TABLE t2 USING INDEX i4 +# +do_execsql_test 5.8.0 {CREATE INDEX i4 ON t2(c)} +det 5.8.1 "SELECT c, d FROM t2 ORDER BY c" { + 0 0 0 {SCAN TABLE t2 USING INDEX i4} +} + +# EVIDENCE-OF: R-13931-10421 sqlite> EXPLAIN QUERY PLAN SELECT +# (SELECT b FROM t1 WHERE a=0), (SELECT a FROM t1 WHERE b=t2.c) FROM t2; +# 0|0|0|SCAN TABLE t2 +# 0|0|0|EXECUTE SCALAR SUBQUERY 1 +# 1|0|0|SEARCH TABLE t1 USING COVERING INDEX i2 (a=?) +# 0|0|0|EXECUTE CORRELATED SCALAR SUBQUERY 2 +# 2|0|0|SEARCH TABLE t1 USING INDEX i3 (b=?) +# +det 5.9 { + SELECT (SELECT b FROM t1 WHERE a=0), (SELECT a FROM t1 WHERE b=t2.c) FROM t2 +} { + 0 0 0 {SCAN TABLE t2 USING COVERING INDEX i4} + 0 0 0 {EXECUTE SCALAR SUBQUERY 1} + 1 0 0 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=?)} + 0 0 0 {EXECUTE CORRELATED SCALAR SUBQUERY 2} + 2 0 0 {SEARCH TABLE t1 USING INDEX i3 (b=?)} +} + +# EVIDENCE-OF: R-50892-45943 sqlite> EXPLAIN QUERY PLAN +# SELECT count(*) FROM (SELECT max(b) AS x FROM t1 GROUP BY a) GROUP BY x; +# 1|0|0|SCAN TABLE t1 USING COVERING INDEX i2 +# 0|0|0|SCAN SUBQUERY 1 +# 0|0|0|USE TEMP B-TREE FOR GROUP BY +# +det 5.10 { + SELECT count(*) FROM (SELECT max(b) AS x FROM t1 GROUP BY a) GROUP BY x +} { + 1 0 0 {SCAN TABLE t1 USING COVERING INDEX i2} + 0 0 0 {SCAN SUBQUERY 1} + 0 0 0 {USE TEMP B-TREE FOR GROUP BY} +} + +# EVIDENCE-OF: R-46219-33846 sqlite> EXPLAIN QUERY PLAN +# SELECT * FROM (SELECT * FROM t2 WHERE c=1), t1; +# 0|0|0|SEARCH TABLE t2 USING INDEX i4 (c=?) +# 0|1|1|SCAN TABLE t1 +# +det 5.11 "SELECT a, b FROM (SELECT * FROM t2 WHERE c=1), t1" { + 0 0 0 {SEARCH TABLE t2 USING INDEX i4 (c=?)} + 0 1 1 {SCAN TABLE t1 USING COVERING INDEX i2} +} + +# EVIDENCE-OF: R-37879-39987 sqlite> EXPLAIN QUERY PLAN +# SELECT a FROM t1 UNION SELECT c FROM t2; +# 1|0|0|SCAN TABLE t1 +# 2|0|0|SCAN TABLE t2 +# 0|0|0|COMPOUND SUBQUERIES 1 AND 2 USING TEMP B-TREE (UNION) +# +det 5.12 "SELECT a,b FROM t1 UNION SELECT c, 99 FROM t2" { + 1 0 0 {SCAN TABLE t1 USING COVERING INDEX i2} + 2 0 0 {SCAN TABLE t2 USING COVERING INDEX i4} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 USING TEMP B-TREE (UNION)} +} + +# EVIDENCE-OF: R-44864-63011 sqlite> EXPLAIN QUERY PLAN +# SELECT a FROM t1 EXCEPT SELECT d FROM t2 ORDER BY 1; +# 1|0|0|SCAN TABLE t1 USING COVERING INDEX i2 +# 2|0|0|SCAN TABLE t2 2|0|0|USE TEMP B-TREE FOR ORDER BY +# 0|0|0|COMPOUND SUBQUERIES 1 AND 2 (EXCEPT) +# +det 5.13 "SELECT a FROM t1 EXCEPT SELECT d FROM t2 ORDER BY 1" { + 1 0 0 {SCAN TABLE t1 USING COVERING INDEX i1} + 2 0 0 {SCAN TABLE t2} + 2 0 0 {USE TEMP B-TREE FOR ORDER BY} + 0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (EXCEPT)} +} + + +#------------------------------------------------------------------------- +# The following tests - eqp-6.* - test that the example C code on +# documentation page eqp.html works. The C code is duplicated in test1.c +# and wrapped in Tcl command [print_explain_query_plan] +# +set boilerplate { + proc explain_query_plan {db sql} { + set stmt [sqlite3_prepare_v2 db $sql -1 DUMMY] + print_explain_query_plan $stmt + sqlite3_finalize $stmt + } + sqlite3 db test.db + explain_query_plan db {%SQL%} + db close + exit +} + +# Do a "Print Explain Query Plan" test. +proc do_peqp_test {tn sql res} { + set fd [open script.tcl w] + puts $fd [string map [list %SQL% $sql] $::boilerplate] + close $fd + + uplevel do_test $tn [list { + set fd [open "|[info nameofexec] script.tcl"] + set data [read $fd] + close $fd + set data + }] [list $res] +} + +do_peqp_test 6.1 { + SELECT a, b FROM t1 EXCEPT SELECT d, 99 FROM t2 ORDER BY 1 +} [string trimleft { +1 0 0 SCAN TABLE t1 USING COVERING INDEX i2 +2 0 0 SCAN TABLE t2 +2 0 0 USE TEMP B-TREE FOR ORDER BY +0 0 0 COMPOUND SUBQUERIES 1 AND 2 (EXCEPT) +}] + +#------------------------------------------------------------------------- +# The following tests - eqp-7.* - test that queries that use the OP_Count +# optimization return something sensible with EQP. +# +drop_all_tables + +do_execsql_test 7.0 { + CREATE TABLE t1(a INT, b INT, ex CHAR(100)); + CREATE TABLE t2(a INT, b INT, ex CHAR(100)); + CREATE INDEX i1 ON t2(a); +} + +det 7.1 "SELECT count(*) FROM t1" { + 0 0 0 {SCAN TABLE t1} +} + +det 7.2 "SELECT count(*) FROM t2" { + 0 0 0 {SCAN TABLE t2 USING COVERING INDEX i1} +} + +do_execsql_test 7.3 { + INSERT INTO t1(a,b) VALUES(1, 2); + INSERT INTO t1(a,b) VALUES(3, 4); + + INSERT INTO t2(a,b) VALUES(1, 2); + INSERT INTO t2(a,b) VALUES(3, 4); + INSERT INTO t2(a,b) VALUES(5, 6); + + ANALYZE; +} + +db close +sqlite3 db test.db + +det 7.4 "SELECT count(*) FROM t1" { + 0 0 0 {SCAN TABLE t1} +} + +det 7.5 "SELECT count(*) FROM t2" { + 0 0 0 {SCAN TABLE t2 USING COVERING INDEX i1} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/errmsg.test b/components/external/SQLite-3.8.1/test/errmsg.test new file mode 100644 index 0000000000000000000000000000000000000000..6b3f3b7db6954a62f31027e48aa628cee7e44efe --- /dev/null +++ b/components/external/SQLite-3.8.1/test/errmsg.test @@ -0,0 +1,118 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# Test that if sqlite3_prepare_v2() is used to prepare a query, the +# error-message associated with an sqlite3_step() error is available +# immediately. Whereas if sqlite3_prepare() is used, it is not available +# until sqlite3_finalize() or sqlite3_reset() has been called. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set testprefix errmsg + +# Test organization: +# +# errmsg-1.* User-defined SQL function errors +# errmsg-2.* Errors generated by the VDBE (constraint failures etc.) +# errmsg-3.* SQLITE_SCHEMA and statement recompilation errors. +# + +proc error_messages_worker {prepare sql schema} { + set ret [list] + + set stmt [$prepare db $sql -1 dummy] + execsql $schema + lappend ret [sqlite3_step $stmt] + lappend ret [sqlite3_errmsg db] + lappend ret [sqlite3_finalize $stmt] + lappend ret [sqlite3_errmsg db] + + set ret +} + +proc error_messages_v2 {sql {schema {}}} { + error_messages_worker sqlite3_prepare_v2 $sql $schema +} + +proc error_messages {sql {schema {}}} { + error_messages_worker sqlite3_prepare $sql $schema +} + +proc sql_error {msg} { error $msg } +db func sql_error sql_error + +#------------------------------------------------------------------------- +# Test error messages returned by user-defined SQL functions. +# +do_test 1.1 { + error_messages "SELECT sql_error('custom message')" +} [list {*}{ + SQLITE_ERROR {SQL logic error or missing database} + SQLITE_ERROR {custom message} +}] +do_test 1.2 { + error_messages_v2 "SELECT sql_error('custom message')" +} [list {*}{ + SQLITE_ERROR {custom message} + SQLITE_ERROR {custom message} +}] + +#------------------------------------------------------------------------- +# Test error messages generated directly by VDBE code (e.g. constraint +# failures). +# +do_execsql_test 2.1 { + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + INSERT INTO t1 VALUES('abc', 'def'); +} +do_test 2.2 { + error_messages "INSERT INTO t1 VALUES('ghi', 'def')" +} [list {*}{ + SQLITE_ERROR {SQL logic error or missing database} + SQLITE_CONSTRAINT {column b is not unique} +}] +verify_ex_errcode 2.2b SQLITE_CONSTRAINT_UNIQUE +do_test 2.3 { + error_messages_v2 "INSERT INTO t1 VALUES('ghi', 'def')" +} [list {*}{ + SQLITE_CONSTRAINT {column b is not unique} + SQLITE_CONSTRAINT {column b is not unique} +}] +verify_ex_errcode 2.3b SQLITE_CONSTRAINT_UNIQUE + +#------------------------------------------------------------------------- +# Test SQLITE_SCHEMA errors. And, for _v2(), test that if the schema +# change invalidates the SQL statement itself the error message is returned +# correctly. +# +do_execsql_test 3.1.1 { + CREATE TABLE t2(a PRIMARY KEY, b UNIQUE); + INSERT INTO t2 VALUES('abc', 'def'); +} +do_test 3.1.2 { + error_messages "SELECT a FROM t2" "DROP TABLE t2" +} [list {*}{ + SQLITE_ERROR {SQL logic error or missing database} + SQLITE_SCHEMA {database schema has changed} +}] +do_execsql_test 3.2.1 { + CREATE TABLE t2(a PRIMARY KEY, b UNIQUE); + INSERT INTO t2 VALUES('abc', 'def'); +} +do_test 3.2.2 { + error_messages_v2 "SELECT a FROM t2" "DROP TABLE t2" +} [list {*}{ + SQLITE_ERROR {no such table: t2} + SQLITE_ERROR {no such table: t2} +}] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/eval.test b/components/external/SQLite-3.8.1/test/eval.test new file mode 100644 index 0000000000000000000000000000000000000000..912dc8215bdf6ddf8476399c4f5b03b9da9c9c69 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/eval.test @@ -0,0 +1,75 @@ +# 2008 July 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file experiments with recursion using the "test_eval()" SQL function +# in order to make sure that SQLite is reentrant. +# +# $Id: eval.test,v 1.2 2008/10/13 10:37:50 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table to work with. +# +do_test eval-1.1 { + execsql { + CREATE TABLE t1(x INTEGER PRIMARY KEY); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 SELECT x+2 FROM t1; + INSERT INTO t1 SELECT x+4 FROM t1; + INSERT INTO t1 SELECT x+8 FROM t1; + INSERT INTO t1 SELECT x+16 FROM t1; + INSERT INTO t1 SELECT x+32 FROM t1; + INSERT INTO t1 SELECT x+64 FROM t1; + INSERT INTO t1 SELECT x+128 FROM t1; + INSERT INTO t1 SELECT x+256 FROM t1; + SELECT count(*), max(x) FROM t1; + } +} {512 512} +do_test eval-1.2 { + execsql { + SELECT x, test_eval('SELECT max(x) FROM t1 WHERE x<' || x) FROM t1 LIMIT 5 + } +} {1 {} 2 1 3 2 4 3 5 4} + +# Delete a row out from under a read cursor in the middle of +# collecting the arguments for a single row in a result set. +# Verify that subsequent rows come out as NULL. +# +do_test eval-2.1 { + execsql { + CREATE TABLE t2(x,y); + INSERT INTO t2 SELECT x, x+1 FROM t1 WHERE x<5; + SELECT x, test_eval('DELETE FROM t2 WHERE x='||x), y FROM t2; + } +} {1 {} {} 2 {} {} 3 {} {} 4 {} {}} +do_test eval-2.2 { + execsql { + SELECT * FROM t2 + } +} {} + +# Modify a row while it is being read. +# +do_test eval-3.1 { + execsql { + INSERT INTO t2 SELECT x, x+1 FROM t1 WHERE x<5; + SELECT x, test_eval('UPDATE t2 SET y=y+100 WHERE x='||x), y FROM t2; + } +} {1 {} 102 2 {} 103 3 {} 104 4 {} 105} + +do_test eval-4.1 { + execsql { SELECT test_eval('SELECT "abcdefghij"') } +} {abcdefghij} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/exclusive.test b/components/external/SQLite-3.8.1/test/exclusive.test new file mode 100644 index 0000000000000000000000000000000000000000..c000dfefa4d803891d3259f58a7dc9fe2a87e336 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/exclusive.test @@ -0,0 +1,508 @@ +# 2007 March 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus +# of these tests is exclusive access mode (i.e. the thing activated by +# "PRAGMA locking_mode = EXCLUSIVE"). +# +# $Id: exclusive.test,v 1.15 2009/06/26 12:30:40 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!pager_pragmas} { + finish_test + return +} + +forcedelete test2.db-journal +forcedelete test2.db +forcedelete test3.db-journal +forcedelete test3.db +forcedelete test4.db-journal +forcedelete test4.db + +#---------------------------------------------------------------------- +# Test cases exclusive-1.X test the PRAGMA logic. +# +do_test exclusive-1.0 { + execsql { + pragma locking_mode; + pragma main.locking_mode; + pragma temp.locking_mode; + } +} [list normal normal exclusive] +do_test exclusive-1.1 { + execsql { + pragma locking_mode = exclusive; + } +} {exclusive} +do_test exclusive-1.2 { + execsql { + pragma locking_mode; + pragma main.locking_mode; + pragma temp.locking_mode; + } +} [list exclusive exclusive exclusive] +do_test exclusive-1.3 { + execsql { + pragma locking_mode = normal; + } +} {normal} +do_test exclusive-1.4 { + execsql { + pragma locking_mode; + pragma main.locking_mode; + pragma temp.locking_mode; + } +} [list normal normal exclusive] +do_test exclusive-1.5 { + execsql { + pragma locking_mode = invalid; + } +} {normal} +do_test exclusive-1.6 { + execsql { + pragma locking_mode; + pragma main.locking_mode; + pragma temp.locking_mode; + } +} [list normal normal exclusive] +ifcapable attach { + do_test exclusive-1.7 { + execsql { + pragma locking_mode = exclusive; + ATTACH 'test2.db' as aux; + } + execsql { + pragma main.locking_mode; + pragma aux.locking_mode; + } + } {exclusive exclusive} + do_test exclusive-1.8 { + execsql { + pragma main.locking_mode = normal; + } + execsql { + pragma main.locking_mode; + pragma temp.locking_mode; + pragma aux.locking_mode; + } + } [list normal exclusive exclusive] + do_test exclusive-1.9 { + execsql { + pragma locking_mode; + } + } {exclusive} + do_test exclusive-1.10 { + execsql { + ATTACH 'test3.db' as aux2; + } + execsql { + pragma main.locking_mode; + pragma aux.locking_mode; + pragma aux2.locking_mode; + } + } {normal exclusive exclusive} + do_test exclusive-1.11 { + execsql { + pragma aux.locking_mode = normal; + } + execsql { + pragma main.locking_mode; + pragma aux.locking_mode; + pragma aux2.locking_mode; + } + } {normal normal exclusive} + do_test exclusive-1.12 { + execsql { + pragma locking_mode = normal; + } + execsql { + pragma main.locking_mode; + pragma temp.locking_mode; + pragma aux.locking_mode; + pragma aux2.locking_mode; + } + } [list normal exclusive normal normal] + do_test exclusive-1.13 { + execsql { + ATTACH 'test4.db' as aux3; + } + execsql { + pragma main.locking_mode; + pragma temp.locking_mode; + pragma aux.locking_mode; + pragma aux2.locking_mode; + pragma aux3.locking_mode; + } + } [list normal exclusive normal normal normal] + + do_test exclusive-1.99 { + execsql { + DETACH aux; + DETACH aux2; + DETACH aux3; + } + } {} +} + +#---------------------------------------------------------------------- +# Test cases exclusive-2.X verify that connections in exclusive +# locking_mode do not relinquish locks. +# +do_test exclusive-2.0 { + execsql { + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(1, 2, 3); + PRAGMA locking_mode = exclusive; + } +} {exclusive} +do_test exclusive-2.1 { + sqlite3 db2 test.db + execsql { + INSERT INTO abc VALUES(4, 5, 6); + SELECT * FROM abc; + } db2 +} {1 2 3 4 5 6} +do_test exclusive-2.2 { + # This causes connection 'db' (in exclusive mode) to establish + # a shared-lock on the db. The other connection should now be + # locked out as a writer. + execsql { + SELECT * FROM abc; + } db +} {1 2 3 4 5 6} +do_test exclusive-2.4 { + execsql { + SELECT * FROM abc; + } db2 +} {1 2 3 4 5 6} +do_test exclusive-2.5 { + catchsql { + INSERT INTO abc VALUES(7, 8, 9); + } db2 +} {1 {database is locked}} +sqlite3_soft_heap_limit 0 +do_test exclusive-2.6 { + # Because connection 'db' only has a shared-lock, the other connection + # will be able to get a RESERVED, but will fail to upgrade to EXCLUSIVE. + execsql { + BEGIN; + INSERT INTO abc VALUES(7, 8, 9); + } db2 + catchsql { + COMMIT + } db2 +} {1 {database is locked}} +do_test exclusive-2.7 { + catchsql { + COMMIT + } db2 +} {1 {database is locked}} +do_test exclusive-2.8 { + execsql { + ROLLBACK; + } db2 +} {} +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) + +do_test exclusive-2.9 { + # Write the database to establish the exclusive lock with connection 'db. + execsql { + INSERT INTO abc VALUES(7, 8, 9); + } db + catchsql { + SELECT * FROM abc; + } db2 +} {1 {database is locked}} +do_test exclusive-2.10 { + # Changing the locking-mode does not release any locks. + execsql { + PRAGMA locking_mode = normal; + } db + catchsql { + SELECT * FROM abc; + } db2 +} {1 {database is locked}} +do_test exclusive-2.11 { + # After changing the locking mode, accessing the db releases locks. + execsql { + SELECT * FROM abc; + } db + execsql { + SELECT * FROM abc; + } db2 +} {1 2 3 4 5 6 7 8 9} +db2 close + +#---------------------------------------------------------------------- +# Tests exclusive-3.X - test that a connection in exclusive mode +# truncates instead of deletes the journal file when committing +# a transaction. +# +# These tests are not run on windows because the windows backend +# opens the journal file for exclusive access, preventing its contents +# from being inspected externally. +# +if {$tcl_platform(platform) != "windows"} { + + # Return a list of two booleans (either 0 or 1). The first is true + # if the named file exists. The second is true only if the file + # exists and the first 28 bytes contain at least one non-zero byte. + # + proc filestate {fname} { + set exists 0 + set content 0 + if {[file exists $fname]} { + set exists 1 + set hdr [hexio_read $fname 0 28] + set content [expr {0==[string match $hdr [string repeat 0 56]]}] + } + list $exists $content + } + + do_test exclusive-3.0 { + filestate test.db-journal + } {0 0} + do_test exclusive-3.1 { + execsql { + PRAGMA locking_mode = exclusive; + BEGIN; + DELETE FROM abc; + } + filestate test.db-journal + } {1 1} + do_test exclusive-3.2 { + execsql { + COMMIT; + } + filestate test.db-journal + } {1 0} + do_test exclusive-3.3 { + execsql { + INSERT INTO abc VALUES('A', 'B', 'C'); + SELECT * FROM abc; + } + } {A B C} + do_test exclusive-3.4 { + execsql { + BEGIN; + UPDATE abc SET a = 1, b = 2, c = 3; + ROLLBACK; + SELECT * FROM abc; + } + } {A B C} + do_test exclusive-3.5 { + filestate test.db-journal + } {1 0} + do_test exclusive-3.6 { + execsql { + PRAGMA locking_mode = normal; + SELECT * FROM abc; + } + filestate test.db-journal + } {0 0} +} + +#---------------------------------------------------------------------- +# Tests exclusive-4.X - test that rollback works correctly when +# in exclusive-access mode. +# + +# The following procedure computes a "signature" for table "t3". If +# T3 changes in any way, the signature should change. +# +# This is used to test ROLLBACK. We gather a signature for t3, then +# make lots of changes to t3, then rollback and take another signature. +# The two signatures should be the same. +# +proc signature {} { + return [db eval {SELECT count(*), md5sum(x) FROM t3}] +} + +do_test exclusive-4.0 { + execsql { PRAGMA locking_mode = exclusive; } + execsql { PRAGMA default_cache_size = 10; } + execsql { + BEGIN; + CREATE TABLE t3(x TEXT); + INSERT INTO t3 VALUES(randstr(10,400)); + INSERT INTO t3 VALUES(randstr(10,400)); + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + COMMIT; + } + execsql {SELECT count(*) FROM t3;} +} {32} + +set ::X [signature] +do_test exclusive-4.1 { + execsql { + BEGIN; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + SELECT count(*) FROM t3; + ROLLBACK; + } + signature +} $::X + +do_test exclusive-4.2 { + execsql { + BEGIN; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + ROLLBACK; + } + signature +} $::X + +do_test exclusive-4.3 { + execsql { + INSERT INTO t3 SELECT randstr(10,400) FROM t3 WHERE random()%10==0; + } +} {} + +do_test exclusive-4.4 { + catch {set ::X [signature]} +} {0} +do_test exclusive-4.5 { + execsql { + PRAGMA locking_mode = NORMAL; + DROP TABLE t3; + DROP TABLE abc; + } +} {normal} + +#---------------------------------------------------------------------- +# Tests exclusive-5.X - test that statement journals are truncated +# instead of deleted when in exclusive access mode. +# + +# Close and reopen the database so that the temp database is no +# longer active. +# +db close +sqlite3 db test.db + +# if we're using proxy locks, we use 3 filedescriptors for a db +# that is open but NOT writing changes, normally +# sqlite uses 1 (proxy locking adds the conch and the local lock) +set using_proxy 0 +foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] { + set using_proxy $value +} +set extrafds 0 +if {$using_proxy!=0} { + set extrafds 2 +} + +do_test exclusive-5.0 { + execsql { + CREATE TABLE abc(a UNIQUE, b UNIQUE, c UNIQUE); + BEGIN; + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc SELECT a+1, b+1, c+1 FROM abc; + } +} {} +do_test exclusive-5.1 { + # Three files are open: The db, journal and statement-journal. + set sqlite_open_file_count + expr $sqlite_open_file_count-$extrafds +} [expr 3 - ($TEMP_STORE>=2)] +do_test exclusive-5.2 { + execsql { + COMMIT; + } + # One file open: the db. + set sqlite_open_file_count + expr $sqlite_open_file_count-$extrafds +} {1} +do_test exclusive-5.3 { + execsql { + PRAGMA locking_mode = exclusive; + BEGIN; + INSERT INTO abc VALUES(5, 6, 7); + } + # Two files open: the db and journal. + set sqlite_open_file_count + expr $sqlite_open_file_count-$extrafds +} {2} +do_test exclusive-5.4 { + execsql { + INSERT INTO abc SELECT a+10, b+10, c+10 FROM abc; + } + # Three files are open: The db, journal and statement-journal. + set sqlite_open_file_count + expr $sqlite_open_file_count-$extrafds +} [expr 3 - ($TEMP_STORE>=2)] +do_test exclusive-5.5 { + execsql { + COMMIT; + } + # Three files are still open: The db, journal and statement-journal. + set sqlite_open_file_count + expr $sqlite_open_file_count-$extrafds +} [expr 3 - ($TEMP_STORE>=2)] +do_test exclusive-5.6 { + execsql { + PRAGMA locking_mode = normal; + SELECT * FROM abc; + } +} {normal 1 2 3 2 3 4 5 6 7 11 12 13 12 13 14 15 16 17} +do_test exclusive-5.7 { + # Just the db open. + set sqlite_open_file_count + expr $sqlite_open_file_count-$extrafds +} {1} + +#------------------------------------------------------------------------- + +do_execsql_test exclusive-6.1 { + CREATE TABLE t4(a, b); + INSERT INTO t4 VALUES('Eden', 1955); + BEGIN; + INSERT INTO t4 VALUES('Macmillan', 1957); + INSERT INTO t4 VALUES('Douglas-Home', 1963); + INSERT INTO t4 VALUES('Wilson', 1964); +} +do_test exclusive-6.2 { + forcedelete test2.db test2.db-journal + copy_file test.db test2.db + copy_file test.db-journal test2.db-journal + sqlite3 db test2.db +} {} + +do_execsql_test exclusive-6.3 { + PRAGMA locking_mode = EXCLUSIVE; + SELECT * FROM t4; +} {exclusive Eden 1955} + +do_test exclusive-6.4 { + db close + forcedelete test.db test.db-journal + set fd [open test.db-journal w] + puts $fd x + close $fd + sqlite3 db test.db +} {} + +do_execsql_test exclusive-6.5 { + PRAGMA locking_mode = EXCLUSIVE; + SELECT * FROM sqlite_master; +} {exclusive} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/exclusive2.test b/components/external/SQLite-3.8.1/test/exclusive2.test new file mode 100644 index 0000000000000000000000000000000000000000..54203e3d8f3f8ed9fe40d9dcf93778b20e7001a0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/exclusive2.test @@ -0,0 +1,325 @@ +# 2007 March 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# $Id: exclusive2.test,v 1.10 2008/11/27 02:22:11 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +ifcapable {!pager_pragmas} { + finish_test + return +} + +# Tests in this file verify that locking_mode=exclusive causes SQLite to +# use cached pages even if the database is changed on disk. This doesn't +# work with mmap. +if {[permutation]=="mmap"} { + finish_test + return +} + +# This module does not work right if the cache spills at unexpected +# moments. So disable the soft-heap-limit. +# +sqlite3_soft_heap_limit 0 + +proc pagerChangeCounter {filename new {fd ""}} { + if {$fd==""} { + set fd [open $filename RDWR] + fconfigure $fd -translation binary -encoding binary + set needClose 1 + } else { + set needClose 0 + } + if {$new ne ""} { + seek $fd 24 + set a [expr {($new&0xFF000000)>>24}] + set b [expr {($new&0x00FF0000)>>16}] + set c [expr {($new&0x0000FF00)>>8}] + set d [expr {($new&0x000000FF)}] + puts -nonewline $fd [binary format cccc $a $b $c $d] + flush $fd + } + + seek $fd 24 + foreach {a b c d} [list 0 0 0 0] {} + binary scan [read $fd 4] cccc a b c d + set ret [expr ($a&0x000000FF)<<24] + incr ret [expr ($b&0x000000FF)<<16] + incr ret [expr ($c&0x000000FF)<<8] + incr ret [expr ($d&0x000000FF)<<0] + + if {$needClose} {close $fd} + return $ret +} + +proc readPagerChangeCounter {filename} { + set fd [open $filename RDONLY] + fconfigure $fd -translation binary -encoding binary + + seek $fd 24 + foreach {a b c d} [list 0 0 0 0] {} + binary scan [read $fd 4] cccc a b c d + set ret [expr ($a&0x000000FF)<<24] + incr ret [expr ($b&0x000000FF)<<16] + incr ret [expr ($c&0x000000FF)<<8] + incr ret [expr ($d&0x000000FF)<<0] + + close $fd + return $ret +} + + +proc t1sig {{db db}} { + execsql {SELECT count(*), md5sum(a) FROM t1} $db +} +do_test exclusive2-1.0 { + readPagerChangeCounter test.db +} {0} + +#----------------------------------------------------------------------- +# The following tests - exclusive2-1.X - check that: +# +# 1-3: Build a database with connection 1, calculate a signature. +# 4-7: Modify the database using a second connection in a way that +# does not modify the freelist, then reset the pager change-counter +# to the value it had before the modifications. +# 8: Check that using the first connection, the database signature +# is still the same. This is because it uses the in-memory cache. +# It can't tell the db has changed because we reset the change-counter. +# 9: Increment the change-counter. +# 10: Ensure that the first connection now sees the updated database. It +# sees the change-counter has been incremented and discards the +# invalid in-memory cache. +# +# This will only work if the database cache is large enough to hold +# the entire database. In the case of 1024 byte pages, this means +# the cache size must be at least 17. Otherwise, some pages will be +# loaded from the database file in step 8. +# +# For similar reasons, this test does not work with the memsubsys1 permutation. +# Permutation memsubsys1 configures the pcache subsystem to use a static +# allocation of 24 pages (shared between all pagers). This is not enough for +# this test. +# +do_test exclusive2-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1(a) VALUES(randstr(10, 400)); + INSERT INTO t1(a) VALUES(randstr(10, 400)); + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + COMMIT; + SELECT count(*) FROM t1; + } +} {64} +do_test exclusive2-1.2.1 { + # Make sure the pager cache is large enough to store the + # entire database. + set nPage [expr [file size test.db]/1024] + if {$::SQLITE_DEFAULT_CACHE_SIZE < $nPage} { + execsql "PRAGMA cache_size = $nPage" + } + expr {[execsql {PRAGMA cache_size}] >= $nPage} +} {1} +do_test exclusive2-1.2 { + set ::sig [t1sig] + readPagerChangeCounter test.db +} {1} +do_test exclusive2-1.3 { + t1sig +} $::sig +do_test exclusive2-1.4 { + sqlite3 db2 test.db + t1sig db2 +} $::sig +do_test exclusive2-1.5 { + execsql { + UPDATE t1 SET b=a, a=NULL; + } db2 + expr {[t1sig db2] eq $::sig} +} 0 +do_test exclusive2-1.6 { + readPagerChangeCounter test.db +} {2} +do_test exclusive2-1.7 { + pagerChangeCounter test.db 1 +} {1} +if {[permutation] != "memsubsys1"} { + do_test exclusive2-1.9 { + t1sig + expr {[t1sig] eq $::sig} + } {1} +} +do_test exclusive2-1.10 { + pagerChangeCounter test.db 2 +} {2} +do_test exclusive2-1.11 { + expr {[t1sig] eq $::sig} +} {0} +db2 close + +#-------------------------------------------------------------------- +# These tests - exclusive2-2.X - are similar to exclusive2-1.X, +# except that they are run with locking_mode=EXCLUSIVE. +# +# 1-3: Build a database with exclusive-access connection 1, +# calculate a signature. +# 4: Corrupt the database by writing 10000 bytes of garbage +# starting at the beginning of page 2. Check that connection 1 +# still works. It should be accessing the in-memory cache. +# 5-6: Modify the dataase change-counter. Connection 1 still works +# entirely from in-memory cache, because it doesn't check the +# change-counter. +# 7-8 Set the locking-mode back to normal. After the db is unlocked, +# SQLite detects the modified change-counter and discards the +# in-memory cache. Then it finds the corruption caused in step 4.... +# +# As above, this test is only applicable if the pager cache is +# large enough to hold the entire database. With 1024 byte pages, +# this means 19 pages. We also need to disable the soft-heap-limit +# to prevent memory-induced cache spills. +# +do_test exclusive2-2.1 { + execsql {PRAGMA cache_size=1000;} + execsql {PRAGMA locking_mode = exclusive;} + execsql { + BEGIN; + DELETE FROM t1; + INSERT INTO t1(a) VALUES(randstr(10, 400)); + INSERT INTO t1(a) VALUES(randstr(10, 400)); + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + INSERT INTO t1(a) SELECT randstr(10, 400) FROM t1; + COMMIT; + SELECT count(*) FROM t1; + } +} {64} +do_test exclusive2-2.2.1 { + # Make sure the pager cache is large enough to store the + # entire database. + set nPage [expr [file size test.db]/1024] + if {$::SQLITE_DEFAULT_CACHE_SIZE < $nPage} { + execsql "PRAGMA cache_size = $nPage" + } + expr {[execsql {PRAGMA cache_size}] >= $nPage} +} {1} +do_test exclusive2-2.2 { + set ::sig [t1sig] + readPagerChangeCounter test.db +} {3} +do_test exclusive2-2.3 { + t1sig +} $::sig + +do_test exclusive2-2.4 { + set ::fd [open test.db RDWR] + fconfigure $::fd -translation binary + seek $::fd 1024 + puts -nonewline $::fd [string repeat [binary format c 0] 10000] + flush $::fd + t1sig +} $::sig + +do_test exclusive2-2.5 { + pagerChangeCounter test.db 5 $::fd +} {5} +do_test exclusive2-2.6 { + t1sig +} $::sig +do_test exclusive2-2.7 { + execsql {PRAGMA locking_mode = normal} + t1sig +} $::sig + +do_test exclusive2-2.8 { + set rc [catch {t1sig} msg] + list $rc $msg +} {1 {database disk image is malformed}} + +#-------------------------------------------------------------------- +# These tests - exclusive2-3.X - verify that the pager change-counter +# is only incremented by the first change when in exclusive access +# mode. In normal mode, the change-counter is incremented once +# per write-transaction. +# + +db close +catch {close $::fd} +forcedelete test.db +forcedelete test.db-journal + +do_test exclusive2-3.0 { + sqlite3 db test.db + execsql { + BEGIN; + CREATE TABLE t1(a UNIQUE); + INSERT INTO t1 VALUES(randstr(200, 200)); + INSERT INTO t1 VALUES(randstr(200, 200)); + COMMIT; + } + readPagerChangeCounter test.db +} {1} +do_test exclusive2-3.1 { + execsql { + INSERT INTO t1 VALUES(randstr(200, 200)); + } + readPagerChangeCounter test.db +} {2} +do_test exclusive2-3.2 { + execsql { + INSERT INTO t1 VALUES(randstr(200, 200)); + } + readPagerChangeCounter test.db +} {3} +do_test exclusive2-3.3 { + execsql { + PRAGMA locking_mode = exclusive; + INSERT INTO t1 VALUES(randstr(200, 200)); + } + readPagerChangeCounter test.db +} {4} +do_test exclusive2-3.4 { +breakpoint + execsql { + INSERT INTO t1 VALUES(randstr(200, 200)); + } + readPagerChangeCounter test.db +} {4} +do_test exclusive2-3.5 { + execsql { + PRAGMA locking_mode = normal; + INSERT INTO t1 VALUES(randstr(200, 200)); + } + readPagerChangeCounter test.db +} {4} +do_test exclusive2-3.6 { + execsql { + INSERT INTO t1 VALUES(randstr(200, 200)); + } + readPagerChangeCounter test.db +} {5} +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) + +finish_test diff --git a/components/external/SQLite-3.8.1/test/exec.test b/components/external/SQLite-3.8.1/test/exec.test new file mode 100644 index 0000000000000000000000000000000000000000..dbcc6265b344bc8cbdfe650bf87bd0b665176a01 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/exec.test @@ -0,0 +1,37 @@ +# 2008 Jan 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the sqlite3_exec interface +# +# $Id: exec.test,v 1.1 2008/01/21 16:22:46 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test exec-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + SELECT * FROM t1; + } +} {1 2} +do_test exec-1.2 { + sqlite3_exec db {/* comment */;;; SELECT * FROM t1; /* comment */} +} {0 {a b 1 2}} +do_test exec-1.3 { + sqlite3 db2 test.db + db2 eval {CREATE TABLE t2(x, y);} + db2 close + sqlite3_exec db {SELECT * FROM t1} +} {0 {a b 1 2}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/exists.test b/components/external/SQLite-3.8.1/test/exists.test new file mode 100644 index 0000000000000000000000000000000000000000..fb73797d2997a90ec859aa1c20962d6b782b6447 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/exists.test @@ -0,0 +1,198 @@ +# 2011 April 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the various schema modification statements +# that feature "IF EXISTS" or "IF NOT EXISTS" clauses. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl + + +foreach jm {rollback wal} { + + set testprefix exists-$jm + + # This block of tests is targeted at CREATE XXX IF NOT EXISTS statements. + # + do_multiclient_test tn { + + # TABLE objects. + # + do_test 1.$tn.1.1 { + if {$jm == "wal"} { sql2 { PRAGMA journal_mode = WAL } } + sql2 { CREATE TABLE t1(x) } + sql1 { CREATE TABLE IF NOT EXISTS t1(a, b) } + sql2 { DROP TABLE t1 } + sql1 { CREATE TABLE IF NOT EXISTS t1(a, b) } + sql2 { SELECT name FROM sqlite_master WHERE type = 'table' } + } {t1} + + do_test 1.$tn.1.2 { + sql2 { CREATE TABLE t2(x) } + sql1 { CREATE TABLE IF NOT EXISTS t2 AS SELECT * FROM t1 } + sql2 { DROP TABLE t2 } + sql1 { CREATE TABLE IF NOT EXISTS t2 AS SELECT * FROM t1 } + sql2 { SELECT name FROM sqlite_master WHERE type = 'table' } + } {t1 t2} + + + # INDEX objects. + # + do_test 1.$tn.2 { + sql2 { CREATE INDEX i1 ON t1(a) } + sql1 { CREATE INDEX IF NOT EXISTS i1 ON t1(a, b) } + sql2 { DROP INDEX i1 } + sql1 { CREATE INDEX IF NOT EXISTS i1 ON t1(a, b) } + sql2 { SELECT name FROM sqlite_master WHERE type = 'index' } + } {i1} + + # VIEW objects. + # + do_test 1.$tn.3 { + sql2 { CREATE VIEW v1 AS SELECT * FROM t1 } + sql1 { CREATE VIEW IF NOT EXISTS v1 AS SELECT * FROM t1 } + sql2 { DROP VIEW v1 } + sql1 { CREATE VIEW IF NOT EXISTS v1 AS SELECT * FROM t1 } + sql2 { SELECT name FROM sqlite_master WHERE type = 'view' } + } {v1} + + # TRIGGER objects. + # + do_test $tn.4 { + sql2 { CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN SELECT 1; END } + sql1 { CREATE TRIGGER IF NOT EXISTS tr1 AFTER INSERT ON t1 BEGIN SELECT 1; END } + sql2 { DROP TRIGGER tr1 } + sql1 { CREATE TRIGGER IF NOT EXISTS tr1 AFTER INSERT ON t1 BEGIN SELECT 1; END } + sql2 { SELECT name FROM sqlite_master WHERE type = 'trigger' } + } {tr1} + } + + # This block of tests is targeted at DROP XXX IF EXISTS statements. + # + do_multiclient_test tn { + + # TABLE objects. + # + do_test 2.$tn.1 { + if {$jm == "wal"} { sql1 { PRAGMA journal_mode = WAL } } + sql1 { DROP TABLE IF EXISTS t1 } + sql2 { CREATE TABLE t1(x) } + sql1 { DROP TABLE IF EXISTS t1 } + sql2 { SELECT name FROM sqlite_master WHERE type = 'table' } + } {} + + # INDEX objects. + # + do_test 2.$tn.2 { + sql1 { CREATE TABLE t2(x) } + sql1 { DROP INDEX IF EXISTS i2 } + sql2 { CREATE INDEX i2 ON t2(x) } + sql1 { DROP INDEX IF EXISTS i2 } + sql2 { SELECT name FROM sqlite_master WHERE type = 'index' } + } {} + + # VIEW objects. + # + do_test 2.$tn.3 { + sql1 { DROP VIEW IF EXISTS v1 } + sql2 { CREATE VIEW v1 AS SELECT * FROM t2 } + sql1 { DROP VIEW IF EXISTS v1 } + sql2 { SELECT name FROM sqlite_master WHERE type = 'view' } + } {} + + # TRIGGER objects. + # + do_test 2.$tn.4 { + sql1 { DROP TRIGGER IF EXISTS tr1 } + sql2 { CREATE TRIGGER tr1 AFTER INSERT ON t2 BEGIN SELECT 1; END } + sql1 { DROP TRIGGER IF EXISTS tr1 } + sql2 { SELECT name FROM sqlite_master WHERE type = 'trigger' } + } {} + } + + # This block of tests is targeted at DROP XXX IF EXISTS statements with + # attached databases. + # + do_multiclient_test tn { + + forcedelete test.db2 + do_test 3.$tn.0 { + sql1 { ATTACH 'test.db2' AS aux } + sql2 { ATTACH 'test.db2' AS aux } + } {} + + # TABLE objects. + # + do_test 3.$tn.1.1 { + sql1 { DROP TABLE IF EXISTS aux.t1 } + sql2 { CREATE TABLE aux.t1(x) } + sql1 { DROP TABLE IF EXISTS aux.t1 } + sql2 { SELECT name FROM aux.sqlite_master WHERE type = 'table' } + } {} + do_test 3.$tn.1.2 { + sql1 { DROP TABLE IF EXISTS t1 } + sql2 { CREATE TABLE aux.t1(x) } + sql1 { DROP TABLE IF EXISTS t1 } + sql2 { SELECT name FROM aux.sqlite_master WHERE type = 'table' } + } {} + + # INDEX objects. + # + do_test 3.$tn.2.1 { + sql1 { CREATE TABLE aux.t2(x) } + sql1 { DROP INDEX IF EXISTS aux.i2 } + sql2 { CREATE INDEX aux.i2 ON t2(x) } + sql1 { DROP INDEX IF EXISTS aux.i2 } + sql2 { SELECT name FROM aux.sqlite_master WHERE type = 'index' } + } {} + do_test 3.$tn.2.2 { + sql1 { DROP INDEX IF EXISTS i2 } + sql2 { CREATE INDEX aux.i2 ON t2(x) } + sql1 { DROP INDEX IF EXISTS i2 } + sql2 { SELECT * FROM aux.sqlite_master WHERE type = 'index' } + } {} + + # VIEW objects. + # + do_test 3.$tn.3.1 { + sql1 { DROP VIEW IF EXISTS aux.v1 } + sql2 { CREATE VIEW aux.v1 AS SELECT * FROM t2 } + sql1 { DROP VIEW IF EXISTS aux.v1 } + sql2 { SELECT name FROM aux.sqlite_master WHERE type = 'view' } + } {} + do_test 3.$tn.3.2 { + sql1 { DROP VIEW IF EXISTS v1 } + sql2 { CREATE VIEW aux.v1 AS SELECT * FROM t2 } + sql1 { DROP VIEW IF EXISTS v1 } + sql2 { SELECT name FROM aux.sqlite_master WHERE type = 'view' } + } {} + + # TRIGGER objects. + # + do_test 3.$tn.4.1 { + sql1 { DROP TRIGGER IF EXISTS aux.tr1 } + sql2 { CREATE TRIGGER aux.tr1 AFTER INSERT ON t2 BEGIN SELECT 1; END } + sql1 { DROP TRIGGER IF EXISTS aux.tr1 } + sql2 { SELECT name FROM aux.sqlite_master WHERE type = 'trigger' } + } {} + do_test 3.$tn.4.2 { + sql1 { DROP TRIGGER IF EXISTS tr1 } + sql2 { CREATE TRIGGER aux.tr1 AFTER INSERT ON t2 BEGIN SELECT 1; END } + sql1 { DROP TRIGGER IF EXISTS tr1 } + sql2 { SELECT name FROM aux.sqlite_master WHERE type = 'trigger' } + } {} + } +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/expr.test b/components/external/SQLite-3.8.1/test/expr.test new file mode 100644 index 0000000000000000000000000000000000000000..cc4c9c67f1815e4a76db82292434e18fd08650aa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/expr.test @@ -0,0 +1,943 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing expressions. +# +# $Id: expr.test,v 1.67 2009/02/04 03:59:25 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table to work with. +# +ifcapable floatingpoint { + execsql {CREATE TABLE test1(i1 int, i2 int, r1 real, r2 real, t1 text, t2 text)} + execsql {INSERT INTO test1 VALUES(1,2,1.1,2.2,'hello','world')} +} +ifcapable !floatingpoint { + execsql {CREATE TABLE test1(i1 int, i2 int, t1 text, t2 text)} + execsql {INSERT INTO test1 VALUES(1,2,'hello','world')} +} + +proc test_expr {name settings expr result} { + do_test $name [format { + execsql {BEGIN; UPDATE test1 SET %s; SELECT %s FROM test1; ROLLBACK;} + } $settings $expr] $result +} +proc test_realnum_expr {name settings expr result} { + do_realnum_test $name [format { + execsql {BEGIN; UPDATE test1 SET %s; SELECT %s FROM test1; ROLLBACK;} + } $settings $expr] $result +} + +test_expr expr-1.1 {i1=10, i2=20} {i1+i2} 30 +test_expr expr-1.2 {i1=10, i2=20} {i1-i2} -10 +test_expr expr-1.3 {i1=10, i2=20} {i1*i2} 200 +test_expr expr-1.4 {i1=10, i2=20} {i1/i2} 0 +test_expr expr-1.5 {i1=10, i2=20} {i2/i1} 2 +test_expr expr-1.6 {i1=10, i2=20} {i2i1} 1 +test_expr expr-1.9 {i1=10, i2=20} {i2>=i1} 1 +test_expr expr-1.10 {i1=10, i2=20} {i2!=i1} 1 +test_expr expr-1.11 {i1=10, i2=20} {i2=i1} 0 +test_expr expr-1.12 {i1=10, i2=20} {i2<>i1} 1 +test_expr expr-1.13 {i1=10, i2=20} {i2==i1} 0 +test_expr expr-1.14 {i1=20, i2=20} {i2i1} 0 +test_expr expr-1.17 {i1=20, i2=20} {i2>=i1} 1 +test_expr expr-1.18 {i1=20, i2=20} {i2!=i1} 0 +test_expr expr-1.19 {i1=20, i2=20} {i2=i1} 1 +test_expr expr-1.20 {i1=20, i2=20} {i2<>i1} 0 +test_expr expr-1.21 {i1=20, i2=20} {i2==i1} 1 +ifcapable floatingpoint { + test_expr expr-1.22 {i1=1, i2=2, r1=3.0} {i1+i2*r1} {7.0} + test_expr expr-1.23 {i1=1, i2=2, r1=3.0} {(i1+i2)*r1} {9.0} +} +test_expr expr-1.24 {i1=1, i2=2} {min(i1,i2,i1+i2,i1-i2)} {-1} +test_expr expr-1.25 {i1=1, i2=2} {max(i1,i2,i1+i2,i1-i2)} {3} +test_expr expr-1.26 {i1=1, i2=2} {max(i1,i2,i1+i2,i1-i2)} {3} +test_expr expr-1.27 {i1=1, i2=2} {i1==1 AND i2=2} {1} +test_expr expr-1.28 {i1=1, i2=2} {i1=2 AND i2=1} {0} +test_expr expr-1.29 {i1=1, i2=2} {i1=1 AND i2=1} {0} +test_expr expr-1.30 {i1=1, i2=2} {i1=2 AND i2=2} {0} +test_expr expr-1.31 {i1=1, i2=2} {i1==1 OR i2=2} {1} +test_expr expr-1.32 {i1=1, i2=2} {i1=2 OR i2=1} {0} +test_expr expr-1.33 {i1=1, i2=2} {i1=1 OR i2=1} {1} +test_expr expr-1.34 {i1=1, i2=2} {i1=2 OR i2=2} {1} +test_expr expr-1.35 {i1=1, i2=2} {i1-i2=-1} {1} +test_expr expr-1.36 {i1=1, i2=0} {not i1} {0} +test_expr expr-1.37 {i1=1, i2=0} {not i2} {1} +test_expr expr-1.38 {i1=1} {-i1} {-1} +test_expr expr-1.39 {i1=1} {+i1} {1} +test_expr expr-1.40 {i1=1, i2=2} {+(i2+i1)} {3} +test_expr expr-1.41 {i1=1, i2=2} {-(i2+i1)} {-3} +test_expr expr-1.42 {i1=1, i2=2} {i1|i2} {3} +test_expr expr-1.42b {i1=1, i2=2} {4|2} {6} +test_expr expr-1.43 {i1=1, i2=2} {i1&i2} {0} +test_expr expr-1.43b {i1=1, i2=2} {4&5} {4} +test_expr expr-1.44 {i1=1} {~i1} {-2} +test_expr expr-1.44b {i1=NULL} {~i1} {{}} +test_expr expr-1.45a {i1=1, i2=3} {i1<>i2} {8} +test_expr expr-1.45c {i1=1, i2=0} {i1<>i2} {0} +test_expr expr-1.46a {i1=32, i2=3} {i1>>i2} {4} +test_expr expr-1.46b {i1=32, i2=6} {i1>>i2} {0} +test_expr expr-1.46c {i1=-32, i2=3} {i1>>i2} {-4} +test_expr expr-1.46d {i1=-32, i2=100} {i1>>i2} {-1} +test_expr expr-1.46e {i1=32, i2=-3} {i1>>i2} {256} +test_expr expr-1.47 {i1=9999999999, i2=8888888888} {i1i2} 1 +test_expr expr-1.50 {i1=99999999999, i2=99999999998} {i1i2} 1 +test_expr expr-1.53 {i1=099999999999, i2=99999999999} {i1i2} 0 +test_expr expr-1.56 {i1=25, i2=11} {i1%i2} 3 +test_expr expr-1.58 {i1=NULL, i2=1} {coalesce(i1+i2,99)} 99 +test_expr expr-1.59 {i1=1, i2=NULL} {coalesce(i1+i2,99)} 99 +test_expr expr-1.60 {i1=NULL, i2=NULL} {coalesce(i1+i2,99)} 99 +test_expr expr-1.61 {i1=NULL, i2=1} {coalesce(i1-i2,99)} 99 +test_expr expr-1.62 {i1=1, i2=NULL} {coalesce(i1-i2,99)} 99 +test_expr expr-1.63 {i1=NULL, i2=NULL} {coalesce(i1-i2,99)} 99 +test_expr expr-1.64 {i1=NULL, i2=1} {coalesce(i1*i2,99)} 99 +test_expr expr-1.65 {i1=1, i2=NULL} {coalesce(i1*i2,99)} 99 +test_expr expr-1.66 {i1=NULL, i2=NULL} {coalesce(i1*i2,99)} 99 +test_expr expr-1.67 {i1=NULL, i2=1} {coalesce(i1/i2,99)} 99 +test_expr expr-1.68 {i1=1, i2=NULL} {coalesce(i1/i2,99)} 99 +test_expr expr-1.69 {i1=NULL, i2=NULL} {coalesce(i1/i2,99)} 99 +test_expr expr-1.70 {i1=NULL, i2=1} {coalesce(i1i2,99)} 99 +test_expr expr-1.72 {i1=NULL, i2=NULL} {coalesce(i1<=i2,99)} 99 +test_expr expr-1.73 {i1=NULL, i2=1} {coalesce(i1>=i2,99)} 99 +test_expr expr-1.74 {i1=1, i2=NULL} {coalesce(i1!=i2,99)} 99 +test_expr expr-1.75 {i1=NULL, i2=NULL} {coalesce(i1==i2,99)} 99 +test_expr expr-1.76 {i1=NULL, i2=NULL} {coalesce(not i1,99)} 99 +test_expr expr-1.77 {i1=NULL, i2=NULL} {coalesce(-i1,99)} 99 +test_expr expr-1.78 {i1=NULL, i2=NULL} {coalesce(i1 IS NULL AND i2=5,99)} 99 +test_expr expr-1.79 {i1=NULL, i2=NULL} {coalesce(i1 IS NULL OR i2=5,99)} 1 +test_expr expr-1.80 {i1=NULL, i2=NULL} {coalesce(i1=5 AND i2 IS NULL,99)} 99 +test_expr expr-1.81 {i1=NULL, i2=NULL} {coalesce(i1=5 OR i2 IS NULL,99)} 1 +test_expr expr-1.82 {i1=NULL, i2=3} {coalesce(min(i1,i2,1),99)} 99 +test_expr expr-1.83 {i1=NULL, i2=3} {coalesce(max(i1,i2,1),99)} 99 +test_expr expr-1.84 {i1=3, i2=NULL} {coalesce(min(i1,i2,1),99)} 99 +test_expr expr-1.85 {i1=3, i2=NULL} {coalesce(max(i1,i2,1),99)} 99 +test_expr expr-1.86 {i1=3, i2=8} {5 between i1 and i2} 1 +test_expr expr-1.87 {i1=3, i2=8} {5 not between i1 and i2} 0 +test_expr expr-1.88 {i1=3, i2=8} {55 between i1 and i2} 0 +test_expr expr-1.89 {i1=3, i2=8} {55 not between i1 and i2} 1 +test_expr expr-1.90 {i1=3, i2=NULL} {5 between i1 and i2} {{}} +test_expr expr-1.91 {i1=3, i2=NULL} {5 not between i1 and i2} {{}} +test_expr expr-1.92 {i1=3, i2=NULL} {2 between i1 and i2} 0 +test_expr expr-1.93 {i1=3, i2=NULL} {2 not between i1 and i2} 1 +test_expr expr-1.94 {i1=NULL, i2=8} {2 between i1 and i2} {{}} +test_expr expr-1.95 {i1=NULL, i2=8} {2 not between i1 and i2} {{}} +test_expr expr-1.94 {i1=NULL, i2=8} {55 between i1 and i2} 0 +test_expr expr-1.95 {i1=NULL, i2=8} {55 not between i1 and i2} 1 +test_expr expr-1.96 {i1=NULL, i2=3} {coalesce(i1<>i2,99)} 99 +test_expr expr-1.98 {i1=NULL, i2=NULL} {coalesce(i1|i2,99)} 99 +test_expr expr-1.99 {i1=32, i2=NULL} {coalesce(i1&i2,99)} 99 +test_expr expr-1.100 {i1=1, i2=''} {i1=i2} 0 +test_expr expr-1.101 {i1=0, i2=''} {i1=i2} 0 + +# Check for proper handling of 64-bit integer values. +# +if {[working_64bit_int]} { + test_expr expr-1.102 {i1=40, i2=1} {i2<1} 1 +} + +if {[working_64bit_int]} { + test_realnum_expr expr-1.106 {i1=0} {-9223372036854775808/-1} 9.22337203685478e+18 +} + +test_expr expr-1.107 {i1=0} {-9223372036854775808%-1} 0 +test_expr expr-1.108 {i1=0} {1%0} {{}} +test_expr expr-1.109 {i1=0} {1/0} {{}} + +if {[working_64bit_int]} { + test_expr expr-1.110 {i1=0} {-9223372036854775807/-1} 9223372036854775807 +} + +test_expr expr-1.111 {i1=NULL, i2=8} {i1 IS i2} 0 +test_expr expr-1.112 {i1=NULL, i2=NULL} {i1 IS i2} 1 +test_expr expr-1.113 {i1=6, i2=NULL} {i1 IS i2} 0 +test_expr expr-1.114 {i1=6, i2=6} {i1 IS i2} 1 +test_expr expr-1.115 {i1=NULL, i2=8} \ + {CASE WHEN i1 IS i2 THEN 'yes' ELSE 'no' END} no +test_expr expr-1.116 {i1=NULL, i2=NULL} \ + {CASE WHEN i1 IS i2 THEN 'yes' ELSE 'no' END} yes +test_expr expr-1.117 {i1=6, i2=NULL} \ + {CASE WHEN i1 IS i2 THEN 'yes' ELSE 'no' END} no +test_expr expr-1.118 {i1=8, i2=8} \ + {CASE WHEN i1 IS i2 THEN 'yes' ELSE 'no' END} yes +test_expr expr-1.119 {i1=NULL, i2=8} {i1 IS NOT i2} 1 +test_expr expr-1.120 {i1=NULL, i2=NULL} {i1 IS NOT i2} 0 +test_expr expr-1.121 {i1=6, i2=NULL} {i1 IS NOT i2} 1 +test_expr expr-1.122 {i1=6, i2=6} {i1 IS NOT i2} 0 +test_expr expr-1.123 {i1=NULL, i2=8} \ + {CASE WHEN i1 IS NOT i2 THEN 'yes' ELSE 'no' END} yes +test_expr expr-1.124 {i1=NULL, i2=NULL} \ + {CASE WHEN i1 IS NOT i2 THEN 'yes' ELSE 'no' END} no +test_expr expr-1.125 {i1=6, i2=NULL} \ + {CASE WHEN i1 IS NOT i2 THEN 'yes' ELSE 'no' END} yes +test_expr expr-1.126 {i1=8, i2=8} \ + {CASE WHEN i1 IS NOT i2 THEN 'yes' ELSE 'no' END} no + +ifcapable floatingpoint {if {[working_64bit_int]} { + test_expr expr-1.200\ + {i1=9223372036854775806, i2=1} {i1+i2} 9223372036854775807 + test_realnum_expr expr-1.201\ + {i1=9223372036854775806, i2=2} {i1+i2} 9.22337203685478e+18 + test_realnum_expr expr-1.202\ + {i1=9223372036854775806, i2=100000} {i1+i2} 9.22337203685488e+18 + test_realnum_expr expr-1.203\ + {i1=9223372036854775807, i2=0} {i1+i2} 9223372036854775807 + test_realnum_expr expr-1.204\ + {i1=9223372036854775807, i2=1} {i1+i2} 9.22337203685478e+18 + test_realnum_expr expr-1.205\ + {i2=9223372036854775806, i1=1} {i1+i2} 9223372036854775807 + test_realnum_expr expr-1.206\ + {i2=9223372036854775806, i1=2} {i1+i2} 9.22337203685478e+18 + test_realnum_expr expr-1.207\ + {i2=9223372036854775806, i1=100000} {i1+i2} 9.22337203685488e+18 + test_realnum_expr expr-1.208\ + {i2=9223372036854775807, i1=0} {i1+i2} 9223372036854775807 + test_realnum_expr expr-1.209\ + {i2=9223372036854775807, i1=1} {i1+i2} 9.22337203685478e+18 + test_realnum_expr expr-1.210\ + {i1=-9223372036854775807, i2=-1} {i1+i2} -9223372036854775808 + test_realnum_expr expr-1.211\ + {i1=-9223372036854775807, i2=-2} {i1+i2} -9.22337203685478e+18 + test_realnum_expr expr-1.212\ + {i1=-9223372036854775807, i2=-100000} {i1+i2} -9.22337203685488e+18 + test_realnum_expr expr-1.213\ + {i1=-9223372036854775808, i2=0} {i1+i2} -9223372036854775808 + test_realnum_expr expr-1.214\ + {i1=-9223372036854775808, i2=-1} {i1+i2} -9.22337203685478e+18 + test_realnum_expr expr-1.215\ + {i2=-9223372036854775807, i1=-1} {i1+i2} -9223372036854775808 + test_realnum_expr expr-1.216\ + {i2=-9223372036854775807, i1=-2} {i1+i2} -9.22337203685478e+18 + test_realnum_expr expr-1.217\ + {i2=-9223372036854775807, i1=-100000} {i1+i2} -9.22337203685488e+18 + test_realnum_expr expr-1.218\ + {i2=-9223372036854775808, i1=0} {i1+i2} -9223372036854775808 + test_realnum_expr expr-1.219\ + {i2=-9223372036854775808, i1=-1} {i1+i2} -9.22337203685478e+18 + test_realnum_expr expr-1.220\ + {i1=9223372036854775806, i2=-1} {i1-i2} 9223372036854775807 + test_realnum_expr expr-1.221\ + {i1=9223372036854775806, i2=-2} {i1-i2} 9.22337203685478e+18 + test_realnum_expr expr-1.222\ + {i1=9223372036854775806, i2=-100000} {i1-i2} 9.22337203685488e+18 + test_realnum_expr expr-1.223\ + {i1=9223372036854775807, i2=0} {i1-i2} 9223372036854775807 + test_realnum_expr expr-1.224\ + {i1=9223372036854775807, i2=-1} {i1-i2} 9.22337203685478e+18 + test_realnum_expr expr-1.225\ + {i2=-9223372036854775806, i1=1} {i1-i2} 9223372036854775807 + test_realnum_expr expr-1.226\ + {i2=-9223372036854775806, i1=2} {i1-i2} 9.22337203685478e+18 + test_realnum_expr expr-1.227\ + {i2=-9223372036854775806, i1=100000} {i1-i2} 9.22337203685488e+18 + test_realnum_expr expr-1.228\ + {i2=-9223372036854775807, i1=0} {i1-i2} 9223372036854775807 + test_realnum_expr expr-1.229\ + {i2=-9223372036854775807, i1=1} {i1-i2} 9.22337203685478e+18 + test_realnum_expr expr-1.230\ + {i1=-9223372036854775807, i2=1} {i1-i2} -9223372036854775808 + test_realnum_expr expr-1.231\ + {i1=-9223372036854775807, i2=2} {i1-i2} -9.22337203685478e+18 + test_realnum_expr expr-1.232\ + {i1=-9223372036854775807, i2=100000} {i1-i2} -9.22337203685488e+18 + test_realnum_expr expr-1.233\ + {i1=-9223372036854775808, i2=0} {i1-i2} -9223372036854775808 + test_realnum_expr expr-1.234\ + {i1=-9223372036854775808, i2=1} {i1-i2} -9.22337203685478e+18 + test_realnum_expr expr-1.235\ + {i2=9223372036854775807, i1=-1} {i1-i2} -9223372036854775808 + test_realnum_expr expr-1.236\ + {i2=9223372036854775807, i1=-2} {i1-i2} -9.22337203685478e+18 + test_realnum_expr expr-1.237\ + {i2=9223372036854775807, i1=-100000} {i1-i2} -9.22337203685488e+18 + test_realnum_expr expr-1.238\ + {i2=9223372036854775807, i1=0} {i1-i2} -9223372036854775807 + test_realnum_expr expr-1.239\ + {i2=9223372036854775807, i1=-1} {i1-i2} -9223372036854775808 + + test_realnum_expr expr-1.250\ + {i1=4294967296, i2=2147483648} {i1*i2} 9.22337203685478e+18 + test_realnum_expr expr-1.251\ + {i1=4294967296, i2=2147483647} {i1*i2} 9223372032559808512 + test_realnum_expr expr-1.252\ + {i1=-4294967296, i2=2147483648} {i1*i2} -9223372036854775808 + test_realnum_expr expr-1.253\ + {i1=-4294967296, i2=2147483647} {i1*i2} -9223372032559808512 + test_realnum_expr expr-1.254\ + {i1=4294967296, i2=-2147483648} {i1*i2} -9223372036854775808 + test_realnum_expr expr-1.255\ + {i1=4294967296, i2=-2147483647} {i1*i2} -9223372032559808512 + test_realnum_expr expr-1.256\ + {i1=-4294967296, i2=-2147483648} {i1*i2} 9.22337203685478e+18 + test_realnum_expr expr-1.257\ + {i1=-4294967296, i2=-2147483647} {i1*i2} 9223372032559808512 + +}} + +ifcapable floatingpoint { + test_expr expr-2.1 {r1=1.23, r2=2.34} {r1+r2} 3.57 + test_expr expr-2.2 {r1=1.23, r2=2.34} {r1-r2} -1.11 + test_expr expr-2.3 {r1=1.23, r2=2.34} {r1*r2} 2.8782 +} +set tcl_precision 15 +ifcapable floatingpoint { + test_expr expr-2.4 {r1=1.23, r2=2.34} {r1/r2} 0.525641025641026 + test_expr expr-2.5 {r1=1.23, r2=2.34} {r2/r1} 1.90243902439024 + test_expr expr-2.6 {r1=1.23, r2=2.34} {r2r1} 1 + test_expr expr-2.9 {r1=1.23, r2=2.34} {r2>=r1} 1 + test_expr expr-2.10 {r1=1.23, r2=2.34} {r2!=r1} 1 + test_expr expr-2.11 {r1=1.23, r2=2.34} {r2=r1} 0 + test_expr expr-2.12 {r1=1.23, r2=2.34} {r2<>r1} 1 + test_expr expr-2.13 {r1=1.23, r2=2.34} {r2==r1} 0 + test_expr expr-2.14 {r1=2.34, r2=2.34} {r2r1} 0 + test_expr expr-2.17 {r1=2.34, r2=2.34} {r2>=r1} 1 + test_expr expr-2.18 {r1=2.34, r2=2.34} {r2!=r1} 0 + test_expr expr-2.19 {r1=2.34, r2=2.34} {r2=r1} 1 + test_expr expr-2.20 {r1=2.34, r2=2.34} {r2<>r1} 0 + test_expr expr-2.21 {r1=2.34, r2=2.34} {r2==r1} 1 + test_expr expr-2.22 {r1=1.23, r2=2.34} {min(r1,r2,r1+r2,r1-r2)} {-1.11} + test_expr expr-2.23 {r1=1.23, r2=2.34} {max(r1,r2,r1+r2,r1-r2)} {3.57} + test_expr expr-2.24 {r1=25.0, r2=11.0} {r1%r2} 3.0 + test_expr expr-2.25 {r1=1.23, r2=NULL} {coalesce(r1+r2,99.0)} 99.0 + test_expr expr-2.26 {r1=1e300, r2=1e300} {coalesce((r1*r2)*0.0,99.0)} 99.0 + test_expr expr-2.26b {r1=1e300, r2=-1e300} {coalesce((r1*r2)*0.0,99.0)} 99.0 + test_expr expr-2.27 {r1=1.1, r2=0.0} {r1/r2} {{}} + test_expr expr-2.28 {r1=1.1, r2=0.0} {r1%r2} {{}} +} + +test_expr expr-3.1 {t1='abc', t2='xyz'} {t1t2} 0 +test_expr expr-3.8 {t1='xyz', t2='abc'} {t1>t2} 1 +test_expr expr-3.9 {t1='abc', t2='abc'} {t1>t2} 0 +test_expr expr-3.10 {t1='abc', t2='xyz'} {t1>=t2} 0 +test_expr expr-3.11 {t1='xyz', t2='abc'} {t1>=t2} 1 +test_expr expr-3.12 {t1='abc', t2='abc'} {t1>=t2} 1 +test_expr expr-3.13 {t1='abc', t2='xyz'} {t1=t2} 0 +test_expr expr-3.14 {t1='xyz', t2='abc'} {t1=t2} 0 +test_expr expr-3.15 {t1='abc', t2='abc'} {t1=t2} 1 +test_expr expr-3.16 {t1='abc', t2='xyz'} {t1==t2} 0 +test_expr expr-3.17 {t1='xyz', t2='abc'} {t1==t2} 0 +test_expr expr-3.18 {t1='abc', t2='abc'} {t1==t2} 1 +test_expr expr-3.19 {t1='abc', t2='xyz'} {t1<>t2} 1 +test_expr expr-3.20 {t1='xyz', t2='abc'} {t1<>t2} 1 +test_expr expr-3.21 {t1='abc', t2='abc'} {t1<>t2} 0 +test_expr expr-3.22 {t1='abc', t2='xyz'} {t1!=t2} 1 +test_expr expr-3.23 {t1='xyz', t2='abc'} {t1!=t2} 1 +test_expr expr-3.24 {t1='abc', t2='abc'} {t1!=t2} 0 +test_expr expr-3.25 {t1=NULL, t2='hi'} {t1 isnull} 1 +test_expr expr-3.25b {t1=NULL, t2='hi'} {t1 is null} 1 +test_expr expr-3.26 {t1=NULL, t2='hi'} {t2 isnull} 0 +test_expr expr-3.27 {t1=NULL, t2='hi'} {t1 notnull} 0 +test_expr expr-3.28 {t1=NULL, t2='hi'} {t2 notnull} 1 +test_expr expr-3.28b {t1=NULL, t2='hi'} {t2 is not null} 1 +test_expr expr-3.29 {t1='xyz', t2='abc'} {t1||t2} {xyzabc} +test_expr expr-3.30 {t1=NULL, t2='abc'} {t1||t2} {{}} +test_expr expr-3.31 {t1='xyz', t2=NULL} {t1||t2} {{}} +test_expr expr-3.32 {t1='xyz', t2='abc'} {t1||' hi '||t2} {{xyz hi abc}} +test_expr epxr-3.33 {t1='abc', t2=NULL} {coalesce(t1t2,99)} 99 +test_expr epxr-3.36 {t1='abc', t2=NULL} {coalesce(t2>t1,99)} 99 +test_expr epxr-3.37 {t1='abc', t2=NULL} {coalesce(t1<=t2,99)} 99 +test_expr epxr-3.38 {t1='abc', t2=NULL} {coalesce(t2<=t1,99)} 99 +test_expr epxr-3.39 {t1='abc', t2=NULL} {coalesce(t1>=t2,99)} 99 +test_expr epxr-3.40 {t1='abc', t2=NULL} {coalesce(t2>=t1,99)} 99 +test_expr epxr-3.41 {t1='abc', t2=NULL} {coalesce(t1==t2,99)} 99 +test_expr epxr-3.42 {t1='abc', t2=NULL} {coalesce(t2==t1,99)} 99 +test_expr epxr-3.43 {t1='abc', t2=NULL} {coalesce(t1!=t2,99)} 99 +test_expr epxr-3.44 {t1='abc', t2=NULL} {coalesce(t2!=t1,99)} 99 + +test_expr expr-4.1 {t1='abc', t2='Abc'} {t1t2} 1 +test_expr expr-4.3 {t1='abc', t2='Bbc'} {t1t2} 1 +test_expr expr-4.5 {t1='0', t2='0.0'} {t1==t2} 0 +test_expr expr-4.6 {t1='0.000', t2='0.0'} {t1==t2} 0 +test_expr expr-4.7 {t1=' 0.000', t2=' 0.0'} {t1==t2} 0 +test_expr expr-4.8 {t1='0.0', t2='abc'} {t1r2} 0 + test_expr expr-4.11 {r1='abc', r2='Abc'} {r1r2} 1 + test_expr expr-4.13 {r1='abc', r2='Bbc'} {r1r2} 1 + test_expr expr-4.15 {r1='0', r2='0.0'} {r1==r2} 1 + test_expr expr-4.16 {r1='0.000', r2='0.0'} {r1==r2} 1 + test_expr expr-4.17 {r1=' 0.000', r2=' 0.0'} {r1==r2} 1 + test_expr expr-4.18 {r1='0.0', r2='abc'} {r1r2} 0 +} + +# CSL is true if LIKE is case sensitive and false if not. +# NCSL is the opposite. Use these variables as the result +# on operations where case makes a difference. +set CSL $sqlite_options(casesensitivelike) +set NCSL [expr {!$CSL}] + +test_expr expr-5.1 {t1='abc', t2='xyz'} {t1 LIKE t2} 0 +test_expr expr-5.2a {t1='abc', t2='abc'} {t1 LIKE t2} 1 +test_expr expr-5.2b {t1='abc', t2='ABC'} {t1 LIKE t2} $NCSL +test_expr expr-5.3a {t1='abc', t2='a_c'} {t1 LIKE t2} 1 +test_expr expr-5.3b {t1='abc', t2='A_C'} {t1 LIKE t2} $NCSL +test_expr expr-5.4 {t1='abc', t2='abc_'} {t1 LIKE t2} 0 +test_expr expr-5.5a {t1='abc', t2='a%c'} {t1 LIKE t2} 1 +test_expr expr-5.5b {t1='abc', t2='A%C'} {t1 LIKE t2} $NCSL +test_expr expr-5.5c {t1='abdc', t2='a%c'} {t1 LIKE t2} 1 +test_expr expr-5.5d {t1='ac', t2='a%c'} {t1 LIKE t2} 1 +test_expr expr-5.5e {t1='ac', t2='A%C'} {t1 LIKE t2} $NCSL +test_expr expr-5.6a {t1='abxyzzyc', t2='a%c'} {t1 LIKE t2} 1 +test_expr expr-5.6b {t1='abxyzzyc', t2='A%C'} {t1 LIKE t2} $NCSL +test_expr expr-5.7a {t1='abxyzzy', t2='a%c'} {t1 LIKE t2} 0 +test_expr expr-5.7b {t1='abxyzzy', t2='A%C'} {t1 LIKE t2} 0 +test_expr expr-5.8a {t1='abxyzzycx', t2='a%c'} {t1 LIKE t2} 0 +test_expr expr-5.8b {t1='abxyzzycy', t2='a%cx'} {t1 LIKE t2} 0 +test_expr expr-5.8c {t1='abxyzzycx', t2='A%C'} {t1 LIKE t2} 0 +test_expr expr-5.8d {t1='abxyzzycy', t2='A%CX'} {t1 LIKE t2} 0 +test_expr expr-5.9a {t1='abc', t2='a%_c'} {t1 LIKE t2} 1 +test_expr expr-5.9b {t1='ac', t2='a%_c'} {t1 LIKE t2} 0 +test_expr expr-5.9c {t1='abc', t2='A%_C'} {t1 LIKE t2} $NCSL +test_expr expr-5.9d {t1='ac', t2='A%_C'} {t1 LIKE t2} 0 +test_expr expr-5.10a {t1='abxyzzyc', t2='a%_c'} {t1 LIKE t2} 1 +test_expr expr-5.10b {t1='abxyzzyc', t2='A%_C'} {t1 LIKE t2} $NCSL +test_expr expr-5.11 {t1='abc', t2='xyz'} {t1 NOT LIKE t2} 1 +test_expr expr-5.12a {t1='abc', t2='abc'} {t1 NOT LIKE t2} 0 +test_expr expr-5.12b {t1='abc', t2='ABC'} {t1 NOT LIKE t2} $CSL +test_expr expr-5.13 {t1='A'} {t1 LIKE 'A%_'} 0 +test_expr expr-5.14 {t1='AB'} {t1 LIKE 'A%b' ESCAPE 'b'} 0 + +# The following tests only work on versions of TCL that support Unicode +# +if {"\u1234"!="u1234"} { + test_expr expr-5.13a "t1='a\u0080c', t2='a_c'" {t1 LIKE t2} 1 + test_expr expr-5.13b "t1='a\u0080c', t2='A_C'" {t1 LIKE t2} $NCSL + test_expr expr-5.14a "t1='a\u07FFc', t2='a_c'" {t1 LIKE t2} 1 + test_expr expr-5.14b "t1='a\u07FFc', t2='A_C'" {t1 LIKE t2} $NCSL + test_expr expr-5.15a "t1='a\u0800c', t2='a_c'" {t1 LIKE t2} 1 + test_expr expr-5.15b "t1='a\u0800c', t2='A_C'" {t1 LIKE t2} $NCSL + test_expr expr-5.16a "t1='a\uFFFFc', t2='a_c'" {t1 LIKE t2} 1 + test_expr expr-5.16b "t1='a\uFFFFc', t2='A_C'" {t1 LIKE t2} $NCSL + test_expr expr-5.17 "t1='a\u0080', t2='A__'" {t1 LIKE t2} 0 + test_expr expr-5.18 "t1='a\u07FF', t2='A__'" {t1 LIKE t2} 0 + test_expr expr-5.19 "t1='a\u0800', t2='A__'" {t1 LIKE t2} 0 + test_expr expr-5.20 "t1='a\uFFFF', t2='A__'" {t1 LIKE t2} 0 + test_expr expr-5.21a "t1='ax\uABCD', t2='a_\uABCD'" {t1 LIKE t2} 1 + test_expr expr-5.21b "t1='ax\uABCD', t2='A_\uABCD'" {t1 LIKE t2} $NCSL + test_expr expr-5.22a "t1='ax\u1234', t2='a%\u1234'" {t1 LIKE t2} 1 + test_expr expr-5.22b "t1='ax\u1234', t2='A%\u1234'" {t1 LIKE t2} $NCSL + test_expr expr-5.23a "t1='ax\uFEDC', t2='a_%'" {t1 LIKE t2} 1 + test_expr expr-5.23b "t1='ax\uFEDC', t2='A_%'" {t1 LIKE t2} $NCSL + test_expr expr-5.24a "t1='ax\uFEDCy\uFEDC', t2='a%\uFEDC'" {t1 LIKE t2} 1 + test_expr expr-5.24b "t1='ax\uFEDCy\uFEDC', t2='A%\uFEDC'" {t1 LIKE t2} $NCSL +} + +test_expr expr-5.54 {t1='abc', t2=NULL} {t1 LIKE t2} {{}} +test_expr expr-5.55 {t1='abc', t2=NULL} {t1 NOT LIKE t2} {{}} +test_expr expr-5.56 {t1='abc', t2=NULL} {t2 LIKE t1} {{}} +test_expr expr-5.57 {t1='abc', t2=NULL} {t2 NOT LIKE t1} {{}} + +# LIKE expressions that use ESCAPE characters. +test_expr expr-5.58a {t1='abc', t2='a_c'} {t1 LIKE t2 ESCAPE '7'} 1 +test_expr expr-5.58b {t1='abc', t2='A_C'} {t1 LIKE t2 ESCAPE '7'} $NCSL +test_expr expr-5.59a {t1='a_c', t2='a7_c'} {t1 LIKE t2 ESCAPE '7'} 1 +test_expr expr-5.59b {t1='a_c', t2='A7_C'} {t1 LIKE t2 ESCAPE '7'} $NCSL +test_expr expr-5.60a {t1='abc', t2='a7_c'} {t1 LIKE t2 ESCAPE '7'} 0 +test_expr expr-5.60b {t1='abc', t2='A7_C'} {t1 LIKE t2 ESCAPE '7'} 0 +test_expr expr-5.61a {t1='a7Xc', t2='a7_c'} {t1 LIKE t2 ESCAPE '7'} 0 +test_expr expr-5.61b {t1='a7Xc', t2='A7_C'} {t1 LIKE t2 ESCAPE '7'} 0 +test_expr expr-5.62a {t1='abcde', t2='a%e'} {t1 LIKE t2 ESCAPE '7'} 1 +test_expr expr-5.62b {t1='abcde', t2='A%E'} {t1 LIKE t2 ESCAPE '7'} $NCSL +test_expr expr-5.63a {t1='abcde', t2='a7%e'} {t1 LIKE t2 ESCAPE '7'} 0 +test_expr expr-5.63b {t1='abcde', t2='A7%E'} {t1 LIKE t2 ESCAPE '7'} 0 +test_expr expr-5.64a {t1='a7cde', t2='a7%e'} {t1 LIKE t2 ESCAPE '7'} 0 +test_expr expr-5.64b {t1='a7cde', t2='A7%E'} {t1 LIKE t2 ESCAPE '7'} 0 +test_expr expr-5.65a {t1='a7cde', t2='a77%e'} {t1 LIKE t2 ESCAPE '7'} 1 +test_expr expr-5.65b {t1='a7cde', t2='A77%E'} {t1 LIKE t2 ESCAPE '7'} $NCSL +test_expr expr-5.66a {t1='abc7', t2='a%77'} {t1 LIKE t2 ESCAPE '7'} 1 +test_expr expr-5.66b {t1='abc7', t2='A%77'} {t1 LIKE t2 ESCAPE '7'} $NCSL +test_expr expr-5.67a {t1='abc_', t2='a%7_'} {t1 LIKE t2 ESCAPE '7'} 1 +test_expr expr-5.67b {t1='abc_', t2='A%7_'} {t1 LIKE t2 ESCAPE '7'} $NCSL +test_expr expr-5.68a {t1='abc7', t2='a%7_'} {t1 LIKE t2 ESCAPE '7'} 0 +test_expr expr-5.68b {t1='abc7', t2='A%7_'} {t1 LIKE t2 ESCAPE '7'} 0 + +# These are the same test as the block above, but using a multi-byte +# character as the escape character. +if {"\u1234"!="u1234"} { + test_expr expr-5.69a "t1='abc', t2='a_c'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 1 + test_expr expr-5.69b "t1='abc', t2='A_C'" \ + "t1 LIKE t2 ESCAPE '\u1234'" $NCSL + test_expr expr-5.70a "t1='a_c', t2='a\u1234_c'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 1 + test_expr expr-5.70b "t1='a_c', t2='A\u1234_C'" \ + "t1 LIKE t2 ESCAPE '\u1234'" $NCSL + test_expr expr-5.71a "t1='abc', t2='a\u1234_c'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 + test_expr expr-5.71b "t1='abc', t2='A\u1234_C'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 + test_expr expr-5.72a "t1='a\u1234Xc', t2='a\u1234_c'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 + test_expr expr-5.72b "t1='a\u1234Xc', t2='A\u1234_C'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 + test_expr expr-5.73a "t1='abcde', t2='a%e'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 1 + test_expr expr-5.73b "t1='abcde', t2='A%E'" \ + "t1 LIKE t2 ESCAPE '\u1234'" $NCSL + test_expr expr-5.74a "t1='abcde', t2='a\u1234%e'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 + test_expr expr-5.74b "t1='abcde', t2='A\u1234%E'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 + test_expr expr-5.75a "t1='a\u1234cde', t2='a\u1234%e'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 + test_expr expr-5.75b "t1='a\u1234cde', t2='A\u1234%E'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 + test_expr expr-5.76a "t1='a\u1234cde', t2='a\u1234\u1234%e'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 1 + test_expr expr-5.76b "t1='a\u1234cde', t2='A\u1234\u1234%E'" \ + "t1 LIKE t2 ESCAPE '\u1234'" $NCSL + test_expr expr-5.77a "t1='abc\u1234', t2='a%\u1234\u1234'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 1 + test_expr expr-5.77b "t1='abc\u1234', t2='A%\u1234\u1234'" \ + "t1 LIKE t2 ESCAPE '\u1234'" $NCSL + test_expr expr-5.78a "t1='abc_', t2='a%\u1234_'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 1 + test_expr expr-5.78b "t1='abc_', t2='A%\u1234_'" \ + "t1 LIKE t2 ESCAPE '\u1234'" $NCSL + test_expr expr-5.79a "t1='abc\u1234', t2='a%\u1234_'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 + test_expr expr-5.79b "t1='abc\u1234', t2='A%\u1234_'" \ + "t1 LIKE t2 ESCAPE '\u1234'" 0 +} + +test_expr expr-6.1 {t1='abc', t2='xyz'} {t1 GLOB t2} 0 +test_expr expr-6.2 {t1='abc', t2='ABC'} {t1 GLOB t2} 0 +test_expr expr-6.3 {t1='abc', t2='A?C'} {t1 GLOB t2} 0 +test_expr expr-6.4 {t1='abc', t2='a?c'} {t1 GLOB t2} 1 +test_expr expr-6.5 {t1='abc', t2='abc?'} {t1 GLOB t2} 0 +test_expr expr-6.6 {t1='abc', t2='A*C'} {t1 GLOB t2} 0 +test_expr expr-6.7 {t1='abc', t2='a*c'} {t1 GLOB t2} 1 +test_expr expr-6.8 {t1='abxyzzyc', t2='a*c'} {t1 GLOB t2} 1 +test_expr expr-6.9 {t1='abxyzzy', t2='a*c'} {t1 GLOB t2} 0 +test_expr expr-6.10 {t1='abxyzzycx', t2='a*c'} {t1 GLOB t2} 0 +test_expr expr-6.11 {t1='abc', t2='xyz'} {t1 NOT GLOB t2} 1 +test_expr expr-6.12 {t1='abc', t2='abc'} {t1 NOT GLOB t2} 0 +test_expr expr-6.13 {t1='abc', t2='a[bx]c'} {t1 GLOB t2} 1 +test_expr expr-6.14 {t1='abc', t2='a[cx]c'} {t1 GLOB t2} 0 +test_expr expr-6.15 {t1='abc', t2='a[a-d]c'} {t1 GLOB t2} 1 +test_expr expr-6.16 {t1='abc', t2='a[^a-d]c'} {t1 GLOB t2} 0 +test_expr expr-6.17 {t1='abc', t2='a[A-Dc]c'} {t1 GLOB t2} 0 +test_expr expr-6.18 {t1='abc', t2='a[^A-Dc]c'} {t1 GLOB t2} 1 +test_expr expr-6.19 {t1='abc', t2='a[]b]c'} {t1 GLOB t2} 1 +test_expr expr-6.20 {t1='abc', t2='a[^]b]c'} {t1 GLOB t2} 0 +test_expr expr-6.21a {t1='abcdefg', t2='a*[de]g'} {t1 GLOB t2} 0 +test_expr expr-6.21b {t1='abcdefg', t2='a*[df]g'} {t1 GLOB t2} 1 +test_expr expr-6.21c {t1='abcdefg', t2='a*[d-h]g'} {t1 GLOB t2} 1 +test_expr expr-6.21d {t1='abcdefg', t2='a*[b-e]g'} {t1 GLOB t2} 0 +test_expr expr-6.22a {t1='abcdefg', t2='a*[^de]g'} {t1 GLOB t2} 1 +test_expr expr-6.22b {t1='abcdefg', t2='a*[^def]g'} {t1 GLOB t2} 0 +test_expr expr-6.23 {t1='abcdefg', t2='a*?g'} {t1 GLOB t2} 1 +test_expr expr-6.24 {t1='ac', t2='a*c'} {t1 GLOB t2} 1 +test_expr expr-6.25 {t1='ac', t2='a*?c'} {t1 GLOB t2} 0 +test_expr expr-6.26 {t1='a*c', t2='a[*]c'} {t1 GLOB t2} 1 +test_expr expr-6.27 {t1='a?c', t2='a[?]c'} {t1 GLOB t2} 1 +test_expr expr-6.28 {t1='a[c', t2='a[[]c'} {t1 GLOB t2} 1 + + +# These tests only work on versions of TCL that support Unicode +# +if {"\u1234"!="u1234"} { + test_expr expr-6.26 "t1='a\u0080c', t2='a?c'" {t1 GLOB t2} 1 + test_expr expr-6.27 "t1='a\u07ffc', t2='a?c'" {t1 GLOB t2} 1 + test_expr expr-6.28 "t1='a\u0800c', t2='a?c'" {t1 GLOB t2} 1 + test_expr expr-6.29 "t1='a\uffffc', t2='a?c'" {t1 GLOB t2} 1 + test_expr expr-6.30 "t1='a\u1234', t2='a?'" {t1 GLOB t2} 1 + test_expr expr-6.31 "t1='a\u1234', t2='a??'" {t1 GLOB t2} 0 + test_expr expr-6.32 "t1='ax\u1234', t2='a?\u1234'" {t1 GLOB t2} 1 + test_expr expr-6.33 "t1='ax\u1234', t2='a*\u1234'" {t1 GLOB t2} 1 + test_expr expr-6.34 "t1='ax\u1234y\u1234', t2='a*\u1234'" {t1 GLOB t2} 1 + test_expr expr-6.35 "t1='a\u1234b', t2='a\[x\u1234y\]b'" {t1 GLOB t2} 1 + test_expr expr-6.36 "t1='a\u1234b', t2='a\[\u1233-\u1235\]b'" {t1 GLOB t2} 1 + test_expr expr-6.37 "t1='a\u1234b', t2='a\[\u1234-\u124f\]b'" {t1 GLOB t2} 1 + test_expr expr-6.38 "t1='a\u1234b', t2='a\[\u1235-\u124f\]b'" {t1 GLOB t2} 0 + test_expr expr-6.39 "t1='a\u1234b', t2='a\[a-\u1235\]b'" {t1 GLOB t2} 1 + test_expr expr-6.40 "t1='a\u1234b', t2='a\[a-\u1234\]b'" {t1 GLOB t2} 1 + test_expr expr-6.41 "t1='a\u1234b', t2='a\[a-\u1233\]b'" {t1 GLOB t2} 0 +} + +test_expr expr-6.51 {t1='ABC', t2='xyz'} {t1 GLOB t2} 0 +test_expr expr-6.52 {t1='ABC', t2='abc'} {t1 GLOB t2} 0 +test_expr expr-6.53 {t1='ABC', t2='a?c'} {t1 GLOB t2} 0 +test_expr expr-6.54 {t1='ABC', t2='A?C'} {t1 GLOB t2} 1 +test_expr expr-6.55 {t1='ABC', t2='abc?'} {t1 GLOB t2} 0 +test_expr expr-6.56 {t1='ABC', t2='a*c'} {t1 GLOB t2} 0 +test_expr expr-6.57 {t1='ABC', t2='A*C'} {t1 GLOB t2} 1 +test_expr expr-6.58 {t1='ABxyzzyC', t2='A*C'} {t1 GLOB t2} 1 +test_expr expr-6.59 {t1='ABxyzzy', t2='A*C'} {t1 GLOB t2} 0 +test_expr expr-6.60 {t1='ABxyzzyCx', t2='A*C'} {t1 GLOB t2} 0 +test_expr expr-6.61 {t1='ABC', t2='xyz'} {t1 NOT GLOB t2} 1 +test_expr expr-6.62 {t1='ABC', t2='ABC'} {t1 NOT GLOB t2} 0 +test_expr expr-6.63 {t1='ABC', t2='A[Bx]C'} {t1 GLOB t2} 1 +test_expr expr-6.64 {t1='ABC', t2='A[Cx]C'} {t1 GLOB t2} 0 +test_expr expr-6.65 {t1='ABC', t2='A[A-D]C'} {t1 GLOB t2} 1 +test_expr expr-6.66 {t1='ABC', t2='A[^A-D]C'} {t1 GLOB t2} 0 +test_expr expr-6.67 {t1='ABC', t2='A[a-dC]C'} {t1 GLOB t2} 0 +test_expr expr-6.68 {t1='ABC', t2='A[^a-dC]C'} {t1 GLOB t2} 1 +test_expr expr-6.69a {t1='ABC', t2='A[]B]C'} {t1 GLOB t2} 1 +test_expr expr-6.69b {t1='A]C', t2='A[]B]C'} {t1 GLOB t2} 1 +test_expr expr-6.70a {t1='ABC', t2='A[^]B]C'} {t1 GLOB t2} 0 +test_expr expr-6.70b {t1='AxC', t2='A[^]B]C'} {t1 GLOB t2} 1 +test_expr expr-6.70c {t1='A]C', t2='A[^]B]C'} {t1 GLOB t2} 0 +test_expr expr-6.71 {t1='ABCDEFG', t2='A*[DE]G'} {t1 GLOB t2} 0 +test_expr expr-6.72 {t1='ABCDEFG', t2='A*[^DE]G'} {t1 GLOB t2} 1 +test_expr expr-6.73 {t1='ABCDEFG', t2='A*?G'} {t1 GLOB t2} 1 +test_expr expr-6.74 {t1='AC', t2='A*C'} {t1 GLOB t2} 1 +test_expr expr-6.75 {t1='AC', t2='A*?C'} {t1 GLOB t2} 0 + +test_expr expr-6.63 {t1=NULL, t2='a*?c'} {t1 GLOB t2} {{}} +test_expr expr-6.64 {t1='ac', t2=NULL} {t1 GLOB t2} {{}} +test_expr expr-6.65 {t1=NULL, t2='a*?c'} {t1 NOT GLOB t2} {{}} +test_expr expr-6.66 {t1='ac', t2=NULL} {t1 NOT GLOB t2} {{}} + +# Check that the affinity of a CAST expression is calculated correctly. +ifcapable cast { + test_expr expr-6.67 {t1='01', t2=1} {t1 = t2} 0 + test_expr expr-6.68 {t1='1', t2=1} {t1 = t2} 1 + test_expr expr-6.69 {t1='01', t2=1} {CAST(t1 AS INTEGER) = t2} 1 +} + +test_expr expr-case.1 {i1=1, i2=2} \ + {CASE WHEN i1 = i2 THEN 'eq' ELSE 'ne' END} ne +test_expr expr-case.2 {i1=2, i2=2} \ + {CASE WHEN i1 = i2 THEN 'eq' ELSE 'ne' END} eq +test_expr expr-case.3 {i1=NULL, i2=2} \ + {CASE WHEN i1 = i2 THEN 'eq' ELSE 'ne' END} ne +test_expr expr-case.4 {i1=2, i2=NULL} \ + {CASE WHEN i1 = i2 THEN 'eq' ELSE 'ne' END} ne +test_expr expr-case.5 {i1=2} \ + {CASE i1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'error' END} two +test_expr expr-case.6 {i1=1} \ + {CASE i1 WHEN 1 THEN 'one' WHEN NULL THEN 'two' ELSE 'error' END} one +test_expr expr-case.7 {i1=2} \ + {CASE i1 WHEN 1 THEN 'one' WHEN NULL THEN 'two' ELSE 'error' END} error +test_expr expr-case.8 {i1=3} \ + {CASE i1 WHEN 1 THEN 'one' WHEN NULL THEN 'two' ELSE 'error' END} error +test_expr expr-case.9 {i1=3} \ + {CASE i1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'error' END} error +test_expr expr-case.10 {i1=3} \ + {CASE i1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' END} {{}} +test_expr expr-case.11 {i1=null} \ + {CASE i1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 3 END} 3 +test_expr expr-case.12 {i1=1} \ + {CASE i1 WHEN 1 THEN null WHEN 2 THEN 'two' ELSE 3 END} {{}} +test_expr expr-case.13 {i1=7} \ + { CASE WHEN i1 < 5 THEN 'low' + WHEN i1 < 10 THEN 'medium' + WHEN i1 < 15 THEN 'high' ELSE 'error' END} medium + + +# The sqliteExprIfFalse and sqliteExprIfTrue routines are only +# executed as part of a WHERE clause. Create a table suitable +# for testing these functions. +# +execsql {DROP TABLE test1} +execsql {CREATE TABLE test1(a int, b int);} +for {set i 1} {$i<=20} {incr i} { + execsql "INSERT INTO test1 VALUES($i,[expr {1<<$i}])" +} +execsql "INSERT INTO test1 VALUES(NULL,0)" +do_test expr-7.1 { + execsql {SELECT * FROM test1 ORDER BY a} +} {{} 0 1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024 11 2048 12 4096 13 8192 14 16384 15 32768 16 65536 17 131072 18 262144 19 524288 20 1048576} + +proc test_expr2 {name expr result} { + do_test $name [format { + execsql {SELECT a FROM test1 WHERE %s ORDER BY a} + } $expr] $result +} + +test_expr2 expr-7.2 {a<10 AND a>8} {9} +test_expr2 expr-7.3 {a<=10 AND a>=8} {8 9 10} +test_expr2 expr-7.4 {a>=8 AND a<=10} {8 9 10} +test_expr2 expr-7.5 {a>=20 OR a<=1} {1 20} +test_expr2 expr-7.6 {b!=4 AND a<=3} {1 3} +test_expr2 expr-7.7 {b==8 OR b==16 OR b==32} {3 4 5} +test_expr2 expr-7.8 {NOT b<>8 OR b==1024} {3 10} +test_expr2 expr-7.9 {b LIKE '10%'} {10 20} +test_expr2 expr-7.10 {b LIKE '_4'} {6} +test_expr2 expr-7.11 {a GLOB '1?'} {10 11 12 13 14 15 16 17 18 19} +test_expr2 expr-7.12 {b GLOB '1*4'} {10 14} +test_expr2 expr-7.13 {b GLOB '*1[456]'} {4} +test_expr2 expr-7.14 {a ISNULL} {{}} +test_expr2 expr-7.15 {a NOTNULL AND a<3} {1 2} +test_expr2 expr-7.16 {a AND a<3} {1 2} +test_expr2 expr-7.17 {NOT a} {} +test_expr2 expr-7.18 {a==11 OR (b>1000 AND b<2000)} {10 11} +test_expr2 expr-7.19 {a<=1 OR a>=20} {1 20} +test_expr2 expr-7.20 {a<1 OR a>20} {} +test_expr2 expr-7.21 {a>19 OR a<1} {20} +test_expr2 expr-7.22 {a!=1 OR a=100} \ + {2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20} +test_expr2 expr-7.23 {(a notnull AND a<4) OR a==8} {1 2 3 8} +test_expr2 expr-7.24 {a LIKE '2_' OR a==8} {8 20} +test_expr2 expr-7.25 {a GLOB '2?' OR a==8} {8 20} +test_expr2 expr-7.26 {a isnull OR a=8} {{} 8} +test_expr2 expr-7.27 {a notnull OR a=8} \ + {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20} +test_expr2 expr-7.28 {a<0 OR b=0} {{}} +test_expr2 expr-7.29 {b=0 OR a<0} {{}} +test_expr2 expr-7.30 {a<0 AND b=0} {} +test_expr2 expr-7.31 {b=0 AND a<0} {} +test_expr2 expr-7.32 {a IS NULL AND (a<0 OR b=0)} {{}} +test_expr2 expr-7.33 {a IS NULL AND (b=0 OR a<0)} {{}} +test_expr2 expr-7.34 {a IS NULL AND (a<0 AND b=0)} {} +test_expr2 expr-7.35 {a IS NULL AND (b=0 AND a<0)} {} +test_expr2 expr-7.32 {(a<0 OR b=0) AND a IS NULL} {{}} +test_expr2 expr-7.33 {(b=0 OR a<0) AND a IS NULL} {{}} +test_expr2 expr-7.34 {(a<0 AND b=0) AND a IS NULL} {} +test_expr2 expr-7.35 {(b=0 AND a<0) AND a IS NULL} {} +test_expr2 expr-7.36 {a<2 OR (a<0 OR b=0)} {{} 1} +test_expr2 expr-7.37 {a<2 OR (b=0 OR a<0)} {{} 1} +test_expr2 expr-7.38 {a<2 OR (a<0 AND b=0)} {1} +test_expr2 expr-7.39 {a<2 OR (b=0 AND a<0)} {1} +ifcapable floatingpoint { + test_expr2 expr-7.40 {((a<2 OR a IS NULL) AND b<3) OR b>1e10} {{} 1} +} +test_expr2 expr-7.41 {a BETWEEN -1 AND 1} {1} +test_expr2 expr-7.42 {a NOT BETWEEN 2 AND 100} {1} +test_expr2 expr-7.43 {(b+1234)||'this is a string that is at least 32 characters long' BETWEEN 1 AND 2} {} +test_expr2 expr-7.44 {123||'xabcdefghijklmnopqrstuvwyxz01234567890'||a BETWEEN '123a' AND '123b'} {} +test_expr2 expr-7.45 {((123||'xabcdefghijklmnopqrstuvwyxz01234567890'||a) BETWEEN '123a' AND '123b')<0} {} +test_expr2 expr-7.46 {((123||'xabcdefghijklmnopqrstuvwyxz01234567890'||a) BETWEEN '123a' AND '123z')>0} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20} + +test_expr2 expr-7.50 {((a between 1 and 2 OR 0) AND 1) OR 0} {1 2} +test_expr2 expr-7.51 {((a not between 3 and 100 OR 0) AND 1) OR 0} {1 2} + +ifcapable subquery { + test_expr2 expr-7.52 {((a in (1,2) OR 0) AND 1) OR 0} {1 2} + test_expr2 expr-7.53 \ + {((a not in (3,4,5,6,7,8,9,10) OR 0) AND a<11) OR 0} {1 2} +} +test_expr2 expr-7.54 {((a>0 OR 0) AND a<3) OR 0} {1 2} +ifcapable subquery { + test_expr2 expr-7.55 {((a in (1,2) OR 0) IS NULL AND 1) OR 0} {{}} + test_expr2 expr-7.56 \ + {((a not in (3,4,5,6,7,8,9,10) IS NULL OR 0) AND 1) OR 0} {{}} +} +test_expr2 expr-7.57 {((a>0 IS NULL OR 0) AND 1) OR 0} {{}} + +test_expr2 expr-7.58 {(a||'')<='1'} {1} + +test_expr2 expr-7.59 {LIKE('10%',b)} {10 20} +test_expr2 expr-7.60 {LIKE('_4',b)} {6} +test_expr2 expr-7.61 {GLOB('1?',a)} {10 11 12 13 14 15 16 17 18 19} +test_expr2 expr-7.62 {GLOB('1*4',b)} {10 14} +test_expr2 expr-7.63 {GLOB('*1[456]',b)} {4} +test_expr2 expr-7.64 {b = abs(-2)} {1} +test_expr2 expr-7.65 {b = abs(+-2)} {1} +test_expr2 expr-7.66 {b = abs(++-2)} {1} +test_expr2 expr-7.67 {b = abs(+-+-2)} {1} +test_expr2 expr-7.68 {b = abs(+-++-2)} {1} +test_expr2 expr-7.69 {b = abs(++++-2)} {1} +test_expr2 expr-7.70 {b = 5 - abs(+3)} {1} +test_expr2 expr-7.71 {b = 5 - abs(-3)} {1} +ifcapable floatingpoint { + test_expr2 expr-7.72 {b = abs(-2.0)} {1} +} +test_expr2 expr-7.73 {b = 6 - abs(-a)} {2} +ifcapable floatingpoint { + test_expr2 expr-7.74 {b = abs(8.0)} {3} +} + +# Test the CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP expressions. +# +ifcapable {floatingpoint} { + set sqlite_current_time 1157124849 + do_test expr-8.1 { + execsql {SELECT CURRENT_TIME} + } {15:34:09} + do_test expr-8.2 { + execsql {SELECT CURRENT_DATE} + } {2006-09-01} + do_test expr-8.3 { + execsql {SELECT CURRENT_TIMESTAMP} + } {{2006-09-01 15:34:09}} +} +ifcapable datetime { + do_test expr-8.4 { + execsql {SELECT CURRENT_TIME==time('now');} + } 1 + do_test expr-8.5 { + execsql {SELECT CURRENT_DATE==date('now');} + } 1 + do_test expr-8.6 { + execsql {SELECT CURRENT_TIMESTAMP==datetime('now');} + } 1 +} +set sqlite_current_time 0 + +ifcapable floatingpoint { + do_test expr-9.1 { + execsql {SELECT round(-('-'||'123'))} + } 123.0 +} + +# Test an error message that can be generated by the LIKE expression +do_test expr-10.1 { + catchsql {SELECT 'abc' LIKE 'abc' ESCAPE ''} +} {1 {ESCAPE expression must be a single character}} +do_test expr-10.2 { + catchsql {SELECT 'abc' LIKE 'abc' ESCAPE 'ab'} +} {1 {ESCAPE expression must be a single character}} + +# If we specify an integer constant that is bigger than the largest +# possible integer, code the integer as a real number. +# +do_test expr-11.1 { + execsql {SELECT typeof(9223372036854775807)} +} {integer} +do_test expr-11.2 { + execsql {SELECT typeof(00000009223372036854775807)} +} {integer} +do_test expr-11.3 { + execsql {SELECT typeof(+9223372036854775807)} +} {integer} +do_test expr-11.4 { + execsql {SELECT typeof(+000000009223372036854775807)} +} {integer} +do_test expr-11.5 { + execsql {SELECT typeof(9223372036854775808)} +} {real} +do_test expr-11.6 { + execsql {SELECT typeof(00000009223372036854775808)} +} {real} +do_test expr-11.7 { + execsql {SELECT typeof(+9223372036854775808)} +} {real} +do_test expr-11.8 { + execsql {SELECT typeof(+0000009223372036854775808)} +} {real} +do_test expr-11.11 { + execsql {SELECT typeof(-9223372036854775808)} +} {integer} +do_test expr-11.12 { + execsql {SELECT typeof(-00000009223372036854775808)} +} {integer} +ifcapable floatingpoint { + do_test expr-11.13 { + execsql {SELECT typeof(-9223372036854775809)} + } {real} + do_test expr-11.14 { + execsql {SELECT typeof(-00000009223372036854775809)} + } {real} +} + +# These two statements used to leak memory (because of missing %destructor +# directives in parse.y). +do_test expr-12.1 { + catchsql { + SELECT (CASE a>4 THEN 1 ELSE 0 END) FROM test1; + } +} {1 {near "THEN": syntax error}} +do_test expr-12.2 { + catchsql { + SELECT (CASE WHEN a>4 THEN 1 ELSE 0) FROM test1; + } +} {1 {near ")": syntax error}} + +ifcapable floatingpoint { + do_realnum_test expr-13.1 { + execsql { + SELECT 12345678901234567890; + } + } {1.23456789012346e+19} +} + +# Implicit String->Integer conversion is used when possible. +# +if {[working_64bit_int]} { + do_test expr-13.2 { + execsql { + SELECT 0+'9223372036854775807' + } + } {9223372036854775807} + do_test expr-13.3 { + execsql { + SELECT '9223372036854775807'+0 + } + } {9223372036854775807} +} + +# If the value is too large, use String->Float conversion. +# +ifcapable floatingpoint { + do_realnum_test expr-13.4 { + execsql { + SELECT 0+'9223372036854775808' + } + } {9.22337203685478e+18} + do_realnum_test expr-13.5 { + execsql { + SELECT '9223372036854775808'+0 + } + } {9.22337203685478e+18} +} + +# Use String->float conversion if the value is explicitly a floating +# point value. +# +do_realnum_test expr-13.6 { + execsql { + SELECT 0+'9223372036854775807.0' + } +} {9.22337203685478e+18} +do_realnum_test expr-13.7 { + execsql { + SELECT '9223372036854775807.0'+0 + } +} {9.22337203685478e+18} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fallocate.test b/components/external/SQLite-3.8.1/test/fallocate.test new file mode 100644 index 0000000000000000000000000000000000000000..f523c2cc4a834f36189656c370f82086f0007906 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fallocate.test @@ -0,0 +1,145 @@ +# 2010 July 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +file_control_chunksize_test db main [expr 1024*1024] + +do_test fallocate-1.1 { + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 1; + CREATE TABLE t1(a, b); + } + file size test.db +} [expr 1*1024*1024] + +do_test fallocate-1.2 { + execsql { INSERT INTO t1 VALUES(1, zeroblob(1024*900)) } + file size test.db +} [expr 1*1024*1024] + +do_test fallocate-1.3 { + execsql { INSERT INTO t1 VALUES(2, zeroblob(1024*900)) } + file size test.db +} [expr 2*1024*1024] + +do_test fallocate-1.4 { + execsql { DELETE FROM t1 WHERE a = 1 } + file size test.db +} [expr 1*1024*1024] + +do_test fallocate-1.5 { + execsql { DELETE FROM t1 WHERE a = 2 } + file size test.db +} [expr 1*1024*1024] + +do_test fallocate-1.6 { + execsql { PRAGMA freelist_count } +} {0} + +# Start a write-transaction and read the "database file size" field from +# the journal file. This field should be set to the number of pages in +# the database file based on the size of the file on disk, not the actual +# logical size of the database within the file. +# +# We need to check this to verify that if in the unlikely event a rollback +# causes a database file to grow, the database grows to its previous size +# on disk, not to the minimum size required to hold the database image. +# +do_test fallocate-1.7 { + execsql { BEGIN; INSERT INTO t1 VALUES(1, 2); } + if {[permutation] != "inmemory_journal"} { + hexio_get_int [hexio_read test.db-journal 16 4] + } else { + set {} 1024 + } +} {1024} +do_test fallocate-1.8 { execsql { COMMIT } } {} + + +#------------------------------------------------------------------------- +# The following tests - fallocate-2.* - test that things work in WAL +# mode as well. +# +set skipwaltests [expr { + [permutation]=="journaltest" || [permutation]=="inmemory_journal" +}] +ifcapable !wal { set skipwaltests 1 } + +if {!$skipwaltests} { + db close + forcedelete test.db + sqlite3 db test.db + file_control_chunksize_test db main [expr 32*1024] + + do_test fallocate-2.1 { + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + } + file size test.db + } [expr 32*1024] + + do_test fallocate-2.2 { + execsql { INSERT INTO t1 VALUES(1, zeroblob(35*1024)) } + execsql { PRAGMA wal_checkpoint } + file size test.db + } [expr 64*1024] + + do_test fallocate-2.3 { + execsql { DELETE FROM t1 } + execsql { VACUUM } + file size test.db + } [expr 64*1024] + + do_test fallocate-2.4 { + execsql { PRAGMA wal_checkpoint } + file size test.db + } [expr 32*1024] + + do_test fallocate-2.5 { + execsql { + INSERT INTO t1 VALUES(2, randomblob(35*1024)); + PRAGMA wal_checkpoint; + INSERT INTO t1 VALUES(3, randomblob(128)); + DELETE FROM t1 WHERE a = 2; + VACUUM; + } + file size test.db + } [expr 64*1024] + + do_test fallocate-2.6 { + sqlite3 db2 test.db + execsql { BEGIN ; SELECT count(a) FROM t1 } db2 + execsql { + INSERT INTO t1 VALUES(4, randomblob(128)); + PRAGMA wal_checkpoint; + } + file size test.db + } [expr 64*1024] + + do_test fallocate-2.7 { + execsql { SELECT count(b) FROM t1 } db2 + } {1} + + do_test fallocate-2.8 { + execsql { COMMIT } db2 + execsql { PRAGMA wal_checkpoint } + file size test.db + } [expr 32*1024] +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/filectrl.test b/components/external/SQLite-3.8.1/test/filectrl.test new file mode 100644 index 0000000000000000000000000000000000000000..1d878bf968b002693118ac973c7ab5c5a0302e61 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/filectrl.test @@ -0,0 +1,47 @@ +# 2008 Jan 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: filectrl.test,v 1.2 2008/11/21 00:10:35 aswift Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +do_test filectrl-1.1 { + file_control_test db +} {} +do_test filectrl-1.2 { + db eval {CREATE TEMP TABLE x(y);} + file_control_test db +} {} +do_test filectrl-1.3 { + db close + sqlite3 db :memory: + file_control_test db +} {} +do_test filectrl-1.4 { + sqlite3 db test.db + file_control_lasterrno_test db +} {} +do_test filectrl-1.5 { + db close + sqlite3 db test_control_lockproxy.db + file_control_lockproxy_test db [get_pwd] +} {} +do_test filectrl-1.6 { + sqlite3 db test.db + set fn [file_control_tempfilename db] + puts -nonewline \[$fn\] + set fn +} {/etilqs_/} +db close +forcedelete .test_control_lockproxy.db-conch test.proxy +finish_test diff --git a/components/external/SQLite-3.8.1/test/filefmt.test b/components/external/SQLite-3.8.1/test/filefmt.test new file mode 100644 index 0000000000000000000000000000000000000000..2df142443602e1a8914b191e31f87ffa0d89b256 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/filefmt.test @@ -0,0 +1,250 @@ +# 2007 April 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify database file format. +# +# $Id: filefmt.test,v 1.3 2009/06/18 11:34:43 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +db close +forcedelete test.db test.db-journal + +# Database begins with valid 16-byte header string. +# +do_test filefmt-1.1 { + sqlite3 db test.db + db eval {CREATE TABLE t1(x)} + db close + hexio_read test.db 0 16 +} {53514C69746520666F726D6174203300} + +# If the 16-byte header is changed, the file will not open +# +do_test filefmt-1.2 { + hexio_write test.db 0 54 + set x [catch {sqlite3 db test.db} err] + lappend x $err +} {0 {}} +do_test filefmt-1.3 { + catchsql { + SELECT count(*) FROM sqlite_master + } +} {1 {file is encrypted or is not a database}} +do_test filefmt-1.4 { + db close + hexio_write test.db 0 53 + sqlite3 db test.db + catchsql { + SELECT count(*) FROM sqlite_master + } +} {0 1} + +# The page-size is stored at offset 16 +# +ifcapable pager_pragmas { + foreach pagesize {512 1024 2048 4096 8192 16384 32768} { + if {[info exists SQLITE_MAX_PAGE_SIZE] + && $pagesize>$SQLITE_MAX_PAGE_SIZE} continue + do_test filefmt-1.5.$pagesize.1 { + db close + forcedelete test.db + sqlite3 db test.db + db eval "PRAGMA auto_vacuum=OFF" + db eval "PRAGMA page_size=$pagesize" + db eval {CREATE TABLE t1(x)} + file size test.db + } [expr $pagesize*2] + do_test filefmt-1.5.$pagesize.2 { + hexio_get_int [hexio_read test.db 16 2] + } $pagesize + } +} + +# The page-size must be a power of 2 +# +do_test filefmt-1.6 { + db close + hexio_write test.db 16 [hexio_render_int16 1025] + sqlite3 db test.db + catchsql { + SELECT count(*) FROM sqlite_master + } +} {1 {file is encrypted or is not a database}} + + +# The page-size must be at least 512 bytes +# +do_test filefmt-1.7 { + db close + hexio_write test.db 16 [hexio_render_int16 256] + sqlite3 db test.db + catchsql { + SELECT count(*) FROM sqlite_master + } +} {1 {file is encrypted or is not a database}} + +# Usable space per page (page-size minus unused space per page) +# must be at least 480 bytes +# +ifcapable pager_pragmas { + do_test filefmt-1.8 { + db close + forcedelete test.db + sqlite3 db test.db + db eval {PRAGMA page_size=512; CREATE TABLE t1(x)} + db close + hexio_write test.db 20 21 + sqlite3 db test.db + catchsql { + SELECT count(*) FROM sqlite_master + } + } {1 {file is encrypted or is not a database}} +} + +#------------------------------------------------------------------------- +# The following block of tests - filefmt-2.* - test that versions 3.7.0 +# and later can read and write databases that have been modified or created +# by 3.6.23.1 and earlier. The difference difference is that 3.7.0 stores +# the size of the database in the database file header, whereas 3.6.23.1 +# always derives this from the size of the file. +# +db close +forcedelete test.db + +set a_string_counter 1 +proc a_string {n} { + incr ::a_string_counter + string range [string repeat "${::a_string_counter}." $n] 1 $n +} +sqlite3 db test.db +db func a_string a_string + +do_execsql_test filefmt-2.1.1 { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(a); + CREATE INDEX i1 ON t1(a); + INSERT INTO t1 VALUES(a_string(3000)); + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(1); +} {} +do_test filefmt-2.1.2 { + hexio_read test.db 28 4 +} {00000009} + +do_test filefmt-2.1.3 { + sql36231 { INSERT INTO t1 VALUES(a_string(3000)) } +} {} + +do_execsql_test filefmt-2.1.4 { INSERT INTO t2 VALUES(2) } {} +integrity_check filefmt-2.1.5 +do_test filefmt-2.1.6 { hexio_read test.db 28 4 } {00000010} + +db close +forcedelete test.db +sqlite3 db test.db +db func a_string a_string + +do_execsql_test filefmt-2.2.1 { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(a); + CREATE INDEX i1 ON t1(a); + INSERT INTO t1 VALUES(a_string(3000)); + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(1); +} {} +do_test filefmt-2.2.2 { + hexio_read test.db 28 4 +} {00000009} + +do_test filefmt-2.2.3 { + sql36231 { INSERT INTO t1 VALUES(a_string(3000)) } +} {} + +do_execsql_test filefmt-2.2.4 { + PRAGMA integrity_check; + BEGIN; + INSERT INTO t2 VALUES(2); + SAVEPOINT a; + INSERT INTO t2 VALUES(3); + ROLLBACK TO a; +} {ok} + +integrity_check filefmt-2.2.5 +do_execsql_test filefmt-2.2.6 { COMMIT } {} +db close +sqlite3 db test.db +integrity_check filefmt-2.2.7 + +#-------------------------------------------------------------------------- +# Check that ticket 89b8c9ac54 is fixed. Before the fix, the SELECT +# statement would return SQLITE_CORRUPT. The database file was not actually +# corrupted, but SQLite was reporting that it was. +# +db close +forcedelete test.db +sqlite3 db test.db +do_execsql_test filefmt-3.1 { + PRAGMA auto_vacuum = 1; + CREATE TABLE t1(a, b); +} {} +do_test filefmt-3.2 { + sql36231 { DROP TABLE t1 } +} {} +do_execsql_test filefmt-3.3 { + SELECT * FROM sqlite_master; + PRAGMA integrity_check; +} {ok} + +reset_db +do_execsql_test filefmt-4.1 { + PRAGMA auto_vacuum = 1; + CREATE TABLE t1(x, y); + CREATE TABLE t2(x, y); + + INSERT INTO t1 VALUES(randomblob(100), randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100), randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100), randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100), randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100), randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100), randomblob(100)); + + INSERT INTO t2 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t2 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t2 SELECT randomblob(100), randomblob(100) FROM t1; + INSERT INTO t2 SELECT randomblob(100), randomblob(100) FROM t1; +} + +do_test filefmt-4.2 { + sql36231 { INSERT INTO t2 SELECT * FROM t1 } +} {} + +do_test filefmt-4.3 { + forcedelete bak.db + db backup bak.db +} {} + +do_test filefmt-4.4 { + sqlite3 db2 bak.db + db2 eval { PRAGMA integrity_check } +} {ok} +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fkey1.test b/components/external/SQLite-3.8.1/test/fkey1.test new file mode 100644 index 0000000000000000000000000000000000000000..90a4c44409ed94d68188651efe3eabeedc7ce3eb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fkey1.test @@ -0,0 +1,124 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for foreign keys. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!foreignkey} { + finish_test + return +} + +# Create a table and some data to work with. +# +do_test fkey1-1.0 { + execsql { + CREATE TABLE t1( + a INTEGER PRIMARY KEY, + b INTEGER + REFERENCES t1 ON DELETE CASCADE + REFERENCES t2, + c TEXT, + FOREIGN KEY (b,c) REFERENCES t2(x,y) ON UPDATE CASCADE + ); + } +} {} +do_test fkey1-1.1 { + execsql { + CREATE TABLE t2( + x INTEGER PRIMARY KEY, + y TEXT + ); + } +} {} +do_test fkey1-1.2 { + execsql { + CREATE TABLE t3( + a INTEGER REFERENCES t2, + b INTEGER REFERENCES t1, + FOREIGN KEY (a,b) REFERENCES t2(x,y) + ); + } +} {} + +do_test fkey1-2.1 { + execsql { + CREATE TABLE t4(a integer primary key); + CREATE TABLE t5(x references t4); + CREATE TABLE t6(x references t4); + CREATE TABLE t7(x references t4); + CREATE TABLE t8(x references t4); + CREATE TABLE t9(x references t4); + CREATE TABLE t10(x references t4); + DROP TABLE t7; + DROP TABLE t9; + DROP TABLE t5; + DROP TABLE t8; + DROP TABLE t6; + DROP TABLE t10; + } +} {} + +do_test fkey1-3.1 { + execsql { + CREATE TABLE t5(a PRIMARY KEY, b, c); + CREATE TABLE t6( + d REFERENCES t5, + e REFERENCES t5(c) + ); + PRAGMA foreign_key_list(t6); + } +} [concat \ + {0 0 t5 e c {NO ACTION} {NO ACTION} NONE} \ + {1 0 t5 d {} {NO ACTION} {NO ACTION} NONE} \ +] +do_test fkey1-3.2 { + execsql { + CREATE TABLE t7(d, e, f, + FOREIGN KEY (d, e) REFERENCES t5(a, b) + ); + PRAGMA foreign_key_list(t7); + } +} [concat \ + {0 0 t5 d a {NO ACTION} {NO ACTION} NONE} \ + {0 1 t5 e b {NO ACTION} {NO ACTION} NONE} \ +] +do_test fkey1-3.3 { + execsql { + CREATE TABLE t8(d, e, f, + FOREIGN KEY (d, e) REFERENCES t5 ON DELETE CASCADE ON UPDATE SET NULL + ); + PRAGMA foreign_key_list(t8); + } +} [concat \ + {0 0 t5 d {} {SET NULL} CASCADE NONE} \ + {0 1 t5 e {} {SET NULL} CASCADE NONE} \ +] +do_test fkey1-3.4 { + execsql { + CREATE TABLE t9(d, e, f, + FOREIGN KEY (d, e) REFERENCES t5 ON DELETE CASCADE ON UPDATE SET DEFAULT + ); + PRAGMA foreign_key_list(t9); + } +} [concat \ + {0 0 t5 d {} {SET DEFAULT} CASCADE NONE} \ + {0 1 t5 e {} {SET DEFAULT} CASCADE NONE} \ +] +do_test fkey1-3.5 { + sqlite3_db_status db DBSTATUS_DEFERRED_FKS 0 +} {0 0 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fkey2.test b/components/external/SQLite-3.8.1/test/fkey2.test new file mode 100644 index 0000000000000000000000000000000000000000..3e5b27c1e6791edb5ee0505b9d67eb4ffbb4ec4b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fkey2.test @@ -0,0 +1,2017 @@ +# 2009 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for foreign keys. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!foreignkey||!trigger} { + finish_test + return +} + +#------------------------------------------------------------------------- +# Test structure: +# +# fkey2-1.*: Simple tests to check that immediate and deferred foreign key +# constraints work when not inside a transaction. +# +# fkey2-2.*: Tests to verify that deferred foreign keys work inside +# explicit transactions (i.e that processing really is deferred). +# +# fkey2-3.*: Tests that a statement transaction is rolled back if an +# immediate foreign key constraint is violated. +# +# fkey2-4.*: Test that FK actions may recurse even when recursive triggers +# are disabled. +# +# fkey2-5.*: Check that if foreign-keys are enabled, it is not possible +# to write to an FK column using the incremental blob API. +# +# fkey2-6.*: Test that FK processing is automatically disabled when +# running VACUUM. +# +# fkey2-7.*: Test using an IPK as the key in the child (referencing) table. +# +# fkey2-8.*: Test that enabling/disabling foreign key support while a +# transaction is active is not possible. +# +# fkey2-9.*: Test SET DEFAULT actions. +# +# fkey2-10.*: Test errors. +# +# fkey2-11.*: Test CASCADE actions. +# +# fkey2-12.*: Test RESTRICT actions. +# +# fkey2-13.*: Test that FK processing is performed when a row is REPLACED by +# an UPDATE or INSERT statement. +# +# fkey2-14.*: Test the ALTER TABLE and DROP TABLE commands. +# +# fkey2-15.*: Test that if there are no (known) outstanding foreign key +# constraint violations in the database, inserting into a parent +# table or deleting from a child table does not cause SQLite +# to check if this has repaired an outstanding violation. +# +# fkey2-16.*: Test that rows that refer to themselves may be inserted, +# updated and deleted. +# +# fkey2-17.*: Test that the "count_changes" pragma does not interfere with +# FK constraint processing. +# +# fkey2-18.*: Test that the authorization callback is invoked when processing +# FK constraints. +# +# fkey2-20.*: Test that ON CONFLICT clauses specified as part of statements +# do not affect the operation of FK constraints. +# +# fkey2-genfkey.*: Tests that were used with the shell tool .genfkey +# command. Recycled to test the built-in implementation. +# +# fkey2-dd08e5.*: Tests to verify that ticket dd08e5a988d00decc4a543daa8d +# has been fixed. +# + + +execsql { PRAGMA foreign_keys = on } + +set FkeySimpleSchema { + PRAGMA foreign_keys = on; + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TABLE t2(c REFERENCES t1(a) /D/ , d); + + CREATE TABLE t3(a PRIMARY KEY, b); + CREATE TABLE t4(c REFERENCES t3 /D/, d); + + CREATE TABLE t7(a, b INTEGER PRIMARY KEY); + CREATE TABLE t8(c REFERENCES t7 /D/, d); + + CREATE TABLE t9(a REFERENCES nosuchtable, b); + CREATE TABLE t10(a REFERENCES t9(c) /D/, b); +} + + +set FkeySimpleTests { + 1.1 "INSERT INTO t2 VALUES(1, 3)" {1 {foreign key constraint failed}} + 1.2 "INSERT INTO t1 VALUES(1, 2)" {0 {}} + 1.3 "INSERT INTO t2 VALUES(1, 3)" {0 {}} + 1.4 "INSERT INTO t2 VALUES(2, 4)" {1 {foreign key constraint failed}} + 1.5 "INSERT INTO t2 VALUES(NULL, 4)" {0 {}} + 1.6 "UPDATE t2 SET c=2 WHERE d=4" {1 {foreign key constraint failed}} + 1.7 "UPDATE t2 SET c=1 WHERE d=4" {0 {}} + 1.9 "UPDATE t2 SET c=1 WHERE d=4" {0 {}} + 1.10 "UPDATE t2 SET c=NULL WHERE d=4" {0 {}} + 1.11 "DELETE FROM t1 WHERE a=1" {1 {foreign key constraint failed}} + 1.12 "UPDATE t1 SET a = 2" {1 {foreign key constraint failed}} + 1.13 "UPDATE t1 SET a = 1" {0 {}} + + 2.1 "INSERT INTO t4 VALUES(1, 3)" {1 {foreign key constraint failed}} + 2.2 "INSERT INTO t3 VALUES(1, 2)" {0 {}} + 2.3 "INSERT INTO t4 VALUES(1, 3)" {0 {}} + + 4.1 "INSERT INTO t8 VALUES(1, 3)" {1 {foreign key constraint failed}} + 4.2 "INSERT INTO t7 VALUES(2, 1)" {0 {}} + 4.3 "INSERT INTO t8 VALUES(1, 3)" {0 {}} + 4.4 "INSERT INTO t8 VALUES(2, 4)" {1 {foreign key constraint failed}} + 4.5 "INSERT INTO t8 VALUES(NULL, 4)" {0 {}} + 4.6 "UPDATE t8 SET c=2 WHERE d=4" {1 {foreign key constraint failed}} + 4.7 "UPDATE t8 SET c=1 WHERE d=4" {0 {}} + 4.9 "UPDATE t8 SET c=1 WHERE d=4" {0 {}} + 4.10 "UPDATE t8 SET c=NULL WHERE d=4" {0 {}} + 4.11 "DELETE FROM t7 WHERE b=1" {1 {foreign key constraint failed}} + 4.12 "UPDATE t7 SET b = 2" {1 {foreign key constraint failed}} + 4.13 "UPDATE t7 SET b = 1" {0 {}} + 4.14 "INSERT INTO t8 VALUES('a', 'b')" {1 {foreign key constraint failed}} + 4.15 "UPDATE t7 SET b = 5" {1 {foreign key constraint failed}} + 4.16 "UPDATE t7 SET rowid = 5" {1 {foreign key constraint failed}} + 4.17 "UPDATE t7 SET a = 10" {0 {}} + + 5.1 "INSERT INTO t9 VALUES(1, 3)" {1 {no such table: main.nosuchtable}} + 5.2 "INSERT INTO t10 VALUES(1, 3)" + {1 {foreign key mismatch - "t10" referencing "t9"}} +} + +do_test fkey2-1.1.0 { + execsql [string map {/D/ {}} $FkeySimpleSchema] +} {} +foreach {tn zSql res} $FkeySimpleTests { + do_test fkey2-1.1.$tn.1 { catchsql $zSql } $res + do_test fkey2-1.1.$tn.2 { execsql {PRAGMA foreign_key_check(t1)} } {} + do_test fkey2-1.1.$tn.3 { execsql {PRAGMA foreign_key_check(t2)} } {} + do_test fkey2-1.1.$tn.4 { execsql {PRAGMA foreign_key_check(t3)} } {} + do_test fkey2-1.1.$tn.5 { execsql {PRAGMA foreign_key_check(t4)} } {} + do_test fkey2-1.1.$tn.6 { execsql {PRAGMA foreign_key_check(t7)} } {} + do_test fkey2-1.1.$tn.7 { execsql {PRAGMA foreign_key_check(t8)} } {} +} +drop_all_tables + +do_test fkey2-1.2.0 { + execsql [string map {/D/ {DEFERRABLE INITIALLY DEFERRED}} $FkeySimpleSchema] +} {} +foreach {tn zSql res} $FkeySimpleTests { + do_test fkey2-1.2.$tn { catchsql $zSql } $res + do_test fkey2-1.2.$tn.2 { execsql {PRAGMA foreign_key_check(t1)} } {} + do_test fkey2-1.2.$tn.3 { execsql {PRAGMA foreign_key_check(t2)} } {} + do_test fkey2-1.2.$tn.4 { execsql {PRAGMA foreign_key_check(t3)} } {} + do_test fkey2-1.2.$tn.5 { execsql {PRAGMA foreign_key_check(t4)} } {} + do_test fkey2-1.2.$tn.6 { execsql {PRAGMA foreign_key_check(t7)} } {} + do_test fkey2-1.2.$tn.7 { execsql {PRAGMA foreign_key_check(t8)} } {} +} +drop_all_tables + +do_test fkey2-1.3.0 { + execsql [string map {/D/ {}} $FkeySimpleSchema] + execsql { PRAGMA count_changes = 1 } +} {} +foreach {tn zSql res} $FkeySimpleTests { + if {$res == "0 {}"} { set res {0 1} } + do_test fkey2-1.3.$tn { catchsql $zSql } $res + do_test fkey2-1.3.$tn.2 { execsql {PRAGMA foreign_key_check(t1)} } {} + do_test fkey2-1.3.$tn.3 { execsql {PRAGMA foreign_key_check(t2)} } {} + do_test fkey2-1.3.$tn.4 { execsql {PRAGMA foreign_key_check(t3)} } {} + do_test fkey2-1.3.$tn.5 { execsql {PRAGMA foreign_key_check(t4)} } {} + do_test fkey2-1.3.$tn.6 { execsql {PRAGMA foreign_key_check(t7)} } {} + do_test fkey2-1.3.$tn.7 { execsql {PRAGMA foreign_key_check(t8)} } {} +} +execsql { PRAGMA count_changes = 0 } +drop_all_tables + +do_test fkey2-1.4.0 { + execsql [string map {/D/ {}} $FkeySimpleSchema] + execsql { PRAGMA count_changes = 1 } +} {} +foreach {tn zSql res} $FkeySimpleTests { + if {$res == "0 {}"} { set res {0 1} } + execsql BEGIN + do_test fkey2-1.4.$tn { catchsql $zSql } $res + execsql COMMIT +} +execsql { PRAGMA count_changes = 0 } +drop_all_tables + +# Special test: When the parent key is an IPK, make sure the affinity of +# the IPK is not applied to the child key value before it is inserted +# into the child table. +do_test fkey2-1.5.1 { + execsql { + CREATE TABLE i(i INTEGER PRIMARY KEY); + CREATE TABLE j(j REFERENCES i); + INSERT INTO i VALUES(35); + INSERT INTO j VALUES('35.0'); + SELECT j, typeof(j) FROM j; + } +} {35.0 text} +do_test fkey2-1.5.2 { + catchsql { DELETE FROM i } +} {1 {foreign key constraint failed}} + +# Same test using a regular primary key with integer affinity. +drop_all_tables +do_test fkey2-1.6.1 { + execsql { + CREATE TABLE i(i INT UNIQUE); + CREATE TABLE j(j REFERENCES i(i)); + INSERT INTO i VALUES('35.0'); + INSERT INTO j VALUES('35.0'); + SELECT j, typeof(j) FROM j; + SELECT i, typeof(i) FROM i; + } +} {35.0 text 35 integer} +do_test fkey2-1.6.2 { + catchsql { DELETE FROM i } +} {1 {foreign key constraint failed}} + +# Use a collation sequence on the parent key. +drop_all_tables +do_test fkey2-1.7.1 { + execsql { + CREATE TABLE i(i TEXT COLLATE nocase PRIMARY KEY); + CREATE TABLE j(j TEXT COLLATE binary REFERENCES i(i)); + INSERT INTO i VALUES('SQLite'); + INSERT INTO j VALUES('sqlite'); + } + catchsql { DELETE FROM i } +} {1 {foreign key constraint failed}} + +# Use the parent key collation even if it is default and the child key +# has an explicit value. +drop_all_tables +do_test fkey2-1.7.2 { + execsql { + CREATE TABLE i(i TEXT PRIMARY KEY); -- Colseq is "BINARY" + CREATE TABLE j(j TEXT COLLATE nocase REFERENCES i(i)); + INSERT INTO i VALUES('SQLite'); + } + catchsql { INSERT INTO j VALUES('sqlite') } +} {1 {foreign key constraint failed}} +do_test fkey2-1.7.3 { + execsql { + INSERT INTO i VALUES('sqlite'); + INSERT INTO j VALUES('sqlite'); + DELETE FROM i WHERE i = 'SQLite'; + } + catchsql { DELETE FROM i WHERE i = 'sqlite' } +} {1 {foreign key constraint failed}} + +#------------------------------------------------------------------------- +# This section (test cases fkey2-2.*) contains tests to check that the +# deferred foreign key constraint logic works. +# +proc fkey2-2-test {tn nocommit sql {res {}}} { + if {$res eq "FKV"} { + set expected {1 {foreign key constraint failed}} + } else { + set expected [list 0 $res] + } + do_test fkey2-2.$tn [list catchsql $sql] $expected + if {$nocommit} { + do_test fkey2-2.${tn}c { + catchsql COMMIT + } {1 {foreign key constraint failed}} + } +} + +fkey2-2-test 1 0 { + CREATE TABLE node( + nodeid PRIMARY KEY, + parent REFERENCES node DEFERRABLE INITIALLY DEFERRED + ); + CREATE TABLE leaf( + cellid PRIMARY KEY, + parent REFERENCES node DEFERRABLE INITIALLY DEFERRED + ); +} + +fkey2-2-test 1 0 "INSERT INTO node VALUES(1, 0)" FKV +fkey2-2-test 2 0 "BEGIN" +fkey2-2-test 3 1 "INSERT INTO node VALUES(1, 0)" +fkey2-2-test 4 0 "UPDATE node SET parent = NULL" +fkey2-2-test 5 0 "COMMIT" +fkey2-2-test 6 0 "SELECT * FROM node" {1 {}} + +fkey2-2-test 7 0 "BEGIN" +fkey2-2-test 8 1 "INSERT INTO leaf VALUES('a', 2)" +fkey2-2-test 9 1 "INSERT INTO node VALUES(2, 0)" +fkey2-2-test 10 0 "UPDATE node SET parent = 1 WHERE nodeid = 2" +fkey2-2-test 11 0 "COMMIT" +fkey2-2-test 12 0 "SELECT * FROM node" {1 {} 2 1} +fkey2-2-test 13 0 "SELECT * FROM leaf" {a 2} + +fkey2-2-test 14 0 "BEGIN" +fkey2-2-test 15 1 "DELETE FROM node WHERE nodeid = 2" +fkey2-2-test 16 0 "INSERT INTO node VALUES(2, NULL)" +fkey2-2-test 17 0 "COMMIT" +fkey2-2-test 18 0 "SELECT * FROM node" {1 {} 2 {}} +fkey2-2-test 19 0 "SELECT * FROM leaf" {a 2} + +fkey2-2-test 20 0 "BEGIN" +fkey2-2-test 21 0 "INSERT INTO leaf VALUES('b', 1)" +fkey2-2-test 22 0 "SAVEPOINT save" +fkey2-2-test 23 0 "DELETE FROM node WHERE nodeid = 1" +fkey2-2-test 24 0 "ROLLBACK TO save" +fkey2-2-test 25 0 "COMMIT" +fkey2-2-test 26 0 "SELECT * FROM node" {1 {} 2 {}} +fkey2-2-test 27 0 "SELECT * FROM leaf" {a 2 b 1} + +fkey2-2-test 28 0 "BEGIN" +fkey2-2-test 29 0 "INSERT INTO leaf VALUES('c', 1)" +fkey2-2-test 30 0 "SAVEPOINT save" +fkey2-2-test 31 0 "DELETE FROM node WHERE nodeid = 1" +fkey2-2-test 32 1 "RELEASE save" +fkey2-2-test 33 1 "DELETE FROM leaf WHERE cellid = 'b'" +fkey2-2-test 34 0 "DELETE FROM leaf WHERE cellid = 'c'" +fkey2-2-test 35 0 "COMMIT" +fkey2-2-test 36 0 "SELECT * FROM node" {2 {}} +fkey2-2-test 37 0 "SELECT * FROM leaf" {a 2} + +fkey2-2-test 38 0 "SAVEPOINT outer" +fkey2-2-test 39 1 "INSERT INTO leaf VALUES('d', 3)" +fkey2-2-test 40 1 "RELEASE outer" FKV +fkey2-2-test 41 1 "INSERT INTO leaf VALUES('e', 3)" +fkey2-2-test 42 0 "INSERT INTO node VALUES(3, 2)" +fkey2-2-test 43 0 "RELEASE outer" + +fkey2-2-test 44 0 "SAVEPOINT outer" +fkey2-2-test 45 1 "DELETE FROM node WHERE nodeid=3" +fkey2-2-test 47 0 "INSERT INTO node VALUES(3, 2)" +fkey2-2-test 48 0 "ROLLBACK TO outer" +fkey2-2-test 49 0 "RELEASE outer" + +fkey2-2-test 50 0 "SAVEPOINT outer" +fkey2-2-test 51 1 "INSERT INTO leaf VALUES('f', 4)" +fkey2-2-test 52 1 "SAVEPOINT inner" +fkey2-2-test 53 1 "INSERT INTO leaf VALUES('g', 4)" +fkey2-2-test 54 1 "RELEASE outer" FKV +fkey2-2-test 55 1 "ROLLBACK TO inner" +fkey2-2-test 56 0 "COMMIT" FKV +fkey2-2-test 57 0 "INSERT INTO node VALUES(4, NULL)" +fkey2-2-test 58 0 "RELEASE outer" +fkey2-2-test 59 0 "SELECT * FROM node" {2 {} 3 2 4 {}} +fkey2-2-test 60 0 "SELECT * FROM leaf" {a 2 d 3 e 3 f 4} + +# The following set of tests check that if a statement that affects +# multiple rows violates some foreign key constraints, then strikes a +# constraint that causes the statement-transaction to be rolled back, +# the deferred constraint counter is correctly reset to the value it +# had before the statement-transaction was opened. +# +fkey2-2-test 61 0 "BEGIN" +fkey2-2-test 62 0 "DELETE FROM leaf" +fkey2-2-test 63 0 "DELETE FROM node" +fkey2-2-test 64 1 "INSERT INTO leaf VALUES('a', 1)" +fkey2-2-test 65 1 "INSERT INTO leaf VALUES('b', 2)" +fkey2-2-test 66 1 "INSERT INTO leaf VALUES('c', 1)" +do_test fkey2-2-test-67 { + catchsql "INSERT INTO node SELECT parent, 3 FROM leaf" +} {1 {column nodeid is not unique}} +fkey2-2-test 68 0 "COMMIT" FKV +fkey2-2-test 69 1 "INSERT INTO node VALUES(1, NULL)" +fkey2-2-test 70 0 "INSERT INTO node VALUES(2, NULL)" +fkey2-2-test 71 0 "COMMIT" + +fkey2-2-test 72 0 "BEGIN" +fkey2-2-test 73 1 "DELETE FROM node" +fkey2-2-test 74 0 "INSERT INTO node(nodeid) SELECT DISTINCT parent FROM leaf" +fkey2-2-test 75 0 "COMMIT" + +#------------------------------------------------------------------------- +# Test cases fkey2-3.* test that a program that executes foreign key +# actions (CASCADE, SET DEFAULT, SET NULL etc.) or tests FK constraints +# opens a statement transaction if required. +# +# fkey2-3.1.*: Test UPDATE statements. +# fkey2-3.2.*: Test DELETE statements. +# +drop_all_tables +do_test fkey2-3.1.1 { + execsql { + CREATE TABLE ab(a PRIMARY KEY, b); + CREATE TABLE cd( + c PRIMARY KEY REFERENCES ab ON UPDATE CASCADE ON DELETE CASCADE, + d + ); + CREATE TABLE ef( + e REFERENCES cd ON UPDATE CASCADE, + f, CHECK (e!=5) + ); + } +} {} +do_test fkey2-3.1.2 { + execsql { + INSERT INTO ab VALUES(1, 'b'); + INSERT INTO cd VALUES(1, 'd'); + INSERT INTO ef VALUES(1, 'e'); + } +} {} +do_test fkey2-3.1.3 { + catchsql { UPDATE ab SET a = 5 } +} {1 {constraint failed}} +do_test fkey2-3.1.4 { + execsql { SELECT * FROM ab } +} {1 b} +do_test fkey2-3.1.4 { + execsql BEGIN; + catchsql { UPDATE ab SET a = 5 } +} {1 {constraint failed}} +do_test fkey2-3.1.5 { + execsql COMMIT; + execsql { SELECT * FROM ab; SELECT * FROM cd; SELECT * FROM ef } +} {1 b 1 d 1 e} + +do_test fkey2-3.2.1 { + execsql BEGIN; + catchsql { DELETE FROM ab } +} {1 {foreign key constraint failed}} +do_test fkey2-3.2.2 { + execsql COMMIT + execsql { SELECT * FROM ab; SELECT * FROM cd; SELECT * FROM ef } +} {1 b 1 d 1 e} + +#------------------------------------------------------------------------- +# Test cases fkey2-4.* test that recursive foreign key actions +# (i.e. CASCADE) are allowed even if recursive triggers are disabled. +# +drop_all_tables +do_test fkey2-4.1 { + execsql { + CREATE TABLE t1( + node PRIMARY KEY, + parent REFERENCES t1 ON DELETE CASCADE + ); + CREATE TABLE t2(node PRIMARY KEY, parent); + CREATE TRIGGER t2t AFTER DELETE ON t2 BEGIN + DELETE FROM t2 WHERE parent = old.node; + END; + INSERT INTO t1 VALUES(1, NULL); + INSERT INTO t1 VALUES(2, 1); + INSERT INTO t1 VALUES(3, 1); + INSERT INTO t1 VALUES(4, 2); + INSERT INTO t1 VALUES(5, 2); + INSERT INTO t1 VALUES(6, 3); + INSERT INTO t1 VALUES(7, 3); + INSERT INTO t2 SELECT * FROM t1; + } +} {} +do_test fkey2-4.2 { + execsql { PRAGMA recursive_triggers = off } + execsql { + BEGIN; + DELETE FROM t1 WHERE node = 1; + SELECT node FROM t1; + } +} {} +do_test fkey2-4.3 { + execsql { + DELETE FROM t2 WHERE node = 1; + SELECT node FROM t2; + ROLLBACK; + } +} {4 5 6 7} +do_test fkey2-4.4 { + execsql { PRAGMA recursive_triggers = on } + execsql { + BEGIN; + DELETE FROM t1 WHERE node = 1; + SELECT node FROM t1; + } +} {} +do_test fkey2-4.3 { + execsql { + DELETE FROM t2 WHERE node = 1; + SELECT node FROM t2; + ROLLBACK; + } +} {} + +#------------------------------------------------------------------------- +# Test cases fkey2-5.* verify that the incremental blob API may not +# write to a foreign key column while foreign-keys are enabled. +# +drop_all_tables +ifcapable incrblob { + do_test fkey2-5.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1(a)); + INSERT INTO t1 VALUES('hello', 'world'); + INSERT INTO t2 VALUES('key', 'hello'); + } + } {} + do_test fkey2-5.2 { + set rc [catch { set fd [db incrblob t2 b 1] } msg] + list $rc $msg + } {1 {cannot open foreign key column for writing}} + do_test fkey2-5.3 { + set rc [catch { set fd [db incrblob -readonly t2 b 1] } msg] + close $fd + set rc + } {0} + do_test fkey2-5.4 { + execsql { PRAGMA foreign_keys = off } + set rc [catch { set fd [db incrblob t2 b 1] } msg] + close $fd + set rc + } {0} + do_test fkey2-5.5 { + execsql { PRAGMA foreign_keys = on } + } {} +} + +drop_all_tables +ifcapable vacuum { + do_test fkey2-6.1 { + execsql { + CREATE TABLE t1(a REFERENCES t2(c), b); + CREATE TABLE t2(c UNIQUE, b); + INSERT INTO t2 VALUES(1, 2); + INSERT INTO t1 VALUES(1, 2); + VACUUM; + } + } {} +} + +#------------------------------------------------------------------------- +# Test that it is possible to use an INTEGER PRIMARY KEY as the child key +# of a foreign constraint. +# +drop_all_tables +do_test fkey2-7.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TABLE t2(c INTEGER PRIMARY KEY REFERENCES t1, b); + } +} {} +do_test fkey2-7.2 { + catchsql { INSERT INTO t2 VALUES(1, 'A'); } +} {1 {foreign key constraint failed}} +do_test fkey2-7.3 { + execsql { + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(2, 3); + INSERT INTO t2 VALUES(1, 'A'); + } +} {} +do_test fkey2-7.4 { + execsql { UPDATE t2 SET c = 2 } +} {} +do_test fkey2-7.5 { + catchsql { UPDATE t2 SET c = 3 } +} {1 {foreign key constraint failed}} +do_test fkey2-7.6 { + catchsql { DELETE FROM t1 WHERE a = 2 } +} {1 {foreign key constraint failed}} +do_test fkey2-7.7 { + execsql { DELETE FROM t1 WHERE a = 1 } +} {} +do_test fkey2-7.8 { + catchsql { UPDATE t1 SET a = 3 } +} {1 {foreign key constraint failed}} +do_test fkey2-7.9 { + catchsql { UPDATE t2 SET rowid = 3 } +} {1 {foreign key constraint failed}} + +#------------------------------------------------------------------------- +# Test that it is not possible to enable/disable FK support while a +# transaction is open. +# +drop_all_tables +proc fkey2-8-test {tn zSql value} { + do_test fkey-2.8.$tn.1 [list execsql $zSql] {} + do_test fkey-2.8.$tn.2 { execsql "PRAGMA foreign_keys" } $value +} +fkey2-8-test 1 { PRAGMA foreign_keys = 0 } 0 +fkey2-8-test 2 { PRAGMA foreign_keys = 1 } 1 +fkey2-8-test 3 { BEGIN } 1 +fkey2-8-test 4 { PRAGMA foreign_keys = 0 } 1 +fkey2-8-test 5 { COMMIT } 1 +fkey2-8-test 6 { PRAGMA foreign_keys = 0 } 0 +fkey2-8-test 7 { BEGIN } 0 +fkey2-8-test 8 { PRAGMA foreign_keys = 1 } 0 +fkey2-8-test 9 { COMMIT } 0 +fkey2-8-test 10 { PRAGMA foreign_keys = 1 } 1 +fkey2-8-test 11 { PRAGMA foreign_keys = off } 0 +fkey2-8-test 12 { PRAGMA foreign_keys = on } 1 +fkey2-8-test 13 { PRAGMA foreign_keys = no } 0 +fkey2-8-test 14 { PRAGMA foreign_keys = yes } 1 +fkey2-8-test 15 { PRAGMA foreign_keys = false } 0 +fkey2-8-test 16 { PRAGMA foreign_keys = true } 1 + +#------------------------------------------------------------------------- +# The following tests, fkey2-9.*, test SET DEFAULT actions. +# +drop_all_tables +do_test fkey2-9.1.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + CREATE TABLE t2( + c INTEGER PRIMARY KEY, + d INTEGER DEFAULT 1 REFERENCES t1 ON DELETE SET DEFAULT + ); + DELETE FROM t1; + } +} {} +do_test fkey2-9.1.2 { + execsql { + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t2 VALUES(1, 2); + SELECT * FROM t2; + DELETE FROM t1 WHERE a = 2; + SELECT * FROM t2; + } +} {1 2 1 1} +do_test fkey2-9.1.3 { + execsql { + INSERT INTO t1 VALUES(2, 'two'); + UPDATE t2 SET d = 2; + DELETE FROM t1 WHERE a = 1; + SELECT * FROM t2; + } +} {1 2} +do_test fkey2-9.1.4 { + execsql { SELECT * FROM t1 } +} {2 two} +do_test fkey2-9.1.5 { + catchsql { DELETE FROM t1 } +} {1 {foreign key constraint failed}} + +do_test fkey2-9.2.1 { + execsql { + CREATE TABLE pp(a, b, c, PRIMARY KEY(b, c)); + CREATE TABLE cc(d DEFAULT 3, e DEFAULT 1, f DEFAULT 2, + FOREIGN KEY(f, d) REFERENCES pp + ON UPDATE SET DEFAULT + ON DELETE SET NULL + ); + INSERT INTO pp VALUES(1, 2, 3); + INSERT INTO pp VALUES(4, 5, 6); + INSERT INTO pp VALUES(7, 8, 9); + } +} {} +do_test fkey2-9.2.2 { + execsql { + INSERT INTO cc VALUES(6, 'A', 5); + INSERT INTO cc VALUES(6, 'B', 5); + INSERT INTO cc VALUES(9, 'A', 8); + INSERT INTO cc VALUES(9, 'B', 8); + UPDATE pp SET b = 1 WHERE a = 7; + SELECT * FROM cc; + } +} {6 A 5 6 B 5 3 A 2 3 B 2} +do_test fkey2-9.2.3 { + execsql { + DELETE FROM pp WHERE a = 4; + SELECT * FROM cc; + } +} {{} A {} {} B {} 3 A 2 3 B 2} + +#------------------------------------------------------------------------- +# The following tests, fkey2-10.*, test "foreign key mismatch" and +# other errors. +# +set tn 0 +foreach zSql [list { + CREATE TABLE p(a PRIMARY KEY, b); + CREATE TABLE c(x REFERENCES p(c)); +} { + CREATE TABLE c(x REFERENCES v(y)); + CREATE VIEW v AS SELECT x AS y FROM c; +} { + CREATE TABLE p(a, b, PRIMARY KEY(a, b)); + CREATE TABLE c(x REFERENCES p); +} { + CREATE TABLE p(a COLLATE binary, b); + CREATE UNIQUE INDEX i ON p(a COLLATE nocase); + CREATE TABLE c(x REFERENCES p(a)); +}] { + drop_all_tables + do_test fkey2-10.1.[incr tn] { + execsql $zSql + catchsql { INSERT INTO c DEFAULT VALUES } + } {/1 {foreign key mismatch - "c" referencing "."}/} +} + +# "rowid" cannot be used as part of a child or parent key definition +# unless it happens to be the name of an explicitly declared column. +# +do_test fkey2-10.2.1 { + drop_all_tables + catchsql { + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TABLE t2(c, d, FOREIGN KEY(rowid) REFERENCES t1(a)); + } +} {1 {unknown column "rowid" in foreign key definition}} +do_test fkey2-10.2.2 { + drop_all_tables + catchsql { + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TABLE t2(rowid, d, FOREIGN KEY(rowid) REFERENCES t1(a)); + } +} {0 {}} +do_test fkey2-10.2.1 { + drop_all_tables + catchsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d, FOREIGN KEY(c) REFERENCES t1(rowid)); + INSERT INTO t1(rowid, a, b) VALUES(1, 1, 1); + INSERT INTO t2 VALUES(1, 1); + } +} {1 {foreign key mismatch - "t2" referencing "t1"}} +do_test fkey2-10.2.2 { + drop_all_tables + catchsql { + CREATE TABLE t1(rowid PRIMARY KEY, b); + CREATE TABLE t2(c, d, FOREIGN KEY(c) REFERENCES t1(rowid)); + INSERT INTO t1(rowid, b) VALUES(1, 1); + INSERT INTO t2 VALUES(1, 1); + } +} {0 {}} + + +#------------------------------------------------------------------------- +# The following tests, fkey2-11.*, test CASCADE actions. +# +drop_all_tables +do_test fkey2-11.1.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + CREATE TABLE t2(c, d, FOREIGN KEY(c) REFERENCES t1(a) ON UPDATE CASCADE); + + INSERT INTO t1 VALUES(10, 100); + INSERT INTO t2 VALUES(10, 100); + UPDATE t1 SET a = 15; + SELECT * FROM t2; + } +} {15 100} + +#------------------------------------------------------------------------- +# The following tests, fkey2-12.*, test RESTRICT actions. +# +drop_all_tables +do_test fkey2-12.1.1 { + execsql { + CREATE TABLE t1(a, b PRIMARY KEY); + CREATE TABLE t2( + x REFERENCES t1 ON UPDATE RESTRICT DEFERRABLE INITIALLY DEFERRED + ); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t1 VALUES(3, 'three'); + } +} {} +do_test fkey2-12.1.2 { + execsql "BEGIN" + execsql "INSERT INTO t2 VALUES('two')" +} {} +do_test fkey2-12.1.3 { + execsql "UPDATE t1 SET b = 'four' WHERE b = 'one'" +} {} +do_test fkey2-12.1.4 { + catchsql "UPDATE t1 SET b = 'five' WHERE b = 'two'" +} {1 {foreign key constraint failed}} +do_test fkey2-12.1.5 { + execsql "DELETE FROM t1 WHERE b = 'two'" +} {} +do_test fkey2-12.1.6 { + catchsql "COMMIT" +} {1 {foreign key constraint failed}} +do_test fkey2-12.1.7 { + execsql { + INSERT INTO t1 VALUES(2, 'two'); + COMMIT; + } +} {} + +drop_all_tables +do_test fkey2-12.2.1 { + execsql { + CREATE TABLE t1(x COLLATE NOCASE PRIMARY KEY); + CREATE TRIGGER tt1 AFTER DELETE ON t1 + WHEN EXISTS ( SELECT 1 FROM t2 WHERE old.x = y ) + BEGIN + INSERT INTO t1 VALUES(old.x); + END; + CREATE TABLE t2(y REFERENCES t1); + INSERT INTO t1 VALUES('A'); + INSERT INTO t1 VALUES('B'); + INSERT INTO t2 VALUES('a'); + INSERT INTO t2 VALUES('b'); + + SELECT * FROM t1; + SELECT * FROM t2; + } +} {A B a b} +do_test fkey2-12.2.2 { + execsql { DELETE FROM t1 } + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + } +} {A B a b} +do_test fkey2-12.2.3 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(y REFERENCES t1 ON DELETE RESTRICT); + INSERT INTO t2 VALUES('a'); + INSERT INTO t2 VALUES('b'); + } + catchsql { DELETE FROM t1 } +} {1 {foreign key constraint failed}} +do_test fkey2-12.2.4 { + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + } +} {A B a b} + +drop_all_tables +do_test fkey2-12.3.1 { + execsql { + CREATE TABLE up( + c00, c01, c02, c03, c04, c05, c06, c07, c08, c09, + c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, + c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, + c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, + PRIMARY KEY(c34, c35) + ); + CREATE TABLE down( + c00, c01, c02, c03, c04, c05, c06, c07, c08, c09, + c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, + c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, + c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, + FOREIGN KEY(c39, c38) REFERENCES up ON UPDATE CASCADE + ); + } +} {} +do_test fkey2-12.3.2 { + execsql { + INSERT INTO up(c34, c35) VALUES('yes', 'no'); + INSERT INTO down(c39, c38) VALUES('yes', 'no'); + UPDATE up SET c34 = 'possibly'; + SELECT c38, c39 FROM down; + DELETE FROM down; + } +} {no possibly} +do_test fkey2-12.3.3 { + catchsql { INSERT INTO down(c39, c38) VALUES('yes', 'no') } +} {1 {foreign key constraint failed}} +do_test fkey2-12.3.4 { + execsql { + INSERT INTO up(c34, c35) VALUES('yes', 'no'); + INSERT INTO down(c39, c38) VALUES('yes', 'no'); + } + catchsql { DELETE FROM up WHERE c34 = 'yes' } +} {1 {foreign key constraint failed}} +do_test fkey2-12.3.5 { + execsql { + DELETE FROM up WHERE c34 = 'possibly'; + SELECT c34, c35 FROM up; + SELECT c39, c38 FROM down; + } +} {yes no yes no} + +#------------------------------------------------------------------------- +# The following tests, fkey2-13.*, test that FK processing is performed +# when rows are REPLACEd. +# +drop_all_tables +do_test fkey2-13.1.1 { + execsql { + CREATE TABLE pp(a UNIQUE, b, c, PRIMARY KEY(b, c)); + CREATE TABLE cc(d, e, f UNIQUE, FOREIGN KEY(d, e) REFERENCES pp); + INSERT INTO pp VALUES(1, 2, 3); + INSERT INTO cc VALUES(2, 3, 1); + } +} {} +foreach {tn stmt} { + 1 "REPLACE INTO pp VALUES(1, 4, 5)" + 2 "REPLACE INTO pp(rowid, a, b, c) VALUES(1, 2, 3, 4)" +} { + do_test fkey2-13.1.$tn.1 { + catchsql $stmt + } {1 {foreign key constraint failed}} + do_test fkey2-13.1.$tn.2 { + execsql { + SELECT * FROM pp; + SELECT * FROM cc; + } + } {1 2 3 2 3 1} + do_test fkey2-13.1.$tn.3 { + execsql BEGIN; + catchsql $stmt + } {1 {foreign key constraint failed}} + do_test fkey2-13.1.$tn.4 { + execsql { + COMMIT; + SELECT * FROM pp; + SELECT * FROM cc; + } + } {1 2 3 2 3 1} +} +do_test fkey2-13.1.3 { + execsql { + REPLACE INTO pp(rowid, a, b, c) VALUES(1, 2, 2, 3); + SELECT rowid, * FROM pp; + SELECT * FROM cc; + } +} {1 2 2 3 2 3 1} +do_test fkey2-13.1.4 { + execsql { + REPLACE INTO pp(rowid, a, b, c) VALUES(2, 2, 2, 3); + SELECT rowid, * FROM pp; + SELECT * FROM cc; + } +} {2 2 2 3 2 3 1} + +#------------------------------------------------------------------------- +# The following tests, fkey2-14.*, test that the "DROP TABLE" and "ALTER +# TABLE" commands work as expected wrt foreign key constraints. +# +# fkey2-14.1*: ALTER TABLE ADD COLUMN +# fkey2-14.2*: ALTER TABLE RENAME TABLE +# fkey2-14.3*: DROP TABLE +# +drop_all_tables +ifcapable altertable { + do_test fkey2-14.1.1 { + # Adding a column with a REFERENCES clause is not supported. + execsql { + CREATE TABLE t1(a PRIMARY KEY); + CREATE TABLE t2(a, b); + } + catchsql { ALTER TABLE t2 ADD COLUMN c REFERENCES t1 } + } {0 {}} + do_test fkey2-14.1.2 { + catchsql { ALTER TABLE t2 ADD COLUMN d DEFAULT NULL REFERENCES t1 } + } {0 {}} + do_test fkey2-14.1.3 { + catchsql { ALTER TABLE t2 ADD COLUMN e REFERENCES t1 DEFAULT NULL} + } {0 {}} + do_test fkey2-14.1.4 { + catchsql { ALTER TABLE t2 ADD COLUMN f REFERENCES t1 DEFAULT 'text'} + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test fkey2-14.1.5 { + catchsql { ALTER TABLE t2 ADD COLUMN g DEFAULT CURRENT_TIME REFERENCES t1 } + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test fkey2-14.1.6 { + execsql { + PRAGMA foreign_keys = off; + ALTER TABLE t2 ADD COLUMN h DEFAULT 'text' REFERENCES t1; + PRAGMA foreign_keys = on; + SELECT sql FROM sqlite_master WHERE name='t2'; + } + } {{CREATE TABLE t2(a, b, c REFERENCES t1, d DEFAULT NULL REFERENCES t1, e REFERENCES t1 DEFAULT NULL, h DEFAULT 'text' REFERENCES t1)}} + + + # Test the sqlite_rename_parent() function directly. + # + proc test_rename_parent {zCreate zOld zNew} { + db eval {SELECT sqlite_rename_parent($zCreate, $zOld, $zNew)} + } + do_test fkey2-14.2.1.1 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + do_test fkey2-14.2.1.2 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t4 t3 + } {{CREATE TABLE t1(a REFERENCES t2)}} + do_test fkey2-14.2.1.3 { + test_rename_parent {CREATE TABLE t1(a REFERENCES "t2")} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + + # Test ALTER TABLE RENAME TABLE a bit. + # + do_test fkey2-14.2.2.1 { + drop_all_tables + execsql { + CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1); + CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2); + CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1); + } + execsql { SELECT sql FROM sqlite_master WHERE type = 'table'} + } [list \ + {CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1)} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2)} \ + {CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1)} \ + ] + do_test fkey2-14.2.2.2 { + execsql { ALTER TABLE t1 RENAME TO t4 } + execsql { SELECT sql FROM sqlite_master WHERE type = 'table'} + } [list \ + {CREATE TABLE "t4"(a PRIMARY KEY, b REFERENCES "t4")} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES "t4", c REFERENCES t2)} \ + {CREATE TABLE t3(a REFERENCES "t4", b REFERENCES t2, c REFERENCES "t4")} \ + ] + do_test fkey2-14.2.2.3 { + catchsql { INSERT INTO t3 VALUES(1, 2, 3) } + } {1 {foreign key constraint failed}} + do_test fkey2-14.2.2.4 { + execsql { INSERT INTO t4 VALUES(1, NULL) } + } {} + do_test fkey2-14.2.2.5 { + catchsql { UPDATE t4 SET b = 5 } + } {1 {foreign key constraint failed}} + do_test fkey2-14.2.2.6 { + catchsql { UPDATE t4 SET b = 1 } + } {0 {}} + do_test fkey2-14.2.2.7 { + execsql { INSERT INTO t3 VALUES(1, NULL, 1) } + } {} + + # Repeat for TEMP tables + # + drop_all_tables + do_test fkey2-14.1tmp.1 { + # Adding a column with a REFERENCES clause is not supported. + execsql { + CREATE TEMP TABLE t1(a PRIMARY KEY); + CREATE TEMP TABLE t2(a, b); + } + catchsql { ALTER TABLE t2 ADD COLUMN c REFERENCES t1 } + } {0 {}} + do_test fkey2-14.1tmp.2 { + catchsql { ALTER TABLE t2 ADD COLUMN d DEFAULT NULL REFERENCES t1 } + } {0 {}} + do_test fkey2-14.1tmp.3 { + catchsql { ALTER TABLE t2 ADD COLUMN e REFERENCES t1 DEFAULT NULL} + } {0 {}} + do_test fkey2-14.1tmp.4 { + catchsql { ALTER TABLE t2 ADD COLUMN f REFERENCES t1 DEFAULT 'text'} + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test fkey2-14.1tmp.5 { + catchsql { ALTER TABLE t2 ADD COLUMN g DEFAULT CURRENT_TIME REFERENCES t1 } + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test fkey2-14.1tmp.6 { + execsql { + PRAGMA foreign_keys = off; + ALTER TABLE t2 ADD COLUMN h DEFAULT 'text' REFERENCES t1; + PRAGMA foreign_keys = on; + SELECT sql FROM sqlite_temp_master WHERE name='t2'; + } + } {{CREATE TABLE t2(a, b, c REFERENCES t1, d DEFAULT NULL REFERENCES t1, e REFERENCES t1 DEFAULT NULL, h DEFAULT 'text' REFERENCES t1)}} + + do_test fkey2-14.2tmp.1.1 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + do_test fkey2-14.2tmp.1.2 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t4 t3 + } {{CREATE TABLE t1(a REFERENCES t2)}} + do_test fkey2-14.2tmp.1.3 { + test_rename_parent {CREATE TABLE t1(a REFERENCES "t2")} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + + # Test ALTER TABLE RENAME TABLE a bit. + # + do_test fkey2-14.2tmp.2.1 { + drop_all_tables + execsql { + CREATE TEMP TABLE t1(a PRIMARY KEY, b REFERENCES t1); + CREATE TEMP TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2); + CREATE TEMP TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1); + } + execsql { SELECT sql FROM sqlite_temp_master WHERE type = 'table'} + } [list \ + {CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1)} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2)} \ + {CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1)} \ + ] + do_test fkey2-14.2tmp.2.2 { + execsql { ALTER TABLE t1 RENAME TO t4 } + execsql { SELECT sql FROM sqlite_temp_master WHERE type = 'table'} + } [list \ + {CREATE TABLE "t4"(a PRIMARY KEY, b REFERENCES "t4")} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES "t4", c REFERENCES t2)} \ + {CREATE TABLE t3(a REFERENCES "t4", b REFERENCES t2, c REFERENCES "t4")} \ + ] + do_test fkey2-14.2tmp.2.3 { + catchsql { INSERT INTO t3 VALUES(1, 2, 3) } + } {1 {foreign key constraint failed}} + do_test fkey2-14.2tmp.2.4 { + execsql { INSERT INTO t4 VALUES(1, NULL) } + } {} + do_test fkey2-14.2tmp.2.5 { + catchsql { UPDATE t4 SET b = 5 } + } {1 {foreign key constraint failed}} + do_test fkey2-14.2tmp.2.6 { + catchsql { UPDATE t4 SET b = 1 } + } {0 {}} + do_test fkey2-14.2tmp.2.7 { + execsql { INSERT INTO t3 VALUES(1, NULL, 1) } + } {} + + # Repeat for ATTACH-ed tables + # + drop_all_tables + do_test fkey2-14.1aux.1 { + # Adding a column with a REFERENCES clause is not supported. + execsql { + ATTACH ':memory:' AS aux; + CREATE TABLE aux.t1(a PRIMARY KEY); + CREATE TABLE aux.t2(a, b); + } + catchsql { ALTER TABLE t2 ADD COLUMN c REFERENCES t1 } + } {0 {}} + do_test fkey2-14.1aux.2 { + catchsql { ALTER TABLE t2 ADD COLUMN d DEFAULT NULL REFERENCES t1 } + } {0 {}} + do_test fkey2-14.1aux.3 { + catchsql { ALTER TABLE t2 ADD COLUMN e REFERENCES t1 DEFAULT NULL} + } {0 {}} + do_test fkey2-14.1aux.4 { + catchsql { ALTER TABLE t2 ADD COLUMN f REFERENCES t1 DEFAULT 'text'} + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test fkey2-14.1aux.5 { + catchsql { ALTER TABLE t2 ADD COLUMN g DEFAULT CURRENT_TIME REFERENCES t1 } + } {1 {Cannot add a REFERENCES column with non-NULL default value}} + do_test fkey2-14.1aux.6 { + execsql { + PRAGMA foreign_keys = off; + ALTER TABLE t2 ADD COLUMN h DEFAULT 'text' REFERENCES t1; + PRAGMA foreign_keys = on; + SELECT sql FROM aux.sqlite_master WHERE name='t2'; + } + } {{CREATE TABLE t2(a, b, c REFERENCES t1, d DEFAULT NULL REFERENCES t1, e REFERENCES t1 DEFAULT NULL, h DEFAULT 'text' REFERENCES t1)}} + + do_test fkey2-14.2aux.1.1 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + do_test fkey2-14.2aux.1.2 { + test_rename_parent {CREATE TABLE t1(a REFERENCES t2)} t4 t3 + } {{CREATE TABLE t1(a REFERENCES t2)}} + do_test fkey2-14.2aux.1.3 { + test_rename_parent {CREATE TABLE t1(a REFERENCES "t2")} t2 t3 + } {{CREATE TABLE t1(a REFERENCES "t3")}} + + # Test ALTER TABLE RENAME TABLE a bit. + # + do_test fkey2-14.2aux.2.1 { + drop_all_tables + execsql { + CREATE TABLE aux.t1(a PRIMARY KEY, b REFERENCES t1); + CREATE TABLE aux.t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2); + CREATE TABLE aux.t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1); + } + execsql { SELECT sql FROM aux.sqlite_master WHERE type = 'table'} + } [list \ + {CREATE TABLE t1(a PRIMARY KEY, b REFERENCES t1)} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES t1, c REFERENCES t2)} \ + {CREATE TABLE t3(a REFERENCES t1, b REFERENCES t2, c REFERENCES t1)} \ + ] + do_test fkey2-14.2aux.2.2 { + execsql { ALTER TABLE t1 RENAME TO t4 } + execsql { SELECT sql FROM aux.sqlite_master WHERE type = 'table'} + } [list \ + {CREATE TABLE "t4"(a PRIMARY KEY, b REFERENCES "t4")} \ + {CREATE TABLE t2(a PRIMARY KEY, b REFERENCES "t4", c REFERENCES t2)} \ + {CREATE TABLE t3(a REFERENCES "t4", b REFERENCES t2, c REFERENCES "t4")} \ + ] + do_test fkey2-14.2aux.2.3 { + catchsql { INSERT INTO t3 VALUES(1, 2, 3) } + } {1 {foreign key constraint failed}} + do_test fkey2-14.2aux.2.4 { + execsql { INSERT INTO t4 VALUES(1, NULL) } + } {} + do_test fkey2-14.2aux.2.5 { + catchsql { UPDATE t4 SET b = 5 } + } {1 {foreign key constraint failed}} + do_test fkey2-14.2aux.2.6 { + catchsql { UPDATE t4 SET b = 1 } + } {0 {}} + do_test fkey2-14.2aux.2.7 { + execsql { INSERT INTO t3 VALUES(1, NULL, 1) } + } {} +} + +do_test fkey-2.14.3.1 { + drop_all_tables + execsql { + CREATE TABLE t1(a, b REFERENCES nosuchtable); + DROP TABLE t1; + } +} {} +do_test fkey-2.14.3.2 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES('a', 1); + CREATE TABLE t2(x REFERENCES t1); + INSERT INTO t2 VALUES('a'); + } +} {} +do_test fkey-2.14.3.3 { + catchsql { DROP TABLE t1 } +} {1 {foreign key constraint failed}} +do_test fkey-2.14.3.4 { + execsql { + DELETE FROM t2; + DROP TABLE t1; + } +} {} +do_test fkey-2.14.3.4 { + catchsql { INSERT INTO t2 VALUES('x') } +} {1 {no such table: main.t1}} +do_test fkey-2.14.3.5 { + execsql { + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES('x'); + } + execsql { INSERT INTO t2 VALUES('x') } +} {} +do_test fkey-2.14.3.6 { + catchsql { DROP TABLE t1 } +} {1 {foreign key constraint failed}} +do_test fkey-2.14.3.7 { + execsql { + DROP TABLE t2; + DROP TABLE t1; + } +} {} +do_test fkey-2.14.3.8 { + execsql { + CREATE TABLE pp(x, y, PRIMARY KEY(x, y)); + CREATE TABLE cc(a, b, FOREIGN KEY(a, b) REFERENCES pp(x, z)); + } + catchsql { INSERT INTO cc VALUES(1, 2) } +} {1 {foreign key mismatch - "cc" referencing "pp"}} +do_test fkey-2.14.3.9 { + execsql { DROP TABLE cc } +} {} +do_test fkey-2.14.3.10 { + execsql { + CREATE TABLE cc(a, b, + FOREIGN KEY(a, b) REFERENCES pp DEFERRABLE INITIALLY DEFERRED + ); + } + execsql { + INSERT INTO pp VALUES('a', 'b'); + INSERT INTO cc VALUES('a', 'b'); + BEGIN; + DROP TABLE pp; + CREATE TABLE pp(a, b, c, PRIMARY KEY(b, c)); + INSERT INTO pp VALUES(1, 'a', 'b'); + COMMIT; + } +} {} +do_test fkey-2.14.3.11 { + execsql { + BEGIN; + DROP TABLE cc; + DROP TABLE pp; + COMMIT; + } +} {} +do_test fkey-2.14.3.12 { + execsql { + CREATE TABLE b1(a, b); + CREATE TABLE b2(a, b REFERENCES b1); + DROP TABLE b1; + } +} {} +do_test fkey-2.14.3.13 { + execsql { + CREATE TABLE b3(a, b REFERENCES b2 DEFERRABLE INITIALLY DEFERRED); + DROP TABLE b2; + } +} {} + +# Test that nothing goes wrong when dropping a table that refers to a view. +# Or dropping a view that an existing FK (incorrectly) refers to. Or either +# of the above scenarios with a virtual table. +drop_all_tables +do_test fkey-2.14.4.1 { + execsql { + CREATE TABLE t1(x REFERENCES v); + CREATE VIEW v AS SELECT * FROM t1; + } +} {} +do_test fkey-2.14.4.2 { + execsql { + DROP VIEW v; + } +} {} +ifcapable vtab { + register_echo_module db + do_test fkey-2.14.4.3 { + execsql { CREATE VIRTUAL TABLE v USING echo(t1) } + } {} + do_test fkey-2.14.4.2 { + execsql { + DROP TABLE v; + } + } {} +} + +#------------------------------------------------------------------------- +# The following tests, fkey2-15.*, test that unnecessary FK related scans +# and lookups are avoided when the constraint counters are zero. +# +drop_all_tables +proc execsqlS {zSql} { + set ::sqlite_search_count 0 + set ::sqlite_found_count 0 + set res [uplevel [list execsql $zSql]] + concat [expr $::sqlite_found_count + $::sqlite_search_count] $res +} +do_test fkey2-15.1.1 { + execsql { + CREATE TABLE pp(a PRIMARY KEY, b); + CREATE TABLE cc(x, y REFERENCES pp DEFERRABLE INITIALLY DEFERRED); + INSERT INTO pp VALUES(1, 'one'); + INSERT INTO pp VALUES(2, 'two'); + INSERT INTO cc VALUES('neung', 1); + INSERT INTO cc VALUES('song', 2); + } +} {} +do_test fkey2-15.1.2 { + execsqlS { INSERT INTO pp VALUES(3, 'three') } +} {0} +do_test fkey2-15.1.3 { + execsql { + BEGIN; + INSERT INTO cc VALUES('see', 4); -- Violates deferred constraint + } + execsqlS { INSERT INTO pp VALUES(5, 'five') } +} {2} +do_test fkey2-15.1.4 { + execsql { DELETE FROM cc WHERE x = 'see' } + execsqlS { INSERT INTO pp VALUES(6, 'six') } +} {0} +do_test fkey2-15.1.5 { + execsql COMMIT +} {} +do_test fkey2-15.1.6 { + execsql BEGIN + execsqlS { + DELETE FROM cc WHERE x = 'neung'; + ROLLBACK; + } +} {1} +do_test fkey2-15.1.7 { + execsql { + BEGIN; + DELETE FROM pp WHERE a = 2; + } + execsqlS { + DELETE FROM cc WHERE x = 'neung'; + ROLLBACK; + } +} {2} + +#------------------------------------------------------------------------- +# This next block of tests, fkey2-16.*, test that rows that refer to +# themselves may be inserted and deleted. +# +foreach {tn zSchema} { + 1 { CREATE TABLE self(a INTEGER PRIMARY KEY, b REFERENCES self(a)) } + 2 { CREATE TABLE self(a PRIMARY KEY, b REFERENCES self(a)) } + 3 { CREATE TABLE self(a UNIQUE, b INTEGER PRIMARY KEY REFERENCES self(a)) } +} { + drop_all_tables + do_test fkey2-16.1.$tn.1 { + execsql $zSchema + execsql { INSERT INTO self VALUES(13, 13) } + } {} + do_test fkey2-16.1.$tn.2 { + execsql { UPDATE self SET a = 14, b = 14 } + } {} + + do_test fkey2-16.1.$tn.3 { + catchsql { UPDATE self SET b = 15 } + } {1 {foreign key constraint failed}} + + do_test fkey2-16.1.$tn.4 { + catchsql { UPDATE self SET a = 15 } + } {1 {foreign key constraint failed}} + + do_test fkey2-16.1.$tn.5 { + catchsql { UPDATE self SET a = 15, b = 16 } + } {1 {foreign key constraint failed}} + + do_test fkey2-16.1.$tn.6 { + catchsql { UPDATE self SET a = 17, b = 17 } + } {0 {}} + + do_test fkey2-16.1.$tn.7 { + execsql { DELETE FROM self } + } {} + do_test fkey2-16.1.$tn.8 { + catchsql { INSERT INTO self VALUES(20, 21) } + } {1 {foreign key constraint failed}} +} + +#------------------------------------------------------------------------- +# This next block of tests, fkey2-17.*, tests that if "PRAGMA count_changes" +# is turned on statements that violate immediate FK constraints return +# SQLITE_CONSTRAINT immediately, not after returning a number of rows. +# Whereas statements that violate deferred FK constraints return the number +# of rows before failing. +# +# Also test that rows modified by FK actions are not counted in either the +# returned row count or the values returned by sqlite3_changes(). Like +# trigger related changes, they are included in sqlite3_total_changes() though. +# +drop_all_tables +do_test fkey2-17.1.1 { + execsql { PRAGMA count_changes = 1 } + execsql { + CREATE TABLE one(a, b, c, UNIQUE(b, c)); + CREATE TABLE two(d, e, f, FOREIGN KEY(e, f) REFERENCES one(b, c)); + INSERT INTO one VALUES(1, 2, 3); + } +} {1} +do_test fkey2-17.1.2 { + set STMT [sqlite3_prepare_v2 db "INSERT INTO two VALUES(4, 5, 6)" -1 dummy] + sqlite3_step $STMT +} {SQLITE_CONSTRAINT} +verify_ex_errcode fkey2-17.1.2b SQLITE_CONSTRAINT_FOREIGNKEY +ifcapable autoreset { + do_test fkey2-17.1.3 { + sqlite3_step $STMT + } {SQLITE_CONSTRAINT} + verify_ex_errcode fkey2-17.1.3b SQLITE_CONSTRAINT_FOREIGNKEY +} else { + do_test fkey2-17.1.3 { + sqlite3_step $STMT + } {SQLITE_MISUSE} +} +do_test fkey2-17.1.4 { + sqlite3_finalize $STMT +} {SQLITE_CONSTRAINT} +verify_ex_errcode fkey2-17.1.4b SQLITE_CONSTRAINT_FOREIGNKEY +do_test fkey2-17.1.5 { + execsql { + INSERT INTO one VALUES(2, 3, 4); + INSERT INTO one VALUES(3, 4, 5); + INSERT INTO two VALUES(1, 2, 3); + INSERT INTO two VALUES(2, 3, 4); + INSERT INTO two VALUES(3, 4, 5); + } +} {1 1 1 1 1} +do_test fkey2-17.1.6 { + catchsql { + BEGIN; + INSERT INTO one VALUES(0, 0, 0); + UPDATE two SET e=e+1, f=f+1; + } +} {1 {foreign key constraint failed}} +do_test fkey2-17.1.7 { + execsql { SELECT * FROM one } +} {1 2 3 2 3 4 3 4 5 0 0 0} +do_test fkey2-17.1.8 { + execsql { SELECT * FROM two } +} {1 2 3 2 3 4 3 4 5} +do_test fkey2-17.1.9 { + execsql COMMIT +} {} +do_test fkey2-17.1.10 { + execsql { + CREATE TABLE three( + g, h, i, + FOREIGN KEY(h, i) REFERENCES one(b, c) DEFERRABLE INITIALLY DEFERRED + ); + } +} {} +do_test fkey2-17.1.11 { + set STMT [sqlite3_prepare_v2 db "INSERT INTO three VALUES(7, 8, 9)" -1 dummy] + sqlite3_step $STMT +} {SQLITE_ROW} +do_test fkey2-17.1.12 { + sqlite3_column_text $STMT 0 +} {1} +do_test fkey2-17.1.13 { + sqlite3_step $STMT +} {SQLITE_CONSTRAINT} +verify_ex_errcode fkey2-17.1.13b SQLITE_CONSTRAINT_FOREIGNKEY +do_test fkey2-17.1.14 { + sqlite3_finalize $STMT +} {SQLITE_CONSTRAINT} +verify_ex_errcode fkey2-17.1.14b SQLITE_CONSTRAINT_FOREIGNKEY + +drop_all_tables +do_test fkey2-17.2.1 { + execsql { + CREATE TABLE high("a'b!" PRIMARY KEY, b); + CREATE TABLE low( + c, + "d&6" REFERENCES high ON UPDATE CASCADE ON DELETE CASCADE + ); + } +} {} +do_test fkey2-17.2.2 { + execsql { + INSERT INTO high VALUES('a', 'b'); + INSERT INTO low VALUES('b', 'a'); + } + db changes +} {1} +set nTotal [db total_changes] +do_test fkey2-17.2.3 { + execsql { UPDATE high SET "a'b!" = 'c' } +} {1} +do_test fkey2-17.2.4 { + db changes +} {1} +do_test fkey2-17.2.5 { + expr [db total_changes] - $nTotal +} {2} +do_test fkey2-17.2.6 { + execsql { SELECT * FROM high ; SELECT * FROM low } +} {c b b c} +do_test fkey2-17.2.7 { + execsql { DELETE FROM high } +} {1} +do_test fkey2-17.2.8 { + db changes +} {1} +do_test fkey2-17.2.9 { + expr [db total_changes] - $nTotal +} {4} +do_test fkey2-17.2.10 { + execsql { SELECT * FROM high ; SELECT * FROM low } +} {} +execsql { PRAGMA count_changes = 0 } + +#------------------------------------------------------------------------- +# Test that the authorization callback works. +# + +ifcapable auth { + do_test fkey2-18.1 { + execsql { + CREATE TABLE long(a, b PRIMARY KEY, c); + CREATE TABLE short(d, e, f REFERENCES long); + CREATE TABLE mid(g, h, i REFERENCES long DEFERRABLE INITIALLY DEFERRED); + } + } {} + + proc auth {args} {eval lappend ::authargs $args ; return SQLITE_OK} + db auth auth + + # An insert on the parent table must read the child key of any deferred + # foreign key constraints. But not the child key of immediate constraints. + set authargs {} + do_test fkey2-18.2 { + execsql { INSERT INTO long VALUES(1, 2, 3) } + set authargs + } {SQLITE_INSERT long {} main {} SQLITE_READ mid i main {}} + + # An insert on the child table of an immediate constraint must read the + # parent key columns (to see if it is a violation or not). + set authargs {} + do_test fkey2-18.3 { + execsql { INSERT INTO short VALUES(1, 3, 2) } + set authargs + } {SQLITE_INSERT short {} main {} SQLITE_READ long b main {}} + + # As must an insert on the child table of a deferred constraint. + set authargs {} + do_test fkey2-18.4 { + execsql { INSERT INTO mid VALUES(1, 3, 2) } + set authargs + } {SQLITE_INSERT mid {} main {} SQLITE_READ long b main {}} + + do_test fkey2-18.5 { + execsql { + CREATE TABLE nought(a, b PRIMARY KEY, c); + CREATE TABLE cross(d, e, f, + FOREIGN KEY(e) REFERENCES nought(b) ON UPDATE CASCADE + ); + } + execsql { INSERT INTO nought VALUES(2, 1, 2) } + execsql { INSERT INTO cross VALUES(0, 1, 0) } + set authargs [list] + execsql { UPDATE nought SET b = 5 } + set authargs + } {SQLITE_UPDATE nought b main {} SQLITE_READ cross e main {} SQLITE_READ cross e main {} SQLITE_READ nought b main {} SQLITE_READ nought b main {} SQLITE_READ nought b main {} SQLITE_UPDATE cross e main {} SQLITE_READ nought b main {} SQLITE_READ cross e main {} SQLITE_READ nought b main {} SQLITE_READ nought b main {}} + + do_test fkey2-18.6 { + execsql {SELECT * FROM cross} + } {0 5 0} + + do_test fkey2-18.7 { + execsql { + CREATE TABLE one(a INTEGER PRIMARY KEY, b); + CREATE TABLE two(b, c REFERENCES one); + INSERT INTO one VALUES(101, 102); + } + set authargs [list] + execsql { INSERT INTO two VALUES(100, 101); } + set authargs + } {SQLITE_INSERT two {} main {} SQLITE_READ one a main {}} + + # Return SQLITE_IGNORE to requests to read from the parent table. This + # causes inserts of non-NULL keys into the child table to fail. + # + rename auth {} + proc auth {args} { + if {[lindex $args 1] == "long"} {return SQLITE_IGNORE} + return SQLITE_OK + } + do_test fkey2-18.8 { + catchsql { INSERT INTO short VALUES(1, 3, 2) } + } {1 {foreign key constraint failed}} + do_test fkey2-18.9 { + execsql { INSERT INTO short VALUES(1, 3, NULL) } + } {} + do_test fkey2-18.10 { + execsql { SELECT * FROM short } + } {1 3 2 1 3 {}} + do_test fkey2-18.11 { + catchsql { UPDATE short SET f = 2 WHERE f IS NULL } + } {1 {foreign key constraint failed}} + + db auth {} + unset authargs +} + + +do_test fkey2-19.1 { + execsql { + CREATE TABLE main(id INTEGER PRIMARY KEY); + CREATE TABLE sub(id INT REFERENCES main(id)); + INSERT INTO main VALUES(1); + INSERT INTO main VALUES(2); + INSERT INTO sub VALUES(2); + } +} {} +do_test fkey2-19.2 { + set S [sqlite3_prepare_v2 db "DELETE FROM main WHERE id = ?" -1 dummy] + sqlite3_bind_int $S 1 2 + sqlite3_step $S +} {SQLITE_CONSTRAINT} +verify_ex_errcode fkey2-19.2b SQLITE_CONSTRAINT_FOREIGNKEY +do_test fkey2-19.3 { + sqlite3_reset $S +} {SQLITE_CONSTRAINT} +verify_ex_errcode fkey2-19.3b SQLITE_CONSTRAINT_FOREIGNKEY +do_test fkey2-19.4 { + sqlite3_bind_int $S 1 1 + sqlite3_step $S +} {SQLITE_DONE} +do_test fkey2-19.4 { + sqlite3_finalize $S +} {SQLITE_OK} + +drop_all_tables +do_test fkey2-20.1 { + execsql { + CREATE TABLE pp(a PRIMARY KEY, b); + CREATE TABLE cc(c PRIMARY KEY, d REFERENCES pp); + } +} {} + +foreach {tn insert} { + 1 "INSERT" + 2 "INSERT OR IGNORE" + 3 "INSERT OR ABORT" + 4 "INSERT OR ROLLBACK" + 5 "INSERT OR REPLACE" + 6 "INSERT OR FAIL" +} { + do_test fkey2-20.2.$tn.1 { + catchsql "$insert INTO cc VALUES(1, 2)" + } {1 {foreign key constraint failed}} + do_test fkey2-20.2.$tn.2 { + execsql { SELECT * FROM cc } + } {} + do_test fkey2-20.2.$tn.3 { + execsql { + BEGIN; + INSERT INTO pp VALUES(2, 'two'); + INSERT INTO cc VALUES(1, 2); + } + catchsql "$insert INTO cc VALUES(3, 4)" + } {1 {foreign key constraint failed}} + do_test fkey2-20.2.$tn.4 { + execsql { COMMIT ; SELECT * FROM cc } + } {1 2} + do_test fkey2-20.2.$tn.5 { + execsql { DELETE FROM cc ; DELETE FROM pp } + } {} +} + +foreach {tn update} { + 1 "UPDATE" + 2 "UPDATE OR IGNORE" + 3 "UPDATE OR ABORT" + 4 "UPDATE OR ROLLBACK" + 5 "UPDATE OR REPLACE" + 6 "UPDATE OR FAIL" +} { + do_test fkey2-20.3.$tn.1 { + execsql { + INSERT INTO pp VALUES(2, 'two'); + INSERT INTO cc VALUES(1, 2); + } + } {} + do_test fkey2-20.3.$tn.2 { + catchsql "$update pp SET a = 1" + } {1 {foreign key constraint failed}} + do_test fkey2-20.3.$tn.3 { + execsql { SELECT * FROM pp } + } {2 two} + do_test fkey2-20.3.$tn.4 { + catchsql "$update cc SET d = 1" + } {1 {foreign key constraint failed}} + do_test fkey2-20.3.$tn.5 { + execsql { SELECT * FROM cc } + } {1 2} + do_test fkey2-20.3.$tn.6 { + execsql { + BEGIN; + INSERT INTO pp VALUES(3, 'three'); + } + catchsql "$update pp SET a = 1 WHERE a = 2" + } {1 {foreign key constraint failed}} + do_test fkey2-20.3.$tn.7 { + execsql { COMMIT ; SELECT * FROM pp } + } {2 two 3 three} + do_test fkey2-20.3.$tn.8 { + execsql { + BEGIN; + INSERT INTO cc VALUES(2, 2); + } + catchsql "$update cc SET d = 1 WHERE c = 1" + } {1 {foreign key constraint failed}} + do_test fkey2-20.3.$tn.9 { + execsql { COMMIT ; SELECT * FROM cc } + } {1 2 2 2} + do_test fkey2-20.3.$tn.10 { + execsql { DELETE FROM cc ; DELETE FROM pp } + } {} +} + +#------------------------------------------------------------------------- +# The following block of tests, those prefixed with "fkey2-genfkey.", are +# the same tests that were used to test the ".genfkey" command provided +# by the shell tool. So these tests show that the built-in foreign key +# implementation is more or less compatible with the triggers generated +# by genfkey. +# +drop_all_tables +do_test fkey2-genfkey.1.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c)); + CREATE TABLE t2(e REFERENCES t1, f); + CREATE TABLE t3(g, h, i, FOREIGN KEY (h, i) REFERENCES t1(b, c)); + } +} {} +do_test fkey2-genfkey.1.2 { + catchsql { INSERT INTO t2 VALUES(1, 2) } +} {1 {foreign key constraint failed}} +do_test fkey2-genfkey.1.3 { + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t2 VALUES(1, 2); + } +} {} +do_test fkey2-genfkey.1.4 { + execsql { INSERT INTO t2 VALUES(NULL, 3) } +} {} +do_test fkey2-genfkey.1.5 { + catchsql { UPDATE t2 SET e = 5 WHERE e IS NULL } +} {1 {foreign key constraint failed}} +do_test fkey2-genfkey.1.6 { + execsql { UPDATE t2 SET e = 1 WHERE e IS NULL } +} {} +do_test fkey2-genfkey.1.7 { + execsql { UPDATE t2 SET e = NULL WHERE f = 3 } +} {} +do_test fkey2-genfkey.1.8 { + catchsql { UPDATE t1 SET a = 10 } +} {1 {foreign key constraint failed}} +do_test fkey2-genfkey.1.9 { + catchsql { UPDATE t1 SET a = NULL } +} {1 {datatype mismatch}} +do_test fkey2-genfkey.1.10 { + catchsql { DELETE FROM t1 } +} {1 {foreign key constraint failed}} +do_test fkey2-genfkey.1.11 { + execsql { UPDATE t2 SET e = NULL } +} {} +do_test fkey2-genfkey.1.12 { + execsql { + UPDATE t1 SET a = 10; + DELETE FROM t1; + DELETE FROM t2; + } +} {} +do_test fkey2-genfkey.1.13 { + execsql { + INSERT INTO t3 VALUES(1, NULL, NULL); + INSERT INTO t3 VALUES(1, 2, NULL); + INSERT INTO t3 VALUES(1, NULL, 3); + } +} {} +do_test fkey2-genfkey.1.14 { + catchsql { INSERT INTO t3 VALUES(3, 1, 4) } +} {1 {foreign key constraint failed}} +do_test fkey2-genfkey.1.15 { + execsql { + INSERT INTO t1 VALUES(1, 1, 4); + INSERT INTO t3 VALUES(3, 1, 4); + } +} {} +do_test fkey2-genfkey.1.16 { + catchsql { DELETE FROM t1 } +} {1 {foreign key constraint failed}} +do_test fkey2-genfkey.1.17 { + catchsql { UPDATE t1 SET b = 10} +} {1 {foreign key constraint failed}} +do_test fkey2-genfkey.1.18 { + execsql { UPDATE t1 SET a = 10} +} {} +do_test fkey2-genfkey.1.19 { + catchsql { UPDATE t3 SET h = 'hello' WHERE i = 3} +} {1 {foreign key constraint failed}} + +drop_all_tables +do_test fkey2-genfkey.2.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c)); + CREATE TABLE t2(e REFERENCES t1 ON UPDATE CASCADE ON DELETE CASCADE, f); + CREATE TABLE t3(g, h, i, + FOREIGN KEY (h, i) + REFERENCES t1(b, c) ON UPDATE CASCADE ON DELETE CASCADE + ); + } +} {} +do_test fkey2-genfkey.2.2 { + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + INSERT INTO t2 VALUES(1, 'one'); + INSERT INTO t2 VALUES(4, 'four'); + } +} {} +do_test fkey2-genfkey.2.3 { + execsql { + UPDATE t1 SET a = 2 WHERE a = 1; + SELECT * FROM t2; + } +} {2 one 4 four} +do_test fkey2-genfkey.2.4 { + execsql { + DELETE FROM t1 WHERE a = 4; + SELECT * FROM t2; + } +} {2 one} + +do_test fkey2-genfkey.2.5 { + execsql { + INSERT INTO t3 VALUES('hello', 2, 3); + UPDATE t1 SET c = 2; + SELECT * FROM t3; + } +} {hello 2 2} +do_test fkey2-genfkey.2.6 { + execsql { + DELETE FROM t1; + SELECT * FROM t3; + } +} {} + +drop_all_tables +do_test fkey2-genfkey.3.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(c, b)); + CREATE TABLE t2(e REFERENCES t1 ON UPDATE SET NULL ON DELETE SET NULL, f); + CREATE TABLE t3(g, h, i, + FOREIGN KEY (h, i) + REFERENCES t1(b, c) ON UPDATE SET NULL ON DELETE SET NULL + ); + } +} {} +do_test fkey2-genfkey.3.2 { + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + INSERT INTO t2 VALUES(1, 'one'); + INSERT INTO t2 VALUES(4, 'four'); + } +} {} +do_test fkey2-genfkey.3.3 { + execsql { + UPDATE t1 SET a = 2 WHERE a = 1; + SELECT * FROM t2; + } +} {{} one 4 four} +do_test fkey2-genfkey.3.4 { + execsql { + DELETE FROM t1 WHERE a = 4; + SELECT * FROM t2; + } +} {{} one {} four} +do_test fkey2-genfkey.3.5 { + execsql { + INSERT INTO t3 VALUES('hello', 2, 3); + UPDATE t1 SET c = 2; + SELECT * FROM t3; + } +} {hello {} {}} +do_test fkey2-genfkey.3.6 { + execsql { + UPDATE t3 SET h = 2, i = 2; + DELETE FROM t1; + SELECT * FROM t3; + } +} {hello {} {}} + +#------------------------------------------------------------------------- +# Verify that ticket dd08e5a988d00decc4a543daa8dbbfab9c577ad8 has been +# fixed. +# +do_test fkey2-dd08e5.1.1 { + execsql { + PRAGMA foreign_keys=ON; + CREATE TABLE tdd08(a INTEGER PRIMARY KEY, b); + CREATE UNIQUE INDEX idd08 ON tdd08(a,b); + INSERT INTO tdd08 VALUES(200,300); + + CREATE TABLE tdd08_b(w,x,y, FOREIGN KEY(x,y) REFERENCES tdd08(a,b)); + INSERT INTO tdd08_b VALUES(100,200,300); + } +} {} +do_test fkey2-dd08e5.1.2 { + catchsql { + DELETE FROM tdd08; + } +} {1 {foreign key constraint failed}} +do_test fkey2-dd08e5.1.3 { + execsql { + SELECT * FROM tdd08; + } +} {200 300} +do_test fkey2-dd08e5.1.4 { + catchsql { + INSERT INTO tdd08_b VALUES(400,500,300); + } +} {1 {foreign key constraint failed}} +do_test fkey2-dd08e5.1.5 { + catchsql { + UPDATE tdd08_b SET x=x+1; + } +} {1 {foreign key constraint failed}} +do_test fkey2-dd08e5.1.6 { + catchsql { + UPDATE tdd08 SET a=a+1; + } +} {1 {foreign key constraint failed}} + +#------------------------------------------------------------------------- +# Verify that ticket ce7c133ea6cc9ccdc1a60d80441f80b6180f5eba +# fixed. +# +do_test fkey2-ce7c13.1.1 { + execsql { + CREATE TABLE tce71(a INTEGER PRIMARY KEY, b); + CREATE UNIQUE INDEX ice71 ON tce71(a,b); + INSERT INTO tce71 VALUES(100,200); + CREATE TABLE tce72(w, x, y, FOREIGN KEY(x,y) REFERENCES tce71(a,b)); + INSERT INTO tce72 VALUES(300,100,200); + UPDATE tce71 set b = 200 where a = 100; + SELECT * FROM tce71, tce72; + } +} {100 200 300 100 200} +do_test fkey2-ce7c13.1.2 { + catchsql { + UPDATE tce71 set b = 201 where a = 100; + } +} {1 {foreign key constraint failed}} +do_test fkey2-ce7c13.1.3 { + catchsql { + UPDATE tce71 set a = 101 where a = 100; + } +} {1 {foreign key constraint failed}} +do_test fkey2-ce7c13.1.4 { + execsql { + CREATE TABLE tce73(a INTEGER PRIMARY KEY, b, UNIQUE(a,b)); + INSERT INTO tce73 VALUES(100,200); + CREATE TABLE tce74(w, x, y, FOREIGN KEY(x,y) REFERENCES tce73(a,b)); + INSERT INTO tce74 VALUES(300,100,200); + UPDATE tce73 set b = 200 where a = 100; + SELECT * FROM tce73, tce74; + } +} {100 200 300 100 200} +do_test fkey2-ce7c13.1.5 { + catchsql { + UPDATE tce73 set b = 201 where a = 100; + } +} {1 {foreign key constraint failed}} +do_test fkey2-ce7c13.1.6 { + catchsql { + UPDATE tce73 set a = 101 where a = 100; + } +} {1 {foreign key constraint failed}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fkey3.test b/components/external/SQLite-3.8.1/test/fkey3.test new file mode 100644 index 0000000000000000000000000000000000000000..6a11f8883ec74c60a8d9f8130c97981a2041af33 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fkey3.test @@ -0,0 +1,186 @@ +# 2009 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for foreign keys. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!foreignkey||!trigger} { + finish_test + return +} + +set testprefix fkey3 + +# Create a table and some data to work with. +# +do_test fkey3-1.1 { + execsql { + PRAGMA foreign_keys=ON; + CREATE TABLE t1(x INTEGER PRIMARY KEY); + INSERT INTO t1 VALUES(100); + INSERT INTO t1 VALUES(101); + CREATE TABLE t2(y INTEGER REFERENCES t1 (x)); + INSERT INTO t2 VALUES(100); + INSERT INTO t2 VALUES(101); + SELECT 1, x FROM t1; + SELECT 2, y FROM t2; + } +} {1 100 1 101 2 100 2 101} + +do_test fkey3-1.2 { + catchsql { + DELETE FROM t1 WHERE x=100; + } +} {1 {foreign key constraint failed}} + +do_test fkey3-1.3 { + catchsql { + DROP TABLE t1; + } +} {1 {foreign key constraint failed}} + +do_test fkey3-1.4 { + execsql { + DROP TABLE t2; + } +} {} + +do_test fkey3-1.5 { + execsql { + DROP TABLE t1; + } +} {} + +do_test fkey3-2.1 { + execsql { + PRAGMA foreign_keys=ON; + CREATE TABLE t1(x INTEGER PRIMARY KEY); + INSERT INTO t1 VALUES(100); + INSERT INTO t1 VALUES(101); + CREATE TABLE t2(y INTEGER PRIMARY KEY REFERENCES t1 (x) ON UPDATE SET NULL); + } + execsql { + INSERT INTO t2 VALUES(100); + INSERT INTO t2 VALUES(101); + SELECT 1, x FROM t1; + SELECT 2, y FROM t2; + } +} {1 100 1 101 2 100 2 101} + + +#------------------------------------------------------------------------- +# The following tests - fkey-3.* - test some edge cases to do with +# inserting rows into tables that have foreign keys where the parent +# table is the same as the child table. Especially cases where the +# new row being inserted matches itself. +# +do_execsql_test 3.1.1 { + CREATE TABLE t3(a, b, c, d, + UNIQUE(a, b), + FOREIGN KEY(c, d) REFERENCES t3(a, b) + ); + INSERT INTO t3 VALUES(1, 2, 1, 2); +} {} +do_catchsql_test 3.1.2 { + INSERT INTO t3 VALUES(NULL, 2, 5, 2); +} {1 {foreign key constraint failed}} +do_catchsql_test 3.1.3 { + INSERT INTO t3 VALUES(NULL, 3, 5, 2); +} {1 {foreign key constraint failed}} + +do_execsql_test 3.2.1 { + CREATE TABLE t4(a UNIQUE, b REFERENCES t4(a)); +} +do_catchsql_test 3.2.2 { + INSERT INTO t4 VALUES(NULL, 1); +} {1 {foreign key constraint failed}} + +do_execsql_test 3.3.1 { + CREATE TABLE t5(a INTEGER PRIMARY KEY, b REFERENCES t5(a)); + INSERT INTO t5 VALUES(NULL, 1); +} {} +do_catchsql_test 3.3.2 { + INSERT INTO t5 VALUES(NULL, 3); +} {1 {foreign key constraint failed}} + +do_execsql_test 3.4.1 { + CREATE TABLE t6(a INTEGER PRIMARY KEY, b, c, d, + FOREIGN KEY(c, d) REFERENCES t6(a, b) + ); + CREATE UNIQUE INDEX t6i ON t6(b, a); +} +do_execsql_test 3.4.2 { INSERT INTO t6 VALUES(NULL, 'a', 1, 'a'); } {} +do_execsql_test 3.4.3 { INSERT INTO t6 VALUES(2, 'a', 2, 'a'); } {} +do_execsql_test 3.4.4 { INSERT INTO t6 VALUES(NULL, 'a', 1, 'a'); } {} +do_execsql_test 3.4.5 { INSERT INTO t6 VALUES(5, 'a', 2, 'a'); } {} +do_catchsql_test 3.4.6 { + INSERT INTO t6 VALUES(NULL, 'a', 65, 'a'); +} {1 {foreign key constraint failed}} + +do_execsql_test 3.4.7 { + INSERT INTO t6 VALUES(100, 'one', 100, 'one'); + DELETE FROM t6 WHERE a = 100; +} +do_execsql_test 3.4.8 { + INSERT INTO t6 VALUES(100, 'one', 100, 'one'); + UPDATE t6 SET c = 1, d = 'a' WHERE a = 100; + DELETE FROM t6 WHERE a = 100; +} + +do_execsql_test 3.5.1 { + CREATE TABLE t7(a, b, c, d INTEGER PRIMARY KEY, + FOREIGN KEY(c, d) REFERENCES t7(a, b) + ); + CREATE UNIQUE INDEX t7i ON t7(a, b); +} +do_execsql_test 3.5.2 { INSERT INTO t7 VALUES('x', 1, 'x', NULL) } {} +do_execsql_test 3.5.3 { INSERT INTO t7 VALUES('x', 2, 'x', 2) } {} +do_catchsql_test 3.5.4 { + INSERT INTO t7 VALUES('x', 450, 'x', NULL); +} {1 {foreign key constraint failed}} +do_catchsql_test 3.5.5 { + INSERT INTO t7 VALUES('x', 450, 'x', 451); +} {1 {foreign key constraint failed}} + + +do_execsql_test 3.6.1 { + CREATE TABLE t8(a, b, c, d, e, FOREIGN KEY(c, d) REFERENCES t8(a, b)); + CREATE UNIQUE INDEX t8i1 ON t8(a, b); + CREATE UNIQUE INDEX t8i2 ON t8(c); + INSERT INTO t8 VALUES(1, 1, 1, 1, 1); +} +do_catchsql_test 3.6.2 { + UPDATE t8 SET d = 2; +} {1 {foreign key constraint failed}} +do_execsql_test 3.6.3 { UPDATE t8 SET d = 1; } +do_execsql_test 3.6.4 { UPDATE t8 SET e = 2; } + +do_catchsql_test 3.6.5 { + CREATE TABLE TestTable ( + id INTEGER PRIMARY KEY, + name text, + source_id integer not null, + parent_id integer, + + foreign key(source_id, parent_id) references TestTable(source_id, id) + ); + CREATE UNIQUE INDEX testindex on TestTable(source_id, id); + PRAGMA foreign_keys=1; + INSERT INTO TestTable VALUES (1, 'parent', 1, null); + INSERT INTO TestTable VALUES (2, 'child', 1, 1); + UPDATE TestTable SET parent_id=1000 where id=2; +} {1 {foreign key constraint failed}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fkey4.test b/components/external/SQLite-3.8.1/test/fkey4.test new file mode 100644 index 0000000000000000000000000000000000000000..79cf663478f0cbf722a5a976e09c2a2f540603f3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fkey4.test @@ -0,0 +1,57 @@ +# 2011 Feb 04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file test deferred foreign key constraint processing to make +# sure that when a statement not within BEGIN...END fails a constraint, +# that statement doesn't hold the transaction open thus allowing +# a subsequent statement to fail a deferred constraint with impunity. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!foreignkey||!trigger} { + finish_test + return +} + +# Create a table and some data to work with. +# +do_test fkey4-1.1 { + execsql { + PRAGMA foreign_keys = ON; + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TABLE t2(c REFERENCES t1 DEFERRABLE INITIALLY DEFERRED, d); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(1,3); + } +} {} + +do_test fkey4-1.2 { + set ::DB [sqlite3_connection_pointer db] + set ::SQL {INSERT INTO t2 VALUES(2,4)} + set ::STMT1 [sqlite3_prepare_v2 $::DB $::SQL -1 TAIL] + sqlite3_step $::STMT1 +} {SQLITE_CONSTRAINT} +verify_ex_errcode fkey4-1.2b SQLITE_CONSTRAINT_FOREIGNKEY +do_test fkey4-1.3 { + set ::STMT2 [sqlite3_prepare_v2 $::DB $::SQL -1 TAIL] + sqlite3_step $::STMT2 +} {SQLITE_CONSTRAINT} +verify_ex_errcode fkey4-1.3b SQLITE_CONSTRAINT_FOREIGNKEY +do_test fkey4-1.4 { + db eval {SELECT * FROM t2} +} {1 3} +sqlite3_finalize $::STMT1 +sqlite3_finalize $::STMT2 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fkey5.test b/components/external/SQLite-3.8.1/test/fkey5.test new file mode 100644 index 0000000000000000000000000000000000000000..5aa8b1d4b7aa7ecfa1023be9e317ea0ab63e250c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fkey5.test @@ -0,0 +1,363 @@ +# 2012 December 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file tests the PRAGMA foreign_key_check command. +# +# EVIDENCE-OF: R-05426-18119 PRAGMA foreign_key_check; PRAGMA +# foreign_key_check(table-name); + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix fkey5 + +ifcapable {!foreignkey} { + finish_test + return +} + +do_test fkey5-1.1 { + db eval { + CREATE TABLE p1(a INTEGER PRIMARY KEY); INSERT INTO p1 VALUES(88),(89); + CREATE TABLE p2(a INT PRIMARY KEY); INSERT INTO p2 VALUES(77),(78); + CREATE TABLE p3(a TEXT PRIMARY KEY); + INSERT INTO p3 VALUES(66),(67),('alpha'),('BRAVO'); + CREATE TABLE p4(a TEXT PRIMARY KEY COLLATE nocase); + INSERT INTO p4 VALUES('alpha'),('BRAVO'),('55'),('Delta'),('ECHO'); + CREATE TABLE p5(a INTEGER PRIMARY KEY, b, c, UNIQUE(b,c)); + INSERT INTO p5 VALUES(1,'Alpha','abc'),(2,'beta','def'); + CREATE TABLE p6(a INTEGER PRIMARY KEY, b TEXT COLLATE nocase, + c TEXT COLLATE rtrim, UNIQUE(b,c)); + INSERT INTO p6 VALUES(1,'Alpha','abc '),(2,'bETA','def '); + + CREATE TABLE c1(x INTEGER PRIMARY KEY references p1); + CREATE TABLE c2(x INTEGER PRIMARY KEY references p2); + CREATE TABLE c3(x INTEGER PRIMARY KEY references p3); + CREATE TABLE c4(x INTEGER PRIMARY KEY references p4); + CREATE TABLE c5(x INT references p1); + CREATE TABLE c6(x INT references p2); + CREATE TABLE c7(x INT references p3); + CREATE TABLE c8(x INT references p4); + CREATE TABLE c9(x TEXT UNIQUE references p1); + CREATE TABLE c10(x TEXT UNIQUE references p2); + CREATE TABLE c11(x TEXT UNIQUE references p3); + CREATE TABLE c12(x TEXT UNIQUE references p4); + CREATE TABLE c13(x TEXT COLLATE nocase references p3); + CREATE TABLE c14(x TEXT COLLATE nocase references p4); + CREATE TABLE c15(x, y, FOREIGN KEY(x,y) REFERENCES p5(b,c)); + CREATE TABLE c16(x, y, FOREIGN KEY(x,y) REFERENCES p5(c,b)); + CREATE TABLE c17(x, y, FOREIGN KEY(x,y) REFERENCES p6(b,c)); + CREATE TABLE c18(x, y, FOREIGN KEY(x,y) REFERENCES p6(c,b)); + CREATE TABLE c19(x TEXT COLLATE nocase, y TEXT COLLATE rtrim, + FOREIGN KEY(x,y) REFERENCES p5(b,c)); + CREATE TABLE c20(x TEXT COLLATE nocase, y TEXT COLLATE rtrim, + FOREIGN KEY(x,y) REFERENCES p5(c,b)); + CREATE TABLE c21(x TEXT COLLATE nocase, y TEXT COLLATE rtrim, + FOREIGN KEY(x,y) REFERENCES p6(b,c)); + CREATE TABLE c22(x TEXT COLLATE nocase, y TEXT COLLATE rtrim, + FOREIGN KEY(x,y) REFERENCES p6(c,b)); + + PRAGMA foreign_key_check; + } +} {} +do_test fkey5-1.2 { + db eval { + INSERT INTO c1 VALUES(90),(87),(88); + PRAGMA foreign_key_check; + } +} {c1 87 p1 0 c1 90 p1 0} +do_test fkey5-1.3 { + db eval { + PRAGMA foreign_key_check(c1); + } +} {c1 87 p1 0 c1 90 p1 0} +do_test fkey5-1.4 { + db eval { + PRAGMA foreign_key_check(c2); + } +} {} + +# EVIDENCE-OF: R-45728-08709 There are four columns in each result row. +# +# EVIDENCE-OF: R-55672-01620 The first column is the name of the table +# that contains the REFERENCES clause. +# +# EVIDENCE-OF: R-25219-25618 The second column is the rowid of the row +# that contains the invalid REFERENCES clause. +# +# EVIDENCE-OF: R-40482-20265 The third column is the name of the table +# that is referred to. +# +# EVIDENCE-OF: R-62839-07969 The fourth column is the index of the +# specific foreign key constraint that failed. +# +do_test fkey5-2.0 { + db eval { + INSERT INTO c5 SELECT x FROM c1; + DELETE FROM c1; + PRAGMA foreign_key_check; + } +} {c5 1 p1 0 c5 3 p1 0} +do_test fkey5-2.1 { + db eval { + PRAGMA foreign_key_check(c5); + } +} {c5 1 p1 0 c5 3 p1 0} +do_test fkey5-2.2 { + db eval { + PRAGMA foreign_key_check(c1); + } +} {} +do_execsql_test fkey5-2.3 { + PRAGMA foreign_key_list(c5); +} {0 0 p1 x {} {NO ACTION} {NO ACTION} NONE} + +do_test fkey5-3.0 { + db eval { + INSERT INTO c9 SELECT x FROM c5; + DELETE FROM c5; + PRAGMA foreign_key_check; + } +} {c9 1 p1 0 c9 3 p1 0} +do_test fkey5-3.1 { + db eval { + PRAGMA foreign_key_check(c9); + } +} {c9 1 p1 0 c9 3 p1 0} +do_test fkey5-3.2 { + db eval { + PRAGMA foreign_key_check(c5); + } +} {} + +do_test fkey5-4.0 { + db eval { + DELETE FROM c9; + INSERT INTO c2 VALUES(79),(77),(76); + PRAGMA foreign_key_check; + } +} {c2 76 p2 0 c2 79 p2 0} +do_test fkey5-4.1 { + db eval { + PRAGMA foreign_key_check(c2); + } +} {c2 76 p2 0 c2 79 p2 0} +do_test fkey5-4.2 { + db eval { + INSERT INTO c6 SELECT x FROM c2; + DELETE FROM c2; + PRAGMA foreign_key_check; + } +} {c6 1 p2 0 c6 3 p2 0} +do_test fkey5-4.3 { + db eval { + PRAGMA foreign_key_check(c6); + } +} {c6 1 p2 0 c6 3 p2 0} +do_test fkey5-4.4 { + db eval { + INSERT INTO c10 SELECT x FROM c6; + DELETE FROM c6; + PRAGMA foreign_key_check; + } +} {c10 1 p2 0 c10 3 p2 0} +do_test fkey5-4.5 { + db eval { + PRAGMA foreign_key_check(c10); + } +} {c10 1 p2 0 c10 3 p2 0} + +do_test fkey5-5.0 { + db eval { + DELETE FROM c10; + INSERT INTO c3 VALUES(68),(67),(65); + PRAGMA foreign_key_check; + } +} {c3 65 p3 0 c3 68 p3 0} +do_test fkey5-5.1 { + db eval { + PRAGMA foreign_key_check(c3); + } +} {c3 65 p3 0 c3 68 p3 0} +do_test fkey5-5.2 { + db eval { + INSERT INTO c7 SELECT x FROM c3; + INSERT INTO c7 VALUES('Alpha'),('alpha'),('foxtrot'); + DELETE FROM c3; + PRAGMA foreign_key_check; + } +} {c7 1 p3 0 c7 3 p3 0 c7 4 p3 0 c7 6 p3 0} +do_test fkey5-5.3 { + db eval { + PRAGMA foreign_key_check(c7); + } +} {c7 1 p3 0 c7 3 p3 0 c7 4 p3 0 c7 6 p3 0} +do_test fkey5-5.4 { + db eval { + INSERT INTO c11 SELECT x FROM c7; + DELETE FROM c7; + PRAGMA foreign_key_check; + } +} {c11 1 p3 0 c11 3 p3 0 c11 4 p3 0 c11 6 p3 0} +do_test fkey5-5.5 { + db eval { + PRAGMA foreign_key_check(c11); + } +} {c11 1 p3 0 c11 3 p3 0 c11 4 p3 0 c11 6 p3 0} + +do_test fkey5-6.0 { + db eval { + DELETE FROM c11; + INSERT INTO c4 VALUES(54),(55),(56); + PRAGMA foreign_key_check; + } +} {c4 54 p4 0 c4 56 p4 0} +do_test fkey5-6.1 { + db eval { + PRAGMA foreign_key_check(c4); + } +} {c4 54 p4 0 c4 56 p4 0} +do_test fkey5-6.2 { + db eval { + INSERT INTO c8 SELECT x FROM c4; + INSERT INTO c8 VALUES('Alpha'),('ALPHA'),('foxtrot'); + DELETE FROM c4; + PRAGMA foreign_key_check; + } +} {c8 1 p4 0 c8 3 p4 0 c8 6 p4 0} +do_test fkey5-6.3 { + db eval { + PRAGMA foreign_key_check(c8); + } +} {c8 1 p4 0 c8 3 p4 0 c8 6 p4 0} +do_test fkey5-6.4 { + db eval { + INSERT INTO c12 SELECT x FROM c8; + DELETE FROM c8; + PRAGMA foreign_key_check; + } +} {c12 1 p4 0 c12 3 p4 0 c12 6 p4 0} +do_test fkey5-6.5 { + db eval { + PRAGMA foreign_key_check(c12); + } +} {c12 1 p4 0 c12 3 p4 0 c12 6 p4 0} + +do_test fkey5-7.1 { + db eval { + INSERT OR IGNORE INTO c13 SELECT * FROM c12; + INSERT OR IGNORE INTO C14 SELECT * FROM c12; + DELETE FROM c12; + PRAGMA foreign_key_check; + } +} {c14 1 p4 0 c14 3 p4 0 c14 6 p4 0 c13 1 p3 0 c13 2 p3 0 c13 3 p3 0 c13 4 p3 0 c13 5 p3 0 c13 6 p3 0} +do_test fkey5-7.2 { + db eval { + PRAGMA foreign_key_check(c14); + } +} {c14 1 p4 0 c14 3 p4 0 c14 6 p4 0} +do_test fkey5-7.3 { + db eval { + PRAGMA foreign_key_check(c13); + } +} {c13 1 p3 0 c13 2 p3 0 c13 3 p3 0 c13 4 p3 0 c13 5 p3 0 c13 6 p3 0} + +do_test fkey5-8.0 { + db eval { + DELETE FROM c13; + DELETE FROM c14; + INSERT INTO c19 VALUES('alpha','abc'); + PRAGMA foreign_key_check(c19); + } +} {c19 1 p5 0} +do_test fkey5-8.1 { + db eval { + DELETE FROM c19; + INSERT INTO c19 VALUES('Alpha','abc'); + PRAGMA foreign_key_check(c19); + } +} {} +do_test fkey5-8.2 { + db eval { + INSERT INTO c20 VALUES('Alpha','abc'); + PRAGMA foreign_key_check(c20); + } +} {c20 1 p5 0} +do_test fkey5-8.3 { + db eval { + DELETE FROM c20; + INSERT INTO c20 VALUES('abc','Alpha'); + PRAGMA foreign_key_check(c20); + } +} {} +do_test fkey5-8.4 { + db eval { + INSERT INTO c21 VALUES('alpha','abc '); + PRAGMA foreign_key_check(c21); + } +} {} +do_test fkey5-8.5 { + db eval { + DELETE FROM c21; + INSERT INTO c19 VALUES('Alpha','abc'); + PRAGMA foreign_key_check(c21); + } +} {} +do_test fkey5-8.6 { + db eval { + INSERT INTO c22 VALUES('Alpha','abc'); + PRAGMA foreign_key_check(c22); + } +} {c22 1 p6 0} +do_test fkey5-8.7 { + db eval { + DELETE FROM c22; + INSERT INTO c22 VALUES('abc ','ALPHA'); + PRAGMA foreign_key_check(c22); + } +} {} + + +#------------------------------------------------------------------------- +# Tests 9.* verify that missing parent tables are handled correctly. +# +do_execsql_test 9.1.1 { + CREATE TABLE k1(x REFERENCES s1); + PRAGMA foreign_key_check(k1); +} {} +do_execsql_test 9.1.2 { + INSERT INTO k1 VALUES(NULL); + PRAGMA foreign_key_check(k1); +} {} +do_execsql_test 9.1.3 { + INSERT INTO k1 VALUES(1); + PRAGMA foreign_key_check(k1); +} {k1 2 s1 0} + +do_execsql_test 9.2.1 { + CREATE TABLE k2(x, y, FOREIGN KEY(x, y) REFERENCES s1(a, b)); + PRAGMA foreign_key_check(k2); +} {} +do_execsql_test 9.2 { + INSERT INTO k2 VALUES(NULL, 'five'); + PRAGMA foreign_key_check(k2); +} {} +do_execsql_test 9.3 { + INSERT INTO k2 VALUES('one', NULL); + PRAGMA foreign_key_check(k2); +} {} +do_execsql_test 9.4 { + INSERT INTO k2 VALUES('six', 'seven'); + PRAGMA foreign_key_check(k2); +} {k2 3 s1 0} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fkey6.test b/components/external/SQLite-3.8.1/test/fkey6.test new file mode 100644 index 0000000000000000000000000000000000000000..8f901164873686eb3d7666b8a24f451f293e4cd4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fkey6.test @@ -0,0 +1,176 @@ +# 2013-07-11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file tests the PRAGMA defer_foreign_keys and +# SQLITE_DBSTATUS_DEFERRED_FKS +# +# EVIDENCE-OF: R-18981-16292 When the defer_foreign_keys PRAGMA is on, +# enforcement of all foreign key constraints is delayed until the +# outermost transaction is committed. +# +# EVIDENCE-OF: R-28911-57501 The defer_foreign_keys pragma defaults to +# OFF so that foreign key constraints are only deferred if they are +# created as "DEFERRABLE INITIALLY DEFERRED". + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!foreignkey} { + finish_test + return +} + +do_execsql_test fkey6-1.0 { + PRAGMA defer_foreign_keys; +} {0} + +do_execsql_test fkey6-1.1 { + PRAGMA foreign_keys=ON; + CREATE TABLE t1(x INTEGER PRIMARY KEY); + CREATE TABLE t2(y INTEGER PRIMARY KEY, + z INTEGER REFERENCES t1(x) DEFERRABLE INITIALLY DEFERRED); + CREATE INDEX t2z ON t2(z); + CREATE TABLE t3(u INTEGER PRIMARY KEY, v INTEGER REFERENCES t1(x)); + CREATE INDEX t3v ON t3(v); + INSERT INTO t1 VALUES(1),(2),(3),(4),(5); + INSERT INTO t2 VALUES(1,1),(2,2); + INSERT INTO t3 VALUES(3,3),(4,4); +} {} +do_test fkey6-1.2 { + catchsql {DELETE FROM t1 WHERE x=2;} +} {1 {foreign key constraint failed}} +do_test fkey6-1.3 { + sqlite3_db_status db DBSTATUS_DEFERRED_FKS 0 +} {0 0 0} +do_test fkey6-1.4 { + execsql { + BEGIN; + DELETE FROM t1 WHERE x=1; + } +} {} +do_test fkey6-1.5.1 { + sqlite3_db_status db DBSTATUS_DEFERRED_FKS 1 +} {0 1 0} +do_test fkey6-1.5.2 { + sqlite3_db_status db DBSTATUS_DEFERRED_FKS 0 +} {0 1 0} +do_test fkey6-1.6 { + execsql { + ROLLBACK; + } +} {} +do_test fkey6-1.7 { + sqlite3_db_status db DBSTATUS_DEFERRED_FKS 0 +} {0 0 0} +do_test fkey6-1.8 { + execsql { + PRAGMA defer_foreign_keys=ON; + BEGIN; + DELETE FROM t1 WHERE x=3; + } +} {} +do_test fkey6-1.9 { + sqlite3_db_status db DBSTATUS_DEFERRED_FKS 0 +} {0 1 0} + +# EVIDENCE-OF: R-21752-26913 The defer_foreign_keys pragma is +# automatically switched off at each COMMIT or ROLLBACK. Hence, the +# defer_foreign_keys pragma must be separately enabled for each +# transaction. +do_execsql_test fkey6-1.10.1 { + PRAGMA defer_foreign_keys; + ROLLBACK; + PRAGMA defer_foreign_keys; + BEGIN; + PRAGMA defer_foreign_keys=ON; + PRAGMA defer_foreign_keys; + COMMIT; + PRAGMA defer_foreign_keys; + BEGIN; +} {1 0 1 0} +do_test fkey6-1.10.2 { + catchsql {DELETE FROM t1 WHERE x=3} +} {1 {foreign key constraint failed}} +db eval {ROLLBACK} + +do_test fkey6-1.20 { + execsql { + BEGIN; + DELETE FROM t1 WHERE x=1; + } + sqlite3_db_status db DBSTATUS_DEFERRED_FKS 0 +} {0 1 0} +do_test fkey6-1.21 { + execsql { + DELETE FROM t2 WHERE y=1; + } + sqlite3_db_status db DBSTATUS_DEFERRED_FKS 0 +} {0 0 0} +do_test fkey6-1.22 { + execsql { + COMMIT; + } +} {} + +do_execsql_test fkey6-2.1 { + CREATE TABLE p1(a PRIMARY KEY); + INSERT INTO p1 VALUES('one'), ('two'); + CREATE TABLE c1(x REFERENCES p1); + INSERT INTO c1 VALUES('two'), ('one'); +} + +do_execsql_test fkey6-2.2 { + BEGIN; + PRAGMA defer_foreign_keys = 1; + DELETE FROM p1; + ROLLBACK; + PRAGMA defer_foreign_keys; +} {0} + +do_execsql_test fkey6-2.3 { + BEGIN; + PRAGMA defer_foreign_keys = 1; + DROP TABLE p1; + PRAGMA vdbe_trace = 0; + ROLLBACK; + PRAGMA defer_foreign_keys; +} {0} + +do_execsql_test fkey6-2.4 { + BEGIN; + PRAGMA defer_foreign_keys = 1; + DELETE FROM p1; + DROP TABLE c1; + COMMIT; + PRAGMA defer_foreign_keys; +} {0} + +do_execsql_test fkey6-2.5 { + DROP TABLE p1; + CREATE TABLE p1(a PRIMARY KEY); + INSERT INTO p1 VALUES('one'), ('two'); + CREATE TABLE c1(x REFERENCES p1); + INSERT INTO c1 VALUES('two'), ('one'); +} + +do_execsql_test fkey6-2.6 { + BEGIN; + PRAGMA defer_foreign_keys = 1; + INSERT INTO c1 VALUES('three'); + DROP TABLE c1; + COMMIT; + PRAGMA defer_foreign_keys; +} {0} + + +finish_test + diff --git a/components/external/SQLite-3.8.1/test/fkey7.test b/components/external/SQLite-3.8.1/test/fkey7.test new file mode 100644 index 0000000000000000000000000000000000000000..c2682edbe5fbf3a286693b380046f6592f77e472 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fkey7.test @@ -0,0 +1,54 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for foreign keys. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix fkey7 + +ifcapable {!foreignkey} { + finish_test + return +} + +do_execsql_test 1.1 { + PRAGMA foreign_keys = 1; + + CREATE TABLE s1(a PRIMARY KEY, b); + CREATE TABLE par(a, b REFERENCES s1, c UNIQUE, PRIMARY KEY(a)); + + CREATE TABLE c1(a, b REFERENCES par); + CREATE TABLE c2(a, b REFERENCES par); + CREATE TABLE c3(a, b REFERENCES par(c)); +} + +proc auth {op tbl args} { + if {$op == "SQLITE_READ"} { set ::tbls($tbl) 1 } + return "SQLITE_OK" +} +db auth auth +db cache size 0 +proc do_tblsread_test {tn sql tbllist} { + array unset ::tbls + uplevel [list execsql $sql] + uplevel [list do_test $tn {lsort [array names ::tbls]} $tbllist] +} + +do_tblsread_test 1.2 { UPDATE par SET b=? WHERE a=? } {par s1} +do_tblsread_test 1.3 { UPDATE par SET a=? WHERE b=? } {c1 c2 par} +do_tblsread_test 1.4 { UPDATE par SET c=? WHERE b=? } {c3 par} +do_tblsread_test 1.5 { UPDATE par SET a=?,b=?,c=? WHERE b=? } {c1 c2 c3 par s1} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fkey_malloc.test b/components/external/SQLite-3.8.1/test/fkey_malloc.test new file mode 100644 index 0000000000000000000000000000000000000000..b4b5b4eed7d056aabbe668ad881a3e747db9bb67 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fkey_malloc.test @@ -0,0 +1,131 @@ +# 2009 September 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !foreignkey||!trigger { + finish_test + return +} +source $testdir/malloc_common.tcl + +do_malloc_test fkey_malloc-1 -sqlprep { + PRAGMA foreign_keys = 1; + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + CREATE TABLE t2(x REFERENCES t1 ON UPDATE CASCADE ON DELETE CASCADE); +} -sqlbody { + INSERT INTO t1 VALUES('aaa', 1); + INSERT INTO t2 VALUES('aaa'); + UPDATE t1 SET a = 'bbb'; + DELETE FROM t1; + PRAGMA foreign_key_check; +} + +do_malloc_test fkey_malloc-2 -sqlprep { + PRAGMA foreign_keys = 1; + CREATE TABLE t1(a, b, UNIQUE(a, b)); +} -sqlbody { + CREATE TABLE t2(x, y, + FOREIGN KEY(x, y) REFERENCES t1(a, b) DEFERRABLE INITIALLY DEFERRED + ); + BEGIN; + INSERT INTO t2 VALUES('a', 'b'); + INSERT INTO t1 VALUES('a', 'b'); + UPDATE t1 SET a = 'c'; + DELETE FROM t2; + INSERT INTO t2 VALUES('d', 'b'); + UPDATE t2 SET x = 'c'; + COMMIT; +} + +do_malloc_test fkey_malloc-3 -sqlprep { + PRAGMA foreign_keys = 1; + CREATE TABLE t1(x INTEGER PRIMARY KEY); + CREATE TABLE t2(y DEFAULT 14 REFERENCES t1(x) ON UPDATE SET DEFAULT); + CREATE TABLE t3(y REFERENCES t1 ON UPDATE SET NULL); + INSERT INTO t1 VALUES(13); + INSERT INTO t2 VALUES(13); + INSERT INTO t3 VALUES(13); +} -sqlbody { + UPDATE t1 SET x = 14; +} + +proc catch_fk_error {zSql} { + set rc [catch {db eval $zSql} msg] + if {$rc==0} { + return $msg + } + if {[string match {*foreign key*} $msg]} { + return "" + } + if {$msg eq "out of memory" || $msg eq "constraint failed"} { + error 1 + } + error $msg +} + +do_malloc_test fkey_malloc-4 -sqlprep { + PRAGMA foreign_keys = 1; + CREATE TABLE t1(x INTEGER PRIMARY KEY, y UNIQUE); + CREATE TABLE t2(z REFERENCES t1(x), a REFERENCES t1(y)); + CREATE TABLE t3(x); + CREATE TABLE t4(z REFERENCES t3); + CREATE TABLE t5(x, y); + CREATE TABLE t6(z REFERENCES t5(x)); + CREATE INDEX i51 ON t5(x); + CREATE INDEX i52 ON t5(y, x); + INSERT INTO t1 VALUES(1, 2); +} -tclbody { + catch_fk_error {INSERT INTO t2 VALUES(1, 3)} + catch_fk_error {INSERT INTO t4 VALUES(2)} + catch_fk_error {INSERT INTO t6 VALUES(2)} +} + +do_malloc_test fkey_malloc-5 -sqlprep { + PRAGMA foreign_keys = 1; + CREATE TABLE t1(x, y, PRIMARY KEY(x, y)); + CREATE TABLE t2(a, b, FOREIGN KEY(a, b) REFERENCES t1 ON UPDATE CASCADE); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t2 VALUES(1, 2); +} -sqlbody { + UPDATE t1 SET x = 5; +} + +do_malloc_test fkey_malloc-6 -sqlprep { + PRAGMA foreign_keys = 1; + CREATE TABLE t1( + x PRIMARY KEY, + y REFERENCES t1 ON DELETE RESTRICT ON UPDATE SET DEFAULT + ); + INSERT INTO t1 VALUES('abc', 'abc'); + INSERT INTO t1 VALUES('def', 'def'); +} -sqlbody { + INSERT INTO t1 VALUES('ghi', 'ghi'); + DELETE FROM t1 WHERE rowid>1; + UPDATE t1 SET x='jkl', y='jkl'; +} + +do_malloc_test fkey_malloc-7 -sqlprep { + PRAGMA foreign_keys = 1; + CREATE TABLE x(a, b, PRIMARY KEY(a, b)); + CREATE TABLE y(c, d, + FOREIGN KEY(d, c) REFERENCES x DEFERRABLE INITIALLY DEFERRED + ); + CREATE TABLE z(e, f, FOREIGN KEY(e, f) REFERENCES x); +} -sqlbody { + DROP TABLE y; + DROP TABLE x; +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/format4.test b/components/external/SQLite-3.8.1/test/format4.test new file mode 100644 index 0000000000000000000000000000000000000000..14d794709b8743ffd5aeb3011f49cc46d657d219 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/format4.test @@ -0,0 +1,65 @@ +# 2005 December 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that the new serial_type +# values of 8 (integer 0) and 9 (integer 1) work correctly. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +db eval {PRAGMA legacy_file_format=OFF} + +# The size of the database depends on whether or not autovacuum +# is enabled. +# +ifcapable autovacuum { + if {[db one {PRAGMA auto_vacuum}]} { + set small 3072 + set large 5120 + } else { + set small 2048 + set large 4096 + } +} else { + set small 2048 + set large 4096 +} + +do_test format4-1.1 { + execsql { + CREATE TABLE t1(x0,x1,x2,x3,x4,x5,x6,x7,x8,x9); + INSERT INTO t1 VALUES(0,0,0,0,0,0,0,0,0,0); + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + } + file size test.db +} $small +do_test format4-1.2 { + execsql { + UPDATE t1 SET x0=1, x1=1, x2=1, x3=1, x4=1, x5=1, x6=1, x7=1, x8=1, x9=1 + } + file size test.db +} $small +do_test format4-1.3 { + execsql { + UPDATE t1 SET x0=2, x1=2, x2=2, x3=2, x4=2, x5=2, x6=2, x7=2, x8=2, x9=2 + } + file size test.db +} $large + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts-9fd058691.test b/components/external/SQLite-3.8.1/test/fts-9fd058691.test new file mode 100644 index 0000000000000000000000000000000000000000..b228482d46bb84c7e8a620a9589e68bf8d43861c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts-9fd058691.test @@ -0,0 +1,59 @@ +# 2011 October 13 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for the FTS SQLite module. +# +# This file implements tests to verify that ticket [9fd058691] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +set ::testprefix fts3-9fd058691 + +do_execsql_test 1.0 { + CREATE VIRTUAL TABLE fts USING fts3( tags TEXT); + INSERT INTO fts (tags) VALUES ('tag1'); + SELECT * FROM fts WHERE tags MATCH 'tag1'; +} {tag1} + +do_test 1.1 { + db close + sqlite3 db test.db + execsql { + UPDATE fts SET tags = 'tag1' WHERE rowid = 1; + SELECT * FROM fts WHERE tags MATCH 'tag1'; + } +} {tag1} + +db close +forcedelete test.db +sqlite3 db test.db + +do_execsql_test 2.0 { + CREATE VIRTUAL TABLE fts USING fts3(tags TEXT); + INSERT INTO fts (docid, tags) VALUES (1, 'tag1'); + INSERT INTO fts (docid, tags) VALUES (2, NULL); + INSERT INTO fts (docid, tags) VALUES (3, 'three'); +} {} + +do_test 2.1 { + execsql { + UPDATE fts SET tags = 'two' WHERE rowid = 2; + SELECT * FROM fts WHERE tags MATCH 'two'; + } +} {two} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1a.test b/components/external/SQLite-3.8.1/test/fts1a.test new file mode 100644 index 0000000000000000000000000000000000000000..b63e79a81b30dbd591e745426c523cd2ff797cd8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1a.test @@ -0,0 +1,186 @@ +# 2006 September 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS1 module. +# +# $Id: fts1a.test,v 1.4 2006/09/28 19:43:32 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +# Construct a full-text search table containing five keywords: +# one, two, three, four, and five, in various combinations. The +# rowid for each will be a bitmask for the elements it contains. +# +db eval { + CREATE VIRTUAL TABLE t1 USING fts1(content); + INSERT INTO t1(content) VALUES('one'); + INSERT INTO t1(content) VALUES('two'); + INSERT INTO t1(content) VALUES('one two'); + INSERT INTO t1(content) VALUES('three'); + INSERT INTO t1(content) VALUES('one three'); + INSERT INTO t1(content) VALUES('two three'); + INSERT INTO t1(content) VALUES('one two three'); + INSERT INTO t1(content) VALUES('four'); + INSERT INTO t1(content) VALUES('one four'); + INSERT INTO t1(content) VALUES('two four'); + INSERT INTO t1(content) VALUES('one two four'); + INSERT INTO t1(content) VALUES('three four'); + INSERT INTO t1(content) VALUES('one three four'); + INSERT INTO t1(content) VALUES('two three four'); + INSERT INTO t1(content) VALUES('one two three four'); + INSERT INTO t1(content) VALUES('five'); + INSERT INTO t1(content) VALUES('one five'); + INSERT INTO t1(content) VALUES('two five'); + INSERT INTO t1(content) VALUES('one two five'); + INSERT INTO t1(content) VALUES('three five'); + INSERT INTO t1(content) VALUES('one three five'); + INSERT INTO t1(content) VALUES('two three five'); + INSERT INTO t1(content) VALUES('one two three five'); + INSERT INTO t1(content) VALUES('four five'); + INSERT INTO t1(content) VALUES('one four five'); + INSERT INTO t1(content) VALUES('two four five'); + INSERT INTO t1(content) VALUES('one two four five'); + INSERT INTO t1(content) VALUES('three four five'); + INSERT INTO t1(content) VALUES('one three four five'); + INSERT INTO t1(content) VALUES('two three four five'); + INSERT INTO t1(content) VALUES('one two three four five'); +} + +do_test fts1a-1.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts1a-1.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two'} +} {3 7 11 15 19 23 27 31} +do_test fts1a-1.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one'} +} {3 7 11 15 19 23 27 31} +do_test fts1a-1.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two three'} +} {7 15 23 31} +do_test fts1a-1.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one three two'} +} {7 15 23 31} +do_test fts1a-1.6 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two three one'} +} {7 15 23 31} +do_test fts1a-1.7 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one three'} +} {7 15 23 31} +do_test fts1a-1.8 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three one two'} +} {7 15 23 31} +do_test fts1a-1.9 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three two one'} +} {7 15 23 31} +do_test fts1a-1.10 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two THREE'} +} {7 15 23 31} +do_test fts1a-1.11 { + execsql {SELECT rowid FROM t1 WHERE content MATCH ' ONE Two three '} +} {7 15 23 31} + +do_test fts1a-2.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one"'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts1a-2.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two"'} +} {3 7 11 15 19 23 27 31} +do_test fts1a-2.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"two one"'} +} {} +do_test fts1a-2.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three"'} +} {7 15 23 31} +do_test fts1a-2.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two"'} +} {} +do_test fts1a-2.6 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three four"'} +} {15 31} +do_test fts1a-2.7 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two four"'} +} {} +do_test fts1a-2.8 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three five"'} +} {21} +do_test fts1a-2.9 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" five'} +} {21 29} +do_test fts1a-2.10 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three"'} +} {21 29} +do_test fts1a-2.11 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three" four'} +} {29} +do_test fts1a-2.12 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five four "one three"'} +} {29} +do_test fts1a-2.13 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" four five'} +} {29} + +do_test fts1a-3.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts1a-3.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one -two'} +} {1 5 9 13 17 21 25 29} +do_test fts1a-3.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '-two one'} +} {1 5 9 13 17 21 25 29} + +do_test fts1a-4.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one OR two'} +} {1 2 3 5 6 7 9 10 11 13 14 15 17 18 19 21 22 23 25 26 27 29 30 31} +do_test fts1a-4.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two" OR three'} +} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31} +do_test fts1a-4.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR "one two"'} +} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31} +do_test fts1a-4.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three'} +} {3 5 7 11 13 15 19 21 23 27 29 31} +do_test fts1a-4.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR two one'} +} {3 5 7 11 13 15 19 21 23 27 29 31} +do_test fts1a-4.6 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three OR four'} +} {3 5 7 9 11 13 15 19 21 23 25 27 29 31} +do_test fts1a-4.7 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two OR three OR four one'} +} {3 5 7 9 11 13 15 19 21 23 25 27 29 31} + +# Test the ability to handle NULL content +# +do_test fts1a-5.1 { + execsql {INSERT INTO t1(content) VALUES(NULL)} +} {} +do_test fts1a-5.2 { + set rowid [db last_insert_rowid] + execsql {SELECT content FROM t1 WHERE rowid=$rowid} +} {{}} +do_test fts1a-5.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH NULL} +} {} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1b.test b/components/external/SQLite-3.8.1/test/fts1b.test new file mode 100644 index 0000000000000000000000000000000000000000..2bbe1aab8004791af162a767022a7cd8d42ea1f6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1b.test @@ -0,0 +1,147 @@ +# 2006 September 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS1 module. +# +# $Id: fts1b.test,v 1.4 2006/09/18 02:12:48 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +# Fill the full-text index "t1" with phrases in english, spanish, +# and german. For the i-th row, fill in the names for the bits +# that are set in the value of i. The least significant bit is +# 1. For example, the value 5 is 101 in binary which will be +# converted to "one three" in english. +# +proc fill_multilanguage_fulltext_t1 {} { + set english {one two three four five} + set spanish {un dos tres cuatro cinco} + set german {eine zwei drei vier funf} + + for {set i 1} {$i<=31} {incr i} { + set cmd "INSERT INTO t1 VALUES" + set vset {} + foreach lang {english spanish german} { + set words {} + for {set j 0; set k 1} {$j<5} {incr j; incr k $k} { + if {$k&$i} {lappend words [lindex [set $lang] $j]} + } + lappend vset "'$words'" + } + set sql "INSERT INTO t1(english,spanish,german) VALUES([join $vset ,])" + # puts $sql + db eval $sql + } +} + +# Construct a full-text search table containing five keywords: +# one, two, three, four, and five, in various combinations. The +# rowid for each will be a bitmask for the elements it contains. +# +db eval { + CREATE VIRTUAL TABLE t1 USING fts1(english,spanish,german); +} +fill_multilanguage_fulltext_t1 + +do_test fts1b-1.1 { + execsql {SELECT rowid FROM t1 WHERE english MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts1b-1.2 { + execsql {SELECT rowid FROM t1 WHERE spanish MATCH 'one'} +} {} +do_test fts1b-1.3 { + execsql {SELECT rowid FROM t1 WHERE german MATCH 'one'} +} {} +do_test fts1b-1.4 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts1b-1.5 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one dos drei'} +} {7 15 23 31} +do_test fts1b-1.6 { + execsql {SELECT english, spanish, german FROM t1 WHERE rowid=1} +} {one un eine} +do_test fts1b-1.7 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"one un"'} +} {} + +do_test fts1b-2.1 { + execsql { + CREATE VIRTUAL TABLE t2 USING fts1(from,to); + INSERT INTO t2([from],[to]) VALUES ('one two three', 'four five six'); + SELECT [from], [to] FROM t2 + } +} {{one two three} {four five six}} + + +# Compute an SQL string that contains the words one, two, three,... to +# describe bits set in the value $i. Only the lower 5 bits are examined. +# +proc wordset {i} { + set x {} + for {set j 0; set k 1} {$j<5} {incr j; incr k $k} { + if {$k&$i} {lappend x [lindex {one two three four five} $j]} + } + return '$x' +} + +# Create a new FTS table with three columns: +# +# norm: words for the bits of rowid +# plusone: words for the bits of rowid+1 +# invert: words for the bits of ~rowid +# +db eval { + CREATE VIRTUAL TABLE t4 USING fts1([norm],'plusone',"invert"); +} +for {set i 1} {$i<=15} {incr i} { + set vset [list [wordset $i] [wordset [expr {$i+1}]] [wordset [expr {~$i}]]] + db eval "INSERT INTO t4(norm,plusone,invert) VALUES([join $vset ,]);" +} + +do_test fts1b-4.1 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one'} +} {1 3 5 7 9 11 13 15} +do_test fts1b-4.2 { + execsql {SELECT rowid FROM t4 WHERE norm MATCH 'one'} +} {1 3 5 7 9 11 13 15} +do_test fts1b-4.3 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'one'} +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} +do_test fts1b-4.4 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:one'} +} {2 4 6 8 10 12 14} +do_test fts1b-4.5 { + execsql {SELECT rowid FROM t4 WHERE plusone MATCH 'one'} +} {2 4 6 8 10 12 14} +do_test fts1b-4.6 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one plusone:two'} +} {1 5 9 13} +do_test fts1b-4.7 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one two'} +} {1 3 5 7 9 11 13 15} +do_test fts1b-4.8 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:two norm:one'} +} {1 5 9 13} +do_test fts1b-4.9 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'two norm:one'} +} {1 3 5 7 9 11 13 15} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1c.test b/components/external/SQLite-3.8.1/test/fts1c.test new file mode 100644 index 0000000000000000000000000000000000000000..a12469593aa5b4a2b1d18c4c534f9a6619d433d2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1c.test @@ -0,0 +1,1213 @@ +# 2006 September 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS1 module. +# +# $Id: fts1c.test,v 1.11 2006/10/04 17:35:28 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +# Create a table of sample email data. The data comes from email +# archives of Enron executives that was published as part of the +# litigation against that company. +# +do_test fts1c-1.1 { + db eval { + CREATE VIRTUAL TABLE email USING fts1([from],[to],subject,body); + BEGIN TRANSACTION; +INSERT INTO email([from],[to],subject,body) VALUES('savita.puthigai@enron.com', 'traders.eol@enron.com, traders.eol@enron.com', 'EnronOnline- Change to Autohedge', 'Effective Monday, October 22, 2001 the following changes will be made to the Autohedge functionality on EnronOnline. + +The volume on the hedge will now respect the minimum volume and volume increment settings on the parent product. See rules below: + +? If the transaction volume on the child is less than half of the parent''s minimum volume no hedge will occur. +? If the transaction volume on the child is more than half the parent''s minimum volume but less than half the volume increment on the parent, the hedge will volume will be the parent''s minimum volume. +? For all other volumes, the same rounding rules will apply based on the volume increment on the parent product. + +Please see example below: + +Parent''s Settings: +Minimum: 5000 +Increment: 1000 + +Volume on Autohedge transaction Volume Hedged +1 - 2499 0 +2500 - 5499 5000 +5500 - 6499 6000'); +INSERT INTO email([from],[to],subject,body) VALUES('dana.davis@enron.com', 'laynie.east@enron.com, lisa.king@enron.com, lisa.best@enron.com,', 'Leaving Early', 'FYI: +If it''s ok with everyone''s needs, I would like to leave @4pm. If you think +you will need my assistance past the 4 o''clock hour just let me know; I''ll +be more than willing to stay.'); +INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'louise.kitchen@enron.com', '<> - CC02.06.02', 'The following expense report is ready for approval: + +Employee Name: Christopher F. Calger +Status last changed by: Mollie E. Gustafson Ms +Expense Report Name: CC02.06.02 +Report Total: $3,972.93 +Amount Due Employee: $3,972.93 + + +To approve this expense report, click on the following link for Concur Expense. +http://expensexms.enron.com'); +INSERT INTO email([from],[to],subject,body) VALUES('jeff.duff@enron.com', 'julie.johnson@enron.com', 'Work request', 'Julie, + +Could you print off the current work request report by 1:30 today? + +Gentlemen, + +I''d like to review this today at 1:30 in our office. Also, could you provide +me with your activity reports so I can have Julie enter this information. + +JD'); +INSERT INTO email([from],[to],subject,body) VALUES('v.weldon@enron.com', 'gary.l.carrier@usa.dupont.com, scott.joyce@bankofamerica.com', 'Enron News', 'This could turn into something big.... +http://biz.yahoo.com/rf/010129/n29305829.html'); +INSERT INTO email([from],[to],subject,body) VALUES('mark.haedicke@enron.com', 'paul.simons@enron.com', 'Re: First Polish Deal!', 'Congrats! Things seem to be building rapidly now on the Continent. Mark'); +INSERT INTO email([from],[to],subject,body) VALUES('e..carter@enron.com', 't..robinson@enron.com', 'FW: Producers Newsletter 9-24-2001', ' +The producer lumber pricing sheet. + -----Original Message----- +From: Johnson, Jay +Sent: Tuesday, October 16, 2001 3:42 PM +To: Carter, Karen E. +Subject: FW: Producers Newsletter 9-24-2001 + + + + -----Original Message----- +From: Daigre, Sergai +Sent: Friday, September 21, 2001 8:33 PM +Subject: Producers Newsletter 9-24-2001 + + '); +INSERT INTO email([from],[to],subject,body) VALUES('david.delainey@enron.com', 'kenneth.lay@enron.com', 'Greater Houston Partnership', 'Ken, in response to the letter from Mr Miguel San Juan, my suggestion would +be to offer up the Falcon for their use; however, given the tight time frame +and your recent visit with Mr. Fox that it would be difficult for either you +or me to participate. + +I spoke to Max and he agrees with this approach. + +I hope this meets with your approval. + +Regards +Delainey'); +INSERT INTO email([from],[to],subject,body) VALUES('lachandra.fenceroy@enron.com', 'lindy.donoho@enron.com', 'FW: Bus Applications Meeting Follow Up', 'Lindy, + +Here is the original memo we discussed earlier. Please provide any information that you may have. + +Your cooperation is greatly appreciated. + +Thanks, + +lachandra.fenceroy@enron.com +713.853.3884 +877.498.3401 Pager + + -----Original Message----- +From: Bisbee, Joanne +Sent: Wednesday, September 26, 2001 7:50 AM +To: Fenceroy, LaChandra +Subject: FW: Bus Applications Meeting Follow Up + +Lachandra, Please get with David Duff today and see what this is about. Who are our TW accounting business users? + + -----Original Message----- +From: Koh, Wendy +Sent: Tuesday, September 25, 2001 2:41 PM +To: Bisbee, Joanne +Subject: Bus Applications Meeting Follow Up + +Lisa brought up a TW change effective Nov 1. It involves eliminating a turnback surcharge. I have no other information, but you might check with the business folks for any system changes required. + +Wendy'); +INSERT INTO email([from],[to],subject,body) VALUES('danny.mccarty@enron.com', 'fran.fagan@enron.com', 'RE: worksheets', 'Fran, + If Julie''s merit needs to be lump sum, just move it over to that column. Also, send me Eric Gadd''s sheets as well. Thanks. +Dan + + -----Original Message----- +From: Fagan, Fran +Sent: Thursday, December 20, 2001 11:10 AM +To: McCarty, Danny +Subject: worksheets + +As discussed, attached are your sheets for bonus and merit. + +Thanks, + +Fran Fagan +Sr. HR Rep +713.853.5219 + + + << File: McCartyMerit.xls >> << File: mccartyBonusCommercial_UnP.xls >> + +'); +INSERT INTO email([from],[to],subject,body) VALUES('bert.meyers@enron.com', 'shift.dl-portland@enron.com', 'OCTOBER SCHEDULE', 'TEAM, + +PLEASE SEND ME ANY REQUESTS THAT YOU HAVE FOR OCTOBER. SO FAR I HAVE THEM FOR LEAF. I WOULD LIKE TO HAVE IT DONE BY THE 15TH OF THE MONTH. ANY QUESTIONS PLEASE GIVE ME A CALL. + +BERT'); +INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'john.arnold@enron.com, bilal.bajwa@enron.com, john.griffith@enron.com,', 'TRV Notification: (NG - PROPT P/L - 09/27/2001)', 'The report named: NG - PROPT P/L , published as of 09/27/2001 is now available for viewing on the website.'); +INSERT INTO email([from],[to],subject,body) VALUES('patrice.mims@enron.com', 'calvin.eakins@enron.com', 'Re: Small business supply assistance', 'Hi Calvin + + +I spoke with Rickey (boy, is he long-winded!!). Gave him the name of our +credit guy, Russell Diamond. + +Thank for your help!'); +INSERT INTO email([from],[to],subject,body) VALUES('legal <.hall@enron.com>', 'stephanie.panus@enron.com', 'Termination update', 'City of Vernon and Salt River Project terminated their contracts. I will fax these notices to you.'); +INSERT INTO email([from],[to],subject,body) VALUES('d..steffes@enron.com', 'richard.shapiro@enron.com', 'EES / ENA Government Affairs Staffing & Outside Services', 'Rick -- + +Here is the information on staffing and outside services. Call if you need anything else. + +Jim + + '); +INSERT INTO email([from],[to],subject,body) VALUES('gelliott@industrialinfo.com', 'pcopello@industrialinfo.com', 'ECAAR (Gavin), WSCC (Diablo Canyon), & NPCC (Seabrook)', 'Dear Power Outage Database Customer, +Attached you will find an excel document. The outages contained within are forced or rescheduled outages. Your daily delivery will still contain these outages. +In addition to the two excel documents, there is a dbf file that is formatted like your daily deliveries you receive nightly. This will enable you to load the data into your regular database. Any questions please let me know. Thanks. +Greg Elliott +IIR, Inc. +713-783-5147 x 3481 +outages@industrialinfo.com +THE INFORMATION CONTAINED IN THIS E-MAIL IS LEGALLY PRIVILEGED AND CONFIDENTIAL INFORMATION INTENDED ONLY FOR THE USE OF THE INDIVIDUAL OR ENTITY NAMED ABOVE. YOU ARE HEREBY NOTIFIED THAT ANY DISSEMINATION, DISTRIBUTION, OR COPY OF THIS E-MAIL TO UNAUTHORIZED ENTITIES IS STRICTLY PROHIBITED. IF YOU HAVE RECEIVED THIS +E-MAIL IN ERROR, PLEASE DELETE IT. + - OUTAGE.dbf + - 111201R.xls + - 111201.xls '); +INSERT INTO email([from],[to],subject,body) VALUES('enron.announcements@enron.com', 'all_ena_egm_eim@enron.com', 'EWS Brown Bag', 'MARK YOUR LUNCH CALENDARS NOW ! + +You are invited to attend the EWS Brown Bag Lunch Series + +Featuring: RAY BOWEN, COO + +Topic: Enron Industrial Markets + +Thursday, March 15, 2001 +11:30 am - 12:30 pm +EB 5 C2 + + +You bring your lunch, Limited Seating +We provide drinks and dessert. RSVP x 3-9610'); +INSERT INTO email([from],[to],subject,body) VALUES('chris.germany@enron.com', 'ingrid.immer@williams.com', 'Re: About St Pauls', 'Sounds good to me. I bet this is next to the Warick?? Hotel. + + + + +"Immer, Ingrid" on 12/21/2000 11:48:47 AM +To: "''chris.germany@enron.com''" +cc: +Subject: About St Pauls + + + + + <> +? +?http://www.stpaulshouston.org/about.html + +Chris, + +I like the looks of this place.? What do you think about going here Christmas +eve?? They have an 11:00 a.m. service and a candlelight service at 5:00 p.m., +among others. + +Let me know.?? ii + + - About St Pauls.url + +'); +INSERT INTO email([from],[to],subject,body) VALUES('nas@cpuc.ca.gov', 'skatz@sempratrading.com, kmccrea@sablaw.com, thompson@wrightlaw.com,', 'Reply Brief filed July 31, 2000', ' - CPUC01-#76371-v1-Revised_Reply_Brief__Due_today_7_31_.doc'); +INSERT INTO email([from],[to],subject,body) VALUES('gascontrol@aglresources.com', 'dscott4@enron.com, lcampbel@enron.com', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder +As discussed in the Winter Operations Meeting on Sept.29,2000, +E-Gas(Emergency Gas) will not be offered this winter as a service from AGLC. +Marketers and Poolers can receive gas via Peaking and IBSS nominations(daisy +chain) from other marketers up to the 6 p.m. Same Day 2 nomination cycle. +'); +INSERT INTO email([from],[to],subject,body) VALUES('dutch.quigley@enron.com', 'rwolkwitz@powermerchants.com', '', ' + +Here is a goody for you'); +INSERT INTO email([from],[to],subject,body) VALUES('ryan.o''rourke@enron.com', 'k..allen@enron.com, randy.bhatia@enron.com, frank.ermis@enron.com,', 'TRV Notification: (West VaR - 11/07/2001)', 'The report named: West VaR , published as of 11/07/2001 is now available for viewing on the website.'); +INSERT INTO email([from],[to],subject,body) VALUES('mjones7@txu.com', 'cstone1@txu.com, ggreen2@txu.com, timpowell@txu.com,', 'Enron / HPL Actuals for July 10, 2000', 'Teco Tap 10.000 / Enron ; 110.000 / HPL IFERC + +LS HPL LSK IC 30.000 / Enron +'); +INSERT INTO email([from],[to],subject,body) VALUES('susan.pereira@enron.com', 'kkw816@aol.com', 'soccer practice', 'Kathy- + +Is it safe to assume that practice is cancelled for tonight?? + +Susan Pereira'); +INSERT INTO email([from],[to],subject,body) VALUES('mark.whitt@enron.com', 'barry.tycholiz@enron.com', 'Huber Internal Memo', 'Please look at this. I didn''t know how deep to go with the desk. Do you think this works. + + '); +INSERT INTO email([from],[to],subject,body) VALUES('m..forney@enron.com', 'george.phillips@enron.com', '', 'George, +Give me a call and we will further discuss opportunities on the 13st floor. + +Thanks, +JMForney +3-7160'); +INSERT INTO email([from],[to],subject,body) VALUES('brad.mckay@enron.com', 'angusmcka@aol.com', 'Re: (no subject)', 'not yet'); +INSERT INTO email([from],[to],subject,body) VALUES('adam.bayer@enron.com', 'jonathan.mckay@enron.com', 'FW: Curve Fetch File', 'Here is the curve fetch file sent to me. It has plenty of points in it. If you give me a list of which ones you need we may be able to construct a secondary worksheet to vlookup the values. + +adam +35227 + + + -----Original Message----- +From: Royed, Jeff +Sent: Tuesday, September 25, 2001 11:37 AM +To: Bayer, Adam +Subject: Curve Fetch File + +Let me know if it works. It may be required to have a certain version of Oracle for it to work properly. + + + +Jeff Royed +Enron +Energy Operations +Phone: 713-853-5295'); +INSERT INTO email([from],[to],subject,body) VALUES('matt.smith@enron.com', 'yan.wang@enron.com', 'Report Formats', 'Yan, + +The merged reports look great. I believe the only orientation changes are to +"unmerge" the following six reports: + +31 Keystone Receipts +15 Questar Pipeline +40 Rockies Production +22 West_2 +23 West_3 +25 CIG_WIC + +The orientation of the individual reports should be correct. Thanks. + +Mat + +PS. Just a reminder to add the "*" by the title of calculated points.'); +INSERT INTO email([from],[to],subject,body) VALUES('michelle.lokay@enron.com', 'jimboman@bigfoot.com', 'Egyptian Festival', '---------------------- Forwarded by Michelle Lokay/ET&S/Enron on 09/07/2000 +10:08 AM --------------------------- + + +"Karkour, Randa" on 09/07/2000 09:01:04 AM +To: "''Agheb (E-mail)" , "Leila Mankarious (E-mail)" +, "''Marymankarious (E-mail)" +, "Michelle lokay (E-mail)" , "Ramy +Mankarious (E-mail)" +cc: + +Subject: Egyptian Festival + + + <> + + http://www.egyptianfestival.com/ + + - Egyptian Festival.url +'); +INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'sherry.dawson@enron.com', 'Urgent!!! --- New EAST books', 'This has to be done.................................. + +Thanks +---------------------- Forwarded by Errol McLaughlin/Corp/Enron on 12/20/2000 +08:39 AM --------------------------- + + + + From: William Kelly @ ECT 12/20/2000 08:31 AM + + +To: Kam Keiser/HOU/ECT@ECT, Darron C Giron/HOU/ECT@ECT, David +Baumbach/HOU/ECT@ECT, Errol McLaughlin/Corp/Enron@ENRON +cc: Kimat Singla/HOU/ECT@ECT, Kulvinder Fowler/NA/Enron@ENRON, Kyle R +Lilly/HOU/ECT@ECT, Jeff Royed/Corp/Enron@ENRON, Alejandra +Chavez/NA/Enron@ENRON, Crystal Hyde/HOU/ECT@ECT + +Subject: New EAST books + +We have new book names in TAGG for our intramonth portfolios and it is +extremely important that any deal booked to the East is communicated quickly +to someone on my team. I know it will take some time for the new names to +sink in and I do not want us to miss any positions or P&L. + +Thanks for your help on this. + +New: +Scott Neal : East Northeast +Dick Jenkins: East Marketeast + +WK +'); +INSERT INTO email([from],[to],subject,body) VALUES('david.forster@enron.com', 'eol.wide@enron.com', 'Change to Stack Manager', 'Effective immediately, there is a change to the Stack Manager which will +affect any Inactive Child. + +An inactive Child with links to Parent products will not have their +calculated prices updated until the Child product is Activated. + +When the Child Product is activated, the price will be recalculated and +updated BEFORE it is displayed on the web. + +This means that if you are inputting a basis price on a Child product, you +will not see the final, calculated price until you Activate the product, at +which time the customer will also see it. + +If you have any questions, please contact the Help Desk on: + +Americas: 713 853 4357 +Europe: + 44 (0) 20 7783 7783 +Asia/Australia: +61 2 9229 2300 + +Dave'); +INSERT INTO email([from],[to],subject,body) VALUES('vince.kaminski@enron.com', 'jhh1@email.msn.com', 'Re: Light reading - see pieces beginning on page 7', 'John, + +I saw it. Very interesting. + +Vince + + + + + +"John H Herbert" on 07/28/2000 08:38:08 AM +To: "Vince J Kaminski" +cc: +Subject: Light reading - see pieces beginning on page 7 + + +Cheers and have a nice weekend, + + +JHHerbert + + + + + - gd000728.pdf + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('matthew.lenhart@enron.com', 'mmmarcantel@equiva.com', 'RE:', 'i will try to line up a pig for you '); +INSERT INTO email([from],[to],subject,body) VALUES('jae.black@enron.com', 'claudette.harvey@enron.com, chaun.roberts@enron.com, judy.martinez@enron.com,', 'Disaster Recovery Equipment', 'As a reminder...there are several pieces of equipment that are set up on the 30th Floor, as well as on our floor, for the Disaster Recovery Team. PLEASE DO NOT TAKE, BORROW OR USE this equipment. Should you need to use another computer system, other than yours, or make conference calls please work with your Assistant to help find or set up equipment for you to use. + +Thanks for your understanding in this matter. + +T.Jae Black +East Power Trading +Assistant to Kevin Presto +off. 713-853-5800 +fax 713-646-8272 +cell 713-539-4760'); +INSERT INTO email([from],[to],subject,body) VALUES('eric.bass@enron.com', 'dale.neuner@enron.com', '5 X 24', 'Dale, + +Have you heard anything more on the 5 X 24s? We would like to get this +product out ASAP. + + +Thanks, + +Eric'); +INSERT INTO email([from],[to],subject,body) VALUES('messenger@smartreminders.com', 'm..tholt@enron.com', '10% Coupon - PrintPal Printer Cartridges - 100% Guaranteed', '[IMAGE] +[IMAGE][IMAGE][IMAGE] +Dear SmartReminders Member, + [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] + + + + + + + + + + + + + + + + + + + + + +We respect your privacy and are a Certified Participant of the BBBOnLine + Privacy Program. To be removed from future offers,click here. +SmartReminders.com is a permission based service. To unsubscribe click here . '); +INSERT INTO email([from],[to],subject,body) VALUES('benjamin.rogers@enron.com', 'mark.bernstein@enron.com', '', 'The guy you are talking about left CIN under a "cloud of suspicion" sort of +speak. He was the one who got into several bad deals and PPA''s in California +for CIN, thus he left on a bad note. Let me know if you need more detail +than that, I felt this was the type of info you were looking for. Thanks! +Ben'); +INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'michelle.cash@enron.com', 'Expense Report Receipts Not Received', 'Employee Name: Michelle Cash +Report Name: Houston Cellular 8-11-01 +Report Date: 12/13/01 +Report ID: 594D37C9ED2111D5B452 +Submitted On: 12/13/01 + +You are only allowed 2 reports with receipts outstanding. Your expense reports will not be paid until you meet this requirement.'); +INSERT INTO email([from],[to],subject,body) VALUES('susan.mara@enron.com', 'ray.alvarez@enron.com, mark.palmer@enron.com, karen.denne@enron.com,', 'CAISO Emergency Motion -- to discontinue market-based rates for', 'FYI. the latest broadside against the generators. + +Sue Mara +Enron Corp. +Tel: (415) 782-7802 +Fax:(415) 782-7854 +----- Forwarded by Susan J Mara/NA/Enron on 06/08/2001 12:24 PM ----- + + + "Milner, Marcie" 06/08/2001 11:13 AM To: "''smara@enron.com''" cc: Subject: CAISO Emergency Motion + + +Sue, did you see this emergency motion the CAISO filed today? Apparently +they are requesting that FERC discontinue market-based rates immediately and +grant refunds plus interest on the difference between cost-based rates and +market revenues received back to May 2000. They are requesting the +commission act within 14 days. Have you heard anything about what they are +doing? + +Marcie + +http://www.caiso.com/docs/2001/06/08/200106081005526469.pdf +'); +INSERT INTO email([from],[to],subject,body) VALUES('fletcher.sturm@enron.com', 'eloy.escobar@enron.com', 'Re: General Brinks Position Meeting', 'Eloy, + +Who is General Brinks? + +Fletch'); +INSERT INTO email([from],[to],subject,body) VALUES('nailia.dindarova@enron.com', 'richard.shapiro@enron.com', 'Documents for Mark Frevert (on EU developments and lessons from', 'Rick, + +Here are the documents that Peter has prepared for Mark Frevert. + +Nailia +---------------------- Forwarded by Nailia Dindarova/LON/ECT on 25/06/2001 +16:36 --------------------------- + + +Nailia Dindarova +25/06/2001 15:36 +To: Michael Brown/Enron@EUEnronXGate +cc: Ross Sankey/Enron@EUEnronXGate, Eric Shaw/ENRON@EUEnronXGate, Peter +Styles/LON/ECT@ECT + +Subject: Documents for Mark Frevert (on EU developments and lessons from +California) + +Michael, + + +These are the documents that Peter promised to give to you for Mark Frevert. +He has now handed them to him in person but asked me to transmit them +electronically to you, as well as Eric and Ross. + +Nailia + + + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('peggy.a.kostial@accenture.com', 'dave.samuels@enron.com', 'EOL-Accenture Deal Sheet', 'Dave - + +Attached are our comments and suggested changes. Please call to review. + +On the time line for completion, we have four critical steps to complete: + Finalize market analysis to refine business case, specifically + projected revenue stream + Complete counterparty surveying, including targeting 3 CPs for letters + of intent + Review Enron asset base for potential reuse/ licensing + Contract negotiations + +Joe will come back to us with an updated time line, but it is my +expectation that we are still on the same schedule (we just begun week +three) with possibly a week or so slippage.....contract negotiations will +probably be the critical path. + +We will send our cut at the actual time line here shortly. Thanks, + +Peggy + +(See attached file: accenture-dealpoints v2.doc) + - accenture-dealpoints v2.doc '); +INSERT INTO email([from],[to],subject,body) VALUES('thomas.martin@enron.com', 'thomas.martin@enron.com', 'Re: Guadalupe Power Partners LP', '---------------------- Forwarded by Thomas A Martin/HOU/ECT on 03/20/2001 +03:49 PM --------------------------- + + +Thomas A Martin +10/11/2000 03:55 PM +To: Patrick Wade/HOU/ECT@ECT +cc: +Subject: Re: Guadalupe Power Partners LP + +The deal is physically served at Oasis Waha or Oasis Katy and is priced at +either HSC, Waha or Katytailgate GD at buyers option three days prior to +NYMEX close. + +'); +INSERT INTO email([from],[to],subject,body) VALUES('judy.townsend@enron.com', 'dan.junek@enron.com, chris.germany@enron.com', 'Columbia Distribution''s Capacity Available for Release - Sum', '---------------------- Forwarded by Judy Townsend/HOU/ECT on 03/09/2001 11:04 +AM --------------------------- + + +agoddard@nisource.com on 03/08/2001 09:16:57 AM +To: " - *Koch, Kent" , " - +*Millar, Debra" , " - *Burke, Lynn" + +cc: " - *Heckathorn, Tom" +Subject: Columbia Distribution''s Capacity Available for Release - Sum + + +Attached is Columbia Distribution''s notice of capacity available for release +for +the summer of 2001 (Apr. 2001 through Oct. 2001). + +Please note that the deadline for bids is 3:00pm EST on March 20, 2001. + +If you have any questions, feel free to contact any of the representatives +listed +at the bottom of the attachment. + +Aaron Goddard + + + + + - 2001Summer.doc +'); +INSERT INTO email([from],[to],subject,body) VALUES('rhonda.denton@enron.com', 'tim.belden@enron.com, dana.davis@enron.com, genia.fitzgerald@enron.com,', 'Split Rock Energy LLC', 'We have received the executed EEI contract from this CP dated 12/12/2000. +Copies will be distributed to Legal and Credit.'); +INSERT INTO email([from],[to],subject,body) VALUES('kerrymcelroy@dwt.com', 'jack.speer@alcoa.com, crow@millernash.com, michaelearly@earthlink.net,', 'Oral Argument Request', ' - Oral Argument Request.doc'); +INSERT INTO email([from],[to],subject,body) VALUES('mike.carson@enron.com', 'rlmichaelis@hormel.com', '', 'Did you come in town this wk end..... My new number at our house is : +713-668-3712...... my cell # is 281-381-7332 + +the kid'); +INSERT INTO email([from],[to],subject,body) VALUES('cooper.richey@enron.com', 'trycooper@hotmail.com', 'FW: Contact Info', ' + +-----Original Message----- +From: Punja, Karim +Sent: Thursday, December 13, 2001 2:35 PM +To: Richey, Cooper +Subject: Contact Info + + +Cooper, + +Its been a real pleasure working with you (even though it was for only a small amount of time) +I hope we can stay in touch. + +Home# 234-0249 +email: kpunja@hotmail.com + +Take Care, + +Karim. + '); +INSERT INTO email([from],[to],subject,body) VALUES('bjm30@earthlink.net', 'mcguinn.k@enron.com, mcguinn.ian@enron.com, mcguinn.stephen@enron.com,', 'email address change', 'Hello all. + +I haven''t talked to many of you via email recently but I do want to give you +my new address for your email file: + + bjm30@earthlink.net + +I hope all is well. + +Brian McGuinn'); +INSERT INTO email([from],[to],subject,body) VALUES('shelley.corman@enron.com', 'steve.hotte@enron.com', 'Flat Panels', 'Can you please advise what is going on with the flat panels that we had planned to distribute to our gas logistics team. It was in the budget and we had the okay, but now I''m hearing there is some hold-up & the units are stored on 44. + +Shelley'); +INSERT INTO email([from],[to],subject,body) VALUES('sara.davidson@enron.com', 'john.schwartzenburg@enron.com, scott.dieball@enron.com, recipients@enron.com,', '2001 Enron Law Conference (Distribution List 2)', ' Enron Law Conference + +San Antonio, Texas May 2-4, 2001 Westin Riverwalk + + See attached memo for more details!! + + +? Registration for the law conference this year will be handled through an +Online RSVP Form on the Enron Law Conference Website at +http://lawconference.corp.enron.com. The website is still under construction +and will not be available until Thursday, March 15, 2001. + +? We will send you another e-mail to confirm when the Law Conference Website +is operational. + +? Please complete the Online RSVP Form as soon as it is available and submit +it no later than Friday, March 30th. + + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('tori.kuykendall@enron.com', 'heath.b.taylor@accenture.com', 'Re:', 'hey - thats funny about john - he definitely remembers him - i''ll call pat +and let him know - we are coming on saturday - i just havent had a chance to +call you guys back -- looking forward to it -- i probably need the +directions again though'); +INSERT INTO email([from],[to],subject,body) VALUES('darron.giron@enron.com', 'bryce.baxter@enron.com', 'Re: Feedback for Audrey Cook', 'Bryce, + +I''ll get it done today. + +DG 3-9573 + + + + + + From: Bryce Baxter 06/12/2000 07:15 PM + + +To: Darron C Giron/HOU/ECT@ECT +cc: +Subject: Feedback for Audrey Cook + +You were identified as a reviewer for Audrey Cook. If possible, could you +complete her feedback by end of business Wednesday? It will really help me +in the PRC process to have your input. Thanks. + +'); +INSERT INTO email([from],[to],subject,body) VALUES('casey.evans@enron.com', 'stephanie.sever@enron.com', 'Gas EOL ID', 'Stephanie, + +In conjunction with the recent movement of several power traders, they are changing the names of their gas books as well. The names of the new gas books and traders are as follows: + +PWR-NG-LT-SPP: Mike Carson +PWR-NG-LT-SERC: Jeff King + +If you need to know their power desk to map their ID to their gas books, those desks are as follows: + +EPMI-LT-SPP: Mike Carson +EPMI-LT-SERC: Jeff King + +I will be in training this afternoon, but will be back when class is over. Let me know if you have any questions. + +Thanks for your help! +Casey'); +INSERT INTO email([from],[to],subject,body) VALUES('darrell.schoolcraft@enron.com', 'david.roensch@enron.com, kimberly.watson@enron.com, michelle.lokay@enron.com,', 'Postings', 'Please see the attached. + + +ds + + + + + '); +INSERT INTO email([from],[to],subject,body) VALUES('mcominsky@aol.com', 'cpatman@bracepatt.com, james_derrick@enron.com', 'Jurisprudence Luncheon', 'Carrin & Jim -- + +It was an honor and a pleasure to meet both of you yesterday. I know we will +have fun working together on this very special event. + +Jeff left the jurisprudence luncheon lists for me before he left on vacation. + I wasn''t sure whether he transmitted them to you as well. Would you please +advise me if you would like them sent to you? I can email the MS Excel files +or I can fax the hard copies to you. Please advise what is most convenient. + +I plan to be in town through the holidays and can be reached by phone, email, +or cell phone at any time. My cell phone number is 713/705-4829. + +Thanks again for your interest in the ADL''s work. Martin. + +Martin B. Cominsky +Director, Southwest Region +Anti-Defamation League +713/627-3490, ext. 122 +713/627-2011 (fax) +MCominsky@aol.com'); +INSERT INTO email([from],[to],subject,body) VALUES('phillip.love@enron.com', 'todagost@utmb.edu, gbsonnta@utmb.edu', 'New President', 'I had a little bird put a word in my ear. Is there any possibility for Ben +Raimer to be Bush''s secretary of HHS? Just curious about that infamous UTMB +rumor mill. Hope things are well, happy holidays. +PL'); +INSERT INTO email([from],[to],subject,body) VALUES('marie.heard@enron.com', 'ehamilton@fna.com', 'ISDA Master Agreement', 'Erin: + +Pursuant to your request, attached are the Schedule to the ISDA Master Agreement, together with Paragraph 13 to the ISDA Credit Support Annex. Please let me know if you need anything else. We look forward to hearing your comments. + +Marie + +Marie Heard +Senior Legal Specialist +Enron North America Corp. +Phone: (713) 853-3907 +Fax: (713) 646-3490 +marie.heard@enron.com + + '); +INSERT INTO email([from],[to],subject,body) VALUES('andrea.ring@enron.com', 'beverly.beaty@enron.com', 'Re: Tennessee Buy - Louis Dreyfus', 'Beverly - once again thanks so much for your help on this. + + + + '); +INSERT INTO email([from],[to],subject,body) VALUES('karolyn.criado@enron.com', 'j..bonin@enron.com, felicia.case@enron.com, b..clapp@enron.com,', 'Price List week of Oct. 8-9, 2001', ' +Please contact me if you have any questions regarding last weeks prices. + +Thank you, +Karolyn Criado +3-9441 + + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('kevin.presto@enron.com', 'edward.baughman@enron.com, billy.braddock@enron.com', 'Associated', 'Please begin working on filling our Associated short position in 02. I would like to take this risk off the books. + +In addition, please find out what a buy-out of VEPCO would cost us. With Rogers transitioning to run our retail risk management, I would like to clean up our customer positions. + +We also need to continue to explore a JEA buy-out. + +Thanks.'); +INSERT INTO email([from],[to],subject,body) VALUES('stacy.dickson@enron.com', 'gregg.penman@enron.com', 'RE: Constellation TC 5-7-01', 'Gregg, + +I am at home with a sick baby. (Lots of fun!) I will call you about this +tomorrow. + +Stacy'); +INSERT INTO email([from],[to],subject,body) VALUES('joe.quenet@enron.com', 'dfincher@utilicorp.com', '', 'hey big guy.....check this out..... + + w ww.gorelieberman-2000.com/'); +INSERT INTO email([from],[to],subject,body) VALUES('k..allen@enron.com', 'jacqestc@aol.com', '', 'Jacques, + +I sent you a fax of Kevin Kolb''s comments on the release. The payoff on the note would be $36,248 ($36090(principal) + $158 (accrued interest)). +This is assuming we wrap this up on Tuesday. + +Please email to confirm that their changes are ok so I can set up a meeting on Tuesday to reach closure. + +Phillip'); +INSERT INTO email([from],[to],subject,body) VALUES('kourtney.nelson@enron.com', 'mike.swerzbin@enron.com', 'Adjusted L/R Balance', 'Mike, + +I placed the adjusted L/R Balance on the Enronwest site. It is under the "Staff/Kourtney Nelson". There are two links: + +1) "Adj L_R" is the same data/format from the weekly strategy meeting. +2) "New Gen 2001_2002" link has all of the supply side info that is used to calculate the L/R balance + -Please note the Data Flag column, a value of "3" indicates the project was cancelled, on hold, etc and is not included in the calc. + +Both of these sheets are interactive Excel spreadsheets and thus you can play around with the data as you please. Also, James Bruce is working to get his gen report on the web. That will help with your access to information on new gen. + +Please let me know if you have any questions or feedback, + +Kourtney + + + +Kourtney Nelson +Fundamental Analysis +Enron North America +(503) 464-8280 +kourtney.nelson@enron.com'); +INSERT INTO email([from],[to],subject,body) VALUES('d..thomas@enron.com', 'naveed.ahmed@enron.com', 'FW: Current Enron TCC Portfolio', ' + +-----Original Message----- +From: Grace, Rebecca M. +Sent: Monday, December 17, 2001 9:44 AM +To: Thomas, Paul D. +Cc: Cashion, Jim; Allen, Thresa A.; May, Tom +Subject: RE: Current Enron TCC Portfolio + + +Paul, + +I reviewed NY''s list. I agree with all of their contracts numbers and mw amounts. + +Call if you have any more questions. + +Rebecca + + + + -----Original Message----- +From: Thomas, Paul D. +Sent: Monday, December 17, 2001 9:08 AM +To: Grace, Rebecca M. +Subject: FW: Current Enron TCC Portfolio + + << File: enrontccs.xls >> +Rebecca, +Let me know if you see any differences. + +Paul +X 3-0403 +-----Original Message----- +From: Thomas, Paul D. +Sent: Monday, December 17, 2001 9:04 AM +To: Ahmed, Naveed +Subject: FW: Current Enron TCC Portfolio + + + + +-----Original Message----- +From: Thomas, Paul D. +Sent: Thursday, December 13, 2001 10:01 AM +To: Baughman, Edward D. +Subject: Current Enron TCC Portfolio + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('stephanie.panus@enron.com', 'william.bradford@enron.com, debbie.brackett@enron.com,', 'Coastal Merchant Energy/El Paso Merchant Energy', 'Coastal Merchant Energy, L.P. merged with and into El Paso Merchant Energy, +L.P., effective February 1, 2001, with the surviving entity being El Paso +Merchant Energy, L.P. We currently have ISDA Master Agreements with both +counterparties. Please see the attached memo regarding the existing Masters +and let us know which agreement should be terminated. + +Thanks, +Stephanie +'); +INSERT INTO email([from],[to],subject,body) VALUES('kam.keiser@enron.com', 'c..kenne@enron.com', 'RE: What about this too???', ' + + -----Original Message----- +From: Kenne, Dawn C. +Sent: Wednesday, February 06, 2002 11:50 AM +To: Keiser, Kam +Subject: What about this too??? + + + << File: Netco Trader Matrix.xls >> + '); +INSERT INTO email([from],[to],subject,body) VALUES('chris.meyer@enron.com', 'joe.parks@enron.com', 'Centana', 'Talked to Chip. We do need Cash Committe approval given the netting feature of your deal, which means Batch Funding Request. Please update per my previous e-mail and forward. + +Thanks + +chris +x31666'); +INSERT INTO email([from],[to],subject,body) VALUES('debra.perlingiere@enron.com', 'jworman@academyofhealth.com', '', 'Have a great weekend! Happy Fathers Day! + + +Debra Perlingiere +Enron North America Corp. +1400 Smith Street, EB 3885 +Houston, Texas 77002 +dperlin@enron.com +Phone 713-853-7658 +Fax 713-646-3490'); +INSERT INTO email([from],[to],subject,body) VALUES('outlook.team@enron.com', '', 'Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia &', 'CALENDAR ENTRY: APPOINTMENT + +Description: + Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia & Dir Rpts. - 4102 + +Date: 1/5/2001 +Time: 9:00 AM - 10:00 AM (Central Standard Time) + +Chairperson: Outlook Migration Team + +Detailed Description:'); +INSERT INTO email([from],[to],subject,body) VALUES('diana.seifert@enron.com', 'mark.taylor@enron.com', 'Guest access Chile', 'Hello Mark, + +Justin Boyd told me that your can help me with questions regarding Chile. +We got a request for guest access through MG. +The company is called Escondida and is a subsidiary of BHP Australia. + +Please advise if I can set up a guest account or not. +F.Y.I.: MG is planning to put a "in w/h Chile" contract for Copper on-line as +soon as Enron has done the due diligence for this country. +Thanks ! + + +Best regards + +Diana Seifert +EOL PCG'); +INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'mark.whitt@enron.com', '<> - 121001', 'The Approval status has changed on the following report: + +Status last changed by: Barry L. Tycholiz +Expense Report Name: 121001 +Report Total: $198.98 +Amount Due Employee: $198.98 +Amount Approved: $198.98 +Amount Paid: $0.00 +Approval Status: Approved +Payment Status: Pending + + +To review this expense report, click on the following link for Concur Expense. +http://expensexms.enron.com'); +INSERT INTO email([from],[to],subject,body) VALUES('kevin.hyatt@enron.com', '', 'Technical Support', 'Outside the U.S., please refer to the list below: + +Australia: +1800 678-515 +support@palm-au.com + +Canada: +1905 305-6530 +support@palm.com + +New Zealand: +0800 446-398 +support@palm-nz.com + +U.K.: +0171 867 0108 +eurosupport@palm.3com.com + +Please refer to the Worldwide Customer Support card for a complete technical support contact list.'); +INSERT INTO email([from],[to],subject,body) VALUES('geoff.storey@enron.com', 'dutch.quigley@enron.com', 'RE:', 'duke contact? + + -----Original Message----- +From: Quigley, Dutch +Sent: Wednesday, October 31, 2001 10:14 AM +To: Storey, Geoff +Subject: RE: + +bp corp Albert LaMore 281-366-4962 + +running the reports now + + + -----Original Message----- +From: Storey, Geoff +Sent: Wednesday, October 31, 2001 10:10 AM +To: Quigley, Dutch +Subject: RE: + +give me a contact over there too +BP + + + -----Original Message----- +From: Quigley, Dutch +Sent: Wednesday, October 31, 2001 9:42 AM +To: Storey, Geoff +Subject: + +Coral Jeff Whitnah 713-767-5374 +Relaint Steve McGinn 713-207-4000'); +INSERT INTO email([from],[to],subject,body) VALUES('pete.davis@enron.com', 'pete.davis@enron.com', 'Start Date: 4/22/01; HourAhead hour: 3; ', 'Start Date: 4/22/01; HourAhead hour: 3; No ancillary schedules awarded. +Variances detected. +Variances detected in Load schedule. + + LOG MESSAGES: + +PARSING FILE -->> O:\Portland\WestDesk\California Scheduling\ISO Final +Schedules\2001042203.txt + +---- Load Schedule ---- +$$$ Variance found in table tblLoads. + Details: (Hour: 3 / Preferred: 1.92 / Final: 1.89) + TRANS_TYPE: FINAL + LOAD_ID: PGE4 + MKT_TYPE: 2 + TRANS_DATE: 4/22/01 + SC_ID: EPMI + +'); +INSERT INTO email([from],[to],subject,body) VALUES('john.postlethwaite@enron.com', 'john.zufferli@enron.com', 'Reference', 'John, hope things are going well up there for you. The big day is almost here for you and Jessica. I was wondering if I could use your name as a job reference if need be. I am just trying to get everything in order just in case something happens. + +John'); +INSERT INTO email([from],[to],subject,body) VALUES('jeffrey.shankman@enron.com', 'lschiffm@jonesday.com', 'Re:', 'I saw you called on the cell this a.m. Sorry I missed you. (I was in the +shower). I have had a shitty week--I suspect my silence (not only to you, +but others) after our phone call is a result of the week. I''m seeing Glen at +11:15....talk to you'); +INSERT INTO email([from],[to],subject,body) VALUES('litebytz@enron.com', '', 'Lite Bytz RSVP', ' +This week''s Lite Bytz presentation will feature the following TOOLZ speaker: + +Richard McDougall +Solaris 8 +Thursday, June 7, 2001 + +If you have not already signed up, please RSVP via email to litebytz@enron.com by the end of the day Tuesday, June 5, 2001. + +*Remember: this is now a Brown Bag Event--so bring your lunch and we will provide cookies and drinks. + +Click below for more details. + +http://home.enron.com:84/messaging/litebytztoolzprint.jpg'); + COMMIT; + } +} {} + +############################################################################### +# Everything above just builds an interesting test database. The actual +# tests come after this comment. +############################################################################### + +do_test fts1c-1.2 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark' + } +} {6 17 25 38 40 42 73 74} +do_test fts1c-1.3 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'susan' + } +} {24 40} +do_test fts1c-1.4 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark susan' + } +} {40} +do_test fts1c-1.5 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'susan mark' + } +} {40} +do_test fts1c-1.6 { + execsql { + SELECT rowid FROM email WHERE email MATCH '"mark susan"' + } +} {} +do_test fts1c-1.7 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark -susan' + } +} {6 17 25 38 42 73 74} +do_test fts1c-1.8 { + execsql { + SELECT rowid FROM email WHERE email MATCH '-mark susan' + } +} {24} +do_test fts1c-1.9 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark OR susan' + } +} {6 17 24 25 38 40 42 73 74} + +# Some simple tests of the automatic "offsets(email)" column. In the sample +# data set above, only one message, number 20, contains the words +# "gas" and "reminder" in both body and subject. +# +do_test fts1c-2.1 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE email MATCH 'gas reminder' + } +} {20 {2 0 42 3 2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}} +do_test fts1c-2.2 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE email MATCH 'subject:gas reminder' + } +} {20 {2 0 42 3 2 1 54 8 3 1 54 8}} +do_test fts1c-2.3 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE email MATCH 'body:gas reminder' + } +} {20 {2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}} +do_test fts1c-2.4 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE subject MATCH 'gas reminder' + } +} {20 {2 0 42 3 2 1 54 8}} +do_test fts1c-2.5 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE body MATCH 'gas reminder' + } +} {20 {3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}} + +# Document 32 contains 5 instances of the world "child". But only +# 3 of them are paired with "product". Make sure only those instances +# that match the phrase appear in the offsets(email) list. +# +do_test fts1c-3.1 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE body MATCH 'child product' AND +rowid=32 + } +} {32 {3 0 94 5 3 0 114 5 3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7 3 1 493 7}} +do_test fts1c-3.2 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE body MATCH '"child product"' + } +} {32 {3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7}} + +# Snippet generator tests +# +do_test fts1c-4.1 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'subject:gas reminder' + } +} {{Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder}} +do_test fts1c-4.2 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'christmas candlelight' + } +} {{... place.? What do you think about going here Christmas +eve?? They have an 11:00 a.m. service and a candlelight service at 5:00 p.m., +among others. ...}} + +do_test fts1c-4.3 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'deal sheet potential reuse' + } +} {{EOL-Accenture Deal Sheet ... intent + Review Enron asset base for potential reuse/ licensing + Contract negotiations ...}} +do_test fts1c-4.4 { + execsql { + SELECT snippet(email,'<<<','>>>',' ') FROM email + WHERE email MATCH 'deal sheet potential reuse' + } +} {{EOL-Accenture <<>> <<>> intent + Review Enron asset base for <<>> <<>>/ licensing + Contract negotiations }} +do_test fts1c-4.5 { + execsql { + SELECT snippet(email,'<<<','>>>',' ') FROM email + WHERE email MATCH 'first things' + } +} {{Re: <<>> Polish Deal! Congrats! <<>> seem to be building rapidly now on the }} +do_test fts1c-4.6 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'chris is here' + } +} {{chris.germany@enron.com ... Sounds good to me. I bet this is next to the Warick?? Hotel. ... place.? What do you think about going here Christmas +eve?? They have an 11:00 a.m. ...}} +do_test fts1c-4.7 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH '"pursuant to"' + } +} {{Erin: + +Pursuant to your request, attached are the Schedule to ...}} +do_test fts1c-4.8 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'ancillary load davis' + } +} {{pete.davis@enron.com ... Start Date: 4/22/01; HourAhead hour: 3; No ancillary schedules awarded. +Variances detected. +Variances detected in Load schedule. + + LOG MESSAGES: + +PARSING ...}} + +# Combinations of AND and OR operators: +# +do_test fts1c-5.1 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'questar enron OR com' + } +} {{matt.smith@enron.com ... six reports: + +31 Keystone Receipts +15 Questar Pipeline +40 Rockies Production +22 West_2 ...}} +do_test fts1c-5.2 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'enron OR com questar' + } +} {{matt.smith@enron.com ... six reports: + +31 Keystone Receipts +15 Questar Pipeline +40 Rockies Production +22 West_2 ...}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1d.test b/components/external/SQLite-3.8.1/test/fts1d.test new file mode 100644 index 0000000000000000000000000000000000000000..ea2303489ce101220287e4be82ae52f222775193 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1d.test @@ -0,0 +1,65 @@ +# 2006 October 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS1 module, and in particular +# the Porter stemmer. +# +# $Id: fts1d.test,v 1.1 2006/10/01 18:41:21 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +do_test fts1d-1.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts1(content, tokenize porter); + INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping'); + SELECT rowid FROM t1 WHERE content MATCH 'run jump'; + } +} {1} +do_test fts1d-1.2 { + execsql { + SELECT snippet(t1) FROM t1 WHERE t1 MATCH 'run jump'; + } +} {{running and jumping}} +do_test fts1d-1.3 { + execsql { + INSERT INTO t1(rowid, content) + VALUES(2, 'abcdefghijklmnopqrstuvwyxz'); + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijqrstuvwyxz' + } +} {2 abcdefghijklmnopqrstuvwyxz} +do_test fts1d-1.4 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijXXXXqrstuvwyxz' + } +} {2 abcdefghijklmnopqrstuvwyxz} +do_test fts1d-1.5 { + execsql { + INSERT INTO t1(rowid, content) + VALUES(3, 'The value is 123456789'); + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123789' + } +} {3 {The value is 123456789}} +do_test fts1d-1.6 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123000000789' + } +} {3 {The value is 123456789}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1e.test b/components/external/SQLite-3.8.1/test/fts1e.test new file mode 100644 index 0000000000000000000000000000000000000000..479cfac91d01b6dc397d9afd57d57165d610d3a7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1e.test @@ -0,0 +1,85 @@ +# 2006 October 19 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing deletions in the FTS1 module. +# +# $Id: fts1e.test,v 1.1 2006/10/19 23:28:35 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +# Construct a full-text search table containing keywords which are the +# ordinal numbers of the bit positions set for a sequence of integers, +# which are used for the rowid. There are a total of 30 INSERT and +# DELETE statements, so that we'll test both the segmentMerge() merge +# (over the first 16) and the termSelect() merge (over the level-1 +# segment and 14 level-0 segments). +db eval { + CREATE VIRTUAL TABLE t1 USING fts1(content); + INSERT INTO t1 (rowid, content) VALUES(1, 'one'); + INSERT INTO t1 (rowid, content) VALUES(2, 'two'); + INSERT INTO t1 (rowid, content) VALUES(3, 'one two'); + INSERT INTO t1 (rowid, content) VALUES(4, 'three'); + DELETE FROM t1 WHERE rowid = 1; + INSERT INTO t1 (rowid, content) VALUES(5, 'one three'); + INSERT INTO t1 (rowid, content) VALUES(6, 'two three'); + INSERT INTO t1 (rowid, content) VALUES(7, 'one two three'); + DELETE FROM t1 WHERE rowid = 4; + INSERT INTO t1 (rowid, content) VALUES(8, 'four'); + INSERT INTO t1 (rowid, content) VALUES(9, 'one four'); + INSERT INTO t1 (rowid, content) VALUES(10, 'two four'); + DELETE FROM t1 WHERE rowid = 7; + INSERT INTO t1 (rowid, content) VALUES(11, 'one two four'); + INSERT INTO t1 (rowid, content) VALUES(12, 'three four'); + INSERT INTO t1 (rowid, content) VALUES(13, 'one three four'); + DELETE FROM t1 WHERE rowid = 10; + INSERT INTO t1 (rowid, content) VALUES(14, 'two three four'); + INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four'); + INSERT INTO t1 (rowid, content) VALUES(16, 'five'); + DELETE FROM t1 WHERE rowid = 13; + INSERT INTO t1 (rowid, content) VALUES(17, 'one five'); + INSERT INTO t1 (rowid, content) VALUES(18, 'two five'); + INSERT INTO t1 (rowid, content) VALUES(19, 'one two five'); + DELETE FROM t1 WHERE rowid = 16; + INSERT INTO t1 (rowid, content) VALUES(20, 'three five'); + INSERT INTO t1 (rowid, content) VALUES(21, 'one three five'); + INSERT INTO t1 (rowid, content) VALUES(22, 'two three five'); + DELETE FROM t1 WHERE rowid = 19; + DELETE FROM t1 WHERE rowid = 22; +} + +do_test fts1f-1.1 { + execsql {SELECT COUNT(*) FROM t1} +} {14} + +do_test fts1e-2.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {3 5 9 11 15 17 21} + +do_test fts1e-2.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'} +} {2 3 6 11 14 15 18} + +do_test fts1e-2.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'} +} {5 6 12 14 15 20 21} + +do_test fts1e-2.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'} +} {8 9 11 12 14 15} + +do_test fts1e-2.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'} +} {17 18 20 21} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1f.test b/components/external/SQLite-3.8.1/test/fts1f.test new file mode 100644 index 0000000000000000000000000000000000000000..19dea0a32958b2500ccd62063ddc75af3dd14eb9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1f.test @@ -0,0 +1,90 @@ +# 2006 October 19 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing updates in the FTS1 module. +# +# $Id: fts1f.test,v 1.2 2007/02/23 00:14:06 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +# Construct a full-text search table containing keywords which are the +# ordinal numbers of the bit positions set for a sequence of integers, +# which are used for the rowid. There are a total of 31 INSERT, +# UPDATE, and DELETE statements, so that we'll test both the +# segmentMerge() merge (over the first 16) and the termSelect() merge +# (over the level-1 segment and 15 level-0 segments). +db eval { + CREATE VIRTUAL TABLE t1 USING fts1(content); + INSERT INTO t1 (rowid, content) VALUES(1, 'one'); + INSERT INTO t1 (rowid, content) VALUES(2, 'two'); + INSERT INTO t1 (rowid, content) VALUES(3, 'one two'); + INSERT INTO t1 (rowid, content) VALUES(4, 'three'); + INSERT INTO t1 (rowid, content) VALUES(5, 'one three'); + INSERT INTO t1 (rowid, content) VALUES(6, 'two three'); + INSERT INTO t1 (rowid, content) VALUES(7, 'one two three'); + DELETE FROM t1 WHERE rowid = 4; + INSERT INTO t1 (rowid, content) VALUES(8, 'four'); + UPDATE t1 SET content = 'update one three' WHERE rowid = 1; + INSERT INTO t1 (rowid, content) VALUES(9, 'one four'); + INSERT INTO t1 (rowid, content) VALUES(10, 'two four'); + DELETE FROM t1 WHERE rowid = 7; + INSERT INTO t1 (rowid, content) VALUES(11, 'one two four'); + INSERT INTO t1 (rowid, content) VALUES(12, 'three four'); + INSERT INTO t1 (rowid, content) VALUES(13, 'one three four'); + DELETE FROM t1 WHERE rowid = 10; + INSERT INTO t1 (rowid, content) VALUES(14, 'two three four'); + INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four'); + UPDATE t1 SET content = 'update two five' WHERE rowid = 8; + INSERT INTO t1 (rowid, content) VALUES(16, 'five'); + DELETE FROM t1 WHERE rowid = 13; + INSERT INTO t1 (rowid, content) VALUES(17, 'one five'); + INSERT INTO t1 (rowid, content) VALUES(18, 'two five'); + INSERT INTO t1 (rowid, content) VALUES(19, 'one two five'); + DELETE FROM t1 WHERE rowid = 16; + INSERT INTO t1 (rowid, content) VALUES(20, 'three five'); + INSERT INTO t1 (rowid, content) VALUES(21, 'one three five'); + INSERT INTO t1 (rowid, content) VALUES(22, 'two three five'); + DELETE FROM t1 WHERE rowid = 19; + UPDATE t1 SET content = 'update' WHERE rowid = 15; +} + +do_test fts1f-1.1 { + execsql {SELECT COUNT(*) FROM t1} +} {16} + +do_test fts1f-2.0 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'update'} +} {1 8 15} + +do_test fts1f-2.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {1 3 5 9 11 17 21} + +do_test fts1f-2.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'} +} {2 3 6 8 11 14 18 22} + +do_test fts1f-2.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'} +} {1 5 6 12 14 20 21 22} + +do_test fts1f-2.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'} +} {9 11 12 14} + +do_test fts1f-2.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'} +} {8 17 18 20 21 22} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1i.test b/components/external/SQLite-3.8.1/test/fts1i.test new file mode 100644 index 0000000000000000000000000000000000000000..803b93bf2944c288a15e6a47afe8a3a159b75e1b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1i.test @@ -0,0 +1,88 @@ +# 2007 January 17 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite fts1 library. The +# focus here is testing handling of UPDATE when using UTF-16-encoded +# databases. +# +# $Id: fts1i.test,v 1.2 2007/01/24 03:43:20 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + + +# Return the UTF-16 representation of the supplied UTF-8 string $str. +# If $nt is true, append two 0x00 bytes as a nul terminator. +# NOTE(shess) Copied from capi3.test. +proc utf16 {str {nt 1}} { + set r [encoding convertto unicode $str] + if {$nt} { + append r "\x00\x00" + } + return $r +} + +db eval { + PRAGMA encoding = "UTF-16le"; + CREATE VIRTUAL TABLE t1 USING fts1(content); +} + +do_test fts1i-1.0 { + execsql {PRAGMA encoding} +} {UTF-16le} + +do_test fts1i-1.1 { + execsql {INSERT INTO t1 (rowid, content) VALUES(1, 'one')} + execsql {SELECT content FROM t1 WHERE rowid = 1} +} {one} + +do_test fts1i-1.2 { + set sql "INSERT INTO t1 (rowid, content) VALUES(2, 'two')" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 2} +} {two} + +do_test fts1i-1.3 { + set sql "INSERT INTO t1 (rowid, content) VALUES(3, 'three')" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + set sql "UPDATE t1 SET content = 'trois' WHERE rowid = 3" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 3} +} {trois} + +do_test fts1i-1.4 { + set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(4, 'four')}] + set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 4} +} {four} + +do_test fts1i-1.5 { + set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(5, 'five')}] + set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + set sql "UPDATE t1 SET content = 'cinq' WHERE rowid = 5" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 5} +} {cinq} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1j.test b/components/external/SQLite-3.8.1/test/fts1j.test new file mode 100644 index 0000000000000000000000000000000000000000..4dac22abbfe82c89d6c93c0886d16e655955d893 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1j.test @@ -0,0 +1,89 @@ +# 2007 February 6 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. This +# tests creating fts1 tables in an attached database. +# +# $Id: fts1j.test,v 1.1 2007/02/07 01:01:18 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +# Clean up anything left over from a previous pass. +forcedelete test2.db +forcedelete test2.db-journal +sqlite3 db2 test2.db + +db eval { + CREATE VIRTUAL TABLE t3 USING fts1(content); + INSERT INTO t3 (rowid, content) VALUES(1, "hello world"); +} + +db2 eval { + CREATE VIRTUAL TABLE t1 USING fts1(content); + INSERT INTO t1 (rowid, content) VALUES(1, "hello world"); + INSERT INTO t1 (rowid, content) VALUES(2, "hello there"); + INSERT INTO t1 (rowid, content) VALUES(3, "cruel world"); +} + +# This has always worked because the t1_* tables used by fts1 will be +# the defaults. +do_test fts1j-1.1 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + SELECT rowid FROM t1 WHERE t1 MATCH 'hello'; + DETACH DATABASE two; + } +} {1 2} +# Make certain we're detached if there was an error. +catch {db eval {DETACH DATABASE two}} + +# In older code, this appears to work fine, but the t2_* tables used +# by fts1 will be created in database 'main' instead of database +# 'two'. It appears to work fine because the tables end up being the +# defaults, but obviously is badly broken if you hope to use things +# other than in the exact same ATTACH setup. +do_test fts1j-1.2 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + CREATE VIRTUAL TABLE two.t2 USING fts1(content); + INSERT INTO t2 (rowid, content) VALUES(1, "hello world"); + INSERT INTO t2 (rowid, content) VALUES(2, "hello there"); + INSERT INTO t2 (rowid, content) VALUES(3, "cruel world"); + SELECT rowid FROM t2 WHERE t2 MATCH 'hello'; + DETACH DATABASE two; + } +} {1 2} +catch {db eval {DETACH DATABASE two}} + +# In older code, this broke because the fts1 code attempted to create +# t3_* tables in database 'main', but they already existed. Normally +# this wouldn't happen without t3 itself existing, in which case the +# fts1 code would never be called in the first place. +do_test fts1j-1.3 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + + CREATE VIRTUAL TABLE two.t3 USING fts1(content); + INSERT INTO two.t3 (rowid, content) VALUES(2, "hello there"); + INSERT INTO two.t3 (rowid, content) VALUES(3, "cruel world"); + SELECT rowid FROM two.t3 WHERE t3 MATCH 'hello'; + + DETACH DATABASE two; + } db2 +} {2} +catch {db eval {DETACH DATABASE two}} + +catch {db2 close} +forcedelete test2.db + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1k.test b/components/external/SQLite-3.8.1/test/fts1k.test new file mode 100644 index 0000000000000000000000000000000000000000..35b94d2ae7ea734bfaffd9767d21530f4f849a5d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1k.test @@ -0,0 +1,69 @@ +# 2007 March 28 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing isspace/isalnum/tolower problems with the +# FTS1 module. Unfortunately, this code isn't a really principled set +# of tests, because it is impossible to know where new uses of these +# functions might appear. +# +# $Id: fts1k.test,v 1.2 2007/12/13 21:54:11 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +# Tests that startsWith() (calls isspace, tolower, isalnum) can handle +# hi-bit chars. parseSpec() also calls isalnum here. +do_test fts1k-1.1 { + execsql "CREATE VIRTUAL TABLE t1 USING fts1(content, \x80)" +} {} + +# Additionally tests isspace() call in getToken(), and isalnum() call +# in tokenListToIdList(). +do_test fts1k-1.2 { + catch { + execsql "CREATE VIRTUAL TABLE t2 USING fts1(content, tokenize \x80)" + } + sqlite3_errmsg $DB +} "unknown tokenizer: \x80" + +# Additionally test final isalnum() in startsWith(). +do_test fts1k-1.3 { + execsql "CREATE VIRTUAL TABLE t3 USING fts1(content, tokenize\x80)" +} {} + +# The snippet-generation code has calls to isspace() which are sort of +# hard to get to. It finds convenient breakpoints by starting ~40 +# chars before and after the matched term, and scanning ~10 chars +# around that position for isspace() characters. The long word with +# embedded hi-bit chars causes one of these isspace() calls to be +# exercised. The version with a couple extra spaces should cause the +# other isspace() call to be exercised. [Both cases have been tested +# in the debugger, but I'm hoping to continue to catch it if simple +# constant changes change things slightly. +# +# The trailing and leading hi-bit chars help with code which tests for +# isspace() to coalesce multiple spaces. + +set word "\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80" +set phrase1 "$word $word $word target $word $word $word" +set phrase2 "$word $word $word target $word $word $word" + +db eval {CREATE VIRTUAL TABLE t4 USING fts1(content)} +db eval "INSERT INTO t4 (content) VALUES ('$phrase1')" +db eval "INSERT INTO t4 (content) VALUES ('$phrase2')" + +do_test fts1k-1.4 { + execsql {SELECT rowid, length(snippet(t4)) FROM t4 WHERE t4 MATCH 'target'} +} {1 111 2 117} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1l.test b/components/external/SQLite-3.8.1/test/fts1l.test new file mode 100644 index 0000000000000000000000000000000000000000..924be3380132f2d8698e391e219cabe91096ab8e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1l.test @@ -0,0 +1,65 @@ +# 2007 April 9 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. fts1 +# DELETE handling assumed all fields were non-null. This was not +# the intention at all. +# +# $Id: fts1l.test,v 1.1 2007/04/09 20:45:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts1(col_a, col_b); + + INSERT INTO t1(rowid, col_a, col_b) VALUES(1, 'testing', 'testing'); + INSERT INTO t1(rowid, col_a, col_b) VALUES(2, 'only a', null); + INSERT INTO t1(rowid, col_a, col_b) VALUES(3, null, 'only b'); + INSERT INTO t1(rowid, col_a, col_b) VALUES(4, null, null); +} + +do_test fts1m-1.0 { + execsql { + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {2 2 4} + +do_test fts1m-1.1 { + execsql { + DELETE FROM t1 WHERE rowid = 1; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {1 1 3} + +do_test fts1m-1.2 { + execsql { + DELETE FROM t1 WHERE rowid = 2; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {0 1 2} + +do_test fts1m-1.3 { + execsql { + DELETE FROM t1 WHERE rowid = 3; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {0 0 1} + +do_test fts1m-1.4 { + execsql { + DELETE FROM t1 WHERE rowid = 4; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {0 0 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1m.test b/components/external/SQLite-3.8.1/test/fts1m.test new file mode 100644 index 0000000000000000000000000000000000000000..c2f8f915a1d9a0f2781fd97cb3d634274a8c0efa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1m.test @@ -0,0 +1,50 @@ +# 2007 July 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing the FTS1 module, specifically snippet +# generation. Extracted from fts2o.test. +# +# $Id: fts1m.test,v 1.1 2007/07/25 00:25:20 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is not defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +#--------------------------------------------------------------------- +# These tests, fts1m-1.*, test that ticket #2429 is fixed. +# +db eval { + CREATE VIRTUAL TABLE t1 USING fts1(a, b, c); + INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one four two'); +} +do_test fts1m-1.1 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE c MATCH 'four'; + } +} {1 {one four two}} +do_test fts1m-1.2 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE b MATCH 'four'; + } +} {1 {one four}} +do_test fts1m-1.3 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE a MATCH 'four'; + } +} {1 {one three four}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1n.test b/components/external/SQLite-3.8.1/test/fts1n.test new file mode 100644 index 0000000000000000000000000000000000000000..2f102b4e2cd758200a00b72a1723c4184731bcae --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1n.test @@ -0,0 +1,45 @@ +# 2007 July 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing the FTS1 module for errors in the handling +# of SQLITE_SCHEMA. +# +# $Id: fts1n.test,v 1.1 2007/07/25 00:38:06 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is not defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +do_test fts1m-1.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts1(a, b, c); + INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one two'); + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + } +} {{one three four} {one four} {one two}} + +# This test was crashing at one point. +# +do_test fts1m-1.2 { + execsql { + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + CREATE TABLE t3(a, b, c); + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + } +} {{one three four} {one four} {one two} {one three four} {one four} {one two}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1o.test b/components/external/SQLite-3.8.1/test/fts1o.test new file mode 100644 index 0000000000000000000000000000000000000000..61fd74ca0efc4c6b1733a180f7d998e5fe2e23f3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1o.test @@ -0,0 +1,138 @@ +# 2007 July 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing the FTS1 module rename functionality. Mostly +# copied from fts2o.test. +# +# $Id: fts1o.test,v 1.2 2007/08/30 20:01:33 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is not defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts1(a, b, c); + INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one four two'); +} + +#--------------------------------------------------------------------- +# Test that it is possible to rename an fts1 table. +# +do_test fts1o-1.1 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {t1 t1_content t1_term} +do_test fts1o-1.2 { + execsql { ALTER TABLE t1 RENAME to fts_t1; } +} {} +do_test fts1o-1.3 { + execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; } +} {1 {one three four}} +do_test fts1o-1.4 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {fts_t1 fts_t1_content fts_t1_term} + +# See what happens when renaming the fts1 table fails. +# +do_test fts1o-2.1 { + catchsql { + CREATE TABLE t1_term(a, b, c); + ALTER TABLE fts_t1 RENAME to t1; + } +} {1 {SQL logic error or missing database}} +do_test fts1o-2.2 { + execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; } +} {1 {one three four}} +do_test fts1o-2.3 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {fts_t1 fts_t1_content fts_t1_term t1_term} + +# See what happens when renaming the fts1 table fails inside a transaction. +# +do_test fts1o-3.1 { + execsql { + BEGIN; + INSERT INTO fts_t1(a, b, c) VALUES('one two three', 'one four', 'one two'); + } +} {} +do_test fts1o-3.2 { + catchsql { + ALTER TABLE fts_t1 RENAME to t1; + } +} {1 {SQL logic error or missing database}} +# NOTE(shess) rowid AS rowid to defeat caching. Otherwise, this +# seg-faults, I suspect that there's something up with a stale +# virtual-table reference, but I'm not quite sure how it happens here +# but not for fts2o.test. +do_test fts1o-3.3 { + execsql { SELECT rowid AS rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; } +} {1 {one three four}} +do_test fts1o-3.4 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {fts_t1 fts_t1_content fts_t1_term t1_term} +do_test fts1o-3.5 { + execsql COMMIT + execsql {SELECT a FROM fts_t1} +} {{one three four} {one two three}} +do_test fts1o-3.6 { + execsql { SELECT a, b, c FROM fts_t1 WHERE c MATCH 'four'; } +} {{one three four} {one four} {one four two}} + +#--------------------------------------------------------------------- +# Test that it is possible to rename an fts1 table in an attached +# database. +# +forcedelete test2.db test2.db-journal + +do_test fts1o-4.1 { + execsql { + DROP TABLE t1_term; + ALTER TABLE fts_t1 RENAME to t1; + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + } +} {{one three four} {one four} {one four two} {one two three} {one four} {one two}} + +do_test fts1o-4.2 { + execsql { + ATTACH 'test2.db' AS aux; + CREATE VIRTUAL TABLE aux.t1 USING fts1(a, b, c); + INSERT INTO aux.t1(a, b, c) VALUES( + 'neung song sahm', 'neung see', 'neung see song' + ); + } +} {} + +do_test fts1o-4.3 { + execsql { SELECT a, b, c FROM aux.t1 WHERE a MATCH 'song'; } +} {{neung song sahm} {neung see} {neung see song}} + +do_test fts1o-4.4 { + execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; } +} {{one three four} {one four} {one four two} {one two three} {one four} {one two}} + +do_test fts1o-4.5 { + execsql { ALTER TABLE aux.t1 RENAME TO t2 } +} {} + +do_test fts1o-4.6 { + execsql { SELECT a, b, c FROM t2 WHERE a MATCH 'song'; } +} {{neung song sahm} {neung see} {neung see song}} + +do_test fts1o-4.7 { + execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; } +} {{one three four} {one four} {one four two} {one two three} {one four} {one two}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts1porter.test b/components/external/SQLite-3.8.1/test/fts1porter.test new file mode 100644 index 0000000000000000000000000000000000000000..0ca87a01edfa4fcdccef62450f46572c7e872aaf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts1porter.test @@ -0,0 +1,23590 @@ +# 2006 October 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS1 module, and in particular +# the Porter stemmer. +# +# $Id: fts1porter.test,v 1.5 2006/10/03 19:37:37 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS1 is defined, omit this file. +ifcapable !fts1 { + finish_test + return +} + +# Test data for the Porter stemmer. The first word of each line +# is the input. The second word is the desired output. +# +# This test data is taken from http://www.tartarus.org/martin/PorterStemmer/ +# There is no claim of copyright made on that page, but you should +# probably contact the author (Martin Porter - the inventor of the +# Porter Stemmer algorithm) if you want to use this test data in a +# commerical product of some kind. The stemmer code in FTS1 is a +# complete rewrite from scratch based on the algorithm specification +# and does not contain any code under copyright. +# +set porter_test_data { + a a + aaron aaron + abaissiez abaissiez + abandon abandon + abandoned abandon + abase abas + abash abash + abate abat + abated abat + abatement abat + abatements abat + abates abat + abbess abbess + abbey abbei + abbeys abbei + abbominable abbomin + abbot abbot + abbots abbot + abbreviated abbrevi + abed ab + abel abel + aberga aberga + abergavenny abergavenni + abet abet + abetting abet + abhominable abhomin + abhor abhor + abhorr abhorr + abhorred abhor + abhorring abhor + abhors abhor + abhorson abhorson + abide abid + abides abid + abilities abil + ability abil + abject abject + abjectly abjectli + abjects abject + abjur abjur + abjure abjur + able abl + abler abler + aboard aboard + abode abod + aboded abod + abodements abod + aboding abod + abominable abomin + abominably abomin + abominations abomin + abortive abort + abortives abort + abound abound + abounding abound + about about + above abov + abr abr + abraham abraham + abram abram + abreast abreast + abridg abridg + abridge abridg + abridged abridg + abridgment abridg + abroach abroach + abroad abroad + abrogate abrog + abrook abrook + abrupt abrupt + abruption abrupt + abruptly abruptli + absence absenc + absent absent + absey absei + absolute absolut + absolutely absolut + absolv absolv + absolver absolv + abstains abstain + abstemious abstemi + abstinence abstin + abstract abstract + absurd absurd + absyrtus absyrtu + abundance abund + abundant abund + abundantly abundantli + abus abu + abuse abus + abused abus + abuser abus + abuses abus + abusing abus + abutting abut + aby abi + abysm abysm + ac ac + academe academ + academes academ + accent accent + accents accent + accept accept + acceptable accept + acceptance accept + accepted accept + accepts accept + access access + accessary accessari + accessible access + accidence accid + accident accid + accidental accident + accidentally accident + accidents accid + accite accit + accited accit + accites accit + acclamations acclam + accommodate accommod + accommodated accommod + accommodation accommod + accommodations accommod + accommodo accommodo + accompanied accompani + accompany accompani + accompanying accompani + accomplices accomplic + accomplish accomplish + accomplished accomplish + accomplishing accomplish + accomplishment accomplish + accompt accompt + accord accord + accordant accord + accorded accord + accordeth accordeth + according accord + accordingly accordingli + accords accord + accost accost + accosted accost + account account + accountant account + accounted account + accounts account + accoutred accoutr + accoutrement accoutr + accoutrements accoutr + accrue accru + accumulate accumul + accumulated accumul + accumulation accumul + accurs accur + accursed accurs + accurst accurst + accus accu + accusation accus + accusations accus + accusative accus + accusativo accusativo + accuse accus + accused accus + accuser accus + accusers accus + accuses accus + accuseth accuseth + accusing accus + accustom accustom + accustomed accustom + ace ac + acerb acerb + ache ach + acheron acheron + aches ach + achiev achiev + achieve achiev + achieved achiev + achievement achiev + achievements achiev + achiever achiev + achieves achiev + achieving achiev + achilles achil + aching ach + achitophel achitophel + acknowledg acknowledg + acknowledge acknowledg + acknowledged acknowledg + acknowledgment acknowledg + acknown acknown + acold acold + aconitum aconitum + acordo acordo + acorn acorn + acquaint acquaint + acquaintance acquaint + acquainted acquaint + acquaints acquaint + acquir acquir + acquire acquir + acquisition acquisit + acquit acquit + acquittance acquitt + acquittances acquitt + acquitted acquit + acre acr + acres acr + across across + act act + actaeon actaeon + acted act + acting act + action action + actions action + actium actium + active activ + actively activ + activity activ + actor actor + actors actor + acts act + actual actual + acture actur + acute acut + acutely acut + ad ad + adage adag + adallas adalla + adam adam + adamant adam + add add + added ad + adder adder + adders adder + addeth addeth + addict addict + addicted addict + addiction addict + adding ad + addition addit + additions addit + addle addl + address address + addressing address + addrest addrest + adds add + adhere adher + adheres adher + adieu adieu + adieus adieu + adjacent adjac + adjoin adjoin + adjoining adjoin + adjourn adjourn + adjudg adjudg + adjudged adjudg + adjunct adjunct + administer administ + administration administr + admir admir + admirable admir + admiral admir + admiration admir + admire admir + admired admir + admirer admir + admiring admir + admiringly admiringli + admission admiss + admit admit + admits admit + admittance admitt + admitted admit + admitting admit + admonish admonish + admonishing admonish + admonishment admonish + admonishments admonish + admonition admonit + ado ado + adonis adoni + adopt adopt + adopted adopt + adoptedly adoptedli + adoption adopt + adoptious adopti + adopts adopt + ador ador + adoration ador + adorations ador + adore ador + adorer ador + adores ador + adorest adorest + adoreth adoreth + adoring ador + adorn adorn + adorned adorn + adornings adorn + adornment adorn + adorns adorn + adown adown + adramadio adramadio + adrian adrian + adriana adriana + adriano adriano + adriatic adriat + adsum adsum + adulation adul + adulterate adulter + adulterates adulter + adulterers adulter + adulteress adulteress + adulteries adulteri + adulterous adulter + adultery adulteri + adultress adultress + advanc advanc + advance advanc + advanced advanc + advancement advanc + advancements advanc + advances advanc + advancing advanc + advantage advantag + advantageable advantag + advantaged advantag + advantageous advantag + advantages advantag + advantaging advantag + advent advent + adventur adventur + adventure adventur + adventures adventur + adventuring adventur + adventurous adventur + adventurously adventur + adversaries adversari + adversary adversari + adverse advers + adversely advers + adversities advers + adversity advers + advertis adverti + advertise advertis + advertised advertis + advertisement advertis + advertising advertis + advice advic + advis advi + advise advis + advised advis + advisedly advisedli + advises advis + advisings advis + advocate advoc + advocation advoc + aeacida aeacida + aeacides aeacid + aedile aedil + aediles aedil + aegeon aegeon + aegion aegion + aegles aegl + aemelia aemelia + aemilia aemilia + aemilius aemiliu + aeneas aenea + aeolus aeolu + aer aer + aerial aerial + aery aeri + aesculapius aesculapiu + aeson aeson + aesop aesop + aetna aetna + afar afar + afear afear + afeard afeard + affability affabl + affable affabl + affair affair + affaire affair + affairs affair + affect affect + affectation affect + affectations affect + affected affect + affectedly affectedli + affecteth affecteth + affecting affect + affection affect + affectionate affection + affectionately affection + affections affect + affects affect + affeer affeer + affianc affianc + affiance affianc + affianced affianc + affied affi + affin affin + affined affin + affinity affin + affirm affirm + affirmation affirm + affirmatives affirm + afflict afflict + afflicted afflict + affliction afflict + afflictions afflict + afflicts afflict + afford afford + affordeth affordeth + affords afford + affray affrai + affright affright + affrighted affright + affrights affright + affront affront + affronted affront + affy affi + afield afield + afire afir + afloat afloat + afoot afoot + afore afor + aforehand aforehand + aforesaid aforesaid + afraid afraid + afresh afresh + afric afric + africa africa + african african + afront afront + after after + afternoon afternoon + afterward afterward + afterwards afterward + ag ag + again again + against against + agamemmon agamemmon + agamemnon agamemnon + agate agat + agaz agaz + age ag + aged ag + agenor agenor + agent agent + agents agent + ages ag + aggravate aggrav + aggrief aggrief + agile agil + agincourt agincourt + agitation agit + aglet aglet + agnize agniz + ago ago + agone agon + agony agoni + agree agre + agreed agre + agreeing agre + agreement agreement + agrees agre + agrippa agrippa + aground aground + ague agu + aguecheek aguecheek + agued agu + agueface aguefac + agues agu + ah ah + aha aha + ahungry ahungri + ai ai + aialvolio aialvolio + aiaria aiaria + aid aid + aidance aidanc + aidant aidant + aided aid + aiding aid + aidless aidless + aids aid + ail ail + aim aim + aimed aim + aimest aimest + aiming aim + aims aim + ainsi ainsi + aio aio + air air + aired air + airless airless + airs air + airy airi + ajax ajax + akilling akil + al al + alabaster alabast + alack alack + alacrity alacr + alarbus alarbu + alarm alarm + alarms alarm + alarum alarum + alarums alarum + alas ala + alb alb + alban alban + albans alban + albany albani + albeit albeit + albion albion + alchemist alchemist + alchemy alchemi + alcibiades alcibiad + alcides alcid + alder alder + alderman alderman + aldermen aldermen + ale al + alecto alecto + alehouse alehous + alehouses alehous + alencon alencon + alengon alengon + aleppo aleppo + ales al + alewife alewif + alexander alexand + alexanders alexand + alexandria alexandria + alexandrian alexandrian + alexas alexa + alias alia + alice alic + alien alien + aliena aliena + alight alight + alighted alight + alights alight + aliis alii + alike alik + alisander alisand + alive aliv + all all + alla alla + allay allai + allayed allai + allaying allai + allayment allay + allayments allay + allays allai + allegation alleg + allegations alleg + allege alleg + alleged alleg + allegiance allegi + allegiant allegi + alley allei + alleys allei + allhallowmas allhallowma + alliance allianc + allicholy allicholi + allied alli + allies alli + alligant allig + alligator allig + allons allon + allot allot + allots allot + allotted allot + allottery allotteri + allow allow + allowance allow + allowed allow + allowing allow + allows allow + allur allur + allure allur + allurement allur + alluring allur + allusion allus + ally alli + allycholly allycholli + almain almain + almanac almanac + almanack almanack + almanacs almanac + almighty almighti + almond almond + almost almost + alms alm + almsman almsman + aloes alo + aloft aloft + alone alon + along along + alonso alonso + aloof aloof + aloud aloud + alphabet alphabet + alphabetical alphabet + alphonso alphonso + alps alp + already alreadi + also also + alt alt + altar altar + altars altar + alter alter + alteration alter + altered alter + alters alter + althaea althaea + although although + altitude altitud + altogether altogeth + alton alton + alway alwai + always alwai + am am + amaimon amaimon + amain amain + amaking amak + amamon amamon + amaz amaz + amaze amaz + amazed amaz + amazedly amazedli + amazedness amazed + amazement amaz + amazes amaz + amazeth amazeth + amazing amaz + amazon amazon + amazonian amazonian + amazons amazon + ambassador ambassador + ambassadors ambassador + amber amber + ambiguides ambiguid + ambiguities ambigu + ambiguous ambigu + ambition ambit + ambitions ambit + ambitious ambiti + ambitiously ambiti + amble ambl + ambled ambl + ambles ambl + ambling ambl + ambo ambo + ambuscadoes ambuscado + ambush ambush + amen amen + amend amend + amended amend + amendment amend + amends amend + amerce amerc + america america + ames am + amiable amiabl + amid amid + amidst amidst + amiens amien + amis ami + amiss amiss + amities amiti + amity amiti + amnipotent amnipot + among among + amongst amongst + amorous amor + amorously amor + amort amort + amount amount + amounts amount + amour amour + amphimacus amphimacu + ample ampl + ampler ampler + amplest amplest + amplified amplifi + amplify amplifi + amply ampli + ampthill ampthil + amurath amurath + amyntas amynta + an an + anatomiz anatomiz + anatomize anatom + anatomy anatomi + ancestor ancestor + ancestors ancestor + ancestry ancestri + anchises anchis + anchor anchor + anchorage anchorag + anchored anchor + anchoring anchor + anchors anchor + anchovies anchovi + ancient ancient + ancientry ancientri + ancients ancient + ancus ancu + and and + andirons andiron + andpholus andpholu + andren andren + andrew andrew + andromache andromach + andronici andronici + andronicus andronicu + anew anew + ang ang + angel angel + angelica angelica + angelical angel + angelo angelo + angels angel + anger anger + angerly angerli + angers anger + anges ang + angiers angier + angl angl + anglais anglai + angle angl + angler angler + angleterre angleterr + angliae anglia + angling angl + anglish anglish + angrily angrili + angry angri + anguish anguish + angus angu + animal anim + animals anim + animis animi + anjou anjou + ankle ankl + anna anna + annals annal + anne ann + annex annex + annexed annex + annexions annexion + annexment annex + annothanize annothan + announces announc + annoy annoi + annoyance annoy + annoying annoi + annual annual + anoint anoint + anointed anoint + anon anon + another anoth + anselmo anselmo + answer answer + answerable answer + answered answer + answerest answerest + answering answer + answers answer + ant ant + ante ant + antenor antenor + antenorides antenorid + anteroom anteroom + anthem anthem + anthems anthem + anthony anthoni + anthropophagi anthropophagi + anthropophaginian anthropophaginian + antiates antiat + antic antic + anticipate anticip + anticipates anticip + anticipatest anticipatest + anticipating anticip + anticipation anticip + antick antick + anticly anticli + antics antic + antidote antidot + antidotes antidot + antigonus antigonu + antiopa antiopa + antipathy antipathi + antipholus antipholu + antipholuses antipholus + antipodes antipod + antiquary antiquari + antique antiqu + antiquity antiqu + antium antium + antoniad antoniad + antonio antonio + antonius antoniu + antony antoni + antres antr + anvil anvil + any ani + anybody anybodi + anyone anyon + anything anyth + anywhere anywher + ap ap + apace apac + apart apart + apartment apart + apartments apart + ape ap + apemantus apemantu + apennines apennin + apes ap + apiece apiec + apish apish + apollinem apollinem + apollo apollo + apollodorus apollodoru + apology apolog + apoplex apoplex + apoplexy apoplexi + apostle apostl + apostles apostl + apostrophas apostropha + apoth apoth + apothecary apothecari + appal appal + appall appal + appalled appal + appals appal + apparel apparel + apparell apparel + apparelled apparel + apparent appar + apparently appar + apparition apparit + apparitions apparit + appeach appeach + appeal appeal + appeals appeal + appear appear + appearance appear + appeared appear + appeareth appeareth + appearing appear + appears appear + appeas appea + appease appeas + appeased appeas + appelant appel + appele appel + appelee appele + appeles appel + appelez appelez + appellant appel + appellants appel + appelons appelon + appendix appendix + apperil apperil + appertain appertain + appertaining appertain + appertainings appertain + appertains appertain + appertinent appertin + appertinents appertin + appetite appetit + appetites appetit + applaud applaud + applauded applaud + applauding applaud + applause applaus + applauses applaus + apple appl + apples appl + appletart appletart + appliance applianc + appliances applianc + applications applic + applied appli + applies appli + apply appli + applying appli + appoint appoint + appointed appoint + appointment appoint + appointments appoint + appoints appoint + apprehend apprehend + apprehended apprehend + apprehends apprehend + apprehension apprehens + apprehensions apprehens + apprehensive apprehens + apprendre apprendr + apprenne apprenn + apprenticehood apprenticehood + appris appri + approach approach + approachers approach + approaches approach + approacheth approacheth + approaching approach + approbation approb + approof approof + appropriation appropri + approv approv + approve approv + approved approv + approvers approv + approves approv + appurtenance appurten + appurtenances appurten + apricocks apricock + april april + apron apron + aprons apron + apt apt + apter apter + aptest aptest + aptly aptli + aptness apt + aqua aqua + aquilon aquilon + aquitaine aquitain + arabia arabia + arabian arabian + araise arais + arbitrate arbitr + arbitrating arbitr + arbitrator arbitr + arbitrement arbitr + arbors arbor + arbour arbour + arc arc + arch arch + archbishop archbishop + archbishopric archbishopr + archdeacon archdeacon + arched arch + archelaus archelau + archer archer + archers archer + archery archeri + archibald archibald + archidamus archidamu + architect architect + arcu arcu + arde ard + arden arden + ardent ardent + ardour ardour + are ar + argal argal + argier argier + argo argo + argosies argosi + argosy argosi + argu argu + argue argu + argued argu + argues argu + arguing argu + argument argument + arguments argument + argus argu + ariachne ariachn + ariadne ariadn + ariel ariel + aries ari + aright aright + arinado arinado + arinies arini + arion arion + arise aris + arises aris + ariseth ariseth + arising aris + aristode aristod + aristotle aristotl + arithmetic arithmet + arithmetician arithmetician + ark ark + arm arm + arma arma + armado armado + armadoes armado + armagnac armagnac + arme arm + armed arm + armenia armenia + armies armi + armigero armigero + arming arm + armipotent armipot + armor armor + armour armour + armourer armour + armourers armour + armours armour + armoury armouri + arms arm + army armi + arn arn + aroint aroint + arose aros + arouse arous + aroused arous + arragon arragon + arraign arraign + arraigned arraign + arraigning arraign + arraignment arraign + arrant arrant + arras arra + array arrai + arrearages arrearag + arrest arrest + arrested arrest + arrests arrest + arriv arriv + arrival arriv + arrivance arriv + arrive arriv + arrived arriv + arrives arriv + arriving arriv + arrogance arrog + arrogancy arrog + arrogant arrog + arrow arrow + arrows arrow + art art + artemidorus artemidoru + arteries arteri + arthur arthur + article articl + articles articl + articulate articul + artificer artific + artificial artifici + artillery artilleri + artire artir + artist artist + artists artist + artless artless + artois artoi + arts art + artus artu + arviragus arviragu + as as + asaph asaph + ascanius ascaniu + ascend ascend + ascended ascend + ascendeth ascendeth + ascends ascend + ascension ascens + ascent ascent + ascribe ascrib + ascribes ascrib + ash ash + asham asham + ashamed asham + asher asher + ashes ash + ashford ashford + ashore ashor + ashouting ashout + ashy ashi + asia asia + aside asid + ask ask + askance askanc + asked ask + asker asker + asketh asketh + asking ask + asks ask + aslant aslant + asleep asleep + asmath asmath + asp asp + aspect aspect + aspects aspect + aspen aspen + aspersion aspers + aspic aspic + aspicious aspici + aspics aspic + aspir aspir + aspiration aspir + aspire aspir + aspiring aspir + asquint asquint + ass ass + assail assail + assailable assail + assailant assail + assailants assail + assailed assail + assaileth assaileth + assailing assail + assails assail + assassination assassin + assault assault + assaulted assault + assaults assault + assay assai + assaying assai + assays assai + assemblance assembl + assemble assembl + assembled assembl + assemblies assembl + assembly assembl + assent assent + asses ass + assez assez + assign assign + assigned assign + assigns assign + assinico assinico + assist assist + assistance assist + assistances assist + assistant assist + assistants assist + assisted assist + assisting assist + associate associ + associated associ + associates associ + assuage assuag + assubjugate assubjug + assum assum + assume assum + assumes assum + assumption assumpt + assur assur + assurance assur + assure assur + assured assur + assuredly assuredli + assures assur + assyrian assyrian + astonish astonish + astonished astonish + astraea astraea + astray astrai + astrea astrea + astronomer astronom + astronomers astronom + astronomical astronom + astronomy astronomi + asunder asund + at at + atalanta atalanta + ate at + ates at + athenian athenian + athenians athenian + athens athen + athol athol + athversary athversari + athwart athwart + atlas atla + atomies atomi + atomy atomi + atone aton + atonement aton + atonements aton + atropos atropo + attach attach + attached attach + attachment attach + attain attain + attainder attaind + attains attain + attaint attaint + attainted attaint + attainture attaintur + attempt attempt + attemptable attempt + attempted attempt + attempting attempt + attempts attempt + attend attend + attendance attend + attendant attend + attendants attend + attended attend + attendents attend + attendeth attendeth + attending attend + attends attend + attent attent + attention attent + attentive attent + attentivenes attentiven + attest attest + attested attest + attir attir + attire attir + attired attir + attires attir + attorney attornei + attorneyed attornei + attorneys attornei + attorneyship attorneyship + attract attract + attraction attract + attractive attract + attracts attract + attribute attribut + attributed attribut + attributes attribut + attribution attribut + attributive attribut + atwain atwain + au au + aubrey aubrei + auburn auburn + aucun aucun + audacious audaci + audaciously audaci + audacity audac + audible audibl + audience audienc + audis audi + audit audit + auditor auditor + auditors auditor + auditory auditori + audre audr + audrey audrei + aufidius aufidiu + aufidiuses aufidius + auger auger + aught aught + augment augment + augmentation augment + augmented augment + augmenting augment + augurer augur + augurers augur + augures augur + auguring augur + augurs augur + augury auguri + august august + augustus augustu + auld auld + aumerle aumerl + aunchient aunchient + aunt aunt + aunts aunt + auricular auricular + aurora aurora + auspicious auspici + aussi aussi + austere auster + austerely auster + austereness auster + austerity auster + austria austria + aut aut + authentic authent + author author + authorities author + authority author + authorized author + authorizing author + authors author + autolycus autolycu + autre autr + autumn autumn + auvergne auvergn + avail avail + avails avail + avarice avaric + avaricious avarici + avaunt avaunt + ave av + aveng aveng + avenge aveng + avenged aveng + averring aver + avert avert + aves av + avez avez + avis avi + avoid avoid + avoided avoid + avoiding avoid + avoids avoid + avoirdupois avoirdupoi + avouch avouch + avouched avouch + avouches avouch + avouchment avouch + avow avow + aw aw + await await + awaits await + awak awak + awake awak + awaked awak + awaken awaken + awakened awaken + awakens awaken + awakes awak + awaking awak + award award + awards award + awasy awasi + away awai + awe aw + aweary aweari + aweless aweless + awful aw + awhile awhil + awkward awkward + awl awl + awooing awoo + awork awork + awry awri + axe ax + axle axl + axletree axletre + ay ay + aye ay + ayez ayez + ayli ayli + azur azur + azure azur + b b + ba ba + baa baa + babbl babbl + babble babbl + babbling babbl + babe babe + babes babe + babies babi + baboon baboon + baboons baboon + baby babi + babylon babylon + bacare bacar + bacchanals bacchan + bacchus bacchu + bach bach + bachelor bachelor + bachelors bachelor + back back + backbite backbit + backbitten backbitten + backing back + backs back + backward backward + backwardly backwardli + backwards backward + bacon bacon + bacons bacon + bad bad + bade bade + badge badg + badged badg + badges badg + badly badli + badness bad + baes bae + baffl baffl + baffle baffl + baffled baffl + bag bag + baggage baggag + bagot bagot + bagpipe bagpip + bags bag + bail bail + bailiff bailiff + baillez baillez + baily baili + baisant baisant + baisees baise + baiser baiser + bait bait + baited bait + baiting bait + baitings bait + baits bait + bajazet bajazet + bak bak + bake bake + baked bake + baker baker + bakers baker + bakes bake + baking bake + bal bal + balanc balanc + balance balanc + balcony balconi + bald bald + baldrick baldrick + bale bale + baleful bale + balk balk + ball ball + ballad ballad + ballads ballad + ballast ballast + ballasting ballast + ballet ballet + ballow ballow + balls ball + balm balm + balms balm + balmy balmi + balsam balsam + balsamum balsamum + balth balth + balthasar balthasar + balthazar balthazar + bames bame + ban ban + banbury banburi + band band + bandied bandi + banding band + bandit bandit + banditti banditti + banditto banditto + bands band + bandy bandi + bandying bandi + bane bane + banes bane + bang bang + bangor bangor + banish banish + banished banish + banishers banish + banishment banish + banister banist + bank bank + bankrout bankrout + bankrupt bankrupt + bankrupts bankrupt + banks bank + banner banner + bannerets banneret + banners banner + banning ban + banns bann + banquet banquet + banqueted banquet + banqueting banquet + banquets banquet + banquo banquo + bans ban + baptism baptism + baptista baptista + baptiz baptiz + bar bar + barbarian barbarian + barbarians barbarian + barbarism barbar + barbarous barbar + barbary barbari + barbason barbason + barbed barb + barber barber + barbermonger barbermong + bard bard + bardolph bardolph + bards bard + bare bare + bared bare + barefac barefac + barefaced barefac + barefoot barefoot + bareheaded barehead + barely bare + bareness bare + barful bar + bargain bargain + bargains bargain + barge barg + bargulus bargulu + baring bare + bark bark + barking bark + barkloughly barkloughli + barks bark + barky barki + barley barlei + barm barm + barn barn + barnacles barnacl + barnardine barnardin + barne barn + barnes barn + barnet barnet + barns barn + baron baron + barons baron + barony baroni + barr barr + barrabas barraba + barrel barrel + barrels barrel + barren barren + barrenly barrenli + barrenness barren + barricado barricado + barricadoes barricado + barrow barrow + bars bar + barson barson + barter barter + bartholomew bartholomew + bas ba + basan basan + base base + baseless baseless + basely base + baseness base + baser baser + bases base + basest basest + bashful bash + bashfulness bash + basilisco basilisco + basilisk basilisk + basilisks basilisk + basimecu basimecu + basin basin + basingstoke basingstok + basins basin + basis basi + bask bask + basket basket + baskets basket + bass bass + bassanio bassanio + basset basset + bassianus bassianu + basta basta + bastard bastard + bastardizing bastard + bastardly bastardli + bastards bastard + bastardy bastardi + basted bast + bastes bast + bastinado bastinado + basting bast + bat bat + batailles batail + batch batch + bate bate + bated bate + bates bate + bath bath + bathe bath + bathed bath + bathing bath + baths bath + bating bate + batler batler + bats bat + batt batt + battalia battalia + battalions battalion + batten batten + batter batter + battering batter + batters batter + battery batteri + battle battl + battled battl + battlefield battlefield + battlements battlement + battles battl + batty batti + bauble baubl + baubles baubl + baubling baubl + baulk baulk + bavin bavin + bawcock bawcock + bawd bawd + bawdry bawdri + bawds bawd + bawdy bawdi + bawl bawl + bawling bawl + bay bai + baying bai + baynard baynard + bayonne bayonn + bays bai + be be + beach beach + beached beach + beachy beachi + beacon beacon + bead bead + beaded bead + beadle beadl + beadles beadl + beads bead + beadsmen beadsmen + beagle beagl + beagles beagl + beak beak + beaks beak + beam beam + beamed beam + beams beam + bean bean + beans bean + bear bear + beard beard + bearded beard + beardless beardless + beards beard + bearer bearer + bearers bearer + bearest bearest + beareth beareth + bearing bear + bears bear + beast beast + beastliest beastliest + beastliness beastli + beastly beastli + beasts beast + beat beat + beated beat + beaten beaten + beating beat + beatrice beatric + beats beat + beau beau + beaufort beaufort + beaumond beaumond + beaumont beaumont + beauteous beauteou + beautied beauti + beauties beauti + beautified beautifi + beautiful beauti + beautify beautifi + beauty beauti + beaver beaver + beavers beaver + became becam + because becaus + bechanc bechanc + bechance bechanc + bechanced bechanc + beck beck + beckon beckon + beckons beckon + becks beck + becom becom + become becom + becomed becom + becomes becom + becoming becom + becomings becom + bed bed + bedabbled bedabbl + bedash bedash + bedaub bedaub + bedazzled bedazzl + bedchamber bedchamb + bedclothes bedcloth + bedded bed + bedeck bedeck + bedecking bedeck + bedew bedew + bedfellow bedfellow + bedfellows bedfellow + bedford bedford + bedlam bedlam + bedrench bedrench + bedrid bedrid + beds bed + bedtime bedtim + bedward bedward + bee bee + beef beef + beefs beef + beehives beehiv + been been + beer beer + bees bee + beest beest + beetle beetl + beetles beetl + beeves beev + befall befal + befallen befallen + befalls befal + befell befel + befits befit + befitted befit + befitting befit + befor befor + before befor + beforehand beforehand + befortune befortun + befriend befriend + befriended befriend + befriends befriend + beg beg + began began + beget beget + begets beget + begetting beget + begg begg + beggar beggar + beggared beggar + beggarly beggarli + beggarman beggarman + beggars beggar + beggary beggari + begging beg + begin begin + beginners beginn + beginning begin + beginnings begin + begins begin + begnawn begnawn + begone begon + begot begot + begotten begotten + begrimed begrim + begs beg + beguil beguil + beguile beguil + beguiled beguil + beguiles beguil + beguiling beguil + begun begun + behalf behalf + behalfs behalf + behav behav + behaved behav + behavedst behavedst + behavior behavior + behaviors behavior + behaviour behaviour + behaviours behaviour + behead behead + beheaded behead + beheld beheld + behest behest + behests behest + behind behind + behold behold + beholder behold + beholders behold + beholdest beholdest + beholding behold + beholds behold + behoof behoof + behooffull behoofful + behooves behoov + behove behov + behoves behov + behowls behowl + being be + bel bel + belarius belariu + belch belch + belching belch + beldam beldam + beldame beldam + beldams beldam + belee bele + belgia belgia + belie beli + belied beli + belief belief + beliest beliest + believ believ + believe believ + believed believ + believes believ + believest believest + believing believ + belike belik + bell bell + bellario bellario + belle bell + bellied belli + bellies belli + bellman bellman + bellona bellona + bellow bellow + bellowed bellow + bellowing bellow + bellows bellow + bells bell + belly belli + bellyful belly + belman belman + belmont belmont + belock belock + belong belong + belonging belong + belongings belong + belongs belong + belov belov + beloved belov + beloving belov + below below + belt belt + belzebub belzebub + bemadding bemad + bemet bemet + bemete bemet + bemoan bemoan + bemoaned bemoan + bemock bemock + bemoil bemoil + bemonster bemonst + ben ben + bench bench + bencher bencher + benches bench + bend bend + bended bend + bending bend + bends bend + bene bene + beneath beneath + benedicite benedicit + benedick benedick + benediction benedict + benedictus benedictu + benefactors benefactor + benefice benefic + beneficial benefici + benefit benefit + benefited benefit + benefits benefit + benetted benet + benevolence benevol + benevolences benevol + benied beni + benison benison + bennet bennet + bent bent + bentii bentii + bentivolii bentivolii + bents bent + benumbed benumb + benvolio benvolio + bepaint bepaint + bepray beprai + bequeath bequeath + bequeathed bequeath + bequeathing bequeath + bequest bequest + ber ber + berard berard + berattle berattl + beray berai + bere bere + bereave bereav + bereaved bereav + bereaves bereav + bereft bereft + bergamo bergamo + bergomask bergomask + berhym berhym + berhyme berhym + berkeley berkelei + bermoothes bermooth + bernardo bernardo + berod berod + berowne berown + berri berri + berries berri + berrord berrord + berry berri + bertram bertram + berwick berwick + bescreen bescreen + beseech beseech + beseeched beseech + beseechers beseech + beseeching beseech + beseek beseek + beseem beseem + beseemeth beseemeth + beseeming beseem + beseems beseem + beset beset + beshrew beshrew + beside besid + besides besid + besieg besieg + besiege besieg + besieged besieg + beslubber beslubb + besmear besmear + besmeared besmear + besmirch besmirch + besom besom + besort besort + besotted besot + bespake bespak + bespeak bespeak + bespice bespic + bespoke bespok + bespotted bespot + bess bess + bessy bessi + best best + bestained bestain + bested best + bestial bestial + bestir bestir + bestirr bestirr + bestow bestow + bestowed bestow + bestowing bestow + bestows bestow + bestraught bestraught + bestrew bestrew + bestrid bestrid + bestride bestrid + bestrides bestrid + bet bet + betake betak + beteem beteem + bethink bethink + bethought bethought + bethrothed bethroth + bethump bethump + betid betid + betide betid + betideth betideth + betime betim + betimes betim + betoken betoken + betook betook + betossed betoss + betray betrai + betrayed betrai + betraying betrai + betrays betrai + betrims betrim + betroth betroth + betrothed betroth + betroths betroth + bett bett + betted bet + better better + bettered better + bettering better + betters better + betting bet + bettre bettr + between between + betwixt betwixt + bevel bevel + beverage beverag + bevis bevi + bevy bevi + bewail bewail + bewailed bewail + bewailing bewail + bewails bewail + beware bewar + bewasted bewast + beweep beweep + bewept bewept + bewet bewet + bewhored bewhor + bewitch bewitch + bewitched bewitch + bewitchment bewitch + bewray bewrai + beyond beyond + bezonian bezonian + bezonians bezonian + bianca bianca + bianco bianco + bias bia + bibble bibbl + bickerings bicker + bid bid + bidden bidden + bidding bid + biddings bid + biddy biddi + bide bide + bides bide + biding bide + bids bid + bien bien + bier bier + bifold bifold + big big + bigamy bigami + biggen biggen + bigger bigger + bigness big + bigot bigot + bilberry bilberri + bilbo bilbo + bilboes bilbo + bilbow bilbow + bill bill + billeted billet + billets billet + billiards billiard + billing bill + billow billow + billows billow + bills bill + bin bin + bind bind + bindeth bindeth + binding bind + binds bind + biondello biondello + birch birch + bird bird + birding bird + birdlime birdlim + birds bird + birnam birnam + birth birth + birthday birthdai + birthdom birthdom + birthplace birthplac + birthright birthright + birthrights birthright + births birth + bis bi + biscuit biscuit + bishop bishop + bishops bishop + bisson bisson + bit bit + bitch bitch + bite bite + biter biter + bites bite + biting bite + bits bit + bitt bitt + bitten bitten + bitter bitter + bitterest bitterest + bitterly bitterli + bitterness bitter + blab blab + blabb blabb + blabbing blab + blabs blab + black black + blackamoor blackamoor + blackamoors blackamoor + blackberries blackberri + blackberry blackberri + blacker blacker + blackest blackest + blackfriars blackfriar + blackheath blackheath + blackmere blackmer + blackness black + blacks black + bladder bladder + bladders bladder + blade blade + bladed blade + blades blade + blains blain + blam blam + blame blame + blamed blame + blameful blame + blameless blameless + blames blame + blanc blanc + blanca blanca + blanch blanch + blank blank + blanket blanket + blanks blank + blaspheme blasphem + blaspheming blasphem + blasphemous blasphem + blasphemy blasphemi + blast blast + blasted blast + blasting blast + blastments blastment + blasts blast + blaz blaz + blaze blaze + blazes blaze + blazing blaze + blazon blazon + blazoned blazon + blazoning blazon + bleach bleach + bleaching bleach + bleak bleak + blear blear + bleared blear + bleat bleat + bleated bleat + bleats bleat + bled bled + bleed bleed + bleedest bleedest + bleedeth bleedeth + bleeding bleed + bleeds bleed + blemish blemish + blemishes blemish + blench blench + blenches blench + blend blend + blended blend + blent blent + bless bless + blessed bless + blessedly blessedli + blessedness blessed + blesses bless + blesseth blesseth + blessing bless + blessings bless + blest blest + blew blew + blind blind + blinded blind + blindfold blindfold + blinding blind + blindly blindli + blindness blind + blinds blind + blink blink + blinking blink + bliss bliss + blist blist + blister blister + blisters blister + blithe blith + blithild blithild + bloat bloat + block block + blockish blockish + blocks block + blois bloi + blood blood + blooded blood + bloodhound bloodhound + bloodied bloodi + bloodier bloodier + bloodiest bloodiest + bloodily bloodili + bloodless bloodless + bloods blood + bloodshed bloodsh + bloodshedding bloodshed + bloodstained bloodstain + bloody bloodi + bloom bloom + blooms bloom + blossom blossom + blossoming blossom + blossoms blossom + blot blot + blots blot + blotted blot + blotting blot + blount blount + blow blow + blowed blow + blowers blower + blowest blowest + blowing blow + blown blown + blows blow + blowse blows + blubb blubb + blubber blubber + blubbering blubber + blue blue + bluecaps bluecap + bluest bluest + blunt blunt + blunted blunt + blunter blunter + bluntest bluntest + blunting blunt + bluntly bluntli + bluntness blunt + blunts blunt + blur blur + blurr blurr + blurs blur + blush blush + blushes blush + blushest blushest + blushing blush + blust blust + bluster bluster + blusterer bluster + blusters bluster + bo bo + boar boar + board board + boarded board + boarding board + boards board + boarish boarish + boars boar + boast boast + boasted boast + boastful boast + boasting boast + boasts boast + boat boat + boats boat + boatswain boatswain + bob bob + bobb bobb + boblibindo boblibindo + bobtail bobtail + bocchus bocchu + bode bode + boded bode + bodements bodement + bodes bode + bodg bodg + bodied bodi + bodies bodi + bodiless bodiless + bodily bodili + boding bode + bodkin bodkin + body bodi + bodykins bodykin + bog bog + boggle boggl + boggler boggler + bogs bog + bohemia bohemia + bohemian bohemian + bohun bohun + boil boil + boiling boil + boils boil + boist boist + boisterous boister + boisterously boister + boitier boitier + bold bold + bolden bolden + bolder bolder + boldest boldest + boldly boldli + boldness bold + bolds bold + bolingbroke bolingbrok + bolster bolster + bolt bolt + bolted bolt + bolter bolter + bolters bolter + bolting bolt + bolts bolt + bombard bombard + bombards bombard + bombast bombast + bon bon + bona bona + bond bond + bondage bondag + bonded bond + bondmaid bondmaid + bondman bondman + bondmen bondmen + bonds bond + bondslave bondslav + bone bone + boneless boneless + bones bone + bonfire bonfir + bonfires bonfir + bonjour bonjour + bonne bonn + bonnet bonnet + bonneted bonnet + bonny bonni + bonos bono + bonto bonto + bonville bonvil + bood bood + book book + bookish bookish + books book + boon boon + boor boor + boorish boorish + boors boor + boot boot + booted boot + booties booti + bootless bootless + boots boot + booty booti + bor bor + bora bora + borachio borachio + bordeaux bordeaux + border border + bordered border + borderers border + borders border + bore bore + boreas borea + bores bore + boring bore + born born + borne born + borough borough + boroughs borough + borrow borrow + borrowed borrow + borrower borrow + borrowing borrow + borrows borrow + bosko bosko + boskos bosko + bosky boski + bosom bosom + bosoms bosom + boson boson + boss boss + bosworth bosworth + botch botch + botcher botcher + botches botch + botchy botchi + both both + bots bot + bottle bottl + bottled bottl + bottles bottl + bottom bottom + bottomless bottomless + bottoms bottom + bouciqualt bouciqualt + bouge boug + bough bough + boughs bough + bought bought + bounce bounc + bouncing bounc + bound bound + bounded bound + bounden bounden + boundeth boundeth + bounding bound + boundless boundless + bounds bound + bounteous bounteou + bounteously bounteous + bounties bounti + bountiful bounti + bountifully bountifulli + bounty bounti + bourbier bourbier + bourbon bourbon + bourchier bourchier + bourdeaux bourdeaux + bourn bourn + bout bout + bouts bout + bove bove + bow bow + bowcase bowcas + bowed bow + bowels bowel + bower bower + bowing bow + bowl bowl + bowler bowler + bowling bowl + bowls bowl + bows bow + bowsprit bowsprit + bowstring bowstr + box box + boxes box + boy boi + boyet boyet + boyish boyish + boys boi + brabant brabant + brabantio brabantio + brabble brabbl + brabbler brabbler + brac brac + brace brace + bracelet bracelet + bracelets bracelet + brach brach + bracy braci + brag brag + bragg bragg + braggardism braggard + braggards braggard + braggart braggart + braggarts braggart + bragged brag + bragging brag + bragless bragless + brags brag + braid braid + braided braid + brain brain + brained brain + brainford brainford + brainish brainish + brainless brainless + brains brain + brainsick brainsick + brainsickly brainsickli + brake brake + brakenbury brakenburi + brakes brake + brambles brambl + bran bran + branch branch + branches branch + branchless branchless + brand brand + branded brand + brandish brandish + brandon brandon + brands brand + bras bra + brass brass + brassy brassi + brat brat + brats brat + brav brav + brave brave + braved brave + bravely brave + braver braver + bravery braveri + braves brave + bravest bravest + braving brave + brawl brawl + brawler brawler + brawling brawl + brawls brawl + brawn brawn + brawns brawn + bray brai + braying brai + braz braz + brazen brazen + brazier brazier + breach breach + breaches breach + bread bread + breadth breadth + break break + breaker breaker + breakfast breakfast + breaking break + breaks break + breast breast + breasted breast + breasting breast + breastplate breastplat + breasts breast + breath breath + breathe breath + breathed breath + breather breather + breathers breather + breathes breath + breathest breathest + breathing breath + breathless breathless + breaths breath + brecknock brecknock + bred bred + breech breech + breeches breech + breeching breech + breed breed + breeder breeder + breeders breeder + breeding breed + breeds breed + breese brees + breeze breez + breff breff + bretagne bretagn + brethen brethen + bretheren bretheren + brethren brethren + brevis brevi + brevity breviti + brew brew + brewage brewag + brewer brewer + brewers brewer + brewing brew + brews brew + briareus briareu + briars briar + brib brib + bribe bribe + briber briber + bribes bribe + brick brick + bricklayer bricklay + bricks brick + bridal bridal + bride bride + bridegroom bridegroom + bridegrooms bridegroom + brides bride + bridge bridg + bridgenorth bridgenorth + bridges bridg + bridget bridget + bridle bridl + bridled bridl + brief brief + briefer briefer + briefest briefest + briefly briefli + briefness brief + brier brier + briers brier + brigandine brigandin + bright bright + brighten brighten + brightest brightest + brightly brightli + brightness bright + brim brim + brimful brim + brims brim + brimstone brimston + brinded brind + brine brine + bring bring + bringer bringer + bringeth bringeth + bringing bring + bringings bring + brings bring + brinish brinish + brink brink + brisk brisk + brisky briski + bristle bristl + bristled bristl + bristly bristli + bristol bristol + bristow bristow + britain britain + britaine britain + britaines britain + british british + briton briton + britons briton + brittany brittani + brittle brittl + broach broach + broached broach + broad broad + broader broader + broadsides broadsid + brocas broca + brock brock + brogues brogu + broil broil + broiling broil + broils broil + broke broke + broken broken + brokenly brokenli + broker broker + brokers broker + brokes broke + broking broke + brooch brooch + brooches brooch + brood brood + brooded brood + brooding brood + brook brook + brooks brook + broom broom + broomstaff broomstaff + broth broth + brothel brothel + brother brother + brotherhood brotherhood + brotherhoods brotherhood + brotherly brotherli + brothers brother + broths broth + brought brought + brow brow + brown brown + browner browner + brownist brownist + browny browni + brows brow + browse brows + browsing brows + bruis brui + bruise bruis + bruised bruis + bruises bruis + bruising bruis + bruit bruit + bruited bruit + brundusium brundusium + brunt brunt + brush brush + brushes brush + brute brute + brutish brutish + brutus brutu + bubble bubbl + bubbles bubbl + bubbling bubbl + bubukles bubukl + buck buck + bucket bucket + buckets bucket + bucking buck + buckingham buckingham + buckle buckl + buckled buckl + buckler buckler + bucklers buckler + bucklersbury bucklersburi + buckles buckl + buckram buckram + bucks buck + bud bud + budded bud + budding bud + budge budg + budger budger + budget budget + buds bud + buff buff + buffet buffet + buffeting buffet + buffets buffet + bug bug + bugbear bugbear + bugle bugl + bugs bug + build build + builded build + buildeth buildeth + building build + buildings build + builds build + built built + bulk bulk + bulks bulk + bull bull + bullcalf bullcalf + bullen bullen + bullens bullen + bullet bullet + bullets bullet + bullocks bullock + bulls bull + bully bulli + bulmer bulmer + bulwark bulwark + bulwarks bulwark + bum bum + bumbast bumbast + bump bump + bumper bumper + bums bum + bunch bunch + bunches bunch + bundle bundl + bung bung + bunghole bunghol + bungle bungl + bunting bunt + buoy buoi + bur bur + burbolt burbolt + burd burd + burden burden + burdened burden + burdening burden + burdenous burden + burdens burden + burgh burgh + burgher burgher + burghers burgher + burglary burglari + burgomasters burgomast + burgonet burgonet + burgundy burgundi + burial burial + buried buri + burier burier + buriest buriest + burly burli + burn burn + burned burn + burnet burnet + burneth burneth + burning burn + burnish burnish + burns burn + burnt burnt + burr burr + burrows burrow + burs bur + burst burst + bursting burst + bursts burst + burthen burthen + burthens burthen + burton burton + bury buri + burying buri + bush bush + bushels bushel + bushes bush + bushy bushi + busied busi + busily busili + busines busin + business busi + businesses busi + buskin buskin + busky buski + buss buss + busses buss + bussing buss + bustle bustl + bustling bustl + busy busi + but but + butcheed butche + butcher butcher + butchered butcher + butcheries butcheri + butcherly butcherli + butchers butcher + butchery butcheri + butler butler + butt butt + butter butter + buttered butter + butterflies butterfli + butterfly butterfli + butterwoman butterwoman + buttery butteri + buttock buttock + buttocks buttock + button button + buttonhole buttonhol + buttons button + buttress buttress + buttry buttri + butts butt + buxom buxom + buy bui + buyer buyer + buying bui + buys bui + buzz buzz + buzzard buzzard + buzzards buzzard + buzzers buzzer + buzzing buzz + by by + bye bye + byzantium byzantium + c c + ca ca + cabbage cabbag + cabileros cabilero + cabin cabin + cabins cabin + cable cabl + cables cabl + cackling cackl + cacodemon cacodemon + caddis caddi + caddisses caddiss + cade cade + cadence cadenc + cadent cadent + cades cade + cadmus cadmu + caduceus caduceu + cadwal cadwal + cadwallader cadwallad + caelius caeliu + caelo caelo + caesar caesar + caesarion caesarion + caesars caesar + cage cage + caged cage + cagion cagion + cain cain + caithness caith + caitiff caitiff + caitiffs caitiff + caius caiu + cak cak + cake cake + cakes cake + calaber calab + calais calai + calamities calam + calamity calam + calchas calcha + calculate calcul + calen calen + calendar calendar + calendars calendar + calf calf + caliban caliban + calibans caliban + calipolis calipoli + cality caliti + caliver caliv + call call + callat callat + called call + callet callet + calling call + calls call + calm calm + calmest calmest + calmly calmli + calmness calm + calms calm + calpurnia calpurnia + calumniate calumni + calumniating calumni + calumnious calumni + calumny calumni + calve calv + calved calv + calves calv + calveskins calveskin + calydon calydon + cam cam + cambio cambio + cambria cambria + cambric cambric + cambrics cambric + cambridge cambridg + cambyses cambys + came came + camel camel + camelot camelot + camels camel + camest camest + camillo camillo + camlet camlet + camomile camomil + camp camp + campeius campeiu + camping camp + camps camp + can can + canakin canakin + canaries canari + canary canari + cancel cancel + cancell cancel + cancelled cancel + cancelling cancel + cancels cancel + cancer cancer + candidatus candidatu + candied candi + candle candl + candles candl + candlesticks candlestick + candy candi + canidius canidiu + cank cank + canker canker + cankerblossom cankerblossom + cankers canker + cannibally cannib + cannibals cannib + cannon cannon + cannoneer cannon + cannons cannon + cannot cannot + canon canon + canoniz canoniz + canonize canon + canonized canon + canons canon + canopied canopi + canopies canopi + canopy canopi + canst canst + canstick canstick + canterbury canterburi + cantle cantl + cantons canton + canus canu + canvas canva + canvass canvass + canzonet canzonet + cap cap + capability capabl + capable capabl + capacities capac + capacity capac + caparison caparison + capdv capdv + cape cape + capel capel + capels capel + caper caper + capers caper + capet capet + caphis caphi + capilet capilet + capitaine capitain + capital capit + capite capit + capitol capitol + capitulate capitul + capocchia capocchia + capon capon + capons capon + capp capp + cappadocia cappadocia + capriccio capriccio + capricious caprici + caps cap + capt capt + captain captain + captains captain + captainship captainship + captious captiou + captivate captiv + captivated captiv + captivates captiv + captive captiv + captives captiv + captivity captiv + captum captum + capucius capuciu + capulet capulet + capulets capulet + car car + carack carack + caracks carack + carat carat + caraways carawai + carbonado carbonado + carbuncle carbuncl + carbuncled carbuncl + carbuncles carbuncl + carcanet carcanet + carcase carcas + carcases carcas + carcass carcass + carcasses carcass + card card + cardecue cardecu + carded card + carders carder + cardinal cardin + cardinally cardin + cardinals cardin + cardmaker cardmak + cards card + carduus carduu + care care + cared care + career career + careers career + careful care + carefully carefulli + careless careless + carelessly carelessli + carelessness careless + cares care + caret caret + cargo cargo + carl carl + carlisle carlisl + carlot carlot + carman carman + carmen carmen + carnal carnal + carnally carnal + carnarvonshire carnarvonshir + carnation carnat + carnations carnat + carol carol + carous carou + carouse carous + caroused carous + carouses carous + carousing carous + carp carp + carpenter carpent + carper carper + carpet carpet + carpets carpet + carping carp + carriage carriag + carriages carriag + carried carri + carrier carrier + carriers carrier + carries carri + carrion carrion + carrions carrion + carry carri + carrying carri + cars car + cart cart + carters carter + carthage carthag + carts cart + carv carv + carve carv + carved carv + carver carver + carves carv + carving carv + cas ca + casa casa + casaer casaer + casca casca + case case + casement casement + casements casement + cases case + cash cash + cashier cashier + casing case + cask cask + casket casket + casketed casket + caskets casket + casque casqu + casques casqu + cassado cassado + cassandra cassandra + cassibelan cassibelan + cassio cassio + cassius cassiu + cassocks cassock + cast cast + castalion castalion + castaway castawai + castaways castawai + casted cast + caster caster + castigate castig + castigation castig + castile castil + castiliano castiliano + casting cast + castle castl + castles castl + casts cast + casual casual + casually casual + casualties casualti + casualty casualti + cat cat + cataian cataian + catalogue catalogu + cataplasm cataplasm + cataracts cataract + catarrhs catarrh + catastrophe catastroph + catch catch + catcher catcher + catches catch + catching catch + cate cate + catechising catechis + catechism catech + catechize catech + cater cater + caterpillars caterpillar + caters cater + caterwauling caterwaul + cates cate + catesby catesbi + cathedral cathedr + catlike catlik + catling catl + catlings catl + cato cato + cats cat + cattle cattl + caucasus caucasu + caudle caudl + cauf cauf + caught caught + cauldron cauldron + caus cau + cause caus + caused caus + causeless causeless + causer causer + causes caus + causest causest + causeth causeth + cautel cautel + cautelous cautel + cautels cautel + cauterizing cauter + caution caution + cautions caution + cavaleiro cavaleiro + cavalery cavaleri + cavaliers cavali + cave cave + cavern cavern + caverns cavern + caves cave + caveto caveto + caviary caviari + cavil cavil + cavilling cavil + cawdor cawdor + cawdron cawdron + cawing caw + ce ce + ceas cea + cease ceas + ceases ceas + ceaseth ceaseth + cedar cedar + cedars cedar + cedius cediu + celebrate celebr + celebrated celebr + celebrates celebr + celebration celebr + celerity celer + celestial celesti + celia celia + cell cell + cellar cellar + cellarage cellarag + celsa celsa + cement cement + censer censer + censor censor + censorinus censorinu + censur censur + censure censur + censured censur + censurers censur + censures censur + censuring censur + centaur centaur + centaurs centaur + centre centr + cents cent + centuries centuri + centurion centurion + centurions centurion + century centuri + cerberus cerberu + cerecloth cerecloth + cerements cerement + ceremonial ceremoni + ceremonies ceremoni + ceremonious ceremoni + ceremoniously ceremoni + ceremony ceremoni + ceres cere + cerns cern + certain certain + certainer certain + certainly certainli + certainties certainti + certainty certainti + certes cert + certificate certif + certified certifi + certifies certifi + certify certifi + ces ce + cesario cesario + cess cess + cesse cess + cestern cestern + cetera cetera + cette cett + chaces chace + chaf chaf + chafe chafe + chafed chafe + chafes chafe + chaff chaff + chaffless chaffless + chafing chafe + chain chain + chains chain + chair chair + chairs chair + chalic chalic + chalice chalic + chalices chalic + chalk chalk + chalks chalk + chalky chalki + challeng challeng + challenge challeng + challenged challeng + challenger challeng + challengers challeng + challenges challeng + cham cham + chamber chamber + chamberers chamber + chamberlain chamberlain + chamberlains chamberlain + chambermaid chambermaid + chambermaids chambermaid + chambers chamber + chameleon chameleon + champ champ + champagne champagn + champain champain + champains champain + champion champion + champions champion + chanc chanc + chance chanc + chanced chanc + chancellor chancellor + chances chanc + chandler chandler + chang chang + change chang + changeable changeabl + changed chang + changeful chang + changeling changel + changelings changel + changer changer + changes chang + changest changest + changing chang + channel channel + channels channel + chanson chanson + chant chant + chanticleer chanticl + chanting chant + chantries chantri + chantry chantri + chants chant + chaos chao + chap chap + chape chape + chapel chapel + chapeless chapeless + chapels chapel + chaplain chaplain + chaplains chaplain + chapless chapless + chaplet chaplet + chapmen chapmen + chaps chap + chapter chapter + character charact + charactered charact + characterless characterless + characters charact + charactery characteri + characts charact + charbon charbon + chare chare + chares chare + charg charg + charge charg + charged charg + chargeful charg + charges charg + chargeth chargeth + charging charg + chariest chariest + chariness chari + charing chare + chariot chariot + chariots chariot + charitable charit + charitably charit + charities chariti + charity chariti + charlemain charlemain + charles charl + charm charm + charmed charm + charmer charmer + charmeth charmeth + charmian charmian + charming charm + charmingly charmingli + charms charm + charneco charneco + charnel charnel + charolois charoloi + charon charon + charter charter + charters charter + chartreux chartreux + chary chari + charybdis charybdi + chas cha + chase chase + chased chase + chaser chaser + chaseth chaseth + chasing chase + chaste chast + chastely chast + chastis chasti + chastise chastis + chastised chastis + chastisement chastis + chastity chastiti + chat chat + chatham chatham + chatillon chatillon + chats chat + chatt chatt + chattels chattel + chatter chatter + chattering chatter + chattles chattl + chaud chaud + chaunted chaunt + chaw chaw + chawdron chawdron + che che + cheap cheap + cheapen cheapen + cheaper cheaper + cheapest cheapest + cheaply cheapli + cheapside cheapsid + cheat cheat + cheated cheat + cheater cheater + cheaters cheater + cheating cheat + cheats cheat + check check + checked check + checker checker + checking check + checks check + cheek cheek + cheeks cheek + cheer cheer + cheered cheer + cheerer cheerer + cheerful cheer + cheerfully cheerfulli + cheering cheer + cheerless cheerless + cheerly cheerli + cheers cheer + cheese chees + chequer chequer + cher cher + cherish cherish + cherished cherish + cherisher cherish + cherishes cherish + cherishing cherish + cherries cherri + cherry cherri + cherrypit cherrypit + chertsey chertsei + cherub cherub + cherubims cherubim + cherubin cherubin + cherubins cherubin + cheshu cheshu + chess chess + chest chest + chester chester + chestnut chestnut + chestnuts chestnut + chests chest + chetas cheta + chev chev + cheval cheval + chevalier chevali + chevaliers chevali + cheveril cheveril + chew chew + chewed chew + chewet chewet + chewing chew + chez chez + chi chi + chick chick + chicken chicken + chickens chicken + chicurmurco chicurmurco + chid chid + chidden chidden + chide chide + chiders chider + chides chide + chiding chide + chief chief + chiefest chiefest + chiefly chiefli + chien chien + child child + childed child + childeric childer + childhood childhood + childhoods childhood + childing child + childish childish + childishness childish + childlike childlik + childness child + children children + chill chill + chilling chill + chime chime + chimes chime + chimney chimnei + chimneypiece chimneypiec + chimneys chimnei + chimurcho chimurcho + chin chin + china china + chine chine + chines chine + chink chink + chinks chink + chins chin + chipp chipp + chipper chipper + chips chip + chiron chiron + chirping chirp + chirrah chirrah + chirurgeonly chirurgeonli + chisel chisel + chitopher chitoph + chivalrous chivalr + chivalry chivalri + choice choic + choicely choic + choicest choicest + choir choir + choirs choir + chok chok + choke choke + choked choke + chokes choke + choking choke + choler choler + choleric choler + cholers choler + chollors chollor + choose choos + chooser chooser + chooses choos + chooseth chooseth + choosing choos + chop chop + chopine chopin + choplogic choplog + chopp chopp + chopped chop + chopping chop + choppy choppi + chops chop + chopt chopt + chor chor + choristers chorist + chorus choru + chose chose + chosen chosen + chough chough + choughs chough + chrish chrish + christ christ + christen christen + christendom christendom + christendoms christendom + christening christen + christenings christen + christian christian + christianlike christianlik + christians christian + christmas christma + christom christom + christopher christoph + christophero christophero + chronicle chronicl + chronicled chronicl + chronicler chronicl + chroniclers chronicl + chronicles chronicl + chrysolite chrysolit + chuck chuck + chucks chuck + chud chud + chuffs chuff + church church + churches church + churchman churchman + churchmen churchmen + churchyard churchyard + churchyards churchyard + churl churl + churlish churlish + churlishly churlishli + churls churl + churn churn + chus chu + cicatrice cicatric + cicatrices cicatric + cicely cice + cicero cicero + ciceter cicet + ciel ciel + ciitzens ciitzen + cilicia cilicia + cimber cimber + cimmerian cimmerian + cinable cinabl + cincture cinctur + cinders cinder + cine cine + cinna cinna + cinque cinqu + cipher cipher + ciphers cipher + circa circa + circe circ + circle circl + circled circl + circlets circlet + circling circl + circuit circuit + circum circum + circumcised circumcis + circumference circumfer + circummur circummur + circumscrib circumscrib + circumscribed circumscrib + circumscription circumscript + circumspect circumspect + circumstance circumst + circumstanced circumstanc + circumstances circumst + circumstantial circumstanti + circumvent circumv + circumvention circumvent + cistern cistern + citadel citadel + cital cital + cite cite + cited cite + cites cite + cities citi + citing cite + citizen citizen + citizens citizen + cittern cittern + city citi + civet civet + civil civil + civility civil + civilly civilli + clack clack + clad clad + claim claim + claiming claim + claims claim + clamb clamb + clamber clamber + clammer clammer + clamor clamor + clamorous clamor + clamors clamor + clamour clamour + clamours clamour + clang clang + clangor clangor + clap clap + clapp clapp + clapped clap + clapper clapper + clapping clap + claps clap + clare clare + clarence clarenc + claret claret + claribel claribel + clasp clasp + clasps clasp + clatter clatter + claud claud + claudio claudio + claudius claudiu + clause claus + claw claw + clawed claw + clawing claw + claws claw + clay clai + clays clai + clean clean + cleanliest cleanliest + cleanly cleanli + cleans clean + cleanse cleans + cleansing cleans + clear clear + clearer clearer + clearest clearest + clearly clearli + clearness clear + clears clear + cleave cleav + cleaving cleav + clef clef + cleft cleft + cleitus cleitu + clemency clemenc + clement clement + cleomenes cleomen + cleopatpa cleopatpa + cleopatra cleopatra + clepeth clepeth + clept clept + clerestories clerestori + clergy clergi + clergyman clergyman + clergymen clergymen + clerk clerk + clerkly clerkli + clerks clerk + clew clew + client client + clients client + cliff cliff + clifford clifford + cliffords clifford + cliffs cliff + clifton clifton + climate climat + climature climatur + climb climb + climbed climb + climber climber + climbeth climbeth + climbing climb + climbs climb + clime clime + cling cling + clink clink + clinking clink + clinquant clinquant + clip clip + clipp clipp + clipper clipper + clippeth clippeth + clipping clip + clipt clipt + clitus clitu + clo clo + cloak cloak + cloakbag cloakbag + cloaks cloak + clock clock + clocks clock + clod clod + cloddy cloddi + clodpole clodpol + clog clog + clogging clog + clogs clog + cloister cloister + cloistress cloistress + cloquence cloquenc + clos clo + close close + closed close + closely close + closeness close + closer closer + closes close + closest closest + closet closet + closing close + closure closur + cloten cloten + clotens cloten + cloth cloth + clothair clothair + clotharius clothariu + clothe cloth + clothes cloth + clothier clothier + clothiers clothier + clothing cloth + cloths cloth + clotpoles clotpol + clotpoll clotpol + cloud cloud + clouded cloud + cloudiness cloudi + clouds cloud + cloudy cloudi + clout clout + clouted clout + clouts clout + cloven cloven + clover clover + cloves clove + clovest clovest + clowder clowder + clown clown + clownish clownish + clowns clown + cloy cloi + cloyed cloi + cloying cloi + cloyless cloyless + cloyment cloyment + cloys cloi + club club + clubs club + cluck cluck + clung clung + clust clust + clusters cluster + clutch clutch + clyster clyster + cneius cneiu + cnemies cnemi + co co + coach coach + coaches coach + coachmakers coachmak + coact coact + coactive coactiv + coagulate coagul + coal coal + coals coal + coarse coars + coarsely coars + coast coast + coasting coast + coasts coast + coat coat + coated coat + coats coat + cobble cobbl + cobbled cobbl + cobbler cobbler + cobham cobham + cobloaf cobloaf + cobweb cobweb + cobwebs cobweb + cock cock + cockatrice cockatric + cockatrices cockatric + cockle cockl + cockled cockl + cockney cocknei + cockpit cockpit + cocks cock + cocksure cocksur + coctus coctu + cocytus cocytu + cod cod + codding cod + codling codl + codpiece codpiec + codpieces codpiec + cods cod + coelestibus coelestibu + coesar coesar + coeur coeur + coffer coffer + coffers coffer + coffin coffin + coffins coffin + cog cog + cogging cog + cogitation cogit + cogitations cogit + cognition cognit + cognizance cogniz + cogscomb cogscomb + cohabitants cohabit + coher coher + cohere coher + coherence coher + coherent coher + cohorts cohort + coif coif + coign coign + coil coil + coin coin + coinage coinag + coiner coiner + coining coin + coins coin + col col + colbrand colbrand + colchos colcho + cold cold + colder colder + coldest coldest + coldly coldli + coldness cold + coldspur coldspur + colebrook colebrook + colic colic + collar collar + collars collar + collateral collater + colleagued colleagu + collect collect + collected collect + collection collect + college colleg + colleges colleg + collied colli + collier collier + colliers collier + collop collop + collusion collus + colme colm + colmekill colmekil + coloquintida coloquintida + color color + colors color + colossus colossu + colour colour + colourable colour + coloured colour + colouring colour + colours colour + colt colt + colted colt + colts colt + columbine columbin + columbines columbin + colville colvil + com com + comagene comagen + comart comart + comb comb + combat combat + combatant combat + combatants combat + combated combat + combating combat + combin combin + combinate combin + combination combin + combine combin + combined combin + combless combless + combustion combust + come come + comedian comedian + comedians comedian + comedy comedi + comeliness comeli + comely come + comer comer + comers comer + comes come + comest comest + comet comet + cometh cometh + comets comet + comfect comfect + comfit comfit + comfits comfit + comfort comfort + comfortable comfort + comforted comfort + comforter comfort + comforting comfort + comfortless comfortless + comforts comfort + comic comic + comical comic + coming come + comings come + cominius cominiu + comma comma + command command + commande command + commanded command + commander command + commanders command + commanding command + commandment command + commandments command + commands command + comme comm + commenc commenc + commence commenc + commenced commenc + commencement commenc + commences commenc + commencing commenc + commend commend + commendable commend + commendation commend + commendations commend + commended commend + commending commend + commends commend + comment comment + commentaries commentari + commenting comment + comments comment + commerce commerc + commingled commingl + commiseration commiser + commission commiss + commissioners commission + commissions commiss + commit commit + commits commit + committ committ + committed commit + committing commit + commix commix + commixed commix + commixtion commixt + commixture commixtur + commodious commodi + commodities commod + commodity commod + common common + commonalty commonalti + commoner common + commoners common + commonly commonli + commons common + commonweal commonw + commonwealth commonwealth + commotion commot + commotions commot + commune commun + communicat communicat + communicate commun + communication commun + communities commun + community commun + comonty comonti + compact compact + companies compani + companion companion + companions companion + companionship companionship + company compani + compar compar + comparative compar + compare compar + compared compar + comparing compar + comparison comparison + comparisons comparison + compartner compartn + compass compass + compasses compass + compassing compass + compassion compass + compassionate compassion + compeers compeer + compel compel + compell compel + compelled compel + compelling compel + compels compel + compensation compens + competence compet + competency compet + competent compet + competitor competitor + competitors competitor + compil compil + compile compil + compiled compil + complain complain + complainer complain + complainest complainest + complaining complain + complainings complain + complains complain + complaint complaint + complaints complaint + complement complement + complements complement + complete complet + complexion complexion + complexioned complexion + complexions complexion + complices complic + complies compli + compliment compliment + complimental compliment + compliments compliment + complot complot + complots complot + complotted complot + comply compli + compos compo + compose compos + composed compos + composition composit + compost compost + composture compostur + composure composur + compound compound + compounded compound + compounds compound + comprehend comprehend + comprehended comprehend + comprehends comprehend + compremises compremis + compris compri + comprising compris + compromis compromi + compromise compromis + compt compt + comptible comptibl + comptrollers comptrol + compulsatory compulsatori + compulsion compuls + compulsive compuls + compunctious compuncti + computation comput + comrade comrad + comrades comrad + comutual comutu + con con + concave concav + concavities concav + conceal conceal + concealed conceal + concealing conceal + concealment conceal + concealments conceal + conceals conceal + conceit conceit + conceited conceit + conceitless conceitless + conceits conceit + conceiv conceiv + conceive conceiv + conceived conceiv + conceives conceiv + conceiving conceiv + conception concept + conceptions concept + conceptious concepti + concern concern + concernancy concern + concerneth concerneth + concerning concern + concernings concern + concerns concern + conclave conclav + conclud conclud + conclude conclud + concluded conclud + concludes conclud + concluding conclud + conclusion conclus + conclusions conclus + concolinel concolinel + concord concord + concubine concubin + concupiscible concupisc + concupy concupi + concur concur + concurring concur + concurs concur + condemn condemn + condemnation condemn + condemned condemn + condemning condemn + condemns condemn + condescend condescend + condign condign + condition condit + conditionally condition + conditions condit + condole condol + condolement condol + condoling condol + conduce conduc + conduct conduct + conducted conduct + conducting conduct + conductor conductor + conduit conduit + conduits conduit + conected conect + coney conei + confection confect + confectionary confectionari + confections confect + confederacy confederaci + confederate confeder + confederates confeder + confer confer + conference confer + conferr conferr + conferring confer + confess confess + confessed confess + confesses confess + confesseth confesseth + confessing confess + confession confess + confessions confess + confessor confessor + confidence confid + confident confid + confidently confid + confin confin + confine confin + confined confin + confineless confineless + confiners confin + confines confin + confining confin + confirm confirm + confirmation confirm + confirmations confirm + confirmed confirm + confirmer confirm + confirmers confirm + confirming confirm + confirmities confirm + confirms confirm + confiscate confisc + confiscated confisc + confiscation confisc + confixed confix + conflict conflict + conflicting conflict + conflicts conflict + confluence confluenc + conflux conflux + conform conform + conformable conform + confound confound + confounded confound + confounding confound + confounds confound + confront confront + confronted confront + confus confu + confused confus + confusedly confusedli + confusion confus + confusions confus + confutation confut + confutes confut + congeal congeal + congealed congeal + congealment congeal + congee conge + conger conger + congest congest + congied congi + congratulate congratul + congreeing congre + congreeted congreet + congregate congreg + congregated congreg + congregation congreg + congregations congreg + congruent congruent + congruing congru + conies coni + conjectural conjectur + conjecture conjectur + conjectures conjectur + conjoin conjoin + conjoined conjoin + conjoins conjoin + conjointly conjointli + conjunct conjunct + conjunction conjunct + conjunctive conjunct + conjur conjur + conjuration conjur + conjurations conjur + conjure conjur + conjured conjur + conjurer conjur + conjurers conjur + conjures conjur + conjuring conjur + conjuro conjuro + conn conn + connected connect + connive conniv + conqu conqu + conquer conquer + conquered conquer + conquering conquer + conqueror conqueror + conquerors conqueror + conquers conquer + conquest conquest + conquests conquest + conquring conqur + conrade conrad + cons con + consanguineous consanguin + consanguinity consanguin + conscienc conscienc + conscience conscienc + consciences conscienc + conscionable conscion + consecrate consecr + consecrated consecr + consecrations consecr + consent consent + consented consent + consenting consent + consents consent + consequence consequ + consequences consequ + consequently consequ + conserve conserv + conserved conserv + conserves conserv + consider consid + considerance consider + considerate consider + consideration consider + considerations consider + considered consid + considering consid + considerings consid + considers consid + consign consign + consigning consign + consist consist + consisteth consisteth + consisting consist + consistory consistori + consists consist + consolate consol + consolation consol + consonancy conson + consonant conson + consort consort + consorted consort + consortest consortest + conspectuities conspectu + conspir conspir + conspiracy conspiraci + conspirant conspir + conspirator conspir + conspirators conspir + conspire conspir + conspired conspir + conspirers conspir + conspires conspir + conspiring conspir + constable constabl + constables constabl + constance constanc + constancies constanc + constancy constanc + constant constant + constantine constantin + constantinople constantinopl + constantly constantli + constellation constel + constitution constitut + constrain constrain + constrained constrain + constraineth constraineth + constrains constrain + constraint constraint + constring constr + construction construct + construe constru + consul consul + consuls consul + consulship consulship + consulships consulship + consult consult + consulting consult + consults consult + consum consum + consume consum + consumed consum + consumes consum + consuming consum + consummate consumm + consummation consumm + consumption consumpt + consumptions consumpt + contagion contagion + contagious contagi + contain contain + containing contain + contains contain + contaminate contamin + contaminated contamin + contemn contemn + contemned contemn + contemning contemn + contemns contemn + contemplate contempl + contemplation contempl + contemplative contempl + contempt contempt + contemptible contempt + contempts contempt + contemptuous contemptu + contemptuously contemptu + contend contend + contended contend + contending contend + contendon contendon + content content + contenta contenta + contented content + contenteth contenteth + contention content + contentious contenti + contentless contentless + contento contento + contents content + contest contest + contestation contest + continence contin + continency contin + continent contin + continents contin + continu continu + continual continu + continually continu + continuance continu + continuantly continuantli + continuate continu + continue continu + continued continu + continuer continu + continues continu + continuing continu + contract contract + contracted contract + contracting contract + contraction contract + contradict contradict + contradicted contradict + contradiction contradict + contradicts contradict + contraries contrari + contrarieties contrarieti + contrariety contrarieti + contrarious contrari + contrariously contrari + contrary contrari + contre contr + contribution contribut + contributors contributor + contrite contrit + contriv contriv + contrive contriv + contrived contriv + contriver contriv + contrives contriv + contriving contriv + control control + controll control + controller control + controlling control + controlment control + controls control + controversy controversi + contumelious contumeli + contumeliously contumeli + contumely contum + contusions contus + convenience conveni + conveniences conveni + conveniency conveni + convenient conveni + conveniently conveni + convented convent + conventicles conventicl + convents convent + convers conver + conversant convers + conversation convers + conversations convers + converse convers + conversed convers + converses convers + conversing convers + conversion convers + convert convert + converted convert + convertest convertest + converting convert + convertite convertit + convertites convertit + converts convert + convey convei + conveyance convey + conveyances convey + conveyers convey + conveying convei + convict convict + convicted convict + convince convinc + convinced convinc + convinces convinc + convive conviv + convocation convoc + convoy convoi + convulsions convuls + cony coni + cook cook + cookery cookeri + cooks cook + cool cool + cooled cool + cooling cool + cools cool + coop coop + coops coop + cop cop + copatain copatain + cope cope + cophetua cophetua + copied copi + copies copi + copious copiou + copper copper + copperspur copperspur + coppice coppic + copulation copul + copulatives copul + copy copi + cor cor + coragio coragio + coral coral + coram coram + corambus corambu + coranto coranto + corantos coranto + corbo corbo + cord cord + corded cord + cordelia cordelia + cordial cordial + cordis cordi + cords cord + core core + corin corin + corinth corinth + corinthian corinthian + coriolanus coriolanu + corioli corioli + cork cork + corky corki + cormorant cormor + corn corn + cornelia cornelia + cornelius corneliu + corner corner + corners corner + cornerstone cornerston + cornets cornet + cornish cornish + corns corn + cornuto cornuto + cornwall cornwal + corollary corollari + coronal coron + coronation coron + coronet coronet + coronets coronet + corporal corpor + corporals corpor + corporate corpor + corpse corps + corpulent corpul + correct correct + corrected correct + correcting correct + correction correct + correctioner correction + corrects correct + correspondence correspond + correspondent correspond + corresponding correspond + corresponsive correspons + corrigible corrig + corrival corriv + corrivals corriv + corroborate corrobor + corrosive corros + corrupt corrupt + corrupted corrupt + corrupter corrupt + corrupters corrupt + corruptible corrupt + corruptibly corrupt + corrupting corrupt + corruption corrupt + corruptly corruptli + corrupts corrupt + corse cors + corses cors + corslet corslet + cosmo cosmo + cost cost + costard costard + costermongers costermong + costlier costlier + costly costli + costs cost + cot cot + cote cote + coted cote + cotsall cotsal + cotsole cotsol + cotswold cotswold + cottage cottag + cottages cottag + cotus cotu + couch couch + couched couch + couching couch + couchings couch + coude coud + cough cough + coughing cough + could could + couldst couldst + coulter coulter + council council + councillor councillor + councils council + counsel counsel + counsell counsel + counsellor counsellor + counsellors counsellor + counselor counselor + counselors counselor + counsels counsel + count count + counted count + countenanc countenanc + countenance counten + countenances counten + counter counter + counterchange counterchang + countercheck countercheck + counterfeit counterfeit + counterfeited counterfeit + counterfeiting counterfeit + counterfeitly counterfeitli + counterfeits counterfeit + countermand countermand + countermands countermand + countermines countermin + counterpart counterpart + counterpoints counterpoint + counterpois counterpoi + counterpoise counterpois + counters counter + countervail countervail + countess countess + countesses countess + counties counti + counting count + countless countless + countries countri + countrv countrv + country countri + countryman countryman + countrymen countrymen + counts count + county counti + couper couper + couple coupl + coupled coupl + couplement couplement + couples coupl + couplet couplet + couplets couplet + cour cour + courage courag + courageous courag + courageously courag + courages courag + courier courier + couriers courier + couronne couronn + cours cour + course cours + coursed cours + courser courser + coursers courser + courses cours + coursing cours + court court + courted court + courteous courteou + courteously courteous + courtesan courtesan + courtesies courtesi + courtesy courtesi + courtezan courtezan + courtezans courtezan + courtier courtier + courtiers courtier + courtlike courtlik + courtly courtli + courtney courtnei + courts court + courtship courtship + cousin cousin + cousins cousin + couterfeit couterfeit + coutume coutum + covenant coven + covenants coven + covent covent + coventry coventri + cover cover + covered cover + covering cover + coverlet coverlet + covers cover + covert covert + covertly covertli + coverture covertur + covet covet + coveted covet + coveting covet + covetings covet + covetous covet + covetously covet + covetousness covet + covets covet + cow cow + coward coward + cowarded coward + cowardice cowardic + cowardly cowardli + cowards coward + cowardship cowardship + cowish cowish + cowl cowl + cowslip cowslip + cowslips cowslip + cox cox + coxcomb coxcomb + coxcombs coxcomb + coy coi + coystrill coystril + coz coz + cozen cozen + cozenage cozenag + cozened cozen + cozener cozen + cozeners cozen + cozening cozen + coziers cozier + crab crab + crabbed crab + crabs crab + crack crack + cracked crack + cracker cracker + crackers cracker + cracking crack + cracks crack + cradle cradl + cradled cradl + cradles cradl + craft craft + crafted craft + craftied crafti + craftier craftier + craftily craftili + crafts craft + craftsmen craftsmen + crafty crafti + cram cram + cramm cramm + cramp cramp + cramps cramp + crams cram + cranking crank + cranks crank + cranmer cranmer + crannied cranni + crannies cranni + cranny cranni + crants crant + crare crare + crash crash + crassus crassu + crav crav + crave crave + craved crave + craven craven + cravens craven + craves crave + craveth craveth + craving crave + crawl crawl + crawling crawl + crawls crawl + craz craz + crazed craze + crazy crazi + creaking creak + cream cream + create creat + created creat + creates creat + creating creat + creation creation + creator creator + creature creatur + creatures creatur + credence credenc + credent credent + credible credibl + credit credit + creditor creditor + creditors creditor + credo credo + credulity credul + credulous credul + creed creed + creek creek + creeks creek + creep creep + creeping creep + creeps creep + crept crept + crescent crescent + crescive cresciv + cressets cresset + cressid cressid + cressida cressida + cressids cressid + cressy cressi + crest crest + crested crest + crestfall crestfal + crestless crestless + crests crest + cretan cretan + crete crete + crevice crevic + crew crew + crews crew + crib crib + cribb cribb + cribs crib + cricket cricket + crickets cricket + cried cri + criedst criedst + crier crier + cries cri + criest criest + crieth crieth + crime crime + crimeful crime + crimeless crimeless + crimes crime + criminal crimin + crimson crimson + cringe cring + cripple crippl + crisp crisp + crisped crisp + crispian crispian + crispianus crispianu + crispin crispin + critic critic + critical critic + critics critic + croak croak + croaking croak + croaks croak + crocodile crocodil + cromer cromer + cromwell cromwel + crone crone + crook crook + crookback crookback + crooked crook + crooking crook + crop crop + cropp cropp + crosby crosbi + cross cross + crossed cross + crosses cross + crossest crossest + crossing cross + crossings cross + crossly crossli + crossness cross + crost crost + crotchets crotchet + crouch crouch + crouching crouch + crow crow + crowd crowd + crowded crowd + crowding crowd + crowds crowd + crowflowers crowflow + crowing crow + crowkeeper crowkeep + crown crown + crowned crown + crowner crowner + crownet crownet + crownets crownet + crowning crown + crowns crown + crows crow + crudy crudi + cruel cruel + cruell cruell + crueller crueller + cruelly cruelli + cruels cruel + cruelty cruelti + crum crum + crumble crumbl + crumbs crumb + crupper crupper + crusadoes crusado + crush crush + crushed crush + crushest crushest + crushing crush + crust crust + crusts crust + crusty crusti + crutch crutch + crutches crutch + cry cry + crying cry + crystal crystal + crystalline crystallin + crystals crystal + cub cub + cubbert cubbert + cubiculo cubiculo + cubit cubit + cubs cub + cuckold cuckold + cuckoldly cuckoldli + cuckolds cuckold + cuckoo cuckoo + cucullus cucullu + cudgel cudgel + cudgeled cudgel + cudgell cudgel + cudgelling cudgel + cudgels cudgel + cue cue + cues cue + cuff cuff + cuffs cuff + cuique cuiqu + cull cull + culling cull + cullion cullion + cullionly cullionli + cullions cullion + culpable culpabl + culverin culverin + cum cum + cumber cumber + cumberland cumberland + cunning cun + cunningly cunningli + cunnings cun + cuore cuor + cup cup + cupbearer cupbear + cupboarding cupboard + cupid cupid + cupids cupid + cuppele cuppel + cups cup + cur cur + curan curan + curate curat + curb curb + curbed curb + curbing curb + curbs curb + curd curd + curdied curdi + curds curd + cure cure + cured cure + cureless cureless + curer curer + cures cure + curfew curfew + curing cure + curio curio + curiosity curios + curious curiou + curiously curious + curl curl + curled curl + curling curl + curls curl + currance curranc + currants currant + current current + currents current + currish currish + curry curri + curs cur + curse curs + cursed curs + curses curs + cursies cursi + cursing curs + cursorary cursorari + curst curst + curster curster + curstest curstest + curstness curst + cursy cursi + curtail curtail + curtain curtain + curtains curtain + curtal curtal + curtis curti + curtle curtl + curtsied curtsi + curtsies curtsi + curtsy curtsi + curvet curvet + curvets curvet + cushes cush + cushion cushion + cushions cushion + custalorum custalorum + custard custard + custody custodi + custom custom + customary customari + customed custom + customer custom + customers custom + customs custom + custure custur + cut cut + cutler cutler + cutpurse cutpurs + cutpurses cutpurs + cuts cut + cutter cutter + cutting cut + cuttle cuttl + cxsar cxsar + cyclops cyclop + cydnus cydnu + cygnet cygnet + cygnets cygnet + cym cym + cymbals cymbal + cymbeline cymbelin + cyme cyme + cynic cynic + cynthia cynthia + cypress cypress + cypriot cypriot + cyprus cypru + cyrus cyru + cytherea cytherea + d d + dabbled dabbl + dace dace + dad dad + daedalus daedalu + daemon daemon + daff daff + daffed daf + daffest daffest + daffodils daffodil + dagger dagger + daggers dagger + dagonet dagonet + daily daili + daintier daintier + dainties dainti + daintiest daintiest + daintily daintili + daintiness dainti + daintry daintri + dainty dainti + daisied daisi + daisies daisi + daisy daisi + dale dale + dalliance dallianc + dallied dalli + dallies dalli + dally dalli + dallying dalli + dalmatians dalmatian + dam dam + damage damag + damascus damascu + damask damask + damasked damask + dame dame + dames dame + damm damm + damn damn + damnable damnabl + damnably damnabl + damnation damnat + damned damn + damns damn + damoiselle damoisel + damon damon + damosella damosella + damp damp + dams dam + damsel damsel + damsons damson + dan dan + danc danc + dance danc + dancer dancer + dances danc + dancing danc + dandle dandl + dandy dandi + dane dane + dang dang + danger danger + dangerous danger + dangerously danger + dangers danger + dangling dangl + daniel daniel + danish danish + dank dank + dankish dankish + danskers dansker + daphne daphn + dappled dappl + dapples dappl + dar dar + dardan dardan + dardanian dardanian + dardanius dardaniu + dare dare + dared dare + dareful dare + dares dare + darest darest + daring dare + darius dariu + dark dark + darken darken + darkening darken + darkens darken + darker darker + darkest darkest + darkling darkl + darkly darkli + darkness dark + darling darl + darlings darl + darnel darnel + darraign darraign + dart dart + darted dart + darter darter + dartford dartford + darting dart + darts dart + dash dash + dashes dash + dashing dash + dastard dastard + dastards dastard + dat dat + datchet datchet + date date + dated date + dateless dateless + dates date + daub daub + daughter daughter + daughters daughter + daunt daunt + daunted daunt + dauntless dauntless + dauphin dauphin + daventry daventri + davy davi + daw daw + dawn dawn + dawning dawn + daws daw + day dai + daylight daylight + days dai + dazzle dazzl + dazzled dazzl + dazzling dazzl + de de + dead dead + deadly deadli + deaf deaf + deafing deaf + deafness deaf + deafs deaf + deal deal + dealer dealer + dealers dealer + dealest dealest + dealing deal + dealings deal + deals deal + dealt dealt + dean dean + deanery deaneri + dear dear + dearer dearer + dearest dearest + dearly dearli + dearness dear + dears dear + dearth dearth + dearths dearth + death death + deathbed deathb + deathful death + deaths death + deathsman deathsman + deathsmen deathsmen + debarred debar + debase debas + debate debat + debated debat + debatement debat + debateth debateth + debating debat + debauch debauch + debile debil + debility debil + debitor debitor + debonair debonair + deborah deborah + debosh debosh + debt debt + debted debt + debtor debtor + debtors debtor + debts debt + debuty debuti + decay decai + decayed decai + decayer decay + decaying decai + decays decai + deceas decea + decease deceas + deceased deceas + deceit deceit + deceitful deceit + deceits deceit + deceiv deceiv + deceivable deceiv + deceive deceiv + deceived deceiv + deceiver deceiv + deceivers deceiv + deceives deceiv + deceivest deceivest + deceiveth deceiveth + deceiving deceiv + december decemb + decent decent + deceptious decepti + decerns decern + decide decid + decides decid + decimation decim + decipher deciph + deciphers deciph + decision decis + decius deciu + deck deck + decking deck + decks deck + deckt deckt + declare declar + declares declar + declension declens + declensions declens + declin declin + decline declin + declined declin + declines declin + declining declin + decoct decoct + decorum decorum + decreas decrea + decrease decreas + decreasing decreas + decree decre + decreed decre + decrees decre + decrepit decrepit + dedicate dedic + dedicated dedic + dedicates dedic + dedication dedic + deed deed + deedless deedless + deeds deed + deem deem + deemed deem + deep deep + deeper deeper + deepest deepest + deeply deepli + deeps deep + deepvow deepvow + deer deer + deesse deess + defac defac + deface defac + defaced defac + defacer defac + defacers defac + defacing defac + defam defam + default default + defeat defeat + defeated defeat + defeats defeat + defeatures defeatur + defect defect + defective defect + defects defect + defence defenc + defences defenc + defend defend + defendant defend + defended defend + defender defend + defenders defend + defending defend + defends defend + defense defens + defensible defens + defensive defens + defer defer + deferr deferr + defiance defianc + deficient defici + defied defi + defies defi + defil defil + defile defil + defiler defil + defiles defil + defiling defil + define defin + definement defin + definite definit + definitive definit + definitively definit + deflow deflow + deflower deflow + deflowered deflow + deform deform + deformed deform + deformities deform + deformity deform + deftly deftli + defunct defunct + defunction defunct + defuse defus + defy defi + defying defi + degenerate degener + degraded degrad + degree degre + degrees degre + deified deifi + deifying deifi + deign deign + deigned deign + deiphobus deiphobu + deities deiti + deity deiti + deja deja + deject deject + dejected deject + delabreth delabreth + delay delai + delayed delai + delaying delai + delays delai + delectable delect + deliberate deliber + delicate delic + delicates delic + delicious delici + deliciousness delici + delight delight + delighted delight + delightful delight + delights delight + delinquents delinqu + deliv deliv + deliver deliv + deliverance deliver + delivered deliv + delivering deliv + delivers deliv + delivery deliveri + delphos delpho + deluded delud + deluding delud + deluge delug + delve delv + delver delver + delves delv + demand demand + demanded demand + demanding demand + demands demand + demean demean + demeanor demeanor + demeanour demeanour + demerits demerit + demesnes demesn + demetrius demetriu + demi demi + demigod demigod + demise demis + demoiselles demoisel + demon demon + demonstrable demonstr + demonstrate demonstr + demonstrated demonstr + demonstrating demonstr + demonstration demonstr + demonstrative demonstr + demure demur + demurely demur + demuring demur + den den + denay denai + deni deni + denial denial + denials denial + denied deni + denier denier + denies deni + deniest deniest + denis deni + denmark denmark + dennis denni + denny denni + denote denot + denoted denot + denotement denot + denounc denounc + denounce denounc + denouncing denounc + dens den + denunciation denunci + deny deni + denying deni + deo deo + depart depart + departed depart + departest departest + departing depart + departure departur + depeche depech + depend depend + dependant depend + dependants depend + depended depend + dependence depend + dependences depend + dependency depend + dependent depend + dependents depend + depender depend + depending depend + depends depend + deplore deplor + deploring deplor + depopulate depopul + depos depo + depose depos + deposed depos + deposing depos + depositaries depositari + deprav deprav + depravation deprav + deprave deprav + depraved deprav + depraves deprav + depress depress + depriv depriv + deprive depriv + depth depth + depths depth + deputation deput + depute deput + deputed deput + deputies deputi + deputing deput + deputy deputi + deracinate deracin + derby derbi + dercetas derceta + dere dere + derides derid + derision deris + deriv deriv + derivation deriv + derivative deriv + derive deriv + derived deriv + derives deriv + derogate derog + derogately derog + derogation derog + des de + desartless desartless + descant descant + descend descend + descended descend + descending descend + descends descend + descension descens + descent descent + descents descent + describe describ + described describ + describes describ + descried descri + description descript + descriptions descript + descry descri + desdemon desdemon + desdemona desdemona + desert desert + deserts desert + deserv deserv + deserve deserv + deserved deserv + deservedly deservedli + deserver deserv + deservers deserv + deserves deserv + deservest deservest + deserving deserv + deservings deserv + design design + designment design + designments design + designs design + desir desir + desire desir + desired desir + desirers desir + desires desir + desirest desirest + desiring desir + desirous desir + desist desist + desk desk + desolate desol + desolation desol + desp desp + despair despair + despairing despair + despairs despair + despatch despatch + desperate desper + desperately desper + desperation desper + despis despi + despise despis + despised despis + despiser despis + despiseth despiseth + despising despis + despite despit + despiteful despit + despoiled despoil + dest dest + destin destin + destined destin + destinies destini + destiny destini + destitute destitut + destroy destroi + destroyed destroi + destroyer destroy + destroyers destroy + destroying destroi + destroys destroi + destruction destruct + destructions destruct + det det + detain detain + detains detain + detect detect + detected detect + detecting detect + detection detect + detector detector + detects detect + detention detent + determin determin + determinate determin + determination determin + determinations determin + determine determin + determined determin + determines determin + detest detest + detestable detest + detested detest + detesting detest + detests detest + detract detract + detraction detract + detractions detract + deucalion deucalion + deuce deuc + deum deum + deux deux + devant devant + devesting devest + device devic + devices devic + devil devil + devilish devilish + devils devil + devis devi + devise devis + devised devis + devises devis + devising devis + devoid devoid + devonshire devonshir + devote devot + devoted devot + devotion devot + devour devour + devoured devour + devourers devour + devouring devour + devours devour + devout devout + devoutly devoutli + dew dew + dewberries dewberri + dewdrops dewdrop + dewlap dewlap + dewlapp dewlapp + dews dew + dewy dewi + dexter dexter + dexteriously dexteri + dexterity dexter + di di + diable diabl + diablo diablo + diadem diadem + dial dial + dialect dialect + dialogue dialogu + dialogued dialogu + dials dial + diameter diamet + diamond diamond + diamonds diamond + dian dian + diana diana + diaper diaper + dibble dibbl + dic dic + dice dice + dicers dicer + dich dich + dick dick + dickens dicken + dickon dickon + dicky dicki + dictator dictat + diction diction + dictynna dictynna + did did + diddle diddl + didest didest + dido dido + didst didst + die die + died di + diedst diedst + dies di + diest diest + diet diet + dieted diet + dieter dieter + dieu dieu + diff diff + differ differ + difference differ + differences differ + differency differ + different differ + differing differ + differs differ + difficile difficil + difficult difficult + difficulties difficulti + difficulty difficulti + diffidence diffid + diffidences diffid + diffus diffu + diffused diffus + diffusest diffusest + dig dig + digest digest + digested digest + digestion digest + digestions digest + digg digg + digging dig + dighton dighton + dignified dignifi + dignifies dignifi + dignify dignifi + dignities digniti + dignity digniti + digress digress + digressing digress + digression digress + digs dig + digt digt + dilate dilat + dilated dilat + dilations dilat + dilatory dilatori + dild dild + dildos dildo + dilemma dilemma + dilemmas dilemma + diligence dilig + diligent dilig + diluculo diluculo + dim dim + dimension dimens + dimensions dimens + diminish diminish + diminishing diminish + diminution diminut + diminutive diminut + diminutives diminut + dimm dimm + dimmed dim + dimming dim + dimpled dimpl + dimples dimpl + dims dim + din din + dine dine + dined dine + diner diner + dines dine + ding ding + dining dine + dinner dinner + dinners dinner + dinnertime dinnertim + dint dint + diomed diom + diomede diomed + diomedes diomed + dion dion + dip dip + dipp dipp + dipping dip + dips dip + dir dir + dire dire + direct direct + directed direct + directing direct + direction direct + directions direct + directitude directitud + directive direct + directly directli + directs direct + direful dire + direness dire + direst direst + dirge dirg + dirges dirg + dirt dirt + dirty dirti + dis di + disability disabl + disable disabl + disabled disabl + disabling disabl + disadvantage disadvantag + disagree disagre + disallow disallow + disanimates disanim + disannul disannul + disannuls disannul + disappointed disappoint + disarm disarm + disarmed disarm + disarmeth disarmeth + disarms disarm + disaster disast + disasters disast + disastrous disastr + disbench disbench + disbranch disbranch + disburdened disburden + disburs disbur + disburse disburs + disbursed disburs + discandy discandi + discandying discandi + discard discard + discarded discard + discase discas + discased discas + discern discern + discerner discern + discerning discern + discernings discern + discerns discern + discharg discharg + discharge discharg + discharged discharg + discharging discharg + discipled discipl + disciples discipl + disciplin disciplin + discipline disciplin + disciplined disciplin + disciplines disciplin + disclaim disclaim + disclaiming disclaim + disclaims disclaim + disclos disclo + disclose disclos + disclosed disclos + discloses disclos + discolour discolour + discoloured discolour + discolours discolour + discomfit discomfit + discomfited discomfit + discomfiture discomfitur + discomfort discomfort + discomfortable discomfort + discommend discommend + disconsolate disconsol + discontent discont + discontented discont + discontentedly discontentedli + discontenting discont + discontents discont + discontinue discontinu + discontinued discontinu + discord discord + discordant discord + discords discord + discourse discours + discoursed discours + discourser discours + discourses discours + discoursive discours + discourtesy discourtesi + discov discov + discover discov + discovered discov + discoverers discover + discoveries discoveri + discovering discov + discovers discov + discovery discoveri + discredit discredit + discredited discredit + discredits discredit + discreet discreet + discreetly discreetli + discretion discret + discretions discret + discuss discuss + disdain disdain + disdained disdain + disdaineth disdaineth + disdainful disdain + disdainfully disdainfulli + disdaining disdain + disdains disdain + disdnguish disdnguish + diseas disea + disease diseas + diseased diseas + diseases diseas + disedg disedg + disembark disembark + disfigure disfigur + disfigured disfigur + disfurnish disfurnish + disgorge disgorg + disgrac disgrac + disgrace disgrac + disgraced disgrac + disgraceful disgrac + disgraces disgrac + disgracing disgrac + disgracious disgraci + disguis disgui + disguise disguis + disguised disguis + disguiser disguis + disguises disguis + disguising disguis + dish dish + dishabited dishabit + dishclout dishclout + dishearten dishearten + disheartens dishearten + dishes dish + dishonest dishonest + dishonestly dishonestli + dishonesty dishonesti + dishonor dishonor + dishonorable dishonor + dishonors dishonor + dishonour dishonour + dishonourable dishonour + dishonoured dishonour + dishonours dishonour + disinherit disinherit + disinherited disinherit + disjoin disjoin + disjoining disjoin + disjoins disjoin + disjoint disjoint + disjunction disjunct + dislik dislik + dislike dislik + disliken disliken + dislikes dislik + dislimns dislimn + dislocate disloc + dislodg dislodg + disloyal disloy + disloyalty disloyalti + dismal dismal + dismantle dismantl + dismantled dismantl + dismask dismask + dismay dismai + dismayed dismai + dismemb dismemb + dismember dismemb + dismes dism + dismiss dismiss + dismissed dismiss + dismissing dismiss + dismission dismiss + dismount dismount + dismounted dismount + disnatur disnatur + disobedience disobedi + disobedient disobedi + disobey disobei + disobeys disobei + disorb disorb + disorder disord + disordered disord + disorderly disorderli + disorders disord + disparage disparag + disparagement disparag + disparagements disparag + dispark dispark + dispatch dispatch + dispensation dispens + dispense dispens + dispenses dispens + dispers disper + disperse dispers + dispersed dispers + dispersedly dispersedli + dispersing dispers + dispiteous dispit + displac displac + displace displac + displaced displac + displant displant + displanting displant + display displai + displayed displai + displeas displea + displease displeas + displeased displeas + displeasing displeas + displeasure displeasur + displeasures displeasur + disponge dispong + disport disport + disports disport + dispos dispo + dispose dispos + disposed dispos + disposer dispos + disposing dispos + disposition disposit + dispositions disposit + dispossess dispossess + dispossessing dispossess + disprais disprai + dispraise disprais + dispraising disprais + dispraisingly dispraisingli + dispropertied disproperti + disproportion disproport + disproportioned disproport + disprov disprov + disprove disprov + disproved disprov + dispursed dispurs + disputable disput + disputation disput + disputations disput + dispute disput + disputed disput + disputes disput + disputing disput + disquantity disquant + disquiet disquiet + disquietly disquietli + disrelish disrelish + disrobe disrob + disseat disseat + dissemble dissembl + dissembled dissembl + dissembler dissembl + dissemblers dissembl + dissembling dissembl + dissembly dissembl + dissension dissens + dissensions dissens + dissentious dissenti + dissever dissev + dissipation dissip + dissolute dissolut + dissolutely dissolut + dissolution dissolut + dissolutions dissolut + dissolv dissolv + dissolve dissolv + dissolved dissolv + dissolves dissolv + dissuade dissuad + dissuaded dissuad + distaff distaff + distaffs distaff + distain distain + distains distain + distance distanc + distant distant + distaste distast + distasted distast + distasteful distast + distemp distemp + distemper distemp + distemperature distemperatur + distemperatures distemperatur + distempered distemp + distempering distemp + distil distil + distill distil + distillation distil + distilled distil + distills distil + distilment distil + distinct distinct + distinction distinct + distinctly distinctli + distingue distingu + distinguish distinguish + distinguishes distinguish + distinguishment distinguish + distract distract + distracted distract + distractedly distractedli + distraction distract + distractions distract + distracts distract + distrain distrain + distraught distraught + distress distress + distressed distress + distresses distress + distressful distress + distribute distribut + distributed distribut + distribution distribut + distrust distrust + distrustful distrust + disturb disturb + disturbed disturb + disturbers disturb + disturbing disturb + disunite disunit + disvalued disvalu + disvouch disvouch + dit dit + ditch ditch + ditchers ditcher + ditches ditch + dites dite + ditties ditti + ditty ditti + diurnal diurnal + div div + dive dive + diver diver + divers diver + diversely divers + diversity divers + divert divert + diverted divert + diverts divert + dives dive + divest divest + dividable divid + dividant divid + divide divid + divided divid + divides divid + divideth divideth + divin divin + divination divin + divine divin + divinely divin + divineness divin + diviner divin + divines divin + divinest divinest + divining divin + divinity divin + division divis + divisions divis + divorc divorc + divorce divorc + divorced divorc + divorcement divorc + divorcing divorc + divulg divulg + divulge divulg + divulged divulg + divulging divulg + dizy dizi + dizzy dizzi + do do + doating doat + dobbin dobbin + dock dock + docks dock + doct doct + doctor doctor + doctors doctor + doctrine doctrin + document document + dodge dodg + doe doe + doer doer + doers doer + does doe + doest doest + doff doff + dog dog + dogberry dogberri + dogfish dogfish + dogg dogg + dogged dog + dogs dog + doigts doigt + doing do + doings do + doit doit + doits doit + dolabella dolabella + dole dole + doleful dole + doll doll + dollar dollar + dollars dollar + dolor dolor + dolorous dolor + dolour dolour + dolours dolour + dolphin dolphin + dolt dolt + dolts dolt + domestic domest + domestics domest + dominance domin + dominations domin + dominator domin + domine domin + domineer domin + domineering domin + dominical domin + dominion dominion + dominions dominion + domitius domitiu + dommelton dommelton + don don + donalbain donalbain + donation donat + donc donc + doncaster doncast + done done + dong dong + donn donn + donne donn + donner donner + donnerai donnerai + doom doom + doomsday doomsdai + door door + doorkeeper doorkeep + doors door + dorcas dorca + doreus doreu + doricles doricl + dormouse dormous + dorothy dorothi + dorset dorset + dorsetshire dorsetshir + dost dost + dotage dotag + dotant dotant + dotard dotard + dotards dotard + dote dote + doted dote + doters doter + dotes dote + doteth doteth + doth doth + doting dote + double doubl + doubled doubl + doubleness doubl + doubler doubler + doublet doublet + doublets doublet + doubling doubl + doubly doubli + doubt doubt + doubted doubt + doubtful doubt + doubtfully doubtfulli + doubting doubt + doubtless doubtless + doubts doubt + doug doug + dough dough + doughty doughti + doughy doughi + douglas dougla + dout dout + doute dout + douts dout + dove dove + dovehouse dovehous + dover dover + doves dove + dow dow + dowager dowag + dowdy dowdi + dower dower + dowerless dowerless + dowers dower + dowlas dowla + dowle dowl + down down + downfall downfal + downright downright + downs down + downstairs downstair + downtrod downtrod + downward downward + downwards downward + downy downi + dowries dowri + dowry dowri + dowsabel dowsabel + doxy doxi + dozed doze + dozen dozen + dozens dozen + dozy dozi + drab drab + drabbing drab + drabs drab + drachma drachma + drachmas drachma + draff draff + drag drag + dragg dragg + dragged drag + dragging drag + dragon dragon + dragonish dragonish + dragons dragon + drain drain + drained drain + drains drain + drake drake + dram dram + dramatis dramati + drank drank + draught draught + draughts draught + drave drave + draw draw + drawbridge drawbridg + drawer drawer + drawers drawer + draweth draweth + drawing draw + drawling drawl + drawn drawn + draws draw + drayman drayman + draymen draymen + dread dread + dreaded dread + dreadful dread + dreadfully dreadfulli + dreading dread + dreads dread + dream dream + dreamer dreamer + dreamers dreamer + dreaming dream + dreams dream + dreamt dreamt + drearning drearn + dreary dreari + dreg dreg + dregs dreg + drench drench + drenched drench + dress dress + dressed dress + dresser dresser + dressing dress + dressings dress + drest drest + drew drew + dribbling dribbl + dried dri + drier drier + dries dri + drift drift + drily drili + drink drink + drinketh drinketh + drinking drink + drinkings drink + drinks drink + driv driv + drive drive + drivelling drivel + driven driven + drives drive + driveth driveth + driving drive + drizzle drizzl + drizzled drizzl + drizzles drizzl + droit droit + drollery drolleri + dromio dromio + dromios dromio + drone drone + drones drone + droop droop + droopeth droopeth + drooping droop + droops droop + drop drop + dropheir dropheir + droplets droplet + dropp dropp + dropper dropper + droppeth droppeth + dropping drop + droppings drop + drops drop + dropsied dropsi + dropsies dropsi + dropsy dropsi + dropt dropt + dross dross + drossy drossi + drought drought + drove drove + droven droven + drovier drovier + drown drown + drowned drown + drowning drown + drowns drown + drows drow + drowse drows + drowsily drowsili + drowsiness drowsi + drowsy drowsi + drudge drudg + drudgery drudgeri + drudges drudg + drug drug + drugg drugg + drugs drug + drum drum + drumble drumbl + drummer drummer + drumming drum + drums drum + drunk drunk + drunkard drunkard + drunkards drunkard + drunken drunken + drunkenly drunkenli + drunkenness drunken + dry dry + dryness dryness + dst dst + du du + dub dub + dubb dubb + ducat ducat + ducats ducat + ducdame ducdam + duchess duchess + duchies duchi + duchy duchi + duck duck + ducking duck + ducks duck + dudgeon dudgeon + due due + duellist duellist + duello duello + duer duer + dues due + duff duff + dug dug + dugs dug + duke duke + dukedom dukedom + dukedoms dukedom + dukes duke + dulcet dulcet + dulche dulch + dull dull + dullard dullard + duller duller + dullest dullest + dulling dull + dullness dull + dulls dull + dully dulli + dulness dul + duly duli + dumain dumain + dumb dumb + dumbe dumb + dumbly dumbl + dumbness dumb + dump dump + dumps dump + dun dun + duncan duncan + dung dung + dungeon dungeon + dungeons dungeon + dunghill dunghil + dunghills dunghil + dungy dungi + dunnest dunnest + dunsinane dunsinan + dunsmore dunsmor + dunstable dunstabl + dupp dupp + durance duranc + during dure + durst durst + dusky duski + dust dust + dusted dust + dusty dusti + dutch dutch + dutchman dutchman + duteous duteou + duties duti + dutiful duti + duty duti + dwarf dwarf + dwarfish dwarfish + dwell dwell + dwellers dweller + dwelling dwell + dwells dwell + dwelt dwelt + dwindle dwindl + dy dy + dye dye + dyed dy + dyer dyer + dying dy + e e + each each + eager eager + eagerly eagerli + eagerness eager + eagle eagl + eagles eagl + eaning ean + eanlings eanl + ear ear + earing ear + earl earl + earldom earldom + earlier earlier + earliest earliest + earliness earli + earls earl + early earli + earn earn + earned earn + earnest earnest + earnestly earnestli + earnestness earnest + earns earn + ears ear + earth earth + earthen earthen + earthlier earthlier + earthly earthli + earthquake earthquak + earthquakes earthquak + earthy earthi + eas ea + ease eas + eased eas + easeful eas + eases eas + easier easier + easiest easiest + easiliest easiliest + easily easili + easiness easi + easing eas + east east + eastcheap eastcheap + easter easter + eastern eastern + eastward eastward + easy easi + eat eat + eaten eaten + eater eater + eaters eater + eating eat + eats eat + eaux eaux + eaves eav + ebb ebb + ebbing eb + ebbs ebb + ebon ebon + ebony eboni + ebrew ebrew + ecce ecc + echapper echapp + echo echo + echoes echo + eclips eclip + eclipse eclips + eclipses eclips + ecolier ecoli + ecoutez ecoutez + ecstacy ecstaci + ecstasies ecstasi + ecstasy ecstasi + ecus ecu + eden eden + edg edg + edgar edgar + edge edg + edged edg + edgeless edgeless + edges edg + edict edict + edicts edict + edifice edific + edifices edific + edified edifi + edifies edifi + edition edit + edm edm + edmund edmund + edmunds edmund + edmundsbury edmundsburi + educate educ + educated educ + education educ + edward edward + eel eel + eels eel + effect effect + effected effect + effectless effectless + effects effect + effectual effectu + effectually effectu + effeminate effemin + effigies effigi + effus effu + effuse effus + effusion effus + eftest eftest + egal egal + egally egal + eget eget + egeus egeu + egg egg + eggs egg + eggshell eggshel + eglamour eglamour + eglantine eglantin + egma egma + ego ego + egregious egregi + egregiously egregi + egress egress + egypt egypt + egyptian egyptian + egyptians egyptian + eie eie + eight eight + eighteen eighteen + eighth eighth + eightpenny eightpenni + eighty eighti + eisel eisel + either either + eject eject + eke ek + el el + elbe elb + elbow elbow + elbows elbow + eld eld + elder elder + elders elder + eldest eldest + eleanor eleanor + elect elect + elected elect + election elect + elegancy eleg + elegies elegi + element element + elements element + elephant eleph + elephants eleph + elevated elev + eleven eleven + eleventh eleventh + elf elf + elflocks elflock + eliads eliad + elinor elinor + elizabeth elizabeth + ell ell + elle ell + ellen ellen + elm elm + eloquence eloqu + eloquent eloqu + else els + elsewhere elsewher + elsinore elsinor + eltham eltham + elves elv + elvish elvish + ely eli + elysium elysium + em em + emballing embal + embalm embalm + embalms embalm + embark embark + embarked embark + embarquements embarqu + embassade embassad + embassage embassag + embassies embassi + embassy embassi + embattailed embattail + embattl embattl + embattle embattl + embay embai + embellished embellish + embers ember + emblaze emblaz + emblem emblem + emblems emblem + embodied embodi + embold embold + emboldens embolden + emboss emboss + embossed emboss + embounded embound + embowel embowel + embowell embowel + embrac embrac + embrace embrac + embraced embrac + embracement embrac + embracements embrac + embraces embrac + embracing embrac + embrasures embrasur + embroider embroid + embroidery embroideri + emhracing emhrac + emilia emilia + eminence emin + eminent emin + eminently emin + emmanuel emmanuel + emnity emniti + empale empal + emperal emper + emperess emperess + emperial emperi + emperor emperor + empery emperi + emphasis emphasi + empire empir + empirics empir + empiricutic empiricut + empleached empleach + employ emploi + employed emploi + employer employ + employment employ + employments employ + empoison empoison + empress empress + emptied empti + emptier emptier + empties empti + emptiness empti + empty empti + emptying empti + emulate emul + emulation emul + emulations emul + emulator emul + emulous emul + en en + enact enact + enacted enact + enacts enact + enactures enactur + enamell enamel + enamelled enamel + enamour enamour + enamoured enamour + enanmour enanmour + encamp encamp + encamped encamp + encave encav + enceladus enceladu + enchaf enchaf + enchafed enchaf + enchant enchant + enchanted enchant + enchanting enchant + enchantingly enchantingli + enchantment enchant + enchantress enchantress + enchants enchant + enchas encha + encircle encircl + encircled encircl + enclos enclo + enclose enclos + enclosed enclos + encloses enclos + encloseth encloseth + enclosing enclos + enclouded encloud + encompass encompass + encompassed encompass + encompasseth encompasseth + encompassment encompass + encore encor + encorporal encorpor + encount encount + encounter encount + encountered encount + encounters encount + encourage encourag + encouraged encourag + encouragement encourag + encrimsoned encrimson + encroaching encroach + encumb encumb + end end + endamage endamag + endamagement endamag + endanger endang + endart endart + endear endear + endeared endear + endeavour endeavour + endeavours endeavour + ended end + ender ender + ending end + endings end + endite endit + endless endless + endow endow + endowed endow + endowments endow + endows endow + ends end + endu endu + endue endu + endur endur + endurance endur + endure endur + endured endur + endures endur + enduring endur + endymion endymion + eneas enea + enemies enemi + enemy enemi + enernies enerni + enew enew + enfeebled enfeebl + enfeebles enfeebl + enfeoff enfeoff + enfetter enfett + enfoldings enfold + enforc enforc + enforce enforc + enforced enforc + enforcedly enforcedli + enforcement enforc + enforces enforc + enforcest enforcest + enfranched enfranch + enfranchis enfranchi + enfranchise enfranchis + enfranchised enfranchis + enfranchisement enfranchis + enfreed enfre + enfreedoming enfreedom + engag engag + engage engag + engaged engag + engagements engag + engaging engag + engaol engaol + engend engend + engender engend + engenders engend + engilds engild + engine engin + engineer engin + enginer engin + engines engin + engirt engirt + england england + english english + englishman englishman + englishmen englishmen + engluts englut + englutted englut + engraffed engraf + engraft engraft + engrafted engraft + engrav engrav + engrave engrav + engross engross + engrossed engross + engrossest engrossest + engrossing engross + engrossments engross + enguard enguard + enigma enigma + enigmatical enigmat + enjoin enjoin + enjoined enjoin + enjoy enjoi + enjoyed enjoi + enjoyer enjoy + enjoying enjoi + enjoys enjoi + enkindle enkindl + enkindled enkindl + enlard enlard + enlarg enlarg + enlarge enlarg + enlarged enlarg + enlargement enlarg + enlargeth enlargeth + enlighten enlighten + enlink enlink + enmesh enmesh + enmities enmiti + enmity enmiti + ennoble ennobl + ennobled ennobl + enobarb enobarb + enobarbus enobarbu + enon enon + enormity enorm + enormous enorm + enough enough + enow enow + enpatron enpatron + enpierced enpierc + enquir enquir + enquire enquir + enquired enquir + enrag enrag + enrage enrag + enraged enrag + enrages enrag + enrank enrank + enrapt enrapt + enrich enrich + enriched enrich + enriches enrich + enridged enridg + enrings enr + enrob enrob + enrobe enrob + enroll enrol + enrolled enrol + enrooted enroot + enrounded enround + enschedul enschedul + ensconce ensconc + ensconcing ensconc + enseamed enseam + ensear ensear + enseigne enseign + enseignez enseignez + ensemble ensembl + enshelter enshelt + enshielded enshield + enshrines enshrin + ensign ensign + ensigns ensign + enskied enski + ensman ensman + ensnare ensnar + ensnared ensnar + ensnareth ensnareth + ensteep ensteep + ensu ensu + ensue ensu + ensued ensu + ensues ensu + ensuing ensu + enswathed enswath + ent ent + entail entail + entame entam + entangled entangl + entangles entangl + entendre entendr + enter enter + entered enter + entering enter + enterprise enterpris + enterprises enterpris + enters enter + entertain entertain + entertained entertain + entertainer entertain + entertaining entertain + entertainment entertain + entertainments entertain + enthrall enthral + enthralled enthral + enthron enthron + enthroned enthron + entice entic + enticements entic + enticing entic + entire entir + entirely entir + entitle entitl + entitled entitl + entitling entitl + entomb entomb + entombed entomb + entrails entrail + entrance entranc + entrances entranc + entrap entrap + entrapp entrapp + entre entr + entreat entreat + entreated entreat + entreaties entreati + entreating entreat + entreatments entreat + entreats entreat + entreaty entreati + entrench entrench + entry entri + entwist entwist + envelop envelop + envenom envenom + envenomed envenom + envenoms envenom + envied envi + envies envi + envious enviou + enviously envious + environ environ + environed environ + envoy envoi + envy envi + envying envi + enwheel enwheel + enwombed enwomb + enwraps enwrap + ephesian ephesian + ephesians ephesian + ephesus ephesu + epicure epicur + epicurean epicurean + epicures epicur + epicurism epicur + epicurus epicuru + epidamnum epidamnum + epidaurus epidauru + epigram epigram + epilepsy epilepsi + epileptic epilept + epilogue epilogu + epilogues epilogu + epistles epistl + epistrophus epistrophu + epitaph epitaph + epitaphs epitaph + epithet epithet + epitheton epitheton + epithets epithet + epitome epitom + equal equal + equalities equal + equality equal + equall equal + equally equal + equalness equal + equals equal + equinoctial equinocti + equinox equinox + equipage equipag + equity equiti + equivocal equivoc + equivocate equivoc + equivocates equivoc + equivocation equivoc + equivocator equivoc + er er + erbear erbear + erbearing erbear + erbears erbear + erbeat erbeat + erblows erblow + erboard erboard + erborne erborn + ercame ercam + ercast ercast + ercharg ercharg + ercharged ercharg + ercharging ercharg + ercles ercl + ercome ercom + ercover ercov + ercrows ercrow + erdoing erdo + ere er + erebus erebu + erect erect + erected erect + erecting erect + erection erect + erects erect + erewhile erewhil + erflourish erflourish + erflow erflow + erflowing erflow + erflows erflow + erfraught erfraught + erga erga + ergalled ergal + erglanced erglanc + ergo ergo + ergone ergon + ergrow ergrow + ergrown ergrown + ergrowth ergrowth + erhang erhang + erhanging erhang + erhasty erhasti + erhear erhear + erheard erheard + eringoes eringo + erjoy erjoi + erleap erleap + erleaps erleap + erleavens erleaven + erlook erlook + erlooking erlook + ermaster ermast + ermengare ermengar + ermount ermount + ern ern + ernight ernight + eros ero + erpaid erpaid + erparted erpart + erpast erpast + erpays erpai + erpeer erpeer + erperch erperch + erpicturing erpictur + erpingham erpingham + erposting erpost + erpow erpow + erpress erpress + erpressed erpress + err err + errand errand + errands errand + errant errant + errate errat + erraught erraught + erreaches erreach + erred er + errest errest + erring er + erroneous erron + error error + errors error + errs err + errule errul + errun errun + erset erset + ershade ershad + ershades ershad + ershine ershin + ershot ershot + ersized ersiz + erskip erskip + erslips erslip + erspreads erspread + erst erst + erstare erstar + erstep erstep + erstunk erstunk + ersway erswai + ersways erswai + erswell erswel + erta erta + ertake ertak + erteemed erteem + erthrow erthrow + erthrown erthrown + erthrows erthrow + ertook ertook + ertop ertop + ertopping ertop + ertrip ertrip + erturn erturn + erudition erudit + eruption erupt + eruptions erupt + ervalues ervalu + erwalk erwalk + erwatch erwatch + erween erween + erweens erween + erweigh erweigh + erweighs erweigh + erwhelm erwhelm + erwhelmed erwhelm + erworn erworn + es es + escalus escalu + escap escap + escape escap + escaped escap + escapes escap + eschew eschew + escoted escot + esill esil + especial especi + especially especi + esperance esper + espials espial + espied espi + espies espi + espous espou + espouse espous + espy espi + esquire esquir + esquires esquir + essay essai + essays essai + essence essenc + essential essenti + essentially essenti + esses ess + essex essex + est est + establish establish + established establish + estate estat + estates estat + esteem esteem + esteemed esteem + esteemeth esteemeth + esteeming esteem + esteems esteem + estimable estim + estimate estim + estimation estim + estimations estim + estime estim + estranged estrang + estridge estridg + estridges estridg + et et + etc etc + etceteras etcetera + ete et + eternal etern + eternally etern + eterne etern + eternity etern + eterniz eterniz + etes et + ethiop ethiop + ethiope ethiop + ethiopes ethiop + ethiopian ethiopian + etna etna + eton eton + etre etr + eunuch eunuch + eunuchs eunuch + euphrates euphrat + euphronius euphroniu + euriphile euriphil + europa europa + europe europ + ev ev + evade evad + evades evad + evans evan + evasion evas + evasions evas + eve ev + even even + evening even + evenly evenli + event event + eventful event + events event + ever ever + everlasting everlast + everlastingly everlastingli + evermore evermor + every everi + everyone everyon + everything everyth + everywhere everywher + evidence evid + evidences evid + evident evid + evil evil + evilly evilli + evils evil + evitate evit + ewe ew + ewer ewer + ewers ewer + ewes ew + exact exact + exacted exact + exactest exactest + exacting exact + exaction exact + exactions exact + exactly exactli + exacts exact + exalt exalt + exalted exalt + examin examin + examination examin + examinations examin + examine examin + examined examin + examines examin + exampl exampl + example exampl + exampled exampl + examples exampl + exasperate exasper + exasperates exasper + exceed exce + exceeded exceed + exceedeth exceedeth + exceeding exceed + exceedingly exceedingli + exceeds exce + excel excel + excelled excel + excellence excel + excellencies excel + excellency excel + excellent excel + excellently excel + excelling excel + excels excel + except except + excepted except + excepting except + exception except + exceptions except + exceptless exceptless + excess excess + excessive excess + exchang exchang + exchange exchang + exchanged exchang + exchequer exchequ + exchequers exchequ + excite excit + excited excit + excitements excit + excites excit + exclaim exclaim + exclaims exclaim + exclamation exclam + exclamations exclam + excludes exclud + excommunicate excommun + excommunication excommun + excrement excrement + excrements excrement + excursion excurs + excursions excurs + excus excu + excusable excus + excuse excus + excused excus + excuses excus + excusez excusez + excusing excus + execrable execr + execrations execr + execute execut + executed execut + executing execut + execution execut + executioner execution + executioners execution + executor executor + executors executor + exempt exempt + exempted exempt + exequies exequi + exercise exercis + exercises exercis + exeter exet + exeunt exeunt + exhal exhal + exhalation exhal + exhalations exhal + exhale exhal + exhales exhal + exhaust exhaust + exhibit exhibit + exhibiters exhibit + exhibition exhibit + exhort exhort + exhortation exhort + exigent exig + exil exil + exile exil + exiled exil + exion exion + exist exist + exists exist + exit exit + exits exit + exorciser exorcis + exorcisms exorc + exorcist exorcist + expect expect + expectance expect + expectancy expect + expectation expect + expectations expect + expected expect + expecters expect + expecting expect + expects expect + expedience expedi + expedient expedi + expediently expedi + expedition expedit + expeditious expediti + expel expel + expell expel + expelling expel + expels expel + expend expend + expense expens + expenses expens + experienc experienc + experience experi + experiences experi + experiment experi + experimental experiment + experiments experi + expert expert + expertness expert + expiate expiat + expiation expiat + expir expir + expiration expir + expire expir + expired expir + expires expir + expiring expir + explication explic + exploit exploit + exploits exploit + expos expo + expose expos + exposing expos + exposition exposit + expositor expositor + expostulate expostul + expostulation expostul + exposture expostur + exposure exposur + expound expound + expounded expound + express express + expressed express + expresseth expresseth + expressing express + expressive express + expressly expressli + expressure expressur + expuls expul + expulsion expuls + exquisite exquisit + exsufflicate exsuffl + extant extant + extemporal extempor + extemporally extempor + extempore extempor + extend extend + extended extend + extends extend + extent extent + extenuate extenu + extenuated extenu + extenuates extenu + extenuation extenu + exterior exterior + exteriorly exteriorli + exteriors exterior + extermin extermin + extern extern + external extern + extinct extinct + extincted extinct + extincture extinctur + extinguish extinguish + extirp extirp + extirpate extirp + extirped extirp + extol extol + extoll extol + extolment extol + exton exton + extort extort + extorted extort + extortion extort + extortions extort + extra extra + extract extract + extracted extract + extracting extract + extraordinarily extraordinarili + extraordinary extraordinari + extraught extraught + extravagancy extravag + extravagant extravag + extreme extrem + extremely extrem + extremes extrem + extremest extremest + extremities extrem + extremity extrem + exuent exuent + exult exult + exultation exult + ey ey + eyas eya + eyases eyas + eye ey + eyeball eyebal + eyeballs eyebal + eyebrow eyebrow + eyebrows eyebrow + eyed ei + eyeless eyeless + eyelid eyelid + eyelids eyelid + eyes ey + eyesight eyesight + eyestrings eyestr + eying ei + eyne eyn + eyrie eyri + fa fa + fabian fabian + fable fabl + fables fabl + fabric fabric + fabulous fabul + fac fac + face face + faced face + facere facer + faces face + faciant faciant + facile facil + facility facil + facinerious facineri + facing face + facit facit + fact fact + faction faction + factionary factionari + factions faction + factious factiou + factor factor + factors factor + faculties faculti + faculty faculti + fade fade + faded fade + fadeth fadeth + fadge fadg + fading fade + fadings fade + fadom fadom + fadoms fadom + fagot fagot + fagots fagot + fail fail + failing fail + fails fail + fain fain + faint faint + fainted faint + fainter fainter + fainting faint + faintly faintli + faintness faint + faints faint + fair fair + fairer fairer + fairest fairest + fairies fairi + fairing fair + fairings fair + fairly fairli + fairness fair + fairs fair + fairwell fairwel + fairy fairi + fais fai + fait fait + faites fait + faith faith + faithful faith + faithfull faithful + faithfully faithfulli + faithless faithless + faiths faith + faitors faitor + fal fal + falchion falchion + falcon falcon + falconbridge falconbridg + falconer falcon + falconers falcon + fall fall + fallacy fallaci + fallen fallen + falleth falleth + falliable falliabl + fallible fallibl + falling fall + fallow fallow + fallows fallow + falls fall + fally falli + falorous falor + false fals + falsehood falsehood + falsely fals + falseness fals + falser falser + falsify falsifi + falsing fals + falstaff falstaff + falstaffs falstaff + falter falter + fam fam + fame fame + famed fame + familiar familiar + familiarity familiar + familiarly familiarli + familiars familiar + family famili + famine famin + famish famish + famished famish + famous famou + famoused famous + famously famous + fan fan + fanatical fanat + fancies fanci + fancy fanci + fane fane + fanes fane + fang fang + fangled fangl + fangless fangless + fangs fang + fann fann + fanning fan + fans fan + fantasied fantasi + fantasies fantasi + fantastic fantast + fantastical fantast + fantastically fantast + fantasticoes fantastico + fantasy fantasi + fap fap + far far + farborough farborough + farced farc + fardel fardel + fardels fardel + fare fare + fares fare + farewell farewel + farewells farewel + fariner farin + faring fare + farm farm + farmer farmer + farmhouse farmhous + farms farm + farre farr + farrow farrow + farther farther + farthest farthest + farthing farth + farthingale farthingal + farthingales farthingal + farthings farth + fartuous fartuou + fas fa + fashion fashion + fashionable fashion + fashioning fashion + fashions fashion + fast fast + fasted fast + fasten fasten + fastened fasten + faster faster + fastest fastest + fasting fast + fastly fastli + fastolfe fastolf + fasts fast + fat fat + fatal fatal + fatally fatal + fate fate + fated fate + fates fate + father father + fathered father + fatherless fatherless + fatherly fatherli + fathers father + fathom fathom + fathomless fathomless + fathoms fathom + fatigate fatig + fatness fat + fats fat + fatted fat + fatter fatter + fattest fattest + fatting fat + fatuus fatuu + fauconbridge fauconbridg + faulconbridge faulconbridg + fault fault + faultiness faulti + faultless faultless + faults fault + faulty faulti + fausse fauss + fauste faust + faustuses faustus + faut faut + favor favor + favorable favor + favorably favor + favors favor + favour favour + favourable favour + favoured favour + favouredly favouredli + favourer favour + favourers favour + favouring favour + favourite favourit + favourites favourit + favours favour + favout favout + fawn fawn + fawneth fawneth + fawning fawn + fawns fawn + fay fai + fe fe + fealty fealti + fear fear + feared fear + fearest fearest + fearful fear + fearfull fearful + fearfully fearfulli + fearfulness fear + fearing fear + fearless fearless + fears fear + feast feast + feasted feast + feasting feast + feasts feast + feat feat + feated feat + feater feater + feather feather + feathered feather + feathers feather + featly featli + feats feat + featur featur + feature featur + featured featur + featureless featureless + features featur + february februari + fecks feck + fed fed + fedary fedari + federary federari + fee fee + feeble feebl + feebled feebl + feebleness feebl + feebling feebl + feebly feebli + feed feed + feeder feeder + feeders feeder + feedeth feedeth + feeding feed + feeds feed + feel feel + feeler feeler + feeling feel + feelingly feelingli + feels feel + fees fee + feet feet + fehemently fehement + feign feign + feigned feign + feigning feign + feil feil + feith feith + felicitate felicit + felicity felic + fell fell + fellest fellest + fellies felli + fellow fellow + fellowly fellowli + fellows fellow + fellowship fellowship + fellowships fellowship + fells fell + felon felon + felonious feloni + felony feloni + felt felt + female femal + females femal + feminine feminin + fen fen + fenc fenc + fence fenc + fencer fencer + fencing fenc + fends fend + fennel fennel + fenny fenni + fens fen + fenton fenton + fer fer + ferdinand ferdinand + fere fere + fernseed fernse + ferrara ferrara + ferrers ferrer + ferret ferret + ferry ferri + ferryman ferryman + fertile fertil + fertility fertil + fervency fervenc + fervour fervour + fery feri + fest fest + feste fest + fester fester + festinate festin + festinately festin + festival festiv + festivals festiv + fet fet + fetch fetch + fetches fetch + fetching fetch + fetlock fetlock + fetlocks fetlock + fett fett + fetter fetter + fettering fetter + fetters fetter + fettle fettl + feu feu + feud feud + fever fever + feverous fever + fevers fever + few few + fewer fewer + fewest fewest + fewness few + fickle fickl + fickleness fickl + fico fico + fiction fiction + fiddle fiddl + fiddler fiddler + fiddlestick fiddlestick + fidele fidel + fidelicet fidelicet + fidelity fidel + fidius fidiu + fie fie + field field + fielded field + fields field + fiend fiend + fiends fiend + fierce fierc + fiercely fierc + fierceness fierc + fiery fieri + fife fife + fifes fife + fifteen fifteen + fifteens fifteen + fifteenth fifteenth + fifth fifth + fifty fifti + fiftyfold fiftyfold + fig fig + fight fight + fighter fighter + fightest fightest + fighteth fighteth + fighting fight + fights fight + figo figo + figs fig + figur figur + figure figur + figured figur + figures figur + figuring figur + fike fike + fil fil + filberts filbert + filch filch + filches filch + filching filch + file file + filed file + files file + filial filial + filius filiu + fill fill + filled fill + fillet fillet + filling fill + fillip fillip + fills fill + filly filli + film film + fils fil + filth filth + filths filth + filthy filthi + fin fin + finally final + finch finch + find find + finder finder + findeth findeth + finding find + findings find + finds find + fine fine + fineless fineless + finely fine + finem finem + fineness fine + finer finer + fines fine + finest finest + fing fing + finger finger + fingering finger + fingers finger + fingre fingr + fingres fingr + finical finic + finish finish + finished finish + finisher finish + finless finless + finn finn + fins fin + finsbury finsburi + fir fir + firago firago + fire fire + firebrand firebrand + firebrands firebrand + fired fire + fires fire + firework firework + fireworks firework + firing fire + firk firk + firm firm + firmament firmament + firmly firmli + firmness firm + first first + firstlings firstl + fish fish + fisher fisher + fishermen fishermen + fishers fisher + fishes fish + fishified fishifi + fishmonger fishmong + fishpond fishpond + fisnomy fisnomi + fist fist + fisting fist + fists fist + fistula fistula + fit fit + fitchew fitchew + fitful fit + fitly fitli + fitment fitment + fitness fit + fits fit + fitted fit + fitter fitter + fittest fittest + fitteth fitteth + fitting fit + fitzwater fitzwat + five five + fivepence fivep + fives five + fix fix + fixed fix + fixes fix + fixeth fixeth + fixing fix + fixture fixtur + fl fl + flag flag + flagging flag + flagon flagon + flagons flagon + flags flag + flail flail + flakes flake + flaky flaki + flam flam + flame flame + flamen flamen + flamens flamen + flames flame + flaming flame + flaminius flaminiu + flanders flander + flannel flannel + flap flap + flaring flare + flash flash + flashes flash + flashing flash + flask flask + flat flat + flatly flatli + flatness flat + flats flat + flatt flatt + flatter flatter + flattered flatter + flatterer flatter + flatterers flatter + flatterest flatterest + flatteries flatteri + flattering flatter + flatters flatter + flattery flatteri + flaunts flaunt + flavio flavio + flavius flaviu + flaw flaw + flaws flaw + flax flax + flaxen flaxen + flay flai + flaying flai + flea flea + fleance fleanc + fleas flea + flecked fleck + fled fled + fledge fledg + flee flee + fleec fleec + fleece fleec + fleeces fleec + fleer fleer + fleering fleer + fleers fleer + fleet fleet + fleeter fleeter + fleeting fleet + fleming fleme + flemish flemish + flesh flesh + fleshes flesh + fleshly fleshli + fleshment fleshment + fleshmonger fleshmong + flew flew + flexible flexibl + flexure flexur + flibbertigibbet flibbertigibbet + flickering flicker + flidge flidg + fliers flier + flies fli + flieth flieth + flight flight + flights flight + flighty flighti + flinch flinch + fling fling + flint flint + flints flint + flinty flinti + flirt flirt + float float + floated float + floating float + flock flock + flocks flock + flood flood + floodgates floodgat + floods flood + floor floor + flora flora + florence florenc + florentine florentin + florentines florentin + florentius florentiu + florizel florizel + flote flote + floulish floulish + flour flour + flourish flourish + flourishes flourish + flourisheth flourisheth + flourishing flourish + flout flout + flouted flout + flouting flout + flouts flout + flow flow + flowed flow + flower flower + flowerets floweret + flowers flower + flowing flow + flown flown + flows flow + fluellen fluellen + fluent fluent + flung flung + flush flush + flushing flush + fluster fluster + flute flute + flutes flute + flutter flutter + flux flux + fluxive fluxiv + fly fly + flying fly + fo fo + foal foal + foals foal + foam foam + foamed foam + foaming foam + foams foam + foamy foami + fob fob + focative foc + fodder fodder + foe foe + foeman foeman + foemen foemen + foes foe + fog fog + foggy foggi + fogs fog + foh foh + foi foi + foil foil + foiled foil + foils foil + foin foin + foining foin + foins foin + fois foi + foison foison + foisons foison + foist foist + foix foix + fold fold + folded fold + folds fold + folio folio + folk folk + folks folk + follies folli + follow follow + followed follow + follower follow + followers follow + followest followest + following follow + follows follow + folly folli + fond fond + fonder fonder + fondly fondli + fondness fond + font font + fontibell fontibel + food food + fool fool + fooleries fooleri + foolery fooleri + foolhardy foolhardi + fooling fool + foolish foolish + foolishly foolishli + foolishness foolish + fools fool + foot foot + football footbal + footboy footboi + footboys footboi + footed foot + footfall footfal + footing foot + footman footman + footmen footmen + footpath footpath + footsteps footstep + footstool footstool + fopp fopp + fopped fop + foppery fopperi + foppish foppish + fops fop + for for + forage forag + foragers forag + forbade forbad + forbear forbear + forbearance forbear + forbears forbear + forbid forbid + forbidden forbidden + forbiddenly forbiddenli + forbids forbid + forbod forbod + forborne forborn + forc forc + force forc + forced forc + forceful forc + forceless forceless + forces forc + forcible forcibl + forcibly forcibl + forcing forc + ford ford + fordid fordid + fordo fordo + fordoes fordo + fordone fordon + fore fore + forecast forecast + forefather forefath + forefathers forefath + forefinger forefing + forego forego + foregone foregon + forehand forehand + forehead forehead + foreheads forehead + forehorse forehors + foreign foreign + foreigner foreign + foreigners foreign + foreknowing foreknow + foreknowledge foreknowledg + foremost foremost + forenamed forenam + forenoon forenoon + forerun forerun + forerunner forerunn + forerunning forerun + foreruns forerun + foresaid foresaid + foresaw foresaw + foresay foresai + foresee forese + foreseeing forese + foresees forese + foreshow foreshow + foreskirt foreskirt + forespent foresp + forest forest + forestall forestal + forestalled forestal + forester forest + foresters forest + forests forest + foretell foretel + foretelling foretel + foretells foretel + forethink forethink + forethought forethought + foretold foretold + forever forev + foreward foreward + forewarn forewarn + forewarned forewarn + forewarning forewarn + forfeit forfeit + forfeited forfeit + forfeiters forfeit + forfeiting forfeit + forfeits forfeit + forfeiture forfeitur + forfeitures forfeitur + forfend forfend + forfended forfend + forg forg + forgave forgav + forge forg + forged forg + forgeries forgeri + forgery forgeri + forges forg + forget forget + forgetful forget + forgetfulness forget + forgetive forget + forgets forget + forgetting forget + forgive forgiv + forgiven forgiven + forgiveness forgiv + forgo forgo + forgoing forgo + forgone forgon + forgot forgot + forgotten forgotten + fork fork + forked fork + forks fork + forlorn forlorn + form form + formal formal + formally formal + formed form + former former + formerly formerli + formless formless + forms form + fornication fornic + fornications fornic + fornicatress fornicatress + forres forr + forrest forrest + forsake forsak + forsaken forsaken + forsaketh forsaketh + forslow forslow + forsook forsook + forsooth forsooth + forspent forspent + forspoke forspok + forswear forswear + forswearing forswear + forswore forswor + forsworn forsworn + fort fort + forted fort + forth forth + forthcoming forthcom + forthlight forthlight + forthright forthright + forthwith forthwith + fortification fortif + fortifications fortif + fortified fortifi + fortifies fortifi + fortify fortifi + fortinbras fortinbra + fortitude fortitud + fortnight fortnight + fortress fortress + fortresses fortress + forts fort + fortun fortun + fortuna fortuna + fortunate fortun + fortunately fortun + fortune fortun + fortuned fortun + fortunes fortun + fortward fortward + forty forti + forum forum + forward forward + forwarding forward + forwardness forward + forwards forward + forwearied forweari + fosset fosset + fost fost + foster foster + fostered foster + fought fought + foughten foughten + foul foul + fouler fouler + foulest foulest + foully foulli + foulness foul + found found + foundation foundat + foundations foundat + founded found + founder founder + fount fount + fountain fountain + fountains fountain + founts fount + four four + fourscore fourscor + fourteen fourteen + fourth fourth + foutra foutra + fowl fowl + fowler fowler + fowling fowl + fowls fowl + fox fox + foxes fox + foxship foxship + fracted fract + fraction fraction + fractions fraction + fragile fragil + fragment fragment + fragments fragment + fragrant fragrant + frail frail + frailer frailer + frailties frailti + frailty frailti + fram fram + frame frame + framed frame + frames frame + frampold frampold + fran fran + francais francai + france franc + frances franc + franchise franchis + franchised franchis + franchisement franchis + franchises franchis + franciae francia + francis franci + francisca francisca + franciscan franciscan + francisco francisco + frank frank + franker franker + frankfort frankfort + franklin franklin + franklins franklin + frankly frankli + frankness frank + frantic frantic + franticly franticli + frateretto frateretto + fratrum fratrum + fraud fraud + fraudful fraud + fraught fraught + fraughtage fraughtag + fraughting fraught + fray frai + frays frai + freckl freckl + freckled freckl + freckles freckl + frederick frederick + free free + freed freed + freedom freedom + freedoms freedom + freehearted freeheart + freelier freelier + freely freeli + freeman freeman + freemen freemen + freeness freeness + freer freer + frees free + freestone freeston + freetown freetown + freeze freez + freezes freez + freezing freez + freezings freez + french french + frenchman frenchman + frenchmen frenchmen + frenchwoman frenchwoman + frenzy frenzi + frequent frequent + frequents frequent + fresh fresh + fresher fresher + freshes fresh + freshest freshest + freshly freshli + freshness fresh + fret fret + fretful fret + frets fret + fretted fret + fretten fretten + fretting fret + friar friar + friars friar + friday fridai + fridays fridai + friend friend + friended friend + friending friend + friendless friendless + friendliness friendli + friendly friendli + friends friend + friendship friendship + friendships friendship + frieze friez + fright fright + frighted fright + frightened frighten + frightful fright + frighting fright + frights fright + fringe fring + fringed fring + frippery fripperi + frisk frisk + fritters fritter + frivolous frivol + fro fro + frock frock + frog frog + frogmore frogmor + froissart froissart + frolic frolic + from from + front front + fronted front + frontier frontier + frontiers frontier + fronting front + frontlet frontlet + fronts front + frost frost + frosts frost + frosty frosti + froth froth + froward froward + frown frown + frowning frown + frowningly frowningli + frowns frown + froze froze + frozen frozen + fructify fructifi + frugal frugal + fruit fruit + fruiterer fruiter + fruitful fruit + fruitfully fruitfulli + fruitfulness fruit + fruition fruition + fruitless fruitless + fruits fruit + frush frush + frustrate frustrat + frutify frutifi + fry fry + fubb fubb + fuel fuel + fugitive fugit + fulfil fulfil + fulfill fulfil + fulfilling fulfil + fulfils fulfil + full full + fullam fullam + fuller fuller + fullers fuller + fullest fullest + fullness full + fully fulli + fulness ful + fulsome fulsom + fulvia fulvia + fum fum + fumble fumbl + fumbles fumbl + fumblest fumblest + fumbling fumbl + fume fume + fumes fume + fuming fume + fumiter fumit + fumitory fumitori + fun fun + function function + functions function + fundamental fundament + funeral funer + funerals funer + fur fur + furbish furbish + furies furi + furious furiou + furlongs furlong + furnace furnac + furnaces furnac + furnish furnish + furnished furnish + furnishings furnish + furniture furnitur + furnival furniv + furor furor + furr furr + furrow furrow + furrowed furrow + furrows furrow + furth furth + further further + furtherance further + furtherer further + furthermore furthermor + furthest furthest + fury furi + furze furz + furzes furz + fust fust + fustian fustian + fustilarian fustilarian + fusty fusti + fut fut + future futur + futurity futur + g g + gabble gabbl + gaberdine gaberdin + gabriel gabriel + gad gad + gadding gad + gads gad + gadshill gadshil + gag gag + gage gage + gaged gage + gagg gagg + gaging gage + gagne gagn + gain gain + gained gain + gainer gainer + gaingiving gaingiv + gains gain + gainsaid gainsaid + gainsay gainsai + gainsaying gainsai + gainsays gainsai + gainst gainst + gait gait + gaited gait + galathe galath + gale gale + galen galen + gales gale + gall gall + gallant gallant + gallantly gallantli + gallantry gallantri + gallants gallant + galled gall + gallery galleri + galley gallei + galleys gallei + gallia gallia + gallian gallian + galliard galliard + galliasses galliass + gallimaufry gallimaufri + galling gall + gallons gallon + gallop gallop + galloping gallop + gallops gallop + gallow gallow + galloway gallowai + gallowglasses gallowglass + gallows gallow + gallowses gallows + galls gall + gallus gallu + gam gam + gambol gambol + gambold gambold + gambols gambol + gamboys gamboi + game game + gamers gamer + games game + gamesome gamesom + gamester gamest + gaming game + gammon gammon + gamut gamut + gan gan + gangren gangren + ganymede ganymed + gaol gaol + gaoler gaoler + gaolers gaoler + gaols gaol + gap gap + gape gape + gapes gape + gaping gape + gar gar + garb garb + garbage garbag + garboils garboil + garcon garcon + gard gard + garde gard + garden garden + gardener garden + gardeners garden + gardens garden + gardez gardez + gardiner gardin + gardon gardon + gargantua gargantua + gargrave gargrav + garish garish + garland garland + garlands garland + garlic garlic + garment garment + garments garment + garmet garmet + garner garner + garners garner + garnish garnish + garnished garnish + garret garret + garrison garrison + garrisons garrison + gart gart + garter garter + garterd garterd + gartering garter + garters garter + gascony gasconi + gash gash + gashes gash + gaskins gaskin + gasp gasp + gasping gasp + gasted gast + gastness gast + gat gat + gate gate + gated gate + gates gate + gath gath + gather gather + gathered gather + gathering gather + gathers gather + gatories gatori + gatory gatori + gaud gaud + gaudeo gaudeo + gaudy gaudi + gauge gaug + gaul gaul + gaultree gaultre + gaunt gaunt + gauntlet gauntlet + gauntlets gauntlet + gav gav + gave gave + gavest gavest + gawded gawd + gawds gawd + gawsey gawsei + gay gai + gayness gay + gaz gaz + gaze gaze + gazed gaze + gazer gazer + gazers gazer + gazes gaze + gazeth gazeth + gazing gaze + gear gear + geck geck + geese gees + geffrey geffrei + geld geld + gelded geld + gelding geld + gelida gelida + gelidus gelidu + gelt gelt + gem gem + geminy gemini + gems gem + gen gen + gender gender + genders gender + general gener + generally gener + generals gener + generation gener + generations gener + generative gener + generosity generos + generous gener + genitive genit + genitivo genitivo + genius geniu + gennets gennet + genoa genoa + genoux genoux + gens gen + gent gent + gentilhomme gentilhomm + gentility gentil + gentle gentl + gentlefolks gentlefolk + gentleman gentleman + gentlemanlike gentlemanlik + gentlemen gentlemen + gentleness gentl + gentler gentler + gentles gentl + gentlest gentlest + gentlewoman gentlewoman + gentlewomen gentlewomen + gently gentli + gentry gentri + george georg + gerard gerard + germaines germain + germains germain + german german + germane german + germans german + germany germani + gertrude gertrud + gest gest + gests gest + gesture gestur + gestures gestur + get get + getrude getrud + gets get + getter getter + getting get + ghastly ghastli + ghost ghost + ghosted ghost + ghostly ghostli + ghosts ghost + gi gi + giant giant + giantess giantess + giantlike giantlik + giants giant + gib gib + gibber gibber + gibbet gibbet + gibbets gibbet + gibe gibe + giber giber + gibes gibe + gibing gibe + gibingly gibingli + giddily giddili + giddiness giddi + giddy giddi + gift gift + gifts gift + gig gig + giglets giglet + giglot giglot + gilbert gilbert + gild gild + gilded gild + gilding gild + gilliams gilliam + gillian gillian + gills gill + gillyvors gillyvor + gilt gilt + gimmal gimmal + gimmers gimmer + gin gin + ging ging + ginger ginger + gingerbread gingerbread + gingerly gingerli + ginn ginn + gins gin + gioucestershire gioucestershir + gipes gipe + gipsies gipsi + gipsy gipsi + gird gird + girded gird + girdle girdl + girdled girdl + girdles girdl + girdling girdl + girl girl + girls girl + girt girt + girth girth + gis gi + giv giv + give give + given given + giver giver + givers giver + gives give + givest givest + giveth giveth + giving give + givings give + glad glad + gladded glad + gladding glad + gladly gladli + gladness glad + glamis glami + glanc glanc + glance glanc + glanced glanc + glances glanc + glancing glanc + glanders glander + glansdale glansdal + glare glare + glares glare + glass glass + glasses glass + glassy glassi + glaz glaz + glazed glaze + gleams gleam + glean glean + gleaned glean + gleaning glean + gleeful gleeful + gleek gleek + gleeking gleek + gleeks gleek + glend glend + glendower glendow + glib glib + glide glide + glided glide + glides glide + glideth glideth + gliding glide + glimmer glimmer + glimmering glimmer + glimmers glimmer + glimpse glimps + glimpses glimps + glist glist + glistening glisten + glister glister + glistering glister + glisters glister + glitt glitt + glittering glitter + globe globe + globes globe + glooming gloom + gloomy gloomi + glories glori + glorified glorifi + glorify glorifi + glorious gloriou + gloriously glorious + glory glori + glose glose + gloss gloss + glosses gloss + glou glou + glouceste gloucest + gloucester gloucest + gloucestershire gloucestershir + glove glove + glover glover + gloves glove + glow glow + glowed glow + glowing glow + glowworm glowworm + gloz gloz + gloze gloze + glozes gloze + glu glu + glue glue + glued glu + glues glue + glut glut + glutt glutt + glutted glut + glutton glutton + gluttoning glutton + gluttony gluttoni + gnarled gnarl + gnarling gnarl + gnat gnat + gnats gnat + gnaw gnaw + gnawing gnaw + gnawn gnawn + gnaws gnaw + go go + goad goad + goaded goad + goads goad + goal goal + goat goat + goatish goatish + goats goat + gobbets gobbet + gobbo gobbo + goblet goblet + goblets goblet + goblin goblin + goblins goblin + god god + godded god + godden godden + goddess goddess + goddesses goddess + goddild goddild + godfather godfath + godfathers godfath + godhead godhead + godlike godlik + godliness godli + godly godli + godmother godmoth + gods god + godson godson + goer goer + goers goer + goes goe + goest goest + goeth goeth + goffe goff + gogs gog + going go + gold gold + golden golden + goldenly goldenli + goldsmith goldsmith + goldsmiths goldsmith + golgotha golgotha + goliases golias + goliath goliath + gon gon + gondola gondola + gondolier gondoli + gone gone + goneril goneril + gong gong + gonzago gonzago + gonzalo gonzalo + good good + goodfellow goodfellow + goodlier goodlier + goodliest goodliest + goodly goodli + goodman goodman + goodness good + goodnight goodnight + goodrig goodrig + goods good + goodwife goodwif + goodwill goodwil + goodwin goodwin + goodwins goodwin + goodyear goodyear + goodyears goodyear + goose goos + gooseberry gooseberri + goosequills goosequil + goot goot + gor gor + gorbellied gorbelli + gorboduc gorboduc + gordian gordian + gore gore + gored gore + gorg gorg + gorge gorg + gorgeous gorgeou + gorget gorget + gorging gorg + gorgon gorgon + gormandize gormand + gormandizing gormand + gory gori + gosling gosl + gospel gospel + gospels gospel + goss goss + gossamer gossam + gossip gossip + gossiping gossip + gossiplike gossiplik + gossips gossip + got got + goth goth + goths goth + gotten gotten + gourd gourd + gout gout + gouts gout + gouty gouti + govern govern + governance govern + governed govern + governess gover + government govern + governor governor + governors governor + governs govern + gower gower + gown gown + gowns gown + grac grac + grace grace + graced grace + graceful grace + gracefully gracefulli + graceless graceless + graces grace + gracing grace + gracious graciou + graciously gracious + gradation gradat + graff graff + graffing graf + graft graft + grafted graft + grafters grafter + grain grain + grained grain + grains grain + gramercies gramerci + gramercy gramerci + grammar grammar + grand grand + grandam grandam + grandame grandam + grandchild grandchild + grande grand + grandeur grandeur + grandfather grandfath + grandjurors grandjuror + grandmother grandmoth + grandpre grandpr + grandsir grandsir + grandsire grandsir + grandsires grandsir + grange grang + grant grant + granted grant + granting grant + grants grant + grape grape + grapes grape + grapple grappl + grapples grappl + grappling grappl + grasp grasp + grasped grasp + grasps grasp + grass grass + grasshoppers grasshopp + grassy grassi + grate grate + grated grate + grateful grate + grates grate + gratiano gratiano + gratify gratifi + gratii gratii + gratillity gratil + grating grate + gratis grati + gratitude gratitud + gratulate gratul + grav grav + grave grave + gravediggers gravedigg + gravel gravel + graveless graveless + gravell gravel + gravely grave + graven graven + graveness grave + graver graver + graves grave + gravest gravest + gravestone graveston + gravities graviti + gravity graviti + gravy gravi + gray grai + graymalkin graymalkin + graz graz + graze graze + grazed graze + grazing graze + grease greas + greases greas + greasily greasili + greasy greasi + great great + greater greater + greatest greatest + greatly greatli + greatness great + grecian grecian + grecians grecian + gree gree + greece greec + greed greed + greedily greedili + greediness greedi + greedy greedi + greeing gree + greek greek + greekish greekish + greeks greek + green green + greener greener + greenly greenli + greens green + greensleeves greensleev + greenwich greenwich + greenwood greenwood + greet greet + greeted greet + greeting greet + greetings greet + greets greet + greg greg + gregory gregori + gremio gremio + grew grew + grey grei + greybeard greybeard + greybeards greybeard + greyhound greyhound + greyhounds greyhound + grief grief + griefs grief + griev griev + grievance grievanc + grievances grievanc + grieve griev + grieved griev + grieves griev + grievest grievest + grieving griev + grievingly grievingli + grievous grievou + grievously grievous + griffin griffin + griffith griffith + grim grim + grime grime + grimly grimli + grin grin + grind grind + grinding grind + grindstone grindston + grinning grin + grip grip + gripe gripe + gripes gripe + griping gripe + grise grise + grisly grisli + grissel grissel + grize grize + grizzle grizzl + grizzled grizzl + groan groan + groaning groan + groans groan + groat groat + groats groat + groin groin + groom groom + grooms groom + grop grop + groping grope + gros gro + gross gross + grosser grosser + grossly grossli + grossness gross + ground ground + grounded ground + groundlings groundl + grounds ground + grove grove + grovel grovel + grovelling grovel + groves grove + grow grow + groweth groweth + growing grow + grown grown + grows grow + growth growth + grub grub + grubb grubb + grubs grub + grudge grudg + grudged grudg + grudges grudg + grudging grudg + gruel gruel + grumble grumbl + grumblest grumblest + grumbling grumbl + grumblings grumbl + grumio grumio + grund grund + grunt grunt + gualtier gualtier + guard guard + guardage guardag + guardant guardant + guarded guard + guardian guardian + guardians guardian + guards guard + guardsman guardsman + gud gud + gudgeon gudgeon + guerdon guerdon + guerra guerra + guess guess + guesses guess + guessingly guessingli + guest guest + guests guest + guiana guiana + guichard guichard + guide guid + guided guid + guider guider + guiderius guideriu + guides guid + guiding guid + guidon guidon + guienne guienn + guil guil + guildenstern guildenstern + guilders guilder + guildford guildford + guildhall guildhal + guile guil + guiled guil + guileful guil + guilfords guilford + guilt guilt + guiltian guiltian + guiltier guiltier + guiltily guiltili + guiltiness guilti + guiltless guiltless + guilts guilt + guilty guilti + guinea guinea + guinever guinev + guise guis + gul gul + gules gule + gulf gulf + gulfs gulf + gull gull + gulls gull + gum gum + gumm gumm + gums gum + gun gun + gunner gunner + gunpowder gunpowd + guns gun + gurnet gurnet + gurney gurnei + gust gust + gusts gust + gusty gusti + guts gut + gutter gutter + guy gui + guynes guyn + guysors guysor + gypsy gypsi + gyve gyve + gyved gyve + gyves gyve + h h + ha ha + haberdasher haberdash + habiliment habili + habiliments habili + habit habit + habitation habit + habited habit + habits habit + habitude habitud + hack hack + hacket hacket + hackney hacknei + hacks hack + had had + hadst hadst + haec haec + haeres haer + hag hag + hagar hagar + haggard haggard + haggards haggard + haggish haggish + haggled haggl + hags hag + hail hail + hailed hail + hailstone hailston + hailstones hailston + hair hair + hairless hairless + hairs hair + hairy hairi + hal hal + halberd halberd + halberds halberd + halcyon halcyon + hale hale + haled hale + hales hale + half half + halfcan halfcan + halfpence halfpenc + halfpenny halfpenni + halfpennyworth halfpennyworth + halfway halfwai + halidom halidom + hall hall + halloa halloa + halloing hallo + hallond hallond + halloo halloo + hallooing halloo + hallow hallow + hallowed hallow + hallowmas hallowma + hallown hallown + hals hal + halt halt + halter halter + halters halter + halting halt + halts halt + halves halv + ham ham + hames hame + hamlet hamlet + hammer hammer + hammered hammer + hammering hammer + hammers hammer + hamper hamper + hampton hampton + hams ham + hamstring hamstr + hand hand + handed hand + handful hand + handicraft handicraft + handicraftsmen handicraftsmen + handing hand + handiwork handiwork + handkercher handkerch + handkerchers handkerch + handkerchief handkerchief + handle handl + handled handl + handles handl + handless handless + handlest handlest + handling handl + handmaid handmaid + handmaids handmaid + hands hand + handsaw handsaw + handsome handsom + handsomely handsom + handsomeness handsom + handwriting handwrit + handy handi + hang hang + hanged hang + hangers hanger + hangeth hangeth + hanging hang + hangings hang + hangman hangman + hangmen hangmen + hangs hang + hannibal hannib + hap hap + hapless hapless + haply hapli + happ happ + happen happen + happened happen + happier happier + happies happi + happiest happiest + happily happili + happiness happi + happy happi + haps hap + harbinger harbing + harbingers harbing + harbor harbor + harbour harbour + harbourage harbourag + harbouring harbour + harbours harbour + harcourt harcourt + hard hard + harder harder + hardest hardest + hardiest hardiest + hardiment hardiment + hardiness hardi + hardly hardli + hardness hard + hardocks hardock + hardy hardi + hare hare + harelip harelip + hares hare + harfleur harfleur + hark hark + harlot harlot + harlotry harlotri + harlots harlot + harm harm + harmed harm + harmful harm + harming harm + harmless harmless + harmonious harmoni + harmony harmoni + harms harm + harness har + harp harp + harper harper + harpier harpier + harping harp + harpy harpi + harried harri + harrow harrow + harrows harrow + harry harri + harsh harsh + harshly harshli + harshness harsh + hart hart + harts hart + harum harum + harvest harvest + has ha + hast hast + haste hast + hasted hast + hasten hasten + hastes hast + hastily hastili + hasting hast + hastings hast + hasty hasti + hat hat + hatch hatch + hatches hatch + hatchet hatchet + hatching hatch + hatchment hatchment + hate hate + hated hate + hateful hate + hater hater + haters hater + hates hate + hateth hateth + hatfield hatfield + hath hath + hating hate + hatred hatr + hats hat + haud haud + hauf hauf + haught haught + haughtiness haughti + haughty haughti + haunch haunch + haunches haunch + haunt haunt + haunted haunt + haunting haunt + haunts haunt + hautboy hautboi + hautboys hautboi + have have + haven haven + havens haven + haver haver + having have + havings have + havior havior + haviour haviour + havoc havoc + hawk hawk + hawking hawk + hawks hawk + hawthorn hawthorn + hawthorns hawthorn + hay hai + hazard hazard + hazarded hazard + hazards hazard + hazel hazel + hazelnut hazelnut + he he + head head + headborough headborough + headed head + headier headier + heading head + headland headland + headless headless + headlong headlong + heads head + headsman headsman + headstrong headstrong + heady headi + heal heal + healed heal + healing heal + heals heal + health health + healthful health + healths health + healthsome healthsom + healthy healthi + heap heap + heaping heap + heaps heap + hear hear + heard heard + hearer hearer + hearers hearer + hearest hearest + heareth heareth + hearing hear + hearings hear + heark heark + hearken hearken + hearkens hearken + hears hear + hearsay hearsai + hearse hears + hearsed hears + hearst hearst + heart heart + heartache heartach + heartbreak heartbreak + heartbreaking heartbreak + hearted heart + hearten hearten + hearth hearth + hearths hearth + heartily heartili + heartiness hearti + heartless heartless + heartlings heartl + heartly heartli + hearts heart + heartsick heartsick + heartstrings heartstr + hearty hearti + heat heat + heated heat + heath heath + heathen heathen + heathenish heathenish + heating heat + heats heat + heauties heauti + heav heav + heave heav + heaved heav + heaven heaven + heavenly heavenli + heavens heaven + heaves heav + heavier heavier + heaviest heaviest + heavily heavili + heaviness heavi + heaving heav + heavings heav + heavy heavi + hebona hebona + hebrew hebrew + hecate hecat + hectic hectic + hector hector + hectors hector + hecuba hecuba + hedg hedg + hedge hedg + hedgehog hedgehog + hedgehogs hedgehog + hedges hedg + heed heed + heeded heed + heedful heed + heedfull heedful + heedfully heedfulli + heedless heedless + heel heel + heels heel + hefted heft + hefts heft + heifer heifer + heifers heifer + heigh heigh + height height + heighten heighten + heinous heinou + heinously heinous + heir heir + heiress heiress + heirless heirless + heirs heir + held held + helen helen + helena helena + helenus helenu + helias helia + helicons helicon + hell hell + hellespont hellespont + hellfire hellfir + hellish hellish + helm helm + helmed helm + helmet helmet + helmets helmet + helms helm + help help + helper helper + helpers helper + helpful help + helping help + helpless helpless + helps help + helter helter + hem hem + heme heme + hemlock hemlock + hemm hemm + hemp hemp + hempen hempen + hems hem + hen hen + hence henc + henceforth henceforth + henceforward henceforward + henchman henchman + henri henri + henricus henricu + henry henri + hens hen + hent hent + henton henton + her her + herald herald + heraldry heraldri + heralds herald + herb herb + herbert herbert + herblets herblet + herbs herb + herculean herculean + hercules hercul + herd herd + herds herd + herdsman herdsman + herdsmen herdsmen + here here + hereabout hereabout + hereabouts hereabout + hereafter hereaft + hereby herebi + hereditary hereditari + hereford hereford + herefordshire herefordshir + herein herein + hereof hereof + heresies heresi + heresy heresi + heretic heret + heretics heret + hereto hereto + hereupon hereupon + heritage heritag + heritier heriti + hermes herm + hermia hermia + hermione hermion + hermit hermit + hermitage hermitag + hermits hermit + herne hern + hero hero + herod herod + herods herod + heroes hero + heroic heroic + heroical heroic + herring her + herrings her + hers her + herself herself + hesperides hesperid + hesperus hesperu + hest hest + hests hest + heure heur + heureux heureux + hew hew + hewgh hewgh + hewing hew + hewn hewn + hews hew + hey hei + heyday heydai + hibocrates hibocr + hic hic + hiccups hiccup + hick hick + hid hid + hidden hidden + hide hide + hideous hideou + hideously hideous + hideousness hideous + hides hide + hidest hidest + hiding hide + hie hie + hied hi + hiems hiem + hies hi + hig hig + high high + higher higher + highest highest + highly highli + highmost highmost + highness high + hight hight + highway highwai + highways highwai + hilding hild + hildings hild + hill hill + hillo hillo + hilloa hilloa + hills hill + hilt hilt + hilts hilt + hily hili + him him + himself himself + hinc hinc + hinckley hincklei + hind hind + hinder hinder + hindered hinder + hinders hinder + hindmost hindmost + hinds hind + hing hing + hinge hing + hinges hing + hint hint + hip hip + hipp hipp + hipparchus hipparchu + hippolyta hippolyta + hips hip + hir hir + hire hire + hired hire + hiren hiren + hirtius hirtiu + his hi + hisperia hisperia + hiss hiss + hisses hiss + hissing hiss + hist hist + historical histor + history histori + hit hit + hither hither + hitherto hitherto + hitherward hitherward + hitherwards hitherward + hits hit + hitting hit + hive hive + hives hive + hizzing hizz + ho ho + hoa hoa + hoar hoar + hoard hoard + hoarded hoard + hoarding hoard + hoars hoar + hoarse hoars + hoary hoari + hob hob + hobbididence hobbidid + hobby hobbi + hobbyhorse hobbyhors + hobgoblin hobgoblin + hobnails hobnail + hoc hoc + hod hod + hodge hodg + hog hog + hogs hog + hogshead hogshead + hogsheads hogshead + hois hoi + hoise hois + hoist hoist + hoisted hoist + hoists hoist + holborn holborn + hold hold + holden holden + holder holder + holdeth holdeth + holdfast holdfast + holding hold + holds hold + hole hole + holes hole + holidam holidam + holidame holidam + holiday holidai + holidays holidai + holier holier + holiest holiest + holily holili + holiness holi + holla holla + holland holland + hollander holland + hollanders holland + holloa holloa + holloaing holloa + hollow hollow + hollowly hollowli + hollowness hollow + holly holli + holmedon holmedon + holofernes holofern + holp holp + holy holi + homage homag + homager homag + home home + homely home + homes home + homespuns homespun + homeward homeward + homewards homeward + homicide homicid + homicides homicid + homily homili + hominem hominem + hommes homm + homo homo + honest honest + honester honest + honestest honestest + honestly honestli + honesty honesti + honey honei + honeycomb honeycomb + honeying honei + honeyless honeyless + honeysuckle honeysuckl + honeysuckles honeysuckl + honi honi + honneur honneur + honor honor + honorable honor + honorably honor + honorato honorato + honors honor + honour honour + honourable honour + honourably honour + honoured honour + honourest honourest + honourible honour + honouring honour + honours honour + hoo hoo + hood hood + hooded hood + hoodman hoodman + hoods hood + hoodwink hoodwink + hoof hoof + hoofs hoof + hook hook + hooking hook + hooks hook + hoop hoop + hoops hoop + hoot hoot + hooted hoot + hooting hoot + hoots hoot + hop hop + hope hope + hopeful hope + hopeless hopeless + hopes hope + hopest hopest + hoping hope + hopkins hopkin + hoppedance hopped + hor hor + horace horac + horatio horatio + horizon horizon + horn horn + hornbook hornbook + horned horn + horner horner + horning horn + hornpipes hornpip + horns horn + horologe horolog + horrible horribl + horribly horribl + horrid horrid + horrider horrid + horridly horridli + horror horror + horrors horror + hors hor + horse hors + horseback horseback + horsed hors + horsehairs horsehair + horseman horseman + horsemanship horsemanship + horsemen horsemen + horses hors + horseway horsewai + horsing hors + hortensio hortensio + hortensius hortensiu + horum horum + hose hose + hospitable hospit + hospital hospit + hospitality hospit + host host + hostage hostag + hostages hostag + hostess hostess + hostile hostil + hostility hostil + hostilius hostiliu + hosts host + hot hot + hotly hotli + hotspur hotspur + hotter hotter + hottest hottest + hound hound + hounds hound + hour hour + hourly hourli + hours hour + hous hou + house hous + household household + householder household + householders household + households household + housekeeper housekeep + housekeepers housekeep + housekeeping housekeep + houseless houseless + houses hous + housewife housewif + housewifery housewiferi + housewives housew + hovel hovel + hover hover + hovered hover + hovering hover + hovers hover + how how + howbeit howbeit + howe how + howeer howeer + however howev + howl howl + howled howl + howlet howlet + howling howl + howls howl + howsoe howso + howsoever howsoev + howsome howsom + hoxes hox + hoy hoi + hoyday hoydai + hubert hubert + huddled huddl + huddling huddl + hue hue + hued hu + hues hue + hug hug + huge huge + hugely huge + hugeness huge + hugg hugg + hugger hugger + hugh hugh + hugs hug + hujus huju + hulk hulk + hulks hulk + hull hull + hulling hull + hullo hullo + hum hum + human human + humane human + humanely human + humanity human + humble humbl + humbled humbl + humbleness humbl + humbler humbler + humbles humbl + humblest humblest + humbling humbl + humbly humbl + hume hume + humh humh + humidity humid + humility humil + humming hum + humor humor + humorous humor + humors humor + humour humour + humourists humourist + humours humour + humphrey humphrei + humphry humphri + hums hum + hundred hundr + hundreds hundr + hundredth hundredth + hung hung + hungarian hungarian + hungary hungari + hunger hunger + hungerford hungerford + hungerly hungerli + hungry hungri + hunt hunt + hunted hunt + hunter hunter + hunters hunter + hunteth hunteth + hunting hunt + huntington huntington + huntress huntress + hunts hunt + huntsman huntsman + huntsmen huntsmen + hurdle hurdl + hurl hurl + hurling hurl + hurls hurl + hurly hurli + hurlyburly hurlyburli + hurricano hurricano + hurricanoes hurricano + hurried hurri + hurries hurri + hurry hurri + hurt hurt + hurting hurt + hurtled hurtl + hurtless hurtless + hurtling hurtl + hurts hurt + husband husband + husbanded husband + husbandless husbandless + husbandry husbandri + husbands husband + hush hush + hushes hush + husht husht + husks husk + huswife huswif + huswifes huswif + hutch hutch + hybla hybla + hydra hydra + hyen hyen + hymen hymen + hymenaeus hymenaeu + hymn hymn + hymns hymn + hyperboles hyperbol + hyperbolical hyperbol + hyperion hyperion + hypocrisy hypocrisi + hypocrite hypocrit + hypocrites hypocrit + hyrcan hyrcan + hyrcania hyrcania + hyrcanian hyrcanian + hyssop hyssop + hysterica hysterica + i i + iachimo iachimo + iaculis iaculi + iago iago + iament iament + ibat ibat + icarus icaru + ice ic + iceland iceland + ici ici + icicle icicl + icicles icicl + icy ici + idea idea + ideas idea + idem idem + iden iden + ides id + idiot idiot + idiots idiot + idle idl + idleness idl + idles idl + idly idli + idol idol + idolatrous idolatr + idolatry idolatri + ield ield + if if + ifs if + ignis igni + ignoble ignobl + ignobly ignobl + ignominious ignomini + ignominy ignomini + ignomy ignomi + ignorance ignor + ignorant ignor + ii ii + iii iii + iiii iiii + il il + ilbow ilbow + ild ild + ilion ilion + ilium ilium + ill ill + illegitimate illegitim + illiterate illiter + illness ill + illo illo + ills ill + illume illum + illumin illumin + illuminate illumin + illumineth illumineth + illusion illus + illusions illus + illustrate illustr + illustrated illustr + illustrious illustri + illyria illyria + illyrian illyrian + ils il + im im + image imag + imagery imageri + images imag + imagin imagin + imaginary imaginari + imagination imagin + imaginations imagin + imagine imagin + imagining imagin + imaginings imagin + imbar imbar + imbecility imbecil + imbrue imbru + imitari imitari + imitate imit + imitated imit + imitation imit + imitations imit + immaculate immacul + immanity imman + immask immask + immaterial immateri + immediacy immediaci + immediate immedi + immediately immedi + imminence immin + imminent immin + immoderate immoder + immoderately immoder + immodest immodest + immoment immoment + immortal immort + immortaliz immortaliz + immortally immort + immur immur + immured immur + immures immur + imogen imogen + imp imp + impaint impaint + impair impair + impairing impair + impale impal + impaled impal + impanelled impanel + impart impart + imparted impart + impartial imparti + impartment impart + imparts impart + impasted impast + impatience impati + impatient impati + impatiently impati + impawn impawn + impeach impeach + impeached impeach + impeachment impeach + impeachments impeach + impedes imped + impediment impedi + impediments impedi + impenetrable impenetr + imperator imper + imperceiverant imperceiver + imperfect imperfect + imperfection imperfect + imperfections imperfect + imperfectly imperfectli + imperial imperi + imperious imperi + imperiously imperi + impertinency impertin + impertinent impertin + impeticos impetico + impetuosity impetuos + impetuous impetu + impieties impieti + impiety impieti + impious impiou + implacable implac + implements implement + implies impli + implor implor + implorators implor + implore implor + implored implor + imploring implor + impon impon + import import + importance import + importancy import + important import + importantly importantli + imported import + importeth importeth + importing import + importless importless + imports import + importun importun + importunacy importunaci + importunate importun + importune importun + importunes importun + importunity importun + impos impo + impose impos + imposed impos + imposition imposit + impositions imposit + impossibilities imposs + impossibility imposs + impossible imposs + imposthume imposthum + impostor impostor + impostors impostor + impotence impot + impotent impot + impounded impound + impregnable impregn + imprese impres + impress impress + impressed impress + impressest impressest + impression impress + impressure impressur + imprimendum imprimendum + imprimis imprimi + imprint imprint + imprinted imprint + imprison imprison + imprisoned imprison + imprisoning imprison + imprisonment imprison + improbable improb + improper improp + improve improv + improvident improvid + impudence impud + impudency impud + impudent impud + impudently impud + impudique impudiqu + impugn impugn + impugns impugn + impure impur + imputation imput + impute imput + in in + inaccessible inaccess + inaidable inaid + inaudible inaud + inauspicious inauspici + incaged incag + incantations incant + incapable incap + incardinate incardin + incarnadine incarnadin + incarnate incarn + incarnation incarn + incens incen + incense incens + incensed incens + incensement incens + incenses incens + incensing incens + incertain incertain + incertainties incertainti + incertainty incertainti + incessant incess + incessantly incessantli + incest incest + incestuous incestu + inch inch + incharitable incharit + inches inch + incidency incid + incident incid + incision incis + incite incit + incites incit + incivil incivil + incivility incivil + inclin inclin + inclinable inclin + inclination inclin + incline inclin + inclined inclin + inclines inclin + inclining inclin + inclips inclip + include includ + included includ + includes includ + inclusive inclus + incomparable incompar + incomprehensible incomprehens + inconsiderate inconsider + inconstancy inconst + inconstant inconst + incontinency incontin + incontinent incontin + incontinently incontin + inconvenience inconveni + inconveniences inconveni + inconvenient inconveni + incony inconi + incorporate incorpor + incorps incorp + incorrect incorrect + increas increa + increase increas + increases increas + increaseth increaseth + increasing increas + incredible incred + incredulous incredul + incur incur + incurable incur + incurr incurr + incurred incur + incursions incurs + ind ind + inde ind + indebted indebt + indeed inde + indent indent + indented indent + indenture indentur + indentures indentur + index index + indexes index + india india + indian indian + indict indict + indicted indict + indictment indict + indies indi + indifferency indiffer + indifferent indiffer + indifferently indiffer + indigent indig + indigest indigest + indigested indigest + indign indign + indignation indign + indignations indign + indigne indign + indignities indign + indignity indign + indirect indirect + indirection indirect + indirections indirect + indirectly indirectli + indiscreet indiscreet + indiscretion indiscret + indispos indispo + indisposition indisposit + indissoluble indissolubl + indistinct indistinct + indistinguish indistinguish + indistinguishable indistinguish + indited indit + individable individ + indrench indrench + indu indu + indubitate indubit + induc induc + induce induc + induced induc + inducement induc + induction induct + inductions induct + indue indu + indued indu + indues indu + indulgence indulg + indulgences indulg + indulgent indulg + indurance indur + industrious industri + industriously industri + industry industri + inequality inequ + inestimable inestim + inevitable inevit + inexecrable inexecr + inexorable inexor + inexplicable inexplic + infallible infal + infallibly infal + infamonize infamon + infamous infam + infamy infami + infancy infanc + infant infant + infants infant + infect infect + infected infect + infecting infect + infection infect + infections infect + infectious infecti + infectiously infecti + infects infect + infer infer + inference infer + inferior inferior + inferiors inferior + infernal infern + inferr inferr + inferreth inferreth + inferring infer + infest infest + infidel infidel + infidels infidel + infinite infinit + infinitely infinit + infinitive infinit + infirm infirm + infirmities infirm + infirmity infirm + infixed infix + infixing infix + inflam inflam + inflame inflam + inflaming inflam + inflammation inflamm + inflict inflict + infliction inflict + influence influenc + influences influenc + infold infold + inform inform + informal inform + information inform + informations inform + informed inform + informer inform + informs inform + infortunate infortun + infring infr + infringe infring + infringed infring + infus infu + infuse infus + infused infus + infusing infus + infusion infus + ingener ingen + ingenious ingeni + ingeniously ingeni + inglorious inglori + ingots ingot + ingraffed ingraf + ingraft ingraft + ingrate ingrat + ingrated ingrat + ingrateful ingrat + ingratitude ingratitud + ingratitudes ingratitud + ingredient ingredi + ingredients ingredi + ingross ingross + inhabit inhabit + inhabitable inhabit + inhabitants inhabit + inhabited inhabit + inhabits inhabit + inhearse inhears + inhearsed inhears + inherent inher + inherit inherit + inheritance inherit + inherited inherit + inheriting inherit + inheritor inheritor + inheritors inheritor + inheritrix inheritrix + inherits inherit + inhibited inhibit + inhibition inhibit + inhoop inhoop + inhuman inhuman + iniquities iniqu + iniquity iniqu + initiate initi + injointed injoint + injunction injunct + injunctions injunct + injur injur + injure injur + injurer injur + injuries injuri + injurious injuri + injury injuri + injustice injustic + ink ink + inkhorn inkhorn + inkle inkl + inkles inkl + inkling inkl + inky inki + inlaid inlaid + inland inland + inlay inlai + inly inli + inmost inmost + inn inn + inner inner + innkeeper innkeep + innocence innoc + innocency innoc + innocent innoc + innocents innoc + innovation innov + innovator innov + inns inn + innumerable innumer + inoculate inocul + inordinate inordin + inprimis inprimi + inquir inquir + inquire inquir + inquiry inquiri + inquisition inquisit + inquisitive inquisit + inroads inroad + insane insan + insanie insani + insatiate insati + insconce insconc + inscrib inscrib + inscription inscript + inscriptions inscript + inscroll inscrol + inscrutable inscrut + insculp insculp + insculpture insculptur + insensible insens + inseparable insepar + inseparate insepar + insert insert + inserted insert + inset inset + inshell inshel + inshipp inshipp + inside insid + insinewed insinew + insinuate insinu + insinuateth insinuateth + insinuating insinu + insinuation insinu + insisted insist + insisting insist + insisture insistur + insociable insoci + insolence insol + insolent insol + insomuch insomuch + inspir inspir + inspiration inspir + inspirations inspir + inspire inspir + inspired inspir + install instal + installed instal + instalment instal + instance instanc + instances instanc + instant instant + instantly instantli + instate instat + instead instead + insteeped insteep + instigate instig + instigated instig + instigation instig + instigations instig + instigator instig + instinct instinct + instinctively instinct + institute institut + institutions institut + instruct instruct + instructed instruct + instruction instruct + instructions instruct + instructs instruct + instrument instrument + instrumental instrument + instruments instrument + insubstantial insubstanti + insufficience insuffici + insufficiency insuffici + insult insult + insulted insult + insulting insult + insultment insult + insults insult + insupportable insupport + insuppressive insuppress + insurrection insurrect + insurrections insurrect + int int + integer integ + integritas integrita + integrity integr + intellect intellect + intellects intellect + intellectual intellectu + intelligence intellig + intelligencer intelligenc + intelligencing intelligenc + intelligent intellig + intelligis intelligi + intelligo intelligo + intemperance intemper + intemperate intemper + intend intend + intended intend + intendeth intendeth + intending intend + intendment intend + intends intend + intenible inten + intent intent + intention intent + intentively intent + intents intent + inter inter + intercept intercept + intercepted intercept + intercepter intercept + interception intercept + intercepts intercept + intercession intercess + intercessors intercessor + interchained interchain + interchang interchang + interchange interchang + interchangeably interchang + interchangement interchang + interchanging interchang + interdiction interdict + interest interest + interim interim + interims interim + interior interior + interjections interject + interjoin interjoin + interlude interlud + intermingle intermingl + intermission intermiss + intermissive intermiss + intermit intermit + intermix intermix + intermixed intermix + interpose interpos + interposer interpos + interposes interpos + interpret interpret + interpretation interpret + interpreted interpret + interpreter interpret + interpreters interpret + interprets interpret + interr interr + interred inter + interrogatories interrogatori + interrupt interrupt + interrupted interrupt + interrupter interrupt + interruptest interruptest + interruption interrupt + interrupts interrupt + intertissued intertissu + intervallums intervallum + interview interview + intestate intest + intestine intestin + intil intil + intimate intim + intimation intim + intitled intitl + intituled intitul + into into + intolerable intoler + intoxicates intox + intreasured intreasur + intreat intreat + intrench intrench + intrenchant intrench + intricate intric + intrinse intrins + intrinsicate intrins + intrude intrud + intruder intrud + intruding intrud + intrusion intrus + inundation inund + inure inur + inurn inurn + invade invad + invades invad + invasion invas + invasive invas + invectively invect + invectives invect + inveigled inveigl + invent invent + invented invent + invention invent + inventions invent + inventor inventor + inventorially inventori + inventoried inventori + inventors inventor + inventory inventori + inverness inver + invert invert + invest invest + invested invest + investing invest + investments invest + inveterate inveter + invincible invinc + inviolable inviol + invised invis + invisible invis + invitation invit + invite invit + invited invit + invites invit + inviting invit + invitis inviti + invocate invoc + invocation invoc + invoke invok + invoked invok + invulnerable invulner + inward inward + inwardly inwardli + inwardness inward + inwards inward + ionia ionia + ionian ionian + ipse ips + ipswich ipswich + ira ira + irae ira + iras ira + ire ir + ireful ir + ireland ireland + iris iri + irish irish + irishman irishman + irishmen irishmen + irks irk + irksome irksom + iron iron + irons iron + irreconcil irreconcil + irrecoverable irrecover + irregular irregular + irregulous irregul + irreligious irreligi + irremovable irremov + irreparable irrepar + irresolute irresolut + irrevocable irrevoc + is is + isabel isabel + isabella isabella + isbel isbel + isbels isbel + iscariot iscariot + ise is + ish ish + isidore isidor + isis isi + island island + islander island + islanders island + islands island + isle isl + isles isl + israel israel + issu issu + issue issu + issued issu + issueless issueless + issues issu + issuing issu + ist ist + ista ista + it it + italian italian + italy itali + itch itch + itches itch + itching itch + item item + items item + iteration iter + ithaca ithaca + its it + itself itself + itshall itshal + iv iv + ivory ivori + ivy ivi + iwis iwi + ix ix + j j + jacet jacet + jack jack + jackanapes jackanap + jacks jack + jacksauce jacksauc + jackslave jackslav + jacob jacob + jade jade + jaded jade + jades jade + jail jail + jakes jake + jamany jamani + james jame + jamy jami + jane jane + jangled jangl + jangling jangl + january januari + janus janu + japhet japhet + jaquenetta jaquenetta + jaques jaqu + jar jar + jarring jar + jars jar + jarteer jarteer + jasons jason + jaunce jaunc + jauncing jaunc + jaundice jaundic + jaundies jaundi + jaw jaw + jawbone jawbon + jaws jaw + jay jai + jays jai + jc jc + je je + jealous jealou + jealousies jealousi + jealousy jealousi + jeer jeer + jeering jeer + jelly jelli + jenny jenni + jeopardy jeopardi + jephtha jephtha + jephthah jephthah + jerkin jerkin + jerkins jerkin + jerks jerk + jeronimy jeronimi + jerusalem jerusalem + jeshu jeshu + jesses jess + jessica jessica + jest jest + jested jest + jester jester + jesters jester + jesting jest + jests jest + jesu jesu + jesus jesu + jet jet + jets jet + jew jew + jewel jewel + jeweller jewel + jewels jewel + jewess jewess + jewish jewish + jewry jewri + jews jew + jezebel jezebel + jig jig + jigging jig + jill jill + jills jill + jingling jingl + joan joan + job job + jockey jockei + jocund jocund + jog jog + jogging jog + john john + johns john + join join + joinder joinder + joined join + joiner joiner + joineth joineth + joins join + joint joint + jointed joint + jointing joint + jointly jointli + jointress jointress + joints joint + jointure jointur + jollity jolliti + jolly jolli + jolt jolt + joltheads jolthead + jordan jordan + joseph joseph + joshua joshua + jot jot + jour jour + jourdain jourdain + journal journal + journey journei + journeying journei + journeyman journeyman + journeymen journeymen + journeys journei + jove jove + jovem jovem + jovial jovial + jowl jowl + jowls jowl + joy joi + joyed joi + joyful joy + joyfully joyfulli + joyless joyless + joyous joyou + joys joi + juan juan + jud jud + judas juda + judases judas + jude jude + judg judg + judge judg + judged judg + judgement judgement + judges judg + judgest judgest + judging judg + judgment judgment + judgments judgment + judicious judici + jug jug + juggle juggl + juggled juggl + juggler juggler + jugglers juggler + juggling juggl + jugs jug + juice juic + juiced juic + jul jul + jule jule + julia julia + juliet juliet + julietta julietta + julio julio + julius juliu + july juli + jump jump + jumpeth jumpeth + jumping jump + jumps jump + june june + junes june + junior junior + junius juniu + junkets junket + juno juno + jupiter jupit + jure jure + jurement jurement + jurisdiction jurisdict + juror juror + jurors juror + jury juri + jurymen jurymen + just just + justeius justeiu + justest justest + justice justic + justicer justic + justicers justic + justices justic + justification justif + justified justifi + justify justifi + justle justl + justled justl + justles justl + justling justl + justly justli + justness just + justs just + jutting jut + jutty jutti + juvenal juven + kam kam + kate kate + kated kate + kates kate + katharine katharin + katherina katherina + katherine katherin + kecksies kecksi + keech keech + keel keel + keels keel + keen keen + keenness keen + keep keep + keepdown keepdown + keeper keeper + keepers keeper + keepest keepest + keeping keep + keeps keep + keiser keiser + ken ken + kendal kendal + kennel kennel + kent kent + kentish kentish + kentishman kentishman + kentishmen kentishmen + kept kept + kerchief kerchief + kerely kere + kern kern + kernal kernal + kernel kernel + kernels kernel + kerns kern + kersey kersei + kettle kettl + kettledrum kettledrum + kettledrums kettledrum + key kei + keys kei + kibe kibe + kibes kibe + kick kick + kicked kick + kickshaws kickshaw + kickshawses kickshaws + kicky kicki + kid kid + kidney kidnei + kikely kike + kildare kildar + kill kill + killed kill + killer killer + killeth killeth + killing kill + killingworth killingworth + kills kill + kiln kiln + kimbolton kimbolton + kin kin + kind kind + kinder kinder + kindest kindest + kindle kindl + kindled kindl + kindless kindless + kindlier kindlier + kindling kindl + kindly kindli + kindness kind + kindnesses kind + kindred kindr + kindreds kindr + kinds kind + kine kine + king king + kingdom kingdom + kingdoms kingdom + kingly kingli + kings king + kinred kinr + kins kin + kinsman kinsman + kinsmen kinsmen + kinswoman kinswoman + kirtle kirtl + kirtles kirtl + kiss kiss + kissed kiss + kisses kiss + kissing kiss + kitchen kitchen + kitchens kitchen + kite kite + kites kite + kitten kitten + kj kj + kl kl + klll klll + knack knack + knacks knack + knapp knapp + knav knav + knave knave + knaveries knaveri + knavery knaveri + knaves knave + knavish knavish + knead knead + kneaded knead + kneading knead + knee knee + kneel kneel + kneeling kneel + kneels kneel + knees knee + knell knell + knew knew + knewest knewest + knife knife + knight knight + knighted knight + knighthood knighthood + knighthoods knighthood + knightly knightli + knights knight + knit knit + knits knit + knitters knitter + knitteth knitteth + knives knive + knobs knob + knock knock + knocking knock + knocks knock + knog knog + knoll knoll + knot knot + knots knot + knotted knot + knotty knotti + know know + knower knower + knowest knowest + knowing know + knowingly knowingli + knowings know + knowledge knowledg + known known + knows know + l l + la la + laban laban + label label + labell label + labienus labienu + labio labio + labor labor + laboring labor + labors labor + labour labour + laboured labour + labourer labour + labourers labour + labouring labour + labours labour + laboursome laboursom + labras labra + labyrinth labyrinth + lac lac + lace lace + laced lace + lacedaemon lacedaemon + laces lace + lacies laci + lack lack + lackbeard lackbeard + lacked lack + lackey lackei + lackeying lackei + lackeys lackei + lacking lack + lacks lack + lad lad + ladder ladder + ladders ladder + lade lade + laden laden + ladies ladi + lading lade + lads lad + lady ladi + ladybird ladybird + ladyship ladyship + ladyships ladyship + laer laer + laertes laert + lafeu lafeu + lag lag + lagging lag + laid laid + lain lain + laissez laissez + lake lake + lakes lake + lakin lakin + lam lam + lamb lamb + lambert lambert + lambkin lambkin + lambkins lambkin + lambs lamb + lame lame + lamely lame + lameness lame + lament lament + lamentable lament + lamentably lament + lamentation lament + lamentations lament + lamented lament + lamenting lament + lamentings lament + laments lament + lames lame + laming lame + lammas lamma + lammastide lammastid + lamound lamound + lamp lamp + lampass lampass + lamps lamp + lanc lanc + lancaster lancast + lance lanc + lances lanc + lanceth lanceth + lanch lanch + land land + landed land + landing land + landless landless + landlord landlord + landmen landmen + lands land + lane lane + lanes lane + langage langag + langley langlei + langton langton + language languag + languageless languageless + languages languag + langues langu + languish languish + languished languish + languishes languish + languishing languish + languishings languish + languishment languish + languor languor + lank lank + lantern lantern + lanterns lantern + lanthorn lanthorn + lap lap + lapis lapi + lapland lapland + lapp lapp + laps lap + lapse laps + lapsed laps + lapsing laps + lapwing lapw + laquais laquai + larded lard + larder larder + larding lard + lards lard + large larg + largely larg + largeness larg + larger larger + largess largess + largest largest + lark lark + larks lark + larron larron + lartius lartiu + larum larum + larums larum + las la + lascivious lascivi + lash lash + lass lass + lasses lass + last last + lasted last + lasting last + lastly lastli + lasts last + latch latch + latches latch + late late + lated late + lately late + later later + latest latest + lath lath + latin latin + latten latten + latter latter + lattice lattic + laud laud + laudable laudabl + laudis laudi + laugh laugh + laughable laughabl + laughed laugh + laugher laugher + laughest laughest + laughing laugh + laughs laugh + laughter laughter + launce launc + launcelot launcelot + launces launc + launch launch + laund laund + laundress laundress + laundry laundri + laur laur + laura laura + laurel laurel + laurels laurel + laurence laurenc + laus lau + lavache lavach + lave lave + lavee lave + lavender lavend + lavina lavina + lavinia lavinia + lavish lavish + lavishly lavishli + lavolt lavolt + lavoltas lavolta + law law + lawful law + lawfully lawfulli + lawless lawless + lawlessly lawlessli + lawn lawn + lawns lawn + lawrence lawrenc + laws law + lawyer lawyer + lawyers lawyer + lay lai + layer layer + layest layest + laying lai + lays lai + lazar lazar + lazars lazar + lazarus lazaru + lazy lazi + lc lc + ld ld + ldst ldst + le le + lead lead + leaden leaden + leader leader + leaders leader + leadest leadest + leading lead + leads lead + leaf leaf + leagu leagu + league leagu + leagued leagu + leaguer leaguer + leagues leagu + leah leah + leak leak + leaky leaki + lean lean + leander leander + leaner leaner + leaning lean + leanness lean + leans lean + leap leap + leaped leap + leaping leap + leaps leap + leapt leapt + lear lear + learn learn + learned learn + learnedly learnedli + learning learn + learnings learn + learns learn + learnt learnt + leas lea + lease leas + leases leas + leash leash + leasing leas + least least + leather leather + leathern leathern + leav leav + leave leav + leaven leaven + leavening leaven + leaver leaver + leaves leav + leaving leav + leavy leavi + lecher lecher + lecherous lecher + lechers lecher + lechery lecheri + lecon lecon + lecture lectur + lectures lectur + led led + leda leda + leech leech + leeches leech + leek leek + leeks leek + leer leer + leers leer + lees lee + leese lees + leet leet + leets leet + left left + leg leg + legacies legaci + legacy legaci + legate legat + legatine legatin + lege lege + legerity leger + leges lege + legg legg + legion legion + legions legion + legitimate legitim + legitimation legitim + legs leg + leicester leicest + leicestershire leicestershir + leiger leiger + leigers leiger + leisure leisur + leisurely leisur + leisures leisur + leman leman + lemon lemon + lena lena + lend lend + lender lender + lending lend + lendings lend + lends lend + length length + lengthen lengthen + lengthens lengthen + lengths length + lenity leniti + lennox lennox + lent lent + lenten lenten + lentus lentu + leo leo + leon leon + leonardo leonardo + leonati leonati + leonato leonato + leonatus leonatu + leontes leont + leopard leopard + leopards leopard + leper leper + leperous leper + lepidus lepidu + leprosy leprosi + lequel lequel + lers ler + les le + less less + lessen lessen + lessens lessen + lesser lesser + lesson lesson + lessoned lesson + lessons lesson + lest lest + lestrake lestrak + let let + lethargied lethargi + lethargies lethargi + lethargy lethargi + lethe leth + lets let + lett lett + letter letter + letters letter + letting let + lettuce lettuc + leur leur + leve leve + level level + levell level + levelled level + levels level + leven leven + levers lever + leviathan leviathan + leviathans leviathan + levied levi + levies levi + levity leviti + levy levi + levying levi + lewd lewd + lewdly lewdli + lewdness lewd + lewdsters lewdster + lewis lewi + liable liabl + liar liar + liars liar + libbard libbard + libelling libel + libels libel + liberal liber + liberality liber + liberte libert + liberties liberti + libertine libertin + libertines libertin + liberty liberti + library librari + libya libya + licence licenc + licens licen + license licens + licentious licenti + lichas licha + licio licio + lick lick + licked lick + licker licker + lictors lictor + lid lid + lids lid + lie lie + lied li + lief lief + liefest liefest + liege lieg + liegeman liegeman + liegemen liegemen + lien lien + lies li + liest liest + lieth lieth + lieu lieu + lieutenant lieuten + lieutenantry lieutenantri + lieutenants lieuten + lieve liev + life life + lifeblood lifeblood + lifeless lifeless + lifelings lifel + lift lift + lifted lift + lifter lifter + lifteth lifteth + lifting lift + lifts lift + lig lig + ligarius ligariu + liggens liggen + light light + lighted light + lighten lighten + lightens lighten + lighter lighter + lightest lightest + lightly lightli + lightness light + lightning lightn + lightnings lightn + lights light + lik lik + like like + liked like + likeliest likeliest + likelihood likelihood + likelihoods likelihood + likely like + likeness like + liker liker + likes like + likest likest + likewise likewis + liking like + likings like + lilies lili + lily lili + lim lim + limander limand + limb limb + limbeck limbeck + limbecks limbeck + limber limber + limbo limbo + limbs limb + lime lime + limed lime + limehouse limehous + limekilns limekiln + limit limit + limitation limit + limited limit + limits limit + limn limn + limp limp + limping limp + limps limp + lin lin + lincoln lincoln + lincolnshire lincolnshir + line line + lineal lineal + lineally lineal + lineament lineament + lineaments lineament + lined line + linen linen + linens linen + lines line + ling ling + lingare lingar + linger linger + lingered linger + lingers linger + linguist linguist + lining line + link link + links link + linsey linsei + linstock linstock + linta linta + lion lion + lionel lionel + lioness lioness + lions lion + lip lip + lipp lipp + lips lip + lipsbury lipsburi + liquid liquid + liquor liquor + liquorish liquorish + liquors liquor + lirra lirra + lisbon lisbon + lisp lisp + lisping lisp + list list + listen listen + listening listen + lists list + literatured literatur + lither lither + litter litter + little littl + littlest littlest + liv liv + live live + lived live + livelier liveli + livelihood livelihood + livelong livelong + lively live + liver liver + liveries liveri + livers liver + livery liveri + lives live + livest livest + liveth liveth + livia livia + living live + livings live + lizard lizard + lizards lizard + ll ll + lll lll + llous llou + lnd lnd + lo lo + loa loa + loach loach + load load + loaden loaden + loading load + loads load + loaf loaf + loam loam + loan loan + loath loath + loathe loath + loathed loath + loather loather + loathes loath + loathing loath + loathly loathli + loathness loath + loathsome loathsom + loathsomeness loathsom + loathsomest loathsomest + loaves loav + lob lob + lobbies lobbi + lobby lobbi + local local + lochaber lochab + lock lock + locked lock + locking lock + lockram lockram + locks lock + locusts locust + lode lode + lodg lodg + lodge lodg + lodged lodg + lodgers lodger + lodges lodg + lodging lodg + lodgings lodg + lodovico lodovico + lodowick lodowick + lofty lofti + log log + logger logger + loggerhead loggerhead + loggerheads loggerhead + loggets logget + logic logic + logs log + loins loin + loiter loiter + loiterer loiter + loiterers loiter + loitering loiter + lolling loll + lolls loll + lombardy lombardi + london london + londoners london + lone lone + loneliness loneli + lonely lone + long long + longaville longavil + longboat longboat + longed long + longer longer + longest longest + longeth longeth + longing long + longings long + longly longli + longs long + longtail longtail + loo loo + loof loof + look look + looked look + looker looker + lookers looker + lookest lookest + looking look + looks look + loon loon + loop loop + loos loo + loose loos + loosed loos + loosely loos + loosen loosen + loosing loos + lop lop + lopp lopp + loquitur loquitur + lord lord + lorded lord + lording lord + lordings lord + lordliness lordli + lordly lordli + lords lord + lordship lordship + lordships lordship + lorenzo lorenzo + lorn lorn + lorraine lorrain + lorship lorship + los lo + lose lose + loser loser + losers loser + loses lose + losest losest + loseth loseth + losing lose + loss loss + losses loss + lost lost + lot lot + lots lot + lott lott + lottery lotteri + loud loud + louder louder + loudly loudli + lour lour + loureth loureth + louring lour + louse lous + louses lous + lousy lousi + lout lout + louted lout + louts lout + louvre louvr + lov lov + love love + loved love + lovedst lovedst + lovel lovel + lovelier loveli + loveliness loveli + lovell lovel + lovely love + lover lover + lovered lover + lovers lover + loves love + lovest lovest + loveth loveth + loving love + lovingly lovingli + low low + lowe low + lower lower + lowest lowest + lowing low + lowliness lowli + lowly lowli + lown lown + lowness low + loyal loyal + loyally loyal + loyalties loyalti + loyalty loyalti + lozel lozel + lt lt + lubber lubber + lubberly lubberli + luc luc + luccicos luccico + luce luce + lucentio lucentio + luces luce + lucetta lucetta + luciana luciana + lucianus lucianu + lucifer lucif + lucifier lucifi + lucilius luciliu + lucina lucina + lucio lucio + lucius luciu + luck luck + luckier luckier + luckiest luckiest + luckily luckili + luckless luckless + lucky lucki + lucre lucr + lucrece lucrec + lucretia lucretia + lucullius luculliu + lucullus lucullu + lucy luci + lud lud + ludlow ludlow + lug lug + lugg lugg + luggage luggag + luke luke + lukewarm lukewarm + lull lull + lulla lulla + lullaby lullabi + lulls lull + lumbert lumbert + lump lump + lumpish lumpish + luna luna + lunacies lunaci + lunacy lunaci + lunatic lunat + lunatics lunat + lunes lune + lungs lung + lupercal luperc + lurch lurch + lure lure + lurk lurk + lurketh lurketh + lurking lurk + lurks lurk + luscious lusciou + lush lush + lust lust + lusted lust + luster luster + lustful lust + lustier lustier + lustiest lustiest + lustig lustig + lustihood lustihood + lustily lustili + lustre lustr + lustrous lustrou + lusts lust + lusty lusti + lute lute + lutes lute + lutestring lutestr + lutheran lutheran + luxurious luxuri + luxuriously luxuri + luxury luxuri + ly ly + lycaonia lycaonia + lycurguses lycurgus + lydia lydia + lye lye + lyen lyen + lying ly + lym lym + lymoges lymog + lynn lynn + lysander lysand + m m + ma ma + maan maan + mab mab + macbeth macbeth + maccabaeus maccabaeu + macdonwald macdonwald + macduff macduff + mace mace + macedon macedon + maces mace + machiavel machiavel + machination machin + machinations machin + machine machin + mack mack + macmorris macmorri + maculate macul + maculation macul + mad mad + madam madam + madame madam + madams madam + madcap madcap + madded mad + madding mad + made made + madeira madeira + madly madli + madman madman + madmen madmen + madness mad + madonna madonna + madrigals madrig + mads mad + maecenas maecena + maggot maggot + maggots maggot + magic magic + magical magic + magician magician + magistrate magistr + magistrates magistr + magnanimity magnanim + magnanimous magnanim + magni magni + magnifi magnifi + magnificence magnific + magnificent magnific + magnifico magnifico + magnificoes magnifico + magnus magnu + mahomet mahomet + mahu mahu + maid maid + maiden maiden + maidenhead maidenhead + maidenheads maidenhead + maidenhood maidenhood + maidenhoods maidenhood + maidenliest maidenliest + maidenly maidenli + maidens maiden + maidhood maidhood + maids maid + mail mail + mailed mail + mails mail + maim maim + maimed maim + maims maim + main main + maincourse maincours + maine main + mainly mainli + mainmast mainmast + mains main + maintain maintain + maintained maintain + maintains maintain + maintenance mainten + mais mai + maison maison + majestas majesta + majestee majeste + majestic majest + majestical majest + majestically majest + majesties majesti + majesty majesti + major major + majority major + mak mak + make make + makeless makeless + maker maker + makers maker + makes make + makest makest + maketh maketh + making make + makings make + mal mal + mala mala + maladies maladi + malady maladi + malapert malapert + malcolm malcolm + malcontent malcont + malcontents malcont + male male + maledictions maledict + malefactions malefact + malefactor malefactor + malefactors malefactor + males male + malevolence malevol + malevolent malevol + malhecho malhecho + malice malic + malicious malici + maliciously malici + malign malign + malignancy malign + malignant malign + malignantly malignantli + malkin malkin + mall mall + mallard mallard + mallet mallet + mallows mallow + malmsey malmsei + malt malt + maltworms maltworm + malvolio malvolio + mamillius mamilliu + mammering mammer + mammet mammet + mammets mammet + mammock mammock + man man + manacle manacl + manacles manacl + manage manag + managed manag + manager manag + managing manag + manakin manakin + manchus manchu + mandate mandat + mandragora mandragora + mandrake mandrak + mandrakes mandrak + mane mane + manent manent + manes mane + manet manet + manfully manfulli + mangle mangl + mangled mangl + mangles mangl + mangling mangl + mangy mangi + manhood manhood + manhoods manhood + manifest manifest + manifested manifest + manifests manifest + manifold manifold + manifoldly manifoldli + manka manka + mankind mankind + manlike manlik + manly manli + mann mann + manna manna + manner manner + mannerly mannerli + manners manner + manningtree manningtre + mannish mannish + manor manor + manors manor + mans man + mansion mansion + mansionry mansionri + mansions mansion + manslaughter manslaught + mantle mantl + mantled mantl + mantles mantl + mantua mantua + mantuan mantuan + manual manual + manure manur + manured manur + manus manu + many mani + map map + mapp mapp + maps map + mar mar + marble marbl + marbled marbl + marcade marcad + marcellus marcellu + march march + marches march + marcheth marcheth + marching march + marchioness marchio + marchpane marchpan + marcians marcian + marcius marciu + marcus marcu + mardian mardian + mare mare + mares mare + marg marg + margarelon margarelon + margaret margaret + marge marg + margent margent + margery margeri + maria maria + marian marian + mariana mariana + maries mari + marigold marigold + mariner marin + mariners marin + maritime maritim + marjoram marjoram + mark mark + marked mark + market market + marketable market + marketplace marketplac + markets market + marking mark + markman markman + marks mark + marl marl + marle marl + marmoset marmoset + marquess marquess + marquis marqui + marr marr + marriage marriag + marriages marriag + married marri + marries marri + marring mar + marrow marrow + marrowless marrowless + marrows marrow + marry marri + marrying marri + mars mar + marseilles marseil + marsh marsh + marshal marshal + marshalsea marshalsea + marshalship marshalship + mart mart + marted mart + martem martem + martext martext + martial martial + martin martin + martino martino + martius martiu + martlemas martlema + martlet martlet + marts mart + martyr martyr + martyrs martyr + marullus marullu + marv marv + marvel marvel + marvell marvel + marvellous marvel + marvellously marvel + marvels marvel + mary mari + mas ma + masculine masculin + masham masham + mask mask + masked mask + masker masker + maskers masker + masking mask + masks mask + mason mason + masonry masonri + masons mason + masque masqu + masquers masquer + masques masqu + masquing masqu + mass mass + massacre massacr + massacres massacr + masses mass + massy massi + mast mast + mastcr mastcr + master master + masterdom masterdom + masterest masterest + masterless masterless + masterly masterli + masterpiece masterpiec + masters master + mastership mastership + mastic mastic + mastiff mastiff + mastiffs mastiff + masts mast + match match + matches match + matcheth matcheth + matching match + matchless matchless + mate mate + mated mate + mater mater + material materi + mates mate + mathematics mathemat + matin matin + matron matron + matrons matron + matter matter + matters matter + matthew matthew + mattock mattock + mattress mattress + mature matur + maturity matur + maud maud + maudlin maudlin + maugre maugr + maul maul + maund maund + mauri mauri + mauritania mauritania + mauvais mauvai + maw maw + maws maw + maxim maxim + may mai + mayday maydai + mayest mayest + mayor mayor + maypole maypol + mayst mayst + maz maz + maze maze + mazed maze + mazes maze + mazzard mazzard + me me + meacock meacock + mead mead + meadow meadow + meadows meadow + meads mead + meagre meagr + meal meal + meals meal + mealy meali + mean mean + meanders meander + meaner meaner + meanest meanest + meaneth meaneth + meaning mean + meanings mean + meanly meanli + means mean + meant meant + meantime meantim + meanwhile meanwhil + measles measl + measur measur + measurable measur + measure measur + measured measur + measureless measureless + measures measur + measuring measur + meat meat + meats meat + mechanic mechan + mechanical mechan + mechanicals mechan + mechanics mechan + mechante mechant + med med + medal medal + meddle meddl + meddler meddler + meddling meddl + mede mede + medea medea + media media + mediation mediat + mediators mediat + medice medic + medicinal medicin + medicine medicin + medicines medicin + meditate medit + meditates medit + meditating medit + meditation medit + meditations medit + mediterranean mediterranean + mediterraneum mediterraneum + medlar medlar + medlars medlar + meed meed + meeds meed + meek meek + meekly meekli + meekness meek + meet meet + meeter meeter + meetest meetest + meeting meet + meetings meet + meetly meetli + meetness meet + meets meet + meg meg + mehercle mehercl + meilleur meilleur + meiny meini + meisen meisen + melancholies melancholi + melancholy melancholi + melford melford + mell mell + mellifluous melliflu + mellow mellow + mellowing mellow + melodious melodi + melody melodi + melt melt + melted melt + melteth melteth + melting melt + melts melt + melun melun + member member + members member + memento memento + memorable memor + memorandums memorandum + memorial memori + memorials memori + memories memori + memoriz memoriz + memorize memor + memory memori + memphis memphi + men men + menac menac + menace menac + menaces menac + menaphon menaphon + menas mena + mend mend + mended mend + mender mender + mending mend + mends mend + menecrates menecr + menelaus menelau + menenius meneniu + mental mental + menteith menteith + mention mention + mentis menti + menton menton + mephostophilus mephostophilu + mer mer + mercatante mercatant + mercatio mercatio + mercenaries mercenari + mercenary mercenari + mercer mercer + merchandise merchandis + merchandized merchand + merchant merchant + merchants merchant + mercies merci + merciful merci + mercifully mercifulli + merciless merciless + mercurial mercuri + mercuries mercuri + mercury mercuri + mercutio mercutio + mercy merci + mere mere + mered mere + merely mere + merest merest + meridian meridian + merit merit + merited merit + meritorious meritori + merits merit + merlin merlin + mermaid mermaid + mermaids mermaid + merops merop + merrier merrier + merriest merriest + merrily merrili + merriman merriman + merriment merriment + merriments merriment + merriness merri + merry merri + mervailous mervail + mes me + mesh mesh + meshes mesh + mesopotamia mesopotamia + mess mess + message messag + messages messag + messala messala + messaline messalin + messenger messeng + messengers messeng + messes mess + messina messina + met met + metal metal + metals metal + metamorphis metamorphi + metamorphoses metamorphos + metaphor metaphor + metaphysical metaphys + metaphysics metaphys + mete mete + metellus metellu + meteor meteor + meteors meteor + meteyard meteyard + metheglin metheglin + metheglins metheglin + methink methink + methinks methink + method method + methods method + methought methought + methoughts methought + metre metr + metres metr + metropolis metropoli + mette mett + mettle mettl + mettled mettl + meus meu + mew mew + mewed mew + mewling mewl + mexico mexico + mi mi + mice mice + michael michael + michaelmas michaelma + micher micher + miching mich + mickle mickl + microcosm microcosm + mid mid + midas mida + middest middest + middle middl + middleham middleham + midnight midnight + midriff midriff + midst midst + midsummer midsumm + midway midwai + midwife midwif + midwives midwiv + mienne mienn + might might + mightful might + mightier mightier + mightiest mightiest + mightily mightili + mightiness mighti + mightst mightst + mighty mighti + milan milan + milch milch + mild mild + milder milder + mildest mildest + mildew mildew + mildews mildew + mildly mildli + mildness mild + mile mile + miles mile + milford milford + militarist militarist + military militari + milk milk + milking milk + milkmaid milkmaid + milks milk + milksops milksop + milky milki + mill mill + mille mill + miller miller + milliner millin + million million + millioned million + millions million + mills mill + millstones millston + milo milo + mimic mimic + minc minc + mince minc + minces minc + mincing minc + mind mind + minded mind + minding mind + mindless mindless + minds mind + mine mine + mineral miner + minerals miner + minerva minerva + mines mine + mingle mingl + mingled mingl + mingling mingl + minikin minikin + minim minim + minime minim + minimo minimo + minimus minimu + mining mine + minion minion + minions minion + minist minist + minister minist + ministers minist + ministration ministr + minnow minnow + minnows minnow + minola minola + minority minor + minos mino + minotaurs minotaur + minstrel minstrel + minstrels minstrel + minstrelsy minstrelsi + mint mint + mints mint + minute minut + minutely minut + minutes minut + minx minx + mio mio + mir mir + mirable mirabl + miracle miracl + miracles miracl + miraculous miracul + miranda miranda + mire mire + mirror mirror + mirrors mirror + mirth mirth + mirthful mirth + miry miri + mis mi + misadventur misadventur + misadventure misadventur + misanthropos misanthropo + misapplied misappli + misbecame misbecam + misbecom misbecom + misbecome misbecom + misbegot misbegot + misbegotten misbegotten + misbeliever misbeliev + misbelieving misbeliev + misbhav misbhav + miscall miscal + miscalled miscal + miscarried miscarri + miscarries miscarri + miscarry miscarri + miscarrying miscarri + mischance mischanc + mischances mischanc + mischief mischief + mischiefs mischief + mischievous mischiev + misconceived misconceiv + misconst misconst + misconster misconst + misconstruction misconstruct + misconstrued misconstru + misconstrues misconstru + miscreant miscreant + miscreate miscreat + misdeed misde + misdeeds misde + misdemean misdemean + misdemeanours misdemeanour + misdoubt misdoubt + misdoubteth misdoubteth + misdoubts misdoubt + misenum misenum + miser miser + miserable miser + miserably miser + misericorde misericord + miseries miseri + misers miser + misery miseri + misfortune misfortun + misfortunes misfortun + misgive misgiv + misgives misgiv + misgiving misgiv + misgoverned misgovern + misgovernment misgovern + misgraffed misgraf + misguide misguid + mishap mishap + mishaps mishap + misheard misheard + misinterpret misinterpret + mislead mislead + misleader mislead + misleaders mislead + misleading mislead + misled misl + mislike mislik + misord misord + misplac misplac + misplaced misplac + misplaces misplac + mispris mispri + misprised mispris + misprision mispris + misprizing mispriz + misproud misproud + misquote misquot + misreport misreport + miss miss + missed miss + misses miss + misshap misshap + misshapen misshapen + missheathed missheath + missing miss + missingly missingli + missions mission + missive missiv + missives missiv + misspoke misspok + mist mist + mista mista + mistak mistak + mistake mistak + mistaken mistaken + mistakes mistak + mistaketh mistaketh + mistaking mistak + mistakings mistak + mistemp mistemp + mistempered mistemp + misterm misterm + mistful mist + misthink misthink + misthought misthought + mistletoe mistleto + mistook mistook + mistreadings mistread + mistress mistress + mistresses mistress + mistresss mistresss + mistriship mistriship + mistrust mistrust + mistrusted mistrust + mistrustful mistrust + mistrusting mistrust + mists mist + misty misti + misus misu + misuse misus + misused misus + misuses misus + mites mite + mithridates mithrid + mitigate mitig + mitigation mitig + mix mix + mixed mix + mixture mixtur + mixtures mixtur + mm mm + mnd mnd + moan moan + moans moan + moat moat + moated moat + mobled mobl + mock mock + mockable mockabl + mocker mocker + mockeries mockeri + mockers mocker + mockery mockeri + mocking mock + mocks mock + mockvater mockvat + mockwater mockwat + model model + modena modena + moderate moder + moderately moder + moderation moder + modern modern + modest modest + modesties modesti + modestly modestli + modesty modesti + modicums modicum + modo modo + module modul + moe moe + moi moi + moiety moieti + moist moist + moisten moisten + moisture moistur + moldwarp moldwarp + mole mole + molehill molehil + moles mole + molest molest + molestation molest + mollification mollif + mollis molli + molten molten + molto molto + mome mome + moment moment + momentary momentari + moming mome + mon mon + monachum monachum + monarch monarch + monarchies monarchi + monarchize monarch + monarcho monarcho + monarchs monarch + monarchy monarchi + monast monast + monastery monasteri + monastic monast + monday mondai + monde mond + money monei + moneys monei + mong mong + monger monger + mongers monger + monging mong + mongrel mongrel + mongrels mongrel + mongst mongst + monk monk + monkey monkei + monkeys monkei + monks monk + monmouth monmouth + monopoly monopoli + mons mon + monsieur monsieur + monsieurs monsieur + monster monster + monsters monster + monstrous monstrou + monstrously monstrous + monstrousness monstrous + monstruosity monstruos + montacute montacut + montage montag + montague montagu + montagues montagu + montano montano + montant montant + montez montez + montferrat montferrat + montgomery montgomeri + month month + monthly monthli + months month + montjoy montjoi + monument monument + monumental monument + monuments monument + mood mood + moods mood + moody moodi + moon moon + moonbeams moonbeam + moonish moonish + moonlight moonlight + moons moon + moonshine moonshin + moonshines moonshin + moor moor + moorfields moorfield + moors moor + moorship moorship + mop mop + mope mope + moping mope + mopping mop + mopsa mopsa + moral moral + moraler moral + morality moral + moralize moral + mordake mordak + more more + moreover moreov + mores more + morgan morgan + mori mori + morisco morisco + morn morn + morning morn + mornings morn + morocco morocco + morris morri + morrow morrow + morrows morrow + morsel morsel + morsels morsel + mort mort + mortal mortal + mortality mortal + mortally mortal + mortals mortal + mortar mortar + mortgaged mortgag + mortified mortifi + mortifying mortifi + mortimer mortim + mortimers mortim + mortis morti + mortise mortis + morton morton + mose mose + moss moss + mossgrown mossgrown + most most + mote mote + moth moth + mother mother + mothers mother + moths moth + motion motion + motionless motionless + motions motion + motive motiv + motives motiv + motley motlei + mots mot + mought mought + mould mould + moulded mould + mouldeth mouldeth + moulds mould + mouldy mouldi + moult moult + moulten moulten + mounch mounch + mounseur mounseur + mounsieur mounsieur + mount mount + mountain mountain + mountaineer mountain + mountaineers mountain + mountainous mountain + mountains mountain + mountant mountant + mountanto mountanto + mountebank mountebank + mountebanks mountebank + mounted mount + mounteth mounteth + mounting mount + mounts mount + mourn mourn + mourned mourn + mourner mourner + mourners mourner + mournful mourn + mournfully mournfulli + mourning mourn + mourningly mourningli + mournings mourn + mourns mourn + mous mou + mouse mous + mousetrap mousetrap + mousing mous + mouth mouth + mouthed mouth + mouths mouth + mov mov + movables movabl + move move + moveable moveabl + moveables moveabl + moved move + mover mover + movers mover + moves move + moveth moveth + moving move + movingly movingli + movousus movousu + mow mow + mowbray mowbrai + mower mower + mowing mow + mows mow + moy moi + moys moi + moyses moys + mrs mr + much much + muck muck + mud mud + mudded mud + muddied muddi + muddy muddi + muffins muffin + muffl muffl + muffle muffl + muffled muffl + muffler muffler + muffling muffl + mugger mugger + mugs mug + mulberries mulberri + mulberry mulberri + mule mule + mules mule + muleteers mulet + mulier mulier + mulieres mulier + muliteus muliteu + mull mull + mulmutius mulmutiu + multiplied multipli + multiply multipli + multiplying multipli + multipotent multipot + multitude multitud + multitudes multitud + multitudinous multitudin + mum mum + mumble mumbl + mumbling mumbl + mummers mummer + mummy mummi + mun mun + munch munch + muniments muniment + munition munit + murd murd + murder murder + murdered murder + murderer murder + murderers murder + murdering murder + murderous murder + murders murder + mure mure + murk murk + murkiest murkiest + murky murki + murmur murmur + murmurers murmur + murmuring murmur + murrain murrain + murray murrai + murrion murrion + murther murther + murtherer murther + murtherers murther + murthering murther + murtherous murther + murthers murther + mus mu + muscadel muscadel + muscovites muscovit + muscovits muscovit + muscovy muscovi + muse muse + muses muse + mush mush + mushrooms mushroom + music music + musical music + musician musician + musicians musician + musics music + musing muse + musings muse + musk musk + musket musket + muskets musket + muskos musko + muss muss + mussel mussel + mussels mussel + must must + mustachio mustachio + mustard mustard + mustardseed mustardse + muster muster + mustering muster + musters muster + musty musti + mutability mutabl + mutable mutabl + mutation mutat + mutations mutat + mute mute + mutes mute + mutest mutest + mutine mutin + mutineer mutin + mutineers mutin + mutines mutin + mutinies mutini + mutinous mutin + mutiny mutini + mutius mutiu + mutter mutter + muttered mutter + mutton mutton + muttons mutton + mutual mutual + mutualities mutual + mutually mutual + muzzl muzzl + muzzle muzzl + muzzled muzzl + mv mv + mww mww + my my + mynheers mynheer + myrmidon myrmidon + myrmidons myrmidon + myrtle myrtl + myself myself + myst myst + mysteries mysteri + mystery mysteri + n n + nag nag + nage nage + nags nag + naiads naiad + nail nail + nails nail + nak nak + naked nake + nakedness naked + nal nal + nam nam + name name + named name + nameless nameless + namely name + names name + namest namest + naming name + nan nan + nance nanc + nap nap + nape nape + napes nape + napkin napkin + napkins napkin + naples napl + napless napless + napping nap + naps nap + narbon narbon + narcissus narcissu + narines narin + narrow narrow + narrowly narrowli + naso naso + nasty nasti + nathaniel nathaniel + natifs natif + nation nation + nations nation + native nativ + nativity nativ + natur natur + natural natur + naturalize natur + naturally natur + nature natur + natured natur + natures natur + natus natu + naught naught + naughtily naughtili + naughty naughti + navarre navarr + nave nave + navel navel + navigation navig + navy navi + nay nai + nayward nayward + nayword nayword + nazarite nazarit + ne ne + neaf neaf + neamnoins neamnoin + neanmoins neanmoin + neapolitan neapolitan + neapolitans neapolitan + near near + nearer nearer + nearest nearest + nearly nearli + nearness near + neat neat + neatly neatli + neb neb + nebour nebour + nebuchadnezzar nebuchadnezzar + nec nec + necessaries necessari + necessarily necessarili + necessary necessari + necessitied necess + necessities necess + necessity necess + neck neck + necklace necklac + necks neck + nectar nectar + ned ned + nedar nedar + need need + needed need + needer needer + needful need + needfull needful + needing need + needle needl + needles needl + needless needless + needly needli + needs need + needy needi + neer neer + neeze neez + nefas nefa + negation negat + negative neg + negatives neg + neglect neglect + neglected neglect + neglecting neglect + neglectingly neglectingli + neglection neglect + negligence neglig + negligent neglig + negotiate negoti + negotiations negoti + negro negro + neigh neigh + neighbors neighbor + neighbour neighbour + neighbourhood neighbourhood + neighbouring neighbour + neighbourly neighbourli + neighbours neighbour + neighing neigh + neighs neigh + neither neither + nell nell + nemean nemean + nemesis nemesi + neoptolemus neoptolemu + nephew nephew + nephews nephew + neptune neptun + ner ner + nereides nereid + nerissa nerissa + nero nero + neroes nero + ners ner + nerve nerv + nerves nerv + nervii nervii + nervy nervi + nessus nessu + nest nest + nestor nestor + nests nest + net net + nether nether + netherlands netherland + nets net + nettle nettl + nettled nettl + nettles nettl + neuter neuter + neutral neutral + nev nev + never never + nevil nevil + nevils nevil + new new + newborn newborn + newer newer + newest newest + newgate newgat + newly newli + newness new + news new + newsmongers newsmong + newt newt + newts newt + next next + nibbling nibbl + nicanor nicanor + nice nice + nicely nice + niceness nice + nicer nicer + nicety niceti + nicholas nichola + nick nick + nickname nicknam + nicks nick + niece niec + nieces niec + niggard niggard + niggarding niggard + niggardly niggardli + nigh nigh + night night + nightcap nightcap + nightcaps nightcap + nighted night + nightgown nightgown + nightingale nightingal + nightingales nightingal + nightly nightli + nightmare nightmar + nights night + nightwork nightwork + nihil nihil + nile nile + nill nill + nilus nilu + nimble nimbl + nimbleness nimbl + nimbler nimbler + nimbly nimbl + nine nine + nineteen nineteen + ning ning + ningly ningli + ninny ninni + ninth ninth + ninus ninu + niobe niob + niobes niob + nip nip + nipp nipp + nipping nip + nipple nippl + nips nip + nit nit + nly nly + nnight nnight + nnights nnight + no no + noah noah + nob nob + nobility nobil + nobis nobi + noble nobl + nobleman nobleman + noblemen noblemen + nobleness nobl + nobler nobler + nobles nobl + noblesse nobless + noblest noblest + nobly nobli + nobody nobodi + noces noce + nod nod + nodded nod + nodding nod + noddle noddl + noddles noddl + noddy noddi + nods nod + noes noe + nointed noint + nois noi + noise nois + noiseless noiseless + noisemaker noisemak + noises nois + noisome noisom + nole nole + nominate nomin + nominated nomin + nomination nomin + nominativo nominativo + non non + nonage nonag + nonce nonc + none none + nonino nonino + nonny nonni + nonpareil nonpareil + nonsuits nonsuit + nony noni + nook nook + nooks nook + noon noon + noonday noondai + noontide noontid + nor nor + norbery norberi + norfolk norfolk + norman norman + normandy normandi + normans norman + north north + northampton northampton + northamptonshire northamptonshir + northerly northerli + northern northern + northgate northgat + northumberland northumberland + northumberlands northumberland + northward northward + norway norwai + norways norwai + norwegian norwegian + norweyan norweyan + nos no + nose nose + nosegays nosegai + noseless noseless + noses nose + noster noster + nostra nostra + nostril nostril + nostrils nostril + not not + notable notabl + notably notabl + notary notari + notch notch + note note + notebook notebook + noted note + notedly notedli + notes note + notest notest + noteworthy noteworthi + nothing noth + nothings noth + notice notic + notify notifi + noting note + notion notion + notorious notori + notoriously notori + notre notr + notwithstanding notwithstand + nought nought + noun noun + nouns noun + nourish nourish + nourished nourish + nourisher nourish + nourishes nourish + nourisheth nourisheth + nourishing nourish + nourishment nourish + nous nou + novel novel + novelties novelti + novelty novelti + noverbs noverb + novi novi + novice novic + novices novic + novum novum + now now + nowhere nowher + noyance noyanc + ns ns + nt nt + nubibus nubibu + numa numa + numb numb + number number + numbered number + numbering number + numberless numberless + numbers number + numbness numb + nun nun + nuncio nuncio + nuncle nuncl + nunnery nunneri + nuns nun + nuntius nuntiu + nuptial nuptial + nurs nur + nurse nurs + nursed nurs + nurser nurser + nursery nurseri + nurses nurs + nurseth nurseth + nursh nursh + nursing nurs + nurtur nurtur + nurture nurtur + nut nut + nuthook nuthook + nutmeg nutmeg + nutmegs nutmeg + nutriment nutriment + nuts nut + nutshell nutshel + ny ny + nym nym + nymph nymph + nymphs nymph + o o + oak oak + oaken oaken + oaks oak + oared oar + oars oar + oatcake oatcak + oaten oaten + oath oath + oathable oathabl + oaths oath + oats oat + ob ob + obduracy obduraci + obdurate obdur + obedience obedi + obedient obedi + obeisance obeis + oberon oberon + obey obei + obeyed obei + obeying obei + obeys obei + obidicut obidicut + object object + objected object + objections object + objects object + oblation oblat + oblations oblat + obligation oblig + obligations oblig + obliged oblig + oblique obliqu + oblivion oblivion + oblivious oblivi + obloquy obloqui + obscene obscen + obscenely obscen + obscur obscur + obscure obscur + obscured obscur + obscurely obscur + obscures obscur + obscuring obscur + obscurity obscur + obsequies obsequi + obsequious obsequi + obsequiously obsequi + observ observ + observance observ + observances observ + observancy observ + observant observ + observants observ + observation observ + observe observ + observed observ + observer observ + observers observ + observing observ + observingly observingli + obsque obsqu + obstacle obstacl + obstacles obstacl + obstinacy obstinaci + obstinate obstin + obstinately obstin + obstruct obstruct + obstruction obstruct + obstructions obstruct + obtain obtain + obtained obtain + obtaining obtain + occasion occas + occasions occas + occident occid + occidental occident + occulted occult + occupat occupat + occupation occup + occupations occup + occupied occupi + occupies occupi + occupy occupi + occurrence occurr + occurrences occurr + occurrents occurr + ocean ocean + oceans ocean + octavia octavia + octavius octaviu + ocular ocular + od od + odd odd + oddest oddest + oddly oddli + odds odd + ode od + odes od + odious odiou + odoriferous odorifer + odorous odor + odour odour + odours odour + ods od + oeillades oeillad + oes oe + oeuvres oeuvr + of of + ofephesus ofephesu + off off + offal offal + offence offenc + offenceful offenc + offences offenc + offend offend + offended offend + offendendo offendendo + offender offend + offenders offend + offendeth offendeth + offending offend + offendress offendress + offends offend + offense offens + offenseless offenseless + offenses offens + offensive offens + offer offer + offered offer + offering offer + offerings offer + offers offer + offert offert + offic offic + office offic + officed offic + officer offic + officers offic + offices offic + official offici + officious offici + offspring offspr + oft oft + often often + oftener often + oftentimes oftentim + oh oh + oil oil + oils oil + oily oili + old old + oldcastle oldcastl + olden olden + older older + oldest oldest + oldness old + olive oliv + oliver oliv + olivers oliv + olives oliv + olivia olivia + olympian olympian + olympus olympu + oman oman + omans oman + omen omen + ominous omin + omission omiss + omit omit + omittance omitt + omitted omit + omitting omit + omne omn + omnes omn + omnipotent omnipot + on on + once onc + one on + ones on + oneyers oney + ongles ongl + onion onion + onions onion + only onli + onset onset + onward onward + onwards onward + oo oo + ooze ooz + oozes ooz + oozy oozi + op op + opal opal + ope op + open open + opener open + opening open + openly openli + openness open + opens open + operant oper + operate oper + operation oper + operations oper + operative oper + opes op + oph oph + ophelia ophelia + opinion opinion + opinions opinion + opportune opportun + opportunities opportun + opportunity opportun + oppos oppo + oppose oppos + opposed oppos + opposeless opposeless + opposer oppos + opposers oppos + opposes oppos + opposing oppos + opposite opposit + opposites opposit + opposition opposit + oppositions opposit + oppress oppress + oppressed oppress + oppresses oppress + oppresseth oppresseth + oppressing oppress + oppression oppress + oppressor oppressor + opprest opprest + opprobriously opprobri + oppugnancy oppugn + opulency opul + opulent opul + or or + oracle oracl + oracles oracl + orange orang + oration orat + orator orat + orators orat + oratory oratori + orb orb + orbed orb + orbs orb + orchard orchard + orchards orchard + ord ord + ordain ordain + ordained ordain + ordaining ordain + order order + ordered order + ordering order + orderless orderless + orderly orderli + orders order + ordinance ordin + ordinant ordin + ordinaries ordinari + ordinary ordinari + ordnance ordnanc + ords ord + ordure ordur + ore or + organ organ + organs organ + orgillous orgil + orient orient + orifex orifex + origin origin + original origin + orisons orison + ork ork + orlando orlando + orld orld + orleans orlean + ornament ornament + ornaments ornament + orodes orod + orphan orphan + orphans orphan + orpheus orpheu + orsino orsino + ort ort + orthography orthographi + orts ort + oscorbidulchos oscorbidulcho + osier osier + osiers osier + osprey osprei + osr osr + osric osric + ossa ossa + ost ost + ostent ostent + ostentare ostentar + ostentation ostent + ostents ostent + ostler ostler + ostlers ostler + ostrich ostrich + osw osw + oswald oswald + othello othello + other other + othergates otherg + others other + otherwhere otherwher + otherwhiles otherwhil + otherwise otherwis + otter otter + ottoman ottoman + ottomites ottomit + oublie oubli + ouches ouch + ought ought + oui oui + ounce ounc + ounces ounc + ouphes ouph + our our + ours our + ourself ourself + ourselves ourselv + ousel ousel + out out + outbids outbid + outbrave outbrav + outbraves outbrav + outbreak outbreak + outcast outcast + outcries outcri + outcry outcri + outdar outdar + outdare outdar + outdares outdar + outdone outdon + outfac outfac + outface outfac + outfaced outfac + outfacing outfac + outfly outfli + outfrown outfrown + outgo outgo + outgoes outgo + outgrown outgrown + outjest outjest + outlaw outlaw + outlawry outlawri + outlaws outlaw + outliv outliv + outlive outliv + outlives outliv + outliving outliv + outlook outlook + outlustres outlustr + outpriz outpriz + outrage outrag + outrageous outrag + outrages outrag + outran outran + outright outright + outroar outroar + outrun outrun + outrunning outrun + outruns outrun + outscold outscold + outscorn outscorn + outsell outsel + outsells outsel + outside outsid + outsides outsid + outspeaks outspeak + outsport outsport + outstare outstar + outstay outstai + outstood outstood + outstretch outstretch + outstretched outstretch + outstrike outstrik + outstrip outstrip + outstripped outstrip + outswear outswear + outvenoms outvenom + outward outward + outwardly outwardli + outwards outward + outwear outwear + outweighs outweigh + outwent outwent + outworn outworn + outworths outworth + oven oven + over over + overawe overaw + overbear overbear + overblown overblown + overboard overboard + overbold overbold + overborne overborn + overbulk overbulk + overbuys overbui + overcame overcam + overcast overcast + overcharg overcharg + overcharged overcharg + overcome overcom + overcomes overcom + overdone overdon + overearnest overearnest + overfar overfar + overflow overflow + overflown overflown + overglance overgl + overgo overgo + overgone overgon + overgorg overgorg + overgrown overgrown + overhead overhead + overhear overhear + overheard overheard + overhold overhold + overjoyed overjoi + overkind overkind + overland overland + overleather overleath + overlive overl + overlook overlook + overlooking overlook + overlooks overlook + overmaster overmast + overmounting overmount + overmuch overmuch + overpass overpass + overpeer overp + overpeering overp + overplus overplu + overrul overrul + overrun overrun + overscutch overscutch + overset overset + overshades overshad + overshine overshin + overshines overshin + overshot overshot + oversights oversight + overspread overspread + overstain overstain + overswear overswear + overt overt + overta overta + overtake overtak + overtaketh overtaketh + overthrow overthrow + overthrown overthrown + overthrows overthrow + overtook overtook + overtopp overtopp + overture overtur + overturn overturn + overwatch overwatch + overween overween + overweening overween + overweigh overweigh + overwhelm overwhelm + overwhelming overwhelm + overworn overworn + ovid ovid + ovidius ovidiu + ow ow + owe ow + owed ow + owedst owedst + owen owen + owes ow + owest owest + oweth oweth + owing ow + owl owl + owls owl + own own + owner owner + owners owner + owning own + owns own + owy owi + ox ox + oxen oxen + oxford oxford + oxfordshire oxfordshir + oxlips oxlip + oyes oy + oyster oyster + p p + pabble pabbl + pabylon pabylon + pac pac + pace pace + paced pace + paces pace + pacified pacifi + pacify pacifi + pacing pace + pack pack + packet packet + packets packet + packhorses packhors + packing pack + packings pack + packs pack + packthread packthread + pacorus pacoru + paction paction + pad pad + paddle paddl + paddling paddl + paddock paddock + padua padua + pagan pagan + pagans pagan + page page + pageant pageant + pageants pageant + pages page + pah pah + paid paid + pail pail + pailfuls pail + pails pail + pain pain + pained pain + painful pain + painfully painfulli + pains pain + paint paint + painted paint + painter painter + painting paint + paintings paint + paints paint + pair pair + paired pair + pairs pair + pajock pajock + pal pal + palabras palabra + palace palac + palaces palac + palamedes palamed + palate palat + palates palat + palatine palatin + palating palat + pale pale + paled pale + paleness pale + paler paler + pales pale + palestine palestin + palfrey palfrei + palfreys palfrei + palisadoes palisado + pall pall + pallabris pallabri + pallas palla + pallets pallet + palm palm + palmer palmer + palmers palmer + palms palm + palmy palmi + palpable palpabl + palsied palsi + palsies palsi + palsy palsi + palt palt + palter palter + paltry paltri + paly pali + pamp pamp + pamper pamper + pamphlets pamphlet + pan pan + pancackes pancack + pancake pancak + pancakes pancak + pandar pandar + pandars pandar + pandarus pandaru + pander pander + panderly panderli + panders pander + pandulph pandulph + panel panel + pang pang + panging pang + pangs pang + pannier pannier + pannonians pannonian + pansa pansa + pansies pansi + pant pant + pantaloon pantaloon + panted pant + pantheon pantheon + panther panther + panthino panthino + panting pant + pantingly pantingli + pantler pantler + pantry pantri + pants pant + pap pap + papal papal + paper paper + papers paper + paphlagonia paphlagonia + paphos papho + papist papist + paps pap + par par + parable parabl + paracelsus paracelsu + paradise paradis + paradox paradox + paradoxes paradox + paragon paragon + paragons paragon + parallel parallel + parallels parallel + paramour paramour + paramours paramour + parapets parapet + paraquito paraquito + parasite parasit + parasites parasit + parca parca + parcel parcel + parcell parcel + parcels parcel + parch parch + parched parch + parching parch + parchment parchment + pard pard + pardon pardon + pardona pardona + pardoned pardon + pardoner pardon + pardoning pardon + pardonne pardonn + pardonner pardonn + pardonnez pardonnez + pardons pardon + pare pare + pared pare + parel parel + parent parent + parentage parentag + parents parent + parfect parfect + paring pare + parings pare + paris pari + parish parish + parishioners parishion + parisians parisian + paritors paritor + park park + parks park + parle parl + parler parler + parles parl + parley parlei + parlez parlez + parliament parliament + parlors parlor + parlour parlour + parlous parlou + parmacity parmac + parolles parol + parricide parricid + parricides parricid + parrot parrot + parrots parrot + parsley parslei + parson parson + part part + partake partak + partaken partaken + partaker partak + partakers partak + parted part + parthia parthia + parthian parthian + parthians parthian + parti parti + partial partial + partialize partial + partially partial + participate particip + participation particip + particle particl + particular particular + particularities particular + particularize particular + particularly particularli + particulars particular + parties parti + parting part + partisan partisan + partisans partisan + partition partit + partizan partizan + partlet partlet + partly partli + partner partner + partners partner + partridge partridg + parts part + party parti + pas pa + pash pash + pashed pash + pashful pash + pass pass + passable passabl + passado passado + passage passag + passages passag + passant passant + passed pass + passenger passeng + passengers passeng + passes pass + passeth passeth + passing pass + passio passio + passion passion + passionate passion + passioning passion + passions passion + passive passiv + passport passport + passy passi + past past + paste past + pasterns pastern + pasties pasti + pastime pastim + pastimes pastim + pastoral pastor + pastorals pastor + pastors pastor + pastry pastri + pasture pastur + pastures pastur + pasty pasti + pat pat + patay patai + patch patch + patchery patcheri + patches patch + pate pate + pated pate + patent patent + patents patent + paternal patern + pates pate + path path + pathetical pathet + paths path + pathway pathwai + pathways pathwai + patience patienc + patient patient + patiently patient + patients patient + patines patin + patrician patrician + patricians patrician + patrick patrick + patrimony patrimoni + patroclus patroclu + patron patron + patronage patronag + patroness patro + patrons patron + patrum patrum + patter patter + pattern pattern + patterns pattern + pattle pattl + pauca pauca + paucas pauca + paul paul + paulina paulina + paunch paunch + paunches paunch + pause paus + pauser pauser + pauses paus + pausingly pausingli + pauvres pauvr + pav pav + paved pave + pavement pavement + pavilion pavilion + pavilions pavilion + pavin pavin + paw paw + pawn pawn + pawns pawn + paws paw + pax pax + pay pai + payest payest + paying pai + payment payment + payments payment + pays pai + paysan paysan + paysans paysan + pe pe + peace peac + peaceable peaceabl + peaceably peaceabl + peaceful peac + peacemakers peacemak + peaces peac + peach peach + peaches peach + peacock peacock + peacocks peacock + peak peak + peaking peak + peal peal + peals peal + pear pear + peard peard + pearl pearl + pearls pearl + pears pear + peas pea + peasant peasant + peasantry peasantri + peasants peasant + peascod peascod + pease peas + peaseblossom peaseblossom + peat peat + peaten peaten + peating peat + pebble pebbl + pebbled pebbl + pebbles pebbl + peck peck + pecks peck + peculiar peculiar + pecus pecu + pedant pedant + pedantical pedant + pedascule pedascul + pede pede + pedestal pedest + pedigree pedigre + pedlar pedlar + pedlars pedlar + pedro pedro + peds ped + peel peel + peep peep + peeped peep + peeping peep + peeps peep + peer peer + peereth peereth + peering peer + peerless peerless + peers peer + peesel peesel + peevish peevish + peevishly peevishli + peflur peflur + peg peg + pegasus pegasu + pegs peg + peise peis + peised peis + peize peiz + pelf pelf + pelican pelican + pelion pelion + pell pell + pella pella + pelleted pellet + peloponnesus peloponnesu + pelt pelt + pelting pelt + pembroke pembrok + pen pen + penalties penalti + penalty penalti + penance penanc + pence penc + pencil pencil + pencill pencil + pencils pencil + pendant pendant + pendent pendent + pendragon pendragon + pendulous pendul + penelope penelop + penetrable penetr + penetrate penetr + penetrative penetr + penitence penit + penitent penit + penitential penitenti + penitently penit + penitents penit + penker penker + penknife penknif + penn penn + penned pen + penning pen + pennons pennon + penny penni + pennyworth pennyworth + pennyworths pennyworth + pens pen + pense pens + pension pension + pensioners pension + pensive pensiv + pensived pensiv + pensively pensiv + pent pent + pentecost pentecost + penthesilea penthesilea + penthouse penthous + penurious penuri + penury penuri + peopl peopl + people peopl + peopled peopl + peoples peopl + pepin pepin + pepper pepper + peppercorn peppercorn + peppered pepper + per per + peradventure peradventur + peradventures peradventur + perceiv perceiv + perceive perceiv + perceived perceiv + perceives perceiv + perceiveth perceiveth + perch perch + perchance perchanc + percies perci + percussion percuss + percy perci + perdie perdi + perdita perdita + perdition perdit + perdonato perdonato + perdu perdu + perdurable perdur + perdurably perdur + perdy perdi + pere pere + peregrinate peregrin + peremptorily peremptorili + peremptory peremptori + perfect perfect + perfected perfect + perfecter perfect + perfectest perfectest + perfection perfect + perfections perfect + perfectly perfectli + perfectness perfect + perfidious perfidi + perfidiously perfidi + perforce perforc + perform perform + performance perform + performances perform + performed perform + performer perform + performers perform + performing perform + performs perform + perfum perfum + perfume perfum + perfumed perfum + perfumer perfum + perfumes perfum + perge perg + perhaps perhap + periapts periapt + perigort perigort + perigouna perigouna + peril peril + perilous peril + perils peril + period period + periods period + perish perish + perished perish + perishest perishest + perisheth perisheth + perishing perish + periwig periwig + perjur perjur + perjure perjur + perjured perjur + perjuries perjuri + perjury perjuri + perk perk + perkes perk + permafoy permafoi + permanent perman + permission permiss + permissive permiss + permit permit + permitted permit + pernicious pernici + perniciously pernici + peroration peror + perpend perpend + perpendicular perpendicular + perpendicularly perpendicularli + perpetual perpetu + perpetually perpetu + perpetuity perpetu + perplex perplex + perplexed perplex + perplexity perplex + pers per + persecuted persecut + persecutions persecut + persecutor persecutor + perseus perseu + persever persev + perseverance persever + persevers persev + persia persia + persian persian + persist persist + persisted persist + persistency persist + persistive persist + persists persist + person person + personae persona + personage personag + personages personag + personal person + personally person + personate person + personated person + personates person + personating person + persons person + perspective perspect + perspectively perspect + perspectives perspect + perspicuous perspicu + persuade persuad + persuaded persuad + persuades persuad + persuading persuad + persuasion persuas + persuasions persuas + pert pert + pertain pertain + pertaining pertain + pertains pertain + pertaunt pertaunt + pertinent pertin + pertly pertli + perturb perturb + perturbation perturb + perturbations perturb + perturbed perturb + perus peru + perusal perus + peruse perus + perused perus + perusing perus + perverse pervers + perversely pervers + perverseness pervers + pervert pervert + perverted pervert + peseech peseech + pest pest + pester pester + pestiferous pestifer + pestilence pestil + pestilent pestil + pet pet + petar petar + peter peter + petit petit + petition petit + petitionary petitionari + petitioner petition + petitioners petition + petitions petit + peto peto + petrarch petrarch + petruchio petruchio + petter petter + petticoat petticoat + petticoats petticoat + pettiness petti + pettish pettish + pettitoes pettito + petty petti + peu peu + pew pew + pewter pewter + pewterer pewter + phaethon phaethon + phaeton phaeton + phantasime phantasim + phantasimes phantasim + phantasma phantasma + pharamond pharamond + pharaoh pharaoh + pharsalia pharsalia + pheasant pheasant + pheazar pheazar + phebe phebe + phebes phebe + pheebus pheebu + pheeze pheez + phibbus phibbu + philadelphos philadelpho + philario philario + philarmonus philarmonu + philemon philemon + philip philip + philippan philippan + philippe philipp + philippi philippi + phillida phillida + philo philo + philomel philomel + philomela philomela + philosopher philosoph + philosophers philosoph + philosophical philosoph + philosophy philosophi + philostrate philostr + philotus philotu + phlegmatic phlegmat + phoebe phoeb + phoebus phoebu + phoenicia phoenicia + phoenicians phoenician + phoenix phoenix + phorbus phorbu + photinus photinu + phrase phrase + phraseless phraseless + phrases phrase + phrygia phrygia + phrygian phrygian + phrynia phrynia + physic physic + physical physic + physician physician + physicians physician + physics physic + pia pia + pibble pibbl + pible pibl + picardy picardi + pick pick + pickaxe pickax + pickaxes pickax + pickbone pickbon + picked pick + pickers picker + picking pick + pickle pickl + picklock picklock + pickpurse pickpurs + picks pick + pickt pickt + pickthanks pickthank + pictur pictur + picture pictur + pictured pictur + pictures pictur + pid pid + pie pie + piec piec + piece piec + pieces piec + piecing piec + pied pi + piedness pied + pier pier + pierc pierc + pierce pierc + pierced pierc + pierces pierc + pierceth pierceth + piercing pierc + piercy pierci + piers pier + pies pi + piety pieti + pig pig + pigeon pigeon + pigeons pigeon + pight pight + pigmy pigmi + pigrogromitus pigrogromitu + pike pike + pikes pike + pil pil + pilate pilat + pilates pilat + pilchers pilcher + pile pile + piles pile + pilf pilf + pilfering pilfer + pilgrim pilgrim + pilgrimage pilgrimag + pilgrims pilgrim + pill pill + pillage pillag + pillagers pillag + pillar pillar + pillars pillar + pillicock pillicock + pillory pillori + pillow pillow + pillows pillow + pills pill + pilot pilot + pilots pilot + pimpernell pimpernel + pin pin + pinch pinch + pinched pinch + pinches pinch + pinching pinch + pindarus pindaru + pine pine + pined pine + pines pine + pinfold pinfold + pining pine + pinion pinion + pink pink + pinn pinn + pinnace pinnac + pins pin + pinse pins + pint pint + pintpot pintpot + pioned pion + pioneers pioneer + pioner pioner + pioners pioner + pious piou + pip pip + pipe pipe + piper piper + pipers piper + pipes pipe + piping pipe + pippin pippin + pippins pippin + pirate pirat + pirates pirat + pisa pisa + pisanio pisanio + pish pish + pismires pismir + piss piss + pissing piss + pistol pistol + pistols pistol + pit pit + pitch pitch + pitched pitch + pitcher pitcher + pitchers pitcher + pitchy pitchi + piteous piteou + piteously piteous + pitfall pitfal + pith pith + pithless pithless + pithy pithi + pitie piti + pitied piti + pities piti + pitiful piti + pitifully pitifulli + pitiless pitiless + pits pit + pittance pittanc + pittie pitti + pittikins pittikin + pity piti + pitying piti + pius piu + plac plac + place place + placed place + placentio placentio + places place + placeth placeth + placid placid + placing place + plack plack + placket placket + plackets placket + plagu plagu + plague plagu + plagued plagu + plagues plagu + plaguing plagu + plaguy plagui + plain plain + plainer plainer + plainest plainest + plaining plain + plainings plain + plainly plainli + plainness plain + plains plain + plainsong plainsong + plaintful plaint + plaintiff plaintiff + plaintiffs plaintiff + plaints plaint + planched planch + planet planet + planetary planetari + planets planet + planks plank + plant plant + plantage plantag + plantagenet plantagenet + plantagenets plantagenet + plantain plantain + plantation plantat + planted plant + planteth planteth + plants plant + plash plash + plashy plashi + plast plast + plaster plaster + plasterer plaster + plat plat + plate plate + plated plate + plates plate + platform platform + platforms platform + plats plat + platted plat + plausible plausibl + plausive plausiv + plautus plautu + play plai + played plai + player player + players player + playeth playeth + playfellow playfellow + playfellows playfellow + playhouse playhous + playing plai + plays plai + plea plea + pleach pleach + pleached pleach + plead plead + pleaded plead + pleader pleader + pleaders pleader + pleading plead + pleads plead + pleas plea + pleasance pleasanc + pleasant pleasant + pleasantly pleasantli + please pleas + pleased pleas + pleaser pleaser + pleasers pleaser + pleases pleas + pleasest pleasest + pleaseth pleaseth + pleasing pleas + pleasure pleasur + pleasures pleasur + plebeians plebeian + plebeii plebeii + plebs pleb + pledge pledg + pledges pledg + pleines plein + plenitude plenitud + plenteous plenteou + plenteously plenteous + plenties plenti + plentiful plenti + plentifully plentifulli + plenty plenti + pless pless + plessed pless + plessing pless + pliant pliant + plied pli + plies pli + plight plight + plighted plight + plighter plighter + plod plod + plodded plod + plodders plodder + plodding plod + plods plod + plood plood + ploody ploodi + plot plot + plots plot + plotted plot + plotter plotter + plough plough + ploughed plough + ploughman ploughman + ploughmen ploughmen + plow plow + plows plow + pluck pluck + plucked pluck + plucker plucker + plucking pluck + plucks pluck + plue plue + plum plum + plume plume + plumed plume + plumes plume + plummet plummet + plump plump + plumpy plumpi + plums plum + plung plung + plunge plung + plunged plung + plural plural + plurisy plurisi + plus plu + pluto pluto + plutus plutu + ply ply + po po + pocket pocket + pocketing pocket + pockets pocket + pocky pocki + pody podi + poem poem + poesy poesi + poet poet + poetical poetic + poetry poetri + poets poet + poictiers poictier + poinards poinard + poins poin + point point + pointblank pointblank + pointed point + pointing point + points point + pois poi + poise pois + poising pois + poison poison + poisoned poison + poisoner poison + poisoning poison + poisonous poison + poisons poison + poke poke + poking poke + pol pol + polack polack + polacks polack + poland poland + pold pold + pole pole + poleaxe poleax + polecat polecat + polecats polecat + polemon polemon + poles pole + poli poli + policies polici + policy polici + polish polish + polished polish + politic polit + politician politician + politicians politician + politicly politicli + polixenes polixen + poll poll + polluted pollut + pollution pollut + polonius poloniu + poltroons poltroon + polusion polus + polydamus polydamu + polydore polydor + polyxena polyxena + pomander pomand + pomegranate pomegran + pomewater pomewat + pomfret pomfret + pomgarnet pomgarnet + pommel pommel + pomp pomp + pompeius pompeiu + pompey pompei + pompion pompion + pompous pompou + pomps pomp + pond pond + ponder ponder + ponderous ponder + ponds pond + poniard poniard + poniards poniard + pont pont + pontic pontic + pontifical pontif + ponton ponton + pooh pooh + pool pool + poole pool + poop poop + poor poor + poorer poorer + poorest poorest + poorly poorli + pop pop + pope pope + popedom popedom + popilius popiliu + popingay popingai + popish popish + popp popp + poppy poppi + pops pop + popular popular + popularity popular + populous popul + porch porch + porches porch + pore pore + poring pore + pork pork + porn porn + porpentine porpentin + porridge porridg + porringer porring + port port + portable portabl + portage portag + portal portal + portance portanc + portcullis portculli + portend portend + portends portend + portent portent + portentous portent + portents portent + porter porter + porters porter + portia portia + portion portion + portly portli + portotartarossa portotartarossa + portrait portrait + portraiture portraitur + ports port + portugal portug + pose pose + posied posi + posies posi + position posit + positive posit + positively posit + posse poss + possess possess + possessed possess + possesses possess + possesseth possesseth + possessing possess + possession possess + possessions possess + possessor possessor + posset posset + possets posset + possibilities possibl + possibility possibl + possible possibl + possibly possibl + possitable possit + post post + poste post + posted post + posterior posterior + posteriors posterior + posterity poster + postern postern + posterns postern + posters poster + posthorse posthors + posthorses posthors + posthumus posthumu + posting post + postmaster postmast + posts post + postscript postscript + posture postur + postures postur + posy posi + pot pot + potable potabl + potations potat + potato potato + potatoes potato + potch potch + potency potenc + potent potent + potentates potent + potential potenti + potently potent + potents potent + pothecary pothecari + pother pother + potion potion + potions potion + potpan potpan + pots pot + potter potter + potting pot + pottle pottl + pouch pouch + poulter poulter + poultice poultic + poultney poultnei + pouncet pouncet + pound pound + pounds pound + pour pour + pourest pourest + pouring pour + pourquoi pourquoi + pours pour + pout pout + poverty poverti + pow pow + powd powd + powder powder + power power + powerful power + powerfully powerfulli + powerless powerless + powers power + pox pox + poys poi + poysam poysam + prabbles prabbl + practic practic + practice practic + practiced practic + practicer practic + practices practic + practicing practic + practis practi + practisants practis + practise practis + practiser practis + practisers practis + practises practis + practising practis + praeclarissimus praeclarissimu + praemunire praemunir + praetor praetor + praetors praetor + pragging prag + prague pragu + prain prain + prains prain + prais prai + praise prais + praised prais + praises prais + praisest praisest + praiseworthy praiseworthi + praising prais + prancing pranc + prank prank + pranks prank + prat prat + prate prate + prated prate + prater prater + prating prate + prattle prattl + prattler prattler + prattling prattl + prave prave + prawls prawl + prawns prawn + pray prai + prayer prayer + prayers prayer + praying prai + prays prai + pre pre + preach preach + preached preach + preachers preacher + preaches preach + preaching preach + preachment preachment + pread pread + preambulate preambul + precedence preced + precedent preced + preceding preced + precept precept + preceptial precepti + precepts precept + precinct precinct + precious preciou + preciously precious + precipice precipic + precipitating precipit + precipitation precipit + precise precis + precisely precis + preciseness precis + precisian precisian + precor precor + precurse precurs + precursors precursor + predeceased predeceas + predecessor predecessor + predecessors predecessor + predestinate predestin + predicament predica + predict predict + prediction predict + predictions predict + predominance predomin + predominant predomin + predominate predomin + preeches preech + preeminence preemin + preface prefac + prefer prefer + preferment prefer + preferments prefer + preferr preferr + preferreth preferreth + preferring prefer + prefers prefer + prefiguring prefigur + prefix prefix + prefixed prefix + preformed preform + pregnancy pregnanc + pregnant pregnant + pregnantly pregnantli + prejudicates prejud + prejudice prejudic + prejudicial prejudici + prelate prelat + premeditated premedit + premeditation premedit + premised premis + premises premis + prenez prenez + prenominate prenomin + prentice prentic + prentices prentic + preordinance preordin + prepar prepar + preparation prepar + preparations prepar + prepare prepar + prepared prepar + preparedly preparedli + prepares prepar + preparing prepar + prepost prepost + preposterous preposter + preposterously preposter + prerogatifes prerogatif + prerogative prerog + prerogatived prerogativ + presage presag + presagers presag + presages presag + presageth presageth + presaging presag + prescience prescienc + prescribe prescrib + prescript prescript + prescription prescript + prescriptions prescript + prescripts prescript + presence presenc + presences presenc + present present + presentation present + presented present + presenter present + presenters present + presenteth presenteth + presenting present + presently present + presentment present + presents present + preserv preserv + preservation preserv + preservative preserv + preserve preserv + preserved preserv + preserver preserv + preservers preserv + preserving preserv + president presid + press press + pressed press + presser presser + presses press + pressing press + pressure pressur + pressures pressur + prest prest + prester prester + presume presum + presumes presum + presuming presum + presumption presumpt + presumptuous presumptu + presuppos presuppo + pret pret + pretence pretenc + pretences pretenc + pretend pretend + pretended pretend + pretending pretend + pretense pretens + pretext pretext + pretia pretia + prettier prettier + prettiest prettiest + prettily prettili + prettiness pretti + pretty pretti + prevail prevail + prevailed prevail + prevaileth prevaileth + prevailing prevail + prevailment prevail + prevails prevail + prevent prevent + prevented prevent + prevention prevent + preventions prevent + prevents prevent + prey prei + preyful prey + preys prei + priam priam + priami priami + priamus priamu + pribbles pribbl + price price + prick prick + pricked prick + pricket pricket + pricking prick + pricks prick + pricksong pricksong + pride pride + prides pride + pridge pridg + prie prie + pried pri + prief prief + pries pri + priest priest + priesthood priesthood + priests priest + prig prig + primal primal + prime prime + primer primer + primero primero + primest primest + primitive primit + primo primo + primogenity primogen + primrose primros + primroses primros + primy primi + prince princ + princely princ + princes princ + princess princess + principal princip + principalities princip + principality princip + principle principl + principles principl + princox princox + prings pring + print print + printed print + printing print + printless printless + prints print + prioress prioress + priories priori + priority prioriti + priory priori + priscian priscian + prison prison + prisoner prison + prisoners prison + prisonment prison + prisonnier prisonni + prisons prison + pristine pristin + prithe prith + prithee prithe + privacy privaci + private privat + privately privat + privates privat + privilage privilag + privileg privileg + privilege privileg + privileged privileg + privileges privileg + privilegio privilegio + privily privili + privity priviti + privy privi + priz priz + prize prize + prized prize + prizer prizer + prizes prize + prizest prizest + prizing prize + pro pro + probable probabl + probal probal + probation probat + proceed proce + proceeded proceed + proceeders proceed + proceeding proceed + proceedings proceed + proceeds proce + process process + procession process + proclaim proclaim + proclaimed proclaim + proclaimeth proclaimeth + proclaims proclaim + proclamation proclam + proclamations proclam + proconsul proconsul + procrastinate procrastin + procreant procreant + procreants procreant + procreation procreat + procrus procru + proculeius proculeiu + procur procur + procurator procur + procure procur + procured procur + procures procur + procuring procur + prodigal prodig + prodigality prodig + prodigally prodig + prodigals prodig + prodigies prodigi + prodigious prodigi + prodigiously prodigi + prodigy prodigi + proditor proditor + produc produc + produce produc + produced produc + produces produc + producing produc + proface profac + profan profan + profanation profan + profane profan + profaned profan + profanely profan + profaneness profan + profaners profan + profaning profan + profess profess + professed profess + professes profess + profession profess + professions profess + professors professor + proffer proffer + proffered proffer + profferer proffer + proffers proffer + proficient profici + profit profit + profitable profit + profitably profit + profited profit + profiting profit + profitless profitless + profits profit + profound profound + profoundest profoundest + profoundly profoundli + progenitors progenitor + progeny progeni + progne progn + prognosticate prognost + prognostication prognost + progress progress + progression progress + prohibit prohibit + prohibition prohibit + project project + projection project + projects project + prolixious prolixi + prolixity prolix + prologue prologu + prologues prologu + prolong prolong + prolongs prolong + promethean promethean + prometheus prometheu + promis promi + promise promis + promised promis + promises promis + promiseth promiseth + promising promis + promontory promontori + promotion promot + promotions promot + prompt prompt + prompted prompt + promptement promptement + prompter prompter + prompting prompt + prompts prompt + prompture promptur + promulgate promulg + prone prone + prononcer prononc + prononcez prononcez + pronoun pronoun + pronounc pronounc + pronounce pronounc + pronounced pronounc + pronouncing pronounc + pronouns pronoun + proof proof + proofs proof + prop prop + propagate propag + propagation propag + propend propend + propension propens + proper proper + properer proper + properly properli + propertied properti + properties properti + property properti + prophecies propheci + prophecy propheci + prophesied prophesi + prophesier prophesi + prophesy prophesi + prophesying prophesi + prophet prophet + prophetess prophetess + prophetic prophet + prophetically prophet + prophets prophet + propinquity propinqu + propontic propont + proportion proport + proportionable proportion + proportions proport + propos propo + propose propos + proposed propos + proposer propos + proposes propos + proposing propos + proposition proposit + propositions proposit + propounded propound + propp propp + propre propr + propriety proprieti + props prop + propugnation propugn + prorogue prorogu + prorogued prorogu + proscription proscript + proscriptions proscript + prose prose + prosecute prosecut + prosecution prosecut + proselytes proselyt + proserpina proserpina + prosp prosp + prospect prospect + prosper prosper + prosperity prosper + prospero prospero + prosperous prosper + prosperously prosper + prospers prosper + prostitute prostitut + prostrate prostrat + protect protect + protected protect + protection protect + protector protector + protectors protector + protectorship protectorship + protectress protectress + protects protect + protest protest + protestation protest + protestations protest + protested protest + protester protest + protesting protest + protests protest + proteus proteu + protheus protheu + protract protract + protractive protract + proud proud + prouder prouder + proudest proudest + proudlier proudlier + proudly proudli + prouds proud + prov prov + provand provand + prove prove + proved prove + provender provend + proverb proverb + proverbs proverb + proves prove + proveth proveth + provide provid + provided provid + providence provid + provident provid + providently provid + provider provid + provides provid + province provinc + provinces provinc + provincial provinci + proving prove + provision provis + proviso proviso + provocation provoc + provok provok + provoke provok + provoked provok + provoker provok + provokes provok + provoketh provoketh + provoking provok + provost provost + prowess prowess + prudence prudenc + prudent prudent + prun prun + prune prune + prunes prune + pruning prune + pry pry + prying pry + psalm psalm + psalmist psalmist + psalms psalm + psalteries psalteri + ptolemies ptolemi + ptolemy ptolemi + public public + publican publican + publication public + publicly publicli + publicola publicola + publish publish + published publish + publisher publish + publishing publish + publius publiu + pucelle pucel + puck puck + pudder pudder + pudding pud + puddings pud + puddle puddl + puddled puddl + pudency pudenc + pueritia pueritia + puff puff + puffing puf + puffs puff + pugging pug + puis pui + puissance puissanc + puissant puissant + puke puke + puking puke + pulcher pulcher + puling pule + pull pull + puller puller + pullet pullet + pulling pull + pulls pull + pulpit pulpit + pulpiter pulpit + pulpits pulpit + pulse puls + pulsidge pulsidg + pump pump + pumpion pumpion + pumps pump + pun pun + punched punch + punish punish + punished punish + punishes punish + punishment punish + punishments punish + punk punk + punto punto + puny puni + pupil pupil + pupils pupil + puppet puppet + puppets puppet + puppies puppi + puppy puppi + pur pur + purblind purblind + purchas purcha + purchase purchas + purchased purchas + purchases purchas + purchaseth purchaseth + purchasing purchas + pure pure + purely pure + purer purer + purest purest + purg purg + purgation purgat + purgative purg + purgatory purgatori + purge purg + purged purg + purgers purger + purging purg + purifies purifi + purifying purifi + puritan puritan + purity puriti + purlieus purlieu + purple purpl + purpled purpl + purples purpl + purport purport + purpos purpo + purpose purpos + purposed purpos + purposely purpos + purposes purpos + purposeth purposeth + purposing purpos + purr purr + purs pur + purse purs + pursents pursent + purses purs + pursu pursu + pursue pursu + pursued pursu + pursuers pursuer + pursues pursu + pursuest pursuest + pursueth pursueth + pursuing pursu + pursuit pursuit + pursuivant pursuiv + pursuivants pursuiv + pursy pursi + purus puru + purveyor purveyor + push push + pushes push + pusillanimity pusillanim + put put + putrefy putrefi + putrified putrifi + puts put + putter putter + putting put + puttock puttock + puzzel puzzel + puzzle puzzl + puzzled puzzl + puzzles puzzl + py py + pygmalion pygmalion + pygmies pygmi + pygmy pygmi + pyramid pyramid + pyramides pyramid + pyramids pyramid + pyramis pyrami + pyramises pyramis + pyramus pyramu + pyrenean pyrenean + pyrrhus pyrrhu + pythagoras pythagora + qu qu + quadrangle quadrangl + quae quae + quaff quaff + quaffing quaf + quagmire quagmir + quail quail + quailing quail + quails quail + quaint quaint + quaintly quaintli + quak quak + quake quak + quakes quak + qualification qualif + qualified qualifi + qualifies qualifi + qualify qualifi + qualifying qualifi + qualite qualit + qualities qualiti + quality qualiti + qualm qualm + qualmish qualmish + quam quam + quand quand + quando quando + quantities quantiti + quantity quantiti + quare quar + quarrel quarrel + quarrell quarrel + quarreller quarrel + quarrelling quarrel + quarrelous quarrel + quarrels quarrel + quarrelsome quarrelsom + quarries quarri + quarry quarri + quart quart + quarter quarter + quartered quarter + quartering quarter + quarters quarter + quarts quart + quasi quasi + quat quat + quatch quatch + quay quai + que que + quean quean + queas quea + queasiness queasi + queasy queasi + queen queen + queens queen + quell quell + queller queller + quench quench + quenched quench + quenching quench + quenchless quenchless + quern quern + quest quest + questant questant + question question + questionable question + questioned question + questioning question + questionless questionless + questions question + questrists questrist + quests quest + queubus queubu + qui qui + quick quick + quicken quicken + quickens quicken + quicker quicker + quicklier quicklier + quickly quickli + quickness quick + quicksand quicksand + quicksands quicksand + quicksilverr quicksilverr + quid quid + quiddities quidditi + quiddits quiddit + quier quier + quiet quiet + quieter quieter + quietly quietli + quietness quiet + quietus quietu + quill quill + quillets quillet + quills quill + quilt quilt + quinapalus quinapalu + quince quinc + quinces quinc + quintain quintain + quintessence quintess + quintus quintu + quip quip + quips quip + quire quir + quiring quir + quirk quirk + quirks quirk + quis qui + quit quit + quite quit + quits quit + quittance quittanc + quitted quit + quitting quit + quiver quiver + quivering quiver + quivers quiver + quo quo + quod quod + quoifs quoif + quoint quoint + quoit quoit + quoits quoit + quondam quondam + quoniam quoniam + quote quot + quoted quot + quotes quot + quoth quoth + quotidian quotidian + r r + rabbit rabbit + rabble rabbl + rabblement rabblement + race race + rack rack + rackers racker + racket racket + rackets racket + racking rack + racks rack + radiance radianc + radiant radiant + radish radish + rafe rafe + raft raft + rag rag + rage rage + rages rage + rageth rageth + ragg ragg + ragged rag + raggedness ragged + raging rage + ragozine ragozin + rags rag + rah rah + rail rail + railed rail + railer railer + railest railest + raileth raileth + railing rail + rails rail + raiment raiment + rain rain + rainbow rainbow + raineth raineth + raining rain + rainold rainold + rains rain + rainy raini + rais rai + raise rais + raised rais + raises rais + raising rais + raisins raisin + rak rak + rake rake + rakers raker + rakes rake + ral ral + rald rald + ralph ralph + ram ram + rambures rambur + ramm ramm + rampallian rampallian + rampant rampant + ramping ramp + rampir rampir + ramps ramp + rams ram + ramsey ramsei + ramston ramston + ran ran + rance ranc + rancorous rancor + rancors rancor + rancour rancour + random random + rang rang + range rang + ranged rang + rangers ranger + ranges rang + ranging rang + rank rank + ranker ranker + rankest rankest + ranking rank + rankle rankl + rankly rankli + rankness rank + ranks rank + ransack ransack + ransacking ransack + ransom ransom + ransomed ransom + ransoming ransom + ransomless ransomless + ransoms ransom + rant rant + ranting rant + rap rap + rape rape + rapes rape + rapier rapier + rapiers rapier + rapine rapin + raps rap + rapt rapt + rapture raptur + raptures raptur + rar rar + rare rare + rarely rare + rareness rare + rarer rarer + rarest rarest + rarities rariti + rarity rariti + rascal rascal + rascalliest rascalliest + rascally rascal + rascals rascal + rased rase + rash rash + rasher rasher + rashly rashli + rashness rash + rat rat + ratcatcher ratcatch + ratcliff ratcliff + rate rate + rated rate + rately rate + rates rate + rather rather + ratherest ratherest + ratified ratifi + ratifiers ratifi + ratify ratifi + rating rate + rational ration + ratolorum ratolorum + rats rat + ratsbane ratsban + rattle rattl + rattles rattl + rattling rattl + rature ratur + raught raught + rav rav + rave rave + ravel ravel + raven raven + ravening raven + ravenous raven + ravens raven + ravenspurgh ravenspurgh + raves rave + ravin ravin + raving rave + ravish ravish + ravished ravish + ravisher ravish + ravishing ravish + ravishments ravish + raw raw + rawer rawer + rawly rawli + rawness raw + ray rai + rayed rai + rays rai + raz raz + raze raze + razed raze + razes raze + razeth razeth + razing raze + razor razor + razorable razor + razors razor + razure razur + re re + reach reach + reaches reach + reacheth reacheth + reaching reach + read read + reader reader + readiest readiest + readily readili + readiness readi + reading read + readins readin + reads read + ready readi + real real + really realli + realm realm + realms realm + reap reap + reapers reaper + reaping reap + reaps reap + rear rear + rears rear + rearward rearward + reason reason + reasonable reason + reasonably reason + reasoned reason + reasoning reason + reasonless reasonless + reasons reason + reave reav + rebate rebat + rebato rebato + rebeck rebeck + rebel rebel + rebell rebel + rebelling rebel + rebellion rebellion + rebellious rebelli + rebels rebel + rebound rebound + rebuk rebuk + rebuke rebuk + rebukeable rebuk + rebuked rebuk + rebukes rebuk + rebus rebu + recall recal + recant recant + recantation recant + recanter recant + recanting recant + receipt receipt + receipts receipt + receiv receiv + receive receiv + received receiv + receiver receiv + receives receiv + receivest receivest + receiveth receiveth + receiving receiv + receptacle receptacl + rechate rechat + reciprocal reciproc + reciprocally reciproc + recite recit + recited recit + reciterai reciterai + reck reck + recking reck + reckless reckless + reckon reckon + reckoned reckon + reckoning reckon + reckonings reckon + recks reck + reclaim reclaim + reclaims reclaim + reclusive reclus + recognizance recogniz + recognizances recogniz + recoil recoil + recoiling recoil + recollected recollect + recomforted recomfort + recomforture recomfortur + recommend recommend + recommended recommend + recommends recommend + recompens recompen + recompense recompens + reconcil reconcil + reconcile reconcil + reconciled reconcil + reconcilement reconcil + reconciler reconcil + reconciles reconcil + reconciliation reconcili + record record + recordation record + recorded record + recorder record + recorders record + records record + recount recount + recounted recount + recounting recount + recountments recount + recounts recount + recourse recours + recov recov + recover recov + recoverable recover + recovered recov + recoveries recoveri + recovers recov + recovery recoveri + recreant recreant + recreants recreant + recreate recreat + recreation recreat + rectify rectifi + rector rector + rectorship rectorship + recure recur + recured recur + red red + redbreast redbreast + redder redder + reddest reddest + rede rede + redeem redeem + redeemed redeem + redeemer redeem + redeeming redeem + redeems redeem + redeliver redeliv + redemption redempt + redime redim + redness red + redoubled redoubl + redoubted redoubt + redound redound + redress redress + redressed redress + redresses redress + reduce reduc + reechy reechi + reed reed + reeds reed + reek reek + reeking reek + reeks reek + reeky reeki + reel reel + reeleth reeleth + reeling reel + reels reel + refell refel + refer refer + reference refer + referr referr + referred refer + refigured refigur + refin refin + refined refin + reflect reflect + reflecting reflect + reflection reflect + reflex reflex + reform reform + reformation reform + reformed reform + refractory refractori + refrain refrain + refresh refresh + refreshing refresh + reft reft + refts reft + refuge refug + refus refu + refusal refus + refuse refus + refused refus + refusest refusest + refusing refus + reg reg + regal regal + regalia regalia + regan regan + regard regard + regardance regard + regarded regard + regardfully regardfulli + regarding regard + regards regard + regenerate regener + regent regent + regentship regentship + regia regia + regiment regiment + regiments regiment + regina regina + region region + regions region + regist regist + register regist + registers regist + regreet regreet + regreets regreet + regress regress + reguerdon reguerdon + regular regular + rehears rehear + rehearsal rehears + rehearse rehears + reign reign + reigned reign + reignier reignier + reigning reign + reigns reign + rein rein + reinforc reinforc + reinforce reinforc + reinforcement reinforc + reins rein + reiterate reiter + reject reject + rejected reject + rejoic rejoic + rejoice rejoic + rejoices rejoic + rejoiceth rejoiceth + rejoicing rejoic + rejoicingly rejoicingli + rejoindure rejoindur + rejourn rejourn + rel rel + relapse relaps + relate relat + relates relat + relation relat + relations relat + relative rel + releas relea + release releas + released releas + releasing releas + relent relent + relenting relent + relents relent + reliances relianc + relics relic + relief relief + reliev reliev + relieve reliev + relieved reliev + relieves reliev + relieving reliev + religion religion + religions religion + religious religi + religiously religi + relinquish relinquish + reliques reliqu + reliquit reliquit + relish relish + relume relum + rely reli + relying reli + remain remain + remainder remaind + remainders remaind + remained remain + remaineth remaineth + remaining remain + remains remain + remark remark + remarkable remark + remediate remedi + remedied remedi + remedies remedi + remedy remedi + rememb rememb + remember rememb + remembered rememb + remembers rememb + remembrance remembr + remembrancer remembranc + remembrances remembr + remercimens remercimen + remiss remiss + remission remiss + remissness remiss + remit remit + remnant remnant + remnants remnant + remonstrance remonstr + remorse remors + remorseful remors + remorseless remorseless + remote remot + remotion remot + remov remov + remove remov + removed remov + removedness removed + remover remov + removes remov + removing remov + remunerate remuner + remuneration remuner + rence renc + rend rend + render render + rendered render + renders render + rendezvous rendezv + renegado renegado + renege reneg + reneges reneg + renew renew + renewed renew + renewest renewest + renounce renounc + renouncement renounc + renouncing renounc + renowmed renowm + renown renown + renowned renown + rent rent + rents rent + repaid repaid + repair repair + repaired repair + repairing repair + repairs repair + repass repass + repast repast + repasture repastur + repay repai + repaying repai + repays repai + repeal repeal + repealing repeal + repeals repeal + repeat repeat + repeated repeat + repeating repeat + repeats repeat + repel repel + repent repent + repentance repent + repentant repent + repented repent + repenting repent + repents repent + repetition repetit + repetitions repetit + repin repin + repine repin + repining repin + replant replant + replenish replenish + replenished replenish + replete replet + replication replic + replied repli + replies repli + repliest repliest + reply repli + replying repli + report report + reported report + reporter report + reportest reportest + reporting report + reportingly reportingli + reports report + reposal repos + repose repos + reposeth reposeth + reposing repos + repossess repossess + reprehend reprehend + reprehended reprehend + reprehending reprehend + represent repres + representing repres + reprieve repriev + reprieves repriev + reprisal repris + reproach reproach + reproaches reproach + reproachful reproach + reproachfully reproachfulli + reprobate reprob + reprobation reprob + reproof reproof + reprov reprov + reprove reprov + reproveable reprov + reproves reprov + reproving reprov + repugn repugn + repugnancy repugn + repugnant repugn + repulse repuls + repulsed repuls + repurchas repurcha + repured repur + reputation reput + repute reput + reputed reput + reputeless reputeless + reputes reput + reputing reput + request request + requested request + requesting request + requests request + requiem requiem + requir requir + require requir + required requir + requires requir + requireth requireth + requiring requir + requisite requisit + requisites requisit + requit requit + requital requit + requite requit + requited requit + requites requit + rer rer + rere rere + rers rer + rescu rescu + rescue rescu + rescued rescu + rescues rescu + rescuing rescu + resemblance resembl + resemble resembl + resembled resembl + resembles resembl + resembleth resembleth + resembling resembl + reserv reserv + reservation reserv + reserve reserv + reserved reserv + reserves reserv + reside resid + residence resid + resident resid + resides resid + residing resid + residue residu + resign resign + resignation resign + resist resist + resistance resist + resisted resist + resisting resist + resists resist + resolute resolut + resolutely resolut + resolutes resolut + resolution resolut + resolv resolv + resolve resolv + resolved resolv + resolvedly resolvedli + resolves resolv + resolveth resolveth + resort resort + resorted resort + resounding resound + resounds resound + respeaking respeak + respect respect + respected respect + respecting respect + respective respect + respectively respect + respects respect + respice respic + respite respit + respites respit + responsive respons + respose respos + ress ress + rest rest + rested rest + resteth resteth + restful rest + resting rest + restitution restitut + restless restless + restor restor + restoration restor + restorative restor + restore restor + restored restor + restores restor + restoring restor + restrain restrain + restrained restrain + restraining restrain + restrains restrain + restraint restraint + rests rest + resty resti + resum resum + resume resum + resumes resum + resurrections resurrect + retail retail + retails retail + retain retain + retainers retain + retaining retain + retell retel + retention retent + retentive retent + retinue retinu + retir retir + retire retir + retired retir + retirement retir + retires retir + retiring retir + retold retold + retort retort + retorts retort + retourne retourn + retract retract + retreat retreat + retrograde retrograd + rets ret + return return + returned return + returnest returnest + returneth returneth + returning return + returns return + revania revania + reveal reveal + reveals reveal + revel revel + reveler revel + revell revel + reveller revel + revellers revel + revelling revel + revelry revelri + revels revel + reveng reveng + revenge reveng + revenged reveng + revengeful reveng + revengement reveng + revenger reveng + revengers reveng + revenges reveng + revenging reveng + revengingly revengingli + revenue revenu + revenues revenu + reverb reverb + reverberate reverber + reverbs reverb + reverenc reverenc + reverence rever + reverend reverend + reverent rever + reverently rever + revers rever + reverse revers + reversion revers + reverted revert + review review + reviewest reviewest + revil revil + revile revil + revisits revisit + reviv reviv + revive reviv + revives reviv + reviving reviv + revok revok + revoke revok + revokement revok + revolt revolt + revolted revolt + revolting revolt + revolts revolt + revolution revolut + revolutions revolut + revolve revolv + revolving revolv + reward reward + rewarded reward + rewarder reward + rewarding reward + rewards reward + reword reword + reworded reword + rex rex + rey rei + reynaldo reynaldo + rford rford + rful rful + rfull rfull + rhapsody rhapsodi + rheims rheim + rhenish rhenish + rhesus rhesu + rhetoric rhetor + rheum rheum + rheumatic rheumat + rheums rheum + rheumy rheumi + rhinoceros rhinocero + rhodes rhode + rhodope rhodop + rhubarb rhubarb + rhym rhym + rhyme rhyme + rhymers rhymer + rhymes rhyme + rhyming rhyme + rialto rialto + rib rib + ribald ribald + riband riband + ribands riband + ribaudred ribaudr + ribb ribb + ribbed rib + ribbon ribbon + ribbons ribbon + ribs rib + rice rice + rich rich + richard richard + richer richer + riches rich + richest richest + richly richli + richmond richmond + richmonds richmond + rid rid + riddance riddanc + ridden ridden + riddle riddl + riddles riddl + riddling riddl + ride ride + rider rider + riders rider + rides ride + ridest ridest + rideth rideth + ridge ridg + ridges ridg + ridiculous ridicul + riding ride + rids rid + rien rien + ries ri + rifle rifl + rift rift + rifted rift + rig rig + rigg rigg + riggish riggish + right right + righteous righteou + righteously righteous + rightful right + rightfully rightfulli + rightly rightli + rights right + rigol rigol + rigorous rigor + rigorously rigor + rigour rigour + ril ril + rim rim + rin rin + rinaldo rinaldo + rind rind + ring ring + ringing ring + ringleader ringlead + ringlets ringlet + rings ring + ringwood ringwood + riot riot + rioter rioter + rioting riot + riotous riotou + riots riot + rip rip + ripe ripe + ripely ripe + ripen ripen + ripened ripen + ripeness ripe + ripening ripen + ripens ripen + riper riper + ripest ripest + riping ripe + ripp ripp + ripping rip + rise rise + risen risen + rises rise + riseth riseth + rish rish + rising rise + rite rite + rites rite + rivage rivag + rival rival + rivality rival + rivall rival + rivals rival + rive rive + rived rive + rivelled rivel + river river + rivers river + rivet rivet + riveted rivet + rivets rivet + rivo rivo + rj rj + rless rless + road road + roads road + roam roam + roaming roam + roan roan + roar roar + roared roar + roarers roarer + roaring roar + roars roar + roast roast + roasted roast + rob rob + roba roba + robas roba + robb robb + robbed rob + robber robber + robbers robber + robbery robberi + robbing rob + robe robe + robed robe + robert robert + robes robe + robin robin + robs rob + robustious robusti + rochester rochest + rochford rochford + rock rock + rocks rock + rocky rocki + rod rod + rode rode + roderigo roderigo + rods rod + roe roe + roes roe + roger roger + rogero rogero + rogue rogu + roguery rogueri + rogues rogu + roguish roguish + roi roi + roisting roist + roll roll + rolled roll + rolling roll + rolls roll + rom rom + romage romag + roman roman + romano romano + romanos romano + romans roman + rome rome + romeo romeo + romish romish + rondure rondur + ronyon ronyon + rood rood + roof roof + roofs roof + rook rook + rooks rook + rooky rooki + room room + rooms room + root root + rooted root + rootedly rootedli + rooteth rooteth + rooting root + roots root + rope rope + ropery roperi + ropes rope + roping rope + ros ro + rosalind rosalind + rosalinda rosalinda + rosalinde rosalind + rosaline rosalin + roscius rosciu + rose rose + rosed rose + rosemary rosemari + rosencrantz rosencrantz + roses rose + ross ross + rosy rosi + rot rot + rote rote + roted rote + rother rother + rotherham rotherham + rots rot + rotted rot + rotten rotten + rottenness rotten + rotting rot + rotundity rotund + rouen rouen + rough rough + rougher rougher + roughest roughest + roughly roughli + roughness rough + round round + rounded round + roundel roundel + rounder rounder + roundest roundest + rounding round + roundly roundli + rounds round + roundure roundur + rous rou + rouse rous + roused rous + rousillon rousillon + rously rousli + roussi roussi + rout rout + routed rout + routs rout + rove rove + rover rover + row row + rowel rowel + rowland rowland + rowlands rowland + roy roi + royal royal + royalize royal + royally royal + royalties royalti + royalty royalti + roynish roynish + rs rs + rt rt + rub rub + rubb rubb + rubbing rub + rubbish rubbish + rubies rubi + rubious rubiou + rubs rub + ruby rubi + rud rud + rudand rudand + rudder rudder + ruddiness ruddi + ruddock ruddock + ruddy ruddi + rude rude + rudely rude + rudeness rude + ruder ruder + rudesby rudesbi + rudest rudest + rudiments rudiment + rue rue + rued ru + ruff ruff + ruffian ruffian + ruffians ruffian + ruffle ruffl + ruffling ruffl + ruffs ruff + rug rug + rugby rugbi + rugemount rugemount + rugged rug + ruin ruin + ruinate ruinat + ruined ruin + ruining ruin + ruinous ruinou + ruins ruin + rul rul + rule rule + ruled rule + ruler ruler + rulers ruler + rules rule + ruling rule + rumble rumbl + ruminaies ruminai + ruminat ruminat + ruminate rumin + ruminated rumin + ruminates rumin + rumination rumin + rumor rumor + rumour rumour + rumourer rumour + rumours rumour + rump rump + run run + runagate runag + runagates runag + runaway runawai + runaways runawai + rung rung + runn runn + runner runner + runners runner + running run + runs run + rupture ruptur + ruptures ruptur + rural rural + rush rush + rushes rush + rushing rush + rushling rushl + rushy rushi + russet russet + russia russia + russian russian + russians russian + rust rust + rusted rust + rustic rustic + rustically rustic + rustics rustic + rustle rustl + rustling rustl + rusts rust + rusty rusti + rut rut + ruth ruth + ruthful ruth + ruthless ruthless + rutland rutland + ruttish ruttish + ry ry + rye rye + rything ryth + s s + sa sa + saba saba + sabbath sabbath + sable sabl + sables sabl + sack sack + sackbuts sackbut + sackcloth sackcloth + sacked sack + sackerson sackerson + sacks sack + sacrament sacrament + sacred sacr + sacrific sacrif + sacrifice sacrific + sacrificers sacrific + sacrifices sacrific + sacrificial sacrifici + sacrificing sacrif + sacrilegious sacrilegi + sacring sacr + sad sad + sadder sadder + saddest saddest + saddle saddl + saddler saddler + saddles saddl + sadly sadli + sadness sad + saf saf + safe safe + safeguard safeguard + safely safe + safer safer + safest safest + safeties safeti + safety safeti + saffron saffron + sag sag + sage sage + sagittary sagittari + said said + saidst saidst + sail sail + sailing sail + sailmaker sailmak + sailor sailor + sailors sailor + sails sail + sain sain + saint saint + sainted saint + saintlike saintlik + saints saint + saith saith + sake sake + sakes sake + sala sala + salad salad + salamander salamand + salary salari + sale sale + salerio salerio + salicam salicam + salique saliqu + salisbury salisburi + sall sall + sallet sallet + sallets sallet + sallies salli + sallow sallow + sally salli + salmon salmon + salmons salmon + salt salt + salter salter + saltiers saltier + saltness salt + saltpetre saltpetr + salutation salut + salutations salut + salute salut + saluted salut + salutes salut + saluteth saluteth + salv salv + salvation salvat + salve salv + salving salv + same same + samingo samingo + samp samp + sampire sampir + sample sampl + sampler sampler + sampson sampson + samson samson + samsons samson + sancta sancta + sanctified sanctifi + sanctifies sanctifi + sanctify sanctifi + sanctimonies sanctimoni + sanctimonious sanctimoni + sanctimony sanctimoni + sanctities sanctiti + sanctity sanctiti + sanctuarize sanctuar + sanctuary sanctuari + sand sand + sandal sandal + sandbag sandbag + sanded sand + sands sand + sandy sandi + sandys sandi + sang sang + sanguine sanguin + sanguis sangui + sanity saniti + sans san + santrailles santrail + sap sap + sapient sapient + sapit sapit + sapless sapless + sapling sapl + sapphire sapphir + sapphires sapphir + saracens saracen + sarcenet sarcenet + sard sard + sardians sardian + sardinia sardinia + sardis sardi + sarum sarum + sat sat + satan satan + satchel satchel + sate sate + sated sate + satiate satiat + satiety satieti + satin satin + satire satir + satirical satir + satis sati + satisfaction satisfact + satisfied satisfi + satisfies satisfi + satisfy satisfi + satisfying satisfi + saturday saturdai + saturdays saturdai + saturn saturn + saturnine saturnin + saturninus saturninu + satyr satyr + satyrs satyr + sauc sauc + sauce sauc + sauced sauc + saucers saucer + sauces sauc + saucily saucili + sauciness sauci + saucy sauci + sauf sauf + saunder saunder + sav sav + savage savag + savagely savag + savageness savag + savagery savageri + savages savag + save save + saved save + saves save + saving save + saviour saviour + savory savori + savour savour + savouring savour + savours savour + savoury savouri + savoy savoi + saw saw + sawed saw + sawest sawest + sawn sawn + sawpit sawpit + saws saw + sawyer sawyer + saxons saxon + saxony saxoni + saxton saxton + say sai + sayest sayest + saying sai + sayings sai + says sai + sayst sayst + sblood sblood + sc sc + scab scab + scabbard scabbard + scabs scab + scaffold scaffold + scaffoldage scaffoldag + scal scal + scald scald + scalded scald + scalding scald + scale scale + scaled scale + scales scale + scaling scale + scall scall + scalp scalp + scalps scalp + scaly scali + scamble scambl + scambling scambl + scamels scamel + scan scan + scandal scandal + scandaliz scandaliz + scandalous scandal + scandy scandi + scann scann + scant scant + scanted scant + scanter scanter + scanting scant + scantling scantl + scants scant + scap scap + scape scape + scaped scape + scapes scape + scapeth scapeth + scar scar + scarce scarc + scarcely scarc + scarcity scarciti + scare scare + scarecrow scarecrow + scarecrows scarecrow + scarf scarf + scarfed scarf + scarfs scarf + scaring scare + scarlet scarlet + scarr scarr + scarre scarr + scars scar + scarus scaru + scath scath + scathe scath + scathful scath + scatt scatt + scatter scatter + scattered scatter + scattering scatter + scatters scatter + scelera scelera + scelerisque scelerisqu + scene scene + scenes scene + scent scent + scented scent + scept scept + scepter scepter + sceptre sceptr + sceptred sceptr + sceptres sceptr + schedule schedul + schedules schedul + scholar scholar + scholarly scholarli + scholars scholar + school school + schoolboy schoolboi + schoolboys schoolboi + schoolfellows schoolfellow + schooling school + schoolmaster schoolmast + schoolmasters schoolmast + schools school + sciatica sciatica + sciaticas sciatica + science scienc + sciences scienc + scimitar scimitar + scion scion + scions scion + scissors scissor + scoff scoff + scoffer scoffer + scoffing scof + scoffs scoff + scoggin scoggin + scold scold + scolding scold + scolds scold + sconce sconc + scone scone + scope scope + scopes scope + scorch scorch + scorched scorch + score score + scored score + scores score + scoring score + scorn scorn + scorned scorn + scornful scorn + scornfully scornfulli + scorning scorn + scorns scorn + scorpion scorpion + scorpions scorpion + scot scot + scotch scotch + scotches scotch + scotland scotland + scots scot + scottish scottish + scoundrels scoundrel + scour scour + scoured scour + scourg scourg + scourge scourg + scouring scour + scout scout + scouts scout + scowl scowl + scrap scrap + scrape scrape + scraping scrape + scraps scrap + scratch scratch + scratches scratch + scratching scratch + scream scream + screams scream + screech screech + screeching screech + screen screen + screens screen + screw screw + screws screw + scribbl scribbl + scribbled scribbl + scribe scribe + scribes scribe + scrimers scrimer + scrip scrip + scrippage scrippag + scripture scriptur + scriptures scriptur + scrivener scriven + scroll scroll + scrolls scroll + scroop scroop + scrowl scrowl + scroyles scroyl + scrubbed scrub + scruple scrupl + scruples scrupl + scrupulous scrupul + scuffles scuffl + scuffling scuffl + scullion scullion + sculls scull + scum scum + scurril scurril + scurrility scurril + scurrilous scurril + scurvy scurvi + scuse scuse + scut scut + scutcheon scutcheon + scutcheons scutcheon + scylla scylla + scythe scyth + scythed scyth + scythia scythia + scythian scythian + sdeath sdeath + se se + sea sea + seacoal seacoal + seafaring seafar + seal seal + sealed seal + sealing seal + seals seal + seam seam + seamen seamen + seamy seami + seaport seaport + sear sear + searce searc + search search + searchers searcher + searches search + searcheth searcheth + searching search + seared sear + seas sea + seasick seasick + seaside seasid + season season + seasoned season + seasons season + seat seat + seated seat + seats seat + sebastian sebastian + second second + secondarily secondarili + secondary secondari + seconded second + seconds second + secrecy secreci + secret secret + secretaries secretari + secretary secretari + secretly secretli + secrets secret + sect sect + sectary sectari + sects sect + secundo secundo + secure secur + securely secur + securing secur + security secur + sedg sedg + sedge sedg + sedges sedg + sedgy sedgi + sedition sedit + seditious sediti + seduc seduc + seduce seduc + seduced seduc + seducer seduc + seducing seduc + see see + seed seed + seeded seed + seedness seed + seeds seed + seedsman seedsman + seein seein + seeing see + seek seek + seeking seek + seeks seek + seel seel + seeling seel + seely seeli + seem seem + seemed seem + seemers seemer + seemest seemest + seemeth seemeth + seeming seem + seemingly seemingli + seemly seemli + seems seem + seen seen + seer seer + sees see + seese sees + seest seest + seethe seeth + seethes seeth + seething seeth + seeting seet + segregation segreg + seigneur seigneur + seigneurs seigneur + seiz seiz + seize seiz + seized seiz + seizes seiz + seizeth seizeth + seizing seiz + seizure seizur + seld seld + seldom seldom + select select + seleucus seleucu + self self + selfsame selfsam + sell sell + seller seller + selling sell + sells sell + selves selv + semblable semblabl + semblably semblabl + semblance semblanc + semblances semblanc + semblative sembl + semi semi + semicircle semicircl + semiramis semirami + semper semper + sempronius semproniu + senate senat + senator senat + senators senat + send send + sender sender + sendeth sendeth + sending send + sends send + seneca seneca + senior senior + seniory seniori + senis seni + sennet sennet + senoys senoi + sense sens + senseless senseless + senses sens + sensible sensibl + sensibly sensibl + sensual sensual + sensuality sensual + sent sent + sentenc sentenc + sentence sentenc + sentences sentenc + sententious sententi + sentinel sentinel + sentinels sentinel + separable separ + separate separ + separated separ + separates separ + separation separ + septentrion septentrion + sepulchre sepulchr + sepulchres sepulchr + sepulchring sepulchr + sequel sequel + sequence sequenc + sequent sequent + sequest sequest + sequester sequest + sequestration sequestr + sere sere + serenis sereni + serge serg + sergeant sergeant + serious seriou + seriously serious + sermon sermon + sermons sermon + serpent serpent + serpentine serpentin + serpents serpent + serpigo serpigo + serv serv + servant servant + servanted servant + servants servant + serve serv + served serv + server server + serves serv + serveth serveth + service servic + serviceable servic + services servic + servile servil + servility servil + servilius serviliu + serving serv + servingman servingman + servingmen servingmen + serviteur serviteur + servitor servitor + servitors servitor + servitude servitud + sessa sessa + session session + sessions session + sestos sesto + set set + setebos setebo + sets set + setter setter + setting set + settle settl + settled settl + settlest settlest + settling settl + sev sev + seven seven + sevenfold sevenfold + sevennight sevennight + seventeen seventeen + seventh seventh + seventy seventi + sever sever + several sever + severally sever + severals sever + severe sever + severed sever + severely sever + severest severest + severing sever + severity sever + severn severn + severs sever + sew sew + seward seward + sewer sewer + sewing sew + sex sex + sexes sex + sexton sexton + sextus sextu + seymour seymour + seyton seyton + sfoot sfoot + sh sh + shackle shackl + shackles shackl + shade shade + shades shade + shadow shadow + shadowed shadow + shadowing shadow + shadows shadow + shadowy shadowi + shady shadi + shafalus shafalu + shaft shaft + shafts shaft + shag shag + shak shak + shake shake + shaked shake + shaken shaken + shakes shake + shaking shake + shales shale + shall shall + shallenge shalleng + shallow shallow + shallowest shallowest + shallowly shallowli + shallows shallow + shalt shalt + sham sham + shambles shambl + shame shame + shamed shame + shameful shame + shamefully shamefulli + shameless shameless + shames shame + shamest shamest + shaming shame + shank shank + shanks shank + shap shap + shape shape + shaped shape + shapeless shapeless + shapen shapen + shapes shape + shaping shape + shar shar + shard shard + sharded shard + shards shard + share share + shared share + sharers sharer + shares share + sharing share + shark shark + sharp sharp + sharpen sharpen + sharpened sharpen + sharpens sharpen + sharper sharper + sharpest sharpest + sharply sharpli + sharpness sharp + sharps sharp + shatter shatter + shav shav + shave shave + shaven shaven + shaw shaw + she she + sheaf sheaf + sheal sheal + shear shear + shearers shearer + shearing shear + shearman shearman + shears shear + sheath sheath + sheathe sheath + sheathed sheath + sheathes sheath + sheathing sheath + sheaved sheav + sheaves sheav + shed shed + shedding shed + sheds shed + sheen sheen + sheep sheep + sheepcote sheepcot + sheepcotes sheepcot + sheeps sheep + sheepskins sheepskin + sheer sheer + sheet sheet + sheeted sheet + sheets sheet + sheffield sheffield + shelf shelf + shell shell + shells shell + shelt shelt + shelter shelter + shelters shelter + shelves shelv + shelving shelv + shelvy shelvi + shent shent + shepherd shepherd + shepherdes shepherd + shepherdess shepherdess + shepherdesses shepherdess + shepherds shepherd + sher sher + sheriff sheriff + sherris sherri + shes she + sheweth sheweth + shield shield + shielded shield + shields shield + shift shift + shifted shift + shifting shift + shifts shift + shilling shill + shillings shill + shin shin + shine shine + shines shine + shineth shineth + shining shine + shins shin + shiny shini + ship ship + shipboard shipboard + shipman shipman + shipmaster shipmast + shipmen shipmen + shipp shipp + shipped ship + shipping ship + ships ship + shipt shipt + shipwreck shipwreck + shipwrecking shipwreck + shipwright shipwright + shipwrights shipwright + shire shire + shirley shirlei + shirt shirt + shirts shirt + shive shive + shiver shiver + shivering shiver + shivers shiver + shoal shoal + shoals shoal + shock shock + shocks shock + shod shod + shoe shoe + shoeing shoe + shoemaker shoemak + shoes shoe + shog shog + shone shone + shook shook + shoon shoon + shoot shoot + shooter shooter + shootie shooti + shooting shoot + shoots shoot + shop shop + shops shop + shore shore + shores shore + shorn shorn + short short + shortcake shortcak + shorten shorten + shortened shorten + shortens shorten + shorter shorter + shortly shortli + shortness short + shot shot + shotten shotten + shoughs shough + should should + shoulder shoulder + shouldering shoulder + shoulders shoulder + shouldst shouldst + shout shout + shouted shout + shouting shout + shouts shout + shov shov + shove shove + shovel shovel + shovels shovel + show show + showed show + shower shower + showers shower + showest showest + showing show + shown shown + shows show + shreds shred + shrew shrew + shrewd shrewd + shrewdly shrewdli + shrewdness shrewd + shrewish shrewish + shrewishly shrewishli + shrewishness shrewish + shrews shrew + shrewsbury shrewsburi + shriek shriek + shrieking shriek + shrieks shriek + shrieve shriev + shrift shrift + shrill shrill + shriller shriller + shrills shrill + shrilly shrilli + shrimp shrimp + shrine shrine + shrink shrink + shrinking shrink + shrinks shrink + shriv shriv + shrive shrive + shriver shriver + shrives shrive + shriving shrive + shroud shroud + shrouded shroud + shrouding shroud + shrouds shroud + shrove shrove + shrow shrow + shrows shrow + shrub shrub + shrubs shrub + shrug shrug + shrugs shrug + shrunk shrunk + shudd shudd + shudders shudder + shuffl shuffl + shuffle shuffl + shuffled shuffl + shuffling shuffl + shun shun + shunless shunless + shunn shunn + shunned shun + shunning shun + shuns shun + shut shut + shuts shut + shuttle shuttl + shy shy + shylock shylock + si si + sibyl sibyl + sibylla sibylla + sibyls sibyl + sicil sicil + sicilia sicilia + sicilian sicilian + sicilius siciliu + sicils sicil + sicily sicili + sicinius siciniu + sick sick + sicken sicken + sickens sicken + sicker sicker + sickle sickl + sicklemen sicklemen + sicklied sickli + sickliness sickli + sickly sickli + sickness sick + sicles sicl + sicyon sicyon + side side + sided side + sides side + siege sieg + sieges sieg + sienna sienna + sies si + sieve siev + sift sift + sifted sift + sigeia sigeia + sigh sigh + sighed sigh + sighing sigh + sighs sigh + sight sight + sighted sight + sightless sightless + sightly sightli + sights sight + sign sign + signal signal + signet signet + signieur signieur + significant signific + significants signific + signified signifi + signifies signifi + signify signifi + signifying signifi + signior signior + signiories signiori + signiors signior + signiory signiori + signor signor + signories signori + signs sign + signum signum + silenc silenc + silence silenc + silenced silenc + silencing silenc + silent silent + silently silent + silius siliu + silk silk + silken silken + silkman silkman + silks silk + silliest silliest + silliness silli + silling sill + silly silli + silva silva + silver silver + silvered silver + silverly silverli + silvia silvia + silvius silviu + sima sima + simile simil + similes simil + simois simoi + simon simon + simony simoni + simp simp + simpcox simpcox + simple simpl + simpleness simpl + simpler simpler + simples simpl + simplicity simplic + simply simpli + simular simular + simulation simul + sin sin + since sinc + sincere sincer + sincerely sincer + sincerity sincer + sinel sinel + sinew sinew + sinewed sinew + sinews sinew + sinewy sinewi + sinful sin + sinfully sinfulli + sing sing + singe sing + singeing sing + singer singer + singes sing + singeth singeth + singing sing + single singl + singled singl + singleness singl + singly singli + sings sing + singular singular + singulariter singularit + singularities singular + singularity singular + singuled singul + sinister sinist + sink sink + sinking sink + sinks sink + sinn sinn + sinner sinner + sinners sinner + sinning sin + sinon sinon + sins sin + sip sip + sipping sip + sir sir + sire sire + siren siren + sirrah sirrah + sirs sir + sist sist + sister sister + sisterhood sisterhood + sisterly sisterli + sisters sister + sit sit + sith sith + sithence sithenc + sits sit + sitting sit + situate situat + situation situat + situations situat + siward siward + six six + sixpence sixpenc + sixpences sixpenc + sixpenny sixpenni + sixteen sixteen + sixth sixth + sixty sixti + siz siz + size size + sizes size + sizzle sizzl + skains skain + skamble skambl + skein skein + skelter skelter + skies ski + skilful skil + skilfully skilfulli + skill skill + skilless skilless + skillet skillet + skillful skill + skills skill + skim skim + skimble skimbl + skin skin + skinker skinker + skinny skinni + skins skin + skip skip + skipp skipp + skipper skipper + skipping skip + skirmish skirmish + skirmishes skirmish + skirr skirr + skirted skirt + skirts skirt + skittish skittish + skulking skulk + skull skull + skulls skull + sky sky + skyey skyei + skyish skyish + slab slab + slack slack + slackly slackli + slackness slack + slain slain + slake slake + sland sland + slander slander + slandered slander + slanderer slander + slanderers slander + slandering slander + slanderous slander + slanders slander + slash slash + slaught slaught + slaughter slaughter + slaughtered slaughter + slaughterer slaughter + slaughterman slaughterman + slaughtermen slaughtermen + slaughterous slaughter + slaughters slaughter + slave slave + slaver slaver + slavery slaveri + slaves slave + slavish slavish + slay slai + slayeth slayeth + slaying slai + slays slai + sleave sleav + sledded sled + sleek sleek + sleekly sleekli + sleep sleep + sleeper sleeper + sleepers sleeper + sleepest sleepest + sleeping sleep + sleeps sleep + sleepy sleepi + sleeve sleev + sleeves sleev + sleid sleid + sleided sleid + sleight sleight + sleights sleight + slender slender + slenderer slender + slenderly slenderli + slept slept + slew slew + slewest slewest + slice slice + slid slid + slide slide + slides slide + sliding slide + slight slight + slighted slight + slightest slightest + slightly slightli + slightness slight + slights slight + slily slili + slime slime + slimy slimi + slings sling + slink slink + slip slip + slipp slipp + slipper slipper + slippers slipper + slippery slipperi + slips slip + slish slish + slit slit + sliver sliver + slobb slobb + slomber slomber + slop slop + slope slope + slops slop + sloth sloth + slothful sloth + slough slough + slovenly slovenli + slovenry slovenri + slow slow + slower slower + slowly slowli + slowness slow + slubber slubber + slug slug + sluggard sluggard + sluggardiz sluggardiz + sluggish sluggish + sluic sluic + slumb slumb + slumber slumber + slumbers slumber + slumbery slumberi + slunk slunk + slut slut + sluts slut + sluttery slutteri + sluttish sluttish + sluttishness sluttish + sly sly + slys sly + smack smack + smacking smack + smacks smack + small small + smaller smaller + smallest smallest + smallness small + smalus smalu + smart smart + smarting smart + smartly smartli + smatch smatch + smatter smatter + smear smear + smell smell + smelling smell + smells smell + smelt smelt + smil smil + smile smile + smiled smile + smiles smile + smilest smilest + smilets smilet + smiling smile + smilingly smilingli + smirch smirch + smirched smirch + smit smit + smite smite + smites smite + smith smith + smithfield smithfield + smock smock + smocks smock + smok smok + smoke smoke + smoked smoke + smokes smoke + smoking smoke + smoky smoki + smooth smooth + smoothed smooth + smoothing smooth + smoothly smoothli + smoothness smooth + smooths smooth + smote smote + smoth smoth + smother smother + smothered smother + smothering smother + smug smug + smulkin smulkin + smutch smutch + snaffle snaffl + snail snail + snails snail + snake snake + snakes snake + snaky snaki + snap snap + snapp snapp + snapper snapper + snar snar + snare snare + snares snare + snarl snarl + snarleth snarleth + snarling snarl + snatch snatch + snatchers snatcher + snatches snatch + snatching snatch + sneak sneak + sneaking sneak + sneap sneap + sneaping sneap + sneck sneck + snip snip + snipe snipe + snipt snipt + snore snore + snores snore + snoring snore + snorting snort + snout snout + snow snow + snowballs snowbal + snowed snow + snowy snowi + snuff snuff + snuffs snuff + snug snug + so so + soak soak + soaking soak + soaks soak + soar soar + soaring soar + soars soar + sob sob + sobbing sob + sober sober + soberly soberli + sobriety sobrieti + sobs sob + sociable sociabl + societies societi + society societi + socks sock + socrates socrat + sod sod + sodden sodden + soe soe + soever soever + soft soft + soften soften + softens soften + softer softer + softest softest + softly softli + softness soft + soil soil + soiled soil + soilure soilur + soit soit + sojourn sojourn + sol sol + sola sola + solace solac + solanio solanio + sold sold + soldat soldat + solder solder + soldest soldest + soldier soldier + soldiers soldier + soldiership soldiership + sole sole + solely sole + solem solem + solemn solemn + solemness solem + solemnities solemn + solemnity solemn + solemniz solemniz + solemnize solemn + solemnized solemn + solemnly solemnli + soles sole + solicit solicit + solicitation solicit + solicited solicit + soliciting solicit + solicitings solicit + solicitor solicitor + solicits solicit + solid solid + solidares solidar + solidity solid + solinus solinu + solitary solitari + solomon solomon + solon solon + solum solum + solus solu + solyman solyman + some some + somebody somebodi + someone someon + somerset somerset + somerville somervil + something someth + sometime sometim + sometimes sometim + somever somev + somewhat somewhat + somewhere somewher + somewhither somewhith + somme somm + son son + sonance sonanc + song song + songs song + sonnet sonnet + sonneting sonnet + sonnets sonnet + sons son + sont sont + sonties sonti + soon soon + sooner sooner + soonest soonest + sooth sooth + soothe sooth + soothers soother + soothing sooth + soothsay soothsai + soothsayer soothsay + sooty sooti + sop sop + sophister sophist + sophisticated sophist + sophy sophi + sops sop + sorcerer sorcer + sorcerers sorcer + sorceress sorceress + sorceries sorceri + sorcery sorceri + sore sore + sorel sorel + sorely sore + sorer sorer + sores sore + sorrier sorrier + sorriest sorriest + sorrow sorrow + sorrowed sorrow + sorrowest sorrowest + sorrowful sorrow + sorrowing sorrow + sorrows sorrow + sorry sorri + sort sort + sortance sortanc + sorted sort + sorting sort + sorts sort + sossius sossiu + sot sot + soto soto + sots sot + sottish sottish + soud soud + sought sought + soul soul + sould sould + soulless soulless + souls soul + sound sound + sounded sound + sounder sounder + soundest soundest + sounding sound + soundless soundless + soundly soundli + soundness sound + soundpost soundpost + sounds sound + sour sour + source sourc + sources sourc + sourest sourest + sourly sourli + sours sour + sous sou + souse sous + south south + southam southam + southampton southampton + southerly southerli + southern southern + southward southward + southwark southwark + southwell southwel + souviendrai souviendrai + sov sov + sovereign sovereign + sovereignest sovereignest + sovereignly sovereignli + sovereignty sovereignti + sovereignvours sovereignvour + sow sow + sowing sow + sowl sowl + sowter sowter + space space + spaces space + spacious spaciou + spade spade + spades spade + spain spain + spak spak + spake spake + spakest spakest + span span + spangle spangl + spangled spangl + spaniard spaniard + spaniel spaniel + spaniels spaniel + spanish spanish + spann spann + spans span + spar spar + spare spare + spares spare + sparing spare + sparingly sparingli + spark spark + sparkle sparkl + sparkles sparkl + sparkling sparkl + sparks spark + sparrow sparrow + sparrows sparrow + sparta sparta + spartan spartan + spavin spavin + spavins spavin + spawn spawn + speak speak + speaker speaker + speakers speaker + speakest speakest + speaketh speaketh + speaking speak + speaks speak + spear spear + speargrass speargrass + spears spear + special special + specialities special + specially special + specialties specialti + specialty specialti + specify specifi + speciously specious + spectacle spectacl + spectacled spectacl + spectacles spectacl + spectators spectat + spectatorship spectatorship + speculation specul + speculations specul + speculative specul + sped sped + speech speech + speeches speech + speechless speechless + speed speed + speeded speed + speedier speedier + speediest speediest + speedily speedili + speediness speedi + speeding speed + speeds speed + speedy speedi + speens speen + spell spell + spelling spell + spells spell + spelt spelt + spencer spencer + spend spend + spendest spendest + spending spend + spends spend + spendthrift spendthrift + spent spent + sperato sperato + sperm sperm + spero spero + sperr sperr + spher spher + sphere sphere + sphered sphere + spheres sphere + spherical spheric + sphery spheri + sphinx sphinx + spice spice + spiced spice + spicery spiceri + spices spice + spider spider + spiders spider + spied spi + spies spi + spieth spieth + spightfully spightfulli + spigot spigot + spill spill + spilling spill + spills spill + spilt spilt + spilth spilth + spin spin + spinii spinii + spinners spinner + spinster spinster + spinsters spinster + spire spire + spirit spirit + spirited spirit + spiritless spiritless + spirits spirit + spiritual spiritu + spiritualty spiritualti + spirt spirt + spit spit + spital spital + spite spite + spited spite + spiteful spite + spites spite + spits spit + spitted spit + spitting spit + splay splai + spleen spleen + spleenful spleen + spleens spleen + spleeny spleeni + splendour splendour + splenitive splenit + splinter splinter + splinters splinter + split split + splits split + splitted split + splitting split + spoil spoil + spoils spoil + spok spok + spoke spoke + spoken spoken + spokes spoke + spokesman spokesman + sponge spong + spongy spongi + spoon spoon + spoons spoon + sport sport + sportful sport + sporting sport + sportive sportiv + sports sport + spot spot + spotless spotless + spots spot + spotted spot + spousal spousal + spouse spous + spout spout + spouting spout + spouts spout + sprag sprag + sprang sprang + sprat sprat + sprawl sprawl + spray sprai + sprays sprai + spread spread + spreading spread + spreads spread + sprighted spright + sprightful spright + sprightly sprightli + sprigs sprig + spring spring + springe spring + springes spring + springeth springeth + springhalt springhalt + springing spring + springs spring + springtime springtim + sprinkle sprinkl + sprinkles sprinkl + sprite sprite + sprited sprite + spritely sprite + sprites sprite + spriting sprite + sprout sprout + spruce spruce + sprung sprung + spun spun + spur spur + spurio spurio + spurn spurn + spurns spurn + spurr spurr + spurrer spurrer + spurring spur + spurs spur + spy spy + spying spy + squabble squabbl + squadron squadron + squadrons squadron + squand squand + squar squar + square squar + squarer squarer + squares squar + squash squash + squeak squeak + squeaking squeak + squeal squeal + squealing squeal + squeezes squeez + squeezing squeez + squele squel + squier squier + squints squint + squiny squini + squire squir + squires squir + squirrel squirrel + st st + stab stab + stabb stabb + stabbed stab + stabbing stab + stable stabl + stableness stabl + stables stabl + stablish stablish + stablishment stablish + stabs stab + stacks stack + staff staff + stafford stafford + staffords stafford + staffordshire staffordshir + stag stag + stage stage + stages stage + stagger stagger + staggering stagger + staggers stagger + stags stag + staid staid + staider staider + stain stain + stained stain + staines stain + staineth staineth + staining stain + stainless stainless + stains stain + stair stair + stairs stair + stake stake + stakes stake + stale stale + staled stale + stalk stalk + stalking stalk + stalks stalk + stall stall + stalling stall + stalls stall + stamford stamford + stammer stammer + stamp stamp + stamped stamp + stamps stamp + stanch stanch + stanchless stanchless + stand stand + standard standard + standards standard + stander stander + standers stander + standest standest + standeth standeth + standing stand + stands stand + staniel staniel + stanley stanlei + stanze stanz + stanzo stanzo + stanzos stanzo + staple stapl + staples stapl + star star + stare stare + stared stare + stares stare + staring stare + starings stare + stark stark + starkly starkli + starlight starlight + starling starl + starr starr + starry starri + stars star + start start + started start + starting start + startingly startingli + startle startl + startles startl + starts start + starv starv + starve starv + starved starv + starvelackey starvelackei + starveling starvel + starveth starveth + starving starv + state state + statelier stateli + stately state + states state + statesman statesman + statesmen statesmen + statilius statiliu + station station + statist statist + statists statist + statue statu + statues statu + stature statur + statures statur + statute statut + statutes statut + stave stave + staves stave + stay stai + stayed stai + stayest stayest + staying stai + stays stai + stead stead + steaded stead + steadfast steadfast + steadier steadier + steads stead + steal steal + stealer stealer + stealers stealer + stealing steal + steals steal + stealth stealth + stealthy stealthi + steed steed + steeds steed + steel steel + steeled steel + steely steeli + steep steep + steeped steep + steeple steepl + steeples steepl + steeps steep + steepy steepi + steer steer + steerage steerag + steering steer + steers steer + stelled stell + stem stem + stemming stem + stench stench + step step + stepdame stepdam + stephano stephano + stephen stephen + stepmothers stepmoth + stepp stepp + stepping step + steps step + sterile steril + sterility steril + sterling sterl + stern stern + sternage sternag + sterner sterner + sternest sternest + sternness stern + steterat steterat + stew stew + steward steward + stewards steward + stewardship stewardship + stewed stew + stews stew + stick stick + sticking stick + stickler stickler + sticks stick + stiff stiff + stiffen stiffen + stiffly stiffli + stifle stifl + stifled stifl + stifles stifl + stigmatic stigmat + stigmatical stigmat + stile stile + still still + stiller stiller + stillest stillest + stillness still + stilly stilli + sting sting + stinging sting + stingless stingless + stings sting + stink stink + stinking stink + stinkingly stinkingli + stinks stink + stint stint + stinted stint + stints stint + stir stir + stirr stirr + stirred stir + stirrer stirrer + stirrers stirrer + stirreth stirreth + stirring stir + stirrup stirrup + stirrups stirrup + stirs stir + stitchery stitcheri + stitches stitch + stithied stithi + stithy stithi + stoccadoes stoccado + stoccata stoccata + stock stock + stockfish stockfish + stocking stock + stockings stock + stockish stockish + stocks stock + stog stog + stogs stog + stoics stoic + stokesly stokesli + stol stol + stole stole + stolen stolen + stolest stolest + stomach stomach + stomachers stomach + stomaching stomach + stomachs stomach + ston ston + stone stone + stonecutter stonecutt + stones stone + stonish stonish + stony stoni + stood stood + stool stool + stools stool + stoop stoop + stooping stoop + stoops stoop + stop stop + stope stope + stopp stopp + stopped stop + stopping stop + stops stop + stor stor + store store + storehouse storehous + storehouses storehous + stores store + stories stori + storm storm + stormed storm + storming storm + storms storm + stormy stormi + story stori + stoup stoup + stoups stoup + stout stout + stouter stouter + stoutly stoutli + stoutness stout + stover stover + stow stow + stowage stowag + stowed stow + strachy strachi + stragglers straggler + straggling straggl + straight straight + straightest straightest + straightway straightwai + strain strain + strained strain + straining strain + strains strain + strait strait + straited strait + straiter straiter + straitly straitli + straitness strait + straits strait + strand strand + strange strang + strangely strang + strangeness strang + stranger stranger + strangers stranger + strangest strangest + strangle strangl + strangled strangl + strangler strangler + strangles strangl + strangling strangl + strappado strappado + straps strap + stratagem stratagem + stratagems stratagem + stratford stratford + strato strato + straw straw + strawberries strawberri + strawberry strawberri + straws straw + strawy strawi + stray strai + straying strai + strays strai + streak streak + streaks streak + stream stream + streamers streamer + streaming stream + streams stream + streching strech + street street + streets street + strength strength + strengthen strengthen + strengthened strengthen + strengthless strengthless + strengths strength + stretch stretch + stretched stretch + stretches stretch + stretching stretch + strew strew + strewing strew + strewings strew + strewments strewment + stricken stricken + strict strict + stricter stricter + strictest strictest + strictly strictli + stricture strictur + stride stride + strides stride + striding stride + strife strife + strifes strife + strik strik + strike strike + strikers striker + strikes strike + strikest strikest + striking strike + string string + stringless stringless + strings string + strip strip + stripes stripe + stripling stripl + striplings stripl + stripp stripp + stripping strip + striv striv + strive strive + strives strive + striving strive + strok strok + stroke stroke + strokes stroke + strond strond + stronds strond + strong strong + stronger stronger + strongest strongest + strongly strongli + strooke strook + strossers strosser + strove strove + strown strown + stroy stroi + struck struck + strucken strucken + struggle struggl + struggles struggl + struggling struggl + strumpet strumpet + strumpeted strumpet + strumpets strumpet + strung strung + strut strut + struts strut + strutted strut + strutting strut + stubble stubbl + stubborn stubborn + stubbornest stubbornest + stubbornly stubbornli + stubbornness stubborn + stuck stuck + studded stud + student student + students student + studied studi + studies studi + studious studiou + studiously studious + studs stud + study studi + studying studi + stuff stuff + stuffing stuf + stuffs stuff + stumble stumbl + stumbled stumbl + stumblest stumblest + stumbling stumbl + stump stump + stumps stump + stung stung + stupefy stupefi + stupid stupid + stupified stupifi + stuprum stuprum + sturdy sturdi + sty sty + styga styga + stygian stygian + styl styl + style style + styx styx + su su + sub sub + subcontracted subcontract + subdu subdu + subdue subdu + subdued subdu + subduements subduement + subdues subdu + subduing subdu + subject subject + subjected subject + subjection subject + subjects subject + submerg submerg + submission submiss + submissive submiss + submit submit + submits submit + submitting submit + suborn suborn + subornation suborn + suborned suborn + subscrib subscrib + subscribe subscrib + subscribed subscrib + subscribes subscrib + subscription subscript + subsequent subsequ + subsidies subsidi + subsidy subsidi + subsist subsist + subsisting subsist + substance substanc + substances substanc + substantial substanti + substitute substitut + substituted substitut + substitutes substitut + substitution substitut + subtile subtil + subtilly subtilli + subtle subtl + subtleties subtleti + subtlety subtleti + subtly subtli + subtractors subtractor + suburbs suburb + subversion subvers + subverts subvert + succedant succed + succeed succe + succeeded succeed + succeeders succeed + succeeding succeed + succeeds succe + success success + successantly successantli + successes success + successful success + successfully successfulli + succession success + successive success + successively success + successor successor + successors successor + succour succour + succours succour + such such + suck suck + sucker sucker + suckers sucker + sucking suck + suckle suckl + sucks suck + sudden sudden + suddenly suddenli + sue sue + sued su + suerly suerli + sues sue + sueth sueth + suff suff + suffer suffer + sufferance suffer + sufferances suffer + suffered suffer + suffering suffer + suffers suffer + suffic suffic + suffice suffic + sufficed suffic + suffices suffic + sufficeth sufficeth + sufficiency suffici + sufficient suffici + sufficiently suffici + sufficing suffic + sufficit sufficit + suffigance suffig + suffocate suffoc + suffocating suffoc + suffocation suffoc + suffolk suffolk + suffrage suffrag + suffrages suffrag + sug sug + sugar sugar + sugarsop sugarsop + suggest suggest + suggested suggest + suggesting suggest + suggestion suggest + suggestions suggest + suggests suggest + suis sui + suit suit + suitable suitabl + suited suit + suiting suit + suitor suitor + suitors suitor + suits suit + suivez suivez + sullen sullen + sullens sullen + sullied sulli + sullies sulli + sully sulli + sulph sulph + sulpherous sulpher + sulphur sulphur + sulphurous sulphur + sultan sultan + sultry sultri + sum sum + sumless sumless + summ summ + summa summa + summary summari + summer summer + summers summer + summit summit + summon summon + summoners summon + summons summon + sumpter sumpter + sumptuous sumptuou + sumptuously sumptuous + sums sum + sun sun + sunbeams sunbeam + sunburning sunburn + sunburnt sunburnt + sund sund + sunday sundai + sundays sundai + sunder sunder + sunders sunder + sundry sundri + sung sung + sunk sunk + sunken sunken + sunny sunni + sunrising sunris + suns sun + sunset sunset + sunshine sunshin + sup sup + super super + superficial superfici + superficially superfici + superfluity superflu + superfluous superflu + superfluously superflu + superflux superflux + superior superior + supernal supern + supernatural supernatur + superpraise superprais + superscript superscript + superscription superscript + superserviceable superservic + superstition superstit + superstitious superstiti + superstitiously superstiti + supersubtle supersubtl + supervise supervis + supervisor supervisor + supp supp + supper supper + suppers supper + suppertime suppertim + supping sup + supplant supplant + supple suppl + suppler suppler + suppliance supplianc + suppliant suppliant + suppliants suppliant + supplicant supplic + supplication supplic + supplications supplic + supplie suppli + supplied suppli + supplies suppli + suppliest suppliest + supply suppli + supplyant supplyant + supplying suppli + supplyment supplyment + support support + supportable support + supportance support + supported support + supporter support + supporters support + supporting support + supportor supportor + suppos suppo + supposal suppos + suppose suppos + supposed suppos + supposes suppos + supposest supposest + supposing suppos + supposition supposit + suppress suppress + suppressed suppress + suppresseth suppresseth + supremacy supremaci + supreme suprem + sups sup + sur sur + surance suranc + surcease surceas + surd surd + sure sure + surecard surecard + surely sure + surer surer + surest surest + sureties sureti + surety sureti + surfeit surfeit + surfeited surfeit + surfeiter surfeit + surfeiting surfeit + surfeits surfeit + surge surg + surgeon surgeon + surgeons surgeon + surgere surger + surgery surgeri + surges surg + surly surli + surmis surmi + surmise surmis + surmised surmis + surmises surmis + surmount surmount + surmounted surmount + surmounts surmount + surnam surnam + surname surnam + surnamed surnam + surpasseth surpasseth + surpassing surpass + surplice surplic + surplus surplu + surpris surpri + surprise surpris + surprised surpris + surrender surrend + surrey surrei + surreys surrei + survey survei + surveyest surveyest + surveying survei + surveyor surveyor + surveyors surveyor + surveys survei + survive surviv + survives surviv + survivor survivor + susan susan + suspect suspect + suspected suspect + suspecting suspect + suspects suspect + suspend suspend + suspense suspens + suspicion suspicion + suspicions suspicion + suspicious suspici + suspiration suspir + suspire suspir + sust sust + sustain sustain + sustaining sustain + sutler sutler + sutton sutton + suum suum + swabber swabber + swaddling swaddl + swag swag + swagg swagg + swagger swagger + swaggerer swagger + swaggerers swagger + swaggering swagger + swain swain + swains swain + swallow swallow + swallowed swallow + swallowing swallow + swallows swallow + swam swam + swan swan + swans swan + sward sward + sware sware + swarm swarm + swarming swarm + swart swart + swarth swarth + swarths swarth + swarthy swarthi + swashers swasher + swashing swash + swath swath + swathing swath + swathling swathl + sway swai + swaying swai + sways swai + swear swear + swearer swearer + swearers swearer + swearest swearest + swearing swear + swearings swear + swears swear + sweat sweat + sweaten sweaten + sweating sweat + sweats sweat + sweaty sweati + sweep sweep + sweepers sweeper + sweeps sweep + sweet sweet + sweeten sweeten + sweetens sweeten + sweeter sweeter + sweetest sweetest + sweetheart sweetheart + sweeting sweet + sweetly sweetli + sweetmeats sweetmeat + sweetness sweet + sweets sweet + swell swell + swelling swell + swellings swell + swells swell + swelter swelter + sweno sweno + swept swept + swerve swerv + swerver swerver + swerving swerv + swift swift + swifter swifter + swiftest swiftest + swiftly swiftli + swiftness swift + swill swill + swills swill + swim swim + swimmer swimmer + swimmers swimmer + swimming swim + swims swim + swine swine + swineherds swineherd + swing swing + swinge swing + swinish swinish + swinstead swinstead + switches switch + swits swit + switzers switzer + swol swol + swoll swoll + swoln swoln + swoon swoon + swooned swoon + swooning swoon + swoons swoon + swoop swoop + swoopstake swoopstak + swor swor + sword sword + sworder sworder + swords sword + swore swore + sworn sworn + swounded swound + swounds swound + swum swum + swung swung + sy sy + sycamore sycamor + sycorax sycorax + sylla sylla + syllable syllabl + syllables syllabl + syllogism syllog + symbols symbol + sympathise sympathis + sympathiz sympathiz + sympathize sympath + sympathized sympath + sympathy sympathi + synagogue synagogu + synod synod + synods synod + syracuse syracus + syracusian syracusian + syracusians syracusian + syria syria + syrups syrup + t t + ta ta + taber taber + table tabl + tabled tabl + tables tabl + tablet tablet + tabor tabor + taborer tabor + tabors tabor + tabourines tabourin + taciturnity taciturn + tack tack + tackle tackl + tackled tackl + tackles tackl + tackling tackl + tacklings tackl + taddle taddl + tadpole tadpol + taffeta taffeta + taffety taffeti + tag tag + tagrag tagrag + tah tah + tail tail + tailor tailor + tailors tailor + tails tail + taint taint + tainted taint + tainting taint + taints taint + tainture taintur + tak tak + take take + taken taken + taker taker + takes take + takest takest + taketh taketh + taking take + tal tal + talbot talbot + talbotites talbotit + talbots talbot + tale tale + talent talent + talents talent + taleporter taleport + tales tale + talk talk + talked talk + talker talker + talkers talker + talkest talkest + talking talk + talks talk + tall tall + taller taller + tallest tallest + tallies talli + tallow tallow + tally talli + talons talon + tam tam + tambourines tambourin + tame tame + tamed tame + tamely tame + tameness tame + tamer tamer + tames tame + taming tame + tamora tamora + tamworth tamworth + tan tan + tang tang + tangle tangl + tangled tangl + tank tank + tanlings tanl + tann tann + tanned tan + tanner tanner + tanquam tanquam + tanta tanta + tantaene tantaen + tap tap + tape tape + taper taper + tapers taper + tapestries tapestri + tapestry tapestri + taphouse taphous + tapp tapp + tapster tapster + tapsters tapster + tar tar + tardied tardi + tardily tardili + tardiness tardi + tardy tardi + tarentum tarentum + targe targ + targes targ + target target + targets target + tarpeian tarpeian + tarquin tarquin + tarquins tarquin + tarr tarr + tarre tarr + tarriance tarrianc + tarried tarri + tarries tarri + tarry tarri + tarrying tarri + tart tart + tartar tartar + tartars tartar + tartly tartli + tartness tart + task task + tasker tasker + tasking task + tasks task + tassel tassel + taste tast + tasted tast + tastes tast + tasting tast + tatt tatt + tatter tatter + tattered tatter + tatters tatter + tattle tattl + tattling tattl + tattlings tattl + taught taught + taunt taunt + taunted taunt + taunting taunt + tauntingly tauntingli + taunts taunt + taurus tauru + tavern tavern + taverns tavern + tavy tavi + tawdry tawdri + tawny tawni + tax tax + taxation taxat + taxations taxat + taxes tax + taxing tax + tc tc + te te + teach teach + teacher teacher + teachers teacher + teaches teach + teachest teachest + teacheth teacheth + teaching teach + team team + tear tear + tearful tear + tearing tear + tears tear + tearsheet tearsheet + teat teat + tedious tediou + tediously tedious + tediousness tedious + teem teem + teeming teem + teems teem + teen teen + teeth teeth + teipsum teipsum + telamon telamon + telamonius telamoniu + tell tell + teller teller + telling tell + tells tell + tellus tellu + temp temp + temper temper + temperality temper + temperance temper + temperate temper + temperately temper + tempers temper + tempest tempest + tempests tempest + tempestuous tempestu + temple templ + temples templ + temporal tempor + temporary temporari + temporiz temporiz + temporize tempor + temporizer tempor + temps temp + tempt tempt + temptation temptat + temptations temptat + tempted tempt + tempter tempter + tempters tempter + tempteth tempteth + tempting tempt + tempts tempt + ten ten + tenable tenabl + tenant tenant + tenantius tenantiu + tenantless tenantless + tenants tenant + tench tench + tend tend + tendance tendanc + tended tend + tender tender + tendered tender + tenderly tenderli + tenderness tender + tenders tender + tending tend + tends tend + tenedos tenedo + tenement tenement + tenements tenement + tenfold tenfold + tennis tenni + tenour tenour + tenours tenour + tens ten + tent tent + tented tent + tenth tenth + tenths tenth + tents tent + tenure tenur + tenures tenur + tercel tercel + tereus tereu + term term + termagant termag + termed term + terminations termin + termless termless + terms term + terra terra + terrace terrac + terram terram + terras terra + terre terr + terrene terren + terrestrial terrestri + terrible terribl + terribly terribl + territories territori + territory territori + terror terror + terrors terror + tertian tertian + tertio tertio + test test + testament testament + tested test + tester tester + testern testern + testify testifi + testimonied testimoni + testimonies testimoni + testimony testimoni + testiness testi + testril testril + testy testi + tetchy tetchi + tether tether + tetter tetter + tevil tevil + tewksbury tewksburi + text text + tgv tgv + th th + thaes thae + thames thame + than than + thane thane + thanes thane + thank thank + thanked thank + thankful thank + thankfully thankfulli + thankfulness thank + thanking thank + thankings thank + thankless thankless + thanks thank + thanksgiving thanksgiv + thasos thaso + that that + thatch thatch + thaw thaw + thawing thaw + thaws thaw + the the + theatre theatr + theban theban + thebes thebe + thee thee + theft theft + thefts theft + thein thein + their their + theirs their + theise theis + them them + theme theme + themes theme + themselves themselv + then then + thence thenc + thenceforth thenceforth + theoric theoric + there there + thereabout thereabout + thereabouts thereabout + thereafter thereaft + thereat thereat + thereby therebi + therefore therefor + therein therein + thereof thereof + thereon thereon + thereto thereto + thereunto thereunto + thereupon thereupon + therewith therewith + therewithal therewith + thersites thersit + these these + theseus theseu + thessalian thessalian + thessaly thessali + thetis theti + thews thew + they thei + thick thick + thicken thicken + thickens thicken + thicker thicker + thickest thickest + thicket thicket + thickskin thickskin + thief thief + thievery thieveri + thieves thiev + thievish thievish + thigh thigh + thighs thigh + thimble thimbl + thimbles thimbl + thin thin + thine thine + thing thing + things thing + think think + thinkest thinkest + thinking think + thinkings think + thinks think + thinkst thinkst + thinly thinli + third third + thirdly thirdli + thirds third + thirst thirst + thirsting thirst + thirsts thirst + thirsty thirsti + thirteen thirteen + thirties thirti + thirtieth thirtieth + thirty thirti + this thi + thisby thisbi + thisne thisn + thistle thistl + thistles thistl + thither thither + thitherward thitherward + thoas thoa + thomas thoma + thorn thorn + thorns thorn + thorny thorni + thorough thorough + thoroughly thoroughli + those those + thou thou + though though + thought thought + thoughtful thought + thoughts thought + thousand thousand + thousands thousand + thracian thracian + thraldom thraldom + thrall thrall + thralled thrall + thralls thrall + thrash thrash + thrasonical thrason + thread thread + threadbare threadbar + threaden threaden + threading thread + threat threat + threaten threaten + threatening threaten + threatens threaten + threatest threatest + threats threat + three three + threefold threefold + threepence threepenc + threepile threepil + threes three + threescore threescor + thresher thresher + threshold threshold + threw threw + thrice thrice + thrift thrift + thriftless thriftless + thrifts thrift + thrifty thrifti + thrill thrill + thrilling thrill + thrills thrill + thrive thrive + thrived thrive + thrivers thriver + thrives thrive + thriving thrive + throat throat + throats throat + throbbing throb + throbs throb + throca throca + throe throe + throes throe + thromuldo thromuldo + thron thron + throne throne + throned throne + thrones throne + throng throng + thronging throng + throngs throng + throstle throstl + throttle throttl + through through + throughfare throughfar + throughfares throughfar + throughly throughli + throughout throughout + throw throw + thrower thrower + throwest throwest + throwing throw + thrown thrown + throws throw + thrum thrum + thrumm thrumm + thrush thrush + thrust thrust + thrusteth thrusteth + thrusting thrust + thrusts thrust + thumb thumb + thumbs thumb + thump thump + thund thund + thunder thunder + thunderbolt thunderbolt + thunderbolts thunderbolt + thunderer thunder + thunders thunder + thunderstone thunderston + thunderstroke thunderstrok + thurio thurio + thursday thursdai + thus thu + thwack thwack + thwart thwart + thwarted thwart + thwarting thwart + thwartings thwart + thy thy + thyme thyme + thymus thymu + thyreus thyreu + thyself thyself + ti ti + tib tib + tiber tiber + tiberio tiberio + tibey tibei + ticed tice + tick tick + tickl tickl + tickle tickl + tickled tickl + tickles tickl + tickling tickl + ticklish ticklish + tiddle tiddl + tide tide + tides tide + tidings tide + tidy tidi + tie tie + tied ti + ties ti + tiff tiff + tiger tiger + tigers tiger + tight tight + tightly tightli + tike tike + til til + tile tile + till till + tillage tillag + tilly tilli + tilt tilt + tilter tilter + tilth tilth + tilting tilt + tilts tilt + tiltyard tiltyard + tim tim + timandra timandra + timber timber + time time + timeless timeless + timelier timeli + timely time + times time + timon timon + timor timor + timorous timor + timorously timor + tinct tinct + tincture tinctur + tinctures tinctur + tinder tinder + tingling tingl + tinker tinker + tinkers tinker + tinsel tinsel + tiny tini + tip tip + tipp tipp + tippling tippl + tips tip + tipsy tipsi + tiptoe tipto + tir tir + tire tire + tired tire + tires tire + tirest tirest + tiring tire + tirra tirra + tirrits tirrit + tis ti + tish tish + tisick tisick + tissue tissu + titan titan + titania titania + tithe tith + tithed tith + tithing tith + titinius titiniu + title titl + titled titl + titleless titleless + titles titl + tittle tittl + tittles tittl + titular titular + titus titu + tn tn + to to + toad toad + toads toad + toadstool toadstool + toast toast + toasted toast + toasting toast + toasts toast + toaze toaz + toby tobi + tock tock + tod tod + today todai + todpole todpol + tods tod + toe toe + toes toe + tofore tofor + toge toge + toged toge + together togeth + toil toil + toiled toil + toiling toil + toils toil + token token + tokens token + told told + toledo toledo + tolerable toler + toll toll + tolling toll + tom tom + tomb tomb + tombe tomb + tombed tomb + tombless tombless + tomboys tomboi + tombs tomb + tomorrow tomorrow + tomyris tomyri + ton ton + tongs tong + tongu tongu + tongue tongu + tongued tongu + tongueless tongueless + tongues tongu + tonight tonight + too too + took took + tool tool + tools tool + tooth tooth + toothache toothach + toothpick toothpick + toothpicker toothpick + top top + topas topa + topful top + topgallant topgal + topless topless + topmast topmast + topp topp + topping top + topple toppl + topples toppl + tops top + topsail topsail + topsy topsi + torch torch + torchbearer torchbear + torchbearers torchbear + torcher torcher + torches torch + torchlight torchlight + tore tore + torment torment + tormenta tormenta + tormente torment + tormented torment + tormenting torment + tormentors tormentor + torments torment + torn torn + torrent torrent + tortive tortiv + tortoise tortois + tortur tortur + torture tortur + tortured tortur + torturer tortur + torturers tortur + tortures tortur + torturest torturest + torturing tortur + toryne toryn + toss toss + tossed toss + tosseth tosseth + tossing toss + tot tot + total total + totally total + tott tott + tottered totter + totters totter + tou tou + touch touch + touched touch + touches touch + toucheth toucheth + touching touch + touchstone touchston + tough tough + tougher tougher + toughness tough + touraine tourain + tournaments tournament + tours tour + tous tou + tout tout + touze touz + tow tow + toward toward + towardly towardli + towards toward + tower tower + towering tower + towers tower + town town + towns town + township township + townsman townsman + townsmen townsmen + towton towton + toy toi + toys toi + trace trace + traces trace + track track + tract tract + tractable tractabl + trade trade + traded trade + traders trader + trades trade + tradesman tradesman + tradesmen tradesmen + trading trade + tradition tradit + traditional tradit + traduc traduc + traduced traduc + traducement traduc + traffic traffic + traffickers traffick + traffics traffic + tragedian tragedian + tragedians tragedian + tragedies tragedi + tragedy tragedi + tragic tragic + tragical tragic + trail trail + train train + trained train + training train + trains train + trait trait + traitor traitor + traitorly traitorli + traitorous traitor + traitorously traitor + traitors traitor + traitress traitress + traject traject + trammel trammel + trample trampl + trampled trampl + trampling trampl + tranc tranc + trance tranc + tranio tranio + tranquil tranquil + tranquillity tranquil + transcendence transcend + transcends transcend + transferred transfer + transfigur transfigur + transfix transfix + transform transform + transformation transform + transformations transform + transformed transform + transgress transgress + transgresses transgress + transgressing transgress + transgression transgress + translate translat + translated translat + translates translat + translation translat + transmigrates transmigr + transmutation transmut + transparent transpar + transport transport + transportance transport + transported transport + transporting transport + transports transport + transpose transpos + transshape transshap + trap trap + trapp trapp + trappings trap + traps trap + trash trash + travail travail + travails travail + travel travel + traveler travel + traveling travel + travell travel + travelled travel + traveller travel + travellers travel + travellest travellest + travelling travel + travels travel + travers traver + traverse travers + tray trai + treacherous treacher + treacherously treacher + treachers treacher + treachery treacheri + tread tread + treading tread + treads tread + treason treason + treasonable treason + treasonous treason + treasons treason + treasure treasur + treasurer treasur + treasures treasur + treasuries treasuri + treasury treasuri + treat treat + treaties treati + treatise treatis + treats treat + treaty treati + treble trebl + trebled trebl + trebles trebl + trebonius treboniu + tree tree + trees tree + tremble trembl + trembled trembl + trembles trembl + tremblest tremblest + trembling trembl + tremblingly tremblingli + tremor tremor + trempling trempl + trench trench + trenchant trenchant + trenched trench + trencher trencher + trenchering trencher + trencherman trencherman + trenchers trencher + trenches trench + trenching trench + trent trent + tres tre + trespass trespass + trespasses trespass + tressel tressel + tresses tress + treys trei + trial trial + trials trial + trib trib + tribe tribe + tribes tribe + tribulation tribul + tribunal tribun + tribune tribun + tribunes tribun + tributaries tributari + tributary tributari + tribute tribut + tributes tribut + trice trice + trick trick + tricking trick + trickling trickl + tricks trick + tricksy tricksi + trident trident + tried tri + trier trier + trifle trifl + trifled trifl + trifler trifler + trifles trifl + trifling trifl + trigon trigon + trill trill + trim trim + trimly trimli + trimm trimm + trimmed trim + trimming trim + trims trim + trinculo trinculo + trinculos trinculo + trinkets trinket + trip trip + tripartite tripartit + tripe tripe + triple tripl + triplex triplex + tripoli tripoli + tripolis tripoli + tripp tripp + tripping trip + trippingly trippingli + trips trip + tristful trist + triton triton + triumph triumph + triumphant triumphant + triumphantly triumphantli + triumpher triumpher + triumphers triumpher + triumphing triumph + triumphs triumph + triumvir triumvir + triumvirate triumvir + triumvirs triumvir + triumviry triumviri + trivial trivial + troat troat + trod trod + trodden trodden + troiant troiant + troien troien + troilus troilu + troiluses troilus + trojan trojan + trojans trojan + troll troll + tromperies tromperi + trompet trompet + troop troop + trooping troop + troops troop + trop trop + trophies trophi + trophy trophi + tropically tropic + trot trot + troth troth + trothed troth + troths troth + trots trot + trotting trot + trouble troubl + troubled troubl + troubler troubler + troubles troubl + troublesome troublesom + troublest troublest + troublous troublou + trough trough + trout trout + trouts trout + trovato trovato + trow trow + trowel trowel + trowest trowest + troy troi + troyan troyan + troyans troyan + truant truant + truce truce + truckle truckl + trudge trudg + true true + trueborn trueborn + truepenny truepenni + truer truer + truest truest + truie truie + trull trull + trulls trull + truly truli + trump trump + trumpery trumperi + trumpet trumpet + trumpeter trumpet + trumpeters trumpet + trumpets trumpet + truncheon truncheon + truncheoners truncheon + trundle trundl + trunk trunk + trunks trunk + trust trust + trusted trust + truster truster + trusters truster + trusting trust + trusts trust + trusty trusti + truth truth + truths truth + try try + ts ts + tu tu + tuae tuae + tub tub + tubal tubal + tubs tub + tuck tuck + tucket tucket + tuesday tuesdai + tuft tuft + tufts tuft + tug tug + tugg tugg + tugging tug + tuition tuition + tullus tullu + tully tulli + tumble tumbl + tumbled tumbl + tumbler tumbler + tumbling tumbl + tumult tumult + tumultuous tumultu + tun tun + tune tune + tuneable tuneabl + tuned tune + tuners tuner + tunes tune + tunis tuni + tuns tun + tupping tup + turban turban + turbans turban + turbulence turbul + turbulent turbul + turd turd + turf turf + turfy turfi + turk turk + turkey turkei + turkeys turkei + turkish turkish + turks turk + turlygod turlygod + turmoil turmoil + turmoiled turmoil + turn turn + turnbull turnbul + turncoat turncoat + turncoats turncoat + turned turn + turneth turneth + turning turn + turnips turnip + turns turn + turph turph + turpitude turpitud + turquoise turquois + turret turret + turrets turret + turtle turtl + turtles turtl + turvy turvi + tuscan tuscan + tush tush + tut tut + tutor tutor + tutored tutor + tutors tutor + tutto tutto + twain twain + twang twang + twangling twangl + twas twa + tway twai + tweaks tweak + tween tween + twelfth twelfth + twelve twelv + twelvemonth twelvemonth + twentieth twentieth + twenty twenti + twere twere + twice twice + twig twig + twiggen twiggen + twigs twig + twilight twilight + twill twill + twilled twill + twin twin + twine twine + twink twink + twinkle twinkl + twinkled twinkl + twinkling twinkl + twinn twinn + twins twin + twire twire + twist twist + twisted twist + twit twit + twits twit + twitting twit + twixt twixt + two two + twofold twofold + twopence twopenc + twopences twopenc + twos two + twould twould + tyb tyb + tybalt tybalt + tybalts tybalt + tyburn tyburn + tying ty + tyke tyke + tymbria tymbria + type type + types type + typhon typhon + tyrannical tyrann + tyrannically tyrann + tyrannize tyrann + tyrannous tyrann + tyranny tyranni + tyrant tyrant + tyrants tyrant + tyrian tyrian + tyrrel tyrrel + u u + ubique ubiqu + udders udder + udge udg + uds ud + uglier uglier + ugliest ugliest + ugly ugli + ulcer ulcer + ulcerous ulcer + ulysses ulyss + um um + umber umber + umbra umbra + umbrage umbrag + umfrevile umfrevil + umpire umpir + umpires umpir + un un + unable unabl + unaccommodated unaccommod + unaccompanied unaccompani + unaccustom unaccustom + unaching unach + unacquainted unacquaint + unactive unact + unadvis unadvi + unadvised unadvis + unadvisedly unadvisedli + unagreeable unagre + unanel unanel + unanswer unansw + unappeas unappea + unapproved unapprov + unapt unapt + unaptness unapt + unarm unarm + unarmed unarm + unarms unarm + unassail unassail + unassailable unassail + unattainted unattaint + unattempted unattempt + unattended unattend + unauspicious unauspici + unauthorized unauthor + unavoided unavoid + unawares unawar + unback unback + unbak unbak + unbanded unband + unbar unbar + unbarb unbarb + unbashful unbash + unbated unbat + unbatter unbatt + unbecoming unbecom + unbefitting unbefit + unbegot unbegot + unbegotten unbegotten + unbelieved unbeliev + unbend unbend + unbent unbent + unbewail unbewail + unbid unbid + unbidden unbidden + unbind unbind + unbinds unbind + unbitted unbit + unbless unbless + unblest unblest + unbloodied unbloodi + unblown unblown + unbodied unbodi + unbolt unbolt + unbolted unbolt + unbonneted unbonnet + unbookish unbookish + unborn unborn + unbosom unbosom + unbound unbound + unbounded unbound + unbow unbow + unbowed unbow + unbrac unbrac + unbraced unbrac + unbraided unbraid + unbreathed unbreath + unbred unbr + unbreech unbreech + unbridled unbridl + unbroke unbrok + unbruis unbrui + unbruised unbruis + unbuckle unbuckl + unbuckles unbuckl + unbuckling unbuckl + unbuild unbuild + unburden unburden + unburdens unburden + unburied unburi + unburnt unburnt + unburthen unburthen + unbutton unbutton + unbuttoning unbutton + uncapable uncap + uncape uncap + uncase uncas + uncasing uncas + uncaught uncaught + uncertain uncertain + uncertainty uncertainti + unchain unchain + unchanging unchang + uncharge uncharg + uncharged uncharg + uncharitably uncharit + unchary unchari + unchaste unchast + uncheck uncheck + unchilded unchild + uncivil uncivil + unclaim unclaim + unclasp unclasp + uncle uncl + unclean unclean + uncleanliness uncleanli + uncleanly uncleanli + uncleanness unclean + uncles uncl + unclew unclew + unclog unclog + uncoined uncoin + uncolted uncolt + uncomeliness uncomeli + uncomfortable uncomfort + uncompassionate uncompassion + uncomprehensive uncomprehens + unconfinable unconfin + unconfirm unconfirm + unconfirmed unconfirm + unconquer unconqu + unconquered unconqu + unconsidered unconsid + unconstant unconst + unconstrain unconstrain + unconstrained unconstrain + uncontemn uncontemn + uncontroll uncontrol + uncorrected uncorrect + uncounted uncount + uncouple uncoupl + uncourteous uncourt + uncouth uncouth + uncover uncov + uncovered uncov + uncropped uncrop + uncross uncross + uncrown uncrown + unction unction + unctuous unctuou + uncuckolded uncuckold + uncurable uncur + uncurbable uncurb + uncurbed uncurb + uncurls uncurl + uncurrent uncurr + uncurse uncurs + undaunted undaunt + undeaf undeaf + undeck undeck + undeeded undeed + under under + underbearing underbear + underborne underborn + undercrest undercrest + underfoot underfoot + undergo undergo + undergoes undergo + undergoing undergo + undergone undergon + underground underground + underhand underhand + underlings underl + undermine undermin + underminers undermin + underneath underneath + underprizing underpr + underprop underprop + understand understand + understandeth understandeth + understanding understand + understandings understand + understands understand + understood understood + underta underta + undertake undertak + undertakeing undertak + undertaker undertak + undertakes undertak + undertaking undertak + undertakings undertak + undertook undertook + undervalu undervalu + undervalued undervalu + underwent underw + underwrit underwrit + underwrite underwrit + undescried undescri + undeserved undeserv + undeserver undeserv + undeservers undeserv + undeserving undeserv + undetermin undetermin + undid undid + undinted undint + undiscernible undiscern + undiscover undiscov + undishonoured undishonour + undispos undispo + undistinguishable undistinguish + undistinguished undistinguish + undividable undivid + undivided undivid + undivulged undivulg + undo undo + undoes undo + undoing undo + undone undon + undoubted undoubt + undoubtedly undoubtedli + undream undream + undress undress + undressed undress + undrown undrown + unduteous undut + undutiful unduti + une un + uneared unear + unearned unearn + unearthly unearthli + uneasines uneasin + uneasy uneasi + uneath uneath + uneducated uneduc + uneffectual uneffectu + unelected unelect + unequal unequ + uneven uneven + unexamin unexamin + unexecuted unexecut + unexpected unexpect + unexperienc unexperienc + unexperient unexperi + unexpressive unexpress + unfair unfair + unfaithful unfaith + unfallible unfal + unfam unfam + unfashionable unfashion + unfasten unfasten + unfather unfath + unfathered unfath + unfed unf + unfeed unfe + unfeeling unfeel + unfeigned unfeign + unfeignedly unfeignedli + unfellowed unfellow + unfelt unfelt + unfenced unfenc + unfilial unfili + unfill unfil + unfinish unfinish + unfirm unfirm + unfit unfit + unfitness unfit + unfix unfix + unfledg unfledg + unfold unfold + unfolded unfold + unfoldeth unfoldeth + unfolding unfold + unfolds unfold + unfool unfool + unforc unforc + unforced unforc + unforfeited unforfeit + unfortified unfortifi + unfortunate unfortun + unfought unfought + unfrequented unfrequ + unfriended unfriend + unfurnish unfurnish + ungain ungain + ungalled ungal + ungart ungart + ungarter ungart + ungenitur ungenitur + ungentle ungentl + ungentleness ungentl + ungently ungent + ungird ungird + ungodly ungodli + ungor ungor + ungot ungot + ungotten ungotten + ungovern ungovern + ungracious ungraci + ungrateful ungrat + ungravely ungrav + ungrown ungrown + unguarded unguard + unguem unguem + unguided unguid + unhack unhack + unhair unhair + unhallow unhallow + unhallowed unhallow + unhand unhand + unhandled unhandl + unhandsome unhandsom + unhang unhang + unhappied unhappi + unhappily unhappili + unhappiness unhappi + unhappy unhappi + unhardened unharden + unharm unharm + unhatch unhatch + unheard unheard + unhearts unheart + unheedful unheed + unheedfully unheedfulli + unheedy unheedi + unhelpful unhelp + unhidden unhidden + unholy unholi + unhop unhop + unhopefullest unhopefullest + unhorse unhors + unhospitable unhospit + unhous unhou + unhoused unhous + unhurtful unhurt + unicorn unicorn + unicorns unicorn + unimproved unimprov + uninhabitable uninhabit + uninhabited uninhabit + unintelligent unintellig + union union + unions union + unite unit + united unit + unity uniti + universal univers + universe univers + universities univers + university univers + unjointed unjoint + unjust unjust + unjustice unjustic + unjustly unjustli + unkennel unkennel + unkept unkept + unkind unkind + unkindest unkindest + unkindly unkindli + unkindness unkind + unking unk + unkinglike unkinglik + unkiss unkiss + unknit unknit + unknowing unknow + unknown unknown + unlace unlac + unlaid unlaid + unlawful unlaw + unlawfully unlawfulli + unlearn unlearn + unlearned unlearn + unless unless + unlesson unlesson + unletter unlett + unlettered unlett + unlick unlick + unlike unlik + unlikely unlik + unlimited unlimit + unlineal unlin + unlink unlink + unload unload + unloaded unload + unloading unload + unloads unload + unlock unlock + unlocks unlock + unlook unlook + unlooked unlook + unloos unloo + unloose unloos + unlov unlov + unloving unlov + unluckily unluckili + unlucky unlucki + unmade unmad + unmake unmak + unmanly unmanli + unmann unmann + unmanner unmann + unmannerd unmannerd + unmannerly unmannerli + unmarried unmarri + unmask unmask + unmasked unmask + unmasking unmask + unmasks unmask + unmast unmast + unmatch unmatch + unmatchable unmatch + unmatched unmatch + unmeasurable unmeasur + unmeet unmeet + unmellowed unmellow + unmerciful unmerci + unmeritable unmerit + unmeriting unmerit + unminded unmind + unmindfull unmindful + unmingled unmingl + unmitigable unmitig + unmitigated unmitig + unmix unmix + unmoan unmoan + unmov unmov + unmoved unmov + unmoving unmov + unmuffles unmuffl + unmuffling unmuffl + unmusical unmus + unmuzzle unmuzzl + unmuzzled unmuzzl + unnatural unnatur + unnaturally unnatur + unnaturalness unnatur + unnecessarily unnecessarili + unnecessary unnecessari + unneighbourly unneighbourli + unnerved unnerv + unnoble unnobl + unnoted unnot + unnumb unnumb + unnumber unnumb + unowed unow + unpack unpack + unpaid unpaid + unparagon unparagon + unparallel unparallel + unpartial unparti + unpath unpath + unpaved unpav + unpay unpai + unpeaceable unpeac + unpeg unpeg + unpeople unpeopl + unpeopled unpeopl + unperfect unperfect + unperfectness unperfect + unpick unpick + unpin unpin + unpink unpink + unpitied unpiti + unpitifully unpitifulli + unplagu unplagu + unplausive unplaus + unpleas unplea + unpleasant unpleas + unpleasing unpleas + unpolicied unpolici + unpolish unpolish + unpolished unpolish + unpolluted unpollut + unpossess unpossess + unpossessing unpossess + unpossible unposs + unpractis unpracti + unpregnant unpregn + unpremeditated unpremedit + unprepar unprepar + unprepared unprepar + unpress unpress + unprevailing unprevail + unprevented unprev + unpriz unpriz + unprizable unpriz + unprofitable unprofit + unprofited unprofit + unproper unprop + unproperly unproperli + unproportion unproport + unprovide unprovid + unprovided unprovid + unprovident unprovid + unprovokes unprovok + unprun unprun + unpruned unprun + unpublish unpublish + unpurged unpurg + unpurpos unpurpo + unqualitied unqual + unqueen unqueen + unquestion unquest + unquestionable unquestion + unquiet unquiet + unquietly unquietli + unquietness unquiet + unraised unrais + unrak unrak + unread unread + unready unreadi + unreal unreal + unreasonable unreason + unreasonably unreason + unreclaimed unreclaim + unreconciled unreconcil + unreconciliable unreconcili + unrecounted unrecount + unrecuring unrecur + unregarded unregard + unregist unregist + unrelenting unrel + unremovable unremov + unremovably unremov + unreprievable unrepriev + unresolv unresolv + unrespected unrespect + unrespective unrespect + unrest unrest + unrestor unrestor + unrestrained unrestrain + unreveng unreveng + unreverend unreverend + unreverent unrever + unrevers unrev + unrewarded unreward + unrighteous unright + unrightful unright + unripe unrip + unripp unripp + unrivall unrival + unroll unrol + unroof unroof + unroosted unroost + unroot unroot + unrough unrough + unruly unruli + unsafe unsaf + unsaluted unsalut + unsanctified unsanctifi + unsatisfied unsatisfi + unsavoury unsavouri + unsay unsai + unscalable unscal + unscann unscann + unscarr unscarr + unschool unschool + unscorch unscorch + unscour unscour + unscratch unscratch + unseal unseal + unseam unseam + unsearch unsearch + unseason unseason + unseasonable unseason + unseasonably unseason + unseasoned unseason + unseconded unsecond + unsecret unsecret + unseduc unseduc + unseeing unse + unseeming unseem + unseemly unseemli + unseen unseen + unseminar unseminar + unseparable unsepar + unserviceable unservic + unset unset + unsettle unsettl + unsettled unsettl + unsever unsev + unsex unsex + unshak unshak + unshaked unshak + unshaken unshaken + unshaped unshap + unshapes unshap + unsheath unsheath + unsheathe unsheath + unshorn unshorn + unshout unshout + unshown unshown + unshrinking unshrink + unshrubb unshrubb + unshunn unshunn + unshunnable unshunn + unsifted unsift + unsightly unsightli + unsinew unsinew + unsisting unsist + unskilful unskil + unskilfully unskilfulli + unskillful unskil + unslipping unslip + unsmirched unsmirch + unsoil unsoil + unsolicited unsolicit + unsorted unsort + unsought unsought + unsound unsound + unsounded unsound + unspeak unspeak + unspeakable unspeak + unspeaking unspeak + unsphere unspher + unspoke unspok + unspoken unspoken + unspotted unspot + unsquar unsquar + unstable unstabl + unstaid unstaid + unstain unstain + unstained unstain + unstanched unstanch + unstate unstat + unsteadfast unsteadfast + unstooping unstoop + unstringed unstring + unstuff unstuff + unsubstantial unsubstanti + unsuitable unsuit + unsuiting unsuit + unsullied unsulli + unsunn unsunn + unsur unsur + unsure unsur + unsuspected unsuspect + unsway unswai + unswayable unsway + unswayed unswai + unswear unswear + unswept unswept + unsworn unsworn + untainted untaint + untalk untalk + untangle untangl + untangled untangl + untasted untast + untaught untaught + untempering untemp + untender untend + untent untent + untented untent + unthankful unthank + unthankfulness unthank + unthink unthink + unthought unthought + unthread unthread + unthrift unthrift + unthrifts unthrift + unthrifty unthrifti + untie unti + untied unti + until until + untimber untimb + untimely untim + untir untir + untirable untir + untired untir + untitled untitl + unto unto + untold untold + untouch untouch + untoward untoward + untowardly untowardli + untraded untrad + untrain untrain + untrained untrain + untread untread + untreasur untreasur + untried untri + untrimmed untrim + untrod untrod + untrodden untrodden + untroubled untroubl + untrue untru + untrussing untruss + untruth untruth + untruths untruth + untucked untuck + untun untun + untune untun + untuneable untun + untutor untutor + untutored untutor + untwine untwin + unurg unurg + unus unu + unused unus + unusual unusu + unvalued unvalu + unvanquish unvanquish + unvarnish unvarnish + unveil unveil + unveiling unveil + unvenerable unvener + unvex unvex + unviolated unviol + unvirtuous unvirtu + unvisited unvisit + unvulnerable unvulner + unwares unwar + unwarily unwarili + unwash unwash + unwatch unwatch + unwearied unweari + unwed unw + unwedgeable unwedg + unweeded unweed + unweighed unweigh + unweighing unweigh + unwelcome unwelcom + unwept unwept + unwhipp unwhipp + unwholesome unwholesom + unwieldy unwieldi + unwilling unwil + unwillingly unwillingli + unwillingness unwilling + unwind unwind + unwiped unwip + unwise unwis + unwisely unwis + unwish unwish + unwished unwish + unwitted unwit + unwittingly unwittingli + unwonted unwont + unwooed unwoo + unworthier unworthi + unworthiest unworthiest + unworthily unworthili + unworthiness unworthi + unworthy unworthi + unwrung unwrung + unyok unyok + unyoke unyok + up up + upbraid upbraid + upbraided upbraid + upbraidings upbraid + upbraids upbraid + uphoarded uphoard + uphold uphold + upholdeth upholdeth + upholding uphold + upholds uphold + uplift uplift + uplifted uplift + upmost upmost + upon upon + upper upper + uprear uprear + upreared uprear + upright upright + uprighteously upright + uprightness upright + uprise upris + uprising upris + uproar uproar + uproars uproar + uprous uprou + upshoot upshoot + upshot upshot + upside upsid + upspring upspr + upstairs upstair + upstart upstart + upturned upturn + upward upward + upwards upward + urchin urchin + urchinfield urchinfield + urchins urchin + urg urg + urge urg + urged urg + urgent urgent + urges urg + urgest urgest + urging urg + urinal urin + urinals urin + urine urin + urn urn + urns urn + urs ur + ursa ursa + ursley urslei + ursula ursula + urswick urswick + us us + usage usag + usance usanc + usances usanc + use us + used us + useful us + useless useless + user user + uses us + usest usest + useth useth + usher usher + ushered usher + ushering usher + ushers usher + using us + usual usual + usually usual + usurer usur + usurers usur + usuries usuri + usuring usur + usurp usurp + usurpation usurp + usurped usurp + usurper usurp + usurpers usurp + usurping usurp + usurpingly usurpingli + usurps usurp + usury usuri + ut ut + utensil utensil + utensils utensil + utility util + utmost utmost + utt utt + utter utter + utterance utter + uttered utter + uttereth uttereth + uttering utter + utterly utterli + uttermost uttermost + utters utter + uy uy + v v + va va + vacancy vacanc + vacant vacant + vacation vacat + vade vade + vagabond vagabond + vagabonds vagabond + vagram vagram + vagrom vagrom + vail vail + vailed vail + vailing vail + vaillant vaillant + vain vain + vainer vainer + vainglory vainglori + vainly vainli + vainness vain + vais vai + valanc valanc + valance valanc + vale vale + valence valenc + valentine valentin + valentinus valentinu + valentio valentio + valeria valeria + valerius valeriu + vales vale + valiant valiant + valiantly valiantli + valiantness valiant + validity valid + vallant vallant + valley vallei + valleys vallei + vally valli + valor valor + valorous valor + valorously valor + valour valour + valu valu + valuation valuat + value valu + valued valu + valueless valueless + values valu + valuing valu + vane vane + vanish vanish + vanished vanish + vanishes vanish + vanishest vanishest + vanishing vanish + vanities vaniti + vanity vaniti + vanquish vanquish + vanquished vanquish + vanquisher vanquish + vanquishest vanquishest + vanquisheth vanquisheth + vant vant + vantage vantag + vantages vantag + vantbrace vantbrac + vapians vapian + vapor vapor + vaporous vapor + vapour vapour + vapours vapour + vara vara + variable variabl + variance varianc + variation variat + variations variat + varied vari + variest variest + variety varieti + varld varld + varlet varlet + varletry varletri + varlets varlet + varletto varletto + varnish varnish + varrius varriu + varro varro + vary vari + varying vari + vassal vassal + vassalage vassalag + vassals vassal + vast vast + vastidity vastid + vasty vasti + vat vat + vater vater + vaudemont vaudemont + vaughan vaughan + vault vault + vaultages vaultag + vaulted vault + vaulting vault + vaults vault + vaulty vaulti + vaumond vaumond + vaunt vaunt + vaunted vaunt + vaunter vaunter + vaunting vaunt + vauntingly vauntingli + vaunts vaunt + vauvado vauvado + vaux vaux + vaward vaward + ve ve + veal veal + vede vede + vehemence vehem + vehemency vehem + vehement vehement + vehor vehor + veil veil + veiled veil + veiling veil + vein vein + veins vein + vell vell + velure velur + velutus velutu + velvet velvet + vendible vendibl + venerable vener + venereal vener + venetia venetia + venetian venetian + venetians venetian + veneys venei + venge veng + vengeance vengeanc + vengeances vengeanc + vengeful veng + veni veni + venial venial + venice venic + venison venison + venit venit + venom venom + venomous venom + venomously venom + vent vent + ventages ventag + vented vent + ventidius ventidiu + ventricle ventricl + vents vent + ventur ventur + venture ventur + ventured ventur + ventures ventur + venturing ventur + venturous ventur + venue venu + venus venu + venuto venuto + ver ver + verb verb + verba verba + verbal verbal + verbatim verbatim + verbosity verbos + verdict verdict + verdun verdun + verdure verdur + vere vere + verefore verefor + verg verg + verge verg + vergers verger + verges verg + verier verier + veriest veriest + verified verifi + verify verifi + verily verili + veritable verit + verite verit + verities veriti + verity veriti + vermilion vermilion + vermin vermin + vernon vernon + verona verona + veronesa veronesa + versal versal + verse vers + verses vers + versing vers + vert vert + very veri + vesper vesper + vessel vessel + vessels vessel + vestal vestal + vestments vestment + vesture vestur + vetch vetch + vetches vetch + veux veux + vex vex + vexation vexat + vexations vexat + vexed vex + vexes vex + vexest vexest + vexeth vexeth + vexing vex + vi vi + via via + vial vial + vials vial + viand viand + viands viand + vic vic + vicar vicar + vice vice + vicegerent viceger + vicentio vicentio + viceroy viceroi + viceroys viceroi + vices vice + vici vici + vicious viciou + viciousness vicious + vict vict + victims victim + victor victor + victoress victoress + victories victori + victorious victori + victors victor + victory victori + victual victual + victuall victual + victuals victual + videlicet videlicet + video video + vides vide + videsne videsn + vidi vidi + vie vie + vied vi + vienna vienna + view view + viewest viewest + vieweth vieweth + viewing view + viewless viewless + views view + vigil vigil + vigilance vigil + vigilant vigil + vigitant vigit + vigour vigour + vii vii + viii viii + vile vile + vilely vile + vileness vile + viler viler + vilest vilest + vill vill + village villag + villager villag + villagery villageri + villages villag + villain villain + villainies villaini + villainous villain + villainously villain + villains villain + villainy villaini + villanies villani + villanous villan + villany villani + villiago villiago + villian villian + villianda villianda + villians villian + vinaigre vinaigr + vincentio vincentio + vincere vincer + vindicative vindic + vine vine + vinegar vinegar + vines vine + vineyard vineyard + vineyards vineyard + vint vint + vintner vintner + viol viol + viola viola + violate violat + violated violat + violates violat + violation violat + violator violat + violence violenc + violent violent + violenta violenta + violenteth violenteth + violently violent + violet violet + violets violet + viper viper + viperous viper + vipers viper + vir vir + virgilia virgilia + virgin virgin + virginal virgin + virginalling virginal + virginity virgin + virginius virginiu + virgins virgin + virgo virgo + virtue virtu + virtues virtu + virtuous virtuou + virtuously virtuous + visag visag + visage visag + visages visag + visard visard + viscount viscount + visible visibl + visibly visibl + vision vision + visions vision + visit visit + visitation visit + visitations visit + visited visit + visiting visit + visitings visit + visitor visitor + visitors visitor + visits visit + visor visor + vita vita + vitae vita + vital vital + vitement vitement + vitruvio vitruvio + vitx vitx + viva viva + vivant vivant + vive vive + vixen vixen + viz viz + vizaments vizament + vizard vizard + vizarded vizard + vizards vizard + vizor vizor + vlouting vlout + vocation vocat + vocativo vocativo + vocatur vocatur + voce voce + voic voic + voice voic + voices voic + void void + voided void + voiding void + voke voke + volable volabl + volant volant + volivorco volivorco + volley vollei + volquessen volquessen + volsce volsc + volsces volsc + volscian volscian + volscians volscian + volt volt + voltemand voltemand + volubility volubl + voluble volubl + volume volum + volumes volum + volumnia volumnia + volumnius volumniu + voluntaries voluntari + voluntary voluntari + voluptuously voluptu + voluptuousness voluptu + vomissement vomiss + vomit vomit + vomits vomit + vor vor + vore vore + vortnight vortnight + vot vot + votaries votari + votarist votarist + votarists votarist + votary votari + votre votr + vouch vouch + voucher voucher + vouchers voucher + vouches vouch + vouching vouch + vouchsaf vouchsaf + vouchsafe vouchsaf + vouchsafed vouchsaf + vouchsafes vouchsaf + vouchsafing vouchsaf + voudrais voudrai + vour vour + vous vou + voutsafe voutsaf + vow vow + vowed vow + vowel vowel + vowels vowel + vowing vow + vows vow + vox vox + voyage voyag + voyages voyag + vraiment vraiment + vulcan vulcan + vulgar vulgar + vulgarly vulgarli + vulgars vulgar + vulgo vulgo + vulnerable vulner + vulture vultur + vultures vultur + vurther vurther + w w + wad wad + waddled waddl + wade wade + waded wade + wafer wafer + waft waft + waftage waftag + wafting waft + wafts waft + wag wag + wage wage + wager wager + wagers wager + wages wage + wagging wag + waggish waggish + waggling waggl + waggon waggon + waggoner waggon + wagon wagon + wagoner wagon + wags wag + wagtail wagtail + wail wail + wailful wail + wailing wail + wails wail + wain wain + wainropes wainrop + wainscot wainscot + waist waist + wait wait + waited wait + waiter waiter + waiteth waiteth + waiting wait + waits wait + wak wak + wake wake + waked wake + wakefield wakefield + waken waken + wakened waken + wakes wake + wakest wakest + waking wake + wales wale + walk walk + walked walk + walking walk + walks walk + wall wall + walled wall + wallet wallet + wallets wallet + wallon wallon + walloon walloon + wallow wallow + walls wall + walnut walnut + walter walter + wan wan + wand wand + wander wander + wanderer wander + wanderers wander + wandering wander + wanders wander + wands wand + wane wane + waned wane + wanes wane + waning wane + wann wann + want want + wanted want + wanteth wanteth + wanting want + wanton wanton + wantonly wantonli + wantonness wanton + wantons wanton + wants want + wappen wappen + war war + warble warbl + warbling warbl + ward ward + warded ward + warden warden + warder warder + warders warder + wardrobe wardrob + wardrop wardrop + wards ward + ware ware + wares ware + warily warili + warkworth warkworth + warlike warlik + warm warm + warmed warm + warmer warmer + warming warm + warms warm + warmth warmth + warn warn + warned warn + warning warn + warnings warn + warns warn + warp warp + warped warp + warr warr + warrant warrant + warranted warrant + warranteth warranteth + warrantise warrantis + warrantize warrant + warrants warrant + warranty warranti + warren warren + warrener warren + warring war + warrior warrior + warriors warrior + wars war + wart wart + warwick warwick + warwickshire warwickshir + wary wari + was wa + wash wash + washed wash + washer washer + washes wash + washford washford + washing wash + wasp wasp + waspish waspish + wasps wasp + wassail wassail + wassails wassail + wast wast + waste wast + wasted wast + wasteful wast + wasters waster + wastes wast + wasting wast + wat wat + watch watch + watched watch + watchers watcher + watches watch + watchful watch + watching watch + watchings watch + watchman watchman + watchmen watchmen + watchword watchword + water water + waterdrops waterdrop + watered water + waterfly waterfli + waterford waterford + watering water + waterish waterish + waterpots waterpot + waterrugs waterrug + waters water + waterton waterton + watery wateri + wav wav + wave wave + waved wave + waver waver + waverer waver + wavering waver + waves wave + waving wave + waw waw + wawl wawl + wax wax + waxed wax + waxen waxen + waxes wax + waxing wax + way wai + waylaid waylaid + waylay waylai + ways wai + wayward wayward + waywarder wayward + waywardness wayward + we we + weak weak + weaken weaken + weakens weaken + weaker weaker + weakest weakest + weakling weakl + weakly weakli + weakness weak + weal weal + wealsmen wealsmen + wealth wealth + wealthiest wealthiest + wealthily wealthili + wealthy wealthi + wealtlly wealtlli + wean wean + weapon weapon + weapons weapon + wear wear + wearer wearer + wearers wearer + wearied weari + wearies weari + weariest weariest + wearily wearili + weariness weari + wearing wear + wearisome wearisom + wears wear + weary weari + weasel weasel + weather weather + weathercock weathercock + weathers weather + weav weav + weave weav + weaver weaver + weavers weaver + weaves weav + weaving weav + web web + wed wed + wedded wed + wedding wed + wedg wedg + wedged wedg + wedges wedg + wedlock wedlock + wednesday wednesdai + weed weed + weeded weed + weeder weeder + weeding weed + weeds weed + weedy weedi + week week + weeke week + weekly weekli + weeks week + ween ween + weening ween + weep weep + weeper weeper + weeping weep + weepingly weepingli + weepings weep + weeps weep + weet weet + weigh weigh + weighed weigh + weighing weigh + weighs weigh + weight weight + weightier weightier + weightless weightless + weights weight + weighty weighti + weird weird + welcom welcom + welcome welcom + welcomer welcom + welcomes welcom + welcomest welcomest + welfare welfar + welkin welkin + well well + wells well + welsh welsh + welshman welshman + welshmen welshmen + welshwomen welshwomen + wench wench + wenches wench + wenching wench + wend wend + went went + wept wept + weraday weradai + were were + wert wert + west west + western western + westminster westminst + westmoreland westmoreland + westward westward + wet wet + wether wether + wetting wet + wezand wezand + whale whale + whales whale + wharf wharf + wharfs wharf + what what + whate whate + whatever whatev + whatsoe whatso + whatsoever whatsoev + whatsome whatsom + whe whe + wheat wheat + wheaten wheaten + wheel wheel + wheeling wheel + wheels wheel + wheer wheer + wheeson wheeson + wheezing wheez + whelk whelk + whelks whelk + whelm whelm + whelp whelp + whelped whelp + whelps whelp + when when + whenas whena + whence whenc + whencesoever whencesoev + whene whene + whenever whenev + whensoever whensoev + where where + whereabout whereabout + whereas wherea + whereat whereat + whereby wherebi + wherefore wherefor + wherein wherein + whereinto whereinto + whereof whereof + whereon whereon + whereout whereout + whereso whereso + wheresoe whereso + wheresoever wheresoev + wheresome wheresom + whereto whereto + whereuntil whereuntil + whereunto whereunto + whereupon whereupon + wherever wherev + wherewith wherewith + wherewithal wherewith + whet whet + whether whether + whetstone whetston + whetted whet + whew whew + whey whei + which which + whiff whiff + whiffler whiffler + while while + whiles while + whilst whilst + whin whin + whine whine + whined whine + whinid whinid + whining whine + whip whip + whipp whipp + whippers whipper + whipping whip + whips whip + whipster whipster + whipstock whipstock + whipt whipt + whirl whirl + whirled whirl + whirligig whirligig + whirling whirl + whirlpool whirlpool + whirls whirl + whirlwind whirlwind + whirlwinds whirlwind + whisp whisp + whisper whisper + whispering whisper + whisperings whisper + whispers whisper + whist whist + whistle whistl + whistles whistl + whistling whistl + whit whit + white white + whitehall whitehal + whitely white + whiteness white + whiter whiter + whites white + whitest whitest + whither whither + whiting white + whitmore whitmor + whitsters whitster + whitsun whitsun + whittle whittl + whizzing whizz + who who + whoa whoa + whoe whoe + whoever whoever + whole whole + wholesom wholesom + wholesome wholesom + wholly wholli + whom whom + whoobub whoobub + whoop whoop + whooping whoop + whor whor + whore whore + whoremaster whoremast + whoremasterly whoremasterli + whoremonger whoremong + whores whore + whoreson whoreson + whoresons whoreson + whoring whore + whorish whorish + whose whose + whoso whoso + whosoe whoso + whosoever whosoev + why why + wi wi + wick wick + wicked wick + wickednes wickedn + wickedness wicked + wicket wicket + wicky wicki + wid wid + wide wide + widens widen + wider wider + widow widow + widowed widow + widower widow + widowhood widowhood + widows widow + wield wield + wife wife + wight wight + wights wight + wild wild + wildcats wildcat + wilder wilder + wilderness wilder + wildest wildest + wildfire wildfir + wildly wildli + wildness wild + wilds wild + wiles wile + wilful wil + wilfull wilful + wilfully wilfulli + wilfulnes wilfuln + wilfulness wil + will will + willed will + willers willer + willeth willeth + william william + williams william + willing will + willingly willingli + willingness willing + willoughby willoughbi + willow willow + wills will + wilt wilt + wiltshire wiltshir + wimpled wimpl + win win + wince winc + winch winch + winchester winchest + wincot wincot + wind wind + winded wind + windgalls windgal + winding wind + windlasses windlass + windmill windmil + window window + windows window + windpipe windpip + winds wind + windsor windsor + windy windi + wine wine + wing wing + winged wing + wingfield wingfield + wingham wingham + wings wing + wink wink + winking wink + winks wink + winner winner + winners winner + winning win + winnow winnow + winnowed winnow + winnows winnow + wins win + winter winter + winterly winterli + winters winter + wip wip + wipe wipe + wiped wipe + wipes wipe + wiping wipe + wire wire + wires wire + wiry wiri + wisdom wisdom + wisdoms wisdom + wise wise + wiselier wiseli + wisely wise + wiser wiser + wisest wisest + wish wish + wished wish + wisher wisher + wishers wisher + wishes wish + wishest wishest + wisheth wisheth + wishful wish + wishing wish + wishtly wishtli + wisp wisp + wist wist + wit wit + witb witb + witch witch + witchcraft witchcraft + witches witch + witching witch + with with + withal withal + withdraw withdraw + withdrawing withdraw + withdrawn withdrawn + withdrew withdrew + wither wither + withered wither + withering wither + withers wither + withheld withheld + withhold withhold + withholds withhold + within within + withold withold + without without + withstand withstand + withstanding withstand + withstood withstood + witless witless + witness wit + witnesses wit + witnesseth witnesseth + witnessing wit + wits wit + witted wit + wittenberg wittenberg + wittiest wittiest + wittily wittili + witting wit + wittingly wittingli + wittol wittol + wittolly wittolli + witty witti + wiv wiv + wive wive + wived wive + wives wive + wiving wive + wizard wizard + wizards wizard + wo wo + woe woe + woeful woeful + woefull woeful + woefullest woefullest + woes woe + woful woful + wolf wolf + wolfish wolfish + wolsey wolsei + wolves wolv + wolvish wolvish + woman woman + womanhood womanhood + womanish womanish + womankind womankind + womanly womanli + womb womb + wombs womb + womby wombi + women women + won won + woncot woncot + wond wond + wonder wonder + wondered wonder + wonderful wonder + wonderfully wonderfulli + wondering wonder + wonders wonder + wondrous wondrou + wondrously wondrous + wont wont + wonted wont + woo woo + wood wood + woodbine woodbin + woodcock woodcock + woodcocks woodcock + wooden wooden + woodland woodland + woodman woodman + woodmonger woodmong + woods wood + woodstock woodstock + woodville woodvil + wooed woo + wooer wooer + wooers wooer + wooes wooe + woof woof + wooing woo + wooingly wooingli + wool wool + woollen woollen + woolly woolli + woolsack woolsack + woolsey woolsei + woolward woolward + woos woo + wor wor + worcester worcest + word word + words word + wore wore + worins worin + work work + workers worker + working work + workings work + workman workman + workmanly workmanli + workmanship workmanship + workmen workmen + works work + worky worki + world world + worldlings worldl + worldly worldli + worlds world + worm worm + worms worm + wormwood wormwood + wormy wormi + worn worn + worried worri + worries worri + worry worri + worrying worri + worse wors + worser worser + worship worship + worshipful worship + worshipfully worshipfulli + worshipp worshipp + worshipper worshipp + worshippers worshipp + worshippest worshippest + worships worship + worst worst + worsted worst + wort wort + worth worth + worthied worthi + worthier worthier + worthies worthi + worthiest worthiest + worthily worthili + worthiness worthi + worthless worthless + worths worth + worthy worthi + worts wort + wot wot + wots wot + wotting wot + wouid wouid + would would + wouldest wouldest + wouldst wouldst + wound wound + wounded wound + wounding wound + woundings wound + woundless woundless + wounds wound + wouns woun + woven woven + wow wow + wrack wrack + wrackful wrack + wrangle wrangl + wrangler wrangler + wranglers wrangler + wrangling wrangl + wrap wrap + wrapp wrapp + wraps wrap + wrapt wrapt + wrath wrath + wrathful wrath + wrathfully wrathfulli + wraths wrath + wreak wreak + wreakful wreak + wreaks wreak + wreath wreath + wreathed wreath + wreathen wreathen + wreaths wreath + wreck wreck + wrecked wreck + wrecks wreck + wren wren + wrench wrench + wrenching wrench + wrens wren + wrest wrest + wrested wrest + wresting wrest + wrestle wrestl + wrestled wrestl + wrestler wrestler + wrestling wrestl + wretch wretch + wretchcd wretchcd + wretched wretch + wretchedness wretched + wretches wretch + wring wring + wringer wringer + wringing wring + wrings wring + wrinkle wrinkl + wrinkled wrinkl + wrinkles wrinkl + wrist wrist + wrists wrist + writ writ + write write + writer writer + writers writer + writes write + writhled writhl + writing write + writings write + writs writ + written written + wrong wrong + wronged wrong + wronger wronger + wrongful wrong + wrongfully wrongfulli + wronging wrong + wrongly wrongli + wrongs wrong + wronk wronk + wrote wrote + wroth wroth + wrought wrought + wrung wrung + wry wry + wrying wry + wt wt + wul wul + wye wye + x x + xanthippe xanthipp + xi xi + xii xii + xiii xiii + xiv xiv + xv xv + y y + yard yard + yards yard + yare yare + yarely yare + yarn yarn + yaughan yaughan + yaw yaw + yawn yawn + yawning yawn + ycleped yclepe + ycliped yclipe + ye ye + yea yea + yead yead + year year + yearly yearli + yearn yearn + yearns yearn + years year + yeas yea + yeast yeast + yedward yedward + yell yell + yellow yellow + yellowed yellow + yellowing yellow + yellowness yellow + yellows yellow + yells yell + yelping yelp + yeoman yeoman + yeomen yeomen + yerk yerk + yes ye + yesterday yesterdai + yesterdays yesterdai + yesternight yesternight + yesty yesti + yet yet + yew yew + yicld yicld + yield yield + yielded yield + yielder yielder + yielders yielder + yielding yield + yields yield + yok yok + yoke yoke + yoked yoke + yokefellow yokefellow + yokes yoke + yoketh yoketh + yon yon + yond yond + yonder yonder + yongrey yongrei + yore yore + yorick yorick + york york + yorkists yorkist + yorks york + yorkshire yorkshir + you you + young young + younger younger + youngest youngest + youngling youngl + younglings youngl + youngly youngli + younker younker + your your + yours your + yourself yourself + yourselves yourselv + youth youth + youthful youth + youths youth + youtli youtli + zanies zani + zany zani + zeal zeal + zealous zealou + zeals zeal + zed zed + zenelophon zenelophon + zenith zenith + zephyrs zephyr + zir zir + zo zo + zodiac zodiac + zodiacs zodiac + zone zone + zounds zound + zwagger zwagger +} + +# Create a full-text index to use for testing the stemmer. +# +db close +sqlite3 db :memory: +db eval { + CREATE VIRTUAL TABLE t1 USING fts1(word, tokenize Porter); +} + +foreach {pfrom pto} $porter_test_data { + do_test fts1porter-$pfrom { + execsql { + DELETE FROM t1_term; + DELETE FROM t1_content; + INSERT INTO t1(word) VALUES($pfrom); + SELECT term FROM t1_term; + } + } $pto +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2.test b/components/external/SQLite-3.8.1/test/fts2.test new file mode 100644 index 0000000000000000000000000000000000000000..b1e2959366cb3a66992622ce96a30989c1807ebb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2.test @@ -0,0 +1,67 @@ +# 2008 July 22 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs all tests. +# +# $Id: fts2.test,v 1.2 2008/07/23 18:17:32 drh Exp $ + +proc lshift {lvar} { + upvar $lvar l + set ret [lindex $l 0] + set l [lrange $l 1 end] + return $ret +} +while {[set arg [lshift argv]] != ""} { + switch -- $arg { + -sharedpagercache { + sqlite3_enable_shared_cache 1 + } + -soak { + set G(issoak) 1 + } + default { + set argv [linsert $argv 0 $arg] + break + } + } +} + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + return +} +rename finish_test really_finish_test +proc finish_test {} {} +set G(isquick) 1 + +set EXCLUDE { + fts2.test +} + +# Files to include in the test. If this list is empty then everything +# that is not in the EXCLUDE list is run. +# +set INCLUDE { +} + +foreach testfile [lsort -dictionary [glob $testdir/fts2*.test]] { + set tail [file tail $testfile] + if {[lsearch -exact $EXCLUDE $tail]>=0} continue + if {[llength $INCLUDE]>0 && [lsearch -exact $INCLUDE $tail]<0} continue + source $testfile + catch {db close} + if {$sqlite_open_file_count>0} { + puts "$tail did not close all files: $sqlite_open_file_count" + fail_test $tail + set sqlite_open_file_count 0 + } +} + +set sqlite_open_file_count 0 +really_finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2a.test b/components/external/SQLite-3.8.1/test/fts2a.test new file mode 100644 index 0000000000000000000000000000000000000000..2d1566fcceb0cf1179decde53c70fc841425324f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2a.test @@ -0,0 +1,202 @@ +# 2006 September 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS2 module. +# +# $Id: fts2a.test,v 1.2 2007/05/21 21:59:18 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# Construct a full-text search table containing five keywords: +# one, two, three, four, and five, in various combinations. The +# rowid for each will be a bitmask for the elements it contains. +# +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(content); + INSERT INTO t1(content) VALUES('one'); + INSERT INTO t1(content) VALUES('two'); + INSERT INTO t1(content) VALUES('one two'); + INSERT INTO t1(content) VALUES('three'); + INSERT INTO t1(content) VALUES('one three'); + INSERT INTO t1(content) VALUES('two three'); + INSERT INTO t1(content) VALUES('one two three'); + INSERT INTO t1(content) VALUES('four'); + INSERT INTO t1(content) VALUES('one four'); + INSERT INTO t1(content) VALUES('two four'); + INSERT INTO t1(content) VALUES('one two four'); + INSERT INTO t1(content) VALUES('three four'); + INSERT INTO t1(content) VALUES('one three four'); + INSERT INTO t1(content) VALUES('two three four'); + INSERT INTO t1(content) VALUES('one two three four'); + INSERT INTO t1(content) VALUES('five'); + INSERT INTO t1(content) VALUES('one five'); + INSERT INTO t1(content) VALUES('two five'); + INSERT INTO t1(content) VALUES('one two five'); + INSERT INTO t1(content) VALUES('three five'); + INSERT INTO t1(content) VALUES('one three five'); + INSERT INTO t1(content) VALUES('two three five'); + INSERT INTO t1(content) VALUES('one two three five'); + INSERT INTO t1(content) VALUES('four five'); + INSERT INTO t1(content) VALUES('one four five'); + INSERT INTO t1(content) VALUES('two four five'); + INSERT INTO t1(content) VALUES('one two four five'); + INSERT INTO t1(content) VALUES('three four five'); + INSERT INTO t1(content) VALUES('one three four five'); + INSERT INTO t1(content) VALUES('two three four five'); + INSERT INTO t1(content) VALUES('one two three four five'); +} + +do_test fts2a-1.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts2a-1.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two'} +} {3 7 11 15 19 23 27 31} +do_test fts2a-1.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one'} +} {3 7 11 15 19 23 27 31} +do_test fts2a-1.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two three'} +} {7 15 23 31} +do_test fts2a-1.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one three two'} +} {7 15 23 31} +do_test fts2a-1.6 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two three one'} +} {7 15 23 31} +do_test fts2a-1.7 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one three'} +} {7 15 23 31} +do_test fts2a-1.8 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three one two'} +} {7 15 23 31} +do_test fts2a-1.9 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three two one'} +} {7 15 23 31} +do_test fts2a-1.10 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two THREE'} +} {7 15 23 31} +do_test fts2a-1.11 { + execsql {SELECT rowid FROM t1 WHERE content MATCH ' ONE Two three '} +} {7 15 23 31} + +do_test fts2a-2.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one"'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts2a-2.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two"'} +} {3 7 11 15 19 23 27 31} +do_test fts2a-2.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"two one"'} +} {} +do_test fts2a-2.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three"'} +} {7 15 23 31} +do_test fts2a-2.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two"'} +} {} +do_test fts2a-2.6 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three four"'} +} {15 31} +do_test fts2a-2.7 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two four"'} +} {} +do_test fts2a-2.8 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three five"'} +} {21} +do_test fts2a-2.9 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" five'} +} {21 29} +do_test fts2a-2.10 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three"'} +} {21 29} +do_test fts2a-2.11 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three" four'} +} {29} +do_test fts2a-2.12 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five four "one three"'} +} {29} +do_test fts2a-2.13 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" four five'} +} {29} + +do_test fts2a-3.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts2a-3.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one -two'} +} {1 5 9 13 17 21 25 29} +do_test fts2a-3.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '-two one'} +} {1 5 9 13 17 21 25 29} + +do_test fts2a-4.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one OR two'} +} {1 2 3 5 6 7 9 10 11 13 14 15 17 18 19 21 22 23 25 26 27 29 30 31} +do_test fts2a-4.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two" OR three'} +} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31} +do_test fts2a-4.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR "one two"'} +} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31} +do_test fts2a-4.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three'} +} {3 5 7 11 13 15 19 21 23 27 29 31} +do_test fts2a-4.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR two one'} +} {3 5 7 11 13 15 19 21 23 27 29 31} +do_test fts2a-4.6 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three OR four'} +} {3 5 7 9 11 13 15 19 21 23 25 27 29 31} +do_test fts2a-4.7 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two OR three OR four one'} +} {3 5 7 9 11 13 15 19 21 23 25 27 29 31} + +# Test the ability to handle NULL content +# +do_test fts2a-5.1 { + execsql {INSERT INTO t1(content) VALUES(NULL)} +} {} +do_test fts2a-5.2 { + set rowid [db last_insert_rowid] + execsql {SELECT content FROM t1 WHERE rowid=$rowid} +} {{}} +do_test fts2a-5.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH NULL} +} {} + +# Test the ability to handle non-positive rowids +# +do_test fts2a-6.0 { + execsql {INSERT INTO t1(rowid, content) VALUES(0, 'four five')} +} {} +do_test fts2a-6.1 { + execsql {SELECT content FROM t1 WHERE rowid = 0} +} {{four five}} +do_test fts2a-6.2 { + execsql {INSERT INTO t1(rowid, content) VALUES(-1, 'three four')} +} {} +do_test fts2a-6.3 { + execsql {SELECT content FROM t1 WHERE rowid = -1} +} {{three four}} +do_test fts2a-6.4 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'four'} +} {-1 0 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2b.test b/components/external/SQLite-3.8.1/test/fts2b.test new file mode 100644 index 0000000000000000000000000000000000000000..169cd8a0a3d427f1a181116036127acfa9680122 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2b.test @@ -0,0 +1,147 @@ +# 2006 September 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS2 module. +# +# $Id: fts2b.test,v 1.1 2006/10/19 23:36:26 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# Fill the full-text index "t1" with phrases in english, spanish, +# and german. For the i-th row, fill in the names for the bits +# that are set in the value of i. The least significant bit is +# 1. For example, the value 5 is 101 in binary which will be +# converted to "one three" in english. +# +proc fill_multilanguage_fulltext_t1 {} { + set english {one two three four five} + set spanish {un dos tres cuatro cinco} + set german {eine zwei drei vier funf} + + for {set i 1} {$i<=31} {incr i} { + set cmd "INSERT INTO t1 VALUES" + set vset {} + foreach lang {english spanish german} { + set words {} + for {set j 0; set k 1} {$j<5} {incr j; incr k $k} { + if {$k&$i} {lappend words [lindex [set $lang] $j]} + } + lappend vset "'$words'" + } + set sql "INSERT INTO t1(english,spanish,german) VALUES([join $vset ,])" + # puts $sql + db eval $sql + } +} + +# Construct a full-text search table containing five keywords: +# one, two, three, four, and five, in various combinations. The +# rowid for each will be a bitmask for the elements it contains. +# +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(english,spanish,german); +} +fill_multilanguage_fulltext_t1 + +do_test fts2b-1.1 { + execsql {SELECT rowid FROM t1 WHERE english MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts2b-1.2 { + execsql {SELECT rowid FROM t1 WHERE spanish MATCH 'one'} +} {} +do_test fts2b-1.3 { + execsql {SELECT rowid FROM t1 WHERE german MATCH 'one'} +} {} +do_test fts2b-1.4 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts2b-1.5 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one dos drei'} +} {7 15 23 31} +do_test fts2b-1.6 { + execsql {SELECT english, spanish, german FROM t1 WHERE rowid=1} +} {one un eine} +do_test fts2b-1.7 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"one un"'} +} {} + +do_test fts2b-2.1 { + execsql { + CREATE VIRTUAL TABLE t2 USING fts2(from,to); + INSERT INTO t2([from],[to]) VALUES ('one two three', 'four five six'); + SELECT [from], [to] FROM t2 + } +} {{one two three} {four five six}} + + +# Compute an SQL string that contains the words one, two, three,... to +# describe bits set in the value $i. Only the lower 5 bits are examined. +# +proc wordset {i} { + set x {} + for {set j 0; set k 1} {$j<5} {incr j; incr k $k} { + if {$k&$i} {lappend x [lindex {one two three four five} $j]} + } + return '$x' +} + +# Create a new FTS table with three columns: +# +# norm: words for the bits of rowid +# plusone: words for the bits of rowid+1 +# invert: words for the bits of ~rowid +# +db eval { + CREATE VIRTUAL TABLE t4 USING fts2([norm],'plusone',"invert"); +} +for {set i 1} {$i<=15} {incr i} { + set vset [list [wordset $i] [wordset [expr {$i+1}]] [wordset [expr {~$i}]]] + db eval "INSERT INTO t4(norm,plusone,invert) VALUES([join $vset ,]);" +} + +do_test fts2b-4.1 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one'} +} {1 3 5 7 9 11 13 15} +do_test fts2b-4.2 { + execsql {SELECT rowid FROM t4 WHERE norm MATCH 'one'} +} {1 3 5 7 9 11 13 15} +do_test fts2b-4.3 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'one'} +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} +do_test fts2b-4.4 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:one'} +} {2 4 6 8 10 12 14} +do_test fts2b-4.5 { + execsql {SELECT rowid FROM t4 WHERE plusone MATCH 'one'} +} {2 4 6 8 10 12 14} +do_test fts2b-4.6 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one plusone:two'} +} {1 5 9 13} +do_test fts2b-4.7 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one two'} +} {1 3 5 7 9 11 13 15} +do_test fts2b-4.8 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:two norm:one'} +} {1 5 9 13} +do_test fts2b-4.9 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'two norm:one'} +} {1 3 5 7 9 11 13 15} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2c.test b/components/external/SQLite-3.8.1/test/fts2c.test new file mode 100644 index 0000000000000000000000000000000000000000..cc6c9bbb5dcc2e2eb9fcfbef88d39ee8e5dc8f18 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2c.test @@ -0,0 +1,1213 @@ +# 2006 September 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS2 module. +# +# $Id: fts2c.test,v 1.1 2006/10/19 23:36:26 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# Create a table of sample email data. The data comes from email +# archives of Enron executives that was published as part of the +# litigation against that company. +# +do_test fts2c-1.1 { + db eval { + CREATE VIRTUAL TABLE email USING fts2([from],[to],subject,body); + BEGIN TRANSACTION; +INSERT INTO email([from],[to],subject,body) VALUES('savita.puthigai@enron.com', 'traders.eol@enron.com, traders.eol@enron.com', 'EnronOnline- Change to Autohedge', 'Effective Monday, October 22, 2001 the following changes will be made to the Autohedge functionality on EnronOnline. + +The volume on the hedge will now respect the minimum volume and volume increment settings on the parent product. See rules below: + +? If the transaction volume on the child is less than half of the parent''s minimum volume no hedge will occur. +? If the transaction volume on the child is more than half the parent''s minimum volume but less than half the volume increment on the parent, the hedge will volume will be the parent''s minimum volume. +? For all other volumes, the same rounding rules will apply based on the volume increment on the parent product. + +Please see example below: + +Parent''s Settings: +Minimum: 5000 +Increment: 1000 + +Volume on Autohedge transaction Volume Hedged +1 - 2499 0 +2500 - 5499 5000 +5500 - 6499 6000'); +INSERT INTO email([from],[to],subject,body) VALUES('dana.davis@enron.com', 'laynie.east@enron.com, lisa.king@enron.com, lisa.best@enron.com,', 'Leaving Early', 'FYI: +If it''s ok with everyone''s needs, I would like to leave @4pm. If you think +you will need my assistance past the 4 o''clock hour just let me know; I''ll +be more than willing to stay.'); +INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'louise.kitchen@enron.com', '<> - CC02.06.02', 'The following expense report is ready for approval: + +Employee Name: Christopher F. Calger +Status last changed by: Mollie E. Gustafson Ms +Expense Report Name: CC02.06.02 +Report Total: $3,972.93 +Amount Due Employee: $3,972.93 + + +To approve this expense report, click on the following link for Concur Expense. +http://expensexms.enron.com'); +INSERT INTO email([from],[to],subject,body) VALUES('jeff.duff@enron.com', 'julie.johnson@enron.com', 'Work request', 'Julie, + +Could you print off the current work request report by 1:30 today? + +Gentlemen, + +I''d like to review this today at 1:30 in our office. Also, could you provide +me with your activity reports so I can have Julie enter this information. + +JD'); +INSERT INTO email([from],[to],subject,body) VALUES('v.weldon@enron.com', 'gary.l.carrier@usa.dupont.com, scott.joyce@bankofamerica.com', 'Enron News', 'This could turn into something big.... +http://biz.yahoo.com/rf/010129/n29305829.html'); +INSERT INTO email([from],[to],subject,body) VALUES('mark.haedicke@enron.com', 'paul.simons@enron.com', 'Re: First Polish Deal!', 'Congrats! Things seem to be building rapidly now on the Continent. Mark'); +INSERT INTO email([from],[to],subject,body) VALUES('e..carter@enron.com', 't..robinson@enron.com', 'FW: Producers Newsletter 9-24-2001', ' +The producer lumber pricing sheet. + -----Original Message----- +From: Johnson, Jay +Sent: Tuesday, October 16, 2001 3:42 PM +To: Carter, Karen E. +Subject: FW: Producers Newsletter 9-24-2001 + + + + -----Original Message----- +From: Daigre, Sergai +Sent: Friday, September 21, 2001 8:33 PM +Subject: Producers Newsletter 9-24-2001 + + '); +INSERT INTO email([from],[to],subject,body) VALUES('david.delainey@enron.com', 'kenneth.lay@enron.com', 'Greater Houston Partnership', 'Ken, in response to the letter from Mr Miguel San Juan, my suggestion would +be to offer up the Falcon for their use; however, given the tight time frame +and your recent visit with Mr. Fox that it would be difficult for either you +or me to participate. + +I spoke to Max and he agrees with this approach. + +I hope this meets with your approval. + +Regards +Delainey'); +INSERT INTO email([from],[to],subject,body) VALUES('lachandra.fenceroy@enron.com', 'lindy.donoho@enron.com', 'FW: Bus Applications Meeting Follow Up', 'Lindy, + +Here is the original memo we discussed earlier. Please provide any information that you may have. + +Your cooperation is greatly appreciated. + +Thanks, + +lachandra.fenceroy@enron.com +713.853.3884 +877.498.3401 Pager + + -----Original Message----- +From: Bisbee, Joanne +Sent: Wednesday, September 26, 2001 7:50 AM +To: Fenceroy, LaChandra +Subject: FW: Bus Applications Meeting Follow Up + +Lachandra, Please get with David Duff today and see what this is about. Who are our TW accounting business users? + + -----Original Message----- +From: Koh, Wendy +Sent: Tuesday, September 25, 2001 2:41 PM +To: Bisbee, Joanne +Subject: Bus Applications Meeting Follow Up + +Lisa brought up a TW change effective Nov 1. It involves eliminating a turnback surcharge. I have no other information, but you might check with the business folks for any system changes required. + +Wendy'); +INSERT INTO email([from],[to],subject,body) VALUES('danny.mccarty@enron.com', 'fran.fagan@enron.com', 'RE: worksheets', 'Fran, + If Julie''s merit needs to be lump sum, just move it over to that column. Also, send me Eric Gadd''s sheets as well. Thanks. +Dan + + -----Original Message----- +From: Fagan, Fran +Sent: Thursday, December 20, 2001 11:10 AM +To: McCarty, Danny +Subject: worksheets + +As discussed, attached are your sheets for bonus and merit. + +Thanks, + +Fran Fagan +Sr. HR Rep +713.853.5219 + + + << File: McCartyMerit.xls >> << File: mccartyBonusCommercial_UnP.xls >> + +'); +INSERT INTO email([from],[to],subject,body) VALUES('bert.meyers@enron.com', 'shift.dl-portland@enron.com', 'OCTOBER SCHEDULE', 'TEAM, + +PLEASE SEND ME ANY REQUESTS THAT YOU HAVE FOR OCTOBER. SO FAR I HAVE THEM FOR LEAF. I WOULD LIKE TO HAVE IT DONE BY THE 15TH OF THE MONTH. ANY QUESTIONS PLEASE GIVE ME A CALL. + +BERT'); +INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'john.arnold@enron.com, bilal.bajwa@enron.com, john.griffith@enron.com,', 'TRV Notification: (NG - PROPT P/L - 09/27/2001)', 'The report named: NG - PROPT P/L , published as of 09/27/2001 is now available for viewing on the website.'); +INSERT INTO email([from],[to],subject,body) VALUES('patrice.mims@enron.com', 'calvin.eakins@enron.com', 'Re: Small business supply assistance', 'Hi Calvin + + +I spoke with Rickey (boy, is he long-winded!!). Gave him the name of our +credit guy, Russell Diamond. + +Thank for your help!'); +INSERT INTO email([from],[to],subject,body) VALUES('legal <.hall@enron.com>', 'stephanie.panus@enron.com', 'Termination update', 'City of Vernon and Salt River Project terminated their contracts. I will fax these notices to you.'); +INSERT INTO email([from],[to],subject,body) VALUES('d..steffes@enron.com', 'richard.shapiro@enron.com', 'EES / ENA Government Affairs Staffing & Outside Services', 'Rick -- + +Here is the information on staffing and outside services. Call if you need anything else. + +Jim + + '); +INSERT INTO email([from],[to],subject,body) VALUES('gelliott@industrialinfo.com', 'pcopello@industrialinfo.com', 'ECAAR (Gavin), WSCC (Diablo Canyon), & NPCC (Seabrook)', 'Dear Power Outage Database Customer, +Attached you will find an excel document. The outages contained within are forced or rescheduled outages. Your daily delivery will still contain these outages. +In addition to the two excel documents, there is a dbf file that is formatted like your daily deliveries you receive nightly. This will enable you to load the data into your regular database. Any questions please let me know. Thanks. +Greg Elliott +IIR, Inc. +713-783-5147 x 3481 +outages@industrialinfo.com +THE INFORMATION CONTAINED IN THIS E-MAIL IS LEGALLY PRIVILEGED AND CONFIDENTIAL INFORMATION INTENDED ONLY FOR THE USE OF THE INDIVIDUAL OR ENTITY NAMED ABOVE. YOU ARE HEREBY NOTIFIED THAT ANY DISSEMINATION, DISTRIBUTION, OR COPY OF THIS E-MAIL TO UNAUTHORIZED ENTITIES IS STRICTLY PROHIBITED. IF YOU HAVE RECEIVED THIS +E-MAIL IN ERROR, PLEASE DELETE IT. + - OUTAGE.dbf + - 111201R.xls + - 111201.xls '); +INSERT INTO email([from],[to],subject,body) VALUES('enron.announcements@enron.com', 'all_ena_egm_eim@enron.com', 'EWS Brown Bag', 'MARK YOUR LUNCH CALENDARS NOW ! + +You are invited to attend the EWS Brown Bag Lunch Series + +Featuring: RAY BOWEN, COO + +Topic: Enron Industrial Markets + +Thursday, March 15, 2001 +11:30 am - 12:30 pm +EB 5 C2 + + +You bring your lunch, Limited Seating +We provide drinks and dessert. RSVP x 3-9610'); +INSERT INTO email([from],[to],subject,body) VALUES('chris.germany@enron.com', 'ingrid.immer@williams.com', 'Re: About St Pauls', 'Sounds good to me. I bet this is next to the Warick?? Hotel. + + + + +"Immer, Ingrid" on 12/21/2000 11:48:47 AM +To: "''chris.germany@enron.com''" +cc: +Subject: About St Pauls + + + + + <> +? +?http://www.stpaulshouston.org/about.html + +Chris, + +I like the looks of this place.? What do you think about going here Christmas +eve?? They have an 11:00 a.m. service and a candlelight service at 5:00 p.m., +among others. + +Let me know.?? ii + + - About St Pauls.url + +'); +INSERT INTO email([from],[to],subject,body) VALUES('nas@cpuc.ca.gov', 'skatz@sempratrading.com, kmccrea@sablaw.com, thompson@wrightlaw.com,', 'Reply Brief filed July 31, 2000', ' - CPUC01-#76371-v1-Revised_Reply_Brief__Due_today_7_31_.doc'); +INSERT INTO email([from],[to],subject,body) VALUES('gascontrol@aglresources.com', 'dscott4@enron.com, lcampbel@enron.com', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder +As discussed in the Winter Operations Meeting on Sept.29,2000, +E-Gas(Emergency Gas) will not be offered this winter as a service from AGLC. +Marketers and Poolers can receive gas via Peaking and IBSS nominations(daisy +chain) from other marketers up to the 6 p.m. Same Day 2 nomination cycle. +'); +INSERT INTO email([from],[to],subject,body) VALUES('dutch.quigley@enron.com', 'rwolkwitz@powermerchants.com', '', ' + +Here is a goody for you'); +INSERT INTO email([from],[to],subject,body) VALUES('ryan.o''rourke@enron.com', 'k..allen@enron.com, randy.bhatia@enron.com, frank.ermis@enron.com,', 'TRV Notification: (West VaR - 11/07/2001)', 'The report named: West VaR , published as of 11/07/2001 is now available for viewing on the website.'); +INSERT INTO email([from],[to],subject,body) VALUES('mjones7@txu.com', 'cstone1@txu.com, ggreen2@txu.com, timpowell@txu.com,', 'Enron / HPL Actuals for July 10, 2000', 'Teco Tap 10.000 / Enron ; 110.000 / HPL IFERC + +LS HPL LSK IC 30.000 / Enron +'); +INSERT INTO email([from],[to],subject,body) VALUES('susan.pereira@enron.com', 'kkw816@aol.com', 'soccer practice', 'Kathy- + +Is it safe to assume that practice is cancelled for tonight?? + +Susan Pereira'); +INSERT INTO email([from],[to],subject,body) VALUES('mark.whitt@enron.com', 'barry.tycholiz@enron.com', 'Huber Internal Memo', 'Please look at this. I didn''t know how deep to go with the desk. Do you think this works. + + '); +INSERT INTO email([from],[to],subject,body) VALUES('m..forney@enron.com', 'george.phillips@enron.com', '', 'George, +Give me a call and we will further discuss opportunities on the 13st floor. + +Thanks, +JMForney +3-7160'); +INSERT INTO email([from],[to],subject,body) VALUES('brad.mckay@enron.com', 'angusmcka@aol.com', 'Re: (no subject)', 'not yet'); +INSERT INTO email([from],[to],subject,body) VALUES('adam.bayer@enron.com', 'jonathan.mckay@enron.com', 'FW: Curve Fetch File', 'Here is the curve fetch file sent to me. It has plenty of points in it. If you give me a list of which ones you need we may be able to construct a secondary worksheet to vlookup the values. + +adam +35227 + + + -----Original Message----- +From: Royed, Jeff +Sent: Tuesday, September 25, 2001 11:37 AM +To: Bayer, Adam +Subject: Curve Fetch File + +Let me know if it works. It may be required to have a certain version of Oracle for it to work properly. + + + +Jeff Royed +Enron +Energy Operations +Phone: 713-853-5295'); +INSERT INTO email([from],[to],subject,body) VALUES('matt.smith@enron.com', 'yan.wang@enron.com', 'Report Formats', 'Yan, + +The merged reports look great. I believe the only orientation changes are to +"unmerge" the following six reports: + +31 Keystone Receipts +15 Questar Pipeline +40 Rockies Production +22 West_2 +23 West_3 +25 CIG_WIC + +The orientation of the individual reports should be correct. Thanks. + +Mat + +PS. Just a reminder to add the "*" by the title of calculated points.'); +INSERT INTO email([from],[to],subject,body) VALUES('michelle.lokay@enron.com', 'jimboman@bigfoot.com', 'Egyptian Festival', '---------------------- Forwarded by Michelle Lokay/ET&S/Enron on 09/07/2000 +10:08 AM --------------------------- + + +"Karkour, Randa" on 09/07/2000 09:01:04 AM +To: "''Agheb (E-mail)" , "Leila Mankarious (E-mail)" +, "''Marymankarious (E-mail)" +, "Michelle lokay (E-mail)" , "Ramy +Mankarious (E-mail)" +cc: + +Subject: Egyptian Festival + + + <> + + http://www.egyptianfestival.com/ + + - Egyptian Festival.url +'); +INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'sherry.dawson@enron.com', 'Urgent!!! --- New EAST books', 'This has to be done.................................. + +Thanks +---------------------- Forwarded by Errol McLaughlin/Corp/Enron on 12/20/2000 +08:39 AM --------------------------- + + + + From: William Kelly @ ECT 12/20/2000 08:31 AM + + +To: Kam Keiser/HOU/ECT@ECT, Darron C Giron/HOU/ECT@ECT, David +Baumbach/HOU/ECT@ECT, Errol McLaughlin/Corp/Enron@ENRON +cc: Kimat Singla/HOU/ECT@ECT, Kulvinder Fowler/NA/Enron@ENRON, Kyle R +Lilly/HOU/ECT@ECT, Jeff Royed/Corp/Enron@ENRON, Alejandra +Chavez/NA/Enron@ENRON, Crystal Hyde/HOU/ECT@ECT + +Subject: New EAST books + +We have new book names in TAGG for our intramonth portfolios and it is +extremely important that any deal booked to the East is communicated quickly +to someone on my team. I know it will take some time for the new names to +sink in and I do not want us to miss any positions or P&L. + +Thanks for your help on this. + +New: +Scott Neal : East Northeast +Dick Jenkins: East Marketeast + +WK +'); +INSERT INTO email([from],[to],subject,body) VALUES('david.forster@enron.com', 'eol.wide@enron.com', 'Change to Stack Manager', 'Effective immediately, there is a change to the Stack Manager which will +affect any Inactive Child. + +An inactive Child with links to Parent products will not have their +calculated prices updated until the Child product is Activated. + +When the Child Product is activated, the price will be recalculated and +updated BEFORE it is displayed on the web. + +This means that if you are inputting a basis price on a Child product, you +will not see the final, calculated price until you Activate the product, at +which time the customer will also see it. + +If you have any questions, please contact the Help Desk on: + +Americas: 713 853 4357 +Europe: + 44 (0) 20 7783 7783 +Asia/Australia: +61 2 9229 2300 + +Dave'); +INSERT INTO email([from],[to],subject,body) VALUES('vince.kaminski@enron.com', 'jhh1@email.msn.com', 'Re: Light reading - see pieces beginning on page 7', 'John, + +I saw it. Very interesting. + +Vince + + + + + +"John H Herbert" on 07/28/2000 08:38:08 AM +To: "Vince J Kaminski" +cc: +Subject: Light reading - see pieces beginning on page 7 + + +Cheers and have a nice weekend, + + +JHHerbert + + + + + - gd000728.pdf + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('matthew.lenhart@enron.com', 'mmmarcantel@equiva.com', 'RE:', 'i will try to line up a pig for you '); +INSERT INTO email([from],[to],subject,body) VALUES('jae.black@enron.com', 'claudette.harvey@enron.com, chaun.roberts@enron.com, judy.martinez@enron.com,', 'Disaster Recovery Equipment', 'As a reminder...there are several pieces of equipment that are set up on the 30th Floor, as well as on our floor, for the Disaster Recovery Team. PLEASE DO NOT TAKE, BORROW OR USE this equipment. Should you need to use another computer system, other than yours, or make conference calls please work with your Assistant to help find or set up equipment for you to use. + +Thanks for your understanding in this matter. + +T.Jae Black +East Power Trading +Assistant to Kevin Presto +off. 713-853-5800 +fax 713-646-8272 +cell 713-539-4760'); +INSERT INTO email([from],[to],subject,body) VALUES('eric.bass@enron.com', 'dale.neuner@enron.com', '5 X 24', 'Dale, + +Have you heard anything more on the 5 X 24s? We would like to get this +product out ASAP. + + +Thanks, + +Eric'); +INSERT INTO email([from],[to],subject,body) VALUES('messenger@smartreminders.com', 'm..tholt@enron.com', '10% Coupon - PrintPal Printer Cartridges - 100% Guaranteed', '[IMAGE] +[IMAGE][IMAGE][IMAGE] +Dear SmartReminders Member, + [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] + + + + + + + + + + + + + + + + + + + + + +We respect your privacy and are a Certified Participant of the BBBOnLine + Privacy Program. To be removed from future offers,click here. +SmartReminders.com is a permission based service. To unsubscribe click here . '); +INSERT INTO email([from],[to],subject,body) VALUES('benjamin.rogers@enron.com', 'mark.bernstein@enron.com', '', 'The guy you are talking about left CIN under a "cloud of suspicion" sort of +speak. He was the one who got into several bad deals and PPA''s in California +for CIN, thus he left on a bad note. Let me know if you need more detail +than that, I felt this was the type of info you were looking for. Thanks! +Ben'); +INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'michelle.cash@enron.com', 'Expense Report Receipts Not Received', 'Employee Name: Michelle Cash +Report Name: Houston Cellular 8-11-01 +Report Date: 12/13/01 +Report ID: 594D37C9ED2111D5B452 +Submitted On: 12/13/01 + +You are only allowed 2 reports with receipts outstanding. Your expense reports will not be paid until you meet this requirement.'); +INSERT INTO email([from],[to],subject,body) VALUES('susan.mara@enron.com', 'ray.alvarez@enron.com, mark.palmer@enron.com, karen.denne@enron.com,', 'CAISO Emergency Motion -- to discontinue market-based rates for', 'FYI. the latest broadside against the generators. + +Sue Mara +Enron Corp. +Tel: (415) 782-7802 +Fax:(415) 782-7854 +----- Forwarded by Susan J Mara/NA/Enron on 06/08/2001 12:24 PM ----- + + + "Milner, Marcie" 06/08/2001 11:13 AM To: "''smara@enron.com''" cc: Subject: CAISO Emergency Motion + + +Sue, did you see this emergency motion the CAISO filed today? Apparently +they are requesting that FERC discontinue market-based rates immediately and +grant refunds plus interest on the difference between cost-based rates and +market revenues received back to May 2000. They are requesting the +commission act within 14 days. Have you heard anything about what they are +doing? + +Marcie + +http://www.caiso.com/docs/2001/06/08/200106081005526469.pdf +'); +INSERT INTO email([from],[to],subject,body) VALUES('fletcher.sturm@enron.com', 'eloy.escobar@enron.com', 'Re: General Brinks Position Meeting', 'Eloy, + +Who is General Brinks? + +Fletch'); +INSERT INTO email([from],[to],subject,body) VALUES('nailia.dindarova@enron.com', 'richard.shapiro@enron.com', 'Documents for Mark Frevert (on EU developments and lessons from', 'Rick, + +Here are the documents that Peter has prepared for Mark Frevert. + +Nailia +---------------------- Forwarded by Nailia Dindarova/LON/ECT on 25/06/2001 +16:36 --------------------------- + + +Nailia Dindarova +25/06/2001 15:36 +To: Michael Brown/Enron@EUEnronXGate +cc: Ross Sankey/Enron@EUEnronXGate, Eric Shaw/ENRON@EUEnronXGate, Peter +Styles/LON/ECT@ECT + +Subject: Documents for Mark Frevert (on EU developments and lessons from +California) + +Michael, + + +These are the documents that Peter promised to give to you for Mark Frevert. +He has now handed them to him in person but asked me to transmit them +electronically to you, as well as Eric and Ross. + +Nailia + + + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('peggy.a.kostial@accenture.com', 'dave.samuels@enron.com', 'EOL-Accenture Deal Sheet', 'Dave - + +Attached are our comments and suggested changes. Please call to review. + +On the time line for completion, we have four critical steps to complete: + Finalize market analysis to refine business case, specifically + projected revenue stream + Complete counterparty surveying, including targeting 3 CPs for letters + of intent + Review Enron asset base for potential reuse/ licensing + Contract negotiations + +Joe will come back to us with an updated time line, but it is my +expectation that we are still on the same schedule (we just begun week +three) with possibly a week or so slippage.....contract negotiations will +probably be the critical path. + +We will send our cut at the actual time line here shortly. Thanks, + +Peggy + +(See attached file: accenture-dealpoints v2.doc) + - accenture-dealpoints v2.doc '); +INSERT INTO email([from],[to],subject,body) VALUES('thomas.martin@enron.com', 'thomas.martin@enron.com', 'Re: Guadalupe Power Partners LP', '---------------------- Forwarded by Thomas A Martin/HOU/ECT on 03/20/2001 +03:49 PM --------------------------- + + +Thomas A Martin +10/11/2000 03:55 PM +To: Patrick Wade/HOU/ECT@ECT +cc: +Subject: Re: Guadalupe Power Partners LP + +The deal is physically served at Oasis Waha or Oasis Katy and is priced at +either HSC, Waha or Katytailgate GD at buyers option three days prior to +NYMEX close. + +'); +INSERT INTO email([from],[to],subject,body) VALUES('judy.townsend@enron.com', 'dan.junek@enron.com, chris.germany@enron.com', 'Columbia Distribution''s Capacity Available for Release - Sum', '---------------------- Forwarded by Judy Townsend/HOU/ECT on 03/09/2001 11:04 +AM --------------------------- + + +agoddard@nisource.com on 03/08/2001 09:16:57 AM +To: " - *Koch, Kent" , " - +*Millar, Debra" , " - *Burke, Lynn" + +cc: " - *Heckathorn, Tom" +Subject: Columbia Distribution''s Capacity Available for Release - Sum + + +Attached is Columbia Distribution''s notice of capacity available for release +for +the summer of 2001 (Apr. 2001 through Oct. 2001). + +Please note that the deadline for bids is 3:00pm EST on March 20, 2001. + +If you have any questions, feel free to contact any of the representatives +listed +at the bottom of the attachment. + +Aaron Goddard + + + + + - 2001Summer.doc +'); +INSERT INTO email([from],[to],subject,body) VALUES('rhonda.denton@enron.com', 'tim.belden@enron.com, dana.davis@enron.com, genia.fitzgerald@enron.com,', 'Split Rock Energy LLC', 'We have received the executed EEI contract from this CP dated 12/12/2000. +Copies will be distributed to Legal and Credit.'); +INSERT INTO email([from],[to],subject,body) VALUES('kerrymcelroy@dwt.com', 'jack.speer@alcoa.com, crow@millernash.com, michaelearly@earthlink.net,', 'Oral Argument Request', ' - Oral Argument Request.doc'); +INSERT INTO email([from],[to],subject,body) VALUES('mike.carson@enron.com', 'rlmichaelis@hormel.com', '', 'Did you come in town this wk end..... My new number at our house is : +713-668-3712...... my cell # is 281-381-7332 + +the kid'); +INSERT INTO email([from],[to],subject,body) VALUES('cooper.richey@enron.com', 'trycooper@hotmail.com', 'FW: Contact Info', ' + +-----Original Message----- +From: Punja, Karim +Sent: Thursday, December 13, 2001 2:35 PM +To: Richey, Cooper +Subject: Contact Info + + +Cooper, + +Its been a real pleasure working with you (even though it was for only a small amount of time) +I hope we can stay in touch. + +Home# 234-0249 +email: kpunja@hotmail.com + +Take Care, + +Karim. + '); +INSERT INTO email([from],[to],subject,body) VALUES('bjm30@earthlink.net', 'mcguinn.k@enron.com, mcguinn.ian@enron.com, mcguinn.stephen@enron.com,', 'email address change', 'Hello all. + +I haven''t talked to many of you via email recently but I do want to give you +my new address for your email file: + + bjm30@earthlink.net + +I hope all is well. + +Brian McGuinn'); +INSERT INTO email([from],[to],subject,body) VALUES('shelley.corman@enron.com', 'steve.hotte@enron.com', 'Flat Panels', 'Can you please advise what is going on with the flat panels that we had planned to distribute to our gas logistics team. It was in the budget and we had the okay, but now I''m hearing there is some hold-up & the units are stored on 44. + +Shelley'); +INSERT INTO email([from],[to],subject,body) VALUES('sara.davidson@enron.com', 'john.schwartzenburg@enron.com, scott.dieball@enron.com, recipients@enron.com,', '2001 Enron Law Conference (Distribution List 2)', ' Enron Law Conference + +San Antonio, Texas May 2-4, 2001 Westin Riverwalk + + See attached memo for more details!! + + +? Registration for the law conference this year will be handled through an +Online RSVP Form on the Enron Law Conference Website at +http://lawconference.corp.enron.com. The website is still under construction +and will not be available until Thursday, March 15, 2001. + +? We will send you another e-mail to confirm when the Law Conference Website +is operational. + +? Please complete the Online RSVP Form as soon as it is available and submit +it no later than Friday, March 30th. + + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('tori.kuykendall@enron.com', 'heath.b.taylor@accenture.com', 'Re:', 'hey - thats funny about john - he definitely remembers him - i''ll call pat +and let him know - we are coming on saturday - i just havent had a chance to +call you guys back -- looking forward to it -- i probably need the +directions again though'); +INSERT INTO email([from],[to],subject,body) VALUES('darron.giron@enron.com', 'bryce.baxter@enron.com', 'Re: Feedback for Audrey Cook', 'Bryce, + +I''ll get it done today. + +DG 3-9573 + + + + + + From: Bryce Baxter 06/12/2000 07:15 PM + + +To: Darron C Giron/HOU/ECT@ECT +cc: +Subject: Feedback for Audrey Cook + +You were identified as a reviewer for Audrey Cook. If possible, could you +complete her feedback by end of business Wednesday? It will really help me +in the PRC process to have your input. Thanks. + +'); +INSERT INTO email([from],[to],subject,body) VALUES('casey.evans@enron.com', 'stephanie.sever@enron.com', 'Gas EOL ID', 'Stephanie, + +In conjunction with the recent movement of several power traders, they are changing the names of their gas books as well. The names of the new gas books and traders are as follows: + +PWR-NG-LT-SPP: Mike Carson +PWR-NG-LT-SERC: Jeff King + +If you need to know their power desk to map their ID to their gas books, those desks are as follows: + +EPMI-LT-SPP: Mike Carson +EPMI-LT-SERC: Jeff King + +I will be in training this afternoon, but will be back when class is over. Let me know if you have any questions. + +Thanks for your help! +Casey'); +INSERT INTO email([from],[to],subject,body) VALUES('darrell.schoolcraft@enron.com', 'david.roensch@enron.com, kimberly.watson@enron.com, michelle.lokay@enron.com,', 'Postings', 'Please see the attached. + + +ds + + + + + '); +INSERT INTO email([from],[to],subject,body) VALUES('mcominsky@aol.com', 'cpatman@bracepatt.com, james_derrick@enron.com', 'Jurisprudence Luncheon', 'Carrin & Jim -- + +It was an honor and a pleasure to meet both of you yesterday. I know we will +have fun working together on this very special event. + +Jeff left the jurisprudence luncheon lists for me before he left on vacation. + I wasn''t sure whether he transmitted them to you as well. Would you please +advise me if you would like them sent to you? I can email the MS Excel files +or I can fax the hard copies to you. Please advise what is most convenient. + +I plan to be in town through the holidays and can be reached by phone, email, +or cell phone at any time. My cell phone number is 713/705-4829. + +Thanks again for your interest in the ADL''s work. Martin. + +Martin B. Cominsky +Director, Southwest Region +Anti-Defamation League +713/627-3490, ext. 122 +713/627-2011 (fax) +MCominsky@aol.com'); +INSERT INTO email([from],[to],subject,body) VALUES('phillip.love@enron.com', 'todagost@utmb.edu, gbsonnta@utmb.edu', 'New President', 'I had a little bird put a word in my ear. Is there any possibility for Ben +Raimer to be Bush''s secretary of HHS? Just curious about that infamous UTMB +rumor mill. Hope things are well, happy holidays. +PL'); +INSERT INTO email([from],[to],subject,body) VALUES('marie.heard@enron.com', 'ehamilton@fna.com', 'ISDA Master Agreement', 'Erin: + +Pursuant to your request, attached are the Schedule to the ISDA Master Agreement, together with Paragraph 13 to the ISDA Credit Support Annex. Please let me know if you need anything else. We look forward to hearing your comments. + +Marie + +Marie Heard +Senior Legal Specialist +Enron North America Corp. +Phone: (713) 853-3907 +Fax: (713) 646-3490 +marie.heard@enron.com + + '); +INSERT INTO email([from],[to],subject,body) VALUES('andrea.ring@enron.com', 'beverly.beaty@enron.com', 'Re: Tennessee Buy - Louis Dreyfus', 'Beverly - once again thanks so much for your help on this. + + + + '); +INSERT INTO email([from],[to],subject,body) VALUES('karolyn.criado@enron.com', 'j..bonin@enron.com, felicia.case@enron.com, b..clapp@enron.com,', 'Price List week of Oct. 8-9, 2001', ' +Please contact me if you have any questions regarding last weeks prices. + +Thank you, +Karolyn Criado +3-9441 + + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('kevin.presto@enron.com', 'edward.baughman@enron.com, billy.braddock@enron.com', 'Associated', 'Please begin working on filling our Associated short position in 02. I would like to take this risk off the books. + +In addition, please find out what a buy-out of VEPCO would cost us. With Rogers transitioning to run our retail risk management, I would like to clean up our customer positions. + +We also need to continue to explore a JEA buy-out. + +Thanks.'); +INSERT INTO email([from],[to],subject,body) VALUES('stacy.dickson@enron.com', 'gregg.penman@enron.com', 'RE: Constellation TC 5-7-01', 'Gregg, + +I am at home with a sick baby. (Lots of fun!) I will call you about this +tomorrow. + +Stacy'); +INSERT INTO email([from],[to],subject,body) VALUES('joe.quenet@enron.com', 'dfincher@utilicorp.com', '', 'hey big guy.....check this out..... + + w ww.gorelieberman-2000.com/'); +INSERT INTO email([from],[to],subject,body) VALUES('k..allen@enron.com', 'jacqestc@aol.com', '', 'Jacques, + +I sent you a fax of Kevin Kolb''s comments on the release. The payoff on the note would be $36,248 ($36090(principal) + $158 (accrued interest)). +This is assuming we wrap this up on Tuesday. + +Please email to confirm that their changes are ok so I can set up a meeting on Tuesday to reach closure. + +Phillip'); +INSERT INTO email([from],[to],subject,body) VALUES('kourtney.nelson@enron.com', 'mike.swerzbin@enron.com', 'Adjusted L/R Balance', 'Mike, + +I placed the adjusted L/R Balance on the Enronwest site. It is under the "Staff/Kourtney Nelson". There are two links: + +1) "Adj L_R" is the same data/format from the weekly strategy meeting. +2) "New Gen 2001_2002" link has all of the supply side info that is used to calculate the L/R balance + -Please note the Data Flag column, a value of "3" indicates the project was cancelled, on hold, etc and is not included in the calc. + +Both of these sheets are interactive Excel spreadsheets and thus you can play around with the data as you please. Also, James Bruce is working to get his gen report on the web. That will help with your access to information on new gen. + +Please let me know if you have any questions or feedback, + +Kourtney + + + +Kourtney Nelson +Fundamental Analysis +Enron North America +(503) 464-8280 +kourtney.nelson@enron.com'); +INSERT INTO email([from],[to],subject,body) VALUES('d..thomas@enron.com', 'naveed.ahmed@enron.com', 'FW: Current Enron TCC Portfolio', ' + +-----Original Message----- +From: Grace, Rebecca M. +Sent: Monday, December 17, 2001 9:44 AM +To: Thomas, Paul D. +Cc: Cashion, Jim; Allen, Thresa A.; May, Tom +Subject: RE: Current Enron TCC Portfolio + + +Paul, + +I reviewed NY''s list. I agree with all of their contracts numbers and mw amounts. + +Call if you have any more questions. + +Rebecca + + + + -----Original Message----- +From: Thomas, Paul D. +Sent: Monday, December 17, 2001 9:08 AM +To: Grace, Rebecca M. +Subject: FW: Current Enron TCC Portfolio + + << File: enrontccs.xls >> +Rebecca, +Let me know if you see any differences. + +Paul +X 3-0403 +-----Original Message----- +From: Thomas, Paul D. +Sent: Monday, December 17, 2001 9:04 AM +To: Ahmed, Naveed +Subject: FW: Current Enron TCC Portfolio + + + + +-----Original Message----- +From: Thomas, Paul D. +Sent: Thursday, December 13, 2001 10:01 AM +To: Baughman, Edward D. +Subject: Current Enron TCC Portfolio + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('stephanie.panus@enron.com', 'william.bradford@enron.com, debbie.brackett@enron.com,', 'Coastal Merchant Energy/El Paso Merchant Energy', 'Coastal Merchant Energy, L.P. merged with and into El Paso Merchant Energy, +L.P., effective February 1, 2001, with the surviving entity being El Paso +Merchant Energy, L.P. We currently have ISDA Master Agreements with both +counterparties. Please see the attached memo regarding the existing Masters +and let us know which agreement should be terminated. + +Thanks, +Stephanie +'); +INSERT INTO email([from],[to],subject,body) VALUES('kam.keiser@enron.com', 'c..kenne@enron.com', 'RE: What about this too???', ' + + -----Original Message----- +From: Kenne, Dawn C. +Sent: Wednesday, February 06, 2002 11:50 AM +To: Keiser, Kam +Subject: What about this too??? + + + << File: Netco Trader Matrix.xls >> + '); +INSERT INTO email([from],[to],subject,body) VALUES('chris.meyer@enron.com', 'joe.parks@enron.com', 'Centana', 'Talked to Chip. We do need Cash Committe approval given the netting feature of your deal, which means Batch Funding Request. Please update per my previous e-mail and forward. + +Thanks + +chris +x31666'); +INSERT INTO email([from],[to],subject,body) VALUES('debra.perlingiere@enron.com', 'jworman@academyofhealth.com', '', 'Have a great weekend! Happy Fathers Day! + + +Debra Perlingiere +Enron North America Corp. +1400 Smith Street, EB 3885 +Houston, Texas 77002 +dperlin@enron.com +Phone 713-853-7658 +Fax 713-646-3490'); +INSERT INTO email([from],[to],subject,body) VALUES('outlook.team@enron.com', '', 'Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia &', 'CALENDAR ENTRY: APPOINTMENT + +Description: + Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia & Dir Rpts. - 4102 + +Date: 1/5/2001 +Time: 9:00 AM - 10:00 AM (Central Standard Time) + +Chairperson: Outlook Migration Team + +Detailed Description:'); +INSERT INTO email([from],[to],subject,body) VALUES('diana.seifert@enron.com', 'mark.taylor@enron.com', 'Guest access Chile', 'Hello Mark, + +Justin Boyd told me that your can help me with questions regarding Chile. +We got a request for guest access through MG. +The company is called Escondida and is a subsidiary of BHP Australia. + +Please advise if I can set up a guest account or not. +F.Y.I.: MG is planning to put a "in w/h Chile" contract for Copper on-line as +soon as Enron has done the due diligence for this country. +Thanks ! + + +Best regards + +Diana Seifert +EOL PCG'); +INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'mark.whitt@enron.com', '<> - 121001', 'The Approval status has changed on the following report: + +Status last changed by: Barry L. Tycholiz +Expense Report Name: 121001 +Report Total: $198.98 +Amount Due Employee: $198.98 +Amount Approved: $198.98 +Amount Paid: $0.00 +Approval Status: Approved +Payment Status: Pending + + +To review this expense report, click on the following link for Concur Expense. +http://expensexms.enron.com'); +INSERT INTO email([from],[to],subject,body) VALUES('kevin.hyatt@enron.com', '', 'Technical Support', 'Outside the U.S., please refer to the list below: + +Australia: +1800 678-515 +support@palm-au.com + +Canada: +1905 305-6530 +support@palm.com + +New Zealand: +0800 446-398 +support@palm-nz.com + +U.K.: +0171 867 0108 +eurosupport@palm.3com.com + +Please refer to the Worldwide Customer Support card for a complete technical support contact list.'); +INSERT INTO email([from],[to],subject,body) VALUES('geoff.storey@enron.com', 'dutch.quigley@enron.com', 'RE:', 'duke contact? + + -----Original Message----- +From: Quigley, Dutch +Sent: Wednesday, October 31, 2001 10:14 AM +To: Storey, Geoff +Subject: RE: + +bp corp Albert LaMore 281-366-4962 + +running the reports now + + + -----Original Message----- +From: Storey, Geoff +Sent: Wednesday, October 31, 2001 10:10 AM +To: Quigley, Dutch +Subject: RE: + +give me a contact over there too +BP + + + -----Original Message----- +From: Quigley, Dutch +Sent: Wednesday, October 31, 2001 9:42 AM +To: Storey, Geoff +Subject: + +Coral Jeff Whitnah 713-767-5374 +Relaint Steve McGinn 713-207-4000'); +INSERT INTO email([from],[to],subject,body) VALUES('pete.davis@enron.com', 'pete.davis@enron.com', 'Start Date: 4/22/01; HourAhead hour: 3; ', 'Start Date: 4/22/01; HourAhead hour: 3; No ancillary schedules awarded. +Variances detected. +Variances detected in Load schedule. + + LOG MESSAGES: + +PARSING FILE -->> O:\Portland\WestDesk\California Scheduling\ISO Final +Schedules\2001042203.txt + +---- Load Schedule ---- +$$$ Variance found in table tblLoads. + Details: (Hour: 3 / Preferred: 1.92 / Final: 1.89) + TRANS_TYPE: FINAL + LOAD_ID: PGE4 + MKT_TYPE: 2 + TRANS_DATE: 4/22/01 + SC_ID: EPMI + +'); +INSERT INTO email([from],[to],subject,body) VALUES('john.postlethwaite@enron.com', 'john.zufferli@enron.com', 'Reference', 'John, hope things are going well up there for you. The big day is almost here for you and Jessica. I was wondering if I could use your name as a job reference if need be. I am just trying to get everything in order just in case something happens. + +John'); +INSERT INTO email([from],[to],subject,body) VALUES('jeffrey.shankman@enron.com', 'lschiffm@jonesday.com', 'Re:', 'I saw you called on the cell this a.m. Sorry I missed you. (I was in the +shower). I have had a shitty week--I suspect my silence (not only to you, +but others) after our phone call is a result of the week. I''m seeing Glen at +11:15....talk to you'); +INSERT INTO email([from],[to],subject,body) VALUES('litebytz@enron.com', '', 'Lite Bytz RSVP', ' +This week''s Lite Bytz presentation will feature the following TOOLZ speaker: + +Richard McDougall +Solaris 8 +Thursday, June 7, 2001 + +If you have not already signed up, please RSVP via email to litebytz@enron.com by the end of the day Tuesday, June 5, 2001. + +*Remember: this is now a Brown Bag Event--so bring your lunch and we will provide cookies and drinks. + +Click below for more details. + +http://home.enron.com:84/messaging/litebytztoolzprint.jpg'); + COMMIT; + } +} {} + +############################################################################### +# Everything above just builds an interesting test database. The actual +# tests come after this comment. +############################################################################### + +do_test fts2c-1.2 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark' + } +} {6 17 25 38 40 42 73 74} +do_test fts2c-1.3 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'susan' + } +} {24 40} +do_test fts2c-1.4 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark susan' + } +} {40} +do_test fts2c-1.5 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'susan mark' + } +} {40} +do_test fts2c-1.6 { + execsql { + SELECT rowid FROM email WHERE email MATCH '"mark susan"' + } +} {} +do_test fts2c-1.7 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark -susan' + } +} {6 17 25 38 42 73 74} +do_test fts2c-1.8 { + execsql { + SELECT rowid FROM email WHERE email MATCH '-mark susan' + } +} {24} +do_test fts2c-1.9 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark OR susan' + } +} {6 17 24 25 38 40 42 73 74} + +# Some simple tests of the automatic "offsets(email)" column. In the sample +# data set above, only one message, number 20, contains the words +# "gas" and "reminder" in both body and subject. +# +do_test fts2c-2.1 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE email MATCH 'gas reminder' + } +} {20 {2 0 42 3 2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}} +do_test fts2c-2.2 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE email MATCH 'subject:gas reminder' + } +} {20 {2 0 42 3 2 1 54 8 3 1 54 8}} +do_test fts2c-2.3 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE email MATCH 'body:gas reminder' + } +} {20 {2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}} +do_test fts2c-2.4 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE subject MATCH 'gas reminder' + } +} {20 {2 0 42 3 2 1 54 8}} +do_test fts2c-2.5 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE body MATCH 'gas reminder' + } +} {20 {3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}} + +# Document 32 contains 5 instances of the world "child". But only +# 3 of them are paired with "product". Make sure only those instances +# that match the phrase appear in the offsets(email) list. +# +do_test fts2c-3.1 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE body MATCH 'child product' AND +rowid=32 + } +} {32 {3 0 94 5 3 0 114 5 3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7 3 1 493 7}} +do_test fts2c-3.2 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE body MATCH '"child product"' + } +} {32 {3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7}} + +# Snippet generator tests +# +do_test fts2c-4.1 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'subject:gas reminder' + } +} {{Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder}} +do_test fts2c-4.2 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'christmas candlelight' + } +} {{... place.? What do you think about going here Christmas +eve?? They have an 11:00 a.m. service and a candlelight service at 5:00 p.m., +among others. ...}} + +do_test fts2c-4.3 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'deal sheet potential reuse' + } +} {{EOL-Accenture Deal Sheet ... intent + Review Enron asset base for potential reuse/ licensing + Contract negotiations ...}} +do_test fts2c-4.4 { + execsql { + SELECT snippet(email,'<<<','>>>',' ') FROM email + WHERE email MATCH 'deal sheet potential reuse' + } +} {{EOL-Accenture <<>> <<>> intent + Review Enron asset base for <<>> <<>>/ licensing + Contract negotiations }} +do_test fts2c-4.5 { + execsql { + SELECT snippet(email,'<<<','>>>',' ') FROM email + WHERE email MATCH 'first things' + } +} {{Re: <<>> Polish Deal! Congrats! <<>> seem to be building rapidly now on the }} +do_test fts2c-4.6 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'chris is here' + } +} {{chris.germany@enron.com ... Sounds good to me. I bet this is next to the Warick?? Hotel. ... place.? What do you think about going here Christmas +eve?? They have an 11:00 a.m. ...}} +do_test fts2c-4.7 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH '"pursuant to"' + } +} {{Erin: + +Pursuant to your request, attached are the Schedule to ...}} +do_test fts2c-4.8 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'ancillary load davis' + } +} {{pete.davis@enron.com ... Start Date: 4/22/01; HourAhead hour: 3; No ancillary schedules awarded. +Variances detected. +Variances detected in Load schedule. + + LOG MESSAGES: + +PARSING ...}} + +# Combinations of AND and OR operators: +# +do_test fts2c-5.1 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'questar enron OR com' + } +} {{matt.smith@enron.com ... six reports: + +31 Keystone Receipts +15 Questar Pipeline +40 Rockies Production +22 West_2 ...}} +do_test fts2c-5.2 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'enron OR com questar' + } +} {{matt.smith@enron.com ... six reports: + +31 Keystone Receipts +15 Questar Pipeline +40 Rockies Production +22 West_2 ...}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2d.test b/components/external/SQLite-3.8.1/test/fts2d.test new file mode 100644 index 0000000000000000000000000000000000000000..d8090d8f0ccf3e65a89333d93c6b7923b3a188ec --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2d.test @@ -0,0 +1,65 @@ +# 2006 October 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS2 module, and in particular +# the Porter stemmer. +# +# $Id: fts2d.test,v 1.1 2006/10/19 23:36:26 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +do_test fts2d-1.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts2(content, tokenize porter); + INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping'); + SELECT rowid FROM t1 WHERE content MATCH 'run jump'; + } +} {1} +do_test fts2d-1.2 { + execsql { + SELECT snippet(t1) FROM t1 WHERE t1 MATCH 'run jump'; + } +} {{running and jumping}} +do_test fts2d-1.3 { + execsql { + INSERT INTO t1(rowid, content) + VALUES(2, 'abcdefghijklmnopqrstuvwyxz'); + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijqrstuvwyxz' + } +} {2 abcdefghijklmnopqrstuvwyxz} +do_test fts2d-1.4 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijXXXXqrstuvwyxz' + } +} {2 abcdefghijklmnopqrstuvwyxz} +do_test fts2d-1.5 { + execsql { + INSERT INTO t1(rowid, content) + VALUES(3, 'The value is 123456789'); + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123789' + } +} {3 {The value is 123456789}} +do_test fts2d-1.6 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123000000789' + } +} {3 {The value is 123456789}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2e.test b/components/external/SQLite-3.8.1/test/fts2e.test new file mode 100644 index 0000000000000000000000000000000000000000..71845acdde41d4c42e6aa4e849aa9b1c9b9e9501 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2e.test @@ -0,0 +1,85 @@ +# 2006 October 19 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing deletions in the FTS2 module. +# +# $Id: fts2e.test,v 1.1 2006/10/19 23:36:26 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# Construct a full-text search table containing keywords which are the +# ordinal numbers of the bit positions set for a sequence of integers, +# which are used for the rowid. There are a total of 30 INSERT and +# DELETE statements, so that we'll test both the segmentMerge() merge +# (over the first 16) and the termSelect() merge (over the level-1 +# segment and 14 level-0 segments). +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(content); + INSERT INTO t1 (rowid, content) VALUES(1, 'one'); + INSERT INTO t1 (rowid, content) VALUES(2, 'two'); + INSERT INTO t1 (rowid, content) VALUES(3, 'one two'); + INSERT INTO t1 (rowid, content) VALUES(4, 'three'); + DELETE FROM t1 WHERE rowid = 1; + INSERT INTO t1 (rowid, content) VALUES(5, 'one three'); + INSERT INTO t1 (rowid, content) VALUES(6, 'two three'); + INSERT INTO t1 (rowid, content) VALUES(7, 'one two three'); + DELETE FROM t1 WHERE rowid = 4; + INSERT INTO t1 (rowid, content) VALUES(8, 'four'); + INSERT INTO t1 (rowid, content) VALUES(9, 'one four'); + INSERT INTO t1 (rowid, content) VALUES(10, 'two four'); + DELETE FROM t1 WHERE rowid = 7; + INSERT INTO t1 (rowid, content) VALUES(11, 'one two four'); + INSERT INTO t1 (rowid, content) VALUES(12, 'three four'); + INSERT INTO t1 (rowid, content) VALUES(13, 'one three four'); + DELETE FROM t1 WHERE rowid = 10; + INSERT INTO t1 (rowid, content) VALUES(14, 'two three four'); + INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four'); + INSERT INTO t1 (rowid, content) VALUES(16, 'five'); + DELETE FROM t1 WHERE rowid = 13; + INSERT INTO t1 (rowid, content) VALUES(17, 'one five'); + INSERT INTO t1 (rowid, content) VALUES(18, 'two five'); + INSERT INTO t1 (rowid, content) VALUES(19, 'one two five'); + DELETE FROM t1 WHERE rowid = 16; + INSERT INTO t1 (rowid, content) VALUES(20, 'three five'); + INSERT INTO t1 (rowid, content) VALUES(21, 'one three five'); + INSERT INTO t1 (rowid, content) VALUES(22, 'two three five'); + DELETE FROM t1 WHERE rowid = 19; + DELETE FROM t1 WHERE rowid = 22; +} + +do_test fts2f-1.1 { + execsql {SELECT COUNT(*) FROM t1} +} {14} + +do_test fts2e-2.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {3 5 9 11 15 17 21} + +do_test fts2e-2.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'} +} {2 3 6 11 14 15 18} + +do_test fts2e-2.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'} +} {5 6 12 14 15 20 21} + +do_test fts2e-2.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'} +} {8 9 11 12 14 15} + +do_test fts2e-2.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'} +} {17 18 20 21} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2f.test b/components/external/SQLite-3.8.1/test/fts2f.test new file mode 100644 index 0000000000000000000000000000000000000000..49cff14664af2fb9567e4dc2619631acb86e5c03 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2f.test @@ -0,0 +1,90 @@ +# 2006 October 19 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing updates in the FTS2 module. +# +# $Id: fts2f.test,v 1.2 2007/02/23 00:14:06 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# Construct a full-text search table containing keywords which are the +# ordinal numbers of the bit positions set for a sequence of integers, +# which are used for the rowid. There are a total of 31 INSERT, +# UPDATE, and DELETE statements, so that we'll test both the +# segmentMerge() merge (over the first 16) and the termSelect() merge +# (over the level-1 segment and 15 level-0 segments). +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(content); + INSERT INTO t1 (rowid, content) VALUES(1, 'one'); + INSERT INTO t1 (rowid, content) VALUES(2, 'two'); + INSERT INTO t1 (rowid, content) VALUES(3, 'one two'); + INSERT INTO t1 (rowid, content) VALUES(4, 'three'); + INSERT INTO t1 (rowid, content) VALUES(5, 'one three'); + INSERT INTO t1 (rowid, content) VALUES(6, 'two three'); + INSERT INTO t1 (rowid, content) VALUES(7, 'one two three'); + DELETE FROM t1 WHERE rowid = 4; + INSERT INTO t1 (rowid, content) VALUES(8, 'four'); + UPDATE t1 SET content = 'update one three' WHERE rowid = 1; + INSERT INTO t1 (rowid, content) VALUES(9, 'one four'); + INSERT INTO t1 (rowid, content) VALUES(10, 'two four'); + DELETE FROM t1 WHERE rowid = 7; + INSERT INTO t1 (rowid, content) VALUES(11, 'one two four'); + INSERT INTO t1 (rowid, content) VALUES(12, 'three four'); + INSERT INTO t1 (rowid, content) VALUES(13, 'one three four'); + DELETE FROM t1 WHERE rowid = 10; + INSERT INTO t1 (rowid, content) VALUES(14, 'two three four'); + INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four'); + UPDATE t1 SET content = 'update two five' WHERE rowid = 8; + INSERT INTO t1 (rowid, content) VALUES(16, 'five'); + DELETE FROM t1 WHERE rowid = 13; + INSERT INTO t1 (rowid, content) VALUES(17, 'one five'); + INSERT INTO t1 (rowid, content) VALUES(18, 'two five'); + INSERT INTO t1 (rowid, content) VALUES(19, 'one two five'); + DELETE FROM t1 WHERE rowid = 16; + INSERT INTO t1 (rowid, content) VALUES(20, 'three five'); + INSERT INTO t1 (rowid, content) VALUES(21, 'one three five'); + INSERT INTO t1 (rowid, content) VALUES(22, 'two three five'); + DELETE FROM t1 WHERE rowid = 19; + UPDATE t1 SET content = 'update' WHERE rowid = 15; +} + +do_test fts2f-1.1 { + execsql {SELECT COUNT(*) FROM t1} +} {16} + +do_test fts2f-2.0 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'update'} +} {1 8 15} + +do_test fts2f-2.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {1 3 5 9 11 17 21} + +do_test fts2f-2.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'} +} {2 3 6 8 11 14 18 22} + +do_test fts2f-2.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'} +} {1 5 6 12 14 20 21 22} + +do_test fts2f-2.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'} +} {9 11 12 14} + +do_test fts2f-2.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'} +} {8 17 18 20 21 22} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2g.test b/components/external/SQLite-3.8.1/test/fts2g.test new file mode 100644 index 0000000000000000000000000000000000000000..4cffb91fc7f1f4359e4c2339b0f4f4a672b75a13 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2g.test @@ -0,0 +1,93 @@ +# 2006 October 19 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing handling of edge cases for various doclist +# merging functions in the FTS2 module query logic. +# +# $Id: fts2g.test,v 1.3 2007/11/16 00:23:08 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(content); + INSERT INTO t1 (rowid, content) VALUES(1, 'this is a test'); + INSERT INTO t1 (rowid, content) VALUES(2, 'also a test'); +} + +# No hits at all. Returns empty doclists from termSelect(). +do_test fts2g-1.1 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something'} +} {} + +# Empty left in docListExceptMerge(). +do_test fts2g-1.2 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH '-this something'} +} {} + +# Empty right in docListExceptMerge(). +do_test fts2g-1.3 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this -something'} +} {1} + +# Empty left in docListPhraseMerge(). +do_test fts2g-1.4 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"this something"'} +} {} + +# Empty right in docListPhraseMerge(). +do_test fts2g-1.5 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"something is"'} +} {} + +# Empty left in docListOrMerge(). +do_test fts2g-1.6 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something OR this'} +} {1} + +# Empty right in docListOrMerge(). +do_test fts2g-1.7 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this OR something'} +} {1} + +# Empty left in docListAndMerge(). +do_test fts2g-1.8 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something this'} +} {} + +# Empty right in docListAndMerge(). +do_test fts2g-1.9 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this something'} +} {} + +# No support for all-except queries. +do_test fts2g-1.10 { + catchsql {SELECT rowid FROM t1 WHERE t1 MATCH '-this -something'} +} {1 {SQL logic error or missing database}} + +# Test that docListOrMerge() correctly handles reaching the end of one +# doclist before it reaches the end of the other. +do_test fts2g-1.11 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this OR also'} +} {1 2} +do_test fts2g-1.12 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'also OR this'} +} {1 2} + +# Empty left and right in docListOrMerge(). Each term matches neither +# row, and when combined there was an assertion failure. +do_test fts2g-1.13 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something OR nothing'} +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2h.test b/components/external/SQLite-3.8.1/test/fts2h.test new file mode 100644 index 0000000000000000000000000000000000000000..72561d85bc41dfa4c86124452817d6b9c5935641 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2h.test @@ -0,0 +1,76 @@ +# 2006 October 31 (scaaarey) +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# here is testing correct handling of excessively long terms. +# +# $Id: fts2h.test,v 1.1 2006/11/29 21:03:01 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# Generate a term of len copies of char. +proc bigterm {char len} { + for {set term ""} {$len>0} {incr len -1} { + append term $char + } + return $term +} + +# Generate a document of bigterms based on characters from the list +# chars. +proc bigtermdoc {chars len} { + set doc "" + foreach char $chars { + append doc " " [bigterm $char $len] + } + return $doc +} + +set len 5000 +set doc1 [bigtermdoc {a b c d} $len] +set doc2 [bigtermdoc {b d e f} $len] +set doc3 [bigtermdoc {a c e} $len] + +set aterm [bigterm a $len] +set bterm [bigterm b $len] +set xterm [bigterm x $len] + +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(content); + INSERT INTO t1 (rowid, content) VALUES(1, $doc1); + INSERT INTO t1 (rowid, content) VALUES(2, $doc2); + INSERT INTO t1 (rowid, content) VALUES(3, $doc3); +} + +# No hits at all. Returns empty doclists from termSelect(). +do_test fts2h-1.1 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something'} +} {} + +do_test fts2h-1.2 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH $aterm} +} {1 3} + +do_test fts2h-1.2 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH $xterm} +} {} + +do_test fts2h-1.3 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '$aterm -$xterm'" +} {1 3} + +do_test fts2h-1.4 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"$aterm $bterm\"'" +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2i.test b/components/external/SQLite-3.8.1/test/fts2i.test new file mode 100644 index 0000000000000000000000000000000000000000..e732e6a8a9e46ee2fcfe7c494c4287427c74c4da --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2i.test @@ -0,0 +1,87 @@ +# 2007 January 17 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite fts2 library. The +# focus here is testing handling of UPDATE when using UTF-16-encoded +# databases. +# +# $Id: fts2i.test,v 1.2 2007/01/24 03:46:35 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# Return the UTF-16 representation of the supplied UTF-8 string $str. +# If $nt is true, append two 0x00 bytes as a nul terminator. +# NOTE(shess) Copied from capi3.test. +proc utf16 {str {nt 1}} { + set r [encoding convertto unicode $str] + if {$nt} { + append r "\x00\x00" + } + return $r +} + +db eval { + PRAGMA encoding = "UTF-16le"; + CREATE VIRTUAL TABLE t1 USING fts2(content); +} + +do_test fts2i-1.0 { + execsql {PRAGMA encoding} +} {UTF-16le} + +do_test fts2i-1.1 { + execsql {INSERT INTO t1 (rowid, content) VALUES(1, 'one')} + execsql {SELECT content FROM t1 WHERE rowid = 1} +} {one} + +do_test fts2i-1.2 { + set sql "INSERT INTO t1 (rowid, content) VALUES(2, 'two')" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 2} +} {two} + +do_test fts2i-1.3 { + set sql "INSERT INTO t1 (rowid, content) VALUES(3, 'three')" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + set sql "UPDATE t1 SET content = 'trois' WHERE rowid = 3" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 3} +} {trois} + +do_test fts2i-1.4 { + set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(4, 'four')}] + set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 4} +} {four} + +do_test fts2i-1.5 { + set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(5, 'five')}] + set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + set sql "UPDATE t1 SET content = 'cinq' WHERE rowid = 5" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 5} +} {cinq} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2j.test b/components/external/SQLite-3.8.1/test/fts2j.test new file mode 100644 index 0000000000000000000000000000000000000000..a8a2c07c18e364b1c24fd4c41ed097d672bd2c47 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2j.test @@ -0,0 +1,89 @@ +# 2007 February 6 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. This +# tests creating fts2 tables in an attached database. +# +# $Id: fts2j.test,v 1.1 2007/02/07 01:01:18 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# Clean up anything left over from a previous pass. +forcedelete test2.db +forcedelete test2.db-journal +sqlite3 db2 test2.db + +db eval { + CREATE VIRTUAL TABLE t3 USING fts2(content); + INSERT INTO t3 (rowid, content) VALUES(1, "hello world"); +} + +db2 eval { + CREATE VIRTUAL TABLE t1 USING fts2(content); + INSERT INTO t1 (rowid, content) VALUES(1, "hello world"); + INSERT INTO t1 (rowid, content) VALUES(2, "hello there"); + INSERT INTO t1 (rowid, content) VALUES(3, "cruel world"); +} + +# This has always worked because the t1_* tables used by fts2 will be +# the defaults. +do_test fts2j-1.1 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + SELECT rowid FROM t1 WHERE t1 MATCH 'hello'; + DETACH DATABASE two; + } +} {1 2} +# Make certain we're detached if there was an error. +catch {db eval {DETACH DATABASE two}} + +# In older code, this appears to work fine, but the t2_* tables used +# by fts2 will be created in database 'main' instead of database +# 'two'. It appears to work fine because the tables end up being the +# defaults, but obviously is badly broken if you hope to use things +# other than in the exact same ATTACH setup. +do_test fts2j-1.2 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + CREATE VIRTUAL TABLE two.t2 USING fts2(content); + INSERT INTO t2 (rowid, content) VALUES(1, "hello world"); + INSERT INTO t2 (rowid, content) VALUES(2, "hello there"); + INSERT INTO t2 (rowid, content) VALUES(3, "cruel world"); + SELECT rowid FROM t2 WHERE t2 MATCH 'hello'; + DETACH DATABASE two; + } +} {1 2} +catch {db eval {DETACH DATABASE two}} + +# In older code, this broke because the fts2 code attempted to create +# t3_* tables in database 'main', but they already existed. Normally +# this wouldn't happen without t3 itself existing, in which case the +# fts2 code would never be called in the first place. +do_test fts2j-1.3 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + + CREATE VIRTUAL TABLE two.t3 USING fts2(content); + INSERT INTO two.t3 (rowid, content) VALUES(2, "hello there"); + INSERT INTO two.t3 (rowid, content) VALUES(3, "cruel world"); + SELECT rowid FROM two.t3 WHERE t3 MATCH 'hello'; + + DETACH DATABASE two; + } db2 +} {2} +catch {db eval {DETACH DATABASE two}} + +catch {db2 close} +forcedelete test2.db + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2k.test b/components/external/SQLite-3.8.1/test/fts2k.test new file mode 100644 index 0000000000000000000000000000000000000000..e7d5f0dff41afdfd401f6a2b5a9a84e80fab0ea4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2k.test @@ -0,0 +1,105 @@ +# 2007 March 9 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. These +# make sure that fts2 insertion buffering is fully transparent when +# using transactions. +# +# $Id: fts2k.test,v 1.2 2007/08/10 23:47:04 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(content); + INSERT INTO t1 (rowid, content) VALUES(1, "hello world"); + INSERT INTO t1 (rowid, content) VALUES(2, "hello there"); + INSERT INTO t1 (rowid, content) VALUES(3, "cruel world"); +} + +# Test that possibly-buffered inserts went through after commit. +do_test fts2k-1.1 { + execsql { + BEGIN TRANSACTION; + INSERT INTO t1 (rowid, content) VALUES(4, "false world"); + INSERT INTO t1 (rowid, content) VALUES(5, "false door"); + COMMIT TRANSACTION; + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + } +} {1 3 4} + +# Test that buffered inserts are seen by selects in the same +# transaction. +do_test fts2k-1.2 { + execsql { + BEGIN TRANSACTION; + INSERT INTO t1 (rowid, content) VALUES(6, "another world"); + INSERT INTO t1 (rowid, content) VALUES(7, "another test"); + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + COMMIT TRANSACTION; + } +} {1 3 4 6} + +# Test that buffered inserts are seen within a transaction. This is +# really the same test as 1.2. +do_test fts2k-1.3 { + execsql { + BEGIN TRANSACTION; + INSERT INTO t1 (rowid, content) VALUES(8, "second world"); + INSERT INTO t1 (rowid, content) VALUES(9, "second sight"); + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + ROLLBACK TRANSACTION; + } +} {1 3 4 6 8} + +# Double-check that the previous result doesn't persist past the +# rollback! +do_test fts2k-1.4 { + execsql { + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + } +} {1 3 4 6} + +# Test it all together. +do_test fts2k-1.5 { + execsql { + BEGIN TRANSACTION; + INSERT INTO t1 (rowid, content) VALUES(10, "second world"); + INSERT INTO t1 (rowid, content) VALUES(11, "second sight"); + ROLLBACK TRANSACTION; + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + } +} {1 3 4 6} + +# Test that the obvious case works. +do_test fts2k-1.6 { + execsql { + BEGIN; + INSERT INTO t1 (rowid, content) VALUES(12, "third world"); + COMMIT; + SELECT rowid FROM t1 WHERE t1 MATCH 'third'; + } +} {12} + +# This is exactly the same as the previous test, except that older +# code loses the INSERT due to an SQLITE_SCHEMA error. +do_test fts2k-1.7 { + execsql { + BEGIN; + INSERT INTO t1 (rowid, content) VALUES(13, "third dimension"); + CREATE TABLE x (c); + COMMIT; + SELECT rowid FROM t1 WHERE t1 MATCH 'dimension'; + } +} {13} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2l.test b/components/external/SQLite-3.8.1/test/fts2l.test new file mode 100644 index 0000000000000000000000000000000000000000..42f5ba134f53c1460505fa62b0bf2ce19bae4547 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2l.test @@ -0,0 +1,69 @@ +# 2007 March 28 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing isspace/isalnum/tolower problems with the +# FTS2 module. Unfortunately, this code isn't a really principled set +# of tests, because it is impossible to know where new uses of these +# functions might appear. +# +# $Id: fts2l.test,v 1.2 2007/12/13 21:54:11 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# Tests that startsWith() (calls isspace, tolower, isalnum) can handle +# hi-bit chars. parseSpec() also calls isalnum here. +do_test fts2l-1.1 { + execsql "CREATE VIRTUAL TABLE t1 USING fts2(content, \x80)" +} {} + +# Additionally tests isspace() call in getToken(), and isalnum() call +# in tokenListToIdList(). +do_test fts2l-1.2 { + catch { + execsql "CREATE VIRTUAL TABLE t2 USING fts2(content, tokenize \x80)" + } + sqlite3_errmsg $DB +} "unknown tokenizer: \x80" + +# Additionally test final isalnum() in startsWith(). +do_test fts2l-1.3 { + execsql "CREATE VIRTUAL TABLE t3 USING fts2(content, tokenize\x80)" +} {} + +# The snippet-generation code has calls to isspace() which are sort of +# hard to get to. It finds convenient breakpoints by starting ~40 +# chars before and after the matched term, and scanning ~10 chars +# around that position for isspace() characters. The long word with +# embedded hi-bit chars causes one of these isspace() calls to be +# exercised. The version with a couple extra spaces should cause the +# other isspace() call to be exercised. [Both cases have been tested +# in the debugger, but I'm hoping to continue to catch it if simple +# constant changes change things slightly. +# +# The trailing and leading hi-bit chars help with code which tests for +# isspace() to coalesce multiple spaces. + +set word "\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80" +set phrase1 "$word $word $word target $word $word $word" +set phrase2 "$word $word $word target $word $word $word" + +db eval {CREATE VIRTUAL TABLE t4 USING fts2(content)} +db eval "INSERT INTO t4 (content) VALUES ('$phrase1')" +db eval "INSERT INTO t4 (content) VALUES ('$phrase2')" + +do_test fts2l-1.4 { + execsql {SELECT rowid, length(snippet(t4)) FROM t4 WHERE t4 MATCH 'target'} +} {1 111 2 117} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2m.test b/components/external/SQLite-3.8.1/test/fts2m.test new file mode 100644 index 0000000000000000000000000000000000000000..6552637a62ce703fbd24ebe3593cec0fd5714dd4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2m.test @@ -0,0 +1,65 @@ +# 2007 April 9 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. fts2 +# DELETE handling assumed all fields were non-null. This was not +# the intention at all. +# +# $Id: fts2m.test,v 1.1 2007/04/09 20:45:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(col_a, col_b); + + INSERT INTO t1(rowid, col_a, col_b) VALUES(1, 'testing', 'testing'); + INSERT INTO t1(rowid, col_a, col_b) VALUES(2, 'only a', null); + INSERT INTO t1(rowid, col_a, col_b) VALUES(3, null, 'only b'); + INSERT INTO t1(rowid, col_a, col_b) VALUES(4, null, null); +} + +do_test fts2m-1.0 { + execsql { + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {2 2 4} + +do_test fts2m-1.1 { + execsql { + DELETE FROM t1 WHERE rowid = 1; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {1 1 3} + +do_test fts2m-1.2 { + execsql { + DELETE FROM t1 WHERE rowid = 2; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {0 1 2} + +do_test fts2m-1.3 { + execsql { + DELETE FROM t1 WHERE rowid = 3; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {0 0 1} + +do_test fts2m-1.4 { + execsql { + DELETE FROM t1 WHERE rowid = 4; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {0 0 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2n.test b/components/external/SQLite-3.8.1/test/fts2n.test new file mode 100644 index 0000000000000000000000000000000000000000..ca0b4fe9ffb26e8c665be2d6c3b5dd6c4c95b35b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2n.test @@ -0,0 +1,196 @@ +# 2007 April 26 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements tests for prefix-searching in the fts2 +# component of the SQLite library. +# +# $Id: fts2n.test,v 1.2 2007/12/13 21:54:11 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +# A large string to prime the pump with. +set text { + Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas + iaculis mollis ipsum. Praesent rhoncus placerat justo. Duis non quam + sed turpis posuere placerat. Curabitur et lorem in lorem porttitor + aliquet. Pellentesque bibendum tincidunt diam. Vestibulum blandit + ante nec elit. In sapien diam, facilisis eget, dictum sed, viverra + at, felis. Vestibulum magna. Sed magna dolor, vestibulum rhoncus, + ornare vel, vulputate sit amet, felis. Integer malesuada, tellus at + luctus gravida, diam nunc porta nibh, nec imperdiet massa metus eu + lectus. Aliquam nisi. Nunc fringilla nulla at lectus. Suspendisse + potenti. Cum sociis natoque penatibus et magnis dis parturient + montes, nascetur ridiculus mus. Pellentesque odio nulla, feugiat eu, + suscipit nec, consequat quis, risus. +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(c); + + INSERT INTO t1(rowid, c) VALUES(1, $text); + INSERT INTO t1(rowid, c) VALUES(2, 'Another lovely row'); +} + +# Exact match +do_test fts2n-1.1 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lorem'" +} {1} + +# And a prefix +do_test fts2n-1.2 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lore*'" +} {1} + +# Prefix includes exact match +do_test fts2n-1.3 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lorem*'" +} {1} + +# Make certain everything isn't considered a prefix! +do_test fts2n-1.4 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lore'" +} {} + +# Prefix across multiple rows. +do_test fts2n-1.5 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lo*'" +} {1 2} + +# Likewise, with multiple hits in one document. +do_test fts2n-1.6 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'l*'" +} {1 2} + +# Prefix which should only hit one document. +do_test fts2n-1.7 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lov*'" +} {2} + +# * not at end is dropped. +do_test fts2n-1.8 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lo *'" +} {} + +# Stand-alone * is dropped. +do_test fts2n-1.9 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '*'" +} {} + +# Phrase-query prefix. +do_test fts2n-1.10 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"lovely r*\"'" +} {2} +do_test fts2n-1.11 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"lovely r\"'" +} {} + +# Phrase query with multiple prefix matches. +do_test fts2n-1.12 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"a* l*\"'" +} {1 2} + +# Phrase query with multiple prefix matches. +do_test fts2n-1.13 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"a* l* row\"'" +} {2} + + + + +# Test across updates (and, by implication, deletes). + +# Version of text without "lorem". +regsub -all {[Ll]orem} $text '' ntext + +db eval { + CREATE VIRTUAL TABLE t2 USING fts2(c); + + INSERT INTO t2(rowid, c) VALUES(1, $text); + INSERT INTO t2(rowid, c) VALUES(2, 'Another lovely row'); + UPDATE t2 SET c = $ntext WHERE rowid = 1; +} + +# Can't see lorem as an exact match. +do_test fts2n-2.1 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lorem'" +} {} + +# Can't see a prefix of lorem, either. +do_test fts2n-2.2 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lore*'" +} {} + +# Can see lovely in the other document. +do_test fts2n-2.3 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lo*'" +} {2} + +# Can still see other hits. +do_test fts2n-2.4 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'l*'" +} {1 2} + +# Prefix which should only hit one document. +do_test fts2n-2.5 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lov*'" +} {2} + + + +# Test with a segment which will have multiple levels in the tree. + +# Build a big document with lots of unique terms. +set bigtext $text +foreach c {a b c d e} { + regsub -all {[A-Za-z]+} $bigtext "&$c" t + append bigtext $t +} + +# Populate a table with many copies of the big document, so that we +# can test the number of hits found. Populate $ret with the expected +# hit counts for each row. offsets() returns 4 elements for every +# hit. We'll have 6 hits for row 1, 1 for row 2, and 6*(2^5)==192 for +# $bigtext. +set ret {6 1} +db eval { + BEGIN; + CREATE VIRTUAL TABLE t3 USING fts2(c); + + INSERT INTO t3(rowid, c) VALUES(1, $text); + INSERT INTO t3(rowid, c) VALUES(2, 'Another lovely row'); +} +for {set i 0} {$i<100} {incr i} { + db eval {INSERT INTO t3(rowid, c) VALUES(3+$i, $bigtext)} + lappend ret 192 +} +db eval {COMMIT;} + +# Test that we get the expected number of hits. +do_test fts2n-3.1 { + set t {} + db eval {SELECT offsets(t3) as o FROM t3 WHERE t3 MATCH 'l*'} { + set l [llength $o] + lappend t [expr {$l/4}] + } + set t +} $ret + +# TODO(shess) It would be useful to test a couple edge cases, but I +# don't know if we have the precision to manage it from here at this +# time. Prefix hits can cross leaves, which the code above _should_ +# hit by virtue of size. There are two variations on this. If the +# tree is 2 levels high, the code will find the leaf-node extent +# directly, but if its higher, the code will have to follow two +# separate interior branches down the tree. Both should be tested. + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2o.test b/components/external/SQLite-3.8.1/test/fts2o.test new file mode 100644 index 0000000000000000000000000000000000000000..63e71b958a43f8df1b7b23bf7fde5e5f94995492 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2o.test @@ -0,0 +1,169 @@ +# 2007 June 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS2 module. +# +# $Id: fts2o.test,v 1.4 2007/07/02 10:16:50 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is not defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +#--------------------------------------------------------------------- +# These tests, fts2o-1.*, test that ticket #2429 is fixed. +# +db eval { + CREATE VIRTUAL TABLE t1 USING fts2(a, b, c); + INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one four two'); +} +do_test fts2o-1.1 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE c MATCH 'four'; + } +} {1 {one four two}} +do_test fts2o-1.2 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE b MATCH 'four'; + } +} {1 {one four}} +do_test fts2o-1.3 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE a MATCH 'four'; + } +} {1 {one three four}} + +#--------------------------------------------------------------------- +# Test that it is possible to rename an fts2 table. +# +do_test fts2o-2.1 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {t1 t1_content t1_segments t1_segdir} +do_test fts2o-2.2 { + execsql { ALTER TABLE t1 RENAME to fts_t1; } +} {} +do_test fts2o-2.3 { + execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; } +} {1 {one three four}} +do_test fts2o-2.4 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir} + +# See what happens when renaming the fts2 table fails. +# +do_test fts2o-2.5 { + catchsql { + CREATE TABLE t1_segdir(a, b, c); + ALTER TABLE fts_t1 RENAME to t1; + } +} {1 {SQL logic error or missing database}} +do_test fts2o-2.6 { + execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; } +} {1 {one three four}} +do_test fts2o-2.7 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir t1_segdir} + +# See what happens when renaming the fts2 table fails inside a transaction. +# +do_test fts2o-2.8 { + execsql { + BEGIN; + INSERT INTO fts_t1(a, b, c) VALUES('one two three', 'one four', 'one two'); + } +} {} +do_test fts2o-2.9 { + catchsql { + ALTER TABLE fts_t1 RENAME to t1; + } +} {1 {SQL logic error or missing database}} +do_test fts2o-2.10 { + execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; } +} {1 {one three four}} +do_test fts2o-2.11 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir t1_segdir} +do_test fts2o-2.12 { + execsql COMMIT + execsql {SELECT a FROM fts_t1} +} {{one three four} {one two three}} +do_test fts2o-2.12 { + execsql { SELECT a, b, c FROM fts_t1 WHERE c MATCH 'four'; } +} {{one three four} {one four} {one four two}} + +#------------------------------------------------------------------- +# Close, delete and reopen the database. The following test should +# be run on an initially empty db. +# +db close +forcedelete test.db test.db-journal +sqlite3 db test.db + +do_test fts2o-3.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts2(a, b, c); + INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one two'); + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + } +} {{one three four} {one four} {one two}} + +# This test was crashing at one point. +# +do_test fts2o-3.2 { + execsql { + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + CREATE TABLE t3(a, b, c); + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + } +} {{one three four} {one four} {one two} {one three four} {one four} {one two}} + +#--------------------------------------------------------------------- +# Test that it is possible to rename an fts2 table in an attached +# database. +# +forcedelete test2.db test2.db-journal + +do_test fts2o-3.1 { + execsql { + ATTACH 'test2.db' AS aux; + CREATE VIRTUAL TABLE aux.t1 USING fts2(a, b, c); + INSERT INTO aux.t1(a, b, c) VALUES( + 'neung song sahm', 'neung see', 'neung see song' + ); + } +} {} + +do_test fts2o-3.2 { + execsql { SELECT a, b, c FROM aux.t1 WHERE a MATCH 'song'; } +} {{neung song sahm} {neung see} {neung see song}} + +do_test fts2o-3.3 { + execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; } +} {{one three four} {one four} {one two}} + +do_test fts2o-3.4 { + execsql { ALTER TABLE aux.t1 RENAME TO t2 } +} {} + +do_test fts2o-3.2 { + execsql { SELECT a, b, c FROM t2 WHERE a MATCH 'song'; } +} {{neung song sahm} {neung see} {neung see song}} + +do_test fts2o-3.3 { + execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; } +} {{one three four} {one four} {one two}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2p.test b/components/external/SQLite-3.8.1/test/fts2p.test new file mode 100644 index 0000000000000000000000000000000000000000..38a8079d8ff0b3cfe665a1ccc588d64884f6b2d9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2p.test @@ -0,0 +1,357 @@ +# 2008 June 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file exercises some new testing functions in the FTS2 module, +# and then uses them to do some basic tests that FTS2 is internally +# working as expected. +# +# $Id: fts2p.test,v 1.1 2008/07/22 23:32:28 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is not defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +#************************************************************************* +# Probe to see if support for these functions is compiled in. +# TODO(shess): Change main.mk to do the right thing and remove this test. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'x'); +} + +set s {SELECT dump_terms(t1, 1) FROM t1 LIMIT 1} +set r {1 {unable to use function dump_terms in the requested context}} +if {[catchsql $s]==$r} { + finish_test + return +} + +#************************************************************************* +# Test that the new functions give appropriate errors. +do_test fts2p-0.0 { + catchsql { + SELECT dump_terms(t1, 1) FROM t1 LIMIT 1; + } +} {1 {dump_terms: incorrect arguments}} + +do_test fts2p-0.1 { + catchsql { + SELECT dump_terms(t1, 0, 0, 0) FROM t1 LIMIT 1; + } +} {1 {dump_terms: incorrect arguments}} + +do_test fts2p-0.2 { + catchsql { + SELECT dump_terms(1, t1) FROM t1 LIMIT 1; + } +} {1 {unable to use function dump_terms in the requested context}} + +do_test fts2p-0.3 { + catchsql { + SELECT dump_terms(t1, 16, 16) FROM t1 LIMIT 1; + } +} {1 {dump_terms: segment not found}} + +do_test fts2p-0.4 { + catchsql { + SELECT dump_doclist(t1) FROM t1 LIMIT 1; + } +} {1 {dump_doclist: incorrect arguments}} + +do_test fts2p-0.5 { + catchsql { + SELECT dump_doclist(t1, NULL) FROM t1 LIMIT 1; + } +} {1 {dump_doclist: empty second argument}} + +do_test fts2p-0.6 { + catchsql { + SELECT dump_doclist(t1, '') FROM t1 LIMIT 1; + } +} {1 {dump_doclist: empty second argument}} + +do_test fts2p-0.7 { + catchsql { + SELECT dump_doclist(t1, 'a', 0) FROM t1 LIMIT 1; + } +} {1 {dump_doclist: incorrect arguments}} + +do_test fts2p-0.8 { + catchsql { + SELECT dump_doclist(t1, 'a', 0, 0, 0) FROM t1 LIMIT 1; + } +} {1 {dump_doclist: incorrect arguments}} + +do_test fts2p-0.9 { + catchsql { + SELECT dump_doclist(t1, 'a', 16, 16) FROM t1 LIMIT 1; + } +} {1 {dump_doclist: segment not found}} + +#************************************************************************* +# Utility function to check for the expected terms in the segment +# level/index. _all version does same but for entire index. +proc check_terms {test level index terms} { + # TODO(shess): Figure out why uplevel in do_test can't catch + # $level and $index directly. + set ::level $level + set ::index $index + do_test $test.terms { + execsql { + SELECT dump_terms(t1, $::level, $::index) FROM t1 LIMIT 1; + } + } [list $terms] +} +proc check_terms_all {test terms} { + do_test $test.terms { + execsql { + SELECT dump_terms(t1) FROM t1 LIMIT 1; + } + } [list $terms] +} + +# Utility function to check for the expected doclist for the term in +# segment level/index. _all version does same for entire index. +proc check_doclist {test level index term doclist} { + # TODO(shess): Again, why can't the non-:: versions work? + set ::term $term + set ::level $level + set ::index $index + do_test $test { + execsql { + SELECT dump_doclist(t1, $::term, $::level, $::index) FROM t1 LIMIT 1; + } + } [list $doclist] +} +proc check_doclist_all {test term doclist} { + set ::term $term + do_test $test { + execsql { + SELECT dump_doclist(t1, $::term) FROM t1 LIMIT 1; + } + } [list $doclist] +} + +#************************************************************************* +# Test the segments resulting from straight-forward inserts. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); +} + +# Check for expected segments and expected matches. +do_test fts2p-1.0.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0 0 1 0 2} +do_test fts2p-1.0.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid; + } +} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \ + {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \ + {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}] + +# Check the specifics of the segments constructed. +# Logical view of entire index. +check_terms_all fts2p-1.0.1 {a is test that this was} +check_doclist_all fts2p-1.0.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist_all fts2p-1.0.1.2 is {[1 0[1]] [3 0[1]]} +check_doclist_all fts2p-1.0.1.3 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist_all fts2p-1.0.1.4 that {[2 0[0]]} +check_doclist_all fts2p-1.0.1.5 this {[1 0[0]] [3 0[0]]} +check_doclist_all fts2p-1.0.1.6 was {[2 0[1]]} + +# Segment 0,0 +check_terms fts2p-1.0.2 0 0 {a is test this} +check_doclist fts2p-1.0.2.1 0 0 a {[1 0[2]]} +check_doclist fts2p-1.0.2.2 0 0 is {[1 0[1]]} +check_doclist fts2p-1.0.2.3 0 0 test {[1 0[3]]} +check_doclist fts2p-1.0.2.4 0 0 this {[1 0[0]]} + +# Segment 0,1 +check_terms fts2p-1.0.3 0 1 {a test that was} +check_doclist fts2p-1.0.3.1 0 1 a {[2 0[2]]} +check_doclist fts2p-1.0.3.2 0 1 test {[2 0[3]]} +check_doclist fts2p-1.0.3.3 0 1 that {[2 0[0]]} +check_doclist fts2p-1.0.3.4 0 1 was {[2 0[1]]} + +# Segment 0,2 +check_terms fts2p-1.0.4 0 2 {a is test this} +check_doclist fts2p-1.0.4.1 0 2 a {[3 0[2]]} +check_doclist fts2p-1.0.4.2 0 2 is {[3 0[1]]} +check_doclist fts2p-1.0.4.3 0 2 test {[3 0[3]]} +check_doclist fts2p-1.0.4.4 0 2 this {[3 0[0]]} + +#************************************************************************* +# Test the segments resulting from inserts followed by a delete. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE rowid = 1; +} + +do_test fts2p-1.1.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0 0 1 0 2 0 3} +do_test fts2p-1.1.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}} + +check_terms_all fts2p-1.1.1 {a is test that this was} +check_doclist_all fts2p-1.1.1.1 a {[2 0[2]] [3 0[2]]} +check_doclist_all fts2p-1.1.1.2 is {[3 0[1]]} +check_doclist_all fts2p-1.1.1.3 test {[2 0[3]] [3 0[3]]} +check_doclist_all fts2p-1.1.1.4 that {[2 0[0]]} +check_doclist_all fts2p-1.1.1.5 this {[3 0[0]]} +check_doclist_all fts2p-1.1.1.6 was {[2 0[1]]} + +check_terms fts2p-1.1.2 0 0 {a is test this} +check_doclist fts2p-1.1.2.1 0 0 a {[1 0[2]]} +check_doclist fts2p-1.1.2.2 0 0 is {[1 0[1]]} +check_doclist fts2p-1.1.2.3 0 0 test {[1 0[3]]} +check_doclist fts2p-1.1.2.4 0 0 this {[1 0[0]]} + +check_terms fts2p-1.1.3 0 1 {a test that was} +check_doclist fts2p-1.1.3.1 0 1 a {[2 0[2]]} +check_doclist fts2p-1.1.3.2 0 1 test {[2 0[3]]} +check_doclist fts2p-1.1.3.3 0 1 that {[2 0[0]]} +check_doclist fts2p-1.1.3.4 0 1 was {[2 0[1]]} + +check_terms fts2p-1.1.4 0 2 {a is test this} +check_doclist fts2p-1.1.4.1 0 2 a {[3 0[2]]} +check_doclist fts2p-1.1.4.2 0 2 is {[3 0[1]]} +check_doclist fts2p-1.1.4.3 0 2 test {[3 0[3]]} +check_doclist fts2p-1.1.4.4 0 2 this {[3 0[0]]} + +check_terms fts2p-1.1.5 0 3 {a is test this} +check_doclist fts2p-1.1.5.1 0 3 a {[1]} +check_doclist fts2p-1.1.5.2 0 3 is {[1]} +check_doclist fts2p-1.1.5.3 0 3 test {[1]} +check_doclist fts2p-1.1.5.4 0 3 this {[1]} + +#************************************************************************* +# Test results when all references to certain tokens are deleted. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE rowid IN (1,3); +} + +# Still 4 segments because 0,3 will contain deletes for rowid 1 and 3. +do_test fts2p-1.2.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0 0 1 0 2 0 3} +do_test fts2p-1.2.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}} + +check_terms_all fts2p-1.2.1 {a is test that this was} +check_doclist_all fts2p-1.2.1.1 a {[2 0[2]]} +check_doclist_all fts2p-1.2.1.2 is {} +check_doclist_all fts2p-1.2.1.3 test {[2 0[3]]} +check_doclist_all fts2p-1.2.1.4 that {[2 0[0]]} +check_doclist_all fts2p-1.2.1.5 this {} +check_doclist_all fts2p-1.2.1.6 was {[2 0[1]]} + +check_terms fts2p-1.2.2 0 0 {a is test this} +check_doclist fts2p-1.2.2.1 0 0 a {[1 0[2]]} +check_doclist fts2p-1.2.2.2 0 0 is {[1 0[1]]} +check_doclist fts2p-1.2.2.3 0 0 test {[1 0[3]]} +check_doclist fts2p-1.2.2.4 0 0 this {[1 0[0]]} + +check_terms fts2p-1.2.3 0 1 {a test that was} +check_doclist fts2p-1.2.3.1 0 1 a {[2 0[2]]} +check_doclist fts2p-1.2.3.2 0 1 test {[2 0[3]]} +check_doclist fts2p-1.2.3.3 0 1 that {[2 0[0]]} +check_doclist fts2p-1.2.3.4 0 1 was {[2 0[1]]} + +check_terms fts2p-1.2.4 0 2 {a is test this} +check_doclist fts2p-1.2.4.1 0 2 a {[3 0[2]]} +check_doclist fts2p-1.2.4.2 0 2 is {[3 0[1]]} +check_doclist fts2p-1.2.4.3 0 2 test {[3 0[3]]} +check_doclist fts2p-1.2.4.4 0 2 this {[3 0[0]]} + +check_terms fts2p-1.2.5 0 3 {a is test this} +check_doclist fts2p-1.2.5.1 0 3 a {[1] [3]} +check_doclist fts2p-1.2.5.2 0 3 is {[1] [3]} +check_doclist fts2p-1.2.5.3 0 3 test {[1] [3]} +check_doclist fts2p-1.2.5.4 0 3 this {[1] [3]} + +#************************************************************************* +# Test results when everything is optimized manually. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE rowid IN (1,3); + DROP TABLE IF EXISTS t1old; + ALTER TABLE t1 RENAME TO t1old; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) SELECT rowid, c FROM t1old; + DROP TABLE t1old; +} + +# Should be a single optimal segment with the same logical results. +do_test fts2p-1.3.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0} +do_test fts2p-1.3.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}} + +check_terms_all fts2p-1.3.1 {a test that was} +check_doclist_all fts2p-1.3.1.1 a {[2 0[2]]} +check_doclist_all fts2p-1.3.1.2 test {[2 0[3]]} +check_doclist_all fts2p-1.3.1.3 that {[2 0[0]]} +check_doclist_all fts2p-1.3.1.4 was {[2 0[1]]} + +check_terms fts2p-1.3.2 0 0 {a test that was} +check_doclist fts2p-1.3.2.1 0 0 a {[2 0[2]]} +check_doclist fts2p-1.3.2.2 0 0 test {[2 0[3]]} +check_doclist fts2p-1.3.2.3 0 0 that {[2 0[0]]} +check_doclist fts2p-1.3.2.4 0 0 was {[2 0[1]]} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2q.test b/components/external/SQLite-3.8.1/test/fts2q.test new file mode 100644 index 0000000000000000000000000000000000000000..cba78d583f8657e9affdd75537532be82349dab9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2q.test @@ -0,0 +1,346 @@ +# 2008 June 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing the FTS2 module's optimize() function. +# +# $Id: fts2q.test,v 1.2 2008/07/22 23:49:44 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is not defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +#************************************************************************* +# Probe to see if support for the FTS2 dump_* functions is compiled in. +# TODO(shess): Change main.mk to do the right thing and remove this test. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'x'); +} + +set s {SELECT dump_terms(t1, 1) FROM t1 LIMIT 1} +set r {1 {unable to use function dump_terms in the requested context}} +if {[catchsql $s]==$r} { + finish_test + return +} + +#************************************************************************* +# Utility function to check for the expected terms in the segment +# level/index. _all version does same but for entire index. +proc check_terms {test level index terms} { + # TODO(shess): Figure out why uplevel in do_test can't catch + # $level and $index directly. + set ::level $level + set ::index $index + do_test $test.terms { + execsql { + SELECT dump_terms(t1, $::level, $::index) FROM t1 LIMIT 1; + } + } [list $terms] +} +proc check_terms_all {test terms} { + do_test $test.terms { + execsql { + SELECT dump_terms(t1) FROM t1 LIMIT 1; + } + } [list $terms] +} + +# Utility function to check for the expected doclist for the term in +# segment level/index. _all version does same for entire index. +proc check_doclist {test level index term doclist} { + # TODO(shess): Again, why can't the non-:: versions work? + set ::term $term + set ::level $level + set ::index $index + do_test $test { + execsql { + SELECT dump_doclist(t1, $::term, $::level, $::index) FROM t1 LIMIT 1; + } + } [list $doclist] +} +proc check_doclist_all {test term doclist} { + set ::term $term + do_test $test { + execsql { + SELECT dump_doclist(t1, $::term) FROM t1 LIMIT 1; + } + } [list $doclist] +} + +#************************************************************************* +# Test results when all rows are deleted and one is added back. +# Previously older segments would continue to exist, but now the index +# should be dropped when the table is empty. The results should look +# exactly like we never added the earlier rows in the first place. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE 1=1; -- Delete each row rather than dropping table. + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); +} + +# Should be a single initial segment. +do_test fts2q-1.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0} +do_test fts2q-1.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid; + } +} {{0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}} + +check_terms_all fts2q-1.1 {a is test this} +check_doclist_all fts2q-1.1.1 a {[1 0[2]]} +check_doclist_all fts2q-1.1.2 is {[1 0[1]]} +check_doclist_all fts2q-1.1.3 test {[1 0[3]]} +check_doclist_all fts2q-1.1.4 this {[1 0[0]]} + +check_terms fts2q-1.2 0 0 {a is test this} +check_doclist fts2q-1.2.1 0 0 a {[1 0[2]]} +check_doclist fts2q-1.2.2 0 0 is {[1 0[1]]} +check_doclist fts2q-1.2.3 0 0 test {[1 0[3]]} +check_doclist fts2q-1.2.4 0 0 this {[1 0[0]]} + +#************************************************************************* +# Test results when everything is optimized manually. +# NOTE(shess): This is a copy of fts2c-1.3. I've pulled a copy here +# because fts2q-2 and fts2q-3 should have identical results. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE rowid IN (1,3); + DROP TABLE IF EXISTS t1old; + ALTER TABLE t1 RENAME TO t1old; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) SELECT rowid, c FROM t1old; + DROP TABLE t1old; +} + +# Should be a single optimal segment with the same logical results. +do_test fts2q-2.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0} +do_test fts2q-2.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}} + +check_terms_all fts2q-2.1 {a test that was} +check_doclist_all fts2q-2.1.1 a {[2 0[2]]} +check_doclist_all fts2q-2.1.2 test {[2 0[3]]} +check_doclist_all fts2q-2.1.3 that {[2 0[0]]} +check_doclist_all fts2q-2.1.4 was {[2 0[1]]} + +check_terms fts2q-2.2 0 0 {a test that was} +check_doclist fts2q-2.2.1 0 0 a {[2 0[2]]} +check_doclist fts2q-2.2.2 0 0 test {[2 0[3]]} +check_doclist fts2q-2.2.3 0 0 that {[2 0[0]]} +check_doclist fts2q-2.2.4 0 0 was {[2 0[1]]} + +#************************************************************************* +# Test results when everything is optimized via optimize(). +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE rowid IN (1,3); + SELECT OPTIMIZE(t1) FROM t1 LIMIT 1; +} + +# Should be a single optimal segment with the same logical results. +do_test fts2q-3.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0} +do_test fts2q-3.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}} + +check_terms_all fts2q-3.1 {a test that was} +check_doclist_all fts2q-3.1.1 a {[2 0[2]]} +check_doclist_all fts2q-3.1.2 test {[2 0[3]]} +check_doclist_all fts2q-3.1.3 that {[2 0[0]]} +check_doclist_all fts2q-3.1.4 was {[2 0[1]]} + +check_terms fts2q-3.2 0 0 {a test that was} +check_doclist fts2q-3.2.1 0 0 a {[2 0[2]]} +check_doclist fts2q-3.2.2 0 0 test {[2 0[3]]} +check_doclist fts2q-3.2.3 0 0 that {[2 0[0]]} +check_doclist fts2q-3.2.4 0 0 was {[2 0[1]]} + +#************************************************************************* +# Test optimize() against a table involving segment merges. +# NOTE(shess): Since there's no transaction, each of the INSERT/UPDATE +# statements generates a segment. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); + + UPDATE t1 SET c = 'This is a test one' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test one' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test one' WHERE rowid = 3; + + UPDATE t1 SET c = 'This is a test two' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test two' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test two' WHERE rowid = 3; + + UPDATE t1 SET c = 'This is a test three' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test three' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test three' WHERE rowid = 3; + + UPDATE t1 SET c = 'This is a test four' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test four' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test four' WHERE rowid = 3; + + UPDATE t1 SET c = 'This is a test' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test' WHERE rowid = 3; +} + +# 2 segments in level 0, 1 in level 1 (18 segments created, 16 +# merged). +do_test fts2q-4.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0 0 1 1 0} + +do_test fts2q-4.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid; + } +} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \ + {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \ + {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}] + +check_terms_all fts2q-4.1 {a four is one test that this three two was} +check_doclist_all fts2q-4.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist_all fts2q-4.1.2 four {} +check_doclist_all fts2q-4.1.3 is {[1 0[1]] [3 0[1]]} +check_doclist_all fts2q-4.1.4 one {} +check_doclist_all fts2q-4.1.5 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist_all fts2q-4.1.6 that {[2 0[0]]} +check_doclist_all fts2q-4.1.7 this {[1 0[0]] [3 0[0]]} +check_doclist_all fts2q-4.1.8 three {} +check_doclist_all fts2q-4.1.9 two {} +check_doclist_all fts2q-4.1.10 was {[2 0[1]]} + +check_terms fts2q-4.2 0 0 {a four test that was} +check_doclist fts2q-4.2.1 0 0 a {[2 0[2]]} +check_doclist fts2q-4.2.2 0 0 four {[2]} +check_doclist fts2q-4.2.3 0 0 test {[2 0[3]]} +check_doclist fts2q-4.2.4 0 0 that {[2 0[0]]} +check_doclist fts2q-4.2.5 0 0 was {[2 0[1]]} + +check_terms fts2q-4.3 0 1 {a four is test this} +check_doclist fts2q-4.3.1 0 1 a {[3 0[2]]} +check_doclist fts2q-4.3.2 0 1 four {[3]} +check_doclist fts2q-4.3.3 0 1 is {[3 0[1]]} +check_doclist fts2q-4.3.4 0 1 test {[3 0[3]]} +check_doclist fts2q-4.3.5 0 1 this {[3 0[0]]} + +check_terms fts2q-4.4 1 0 {a four is one test that this three two was} +check_doclist fts2q-4.4.1 1 0 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist fts2q-4.4.2 1 0 four {[1] [2 0[4]] [3 0[4]]} +check_doclist fts2q-4.4.3 1 0 is {[1 0[1]] [3 0[1]]} +check_doclist fts2q-4.4.4 1 0 one {[1] [2] [3]} +check_doclist fts2q-4.4.5 1 0 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist fts2q-4.4.6 1 0 that {[2 0[0]]} +check_doclist fts2q-4.4.7 1 0 this {[1 0[0]] [3 0[0]]} +check_doclist fts2q-4.4.8 1 0 three {[1] [2] [3]} +check_doclist fts2q-4.4.9 1 0 two {[1] [2] [3]} +check_doclist fts2q-4.4.10 1 0 was {[2 0[1]]} + +# Optimize should leave the result in the level of the highest-level +# prior segment. +do_test fts2q-4.5 { + execsql { + SELECT OPTIMIZE(t1) FROM t1 LIMIT 1; + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {{Index optimized} 1 0} + +# Identical to fts2q-4.matches. +do_test fts2q-4.5.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY rowid; + } +} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \ + {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \ + {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}] + +check_terms_all fts2q-4.5.1 {a is test that this was} +check_doclist_all fts2q-4.5.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist_all fts2q-4.5.1.2 is {[1 0[1]] [3 0[1]]} +check_doclist_all fts2q-4.5.1.3 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist_all fts2q-4.5.1.4 that {[2 0[0]]} +check_doclist_all fts2q-4.5.1.5 this {[1 0[0]] [3 0[0]]} +check_doclist_all fts2q-4.5.1.6 was {[2 0[1]]} + +check_terms fts2q-4.5.2 1 0 {a is test that this was} +check_doclist fts2q-4.5.2.1 1 0 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist fts2q-4.5.2.2 1 0 is {[1 0[1]] [3 0[1]]} +check_doclist fts2q-4.5.2.3 1 0 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist fts2q-4.5.2.4 1 0 that {[2 0[0]]} +check_doclist fts2q-4.5.2.5 1 0 this {[1 0[0]] [3 0[0]]} +check_doclist fts2q-4.5.2.6 1 0 was {[2 0[1]]} + +# Re-optimizing does nothing. +do_test fts2q-5.0 { + execsql { + SELECT OPTIMIZE(t1) FROM t1 LIMIT 1; + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {{Index already optimal} 1 0} + +# Even if we move things around, still does nothing. +do_test fts2q-5.1 { + execsql { + UPDATE t1_segdir SET level = 2 WHERE level = 1 AND idx = 0; + SELECT OPTIMIZE(t1) FROM t1 LIMIT 1; + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {{Index already optimal} 2 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2r.test b/components/external/SQLite-3.8.1/test/fts2r.test new file mode 100644 index 0000000000000000000000000000000000000000..c0be3671154b2e8e342cfa013437974ba140ab34 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2r.test @@ -0,0 +1,121 @@ +# 2008 July 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# These tests exercise the various types of fts2 cursors. +# +# $Id: fts2r.test,v 1.1 2008/07/29 20:38:18 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is not defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +#************************************************************************* +# Test table scan (QUERY_GENERIC). This kind of query happens for +# queries with no WHERE clause, or for WHERE clauses which cannot be +# satisfied by an index. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts2(c); + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); +} + +do_test fts2e-1.1 { + execsql { + SELECT rowid FROM t1 ORDER BY rowid; + } +} {1 2 3} + +do_test fts2e-1.2 { + execsql { + SELECT rowid FROM t1 WHERE c LIKE '%test' ORDER BY rowid; + } +} {1 2 3} + +do_test fts2e-1.3 { + execsql { + SELECT rowid FROM t1 WHERE c LIKE 'That%' ORDER BY rowid; + } +} {2} + +#************************************************************************* +# Test lookup by rowid (QUERY_ROWID). This kind of query happens for +# queries which select by the rowid implicit index. +db eval { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE VIRTUAL TABLE t1 USING fts2(c); + CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, weight INTEGER UNIQUE); + INSERT INTO t2 VALUES (null, 10); + INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'This is a test'); + INSERT INTO t2 VALUES (null, 5); + INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'That was a test'); + INSERT INTO t2 VALUES (null, 20); + INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'This is a test'); +} + +# TODO(shess): This actually is doing QUERY_GENERIC? I'd have +# expected QUERY_ROWID in this case, as for a very large table the +# full scan is less efficient. +do_test fts2e-2.1 { + execsql { + SELECT rowid FROM t1 WHERE rowid in (1, 2, 10); + } +} {1 2} + +do_test fts2e-2.2 { + execsql { + SELECT t1.rowid, weight FROM t1, t2 WHERE t2.id = t1.rowid ORDER BY weight; + } +} {2 5 1 10 3 20} + +do_test fts2e-2.3 { + execsql { + SELECT t1.rowid, weight FROM t1, t2 + WHERE t2.weight>5 AND t2.id = t1.rowid ORDER BY weight; + } +} {1 10 3 20} + +#************************************************************************* +# Test lookup by MATCH (QUERY_FULLTEXT). This is the fulltext index. +db eval { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE VIRTUAL TABLE t1 USING fts2(c); + CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, weight INTEGER UNIQUE); + INSERT INTO t2 VALUES (null, 10); + INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'This is a test'); + INSERT INTO t2 VALUES (null, 5); + INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'That was a test'); + INSERT INTO t2 VALUES (null, 20); + INSERT INTO t1 (rowid, c) VALUES (last_insert_rowid(), 'This is a test'); +} + +do_test fts2e-3.1 { + execsql { + SELECT rowid FROM t1 WHERE t1 MATCH 'this' ORDER BY rowid; + } +} {1 3} + +do_test fts2e-3.2 { + execsql { + SELECT t1.rowid, weight FROM t1, t2 + WHERE t1 MATCH 'this' AND t1.rowid = t2.id ORDER BY weight; + } +} {1 10 3 20} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts2token.test b/components/external/SQLite-3.8.1/test/fts2token.test new file mode 100644 index 0000000000000000000000000000000000000000..de5f94d7fc5a172489de6536ad499f498feb034c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts2token.test @@ -0,0 +1,174 @@ +# 2007 June 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing the pluggable tokeniser feature of the +# FTS2 module. +# +# $Id: fts2token.test,v 1.3 2007/06/25 12:05:40 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS2 is defined, omit this file. +ifcapable !fts2 { + finish_test + return +} + +proc escape_string {str} { + set out "" + foreach char [split $str ""] { + scan $char %c i + if {$i<=127} { + append out $char + } else { + append out [format {\x%.4x} $i] + } + } + set out +} + +#-------------------------------------------------------------------------- +# Test cases fts2token-1.* are the warm-body test for the SQL scalar +# function fts2_tokenizer(). The procedure is as follows: +# +# 1: Verify that there is no such fts2 tokenizer as 'blah'. +# +# 2: Query for the built-in tokenizer 'simple'. Insert a copy of the +# retrieved value as tokenizer 'blah'. +# +# 3: Test that the value returned for tokenizer 'blah' is now the +# same as that retrieved for 'simple'. +# +# 4: Test that it is now possible to create an fts2 table using +# tokenizer 'blah' (it was not possible in step 1). +# +# 5: Test that the table created to use tokenizer 'blah' is usable. +# +do_test fts2token-1.1 { + catchsql { + CREATE VIRTUAL TABLE t1 USING fts2(content, tokenize blah); + } +} {1 {unknown tokenizer: blah}} +do_test fts2token-1.2 { + execsql { + SELECT fts2_tokenizer('blah', fts2_tokenizer('simple')) IS NULL; + } +} {0} +do_test fts2token-1.3 { + execsql { + SELECT fts2_tokenizer('blah') == fts2_tokenizer('simple'); + } +} {1} +do_test fts2token-1.4 { + catchsql { + CREATE VIRTUAL TABLE t1 USING fts2(content, tokenize blah); + } +} {0 {}} +do_test fts2token-1.5 { + execsql { + INSERT INTO t1(content) VALUES('There was movement at the station'); + INSERT INTO t1(content) VALUES('For the word has passed around'); + INSERT INTO t1(content) VALUES('That the colt from ol regret had got away'); + SELECT content FROM t1 WHERE content MATCH 'movement' + } +} {{There was movement at the station}} + +#-------------------------------------------------------------------------- +# Test cases fts2token-2.* test error cases in the scalar function based +# API for getting and setting tokenizers. +# +do_test fts2token-2.1 { + catchsql { + SELECT fts2_tokenizer('nosuchtokenizer'); + } +} {1 {unknown tokenizer: nosuchtokenizer}} + +#-------------------------------------------------------------------------- +# Test cases fts2token-3.* test the three built-in tokenizers with a +# simple input string via the built-in test function. This is as much +# to test the test function as the tokenizer implementations. +# +do_test fts2token-3.1 { + execsql { + SELECT fts2_tokenizer_test('simple', 'I don''t see how'); + } +} {{0 i I 1 don don 2 t t 3 see see 4 how how}} +do_test fts2token-3.2 { + execsql { + SELECT fts2_tokenizer_test('porter', 'I don''t see how'); + } +} {{0 i I 1 don don 2 t t 3 see see 4 how how}} +ifcapable icu { + do_test fts2token-3.3 { + execsql { + SELECT fts2_tokenizer_test('icu', 'I don''t see how'); + } + } {{0 i I 1 don't don't 2 see see 3 how how}} +} + +#-------------------------------------------------------------------------- +# Test cases fts2token-4.* test the ICU tokenizer. In practice, this +# tokenizer only has two modes - "thai" and "everybody else". Some other +# Asian languages (Lao, Khmer etc.) require the same special treatment as +# Thai, but ICU doesn't support them yet. +# +ifcapable icu { + + proc do_icu_test {name locale input output} { + set ::out [db eval { SELECT fts2_tokenizer_test('icu', $locale, $input) }] + do_test $name { + lindex $::out 0 + } $output + } + + do_icu_test fts2token-4.1 en_US {} {} + do_icu_test fts2token-4.2 en_US {Test cases fts2} [list \ + 0 test Test 1 cases cases 2 fts2 fts2 + ] + + # The following test shows that ICU is smart enough to recognise + # Thai chararacters, even when the locale is set to English/United + # States. + # + set input "\u0e2d\u0e30\u0e44\u0e23\u0e19\u0e30\u0e04\u0e23\u0e31\u0e1a" + set output "0 \u0e2d\u0e30\u0e44\u0e23 \u0e2d\u0e30\u0e44\u0e23 " + append output "1 \u0e19\u0e30 \u0e19\u0e30 " + append output "2 \u0e04\u0e23\u0e31\u0e1a \u0e04\u0e23\u0e31\u0e1a" + + do_icu_test fts2token-4.3 th_TH $input $output + do_icu_test fts2token-4.4 en_US $input $output + + # ICU handles an unknown locale by falling back to the default. + # So this is not an error. + do_icu_test fts2token-4.5 MiddleOfTheOcean $input $output + + set longtoken "AReallyReallyLongTokenOneThatWillSurelyRequire" + append longtoken "AReallocInTheIcuTokenizerCode" + + set input "short tokens then " + append input $longtoken + set output "0 short short " + append output "1 tokens tokens " + append output "2 then then " + append output "3 [string tolower $longtoken] $longtoken" + + do_icu_test fts2token-4.6 MiddleOfTheOcean $input $output + do_icu_test fts2token-4.7 th_TH $input $output + do_icu_test fts2token-4.8 en_US $input $output +} + +do_test fts2token-internal { + execsql { SELECT fts2_tokenizer_internal_test() } +} {ok} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3.test b/components/external/SQLite-3.8.1/test/fts3.test new file mode 100644 index 0000000000000000000000000000000000000000..f42220bdc80ff8516468500c6644b6d7cb286d76 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3.test @@ -0,0 +1,19 @@ +# 2007 November 23 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs all tests. +# +# $Id: fts3.test,v 1.2 2008/07/23 18:17:32 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/permutations.test + +ifcapable fts3 { + run_test_suite fts3 +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3_common.tcl b/components/external/SQLite-3.8.1/test/fts3_common.tcl new file mode 100644 index 0000000000000000000000000000000000000000..2ed1f70bf626bee9781bdba5393c3a004227c841 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3_common.tcl @@ -0,0 +1,416 @@ +# 2009 November 04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains common code used the fts3 tests. At one point +# equivalent functionality was implemented in C code. But it is easier +# to use Tcl. +# + +#------------------------------------------------------------------------- +# INSTRUCTIONS +# +# The following commands are available: +# +# fts3_build_db_1 N +# Using database handle [db] create an FTS4 table named t1 and populate +# it with N rows of data. N must be less than 10,000. Refer to the +# header comments above the proc implementation below for details. +# +# fts3_build_db_2 N +# Using database handle [db] create an FTS4 table named t2 and populate +# it with N rows of data. N must be less than 100,000. Refer to the +# header comments above the proc implementation below for details. +# +# fts3_integrity_check TBL +# TBL must be an FTS table in the database currently opened by handle +# [db]. This proc loads and tokenizes all documents within the table, +# then checks that the current contents of the FTS index matches the +# results. +# +# fts3_terms TBL WHERE +# Todo. +# +# fts3_doclist TBL TERM WHERE +# Todo. +# +# +# + +#------------------------------------------------------------------------- +# USAGE: fts3_build_db_1 SWITCHES N +# +# Build a sample FTS table in the database opened by database connection +# [db]. The name of the new table is "t1". +# +proc fts3_build_db_1 {args} { + + set default(-module) fts4 + + set nArg [llength $args] + if {($nArg%2)==0} { + error "wrong # args: should be \"fts3_build_db_1 ?switches? n\"" + } + + set n [lindex $args [expr $nArg-1]] + array set opts [array get default] + array set opts [lrange $args 0 [expr $nArg-2]] + foreach k [array names opts] { + if {0==[info exists default($k)]} { error "unknown option: $k" } + } + + if {$n > 10000} {error "n must be <= 10000"} + db eval "CREATE VIRTUAL TABLE t1 USING $opts(-module) (x, y)" + + set xwords [list zero one two three four five six seven eight nine ten] + set ywords [list alpha beta gamma delta epsilon zeta eta theta iota kappa] + + for {set i 0} {$i < $n} {incr i} { + set x "" + set y "" + + set x [list] + lappend x [lindex $xwords [expr ($i / 1000) % 10]] + lappend x [lindex $xwords [expr ($i / 100) % 10]] + lappend x [lindex $xwords [expr ($i / 10) % 10]] + lappend x [lindex $xwords [expr ($i / 1) % 10]] + + set y [list] + lappend y [lindex $ywords [expr ($i / 1000) % 10]] + lappend y [lindex $ywords [expr ($i / 100) % 10]] + lappend y [lindex $ywords [expr ($i / 10) % 10]] + lappend y [lindex $ywords [expr ($i / 1) % 10]] + + db eval { INSERT INTO t1(docid, x, y) VALUES($i, $x, $y) } + } +} + +#------------------------------------------------------------------------- +# USAGE: fts3_build_db_2 N ARGS +# +# Build a sample FTS table in the database opened by database connection +# [db]. The name of the new table is "t2". +# +proc fts3_build_db_2 {args} { + + set default(-module) fts4 + set default(-extra) "" + + set nArg [llength $args] + if {($nArg%2)==0} { + error "wrong # args: should be \"fts3_build_db_1 ?switches? n\"" + } + + set n [lindex $args [expr $nArg-1]] + array set opts [array get default] + array set opts [lrange $args 0 [expr $nArg-2]] + foreach k [array names opts] { + if {0==[info exists default($k)]} { error "unknown option: $k" } + } + + if {$n > 100000} {error "n must be <= 100000"} + + set sql "CREATE VIRTUAL TABLE t2 USING $opts(-module) (content" + if {$opts(-extra) != ""} { + append sql ", " $opts(-extra) + } + append sql ")" + db eval $sql + + set chars [list a b c d e f g h i j k l m n o p q r s t u v w x y z ""] + + for {set i 0} {$i < $n} {incr i} { + set word "" + set nChar [llength $chars] + append word [lindex $chars [expr {($i / 1) % $nChar}]] + append word [lindex $chars [expr {($i / $nChar) % $nChar}]] + append word [lindex $chars [expr {($i / ($nChar*$nChar)) % $nChar}]] + + db eval { INSERT INTO t2(docid, content) VALUES($i, $word) } + } +} + +#------------------------------------------------------------------------- +# USAGE: fts3_integrity_check TBL +# +# This proc is used to verify that the full-text index is consistent with +# the contents of the fts3 table. In other words, it checks that the +# data in the %_contents table matches that in the %_segdir and %_segments +# tables. +# +# This is not an efficient procedure. It uses a lot of memory and a lot +# of CPU. But it is better than not checking at all. +# +# The procedure is: +# +# 1) Read the entire full-text index from the %_segdir and %_segments +# tables into memory. For each entry in the index, the following is +# done: +# +# set C($iDocid,$iCol,$iPosition) $zTerm +# +# 2) Iterate through each column of each row of the %_content table. +# Tokenize all documents, and check that for each token there is +# a corresponding entry in the $C array. After checking a token, +# [unset] the $C array entry. +# +# 3) Check that array $C is now empty. +# +# +proc fts3_integrity_check {tbl} { + + fts3_read2 $tbl 1 A + + foreach zTerm [array names A] { + #puts $zTerm + foreach doclist $A($zTerm) { + set docid 0 + while {[string length $doclist]>0} { + set iCol 0 + set iPos 0 + set lPos [list] + set lCol [list] + + # First varint of a doclist-entry is the docid. Delta-compressed + # with respect to the docid of the previous entry. + # + incr docid [gobble_varint doclist] + if {[info exists D($zTerm,$docid)]} { + while {[set iDelta [gobble_varint doclist]] != 0} {} + continue + } + set D($zTerm,$docid) 1 + + # Gobble varints until the 0x00 that terminates the doclist-entry + # is found. + while {[set iDelta [gobble_varint doclist]] > 0} { + if {$iDelta == 1} { + set iCol [gobble_varint doclist] + set iPos 0 + } else { + incr iPos $iDelta + incr iPos -2 + set C($docid,$iCol,$iPos) $zTerm + } + } + } + } + } + + foreach key [array names C] { + #puts "$key -> $C($key)" + } + + + db eval "SELECT * FROM ${tbl}_content" E { + set iCol 0 + set iDoc $E(docid) + foreach col [lrange $E(*) 1 end] { + set c $E($col) + set sql {SELECT fts3_tokenizer_test('simple', $c)} + + foreach {pos term dummy} [db one $sql] { + if {![info exists C($iDoc,$iCol,$pos)]} { + set es "Error at docid=$iDoc col=$iCol pos=$pos. Index is missing" + lappend errors $es + } else { + if {[string compare $C($iDoc,$iCol,$pos) $term]} { + set es "Error at docid=$iDoc col=$iCol pos=$pos. Index " + append es "has \"$C($iDoc,$iCol,$pos)\", document has \"$term\"" + lappend errors $es + } + unset C($iDoc,$iCol,$pos) + } + } + incr iCol + } + } + + foreach c [array names C] { + lappend errors "Bad index entry: $c -> $C($c)" + } + + if {[info exists errors]} { return [join $errors "\n"] } + return "ok" +} + +# USAGE: fts3_terms TBL WHERE +# +# Argument TBL must be the name of an FTS3 table. Argument WHERE is an +# SQL expression that will be used as the WHERE clause when scanning +# the %_segdir table. As in the following query: +# +# "SELECT * FROM ${TBL}_segdir WHERE ${WHERE}" +# +# This function returns a list of all terms present in the segments +# selected by the statement above. +# +proc fts3_terms {tbl where} { + fts3_read $tbl $where a + return [lsort [array names a]] +} + + +# USAGE: fts3_doclist TBL TERM WHERE +# +# Argument TBL must be the name of an FTS3 table. TERM is a term that may +# or may not be present in the table. Argument WHERE is used to select a +# subset of the b-tree segments in the associated full-text index as +# described above for [fts3_terms]. +# +# This function returns the results of merging the doclists associated +# with TERM in the selected segments. Each doclist is an element of the +# returned list. Each doclist is formatted as follows: +# +# [$docid ?$col[$off1 $off2...]?...] +# +# The formatting is odd for a Tcl command in order to be compatible with +# the original C-language implementation. If argument WHERE is "1", then +# any empty doclists are omitted from the returned list. +# +proc fts3_doclist {tbl term where} { + fts3_read $tbl $where a + + + foreach doclist $a($term) { + set docid 0 + + while {[string length $doclist]>0} { + set iCol 0 + set iPos 0 + set lPos [list] + set lCol [list] + incr docid [gobble_varint doclist] + + while {[set iDelta [gobble_varint doclist]] > 0} { + if {$iDelta == 1} { + lappend lCol [list $iCol $lPos] + set iPos 0 + set lPos [list] + set iCol [gobble_varint doclist] + } else { + incr iPos $iDelta + incr iPos -2 + lappend lPos $iPos + } + } + + if {[llength $lPos]>0} { + lappend lCol [list $iCol $lPos] + } + + if {$where != "1" || [llength $lCol]>0} { + set ret($docid) $lCol + } else { + unset -nocomplain ret($docid) + } + } + } + + set lDoc [list] + foreach docid [lsort -integer [array names ret]] { + set lCol [list] + set cols "" + foreach col $ret($docid) { + foreach {iCol lPos} $col {} + append cols " $iCol\[[join $lPos { }]\]" + } + lappend lDoc "\[${docid}${cols}\]" + } + + join $lDoc " " +} + +########################################################################### + +proc gobble_varint {varname} { + upvar $varname blob + set n [read_fts3varint $blob ret] + set blob [string range $blob $n end] + return $ret +} +proc gobble_string {varname nLength} { + upvar $varname blob + set ret [string range $blob 0 [expr $nLength-1]] + set blob [string range $blob $nLength end] + return $ret +} + +# The argument is a blob of data representing an FTS3 segment leaf. +# Return a list consisting of alternating terms (strings) and doclists +# (blobs of data). +# +proc fts3_readleaf {blob} { + set zPrev "" + set terms [list] + + while {[string length $blob] > 0} { + set nPrefix [gobble_varint blob] + set nSuffix [gobble_varint blob] + + set zTerm [string range $zPrev 0 [expr $nPrefix-1]] + append zTerm [gobble_string blob $nSuffix] + set nDoclist [gobble_varint blob] + set doclist [gobble_string blob $nDoclist] + + lappend terms $zTerm $doclist + set zPrev $zTerm + } + + return $terms +} + +proc fts3_read2 {tbl where varname} { + upvar $varname a + array unset a + db eval " SELECT start_block, leaves_end_block, root + FROM ${tbl}_segdir WHERE $where + ORDER BY level ASC, idx DESC + " { + set c 0 + binary scan $root c c + if {$c==0} { + foreach {t d} [fts3_readleaf $root] { lappend a($t) $d } + } else { + db eval " SELECT block + FROM ${tbl}_segments + WHERE blockid>=$start_block AND blockid<=$leaves_end_block + ORDER BY blockid + " { + foreach {t d} [fts3_readleaf $block] { lappend a($t) $d } + } + } + } +} + +proc fts3_read {tbl where varname} { + upvar $varname a + array unset a + db eval " SELECT start_block, leaves_end_block, root + FROM ${tbl}_segdir WHERE $where + ORDER BY level DESC, idx ASC + " { + if {$start_block == 0} { + foreach {t d} [fts3_readleaf $root] { lappend a($t) $d } + } else { + db eval " SELECT block + FROM ${tbl}_segments + WHERE blockid>=$start_block AND blockid<$leaves_end_block + ORDER BY blockid + " { + foreach {t d} [fts3_readleaf $block] { lappend a($t) $d } + + } + } + } +} + +########################################################################## + diff --git a/components/external/SQLite-3.8.1/test/fts3aa.test b/components/external/SQLite-3.8.1/test/fts3aa.test new file mode 100644 index 0000000000000000000000000000000000000000..bde38af5531f759615dcae864919164164a38d99 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3aa.test @@ -0,0 +1,226 @@ +# 2006 September 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# +# $Id: fts3aa.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Construct a full-text search table containing five keywords: +# one, two, three, four, and five, in various combinations. The +# rowid for each will be a bitmask for the elements it contains. +# +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(content); + INSERT INTO t1(content) VALUES('one'); + INSERT INTO t1(content) VALUES('two'); + INSERT INTO t1(content) VALUES('one two'); + INSERT INTO t1(content) VALUES('three'); + INSERT INTO t1(content) VALUES('one three'); + INSERT INTO t1(content) VALUES('two three'); + INSERT INTO t1(content) VALUES('one two three'); + INSERT INTO t1(content) VALUES('four'); + INSERT INTO t1(content) VALUES('one four'); + INSERT INTO t1(content) VALUES('two four'); + INSERT INTO t1(content) VALUES('one two four'); + INSERT INTO t1(content) VALUES('three four'); + INSERT INTO t1(content) VALUES('one three four'); + INSERT INTO t1(content) VALUES('two three four'); + INSERT INTO t1(content) VALUES('one two three four'); + INSERT INTO t1(content) VALUES('five'); + INSERT INTO t1(content) VALUES('one five'); + INSERT INTO t1(content) VALUES('two five'); + INSERT INTO t1(content) VALUES('one two five'); + INSERT INTO t1(content) VALUES('three five'); + INSERT INTO t1(content) VALUES('one three five'); + INSERT INTO t1(content) VALUES('two three five'); + INSERT INTO t1(content) VALUES('one two three five'); + INSERT INTO t1(content) VALUES('four five'); + INSERT INTO t1(content) VALUES('one four five'); + INSERT INTO t1(content) VALUES('two four five'); + INSERT INTO t1(content) VALUES('one two four five'); + INSERT INTO t1(content) VALUES('three four five'); + INSERT INTO t1(content) VALUES('one three four five'); + INSERT INTO t1(content) VALUES('two three four five'); + INSERT INTO t1(content) VALUES('one two three four five'); +} + +do_test fts3aa-1.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts3aa-1.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two'} +} {3 7 11 15 19 23 27 31} +do_test fts3aa-1.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one'} +} {3 7 11 15 19 23 27 31} +do_test fts3aa-1.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two three'} +} {7 15 23 31} +do_test fts3aa-1.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one three two'} +} {7 15 23 31} +do_test fts3aa-1.6 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two three one'} +} {7 15 23 31} +do_test fts3aa-1.7 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two one three'} +} {7 15 23 31} +do_test fts3aa-1.8 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three one two'} +} {7 15 23 31} +do_test fts3aa-1.9 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three two one'} +} {7 15 23 31} +do_test fts3aa-1.10 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two THREE'} +} {7 15 23 31} +do_test fts3aa-1.11 { + execsql {SELECT rowid FROM t1 WHERE content MATCH ' ONE Two three '} +} {7 15 23 31} + +do_test fts3aa-2.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one"'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts3aa-2.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two"'} +} {3 7 11 15 19 23 27 31} +do_test fts3aa-2.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"two one"'} +} {} +do_test fts3aa-2.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three"'} +} {7 15 23 31} +do_test fts3aa-2.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two"'} +} {} +do_test fts3aa-2.6 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two three four"'} +} {15 31} +do_test fts3aa-2.7 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three two four"'} +} {} +do_test fts3aa-2.8 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three five"'} +} {21} +do_test fts3aa-2.9 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" five'} +} {21 29} +do_test fts3aa-2.10 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three"'} +} {21 29} +do_test fts3aa-2.11 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five "one three" four'} +} {29} +do_test fts3aa-2.12 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five four "one three"'} +} {29} +do_test fts3aa-2.13 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one three" four five'} +} {29} + +do_test fts3aa-3.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts3aa-3.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one -two'} +} {1 5 9 13 17 21 25 29} +do_test fts3aa-3.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '-two one'} +} {1 5 9 13 17 21 25 29} + +breakpoint +do_test fts3aa-4.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one OR two'} +} {1 2 3 5 6 7 9 10 11 13 14 15 17 18 19 21 22 23 25 26 27 29 30 31} +do_test fts3aa-4.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH '"one two" OR three'} +} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31} +do_test fts3aa-4.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR "one two"'} +} {3 4 5 6 7 11 12 13 14 15 19 20 21 22 23 27 28 29 30 31} +do_test fts3aa-4.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three'} +} {3 5 7 11 13 15 19 21 23 27 29 31} +do_test fts3aa-4.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three OR two one'} +} {3 5 7 11 13 15 19 21 23 27 29 31} +do_test fts3aa-4.6 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one two OR three OR four'} +} {3 5 7 9 11 13 15 19 21 23 25 27 29 31} +do_test fts3aa-4.7 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two OR three OR four one'} +} {3 5 7 9 11 13 15 19 21 23 25 27 29 31} + +# Test the ability to handle NULL content +# +do_test fts3aa-5.1 { + execsql {INSERT INTO t1(content) VALUES(NULL)} +} {} +do_test fts3aa-5.2 { + set rowid [db last_insert_rowid] + execsql {SELECT content FROM t1 WHERE rowid=$rowid} +} {{}} +do_test fts3aa-5.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH NULL} +} {} + +# Test the ability to handle non-positive rowids +# +do_test fts3aa-6.0 { + execsql {INSERT INTO t1(rowid, content) VALUES(0, 'four five')} +} {} +do_test fts3aa-6.1 { + execsql {SELECT content FROM t1 WHERE rowid = 0} +} {{four five}} +do_test fts3aa-6.2 { + execsql {INSERT INTO t1(rowid, content) VALUES(-1, 'three four')} +} {} +do_test fts3aa-6.3 { + execsql {SELECT content FROM t1 WHERE rowid = -1} +} {{three four}} +do_test fts3aa-6.4 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'four'} +} {-1 0 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31} + +# Test creation of FTS3 and FTS4 tables with columns that contain +# an "=" character. +# +do_execsql_test fts3aa-7.1 { + CREATE VIRTUAL TABLE t2 USING fts3(xyz=abc); + SELECT xyz FROM t2; +} {} +do_catchsql_test fts3aa-7.2 { + CREATE VIRTUAL TABLE t3 USING fts4(xyz=abc); +} {1 {unrecognized parameter: xyz=abc}} +do_catchsql_test fts3aa-7.3 { + CREATE VIRTUAL TABLE t3 USING fts4(xyz = abc); +} {1 {unrecognized parameter: xyz = abc}} + +do_execsql_test fts3aa-7.4 { + CREATE VIRTUAL TABLE t3 USING fts3(tokenize=simple, tokenize=simple); + SELECT tokenize FROM t3; +} {} +do_catchsql_test fts3aa-7.5 { + CREATE VIRTUAL TABLE t4 USING fts4(tokenize=simple, tokenize=simple); +} {1 {unrecognized parameter: tokenize=simple}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3ab.test b/components/external/SQLite-3.8.1/test/fts3ab.test new file mode 100644 index 0000000000000000000000000000000000000000..e1f3bdc9cfe02911ddc1cd7fa886707f5e2a2fde --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3ab.test @@ -0,0 +1,148 @@ +# 2006 September 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# +# $Id: fts3ab.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Fill the full-text index "t1" with phrases in english, spanish, +# and german. For the i-th row, fill in the names for the bits +# that are set in the value of i. The least significant bit is +# 1. For example, the value 5 is 101 in binary which will be +# converted to "one three" in english. +# +proc fill_multilanguage_fulltext_t1 {} { + set english {one two three four five} + set spanish {un dos tres cuatro cinco} + set german {eine zwei drei vier funf} + + for {set i 1} {$i<=31} {incr i} { + set cmd "INSERT INTO t1 VALUES" + set vset {} + foreach lang {english spanish german} { + set words {} + for {set j 0; set k 1} {$j<5} {incr j; incr k $k} { + if {$k&$i} {lappend words [lindex [set $lang] $j]} + } + lappend vset "'$words'" + } + set sql "INSERT INTO t1(english,spanish,german) VALUES([join $vset ,])" + # puts $sql + db eval $sql + } +} + +# Construct a full-text search table containing five keywords: +# one, two, three, four, and five, in various combinations. The +# rowid for each will be a bitmask for the elements it contains. +# +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(english,spanish,german); +} +fill_multilanguage_fulltext_t1 + +do_test fts3ab-1.1 { + execsql {SELECT rowid FROM t1 WHERE english MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts3ab-1.2 { + execsql {SELECT rowid FROM t1 WHERE spanish MATCH 'one'} +} {} +do_test fts3ab-1.3 { + execsql {SELECT rowid FROM t1 WHERE german MATCH 'one'} +} {} +do_test fts3ab-1.4 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one'} +} {1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31} +do_test fts3ab-1.5 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'one dos drei'} +} {7 15 23 31} +do_test fts3ab-1.6 { + execsql {SELECT english, spanish, german FROM t1 WHERE rowid=1} +} {one un eine} +do_test fts3ab-1.7 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"one un"'} +} {} + +do_test fts3ab-2.1 { + execsql { + CREATE VIRTUAL TABLE t2 USING fts3(from,to); + INSERT INTO t2([from],[to]) VALUES ('one two three', 'four five six'); + SELECT [from], [to] FROM t2 + } +} {{one two three} {four five six}} + + +# Compute an SQL string that contains the words one, two, three,... to +# describe bits set in the value $i. Only the lower 5 bits are examined. +# +proc wordset {i} { + set x {} + for {set j 0; set k 1} {$j<5} {incr j; incr k $k} { + if {$k&$i} {lappend x [lindex {one two three four five} $j]} + } + return '$x' +} + +# Create a new FTS table with three columns: +# +# norm: words for the bits of rowid +# plusone: words for the bits of rowid+1 +# invert: words for the bits of ~rowid +# +db eval { + CREATE VIRTUAL TABLE t4 USING fts3([norm],'plusone',"invert"); +} +for {set i 1} {$i<=15} {incr i} { + set vset [list [wordset $i] [wordset [expr {$i+1}]] [wordset [expr {~$i}]]] + db eval "INSERT INTO t4(norm,plusone,invert) VALUES([join $vset ,]);" +} + +breakpoint +do_test fts3ab-4.1 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one'} +} {1 3 5 7 9 11 13 15} +do_test fts3ab-4.2 { + execsql {SELECT rowid FROM t4 WHERE norm MATCH 'one'} +} {1 3 5 7 9 11 13 15} +do_test fts3ab-4.3 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'one'} +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} +do_test fts3ab-4.4 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:one'} +} {2 4 6 8 10 12 14} +do_test fts3ab-4.5 { + execsql {SELECT rowid FROM t4 WHERE plusone MATCH 'one'} +} {2 4 6 8 10 12 14} +do_test fts3ab-4.6 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one plusone:two'} +} {1 5 9 13} +do_test fts3ab-4.7 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'norm:one two'} +} {1 3 5 7 9 11 13 15} +do_test fts3ab-4.8 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'plusone:two norm:one'} +} {1 5 9 13} +do_test fts3ab-4.9 { + execsql {SELECT rowid FROM t4 WHERE t4 MATCH 'two norm:one'} +} {1 3 5 7 9 11 13 15} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3ac.test b/components/external/SQLite-3.8.1/test/fts3ac.test new file mode 100644 index 0000000000000000000000000000000000000000..84da924b6e8aee8613e17c842ffd1b68646f1ceb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3ac.test @@ -0,0 +1,1219 @@ +# 2006 September 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# +# $Id: fts3ac.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Create a table of sample email data. The data comes from email +# archives of Enron executives that was published as part of the +# litigation against that company. +# +do_test fts3ac-1.1 { + db eval { + CREATE VIRTUAL TABLE email USING fts3([from],[to],subject,body); + BEGIN TRANSACTION; +INSERT INTO email([from],[to],subject,body) VALUES('savita.puthigai@enron.com', 'traders.eol@enron.com, traders.eol@enron.com', 'EnronOnline- Change to Autohedge', 'Effective Monday, October 22, 2001 the following changes will be made to the Autohedge functionality on EnronOnline. + +The volume on the hedge will now respect the minimum volume and volume increment settings on the parent product. See rules below: + +? If the transaction volume on the child is less than half of the parent''s minimum volume no hedge will occur. +? If the transaction volume on the child is more than half the parent''s minimum volume but less than half the volume increment on the parent, the hedge will volume will be the parent''s minimum volume. +? For all other volumes, the same rounding rules will apply based on the volume increment on the parent product. + +Please see example below: + +Parent''s Settings: +Minimum: 5000 +Increment: 1000 + +Volume on Autohedge transaction Volume Hedged +1 - 2499 0 +2500 - 5499 5000 +5500 - 6499 6000'); +INSERT INTO email([from],[to],subject,body) VALUES('dana.davis@enron.com', 'laynie.east@enron.com, lisa.king@enron.com, lisa.best@enron.com,', 'Leaving Early', 'FYI: +If it''s ok with everyone''s needs, I would like to leave @4pm. If you think +you will need my assistance past the 4 o''clock hour just let me know; I''ll +be more than willing to stay.'); +INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'louise.kitchen@enron.com', '<> - CC02.06.02', 'The following expense report is ready for approval: + +Employee Name: Christopher F. Calger +Status last changed by: Mollie E. Gustafson Ms +Expense Report Name: CC02.06.02 +Report Total: $3,972.93 +Amount Due Employee: $3,972.93 + + +To approve this expense report, click on the following link for Concur Expense. +http://expensexms.enron.com'); +INSERT INTO email([from],[to],subject,body) VALUES('jeff.duff@enron.com', 'julie.johnson@enron.com', 'Work request', 'Julie, + +Could you print off the current work request report by 1:30 today? + +Gentlemen, + +I''d like to review this today at 1:30 in our office. Also, could you provide +me with your activity reports so I can have Julie enter this information. + +JD'); +INSERT INTO email([from],[to],subject,body) VALUES('v.weldon@enron.com', 'gary.l.carrier@usa.dupont.com, scott.joyce@bankofamerica.com', 'Enron News', 'This could turn into something big.... +http://biz.yahoo.com/rf/010129/n29305829.html'); +INSERT INTO email([from],[to],subject,body) VALUES('mark.haedicke@enron.com', 'paul.simons@enron.com', 'Re: First Polish Deal!', 'Congrats! Things seem to be building rapidly now on the Continent. Mark'); +INSERT INTO email([from],[to],subject,body) VALUES('e..carter@enron.com', 't..robinson@enron.com', 'FW: Producers Newsletter 9-24-2001', ' +The producer lumber pricing sheet. + -----Original Message----- +From: Johnson, Jay +Sent: Tuesday, October 16, 2001 3:42 PM +To: Carter, Karen E. +Subject: FW: Producers Newsletter 9-24-2001 + + + + -----Original Message----- +From: Daigre, Sergai +Sent: Friday, September 21, 2001 8:33 PM +Subject: Producers Newsletter 9-24-2001 + + '); +INSERT INTO email([from],[to],subject,body) VALUES('david.delainey@enron.com', 'kenneth.lay@enron.com', 'Greater Houston Partnership', 'Ken, in response to the letter from Mr Miguel San Juan, my suggestion would +be to offer up the Falcon for their use; however, given the tight time frame +and your recent visit with Mr. Fox that it would be difficult for either you +or me to participate. + +I spoke to Max and he agrees with this approach. + +I hope this meets with your approval. + +Regards +Delainey'); +INSERT INTO email([from],[to],subject,body) VALUES('lachandra.fenceroy@enron.com', 'lindy.donoho@enron.com', 'FW: Bus Applications Meeting Follow Up', 'Lindy, + +Here is the original memo we discussed earlier. Please provide any information that you may have. + +Your cooperation is greatly appreciated. + +Thanks, + +lachandra.fenceroy@enron.com +713.853.3884 +877.498.3401 Pager + + -----Original Message----- +From: Bisbee, Joanne +Sent: Wednesday, September 26, 2001 7:50 AM +To: Fenceroy, LaChandra +Subject: FW: Bus Applications Meeting Follow Up + +Lachandra, Please get with David Duff today and see what this is about. Who are our TW accounting business users? + + -----Original Message----- +From: Koh, Wendy +Sent: Tuesday, September 25, 2001 2:41 PM +To: Bisbee, Joanne +Subject: Bus Applications Meeting Follow Up + +Lisa brought up a TW change effective Nov 1. It involves eliminating a turnback surcharge. I have no other information, but you might check with the business folks for any system changes required. + +Wendy'); +INSERT INTO email([from],[to],subject,body) VALUES('danny.mccarty@enron.com', 'fran.fagan@enron.com', 'RE: worksheets', 'Fran, + If Julie''s merit needs to be lump sum, just move it over to that column. Also, send me Eric Gadd''s sheets as well. Thanks. +Dan + + -----Original Message----- +From: Fagan, Fran +Sent: Thursday, December 20, 2001 11:10 AM +To: McCarty, Danny +Subject: worksheets + +As discussed, attached are your sheets for bonus and merit. + +Thanks, + +Fran Fagan +Sr. HR Rep +713.853.5219 + + + << File: McCartyMerit.xls >> << File: mccartyBonusCommercial_UnP.xls >> + +'); +INSERT INTO email([from],[to],subject,body) VALUES('bert.meyers@enron.com', 'shift.dl-portland@enron.com', 'OCTOBER SCHEDULE', 'TEAM, + +PLEASE SEND ME ANY REQUESTS THAT YOU HAVE FOR OCTOBER. SO FAR I HAVE THEM FOR LEAF. I WOULD LIKE TO HAVE IT DONE BY THE 15TH OF THE MONTH. ANY QUESTIONS PLEASE GIVE ME A CALL. + +BERT'); +INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'john.arnold@enron.com, bilal.bajwa@enron.com, john.griffith@enron.com,', 'TRV Notification: (NG - PROPT P/L - 09/27/2001)', 'The report named: NG - PROPT P/L , published as of 09/27/2001 is now available for viewing on the website.'); +INSERT INTO email([from],[to],subject,body) VALUES('patrice.mims@enron.com', 'calvin.eakins@enron.com', 'Re: Small business supply assistance', 'Hi Calvin + + +I spoke with Rickey (boy, is he long-winded!!). Gave him the name of our +credit guy, Russell Diamond. + +Thank for your help!'); +INSERT INTO email([from],[to],subject,body) VALUES('legal <.hall@enron.com>', 'stephanie.panus@enron.com', 'Termination update', 'City of Vernon and Salt River Project terminated their contracts. I will fax these notices to you.'); +INSERT INTO email([from],[to],subject,body) VALUES('d..steffes@enron.com', 'richard.shapiro@enron.com', 'EES / ENA Government Affairs Staffing & Outside Services', 'Rick -- + +Here is the information on staffing and outside services. Call if you need anything else. + +Jim + + '); +INSERT INTO email([from],[to],subject,body) VALUES('gelliott@industrialinfo.com', 'pcopello@industrialinfo.com', 'ECAAR (Gavin), WSCC (Diablo Canyon), & NPCC (Seabrook)', 'Dear Power Outage Database Customer, +Attached you will find an excel document. The outages contained within are forced or rescheduled outages. Your daily delivery will still contain these outages. +In addition to the two excel documents, there is a dbf file that is formatted like your daily deliveries you receive nightly. This will enable you to load the data into your regular database. Any questions please let me know. Thanks. +Greg Elliott +IIR, Inc. +713-783-5147 x 3481 +outages@industrialinfo.com +THE INFORMATION CONTAINED IN THIS E-MAIL IS LEGALLY PRIVILEGED AND CONFIDENTIAL INFORMATION INTENDED ONLY FOR THE USE OF THE INDIVIDUAL OR ENTITY NAMED ABOVE. YOU ARE HEREBY NOTIFIED THAT ANY DISSEMINATION, DISTRIBUTION, OR COPY OF THIS E-MAIL TO UNAUTHORIZED ENTITIES IS STRICTLY PROHIBITED. IF YOU HAVE RECEIVED THIS +E-MAIL IN ERROR, PLEASE DELETE IT. + - OUTAGE.dbf + - 111201R.xls + - 111201.xls '); +INSERT INTO email([from],[to],subject,body) VALUES('enron.announcements@enron.com', 'all_ena_egm_eim@enron.com', 'EWS Brown Bag', 'MARK YOUR LUNCH CALENDARS NOW ! + +You are invited to attend the EWS Brown Bag Lunch Series + +Featuring: RAY BOWEN, COO + +Topic: Enron Industrial Markets + +Thursday, March 15, 2001 +11:30 am - 12:30 pm +EB 5 C2 + + +You bring your lunch, Limited Seating +We provide drinks and dessert. RSVP x 3-9610'); +INSERT INTO email([from],[to],subject,body) VALUES('chris.germany@enron.com', 'ingrid.immer@williams.com', 'Re: About St Pauls', 'Sounds good to me. I bet this is next to the Warick?? Hotel. + + + + +"Immer, Ingrid" on 12/21/2000 11:48:47 AM +To: "''chris.germany@enron.com''" +cc: +Subject: About St Pauls + + + + + <> +? +?http://www.stpaulshouston.org/about.html + +Chris, + +I like the looks of this place.? What do you think about going here Christmas +eve?? They have an 11:00 a.m. service and a candlelight service at 5:00 p.m., +among others. + +Let me know.?? ii + + - About St Pauls.url + +'); +INSERT INTO email([from],[to],subject,body) VALUES('nas@cpuc.ca.gov', 'skatz@sempratrading.com, kmccrea@sablaw.com, thompson@wrightlaw.com,', 'Reply Brief filed July 31, 2000', ' - CPUC01-#76371-v1-Revised_Reply_Brief__Due_today_7_31_.doc'); +INSERT INTO email([from],[to],subject,body) VALUES('gascontrol@aglresources.com', 'dscott4@enron.com, lcampbel@enron.com', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder', 'Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder +As discussed in the Winter Operations Meeting on Sept.29,2000, +E-Gas(Emergency Gas) will not be offered this winter as a service from AGLC. +Marketers and Poolers can receive gas via Peaking and IBSS nominations(daisy +chain) from other marketers up to the 6 p.m. Same Day 2 nomination cycle. +'); +INSERT INTO email([from],[to],subject,body) VALUES('dutch.quigley@enron.com', 'rwolkwitz@powermerchants.com', '', ' + +Here is a goody for you'); +INSERT INTO email([from],[to],subject,body) VALUES('ryan.o''rourke@enron.com', 'k..allen@enron.com, randy.bhatia@enron.com, frank.ermis@enron.com,', 'TRV Notification: (West VaR - 11/07/2001)', 'The report named: West VaR , published as of 11/07/2001 is now available for viewing on the website.'); +INSERT INTO email([from],[to],subject,body) VALUES('mjones7@txu.com', 'cstone1@txu.com, ggreen2@txu.com, timpowell@txu.com,', 'Enron / HPL Actuals for July 10, 2000', 'Teco Tap 10.000 / Enron ; 110.000 / HPL IFERC + +LS HPL LSK IC 30.000 / Enron +'); +INSERT INTO email([from],[to],subject,body) VALUES('susan.pereira@enron.com', 'kkw816@aol.com', 'soccer practice', 'Kathy- + +Is it safe to assume that practice is cancelled for tonight?? + +Susan Pereira'); +INSERT INTO email([from],[to],subject,body) VALUES('mark.whitt@enron.com', 'barry.tycholiz@enron.com', 'Huber Internal Memo', 'Please look at this. I didn''t know how deep to go with the desk. Do you think this works. + + '); +INSERT INTO email([from],[to],subject,body) VALUES('m..forney@enron.com', 'george.phillips@enron.com', '', 'George, +Give me a call and we will further discuss opportunities on the 13st floor. + +Thanks, +JMForney +3-7160'); +INSERT INTO email([from],[to],subject,body) VALUES('brad.mckay@enron.com', 'angusmcka@aol.com', 'Re: (no subject)', 'not yet'); +INSERT INTO email([from],[to],subject,body) VALUES('adam.bayer@enron.com', 'jonathan.mckay@enron.com', 'FW: Curve Fetch File', 'Here is the curve fetch file sent to me. It has plenty of points in it. If you give me a list of which ones you need we may be able to construct a secondary worksheet to vlookup the values. + +adam +35227 + + + -----Original Message----- +From: Royed, Jeff +Sent: Tuesday, September 25, 2001 11:37 AM +To: Bayer, Adam +Subject: Curve Fetch File + +Let me know if it works. It may be required to have a certain version of Oracle for it to work properly. + + + +Jeff Royed +Enron +Energy Operations +Phone: 713-853-5295'); +INSERT INTO email([from],[to],subject,body) VALUES('matt.smith@enron.com', 'yan.wang@enron.com', 'Report Formats', 'Yan, + +The merged reports look great. I believe the only orientation changes are to +"unmerge" the following six reports: + +31 Keystone Receipts +15 Questar Pipeline +40 Rockies Production +22 West_2 +23 West_3 +25 CIG_WIC + +The orientation of the individual reports should be correct. Thanks. + +Mat + +PS. Just a reminder to add the "*" by the title of calculated points.'); +INSERT INTO email([from],[to],subject,body) VALUES('michelle.lokay@enron.com', 'jimboman@bigfoot.com', 'Egyptian Festival', '---------------------- Forwarded by Michelle Lokay/ET&S/Enron on 09/07/2000 +10:08 AM --------------------------- + + +"Karkour, Randa" on 09/07/2000 09:01:04 AM +To: "''Agheb (E-mail)" , "Leila Mankarious (E-mail)" +, "''Marymankarious (E-mail)" +, "Michelle lokay (E-mail)" , "Ramy +Mankarious (E-mail)" +cc: + +Subject: Egyptian Festival + + + <> + + http://www.egyptianfestival.com/ + + - Egyptian Festival.url +'); +INSERT INTO email([from],[to],subject,body) VALUES('errol.mclaughlin@enron.com', 'sherry.dawson@enron.com', 'Urgent!!! --- New EAST books', 'This has to be done.................................. + +Thanks +---------------------- Forwarded by Errol McLaughlin/Corp/Enron on 12/20/2000 +08:39 AM --------------------------- + + + + From: William Kelly @ ECT 12/20/2000 08:31 AM + + +To: Kam Keiser/HOU/ECT@ECT, Darron C Giron/HOU/ECT@ECT, David +Baumbach/HOU/ECT@ECT, Errol McLaughlin/Corp/Enron@ENRON +cc: Kimat Singla/HOU/ECT@ECT, Kulvinder Fowler/NA/Enron@ENRON, Kyle R +Lilly/HOU/ECT@ECT, Jeff Royed/Corp/Enron@ENRON, Alejandra +Chavez/NA/Enron@ENRON, Crystal Hyde/HOU/ECT@ECT + +Subject: New EAST books + +We have new book names in TAGG for our intramonth portfolios and it is +extremely important that any deal booked to the East is communicated quickly +to someone on my team. I know it will take some time for the new names to +sink in and I do not want us to miss any positions or P&L. + +Thanks for your help on this. + +New: +Scott Neal : East Northeast +Dick Jenkins: East Marketeast + +WK +'); +INSERT INTO email([from],[to],subject,body) VALUES('david.forster@enron.com', 'eol.wide@enron.com', 'Change to Stack Manager', 'Effective immediately, there is a change to the Stack Manager which will +affect any Inactive Child. + +An inactive Child with links to Parent products will not have their +calculated prices updated until the Child product is Activated. + +When the Child Product is activated, the price will be recalculated and +updated BEFORE it is displayed on the web. + +This means that if you are inputting a basis price on a Child product, you +will not see the final, calculated price until you Activate the product, at +which time the customer will also see it. + +If you have any questions, please contact the Help Desk on: + +Americas: 713 853 4357 +Europe: + 44 (0) 20 7783 7783 +Asia/Australia: +61 2 9229 2300 + +Dave'); +INSERT INTO email([from],[to],subject,body) VALUES('vince.kaminski@enron.com', 'jhh1@email.msn.com', 'Re: Light reading - see pieces beginning on page 7', 'John, + +I saw it. Very interesting. + +Vince + + + + + +"John H Herbert" on 07/28/2000 08:38:08 AM +To: "Vince J Kaminski" +cc: +Subject: Light reading - see pieces beginning on page 7 + + +Cheers and have a nice weekend, + + +JHHerbert + + + + + - gd000728.pdf + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('matthew.lenhart@enron.com', 'mmmarcantel@equiva.com', 'RE:', 'i will try to line up a pig for you '); +INSERT INTO email([from],[to],subject,body) VALUES('jae.black@enron.com', 'claudette.harvey@enron.com, chaun.roberts@enron.com, judy.martinez@enron.com,', 'Disaster Recovery Equipment', 'As a reminder...there are several pieces of equipment that are set up on the 30th Floor, as well as on our floor, for the Disaster Recovery Team. PLEASE DO NOT TAKE, BORROW OR USE this equipment. Should you need to use another computer system, other than yours, or make conference calls please work with your Assistant to help find or set up equipment for you to use. + +Thanks for your understanding in this matter. + +T.Jae Black +East Power Trading +Assistant to Kevin Presto +off. 713-853-5800 +fax 713-646-8272 +cell 713-539-4760'); +INSERT INTO email([from],[to],subject,body) VALUES('eric.bass@enron.com', 'dale.neuner@enron.com', '5 X 24', 'Dale, + +Have you heard anything more on the 5 X 24s? We would like to get this +product out ASAP. + + +Thanks, + +Eric'); +INSERT INTO email([from],[to],subject,body) VALUES('messenger@smartreminders.com', 'm..tholt@enron.com', '10% Coupon - PrintPal Printer Cartridges - 100% Guaranteed', '[IMAGE] +[IMAGE][IMAGE][IMAGE] +Dear SmartReminders Member, + [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] [IMAGE] + + + + + + + + + + + + + + + + + + + + + +We respect your privacy and are a Certified Participant of the BBBOnLine + Privacy Program. To be removed from future offers,click here. +SmartReminders.com is a permission based service. To unsubscribe click here . '); +INSERT INTO email([from],[to],subject,body) VALUES('benjamin.rogers@enron.com', 'mark.bernstein@enron.com', '', 'The guy you are talking about left CIN under a "cloud of suspicion" sort of +speak. He was the one who got into several bad deals and PPA''s in California +for CIN, thus he left on a bad note. Let me know if you need more detail +than that, I felt this was the type of info you were looking for. Thanks! +Ben'); +INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'michelle.cash@enron.com', 'Expense Report Receipts Not Received', 'Employee Name: Michelle Cash +Report Name: Houston Cellular 8-11-01 +Report Date: 12/13/01 +Report ID: 594D37C9ED2111D5B452 +Submitted On: 12/13/01 + +You are only allowed 2 reports with receipts outstanding. Your expense reports will not be paid until you meet this requirement.'); +INSERT INTO email([from],[to],subject,body) VALUES('susan.mara@enron.com', 'ray.alvarez@enron.com, mark.palmer@enron.com, karen.denne@enron.com,', 'CAISO Emergency Motion -- to discontinue market-based rates for', 'FYI. the latest broadside against the generators. + +Sue Mara +Enron Corp. +Tel: (415) 782-7802 +Fax:(415) 782-7854 +----- Forwarded by Susan J Mara/NA/Enron on 06/08/2001 12:24 PM ----- + + + "Milner, Marcie" 06/08/2001 11:13 AM To: "''smara@enron.com''" cc: Subject: CAISO Emergency Motion + + +Sue, did you see this emergency motion the CAISO filed today? Apparently +they are requesting that FERC discontinue market-based rates immediately and +grant refunds plus interest on the difference between cost-based rates and +market revenues received back to May 2000. They are requesting the +commission act within 14 days. Have you heard anything about what they are +doing? + +Marcie + +http://www.caiso.com/docs/2001/06/08/200106081005526469.pdf +'); +INSERT INTO email([from],[to],subject,body) VALUES('fletcher.sturm@enron.com', 'eloy.escobar@enron.com', 'Re: General Brinks Position Meeting', 'Eloy, + +Who is General Brinks? + +Fletch'); +INSERT INTO email([from],[to],subject,body) VALUES('nailia.dindarova@enron.com', 'richard.shapiro@enron.com', 'Documents for Mark Frevert (on EU developments and lessons from', 'Rick, + +Here are the documents that Peter has prepared for Mark Frevert. + +Nailia +---------------------- Forwarded by Nailia Dindarova/LON/ECT on 25/06/2001 +16:36 --------------------------- + + +Nailia Dindarova +25/06/2001 15:36 +To: Michael Brown/Enron@EUEnronXGate +cc: Ross Sankey/Enron@EUEnronXGate, Eric Shaw/ENRON@EUEnronXGate, Peter +Styles/LON/ECT@ECT + +Subject: Documents for Mark Frevert (on EU developments and lessons from +California) + +Michael, + + +These are the documents that Peter promised to give to you for Mark Frevert. +He has now handed them to him in person but asked me to transmit them +electronically to you, as well as Eric and Ross. + +Nailia + + + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('peggy.a.kostial@accenture.com', 'dave.samuels@enron.com', 'EOL-Accenture Deal Sheet', 'Dave - + +Attached are our comments and suggested changes. Please call to review. + +On the time line for completion, we have four critical steps to complete: + Finalize market analysis to refine business case, specifically + projected revenue stream + Complete counterparty surveying, including targeting 3 CPs for letters + of intent + Review Enron asset base for potential reuse/ licensing + Contract negotiations + +Joe will come back to us with an updated time line, but it is my +expectation that we are still on the same schedule (we just begun week +three) with possibly a week or so slippage.....contract negotiations will +probably be the critical path. + +We will send our cut at the actual time line here shortly. Thanks, + +Peggy + +(See attached file: accenture-dealpoints v2.doc) + - accenture-dealpoints v2.doc '); +INSERT INTO email([from],[to],subject,body) VALUES('thomas.martin@enron.com', 'thomas.martin@enron.com', 'Re: Guadalupe Power Partners LP', '---------------------- Forwarded by Thomas A Martin/HOU/ECT on 03/20/2001 +03:49 PM --------------------------- + + +Thomas A Martin +10/11/2000 03:55 PM +To: Patrick Wade/HOU/ECT@ECT +cc: +Subject: Re: Guadalupe Power Partners LP + +The deal is physically served at Oasis Waha or Oasis Katy and is priced at +either HSC, Waha or Katytailgate GD at buyers option three days prior to +NYMEX close. + +'); +INSERT INTO email([from],[to],subject,body) VALUES('judy.townsend@enron.com', 'dan.junek@enron.com, chris.germany@enron.com', 'Columbia Distribution''s Capacity Available for Release - Sum', '---------------------- Forwarded by Judy Townsend/HOU/ECT on 03/09/2001 11:04 +AM --------------------------- + + +agoddard@nisource.com on 03/08/2001 09:16:57 AM +To: " - *Koch, Kent" , " - +*Millar, Debra" , " - *Burke, Lynn" + +cc: " - *Heckathorn, Tom" +Subject: Columbia Distribution''s Capacity Available for Release - Sum + + +Attached is Columbia Distribution''s notice of capacity available for release +for +the summer of 2001 (Apr. 2001 through Oct. 2001). + +Please note that the deadline for bids is 3:00pm EST on March 20, 2001. + +If you have any questions, feel free to contact any of the representatives +listed +at the bottom of the attachment. + +Aaron Goddard + + + + + - 2001Summer.doc +'); +INSERT INTO email([from],[to],subject,body) VALUES('rhonda.denton@enron.com', 'tim.belden@enron.com, dana.davis@enron.com, genia.fitzgerald@enron.com,', 'Split Rock Energy LLC', 'We have received the executed EEI contract from this CP dated 12/12/2000. +Copies will be distributed to Legal and Credit.'); +INSERT INTO email([from],[to],subject,body) VALUES('kerrymcelroy@dwt.com', 'jack.speer@alcoa.com, crow@millernash.com, michaelearly@earthlink.net,', 'Oral Argument Request', ' - Oral Argument Request.doc'); +INSERT INTO email([from],[to],subject,body) VALUES('mike.carson@enron.com', 'rlmichaelis@hormel.com', '', 'Did you come in town this wk end..... My new number at our house is : +713-668-3712...... my cell # is 281-381-7332 + +the kid'); +INSERT INTO email([from],[to],subject,body) VALUES('cooper.richey@enron.com', 'trycooper@hotmail.com', 'FW: Contact Info', ' + +-----Original Message----- +From: Punja, Karim +Sent: Thursday, December 13, 2001 2:35 PM +To: Richey, Cooper +Subject: Contact Info + + +Cooper, + +Its been a real pleasure working with you (even though it was for only a small amount of time) +I hope we can stay in touch. + +Home# 234-0249 +email: kpunja@hotmail.com + +Take Care, + +Karim. + '); +INSERT INTO email([from],[to],subject,body) VALUES('bjm30@earthlink.net', 'mcguinn.k@enron.com, mcguinn.ian@enron.com, mcguinn.stephen@enron.com,', 'email address change', 'Hello all. + +I haven''t talked to many of you via email recently but I do want to give you +my new address for your email file: + + bjm30@earthlink.net + +I hope all is well. + +Brian McGuinn'); +INSERT INTO email([from],[to],subject,body) VALUES('shelley.corman@enron.com', 'steve.hotte@enron.com', 'Flat Panels', 'Can you please advise what is going on with the flat panels that we had planned to distribute to our gas logistics team. It was in the budget and we had the okay, but now I''m hearing there is some hold-up & the units are stored on 44. + +Shelley'); +INSERT INTO email([from],[to],subject,body) VALUES('sara.davidson@enron.com', 'john.schwartzenburg@enron.com, scott.dieball@enron.com, recipients@enron.com,', '2001 Enron Law Conference (Distribution List 2)', ' Enron Law Conference + +San Antonio, Texas May 2-4, 2001 Westin Riverwalk + + See attached memo for more details!! + + +? Registration for the law conference this year will be handled through an +Online RSVP Form on the Enron Law Conference Website at +http://lawconference.corp.enron.com. The website is still under construction +and will not be available until Thursday, March 15, 2001. + +? We will send you another e-mail to confirm when the Law Conference Website +is operational. + +? Please complete the Online RSVP Form as soon as it is available and submit +it no later than Friday, March 30th. + + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('tori.kuykendall@enron.com', 'heath.b.taylor@accenture.com', 'Re:', 'hey - thats funny about john - he definitely remembers him - i''ll call pat +and let him know - we are coming on saturday - i just havent had a chance to +call you guys back -- looking forward to it -- i probably need the +directions again though'); +INSERT INTO email([from],[to],subject,body) VALUES('darron.giron@enron.com', 'bryce.baxter@enron.com', 'Re: Feedback for Audrey Cook', 'Bryce, + +I''ll get it done today. + +DG 3-9573 + + + + + + From: Bryce Baxter 06/12/2000 07:15 PM + + +To: Darron C Giron/HOU/ECT@ECT +cc: +Subject: Feedback for Audrey Cook + +You were identified as a reviewer for Audrey Cook. If possible, could you +complete her feedback by end of business Wednesday? It will really help me +in the PRC process to have your input. Thanks. + +'); +INSERT INTO email([from],[to],subject,body) VALUES('casey.evans@enron.com', 'stephanie.sever@enron.com', 'Gas EOL ID', 'Stephanie, + +In conjunction with the recent movement of several power traders, they are changing the names of their gas books as well. The names of the new gas books and traders are as follows: + +PWR-NG-LT-SPP: Mike Carson +PWR-NG-LT-SERC: Jeff King + +If you need to know their power desk to map their ID to their gas books, those desks are as follows: + +EPMI-LT-SPP: Mike Carson +EPMI-LT-SERC: Jeff King + +I will be in training this afternoon, but will be back when class is over. Let me know if you have any questions. + +Thanks for your help! +Casey'); +INSERT INTO email([from],[to],subject,body) VALUES('darrell.schoolcraft@enron.com', 'david.roensch@enron.com, kimberly.watson@enron.com, michelle.lokay@enron.com,', 'Postings', 'Please see the attached. + + +ds + + + + + '); +INSERT INTO email([from],[to],subject,body) VALUES('mcominsky@aol.com', 'cpatman@bracepatt.com, james_derrick@enron.com', 'Jurisprudence Luncheon', 'Carrin & Jim -- + +It was an honor and a pleasure to meet both of you yesterday. I know we will +have fun working together on this very special event. + +Jeff left the jurisprudence luncheon lists for me before he left on vacation. + I wasn''t sure whether he transmitted them to you as well. Would you please +advise me if you would like them sent to you? I can email the MS Excel files +or I can fax the hard copies to you. Please advise what is most convenient. + +I plan to be in town through the holidays and can be reached by phone, email, +or cell phone at any time. My cell phone number is 713/705-4829. + +Thanks again for your interest in the ADL''s work. Martin. + +Martin B. Cominsky +Director, Southwest Region +Anti-Defamation League +713/627-3490, ext. 122 +713/627-2011 (fax) +MCominsky@aol.com'); +INSERT INTO email([from],[to],subject,body) VALUES('phillip.love@enron.com', 'todagost@utmb.edu, gbsonnta@utmb.edu', 'New President', 'I had a little bird put a word in my ear. Is there any possibility for Ben +Raimer to be Bush''s secretary of HHS? Just curious about that infamous UTMB +rumor mill. Hope things are well, happy holidays. +PL'); +INSERT INTO email([from],[to],subject,body) VALUES('marie.heard@enron.com', 'ehamilton@fna.com', 'ISDA Master Agreement', 'Erin: + +Pursuant to your request, attached are the Schedule to the ISDA Master Agreement, together with Paragraph 13 to the ISDA Credit Support Annex. Please let me know if you need anything else. We look forward to hearing your comments. + +Marie + +Marie Heard +Senior Legal Specialist +Enron North America Corp. +Phone: (713) 853-3907 +Fax: (713) 646-3490 +marie.heard@enron.com + + '); +INSERT INTO email([from],[to],subject,body) VALUES('andrea.ring@enron.com', 'beverly.beaty@enron.com', 'Re: Tennessee Buy - Louis Dreyfus', 'Beverly - once again thanks so much for your help on this. + + + + '); +INSERT INTO email([from],[to],subject,body) VALUES('karolyn.criado@enron.com', 'j..bonin@enron.com, felicia.case@enron.com, b..clapp@enron.com,', 'Price List week of Oct. 8-9, 2001', ' +Please contact me if you have any questions regarding last weeks prices. + +Thank you, +Karolyn Criado +3-9441 + + + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('kevin.presto@enron.com', 'edward.baughman@enron.com, billy.braddock@enron.com', 'Associated', 'Please begin working on filling our Associated short position in 02. I would like to take this risk off the books. + +In addition, please find out what a buy-out of VEPCO would cost us. With Rogers transitioning to run our retail risk management, I would like to clean up our customer positions. + +We also need to continue to explore a JEA buy-out. + +Thanks.'); +INSERT INTO email([from],[to],subject,body) VALUES('stacy.dickson@enron.com', 'gregg.penman@enron.com', 'RE: Constellation TC 5-7-01', 'Gregg, + +I am at home with a sick baby. (Lots of fun!) I will call you about this +tomorrow. + +Stacy'); +INSERT INTO email([from],[to],subject,body) VALUES('joe.quenet@enron.com', 'dfincher@utilicorp.com', '', 'hey big guy.....check this out..... + + w ww.gorelieberman-2000.com/'); +INSERT INTO email([from],[to],subject,body) VALUES('k..allen@enron.com', 'jacqestc@aol.com', '', 'Jacques, + +I sent you a fax of Kevin Kolb''s comments on the release. The payoff on the note would be $36,248 ($36090(principal) + $158 (accrued interest)). +This is assuming we wrap this up on Tuesday. + +Please email to confirm that their changes are ok so I can set up a meeting on Tuesday to reach closure. + +Phillip'); +INSERT INTO email([from],[to],subject,body) VALUES('kourtney.nelson@enron.com', 'mike.swerzbin@enron.com', 'Adjusted L/R Balance', 'Mike, + +I placed the adjusted L/R Balance on the Enronwest site. It is under the "Staff/Kourtney Nelson". There are two links: + +1) "Adj L_R" is the same data/format from the weekly strategy meeting. +2) "New Gen 2001_2002" link has all of the supply side info that is used to calculate the L/R balance + -Please note the Data Flag column, a value of "3" indicates the project was cancelled, on hold, etc and is not included in the calc. + +Both of these sheets are interactive Excel spreadsheets and thus you can play around with the data as you please. Also, James Bruce is working to get his gen report on the web. That will help with your access to information on new gen. + +Please let me know if you have any questions or feedback, + +Kourtney + + + +Kourtney Nelson +Fundamental Analysis +Enron North America +(503) 464-8280 +kourtney.nelson@enron.com'); +INSERT INTO email([from],[to],subject,body) VALUES('d..thomas@enron.com', 'naveed.ahmed@enron.com', 'FW: Current Enron TCC Portfolio', ' + +-----Original Message----- +From: Grace, Rebecca M. +Sent: Monday, December 17, 2001 9:44 AM +To: Thomas, Paul D. +Cc: Cashion, Jim; Allen, Thresa A.; May, Tom +Subject: RE: Current Enron TCC Portfolio + + +Paul, + +I reviewed NY''s list. I agree with all of their contracts numbers and mw amounts. + +Call if you have any more questions. + +Rebecca + + + + -----Original Message----- +From: Thomas, Paul D. +Sent: Monday, December 17, 2001 9:08 AM +To: Grace, Rebecca M. +Subject: FW: Current Enron TCC Portfolio + + << File: enrontccs.xls >> +Rebecca, +Let me know if you see any differences. + +Paul +X 3-0403 +-----Original Message----- +From: Thomas, Paul D. +Sent: Monday, December 17, 2001 9:04 AM +To: Ahmed, Naveed +Subject: FW: Current Enron TCC Portfolio + + + + +-----Original Message----- +From: Thomas, Paul D. +Sent: Thursday, December 13, 2001 10:01 AM +To: Baughman, Edward D. +Subject: Current Enron TCC Portfolio + + +'); +INSERT INTO email([from],[to],subject,body) VALUES('stephanie.panus@enron.com', 'william.bradford@enron.com, debbie.brackett@enron.com,', 'Coastal Merchant Energy/El Paso Merchant Energy', 'Coastal Merchant Energy, L.P. merged with and into El Paso Merchant Energy, +L.P., effective February 1, 2001, with the surviving entity being El Paso +Merchant Energy, L.P. We currently have ISDA Master Agreements with both +counterparties. Please see the attached memo regarding the existing Masters +and let us know which agreement should be terminated. + +Thanks, +Stephanie +'); +INSERT INTO email([from],[to],subject,body) VALUES('kam.keiser@enron.com', 'c..kenne@enron.com', 'RE: What about this too???', ' + + -----Original Message----- +From: Kenne, Dawn C. +Sent: Wednesday, February 06, 2002 11:50 AM +To: Keiser, Kam +Subject: What about this too??? + + + << File: Netco Trader Matrix.xls >> + '); +INSERT INTO email([from],[to],subject,body) VALUES('chris.meyer@enron.com', 'joe.parks@enron.com', 'Centana', 'Talked to Chip. We do need Cash Committe approval given the netting feature of your deal, which means Batch Funding Request. Please update per my previous e-mail and forward. + +Thanks + +chris +x31666'); +INSERT INTO email([from],[to],subject,body) VALUES('debra.perlingiere@enron.com', 'jworman@academyofhealth.com', '', 'Have a great weekend! Happy Fathers Day! + + +Debra Perlingiere +Enron North America Corp. +1400 Smith Street, EB 3885 +Houston, Texas 77002 +dperlin@enron.com +Phone 713-853-7658 +Fax 713-646-3490'); +INSERT INTO email([from],[to],subject,body) VALUES('outlook.team@enron.com', '', 'Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia &', 'CALENDAR ENTRY: APPOINTMENT + +Description: + Demo by Martha Janousek of Dashboard & Pipeline Profile / Julia & Dir Rpts. - 4102 + +Date: 1/5/2001 +Time: 9:00 AM - 10:00 AM (Central Standard Time) + +Chairperson: Outlook Migration Team + +Detailed Description:'); +INSERT INTO email([from],[to],subject,body) VALUES('diana.seifert@enron.com', 'mark.taylor@enron.com', 'Guest access Chile', 'Hello Mark, + +Justin Boyd told me that your can help me with questions regarding Chile. +We got a request for guest access through MG. +The company is called Escondida and is a subsidiary of BHP Australia. + +Please advise if I can set up a guest account or not. +F.Y.I.: MG is planning to put a "in w/h Chile" contract for Copper on-line as +soon as Enron has done the due diligence for this country. +Thanks ! + + +Best regards + +Diana Seifert +EOL PCG'); +INSERT INTO email([from],[to],subject,body) VALUES('enron_update@concureworkplace.com', 'mark.whitt@enron.com', '<> - 121001', 'The Approval status has changed on the following report: + +Status last changed by: Barry L. Tycholiz +Expense Report Name: 121001 +Report Total: $198.98 +Amount Due Employee: $198.98 +Amount Approved: $198.98 +Amount Paid: $0.00 +Approval Status: Approved +Payment Status: Pending + + +To review this expense report, click on the following link for Concur Expense. +http://expensexms.enron.com'); +INSERT INTO email([from],[to],subject,body) VALUES('kevin.hyatt@enron.com', '', 'Technical Support', 'Outside the U.S., please refer to the list below: + +Australia: +1800 678-515 +support@palm-au.com + +Canada: +1905 305-6530 +support@palm.com + +New Zealand: +0800 446-398 +support@palm-nz.com + +U.K.: +0171 867 0108 +eurosupport@palm.3com.com + +Please refer to the Worldwide Customer Support card for a complete technical support contact list.'); +INSERT INTO email([from],[to],subject,body) VALUES('geoff.storey@enron.com', 'dutch.quigley@enron.com', 'RE:', 'duke contact? + + -----Original Message----- +From: Quigley, Dutch +Sent: Wednesday, October 31, 2001 10:14 AM +To: Storey, Geoff +Subject: RE: + +bp corp Albert LaMore 281-366-4962 + +running the reports now + + + -----Original Message----- +From: Storey, Geoff +Sent: Wednesday, October 31, 2001 10:10 AM +To: Quigley, Dutch +Subject: RE: + +give me a contact over there too +BP + + + -----Original Message----- +From: Quigley, Dutch +Sent: Wednesday, October 31, 2001 9:42 AM +To: Storey, Geoff +Subject: + +Coral Jeff Whitnah 713-767-5374 +Relaint Steve McGinn 713-207-4000'); +INSERT INTO email([from],[to],subject,body) VALUES('pete.davis@enron.com', 'pete.davis@enron.com', 'Start Date: 4/22/01; HourAhead hour: 3; ', 'Start Date: 4/22/01; HourAhead hour: 3; No ancillary schedules awarded. +Variances detected. +Variances detected in Load schedule. + + LOG MESSAGES: + +PARSING FILE -->> O:\Portland\WestDesk\California Scheduling\ISO Final +Schedules\2001042203.txt + +---- Load Schedule ---- +$$$ Variance found in table tblLoads. + Details: (Hour: 3 / Preferred: 1.92 / Final: 1.89) + TRANS_TYPE: FINAL + LOAD_ID: PGE4 + MKT_TYPE: 2 + TRANS_DATE: 4/22/01 + SC_ID: EPMI + +'); +INSERT INTO email([from],[to],subject,body) VALUES('john.postlethwaite@enron.com', 'john.zufferli@enron.com', 'Reference', 'John, hope things are going well up there for you. The big day is almost here for you and Jessica. I was wondering if I could use your name as a job reference if need be. I am just trying to get everything in order just in case something happens. + +John'); +INSERT INTO email([from],[to],subject,body) VALUES('jeffrey.shankman@enron.com', 'lschiffm@jonesday.com', 'Re:', 'I saw you called on the cell this a.m. Sorry I missed you. (I was in the +shower). I have had a shitty week--I suspect my silence (not only to you, +but others) after our phone call is a result of the week. I''m seeing Glen at +11:15....talk to you'); +INSERT INTO email([from],[to],subject,body) VALUES('litebytz@enron.com', '', 'Lite Bytz RSVP', ' +This week''s Lite Bytz presentation will feature the following TOOLZ speaker: + +Richard McDougall +Solaris 8 +Thursday, June 7, 2001 + +If you have not already signed up, please RSVP via email to litebytz@enron.com by the end of the day Tuesday, June 5, 2001. + +*Remember: this is now a Brown Bag Event--so bring your lunch and we will provide cookies and drinks. + +Click below for more details. + +http://home.enron.com:84/messaging/litebytztoolzprint.jpg'); + COMMIT; + } +} {} + +############################################################################### +# Everything above just builds an interesting test database. The actual +# tests come after this comment. +############################################################################### + +do_test fts3ac-1.2 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark' + } +} {6 17 25 38 40 42 73 74} +do_test fts3ac-1.3 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'susan' + } +} {24 40} +do_test fts3ac-1.4 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark susan' + } +} {40} +do_test fts3ac-1.5 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'susan mark' + } +} {40} +do_test fts3ac-1.6 { + execsql { + SELECT rowid FROM email WHERE email MATCH '"mark susan"' + } +} {} +do_test fts3ac-1.7 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark -susan' + } +} {6 17 25 38 42 73 74} +do_test fts3ac-1.8 { + execsql { + SELECT rowid FROM email WHERE email MATCH '-mark susan' + } +} {24} +do_test fts3ac-1.9 { + execsql { + SELECT rowid FROM email WHERE email MATCH 'mark OR susan' + } +} {6 17 24 25 38 40 42 73 74} + +# Some simple tests of the automatic "offsets(email)" column. In the sample +# data set above, only one message, number 20, contains the words +# "gas" and "reminder" in both body and subject. +# +do_test fts3ac-2.1 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE email MATCH 'gas reminder' + } +} {20 {2 0 42 3 2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}} +do_test fts3ac-2.2 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE email MATCH 'subject:gas reminder' + } +} {20 {2 0 42 3 2 1 54 8 3 1 54 8}} +do_test fts3ac-2.3 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE email MATCH 'body:gas reminder' + } +} {20 {2 1 54 8 3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}} +do_test fts3ac-2.4 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE subject MATCH 'gas reminder' + } +} {20 {2 0 42 3 2 1 54 8}} +do_test fts3ac-2.5 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE body MATCH 'gas reminder' + } +} {20 {3 0 42 3 3 1 54 8 3 0 129 3 3 0 143 3 3 0 240 3}} + +# Document 32 contains 5 instances of the world "child". But only +# 3 of them are paired with "product". Make sure only those instances +# that match the phrase appear in the offsets(email) list. +# +do_test fts3ac-3.1 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE body MATCH 'child product' AND +rowid=32 + } +} {32 {3 0 94 5 3 0 114 5 3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7 3 1 493 7}} +do_test fts3ac-3.2 { + execsql { + SELECT rowid, offsets(email) FROM email + WHERE body MATCH '"child product"' + } +} {32 {3 0 207 5 3 1 213 7 3 0 245 5 3 1 251 7 3 0 409 5 3 1 415 7}} + +# Snippet generator tests +# +do_test fts3ac-4.1 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'subject:gas reminder' + } +} {{Alert Posted 10:00 AM November 20,2000: E-GAS Request Reminder}} +do_test fts3ac-4.2 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'christmas candlelight' + } +} {{...here Christmas +eve?? They have an 11:00 a.m. service and a candlelight service...}} + +do_test fts3ac-4.3 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'deal sheet potential reuse' + } +} {{EOL-Accenture Deal Sheet...asset base for potential reuse/ licensing + Contract negotiations...}} +do_test fts3ac-4.4 { + execsql { + SELECT snippet(email,'<<<','>>>',' ') FROM email + WHERE email MATCH 'deal sheet potential reuse' + } +} {{EOL-Accenture <<>> <<>> asset base for <<>> <<>>/ licensing + Contract negotiations }} +do_test fts3ac-4.5 { + execsql { + SELECT snippet(email,'<<<','>>>',' ') FROM email + WHERE email MATCH 'first things' + } +} {{Re: <<>> Polish Deal! Congrats! <<>> seem to be building rapidly now }} +do_test fts3ac-4.6 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'chris is here' + } +} {{...chris.germany@enron.com'" <chris...bet this is next to...about going here Christmas +eve...}} +do_test fts3ac-4.7 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH '"pursuant to"' + } +} {{Erin: + +Pursuant to your request, attached are the Schedule to the ISDA Master Agreement, together...}} +do_test fts3ac-4.8 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'ancillary load davis' + } +} {{pete.davis@enron.com...3; No ancillary schedules awarded...detected in Load schedule. + + LOG...}} + +# Combinations of AND and OR operators: +# +do_test fts3ac-5.1 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'questar enron OR com' + } +} {{matt.smith@enron.com...31 Keystone Receipts +15 Questar Pipeline +40 Rockies...}} + +do_test fts3ac-5.2 { + execsql { + SELECT snippet(email) FROM email + WHERE email MATCH 'enron OR com questar' + } +} {{matt.smith@enron.com...31 Keystone Receipts +15 Questar Pipeline +40 Rockies...}} + +#------------------------------------------------------------------------- +# Test a problem reported on the mailing list. +# +do_test fts3ac-6.1 { + execsql { + CREATE VIRTUAL TABLE ft USING fts3(one, two); + INSERT INTO ft VALUES('', 'foo'); + INSERT INTO ft VALUES('foo', 'foo'); + SELECT offsets(ft) FROM ft WHERE ft MATCH 'foo'; + } +} {{1 0 0 3} {0 0 0 3 1 0 0 3}} +do_test fts3ac-6.2 { + execsql { + DELETE FROM ft WHERE one = 'foo'; + SELECT offsets(ft) FROM ft WHERE ft MATCH 'foo'; + } +} {{1 0 0 3}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3ad.test b/components/external/SQLite-3.8.1/test/fts3ad.test new file mode 100644 index 0000000000000000000000000000000000000000..e373339d4e74b10991efac46192c1e00c397a475 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3ad.test @@ -0,0 +1,106 @@ +# 2006 October 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module, and in particular +# the Porter stemmer. +# +# $Id: fts3ad.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +do_test fts3ad-1.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize porter); + INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping'); + SELECT rowid FROM t1 WHERE content MATCH 'run jump'; + } +} {1} +do_test fts3ad-1.2 { + execsql { + SELECT snippet(t1) FROM t1 WHERE t1 MATCH 'run jump'; + } +} {{running and jumping}} +do_test fts3ad-1.3 { + execsql { + INSERT INTO t1(rowid, content) + VALUES(2, 'abcdefghijklmnopqrstuvwyxz'); + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijqrstuvwyxz' + } +} {2 abcdefghijklmnopqrstuvwyxz} +do_test fts3ad-1.4 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH 'abcdefghijXXXXqrstuvwyxz' + } +} {2 abcdefghijklmnopqrstuvwyxz} +do_test fts3ad-1.5 { + execsql { + INSERT INTO t1(rowid, content) + VALUES(3, 'The value is 123456789'); + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123789' + } +} {3 {The value is 123456789}} +do_test fts3ad-1.6 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE t1 MATCH '123000000789' + } +} {3 {The value is 123456789}} + +do_test fts3ad-2.1 { + execsql { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize porter); + INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping'); + SELECT rowid FROM t1 WHERE content MATCH 'run jump'; + } +} {1} +do_test fts3ad-2.2 { + execsql { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize= porter); + INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping'); + SELECT rowid FROM t1 WHERE content MATCH 'run jump'; + } +} {1} +do_test fts3ad-2.3 { + execsql { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize= simple); + INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping'); + SELECT rowid FROM t1 WHERE content MATCH 'run jump'; + } +} {} +do_test fts3ad-2.4 { + execsql { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize= porter); + INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping'); + SELECT rowid FROM t1 WHERE content MATCH 'run jump'; + } +} {1} +do_test fts3ad-2.5 { + execsql { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize = porter); + INSERT INTO t1(rowid, content) VALUES(1, 'running and jumping'); + SELECT rowid FROM t1 WHERE content MATCH 'run jump'; + } +} {1} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3ae.test b/components/external/SQLite-3.8.1/test/fts3ae.test new file mode 100644 index 0000000000000000000000000000000000000000..b87268897df8ea00f9294aa291e1fb768af0c902 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3ae.test @@ -0,0 +1,85 @@ +# 2006 October 19 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing deletions in the FTS3 module. +# +# $Id: fts3ae.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Construct a full-text search table containing keywords which are the +# ordinal numbers of the bit positions set for a sequence of integers, +# which are used for the rowid. There are a total of 30 INSERT and +# DELETE statements, so that we'll test both the segmentMerge() merge +# (over the first 16) and the termSelect() merge (over the level-1 +# segment and 14 level-0 segments). +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(content); + INSERT INTO t1 (rowid, content) VALUES(1, 'one'); + INSERT INTO t1 (rowid, content) VALUES(2, 'two'); + INSERT INTO t1 (rowid, content) VALUES(3, 'one two'); + INSERT INTO t1 (rowid, content) VALUES(4, 'three'); + DELETE FROM t1 WHERE rowid = 1; + INSERT INTO t1 (rowid, content) VALUES(5, 'one three'); + INSERT INTO t1 (rowid, content) VALUES(6, 'two three'); + INSERT INTO t1 (rowid, content) VALUES(7, 'one two three'); + DELETE FROM t1 WHERE rowid = 4; + INSERT INTO t1 (rowid, content) VALUES(8, 'four'); + INSERT INTO t1 (rowid, content) VALUES(9, 'one four'); + INSERT INTO t1 (rowid, content) VALUES(10, 'two four'); + DELETE FROM t1 WHERE rowid = 7; + INSERT INTO t1 (rowid, content) VALUES(11, 'one two four'); + INSERT INTO t1 (rowid, content) VALUES(12, 'three four'); + INSERT INTO t1 (rowid, content) VALUES(13, 'one three four'); + DELETE FROM t1 WHERE rowid = 10; + INSERT INTO t1 (rowid, content) VALUES(14, 'two three four'); + INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four'); + INSERT INTO t1 (rowid, content) VALUES(16, 'five'); + DELETE FROM t1 WHERE rowid = 13; + INSERT INTO t1 (rowid, content) VALUES(17, 'one five'); + INSERT INTO t1 (rowid, content) VALUES(18, 'two five'); + INSERT INTO t1 (rowid, content) VALUES(19, 'one two five'); + DELETE FROM t1 WHERE rowid = 16; + INSERT INTO t1 (rowid, content) VALUES(20, 'three five'); + INSERT INTO t1 (rowid, content) VALUES(21, 'one three five'); + INSERT INTO t1 (rowid, content) VALUES(22, 'two three five'); + DELETE FROM t1 WHERE rowid = 19; + DELETE FROM t1 WHERE rowid = 22; +} + +do_test fts3ae-1.1 { + execsql {SELECT COUNT(*) FROM t1} +} {14} + +do_test fts3ae-2.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {3 5 9 11 15 17 21} + +do_test fts3ae-2.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'} +} {2 3 6 11 14 15 18} + +do_test fts3ae-2.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'} +} {5 6 12 14 15 20 21} + +do_test fts3ae-2.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'} +} {8 9 11 12 14 15} + +do_test fts3ae-2.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'} +} {17 18 20 21} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3af.test b/components/external/SQLite-3.8.1/test/fts3af.test new file mode 100644 index 0000000000000000000000000000000000000000..221ac4c3bcab5b1f8ec821bab8fbd788189c9e92 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3af.test @@ -0,0 +1,90 @@ +# 2006 October 19 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing updates in the FTS3 module. +# +# $Id: fts3af.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Construct a full-text search table containing keywords which are the +# ordinal numbers of the bit positions set for a sequence of integers, +# which are used for the rowid. There are a total of 31 INSERT, +# UPDATE, and DELETE statements, so that we'll test both the +# segmentMerge() merge (over the first 16) and the termSelect() merge +# (over the level-1 segment and 15 level-0 segments). +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(content); + INSERT INTO t1 (rowid, content) VALUES(1, 'one'); + INSERT INTO t1 (rowid, content) VALUES(2, 'two'); + INSERT INTO t1 (rowid, content) VALUES(3, 'one two'); + INSERT INTO t1 (rowid, content) VALUES(4, 'three'); + INSERT INTO t1 (rowid, content) VALUES(5, 'one three'); + INSERT INTO t1 (rowid, content) VALUES(6, 'two three'); + INSERT INTO t1 (rowid, content) VALUES(7, 'one two three'); + DELETE FROM t1 WHERE rowid = 4; + INSERT INTO t1 (rowid, content) VALUES(8, 'four'); + UPDATE t1 SET content = 'update one three' WHERE rowid = 1; + INSERT INTO t1 (rowid, content) VALUES(9, 'one four'); + INSERT INTO t1 (rowid, content) VALUES(10, 'two four'); + DELETE FROM t1 WHERE rowid = 7; + INSERT INTO t1 (rowid, content) VALUES(11, 'one two four'); + INSERT INTO t1 (rowid, content) VALUES(12, 'three four'); + INSERT INTO t1 (rowid, content) VALUES(13, 'one three four'); + DELETE FROM t1 WHERE rowid = 10; + INSERT INTO t1 (rowid, content) VALUES(14, 'two three four'); + INSERT INTO t1 (rowid, content) VALUES(15, 'one two three four'); + UPDATE t1 SET content = 'update two five' WHERE rowid = 8; + INSERT INTO t1 (rowid, content) VALUES(16, 'five'); + DELETE FROM t1 WHERE rowid = 13; + INSERT INTO t1 (rowid, content) VALUES(17, 'one five'); + INSERT INTO t1 (rowid, content) VALUES(18, 'two five'); + INSERT INTO t1 (rowid, content) VALUES(19, 'one two five'); + DELETE FROM t1 WHERE rowid = 16; + INSERT INTO t1 (rowid, content) VALUES(20, 'three five'); + INSERT INTO t1 (rowid, content) VALUES(21, 'one three five'); + INSERT INTO t1 (rowid, content) VALUES(22, 'two three five'); + DELETE FROM t1 WHERE rowid = 19; + UPDATE t1 SET content = 'update' WHERE rowid = 15; +} + +do_test fts3af-1.1 { + execsql {SELECT COUNT(*) FROM t1} +} {16} + +do_test fts3af-2.0 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'update'} +} {1 8 15} + +do_test fts3af-2.1 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'one'} +} {1 3 5 9 11 17 21} + +do_test fts3af-2.2 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'two'} +} {2 3 6 8 11 14 18 22} + +do_test fts3af-2.3 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'three'} +} {1 5 6 12 14 20 21 22} + +do_test fts3af-2.4 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'four'} +} {9 11 12 14} + +do_test fts3af-2.5 { + execsql {SELECT rowid FROM t1 WHERE content MATCH 'five'} +} {8 17 18 20 21 22} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3ag.test b/components/external/SQLite-3.8.1/test/fts3ag.test new file mode 100644 index 0000000000000000000000000000000000000000..18ed5ae31f5e3ef1fed24711434c3a94ad498352 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3ag.test @@ -0,0 +1,94 @@ +# 2006 October 19 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing handling of edge cases for various doclist +# merging functions in the FTS3 module query logic. +# +# $Id: fts3ag.test,v 1.2 2007/11/16 00:23:08 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(content); + INSERT INTO t1 (rowid, content) VALUES(1, 'this is a test'); + INSERT INTO t1 (rowid, content) VALUES(2, 'also a test'); +} + +# No hits at all. Returns empty doclists from termSelect(). +do_test fts3ag-1.1 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something'} +} {} + +# Empty left in docListExceptMerge(). +do_test fts3ag-1.2 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH '-this something'} +} {} + +# Empty right in docListExceptMerge(). +do_test fts3ag-1.3 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this -something'} +} {1} + +# Empty left in docListPhraseMerge(). +do_test fts3ag-1.4 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"this something"'} +} {} + +# Empty right in docListPhraseMerge(). +do_test fts3ag-1.5 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH '"something is"'} +} {} + +# Empty left in docListOrMerge(). +do_test fts3ag-1.6 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something OR this'} +} {1} + +# Empty right in docListOrMerge(). +do_test fts3ag-1.7 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this OR something'} +} {1} + +# Empty left in docListAndMerge(). +do_test fts3ag-1.8 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something this'} +} {} + +# Empty right in docListAndMerge(). +do_test fts3ag-1.9 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this something'} +} {} + +# No support for all-except queries. +do_test fts3ag-1.10 { + catchsql {SELECT rowid FROM t1 WHERE t1 MATCH '-this -something'} +} {1 {malformed MATCH expression: [-this -something]}} + +# Test that docListOrMerge() correctly handles reaching the end of one +# doclist before it reaches the end of the other. +do_test fts3ag-1.11 { +breakpoint + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'this OR also'} +} {1 2} +do_test fts3ag-1.12 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'also OR this'} +} {1 2} + +# Empty left and right in docListOrMerge(). Each term matches neither +# row, and when combined there was an assertion failure. +do_test fts3ag-1.13 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something OR nothing'} +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3ah.test b/components/external/SQLite-3.8.1/test/fts3ah.test new file mode 100644 index 0000000000000000000000000000000000000000..3810ec37b5c8c5bd35683c5537520b6b1f59d299 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3ah.test @@ -0,0 +1,71 @@ +# 2006 October 31 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# here is testing correct handling of very long terms. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Generate a document of bigterms based on characters from the list +# chars. +proc bigtermdoc {chars len} { + set doc "" + foreach char $chars { + append doc " " [string repeat $char $len] + } + return $doc +} + +set len 5000 +set doc1 [bigtermdoc {a b c d} $len] +set doc2 [bigtermdoc {b d e f} $len] +set doc3 [bigtermdoc {a c e} $len] + +set aterm [string repeat a $len] +set bterm [string repeat b $len] +set xterm [string repeat x $len] + +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(content); + INSERT INTO t1 (rowid, content) VALUES(1, $doc1); + INSERT INTO t1 (rowid, content) VALUES(2, $doc2); + INSERT INTO t1 (rowid, content) VALUES(3, $doc3); +} + +# No hits at all. Returns empty doclists from termSelect(). +do_test fts3ah-1.1 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'something'} +} {} + +do_test fts3ah-1.2 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH $aterm} +} {1 3} + +do_test fts3ah-1.3 { + execsql {SELECT rowid FROM t1 WHERE t1 MATCH $xterm} +} {} + +do_test fts3ah-1.4 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '$aterm -$xterm'" +} {1 3} + +do_test fts3ah-1.5 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"$aterm $bterm\"'" +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3ai.test b/components/external/SQLite-3.8.1/test/fts3ai.test new file mode 100644 index 0000000000000000000000000000000000000000..b17b5bdd553d91993341463f17de60a30a521002 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3ai.test @@ -0,0 +1,92 @@ +# 2007 January 17 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite fts3 library. The +# focus here is testing handling of UPDATE when using UTF-16-encoded +# databases. +# +# $Id: fts3ai.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +ifcapable !utf16 { + finish_test + return +} + +# Return the UTF-16 representation of the supplied UTF-8 string $str. +# If $nt is true, append two 0x00 bytes as a nul terminator. +# NOTE(shess) Copied from capi3.test. +proc utf16 {str {nt 1}} { + set r [encoding convertto unicode $str] + if {$nt} { + append r "\x00\x00" + } + return $r +} + +db eval { + PRAGMA encoding = "UTF-16le"; + CREATE VIRTUAL TABLE t1 USING fts3(content); +} + +do_test fts3ai-1.0 { + execsql {PRAGMA encoding} +} {UTF-16le} + +do_test fts3ai-1.1 { + execsql {INSERT INTO t1 (rowid, content) VALUES(1, 'one')} + execsql {SELECT content FROM t1 WHERE rowid = 1} +} {one} + +do_test fts3ai-1.2 { + set sql "INSERT INTO t1 (rowid, content) VALUES(2, 'two')" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 2} +} {two} + +do_test fts3ai-1.3 { + set sql "INSERT INTO t1 (rowid, content) VALUES(3, 'three')" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + set sql "UPDATE t1 SET content = 'trois' WHERE rowid = 3" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 3} +} {trois} + +do_test fts3ai-1.4 { + set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(4, 'four')}] + set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 4} +} {four} + +do_test fts3ai-1.5 { + set sql16 [utf16 {INSERT INTO t1 (rowid, content) VALUES(5, 'five')}] + set STMT [sqlite3_prepare16 $DB $sql16 -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + set sql "UPDATE t1 SET content = 'cinq' WHERE rowid = 5" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_step $STMT + sqlite3_finalize $STMT + execsql {SELECT content FROM t1 WHERE rowid = 5} +} {cinq} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3aj.test b/components/external/SQLite-3.8.1/test/fts3aj.test new file mode 100644 index 0000000000000000000000000000000000000000..f3d46f2ad80c6121cd7034d9220c5a6772044d17 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3aj.test @@ -0,0 +1,89 @@ +# 2007 February 6 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. This +# tests creating fts3 tables in an attached database. +# +# $Id: fts3aj.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Clean up anything left over from a previous pass. +forcedelete test2.db +forcedelete test2.db-journal +sqlite3 db2 test2.db + +db eval { + CREATE VIRTUAL TABLE t3 USING fts3(content); + INSERT INTO t3 (rowid, content) VALUES(1, "hello world"); +} + +db2 eval { + CREATE VIRTUAL TABLE t1 USING fts3(content); + INSERT INTO t1 (rowid, content) VALUES(1, "hello world"); + INSERT INTO t1 (rowid, content) VALUES(2, "hello there"); + INSERT INTO t1 (rowid, content) VALUES(3, "cruel world"); +} + +# This has always worked because the t1_* tables used by fts3 will be +# the defaults. +do_test fts3aj-1.1 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + SELECT rowid FROM t1 WHERE t1 MATCH 'hello'; + DETACH DATABASE two; + } +} {1 2} +# Make certain we're detached if there was an error. +catch {db eval {DETACH DATABASE two}} + +# In older code, this appears to work fine, but the t2_* tables used +# by fts3 will be created in database 'main' instead of database +# 'two'. It appears to work fine because the tables end up being the +# defaults, but obviously is badly broken if you hope to use things +# other than in the exact same ATTACH setup. +do_test fts3aj-1.2 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + CREATE VIRTUAL TABLE two.t2 USING fts3(content); + INSERT INTO t2 (rowid, content) VALUES(1, "hello world"); + INSERT INTO t2 (rowid, content) VALUES(2, "hello there"); + INSERT INTO t2 (rowid, content) VALUES(3, "cruel world"); + SELECT rowid FROM t2 WHERE t2 MATCH 'hello'; + DETACH DATABASE two; + } +} {1 2} +catch {db eval {DETACH DATABASE two}} + +# In older code, this broke because the fts3 code attempted to create +# t3_* tables in database 'main', but they already existed. Normally +# this wouldn't happen without t3 itself existing, in which case the +# fts3 code would never be called in the first place. +do_test fts3aj-1.3 { + execsql { + ATTACH DATABASE 'test2.db' AS two; + + CREATE VIRTUAL TABLE two.t3 USING fts3(content); + INSERT INTO two.t3 (rowid, content) VALUES(2, "hello there"); + INSERT INTO two.t3 (rowid, content) VALUES(3, "cruel world"); + SELECT rowid FROM two.t3 WHERE t3 MATCH 'hello'; + + DETACH DATABASE two; + } db2 +} {2} +catch {db eval {DETACH DATABASE two}} + +catch {db2 close} +forcedelete test2.db + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3ak.test b/components/external/SQLite-3.8.1/test/fts3ak.test new file mode 100644 index 0000000000000000000000000000000000000000..a263f0b7404d552425850945faaf134284421322 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3ak.test @@ -0,0 +1,105 @@ +# 2007 March 9 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. These +# make sure that fts3 insertion buffering is fully transparent when +# using transactions. +# +# $Id: fts3ak.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(content); + INSERT INTO t1 (rowid, content) VALUES(1, "hello world"); + INSERT INTO t1 (rowid, content) VALUES(2, "hello there"); + INSERT INTO t1 (rowid, content) VALUES(3, "cruel world"); +} + +# Test that possibly-buffered inserts went through after commit. +do_test fts3ak-1.1 { + execsql { + BEGIN TRANSACTION; + INSERT INTO t1 (rowid, content) VALUES(4, "false world"); + INSERT INTO t1 (rowid, content) VALUES(5, "false door"); + COMMIT TRANSACTION; + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + } +} {1 3 4} + +# Test that buffered inserts are seen by selects in the same +# transaction. +do_test fts3ak-1.2 { + execsql { + BEGIN TRANSACTION; + INSERT INTO t1 (rowid, content) VALUES(6, "another world"); + INSERT INTO t1 (rowid, content) VALUES(7, "another test"); + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + COMMIT TRANSACTION; + } +} {1 3 4 6} + +# Test that buffered inserts are seen within a transaction. This is +# really the same test as 1.2. +do_test fts3ak-1.3 { + execsql { + BEGIN TRANSACTION; + INSERT INTO t1 (rowid, content) VALUES(8, "second world"); + INSERT INTO t1 (rowid, content) VALUES(9, "second sight"); + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + ROLLBACK TRANSACTION; + } +} {1 3 4 6 8} + +# Double-check that the previous result doesn't persist past the +# rollback! +do_test fts3ak-1.4 { + execsql { + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + } +} {1 3 4 6} + +# Test it all together. +do_test fts3ak-1.5 { + execsql { + BEGIN TRANSACTION; + INSERT INTO t1 (rowid, content) VALUES(10, "second world"); + INSERT INTO t1 (rowid, content) VALUES(11, "second sight"); + ROLLBACK TRANSACTION; + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; + } +} {1 3 4 6} + +# Test that the obvious case works. +do_test fts3ak-1.6 { + execsql { + BEGIN; + INSERT INTO t1 (rowid, content) VALUES(12, "third world"); + COMMIT; + SELECT rowid FROM t1 WHERE t1 MATCH 'third'; + } +} {12} + +# This is exactly the same as the previous test, except that older +# code loses the INSERT due to an SQLITE_SCHEMA error. +do_test fts3ak-1.7 { + execsql { + BEGIN; + INSERT INTO t1 (rowid, content) VALUES(13, "third dimension"); + CREATE TABLE x (c); + COMMIT; + SELECT rowid FROM t1 WHERE t1 MATCH 'dimension'; + } +} {13} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3al.test b/components/external/SQLite-3.8.1/test/fts3al.test new file mode 100644 index 0000000000000000000000000000000000000000..02cc0d1695297c7394e97be5bb971e8b1b619973 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3al.test @@ -0,0 +1,73 @@ +# 2007 March 28 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing isspace/isalnum/tolower problems with the +# FTS3 module. Unfortunately, this code isn't a really principled set +# of tests, because it is impossible to know where new uses of these +# functions might appear. +# +# $Id: fts3al.test,v 1.2 2007/12/13 21:54:11 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Tests that startsWith() (calls isspace, tolower, isalnum) can handle +# hi-bit chars. parseSpec() also calls isalnum here. +do_test fts3al-1.1 { + execsql "CREATE VIRTUAL TABLE t1 USING fts3(content, \x80)" +} {} + +# Additionally tests isspace() call in getToken(), and isalnum() call +# in tokenListToIdList(). +do_test fts3al-1.2 { + catch { + execsql "CREATE VIRTUAL TABLE t2 USING fts3(content, tokenize \x80)" + } + sqlite3_errmsg $DB +} "unknown tokenizer: \x80" + +# Additionally test final isalnum() in startsWith(). +do_test fts3al-1.3 { + execsql "CREATE VIRTUAL TABLE t3 USING fts3(content, tokenize\x80)" +} {} + +# The snippet-generation code has calls to isspace() which are sort of +# hard to get to. It finds convenient breakpoints by starting ~40 +# chars before and after the matched term, and scanning ~10 chars +# around that position for isspace() characters. The long word with +# embedded hi-bit chars causes one of these isspace() calls to be +# exercised. The version with a couple extra spaces should cause the +# other isspace() call to be exercised. [Both cases have been tested +# in the debugger, but I'm hoping to continue to catch it if simple +# constant changes change things slightly. +# +# The trailing and leading hi-bit chars help with code which tests for +# isspace() to coalesce multiple spaces. +# +# UPDATE: The above is no longer true; there is no such code in fts3. +# But leave the test in just the same. +# + +set word "\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80xxxxx\x80" +set phrase1 "$word $word $word target $word $word $word" +set phrase2 "$word $word $word target $word $word $word" + +db eval {CREATE VIRTUAL TABLE t4 USING fts3(content)} +db eval "INSERT INTO t4 (content) VALUES ('$phrase1')" +db eval "INSERT INTO t4 (content) VALUES ('$phrase2')" + +do_test fts3al-1.4 { + execsql {SELECT rowid, length(snippet(t4)) FROM t4 WHERE t4 MATCH 'target'} +} {1 241 2 247} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3am.test b/components/external/SQLite-3.8.1/test/fts3am.test new file mode 100644 index 0000000000000000000000000000000000000000..4a09cd80fb538ce375ea81afd37a6465f626973a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3am.test @@ -0,0 +1,65 @@ +# 2007 April 9 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements regression tests for SQLite library. fts3 +# DELETE handling assumed all fields were non-null. This was not +# the intention at all. +# +# $Id: fts3am.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(col_a, col_b); + + INSERT INTO t1(rowid, col_a, col_b) VALUES(1, 'testing', 'testing'); + INSERT INTO t1(rowid, col_a, col_b) VALUES(2, 'only a', null); + INSERT INTO t1(rowid, col_a, col_b) VALUES(3, null, 'only b'); + INSERT INTO t1(rowid, col_a, col_b) VALUES(4, null, null); +} + +do_test fts3am-1.0 { + execsql { + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {2 2 4} + +do_test fts3am-1.1 { + execsql { + DELETE FROM t1 WHERE rowid = 1; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {1 1 3} + +do_test fts3am-1.2 { + execsql { + DELETE FROM t1 WHERE rowid = 2; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {0 1 2} + +do_test fts3am-1.3 { + execsql { + DELETE FROM t1 WHERE rowid = 3; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {0 0 1} + +do_test fts3am-1.4 { + execsql { + DELETE FROM t1 WHERE rowid = 4; + SELECT COUNT(col_a), COUNT(col_b), COUNT(*) FROM t1; + } +} {0 0 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3an.test b/components/external/SQLite-3.8.1/test/fts3an.test new file mode 100644 index 0000000000000000000000000000000000000000..521102776718fe2215e0028a68d3d99e83524c98 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3an.test @@ -0,0 +1,218 @@ +# 2007 April 26 +# +# The author disclaims copyright to this source code. +# +#************************************************************************* +# This file implements tests for prefix-searching in the fts3 +# component of the SQLite library. +# +# $Id: fts3an.test,v 1.2 2007/12/13 21:54:11 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# A large string to prime the pump with. +set text { + Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas + iaculis mollis ipsum. Praesent rhoncus placerat justo. Duis non quam + sed turpis posuere placerat. Curabitur et lorem in lorem porttitor + aliquet. Pellentesque bibendum tincidunt diam. Vestibulum blandit + ante nec elit. In sapien diam, facilisis eget, dictum sed, viverra + at, felis. Vestibulum magna. Sed magna dolor, vestibulum rhoncus, + ornare vel, vulputate sit amet, felis. Integer malesuada, tellus at + luctus gravida, diam nunc porta nibh, nec imperdiet massa metus eu + lectus. Aliquam nisi. Nunc fringilla nulla at lectus. Suspendisse + potenti. Cum sociis natoque penatibus et magnis dis parturient + montes, nascetur ridiculus mus. Pellentesque odio nulla, feugiat eu, + suscipit nec, consequat quis, risus. +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(c); + + INSERT INTO t1(rowid, c) VALUES(1, $text); + INSERT INTO t1(rowid, c) VALUES(2, 'Another lovely row'); +} + +# Exact match +do_test fts3an-1.1 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lorem'" +} {1} + +# And a prefix +do_test fts3an-1.2 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lore*'" +} {1} + +# Prefix includes exact match +do_test fts3an-1.3 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lorem*'" +} {1} + +# Make certain everything isn't considered a prefix! +do_test fts3an-1.4 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lore'" +} {} + +# Prefix across multiple rows. +do_test fts3an-1.5 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lo*'" +} {1 2} + +# Likewise, with multiple hits in one document. +do_test fts3an-1.6 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'l*'" +} {1 2} + +# Prefix which should only hit one document. +do_test fts3an-1.7 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lov*'" +} {2} + +# * not at end is dropped. +do_test fts3an-1.8 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH 'lo *'" +} {} + +# Stand-alone * is dropped. +do_test fts3an-1.9 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '*'" +} {} + +# Phrase-query prefix. +do_test fts3an-1.10 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"lovely r*\"'" +} {2} +do_test fts3an-1.11 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"lovely r\"'" +} {} + +# Phrase query with multiple prefix matches. +do_test fts3an-1.12 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"a* l*\"'" +} {1 2} + +# Phrase query with multiple prefix matches. +do_test fts3an-1.13 { + execsql "SELECT rowid FROM t1 WHERE t1 MATCH '\"a* l* row\"'" +} {2} + + + + +# Test across updates (and, by implication, deletes). + +# Version of text without "lorem". +regsub -all {[Ll]orem} $text '' ntext + +db eval { + CREATE VIRTUAL TABLE t2 USING fts3(c); + + INSERT INTO t2(rowid, c) VALUES(1, $text); + INSERT INTO t2(rowid, c) VALUES(2, 'Another lovely row'); + UPDATE t2 SET c = $ntext WHERE rowid = 1; +} + +# Can't see lorem as an exact match. +do_test fts3an-2.1 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lorem'" +} {} + +# Can't see a prefix of lorem, either. +do_test fts3an-2.2 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lore*'" +} {} + +# Can see lovely in the other document. +do_test fts3an-2.3 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lo*'" +} {2} + +# Can still see other hits. +do_test fts3an-2.4 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'l*'" +} {1 2} + +# Prefix which should only hit one document. +do_test fts3an-2.5 { + execsql "SELECT rowid FROM t2 WHERE t2 MATCH 'lov*'" +} {2} + + + +# Test with a segment which will have multiple levels in the tree. + +# Build a big document with lots of unique terms. +set bigtext $text +foreach c {a b c d e} { + regsub -all {[A-Za-z]+} $bigtext "&$c" t + append bigtext $t +} + +# Populate a table with many copies of the big document, so that we +# can test the number of hits found. Populate $ret with the expected +# hit counts for each row. offsets() returns 4 elements for every +# hit. We'll have 6 hits for row 1, 1 for row 2, and 6*(2^5)==192 for +# $bigtext. +set ret {6 1} +db eval { + BEGIN; + CREATE VIRTUAL TABLE t3 USING fts3(c); + + INSERT INTO t3(rowid, c) VALUES(1, $text); + INSERT INTO t3(rowid, c) VALUES(2, 'Another lovely row'); +} +for {set i 0} {$i<68} {incr i} { + db eval {INSERT INTO t3(rowid, c) VALUES(3+$i, $bigtext)} + lappend ret 192 +} +db eval {COMMIT;} + +# Test that we get the expected number of hits. +do_test fts3an-3.1 { + set t {} + db eval {SELECT offsets(t3) as o FROM t3 WHERE t3 MATCH 'l*'} { + set l [llength $o] + lappend t [expr {$l/4}] + } + set t +} $ret + +# Test a boundary condition: More than 2^16 terms that match a searched for +# prefix in a single segment. +# +puts "This next test can take a little while (~ 30 seconds)..." +do_test fts3an-4.1 { + execsql { CREATE VIRTUAL TABLE ft USING fts3(x) } + execsql BEGIN + execsql { INSERT INTO ft VALUES(NULL) } + execsql { INSERT INTO ft SELECT * FROM ft } ;# 2 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 4 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 8 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 16 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 32 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 64 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 128 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 256 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 512 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 1024 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 2048 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 4096 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 8192 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 16384 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 32768 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 65536 + execsql { INSERT INTO ft SELECT * FROM ft } ;# 131072 + execsql COMMIT + execsql { UPDATE ft SET x = 'abc' || rowid } + execsql { SELECT count(*) FROM ft WHERE x MATCH 'abc*' } +} {131072} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3ao.test b/components/external/SQLite-3.8.1/test/fts3ao.test new file mode 100644 index 0000000000000000000000000000000000000000..91693094dbf54929b2fafcd5c7d7cabb876c13eb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3ao.test @@ -0,0 +1,222 @@ +# 2007 June 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# +# $Id: fts3ao.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +set ::testprefix fts3ao + +#--------------------------------------------------------------------- +# These tests, fts3ao-1.*, test that ticket #2429 is fixed. +# +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(a, b, c); + INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one four two'); +} +do_test fts3ao-1.1 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE c MATCH 'four'; + } +} {1 {one four two}} +do_test fts3ao-1.2 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE b MATCH 'four'; + } +} {1 {one four}} +do_test fts3ao-1.3 { + execsql { + SELECT rowid, snippet(t1) FROM t1 WHERE a MATCH 'four'; + } +} {1 {one three four}} + +#--------------------------------------------------------------------- +# Test that it is possible to rename an fts3 table. +# +do_test fts3ao-2.1 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {t1 t1_content t1_segments t1_segdir} +do_test fts3ao-2.2 { + execsql { ALTER TABLE t1 RENAME to fts_t1; } +} {} +do_test fts3ao-2.3 { + execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; } +} {1 {one three four}} +do_test fts3ao-2.4 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir} + +# See what happens when renaming the fts3 table fails. +# +do_test fts3ao-2.5 { + catchsql { + CREATE TABLE t1_segdir(a, b, c); + ALTER TABLE fts_t1 RENAME to t1; + } +} {1 {SQL logic error or missing database}} +do_test fts3ao-2.6 { + execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; } +} {1 {one three four}} +do_test fts3ao-2.7 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir t1_segdir} + +# See what happens when renaming the fts3 table fails inside a transaction. +# +do_test fts3ao-2.8 { + execsql { + BEGIN; + INSERT INTO fts_t1(a, b, c) VALUES('one two three', 'one four', 'one two'); + } +} {} +do_test fts3ao-2.9 { + catchsql { + ALTER TABLE fts_t1 RENAME to t1; + } +} {1 {SQL logic error or missing database}} +do_test fts3ao-2.10 { + execsql { SELECT rowid, snippet(fts_t1) FROM fts_t1 WHERE a MATCH 'four'; } +} {1 {one three four}} +do_test fts3ao-2.11 { + execsql { SELECT tbl_name FROM sqlite_master WHERE type = 'table'} +} {fts_t1 fts_t1_content fts_t1_segments fts_t1_segdir t1_segdir} +do_test fts3ao-2.12 { + execsql COMMIT + execsql {SELECT a FROM fts_t1} +} {{one three four} {one two three}} +do_test fts3ao-2.12 { + execsql { SELECT a, b, c FROM fts_t1 WHERE c MATCH 'four'; } +} {{one three four} {one four} {one four two}} + +#------------------------------------------------------------------- +# Close, delete and reopen the database. The following test should +# be run on an initially empty db. +# +db close +forcedelete test.db test.db-journal +sqlite3 db test.db + +do_test fts3ao-3.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts3(a, b, c); + INSERT INTO t1(a, b, c) VALUES('one three four', 'one four', 'one two'); + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + } +} {{one three four} {one four} {one two}} + +# This test was crashing at one point. +# +do_test fts3ao-3.2 { + execsql { + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + CREATE TABLE t3(a, b, c); + SELECT a, b, c FROM t1 WHERE c MATCH 'two'; + } +} {{one three four} {one four} {one two} {one three four} {one four} {one two}} + +#--------------------------------------------------------------------- +# Test that it is possible to rename an fts3 table in an attached +# database. +# +forcedelete test2.db test2.db-journal + +do_test fts3ao-3.1 { + execsql { + ATTACH 'test2.db' AS aux; + CREATE VIRTUAL TABLE aux.t1 USING fts3(a, b, c); + INSERT INTO aux.t1(a, b, c) VALUES( + 'neung song sahm', 'neung see', 'neung see song' + ); + } +} {} + +do_test fts3ao-3.2 { + execsql { SELECT a, b, c FROM aux.t1 WHERE a MATCH 'song'; } +} {{neung song sahm} {neung see} {neung see song}} + +do_test fts3ao-3.3 { + execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; } +} {{one three four} {one four} {one two}} + +do_test fts3ao-3.4 { + execsql { ALTER TABLE aux.t1 RENAME TO t2 } +} {} + +do_test fts3ao-3.2 { + execsql { SELECT a, b, c FROM t2 WHERE a MATCH 'song'; } +} {{neung song sahm} {neung see} {neung see song}} + +do_test fts3ao-3.3 { + execsql { SELECT a, b, c FROM t1 WHERE c MATCH 'two'; } +} {{one three four} {one four} {one two}} + +#--------------------------------------------------------------------- +# Test that it is possible to rename an fts3 table within a +# transaction. +# +do_test fts3ao-4.1 { + execsql { + CREATE VIRTUAL TABLE t4 USING fts3; + INSERT INTO t4 VALUES('the quick brown fox'); + } +} {} +do_test fts3ao-4.2 { + execsql { + BEGIN; + INSERT INTO t4 VALUES('jumped over the'); + } +} {} +do_test fts3ao-4.3 { execsql { ALTER TABLE t4 RENAME TO t5; } } {} +do_test fts3ao-4.4 { execsql { INSERT INTO t5 VALUES('lazy dog'); } } {} +do_test fts3ao-4.5 { execsql COMMIT } {} +do_test fts3ao-4.6 { + execsql { SELECT * FROM t5 } +} {{the quick brown fox} {jumped over the} {lazy dog}} +do_test fts3ao-4.7 { + execsql { + BEGIN; + INSERT INTO t5 VALUES('Down came a jumbuck to drink at that billabong'); + ALTER TABLE t5 RENAME TO t6; + INSERT INTO t6 VALUES('Down came the troopers, one, two, three'); + ROLLBACK; + SELECT * FROM t5; + } +} {{the quick brown fox} {jumped over the} {lazy dog}} +do_execsql_test fts3ao-4.8 { + SELECT snippet(t5, '[', ']') FROM t5 WHERE t5 MATCH 'the' +} {{[the] quick brown fox} {jumped over [the]}} + +# Test that it is possible to rename an FTS4 table. Renaming an FTS4 table +# involves renaming the extra %_docsize and %_stat tables. +# +do_execsql_test 5.1 { + CREATE VIRTUAL TABLE t7 USING FTS4; + INSERT INTO t7 VALUES('coined by a German clinician'); + SELECT count(*) FROM sqlite_master WHERE name LIKE 't7%'; + SELECT count(*) FROM sqlite_master WHERE name LIKE 't8%'; +} {6 0} +do_execsql_test 5.2 { + ALTER TABLE t7 RENAME TO t8; + SELECT count(*) FROM sqlite_master WHERE name LIKE 't7%'; + SELECT count(*) FROM sqlite_master WHERE name LIKE 't8%'; +} {0 6} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3atoken.test b/components/external/SQLite-3.8.1/test/fts3atoken.test new file mode 100644 index 0000000000000000000000000000000000000000..b7722c7d041b3509bee6891b68da04ea82067530 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3atoken.test @@ -0,0 +1,195 @@ +# 2007 June 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing the pluggable tokeniser feature of the +# FTS3 module. +# +# $Id: fts3atoken.test,v 1.1 2007/08/20 17:38:42 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +set ::testprefix fts3token + +proc escape_string {str} { + set out "" + foreach char [split $str ""] { + scan $char %c i + if {$i<=127} { + append out $char + } else { + append out [format {\x%.4x} $i] + } + } + set out +} + +#-------------------------------------------------------------------------- +# Test cases fts3token-1.* are the warm-body test for the SQL scalar +# function fts3_tokenizer(). The procedure is as follows: +# +# 1: Verify that there is no such fts3 tokenizer as 'blah'. +# +# 2: Query for the built-in tokenizer 'simple'. Insert a copy of the +# retrieved value as tokenizer 'blah'. +# +# 3: Test that the value returned for tokenizer 'blah' is now the +# same as that retrieved for 'simple'. +# +# 4: Test that it is now possible to create an fts3 table using +# tokenizer 'blah' (it was not possible in step 1). +# +# 5: Test that the table created to use tokenizer 'blah' is usable. +# +do_test fts3token-1.1 { + catchsql { + CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize blah); + } +} {1 {unknown tokenizer: blah}} +do_test fts3token-1.2 { + execsql { + SELECT fts3_tokenizer('blah', fts3_tokenizer('simple')) IS NULL; + } +} {0} +do_test fts3token-1.3 { + execsql { + SELECT fts3_tokenizer('blah') == fts3_tokenizer('simple'); + } +} {1} +do_test fts3token-1.4 { + catchsql { + CREATE VIRTUAL TABLE t1 USING fts3(content, tokenize blah); + } +} {0 {}} +do_test fts3token-1.5 { + execsql { + INSERT INTO t1(content) VALUES('There was movement at the station'); + INSERT INTO t1(content) VALUES('For the word has passed around'); + INSERT INTO t1(content) VALUES('That the colt from ol regret had got away'); + SELECT content FROM t1 WHERE content MATCH 'movement' + } +} {{There was movement at the station}} + +#-------------------------------------------------------------------------- +# Test cases fts3token-2.* test error cases in the scalar function based +# API for getting and setting tokenizers. +# +do_test fts3token-2.1 { + catchsql { + SELECT fts3_tokenizer('nosuchtokenizer'); + } +} {1 {unknown tokenizer: nosuchtokenizer}} + +#-------------------------------------------------------------------------- +# Test cases fts3token-3.* test the three built-in tokenizers with a +# simple input string via the built-in test function. This is as much +# to test the test function as the tokenizer implementations. +# +do_test fts3token-3.1 { + execsql { + SELECT fts3_tokenizer_test('simple', 'I don''t see how'); + } +} {{0 i I 1 don don 2 t t 3 see see 4 how how}} +do_test fts3token-3.2 { + execsql { + SELECT fts3_tokenizer_test('porter', 'I don''t see how'); + } +} {{0 i I 1 don don 2 t t 3 see see 4 how how}} +ifcapable icu { + do_test fts3token-3.3 { + execsql { + SELECT fts3_tokenizer_test('icu', 'I don''t see how'); + } + } {{0 i I 1 don't don't 2 see see 3 how how}} +} + +#-------------------------------------------------------------------------- +# Test cases fts3token-4.* test the ICU tokenizer. In practice, this +# tokenizer only has two modes - "thai" and "everybody else". Some other +# Asian languages (Lao, Khmer etc.) require the same special treatment as +# Thai, but ICU doesn't support them yet. +# +ifcapable icu { + + proc do_icu_test {name locale input output} { + set ::out [db eval { SELECT fts3_tokenizer_test('icu', $locale, $input) }] + do_test $name { + lindex $::out 0 + } $output + } + + do_icu_test fts3token-4.1 en_US {} {} + do_icu_test fts3token-4.2 en_US {Test cases fts3} [list \ + 0 test Test 1 cases cases 2 fts3 fts3 + ] + + # The following test shows that ICU is smart enough to recognise + # Thai chararacters, even when the locale is set to English/United + # States. + # + set input "\u0e2d\u0e30\u0e44\u0e23\u0e19\u0e30\u0e04\u0e23\u0e31\u0e1a" + set output "0 \u0e2d\u0e30\u0e44\u0e23 \u0e2d\u0e30\u0e44\u0e23 " + append output "1 \u0e19\u0e30 \u0e19\u0e30 " + append output "2 \u0e04\u0e23\u0e31\u0e1a \u0e04\u0e23\u0e31\u0e1a" + + do_icu_test fts3token-4.3 th_TH $input $output + do_icu_test fts3token-4.4 en_US $input $output + + # ICU handles an unknown locale by falling back to the default. + # So this is not an error. + do_icu_test fts3token-4.5 MiddleOfTheOcean $input $output + + set longtoken "AReallyReallyLongTokenOneThatWillSurelyRequire" + append longtoken "AReallocInTheIcuTokenizerCode" + + set input "short tokens then " + append input $longtoken + set output "0 short short " + append output "1 tokens tokens " + append output "2 then then " + append output "3 [string tolower $longtoken] $longtoken" + + do_icu_test fts3token-4.6 MiddleOfTheOcean $input $output + do_icu_test fts3token-4.7 th_TH $input $output + do_icu_test fts3token-4.8 en_US $input $output + + do_execsql_test 5.1 { + CREATE VIRTUAL TABLE x1 USING fts3(name,TOKENIZE icu en_US); + insert into x1 (name) values (NULL); + insert into x1 (name) values (NULL); + delete from x1; + } + + proc cp_to_str {codepoint_list} { + set fmt [string repeat %c [llength $codepoint_list]] + eval [list format $fmt] $codepoint_list + } + + do_test 5.2 { + set str [cp_to_str {19968 26085 32822 32645 27874 23433 20986}] + execsql { INSERT INTO x1 VALUES($str) } + } {} +} + + +do_test fts3token-internal { + execsql { SELECT fts3_tokenizer_internal_test() } +} {ok} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3auto.test b/components/external/SQLite-3.8.1/test/fts3auto.test new file mode 100644 index 0000000000000000000000000000000000000000..20640d29ac7c4d9c2e2786f1aaeac980f134a256 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3auto.test @@ -0,0 +1,709 @@ +# 2011 June 10 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If this build does not include FTS3, skip the tests in this file. +# +ifcapable !fts3 { finish_test ; return } +source $testdir/fts3_common.tcl +source $testdir/malloc_common.tcl + +set testprefix fts3auto +set sfep $sqlite_fts3_enable_parentheses +set sqlite_fts3_enable_parentheses 1 + +#-------------------------------------------------------------------------- +# Start of Tcl infrastructure used by tests. The entry points are: +# +# do_fts3query_test +# fts3_make_deferrable +# fts3_zero_long_segments +# + +# +# do_fts3query_test TESTNAME ?OPTIONS? TABLE MATCHEXPR +# +# This proc runs several test cases on FTS3/4 table $TABLE using match +# expression $MATCHEXPR. All documents in $TABLE must be formatted so that +# they can be "tokenized" using the Tcl list commands (llength, lindex etc.). +# The name and column names used by $TABLE must not require any quoting or +# escaping when used in SQL statements. +# +# $MATCHINFO may be any expression accepted by the FTS4 MATCH operator, +# except that the ":token" syntax is not supported. Tcl list +# commands are used to tokenize the expression. Any parenthesis must appear +# either as separate list elements, or as the first (for opening) or last +# (for closing) character of a list element. i.e. the expression "(a OR b)c" +# will not be parsed correctly, but "( a OR b) c" will. +# +# Available OPTIONS are: +# +# -deferred TOKENLIST +# +# If the "deferred" option is supplied, it is passed a list of tokens that +# are deferred by FTS and result in the relevant matchinfo() stats being an +# approximation. +# +set sqlite_fts3_enable_parentheses 1 +proc do_fts3query_test {tn args} { + + set nArg [llength $args] + if {$nArg < 2 || ($nArg % 2)} { + set cmd do_fts3query_test + error "wrong # args: should be \"$cmd ?-deferred LIST? TABLE MATCHEXPR\"" + } + set tbl [lindex $args [expr $nArg-2]] + set match [lindex $args [expr $nArg-1]] + set deferred [list] + + foreach {k v} [lrange $args 0 [expr $nArg-3]] { + switch -- $k { + -deferred { + ifcapable fts4_deferred { set deferred $v } + } + default { + error "bad option \"$k\": must be -deferred" + } + } + } + + get_near_results $tbl $match $deferred aHit + get_near_results $tbl [string map {AND OR} $match] $deferred aMatchinfo + + set matchinfo_asc [list] + foreach docid [lsort -integer -incr [array names aHit]] { + lappend matchinfo_asc $docid $aMatchinfo($docid) + } + set matchinfo_desc [list] + foreach docid [lsort -integer -decr [array names aHit]] { + lappend matchinfo_desc $docid $aMatchinfo($docid) + } + + set title "(\"$match\" -> [llength [array names aHit]] rows)" + + do_execsql_test $tn$title.1 " + SELECT docid FROM $tbl WHERE $tbl MATCH '$match' ORDER BY docid ASC + " [lsort -integer -incr [array names aHit]] + + do_execsql_test $tn$title.2 " + SELECT docid FROM $tbl WHERE $tbl MATCH '$match' ORDER BY docid DESC + " [lsort -integer -decr [array names aHit]] + + do_execsql_test $tn$title.3 " + SELECT docid, mit(matchinfo($tbl, 'x')) FROM $tbl + WHERE $tbl MATCH '$match' ORDER BY docid DESC + " $matchinfo_desc + + do_execsql_test $tn$title.4 " + SELECT docid, mit(matchinfo($tbl, 'x')) FROM $tbl + WHERE $tbl MATCH '$match' ORDER BY docid ASC + " $matchinfo_asc +} + +# fts3_make_deferrable TABLE TOKEN ?NROW? +# +proc fts3_make_deferrable {tbl token {nRow 0}} { + + set stmt [sqlite3_prepare db "SELECT * FROM $tbl" -1 dummy] + set name [sqlite3_column_name $stmt 0] + sqlite3_finalize $stmt + + if {$nRow==0} { + set nRow [db one "SELECT count(*) FROM $tbl"] + } + set pgsz [db one "PRAGMA page_size"] + execsql BEGIN + for {set i 0} {$i < ($nRow * $pgsz * 1.2)/100} {incr i} { + set doc [string repeat "$token " 100] + execsql "INSERT INTO $tbl ($name) VALUES(\$doc)" + } + execsql "INSERT INTO $tbl ($name) VALUES('aaaaaaa ${token}aaaaa')" + execsql COMMIT + + return [expr $nRow*$pgsz] +} + +# fts3_zero_long_segments TABLE ?LIMIT? +# +proc fts3_zero_long_segments {tbl limit} { + execsql " + UPDATE ${tbl}_segments + SET block = zeroblob(length(block)) + WHERE length(block)>$limit + " + return [db changes] +} + + +proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r +} +db func mit mit + +proc fix_phrase_expr {cols expr colfiltervar} { + upvar $colfiltervar iColFilter + + set out [list] + foreach t $expr { + if {[string match *:* $t]} { + set col [lindex [split $t :] 0] + set t [lindex [split $t :] 1] + set iCol [lsearch $cols $col] + if {$iCol<0} { error "unknown column: $col" } + if {$iColFilter < 0} { + set iColFilter $iCol + } elseif {$iColFilter != $iCol} { + set iColFilter [llength $cols] + } + } + lappend out $t + } + + return $out +} + +proc fix_near_expr {cols expr colfiltervar} { + upvar $colfiltervar iColFilter + + set iColFilter -1 + + set out [list] + lappend out [fix_phrase_expr $cols [lindex $expr 0] iColFilter] + foreach {a b} [lrange $expr 1 end] { + if {[string match -nocase near $a]} { set a 10 } + if {[string match -nocase near/* $a]} { set a [string range $a 5 end] } + lappend out $a + lappend out [fix_phrase_expr $cols $b iColFilter] + } + return $out +} + +proc get_single_near_results {tbl expr deferred arrayvar nullvar} { + upvar $arrayvar aMatchinfo + upvar $nullvar nullentry + catch {array unset aMatchinfo} + + set cols [list] + set miss [list] + db eval "PRAGMA table_info($tbl)" A { lappend cols $A(name) ; lappend miss 0 } + set expr [fix_near_expr $cols $expr iColFilter] + + # Calculate the expected results using [fts3_near_match]. The following + # loop populates the "hits" and "counts" arrays as follows: + # + # 1. For each document in the table that matches the NEAR expression, + # hits($docid) is set to 1. The set of docids that match the expression + # can therefore be found using [array names hits]. + # + # 2. For each column of each document in the table, counts($docid,$iCol) + # is set to the -phrasecountvar output. + # + set res [list] + catch { array unset hits } + db eval "SELECT docid, * FROM $tbl" d { + set iCol 0 + foreach col [lrange $d(*) 1 end] { + set docid $d(docid) + if {$iColFilter<0 || $iCol==$iColFilter} { + set hit [fts3_near_match $d($col) $expr -p counts($docid,$iCol)] + if {$hit} { set hits($docid) 1 } + } else { + set counts($docid,$iCol) $miss + } + incr iCol + } + } + set nPhrase [expr ([llength $expr]+1)/2] + set nCol $iCol + + # This block populates the nHit and nDoc arrays. For each phrase/column + # in the query/table, array elements are set as follows: + # + # nHit($iPhrase,$iCol) - Total number of hits for phrase $iPhrase in + # column $iCol. + # + # nDoc($iPhrase,$iCol) - Number of documents with at least one hit for + # phrase $iPhrase in column $iCol. + # + for {set iPhrase 0} {$iPhrase < $nPhrase} {incr iPhrase} { + for {set iCol 0} {$iCol < $nCol} {incr iCol} { + set nHit($iPhrase,$iCol) 0 + set nDoc($iPhrase,$iCol) 0 + } + } + foreach key [array names counts] { + set iCol [lindex [split $key ,] 1] + set iPhrase 0 + foreach c $counts($key) { + if {$c>0} { incr nDoc($iPhrase,$iCol) 1 } + incr nHit($iPhrase,$iCol) $c + incr iPhrase + } + } + + if {[llength $deferred] && [llength $expr]==1} { + set phrase [lindex $expr 0] + set rewritten [list] + set partial 0 + foreach tok $phrase { + if {[lsearch $deferred $tok]>=0} { + lappend rewritten * + } else { + lappend rewritten $tok + set partial 1 + } + } + if {$partial==0} { + set tblsize [db one "SELECT count(*) FROM $tbl"] + for {set iCol 0} {$iCol < $nCol} {incr iCol} { + set nHit(0,$iCol) $tblsize + set nDoc(0,$iCol) $tblsize + } + } elseif {$rewritten != $phrase} { + while {[lindex $rewritten end] == "*"} { + set rewritten [lrange $rewritten 0 end-1] + } + while {[lindex $rewritten 0] == "*"} { + set rewritten [lrange $rewritten 1 end] + } + get_single_near_results $tbl [list $rewritten] {} aRewrite nullentry + foreach docid [array names hits] { + set aMatchinfo($docid) $aRewrite($docid) + } + return + } + } + + # Set up the aMatchinfo array. For each document, set aMatchinfo($docid) to + # contain the output of matchinfo('x') for the document. + # + foreach docid [array names hits] { + set mi [list] + for {set iPhrase 0} {$iPhrase<$nPhrase} {incr iPhrase} { + for {set iCol 0} {$iCol<$nCol} {incr iCol} { + lappend mi [lindex $counts($docid,$iCol) $iPhrase] + lappend mi $nHit($iPhrase,$iCol) + lappend mi $nDoc($iPhrase,$iCol) + } + } + set aMatchinfo($docid) $mi + } + + # Set up the nullentry output. + # + set nullentry [list] + for {set iPhrase 0} {$iPhrase<$nPhrase} {incr iPhrase} { + for {set iCol 0} {$iCol<$nCol} {incr iCol} { + lappend nullentry 0 $nHit($iPhrase,$iCol) $nDoc($iPhrase,$iCol) + } + } +} + + +proc matching_brackets {expr} { + if {[string range $expr 0 0]!="(" || [string range $expr end end] !=")"} { + return 0 + } + + set iBracket 1 + set nExpr [string length $expr] + for {set i 1} {$iBracket && $i < $nExpr} {incr i} { + set c [string range $expr $i $i] + if {$c == "("} {incr iBracket} + if {$c == ")"} {incr iBracket -1} + } + + return [expr ($iBracket==0 && $i==$nExpr)] +} + +proc get_near_results {tbl expr deferred arrayvar {nullvar ""}} { + upvar $arrayvar aMatchinfo + if {$nullvar != ""} { upvar $nullvar nullentry } + + set expr [string trim $expr] + while { [matching_brackets $expr] } { + set expr [string trim [string range $expr 1 end-1]] + } + + set prec(NOT) 1 + set prec(AND) 2 + set prec(OR) 3 + + set currentprec 0 + set iBracket 0 + set expr_length [llength $expr] + for {set i 0} {$i < $expr_length} {incr i} { + set op [lindex $expr $i] + if {$iBracket==0 && [info exists prec($op)] && $prec($op)>=$currentprec } { + set opidx $i + set currentprec $prec($op) + } else { + for {set j 0} {$j < [string length $op]} {incr j} { + set c [string range $op $j $j] + if {$c == "("} { incr iBracket +1 } + if {$c == ")"} { incr iBracket -1 } + } + } + } + if {$iBracket!=0} { error "mismatched brackets in: $expr" } + + if {[info exists opidx]==0} { + get_single_near_results $tbl $expr $deferred aMatchinfo nullentry + } else { + set eLeft [lrange $expr 0 [expr $opidx-1]] + set eRight [lrange $expr [expr $opidx+1] end] + + get_near_results $tbl $eLeft $deferred aLeft nullleft + get_near_results $tbl $eRight $deferred aRight nullright + + switch -- [lindex $expr $opidx] { + "NOT" { + foreach hit [array names aLeft] { + if {0==[info exists aRight($hit)]} { + set aMatchinfo($hit) $aLeft($hit) + } + } + set nullentry $nullleft + } + + "AND" { + foreach hit [array names aLeft] { + if {[info exists aRight($hit)]} { + set aMatchinfo($hit) [concat $aLeft($hit) $aRight($hit)] + } + } + set nullentry [concat $nullleft $nullright] + } + + "OR" { + foreach hit [array names aLeft] { + if {[info exists aRight($hit)]} { + set aMatchinfo($hit) [concat $aLeft($hit) $aRight($hit)] + unset aRight($hit) + } else { + set aMatchinfo($hit) [concat $aLeft($hit) $nullright] + } + } + foreach hit [array names aRight] { + set aMatchinfo($hit) [concat $nullleft $aRight($hit)] + } + + set nullentry [concat $nullleft $nullright] + } + } + } +} + + +# End of test procs. Actual tests are below this line. +#-------------------------------------------------------------------------- + +#-------------------------------------------------------------------------- +# The following test cases - fts3auto-1.* - focus on testing the Tcl +# command [fts3_near_match], which is used by other tests in this file. +# +proc test_fts3_near_match {tn doc expr res} { + fts3_near_match $doc $expr -phrasecountvar p + uplevel do_test [list $tn] [list [list set {} $p]] [list $res] +} + +test_fts3_near_match 1.1.1 {a b c a b} a {2} +test_fts3_near_match 1.1.2 {a b c a b} {a 5 b 6 c} {2 2 1} +test_fts3_near_match 1.1.3 {a b c a b} {"a b"} {2} +test_fts3_near_match 1.1.4 {a b c a b} {"b c"} {1} +test_fts3_near_match 1.1.5 {a b c a b} {"c c"} {0} + +test_fts3_near_match 1.2.1 "a b c d e f g" {b 2 f} {0 0} +test_fts3_near_match 1.2.2 "a b c d e f g" {b 3 f} {1 1} +test_fts3_near_match 1.2.3 "a b c d e f g" {f 2 b} {0 0} +test_fts3_near_match 1.2.4 "a b c d e f g" {f 3 b} {1 1} +test_fts3_near_match 1.2.5 "a b c d e f g" {"a b" 2 "f g"} {0 0} +test_fts3_near_match 1.2.6 "a b c d e f g" {"a b" 3 "f g"} {1 1} + +set A "a b c d e f g h i j k l m n o p q r s t u v w x y z" +test_fts3_near_match 1.3.1 $A {"c d" 5 "i j" 1 "e f"} {0 0 0} +test_fts3_near_match 1.3.2 $A {"c d" 5 "i j" 2 "e f"} {1 1 1} + +#-------------------------------------------------------------------------- +# Test cases fts3auto-2.* run some simple tests using the +# [do_fts3query_test] proc. +# +foreach {tn create} { + 1 "fts4(a, b)" + 2 "fts4(a, b, order=DESC)" + 3 "fts4(a, b, order=ASC)" + 4 "fts4(a, b, prefix=1)" + 5 "fts4(a, b, order=DESC, prefix=1)" + 6 "fts4(a, b, order=ASC, prefix=1)" +} { + do_test 2.$tn.1 { + catchsql { DROP TABLE t1 } + execsql "CREATE VIRTUAL TABLE t1 USING $create" + for {set i 0} {$i<32} {incr i} { + set doc [list] + if {$i&0x01} {lappend doc one} + if {$i&0x02} {lappend doc two} + if {$i&0x04} {lappend doc three} + if {$i&0x08} {lappend doc four} + if {$i&0x10} {lappend doc five} + execsql { INSERT INTO t1 VALUES($doc, null) } + } + } {} + + foreach {tn2 expr} { + 1 {one} + 2 {one NEAR/1 five} + 3 {t*} + 4 {t* NEAR/0 five} + 5 {o* NEAR/1 f*} + 6 {one NEAR five NEAR two NEAR four NEAR three} + 7 {one NEAR xyz} + 8 {one OR two} + 9 {one AND two} + 10 {one NOT two} + 11 {one AND two OR three} + 12 {three OR one AND two} + 13 {(three OR one) AND two} + 14 {(three OR one) AND two NOT (five NOT four)} + 15 {"one two"} + 16 {"one two" NOT "three four"} + } { + do_fts3query_test 2.$tn.2.$tn2 t1 $expr + } +} + +#-------------------------------------------------------------------------- +# Some test cases involving deferred tokens. +# + +foreach {tn create} { + 1 "fts4(x)" + 2 "fts4(x, order=DESC)" +} { + catchsql { DROP TABLE t1 } + execsql "CREATE VIRTUAL TABLE t1 USING $create" + do_execsql_test 3.$tn.1 { + INSERT INTO t1(docid, x) VALUES(-2, 'a b c d e f g h i j k'); + INSERT INTO t1(docid, x) VALUES(-1, 'b c d e f g h i j k a'); + INSERT INTO t1(docid, x) VALUES(0, 'c d e f g h i j k a b'); + INSERT INTO t1(docid, x) VALUES(1, 'd e f g h i j k a b c'); + INSERT INTO t1(docid, x) VALUES(2, 'e f g h i j k a b c d'); + INSERT INTO t1(docid, x) VALUES(3, 'f g h i j k a b c d e'); + INSERT INTO t1(docid, x) VALUES(4, 'a c e g i k'); + INSERT INTO t1(docid, x) VALUES(5, 'a d g j'); + INSERT INTO t1(docid, x) VALUES(6, 'c a b'); + } + + set limit [fts3_make_deferrable t1 c] + + do_fts3query_test 3.$tn.2.1 t1 {a OR c} + + ifcapable fts4_deferred { + do_test 3.$tn.3 { fts3_zero_long_segments t1 $limit } {1} + } + + foreach {tn2 expr def} { + 1 {a NEAR c} {} + 2 {a AND c} c + 3 {"a c"} c + 4 {"c a"} c + 5 {"a c" NEAR/1 g} {} + 6 {"a c" NEAR/0 g} {} + } { + do_fts3query_test 3.$tn.4.$tn2 -deferred $def t1 $expr + } +} + +#-------------------------------------------------------------------------- +# +foreach {tn create} { + 1 "fts4(x, y)" + 2 "fts4(x, y, order=DESC)" + 3 "fts4(x, y, order=DESC, prefix=2)" +} { + + execsql [subst { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING $create; + INSERT INTO t1 VALUES('one two five four five', ''); + INSERT INTO t1 VALUES('', 'one two five four five'); + INSERT INTO t1 VALUES('one two', 'five four five'); + }] + + do_fts3query_test 4.$tn.1.1 t1 {one AND five} + do_fts3query_test 4.$tn.1.2 t1 {one NEAR five} + do_fts3query_test 4.$tn.1.3 t1 {one NEAR/1 five} + do_fts3query_test 4.$tn.1.4 t1 {one NEAR/2 five} + do_fts3query_test 4.$tn.1.5 t1 {one NEAR/3 five} + + do_test 4.$tn.2 { + set limit [fts3_make_deferrable t1 five] + execsql { INSERT INTO t1(t1) VALUES('optimize') } + ifcapable fts4_deferred { + expr {[fts3_zero_long_segments t1 $limit]>0} + } else { + expr 1 + } + } {1} + + do_fts3query_test 4.$tn.3.1 -deferred five t1 {one AND five} + do_fts3query_test 4.$tn.3.2 -deferred five t1 {one NEAR five} + do_fts3query_test 4.$tn.3.3 -deferred five t1 {one NEAR/1 five} + do_fts3query_test 4.$tn.3.4 -deferred five t1 {one NEAR/2 five} + + do_fts3query_test 4.$tn.3.5 -deferred five t1 {one NEAR/3 five} + + do_fts3query_test 4.$tn.4.1 -deferred fi* t1 {on* AND fi*} + do_fts3query_test 4.$tn.4.2 -deferred fi* t1 {on* NEAR fi*} + do_fts3query_test 4.$tn.4.3 -deferred fi* t1 {on* NEAR/1 fi*} + do_fts3query_test 4.$tn.4.4 -deferred fi* t1 {on* NEAR/2 fi*} + do_fts3query_test 4.$tn.4.5 -deferred fi* t1 {on* NEAR/3 fi*} +} + +#-------------------------------------------------------------------------- +# The following test cases - fts3auto-5.* - focus on using prefix indexes. +# +set chunkconfig [fts3_configure_incr_load 1 1] +foreach {tn create pending} { + 1 "fts4(a, b)" 1 + 2 "fts4(a, b, order=ASC, prefix=1)" 1 + 3 "fts4(a, b, order=ASC, prefix=\"1,3\")" 0 + 4 "fts4(a, b, order=DESC, prefix=\"2,4\")" 0 + 5 "fts4(a, b, order=DESC, prefix=\"1\")" 0 + 6 "fts4(a, b, order=ASC, prefix=\"1,3\")" 0 +} { + + execsql [subst { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING $create; + }] + + if {$pending} {execsql BEGIN} + + foreach {a b} { + "the song of songs which is solomons" + "let him kiss me with the kisses of his mouth for thy love is better than wine" + "because of the savour of thy good ointments thy name is as ointment poured forth therefore do the virgins love thee" + "draw me we will run after thee the king hath brought me into his chambers we will be glad and rejoice in thee we will remember thy love more than wine the upright love thee" + "i am black but comely o ye daughters of jerusalem as the tents of kedar as the curtains of solomon" + "look not upon me because i am black because the sun hath looked upon me my mothers children were angry with me they made me the keeper of the vineyards but mine own vineyard have i not kept" + "tell me o thou whom my soul loveth where thou feedest where thou makest thy flock to rest at noon for why should i be as one that turneth aside by the flocks of thy companions?" + "if thou know not o thou fairest among women go thy way forth by the footsteps of the flock and feed thy kids beside the shepherds tents" + "i have compared thee o my love to a company of horses in pharaohs chariots" + "thy cheeks are comely with rows of jewels thy neck with chains of gold" + "we will make thee borders of gold with studs of silver" + "while the king sitteth at his table my spikenard sendeth forth the smell thereof" + "a bundle of myrrh is my wellbeloved unto me he shall lie all night betwixt my breasts" + "my beloved is unto me as a cluster of camphire in the vineyards of en gedi" + "behold thou art fair my love behold thou art fair thou hast doves eyes" + "behold thou art fair my beloved yea pleasant also our bed is green" + "the beams of our house are cedar and our rafters of fir" + } { + execsql {INSERT INTO t1(a, b) VALUES($a, $b)} + } + + + do_fts3query_test 5.$tn.1.1 t1 {s*} + do_fts3query_test 5.$tn.1.2 t1 {so*} + do_fts3query_test 5.$tn.1.3 t1 {"s* o*"} + do_fts3query_test 5.$tn.1.4 t1 {b* NEAR/3 a*} + do_fts3query_test 5.$tn.1.5 t1 {a*} + do_fts3query_test 5.$tn.1.6 t1 {th* NEAR/5 a* NEAR/5 w*} + do_fts3query_test 5.$tn.1.7 t1 {"b* th* art* fair*"} + + if {$pending} {execsql COMMIT} +} +eval fts3_configure_incr_load $chunkconfig + +foreach {tn pending create} { + 1 0 "fts4(a, b, c, d)" + 2 1 "fts4(a, b, c, d)" + 3 0 "fts4(a, b, c, d, order=DESC)" + 4 1 "fts4(a, b, c, d, order=DESC)" +} { + execsql [subst { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING $create; + }] + + + if {$pending} { execsql BEGIN } + + foreach {a b c d} { + "A B C" "D E F" "G H I" "J K L" + "B C D" "E F G" "H I J" "K L A" + "C D E" "F G H" "I J K" "L A B" + "D E F" "G H I" "J K L" "A B C" + "E F G" "H I J" "K L A" "B C D" + "F G H" "I J K" "L A B" "C D E" + } { + execsql { INSERT INTO t1 VALUES($a, $b, $c, $d) } + } + + do_fts3query_test 6.$tn.1 t1 {b:G} + do_fts3query_test 6.$tn.2 t1 {b:G AND c:I} + do_fts3query_test 6.$tn.3 t1 {b:G NEAR c:I} + do_fts3query_test 6.$tn.4 t1 {a:C OR b:G OR c:K OR d:C} + + do_fts3query_test 6.$tn.5 t1 {a:G OR b:G} + + catchsql { COMMIT } +} + +foreach {tn create} { + 1 "fts4(x)" + 2 "fts4(x, order=DESC)" +} { + execsql [subst { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING $create; + }] + + foreach {x} { + "F E N O T K X V A X I E X A P G Q V H U" + "R V A E T C V Q N I E L O N U G J K L U" + "U Y I G W M V F J L X I D C H F P J Q B" + "S G D Z X R P G S S Y B K A S G A I L L" + "L S I C H T Z S R Q P R N K J X L F M J" + "C C C D P X B Z C M A D A C X S B T X V" + "W Y J M D R G V R K B X S A W R I T N C" + "P K L W T M S P O Y Y V V O E H Q A I R" + "C D Y I C Z F H J C O Y A Q F L S B D K" + "P G S C Y C Y V I M B D S Z D D Y W I E" + "Z K Z U E E S F Y X T U A L W O U J C Q" + "P A T Z S W L P L Q V Y Y I P W U X S S" + "I U I H U O F Z F R H R F T N D X A G M" + "N A B M S H K X S O Y D T X S B R Y H Z" + "L U D A S K I L S V Z J P U B E B Y H M" + } { + execsql { INSERT INTO t1 VALUES($x) } + } + + # Add extra documents to the database such that token "B" will be considered + # deferrable if considering the other tokens means that 2 or fewer documents + # will be loaded into memory. + # + fts3_make_deferrable t1 B 2 + + # B is not deferred in either of the first two tests below, since filtering + # on "M" or "D" returns 10 documents or so. But filtering on "M * D" only + # returns 2, so B is deferred in this case. + # + do_fts3query_test 7.$tn.1 t1 {"M B"} + do_fts3query_test 7.$tn.2 t1 {"B D"} + do_fts3query_test 7.$tn.3 -deferred B t1 {"M B D"} +} + +set sqlite_fts3_enable_parentheses $sfep +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3aux1.test b/components/external/SQLite-3.8.1/test/fts3aux1.test new file mode 100644 index 0000000000000000000000000000000000000000..d17ac85df5dda4adbfe73a19e5ea481cc6dc37db --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3aux1.test @@ -0,0 +1,521 @@ +# 2011 January 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !fts3 { finish_test ; return } +set ::testprefix fts3aux1 + +do_execsql_test 1.1 { + CREATE VIRTUAL TABLE t1 USING fts4; + INSERT INTO t1 VALUES('one two three four'); + INSERT INTO t1 VALUES('three four five six'); + INSERT INTO t1 VALUES('one three five seven'); + + CREATE VIRTUAL TABLE terms USING fts4aux(t1); + SELECT term, documents, occurrences FROM terms WHERE col = '*'; +} { + five 2 2 four 2 2 one 2 2 seven 1 1 + six 1 1 three 3 3 two 1 1 +} + +do_execsql_test 1.2 { + INSERT INTO t1 VALUES('one one one three three three'); + SELECT term, documents, occurrences FROM terms WHERE col = '*'; +} { + five 2 2 four 2 2 one 3 5 seven 1 1 + six 1 1 three 4 6 two 1 1 +} + +do_execsql_test 1.3.1 { DELETE FROM t1; } +do_execsql_test 1.3.2 { + SELECT term, documents, occurrences FROM terms WHERE col = '*'; +} + +do_execsql_test 1.4 { + INSERT INTO t1 VALUES('a b a b a b a'); + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + SELECT term, documents, occurrences FROM terms WHERE col = '*'; +} {a 256 1024 b 256 768} + +#------------------------------------------------------------------------- +# The following tests verify that the fts4aux module uses the full-text +# index to reduce the number of rows scanned in the following circumstances: +# +# * when there is equality comparison against the term column using the +# BINARY collating sequence. +# +# * when there is a range constraint on the term column using the BINARY +# collating sequence. +# +# And also uses the full-text index to optimize ORDER BY clauses of the +# form "ORDER BY term ASC" or equivalent. +# +# Test organization is: +# +# fts3aux1-2.1.*: equality constraints. +# fts3aux1-2.2.*: range constraints. +# fts3aux1-2.3.*: ORDER BY optimization. +# + +do_execsql_test 2.0 { + DROP TABLE t1; + DROP TABLE terms; + + CREATE VIRTUAL TABLE x1 USING fts4(x); + INSERT INTO x1(x1) VALUES('nodesize=24'); + CREATE VIRTUAL TABLE terms USING fts4aux(x1); + + CREATE VIEW terms_v AS + SELECT term, documents, occurrences FROM terms WHERE col = '*'; + + INSERT INTO x1 VALUES('braes brag bragged bragger bragging'); + INSERT INTO x1 VALUES('brags braid braided braiding braids'); + INSERT INTO x1 VALUES('brain brainchild brained braining brains'); + INSERT INTO x1 VALUES('brainstem brainstems brainstorm brainstorms'); +} + +proc rec {varname x} { + global $varname + incr $varname + return 1 +} +db func rec rec + +# Use EQP to show that the WHERE expression "term='braid'" uses a different +# index number (1) than "+term='braid'" (0). +# +do_execsql_test 2.1.1.1 { + EXPLAIN QUERY PLAN SELECT * FROM terms WHERE term='braid' +} { 0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 1:} } +do_execsql_test 2.1.1.2 { + EXPLAIN QUERY PLAN SELECT * FROM terms WHERE +term='braid' +} {0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 0:}} + +# Now show that using "term='braid'" means the virtual table returns +# only 1 row to SQLite, but "+term='braid'" means all 19 are returned. +# +do_test 2.1.2.1 { + set cnt 0 + execsql { SELECT * FROM terms_v WHERE rec('cnt', term) AND term='braid' } + set cnt +} {2} +do_test 2.1.2.2 { + set cnt 0 + execsql { SELECT * FROM terms_v WHERE rec('cnt', term) AND +term='braid' } + set cnt +} {38} + +# Similar to the test immediately above, but using a term ("breakfast") that +# is not featured in the dataset. +# +do_test 2.1.3.1 { + set cnt 0 + execsql { SELECT * FROM terms_v WHERE rec('cnt', term) AND term='breakfast' } + set cnt +} {0} +do_test 2.1.3.2 { + set cnt 0 + execsql { SELECT * FROM terms_v WHERE rec('cnt', term) AND +term='breakfast' } + set cnt +} {38} + +do_execsql_test 2.1.4.1 { SELECT * FROM terms_v WHERE term='braid' } {braid 1 1} +do_execsql_test 2.1.4.2 { SELECT * FROM terms_v WHERE +term='braid'} {braid 1 1} +do_execsql_test 2.1.4.3 { SELECT * FROM terms_v WHERE term='breakfast' } {} +do_execsql_test 2.1.4.4 { SELECT * FROM terms_v WHERE +term='breakfast' } {} + +do_execsql_test 2.1.4.5 { SELECT * FROM terms_v WHERE term='cba' } {} +do_execsql_test 2.1.4.6 { SELECT * FROM terms_v WHERE +term='cba' } {} +do_execsql_test 2.1.4.7 { SELECT * FROM terms_v WHERE term='abc' } {} +do_execsql_test 2.1.4.8 { SELECT * FROM terms_v WHERE +term='abc' } {} + +# Special case: term=NULL +# +do_execsql_test 2.1.5 { SELECT * FROM terms WHERE term=NULL } {} + +do_execsql_test 2.2.1.1 { + EXPLAIN QUERY PLAN SELECT * FROM terms WHERE term>'brain' +} { 0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 2:} } +do_execsql_test 2.2.1.2 { + EXPLAIN QUERY PLAN SELECT * FROM terms WHERE +term>'brain' +} { 0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 0:} } + +do_execsql_test 2.2.1.3 { + EXPLAIN QUERY PLAN SELECT * FROM terms WHERE term<'brain' +} { 0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 4:} } +do_execsql_test 2.2.1.4 { + EXPLAIN QUERY PLAN SELECT * FROM terms WHERE +term<'brain' +} { 0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 0:} } + +do_execsql_test 2.2.1.5 { + EXPLAIN QUERY PLAN SELECT * FROM terms WHERE term BETWEEN 'brags' AND 'brain' +} { 0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 6:} } +do_execsql_test 2.2.1.6 { + EXPLAIN QUERY PLAN SELECT * FROM terms WHERE +term BETWEEN 'brags' AND 'brain' +} { 0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 0:} } + +do_test 2.2.2.1 { + set cnt 0 + execsql { SELECT * FROM terms WHERE rec('cnt', term) AND term>'brain' } + set cnt +} {18} +do_test 2.2.2.2 { + set cnt 0 + execsql { SELECT * FROM terms WHERE rec('cnt', term) AND +term>'brain' } + set cnt +} {38} +do_execsql_test 2.2.2.3 { + SELECT term, documents, occurrences FROM terms_v WHERE term>'brain' +} { + brainchild 1 1 brained 1 1 braining 1 1 brains 1 1 + brainstem 1 1 brainstems 1 1 brainstorm 1 1 brainstorms 1 1 +} +do_execsql_test 2.2.2.4 { + SELECT term, documents, occurrences FROM terms_v WHERE +term>'brain' +} { + brainchild 1 1 brained 1 1 braining 1 1 brains 1 1 + brainstem 1 1 brainstems 1 1 brainstorm 1 1 brainstorms 1 1 +} +do_execsql_test 2.2.2.5 { + SELECT term, documents, occurrences FROM terms_v WHERE term>='brain' +} { + brain 1 1 + brainchild 1 1 brained 1 1 braining 1 1 brains 1 1 + brainstem 1 1 brainstems 1 1 brainstorm 1 1 brainstorms 1 1 +} +do_execsql_test 2.2.2.6 { + SELECT term, documents, occurrences FROM terms_v WHERE +term>='brain' +} { + brain 1 1 + brainchild 1 1 brained 1 1 braining 1 1 brains 1 1 + brainstem 1 1 brainstems 1 1 brainstorm 1 1 brainstorms 1 1 +} + +do_execsql_test 2.2.2.7 { + SELECT term, documents, occurrences FROM terms_v WHERE term>='abc' +} { + braes 1 1 brag 1 1 bragged 1 1 bragger 1 1 + bragging 1 1 brags 1 1 braid 1 1 braided 1 1 + braiding 1 1 braids 1 1 brain 1 1 brainchild 1 1 + brained 1 1 braining 1 1 brains 1 1 brainstem 1 1 + brainstems 1 1 brainstorm 1 1 brainstorms 1 1 +} +do_execsql_test 2.2.2.8 { + SELECT term, documents, occurrences FROM terms_v WHERE +term>='abc' +} { + braes 1 1 brag 1 1 bragged 1 1 bragger 1 1 + bragging 1 1 brags 1 1 braid 1 1 braided 1 1 + braiding 1 1 braids 1 1 brain 1 1 brainchild 1 1 + brained 1 1 braining 1 1 brains 1 1 brainstem 1 1 + brainstems 1 1 brainstorm 1 1 brainstorms 1 1 +} + +do_execsql_test 2.2.2.9 { + SELECT term, documents, occurrences FROM terms_v WHERE term>='brainstorms' +} {brainstorms 1 1} +do_execsql_test 2.2.2.10 { + SELECT term, documents, occurrences FROM terms_v WHERE term>='brainstorms' +} {brainstorms 1 1} +do_execsql_test 2.2.2.11 { SELECT * FROM terms_v WHERE term>'brainstorms' } {} +do_execsql_test 2.2.2.12 { SELECT * FROM terms_v WHERE term>'brainstorms' } {} + +do_execsql_test 2.2.2.13 { SELECT * FROM terms_v WHERE term>'cba' } {} +do_execsql_test 2.2.2.14 { SELECT * FROM terms_v WHERE term>'cba' } {} + +do_test 2.2.3.1 { + set cnt 0 + execsql { SELECT * FROM terms WHERE rec('cnt', term) AND term<'brain' } + set cnt +} {22} +do_test 2.2.3.2 { + set cnt 0 + execsql { SELECT * FROM terms WHERE rec('cnt', term) AND +term<'brain' } + set cnt +} {38} +do_execsql_test 2.2.3.3 { + SELECT term, documents, occurrences FROM terms_v WHERE term<'brain' +} { + braes 1 1 brag 1 1 bragged 1 1 bragger 1 1 bragging 1 1 + brags 1 1 braid 1 1 braided 1 1 braiding 1 1 braids 1 1 +} +do_execsql_test 2.2.3.4 { + SELECT term, documents, occurrences FROM terms_v WHERE +term<'brain' +} { + braes 1 1 brag 1 1 bragged 1 1 bragger 1 1 bragging 1 1 + brags 1 1 braid 1 1 braided 1 1 braiding 1 1 braids 1 1 +} +do_execsql_test 2.2.3.5 { + SELECT term, documents, occurrences FROM terms_v WHERE term<='brain' +} { + braes 1 1 brag 1 1 bragged 1 1 bragger 1 1 bragging 1 1 + brags 1 1 braid 1 1 braided 1 1 braiding 1 1 braids 1 1 + brain 1 1 +} +do_execsql_test 2.2.3.6 { + SELECT term, documents, occurrences FROM terms_v WHERE +term<='brain' +} { + braes 1 1 brag 1 1 bragged 1 1 bragger 1 1 bragging 1 1 + brags 1 1 braid 1 1 braided 1 1 braiding 1 1 braids 1 1 + brain 1 1 +} + +do_test 2.2.4.1 { + set cnt 0 + execsql { + SELECT term, documents, occurrences FROM terms + WHERE rec('cnt', term) AND term BETWEEN 'brags' AND 'brain' + } + set cnt +} {12} +do_test 2.2.4.2 { + set cnt 0 + execsql { + SELECT term, documents, occurrences FROM terms + WHERE rec('cnt', term) AND +term BETWEEN 'brags' AND 'brain' + } + set cnt +} {38} +do_execsql_test 2.2.4.3 { + SELECT term, documents, occurrences FROM terms_v + WHERE rec('cnt', term) AND term BETWEEN 'brags' AND 'brain' +} { + brags 1 1 braid 1 1 braided 1 1 braiding 1 1 braids 1 1 brain 1 1 +} +do_execsql_test 2.2.4.4 { + SELECT term, documents, occurrences FROM terms_v + WHERE rec('cnt', term) AND +term BETWEEN 'brags' AND 'brain' +} { + brags 1 1 braid 1 1 braided 1 1 braiding 1 1 braids 1 1 brain 1 1 +} +do_execsql_test 2.2.4.5 { + SELECT term, documents, occurrences FROM terms_v + WHERE rec('cnt', term) AND term > 'brags' AND term < 'brain' +} { + braid 1 1 braided 1 1 braiding 1 1 braids 1 1 +} +do_execsql_test 2.2.4.6 { + SELECT term, documents, occurrences FROM terms_v + WHERE rec('cnt', term) AND +term > 'brags' AND +term < 'brain' +} { + braid 1 1 braided 1 1 braiding 1 1 braids 1 1 +} + +# Check that "ORDER BY term ASC" and equivalents are sorted by the +# virtual table implementation. Any other ORDER BY clause requires +# SQLite to sort results using a temporary b-tree. +# +foreach {tn sort orderby} { + 1 0 "ORDER BY term ASC" + 2 0 "ORDER BY term" + 3 1 "ORDER BY term DESC" + 4 1 "ORDER BY documents ASC" + 5 1 "ORDER BY documents" + 6 1 "ORDER BY documents DESC" + 7 1 "ORDER BY occurrences ASC" + 8 1 "ORDER BY occurrences" + 9 1 "ORDER BY occurrences DESC" +} { + + set res [list 0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 0:}] + if {$sort} { lappend res 0 0 0 {USE TEMP B-TREE FOR ORDER BY} } + + set sql "SELECT * FROM terms $orderby" + do_execsql_test 2.3.1.$tn "EXPLAIN QUERY PLAN $sql" $res +} + +#------------------------------------------------------------------------- +# The next set of tests, fts3aux1-3.*, test error conditions in the +# fts4aux module. Except, fault injection testing (OOM, IO error etc.) is +# done in fts3fault2.test +# + +do_execsql_test 3.1.1 { + CREATE VIRTUAL TABLE t2 USING fts4; +} + +do_catchsql_test 3.1.2 { + CREATE VIRTUAL TABLE terms2 USING fts4aux; +} {1 {invalid arguments to fts4aux constructor}} +do_catchsql_test 3.1.3 { + CREATE VIRTUAL TABLE terms2 USING fts4aux(t2, t2); +} {1 {invalid arguments to fts4aux constructor}} + +do_execsql_test 3.2.1 { + CREATE VIRTUAL TABLE terms3 USING fts4aux(does_not_exist) +} +do_catchsql_test 3.2.2 { + SELECT * FROM terms3 +} {1 {SQL logic error or missing database}} +do_catchsql_test 3.2.3 { + SELECT * FROM terms3 WHERE term = 'abc' +} {1 {SQL logic error or missing database}} + +do_catchsql_test 3.3.1 { + INSERT INTO terms VALUES(1,2,3); +} {1 {table terms may not be modified}} +do_catchsql_test 3.3.2 { + DELETE FROM terms +} {1 {table terms may not be modified}} +do_catchsql_test 3.3.3 { + UPDATE terms set documents = documents+1; +} {1 {table terms may not be modified}} + + +#------------------------------------------------------------------------- +# The following tests - fts4aux-4.* - test that joins work with fts4aux +# tables. And that fts4aux provides reasonably sane cost information via +# xBestIndex to the query planner. +# +db close +forcedelete test.db +sqlite3 db test.db +do_execsql_test 4.1 { + CREATE VIRTUAL TABLE x1 USING fts4(x); + CREATE VIRTUAL TABLE terms USING fts4aux(x1); + CREATE TABLE x2(y); + CREATE TABLE x3(y); + CREATE INDEX i1 ON x3(y); + + INSERT INTO x1 VALUES('a b c d e'); + INSERT INTO x1 VALUES('f g h i j'); + INSERT INTO x1 VALUES('k k l l a'); + + INSERT INTO x2 SELECT term FROM terms WHERE col = '*'; + INSERT INTO x3 SELECT term FROM terms WHERE col = '*'; +} + +proc do_plansql_test {tn sql r} { + uplevel do_execsql_test $tn [list "EXPLAIN QUERY PLAN $sql ; $sql"] [list $r] +} + +do_plansql_test 4.2 { + SELECT y FROM x2, terms WHERE y = term AND col = '*' +} { + 0 0 0 {SCAN TABLE x2} + 0 1 1 {SCAN TABLE terms VIRTUAL TABLE INDEX 1:} + a b c d e f g h i j k l +} + +do_plansql_test 4.3 { + SELECT y FROM terms, x2 WHERE y = term AND col = '*' +} { + 0 0 1 {SCAN TABLE x2} + 0 1 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 1:} + a b c d e f g h i j k l +} + +do_plansql_test 4.4 { + SELECT y FROM x3, terms WHERE y = term AND col = '*' +} { + 0 0 1 {SCAN TABLE terms VIRTUAL TABLE INDEX 0:} + 0 1 0 {SEARCH TABLE x3 USING COVERING INDEX i1 (y=?)} + a b c d e f g h i j k l +} + +do_plansql_test 4.5 { + SELECT y FROM terms, x3 WHERE y = term AND occurrences>1 AND col = '*' +} { + 0 0 0 {SCAN TABLE terms VIRTUAL TABLE INDEX 0:} + 0 1 1 {SEARCH TABLE x3 USING COVERING INDEX i1 (y=?)} + a k l +} + +#------------------------------------------------------------------------- +# The following tests check that fts4aux can handle an fts table with an +# odd name (one that requires quoting for use in SQL statements). And that +# the argument to the fts4aux constructor is properly dequoted before use. +# +do_execsql_test 5.1 { + CREATE VIRTUAL TABLE "abc '!' def" USING fts4(x, y); + INSERT INTO "abc '!' def" VALUES('XX', 'YY'); + + CREATE VIRTUAL TABLE terms3 USING fts4aux("abc '!' def"); + SELECT * FROM terms3; +} {xx * 1 1 xx 0 1 1 yy * 1 1 yy 1 1 1} + +do_execsql_test 5.2 { + CREATE VIRTUAL TABLE "%%^^%%" USING fts4aux('abc ''!'' def'); + SELECT * FROM "%%^^%%"; +} {xx * 1 1 xx 0 1 1 yy * 1 1 yy 1 1 1} + +#------------------------------------------------------------------------- +# Test that we can create an fts4aux table in the temp database. +# +forcedelete test.db2 +do_execsql_test 6.1 { + CREATE VIRTUAL TABLE ft1 USING fts4(x, y); + INSERT INTO ft1 VALUES('a b', 'c d'); + INSERT INTO ft1 VALUES('e e', 'c d'); + INSERT INTO ft1 VALUES('a a', 'b b'); + CREATE VIRTUAL TABLE temp.aux1 USING fts4aux(main, ft1); + SELECT * FROM aux1; +} { + a * 2 3 a 0 2 3 + b * 2 3 b 0 1 1 b 1 1 2 + c * 2 2 c 1 2 2 + d * 2 2 d 1 2 2 + e * 1 2 e 0 1 2 +} + +do_execsql_test 6.2 { + ATTACH 'test.db2' AS att; + CREATE VIRTUAL TABLE att.ft1 USING fts4(x, y); + INSERT INTO att.ft1 VALUES('v w', 'x y'); + INSERT INTO att.ft1 VALUES('z z', 'x y'); + INSERT INTO att.ft1 VALUES('v v', 'w w'); + CREATE VIRTUAL TABLE temp.aux2 USING fts4aux(att, ft1); + SELECT * FROM aux2; +} { + v * 2 3 v 0 2 3 + w * 2 3 w 0 1 1 w 1 1 2 + x * 2 2 x 1 2 2 + y * 2 2 y 1 2 2 + z * 1 2 z 0 1 2 +} + +foreach {tn q res1 res2} { + 1 { SELECT * FROM %%% WHERE term = 'a' } {a * 2 3 a 0 2 3} {} + 2 { SELECT * FROM %%% WHERE term = 'x' } {} {x * 2 2 x 1 2 2} + + 3 { SELECT * FROM %%% WHERE term >= 'y' } + {} {y * 2 2 y 1 2 2 z * 1 2 z 0 1 2} + + 4 { SELECT * FROM %%% WHERE term <= 'c' } + {a * 2 3 a 0 2 3 b * 2 3 b 0 1 1 b 1 1 2 c * 2 2 c 1 2 2} {} +} { + set sql1 [string map {%%% aux1} $q] + set sql2 [string map {%%% aux2} $q] + + do_execsql_test 7.$tn.1 $sql1 $res1 + do_execsql_test 7.$tn.2 $sql2 $res2 +} + +do_test 8.1 { + catchsql { CREATE VIRTUAL TABLE att.aux3 USING fts4aux(main, ft1) } +} {1 {invalid arguments to fts4aux constructor}} + +do_test 8.2 { + execsql {DETACH att} + catchsql { SELECT * FROM aux2 } +} {1 {SQL logic error or missing database}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3aux2.test b/components/external/SQLite-3.8.1/test/fts3aux2.test new file mode 100644 index 0000000000000000000000000000000000000000..e108fc4b80b583933e5dbfc5b69010391f37c1f4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3aux2.test @@ -0,0 +1,144 @@ +# 2011 January 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !fts3 { finish_test ; return } +set ::testprefix fts3aux2 + +do_execsql_test 1.1 { + CREATE VIRTUAL TABLE t1 USING fts4(a, b, languageid=l); + INSERT INTO t1(a, b, l) VALUES + ('zero zero', 'zero zero', 0), + ('one two', 'three four', 1), + ('five six', 'seven eight', 2) + ; + CREATE VIRTUAL TABLE terms USING fts4aux(t1); +} {} + +do_execsql_test 1.2.1 { + SELECT term, documents, occurrences, languageid FROM terms WHERE col = '*'; +} {zero 1 4 0} + +do_execsql_test 1.2.2 { + SELECT * FROM terms; +} {zero * 1 4 zero 0 1 2 zero 1 1 2} + +do_execsql_test 1.2.3 { + SELECT * FROM terms WHERE languageid=''; +} {} + +do_execsql_test 1.2.4 { + SELECT * FROM terms WHERE languageid=-1; +} {} + +do_execsql_test 1.2.5 { + SELECT * FROM terms WHERE languageid=9223372036854775807; +} {} + +do_execsql_test 1.2.6 { + SELECT * FROM terms WHERE languageid=-9223372036854775808; +} {} + +do_execsql_test 1.2.7 { + SELECT * FROM terms WHERE languageid=NULL; +} {} + +do_execsql_test 1.3.1 { + SELECT term, documents, occurrences, languageid + FROM terms WHERE col = '*' AND languageid=1; +} { + four 1 1 1 one 1 1 1 three 1 1 1 two 1 1 1 +} + +do_execsql_test 1.3.2 { + SELECT term, col, documents, occurrences, languageid + FROM terms WHERE languageid=1; +} { + four * 1 1 1 four 1 1 1 1 + one * 1 1 1 one 0 1 1 1 + three * 1 1 1 three 1 1 1 1 + two * 1 1 1 two 0 1 1 1 +} + +do_execsql_test 1.3.3 { + SELECT term, col, documents, occurrences, languageid + FROM terms WHERE languageid=1 AND term='zero' +} { +} + +do_execsql_test 1.3.4 { + SELECT term, col, documents, occurrences, languageid + FROM terms WHERE languageid='1' AND term='two' +} { + two * 1 1 1 two 0 1 1 1 +} + +do_execsql_test 1.3.5 { + SELECT term, col, documents, occurrences, languageid + FROM terms WHERE languageid='+1' AND term>'four' +} { + one * 1 1 1 one 0 1 1 1 + three * 1 1 1 three 1 1 1 1 + two * 1 1 1 two 0 1 1 1 +} + +do_execsql_test 1.4.1 { + SELECT term, documents, occurrences, languageid + FROM terms WHERE col = '*' AND languageid=2; +} { + eight 1 1 2 five 1 1 2 seven 1 1 2 six 1 1 2 +} + +do_execsql_test 1.4.2 { + SELECT term, col, documents, occurrences, languageid + FROM terms WHERE languageid=2; +} { + eight * 1 1 2 eight 1 1 1 2 + five * 1 1 2 five 0 1 1 2 + seven * 1 1 2 seven 1 1 1 2 + six * 1 1 2 six 0 1 1 2 +} + +do_execsql_test 1.4.3 { + SELECT term, col, documents, occurrences, languageid + FROM terms WHERE languageid=2 AND term='five'; +} { + five * 1 1 2 five 0 1 1 2 +} + +do_execsql_test 1.4.4 { + SELECT term, col, documents, occurrences, languageid + FROM terms WHERE term='five' AND languageid=2 +} { + five * 1 1 2 five 0 1 1 2 +} + +do_execsql_test 1.4.5 { + SELECT term, col, documents, occurrences, languageid + FROM terms WHERE term>='seven' AND languageid=2 +} { + seven * 1 1 2 seven 1 1 1 2 + six * 1 1 2 six 0 1 1 2 +} + +do_execsql_test 1.4.6 { + SELECT term, col, documents, occurrences, languageid + FROM terms WHERE term>='e' AND term<'seven' AND languageid=2 +} { + eight * 1 1 2 eight 1 1 1 2 + five * 1 1 2 five 0 1 1 2 +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3b.test b/components/external/SQLite-3.8.1/test/fts3b.test new file mode 100644 index 0000000000000000000000000000000000000000..9bde3a254c2885f361824b86f28e95f21b8befb0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3b.test @@ -0,0 +1,230 @@ +# 2007 August 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. This +# script tests for the fts2 rowid-versus-vacuum problem (ticket #2566). +# +# $Id: fts3b.test,v 1.3 2007/09/13 18:14:49 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (c) VALUES('this is a test'); + INSERT INTO t1 (c) VALUES('that was a test'); + INSERT INTO t1 (c) VALUES('this is fun'); + DELETE FROM t1 WHERE c = 'that was a test'; +} + +# Baseline test. +do_test fts3b-1.1 { + execsql { + SELECT rowid FROM t1 WHERE c MATCH 'this'; + } +} {1 3} + +db eval {VACUUM} + +# The VACUUM renumbered the t1_content table in fts2, which breaks +# this. +do_test fts3b-1.2 { + execsql { + SELECT rowid FROM t1 WHERE c MATCH 'this'; + } +} {1 3} + +# The t2 table is unfortunately pretty contrived. We need documents +# that are bigger than ROOT_MAX (1024) to force segments out of the +# segdir and into %_segments. We also need to force segment merging +# to generate a hole in the %_segments table, which needs more than 16 +# docs. Beyond that, to test correct operation of BLOCK_SELECT_STMT, +# we need to merge a mult-level tree, which is where the 10,000 comes +# from. Which is slow, thus the set of transactions, with the 500 +# being a number such that 10,000/500 > 16. +set text { + Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas + iaculis mollis ipsum. Praesent rhoncus placerat justo. Duis non quam + sed turpis posuere placerat. Curabitur et lorem in lorem porttitor + aliquet. Pellentesque bibendum tincidunt diam. Vestibulum blandit + ante nec elit. In sapien diam, facilisis eget, dictum sed, viverra + at, felis. Vestibulum magna. Sed magna dolor, vestibulum rhoncus, + ornare vel, vulputate sit amet, felis. Integer malesuada, tellus at + luctus gravida, diam nunc porta nibh, nec imperdiet massa metus eu + lectus. Aliquam nisi. Nunc fringilla nulla at lectus. Suspendisse + potenti. Cum sociis natoque penatibus et magnis dis parturient + montes, nascetur ridiculus mus. Pellentesque odio nulla, feugiat eu, + suscipit nec, consequat quis, risus. +} +append text $text + +db eval {CREATE VIRTUAL TABLE t2 USING fts3(c)} +set res {} +db eval {BEGIN} +for {set ii 0} {$ii<10000} {incr ii} { + db eval {INSERT INTO t2 (c) VALUES ($text)} + lappend res [expr {$ii+1}] + if {($ii%500)==0} { + db eval { + COMMIT; + BEGIN; + } + } +} +db eval {COMMIT} + +do_test fts3b-2.1 { + execsql { + SELECT rowid FROM t2 WHERE c MATCH 'lorem'; + } +} $res + +db eval {VACUUM} + +# The VACUUM renumbered the t2_segment table in fts2, which would +# break the following. +do_test fts3b-2.2 { + execsql { + SELECT rowid FROM t2 WHERE c MATCH 'lorem'; + } +} $res + +# Since fts3 is already an API break, I've marked the table-named +# column HIDDEN. + +db eval { + CREATE VIRTUAL TABLE t3 USING fts3(c); + INSERT INTO t3 (c) VALUES('this is a test'); + INSERT INTO t3 (c) VALUES('that was a test'); + INSERT INTO t3 (c) VALUES('this is fun'); + DELETE FROM t3 WHERE c = 'that was a test'; +} + +# Test that the table-named column still works. +do_test fts3b-3.1 { + execsql { + SELECT snippet(t3) FROM t3 WHERE t3 MATCH 'test'; + } +} {{this is a test}} + +# Test that the column doesn't appear when selecting all columns. +do_test fts3b-3.2 { + execsql { + SELECT * FROM t3 WHERE rowid = 1; + } +} {{this is a test}} + +# Test that the column doesn't conflict with inserts that don't name +# columns. +do_test fts3b-3.3 { + execsql { + INSERT INTO t3 VALUES ('another test'); + } +} {} + +# fts3 adds a new implicit column, docid, which acts as an alias for +# rowid. + +db eval { + CREATE VIRTUAL TABLE t4 USING fts3(c); + INSERT INTO t4 (c) VALUES('this is a test'); + INSERT INTO t4 (c) VALUES('that was a test'); + INSERT INTO t4 (c) VALUES('this is fun'); + DELETE FROM t4 WHERE c = 'that was a test'; +} + +# Test that docid is present and identical to rowid. +do_test fts3b-4.1 { + execsql { + SELECT rowid FROM t4 WHERE rowid <> docid; + } +} {} + +# Test that docid is hidden. +do_test fts3b-4.2 { + execsql { + SELECT * FROM t4 WHERE rowid = 1; + } +} {{this is a test}} + +# Test that docid can be selected. +do_test fts3b-4.3 { + execsql { + SELECT docid, * FROM t4 WHERE rowid = 1; + } +} {1 {this is a test}} + +# Test that docid can be used in WHERE. +do_test fts3b-4.4 { + execsql { + SELECT docid, * FROM t4 WHERE docid = 1; + } +} {1 {this is a test}} + +# Test that the column doesn't conflict with inserts that don't name +# columns. [Yes, this is the same as fts3b-3.3, here just in case the +# goals of that test change.] +do_test fts3b-4.5 { + execsql { + INSERT INTO t4 VALUES ('another test'); + } +} {} + +# Test that the docid can be forced on insert. +do_test fts3b-4.6 { + execsql { + INSERT INTO t4 (docid, c) VALUES (10, 'yet another test'); + SELECT * FROM t4 WHERE docid = 10; + } +} {{yet another test}} + +# Test that rowid can also be forced. +do_test fts3b-4.7 { + execsql { + INSERT INTO t4 (docid, c) VALUES (12, 'still testing'); + SELECT * FROM t4 WHERE docid = 12; + } +} {{still testing}} + +# If an insert tries to set both docid and rowid, require an error. +do_test fts3b-4.8 { + catchsql { + INSERT INTO t4 (rowid, docid, c) VALUES (14, 15, 'bad test'); + SELECT * FROM t4 WHERE docid = 14; + } +} {1 {SQL logic error or missing database}} + +do_test fts3b-4.9 { + execsql { SELECT docid FROM t4 WHERE t4 MATCH 'testing' } +} {12} +do_test fts3b-4.10 { + execsql { + UPDATE t4 SET docid = 14 WHERE docid = 12; + SELECT docid FROM t4 WHERE t4 MATCH 'testing'; + } +} {14} +do_test fts3b-4.11 { + execsql { SELECT * FROM t4 WHERE rowid = 14; } +} {{still testing}} +do_test fts3b-4.12 { + execsql { SELECT * FROM t4 WHERE rowid = 12; } +} {} +do_test fts3b-4.13 { + execsql { SELECT docid FROM t4 WHERE t4 MATCH 'still'; } +} {14} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3c.test b/components/external/SQLite-3.8.1/test/fts3c.test new file mode 100644 index 0000000000000000000000000000000000000000..6b63264a680c0df378d394abebc020ffac3c4aa7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3c.test @@ -0,0 +1,255 @@ +# 2008 June 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file exercises some new testing functions in the FTS3 module, +# and then uses them to do some basic tests that FTS3 is internally +# working as expected. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/fts3_common.tcl + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +#************************************************************************* +# Utility function to check for the expected terms in the segment +# level/index. _all version does same but for entire index. +proc check_terms {test level index terms} { + set where "level = $level AND idx = $index" + do_test $test.terms [list fts3_terms t1 $where] $terms +} +proc check_terms_all {test terms} { + do_test $test.terms [list fts3_terms t1 1] $terms +} + +# Utility function to check for the expected doclist for the term in +# segment level/index. _all version does same for entire index. +proc check_doclist {test level index term doclist} { + set where "level = $level AND idx = $index" + do_test $test [list fts3_doclist t1 $term $where] $doclist +} +proc check_doclist_all {test term doclist} { + do_test $test [list fts3_doclist t1 $term 1] $doclist +} + +#************************************************************************* +# Test the segments resulting from straight-forward inserts. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (docid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (docid, c) VALUES (3, 'This is a test'); +} + +# Check for expected segments and expected matches. +do_test fts3c-1.0.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0 0 1 0 2} +do_test fts3c-1.0.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid; + } +} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \ + {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \ + {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}] + +# Check the specifics of the segments constructed. +# Logical view of entire index. +check_terms_all fts3c-1.0.1 {a is test that this was} +check_doclist_all fts3c-1.0.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist_all fts3c-1.0.1.2 is {[1 0[1]] [3 0[1]]} +check_doclist_all fts3c-1.0.1.3 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist_all fts3c-1.0.1.4 that {[2 0[0]]} +check_doclist_all fts3c-1.0.1.5 this {[1 0[0]] [3 0[0]]} +check_doclist_all fts3c-1.0.1.6 was {[2 0[1]]} + +# Segment 0,0 +check_terms fts3c-1.0.2 0 0 {a is test this} +check_doclist fts3c-1.0.2.1 0 0 a {[1 0[2]]} +check_doclist fts3c-1.0.2.2 0 0 is {[1 0[1]]} +check_doclist fts3c-1.0.2.3 0 0 test {[1 0[3]]} +check_doclist fts3c-1.0.2.4 0 0 this {[1 0[0]]} + +# Segment 0,1 +check_terms fts3c-1.0.3 0 1 {a test that was} +check_doclist fts3c-1.0.3.1 0 1 a {[2 0[2]]} +check_doclist fts3c-1.0.3.2 0 1 test {[2 0[3]]} +check_doclist fts3c-1.0.3.3 0 1 that {[2 0[0]]} +check_doclist fts3c-1.0.3.4 0 1 was {[2 0[1]]} + +# Segment 0,2 +check_terms fts3c-1.0.4 0 2 {a is test this} +check_doclist fts3c-1.0.4.1 0 2 a {[3 0[2]]} +check_doclist fts3c-1.0.4.2 0 2 is {[3 0[1]]} +check_doclist fts3c-1.0.4.3 0 2 test {[3 0[3]]} +check_doclist fts3c-1.0.4.4 0 2 this {[3 0[0]]} + +#************************************************************************* +# Test the segments resulting from inserts followed by a delete. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (docid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (docid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE docid = 1; +} + +do_test fts3c-1.1.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0 0 1 0 2 0 3} +do_test fts3c-1.1.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}} + +check_terms_all fts3c-1.1.1 {a is test that this was} +check_doclist_all fts3c-1.1.1.1 a {[2 0[2]] [3 0[2]]} +check_doclist_all fts3c-1.1.1.2 is {[3 0[1]]} +check_doclist_all fts3c-1.1.1.3 test {[2 0[3]] [3 0[3]]} +check_doclist_all fts3c-1.1.1.4 that {[2 0[0]]} +check_doclist_all fts3c-1.1.1.5 this {[3 0[0]]} +check_doclist_all fts3c-1.1.1.6 was {[2 0[1]]} + +check_terms fts3c-1.1.2 0 0 {a is test this} +check_doclist fts3c-1.1.2.1 0 0 a {[1 0[2]]} +check_doclist fts3c-1.1.2.2 0 0 is {[1 0[1]]} +check_doclist fts3c-1.1.2.3 0 0 test {[1 0[3]]} +check_doclist fts3c-1.1.2.4 0 0 this {[1 0[0]]} + +check_terms fts3c-1.1.3 0 1 {a test that was} +check_doclist fts3c-1.1.3.1 0 1 a {[2 0[2]]} +check_doclist fts3c-1.1.3.2 0 1 test {[2 0[3]]} +check_doclist fts3c-1.1.3.3 0 1 that {[2 0[0]]} +check_doclist fts3c-1.1.3.4 0 1 was {[2 0[1]]} + +check_terms fts3c-1.1.4 0 2 {a is test this} +check_doclist fts3c-1.1.4.1 0 2 a {[3 0[2]]} +check_doclist fts3c-1.1.4.2 0 2 is {[3 0[1]]} +check_doclist fts3c-1.1.4.3 0 2 test {[3 0[3]]} +check_doclist fts3c-1.1.4.4 0 2 this {[3 0[0]]} + +check_terms fts3c-1.1.5 0 3 {a is test this} +check_doclist fts3c-1.1.5.1 0 3 a {[1]} +check_doclist fts3c-1.1.5.2 0 3 is {[1]} +check_doclist fts3c-1.1.5.3 0 3 test {[1]} +check_doclist fts3c-1.1.5.4 0 3 this {[1]} + +#************************************************************************* +# Test results when all references to certain tokens are deleted. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (docid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (docid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE docid IN (1,3); +} + +# Still 4 segments because 0,3 will contain deletes for docid 1 and 3. +do_test fts3c-1.2.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0 0 1 0 2 0 3} +do_test fts3c-1.2.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}} + +check_terms_all fts3c-1.2.1 {a is test that this was} +check_doclist_all fts3c-1.2.1.1 a {[2 0[2]]} +check_doclist_all fts3c-1.2.1.2 is {} +check_doclist_all fts3c-1.2.1.3 test {[2 0[3]]} +check_doclist_all fts3c-1.2.1.4 that {[2 0[0]]} +check_doclist_all fts3c-1.2.1.5 this {} +check_doclist_all fts3c-1.2.1.6 was {[2 0[1]]} + +check_terms fts3c-1.2.2 0 0 {a is test this} +check_doclist fts3c-1.2.2.1 0 0 a {[1 0[2]]} +check_doclist fts3c-1.2.2.2 0 0 is {[1 0[1]]} +check_doclist fts3c-1.2.2.3 0 0 test {[1 0[3]]} +check_doclist fts3c-1.2.2.4 0 0 this {[1 0[0]]} + +check_terms fts3c-1.2.3 0 1 {a test that was} +check_doclist fts3c-1.2.3.1 0 1 a {[2 0[2]]} +check_doclist fts3c-1.2.3.2 0 1 test {[2 0[3]]} +check_doclist fts3c-1.2.3.3 0 1 that {[2 0[0]]} +check_doclist fts3c-1.2.3.4 0 1 was {[2 0[1]]} + +check_terms fts3c-1.2.4 0 2 {a is test this} +check_doclist fts3c-1.2.4.1 0 2 a {[3 0[2]]} +check_doclist fts3c-1.2.4.2 0 2 is {[3 0[1]]} +check_doclist fts3c-1.2.4.3 0 2 test {[3 0[3]]} +check_doclist fts3c-1.2.4.4 0 2 this {[3 0[0]]} + +check_terms fts3c-1.2.5 0 3 {a is test this} +check_doclist fts3c-1.2.5.1 0 3 a {[1] [3]} +check_doclist fts3c-1.2.5.2 0 3 is {[1] [3]} +check_doclist fts3c-1.2.5.3 0 3 test {[1] [3]} +check_doclist fts3c-1.2.5.4 0 3 this {[1] [3]} + +#************************************************************************* +# Test results when everything is optimized manually. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (docid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (docid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE docid IN (1,3); + DROP TABLE IF EXISTS t1old; + ALTER TABLE t1 RENAME TO t1old; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) SELECT docid, c FROM t1old; + DROP TABLE t1old; +} + +# Should be a single optimal segment with the same logical results. +do_test fts3c-1.3.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0} +do_test fts3c-1.3.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}} + +check_terms_all fts3c-1.3.1 {a test that was} +check_doclist_all fts3c-1.3.1.1 a {[2 0[2]]} +check_doclist_all fts3c-1.3.1.2 test {[2 0[3]]} +check_doclist_all fts3c-1.3.1.3 that {[2 0[0]]} +check_doclist_all fts3c-1.3.1.4 was {[2 0[1]]} + +check_terms fts3c-1.3.2 0 0 {a test that was} +check_doclist fts3c-1.3.2.1 0 0 a {[2 0[2]]} +check_doclist fts3c-1.3.2.2 0 0 test {[2 0[3]]} +check_doclist fts3c-1.3.2.3 0 0 that {[2 0[0]]} +check_doclist fts3c-1.3.2.4 0 0 was {[2 0[1]]} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3comp1.test b/components/external/SQLite-3.8.1/test/fts3comp1.test new file mode 100644 index 0000000000000000000000000000000000000000..9f13aaa64ea59748dcad5ecd26c736ffda1be442 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3comp1.test @@ -0,0 +1,115 @@ +# 2011 January 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !fts3 { finish_test ; return } +set ::testprefix fts3comp1 + +# Create a pretend compression system. +# +# Each time the [zip] function is called, an entry is added to the ::strings +# array mapping from an integer key to the string argument to zip. The key +# is returned. Later on, when the key is passed to [unzip], the original +# string is retrieved from the ::strings array and returned. +# +set next_x 0 +proc zip {x} { + incr ::next_x + set ::strings($::next_x) $x + return $::next_x +} +proc unzip {x} { + return $::strings($x) +} + +foreach {tn zip unzip} { + 1 zip unzip + 2 {z.i.p!!} {un "zip"} +} { + + set next_x 0 + catch {db close} + forcedelete test.db + sqlite3 db test.db + db func $zip zip + db func $unzip unzip + + # Create a table that uses zip/unzip. Check that content inserted into + # the table can be read back (using a full-scan query). Check that the + # underlying %_content table contains the compressed (integer) values. + # + do_execsql_test 1.$tn.0 " + CREATE VIRTUAL TABLE t1 USING fts4( + a, b, + compress='$zip', uncompress='$unzip' + ); + " + do_execsql_test 1.$tn.1 { + INSERT INTO t1 VALUES('one two three', 'two four six'); + SELECT a, b FROM t1; + } {{one two three} {two four six}} + do_execsql_test 1.$tn.2 { + SELECT c0a, c1b FROM t1_content; + } {1 2} + + # Insert another row and check that it can be read back. Also that the + # %_content table still contains all compressed content. This time, try + # full-text index and by-docid queries too. + # + do_execsql_test 1.$tn.3 { + INSERT INTO t1 VALUES('three six nine', 'four eight twelve'); + SELECT a, b FROM t1; + } {{one two three} {two four six} {three six nine} {four eight twelve}} + do_execsql_test 1.$tn.4 { + SELECT c0a, c1b FROM t1_content; + } {1 2 3 4} + + do_execsql_test 1.$tn.5 { + SELECT a, b FROM t1 WHERE docid = 2 + } {{three six nine} {four eight twelve}} + do_execsql_test 1.$tn.6 { + SELECT a, b FROM t1 WHERE t1 MATCH 'two' + } {{one two three} {two four six}} + + # Delete a row and check that the full-text index is correctly updated. + # Inspect the full-text index using an fts4aux table. + # + do_execsql_test 1.$tn.7 { + CREATE VIRTUAL TABLE terms USING fts4aux(t1); + SELECT term, documents, occurrences FROM terms WHERE col = '*'; + } { + eight 1 1 four 2 2 nine 1 1 one 1 1 + six 2 2 three 2 2 twelve 1 1 two 1 2 + } + do_execsql_test 1.$tn.8 { + DELETE FROM t1 WHERE docid = 1; + SELECT term, documents, occurrences FROM terms WHERE col = '*'; + } { + eight 1 1 four 1 1 nine 1 1 + six 1 1 three 1 1 twelve 1 1 + } + do_execsql_test 1.$tn.9 { SELECT c0a, c1b FROM t1_content } {3 4} +} + +# Test that is an error to specify just one of compress and uncompress. +# +do_catchsql_test 2.1 { + CREATE VIRTUAL TABLE t2 USING fts4(x, compress=zip) +} {1 {missing uncompress parameter in fts4 constructor}} +do_catchsql_test 2.2 { + CREATE VIRTUAL TABLE t2 USING fts4(x, uncompress=unzip) +} {1 {missing compress parameter in fts4 constructor}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3conf.test b/components/external/SQLite-3.8.1/test/fts3conf.test new file mode 100644 index 0000000000000000000000000000000000000000..e91efbefbef9d5646b18c2b897646b386dd74112 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3conf.test @@ -0,0 +1,181 @@ +# 2011 April 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix fts3conf + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + + +proc fts3_integrity {tn db tbl} { + + if {[sqlite3_get_autocommit $db]==0} { + error "fts3_integrity does not work with an open transaction" + } + + set sql [db one {SELECT sql FROM sqlite_master WHERE name = $tbl}] + regexp -nocase {[^(]* using (.*)} $sql -> tail + set cols [list] + $db eval "PRAGMA table_info($tbl)" { + lappend cols $name + } + set cols [join [concat docid $cols] ,] + + $db eval [subst { + CREATE VIRTUAL TABLE fts3check USING fts4term($tbl); + CREATE VIRTUAL TABLE temp.fts3check2 USING $tail; + INSERT INTO temp.fts3check2($cols) SELECT docid, * FROM $tbl; + CREATE VIRTUAL TABLE temp.fts3check3 USING fts4term(fts3check2); + }] + + set m1 [$db one {SELECT md5sum(term, docid, col, pos) FROM fts3check}] + set m2 [$db one {SELECT md5sum(term, docid, col, pos) FROM fts3check3}] + + $db eval { + DROP TABLE fts3check; + DROP TABLE temp.fts3check2; + DROP TABLE temp.fts3check3; + } + + uplevel [list do_test $tn [list set {} $m1] $m2] +} + +do_execsql_test 1.0.1 { + CREATE VIRTUAL TABLE t1 USING fts3(x); + INSERT INTO t1(rowid, x) VALUES(1, 'a b c d'); + INSERT INTO t1(rowid, x) VALUES(2, 'e f g h'); + + CREATE TABLE source(a, b); + INSERT INTO source VALUES(4, 'z'); + INSERT INTO source VALUES(2, 'y'); +} +db_save_and_close + +set T1 "INTO t1(rowid, x) VALUES(1, 'x')" +set T2 "INTO t1(rowid, x) SELECT * FROM source" + +set T3 "t1 SET docid = 2 WHERE docid = 1" +set T4 "t1 SET docid = CASE WHEN docid = 1 THEN 4 ELSE 3 END WHERE docid <=2" + +foreach {tn sql uses constraint data} [subst { + 1 "INSERT OR ROLLBACK $T1" 0 1 {{a b c d} {e f g h}} + 2 "INSERT OR ABORT $T1" 0 1 {{a b c d} {e f g h} {i j k l}} + 3 "INSERT OR FAIL $T1" 0 1 {{a b c d} {e f g h} {i j k l}} + 4 "INSERT OR IGNORE $T1" 0 0 {{a b c d} {e f g h} {i j k l}} + 5 "INSERT OR REPLACE $T1" 0 0 {x {e f g h} {i j k l}} + + 6 "INSERT OR ROLLBACK $T2" 1 1 {{a b c d} {e f g h}} + 7 "INSERT OR ABORT $T2" 1 1 {{a b c d} {e f g h} {i j k l}} + 8 "INSERT OR FAIL $T2" 1 1 {{a b c d} {e f g h} {i j k l} z} + 9 "INSERT OR IGNORE $T2" 1 0 {{a b c d} {e f g h} {i j k l} z} + 10 "INSERT OR REPLACE $T2" 1 0 {{a b c d} y {i j k l} z} + + 11 "UPDATE OR ROLLBACK $T3" 1 1 {{a b c d} {e f g h}} + 12 "UPDATE OR ABORT $T3" 1 1 {{a b c d} {e f g h} {i j k l}} + 13 "UPDATE OR FAIL $T3" 1 1 {{a b c d} {e f g h} {i j k l}} + 14 "UPDATE OR IGNORE $T3" 1 0 {{a b c d} {e f g h} {i j k l}} + 15 "UPDATE OR REPLACE $T3" 1 0 {{a b c d} {i j k l}} + + 16 "UPDATE OR ROLLBACK $T4" 1 1 {{a b c d} {e f g h}} + 17 "UPDATE OR ABORT $T4" 1 1 {{a b c d} {e f g h} {i j k l}} + 18 "UPDATE OR FAIL $T4" 1 1 {{e f g h} {i j k l} {a b c d}} + 19 "UPDATE OR IGNORE $T4" 1 0 {{e f g h} {i j k l} {a b c d}} + 20 "UPDATE OR REPLACE $T4" 1 0 {{e f g h} {a b c d}} +}] { + db_restore_and_reopen + execsql { + BEGIN; + INSERT INTO t1(rowid, x) VALUES(3, 'i j k l'); + } + set R(0) {0 {}} + set R(1) {1 {constraint failed}} + do_catchsql_test 1.$tn.1 $sql $R($constraint) + do_catchsql_test 1.$tn.2 { SELECT * FROM t1 } [list 0 $data] + catchsql COMMIT + + fts3_integrity 1.$tn.3 db t1 + + do_test 1.$tn.4 [list sql_uses_stmt db $sql] $uses +} + +do_execsql_test 2.1.1 { + DELETE FROM t1; + BEGIN; + INSERT INTO t1 VALUES('a b c'); + SAVEPOINT a; + INSERT INTO t1 VALUES('x y z'); + ROLLBACK TO a; + COMMIT; +} +fts3_integrity 2.1.2 db t1 + +do_catchsql_test 2.2.1 { + DELETE FROM t1; + BEGIN; + INSERT INTO t1(docid, x) VALUES(0, 'a b c'); + INSERT INTO t1(docid, x) VALUES(1, 'a b c'); + REPLACE INTO t1(docid, x) VALUES('zero', 'd e f'); +} {1 {datatype mismatch}} +do_execsql_test 2.2.2 { COMMIT } +do_execsql_test 2.2.3 { SELECT * FROM t1 } {{a b c} {a b c}} +fts3_integrity 2.2.4 db t1 + +do_execsql_test 3.1 { + CREATE VIRTUAL TABLE t3 USING fts4; + REPLACE INTO t3(docid, content) VALUES (1, 'one two'); + SELECT quote(matchinfo(t3, 'na')) FROM t3 WHERE t3 MATCH 'one' +} {X'0100000002000000'} + +do_execsql_test 3.2 { + REPLACE INTO t3(docid, content) VALUES (2, 'one two three four'); + SELECT quote(matchinfo(t3, 'na')) FROM t3 WHERE t3 MATCH 'four' +} {X'0200000003000000'} + +do_execsql_test 3.3 { + REPLACE INTO t3(docid, content) VALUES (1, 'one two three four five six'); + SELECT quote(matchinfo(t3, 'na')) FROM t3 WHERE t3 MATCH 'six' +} {X'0200000005000000'} + +do_execsql_test 3.4 { + UPDATE OR REPLACE t3 SET docid = 2 WHERE docid=1; + SELECT quote(matchinfo(t3, 'na')) FROM t3 WHERE t3 MATCH 'six' +} {X'0100000006000000'} + +do_execsql_test 3.5 { + UPDATE OR REPLACE t3 SET docid = 3 WHERE docid=2; + SELECT quote(matchinfo(t3, 'na')) FROM t3 WHERE t3 MATCH 'six' +} {X'0100000006000000'} + +do_execsql_test 3.6 { + REPLACE INTO t3(docid, content) VALUES (3, 'one two'); + SELECT quote(matchinfo(t3, 'na')) FROM t3 WHERE t3 MATCH 'one' +} {X'0100000002000000'} + +do_execsql_test 3.7 { + REPLACE INTO t3(docid, content) VALUES (NULL, 'one two three four'); + REPLACE INTO t3(docid, content) VALUES (NULL, 'one two three four five six'); + SELECT docid FROM t3; +} {3 4 5} + +do_execsql_test 3.8 { + UPDATE OR REPLACE t3 SET docid = 5, content='three four' WHERE docid = 4; + SELECT quote(matchinfo(t3, 'na')) FROM t3 WHERE t3 MATCH 'one' +} {X'0200000002000000'} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3corrupt.test b/components/external/SQLite-3.8.1/test/fts3corrupt.test new file mode 100644 index 0000000000000000000000000000000000000000..cb50e3e46ae527183de775bbc34189fcdf5169f8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3corrupt.test @@ -0,0 +1,168 @@ +# 2010 October 27 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# Test that the FTS3 extension does not crash when it encounters a +# corrupt data structure on disk. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { finish_test ; return } + +set ::testprefix fts3corrupt + + +# Test that a doclist with a length field that indicates that the doclist +# extends past the end of the node on which it resides is correctly identified +# as database corruption. +# +do_execsql_test 1.0 { + CREATE VIRTUAL TABLE t1 USING fts3; + INSERT INTO t1 VALUES('hello'); +} {} +do_test fts3corrupt-1.1 { + set blob [db one {SELECT root from t1_segdir}] + set blob [binary format a7ca* $blob 24 [string range $blob 8 end]] + execsql { UPDATE t1_segdir SET root = $blob } +} {} +do_test fts3corrupt-1.2 { + foreach w {a b c d e f g h i j k l m n o} { + execsql { INSERT INTO t1 VALUES($w) } + } +} {} +do_catchsql_test 1.3 { + INSERT INTO t1 VALUES('world'); +} {1 {database disk image is malformed}} +do_test 1.3.1 { sqlite3_extended_errcode db } SQLITE_CORRUPT_VTAB +do_execsql_test 1.4 { + DROP TABLE t1; +} + +# This block of tests checks that corruption is correctly detected if the +# length field of a term on a leaf node indicates that the term extends past +# the end of the node on which it resides. There are two cases: +# +# 1. The first term on the node. +# 2. The second or subsequent term on the node (prefix compressed term). +# +do_execsql_test 2.0 { + CREATE VIRTUAL TABLE t1 USING fts3; + BEGIN; + INSERT INTO t1 VALUES('hello'); + INSERT INTO t1 VALUES('hello'); + INSERT INTO t1 VALUES('hello'); + INSERT INTO t1 VALUES('hello'); + INSERT INTO t1 VALUES('hello'); + COMMIT; +} {} +do_test fts3corrupt-2.1 { + set blob [db one {SELECT root from t1_segdir}] + set blob [binary format a*a* "\x00\x7F" [string range $blob 2 end]] + execsql { UPDATE t1_segdir SET root = $blob } +} {} +do_catchsql_test 2.2 { + SELECT rowid FROM t1 WHERE t1 MATCH 'hello' +} {1 {database disk image is malformed}} +do_test 2.2.1 { sqlite3_extended_errcode db } SQLITE_CORRUPT_VTAB + +do_execsql_test 3.0 { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts3; + BEGIN; + INSERT INTO t1 VALUES('hello'); + INSERT INTO t1 VALUES('world'); + COMMIT; +} {} +do_test fts3corrupt-3.1 { + set blob [db one {SELECT quote(root) from t1_segdir}] + set blob [binary format a11a*a* $blob "\x7F" [string range $blob 12 end]] + execsql { UPDATE t1_segdir SET root = $blob } +} {} +do_catchsql_test 3.2 { + SELECT rowid FROM t1 WHERE t1 MATCH 'world' +} {1 {database disk image is malformed}} +do_test 3.2.1 { sqlite3_extended_errcode db } SQLITE_CORRUPT_VTAB + + +do_execsql_test 4.0 { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts3; + INSERT INTO t1(t1) VALUES('nodesize=24'); +} +do_test fts3corrupt-4.1 { + execsql BEGIN + foreach s { + "amxtvoo adqwroyhz auq aithtir avniqnuynvf axp ahibayfynig agbicpm" + "ajdtebs anteaxr aieynenwmd awpl alo akxcrwow aoxftge aoqvgul" + "amcfvdr auz apu aebelm ahuxyz aqc asyafdb agulvhvqu" + "apepwfyz azkhdvkw aenyelxzbk aslnitbyet aycdsdcpgr aqzzdbc agfi axnypydou" + "aaqrzzcm apcxdxo atumltzj aevvivo aodknoft aqoyytoz alobx apldt" + } { + execsql { INSERT INTO t1 VALUES($s) } + } + execsql COMMIT +} {} + +do_catchsql_test 4.2 { + UPDATE t1_segdir SET root = X'FFFFFFFFFFFFFFFF'; + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; +} {1 {database disk image is malformed}} +do_test 4.2.1 { sqlite3_extended_errcode db } SQLITE_CORRUPT_VTAB + +set blob [binary format cca*cca*cca*cca*cca*cca*cca*cca*cca*cca*a* \ + 22 120 [string repeat a 120] \ + 22 120 [string repeat b 120] \ + 22 120 [string repeat c 120] \ + 22 120 [string repeat d 120] \ + 22 120 [string repeat e 120] \ + 22 120 [string repeat f 120] \ + 22 120 [string repeat g 120] \ + 22 120 [string repeat h 120] \ + 22 120 [string repeat i 120] \ + 22 120 [string repeat j 120] \ + "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" +] + +do_catchsql_test 4.3 { + UPDATE t1_segdir SET root = $blob; + SELECT rowid FROM t1 WHERE t1 MATCH 'world'; +} {1 {database disk image is malformed}} +do_test 4.3.1 { sqlite3_extended_errcode db } SQLITE_CORRUPT_VTAB + +# Test a special kind of corruption, where the %_stat table contains +# an invalid entry. At one point this could lead to a division-by-zero +# error in fts4. +# +do_execsql_test 5.0 { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts4; +} +do_test 5.1 { + db func nn nn + execsql BEGIN + execsql { INSERT INTO t1 VALUES('one') } + execsql { INSERT INTO t1 VALUES('two') } + execsql { INSERT INTO t1 VALUES('three') } + execsql { INSERT INTO t1 VALUES('four') } + execsql COMMIT +} {} +do_catchsql_test 5.2 { + UPDATE t1_stat SET value = X'0000'; + SELECT matchinfo(t1, 'nxa') FROM t1 WHERE t1 MATCH 't*'; +} {1 {database disk image is malformed}} +do_test 5.2.1 { sqlite3_extended_errcode db } SQLITE_CORRUPT_VTAB +do_catchsql_test 5.3 { + UPDATE t1_stat SET value = NULL; + SELECT matchinfo(t1, 'nxa') FROM t1 WHERE t1 MATCH 't*'; +} {1 {database disk image is malformed}} +do_test 5.3.1 { sqlite3_extended_errcode db } SQLITE_CORRUPT_VTAB + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3corrupt2.test b/components/external/SQLite-3.8.1/test/fts3corrupt2.test new file mode 100644 index 0000000000000000000000000000000000000000..78c76778f5c8bf3c1d923e6d336348014bd0f280 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3corrupt2.test @@ -0,0 +1,110 @@ +# 2010 October 30 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# Test that the FTS3 extension does not crash when it encounters a +# corrupt data structure on disk. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { finish_test ; return } + +set ::testprefix fts3corrupt2 + +set data [list] +lappend data {*}{ + "amxtvoo adqwroyhz auq aithtir avniqnuynvf axp ahibayfynig agbicpm" + "ajdtebs anteaxr aieynenwmd awpl alo akxcrwow aoxftge aoqvgul" + "amcfvdr auz apu aebelm ahuxyz aqc asyafdb agulvhvqu" + "apepwfyz azkhdvkw aenyelxzbk aslnitbyet aycdsdcpgr aqzzdbc agfi axnypydou" + "aaqrzzcm apcxdxo atumltzj aevvivo aodknoft aqoyytoz alobx apldt" + "adjllxlhnmj aiuhvuj adwppceuht atvj azrsam ahkjqdhny audlqxr aotgcd" + "aira azflsceos awj auzbobfkc awmezplr aeh awec ahndxlmv" + "aydwnied alk auoap agihyqeix aymqxzajnl aydwnied aojkarx agbo" + "ahajsmcl anvx amdhjm aoptsj agugzjjm apkevm acnj acjg" + "amwtkw aogttbykvt aubwrfqnbjf ajow agsj aerkqzjdqst anenlvbalkn arfajzzgckx" + "adqqqofkmz amjpavjuhw aqgehgnb awvvxlbtqzn agstqko akmkzehyh atagzey agwja" + "amag ahe autkllywhr avnk atmt akn anvdh aixfrv" + "aqdyerbws avefykly awl azaduojgzo anxfsmw axpt abgbvk ati" + "attyqkwz aiweypiczul afy asitaqbczhh aitxisizpv auhviq aibql ajfqc" + "aylzprtmta aiuemihqrpi awluvgsw ampbuy axlifpzfqr aems aoaxwads apianfn" + "aodrkijelq acdb aaserrdxm aqyasgofqu aevvivo afi apmwu aeoqysl" + "amqnk ankaotm ayfy ajcupeeoc advcbukan aucahlwnyk adbfyo azqjpeant" + "afczpp asqrs ahslvda akhlf aiqgdp atyd aznuglxqbrg awirndrh" + "aqhiajp amxeazb asxuehg akod axvolvsp agcz asmovmohy acmqa" + "avvomv aafms ashuaec arevx audtq alrwqhjvao avgsgpg ajbrctpsel" + "atxoirr ayopboobqdu ajunntua arh aernimxid aipljda aglo aefk" + "aonxf acmnnkna abgviaswe aulvcbv axp apemgakpzo aibql acioaid" + "axo alrwqhjvao ayqounftdzl azmoakdyh apajze ajk artvy apxiamy" + "ayjafsraz addjj agsj asejtziqws acatvhegu aoxdjqblsvv aekdmmbs aaobe" + "abjjvzubkwt alczv ati awz auyxgcxeb aymjoym anqoukprtyt atwfhpmbooh" + "ajfqz aethlgir aclcx aowlyvetby aproqm afjlqtkv anebfy akzrcpfrrvw" + "aoledfotm aiwlfm aeejlaej anz abgbvk aktfn aayoh anpywgdvgz" + "acvmldguld asdvz aqb aeomsyzyu aggylhprbdz asrfkwz auipybpsn agsnszzfb" +} + +do_test fts3corrupt2-1.0 { + execsql BEGIN + execsql { CREATE VIRTUAL TABLE t2 USING FTS3(a, b); } + execsql { INSERT INTO t2(t2) VALUES('nodesize=32') } + foreach d $data { + execsql { INSERT INTO t2 VALUES($d, $d) } + } + execsql COMMIT + execsql { SELECT count(*) FROM t2_segments } +} {163} + +proc set_byte {blob byte val} { + binary format a*ca* \ + [string range $blob 0 [expr $byte-1]] \ + $val \ + [string range $blob [expr $byte+1] end] \ +} + +set tn 0 +set c 256 +foreach {rowid sz blob} [ + db eval {SELECT rowid, length(block), block FROM t2_segments} +] { + incr tn + set c [expr (($c+255)%256)] + for {set i 0} {$i < $sz} {incr i} { + set b2 [set_byte $blob $i $c] + execsql { UPDATE t2_segments SET block = $b2 WHERE rowid = $rowid } + do_test fts3corrupt2-1.$tn.$i { + catchsql { SELECT * FROM t2 WHERE t2 MATCH 'a*' } + set {} {} + } {} + } + execsql { UPDATE t2_segments SET block = $blob WHERE rowid = $rowid } +} + +foreach c {50 100 150 200 250} { + foreach {rowid sz blob} [ + db eval {SELECT rowid, length(root), root FROM t2_segdir} + ] { + incr tn + for {set i 0} {$i < $sz} {incr i} { + set b2 [set_byte $blob $i $c] + execsql { UPDATE t2_segdir SET root = $b2 WHERE rowid = $rowid } + do_test fts3corrupt2-2.$c.$tn.$i { + catchsql { SELECT * FROM t2 WHERE t2 MATCH 'a*' } + set {} {} + } {} + } + execsql { UPDATE t2_segdir SET root = $blob WHERE rowid = $rowid } + } +} + + + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3cov.test b/components/external/SQLite-3.8.1/test/fts3cov.test new file mode 100644 index 0000000000000000000000000000000000000000..c43999d2da04c7be895a1250a6302fd3062309bd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3cov.test @@ -0,0 +1,432 @@ +# 2009 December 03 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The tests in this file are structural coverage tests for FTS3. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If this build does not include FTS3, skip the tests in this file. +# +ifcapable !fts3 { finish_test ; return } +source $testdir/fts3_common.tcl +source $testdir/malloc_common.tcl + +set DO_MALLOC_TEST 0 +set testprefix fts3cov + +#-------------------------------------------------------------------------- +# When it first needs to read a block from the %_segments table, the FTS3 +# module compiles an SQL statement for that purpose. The statement is +# stored and reused each subsequent time a block is read. This test case +# tests the effects of an OOM error occuring while compiling the statement. +# +# Similarly, when FTS3 first needs to scan through a set of segment leaves +# to find a set of documents that matches a term, it allocates a string +# containing the text of the required SQL, and compiles one or more +# statements to traverse the leaves. This test case tests that OOM errors +# that occur while allocating this string and statement are handled correctly +# also. +# +do_test fts3cov-1.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts3(x); + INSERT INTO t1(t1) VALUES('nodesize=24'); + BEGIN; + INSERT INTO t1 VALUES('Is the night chilly and dark?'); + INSERT INTO t1 VALUES('The night is chilly, but not dark.'); + INSERT INTO t1 VALUES('The thin gray cloud is spread on high,'); + INSERT INTO t1 VALUES('It covers but not hides the sky.'); + COMMIT; + SELECT count(*)>0 FROM t1_segments; + } +} {1} + +set DO_MALLOC_TEST 1 +do_restart_select_test fts3cov-1.2 { + SELECT docid FROM t1 WHERE t1 MATCH 'chilly'; +} {1 2} +set DO_MALLOC_TEST 0 + +#-------------------------------------------------------------------------- +# When querying the full-text index, if an expected internal node block is +# missing from the %_segments table, or if a NULL value is stored in the +# %_segments table instead of a binary blob, database corruption should be +# reported. +# +# Even with tiny 24 byte nodes, it takes a fair bit of data to produce a +# segment b-tree that uses the %_segments table to store internal nodes. +# +do_test fts3cov-2.1 { + execsql { + INSERT INTO t1(t1) VALUES('nodesize=24'); + BEGIN; + INSERT INTO t1 VALUES('The moon is behind, and at the full;'); + INSERT INTO t1 VALUES('And yet she looks both small and dull.'); + INSERT INTO t1 VALUES('The night is chill, the cloud is gray:'); + INSERT INTO t1 VALUES('''T is a month before the month of May,'); + INSERT INTO t1 VALUES('And the Spring comes slowly up this way.'); + INSERT INTO t1 VALUES('The lovely lady, Christabel,'); + INSERT INTO t1 VALUES('Whom her father loves so well,'); + INSERT INTO t1 VALUES('What makes her in the wood so late,'); + INSERT INTO t1 VALUES('A furlong from the castle gate?'); + INSERT INTO t1 VALUES('She had dreams all yesternight'); + INSERT INTO t1 VALUES('Of her own betrothed knight;'); + INSERT INTO t1 VALUES('And she in the midnight wood will pray'); + INSERT INTO t1 VALUES('For the weal of her lover that''s far away.'); + COMMIT; + } + execsql { + INSERT INTO t1(t1) VALUES('optimize'); + SELECT substr(hex(root), 1, 2) FROM t1_segdir; + } +} {03} + +# Test the "missing entry" case: +do_test fts3cov-2.2 { + set root [db one {SELECT root FROM t1_segdir}] + read_fts3varint [string range $root 1 end] left_child + execsql { DELETE FROM t1_segments WHERE blockid = $left_child } +} {} +do_error_test fts3cov-2.3 { + SELECT * FROM t1 WHERE t1 MATCH 'c*' +} {SQL logic error or missing database} + +# Test the "replaced with NULL" case: +do_test fts3cov-2.4 { + execsql { INSERT INTO t1_segments VALUES($left_child, NULL) } +} {} +do_error_test fts3cov-2.5 { + SELECT * FROM t1 WHERE t1 MATCH 'cloud' +} {SQL logic error or missing database} + +#-------------------------------------------------------------------------- +# The following tests are to test the effects of OOM errors while storing +# terms in the pending-hash table. Specifically, while creating doclist +# blobs to store in the table. More specifically, to test OOM errors while +# appending column numbers to doclists. For example, if a doclist consists +# of: +# +# 0x01 +# +# The following tests check that malloc errors encountered while appending +# the "0x01 " data to the dynamically growable blob used to +# accumulate the doclist in memory are handled correctly. +# +do_test fts3cov-3.1 { + set cols [list] + set vals [list] + for {set i 0} {$i < 120} {incr i} { + lappend cols "col$i" + lappend vals "'word'" + } + execsql "CREATE VIRTUAL TABLE t2 USING fts3([join $cols ,])" +} {} +set DO_MALLOC_TEST 1 +do_write_test fts3cov-3.2 t2_content " + INSERT INTO t2(docid, [join $cols ,]) VALUES(1, [join $vals ,]) +" +do_write_test fts3cov-3.3 t2_content " + INSERT INTO t2(docid, [join $cols ,]) VALUES(200, [join $vals ,]) +" +do_write_test fts3cov-3.4 t2_content " + INSERT INTO t2(docid, [join $cols ,]) VALUES(60000, [join $vals ,]) +" + +#------------------------------------------------------------------------- +# If too much data accumulates in the pending-terms hash table, it is +# flushed to the database automatically, even if the transaction has not +# finished. The following tests check the effects of encountering an OOM +# while doing this. +# +do_test fts3cov-4.1 { + execsql { + CREATE VIRTUAL TABLE t3 USING fts3(x); + INSERT INTO t3(t3) VALUES('nodesize=24'); + INSERT INTO t3(t3) VALUES('maxpending=100'); + } +} {} +set DO_MALLOC_TEST 1 +do_write_test fts3cov-4.2 t3_content { + INSERT INTO t3(docid, x) + SELECT 1, 'Then Christabel stretched forth her hand,' UNION ALL + SELECT 3, 'And comforted fair Geraldine:' UNION ALL + SELECT 4, '''O well, bright dame, may you command' UNION ALL + SELECT 5, 'The service of Sir Leoline;' UNION ALL + SELECT 2, 'And gladly our stout chivalry' UNION ALL + SELECT 7, 'Will he send forth, and friends withal,' UNION ALL + SELECT 8, 'To guide and guard you safe and free' UNION ALL + SELECT 6, 'Home to your noble father''s hall.''' +} + +#------------------------------------------------------------------------- +# When building the internal tree structure for each segment b-tree, FTS3 +# assumes that the content of each internal node will be less than +# $nodesize bytes, where $nodesize is the advisory node size. If this turns +# out to be untrue, then an extra buffer must be malloc'd for each term. +# This test case tests these paths and the effects of said mallocs failing +# by inserting insert a document with some fairly large terms into a +# full-text table with a very small node-size. +# +# Test this handling of large terms in three contexts: +# +# 1. When flushing the pending-terms table. +# 2. When optimizing the data structures using the INSERT syntax. +# 2. When optimizing the data structures using the deprecated SELECT syntax. +# +do_test fts3cov-5.1 { + execsql { + CREATE VIRTUAL TABLE t4 USING fts3(x); + INSERT INTO t4(t4) VALUES('nodesize=24'); + } +} {} +set DO_MALLOC_TEST 1 + +# Test when flushing pending-terms table. +do_write_test fts3cov-5.2 t4_content { + INSERT INTO t4 + SELECT 'ItisanancientMarinerAndhestoppethoneofthreeAA' UNION ALL + SELECT 'ItisanancientMarinerAndhestoppethoneofthreeBB' UNION ALL + SELECT 'ItisanancientMarinerAndhestoppethoneofthreeCC' UNION ALL + SELECT 'BythylonggreybeardandglitteringeyeNowwhereforestoppstAA' UNION ALL + SELECT 'BythylonggreybeardandglitteringeyeNowwhereforestoppstBB' UNION ALL + SELECT 'BythylonggreybeardandglitteringeyeNowwhereforestoppstCC' +} + +# Test when optimizing via INSERT. +do_test fts3cov-5.3 { execsql { INSERT INTO t4 VALUES('extra!') } } {} +do_write_test fts3cov-5.2 t4_segments { INSERT INTO t4(t4) VALUES('optimize') } + +# Test when optimizing via SELECT. +do_test fts3cov-5.5 { execsql { INSERT INTO t4 VALUES('more extra!') } } {} +do_write_test fts3cov-5.6 t4_segments { + SELECT * FROM (SELECT optimize(t4) FROM t4 LIMIT 1) + EXCEPT SELECT 'Index optimized' +} + +#------------------------------------------------------------------------- +# When merging all segments at a given level to create a single segment +# at level+1, FTS3 runs a query of the form: +# +# SELECT count(*) FROM %_segdir WHERE level = ? +# +# The query is compiled the first time this operation is required and +# reused thereafter. This test aims to test the effects of an OOM while +# preparing and executing this query for the first time. +# +# Then, keep inserting rows into the table so that the effects of an OOM +# while re-executing the same query can also be tested. +# +do_test fts3cov-6.1 { + execsql { CREATE VIRTUAL TABLE t5 USING fts3(x) } + for {set i 0} {$i<16} {incr i} { execsql "INSERT INTO t5 VALUES('term$i')" } + execsql { SELECT count(*) FROM t5_segdir } +} {16} + +# First time. +db close +sqlite3 db test.db +do_write_test fts3cov-6.2 t5_content { + INSERT INTO t5 VALUES('segment number 16!'); +} + +# Second time. +do_test fts3cov-6.3 { + for {set i 1} {$i<16} {incr i} { execsql "INSERT INTO t5 VALUES('term$i')" } + execsql { SELECT count(*) FROM t5_segdir } +} {17} +do_write_test fts3cov-6.4 t5_content { + INSERT INTO t5 VALUES('segment number 16!'); +} + +#------------------------------------------------------------------------- +# Update the docid of a row. Test this in two scenarios: +# +# 1. When the row being updated is the only row in the table. +# 2. When it is not. +# +# The two cases above take different paths because in case 1 all data +# structures can simply be emptied before inserting the new row record. +# In case 2, the data structures actually have to be updated. +# +do_test fts3cov-7.1 { + execsql { + CREATE VIRTUAL TABLE t7 USING fts3(a, b, c); + INSERT INTO t7 VALUES('A', 'B', 'C'); + UPDATE t7 SET docid = 5; + SELECT docid, * FROM t7; + } +} {5 A B C} +do_test fts3cov-7.2 { + execsql { + INSERT INTO t7 VALUES('D', 'E', 'F'); + UPDATE t7 SET docid = 1 WHERE docid = 6; + SELECT docid, * FROM t7; + } +} {1 D E F 5 A B C} + +#------------------------------------------------------------------------- +# If a set of documents are modified within a transaction, the +# pending-terms table must be flushed each time a document with a docid +# less than or equal to the previous docid is modified. +# +# This test checks the effects of an OOM error occuring when the +# pending-terms table is flushed for this reason as part of a DELETE +# statement. +# +do_malloc_test fts3cov-8 -sqlprep { + BEGIN; + CREATE VIRTUAL TABLE t8 USING fts3; + INSERT INTO t8 VALUES('the output of each batch run'); + INSERT INTO t8 VALUES('(possibly a day''s work)'); + INSERT INTO t8 VALUES('was written to two separate disks'); + COMMIT; +} -sqlbody { + BEGIN; + DELETE FROM t8 WHERE rowid = 3; + DELETE FROM t8 WHERE rowid = 2; + DELETE FROM t8 WHERE rowid = 1; + COMMIT; +} + +#------------------------------------------------------------------------- +# Test some branches in the code that handles "special" inserts like: +# +# INSERT INTO t1(t1) VALUES('optimize'); +# +# Also test that an optimize (INSERT method) works on an empty table. +# +set DO_MALLOC_TEST 0 +do_test fts3cov-9.1 { + execsql { CREATE VIRTUAL TABLE xx USING fts3 } +} {} +do_error_test fts3cov-9.2 { + INSERT INTO xx(xx) VALUES('optimise'); -- British spelling +} {SQL logic error or missing database} +do_error_test fts3cov-9.3 { + INSERT INTO xx(xx) VALUES('short'); +} {SQL logic error or missing database} +do_error_test fts3cov-9.4 { + INSERT INTO xx(xx) VALUES('waytoolongtobecorrect'); +} {SQL logic error or missing database} +do_test fts3cov-9.5 { + execsql { INSERT INTO xx(xx) VALUES('optimize') } +} {} + +#------------------------------------------------------------------------- +# Test that a table can be optimized in the middle of a transaction when +# the pending-terms table is non-empty. This case involves some extra +# branches because data must be read not only from the database, but +# also from the pending-terms table. +# +do_malloc_test fts3cov-10 -sqlprep { + CREATE VIRTUAL TABLE t10 USING fts3; + INSERT INTO t10 VALUES('Optimising images for the web is a tricky business'); + BEGIN; + INSERT INTO t10 VALUES('You have to get the right balance between'); +} -sqlbody { + INSERT INTO t10(t10) VALUES('optimize'); +} + +#------------------------------------------------------------------------- +# Test a full-text query for a term that was once in the index, but is +# no longer. +# +do_test fts3cov-11.1 { + execsql { + CREATE VIRTUAL TABLE xx USING fts3; + INSERT INTO xx VALUES('one two three'); + INSERT INTO xx VALUES('four five six'); + DELETE FROM xx WHERE docid = 1; + } + execsql { SELECT * FROM xx WHERE xx MATCH 'two' } +} {} + + +do_malloc_test fts3cov-12 -sqlprep { + CREATE VIRTUAL TABLE t12 USING fts3; + INSERT INTO t12 VALUES('is one of the two togther'); + BEGIN; + INSERT INTO t12 VALUES('one which was appropriate at the time'); +} -sqlbody { + SELECT * FROM t12 WHERE t12 MATCH 'one' +} + +do_malloc_test fts3cov-13 -sqlprep { + PRAGMA encoding = 'UTF-16'; + CREATE VIRTUAL TABLE t13 USING fts3; + INSERT INTO t13 VALUES('two scalar functions'); + INSERT INTO t13 VALUES('scalar two functions'); + INSERT INTO t13 VALUES('functions scalar two'); +} -sqlbody { + SELECT snippet(t13, '%%', '%%', '#') FROM t13 WHERE t13 MATCH 'two'; + SELECT snippet(t13, '%%', '%%') FROM t13 WHERE t13 MATCH 'two'; + SELECT snippet(t13, '%%') FROM t13 WHERE t13 MATCH 'two'; +} + +do_execsql_test 14.0 { + CREATE VIRTUAL TABLE t14 USING fts4(a, b); + INSERT INTO t14 VALUES('one two three', 'one three four'); + INSERT INTO t14 VALUES('a b c', 'd e a'); +} +do_execsql_test 14.1 { + SELECT rowid FROM t14 WHERE t14 MATCH '"one two three"' +} {1} +do_execsql_test 14.2 { + SELECT rowid FROM t14 WHERE t14 MATCH '"one four"' +} {} +do_execsql_test 14.3 { + SELECT rowid FROM t14 WHERE t14 MATCH '"e a"' +} {2} +do_execsql_test 14.5 { + SELECT rowid FROM t14 WHERE t14 MATCH '"e b"' +} {} +do_catchsql_test 14.6 { + SELECT rowid FROM t14 WHERE rowid MATCH 'one' +} {1 {unable to use function MATCH in the requested context}} +do_catchsql_test 14.7 { + SELECT rowid FROM t14 WHERE docid MATCH 'one' +} {1 {unable to use function MATCH in the requested context}} + +do_execsql_test 15.0 { + CREATE VIRTUAL TABLE t15 USING fts4(a, b, c); + INSERT INTO t15 VALUES('abc def ghi', 'abc2 def2 ghi2', 'abc3 def3 ghi3'); + INSERT INTO t15 VALUES('abc2 def2 ghi2', 'abc2 def2 ghi2', 'abc def3 ghi3'); +} +do_execsql_test 15.1 { + SELECT rowid FROM t15 WHERE t15 MATCH '"abc* def2"' +} {1 2} + +# Test a corruption case. +# +do_execsql_test 16.1 { + CREATE VIRTUAL TABLE t16 USING fts4; + INSERT INTO t16 VALUES('theoretical work to examine the relationship'); + INSERT INTO t16 VALUES('solution of our problems on the invisible'); + DELETE FROM t16_content WHERE rowid = 2; +} +do_catchsql_test 16.2 { + SELECT * FROM t16 WHERE t16 MATCH 'invisible' +} {1 {database disk image is malformed}} + +# And another corruption test case. +# +do_execsql_test 17.1 { + CREATE VIRTUAL TABLE t17 USING fts4; + INSERT INTO t17(content) VALUES('one one one'); + UPDATE t17_segdir SET root = X'00036F6E65FFFFFFFFFFFFFFFFFFFFFF02030300' +} {} +do_catchsql_test 17.2 { + SELECT * FROM t17 WHERE t17 MATCH 'one' +} {1 {database disk image is malformed}} + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3d.test b/components/external/SQLite-3.8.1/test/fts3d.test new file mode 100644 index 0000000000000000000000000000000000000000..1ae992b3119cbd51109c50c917409338cff04c64 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3d.test @@ -0,0 +1,360 @@ +# 2008 June 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The focus +# of this script is testing the FTS3 module's optimize() function. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/fts3_common.tcl + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +#************************************************************************* +# Utility function to check for the expected terms in the segment +# level/index. _all version does same but for entire index. +proc check_terms {test level index terms} { + set where "level = $level AND idx = $index" + do_test $test.terms [list fts3_terms t1 $where] $terms +} +proc check_terms_all {test terms} { + do_test $test.terms [list fts3_terms t1 1] $terms +} + +# Utility function to check for the expected doclist for the term in +# segment level/index. _all version does same for entire index. +proc check_doclist {test level index term doclist} { + set where "level = $level AND idx = $index" + do_test $test.doclist [list fts3_doclist t1 $term $where] $doclist +} +proc check_doclist_all {test term doclist} { + do_test $test.doclist [list fts3_doclist t1 $term 1] $doclist +} + +#************************************************************************* +# Test results when all rows are deleted and one is added back. +# Previously older segments would continue to exist, but now the index +# should be dropped when the table is empty. The results should look +# exactly like we never added the earlier rows in the first place. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (docid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (docid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE 1=1; -- Delete each row rather than dropping table. + INSERT INTO t1 (docid, c) VALUES (1, 'This is a test'); +} + +# Should be a single initial segment. +do_test fts3d-1.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0} +do_test fts3d-1.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid; + } +} {{0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}} + +check_terms_all fts3d-1.1 {a is test this} +check_doclist_all fts3d-1.1.1 a {[1 0[2]]} +check_doclist_all fts3d-1.1.2 is {[1 0[1]]} +check_doclist_all fts3d-1.1.3 test {[1 0[3]]} +check_doclist_all fts3d-1.1.4 this {[1 0[0]]} + +check_terms fts3d-1.2 0 0 {a is test this} +check_doclist fts3d-1.2.1 0 0 a {[1 0[2]]} +check_doclist fts3d-1.2.2 0 0 is {[1 0[1]]} +check_doclist fts3d-1.2.3 0 0 test {[1 0[3]]} +check_doclist fts3d-1.2.4 0 0 this {[1 0[0]]} + +#************************************************************************* +# Test results when everything is optimized manually. +# NOTE(shess): This is a copy of fts3c-1.3. I've pulled a copy here +# because fts3d-2 and fts3d-3 should have identical results. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (docid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (docid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE docid IN (1,3); + DROP TABLE IF EXISTS t1old; + ALTER TABLE t1 RENAME TO t1old; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) SELECT docid, c FROM t1old; + DROP TABLE t1old; +} + +# Should be a single optimal segment with the same logical results. +do_test fts3d-2.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0} +do_test fts3d-2.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}} + +check_terms_all fts3d-2.1 {a test that was} +check_doclist_all fts3d-2.1.1 a {[2 0[2]]} +check_doclist_all fts3d-2.1.2 test {[2 0[3]]} +check_doclist_all fts3d-2.1.3 that {[2 0[0]]} +check_doclist_all fts3d-2.1.4 was {[2 0[1]]} + +check_terms fts3d-2.2 0 0 {a test that was} +check_doclist fts3d-2.2.1 0 0 a {[2 0[2]]} +check_doclist fts3d-2.2.2 0 0 test {[2 0[3]]} +check_doclist fts3d-2.2.3 0 0 that {[2 0[0]]} +check_doclist fts3d-2.2.4 0 0 was {[2 0[1]]} + +#************************************************************************* +# Test results when everything is optimized via optimize(). +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (docid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (docid, c) VALUES (3, 'This is a test'); + DELETE FROM t1 WHERE docid IN (1,3); + SELECT OPTIMIZE(t1) FROM t1 LIMIT 1; +} + +# Should be a single optimal segment with the same logical results. +do_test fts3d-3.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0} +do_test fts3d-3.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid; + } +} {{0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4}} + +check_terms_all fts3d-3.1 {a test that was} +check_doclist_all fts3d-3.1.1 a {[2 0[2]]} +check_doclist_all fts3d-3.1.2 test {[2 0[3]]} +check_doclist_all fts3d-3.1.3 that {[2 0[0]]} +check_doclist_all fts3d-3.1.4 was {[2 0[1]]} + +check_terms fts3d-3.2 0 0 {a test that was} +check_doclist fts3d-3.2.1 0 0 a {[2 0[2]]} +check_doclist fts3d-3.2.2 0 0 test {[2 0[3]]} +check_doclist fts3d-3.2.3 0 0 that {[2 0[0]]} +check_doclist fts3d-3.2.4 0 0 was {[2 0[1]]} + +#************************************************************************* +# Test optimize() against a table involving segment merges. +# NOTE(shess): Since there's no transaction, each of the INSERT/UPDATE +# statements generates a segment. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts3(c); + + INSERT INTO t1 (rowid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (rowid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (rowid, c) VALUES (3, 'This is a test'); + + UPDATE t1 SET c = 'This is a test one' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test one' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test one' WHERE rowid = 3; + + UPDATE t1 SET c = 'This is a test two' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test two' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test two' WHERE rowid = 3; + + UPDATE t1 SET c = 'This is a test three' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test three' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test three' WHERE rowid = 3; + + UPDATE t1 SET c = 'This is a test four' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test four' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test four' WHERE rowid = 3; + + UPDATE t1 SET c = 'This is a test' WHERE rowid = 1; + UPDATE t1 SET c = 'That was a test' WHERE rowid = 2; + UPDATE t1 SET c = 'This is a test' WHERE rowid = 3; +} + +# 2 segments in level 0, 1 in level 1 (18 segments created, 16 +# merged). +do_test fts3d-4.segments { + execsql { + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {0 0 0 1 1 0} + +do_test fts3d-4.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid; + } +} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \ + {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \ + {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}] + +check_terms_all fts3d-4.1 {a four is one test that this three two was} +check_doclist_all fts3d-4.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist_all fts3d-4.1.2 four {} +check_doclist_all fts3d-4.1.3 is {[1 0[1]] [3 0[1]]} +check_doclist_all fts3d-4.1.4 one {} +check_doclist_all fts3d-4.1.5 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist_all fts3d-4.1.6 that {[2 0[0]]} +check_doclist_all fts3d-4.1.7 this {[1 0[0]] [3 0[0]]} +check_doclist_all fts3d-4.1.8 three {} +check_doclist_all fts3d-4.1.9 two {} +check_doclist_all fts3d-4.1.10 was {[2 0[1]]} + +check_terms fts3d-4.2 0 0 {a four test that was} +check_doclist fts3d-4.2.1 0 0 a {[2 0[2]]} +check_doclist fts3d-4.2.2 0 0 four {[2]} +check_doclist fts3d-4.2.3 0 0 test {[2 0[3]]} +check_doclist fts3d-4.2.4 0 0 that {[2 0[0]]} +check_doclist fts3d-4.2.5 0 0 was {[2 0[1]]} + +check_terms fts3d-4.3 0 1 {a four is test this} +check_doclist fts3d-4.3.1 0 1 a {[3 0[2]]} +check_doclist fts3d-4.3.2 0 1 four {[3]} +check_doclist fts3d-4.3.3 0 1 is {[3 0[1]]} +check_doclist fts3d-4.3.4 0 1 test {[3 0[3]]} +check_doclist fts3d-4.3.5 0 1 this {[3 0[0]]} + +check_terms fts3d-4.4 1 0 {a four is one test that this three two was} +check_doclist fts3d-4.4.1 1 0 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist fts3d-4.4.2 1 0 four {[1] [2 0[4]] [3 0[4]]} +check_doclist fts3d-4.4.3 1 0 is {[1 0[1]] [3 0[1]]} +check_doclist fts3d-4.4.4 1 0 one {[1] [2] [3]} +check_doclist fts3d-4.4.5 1 0 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist fts3d-4.4.6 1 0 that {[2 0[0]]} +check_doclist fts3d-4.4.7 1 0 this {[1 0[0]] [3 0[0]]} +check_doclist fts3d-4.4.8 1 0 three {[1] [2] [3]} +check_doclist fts3d-4.4.9 1 0 two {[1] [2] [3]} +check_doclist fts3d-4.4.10 1 0 was {[2 0[1]]} + +# Optimize should leave the result in the level of the highest-level +# prior segment. +breakpoint +do_test fts3d-4.5 { + execsql { + SELECT OPTIMIZE(t1) FROM t1 LIMIT 1; + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {{Index optimized} 1 0} + +# Identical to fts3d-4.matches. +do_test fts3d-4.5.matches { + execsql { + SELECT OFFSETS(t1) FROM t1 + WHERE t1 MATCH 'this OR that OR was OR a OR is OR test' ORDER BY docid; + } +} [list {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4} \ + {0 1 0 4 0 2 5 3 0 3 9 1 0 5 11 4} \ + {0 0 0 4 0 4 5 2 0 3 8 1 0 5 10 4}] + +check_terms_all fts3d-4.5.1 {a is test that this was} +check_doclist_all fts3d-4.5.1.1 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist_all fts3d-4.5.1.2 is {[1 0[1]] [3 0[1]]} +check_doclist_all fts3d-4.5.1.3 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist_all fts3d-4.5.1.4 that {[2 0[0]]} +check_doclist_all fts3d-4.5.1.5 this {[1 0[0]] [3 0[0]]} +check_doclist_all fts3d-4.5.1.6 was {[2 0[1]]} + +check_terms fts3d-4.5.2 1 0 {a is test that this was} +check_doclist fts3d-4.5.2.1 1 0 a {[1 0[2]] [2 0[2]] [3 0[2]]} +check_doclist fts3d-4.5.2.2 1 0 is {[1 0[1]] [3 0[1]]} +check_doclist fts3d-4.5.2.3 1 0 test {[1 0[3]] [2 0[3]] [3 0[3]]} +check_doclist fts3d-4.5.2.4 1 0 that {[2 0[0]]} +check_doclist fts3d-4.5.2.5 1 0 this {[1 0[0]] [3 0[0]]} +check_doclist fts3d-4.5.2.6 1 0 was {[2 0[1]]} + +# Re-optimizing does nothing. +do_test fts3d-5.0 { + execsql { + SELECT OPTIMIZE(t1) FROM t1 LIMIT 1; + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {{Index already optimal} 1 0} + +# Even if we move things around, still does nothing. +do_test fts3d-5.1 { + execsql { + UPDATE t1_segdir SET level = 2 WHERE level = 1 AND idx = 0; + SELECT OPTIMIZE(t1) FROM t1 LIMIT 1; + SELECT level, idx FROM t1_segdir ORDER BY level, idx; + } +} {{Index already optimal} 2 0} + + +# ALTER TABLE RENAME should work regardless of the database encoding. +# +do_test fts3d-6.0 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA encoding=UTF8; + CREATE VIRTUAL TABLE fts USING fts3(a,b,c); + SELECT name FROM sqlite_master WHERE name GLOB '???_*' ORDER BY 1; + } +} {fts_content fts_segdir fts_segments} +do_test fts3d-6.1 { + db eval { + ALTER TABLE fts RENAME TO xyz; + SELECT name FROM sqlite_master WHERE name GLOB '???_*' ORDER BY 1; + } +} {xyz_content xyz_segdir xyz_segments} +do_test fts3d-6.2 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA encoding=UTF16le; + CREATE VIRTUAL TABLE fts USING fts3(a,b,c); + SELECT name FROM sqlite_master WHERE name GLOB '???_*' ORDER BY 1; + } +} {fts_content fts_segdir fts_segments} +do_test fts3d-6.3 { + db eval { + ALTER TABLE fts RENAME TO xyz; + SELECT name FROM sqlite_master WHERE name GLOB '???_*' ORDER BY 1; + } +} {xyz_content xyz_segdir xyz_segments} +do_test fts3d-6.4 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA encoding=UTF16be; + CREATE VIRTUAL TABLE fts USING fts3(a,b,c); + SELECT name FROM sqlite_master WHERE name GLOB '???_*' ORDER BY 1; + } +} {fts_content fts_segdir fts_segments} +do_test fts3d-6.5 { + db eval { + ALTER TABLE fts RENAME TO xyz; + SELECT name FROM sqlite_master WHERE name GLOB '???_*' ORDER BY 1; + } +} {xyz_content xyz_segdir xyz_segments} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3defer.test b/components/external/SQLite-3.8.1/test/fts3defer.test new file mode 100644 index 0000000000000000000000000000000000000000..532d4dfa6a6d2d78309ebb3f169f34229d0c6991 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3defer.test @@ -0,0 +1,527 @@ +# 2010 October 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +ifcapable !fts3||!fts4_deferred { + finish_test + return +} + +set sqlite_fts3_enable_parentheses 1 + +set fts3_simple_deferred_tokens_only 1 + +set ::testprefix fts3defer + +#-------------------------------------------------------------------------- +# Test cases fts3defer-1.* are the "warm body" cases. The database contains +# one row with 15000 instances of the token "a". This makes the doclist for +# "a" so large that FTS3 will avoid loading it in most cases. +# +# To show this, test cases fts3defer-1.2.* execute a bunch of FTS3 queries +# involving token "a". Then, fts3defer-1.3.* replaces the doclist for token +# "a" with all zeroes and fts3defer-1.4.* repeats the tests from 1.2. If +# the tests still work, we can conclude that the doclist for "a" was not +# used. +# + +set aaa [string repeat "a " 15000] + +do_execsql_test 1.1 { + CREATE VIRTUAL TABLE t1 USING fts4; + BEGIN; + INSERT INTO t1 VALUES('this is a dog'); + INSERT INTO t1 VALUES('an instance of a phrase'); + INSERT INTO t1 VALUES('an instance of a longer phrase'); + INSERT INTO t1 VALUES($aaa); + COMMIT; +} {} + +set tests { + 1 {SELECT rowid FROM t1 WHERE t1 MATCH '"a dog"'} {1} + 2 {SELECT rowid FROM t1 WHERE t1 MATCH '"is a dog"'} {1} + 3 {SELECT rowid FROM t1 WHERE t1 MATCH '"a longer phrase"'} {3} + 4 {SELECT snippet(t1) FROM t1 WHERE t1 MATCH '"a longer phrase"'} + {"an instance of a longer phrase"} + 5 {SELECT rowid FROM t1 WHERE t1 MATCH 'a dog'} {1} +} + +do_select_tests 1.2 $tests + +do_execsql_test 1.3 { + SELECT count(*) FROM t1_segments WHERE length(block)>10000; + UPDATE t1_segments + SET block = zeroblob(length(block)) + WHERE length(block)>10000; +} {1} + +do_select_tests 1.4 $tests + +# Drop the table. It is corrupt now anyhow, so not useful for subsequent tests. +# +do_execsql_test 1.5 { DROP TABLE t1 } + +#-------------------------------------------------------------------------- +# These tests - fts3defer-2.* - are more rigorous. They test that for a +# variety of queries, FTS3 and FTS4 return the same results. And that +# zeroing the very large doclists that FTS4 does not load does not change +# the results. +# +# They use the following pseudo-randomly generated document data. The +# tokens "zm" and "jk" are especially common in this dataset. Additionally, +# two documents are added to the pseudo-random data before it is loaded +# into FTS4 containing 100,000 instances of the "zm" and "jk" tokens. This +# makes the doclists for those tokens so large that FTS4 avoids loading them +# into memory if possible. +# +set data [list] +lappend data [string repeat "zm " 100000] +lappend data [string repeat "jk " 100000] +lappend data {*}{ + "zm zm agmckuiu uhzq nsab jk rrkx duszemmzl hyq jk" + "jk uhzq zm zm rgpzmlnmd zm zk jk jk zm" + "duszemmzl zm jk xldlpy zm jk sbptoa xh jk xldlpy" + "zm xh zm xqf azavwm jk jk trqd rgpzmlnmd jk" + "zm vwq urvysbnykk ubwrfqnbjf zk lsz jk doiwavhwwo jk jk" + "jk xduvfhk orpfawpx zkhdvkw jk mjpavjuhw zm jk duszemmzl zm" + "jk igju jk jk zm hmjf xh zm gwdfhwurx zk" + "vgsld jk jk zm hrlipdm jn zm zsmhnf vgsld duszemmzl" + "gtuiexzsu aayxpmve zm zm zm drir scpgna xh azavwm uhzq" + "farlehdhq hkfoudzftq igju duszemmzl xnxhf ewle zm hrlipdm urvysbnykk kn" + "xnxhf jk jk agmckuiu duszemmzl jk zm zm jk vgsld" + "zm zm zm jk jk urvysbnykk ogttbykvt zm zm jk" + "iasrqgqv zm azavwm zidhxhbtv jk jk mjpavjuhw zm zm ajmvcydy" + "rgpzmlnmd tmt mjpavjuhw xh igju jk azavwm fibokdry vgsld ofm" + "zm jk vgsld jk xh jk csjqxhgj drir jk pmrb" + "xh jk jk zm rrkx duszemmzl mjpavjuhw xldlpy igju zm" + "jk hkfoudzftq zf rrkx wdmy jupk jk zm urvysbnykk npywgdvgz" + "zm jk zm zm zhbrzadb uenvbm aayxpmve urvysbnykk duszemmzl jk" + "uenvbm jk zm fxw xh bdilwmjw mjpavjuhw uv jk zm" + "nk jk bnhc pahlds jk igju dzadnqzprr jk jk jk" + "uhzq uv zm duszemmzl tlqix jk jk xh jk zm" + "jk zm agmckuiu urvysbnykk jk jk zm zm jk jk" + "azavwm mjpavjuhw lsgshn trqd xldlpy ogyavjvv agmckuiu ryvwwhlbc jk jk" + "tmt jk zk zm azavwm ofm acpgim bvgimjik iasrqgqv wuvajhwqz" + "igju ogyavjvv xrbdak rrkx fibokdry zf ujfhmrllq jk zm hxgwvib" + "zm pahlds jk uenvbm aayxpmve iaf hmjf xph vnlyvtkgx zm" + "jk xnxhf igju jk xh jk nvfasfh zm js jk" + "zm zm rwaj igju xr rrkx xnxhf nvfasfh skxbsqzvmt xatbxeqq" + "vgsld zm ujfhmrllq uhzq ogyavjvv nsab azavwm zm vgsld jmfiqhwnjg" + "ymjoym duszemmzl urvysbnykk azavwm jk jmfiqhwnjg bu qcdziqomqk vnlyvtkgx" + "zm nbilqcnz dzadnqzprr xh bkfgzsxn urvysbnykk xrujfzxqf zm zf agmckuiu" + "jk urvysbnykk nvfasfh zf xh zm zm qcdziqomqk qvxtclg wdmy" + "fibokdry jk urvysbnykk jk xr osff zm cvnnsl zm vgsld" + "jk mjpavjuhw hkfoudzftq jk zm xh xqf urvysbnykk jk iasrqgqv" + "jk csjqxhgj duszemmzl iasrqgqv aayxpmve zm brsuoqww jk qpmhtvl wluvgsw" + "jk mj azavwm jk zm jn dzadnqzprr zm jk uhzq" + "zk xqf jupk fxw nbilqcnz zm jk jcpiwj tznlvbfcv nvfasfh" + "jk jcpiwj zm xnxhf zm mjpavjuhw mj drir pa pvjrjlas" + "duszemmzl dzadnqzprr jk swc duszemmzl tmt jk jk pahlds jk" + "zk zm jk zm zm eczkjblu zm hi pmrb jk" + "azavwm zm iz agmckuiu jk sntk jk duszemmzl duszemmzl zm" + "jk zm jk eczkjblu urvysbnykk sk gnl jk ttvgf hmjf" + "jk bnhc jjrxpjkb mjpavjuhw fibokdry igju jk zm zm xh" + "wxe ogttbykvt uhzq xr iaf zf urvysbnykk aayxpmve oacaxgjoo mjpavjuhw" + "gazrt jk ephknonq myjp uenvbm wuvajhwqz jk zm xnxhf nvfasfh" + "zm aayxpmve csjqxhgj xnxhf xr jk aayxpmve xnxhf zm zm" + "sokcyf zm ogyavjvv jk zm fibokdry zm jk igju igju" + "vgsld bvgimjik xuprtlyle jk akmikrqyt jk aayxpmve hkfoudzftq ddjj ithtir" + "zm uhzq ovkyevlgv zk uenvbm csjqxhgj jk vgsld pgybs jk" + "zm agmckuiu zexh fibokdry jk uhzq bu tugflixoex xnxhf sk" + "zm zf uenvbm jk azavwm zm zm agmckuiu zm jk" + "rrkx jk zf jt zm oacaxgjoo fibokdry wdmy igju csjqxhgj" + "hi igju zm jk zidhxhbtv dzadnqzprr jk jk trqd duszemmzl" + "zm zm mjpavjuhw xrbdak qrvbjruc jk qzzqdxq guwq cvnnsl zm" + "ithtir jk jk qcdziqomqk zm farlehdhq zm zm xrbdak jk" + "ixfipk csjqxhgj azavwm sokcyf ttvgf vgsld jk sk xh zk" + "nvfasfh azavwm zm zm zm fxw nvfasfh zk gnl trqd" + "zm fibokdry csjqxhgj ofm dzadnqzprr jk akmikrqyt orpfawpx duszemmzl vwq" + "csjqxhgj jk jk vgsld urvysbnykk jk nxum jk jk nxum" + "zm hkfoudzftq jk ryvwwhlbc mjpavjuhw ephknonq jk zm ogyavjvv zm" + "lwa hi xnxhf qdyerbws zk njtc jk uhzq zm jk" + "trqd zm dzadnqzprr zm urvysbnykk jk lsz jk mjpavjuhw cmnnkna" + "duszemmzl zk jk jk fibokdry jseuhjnzo zm aayxpmve zk jk" + "fibokdry jk sviq qvxtclg wdmy jk doiwavhwwo zexh jk zm" + "jupk zm xh jk mjpavjuhw zm jk nsab npywgdvgz duszemmzl" + "zm igju zm zm nvfasfh eh hkfoudzftq fibokdry fxw xkblf" + "jk zm jk jk zm xh zk abthnzcv zf csjqxhgj" + "zm zm jk nkaotm urvysbnykk sbptoa bq jk ktxdty ubwrfqnbjf" + "nvfasfh aayxpmve xdcuz zm tugflixoex jcpiwj zm mjpavjuhw fibokdry doiwavhwwo" + "iaf jk mjpavjuhw zm duszemmzl jk jk uhzq pahlds fibokdry" + "ddjj zk azavwm jk swc zm gjtexkv jk xh jk" + "igju jk csjqxhgj zm jk dzadnqzprr duszemmzl ulvcbv jk jk" + "jk fibokdry zm csjqxhgj jn zm zm zm zf uhzq" + "duszemmzl jk xkblf zk hrlipdm aayxpmve uenvbm uhzq jk zf" + "dzadnqzprr jk zm zdu nvfasfh zm jk urvysbnykk hmjf jk" + "jk aayxpmve aserrdxm acpgim fibokdry jk drir wxe brsuoqww rrkx" + "uhzq csjqxhgj nvfasfh jk rrkx qbamok trqd uenvbm sntk zm" + "ps azavwm zkhdvkw jk zm jk jk zm csjqxhgj xedlrcfo" + "jk jk ogyavjvv jk zm farlehdhq duszemmzl jk agitgxamxe jk" + "qzzqdxq rwaj jk jk zm xqf jk uenvbm jk zk" + "zm hxgwvib akmikrqyt zf agmckuiu uenvbm bq npywgdvgz azavwm jk" + "zf jmfiqhwnjg js igju zm aayxpmve zm mbxnljomiv csjqxhgj nvfasfh" + "zm jk jk gazrt jk jk lkc jk nvfasfh jk" + "xldlpy orpfawpx zkhdvkw jk zm igju zm urvysbnykk dzadnqzprr mbxnljomiv" + "urvysbnykk jk zk igju zm uenvbm jk zm ithtir jk" + "zm zk zm zf ofm zm xdcuz dzadnqzprr zm vgsld" + "sbptoa jk tugflixoex jk zm zm vgsld zm xh zm" + "uhzq jk zk evvivo vgsld vniqnuynvf agmckuiu jk zm zm" + "zm nvfasfh zm zm zm abthnzcv uenvbm jk zk dzadnqzprr" + "zm azavwm igju qzzqdxq jk xnxhf abthnzcv jk nvfasfh zm" + "qbamok fxw vgsld igju cmnnkna xnxhf vniqnuynvf zk xh zm" + "nvfasfh zk zm mjpavjuhw dzadnqzprr jk jk duszemmzl xldlpy nvfasfh" + "xnxhf sviq nsab npywgdvgz osff vgsld farlehdhq fibokdry wjbkhzsa hhac" + "zm azavwm scpgna jk jk bq jk duszemmzl fibokdry ovkyevlgv" + "csjqxhgj zm jk jk duszemmzl zk xh zm jk zf" + "urvysbnykk dzadnqzprr csjqxhgj mjpavjuhw ubwrfqnbjf nkaotm jk jk zm drir" + "nvfasfh xh igju zm wluvgsw jk zm srwwnezqk ewle ovnq" + "jk nvfasfh eh ktxdty urvysbnykk vgsld zm jk eh uenvbm" + "orpfawpx pahlds jk uhzq hi zm zm zf jk dzadnqzprr" + "srwwnezqk csjqxhgj rbwzuf nvfasfh jcpiwj xldlpy nvfasfh jk vgsld wjybxmieki" +} + +proc add_empty_records {n} { + execsql BEGIN + for {set i 0} {$i < $n} {incr i} { + execsql { INSERT INTO t1 VALUES('') } + } + execsql COMMIT +} + + +#set e [list] +#foreach d $data {set e [concat $e $d]} +#puts [lsort -unique $e] +#exit + +set zero_long_doclists { + UPDATE t1_segments SET block=zeroblob(length(block)) WHERE length(block)>10000 +} + +foreach {tn setup} { + 1 { + set dmt_modes 0 + execsql { CREATE VIRTUAL TABLE t1 USING FTS3 } + foreach doc $data { execsql { INSERT INTO t1 VALUES($doc) } } + } + 2 { + set dmt_modes 0 + execsql { CREATE VIRTUAL TABLE t1 USING FTS4 } + foreach doc $data { execsql { INSERT INTO t1 VALUES($doc) } } + } + 3 { + set dmt_modes {0 1 2} + execsql { CREATE VIRTUAL TABLE t1 USING FTS4 } + foreach doc $data { execsql { INSERT INTO t1 VALUES($doc) } } + add_empty_records 1000 + execsql $zero_long_doclists + } + 4 { + set dmt_modes 0 + execsql { CREATE VIRTUAL TABLE t1 USING FTS4 } + foreach doc $data { execsql { INSERT INTO t1 VALUES($doc) } } + add_empty_records 1000 + execsql "INSERT INTO t1(t1) VALUES('optimize')" + execsql $zero_long_doclists + } + 5 { + set dmt_modes 0 + execsql { CREATE VIRTUAL TABLE t1 USING FTS4(matchinfo=fts3) } + foreach doc $data { execsql { INSERT INTO t1 VALUES($doc) } } + add_empty_records 1000 + execsql $zero_long_doclists + } +} { + + execsql { DROP TABLE IF EXISTS t1 } + eval $setup + set ::testprefix fts3defer-2.$tn + set DO_MALLOC_TEST 0 + + do_execsql_test 0 { + SELECT count(*) FROM t1_segments WHERE length(block)>10000 + } {2} + + do_select_test 1.1 { + SELECT rowid FROM t1 WHERE t1 MATCH 'jk xnxhf' + } {13 29 40 47 48 52 63 92} + do_select_test 1.2 { + SELECT rowid FROM t1 WHERE t1 MATCH 'jk eh' + } {100} + do_select_test 1.3 { + SELECT rowid FROM t1 WHERE t1 MATCH 'jk ubwrfqnbjf' + } {7 70 98} + do_select_test 1.4 { + SELECT rowid FROM t1 WHERE t1 MATCH 'duszemmzl jk' + } {3 5 8 10 13 18 20 23 32 37 41 43 55 60 65 67 72 74 76 81 94 96 97} + do_select_test 1.5 { + SELECT rowid FROM t1 WHERE t1 MATCH 'ubwrfqnbjf jk' + } {7 70 98} + do_select_test 1.6 { + SELECT rowid FROM t1 WHERE t1 MATCH 'jk ubwrfqnbjf jk jk jk jk' + } {7 70 98} + do_select_test 1.7 { + SELECT rowid FROM t1 WHERE t1 MATCH 'zm xnxhf' + } {12 13 29 30 40 47 48 52 63 92 93} + do_select_test 1.8 { + SELECT rowid FROM t1 WHERE t1 MATCH 'zm eh' + } {68 100} + do_select_test 1.9 { + SELECT rowid FROM t1 WHERE t1 MATCH 'zm ubwrfqnbjf' + } {7 70 98} + do_select_test 1.10 { + SELECT rowid FROM t1 WHERE t1 MATCH 'z* vgsld' + } {10 13 17 31 35 51 58 88 89 90 93 100} + + if { $fts3_simple_deferred_tokens_only==0 } { + do_select_test 1.11 { + SELECT rowid FROM t1 + WHERE t1 MATCH '( + zdu OR zexh OR zf OR zhbrzadb OR zidhxhbtv OR + zk OR zkhdvkw OR zm OR zsmhnf + ) vgsld' + } {10 13 17 31 35 51 58 88 89 90 93 100} + } + + do_select_test 2.1 { + SELECT rowid FROM t1 WHERE t1 MATCH '"zm agmckuiu"' + } {3 24 52 53} + do_select_test 2.2 { + SELECT rowid FROM t1 WHERE t1 MATCH '"zm zf"' + } {33 53 75 88 101} + do_select_test 2.3 { + SELECT rowid FROM t1 WHERE t1 MATCH '"zm aayxpmve"' + } {48 65 84} + do_select_test 2.4 { + SELECT rowid FROM t1 WHERE t1 MATCH '"aayxpmve zm"' + } {11 37 84} + do_select_test 2.5 { + SELECT rowid FROM t1 WHERE t1 MATCH '"jk azavwm"' + } {16 53} + do_select_test 2.6 { + SELECT rowid FROM t1 WHERE t1 MATCH '"xh jk jk"' + } {18} + do_select_test 2.7 { + SELECT rowid FROM t1 WHERE t1 MATCH '"zm jk vgsld"' + } {13 17} + do_select_test 2.8 { + SELECT rowid FROM t1 WHERE t1 MATCH '"zm jk vgsld lkjlkjlkj"' + } {} + + do_select_test 3.1 { + SELECT snippet(t1, '[', ']') FROM t1 WHERE t1 MATCH '"zm agmckuiu"' + } { + {zm [zm] [agmckuiu] uhzq nsab jk rrkx duszemmzl hyq jk} + {jk [zm] [agmckuiu] urvysbnykk jk jk zm zm jk jk} + {[zm] [agmckuiu] zexh fibokdry jk uhzq bu tugflixoex xnxhf sk} + {zm zf uenvbm jk azavwm zm [zm] [agmckuiu] zm jk} + } + + do_select_test 3.2 { + SELECT snippet(t1, '[', ']') FROM t1 WHERE t1 MATCH 'xnxhf jk' + } { + {[xnxhf] [jk] [jk] agmckuiu duszemmzl [jk] zm zm [jk] vgsld} + {[jk] [xnxhf] igju [jk] xh [jk] nvfasfh zm js [jk]} + {[jk] jcpiwj zm [xnxhf] zm mjpavjuhw mj drir pa pvjrjlas} + {gazrt [jk] ephknonq myjp uenvbm wuvajhwqz [jk] zm [xnxhf] nvfasfh} + {zm aayxpmve csjqxhgj [xnxhf] xr [jk] aayxpmve [xnxhf] zm zm} + {zm agmckuiu zexh fibokdry [jk] uhzq bu tugflixoex [xnxhf] sk} + {lwa hi [xnxhf] qdyerbws zk njtc [jk] uhzq zm [jk]} + {zm azavwm igju qzzqdxq [jk] [xnxhf] abthnzcv [jk] nvfasfh zm} + } + + do_select_test 4.1 { + SELECT offsets(t1) FROM t1 WHERE t1 MATCH '"jk uenvbm"' + } { + {0 0 10 2 0 1 13 6} {0 0 26 2 0 1 29 6} + } + + do_select_test 4.2 { + SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'duszemmzl jk fibokdry' + } { + {0 2 3 8 0 1 36 2 0 0 58 9} + {0 0 0 9 0 1 13 2 0 1 16 2 0 2 19 8 0 1 53 2} + {0 1 4 2 0 0 20 9 0 1 30 2 0 1 33 2 0 2 48 8} + {0 1 17 2 0 1 20 2 0 1 26 2 0 0 29 9 0 2 39 8} + } + + do_select_test 4.3 { + SELECT offsets(t1) FROM t1 + WHERE t1 MATCH 'vgsld (hrlipdm OR (aapmve NEAR duszemmzl))' + } {{0 0 0 5 0 1 15 7 0 0 36 5}} + + # The following block of tests runs normally with FTS3 or FTS4 without the + # long doclists zeroed. And with OOM-injection for FTS4 with long doclists + # zeroed. Change this by messing with the [set dmt_modes] commands above. + # + foreach DO_MALLOC_TEST $dmt_modes { + + # Phrase search. + # + do_select_test 5.$DO_MALLOC_TEST.1 { + SELECT rowid FROM t1 WHERE t1 MATCH '"jk mjpavjuhw"' + } {8 15 36 64 67 72} + + # Multiple tokens search. + do_select_test 5.$DO_MALLOC_TEST.2 { + SELECT rowid FROM t1 WHERE t1 MATCH 'duszemmzl zm' + } {3 5 8 10 12 13 18 20 23 37 43 55 60 65 67 72 74 81 94 96 97} + + # snippet() function with phrase. + do_select_test 5.$DO_MALLOC_TEST.3 { + SELECT snippet(t1, '[', ']') FROM t1 WHERE t1 MATCH '"zm aayxpmve"' + } { + {[zm] [aayxpmve] csjqxhgj xnxhf xr jk aayxpmve xnxhf zm zm} + {duszemmzl zk jk jk fibokdry jseuhjnzo [zm] [aayxpmve] zk jk} + {zf jmfiqhwnjg js igju [zm] [aayxpmve] zm mbxnljomiv csjqxhgj nvfasfh} + } + + # snippet() function with multiple tokens. + do_select_test 5.$DO_MALLOC_TEST.4 { + SELECT snippet(t1, '[', ']') FROM t1 WHERE t1 MATCH 'zm zhbrzadb' + } { + {[zm] jk [zm] [zm] [zhbrzadb] uenvbm aayxpmve urvysbnykk duszemmzl jk} + } + + # snippet() function with phrase. + do_select_test 5.$DO_MALLOC_TEST.5 { + SELECT offsets(t1) FROM t1 WHERE t1 MATCH '"zm aayxpmve"' + } { + {0 0 0 2 0 1 3 8} {0 0 38 2 0 1 41 8} {0 0 22 2 0 1 25 8} + } + + # snippet() function with multiple tokens. + do_select_test 5.$DO_MALLOC_TEST.6 { + SELECT offsets(t1) FROM t1 WHERE t1 MATCH 'zm zhbrzadb' + } { + {0 0 0 2 0 0 6 2 0 0 9 2 0 1 12 8} + } + + set DO_MALLOC_TEST 0 + } + + do_select_test 6.1 { + SELECT rowid FROM t1 + WHERE t1 MATCH 'vgsld (hrlipdm OR (aayxpmve duszemmzl))' + } {10} + do_select_test 6.2.1 { + SELECT rowid FROM t1 WHERE t1 MATCH '"jk xduvfhk"' + } {8} + do_select_test 6.2.2 { + SELECT rowid FROM t1 WHERE t1 MATCH '"zm azavwm"' + } {15 26 92 96} + if {$fts3_simple_deferred_tokens_only==0} { + do_select_test 6.2.3 { + SELECT rowid FROM t1 WHERE t1 MATCH '"jk xduvfhk" OR "zm azavwm"' + } {8 15 26 92 96} + } + + if {$tn>1} { + # These tests will not work with $tn==1, as in this case table t1 is + # created using FTS3. The ^ syntax is only available with FTS4 tables. + # + do_select_test 7.1 { + SELECT rowid FROM t1 WHERE t1 MATCH '^zm mjpavjuhw' + } {56 62} + do_select_test 7.2 { + SELECT rowid FROM t1 WHERE t1 MATCH '^azavwm zm' + } {43} + } +} + +set testprefix fts3defer + +do_execsql_test 3.1 { + CREATE VIRTUAL TABLE x1 USING fts4(a, b); + INSERT INTO x1 VALUES('a b c', 'd e f'); + INSERT INTO x1 SELECT * FROM x1; + INSERT INTO x1 SELECT * FROM x1; + INSERT INTO x1 SELECT * FROM x1; + INSERT INTO x1 SELECT * FROM x1; +} +do_execsql_test 3.2 " + INSERT INTO x1 VALUES( + '[string repeat {d } 3000]', '[string repeat {f } 30000]' + ); + INSERT INTO x1(x1) VALUES('optimize'); +" + +do_execsql_test 3.3 { + SELECT count(*) FROM x1 WHERE x1 MATCH '"d e f"' +} {16} + +# At one point the following was causing a floating-point exception. +# +do_execsql_test 4.1 { + CREATE VIRTUAL TABLE x2 USING FTS4(x); + BEGIN; + INSERT INTO x2 VALUES('m m m m m m m m m m m m m m m m m m m m m m m m m m'); + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 SELECT * FROM x2; + INSERT INTO x2 VALUES('a b c d e f g h i j k l m n o p q r s t u v w x y m'); + COMMIT; +} +do_execsql_test 4.2 { + SELECT * FROM x2 WHERE x2 MATCH 'a b c d e f g h i j k l m n o p q r s'; +} {{a b c d e f g h i j k l m n o p q r s t u v w x y m}} + +set tokenizers {1 simple} +ifcapable icu { lappend tokenizers 2 {icu en_US} } +foreach {tn tokenizer} $tokenizers { + do_execsql_test 5.$tn.1 " + CREATE VIRTUAL TABLE x3 USING FTS4(a, b, TOKENIZE $tokenizer) + " + do_execsql_test 5.$tn.2 { + BEGIN; + INSERT INTO x3 VALUES('b b b b b b b b b b b', 'b b b b b b b b b b b b b'); + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 SELECT * FROM x3; + INSERT INTO x3 VALUES('a b c', NULL); + INSERT INTO x3 VALUES('a x c', NULL); + COMMIT; + + SELECT * FROM x3 WHERE x3 MATCH 'a b'; + } {{a b c} {}} + + do_execsql_test 5.$tn.3 { DROP TABLE x3 } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3defer2.test b/components/external/SQLite-3.8.1/test/fts3defer2.test new file mode 100644 index 0000000000000000000000000000000000000000..608371f15d6275d855a280c9cef21177ce43c695 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3defer2.test @@ -0,0 +1,155 @@ +# 2010 October 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +ifcapable !fts3||!fts4_deferred { + finish_test + return +} + +set testprefix fts3defer2 + +proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r +} +db func mit mit + +#----------------------------------------------------------------------------- +# This block of tests - fts3defer2-1.* - test the interaction of deferred NEAR +# expressions and the snippet, offsets and matchinfo functions. +# +do_execsql_test 1.1.1 { + CREATE VIRTUAL TABLE t1 USING fts4; +} +do_execsql_test 1.1.2 "INSERT INTO t1 VALUES('[string repeat {a } 20000]')" +do_execsql_test 1.1.3 "INSERT INTO t1 VALUES('[string repeat {z } 20000]')" +do_execsql_test 1.1.4 { + INSERT INTO t1 VALUES('a b c d e f a x y'); + INSERT INTO t1 VALUES(''); + INSERT INTO t1 VALUES(''); + INSERT INTO t1 VALUES(''); + INSERT INTO t1 VALUES(''); + INSERT INTO t1 VALUES(''); + INSERT INTO t1(t1) VALUES('optimize'); +} +do_execsql_test 1.1.4 { + SELECT count(*) FROM t1_segments WHERE length(block)>10000; + UPDATE t1_segments SET block = zeroblob(length(block)) WHERE length(block)>10000; +} {2} + +do_execsql_test 1.2.0 { + SELECT content FROM t1 WHERE t1 MATCH 'f (e a)'; +} {{a b c d e f a x y}} + +do_execsql_test 1.2.1 { + SELECT content FROM t1 WHERE t1 MATCH 'f (e NEAR/2 a)'; +} {{a b c d e f a x y}} + +do_execsql_test 1.2.2 { + SELECT snippet(t1, '[', ']'), offsets(t1), mit(matchinfo(t1, 'pcxnal')) + FROM t1 WHERE t1 MATCH 'f (e NEAR/2 a)'; +} [list \ + {a b c d [e] [f] [a] x y} \ + {0 1 8 1 0 0 10 1 0 2 12 1} \ + [list 3 1 1 1 1 1 1 1 1 1 1 8 5001 9] +] + +do_execsql_test 1.2.3 { + SELECT snippet(t1, '[', ']'), offsets(t1), mit(matchinfo(t1, 'pcxnal')) + FROM t1 WHERE t1 MATCH 'f (e NEAR/3 a)'; +} [list \ + {[a] b c d [e] [f] [a] x y} \ + {0 2 0 1 0 1 8 1 0 0 10 1 0 2 12 1} \ + [list 3 1 1 1 1 1 1 1 2 2 1 8 5001 9] +] + +do_execsql_test 1.3.1 { DROP TABLE t1 } + +#----------------------------------------------------------------------------- +# Test cases fts3defer2-2.* focus specifically on the matchinfo function. +# +do_execsql_test 2.1.1 "CREATE VIRTUAL TABLE t2 USING fts4" +do_execsql_test 2.1.2 "INSERT INTO t2 VALUES('[string repeat {a } 10000]')" +do_execsql_test 2.1.3 "INSERT INTO t2 VALUES('b [string repeat {z } 10000]')" +do_execsql_test 2.1.4 [string repeat "INSERT INTO t2 VALUES('x');" 50] +do_execsql_test 2.1.5 { + INSERT INTO t2 VALUES('a b c d e f g z'); + INSERT INTO t2 VALUES('a b c d e f g'); +} +foreach {tn sql} { + 1 {} + 2 { INSERT INTO t2(t2) VALUES('optimize') } + 3 { UPDATE t2_segments SET block = zeroblob(length(block)) + WHERE length(block)>10000; + } +} { + execsql $sql + + do_execsql_test 2.2.$tn.1 { + SELECT mit(matchinfo(t2, 'pcxnal')) FROM t2 WHERE t2 MATCH 'a b'; + } [list \ + [list 2 1 1 54 54 1 3 3 54 372 8] \ + [list 2 1 1 54 54 1 3 3 54 372 7] \ + ] + + do_execsql_test 2.2.$tn.2 { + SELECT mit(matchinfo(t2, 'x')) FROM t2 WHERE t2 MATCH 'g z'; + } [list \ + [list 1 2 2 1 54 54] \ + ] + + set sqlite_fts3_enable_parentheses 1 + do_execsql_test 2.2.$tn.3 { + SELECT mit(matchinfo(t2, 'x')) FROM t2 WHERE t2 MATCH 'g OR (g z)'; + } [list \ + [list 1 2 2 1 2 2 1 54 54] \ + [list 1 2 2 1 2 2 0 54 54] \ + ] + set sqlite_fts3_enable_parentheses 0 +} + +do_execsql_test 2.3.1 { + CREATE VIRTUAL TABLE t3 USING fts4; + INSERT INTO t3 VALUES('a b c d e f'); + INSERT INTO t3 VALUES('x b c d e f'); + INSERT INTO t3 VALUES('d e f a b c'); + INSERT INTO t3 VALUES('b c d e f'); + INSERT INTO t3 VALUES(''); + INSERT INTO t3 VALUES(''); + INSERT INTO t3 VALUES(''); + INSERT INTO t3 VALUES(''); + INSERT INTO t3 VALUES(''); + INSERT INTO t3 VALUES(''); +} +do_execsql_test 2.3.2 " + INSERT INTO t3 VALUES('f e d c b [string repeat {a } 10000]') +" +foreach {tn sql} { + 1 {} + 2 { INSERT INTO t3(t3) VALUES('optimize') } + 3 { UPDATE t3_segments SET block = zeroblob(length(block)) + WHERE length(block)>10000; + } +} { + execsql $sql + do_execsql_test 2.4.$tn { + SELECT docid, mit(matchinfo(t3, 'pcxnal')) FROM t3 WHERE t3 MATCH '"a b c"'; + } {1 {1 1 1 4 4 11 912 6} 3 {1 1 1 4 4 11 912 6}} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3defer3.test b/components/external/SQLite-3.8.1/test/fts3defer3.test new file mode 100644 index 0000000000000000000000000000000000000000..a795e92bcf1ab8fcde102113258920c289a9e10c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3defer3.test @@ -0,0 +1,84 @@ +# 2010 October 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains a very simple test to show that the deferred tokens +# optimization is doing something. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +ifcapable !fts3||!fts4_deferred { + finish_test + return +} +set testprefix fts3defer3 + +set nDoclist 3204 +set nDoc 800 + +# Set up a database that contains 800 rows. Each row contains the document +# "b b", except for the row with docid=200, which contains "a b". Hence +# token "b" is extremely common and token "a" is not. +# +do_test 1.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts4; + BEGIN; + } + for {set i 1} {$i <= $nDoc} {incr i} { + set document "b b" + if {$i==200} { set document "a b" } + execsql { INSERT INTO t1 (docid, content) VALUES($i, $document) } + } + execsql COMMIT +} {} + +# Check that the db contains two doclists. A small one for "a" and a +# larger one for "b". +# +do_execsql_test 1.2 { + SELECT blockid, length(block) FROM t1_segments; +} [list 1 8 2 $nDoclist] + +# Query for 'a b'. Although this test doesn't prove so, token "b" will +# be deferred because of the very large associated doclist. +# +do_execsql_test 1.3 { + SELECT docid, content FROM t1 WHERE t1 MATCH 'a b'; +} {200 {a b}} + +# Zero out the doclist for token "b" within the database file. Now the +# only queries that use token "b" that will work are those that defer +# it. Any query that tries to use the doclist belonging to token "b" +# will fail. +# +do_test 1.4 { + set fd [db incrblob t1_segments block 2] + puts -nonewline $fd [string repeat "\00" $nDoclist] + close $fd +} {} + +# The first two queries succeed, as they defer token "b". The last one +# fails, as it tries to load the corrupt doclist. +# +do_execsql_test 1.5 { + SELECT docid, content FROM t1 WHERE t1 MATCH 'a b'; +} {200 {a b}} +do_execsql_test 1.6 { + SELECT count(*) FROM t1 WHERE t1 MATCH 'a b'; +} {1} +do_catchsql_test 1.7 { + SELECT count(*) FROM t1 WHERE t1 MATCH 'b'; +} {1 {database disk image is malformed}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3drop.test b/components/external/SQLite-3.8.1/test/fts3drop.test new file mode 100644 index 0000000000000000000000000000000000000000..8b76eafec01b2170e8817c8a5fb579ce0472f194 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3drop.test @@ -0,0 +1,61 @@ +# 2011 October 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. More specifically, +# that DROP TABLE commands can co-exist with savepoints inside transactions. +# See ticket [48f299634a] for details. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix fts3drop + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +do_execsql_test 1.1 { + CREATE VIRTUAL TABLE f1 USING fts3; + INSERT INTO f1 VALUES('a b c'); +} + +do_execsql_test 1.2 { + BEGIN; + INSERT INTO f1 VALUES('d e f'); + SAVEPOINT one; + INSERT INTO f1 VALUES('g h i'); + DROP TABLE f1; + ROLLBACK TO one; + COMMIT; +} + +do_execsql_test 1.3 { + SELECT * FROM f1; +} {{a b c} {d e f}} + +do_execsql_test 1.4 { + BEGIN; + INSERT INTO f1 VALUES('g h i'); + SAVEPOINT one; + INSERT INTO f1 VALUES('j k l'); + DROP TABLE f1; + RELEASE one; + ROLLBACK; +} + +do_execsql_test 1.5 { + SELECT * FROM f1; +} {{a b c} {d e f}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3e.test b/components/external/SQLite-3.8.1/test/fts3e.test new file mode 100644 index 0000000000000000000000000000000000000000..03caaf85f23686db63c5aafa554c5ffbf73c69db --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3e.test @@ -0,0 +1,125 @@ +# 2008 July 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# These tests exercise the various types of fts3 cursors. +# +# $Id: fts3e.test,v 1.1 2008/07/29 20:24:46 shess Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +#************************************************************************* +# Test table scan (QUERY_GENERIC). This kind of query happens for +# queries with no WHERE clause, or for WHERE clauses which cannot be +# satisfied by an index. +db eval { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts3(c); + INSERT INTO t1 (docid, c) VALUES (1, 'This is a test'); + INSERT INTO t1 (docid, c) VALUES (2, 'That was a test'); + INSERT INTO t1 (docid, c) VALUES (3, 'This is a test'); +} + +do_test fts3e-1.1 { + execsql { + SELECT docid FROM t1 ORDER BY docid; + } +} {1 2 3} + +do_test fts3e-1.2 { + execsql { + SELECT docid FROM t1 WHERE c LIKE '%test' ORDER BY docid; + } +} {1 2 3} + +do_test fts3e-1.3 { + execsql { + SELECT docid FROM t1 WHERE c LIKE 'That%' ORDER BY docid; + } +} {2} + +#************************************************************************* +# Test lookup by docid (QUERY_DOCID). This kind of query happens for +# queries which select by the docid/rowid implicit index. +db eval { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE VIRTUAL TABLE t1 USING fts3(c); + CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, weight INTEGER UNIQUE); + INSERT INTO t2 VALUES (null, 10); + INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'This is a test'); + INSERT INTO t2 VALUES (null, 5); + INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'That was a test'); + INSERT INTO t2 VALUES (null, 20); + INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'This is a test'); +} + +# TODO(shess): This actually is doing QUERY_GENERIC? I'd have +# expected QUERY_DOCID in this case, as for a very large table the +# full scan is less efficient. +do_test fts3e-2.1 { + execsql { + SELECT docid FROM t1 WHERE docid in (1, 2, 10); + SELECT rowid FROM t1 WHERE rowid in (1, 2, 10); + } +} {1 2 1 2} + +do_test fts3e-2.2 { + execsql { + SELECT docid, weight FROM t1, t2 WHERE t2.id = t1.docid ORDER BY weight; + SELECT t1.rowid, weight FROM t1, t2 WHERE t2.id = t1.rowid ORDER BY weight; + } +} {2 5 1 10 3 20 2 5 1 10 3 20} + +do_test fts3e-2.3 { + execsql { + SELECT docid, weight FROM t1, t2 + WHERE t2.weight>5 AND t2.id = t1.docid ORDER BY weight; + SELECT t1.rowid, weight FROM t1, t2 + WHERE t2.weight>5 AND t2.id = t1.rowid ORDER BY weight; + } +} {1 10 3 20 1 10 3 20} + +#************************************************************************* +# Test lookup by MATCH (QUERY_FULLTEXT). This is the fulltext index. +db eval { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE VIRTUAL TABLE t1 USING fts3(c); + CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, weight INTEGER UNIQUE); + INSERT INTO t2 VALUES (null, 10); + INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'This is a test'); + INSERT INTO t2 VALUES (null, 5); + INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'That was a test'); + INSERT INTO t2 VALUES (null, 20); + INSERT INTO t1 (docid, c) VALUES (last_insert_rowid(), 'This is a test'); +} + +do_test fts3e-3.1 { + execsql { + SELECT docid FROM t1 WHERE t1 MATCH 'this' ORDER BY docid; + } +} {1 3} + +do_test fts3e-3.2 { + execsql { + SELECT docid, weight FROM t1, t2 + WHERE t1 MATCH 'this' AND t1.docid = t2.id ORDER BY weight; + } +} {1 10 3 20} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3expr.test b/components/external/SQLite-3.8.1/test/fts3expr.test new file mode 100644 index 0000000000000000000000000000000000000000..e7c4f65598acfafb6cf1b4d1f59225e7d35c2ebd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3expr.test @@ -0,0 +1,499 @@ +# 2006 September 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# +# $Id: fts3expr.test,v 1.9 2009/07/28 16:44:26 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +set sqlite_fts3_enable_parentheses 1 + +proc test_fts3expr {expr} { + db one {SELECT fts3_exprtest('simple', $expr, 'a', 'b', 'c')} +} +do_test fts3expr-1.0 { + test_fts3expr "abcd" +} {PHRASE 3 0 abcd} +do_test fts3expr-1.1 { + test_fts3expr " tag " +} {PHRASE 3 0 tag} + +do_test fts3expr-1.2 { + test_fts3expr "ab AND cd" +} {AND {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.2.1 { + test_fts3expr "ab cd" +} {AND {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.3 { + test_fts3expr "ab OR cd" +} {OR {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.4 { + test_fts3expr "ab NOT cd" +} {NOT {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.5 { + test_fts3expr "ab NEAR cd" +} {NEAR/10 {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.6.1 { + test_fts3expr "ab NEAR/5 cd" +} {NEAR/5 {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.6.2 { + test_fts3expr "ab NEAR/87654321 cd" +} {NEAR/87654321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.6.3 { + test_fts3expr "ab NEAR/7654321 cd" +} {NEAR/7654321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.6.4 { + test_fts3expr "ab NEAR/654321 cd" +} {NEAR/654321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.6.5 { + test_fts3expr "ab NEAR/54321 cd" +} {NEAR/54321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.6.6 { + test_fts3expr "ab NEAR/4321 cd" +} {NEAR/4321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.6.7 { + test_fts3expr "ab NEAR/321 cd" +} {NEAR/321 {PHRASE 3 0 ab} {PHRASE 3 0 cd}} +do_test fts3expr-1.6.8 { + test_fts3expr "ab NEAR/21 cd" +} {NEAR/21 {PHRASE 3 0 ab} {PHRASE 3 0 cd}} + +do_test fts3expr-1.7 { + test_fts3expr {"one two three"} +} {PHRASE 3 0 one two three} +do_test fts3expr-1.8.1 { + test_fts3expr {zero "one two three" four} +} {AND {AND {PHRASE 3 0 zero} {PHRASE 3 0 one two three}} {PHRASE 3 0 four}} +do_test fts3expr-1.8.2 { + test_fts3expr {zero AND "one two three" four} +} {AND {AND {PHRASE 3 0 zero} {PHRASE 3 0 one two three}} {PHRASE 3 0 four}} +do_test fts3expr-1.8.3 { + test_fts3expr {zero "one two three" AND four} +} {AND {AND {PHRASE 3 0 zero} {PHRASE 3 0 one two three}} {PHRASE 3 0 four}} +do_test fts3expr-1.8.4 { + test_fts3expr {zero AND "one two three" AND four} +} {AND {AND {PHRASE 3 0 zero} {PHRASE 3 0 one two three}} {PHRASE 3 0 four}} +do_test fts3expr-1.9.1 { + test_fts3expr {"one* two three"} +} {PHRASE 3 0 one+ two three} +do_test fts3expr-1.9.2 { + test_fts3expr {"one two* three"} +} {PHRASE 3 0 one two+ three} +do_test fts3expr-1.9.3 { + test_fts3expr {"one* two* three"} +} {PHRASE 3 0 one+ two+ three} +do_test fts3expr-1.9.4 { + test_fts3expr {"one two three*"} +} {PHRASE 3 0 one two three+} +do_test fts3expr-1.9.5 { + test_fts3expr {"one* two three*"} +} {PHRASE 3 0 one+ two three+} +do_test fts3expr-1.9.6 { + test_fts3expr {"one two* three*"} +} {PHRASE 3 0 one two+ three+} +do_test fts3expr-1.9.7 { + test_fts3expr {"one* two* three*"} +} {PHRASE 3 0 one+ two+ three+} + +do_test fts3expr-1.10 { + test_fts3expr {one* two} +} {AND {PHRASE 3 0 one+} {PHRASE 3 0 two}} +do_test fts3expr-1.11 { + test_fts3expr {one two*} +} {AND {PHRASE 3 0 one} {PHRASE 3 0 two+}} + +do_test fts3expr-1.14 { + test_fts3expr {a:one two} +} {AND {PHRASE 0 0 one} {PHRASE 3 0 two}} +do_test fts3expr-1.15.1 { + test_fts3expr {one b:two} +} {AND {PHRASE 3 0 one} {PHRASE 1 0 two}} +do_test fts3expr-1.15.2 { + test_fts3expr {one B:two} +} {AND {PHRASE 3 0 one} {PHRASE 1 0 two}} + +do_test fts3expr-1.16 { + test_fts3expr {one AND two AND three AND four AND five} +} [list AND \ + [list AND \ + [list AND \ + [list AND {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + {PHRASE 3 0 three} \ + ] \ + {PHRASE 3 0 four} \ + ] \ + {PHRASE 3 0 five} \ + ] +do_test fts3expr-1.17 { + test_fts3expr {(one AND two) AND ((three AND four) AND five)} +} [list AND \ + [list AND {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + [list AND \ + [list AND {PHRASE 3 0 three} {PHRASE 3 0 four}] \ + {PHRASE 3 0 five} \ + ] \ + ] +do_test fts3expr-1.18 { + test_fts3expr {(one AND two) OR ((three AND four) AND five)} +} [list OR \ + [list AND {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + [list AND \ + [list AND {PHRASE 3 0 three} {PHRASE 3 0 four}] \ + {PHRASE 3 0 five} \ + ] \ + ] +do_test fts3expr-1.19 { + test_fts3expr {(one AND two) AND ((three AND four) OR five)} +} [list AND \ + [list AND {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + [list OR \ + [list AND {PHRASE 3 0 three} {PHRASE 3 0 four}] \ + {PHRASE 3 0 five} \ + ] \ + ] +do_test fts3expr-1.20 { + test_fts3expr {(one OR two) AND ((three OR four) AND five)} +} [list AND \ + [list OR {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + [list AND \ + [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \ + {PHRASE 3 0 five} \ + ] \ + ] +do_test fts3expr-1.21 { + test_fts3expr {(one OR two) AND ((three NOT four) AND five)} +} [list AND \ + [list OR {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + [list AND \ + [list NOT {PHRASE 3 0 three} {PHRASE 3 0 four}] \ + {PHRASE 3 0 five} \ + ] \ + ] +do_test fts3expr-1.22 { + test_fts3expr {(one OR two) NOT ((three OR four) AND five)} +} [list NOT \ + [list OR {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + [list AND \ + [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \ + {PHRASE 3 0 five} \ + ] \ + ] +do_test fts3expr-1.23 { + test_fts3expr {(((((one OR two))))) NOT (((((three OR four))) AND five))} +} [list NOT \ + [list OR {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + [list AND \ + [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \ + {PHRASE 3 0 five} \ + ] \ + ] +do_test fts3expr-1.24 { + test_fts3expr {one NEAR two} +} [list NEAR/10 {PHRASE 3 0 one} {PHRASE 3 0 two}] +do_test fts3expr-1.25 { + test_fts3expr {(one NEAR two)} +} [list NEAR/10 {PHRASE 3 0 one} {PHRASE 3 0 two}] +do_test fts3expr-1.26 { + test_fts3expr {((((((one NEAR two))))))} +} [list NEAR/10 {PHRASE 3 0 one} {PHRASE 3 0 two}] +do_test fts3expr-1.27 { + test_fts3expr {(one NEAR two) OR ((three OR four) AND five)} +} [list OR \ + [list NEAR/10 {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + [list AND \ + [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \ + {PHRASE 3 0 five} \ + ] \ + ] +do_test fts3expr-1.28 { + test_fts3expr {(one NEAR/321 two) OR ((three OR four) AND five)} +} [list OR \ + [list NEAR/321 {PHRASE 3 0 one} {PHRASE 3 0 two}] \ + [list AND \ + [list OR {PHRASE 3 0 three} {PHRASE 3 0 four}] \ + {PHRASE 3 0 five} \ + ] \ + ] + +proc strip_phrase_data {L} { + if {[lindex $L 0] eq "PHRASE"} { + return [lrange $L 3 end] + } + return [list \ + [lindex $L 0] \ + [strip_phrase_data [lindex $L 1]] \ + [strip_phrase_data [lindex $L 2]] \ + ] +} +proc test_fts3expr2 {expr} { + strip_phrase_data [ + db one {SELECT fts3_exprtest('simple', $expr, 'a', 'b', 'c')} + ] +} +do_test fts3expr-2.1 { + test_fts3expr2 "ab OR cd AND ef" +} {OR ab {AND cd ef}} +do_test fts3expr-2.2 { + test_fts3expr2 "cd AND ef OR ab" +} {OR {AND cd ef} ab} +do_test fts3expr-2.3 { + test_fts3expr2 "ab AND cd AND ef OR gh" +} {OR {AND {AND ab cd} ef} gh} +do_test fts3expr-2.4 { + test_fts3expr2 "ab AND cd OR ef AND gh" +} {OR {AND ab cd} {AND ef gh}} +do_test fts3expr-2.5 { + test_fts3expr2 "ab cd" +} {AND ab cd} + +do_test fts3expr-3.1 { + test_fts3expr2 "(ab OR cd) AND ef" +} {AND {OR ab cd} ef} +do_test fts3expr-3.2 { + test_fts3expr2 "ef AND (ab OR cd)" +} {AND ef {OR ab cd}} +do_test fts3expr-3.3 { + test_fts3expr2 "(ab OR cd)" +} {OR ab cd} +do_test fts3expr-3.4 { + test_fts3expr2 "(((ab OR cd)))" +} {OR ab cd} + +do_test fts3expr-3.5 { + test_fts3expr2 "one AND (two NEAR three)" +} {AND one {NEAR/10 two three}} +do_test fts3expr-3.6 { + test_fts3expr2 "one (two NEAR three)" +} {AND one {NEAR/10 two three}} +do_test fts3expr-3.7 { + test_fts3expr2 "(two NEAR three) one" +} {AND {NEAR/10 two three} one} +do_test fts3expr-3.8 { + test_fts3expr2 "(two NEAR three) AND one" +} {AND {NEAR/10 two three} one} +do_test fts3expr-3.9 { + test_fts3expr2 "(two NEAR three) (four five)" +} {AND {NEAR/10 two three} {AND four five}} +do_test fts3expr-3.10 { + test_fts3expr2 "(two NEAR three) AND (four five)" +} {AND {NEAR/10 two three} {AND four five}} +do_test fts3expr-3.11 { + test_fts3expr2 "(two NEAR three) (four NEAR five)" +} {AND {NEAR/10 two three} {NEAR/10 four five}} +do_test fts3expr-3.12 { + test_fts3expr2 "(two NEAR three) OR (four NEAR five)" +} {OR {NEAR/10 two three} {NEAR/10 four five}} + +do_test fts3expr-3.13 { + test_fts3expr2 "(two NEAR/1a three)" +} {AND {AND {AND two near} 1a} three} + +do_test fts3expr-3.14 { + test_fts3expr2 "(two NEAR// three)" +} {AND {AND two near} three} +do_test fts3expr-3.15 { + test_fts3expr2 "(two NEAR/: three)" +} {AND {AND two near} three} + +do_test fts3expr-3.16 { + test_fts3expr2 "(two NEAR three)OR(four NEAR five)" +} {OR {NEAR/10 two three} {NEAR/10 four five}} +do_test fts3expr-3.17 { + test_fts3expr2 "(two NEAR three)OR\"four five\"" +} {OR {NEAR/10 two three} {four five}} +do_test fts3expr-3.18 { + test_fts3expr2 "one \u0080wo" +} "AND one \u0080wo" + + + +#------------------------------------------------------------------------ +# The following tests, fts3expr-4.*, test the parsers response to syntax +# errors in query expressions. This is done using a real fts3 table and +# MATCH clauses, not the parser test interface. +# +do_test fts3expr-4.1 { + execsql { CREATE VIRTUAL TABLE t1 USING fts3(a, b, c) } +} {} + +# Mismatched parenthesis: +do_test fts3expr-4.2.1 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example AND (hello OR world))' } +} {1 {malformed MATCH expression: [example AND (hello OR world))]}} +do_test fts3expr-4.2.2 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example AND (hello OR world' } +} {1 {malformed MATCH expression: [example AND (hello OR world]}} +do_test fts3expr-4.2.3 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH '(hello' } +} {1 {malformed MATCH expression: [(hello]}} +do_test fts3expr-4.2.4 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH '(' } +} {1 {malformed MATCH expression: [(]}} +do_test fts3expr-4.2.5 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH ')' } +} {1 {malformed MATCH expression: [)]}} + +do_test fts3expr-4.2.6 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example (hello world' } +} {1 {malformed MATCH expression: [example (hello world]}} + +# Unterminated quotation marks: +do_test fts3expr-4.3.1 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example OR "hello world' } +} {1 {malformed MATCH expression: [example OR "hello world]}} +do_test fts3expr-4.3.2 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'example OR hello world"' } +} {1 {malformed MATCH expression: [example OR hello world"]}} + +# Binary operators without the required operands. +do_test fts3expr-4.4.1 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'OR hello world' } +} {1 {malformed MATCH expression: [OR hello world]}} +do_test fts3expr-4.4.2 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'hello world OR' } +} {1 {malformed MATCH expression: [hello world OR]}} +do_test fts3expr-4.4.3 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'one (hello world OR) two' } +} {1 {malformed MATCH expression: [one (hello world OR) two]}} +do_test fts3expr-4.4.4 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'one (OR hello world) two' } +} {1 {malformed MATCH expression: [one (OR hello world) two]}} + +# NEAR operators with something other than phrases as arguments. +do_test fts3expr-4.5.1 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH '(hello OR world) NEAR one' } +} {1 {malformed MATCH expression: [(hello OR world) NEAR one]}} +do_test fts3expr-4.5.2 { + catchsql { SELECT * FROM t1 WHERE t1 MATCH 'one NEAR (hello OR world)' } +} {1 {malformed MATCH expression: [one NEAR (hello OR world)]}} + +#------------------------------------------------------------------------ +# The following OOM tests are designed to cover cases in fts3_expr.c. +# +source $testdir/malloc_common.tcl +do_malloc_test fts3expr-malloc-1 -sqlbody { + SELECT fts3_exprtest('simple', 'a b c "d e f"', 'a', 'b', 'c') +} +do_malloc_test fts3expr-malloc-2 -tclprep { + set sqlite_fts3_enable_parentheses 0 +} -sqlbody { + SELECT fts3_exprtest('simple', 'a -b', 'a', 'b', 'c') +} -cleanup { + set sqlite_fts3_enable_parentheses 1 +} + +#------------------------------------------------------------------------ +# The following tests are not very important. They cover error handling +# cases in the test code, which makes test coverage easier to measure. +# +do_test fts3expr-5.1 { + catchsql { SELECT fts3_exprtest('simple', 'a b') } +} {1 {Usage: fts3_exprtest(tokenizer, expr, col1, ...}} +do_test fts3expr-5.2 { + catchsql { SELECT fts3_exprtest('doesnotexist', 'a b', 'c') } +} {1 {No such tokenizer module}} +do_test fts3expr-5.3 { + catchsql { SELECT fts3_exprtest('simple', 'a b OR', 'c') } +} {1 {Error parsing expression}} + +#------------------------------------------------------------------------ +# The next set of tests verifies that things actually work as they are +# supposed to when using the new syntax. +# +do_test fts3expr-6.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts3(a); + } + for {set ii 1} {$ii < 32} {incr ii} { + set v [list] + if {$ii & 1} { lappend v one } + if {$ii & 2} { lappend v two } + if {$ii & 4} { lappend v three } + if {$ii & 8} { lappend v four } + if {$ii & 16} { lappend v five } + execsql { INSERT INTO t1 VALUES($v) } + } + + execsql {SELECT rowid FROM t1 WHERE t1 MATCH 'five four one' ORDER BY rowid} +} {25 27 29 31} + +foreach {id expr res} { + + 2 "five four NOT one" {24 26 28 30} + + 3 "five AND four OR one" + {1 3 5 7 9 11 13 15 17 19 21 23 24 25 26 27 28 29 30 31} + + 4 "five AND (four OR one)" {17 19 21 23 24 25 26 27 28 29 30 31} + + 5 "five NOT (four OR one)" {16 18 20 22} + + 6 "(five NOT (four OR one)) OR (five AND (four OR one))" + {16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31} + + 7 "(five OR one) AND two AND three" {7 15 22 23 30 31} + + 8 "five OR one AND two AND three" + {7 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31} + + 9 "five OR one two three" + {7 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31} + + 10 "five OR \"one two three\"" + {7 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31} + + 11 "one two OR four five NOT three" {3 7 11 15 19 23 24 25 26 27 31} + + 12 "(one two OR four five) NOT three" {3 11 19 24 25 26 27} + + 13 "((((((one two OR four five)))))) NOT three" {3 11 19 24 25 26 27} + +} { + do_test fts3expr-6.1.$id { + execsql { SELECT rowid FROM t1 WHERE t1 MATCH $expr ORDER BY rowid } + } $res +} + +set sqlite_fts3_enable_parentheses 0 +foreach {id expr res} { + 1 "one -two three" {5 13 21 29} + 2 "-two one three" {5 13 21 29} + 3 "one three -two" {5 13 21 29} + 4 "-one -two three" {4 12 20 28} + 5 "three -one -two" {4 12 20 28} + 6 "-one three -two" {4 12 20 28} +} { + do_test fts3expr-6.2.$id { + execsql { SELECT rowid FROM t1 WHERE t1 MATCH $expr ORDER BY rowid } + } $res +} +set sqlite_fts3_enable_parentheses 1 + +do_test fts3expr-7.1 { + execsql { + CREATE VIRTUAL TABLE test USING fts3 (keyword); + INSERT INTO test VALUES ('abc'); + SELECT * FROM test WHERE keyword MATCH '""'; + } +} {} + + +set sqlite_fts3_enable_parentheses 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3expr2.test b/components/external/SQLite-3.8.1/test/fts3expr2.test new file mode 100644 index 0000000000000000000000000000000000000000..c3d161730b47f9c0e9e11263555d2d6090ed4e62 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3expr2.test @@ -0,0 +1,166 @@ +# 2009 January 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module syntax parser. +# +# $Id: fts3expr2.test,v 1.2 2009/06/05 17:09:12 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Test overview: +# +# The tests in this file are pseudo-randomly generated. They test +# the fts3 match expression parser via the test interface +# SQL function "fts3_exprtest" (see comments in fts3_expr.c). +# +# Each test case works as follows: +# +# 1. A random expression tree is generated using proc [random_expr_tree]. +# 2. The expression tree is converted to the text of an equivalent +# fts3 expression using proc [tree_to_expr]. +# 3. The test SQL function "fts3_exprtest" is used to parse the +# expression text generated in step (2), returning a parsed expression +# tree. +# 4. Test that the tree returned in step (3) matches that generated in +# step (1). +# +# In step (2), 4 different fts3 expressions are created from each +# expression tree by varying the following boolean properties: +# +# * Whether or not superflous parenthesis are included. i.e. if +# "a OR b AND (c OR d)" or "a OR (b AND (c OR d))" is generated. +# +# * Whether or not explict AND operators are used. i.e. if +# "a OR b AND c" or "a OR b c" is generated. +# + +set sqlite_fts3_enable_parentheses 1 + +proc strip_phrase_data {L} { + if {[lindex $L 0] eq "PHRASE"} { + return [list P [lrange $L 3 end]] + } + return [list \ + [lindex $L 0] \ + [strip_phrase_data [lindex $L 1]] \ + [strip_phrase_data [lindex $L 2]] \ + ] +} +proc test_fts3expr2 {expr} { + strip_phrase_data [ + db one {SELECT fts3_exprtest('simple', $expr, 'a', 'b', 'c')} + ] +} + +proc rnd {nMax} { expr {int(rand()*$nMax)} } + +proc random_phrase {} { + set phrases [list one two three four "one two" "three four"] + list P [lindex $phrases [rnd [llength $phrases]]] +} + +# Generate and return a pseudo-random expression tree. Using the same +# format returned by the [test_fts3expr2] proc. +# +proc random_expr_tree {iHeight} { + if {$iHeight==0 || [rnd 3]==0} { + return [random_phrase] + } + + set operators [list NEAR NOT AND OR] + set op [lindex $operators [rnd 4]] + + if {$op eq "NEAR"} { + set iDistance [rnd 15] + return [list $op/$iDistance [random_phrase] [random_phrase]] + } + + set iNH [expr {$iHeight - 1}] + return [list $op [random_expr_tree $iNH] [random_expr_tree $iNH]] +} + +# Given an expression tree, generate a corresponding expression. +# +proc tree_to_expr {tree all_brackets implicit_and} { + set prec(NOT) 2 + set prec(AND) 3 + set prec() 3 + set prec(OR) 4 + + set op [lindex $tree 0] + + if {$op eq "P"} { + set phrase [lindex $tree 1] + if {[llength $phrase]>1} { + return "\"$phrase\"" + } else { + return $phrase + } + } + + if {$op eq "NEAR/10"} { + set op "NEAR" + } + if {$op eq "AND" && $implicit_and} { + set op "" + } + + set lhs [lindex $tree 1] + set rhs [lindex $tree 2] + set zLeft [tree_to_expr $lhs $all_brackets $implicit_and] + set zRight [tree_to_expr $rhs $all_brackets $implicit_and] + + set iPrec 5 + set iLeftPrec 0 + set iRightPrec 0 + + catch {set iPrec $prec($op)} + catch {set iLeftPrec $prec([lindex $lhs 0])} + catch {set iRightPrec $prec([lindex $rhs 0])} + + if {$iLeftPrec > $iPrec || $all_brackets} { + set zLeft "($zLeft)" + } + if {$iRightPrec >= $iPrec || $all_brackets} { + set zRight "($zRight)" + } + + return "$zLeft $op $zRight" +} + +proc do_exprparse_test {name expr tree} { + uplevel do_test $name [list "test_fts3expr2 {$expr}"] [list $tree] +} + +for {set iTest 1} {$iTest<500} {incr iTest} { + set t [random_expr_tree 4] + + set e1 [tree_to_expr $t 0 0] + set e2 [tree_to_expr $t 0 1] + set e3 [tree_to_expr $t 1 0] + set e4 [tree_to_expr $t 1 1] + + do_exprparse_test fts3expr2-$iTest.1 $e1 $t + do_exprparse_test fts3expr2-$iTest.2 $e2 $t + do_exprparse_test fts3expr2-$iTest.3 $e3 $t + do_exprparse_test fts3expr2-$iTest.4 $e4 $t +} + +set sqlite_fts3_enable_parentheses 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3expr3.test b/components/external/SQLite-3.8.1/test/fts3expr3.test new file mode 100644 index 0000000000000000000000000000000000000000..a8d7319266afed1269af26dbdaa3b7aadeda27d1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3expr3.test @@ -0,0 +1,206 @@ +# 2009 January 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the part of the FTS3 expression +# parser that rebalances large expressions. +# +# $Id: fts3expr2.test,v 1.2 2009/06/05 17:09:12 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +set ::testprefix fts3expr3 + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +set sqlite_fts3_enable_parentheses 1 + +proc strip_phrase_data {L} { + if {[lindex $L 0] eq "PHRASE"} { + return [list P [lrange $L 3 end]] + } + return [list \ + [lindex $L 0] \ + [strip_phrase_data [lindex $L 1]] \ + [strip_phrase_data [lindex $L 2]] \ + ] +} +proc test_fts3expr2 {expr} { + strip_phrase_data [ + db one {SELECT fts3_exprtest_rebalance('simple', $expr, 'a', 'b', 'c')} + ] +} + +proc balanced_exprtree_structure {nEntry} { + set L [list] + for {set i 1} {$i <= $nEntry} {incr i} { + lappend L xxx + } + while {[llength $L] > 1} { + set N [list] + if {[llength $L] % 2} { + foreach {a b} [lrange $L 0 end-1] { lappend N [list AND $a $b] } + lappend N [lindex $L end] + } else { + foreach {a b} $L { lappend N [list AND $a $b] } + } + set L $N + } + return [lindex $L 0] +} + +proc balanced_and_tree {nEntry} { + set query [balanced_exprtree_structure $nEntry] + if {$query == "xxx"} { + return "P 1" + } + for {set i 1} {$i <= $nEntry} {incr i} { + regsub xxx $query "{P $i}" query + } + return $query +} + +proc random_tree_structure {nEntry bParen op} { + set query xxx + for {set i 1} {$i < $nEntry} {incr i} { + set x1 [expr int(rand()*4.0)] + set x2 [expr int(rand()*2.0)] + if {$x1==0 && $bParen} { + set query "($query)" + } + if {$x2} { + set query "xxx $op $query" + } else { + set query "$query $op xxx" + } + } + return $query +} + +proc random_and_query {nEntry {bParen 0}} { + set query [random_tree_structure $nEntry $bParen AND] + for {set i 1} {$i <= $nEntry} {incr i} { + regsub xxx $query $i query + } + return $query +} + +proc random_or_query {nEntry} { + set query [random_tree_structure $nEntry 1 OR] + for {set i 1} {$i <= $nEntry} {incr i} { + regsub xxx $query $i query + } + return $query +} + +proc random_andor_query {nEntry} { + set query [random_tree_structure $nEntry 1 AND] + for {set i 1} {$i <= $nEntry} {incr i} { + regsub xxx $query "([random_or_query $nEntry])" query + } + return $query +} + +proc balanced_andor_tree {nEntry} { + set tree [balanced_exprtree_structure $nEntry] + set node "{[balanced_and_tree $nEntry]}" + regsub -all AND $node OR node + regsub -all xxx $tree $node tree + return $tree +} + +# Test that queries like "1 AND 2 AND 3 AND 4..." are transformed to +# balanced trees by FTS. +# +for {set i 1} {$i < 100} {incr i} { + do_test 1.$i { + test_fts3expr2 [random_and_query $i] + } [balanced_and_tree $i] +} + +# Same again, except with parenthesis inserted at arbitrary points. +# +for {set i 1} {$i < 100} {incr i} { + do_test 2.$i { + test_fts3expr2 [random_and_query $i 1] + } [balanced_and_tree $i] +} + +# Now attempt to balance two AND trees joined by an OR. +# +for {set i 1} {$i < 100} {incr i} { + do_test 3.$i { + test_fts3expr2 "[random_and_query $i 1] OR [random_and_query $i 1]" + } [list OR [balanced_and_tree $i] [balanced_and_tree $i]] +} + +# Try trees of AND nodes with leaves that are themselves trees of OR nodes. +# +for {set i 2} {$i < 64} {incr i 4} { + do_test 3.$i { + test_fts3expr2 [random_andor_query $i] + } [balanced_andor_tree $i] +} + +# These exceed the depth limit. +# +for {set i 65} {$i < 70} {incr i} { + do_test 3.$i { + list [catch {test_fts3expr2 [random_andor_query $i]} msg] $msg + } {1 {Error parsing expression}} +} + +# This also exceeds the depth limit. +# + +do_test 4.1.1 { + set q "1" + for {set i 2} {$i < 5000} {incr i} { + append q " AND $i" + } + list [catch {test_fts3expr2 $q} msg] $msg +} {1 {Error parsing expression}} +do_test 4.1.2 { + set q "1" + for {set i 2} {$i < 4000} {incr i} { + append q " AND $i" + } + catch {test_fts3expr2 $q} +} {0} + +proc create_toggle_tree {nDepth} { + if {$nDepth == 0} { return xxx } + set nNew [expr $nDepth-1] + if {$nDepth % 2} { + return "([create_toggle_tree $nNew]) OR ([create_toggle_tree $nNew])" + } + return "([create_toggle_tree $nNew]) AND ([create_toggle_tree $nNew])" +} + +do_test 4.2 { + list [catch {test_fts3expr2 [create_toggle_tree 17]} msg] $msg +} {1 {Error parsing expression}} + +set query [random_andor_query 12] +set result [balanced_andor_tree 12] +do_faultsim_test fts3expr3-fault-1 -faults oom-* -body { + test_fts3expr2 $::query +} -test { + faultsim_test_result [list 0 $::result] +} + +set sqlite_fts3_enable_parentheses 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3fault.test b/components/external/SQLite-3.8.1/test/fts3fault.test new file mode 100644 index 0000000000000000000000000000000000000000..ab82daa935622f3038416e8accbdda56cb6b8aef --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3fault.test @@ -0,0 +1,231 @@ +# 2010 June 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set ::testprefix fts3fault + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { finish_test ; return } + +# Test error handling in the sqlite3Fts3Init() function. This is the +# function that registers the FTS3 module and various support functions +# with SQLite. +# +do_faultsim_test 1 -body { + sqlite3 db test.db + expr 0 +} -test { + catch { db close } +} + +# Test error handling in an "ALTER TABLE ... RENAME TO" statement on an +# FTS3 table. Specifically, test renaming the table within a transaction +# after it has been written to. +# +faultsim_delete_and_reopen +do_execsql_test 2.0 { + CREATE VIRTUAL TABLE t1 USING fts3; + INSERT INTO t1 VALUES('test renaming the table'); + INSERT INTO t1 VALUES(' after it has been written'); +} +do_faultsim_test 2 -prep { + sqlite3 db test.db + execsql { + BEGIN; + INSERT INTO t1 VALUES('registers the FTS3 module'); + INSERT INTO t1 VALUES('various support functions'); + } +} -body { + execsql { ALTER TABLE t1 RENAME TO t2 } +} -test { + faultsim_test_result {0 {}} +} + +# Test error handling in the special case where a single prefix query +# matches terms that reside on a large range of leaf nodes. +# +do_test fts3fault-3.0 { + sqlite3 db test.db + execsql { CREATE VIRTUAL TABLE t3 USING fts4; } + execsql { INSERT INTO t3(t3) VALUES('nodesize=50') } + execsql { BEGIN } + for {set i 0} {$i < 1000} {incr i} { + execsql { INSERT INTO t3 VALUES('aaa' || $i) } + } + execsql { COMMIT } +} {} + +do_faultsim_test 3 -faults oom-transient -prep { + sqlite3 db test.db + execsql { SELECT * FROM t3 WHERE t3 MATCH 'x' } +} -body { + execsql { SELECT count(rowid) FROM t3 WHERE t3 MATCH 'aa*' } +} -test { + faultsim_test_result {0 1000} +} + +do_test fts3fault-4.0 { + faultsim_delete_and_reopen + execsql { + CREATE VIRTUAL TABLE t4 USING fts4; + INSERT INTO t4 VALUES('The British Government called on'); + INSERT INTO t4 VALUES('as pesetas then became much'); + } +} {} +faultsim_save_and_close +do_faultsim_test 4 -prep { + faultsim_restore_and_reopen + execsql { SELECT content FROM t4 } +} -body { + execsql { SELECT optimize(t4) FROM t4 LIMIT 1 } +} -test { + faultsim_test_result {0 {{Index optimized}}} +} + +do_test fts3fault-5.0 { + faultsim_delete_and_reopen + execsql { + CREATE VIRTUAL TABLE t5 USING fts4; + INSERT INTO t5 VALUES('The British Government called on'); + INSERT INTO t5 VALUES('as pesetas then became much'); + } +} {} +faultsim_save_and_close +do_faultsim_test 5 -prep { + faultsim_restore_and_reopen + execsql { + BEGIN; + INSERT INTO t5 VALUES('influential in shaping his future outlook'); + INSERT INTO t5 VALUES('might be acceptable to the British electorate'); + } +} -body { + execsql { SELECT rowid FROM t5 WHERE t5 MATCH 'british' } +} -test { + faultsim_test_result {0 {1 4}} +} + +do_test fts3fault-6.0 { + faultsim_delete_and_reopen + execsql { CREATE VIRTUAL TABLE t6 USING fts4 } +} {} +faultsim_save_and_close +do_faultsim_test 6 -prep { + faultsim_restore_and_reopen + execsql { SELECT rowid FROM t6 } +} -body { + execsql { DROP TABLE t6 } +} -test { + faultsim_test_result {0 {}} +} + +# Test various malloc failures while processing FTS4 parameters. +# +do_faultsim_test 7.1 -prep { + faultsim_delete_and_reopen +} -body { + execsql { CREATE VIRTUAL TABLE t1 USING fts4(a, b, matchinfo=fts3) } +} -test { + faultsim_test_result {0 {}} +} +do_faultsim_test 7.2 -prep { + faultsim_delete_and_reopen +} -body { + execsql { CREATE VIRTUAL TABLE t1 USING fts4(a, b, matchinfo=fs3) } +} -test { + faultsim_test_result {1 {unrecognized matchinfo: fs3}} \ + {1 {vtable constructor failed: t1}} \ + {1 {SQL logic error or missing database}} +} +do_faultsim_test 7.3 -prep { + faultsim_delete_and_reopen +} -body { + execsql { CREATE VIRTUAL TABLE t1 USING fts4(a, b, matchnfo=fts3) } +} -test { + faultsim_test_result {1 {unrecognized parameter: matchnfo=fts3}} \ + {1 {vtable constructor failed: t1}} \ + {1 {SQL logic error or missing database}} +} + +proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r +} + +do_test 8.0 { + faultsim_delete_and_reopen + execsql { CREATE VIRTUAL TABLE t8 USING fts4 } + execsql "INSERT INTO t8 VALUES('a b c')" + execsql "INSERT INTO t8 VALUES('b b b')" + execsql "INSERT INTO t8 VALUES('[string repeat {c } 50000]')" + execsql "INSERT INTO t8 VALUES('d d d')" + execsql "INSERT INTO t8 VALUES('e e e')" + execsql "INSERT INTO t8(t8) VALUES('optimize')" + faultsim_save_and_close +} {} + +do_faultsim_test 8.1 -prep { + faultsim_restore_and_reopen + db func mit mit +} -body { + execsql { SELECT mit(matchinfo(t8, 'x')) FROM t8 WHERE t8 MATCH 'a b c' } +} -test { + faultsim_test_result {0 {{1 1 1 1 4 2 1 5 5}}} +} +do_faultsim_test 8.2 -faults oom-t* -prep { + faultsim_restore_and_reopen + db func mit mit +} -body { + execsql { SELECT mit(matchinfo(t8, 's')) FROM t8 WHERE t8 MATCH 'a b c' } +} -test { + faultsim_test_result {0 3} +} +do_faultsim_test 8.3 -prep { + faultsim_restore_and_reopen + db func mit mit +} -body { + execsql { SELECT mit(matchinfo(t8, 'a')) FROM t8 WHERE t8 MATCH 'a b c' } +} -test { + faultsim_test_result {0 10002} +} +do_faultsim_test 8.4 -prep { + faultsim_restore_and_reopen + db func mit mit +} -body { + execsql { SELECT mit(matchinfo(t8, 'l')) FROM t8 WHERE t8 MATCH 'a b c' } +} -test { + faultsim_test_result {0 3} +} + +do_test 9.0 { + faultsim_delete_and_reopen + execsql { + CREATE VIRTUAL TABLE t9 USING fts4(tokenize=porter); + INSERT INTO t9 VALUES( + 'this record is used toooooooooooooooooooooooooooooooooooooo try to' + ); + SELECT offsets(t9) FROM t9 WHERE t9 MATCH 'to*'; + } + faultsim_save_and_close +} {} +do_faultsim_test 9.1 -prep { + faultsim_restore_and_reopen +} -body { + execsql { SELECT offsets(t9) FROM t9 WHERE t9 MATCH 'to*' } +} -test { + faultsim_test_result {0 {{0 0 20 39 0 0 64 2}}} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3fault2.test b/components/external/SQLite-3.8.1/test/fts3fault2.test new file mode 100644 index 0000000000000000000000000000000000000000..f2d10bc3f8476649153ef3a485e8e9a0cabbf9d1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3fault2.test @@ -0,0 +1,158 @@ +# 2011 February 3 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix fts3fault2 + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { finish_test ; return } + +do_test 1.0 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts4(x); + INSERT INTO t1 VALUES('a b c'); + INSERT INTO t1 VALUES('c d e'); + CREATE VIRTUAL TABLE terms USING fts4aux(t1); + } + faultsim_save_and_close +} {} + +do_faultsim_test 1.1 -prep { + faultsim_restore_and_reopen + db eval {SELECT * FROM sqlite_master} +} -body { + execsql "CREATE VIRTUAL TABLE terms2 USING fts4aux(t1)" +} -test { + faultsim_test_result {0 {}} +} + +do_faultsim_test 1.2 -prep { + faultsim_restore_and_reopen + db eval {SELECT * FROM sqlite_master} +} -body { + execsql "SELECT * FROM terms" +} -test { + faultsim_test_result {0 {a * 1 1 a 0 1 1 b * 1 1 b 0 1 1 c * 2 2 c 0 2 2 d * 1 1 d 0 1 1 e * 1 1 e 0 1 1}} +} + +do_faultsim_test 1.3 -prep { + faultsim_restore_and_reopen + db eval {SELECT * FROM sqlite_master} +} -body { + execsql "SELECT * FROM terms WHERE term>'a' AND TERM < 'd'" +} -test { + faultsim_test_result {0 {b * 1 1 b 0 1 1 c * 2 2 c 0 2 2}} +} + +do_faultsim_test 1.4 -prep { + faultsim_restore_and_reopen + db eval {SELECT * FROM sqlite_master} +} -body { + execsql "SELECT * FROM terms WHERE term='c'" +} -test { + faultsim_test_result {0 {c * 2 2 c 0 2 2}} +} + +do_test 2.0 { + faultsim_delete_and_reopen + execsql { + CREATE VIRTUAL TABLE tx USING fts4(a, b); + INSERT INTO tx VALUES('a b c', 'x y z'); + CREATE VIRTUAL TABLE terms2 USING fts4aux(tx); + } + faultsim_save_and_close +} {} + +do_faultsim_test 2.1 -prep { + faultsim_restore_and_reopen + db eval {SELECT * FROM sqlite_master} +} -body { + execsql "SELECT * FROM terms2" +} -test { + faultsim_test_result {0 {a * 1 1 a 0 1 1 b * 1 1 b 0 1 1 c * 1 1 c 0 1 1 x * 1 1 x 1 1 1 y * 1 1 y 1 1 1 z * 1 1 z 1 1 1}} +} + +do_faultsim_test 3.0 -faults oom* -prep { + faultsim_delete_and_reopen + db eval { CREATE TABLE 'xx yy'(a, b); } +} -body { + execsql { + CREATE VIRTUAL TABLE tt USING fts4(content="xx yy"); + } +} -test { + faultsim_test_result {0 {}} +} + +do_faultsim_test 3.1 -faults oom* -prep { + faultsim_delete_and_reopen + db func zip zip + db func unzip unzip +} -body { + execsql { + CREATE VIRTUAL TABLE tt USING fts4(compress=zip, uncompress=unzip); + } +} -test { + faultsim_test_result {0 {}} +} + +do_test 4.0 { + faultsim_delete_and_reopen + execsql { + CREATE VIRTUAL TABLE ft USING fts4(a, b); + INSERT INTO ft VALUES('U U T C O', 'F N D E S'); + INSERT INTO ft VALUES('P H X G B', 'I D M R U'); + INSERT INTO ft VALUES('P P X D M', 'Y V N T C'); + INSERT INTO ft VALUES('Z L Q O W', 'D F U N Q'); + INSERT INTO ft VALUES('A J D U P', 'C H M Q E'); + INSERT INTO ft VALUES('P S A O H', 'S Z C W D'); + INSERT INTO ft VALUES('T B N L W', 'C A K T I'); + INSERT INTO ft VALUES('K E Z L O', 'L L Y C E'); + INSERT INTO ft VALUES('C R E S V', 'Q V F W P'); + INSERT INTO ft VALUES('S K H G W', 'R W Q F G'); + } + faultsim_save_and_close +} {} +do_faultsim_test 4.1 -prep { + faultsim_restore_and_reopen + db eval {SELECT * FROM sqlite_master} +} -body { + execsql { INSERT INTO ft(ft) VALUES('rebuild') } +} -test { + faultsim_test_result {0 {}} +} + +ifcapable fts3_unicode { + do_test 5.0 { + faultsim_delete_and_reopen + execsql { + CREATE VIRTUAL TABLE ft USING fts4(a, tokenize=unicode61); + } + faultsim_save_and_close + } {} + + do_faultsim_test 5.1 -faults oom* -prep { + faultsim_restore_and_reopen + db eval {SELECT * FROM sqlite_master} + } -body { + execsql { INSERT INTO ft VALUES('the quick brown fox'); } + execsql { INSERT INTO ft VALUES( + 'theunusuallylongtokenthatjustdragsonandonandonandthendragsonsomemoreeof' + ); + } + execsql { SELECT docid FROM ft WHERE ft MATCH 'th*' } + } -test { + faultsim_test_result {0 {1 2}} + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3first.test b/components/external/SQLite-3.8.1/test/fts3first.test new file mode 100644 index 0000000000000000000000000000000000000000..673f818debc98dd9c60775621a0e2856c12675a4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3first.test @@ -0,0 +1,163 @@ +# 2011 October 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +ifcapable !fts3 { + finish_test + return +} + +set testprefix fts3first + +proc lreverse {L} { + set res [list] + for {set ii [expr [llength $L]-1]} {$ii>=0} {incr ii -1} { + lappend res [lindex $L $ii] + } + set res +} + +proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r +} +db func mit mit + +do_execsql_test 1.0 { + CREATE VIRTUAL TABLE x1 USING FTS4(a, b, c); + INSERT INTO x1(docid,a,b,c) VALUES(0, 'K H D S T', 'V M N Y K', 'S Z N Q S'); + INSERT INTO x1(docid,a,b,c) VALUES(1, 'K N J L W', 'S Z W J Q', 'D U W S E'); + INSERT INTO x1(docid,a,b,c) VALUES(2, 'B P M O I', 'R P H W S', 'R J L L E'); + INSERT INTO x1(docid,a,b,c) VALUES(3, 'U R Q M L', 'M J K A V', 'Q W J T J'); + INSERT INTO x1(docid,a,b,c) VALUES(4, 'N J C Y N', 'R U D X V', 'B O U A Q'); + INSERT INTO x1(docid,a,b,c) VALUES(5, 'Q L X L U', 'I F N X S', 'U Q A N Y'); + INSERT INTO x1(docid,a,b,c) VALUES(6, 'M R G U T', 'U V I Q P', 'X Y D L S'); + INSERT INTO x1(docid,a,b,c) VALUES(7, 'D Y P O I', 'X J P K R', 'V O T H V'); + INSERT INTO x1(docid,a,b,c) VALUES(8, 'R Y D L R', 'U U E S J', 'N W L M R'); + INSERT INTO x1(docid,a,b,c) VALUES(9, 'Z P F N P', 'W A X D U', 'V A E Q A'); + INSERT INTO x1(docid,a,b,c) VALUES(10, 'Q I A Q M', 'N D K H C', 'A H T Q Z'); + INSERT INTO x1(docid,a,b,c) VALUES(11, 'T E R Q B', 'C I B C B', 'F Z U W R'); + INSERT INTO x1(docid,a,b,c) VALUES(12, 'E S V U W', 'T P F W H', 'A M D J Q'); + INSERT INTO x1(docid,a,b,c) VALUES(13, 'X S B X Y', 'U D N D P', 'X Z Y G F'); + INSERT INTO x1(docid,a,b,c) VALUES(14, 'K H A B L', 'S R C C Z', 'D W E H J'); + INSERT INTO x1(docid,a,b,c) VALUES(15, 'C E U C C', 'W F M N M', 'T Z U X T'); + INSERT INTO x1(docid,a,b,c) VALUES(16, 'Q G C G H', 'H N N B H', 'B Q I H Y'); + INSERT INTO x1(docid,a,b,c) VALUES(17, 'Q T S K B', 'W B D Y N', 'V J P E C'); + INSERT INTO x1(docid,a,b,c) VALUES(18, 'A J M O Q', 'L G Y Y A', 'G N M R N'); + INSERT INTO x1(docid,a,b,c) VALUES(19, 'T R Y P Y', 'N V Y B X', 'L Z T N T'); + + CREATE VIRTUAL TABLE x2 USING FTS4(a, b, c, order=DESC); + INSERT INTO x2(docid, a, b, c) SELECT docid, a, b, c FROM x1; +} + + +# Test queries. +# +foreach x {1 2} { + foreach {tn match res} { + 1 "^K" {0 1 14} + 2 "^S" {0 1 14} + 3 "^W" {9 15 17} + 4 "^J" {} + 5 "^E" {12} + 6 "V ^-E" {0 3 4 6 7 9 17 19} + 7 "V -^E" {0 3 4 6 7 9 17 19} + 8 "^-E V" {0 3 4 6 7 9 17 19} + 9 "-^E V" {0 3 4 6 7 9 17 19} + 10 "V" {0 3 4 6 7 9 12 17 19} + + 11 {"^K H"} {0 14} + 12 {"K H"} {0 10 14} + 13 {"K ^H"} {} + } { + set rev [lreverse $res] + do_execsql_test 1.$x.$tn.1 {SELECT docid FROM x1 WHERE x1 MATCH $match} $res + do_execsql_test 1.$x.$tn.2 {SELECT docid FROM x2 WHERE x2 MATCH $match} $rev + } + + do_execsql_test 1.$x.[expr $tn+1] { + INSERT INTO x1(x1) VALUES('optimize'); + INSERT INTO x2(x2) VALUES('optimize'); + } {} +} + +# Test the snippet() function. +# +foreach {tn match res} { + 1 {^K} {{[K] H D S T} {[K] N J L W} {[K] H A B L}} + 2 {^X} {{[X] Y D L S} {[X] J P K R} {[X] S B X Y}} + 3 {^X Y} {{[X] [Y] D L S} {D [Y] P O I...[X] J P K R} {[X] S B X [Y]}} +} { + set rev [lreverse $res] + + do_execsql_test 1.3.$tn.1 { + SELECT snippet(x1, '[', ']', '...') FROM x1 WHERE x1 MATCH $match + } $res + + do_execsql_test 1.3.$tn.2 { + SELECT snippet(x2, '[', ']', '...') FROM x2 WHERE x2 MATCH $match + } $rev +} + +# Test matchinfo(). +# +foreach {tn match res} { + 1 {^K} { + {1 3 3 0 0 0 0 0 0} + {1 3 3 0 0 0 0 0 0} + {1 3 3 0 0 0 0 0 0} + } + 2 {^X} { + {0 1 1 0 1 1 1 2 2} + {0 1 1 1 1 1 0 2 2} + {1 1 1 0 1 1 1 2 2} + } + 3 {^X Y} { + {0 1 1 0 1 1 1 2 2 0 6 5 0 5 4 1 4 4} + {0 1 1 1 1 1 0 2 2 1 6 5 0 5 4 0 4 4} + {1 1 1 0 1 1 1 2 2 1 6 5 0 5 4 1 4 4} + } +} { + set rev [lreverse $res] + + do_execsql_test 1.3.$tn.1 { + SELECT mit(matchinfo(x1, 'x')) FROM x1 WHERE x1 MATCH $match + } $res + do_execsql_test 1.3.$tn.2 { + SELECT mit(matchinfo(x2, 'x')) FROM x2 WHERE x2 MATCH $match + } $rev +} + +# Test that ^ is ignored for FTS3 tables. +# +do_execsql_test 2.1 { + CREATE VIRTUAL TABLE x3 USING fts3; + INSERT INTO x3 VALUES('A B C'); + INSERT INTO x3 VALUES('B A C'); + + CREATE VIRTUAL TABLE x4 USING fts4; + INSERT INTO x4 VALUES('A B C'); + INSERT INTO x4 VALUES('B A C'); +} + +do_execsql_test 2.2.1 { + SELECT * FROM x3 WHERE x3 MATCH '^A'; +} {{A B C} {B A C}} +do_execsql_test 2.2.2 { + SELECT * FROM x4 WHERE x4 MATCH '^A'; +} {{A B C}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3malloc.test b/components/external/SQLite-3.8.1/test/fts3malloc.test new file mode 100644 index 0000000000000000000000000000000000000000..ed30fe24c8ab0928bae84471e7b8c9e2ad302d2b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3malloc.test @@ -0,0 +1,307 @@ +# 2009 October 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests to verify that malloc() errors that occur +# within the FTS3 module code are handled correctly. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !fts3 { finish_test ; return } +source $testdir/malloc_common.tcl +source $testdir/fts3_common.tcl + +# Ensure the lookaside buffer is disabled for these tests. +# +sqlite3 db test.db +sqlite3_db_config_lookaside db 0 0 0 + +set sqlite_fts3_enable_parentheses 1 +set DO_MALLOC_TEST 1 + +# Test organization: +# +# fts3_malloc-1.*: Test OOM during CREATE and DROP table statements. +# fts3_malloc-2.*: Test OOM during SELECT operations. +# fts3_malloc-3.*: Test OOM during SELECT operations with a larger database. +# fts3_malloc-4.*: Test OOM during database write operations. +# fts3_malloc-5.*: Test that a couple of memory leaks that could follow +# OOM in tokenizer code have been fixed. +# + + +proc normal_list {l} { + set ret [list] + foreach elem $l {lappend ret $elem} + set ret +} + +do_write_test fts3_malloc-1.1 sqlite_master { + CREATE VIRTUAL TABLE ft1 USING fts3(a, b) +} +do_write_test fts3_malloc-1.2 sqlite_master { + CREATE VIRTUAL TABLE ft2 USING fts3([a], [b]); +} +do_write_test fts3_malloc-1.3 sqlite_master { + CREATE VIRTUAL TABLE ft3 USING fts3('a', "b"); +} +do_write_test fts3_malloc-1.4 sqlite_master { + CREATE VIRTUAL TABLE ft4 USING fts3(`a`, 'fred''s column'); +} +do_error_test fts3_malloc-1.5 { + CREATE VIRTUAL TABLE ft5 USING fts3(a, b, tokenize unknown) +} {unknown tokenizer: unknown} +do_write_test fts3_malloc-1.6 sqlite_master { + CREATE VIRTUAL TABLE ft6 USING fts3(a, b, tokenize porter) +} +do_write_test fts3_malloc-1.7 sqlite_master { + CREATE VIRTUAL TABLE ft7 USING fts4(a, b, notindexed=b) +} + +# Test the xConnect/xDisconnect methods: +#db eval { ATTACH 'test2.db' AS aux } +#do_write_test fts3_malloc-1.6 aux.sqlite_master { +# CREATE VIRTUAL TABLE aux.ft7 USING fts3(a, b, c); +#} +#do_write_test fts3_malloc-1.6 aux.sqlite_master { +# CREATE VIRTUAL TABLE aux.ft7 USING fts3(a, b, c); +#} + + + +do_test fts3_malloc-2.0 { + execsql { + DROP TABLE ft1; + DROP TABLE ft2; + DROP TABLE ft3; + DROP TABLE ft4; + DROP TABLE ft6; + DROP TABLE ft7; + } + execsql { CREATE VIRTUAL TABLE ft USING fts3(a, b) } + for {set ii 1} {$ii < 32} {incr ii} { + set a [list] + set b [list] + if {$ii & 0x01} {lappend a one ; lappend b neung} + if {$ii & 0x02} {lappend a two ; lappend b song } + if {$ii & 0x04} {lappend a three ; lappend b sahm } + if {$ii & 0x08} {lappend a four ; lappend b see } + if {$ii & 0x10} {lappend a five ; lappend b hah } + execsql { INSERT INTO ft VALUES($a, $b) } + } +} {} + +foreach {tn sql result} { + 1 "SELECT count(*) FROM sqlite_master" {5} + 2 "SELECT * FROM ft WHERE docid = 1" {one neung} + 3 "SELECT * FROM ft WHERE docid = 2" {two song} + 4 "SELECT * FROM ft WHERE docid = 3" {{one two} {neung song}} + + 5 "SELECT a FROM ft" { + {one} {two} {one two} + {three} {one three} {two three} + {one two three} {four} {one four} + {two four} {one two four} {three four} + {one three four} {two three four} {one two three four} + {five} {one five} {two five} + {one two five} {three five} {one three five} + {two three five} {one two three five} {four five} + {one four five} {two four five} {one two four five} + {three four five} {one three four five} {two three four five} + {one two three four five} + } + + 6 "SELECT a FROM ft WHERE a MATCH 'one'" { + {one} {one two} {one three} {one two three} + {one four} {one two four} {one three four} {one two three four} + {one five} {one two five} {one three five} {one two three five} + {one four five} {one two four five} + {one three four five} {one two three four five} + } + + 7 "SELECT a FROM ft WHERE a MATCH 'o*'" { + {one} {one two} {one three} {one two three} + {one four} {one two four} {one three four} {one two three four} + {one five} {one two five} {one three five} {one two three five} + {one four five} {one two four five} + {one three four five} {one two three four five} + } + + 8 "SELECT a FROM ft WHERE a MATCH 'o* t*'" { + {one two} {one three} {one two three} + {one two four} {one three four} {one two three four} + {one two five} {one three five} {one two three five} + {one two four five} {one three four five} {one two three four five} + } + + 9 "SELECT a FROM ft WHERE a MATCH '\"o* t*\"'" { + {one two} {one three} {one two three} + {one two four} {one three four} {one two three four} + {one two five} {one three five} {one two three five} + {one two four five} {one three four five} {one two three four five} + } + + 10 {SELECT a FROM ft WHERE a MATCH '"o* f*"'} { + {one four} {one five} {one four five} + } + + 11 {SELECT a FROM ft WHERE a MATCH '"one two three"'} { + {one two three} + {one two three four} + {one two three five} + {one two three four five} + } + + 12 {SELECT a FROM ft WHERE a MATCH '"two three four"'} { + {two three four} + {one two three four} + {two three four five} + {one two three four five} + } + + 12 {SELECT a FROM ft WHERE a MATCH '"two three" five'} { + {two three five} {one two three five} + {two three four five} {one two three four five} + } + + 13 {SELECT a FROM ft WHERE ft MATCH '"song sahm" hah'} { + {two three five} {one two three five} + {two three four five} {one two three four five} + } + + 14 {SELECT a FROM ft WHERE b MATCH 'neung'} { + {one} {one two} + {one three} {one two three} + {one four} {one two four} + {one three four} {one two three four} + {one five} {one two five} + {one three five} {one two three five} + {one four five} {one two four five} + {one three four five} {one two three four five} + } + + 15 {SELECT a FROM ft WHERE b MATCH '"neung song sahm"'} { + {one two three} {one two three four} + {one two three five} {one two three four five} + } + + 16 {SELECT a FROM ft WHERE b MATCH 'hah "song sahm"'} { + {two three five} {one two three five} + {two three four five} {one two three four five} + } + + 17 {SELECT a FROM ft WHERE b MATCH 'song OR sahm'} { + {two} {one two} {three} + {one three} {two three} {one two three} + {two four} {one two four} {three four} + {one three four} {two three four} {one two three four} + {two five} {one two five} {three five} + {one three five} {two three five} {one two three five} + {two four five} {one two four five} {three four five} + {one three four five} {two three four five} {one two three four five} + } + + 18 {SELECT a FROM ft WHERE a MATCH 'three NOT two'} { + {three} {one three} {three four} + {one three four} {three five} {one three five} + {three four five} {one three four five} + } + + 19 {SELECT a FROM ft WHERE b MATCH 'sahm NOT song'} { + {three} {one three} {three four} + {one three four} {three five} {one three five} + {three four five} {one three four five} + } + + 20 {SELECT a FROM ft WHERE ft MATCH 'sahm NOT song'} { + {three} {one three} {three four} + {one three four} {three five} {one three five} + {three four five} {one three four five} + } + + 21 {SELECT a FROM ft WHERE b MATCH 'neung NEAR song NEAR sahm'} { + {one two three} {one two three four} + {one two three five} {one two three four five} + } + +} { + set result [normal_list $result] + do_select_test fts3_malloc-2.$tn $sql $result +} + +do_test fts3_malloc-3.0 { + execsql BEGIN + for {set ii 32} {$ii < 1024} {incr ii} { + set a [list] + set b [list] + if {$ii & 0x0001} {lappend a one ; lappend b neung } + if {$ii & 0x0002} {lappend a two ; lappend b song } + if {$ii & 0x0004} {lappend a three ; lappend b sahm } + if {$ii & 0x0008} {lappend a four ; lappend b see } + if {$ii & 0x0010} {lappend a five ; lappend b hah } + if {$ii & 0x0020} {lappend a six ; lappend b hok } + if {$ii & 0x0040} {lappend a seven ; lappend b jet } + if {$ii & 0x0080} {lappend a eight ; lappend b bairt } + if {$ii & 0x0100} {lappend a nine ; lappend b gow } + if {$ii & 0x0200} {lappend a ten ; lappend b sip } + execsql { INSERT INTO ft VALUES($a, $b) } + } + execsql COMMIT +} {} +foreach {tn sql result} { + 1 "SELECT count(*) FROM ft" {1023} + + 2 "SELECT a FROM ft WHERE a MATCH 'one two three four five six seven eight'" { + {one two three four five six seven eight} + {one two three four five six seven eight nine} + {one two three four five six seven eight ten} + {one two three four five six seven eight nine ten} + } + + 3 {SELECT count(*), sum(docid) FROM ft WHERE a MATCH 'o*'} { + 512 262144 + } + + 4 {SELECT count(*), sum(docid) FROM ft WHERE a MATCH '"two three four"'} { + 128 66368 + } +} { + set result [normal_list $result] + do_select_test fts3_malloc-3.$tn $sql $result +} + +do_test fts3_malloc-4.0 { + execsql { DELETE FROM ft WHERE docid>=32 } +} {} +foreach {tn sql} { + 1 "DELETE FROM ft WHERE ft MATCH 'one'" + 2 "DELETE FROM ft WHERE ft MATCH 'three'" + 3 "DELETE FROM ft WHERE ft MATCH 'five'" +} { + do_write_test fts3_malloc-4.1.$tn ft_content $sql +} +do_test fts3_malloc-4.2 { + execsql { SELECT a FROM ft } +} {two four {two four}} + +do_write_test fts3_malloc-5.1 ft_content { + INSERT INTO ft VALUES('short alongertoken reallyquitealotlongerimeanit andthistokenisjustsolongthatonemightbeforgivenforimaginingthatitwasmerelyacontrivedexampleandnotarealtoken', 'cynics!') +} +do_test fts3_malloc-5.2 { + execsql { CREATE VIRTUAL TABLE ft8 USING fts3(x, tokenize porter) } +} {} + +do_write_test fts3_malloc-5.3 ft_content { + INSERT INTO ft8 VALUES('short alongertoken reallyquitealotlongerimeanit andthistokenisjustsolongthatonemightbeforgivenforimaginingthatitwasmerelyacontrivedexampleandnotarealtoken') +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3matchinfo.test b/components/external/SQLite-3.8.1/test/fts3matchinfo.test new file mode 100644 index 0000000000000000000000000000000000000000..fd475af2e42c691e928fd881410a2e23022f79d5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3matchinfo.test @@ -0,0 +1,436 @@ +# 2010 November 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for the FTS3 module. The focus +# of this file is tables created with the "matchinfo=fts3" option. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { finish_test ; return } + +set testprefix fts3matchinfo +set sqlite_fts3_enable_parentheses 0 + +proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r +} +db func mit mit + +do_execsql_test 1.0 { + CREATE VIRTUAL TABLE t1 USING fts4(matchinfo=fts3); + SELECT name FROM sqlite_master WHERE type = 'table'; +} {t1 t1_content t1_segments t1_segdir t1_stat} + +do_execsql_test 1.1 { + INSERT INTO t1(content) VALUES('I wandered lonely as a cloud'); + INSERT INTO t1(content) VALUES('That floats on high o''er vales and hills,'); + INSERT INTO t1(content) VALUES('When all at once I saw a crowd,'); + INSERT INTO t1(content) VALUES('A host, of golden daffodils,'); + SELECT mit(matchinfo(t1)) FROM t1 WHERE t1 MATCH 'I'; +} {{1 1 1 2 2} {1 1 1 2 2}} + +# Now create an FTS4 table that does not specify matchinfo=fts3. +# +do_execsql_test 1.2 { + CREATE VIRTUAL TABLE t2 USING fts4; + INSERT INTO t2 SELECT * FROM t1; + SELECT mit(matchinfo(t2)) FROM t2 WHERE t2 MATCH 'I'; +} {{1 1 1 2 2} {1 1 1 2 2}} + +# Test some syntax-error handling. +# +do_catchsql_test 2.0 { + CREATE VIRTUAL TABLE x1 USING fts4(matchinfo=fs3); +} {1 {unrecognized matchinfo: fs3}} +do_catchsql_test 2.1 { + CREATE VIRTUAL TABLE x2 USING fts4(mtchinfo=fts3); +} {1 {unrecognized parameter: mtchinfo=fts3}} +do_catchsql_test 2.2 { + CREATE VIRTUAL TABLE x2 USING fts4(matchinfo=fts5); +} {1 {unrecognized matchinfo: fts5}} + +# Check that with fts3, the "=" character is permitted in column definitions. +# +do_execsql_test 3.1 { + CREATE VIRTUAL TABLE t3 USING fts3(mtchinfo=fts3); + INSERT INTO t3(mtchinfo) VALUES('Beside the lake, beneath the trees'); + SELECT mtchinfo FROM t3; +} {{Beside the lake, beneath the trees}} + +do_execsql_test 3.2 { + CREATE VIRTUAL TABLE xx USING FTS4; +} +do_execsql_test 3.3 { + SELECT * FROM xx WHERE xx MATCH 'abc'; +} +do_execsql_test 3.4 { + SELECT * FROM xx WHERE xx MATCH 'a b c'; +} + + +#-------------------------------------------------------------------------- +# Proc [do_matchinfo_test] is used to test the FTSX matchinfo() function. +# +# The first argument - $tn - is a test identifier. This may be either a +# full identifier (i.e. "fts3matchinfo-1.1") or, if global var $testprefix +# is set, just the numeric component (i.e. "1.1"). +# +# The second argument is the name of an FTSX table. The third is the +# full text of a WHERE/MATCH expression to query the table for +# (i.e. "t1 MATCH 'abc'"). The final argument - $results - should be a +# key-value list (serialized array) with matchinfo() format specifiers +# as keys, and the results of executing the statement: +# +# SELECT matchinfo($tbl, '$key') FROM $tbl WHERE $expr +# +# For example: +# +# CREATE VIRTUAL TABLE t1 USING fts4; +# INSERT INTO t1 VALUES('abc'); +# INSERT INTO t1 VALUES('def'); +# INSERT INTO t1 VALUES('abc abc'); +# +# do_matchinfo_test 1.1 t1 "t1 MATCH 'abc'" { +# n {3 3} +# p {1 1} +# c {1 1} +# x {{1 3 2} {2 3 2}} +# } +# +# If the $results list contains keys mapped to "-" instead of a matchinfo() +# result, then this command computes the expected results based on other +# mappings to test the matchinfo() function. For example, the command above +# could be changed to: +# +# do_matchinfo_test 1.1 t1 "t1 MATCH 'abc'" { +# n {3 3} p {1 1} c {1 1} x {{1 3 2} {2 3 2}} +# pcx - +# } +# +# And this command would compute the expected results for matchinfo(t1, 'pcx') +# based on the results of matchinfo(t1, 'p'), matchinfo(t1, 'c') and +# matchinfo(t1, 'x') in order to test 'pcx'. +# +proc do_matchinfo_test {tn tbl expr results} { + + foreach {fmt res} $results { + if {$res == "-"} continue + set resarray($fmt) $res + } + + set nRow 0 + foreach {fmt res} [array get resarray] { + if {[llength $res]>$nRow} { set nRow [llength $res] } + } + + # Construct expected results for any formats for which the caller + # supplied result is "-". + # + foreach {fmt res} $results { + if {$res == "-"} { + set res [list] + for {set iRow 0} {$iRow<$nRow} {incr iRow} { + set rowres [list] + foreach c [split $fmt ""] { + set rowres [concat $rowres [lindex $resarray($c) $iRow]] + } + lappend res $rowres + } + set resarray($fmt) $res + } + } + + # Test each matchinfo() request individually. + # + foreach {fmt res} [array get resarray] { + set sql "SELECT mit(matchinfo($tbl, '$fmt')) FROM $tbl WHERE $expr" + do_execsql_test $tn.$fmt $sql [normalize2 $res] + } + + # Test them all executed together (multiple invocations of matchinfo()). + # + set exprlist [list] + foreach {format res} [array get resarray] { + lappend exprlist "mit(matchinfo($tbl, '$format'))" + } + set allres [list] + for {set iRow 0} {$iRow<$nRow} {incr iRow} { + foreach {format res} [array get resarray] { + lappend allres [lindex $res $iRow] + } + } + set sql "SELECT [join $exprlist ,] FROM $tbl WHERE $expr" + do_execsql_test $tn.multi $sql [normalize2 $allres] +} +proc normalize2 {list_of_lists} { + set res [list] + foreach elem $list_of_lists { + lappend res [list {*}$elem] + } + return $res +} + + +do_execsql_test 4.1.0 { + CREATE VIRTUAL TABLE t4 USING fts4(x, y); + INSERT INTO t4 VALUES('a b c d e', 'f g h i j'); + INSERT INTO t4 VALUES('f g h i j', 'a b c d e'); +} + +do_matchinfo_test 4.1.1 t4 {t4 MATCH 'a b c'} { + p {3 3} + c {2 2} + x { + {1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1} + {0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1} + } + n {2 2} + l {{5 5} {5 5}} + a {{5 5} {5 5}} + + s {{3 0} {0 3}} + + xxxxxxxxxxxxxxxxxx - pcx - xpc - ccc - pppxpcpcx - laxnpc - + xpxsscplax - +} + +do_matchinfo_test 4.1.2 t4 {t4 MATCH '"g h i"'} { + p {1 1} + c {2 2} + x { + {0 1 1 1 1 1} + {1 1 1 0 1 1} + } + n {2 2} + l {{5 5} {5 5}} + a {{5 5} {5 5}} + + s {{0 1} {1 0}} + + xxxxxxxxxxxxxxxxxx - pcx - xpc - ccc - pppxpcpcx - laxnpc - + sxsxs - +} + +do_matchinfo_test 4.1.3 t4 {t4 MATCH 'a b'} { s {{2 0} {0 2}} } +do_matchinfo_test 4.1.4 t4 {t4 MATCH '"a b" c'} { s {{2 0} {0 2}} } +do_matchinfo_test 4.1.5 t4 {t4 MATCH 'a "b c"'} { s {{2 0} {0 2}} } +do_matchinfo_test 4.1.6 t4 {t4 MATCH 'd d'} { s {{1 0} {0 1}} } +do_matchinfo_test 4.1.7 t4 {t4 MATCH 'f OR abcd'} { + x { + {0 1 1 1 1 1 0 0 0 0 0 0} + {1 1 1 0 1 1 0 0 0 0 0 0} + } +} +do_matchinfo_test 4.1.8 t4 {t4 MATCH 'f -abcd'} { + x { + {0 1 1 1 1 1} + {1 1 1 0 1 1} + } +} + +do_execsql_test 4.2.0 { + CREATE VIRTUAL TABLE t5 USING fts4; + INSERT INTO t5 VALUES('a a a a a'); + INSERT INTO t5 VALUES('a b a b a'); + INSERT INTO t5 VALUES('c b c b c'); + INSERT INTO t5 VALUES('x x x x x'); +} +do_matchinfo_test 4.2.1 t5 {t5 MATCH 'a a'} { + x {{5 8 2 5 8 2} {3 8 2 3 8 2}} + s {2 1} +} +do_matchinfo_test 4.2.2 t5 {t5 MATCH 'a b'} { s {2} } +do_matchinfo_test 4.2.3 t5 {t5 MATCH 'a b a'} { s {3} } +do_matchinfo_test 4.2.4 t5 {t5 MATCH 'a a a'} { s {3 1} } +do_matchinfo_test 4.2.5 t5 {t5 MATCH '"a b" "a b"'} { s {2} } +do_matchinfo_test 4.2.6 t5 {t5 MATCH 'a OR b'} { s {1 2 1} } + +do_execsql_test 4.3.0 "INSERT INTO t5 VALUES('x y [string repeat {b } 50000]')"; + +# It used to be that the second 'a' token would be deferred. That doesn't +# work any longer. +if 0 { + do_matchinfo_test 4.3.1 t5 {t5 MATCH 'a a'} { + x {{5 8 2 5 5 5} {3 8 2 3 5 5}} + s {2 1} + } +} + +do_matchinfo_test 4.3.2 t5 {t5 MATCH 'a b'} { s {2} } +do_matchinfo_test 4.3.3 t5 {t5 MATCH 'a b a'} { s {3} } +do_matchinfo_test 4.3.4 t5 {t5 MATCH 'a a a'} { s {3 1} } +do_matchinfo_test 4.3.5 t5 {t5 MATCH '"a b" "a b"'} { s {2} } +do_matchinfo_test 4.3.6 t5 {t5 MATCH 'a OR b'} { s {1 2 1 1} } + +do_execsql_test 4.4.0.1 { INSERT INTO t5(t5) VALUES('optimize') } + +ifcapable fts4_deferred { + do_execsql_test 4.4.0.2 { + UPDATE t5_segments + SET block = zeroblob(length(block)) + WHERE length(block)>10000; + } +} + +do_matchinfo_test 4.4.2 t5 {t5 MATCH 'a b'} { s {2} } +do_matchinfo_test 4.4.1 t5 {t5 MATCH 'a a'} { s {2 1} } +do_matchinfo_test 4.4.2 t5 {t5 MATCH 'a b'} { s {2} } +do_matchinfo_test 4.4.3 t5 {t5 MATCH 'a b a'} { s {3} } +do_matchinfo_test 4.4.4 t5 {t5 MATCH 'a a a'} { s {3 1} } +do_matchinfo_test 4.4.5 t5 {t5 MATCH '"a b" "a b"'} { s {2} } + +do_execsql_test 4.5.0 { + CREATE VIRTUAL TABLE t6 USING fts4(a, b, c); + INSERT INTO t6 VALUES('a', 'b', 'c'); +} +do_matchinfo_test 4.5.1 t6 {t6 MATCH 'a b c'} { s {{1 1 1}} } + + +#------------------------------------------------------------------------- +# Check the following restrictions: +# +# + Matchinfo flags 'a', 'l' and 'n' can only be used with fts4, not fts3. +# + Matchinfo flag 'l' cannot be used with matchinfo=fts3. +# +do_execsql_test 5.1 { + CREATE VIRTUAL TABLE t7 USING fts3(a, b); + INSERT INTO t7 VALUES('u v w', 'x y z'); + + CREATE VIRTUAL TABLE t8 USING fts4(a, b, matchinfo=fts3); + INSERT INTO t8 VALUES('u v w', 'x y z'); +} + +do_catchsql_test 5.2.1 { + SELECT matchinfo(t7, 'a') FROM t7 WHERE t7 MATCH 'x y' +} {1 {unrecognized matchinfo request: a}} +do_catchsql_test 5.2.2 { + SELECT matchinfo(t7, 'l') FROM t7 WHERE t7 MATCH 'x y' +} {1 {unrecognized matchinfo request: l}} +do_catchsql_test 5.2.3 { + SELECT matchinfo(t7, 'n') FROM t7 WHERE t7 MATCH 'x y' +} {1 {unrecognized matchinfo request: n}} + +do_catchsql_test 5.3.1 { + SELECT matchinfo(t8, 'l') FROM t8 WHERE t8 MATCH 'x y' +} {1 {unrecognized matchinfo request: l}} + +#------------------------------------------------------------------------- +# Test that the offsets() function handles corruption in the %_content +# table correctly. +# +do_execsql_test 6.1 { + CREATE VIRTUAL TABLE t9 USING fts4; + INSERT INTO t9 VALUES( + 'this record is used to try to dectect corruption' + ); + SELECT offsets(t9) FROM t9 WHERE t9 MATCH 'to'; +} {{0 0 20 2 0 0 27 2}} + +do_catchsql_test 6.2 { + UPDATE t9_content SET c0content = 'this record is used to'; + SELECT offsets(t9) FROM t9 WHERE t9 MATCH 'to'; +} {1 {database disk image is malformed}} + +#------------------------------------------------------------------------- +# Test the outcome of matchinfo() when used within a query that does not +# use the full-text index (i.e. lookup by rowid or full-table scan). +# +do_execsql_test 7.1 { + CREATE VIRTUAL TABLE t10 USING fts4; + INSERT INTO t10 VALUES('first record'); + INSERT INTO t10 VALUES('second record'); +} +do_execsql_test 7.2 { + SELECT typeof(matchinfo(t10)), length(matchinfo(t10)) FROM t10; +} {blob 0 blob 0} +do_execsql_test 7.3 { + SELECT typeof(matchinfo(t10)), length(matchinfo(t10)) FROM t10 WHERE docid=1; +} {blob 0} +do_execsql_test 7.4 { + SELECT typeof(matchinfo(t10)), length(matchinfo(t10)) + FROM t10 WHERE t10 MATCH 'record' +} {blob 20 blob 20} + +#------------------------------------------------------------------------- +# Test a special case - matchinfo('nxa') with many zero length documents. +# Special because "x" internally uses a statement used by both "n" and "a". +# This was causing a problem at one point in the obscure case where the +# total number of bytes of data stored in an fts3 table was greater than +# the number of rows. i.e. when the following query returns true: +# +# SELECT sum(length(content)) < count(*) FROM fts4table; +# +do_execsql_test 8.1 { + CREATE VIRTUAL TABLE t11 USING fts4; + INSERT INTO t11(t11) VALUES('nodesize=24'); + INSERT INTO t11 VALUES('quitealongstringoftext'); + INSERT INTO t11 VALUES('anotherquitealongstringoftext'); + INSERT INTO t11 VALUES('athirdlongstringoftext'); + INSERT INTO t11 VALUES('andonemoreforgoodluck'); +} +do_test 8.2 { + for {set i 0} {$i < 200} {incr i} { + execsql { INSERT INTO t11 VALUES('') } + } + execsql { INSERT INTO t11(t11) VALUES('optimize') } +} {} +do_execsql_test 8.3 { + SELECT mit(matchinfo(t11, 'nxa')) FROM t11 WHERE t11 MATCH 'a*' +} {{204 1 3 3 0} {204 1 3 3 0} {204 1 3 3 0}} + +# Corruption related tests. +do_execsql_test 8.4.1.1 { UPDATE t11_stat SET value = X'0000'; } +do_catchsql_test 8.5.1.2 { + SELECT mit(matchinfo(t11, 'nxa')) FROM t11 WHERE t11 MATCH 'a*' +} {1 {database disk image is malformed}} + +do_execsql_test 8.4.2.1 { UPDATE t11_stat SET value = X'00'; } +do_catchsql_test 8.5.2.2 { + SELECT mit(matchinfo(t11, 'nxa')) FROM t11 WHERE t11 MATCH 'a*' +} {1 {database disk image is malformed}} + +do_execsql_test 8.4.3.1 { UPDATE t11_stat SET value = NULL; } +do_catchsql_test 8.5.3.2 { + SELECT mit(matchinfo(t11, 'nxa')) FROM t11 WHERE t11 MATCH 'a*' +} {1 {database disk image is malformed}} + +#------------------------------------------------------------------------- +do_execsql_test 8.1 { + CREATE VIRTUAL TABLE t12 USING fts4; + INSERT INTO t12 VALUES('a b c d'); + SELECT mit(matchinfo(t12, 'x')) FROM t12 WHERE t12 MATCH 'a NEAR/1 d OR a'; +} {{0 0 0 0 0 0 1 1 1}} +do_execsql_test 8.2 { + INSERT INTO t12 VALUES('a d c d'); + SELECT mit(matchinfo(t12, 'x')) FROM t12 WHERE t12 MATCH 'a NEAR/1 d OR a'; +} { + {0 1 1 0 1 1 1 2 2} {1 1 1 1 1 1 1 2 2} +} +do_execsql_test 8.3 { + INSERT INTO t12 VALUES('a d d a'); + SELECT mit(matchinfo(t12, 'x')) FROM t12 WHERE t12 MATCH 'a NEAR/1 d OR a'; +} { + {0 3 2 0 3 2 1 4 3} {1 3 2 1 3 2 1 4 3} {2 3 2 2 3 2 2 4 3} +} + +do_execsql_test 9.1 { + CREATE VIRTUAL TABLE ft2 USING fts4; + INSERT INTO ft2 VALUES('a b c d e'); + INSERT INTO ft2 VALUES('f a b c d'); + SELECT snippet(ft2, '[', ']', '', -1, 1) FROM ft2 WHERE ft2 MATCH 'c'; +} {{[c]} {[c]}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3near.test b/components/external/SQLite-3.8.1/test/fts3near.test new file mode 100644 index 0000000000000000000000000000000000000000..9276fa3737723544863bc8df75dd5fc9382399dd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3near.test @@ -0,0 +1,598 @@ + +# 2007 October 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# +# $Id: fts3near.test,v 1.3 2009/01/02 17:33:46 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +db eval { + CREATE VIRTUAL TABLE t1 USING fts3(content); + INSERT INTO t1(content) VALUES('one three four five'); + INSERT INTO t1(content) VALUES('two three four five'); + INSERT INTO t1(content) VALUES('one two three four five'); +} + +do_test fts3near-1.1 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR/0 three'} +} {1} +do_test fts3near-1.2 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR/1 two'} +} {3} +do_test fts3near-1.3 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR/1 three'} +} {1 3} +do_test fts3near-1.4 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'three NEAR/1 one'} +} {1 3} +do_test fts3near-1.5 { + execsql {SELECT docid FROM t1 WHERE content MATCH '"one two" NEAR/1 five'} +} {} +do_test fts3near-1.6 { + execsql {SELECT docid FROM t1 WHERE content MATCH '"one two" NEAR/2 five'} +} {3} +do_test fts3near-1.7 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR four'} +} {1 3} +do_test fts3near-1.8 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'four NEAR three'} +} {1 2 3} +do_test fts3near-1.9 { + execsql {SELECT docid FROM t1 WHERE content MATCH '"four five" NEAR/0 three'} +} {1 2 3} +do_test fts3near-1.10 { + execsql {SELECT docid FROM t1 WHERE content MATCH '"four five" NEAR/2 one'} +} {1 3} +do_test fts3near-1.11 { + execsql {SELECT docid FROM t1 WHERE content MATCH '"four five" NEAR/1 one'} +} {1} +do_test fts3near-1.12 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'five NEAR/1 "two three"'} +} {2 3} +do_test fts3near-1.13 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR five'} +} {1 3} + +do_test fts3near-1.14 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'four NEAR four'} +} {} +do_test fts3near-1.15 { + execsql {SELECT docid FROM t1 WHERE content MATCH 'one NEAR two NEAR one'} +} {3} + +do_test fts3near-1.16 { + execsql { + SELECT docid FROM t1 WHERE content MATCH '"one three" NEAR/0 "four five"' + } +} {1} +do_test fts3near-1.17 { + execsql { + SELECT docid FROM t1 WHERE content MATCH '"four five" NEAR/0 "one three"' + } +} {1} + + +# Output format of the offsets() function: +# +# +# +db eval { + INSERT INTO t1(content) VALUES('A X B C D A B'); +} +do_test fts3near-2.1 { + execsql { + SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR/0 B' + } +} {{0 0 10 1 0 1 12 1}} +do_test fts3near-2.2 { + execsql { + SELECT offsets(t1) FROM t1 WHERE content MATCH 'B NEAR/0 A' + } +} {{0 1 10 1 0 0 12 1}} +do_test fts3near-2.3 { + execsql { + SELECT offsets(t1) FROM t1 WHERE content MATCH '"C D" NEAR/0 A' + } +} {{0 0 6 1 0 1 8 1 0 2 10 1}} +do_test fts3near-2.4 { + execsql { + SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR/0 "C D"' + } +} {{0 1 6 1 0 2 8 1 0 0 10 1}} +do_test fts3near-2.5 { + execsql { + SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR A' + } +} {{0 0 0 1 0 1 0 1 0 0 10 1 0 1 10 1}} +do_test fts3near-2.6 { + execsql { + INSERT INTO t1 VALUES('A A A'); + SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR/2 A'; + } +} [list [list 0 0 0 1 0 1 0 1 0 0 2 1 0 1 2 1 0 0 4 1 0 1 4 1]] +do_test fts3near-2.7 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES('A A A A'); + SELECT offsets(t1) FROM t1 WHERE content MATCH 'A NEAR A NEAR A'; + } +} [list [list \ + 0 0 0 1 0 1 0 1 0 2 0 1 0 0 2 1 \ + 0 1 2 1 0 2 2 1 0 0 4 1 0 1 4 1 \ + 0 2 4 1 0 0 6 1 0 1 6 1 0 2 6 1 \ +]] + +db eval { + DELETE FROM t1; + INSERT INTO t1(content) VALUES( + 'one two three two four six three six nine four eight twelve' + ); +} + +do_test fts3near-3.1 { + execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'three NEAR/1 one'} +} {{0 1 0 3 0 0 8 5}} +do_test fts3near-3.2 { + execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'one NEAR/1 three'} +} {{0 0 0 3 0 1 8 5}} +do_test fts3near-3.3 { + execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'three NEAR/1 two'} +} {{0 1 4 3 0 0 8 5 0 1 14 3}} +do_test fts3near-3.4 { + execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'three NEAR/2 two'} +} {{0 1 4 3 0 0 8 5 0 1 14 3 0 0 27 5}} +do_test fts3near-3.5 { + execsql {SELECT offsets(t1) FROM t1 WHERE content MATCH 'two NEAR/2 three'} +} {{0 0 4 3 0 1 8 5 0 0 14 3 0 1 27 5}} +do_test fts3near-3.6 { + execsql { + SELECT offsets(t1) FROM t1 WHERE content MATCH 'three NEAR/0 "two four"' + } +} {{0 0 8 5 0 1 14 3 0 2 18 4}} +breakpoint +do_test fts3near-3.7 { + execsql { + SELECT offsets(t1) FROM t1 WHERE content MATCH '"two four" NEAR/0 three'} +} {{0 2 8 5 0 0 14 3 0 1 18 4}} + +db eval { + INSERT INTO t1(content) VALUES(' + This specification defines Cascading Style Sheets, level 2 (CSS2). CSS2 is a style sheet language that allows authors and users to attach style (e.g., fonts, spacing, and aural cues) to structured documents (e.g., HTML documents and XML applications). By separating the presentation style of documents from the content of documents, CSS2 simplifies Web authoring and site maintenance. + + CSS2 builds on CSS1 (see [CSS1]) and, with very few exceptions, all valid CSS1 style sheets are valid CSS2 style sheets. CSS2 supports media-specific style sheets so that authors may tailor the presentation of their documents to visual browsers, aural devices, printers, braille devices, handheld devices, etc. This specification also supports content positioning, downloadable fonts, table layout, features for internationalization, automatic counters and numbering, and some properties related to user interface. + ') +} +do_test fts3near-4.1 { + execsql { + SELECT snippet(t1) FROM t1 WHERE content MATCH 'specification NEAR supports' + } +} {{...braille devices, handheld devices, etc. This specification also supports content positioning, downloadable fonts, table layout...}} + +do_test fts3near-5.1 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'specification attach' + } +} {2} +do_test fts3near-5.2 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'specification NEAR attach' + } +} {} +do_test fts3near-5.3 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'specification NEAR/18 attach' + } +} {} +do_test fts3near-5.4 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'specification NEAR/19 attach' + } +} {2} +do_test fts3near-5.5 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'specification NEAR/000018 attach' + } +} {} +do_test fts3near-5.6 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'specification NEAR/000019 attach' + } +} {2} + +db eval { + INSERT INTO t1 VALUES(' + abbrev aberrations abjurations aboding abr abscesses absolutistic + abstention abuses acanthuses acceptance acclaimers accomplish + accoutring accusation acetonic acid acolytes acquitting acrylonitrile + actives acyclic addicted adenoid adjacently adjusting admissible + adoption adulated advantaging advertisers aedes aerogramme aetiology + affiliative afforest afterclap agamogenesis aggrade agings agonize + agron ailurophile airfreight airspeed alarmists alchemizing + alexandrines alien aliped all allergenic allocator allowances almost + alphabetizes altho alvine amaurosis ambles ameliorate amicability amnio + amour ampicillin amusement anadromous analogues anarchy anchormen + anecdota aneurin angst animating anlage announcements anodized + answerable antemeridian anthracene antiabortionist anticlimaxes + antifriction antimitotic antiphon antiques antithetic anviled + apatosaurus aphrodisia apodal aposiopesis apparatus appendectomies + applications appraisingly appropriate apteryx arabinose + arboricultural archdeaconates archipelago ardently arguers armadillo + arnicas arrayed arrowy arthroscope artisans ascensive ashier + aspersorium assail assentor assignees assonants astereognosis + astringency astutest atheistical atomize attachment attenuates + attrahent audibility augite auricle auteurists autobus autolysis + autosome avenge avidest aw awl ayes babirusa backbeats backgrounder + backseat backswings baddie bagnios baked balefuller ballista balmily + bandbox bandylegged bankruptcy baptism barbering bargain barneys + barracuda barterer bashes bassists bathers batterer bavardage + beachfront beanstalk beauteous become bedim bedtimes beermats begat + begun belabors bellarmine belongings bending benthos bereavements + besieger bestialized betide bevels biases bicarbonates bidentate bigger + bile billow bine biodynamics biomedicine biotites birding bisection + bitingly bkg blackheads blaeberry blanking blatherer bleeper blindage + blithefulness blockish bloodstreams bloused blubbing bluestocking + blurted boatbill bobtailed boffo bold boltrope bondservant bonks + bookbinding bookworm booting borating boscages botchers bougainvillea + bounty bowlegged boyhood bracketed brainstorm brandishes + braunschweigers brazilin breakneck breathlessness brewage bridesmaids + brighter brisker broader brokerages bronziest browband brunets bryology + bucking budlike bugleweed bulkily bulling bummer bunglers bureau burgs + burrito bushfire buss butlery buttressing bylines cabdriver cached + cadaverousnesses cafeterias cakewalk calcifies calendula callboy calms + calyptra camisoles camps candelabrum caned cannolis canoodling cantors + cape caponize capsuling caracoled carbolics carcase carditis caretakers + carnallite carousel carrageenan cartels carves cashbook castanets + casuistry catalyzer catchers categorizations cathexis caucuses + causeway cavetto cede cella cementite centenary centrals ceramics ceria + cervixes chafferer chalcopyrites chamfers change chaotically + characteristically charivari chases chatterer cheats cheeks chef + chemurgy chetah chickaree chigoes chillies chinning chirp chive + chloroforms chokebore choplogic chorioids chromatic chronically + chubbiest chunder chutzpah cimetidine cinque circulated circumscribe + cirrose citrin claddagh clamorousness clapperboards classicalism + clauses cleanse clemency clicker clinchers cliquiest clods closeting + cloudscape clucking cnidarian coalfish coatrack coca cockfights coddled + coeducation coexistence cognitively coiffed colatitude collage + collections collinear colonelcy colorimetric columelliform combos + comforters commence commercialist commit commorancy communized compar + compendiously complainers compliance composition comprised comradery + concelebrants concerted conciliation concourses condensate + condonations confab confessionals confirmed conforming congeal + congregant conjectured conjurers connoisseurs conscripting + conservator consolable conspired constricting consuls contagious + contemporaneity contesters continuities contractors contrarian + contrive convalescents convents convexly convulsed cooncan coparcenary + coprolite copyreader cordially corklike cornflour coroner corralling + corrigible corsages cosies cosmonauts costumer cottontails counselings + counterclaim counterpane countertenors courageously couth coveting + coworker cozier cracklings crampon crappies craved cream credenzas + crematoriums cresol cricoid crinkle criterion crocodile crore crossover + crowded cruelest crunch cruzeiros cryptomeria cubism cuesta culprit + cumquat cupped curdle curly cursoring curvy customized cutting cyclamens + cylindrical cytaster dachshund daikon damages damselfly dangling + darkest databanks dauphine dazzling deadpanned deathday debauchers + debunking decameter decedents decibel decisions declinations + decomposition decoratively decretive deduct deescalated defecating + deferentially definiendum defluxion defrocks degrade deice dekaliters + deli delinquencies deludedly demarcates demineralizers demodulating + demonstrabilities demurred deniabilities denouncement denudation + departure deplorable deposing depredatory deputizes derivational + desalinization descriptors desexes desisted despising destitute + detectability determiner detoxifying devalued devilries devotions + dextrous diagenesis dialling diaphoresis diazonium dickeys diddums + differencing dig dignified dildo dimetric dineric dinosaurs diplodocus + directer dirty disagrees disassembler disburses disclosures + disconcerts discountability discrete disembarrass disenthrone + disgruntled dishpans disintegrators dislodged disobedient + dispassionate dispiritednesses dispraised disqualifying + dissatisfying dissidence dissolvers distich distracting distrusts + ditto diverse divineness dizzily dockyard dodgers doggish doited dom + dominium doohickey doozie dorsum doubleheaders dourer downbeats + downshifted doyennes draftsman dramatic drawling dredge drifter + drivelines droopier drowsed drunkards dubiosities duding dulcifying + dumpcart duodecillion durable duteous dyed dysgenic eagles earplugs + earwitness ebonite echoers economical ectothermous edibility educates + effected effigies eggbeaters egresses ejaculates elasticize elector + electrodynamometer electrophorus elem eligibly eloped emaciating + embarcaderos embezzlers embosses embryectomy emfs emotionalizing + empiricist emu enamels enchained encoded encrusts endeavored endogamous + endothelioma energizes engager engrosses enl enologist enrolls ensphere + enters entirety entrap entryways envies eosinophil epicentral + epigrammatized episodic epochs equestrian equitably erect ernes + errorless escalated eschatology espaliers essonite estop eternity + ethnologically eudemonics euphonious euthenist evangelizations + eventuality evilest evulsion examinee exceptionably exciter + excremental execrably exemplars exhalant exhorter exocrine exothermic + expected expends explainable exploratory expostulatory expunges + extends externals extorts extrapolative extrorse eyebolt eyra + facetiously factor faeries fairings fallacies falsities fancifulness + fantasticalness farmhouse fascinate fatalistically fattener fave + fearlessly featly federates feints fellowman fencers ferny + fertilenesses feta feudality fibers fictionalize fiefs fightback + filefish filmier finaglers fingerboards finochio firefly firmament + fishmeal fitted fjords flagitiousnesses flamen flaps flatfooting + flauntier fleapit fleshes flickertail flints floaty floorboards + floristic flow fluffily fluorescein flutes flyspecks foetal folderols + followable foolhardier footlockers foppish forceless foredo foreknows + foreseeing foretaste forgather forlorn formidableness fortalice + forwarding founding foxhunting fragmentarily frangipani fray freeform + freezable freshening fridges frilliest frizzed frontbench frottages + fruitcake fryable fugleman fulminated functionalists fungoid furfuran + furtive fussy fwd gadolinium galabias gallinaceous galvanism gamers + gangland gaoling garganey garrisoning gasp gate gauger gayety geed + geminately generalissimos genii gentled geochronology geomorphic + geriatricians gesellschaft ghat gibbeting giggles gimps girdlers + glabella glaive glassfuls gleefully glistered globetrotted glorifier + gloving glutathione glyptodont goaled gobsmacked goggliest golliwog + goobers gooseberries gormandizer gouramis grabbier gradually grampuses + grandmothers granulated graptolite gratuitously gravitates greaten + greenmailer greys grills grippers groan gropingly grounding groveling + grueled grunter guardroom guggle guineas gummed gunnysacks gushingly + gutturals gynecoid gyrostabilizer habitudes haemophilia hailer hairs + halest hallow halters hamsters handhelds handsaw hangup haranguer + hardheartedness harlotry harps hashing hated hauntingly hayrack + headcases headphone headword heartbreakers heaters hebephrenia + hedonist heightening heliozoan helots hemelytron hemorrhagic hent + herbicides hereunto heroines heteroclitics heterotrophs hexers + hidebound hies hightails hindmost hippopotomonstrosesquipedalian + histologist hittable hobbledehoys hogans holdings holocrine homegirls + homesteader homogeneousness homopolar honeys hoodwinks hoovered + horizontally horridness horseshoers hospitalization hotdogging houri + housemate howitzers huffier humanist humid humors huntress husbandmen + hyaenas hydride hydrokinetics hydroponically hygrothermograph + hyperbolically hypersensitiveness hypnogogic hypodermically + hypothermia iatrochemistry ichthyological idealist ideograms idling + igniting illegal illuminatingly ilmenite imbibing immateriality + immigrating immortalizes immures imparts impeder imperfection + impersonated implant implying imposition imprecating imprimis + improvising impv inanenesses inaugurate incapably incentivize + incineration incloses incomparableness inconsequential incorporate + incrementing incumbered indecorous indentation indicative indignities + indistinguishably indoors indulges ineducation inerrable + inexperienced infants infestations infirmnesses inflicting + infracostal ingathered ingressions inheritances iniquity + injuriousnesses innervated inoculates inquisitionist insectile + insiders insolate inspirers instatement instr insulates intactness + intellects intensifies intercalations intercontinental interferon + interlarded intermarrying internalizing interpersonally + interrelatednesses intersperse interviewees intolerance + intransigents introducing intubates invades inventing inveterate + invocate iodides irenicism ironsmith irreducibly irresistibility + irriguous isobarisms isometrically issuable itineracies jackdaws + jaggery jangling javelins jeeringly jeremiad jeweler jigsawing jitter + jocosity jokester jot jowls judicative juicy jungly jurists juxtaposed + kalpa karstify keddah kendo kermesses keynote kibbutznik kidnaper + kilogram kindred kingpins kissers klatch kneads knobbed knowingest + kookaburras kruller labefaction labyrinths lacquer laddered lagoons + lambency laminates lancinate landscapist lankiness lapse larked lasso + laterite laudableness laundrywomen lawgiver laypersons leafhoppers + leapfrogs leaven leeches legated legislature leitmotifs lenients + leprous letterheads levelling lexicographically liberalists + librettist licorice lifesaving lightheadedly likelier limekiln limped + lines linkers lipoma liquidator listeners litharge litmus + liverishnesses loamier lobeline locative locutionary loggier loiterer + longevity loomed loping lotion louts lowboys luaus lucrativeness lulus + lumpier lungi lush luthern lymphangial lythraceous machinists maculate + maggot magnetochemistry maharani maimers majored malaprops malignants + maloti mammary manchineel manfully manicotti manipulativenesses + mansards manufactories maraschino margin markdown marooning marshland + mascaraing massaging masticate matchmark matings mattes mausoleum + mayflies mealworm meataxe medevaced medievalist meetings megavitamin + melded melodramatic memorableness mendaciousnesses mensurable + mercenaries mere meronymous mesmerizes mestee metallurgical + metastasize meterages meticulosity mewed microbe microcrystalline + micromanager microsporophyll midiron miffed milder militiamen + millesimal milometer mincing mingily minims minstrelsy mires + misanthropic miscalculate miscomprehended misdefines misery mishears + misled mispickel misrepresent misspending mistranslate miswriting + mixologists mobilizers moderators modulate mojo mollies momentum monde + monied monocles monographs monophyletic monotonousness moocher + moorages morality morion mortally moseyed motherly motorboat mouldering + mousers moveables mucky mudslides mulatto multicellularity + multipartite multivalences mundanities murkiest mushed muskiness + mutability mutisms mycelia myosotis mythicist nacred namable napkin + narghile nastiness nattering nauseations nearliest necessitate + necrophobia neg negotiators neologizes nephrotomy netiquette + neurophysiology newbie newspaper niccolite nielsbohriums nightlong + nincompoops nitpicked nix noddling nomadize nonadhesive noncandidates + nonconducting nondigestible nones nongreasy nonjoinder nonoccurrence + nonporousness nonrestrictive nonstaining nonuniform nooses northwards + nostalgic notepaper nourishment noyades nuclides numberless numskulls + nutmegged nymphaea oatmeal obis objurgators oblivious obsequiousness + obsoletism obtruding occlusions ocher octettes odeums offcuts + officiation ogival oilstone olestras omikron oncogenesis onsetting + oomphs openly ophthalmoscope opposites optimum orangutans + orchestrations ordn organophosphates origin ornithosis orthognathous + oscillatory ossuaries ostracized ounce outbreaks outearning outgrows + outlived outpoints outrunning outspends outwearing overabound + overbalance overcautious overcrowds overdubbing overexpanding + overgraze overindustrialize overlearning overoptimism overproducing + overripe overshadowing overspreading overstuff overtones overwind ow + oxidizing pacer packs paganish painstakingly palate palette pally + palsying pandemic panhandled pantheism papaws papped parading + parallelize paranoia parasitically pardners parietal parodied pars + participator partridgeberry passerines password pastors + paterfamiliases patination patrolman paunch pawnshops peacekeeper + peatbog peculator pedestrianism peduncles pegboard pellucidnesses + pendency penitentiary penstock pentylenetetrazol peptidase perched + perennial performing perigynous peripheralize perjurer permissively + perpetuals persistency perspicuously perturbingly pesky petcock + petrologists pfennige pharmacies phenformin philanderers + philosophically phonecards phosgenes photocomposer photogenic photons + phototype phylloid physiotherapeutics picadores pickup pieces pigging + pilaster pillion pimples pinioned pinpricks pipers pirogi pit + pitifullest pizza placental plainly planing plasmin platforming + playacts playwrights plectra pleurisy plopped plug plumule plussed + poaches poetasters pointless polarize policyholder polkaed + polyadelphous polygraphing polyphonous pomace ponderers pooch poplar + porcelains portableness portly positioning postage posthumously + postponed potages potholed poulard powdering practised pranksters + preadapt preassigning precentors precipitous preconditions predefined + predictors preengage prefers prehumans premedical prenotification + preplanning prepuberty presbytery presentation presidia prestissimo + preterites prevailer prewarmed priding primitively principalships + prisage privileged probed prochurch proctoscope products proficients + prognathism prohibiting proletarianisms prominence promulgates + proofreading property proportions prorate proselytize prosthesis + proteins prototypic provenances provitamin prudish pseudonymities + psychoanalysts psychoneuroses psychrometer publishable pufferies + pullet pulses punchy punkins purchased purities pursers pushover + putridity pylons pyrogenous pzazz quadricepses quaff qualmish quarriers + quasilinear queerness questionnaires quieten quintals quislings quoits + rabidness racketeers radiative radioisotope radiotherapists ragingly + rainband rakishness rampagers rands raped rare raspy ratiocinator + rattlebrain ravening razz reactivation readoption realm reapportioning + reasoning reattempts rebidding rebuts recapitulatory receptiveness + recipes reckonings recognizee recommendatory reconciled reconnoiters + recontaminated recoupments recruits recumbently redact redefine + redheaded redistributable redraw redwing reeled reenlistment reexports + refiles reflate reflowing refortified refried refuses regelate + registrant regretting rehabilitative reigning reinduced reinstalled + reinvesting rejoining relations relegates religiosities reluctivity + remastered reminisce remodifying remounted rends renovate reordered + repartee repel rephrase replicate repossessing reprint reprogramed + repugnantly requiter rescheduling resegregate resettled residually + resold resourcefulness respondent restating restrainedly resubmission + resurveyed retaliating retiarius retorsion retreated retrofitting + returning revanchism reverberated reverted revitalization + revolutionize rewind rhapsodizing rhizogenic rhythms ricketinesses + ridicule righteous rilles rinks rippliest ritualize riyals roast rockery + roguish romanizations rookiest roquelaure rotation rotundity rounder + routinizing rubberize rubricated ruefully ruining rummaged runic + russets ruttish sackers sacrosanctly safeguarding said salaciousness + salinity salsas salutatorians sampan sandbag saned santonin + saprophagous sarnies satem saturant savaged sawbucks scablike scalp + scant scared scatter schedulers schizophrenics schnauzers schoolmarms + scintillae scleroses scoped scotched scram scratchiness screwball + scripting scrubwomen scrutinizing scumbled scuttled seals seasickness + seccos secretions secularizing seditiousnesses seeking segregators + seize selfish semeiology seminarian semitropical sensate sensors + sentimo septicemic sequentially serener serine serums + sesquicentennials seventeen sexiest sforzandos shadowing shallot + shampooing sharking shearer sheered shelters shifter shiner shipper + shitted shoaled shofroth shorebirds shortsightedly showboated shrank + shrines shucking shuttlecocks sickeningly sideling sidewise sigil + signifiers siliceous silty simony simulative singled sinkings sirrah + situps skateboarder sketchpad skim skirmished skulkers skywalk slander + slating sleaziest sleepyheads slicking slink slitting slot slub + slumlords smallest smattered smilier smokers smriti snailfish snatch + snides snitching snooze snowblowers snub soapboxing socialite sockeyes + softest sold solicitings solleret sombreros somnolencies sons sopor + sorites soubrette soupspoon southpaw spaces spandex sparkers spatially + speccing specking spectroscopists speedsters spermatics sphincter + spiffied spindlings spirals spitball splayfeet splitter spokeswomen + spooled sportily spousals sprightliness sprogs spurner squalene + squattered squelches squirms stablish staggerings stalactitic stamp + stands starflower starwort stations stayed steamroll steeplebush + stemmatics stepfathers stereos steroid sticks stillage stinker + stirringly stockpiling stomaching stopcock stormers strabismuses + strainer strappado strawberries streetwise striae strikeouts strives + stroppiest stubbed study stunting style suavity subchloride subdeb + subfields subjoin sublittoral subnotebooks subprograms subside + substantial subtenants subtreasuries succeeding sucked sufferers + sugarier sulfaguanidine sulphating summerhouse sunbonnets sunned + superagency supercontinent superheroes supernatural superscribing + superthin supplest suppositive surcease surfs surprise survey + suspiration svelte swamplands swashes sweatshop swellhead swindling + switching sworn syllabuses sympathetics synchrocyclotron syndic + synonymously syringed tablatures tabulation tackling taiga takas talker + tamarisks tangential tans taproom tarpapers taskmaster tattiest + tautologically taxied teacup tearjerkers technocracies teepee + telegenic telephony telexed temperaments temptress tenderizing tensed + tenuring tergal terned terror testatrices tetherball textile thatched + their theorem thereof thermometers thewy thimerosal thirsty + thoroughwort threateningly thrived through thumbnails thwacks + ticketing tie til timekeepers timorousness tinkers tippers tisane + titrating toastmaster toff toking tomb tongs toolmakings topes topple + torose tortilla totalizing touchlines tousling townsmen trachea + tradeable tragedienne traitorous trances transcendentalists + transferrable tranship translating transmogrifying transportable + transvestism traumatize treachery treed trenail tressing tribeswoman + trichromatism triennials trikes trims triplicate tristich trivializes + trombonist trots trouts trued trunnion tryster tubes tulle tundras turban + turgescence turnround tutelar tweedinesses twill twit tympanum typists + tzarists ulcered ultramodern umbles unaccountability unamended + unassertivenesses unbanned unblocked unbundled uncertified unclaimed + uncoated unconcerns unconvinced uncrossing undefined underbodice + underemphasize undergrowth underpayment undershirts understudy + underwritten undissolved unearthed unentered unexpended unfeeling + unforeseen unfussy unhair unhinges unifilar unimproved uninvitingly + universalization unknowns unlimbering unman unmet unnaturalness + unornament unperturbed unprecedentedly unproportionate unread + unreflecting unreproducible unripe unsatisfying unseaworthiness + unsharable unsociable unstacking unsubtly untactfully untied untruest + unveils unwilled unyokes upheave upraised upstart upwind urethrae + urtexts usurers uvula vacillators vailed validation valvule vanities + varia variously vassaled vav veggies velours venerator ventrals + verbalizes verification vernacularized verticality vestigially via + vicariously victoriousness viewpoint villainies vines violoncellist + virtual viscus vital vitrify viviparous vocalizers voidable volleys + volutes vouches vulcanology wackos waggery wainwrights waling wallowing + wanking wardroom warmup wartiest washwoman watchman watermarks waverer + wayzgoose weariest weatherstripped weediness weevil welcomed + wentletrap whackers wheatworm whelp whf whinged whirl whistles whithers + wholesomeness whosoever widows wikiup willowier windburned windsail + wingspread winterkilled wisecracking witchgrass witling wobbliest + womanliness woodcut woodworking woozy working worldwide worthiest + wrappings wretched writhe wynd xylophone yardarm yea yelped yippee yoni + yuks zealotry zigzagger zitherists zoologists zygosis'); +} + +do_test fts3near-6.1 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'abbrev zygosis' + } +} {3} +do_test fts3near-6.2 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'abbrev NEAR zygosis' + } +} {} +do_test fts3near-6.3 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'abbrev NEAR/100 zygosis' + } +} {} +do_test fts3near-6.4 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'abbrev NEAR/1000 zygosis' + } +} {} +do_test fts3near-6.5 { + execsql { + SELECT docid FROM t1 WHERE content MATCH 'abbrev NEAR/10000 zygosis' + } +} {3} + +# Ticket 38b1ae018f. +# +do_execsql_test fts3near-7.1 { + CREATE VIRTUAL TABLE x USING fts4(y,z); + INSERT INTO x VALUES('aaa bbb ccc ddd', 'bbb ddd aaa ccc'); + SELECT * FROM x where y MATCH 'bbb NEAR/6 aaa'; +} {{aaa bbb ccc ddd} {bbb ddd aaa ccc}} + +do_execsql_test fts3near-7.2 { + CREATE VIRTUAL TABLE t2 USING fts4(a, b); + INSERT INTO t2 VALUES('A B C', 'A D E'); + SELECT * FROM t2 where t2 MATCH 'a:A NEAR E' +} {} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3prefix.test b/components/external/SQLite-3.8.1/test/fts3prefix.test new file mode 100644 index 0000000000000000000000000000000000000000..e7c197da9ddb9cd3e03ab8108e04c3b50db31173 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3prefix.test @@ -0,0 +1,213 @@ +# 2011 May 04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix fts3prefix + +ifcapable !fts3 { + finish_test + return +} + +# This proc tests that the prefixes index appears to represent the same content +# as the terms index. +# +proc fts3_terms_and_prefixes {db tbl prefixlengths} { + + set iIndex 0 + foreach len $prefixlengths { + incr iIndex + $db eval { + DROP TABLE IF EXISTS fts3check1; + DROP TABLE IF EXISTS fts3check2; + } + $db eval "CREATE VIRTUAL TABLE fts3check1 USING fts4term($tbl, 0);" + $db eval "CREATE VIRTUAL TABLE fts3check2 USING fts4term($tbl, $iIndex);" + + $db eval { + DROP TABLE IF EXISTS temp.terms; + DROP TABLE IF EXISTS temp.prefixes; + CREATE TEMP TABLE terms AS SELECT * FROM fts3check1; + CREATE TEMP TABLE prefixes AS SELECT * FROM fts3check2; + CREATE INDEX temp.idx ON prefixes(term); + DROP TABLE fts3check1; + DROP TABLE fts3check2; + } + + set nExpect 0 + $db eval { SELECT term, docid, col, pos FROM temp.terms } a { + if {[string length $a(term)]<$len} continue + incr nExpect + set prefix [string range $a(term) 0 [expr $len-1]] + set r [$db one { + SELECT count(*) FROM temp.prefixes WHERE + term = $prefix AND docid = $a(docid) AND col = $a(col) AND pos = $a(pos) + }] + if {$r != 1} { + error "$t, $a(docid), $a(col), $a(pos)" + } + } + + set nCount [$db one {SELECT count(*) FROM temp.prefixes}] + if {$nCount != $nExpect} { + error "prefixes.count(*) is $nCount expected $nExpect" + } + + execsql { DROP TABLE temp.prefixes } + execsql { DROP TABLE temp.terms } + + set list [list] + $db eval " + SELECT sum( 1 << (16*(level%1024)) ) AS total, (level/1024) AS tree + FROM ${tbl}_segdir GROUP BY tree + " { + lappend list [list $total $tree] + } + + if { [lsort -integer -index 0 $list] != [lsort -integer -index 1 $list] } { + error "inconsistent tree structures: $list" + } + } + + return "" +} +proc fts3_tap_test {tn db tbl lens} { + uplevel [list do_test $tn [list fts3_terms_and_prefixes $db $tbl $lens] ""] +} + +#------------------------------------------------------------------------- +# Test cases 1.* are a sanity check. They test that the prefixes index is +# being constructed correctly for the simplest possible case. +# +do_execsql_test 1.1 { + CREATE VIRTUAL TABLE t1 USING fts4(prefix='1,3,6'); + + CREATE VIRTUAL TABLE p1 USING fts4term(t1, 1); + CREATE VIRTUAL TABLE p2 USING fts4term(t1, 2); + CREATE VIRTUAL TABLE p3 USING fts4term(t1, 3); + CREATE VIRTUAL TABLE terms USING fts4term(t1); +} +do_execsql_test 1.2 { + INSERT INTO t1 VALUES('sqlite mysql firebird'); +} +do_execsql_test 1.3.1 { SELECT term FROM p1 } {f m s} +do_execsql_test 1.3.2 { SELECT term FROM p2 } {fir mys sql} +do_execsql_test 1.3.3 { SELECT term FROM p3 } {firebi sqlite} +do_execsql_test 1.4 { + SELECT term FROM terms; +} {firebird mysql sqlite} + +fts3_tap_test 1.5 db t1 {1 3 6} + +#------------------------------------------------------------------------- +# A slightly more complicated dataset. This test also verifies that DELETE +# operations do not corrupt the prefixes index. +# +do_execsql_test 2.1 { + INSERT INTO t1 VALUES('FTS3 and FTS4 are an SQLite virtual table modules'); + INSERT INTO t1 VALUES('that allows users to perform full-text searches on'); + INSERT INTO t1 VALUES('a set of documents. The most common (and'); + INSERT INTO t1 VALUES('effective) way to describe full-text searches is'); + INSERT INTO t1 VALUES('"what Google, Yahoo and Altavista do with'); + INSERT INTO t1 VALUES('documents placed on the World Wide Web". Users'); + INSERT INTO t1 VALUES('input a term, or series of terms, perhaps'); + INSERT INTO t1 VALUES('connected by a binary operator or grouped together'); + INSERT INTO t1 VALUES('into a phrase, and the full-text query system'); + INSERT INTO t1 VALUES('finds the set of documents that best matches those'); + INSERT INTO t1 VALUES('terms considering the operators and groupings the'); + INSERT INTO t1 VALUES('user has specified. This article describes the'); + INSERT INTO t1 VALUES('deployment and usage of FTS3 and FTS4.'); + INSERT INTO t1 VALUES('FTS1 and FTS2 are obsolete full-text search'); + INSERT INTO t1 VALUES('modules for SQLite. There are known issues with'); + INSERT INTO t1 VALUES('these older modules and their use should be'); + INSERT INTO t1 VALUES('avoided. Portions of the original FTS3 code were'); + INSERT INTO t1 VALUES('contributed to the SQLite project by Scott Hess of'); + INSERT INTO t1 VALUES('Google. It is now developed and maintained as part'); + INSERT INTO t1 VALUES('of SQLite. '); +} +fts3_tap_test 2.2 db t1 {1 3 6} +do_execsql_test 2.3 { DELETE FROM t1 WHERE docid%2; } +fts3_tap_test 2.4 db t1 {1 3 6} + +do_execsql_test 2.5 { INSERT INTO t1(t1) VALUES('optimize') } +fts3_tap_test 2.6 db t1 {1 3 6} + +do_execsql_test 3.1 { + CREATE VIRTUAL TABLE t2 USING fts4(prefix='1,2,3'); + INSERT INTO t2 VALUES('On 12 September the wind direction turned and'); + INSERT INTO t2 VALUES('William''s fleet sailed. A storm blew up and the'); + INSERT INTO t2 VALUES('fleet was forced to take shelter at'); + INSERT INTO t2 VALUES('Saint-Valery-sur-Somme and again wait for the wind'); + INSERT INTO t2 VALUES('to change. On 27 September the Norman fleet'); + INSERT INTO t2 VALUES('finally set sail, landing in England at Pevensey'); + INSERT INTO t2 VALUES('Bay (Sussex) on 28 September. William then moved'); + INSERT INTO t2 VALUES('to Hastings, a few miles to the east, where he'); + INSERT INTO t2 VALUES('built a prefabricated wooden castle for a base of'); + INSERT INTO t2 VALUES('operations. From there, he ravaged the hinterland'); + INSERT INTO t2 VALUES('and waited for Harold''s return from the north.'); + INSERT INTO t2 VALUES('On 12 September the wind direction turned and'); + INSERT INTO t2 VALUES('William''s fleet sailed. A storm blew up and the'); + INSERT INTO t2 VALUES('fleet was forced to take shelter at'); + INSERT INTO t2 VALUES('Saint-Valery-sur-Somme and again wait for the wind'); + INSERT INTO t2 VALUES('to change. On 27 September the Norman fleet'); + INSERT INTO t2 VALUES('finally set sail, landing in England at Pevensey'); + INSERT INTO t2 VALUES('Bay (Sussex) on 28 September. William then moved'); + INSERT INTO t2 VALUES('to Hastings, a few miles to the east, where he'); + INSERT INTO t2 VALUES('built a prefabricated wooden castle for a base of'); + INSERT INTO t2 VALUES('operations. From there, he ravaged the hinterland'); + INSERT INTO t2 VALUES('and waited for Harold''s return from the north.'); +} + +fts3_tap_test 3.2 db t2 {1 2 3} +do_execsql_test 3.3 { SELECT optimize(t2) FROM t2 LIMIT 1 } {{Index optimized}} +fts3_tap_test 3.4 db t2 {1 2 3} + + +#------------------------------------------------------------------------- +# Simple tests for reading the prefix-index. +# +do_execsql_test 4.1 { + CREATE VIRTUAL TABLE t3 USING fts4(prefix="1,4"); + INSERT INTO t3 VALUES('one two three'); + INSERT INTO t3 VALUES('four five six'); + INSERT INTO t3 VALUES('seven eight nine'); +} +do_execsql_test 4.2 { + SELECT * FROM t3 WHERE t3 MATCH 'f*' +} {{four five six}} +do_execsql_test 4.3 { + SELECT * FROM t3 WHERE t3 MATCH 'four*' +} {{four five six}} +do_execsql_test 4.4 { + SELECT * FROM t3 WHERE t3 MATCH 's*' +} {{four five six} {seven eight nine}} +do_execsql_test 4.5 { + SELECT * FROM t3 WHERE t3 MATCH 'sev*' +} {{seven eight nine}} +do_execsql_test 4.6 { + SELECT * FROM t3 WHERE t3 MATCH 'one*' +} {{one two three}} + +#------------------------------------------------------------------------- +# Syntax tests. +# +do_catchsql_test 5.1 { + CREATE VIRTUAL TABLE t4 USING fts4(prefix="abc"); +} {1 {error parsing prefix parameter: abc}} +do_catchsql_test 5.2 { + CREATE VIRTUAL TABLE t4 USING fts4(prefix=""); +} {0 {}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3prefix2.test b/components/external/SQLite-3.8.1/test/fts3prefix2.test new file mode 100644 index 0000000000000000000000000000000000000000..e033fb6bcb82e2158c7ed1eb0af77786bd695813 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3prefix2.test @@ -0,0 +1,61 @@ +# 2012 January 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix fts3prefix2 + +ifcapable !fts3 { + finish_test + return +} + +do_execsql_test 1.0 { PRAGMA page_size = 512 } +do_execsql_test 1.1 { + CREATE VIRTUAL TABLE t1 USING fts4(x, prefix="2,3"); + + BEGIN; + INSERT INTO t1 VALUES('T TX T TX T TX T TX T TX'); + INSERT INTO t1 SELECT * FROM t1; -- 2 + INSERT INTO t1 SELECT * FROM t1; -- 4 + INSERT INTO t1 SELECT * FROM t1; -- 8 + INSERT INTO t1 SELECT * FROM t1; -- 16 + INSERT INTO t1 SELECT * FROM t1; -- 32 + INSERT INTO t1 SELECT * FROM t1; -- 64 + INSERT INTO t1 SELECT * FROM t1; -- 128 + INSERT INTO t1 SELECT * FROM t1; -- 256 + INSERT INTO t1 SELECT * FROM t1; -- 512 + INSERT INTO t1 SELECT * FROM t1; -- 1024 + INSERT INTO t1 SELECT * FROM t1; -- 2048 + COMMIT; +} + +do_execsql_test 1.2 { + INSERT INTO t1 SELECT * FROM t1 LIMIT 10; + INSERT INTO t1 SELECT * FROM t1 LIMIT 10; + INSERT INTO t1 SELECT * FROM t1 LIMIT 10; + DELETE FROM t1 WHERE docid > 5; +} + +do_execsql_test 1.3 { + SELECT * FROM t1 WHERE t1 MATCH 'T*'; +} { + {T TX T TX T TX T TX T TX} + {T TX T TX T TX T TX T TX} + {T TX T TX T TX T TX T TX} + {T TX T TX T TX T TX T TX} + {T TX T TX T TX T TX T TX} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3query.test b/components/external/SQLite-3.8.1/test/fts3query.test new file mode 100644 index 0000000000000000000000000000000000000000..2d12351ae98053c1a16220dfa05d025ca9403da3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3query.test @@ -0,0 +1,212 @@ +# 2009 December 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests of fts3 queries that have been useful during +# the development process as well as some that have been useful in tracking +# down bugs. They are not focused on any particular functionality. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If this build does not include FTS3, skip the tests in this file. +# +ifcapable !fts3 { finish_test ; return } +source $testdir/malloc_common.tcl +source $testdir/fts3_common.tcl +set DO_MALLOC_TEST 0 + +set testprefix fts3query + +do_test fts3query-1.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts3(x); + BEGIN; + INSERT INTO t1 VALUES('The source code for SQLite is in the public'); + } +} {} + +do_select_test fts3query-1.2 { + SELECT * FROM t1; +} {{The source code for SQLite is in the public}} +do_select_test fts3query-1.3 { + SELECT * FROM t1 WHERE t1 MATCH 'sqlite' +} {{The source code for SQLite is in the public}} + +do_test fts3query-1.4 { execsql {COMMIT} } {} + +do_select_test fts3query-1.5 { + SELECT * FROM t1; +} {{The source code for SQLite is in the public}} +do_select_test fts3query-1.6 { + SELECT * FROM t1 WHERE t1 MATCH 'sqlite' +} {{The source code for SQLite is in the public}} + + +set sqlite_fts3_enable_parentheses 1 +do_test fts3query-2.1 { + execsql { + CREATE VIRTUAL TABLE zoink USING fts3; + INSERT INTO zoink VALUES('The apple falls far from the tree'); + } +} {} +do_test fts3query-2.2 { + execsql { + SELECT docid FROM zoink WHERE zoink MATCH '(apple oranges) AND apple' + } +} {} +do_test fts3query-2.3 { + execsql { + SELECT docid FROM zoink WHERE zoink MATCH 'apple AND (oranges apple)' + } +} {} +set sqlite_fts3_enable_parentheses 0 + +do_test fts3query-3.1 { + execsql { + CREATE VIRTUAL TABLE foobar using FTS3(description, tokenize porter); + INSERT INTO foobar (description) values (' + Filed under: Emerging Technologies, EV/Plug-in, Hybrid, Chevrolet, GM, + ZENN 2011 Chevy Volt - Click above for high-res image gallery There are + 16 days left in the month of December. Besides being time for most + Americans to kick their Christmas shopping sessions into high gear and + start planning their resolutions for 2010, it also means that there''s + precious little time for EEStor to "deliver functional technology" to + Zenn Motors as promised. Still, the promises held out by the secretive + company are too great for us to forget about entirely. We''d love for + EEStor''s claims to be independently verified and proven accurate, as + would just about anyone else looking to break free of petroleum in fav + '); + } +} {} + +do_test fts3query-3.2 { + execsql { SELECT docid FROM foobar WHERE description MATCH '"high sp d"' } +} {} + +proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r +} +db func mit mit + +do_test fts3query-3.3 { + execsql { SELECT mit(matchinfo(foobar)) FROM foobar WHERE foobar MATCH 'the' } +} {{1 1 3 3 1}} + +# The following tests check that ticket 775b39dd3c has been fixed. +# +do_test fts3query-4.1 { + execsql { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(number INTEGER PRIMARY KEY, date); + CREATE INDEX i1 ON t1(date); + CREATE VIRTUAL TABLE ft USING fts3(title); + CREATE TABLE bt(title); + } +} {} +do_eqp_test fts3query-4.2 { + SELECT t1.number FROM t1, ft WHERE t1.number=ft.rowid ORDER BY t1.date +} { + 0 0 0 {SCAN TABLE t1 USING COVERING INDEX i1} + 0 1 1 {SCAN TABLE ft VIRTUAL TABLE INDEX 1:} +} +do_eqp_test fts3query-4.3 { + SELECT t1.number FROM ft, t1 WHERE t1.number=ft.rowid ORDER BY t1.date +} { + 0 0 1 {SCAN TABLE t1 USING COVERING INDEX i1} + 0 1 0 {SCAN TABLE ft VIRTUAL TABLE INDEX 1:} +} +do_eqp_test fts3query-4.4 { + SELECT t1.number FROM t1, bt WHERE t1.number=bt.rowid ORDER BY t1.date +} { + 0 0 0 {SCAN TABLE t1 USING COVERING INDEX i1} + 0 1 1 {SEARCH TABLE bt USING INTEGER PRIMARY KEY (rowid=?)} +} +do_eqp_test fts3query-4.5 { + SELECT t1.number FROM bt, t1 WHERE t1.number=bt.rowid ORDER BY t1.date +} { + 0 0 1 {SCAN TABLE t1 USING COVERING INDEX i1} + 0 1 0 {SEARCH TABLE bt USING INTEGER PRIMARY KEY (rowid=?)} +} + + +# Test that calling matchinfo() with the wrong number of arguments, or with +# an invalid argument returns an error. +# +do_execsql_test 5.1 { + CREATE VIRTUAL TABLE t2 USING FTS4; + INSERT INTO t2 VALUES('it was the first time in history'); +} +do_select_tests 5.2 -errorformat { + wrong number of arguments to function %s() +} { + 1 "SELECT matchinfo() FROM t2 WHERE t2 MATCH 'history'" matchinfo + 3 "SELECT snippet(t2, 1, 2, 3, 4, 5, 6) FROM t2 WHERE t2 MATCH 'history'" + snippet +} +do_select_tests 5.3 -errorformat { + illegal first argument to %s +} { + 1 "SELECT matchinfo(content) FROM t2 WHERE t2 MATCH 'history'" matchinfo + 2 "SELECT offsets(content) FROM t2 WHERE t2 MATCH 'history'" offsets + 3 "SELECT snippet(content) FROM t2 WHERE t2 MATCH 'history'" snippet + 4 "SELECT optimize(content) FROM t2 WHERE t2 MATCH 'history'" optimize +} +do_execsql_test 5.4.0 { UPDATE t2_content SET c0content = X'1234' } +do_select_tests 5.4 -errorformat { + illegal first argument to %s +} { + 1 "SELECT matchinfo(content) FROM t2 WHERE t2 MATCH 'history'" matchinfo + 2 "SELECT offsets(content) FROM t2 WHERE t2 MATCH 'history'" offsets + 3 "SELECT snippet(content) FROM t2 WHERE t2 MATCH 'history'" snippet + 4 "SELECT optimize(content) FROM t2 WHERE t2 MATCH 'history'" optimize +} +do_catchsql_test 5.5.1 { + SELECT matchinfo(t2, 'abc') FROM t2 WHERE t2 MATCH 'history' +} {1 {unrecognized matchinfo request: b}} + +do_execsql_test 5.5 { DROP TABLE t2 } + + +# Test the snippet() function with 1 to 6 arguments. +# +do_execsql_test 6.1 { + CREATE VIRTUAL TABLE t3 USING FTS4(a, b); + INSERT INTO t3 VALUES('no gestures', 'another intriguing discovery by observing the hand gestures (called beats) people make while speaking. Research has shown that such gestures do more than add visual emphasis to our words (many people gesture while they''re on the telephone, for example); it seems they actually help our brains find words'); +} +do_select_tests 6.2 { + 1 "SELECT snippet(t3) FROM t3 WHERE t3 MATCH 'gestures'" + {{...hand gestures (called beats) people make while speaking. Research has shown that such gestures do...}} + + 2 "SELECT snippet(t3, 'XXX') FROM t3 WHERE t3 MATCH 'gestures'" + {{...hand XXXgestures
    (called beats) people make while speaking. Research has shown that such XXXgestures
    do...}} + + 3 "SELECT snippet(t3, 'XXX', 'YYY') FROM t3 WHERE t3 MATCH 'gestures'" + {{...hand XXXgesturesYYY (called beats) people make while speaking. Research has shown that such XXXgesturesYYY do...}} + + 4 "SELECT snippet(t3, 'XXX', 'YYY', 'ZZZ') FROM t3 WHERE t3 MATCH 'gestures'" + {{ZZZhand XXXgesturesYYY (called beats) people make while speaking. Research has shown that such XXXgesturesYYY doZZZ}} + + 5 "SELECT snippet(t3, 'XXX', 'YYY', 'ZZZ', 1) FROM t3 WHERE t3 MATCH 'gestures'" + {{ZZZhand XXXgesturesYYY (called beats) people make while speaking. Research has shown that such XXXgesturesYYY doZZZ}} + + 6 "SELECT snippet(t3, 'XXX', 'YYY', 'ZZZ', 0) FROM t3 WHERE t3 MATCH 'gestures'" + {{no XXXgesturesYYY}} + + 7 "SELECT snippet(t3, 'XXX', 'YYY', 'ZZZ', 1, 5) FROM t3 WHERE t3 MATCH 'gestures'" + {{ZZZthe hand XXXgesturesYYY (called beatsZZZ}} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3rnd.test b/components/external/SQLite-3.8.1/test/fts3rnd.test new file mode 100644 index 0000000000000000000000000000000000000000..97af54925f3953e866468ddac7cc3afa8736b471 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3rnd.test @@ -0,0 +1,460 @@ +# 2009 December 03 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Brute force (random data) tests for FTS3. +# + +#------------------------------------------------------------------------- +# +# The FTS3 tests implemented in this file focus on testing that FTS3 +# returns the correct set of documents for various types of full-text +# query. This is done using pseudo-randomly generated data and queries. +# The expected result of each query is calculated using Tcl code. +# +# 1. The database is initialized to contain a single table with three +# columns. 100 rows are inserted into the table. Each of the three +# values in each row is a document consisting of between 0 and 100 +# terms. Terms are selected from a vocabulary of $G(nVocab) terms. +# +# 2. The following is performed 100 times: +# +# a. A row is inserted into the database. The row contents are +# generated as in step 1. The docid is a pseudo-randomly selected +# value between 0 and 1000000. +# +# b. A psuedo-randomly selected row is updated. One of its columns is +# set to contain a new document generated in the same way as the +# documents in step 1. +# +# c. A psuedo-randomly selected row is deleted. +# +# d. For each of several types of fts3 queries, 10 SELECT queries +# of the form: +# +# SELECT docid FROM WHERE MATCH '' +# +# are evaluated. The results are compared to those calculated by +# Tcl code in this file. The patterns used for the different query +# types are: +# +# 1. query = +# 2. query = +# 3. query = " " +# 4. query = " " +# 5. query = " " +# 6. query = NEAR +# 7. query = NEAR/11 NEAR/11 +# 8. query = OR +# 9. query = NOT +# 10. query = AND +# 11. query = NEAR OR NEAR +# 12. query = NEAR NOT NEAR +# 13. query = NEAR AND NEAR +# +# where is a term psuedo-randomly selected from the vocabulary +# and prefix is the first 2 characters of such a term followed by +# a "*" character. +# +# Every second iteration, steps (a) through (d) above are performed +# within a single transaction. This forces the queries in (d) to +# read data from both the database and the in-memory hash table +# that caches the full-text index entries created by steps (a), (b) +# and (c) until the transaction is committed. +# +# The procedure above is run 5 times, using advisory fts3 node sizes of 50, +# 500, 1000 and 2000 bytes. +# +# After the test using an advisory node-size of 50, an OOM test is run using +# the database. This test is similar to step (d) above, except that it tests +# the effects of transient and persistent OOM conditions encountered while +# executing each query. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If this build does not include FTS3, skip the tests in this file. +# +ifcapable !fts3 { finish_test ; return } +source $testdir/fts3_common.tcl +source $testdir/malloc_common.tcl + +set G(nVocab) 100 + +set nVocab 100 +set lVocab [list] + +expr srand(0) + +# Generate a vocabulary of nVocab words. Each word is 3 characters long. +# +set lChar {a b c d e f g h i j k l m n o p q r s t u v w x y z} +for {set i 0} {$i < $nVocab} {incr i} { + set len [expr int(rand()*3)+2] + set word [lindex $lChar [expr int(rand()*26)]] + append word [lindex $lChar [expr int(rand()*26)]] + if {$len>2} { append word [lindex $lChar [expr int(rand()*26)]] } + if {$len>3} { append word [lindex $lChar [expr int(rand()*26)]] } + lappend lVocab $word +} + +proc random_term {} { + lindex $::lVocab [expr {int(rand()*$::nVocab)}] +} + +# Return a document consisting of $nWord arbitrarily selected terms +# from the $::lVocab list. +# +proc generate_doc {nWord} { + set doc [list] + for {set i 0} {$i < $nWord} {incr i} { + lappend doc [random_term] + } + return $doc +} + + + +# Primitives to update the table. +# +unset -nocomplain t1 +proc insert_row {rowid} { + set a [generate_doc [expr int((rand()*100))]] + set b [generate_doc [expr int((rand()*100))]] + set c [generate_doc [expr int((rand()*100))]] + execsql { INSERT INTO t1(docid, a, b, c) VALUES($rowid, $a, $b, $c) } + set ::t1($rowid) [list $a $b $c] +} +proc delete_row {rowid} { + execsql { DELETE FROM t1 WHERE rowid = $rowid } + catch {unset ::t1($rowid)} +} +proc update_row {rowid} { + set cols {a b c} + set iCol [expr int(rand()*3)] + set doc [generate_doc [expr int((rand()*100))]] + lset ::t1($rowid) $iCol $doc + execsql "UPDATE t1 SET [lindex $cols $iCol] = \$doc WHERE rowid = \$rowid" +} + +proc simple_phrase {zPrefix} { + set ret [list] + + set reg [string map {* {[^ ]*}} $zPrefix] + set reg " $reg " + + foreach key [lsort -integer [array names ::t1]] { + set value $::t1($key) + set cnt [list] + foreach col $value { + if {[regexp $reg " $col "]} { lappend ret $key ; break } + } + } + + #lsort -uniq -integer $ret + set ret +} + +# This [proc] is used to test the FTS3 matchinfo() function. +# +proc simple_token_matchinfo {zToken bDesc} { + + set nDoc(0) 0 + set nDoc(1) 0 + set nDoc(2) 0 + set nHit(0) 0 + set nHit(1) 0 + set nHit(2) 0 + + set dir -inc + if {$bDesc} { set dir -dec } + + foreach key [array names ::t1] { + set value $::t1($key) + set a($key) [list] + foreach i {0 1 2} col $value { + set hit [llength [lsearch -all $col $zToken]] + lappend a($key) $hit + incr nHit($i) $hit + if {$hit>0} { incr nDoc($i) } + } + } + + set ret [list] + foreach docid [lsort -integer $dir [array names a]] { + if { [lindex [lsort -integer $a($docid)] end] } { + set matchinfo [list 1 3] + foreach i {0 1 2} hit $a($docid) { + lappend matchinfo $hit $nHit($i) $nDoc($i) + } + lappend ret $docid $matchinfo + } + } + + set ret +} + +proc simple_near {termlist nNear} { + set ret [list] + + foreach {key value} [array get ::t1] { + foreach v $value { + + set l [lsearch -exact -all $v [lindex $termlist 0]] + foreach T [lrange $termlist 1 end] { + set l2 [list] + foreach i $l { + set iStart [expr $i - $nNear - 1] + set iEnd [expr $i + $nNear + 1] + if {$iStart < 0} {set iStart 0} + foreach i2 [lsearch -exact -all [lrange $v $iStart $iEnd] $T] { + incr i2 $iStart + if {$i2 != $i} { lappend l2 $i2 } + } + } + set l [lsort -uniq -integer $l2] + } + + if {[llength $l]} { +#puts "MATCH($key): $v" + lappend ret $key + } + } + } + + lsort -unique -integer $ret +} + +# The following three procs: +# +# setup_not A B +# setup_or A B +# setup_and A B +# +# each take two arguments. Both arguments must be lists of integer values +# sorted by value. The return value is the list produced by evaluating +# the equivalent of "A op B", where op is the FTS3 operator NOT, OR or +# AND. +# +proc setop_not {A B} { + foreach b $B { set n($b) {} } + set ret [list] + foreach a $A { if {![info exists n($a)]} {lappend ret $a} } + return $ret +} +proc setop_or {A B} { + lsort -integer -uniq [concat $A $B] +} +proc setop_and {A B} { + foreach b $B { set n($b) {} } + set ret [list] + foreach a $A { if {[info exists n($a)]} {lappend ret $a} } + return $ret +} + +proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r +} +db func mit mit +set sqlite_fts3_enable_parentheses 1 + +proc do_orderbydocid_test {tn sql res} { + uplevel [list do_select_test $tn.asc "$sql ORDER BY docid ASC" $res] + uplevel [list do_select_test $tn.desc "$sql ORDER BY docid DESC" \ + [lsort -int -dec $res] + ] +} + +set NUM_TRIALS 100 + +foreach {nodesize order} { + 50 DESC + 50 ASC + 500 ASC + 1000 DESC + 2000 ASC +} { + catch { array unset ::t1 } + set testname "$nodesize/$order" + + # Create the FTS3 table. Populate it (and the Tcl array) with 100 rows. + # + db transaction { + catchsql { DROP TABLE t1 } + execsql "CREATE VIRTUAL TABLE t1 USING fts4(a, b, c, order=$order)" + execsql "INSERT INTO t1(t1) VALUES('nodesize=$nodesize')" + for {set i 0} {$i < 100} {incr i} { insert_row $i } + } + + for {set iTest 1} {$iTest <= $NUM_TRIALS} {incr iTest} { + catchsql COMMIT + + set DO_MALLOC_TEST 0 + set nRep 10 + if {$iTest==100 && $nodesize==50} { + set DO_MALLOC_TEST 1 + set nRep 2 + } + + set ::testprefix fts3rnd-1.$testname.$iTest + + # Delete one row, update one row and insert one row. + # + set rows [array names ::t1] + set nRow [llength $rows] + set iUpdate [lindex $rows [expr {int(rand()*$nRow)}]] + set iDelete $iUpdate + while {$iDelete == $iUpdate} { + set iDelete [lindex $rows [expr {int(rand()*$nRow)}]] + } + set iInsert $iUpdate + while {[info exists ::t1($iInsert)]} { + set iInsert [expr {int(rand()*1000000)}] + } + execsql BEGIN + insert_row $iInsert + update_row $iUpdate + delete_row $iDelete + if {0==($iTest%2)} { execsql COMMIT } + + if {0==($iTest%2)} { + #do_test 0 { fts3_integrity_check t1 } ok + } + + # Pick 10 terms from the vocabulary. Check that the results of querying + # the database for the set of documents containing each of these terms + # is the same as the result obtained by scanning the contents of the Tcl + # array for each term. + # + for {set i 0} {$i < 10} {incr i} { + set term [random_term] + do_select_test 1.$i.asc { + SELECT docid, mit(matchinfo(t1)) FROM t1 WHERE t1 MATCH $term + ORDER BY docid ASC + } [simple_token_matchinfo $term 0] + do_select_test 1.$i.desc { + SELECT docid, mit(matchinfo(t1)) FROM t1 WHERE t1 MATCH $term + ORDER BY docid DESC + } [simple_token_matchinfo $term 1] + } + + # This time, use the first two characters of each term as a term prefix + # to query for. Test that querying the Tcl array produces the same results + # as querying the FTS3 table for the prefix. + # + for {set i 0} {$i < $nRep} {incr i} { + set prefix [string range [random_term] 0 end-1] + set match "${prefix}*" + do_orderbydocid_test 2.$i { + SELECT docid FROM t1 WHERE t1 MATCH $match + } [simple_phrase $match] + } + + # Similar to the above, except for phrase queries. + # + for {set i 0} {$i < $nRep} {incr i} { + set term [list [random_term] [random_term]] + set match "\"$term\"" + do_orderbydocid_test 3.$i { + SELECT docid FROM t1 WHERE t1 MATCH $match + } [simple_phrase $term] + } + + # Three word phrases. + # + for {set i 0} {$i < $nRep} {incr i} { + set term [list [random_term] [random_term] [random_term]] + set match "\"$term\"" + do_orderbydocid_test 4.$i { + SELECT docid FROM t1 WHERE t1 MATCH $match + } [simple_phrase $term] + } + + # Three word phrases made up of term-prefixes. + # + for {set i 0} {$i < $nRep} {incr i} { + set query "[string range [random_term] 0 end-1]* " + append query "[string range [random_term] 0 end-1]* " + append query "[string range [random_term] 0 end-1]*" + + set match "\"$query\"" + do_orderbydocid_test 5.$i { + SELECT docid FROM t1 WHERE t1 MATCH $match + } [simple_phrase $query] + } + + # A NEAR query with terms as the arguments: + # + # ... MATCH '$term1 NEAR $term2' ... + # + for {set i 0} {$i < $nRep} {incr i} { + set terms [list [random_term] [random_term]] + set match [join $terms " NEAR "] + do_orderbydocid_test 6.$i { + SELECT docid FROM t1 WHERE t1 MATCH $match + } [simple_near $terms 10] + } + + # A 3-way NEAR query with terms as the arguments. + # + for {set i 0} {$i < $nRep} {incr i} { + set terms [list [random_term] [random_term] [random_term]] + set nNear 11 + set match [join $terms " NEAR/$nNear "] + do_orderbydocid_test 7.$i { + SELECT docid FROM t1 WHERE t1 MATCH $match + } [simple_near $terms $nNear] + } + + # Set operations on simple term queries. + # + foreach {tn op proc} { + 8 OR setop_or + 9 NOT setop_not + 10 AND setop_and + } { + for {set i 0} {$i < $nRep} {incr i} { + set term1 [random_term] + set term2 [random_term] + set match "$term1 $op $term2" + do_orderbydocid_test $tn.$i { + SELECT docid FROM t1 WHERE t1 MATCH $match + } [$proc [simple_phrase $term1] [simple_phrase $term2]] + } + } + + # Set operations on NEAR queries. + # + foreach {tn op proc} { + 11 OR setop_or + 12 NOT setop_not + 13 AND setop_and + } { + for {set i 0} {$i < $nRep} {incr i} { + set term1 [random_term] + set term2 [random_term] + set term3 [random_term] + set term4 [random_term] + set match "$term1 NEAR $term2 $op $term3 NEAR $term4" + do_orderbydocid_test $tn.$i { + SELECT docid FROM t1 WHERE t1 MATCH $match + } [$proc \ + [simple_near [list $term1 $term2] 10] \ + [simple_near [list $term3 $term4] 10] + ] + } + } + + catchsql COMMIT + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3shared.test b/components/external/SQLite-3.8.1/test/fts3shared.test new file mode 100644 index 0000000000000000000000000000000000000000..0943c0510fcb6300b2be9bcbfd56c64c8c40c143 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3shared.test @@ -0,0 +1,176 @@ +# +# 2010 September 17 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is the interactions between the FTS3/4 module +# and shared-cache mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !fts3||!shared_cache { + finish_test + return +} +set ::testprefix fts3shared + +db close +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +# Open two connections to the database in shared-cache mode. +# +sqlite3 db test.db +sqlite3 db2 test.db + +# Create a virtual FTS3 table. Populate it with some initial data. +# +do_execsql_test fts3shared-1.1 { + CREATE VIRTUAL TABLE t1 USING fts3(x); + BEGIN; + INSERT INTO t1 VALUES('We listened and looked sideways up!'); + INSERT INTO t1 VALUES('Fear at my heart, as at a cup,'); + INSERT INTO t1 VALUES('My life-blood seemed to sip!'); + INSERT INTO t1 VALUES('The stars were dim, and thick the night'); + COMMIT; +} {} + +# Open a write transaction and insert rows into the FTS3 table. This takes +# a write-lock on the underlying t1_content table. +# +do_execsql_test fts3shared-1.2 { + BEGIN; + INSERT INTO t1 VALUES('The steersman''s face by his lamp gleamed white;'); +} {} + +# Now try a SELECT on the full-text table. This particular SELECT does not +# read data from the %_content table. But it still attempts to obtain a lock +# on that table and so the SELECT fails. +# +do_test fts3shared-1.3 { + catchsql { + BEGIN; + SELECT rowid FROM t1 WHERE t1 MATCH 'stars' + } db2 +} {1 {database table is locked}} + +# Verify that the first connection can commit its transaction. +# +do_test fts3shared-1.4 { sqlite3_get_autocommit db } 0 +do_execsql_test fts3shared-1.5 { COMMIT } {} +do_test fts3shared-1.6 { sqlite3_get_autocommit db } 1 + +# Verify that the second connection still has an open transaction. +# +do_test fts3shared-1.6 { sqlite3_get_autocommit db2 } 0 + +db close +db2 close + +#------------------------------------------------------------------------- +# The following tests - fts3shared-2.* - test that unless FTS is bypassed +# and the underlying tables accessed directly, it is not possible for an +# SQLITE_LOCKED error to be enountered when committing an FTS transaction. +# +# Any SQLITE_LOCKED error should be returned when the fts4 (or fts4aux) +# table is first read/written within a transaction, not later on. +# +set LOCKED {1 {database table is locked}} +forcedelete test.db +sqlite3 dbR test.db +sqlite3 dbW test.db +do_test 2.1 { + execsql { + CREATE VIRTUAL TABLE t1 USING fts4; + CREATE TABLE t2ext(a, b); + CREATE VIRTUAL TABLE t2 USING fts4(content=t2ext); + CREATE VIRTUAL TABLE t1aux USING fts4aux(t1); + CREATE VIRTUAL TABLE t2aux USING fts4aux(t2); + + INSERT INTO t1 VALUES('a b c'); + INSERT INTO t2(rowid, a, b) VALUES(1, 'd e f', 'g h i'); + } dbW +} {} + +# Test that once [dbW] has written to the FTS table, no client may read +# from the FTS or fts4aux table. +do_test 2.2.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES('j k l'); + } dbW + execsql BEGIN dbR +} {} +do_test 2.2.2 { catchsql "SELECT * FROM t1 WHERE rowid=1" dbR } $LOCKED +do_test 2.2.3 { catchsql "SELECT * FROM t1 WHERE t1 MATCH 'a'" dbR } $LOCKED +do_test 2.2.4 { catchsql "SELECT rowid FROM t1 WHERE t1 MATCH 'a'" dbR } $LOCKED +do_test 2.2.5 { catchsql "SELECT * FROM t1" dbR } $LOCKED +do_test 2.2.6 { catchsql "SELECT * FROM t1aux" dbR } $LOCKED +do_test 2.2.7 { execsql COMMIT dbW } {} +do_test 2.2.8 { execsql COMMIT dbR } {} + +# Same test as 2.2.*, except with a content= table. +# +do_test 2.3.1 { + execsql { + BEGIN; + INSERT INTO t2(rowid, a, b) VALUES(2, 'j k l', 'm n o'); + } dbW + execsql BEGIN dbR +} {} +do_test 2.3.3 { catchsql "SELECT * FROM t2 WHERE t2 MATCH 'a'" dbR } $LOCKED +do_test 2.3.4 { catchsql "SELECT rowid FROM t2 WHERE t2 MATCH 'a'" dbR } $LOCKED +do_test 2.3.6 { catchsql "SELECT * FROM t2aux" dbR } $LOCKED +do_test 2.3.7 { execsql COMMIT dbW } {} +do_test 2.3.8 { execsql COMMIT dbR } {} + +# Test that once a connection has read from the FTS or fts4aux table, +# another connection may not write to the FTS table. +# +foreach {tn sql} { + 1 "SELECT * FROM t1 WHERE rowid=1" + 2 "SELECT * FROM t1 WHERE t1 MATCH 'a'" + 3 "SELECT rowid FROM t1 WHERE t1 MATCH 'a'" + 4 "SELECT * FROM t1" + 5 "SELECT * FROM t1aux" +} { + + do_test 2.4.$tn { + execsql BEGIN dbR + execsql $::sql dbR + execsql BEGIN dbW + catchsql "INSERT INTO t1 VALUES('p q r')" dbW + } $LOCKED + + execsql ROLLBACK dbR + execsql ROLLBACK dbW +} + +# Same test as 2.4.*, except with a content= table. +# +foreach {tn sql} { + 2 "SELECT * FROM t2 WHERE t2 MATCH 'a'" + 3 "SELECT rowid FROM t2 WHERE t2 MATCH 'a'" + 5 "SELECT * FROM t2aux" +} { + + do_test 2.5.$tn { + execsql BEGIN dbR + execsql $::sql dbR + execsql BEGIN dbW + catchsql "INSERT INTO t2(rowid, a, b) VALUES(3, 's t u', 'v w x')" dbW + } $LOCKED + + execsql ROLLBACK dbR + execsql ROLLBACK dbW +} + +dbW close +dbR close +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3snippet.test b/components/external/SQLite-3.8.1/test/fts3snippet.test new file mode 100644 index 0000000000000000000000000000000000000000..415251dcced746f95079689bd1085b513782f34b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3snippet.test @@ -0,0 +1,524 @@ +# 2010 January 07 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# +# The tests in this file test the FTS3 auxillary functions offsets(), +# snippet() and matchinfo() work. At time of writing, running this file +# provides full coverage of fts3_snippet.c. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix fts3snippet + +# If SQLITE_ENABLE_FTS3 is not defined, omit this file. +ifcapable !fts3 { finish_test ; return } +source $testdir/fts3_common.tcl + +set sqlite_fts3_enable_parentheses 1 +set DO_MALLOC_TEST 0 + +# Transform the list $L to its "normal" form. So that it can be compared to +# another list with the same set of elements using [string compare]. +# +proc normalize {L} { + set ret [list] + foreach l $L {lappend ret $l} + return $ret +} + +proc do_offsets_test {name expr args} { + set result [list] + foreach a $args { + lappend result [normalize $a] + } + do_select_test $name { + SELECT offsets(ft) FROM ft WHERE ft MATCH $expr + } $result +} + +# Document text used by a few tests. Contains the English names of all +# integers between 1 and 300. +# +set numbers [normalize { + one two three four five six seven eight nine ten eleven twelve thirteen + fourteen fifteen sixteen seventeen eighteen nineteen twenty twentyone + twentytwo twentythree twentyfour twentyfive twentysix twentyseven + twentyeight twentynine thirty thirtyone thirtytwo thirtythree thirtyfour + thirtyfive thirtysix thirtyseven thirtyeight thirtynine forty fortyone + fortytwo fortythree fortyfour fortyfive fortysix fortyseven fortyeight + fortynine fifty fiftyone fiftytwo fiftythree fiftyfour fiftyfive fiftysix + fiftyseven fiftyeight fiftynine sixty sixtyone sixtytwo sixtythree sixtyfour + sixtyfive sixtysix sixtyseven sixtyeight sixtynine seventy seventyone + seventytwo seventythree seventyfour seventyfive seventysix seventyseven + seventyeight seventynine eighty eightyone eightytwo eightythree eightyfour + eightyfive eightysix eightyseven eightyeight eightynine ninety ninetyone + ninetytwo ninetythree ninetyfour ninetyfive ninetysix ninetyseven + ninetyeight ninetynine onehundred onehundredone onehundredtwo + onehundredthree onehundredfour onehundredfive onehundredsix onehundredseven + onehundredeight onehundrednine onehundredten onehundredeleven + onehundredtwelve onehundredthirteen onehundredfourteen onehundredfifteen + onehundredsixteen onehundredseventeen onehundredeighteen onehundrednineteen + onehundredtwenty onehundredtwentyone onehundredtwentytwo + onehundredtwentythree onehundredtwentyfour onehundredtwentyfive + onehundredtwentysix onehundredtwentyseven onehundredtwentyeight + onehundredtwentynine onehundredthirty onehundredthirtyone + onehundredthirtytwo onehundredthirtythree onehundredthirtyfour + onehundredthirtyfive onehundredthirtysix onehundredthirtyseven + onehundredthirtyeight onehundredthirtynine onehundredforty + onehundredfortyone onehundredfortytwo onehundredfortythree + onehundredfortyfour onehundredfortyfive onehundredfortysix + onehundredfortyseven onehundredfortyeight onehundredfortynine + onehundredfifty onehundredfiftyone onehundredfiftytwo onehundredfiftythree + onehundredfiftyfour onehundredfiftyfive onehundredfiftysix + onehundredfiftyseven onehundredfiftyeight onehundredfiftynine + onehundredsixty onehundredsixtyone onehundredsixtytwo onehundredsixtythree + onehundredsixtyfour onehundredsixtyfive onehundredsixtysix + onehundredsixtyseven onehundredsixtyeight onehundredsixtynine + onehundredseventy onehundredseventyone onehundredseventytwo + onehundredseventythree onehundredseventyfour onehundredseventyfive + onehundredseventysix onehundredseventyseven onehundredseventyeight + onehundredseventynine onehundredeighty onehundredeightyone + onehundredeightytwo onehundredeightythree onehundredeightyfour + onehundredeightyfive onehundredeightysix onehundredeightyseven + onehundredeightyeight onehundredeightynine onehundredninety + onehundredninetyone onehundredninetytwo onehundredninetythree + onehundredninetyfour onehundredninetyfive onehundredninetysix + onehundredninetyseven onehundredninetyeight onehundredninetynine twohundred + twohundredone twohundredtwo twohundredthree twohundredfour twohundredfive + twohundredsix twohundredseven twohundredeight twohundrednine twohundredten + twohundredeleven twohundredtwelve twohundredthirteen twohundredfourteen + twohundredfifteen twohundredsixteen twohundredseventeen twohundredeighteen + twohundrednineteen twohundredtwenty twohundredtwentyone twohundredtwentytwo + twohundredtwentythree twohundredtwentyfour twohundredtwentyfive + twohundredtwentysix twohundredtwentyseven twohundredtwentyeight + twohundredtwentynine twohundredthirty twohundredthirtyone + twohundredthirtytwo twohundredthirtythree twohundredthirtyfour + twohundredthirtyfive twohundredthirtysix twohundredthirtyseven + twohundredthirtyeight twohundredthirtynine twohundredforty + twohundredfortyone twohundredfortytwo twohundredfortythree + twohundredfortyfour twohundredfortyfive twohundredfortysix + twohundredfortyseven twohundredfortyeight twohundredfortynine + twohundredfifty twohundredfiftyone twohundredfiftytwo twohundredfiftythree + twohundredfiftyfour twohundredfiftyfive twohundredfiftysix + twohundredfiftyseven twohundredfiftyeight twohundredfiftynine + twohundredsixty twohundredsixtyone twohundredsixtytwo twohundredsixtythree + twohundredsixtyfour twohundredsixtyfive twohundredsixtysix + twohundredsixtyseven twohundredsixtyeight twohundredsixtynine + twohundredseventy twohundredseventyone twohundredseventytwo + twohundredseventythree twohundredseventyfour twohundredseventyfive + twohundredseventysix twohundredseventyseven twohundredseventyeight + twohundredseventynine twohundredeighty twohundredeightyone + twohundredeightytwo twohundredeightythree twohundredeightyfour + twohundredeightyfive twohundredeightysix twohundredeightyseven + twohundredeightyeight twohundredeightynine twohundredninety + twohundredninetyone twohundredninetytwo twohundredninetythree + twohundredninetyfour twohundredninetyfive twohundredninetysix + twohundredninetyseven twohundredninetyeight twohundredninetynine + threehundred +}] + +foreach {DO_MALLOC_TEST enc} { + 0 utf8 + 1 utf8 + 1 utf16 +} { + + db close + forcedelete test.db + sqlite3 db test.db + sqlite3_db_config_lookaside db 0 0 0 + db eval "PRAGMA encoding = \"$enc\"" + + # Set variable $T to the test name prefix for this iteration of the loop. + # + set T "fts3snippet-1.$enc" + + ########################################################################## + # Test the offset function. + # + do_test $T.1.1 { + execsql { + CREATE VIRTUAL TABLE ft USING fts3; + INSERT INTO ft VALUES('xxx xxx xxx xxx'); + } + } {} + do_offsets_test $T.1.2 {xxx} {0 0 0 3 0 0 4 3 0 0 8 3 0 0 12 3} + do_offsets_test $T.1.3 {"xxx xxx"} { + 0 0 0 3 0 0 4 3 0 1 4 3 0 0 8 3 + 0 1 8 3 0 1 12 3 + } + do_offsets_test $T.1.4 {"xxx xxx" xxx} { + 0 0 0 3 0 2 0 3 0 0 4 3 0 1 4 3 + 0 2 4 3 0 0 8 3 0 1 8 3 0 2 8 3 + 0 1 12 3 0 2 12 3 + } + do_offsets_test $T.1.5 {xxx "xxx xxx"} { + 0 0 0 3 0 1 0 3 0 0 4 3 0 1 4 3 + 0 2 4 3 0 0 8 3 0 1 8 3 0 2 8 3 + 0 0 12 3 0 2 12 3 + } + + do_test $T.2.1 { + set v1 [lrange $numbers 0 99] + execsql { + DROP TABLE IF EXISTS ft; + CREATE VIRTUAL TABLE ft USING fts3(a, b); + INSERT INTO ft VALUES($v1, $numbers); + INSERT INTO ft VALUES($v1, NULL); + } + } {} + + set off [string first "twohundred " $numbers] + do_offsets_test $T.2.1 {twohundred} [list 1 0 $off 10] + + set off [string first "onehundred " $numbers] + do_offsets_test $T.2.2 {onehundred} \ + [list 0 0 $off 10 1 0 $off 10] [list 0 0 $off 10] + + # Test a corruption case: + execsql { UPDATE ft_content SET c1b = 'hello world' WHERE c1b = $numbers } + do_error_test $T.2.3 { + SELECT offsets(ft) FROM ft WHERE ft MATCH 'onehundred' + } {database disk image is malformed} + + ########################################################################## + # Test the snippet function. + # + proc do_snippet_test {name expr iCol nTok args} { + set res [list] + foreach a $args { lappend res [string trim $a] } + do_select_test $name { + SELECT snippet(ft,'{','}','...',$iCol,$nTok) FROM ft WHERE ft MATCH $expr + } $res + } + do_test $T.3.1 { + execsql { + DROP TABLE IF EXISTS ft; + CREATE VIRTUAL TABLE ft USING fts3; + INSERT INTO ft VALUES('one two three four five six seven eight nine ten'); + } + } {} + do_snippet_test $T.3.2 one 0 5 "{one} two three four five..." + do_snippet_test $T.3.3 two 0 5 "one {two} three four five..." + do_snippet_test $T.3.4 three 0 5 "one two {three} four five..." + do_snippet_test $T.3.5 four 0 5 "...two three {four} five six..." + do_snippet_test $T.3.6 five 0 5 "...three four {five} six seven..." + do_snippet_test $T.3.7 six 0 5 "...four five {six} seven eight..." + do_snippet_test $T.3.8 seven 0 5 "...five six {seven} eight nine..." + do_snippet_test $T.3.9 eight 0 5 "...six seven {eight} nine ten" + do_snippet_test $T.3.10 nine 0 5 "...six seven eight {nine} ten" + do_snippet_test $T.3.11 ten 0 5 "...six seven eight nine {ten}" + + do_test $T.4.1 { + execsql { + INSERT INTO ft VALUES( + 'one two three four five ' + || 'six seven eight nine ten ' + || 'eleven twelve thirteen fourteen fifteen ' + || 'sixteen seventeen eighteen nineteen twenty ' + || 'one two three four five ' + || 'six seven eight nine ten ' + || 'eleven twelve thirteen fourteen fifteen ' + || 'sixteen seventeen eighteen nineteen twenty' + ); + } + } {} + + do_snippet_test $T.4.2 {one nine} 0 5 { + {one} two three...eight {nine} ten + } { + {one} two three...eight {nine} ten... + } + + do_snippet_test $T.4.3 {one nine} 0 -5 { + {one} two three four five...six seven eight {nine} ten + } { + {one} two three four five...seven eight {nine} ten eleven... + } + do_snippet_test $T.4.3 {one nineteen} 0 -5 { + ...eighteen {nineteen} twenty {one} two... + } + do_snippet_test $T.4.4 {two nineteen} 0 -5 { + ...eighteen {nineteen} twenty one {two}... + } + do_snippet_test $T.4.5 {three nineteen} 0 -5 { + ...{nineteen} twenty one two {three}... + } + + do_snippet_test $T.4.6 {four nineteen} 0 -5 { + ...two three {four} five six...seventeen eighteen {nineteen} twenty one... + } + do_snippet_test $T.4.7 {four NEAR nineteen} 0 -5 { + ...seventeen eighteen {nineteen} twenty one...two three {four} five six... + } + + do_snippet_test $T.4.8 {four nineteen} 0 5 { + ...three {four} five...eighteen {nineteen} twenty... + } + do_snippet_test $T.4.9 {four NEAR nineteen} 0 5 { + ...eighteen {nineteen} twenty...three {four} five... + } + do_snippet_test $T.4.10 {four NEAR nineteen} 0 -5 { + ...seventeen eighteen {nineteen} twenty one...two three {four} five six... + } + do_snippet_test $T.4.11 {four NOT (nineteen twentyone)} 0 5 { + ...two three {four} five six... + } { + ...two three {four} five six... + } + do_snippet_test $T.4.12 {four OR nineteen NEAR twentyone} 0 5 { + ...two three {four} five six... + } { + ...two three {four} five six... + } + + do_test $T.5.1 { + execsql { + DROP TABLE IF EXISTS ft; + CREATE VIRTUAL TABLE ft USING fts3(a, b, c); + INSERT INTO ft VALUES( + 'one two three four five', + 'four five six seven eight', + 'seven eight nine ten eleven' + ); + } + } {} + + do_snippet_test $T.5.2 {five} -1 3 {...three four {five}} + do_snippet_test $T.5.3 {five} 0 3 {...three four {five}} + do_snippet_test $T.5.4 {five} 1 3 {four {five} six...} + do_snippet_test $T.5.5 {five} 2 3 {seven eight nine...} + + do_test $T.5.6 { + execsql { UPDATE ft SET b = NULL } + } {} + + do_snippet_test $T.5.7 {five} -1 3 {...three four {five}} + do_snippet_test $T.5.8 {five} 0 3 {...three four {five}} + do_snippet_test $T.5.9 {five} 1 3 {} + do_snippet_test $T.5.10 {five} 2 3 {seven eight nine...} + + do_snippet_test $T.5.11 {one "seven eight nine"} -1 -3 { + {one} two three...{seven} {eight} {nine}... + } + + do_test $T.6.1 { + execsql { + DROP TABLE IF EXISTS ft; + CREATE VIRTUAL TABLE ft USING fts3(x); + INSERT INTO ft VALUES($numbers); + } + } {} + do_snippet_test $T.6.2 { + one fifty onehundred onehundredfifty twohundredfifty threehundred + } -1 4 { + {one}...{fifty}...{onehundred}...{onehundredfifty}... + } + do_snippet_test $T.6.3 { + one fifty onehundred onehundredfifty twohundredfifty threehundred + } -1 -4 { + {one} two three four...fortyeight fortynine {fifty} fiftyone...ninetyeight ninetynine {onehundred} onehundredone...onehundredfortyeight onehundredfortynine {onehundredfifty} onehundredfiftyone... + } + + do_test $T.7.1 { + execsql { + BEGIN; + DROP TABLE IF EXISTS ft; + CREATE VIRTUAL TABLE ft USING fts3(x); + } + set testresults [list] + for {set i 1} {$i < 150} {incr i} { + set commas [string repeat , $i] + execsql {INSERT INTO ft VALUES('one' || $commas || 'two')} + lappend testresults "{one}$commas{two}" + } + execsql COMMIT + } {} + eval [list do_snippet_test $T.7.2 {one two} -1 3] $testresults + + ########################################################################## + # Test the matchinfo function. + # + proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r + } + db func mit mit + proc do_matchinfo_test {name expr args} { + set res [list] + foreach a $args { lappend res [normalize $a] } + do_select_test $name { + SELECT mit(matchinfo(ft)) FROM ft WHERE ft MATCH $expr + } $res + } + do_test $T.8.1 { + set ten {one two three four five six seven eight nine ten} + execsql { + DROP TABLE IF EXISTS ft; + CREATE VIRTUAL TABLE ft USING fts3; + INSERT INTO ft VALUES($ten); + INSERT INTO ft VALUES($ten || ' ' || $ten); + } + } {} + + do_matchinfo_test $T.8.2 "one" {1 1 1 3 2} {1 1 2 3 2} + do_matchinfo_test $T.8.3 "one NEAR/3 ten" {2 1 1 1 1 1 1 1} + do_matchinfo_test $T.8.4 "five NEAR/4 ten" \ + {2 1 1 3 2 1 3 2} {2 1 2 3 2 2 3 2} + do_matchinfo_test $T.8.5 "six NEAR/3 ten NEAR/3 two" \ + {3 1 1 1 1 1 1 1 1 1 1} + do_matchinfo_test $T.8.6 "five NEAR/4 ten NEAR/3 two" \ + {3 1 2 2 1 1 1 1 1 1 1} + + do_test $T.9.1 { + execsql { + DROP TABLE IF EXISTS ft; + CREATE VIRTUAL TABLE ft USING fts3(x, y); + } + foreach n {1 2 3} { + set v1 [lrange $numbers 0 [expr $n*100]] + set v2 [string trim [string repeat "$numbers " $n]] + set docid [expr $n * 1000000] + execsql { INSERT INTO ft(docid, x, y) VALUES($docid, $v1, $v2) } + } + } {} + do_matchinfo_test $T.9.2 {two*} \ + { 1 2 1 105 3 101 606 3} \ + { 1 2 3 105 3 202 606 3} \ + { 1 2 101 105 3 303 606 3} + + do_matchinfo_test $T.9.4 {"one* two*"} \ + { 1 2 1 5 3 2 12 3} \ + { 1 2 2 5 3 4 12 3} \ + { 1 2 2 5 3 6 12 3} + + do_matchinfo_test $T.9.5 {twohundredfifty} \ + { 1 2 0 1 1 1 6 3} \ + { 1 2 0 1 1 2 6 3} \ + { 1 2 1 1 1 3 6 3} + + do_matchinfo_test $T.9.6 {"threehundred one"} \ + { 1 2 0 0 0 1 3 2} \ + { 1 2 0 0 0 2 3 2} + + do_matchinfo_test $T.9.7 {one OR fivehundred} \ + { 2 2 1 3 3 1 6 3 0 0 0 0 0 0 } \ + { 2 2 1 3 3 2 6 3 0 0 0 0 0 0 } \ + { 2 2 1 3 3 3 6 3 0 0 0 0 0 0 } + + do_matchinfo_test $T.9.8 {two OR "threehundred one"} \ + { 2 2 1 3 3 1 6 3 0 0 0 0 3 2 } \ + { 2 2 1 3 3 2 6 3 0 0 0 1 3 2 } \ + { 2 2 1 3 3 3 6 3 0 0 0 2 3 2 } + + do_select_test $T.9.9 { + SELECT mit(matchinfo(ft)), mit(matchinfo(ft)) + FROM ft WHERE ft MATCH 'two OR "threehundred one"' + } [normalize { + {2 2 1 3 3 1 6 3 0 0 0 0 3 2} + {2 2 1 3 3 1 6 3 0 0 0 0 3 2} + {2 2 1 3 3 2 6 3 0 0 0 1 3 2} + {2 2 1 3 3 2 6 3 0 0 0 1 3 2} + {2 2 1 3 3 3 6 3 0 0 0 2 3 2} + {2 2 1 3 3 3 6 3 0 0 0 2 3 2} + }] + + # EVIDENCE-OF: R-40630-02268 If used within a SELECT that uses the + # "query by rowid" or "linear scan" strategies, then the snippet and + # offsets both return an empty string, and the matchinfo function + # returns a blob value zero bytes in size. + # + set r 1000000 ;# A rowid that exists in table ft + do_select_test $T.10.0 { SELECT rowid FROM ft WHERE rowid = $r } $r + do_select_test $T.10.1 { + SELECT length(offsets(ft)), typeof(offsets(ft)) FROM ft; + } {0 text 0 text 0 text} + do_select_test $T.10.2 { + SELECT length(offsets(ft)), typeof(offsets(ft)) FROM ft WHERE rowid = $r + } {0 text} + do_select_test $T.10.3 { + SELECT length(snippet(ft)), typeof(snippet(ft)) FROM ft; + } {0 text 0 text 0 text} + do_select_test $T.10.4 { + SELECT length(snippet(ft)), typeof(snippet(ft)) FROM ft WHERE rowid = $r; + } {0 text} + do_select_test $T.10.5 { + SELECT length(matchinfo(ft)), typeof(matchinfo(ft)) FROM ft; + } {0 blob 0 blob 0 blob} + do_select_test $T.10.6 { + SELECT length(matchinfo(ft)), typeof(matchinfo(ft)) FROM ft WHERE rowid = $r + } {0 blob} +} + +#------------------------------------------------------------------------- +# Test an interaction between the snippet() function and OR clauses. +# +do_execsql_test 2.1 { + CREATE VIRTUAL TABLE t2 USING fts4; + INSERT INTO t2 VALUES('one two three four five'); + INSERT INTO t2 VALUES('two three four five one'); + INSERT INTO t2 VALUES('three four five one two'); + INSERT INTO t2 VALUES('four five one two three'); + INSERT INTO t2 VALUES('five one two three four'); +} + +do_execsql_test 2.2 { + SELECT snippet(t2, '[', ']') FROM t2 WHERE t2 MATCH 'one OR (four AND six)' +} { + {[one] two three [four] five} + {two three [four] five [one]} + {three [four] five [one] two} + {[four] five [one] two three} + {five [one] two three [four]} +} + +do_execsql_test 2.3 { + SELECT snippet(t2, '[', ']') FROM t2 + WHERE t2 MATCH 'one OR (four AND six)' + ORDER BY docid DESC +} { + {five [one] two three [four]} + {[four] five [one] two three} + {three [four] five [one] two} + {two three [four] five [one]} + {[one] two three [four] five} +} + +do_execsql_test 2.4 { + INSERT INTO t2 VALUES('six'); +} + +do_execsql_test 2.5 { + SELECT snippet(t2, '[', ']') FROM t2 WHERE t2 MATCH 'one OR (four AND six)' +} { + {[one] two three [four] five} + {two three [four] five [one]} + {three [four] five [one] two} + {[four] five [one] two three} + {five [one] two three [four]} +} + +do_execsql_test 2.6 { + SELECT snippet(t2, '[', ']') FROM t2 + WHERE t2 MATCH 'one OR (four AND six)' + ORDER BY docid DESC +} { + {five [one] two three [four]} + {[four] five [one] two three} + {three [four] five [one] two} + {two three [four] five [one]} + {[one] two three [four] five} +} + +set sqlite_fts3_enable_parentheses 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3sort.test b/components/external/SQLite-3.8.1/test/fts3sort.test new file mode 100644 index 0000000000000000000000000000000000000000..218bf3e827c91ed7c341cae2303136895d9f7d70 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3sort.test @@ -0,0 +1,184 @@ +# 2011 May 04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS3 module. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + + +proc build_database {nRow param} { + db close + forcedelete test.db + sqlite3 db test.db + + set vocab [list aa ab ac ba bb bc ca cb cc da] + expr srand(0) + + execsql "CREATE VIRTUAL TABLE t1 USING fts4($param)" + for {set i 0} {$i < $nRow} {incr i} { + set v [expr int(rand()*1000000)] + set doc [list] + for {set div 1} {$div < 1000000} {set div [expr $div*10]} { + lappend doc [lindex $vocab [expr ($v/$div) % 10]] + } + execsql { INSERT INTO t1 VALUES($doc) } + } +} + +set testprefix fts3sort + +unset -nocomplain CONTROL +foreach {t param} { + 1 "" + 2 "order=asc" + 3 "order=desc" +} { + + set testprefix fts3sort-1.$t + + set nRow 1000 + do_test 1.0 { + build_database $nRow $param + execsql { SELECT count(*) FROM t1 } + } $nRow + + foreach {tn query} { + 1 "SELECT docid, * FROM t1" + 2 "SELECT docid, * FROM t1 WHERE t1 MATCH 'aa'" + 3 "SELECT docid, * FROM t1 WHERE t1 MATCH 'a*'" + 4 "SELECT docid, quote(matchinfo(t1)) FROM t1 WHERE t1 MATCH 'a*'" + 5 "SELECT docid, quote(matchinfo(t1,'pcnxals')) FROM t1 WHERE t1 MATCH 'b*'" + 6 "SELECT docid, * FROM t1 WHERE t1 MATCH 'a* b* c*'" + 7 "SELECT docid, * FROM t1 WHERE t1 MATCH 'aa OR da'" + 8 "SELECT docid, * FROM t1 WHERE t1 MATCH 'nosuchtoken'" + 9 "SELECT docid, snippet(t1) FROM t1 WHERE t1 MATCH 'aa OR da'" + 10 "SELECT docid, snippet(t1) FROM t1 WHERE t1 MATCH 'aa OR nosuchtoken'" + 11 "SELECT docid, snippet(t1) FROM t1 WHERE t1 MATCH 'aa NEAR bb'" + 12 "SELECT docid, snippet(t1) FROM t1 WHERE t1 MATCH '\"aa bb\"'" + 13 "SELECT docid, content FROM t1 WHERE t1 MATCH 'aa NEAR/2 bb NEAR/3 cc'" + 14 "SELECT docid, content FROM t1 WHERE t1 MATCH '\"aa bb cc\"'" + } { + + unset -nocomplain A B C D + set A_list [list] + set B_list [list] + set C_list [list] + set D_list [list] + + unset -nocomplain X + db eval "$query ORDER BY rowid ASC" X { + set A($X(docid)) [array get X] + lappend A_list $X(docid) + } + unset -nocomplain X + db eval "$query ORDER BY rowid DESC" X { + set B($X(docid)) [array get X] + lappend B_list $X(docid) + } + unset -nocomplain X + db eval "$query ORDER BY docid ASC" X { + set C($X(docid)) [array get X] + lappend C_list $X(docid) + } + unset -nocomplain X + db eval "$query ORDER BY docid DESC" X { + set D($X(docid)) [array get X] + lappend D_list $X(docid) + } + + do_test $tn.1 { set A_list } [lsort -integer -increasing $A_list] + do_test $tn.2 { set B_list } [lsort -integer -decreasing $B_list] + do_test $tn.3 { set C_list } [lsort -integer -increasing $C_list] + do_test $tn.4 { set D_list } [lsort -integer -decreasing $D_list] + + unset -nocomplain DATA + unset -nocomplain X + db eval "$query" X { + set DATA($X(docid)) [array get X] + } + + do_test $tn.5 { lsort [array get A] } [lsort [array get DATA]] + do_test $tn.6 { lsort [array get B] } [lsort [array get DATA]] + do_test $tn.7 { lsort [array get C] } [lsort [array get DATA]] + do_test $tn.8 { lsort [array get D] } [lsort [array get DATA]] + + if {[info exists CONTROL($tn)]} { + do_test $tn.9 { set CONTROL($tn) } [lsort [array get DATA]] + } else { + set CONTROL($tn) [lsort [array get DATA]] + } + } +} +unset -nocomplain CONTROL + +set testprefix fts3sort + +#------------------------------------------------------------------------- +# Tests for parsing the "order=asc" and "order=desc" directives. +# +foreach {tn param res} { + 1 "order=asc" {0 {}} + 2 "order=desc" {0 {}} + 3 "order=dec" {1 {unrecognized order: dec}} + 4 "order=xxx, order=asc" {1 {unrecognized order: xxx}} + 5 "order=desc, order=asc" {0 {}} + 6 "order=xxxx, order=asc" {1 {unrecognized order: xxxx}} + 7 "order=desk" {1 {unrecognized order: desk}} +} { + execsql { DROP TABLE IF EXISTS t1 } + do_catchsql_test 2.1.$tn " + CREATE VIRTUAL TABLE t1 USING fts4(a, b, $param) + " $res +} + +do_execsql_test 2.2 { + BEGIN; + CREATE VIRTUAL TABLE t2 USING fts4(order=desc); + INSERT INTO t2 VALUES('aa bb'); + INSERT INTO t2 VALUES('bb cc'); + INSERT INTO t2 VALUES('cc aa'); + SELECT docid FROM t2 WHERE t2 MATCH 'aa'; + END; +} {3 1} +do_execsql_test 2.3 { + SELECT docid FROM t2 WHERE t2 MATCH 'aa'; +} {3 1} +do_execsql_test 2.4 { + SELECT docid FROM t2 WHERE t2 MATCH 'aa' ORDER BY content; +} {1 3} + +#------------------------------------------------------------------------- +# Test that ticket [56be976859] has been fixed. +# +do_execsql_test 3.1 { + CREATE VIRTUAL TABLE t3 USING fts4(x, order=DESC); + INSERT INTO t3(docid, x) VALUES(113382409004785664, 'aa'); + INSERT INTO t3(docid, x) VALUES(1, 'ab'); + SELECT rowid FROM t3 WHERE x MATCH 'a*' ORDER BY docid DESC; +} {113382409004785664 1} +do_execsql_test 3.2 { + CREATE VIRTUAL TABLE t4 USING fts4(x); + INSERT INTO t4(docid, x) VALUES(-113382409004785664, 'aa'); + INSERT INTO t4(docid, x) VALUES(1, 'ab'); + SELECT rowid FROM t4 WHERE x MATCH 'a*'; +} {-113382409004785664 1} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3tok1.test b/components/external/SQLite-3.8.1/test/fts3tok1.test new file mode 100644 index 0000000000000000000000000000000000000000..4faed34d1282a109e0f8f92349f4fe336446dda4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3tok1.test @@ -0,0 +1,115 @@ +# 2013 April 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the "fts3tokenize" virtual table +# that is part of the FTS3 module. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !fts3 { finish_test ; return } +set ::testprefix fts3tok1 + +#------------------------------------------------------------------------- +# Simple test cases. Using the default (simple) tokenizer. +# +do_execsql_test 1.0 { + CREATE VIRTUAL TABLE t1 USING fts3tokenize(simple); + CREATE VIRTUAL TABLE t2 USING fts3tokenize(); + CREATE VIRTUAL TABLE t3 USING fts3tokenize(simple, '', 'xyz '); +} + +foreach {tn tbl} {1 t1 2 t2 3 t3} { + do_execsql_test 1.$tn.1 "SELECT * FROM $tbl WHERE input = 'one two three'" { + {one two three} one 0 3 0 + {one two three} two 4 7 1 + {one two three} three 8 13 2 + } + + do_execsql_test 1.$tn.2 " + SELECT token FROM $tbl WHERE input = 'OnE tWo tHrEe' + " { + one two three + } +} + +do_execsql_test 1.4 { + SELECT token FROM t3 WHERE input = '1x2x3x' +} {1 2 3} + +do_execsql_test 1.5 { + SELECT token FROM t1 WHERE input = '1x2x3x' +} {1x2x3x} + +do_execsql_test 1.6 { + SELECT token FROM t3 WHERE input = '1''2x3x' +} {1'2 3} + +do_execsql_test 1.7 { + SELECT token FROM t3 WHERE input = '' +} {} + +do_execsql_test 1.8 { + SELECT token FROM t3 WHERE input = NULL +} {} + +do_execsql_test 1.9 { + SELECT * FROM t3 WHERE input = 123 +} {123 123 0 3 0} + +do_execsql_test 1.10 { + SELECT * FROM t1 WHERE input = 'a b c' AND token = 'b'; +} { + {a b c} b 2 3 1 +} + +do_execsql_test 1.11 { + SELECT * FROM t1 WHERE token = 'b' AND input = 'a b c'; +} { + {a b c} b 2 3 1 +} + +do_execsql_test 1.12 { + SELECT * FROM t1 WHERE input < 'b' AND input = 'a b c'; +} { + {a b c} a 0 1 0 + {a b c} b 2 3 1 + {a b c} c 4 5 2 +} + +do_execsql_test 1.13.1 { + CREATE TABLE c1(x); + INSERT INTO c1(x) VALUES('a b c'); + INSERT INTO c1(x) VALUES('d e f'); +} +breakpoint +do_execsql_test 1.13.2 { + SELECT * FROM c1, t1 WHERE input = x AND c1.rowid=t1.rowid; +} { + {a b c} {a b c} a 0 1 0 + {d e f} {d e f} e 2 3 1 +} + + +#------------------------------------------------------------------------- +# Error cases. +# +do_catchsql_test 2.0 { + CREATE VIRTUAL TABLE tX USING fts3tokenize(nosuchtokenizer); +} {1 {unknown tokenizer: nosuchtokenizer}} + +do_catchsql_test 2.1 { + CREATE VIRTUAL TABLE t4 USING fts3tokenize; + SELECT * FROM t4; +} {1 {SQL logic error or missing database}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts3tok_err.test b/components/external/SQLite-3.8.1/test/fts3tok_err.test new file mode 100644 index 0000000000000000000000000000000000000000..df0d4beebd266c7adec3398c6e2c38592107c1ed --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts3tok_err.test @@ -0,0 +1,47 @@ +# 2013 April 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the "fts3tokenize" virtual table +# that is part of the FTS3 module. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +ifcapable !fts3 { finish_test ; return } +set ::testprefix fts3tok_err + + +faultsim_save_and_close +do_faultsim_test fts3tok_err-1 -faults oom* -prep { + faultsim_restore_and_reopen +} -body { + execsql { CREATE VIRTUAL TABLE t1 USING fts3tokenize("simple"); } +} -test { + faultsim_test_result {0 {}} +} + +do_test fts3tok_err-2.prep { + faultsim_delete_and_reopen + execsql { CREATE VIRTUAL TABLE t1 USING fts3tokenize("simple"); } + faultsim_save_and_close +} {} + +do_faultsim_test fts3tok_err-2 -faults oom* -prep { + faultsim_restore_and_reopen +} -body { + execsql { SELECT token FROM t1 WHERE input = 'A galaxy far, far away' } +} -test { + faultsim_test_result {0 {a galaxy far far away}} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4aa.test b/components/external/SQLite-3.8.1/test/fts4aa.test new file mode 100644 index 0000000000000000000000000000000000000000..88550c99f781cda98b75f32309a45cefa182deb1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4aa.test @@ -0,0 +1,194 @@ +# 2010 February 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS4 module. +# +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Create the fts_kjv_genesis procedure which fills and FTS3/4 table with +# the complete text of the Book of Genesis. +# +source $testdir/genesis.tcl + +# The following is a list of queries to perform against the above +# FTS3/FTS4 database. We will be trying these queries in various +# configurations to ensure that they always return the same answers. +# +set fts4aa_queries { + {abraham} + {the king} + {"the king"} + {abraham OR joseph} + {ab* OR jos*} + {lived t*} + {spake hebrew} + {melchizedek} + {t* melchizedek} + {melchizedek t*} +} +unset -nocomplain fts4aa_res + +# Set up the baseline results +# +do_test fts4aa-1.0 { + db eval { + CREATE VIRTUAL TABLE t1 USING fts4(words, tokenize porter); + } + fts_kjv_genesis + foreach q $::fts4aa_queries { + set r [db eval {SELECT docid FROM t1 WHERE words MATCH $q ORDER BY docid}] + set ::fts4aa_res($q) $r + } +} {} + +# Legacy test cases +# +do_test fts4aa-1.1 { + db eval { + SELECT docid FROM t1 EXCEPT SELECT docid FROM t1_docsize + } +} {} +do_test fts4aa-1.2 { + db eval { + SELECT docid FROM t1_docsize EXCEPT SELECT docid FROM t1 + } +} {} + +proc mit {blob} { + set scan(littleEndian) i* + set scan(bigEndian) I* + binary scan $blob $scan($::tcl_platform(byteOrder)) r + return $r +} +db func mit mit + +do_test fts4aa-1.3 { + db eval { + SELECT docid, mit(matchinfo(t1, 'pcxnal')) FROM t1 WHERE t1 MATCH 'melchizedek'; + } +} {1014018 {1 1 1 1 1 1533 25 20}} +do_test fts4aa-1.4 { + db eval { + SELECT docid, mit(matchinfo(t1, 'pcxnal')) FROM t1 + WHERE t1 MATCH 'spake hebrew' + ORDER BY docid; + } +} {1039014 {2 1 1 40 40 1 6 6 1533 25 42} 1039017 {2 1 1 40 40 1 6 6 1533 25 26}} +do_test fts4aa-1.5 { + db eval { + SELECT docid, mit(matchinfo(t1, 'pcxnal')) FROM t1 + WHERE t1 MATCH 'laban overtook jacob' + ORDER BY docid; + } +} {1031025 {3 1 2 54 46 1 3 3 2 181 160 1533 25 24}} + +do_test fts4aa-1.6 { + db eval { + DELETE FROM t1 WHERE docid!=1050026; + SELECT hex(size) FROM t1_docsize; + SELECT hex(value) FROM t1_stat; + } +} {17 01176F} + +do_test fts4aa-1.7 { + db eval { + SELECT docid FROM t1 EXCEPT SELECT docid FROM t1_docsize + } +} {} +do_test fts4aa-1.8 { + db eval { + SELECT docid FROM t1_docsize EXCEPT SELECT docid FROM t1 + } +} {} +ifcapable fts4_deferred { + do_test fts4aa-1.9 { + # Note: Token 'in' is being deferred in the following query. + db eval { + SELECT docid, mit(matchinfo(t1, 'pcxnal')) FROM t1 + WHERE t1 MATCH 'joseph died in egypt' + ORDER BY docid; + } + } {1050026 {4 1 1 1 1 1 1 1 2 1 1 1 1 1 1 23 23}} +} + +# Should get the same search results from FTS3 +# +do_test fts4aa-2.0 { + db eval { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts3(words, tokenize porter); + } + fts_kjv_genesis +} {} +unset -nocomplain ii +set ii 0 +foreach {q r} [array get fts4aa_res] { + incr ii + do_test fts4aa-2.$ii { + db eval {SELECT docid FROM t1 WHERE words MATCH $::q ORDER BY docid} + } $r +} + +# Should get the same search results when the page size is very large +# +do_test fts4aa-3.0 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA page_size=65536; + CREATE VIRTUAL TABLE t1 USING fts4(words, tokenize porter); + } + fts_kjv_genesis +} {} +unset -nocomplain ii +set ii 0 +foreach {q r} [array get fts4aa_res] { + incr ii + do_test fts4aa-3.$ii { + db eval {SELECT docid FROM t1 WHERE words MATCH $::q ORDER BY docid} + } $r +} + +# Should get the same search results when an authorizer prevents +# all PRAGMA statements. +# +proc no_pragma_auth {code arg1 arg2 arg3 arg4} { + if {$code=="SQLITE_PRAGMA"} {return SQLITE_DENY} + return SQLITE_OK; +} +do_test fts4aa-4.0 { + db auth ::no_pragma_auth + db eval { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts4(words, tokenize porter); + } + fts_kjv_genesis +} {} +unset -nocomplain ii +set ii 0 +foreach {q r} [array get fts4aa_res] { + incr ii + do_test fts4aa-4.$ii { + db eval {SELECT docid FROM t1 WHERE words MATCH $::q ORDER BY docid} + } $r +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4check.test b/components/external/SQLite-3.8.1/test/fts4check.test new file mode 100644 index 0000000000000000000000000000000000000000..cc1d018aad61a62c4174acb23dd44f0e69757c37 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4check.test @@ -0,0 +1,155 @@ +# 2012 March 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the FTS 'integrity-check' function, +# used to check if the current FTS index accurately reflects the content +# of the table. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/fts3_common.tcl +set ::testprefix fts4check + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Run the integrity-check on FTS table $tbl using database handle $db. If +# the integrity-check passes, return "ok". Otherwise, throw an exception. +# +proc fts_integrity {db tbl} { + $db eval "INSERT INTO $tbl ($tbl) VALUES('integrity-check')" + return "ok" +} + +#------------------------------------------------------------------------- +# Test cases 1.* +# +# 1.0: Build a reasonably sized FTS table (5000 rows). +# +# 1.1: Run the integrity check code to check it passes. +# +# 1.2: Make a series of minor changes to the underlying FTS data structures +# (e.g. delete or insert a row from the %_content table). Check that +# this causes the integrity-check code to fail. +# + +# Build an FTS table and check the integrity-check passes. +# +do_test 1.0 { fts3_build_db_1 5000 } {} +do_test 1.1 { fts_integrity db t1 } {ok} + +# Mess around with the underlying tables. Check that this causes the +# integrity-check test to fail. +# +foreach {tn disruption} { + 1 { + INSERT INTO t1_content(docid, c0x, c1y) VALUES(NULL, 'a', 'b'); + } + 2 { + DELETE FROM t1_content WHERE docid = (SELECT max(docid) FROM t1_content); + } + 3 { + DELETE FROM t1_segdir WHERE level=0 AND idx=( + SELECT max(idx) FROM t1_segdir WHERE level=0 + ); + } +} { + do_execsql_test 1.2.1.$tn "BEGIN; $disruption" + do_catchsql_test 1.2.2.$tn { + INSERT INTO t1 (t1) VALUES('integrity-check') + } {1 {database disk image is malformed}} + do_execsql_test 1.2.3.$tn "ROLLBACK" +} + +do_test 1.3 { fts_integrity db t1 } {ok} + +#------------------------------------------------------------------------- +# Test cases 2.* +# +# 2.0: Build a reasonably sized FTS table (20000 rows) that includes +# prefix indexes. +# +# 2.1: Run the integrity check code to check it passes. +# +# 2.2: Make a series of minor changes to the underlying FTS data structures +# (e.g. delete or insert a row from the %_content table). Check that +# this causes the integrity-check code to fail. +# + +do_test 2.0 { fts3_build_db_2 -extra {prefix="3,1"} 20000 } {} +do_test 2.1 { fts_integrity db t2 } {ok} +foreach {tn disruption} { + 1 { + INSERT INTO t2_content VALUES(NULL, 'xyz') + } + 3 { + DELETE FROM t2_segdir WHERE level=0 AND idx=( + SELECT max(idx) FROM t2_segdir WHERE level=1024 + ); + } +} { + do_execsql_test 2.2.1.$tn "BEGIN; $disruption" + do_catchsql_test 2.2.2.$tn { + INSERT INTO t2 (t2) VALUES('integrity-check') + } {1 {database disk image is malformed}} + do_execsql_test 2.2.3.$tn "ROLLBACK" +} + + +#------------------------------------------------------------------------- +# Test cases 3.* +# +# 3.0: Build a reasonably sized FTS table (5000 rows) that includes +# prefix indexes and uses the languageid= feature. +# +# 3.1: Run the integrity check code to check it passes. +# +# 3.2: Make a series of minor changes to the underlying FTS data structures +# (e.g. delete or insert a row from the %_content table). Check that +# this causes the integrity-check code to fail. +# +do_test 3.0 { + reset_db + fts3_build_db_1 5000 + execsql { + CREATE VIRTUAL TABLE t3 USING fts4(x, y, prefix="2,3", languageid=langid); + } + foreach docid [execsql {SELECT docid FROM t1 ORDER BY 1 ASC}] { + execsql { + INSERT INTO t3(x, y, langid) + SELECT x, y, (docid%9)*4 FROM t1 WHERE docid=$docid; + } + } +} {} +do_test 3.1 { fts_integrity db t3 } {ok} + +foreach {tn disruption} { + 1 { + INSERT INTO t3_content(c0x, c1y, langid) VALUES(NULL, 'a', 0); + } + 2 { + UPDATE t3_content SET langid=langid+1 WHERE rowid = ( + SELECT max(rowid) FROM t3_content + ) + } +} { + do_execsql_test 3.2.1.$tn "BEGIN; $disruption" + do_catchsql_test 3.2.2.$tn { + INSERT INTO t3 (t3) VALUES('integrity-check') + } {1 {database disk image is malformed}} + do_execsql_test 3.2.3.$tn "ROLLBACK" +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4content.test b/components/external/SQLite-3.8.1/test/fts4content.test new file mode 100644 index 0000000000000000000000000000000000000000..6b2cd3cc8ee3c40508fa30439e3c25d0c37af3b3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4content.test @@ -0,0 +1,625 @@ +# 2011 October 03 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the content=xxx FTS4 option. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix fts4content + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +#------------------------------------------------------------------------- +# Test organization: +# +# 1.* - Warm-body tests. +# +# 2.* - Querying a content=xxx FTS table. +# +# 3.* - Writing to a content=xxx FTS table. +# +# 4.* - The "INSERT INTO fts(fts) VALUES('rebuild')" command. +# +# 5.* - Check that CREATE TABLE, DROP TABLE and ALTER TABLE correctly +# ignore any %_content table when used with the content=xxx option. +# +# 6.* - Test the effects of messing with the schema of table xxx after +# creating a content=xxx FTS index. +# +# 7.* - Test that if content=xxx is specified and table xxx does not +# exist, the FTS table can still be used for INSERT and some +# SELECT statements. +# +# 8.* - Test that if the content=xxx and prefix options are used together, +# the 'rebuild' command still works. +# +# 9.* - Test using content=xxx where xxx is a virtual table. +# + +do_execsql_test 1.1.1 { + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES('w x', 'x y', 'y z'); + CREATE VIRTUAL TABLE ft1 USING fts4(content=t1); +} + +do_execsql_test 1.1.2 { + PRAGMA table_info(ft1); +} { + 0 a {} 0 {} 0 + 1 b {} 0 {} 0 + 2 c {} 0 {} 0 +} + +do_execsql_test 1.1.3 { SELECT *, rowid FROM ft1 } {{w x} {x y} {y z} 1} +do_execsql_test 1.1.4 { SELECT a, c FROM ft1 WHERE rowid=1 } {{w x} {y z}} + +do_execsql_test 1.1.5 { INSERT INTO ft1(ft1) VALUES('rebuild') } {} +do_execsql_test 1.1.6 { SELECT rowid FROM ft1 WHERE ft1 MATCH 'x' } {1} +do_execsql_test 1.1.7 { SELECT rowid FROM ft1 WHERE ft1 MATCH 'a' } {} + +do_execsql_test 1.2.1 { + DROP TABLE ft1; + CREATE VIRTUAL TABLE ft1 USING fts4(content=t1, b); + PRAGMA table_info(ft1); +} { + 0 b {} 0 {} 0 +} +do_execsql_test 1.2.2 { + SELECT *, rowid FROM ft1 +} {{x y} 1} + +#------------------------------------------------------------------------- +# The following block of tests - 2.* - test that a content=xxx FTS table +# can be queried. Also tested are cases where rows identified in the FTS +# are missing from the content table, and cases where the index is +# inconsistent with the content table. +# +do_execsql_test 2.0 { + CREATE TABLE t2(x); + INSERT INTO t2 VALUES('O S W W F U C R Q I C N P Z Y Y E Y Y E'); -- 1 + INSERT INTO t2 VALUES('Y X U V L B E H Y J C Y A I A P V F V K'); -- 2 + INSERT INTO t2 VALUES('P W I N J H I I N I F B K D U Q B Z S F'); -- 3 + INSERT INTO t2 VALUES('N R O R H J R H G M D I U U B O M P A U'); -- 4 + INSERT INTO t2 VALUES('Y O V O G T P N G T N F I V B U M J M G'); -- 5 + INSERT INTO t2 VALUES('J O B N K N E C H Z R K J O U G M K L S'); -- 6 + INSERT INTO t2 VALUES('S Z S R I Q U A P W R X H K C Z U L S P'); -- 7 + INSERT INTO t2 VALUES('J C H N R C K R V N M O F Z M Z A I H W'); -- 8 + INSERT INTO t2 VALUES('O Y G I S J U U W O D Z F J K N R P R L'); -- 9 + INSERT INTO t2 VALUES('B G L K U R U P V X Z I H V R W C Q A S'); -- 10 + INSERT INTO t2 VALUES('T F T J F F Y V F W N X K Q A Y L X W G'); -- 11 + INSERT INTO t2 VALUES('C J U H B Q X L C M M Y E G V F W V Z C'); -- 12 + INSERT INTO t2 VALUES('B W L T F S G X D P H N G M R I O A X I'); -- 13 + INSERT INTO t2 VALUES('N G Y O K Q K Z N M H U J E D H U W R K'); -- 14 + INSERT INTO t2 VALUES('U D T R U Y F J D S J X E H Q G V A S Z'); -- 15 + INSERT INTO t2 VALUES('M I W P J S H R J D Q I C G P C T P H R'); -- 16 + INSERT INTO t2 VALUES('J M N I S L X Q C A B F C B Y D H V R J'); -- 17 + INSERT INTO t2 VALUES('F V Z W J Q L P X Y E W B U Q N H X K T'); -- 18 + INSERT INTO t2 VALUES('R F S R Y O F Q E I E G H C B H R X Y N'); -- 19 + INSERT INTO t2 VALUES('U Q Q Q T E P D M F X P J G H X C Q D L'); -- 20 +} + +do_execsql_test 2.1 { + CREATE VIRTUAL TABLE ft2 USING fts4(content=t2); + INSERT INTO ft2(ft2) VALUES('rebuild'); + + -- Modify the backing table a bit: Row 17 is missing and the contents + -- of row 20 do not match the FTS index contents. + DELETE FROM t2 WHERE rowid = 17; + UPDATE t2 SET x = 'a b c d e f g h i j' WHERE rowid = 20; +} + +foreach {tn match rowidlist} { + 1 {S} {1 3 6 7 9 10 13 15 16 17 19} + 2 {"S R"} {7 19} + 3 {"N K N"} {6} + 4 {"Q Q"} {20} + 5 {"B Y D"} {17} +} { + do_execsql_test 2.2.1.$tn { + SELECT rowid FROM ft2 WHERE ft2 MATCH $match + } $rowidlist + + do_execsql_test 2.2.2.$tn { + SELECT docid FROM ft2 WHERE ft2 MATCH $match + } $rowidlist +} + +foreach {tn match result} { + 1 {"N K N"} {{J O B N K N E C H Z R K J O U G M K L S}} + 2 {"Q Q"} {{a b c d e f g h i j}} + 3 {"B Y D"} {{}} +} { + do_execsql_test 2.3.$tn { + SELECT * FROM ft2 WHERE ft2 MATCH $match + } $result +} + +foreach {tn match result} { + 1 {"N K N"} {{..O B [N] [K] [N] E..}} + 2 {"B Y D"} {{}} + 3 {"Q Q"} {{a [b] [c] [d] e f..}} +} { + do_execsql_test 2.4.$tn { + SELECT snippet(ft2, '[', ']', '..', -1, 6) FROM ft2 WHERE ft2 MATCH $match + } $result +} + +foreach {tn match result} { + 1 {"N K N"} {{0 0 6 1 0 1 8 1 0 2 10 1}} + 2 {"B Y D"} {{}} + 3 {"Q Q"} {{0 0 2 1 0 0 4 1 0 1 4 1 0 1 6 1}} + 4 {"Q D L"} {{}} +} { + do_execsql_test 2.5.$tn { + SELECT offsets(ft2) FROM ft2 WHERE ft2 MATCH $match + } $result +} + +#------------------------------------------------------------------------- +# The following block of tests - 3.* - test that the FTS index can be +# modified by writing to the table. But that this has no effect on the +# content table. +# + +do_execsql_test 3.1 { + CREATE TABLE t3(x, y); + CREATE VIRTUAL TABLE ft3 USING fts4(content=t3); +} + +do_catchsql_test 3.1.1 { + INSERT INTO ft3 VALUES('a b c', 'd e f'); +} {1 {constraint failed}} +do_execsql_test 3.1.2 { + INSERT INTO ft3(docid, x, y) VALUES(21, 'a b c', 'd e f'); + SELECT rowid FROM ft3 WHERE ft3 MATCH '"a b c"'; +} {21} +do_execsql_test 3.1.3 { SELECT * FROM t3 } {} + +# This DELETE does not work, since there is no row in [t3] to base the +# DELETE on. So the SELECT on [ft3] still returns rowid 21. +do_execsql_test 3.1.4 { + DELETE FROM ft3; + SELECT rowid FROM ft3 WHERE ft3 MATCH '"a b c"'; +} {21} + +# If the row is added to [t3] before the DELETE on [ft3], it works. +do_execsql_test 3.1.5 { + INSERT INTO t3(rowid, x, y) VALUES(21, 'a b c', 'd e f'); + DELETE FROM ft3; + SELECT rowid FROM ft3 WHERE ft3 MATCH '"a b c"'; +} {} +do_execsql_test 3.1.6 { SELECT rowid FROM t3 } {21} + +do_execsql_test 3.2.1 { + INSERT INTO ft3(rowid, x, y) VALUES(0, 'R T M S M', 'A F O K H'); + INSERT INTO ft3(rowid, x, y) VALUES(1, 'C Z J O X', 'U S Q D K'); + INSERT INTO ft3(rowid, x, y) VALUES(2, 'N G H P O', 'N O P O C'); + INSERT INTO ft3(rowid, x, y) VALUES(3, 'V H S D R', 'K N G E C'); + INSERT INTO ft3(rowid, x, y) VALUES(4, 'J T R V U', 'U X S L C'); + INSERT INTO ft3(rowid, x, y) VALUES(5, 'N A Y N G', 'X D G P Y'); + INSERT INTO ft3(rowid, x, y) VALUES(6, 'I Q I S P', 'D R O Q B'); + INSERT INTO ft3(rowid, x, y) VALUES(7, 'T K T Z J', 'B W D G O'); + INSERT INTO ft3(rowid, x, y) VALUES(8, 'Y K F X T', 'D F G V G'); + INSERT INTO ft3(rowid, x, y) VALUES(9, 'E L E T L', 'P W N F Z'); + INSERT INTO ft3(rowid, x, y) VALUES(10, 'O G J G X', 'G J F E P'); + INSERT INTO ft3(rowid, x, y) VALUES(11, 'O L N N Z', 'K E Z F D'); + INSERT INTO ft3(rowid, x, y) VALUES(12, 'R Z M R J', 'X G I M Z'); + INSERT INTO ft3(rowid, x, y) VALUES(13, 'L X N N X', 'R R N S T'); + INSERT INTO ft3(rowid, x, y) VALUES(14, 'F L B J H', 'K W F L C'); + INSERT INTO ft3(rowid, x, y) VALUES(15, 'P E B M V', 'E A A B U'); + INSERT INTO ft3(rowid, x, y) VALUES(16, 'V E C F P', 'L U T V K'); + INSERT INTO ft3(rowid, x, y) VALUES(17, 'T N O Z N', 'T P Q X N'); + INSERT INTO ft3(rowid, x, y) VALUES(18, 'V W U W R', 'H O A A V'); + INSERT INTO ft3(rowid, x, y) VALUES(19, 'A H N L F', 'I G H B O'); +} + +foreach {tn match rowidlist} { + 1 "N A" {5 19} + 2 "x:O" {1 2 10 11 17} + 3 "y:O" {0 2 6 7 18 19} +} { + set res [list] + foreach rowid $rowidlist { lappend res $rowid {} {} } + + do_execsql_test 3.2.2.$tn { + SELECT rowid, * FROM ft3 WHERE ft3 MATCH $match + } $res + do_execsql_test 3.2.3.$tn { + SELECT docid, * FROM ft3 WHERE ft3 MATCH $match + } $res +} + +do_execsql_test 3.3.1 { + INSERT INTO t3(rowid, x, y) VALUES(0, 'R T M S M', 'A F O K H'); + INSERT INTO t3(rowid, x, y) VALUES(1, 'C Z J O X', 'U S Q D K'); + INSERT INTO t3(rowid, x, y) VALUES(2, 'N G H P O', 'N O P O C'); + INSERT INTO t3(rowid, x, y) VALUES(3, 'V H S D R', 'K N G E C'); + INSERT INTO t3(rowid, x, y) VALUES(4, 'J T R V U', 'U X S L C'); + INSERT INTO t3(rowid, x, y) VALUES(5, 'N A Y N G', 'X D G P Y'); + UPDATE ft3 SET x = y, y = x; + DELETE FROM t3; +} + +foreach {tn match rowidlist} { + 1 "N A" {5 19} + 2 "x:O" {0 2 10 11 17} + 3 "y:O" {1 2 6 7 18 19} +} { + set res [list] + foreach rowid $rowidlist { lappend res $rowid {} {} } + + do_execsql_test 3.3.2.$tn { + SELECT rowid, * FROM ft3 WHERE ft3 MATCH $match + } $res + do_execsql_test 3.3.3.$tn { + SELECT docid, * FROM ft3 WHERE ft3 MATCH $match + } $res +} + +do_execsql_test 3.3.1 { + INSERT INTO t3(rowid, x, y) VALUES(15, 'P E B M V', 'E A A B U'); + INSERT INTO t3(rowid, x, y) VALUES(16, 'V E C F P', 'L U T V K'); + INSERT INTO t3(rowid, x, y) VALUES(17, 'T N O Z N', 'T P Q X N'); + INSERT INTO t3(rowid, x, y) VALUES(18, 'V W U W R', 'H O A A V'); + INSERT INTO t3(rowid, x, y) VALUES(19, 'A H N L F', 'I G H B O'); + DELETE FROM ft3; +} + +foreach {tn match rowidlist} { + 1 "N A" {5} + 2 "x:O" {0 2 10 11} + 3 "y:O" {1 2 6 7} +} { + set res [list] + foreach rowid $rowidlist { lappend res $rowid {} {} } + + do_execsql_test 3.3.2.$tn { + SELECT rowid, * FROM ft3 WHERE ft3 MATCH $match + } $res + do_execsql_test 3.3.3.$tn { + SELECT docid, * FROM ft3 WHERE ft3 MATCH $match + } $res +} + + +#------------------------------------------------------------------------- +# Test cases 4.* test the 'rebuild' command. On content=xxx and regular +# FTS tables. +# +do_execsql_test 4.0 { + CREATE TABLE t4(x); + CREATE VIRTUAL TABLE ft4 USING fts4(content=t4); + CREATE VIRTUAL TABLE ft4x USING fts4(x); +} + +do_execsql_test 4.1.1 { + INSERT INTO ft4x(ft4x) VALUES('rebuild'); + INSERT INTO ft4(ft4) VALUES('rebuild'); +} {} +do_execsql_test 4.1.2 { + SELECT id, quote(value) FROM ft4_stat +} {0 X'000000'} +do_execsql_test 4.1.3 { + SELECT id, quote(value) FROM ft4x_stat +} {0 X'000000'} + +do_execsql_test 4.2.1 { + INSERT INTO ft4x VALUES('M G M F T'); + INSERT INTO ft4x VALUES('Z Q C A U'); + INSERT INTO ft4x VALUES('N L L V'); + INSERT INTO ft4x VALUES('T F D X D'); + INSERT INTO ft4x VALUES('Z H I S D'); + + SELECT id, quote(value) FROM ft4x_stat +} {0 X'05182B'} + +do_execsql_test 4.2.2 { + INSERT INTO ft4(rowid, x) SELECT rowid, * FROM ft4x; + SELECT id, quote(value) FROM ft4_stat +} {0 X'05182B'} + +do_execsql_test 4.2.3 { + SELECT docid, quote(size) FROM ft4_docsize +} {1 X'05' 2 X'05' 3 X'04' 4 X'05' 5 X'05'} + +do_execsql_test 4.2.4 { + INSERT INTO ft4x(ft4x) VALUES('rebuild'); + SELECT id, quote(value) FROM ft4x_stat; + SELECT docid, quote(size) FROM ft4x_docsize +} {0 X'05182B' 1 X'05' 2 X'05' 3 X'04' 4 X'05' 5 X'05'} + +do_execsql_test 4.2.5 { + INSERT INTO ft4(ft4) VALUES('rebuild'); + SELECT id, quote(value) FROM ft4_stat; + SELECT docid, quote(size) FROM ft4_docsize +} {0 X'000000'} + +do_execsql_test 4.2.6 { + INSERT INTO t4(rowid, x) SELECT rowid, x FROM ft4x; + INSERT INTO ft4(ft4) VALUES('rebuild'); + SELECT id, quote(value) FROM ft4_stat; + SELECT docid, quote(size) FROM ft4_docsize +} {0 X'05182B' 1 X'05' 2 X'05' 3 X'04' 4 X'05' 5 X'05'} + + +#------------------------------------------------------------------------- +# Test cases 5.* test that the following commands do not create/move or +# delete a %_content table when used with a content=xxx FTS table. +# +do_execsql_test 5.1.1 { + CREATE TABLE t5(a, b, c, d); + CREATE VIRTUAL TABLE ft5 USING fts4(content=t5); + SELECT name FROM sqlite_master WHERE name LIKE '%t5%'; +} { + t5 ft5 ft5_segments ft5_segdir + sqlite_autoindex_ft5_segdir_1 ft5_docsize ft5_stat +} +do_execsql_test 5.1.2 { + ALTER TABLE ft5 RENAME TO ft6; + SELECT name FROM sqlite_master WHERE name LIKE '%t5%'; +} { + t5 +} +do_execsql_test 5.1.3 { + SELECT name FROM sqlite_master WHERE name LIKE '%t6%'; +} { + ft6 ft6_segments ft6_segdir + sqlite_autoindex_ft6_segdir_1 ft6_docsize ft6_stat +} +do_execsql_test 5.1.4 { + INSERT INTO t5 VALUES('a', 'b', 'c', 'd'); + INSERT INTO ft6(ft6) VALUES('rebuild'); + SELECT rowid FROM ft6 WHERE ft6 MATCH 'b'; +} {1} +do_execsql_test 5.1.5 { + DROP TABLE ft6; + SELECT * FROM t5; +} {a b c d} +do_execsql_test 5.1.6 { + SELECT name FROM sqlite_master WHERE name LIKE '%t6%'; +} { +} +do_execsql_test 5.1.7 { + CREATE VIRTUAL TABLE ft5 USING fts4(content=t5); + CREATE TABLE t5_content(a, b); + DROP TABLE ft5; + SELECT name FROM sqlite_master WHERE name LIKE '%t5%'; +} { + t5 t5_content +} + +#------------------------------------------------------------------------- +# Test cases 6.* test +# +do_catchsql_test 6.1.1 { + CREATE VIRTUAL TABLE ft7 USING fts4(content=t7); +} {1 {vtable constructor failed: ft7}} + +do_execsql_test 6.2.1 { + CREATE TABLE t7(one, two); + CREATE VIRTUAL TABLE ft7 USING fts4(content=t7); + INSERT INTO t7 VALUES('A B', 'B A'); + INSERT INTO t7 VALUES('C D', 'A A'); + SELECT * FROM ft7; +} { + {A B} {B A} {C D} {A A} +} + +do_catchsql_test 6.2.2 { + DROP TABLE t7; + SELECT * FROM ft7; +} {1 {SQL logic error or missing database}} + +db close +sqlite3 db test.db +do_execsql_test 6.2.3 { + SELECT name FROM sqlite_master WHERE name LIKE '%t7%' +} { + ft7 ft7_segments ft7_segdir sqlite_autoindex_ft7_segdir_1 + ft7_docsize ft7_stat +} +do_catchsql_test 6.2.4 { + SELECT * FROM ft7; +} {1 {vtable constructor failed: ft7}} +do_execsql_test 6.2.5 { + CREATE TABLE t7(x, y); + INSERT INTO t7 VALUES('A B', 'B A'); + INSERT INTO t7 VALUES('C D', 'A A'); + SELECT * FROM ft7; +} { + {A B} {B A} {C D} {A A} +} + +do_execsql_test 6.2.6 { + INSERT INTO ft7(ft7) VALUES('rebuild'); + SELECT rowid FROM ft7 WHERE ft7 MATCH '"A A"'; +} {2} + +do_execsql_test 6.2.7 { + DROP TABLE t7; + CREATE TABLE t7(x); +} +do_catchsql_test 6.2.8 { + SELECT * FROM ft7 WHERE ft7 MATCH '"A A"'; +} {1 {SQL logic error or missing database}} +do_catchsql_test 6.2.9 { + SELECT * FROM ft7 WHERE ft7 MATCH '"A A"'; +} {1 {SQL logic error or missing database}} + +db close +sqlite3 db test.db +do_catchsql_test 6.2.10 { + SELECT rowid FROM ft7 WHERE ft7 MATCH '"A A"'; +} {0 2} +do_catchsql_test 6.2.11 { + SELECT rowid, * FROM ft7 WHERE ft7 MATCH '"A A"'; +} {0 {2 {}}} + +#------------------------------------------------------------------------- +# Test cases 7.* +# +do_execsql_test 7.1.1 { + CREATE VIRTUAL TABLE ft8 USING fts4(content=nosuchtable, x); + INSERT INTO ft8(docid, x) VALUES(13, 'U O N X G'); + INSERT INTO ft8(docid, x) VALUES(14, 'C J J U B'); + INSERT INTO ft8(docid, x) VALUES(15, 'N J Y G X'); + INSERT INTO ft8(docid, x) VALUES(16, 'R Y D O R'); + INSERT INTO ft8(docid, x) VALUES(17, 'I Y T Q O'); +} + +do_execsql_test 7.1.2 { + SELECT docid FROM ft8 WHERE ft8 MATCH 'N'; +} {13 15} + +do_execsql_test 7.2.1 { + CREATE VIRTUAL TABLE ft9 USING fts4(content=, x); + INSERT INTO ft9(docid, x) VALUES(13, 'U O N X G'); + INSERT INTO ft9(docid, x) VALUES(14, 'C J J U B'); + INSERT INTO ft9(docid, x) VALUES(15, 'N J Y G X'); + INSERT INTO ft9(docid, x) VALUES(16, 'R Y D O R'); + INSERT INTO ft9(docid, x) VALUES(17, 'I Y T Q O'); +} +do_execsql_test 7.2.2 { + SELECT docid FROM ft9 WHERE ft9 MATCH 'N'; +} {13 15} +do_execsql_test 7.2.3 { + SELECT name FROM sqlite_master WHERE name LIKE 'ft9_%'; +} {ft9_segments ft9_segdir ft9_docsize ft9_stat} + +do_catchsql_test 7.2.4 { + SELECT * FROM ft9 WHERE ft9 MATCH 'N'; +} {1 {SQL logic error or missing database}} + +#------------------------------------------------------------------------- +# Test cases 8.* +# +do_execsql_test 8.1 { + CREATE TABLE t10(a, b); + INSERT INTO t10 VALUES( + 'abasia abasic abask', 'Abassin abastardize abatable'); + INSERT INTO t10 VALUES( + 'abate abatement abater', 'abatis abatised abaton'); + INSERT INTO t10 VALUES( + 'abator abattoir Abatua', 'abature abave abaxial'); + + CREATE VIRTUAL TABLE ft10 USING fts4(content=t10, prefix="2,4", a, b); +} + +do_execsql_test 8.2 { SELECT * FROM ft10 WHERE a MATCH 'ab*'; } +do_execsql_test 8.3 { INSERT INTO ft10(ft10) VALUES('rebuild'); } +do_execsql_test 8.4 { SELECT rowid FROM ft10 WHERE a MATCH 'ab*'; } {1 2 3} +do_execsql_test 8.5 { SELECT rowid FROM ft10 WHERE b MATCH 'abav*'; } {3} +do_execsql_test 8.6 { SELECT rowid FROM ft10 WHERE ft10 MATCH 'abas*'; } {1} + +#------------------------------------------------------------------------- +# Test cases 9.* +# +reset_db +register_echo_module [sqlite3_connection_pointer db] + +do_execsql_test 9.1 { + CREATE TABLE tbl1(a, b); + INSERT INTO tbl1 VALUES('a b', 'c d'); + INSERT INTO tbl1 VALUES('e f', 'a b'); + CREATE VIRTUAL TABLE e1 USING echo(tbl1); + CREATE VIRTUAL TABLE ft1 USING fts4(content=e1); + INSERT INTO ft1(ft1) VALUES('rebuild'); +} + +do_execsql_test 9.2 { + SELECT rowid, * FROM ft1 WHERE ft1 MATCH 'e' +} {2 {e f} {a b}} + +do_execsql_test 9.3 { + SELECT rowid, * FROM ft1 WHERE ft1 MATCH 'a' +} {1 {a b} {c d} 2 {e f} {a b}} + +do_execsql_test 9.4 { + DELETE FROM ft1 WHERE docid=1; +} + +do_execsql_test 9.5 { + SELECT rowid, * FROM ft1 WHERE ft1 MATCH 'a' +} {2 {e f} {a b}} + +do_execsql_test 9.6 { + INSERT INTO ft1(ft1) VALUES('rebuild'); + SELECT rowid, * FROM ft1 WHERE ft1 MATCH 'a' +} {1 {a b} {c d} 2 {e f} {a b}} + + +#------------------------------------------------------------------------- +# Test cases 10.* +# +reset_db +register_fs_module [sqlite3_connection_pointer db] + +proc write_file {path text} { + set fd [open $path w] + puts -nonewline $fd $text + close $fd +} + +write_file t1.txt {a b c d e f g h i j k l m n o p q r s t u v w x y z} +write_file t2.txt {a b c d e f g h i j k l m a b c d e f g h i j k l m} +write_file t3.txt {n o p q r s t u v w x y z n o p q r s t u v w x y z} + +do_execsql_test 10.1 { + CREATE TABLE idx(id INTEGER PRIMARY KEY, path TEXT); + INSERT INTO idx VALUES (1, 't1.txt'); + INSERT INTO idx VALUES (2, 't2.txt'); + INSERT INTO idx VALUES (3, 't3.txt'); + + CREATE VIRTUAL TABLE vt USING fs(idx); + SELECT * FROM vt; +} { + 1 {a b c d e f g h i j k l m n o p q r s t u v w x y z} + 2 {a b c d e f g h i j k l m a b c d e f g h i j k l m} + 3 {n o p q r s t u v w x y z n o p q r s t u v w x y z} +} + +do_execsql_test 10.2 { + SELECT * FROM vt WHERE rowid = 2; +} { + 2 {a b c d e f g h i j k l m a b c d e f g h i j k l m} +} + +do_execsql_test 10.3 { + CREATE VIRTUAL TABLE ft USING fts4(content=vt); + INSERT INTO ft(ft) VALUES('rebuild'); +} + +do_execsql_test 10.4 { + SELECT snippet(ft, '[', ']', '...', -1, 5) FROM ft WHERE ft MATCH 'e' +} { + {...c d [e] f g...} {...c d [e] f g...} +} + +do_execsql_test 10.5 { + SELECT snippet(ft, '[', ']', '...', -1, 5) FROM ft WHERE ft MATCH 't' +} { + {...r s [t] u v...} {...r s [t] u v...} +} + +do_execsql_test 10.6 { DELETE FROM ft WHERE docid=2 } + +do_execsql_test 10.7 { + SELECT snippet(ft, '[', ']', '...', -1, 5) FROM ft WHERE ft MATCH 'e' +} { + {...c d [e] f g...} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4docid.test b/components/external/SQLite-3.8.1/test/fts4docid.test new file mode 100644 index 0000000000000000000000000000000000000000..2328b6ec1d3cf6ea2537b13a94d29ed758077ee1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4docid.test @@ -0,0 +1,116 @@ +# 2012 March 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/fts3_common.tcl +set ::testprefix fts4docid + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Initialize a table with pseudo-randomly generated data. +# +do_execsql_test 1.0 { CREATE VIRTUAL TABLE t1 USING fts4; } +do_test 1.1 { + foreach {docid content} { + 0 {F N K B T I K V B A} 1 {D M J E S P H E L O} + 2 {W U T Q T Q T L H G} 3 {D W H M B R S Z B K} + 4 {F Q I N P Q J L Z D} 5 {J O Q E Y A O E L B} + 6 {O V R A C R K C Y H} 7 {Z J H T Q Q O R A G} + 8 {L K J W G D Y W B M} 9 {K E Y I A Q R Q T S} + 10 {N P H Y Z M R T I C} 11 {E X H O I S E S Z F} + 12 {B Y Q T J X C L L J} 13 {Q D C U U A Q E Z U} + 14 {S I T C J R X S J M} 15 {M X M K E X L H Q Y} + 16 {O W E I C H U Y S Y} 17 {P V V E M T H C C S} + 18 {L Y A M I E N M X O} 19 {S Y R U L S Q Y F P} + 20 {U J S T T J J S V X} 21 {T E I W P O V A A P} + 22 {W D K H D H F G O J} 23 {T X Y P G M J U I L} + 24 {F V X E B C N B K W} 25 {E B A Y N N T Z I C} + 26 {G E E B C P U D H G} 27 {J D J K N S B Q T M} + 28 {Q T G M D O D Y V G} 29 {P X W I W V P W Z G} + } { + execsql { INSERT INTO t1(docid, content) VALUES($docid, $content) } + } +} {} + +# Quick test regarding affinites and the docid/rowid column. +do_execsql_test 2.1.1 { SELECT docid FROM t1 WHERE docid = 5 } {5} +do_execsql_test 2.1.2 { SELECT docid FROM t1 WHERE docid = '5' } {5} +do_execsql_test 2.1.3 { SELECT docid FROM t1 WHERE docid = +5 } {5} +do_execsql_test 2.1.4 { SELECT docid FROM t1 WHERE docid = +'5' } {5} +do_execsql_test 2.1.5 { SELECT docid FROM t1 WHERE docid < 5 } {0 1 2 3 4} +do_execsql_test 2.1.6 { SELECT docid FROM t1 WHERE docid < '5' } {0 1 2 3 4} + +do_execsql_test 2.2.1 { SELECT rowid FROM t1 WHERE rowid = 5 } {5} +do_execsql_test 2.2.2 { SELECT rowid FROM t1 WHERE rowid = '5' } {5} +do_execsql_test 2.2.3 { SELECT rowid FROM t1 WHERE rowid = +5 } {5} +do_execsql_test 2.2.4 { SELECT rowid FROM t1 WHERE rowid = +'5' } {5} +do_execsql_test 2.2.5 { SELECT rowid FROM t1 WHERE rowid < 5 } {0 1 2 3 4} +do_execsql_test 2.2.6 { SELECT rowid FROM t1 WHERE rowid < '5' } {0 1 2 3 4} + +#------------------------------------------------------------------------- +# Now test a bunch of full-text queries featuring range constraints on +# the docid field. Each query is run so that the range constraint: +# +# * is on the docid field, +# * is on the docid field with a unary +, +# * is on the rowid field, +# * is on the rowid field with a unary +. +# +# Queries are run with both "ORDER BY docid DESC" and "ORDER BY docid ASC" +# clauses. +# +foreach {tn where result} { + 1 {WHERE t1 MATCH 'O' AND xxx < 17} {1 5 6 7 11 16} + 2 {WHERE t1 MATCH 'O' AND xxx < 4123456789123456} {1 5 6 7 11 16 18 21 22 28} + 3 {WHERE t1 MATCH 'O' AND xxx < 1} {} + 4 {WHERE t1 MATCH 'O' AND xxx < -4123456789123456} {} + + 5 {WHERE t1 MATCH 'O' AND xxx > 17} {18 21 22 28} + 6 {WHERE t1 MATCH 'O' AND xxx > 4123456789123456} {} + 7 {WHERE t1 MATCH 'O' AND xxx > 1} {5 6 7 11 16 18 21 22 28} + 8 {WHERE t1 MATCH 'O' AND xxx > -4123456789123456} {1 5 6 7 11 16 18 21 22 28} + + 9 {WHERE t1 MATCH '"Q T"' AND xxx < 27} {2 9 12} + 10 {WHERE t1 MATCH '"Q T"' AND xxx <= 27} {2 9 12 27} + 11 {WHERE t1 MATCH '"Q T"' AND xxx > 27} {28} + 12 {WHERE t1 MATCH '"Q T"' AND xxx >= 27} {27 28} +} { + foreach {tn2 ref order} { + 1 docid "ORDER BY docid ASC" + 2 +docid "ORDER BY docid ASC" + 3 rowid "ORDER BY docid ASC" + 4 +rowid "ORDER BY docid ASC" + + 5 docid "ORDER BY docid DESC" + 6 +docid "ORDER BY docid DESC" + 7 rowid "ORDER BY docid DESC" + 8 +rowid "ORDER BY docid DESC" + } { + set w [string map "xxx $ref" $where] + set q "SELECT docid FROM t1 $w $order" + + if {$tn2<5} { + set r [lsort -integer -increasing $result] + } else { + set r [lsort -integer -decreasing $result] + } + + do_execsql_test 3.$tn.$tn2 $q $r + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4incr.test b/components/external/SQLite-3.8.1/test/fts4incr.test new file mode 100644 index 0000000000000000000000000000000000000000..17212efce7fd81ffce82ce14c95da665cf9d234a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4incr.test @@ -0,0 +1,75 @@ +# 2012 March 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/fts3_common.tcl +set ::testprefix fts4incr + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +# Create the fts_kjv_genesis procedure which fills and FTS3/4 table +# with the complete text of the Book of Genesis. +# +source $testdir/genesis.tcl + +do_test 1.0 { + execsql { CREATE VIRTUAL TABLE t1 USING fts4(words) } + fts_kjv_genesis +} {} + +do_execsql_test 1.1 { + SELECT min(docid), max(docid) FROM t1; +} {1001001 1050026} + +foreach {tn q res} { + 1 { SELECT count(*) FROM t1 WHERE t1 MATCH 'and' AND docid < 1010000} 224 + 2 { SELECT count(*) FROM t1 WHERE t1 MATCH '"in the"' AND docid < 1010000} 47 + 3 { SELECT count(*) FROM t1 WHERE t1 MATCH '"And God"' AND docid < 1010000} 33 + 4 { SELECT count(*) FROM t1 WHERE t1 + MATCH '"land of canaan"' AND docid < 1030000 } 7 +} { + foreach s {0 1} { + execsql "INSERT INTO t1(t1) VALUES('test-no-incr-doclist=$s')" + do_execsql_test 2.$tn.$s $q $res + set t($s) [lindex [time [list execsql $q] 100] 0] + } + puts "with optimization: $t(0) without: $t(1)" +} + +do_test 2.1 { + execsql { + CREATE VIRTUAL TABLE t2 USING fts4(order=DESC); + } + set num [list one two three four five six seven eight nine ten] + execsql BEGIN + for {set i 0} {$i < 10000} {incr i} { + set x "[lindex $num [expr $i%10]] zero" + execsql { INSERT INTO t2(docid, content) VALUES($i, $x) } + } + execsql COMMIT + execsql { INSERT INTO t2(t2) VALUES('optimize') } +} {} + +do_execsql_test 2.2 { + SELECT count(*) FROM t2 WHERE t2 MATCH '"never zero"' +} {0} + +do_execsql_test 2.3 { + SELECT count(*) FROM t2 WHERE t2 MATCH '"two zero"' +} {1000} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4langid.test b/components/external/SQLite-3.8.1/test/fts4langid.test new file mode 100644 index 0000000000000000000000000000000000000000..843e11f9ab794e35940c92b8b0e9b1d4cff367c3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4langid.test @@ -0,0 +1,485 @@ +# 2012 March 01 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the languageid=xxx FTS4 option. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix fts4content + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +set ::testprefix fts4langid + +#--------------------------------------------------------------------------- +# Test plan: +# +# 1.* - Warm-body tests created for specific purposes during development. +# Passing these doesn't really prove much. +# +# 2.1.* - Test that FTS queries only ever return rows associated with +# the requested language. +# +# 2.2.* - Same as 2.1.*, after an 'optimize' command. +# +# 2.3.* - Same as 2.1.*, after a 'rebuild' command. +# +# 3.* - Tests with content= tables. Both where there is a real +# underlying content table and where there is not. +# +# 4.* - Test that if one is provided, the tokenizer xLanguage method +# is called to configure the tokenizer before tokenizing query +# or document text. +# +# 5.* - Test the fts4aux table when the associated FTS4 table contains +# multiple languages. +# + +do_execsql_test 1.1 { + CREATE VIRTUAL TABLE t1 USING fts4(a, b, languageid=lang_id); +} + +do_execsql_test 1.2 { + SELECT sql FROM sqlite_master WHERE name = 't1_content'; +} {{CREATE TABLE 't1_content'(docid INTEGER PRIMARY KEY, 'c0a', 'c1b', langid)}} + +do_execsql_test 1.3 {SELECT docid FROM t1} {} +do_execsql_test 1.4 {SELECT lang_id FROM t1} {} + +do_execsql_test 1.5 {INSERT INTO t1(a, b) VALUES('aaa', 'bbb')} +do_execsql_test 1.6 {SELECT lang_id FROM t1 } {0} + +do_execsql_test 1.7 {INSERT INTO t1(a, b, lang_id) VALUES('aaa', 'bbb', 4)} +do_execsql_test 1.8 {SELECT lang_id FROM t1 } {0 4} + +do_execsql_test 1.9 {INSERT INTO t1(a, b, lang_id) VALUES('aaa', 'bbb', 'xyz')} +do_execsql_test 1.10 {SELECT lang_id FROM t1} {0 4 0} + +do_execsql_test 1.11 { + CREATE VIRTUAL TABLE t2 USING fts4; + INSERT INTO t2 VALUES('abc'); +} +do_execsql_test 1.12 { SELECT rowid FROM t2 WHERE content MATCH 'abc' } 1 + +do_execsql_test 1.13 { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts4(languageid=lang_id); + INSERT INTO t1(content) VALUES('a b c'); + INSERT INTO t1(content, lang_id) VALUES('a b c', 1); +} + +do_execsql_test 1.14 { + SELECT rowid FROM t1 WHERE t1 MATCH 'b'; +} {1} +do_execsql_test 1.15 { + SELECT rowid FROM t1 WHERE t1 MATCH 'b' AND lang_id = 0; +} {1} + +do_execsql_test 1.16 { + SELECT rowid FROM t1 WHERE t1 MATCH 'b' AND lang_id = 1; +} {2} + +do_catchsql_test 1.17 { + INSERT INTO t1(content, lang_id) VALUES('123', -1); +} {1 {constraint failed}} + +do_execsql_test 1.18 { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts4(languageid=lang_id); + INSERT INTO t1(content, lang_id) VALUES('A', 13); + INSERT INTO t1(content, lang_id) VALUES('B', 13); + INSERT INTO t1(content, lang_id) VALUES('C', 13); + INSERT INTO t1(content, lang_id) VALUES('D', 13); + INSERT INTO t1(content, lang_id) VALUES('E', 13); + INSERT INTO t1(content, lang_id) VALUES('F', 13); + INSERT INTO t1(content, lang_id) VALUES('G', 13); + INSERT INTO t1(content, lang_id) VALUES('H', 13); + INSERT INTO t1(content, lang_id) VALUES('I', 13); + INSERT INTO t1(content, lang_id) VALUES('J', 13); + INSERT INTO t1(content, lang_id) VALUES('K', 13); + INSERT INTO t1(content, lang_id) VALUES('L', 13); + INSERT INTO t1(content, lang_id) VALUES('M', 13); + INSERT INTO t1(content, lang_id) VALUES('N', 13); + INSERT INTO t1(content, lang_id) VALUES('O', 13); + INSERT INTO t1(content, lang_id) VALUES('P', 13); + INSERT INTO t1(content, lang_id) VALUES('Q', 13); + INSERT INTO t1(content, lang_id) VALUES('R', 13); + INSERT INTO t1(content, lang_id) VALUES('S', 13); + SELECT rowid FROM t1 WHERE t1 MATCH 'A'; +} {} + + +#------------------------------------------------------------------------- +# Test cases 2.* +# +proc build_multilingual_db_1 {db} { + $db eval { CREATE VIRTUAL TABLE t2 USING fts4(x, y, languageid=l) } + + set xwords [list zero one two three four five six seven eight nine ten] + set ywords [list alpha beta gamma delta epsilon zeta eta theta iota kappa] + + for {set i 0} {$i < 1000} {incr i} { + set iLangid [expr $i%9] + set x "" + set y "" + + set x [list] + lappend x [lindex $xwords [expr ($i / 1000) % 10]] + lappend x [lindex $xwords [expr ($i / 100) % 10]] + lappend x [lindex $xwords [expr ($i / 10) % 10]] + lappend x [lindex $xwords [expr ($i / 1) % 10]] + + set y [list] + lappend y [lindex $ywords [expr ($i / 1000) % 10]] + lappend y [lindex $ywords [expr ($i / 100) % 10]] + lappend y [lindex $ywords [expr ($i / 10) % 10]] + lappend y [lindex $ywords [expr ($i / 1) % 10]] + + $db eval { INSERT INTO t2(docid, x, y, l) VALUES($i, $x, $y, $iLangid) } + } + + $db eval { + CREATE TABLE data(x, y, l); + INSERT INTO data(rowid, x, y, l) SELECT docid, x, y, l FROM t2; + } +} + +proc rowid_list_set_langid {langid} { + set ::rowid_list_langid $langid +} +proc rowid_list {pattern} { + set langid $::rowid_list_langid + set res [list] + db eval {SELECT rowid, x, y FROM data WHERE l = $langid ORDER BY rowid ASC} { + if {[string match "*$pattern*" $x] || [string match "*$pattern*" $y]} { + lappend res $rowid + } + } + return $res +} + +proc or_merge_list {list1 list2} { + set res [list] + + set i1 0 + set i2 0 + + set n1 [llength $list1] + set n2 [llength $list2] + + while {$i1 < $n1 && $i2 < $n2} { + set e1 [lindex $list1 $i1] + set e2 [lindex $list2 $i2] + + if {$e1==$e2} { + lappend res $e1 + incr i1 + incr i2 + } elseif {$e1 < $e2} { + lappend res $e1 + incr i1 + } else { + lappend res $e2 + incr i2 + } + } + + concat $res [lrange $list1 $i1 end] [lrange $list2 $i2 end] +} + +proc or_merge_lists {args} { + set res [lindex $args 0] + for {set i 1} {$i < [llength $args]} {incr i} { + set res [or_merge_list $res [lindex $args $i]] + } + set res +} + +proc and_merge_list {list1 list2} { + foreach i $list2 { set a($i) 1 } + set res [list] + foreach i $list1 { + if {[info exists a($i)]} {lappend res $i} + } + set res +} + + +proc and_merge_lists {args} { + set res [lindex $args 0] + for {set i 1} {$i < [llength $args]} {incr i} { + set res [and_merge_list $res [lindex $args $i]] + } + set res +} + +proc filter_list {list langid} { + set res [list] + foreach i $list { + if {($i % 9) == $langid} {lappend res $i} + } + set res +} + +do_test 2.0 { + reset_db + build_multilingual_db_1 db +} {} + +proc do_test_query1 {tn query res_script} { + for {set langid 0} {$langid < 10} {incr langid} { + rowid_list_set_langid $langid + set res [eval $res_script] + + set actual [ + execsql {SELECT docid FROM t2 WHERE t2 MATCH $query AND l = $langid} + ] + do_test $tn.$langid [list set {} $actual] $res + } +} + +# Run some queries. +do_test_query1 2.1.1 {delta} { rowid_list delta } +do_test_query1 2.1.2 {"zero one two"} { rowid_list "zero one two" } +do_test_query1 2.1.3 {zero one two} { + and_merge_lists [rowid_list zero] [rowid_list one] [rowid_list two] +} +do_test_query1 2.1.4 {"zero one" OR "one two"} { + or_merge_lists [rowid_list "zero one"] [rowid_list "one two"] +} + +# Now try the same tests as above, but after running the 'optimize' +# command on the FTS table. +# +do_execsql_test 2.2 { + INSERT INTO t2(t2) VALUES('optimize'); + SELECT count(*) FROM t2_segdir; +} {9} +do_test_query1 2.2.1 {delta} { rowid_list delta } +do_test_query1 2.2.2 {"zero one two"} { rowid_list "zero one two" } +do_test_query1 2.2.3 {zero one two} { + and_merge_lists [rowid_list zero] [rowid_list one] [rowid_list two] +} +do_test_query1 2.2.4 {"zero one" OR "one two"} { + or_merge_lists [rowid_list "zero one"] [rowid_list "one two"] +} + +# And rebuild. +# +do_test 2.3 { + reset_db + build_multilingual_db_1 db + execsql { INSERT INTO t2(t2) VALUES('rebuild') } +} {} +do_test_query1 2.3.1 {delta} { rowid_list delta } +do_test_query1 2.3.2 {"zero one two"} { rowid_list "zero one two" } +do_test_query1 2.3.3 {zero one two} { + and_merge_lists [rowid_list zero] [rowid_list one] [rowid_list two] +} +do_test_query1 2.3.4 {"zero one" OR "one two"} { + or_merge_lists [rowid_list "zero one"] [rowid_list "one two"] +} + +#------------------------------------------------------------------------- +# Test cases 3.* +# +do_test 3.0 { + reset_db + build_multilingual_db_1 db + execsql { + CREATE TABLE t3_data(l, x, y); + INSERT INTO t3_data(rowid, l, x, y) SELECT docid, l, x, y FROM t2; + DROP TABLE t2; + } +} {} +do_execsql_test 3.1 { + CREATE VIRTUAL TABLE t2 USING fts4(content=t3_data, languageid=l); + INSERT INTO t2(t2) VALUES('rebuild'); +} + +do_test_query1 3.1.1 {delta} { rowid_list delta } +do_test_query1 3.1.2 {"zero one two"} { rowid_list "zero one two" } +do_test_query1 3.1.3 {zero one two} { + and_merge_lists [rowid_list zero] [rowid_list one] [rowid_list two] +} +do_test_query1 3.1.4 {"zero one" OR "one two"} { + or_merge_lists [rowid_list "zero one"] [rowid_list "one two"] +} + +do_execsql_test 3.2.1 { + DROP TABLE t2; + CREATE VIRTUAL TABLE t2 USING fts4(x, y, languageid=l, content=nosuchtable); +} + +do_execsql_test 3.2.2 { + INSERT INTO t2(docid, x, y, l) SELECT rowid, x, y, l FROM t3_data; +} + +do_execsql_test 3.2.3 { + DROP TABLE t3_data; +} + +do_test_query1 3.3.1 {delta} { rowid_list delta } +do_test_query1 3.3.2 {"zero one two"} { rowid_list "zero one two" } +do_test_query1 3.3.3 {zero one two} { + and_merge_lists [rowid_list zero] [rowid_list one] [rowid_list two] +} +do_test_query1 3.3.4 {"zero one" OR "one two"} { + or_merge_lists [rowid_list "zero one"] [rowid_list "one two"] +} + +#------------------------------------------------------------------------- +# Test cases 4.* +# +proc build_multilingual_db_2 {db} { + $db eval { + CREATE VIRTUAL TABLE t4 USING fts4( + tokenize=testtokenizer, + languageid=lid + ); + } + for {set i 0} {$i < 50} {incr i} { + execsql { + INSERT INTO t4(docid, content, lid) VALUES($i, 'The Quick Brown Fox', $i) + } + } +} + +do_test 4.1.0 { + reset_db + set ptr [fts3_test_tokenizer] + execsql { SELECT fts3_tokenizer('testtokenizer', $ptr) } + build_multilingual_db_2 db +} {} +do_execsql_test 4.1.1 { + SELECT docid FROM t4 WHERE t4 MATCH 'quick'; +} {0} +do_execsql_test 4.1.2 { + SELECT docid FROM t4 WHERE t4 MATCH 'quick' AND lid=1; +} {} +do_execsql_test 4.1.3 { + SELECT docid FROM t4 WHERE t4 MATCH 'Quick' AND lid=1; +} {1} +for {set i 0} {$i < 50} {incr i} { + do_execsql_test 4.1.4.$i { + SELECT count(*) FROM t4 WHERE t4 MATCH 'fox' AND lid=$i; + } [expr 0==($i%2)] +} +do_catchsql_test 4.1.5 { + INSERT INTO t4(content, lid) VALUES('hello world', 101) +} {1 {SQL logic error or missing database}} + +#------------------------------------------------------------------------- +# Test cases 5.* +# +# The following test cases are designed to detect a 32-bit overflow bug +# that existed at one point. +# +proc build_multilingual_db_3 {db} { + $db eval { + CREATE VIRTUAL TABLE t5 USING fts4(languageid=lid); + } + set languages [list 0 1 2 [expr 1<<30]] + + foreach lid $languages { + execsql { + INSERT INTO t5(docid, content, lid) VALUES( + $lid, 'My language is ' || $lid, $lid + ) + } + } +} + +do_test 5.1.0 { + reset_db + build_multilingual_db_3 db +} {} + +do_execsql_test 5.1.1 { + SELECT level FROM t5_segdir; +} [list 0 1024 2048 [expr 1<<40]] + +do_execsql_test 5.1.2 {SELECT docid FROM t5 WHERE t5 MATCH 'language'} 0 +foreach langid [list 0 1 2 [expr 1<<30]] { + do_execsql_test 5.2.$langid { + SELECT docid FROM t5 WHERE t5 MATCH 'language' AND lid = $langid + } $langid +} + +set lid [expr 1<<30] +do_execsql_test 5.3.1 { + CREATE VIRTUAL TABLE t6 USING fts4(languageid=lid); + INSERT INTO t6 VALUES('I belong to language 0!'); +} +do_test 5.3.2 { + for {set i 0} {$i < 20} {incr i} { + execsql { + INSERT INTO t6(content, lid) VALUES( + 'I (row '||$i||') belong to langauge N!', $lid + ); + } + } + execsql { SELECT docid FROM t6 WHERE t6 MATCH 'belong' } +} {1} + +do_test 5.3.3 { + execsql { SELECT docid FROM t6 WHERE t6 MATCH 'belong' AND lid=$lid} +} {2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21} + +do_execsql_test 5.3.4 { INSERT INTO t6(t6) VALUES('optimize') } {} +do_execsql_test 5.3.5 { SELECT docid FROM t6 WHERE t6 MATCH 'belong' } {1} +do_execsql_test 5.3.6 { + SELECT docid FROM t6 WHERE t6 MATCH 'belong' AND lid=$lid +} {2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21} + + +set lid [expr 1<<30] +foreach lid [list 4 [expr 1<<30]] { + do_execsql_test 5.4.$lid.1 { + DELETE FROM t6; + SELECT count(*) FROM t6_segdir; + SELECT count(*) FROM t6_segments; + } {0 0} + do_execsql_test 5.4.$lid.2 { + INSERT INTO t6(content, lid) VALUES('zero zero zero', $lid); + INSERT INTO t6(content, lid) VALUES('zero zero one', $lid); + INSERT INTO t6(content, lid) VALUES('zero one zero', $lid); + INSERT INTO t6(content, lid) VALUES('zero one one', $lid); + INSERT INTO t6(content, lid) VALUES('one zero zero', $lid); + INSERT INTO t6(content, lid) VALUES('one zero one', $lid); + INSERT INTO t6(content, lid) VALUES('one one zero', $lid); + INSERT INTO t6(content, lid) VALUES('one one one', $lid); + + SELECT docid FROM t6 WHERE t6 MATCH '"zero zero"' AND lid=$lid; + } {1 2 5} + + do_execsql_test 5.4.$lid.3 { + SELECT count(*) FROM t6_segdir; + SELECT count(*) FROM t6_segments; + } {8 0} + + do_execsql_test 5.4.$lid.4 { + INSERT INTO t6(t6) VALUES('merge=100,3'); + INSERT INTO t6(t6) VALUES('merge=100,3'); + SELECT docid FROM t6 WHERE t6 MATCH '"zero zero"' AND lid=$lid; + } {1 2 5} + + do_execsql_test 5.4.$lid.5 { + SELECT count(*) FROM t6_segdir; + SELECT count(*) FROM t6_segments; + } {4 4} +} +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4merge.test b/components/external/SQLite-3.8.1/test/fts4merge.test new file mode 100644 index 0000000000000000000000000000000000000000..fabb651e6499aa598f93108b1917a1e7be236b45 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4merge.test @@ -0,0 +1,341 @@ +# 2012 March 06 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the incremental merge function. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/fts3_common.tcl + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +proc fts3_integrity_check {tbl} { + db eval "INSERT INTO $tbl ($tbl) VALUES('integrity-check')" + return "ok" +} + +foreach mod {fts3 fts4} { + set ::testprefix fts4merge-$mod + reset_db + + #------------------------------------------------------------------------- + # Test cases 1.* + # + do_test 1.0 { fts3_build_db_1 -module $mod 1004 } {} + do_test 1.1 { fts3_integrity_check t1 } {ok} + do_execsql_test 1.1 { + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level + } { + 0 {0 1 2 3 4 5 6 7 8 9 10 11} + 1 {0 1 2 3 4 5 6 7 8 9 10 11 12 13} + 2 {0 1 2} + } + + for {set i 0} {$i<20} {incr i} { + do_execsql_test 1.2.$i.1 { INSERT INTO t1(t1) VALUES('merge=1') } + do_test 1.2.$i.2 { fts3_integrity_check t1 } ok + do_execsql_test 1.2.$i.3 { + SELECT docid FROM t1 WHERE t1 MATCH 'zero one two three' + } {123 132 213 231 312 321} + } + + do_execsql_test 1.3 { + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level + } { + 0 {0 1 2 3} + 1 {0 1 2 3 4 5 6} + 2 {0 1 2 3} + } + + for {set i 0} {$i<100} {incr i} { + do_execsql_test 1.4.$i { INSERT INTO t1(t1) VALUES('merge=1,4') } + do_test 1.4.$i.2 { fts3_integrity_check t1 } ok + do_execsql_test 1.4.$i.3 { + SELECT docid FROM t1 WHERE t1 MATCH 'zero one two three' + } {123 132 213 231 312 321} + } + + do_execsql_test 1.5 { + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level + } { + 2 {0 1} + 3 0 + } + + #------------------------------------------------------------------------- + # Test cases 2.* test that errors in the xxx part of the 'merge=xxx' are + # handled correctly. + # + do_execsql_test 2.0 "CREATE VIRTUAL TABLE t2 USING $mod" + + foreach {tn arg} { + 1 {merge=abc} + 2 {merge=%%%} + 3 {merge=,} + 4 {merge=5,} + 5 {merge=6,%} + 6 {merge=6,six} + 7 {merge=6,1} + 8 {merge=6,0} + } { + do_catchsql_test 2.$tn { + INSERT INTO t2(t2) VALUES($arg); + } {1 {SQL logic error or missing database}} + } + + #------------------------------------------------------------------------- + # Test cases 3.* + # + do_test 3.0 { + reset_db + execsql { PRAGMA page_size = 512 } + fts3_build_db_2 -module $mod 30040 + } {} + do_test 3.1 { fts3_integrity_check t2 } {ok} + + do_execsql_test 3.2 { + SELECT level, group_concat(idx, ' ') FROM t2_segdir GROUP BY level + } { + 0 {0 1 2 3 4 5 6} + 1 {0 1 2 3 4} + 2 {0 1 2 3 4} + 3 {0 1 2 3 4 5 6} + } + + do_execsql_test 3.3 { + INSERT INTO t2(t2) VALUES('merge=1000000,2'); + SELECT level, group_concat(idx, ' ') FROM t2_segdir GROUP BY level + } { + 0 0 + 2 0 + 3 0 + 4 0 + 6 0 + } + + #------------------------------------------------------------------------- + # Test cases 4.* + # + reset_db + do_execsql_test 4.1 " + PRAGMA page_size = 512; + CREATE VIRTUAL TABLE t4 USING $mod; + PRAGMA main.page_size; + " {512} + + do_test 4.2 { + foreach x {a c b d e f g h i j k l m n o p} { + execsql "INSERT INTO t4 VALUES('[string repeat $x 600]')" + } + execsql {SELECT level, group_concat(idx, ' ') FROM t4_segdir GROUP BY level} + } {0 {0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}} + + foreach {tn expect} { + 1 "0 {0 1 2 3 4 5 6 7 8 9 10 11 12 13} 1 0" + 2 "0 {0 1 2 3 4 5 6 7 8 9 10 11 12} 1 0" + 3 "0 {0 1 2 3 4 5 6 7 8 9 10 11} 1 0" + 4 "0 {0 1 2 3 4 5 6 7 8 9 10} 1 0" + 5 "0 {0 1 2 3 4 5 6 7 8 9} 1 0" + 6 "0 {0 1 2 3 4 5 6 7 8} 1 0" + 7 "0 {0 1 2 3 4 5 6 7} 1 0" + 8 "0 {0 1 2 3 4 5 6} 1 0" + 9 "0 {0 1 2 3 4 5} 1 0" + } { + do_execsql_test 4.3.$tn { + INSERT INTO t4(t4) VALUES('merge=1,16'); + SELECT level, group_concat(idx, ' ') FROM t4_segdir GROUP BY level; + } $expect + } + + do_execsql_test 4.4.1 { + SELECT quote(value) FROM t4_stat WHERE rowid=1 + } {X'0006'} + + do_execsql_test 4.4.2 { + DELETE FROM t4_stat WHERE rowid=1; + INSERT INTO t4(t4) VALUES('merge=1,12'); + SELECT level, group_concat(idx, ' ') FROM t4_segdir GROUP BY level; + } "0 {0 1 2 3 4 5} 1 0" + + + #------------------------------------------------------------------------- + # Test cases 5.* + # + # Test that if a crisis-merge occurs that disrupts an ongoing incremental + # merge, the next call to "merge=A,B" identifies this and starts a new + # incremental merge. There are two scenarios: + # + # * There are less segments on the input level that the disrupted + # incremental merge operated on, or + # + # * Sufficient segments exist on the input level but the segments + # contain keys smaller than the largest key in the potential output + # segment. + # + do_test 5.1 { + reset_db + fts3_build_db_1 -module $mod 1000 + } {} + + do_execsql_test 5.2 { + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level; + } { + 0 {0 1 2 3 4 5 6 7} + 1 {0 1 2 3 4 5 6 7 8 9 10 11 12 13} + 2 {0 1 2} + } + + do_execsql_test 5.3 { + INSERT INTO t1(t1) VALUES('merge=1,5'); + INSERT INTO t1(t1) VALUES('merge=1,5'); + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level; + } { + 0 {0 1 2} + 1 {0 1 2 3 4 5 6 7 8 9 10 11 12 13 14} + 2 {0 1 2 3} + } + + do_execsql_test 5.4 {SELECT quote(value) from t1_stat WHERE rowid=1} {X'0105'} + do_test 5.5 { + foreach docid [execsql {SELECT docid FROM t1}] { + execsql {INSERT INTO t1 SELECT * FROM t1 WHERE docid=$docid} + } + } {} + + do_execsql_test 5.6 {SELECT quote(value) from t1_stat WHERE rowid=1} {X'0105'} + + do_execsql_test 5.7 { + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level; + SELECT quote(value) from t1_stat WHERE rowid=1; + } { + 0 {0 1 2 3 4 5 6 7 8 9 10} + 1 {0 1 2 3 4 5 6 7 8 9 10 11 12} + 2 {0 1 2 3 4 5 6 7} + X'0105' + } + + do_execsql_test 5.8 { + INSERT INTO t1(t1) VALUES('merge=1,6'); + INSERT INTO t1(t1) VALUES('merge=1,6'); + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level; + SELECT quote(value) from t1_stat WHERE rowid=1; + } { + 0 {0 1 2 3 4} + 1 {0 1 2 3 4 5 6 7 8 9 10 11 12 13} + 2 {0 1 2 3 4 5 6 7 8} X'0106' + } + + do_test 5.8.1 { fts3_integrity_check t1 } ok + + do_test 5.9 { + set L [expr 16*16*7 + 16*3 + 12] + foreach docid [execsql { + SELECT docid FROM t1 UNION ALL SELECT docid FROM t1 LIMIT $L + }] { + execsql {INSERT INTO t1 SELECT * FROM t1 WHERE docid=$docid} + } + } {} + + do_execsql_test 5.10 { + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level; + SELECT quote(value) from t1_stat WHERE rowid=1; + } { + 0 0 1 {0 1} 2 0 3 0 X'0106' + } + + do_execsql_test 5.11 { + INSERT INTO t1(t1) VALUES('merge=1,6'); + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level; + SELECT quote(value) from t1_stat WHERE rowid=1; + } { + 0 0 1 {0 1} 2 0 3 0 X'' + } + + #------------------------------------------------------------------------- + # Test cases 6.* + # + # At one point the following test caused an assert() to fail (because the + # second 'merge=1,2' operation below actually "merges" a single input + # segment, which was unexpected). + # + do_test 6.1 { + reset_db + set a [string repeat a 900] + set b [string repeat b 900] + set c [string repeat c 900] + set d [string repeat d 900] + + execsql "CREATE VIRTUAL TABLE t1 USING $mod" + execsql { + BEGIN; + INSERT INTO t1 VALUES($a); + INSERT INTO t1 VALUES($b); + COMMIT; + BEGIN; + INSERT INTO t1 VALUES($c); + INSERT INTO t1 VALUES($d); + COMMIT; + } + + execsql { + INSERT INTO t1(t1) VALUES('merge=1,2'); + INSERT INTO t1(t1) VALUES('merge=1,2'); + } + } {} + + #------------------------------------------------------------------------- + # Test cases 7.* + # + # Test that the value returned by sqlite3_total_changes() increases by + # 1 following a no-op "merge=A,B", or by more than 1 if actual work is + # performed. + # + do_test 7.0 { + reset_db + fts3_build_db_1 -module $mod 1000 + } {} + + do_execsql_test 7.1 { + SELECT level, group_concat(idx, ' ') FROM t1_segdir GROUP BY level + } { + 0 {0 1 2 3 4 5 6 7} + 1 {0 1 2 3 4 5 6 7 8 9 10 11 12 13} + 2 {0 1 2} + } + do_test 7.2 { + set x [db total_changes] + execsql { INSERT INTO t1(t1) VALUES('merge=2,10') } + expr { ([db total_changes] - $x)>1 } + } {1} + do_test 7.3 { + set x [db total_changes] + execsql { INSERT INTO t1(t1) VALUES('merge=200,10') } + expr { ([db total_changes] - $x)>1 } + } {1} + do_test 7.4 { + set x [db total_changes] + execsql { INSERT INTO t1(t1) VALUES('merge=200,10') } + expr { ([db total_changes] - $x)>1 } + } {0} + do_test 7.5 { + set x [db total_changes] + execsql { INSERT INTO t1(t1) VALUES('merge=200,10') } + expr { ([db total_changes] - $x)>1 } + } {0} + +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4merge2.test b/components/external/SQLite-3.8.1/test/fts4merge2.test new file mode 100644 index 0000000000000000000000000000000000000000..308b6929fab0338bc2050c26f486023a2483f2aa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4merge2.test @@ -0,0 +1,38 @@ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/fts3_common.tcl +source $testdir/malloc_common.tcl +set ::testprefix fts4merge2 + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + +do_test 1.0 { + fts3_build_db_1 1000 + faultsim_save_and_close +} {} + +do_faultsim_test 1.1 -faults oom-* -prep { + faultsim_restore_and_reopen +} -body { + execsql { INSERT INTO t1(t1) VALUES('merge=32,4') } +} -test { + faultsim_test_result {0 {}} +} + +do_faultsim_test 1.2 -faults oom-t* -prep { + if {$iFail<100} {set iFail 803} + faultsim_restore_and_reopen +} -body { + execsql { INSERT INTO t1(t1) VALUES('merge=1,2') } + execsql { INSERT INTO t1(t1) VALUES('merge=1,2') } +} -test { + faultsim_test_result {0 {}} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4merge3.test b/components/external/SQLite-3.8.1/test/fts4merge3.test new file mode 100644 index 0000000000000000000000000000000000000000..329b4d2cc4ea97720f5b52079af03654d2c17f59 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4merge3.test @@ -0,0 +1,105 @@ +# 2012 March 06 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the incremental merge function. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/fts3_common.tcl +source $testdir/lock_common.tcl +source $testdir/bc_common.tcl + +set ::testprefix fts4merge3 + +ifcapable !fts3 { + finish_test + return +} + +if {"" == [bc_find_binaries backcompat.test]} { + finish_test + return +} + +db close +do_all_bc_test { + + sql2 { PRAGMA page_size = 512 } + if { 0==[catch { sql2 { CREATE VIRTUAL TABLE x USING fts4 } } ] } { + + # Build a large database. + set msg "this takes around 12 seconds" + do_test "1.1 ($msg)" { fts3_build_db_2 20000 } {} + + # Run some queries on it, using the old and new versions. + do_test 1.2 { sql1 "SELECT docid FROM t2 WHERE t2 MATCH 'abc'" } {1485} + do_test 1.3 { sql2 "SELECT docid FROM t2 WHERE t2 MATCH 'abc'" } {1485} + + do_test 1.4 { + set x [sql2 "PRAGMA page_count"] + expr {$x>=1284 && $x<=1286} + } {1} + do_test 1.5 { sql2 { + SELECT level, count(*) FROM t2_segdir GROUP BY level ORDER BY 1 + } } [list 0 15 1 1 2 14 3 4] + + # Run some incr-merge operations on the db. + for {set i 0} {$i<10} {incr i} { + do_test 1.6.$i.1 { sql1 { INSERT INTO t2(t2) VALUES('merge=2,2') } } {} + do_test 1.6.$i.2 { + sql2 "SELECT docid FROM t2 WHERE t2 MATCH 'abc'" + } {1485} + } + + do_test 1.7 { sql2 { + SELECT level, count(*) FROM t2_segdir GROUP BY level ORDER BY 1 + } } [list 0 1 2 18 3 5] + + # Using the old connection, insert many rows. + do_test 1.8 { + for {set i 0} {$i < 1500} {incr i} { + sql2 "INSERT INTO t2 SELECT content FROM t2 WHERE docid = $i" + } + } {} + + do_test 1.9 { sql2 { + SELECT level, count(*) FROM t2_segdir GROUP BY level ORDER BY 1 + } } [list 0 13 1 13 2 5 3 6] + + # Run a big incr-merge operation on the db. + do_test 1.10 { sql1 { INSERT INTO t2(t2) VALUES('merge=2000,2') } } {} + do_test 1.11 { + sql2 "SELECT docid FROM t2 WHERE t2 MATCH 'abc'" + } {1485 21485} + + do_test 1.12 { + for {set i 0} {$i < 1500} {incr i} { + sql2 "INSERT INTO t2 SELECT content FROM t2 WHERE docid = $i" + } + } {} + do_test 1.13 { + sql2 "SELECT docid FROM t2 WHERE t2 MATCH 'abc'" + } {1485 21485 22985} + + do_test 1.14 { + sql2 "INSERT INTO t2(t2) VALUES('optimize')" + sql2 "SELECT docid FROM t2 WHERE t2 MATCH 'abc'" + } {1485 21485 22985} + + do_test 1.15 { sql2 { + SELECT level, count(*) FROM t2_segdir GROUP BY level ORDER BY 1 + } } {6 1} + } +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4merge4.test b/components/external/SQLite-3.8.1/test/fts4merge4.test new file mode 100644 index 0000000000000000000000000000000000000000..8e2119de2b1c63415364ccc7ee0b94fa6f91c12b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4merge4.test @@ -0,0 +1,58 @@ +# 2013 May 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/fts3_common.tcl +set ::testprefix fts4merge4 + +ifcapable !fts3 { + finish_test + return +} + +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +do_execsql_test 1.1 { CREATE VIRTUAL TABLE t1 USING fts4 } + +do_test 1.2 { + for {set i 0} {$i < 2000} {incr i} { + execsql {INSERT INTO t1 VALUES('a b c d e f g h i j k l');} + } +} {} + +do_test 1.3 { + execsql BEGIN + for {set i 0} {$i < 2000} {incr i} { + execsql {INSERT INTO t1 VALUES('a b c d e f g h i j k l');} + } + execsql { + INSERT INTO t1(t1) VALUES('merge=8,50'); + COMMIT + } +} {} + +reset_db +do_execsql_test 2.0 { CREATE VIRTUAL TABLE t1 USING fts4 } +do_test 2.1 { + for {set i 0} {$i < 2000} {incr i} { + execsql {INSERT INTO t1 VALUES('a b c d e f g h i j k l');} + } +} {} +do_execsql_test 2.2 { SELECT count(*) FROM t1_segdir; } 35 +do_execsql_test 2.3 { INSERT INTO t1(t1) VALUES('optimize') } {} +do_execsql_test 2.4 { SELECT count(*) FROM t1_segdir; } 1 + + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/fts4noti.test b/components/external/SQLite-3.8.1/test/fts4noti.test new file mode 100644 index 0000000000000000000000000000000000000000..e926228330dda3f3f7f8d733b6f4dec92b364b64 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4noti.test @@ -0,0 +1,171 @@ +# 2013 June 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing the notindexed=xxx FTS4 option. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix fts4noti + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { + finish_test + return +} + + +#------------------------------------------------------------------------- +# Test that typos in "notindexed=" column names are detected. +# +do_execsql_test 1.0 { + CREATE TABLE cc(a, b, c); +} +foreach {tn arg res} { + 1 "(b, c, notindexed=a)" {1 {no such column: a}} + 2 "(a, b, notindexed=a)" {0 {}} + 3 "(a, b, notindexed=a, notindexed=a)" {0 {}} + 4 "(notindexed=a, a, b)" {0 {}} + 5 "(notindexed=a, notindexed=b, notindexed=c, a, b, c, d)" {0 {}} + 6 "(notindexed=a, notindexed=B, notindexed=c, a, b, c, d)" {0 {}} + 7 "(notindexed=a, notindexed=b, notindexed=c, a, B, c, d)" {0 {}} + 8 "(notindexed=d, content=cc)" {1 {no such column: d}} + 9 "(notindexed=a, content=cc)" {0 {}} + 10 "(notindexed=a, notindexed=b, a)" {1 {no such column: b}} + 11 "(notindexed=a, notindexed=b, b)" {1 {no such column: a}} +} { + do_catchsql_test 1.$tn "CREATE VIRTUAL TABLE t1 USING fts4 $arg" $res + if {[lindex $res 0]==0} { execsql "DROP TABLE t1" } +} + +do_execsql_test 1.x { SELECT name FROM sqlite_master } {cc} + + +#------------------------------------------------------------------------- +# Test that notindexed columns are not indexed. +# +foreach {tn schema} { + 1 { + CREATE VIRTUAL TABLE t1 USING fts4(a, b, c, notindexed=b); + } + 2 { + CREATE TABLE c1(a, b, c); + INSERT INTO c1 VALUES('one two', 'three four', 'five six'); + INSERT INTO c1 VALUES('three four', 'five six', 'one two'); + CREATE VIRTUAL TABLE t1 USING fts4(content=c1, notindexed=b); + } + 3 { + CREATE VIRTUAL TABLE t1 USING fts4(content="", a, b, c, notindexed=b); + } +} { + execsql $schema + + do_execsql_test 2.$tn.1 { + INSERT INTO t1(docid,a,b,c) VALUES(1, 'one two', 'three four', 'five six'); + INSERT INTO t1(docid,a,b,c) VALUES(2, 'three four', 'five six', 'one two'); + } + + do_execsql_test 2.$tn.2 { SELECT docid FROM t1 WHERE t1 MATCH 'one' } {1 2} + do_execsql_test 2.$tn.3 { SELECT docid FROM t1 WHERE t1 MATCH 'three' } {2} + do_execsql_test 2.$tn.4 { SELECT docid FROM t1 WHERE t1 MATCH 'five' } {1} + + do_execsql_test 2.$tn.5 { INSERT INTO t1(t1) VALUES('optimize') } + + do_execsql_test 2.$tn.6 { SELECT docid FROM t1 WHERE t1 MATCH 'one' } {1 2} + do_execsql_test 2.$tn.7 { SELECT docid FROM t1 WHERE t1 MATCH 'three' } {2} + do_execsql_test 2.$tn.8 { SELECT docid FROM t1 WHERE t1 MATCH 'five' } {1} + + if {$tn!=3} { + do_execsql_test 2.$tn.9 { INSERT INTO t1(t1) VALUES('rebuild') } + + do_execsql_test 2.$tn.10 { SELECT docid FROM t1 WHERE t1 MATCH 'one' } {1 2} + do_execsql_test 2.$tn.11 { SELECT docid FROM t1 WHERE t1 MATCH 'three' } {2} + do_execsql_test 2.$tn.12 { SELECT docid FROM t1 WHERE t1 MATCH 'five' } {1} + + do_execsql_test 2.$tn.13 { + SELECT a,b,c FROM t1 WHERE docid=1 + } {{one two} {three four} {five six}} + do_execsql_test 2.$tn.14 { + SELECT a,b,c FROM t1 WHERE docid=2 + } {{three four} {five six} {one two}} + } + + do_execsql_test 2.x { DROP TABLE t1 } +} + +#------------------------------------------------------------------------- +# Test that notindexed columns are not scanned for deferred tokens. +# + +do_execsql_test 3.1 { + CREATE VIRTUAL TABLE t2 USING fts4(x, y, notindexed=x); +} +do_test 3.2 { + set v [string repeat " 1" 50000] + set v1 "x $v" + set v2 "y $v" + execsql { + INSERT INTO t2 VALUES(1, 'x y z'); + INSERT INTO t2 VALUES(2, $v1); + INSERT INTO t2 VALUES(3, $v2); + INSERT INTO t2 VALUES(4, $v2); + INSERT INTO t2 VALUES(5, $v2); + INSERT INTO t2 VALUES(6, $v2); + } +} {} + +do_execsql_test 3.3 { SELECT x FROM t2 WHERE t2 MATCH '2' } {} +do_execsql_test 3.4 { SELECT x FROM t2 WHERE t2 MATCH '1' } {2 3 4 5 6} +do_execsql_test 3.5 { SELECT x FROM t2 WHERE t2 MATCH 'x' } {1 2} +do_execsql_test 3.6 { SELECT x FROM t2 WHERE t2 MATCH 'x 1' } {2} + +do_execsql_test 3.x { DROP TABLE t2 } + +#------------------------------------------------------------------------- +# Test that the types of notindexed columns are not modified. +# +do_execsql_test 4.1 { + CREATE VIRTUAL TABLE t2 USING fts4(poi, addr, notindexed=poi); + INSERT INTO t2 VALUES(114, 'x x x'); + INSERT INTO t2 VALUES(X'1234', 'y y y'); + INSERT INTO t2 VALUES(NULL, 'z z z'); + INSERT INTO t2 VALUES(113.2, 'w w w'); + INSERT INTO t2 VALUES('poi', 'v v v'); +} +do_execsql_test 4.2 { SELECT typeof(poi) FROM t2 WHERE t2 MATCH 'x' } {integer} +do_execsql_test 4.3 { SELECT typeof(poi) FROM t2 WHERE t2 MATCH 'y' } {blob} +do_execsql_test 4.4 { SELECT typeof(poi) FROM t2 WHERE t2 MATCH 'z' } {null} +do_execsql_test 4.5 { SELECT typeof(poi) FROM t2 WHERE t2 MATCH 'w' } {real} +do_execsql_test 4.6 { SELECT typeof(poi) FROM t2 WHERE t2 MATCH 'v' } {text} + +do_execsql_test 4.x { DROP TABLE t2 } + +#------------------------------------------------------------------------- +# Test that multiple notindexed options on a single table work as expected. +# +do_execsql_test 5.1 { + CREATE VIRTUAL TABLE t2 USING fts4( + notindexed="three", one, two, three, notindexed="one", + ); + INSERT INTO t2 VALUES('a', 'b', 'c'); + INSERT INTO t2 VALUES('c', 'a', 'b'); + INSERT INTO t2 VALUES('b', 'c', 'a'); +} +do_execsql_test 5.2 { SELECT docid FROM t2 WHERE t2 MATCH 'a' } {2} +do_execsql_test 5.3 { SELECT docid FROM t2 WHERE t2 MATCH 'b' } {1} +do_execsql_test 5.4 { SELECT docid FROM t2 WHERE t2 MATCH 'c' } {3} + +do_execsql_test 5.x { DROP TABLE t2 } + +finish_test + + + diff --git a/components/external/SQLite-3.8.1/test/fts4unicode.test b/components/external/SQLite-3.8.1/test/fts4unicode.test new file mode 100644 index 0000000000000000000000000000000000000000..8edc2877da899d7799dc3ad9d2f73adccf1ba553 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fts4unicode.test @@ -0,0 +1,563 @@ +# 2012 May 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# +# The tests in this file focus on testing the "unicode" FTS tokenizer. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !fts3_unicode { finish_test ; return } +set ::testprefix fts4unicode + +proc do_unicode_token_test {tn input res} { + set input [string map {' ''} $input] + uplevel [list do_execsql_test $tn " + SELECT fts3_tokenizer_test('unicode61', 'remove_diacritics=0', '$input'); + " [list [list {*}$res]]] +} + +proc do_unicode_token_test2 {tn input res} { + set input [string map {' ''} $input] + uplevel [list do_execsql_test $tn " + SELECT fts3_tokenizer_test('unicode61', '$input'); + " [list [list {*}$res]]] +} + +proc do_unicode_token_test3 {tn args} { + set res [lindex $args end] + set sql "SELECT fts3_tokenizer_test('unicode61'" + foreach a [lrange $args 0 end-1] { + append sql ", '" + append sql [string map {' ''} $a] + append sql "'" + } + append sql ")" + uplevel [list do_execsql_test $tn $sql [list [list {*}$res]]] +} + +do_unicode_token_test 1.0 {a B c D} {0 a a 1 b B 2 c c 3 d D} + +do_unicode_token_test 1.1 "\uC4 \uD6 \uDC" \ + "0 \uE4 \uC4 1 \uF6 \uD6 2 \uFC \uDC" + +do_unicode_token_test 1.2 "x\uC4x x\uD6x x\uDCx" \ + "0 x\uE4x x\uC4x 1 x\uF6x x\uD6x 2 x\uFCx x\uDCx" + +# 0x00DF is a small "sharp s". 0x1E9E is a capital sharp s. +do_unicode_token_test 1.3 "\uDF" "0 \uDF \uDF" +do_unicode_token_test 1.4 "\u1E9E" "0 \uDF \u1E9E" + +do_unicode_token_test 1.5 "The quick brown fox" { + 0 the The 1 quick quick 2 brown brown 3 fox fox +} +do_unicode_token_test 1.6 "The\u00bfquick\u224ebrown\u2263fox" { + 0 the The 1 quick quick 2 brown brown 3 fox fox +} + +do_unicode_token_test2 1.7 {a B c D} {0 a a 1 b B 2 c c 3 d D} +do_unicode_token_test2 1.8 "\uC4 \uD6 \uDC" "0 a \uC4 1 o \uD6 2 u \uDC" + +do_unicode_token_test2 1.9 "x\uC4x x\uD6x x\uDCx" \ + "0 xax x\uC4x 1 xox x\uD6x 2 xux x\uDCx" + +# Check that diacritics are removed if remove_diacritics=1 is specified. +# And that they do not break tokens. +do_unicode_token_test2 1.10 "xx\u0301xx" "0 xxxx xx\u301xx" + +# Title-case mappings work +do_unicode_token_test 1.11 "\u01c5" "0 \u01c6 \u01c5" + +#------------------------------------------------------------------------- +# +set docs [list { + Enhance the INSERT syntax to allow multiple rows to be inserted via the + VALUES clause. +} { + Enhance the CREATE VIRTUAL TABLE command to support the IF NOT EXISTS clause. +} { + Added the sqlite3_stricmp() interface as a counterpart to sqlite3_strnicmp(). +} { + Added the sqlite3_db_readonly() interface. +} { + Added the SQLITE_FCNTL_PRAGMA file control, giving VFS implementations the + ability to add new PRAGMA statements or to override built-in PRAGMAs. +} { + Queries of the form: "SELECT max(x), y FROM table" returns the value of y on + the same row that contains the maximum x value. +} { + Added support for the FTS4 languageid option. +} { + Documented support for the FTS4 content option. This feature has actually + been in the code since version 3.7.9 but is only now considered to be + officially supported. +} { + Pending statements no longer block ROLLBACK. Instead, the pending statement + will return SQLITE_ABORT upon next access after the ROLLBACK. +} { + Improvements to the handling of CSV inputs in the command-line shell +} { + Fix a bug introduced in version 3.7.10 that might cause a LEFT JOIN to be + incorrectly converted into an INNER JOIN if the WHERE clause indexable terms + connected by OR. +}] + +set map(a) [list "\u00C4" "\u00E4"] ; # LATIN LETTER A WITH DIAERESIS +set map(e) [list "\u00CB" "\u00EB"] ; # LATIN LETTER E WITH DIAERESIS +set map(i) [list "\u00CF" "\u00EF"] ; # LATIN LETTER I WITH DIAERESIS +set map(o) [list "\u00D6" "\u00F6"] ; # LATIN LETTER O WITH DIAERESIS +set map(u) [list "\u00DC" "\u00FC"] ; # LATIN LETTER U WITH DIAERESIS +set map(y) [list "\u0178" "\u00FF"] ; # LATIN LETTER Y WITH DIAERESIS +set map(h) [list "\u1E26" "\u1E27"] ; # LATIN LETTER H WITH DIAERESIS +set map(w) [list "\u1E84" "\u1E85"] ; # LATIN LETTER W WITH DIAERESIS +set map(x) [list "\u1E8C" "\u1E8D"] ; # LATIN LETTER X WITH DIAERESIS +foreach k [array names map] { + lappend mappings [string toupper $k] [lindex $map($k) 0] + lappend mappings $k [lindex $map($k) 1] +} +proc mapdoc {doc} { + set doc [regsub -all {[[:space:]]+} $doc " "] + string map $::mappings [string trim $doc] +} + +do_test 2.0 { + execsql { CREATE VIRTUAL TABLE t2 USING fts4(tokenize=unicode61, x); } + foreach doc $docs { + set d [mapdoc $doc] + execsql { INSERT INTO t2 VALUES($d) } + } +} {} + +do_test 2.1 { + set q [mapdoc "row"] + execsql { SELECT * FROM t2 WHERE t2 MATCH $q } +} [list [mapdoc { + Queries of the form: "SELECT max(x), y FROM table" returns the value of y on + the same row that contains the maximum x value. +}]] + +foreach {tn query snippet} { + 2 "row" { + ...returns the value of y on the same [row] that contains + the maximum x value. + } + 3 "ROW" { + ...returns the value of y on the same [row] that contains + the maximum x value. + } + 4 "rollback" { + ...[ROLLBACK]. Instead, the pending statement + will return SQLITE_ABORT upon next access after the [ROLLBACK]. + } + 5 "rOllback" { + ...[ROLLBACK]. Instead, the pending statement + will return SQLITE_ABORT upon next access after the [ROLLBACK]. + } + 6 "lang*" { + Added support for the FTS4 [languageid] option. + } +} { + do_test 2.$tn { + set q [mapdoc $query] + execsql { SELECT snippet(t2, '[', ']', '...') FROM t2 WHERE t2 MATCH $q } + } [list [mapdoc $snippet]] +} + +#------------------------------------------------------------------------- +# Make sure the unicode61 tokenizer does not crash if it is passed a +# NULL pointer. +reset_db +do_execsql_test 3.1 { + CREATE VIRTUAL TABLE t1 USING fts4(tokenize=unicode61, x, y); + INSERT INTO t1 VALUES(NULL, 'a b c'); +} + +do_execsql_test 3.2 { + SELECT snippet(t1, '[', ']') FROM t1 WHERE t1 MATCH 'b' +} {{a [b] c}} + +do_execsql_test 3.3 { + BEGIN; + DELETE FROM t1; + INSERT INTO t1 VALUES('b b b b b b b b b b b', 'b b b b b b b b b b b b b'); + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 VALUES('a b c', NULL); + INSERT INTO t1 VALUES('a x c', NULL); + COMMIT; +} + +do_execsql_test 3.4 { + SELECT * FROM t1 WHERE t1 MATCH 'a b'; +} {{a b c} {}} + +#------------------------------------------------------------------------- +# +reset_db + +do_test 4.1 { + set a "abc\uFFFEdef" + set b "abc\uD800def" + set c "\uFFFEdef" + set d "\uD800def" + execsql { + CREATE VIRTUAL TABLE t1 USING fts4(tokenize=unicode61, x); + INSERT INTO t1 VALUES($a); + INSERT INTO t1 VALUES($b); + INSERT INTO t1 VALUES($c); + INSERT INTO t1 VALUES($d); + } +} {} + +do_test 4.2 { + set a [binary format c* {0x61 0xF7 0xBF 0xBF 0xBF 0x62}] + set b [binary format c* {0x61 0xF7 0xBF 0xBF 0xBF 0xBF 0x62}] + set c [binary format c* {0x61 0xF7 0xBF 0xBF 0xBF 0xBF 0xBF 0x62}] + set d [binary format c* {0x61 0xF7 0xBF 0xBF 0xBF 0xBF 0xBF 0xBF 0x62}] + execsql { + INSERT INTO t1 VALUES($a); + INSERT INTO t1 VALUES($b); + INSERT INTO t1 VALUES($c); + INSERT INTO t1 VALUES($d); + } +} {} + +do_test 4.3 { + set a [binary format c* {0xF7 0xBF 0xBF 0xBF}] + set b [binary format c* {0xF7 0xBF 0xBF 0xBF 0xBF}] + set c [binary format c* {0xF7 0xBF 0xBF 0xBF 0xBF 0xBF}] + set d [binary format c* {0xF7 0xBF 0xBF 0xBF 0xBF 0xBF 0xBF}] + execsql { + INSERT INTO t1 VALUES($a); + INSERT INTO t1 VALUES($b); + INSERT INTO t1 VALUES($c); + INSERT INTO t1 VALUES($d); + } +} {} + +#------------------------------------------------------------------------- + +do_unicode_token_test3 5.1 {tokenchars=} { + sqlite3_reset sqlite3_column_int +} { + 0 sqlite3 sqlite3 + 1 reset reset + 2 sqlite3 sqlite3 + 3 column column + 4 int int +} + +do_unicode_token_test3 5.2 {tokenchars=_} { + sqlite3_reset sqlite3_column_int +} { + 0 sqlite3_reset sqlite3_reset + 1 sqlite3_column_int sqlite3_column_int +} + +do_unicode_token_test3 5.3 {separators=xyz} { + Laotianxhorseyrunszfast +} { + 0 laotian Laotian + 1 horse horse + 2 runs runs + 3 fast fast +} + +do_unicode_token_test3 5.4 {tokenchars=xyz} { + Laotianxhorseyrunszfast +} { + 0 laotianxhorseyrunszfast Laotianxhorseyrunszfast +} + +do_unicode_token_test3 5.5 {tokenchars=_} {separators=zyx} { + sqlite3_resetxsqlite3_column_intyhonda_phantom +} { + 0 sqlite3_reset sqlite3_reset + 1 sqlite3_column_int sqlite3_column_int + 2 honda_phantom honda_phantom +} + +do_unicode_token_test3 5.6 "separators=\u05D1" "abc\u05D1def" { + 0 abc abc 1 def def +} + +do_unicode_token_test3 5.7 \ + "tokenchars=\u2444\u2445" \ + "separators=\u05D0\u05D1\u05D2" \ + "\u2444fre\u2445sh\u05D0water\u05D2fish.\u2445timer" \ + [list \ + 0 \u2444fre\u2445sh \u2444fre\u2445sh \ + 1 water water \ + 2 fish fish \ + 3 \u2445timer \u2445timer \ + ] + +# Check that it is not possible to add a standalone diacritic codepoint +# to either separators or tokenchars. +do_unicode_token_test3 5.8 "separators=\u0301" \ + "hello\u0301world \u0301helloworld" \ + "0 helloworld hello\u0301world 1 helloworld helloworld" + +do_unicode_token_test3 5.9 "tokenchars=\u0301" \ + "hello\u0301world \u0301helloworld" \ + "0 helloworld hello\u0301world 1 helloworld helloworld" + +do_unicode_token_test3 5.10 "separators=\u0301" \ + "remove_diacritics=0" \ + "hello\u0301world \u0301helloworld" \ + "0 hello\u0301world hello\u0301world 1 helloworld helloworld" + +do_unicode_token_test3 5.11 "tokenchars=\u0301" \ + "remove_diacritics=0" \ + "hello\u0301world \u0301helloworld" \ + "0 hello\u0301world hello\u0301world 1 helloworld helloworld" + + +#------------------------------------------------------------------------- + +proc do_tokenize {tokenizer txt} { + set res [list] + foreach {a b c} [db one {SELECT fts3_tokenizer_test($tokenizer, $txt)}] { + lappend res $b + } + set res +} + +# Argument $lCodepoint must be a list of codepoints (integers) that +# correspond to whitespace characters. This command creates a string +# $W from the codepoints, then tokenizes "${W}hello{$W}world${W}" +# using tokenizer $tokenizer. The test passes if the tokenizer successfully +# extracts the two 5 character tokens. +# +proc do_isspace_test {tn tokenizer lCp} { + set whitespace [format [string repeat %c [llength $lCp]] {*}$lCp] + set txt "${whitespace}hello${whitespace}world${whitespace}" + uplevel [list do_test $tn [list do_tokenize $tokenizer $txt] {hello world}] +} + +set tokenizers [list unicode61] +ifcapable icu { lappend tokenizers icu } + +# Some tests to check that the tokenizers can both identify white-space +# codepoints. All codepoints tested below are of type "Zs" in the +# UnicodeData.txt file. +foreach T $tokenizers { + do_isspace_test 6.$T.1 $T 32 + do_isspace_test 6.$T.2 $T 160 + do_isspace_test 6.$T.3 $T 5760 + do_isspace_test 6.$T.4 $T 6158 + do_isspace_test 6.$T.5 $T 8192 + do_isspace_test 6.$T.6 $T 8193 + do_isspace_test 6.$T.7 $T 8194 + do_isspace_test 6.$T.8 $T 8195 + do_isspace_test 6.$T.9 $T 8196 + do_isspace_test 6.$T.10 $T 8197 + do_isspace_test 6.$T.11 $T 8198 + do_isspace_test 6.$T.12 $T 8199 + do_isspace_test 6.$T.13 $T 8200 + do_isspace_test 6.$T.14 $T 8201 + do_isspace_test 6.$T.15 $T 8202 + do_isspace_test 6.$T.16 $T 8239 + do_isspace_test 6.$T.17 $T 8287 + do_isspace_test 6.$T.18 $T 12288 + + do_isspace_test 6.$T.19 $T {32 160 5760 6158} + do_isspace_test 6.$T.20 $T {8192 8193 8194 8195} + do_isspace_test 6.$T.21 $T {8196 8197 8198 8199} + do_isspace_test 6.$T.22 $T {8200 8201 8202 8239} + do_isspace_test 6.$T.23 $T {8287 12288} +} + +#------------------------------------------------------------------------- +# Test that the private use ranges are treated as alphanumeric. +# +breakpoint +foreach {tn1 c} { + 1 \ue000 2 \ue001 3 \uf000 4 \uf8fe 5 \uf8ff +} { + foreach {tn2 config res} { + 1 "" "0 hello*world hello*world" + 2 "separators=*" "0 hello hello 1 world world" + } { + set config [string map [list * $c] $config] + set input [string map [list * $c] "hello*world"] + set output [string map [list * $c] $res] + do_unicode_token_test3 7.$tn1.$tn2 {*}$config $input $output + } +} + +#------------------------------------------------------------------------- +# Cursory test of remove_diacritics=0. +# +# 00C4;LATIN CAPITAL LETTER A WITH DIAERESIS +# 00D6;LATIN CAPITAL LETTER O WITH DIAERESIS +# 00E4;LATIN SMALL LETTER A WITH DIAERESIS +# 00F6;LATIN SMALL LETTER O WITH DIAERESIS +# +do_execsql_test 8.1.1 " + CREATE VIRTUAL TABLE t3 USING fts4(tokenize=unicode61 'remove_diacritics=1'); + INSERT INTO t3 VALUES('o'); + INSERT INTO t3 VALUES('a'); + INSERT INTO t3 VALUES('O'); + INSERT INTO t3 VALUES('A'); + INSERT INTO t3 VALUES('\xD6'); + INSERT INTO t3 VALUES('\xC4'); + INSERT INTO t3 VALUES('\xF6'); + INSERT INTO t3 VALUES('\xE4'); +" +do_execsql_test 8.1.2 { + SELECT rowid FROM t3 WHERE t3 MATCH 'o'; +} {1 3 5 7} +do_execsql_test 8.1.3 { + SELECT rowid FROM t3 WHERE t3 MATCH 'a'; +} {2 4 6 8} +do_execsql_test 8.2.1 { + CREATE VIRTUAL TABLE t4 USING fts4(tokenize=unicode61 "remove_diacritics=0"); + INSERT INTO t4 SELECT * FROM t3; +} +do_execsql_test 8.2.2 { + SELECT rowid FROM t4 WHERE t4 MATCH 'o'; +} {1 3} +do_execsql_test 8.2.3 { + SELECT rowid FROM t4 WHERE t4 MATCH 'a'; +} {2 4} + +#------------------------------------------------------------------------- +# +foreach {tn sql} { + 1 { + CREATE VIRTUAL TABLE t5 USING fts4(tokenize=unicode61 [tokenchars= .]); + CREATE VIRTUAL TABLE t6 USING fts4( + tokenize=unicode61 [tokenchars=="] "tokenchars=[]"); + CREATE VIRTUAL TABLE t7 USING fts4(tokenize=unicode61 [separators=x\xC4]); + } + 2 { + CREATE VIRTUAL TABLE t5 USING fts4(tokenize=unicode61 "tokenchars= ."); + CREATE VIRTUAL TABLE t6 USING fts4(tokenize=unicode61 "tokenchars=[=""]"); + CREATE VIRTUAL TABLE t7 USING fts4(tokenize=unicode61 "separators=x\xC4"); + } + 3 { + CREATE VIRTUAL TABLE t5 USING fts4(tokenize=unicode61 'tokenchars= .'); + CREATE VIRTUAL TABLE t6 USING fts4(tokenize=unicode61 'tokenchars=="[]'); + CREATE VIRTUAL TABLE t7 USING fts4(tokenize=unicode61 'separators=x\xC4'); + } + 4 { + CREATE VIRTUAL TABLE t5 USING fts4(tokenize=unicode61 `tokenchars= .`); + CREATE VIRTUAL TABLE t6 USING fts4(tokenize=unicode61 `tokenchars=[="]`); + CREATE VIRTUAL TABLE t7 USING fts4(tokenize=unicode61 `separators=x\xC4`); + } +} { + do_execsql_test 9.$tn.0 { + DROP TABLE IF EXISTS t5; + DROP TABLE IF EXISTS t5aux; + DROP TABLE IF EXISTS t6; + DROP TABLE IF EXISTS t6aux; + DROP TABLE IF EXISTS t7; + DROP TABLE IF EXISTS t7aux; + } + do_execsql_test 9.$tn.1 $sql + + do_execsql_test 9.$tn.2 { + CREATE VIRTUAL TABLE t5aux USING fts4aux(t5); + INSERT INTO t5 VALUES('one two three/four.five.six'); + SELECT * FROM t5aux; + } { + four.five.six * 1 1 four.five.six 0 1 1 + {one two three} * 1 1 {one two three} 0 1 1 + } + + do_execsql_test 9.$tn.3 { + CREATE VIRTUAL TABLE t6aux USING fts4aux(t6); + INSERT INTO t6 VALUES('alpha=beta"gamma/delta[epsilon]zeta'); + SELECT * FROM t6aux; + } { + {alpha=beta"gamma} * 1 1 {alpha=beta"gamma} 0 1 1 + {delta[epsilon]zeta} * 1 1 {delta[epsilon]zeta} 0 1 1 + } + + do_execsql_test 9.$tn.4 { + CREATE VIRTUAL TABLE t7aux USING fts4aux(t7); + INSERT INTO t7 VALUES('alephxbeth\xC4gimel'); + SELECT * FROM t7aux; + } { + aleph * 1 1 aleph 0 1 1 + beth * 1 1 beth 0 1 1 + gimel * 1 1 gimel 0 1 1 + } +} + +# Check that multiple options are handled correctly. +# +do_execsql_test 10.1 { + DROP TABLE IF EXISTS t1; + CREATE VIRTUAL TABLE t1 USING fts4(tokenize=unicode61 + "tokenchars=xyz" "tokenchars=.=" "separators=.=" "separators=xy" + "separators=a" "separators=a" "tokenchars=a" "tokenchars=a" + ); + + INSERT INTO t1 VALUES('oneatwoxthreeyfour'); + INSERT INTO t1 VALUES('a.single=word'); + CREATE VIRTUAL TABLE t1aux USING fts4aux(t1); + SELECT * FROM t1aux; +} { + .single=word * 1 1 .single=word 0 1 1 + four * 1 1 four 0 1 1 + one * 1 1 one 0 1 1 + three * 1 1 three 0 1 1 + two * 1 1 two 0 1 1 +} + +# Test that case folding happens after tokenization, not before. +# +do_execsql_test 10.2 { + DROP TABLE IF EXISTS t2; + CREATE VIRTUAL TABLE t2 USING fts4(tokenize=unicode61 "separators=aB"); + INSERT INTO t2 VALUES('oneatwoBthree'); + INSERT INTO t2 VALUES('onebtwoAthree'); + CREATE VIRTUAL TABLE t2aux USING fts4aux(t2); + SELECT * FROM t2aux; +} { + one * 1 1 one 0 1 1 + onebtwoathree * 1 1 onebtwoathree 0 1 1 + three * 1 1 three 0 1 1 + two * 1 1 two 0 1 1 +} + +# Test that the tokenchars and separators options work with the +# fts3tokenize table. +# +do_execsql_test 11.1 { + CREATE VIRTUAL TABLE ft1 USING fts3tokenize( + "unicode61", "tokenchars=@.", "separators=1234567890" + ); + SELECT token FROM ft1 WHERE input = 'berlin@street123sydney.road'; +} { + berlin@street sydney.road +} + +finish_test + + + + diff --git a/components/external/SQLite-3.8.1/test/full.test b/components/external/SQLite-3.8.1/test/full.test new file mode 100644 index 0000000000000000000000000000000000000000..a8fe37144982582d1b1e3b191cc6962fb1adf454 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/full.test @@ -0,0 +1,20 @@ +# 2012 September 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs the "full" test suite. It is a peer of the quick.test +# and all.test scripts. +# + +set testdir [file dirname $argv0] +source $testdir/permutations.test + +run_test_suite full + +finish_test diff --git a/components/external/SQLite-3.8.1/test/func.test b/components/external/SQLite-3.8.1/test/func.test new file mode 100644 index 0000000000000000000000000000000000000000..7c7d55e1b706a9c16bd321cb3e3f4f0722645e4c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/func.test @@ -0,0 +1,1346 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing built-in functions. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix func + +# Create a table to work with. +# +do_test func-0.0 { + execsql {CREATE TABLE tbl1(t1 text)} + foreach word {this program is free software} { + execsql "INSERT INTO tbl1 VALUES('$word')" + } + execsql {SELECT t1 FROM tbl1 ORDER BY t1} +} {free is program software this} +do_test func-0.1 { + execsql { + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(NULL); + INSERT INTO t2 VALUES(345); + INSERT INTO t2 VALUES(NULL); + INSERT INTO t2 VALUES(67890); + SELECT * FROM t2; + } +} {1 {} 345 {} 67890} + +# Check out the length() function +# +do_test func-1.0 { + execsql {SELECT length(t1) FROM tbl1 ORDER BY t1} +} {4 2 7 8 4} +do_test func-1.1 { + set r [catch {execsql {SELECT length(*) FROM tbl1 ORDER BY t1}} msg] + lappend r $msg +} {1 {wrong number of arguments to function length()}} +do_test func-1.2 { + set r [catch {execsql {SELECT length(t1,5) FROM tbl1 ORDER BY t1}} msg] + lappend r $msg +} {1 {wrong number of arguments to function length()}} +do_test func-1.3 { + execsql {SELECT length(t1), count(*) FROM tbl1 GROUP BY length(t1) + ORDER BY length(t1)} +} {2 1 4 2 7 1 8 1} +do_test func-1.4 { + execsql {SELECT coalesce(length(a),-1) FROM t2} +} {1 -1 3 -1 5} + +# Check out the substr() function +# +do_test func-2.0 { + execsql {SELECT substr(t1,1,2) FROM tbl1 ORDER BY t1} +} {fr is pr so th} +do_test func-2.1 { + execsql {SELECT substr(t1,2,1) FROM tbl1 ORDER BY t1} +} {r s r o h} +do_test func-2.2 { + execsql {SELECT substr(t1,3,3) FROM tbl1 ORDER BY t1} +} {ee {} ogr ftw is} +do_test func-2.3 { + execsql {SELECT substr(t1,-1,1) FROM tbl1 ORDER BY t1} +} {e s m e s} +do_test func-2.4 { + execsql {SELECT substr(t1,-1,2) FROM tbl1 ORDER BY t1} +} {e s m e s} +do_test func-2.5 { + execsql {SELECT substr(t1,-2,1) FROM tbl1 ORDER BY t1} +} {e i a r i} +do_test func-2.6 { + execsql {SELECT substr(t1,-2,2) FROM tbl1 ORDER BY t1} +} {ee is am re is} +do_test func-2.7 { + execsql {SELECT substr(t1,-4,2) FROM tbl1 ORDER BY t1} +} {fr {} gr wa th} +do_test func-2.8 { + execsql {SELECT t1 FROM tbl1 ORDER BY substr(t1,2,20)} +} {this software free program is} +do_test func-2.9 { + execsql {SELECT substr(a,1,1) FROM t2} +} {1 {} 3 {} 6} +do_test func-2.10 { + execsql {SELECT substr(a,2,2) FROM t2} +} {{} {} 45 {} 78} + +# Only do the following tests if TCL has UTF-8 capabilities +# +if {"\u1234"!="u1234"} { + +# Put some UTF-8 characters in the database +# +do_test func-3.0 { + execsql {DELETE FROM tbl1} + foreach word "contains UTF-8 characters hi\u1234ho" { + execsql "INSERT INTO tbl1 VALUES('$word')" + } + execsql {SELECT t1 FROM tbl1 ORDER BY t1} +} "UTF-8 characters contains hi\u1234ho" +do_test func-3.1 { + execsql {SELECT length(t1) FROM tbl1 ORDER BY t1} +} {5 10 8 5} +do_test func-3.2 { + execsql {SELECT substr(t1,1,2) FROM tbl1 ORDER BY t1} +} {UT ch co hi} +do_test func-3.3 { + execsql {SELECT substr(t1,1,3) FROM tbl1 ORDER BY t1} +} "UTF cha con hi\u1234" +do_test func-3.4 { + execsql {SELECT substr(t1,2,2) FROM tbl1 ORDER BY t1} +} "TF ha on i\u1234" +do_test func-3.5 { + execsql {SELECT substr(t1,2,3) FROM tbl1 ORDER BY t1} +} "TF- har ont i\u1234h" +do_test func-3.6 { + execsql {SELECT substr(t1,3,2) FROM tbl1 ORDER BY t1} +} "F- ar nt \u1234h" +do_test func-3.7 { + execsql {SELECT substr(t1,4,2) FROM tbl1 ORDER BY t1} +} "-8 ra ta ho" +do_test func-3.8 { + execsql {SELECT substr(t1,-1,1) FROM tbl1 ORDER BY t1} +} "8 s s o" +do_test func-3.9 { + execsql {SELECT substr(t1,-3,2) FROM tbl1 ORDER BY t1} +} "F- er in \u1234h" +do_test func-3.10 { + execsql {SELECT substr(t1,-4,3) FROM tbl1 ORDER BY t1} +} "TF- ter ain i\u1234h" +do_test func-3.99 { + execsql {DELETE FROM tbl1} + foreach word {this program is free software} { + execsql "INSERT INTO tbl1 VALUES('$word')" + } + execsql {SELECT t1 FROM tbl1} +} {this program is free software} + +} ;# End \u1234!=u1234 + +# Test the abs() and round() functions. +# +ifcapable !floatingpoint { + do_test func-4.1 { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(2,12345678901234,-1234567890); + INSERT INTO t1 VALUES(3,-2,-5); + } + catchsql {SELECT abs(a,b) FROM t1} + } {1 {wrong number of arguments to function abs()}} +} +ifcapable floatingpoint { + do_test func-4.1 { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(2,1.2345678901234,-12345.67890); + INSERT INTO t1 VALUES(3,-2,-5); + } + catchsql {SELECT abs(a,b) FROM t1} + } {1 {wrong number of arguments to function abs()}} +} +do_test func-4.2 { + catchsql {SELECT abs() FROM t1} +} {1 {wrong number of arguments to function abs()}} +ifcapable floatingpoint { + do_test func-4.3 { + catchsql {SELECT abs(b) FROM t1 ORDER BY a} + } {0 {2 1.2345678901234 2}} + do_test func-4.4 { + catchsql {SELECT abs(c) FROM t1 ORDER BY a} + } {0 {3 12345.6789 5}} +} +ifcapable !floatingpoint { + if {[working_64bit_int]} { + do_test func-4.3 { + catchsql {SELECT abs(b) FROM t1 ORDER BY a} + } {0 {2 12345678901234 2}} + } + do_test func-4.4 { + catchsql {SELECT abs(c) FROM t1 ORDER BY a} + } {0 {3 1234567890 5}} +} +do_test func-4.4.1 { + execsql {SELECT abs(a) FROM t2} +} {1 {} 345 {} 67890} +do_test func-4.4.2 { + execsql {SELECT abs(t1) FROM tbl1} +} {0.0 0.0 0.0 0.0 0.0} + +ifcapable floatingpoint { + do_test func-4.5 { + catchsql {SELECT round(a,b,c) FROM t1} + } {1 {wrong number of arguments to function round()}} + do_test func-4.6 { + catchsql {SELECT round(b,2) FROM t1 ORDER BY b} + } {0 {-2.0 1.23 2.0}} + do_test func-4.7 { + catchsql {SELECT round(b,0) FROM t1 ORDER BY a} + } {0 {2.0 1.0 -2.0}} + do_test func-4.8 { + catchsql {SELECT round(c) FROM t1 ORDER BY a} + } {0 {3.0 -12346.0 -5.0}} + do_test func-4.9 { + catchsql {SELECT round(c,a) FROM t1 ORDER BY a} + } {0 {3.0 -12345.68 -5.0}} + do_test func-4.10 { + catchsql {SELECT 'x' || round(c,a) || 'y' FROM t1 ORDER BY a} + } {0 {x3.0y x-12345.68y x-5.0y}} + do_test func-4.11 { + catchsql {SELECT round() FROM t1 ORDER BY a} + } {1 {wrong number of arguments to function round()}} + do_test func-4.12 { + execsql {SELECT coalesce(round(a,2),'nil') FROM t2} + } {1.0 nil 345.0 nil 67890.0} + do_test func-4.13 { + execsql {SELECT round(t1,2) FROM tbl1} + } {0.0 0.0 0.0 0.0 0.0} + do_test func-4.14 { + execsql {SELECT typeof(round(5.1,1));} + } {real} + do_test func-4.15 { + execsql {SELECT typeof(round(5.1));} + } {real} + do_test func-4.16 { + catchsql {SELECT round(b,2.0) FROM t1 ORDER BY b} + } {0 {-2.0 1.23 2.0}} + # Verify some values reported on the mailing list. + # Some of these fail on MSVC builds with 64-bit + # long doubles, but not on GCC builds with 80-bit + # long doubles. + for {set i 1} {$i<999} {incr i} { + set x1 [expr 40222.5 + $i] + set x2 [expr 40223.0 + $i] + do_test func-4.17.$i { + execsql {SELECT round($x1);} + } $x2 + } + for {set i 1} {$i<999} {incr i} { + set x1 [expr 40222.05 + $i] + set x2 [expr 40222.10 + $i] + do_test func-4.18.$i { + execsql {SELECT round($x1,1);} + } $x2 + } + do_test func-4.20 { + execsql {SELECT round(40223.4999999999);} + } {40223.0} + do_test func-4.21 { + execsql {SELECT round(40224.4999999999);} + } {40224.0} + do_test func-4.22 { + execsql {SELECT round(40225.4999999999);} + } {40225.0} + for {set i 1} {$i<10} {incr i} { + do_test func-4.23.$i { + execsql {SELECT round(40223.4999999999,$i);} + } {40223.5} + do_test func-4.24.$i { + execsql {SELECT round(40224.4999999999,$i);} + } {40224.5} + do_test func-4.25.$i { + execsql {SELECT round(40225.4999999999,$i);} + } {40225.5} + } + for {set i 10} {$i<32} {incr i} { + do_test func-4.26.$i { + execsql {SELECT round(40223.4999999999,$i);} + } {40223.4999999999} + do_test func-4.27.$i { + execsql {SELECT round(40224.4999999999,$i);} + } {40224.4999999999} + do_test func-4.28.$i { + execsql {SELECT round(40225.4999999999,$i);} + } {40225.4999999999} + } + do_test func-4.29 { + execsql {SELECT round(1234567890.5);} + } {1234567891.0} + do_test func-4.30 { + execsql {SELECT round(12345678901.5);} + } {12345678902.0} + do_test func-4.31 { + execsql {SELECT round(123456789012.5);} + } {123456789013.0} + do_test func-4.32 { + execsql {SELECT round(1234567890123.5);} + } {1234567890124.0} + do_test func-4.33 { + execsql {SELECT round(12345678901234.5);} + } {12345678901235.0} + do_test func-4.34 { + execsql {SELECT round(1234567890123.35,1);} + } {1234567890123.4} + do_test func-4.35 { + execsql {SELECT round(1234567890123.445,2);} + } {1234567890123.45} + do_test func-4.36 { + execsql {SELECT round(99999999999994.5);} + } {99999999999995.0} + do_test func-4.37 { + execsql {SELECT round(9999999999999.55,1);} + } {9999999999999.6} + do_test func-4.38 { + execsql {SELECT round(9999999999999.556,2);} + } {9999999999999.56} +} + +# Test the upper() and lower() functions +# +do_test func-5.1 { + execsql {SELECT upper(t1) FROM tbl1} +} {THIS PROGRAM IS FREE SOFTWARE} +do_test func-5.2 { + execsql {SELECT lower(upper(t1)) FROM tbl1} +} {this program is free software} +do_test func-5.3 { + execsql {SELECT upper(a), lower(a) FROM t2} +} {1 1 {} {} 345 345 {} {} 67890 67890} +ifcapable !icu { + do_test func-5.4 { + catchsql {SELECT upper(a,5) FROM t2} + } {1 {wrong number of arguments to function upper()}} +} +do_test func-5.5 { + catchsql {SELECT upper(*) FROM t2} +} {1 {wrong number of arguments to function upper()}} + +# Test the coalesce() and nullif() functions +# +do_test func-6.1 { + execsql {SELECT coalesce(a,'xyz') FROM t2} +} {1 xyz 345 xyz 67890} +do_test func-6.2 { + execsql {SELECT coalesce(upper(a),'nil') FROM t2} +} {1 nil 345 nil 67890} +do_test func-6.3 { + execsql {SELECT coalesce(nullif(1,1),'nil')} +} {nil} +do_test func-6.4 { + execsql {SELECT coalesce(nullif(1,2),'nil')} +} {1} +do_test func-6.5 { + execsql {SELECT coalesce(nullif(1,NULL),'nil')} +} {1} + + +# Test the last_insert_rowid() function +# +do_test func-7.1 { + execsql {SELECT last_insert_rowid()} +} [db last_insert_rowid] + +# Tests for aggregate functions and how they handle NULLs. +# +ifcapable floatingpoint { + do_test func-8.1 { + ifcapable explain { + execsql {EXPLAIN SELECT sum(a) FROM t2;} + } + execsql { + SELECT sum(a), count(a), round(avg(a),2), min(a), max(a), count(*) FROM t2; + } + } {68236 3 22745.33 1 67890 5} +} +ifcapable !floatingpoint { + do_test func-8.1 { + ifcapable explain { + execsql {EXPLAIN SELECT sum(a) FROM t2;} + } + execsql { + SELECT sum(a), count(a), avg(a), min(a), max(a), count(*) FROM t2; + } + } {68236 3 22745.0 1 67890 5} +} +do_test func-8.2 { + execsql { + SELECT max('z+'||a||'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP') FROM t2; + } +} {z+67890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP} + +ifcapable tempdb { + do_test func-8.3 { + execsql { + CREATE TEMP TABLE t3 AS SELECT a FROM t2 ORDER BY a DESC; + SELECT min('z+'||a||'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP') FROM t3; + } + } {z+1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP} +} else { + do_test func-8.3 { + execsql { + CREATE TABLE t3 AS SELECT a FROM t2 ORDER BY a DESC; + SELECT min('z+'||a||'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP') FROM t3; + } + } {z+1abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP} +} +do_test func-8.4 { + execsql { + SELECT max('z+'||a||'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP') FROM t3; + } +} {z+67890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP} +ifcapable compound { + do_test func-8.5 { + execsql { + SELECT sum(x) FROM (SELECT '9223372036' || '854775807' AS x + UNION ALL SELECT -9223372036854775807) + } + } {0} + do_test func-8.6 { + execsql { + SELECT typeof(sum(x)) FROM (SELECT '9223372036' || '854775807' AS x + UNION ALL SELECT -9223372036854775807) + } + } {integer} + do_test func-8.7 { + execsql { + SELECT typeof(sum(x)) FROM (SELECT '9223372036' || '854775808' AS x + UNION ALL SELECT -9223372036854775807) + } + } {real} +ifcapable floatingpoint { + do_test func-8.8 { + execsql { + SELECT sum(x)>0.0 FROM (SELECT '9223372036' || '854775808' AS x + UNION ALL SELECT -9223372036850000000) + } + } {1} +} +ifcapable !floatingpoint { + do_test func-8.8 { + execsql { + SELECT sum(x)>0 FROM (SELECT '9223372036' || '854775808' AS x + UNION ALL SELECT -9223372036850000000) + } + } {1} +} +} + +# How do you test the random() function in a meaningful, deterministic way? +# +do_test func-9.1 { + execsql { + SELECT random() is not null; + } +} {1} +do_test func-9.2 { + execsql { + SELECT typeof(random()); + } +} {integer} +do_test func-9.3 { + execsql { + SELECT randomblob(32) is not null; + } +} {1} +do_test func-9.4 { + execsql { + SELECT typeof(randomblob(32)); + } +} {blob} +do_test func-9.5 { + execsql { + SELECT length(randomblob(32)), length(randomblob(-5)), + length(randomblob(2000)) + } +} {32 1 2000} + +# The "hex()" function was added in order to be able to render blobs +# generated by randomblob(). So this seems like a good place to test +# hex(). +# +ifcapable bloblit { + do_test func-9.10 { + execsql {SELECT hex(x'00112233445566778899aAbBcCdDeEfF')} + } {00112233445566778899AABBCCDDEEFF} +} +set encoding [db one {PRAGMA encoding}] +if {$encoding=="UTF-16le"} { + do_test func-9.11-utf16le { + execsql {SELECT hex(replace('abcdefg','ef','12'))} + } {6100620063006400310032006700} + do_test func-9.12-utf16le { + execsql {SELECT hex(replace('abcdefg','','12'))} + } {6100620063006400650066006700} + do_test func-9.13-utf16le { + execsql {SELECT hex(replace('aabcdefg','a','aaa'))} + } {610061006100610061006100620063006400650066006700} +} elseif {$encoding=="UTF-8"} { + do_test func-9.11-utf8 { + execsql {SELECT hex(replace('abcdefg','ef','12'))} + } {61626364313267} + do_test func-9.12-utf8 { + execsql {SELECT hex(replace('abcdefg','','12'))} + } {61626364656667} + do_test func-9.13-utf8 { + execsql {SELECT hex(replace('aabcdefg','a','aaa'))} + } {616161616161626364656667} +} + +# Use the "sqlite_register_test_function" TCL command which is part of +# the text fixture in order to verify correct operation of some of +# the user-defined SQL function APIs that are not used by the built-in +# functions. +# +set ::DB [sqlite3_connection_pointer db] +sqlite_register_test_function $::DB testfunc +do_test func-10.1 { + catchsql { + SELECT testfunc(NULL,NULL); + } +} {1 {first argument should be one of: int int64 string double null value}} +do_test func-10.2 { + execsql { + SELECT testfunc( + 'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'int', 1234 + ); + } +} {1234} +do_test func-10.3 { + execsql { + SELECT testfunc( + 'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'string', NULL + ); + } +} {{}} + +ifcapable floatingpoint { + do_test func-10.4 { + execsql { + SELECT testfunc( + 'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'double', 1.234 + ); + } + } {1.234} + do_test func-10.5 { + execsql { + SELECT testfunc( + 'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'int', 1234, + 'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'string', NULL, + 'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'double', 1.234, + 'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'int', 1234, + 'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'string', NULL, + 'string', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'double', 1.234 + ); + } + } {1.234} +} + +# Test the built-in sqlite_version(*) SQL function. +# +do_test func-11.1 { + execsql { + SELECT sqlite_version(*); + } +} [sqlite3 -version] + +# Test that destructors passed to sqlite3 by calls to sqlite3_result_text() +# etc. are called. These tests use two special user-defined functions +# (implemented in func.c) only available in test builds. +# +# Function test_destructor() takes one argument and returns a copy of the +# text form of that argument. A destructor is associated with the return +# value. Function test_destructor_count() returns the number of outstanding +# destructor calls for values returned by test_destructor(). +# +if {[db eval {PRAGMA encoding}]=="UTF-8"} { + do_test func-12.1-utf8 { + execsql { + SELECT test_destructor('hello world'), test_destructor_count(); + } + } {{hello world} 1} +} else { + ifcapable {utf16} { + do_test func-12.1-utf16 { + execsql { + SELECT test_destructor16('hello world'), test_destructor_count(); + } + } {{hello world} 1} + } +} +do_test func-12.2 { + execsql { + SELECT test_destructor_count(); + } +} {0} +do_test func-12.3 { + execsql { + SELECT test_destructor('hello')||' world' + } +} {{hello world}} +do_test func-12.4 { + execsql { + SELECT test_destructor_count(); + } +} {0} +do_test func-12.5 { + execsql { + CREATE TABLE t4(x); + INSERT INTO t4 VALUES(test_destructor('hello')); + INSERT INTO t4 VALUES(test_destructor('world')); + SELECT min(test_destructor(x)), max(test_destructor(x)) FROM t4; + } +} {hello world} +do_test func-12.6 { + execsql { + SELECT test_destructor_count(); + } +} {0} +do_test func-12.7 { + execsql { + DROP TABLE t4; + } +} {} + + +# Test that the auxdata API for scalar functions works. This test uses +# a special user-defined function only available in test builds, +# test_auxdata(). Function test_auxdata() takes any number of arguments. +do_test func-13.1 { + execsql { + SELECT test_auxdata('hello world'); + } +} {0} + +do_test func-13.2 { + execsql { + CREATE TABLE t4(a, b); + INSERT INTO t4 VALUES('abc', 'def'); + INSERT INTO t4 VALUES('ghi', 'jkl'); + } +} {} +do_test func-13.3 { + execsql { + SELECT test_auxdata('hello world') FROM t4; + } +} {0 1} +do_test func-13.4 { + execsql { + SELECT test_auxdata('hello world', 123) FROM t4; + } +} {{0 0} {1 1}} +do_test func-13.5 { + execsql { + SELECT test_auxdata('hello world', a) FROM t4; + } +} {{0 0} {1 0}} +do_test func-13.6 { + execsql { + SELECT test_auxdata('hello'||'world', a) FROM t4; + } +} {{0 0} {1 0}} + +# Test that auxilary data is preserved between calls for SQL variables. +do_test func-13.7 { + set DB [sqlite3_connection_pointer db] + set sql "SELECT test_auxdata( ? , a ) FROM t4;" + set STMT [sqlite3_prepare $DB $sql -1 TAIL] + sqlite3_bind_text $STMT 1 hello\000 -1 + set res [list] + while { "SQLITE_ROW"==[sqlite3_step $STMT] } { + lappend res [sqlite3_column_text $STMT 0] + } + lappend res [sqlite3_finalize $STMT] +} {{0 0} {1 0} SQLITE_OK} + +# Test that auxiliary data is discarded when a statement is reset. +do_execsql_test 13.8.1 { + SELECT test_auxdata('constant') FROM t4; +} {0 1} +do_execsql_test 13.8.2 { + SELECT test_auxdata('constant') FROM t4; +} {0 1} +db cache flush +do_execsql_test 13.8.3 { + SELECT test_auxdata('constant') FROM t4; +} {0 1} +set V "one" +do_execsql_test 13.8.4 { + SELECT test_auxdata($V), $V FROM t4; +} {0 one 1 one} +set V "two" +do_execsql_test 13.8.5 { + SELECT test_auxdata($V), $V FROM t4; +} {0 two 1 two} +db cache flush +set V "three" +do_execsql_test 13.8.6 { + SELECT test_auxdata($V), $V FROM t4; +} {0 three 1 three} + + +# Make sure that a function with a very long name is rejected +do_test func-14.1 { + catch { + db function [string repeat X 254] {return "hello"} + } +} {0} +do_test func-14.2 { + catch { + db function [string repeat X 256] {return "hello"} + } +} {1} + +do_test func-15.1 { + catchsql {select test_error(NULL)} +} {1 {}} +do_test func-15.2 { + catchsql {select test_error('this is the error message')} +} {1 {this is the error message}} +do_test func-15.3 { + catchsql {select test_error('this is the error message',12)} +} {1 {this is the error message}} +do_test func-15.4 { + db errorcode +} {12} + +# Test the quote function for BLOB and NULL values. +do_test func-16.1 { + execsql { + CREATE TABLE tbl2(a, b); + } + set STMT [sqlite3_prepare $::DB "INSERT INTO tbl2 VALUES(?, ?)" -1 TAIL] + sqlite3_bind_blob $::STMT 1 abc 3 + sqlite3_step $::STMT + sqlite3_finalize $::STMT + execsql { + SELECT quote(a), quote(b) FROM tbl2; + } +} {X'616263' NULL} + +# Correctly handle function error messages that include %. Ticket #1354 +# +do_test func-17.1 { + proc testfunc1 args {error "Error %d with %s percents %p"} + db function testfunc1 ::testfunc1 + catchsql { + SELECT testfunc1(1,2,3); + } +} {1 {Error %d with %s percents %p}} + +# The SUM function should return integer results when all inputs are integer. +# +do_test func-18.1 { + execsql { + CREATE TABLE t5(x); + INSERT INTO t5 VALUES(1); + INSERT INTO t5 VALUES(-99); + INSERT INTO t5 VALUES(10000); + SELECT sum(x) FROM t5; + } +} {9902} +ifcapable floatingpoint { + do_test func-18.2 { + execsql { + INSERT INTO t5 VALUES(0.0); + SELECT sum(x) FROM t5; + } + } {9902.0} +} + +# The sum of nothing is NULL. But the sum of all NULLs is NULL. +# +# The TOTAL of nothing is 0.0. +# +do_test func-18.3 { + execsql { + DELETE FROM t5; + SELECT sum(x), total(x) FROM t5; + } +} {{} 0.0} +do_test func-18.4 { + execsql { + INSERT INTO t5 VALUES(NULL); + SELECT sum(x), total(x) FROM t5 + } +} {{} 0.0} +do_test func-18.5 { + execsql { + INSERT INTO t5 VALUES(NULL); + SELECT sum(x), total(x) FROM t5 + } +} {{} 0.0} +do_test func-18.6 { + execsql { + INSERT INTO t5 VALUES(123); + SELECT sum(x), total(x) FROM t5 + } +} {123 123.0} + +# Ticket #1664, #1669, #1670, #1674: An integer overflow on SUM causes +# an error. The non-standard TOTAL() function continues to give a helpful +# result. +# +do_test func-18.10 { + execsql { + CREATE TABLE t6(x INTEGER); + INSERT INTO t6 VALUES(1); + INSERT INTO t6 VALUES(1<<62); + SELECT sum(x) - ((1<<62)+1) from t6; + } +} 0 +do_test func-18.11 { + execsql { + SELECT typeof(sum(x)) FROM t6 + } +} integer +ifcapable floatingpoint { + do_test func-18.12 { + catchsql { + INSERT INTO t6 VALUES(1<<62); + SELECT sum(x) - ((1<<62)*2.0+1) from t6; + } + } {1 {integer overflow}} + do_test func-18.13 { + execsql { + SELECT total(x) - ((1<<62)*2.0+1) FROM t6 + } + } 0.0 +} +ifcapable !floatingpoint { + do_test func-18.12 { + catchsql { + INSERT INTO t6 VALUES(1<<62); + SELECT sum(x) - ((1<<62)*2+1) from t6; + } + } {1 {integer overflow}} + do_test func-18.13 { + execsql { + SELECT total(x) - ((1<<62)*2+1) FROM t6 + } + } 0.0 +} +if {[working_64bit_int]} { + do_test func-18.14 { + execsql { + SELECT sum(-9223372036854775805); + } + } -9223372036854775805 +} +ifcapable compound&&subquery { + +do_test func-18.15 { + catchsql { + SELECT sum(x) FROM + (SELECT 9223372036854775807 AS x UNION ALL + SELECT 10 AS x); + } +} {1 {integer overflow}} +if {[working_64bit_int]} { + do_test func-18.16 { + catchsql { + SELECT sum(x) FROM + (SELECT 9223372036854775807 AS x UNION ALL + SELECT -10 AS x); + } + } {0 9223372036854775797} + do_test func-18.17 { + catchsql { + SELECT sum(x) FROM + (SELECT -9223372036854775807 AS x UNION ALL + SELECT 10 AS x); + } + } {0 -9223372036854775797} +} +do_test func-18.18 { + catchsql { + SELECT sum(x) FROM + (SELECT -9223372036854775807 AS x UNION ALL + SELECT -10 AS x); + } +} {1 {integer overflow}} +do_test func-18.19 { + catchsql { + SELECT sum(x) FROM (SELECT 9 AS x UNION ALL SELECT -10 AS x); + } +} {0 -1} +do_test func-18.20 { + catchsql { + SELECT sum(x) FROM (SELECT -9 AS x UNION ALL SELECT 10 AS x); + } +} {0 1} +do_test func-18.21 { + catchsql { + SELECT sum(x) FROM (SELECT -10 AS x UNION ALL SELECT 9 AS x); + } +} {0 -1} +do_test func-18.22 { + catchsql { + SELECT sum(x) FROM (SELECT 10 AS x UNION ALL SELECT -9 AS x); + } +} {0 1} + +} ;# ifcapable compound&&subquery + +# Integer overflow on abs() +# +if {[working_64bit_int]} { + do_test func-18.31 { + catchsql { + SELECT abs(-9223372036854775807); + } + } {0 9223372036854775807} +} +do_test func-18.32 { + catchsql { + SELECT abs(-9223372036854775807-1); + } +} {1 {integer overflow}} + +# The MATCH function exists but is only a stub and always throws an error. +# +do_test func-19.1 { + execsql { + SELECT match(a,b) FROM t1 WHERE 0; + } +} {} +do_test func-19.2 { + catchsql { + SELECT 'abc' MATCH 'xyz'; + } +} {1 {unable to use function MATCH in the requested context}} +do_test func-19.3 { + catchsql { + SELECT 'abc' NOT MATCH 'xyz'; + } +} {1 {unable to use function MATCH in the requested context}} +do_test func-19.4 { + catchsql { + SELECT match(1,2,3); + } +} {1 {wrong number of arguments to function match()}} + +# Soundex tests. +# +if {![catch {db eval {SELECT soundex('hello')}}]} { + set i 0 + foreach {name sdx} { + euler E460 + EULER E460 + Euler E460 + ellery E460 + gauss G200 + ghosh G200 + hilbert H416 + Heilbronn H416 + knuth K530 + kant K530 + Lloyd L300 + LADD L300 + Lukasiewicz L222 + Lissajous L222 + A A000 + 12345 ?000 + } { + incr i + do_test func-20.$i { + execsql {SELECT soundex($name)} + } $sdx + } +} + +# Tests of the REPLACE function. +# +do_test func-21.1 { + catchsql { + SELECT replace(1,2); + } +} {1 {wrong number of arguments to function replace()}} +do_test func-21.2 { + catchsql { + SELECT replace(1,2,3,4); + } +} {1 {wrong number of arguments to function replace()}} +do_test func-21.3 { + execsql { + SELECT typeof(replace("This is the main test string", NULL, "ALT")); + } +} {null} +do_test func-21.4 { + execsql { + SELECT typeof(replace(NULL, "main", "ALT")); + } +} {null} +do_test func-21.5 { + execsql { + SELECT typeof(replace("This is the main test string", "main", NULL)); + } +} {null} +do_test func-21.6 { + execsql { + SELECT replace("This is the main test string", "main", "ALT"); + } +} {{This is the ALT test string}} +do_test func-21.7 { + execsql { + SELECT replace("This is the main test string", "main", "larger-main"); + } +} {{This is the larger-main test string}} +do_test func-21.8 { + execsql { + SELECT replace("aaaaaaa", "a", "0123456789"); + } +} {0123456789012345678901234567890123456789012345678901234567890123456789} + +ifcapable tclvar { + do_test func-21.9 { + # Attempt to exploit a buffer-overflow that at one time existed + # in the REPLACE function. + set ::str "[string repeat A 29998]CC[string repeat A 35537]" + set ::rep [string repeat B 65536] + execsql { + SELECT LENGTH(REPLACE($::str, 'C', $::rep)); + } + } [expr 29998 + 2*65536 + 35537] +} + +# Tests for the TRIM, LTRIM and RTRIM functions. +# +do_test func-22.1 { + catchsql {SELECT trim(1,2,3)} +} {1 {wrong number of arguments to function trim()}} +do_test func-22.2 { + catchsql {SELECT ltrim(1,2,3)} +} {1 {wrong number of arguments to function ltrim()}} +do_test func-22.3 { + catchsql {SELECT rtrim(1,2,3)} +} {1 {wrong number of arguments to function rtrim()}} +do_test func-22.4 { + execsql {SELECT trim(' hi ');} +} {hi} +do_test func-22.5 { + execsql {SELECT ltrim(' hi ');} +} {{hi }} +do_test func-22.6 { + execsql {SELECT rtrim(' hi ');} +} {{ hi}} +do_test func-22.7 { + execsql {SELECT trim(' hi ','xyz');} +} {{ hi }} +do_test func-22.8 { + execsql {SELECT ltrim(' hi ','xyz');} +} {{ hi }} +do_test func-22.9 { + execsql {SELECT rtrim(' hi ','xyz');} +} {{ hi }} +do_test func-22.10 { + execsql {SELECT trim('xyxzy hi zzzy','xyz');} +} {{ hi }} +do_test func-22.11 { + execsql {SELECT ltrim('xyxzy hi zzzy','xyz');} +} {{ hi zzzy}} +do_test func-22.12 { + execsql {SELECT rtrim('xyxzy hi zzzy','xyz');} +} {{xyxzy hi }} +do_test func-22.13 { + execsql {SELECT trim(' hi ','');} +} {{ hi }} +if {[db one {PRAGMA encoding}]=="UTF-8"} { + do_test func-22.14 { + execsql {SELECT hex(trim(x'c280e1bfbff48fbfbf6869',x'6162e1bfbfc280'))} + } {F48FBFBF6869} + do_test func-22.15 { + execsql {SELECT hex(trim(x'6869c280e1bfbff48fbfbf61', + x'6162e1bfbfc280f48fbfbf'))} + } {6869} + do_test func-22.16 { + execsql {SELECT hex(trim(x'ceb1ceb2ceb3',x'ceb1'));} + } {CEB2CEB3} +} +do_test func-22.20 { + execsql {SELECT typeof(trim(NULL));} +} {null} +do_test func-22.21 { + execsql {SELECT typeof(trim(NULL,'xyz'));} +} {null} +do_test func-22.22 { + execsql {SELECT typeof(trim('hello',NULL));} +} {null} + +# This is to test the deprecated sqlite3_aggregate_count() API. +# +ifcapable deprecated { + do_test func-23.1 { + sqlite3_create_aggregate db + execsql { + SELECT legacy_count() FROM t6; + } + } {3} +} + +# The group_concat() function. +# +do_test func-24.1 { + execsql { + SELECT group_concat(t1) FROM tbl1 + } +} {this,program,is,free,software} +do_test func-24.2 { + execsql { + SELECT group_concat(t1,' ') FROM tbl1 + } +} {{this program is free software}} +do_test func-24.3 { + execsql { + SELECT group_concat(t1,' ' || rowid || ' ') FROM tbl1 + } +} {{this 2 program 3 is 4 free 5 software}} +do_test func-24.4 { + execsql { + SELECT group_concat(NULL,t1) FROM tbl1 + } +} {{}} +do_test func-24.5 { + execsql { + SELECT group_concat(t1,NULL) FROM tbl1 + } +} {thisprogramisfreesoftware} +do_test func-24.6 { + execsql { + SELECT 'BEGIN-'||group_concat(t1) FROM tbl1 + } +} {BEGIN-this,program,is,free,software} + +# Ticket #3179: Make sure aggregate functions can take many arguments. +# None of the built-in aggregates do this, so use the md5sum() from the +# test extensions. +# +unset -nocomplain midargs +set midargs {} +unset -nocomplain midres +set midres {} +unset -nocomplain result +for {set i 1} {$i<[sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG -1]} {incr i} { + append midargs ,'/$i' + append midres /$i + set result [md5 \ + "this${midres}program${midres}is${midres}free${midres}software${midres}"] + set sql "SELECT md5sum(t1$midargs) FROM tbl1" + do_test func-24.7.$i { + db eval $::sql + } $result +} + +# Ticket #3806. If the initial string in a group_concat is an empty +# string, the separator that follows should still be present. +# +do_test func-24.8 { + execsql { + SELECT group_concat(CASE t1 WHEN 'this' THEN '' ELSE t1 END) FROM tbl1 + } +} {,program,is,free,software} +do_test func-24.9 { + execsql { + SELECT group_concat(CASE WHEN t1!='software' THEN '' ELSE t1 END) FROM tbl1 + } +} {,,,,software} + +# Ticket #3923. Initial empty strings have a separator. But initial +# NULLs do not. +# +do_test func-24.10 { + execsql { + SELECT group_concat(CASE t1 WHEN 'this' THEN null ELSE t1 END) FROM tbl1 + } +} {program,is,free,software} +do_test func-24.11 { + execsql { + SELECT group_concat(CASE WHEN t1!='software' THEN null ELSE t1 END) FROM tbl1 + } +} {software} +do_test func-24.12 { + execsql { + SELECT group_concat(CASE t1 WHEN 'this' THEN '' + WHEN 'program' THEN null ELSE t1 END) FROM tbl1 + } +} {,is,free,software} + + +# Use the test_isolation function to make sure that type conversions +# on function arguments do not effect subsequent arguments. +# +do_test func-25.1 { + execsql {SELECT test_isolation(t1,t1) FROM tbl1} +} {this program is free software} + +# Try to misuse the sqlite3_create_function() interface. Verify that +# errors are returned. +# +do_test func-26.1 { + abuse_create_function db +} {} + +# The previous test (func-26.1) registered a function with a very long +# function name that takes many arguments and always returns NULL. Verify +# that this function works correctly. +# +do_test func-26.2 { + set a {} + for {set i 1} {$i<=$::SQLITE_MAX_FUNCTION_ARG} {incr i} { + lappend a $i + } + db eval " + SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789([join $a ,]); + " +} {{}} +do_test func-26.3 { + set a {} + for {set i 1} {$i<=$::SQLITE_MAX_FUNCTION_ARG+1} {incr i} { + lappend a $i + } + catchsql " + SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789([join $a ,]); + " +} {1 {too many arguments on function nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789}} +do_test func-26.4 { + set a {} + for {set i 1} {$i<=$::SQLITE_MAX_FUNCTION_ARG-1} {incr i} { + lappend a $i + } + catchsql " + SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789([join $a ,]); + " +} {1 {wrong number of arguments to function nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789()}} +do_test func-26.5 { + catchsql " + SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_12345678a(0); + " +} {1 {no such function: nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_12345678a}} +do_test func-26.6 { + catchsql " + SELECT nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789a(0); + " +} {1 {no such function: nullx_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789a}} + +do_test func-27.1 { + catchsql {SELECT coalesce()} +} {1 {wrong number of arguments to function coalesce()}} +do_test func-27.2 { + catchsql {SELECT coalesce(1)} +} {1 {wrong number of arguments to function coalesce()}} +do_test func-27.3 { + catchsql {SELECT coalesce(1,2)} +} {0 1} + +# Ticket 2d401a94287b5 +# Unknown function in a DEFAULT expression causes a segfault. +# +do_test func-28.1 { + db eval { + CREATE TABLE t28(x, y DEFAULT(nosuchfunc(1))); + } + catchsql { + INSERT INTO t28(x) VALUES(1); + } +} {1 {unknown function: nosuchfunc()}} + +# Verify that the length() and typeof() functions do not actually load +# the content of their argument. +# +do_test func-29.1 { + db eval { + CREATE TABLE t29(id INTEGER PRIMARY KEY, x, y); + INSERT INTO t29 VALUES(1, 2, 3), (2, NULL, 4), (3, 4.5, 5); + INSERT INTO t29 VALUES(4, randomblob(1000000), 6); + INSERT INTO t29 VALUES(5, "hello", 7); + } + db close + sqlite3 db test.db + sqlite3_db_status db CACHE_MISS 1 + db eval {SELECT typeof(x), length(x), typeof(y) FROM t29 ORDER BY id} +} {integer 1 integer null {} integer real 3 integer blob 1000000 integer text 5 integer} +do_test func-29.2 { + set x [lindex [sqlite3_db_status db CACHE_MISS 1] 1] + if {$x<5} {set x 1} + set x +} {1} +do_test func-29.3 { + db close + sqlite3 db test.db + sqlite3_db_status db CACHE_MISS 1 + db eval {SELECT typeof(+x) FROM t29 ORDER BY id} +} {integer null real blob text} +if {[permutation] != "mmap"} { + do_test func-29.4 { + set x [lindex [sqlite3_db_status db CACHE_MISS 1] 1] + if {$x>100} {set x many} + set x + } {many} +} +do_test func-29.5 { + db close + sqlite3 db test.db + sqlite3_db_status db CACHE_MISS 1 + db eval {SELECT sum(length(x)) FROM t29} +} {1000009} +do_test func-29.6 { + set x [lindex [sqlite3_db_status db CACHE_MISS 1] 1] + if {$x<5} {set x 1} + set x +} {1} + +# EVIDENCE-OF: R-29701-50711 The unicode(X) function returns the numeric +# unicode code point corresponding to the first character of the string +# X. +# +# EVIDENCE-OF: R-55469-62130 The char(X1,X2,...,XN) function returns a +# string composed of characters having the unicode code point values of +# integers X1 through XN, respectively. +# +do_execsql_test func-30.1 {SELECT unicode('$');} 36 +do_execsql_test func-30.2 [subst {SELECT unicode('\u00A2');}] 162 +do_execsql_test func-30.3 [subst {SELECT unicode('\u20AC');}] 8364 +do_execsql_test func-30.4 {SELECT char(36,162,8364);} [subst {$\u00A2\u20AC}] + +for {set i 1} {$i<0xd800} {incr i 13} { + do_execsql_test func-30.5.$i {SELECT unicode(char($i))} $i +} +for {set i 57344} {$i<=0xfffd} {incr i 17} { + if {$i==0xfeff} continue + do_execsql_test func-30.5.$i {SELECT unicode(char($i))} $i +} +for {set i 65536} {$i<=0x10ffff} {incr i 139} { + do_execsql_test func-30.5.$i {SELECT unicode(char($i))} $i +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/func2.test b/components/external/SQLite-3.8.1/test/func2.test new file mode 100644 index 0000000000000000000000000000000000000000..08ad857509bc1c00354ceb44de2ae2e016317fec --- /dev/null +++ b/components/external/SQLite-3.8.1/test/func2.test @@ -0,0 +1,511 @@ +# 2009 November 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing built-in functions. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Test plan: +# +# func2-1.*: substr implementation (ascii) +# func2-2.*: substr implementation (utf8) +# func2-3.*: substr implementation (blob) +# + +proc bin_to_hex {blob} { + set bytes {} + binary scan $blob \c* bytes + set bytes2 [list] + foreach b $bytes {lappend bytes2 [format %02X [expr $b & 0xFF]]} + join $bytes2 {} +} + +#---------------------------------------------------------------------------- +# Test cases func2-1.*: substr implementation (ascii) +# + +do_test func2-1.1 { + execsql {SELECT 'Supercalifragilisticexpialidocious'} +} {Supercalifragilisticexpialidocious} + +# substr(x,y), substr(x,y,z) +do_test func2-1.2.1 { + catchsql {SELECT SUBSTR()} +} {1 {wrong number of arguments to function SUBSTR()}} +do_test func2-1.2.2 { + catchsql {SELECT SUBSTR('Supercalifragilisticexpialidocious')} +} {1 {wrong number of arguments to function SUBSTR()}} +do_test func2-1.2.3 { + catchsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 1,1,1)} +} {1 {wrong number of arguments to function SUBSTR()}} + +# p1 is 1-indexed +do_test func2-1.3 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 0)} +} {Supercalifragilisticexpialidocious} +do_test func2-1.4 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 1)} +} {Supercalifragilisticexpialidocious} +do_test func2-1.5 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 2)} +} {upercalifragilisticexpialidocious} +do_test func2-1.6 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 30)} +} {cious} +do_test func2-1.7 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 34)} +} {s} +do_test func2-1.8 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 35)} +} {{}} +do_test func2-1.9 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 36)} +} {{}} + +# if p1<0, start from right +do_test func2-1.10 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -0)} +} {Supercalifragilisticexpialidocious} +do_test func2-1.11 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -1)} +} {s} +do_test func2-1.12 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -2)} +} {us} +do_test func2-1.13 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -30)} +} {rcalifragilisticexpialidocious} +do_test func2-1.14 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -34)} +} {Supercalifragilisticexpialidocious} +do_test func2-1.15 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -35)} +} {Supercalifragilisticexpialidocious} +do_test func2-1.16 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -36)} +} {Supercalifragilisticexpialidocious} + +# p1 is 1-indexed, p2 length to return +do_test func2-1.17.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 0, 1)} +} {{}} +do_test func2-1.17.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 0, 2)} +} {S} +do_test func2-1.18 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 1, 1)} +} {S} +do_test func2-1.19.0 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 2, 0)} +} {{}} +do_test func2-1.19.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 2, 1)} +} {u} +do_test func2-1.19.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 2, 2)} +} {up} +do_test func2-1.20 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 30, 1)} +} {c} +do_test func2-1.21 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 34, 1)} +} {s} +do_test func2-1.22 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 35, 1)} +} {{}} +do_test func2-1.23 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 36, 1)} +} {{}} + +# if p1<0, start from right, p2 length to return +do_test func2-1.24 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -0, 1)} +} {{}} +do_test func2-1.25.0 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -1, 0)} +} {{}} +do_test func2-1.25.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -1, 1)} +} {s} +do_test func2-1.25.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -1, 2)} +} {s} +do_test func2-1.26 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -2, 1)} +} {u} +do_test func2-1.27 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -30, 1)} +} {r} +do_test func2-1.28.0 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -34, 0)} +} {{}} +do_test func2-1.28.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -34, 1)} +} {S} +do_test func2-1.28.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -34, 2)} +} {Su} +do_test func2-1.29.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -35, 1)} +} {{}} +do_test func2-1.29.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -35, 2)} +} {S} +do_test func2-1.30.0 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -36, 0)} +} {{}} +do_test func2-1.30.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -36, 1)} +} {{}} +do_test func2-1.30.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -36, 2)} +} {{}} +do_test func2-1.30.3 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', -36, 3)} +} {S} + +# p1 is 1-indexed, p2 length to return, p2<0 return p2 chars before p1 +do_test func2-1.31.0 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 0, 0)} +} {{}} +do_test func2-1.31.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 0, -1)} +} {{}} +do_test func2-1.31.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 0, -2)} +} {{}} +do_test func2-1.32.0 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 1, 0)} +} {{}} +do_test func2-1.32.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 1, -1)} +} {{}} +do_test func2-1.33.0 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 2, 0)} +} {{}} +do_test func2-1.33.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 2, -1)} +} {S} +do_test func2-1.33.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 2, -2)} +} {S} +do_test func2-1.34.0 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 3, 0)} +} {{}} +do_test func2-1.34.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 3, -1)} +} {u} +do_test func2-1.34.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 3, -2)} +} {Su} +do_test func2-1.35.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 30, -1)} +} {o} +do_test func2-1.35.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 30, -2)} +} {do} +do_test func2-1.36 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 34, -1)} +} {u} +do_test func2-1.37 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 35, -1)} +} {s} +do_test func2-1.38.0 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 36, 0)} +} {{}} +do_test func2-1.38.1 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 36, -1)} +} {{}} +do_test func2-1.38.2 { + execsql {SELECT SUBSTR('Supercalifragilisticexpialidocious', 36, -2)} +} {s} + + +#---------------------------------------------------------------------------- +# Test cases func2-2.*: substr implementation (utf8) +# + +# Only do the following tests if TCL has UTF-8 capabilities +# +if {"\u1234"!="u1234"} { + +do_test func2-2.1.1 { + execsql "SELECT 'hi\u1234ho'" +} "hi\u1234ho" + +# substr(x,y), substr(x,y,z) +do_test func2-2.1.2 { + catchsql "SELECT SUBSTR()" +} {1 {wrong number of arguments to function SUBSTR()}} +do_test func2-2.1.3 { + catchsql "SELECT SUBSTR('hi\u1234ho')" +} {1 {wrong number of arguments to function SUBSTR()}} +do_test func2-2.1.4 { + catchsql "SELECT SUBSTR('hi\u1234ho', 1,1,1)" +} {1 {wrong number of arguments to function SUBSTR()}} + +do_test func2-2.2.0 { + execsql "SELECT SUBSTR('hi\u1234ho', 0, 0)" +} {{}} +do_test func2-2.2.1 { + execsql "SELECT SUBSTR('hi\u1234ho', 0, 1)" +} {{}} +do_test func2-2.2.2 { + execsql "SELECT SUBSTR('hi\u1234ho', 0, 2)" +} "h" +do_test func2-2.2.3 { + execsql "SELECT SUBSTR('hi\u1234ho', 0, 3)" +} "hi" +do_test func2-2.2.4 { + execsql "SELECT SUBSTR('hi\u1234ho', 0, 4)" +} "hi\u1234" +do_test func2-2.2.5 { + execsql "SELECT SUBSTR('hi\u1234ho', 0, 5)" +} "hi\u1234h" +do_test func2-2.2.6 { + execsql "SELECT SUBSTR('hi\u1234ho', 0, 6)" +} "hi\u1234ho" + +do_test func2-2.3.0 { + execsql "SELECT SUBSTR('hi\u1234ho', 1, 0)" +} {{}} +do_test func2-2.3.1 { + execsql "SELECT SUBSTR('hi\u1234ho', 1, 1)" +} "h" +do_test func2-2.3.2 { + execsql "SELECT SUBSTR('hi\u1234ho', 1, 2)" +} "hi" +do_test func2-2.3.3 { + execsql "SELECT SUBSTR('hi\u1234ho', 1, 3)" +} "hi\u1234" +do_test func2-2.3.4 { + execsql "SELECT SUBSTR('hi\u1234ho', 1, 4)" +} "hi\u1234h" +do_test func2-2.3.5 { + execsql "SELECT SUBSTR('hi\u1234ho', 1, 5)" +} "hi\u1234ho" +do_test func2-2.3.6 { + execsql "SELECT SUBSTR('hi\u1234ho', 1, 6)" +} "hi\u1234ho" + +do_test func2-2.4.0 { + execsql "SELECT SUBSTR('hi\u1234ho', 3, 0)" +} {{}} +do_test func2-2.4.1 { + execsql "SELECT SUBSTR('hi\u1234ho', 3, 1)" +} "\u1234" +do_test func2-2.4.2 { + execsql "SELECT SUBSTR('hi\u1234ho', 3, 2)" +} "\u1234h" + +do_test func2-2.5.0 { + execsql "SELECT SUBSTR('\u1234', 0, 0)" +} {{}} +do_test func2-2.5.1 { + execsql "SELECT SUBSTR('\u1234', 0, 1)" +} {{}} +do_test func2-2.5.2 { + execsql "SELECT SUBSTR('\u1234', 0, 2)" +} "\u1234" +do_test func2-2.5.3 { + execsql "SELECT SUBSTR('\u1234', 0, 3)" +} "\u1234" + +do_test func2-2.6.0 { + execsql "SELECT SUBSTR('\u1234', 1, 0)" +} {{}} +do_test func2-2.6.1 { + execsql "SELECT SUBSTR('\u1234', 1, 1)" +} "\u1234" +do_test func2-2.6.2 { + execsql "SELECT SUBSTR('\u1234', 1, 2)" +} "\u1234" +do_test func2-2.6.3 { + execsql "SELECT SUBSTR('\u1234', 1, 3)" +} "\u1234" + +do_test func2-2.7.0 { + execsql "SELECT SUBSTR('\u1234', 2, 0)" +} {{}} +do_test func2-2.7.1 { + execsql "SELECT SUBSTR('\u1234', 2, 1)" +} {{}} +do_test func2-2.7.2 { + execsql "SELECT SUBSTR('\u1234', 2, 2)" +} {{}} + +do_test func2-2.8.0 { + execsql "SELECT SUBSTR('\u1234', -1, 0)" +} {{}} +do_test func2-2.8.1 { + execsql "SELECT SUBSTR('\u1234', -1, 1)" +} "\u1234" +do_test func2-2.8.2 { + execsql "SELECT SUBSTR('\u1234', -1, 2)" +} "\u1234" +do_test func2-2.8.3 { + execsql "SELECT SUBSTR('\u1234', -1, 3)" +} "\u1234" + +} ;# End \u1234!=u1234 + +#---------------------------------------------------------------------------- +# Test cases func2-3.*: substr implementation (blob) +# + +ifcapable {!bloblit} { + finish_test + return +} + +do_test func2-3.1.1 { + set blob [execsql "SELECT x'1234'"] + bin_to_hex [lindex $blob 0] +} "1234" + +# substr(x,y), substr(x,y,z) +do_test func2-3.1.2 { + catchsql {SELECT SUBSTR()} +} {1 {wrong number of arguments to function SUBSTR()}} +do_test func2-3.1.3 { + catchsql {SELECT SUBSTR(x'1234')} +} {1 {wrong number of arguments to function SUBSTR()}} +do_test func2-3.1.4 { + catchsql {SELECT SUBSTR(x'1234', 1,1,1)} +} {1 {wrong number of arguments to function SUBSTR()}} + +do_test func2-3.2.0 { + set blob [execsql "SELECT SUBSTR(x'1234', 0, 0)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.2.1 { + set blob [execsql "SELECT SUBSTR(x'1234', 0, 1)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.2.2 { + set blob [execsql "SELECT SUBSTR(x'1234', 0, 2)"] + bin_to_hex [lindex $blob 0] +} "12" +do_test func2-3.2.3 { + set blob [execsql "SELECT SUBSTR(x'1234', 0, 3)"] + bin_to_hex [lindex $blob 0] +} "1234" + +do_test func2-3.3.0 { + set blob [execsql "SELECT SUBSTR(x'1234', 1, 0)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.3.1 { + set blob [execsql "SELECT SUBSTR(x'1234', 1, 1)"] + bin_to_hex [lindex $blob 0] +} "12" +do_test func2-3.3.2 { + set blob [execsql "SELECT SUBSTR(x'1234', 1, 2)"] + bin_to_hex [lindex $blob 0] +} "1234" +do_test func2-3.3.3 { + set blob [execsql "SELECT SUBSTR(x'1234', 1, 3)"] + bin_to_hex [lindex $blob 0] +} "1234" + +do_test func2-3.4.0 { + set blob [execsql "SELECT SUBSTR(x'1234', -1, 0)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.4.1 { + set blob [execsql "SELECT SUBSTR(x'1234', -1, 1)"] + bin_to_hex [lindex $blob 0] +} "34" +do_test func2-3.4.2 { + set blob [execsql "SELECT SUBSTR(x'1234', -1, 2)"] + bin_to_hex [lindex $blob 0] +} "34" +do_test func2-3.4.3 { + set blob [execsql "SELECT SUBSTR(x'1234', -1, 3)"] + bin_to_hex [lindex $blob 0] +} "34" + +do_test func2-3.5.0 { + set blob [execsql "SELECT SUBSTR(x'1234', -2, 0)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.5.1 { + set blob [execsql "SELECT SUBSTR(x'1234', -2, 1)"] + bin_to_hex [lindex $blob 0] +} "12" +do_test func2-3.5.2 { + set blob [execsql "SELECT SUBSTR(x'1234', -2, 2)"] + bin_to_hex [lindex $blob 0] +} "1234" +do_test func2-3.5.3 { + set blob [execsql "SELECT SUBSTR(x'1234', -2, 3)"] + bin_to_hex [lindex $blob 0] +} "1234" + +do_test func2-3.6.0 { + set blob [execsql "SELECT SUBSTR(x'1234', -1, 0)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.6.1 { + set blob [execsql "SELECT SUBSTR(x'1234', -1, -1)"] + bin_to_hex [lindex $blob 0] +} "12" +do_test func2-3.6.2 { + set blob [execsql "SELECT SUBSTR(x'1234', -1, -2)"] + bin_to_hex [lindex $blob 0] +} "12" +do_test func2-3.6.3 { + set blob [execsql "SELECT SUBSTR(x'1234', -1, -3)"] + bin_to_hex [lindex $blob 0] +} "12" + +do_test func2-3.7.0 { + set blob [execsql "SELECT SUBSTR(x'1234', -2, 0)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.7.1 { + set blob [execsql "SELECT SUBSTR(x'1234', -2, -1)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.7.2 { + set blob [execsql "SELECT SUBSTR(x'1234', -2, -2)"] + bin_to_hex [lindex $blob 0] +} {} + +do_test func2-3.8.0 { + set blob [execsql "SELECT SUBSTR(x'1234', 1, 0)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.8.1 { + set blob [execsql "SELECT SUBSTR(x'1234', 1, -1)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.8.2 { + set blob [execsql "SELECT SUBSTR(x'1234', 1, -2)"] + bin_to_hex [lindex $blob 0] +} {} + +do_test func2-3.9.0 { + set blob [execsql "SELECT SUBSTR(x'1234', 2, 0)"] + bin_to_hex [lindex $blob 0] +} {} +do_test func2-3.9.1 { + set blob [execsql "SELECT SUBSTR(x'1234', 2, -1)"] + bin_to_hex [lindex $blob 0] +} "12" +do_test func2-3.9.2 { + set blob [execsql "SELECT SUBSTR(x'1234', 2, -2)"] + bin_to_hex [lindex $blob 0] +} "12" + +finish_test diff --git a/components/external/SQLite-3.8.1/test/func3.test b/components/external/SQLite-3.8.1/test/func3.test new file mode 100644 index 0000000000000000000000000000000000000000..2a2b7be4f463b76efe7ed36eef293571177096e7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/func3.test @@ -0,0 +1,156 @@ +# 2010 August 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that destructor functions associated +# with functions created using sqlite3_create_function_v2() is +# correctly invoked. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +ifcapable utf16 { + do_test func3-1.1 { + set destroyed 0 + proc destroy {} { set ::destroyed 1 } + sqlite3_create_function_v2 db f2 -1 any -func f2 -destroy destroy + set destroyed + } 0 + do_test func3-1.2 { + sqlite3_create_function_v2 db f2 -1 utf8 -func f2 + set destroyed + } 0 + do_test func3-1.3 { + sqlite3_create_function_v2 db f2 -1 utf16le -func f2 + set destroyed + } 0 + do_test func3-1.4 { + sqlite3_create_function_v2 db f2 -1 utf16be -func f2 + set destroyed + } 1 +} + +do_test func3-2.1 { + set destroyed 0 + proc destroy {} { set ::destroyed 1 } + sqlite3_create_function_v2 db f3 -1 utf8 -func f3 -destroy destroy + set destroyed +} 0 +do_test func3-2.2 { + sqlite3_create_function_v2 db f3 -1 utf8 -func f3 + set destroyed +} 1 + +do_test func3-3.1 { + set destroyed 0 + proc destroy {} { set ::destroyed 1 } + sqlite3_create_function_v2 db f3 -1 any -func f3 -destroy destroy + set destroyed +} 0 +do_test func3-3.2 { + db close + set destroyed +} 1 + +sqlite3 db test.db +do_test func3-4.1 { + set destroyed 0 + set rc [catch { + sqlite3_create_function_v2 db f3 -1 any -func f3 -step f3 -destroy destroy + } msg] + list $rc $msg +} {1 SQLITE_MISUSE} +do_test func3-4.2 { set destroyed } 1 + +# EVIDENCE-OF: R-41921-05214 The likelihood(X,Y) function returns +# argument X unchanged. +# +do_execsql_test func3-5.1 { + SELECT likelihood(9223372036854775807, 0.5); +} {9223372036854775807} +do_execsql_test func3-5.2 { + SELECT likelihood(-9223372036854775808, 0.5); +} {-9223372036854775808} +do_execsql_test func3-5.3 { + SELECT likelihood(14.125, 0.5); +} {14.125} +do_execsql_test func3-5.4 { + SELECT likelihood(NULL, 0.5); +} {{}} +do_execsql_test func3-5.5 { + SELECT likelihood('test-string', 0.5); +} {test-string} +do_execsql_test func3-5.6 { + SELECT quote(likelihood(x'010203000405', 0.5)); +} {X'010203000405'} + +# EVIDENCE-OF: R-44133-61651 The value Y in likelihood(X,Y) must be a +# floating point constant between 0.0 and 1.0, inclusive. +# +do_execsql_test func3-5.7 { + SELECT likelihood(123, 1.0), likelihood(456, 0.0); +} {123 456} +do_test func3-5.8 { + catchsql { + SELECT likelihood(123, 1.000001); + } +} {1 {second argument to likelihood() must be a constant between 0.0 and 1.0}} +do_test func3-5.9 { + catchsql { + SELECT likelihood(123, -0.000001); + } +} {1 {second argument to likelihood() must be a constant between 0.0 and 1.0}} +do_test func3-5.10 { + catchsql { + SELECT likelihood(123, 0.5+0.3); + } +} {1 {second argument to likelihood() must be a constant between 0.0 and 1.0}} + +# EVIDENCE-OF: R-28535-44631 The likelihood(X) function is a no-op that +# the code generator optimizes away so that it consumes no CPU cycles +# during run-time (that is, during calls to sqlite3_step()). +# +do_test func3-5.20 { + db eval {EXPLAIN SELECT likelihood(min(1.0+'2.0',4*11), 0.5)} +} [db eval {EXPLAIN SELECT min(1.0+'2.0',4*11)}] + + +# EVIDENCE-OF: R-11152-23456 The unlikely(X) function returns the +# argument X unchanged. +# +do_execsql_test func3-5.30 { + SELECT unlikely(9223372036854775807); +} {9223372036854775807} +do_execsql_test func3-5.31 { + SELECT unlikely(-9223372036854775808); +} {-9223372036854775808} +do_execsql_test func3-5.32 { + SELECT unlikely(14.125); +} {14.125} +do_execsql_test func3-5.33 { + SELECT unlikely(NULL); +} {{}} +do_execsql_test func3-5.34 { + SELECT unlikely('test-string'); +} {test-string} +do_execsql_test func3-5.35 { + SELECT quote(unlikely(x'010203000405')); +} {X'010203000405'} + +# EVIDENCE-OF: R-22887-63324 The unlikely(X) function is a no-op that +# the code generator optimizes away so that it consumes no CPU cycles at +# run-time (that is, during calls to sqlite3_step()). +# +do_test func3-5.40 { + db eval {EXPLAIN SELECT unlikely(min(1.0+'2.0',4*11))} +} [db eval {EXPLAIN SELECT min(1.0+'2.0',4*11)}] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/func4.test b/components/external/SQLite-3.8.1/test/func4.test new file mode 100644 index 0000000000000000000000000000000000000000..34a8be88400793ca117eeb3058633d6151cef6f7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/func4.test @@ -0,0 +1,758 @@ +# 2013 March 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus of +# this file is testing the tointeger() and toreal() functions. +# +# Several of the toreal() tests are disabled on platforms where floating +# point precision is not high enough to represent their constant integer +# expression arguments as double precision floating point values. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set saved_tcl_precision $tcl_precision +set tcl_precision 0 +load_static_extension db totype + +set highPrecision(1) [expr \ + {[db eval {SELECT tointeger(9223372036854775807 + 1);}] eq {{}}}] + +do_execsql_test func4-1.1 { + SELECT tointeger(NULL); +} {{}} +do_execsql_test func4-1.2 { + SELECT tointeger(''); +} {{}} +do_execsql_test func4-1.3 { + SELECT tointeger(' '); +} {{}} +do_execsql_test func4-1.4 { + SELECT tointeger('1234'); +} {1234} +do_execsql_test func4-1.5 { + SELECT tointeger(' 1234'); +} {{}} +do_execsql_test func4-1.6 { + SELECT tointeger('bad'); +} {{}} +do_execsql_test func4-1.7 { + SELECT tointeger('0xBAD'); +} {{}} +do_execsql_test func4-1.8 { + SELECT tointeger('123BAD'); +} {{}} +do_execsql_test func4-1.9 { + SELECT tointeger('0x123BAD'); +} {{}} +do_execsql_test func4-1.10 { + SELECT tointeger('123NO'); +} {{}} +do_execsql_test func4-1.11 { + SELECT tointeger('0x123NO'); +} {{}} +do_execsql_test func4-1.12 { + SELECT tointeger('-0x1'); +} {{}} +do_execsql_test func4-1.13 { + SELECT tointeger('-0x0'); +} {{}} +do_execsql_test func4-1.14 { + SELECT tointeger('0x0'); +} {{}} +do_execsql_test func4-1.15 { + SELECT tointeger('0x1'); +} {{}} +do_execsql_test func4-1.16 { + SELECT tointeger(-1); +} {-1} +do_execsql_test func4-1.17 { + SELECT tointeger(-0); +} {0} +do_execsql_test func4-1.18 { + SELECT tointeger(0); +} {0} +do_execsql_test func4-1.19 { + SELECT tointeger(1); +} {1} +do_execsql_test func4-1.20 { + SELECT tointeger(-1.79769313486232e308 - 1); +} {{}} +do_execsql_test func4-1.21 { + SELECT tointeger(-1.79769313486232e308); +} {{}} +do_execsql_test func4-1.22 { + SELECT tointeger(-1.79769313486232e308 + 1); +} {{}} +do_execsql_test func4-1.23 { + SELECT tointeger(-9223372036854775808 - 1); +} {-9223372036854775808} +do_execsql_test func4-1.24 { + SELECT tointeger(-9223372036854775808); +} {-9223372036854775808} +do_execsql_test func4-1.25 { + SELECT tointeger(-9223372036854775808 + 1); +} {-9223372036854775807} +do_execsql_test func4-1.26 { + SELECT tointeger(-9223372036854775807 - 1); +} {-9223372036854775808} +do_execsql_test func4-1.27 { + SELECT tointeger(-9223372036854775807); +} {-9223372036854775807} +do_execsql_test func4-1.28 { + SELECT tointeger(-9223372036854775807 + 1); +} {-9223372036854775806} +do_execsql_test func4-1.29 { + SELECT tointeger(-2147483648 - 1); +} {-2147483649} +do_execsql_test func4-1.30 { + SELECT tointeger(-2147483648); +} {-2147483648} +do_execsql_test func4-1.31 { + SELECT tointeger(-2147483648 + 1); +} {-2147483647} +do_execsql_test func4-1.32 { + SELECT tointeger(2147483647 - 1); +} {2147483646} +do_execsql_test func4-1.33 { + SELECT tointeger(2147483647); +} {2147483647} +do_execsql_test func4-1.34 { + SELECT tointeger(2147483647 + 1); +} {2147483648} +do_execsql_test func4-1.35 { + SELECT tointeger(9223372036854775807 - 1); +} {9223372036854775806} +do_execsql_test func4-1.36 { + SELECT tointeger(9223372036854775807); +} {9223372036854775807} +if {$highPrecision(1)} { + do_execsql_test func4-1.37 { + SELECT tointeger(9223372036854775807 + 1); + } {{}} +} +do_execsql_test func4-1.38 { + SELECT tointeger(1.79769313486232e308 - 1); +} {{}} +do_execsql_test func4-1.39 { + SELECT tointeger(1.79769313486232e308); +} {{}} +do_execsql_test func4-1.40 { + SELECT tointeger(1.79769313486232e308 + 1); +} {{}} +do_execsql_test func4-1.41 { + SELECT tointeger(4503599627370496 - 1); +} {4503599627370495} +do_execsql_test func4-1.42 { + SELECT tointeger(4503599627370496); +} {4503599627370496} +do_execsql_test func4-1.43 { + SELECT tointeger(4503599627370496 + 1); +} {4503599627370497} +do_execsql_test func4-1.44 { + SELECT tointeger(9007199254740992 - 1); +} {9007199254740991} +do_execsql_test func4-1.45 { + SELECT tointeger(9007199254740992); +} {9007199254740992} +do_execsql_test func4-1.46 { + SELECT tointeger(9007199254740992 + 1); +} {9007199254740993} +do_execsql_test func4-1.47 { + SELECT tointeger(9223372036854775807 - 1); +} {9223372036854775806} +do_execsql_test func4-1.48 { + SELECT tointeger(9223372036854775807); +} {9223372036854775807} +if {$highPrecision(1)} { + do_execsql_test func4-1.49 { + SELECT tointeger(9223372036854775807 + 1); + } {{}} + do_execsql_test func4-1.50 { + SELECT tointeger(9223372036854775808 - 1); + } {{}} + do_execsql_test func4-1.51 { + SELECT tointeger(9223372036854775808); + } {{}} + do_execsql_test func4-1.52 { + SELECT tointeger(9223372036854775808 + 1); + } {{}} +} +do_execsql_test func4-1.53 { + SELECT tointeger(18446744073709551616 - 1); +} {{}} +do_execsql_test func4-1.54 { + SELECT tointeger(18446744073709551616); +} {{}} +do_execsql_test func4-1.55 { + SELECT tointeger(18446744073709551616 + 1); +} {{}} + +ifcapable floatingpoint { + set highPrecision(2) [expr \ + {[db eval {SELECT toreal(-9223372036854775808 + 1);}] eq {{}}}] + + do_execsql_test func4-2.1 { + SELECT toreal(NULL); + } {{}} + do_execsql_test func4-2.2 { + SELECT toreal(''); + } {{}} + do_execsql_test func4-2.3 { + SELECT toreal(' '); + } {{}} + do_execsql_test func4-2.4 { + SELECT toreal('1234'); + } {1234.0} + do_execsql_test func4-2.5 { + SELECT toreal(' 1234'); + } {{}} + do_execsql_test func4-2.6 { + SELECT toreal('bad'); + } {{}} + do_execsql_test func4-2.7 { + SELECT toreal('0xBAD'); + } {{}} + do_execsql_test func4-2.8 { + SELECT toreal('123BAD'); + } {{}} + do_execsql_test func4-2.9 { + SELECT toreal('0x123BAD'); + } {{}} + do_execsql_test func4-2.10 { + SELECT toreal('123NO'); + } {{}} + do_execsql_test func4-2.11 { + SELECT toreal('0x123NO'); + } {{}} + do_execsql_test func4-2.12 { + SELECT toreal('-0x1'); + } {{}} + do_execsql_test func4-2.13 { + SELECT toreal('-0x0'); + } {{}} + do_execsql_test func4-2.14 { + SELECT toreal('0x0'); + } {{}} + do_execsql_test func4-2.15 { + SELECT toreal('0x1'); + } {{}} + do_execsql_test func4-2.16 { + SELECT toreal(-1); + } {-1.0} + do_execsql_test func4-2.17 { + SELECT toreal(-0); + } {0.0} + do_execsql_test func4-2.18 { + SELECT toreal(0); + } {0.0} + do_execsql_test func4-2.19 { + SELECT toreal(1); + } {1.0} + do_execsql_test func4-2.20 { + SELECT toreal(-1.79769313486232e308 - 1); + } {-Inf} + do_execsql_test func4-2.21 { + SELECT toreal(-1.79769313486232e308); + } {-Inf} + do_execsql_test func4-2.22 { + SELECT toreal(-1.79769313486232e308 + 1); + } {-Inf} + do_execsql_test func4-2.23 { + SELECT toreal(-9223372036854775808 - 1); + } {-9.223372036854776e+18} + do_execsql_test func4-2.24 { + SELECT toreal(-9223372036854775808); + } {-9.223372036854776e+18} + if {$highPrecision(2)} { + do_execsql_test func4-2.25 { + SELECT toreal(-9223372036854775808 + 1); + } {{}} + } + do_execsql_test func4-2.26 { + SELECT toreal(-9223372036854775807 - 1); + } {-9.223372036854776e+18} + if {$highPrecision(2)} { + do_execsql_test func4-2.27 { + SELECT toreal(-9223372036854775807); + } {{}} + do_execsql_test func4-2.28 { + SELECT toreal(-9223372036854775807 + 1); + } {{}} + } + do_execsql_test func4-2.29 { + SELECT toreal(-2147483648 - 1); + } {-2147483649.0} + do_execsql_test func4-2.30 { + SELECT toreal(-2147483648); + } {-2147483648.0} + do_execsql_test func4-2.31 { + SELECT toreal(-2147483648 + 1); + } {-2147483647.0} + do_execsql_test func4-2.32 { + SELECT toreal(2147483647 - 1); + } {2147483646.0} + do_execsql_test func4-2.33 { + SELECT toreal(2147483647); + } {2147483647.0} + do_execsql_test func4-2.34 { + SELECT toreal(2147483647 + 1); + } {2147483648.0} + if {$highPrecision(2)} { + do_execsql_test func4-2.35 { + SELECT toreal(9223372036854775807 - 1); + } {{}} + if {$highPrecision(1)} { + do_execsql_test func4-2.36 { + SELECT toreal(9223372036854775807); + } {{}} + } + } + do_execsql_test func4-2.37 { + SELECT toreal(9223372036854775807 + 1); + } {9.223372036854776e+18} + do_execsql_test func4-2.38 { + SELECT toreal(1.79769313486232e308 - 1); + } {Inf} + do_execsql_test func4-2.39 { + SELECT toreal(1.79769313486232e308); + } {Inf} + do_execsql_test func4-2.40 { + SELECT toreal(1.79769313486232e308 + 1); + } {Inf} + do_execsql_test func4-2.41 { + SELECT toreal(4503599627370496 - 1); + } {4503599627370495.0} + do_execsql_test func4-2.42 { + SELECT toreal(4503599627370496); + } {4503599627370496.0} + do_execsql_test func4-2.43 { + SELECT toreal(4503599627370496 + 1); + } {4503599627370497.0} + do_execsql_test func4-2.44 { + SELECT toreal(9007199254740992 - 1); + } {9007199254740991.0} + do_execsql_test func4-2.45 { + SELECT toreal(9007199254740992); + } {9007199254740992.0} + if {$highPrecision(2)} { + do_execsql_test func4-2.46 { + SELECT toreal(9007199254740992 + 1); + } {{}} + } + do_execsql_test func4-2.47 { + SELECT toreal(9007199254740992 + 2); + } {9007199254740994.0} + do_execsql_test func4-2.48 { + SELECT toreal(tointeger(9223372036854775808) - 1); + } {{}} + if {$highPrecision(1)} { + do_execsql_test func4-2.49 { + SELECT toreal(tointeger(9223372036854775808)); + } {{}} + do_execsql_test func4-2.50 { + SELECT toreal(tointeger(9223372036854775808) + 1); + } {{}} + } + do_execsql_test func4-2.51 { + SELECT toreal(tointeger(18446744073709551616) - 1); + } {{}} + do_execsql_test func4-2.52 { + SELECT toreal(tointeger(18446744073709551616)); + } {{}} + do_execsql_test func4-2.53 { + SELECT toreal(tointeger(18446744073709551616) + 1); + } {{}} +} + +ifcapable check { + do_execsql_test func4-3.1 { + CREATE TABLE t1( + x INTEGER CHECK(tointeger(x) IS NOT NULL) + ); + } {} + do_test func4-3.2 { + catchsql { + INSERT INTO t1 (x) VALUES (NULL); + } + } {1 {constraint failed}} + do_test func4-3.3 { + catchsql { + INSERT INTO t1 (x) VALUES (NULL); + } + } {1 {constraint failed}} + do_test func4-3.4 { + catchsql { + INSERT INTO t1 (x) VALUES (''); + } + } {1 {constraint failed}} + do_test func4-3.5 { + catchsql { + INSERT INTO t1 (x) VALUES ('bad'); + } + } {1 {constraint failed}} + do_test func4-3.6 { + catchsql { + INSERT INTO t1 (x) VALUES ('1234bad'); + } + } {1 {constraint failed}} + do_test func4-3.7 { + catchsql { + INSERT INTO t1 (x) VALUES ('1234.56bad'); + } + } {1 {constraint failed}} + do_test func4-3.8 { + catchsql { + INSERT INTO t1 (x) VALUES (1234); + } + } {0 {}} + do_test func4-3.9 { + catchsql { + INSERT INTO t1 (x) VALUES (1234.56); + } + } {1 {constraint failed}} + do_test func4-3.10 { + catchsql { + INSERT INTO t1 (x) VALUES ('1234'); + } + } {0 {}} + do_test func4-3.11 { + catchsql { + INSERT INTO t1 (x) VALUES ('1234.56'); + } + } {1 {constraint failed}} + do_test func4-3.12 { + catchsql { + INSERT INTO t1 (x) VALUES (ZEROBLOB(4)); + } + } {1 {constraint failed}} + do_test func4-3.13 { + catchsql { + INSERT INTO t1 (x) VALUES (X''); + } + } {1 {constraint failed}} + do_test func4-3.14 { + catchsql { + INSERT INTO t1 (x) VALUES (X'1234'); + } + } {1 {constraint failed}} + do_test func4-3.15 { + catchsql { + INSERT INTO t1 (x) VALUES (X'12345678'); + } + } {1 {constraint failed}} + do_test func4-3.16 { + catchsql { + INSERT INTO t1 (x) VALUES ('1234.00'); + } + } {1 {constraint failed}} + do_test func4-3.17 { + catchsql { + INSERT INTO t1 (x) VALUES (1234.00); + } + } {0 {}} + do_test func4-3.18 { + catchsql { + INSERT INTO t1 (x) VALUES ('-9223372036854775809'); + } + } {1 {constraint failed}} + if {$highPrecision(1)} { + do_test func4-3.19 { + catchsql { + INSERT INTO t1 (x) VALUES (9223372036854775808); + } + } {1 {constraint failed}} + } + do_execsql_test func4-3.20 { + SELECT x FROM t1 ORDER BY x; + } {1234 1234 1234} + + ifcapable floatingpoint { + do_execsql_test func4-4.1 { + CREATE TABLE t2( + x REAL CHECK(toreal(x) IS NOT NULL) + ); + } {} + do_test func4-4.2 { + catchsql { + INSERT INTO t2 (x) VALUES (NULL); + } + } {1 {constraint failed}} + do_test func4-4.3 { + catchsql { + INSERT INTO t2 (x) VALUES (NULL); + } + } {1 {constraint failed}} + do_test func4-4.4 { + catchsql { + INSERT INTO t2 (x) VALUES (''); + } + } {1 {constraint failed}} + do_test func4-4.5 { + catchsql { + INSERT INTO t2 (x) VALUES ('bad'); + } + } {1 {constraint failed}} + do_test func4-4.6 { + catchsql { + INSERT INTO t2 (x) VALUES ('1234bad'); + } + } {1 {constraint failed}} + do_test func4-4.7 { + catchsql { + INSERT INTO t2 (x) VALUES ('1234.56bad'); + } + } {1 {constraint failed}} + do_test func4-4.8 { + catchsql { + INSERT INTO t2 (x) VALUES (1234); + } + } {0 {}} + do_test func4-4.9 { + catchsql { + INSERT INTO t2 (x) VALUES (1234.56); + } + } {0 {}} + do_test func4-4.10 { + catchsql { + INSERT INTO t2 (x) VALUES ('1234'); + } + } {0 {}} + do_test func4-4.11 { + catchsql { + INSERT INTO t2 (x) VALUES ('1234.56'); + } + } {0 {}} + do_test func4-4.12 { + catchsql { + INSERT INTO t2 (x) VALUES (ZEROBLOB(4)); + } + } {1 {constraint failed}} + do_test func4-4.13 { + catchsql { + INSERT INTO t2 (x) VALUES (X''); + } + } {1 {constraint failed}} + do_test func4-4.14 { + catchsql { + INSERT INTO t2 (x) VALUES (X'1234'); + } + } {1 {constraint failed}} + do_test func4-4.15 { + catchsql { + INSERT INTO t2 (x) VALUES (X'12345678'); + } + } {1 {constraint failed}} + do_execsql_test func4-4.16 { + SELECT x FROM t2 ORDER BY x; + } {1234.0 1234.0 1234.56 1234.56} + } +} + +ifcapable floatingpoint { + do_execsql_test func4-5.1 { + SELECT tointeger(toreal('1234')); + } {1234} + do_execsql_test func4-5.2 { + SELECT tointeger(toreal(-1)); + } {-1} + do_execsql_test func4-5.3 { + SELECT tointeger(toreal(-0)); + } {0} + do_execsql_test func4-5.4 { + SELECT tointeger(toreal(0)); + } {0} + do_execsql_test func4-5.5 { + SELECT tointeger(toreal(1)); + } {1} + do_execsql_test func4-5.6 { + SELECT tointeger(toreal(-9223372036854775808 - 1)); + } {-9223372036854775808} + do_execsql_test func4-5.7 { + SELECT tointeger(toreal(-9223372036854775808)); + } {-9223372036854775808} + if {$highPrecision(2)} { + do_execsql_test func4-5.8 { + SELECT tointeger(toreal(-9223372036854775808 + 1)); + } {{}} + } + do_execsql_test func4-5.9 { + SELECT tointeger(toreal(-2147483648 - 1)); + } {-2147483649} + do_execsql_test func4-5.10 { + SELECT tointeger(toreal(-2147483648)); + } {-2147483648} + do_execsql_test func4-5.11 { + SELECT tointeger(toreal(-2147483648 + 1)); + } {-2147483647} + do_execsql_test func4-5.12 { + SELECT tointeger(toreal(2147483647 - 1)); + } {2147483646} + do_execsql_test func4-5.13 { + SELECT tointeger(toreal(2147483647)); + } {2147483647} + do_execsql_test func4-5.14 { + SELECT tointeger(toreal(2147483647 + 1)); + } {2147483648} + do_execsql_test func4-5.15 { + SELECT tointeger(toreal(9223372036854775807 - 1)); + } {{}} + if {$highPrecision(1)} { + do_execsql_test func4-5.16 { + SELECT tointeger(toreal(9223372036854775807)); + } {{}} + do_execsql_test func4-5.17 { + SELECT tointeger(toreal(9223372036854775807 + 1)); + } {{}} + } + do_execsql_test func4-5.18 { + SELECT tointeger(toreal(4503599627370496 - 1)); + } {4503599627370495} + do_execsql_test func4-5.19 { + SELECT tointeger(toreal(4503599627370496)); + } {4503599627370496} + do_execsql_test func4-5.20 { + SELECT tointeger(toreal(4503599627370496 + 1)); + } {4503599627370497} + do_execsql_test func4-5.21 { + SELECT tointeger(toreal(9007199254740992 - 1)); + } {9007199254740991} + do_execsql_test func4-5.22 { + SELECT tointeger(toreal(9007199254740992)); + } {9007199254740992} + if {$highPrecision(2)} { + do_execsql_test func4-5.23 { + SELECT tointeger(toreal(9007199254740992 + 1)); + } {{}} + } + do_execsql_test func4-5.24 { + SELECT tointeger(toreal(9007199254740992 + 2)); + } {9007199254740994} + if {$highPrecision(1)} { + do_execsql_test func4-5.25 { + SELECT tointeger(toreal(9223372036854775808 - 1)); + } {{}} + do_execsql_test func4-5.26 { + SELECT tointeger(toreal(9223372036854775808)); + } {{}} + do_execsql_test func4-5.27 { + SELECT tointeger(toreal(9223372036854775808 + 1)); + } {{}} + } + do_execsql_test func4-5.28 { + SELECT tointeger(toreal(18446744073709551616 - 1)); + } {{}} + do_execsql_test func4-5.29 { + SELECT tointeger(toreal(18446744073709551616)); + } {{}} + do_execsql_test func4-5.30 { + SELECT tointeger(toreal(18446744073709551616 + 1)); + } {{}} +} + +for {set i 0} {$i < 10} {incr i} { + if {$i == 8} continue + do_execsql_test func4-6.1.$i.1 [subst { + SELECT tointeger(x'[string repeat 01 $i]'); + }] {{}} + ifcapable floatingpoint { + do_execsql_test func4-6.1.$i.2 [subst { + SELECT toreal(x'[string repeat 01 $i]'); + }] {{}} + } +} + +do_execsql_test func4-6.2.1 { + SELECT tointeger(x'0102030405060708'); +} {578437695752307201} +do_execsql_test func4-6.2.2 { + SELECT tointeger(x'0807060504030201'); +} {72623859790382856} + +ifcapable floatingpoint { + do_execsql_test func4-6.3.1 { + SELECT toreal(x'ffefffffffffffff'); + } {-1.7976931348623157e+308} + do_execsql_test func4-6.3.2 { + SELECT toreal(x'8010000000000000'); + } {-2.2250738585072014e-308} + do_execsql_test func4-6.3.3 { + SELECT toreal(x'c000000000000000'); + } {-2.0} + do_execsql_test func4-6.3.4 { + SELECT toreal(x'bff0000000000000'); + } {-1.0} + do_execsql_test func4-6.3.5 { + SELECT toreal(x'8000000000000000'); + } {-0.0} + do_execsql_test func4-6.3.6 { + SELECT toreal(x'0000000000000000'); + } {0.0} + do_execsql_test func4-6.3.7 { + SELECT toreal(x'3ff0000000000000'); + } {1.0} + do_execsql_test func4-6.3.8 { + SELECT toreal(x'4000000000000000'); + } {2.0} + do_execsql_test func4-6.3.9 { + SELECT toreal(x'0010000000000000'); + } {2.2250738585072014e-308} + do_execsql_test func4-6.3.10 { + SELECT toreal(x'7fefffffffffffff'); + } {1.7976931348623157e+308} + do_execsql_test func4-6.3.11 { + SELECT toreal(x'8000000000000001'); + } {-5e-324} + do_execsql_test func4-6.3.12 { + SELECT toreal(x'800fffffffffffff'); + } {-2.225073858507201e-308} + do_execsql_test func4-6.3.13 { + SELECT toreal(x'0000000000000001'); + } {5e-324} + do_execsql_test func4-6.3.14 { + SELECT toreal(x'000fffffffffffff'); + } {2.225073858507201e-308} + do_execsql_test func4-6.3.15 { + SELECT toreal(x'fff0000000000000'); + } {-Inf} + do_execsql_test func4-6.3.16 { + SELECT toreal(x'7ff0000000000000'); + } {Inf} + do_execsql_test func4-6.3.17 { + SELECT toreal(x'fff8000000000000'); + } {{}} + do_execsql_test func4-6.3.18 { + SELECT toreal(x'fff0000000000001'); + } {{}} + do_execsql_test func4-6.3.19 { + SELECT toreal(x'fff7ffffffffffff'); + } {{}} + do_execsql_test func4-6.3.20 { + SELECT toreal(x'7ff0000000000001'); + } {{}} + do_execsql_test func4-6.3.21 { + SELECT toreal(x'7ff7ffffffffffff'); + } {{}} + do_execsql_test func4-6.3.22 { + SELECT toreal(x'fff8000000000001'); + } {{}} + do_execsql_test func4-6.3.23 { + SELECT toreal(x'ffffffffffffffff'); + } {{}} + do_execsql_test func4-6.3.24 { + SELECT toreal(x'7ff8000000000000'); + } {{}} + do_execsql_test func4-6.3.25 { + SELECT toreal(x'7fffffffffffffff'); + } {{}} +} + +set tcl_precision $saved_tcl_precision +unset saved_tcl_precision +finish_test diff --git a/components/external/SQLite-3.8.1/test/fuzz-oss1.test b/components/external/SQLite-3.8.1/test/fuzz-oss1.test new file mode 100644 index 0000000000000000000000000000000000000000..08bc6708459dcc0d9df99d837f8f1d1074bf1809 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fuzz-oss1.test @@ -0,0 +1,2001 @@ +# 2012 May 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +# NB: Portions of this file are extracted from open-source projects +# covered by permissive licenses. Use of this file for testing is clearly +# allowed. However, do not incorporate the text of this one file into +# end-products without checking the licenses on the open-source projects +# from which this code was extracted. This warning applies to this one +# file only - not the bulk of the SQLite source code and tests. +# +#*********************************************************************** +# +# This file contains large and complex schemas obtained from open-source +# software projects. The schemas are parsed just to make sure that nothing +# breaks in the parser logic. +# +# These tests merely verify that the parse occurs without error. +# No attempt is made to verify correct operation of the resulting schema +# and statements. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Schema and query extracted from Skrooge.org. +# +do_test fuzz-oss1-skrooge { + db eval { +CREATE TABLE parameters (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_uuid_parent TEXT NOT NULL DEFAULT '',t_name TEXT NOT NULL,t_value TEXT NOT NULL DEFAULT '',b_blob BLOB,d_lastmodifdate DATE NOT NULL DEFAULT CURRENT_TIMESTAMP,i_tmp INTEGER NOT NULL DEFAULT 0); +CREATE TABLE doctransaction (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_name TEXT NOT NULL,t_mode VARCHAR(1) DEFAULT 'U' CHECK (t_mode IN ('U', 'R')),d_date DATE NOT NULL,t_savestep VARCHAR(1) DEFAULT 'N' CHECK (t_savestep IN ('Y', 'N')),i_parent INTEGER, t_refreshviews VARCHAR(1) DEFAULT 'Y' CHECK (t_refreshviews IN ('Y', 'N'))); +CREATE TABLE doctransactionitem (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, rd_doctransaction_id INTEGER NOT NULL,i_object_id INTEGER NOT NULL,t_object_table TEXT NOT NULL,t_action VARCHAR(1) DEFAULT 'I' CHECK (t_action IN ('I', 'U', 'D')),t_sqlorder TEXT NOT NULL DEFAULT ''); +CREATE TABLE doctransactionmsg (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, rd_doctransaction_id INTEGER NOT NULL,t_message TEXT NOT NULL DEFAULT '',t_popup VARCHAR(1) DEFAULT 'Y' CHECK (t_popup IN ('Y', 'N'))); +CREATE TABLE unit(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_name TEXT NOT NULL,t_symbol TEXT NOT NULL DEFAULT '',t_country TEXT NOT NULL DEFAULT '',t_type VARCHAR(1) NOT NULL DEFAULT 'C' CHECK (t_type IN ('1', '2', 'C', 'S', 'I', 'O')),t_internet_code TEXT NOT NULL DEFAULT '',i_nbdecimal INT NOT NULL DEFAULT 2,rd_unit_id INTEGER NOT NULL DEFAULT 0, t_source TEXT NOT NULL DEFAULT ''); +CREATE TABLE unitvalue(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,rd_unit_id INTEGER NOT NULL,d_date DATE NOT NULL,f_quantity FLOAT NOT NULL CHECK (f_quantity>=0)); +CREATE TABLE bank (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_name TEXT NOT NULL DEFAULT '',t_bank_number TEXT NOT NULL DEFAULT '',t_icon TEXT NOT NULL DEFAULT ''); +CREATE TABLE interest(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,rd_account_id INTEGER NOT NULL,d_date DATE NOT NULL,f_rate FLOAT NOT NULL CHECK (f_rate>=0),t_income_value_date_mode VARCHAR(1) NOT NULL DEFAULT 'F' CHECK (t_income_value_date_mode IN ('F', '0', '1', '2', '3', '4', '5')),t_expenditure_value_date_mode VARCHAR(1) NOT NULL DEFAULT 'F' CHECK (t_expenditure_value_date_mode IN ('F', '0', '1', '2', '3', '4', '5')),t_base VARCHAR(3) NOT NULL DEFAULT '24' CHECK (t_base IN ('24', '360', '365'))); +CREATE TABLE operation(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,i_group_id INTEGER NOT NULL DEFAULT 0,i_number INTEGER DEFAULT 0 CHECK (i_number>=0),d_date DATE NOT NULL DEFAULT '0000-00-00',rd_account_id INTEGER NOT NULL,t_mode TEXT NOT NULL DEFAULT '',r_payee_id INTEGER NOT NULL DEFAULT 0,t_comment TEXT NOT NULL DEFAULT '',rc_unit_id INTEGER NOT NULL,t_status VARCHAR(1) NOT NULL DEFAULT 'N' CHECK (t_status IN ('N', 'P', 'Y')),t_bookmarked VARCHAR(1) NOT NULL DEFAULT 'N' CHECK (t_bookmarked IN ('Y', 'N')),t_imported VARCHAR(1) NOT NULL DEFAULT 'N' CHECK (t_imported IN ('Y', 'N', 'P', 'T')),t_template VARCHAR(1) NOT NULL DEFAULT 'N' CHECK (t_template IN ('Y', 'N')),t_import_id TEXT NOT NULL DEFAULT '',i_tmp INTEGER NOT NULL DEFAULT 0,r_recurrentoperation_id INTEGER NOT NULL DEFAULT 0); +CREATE TABLE operationbalance(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,f_balance FLOAT NOT NULL DEFAULT 0,r_operation_id INTEGER NOT NULL); +CREATE TABLE refund (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_name TEXT NOT NULL DEFAULT '',t_comment TEXT NOT NULL DEFAULT '',t_close VARCHAR(1) DEFAULT 'N' CHECK (t_close IN ('Y', 'N'))); +CREATE TABLE payee (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_name TEXT NOT NULL DEFAULT '',t_address TEXT NOT NULL DEFAULT '', t_bookmarked VARCHAR(1) NOT NULL DEFAULT 'N' CHECK (t_bookmarked IN ('Y', 'N'))); +CREATE TABLE suboperation(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_comment TEXT NOT NULL DEFAULT '',rd_operation_id INTEGER NOT NULL,r_category_id INTEGER NOT NULL DEFAULT 0,f_value FLOAT NOT NULL DEFAULT 0.0,i_tmp INTEGER NOT NULL DEFAULT 0,r_refund_id INTEGER NOT NULL DEFAULT 0, t_formula TEXT NOT NULL DEFAULT ''); +CREATE TABLE rule (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_description TEXT NOT NULL DEFAULT '',t_definition TEXT NOT NULL DEFAULT '',t_action_description TEXT NOT NULL DEFAULT '',t_action_definition TEXT NOT NULL DEFAULT '',t_action_type VARCHAR(1) DEFAULT 'S' CHECK (t_action_type IN ('S', 'U', 'A')),t_bookmarked VARCHAR(1) NOT NULL DEFAULT 'N' CHECK (t_bookmarked IN ('Y', 'N')),f_sortorder FLOAT); +CREATE TABLE budget (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,rc_category_id INTEGER NOT NULL DEFAULT 0,t_including_subcategories TEXT NOT NULL DEFAULT 'N' CHECK (t_including_subcategories IN ('Y', 'N')),f_budgeted FLOAT NOT NULL DEFAULT 0.0,f_budgeted_modified FLOAT NOT NULL DEFAULT 0.0,f_transferred FLOAT NOT NULL DEFAULT 0.0,i_year INTEGER NOT NULL DEFAULT 2010,i_month INTEGER NOT NULL DEFAULT 0 CHECK (i_month>=0 AND i_month<=12)); +CREATE TABLE budgetcategory(id INTEGER NOT NULL DEFAULT 0,id_category INTEGER NOT NULL DEFAULT 0); +CREATE TABLE budgetrule (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,rc_category_id INTEGER NOT NULL DEFAULT 0,t_category_condition TEXT NOT NULL DEFAULT 'Y' CHECK (t_category_condition IN ('Y', 'N')),t_year_condition TEXT NOT NULL DEFAULT 'Y' CHECK (t_year_condition IN ('Y', 'N')),i_year INTEGER NOT NULL DEFAULT 2010,i_month INTEGER NOT NULL DEFAULT 0 CHECK (i_month>=0 AND i_month<=12),t_month_condition TEXT NOT NULL DEFAULT 'Y' CHECK (t_month_condition IN ('Y', 'N')),i_condition INTEGER NOT NULL DEFAULT 0 CHECK (i_condition IN (-1,0,1)),f_quantity FLOAT NOT NULL DEFAULT 0.0,t_absolute TEXT NOT NULL DEFAULT 'Y' CHECK (t_absolute IN ('Y', 'N')),rc_category_id_target INTEGER NOT NULL DEFAULT 0,t_category_target TEXT NOT NULL DEFAULT 'Y' CHECK (t_category_target IN ('Y', 'N')),t_rule TEXT NOT NULL DEFAULT 'N' CHECK (t_rule IN ('N', 'C', 'Y'))); +CREATE TABLE "recurrentoperation" (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,d_date DATE NOT NULL DEFAULT '0000-00-00',rd_operation_id INTEGER NOT NULL,i_period_increment INTEGER NOT NULL DEFAULT 1 CHECK (i_period_increment>=0),t_period_unit TEXT NOT NULL DEFAULT 'M' CHECK (t_period_unit IN ('D', 'W', 'M', 'Y')),t_auto_write VARCHAR(1) DEFAULT 'Y' CHECK (t_auto_write IN ('Y', 'N')),i_auto_write_days INTEGER NOT NULL DEFAULT 5 CHECK (i_auto_write_days>=0),t_warn VARCHAR(1) DEFAULT 'Y' CHECK (t_warn IN ('Y', 'N')),i_warn_days INTEGER NOT NULL DEFAULT 5 CHECK (i_warn_days>=0),t_times VARCHAR(1) DEFAULT 'N' CHECK (t_times IN ('Y', 'N')),i_nb_times INTEGER NOT NULL DEFAULT 1 CHECK (i_nb_times>=0)); +CREATE TABLE "category" (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_name TEXT NOT NULL DEFAULT '' CHECK (t_name NOT LIKE '% > %'),t_fullname TEXT,rd_category_id INT,t_bookmarked VARCHAR(1) NOT NULL DEFAULT 'N' CHECK (t_bookmarked IN ('Y', 'N'))); +CREATE TABLE "account"(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_name TEXT NOT NULL,t_number TEXT NOT NULL DEFAULT '',t_agency_number TEXT NOT NULL DEFAULT '',t_agency_address TEXT NOT NULL DEFAULT '',t_comment TEXT NOT NULL DEFAULT '',t_close VARCHAR(1) DEFAULT 'N' CHECK (t_close IN ('Y', 'N')),t_type VARCHAR(1) NOT NULL DEFAULT 'C' CHECK (t_type IN ('C', 'D', 'A', 'I', 'L', 'W', 'O')),t_bookmarked VARCHAR(1) NOT NULL DEFAULT 'N' CHECK (t_bookmarked IN ('Y', 'N')),rd_bank_id INTEGER NOT NULL); +CREATE TABLE "node" (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,t_name TEXT NOT NULL DEFAULT '' CHECK (t_name NOT LIKE '% > %'),t_fullname TEXT,t_icon TEXT DEFAULT '',f_sortorder FLOAT,t_autostart VARCHAR(1) DEFAULT 'N' CHECK (t_autostart IN ('Y', 'N')),t_data TEXT,rd_node_id INT CONSTRAINT fk_id REFERENCES node(id) ON DELETE CASCADE); +CREATE TABLE vm_category_display_tmp( + id INT, + t_name TEXT, + t_fullname TEXT, + rd_category_id INT, + t_bookmarked TEXT, + i_NBOPERATIONS, + f_REALCURRENTAMOUNT +); +CREATE TABLE vm_budget_tmp( + id INT, + rc_category_id INT, + t_including_subcategories TEXT, + f_budgeted REAL, + f_budgeted_modified REAL, + f_transferred REAL, + i_year INT, + i_month INT, + t_CATEGORY, + t_PERIOD, + f_CURRENTAMOUNT, + t_RULES +); +CREATE INDEX idx_doctransaction_parent ON doctransaction (i_parent); +CREATE INDEX idx_doctransactionitem_i_object_id ON doctransactionitem (i_object_id); +CREATE INDEX idx_doctransactionitem_t_object_table ON doctransactionitem (t_object_table); +CREATE INDEX idx_doctransactionitem_t_action ON doctransactionitem (t_action); +CREATE INDEX idx_doctransactionitem_rd_doctransaction_id ON doctransactionitem (rd_doctransaction_id); +CREATE INDEX idx_doctransactionitem_optimization ON doctransactionitem (rd_doctransaction_id, i_object_id, t_object_table, t_action, id); +CREATE INDEX idx_unit_unit_id ON unitvalue(rd_unit_id); +CREATE INDEX idx_account_bank_id ON account(rd_bank_id); +CREATE INDEX idx_account_type ON account(t_type); +CREATE INDEX idx_category_category_id ON category(rd_category_id); +CREATE INDEX idx_category_t_fullname ON category(t_fullname); +CREATE INDEX idx_operation_account_id ON operation (rd_account_id); +CREATE INDEX idx_operation_tmp1_found_transfert ON operation (rc_unit_id, d_date); +CREATE INDEX idx_operation_grouped_operation_id ON operation (i_group_id); +CREATE INDEX idx_operation_i_number ON operation (i_number); +CREATE INDEX idx_operation_i_tmp ON operation (i_tmp); +CREATE INDEX idx_operation_rd_account_id ON operation (rd_account_id); +CREATE INDEX idx_operation_rc_unit_id ON operation (rc_unit_id); +CREATE INDEX idx_operation_t_status ON operation (t_status); +CREATE INDEX idx_operation_t_import_id ON operation (t_import_id); +CREATE INDEX idx_operation_t_template ON operation (t_template); +CREATE INDEX idx_operation_d_date ON operation (d_date); +CREATE INDEX idx_operationbalance_operation_id ON operationbalance (r_operation_id); +CREATE INDEX idx_suboperation_operation_id ON suboperation (rd_operation_id); +CREATE INDEX idx_suboperation_i_tmp ON suboperation (i_tmp); +CREATE INDEX idx_suboperation_category_id ON suboperation (r_category_id); +CREATE INDEX idx_suboperation_refund_id_id ON suboperation (r_refund_id); +CREATE INDEX idx_recurrentoperation_rd_operation_id ON recurrentoperation (rd_operation_id); +CREATE INDEX idx_refund_close ON refund(t_close); +CREATE INDEX idx_interest_account_id ON interest (rd_account_id); +CREATE INDEX idx_rule_action_type ON rule(t_action_type); +CREATE INDEX idx_budget_category_id ON budget(rc_category_id); +CREATE INDEX idx_budgetcategory_id ON budgetcategory (id); +CREATE INDEX idx_budgetcategory_id_category ON budgetcategory (id_category); +CREATE UNIQUE INDEX uidx_parameters_uuid_parent_name ON parameters (t_uuid_parent, t_name); +CREATE UNIQUE INDEX uidx_node_parent_id_name ON node(t_name,rd_node_id); +CREATE UNIQUE INDEX uidx_node_fullname ON node(t_fullname); +CREATE UNIQUE INDEX uidx_unit_name ON unit(t_name); +CREATE UNIQUE INDEX uidx_unit_symbol ON unit(t_symbol); +CREATE UNIQUE INDEX uidx_unitvalue ON unitvalue(d_date,rd_unit_id); +CREATE UNIQUE INDEX uidx_bank_name ON bank(t_name); +CREATE UNIQUE INDEX uidx_account_name ON account(t_name); +CREATE UNIQUE INDEX uidx_category_parent_id_name ON category(t_name,rd_category_id); +CREATE UNIQUE INDEX uidx_category_fullname ON category(t_fullname); +CREATE UNIQUE INDEX uidx_refund_name ON refund(t_name); +CREATE UNIQUE INDEX uidx_payee_name ON payee(t_name); +CREATE UNIQUE INDEX uidx_interest ON interest(d_date,rd_account_id); +CREATE UNIQUE INDEX uidx_budget ON budget(i_year,i_month, rc_category_id); +CREATE VIEW v_node AS SELECT * from node; +CREATE VIEW v_node_displayname AS SELECT *, t_fullname AS t_displayname from node; +CREATE VIEW v_parameters_displayname AS SELECT *, t_name AS t_displayname from parameters; +CREATE TRIGGER fkdc_parameters_parameters_uuid BEFORE DELETE ON parameters FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'parameters'; END; +CREATE TRIGGER fkdc_node_parameters_uuid BEFORE DELETE ON node FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'node'; END; +CREATE TRIGGER cpt_node_fullname1 AFTER INSERT ON node BEGIN UPDATE node SET t_fullname=CASE WHEN new.rd_node_id IS NULL OR new.rd_node_id='' OR new.rd_node_id=0 THEN new.t_name ELSE (SELECT c.t_fullname from node c where c.id=new.rd_node_id)||' > '||new.t_name END WHERE id=new.id;END; +CREATE TRIGGER cpt_node_fullname2 AFTER UPDATE OF t_name, rd_node_id ON node BEGIN UPDATE node SET t_fullname=CASE WHEN new.rd_node_id IS NULL OR new.rd_node_id='' OR new.rd_node_id=0 THEN new.t_name ELSE (SELECT c.t_fullname from node c where c.id=new.rd_node_id)||' > '||new.t_name END WHERE id=new.id;UPDATE node SET t_name=t_name WHERE rd_node_id=new.id;END; +CREATE TRIGGER fki_account_bank_rd_bank_id_id BEFORE INSERT ON account FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (bank est utilisé par account) +Nom de la contrainte : fki_account_bank_rd_bank_id_id') WHERE NEW.rd_bank_id!=0 AND NEW.rd_bank_id!='' AND (SELECT id FROM bank WHERE id = NEW.rd_bank_id) IS NULL; END; +CREATE TRIGGER fku_account_bank_rd_bank_id_id BEFORE UPDATE ON account FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (bank est utilisé par account) +Nom de la contrainte : fku_account_bank_rd_bank_id_id') WHERE NEW.rd_bank_id!=0 AND NEW.rd_bank_id!='' AND (SELECT id FROM bank WHERE id = NEW.rd_bank_id) IS NULL; END; +CREATE TRIGGER fkdc_bank_account_id_rd_bank_id BEFORE DELETE ON bank FOR EACH ROW BEGIN DELETE FROM account WHERE account.rd_bank_id = OLD.id; END; +CREATE TRIGGER fki_budget_category_rc_category_id_id BEFORE INSERT ON budget FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (category est utilisé par budget) +Nom de la contrainte : fki_budget_category_rc_category_id_id') WHERE NEW.rc_category_id!=0 AND NEW.rc_category_id!='' AND (SELECT id FROM category WHERE id = NEW.rc_category_id) IS NULL; END; +CREATE TRIGGER fku_budget_category_rc_category_id_id BEFORE UPDATE ON budget FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (category est utilisé par budget) +Nom de la contrainte : fku_budget_category_rc_category_id_id') WHERE NEW.rc_category_id!=0 AND NEW.rc_category_id!='' AND (SELECT id FROM category WHERE id = NEW.rc_category_id) IS NULL; END; +CREATE TRIGGER fkd_budget_category_rc_category_id_id BEFORE DELETE ON category FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de détruire un objet (category est utilisé par budget) +Nom de la contrainte : fkd_budget_category_rc_category_id_id') WHERE (SELECT rc_category_id FROM budget WHERE rc_category_id = OLD.id) IS NOT NULL; END; +CREATE TRIGGER fki_budgetrule_category_rc_category_id_id BEFORE INSERT ON budgetrule FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (category est utilisé par budgetrule) +Nom de la contrainte : fki_budgetrule_category_rc_category_id_id') WHERE NEW.rc_category_id!=0 AND NEW.rc_category_id!='' AND (SELECT id FROM category WHERE id = NEW.rc_category_id) IS NULL; END; +CREATE TRIGGER fku_budgetrule_category_rc_category_id_id BEFORE UPDATE ON budgetrule FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (category est utilisé par budgetrule) +Nom de la contrainte : fku_budgetrule_category_rc_category_id_id') WHERE NEW.rc_category_id!=0 AND NEW.rc_category_id!='' AND (SELECT id FROM category WHERE id = NEW.rc_category_id) IS NULL; END; +CREATE TRIGGER fkd_budgetrule_category_rc_category_id_id BEFORE DELETE ON category FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de détruire un objet (category est utilisé par budgetrule) +Nom de la contrainte : fkd_budgetrule_category_rc_category_id_id') WHERE (SELECT rc_category_id FROM budgetrule WHERE rc_category_id = OLD.id) IS NOT NULL; END; +CREATE TRIGGER fki_budgetrule_category_rc_category_id_target_id BEFORE INSERT ON budgetrule FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (category est utilisé par budgetrule) +Nom de la contrainte : fki_budgetrule_category_rc_category_id_target_id') WHERE NEW.rc_category_id_target!=0 AND NEW.rc_category_id_target!='' AND (SELECT id FROM category WHERE id = NEW.rc_category_id_target) IS NULL; END; +CREATE TRIGGER fku_budgetrule_category_rc_category_id_target_id BEFORE UPDATE ON budgetrule FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (category est utilisé par budgetrule) +Nom de la contrainte : fku_budgetrule_category_rc_category_id_target_id') WHERE NEW.rc_category_id_target!=0 AND NEW.rc_category_id_target!='' AND (SELECT id FROM category WHERE id = NEW.rc_category_id_target) IS NULL; END; +CREATE TRIGGER fkd_budgetrule_category_rc_category_id_target_id BEFORE DELETE ON category FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de détruire un objet (category est utilisé par budgetrule) +Nom de la contrainte : fkd_budgetrule_category_rc_category_id_target_id') WHERE (SELECT rc_category_id_target FROM budgetrule WHERE rc_category_id_target = OLD.id) IS NOT NULL; END; +CREATE TRIGGER fki_category_category_rd_category_id_id BEFORE INSERT ON category FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (category est utilisé par category) +Nom de la contrainte : fki_category_category_rd_category_id_id') WHERE NEW.rd_category_id!=0 AND NEW.rd_category_id!='' AND (SELECT id FROM category WHERE id = NEW.rd_category_id) IS NULL; END; +CREATE TRIGGER fku_category_category_rd_category_id_id BEFORE UPDATE ON category FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (category est utilisé par category) +Nom de la contrainte : fku_category_category_rd_category_id_id') WHERE NEW.rd_category_id!=0 AND NEW.rd_category_id!='' AND (SELECT id FROM category WHERE id = NEW.rd_category_id) IS NULL; END; +CREATE TRIGGER fkdc_category_category_id_rd_category_id BEFORE DELETE ON category FOR EACH ROW BEGIN DELETE FROM category WHERE category.rd_category_id = OLD.id; END; +CREATE TRIGGER fki_doctransactionitem_doctransaction_rd_doctransaction_id_id BEFORE INSERT ON doctransactionitem FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (doctransaction est utilisé par doctransactionitem) +Nom de la contrainte : fki_doctransactionitem_doctransaction_rd_doctransaction_id_id') WHERE NEW.rd_doctransaction_id!=0 AND NEW.rd_doctransaction_id!='' AND (SELECT id FROM doctransaction WHERE id = NEW.rd_doctransaction_id) IS NULL; END; +CREATE TRIGGER fku_doctransactionitem_doctransaction_rd_doctransaction_id_id BEFORE UPDATE ON doctransactionitem FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (doctransaction est utilisé par doctransactionitem) +Nom de la contrainte : fku_doctransactionitem_doctransaction_rd_doctransaction_id_id') WHERE NEW.rd_doctransaction_id!=0 AND NEW.rd_doctransaction_id!='' AND (SELECT id FROM doctransaction WHERE id = NEW.rd_doctransaction_id) IS NULL; END; +CREATE TRIGGER fkdc_doctransaction_doctransactionitem_id_rd_doctransaction_id BEFORE DELETE ON doctransaction FOR EACH ROW BEGIN DELETE FROM doctransactionitem WHERE doctransactionitem.rd_doctransaction_id = OLD.id; END; +CREATE TRIGGER fki_doctransactionmsg_doctransaction_rd_doctransaction_id_id BEFORE INSERT ON doctransactionmsg FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (doctransaction est utilisé par doctransactionmsg) +Nom de la contrainte : fki_doctransactionmsg_doctransaction_rd_doctransaction_id_id') WHERE NEW.rd_doctransaction_id!=0 AND NEW.rd_doctransaction_id!='' AND (SELECT id FROM doctransaction WHERE id = NEW.rd_doctransaction_id) IS NULL; END; +CREATE TRIGGER fku_doctransactionmsg_doctransaction_rd_doctransaction_id_id BEFORE UPDATE ON doctransactionmsg FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (doctransaction est utilisé par doctransactionmsg) +Nom de la contrainte : fku_doctransactionmsg_doctransaction_rd_doctransaction_id_id') WHERE NEW.rd_doctransaction_id!=0 AND NEW.rd_doctransaction_id!='' AND (SELECT id FROM doctransaction WHERE id = NEW.rd_doctransaction_id) IS NULL; END; +CREATE TRIGGER fkdc_doctransaction_doctransactionmsg_id_rd_doctransaction_id BEFORE DELETE ON doctransaction FOR EACH ROW BEGIN DELETE FROM doctransactionmsg WHERE doctransactionmsg.rd_doctransaction_id = OLD.id; END; +CREATE TRIGGER fki_interest_account_rd_account_id_id BEFORE INSERT ON interest FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (account est utilisé par interest) +Nom de la contrainte : fki_interest_account_rd_account_id_id') WHERE NEW.rd_account_id!=0 AND NEW.rd_account_id!='' AND (SELECT id FROM account WHERE id = NEW.rd_account_id) IS NULL; END; +CREATE TRIGGER fku_interest_account_rd_account_id_id BEFORE UPDATE ON interest FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (account est utilisé par interest) +Nom de la contrainte : fku_interest_account_rd_account_id_id') WHERE NEW.rd_account_id!=0 AND NEW.rd_account_id!='' AND (SELECT id FROM account WHERE id = NEW.rd_account_id) IS NULL; END; +CREATE TRIGGER fkdc_account_interest_id_rd_account_id BEFORE DELETE ON account FOR EACH ROW BEGIN DELETE FROM interest WHERE interest.rd_account_id = OLD.id; END; +CREATE TRIGGER fki_node_node_rd_node_id_id BEFORE INSERT ON node FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (node est utilisé par node) +Nom de la contrainte : fki_node_node_rd_node_id_id') WHERE NEW.rd_node_id!=0 AND NEW.rd_node_id!='' AND (SELECT id FROM node WHERE id = NEW.rd_node_id) IS NULL; END; +CREATE TRIGGER fku_node_node_rd_node_id_id BEFORE UPDATE ON node FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (node est utilisé par node) +Nom de la contrainte : fku_node_node_rd_node_id_id') WHERE NEW.rd_node_id!=0 AND NEW.rd_node_id!='' AND (SELECT id FROM node WHERE id = NEW.rd_node_id) IS NULL; END; +CREATE TRIGGER fkdc_node_node_id_rd_node_id BEFORE DELETE ON node FOR EACH ROW BEGIN DELETE FROM node WHERE node.rd_node_id = OLD.id; END; +CREATE TRIGGER fki_operation_account_rd_account_id_id BEFORE INSERT ON operation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (account est utilisé par operation) +Nom de la contrainte : fki_operation_account_rd_account_id_id') WHERE NEW.rd_account_id!=0 AND NEW.rd_account_id!='' AND (SELECT id FROM account WHERE id = NEW.rd_account_id) IS NULL; END; +CREATE TRIGGER fku_operation_account_rd_account_id_id BEFORE UPDATE ON operation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (account est utilisé par operation) +Nom de la contrainte : fku_operation_account_rd_account_id_id') WHERE NEW.rd_account_id!=0 AND NEW.rd_account_id!='' AND (SELECT id FROM account WHERE id = NEW.rd_account_id) IS NULL; END; +CREATE TRIGGER fkdc_account_operation_id_rd_account_id BEFORE DELETE ON account FOR EACH ROW BEGIN DELETE FROM operation WHERE operation.rd_account_id = OLD.id; END; +CREATE TRIGGER fki_operation_payee_r_payee_id_id BEFORE INSERT ON operation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (payee est utilisé par operation) +Nom de la contrainte : fki_operation_payee_r_payee_id_id') WHERE NEW.r_payee_id!=0 AND NEW.r_payee_id!='' AND (SELECT id FROM payee WHERE id = NEW.r_payee_id) IS NULL; END; +CREATE TRIGGER fku_operation_payee_r_payee_id_id BEFORE UPDATE ON operation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (payee est utilisé par operation) +Nom de la contrainte : fku_operation_payee_r_payee_id_id') WHERE NEW.r_payee_id!=0 AND NEW.r_payee_id!='' AND (SELECT id FROM payee WHERE id = NEW.r_payee_id) IS NULL; END; +CREATE TRIGGER fkd_operation_payee_r_payee_id_id BEFORE DELETE ON payee FOR EACH ROW BEGIN UPDATE operation SET r_payee_id=0 WHERE r_payee_id=OLD.id; END; +CREATE TRIGGER fki_operation_unit_rc_unit_id_id BEFORE INSERT ON operation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (unit est utilisé par operation) +Nom de la contrainte : fki_operation_unit_rc_unit_id_id') WHERE NEW.rc_unit_id!=0 AND NEW.rc_unit_id!='' AND (SELECT id FROM unit WHERE id = NEW.rc_unit_id) IS NULL; END; +CREATE TRIGGER fku_operation_unit_rc_unit_id_id BEFORE UPDATE ON operation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (unit est utilisé par operation) +Nom de la contrainte : fku_operation_unit_rc_unit_id_id') WHERE NEW.rc_unit_id!=0 AND NEW.rc_unit_id!='' AND (SELECT id FROM unit WHERE id = NEW.rc_unit_id) IS NULL; END; +CREATE TRIGGER fkd_operation_unit_rc_unit_id_id BEFORE DELETE ON unit FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de détruire un objet (unit est utilisé par operation) +Nom de la contrainte : fkd_operation_unit_rc_unit_id_id') WHERE (SELECT rc_unit_id FROM operation WHERE rc_unit_id = OLD.id) IS NOT NULL; END; +CREATE TRIGGER fki_operation_recurrentoperation_r_recurrentoperation_id_id BEFORE INSERT ON operation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (recurrentoperation est utilisé par operation) +Nom de la contrainte : fki_operation_recurrentoperation_r_recurrentoperation_id_id') WHERE NEW.r_recurrentoperation_id!=0 AND NEW.r_recurrentoperation_id!='' AND (SELECT id FROM recurrentoperation WHERE id = NEW.r_recurrentoperation_id) IS NULL; END; +CREATE TRIGGER fku_operation_recurrentoperation_r_recurrentoperation_id_id BEFORE UPDATE ON operation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (recurrentoperation est utilisé par operation) +Nom de la contrainte : fku_operation_recurrentoperation_r_recurrentoperation_id_id') WHERE NEW.r_recurrentoperation_id!=0 AND NEW.r_recurrentoperation_id!='' AND (SELECT id FROM recurrentoperation WHERE id = NEW.r_recurrentoperation_id) IS NULL; END; +CREATE TRIGGER fkd_operation_recurrentoperation_r_recurrentoperation_id_id BEFORE DELETE ON recurrentoperation FOR EACH ROW BEGIN UPDATE operation SET r_recurrentoperation_id=0 WHERE r_recurrentoperation_id=OLD.id; END; +CREATE TRIGGER fki_operationbalance_operation_r_operation_id_id BEFORE INSERT ON operationbalance FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (operation est utilisé par operationbalance) +Nom de la contrainte : fki_operationbalance_operation_r_operation_id_id') WHERE NEW.r_operation_id!=0 AND NEW.r_operation_id!='' AND (SELECT id FROM operation WHERE id = NEW.r_operation_id) IS NULL; END; +CREATE TRIGGER fku_operationbalance_operation_r_operation_id_id BEFORE UPDATE ON operationbalance FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (operation est utilisé par operationbalance) +Nom de la contrainte : fku_operationbalance_operation_r_operation_id_id') WHERE NEW.r_operation_id!=0 AND NEW.r_operation_id!='' AND (SELECT id FROM operation WHERE id = NEW.r_operation_id) IS NULL; END; +CREATE TRIGGER fkd_operationbalance_operation_r_operation_id_id BEFORE DELETE ON operation FOR EACH ROW BEGIN UPDATE operationbalance SET r_operation_id=0 WHERE r_operation_id=OLD.id; END; +CREATE TRIGGER fki_recurrentoperation_operation_rd_operation_id_id BEFORE INSERT ON recurrentoperation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (operation est utilisé par recurrentoperation) +Nom de la contrainte : fki_recurrentoperation_operation_rd_operation_id_id') WHERE NEW.rd_operation_id!=0 AND NEW.rd_operation_id!='' AND (SELECT id FROM operation WHERE id = NEW.rd_operation_id) IS NULL; END; +CREATE TRIGGER fku_recurrentoperation_operation_rd_operation_id_id BEFORE UPDATE ON recurrentoperation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (operation est utilisé par recurrentoperation) +Nom de la contrainte : fku_recurrentoperation_operation_rd_operation_id_id') WHERE NEW.rd_operation_id!=0 AND NEW.rd_operation_id!='' AND (SELECT id FROM operation WHERE id = NEW.rd_operation_id) IS NULL; END; +CREATE TRIGGER fkdc_operation_recurrentoperation_id_rd_operation_id BEFORE DELETE ON operation FOR EACH ROW BEGIN DELETE FROM recurrentoperation WHERE recurrentoperation.rd_operation_id = OLD.id; END; +CREATE TRIGGER fki_suboperation_operation_rd_operation_id_id BEFORE INSERT ON suboperation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (operation est utilisé par suboperation) +Nom de la contrainte : fki_suboperation_operation_rd_operation_id_id') WHERE NEW.rd_operation_id!=0 AND NEW.rd_operation_id!='' AND (SELECT id FROM operation WHERE id = NEW.rd_operation_id) IS NULL; END; +CREATE TRIGGER fku_suboperation_operation_rd_operation_id_id BEFORE UPDATE ON suboperation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (operation est utilisé par suboperation) +Nom de la contrainte : fku_suboperation_operation_rd_operation_id_id') WHERE NEW.rd_operation_id!=0 AND NEW.rd_operation_id!='' AND (SELECT id FROM operation WHERE id = NEW.rd_operation_id) IS NULL; END; +CREATE TRIGGER fkdc_operation_suboperation_id_rd_operation_id BEFORE DELETE ON operation FOR EACH ROW BEGIN DELETE FROM suboperation WHERE suboperation.rd_operation_id = OLD.id; END; +CREATE TRIGGER fki_suboperation_category_r_category_id_id BEFORE INSERT ON suboperation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (category est utilisé par suboperation) +Nom de la contrainte : fki_suboperation_category_r_category_id_id') WHERE NEW.r_category_id!=0 AND NEW.r_category_id!='' AND (SELECT id FROM category WHERE id = NEW.r_category_id) IS NULL; END; +CREATE TRIGGER fku_suboperation_category_r_category_id_id BEFORE UPDATE ON suboperation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (category est utilisé par suboperation) +Nom de la contrainte : fku_suboperation_category_r_category_id_id') WHERE NEW.r_category_id!=0 AND NEW.r_category_id!='' AND (SELECT id FROM category WHERE id = NEW.r_category_id) IS NULL; END; +CREATE TRIGGER fkd_suboperation_category_r_category_id_id BEFORE DELETE ON category FOR EACH ROW BEGIN UPDATE suboperation SET r_category_id=0 WHERE r_category_id=OLD.id; END; +CREATE TRIGGER fki_suboperation_refund_r_refund_id_id BEFORE INSERT ON suboperation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (refund est utilisé par suboperation) +Nom de la contrainte : fki_suboperation_refund_r_refund_id_id') WHERE NEW.r_refund_id!=0 AND NEW.r_refund_id!='' AND (SELECT id FROM refund WHERE id = NEW.r_refund_id) IS NULL; END; +CREATE TRIGGER fku_suboperation_refund_r_refund_id_id BEFORE UPDATE ON suboperation FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (refund est utilisé par suboperation) +Nom de la contrainte : fku_suboperation_refund_r_refund_id_id') WHERE NEW.r_refund_id!=0 AND NEW.r_refund_id!='' AND (SELECT id FROM refund WHERE id = NEW.r_refund_id) IS NULL; END; +CREATE TRIGGER fkd_suboperation_refund_r_refund_id_id BEFORE DELETE ON refund FOR EACH ROW BEGIN UPDATE suboperation SET r_refund_id=0 WHERE r_refund_id=OLD.id; END; +CREATE TRIGGER fki_unit_unit_rd_unit_id_id BEFORE INSERT ON unit FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (unit est utilisé par unit) +Nom de la contrainte : fki_unit_unit_rd_unit_id_id') WHERE NEW.rd_unit_id!=0 AND NEW.rd_unit_id!='' AND (SELECT id FROM unit WHERE id = NEW.rd_unit_id) IS NULL; END; +CREATE TRIGGER fku_unit_unit_rd_unit_id_id BEFORE UPDATE ON unit FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (unit est utilisé par unit) +Nom de la contrainte : fku_unit_unit_rd_unit_id_id') WHERE NEW.rd_unit_id!=0 AND NEW.rd_unit_id!='' AND (SELECT id FROM unit WHERE id = NEW.rd_unit_id) IS NULL; END; +CREATE TRIGGER fkdc_unit_unit_id_rd_unit_id BEFORE DELETE ON unit FOR EACH ROW BEGIN DELETE FROM unit WHERE unit.rd_unit_id = OLD.id; END; +CREATE TRIGGER fki_unitvalue_unit_rd_unit_id_id BEFORE INSERT ON unitvalue FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible d''ajouter un objet (unit est utilisé par unitvalue) +Nom de la contrainte : fki_unitvalue_unit_rd_unit_id_id') WHERE NEW.rd_unit_id!=0 AND NEW.rd_unit_id!='' AND (SELECT id FROM unit WHERE id = NEW.rd_unit_id) IS NULL; END; +CREATE TRIGGER fku_unitvalue_unit_rd_unit_id_id BEFORE UPDATE ON unitvalue FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de modifier un objet (unit est utilisé par unitvalue) +Nom de la contrainte : fku_unitvalue_unit_rd_unit_id_id') WHERE NEW.rd_unit_id!=0 AND NEW.rd_unit_id!='' AND (SELECT id FROM unit WHERE id = NEW.rd_unit_id) IS NULL; END; +CREATE TRIGGER fkdc_unit_unitvalue_id_rd_unit_id BEFORE DELETE ON unit FOR EACH ROW BEGIN DELETE FROM unitvalue WHERE unitvalue.rd_unit_id = OLD.id; END; +CREATE TRIGGER fkd_vm_budget_tmp_category_rc_category_id_id BEFORE DELETE ON category FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Impossible de détruire un objet (category est utilisé par vm_budget_tmp) +Nom de la contrainte : fkd_vm_budget_tmp_category_rc_category_id_id') WHERE (SELECT rc_category_id FROM vm_budget_tmp WHERE rc_category_id = OLD.id) IS NOT NULL; END; +CREATE TRIGGER fkdc_category_vm_category_display_tmp_id_rd_category_id BEFORE DELETE ON category FOR EACH ROW BEGIN DELETE FROM vm_category_display_tmp WHERE vm_category_display_tmp.rd_category_id = OLD.id; END; +CREATE VIEW v_unit_displayname AS SELECT *, t_name||' ('||t_symbol||')' AS t_displayname FROM unit; +CREATE VIEW v_unit_tmp1 AS SELECT *,(SELECT count(*) FROM unitvalue s WHERE s.rd_unit_id=unit.id) AS i_NBVALUES, (CASE WHEN unit.rd_unit_id=0 THEN '' ELSE (SELECT (CASE WHEN s.t_symbol!='' THEN s.t_symbol ELSE s.t_name END) FROM unit s WHERE s.id=unit.rd_unit_id) END) AS t_UNIT,(CASE unit.t_type WHEN '1' THEN 'Monnaie principale' WHEN '2' THEN 'Monnaie secondaire' WHEN 'C' THEN 'Monnaie' WHEN 'S' THEN 'Action' WHEN 'I' THEN 'Indice' ELSE 'Objet' END) AS t_TYPENLS, (SELECT MIN(s.d_date) FROM unitvalue s WHERE s.rd_unit_id=unit.id) AS d_MINDATE, (SELECT MAX(s.d_date) FROM unitvalue s WHERE s.rd_unit_id=unit.id) AS d_MAXDATE from unit; +CREATE VIEW v_unit_tmp2 AS SELECT *,CASE WHEN v_unit_tmp1.t_type='1' THEN 1 ELSE IFNULL((SELECT s.f_quantity FROM unitvalue s WHERE s.rd_unit_id=v_unit_tmp1.id AND s.d_date=v_unit_tmp1.d_MAXDATE),1) END AS f_LASTVALUE from v_unit_tmp1; +CREATE VIEW v_unit AS SELECT *,v_unit_tmp2.f_LASTVALUE*IFNULL((SELECT s2.f_LASTVALUE FROM v_unit_tmp2 s2 WHERE s2.id=v_unit_tmp2.rd_unit_id) , 1) AS f_CURRENTAMOUNT from v_unit_tmp2; +CREATE VIEW v_unitvalue_displayname AS SELECT *, (SELECT t_displayname FROM v_unit_displayname WHERE unitvalue.rd_unit_id=v_unit_displayname.id)||' '||STRFTIME('%d/%m/%Y',d_date) AS t_displayname FROM unitvalue; +CREATE VIEW v_unitvalue AS SELECT * FROM unitvalue; +CREATE VIEW v_suboperation AS SELECT * FROM suboperation; +CREATE VIEW v_operation_numbers AS SELECT DISTINCT i_number, rd_account_id FROM operation; +CREATE VIEW v_operation_next_numbers AS SELECT T1.i_number+1 AS i_number FROM v_operation_numbers AS T1 LEFT OUTER JOIN v_operation_numbers T2 ON T2.rd_account_id=T1.rd_account_id AND T2.i_number=T1.i_number+1 WHERE T1.i_number!=0 AND (T2.i_number IS NULL) ORDER BY T1.i_number; +CREATE VIEW v_operation_tmp1 AS SELECT *,(SELECT t_name FROM payee s WHERE s.id=operation.r_payee_id) AS t_PAYEE,(SELECT TOTAL(s.f_value) FROM suboperation s WHERE s.rd_operation_id=operation.ID) AS f_QUANTITY,(SELECT count(*) FROM suboperation s WHERE s.rd_operation_id=operation.ID) AS i_NBSUBCATEGORY FROM operation; +CREATE VIEW v_operation AS SELECT *,(SELECT s.id FROM suboperation s WHERE s.rd_operation_id=v_operation_tmp1.id AND ABS(s.f_value)=(SELECT MAX(ABS(s2.f_value)) FROM suboperation s2 WHERE s2.rd_operation_id=v_operation_tmp1.id)) AS i_MOSTIMPSUBOP,((SELECT s.f_CURRENTAMOUNT FROM v_unit s WHERE s.id=v_operation_tmp1.rc_unit_id)*v_operation_tmp1.f_QUANTITY) AS f_CURRENTAMOUNT, (CASE WHEN v_operation_tmp1.i_group_id<>0 AND EXISTS (SELECT 1 FROM account a WHERE v_operation_tmp1.rd_account_id=a.id AND a.t_type<>'L') AND EXISTS (SELECT 1 FROM v_operation_tmp1 op2, account a WHERE op2.i_group_id=v_operation_tmp1.i_group_id AND op2.rd_account_id=a.id AND a.t_type<>'L' AND op2.rc_unit_id=v_operation_tmp1.rc_unit_id AND op2.f_QUANTITY=-v_operation_tmp1.f_QUANTITY) THEN 'Y' ELSE 'N' END) AS t_TRANSFER FROM v_operation_tmp1; +CREATE VIEW v_operation_displayname AS SELECT *, STRFTIME('%d/%m/%Y',d_date)||' '||IFNULL(t_PAYEE,'')||' '||v_operation.f_CURRENTAMOUNT||' '||(SELECT (CASE WHEN s.t_symbol!='' THEN s.t_symbol ELSE s.t_name END) FROM unit s WHERE s.id=v_operation.rc_unit_id) AS t_displayname FROM v_operation; +CREATE VIEW v_operation_delete AS SELECT *, (CASE WHEN t_status='Y' THEN 'Vous n''êtes pas autorisé à détruire cette opération car en état « rapproché »' END) t_delete_message FROM operation; +CREATE VIEW v_account AS SELECT *,(SELECT MAX(s.d_date) FROM interest s WHERE s.rd_account_id=account.id) AS d_MAXDATE, (SELECT TOTAL(s.f_CURRENTAMOUNT) FROM v_operation s WHERE s.rd_account_id=account.id AND s.t_template='N') AS f_CURRENTAMOUNT FROM account; +CREATE VIEW v_account_delete AS SELECT *, (CASE WHEN EXISTS(SELECT 1 FROM operation WHERE rd_account_id=account.id AND d_date<>'0000-00-00' AND t_template='N' AND t_status='Y') THEN 'Vous n''êtes pas autorisé à détruire ce compte car il contient des opérations rapprochées' END) t_delete_message FROM account; +CREATE VIEW v_bank_displayname AS SELECT *, t_name AS t_displayname FROM bank; +CREATE VIEW v_account_displayname AS SELECT *, (SELECT t_displayname FROM v_bank_displayname WHERE account.rd_bank_id=v_bank_displayname.id)||'-'||t_name AS t_displayname FROM account; +CREATE VIEW v_bank AS SELECT *,(SELECT TOTAL(s.f_CURRENTAMOUNT) FROM v_account s WHERE s.rd_bank_id=bank.id) AS f_CURRENTAMOUNT FROM bank; +CREATE VIEW v_category_displayname AS SELECT *, t_fullname AS t_displayname FROM category; +CREATE VIEW v_category AS SELECT * FROM category; +CREATE VIEW v_recurrentoperation AS SELECT *,i_period_increment||' '||(CASE t_period_unit WHEN 'Y' THEN 'année(s)' WHEN 'M' THEN 'mois' WHEN 'W' THEN 'semaine(s)' ELSE 'jour(s)' END) AS t_PERIODNLS FROM recurrentoperation; +CREATE VIEW v_recurrentoperation_displayname AS SELECT *, STRFTIME('%d/%m/%Y',d_date)||' '||SUBSTR((SELECT t_displayname FROM v_operation_displayname WHERE v_operation_displayname.id=v_recurrentoperation.rd_operation_id), 11) AS t_displayname FROM v_recurrentoperation; +CREATE VIEW v_unitvalue_display AS SELECT *,IFNULL((SELECT (CASE WHEN s.t_symbol!='' THEN s.t_symbol ELSE s.t_name END) FROM unit s WHERE s.id=(SELECT s2.rd_unit_id FROM unit s2 WHERE s2.id=unitvalue.rd_unit_id)),'') AS t_UNIT,STRFTIME('%Y-%m',unitvalue.d_date) AS d_DATEMONTH,STRFTIME('%Y',unitvalue.d_date) AS d_DATEYEAR FROM unitvalue; +CREATE VIEW v_suboperation_display AS SELECT *,IFNULL((SELECT s.t_fullname FROM category s WHERE s.id=v_suboperation.r_category_id),'') AS t_CATEGORY, IFNULL((SELECT s.t_name FROM refund s WHERE s.id=v_suboperation.r_refund_id),'') AS t_REFUND, (CASE WHEN v_suboperation.f_value>=0 THEN v_suboperation.f_value ELSE 0 END) AS f_VALUE_INCOME, (CASE WHEN v_suboperation.f_value<=0 THEN v_suboperation.f_value ELSE 0 END) AS f_VALUE_EXPENSE FROM v_suboperation; +CREATE VIEW v_suboperation_displayname AS SELECT *, t_CATEGORY||' : '||f_value AS t_displayname FROM v_suboperation_display; +CREATE VIEW v_operation_display_all AS SELECT *,(SELECT s.t_name FROM account s WHERE s.id=v_operation.rd_account_id) AS t_ACCOUNT,(SELECT (CASE WHEN s.t_symbol!='' THEN s.t_symbol ELSE s.t_name END) FROM unit s WHERE s.id=v_operation.rc_unit_id) AS t_UNIT,(SELECT s.t_CATEGORY FROM v_suboperation_display s WHERE s.id=v_operation.i_MOSTIMPSUBOP) AS t_CATEGORY,(SELECT s.t_REFUND FROM v_suboperation_display s WHERE s.id=v_operation.i_MOSTIMPSUBOP) AS t_REFUND,(CASE WHEN v_operation.f_QUANTITY<0 THEN '-' WHEN v_operation.f_QUANTITY=0 THEN '' ELSE '+' END) AS t_TYPEEXPENSE, (CASE WHEN v_operation.f_QUANTITY<=0 THEN 'Dépense' ELSE 'Revenu' END) AS t_TYPEEXPENSENLS, STRFTIME('%Y-W%W',v_operation.d_date) AS d_DATEWEEK,STRFTIME('%Y-%m',v_operation.d_date) AS d_DATEMONTH,STRFTIME('%Y',v_operation.d_date)||'-Q'||(CASE WHEN STRFTIME('%m',v_operation.d_date)<='03' THEN '1' WHEN STRFTIME('%m',v_operation.d_date)<='06' THEN '2' WHEN STRFTIME('%m',v_operation.d_date)<='09' THEN '3' ELSE '4' END) AS d_DATEQUARTER, STRFTIME('%Y',v_operation.d_date)||'-S'||(CASE WHEN STRFTIME('%m',v_operation.d_date)<='06' THEN '1' ELSE '2' END) AS d_DATESEMESTER, STRFTIME('%Y',v_operation.d_date) AS d_DATEYEAR, (SELECT count(*) FROM v_recurrentoperation s WHERE s.rd_operation_id=v_operation.id) AS i_NBRECURRENT, (CASE WHEN v_operation.f_QUANTITY>=0 THEN v_operation.f_QUANTITY ELSE 0 END) AS f_QUANTITY_INCOME, (CASE WHEN v_operation.f_QUANTITY<=0 THEN v_operation.f_QUANTITY ELSE 0 END) AS f_QUANTITY_EXPENSE, (SELECT o2.f_balance FROM operationbalance o2 WHERE o2.r_operation_id=v_operation.id ) AS f_BALANCE, (CASE WHEN v_operation.f_QUANTITY>=0 THEN v_operation.f_CURRENTAMOUNT ELSE 0 END) AS f_CURRENTAMOUNT_INCOME, (CASE WHEN v_operation.f_QUANTITY<=0 THEN v_operation.f_CURRENTAMOUNT ELSE 0 END) AS f_CURRENTAMOUNT_EXPENSE FROM v_operation; +CREATE VIEW v_operation_template_display AS SELECT * FROM v_operation_display_all WHERE t_template='Y'; +CREATE VIEW v_operation_display AS SELECT * FROM v_operation_display_all WHERE d_date!='0000-00-00' AND t_template='N'; +CREATE VIEW v_unit_display AS SELECT *,(SELECT TOTAL(o.f_QUANTITY) FROM v_operation_display o WHERE o.rc_unit_id=v_unit.id) AS f_QUANTITYOWNED FROM v_unit; +CREATE VIEW v_account_display AS SELECT (CASE t_type WHEN 'C' THEN 'Courant' WHEN 'D' THEN 'Carte de crédit' WHEN 'A' THEN 'Actif' WHEN 'I' THEN 'Investissement' WHEN 'W' THEN 'Portefeuille' WHEN 'L' THEN 'Prêt' WHEN 'O' THEN 'Autre' END) AS t_TYPENLS,bank.t_name AS t_BANK,bank.t_bank_number AS t_BANK_NUMBER,bank.t_icon AS t_ICON,v_account.*,(v_account.f_CURRENTAMOUNT/(SELECT u.f_CURRENTAMOUNT FROM v_unit u, operation s WHERE u.id=s.rc_unit_id AND s.rd_account_id=v_account.id AND s.d_date='0000-00-00')) AS f_QUANTITY, (SELECT (CASE WHEN u.t_symbol!='' THEN u.t_symbol ELSE u.t_name END) FROM unit u, operation s WHERE u.id=s.rc_unit_id AND s.rd_account_id=v_account.id AND s.d_date='0000-00-00') AS t_UNIT, (SELECT TOTAL(s.f_CURRENTAMOUNT) FROM v_operation s WHERE s.rd_account_id=v_account.id AND s.t_status!='N' AND s.t_template='N') AS f_CHECKED, (SELECT TOTAL(s.f_CURRENTAMOUNT) FROM v_operation s WHERE s.rd_account_id=v_account.id AND s.t_status='N' AND s.t_template='N') AS f_COMING_SOON, (SELECT TOTAL(s.f_CURRENTAMOUNT) FROM v_operation s WHERE s.rd_account_id=v_account.id AND s.d_date<=date('now') AND s.t_template='N') AS f_TODAYAMOUNT, (SELECT count(*) FROM v_operation_display s WHERE s.rd_account_id=v_account.id) AS i_NBOPERATIONS, IFNULL((SELECT s.f_rate FROM interest s WHERE s.rd_account_id=v_account.id AND s.d_date=v_account.d_MAXDATE),0) AS f_RATE FROM v_account, bank WHERE bank.id=v_account.rd_bank_id; +CREATE VIEW v_operation_consolidated AS SELECT (SELECT s.t_TYPENLS FROM v_account_display s WHERE s.id=op.rd_account_id) AS t_ACCOUNTTYPE,(SELECT u.t_TYPENLS FROM v_unit u WHERE u.id=op.rc_unit_id) AS t_UNITTYPE,sop.id AS i_SUBOPID, sop.r_refund_id AS r_refund_id, (CASE WHEN sop.t_comment='' THEN op.t_comment ELSE sop.t_comment END) AS t_REALCOMMENT, sop.t_CATEGORY AS t_REALCATEGORY, sop.t_REFUND AS t_REALREFUND, sop.r_category_id AS i_IDCATEGORY, (CASE WHEN sop.f_value<0 THEN '-' WHEN sop.f_value=0 THEN '' ELSE '+' END) AS t_TYPEEXPENSE, (CASE WHEN sop.f_value<0 THEN 'Dépense' WHEN sop.f_value=0 THEN '' ELSE 'Revenu' END) AS t_TYPEEXPENSENLS, sop.f_value AS f_REALQUANTITY, sop.f_VALUE_INCOME AS f_REALQUANTITY_INCOME, sop.f_VALUE_EXPENSE AS f_REALQUANTITY_EXPENSE, ((SELECT u.f_CURRENTAMOUNT FROM v_unit u WHERE u.id=op.rc_unit_id)*sop.f_value) AS f_REALCURRENTAMOUNT, ((SELECT u.f_CURRENTAMOUNT FROM v_unit u WHERE u.id=op.rc_unit_id)*sop.f_VALUE_INCOME) AS f_REALCURRENTAMOUNT_INCOME, ((SELECT u.f_CURRENTAMOUNT FROM v_unit u WHERE u.id=op.rc_unit_id)*sop.f_VALUE_EXPENSE) AS f_REALCURRENTAMOUNT_EXPENSE, op.* FROM v_operation_display_all AS op, v_suboperation_display AS sop WHERE op.t_template='N' AND sop.rd_operation_id=op.ID; +CREATE VIEW v_operation_prop AS SELECT p.id AS i_PROPPID, p.t_name AS i_PROPPNAME, p.t_value AS i_PROPVALUE, op.* FROM v_operation_consolidated AS op LEFT OUTER JOIN parameters AS p ON p.t_uuid_parent=op.id||'-operation'; +CREATE VIEW v_refund_delete AS SELECT *, (CASE WHEN EXISTS(SELECT 1 FROM v_operation_consolidated WHERE r_refund_id=refund.id AND t_status='Y') THEN 'Vous n''êtes pas autorisé à détruire ce suiveur car utilisé par des opérations rapprochées' END) t_delete_message FROM refund; +CREATE VIEW v_refund AS SELECT *, (SELECT TOTAL(o.f_REALCURRENTAMOUNT) FROM v_operation_consolidated o WHERE o.r_refund_id=refund.id) AS f_CURRENTAMOUNT FROM refund; +CREATE VIEW v_refund_display AS SELECT *,(SELECT MIN(o.d_date) FROM v_operation_consolidated o WHERE o.r_refund_id=v_refund.id) AS d_FIRSTDATE, (SELECT MAX(o.d_date) FROM v_operation_consolidated o WHERE o.r_refund_id=v_refund.id) AS d_LASTDATE FROM v_refund; +CREATE VIEW v_refund_displayname AS SELECT *, t_name AS t_displayname FROM refund; +CREATE VIEW v_payee_delete AS SELECT *, (CASE WHEN EXISTS(SELECT 1 FROM operation WHERE r_payee_id=payee.id AND t_status='Y') THEN 'Vous n''êtes pas autorisé à détruire ce tiers car utilisé par des opérations rapprochées' END) t_delete_message FROM payee; +CREATE VIEW v_payee AS SELECT *, (SELECT TOTAL(o.f_CURRENTAMOUNT) FROM v_operation o WHERE o.r_payee_id=payee.id AND o.t_template='N') AS f_CURRENTAMOUNT FROM payee; +CREATE VIEW v_payee_display AS SELECT * FROM v_payee; +CREATE VIEW v_payee_displayname AS SELECT *, t_name AS t_displayname FROM payee; +CREATE VIEW v_category_delete AS SELECT *, (CASE WHEN EXISTS(SELECT 1 FROM v_operation_consolidated WHERE (t_REALCATEGORY=category.t_fullname OR t_REALCATEGORY like category.t_fullname||'%') AND t_status='Y') THEN 'Vous n''êtes pas autorisé à détruire cette catégorie car utilisée par des opérations rapprochées' END) t_delete_message FROM category; +CREATE VIEW v_category_display_tmp AS SELECT *,(SELECT count(distinct(so.rd_operation_id)) FROM operation o, suboperation so WHERE so.rd_operation_id=o.id AND so.r_category_id=v_category.ID AND o.t_template='N') AS i_NBOPERATIONS, (SELECT TOTAL(o.f_REALCURRENTAMOUNT) FROM v_operation_consolidated o WHERE o.i_IDCATEGORY=v_category.ID) AS f_REALCURRENTAMOUNT FROM v_category; +CREATE VIEW v_category_display AS SELECT *,f_REALCURRENTAMOUNT+(SELECT TOTAL(c.f_REALCURRENTAMOUNT) FROM vm_category_display_tmp c WHERE c.t_fullname LIKE vm_category_display_tmp.t_fullname||' > %') AS f_SUMCURRENTAMOUNT, i_NBOPERATIONS+(SELECT CAST(TOTAL(c.i_NBOPERATIONS) AS INTEGER) FROM vm_category_display_tmp c WHERE c.t_fullname like vm_category_display_tmp.t_fullname||' > %') AS i_SUMNBOPERATIONS, (CASE WHEN t_bookmarked='Y' THEN 'Y' WHEN EXISTS(SELECT 1 FROM category c WHERE c.t_bookmarked='Y' AND c.t_fullname like vm_category_display_tmp.t_fullname||' > %') THEN 'C' ELSE 'N' END) AS t_HASBOOKMARKEDCHILD, (CASE WHEN vm_category_display_tmp.f_REALCURRENTAMOUNT<0 THEN '-' WHEN vm_category_display_tmp.f_REALCURRENTAMOUNT=0 THEN '' ELSE '+' END) AS t_TYPEEXPENSE,(CASE WHEN vm_category_display_tmp.f_REALCURRENTAMOUNT<0 THEN 'Dépense' WHEN vm_category_display_tmp.f_REALCURRENTAMOUNT=0 THEN '' ELSE 'Revenu' END) AS t_TYPEEXPENSENLS FROM vm_category_display_tmp; +CREATE VIEW v_recurrentoperation_display AS SELECT rop.*, op.t_ACCOUNT, op.i_number, op.t_mode, op.i_group_id, op.t_TRANSFER, op.t_PAYEE, op.t_comment, op.t_CATEGORY, op.t_status, op.f_CURRENTAMOUNT FROM v_recurrentoperation rop, v_operation_display_all AS op WHERE rop.rd_operation_id=op.ID; +CREATE VIEW v_rule AS SELECT *,(SELECT COUNT(1) FROM rule r WHERE r.f_sortorder<=rule.f_sortorder) AS i_ORDER FROM rule; +CREATE VIEW v_rule_displayname AS SELECT *, t_definition AS t_displayname FROM rule; +CREATE VIEW v_interest AS SELECT *,(SELECT s.t_name FROM account s WHERE s.id=interest.rd_account_id) AS t_ACCOUNT FROM interest; +CREATE VIEW v_interest_displayname AS SELECT *, STRFTIME('%d/%m/%Y',d_date)||' '||f_rate||'%' AS t_displayname FROM interest; +CREATE VIEW v_budgetrule AS SELECT *, IFNULL((SELECT s.t_fullname FROM category s WHERE s.id=budgetrule.rc_category_id),'') AS t_CATEGORYCONDITION, IFNULL((SELECT s.t_fullname FROM category s WHERE s.id=budgetrule.rc_category_id_target),'') AS t_CATEGORY, (CASE WHEN budgetrule.i_condition=-1 THEN 'Négatif' WHEN budgetrule.i_condition=1 THEN 'Positif' WHEN budgetrule.i_condition=0 THEN 'Tous' END) AS t_WHENNLS, f_quantity||(CASE WHEN budgetrule.t_absolute='N' THEN '%' ELSE (SELECT t_symbol FROM unit WHERE t_type='1') END) AS t_WHATNLS,(CASE WHEN budgetrule.t_rule='N' THEN 'Suivant' WHEN budgetrule.t_rule='C' THEN 'Courant' WHEN budgetrule.t_rule='Y' THEN 'Année' END) AS t_RULENLS FROM budgetrule; +CREATE VIEW v_budgetrule_display AS SELECT * FROM v_budgetrule; +CREATE VIEW v_budgetrule_displayname AS SELECT *, t_WHENNLS||' '||t_WHATNLS||' '||t_RULENLS||' '||t_CATEGORY AS t_displayname FROM v_budgetrule; +CREATE VIEW v_budget_tmp AS SELECT *, IFNULL((SELECT s.t_fullname FROM category s WHERE s.id=budget.rc_category_id),'') AS t_CATEGORY, (i_year||(CASE WHEN i_month=0 THEN '' WHEN i_month<10 THEN '-0'||i_month ELSE '-'||i_month END)) AS t_PERIOD, (SELECT TOTAL(o.f_REALCURRENTAMOUNT) FROM v_operation_consolidated o WHERE STRFTIME('%Y', o.d_date)=i_year AND (i_month=0 OR STRFTIME('%m', o.d_date)=i_month) AND o.i_IDCATEGORY IN (SELECT b2.id_category FROM budgetcategory b2 WHERE b2.id=budget.id)) AS f_CURRENTAMOUNT, (SELECT GROUP_CONCAT(v_budgetrule_displayname.t_displayname,',') FROM v_budgetrule_displayname WHERE (v_budgetrule_displayname.t_year_condition='N' OR budget.i_year=v_budgetrule_displayname.i_year) AND (v_budgetrule_displayname.t_month_condition='N' OR budget.i_month=v_budgetrule_displayname.i_month) AND (v_budgetrule_displayname.t_category_condition='N' OR budget.rc_category_id=v_budgetrule_displayname.rc_category_id) ORDER BY v_budgetrule_displayname.t_absolute DESC, v_budgetrule_displayname.id) AS t_RULES FROM budget; +CREATE VIEW v_budget AS SELECT *, (f_CURRENTAMOUNT-f_budgeted_modified) AS f_DELTABEFORETRANSFER, (f_CURRENTAMOUNT-f_budgeted_modified-f_transferred) AS f_DELTA FROM v_budget_tmp; +CREATE VIEW v_budget_display AS SELECT *, (f_CURRENTAMOUNT-f_budgeted_modified) AS f_DELTABEFORETRANSFER, (f_CURRENTAMOUNT-f_budgeted_modified-f_transferred) AS f_DELTA FROM vm_budget_tmp; +CREATE VIEW v_budget_displayname AS SELECT *, t_CATEGORY||' '||t_PERIOD||' '||f_budgeted_modified AS t_displayname FROM v_budget; +CREATE TRIGGER fkdc_bank_parameters_uuid BEFORE DELETE ON bank FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'bank'; END; +CREATE TRIGGER fkdc_account_parameters_uuid BEFORE DELETE ON account FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'account'; END; +CREATE TRIGGER fkdc_unit_parameters_uuid BEFORE DELETE ON unit FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'unit'; END; +CREATE TRIGGER fkdc_unitvalue_parameters_uuid BEFORE DELETE ON unitvalue FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'unitvalue'; END; +CREATE TRIGGER fkdc_category_parameters_uuid BEFORE DELETE ON category FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'category'; END; +CREATE TRIGGER fkdc_operation_parameters_uuid BEFORE DELETE ON operation FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'operation'; END; +CREATE TRIGGER fkdc_interest_parameters_uuid BEFORE DELETE ON interest FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'interest'; END; +CREATE TRIGGER fkdc_suboperation_parameters_uuid BEFORE DELETE ON suboperation FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'suboperation'; END; +CREATE TRIGGER fkdc_refund_parameters_uuid BEFORE DELETE ON refund FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'refund'; END; +CREATE TRIGGER fkdc_payee_parameters_uuid BEFORE DELETE ON payee FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'payee'; END; +CREATE TRIGGER fkdc_recurrentoperation_parameters_uuid BEFORE DELETE ON recurrentoperation FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'recurrentoperation'; END; +CREATE TRIGGER fkdc_rule_parameters_uuid BEFORE DELETE ON rule FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'rule'; END; +CREATE TRIGGER fkdc_budget_parameters_uuid BEFORE DELETE ON budget FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'budget'; END; +CREATE TRIGGER fkdc_budgetrule_parameters_uuid BEFORE DELETE ON budgetrule FOR EACH ROW BEGIN DELETE FROM parameters WHERE parameters.t_uuid_parent=OLD.id||'-'||'budgetrule'; END; +CREATE TRIGGER cpt_category_fullname1 AFTER INSERT ON category BEGIN UPDATE category SET t_fullname=CASE WHEN rd_category_id IS NULL OR rd_category_id='' OR rd_category_id=0 THEN new.t_name ELSE (SELECT c.t_fullname FROM category c WHERE c.id=new.rd_category_id)||' > '||new.t_name END WHERE id=new.id;END; +CREATE TRIGGER cpt_category_fullname2 AFTER UPDATE OF t_name, rd_category_id ON category BEGIN UPDATE category SET t_fullname=CASE WHEN rd_category_id IS NULL OR rd_category_id='' OR rd_category_id=0 THEN new.t_name ELSE (SELECT c.t_fullname FROM category c WHERE c.id=new.rd_category_id)||' > '||new.t_name END WHERE id=new.id;UPDATE category SET t_name=t_name WHERE rd_category_id=new.id;END; +CREATE TRIGGER fkdc_category_delete BEFORE DELETE ON category FOR EACH ROW BEGIN UPDATE suboperation SET r_category_id=OLD.rd_category_id WHERE r_category_id=OLD.id; END; +explain + SELECT TOTAL(f_CURRENTAMOUNT), d_DATEMONTH + from v_operation_display + WHERE d_DATEMONTH IN ('2012-05', '2012-04') + group by d_DATEMONTH, t_TYPEEXPENSE; + } +} {/.* Goto .*/} + +# The next test requires FTS4 +ifcapable !fts3 { + finish_test + return +} + +# Taken from the gnome-shell project +# +db close +forcedelete test.db +sqlite3 db test.db +do_test fuzz-oss1-gnomeshell { + db eval { +CREATE TABLE Resource (ID INTEGER NOT NULL PRIMARY KEY, Uri TEXT NOT +NULL, UNIQUE (Uri)); +CREATE VIRTUAL TABLE fts USING fts4; +CREATE TABLE "mfo:Action" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mfo:Enclosure" (ID INTEGER NOT NULL PRIMARY KEY, +"mfo:remoteLink" INTEGER, "mfo:remoteLink:graph" INTEGER, +"mfo:groupDefault" INTEGER, "mfo:groupDefault:graph" INTEGER, +"mfo:localLink" INTEGER, "mfo:localLink:graph" INTEGER, "mfo:optional" +INTEGER, "mfo:optional:graph" INTEGER); +CREATE TABLE "mfo:FeedChannel" (ID INTEGER NOT NULL PRIMARY KEY, +"mfo:updatedTime" INTEGER, "mfo:updatedTime:graph" INTEGER, +"mfo:updatedTime:localDate" INTEGER, "mfo:updatedTime:localTime" +INTEGER, "mfo:unreadCount" INTEGER, "mfo:unreadCount:graph" INTEGER, +"mfo:totalCount" INTEGER, "mfo:totalCount:graph" INTEGER, "mfo:action" +INTEGER, "mfo:action:graph" INTEGER, "mfo:type" INTEGER, +"mfo:type:graph" INTEGER); +CREATE TABLE "mfo:FeedElement" (ID INTEGER NOT NULL PRIMARY KEY, +"mfo:image" TEXT COLLATE NOCASE, "mfo:image:graph" INTEGER, +"mfo:feedSettings" INTEGER, "mfo:feedSettings:graph" INTEGER); +CREATE TABLE "mfo:FeedMessage" (ID INTEGER NOT NULL PRIMARY KEY, +"mfo:downloadedTime" INTEGER, "mfo:downloadedTime:graph" INTEGER, +"mfo:downloadedTime:localDate" INTEGER, "mfo:downloadedTime:localTime" +INTEGER); +CREATE TABLE "mfo:FeedMessage_mfo:enclosureList" (ID INTEGER NOT NULL, +"mfo:enclosureList" INTEGER NOT NULL, "mfo:enclosureList:graph" +INTEGER); +CREATE TABLE "mfo:FeedSettings" (ID INTEGER NOT NULL PRIMARY KEY, +"mfo:updateInterval" INTEGER, "mfo:updateInterval:graph" INTEGER, +"mfo:expiryInterval" INTEGER, "mfo:expiryInterval:graph" INTEGER, +"mfo:downloadPath" TEXT COLLATE NOCASE, "mfo:downloadPath:graph" +INTEGER, "mfo:downloadFlag" INTEGER, "mfo:downloadFlag:graph" INTEGER, +"mfo:maxSize" INTEGER, "mfo:maxSize:graph" INTEGER); +CREATE TABLE "mfo:FeedType" (ID INTEGER NOT NULL PRIMARY KEY, +"mfo:name" TEXT COLLATE NOCASE, "mfo:name:graph" INTEGER); +CREATE TABLE "mlo:GeoBoundingBox" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mlo:GeoBoundingBox_mlo:bbNorthWest" (ID INTEGER NOT +NULL, "mlo:bbNorthWest" INTEGER NOT NULL, "mlo:bbNorthWest:graph" +INTEGER); +CREATE TABLE "mlo:GeoBoundingBox_mlo:bbSouthEast" (ID INTEGER NOT +NULL, "mlo:bbSouthEast" INTEGER NOT NULL, "mlo:bbSouthEast:graph" +INTEGER); +CREATE TABLE "mlo:GeoLocation" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mlo:GeoLocation_mlo:asBoundingBox" (ID INTEGER NOT NULL, +"mlo:asBoundingBox" INTEGER NOT NULL, "mlo:asBoundingBox:graph" +INTEGER); +CREATE TABLE "mlo:GeoLocation_mlo:asGeoPoint" (ID INTEGER NOT NULL, +"mlo:asGeoPoint" INTEGER NOT NULL, "mlo:asGeoPoint:graph" INTEGER); +CREATE TABLE "mlo:GeoLocation_mlo:asPostalAddress" (ID INTEGER NOT +NULL, "mlo:asPostalAddress" INTEGER NOT NULL, +"mlo:asPostalAddress:graph" INTEGER); +CREATE TABLE "mlo:GeoPoint" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mlo:GeoPoint_mlo:address" (ID INTEGER NOT NULL, +"mlo:address" TEXT NOT NULL, "mlo:address:graph" INTEGER); +CREATE TABLE "mlo:GeoPoint_mlo:altitude" (ID INTEGER NOT NULL, +"mlo:altitude" REAL NOT NULL, "mlo:altitude:graph" INTEGER); +CREATE TABLE "mlo:GeoPoint_mlo:city" (ID INTEGER NOT NULL, "mlo:city" +TEXT NOT NULL, "mlo:city:graph" INTEGER); +CREATE TABLE "mlo:GeoPoint_mlo:country" (ID INTEGER NOT NULL, +"mlo:country" TEXT NOT NULL, "mlo:country:graph" INTEGER); +CREATE TABLE "mlo:GeoPoint_mlo:latitude" (ID INTEGER NOT NULL, +"mlo:latitude" REAL NOT NULL, "mlo:latitude:graph" INTEGER); +CREATE TABLE "mlo:GeoPoint_mlo:longitude" (ID INTEGER NOT NULL, +"mlo:longitude" REAL NOT NULL, "mlo:longitude:graph" INTEGER); +CREATE TABLE "mlo:GeoPoint_mlo:state" (ID INTEGER NOT NULL, +"mlo:state" TEXT NOT NULL, "mlo:state:graph" INTEGER); +CREATE TABLE "mlo:GeoPoint_mlo:timestamp" (ID INTEGER NOT NULL, +"mlo:timestamp" INTEGER NOT NULL, "mlo:timestamp:graph" INTEGER, +"mlo:timestamp:localDate" INTEGER NOT NULL, "mlo:timestamp:localTime" +INTEGER NOT NULL); +CREATE TABLE "mlo:GeoSphere" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mlo:GeoSphere_mlo:radius" (ID INTEGER NOT NULL, +"mlo:radius" REAL NOT NULL, "mlo:radius:graph" INTEGER); +CREATE TABLE "mlo:Landmark" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mlo:LandmarkCategory" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mlo:LandmarkCategory_mlo:isRemovable" (ID INTEGER NOT +NULL, "mlo:isRemovable" INTEGER NOT NULL, "mlo:isRemovable:graph" +INTEGER); +CREATE TABLE "mlo:Landmark_mlo:belongsToCategory" (ID INTEGER NOT +NULL, "mlo:belongsToCategory" INTEGER NOT NULL, +"mlo:belongsToCategory:graph" INTEGER); +CREATE TABLE "mlo:Landmark_mlo:poiLocation" (ID INTEGER NOT NULL, +"mlo:poiLocation" INTEGER NOT NULL, "mlo:poiLocation:graph" INTEGER); +CREATE TABLE "mlo:LocationBoundingBox" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mlo:LocationBoundingBox_mlo:boxEastLimit" (ID INTEGER +NOT NULL, "mlo:boxEastLimit" INTEGER NOT NULL, +"mlo:boxEastLimit:graph" INTEGER); +CREATE TABLE "mlo:LocationBoundingBox_mlo:boxNorthLimit" (ID INTEGER +NOT NULL, "mlo:boxNorthLimit" INTEGER NOT NULL, +"mlo:boxNorthLimit:graph" INTEGER); +CREATE TABLE "mlo:LocationBoundingBox_mlo:boxSouthWestCorner" (ID +INTEGER NOT NULL, "mlo:boxSouthWestCorner" INTEGER NOT NULL, +"mlo:boxSouthWestCorner:graph" INTEGER); +CREATE TABLE "mlo:LocationBoundingBox_mlo:boxVerticalLimit" (ID +INTEGER NOT NULL, "mlo:boxVerticalLimit" INTEGER NOT NULL, +"mlo:boxVerticalLimit:graph" INTEGER); +CREATE TABLE "mlo:PointOfInterest" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mlo:Route" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mlo:Route_mlo:endTime" (ID INTEGER NOT NULL, +"mlo:endTime" INTEGER NOT NULL, "mlo:endTime:graph" INTEGER, +"mlo:endTime:localDate" INTEGER NOT NULL, "mlo:endTime:localTime" +INTEGER NOT NULL); +CREATE TABLE "mlo:Route_mlo:routeDetails" (ID INTEGER NOT NULL, +"mlo:routeDetails" TEXT NOT NULL, "mlo:routeDetails:graph" INTEGER); +CREATE TABLE "mlo:Route_mlo:startTime" (ID INTEGER NOT NULL, +"mlo:startTime" INTEGER NOT NULL, "mlo:startTime:graph" INTEGER, +"mlo:startTime:localDate" INTEGER NOT NULL, "mlo:startTime:localTime" +INTEGER NOT NULL); +CREATE TABLE "mto:DownloadTransfer" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mto:State" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mto:SyncTransfer" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mto:Transfer" (ID INTEGER NOT NULL PRIMARY KEY, +"mto:transferState" INTEGER, "mto:transferState:graph" INTEGER, +"mto:method" INTEGER, "mto:method:graph" INTEGER, "mto:created" +INTEGER, "mto:created:graph" INTEGER, "mto:created:localDate" INTEGER, +"mto:created:localTime" INTEGER, "mto:account" TEXT COLLATE NOCASE, +"mto:account:graph" INTEGER, "mto:starter" INTEGER, +"mto:starter:graph" INTEGER, "mto:agent" INTEGER, "mto:agent:graph" +INTEGER); +CREATE TABLE "mto:TransferElement" (ID INTEGER NOT NULL PRIMARY KEY, +"mto:source" INTEGER, "mto:source:graph" INTEGER, "mto:destination" +INTEGER, "mto:destination:graph" INTEGER, "mto:startedTime" INTEGER, +"mto:startedTime:graph" INTEGER, "mto:startedTime:localDate" INTEGER, +"mto:startedTime:localTime" INTEGER, "mto:completedTime" INTEGER, +"mto:completedTime:graph" INTEGER, "mto:completedTime:localDate" +INTEGER, "mto:completedTime:localTime" INTEGER, "mto:state" INTEGER, +"mto:state:graph" INTEGER); +CREATE TABLE "mto:TransferMethod" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mto:Transfer_mto:transferList" (ID INTEGER NOT NULL, +"mto:transferList" INTEGER NOT NULL, "mto:transferList:graph" +INTEGER); +CREATE TABLE "mto:Transfer_mto:transferPrivacyLevel" (ID INTEGER NOT +NULL, "mto:transferPrivacyLevel" TEXT NOT NULL, +"mto:transferPrivacyLevel:graph" INTEGER); +CREATE TABLE "mto:UploadTransfer" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "mto:UploadTransfer_mto:transferCategory" (ID INTEGER NOT +NULL, "mto:transferCategory" TEXT NOT NULL, +"mto:transferCategory:graph" INTEGER); +CREATE TABLE "mtp:ScanType" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nao:Property" (ID INTEGER NOT NULL PRIMARY KEY, +"nao:propertyName" TEXT COLLATE NOCASE, "nao:propertyName:graph" +INTEGER, "nao:propertyValue" TEXT COLLATE NOCASE, +"nao:propertyValue:graph" INTEGER); +CREATE TABLE "nao:Tag" (ID INTEGER NOT NULL PRIMARY KEY, +"nao:prefLabel" TEXT COLLATE NOCASE, "nao:prefLabel:graph" INTEGER, +"nao:description" TEXT COLLATE NOCASE, "nao:description:graph" +INTEGER); +CREATE TABLE "nao:Tag_tracker:isDefaultTag" (ID INTEGER NOT NULL, +"tracker:isDefaultTag" INTEGER NOT NULL, "tracker:isDefaultTag:graph" +INTEGER); +CREATE TABLE "nao:Tag_tracker:tagRelatedTo" (ID INTEGER NOT NULL, +"tracker:tagRelatedTo" INTEGER NOT NULL, "tracker:tagRelatedTo:graph" +INTEGER); +CREATE TABLE "ncal:AccessClassification" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:Alarm" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:repeat" INTEGER, "ncal:repeat:graph" INTEGER); +CREATE TABLE "ncal:AlarmAction" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:Alarm_ncal:action" (ID INTEGER NOT NULL, +"ncal:action" INTEGER NOT NULL, "ncal:action:graph" INTEGER); +CREATE TABLE "ncal:Attachment" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:attachmentUri" INTEGER, "ncal:attachmentUri:graph" INTEGER, +"ncal:fmttype" TEXT COLLATE NOCASE, "ncal:fmttype:graph" INTEGER, +"ncal:encoding" INTEGER, "ncal:encoding:graph" INTEGER, +"ncal:attachmentContent" TEXT COLLATE NOCASE, +"ncal:attachmentContent:graph" INTEGER); +CREATE TABLE "ncal:AttachmentEncoding" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:Attendee" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:delegatedTo" INTEGER, "ncal:delegatedTo:graph" INTEGER, +"ncal:delegatedFrom" INTEGER, "ncal:delegatedFrom:graph" INTEGER, +"ncal:cutype" INTEGER, "ncal:cutype:graph" INTEGER, "ncal:member" +INTEGER, "ncal:member:graph" INTEGER, "ncal:role" INTEGER, +"ncal:role:graph" INTEGER, "ncal:rsvp" INTEGER, "ncal:rsvp:graph" +INTEGER, "ncal:partstat" INTEGER, "ncal:partstat:graph" INTEGER); +CREATE TABLE "ncal:AttendeeOrOrganizer" (ID INTEGER NOT NULL PRIMARY +KEY, "ncal:dir" INTEGER, "ncal:dir:graph" INTEGER, +"ncal:involvedContact" INTEGER, "ncal:involvedContact:graph" INTEGER, +"ncal:sentBy" INTEGER, "ncal:sentBy:graph" INTEGER); +CREATE TABLE "ncal:AttendeeRole" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:BydayRulePart" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:BydayRulePart_ncal:bydayModifier" (ID INTEGER NOT +NULL, "ncal:bydayModifier" INTEGER NOT NULL, +"ncal:bydayModifier:graph" INTEGER); +CREATE TABLE "ncal:BydayRulePart_ncal:bydayWeekday" (ID INTEGER NOT +NULL, "ncal:bydayWeekday" INTEGER NOT NULL, "ncal:bydayWeekday:graph" +INTEGER); +CREATE TABLE "ncal:Calendar" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:method" TEXT COLLATE NOCASE, "ncal:method:graph" INTEGER, +"ncal:calscale" INTEGER, "ncal:calscale:graph" INTEGER, "ncal:prodid" +TEXT COLLATE NOCASE, "ncal:prodid:graph" INTEGER, "ncal:version" TEXT +COLLATE NOCASE, "ncal:version:graph" INTEGER); +CREATE TABLE "ncal:CalendarDataObject" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:CalendarScale" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:CalendarUserType" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:Calendar_ncal:component" (ID INTEGER NOT NULL, +"ncal:component" INTEGER NOT NULL, "ncal:component:graph" INTEGER); +CREATE TABLE "ncal:Event" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:eventStatus" INTEGER, "ncal:eventStatus:graph" INTEGER, +"ncal:transp" INTEGER, "ncal:transp:graph" INTEGER); +CREATE TABLE "ncal:EventStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:Freebusy" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:FreebusyPeriod" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:fbtype" INTEGER, "ncal:fbtype:graph" INTEGER); +CREATE TABLE "ncal:FreebusyType" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:Freebusy_ncal:freebusy" (ID INTEGER NOT NULL, +"ncal:freebusy" INTEGER NOT NULL, "ncal:freebusy:graph" INTEGER); +CREATE TABLE "ncal:Journal" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:journalStatus" INTEGER, "ncal:journalStatus:graph" INTEGER); +CREATE TABLE "ncal:JournalStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:NcalDateTime" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:ncalTimezone" INTEGER, "ncal:ncalTimezone:graph" INTEGER, +"ncal:date" INTEGER, "ncal:date:graph" INTEGER, "ncal:date:localDate" +INTEGER, "ncal:date:localTime" INTEGER, "ncal:dateTime" INTEGER, +"ncal:dateTime:graph" INTEGER, "ncal:dateTime:localDate" INTEGER, +"ncal:dateTime:localTime" INTEGER); +CREATE TABLE "ncal:NcalPeriod" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:periodBegin" INTEGER, "ncal:periodBegin:graph" INTEGER, +"ncal:periodBegin:localDate" INTEGER, "ncal:periodBegin:localTime" +INTEGER, "ncal:periodDuration" INTEGER, "ncal:periodDuration:graph" +INTEGER, "ncal:periodEnd" INTEGER, "ncal:periodEnd:graph" INTEGER, +"ncal:periodEnd:localDate" INTEGER, "ncal:periodEnd:localTime" +INTEGER); +CREATE TABLE "ncal:NcalTimeEntity" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:Organizer" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:ParticipationStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:RecurrenceFrequency" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:RecurrenceIdentifier" (ID INTEGER NOT NULL PRIMARY +KEY, "ncal:range" INTEGER, "ncal:range:graph" INTEGER, +"ncal:recurrenceIdDateTime" INTEGER, "ncal:recurrenceIdDateTime:graph" +INTEGER); +CREATE TABLE "ncal:RecurrenceIdentifierRange" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:RecurrenceRule" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:until" INTEGER, "ncal:until:graph" INTEGER, +"ncal:until:localDate" INTEGER, "ncal:until:localTime" INTEGER, +"ncal:wkst" INTEGER, "ncal:wkst:graph" INTEGER, "ncal:interval" +INTEGER, "ncal:interval:graph" INTEGER, "ncal:count" INTEGER, +"ncal:count:graph" INTEGER, "ncal:freq" INTEGER, "ncal:freq:graph" +INTEGER); +CREATE TABLE "ncal:RecurrenceRule_ncal:byday" (ID INTEGER NOT NULL, +"ncal:byday" INTEGER NOT NULL, "ncal:byday:graph" INTEGER); +CREATE TABLE "ncal:RecurrenceRule_ncal:byhour" (ID INTEGER NOT NULL, +"ncal:byhour" INTEGER NOT NULL, "ncal:byhour:graph" INTEGER); +CREATE TABLE "ncal:RecurrenceRule_ncal:byminute" (ID INTEGER NOT NULL, +"ncal:byminute" INTEGER NOT NULL, "ncal:byminute:graph" INTEGER); +CREATE TABLE "ncal:RecurrenceRule_ncal:bymonth" (ID INTEGER NOT NULL, +"ncal:bymonth" INTEGER NOT NULL, "ncal:bymonth:graph" INTEGER); +CREATE TABLE "ncal:RecurrenceRule_ncal:bymonthday" (ID INTEGER NOT +NULL, "ncal:bymonthday" INTEGER NOT NULL, "ncal:bymonthday:graph" +INTEGER); +CREATE TABLE "ncal:RecurrenceRule_ncal:bysecond" (ID INTEGER NOT NULL, +"ncal:bysecond" INTEGER NOT NULL, "ncal:bysecond:graph" INTEGER); +CREATE TABLE "ncal:RecurrenceRule_ncal:bysetpos" (ID INTEGER NOT NULL, +"ncal:bysetpos" INTEGER NOT NULL, "ncal:bysetpos:graph" INTEGER); +CREATE TABLE "ncal:RecurrenceRule_ncal:byweekno" (ID INTEGER NOT NULL, +"ncal:byweekno" INTEGER NOT NULL, "ncal:byweekno:graph" INTEGER); +CREATE TABLE "ncal:RecurrenceRule_ncal:byyearday" (ID INTEGER NOT +NULL, "ncal:byyearday" INTEGER NOT NULL, "ncal:byyearday:graph" +INTEGER); +CREATE TABLE "ncal:RequestStatus" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:statusDescription" TEXT COLLATE NOCASE, +"ncal:statusDescription:graph" INTEGER, "ncal:returnStatus" TEXT +COLLATE NOCASE, "ncal:returnStatus:graph" INTEGER, +"ncal:requestStatusData" TEXT COLLATE NOCASE, +"ncal:requestStatusData:graph" INTEGER); +CREATE TABLE "ncal:TimeTransparency" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:Timezone" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:tzurl" INTEGER, "ncal:tzurl:graph" INTEGER, "ncal:standard" +INTEGER, "ncal:standard:graph" INTEGER, "ncal:daylight" INTEGER, +"ncal:daylight:graph" INTEGER, "ncal:tzid" TEXT COLLATE NOCASE, +"ncal:tzid:graph" INTEGER); +CREATE TABLE "ncal:TimezoneObservance" (ID INTEGER NOT NULL PRIMARY +KEY, "ncal:tzoffsetfrom" TEXT COLLATE NOCASE, +"ncal:tzoffsetfrom:graph" INTEGER, "ncal:tzoffsetto" TEXT COLLATE +NOCASE, "ncal:tzoffsetto:graph" INTEGER, "ncal:tzname" TEXT COLLATE +NOCASE, "ncal:tzname:graph" INTEGER); +CREATE TABLE "ncal:Todo" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:percentComplete" INTEGER, "ncal:percentComplete:graph" INTEGER, +"ncal:completed" INTEGER, "ncal:completed:graph" INTEGER, +"ncal:completed:localDate" INTEGER, "ncal:completed:localTime" +INTEGER, "ncal:todoStatus" INTEGER, "ncal:todoStatus:graph" INTEGER, +"ncal:due" INTEGER, "ncal:due:graph" INTEGER); +CREATE TABLE "ncal:TodoStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:Trigger" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:related" INTEGER, "ncal:related:graph" INTEGER, +"ncal:triggerDateTime" INTEGER, "ncal:triggerDateTime:graph" INTEGER, +"ncal:triggerDateTime:localDate" INTEGER, +"ncal:triggerDateTime:localTime" INTEGER, "ncal:triggerDuration" +INTEGER, "ncal:triggerDuration:graph" INTEGER); +CREATE TABLE "ncal:TriggerRelation" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "ncal:UnionParentClass" (ID INTEGER NOT NULL PRIMARY KEY, +"ncal:lastModified" INTEGER, "ncal:lastModified:graph" INTEGER, +"ncal:lastModified:localDate" INTEGER, "ncal:lastModified:localTime" +INTEGER, "ncal:trigger" INTEGER, "ncal:trigger:graph" INTEGER, +"ncal:created" INTEGER, "ncal:created:graph" INTEGER, +"ncal:created:localDate" INTEGER, "ncal:created:localTime" INTEGER, +"ncal:url" INTEGER, "ncal:url:graph" INTEGER, "ncal:comment" TEXT +COLLATE NOCASE, "ncal:comment:graph" INTEGER, "ncal:summaryAltRep" +INTEGER, "ncal:summaryAltRep:graph" INTEGER, "ncal:priority" INTEGER, +"ncal:priority:graph" INTEGER, "ncal:location" TEXT COLLATE NOCASE, +"ncal:location:graph" INTEGER, "ncal:uid" TEXT COLLATE NOCASE, +"ncal:uid:graph" INTEGER, "ncal:requestStatus" INTEGER, +"ncal:requestStatus:graph" INTEGER, "ncal:recurrenceId" INTEGER, +"ncal:recurrenceId:graph" INTEGER, "ncal:dtstamp" INTEGER, +"ncal:dtstamp:graph" INTEGER, "ncal:dtstamp:localDate" INTEGER, +"ncal:dtstamp:localTime" INTEGER, "ncal:class" INTEGER, +"ncal:class:graph" INTEGER, "ncal:organizer" INTEGER, +"ncal:organizer:graph" INTEGER, "ncal:dtend" INTEGER, +"ncal:dtend:graph" INTEGER, "ncal:summary" TEXT COLLATE NOCASE, +"ncal:summary:graph" INTEGER, "ncal:descriptionAltRep" INTEGER, +"ncal:descriptionAltRep:graph" INTEGER, "ncal:commentAltRep" INTEGER, +"ncal:commentAltRep:graph" INTEGER, "ncal:sequence" INTEGER, +"ncal:sequence:graph" INTEGER, "ncal:contact" TEXT COLLATE NOCASE, +"ncal:contact:graph" INTEGER, "ncal:contactAltRep" INTEGER, +"ncal:contactAltRep:graph" INTEGER, "ncal:locationAltRep" INTEGER, +"ncal:locationAltRep:graph" INTEGER, "ncal:geo" INTEGER, +"ncal:geo:graph" INTEGER, "ncal:resourcesAltRep" INTEGER, +"ncal:resourcesAltRep:graph" INTEGER, "ncal:dtstart" INTEGER, +"ncal:dtstart:graph" INTEGER, "ncal:description" TEXT COLLATE NOCASE, +"ncal:description:graph" INTEGER, "ncal:relatedToSibling" TEXT COLLATE +NOCASE, "ncal:relatedToSibling:graph" INTEGER, "ncal:duration" +INTEGER, "ncal:duration:graph" INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:attach" (ID INTEGER NOT NULL, +"ncal:attach" INTEGER NOT NULL, "ncal:attach:graph" INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:attendee" (ID INTEGER NOT +NULL, "ncal:attendee" INTEGER NOT NULL, "ncal:attendee:graph" +INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:categories" (ID INTEGER NOT +NULL, "ncal:categories" TEXT NOT NULL, "ncal:categories:graph" +INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:exdate" (ID INTEGER NOT NULL, +"ncal:exdate" INTEGER NOT NULL, "ncal:exdate:graph" INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:exrule" (ID INTEGER NOT NULL, +"ncal:exrule" INTEGER NOT NULL, "ncal:exrule:graph" INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:hasAlarm" (ID INTEGER NOT +NULL, "ncal:hasAlarm" INTEGER NOT NULL, "ncal:hasAlarm:graph" +INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:ncalRelation" (ID INTEGER NOT +NULL, "ncal:ncalRelation" TEXT NOT NULL, "ncal:ncalRelation:graph" +INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:rdate" (ID INTEGER NOT NULL, +"ncal:rdate" INTEGER NOT NULL, "ncal:rdate:graph" INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:relatedToChild" (ID INTEGER +NOT NULL, "ncal:relatedToChild" TEXT NOT NULL, +"ncal:relatedToChild:graph" INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:relatedToParent" (ID INTEGER +NOT NULL, "ncal:relatedToParent" TEXT NOT NULL, +"ncal:relatedToParent:graph" INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:resources" (ID INTEGER NOT +NULL, "ncal:resources" TEXT NOT NULL, "ncal:resources:graph" INTEGER); +CREATE TABLE "ncal:UnionParentClass_ncal:rrule" (ID INTEGER NOT NULL, +"ncal:rrule" INTEGER NOT NULL, "ncal:rrule:graph" INTEGER); +CREATE TABLE "ncal:Weekday" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:Affiliation" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:department" TEXT COLLATE NOCASE, "nco:department:graph" INTEGER, +"nco:org" INTEGER, "nco:org:graph" INTEGER, "nco:role" TEXT COLLATE +NOCASE, "nco:role:graph" INTEGER); +CREATE TABLE "nco:Affiliation_nco:title" (ID INTEGER NOT NULL, +"nco:title" TEXT NOT NULL, "nco:title:graph" INTEGER); +CREATE TABLE "nco:AuthorizationStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:BbsNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:CarPhoneNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:CellPhoneNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:Contact" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:fullname" TEXT COLLATE NOCASE, "nco:fullname:graph" INTEGER, +"nco:key" INTEGER, "nco:key:graph" INTEGER, "nco:contactUID" TEXT +COLLATE NOCASE, "nco:contactUID:graph" INTEGER, "nco:contactLocalUID" +TEXT COLLATE NOCASE, "nco:contactLocalUID:graph" INTEGER, +"nco:hasLocation" INTEGER, "nco:hasLocation:graph" INTEGER, +"nco:nickname" TEXT COLLATE NOCASE, "nco:nickname:graph" INTEGER, +"nco:representative" INTEGER, "nco:representative:graph" INTEGER, +"nco:photo" INTEGER, "nco:photo:graph" INTEGER, "nco:birthDate" +INTEGER, "nco:birthDate:graph" INTEGER, "nco:birthDate:localDate" +INTEGER, "nco:birthDate:localTime" INTEGER, "nco:sound" INTEGER, +"nco:sound:graph" INTEGER); +CREATE TABLE "nco:ContactGroup" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:contactGroupName" TEXT COLLATE NOCASE, +"nco:contactGroupName:graph" INTEGER); +CREATE TABLE "nco:ContactList" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:ContactListDataObject" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:ContactList_nco:containsContact" (ID INTEGER NOT +NULL, "nco:containsContact" INTEGER NOT NULL, +"nco:containsContact:graph" INTEGER); +CREATE TABLE "nco:ContactMedium" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:contactMediumComment" TEXT COLLATE NOCASE, +"nco:contactMediumComment:graph" INTEGER); +CREATE TABLE "nco:Contact_ncal:anniversary" (ID INTEGER NOT NULL, +"ncal:anniversary" INTEGER NOT NULL, "ncal:anniversary:graph" +INTEGER); +CREATE TABLE "nco:Contact_ncal:birthday" (ID INTEGER NOT NULL, +"ncal:birthday" INTEGER NOT NULL, "ncal:birthday:graph" INTEGER); +CREATE TABLE "nco:Contact_nco:belongsToGroup" (ID INTEGER NOT NULL, +"nco:belongsToGroup" INTEGER NOT NULL, "nco:belongsToGroup:graph" +INTEGER); +CREATE TABLE "nco:Contact_nco:note" (ID INTEGER NOT NULL, "nco:note" +TEXT NOT NULL, "nco:note:graph" INTEGER); +CREATE TABLE "nco:Contact_scal:anniversary" (ID INTEGER NOT NULL, +"scal:anniversary" INTEGER NOT NULL, "scal:anniversary:graph" +INTEGER); +CREATE TABLE "nco:Contact_scal:birthday" (ID INTEGER NOT NULL, +"scal:birthday" INTEGER NOT NULL, "scal:birthday:graph" INTEGER); +CREATE TABLE "nco:DomesticDeliveryAddress" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:EmailAddress" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:emailAddress" TEXT COLLATE NOCASE UNIQUE, +"nco:emailAddress:graph" INTEGER); +CREATE TABLE "nco:FaxNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:Gender" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:IMAccount" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:imAccountAddress" INTEGER UNIQUE, "nco:imAccountAddress:graph" +INTEGER, "nco:imAccountType" TEXT COLLATE NOCASE, +"nco:imAccountType:graph" INTEGER, "nco:imDisplayName" TEXT COLLATE +NOCASE, "nco:imDisplayName:graph" INTEGER, "nco:imEnabled" INTEGER, +"nco:imEnabled:graph" INTEGER); +CREATE TABLE "nco:IMAccount_nco:hasIMContact" (ID INTEGER NOT NULL, +"nco:hasIMContact" INTEGER NOT NULL, "nco:hasIMContact:graph" +INTEGER); +CREATE TABLE "nco:IMAddress" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:imID" TEXT COLLATE NOCASE, "nco:imID:graph" INTEGER, +"nco:imNickname" TEXT COLLATE NOCASE, "nco:imNickname:graph" INTEGER, +"nco:imAvatar" INTEGER, "nco:imAvatar:graph" INTEGER, "nco:imProtocol" +TEXT COLLATE NOCASE, "nco:imProtocol:graph" INTEGER, +"nco:imStatusMessage" TEXT COLLATE NOCASE, +"nco:imStatusMessage:graph" INTEGER, "nco:imPresence" INTEGER, +"nco:imPresence:graph" INTEGER, "nco:presenceLastModified" INTEGER, +"nco:presenceLastModified:graph" INTEGER, +"nco:presenceLastModified:localDate" INTEGER, +"nco:presenceLastModified:localTime" INTEGER, +"nco:imAddressAuthStatusFrom" INTEGER, +"nco:imAddressAuthStatusFrom:graph" INTEGER, +"nco:imAddressAuthStatusTo" INTEGER, "nco:imAddressAuthStatusTo:graph" +INTEGER); +CREATE TABLE "nco:IMAddress_nco:imCapability" (ID INTEGER NOT NULL, +"nco:imCapability" INTEGER NOT NULL, "nco:imCapability:graph" +INTEGER); +CREATE TABLE "nco:IMCapability" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:InternationalDeliveryAddress" (ID INTEGER NOT NULL +PRIMARY KEY); +CREATE TABLE "nco:IsdnNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:MessagingNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:ModemNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:OrganizationContact" (ID INTEGER NOT NULL PRIMARY +KEY, "nco:logo" INTEGER, "nco:logo:graph" INTEGER); +CREATE TABLE "nco:PagerNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:ParcelDeliveryAddress" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:PcsNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:PersonContact" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:nameFamily" TEXT COLLATE NOCASE, "nco:nameFamily:graph" INTEGER, +"nco:nameGiven" TEXT COLLATE NOCASE, "nco:nameGiven:graph" INTEGER, +"nco:nameAdditional" TEXT COLLATE NOCASE, "nco:nameAdditional:graph" +INTEGER, "nco:nameHonorificSuffix" TEXT COLLATE NOCASE, +"nco:nameHonorificSuffix:graph" INTEGER, "nco:nameHonorificPrefix" +TEXT COLLATE NOCASE, "nco:nameHonorificPrefix:graph" INTEGER, +"nco:hobby" TEXT COLLATE NOCASE, "nco:hobby:graph" INTEGER, +"nco:gender" INTEGER, "nco:gender:graph" INTEGER); +CREATE TABLE "nco:PersonContact_nco:hasAffiliation" (ID INTEGER NOT +NULL, "nco:hasAffiliation" INTEGER NOT NULL, +"nco:hasAffiliation:graph" INTEGER); +CREATE TABLE "nco:PhoneNumber" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:phoneNumber" TEXT COLLATE NOCASE, "nco:phoneNumber:graph" +INTEGER); +CREATE TABLE "nco:PostalAddress" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:region" TEXT COLLATE NOCASE, "nco:region:graph" INTEGER, +"nco:country" TEXT COLLATE NOCASE, "nco:country:graph" INTEGER, +"nco:extendedAddress" TEXT COLLATE NOCASE, +"nco:extendedAddress:graph" INTEGER, "nco:addressLocation" INTEGER, +"nco:addressLocation:graph" INTEGER, "nco:streetAddress" TEXT COLLATE +NOCASE, "nco:streetAddress:graph" INTEGER, "nco:postalcode" TEXT +COLLATE NOCASE, "nco:postalcode:graph" INTEGER, "nco:locality" TEXT +COLLATE NOCASE, "nco:locality:graph" INTEGER, "nco:county" TEXT +COLLATE NOCASE, "nco:county:graph" INTEGER, "nco:district" TEXT +COLLATE NOCASE, "nco:district:graph" INTEGER, "nco:pobox" TEXT +COLLATE NOCASE, "nco:pobox:graph" INTEGER); +CREATE TABLE "nco:PresenceStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:Role" (ID INTEGER NOT NULL PRIMARY KEY, "nco:video" +INTEGER, "nco:video:graph" INTEGER); +CREATE TABLE "nco:Role_nco:blogUrl" (ID INTEGER NOT NULL, +"nco:blogUrl" INTEGER NOT NULL, "nco:blogUrl:graph" INTEGER); +CREATE TABLE "nco:Role_nco:foafUrl" (ID INTEGER NOT NULL, +"nco:foafUrl" INTEGER NOT NULL, "nco:foafUrl:graph" INTEGER); +CREATE TABLE "nco:Role_nco:hasContactMedium" (ID INTEGER NOT NULL, +"nco:hasContactMedium" INTEGER NOT NULL, "nco:hasContactMedium:graph" +INTEGER); +CREATE TABLE "nco:Role_nco:hasEmailAddress" (ID INTEGER NOT NULL, +"nco:hasEmailAddress" INTEGER NOT NULL, "nco:hasEmailAddress:graph" +INTEGER); +CREATE TABLE "nco:Role_nco:hasIMAddress" (ID INTEGER NOT NULL, +"nco:hasIMAddress" INTEGER NOT NULL, "nco:hasIMAddress:graph" +INTEGER); +CREATE TABLE "nco:Role_nco:hasPhoneNumber" (ID INTEGER NOT NULL, +"nco:hasPhoneNumber" INTEGER NOT NULL, "nco:hasPhoneNumber:graph" +INTEGER); +CREATE TABLE "nco:Role_nco:hasPostalAddress" (ID INTEGER NOT NULL, +"nco:hasPostalAddress" INTEGER NOT NULL, "nco:hasPostalAddress:graph" +INTEGER); +CREATE TABLE "nco:Role_nco:url" (ID INTEGER NOT NULL, "nco:url" +INTEGER NOT NULL, "nco:url:graph" INTEGER); +CREATE TABLE "nco:Role_nco:websiteUrl" (ID INTEGER NOT NULL, +"nco:websiteUrl" INTEGER NOT NULL, "nco:websiteUrl:graph" INTEGER); +CREATE TABLE "nco:VideoTelephoneNumber" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nco:VoicePhoneNumber" (ID INTEGER NOT NULL PRIMARY KEY, +"nco:voiceMail" INTEGER, "nco:voiceMail:graph" INTEGER); +CREATE TABLE "nfo:Application" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Archive" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:uncompressedSize" INTEGER, "nfo:uncompressedSize:graph" INTEGER); +CREATE TABLE "nfo:ArchiveItem" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:isPasswordProtected" INTEGER, "nfo:isPasswordProtected:graph" +INTEGER); +CREATE TABLE "nfo:Attachment" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Audio" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:channels" INTEGER, "nfo:channels:graph" INTEGER, +"nfo:sideChannels" INTEGER, "nfo:sideChannels:graph" INTEGER, +"nfo:lfeChannels" INTEGER, "nfo:lfeChannels:graph" INTEGER, +"nfo:sampleCount" INTEGER, "nfo:sampleCount:graph" INTEGER, +"nfo:bitsPerSample" INTEGER, "nfo:bitsPerSample:graph" INTEGER, +"nfo:frontChannels" INTEGER, "nfo:frontChannels:graph" INTEGER, +"nfo:sampleRate" REAL, "nfo:sampleRate:graph" INTEGER, +"nfo:averageAudioBitrate" REAL, "nfo:averageAudioBitrate:graph" +INTEGER, "nfo:rearChannels" INTEGER, "nfo:rearChannels:graph" INTEGER, +"nfo:gain" INTEGER, "nfo:gain:graph" INTEGER, "nfo:peakGain" INTEGER, +"nfo:peakGain:graph" INTEGER, "nfo:audioOffset" REAL, +"nfo:audioOffset:graph" INTEGER); +CREATE TABLE "nfo:Bookmark" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:bookmarks" INTEGER, "nfo:bookmarks:graph" INTEGER, +"nfo:characterPosition" INTEGER, "nfo:characterPosition:graph" +INTEGER, "nfo:pageNumber" INTEGER, "nfo:pageNumber:graph" INTEGER, +"nfo:streamPosition" INTEGER, "nfo:streamPosition:graph" INTEGER, +"nfo:streamDuration" INTEGER, "nfo:streamDuration:graph" INTEGER); +CREATE TABLE "nfo:BookmarkFolder" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:BookmarkFolder_nfo:containsBookmark" (ID INTEGER NOT +NULL, "nfo:containsBookmark" INTEGER NOT NULL, +"nfo:containsBookmark:graph" INTEGER); +CREATE TABLE "nfo:BookmarkFolder_nfo:containsBookmarkFolder" (ID +INTEGER NOT NULL, "nfo:containsBookmarkFolder" INTEGER NOT NULL, +"nfo:containsBookmarkFolder:graph" INTEGER); +CREATE TABLE "nfo:CompressionType" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Cursor" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:DataContainer" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:DeletedResource" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:originalLocation" TEXT COLLATE NOCASE, +"nfo:originalLocation:graph" INTEGER, "nfo:deletionDate" INTEGER, +"nfo:deletionDate:graph" INTEGER, "nfo:deletionDate:localDate" +INTEGER, "nfo:deletionDate:localTime" INTEGER); +CREATE TABLE "nfo:Document" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:tableOfContents" TEXT COLLATE NOCASE, +"nfo:tableOfContents:graph" INTEGER); +CREATE TABLE "nfo:EmbeddedFileDataObject" (ID INTEGER NOT NULL PRIMARY +KEY, "nfo:encoding" TEXT COLLATE NOCASE, "nfo:encoding:graph" +INTEGER); +CREATE TABLE "nfo:Equipment" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:manufacturer" TEXT COLLATE NOCASE, "nfo:manufacturer:graph" +INTEGER, "nfo:model" TEXT COLLATE NOCASE, "nfo:model:graph" INTEGER, +"nfo:equipmentSoftware" TEXT COLLATE NOCASE, +"nfo:equipmentSoftware:graph" INTEGER); +CREATE TABLE "nfo:Executable" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:FileDataObject" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:fileLastAccessed" INTEGER, "nfo:fileLastAccessed:graph" INTEGER, +"nfo:fileLastAccessed:localDate" INTEGER, +"nfo:fileLastAccessed:localTime" INTEGER, "nfo:fileCreated" INTEGER, +"nfo:fileCreated:graph" INTEGER, "nfo:fileCreated:localDate" INTEGER, +"nfo:fileCreated:localTime" INTEGER, "nfo:fileSize" INTEGER, +"nfo:fileSize:graph" INTEGER, "nfo:permissions" TEXT COLLATE NOCASE, +"nfo:permissions:graph" INTEGER, "nfo:fileName" TEXT COLLATE NOCASE, +"nfo:fileName:graph" INTEGER, "nfo:hasHash" INTEGER, +"nfo:hasHash:graph" INTEGER, "nfo:fileOwner" INTEGER, +"nfo:fileOwner:graph" INTEGER, "nfo:fileLastModified" INTEGER, +"nfo:fileLastModified:graph" INTEGER, "nfo:fileLastModified:localDate" +INTEGER, "nfo:fileLastModified:localTime" INTEGER); +CREATE TABLE "nfo:FileHash" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:hashValue" TEXT COLLATE NOCASE, "nfo:hashValue:graph" INTEGER, +"nfo:hashAlgorithm" TEXT COLLATE NOCASE, "nfo:hashAlgorithm:graph" +INTEGER); +CREATE TABLE "nfo:Filesystem" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:FilesystemImage" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Folder" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Font" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:fontFamily" TEXT COLLATE NOCASE, "nfo:fontFamily:graph" INTEGER, +"nfo:foundry" INTEGER, "nfo:foundry:graph" INTEGER); +CREATE TABLE "nfo:HardDiskPartition" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:HelpDocument" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:HtmlDocument" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Icon" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Image" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:verticalResolution" INTEGER, "nfo:verticalResolution:graph" +INTEGER, "nfo:horizontalResolution" INTEGER, +"nfo:horizontalResolution:graph" INTEGER, "nfo:orientation" INTEGER, +"nfo:orientation:graph" INTEGER); +CREATE TABLE "nfo:Image_nfo:depicts" (ID INTEGER NOT NULL, +"nfo:depicts" INTEGER NOT NULL, "nfo:depicts:graph" INTEGER); +CREATE TABLE "nfo:Image_nfo:hasRegionOfInterest" (ID INTEGER NOT NULL, +"nfo:hasRegionOfInterest" INTEGER NOT NULL, +"nfo:hasRegionOfInterest:graph" INTEGER); +CREATE TABLE "nfo:Media" (ID INTEGER NOT NULL PRIMARY KEY, "nfo:count" +INTEGER, "nfo:count:graph" INTEGER, "nfo:duration" INTEGER, +"nfo:duration:graph" INTEGER, "nfo:compressionType" INTEGER, +"nfo:compressionType:graph" INTEGER, "nfo:hasMediaStream" INTEGER, +"nfo:hasMediaStream:graph" INTEGER, "nfo:bitDepth" INTEGER, +"nfo:bitDepth:graph" INTEGER, "nfo:codec" TEXT COLLATE NOCASE, +"nfo:codec:graph" INTEGER, "nfo:encodedBy" TEXT COLLATE NOCASE, +"nfo:encodedBy:graph" INTEGER, "nfo:bitrateType" TEXT COLLATE NOCASE, +"nfo:bitrateType:graph" INTEGER, "nfo:averageBitrate" REAL, +"nfo:averageBitrate:graph" INTEGER, "nfo:genre" TEXT COLLATE NOCASE, +"nfo:genre:graph" INTEGER, "nfo:equipment" INTEGER, +"nfo:equipment:graph" INTEGER, "nfo:lastPlayedPosition" INTEGER, +"nfo:lastPlayedPosition:graph" INTEGER, "nmm:genre" TEXT COLLATE +NOCASE, "nmm:genre:graph" INTEGER, "nmm:skipCounter" INTEGER, +"nmm:skipCounter:graph" INTEGER, "nmm:dlnaProfile" TEXT COLLATE +NOCASE, "nmm:dlnaProfile:graph" INTEGER, "nmm:dlnaMime" TEXT COLLATE +NOCASE, "nmm:dlnaMime:graph" INTEGER, "nmm:uPnPShared" INTEGER, +"nmm:uPnPShared:graph" INTEGER, "mtp:credits" TEXT COLLATE NOCASE, +"mtp:credits:graph" INTEGER, "mtp:creator" TEXT COLLATE NOCASE, +"mtp:creator:graph" INTEGER); +CREATE TABLE "nfo:MediaFileListEntry" (ID INTEGER NOT NULL PRIMARY +KEY, "nfo:listPosition" REAL, "nfo:listPosition:graph" INTEGER, +"nfo:entryUrl" TEXT COLLATE NOCASE, "nfo:entryUrl:graph" INTEGER); +CREATE TABLE "nfo:MediaList" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:entryCounter" INTEGER, "nfo:entryCounter:graph" INTEGER, +"nfo:listDuration" INTEGER, "nfo:listDuration:graph" INTEGER); +CREATE TABLE "nfo:MediaList_nfo:hasMediaFileListEntry" (ID INTEGER NOT +NULL, "nfo:hasMediaFileListEntry" INTEGER NOT NULL, +"nfo:hasMediaFileListEntry:graph" INTEGER); +CREATE TABLE "nfo:MediaList_nfo:mediaListEntry" (ID INTEGER NOT NULL, +"nfo:mediaListEntry" INTEGER NOT NULL, "nfo:mediaListEntry:graph" +INTEGER); +CREATE TABLE "nfo:MediaStream" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Media_mtp:hidden" (ID INTEGER NOT NULL, "mtp:hidden" +INTEGER NOT NULL, "mtp:hidden:graph" INTEGER); +CREATE TABLE "nfo:Media_nmm:alternativeMedia" (ID INTEGER NOT NULL, +"nmm:alternativeMedia" INTEGER NOT NULL, "nmm:alternativeMedia:graph" +INTEGER); +CREATE TABLE "nfo:MindMap" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Note" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:OperatingSystem" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Orientation" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:PaginatedTextDocument" (ID INTEGER NOT NULL PRIMARY +KEY, "nfo:pageCount" INTEGER, "nfo:pageCount:graph" INTEGER); +CREATE TABLE "nfo:PlainTextDocument" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Presentation" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:RasterImage" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:RegionOfInterest" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:regionOfInterestX" REAL, "nfo:regionOfInterestX:graph" INTEGER, +"nfo:regionOfInterestY" REAL, "nfo:regionOfInterestY:graph" INTEGER, +"nfo:regionOfInterestWidth" REAL, "nfo:regionOfInterestWidth:graph" +INTEGER, "nfo:regionOfInterestHeight" REAL, +"nfo:regionOfInterestHeight:graph" INTEGER, "nfo:regionOfInterestType" +INTEGER, "nfo:regionOfInterestType:graph" INTEGER, "nfo:roiRefersTo" +INTEGER, "nfo:roiRefersTo:graph" INTEGER); +CREATE TABLE "nfo:RegionOfInterestContent" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:RemoteDataObject" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:RemotePortAddress" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Software" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:conflicts" INTEGER, "nfo:conflicts:graph" INTEGER, +"nfo:supercedes" INTEGER, "nfo:supercedes:graph" INTEGER, +"nfo:softwareIcon" INTEGER, "nfo:softwareIcon:graph" INTEGER, +"nfo:softwareCmdLine" TEXT COLLATE NOCASE, +"nfo:softwareCmdLine:graph" INTEGER); +CREATE TABLE "nfo:SoftwareApplication" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:SoftwareCategory" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:softwareCategoryIcon" INTEGER, "nfo:softwareCategoryIcon:graph" +INTEGER); +CREATE TABLE "nfo:SoftwareItem" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:SoftwareService" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:SourceCode" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:commentCharacterCount" INTEGER, "nfo:commentCharacterCount:graph" +INTEGER, "nfo:programmingLanguage" TEXT COLLATE NOCASE, +"nfo:programmingLanguage:graph" INTEGER, "nfo:definesClass" TEXT +COLLATE NOCASE, "nfo:definesClass:graph" INTEGER, +"nfo:definesFunction" TEXT COLLATE NOCASE, +"nfo:definesFunction:graph" INTEGER, "nfo:definesGlobalVariable" TEXT +COLLATE NOCASE, "nfo:definesGlobalVariable:graph" INTEGER); +CREATE TABLE "nfo:Spreadsheet" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:TextDocument" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:wordCount" INTEGER, "nfo:wordCount:graph" INTEGER, +"nfo:lineCount" INTEGER, "nfo:lineCount:graph" INTEGER, +"nfo:characterCount" INTEGER, "nfo:characterCount:graph" INTEGER); +CREATE TABLE "nfo:Trash" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:VectorImage" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nfo:Video" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:frameRate" REAL, "nfo:frameRate:graph" INTEGER, "nfo:frameCount" +INTEGER, "nfo:frameCount:graph" INTEGER, "nfo:averageVideoBitrate" +REAL, "nfo:averageVideoBitrate:graph" INTEGER); +CREATE TABLE "nfo:Visual" (ID INTEGER NOT NULL PRIMARY KEY, +"nie:contentCreated" INTEGER, "nie:contentCreated:graph" INTEGER, +"nie:contentCreated:localDate" INTEGER, "nie:contentCreated:localTime" +INTEGER, "nfo:aspectRatio" REAL, "nfo:aspectRatio:graph" INTEGER, +"nfo:heading" REAL, "nfo:heading:graph" INTEGER, "nfo:tilt" REAL, +"nfo:tilt:graph" INTEGER, "nfo:interlaceMode" INTEGER, +"nfo:interlaceMode:graph" INTEGER, "nfo:height" INTEGER, +"nfo:height:graph" INTEGER, "nfo:width" INTEGER, "nfo:width:graph" +INTEGER, "nfo:colorDepth" INTEGER, "nfo:colorDepth:graph" INTEGER); +CREATE TABLE "nfo:WebHistory" (ID INTEGER NOT NULL PRIMARY KEY, +"nfo:domain" TEXT COLLATE NOCASE, "nfo:domain:graph" INTEGER, +"nfo:uri" TEXT COLLATE NOCASE, "nfo:uri:graph" INTEGER); +CREATE TABLE "nfo:Website" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nid3:ID3Audio" (ID INTEGER NOT NULL PRIMARY KEY, +"nid3:title" TEXT COLLATE NOCASE, "nid3:title:graph" INTEGER, +"nid3:albumTitle" TEXT COLLATE NOCASE, "nid3:albumTitle:graph" +INTEGER, "nid3:contentType" TEXT COLLATE NOCASE, +"nid3:contentType:graph" INTEGER, "nid3:length" INTEGER, +"nid3:length:graph" INTEGER, "nid3:recordingYear" INTEGER, +"nid3:recordingYear:graph" INTEGER, "nid3:trackNumber" TEXT COLLATE +NOCASE, "nid3:trackNumber:graph" INTEGER, "nid3:partOfSet" TEXT +COLLATE NOCASE, "nid3:partOfSet:graph" INTEGER, "nid3:comments" TEXT +COLLATE NOCASE, "nid3:comments:graph" INTEGER); +CREATE TABLE "nid3:ID3Audio_nid3:leadArtist" (ID INTEGER NOT NULL, +"nid3:leadArtist" INTEGER NOT NULL, "nid3:leadArtist:graph" INTEGER); +CREATE TABLE "nie:DataObject" (ID INTEGER NOT NULL PRIMARY KEY, +"nie:url" TEXT COLLATE NOCASE UNIQUE, "nie:url:graph" INTEGER, +"nie:byteSize" INTEGER, "nie:byteSize:graph" INTEGER, +"nie:interpretedAs" INTEGER, "nie:interpretedAs:graph" INTEGER, +"nie:lastRefreshed" INTEGER, "nie:lastRefreshed:graph" INTEGER, +"nie:lastRefreshed:localDate" INTEGER, "nie:lastRefreshed:localTime" +INTEGER, "nie:created" INTEGER, "nie:created:graph" INTEGER, +"nie:created:localDate" INTEGER, "nie:created:localTime" INTEGER, +"nfo:belongsToContainer" INTEGER, "nfo:belongsToContainer:graph" +INTEGER, "tracker:available" INTEGER, "tracker:available:graph" +INTEGER); +CREATE TABLE "nie:DataObject_nie:dataSource" (ID INTEGER NOT NULL, +"nie:dataSource" INTEGER NOT NULL, "nie:dataSource:graph" INTEGER); +CREATE TABLE "nie:DataObject_nie:isPartOf" (ID INTEGER NOT NULL, +"nie:isPartOf" INTEGER NOT NULL, "nie:isPartOf:graph" INTEGER); +CREATE TABLE "nie:DataSource" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nie:InformationElement" (ID INTEGER NOT NULL PRIMARY +KEY, "nie:title" TEXT COLLATE NOCASE, "nie:title:graph" INTEGER, +"nie:contentLastModified" INTEGER, "nie:contentLastModified:graph" +INTEGER, "nie:contentLastModified:localDate" INTEGER, +"nie:contentLastModified:localTime" INTEGER, "nie:subject" TEXT +COLLATE NOCASE, "nie:subject:graph" INTEGER, "nie:mimeType" TEXT +COLLATE NOCASE, "nie:mimeType:graph" INTEGER, "nie:language" TEXT +COLLATE NOCASE, "nie:language:graph" INTEGER, "nie:plainTextContent" +TEXT COLLATE NOCASE, "nie:plainTextContent:graph" INTEGER, +"nie:legal" TEXT COLLATE NOCASE, "nie:legal:graph" INTEGER, +"nie:generator" TEXT COLLATE NOCASE, "nie:generator:graph" INTEGER, +"nie:description" TEXT COLLATE NOCASE, "nie:description:graph" +INTEGER, "nie:disclaimer" TEXT COLLATE NOCASE, "nie:disclaimer:graph" +INTEGER, "nie:depends" INTEGER, "nie:depends:graph" INTEGER, +"nie:links" INTEGER, "nie:links:graph" INTEGER, "nie:copyright" TEXT +COLLATE NOCASE, "nie:copyright:graph" INTEGER, "nie:comment" TEXT +COLLATE NOCASE, "nie:comment:graph" INTEGER, "nie:isStoredAs" +INTEGER, "nie:isStoredAs:graph" INTEGER, "nie:version" TEXT COLLATE +NOCASE, "nie:version:graph" INTEGER, "nie:contentCreated" INTEGER, +"nie:contentCreated:graph" INTEGER, "nie:contentCreated:localDate" +INTEGER, "nie:contentCreated:localTime" INTEGER, "nie:contentAccessed" +INTEGER, "nie:contentAccessed:graph" INTEGER, +"nie:contentAccessed:localDate" INTEGER, +"nie:contentAccessed:localTime" INTEGER, "nie:license" TEXT COLLATE +NOCASE, "nie:license:graph" INTEGER, "nie:identifier" TEXT COLLATE +NOCASE, "nie:identifier:graph" INTEGER, "nie:licenseType" TEXT +COLLATE NOCASE, "nie:licenseType:graph" INTEGER, "nie:characterSet" +TEXT COLLATE NOCASE, "nie:characterSet:graph" INTEGER, +"nie:contentSize" INTEGER, "nie:contentSize:graph" INTEGER, +"nie:rootElementOf" INTEGER, "nie:rootElementOf:graph" INTEGER, +"nie:usageCounter" INTEGER, "nie:usageCounter:graph" INTEGER, +"nco:publisher" INTEGER, "nco:publisher:graph" INTEGER, +"nfo:isContentEncrypted" INTEGER, "nfo:isContentEncrypted:graph" +INTEGER, "slo:location" INTEGER, "slo:location:graph" INTEGER, +"nfo:isBootable" INTEGER, "nfo:isBootable:graph" INTEGER, "osinfo:id" +TEXT COLLATE NOCASE, "osinfo:id:graph" INTEGER, "osinfo:mediaId" TEXT +COLLATE NOCASE, "osinfo:mediaId:graph" INTEGER); +CREATE TABLE "nie:InformationElement_mlo:location" (ID INTEGER NOT +NULL, "mlo:location" INTEGER NOT NULL, "mlo:location:graph" INTEGER); +CREATE TABLE "nie:InformationElement_nao:hasProperty" (ID INTEGER NOT +NULL, "nao:hasProperty" INTEGER NOT NULL, "nao:hasProperty:graph" +INTEGER); +CREATE TABLE "nie:InformationElement_nco:contributor" (ID INTEGER NOT +NULL, "nco:contributor" INTEGER NOT NULL, "nco:contributor:graph" +INTEGER); +CREATE TABLE "nie:InformationElement_nco:creator" (ID INTEGER NOT +NULL, "nco:creator" INTEGER NOT NULL, "nco:creator:graph" INTEGER); +CREATE TABLE "nie:InformationElement_nie:hasLogicalPart" (ID INTEGER +NOT NULL, "nie:hasLogicalPart" INTEGER NOT NULL, +"nie:hasLogicalPart:graph" INTEGER); +CREATE TABLE "nie:InformationElement_nie:hasPart" (ID INTEGER NOT +NULL, "nie:hasPart" INTEGER NOT NULL, "nie:hasPart:graph" INTEGER); +CREATE TABLE "nie:InformationElement_nie:informationElementDate" (ID +INTEGER NOT NULL, "nie:informationElementDate" INTEGER NOT NULL, +"nie:informationElementDate:graph" INTEGER, +"nie:informationElementDate:localDate" INTEGER NOT NULL, +"nie:informationElementDate:localTime" INTEGER NOT NULL); +CREATE TABLE "nie:InformationElement_nie:isLogicalPartOf" (ID INTEGER +NOT NULL, "nie:isLogicalPartOf" INTEGER NOT NULL, +"nie:isLogicalPartOf:graph" INTEGER); +CREATE TABLE "nie:InformationElement_nie:keyword" (ID INTEGER NOT +NULL, "nie:keyword" TEXT NOT NULL, "nie:keyword:graph" INTEGER); +CREATE TABLE "nie:InformationElement_nie:relatedTo" (ID INTEGER NOT +NULL, "nie:relatedTo" INTEGER NOT NULL, "nie:relatedTo:graph" +INTEGER); +CREATE TABLE "nmm:AnalogRadio" (ID INTEGER NOT NULL PRIMARY KEY, +"nmm:modulation" INTEGER, "nmm:modulation:graph" INTEGER, +"nmm:frequency" INTEGER, "nmm:frequency:graph" INTEGER); +CREATE TABLE "nmm:Artist" (ID INTEGER NOT NULL PRIMARY KEY, +"nmm:artistName" TEXT COLLATE NOCASE, "nmm:artistName:graph" +INTEGER); +CREATE TABLE "nmm:DigitalRadio" (ID INTEGER NOT NULL PRIMARY KEY, +"nmm:streamingBitrate" INTEGER, "nmm:streamingBitrate:graph" INTEGER, +"nmm:encoding" TEXT COLLATE NOCASE, "nmm:encoding:graph" INTEGER, +"nmm:protocol" TEXT COLLATE NOCASE, "nmm:protocol:graph" INTEGER); +CREATE TABLE "nmm:Flash" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmm:ImageList" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmm:MeteringMode" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmm:MusicAlbum" (ID INTEGER NOT NULL PRIMARY KEY, +"nie:title" TEXT COLLATE NOCASE, "nie:title:graph" INTEGER, +"nmm:albumTrackCount" INTEGER, "nmm:albumTrackCount:graph" INTEGER, +"nmm:albumTitle" TEXT COLLATE NOCASE, "nmm:albumTitle:graph" INTEGER, +"nmm:albumDuration" INTEGER, "nmm:albumDuration:graph" INTEGER, +"nmm:albumGain" INTEGER, "nmm:albumGain:graph" INTEGER, +"nmm:albumPeakGain" INTEGER, "nmm:albumPeakGain:graph" INTEGER); +CREATE TABLE "nmm:MusicAlbumDisc" (ID INTEGER NOT NULL PRIMARY KEY, +"nmm:albumDiscAlbum" INTEGER, "nmm:albumDiscAlbum:graph" INTEGER, +"nmm:musicCDIdentifier" TEXT COLLATE NOCASE, +"nmm:musicCDIdentifier:graph" INTEGER, "nmm:setNumber" INTEGER, +"nmm:setNumber:graph" INTEGER); +CREATE TABLE "nmm:MusicAlbum_nmm:albumArtist" (ID INTEGER NOT NULL, +"nmm:albumArtist" INTEGER NOT NULL, "nmm:albumArtist:graph" INTEGER); +CREATE TABLE "nmm:MusicPiece" (ID INTEGER NOT NULL PRIMARY KEY, +"nie:title" TEXT COLLATE NOCASE, "nie:title:graph" INTEGER, +"nmm:musicAlbum" INTEGER, "nmm:musicAlbum:graph" INTEGER, +"nmm:musicAlbumDisc" INTEGER, "nmm:musicAlbumDisc:graph" INTEGER, +"nmm:beatsPerMinute" INTEGER, "nmm:beatsPerMinute:graph" INTEGER, +"nmm:performer" INTEGER, "nmm:performer:graph" INTEGER, "nmm:composer" +INTEGER, "nmm:composer:graph" INTEGER, "nmm:lyricist" INTEGER, +"nmm:lyricist:graph" INTEGER, "nmm:trackNumber" INTEGER, +"nmm:trackNumber:graph" INTEGER, +"nmm:internationalStandardRecordingCode" TEXT COLLATE NOCASE, +"nmm:internationalStandardRecordingCode:graph" INTEGER); +CREATE TABLE "nmm:MusicPiece_nmm:lyrics" (ID INTEGER NOT NULL, +"nmm:lyrics" INTEGER NOT NULL, "nmm:lyrics:graph" INTEGER); +CREATE TABLE "nmm:Photo" (ID INTEGER NOT NULL PRIMARY KEY, +"nmm:exposureTime" REAL, "nmm:exposureTime:graph" INTEGER, "nmm:flash" +INTEGER, "nmm:flash:graph" INTEGER, "nmm:fnumber" REAL, +"nmm:fnumber:graph" INTEGER, "nmm:focalLength" REAL, +"nmm:focalLength:graph" INTEGER, "nmm:isoSpeed" REAL, +"nmm:isoSpeed:graph" INTEGER, "nmm:meteringMode" INTEGER, +"nmm:meteringMode:graph" INTEGER, "nmm:whiteBalance" INTEGER, +"nmm:whiteBalance:graph" INTEGER, "nmm:isCropped" INTEGER, +"nmm:isCropped:graph" INTEGER, "nmm:isColorCorrected" INTEGER, +"nmm:isColorCorrected:graph" INTEGER); +CREATE TABLE "nmm:Playlist" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmm:RadioModulation" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmm:RadioStation" (ID INTEGER NOT NULL PRIMARY KEY, +"nmm:radioIcon" INTEGER, "nmm:radioIcon:graph" INTEGER, "nmm:radioPTY" +INTEGER, "nmm:radioPTY:graph" INTEGER); +CREATE TABLE "nmm:RadioStation_nmm:carrier" (ID INTEGER NOT NULL, +"nmm:carrier" INTEGER NOT NULL, "nmm:carrier:graph" INTEGER); +CREATE TABLE "nmm:SynchronizedText" (ID INTEGER NOT NULL PRIMARY KEY, +"nmm:isForHearingImpaired" INTEGER, "nmm:isForHearingImpaired:graph" +INTEGER); +CREATE TABLE "nmm:Video" (ID INTEGER NOT NULL PRIMARY KEY, +"nmm:videoAlbum" INTEGER, "nmm:videoAlbum:graph" INTEGER, +"nmm:isSeries" INTEGER, "nmm:isSeries:graph" INTEGER, "nmm:season" +INTEGER, "nmm:season:graph" INTEGER, "nmm:episodeNumber" INTEGER, +"nmm:episodeNumber:graph" INTEGER, "nmm:runTime" INTEGER, +"nmm:runTime:graph" INTEGER, "nmm:synopsis" TEXT COLLATE NOCASE, +"nmm:synopsis:graph" INTEGER, "nmm:MPAARating" TEXT COLLATE NOCASE, +"nmm:MPAARating:graph" INTEGER, "nmm:category" TEXT COLLATE NOCASE, +"nmm:category:graph" INTEGER, "nmm:producedBy" INTEGER, +"nmm:producedBy:graph" INTEGER, "nmm:hasSubtitle" INTEGER, +"nmm:hasSubtitle:graph" INTEGER, "nmm:isContentEncrypted" INTEGER, +"nmm:isContentEncrypted:graph" INTEGER, "mtp:fourCC" TEXT COLLATE +NOCASE, "mtp:fourCC:graph" INTEGER, "mtp:waveformat" TEXT COLLATE +NOCASE, "mtp:waveformat:graph" INTEGER); +CREATE TABLE "nmm:Video_mtp:scantype" (ID INTEGER NOT NULL, +"mtp:scantype" INTEGER NOT NULL, "mtp:scantype:graph" INTEGER); +CREATE TABLE "nmm:Video_nmm:director" (ID INTEGER NOT NULL, +"nmm:director" INTEGER NOT NULL, "nmm:director:graph" INTEGER); +CREATE TABLE "nmm:Video_nmm:leadActor" (ID INTEGER NOT NULL, +"nmm:leadActor" INTEGER NOT NULL, "nmm:leadActor:graph" INTEGER); +CREATE TABLE "nmm:Video_nmm:subtitle" (ID INTEGER NOT NULL, +"nmm:subtitle" INTEGER NOT NULL, "nmm:subtitle:graph" INTEGER); +CREATE TABLE "nmm:WhiteBalance" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:Attachment" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:Call" (ID INTEGER NOT NULL PRIMARY KEY, +"nmo:sentDate" INTEGER, "nmo:sentDate:graph" INTEGER, +"nmo:sentDate:localDate" INTEGER, "nmo:sentDate:localTime" INTEGER, +"nmo:duration" INTEGER, "nmo:duration:graph" INTEGER); +CREATE TABLE "nmo:CommunicationChannel" (ID INTEGER NOT NULL PRIMARY +KEY, "nmo:lastMessageDate" INTEGER, "nmo:lastMessageDate:graph" +INTEGER, "nmo:lastMessageDate:localDate" INTEGER, +"nmo:lastMessageDate:localTime" INTEGER, +"nmo:lastSuccessfulMessageDate" INTEGER, +"nmo:lastSuccessfulMessageDate:graph" INTEGER, +"nmo:lastSuccessfulMessageDate:localDate" INTEGER, +"nmo:lastSuccessfulMessageDate:localTime" INTEGER); +CREATE TABLE "nmo:CommunicationChannel_nmo:hasParticipant" (ID INTEGER +NOT NULL, "nmo:hasParticipant" INTEGER NOT NULL, +"nmo:hasParticipant:graph" INTEGER); +CREATE TABLE "nmo:Conversation" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:DeliveryStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:Email" (ID INTEGER NOT NULL PRIMARY KEY, +"nmo:hasContent" INTEGER, "nmo:hasContent:graph" INTEGER, +"nmo:isFlagged" INTEGER, "nmo:isFlagged:graph" INTEGER, "nmo:isRecent" +INTEGER, "nmo:isRecent:graph" INTEGER, "nmo:status" TEXT COLLATE +NOCASE, "nmo:status:graph" INTEGER, "nmo:responseType" TEXT COLLATE +NOCASE, "nmo:responseType:graph" INTEGER); +CREATE TABLE "nmo:Email_nmo:contentMimeType" (ID INTEGER NOT NULL, +"nmo:contentMimeType" TEXT NOT NULL, "nmo:contentMimeType:graph" +INTEGER); +CREATE TABLE "nmo:IMMessage" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:MMSMessage" (ID INTEGER NOT NULL PRIMARY KEY, +"nmo:mmsHasContent" INTEGER, "nmo:mmsHasContent:graph" INTEGER); +CREATE TABLE "nmo:MailAccount" (ID INTEGER NOT NULL PRIMARY KEY, +"nmo:accountName" TEXT COLLATE NOCASE, "nmo:accountName:graph" +INTEGER, "nmo:accountDisplayName" TEXT COLLATE NOCASE, +"nmo:accountDisplayName:graph" INTEGER, "nmo:fromAddress" INTEGER, +"nmo:fromAddress:graph" INTEGER, "nmo:signature" TEXT COLLATE NOCASE, +"nmo:signature:graph" INTEGER); +CREATE TABLE "nmo:MailFolder" (ID INTEGER NOT NULL PRIMARY KEY, +"nmo:folderName" TEXT COLLATE NOCASE, "nmo:folderName:graph" INTEGER, +"nmo:serverCount" INTEGER, "nmo:serverCount:graph" INTEGER, +"nmo:serverUnreadCount" INTEGER, "nmo:serverUnreadCount:graph" +INTEGER); +CREATE TABLE "nmo:MailboxDataObject" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:Message" (ID INTEGER NOT NULL PRIMARY KEY, +"nmo:sentDate" INTEGER, "nmo:sentDate:graph" INTEGER, +"nmo:sentDate:localDate" INTEGER, "nmo:sentDate:localTime" INTEGER, +"nmo:from" INTEGER, "nmo:from:graph" INTEGER, "nmo:isAnswered" +INTEGER, "nmo:isAnswered:graph" INTEGER, "nmo:isDeleted" INTEGER, +"nmo:isDeleted:graph" INTEGER, "nmo:isDraft" INTEGER, +"nmo:isDraft:graph" INTEGER, "nmo:isRead" INTEGER, "nmo:isRead:graph" +INTEGER, "nmo:isSent" INTEGER, "nmo:isSent:graph" INTEGER, +"nmo:isEmergency" INTEGER, "nmo:isEmergency:graph" INTEGER, +"nmo:htmlMessageContent" TEXT COLLATE NOCASE, +"nmo:htmlMessageContent:graph" INTEGER, "nmo:messageId" TEXT COLLATE +NOCASE, "nmo:messageId:graph" INTEGER, "nmo:messageSubject" TEXT +COLLATE NOCASE, "nmo:messageSubject:graph" INTEGER, +"nmo:receivedDate" INTEGER, "nmo:receivedDate:graph" INTEGER, +"nmo:receivedDate:localDate" INTEGER, "nmo:receivedDate:localTime" +INTEGER, "nmo:replyTo" INTEGER, "nmo:replyTo:graph" INTEGER, +"nmo:sender" INTEGER, "nmo:sender:graph" INTEGER, "nmo:conversation" +INTEGER, "nmo:conversation:graph" INTEGER, "nmo:communicationChannel" +INTEGER, "nmo:communicationChannel:graph" INTEGER, +"nmo:deliveryStatus" INTEGER, "nmo:deliveryStatus:graph" INTEGER, +"nmo:reportDelivery" INTEGER, "nmo:reportDelivery:graph" INTEGER, +"nmo:sentWithReportRead" INTEGER, "nmo:sentWithReportRead:graph" +INTEGER, "nmo:reportReadStatus" INTEGER, "nmo:reportReadStatus:graph" +INTEGER, "nmo:mustAnswerReportRead" INTEGER, +"nmo:mustAnswerReportRead:graph" INTEGER, "nmo:mmsId" TEXT COLLATE +NOCASE, "nmo:mmsId:graph" INTEGER); +CREATE TABLE "nmo:MessageHeader" (ID INTEGER NOT NULL PRIMARY KEY, +"nmo:headerName" TEXT COLLATE NOCASE, "nmo:headerName:graph" INTEGER, +"nmo:headerValue" TEXT COLLATE NOCASE, "nmo:headerValue:graph" +INTEGER); +CREATE TABLE "nmo:Message_nmo:bcc" (ID INTEGER NOT NULL, "nmo:bcc" +INTEGER NOT NULL, "nmo:bcc:graph" INTEGER); +CREATE TABLE "nmo:Message_nmo:cc" (ID INTEGER NOT NULL, "nmo:cc" +INTEGER NOT NULL, "nmo:cc:graph" INTEGER); +CREATE TABLE "nmo:Message_nmo:hasAttachment" (ID INTEGER NOT NULL, +"nmo:hasAttachment" INTEGER NOT NULL, "nmo:hasAttachment:graph" +INTEGER); +CREATE TABLE "nmo:Message_nmo:inReplyTo" (ID INTEGER NOT NULL, +"nmo:inReplyTo" INTEGER NOT NULL, "nmo:inReplyTo:graph" INTEGER); +CREATE TABLE "nmo:Message_nmo:messageHeader" (ID INTEGER NOT NULL, +"nmo:messageHeader" INTEGER NOT NULL, "nmo:messageHeader:graph" +INTEGER); +CREATE TABLE "nmo:Message_nmo:recipient" (ID INTEGER NOT NULL, +"nmo:recipient" INTEGER NOT NULL, "nmo:recipient:graph" INTEGER); +CREATE TABLE "nmo:Message_nmo:references" (ID INTEGER NOT NULL, +"nmo:references" INTEGER NOT NULL, "nmo:references:graph" INTEGER); +CREATE TABLE "nmo:Message_nmo:to" (ID INTEGER NOT NULL, "nmo:to" +INTEGER NOT NULL, "nmo:to:graph" INTEGER); +CREATE TABLE "nmo:MimePart" (ID INTEGER NOT NULL PRIMARY KEY, +"nmo:charSet" TEXT COLLATE NOCASE, "nmo:charSet:graph" INTEGER, +"nmo:contentId" TEXT COLLATE NOCASE, "nmo:contentId:graph" INTEGER, +"nmo:contentTransferEncoding" TEXT COLLATE NOCASE, +"nmo:contentTransferEncoding:graph" INTEGER, "nmo:contentDescription" +TEXT COLLATE NOCASE, "nmo:contentDescription:graph" INTEGER, +"nmo:contentDisposition" TEXT COLLATE NOCASE, +"nmo:contentDisposition:graph" INTEGER); +CREATE TABLE "nmo:MimePart_nmo:mimeHeader" (ID INTEGER NOT NULL, +"nmo:mimeHeader" INTEGER NOT NULL, "nmo:mimeHeader:graph" INTEGER); +CREATE TABLE "nmo:Multipart" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:Multipart_nmo:partBoundary" (ID INTEGER NOT NULL, +"nmo:partBoundary" TEXT NOT NULL, "nmo:partBoundary:graph" INTEGER); +CREATE TABLE "nmo:PermanentChannel" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:PhoneMessage" (ID INTEGER NOT NULL PRIMARY KEY, +"nmo:fromVCard" INTEGER, "nmo:fromVCard:graph" INTEGER, "nmo:encoding" +TEXT COLLATE NOCASE, "nmo:encoding:graph" INTEGER, +"nmo:phoneMessageId" INTEGER, "nmo:phoneMessageId:graph" INTEGER, +"nmo:validityPeriod" INTEGER, "nmo:validityPeriod:graph" INTEGER); +CREATE TABLE "nmo:PhoneMessageFolder" (ID INTEGER NOT NULL PRIMARY +KEY, "nmo:phoneMessageFolderId" TEXT COLLATE NOCASE, +"nmo:phoneMessageFolderId:graph" INTEGER); +CREATE TABLE "nmo:PhoneMessageFolder_nmo:containsPhoneMessage" (ID +INTEGER NOT NULL, "nmo:containsPhoneMessage" INTEGER NOT NULL, +"nmo:containsPhoneMessage:graph" INTEGER); +CREATE TABLE "nmo:PhoneMessageFolder_nmo:containsPhoneMessageFolder" +(ID INTEGER NOT NULL, "nmo:containsPhoneMessageFolder" INTEGER NOT +NULL, "nmo:containsPhoneMessageFolder:graph" INTEGER); +CREATE TABLE "nmo:PhoneMessage_nmo:toVCard" (ID INTEGER NOT NULL, +"nmo:toVCard" INTEGER NOT NULL, "nmo:toVCard:graph" INTEGER); +CREATE TABLE "nmo:ReportReadStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:SMSMessage" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:TransientChannel" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nmo:VOIPCall" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "nrl:InverseFunctionalProperty" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "osinfo:Installer" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "poi:ObjectOfInterest" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "rdf:Property" (ID INTEGER NOT NULL PRIMARY KEY, +"rdfs:domain" INTEGER, "rdfs:domain:graph" INTEGER, "rdfs:range" +INTEGER, "rdfs:range:graph" INTEGER, "tracker:indexed" INTEGER, +"tracker:indexed:graph" INTEGER, "tracker:secondaryIndex" INTEGER, +"tracker:secondaryIndex:graph" INTEGER, "tracker:fulltextIndexed" +INTEGER, "tracker:fulltextIndexed:graph" INTEGER, +"tracker:fulltextNoLimit" INTEGER, "tracker:fulltextNoLimit:graph" +INTEGER, "tracker:transient" INTEGER, "tracker:transient:graph" +INTEGER, "tracker:weight" INTEGER, "tracker:weight:graph" INTEGER, +"tracker:defaultValue" TEXT COLLATE NOCASE, +"tracker:defaultValue:graph" INTEGER, "nrl:maxCardinality" INTEGER, +"nrl:maxCardinality:graph" INTEGER, "tracker:writeback" INTEGER, +"tracker:writeback:graph" INTEGER, "tracker:forceJournal" INTEGER, +"tracker:forceJournal:graph" INTEGER); +CREATE TABLE "rdf:Property_rdfs:subPropertyOf" (ID INTEGER NOT NULL, +"rdfs:subPropertyOf" INTEGER NOT NULL, "rdfs:subPropertyOf:graph" +INTEGER); +CREATE TABLE "rdfs:Class" (ID INTEGER NOT NULL PRIMARY KEY, +"tracker:notify" INTEGER, "tracker:notify:graph" INTEGER); +CREATE TABLE "rdfs:Class_rdfs:subClassOf" (ID INTEGER NOT NULL, +"rdfs:subClassOf" INTEGER NOT NULL, "rdfs:subClassOf:graph" INTEGER); +CREATE TABLE "rdfs:Class_tracker:domainIndex" (ID INTEGER NOT NULL, +"tracker:domainIndex" INTEGER NOT NULL, "tracker:domainIndex:graph" +INTEGER); +CREATE TABLE "rdfs:Literal" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "rdfs:Resource" (ID INTEGER NOT NULL PRIMARY KEY, +Available INTEGER NOT NULL, "rdfs:comment" TEXT COLLATE NOCASE, +"rdfs:comment:graph" INTEGER, "rdfs:label" TEXT COLLATE NOCASE, +"rdfs:label:graph" INTEGER, "tracker:added" INTEGER, +"tracker:added:graph" INTEGER, "tracker:added:localDate" INTEGER, +"tracker:added:localTime" INTEGER, "tracker:modified" INTEGER, +"tracker:modified:graph" INTEGER, "tracker:damaged" INTEGER, +"tracker:damaged:graph" INTEGER, "dc:title" TEXT COLLATE NOCASE, +"dc:title:graph" INTEGER, "dc:creator" TEXT COLLATE NOCASE, +"dc:creator:graph" INTEGER, "dc:subject" TEXT COLLATE NOCASE, +"dc:subject:graph" INTEGER, "dc:description" TEXT COLLATE NOCASE, +"dc:description:graph" INTEGER, "dc:publisher" TEXT COLLATE NOCASE, +"dc:publisher:graph" INTEGER, "dc:type" TEXT COLLATE NOCASE, +"dc:type:graph" INTEGER, "dc:format" TEXT COLLATE NOCASE, +"dc:format:graph" INTEGER, "dc:identifier" TEXT COLLATE NOCASE, +"dc:identifier:graph" INTEGER, "dc:language" TEXT COLLATE NOCASE, +"dc:language:graph" INTEGER, "dc:coverage" TEXT COLLATE NOCASE, +"dc:coverage:graph" INTEGER, "dc:rights" TEXT COLLATE NOCASE, +"dc:rights:graph" INTEGER, "nao:identifier" TEXT COLLATE NOCASE, +"nao:identifier:graph" INTEGER, "nao:numericRating" REAL, +"nao:numericRating:graph" INTEGER, "nao:lastModified" INTEGER, +"nao:lastModified:graph" INTEGER, "nao:lastModified:localDate" +INTEGER, "nao:lastModified:localTime" INTEGER); +CREATE TABLE "rdfs:Resource_dc:contributor" (ID INTEGER NOT NULL, +"dc:contributor" TEXT NOT NULL, "dc:contributor:graph" INTEGER); +CREATE TABLE "rdfs:Resource_dc:date" (ID INTEGER NOT NULL, "dc:date" +INTEGER NOT NULL, "dc:date:graph" INTEGER, "dc:date:localDate" INTEGER +NOT NULL, "dc:date:localTime" INTEGER NOT NULL); +CREATE TABLE "rdfs:Resource_dc:relation" (ID INTEGER NOT NULL, +"dc:relation" TEXT NOT NULL, "dc:relation:graph" INTEGER); +CREATE TABLE "rdfs:Resource_dc:source" (ID INTEGER NOT NULL, +"dc:source" INTEGER NOT NULL, "dc:source:graph" INTEGER); +CREATE TABLE "rdfs:Resource_nao:deprecated" (ID INTEGER NOT NULL, +"nao:deprecated" INTEGER NOT NULL, "nao:deprecated:graph" INTEGER); +CREATE TABLE "rdfs:Resource_nao:hasTag" (ID INTEGER NOT NULL, +"nao:hasTag" INTEGER NOT NULL, "nao:hasTag:graph" INTEGER); +CREATE TABLE "rdfs:Resource_nao:isRelated" (ID INTEGER NOT NULL, +"nao:isRelated" INTEGER NOT NULL, "nao:isRelated:graph" INTEGER); +CREATE TABLE "rdfs:Resource_rdf:type" (ID INTEGER NOT NULL, "rdf:type" +INTEGER NOT NULL, "rdf:type:graph" INTEGER); +CREATE TABLE "scal:AccessLevel" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "scal:AttendanceStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "scal:Attendee" (ID INTEGER NOT NULL PRIMARY KEY, +"scal:attendanceStatus" INTEGER, "scal:attendanceStatus:graph" +INTEGER, "scal:attendeeRole" INTEGER, "scal:attendeeRole:graph" +INTEGER, "scal:attendeeContact" INTEGER, "scal:attendeeContact:graph" +INTEGER, "scal:rsvp" INTEGER, "scal:rsvp:graph" INTEGER, +"scal:calendarUserType" INTEGER, "scal:calendarUserType:graph" +INTEGER); +CREATE TABLE "scal:AttendeeRole" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "scal:Attendee_scal:delegated-from" (ID INTEGER NOT NULL, +"scal:delegated-from" INTEGER NOT NULL, "scal:delegated-from:graph" +INTEGER); +CREATE TABLE "scal:Attendee_scal:delegated-to" (ID INTEGER NOT NULL, +"scal:delegated-to" INTEGER NOT NULL, "scal:delegated-to:graph" +INTEGER); +CREATE TABLE "scal:Attendee_scal:member" (ID INTEGER NOT NULL, +"scal:member" INTEGER NOT NULL, "scal:member:graph" INTEGER); +CREATE TABLE "scal:Attendee_scal:sent-by" (ID INTEGER NOT NULL, +"scal:sent-by" INTEGER NOT NULL, "scal:sent-by:graph" INTEGER); +CREATE TABLE "scal:Calendar" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "scal:CalendarAlarm" (ID INTEGER NOT NULL PRIMARY KEY, +"scal:alarmOffset" INTEGER, "scal:alarmOffset:graph" INTEGER); +CREATE TABLE "scal:CalendarAlarm_scal:alarmAttendee" (ID INTEGER NOT +NULL, "scal:alarmAttendee" INTEGER NOT NULL, +"scal:alarmAttendee:graph" INTEGER); +CREATE TABLE "scal:CalendarItem" (ID INTEGER NOT NULL PRIMARY KEY, +"scal:textLocation" INTEGER, "scal:textLocation:graph" INTEGER, +"scal:resources" TEXT COLLATE NOCASE, "scal:resources:graph" INTEGER, +"scal:transparency" INTEGER, "scal:transparency:graph" INTEGER, +"scal:calendarItemAlarm" INTEGER, "scal:calendarItemAlarm:graph" +INTEGER, "scal:start" INTEGER, "scal:start:graph" INTEGER, "scal:end" +INTEGER, "scal:end:graph" INTEGER, "scal:isAllDay" INTEGER, +"scal:isAllDay:graph" INTEGER, "scal:priority" INTEGER, +"scal:priority:graph" INTEGER, "scal:rdate" INTEGER, +"scal:rdate:graph" INTEGER, "scal:exceptionRDate" INTEGER, +"scal:exceptionRDate:graph" INTEGER); +CREATE TABLE "scal:CalendarItem_scal:access" (ID INTEGER NOT NULL, +"scal:access" INTEGER NOT NULL, "scal:access:graph" INTEGER); +CREATE TABLE "scal:CalendarItem_scal:attachment" (ID INTEGER NOT NULL, +"scal:attachment" INTEGER NOT NULL, "scal:attachment:graph" INTEGER); +CREATE TABLE "scal:CalendarItem_scal:attendee" (ID INTEGER NOT NULL, +"scal:attendee" INTEGER NOT NULL, "scal:attendee:graph" INTEGER); +CREATE TABLE "scal:CalendarItem_scal:belongsToCalendar" (ID INTEGER +NOT NULL, "scal:belongsToCalendar" INTEGER NOT NULL, +"scal:belongsToCalendar:graph" INTEGER); +CREATE TABLE "scal:CalendarItem_scal:contact" (ID INTEGER NOT NULL, +"scal:contact" INTEGER NOT NULL, "scal:contact:graph" INTEGER); +CREATE TABLE "scal:CalendarItem_scal:rrule" (ID INTEGER NOT NULL, +"scal:rrule" INTEGER NOT NULL, "scal:rrule:graph" INTEGER); +CREATE TABLE "scal:CalendarUserType" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "scal:Event" (ID INTEGER NOT NULL PRIMARY KEY, +"scal:eventStatus" INTEGER, "scal:eventStatus:graph" INTEGER); +CREATE TABLE "scal:EventStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "scal:Journal" (ID INTEGER NOT NULL PRIMARY KEY, +"scal:journalStatus" INTEGER, "scal:journalStatus:graph" INTEGER); +CREATE TABLE "scal:JournalStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "scal:RSVPValues" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "scal:RecurrenceRule" (ID INTEGER NOT NULL PRIMARY KEY, +"scal:recurrencePattern" TEXT COLLATE NOCASE, +"scal:recurrencePattern:graph" INTEGER, "scal:recurrenceStartDate" +INTEGER, "scal:recurrenceStartDate:graph" INTEGER, "scal:exception" +INTEGER, "scal:exception:graph" INTEGER); +CREATE TABLE "scal:TimePoint" (ID INTEGER NOT NULL PRIMARY KEY, +"scal:dateTime" INTEGER, "scal:dateTime:graph" INTEGER, +"scal:dateTime:localDate" INTEGER, "scal:dateTime:localTime" INTEGER, +"scal:TimeZone" TEXT COLLATE NOCASE, "scal:TimeZone:graph" INTEGER); +CREATE TABLE "scal:Todo" (ID INTEGER NOT NULL PRIMARY KEY, +"scal:todoStatus" INTEGER, "scal:todoStatus:graph" INTEGER, "scal:due" +INTEGER, "scal:due:graph" INTEGER, "scal:completed" INTEGER, +"scal:completed:graph" INTEGER, "scal:percentComplete" INTEGER, +"scal:percentComplete:graph" INTEGER); +CREATE TABLE "scal:TodoStatus" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "scal:TransparencyValues" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "slo:GeoLocation" (ID INTEGER NOT NULL PRIMARY KEY, +"slo:latitude" REAL, "slo:latitude:graph" INTEGER, "slo:longitude" +REAL, "slo:longitude:graph" INTEGER, "slo:verticalAccuracy" REAL, +"slo:verticalAccuracy:graph" INTEGER, "slo:horizontalAccuracy" REAL, +"slo:horizontalAccuracy:graph" INTEGER, "slo:altitude" REAL, +"slo:altitude:graph" INTEGER, "slo:boundingLatitudeMin" REAL, +"slo:boundingLatitudeMin:graph" INTEGER, "slo:boundingLatitudeMax" +REAL, "slo:boundingLatitudeMax:graph" INTEGER, +"slo:boundingLongitudeMin" REAL, "slo:boundingLongitudeMin:graph" +INTEGER, "slo:boundingLongitudeMax" REAL, +"slo:boundingLongitudeMax:graph" INTEGER, "slo:radius" REAL, +"slo:radius:graph" INTEGER, "slo:timestamp" INTEGER, +"slo:timestamp:graph" INTEGER, "slo:timestamp:localDate" INTEGER, +"slo:timestamp:localTime" INTEGER, "slo:postalAddress" INTEGER, +"slo:postalAddress:graph" INTEGER); +CREATE TABLE "slo:Landmark" (ID INTEGER NOT NULL PRIMARY KEY, +"slo:iconUrl" INTEGER, "slo:iconUrl:graph" INTEGER); +CREATE TABLE "slo:LandmarkCategory" (ID INTEGER NOT NULL PRIMARY KEY, +"slo:isRemovable" INTEGER, "slo:isRemovable:graph" INTEGER, +"slo:categoryIconUrl" INTEGER, "slo:categoryIconUrl:graph" INTEGER); +CREATE TABLE "slo:Landmark_slo:belongsToCategory" (ID INTEGER NOT +NULL, "slo:belongsToCategory" INTEGER NOT NULL, +"slo:belongsToCategory:graph" INTEGER); +CREATE TABLE "slo:Landmark_slo:hasContact" (ID INTEGER NOT NULL, +"slo:hasContact" INTEGER NOT NULL, "slo:hasContact:graph" INTEGER); +CREATE TABLE "slo:Route" (ID INTEGER NOT NULL PRIMARY KEY, +"slo:startTime" INTEGER, "slo:startTime:graph" INTEGER, +"slo:startTime:localDate" INTEGER, "slo:startTime:localTime" INTEGER, +"slo:endTime" INTEGER, "slo:endTime:graph" INTEGER, +"slo:endTime:localDate" INTEGER, "slo:endTime:localTime" INTEGER); +CREATE TABLE "slo:Route_slo:routeDetails" (ID INTEGER NOT NULL, +"slo:routeDetails" TEXT NOT NULL, "slo:routeDetails:graph" INTEGER); +CREATE TABLE "tracker:Namespace" (ID INTEGER NOT NULL PRIMARY KEY, +"tracker:prefix" TEXT COLLATE NOCASE, "tracker:prefix:graph" +INTEGER); +CREATE TABLE "tracker:Ontology" (ID INTEGER NOT NULL PRIMARY KEY); +CREATE TABLE "tracker:Volume" (ID INTEGER NOT NULL PRIMARY KEY, +"tracker:isMounted" INTEGER, "tracker:isMounted:graph" INTEGER, +"tracker:unmountDate" INTEGER, "tracker:unmountDate:graph" INTEGER, +"tracker:unmountDate:localDate" INTEGER, +"tracker:unmountDate:localTime" INTEGER, "tracker:mountPoint" INTEGER, +"tracker:mountPoint:graph" INTEGER, "tracker:isRemovable" INTEGER, +"tracker:isRemovable:graph" INTEGER, "tracker:isOptical" INTEGER, +"tracker:isOptical:graph" INTEGER); +CREATE UNIQUE INDEX "mfo:FeedMessage_mfo:enclosureList_ID_ID" ON +"mfo:FeedMessage_mfo:enclosureList" (ID, "mfo:enclosureList"); +CREATE UNIQUE INDEX "mlo:GeoBoundingBox_mlo:bbNorthWest_ID_ID" ON +"mlo:GeoBoundingBox_mlo:bbNorthWest" (ID, "mlo:bbNorthWest"); +CREATE UNIQUE INDEX "mlo:GeoBoundingBox_mlo:bbSouthEast_ID_ID" ON +"mlo:GeoBoundingBox_mlo:bbSouthEast" (ID, "mlo:bbSouthEast"); +CREATE INDEX "mlo:GeoLocation_mlo:asBoundingBox_ID" ON +"mlo:GeoLocation_mlo:asBoundingBox" (ID); +CREATE UNIQUE INDEX "mlo:GeoLocation_mlo:asBoundingBox_ID_ID" ON +"mlo:GeoLocation_mlo:asBoundingBox" ("mlo:asBoundingBox", ID); +CREATE INDEX "mlo:GeoLocation_mlo:asGeoPoint_ID" ON +"mlo:GeoLocation_mlo:asGeoPoint" (ID); +CREATE UNIQUE INDEX "mlo:GeoLocation_mlo:asGeoPoint_ID_ID" ON +"mlo:GeoLocation_mlo:asGeoPoint" ("mlo:asGeoPoint", ID); +CREATE INDEX "mlo:GeoLocation_mlo:asPostalAddress_ID" ON +"mlo:GeoLocation_mlo:asPostalAddress" (ID); +CREATE UNIQUE INDEX "mlo:GeoLocation_mlo:asPostalAddress_ID_ID" ON +"mlo:GeoLocation_mlo:asPostalAddress" ("mlo:asPostalAddress", ID); +CREATE UNIQUE INDEX "mlo:GeoPoint_mlo:address_ID_ID" ON +"mlo:GeoPoint_mlo:address" (ID, "mlo:address"); +CREATE UNIQUE INDEX "mlo:GeoPoint_mlo:altitude_ID_ID" ON +"mlo:GeoPoint_mlo:altitude" (ID, "mlo:altitude"); +CREATE UNIQUE INDEX "mlo:GeoPoint_mlo:city_ID_ID" ON +"mlo:GeoPoint_mlo:city" (ID, "mlo:city"); +CREATE UNIQUE INDEX "mlo:GeoPoint_mlo:country_ID_ID" ON +"mlo:GeoPoint_mlo:country" (ID, "mlo:country"); +CREATE UNIQUE INDEX "mlo:GeoPoint_mlo:latitude_ID_ID" ON +"mlo:GeoPoint_mlo:latitude" (ID, "mlo:latitude"); +CREATE UNIQUE INDEX "mlo:GeoPoint_mlo:longitude_ID_ID" ON +"mlo:GeoPoint_mlo:longitude" (ID, "mlo:longitude"); +CREATE UNIQUE INDEX "mlo:GeoPoint_mlo:state_ID_ID" ON +"mlo:GeoPoint_mlo:state" (ID, "mlo:state"); +CREATE UNIQUE INDEX "mlo:GeoPoint_mlo:timestamp_ID_ID" ON +"mlo:GeoPoint_mlo:timestamp" (ID, "mlo:timestamp"); +CREATE UNIQUE INDEX "mlo:GeoSphere_mlo:radius_ID_ID" ON +"mlo:GeoSphere_mlo:radius" (ID, "mlo:radius"); +CREATE UNIQUE INDEX "mlo:LandmarkCategory_mlo:isRemovable_ID_ID" ON +"mlo:LandmarkCategory_mlo:isRemovable" (ID, "mlo:isRemovable"); +CREATE UNIQUE INDEX "mlo:Landmark_mlo:belongsToCategory_ID_ID" ON +"mlo:Landmark_mlo:belongsToCategory" (ID, "mlo:belongsToCategory"); +CREATE UNIQUE INDEX "mlo:Landmark_mlo:poiLocation_ID_ID" ON +"mlo:Landmark_mlo:poiLocation" (ID, "mlo:poiLocation"); +CREATE UNIQUE INDEX "mlo:LocationBoundingBox_mlo:boxEastLimit_ID_ID" +ON "mlo:LocationBoundingBox_mlo:boxEastLimit" (ID, +"mlo:boxEastLimit"); +CREATE UNIQUE INDEX "mlo:LocationBoundingBox_mlo:boxNorthLimit_ID_ID" +ON "mlo:LocationBoundingBox_mlo:boxNorthLimit" (ID, +"mlo:boxNorthLimit"); +CREATE UNIQUE INDEX +"mlo:LocationBoundingBox_mlo:boxSouthWestCorner_ID_ID" ON +"mlo:LocationBoundingBox_mlo:boxSouthWestCorner" (ID, +"mlo:boxSouthWestCorner"); +CREATE UNIQUE INDEX +"mlo:LocationBoundingBox_mlo:boxVerticalLimit_ID_ID" ON +"mlo:LocationBoundingBox_mlo:boxVerticalLimit" (ID, +"mlo:boxVerticalLimit"); +CREATE UNIQUE INDEX "mlo:Route_mlo:endTime_ID_ID" ON +"mlo:Route_mlo:endTime" (ID, "mlo:endTime"); +CREATE UNIQUE INDEX "mlo:Route_mlo:routeDetails_ID_ID" ON +"mlo:Route_mlo:routeDetails" (ID, "mlo:routeDetails"); +CREATE UNIQUE INDEX "mlo:Route_mlo:startTime_ID_ID" ON +"mlo:Route_mlo:startTime" (ID, "mlo:startTime"); +CREATE UNIQUE INDEX "mto:Transfer_mto:transferList_ID_ID" ON +"mto:Transfer_mto:transferList" (ID, "mto:transferList"); +CREATE UNIQUE INDEX "mto:Transfer_mto:transferPrivacyLevel_ID_ID" ON +"mto:Transfer_mto:transferPrivacyLevel" (ID, +"mto:transferPrivacyLevel"); +CREATE UNIQUE INDEX "mto:UploadTransfer_mto:transferCategory_ID_ID" ON +"mto:UploadTransfer_mto:transferCategory" (ID, +"mto:transferCategory"); +CREATE UNIQUE INDEX "nao:Tag_tracker:isDefaultTag_ID_ID" ON +"nao:Tag_tracker:isDefaultTag" (ID, "tracker:isDefaultTag"); +CREATE UNIQUE INDEX "nao:Tag_tracker:tagRelatedTo_ID_ID" ON +"nao:Tag_tracker:tagRelatedTo" (ID, "tracker:tagRelatedTo"); +CREATE UNIQUE INDEX "ncal:Alarm_ncal:action_ID_ID" ON +"ncal:Alarm_ncal:action" (ID, "ncal:action"); +CREATE UNIQUE INDEX "ncal:BydayRulePart_ncal:bydayModifier_ID_ID" ON +"ncal:BydayRulePart_ncal:bydayModifier" (ID, "ncal:bydayModifier"); +CREATE UNIQUE INDEX "ncal:BydayRulePart_ncal:bydayWeekday_ID_ID" ON +"ncal:BydayRulePart_ncal:bydayWeekday" (ID, "ncal:bydayWeekday"); +CREATE UNIQUE INDEX "ncal:Calendar_ncal:component_ID_ID" ON +"ncal:Calendar_ncal:component" (ID, "ncal:component"); +CREATE UNIQUE INDEX "ncal:Freebusy_ncal:freebusy_ID_ID" ON +"ncal:Freebusy_ncal:freebusy" (ID, "ncal:freebusy"); +CREATE UNIQUE INDEX "ncal:RecurrenceRule_ncal:byday_ID_ID" ON +"ncal:RecurrenceRule_ncal:byday" (ID, "ncal:byday"); +CREATE UNIQUE INDEX "ncal:RecurrenceRule_ncal:byhour_ID_ID" ON +"ncal:RecurrenceRule_ncal:byhour" (ID, "ncal:byhour"); +CREATE UNIQUE INDEX "ncal:RecurrenceRule_ncal:byminute_ID_ID" ON +"ncal:RecurrenceRule_ncal:byminute" (ID, "ncal:byminute"); +CREATE UNIQUE INDEX "ncal:RecurrenceRule_ncal:bymonth_ID_ID" ON +"ncal:RecurrenceRule_ncal:bymonth" (ID, "ncal:bymonth"); +CREATE UNIQUE INDEX "ncal:RecurrenceRule_ncal:bymonthday_ID_ID" ON +"ncal:RecurrenceRule_ncal:bymonthday" (ID, "ncal:bymonthday"); +CREATE UNIQUE INDEX "ncal:RecurrenceRule_ncal:bysecond_ID_ID" ON +"ncal:RecurrenceRule_ncal:bysecond" (ID, "ncal:bysecond"); +CREATE UNIQUE INDEX "ncal:RecurrenceRule_ncal:bysetpos_ID_ID" ON +"ncal:RecurrenceRule_ncal:bysetpos" (ID, "ncal:bysetpos"); +CREATE UNIQUE INDEX "ncal:RecurrenceRule_ncal:byweekno_ID_ID" ON +"ncal:RecurrenceRule_ncal:byweekno" (ID, "ncal:byweekno"); +CREATE UNIQUE INDEX "ncal:RecurrenceRule_ncal:byyearday_ID_ID" ON +"ncal:RecurrenceRule_ncal:byyearday" (ID, "ncal:byyearday"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:attach_ID_ID" ON +"ncal:UnionParentClass_ncal:attach" (ID, "ncal:attach"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:attendee_ID_ID" ON +"ncal:UnionParentClass_ncal:attendee" (ID, "ncal:attendee"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:categories_ID_ID" ON +"ncal:UnionParentClass_ncal:categories" (ID, "ncal:categories"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:exdate_ID_ID" ON +"ncal:UnionParentClass_ncal:exdate" (ID, "ncal:exdate"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:exrule_ID_ID" ON +"ncal:UnionParentClass_ncal:exrule" (ID, "ncal:exrule"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:hasAlarm_ID_ID" ON +"ncal:UnionParentClass_ncal:hasAlarm" (ID, "ncal:hasAlarm"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:ncalRelation_ID_ID" ON +"ncal:UnionParentClass_ncal:ncalRelation" (ID, "ncal:ncalRelation"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:rdate_ID_ID" ON +"ncal:UnionParentClass_ncal:rdate" (ID, "ncal:rdate"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:relatedToChild_ID_ID" +ON "ncal:UnionParentClass_ncal:relatedToChild" (ID, +"ncal:relatedToChild"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:relatedToParent_ID_ID" +ON "ncal:UnionParentClass_ncal:relatedToParent" (ID, +"ncal:relatedToParent"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:resources_ID_ID" ON +"ncal:UnionParentClass_ncal:resources" (ID, "ncal:resources"); +CREATE UNIQUE INDEX "ncal:UnionParentClass_ncal:rrule_ID_ID" ON +"ncal:UnionParentClass_ncal:rrule" (ID, "ncal:rrule"); +CREATE UNIQUE INDEX "nco:Affiliation_nco:title_ID_ID" ON +"nco:Affiliation_nco:title" (ID, "nco:title"); +CREATE UNIQUE INDEX "nco:ContactList_nco:containsContact_ID_ID" ON +"nco:ContactList_nco:containsContact" (ID, "nco:containsContact"); +CREATE UNIQUE INDEX "nco:Contact_ncal:anniversary_ID_ID" ON +"nco:Contact_ncal:anniversary" (ID, "ncal:anniversary"); +CREATE UNIQUE INDEX "nco:Contact_ncal:birthday_ID_ID" ON +"nco:Contact_ncal:birthday" (ID, "ncal:birthday"); +CREATE UNIQUE INDEX "nco:Contact_nco:belongsToGroup_ID_ID" ON +"nco:Contact_nco:belongsToGroup" (ID, "nco:belongsToGroup"); +CREATE UNIQUE INDEX "nco:Contact_nco:note_ID_ID" ON +"nco:Contact_nco:note" (ID, "nco:note"); +CREATE UNIQUE INDEX "nco:Contact_scal:anniversary_ID_ID" ON +"nco:Contact_scal:anniversary" (ID, "scal:anniversary"); +CREATE UNIQUE INDEX "nco:Contact_scal:birthday_ID_ID" ON +"nco:Contact_scal:birthday" (ID, "scal:birthday"); +CREATE UNIQUE INDEX "nco:IMAccount_nco:hasIMContact_ID_ID" ON +"nco:IMAccount_nco:hasIMContact" (ID, "nco:hasIMContact"); +CREATE UNIQUE INDEX "nco:IMAddress_nco:imCapability_ID_ID" ON +"nco:IMAddress_nco:imCapability" (ID, "nco:imCapability"); +CREATE UNIQUE INDEX "nco:PersonContact_nco:hasAffiliation_ID_ID" ON +"nco:PersonContact_nco:hasAffiliation" (ID, "nco:hasAffiliation"); +CREATE INDEX "nco:PersonContact_nco:nameFamily" ON "nco:PersonContact" +("nco:nameFamily"); +CREATE INDEX "nco:PhoneNumber_nco:phoneNumber" ON "nco:PhoneNumber" +("nco:phoneNumber"); +CREATE UNIQUE INDEX "nco:Role_nco:blogUrl_ID_ID" ON +"nco:Role_nco:blogUrl" (ID, "nco:blogUrl"); +CREATE UNIQUE INDEX "nco:Role_nco:foafUrl_ID_ID" ON +"nco:Role_nco:foafUrl" (ID, "nco:foafUrl"); +CREATE UNIQUE INDEX "nco:Role_nco:hasContactMedium_ID_ID" ON +"nco:Role_nco:hasContactMedium" (ID, "nco:hasContactMedium"); +CREATE INDEX "nco:Role_nco:hasEmailAddress_ID" ON +"nco:Role_nco:hasEmailAddress" (ID); +CREATE UNIQUE INDEX "nco:Role_nco:hasEmailAddress_ID_ID" ON +"nco:Role_nco:hasEmailAddress" ("nco:hasEmailAddress", ID); +CREATE UNIQUE INDEX "nco:Role_nco:hasIMAddress_ID_ID" ON +"nco:Role_nco:hasIMAddress" (ID, "nco:hasIMAddress"); +CREATE UNIQUE INDEX "nco:Role_nco:hasPhoneNumber_ID_ID" ON +"nco:Role_nco:hasPhoneNumber" (ID, "nco:hasPhoneNumber"); +CREATE INDEX "nco:Role_nco:hasPostalAddress_ID" ON +"nco:Role_nco:hasPostalAddress" (ID); +CREATE UNIQUE INDEX "nco:Role_nco:hasPostalAddress_ID_ID" ON +"nco:Role_nco:hasPostalAddress" ("nco:hasPostalAddress", ID); +CREATE UNIQUE INDEX "nco:Role_nco:url_ID_ID" ON "nco:Role_nco:url" +(ID, "nco:url"); +CREATE UNIQUE INDEX "nco:Role_nco:websiteUrl_ID_ID" ON +"nco:Role_nco:websiteUrl" (ID, "nco:websiteUrl"); +CREATE UNIQUE INDEX +"nfo:BookmarkFolder_nfo:containsBookmarkFolder_ID_ID" ON +"nfo:BookmarkFolder_nfo:containsBookmarkFolder" (ID, +"nfo:containsBookmarkFolder"); +CREATE UNIQUE INDEX "nfo:BookmarkFolder_nfo:containsBookmark_ID_ID" ON +"nfo:BookmarkFolder_nfo:containsBookmark" (ID, +"nfo:containsBookmark"); +CREATE INDEX "nfo:FileDataObject_nfo:fileLastModified" ON +"nfo:FileDataObject" ("nfo:fileLastModified"); +CREATE UNIQUE INDEX "nfo:Image_nfo:depicts_ID_ID" ON +"nfo:Image_nfo:depicts" (ID, "nfo:depicts"); +CREATE UNIQUE INDEX "nfo:Image_nfo:hasRegionOfInterest_ID_ID" ON +"nfo:Image_nfo:hasRegionOfInterest" (ID, "nfo:hasRegionOfInterest"); +CREATE UNIQUE INDEX "nfo:MediaList_nfo:hasMediaFileListEntry_ID_ID" ON +"nfo:MediaList_nfo:hasMediaFileListEntry" (ID, +"nfo:hasMediaFileListEntry"); +CREATE UNIQUE INDEX "nfo:MediaList_nfo:mediaListEntry_ID_ID" ON +"nfo:MediaList_nfo:mediaListEntry" (ID, "nfo:mediaListEntry"); +CREATE UNIQUE INDEX "nfo:Media_mtp:hidden_ID_ID" ON +"nfo:Media_mtp:hidden" (ID, "mtp:hidden"); +CREATE UNIQUE INDEX "nfo:Media_nmm:alternativeMedia_ID_ID" ON +"nfo:Media_nmm:alternativeMedia" (ID, "nmm:alternativeMedia"); +CREATE INDEX "nfo:Visual_nie:contentCreated" ON "nfo:Visual" +("nie:contentCreated"); +CREATE UNIQUE INDEX "nid3:ID3Audio_nid3:leadArtist_ID_ID" ON +"nid3:ID3Audio_nid3:leadArtist" (ID, "nid3:leadArtist"); +CREATE UNIQUE INDEX "nie:DataObject_nie:dataSource_ID_ID" ON +"nie:DataObject_nie:dataSource" (ID, "nie:dataSource"); +CREATE UNIQUE INDEX "nie:DataObject_nie:isPartOf_ID_ID" ON +"nie:DataObject_nie:isPartOf" (ID, "nie:isPartOf"); +CREATE INDEX "nie:DataObject_nie:url" ON "nie:DataObject" ("nie:url"); +CREATE INDEX "nie:InformationElement_mlo:location_ID" ON +"nie:InformationElement_mlo:location" (ID); +CREATE UNIQUE INDEX "nie:InformationElement_mlo:location_ID_ID" ON +"nie:InformationElement_mlo:location" ("mlo:location", ID); +CREATE UNIQUE INDEX "nie:InformationElement_nao:hasProperty_ID_ID" ON +"nie:InformationElement_nao:hasProperty" (ID, "nao:hasProperty"); +CREATE UNIQUE INDEX "nie:InformationElement_nco:contributor_ID_ID" ON +"nie:InformationElement_nco:contributor" (ID, "nco:contributor"); +CREATE UNIQUE INDEX "nie:InformationElement_nco:creator_ID_ID" ON +"nie:InformationElement_nco:creator" (ID, "nco:creator"); +CREATE UNIQUE INDEX "nie:InformationElement_nie:hasLogicalPart_ID_ID" +ON "nie:InformationElement_nie:hasLogicalPart" (ID, +"nie:hasLogicalPart"); +CREATE UNIQUE INDEX "nie:InformationElement_nie:hasPart_ID_ID" ON +"nie:InformationElement_nie:hasPart" (ID, "nie:hasPart"); +CREATE UNIQUE INDEX +"nie:InformationElement_nie:informationElementDate_ID_ID" ON +"nie:InformationElement_nie:informationElementDate" (ID, +"nie:informationElementDate"); +CREATE UNIQUE INDEX "nie:InformationElement_nie:isLogicalPartOf_ID_ID" +ON "nie:InformationElement_nie:isLogicalPartOf" (ID, +"nie:isLogicalPartOf"); +CREATE UNIQUE INDEX "nie:InformationElement_nie:keyword_ID_ID" ON +"nie:InformationElement_nie:keyword" (ID, "nie:keyword"); +CREATE UNIQUE INDEX "nie:InformationElement_nie:relatedTo_ID_ID" ON +"nie:InformationElement_nie:relatedTo" (ID, "nie:relatedTo"); +CREATE INDEX "nie:InformationElement_slo:location" ON +"nie:InformationElement" ("slo:location"); +CREATE INDEX "nmm:Artist_nmm:artistName" ON "nmm:Artist" ("nmm:artistName"); +CREATE INDEX "nmm:MusicAlbum_nie:title" ON "nmm:MusicAlbum" ("nie:title"); +CREATE UNIQUE INDEX "nmm:MusicAlbum_nmm:albumArtist_ID_ID" ON +"nmm:MusicAlbum_nmm:albumArtist" (ID, "nmm:albumArtist"); +CREATE INDEX "nmm:MusicPiece_nie:title" ON "nmm:MusicPiece" ("nie:title"); +CREATE UNIQUE INDEX "nmm:MusicPiece_nmm:lyrics_ID_ID" ON +"nmm:MusicPiece_nmm:lyrics" (ID, "nmm:lyrics"); +CREATE INDEX "nmm:MusicPiece_nmm:musicAlbum" ON "nmm:MusicPiece" +("nmm:musicAlbum"); +CREATE INDEX "nmm:MusicPiece_nmm:performer" ON "nmm:MusicPiece" +("nmm:performer"); +CREATE UNIQUE INDEX "nmm:RadioStation_nmm:carrier_ID_ID" ON +"nmm:RadioStation_nmm:carrier" (ID, "nmm:carrier"); +CREATE UNIQUE INDEX "nmm:Video_mtp:scantype_ID_ID" ON +"nmm:Video_mtp:scantype" (ID, "mtp:scantype"); +CREATE UNIQUE INDEX "nmm:Video_nmm:director_ID_ID" ON +"nmm:Video_nmm:director" (ID, "nmm:director"); +CREATE UNIQUE INDEX "nmm:Video_nmm:leadActor_ID_ID" ON +"nmm:Video_nmm:leadActor" (ID, "nmm:leadActor"); +CREATE UNIQUE INDEX "nmm:Video_nmm:subtitle_ID_ID" ON +"nmm:Video_nmm:subtitle" (ID, "nmm:subtitle"); +CREATE INDEX "nmo:Call_nmo:sentDate" ON "nmo:Call" ("nmo:sentDate"); +CREATE INDEX "nmo:CommunicationChannel_nmo:hasParticipant_ID" ON +"nmo:CommunicationChannel_nmo:hasParticipant" (ID); +CREATE UNIQUE INDEX +"nmo:CommunicationChannel_nmo:hasParticipant_ID_ID" ON +"nmo:CommunicationChannel_nmo:hasParticipant" ("nmo:hasParticipant", +ID); +CREATE INDEX "nmo:CommunicationChannel_nmo:lastMessageDate" ON +"nmo:CommunicationChannel" ("nmo:lastMessageDate"); +CREATE UNIQUE INDEX "nmo:Email_nmo:contentMimeType_ID_ID" ON +"nmo:Email_nmo:contentMimeType" (ID, "nmo:contentMimeType"); +CREATE UNIQUE INDEX "nmo:Message_nmo:bcc_ID_ID" ON +"nmo:Message_nmo:bcc" (ID, "nmo:bcc"); +CREATE UNIQUE INDEX "nmo:Message_nmo:cc_ID_ID" ON "nmo:Message_nmo:cc" +(ID, "nmo:cc"); +CREATE INDEX "nmo:Message_nmo:communicationChannel" ON "nmo:Message" +("nmo:communicationChannel", "nmo:receivedDate"); +CREATE INDEX "nmo:Message_nmo:conversation" ON "nmo:Message" +("nmo:conversation"); +CREATE INDEX "nmo:Message_nmo:from" ON "nmo:Message" ("nmo:from"); +CREATE UNIQUE INDEX "nmo:Message_nmo:hasAttachment_ID_ID" ON +"nmo:Message_nmo:hasAttachment" (ID, "nmo:hasAttachment"); +CREATE UNIQUE INDEX "nmo:Message_nmo:inReplyTo_ID_ID" ON +"nmo:Message_nmo:inReplyTo" (ID, "nmo:inReplyTo"); +CREATE UNIQUE INDEX "nmo:Message_nmo:messageHeader_ID_ID" ON +"nmo:Message_nmo:messageHeader" (ID, "nmo:messageHeader"); +CREATE UNIQUE INDEX "nmo:Message_nmo:recipient_ID_ID" ON +"nmo:Message_nmo:recipient" (ID, "nmo:recipient"); +CREATE UNIQUE INDEX "nmo:Message_nmo:references_ID_ID" ON +"nmo:Message_nmo:references" (ID, "nmo:references"); +CREATE INDEX "nmo:Message_nmo:sender" ON "nmo:Message" ("nmo:sender"); +CREATE INDEX "nmo:Message_nmo:sentDate" ON "nmo:Message" ("nmo:sentDate"); +CREATE INDEX "nmo:Message_nmo:to_ID" ON "nmo:Message_nmo:to" (ID); +CREATE UNIQUE INDEX "nmo:Message_nmo:to_ID_ID" ON "nmo:Message_nmo:to" +("nmo:to", ID); +CREATE UNIQUE INDEX "nmo:MimePart_nmo:mimeHeader_ID_ID" ON +"nmo:MimePart_nmo:mimeHeader" (ID, "nmo:mimeHeader"); +CREATE UNIQUE INDEX "nmo:Multipart_nmo:partBoundary_ID_ID" ON +"nmo:Multipart_nmo:partBoundary" (ID, "nmo:partBoundary"); +CREATE UNIQUE INDEX +"nmo:PhoneMessageFolder_nmo:containsPhoneMessageFolder_ID_ID" ON +"nmo:PhoneMessageFolder_nmo:containsPhoneMessageFolder" (ID, +"nmo:containsPhoneMessageFolder"); +CREATE UNIQUE INDEX +"nmo:PhoneMessageFolder_nmo:containsPhoneMessage_ID_ID" ON +"nmo:PhoneMessageFolder_nmo:containsPhoneMessage" (ID, +"nmo:containsPhoneMessage"); +CREATE UNIQUE INDEX "nmo:PhoneMessage_nmo:toVCard_ID_ID" ON +"nmo:PhoneMessage_nmo:toVCard" (ID, "nmo:toVCard"); +CREATE UNIQUE INDEX "rdf:Property_rdfs:subPropertyOf_ID_ID" ON +"rdf:Property_rdfs:subPropertyOf" (ID, "rdfs:subPropertyOf"); +CREATE UNIQUE INDEX "rdfs:Class_rdfs:subClassOf_ID_ID" ON +"rdfs:Class_rdfs:subClassOf" (ID, "rdfs:subClassOf"); +CREATE UNIQUE INDEX "rdfs:Class_tracker:domainIndex_ID_ID" ON +"rdfs:Class_tracker:domainIndex" (ID, "tracker:domainIndex"); +CREATE UNIQUE INDEX "rdfs:Resource_dc:contributor_ID_ID" ON +"rdfs:Resource_dc:contributor" (ID, "dc:contributor"); +CREATE UNIQUE INDEX "rdfs:Resource_dc:date_ID_ID" ON +"rdfs:Resource_dc:date" (ID, "dc:date"); +CREATE UNIQUE INDEX "rdfs:Resource_dc:relation_ID_ID" ON +"rdfs:Resource_dc:relation" (ID, "dc:relation"); +CREATE UNIQUE INDEX "rdfs:Resource_dc:source_ID_ID" ON +"rdfs:Resource_dc:source" (ID, "dc:source"); +CREATE UNIQUE INDEX "rdfs:Resource_nao:deprecated_ID_ID" ON +"rdfs:Resource_nao:deprecated" (ID, "nao:deprecated"); +CREATE INDEX "rdfs:Resource_nao:hasTag_ID" ON "rdfs:Resource_nao:hasTag" (ID); +CREATE UNIQUE INDEX "rdfs:Resource_nao:hasTag_ID_ID" ON +"rdfs:Resource_nao:hasTag" ("nao:hasTag", ID); +CREATE UNIQUE INDEX "rdfs:Resource_nao:isRelated_ID_ID" ON +"rdfs:Resource_nao:isRelated" (ID, "nao:isRelated"); +CREATE UNIQUE INDEX "rdfs:Resource_rdf:type_ID_ID" ON +"rdfs:Resource_rdf:type" (ID, "rdf:type"); +CREATE INDEX "rdfs:Resource_tracker:added" ON "rdfs:Resource" ("tracker:added"); +CREATE UNIQUE INDEX "scal:Attendee_scal:delegated-from_ID_ID" ON +"scal:Attendee_scal:delegated-from" (ID, "scal:delegated-from"); +CREATE UNIQUE INDEX "scal:Attendee_scal:delegated-to_ID_ID" ON +"scal:Attendee_scal:delegated-to" (ID, "scal:delegated-to"); +CREATE UNIQUE INDEX "scal:Attendee_scal:member_ID_ID" ON +"scal:Attendee_scal:member" (ID, "scal:member"); +CREATE UNIQUE INDEX "scal:Attendee_scal:sent-by_ID_ID" ON +"scal:Attendee_scal:sent-by" (ID, "scal:sent-by"); +CREATE UNIQUE INDEX "scal:CalendarAlarm_scal:alarmAttendee_ID_ID" ON +"scal:CalendarAlarm_scal:alarmAttendee" (ID, "scal:alarmAttendee"); +CREATE UNIQUE INDEX "scal:CalendarItem_scal:access_ID_ID" ON +"scal:CalendarItem_scal:access" (ID, "scal:access"); +CREATE UNIQUE INDEX "scal:CalendarItem_scal:attachment_ID_ID" ON +"scal:CalendarItem_scal:attachment" (ID, "scal:attachment"); +CREATE UNIQUE INDEX "scal:CalendarItem_scal:attendee_ID_ID" ON +"scal:CalendarItem_scal:attendee" (ID, "scal:attendee"); +CREATE UNIQUE INDEX "scal:CalendarItem_scal:belongsToCalendar_ID_ID" +ON "scal:CalendarItem_scal:belongsToCalendar" (ID, +"scal:belongsToCalendar"); +CREATE UNIQUE INDEX "scal:CalendarItem_scal:contact_ID_ID" ON +"scal:CalendarItem_scal:contact" (ID, "scal:contact"); +CREATE UNIQUE INDEX "scal:CalendarItem_scal:rrule_ID_ID" ON +"scal:CalendarItem_scal:rrule" (ID, "scal:rrule"); +CREATE INDEX "slo:GeoLocation_slo:postalAddress" ON "slo:GeoLocation" +("slo:postalAddress"); +CREATE UNIQUE INDEX "slo:Landmark_slo:belongsToCategory_ID_ID" ON +"slo:Landmark_slo:belongsToCategory" (ID, "slo:belongsToCategory"); +CREATE UNIQUE INDEX "slo:Landmark_slo:hasContact_ID_ID" ON +"slo:Landmark_slo:hasContact" (ID, "slo:hasContact"); +CREATE UNIQUE INDEX "slo:Route_slo:routeDetails_ID_ID" ON +"slo:Route_slo:routeDetails" (ID, "slo:routeDetails"); + +EXPLAIN SELECT "1_u", (SELECT "nco:fullname" FROM "nco:Contact" WHERE +ID = "1_u") COLLATE NOCASE, (SELECT "nco:nameFamily" FROM +"nco:PersonContact" WHERE ID = "1_u") COLLATE NOCASE, (SELECT +"nco:nameGiven" FROM "nco:PersonContact" WHERE ID = "1_u") +COLLATE NOCASE, (SELECT "nco:nameAdditional" FROM +"nco:PersonContact" WHERE ID = "1_u") COLLATE NOCASE, (SELECT +"nco:nameHonorificPrefix" FROM "nco:PersonContact" WHERE ID = +"1_u") COLLATE NOCASE, (SELECT "nco:nameHonorificSuffix" FROM +"nco:PersonContact" WHERE ID = "1_u") COLLATE NOCASE, (SELECT +"nco:nickname" FROM "nco:Contact" WHERE ID = "1_u") COLLATE +NOCASE, strftime("%s",(SELECT "nco:birthDate" FROM +"nco:Contact" WHERE ID = "1_u")), (SELECT "nie:url" FROM +"nie:DataObject" WHERE ID = (SELECT "nco:photo" FROM +"nco:Contact" WHERE ID = "1_u")) COLLATE NOCASE, (SELECT +GROUP_CONCAT("2_u"||? COLLATE NOCASE||COALESCE((SELECT +"nco:imProtocol" FROM "nco:IMAddress" WHERE ID = "3_u") COLLATE +NOCASE, ? COLLATE NOCASE)||? COLLATE NOCASE||COALESCE((SELECT +"nco:imID" FROM "nco:IMAddress" WHERE ID = "3_u") COLLATE +NOCASE, ? COLLATE NOCASE)||? COLLATE NOCASE||COALESCE((SELECT +"nco:imNickname" FROM "nco:IMAddress" WHERE ID = "3_u") COLLATE +NOCASE, ? COLLATE NOCASE), '\n') FROM (SELECT +"nco:PersonContact_nco:hasAffiliation2"."nco:hasAffiliation" AS +"2_u", "nco:Role_nco:hasIMAddress3"."nco:hasIMAddress" AS +"3_u" FROM "nco:PersonContact_nco:hasAffiliation" AS +"nco:PersonContact_nco:hasAffiliation2", +"nco:Role_nco:hasIMAddress" AS "nco:Role_nco:hasIMAddress3" WHERE +"1_u" = "nco:PersonContact_nco:hasAffiliation2"."ID" AND +"nco:PersonContact_nco:hasAffiliation2"."nco:hasAffiliation" = +"nco:Role_nco:hasIMAddress3"."ID")), (SELECT +GROUP_CONCAT("2_u"||? COLLATE NOCASE||(SELECT "nco:phoneNumber" +FROM "nco:PhoneNumber" WHERE ID = "4_u") COLLATE NOCASE, '\n') +FROM (SELECT "nco:PersonContact_nco:hasAffiliation4"."nco:hasAffiliation" +AS "2_u", "nco:Role_nco:hasPhoneNumber5"."nco:hasPhoneNumber" AS +"4_u" FROM "nco:PersonContact_nco:hasAffiliation" AS +"nco:PersonContact_nco:hasAffiliation4", +"nco:Role_nco:hasPhoneNumber" AS "nco:Role_nco:hasPhoneNumber5" +WHERE "1_u" = "nco:PersonContact_nco:hasAffiliation4"."ID" AND +"nco:PersonContact_nco:hasAffiliation4"."nco:hasAffiliation" = +"nco:Role_nco:hasPhoneNumber5"."ID")), (SELECT +GROUP_CONCAT("2_u"||? COLLATE NOCASE||(SELECT "nco:emailAddress" +FROM "nco:EmailAddress" WHERE ID = "5_u") COLLATE NOCASE, ',') +FROM (SELECT "nco:PersonContact_nco:hasAffiliation6"."nco:hasAffiliation" +AS "2_u", "nco:Role_nco:hasEmailAddress7"."nco:hasEmailAddress" +AS "5_u" FROM "nco:PersonContact_nco:hasAffiliation" AS +"nco:PersonContact_nco:hasAffiliation6", +"nco:Role_nco:hasEmailAddress" AS "nco:Role_nco:hasEmailAddress7" +WHERE "1_u" = "nco:PersonContact_nco:hasAffiliation6"."ID" AND +"nco:PersonContact_nco:hasAffiliation6"."nco:hasAffiliation" = +"nco:Role_nco:hasEmailAddress7"."ID")), (SELECT +GROUP_CONCAT("2_u"||? COLLATE NOCASE||COALESCE((SELECT +GROUP_CONCAT((SELECT Uri FROM Resource WHERE ID = +"nco:blogUrl"),',') FROM "nco:Role_nco:blogUrl" WHERE ID = +"2_u"), ? COLLATE NOCASE)||? COLLATE NOCASE||COALESCE((SELECT +GROUP_CONCAT((SELECT Uri FROM Resource WHERE ID = +"nco:websiteUrl"),',') FROM "nco:Role_nco:websiteUrl" WHERE ID = +"2_u"), ? COLLATE NOCASE)||? COLLATE NOCASE||COALESCE((SELECT +GROUP_CONCAT((SELECT Uri FROM Resource WHERE ID = "nco:url"),',') +FROM "nco:Role_nco:url" WHERE ID = "2_u"), ? COLLATE NOCASE), +'\n') FROM (SELECT +"nco:PersonContact_nco:hasAffiliation8"."nco:hasAffiliation" AS +"2_u" FROM "nco:PersonContact_nco:hasAffiliation" AS +"nco:PersonContact_nco:hasAffiliation8" WHERE "1_u" = +"nco:PersonContact_nco:hasAffiliation8"."ID")), (SELECT +GROUP_CONCAT("6_u", ',') FROM (SELECT +"rdfs:Resource_nao:hasTag9"."nao:hasTag" AS "6_u" FROM +"rdfs:Resource_nao:hasTag" AS "rdfs:Resource_nao:hasTag9" WHERE +"1_u" = "rdfs:Resource_nao:hasTag9"."ID")), (SELECT Uri FROM +Resource WHERE ID = "1_u"), (SELECT GROUP_CONCAT("2_u"||? COLLATE +NOCASE||COALESCE((SELECT "nco:role" FROM "nco:Affiliation" WHERE +ID = "2_u") COLLATE NOCASE, ? COLLATE NOCASE)||? COLLATE +NOCASE||COALESCE((SELECT "nco:department" FROM "nco:Affiliation" +WHERE ID = "2_u") COLLATE NOCASE, ? COLLATE NOCASE)||? COLLATE +NOCASE||COALESCE((SELECT GROUP_CONCAT("nco:title",',') FROM +"nco:Affiliation_nco:title" WHERE ID = "2_u"), ? COLLATE NOCASE), +'\n') FROM (SELECT +"nco:PersonContact_nco:hasAffiliation10"."nco:hasAffiliation" AS +"2_u" FROM "nco:PersonContact_nco:hasAffiliation" AS +"nco:PersonContact_nco:hasAffiliation10" WHERE "1_u" = +"nco:PersonContact_nco:hasAffiliation10"."ID")), (SELECT +GROUP_CONCAT("nco:note",',') FROM "nco:Contact_nco:note" WHERE ID += "1_u"), (SELECT "nco:gender" FROM "nco:PersonContact" WHERE ID += "1_u"), (SELECT GROUP_CONCAT("2_u"||? COLLATE +NOCASE||COALESCE((SELECT "nco:pobox" FROM "nco:PostalAddress" +WHERE ID = "7_u") COLLATE NOCASE, ? COLLATE NOCASE)||? COLLATE +NOCASE||COALESCE((SELECT "nco:district" FROM "nco:PostalAddress" +WHERE ID = "7_u") COLLATE NOCASE, ? COLLATE NOCASE)||? COLLATE +NOCASE||COALESCE((SELECT "nco:county" FROM "nco:PostalAddress" +WHERE ID = "7_u") COLLATE NOCASE, ? COLLATE NOCASE)||? COLLATE +NOCASE||COALESCE((SELECT "nco:locality" FROM "nco:PostalAddress" +WHERE ID = "7_u") COLLATE NOCASE, ? COLLATE NOCASE)||? COLLATE +NOCASE||COALESCE((SELECT "nco:postalcode" FROM +"nco:PostalAddress" WHERE ID = "7_u") COLLATE NOCASE, ? COLLATE +NOCASE)||? COLLATE NOCASE||COALESCE((SELECT "nco:streetAddress" +FROM "nco:PostalAddress" WHERE ID = "7_u") COLLATE NOCASE, ? +COLLATE NOCASE)||? COLLATE NOCASE||COALESCE((SELECT Uri FROM +Resource WHERE ID = (SELECT "nco:addressLocation" FROM +"nco:PostalAddress" WHERE ID = "7_u")), ? COLLATE NOCASE)||? +COLLATE NOCASE||COALESCE((SELECT "nco:extendedAddress" FROM +"nco:PostalAddress" WHERE ID = "7_u") COLLATE NOCASE, ? COLLATE +NOCASE)||? COLLATE NOCASE||COALESCE((SELECT "nco:country" FROM +"nco:PostalAddress" WHERE ID = "7_u") COLLATE NOCASE, ? COLLATE +NOCASE)||? COLLATE NOCASE||COALESCE((SELECT "nco:region" FROM +"nco:PostalAddress" WHERE ID = "7_u") COLLATE NOCASE, ? COLLATE +NOCASE), '\n') FROM (SELECT +"nco:PersonContact_nco:hasAffiliation11"."nco:hasAffiliation" AS +"2_u", "nco:Role_nco:hasPostalAddress12"."nco:hasPostalAddress" +AS "7_u" FROM "nco:PersonContact_nco:hasAffiliation" AS +"nco:PersonContact_nco:hasAffiliation11", +"nco:Role_nco:hasPostalAddress" AS +"nco:Role_nco:hasPostalAddress12" WHERE "1_u" = +"nco:PersonContact_nco:hasAffiliation11"."ID" AND +"nco:PersonContact_nco:hasAffiliation11"."nco:hasAffiliation" = +"nco:Role_nco:hasPostalAddress12"."ID")), (SELECT +GROUP_CONCAT("10_u" COLLATE NOCASE, ',') FROM (SELECT +"nie:InformationElement_nao:hasProperty13"."nao:hasProperty" AS +"8_u", "nao:Property14"."nao:propertyName" AS "9_u", +"nao:Property14"."nao:propertyValue" AS "10_u" FROM +"nie:InformationElement_nao:hasProperty" AS +"nie:InformationElement_nao:hasProperty13", "nao:Property" AS +"nao:Property14" WHERE "1_u" = +"nie:InformationElement_nao:hasProperty13"."ID" AND +"nie:InformationElement_nao:hasProperty13"."nao:hasProperty" = +"nao:Property14"."ID" AND "9_u" IS NOT NULL AND "10_u" IS NOT +NULL AND ("9_u" COLLATE NOCASE = ? COLLATE NOCASE))) FROM (SELECT +"nco:PersonContact1"."ID" AS "1_u" FROM "nco:PersonContact" AS +"nco:PersonContact1") ORDER BY "1_u"; + } +} {/.* Goto .*/} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fuzz.test b/components/external/SQLite-3.8.1/test/fuzz.test new file mode 100644 index 0000000000000000000000000000000000000000..e1b22ae804d554ee5f39ebbc8f6db7bf5455ebb1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fuzz.test @@ -0,0 +1,379 @@ +# 2007 May 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is generating semi-random strings of SQL +# (a.k.a. "fuzz") and sending it into the parser to try to +# generate errors. +# +# The tests in this file are really about testing fuzzily generated +# SQL parse-trees. The majority of the fuzzily generated SQL is +# valid as far as the parser is concerned. +# +# The most complicated trees are for SELECT statements. +# +# $Id: fuzz.test,v 1.19 2009/04/28 11:10:39 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set ::REPEATS 5000 + +# If running quick.test, don't do so many iterations. +if {[info exists ::G(isquick)]} { + if {$::G(isquick)} { set ::REPEATS 20 } +} + +source $testdir/fuzz_common.tcl +expr srand(0) + +#---------------------------------------------------------------- +# These tests caused errors that were first caught by the tests +# in this file. They are still here. +do_test fuzz-1.1 { + execsql { + SELECT 'abc' LIKE X'ABCD'; + } +} {0} +do_test fuzz-1.2 { + execsql { + SELECT 'abc' LIKE zeroblob(10); + } +} {0} +do_test fuzz-1.3 { + execsql { + SELECT zeroblob(10) LIKE 'abc'; + } +} {0} +do_test fuzz-1.4 { + execsql { + SELECT (- -21) % NOT (456 LIKE zeroblob(10)); + } +} {0} +do_test fuzz-1.5 { + execsql { + SELECT (SELECT ( + SELECT (SELECT -2147483648) FROM (SELECT 1) ORDER BY 1 + )) + } +} {-2147483648} +do_test fuzz-1.6 { + execsql { + SELECT 'abc', zeroblob(1) FROM (SELECT 1) ORDER BY 1 + } +} [execsql {SELECT 'abc', zeroblob(1)}] + +do_test fuzz-1.7 { + execsql { + SELECT ( SELECT zeroblob(1000) FROM ( + SELECT * FROM (SELECT 'first') ORDER BY NOT 'in') + ) + } +} [execsql {SELECT zeroblob(1000)}] + +do_test fuzz-1.8 { + # Problems with opcode OP_ToText (did not account for MEM_Zero). + # Also MemExpandBlob() was marking expanded blobs as nul-terminated. + # They are not. + execsql { + SELECT CAST(zeroblob(1000) AS text); + } +} {{}} + +do_test fuzz-1.9 { + # This was causing a NULL pointer dereference of Expr.pList. + execsql { + SELECT 1 FROM (SELECT * FROM sqlite_master WHERE random()) + } +} {} + +do_test fuzz-1.10 { + # Bug in calculation of Parse.ckOffset causing an assert() + # to fail. Probably harmless. + execsql { + SELECT coalesce(1, substr( 1, 2, length('in' IN (SELECT 1)))) + } +} {1} + +do_test fuzz-1.11 { + # The literals (A, B, C, D) are not important, they are just used + # to make the EXPLAIN output easier to read. + # + # The problem here is that the EXISTS(...) expression leaves an + # extra value on the VDBE stack. This is confusing the parent and + # leads to an assert() failure when OP_Insert encounters an integer + # when it expects a record blob. + # + # Update: Any query with (LIMIT 0) was leaking stack. + # + execsql { + SELECT 'A' FROM (SELECT 'B') ORDER BY EXISTS ( + SELECT 'C' FROM (SELECT 'D' LIMIT 0) + ) + } +} {A} + +do_test fuzz-1.12.1 { + # Create a table with a single row. + execsql { + CREATE TABLE abc(b); + INSERT INTO abc VALUES('ABCDE'); + } + + # The following query was crashing. The later subquery (in the FROM) + # clause was flattened into the parent, but the code was not repairng + # the "b" reference in the other sub-query. When the query was executed, + # that "b" refered to a non-existant vdbe table-cursor. + # + execsql { + SELECT 1 IN ( SELECT b UNION SELECT 1 ) FROM (SELECT b FROM abc); + } +} {1} +do_test fuzz-1.12.2 { + # Clean up after the previous query. + execsql { + DROP TABLE abc; + } +} {} + + +do_test fuzz-1.13 { + # The problem here was that when there were more expressions in + # the ORDER BY list than the result-set list. The temporary b-tree + # used for sorting was being misconfigured in this case. + # + execsql { + SELECT 'abcd' UNION SELECT 'efgh' ORDER BY 1 ASC, 1 ASC; + } +} {abcd efgh} + +do_test fuzz-1.14.1 { + execsql { + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(123, 456, 789); + } + + # The [a] reference in the sub-select was causing a problem. Because + # the internal walkSelectExpr() function was not considering compound + # SELECT operators. + execsql { + SELECT 1 FROM abc + GROUP BY c HAVING EXISTS (SELECT a UNION SELECT 123); + } +} {1} +do_test fuzz-1.14.2 { + execsql { + DROP TABLE abc; + } +} {} + +# Making sure previously discovered errors have been fixed. +# +do_test fuzz-1.15 { + execsql { + SELECT hex(CAST(zeroblob(1000) AS integer)) + } +} {30} + +do_test fuzz-1.16.1 { + execsql { + CREATE TABLE abc(a, b, c); + CREATE TABLE def(a, b, c); + CREATE TABLE ghi(a, b, c); + } +} {} +do_test fuzz-1.16.2 { + catchsql { + SELECT DISTINCT EXISTS( + SELECT 1 + FROM ( + SELECT C FROM (SELECT 1) + ) + WHERE (SELECT c) + ) + FROM abc + } +} {0 {}} +do_test fuzz-1.16.3 { + catchsql { + SELECT DISTINCT substr(-456 ISNULL,zeroblob(1000), EXISTS( + SELECT DISTINCT EXISTS( + SELECT DISTINCT b FROM abc + ORDER BY EXISTS ( + SELECT DISTINCT 2147483647 UNION ALL SELECT -2147483648 + ) ASC + ) + FROM ( + SELECT c, c FROM ( + SELECT 456, 'injection' ORDER BY 56.1 ASC, -56.1 DESC + ) + ) + GROUP BY (SELECT ALL (SELECT DISTINCT 'hardware')) + HAVING ( + SELECT DISTINCT c + FROM ( + SELECT ALL -2147483648, 'experiments' + ORDER BY -56.1 ASC, -56.1 DESC + ) + GROUP BY (SELECT DISTINCT 456) IN + (SELECT DISTINCT 'injection') NOT IN (SELECT ALL -456) + HAVING EXISTS ( + SELECT ALL 'injection' + ) + ) + UNION ALL + SELECT a IN ( + SELECT -2147483647 + UNION ALL + SELECT ALL 'injection' + ) + FROM sqlite_master + ) -- end EXISTS + ) /* end SUBSTR() */, c NOTNULL ISNULL + FROM abc + ORDER BY CAST(-56.1 AS blob) ASC + } +} {0 {}} +do_test fuzz-1.16.4 { + execsql { + DROP TABLE abc; DROP TABLE def; DROP TABLE ghi; + } +} {} + +do_test fuzz-1.17 { + catchsql { + SELECT 'hardware', 56.1 NOTNULL, random()&0 + FROM ( + SELECT ALL lower(~ EXISTS ( + SELECT 1 NOT IN (SELECT ALL 1) + )), CAST(456 AS integer), -2147483647 + FROM ( + SELECT DISTINCT -456, CAST(1 AS integer) ISNULL + FROM (SELECT ALL 2147483647, typeof(2147483649)) + ) + ) + GROUP BY CAST(CAST('experiments' AS blob) AS blob) + HAVING random() + } +} {0 {hardware 1 0}} + +do_test fuzz-1.18 { + catchsql { + SELECT -2147483649 << upper('fault' NOT IN ( + SELECT ALL ( + SELECT ALL -1 + ORDER BY -2147483649 + LIMIT ( + SELECT ALL ( + SELECT 0 EXCEPT SELECT DISTINCT 'experiments' ORDER BY 1 ASC + ) + ) + OFFSET EXISTS ( + SELECT ALL + (SELECT ALL -2147483648) NOT IN ( + SELECT ALL 123456789.1234567899 + ) IN (SELECT 2147483649) + FROM sqlite_master + ) NOT IN (SELECT ALL 'The') + ) + )) + } +} {0 -4294967298} + +# At one point the following INSERT statement caused an assert() to fail. +# +do_test fuzz-1.19 { + execsql { CREATE TABLE t1(a) } + catchsql { + INSERT INTO t1 VALUES( + CASE WHEN NULL THEN NULL ELSE ( SELECT 0 ORDER BY 456 ) END + ) + } +} {1 {1st ORDER BY term out of range - should be between 1 and 1}} +do_test fuzz-1.20 { + execsql { DROP TABLE t1 } +} {} + +#---------------------------------------------------------------- +# Test some fuzzily generated expressions. +# +do_fuzzy_test fuzz-2 -template { SELECT [Expr] } + +do_test fuzz-3.1 { + execsql { + CREATE TABLE abc(a, b, c); + CREATE TABLE def(a, b, c); + CREATE TABLE ghi(a, b, c); + } +} {} +set ::TableList [list abc def ghi] + +#---------------------------------------------------------------- +# Test some fuzzily generated SELECT statements. +# +do_fuzzy_test fuzz-3.2 -template {[Select]} + +#---------------------------------------------------------------- +# Insert a small amount of data into the database and then run +# some more generated SELECT statements. +# +do_test fuzz-4.1 { + execsql { + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, 6); + INSERT INTO abc VALUES(7, 8, 9); + INSERT INTO def VALUES(1, 2, 3); + INSERT INTO def VALUES(4, 5, 6); + INSERT INTO def VALUES(7, 8, 9); + INSERT INTO ghi VALUES(1, 2, 3); + INSERT INTO ghi VALUES(4, 5, 6); + INSERT INTO ghi VALUES(7, 8, 9); + CREATE INDEX abc_i ON abc(a, b, c); + CREATE INDEX def_i ON def(c, a, b); + CREATE INDEX ghi_i ON ghi(b, c, a); + } +} {} +do_fuzzy_test fuzz-4.2 -template {[Select]} + +#---------------------------------------------------------------- +# Test some fuzzy INSERT statements: +# +do_test fuzz-5.1 {execsql BEGIN} {} +do_fuzzy_test fuzz-5.2 -template {[Insert]} -errorlist table +integrity_check fuzz-5.2.integrity +do_test fuzz-5.3 {execsql COMMIT} {} +integrity_check fuzz-5.4.integrity + +#---------------------------------------------------------------- +# Now that there is data in the database, run some more SELECT +# statements +# +set ::ColumnList [list a b c] +set E {{no such col} {ambiguous column name}} +do_fuzzy_test fuzz-6.1 -template {[Select]} -errorlist $E + +#---------------------------------------------------------------- +# Run some SELECTs, INSERTs, UPDATEs and DELETEs in a transaction. +# +set E {{no such col} {ambiguous column name} {table}} +do_test fuzz-7.1 {execsql BEGIN} {} +do_fuzzy_test fuzz-7.2 -template {[Statement]} -errorlist $E +integrity_check fuzz-7.3.integrity +do_test fuzz-7.4 {execsql COMMIT} {} +integrity_check fuzz-7.5.integrity + +#---------------------------------------------------------------- +# Many CREATE and DROP TABLE statements: +# +set E [list table duplicate {no such col} {ambiguous column name} {use DROP}] +do_fuzzy_test fuzz-8.1 -template {[CreateOrDropTableOrView]} -errorlist $E + +close $::log +finish_test diff --git a/components/external/SQLite-3.8.1/test/fuzz2.test b/components/external/SQLite-3.8.1/test/fuzz2.test new file mode 100644 index 0000000000000000000000000000000000000000..989b00f056afe1bf3b5e21c0d540e62d4eaa54fd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fuzz2.test @@ -0,0 +1,108 @@ +# 2007 May 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file checks error recovery from malformed SQL strings. +# +# $Id: fuzz2.test,v 1.3 2007/05/15 16:51:37 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +proc fuzzcatch {sql} { + return [lindex [catchsql $sql] 0] +} + +do_test fuzz2-1.1 { + fuzzcatch {SELECT ALL "AAAAAA" . * GROUP BY LIMIT round(1), #12} +} {1} +do_test fuzz2-2.0 { + fuzzcatch {SELECT + #100} +} {1} +do_test fuzz2-2.1 { + fuzzcatch {SELECT 1 WHERE ( #61 NOT MATCH ROUND( 1 ) )} +} {1} +do_test fuzz2-2.2 { + fuzzcatch {SELECT 1 LIMIT NOT #59 COLLATE AAAAAA NOT IN + ( "AAAAAA" NOTNULL <= x'414141414141' IS NULL , ( ROUND ( 1.0 ) ) )} +} {1} +do_test fuzz2-2.3 { + fuzzcatch {INSERT OR REPLACE INTO AAAAAA . "AAAAAA" ( "AAAAAA" ) SELECT DISTINCT * , ( SELECT #252 IN ( SELECT DISTINCT AAAAAA . * ) )} +} {1} +do_test fuzz2-2.4 { + fuzzcatch {SELECT 1 LIMIT NOT #59 COLLATE AAAAAA NOT IN round(1.0)} +} {1} +do_test fuzz2-2.5 { + fuzzcatch {SELECT( #239 )} +} {1} +do_test fuzz2-2.6 { + fuzzcatch {DELETE FROM AAAAAA WHERE #65 NOT NULL} +} {1} +do_test fuzz2-2.7 { + fuzzcatch {ATTACH ROUND( 1.0 ) in AAAAAA . "AAAAAA" AS #122 ISNULL} +} {1} +do_test fuzz2-2.8 { + fuzzcatch {SELECT 1 LIMIT #122 ISNULL} +} {1} +do_test fuzz2-2.9 { + fuzzcatch {CREATE VIEW AAAAAA . "AAAAAA" AS SELECT DISTINCT #162 IS NULL "AAAAAA"} +} {1} +do_test fuzz2-2.10 { + fuzzcatch {DELETE FROM AAAAAA WHERE #202 IS NOT NULL ISNULL} +} {1} +do_test fuzz2-2.11 { + fuzzcatch {UPDATE OR IGNORE "AAAAAA" . "AAAAAA" SET "AAAAAA" = NOT #96} +} {1} +do_test fuzz2-2.12 { + fuzzcatch {SELECT - #196} +} {1} + +ifcapable {trigger} { # Only do the following tests if triggers are enabled + +do_test fuzz2-3.0 { + fuzzcatch {CREATE TRIGGER "AAAAAA" . "AAAAAA" AFTER UPDATE OF "AAAAAA" , "AAAAAA" ON "AAAAAA" . "AAAAAA" FOR EACH ROW BEGIN UPDATE AAAAAA SET "AAAAAA" = #162; END} +} {1} +do_test fuzz2-3.1 { + fuzzcatch {CREATE TRIGGER IF NOT EXISTS "AAAAAA" UPDATE ON "AAAAAA" . AAAAAA FOR EACH ROW BEGIN DELETE FROM "AAAAAA" ; INSERT INTO AAAAAA ( "AAAAAA" ) SELECT DISTINCT "AAAAAA" "AAAAAA" , #167 AAAAAA , "AAAAAA" . * ORDER BY "AAAAAA" ASC , x'414141414141' BETWEEN RAISE ( FAIL , "AAAAAA" ) AND AAAAAA ( * ) NOT NULL DESC LIMIT AAAAAA ; REPLACE INTO AAAAAA ( AAAAAA ) VALUES ( AAAAAA ( * ) ) ; END} +} {1} +do_test fuzz2-3.2 { + fuzzcatch {CREATE TEMP TRIGGER IF NOT EXISTS AAAAAA . "AAAAAA" BEFORE UPDATE OF "AAAAAA" ON AAAAAA . "AAAAAA" BEGIN SELECT ALL * , #175 "AAAAAA" FROM "AAAAAA" . AAAAAA; END} +} {1} + +} ;# End of ifcapable {trigger} + +do_test fuzz2-4.0 { + fuzzcatch {ATTACH DATABASE #168 AS whatever} +} {1} +do_test fuzz2-4.1 { + fuzzcatch {DETACH #133} +} {1} +do_test fuzz2-5.0 { + fuzzcatch {SELECT 1 LIMIT ( SELECT DISTINCT * , AAAAAA , * , AAAAAA , "AAAAAA" . * FROM "AAAAAA" ON ROUND( 1 ) COLLATE AAAAAA OR "AAAAAA" USING ( AAAAAA , "AAAAAA" ) WHERE ROUND( 1 ) GROUP BY ORDER BY #84 ASC , #44 DESC , ( SELECT "AAAAAA" . * , "AAAAAA" . * FROM , ( ) "AAAAAA" USING ( )} +} {1} +do_test fuzz2-5.1 { + fuzzcatch {SELECT 1 WHERE 1 == AAAAAA ( * ) BETWEEN + - ~ + "AAAAAA" . AAAAAA | RAISE ( IGNORE ) COLLATE AAAAAA NOT IN ( SELECT DISTINCT "AAAAAA" . * , * , * WHERE ( SELECT ALL AAAAAA AS "AAAAAA" HAVING CAST ( "AAAAAA" . "AAAAAA" . "AAAAAA" AS AAAAAA ) ORDER BY , , IS NULL ASC , ~ AND DESC LIMIT ( ( "AAAAAA" ) NOT BETWEEN ( ) NOT IN ( ) AND AAAAAA ( ) IS NOT NULL ) OFFSET AAAAAA ( ALL , , ) ) GROUP BY ORDER BY "AAAAAA" . AAAAAA ASC , NULL IN ( SELECT UNION ALL SELECT ALL WHERE HAVING ORDER BY LIMIT UNION SELECT DISTINCT FROM ( ) WHERE + HAVING >> ORDER BY LIMIT . . , "AAAAAA" ) , CAST ( ~ "AAAAAA" . AAAAAA AS "AAAAAA" AAAAAA "AAAAAA" ( + 4294967295 , - 4294967296.0 ) ) ASC LIMIT AAAAAA INTERSECT SELECT ALL * GROUP BY , AAAAAA ( DISTINCT , ) != #241 NOT IN ( , , ) , , CTIME_KW HAVING AAAAAA ORDER BY #103 DESC , #81 ASC LIMIT AAAAAA OFFSET ~ AAAAAA ( ALL AAAAAA . AAAAAA >= AAAAAA . "AAAAAA" . "AAAAAA" ) ) NOTNULL NOT NULL} +} {1} +do_test fuzz2-5.2 { + fuzzcatch {SELECT 1 WHERE 1 == AAAAAA ( * ) BETWEEN + - ~ + "AAAAAA" . AAAAAA | RAISE ( IGNORE ) COLLATE AAAAAA NOT IN ( SELECT DISTINCT "AAAAAA" . * , * , * WHERE ( SELECT ALL AAAAAA AS "AAAAAA" HAVING CAST ( "AAAAAA" . "AAAAAA" . "AAAAAA" AS AAAAAA ) ORDER BY , , IS NULL ASC , ~ AND DESC LIMIT ( ( "AAAAAA" ) NOT BETWEEN ( ) NOT IN ( ) AND AAAAAA ( ) IS NOT NULL ) OFFSET AAAAAA ( ALL , , ) ) GROUP BY ORDER BY "AAAAAA" . AAAAAA ASC , NULL IN ( SELECT UNION ALL SELECT ALL WHERE HAVING ORDER BY LIMIT UNION SELECT DISTINCT FROM ( ) WHERE + HAVING >> ORDER BY LIMIT . . , "AAAAAA" ) , CAST ( ~ "AAAAAA" . AAAAAA AS "AAAAAA" AAAAAA "AAAAAA" ( + 4294967295 , - 4294967296.0 ) ) ASC LIMIT AAAAAA INTERSECT SELECT ALL * GROUP BY , AAAAAA ( DISTINCT , ) != #241 NOT IN ( , , ) , , CTIME_KW HAVING AAAAAA ORDER BY #103 DESC , #81 ASC LIMIT AAAAAA OFFSET ~ AAAAAA ( ALL AAAAAA . AAAAAA >= AAAAAA . "AAAAAA" . "AAAAAA" ) ) NOTNULL NOT NULL} +} {1} +do_test fuzz2-5.3 { + fuzzcatch {UPDATE "AAAAAA" SET "AAAAAA" = - EXISTS ( SELECT DISTINCT * , * ORDER BY #202 ASC , #147 , ~ AAAAAA . "AAAAAA" ASC LIMIT AAAAAA . "AAAAAA" , RAISE ( ABORT , AAAAAA ) UNION ALL SELECT DISTINCT AAAAAA . * , * FROM ( SELECT DISTINCT} +} {1} +do_test fuzz2-5.4 { + fuzzcatch {REPLACE INTO AAAAAA SELECT DISTINCT "AAAAAA" . * WHERE AAAAAA ( AAAAAA ( ) ) GROUP BY AAAAAA . AAAAAA . "AAAAAA" IN "AAAAAA" | AAAAAA ( ALL , ) ORDER BY #238, #92 DESC LIMIT 0 OFFSET - RAISE ( IGNORE ) NOT NULL > RAISE ( IGNORE ) IS NULL} +} {1} +do_test fuzz2-5.5 { + fuzzcatch {SELECT ALL * GROUP BY EXISTS ( SELECT "AAAAAA" . * , AAAAAA ( * ) AS AAAAAA FROM "AAAAAA" . "AAAAAA" AS "AAAAAA" USING ( AAAAAA , "AAAAAA" , "AAAAAA" ) WHERE AAAAAA ( DISTINCT ) - RAISE ( FAIL , "AAAAAA" ) HAVING "AAAAAA" . "AAAAAA" . AAAAAA ORDER BY #182 , #55 ) BETWEEN EXISTS ( SELECT ALL * FROM ( ( } +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fuzz3.test b/components/external/SQLite-3.8.1/test/fuzz3.test new file mode 100644 index 0000000000000000000000000000000000000000..d0efc5250e178c4c7c5dee768e51b263c2f065f7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fuzz3.test @@ -0,0 +1,169 @@ +# 2007 May 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus +# of this file is checking the libraries response to subtly corrupting +# the database file by changing the values of pseudo-randomly selected +# bytes. +# +# $Id: fuzz3.test,v 1.3 2009/01/05 17:19:03 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +expr srand(123) + +proc rstring {n} { + set str s + while {[string length $str] < $n} { + append str [expr rand()] + } + return [string range $str 0 $n] +} + +# Return a randomly generated SQL literal. +# +proc rvalue {} { + switch -- [expr int(rand()*5)] { + 0 { # SQL NULL value. + return NULL + } + 1 { # Integer value. + return [expr int(rand()*1024)] + } + 2 { # Real value. + return [expr rand()] + } + 3 { # String value. + set n [expr int(rand()*2500)] + return "'[rstring $n]'" + } + 4 { # Blob value. + set n [expr int(rand()*2500)] + return "CAST('[rstring $n]' AS BLOB)" + } + } +} + +proc db_checksum {} { + set cksum [execsql { SELECT md5sum(a, b, c) FROM t1 }] + append cksum [execsql { SELECT md5sum(d, e, f) FROM t2 }] + set cksum +} + +# Modify a single byte in the file 'test.db' using tcl IO commands. The +# argument value, which must be an integer, determines both the offset of +# the byte that is modified, and the value that it is set to. The lower +# 8 bits of iMod determine the new byte value. The offset of the byte +# modified is the value of ($iMod >> 8). +# +# The return value is the iMod value required to restore the file +# to its original state. The command: +# +# modify_database [modify_database $x] +# +# leaves the file in the same state as it was in at the start of the +# command (assuming that the file is at least ($x>>8) bytes in size). +# +proc modify_database {iMod} { + set blob [binary format c [expr {$iMod&0xFF}]] + set offset [expr {$iMod>>8}] + + set fd [open test.db r+] + fconfigure $fd -encoding binary -translation binary + seek $fd $offset + set old_blob [read $fd 1] + seek $fd $offset + puts -nonewline $fd $blob + close $fd + + binary scan $old_blob c iOld + return [expr {($offset<<8) + ($iOld&0xFF)}] +} + +proc purge_pcache {} { + ifcapable !memorymanage { + db close + sqlite3 db test.db + } else { + sqlite3_release_memory 10000000 + } + if {[lindex [pcache_stats] 1] != 0} { + error "purge_pcache failed: [pcache_stats]" + } +} + +# This block creates a database to work with. +# +do_test fuzz3-1 { + execsql { + BEGIN; + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(d, e, f); + CREATE INDEX i1 ON t1(a, b, c); + CREATE INDEX i2 ON t2(d, e, f); + } + for {set i 0} {$i < 50} {incr i} { + execsql "INSERT INTO t1 VALUES([rvalue], [rvalue], [rvalue])" + execsql "INSERT INTO t2 VALUES([rvalue], [rvalue], [rvalue])" + } + execsql COMMIT +} {} + +set ::cksum [db_checksum] +do_test fuzz3-2 { + db_checksum +} $::cksum + +for {set ii 0} {$ii < 5000} {incr ii} { + purge_pcache + + # Randomly modify a single byte of the database file somewhere within + # the first 100KB of the file. + set iNew [expr int(rand()*5*1024*256)] + set iOld [modify_database $iNew] + + set iTest 0 + foreach sql { + {SELECT * FROM t2 ORDER BY d} + {SELECT * FROM t1} + {SELECT * FROM t2} + {SELECT * FROM t1 ORDER BY a} + {SELECT * FROM t1 WHERE a = (SELECT a FROM t1 WHERE rowid=25)} + {SELECT * FROM t2 WHERE d = (SELECT d FROM t2 WHERE rowid=1)} + {SELECT * FROM t2 WHERE d = (SELECT d FROM t2 WHERE rowid=50)} + {PRAGMA integrity_check} + } { + do_test fuzz3-$ii.$iNew.[incr iTest] { + foreach {rc msg} [catchsql $sql] {} + if {$rc == 0 + || $msg eq "database or disk is full" + || $msg eq "database disk image is malformed" + || $msg eq "file is encrypted or is not a database" + || [string match "malformed database schema*" $msg] + } { + set msg ok + } + set msg + } {ok} + } + + # Restore the original database file content. Test that the correct + # checksum is now returned. + # + purge_pcache + modify_database $iOld + do_test fuzz3-$ii.$iNew.[incr iTest] { + db_checksum + } $::cksum +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fuzz_common.tcl b/components/external/SQLite-3.8.1/test/fuzz_common.tcl new file mode 100644 index 0000000000000000000000000000000000000000..4ab7dff5c9ba7256e52e1a45bb1fbb04bffa975d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fuzz_common.tcl @@ -0,0 +1,391 @@ +# 2007 May 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: fuzz_common.tcl,v 1.2 2009/01/05 19:36:30 drh Exp $ + +proc fuzz {TemplateList} { + set n [llength $TemplateList] + set i [expr {int(rand()*$n)}] + set r [uplevel 1 subst -novar [list [lindex $TemplateList $i]]] + + string map {"\n" " "} $r +} + +# Fuzzy generation primitives: +# +# Literal +# UnaryOp +# BinaryOp +# Expr +# Table +# Select +# Insert +# + +# Returns a string representing an SQL literal. +# +proc Literal {} { + set TemplateList { + 456 0 -456 1 -1 + 2147483648 2147483647 2147483649 -2147483647 -2147483648 -2147483649 + 'The' 'first' 'experiments' 'in' 'hardware' 'fault' 'injection' + zeroblob(1000) + NULL + 56.1 -56.1 + 123456789.1234567899 + } + fuzz $TemplateList +} + +# Returns a string containing an SQL unary operator (e.g. "+" or "NOT"). +# +proc UnaryOp {} { + set TemplateList {+ - NOT ~} + fuzz $TemplateList +} + +# Returns a string containing an SQL binary operator (e.g. "*" or "/"). +# +proc BinaryOp {} { + set TemplateList { + || * / % + - << >> & | < <= > >= = == != <> AND OR + LIKE GLOB {NOT LIKE} + } + fuzz $TemplateList +} + +# Return the complete text of an SQL expression. +# +set ::ExprDepth 0 +proc Expr { {c {}} } { + incr ::ExprDepth + + set TemplateList [concat $c $c $c {[Literal]}] + if {$::ExprDepth < 3} { + lappend TemplateList \ + {[Expr $c] [BinaryOp] [Expr $c]} \ + {[UnaryOp] [Expr $c]} \ + {[Expr $c] ISNULL} \ + {[Expr $c] NOTNULL} \ + {CAST([Expr $c] AS blob)} \ + {CAST([Expr $c] AS text)} \ + {CAST([Expr $c] AS integer)} \ + {CAST([Expr $c] AS real)} \ + {abs([Expr])} \ + {coalesce([Expr], [Expr])} \ + {hex([Expr])} \ + {length([Expr])} \ + {lower([Expr])} \ + {upper([Expr])} \ + {quote([Expr])} \ + {random()} \ + {randomblob(min(max([Expr],1), 500))} \ + {typeof([Expr])} \ + {substr([Expr],[Expr],[Expr])} \ + {CASE WHEN [Expr $c] THEN [Expr $c] ELSE [Expr $c] END} \ + {[Literal]} {[Literal]} {[Literal]} \ + {[Literal]} {[Literal]} {[Literal]} \ + {[Literal]} {[Literal]} {[Literal]} \ + {[Literal]} {[Literal]} {[Literal]} + } + if {$::SelectDepth < 4} { + lappend TemplateList \ + {([Select 1])} \ + {[Expr $c] IN ([Select 1])} \ + {[Expr $c] NOT IN ([Select 1])} \ + {EXISTS ([Select 1])} \ + } + set res [fuzz $TemplateList] + incr ::ExprDepth -1 + return $res +} + +# Return a valid table name. +# +set ::TableList [list] +proc Table {} { + set TemplateList [concat sqlite_master $::TableList] + fuzz $TemplateList +} + +# Return one of: +# +# "SELECT DISTINCT", "SELECT ALL" or "SELECT" +# +proc SelectKw {} { + set TemplateList { + "SELECT DISTINCT" + "SELECT ALL" + "SELECT" + } + fuzz $TemplateList +} + +# Return a result set for a SELECT statement. +# +proc ResultSet {{nRes 0} {c ""}} { + if {$nRes == 0} { + set nRes [expr {rand()*2 + 1}] + } + + set aRes [list] + for {set ii 0} {$ii < $nRes} {incr ii} { + lappend aRes [Expr $c] + } + + join $aRes ", " +} + +set ::SelectDepth 0 +set ::ColumnList [list] +proc SimpleSelect {{nRes 0}} { + + set TemplateList { + {[SelectKw] [ResultSet $nRes]} + } + + # The ::SelectDepth variable contains the number of ancestor SELECT + # statements (i.e. for a top level SELECT it is set to 0, for a + # sub-select 1, for a sub-select of a sub-select 2 etc.). + # + # If this is already greater than 3, do not generate a complicated + # SELECT statement. This tends to cause parser stack overflow (too + # boring to bother with). + # + if {$::SelectDepth < 4} { + lappend TemplateList \ + {[SelectKw] [ResultSet $nRes $::ColumnList] FROM ([Select])} \ + {[SelectKw] [ResultSet $nRes] FROM ([Select])} \ + {[SelectKw] [ResultSet $nRes $::ColumnList] FROM [Table]} \ + { + [SelectKw] [ResultSet $nRes $::ColumnList] + FROM ([Select]) + GROUP BY [Expr] + HAVING [Expr] + } \ + + if {0 == $nRes} { + lappend TemplateList \ + {[SelectKw] * FROM ([Select])} \ + {[SelectKw] * FROM [Table]} \ + {[SelectKw] * FROM [Table] WHERE [Expr $::ColumnList]} \ + { + [SelectKw] * + FROM [Table],[Table] AS t2 + WHERE [Expr $::ColumnList] + } { + [SelectKw] * + FROM [Table] LEFT OUTER JOIN [Table] AS t2 + ON [Expr $::ColumnList] + WHERE [Expr $::ColumnList] + } + } + } + + fuzz $TemplateList +} + +# Return a SELECT statement. +# +# If boolean parameter $isExpr is set to true, make sure the +# returned SELECT statement returns a single column of data. +# +proc Select {{nMulti 0}} { + set TemplateList { + {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} + {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} + {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} + {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} {[SimpleSelect $nMulti]} + {[SimpleSelect $nMulti] ORDER BY [Expr] DESC} + {[SimpleSelect $nMulti] ORDER BY [Expr] ASC} + {[SimpleSelect $nMulti] ORDER BY [Expr] ASC, [Expr] DESC} + {[SimpleSelect $nMulti] ORDER BY [Expr] LIMIT [Expr] OFFSET [Expr]} + } + + if {$::SelectDepth < 4} { + if {$nMulti == 0} { + set nMulti [expr {(rand()*2)+1}] + } + lappend TemplateList \ + {[SimpleSelect $nMulti] UNION [Select $nMulti]} \ + {[SimpleSelect $nMulti] UNION ALL [Select $nMulti]} \ + {[SimpleSelect $nMulti] EXCEPT [Select $nMulti]} \ + {[SimpleSelect $nMulti] INTERSECT [Select $nMulti]} + } + + incr ::SelectDepth + set res [fuzz $TemplateList] + incr ::SelectDepth -1 + set res +} + +# Generate and return a fuzzy INSERT statement. +# +proc Insert {} { + set TemplateList { + {INSERT INTO [Table] VALUES([Expr], [Expr], [Expr]);} + {INSERT INTO [Table] VALUES([Expr], [Expr], [Expr], [Expr]);} + {INSERT INTO [Table] VALUES([Expr], [Expr]);} + } + fuzz $TemplateList +} + +proc Column {} { + fuzz $::ColumnList +} + +# Generate and return a fuzzy UPDATE statement. +# +proc Update {} { + set TemplateList { + {UPDATE [Table] + SET [Column] = [Expr $::ColumnList] + WHERE [Expr $::ColumnList]} + } + fuzz $TemplateList +} + +proc Delete {} { + set TemplateList { + {DELETE FROM [Table] WHERE [Expr $::ColumnList]} + } + fuzz $TemplateList +} + +proc Statement {} { + set TemplateList { + {[Update]} + {[Insert]} + {[Select]} + {[Delete]} + } + fuzz $TemplateList +} + +# Return an identifier. This just chooses randomly from a fixed set +# of strings. +proc Identifier {} { + set TemplateList { + This just chooses randomly a fixed + We would also thank the developers + for their analysis Samba + } + fuzz $TemplateList +} + +proc Check {} { + # Use a large value for $::SelectDepth, because sub-selects are + # not allowed in expressions used by CHECK constraints. + # + set sd $::SelectDepth + set ::SelectDepth 500 + set TemplateList { + {} + {CHECK ([Expr])} + } + set res [fuzz $TemplateList] + set ::SelectDepth $sd + set res +} + +proc Coltype {} { + set TemplateList { + {INTEGER PRIMARY KEY} + {VARCHAR [Check]} + {PRIMARY KEY} + } + fuzz $TemplateList +} + +proc DropTable {} { + set TemplateList { + {DROP TABLE IF EXISTS [Identifier]} + } + fuzz $TemplateList +} + +proc CreateView {} { + set TemplateList { + {CREATE VIEW [Identifier] AS [Select]} + } + fuzz $TemplateList +} +proc DropView {} { + set TemplateList { + {DROP VIEW IF EXISTS [Identifier]} + } + fuzz $TemplateList +} + +proc CreateTable {} { + set TemplateList { + {CREATE TABLE [Identifier]([Identifier] [Coltype], [Identifier] [Coltype])} + {CREATE TEMP TABLE [Identifier]([Identifier] [Coltype])} + } + fuzz $TemplateList +} + +proc CreateOrDropTableOrView {} { + set TemplateList { + {[CreateTable]} + {[DropTable]} + {[CreateView]} + {[DropView]} + } + fuzz $TemplateList +} + +######################################################################## + +set ::log [open fuzzy.log w] + +# +# Usage: do_fuzzy_test ?? +# +# -template +# -errorlist +# -repeats +# +proc do_fuzzy_test {testname args} { + set ::fuzzyopts(-errorlist) [list] + set ::fuzzyopts(-repeats) $::REPEATS + array set ::fuzzyopts $args + + lappend ::fuzzyopts(-errorlist) {parser stack overflow} + lappend ::fuzzyopts(-errorlist) {ORDER BY} + lappend ::fuzzyopts(-errorlist) {GROUP BY} + lappend ::fuzzyopts(-errorlist) {datatype mismatch} + + for {set ii 0} {$ii < $::fuzzyopts(-repeats)} {incr ii} { + do_test ${testname}.$ii { + set ::sql [subst $::fuzzyopts(-template)] + puts $::log $::sql + flush $::log + set rc [catch {execsql $::sql} msg] + set e 1 + if {$rc} { + set e 0 + foreach error $::fuzzyopts(-errorlist) { + if {[string first $error $msg]>=0} { + set e 1 + break + } + } + } + if {$e == 0} { + puts "" + puts $::sql + puts $msg + } + set e + } {1} + } +} diff --git a/components/external/SQLite-3.8.1/test/fuzz_malloc.test b/components/external/SQLite-3.8.1/test/fuzz_malloc.test new file mode 100644 index 0000000000000000000000000000000000000000..1e31babd92e0d6b6fb2f9aeda6fbd1a4495b4ac6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fuzz_malloc.test @@ -0,0 +1,94 @@ +# +# 2007 May 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests malloc failures in concert with fuzzy SQL generation. +# +# $Id: fuzz_malloc.test,v 1.10 2008/08/20 16:35:10 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !memdebug { + finish_test + return +} + +source $testdir/malloc_common.tcl +source $testdir/fuzz_common.tcl + +if {[info exists G(isquick)]} { + set ::REPEATS 20 +} elseif {[info exists G(issoak)]} { + set ::REPEATS 100 +} else { + set ::REPEATS 40 +} + +# +# Usage: do_fuzzy_malloc_test ?? +# +# -template +# -sqlprep +# -repeats +# +proc do_fuzzy_malloc_test {testname args} { + set ::fuzzyopts(-repeats) $::REPEATS + set ::fuzzyopts(-sqlprep) {} + array set ::fuzzyopts $args + + sqlite3_memdebug_fail -1 + db close + delete_file test.db test.db-journal + sqlite3 db test.db + set ::prep $::fuzzyopts(-sqlprep) + execsql $::prep + set jj 0 + for {set ii 0} {$ii < $::fuzzyopts(-repeats)} {incr ii} { + expr srand($jj) + incr jj + set ::sql [subst $::fuzzyopts(-template)] + # puts fuzyy-sql=\[$::sql\]; flush stdout + foreach {rc res} [catchsql "$::sql"] {} + if {$rc==0} { + do_malloc_test $testname-$ii -sqlbody $::sql -sqlprep $::prep + } else { + incr ii -1 + } + } +} + +#---------------------------------------------------------------- +# Test malloc failure during parsing (and execution) of a fuzzily +# generated expressions. +# +do_fuzzy_malloc_test fuzzy_malloc-1 -template {Select [Expr]} +do_fuzzy_malloc_test fuzzy_malloc-2 -template {[Select]} + +set ::SQLPREP { + BEGIN; + CREATE TABLE abc(a, b, c); + CREATE TABLE def(a, b, c); + CREATE TABLE ghi(a, b, c); + INSERT INTO abc VALUES(1.5, 3, 'a short string'); + INSERT INTO def VALUES(NULL, X'ABCDEF', + 'a longer string. Long enough that it doesn''t fit in Mem.zShort'); + INSERT INTO ghi VALUES(zeroblob(1000), 'hello world', -1257900987654321); + COMMIT; +} +set ::TableList [list abc def ghi] +set ::ColumnList [list a b c] + +do_fuzzy_malloc_test fuzzy_malloc-3 \ + -template {[Select]} \ + -sqlprep $::SQLPREP + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fuzzer1.test b/components/external/SQLite-3.8.1/test/fuzzer1.test new file mode 100644 index 0000000000000000000000000000000000000000..4ee573080762edbe2f658c7dd19a6a793ef7ecdf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fuzzer1.test @@ -0,0 +1,1866 @@ +# 2011 March 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for TCL interface to the +# SQLite library. +# +# The focus of the tests is the word-fuzzer virtual table. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +set ::testprefix fuzzer1 + +load_static_extension db fuzzer + +# Check configuration errors. +# +do_catchsql_test fuzzer1-1.1 { + CREATE VIRTUAL TABLE f USING fuzzer; +} {1 {fuzzer: wrong number of CREATE VIRTUAL TABLE arguments}} + +do_catchsql_test fuzzer1-1.2 { + CREATE VIRTUAL TABLE f USING fuzzer(one, two); +} {1 {fuzzer: wrong number of CREATE VIRTUAL TABLE arguments}} + +do_catchsql_test fuzzer1-1.3 { + CREATE VIRTUAL TABLE f USING fuzzer(nosuchtable); +} {1 {fuzzer: no such table: main.nosuchtable}} + +do_catchsql_test fuzzer1-1.4 { + CREATE TEMP TABLE nosuchtable(a, b, c, d); + CREATE VIRTUAL TABLE f USING fuzzer(nosuchtable); +} {1 {fuzzer: no such table: main.nosuchtable}} + +do_catchsql_test fuzzer1-1.5 { + DROP TABLE temp.nosuchtable; + CREATE TABLE nosuchtable(a, b, c, d); + CREATE VIRTUAL TABLE temp.f USING fuzzer(nosuchtable); +} {1 {fuzzer: no such table: temp.nosuchtable}} + +do_catchsql_test fuzzer1-1.6 { + DROP TABLE IF EXISTS f_rules; + CREATE TABLE f_rules(a, b, c); + CREATE VIRTUAL TABLE f USING fuzzer(f_rules); +} {1 {fuzzer: f_rules has 3 columns, expected 4}} + +do_catchsql_test fuzzer1-1.7 { + DROP TABLE IF EXISTS f_rules; + CREATE TABLE f_rules(a, b, c, d, e); + CREATE VIRTUAL TABLE f USING fuzzer(f_rules); +} {1 {fuzzer: f_rules has 5 columns, expected 4}} + + +do_execsql_test fuzzer1-2.1 { + CREATE TABLE f1_rules(ruleset DEFAULT 0, cfrom, cto, cost); + INSERT INTO f1_rules(cfrom, cto, cost) VALUES('e','a',1); + INSERT INTO f1_rules(cfrom, cto, cost) VALUES('a','e',10); + INSERT INTO f1_rules(cfrom, cto, cost) VALUES('e','o',100); + + CREATE VIRTUAL TABLE f1 USING fuzzer(f1_rules); +} {} + +do_execsql_test fuzzer1-2.1 { + SELECT word, distance FROM f1 WHERE word MATCH 'abcde' +} { + abcde 0 abcda 1 ebcde 10 + ebcda 11 abcdo 100 ebcdo 110 + obcde 110 obcda 111 obcdo 210 +} + +do_execsql_test fuzzer1-2.4 { + INSERT INTO f1_rules(ruleset, cfrom, cto, cost) VALUES(1,'b','x',1); + INSERT INTO f1_rules(ruleset, cfrom, cto, cost) VALUES(1,'d','y',10); + INSERT INTO f1_rules(ruleset, cfrom, cto, cost) VALUES(1,'y','z',100); + + DROP TABLE f1; + CREATE VIRTUAL TABLE f1 USING fuzzer(f1_rules); +} {} + +do_execsql_test fuzzer1-2.5 { + SELECT word, distance FROM f1 WHERE word MATCH 'abcde' +} { + abcde 0 abcda 1 ebcde 10 + ebcda 11 abcdo 100 ebcdo 110 + obcde 110 obcda 111 obcdo 210 +} + +do_execsql_test fuzzer1-2.6 { + SELECT word, distance FROM f1 WHERE word MATCH 'abcde' AND ruleset=0 +} { + abcde 0 abcda 1 ebcde 10 + ebcda 11 abcdo 100 ebcdo 110 + obcde 110 obcda 111 obcdo 210 +} + +do_execsql_test fuzzer1-2.7 { + SELECT word, distance FROM f1 WHERE word MATCH 'abcde' AND ruleset=1 +} { + abcde 0 axcde 1 abcye 10 + axcye 11 abcze 110 axcze 111 +} + +do_test fuzzer1-1.8 { + db eval { + SELECT word, distance FROM f1 WHERE word MATCH 'abcde' AND distance<100 + } +} {abcde 0 abcda 1 ebcde 10 ebcda 11} +do_test fuzzer1-1.9 { + db eval { + SELECT word, distance FROM f1 WHERE word MATCH 'abcde' AND distance<=100 + } +} {abcde 0 abcda 1 ebcde 10 ebcda 11 abcdo 100} +do_test fuzzer1-1.10 { + db eval { + SELECT word, distance FROM f1 + WHERE word MATCH 'abcde' AND distance<100 AND ruleset=0 + } +} {abcde 0 abcda 1 ebcde 10 ebcda 11} +do_test fuzzer1-1.11 { + db eval { + SELECT word, distance FROM f1 + WHERE word MATCH 'abcde' AND distance<=100 AND ruleset=0 + } +} {abcde 0 abcda 1 ebcde 10 ebcda 11 abcdo 100} +do_test fuzzer1-1.12 { + db eval { + SELECT word, distance FROM f1 + WHERE word MATCH 'abcde' AND distance<11 AND ruleset=1 + } +} {abcde 0 axcde 1 abcye 10} +do_test fuzzer1-1.13 { + db eval { + SELECT word, distance FROM f1 + WHERE word MATCH 'abcde' AND distance<=11 AND ruleset=1 + } +} {abcde 0 axcde 1 abcye 10 axcye 11} +do_test fuzzer1-1.14 { + catchsql {INSERT INTO f1 VALUES(1)} +} {1 {table f1 may not be modified}} +do_test fuzzer1-1.15 { + catchsql {DELETE FROM f1} +} {1 {table f1 may not be modified}} +do_test fuzzer1-1.16 { + catchsql {UPDATE f1 SET rowid=rowid+10000} +} {1 {table f1 may not be modified}} + + +do_test fuzzer1-2.0 { + execsql { + -- costs based on English letter frequencies + CREATE TEMP TABLE f2_rules(ruleset DEFAULT 0, cFrom, cTo, cost); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('a','e',24); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('a','o',47); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('a','u',50); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('e','a',23); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('e','i',33); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('e','o',37); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('i','e',33); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('i','y',33); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('o','a',41); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('o','e',46); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('o','u',57); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('u','o',58); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('y','i',33); + + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('t','th',70); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('th','t',66); + + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('a','',84); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','b',106); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('b','',106); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','c',94); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('c','',94); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','d',89); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('d','',89); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','e',83); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('e','',83); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','f',97); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('f','',97); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','g',99); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('g','',99); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','h',86); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('h','',86); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','i',85); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('i','',85); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','j',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('j','',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','k',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('k','',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','l',89); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('l','',89); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','m',96); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('m','',96); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','n',85); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('n','',85); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','o',85); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('o','',85); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','p',100); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('p','',100); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','q',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('q','',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','r',86); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('r','',86); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','s',86); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('s','',86); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','t',84); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('t','',84); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','u',94); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('u','',94); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','v',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('v','',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','w',96); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('w','',96); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','x',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('x','',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','y',100); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('y','',100); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('','z',120); + INSERT INTO f2_rules(cFrom,cTo,cost) VALUES('z','',120); + INSERT INTO f2_rules(ruleset,cFrom,cTo,cost) + SELECT 1, cFrom, cTo, 100 FROM f2_rules WHERE ruleset=0; + INSERT INTO f2_rules(ruleset,cFrom,cTo,cost) + SELECT 2, cFrom, cTo, 200-cost FROM f2_rules WHERE ruleset=0; + INSERT INTO f2_rules(ruleset,cFrom,cTo,cost) + SELECT 3, cFrom, cTo, cost FROM f2_rules WHERE ruleset=0; + INSERT INTO f2_rules(ruleset,cFrom,cTo,cost) + VALUES(3, 'mallard','duck',50), + (3, 'duck', 'mallard', 50), + (3, 'rock', 'stone', 50), + (3, 'stone', 'rock', 50); + + + CREATE VIRTUAL TABLE temp.f2 USING fuzzer(f2_rules); + + -- Street names for the 28269 ZIPCODE. + -- + CREATE TEMP TABLE streetname(n TEXT UNIQUE); + INSERT INTO streetname VALUES('abbotsinch'); + INSERT INTO streetname VALUES('abbottsgate'); + INSERT INTO streetname VALUES('abbywood'); + INSERT INTO streetname VALUES('abner'); + INSERT INTO streetname VALUES('acacia ridge'); + INSERT INTO streetname VALUES('acorn creek'); + INSERT INTO streetname VALUES('acorn forest'); + INSERT INTO streetname VALUES('adel'); + INSERT INTO streetname VALUES('ainslie'); + INSERT INTO streetname VALUES('airways'); + INSERT INTO streetname VALUES('alabaster'); + INSERT INTO streetname VALUES('alba'); + INSERT INTO streetname VALUES('albertine'); + INSERT INTO streetname VALUES('alden glen'); + INSERT INTO streetname VALUES('alderson'); + INSERT INTO streetname VALUES('allen'); + INSERT INTO streetname VALUES('allen a brown'); + INSERT INTO streetname VALUES('allness glen'); + INSERT INTO streetname VALUES('aloysia'); + INSERT INTO streetname VALUES('alpine'); + INSERT INTO streetname VALUES('alwyn'); + INSERT INTO streetname VALUES('amaranthus'); + INSERT INTO streetname VALUES('amber glen'); + INSERT INTO streetname VALUES('amber leigh way'); + INSERT INTO streetname VALUES('amber meadows'); + INSERT INTO streetname VALUES('amberway'); + INSERT INTO streetname VALUES('ame'); + INSERT INTO streetname VALUES('amesbury hill'); + INSERT INTO streetname VALUES('anderson'); + INSERT INTO streetname VALUES('andrew thomas'); + INSERT INTO streetname VALUES('anduin falls'); + INSERT INTO streetname VALUES('ankeny'); + INSERT INTO streetname VALUES('annandale'); + INSERT INTO streetname VALUES('annbick'); + INSERT INTO streetname VALUES('antelope'); + INSERT INTO streetname VALUES('anzack'); + INSERT INTO streetname VALUES('apple glen'); + INSERT INTO streetname VALUES('applevalley'); + INSERT INTO streetname VALUES('appley mead'); + INSERT INTO streetname VALUES('aragorn'); + INSERT INTO streetname VALUES('arbor creek'); + INSERT INTO streetname VALUES('arbor day'); + INSERT INTO streetname VALUES('arbor meadows'); + INSERT INTO streetname VALUES('arbor spring'); + INSERT INTO streetname VALUES('arborview'); + INSERT INTO streetname VALUES('arklow'); + INSERT INTO streetname VALUES('armitage'); + INSERT INTO streetname VALUES('arvin'); + INSERT INTO streetname VALUES('ash cove'); + INSERT INTO streetname VALUES('ashford leigh'); + INSERT INTO streetname VALUES('ashmont'); + INSERT INTO streetname VALUES('atlas'); + INSERT INTO streetname VALUES('atwater'); + INSERT INTO streetname VALUES('auburn hill'); + INSERT INTO streetname VALUES('aulton link'); + INSERT INTO streetname VALUES('austin dekota'); + INSERT INTO streetname VALUES('austin knoll'); + INSERT INTO streetname VALUES('auten'); + INSERT INTO streetname VALUES('autumn harvest'); + INSERT INTO streetname VALUES('autumn oak'); + INSERT INTO streetname VALUES('autumn ridge'); + INSERT INTO streetname VALUES('avalon forest'); + INSERT INTO streetname VALUES('avalon loop'); + INSERT INTO streetname VALUES('avon farm'); + INSERT INTO streetname VALUES('avonhurst'); + INSERT INTO streetname VALUES('avonlea'); + INSERT INTO streetname VALUES('aynrand'); + INSERT INTO streetname VALUES('azure valley'); + INSERT INTO streetname VALUES('baberton'); + INSERT INTO streetname VALUES('baffin'); + INSERT INTO streetname VALUES('baggins'); + INSERT INTO streetname VALUES('balata'); + INSERT INTO streetname VALUES('ballantray'); + INSERT INTO streetname VALUES('ballston'); + INSERT INTO streetname VALUES('balsam tree'); + INSERT INTO streetname VALUES('bambi'); + INSERT INTO streetname VALUES('banwell'); + INSERT INTO streetname VALUES('barbee'); + INSERT INTO streetname VALUES('barefoot forest'); + INSERT INTO streetname VALUES('barnview'); + INSERT INTO streetname VALUES('baroda'); + INSERT INTO streetname VALUES('barson'); + INSERT INTO streetname VALUES('baskerville'); + INSERT INTO streetname VALUES('battle creek'); + INSERT INTO streetname VALUES('baucom'); + INSERT INTO streetname VALUES('bay pines'); + INSERT INTO streetname VALUES('beaker'); + INSERT INTO streetname VALUES('beard'); + INSERT INTO streetname VALUES('beardsley'); + INSERT INTO streetname VALUES('bearoak'); + INSERT INTO streetname VALUES('beauvista'); + INSERT INTO streetname VALUES('beaver creek'); + INSERT INTO streetname VALUES('beaver hollow'); + INSERT INTO streetname VALUES('bedlington'); + INSERT INTO streetname VALUES('beech cove'); + INSERT INTO streetname VALUES('beech crest'); + INSERT INTO streetname VALUES('beith'); + INSERT INTO streetname VALUES('bell glen'); + INSERT INTO streetname VALUES('bellmore'); + INSERT INTO streetname VALUES('bells mill'); + INSERT INTO streetname VALUES('bellville'); + INSERT INTO streetname VALUES('belmar place'); + INSERT INTO streetname VALUES('bembridge'); + INSERT INTO streetname VALUES('bennett neely'); + INSERT INTO streetname VALUES('bentgrass run'); + INSERT INTO streetname VALUES('benthaven'); + INSERT INTO streetname VALUES('bernardy'); + INSERT INTO streetname VALUES('bernbrook shadow'); + INSERT INTO streetname VALUES('berrybrook'); + INSERT INTO streetname VALUES('berrybush'); + INSERT INTO streetname VALUES('berwick'); + INSERT INTO streetname VALUES('betterton'); + INSERT INTO streetname VALUES('bickham'); + INSERT INTO streetname VALUES('billingham'); + INSERT INTO streetname VALUES('birchcroft'); + INSERT INTO streetname VALUES('birchstone'); + INSERT INTO streetname VALUES('birdwell'); + INSERT INTO streetname VALUES('bisaner'); + INSERT INTO streetname VALUES('bitterbush'); + INSERT INTO streetname VALUES('bitterroot'); + INSERT INTO streetname VALUES('black fox'); + INSERT INTO streetname VALUES('black maple'); + INSERT INTO streetname VALUES('black trail'); + INSERT INTO streetname VALUES('blackbird'); + INSERT INTO streetname VALUES('blake a dare'); + INSERT INTO streetname VALUES('blasdell'); + INSERT INTO streetname VALUES('blue aster'); + INSERT INTO streetname VALUES('blue finch'); + INSERT INTO streetname VALUES('blue lilac'); + INSERT INTO streetname VALUES('blue sky'); + INSERT INTO streetname VALUES('blue tick'); + INSERT INTO streetname VALUES('bob beatty'); + INSERT INTO streetname VALUES('bobcat'); + INSERT INTO streetname VALUES('bolton'); + INSERT INTO streetname VALUES('boomerang'); + INSERT INTO streetname VALUES('boulder'); + INSERT INTO streetname VALUES('boxer'); + INSERT INTO streetname VALUES('boxmeer'); + INSERT INTO streetname VALUES('brachnell view'); + INSERT INTO streetname VALUES('bradford lake'); + INSERT INTO streetname VALUES('bradwell'); + INSERT INTO streetname VALUES('brady'); + INSERT INTO streetname VALUES('braids bend'); + INSERT INTO streetname VALUES('bralers'); + INSERT INTO streetname VALUES('brandie glen'); + INSERT INTO streetname VALUES('brandy ridge'); + INSERT INTO streetname VALUES('brandybuck'); + INSERT INTO streetname VALUES('branthurst'); + INSERT INTO streetname VALUES('brassy creek'); + INSERT INTO streetname VALUES('brathay'); + INSERT INTO streetname VALUES('brawer farm'); + INSERT INTO streetname VALUES('breezy morn'); + INSERT INTO streetname VALUES('brenda'); + INSERT INTO streetname VALUES('brenly'); + INSERT INTO streetname VALUES('brenock'); + INSERT INTO streetname VALUES('brianwood'); + INSERT INTO streetname VALUES('briar rose'); + INSERT INTO streetname VALUES('briarcrest'); + INSERT INTO streetname VALUES('briarthorne'); + INSERT INTO streetname VALUES('brick dust'); + INSERT INTO streetname VALUES('bridgepath'); + INSERT INTO streetname VALUES('bridle ridge'); + INSERT INTO streetname VALUES('briggs'); + INSERT INTO streetname VALUES('brightleaf'); + INSERT INTO streetname VALUES('brigstock'); + INSERT INTO streetname VALUES('broad ridge'); + INSERT INTO streetname VALUES('brock'); + INSERT INTO streetname VALUES('brockhampton'); + INSERT INTO streetname VALUES('broken pine'); + INSERT INTO streetname VALUES('brompton'); + INSERT INTO streetname VALUES('brook falls'); + INSERT INTO streetname VALUES('brookings'); + INSERT INTO streetname VALUES('browne'); + INSERT INTO streetname VALUES('brownes creek'); + INSERT INTO streetname VALUES('brownes ferry'); + INSERT INTO streetname VALUES('brownestone view'); + INSERT INTO streetname VALUES('brumit'); + INSERT INTO streetname VALUES('bryn athyn'); + INSERT INTO streetname VALUES('buck'); + INSERT INTO streetname VALUES('bucklebury'); + INSERT INTO streetname VALUES('buckminister'); + INSERT INTO streetname VALUES('buckspring'); + INSERT INTO streetname VALUES('burch'); + INSERT INTO streetname VALUES('burch shire'); + INSERT INTO streetname VALUES('burkston'); + INSERT INTO streetname VALUES('burmith'); + INSERT INTO streetname VALUES('burnaby'); + INSERT INTO streetname VALUES('butterfly'); + INSERT INTO streetname VALUES('cabin creek'); + INSERT INTO streetname VALUES('cairns mill'); + INSERT INTO streetname VALUES('callender'); + INSERT INTO streetname VALUES('cambellton'); + INSERT INTO streetname VALUES('cambridge bay'); + INSERT INTO streetname VALUES('canary'); + INSERT INTO streetname VALUES('canbury'); + INSERT INTO streetname VALUES('candle leaf'); + INSERT INTO streetname VALUES('canipe'); + INSERT INTO streetname VALUES('canipe farm'); + INSERT INTO streetname VALUES('cannon'); + INSERT INTO streetname VALUES('canopy'); + INSERT INTO streetname VALUES('canso'); + INSERT INTO streetname VALUES('canterbrook'); + INSERT INTO streetname VALUES('cardinal glen'); + INSERT INTO streetname VALUES('cardinal point'); + INSERT INTO streetname VALUES('cardinals nest'); + INSERT INTO streetname VALUES('carlota'); + INSERT INTO streetname VALUES('carmathen'); + INSERT INTO streetname VALUES('carver'); + INSERT INTO streetname VALUES('carver pond'); + INSERT INTO streetname VALUES('casa loma'); + INSERT INTO streetname VALUES('caselton'); + INSERT INTO streetname VALUES('castello'); + INSERT INTO streetname VALUES('castle ridge'); + INSERT INTO streetname VALUES('castleglen'); + INSERT INTO streetname VALUES('castlemaine'); + INSERT INTO streetname VALUES('cavett'); + INSERT INTO streetname VALUES('caymus'); + INSERT INTO streetname VALUES('cedardale ridge'); + INSERT INTO streetname VALUES('cedarhurst'); + INSERT INTO streetname VALUES('cemkey way'); + INSERT INTO streetname VALUES('cerise'); + INSERT INTO streetname VALUES('chaceview'); + INSERT INTO streetname VALUES('chadsworth'); + INSERT INTO streetname VALUES('chadwell'); + INSERT INTO streetname VALUES('champions crest'); + INSERT INTO streetname VALUES('chandler haven'); + INSERT INTO streetname VALUES('chapel crossing'); + INSERT INTO streetname VALUES('chapel ridge'); + INSERT INTO streetname VALUES('charles crawford'); + INSERT INTO streetname VALUES('charminster'); + INSERT INTO streetname VALUES('chasewind'); + INSERT INTO streetname VALUES('chavel'); + INSERT INTO streetname VALUES('chelsea jade'); + INSERT INTO streetname VALUES('chestnut knoll'); + INSERT INTO streetname VALUES('cheviot'); + INSERT INTO streetname VALUES('chickadee'); + INSERT INTO streetname VALUES('chidley'); + INSERT INTO streetname VALUES('chimney ridge'); + INSERT INTO streetname VALUES('chimney springs'); + INSERT INTO streetname VALUES('chinaberry'); + INSERT INTO streetname VALUES('chinemist'); + INSERT INTO streetname VALUES('chinquapin'); + INSERT INTO streetname VALUES('chiswell'); + INSERT INTO streetname VALUES('christenbury'); + INSERT INTO streetname VALUES('christenbury hills'); + INSERT INTO streetname VALUES('churchill'); + INSERT INTO streetname VALUES('cindy'); + INSERT INTO streetname VALUES('cinnamon teal'); + INSERT INTO streetname VALUES('citadel'); + INSERT INTO streetname VALUES('clare olivia'); + INSERT INTO streetname VALUES('clarke creek'); + INSERT INTO streetname VALUES('clarke ridge'); + INSERT INTO streetname VALUES('clear day'); + INSERT INTO streetname VALUES('clear stream'); + INSERT INTO streetname VALUES('cleve brown'); + INSERT INTO streetname VALUES('cliff cameron'); + INSERT INTO streetname VALUES('cliffvale'); + INSERT INTO streetname VALUES('cloverside'); + INSERT INTO streetname VALUES('clymer'); + INSERT INTO streetname VALUES('coatbridge'); + INSERT INTO streetname VALUES('cobble glen'); + INSERT INTO streetname VALUES('cochran farm'); + INSERT INTO streetname VALUES('cochrane'); + INSERT INTO streetname VALUES('coleridge'); + INSERT INTO streetname VALUES('coleshire'); + INSERT INTO streetname VALUES('collins'); + INSERT INTO streetname VALUES('colvard'); + INSERT INTO streetname VALUES('colvard park'); + INSERT INTO streetname VALUES('condor'); + INSERT INTO streetname VALUES('conner ridge'); + INSERT INTO streetname VALUES('connery'); + INSERT INTO streetname VALUES('cooper run'); + INSERT INTO streetname VALUES('coopers ridge'); + INSERT INTO streetname VALUES('copper hill'); + INSERT INTO streetname VALUES('coppermine'); + INSERT INTO streetname VALUES('cornelia'); + INSERT INTO streetname VALUES('corner'); + INSERT INTO streetname VALUES('cornerstone'); + INSERT INTO streetname VALUES('cottage oaks'); + INSERT INTO streetname VALUES('cougar'); + INSERT INTO streetname VALUES('coves end'); + INSERT INTO streetname VALUES('cragland'); + INSERT INTO streetname VALUES('crail'); + INSERT INTO streetname VALUES('cranberry nook'); + INSERT INTO streetname VALUES('crawford brook'); + INSERT INTO streetname VALUES('crayton'); + INSERT INTO streetname VALUES('creek breeze'); + INSERT INTO streetname VALUES('crescent ridge'); + INSERT INTO streetname VALUES('crescent view'); + INSERT INTO streetname VALUES('cresta'); + INSERT INTO streetname VALUES('crestfield'); + INSERT INTO streetname VALUES('crestland'); + INSERT INTO streetname VALUES('crestwick'); + INSERT INTO streetname VALUES('crisfield'); + INSERT INTO streetname VALUES('crisp wood'); + INSERT INTO streetname VALUES('croft haven'); + INSERT INTO streetname VALUES('crofton springs'); + INSERT INTO streetname VALUES('cross'); + INSERT INTO streetname VALUES('crosspoint center'); + INSERT INTO streetname VALUES('crownvista'); + INSERT INTO streetname VALUES('crystal arms'); + INSERT INTO streetname VALUES('crystal crest'); + INSERT INTO streetname VALUES('crystal leaf'); + INSERT INTO streetname VALUES('cunningham park'); + INSERT INTO streetname VALUES('cypress pond'); + INSERT INTO streetname VALUES('daffodil'); + INSERT INTO streetname VALUES('daisyfield'); + INSERT INTO streetname VALUES('dalecrest'); + INSERT INTO streetname VALUES('dannelly park'); + INSERT INTO streetname VALUES('daphne'); + INSERT INTO streetname VALUES('daria'); + INSERT INTO streetname VALUES('dartmouth'); + INSERT INTO streetname VALUES('datha'); + INSERT INTO streetname VALUES('david cox'); + INSERT INTO streetname VALUES('davis'); + INSERT INTO streetname VALUES('davis crossing'); + INSERT INTO streetname VALUES('davis lake'); + INSERT INTO streetname VALUES('davis ridge'); + INSERT INTO streetname VALUES('dawnmist'); + INSERT INTO streetname VALUES('daybreak'); + INSERT INTO streetname VALUES('dearmon'); + INSERT INTO streetname VALUES('dearview'); + INSERT INTO streetname VALUES('deaton hill'); + INSERT INTO streetname VALUES('deer cross'); + INSERT INTO streetname VALUES('deerton'); + INSERT INTO streetname VALUES('degrasse'); + INSERT INTO streetname VALUES('delamere'); + INSERT INTO streetname VALUES('dellfield'); + INSERT INTO streetname VALUES('dellinger'); + INSERT INTO streetname VALUES('demington'); + INSERT INTO streetname VALUES('denmeade'); + INSERT INTO streetname VALUES('derita'); + INSERT INTO streetname VALUES('derita woods'); + INSERT INTO streetname VALUES('deruyter'); + INSERT INTO streetname VALUES('dervish'); + INSERT INTO streetname VALUES('devas'); + INSERT INTO streetname VALUES('devon croft'); + INSERT INTO streetname VALUES('devonbridge'); + INSERT INTO streetname VALUES('devongate'); + INSERT INTO streetname VALUES('devonhill'); + INSERT INTO streetname VALUES('dewmorn'); + INSERT INTO streetname VALUES('distribution center'); + INSERT INTO streetname VALUES('dominion crest'); + INSERT INTO streetname VALUES('dominion green'); + INSERT INTO streetname VALUES('dominion village'); + INSERT INTO streetname VALUES('dorshire'); + INSERT INTO streetname VALUES('double creek crossing'); + INSERT INTO streetname VALUES('dow'); + INSERT INTO streetname VALUES('downfield wood'); + INSERT INTO streetname VALUES('downing creek'); + INSERT INTO streetname VALUES('driscol'); + INSERT INTO streetname VALUES('driwood'); + INSERT INTO streetname VALUES('dry brook'); + INSERT INTO streetname VALUES('dumont'); + INSERT INTO streetname VALUES('dunblane'); + INSERT INTO streetname VALUES('dunfield'); + INSERT INTO streetname VALUES('dunoon'); + INSERT INTO streetname VALUES('dunslow'); + INSERT INTO streetname VALUES('dunstaff'); + INSERT INTO streetname VALUES('durham'); + INSERT INTO streetname VALUES('durston'); + INSERT INTO streetname VALUES('dusty cedar'); + INSERT INTO streetname VALUES('dusty trail'); + INSERT INTO streetname VALUES('dutchess'); + INSERT INTO streetname VALUES('duxford'); + INSERT INTO streetname VALUES('eagle creek'); + INSERT INTO streetname VALUES('eagles field'); + INSERT INTO streetname VALUES('eargle'); + INSERT INTO streetname VALUES('earlswood'); + INSERT INTO streetname VALUES('early mist'); + INSERT INTO streetname VALUES('earthenware'); + INSERT INTO streetname VALUES('eastfield park'); + INSERT INTO streetname VALUES('eastfield village'); + INSERT INTO streetname VALUES('easy'); + INSERT INTO streetname VALUES('eben'); + INSERT INTO streetname VALUES('edgepine'); + INSERT INTO streetname VALUES('edgewier'); + INSERT INTO streetname VALUES('edinburgh'); + INSERT INTO streetname VALUES('edinmeadow'); + INSERT INTO streetname VALUES('edmonton'); + INSERT INTO streetname VALUES('edwin jones'); + INSERT INTO streetname VALUES('elberon'); + INSERT INTO streetname VALUES('elderslie'); + INSERT INTO streetname VALUES('elementary view'); + INSERT INTO streetname VALUES('elendil'); + INSERT INTO streetname VALUES('elizabeth'); + INSERT INTO streetname VALUES('elm cove'); + INSERT INTO streetname VALUES('elrond'); + INSERT INTO streetname VALUES('elsenham'); + INSERT INTO streetname VALUES('elven'); + INSERT INTO streetname VALUES('emma lynn'); + INSERT INTO streetname VALUES('english setter'); + INSERT INTO streetname VALUES('enoch'); + INSERT INTO streetname VALUES('equipment'); + INSERT INTO streetname VALUES('ernest russell'); + INSERT INTO streetname VALUES('ernie'); + INSERT INTO streetname VALUES('esmeralda'); + INSERT INTO streetname VALUES('evergreen hollow'); + INSERT INTO streetname VALUES('eversfield'); + INSERT INTO streetname VALUES('ewen'); + INSERT INTO streetname VALUES('ewert cut'); + INSERT INTO streetname VALUES('exbury'); + INSERT INTO streetname VALUES('fair grounds park'); + INSERT INTO streetname VALUES('fairbourne'); + INSERT INTO streetname VALUES('fairchase'); + INSERT INTO streetname VALUES('faircreek'); + INSERT INTO streetname VALUES('fairglen'); + INSERT INTO streetname VALUES('fairlea'); + INSERT INTO streetname VALUES('fairmead'); + INSERT INTO streetname VALUES('fairmeadows'); + INSERT INTO streetname VALUES('fairstone'); + INSERT INTO streetname VALUES('fairvista'); + INSERT INTO streetname VALUES('fairway point'); + INSERT INTO streetname VALUES('falconcrest'); + INSERT INTO streetname VALUES('falls ridge'); + INSERT INTO streetname VALUES('falmouth'); + INSERT INTO streetname VALUES('far west'); + INSERT INTO streetname VALUES('farlow'); + INSERT INTO streetname VALUES('farris wheel'); + INSERT INTO streetname VALUES('fawndale'); + INSERT INTO streetname VALUES('feather bend'); + INSERT INTO streetname VALUES('fernledge'); + INSERT INTO streetname VALUES('fernmoss'); + INSERT INTO streetname VALUES('ferrell commons'); + INSERT INTO streetname VALUES('fieldstone'); + INSERT INTO streetname VALUES('fillian'); + INSERT INTO streetname VALUES('fincher'); + INSERT INTO streetname VALUES('foggy meadow'); + INSERT INTO streetname VALUES('fordyce'); + INSERT INTO streetname VALUES('forest grove'); + INSERT INTO streetname VALUES('forest path'); + INSERT INTO streetname VALUES('forestridge commons'); + INSERT INTO streetname VALUES('forestrock'); + INSERT INTO streetname VALUES('fortunes ridge'); + INSERT INTO streetname VALUES('founders club'); + INSERT INTO streetname VALUES('fountaingrass'); + INSERT INTO streetname VALUES('fox chase'); + INSERT INTO streetname VALUES('fox glen'); + INSERT INTO streetname VALUES('fox hill'); + INSERT INTO streetname VALUES('fox point'); + INSERT INTO streetname VALUES('fox trot'); + INSERT INTO streetname VALUES('foxbriar'); + INSERT INTO streetname VALUES('frank little'); + INSERT INTO streetname VALUES('franzia'); + INSERT INTO streetname VALUES('french woods'); + INSERT INTO streetname VALUES('frostmoor'); + INSERT INTO streetname VALUES('frye'); + INSERT INTO streetname VALUES('furlong'); + INSERT INTO streetname VALUES('galena view'); + INSERT INTO streetname VALUES('gallery pointe'); + INSERT INTO streetname VALUES('gammon'); + INSERT INTO streetname VALUES('garden grove'); + INSERT INTO streetname VALUES('gardendale'); + INSERT INTO streetname VALUES('garganey'); + INSERT INTO streetname VALUES('garnet field'); + INSERT INTO streetname VALUES('garrison'); + INSERT INTO streetname VALUES('garvin'); + INSERT INTO streetname VALUES('garvis'); + INSERT INTO streetname VALUES('gaskill'); + INSERT INTO streetname VALUES('gemstone'); + INSERT INTO streetname VALUES('gibbon'); + INSERT INTO streetname VALUES('gibbon terrace'); + INSERT INTO streetname VALUES('gibbons link'); + INSERT INTO streetname VALUES('gillman'); + INSERT INTO streetname VALUES('gladwood'); + INSERT INTO streetname VALUES('gladwyne'); + INSERT INTO streetname VALUES('glamorgan'); + INSERT INTO streetname VALUES('glaze'); + INSERT INTO streetname VALUES('glen brook'); + INSERT INTO streetname VALUES('glen cove'); + INSERT INTO streetname VALUES('glen hope'); + INSERT INTO streetname VALUES('glen manor'); + INSERT INTO streetname VALUES('glen olden'); + INSERT INTO streetname VALUES('glencairn'); + INSERT INTO streetname VALUES('glendock'); + INSERT INTO streetname VALUES('glenolden'); + INSERT INTO streetname VALUES('glenover'); + INSERT INTO streetname VALUES('glenshire'); + INSERT INTO streetname VALUES('glenstone'); + INSERT INTO streetname VALUES('gold dust'); + INSERT INTO streetname VALUES('golden pond'); + INSERT INTO streetname VALUES('goldenblush'); + INSERT INTO streetname VALUES('goldenfield'); + INSERT INTO streetname VALUES('goose landing'); + INSERT INTO streetname VALUES('gorham gate'); + INSERT INTO streetname VALUES('grabill'); + INSERT INTO streetname VALUES('graburns ford'); + INSERT INTO streetname VALUES('graham'); + INSERT INTO streetname VALUES('grahamson'); + INSERT INTO streetname VALUES('granard'); + INSERT INTO streetname VALUES('grand teton'); + INSERT INTO streetname VALUES('grande heights'); + INSERT INTO streetname VALUES('grandeur'); + INSERT INTO streetname VALUES('granite creek'); + INSERT INTO streetname VALUES('grasset'); + INSERT INTO streetname VALUES('graypark'); + INSERT INTO streetname VALUES('grays ridge'); + INSERT INTO streetname VALUES('great bear'); + INSERT INTO streetname VALUES('green clover'); + INSERT INTO streetname VALUES('green hedge'); + INSERT INTO streetname VALUES('green meadow'); + INSERT INTO streetname VALUES('green pasture'); + INSERT INTO streetname VALUES('greene'); + INSERT INTO streetname VALUES('greenloch'); + INSERT INTO streetname VALUES('greenock ridge'); + INSERT INTO streetname VALUES('greenware'); + INSERT INTO streetname VALUES('greenway village'); + INSERT INTO streetname VALUES('grenelefe village'); + INSERT INTO streetname VALUES('grey dogwood'); + INSERT INTO streetname VALUES('greyhound'); + INSERT INTO streetname VALUES('greylock ridge'); + INSERT INTO streetname VALUES('grosbeak'); + INSERT INTO streetname VALUES('grove'); + INSERT INTO streetname VALUES('groveton'); + INSERT INTO streetname VALUES('groveview'); + INSERT INTO streetname VALUES('hackberry creek'); + INSERT INTO streetname VALUES('hackberry grove'); + INSERT INTO streetname VALUES('hackett'); + INSERT INTO streetname VALUES('haddington'); + INSERT INTO streetname VALUES('hagler'); + INSERT INTO streetname VALUES('halcott'); + INSERT INTO streetname VALUES('half dome'); + INSERT INTO streetname VALUES('hallam'); + INSERT INTO streetname VALUES('hamilton russell'); + INSERT INTO streetname VALUES('hampton place'); + INSERT INTO streetname VALUES('hankins'); + INSERT INTO streetname VALUES('harburn forest'); + INSERT INTO streetname VALUES('harringham'); + INSERT INTO streetname VALUES('harrington woods'); + INSERT INTO streetname VALUES('harris corners'); + INSERT INTO streetname VALUES('harris cove'); + INSERT INTO streetname VALUES('harris glen'); + INSERT INTO streetname VALUES('harris hill'); + INSERT INTO streetname VALUES('harris oak'); + INSERT INTO streetname VALUES('harris pointe'); + INSERT INTO streetname VALUES('harris pond'); + INSERT INTO streetname VALUES('harris ridge'); + INSERT INTO streetname VALUES('harris technology'); + INSERT INTO streetname VALUES('harris woods'); + INSERT INTO streetname VALUES('hartfield downs'); + INSERT INTO streetname VALUES('hattie little'); + INSERT INTO streetname VALUES('hatwynn'); + INSERT INTO streetname VALUES('hawkins'); + INSERT INTO streetname VALUES('hawksnest'); + INSERT INTO streetname VALUES('haybridge'); + INSERT INTO streetname VALUES('hayden'); + INSERT INTO streetname VALUES('hazelcroft'); + INSERT INTO streetname VALUES('hazlitt'); + INSERT INTO streetname VALUES('hazy valley'); + INSERT INTO streetname VALUES('hearst'); + INSERT INTO streetname VALUES('heathcrest'); + INSERT INTO streetname VALUES('heathcroft'); + INSERT INTO streetname VALUES('hedge maple'); + INSERT INTO streetname VALUES('hedgecrest'); + INSERT INTO streetname VALUES('hedingham'); + INSERT INTO streetname VALUES('heman'); + INSERT INTO streetname VALUES('henderson'); + INSERT INTO streetname VALUES('henderson oaks'); + INSERT INTO streetname VALUES('henderson valley'); + INSERT INTO streetname VALUES('hendry'); + INSERT INTO streetname VALUES('heritage hills'); + INSERT INTO streetname VALUES('heritage woods'); + INSERT INTO streetname VALUES('heron cove'); + INSERT INTO streetname VALUES('heron glen'); + INSERT INTO streetname VALUES('hewitt'); + INSERT INTO streetname VALUES('hey rock'); + INSERT INTO streetname VALUES('heysham'); + INSERT INTO streetname VALUES('hickory cove'); + INSERT INTO streetname VALUES('hidden meadow'); + INSERT INTO streetname VALUES('high glen'); + INSERT INTO streetname VALUES('high laurel'); + INSERT INTO streetname VALUES('high valley'); + INSERT INTO streetname VALUES('highcroft'); + INSERT INTO streetname VALUES('highland'); + INSERT INTO streetname VALUES('highland commons'); + INSERT INTO streetname VALUES('highland creek'); + INSERT INTO streetname VALUES('highland glen'); + INSERT INTO streetname VALUES('highland park'); + INSERT INTO streetname VALUES('highlander'); + INSERT INTO streetname VALUES('highstream'); + INSERT INTO streetname VALUES('hilltop'); + INSERT INTO streetname VALUES('hobbitshire'); + INSERT INTO streetname VALUES('hoffman'); + INSERT INTO streetname VALUES('hogans way'); + INSERT INTO streetname VALUES('holbert'); + INSERT INTO streetname VALUES('hollow ridge'); + INSERT INTO streetname VALUES('holly vista'); + INSERT INTO streetname VALUES('hollywood'); + INSERT INTO streetname VALUES('hoover'); + INSERT INTO streetname VALUES('hopkins'); + INSERT INTO streetname VALUES('horace mann'); + INSERT INTO streetname VALUES('hornbeam'); + INSERT INTO streetname VALUES('horse pasture'); + INSERT INTO streetname VALUES('hosta'); + INSERT INTO streetname VALUES('howard'); + INSERT INTO streetname VALUES('hubbard'); + INSERT INTO streetname VALUES('hubbard falls'); + INSERT INTO streetname VALUES('hubbard woods'); + INSERT INTO streetname VALUES('hucks'); + INSERT INTO streetname VALUES('hunters creek'); + INSERT INTO streetname VALUES('hunters pointe'); + INSERT INTO streetname VALUES('hunters spring'); + INSERT INTO streetname VALUES('hunters whip'); + INSERT INTO streetname VALUES('huntmeadow'); + INSERT INTO streetname VALUES('hutchison mcdonald'); + INSERT INTO streetname VALUES('ingleton'); + INSERT INTO streetname VALUES('insdale'); + INSERT INTO streetname VALUES('interstate 85 service'); + INSERT INTO streetname VALUES('iola'); + INSERT INTO streetname VALUES('iredell'); + INSERT INTO streetname VALUES('iron brigade'); + INSERT INTO streetname VALUES('irwin valley'); + INSERT INTO streetname VALUES('irwin wood'); + INSERT INTO streetname VALUES('ivy brook'); + INSERT INTO streetname VALUES('ivy ridge'); + INSERT INTO streetname VALUES('jack russell'); + INSERT INTO streetname VALUES('jackson'); + INSERT INTO streetname VALUES('jacob martin'); + INSERT INTO streetname VALUES('jamison'); + INSERT INTO streetname VALUES('jane'); + INSERT INTO streetname VALUES('jaspar crest'); + INSERT INTO streetname VALUES('jessica'); + INSERT INTO streetname VALUES('jimmy oehler'); + INSERT INTO streetname VALUES('jocelyn'); + INSERT INTO streetname VALUES('johnston mill'); + INSERT INTO streetname VALUES('johnston oehler'); + INSERT INTO streetname VALUES('judal'); + INSERT INTO streetname VALUES('junipeous'); + INSERT INTO streetname VALUES('juniper'); + INSERT INTO streetname VALUES('juniperus'); + INSERT INTO streetname VALUES('kalispell'); + INSERT INTO streetname VALUES('karylsturn'); + INSERT INTO streetname VALUES('katelyn'); + INSERT INTO streetname VALUES('kayron'); + INSERT INTO streetname VALUES('keaton'); + INSERT INTO streetname VALUES('keble'); + INSERT INTO streetname VALUES('keels'); + INSERT INTO streetname VALUES('keith'); + INSERT INTO streetname VALUES('keithwood'); + INSERT INTO streetname VALUES('kelden walker'); + INSERT INTO streetname VALUES('kelsey emma'); + INSERT INTO streetname VALUES('kendrick'); + INSERT INTO streetname VALUES('kenmont'); + INSERT INTO streetname VALUES('kennerly cove'); + INSERT INTO streetname VALUES('kenninghall'); + INSERT INTO streetname VALUES('kent village'); + INSERT INTO streetname VALUES('kestral ridge'); + INSERT INTO streetname VALUES('kestrel'); + INSERT INTO streetname VALUES('kilmartin'); + INSERT INTO streetname VALUES('kilty'); + INSERT INTO streetname VALUES('kinglet'); + INSERT INTO streetname VALUES('kingsland'); + INSERT INTO streetname VALUES('kingsnorth'); + INSERT INTO streetname VALUES('kinsmore'); + INSERT INTO streetname VALUES('kirkgard'); + INSERT INTO streetname VALUES('kirkmont'); + INSERT INTO streetname VALUES('knightsgate'); + INSERT INTO streetname VALUES('kobuk'); + INSERT INTO streetname VALUES('kotlik'); + INSERT INTO streetname VALUES('kotz'); + INSERT INTO streetname VALUES('kyndall walk'); + INSERT INTO streetname VALUES('laborde'); + INSERT INTO streetname VALUES('lady bank'); + INSERT INTO streetname VALUES('lagrande'); + INSERT INTO streetname VALUES('lake'); + INSERT INTO streetname VALUES('lakeridge commons'); + INSERT INTO streetname VALUES('lakeview'); + INSERT INTO streetname VALUES('lakewood edge'); + INSERT INTO streetname VALUES('lakota'); + INSERT INTO streetname VALUES('lambrook'); + INSERT INTO streetname VALUES('lampkin'); + INSERT INTO streetname VALUES('lampkin park'); + INSERT INTO streetname VALUES('langham'); + INSERT INTO streetname VALUES('lanzerac manor'); + INSERT INTO streetname VALUES('larkmead forest'); + INSERT INTO streetname VALUES('lattice'); + INSERT INTO streetname VALUES('laurel crest'); + INSERT INTO streetname VALUES('laurel ridge'); + INSERT INTO streetname VALUES('laurel run'); + INSERT INTO streetname VALUES('laurenfield'); + INSERT INTO streetname VALUES('laveta'); + INSERT INTO streetname VALUES('lazy day'); + INSERT INTO streetname VALUES('leawood run'); + INSERT INTO streetname VALUES('lee marie'); + INSERT INTO streetname VALUES('legacy lake'); + INSERT INTO streetname VALUES('legacy park'); + INSERT INTO streetname VALUES('legato'); + INSERT INTO streetname VALUES('legolas'); + INSERT INTO streetname VALUES('leigh glen'); + INSERT INTO streetname VALUES('lence'); + INSERT INTO streetname VALUES('lenox hill'); + INSERT INTO streetname VALUES('leonine'); + INSERT INTO streetname VALUES('leslie'); + INSERT INTO streetname VALUES('lester hill'); + INSERT INTO streetname VALUES('levisey'); + INSERT INTO streetname VALUES('liberty bell'); + INSERT INTO streetname VALUES('linden berry'); + INSERT INTO streetname VALUES('lisbon'); + INSERT INTO streetname VALUES('little stoney'); + INSERT INTO streetname VALUES('livengood'); + INSERT INTO streetname VALUES('lochway'); + INSERT INTO streetname VALUES('lockman'); + INSERT INTO streetname VALUES('loganville'); + INSERT INTO streetname VALUES('lone tree'); + INSERT INTO streetname VALUES('long creek park'); + INSERT INTO streetname VALUES('long forest'); + INSERT INTO streetname VALUES('looking glass'); + INSERT INTO streetname VALUES('lookout point'); + INSERT INTO streetname VALUES('lowen'); + INSERT INTO streetname VALUES('lusby'); + INSERT INTO streetname VALUES('lyleton'); + INSERT INTO streetname VALUES('lynn lee'); + INSERT INTO streetname VALUES('lynnewood glen'); + INSERT INTO streetname VALUES('machrie'); + INSERT INTO streetname VALUES('mackinac'); + INSERT INTO streetname VALUES('maddox'); + INSERT INTO streetname VALUES('madison park'); + INSERT INTO streetname VALUES('mallard'); + INSERT INTO streetname VALUES('mallard cove'); + INSERT INTO streetname VALUES('mallard forest'); + INSERT INTO streetname VALUES('mallard grove'); + INSERT INTO streetname VALUES('mallard hill'); + INSERT INTO streetname VALUES('mallard park'); + INSERT INTO streetname VALUES('mallard ridge'); + INSERT INTO streetname VALUES('mallard view'); + INSERT INTO streetname VALUES('manbey'); + INSERT INTO streetname VALUES('manning'); + INSERT INTO streetname VALUES('mantario'); + INSERT INTO streetname VALUES('maple'); + INSERT INTO streetname VALUES('maple cove'); + INSERT INTO streetname VALUES('maple park'); + INSERT INTO streetname VALUES('marathon hill'); + INSERT INTO streetname VALUES('marbury'); + INSERT INTO streetname VALUES('marett'); + INSERT INTO streetname VALUES('marigold'); + INSERT INTO streetname VALUES('marionwood'); + INSERT INTO streetname VALUES('marshbank'); + INSERT INTO streetname VALUES('mason'); + INSERT INTO streetname VALUES('mayapple'); + INSERT INTO streetname VALUES('maylandia'); + INSERT INTO streetname VALUES('mayspring'); + INSERT INTO streetname VALUES('mcadam'); + INSERT INTO streetname VALUES('mcchesney'); + INSERT INTO streetname VALUES('mccurdy'); + INSERT INTO streetname VALUES('mcgrath'); + INSERT INTO streetname VALUES('mckendree'); + INSERT INTO streetname VALUES('mclaughlin'); + INSERT INTO streetname VALUES('mctaggart'); + INSERT INTO streetname VALUES('meadow green'); + INSERT INTO streetname VALUES('meadow knoll'); + INSERT INTO streetname VALUES('meadow post'); + INSERT INTO streetname VALUES('meadowmont'); + INSERT INTO streetname VALUES('meadowmont view'); + INSERT INTO streetname VALUES('meadowview hills'); + INSERT INTO streetname VALUES('melshire'); + INSERT INTO streetname VALUES('melstrand'); + INSERT INTO streetname VALUES('mentone'); + INSERT INTO streetname VALUES('meridale crossing'); + INSERT INTO streetname VALUES('merion hills'); + INSERT INTO streetname VALUES('merlot'); + INSERT INTO streetname VALUES('mersham'); + INSERT INTO streetname VALUES('metromont'); + INSERT INTO streetname VALUES('metromont industrial'); + INSERT INTO streetname VALUES('michaw'); + INSERT INTO streetname VALUES('milhaven'); + INSERT INTO streetname VALUES('milhof'); + INSERT INTO streetname VALUES('millstream ridge'); + INSERT INTO streetname VALUES('mineral ridge'); + INSERT INTO streetname VALUES('mint thistle'); + INSERT INTO streetname VALUES('mintleaf'); + INSERT INTO streetname VALUES('mintvale'); + INSERT INTO streetname VALUES('misty'); + INSERT INTO streetname VALUES('misty arbor'); + INSERT INTO streetname VALUES('misty creek'); + INSERT INTO streetname VALUES('misty oaks'); + INSERT INTO streetname VALUES('misty wood'); + INSERT INTO streetname VALUES('mitzi deborah'); + INSERT INTO streetname VALUES('mobile'); + INSERT INTO streetname VALUES('molly elizabeth'); + INSERT INTO streetname VALUES('monmouth'); + INSERT INTO streetname VALUES('montrose'); + INSERT INTO streetname VALUES('moonlight'); + INSERT INTO streetname VALUES('moose'); + INSERT INTO streetname VALUES('morning dew'); + INSERT INTO streetname VALUES('morningsong'); + INSERT INTO streetname VALUES('morningview'); + INSERT INTO streetname VALUES('morsey'); + INSERT INTO streetname VALUES('moss glen'); + INSERT INTO streetname VALUES('mossy bank'); + INSERT INTO streetname VALUES('motor sport'); + INSERT INTO streetname VALUES('mountain laurel'); + INSERT INTO streetname VALUES('mourning dove'); + INSERT INTO streetname VALUES('mozart'); + INSERT INTO streetname VALUES('munsing'); + INSERT INTO streetname VALUES('murray'); + INSERT INTO streetname VALUES('nathan'); + INSERT INTO streetname VALUES('netherhall'); + INSERT INTO streetname VALUES('netherton'); + INSERT INTO streetname VALUES('neuhoff'); + INSERT INTO streetname VALUES('nevin'); + INSERT INTO streetname VALUES('nevin brook'); + INSERT INTO streetname VALUES('nevin glen'); + INSERT INTO streetname VALUES('nevin place'); + INSERT INTO streetname VALUES('new england'); + INSERT INTO streetname VALUES('new house'); + INSERT INTO streetname VALUES('newbary'); + INSERT INTO streetname VALUES('newchurch'); + INSERT INTO streetname VALUES('newfane'); + INSERT INTO streetname VALUES('newgard'); + INSERT INTO streetname VALUES('nicholas'); + INSERT INTO streetname VALUES('nicole'); + INSERT INTO streetname VALUES('nobility'); + INSERT INTO streetname VALUES('norcroft'); + INSERT INTO streetname VALUES('northridge'); + INSERT INTO streetname VALUES('northside'); + INSERT INTO streetname VALUES('northwoods business'); + INSERT INTO streetname VALUES('norway'); + INSERT INTO streetname VALUES('nottinghill'); + INSERT INTO streetname VALUES('numenore'); + INSERT INTO streetname VALUES('nyewood'); + INSERT INTO streetname VALUES('oak'); + INSERT INTO streetname VALUES('oak cove'); + INSERT INTO streetname VALUES('oak pasture'); + INSERT INTO streetname VALUES('oakburn'); + INSERT INTO streetname VALUES('oakwinds'); + INSERT INTO streetname VALUES('oakwood'); + INSERT INTO streetname VALUES('obrien'); + INSERT INTO streetname VALUES('ocala'); + INSERT INTO streetname VALUES('old bridge'); + INSERT INTO streetname VALUES('old fox'); + INSERT INTO streetname VALUES('old potters'); + INSERT INTO streetname VALUES('old statesville'); + INSERT INTO streetname VALUES('old steine'); + INSERT INTO streetname VALUES('old stoney creek'); + INSERT INTO streetname VALUES('old sugar creek'); + INSERT INTO streetname VALUES('old timber'); + INSERT INTO streetname VALUES('old wagon'); + INSERT INTO streetname VALUES('old willow'); + INSERT INTO streetname VALUES('oldenway'); + INSERT INTO streetname VALUES('oneida'); + INSERT INTO streetname VALUES('ontario'); + INSERT INTO streetname VALUES('oriole'); + INSERT INTO streetname VALUES('orofino'); + INSERT INTO streetname VALUES('orr'); + INSERT INTO streetname VALUES('osage'); + INSERT INTO streetname VALUES('osceola'); + INSERT INTO streetname VALUES('osprey knoll'); + INSERT INTO streetname VALUES('oxford hill'); + INSERT INTO streetname VALUES('painted fern'); + INSERT INTO streetname VALUES('painted pony'); + INSERT INTO streetname VALUES('paisley'); + INSERT INTO streetname VALUES('pale moss'); + INSERT INTO streetname VALUES('palladium'); + INSERT INTO streetname VALUES('palmutum'); + INSERT INTO streetname VALUES('palustris'); + INSERT INTO streetname VALUES('panglemont'); + INSERT INTO streetname VALUES('panther'); + INSERT INTO streetname VALUES('panthersville'); + INSERT INTO streetname VALUES('paper whites'); + INSERT INTO streetname VALUES('park'); + INSERT INTO streetname VALUES('parker green'); + INSERT INTO streetname VALUES('parkhouse'); + INSERT INTO streetname VALUES('passour ridge'); + INSERT INTO streetname VALUES('pasture view'); + INSERT INTO streetname VALUES('patricia ann'); + INSERT INTO streetname VALUES('patton'); + INSERT INTO streetname VALUES('patton ridge'); + INSERT INTO streetname VALUES('pawpaw'); + INSERT INTO streetname VALUES('peach'); + INSERT INTO streetname VALUES('peakwood'); + INSERT INTO streetname VALUES('pebble creek'); + INSERT INTO streetname VALUES('pecan cove'); + INSERT INTO streetname VALUES('pedigree'); + INSERT INTO streetname VALUES('pelorus'); + INSERT INTO streetname VALUES('penmore'); + INSERT INTO streetname VALUES('pensfold'); + INSERT INTO streetname VALUES('pepperstone'); + INSERT INTO streetname VALUES('peregrine'); + INSERT INTO streetname VALUES('periwinkle'); + INSERT INTO streetname VALUES('perkins'); + INSERT INTO streetname VALUES('pete brown'); + INSERT INTO streetname VALUES('phillips'); + INSERT INTO streetname VALUES('pickway'); + INSERT INTO streetname VALUES('piercy woods'); + INSERT INTO streetname VALUES('pierpoint'); + INSERT INTO streetname VALUES('pine'); + INSERT INTO streetname VALUES('pine branch'); + INSERT INTO streetname VALUES('pine meadow'); + INSERT INTO streetname VALUES('pineleaf'); + INSERT INTO streetname VALUES('pinewood'); + INSERT INTO streetname VALUES('pintail'); + INSERT INTO streetname VALUES('pipestone'); + INSERT INTO streetname VALUES('placer maple'); + INSERT INTO streetname VALUES('plover'); + INSERT INTO streetname VALUES('plum'); + INSERT INTO streetname VALUES('po box'); + INSERT INTO streetname VALUES('pochard'); + INSERT INTO streetname VALUES('pointview'); + INSERT INTO streetname VALUES('polk and white'); + INSERT INTO streetname VALUES('pond valley'); + INSERT INTO streetname VALUES('pondridge'); + INSERT INTO streetname VALUES('pope farm'); + INSERT INTO streetname VALUES('poplar grove'); + INSERT INTO streetname VALUES('poplar springs'); + INSERT INTO streetname VALUES('portola'); + INSERT INTO streetname VALUES('potters glen'); + INSERT INTO streetname VALUES('powatan'); + INSERT INTO streetname VALUES('prairie valley'); + INSERT INTO streetname VALUES('prescott'); + INSERT INTO streetname VALUES('presmann'); + INSERT INTO streetname VALUES('prestigious'); + INSERT INTO streetname VALUES('princess'); + INSERT INTO streetname VALUES('prosperity'); + INSERT INTO streetname VALUES('prosperity church'); + INSERT INTO streetname VALUES('prosperity commons'); + INSERT INTO streetname VALUES('prosperity park'); + INSERT INTO streetname VALUES('prosperity point'); + INSERT INTO streetname VALUES('prosperity ridge'); + INSERT INTO streetname VALUES('prosperity view'); + INSERT INTO streetname VALUES('purple finch'); + INSERT INTO streetname VALUES('quail'); + INSERT INTO streetname VALUES('queensbury'); + INSERT INTO streetname VALUES('quinn'); + INSERT INTO streetname VALUES('racine'); + INSERT INTO streetname VALUES('radbourne'); + INSERT INTO streetname VALUES('raddington'); + INSERT INTO streetname VALUES('raku'); + INSERT INTO streetname VALUES('rancliffe'); + INSERT INTO streetname VALUES('ravencrest'); + INSERT INTO streetname VALUES('reames'); + INSERT INTO streetname VALUES('rebecca run'); + INSERT INTO streetname VALUES('red bluff'); + INSERT INTO streetname VALUES('red clay'); + INSERT INTO streetname VALUES('red clover'); + INSERT INTO streetname VALUES('red rose'); + INSERT INTO streetname VALUES('red shed'); + INSERT INTO streetname VALUES('red tail'); + INSERT INTO streetname VALUES('redbridge'); + INSERT INTO streetname VALUES('redstart'); + INSERT INTO streetname VALUES('redstone view'); + INSERT INTO streetname VALUES('reedmont'); + INSERT INTO streetname VALUES('reeves'); + INSERT INTO streetname VALUES('regal'); + INSERT INTO streetname VALUES('reinbeck'); + INSERT INTO streetname VALUES('retriever'); + INSERT INTO streetname VALUES('ribbonwalk'); + INSERT INTO streetname VALUES('richardson park'); + INSERT INTO streetname VALUES('richfield'); + INSERT INTO streetname VALUES('riddings'); + INSERT INTO streetname VALUES('ridge'); + INSERT INTO streetname VALUES('ridge cliff'); + INSERT INTO streetname VALUES('ridge path'); + INSERT INTO streetname VALUES('ridge peak'); + INSERT INTO streetname VALUES('ridgefield'); + INSERT INTO streetname VALUES('ridgeline'); + INSERT INTO streetname VALUES('ridgeview commons'); + INSERT INTO streetname VALUES('riley'); + INSERT INTO streetname VALUES('riley woods'); + INSERT INTO streetname VALUES('rillet'); + INSERT INTO streetname VALUES('rindle'); + INSERT INTO streetname VALUES('rivendell'); + INSERT INTO streetname VALUES('robin'); + INSERT INTO streetname VALUES('robins nest'); + INSERT INTO streetname VALUES('robur'); + INSERT INTO streetname VALUES('robyns glen'); + INSERT INTO streetname VALUES('rock stream'); + INSERT INTO streetname VALUES('rockwell'); + INSERT INTO streetname VALUES('rockwell church'); + INSERT INTO streetname VALUES('rocky brook'); + INSERT INTO streetname VALUES('rocky ford club'); + INSERT INTO streetname VALUES('rotary'); + INSERT INTO streetname VALUES('rouda'); + INSERT INTO streetname VALUES('royal bluff'); + INSERT INTO streetname VALUES('royal celadon'); + INSERT INTO streetname VALUES('rubin lura'); + INSERT INTO streetname VALUES('runswyck'); + INSERT INTO streetname VALUES('ruth ferrell'); + INSERT INTO streetname VALUES('ruth polk'); + INSERT INTO streetname VALUES('ryan jay'); + INSERT INTO streetname VALUES('sackett'); + INSERT INTO streetname VALUES('saddle pace'); + INSERT INTO streetname VALUES('saddle run'); + INSERT INTO streetname VALUES('saddle trail'); + INSERT INTO streetname VALUES('saguaro'); + INSERT INTO streetname VALUES('saint audrey'); + INSERT INTO streetname VALUES('saint bernard'); + INSERT INTO streetname VALUES('saint frances'); + INSERT INTO streetname VALUES('sam roper'); + INSERT INTO streetname VALUES('samara'); + INSERT INTO streetname VALUES('sanders creek'); + INSERT INTO streetname VALUES('saquache'); + INSERT INTO streetname VALUES('sarnia'); + INSERT INTO streetname VALUES('savannah springs'); + INSERT INTO streetname VALUES('sawgrass ridge'); + INSERT INTO streetname VALUES('saxonbury'); + INSERT INTO streetname VALUES('scotch moss'); + INSERT INTO streetname VALUES('seasons'); + INSERT INTO streetname VALUES('serenity'); + INSERT INTO streetname VALUES('seths'); + INSERT INTO streetname VALUES('shadow lawn'); + INSERT INTO streetname VALUES('shadow oaks'); + INSERT INTO streetname VALUES('shadow pine'); + INSERT INTO streetname VALUES('shadyside'); + INSERT INTO streetname VALUES('shallow oak'); + INSERT INTO streetname VALUES('shelley'); + INSERT INTO streetname VALUES('shining oak'); + INSERT INTO streetname VALUES('ship'); + INSERT INTO streetname VALUES('shore haven'); + INSERT INTO streetname VALUES('shuman'); + INSERT INTO streetname VALUES('sidney'); + INSERT INTO streetname VALUES('silver birch'); + INSERT INTO streetname VALUES('silvermere'); + INSERT INTO streetname VALUES('simonton'); + INSERT INTO streetname VALUES('singing hills'); + INSERT INTO streetname VALUES('singing oak'); + INSERT INTO streetname VALUES('sipes'); + INSERT INTO streetname VALUES('six point'); + INSERT INTO streetname VALUES('skycrest'); + INSERT INTO streetname VALUES('skyline'); + INSERT INTO streetname VALUES('small'); + INSERT INTO streetname VALUES('smith corners'); + INSERT INTO streetname VALUES('smithwood'); + INSERT INTO streetname VALUES('snow hill'); + INSERT INTO streetname VALUES('soapstone'); + INSERT INTO streetname VALUES('sobeck'); + INSERT INTO streetname VALUES('socata'); + INSERT INTO streetname VALUES('solace'); + INSERT INTO streetname VALUES('solway'); + INSERT INTO streetname VALUES('song sparrow'); + INSERT INTO streetname VALUES('sorrento'); + INSERT INTO streetname VALUES('spector'); + INSERT INTO streetname VALUES('spin drift'); + INSERT INTO streetname VALUES('spring crest'); + INSERT INTO streetname VALUES('spring lee'); + INSERT INTO streetname VALUES('spring park'); + INSERT INTO streetname VALUES('spring terrace'); + INSERT INTO streetname VALUES('spring trace'); + INSERT INTO streetname VALUES('springhaven'); + INSERT INTO streetname VALUES('squirrel trail'); + INSERT INTO streetname VALUES('stardust'); + INSERT INTO streetname VALUES('stargaze'); + INSERT INTO streetname VALUES('starita'); + INSERT INTO streetname VALUES('starmount'); + INSERT INTO streetname VALUES('statesville'); + INSERT INTO streetname VALUES('steed'); + INSERT INTO streetname VALUES('steelewood'); + INSERT INTO streetname VALUES('steepleglen'); + INSERT INTO streetname VALUES('stephens farm'); + INSERT INTO streetname VALUES('stewarton'); + INSERT INTO streetname VALUES('stone park'); + INSERT INTO streetname VALUES('stonebrook'); + INSERT INTO streetname VALUES('stonefield'); + INSERT INTO streetname VALUES('stoneglen'); + INSERT INTO streetname VALUES('stonemarsh'); + INSERT INTO streetname VALUES('stoney garden'); + INSERT INTO streetname VALUES('stoney run'); + INSERT INTO streetname VALUES('stoney valley'); + INSERT INTO streetname VALUES('stoneykirk'); + INSERT INTO streetname VALUES('stream bank'); + INSERT INTO streetname VALUES('stream ridge'); + INSERT INTO streetname VALUES('suburban'); + INSERT INTO streetname VALUES('suffield'); + INSERT INTO streetname VALUES('sugar creek'); + INSERT INTO streetname VALUES('sugarberry'); + INSERT INTO streetname VALUES('sugarstone'); + INSERT INTO streetname VALUES('summer creek'); + INSERT INTO streetname VALUES('summer valley'); + INSERT INTO streetname VALUES('summercrest'); + INSERT INTO streetname VALUES('summercroft'); + INSERT INTO streetname VALUES('summerford'); + INSERT INTO streetname VALUES('summergold'); + INSERT INTO streetname VALUES('sunbeam'); + INSERT INTO streetname VALUES('sunbridge'); + INSERT INTO streetname VALUES('sunpath'); + INSERT INTO streetname VALUES('sunset'); + INSERT INTO streetname VALUES('sunset ridge'); + INSERT INTO streetname VALUES('sunstone'); + INSERT INTO streetname VALUES('suntrace'); + INSERT INTO streetname VALUES('sunwalk'); + INSERT INTO streetname VALUES('sutters hill'); + INSERT INTO streetname VALUES('suttonview'); + INSERT INTO streetname VALUES('swallow tail'); + INSERT INTO streetname VALUES('swanston'); + INSERT INTO streetname VALUES('sweet grove'); + INSERT INTO streetname VALUES('sweet rose'); + INSERT INTO streetname VALUES('sweetbriar ridge'); + INSERT INTO streetname VALUES('sweetfield'); + INSERT INTO streetname VALUES('sydney overlook'); + INSERT INTO streetname VALUES('sylvan'); + INSERT INTO streetname VALUES('symphony woods'); + INSERT INTO streetname VALUES('tallia'); + INSERT INTO streetname VALUES('tallu'); + INSERT INTO streetname VALUES('talwyn'); + INSERT INTO streetname VALUES('tanager'); + INSERT INTO streetname VALUES('tanager park'); + INSERT INTO streetname VALUES('tangley'); + INSERT INTO streetname VALUES('taranasay'); + INSERT INTO streetname VALUES('tarby'); + INSERT INTO streetname VALUES('tarland'); + INSERT INTO streetname VALUES('tarpway'); + INSERT INTO streetname VALUES('tauten'); + INSERT INTO streetname VALUES('taymouth'); + INSERT INTO streetname VALUES('ten trees'); + INSERT INTO streetname VALUES('terrace view'); + INSERT INTO streetname VALUES('terrier'); + INSERT INTO streetname VALUES('tesh'); + INSERT INTO streetname VALUES('teton'); + INSERT INTO streetname VALUES('tewkesbury'); + INSERT INTO streetname VALUES('thelema'); + INSERT INTO streetname VALUES('thistle bloom'); + INSERT INTO streetname VALUES('thistledown'); + INSERT INTO streetname VALUES('thomas ridge'); + INSERT INTO streetname VALUES('thornbrook'); + INSERT INTO streetname VALUES('tifton grass'); + INSERT INTO streetname VALUES('tigerton'); + INSERT INTO streetname VALUES('tomsie efird'); + INSERT INTO streetname VALUES('tor'); + INSERT INTO streetname VALUES('torphin'); + INSERT INTO streetname VALUES('torrence'); + INSERT INTO streetname VALUES('towering pine'); + INSERT INTO streetname VALUES('towhee'); + INSERT INTO streetname VALUES('toxaway'); + INSERT INTO streetname VALUES('tracy glenn'); + INSERT INTO streetname VALUES('tradition view'); + INSERT INTO streetname VALUES('trailer'); + INSERT INTO streetname VALUES('transport'); + INSERT INTO streetname VALUES('trehurst'); + INSERT INTO streetname VALUES('trexler'); + INSERT INTO streetname VALUES('trillium fields'); + INSERT INTO streetname VALUES('trimbach'); + INSERT INTO streetname VALUES('tucker'); + INSERT INTO streetname VALUES('tullamore'); + INSERT INTO streetname VALUES('tullock creek'); + INSERT INTO streetname VALUES('tunston'); + INSERT INTO streetname VALUES('tupelo'); + INSERT INTO streetname VALUES('turnabout'); + INSERT INTO streetname VALUES('turney'); + INSERT INTO streetname VALUES('turtle cross'); + INSERT INTO streetname VALUES('turtleback'); + INSERT INTO streetname VALUES('twelvestone'); + INSERT INTO streetname VALUES('twin'); + INSERT INTO streetname VALUES('twin brook'); + INSERT INTO streetname VALUES('twin lakes'); + INSERT INTO streetname VALUES('twisted pine'); + INSERT INTO streetname VALUES('tyler finley'); + INSERT INTO streetname VALUES('university station'); + INSERT INTO streetname VALUES('uphill'); + INSERT INTO streetname VALUES('valeview'); + INSERT INTO streetname VALUES('valhalla'); + INSERT INTO streetname VALUES('van'); + INSERT INTO streetname VALUES('vance davis'); + INSERT INTO streetname VALUES('vanhoy'); + INSERT INTO streetname VALUES('veckman'); + INSERT INTO streetname VALUES('victoria'); + INSERT INTO streetname VALUES('victory'); + INSERT INTO streetname VALUES('village glen'); + INSERT INTO streetname VALUES('vireo'); + INSERT INTO streetname VALUES('viscount'); + INSERT INTO streetname VALUES('voeltz'); + INSERT INTO streetname VALUES('wade e morgan'); + INSERT INTO streetname VALUES('wake'); + INSERT INTO streetname VALUES('wales'); + INSERT INTO streetname VALUES('wallace ridge'); + INSERT INTO streetname VALUES('waltham'); + INSERT INTO streetname VALUES('wanamassa'); + INSERT INTO streetname VALUES('warbler wood'); + INSERT INTO streetname VALUES('washington'); + INSERT INTO streetname VALUES('water'); + INSERT INTO streetname VALUES('waterelm'); + INSERT INTO streetname VALUES('waterford hills'); + INSERT INTO streetname VALUES('waterford valley'); + INSERT INTO streetname VALUES('waterloo'); + INSERT INTO streetname VALUES('waterton leas'); + INSERT INTO streetname VALUES('waverly lynn'); + INSERT INTO streetname VALUES('waverlyglen'); + INSERT INTO streetname VALUES('wayside'); + INSERT INTO streetname VALUES('westbury lake'); + INSERT INTO streetname VALUES('westray'); + INSERT INTO streetname VALUES('whistlers chase'); + INSERT INTO streetname VALUES('whistley green'); + INSERT INTO streetname VALUES('whistling oak'); + INSERT INTO streetname VALUES('whitcomb'); + INSERT INTO streetname VALUES('white aspen'); + INSERT INTO streetname VALUES('white cascade'); + INSERT INTO streetname VALUES('white mist'); + INSERT INTO streetname VALUES('white rock'); + INSERT INTO streetname VALUES('white stag'); + INSERT INTO streetname VALUES('whitegate'); + INSERT INTO streetname VALUES('whitehill'); + INSERT INTO streetname VALUES('whitetail'); + INSERT INTO streetname VALUES('whitewood'); + INSERT INTO streetname VALUES('wilburn park'); + INSERT INTO streetname VALUES('wild garden'); + INSERT INTO streetname VALUES('wild rose'); + INSERT INTO streetname VALUES('wilkins terrace'); + INSERT INTO streetname VALUES('william ficklen'); + INSERT INTO streetname VALUES('wiltshire ridge'); + INSERT INTO streetname VALUES('windchase'); + INSERT INTO streetname VALUES('winding jordan'); + INSERT INTO streetname VALUES('windy meadow'); + INSERT INTO streetname VALUES('winghaven'); + INSERT INTO streetname VALUES('wingmont'); + INSERT INTO streetname VALUES('winslow'); + INSERT INTO streetname VALUES('winter pine'); + INSERT INTO streetname VALUES('winter view'); + INSERT INTO streetname VALUES('wolf creek'); + INSERT INTO streetname VALUES('wondering oak'); + INSERT INTO streetname VALUES('woodard'); + INSERT INTO streetname VALUES('woodfire'); + INSERT INTO streetname VALUES('woodland commons'); + INSERT INTO streetname VALUES('woodland hills'); + INSERT INTO streetname VALUES('woodnotch'); + INSERT INTO streetname VALUES('woodstone'); + INSERT INTO streetname VALUES('worsley'); + INSERT INTO streetname VALUES('wren creek'); + INSERT INTO streetname VALUES('wrens nest'); + INSERT INTO streetname VALUES('wrexham'); + INSERT INTO streetname VALUES('wt harris'); + INSERT INTO streetname VALUES('wylie meadow'); + INSERT INTO streetname VALUES('wynborough'); + INSERT INTO streetname VALUES('wynbrook'); + INSERT INTO streetname VALUES('wyndham hill'); + INSERT INTO streetname VALUES('yandem'); + INSERT INTO streetname VALUES('yellow rose'); + INSERT INTO streetname VALUES('yellow spaniel'); + INSERT INTO streetname VALUES('yorkford'); + INSERT INTO streetname VALUES('ziegler'); + INSERT INTO streetname VALUES('zion renaissance'); + + SELECT count(*) FROM streetname; + } +} {1228} + +do_test fuzzer1-2.1 { + execsql { + SELECT n, distance FROM f2, streetname + WHERE f2.word MATCH 'wersley' + AND f2.distance<=150 + AND f2.word=streetname.n + } +} {worsley 37} +do_test fuzzer1-2.2 { + execsql { + SELECT n, distance FROM f2, streetname + WHERE f2.word MATCH 'testledown' + AND f2.distance<=150 + AND f2.word=streetname.n + } +} {thistledown 103} +do_test fuzzer1-2.3 { + execsql { + SELECT DISTINCT streetname.n FROM f2, streetname + WHERE f2.word MATCH 'tayle' + AND f2.distance<=200 + AND streetname.n>=f2.word AND streetname.n<=(f2.word || x'F7BFBFBF') + } +} {{tyler finley} trailer taymouth steelewood tallia tallu talwyn thelema} +do_test fuzzer1-2.4 { + execsql { + SELECT DISTINCT streetname.n + FROM f2 JOIN streetname + ON (streetname.n>=f2.word AND streetname.n<=(f2.word || 'zzzzzz')) + WHERE f2.word MATCH 'duck' + AND f2.distance<150 + AND f2.ruleset=3 + ORDER BY 1 + } +} {mallard {mallard cove} {mallard forest} {mallard grove} {mallard hill} {mallard park} {mallard ridge} {mallard view}} +do_test fuzzer1-2.5 { + execsql { + SELECT DISTINCT streetname.n + FROM f2 JOIN streetname + ON (streetname.n>=f2.word AND streetname.n<=(f2.word || 'zzzzzz')) + WHERE f2.word MATCH 'duck' + AND f2.distance<150 + AND f2.ruleset=2 + ORDER BY 1 + } +} {} + +forcedelete test.db2 +do_execsql_test fuzzer1-4.1 { + ATTACH 'test.db2' AS aux; + CREATE TABLE aux.f3_rules(ruleset, cfrom, cto, cost); + INSERT INTO f3_rules(ruleset, cfrom, cto, cost) VALUES(0, 'x','y', 10); + INSERT INTO f3_rules(ruleset, cfrom, cto, cost) VALUES(1, 'a','b', 10); + CREATE VIRTUAL TABLE aux.f3 USING fuzzer(f3_rules); + SELECT word FROM f3 WHERE word MATCH 'ax' +} {ax ay} + +#------------------------------------------------------------------------- +# +# 1.5.1 - Check things work with a fuzzer data table name that requires +# quoting. Also that NULL entries in the "from" column of the +# data table are treated as zero length strings (''). +# +# 1.5.2 - Check that no-op rules (i.e. C->C) are ignored. Test NULL in +# the "to" column of a fuzzer data table. +# +# 1.5.3 - Test out-of-range values for the cost field of the data table. +# +# 1.5.4 - Test out-of-range values for the string fields of the data table. +# +# 1.5.5 - Test out-of-range values for the ruleset field of the data table. +# +do_execsql_test 5.1 { + CREATE TABLE "fuzzer [x] rules table"(a, b, c, d); + INSERT INTO "fuzzer [x] rules table" VALUES(0, NULL, 'abc', 10); + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); + SELECT word, distance FROM x WHERE word MATCH '123' LIMIT 4; +} {123 0 abc123 10 1abc23 10 12abc3 10} + +do_execsql_test 5.2 { + DELETE FROM "fuzzer [x] rules table"; + INSERT INTO "fuzzer [x] rules table" VALUES(0, 'x', NULL, 20); + INSERT INTO "fuzzer [x] rules table" VALUES(0, NULL, NULL, 10); + INSERT INTO "fuzzer [x] rules table" VALUES(0, 'x', 'x', 10); + + DROP TABLE x; + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); + + SELECT word, distance FROM x WHERE word MATCH 'xx'; +} {xx 0 x 20 {} 40} + +do_execsql_test 5.3.1 { + DROP TABLE IF EXISTS x; + INSERT INTO "fuzzer [x] rules table" VALUES(0, 'c', 'd', 1001); +} +do_catchsql_test 5.3.2 { + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); +} {1 {fuzzer: cost must be between 1 and 1000}} + +do_execsql_test 5.3.3 { + DROP TABLE IF EXISTS x; + DELETE FROM "fuzzer [x] rules table"; + INSERT INTO "fuzzer [x] rules table" VALUES(0, 'd', 'c', 0); +} +do_catchsql_test 5.3.4 { + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); +} {1 {fuzzer: cost must be between 1 and 1000}} + +do_execsql_test 5.3.5 { + DROP TABLE IF EXISTS x; + DELETE FROM "fuzzer [x] rules table"; + INSERT INTO "fuzzer [x] rules table" VALUES(0, 'd', 'c', -20); +} +do_catchsql_test 5.3.6 { + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); +} {1 {fuzzer: cost must be between 1 and 1000}} + +do_execsql_test 5.4.1 { + DROP TABLE IF EXISTS x; + DELETE FROM "fuzzer [x] rules table"; + INSERT INTO "fuzzer [x] rules table" VALUES( + 0, 'x', '12345678901234567890123456789012345678901234567890', 2 + ); + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); + SELECT word FROM x WHERE word MATCH 'x'; +} {x 12345678901234567890123456789012345678901234567890} + +do_execsql_test 5.4.2 { + DROP TABLE IF EXISTS x; + DELETE FROM "fuzzer [x] rules table"; + INSERT INTO "fuzzer [x] rules table" VALUES( + 0, 'x', '123456789012345678901234567890123456789012345678901', 2 + ); +} +do_catchsql_test 5.4.3 { + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); +} {1 {fuzzer: maximum string length is 50}} + +do_execsql_test 5.4.4 { + DROP TABLE IF EXISTS x; + DELETE FROM "fuzzer [x] rules table"; + INSERT INTO "fuzzer [x] rules table" VALUES( + 0, '123456789012345678901234567890123456789012345678901', 'x', 2 + ); +} +do_catchsql_test 5.4.5 { + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); +} {1 {fuzzer: maximum string length is 50}} + +do_execsql_test 5.5.1 { + DROP TABLE IF EXISTS x; + DELETE FROM "fuzzer [x] rules table"; + INSERT INTO "fuzzer [x] rules table" VALUES(-1, 'x', 'y', 2); +} +do_catchsql_test 5.5.2 { + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); +} {1 {fuzzer: ruleset must be between 0 and 2147483647}} + +do_execsql_test 5.5.3 { + DROP TABLE IF EXISTS x; + DELETE FROM "fuzzer [x] rules table"; + INSERT INTO "fuzzer [x] rules table" VALUES((1<<32)+100, 'x', 'y', 2); +} +do_catchsql_test 5.5.4 { + CREATE VIRTUAL TABLE x USING fuzzer('fuzzer [x] rules table'); +} {1 {fuzzer: ruleset must be between 0 and 2147483647}} + +#------------------------------------------------------------------------- +# This test uses a fuzzer table with many rules. There is one rule to +# map each possible two character string, where characters are lower-case +# letters used in the English language, to all other possible two character +# strings. In total, (26^4)-(26^2) mappings (the subtracted term represents +# the no-op mappings discarded automatically by the fuzzer). +# +# +do_execsql_test 6.1.1 { + DROP TABLE IF EXISTS x1; + DROP TABLE IF EXISTS x1_rules; + CREATE TABLE x1_rules(ruleset, cFrom, cTo, cost); +} +puts "This test is slow - perhaps around 7 seconds on an average pc" +do_test 6.1.2 { + set LETTERS {a b c d e f g h i j k l m n o p q r s t u v w x y z} + set cost 1 + db transaction { + foreach c1 $LETTERS { + foreach c2 $LETTERS { + foreach c3 $LETTERS { + foreach c4 $LETTERS { + db eval {INSERT INTO x1_rules VALUES(0, $c1||$c2, $c3||$c4, $cost)} + set cost [expr ($cost%1000) + 1] + } + } + } + } + db eval {UPDATE x1_rules SET cost = 20 WHERE cost<20 AND cFrom!='xx'} + } +} {} + +do_execsql_test 6.2 { + SELECT count(*) FROM x1_rules WHERE cTo!=cFrom; +} [expr 26*26*26*26 - 26*26] + +do_execsql_test 6.2.1 { + CREATE VIRTUAL TABLE x1 USING fuzzer(x1_rules); + SELECT word FROM x1 WHERE word MATCH 'xx' LIMIT 10; +} {xx hw hx hy hz ia ib ic id ie} +do_execsql_test 6.2.2 { + SELECT cTo FROM x1_rules WHERE cFrom='xx' + ORDER BY cost asc, rowid asc LIMIT 9; +} {hw hx hy hz ia ib ic id ie} + +#------------------------------------------------------------------------- +# Test using different types of quotes with CREATE VIRTUAL TABLE +# arguments. +# +do_execsql_test 7.1 { + CREATE TABLE [x2 "rules] (a, b, c, d); + INSERT INTO [x2 "rules] VALUES(0, 'a', 'b', 5); +} +foreach {tn sql} { + 1 { CREATE VIRTUAL TABLE x2 USING fuzzer( [x2 "rules] ) } + 2 { CREATE VIRTUAL TABLE x2 USING fuzzer( "x2 ""rules" ) } + 3 { CREATE VIRTUAL TABLE x2 USING fuzzer( 'x2 "rules' ) } + 4 { CREATE VIRTUAL TABLE x2 USING fuzzer( `x2 "rules` ) } +} { + do_execsql_test 7.2.$tn.1 { DROP TABLE IF EXISTS x2 } + do_execsql_test 7.2.$tn.2 $sql + do_execsql_test 7.2.$tn.3 { + SELECT word FROM x2 WHERE word MATCH 'aaa' + } {aaa baa aba aab bab abb bba bbb} +} + +#------------------------------------------------------------------------- +# Test using a fuzzer table in different contexts. +# +do_execsql_test 8.1 { + CREATE TABLE x3_rules(rule_set, cFrom, cTo, cost); + INSERT INTO x3_rules VALUES(2, 'a', 'x', 10); + INSERT INTO x3_rules VALUES(2, 'a', 'y', 9); + INSERT INTO x3_rules VALUES(2, 'a', 'z', 8); + CREATE VIRTUAL TABLE x3 USING fuzzer(x3_rules); +} + +do_execsql_test 8.2.1 { + SELECT cFrom, cTo, word + FROM x3_rules CROSS JOIN x3 + WHERE word MATCH 'a' AND cost=distance AND ruleset=2 + ORDER BY +cTo; +} {a x x a y y a z z} + +do_execsql_test 8.2.2 { + SELECT cFrom, cTo, word + FROM x3 CROSS JOIN x3_rules + WHERE word MATCH 'a' AND cost=distance AND ruleset=2 + ORDER BY +cTo DESC +} {a z z a y y a x x} + +do_execsql_test 8.2.3 { + SELECT cFrom, cTo, word + FROM x3_rules, x3 + WHERE word MATCH 'a' AND cost=distance AND ruleset=2 + ORDER BY +cTo DESC; +} {a z z a y y a x x} + +do_execsql_test 8.2.4 { + SELECT cFrom, cTo, word + FROM x3, x3_rules + WHERE word MATCH 'a' AND cost=distance AND ruleset=2 + ORDER BY +cTo DESC; +} {a z z a y y a x x} + +do_execsql_test 8.2.5 { + CREATE INDEX i1 ON x3_rules(cost); + SELECT cFrom, cTo, word + FROM x3_rules, x3 + WHERE word MATCH 'a' AND cost=distance AND ruleset=2 + ORDER BY +cTo DESC; +} {a z z a y y a x x} + +do_execsql_test 8.2.5 { + SELECT word FROM x3_rules, x3 WHERE word MATCH x3_rules.cFrom AND ruleset=2 +} {a z y x a z y x a z y x} + +do_execsql_test 8.2.6 { + SELECT word FROM x3_rules, x3 + WHERE word MATCH x3_rules.cFrom + AND ruleset=2 + AND x3_rules.cost=8; +} {a z y x} + +do_execsql_test 8.2.7 { + CREATE TABLE t1(a, b); + CREATE INDEX i2 ON t1(b); + SELECT word, distance FROM x3, t1 + WHERE x3.word MATCH t1.a AND ruleset=2 AND distance=t1.b; +} {} + +do_execsql_test 8.2.8 { + INSERT INTO x3_rules VALUES(1, 'a', 't', 5); + INSERT INTO x3_rules VALUES(1, 'a', 'u', 4); + INSERT INTO x3_rules VALUES(1, 'a', 'v', 3); + DROP TABLE x3; + CREATE VIRTUAL TABLE x3 USING fuzzer(x3_rules); + SELECT * FROM x3_rules; +} { + 2 a x 10 + 2 a y 9 + 2 a z 8 + 1 a t 5 + 1 a u 4 + 1 a v 3 +} + +do_catchsql_test 8.2.9 { + SELECT word FROM x3 WHERE ruleset=2 AND word MATCH 'a' AND WORD MATCH 'b'; +} {1 {unable to use function MATCH in the requested context}} + +do_execsql_test 8.2.10 { + SELECT word FROM x3 WHERE ruleset=1 AND word MATCH 'a' +} {a v u t} + +# The term "ruleset<=1" is not handled by the fuzzer module. Instead, it +# is handled by SQLite, which assumes that all rows have a NULL value in +# the ruleset column. Since NULL<=1 is never true, this query returns +# no rows. +do_execsql_test 8.2.11 { + SELECT word FROM x3 WHERE ruleset<=1 AND word MATCH 'a' +} {} + +do_execsql_test 8.2.12 { + SELECT word FROM x3 WHERE ruleset=1 AND word MATCH 'a' ORDER BY distance ASC; +} {a v u t} + +do_execsql_test 8.2.13 { + SELECT word FROM x3 WHERE ruleset=1 AND word MATCH 'a' ORDER BY distance DESC; +} {t u v a} + +do_execsql_test 8.2.13 { + SELECT word FROM x3 WHERE ruleset=1 AND word MATCH 'a' ORDER BY word ASC; +} {a t u v} + +do_execsql_test 8.2.14 { + SELECT word FROM x3 WHERE ruleset=1 AND word MATCH 'a' ORDER BY word DESC; +} {v u t a} + +#------------------------------------------------------------------------- +# +do_execsql_test 9.1 { + CREATE TABLE x4_rules(a, b, c, d); + INSERT INTO x4_rules VALUES(0, 'a', 'b', 10); + INSERT INTO x4_rules VALUES(0, 'a', 'c', 11); + INSERT INTO x4_rules VALUES(0, 'bx', 'zz', 20); + INSERT INTO x4_rules VALUES(0, 'cx', 'yy', 15); + INSERT INTO x4_rules VALUES(0, 'zz', '!!', 50); + CREATE VIRTUAL TABLE x4 USING fuzzer(x4_rules); +} + +do_execsql_test 9.2 { + SELECT word, distance FROM x4 WHERE word MATCH 'ax'; +} {ax 0 bx 10 cx 11 yy 26 zz 30 !! 80} + + +do_execsql_test 10.1 { + CREATE TABLE x5_rules(a, b, c, d); + CREATE VIRTUAL TABLE x5 USING fuzzer(x5_rules); +} + +do_execsql_test 10.2 { + SELECT word, distance FROM x5 WHERE word MATCH + 'aaaaaaaaaXaaaaaaaaaXaaaaaaaaaXaaaaaaaaaXaaaaaaaaa' || + 'aaaaaaaaaXaaaaaaaaaXaaaaaaaaaXaaaaaaaaaXaaaaaaaaa' || + 'aaaaaaaaaXaaaaaaaaaXaaaaaaaaaXaaaaaaaaaXaaaaaaaaa' +} {} + +do_execsql_test 10.3 { + INSERT INTO x5_rules VALUES(0, 'a', '0.1.2.3.4.5.6.7.8.9.a', 1); + DROP TABLE x5; + CREATE VIRTUAL TABLE x5 USING fuzzer(x5_rules); + SELECT length(word) FROM x5 WHERE word MATCH 'a' LIMIT 50; +} {1 21 41 61 81} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/fuzzerfault.test b/components/external/SQLite-3.8.1/test/fuzzerfault.test new file mode 100644 index 0000000000000000000000000000000000000000..6449612a66d605dc481cb9b730b5e2c8b01e4202 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/fuzzerfault.test @@ -0,0 +1,92 @@ +# 2012 February 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for TCL interface to the +# SQLite library. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !vtab { finish_test ; return } +set ::testprefix fuzzerfault + +load_static_extension db fuzzer + +do_test 1-pre1 { + execsql { + CREATE TABLE x1_rules(ruleset, cFrom, cTo, cost); + INSERT INTO x1_rules VALUES(0, 'a', 'b', 1); + INSERT INTO x1_rules VALUES(0, 'a', 'c', 2); + INSERT INTO x1_rules VALUES(0, 'a', 'd', 3); + } + faultsim_save_and_close +} {} +do_faultsim_test 1 -prep { + faultsim_restore_and_reopen + load_static_extension db fuzzer +} -body { + execsql { + CREATE VIRTUAL TABLE x1 USING fuzzer(x1_rules); + SELECT word FROM x1 WHERE word MATCH 'xax'; + } +} -test { + faultsim_test_result {0 {xax xbx xcx xdx}} \ + {1 {vtable constructor failed: x1}} +} + +do_test 2-pre1 { + faultsim_delete_and_reopen + load_static_extension db fuzzer + execsql { + CREATE TABLE x2_rules(ruleset, cFrom, cTo, cost); + INSERT INTO x2_rules VALUES(0, 'a', 'x', 1); + INSERT INTO x2_rules VALUES(0, 'b', 'x', 2); + INSERT INTO x2_rules VALUES(0, 'c', 'x', 3); + CREATE VIRTUAL TABLE x2 USING fuzzer(x2_rules); + } + faultsim_save_and_close +} {} + +do_faultsim_test 2 -prep { + faultsim_restore_and_reopen + load_static_extension db fuzzer +} -body { + execsql { + SELECT count(*) FROM x2 WHERE word MATCH 'abc'; + } +} -test { + faultsim_test_result {0 8} {1 {vtable constructor failed: x2}} +} + +do_test 3-pre1 { + faultsim_delete_and_reopen + execsql { + CREATE TABLE x1_rules(ruleset, cFrom, cTo, cost); + INSERT INTO x1_rules VALUES(0, 'a', + '123456789012345678901234567890a1234567890123456789', 10 + ); + } + faultsim_save_and_close +} {} + +do_faultsim_test 3 -prep { + faultsim_restore_and_reopen + load_static_extension db fuzzer +} -body { + execsql { + CREATE VIRTUAL TABLE x1 USING fuzzer(x1_rules); + SELECT count(*) FROM (SELECT * FROM x1 WHERE word MATCH 'a' LIMIT 2); + } +} -test { + faultsim_test_result {0 2} {1 {vtable constructor failed: x1}} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/genesis.tcl b/components/external/SQLite-3.8.1/test/genesis.tcl new file mode 100644 index 0000000000000000000000000000000000000000..4ba4c8ea214feb4ce42a3fa0a0bbf717f89cfe31 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/genesis.tcl @@ -0,0 +1,1560 @@ +# 2010 February 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements a TCL function that fills an FTS table with +# lots of content useful for testing. This routine is broken out into +# a separate file to facilitate its use by multiple test scripts. +# + +# The fts_kjv_genesis routine is already loaded. This script is a no-op. +if {[lsearch [info procs] fts_kjv_genesis]>=0} return + +# This procedure fills an existing FTS3/FTS4 table with many entries. +# The table needs to have a single column (other than docid) named "words". +# +proc fts_kjv_genesis {} { +db eval { +BEGIN TRANSACTION; +INSERT INTO t1(docid,words) VALUES(1001001,'In the beginning God created the heaven and the earth.'); +INSERT INTO t1(docid,words) VALUES(1001002,'And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.'); +INSERT INTO t1(docid,words) VALUES(1001003,'And God said, Let there be light: and there was light.'); +INSERT INTO t1(docid,words) VALUES(1001004,'And God saw the light, that it was good: and God divided the light from the darkness.'); +INSERT INTO t1(docid,words) VALUES(1001005,'And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day.'); +INSERT INTO t1(docid,words) VALUES(1001006,'And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters.'); +INSERT INTO t1(docid,words) VALUES(1001007,'And God made the firmament, and divided the waters which were under the firmament from the waters which were above the firmament: and it was so.'); +INSERT INTO t1(docid,words) VALUES(1001008,'And God called the firmament Heaven. And the evening and the morning were the second day.'); +INSERT INTO t1(docid,words) VALUES(1001009,'And God said, Let the waters under the heaven be gathered together unto one place, and let the dry land appear: and it was so.'); +INSERT INTO t1(docid,words) VALUES(1001010,'And God called the dry land Earth; and the gathering together of the waters called he Seas: and God saw that it was good.'); +INSERT INTO t1(docid,words) VALUES(1001011,'And God said, Let the earth bring forth grass, the herb yielding seed, and the fruit tree yielding fruit after his kind, whose seed is in itself, upon the earth: and it was so.'); +INSERT INTO t1(docid,words) VALUES(1001012,'And the earth brought forth grass, and herb yielding seed after his kind, and the tree yielding fruit, whose seed was in itself, after his kind: and God saw that it was good.'); +INSERT INTO t1(docid,words) VALUES(1001013,'And the evening and the morning were the third day.'); +INSERT INTO t1(docid,words) VALUES(1001014,'And God said, Let there be lights in the firmament of the heaven to divide the day from the night; and let them be for signs, and for seasons, and for days, and years:'); +INSERT INTO t1(docid,words) VALUES(1001015,'And let them be for lights in the firmament of the heaven to give light upon the earth: and it was so.'); +INSERT INTO t1(docid,words) VALUES(1001016,'And God made two great lights; the greater light to rule the day, and the lesser light to rule the night: he made the stars also.'); +INSERT INTO t1(docid,words) VALUES(1001017,'And God set them in the firmament of the heaven to give light upon the earth,'); +INSERT INTO t1(docid,words) VALUES(1001018,'And to rule over the day and over the night, and to divide the light from the darkness: and God saw that it was good.'); +INSERT INTO t1(docid,words) VALUES(1001019,'And the evening and the morning were the fourth day.'); +INSERT INTO t1(docid,words) VALUES(1001020,'And God said, Let the waters bring forth abundantly the moving creature that hath life, and fowl that may fly above the earth in the open firmament of heaven.'); +INSERT INTO t1(docid,words) VALUES(1001021,'And God created great whales, and every living creature that moveth, which the waters brought forth abundantly, after their kind, and every winged fowl after his kind: and God saw that it was good.'); +INSERT INTO t1(docid,words) VALUES(1001022,'And God blessed them, saying, Be fruitful, and multiply, and fill the waters in the seas, and let fowl multiply in the earth.'); +INSERT INTO t1(docid,words) VALUES(1001023,'And the evening and the morning were the fifth day.'); +INSERT INTO t1(docid,words) VALUES(1001024,'And God said, Let the earth bring forth the living creature after his kind, cattle, and creeping thing, and beast of the earth after his kind: and it was so.'); +INSERT INTO t1(docid,words) VALUES(1001025,'And God made the beast of the earth after his kind, and cattle after their kind, and every thing that creepeth upon the earth after his kind: and God saw that it was good.'); +INSERT INTO t1(docid,words) VALUES(1001026,'And God said, Let us make man in our image, after our likeness: and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle, and over all the earth, and over every creeping thing that creepeth upon the earth.'); +INSERT INTO t1(docid,words) VALUES(1001027,'So God created man in his own image, in the image of God created he him; male and female created he them.'); +INSERT INTO t1(docid,words) VALUES(1001028,'And God blessed them, and God said unto them, Be fruitful, and multiply, and replenish the earth, and subdue it: and have dominion over the fish of the sea, and over the fowl of the air, and over every living thing that moveth upon the earth.'); +INSERT INTO t1(docid,words) VALUES(1001029,'And God said, Behold, I have given you every herb bearing seed, which is upon the face of all the earth, and every tree, in the which is the fruit of a tree yielding seed; to you it shall be for meat.'); +INSERT INTO t1(docid,words) VALUES(1001030,'And to every beast of the earth, and to every fowl of the air, and to every thing that creepeth upon the earth, wherein there is life, I have given every green herb for meat: and it was so.'); +INSERT INTO t1(docid,words) VALUES(1001031,'And God saw every thing that he had made, and, behold, it was very good. And the evening and the morning were the sixth day.'); +INSERT INTO t1(docid,words) VALUES(1002001,'Thus the heavens and the earth were finished, and all the host of them.'); +INSERT INTO t1(docid,words) VALUES(1002002,'And on the seventh day God ended his work which he had made; and he rested on the seventh day from all his work which he had made.'); +INSERT INTO t1(docid,words) VALUES(1002003,'And God blessed the seventh day, and sanctified it: because that in it he had rested from all his work which God created and made.'); +INSERT INTO t1(docid,words) VALUES(1002004,'These are the generations of the heavens and of the earth when they were created, in the day that the LORD God made the earth and the heavens,'); +INSERT INTO t1(docid,words) VALUES(1002005,'And every plant of the field before it was in the earth, and every herb of the field before it grew: for the LORD God had not caused it to rain upon the earth, and there was not a man to till the ground.'); +INSERT INTO t1(docid,words) VALUES(1002006,'But there went up a mist from the earth, and watered the whole face of the ground.'); +INSERT INTO t1(docid,words) VALUES(1002007,'And the LORD God formed man of the dust of the ground, and breathed into his nostrils the breath of life; and man became a living soul.'); +INSERT INTO t1(docid,words) VALUES(1002008,'And the LORD God planted a garden eastward in Eden; and there he put the man whom he had formed.'); +INSERT INTO t1(docid,words) VALUES(1002009,'And out of the ground made the LORD God to grow every tree that is pleasant to the sight, and good for food; the tree of life also in the midst of the garden, and the tree of knowledge of good and evil.'); +INSERT INTO t1(docid,words) VALUES(1002010,'And a river went out of Eden to water the garden; and from thence it was parted, and became into four heads.'); +INSERT INTO t1(docid,words) VALUES(1002011,'The name of the first is Pison: that is it which compasseth the whole land of Havilah, where there is gold;'); +INSERT INTO t1(docid,words) VALUES(1002012,'And the gold of that land is good: there is bdellium and the onyx stone.'); +INSERT INTO t1(docid,words) VALUES(1002013,'And the name of the second river is Gihon: the same is it that compasseth the whole land of Ethiopia.'); +INSERT INTO t1(docid,words) VALUES(1002014,'And the name of the third river is Hiddekel: that is it which goeth toward the east of Assyria. And the fourth river is Euphrates.'); +INSERT INTO t1(docid,words) VALUES(1002015,'And the LORD God took the man, and put him into the garden of Eden to dress it and to keep it.'); +INSERT INTO t1(docid,words) VALUES(1002016,'And the LORD God commanded the man, saying, Of every tree of the garden thou mayest freely eat:'); +INSERT INTO t1(docid,words) VALUES(1002017,'But of the tree of the knowledge of good and evil, thou shalt not eat of it: for in the day that thou eatest thereof thou shalt surely die.'); +INSERT INTO t1(docid,words) VALUES(1002018,'And the LORD God said, It is not good that the man should be alone; I will make him an help meet for him.'); +INSERT INTO t1(docid,words) VALUES(1002019,'And out of the ground the LORD God formed every beast of the field, and every fowl of the air; and brought them unto Adam to see what he would call them: and whatsoever Adam called every living creature, that was the name thereof.'); +INSERT INTO t1(docid,words) VALUES(1002020,'And Adam gave names to all cattle, and to the fowl of the air, and to every beast of the field; but for Adam there was not found an help meet for him.'); +INSERT INTO t1(docid,words) VALUES(1002021,'And the LORD God caused a deep sleep to fall upon Adam, and he slept: and he took one of his ribs, and closed up the flesh instead thereof;'); +INSERT INTO t1(docid,words) VALUES(1002022,'And the rib, which the LORD God had taken from man, made he a woman, and brought her unto the man.'); +INSERT INTO t1(docid,words) VALUES(1002023,'And Adam said, This is now bone of my bones, and flesh of my flesh: she shall be called Woman, because she was taken out of Man.'); +INSERT INTO t1(docid,words) VALUES(1002024,'Therefore shall a man leave his father and his mother, and shall cleave unto his wife: and they shall be one flesh.'); +INSERT INTO t1(docid,words) VALUES(1002025,'And they were both naked, the man and his wife, and were not ashamed.'); +INSERT INTO t1(docid,words) VALUES(1003001,'Now the serpent was more subtil than any beast of the field which the LORD God had made. And he said unto the woman, Yea, hath God said, Ye shall not eat of every tree of the garden?'); +INSERT INTO t1(docid,words) VALUES(1003002,'And the woman said unto the serpent, We may eat of the fruit of the trees of the garden:'); +INSERT INTO t1(docid,words) VALUES(1003003,'But of the fruit of the tree which is in the midst of the garden, God hath said, Ye shall not eat of it, neither shall ye touch it, lest ye die.'); +INSERT INTO t1(docid,words) VALUES(1003004,'And the serpent said unto the woman, Ye shall not surely die:'); +INSERT INTO t1(docid,words) VALUES(1003005,'For God doth know that in the day ye eat thereof, then your eyes shall be opened, and ye shall be as gods, knowing good and evil.'); +INSERT INTO t1(docid,words) VALUES(1003006,'And when the woman saw that the tree was good for food, and that it was pleasant to the eyes, and a tree to be desired to make one wise, she took of the fruit thereof, and did eat, and gave also unto her husband with her; and he did eat.'); +INSERT INTO t1(docid,words) VALUES(1003007,'And the eyes of them both were opened, and they knew that they were naked; and they sewed fig leaves together, and made themselves aprons.'); +INSERT INTO t1(docid,words) VALUES(1003008,'And they heard the voice of the LORD God walking in the garden in the cool of the day: and Adam and his wife hid themselves from the presence of the LORD God amongst the trees of the garden.'); +INSERT INTO t1(docid,words) VALUES(1003009,'And the LORD God called unto Adam, and said unto him, Where art thou?'); +INSERT INTO t1(docid,words) VALUES(1003010,'And he said, I heard thy voice in the garden, and I was afraid, because I was naked; and I hid myself.'); +INSERT INTO t1(docid,words) VALUES(1003011,'And he said, Who told thee that thou wast naked? Hast thou eaten of the tree, whereof I commanded thee that thou shouldest not eat?'); +INSERT INTO t1(docid,words) VALUES(1003012,'And the man said, The woman whom thou gavest to be with me, she gave me of the tree, and I did eat.'); +INSERT INTO t1(docid,words) VALUES(1003013,'And the LORD God said unto the woman, What is this that thou hast done? And the woman said, The serpent beguiled me, and I did eat.'); +INSERT INTO t1(docid,words) VALUES(1003014,'And the LORD God said unto the serpent, Because thou hast done this, thou art cursed above all cattle, and above every beast of the field; upon thy belly shalt thou go, and dust shalt thou eat all the days of thy life:'); +INSERT INTO t1(docid,words) VALUES(1003015,'And I will put enmity between thee and the woman, and between thy seed and her seed; it shall bruise thy head, and thou shalt bruise his heel.'); +INSERT INTO t1(docid,words) VALUES(1003016,'Unto the woman he said, I will greatly multiply thy sorrow and thy conception; in sorrow thou shalt bring forth children; and thy desire shall be to thy husband, and he shall rule over thee.'); +INSERT INTO t1(docid,words) VALUES(1003017,'And unto Adam he said, Because thou hast hearkened unto the voice of thy wife, and hast eaten of the tree, of which I commanded thee, saying, Thou shalt not eat of it: cursed is the ground for thy sake; in sorrow shalt thou eat of it all the days of thy life;'); +INSERT INTO t1(docid,words) VALUES(1003018,'Thorns also and thistles shall it bring forth to thee; and thou shalt eat the herb of the field;'); +INSERT INTO t1(docid,words) VALUES(1003019,'In the sweat of thy face shalt thou eat bread, till thou return unto the ground; for out of it wast thou taken: for dust thou art, and unto dust shalt thou return.'); +INSERT INTO t1(docid,words) VALUES(1003020,'And Adam called his wife''s name Eve; because she was the mother of all living.'); +INSERT INTO t1(docid,words) VALUES(1003021,'Unto Adam also and to his wife did the LORD God make coats of skins, and clothed them.'); +INSERT INTO t1(docid,words) VALUES(1003022,'And the LORD God said, Behold, the man is become as one of us, to know good and evil: and now, lest he put forth his hand, and take also of the tree of life, and eat, and live for ever:'); +INSERT INTO t1(docid,words) VALUES(1003023,'Therefore the LORD God sent him forth from the garden of Eden, to till the ground from whence he was taken.'); +INSERT INTO t1(docid,words) VALUES(1003024,'So he drove out the man; and he placed at the east of the garden of Eden Cherubims, and a flaming sword which turned every way, to keep the way of the tree of life.'); +INSERT INTO t1(docid,words) VALUES(1004001,'And Adam knew Eve his wife; and she conceived, and bare Cain, and said, I have gotten a man from the LORD.'); +INSERT INTO t1(docid,words) VALUES(1004002,'And she again bare his brother Abel. And Abel was a keeper of sheep, but Cain was a tiller of the ground.'); +INSERT INTO t1(docid,words) VALUES(1004003,'And in process of time it came to pass, that Cain brought of the fruit of the ground an offering unto the LORD.'); +INSERT INTO t1(docid,words) VALUES(1004004,'And Abel, he also brought of the firstlings of his flock and of the fat thereof. And the LORD had respect unto Abel and to his offering:'); +INSERT INTO t1(docid,words) VALUES(1004005,'But unto Cain and to his offering he had not respect. And Cain was very wroth, and his countenance fell.'); +INSERT INTO t1(docid,words) VALUES(1004006,'And the LORD said unto Cain, Why art thou wroth? and why is thy countenance fallen?'); +INSERT INTO t1(docid,words) VALUES(1004007,'If thou doest well, shalt thou not be accepted? and if thou doest not well, sin lieth at the door. And unto thee shall be his desire, and thou shalt rule over him.'); +INSERT INTO t1(docid,words) VALUES(1004008,'And Cain talked with Abel his brother: and it came to pass, when they were in the field, that Cain rose up against Abel his brother, and slew him.'); +INSERT INTO t1(docid,words) VALUES(1004009,'And the LORD said unto Cain, Where is Abel thy brother? And he said, I know not: Am I my brother''s keeper?'); +INSERT INTO t1(docid,words) VALUES(1004010,'And he said, What hast thou done? the voice of thy brother''s blood crieth unto me from the ground.'); +INSERT INTO t1(docid,words) VALUES(1004011,'And now art thou cursed from the earth, which hath opened her mouth to receive thy brother''s blood from thy hand;'); +INSERT INTO t1(docid,words) VALUES(1004012,'When thou tillest the ground, it shall not henceforth yield unto thee her strength; a fugitive and a vagabond shalt thou be in the earth.'); +INSERT INTO t1(docid,words) VALUES(1004013,'And Cain said unto the LORD, My punishment is greater than I can bear.'); +INSERT INTO t1(docid,words) VALUES(1004014,'Behold, thou hast driven me out this day from the face of the earth; and from thy face shall I be hid; and I shall be a fugitive and a vagabond in the earth; and it shall come to pass, that every one that findeth me shall slay me.'); +INSERT INTO t1(docid,words) VALUES(1004015,'And the LORD said unto him, Therefore whosoever slayeth Cain, vengeance shall be taken on him sevenfold. And the LORD set a mark upon Cain, lest any finding him should kill him.'); +INSERT INTO t1(docid,words) VALUES(1004016,'And Cain went out from the presence of the LORD, and dwelt in the land of Nod, on the east of Eden.'); +INSERT INTO t1(docid,words) VALUES(1004017,'And Cain knew his wife; and she conceived, and bare Enoch: and he builded a city, and called the name of the city, after the name of his son, Enoch.'); +INSERT INTO t1(docid,words) VALUES(1004018,'And unto Enoch was born Irad: and Irad begat Mehujael: and Mehujael begat Methusael: and Methusael begat Lamech.'); +INSERT INTO t1(docid,words) VALUES(1004019,'And Lamech took unto him two wives: the name of the one was Adah, and the name of the other Zillah.'); +INSERT INTO t1(docid,words) VALUES(1004020,'And Adah bare Jabal: he was the father of such as dwell in tents, and of such as have cattle.'); +INSERT INTO t1(docid,words) VALUES(1004021,'And his brother''s name was Jubal: he was the father of all such as handle the harp and organ.'); +INSERT INTO t1(docid,words) VALUES(1004022,'And Zillah, she also bare Tubalcain, an instructer of every artificer in brass and iron: and the sister of Tubalcain was Naamah.'); +INSERT INTO t1(docid,words) VALUES(1004023,'And Lamech said unto his wives, Adah and Zillah, Hear my voice; ye wives of Lamech, hearken unto my speech: for I have slain a man to my wounding, and a young man to my hurt.'); +INSERT INTO t1(docid,words) VALUES(1004024,'If Cain shall be avenged sevenfold, truly Lamech seventy and sevenfold.'); +INSERT INTO t1(docid,words) VALUES(1004025,'And Adam knew his wife again; and she bare a son, and called his name Seth: For God, said she, hath appointed me another seed instead of Abel, whom Cain slew.'); +INSERT INTO t1(docid,words) VALUES(1004026,'And to Seth, to him also there was born a son; and he called his name Enos: then began men to call upon the name of the LORD.'); +INSERT INTO t1(docid,words) VALUES(1005001,'This is the book of the generations of Adam. In the day that God created man, in the likeness of God made he him;'); +INSERT INTO t1(docid,words) VALUES(1005002,'Male and female created he them; and blessed them, and called their name Adam, in the day when they were created.'); +INSERT INTO t1(docid,words) VALUES(1005003,'And Adam lived an hundred and thirty years, and begat a son in his own likeness, and after his image; and called his name Seth:'); +INSERT INTO t1(docid,words) VALUES(1005004,'And the days of Adam after he had begotten Seth were eight hundred years: and he begat sons and daughters:'); +INSERT INTO t1(docid,words) VALUES(1005005,'And all the days that Adam lived were nine hundred and thirty years: and he died.'); +INSERT INTO t1(docid,words) VALUES(1005006,'And Seth lived an hundred and five years, and begat Enos:'); +INSERT INTO t1(docid,words) VALUES(1005007,'And Seth lived after he begat Enos eight hundred and seven years, and begat sons and daughters:'); +INSERT INTO t1(docid,words) VALUES(1005008,'And all the days of Seth were nine hundred and twelve years: and he died.'); +INSERT INTO t1(docid,words) VALUES(1005009,'And Enos lived ninety years, and begat Cainan:'); +INSERT INTO t1(docid,words) VALUES(1005010,'And Enos lived after he begat Cainan eight hundred and fifteen years, and begat sons and daughters:'); +INSERT INTO t1(docid,words) VALUES(1005011,'And all the days of Enos were nine hundred and five years: and he died.'); +INSERT INTO t1(docid,words) VALUES(1005012,'And Cainan lived seventy years and begat Mahalaleel:'); +INSERT INTO t1(docid,words) VALUES(1005013,'And Cainan lived after he begat Mahalaleel eight hundred and forty years, and begat sons and daughters:'); +INSERT INTO t1(docid,words) VALUES(1005014,'And all the days of Cainan were nine hundred and ten years: and he died.'); +INSERT INTO t1(docid,words) VALUES(1005015,'And Mahalaleel lived sixty and five years, and begat Jared:'); +INSERT INTO t1(docid,words) VALUES(1005016,'And Mahalaleel lived after he begat Jared eight hundred and thirty years, and begat sons and daughters:'); +INSERT INTO t1(docid,words) VALUES(1005017,'And all the days of Mahalaleel were eight hundred ninety and five years: and he died.'); +INSERT INTO t1(docid,words) VALUES(1005018,'And Jared lived an hundred sixty and two years, and he begat Enoch:'); +INSERT INTO t1(docid,words) VALUES(1005019,'And Jared lived after he begat Enoch eight hundred years, and begat sons and daughters:'); +INSERT INTO t1(docid,words) VALUES(1005020,'And all the days of Jared were nine hundred sixty and two years: and he died.'); +INSERT INTO t1(docid,words) VALUES(1005021,'And Enoch lived sixty and five years, and begat Methuselah:'); +INSERT INTO t1(docid,words) VALUES(1005022,'And Enoch walked with God after he begat Methuselah three hundred years, and begat sons and daughters:'); +INSERT INTO t1(docid,words) VALUES(1005023,'And all the days of Enoch were three hundred sixty and five years:'); +INSERT INTO t1(docid,words) VALUES(1005024,'And Enoch walked with God: and he was not; for God took him.'); +INSERT INTO t1(docid,words) VALUES(1005025,'And Methuselah lived an hundred eighty and seven years, and begat Lamech.'); +INSERT INTO t1(docid,words) VALUES(1005026,'And Methuselah lived after he begat Lamech seven hundred eighty and two years, and begat sons and daughters:'); +INSERT INTO t1(docid,words) VALUES(1005027,'And all the days of Methuselah were nine hundred sixty and nine years: and he died.'); +INSERT INTO t1(docid,words) VALUES(1005028,'And Lamech lived an hundred eighty and two years, and begat a son:'); +INSERT INTO t1(docid,words) VALUES(1005029,'And he called his name Noah, saying, This same shall comfort us concerning our work and toil of our hands, because of the ground which the LORD hath cursed.'); +INSERT INTO t1(docid,words) VALUES(1005030,'And Lamech lived after he begat Noah five hundred ninety and five years, and begat sons and daughters:'); +INSERT INTO t1(docid,words) VALUES(1005031,'And all the days of Lamech were seven hundred seventy and seven years: and he died.'); +INSERT INTO t1(docid,words) VALUES(1005032,'And Noah was five hundred years old: and Noah begat Shem, Ham, and Japheth.'); +INSERT INTO t1(docid,words) VALUES(1006001,'And it came to pass, when men began to multiply on the face of the earth, and daughters were born unto them,'); +INSERT INTO t1(docid,words) VALUES(1006002,'That the sons of God saw the daughters of men that they were fair; and they took them wives of all which they chose.'); +INSERT INTO t1(docid,words) VALUES(1006003,'And the LORD said, My spirit shall not always strive with man, for that he also is flesh: yet his days shall be an hundred and twenty years.'); +INSERT INTO t1(docid,words) VALUES(1006004,'There were giants in the earth in those days; and also after that, when the sons of God came in unto the daughters of men, and they bare children to them, the same became mighty men which were of old, men of renown.'); +INSERT INTO t1(docid,words) VALUES(1006005,'And God saw that the wickedness of man was great in the earth, and that every imagination of the thoughts of his heart was only evil continually.'); +INSERT INTO t1(docid,words) VALUES(1006006,'And it repented the LORD that he had made man on the earth, and it grieved him at his heart.'); +INSERT INTO t1(docid,words) VALUES(1006007,'And the LORD said, I will destroy man whom I have created from the face of the earth; both man, and beast, and the creeping thing, and the fowls of the air; for it repenteth me that I have made them.'); +INSERT INTO t1(docid,words) VALUES(1006008,'But Noah found grace in the eyes of the LORD.'); +INSERT INTO t1(docid,words) VALUES(1006009,'These are the generations of Noah: Noah was a just man and perfect in his generations, and Noah walked with God.'); +INSERT INTO t1(docid,words) VALUES(1006010,'And Noah begat three sons, Shem, Ham, and Japheth.'); +INSERT INTO t1(docid,words) VALUES(1006011,'The earth also was corrupt before God, and the earth was filled with violence.'); +INSERT INTO t1(docid,words) VALUES(1006012,'And God looked upon the earth, and, behold, it was corrupt; for all flesh had corrupted his way upon the earth.'); +INSERT INTO t1(docid,words) VALUES(1006013,'And God said unto Noah, The end of all flesh is come before me; for the earth is filled with violence through them; and, behold, I will destroy them with the earth.'); +INSERT INTO t1(docid,words) VALUES(1006014,'Make thee an ark of gopher wood; rooms shalt thou make in the ark, and shalt pitch it within and without with pitch.'); +INSERT INTO t1(docid,words) VALUES(1006015,'And this is the fashion which thou shalt make it of: The length of the ark shall be three hundred cubits, the breadth of it fifty cubits, and the height of it thirty cubits.'); +INSERT INTO t1(docid,words) VALUES(1006016,'A window shalt thou make to the ark, and in a cubit shalt thou finish it above; and the door of the ark shalt thou set in the side thereof; with lower, second, and third stories shalt thou make it.'); +INSERT INTO t1(docid,words) VALUES(1006017,'And, behold, I, even I, do bring a flood of waters upon the earth, to destroy all flesh, wherein is the breath of life, from under heaven; and every thing that is in the earth shall die.'); +INSERT INTO t1(docid,words) VALUES(1006018,'But with thee will I establish my covenant; and thou shalt come into the ark, thou, and thy sons, and thy wife, and thy sons'' wives with thee.'); +INSERT INTO t1(docid,words) VALUES(1006019,'And of every living thing of all flesh, two of every sort shalt thou bring into the ark, to keep them alive with thee; they shall be male and female.'); +INSERT INTO t1(docid,words) VALUES(1006020,'Of fowls after their kind, and of cattle after their kind, of every creeping thing of the earth after his kind, two of every sort shall come unto thee, to keep them alive.'); +INSERT INTO t1(docid,words) VALUES(1006021,'And take thou unto thee of all food that is eaten, and thou shalt gather it to thee; and it shall be for food for thee, and for them.'); +INSERT INTO t1(docid,words) VALUES(1006022,'Thus did Noah; according to all that God commanded him, so did he.'); +INSERT INTO t1(docid,words) VALUES(1007001,'And the LORD said unto Noah, Come thou and all thy house into the ark; for thee have I seen righteous before me in this generation.'); +INSERT INTO t1(docid,words) VALUES(1007002,'Of every clean beast thou shalt take to thee by sevens, the male and his female: and of beasts that are not clean by two, the male and his female.'); +INSERT INTO t1(docid,words) VALUES(1007003,'Of fowls also of the air by sevens, the male and the female; to keep seed alive upon the face of all the earth.'); +INSERT INTO t1(docid,words) VALUES(1007004,'For yet seven days, and I will cause it to rain upon the earth forty days and forty nights; and every living substance that I have made will I destroy from off the face of the earth.'); +INSERT INTO t1(docid,words) VALUES(1007005,'And Noah did according unto all that the LORD commanded him.'); +INSERT INTO t1(docid,words) VALUES(1007006,'And Noah was six hundred years old when the flood of waters was upon the earth.'); +INSERT INTO t1(docid,words) VALUES(1007007,'And Noah went in, and his sons, and his wife, and his sons'' wives with him, into the ark, because of the waters of the flood.'); +INSERT INTO t1(docid,words) VALUES(1007008,'Of clean beasts, and of beasts that are not clean, and of fowls, and of every thing that creepeth upon the earth,'); +INSERT INTO t1(docid,words) VALUES(1007009,'There went in two and two unto Noah into the ark, the male and the female, as God had commanded Noah.'); +INSERT INTO t1(docid,words) VALUES(1007010,'And it came to pass after seven days, that the waters of the flood were upon the earth.'); +INSERT INTO t1(docid,words) VALUES(1007011,'In the six hundredth year of Noah''s life, in the second month, the seventeenth day of the month, the same day were all the fountains of the great deep broken up, and the windows of heaven were opened.'); +INSERT INTO t1(docid,words) VALUES(1007012,'And the rain was upon the earth forty days and forty nights.'); +INSERT INTO t1(docid,words) VALUES(1007013,'In the selfsame day entered Noah, and Shem, and Ham, and Japheth, the sons of Noah, and Noah''s wife, and the three wives of his sons with them, into the ark;'); +INSERT INTO t1(docid,words) VALUES(1007014,'They, and every beast after his kind, and all the cattle after their kind, and every creeping thing that creepeth upon the earth after his kind, and every fowl after his kind, every bird of every sort.'); +INSERT INTO t1(docid,words) VALUES(1007015,'And they went in unto Noah into the ark, two and two of all flesh, wherein is the breath of life.'); +INSERT INTO t1(docid,words) VALUES(1007016,'And they that went in, went in male and female of all flesh, as God had commanded him: and the LORD shut him in.'); +INSERT INTO t1(docid,words) VALUES(1007017,'And the flood was forty days upon the earth; and the waters increased, and bare up the ark, and it was lift up above the earth.'); +INSERT INTO t1(docid,words) VALUES(1007018,'And the waters prevailed, and were increased greatly upon the earth; and the ark went upon the face of the waters.'); +INSERT INTO t1(docid,words) VALUES(1007019,'And the waters prevailed exceedingly upon the earth; and all the high hills, that were under the whole heaven, were covered.'); +INSERT INTO t1(docid,words) VALUES(1007020,'Fifteen cubits upward did the waters prevail; and the mountains were covered.'); +INSERT INTO t1(docid,words) VALUES(1007021,'And all flesh died that moved upon the earth, both of fowl, and of cattle, and of beast, and of every creeping thing that creepeth upon the earth, and every man:'); +INSERT INTO t1(docid,words) VALUES(1007022,'All in whose nostrils was the breath of life, of all that was in the dry land, died.'); +INSERT INTO t1(docid,words) VALUES(1007023,'And every living substance was destroyed which was upon the face of the ground, both man, and cattle, and the creeping things, and the fowl of the heaven; and they were destroyed from the earth: and Noah only remained alive, and they that were with him in the ark.'); +INSERT INTO t1(docid,words) VALUES(1007024,'And the waters prevailed upon the earth an hundred and fifty days.'); +INSERT INTO t1(docid,words) VALUES(1008001,'And God remembered Noah, and every living thing, and all the cattle that was with him in the ark: and God made a wind to pass over the earth, and the waters asswaged;'); +INSERT INTO t1(docid,words) VALUES(1008002,'The fountains also of the deep and the windows of heaven were stopped, and the rain from heaven was restrained;'); +INSERT INTO t1(docid,words) VALUES(1008003,'And the waters returned from off the earth continually: and after the end of the hundred and fifty days the waters were abated.'); +INSERT INTO t1(docid,words) VALUES(1008004,'And the ark rested in the seventh month, on the seventeenth day of the month, upon the mountains of Ararat.'); +INSERT INTO t1(docid,words) VALUES(1008005,'And the waters decreased continually until the tenth month: in the tenth month, on the first day of the month, were the tops of the mountains seen.'); +INSERT INTO t1(docid,words) VALUES(1008006,'And it came to pass at the end of forty days, that Noah opened the window of the ark which he had made:'); +INSERT INTO t1(docid,words) VALUES(1008007,'And he sent forth a raven, which went forth to and fro, until the waters were dried up from off the earth.'); +INSERT INTO t1(docid,words) VALUES(1008008,'Also he sent forth a dove from him, to see if the waters were abated from off the face of the ground;'); +INSERT INTO t1(docid,words) VALUES(1008009,'But the dove found no rest for the sole of her foot, and she returned unto him into the ark, for the waters were on the face of the whole earth: then he put forth his hand, and took her, and pulled her in unto him into the ark.'); +INSERT INTO t1(docid,words) VALUES(1008010,'And he stayed yet other seven days; and again he sent forth the dove out of the ark;'); +INSERT INTO t1(docid,words) VALUES(1008011,'And the dove came in to him in the evening; and, lo, in her mouth was an olive leaf pluckt off: so Noah knew that the waters were abated from off the earth.'); +INSERT INTO t1(docid,words) VALUES(1008012,'And he stayed yet other seven days; and sent forth the dove; which returned not again unto him any more.'); +INSERT INTO t1(docid,words) VALUES(1008013,'And it came to pass in the six hundredth and first year, in the first month, the first day of the month, the waters were dried up from off the earth: and Noah removed the covering of the ark, and looked, and, behold, the face of the ground was dry.'); +INSERT INTO t1(docid,words) VALUES(1008014,'And in the second month, on the seven and twentieth day of the month, was the earth dried.'); +INSERT INTO t1(docid,words) VALUES(1008015,'And God spake unto Noah, saying,'); +INSERT INTO t1(docid,words) VALUES(1008016,'Go forth of the ark, thou, and thy wife, and thy sons, and thy sons'' wives with thee.'); +INSERT INTO t1(docid,words) VALUES(1008017,'Bring forth with thee every living thing that is with thee, of all flesh, both of fowl, and of cattle, and of every creeping thing that creepeth upon the earth; that they may breed abundantly in the earth, and be fruitful, and multiply upon the earth.'); +INSERT INTO t1(docid,words) VALUES(1008018,'And Noah went forth, and his sons, and his wife, and his sons'' wives with him:'); +INSERT INTO t1(docid,words) VALUES(1008019,'Every beast, every creeping thing, and every fowl, and whatsoever creepeth upon the earth, after their kinds, went forth out of the ark.'); +INSERT INTO t1(docid,words) VALUES(1008020,'And Noah builded an altar unto the LORD; and took of every clean beast, and of every clean fowl, and offered burnt offerings on the altar.'); +INSERT INTO t1(docid,words) VALUES(1008021,'And the LORD smelled a sweet savour; and the LORD said in his heart, I will not again curse the ground any more for man''s sake; for the imagination of man''s heart is evil from his youth; neither will I again smite any more every thing living, as I have done.'); +INSERT INTO t1(docid,words) VALUES(1008022,'While the earth remaineth, seedtime and harvest, and cold and heat, and summer and winter, and day and night shall not cease.'); +INSERT INTO t1(docid,words) VALUES(1009001,'And God blessed Noah and his sons, and said unto them, Be fruitful, and multiply, and replenish the earth.'); +INSERT INTO t1(docid,words) VALUES(1009002,'And the fear of you and the dread of you shall be upon every beast of the earth, and upon every fowl of the air, upon all that moveth upon the earth, and upon all the fishes of the sea; into your hand are they delivered.'); +INSERT INTO t1(docid,words) VALUES(1009003,'Every moving thing that liveth shall be meat for you; even as the green herb have I given you all things.'); +INSERT INTO t1(docid,words) VALUES(1009004,'But flesh with the life thereof, which is the blood thereof, shall ye not eat.'); +INSERT INTO t1(docid,words) VALUES(1009005,'And surely your blood of your lives will I require; at the hand of every beast will I require it, and at the hand of man; at the hand of every man''s brother will I require the life of man.'); +INSERT INTO t1(docid,words) VALUES(1009006,'Whoso sheddeth man''s blood, by man shall his blood be shed: for in the image of God made he man.'); +INSERT INTO t1(docid,words) VALUES(1009007,'And you, be ye fruitful, and multiply; bring forth abundantly in the earth, and multiply therein.'); +INSERT INTO t1(docid,words) VALUES(1009008,'And God spake unto Noah, and to his sons with him, saying,'); +INSERT INTO t1(docid,words) VALUES(1009009,'And I, behold, I establish my covenant with you, and with your seed after you;'); +INSERT INTO t1(docid,words) VALUES(1009010,'And with every living creature that is with you, of the fowl, of the cattle, and of every beast of the earth with you; from all that go out of the ark, to every beast of the earth.'); +INSERT INTO t1(docid,words) VALUES(1009011,'And I will establish my covenant with you, neither shall all flesh be cut off any more by the waters of a flood; neither shall there any more be a flood to destroy the earth.'); +INSERT INTO t1(docid,words) VALUES(1009012,'And God said, This is the token of the covenant which I make between me and you and every living creature that is with you, for perpetual generations:'); +INSERT INTO t1(docid,words) VALUES(1009013,'I do set my bow in the cloud, and it shall be for a token of a covenant between me and the earth.'); +INSERT INTO t1(docid,words) VALUES(1009014,'And it shall come to pass, when I bring a cloud over the earth, that the bow shall be seen in the cloud:'); +INSERT INTO t1(docid,words) VALUES(1009015,'And I will remember my covenant, which is between me and you and every living creature of all flesh; and the waters shall no more become a flood to destroy all flesh.'); +INSERT INTO t1(docid,words) VALUES(1009016,'And the bow shall be in the cloud; and I will look upon it, that I may remember the everlasting covenant between God and every living creature of all flesh that is upon the earth.'); +INSERT INTO t1(docid,words) VALUES(1009017,'And God said unto Noah, This is the token of the covenant, which I have established between me and all flesh that is upon the earth.'); +INSERT INTO t1(docid,words) VALUES(1009018,'And the sons of Noah, that went forth of the ark, were Shem, and Ham, and Japheth: and Ham is the father of Canaan.'); +INSERT INTO t1(docid,words) VALUES(1009019,'These are the three sons of Noah: and of them was the whole earth overspread.'); +INSERT INTO t1(docid,words) VALUES(1009020,'And Noah began to be an husbandman, and he planted a vineyard:'); +INSERT INTO t1(docid,words) VALUES(1009021,'And he drank of the wine, and was drunken; and he was uncovered within his tent.'); +INSERT INTO t1(docid,words) VALUES(1009022,'And Ham, the father of Canaan, saw the nakedness of his father, and told his two brethren without.'); +INSERT INTO t1(docid,words) VALUES(1009023,'And Shem and Japheth took a garment, and laid it upon both their shoulders, and went backward, and covered the nakedness of their father; and their faces were backward, and they saw not their father''s nakedness.'); +INSERT INTO t1(docid,words) VALUES(1009024,'And Noah awoke from his wine, and knew what his younger son had done unto him.'); +INSERT INTO t1(docid,words) VALUES(1009025,'And he said, Cursed be Canaan; a servant of servants shall he be unto his brethren.'); +INSERT INTO t1(docid,words) VALUES(1009026,'And he said, Blessed be the LORD God of Shem; and Canaan shall be his servant.'); +INSERT INTO t1(docid,words) VALUES(1009027,'God shall enlarge Japheth, and he shall dwell in the tents of Shem; and Canaan shall be his servant.'); +INSERT INTO t1(docid,words) VALUES(1009028,'And Noah lived after the flood three hundred and fifty years.'); +INSERT INTO t1(docid,words) VALUES(1009029,'And all the days of Noah were nine hundred and fifty years: and he died.'); +INSERT INTO t1(docid,words) VALUES(1010001,'Now these are the generations of the sons of Noah, Shem, Ham, and Japheth: and unto them were sons born after the flood.'); +INSERT INTO t1(docid,words) VALUES(1010002,'The sons of Japheth; Gomer, and Magog, and Madai, and Javan, and Tubal, and Meshech, and Tiras.'); +INSERT INTO t1(docid,words) VALUES(1010003,'And the sons of Gomer; Ashkenaz, and Riphath, and Togarmah.'); +INSERT INTO t1(docid,words) VALUES(1010004,'And the sons of Javan; Elishah, and Tarshish, Kittim, and Dodanim.'); +INSERT INTO t1(docid,words) VALUES(1010005,'By these were the isles of the Gentiles divided in their lands; every one after his tongue, after their families, in their nations.'); +INSERT INTO t1(docid,words) VALUES(1010006,'And the sons of Ham; Cush, and Mizraim, and Phut, and Canaan.'); +INSERT INTO t1(docid,words) VALUES(1010007,'And the sons of Cush; Seba, and Havilah, and Sabtah, and Raamah, and Sabtechah: and the sons of Raamah; Sheba, and Dedan.'); +INSERT INTO t1(docid,words) VALUES(1010008,'And Cush begat Nimrod: he began to be a mighty one in the earth.'); +INSERT INTO t1(docid,words) VALUES(1010009,'He was a mighty hunter before the LORD: wherefore it is said, Even as Nimrod the mighty hunter before the LORD.'); +INSERT INTO t1(docid,words) VALUES(1010010,'And the beginning of his kingdom was Babel, and Erech, and Accad, and Calneh, in the land of Shinar.'); +INSERT INTO t1(docid,words) VALUES(1010011,'Out of that land went forth Asshur, and builded Nineveh, and the city Rehoboth, and Calah,'); +INSERT INTO t1(docid,words) VALUES(1010012,'And Resen between Nineveh and Calah: the same is a great city.'); +INSERT INTO t1(docid,words) VALUES(1010013,'And Mizraim begat Ludim, and Anamim, and Lehabim, and Naphtuhim,'); +INSERT INTO t1(docid,words) VALUES(1010014,'And Pathrusim, and Casluhim, (out of whom came Philistim,) and Caphtorim.'); +INSERT INTO t1(docid,words) VALUES(1010015,'And Canaan begat Sidon his first born, and Heth,'); +INSERT INTO t1(docid,words) VALUES(1010016,'And the Jebusite, and the Amorite, and the Girgasite,'); +INSERT INTO t1(docid,words) VALUES(1010017,'And the Hivite, and the Arkite, and the Sinite,'); +INSERT INTO t1(docid,words) VALUES(1010018,'And the Arvadite, and the Zemarite, and the Hamathite: and afterward were the families of the Canaanites spread abroad.'); +INSERT INTO t1(docid,words) VALUES(1010019,'And the border of the Canaanites was from Sidon, as thou comest to Gerar, unto Gaza; as thou goest, unto Sodom, and Gomorrah, and Admah, and Zeboim, even unto Lasha.'); +INSERT INTO t1(docid,words) VALUES(1010020,'These are the sons of Ham, after their families, after their tongues, in their countries, and in their nations.'); +INSERT INTO t1(docid,words) VALUES(1010021,'Unto Shem also, the father of all the children of Eber, the brother of Japheth the elder, even to him were children born.'); +INSERT INTO t1(docid,words) VALUES(1010022,'The children of Shem; Elam, and Asshur, and Arphaxad, and Lud, and Aram.'); +INSERT INTO t1(docid,words) VALUES(1010023,'And the children of Aram; Uz, and Hul, and Gether, and Mash.'); +INSERT INTO t1(docid,words) VALUES(1010024,'And Arphaxad begat Salah; and Salah begat Eber.'); +INSERT INTO t1(docid,words) VALUES(1010025,'And unto Eber were born two sons: the name of one was Peleg; for in his days was the earth divided; and his brother''s name was Joktan.'); +INSERT INTO t1(docid,words) VALUES(1010026,'And Joktan begat Almodad, and Sheleph, and Hazarmaveth, and Jerah,'); +INSERT INTO t1(docid,words) VALUES(1010027,'And Hadoram, and Uzal, and Diklah,'); +INSERT INTO t1(docid,words) VALUES(1010028,'And Obal, and Abimael, and Sheba,'); +INSERT INTO t1(docid,words) VALUES(1010029,'And Ophir, and Havilah, and Jobab: all these were the sons of Joktan.'); +INSERT INTO t1(docid,words) VALUES(1010030,'And their dwelling was from Mesha, as thou goest unto Sephar a mount of the east.'); +INSERT INTO t1(docid,words) VALUES(1010031,'These are the sons of Shem, after their families, after their tongues, in their lands, after their nations.'); +INSERT INTO t1(docid,words) VALUES(1010032,'These are the families of the sons of Noah, after their generations, in their nations: and by these were the nations divided in the earth after the flood.'); +INSERT INTO t1(docid,words) VALUES(1011001,'And the whole earth was of one language, and of one speech.'); +INSERT INTO t1(docid,words) VALUES(1011002,'And it came to pass, as they journeyed from the east, that they found a plain in the land of Shinar; and they dwelt there.'); +INSERT INTO t1(docid,words) VALUES(1011003,'And they said one to another, Go to, let us make brick, and burn them thoroughly. And they had brick for stone, and slime had they for morter.'); +INSERT INTO t1(docid,words) VALUES(1011004,'And they said, Go to, let us build us a city and a tower, whose top may reach unto heaven; and let us make us a name, lest we be scattered abroad upon the face of the whole earth.'); +INSERT INTO t1(docid,words) VALUES(1011005,'And the LORD came down to see the city and the tower, which the children of men builded.'); +INSERT INTO t1(docid,words) VALUES(1011006,'And the LORD said, Behold, the people is one, and they have all one language; and this they begin to do: and now nothing will be restrained from them, which they have imagined to do.'); +INSERT INTO t1(docid,words) VALUES(1011007,'Go to, let us go down, and there confound their language, that they may not understand one another''s speech.'); +INSERT INTO t1(docid,words) VALUES(1011008,'So the LORD scattered them abroad from thence upon the face of all the earth: and they left off to build the city.'); +INSERT INTO t1(docid,words) VALUES(1011009,'Therefore is the name of it called Babel; because the LORD did there confound the language of all the earth: and from thence did the LORD scatter them abroad upon the face of all the earth.'); +INSERT INTO t1(docid,words) VALUES(1011010,'These are the generations of Shem: Shem was an hundred years old, and begat Arphaxad two years after the flood:'); +INSERT INTO t1(docid,words) VALUES(1011011,'And Shem lived after he begat Arphaxad five hundred years, and begat sons and daughters.'); +INSERT INTO t1(docid,words) VALUES(1011012,'And Arphaxad lived five and thirty years, and begat Salah:'); +INSERT INTO t1(docid,words) VALUES(1011013,'And Arphaxad lived after he begat Salah four hundred and three years, and begat sons and daughters.'); +INSERT INTO t1(docid,words) VALUES(1011014,'And Salah lived thirty years, and begat Eber:'); +INSERT INTO t1(docid,words) VALUES(1011015,'And Salah lived after he begat Eber four hundred and three years, and begat sons and daughters.'); +INSERT INTO t1(docid,words) VALUES(1011016,'And Eber lived four and thirty years, and begat Peleg:'); +INSERT INTO t1(docid,words) VALUES(1011017,'And Eber lived after he begat Peleg four hundred and thirty years, and begat sons and daughters.'); +INSERT INTO t1(docid,words) VALUES(1011018,'And Peleg lived thirty years, and begat Reu:'); +INSERT INTO t1(docid,words) VALUES(1011019,'And Peleg lived after he begat Reu two hundred and nine years, and begat sons and daughters.'); +INSERT INTO t1(docid,words) VALUES(1011020,'And Reu lived two and thirty years, and begat Serug:'); +INSERT INTO t1(docid,words) VALUES(1011021,'And Reu lived after he begat Serug two hundred and seven years, and begat sons and daughters.'); +INSERT INTO t1(docid,words) VALUES(1011022,'And Serug lived thirty years, and begat Nahor:'); +INSERT INTO t1(docid,words) VALUES(1011023,'And Serug lived after he begat Nahor two hundred years, and begat sons and daughters.'); +INSERT INTO t1(docid,words) VALUES(1011024,'And Nahor lived nine and twenty years, and begat Terah:'); +INSERT INTO t1(docid,words) VALUES(1011025,'And Nahor lived after he begat Terah an hundred and nineteen years, and begat sons and daughters.'); +INSERT INTO t1(docid,words) VALUES(1011026,'And Terah lived seventy years, and begat Abram, Nahor, and Haran.'); +INSERT INTO t1(docid,words) VALUES(1011027,'Now these are the generations of Terah: Terah begat Abram, Nahor, and Haran; and Haran begat Lot.'); +INSERT INTO t1(docid,words) VALUES(1011028,'And Haran died before his father Terah in the land of his nativity, in Ur of the Chaldees.'); +INSERT INTO t1(docid,words) VALUES(1011029,'And Abram and Nahor took them wives: the name of Abram''s wife was Sarai; and the name of Nahor''s wife, Milcah, the daughter of Haran, the father of Milcah, and the father of Iscah.'); +INSERT INTO t1(docid,words) VALUES(1011030,'But Sarai was barren; she had no child.'); +INSERT INTO t1(docid,words) VALUES(1011031,'And Terah took Abram his son, and Lot the son of Haran his son''s son, and Sarai his daughter in law, his son Abram''s wife; and they went forth with them from Ur of the Chaldees, to go into the land of Canaan; and they came unto Haran, and dwelt there.'); +INSERT INTO t1(docid,words) VALUES(1011032,'And the days of Terah were two hundred and five years: and Terah died in Haran.'); +INSERT INTO t1(docid,words) VALUES(1012001,'Now the LORD had said unto Abram, Get thee out of thy country, and from thy kindred, and from thy father''s house, unto a land that I will shew thee:'); +INSERT INTO t1(docid,words) VALUES(1012002,'And I will make of thee a great nation, and I will bless thee, and make thy name great; and thou shalt be a blessing:'); +INSERT INTO t1(docid,words) VALUES(1012003,'And I will bless them that bless thee, and curse him that curseth thee: and in thee shall all families of the earth be blessed.'); +INSERT INTO t1(docid,words) VALUES(1012004,'So Abram departed, as the LORD had spoken unto him; and Lot went with him: and Abram was seventy and five years old when he departed out of Haran.'); +INSERT INTO t1(docid,words) VALUES(1012005,'And Abram took Sarai his wife, and Lot his brother''s son, and all their substance that they had gathered, and the souls that they had gotten in Haran; and they went forth to go into the land of Canaan; and into the land of Canaan they came.'); +INSERT INTO t1(docid,words) VALUES(1012006,'And Abram passed through the land unto the place of Sichem, unto the plain of Moreh. And the Canaanite was then in the land.'); +INSERT INTO t1(docid,words) VALUES(1012007,'And the LORD appeared unto Abram, and said, Unto thy seed will I give this land: and there builded he an altar unto the LORD, who appeared unto him.'); +INSERT INTO t1(docid,words) VALUES(1012008,'And he removed from thence unto a mountain on the east of Bethel, and pitched his tent, having Bethel on the west, and Hai on the east: and there he builded an altar unto the LORD, and called upon the name of the LORD.'); +INSERT INTO t1(docid,words) VALUES(1012009,'And Abram journeyed, going on still toward the south.'); +INSERT INTO t1(docid,words) VALUES(1012010,'And there was a famine in the land: and Abram went down into Egypt to sojourn there; for the famine was grievous in the land.'); +INSERT INTO t1(docid,words) VALUES(1012011,'And it came to pass, when he was come near to enter into Egypt, that he said unto Sarai his wife, Behold now, I know that thou art a fair woman to look upon:'); +INSERT INTO t1(docid,words) VALUES(1012012,'Therefore it shall come to pass, when the Egyptians shall see thee, that they shall say, This is his wife: and they will kill me, but they will save thee alive.'); +INSERT INTO t1(docid,words) VALUES(1012013,'Say, I pray thee, thou art my sister: that it may be well with me for thy sake; and my soul shall live because of thee.'); +INSERT INTO t1(docid,words) VALUES(1012014,'And it came to pass, that, when Abram was come into Egypt, the Egyptians beheld the woman that she was very fair.'); +INSERT INTO t1(docid,words) VALUES(1012015,'The princes also of Pharaoh saw her, and commended her before Pharaoh: and the woman was taken into Pharaoh''s house.'); +INSERT INTO t1(docid,words) VALUES(1012016,'And he entreated Abram well for her sake: and he had sheep, and oxen, and he asses, and menservants, and maidservants, and she asses, and camels.'); +INSERT INTO t1(docid,words) VALUES(1012017,'And the LORD plagued Pharaoh and his house with great plagues because of Sarai Abram''s wife.'); +INSERT INTO t1(docid,words) VALUES(1012018,'And Pharaoh called Abram and said, What is this that thou hast done unto me? why didst thou not tell me that she was thy wife?'); +INSERT INTO t1(docid,words) VALUES(1012019,'Why saidst thou, She is my sister? so I might have taken her to me to wife: now therefore behold thy wife, take her, and go thy way.'); +INSERT INTO t1(docid,words) VALUES(1012020,'And Pharaoh commanded his men concerning him: and they sent him away, and his wife, and all that he had.'); +INSERT INTO t1(docid,words) VALUES(1013001,'And Abram went up out of Egypt, he, and his wife, and all that he had, and Lot with him, into the south.'); +INSERT INTO t1(docid,words) VALUES(1013002,'And Abram was very rich in cattle, in silver, and in gold.'); +INSERT INTO t1(docid,words) VALUES(1013003,'And he went on his journeys from the south even to Bethel, unto the place where his tent had been at the beginning, between Bethel and Hai;'); +INSERT INTO t1(docid,words) VALUES(1013004,'Unto the place of the altar, which he had make there at the first: and there Abram called on the name of the LORD.'); +INSERT INTO t1(docid,words) VALUES(1013005,'And Lot also, which went with Abram, had flocks, and herds, and tents.'); +INSERT INTO t1(docid,words) VALUES(1013006,'And the land was not able to bear them, that they might dwell together: for their substance was great, so that they could not dwell together.'); +INSERT INTO t1(docid,words) VALUES(1013007,'And there was a strife between the herdmen of Abram''s cattle and the herdmen of Lot''s cattle: and the Canaanite and the Perizzite dwelled then in the land.'); +INSERT INTO t1(docid,words) VALUES(1013008,'And Abram said unto Lot, Let there be no strife, I pray thee, between me and thee, and between my herdmen and thy herdmen; for we be brethren.'); +INSERT INTO t1(docid,words) VALUES(1013009,'Is not the whole land before thee? separate thyself, I pray thee, from me: if thou wilt take the left hand, then I will go to the right; or if thou depart to the right hand, then I will go to the left.'); +INSERT INTO t1(docid,words) VALUES(1013010,'And Lot lifted up his eyes, and beheld all the plain of Jordan, that it was well watered every where, before the LORD destroyed Sodom and Gomorrah, even as the garden of the LORD, like the land of Egypt, as thou comest unto Zoar.'); +INSERT INTO t1(docid,words) VALUES(1013011,'Then Lot chose him all the plain of Jordan; and Lot journeyed east: and they separated themselves the one from the other.'); +INSERT INTO t1(docid,words) VALUES(1013012,'Abram dwelled in the land of Canaan, and Lot dwelled in the cities of the plain, and pitched his tent toward Sodom.'); +INSERT INTO t1(docid,words) VALUES(1013013,'But the men of Sodom were wicked and sinners before the LORD exceedingly.'); +INSERT INTO t1(docid,words) VALUES(1013014,'And the LORD said unto Abram, after that Lot was separated from him, Lift up now thine eyes, and look from the place where thou art northward, and southward, and eastward, and westward:'); +INSERT INTO t1(docid,words) VALUES(1013015,'For all the land which thou seest, to thee will I give it, and to thy seed for ever.'); +INSERT INTO t1(docid,words) VALUES(1013016,'And I will make thy seed as the dust of the earth: so that if a man can number the dust of the earth, then shall thy seed also be numbered.'); +INSERT INTO t1(docid,words) VALUES(1013017,'Arise, walk through the land in the length of it and in the breadth of it; for I will give it unto thee.'); +INSERT INTO t1(docid,words) VALUES(1013018,'Then Abram removed his tent, and came and dwelt in the plain of Mamre, which is in Hebron, and built there an altar unto the LORD.'); +INSERT INTO t1(docid,words) VALUES(1014001,'And it came to pass in the days of Amraphel king of Shinar, Arioch king of Ellasar, Chedorlaomer king of Elam, and Tidal king of nations;'); +INSERT INTO t1(docid,words) VALUES(1014002,'That these made war with Bera king of Sodom, and with Birsha king of Gomorrah, Shinab king of Admah, and Shemeber king of Zeboiim, and the king of Bela, which is Zoar.'); +INSERT INTO t1(docid,words) VALUES(1014003,'All these were joined together in the vale of Siddim, which is the salt sea.'); +INSERT INTO t1(docid,words) VALUES(1014004,'Twelve years they served Chedorlaomer, and in the thirteenth year they rebelled.'); +INSERT INTO t1(docid,words) VALUES(1014005,'And in the fourteenth year came Chedorlaomer, and the kings that were with him, and smote the Rephaims in Ashteroth Karnaim, and the Zuzims in Ham, and the Emins in Shaveh Kiriathaim,'); +INSERT INTO t1(docid,words) VALUES(1014006,'And the Horites in their mount Seir, unto Elparan, which is by the wilderness.'); +INSERT INTO t1(docid,words) VALUES(1014007,'And they returned, and came to Enmishpat, which is Kadesh, and smote all the country of the Amalekites, and also the Amorites, that dwelt in Hazezontamar.'); +INSERT INTO t1(docid,words) VALUES(1014008,'And there went out the king of Sodom, and the king of Gomorrah, and the king of Admah, and the king of Zeboiim, and the king of Bela (the same is Zoar;) and they joined battle with them in the vale of Siddim;'); +INSERT INTO t1(docid,words) VALUES(1014009,'With Chedorlaomer the king of Elam, and with Tidal king of nations, and Amraphel king of Shinar, and Arioch king of Ellasar; four kings with five.'); +INSERT INTO t1(docid,words) VALUES(1014010,'And the vale of Siddim was full of slimepits; and the kings of Sodom and Gomorrah fled, and fell there; and they that remained fled to the mountain.'); +INSERT INTO t1(docid,words) VALUES(1014011,'And they took all the goods of Sodom and Gomorrah, and all their victuals, and went their way.'); +INSERT INTO t1(docid,words) VALUES(1014012,'And they took Lot, Abram''s brother''s son, who dwelt in Sodom, and his goods, and departed.'); +INSERT INTO t1(docid,words) VALUES(1014013,'And there came one that had escaped, and told Abram the Hebrew; for he dwelt in the plain of Mamre the Amorite, brother of Eshcol, and brother of Aner: and these were confederate with Abram.'); +INSERT INTO t1(docid,words) VALUES(1014014,'And when Abram heard that his brother was taken captive, he armed his trained servants, born in his own house, three hundred and eighteen, and pursued them unto Dan.'); +INSERT INTO t1(docid,words) VALUES(1014015,'And he divided himself against them, he and his servants, by night, and smote them, and pursued them unto Hobah, which is on the left hand of Damascus.'); +INSERT INTO t1(docid,words) VALUES(1014016,'And he brought back all the goods, and also brought again his brother Lot, and his goods, and the women also, and the people.'); +INSERT INTO t1(docid,words) VALUES(1014017,'And the king of Sodom went out to meet him after his return from the slaughter of Chedorlaomer, and of the kings that were with him, at the valley of Shaveh, which is the king''s dale.'); +INSERT INTO t1(docid,words) VALUES(1014018,'And Melchizedek king of Salem brought forth bread and wine: and he was the priest of the most high God.'); +INSERT INTO t1(docid,words) VALUES(1014019,'And he blessed him, and said, Blessed be Abram of the most high God, possessor of heaven and earth:'); +INSERT INTO t1(docid,words) VALUES(1014020,'And blessed be the most high God, which hath delivered thine enemies into thy hand. And he gave him tithes of all.'); +INSERT INTO t1(docid,words) VALUES(1014021,'And the king of Sodom said unto Abram, Give me the persons, and take the goods to thyself.'); +INSERT INTO t1(docid,words) VALUES(1014022,'And Abram said to the king of Sodom, I have lift up mine hand unto the LORD, the most high God, the possessor of heaven and earth,'); +INSERT INTO t1(docid,words) VALUES(1014023,'That I will not take from a thread even to a shoelatchet, and that I will not take any thing that is thine, lest thou shouldest say, I have made Abram rich:'); +INSERT INTO t1(docid,words) VALUES(1014024,'Save only that which the young men have eaten, and the portion of the men which went with me, Aner, Eshcol, and Mamre; let them take their portion.'); +INSERT INTO t1(docid,words) VALUES(1015001,'After these things the word of the LORD came unto Abram in a vision, saying, Fear not, Abram: I am thy shield, and thy exceeding great reward.'); +INSERT INTO t1(docid,words) VALUES(1015002,'And Abram said, LORD God, what wilt thou give me, seeing I go childless, and the steward of my house is this Eliezer of Damascus?'); +INSERT INTO t1(docid,words) VALUES(1015003,'And Abram said, Behold, to me thou hast given no seed: and, lo, one born in my house is mine heir.'); +INSERT INTO t1(docid,words) VALUES(1015004,'And, behold, the word of the LORD came unto him, saying, This shall not be thine heir; but he that shall come forth out of thine own bowels shall be thine heir.'); +INSERT INTO t1(docid,words) VALUES(1015005,'And he brought him forth abroad, and said, Look now toward heaven, and tell the stars, if thou be able to number them: and he said unto him, So shall thy seed be.'); +INSERT INTO t1(docid,words) VALUES(1015006,'And he believed in the LORD; and he counted it to him for righteousness.'); +INSERT INTO t1(docid,words) VALUES(1015007,'And he said unto him, I am the LORD that brought thee out of Ur of the Chaldees, to give thee this land to inherit it.'); +INSERT INTO t1(docid,words) VALUES(1015008,'And he said, LORD God, whereby shall I know that I shall inherit it?'); +INSERT INTO t1(docid,words) VALUES(1015009,'And he said unto him, Take me an heifer of three years old, and a she goat of three years old, and a ram of three years old, and a turtledove, and a young pigeon.'); +INSERT INTO t1(docid,words) VALUES(1015010,'And he took unto him all these, and divided them in the midst, and laid each piece one against another: but the birds divided he not.'); +INSERT INTO t1(docid,words) VALUES(1015011,'And when the fowls came down upon the carcases, Abram drove them away.'); +INSERT INTO t1(docid,words) VALUES(1015012,'And when the sun was going down, a deep sleep fell upon Abram; and, lo, an horror of great darkness fell upon him.'); +INSERT INTO t1(docid,words) VALUES(1015013,'And he said unto Abram, Know of a surety that thy seed shall be a stranger in a land that is not their''s, and shall serve them; and they shall afflict them four hundred years;'); +INSERT INTO t1(docid,words) VALUES(1015014,'And also that nation, whom they shall serve, will I judge: and afterward shall they come out with great substance.'); +INSERT INTO t1(docid,words) VALUES(1015015,'And thou shalt go to thy fathers in peace; thou shalt be buried in a good old age.'); +INSERT INTO t1(docid,words) VALUES(1015016,'But in the fourth generation they shall come hither again: for the iniquity of the Amorites is not yet full.'); +INSERT INTO t1(docid,words) VALUES(1015017,'And it came to pass, that, when the sun went down, and it was dark, behold a smoking furnace, and a burning lamp that passed between those pieces.'); +INSERT INTO t1(docid,words) VALUES(1015018,'In the same day the LORD made a covenant with Abram, saying, Unto thy seed have I given this land, from the river of Egypt unto the great river, the river Euphrates:'); +INSERT INTO t1(docid,words) VALUES(1015019,'The Kenites, and the Kenizzites, and the Kadmonites,'); +INSERT INTO t1(docid,words) VALUES(1015020,'And the Hittites, and the Perizzites, and the Rephaims,'); +INSERT INTO t1(docid,words) VALUES(1015021,'And the Amorites, and the Canaanites, and the Girgashites, and the Jebusites.'); +INSERT INTO t1(docid,words) VALUES(1016001,'Now Sarai Abram''s wife bare him no children: and she had an handmaid, an Egyptian, whose name was Hagar.'); +INSERT INTO t1(docid,words) VALUES(1016002,'And Sarai said unto Abram, Behold now, the LORD hath restrained me from bearing: I pray thee, go in unto my maid; it may be that I may obtain children by her. And Abram hearkened to the voice of Sarai.'); +INSERT INTO t1(docid,words) VALUES(1016003,'And Sarai Abram''s wife took Hagar her maid the Egyptian, after Abram had dwelt ten years in the land of Canaan, and gave her to her husband Abram to be his wife.'); +INSERT INTO t1(docid,words) VALUES(1016004,'And he went in unto Hagar, and she conceived: and when she saw that she had conceived, her mistress was despised in her eyes.'); +INSERT INTO t1(docid,words) VALUES(1016005,'And Sarai said unto Abram, My wrong be upon thee: I have given my maid into thy bosom; and when she saw that she had conceived, I was despised in her eyes: the LORD judge between me and thee.'); +INSERT INTO t1(docid,words) VALUES(1016006,'But Abram said unto Sarai, Behold, thy maid is in thine hand; do to her as it pleaseth thee. And when Sarai dealt hardly with her, she fled from her face.'); +INSERT INTO t1(docid,words) VALUES(1016007,'And the angel of the LORD found her by a fountain of water in the wilderness, by the fountain in the way to Shur.'); +INSERT INTO t1(docid,words) VALUES(1016008,'And he said, Hagar, Sarai''s maid, whence camest thou? and whither wilt thou go? And she said, I flee from the face of my mistress Sarai.'); +INSERT INTO t1(docid,words) VALUES(1016009,'And the angel of the LORD said unto her, Return to thy mistress, and submit thyself under her hands.'); +INSERT INTO t1(docid,words) VALUES(1016010,'And the angel of the LORD said unto her, I will multiply thy seed exceedingly, that it shall not be numbered for multitude.'); +INSERT INTO t1(docid,words) VALUES(1016011,'And the angel of the LORD said unto her, Behold, thou art with child and shalt bear a son, and shalt call his name Ishmael; because the LORD hath heard thy affliction.'); +INSERT INTO t1(docid,words) VALUES(1016012,'And he will be a wild man; his hand will be against every man, and every man''s hand against him; and he shall dwell in the presence of all his brethren.'); +INSERT INTO t1(docid,words) VALUES(1016013,'And she called the name of the LORD that spake unto her, Thou God seest me: for she said, Have I also here looked after him that seeth me?'); +INSERT INTO t1(docid,words) VALUES(1016014,'Wherefore the well was called Beerlahairoi; behold, it is between Kadesh and Bered.'); +INSERT INTO t1(docid,words) VALUES(1016015,'And Hagar bare Abram a son: and Abram called his son''s name, which Hagar bare, Ishmael.'); +INSERT INTO t1(docid,words) VALUES(1016016,'And Abram was fourscore and six years old, when Hagar bare Ishmael to Abram.'); +INSERT INTO t1(docid,words) VALUES(1017001,'And when Abram was ninety years old and nine, the LORD appeared to Abram, and said unto him, I am the Almighty God; walk before me, and be thou perfect.'); +INSERT INTO t1(docid,words) VALUES(1017002,'And I will make my covenant between me and thee, and will multiply thee exceedingly.'); +INSERT INTO t1(docid,words) VALUES(1017003,'And Abram fell on his face: and God talked with him, saying,'); +INSERT INTO t1(docid,words) VALUES(1017004,'As for me, behold, my covenant is with thee, and thou shalt be a father of many nations.'); +INSERT INTO t1(docid,words) VALUES(1017005,'Neither shall thy name any more be called Abram, but thy name shall be Abraham; for a father of many nations have I made thee.'); +INSERT INTO t1(docid,words) VALUES(1017006,'And I will make thee exceeding fruitful, and I will make nations of thee, and kings shall come out of thee.'); +INSERT INTO t1(docid,words) VALUES(1017007,'And I will establish my covenant between me and thee and thy seed after thee in their generations for an everlasting covenant, to be a God unto thee, and to thy seed after thee.'); +INSERT INTO t1(docid,words) VALUES(1017008,'And I will give unto thee, and to thy seed after thee, the land wherein thou art a stranger, all the land of Canaan, for an everlasting possession; and I will be their God.'); +INSERT INTO t1(docid,words) VALUES(1017009,'And God said unto Abraham, Thou shalt keep my covenant therefore, thou, and thy seed after thee in their generations.'); +INSERT INTO t1(docid,words) VALUES(1017010,'This is my covenant, which ye shall keep, between me and you and thy seed after thee; Every man child among you shall be circumcised.'); +INSERT INTO t1(docid,words) VALUES(1017011,'And ye shall circumcise the flesh of your foreskin; and it shall be a token of the covenant betwixt me and you.'); +INSERT INTO t1(docid,words) VALUES(1017012,'And he that is eight days old shall be circumcised among you, every man child in your generations, he that is born in the house, or bought with money of any stranger, which is not of thy seed.'); +INSERT INTO t1(docid,words) VALUES(1017013,'He that is born in thy house, and he that is bought with thy money, must needs be circumcised: and my covenant shall be in your flesh for an everlasting covenant.'); +INSERT INTO t1(docid,words) VALUES(1017014,'And the uncircumcised man child whose flesh of his foreskin is not circumcised, that soul shall be cut off from his people; he hath broken my covenant.'); +INSERT INTO t1(docid,words) VALUES(1017015,'And God said unto Abraham, As for Sarai thy wife, thou shalt not call her name Sarai, but Sarah shall her name be.'); +INSERT INTO t1(docid,words) VALUES(1017016,'And I will bless her, and give thee a son also of her: yea, I will bless her, and she shall be a mother of nations; kings of people shall be of her.'); +INSERT INTO t1(docid,words) VALUES(1017017,'Then Abraham fell upon his face, and laughed, and said in his heart, Shall a child be born unto him that is an hundred years old? and shall Sarah, that is ninety years old, bear?'); +INSERT INTO t1(docid,words) VALUES(1017018,'And Abraham said unto God, O that Ishmael might live before thee!'); +INSERT INTO t1(docid,words) VALUES(1017019,'And God said, Sarah thy wife shall bear thee a son indeed; and thou shalt call his name Isaac: and I will establish my covenant with him for an everlasting covenant, and with his seed after him.'); +INSERT INTO t1(docid,words) VALUES(1017020,'And as for Ishmael, I have heard thee: Behold, I have blessed him, and will make him fruitful, and will multiply him exceedingly; twelve princes shall he beget, and I will make him a great nation.'); +INSERT INTO t1(docid,words) VALUES(1017021,'But my covenant will I establish with Isaac, which Sarah shall bear unto thee at this set time in the next year.'); +INSERT INTO t1(docid,words) VALUES(1017022,'And he left off talking with him, and God went up from Abraham.'); +INSERT INTO t1(docid,words) VALUES(1017023,'And Abraham took Ishmael his son, and all that were born in his house, and all that were bought with his money, every male among the men of Abraham''s house; and circumcised the flesh of their foreskin in the selfsame day, as God had said unto him.'); +INSERT INTO t1(docid,words) VALUES(1017024,'And Abraham was ninety years old and nine, when he was circumcised in the flesh of his foreskin.'); +INSERT INTO t1(docid,words) VALUES(1017025,'And Ishmael his son was thirteen years old, when he was circumcised in the flesh of his foreskin.'); +INSERT INTO t1(docid,words) VALUES(1017026,'In the selfsame day was Abraham circumcised, and Ishmael his son.'); +INSERT INTO t1(docid,words) VALUES(1017027,'And all the men of his house, born in the house, and bought with money of the stranger, were circumcised with him.'); +INSERT INTO t1(docid,words) VALUES(1018001,'And the LORD appeared unto him in the plains of Mamre: and he sat in the tent door in the heat of the day;'); +INSERT INTO t1(docid,words) VALUES(1018002,'And he lift up his eyes and looked, and, lo, three men stood by him: and when he saw them, he ran to meet them from the tent door, and bowed himself toward the ground,'); +INSERT INTO t1(docid,words) VALUES(1018003,'And said, My LORD, if now I have found favour in thy sight, pass not away, I pray thee, from thy servant:'); +INSERT INTO t1(docid,words) VALUES(1018004,'Let a little water, I pray you, be fetched, and wash your feet, and rest yourselves under the tree:'); +INSERT INTO t1(docid,words) VALUES(1018005,'And I will fetch a morsel of bread, and comfort ye your hearts; after that ye shall pass on: for therefore are ye come to your servant. And they said, So do, as thou hast said.'); +INSERT INTO t1(docid,words) VALUES(1018006,'And Abraham hastened into the tent unto Sarah, and said, Make ready quickly three measures of fine meal, knead it, and make cakes upon the hearth.'); +INSERT INTO t1(docid,words) VALUES(1018007,'And Abraham ran unto the herd, and fetcht a calf tender and good, and gave it unto a young man; and he hasted to dress it.'); +INSERT INTO t1(docid,words) VALUES(1018008,'And he took butter, and milk, and the calf which he had dressed, and set it before them; and he stood by them under the tree, and they did eat.'); +INSERT INTO t1(docid,words) VALUES(1018009,'And they said unto him, Where is Sarah thy wife? And he said, Behold, in the tent.'); +INSERT INTO t1(docid,words) VALUES(1018010,'And he said, I will certainly return unto thee according to the time of life; and, lo, Sarah thy wife shall have a son. And Sarah heard it in the tent door, which was behind him.'); +INSERT INTO t1(docid,words) VALUES(1018011,'Now Abraham and Sarah were old and well stricken in age; and it ceased to be with Sarah after the manner of women.'); +INSERT INTO t1(docid,words) VALUES(1018012,'Therefore Sarah laughed within herself, saying, After I am waxed old shall I have pleasure, my lord being old also?'); +INSERT INTO t1(docid,words) VALUES(1018013,'And the LORD said unto Abraham, Wherefore did Sarah laugh, saying, Shall I of a surety bear a child, which am old?'); +INSERT INTO t1(docid,words) VALUES(1018014,'Is any thing too hard for the LORD? At the time appointed I will return unto thee, according to the time of life, and Sarah shall have a son.'); +INSERT INTO t1(docid,words) VALUES(1018015,'Then Sarah denied, saying, I laughed not; for she was afraid. And he said, Nay; but thou didst laugh.'); +INSERT INTO t1(docid,words) VALUES(1018016,'And the men rose up from thence, and looked toward Sodom: and Abraham went with them to bring them on the way.'); +INSERT INTO t1(docid,words) VALUES(1018017,'And the LORD said, Shall I hide from Abraham that thing which I do;'); +INSERT INTO t1(docid,words) VALUES(1018018,'Seeing that Abraham shall surely become a great and mighty nation, and all the nations of the earth shall be blessed in him?'); +INSERT INTO t1(docid,words) VALUES(1018019,'For I know him, that he will command his children and his household after him, and they shall keep the way of the LORD, to do justice and judgment; that the LORD may bring upon Abraham that which he hath spoken of him.'); +INSERT INTO t1(docid,words) VALUES(1018020,'And the LORD said, Because the cry of Sodom and Gomorrah is great, and because their sin is very grievous;'); +INSERT INTO t1(docid,words) VALUES(1018021,'I will go down now, and see whether they have done altogether according to the cry of it, which is come unto me; and if not, I will know.'); +INSERT INTO t1(docid,words) VALUES(1018022,'And the men turned their faces from thence, and went toward Sodom: but Abraham stood yet before the LORD.'); +INSERT INTO t1(docid,words) VALUES(1018023,'And Abraham drew near, and said, Wilt thou also destroy the righteous with the wicked?'); +INSERT INTO t1(docid,words) VALUES(1018024,'Peradventure there be fifty righteous within the city: wilt thou also destroy and not spare the place for the fifty righteous that are therein?'); +INSERT INTO t1(docid,words) VALUES(1018025,'That be far from thee to do after this manner, to slay the righteous with the wicked: and that the righteous should be as the wicked, that be far from thee: Shall not the Judge of all the earth do right?'); +INSERT INTO t1(docid,words) VALUES(1018026,'And the LORD said, If I find in Sodom fifty righteous within the city, then I will spare all the place for their sakes.'); +INSERT INTO t1(docid,words) VALUES(1018027,'And Abraham answered and said, Behold now, I have taken upon me to speak unto the LORD, which am but dust and ashes:'); +INSERT INTO t1(docid,words) VALUES(1018028,'Peradventure there shall lack five of the fifty righteous: wilt thou destroy all the city for lack of five? And he said, If I find there forty and five, I will not destroy it.'); +INSERT INTO t1(docid,words) VALUES(1018029,'And he spake unto him yet again, and said, Peradventure there shall be forty found there. And he said, I will not do it for forty''s sake.'); +INSERT INTO t1(docid,words) VALUES(1018030,'And he said unto him, Oh let not the LORD be angry, and I will speak: Peradventure there shall thirty be found there. And he said, I will not do it, if I find thirty there.'); +INSERT INTO t1(docid,words) VALUES(1018031,'And he said, Behold now, I have taken upon me to speak unto the LORD: Peradventure there shall be twenty found there. And he said, I will not destroy it for twenty''s sake.'); +INSERT INTO t1(docid,words) VALUES(1018032,'And he said, Oh let not the LORD be angry, and I will speak yet but this once: Peradventure ten shall be found there. And he said, I will not destroy it for ten''s sake.'); +INSERT INTO t1(docid,words) VALUES(1018033,'And the LORD went his way, as soon as he had left communing with Abraham: and Abraham returned unto his place.'); +INSERT INTO t1(docid,words) VALUES(1019001,'And there came two angels to Sodom at even; and Lot sat in the gate of Sodom: and Lot seeing them rose up to meet them; and he bowed himself with his face toward the ground;'); +INSERT INTO t1(docid,words) VALUES(1019002,'And he said, Behold now, my lords, turn in, I pray you, into your servant''s house, and tarry all night, and wash your feet, and ye shall rise up early, and go on your ways. And they said, Nay; but we will abide in the street all night.'); +INSERT INTO t1(docid,words) VALUES(1019003,'And he pressed upon them greatly; and they turned in unto him, and entered into his house; and he made them a feast, and did bake unleavened bread, and they did eat.'); +INSERT INTO t1(docid,words) VALUES(1019004,'But before they lay down, the men of the city, even the men of Sodom, compassed the house round, both old and young, all the people from every quarter:'); +INSERT INTO t1(docid,words) VALUES(1019005,'And they called unto Lot, and said unto him, Where are the men which came in to thee this night? bring them out unto us, that we may know them.'); +INSERT INTO t1(docid,words) VALUES(1019006,'And Lot went out at the door unto them, and shut the door after him,'); +INSERT INTO t1(docid,words) VALUES(1019007,'And said, I pray you, brethren, do not so wickedly.'); +INSERT INTO t1(docid,words) VALUES(1019008,'Behold now, I have two daughters which have not known man; let me, I pray you, bring them out unto you, and do ye to them as is good in your eyes: only unto these men do nothing; for therefore came they under the shadow of my roof.'); +INSERT INTO t1(docid,words) VALUES(1019009,'And they said, Stand back. And they said again, This one fellow came in to sojourn, and he will needs be a judge: now will we deal worse with thee, than with them. And they pressed sore upon the man, even Lot, and came near to break the door.'); +INSERT INTO t1(docid,words) VALUES(1019010,'But the men put forth their hand, and pulled Lot into the house to them, and shut to the door.'); +INSERT INTO t1(docid,words) VALUES(1019011,'And they smote the men that were at the door of the house with blindness, both small and great: so that they wearied themselves to find the door.'); +INSERT INTO t1(docid,words) VALUES(1019012,'And the men said unto Lot, Hast thou here any besides? son in law, and thy sons, and thy daughters, and whatsoever thou hast in the city, bring them out of this place:'); +INSERT INTO t1(docid,words) VALUES(1019013,'For we will destroy this place, because the cry of them is waxen great before the face of the LORD; and the LORD hath sent us to destroy it.'); +INSERT INTO t1(docid,words) VALUES(1019014,'And Lot went out, and spake unto his sons in law, which married his daughters, and said, Up, get you out of this place; for the LORD will destroy this city. But he seemed as one that mocked unto his sons in law.'); +INSERT INTO t1(docid,words) VALUES(1019015,'And when the morning arose, then the angels hastened Lot, saying, Arise, take thy wife, and thy two daughters, which are here; lest thou be consumed in the iniquity of the city.'); +INSERT INTO t1(docid,words) VALUES(1019016,'And while he lingered, the men laid hold upon his hand, and upon the hand of his wife, and upon the hand of his two daughters; the LORD being merciful unto him: and they brought him forth, and set him without the city.'); +INSERT INTO t1(docid,words) VALUES(1019017,'And it came to pass, when they had brought them forth abroad, that he said, Escape for thy life; look not behind thee, neither stay thou in all the plain; escape to the mountain, lest thou be consumed.'); +INSERT INTO t1(docid,words) VALUES(1019018,'And Lot said unto them, Oh, not so, my LORD:'); +INSERT INTO t1(docid,words) VALUES(1019019,'Behold now, thy servant hath found grace in thy sight, and thou hast magnified thy mercy, which thou hast shewed unto me in saving my life; and I cannot escape to the mountain, lest some evil take me, and I die:'); +INSERT INTO t1(docid,words) VALUES(1019020,'Behold now, this city is near to flee unto, and it is a little one: Oh, let me escape thither, (is it not a little one?) and my soul shall live.'); +INSERT INTO t1(docid,words) VALUES(1019021,'And he said unto him, See, I have accepted thee concerning this thing also, that I will not overthrow this city, for the which thou hast spoken.'); +INSERT INTO t1(docid,words) VALUES(1019022,'Haste thee, escape thither; for I cannot do anything till thou be come thither. Therefore the name of the city was called Zoar.'); +INSERT INTO t1(docid,words) VALUES(1019023,'The sun was risen upon the earth when Lot entered into Zoar.'); +INSERT INTO t1(docid,words) VALUES(1019024,'Then the LORD rained upon Sodom and upon Gomorrah brimstone and fire from the LORD out of heaven;'); +INSERT INTO t1(docid,words) VALUES(1019025,'And he overthrew those cities, and all the plain, and all the inhabitants of the cities, and that which grew upon the ground.'); +INSERT INTO t1(docid,words) VALUES(1019026,'But his wife looked back from behind him, and she became a pillar of salt.'); +INSERT INTO t1(docid,words) VALUES(1019027,'And Abraham gat up early in the morning to the place where he stood before the LORD:'); +INSERT INTO t1(docid,words) VALUES(1019028,'And he looked toward Sodom and Gomorrah, and toward all the land of the plain, and beheld, and, lo, the smoke of the country went up as the smoke of a furnace.'); +INSERT INTO t1(docid,words) VALUES(1019029,'And it came to pass, when God destroyed the cities of the plain, that God remembered Abraham, and sent Lot out of the midst of the overthrow, when he overthrew the cities in the which Lot dwelt.'); +INSERT INTO t1(docid,words) VALUES(1019030,'And Lot went up out of Zoar, and dwelt in the mountain, and his two daughters with him; for he feared to dwell in Zoar: and he dwelt in a cave, he and his two daughters.'); +INSERT INTO t1(docid,words) VALUES(1019031,'And the firstborn said unto the younger, Our father is old, and there is not a man in the earth to come in unto us after the manner of all the earth:'); +INSERT INTO t1(docid,words) VALUES(1019032,'Come, let us make our father drink wine, and we will lie with him, that we may preserve seed of our father.'); +INSERT INTO t1(docid,words) VALUES(1019033,'And they made their father drink wine that night: and the firstborn went in, and lay with her father; and he perceived not when she lay down, nor when she arose.'); +INSERT INTO t1(docid,words) VALUES(1019034,'And it came to pass on the morrow, that the firstborn said unto the younger, Behold, I lay yesternight with my father: let us make him drink wine this night also; and go thou in, and lie with him, that we may preserve seed of our father.'); +INSERT INTO t1(docid,words) VALUES(1019035,'And they made their father drink wine that night also: and the younger arose, and lay with him; and he perceived not when she lay down, nor when she arose.'); +INSERT INTO t1(docid,words) VALUES(1019036,'Thus were both the daughters of Lot with child by their father.'); +INSERT INTO t1(docid,words) VALUES(1019037,'And the first born bare a son, and called his name Moab: the same is the father of the Moabites unto this day.'); +INSERT INTO t1(docid,words) VALUES(1019038,'And the younger, she also bare a son, and called his name Benammi: the same is the father of the children of Ammon unto this day.'); +INSERT INTO t1(docid,words) VALUES(1020001,'And Abraham journeyed from thence toward the south country, and dwelled between Kadesh and Shur, and sojourned in Gerar.'); +INSERT INTO t1(docid,words) VALUES(1020002,'And Abraham said of Sarah his wife, She is my sister: and Abimelech king of Gerar sent, and took Sarah.'); +INSERT INTO t1(docid,words) VALUES(1020003,'But God came to Abimelech in a dream by night, and said to him, Behold, thou art but a dead man, for the woman which thou hast taken; for she is a man''s wife.'); +INSERT INTO t1(docid,words) VALUES(1020004,'But Abimelech had not come near her: and he said, LORD, wilt thou slay also a righteous nation?'); +INSERT INTO t1(docid,words) VALUES(1020005,'Said he not unto me, She is my sister? and she, even she herself said, He is my brother: in the integrity of my heart and innocency of my hands have I done this.'); +INSERT INTO t1(docid,words) VALUES(1020006,'And God said unto him in a dream, Yea, I know that thou didst this in the integrity of thy heart; for I also withheld thee from sinning against me: therefore suffered I thee not to touch her.'); +INSERT INTO t1(docid,words) VALUES(1020007,'Now therefore restore the man his wife; for he is a prophet, and he shall pray for thee, and thou shalt live: and if thou restore her not, know thou that thou shalt surely die, thou, and all that are thine.'); +INSERT INTO t1(docid,words) VALUES(1020008,'Therefore Abimelech rose early in the morning, and called all his servants, and told all these things in their ears: and the men were sore afraid.'); +INSERT INTO t1(docid,words) VALUES(1020009,'Then Abimelech called Abraham, and said unto him, What hast thou done unto us? and what have I offended thee, that thou hast brought on me and on my kingdom a great sin? thou hast done deeds unto me that ought not to be done.'); +INSERT INTO t1(docid,words) VALUES(1020010,'And Abimelech said unto Abraham, What sawest thou, that thou hast done this thing?'); +INSERT INTO t1(docid,words) VALUES(1020011,'And Abraham said, Because I thought, Surely the fear of God is not in this place; and they will slay me for my wife''s sake.'); +INSERT INTO t1(docid,words) VALUES(1020012,'And yet indeed she is my sister; she is the daughter of my father, but not the daughter of my mother; and she became my wife.'); +INSERT INTO t1(docid,words) VALUES(1020013,'And it came to pass, when God caused me to wander from my father''s house, that I said unto her, This is thy kindness which thou shalt shew unto me; at every place whither we shall come, say of me, He is my brother.'); +INSERT INTO t1(docid,words) VALUES(1020014,'And Abimelech took sheep, and oxen, and menservants, and womenservants, and gave them unto Abraham, and restored him Sarah his wife.'); +INSERT INTO t1(docid,words) VALUES(1020015,'And Abimelech said, Behold, my land is before thee: dwell where it pleaseth thee.'); +INSERT INTO t1(docid,words) VALUES(1020016,'And unto Sarah he said, Behold, I have given thy brother a thousand pieces of silver: behold, he is to thee a covering of the eyes, unto all that are with thee, and with all other: thus she was reproved.'); +INSERT INTO t1(docid,words) VALUES(1020017,'So Abraham prayed unto God: and God healed Abimelech, and his wife, and his maidservants; and they bare children.'); +INSERT INTO t1(docid,words) VALUES(1020018,'For the LORD had fast closed up all the wombs of the house of Abimelech, because of Sarah Abraham''s wife.'); +INSERT INTO t1(docid,words) VALUES(1021001,'And the LORD visited Sarah as he had said, and the LORD did unto Sarah as he had spoken.'); +INSERT INTO t1(docid,words) VALUES(1021002,'For Sarah conceived, and bare Abraham a son in his old age, at the set time of which God had spoken to him.'); +INSERT INTO t1(docid,words) VALUES(1021003,'And Abraham called the name of his son that was born unto him, whom Sarah bare to him, Isaac.'); +INSERT INTO t1(docid,words) VALUES(1021004,'And Abraham circumcised his son Isaac being eight days old, as God had commanded him.'); +INSERT INTO t1(docid,words) VALUES(1021005,'And Abraham was an hundred years old, when his son Isaac was born unto him.'); +INSERT INTO t1(docid,words) VALUES(1021006,'And Sarah said, God hath made me to laugh, so that all that hear will laugh with me.'); +INSERT INTO t1(docid,words) VALUES(1021007,'And she said, Who would have said unto Abraham, that Sarah should have given children suck? for I have born him a son in his old age.'); +INSERT INTO t1(docid,words) VALUES(1021008,'And the child grew, and was weaned: and Abraham made a great feast the same day that Isaac was weaned.'); +INSERT INTO t1(docid,words) VALUES(1021009,'And Sarah saw the son of Hagar the Egyptian, which she had born unto Abraham, mocking.'); +INSERT INTO t1(docid,words) VALUES(1021010,'Wherefore she said unto Abraham, Cast out this bondwoman and her son: for the son of this bondwoman shall not be heir with my son, even with Isaac.'); +INSERT INTO t1(docid,words) VALUES(1021011,'And the thing was very grievous in Abraham''s sight because of his son.'); +INSERT INTO t1(docid,words) VALUES(1021012,'And God said unto Abraham, Let it not be grievous in thy sight because of the lad, and because of thy bondwoman; in all that Sarah hath said unto thee, hearken unto her voice; for in Isaac shall thy seed be called.'); +INSERT INTO t1(docid,words) VALUES(1021013,'And also of the son of the bondwoman will I make a nation, because he is thy seed.'); +INSERT INTO t1(docid,words) VALUES(1021014,'And Abraham rose up early in the morning, and took bread, and a bottle of water, and gave it unto Hagar, putting it on her shoulder, and the child, and sent her away: and she departed, and wandered in the wilderness of Beersheba.'); +INSERT INTO t1(docid,words) VALUES(1021015,'And the water was spent in the bottle, and she cast the child under one of the shrubs.'); +INSERT INTO t1(docid,words) VALUES(1021016,'And she went, and sat her down over against him a good way off, as it were a bow shot: for she said, Let me not see the death of the child. And she sat over against him, and lift up her voice, and wept.'); +INSERT INTO t1(docid,words) VALUES(1021017,'And God heard the voice of the lad; and the angel of God called to Hagar out of heaven, and said unto her, What aileth thee, Hagar? fear not; for God hath heard the voice of the lad where he is.'); +INSERT INTO t1(docid,words) VALUES(1021018,'Arise, lift up the lad, and hold him in thine hand; for I will make him a great nation.'); +INSERT INTO t1(docid,words) VALUES(1021019,'And God opened her eyes, and she saw a well of water; and she went, and filled the bottle with water, and gave the lad drink.'); +INSERT INTO t1(docid,words) VALUES(1021020,'And God was with the lad; and he grew, and dwelt in the wilderness, and became an archer.'); +INSERT INTO t1(docid,words) VALUES(1021021,'And he dwelt in the wilderness of Paran: and his mother took him a wife out of the land of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1021022,'And it came to pass at that time, that Abimelech and Phichol the chief captain of his host spake unto Abraham, saying, God is with thee in all that thou doest:'); +INSERT INTO t1(docid,words) VALUES(1021023,'Now therefore swear unto me here by God that thou wilt not deal falsely with me, nor with my son, nor with my son''s son: but according to the kindness that I have done unto thee, thou shalt do unto me, and to the land wherein thou hast sojourned.'); +INSERT INTO t1(docid,words) VALUES(1021024,'And Abraham said, I will swear.'); +INSERT INTO t1(docid,words) VALUES(1021025,'And Abraham reproved Abimelech because of a well of water, which Abimelech''s servants had violently taken away.'); +INSERT INTO t1(docid,words) VALUES(1021026,'And Abimelech said, I wot not who hath done this thing; neither didst thou tell me, neither yet heard I of it, but to day.'); +INSERT INTO t1(docid,words) VALUES(1021027,'And Abraham took sheep and oxen, and gave them unto Abimelech; and both of them made a covenant.'); +INSERT INTO t1(docid,words) VALUES(1021028,'And Abraham set seven ewe lambs of the flock by themselves.'); +INSERT INTO t1(docid,words) VALUES(1021029,'And Abimelech said unto Abraham, What mean these seven ewe lambs which thou hast set by themselves?'); +INSERT INTO t1(docid,words) VALUES(1021030,'And he said, For these seven ewe lambs shalt thou take of my hand, that they may be a witness unto me, that I have digged this well.'); +INSERT INTO t1(docid,words) VALUES(1021031,'Wherefore he called that place Beersheba; because there they sware both of them.'); +INSERT INTO t1(docid,words) VALUES(1021032,'Thus they made a covenant at Beersheba: then Abimelech rose up, and Phichol the chief captain of his host, and they returned into the land of the Philistines.'); +INSERT INTO t1(docid,words) VALUES(1021033,'And Abraham planted a grove in Beersheba, and called there on the name of the LORD, the everlasting God.'); +INSERT INTO t1(docid,words) VALUES(1021034,'And Abraham sojourned in the Philistines'' land many days.'); +INSERT INTO t1(docid,words) VALUES(1022001,'And it came to pass after these things, that God did tempt Abraham, and said unto him, Abraham: and he said, Behold, here I am.'); +INSERT INTO t1(docid,words) VALUES(1022002,'And he said, Take now thy son, thine only son Isaac, whom thou lovest, and get thee into the land of Moriah; and offer him there for a burnt offering upon one of the mountains which I will tell thee of.'); +INSERT INTO t1(docid,words) VALUES(1022003,'And Abraham rose up early in the morning, and saddled his ass, and took two of his young men with him, and Isaac his son, and clave the wood for the burnt offering, and rose up, and went unto the place of which God had told him.'); +INSERT INTO t1(docid,words) VALUES(1022004,'Then on the third day Abraham lifted up his eyes, and saw the place afar off.'); +INSERT INTO t1(docid,words) VALUES(1022005,'And Abraham said unto his young men, Abide ye here with the ass; and I and the lad will go yonder and worship, and come again to you.'); +INSERT INTO t1(docid,words) VALUES(1022006,'And Abraham took the wood of the burnt offering, and laid it upon Isaac his son; and he took the fire in his hand, and a knife; and they went both of them together.'); +INSERT INTO t1(docid,words) VALUES(1022007,'And Isaac spake unto Abraham his father, and said, My father: and he said, Here am I, my son. And he said, Behold the fire and the wood: but where is the lamb for a burnt offering?'); +INSERT INTO t1(docid,words) VALUES(1022008,'And Abraham said, My son, God will provide himself a lamb for a burnt offering: so they went both of them together.'); +INSERT INTO t1(docid,words) VALUES(1022009,'And they came to the place which God had told him of; and Abraham built an altar there, and laid the wood in order, and bound Isaac his son, and laid him on the altar upon the wood.'); +INSERT INTO t1(docid,words) VALUES(1022010,'And Abraham stretched forth his hand, and took the knife to slay his son.'); +INSERT INTO t1(docid,words) VALUES(1022011,'And the angel of the LORD called unto him out of heaven, and said, Abraham, Abraham: and he said, Here am I.'); +INSERT INTO t1(docid,words) VALUES(1022012,'And he said, Lay not thine hand upon the lad, neither do thou any thing unto him: for now I know that thou fearest God, seeing thou hast not withheld thy son, thine only son from me.'); +INSERT INTO t1(docid,words) VALUES(1022013,'And Abraham lifted up his eyes, and looked, and behold behind him a ram caught in a thicket by his horns: and Abraham went and took the ram, and offered him up for a burnt offering in the stead of his son.'); +INSERT INTO t1(docid,words) VALUES(1022014,'And Abraham called the name of that place Jehovahjireh: as it is said to this day, In the mount of the LORD it shall be seen.'); +INSERT INTO t1(docid,words) VALUES(1022015,'And the angel of the LORD called unto Abraham out of heaven the second time,'); +INSERT INTO t1(docid,words) VALUES(1022016,'And said, By myself have I sworn, saith the LORD, for because thou hast done this thing, and hast not withheld thy son, thine only son:'); +INSERT INTO t1(docid,words) VALUES(1022017,'That in blessing I will bless thee, and in multiplying I will multiply thy seed as the stars of the heaven, and as the sand which is upon the sea shore; and thy seed shall possess the gate of his enemies;'); +INSERT INTO t1(docid,words) VALUES(1022018,'And in thy seed shall all the nations of the earth be blessed; because thou hast obeyed my voice.'); +INSERT INTO t1(docid,words) VALUES(1022019,'So Abraham returned unto his young men, and they rose up and went together to Beersheba; and Abraham dwelt at Beersheba.'); +INSERT INTO t1(docid,words) VALUES(1022020,'And it came to pass after these things, that it was told Abraham, saying, Behold, Milcah, she hath also born children unto thy brother Nahor;'); +INSERT INTO t1(docid,words) VALUES(1022021,'Huz his firstborn, and Buz his brother, and Kemuel the father of Aram,'); +INSERT INTO t1(docid,words) VALUES(1022022,'And Chesed, and Hazo, and Pildash, and Jidlaph, and Bethuel.'); +INSERT INTO t1(docid,words) VALUES(1022023,'And Bethuel begat Rebekah: these eight Milcah did bear to Nahor, Abraham''s brother.'); +INSERT INTO t1(docid,words) VALUES(1022024,'And his concubine, whose name was Reumah, she bare also Tebah, and Gaham, and Thahash, and Maachah.'); +INSERT INTO t1(docid,words) VALUES(1023001,'And Sarah was an hundred and seven and twenty years old: these were the years of the life of Sarah.'); +INSERT INTO t1(docid,words) VALUES(1023002,'And Sarah died in Kirjatharba; the same is Hebron in the land of Canaan: and Abraham came to mourn for Sarah, and to weep for her.'); +INSERT INTO t1(docid,words) VALUES(1023003,'And Abraham stood up from before his dead, and spake unto the sons of Heth, saying,'); +INSERT INTO t1(docid,words) VALUES(1023004,'I am a stranger and a sojourner with you: give me a possession of a buryingplace with you, that I may bury my dead out of my sight.'); +INSERT INTO t1(docid,words) VALUES(1023005,'And the children of Heth answered Abraham, saying unto him,'); +INSERT INTO t1(docid,words) VALUES(1023006,'Hear us, my lord: thou art a mighty prince among us: in the choice of our sepulchres bury thy dead; none of us shall withhold from thee his sepulchre, but that thou mayest bury thy dead.'); +INSERT INTO t1(docid,words) VALUES(1023007,'And Abraham stood up, and bowed himself to the people of the land, even to the children of Heth.'); +INSERT INTO t1(docid,words) VALUES(1023008,'And he communed with them, saying, If it be your mind that I should bury my dead out of my sight; hear me, and intreat for me to Ephron the son of Zohar,'); +INSERT INTO t1(docid,words) VALUES(1023009,'That he may give me the cave of Machpelah, which he hath, which is in the end of his field; for as much money as it is worth he shall give it me for a possession of a buryingplace amongst you.'); +INSERT INTO t1(docid,words) VALUES(1023010,'And Ephron dwelt among the children of Heth: and Ephron the Hittite answered Abraham in the audience of the children of Heth, even of all that went in at the gate of his city, saying,'); +INSERT INTO t1(docid,words) VALUES(1023011,'Nay, my lord, hear me: the field give I thee, and the cave that is therein, I give it thee; in the presence of the sons of my people give I it thee: bury thy dead.'); +INSERT INTO t1(docid,words) VALUES(1023012,'And Abraham bowed down himself before the people of the land.'); +INSERT INTO t1(docid,words) VALUES(1023013,'And he spake unto Ephron in the audience of the people of the land, saying, But if thou wilt give it, I pray thee, hear me: I will give thee money for the field; take it of me, and I will bury my dead there.'); +INSERT INTO t1(docid,words) VALUES(1023014,'And Ephron answered Abraham, saying unto him,'); +INSERT INTO t1(docid,words) VALUES(1023015,'My lord, hearken unto me: the land is worth four hundred shekels of silver; what is that betwixt me and thee? bury therefore thy dead.'); +INSERT INTO t1(docid,words) VALUES(1023016,'And Abraham hearkened unto Ephron; and Abraham weighed to Ephron the silver, which he had named in the audience of the sons of Heth, four hundred shekels of silver, current money with the merchant.'); +INSERT INTO t1(docid,words) VALUES(1023017,'And the field of Ephron which was in Machpelah, which was before Mamre, the field, and the cave which was therein, and all the trees that were in the field, that were in all the borders round about, were made sure'); +INSERT INTO t1(docid,words) VALUES(1023018,'Unto Abraham for a possession in the presence of the children of Heth, before all that went in at the gate of his city.'); +INSERT INTO t1(docid,words) VALUES(1023019,'And after this, Abraham buried Sarah his wife in the cave of the field of Machpelah before Mamre: the same is Hebron in the land of Canaan.'); +INSERT INTO t1(docid,words) VALUES(1023020,'And the field, and the cave that is therein, were made sure unto Abraham for a possession of a buryingplace by the sons of Heth.'); +INSERT INTO t1(docid,words) VALUES(1024001,'And Abraham was old, and well stricken in age: and the LORD had blessed Abraham in all things.'); +INSERT INTO t1(docid,words) VALUES(1024002,'And Abraham said unto his eldest servant of his house, that ruled over all that he had, Put, I pray thee, thy hand under my thigh:'); +INSERT INTO t1(docid,words) VALUES(1024003,'And I will make thee swear by the LORD, the God of heaven, and the God of the earth, that thou shalt not take a wife unto my son of the daughters of the Canaanites, among whom I dwell:'); +INSERT INTO t1(docid,words) VALUES(1024004,'But thou shalt go unto my country, and to my kindred, and take a wife unto my son Isaac.'); +INSERT INTO t1(docid,words) VALUES(1024005,'And the servant said unto him, Peradventure the woman will not be willing to follow me unto this land: must I needs bring thy son again unto the land from whence thou camest?'); +INSERT INTO t1(docid,words) VALUES(1024006,'And Abraham said unto him, Beware thou that thou bring not my son thither again.'); +INSERT INTO t1(docid,words) VALUES(1024007,'The LORD God of heaven, which took me from my father''s house, and from the land of my kindred, and which spake unto me, and that sware unto me, saying, Unto thy seed will I give this land; he shall send his angel before thee, and thou shalt take a wife unto my son from thence.'); +INSERT INTO t1(docid,words) VALUES(1024008,'And if the woman will not be willing to follow thee, then thou shalt be clear from this my oath: only bring not my son thither again.'); +INSERT INTO t1(docid,words) VALUES(1024009,'And the servant put his hand under the thigh of Abraham his master, and sware to him concerning that matter.'); +INSERT INTO t1(docid,words) VALUES(1024010,'And the servant took ten camels of the camels of his master, and departed; for all the goods of his master were in his hand: and he arose, and went to Mesopotamia, unto the city of Nahor.'); +INSERT INTO t1(docid,words) VALUES(1024011,'And he made his camels to kneel down without the city by a well of water at the time of the evening, even the time that women go out to draw water.'); +INSERT INTO t1(docid,words) VALUES(1024012,'And he said O LORD God of my master Abraham, I pray thee, send me good speed this day, and shew kindness unto my master Abraham.'); +INSERT INTO t1(docid,words) VALUES(1024013,'Behold, I stand here by the well of water; and the daughters of the men of the city come out to draw water:'); +INSERT INTO t1(docid,words) VALUES(1024014,'And let it come to pass, that the damsel to whom I shall say, Let down thy pitcher, I pray thee, that I may drink; and she shall say, Drink, and I will give thy camels drink also: let the same be she that thou hast appointed for thy servant Isaac; and thereby shall I know that thou hast shewed kindness unto my master.'); +INSERT INTO t1(docid,words) VALUES(1024015,'And it came to pass, before he had done speaking, that, behold, Rebekah came out, who was born to Bethuel, son of Milcah, the wife of Nahor, Abraham''s brother, with her pitcher upon her shoulder.'); +INSERT INTO t1(docid,words) VALUES(1024016,'And the damsel was very fair to look upon, a virgin, neither had any man known her: and she went down to the well, and filled her pitcher, and came up.'); +INSERT INTO t1(docid,words) VALUES(1024017,'And the servant ran to meet her, and said, Let me, I pray thee, drink a little water of thy pitcher.'); +INSERT INTO t1(docid,words) VALUES(1024018,'And she said, Drink, my lord: and she hasted, and let down her pitcher upon her hand, and gave him drink.'); +INSERT INTO t1(docid,words) VALUES(1024019,'And when she had done giving him drink, she said, I will draw water for thy camels also, until they have done drinking.'); +INSERT INTO t1(docid,words) VALUES(1024020,'And she hasted, and emptied her pitcher into the trough, and ran again unto the well to draw water, and drew for all his camels.'); +INSERT INTO t1(docid,words) VALUES(1024021,'And the man wondering at her held his peace, to wit whether the LORD had made his journey prosperous or not.'); +INSERT INTO t1(docid,words) VALUES(1024022,'And it came to pass, as the camels had done drinking, that the man took a golden earring of half a shekel weight, and two bracelets for her hands of ten shekels weight of gold;'); +INSERT INTO t1(docid,words) VALUES(1024023,'And said, Whose daughter art thou? tell me, I pray thee: is there room in thy father''s house for us to lodge in?'); +INSERT INTO t1(docid,words) VALUES(1024024,'And she said unto him, I am the daughter of Bethuel the son of Milcah, which she bare unto Nahor.'); +INSERT INTO t1(docid,words) VALUES(1024025,'She said moreover unto him, We have both straw and provender enough, and room to lodge in.'); +INSERT INTO t1(docid,words) VALUES(1024026,'And the man bowed down his head, and worshipped the LORD.'); +INSERT INTO t1(docid,words) VALUES(1024027,'And he said, Blessed be the LORD God of my master Abraham, who hath not left destitute my master of his mercy and his truth: I being in the way, the LORD led me to the house of my master''s brethren.'); +INSERT INTO t1(docid,words) VALUES(1024028,'And the damsel ran, and told them of her mother''s house these things.'); +INSERT INTO t1(docid,words) VALUES(1024029,'And Rebekah had a brother, and his name was Laban: and Laban ran out unto the man, unto the well.'); +INSERT INTO t1(docid,words) VALUES(1024030,'And it came to pass, when he saw the earring and bracelets upon his sister''s hands, and when he heard the words of Rebekah his sister, saying, Thus spake the man unto me; that he came unto the man; and, behold, he stood by the camels at the well.'); +INSERT INTO t1(docid,words) VALUES(1024031,'And he said, Come in, thou blessed of the LORD; wherefore standest thou without? for I have prepared the house, and room for the camels.'); +INSERT INTO t1(docid,words) VALUES(1024032,'And the man came into the house: and he ungirded his camels, and gave straw and provender for the camels, and water to wash his feet, and the men''s feet that were with him.'); +INSERT INTO t1(docid,words) VALUES(1024033,'And there was set meat before him to eat: but he said, I will not eat, until I have told mine errand. And he said, Speak on.'); +INSERT INTO t1(docid,words) VALUES(1024034,'And he said, I am Abraham''s servant.'); +INSERT INTO t1(docid,words) VALUES(1024035,'And the LORD hath blessed my master greatly; and he is become great: and he hath given him flocks, and herds, and silver, and gold, and menservants, and maidservants, and camels, and asses.'); +INSERT INTO t1(docid,words) VALUES(1024036,'And Sarah my master''s wife bare a son to my master when she was old: and unto him hath he given all that he hath.'); +INSERT INTO t1(docid,words) VALUES(1024037,'And my master made me swear, saying, Thou shalt not take a wife to my son of the daughters of the Canaanites, in whose land I dwell:'); +INSERT INTO t1(docid,words) VALUES(1024038,'But thou shalt go unto my father''s house, and to my kindred, and take a wife unto my son.'); +INSERT INTO t1(docid,words) VALUES(1024039,'And I said unto my master, Peradventure the woman will not follow me.'); +INSERT INTO t1(docid,words) VALUES(1024040,'And he said unto me, The LORD, before whom I walk, will send his angel with thee, and prosper thy way; and thou shalt take a wife for my son of my kindred, and of my father''s house:'); +INSERT INTO t1(docid,words) VALUES(1024041,'Then shalt thou be clear from this my oath, when thou comest to my kindred; and if they give not thee one, thou shalt be clear from my oath.'); +INSERT INTO t1(docid,words) VALUES(1024042,'And I came this day unto the well, and said, O LORD God of my master Abraham, if now thou do prosper my way which I go:'); +INSERT INTO t1(docid,words) VALUES(1024043,'Behold, I stand by the well of water; and it shall come to pass, that when the virgin cometh forth to draw water, and I say to her, Give me, I pray thee, a little water of thy pitcher to drink;'); +INSERT INTO t1(docid,words) VALUES(1024044,'And she say to me, Both drink thou, and I will also draw for thy camels: let the same be the woman whom the LORD hath appointed out for my master''s son.'); +INSERT INTO t1(docid,words) VALUES(1024045,'And before I had done speaking in mine heart, behold, Rebekah came forth with her pitcher on her shoulder; and she went down unto the well, and drew water: and I said unto her, Let me drink, I pray thee.'); +INSERT INTO t1(docid,words) VALUES(1024046,'And she made haste, and let down her pitcher from her shoulder, and said, Drink, and I will give thy camels drink also: so I drank, and she made the camels drink also.'); +INSERT INTO t1(docid,words) VALUES(1024047,'And I asked her, and said, Whose daughter art thou? And she said, the daughter of Bethuel, Nahor''s son, whom Milcah bare unto him: and I put the earring upon her face, and the bracelets upon her hands.'); +INSERT INTO t1(docid,words) VALUES(1024048,'And I bowed down my head, and worshipped the LORD, and blessed the LORD God of my master Abraham, which had led me in the right way to take my master''s brother''s daughter unto his son.'); +INSERT INTO t1(docid,words) VALUES(1024049,'And now if ye will deal kindly and truly with my master, tell me: and if not, tell me; that I may turn to the right hand, or to the left.'); +INSERT INTO t1(docid,words) VALUES(1024050,'Then Laban and Bethuel answered and said, The thing proceedeth from the LORD: we cannot speak unto thee bad or good.'); +INSERT INTO t1(docid,words) VALUES(1024051,'Behold, Rebekah is before thee, take her, and go, and let her be thy master''s son''s wife, as the LORD hath spoken.'); +INSERT INTO t1(docid,words) VALUES(1024052,'And it came to pass, that, when Abraham''s servant heard their words, he worshipped the LORD, bowing himself to the earth.'); +INSERT INTO t1(docid,words) VALUES(1024053,'And the servant brought forth jewels of silver, and jewels of gold, and raiment, and gave them to Rebekah: he gave also to her brother and to her mother precious things.'); +INSERT INTO t1(docid,words) VALUES(1024054,'And they did eat and drink, he and the men that were with him, and tarried all night; and they rose up in the morning, and he said, Send me away unto my master.'); +INSERT INTO t1(docid,words) VALUES(1024055,'And her brother and her mother said, Let the damsel abide with us a few days, at the least ten; after that she shall go.'); +INSERT INTO t1(docid,words) VALUES(1024056,'And he said unto them, Hinder me not, seeing the LORD hath prospered my way; send me away that I may go to my master.'); +INSERT INTO t1(docid,words) VALUES(1024057,'And they said, We will call the damsel, and enquire at her mouth.'); +INSERT INTO t1(docid,words) VALUES(1024058,'And they called Rebekah, and said unto her, Wilt thou go with this man? And she said, I will go.'); +INSERT INTO t1(docid,words) VALUES(1024059,'And they sent away Rebekah their sister, and her nurse, and Abraham''s servant, and his men.'); +INSERT INTO t1(docid,words) VALUES(1024060,'And they blessed Rebekah, and said unto her, Thou art our sister, be thou the mother of thousands of millions, and let thy seed possess the gate of those which hate them.'); +INSERT INTO t1(docid,words) VALUES(1024061,'And Rebekah arose, and her damsels, and they rode upon the camels, and followed the man: and the servant took Rebekah, and went his way.'); +INSERT INTO t1(docid,words) VALUES(1024062,'And Isaac came from the way of the well Lahairoi; for he dwelt in the south country.'); +INSERT INTO t1(docid,words) VALUES(1024063,'And Isaac went out to meditate in the field at the eventide: and he lifted up his eyes, and saw, and, behold, the camels were coming.'); +INSERT INTO t1(docid,words) VALUES(1024064,'And Rebekah lifted up her eyes, and when she saw Isaac, she lighted off the camel.'); +INSERT INTO t1(docid,words) VALUES(1024065,'For she had said unto the servant, What man is this that walketh in the field to meet us? And the servant had said, It is my master: therefore she took a vail, and covered herself.'); +INSERT INTO t1(docid,words) VALUES(1024066,'And the servant told Isaac all things that he had done.'); +INSERT INTO t1(docid,words) VALUES(1024067,'And Isaac brought her into his mother Sarah''s tent, and took Rebekah, and she became his wife; and he loved her: and Isaac was comforted after his mother''s death.'); +INSERT INTO t1(docid,words) VALUES(1025001,'Then again Abraham took a wife, and her name was Keturah.'); +INSERT INTO t1(docid,words) VALUES(1025002,'And she bare him Zimran, and Jokshan, and Medan, and Midian, and Ishbak, and Shuah.'); +INSERT INTO t1(docid,words) VALUES(1025003,'And Jokshan begat Sheba, and Dedan. And the sons of Dedan were Asshurim, and Letushim, and Leummim.'); +INSERT INTO t1(docid,words) VALUES(1025004,'And the sons of Midian; Ephah, and Epher, and Hanoch, and Abidah, and Eldaah. All these were the children of Keturah.'); +INSERT INTO t1(docid,words) VALUES(1025005,'And Abraham gave all that he had unto Isaac.'); +INSERT INTO t1(docid,words) VALUES(1025006,'But unto the sons of the concubines, which Abraham had, Abraham gave gifts, and sent them away from Isaac his son, while he yet lived, eastward, unto the east country.'); +INSERT INTO t1(docid,words) VALUES(1025007,'And these are the days of the years of Abraham''s life which he lived, an hundred threescore and fifteen years.'); +INSERT INTO t1(docid,words) VALUES(1025008,'Then Abraham gave up the ghost, and died in a good old age, an old man, and full of years; and was gathered to his people.'); +INSERT INTO t1(docid,words) VALUES(1025009,'And his sons Isaac and Ishmael buried him in the cave of Machpelah, in the field of Ephron the son of Zohar the Hittite, which is before Mamre;'); +INSERT INTO t1(docid,words) VALUES(1025010,'The field which Abraham purchased of the sons of Heth: there was Abraham buried, and Sarah his wife.'); +INSERT INTO t1(docid,words) VALUES(1025011,'And it came to pass after the death of Abraham, that God blessed his son Isaac; and Isaac dwelt by the well Lahairoi.'); +INSERT INTO t1(docid,words) VALUES(1025012,'Now these are the generations of Ishmael, Abraham''s son, whom Hagar the Egyptian, Sarah''s handmaid, bare unto Abraham:'); +INSERT INTO t1(docid,words) VALUES(1025013,'And these are the names of the sons of Ishmael, by their names, according to their generations: the firstborn of Ishmael, Nebajoth; and Kedar, and Adbeel, and Mibsam,'); +INSERT INTO t1(docid,words) VALUES(1025014,'And Mishma, and Dumah, and Massa,'); +INSERT INTO t1(docid,words) VALUES(1025015,'Hadar, and Tema, Jetur, Naphish, and Kedemah:'); +INSERT INTO t1(docid,words) VALUES(1025016,'These are the sons of Ishmael, and these are their names, by their towns, and by their castles; twelve princes according to their nations.'); +INSERT INTO t1(docid,words) VALUES(1025017,'And these are the years of the life of Ishmael, an hundred and thirty and seven years: and he gave up the ghost and died; and was gathered unto his people.'); +INSERT INTO t1(docid,words) VALUES(1025018,'And they dwelt from Havilah unto Shur, that is before Egypt, as thou goest toward Assyria: and he died in the presence of all his brethren.'); +INSERT INTO t1(docid,words) VALUES(1025019,'And these are the generations of Isaac, Abraham''s son: Abraham begat Isaac:'); +INSERT INTO t1(docid,words) VALUES(1025020,'And Isaac was forty years old when he took Rebekah to wife, the daughter of Bethuel the Syrian of Padanaram, the sister to Laban the Syrian.'); +INSERT INTO t1(docid,words) VALUES(1025021,'And Isaac intreated the LORD for his wife, because she was barren: and the LORD was intreated of him, and Rebekah his wife conceived.'); +INSERT INTO t1(docid,words) VALUES(1025022,'And the children struggled together within her; and she said, If it be so, why am I thus? And she went to enquire of the LORD.'); +INSERT INTO t1(docid,words) VALUES(1025023,'And the LORD said unto her, Two nations are in thy womb, and two manner of people shall be separated from thy bowels; and the one people shall be stronger than the other people; and the elder shall serve the younger.'); +INSERT INTO t1(docid,words) VALUES(1025024,'And when her days to be delivered were fulfilled, behold, there were twins in her womb.'); +INSERT INTO t1(docid,words) VALUES(1025025,'And the first came out red, all over like an hairy garment; and they called his name Esau.'); +INSERT INTO t1(docid,words) VALUES(1025026,'And after that came his brother out, and his hand took hold on Esau''s heel; and his name was called Jacob: and Isaac was threescore years old when she bare them.'); +INSERT INTO t1(docid,words) VALUES(1025027,'And the boys grew: and Esau was a cunning hunter, a man of the field; and Jacob was a plain man, dwelling in tents.'); +INSERT INTO t1(docid,words) VALUES(1025028,'And Isaac loved Esau, because he did eat of his venison: but Rebekah loved Jacob.'); +INSERT INTO t1(docid,words) VALUES(1025029,'And Jacob sod pottage: and Esau came from the field, and he was faint:'); +INSERT INTO t1(docid,words) VALUES(1025030,'And Esau said to Jacob, Feed me, I pray thee, with that same red pottage; for I am faint: therefore was his name called Edom.'); +INSERT INTO t1(docid,words) VALUES(1025031,'And Jacob said, Sell me this day thy birthright.'); +INSERT INTO t1(docid,words) VALUES(1025032,'And Esau said, Behold, I am at the point to die: and what profit shall this birthright do to me?'); +INSERT INTO t1(docid,words) VALUES(1025033,'And Jacob said, Swear to me this day; and he sware unto him: and he sold his birthright unto Jacob.'); +INSERT INTO t1(docid,words) VALUES(1025034,'Then Jacob gave Esau bread and pottage of lentiles; and he did eat and drink, and rose up, and went his way: thus Esau despised his birthright.'); +INSERT INTO t1(docid,words) VALUES(1026001,'And there was a famine in the land, beside the first famine that was in the days of Abraham. And Isaac went unto Abimelech king of the Philistines unto Gerar.'); +INSERT INTO t1(docid,words) VALUES(1026002,'And the LORD appeared unto him, and said, Go not down into Egypt; dwell in the land which I shall tell thee of:'); +INSERT INTO t1(docid,words) VALUES(1026003,'Sojourn in this land, and I will be with thee, and will bless thee; for unto thee, and unto thy seed, I will give all these countries, and I will perform the oath which I sware unto Abraham thy father;'); +INSERT INTO t1(docid,words) VALUES(1026004,'And I will make thy seed to multiply as the stars of heaven, and will give unto thy seed all these countries; and in thy seed shall all the nations of the earth be blessed;'); +INSERT INTO t1(docid,words) VALUES(1026005,'Because that Abraham obeyed my voice, and kept my charge, my commandments, my statutes, and my laws.'); +INSERT INTO t1(docid,words) VALUES(1026006,'And Isaac dwelt in Gerar:'); +INSERT INTO t1(docid,words) VALUES(1026007,'And the men of the place asked him of his wife; and he said, She is my sister: for he feared to say, She is my wife; lest, said he, the men of the place should kill me for Rebekah; because she was fair to look upon.'); +INSERT INTO t1(docid,words) VALUES(1026008,'And it came to pass, when he had been there a long time, that Abimelech king of the Philistines looked out at a window, and saw, and, behold, Isaac was sporting with Rebekah his wife.'); +INSERT INTO t1(docid,words) VALUES(1026009,'And Abimelech called Isaac, and said, Behold, of a surety she is thy wife; and how saidst thou, She is my sister? And Isaac said unto him, Because I said, Lest I die for her.'); +INSERT INTO t1(docid,words) VALUES(1026010,'And Abimelech said, What is this thou hast done unto us? one of the people might lightly have lien with thy wife, and thou shouldest have brought guiltiness upon us.'); +INSERT INTO t1(docid,words) VALUES(1026011,'And Abimelech charged all his people, saying, He that toucheth this man or his wife shall surely be put to death.'); +INSERT INTO t1(docid,words) VALUES(1026012,'Then Isaac sowed in that land, and received in the same year an hundredfold: and the LORD blessed him.'); +INSERT INTO t1(docid,words) VALUES(1026013,'And the man waxed great, and went forward, and grew until he became very great:'); +INSERT INTO t1(docid,words) VALUES(1026014,'For he had possession of flocks, and possession of herds, and great store of servants: and the Philistines envied him.'); +INSERT INTO t1(docid,words) VALUES(1026015,'For all the wells which his father''s servants had digged in the days of Abraham his father, the Philistines had stopped them, and filled them with earth.'); +INSERT INTO t1(docid,words) VALUES(1026016,'And Abimelech said unto Isaac, Go from us; for thou art much mightier than we.'); +INSERT INTO t1(docid,words) VALUES(1026017,'And Isaac departed thence, and pitched his tent in the valley of Gerar, and dwelt there.'); +INSERT INTO t1(docid,words) VALUES(1026018,'And Isaac digged again the wells of water, which they had digged in the days of Abraham his father; for the Philistines had stopped them after the death of Abraham: and he called their names after the names by which his father had called them.'); +INSERT INTO t1(docid,words) VALUES(1026019,'And Isaac''s servants digged in the valley, and found there a well of springing water.'); +INSERT INTO t1(docid,words) VALUES(1026020,'And the herdmen of Gerar did strive with Isaac''s herdmen, saying, The water is ours: and he called the name of the well Esek; because they strove with him.'); +INSERT INTO t1(docid,words) VALUES(1026021,'And they digged another well, and strove for that also: and he called the name of it Sitnah.'); +INSERT INTO t1(docid,words) VALUES(1026022,'And he removed from thence, and digged another well; and for that they strove not: and he called the name of it Rehoboth; and he said, For now the LORD hath made room for us, and we shall be fruitful in the land.'); +INSERT INTO t1(docid,words) VALUES(1026023,'And he went up from thence to Beersheba.'); +INSERT INTO t1(docid,words) VALUES(1026024,'And the LORD appeared unto him the same night, and said, I am the God of Abraham thy father: fear not, for I am with thee, and will bless thee, and multiply thy seed for my servant Abraham''s sake.'); +INSERT INTO t1(docid,words) VALUES(1026025,'And he builded an altar there, and called upon the name of the LORD, and pitched his tent there: and there Isaac''s servants digged a well.'); +INSERT INTO t1(docid,words) VALUES(1026026,'Then Abimelech went to him from Gerar, and Ahuzzath one of his friends, and Phichol the chief captain of his army.'); +INSERT INTO t1(docid,words) VALUES(1026027,'And Isaac said unto them, Wherefore come ye to me, seeing ye hate me, and have sent me away from you?'); +INSERT INTO t1(docid,words) VALUES(1026028,'And they said, We saw certainly that the LORD was with thee: and we said, Let there be now an oath betwixt us, even betwixt us and thee, and let us make a covenant with thee;'); +INSERT INTO t1(docid,words) VALUES(1026029,'That thou wilt do us no hurt, as we have not touched thee, and as we have done unto thee nothing but good, and have sent thee away in peace: thou art now the blessed of the LORD.'); +INSERT INTO t1(docid,words) VALUES(1026030,'And he made them a feast, and they did eat and drink.'); +INSERT INTO t1(docid,words) VALUES(1026031,'And they rose up betimes in the morning, and sware one to another: and Isaac sent them away, and they departed from him in peace.'); +INSERT INTO t1(docid,words) VALUES(1026032,'And it came to pass the same day, that Isaac''s servants came, and told him concerning the well which they had digged, and said unto him, We have found water.'); +INSERT INTO t1(docid,words) VALUES(1026033,'And he called it Shebah: therefore the name of the city is Beersheba unto this day.'); +INSERT INTO t1(docid,words) VALUES(1026034,'And Esau was forty years old when he took to wife Judith the daughter of Beeri the Hittite, and Bashemath the daughter of Elon the Hittite:'); +INSERT INTO t1(docid,words) VALUES(1026035,'Which were a grief of mind unto Isaac and to Rebekah.'); +INSERT INTO t1(docid,words) VALUES(1027001,'And it came to pass, that when Isaac was old, and his eyes were dim, so that he could not see, he called Esau his eldest son, and said unto him, My son: and he said unto him, Behold, here am I.'); +INSERT INTO t1(docid,words) VALUES(1027002,'And he said, Behold now, I am old, I know not the day of my death:'); +INSERT INTO t1(docid,words) VALUES(1027003,'Now therefore take, I pray thee, thy weapons, thy quiver and thy bow, and go out to the field, and take me some venison;'); +INSERT INTO t1(docid,words) VALUES(1027004,'And make me savoury meat, such as I love, and bring it to me, that I may eat; that my soul may bless thee before I die.'); +INSERT INTO t1(docid,words) VALUES(1027005,'And Rebekah heard when Isaac spake to Esau his son. And Esau went to the field to hunt for venison, and to bring it.'); +INSERT INTO t1(docid,words) VALUES(1027006,'And Rebekah spake unto Jacob her son, saying, Behold, I heard thy father speak unto Esau thy brother, saying,'); +INSERT INTO t1(docid,words) VALUES(1027007,'Bring me venison, and make me savoury meat, that I may eat, and bless thee before the LORD before my death.'); +INSERT INTO t1(docid,words) VALUES(1027008,'Now therefore, my son, obey my voice according to that which I command thee.'); +INSERT INTO t1(docid,words) VALUES(1027009,'Go now to the flock, and fetch me from thence two good kids of the goats; and I will make them savoury meat for thy father, such as he loveth:'); +INSERT INTO t1(docid,words) VALUES(1027010,'And thou shalt bring it to thy father, that he may eat, and that he may bless thee before his death.'); +INSERT INTO t1(docid,words) VALUES(1027011,'And Jacob said to Rebekah his mother, Behold, Esau my brother is a hairy man, and I am a smooth man:'); +INSERT INTO t1(docid,words) VALUES(1027012,'My father peradventure will feel me, and I shall seem to him as a deceiver; and I shall bring a curse upon me, and not a blessing.'); +INSERT INTO t1(docid,words) VALUES(1027013,'And his mother said unto him, Upon me be thy curse, my son: only obey my voice, and go fetch me them.'); +INSERT INTO t1(docid,words) VALUES(1027014,'And he went, and fetched, and brought them to his mother: and his mother made savoury meat, such as his father loved.'); +INSERT INTO t1(docid,words) VALUES(1027015,'And Rebekah took goodly raiment of her eldest son Esau, which were with her in the house, and put them upon Jacob her younger son:'); +INSERT INTO t1(docid,words) VALUES(1027016,'And she put the skins of the kids of the goats upon his hands, and upon the smooth of his neck:'); +INSERT INTO t1(docid,words) VALUES(1027017,'And she gave the savoury meat and the bread, which she had prepared, into the hand of her son Jacob.'); +INSERT INTO t1(docid,words) VALUES(1027018,'And he came unto his father, and said, My father: and he said, Here am I; who art thou, my son?'); +INSERT INTO t1(docid,words) VALUES(1027019,'And Jacob said unto his father, I am Esau thy first born; I have done according as thou badest me: arise, I pray thee, sit and eat of my venison, that thy soul may bless me.'); +INSERT INTO t1(docid,words) VALUES(1027020,'And Isaac said unto his son, How is it that thou hast found it so quickly, my son? And he said, Because the LORD thy God brought it to me.'); +INSERT INTO t1(docid,words) VALUES(1027021,'And Isaac said unto Jacob, Come near, I pray thee, that I may feel thee, my son, whether thou be my very son Esau or not.'); +INSERT INTO t1(docid,words) VALUES(1027022,'And Jacob went near unto Isaac his father; and he felt him, and said, The voice is Jacob''s voice, but the hands are the hands of Esau.'); +INSERT INTO t1(docid,words) VALUES(1027023,'And he discerned him not, because his hands were hairy, as his brother Esau''s hands: so he blessed him.'); +INSERT INTO t1(docid,words) VALUES(1027024,'And he said, Art thou my very son Esau? And he said, I am.'); +INSERT INTO t1(docid,words) VALUES(1027025,'And he said, Bring it near to me, and I will eat of my son''s venison, that my soul may bless thee. And he brought it near to him, and he did eat: and he brought him wine and he drank.'); +INSERT INTO t1(docid,words) VALUES(1027026,'And his father Isaac said unto him, Come near now, and kiss me, my son.'); +INSERT INTO t1(docid,words) VALUES(1027027,'And he came near, and kissed him: and he smelled the smell of his raiment, and blessed him, and said, See, the smell of my son is as the smell of a field which the LORD hath blessed:'); +INSERT INTO t1(docid,words) VALUES(1027028,'Therefore God give thee of the dew of heaven, and the fatness of the earth, and plenty of corn and wine:'); +INSERT INTO t1(docid,words) VALUES(1027029,'Let people serve thee, and nations bow down to thee: be lord over thy brethren, and let thy mother''s sons bow down to thee: cursed be every one that curseth thee, and blessed be he that blesseth thee.'); +INSERT INTO t1(docid,words) VALUES(1027030,'And it came to pass, as soon as Isaac had made an end of blessing Jacob, and Jacob was yet scarce gone out from the presence of Isaac his father, that Esau his brother came in from his hunting.'); +INSERT INTO t1(docid,words) VALUES(1027031,'And he also had made savoury meat, and brought it unto his father, and said unto his father, Let my father arise, and eat of his son''s venison, that thy soul may bless me.'); +INSERT INTO t1(docid,words) VALUES(1027032,'And Isaac his father said unto him, Who art thou? And he said, I am thy son, thy firstborn Esau.'); +INSERT INTO t1(docid,words) VALUES(1027033,'And Isaac trembled very exceedingly, and said, Who? where is he that hath taken venison, and brought it me, and I have eaten of all before thou camest, and have blessed him? yea, and he shall be blessed.'); +INSERT INTO t1(docid,words) VALUES(1027034,'And when Esau heard the words of his father, he cried with a great and exceeding bitter cry, and said unto his father, Bless me, even me also, O my father.'); +INSERT INTO t1(docid,words) VALUES(1027035,'And he said, Thy brother came with subtilty, and hath taken away thy blessing.'); +INSERT INTO t1(docid,words) VALUES(1027036,'And he said, Is not he rightly named Jacob? for he hath supplanted me these two times: he took away my birthright; and, behold, now he hath taken away my blessing. And he said, Hast thou not reserved a blessing for me?'); +INSERT INTO t1(docid,words) VALUES(1027037,'And Isaac answered and said unto Esau, Behold, I have made him thy lord, and all his brethren have I given to him for servants; and with corn and wine have I sustained him: and what shall I do now unto thee, my son?'); +INSERT INTO t1(docid,words) VALUES(1027038,'And Esau said unto his father, Hast thou but one blessing, my father? bless me, even me also, O my father. And Esau lifted up his voice, and wept.'); +INSERT INTO t1(docid,words) VALUES(1027039,'And Isaac his father answered and said unto him, Behold, thy dwelling shall be the fatness of the earth, and of the dew of heaven from above;'); +INSERT INTO t1(docid,words) VALUES(1027040,'And by thy sword shalt thou live, and shalt serve thy brother; and it shall come to pass when thou shalt have the dominion, that thou shalt break his yoke from off thy neck.'); +INSERT INTO t1(docid,words) VALUES(1027041,'And Esau hated Jacob because of the blessing wherewith his father blessed him: and Esau said in his heart, The days of mourning for my father are at hand; then will I slay my brother Jacob.'); +INSERT INTO t1(docid,words) VALUES(1027042,'And these words of Esau her elder son were told to Rebekah: and she sent and called Jacob her younger son, and said unto him, Behold, thy brother Esau, as touching thee, doth comfort himself, purposing to kill thee.'); +INSERT INTO t1(docid,words) VALUES(1027043,'Now therefore, my son, obey my voice; arise, flee thou to Laban my brother to Haran;'); +INSERT INTO t1(docid,words) VALUES(1027044,'And tarry with him a few days, until thy brother''s fury turn away;'); +INSERT INTO t1(docid,words) VALUES(1027045,'Until thy brother''s anger turn away from thee, and he forget that which thou hast done to him: then I will send, and fetch thee from thence: why should I be deprived also of you both in one day?'); +INSERT INTO t1(docid,words) VALUES(1027046,'And Rebekah said to Isaac, I am weary of my life because of the daughters of Heth: if Jacob take a wife of the daughters of Heth, such as these which are of the daughters of the land, what good shall my life do me?'); +INSERT INTO t1(docid,words) VALUES(1028001,'And Isaac called Jacob, and blessed him, and charged him, and said unto him, Thou shalt not take a wife of the daughters of Canaan.'); +INSERT INTO t1(docid,words) VALUES(1028002,'Arise, go to Padanaram, to the house of Bethuel thy mother''s father; and take thee a wife from thence of the daughers of Laban thy mother''s brother.'); +INSERT INTO t1(docid,words) VALUES(1028003,'And God Almighty bless thee, and make thee fruitful, and multiply thee, that thou mayest be a multitude of people;'); +INSERT INTO t1(docid,words) VALUES(1028004,'And give thee the blessing of Abraham, to thee, and to thy seed with thee; that thou mayest inherit the land wherein thou art a stranger, which God gave unto Abraham.'); +INSERT INTO t1(docid,words) VALUES(1028005,'And Isaac sent away Jacob: and he went to Padanaram unto Laban, son of Bethuel the Syrian, the brother of Rebekah, Jacob''s and Esau''s mother.'); +INSERT INTO t1(docid,words) VALUES(1028006,'When Esau saw that Isaac had blessed Jacob, and sent him away to Padanaram, to take him a wife from thence; and that as he blessed him he gave him a charge, saying, Thou shalt not take a wife of the daughers of Canaan;'); +INSERT INTO t1(docid,words) VALUES(1028007,'And that Jacob obeyed his father and his mother, and was gone to Padanaram;'); +INSERT INTO t1(docid,words) VALUES(1028008,'And Esau seeing that the daughters of Canaan pleased not Isaac his father;'); +INSERT INTO t1(docid,words) VALUES(1028009,'Then went Esau unto Ishmael, and took unto the wives which he had Mahalath the daughter of Ishmael Abraham''s son, the sister of Nebajoth, to be his wife.'); +INSERT INTO t1(docid,words) VALUES(1028010,'And Jacob went out from Beersheba, and went toward Haran.'); +INSERT INTO t1(docid,words) VALUES(1028011,'And he lighted upon a certain place, and tarried there all night, because the sun was set; and he took of the stones of that place, and put them for his pillows, and lay down in that place to sleep.'); +INSERT INTO t1(docid,words) VALUES(1028012,'And he dreamed, and behold a ladder set up on the earth, and the top of it reached to heaven: and behold the angels of God ascending and descending on it.'); +INSERT INTO t1(docid,words) VALUES(1028013,'And, behold, the LORD stood above it, and said, I am the LORD God of Abraham thy father, and the God of Isaac: the land whereon thou liest, to thee will I give it, and to thy seed;'); +INSERT INTO t1(docid,words) VALUES(1028014,'And thy seed shall be as the dust of the earth, and thou shalt spread abroad to the west, and to the east, and to the north, and to the south: and in thee and in thy seed shall all the families of the earth be blessed.'); +INSERT INTO t1(docid,words) VALUES(1028015,'And, behold, I am with thee, and will keep thee in all places whither thou goest, and will bring thee again into this land; for I will not leave thee, until I have done that which I have spoken to thee of.'); +INSERT INTO t1(docid,words) VALUES(1028016,'And Jacob awaked out of his sleep, and he said, Surely the LORD is in this place; and I knew it not.'); +INSERT INTO t1(docid,words) VALUES(1028017,'And he was afraid, and said, How dreadful is this place! this is none other but the house of God, and this is the gate of heaven.'); +INSERT INTO t1(docid,words) VALUES(1028018,'And Jacob rose up early in the morning, and took the stone that he had put for his pillows, and set it up for a pillar, and poured oil upon the top of it.'); +INSERT INTO t1(docid,words) VALUES(1028019,'And he called the name of that place Bethel: but the name of that city was called Luz at the first.'); +INSERT INTO t1(docid,words) VALUES(1028020,'And Jacob vowed a vow, saying, If God will be with me, and will keep me in this way that I go, and will give me bread to eat, and raiment to put on,'); +INSERT INTO t1(docid,words) VALUES(1028021,'So that I come again to my father''s house in peace; then shall the LORD be my God:'); +INSERT INTO t1(docid,words) VALUES(1028022,'And this stone, which I have set for a pillar, shall be God''s house: and of all that thou shalt give me I will surely give the tenth unto thee.'); +INSERT INTO t1(docid,words) VALUES(1029001,'Then Jacob went on his journey, and came into the land of the people of the east.'); +INSERT INTO t1(docid,words) VALUES(1029002,'And he looked, and behold a well in the field, and, lo, there were three flocks of sheep lying by it; for out of that well they watered the flocks: and a great stone was upon the well''s mouth.'); +INSERT INTO t1(docid,words) VALUES(1029003,'And thither were all the flocks gathered: and they rolled the stone from the well''s mouth, and watered the sheep, and put the stone again upon the well''s mouth in his place.'); +INSERT INTO t1(docid,words) VALUES(1029004,'And Jacob said unto them, My brethren, whence be ye? And they said, Of Haran are we.'); +INSERT INTO t1(docid,words) VALUES(1029005,'And he said unto them, Know ye Laban the son of Nahor? And they said, We know him.'); +INSERT INTO t1(docid,words) VALUES(1029006,'And he said unto them, Is he well? And they said, He is well: and, behold, Rachel his daughter cometh with the sheep.'); +INSERT INTO t1(docid,words) VALUES(1029007,'And he said, Lo, it is yet high day, neither is it time that the cattle should be gathered together: water ye the sheep, and go and feed them.'); +INSERT INTO t1(docid,words) VALUES(1029008,'And they said, We cannot, until all the flocks be gathered together, and till they roll the stone from the well''s mouth; then we water the sheep.'); +INSERT INTO t1(docid,words) VALUES(1029009,'And while he yet spake with them, Rachel came with her father''s sheep; for she kept them.'); +INSERT INTO t1(docid,words) VALUES(1029010,'And it came to pass, when Jacob saw Rachel the daughter of Laban his mother''s brother, and the sheep of Laban his mother''s brother, that Jacob went near, and rolled the stone from the well''s mouth, and watered the flock of Laban his mother''s brother.'); +INSERT INTO t1(docid,words) VALUES(1029011,'And Jacob kissed Rachel, and lifted up his voice, and wept.'); +INSERT INTO t1(docid,words) VALUES(1029012,'And Jacob told Rachel that he was her father''s brother, and that he was Rebekah''s son: and she ran and told her father.'); +INSERT INTO t1(docid,words) VALUES(1029013,'And it came to pass, when Laban heard the tidings of Jacob his sister''s son, that he ran to meet him, and embraced him, and kissed him, and brought him to his house. And he told Laban all these things.'); +INSERT INTO t1(docid,words) VALUES(1029014,'And Laban said to him, Surely thou art my bone and my flesh. And he abode with him the space of a month.'); +INSERT INTO t1(docid,words) VALUES(1029015,'And Laban said unto Jacob, Because thou art my brother, shouldest thou therefore serve me for nought? tell me, what shall thy wages be?'); +INSERT INTO t1(docid,words) VALUES(1029016,'And Laban had two daughters: the name of the elder was Leah, and the name of the younger was Rachel.'); +INSERT INTO t1(docid,words) VALUES(1029017,'Leah was tender eyed; but Rachel was beautiful and well favoured.'); +INSERT INTO t1(docid,words) VALUES(1029018,'And Jacob loved Rachel; and said, I will serve thee seven years for Rachel thy younger daughter.'); +INSERT INTO t1(docid,words) VALUES(1029019,'And Laban said, It is better that I give her to thee, than that I should give her to another man: abide with me.'); +INSERT INTO t1(docid,words) VALUES(1029020,'And Jacob served seven years for Rachel; and they seemed unto him but a few days, for the love he had to her.'); +INSERT INTO t1(docid,words) VALUES(1029021,'And Jacob said unto Laban, Give me my wife, for my days are fulfilled, that I may go in unto her.'); +INSERT INTO t1(docid,words) VALUES(1029022,'And Laban gathered together all the men of the place, and made a feast.'); +INSERT INTO t1(docid,words) VALUES(1029023,'And it came to pass in the evening, that he took Leah his daughter, and brought her to him; and he went in unto her.'); +INSERT INTO t1(docid,words) VALUES(1029024,'And Laban gave unto his daughter Leah Zilpah his maid for an handmaid.'); +INSERT INTO t1(docid,words) VALUES(1029025,'And it came to pass, that in the morning, behold, it was Leah: and he said to Laban, What is this thou hast done unto me? did not I serve with thee for Rachel? wherefore then hast thou beguiled me?'); +INSERT INTO t1(docid,words) VALUES(1029026,'And Laban said, It must not be so done in our country, to give the younger before the firstborn.'); +INSERT INTO t1(docid,words) VALUES(1029027,'Fulfil her week, and we will give thee this also for the service which thou shalt serve with me yet seven other years.'); +INSERT INTO t1(docid,words) VALUES(1029028,'And Jacob did so, and fulfilled her week: and he gave him Rachel his daughter to wife also.'); +INSERT INTO t1(docid,words) VALUES(1029029,'And Laban gave to Rachel his daughter Bilhah his handmaid to be her maid.'); +INSERT INTO t1(docid,words) VALUES(1029030,'And he went in also unto Rachel, and he loved also Rachel more than Leah, and served with him yet seven other years.'); +INSERT INTO t1(docid,words) VALUES(1029031,'And when the LORD saw that Leah was hated, he opened her womb: but Rachel was barren.'); +INSERT INTO t1(docid,words) VALUES(1029032,'And Leah conceived, and bare a son, and she called his name Reuben: for she said, Surely the LORD hath looked upon my affliction; now therefore my husband will love me.'); +INSERT INTO t1(docid,words) VALUES(1029033,'And she conceived again, and bare a son; and said, Because the LORD hath heard I was hated, he hath therefore given me this son also: and she called his name Simeon.'); +INSERT INTO t1(docid,words) VALUES(1029034,'And she conceived again, and bare a son; and said, Now this time will my husband be joined unto me, because I have born him three sons: therefore was his name called Levi.'); +INSERT INTO t1(docid,words) VALUES(1029035,'And she conceived again, and bare a son: and she said, Now will I praise the LORD: therefore she called his name Judah; and left bearing.'); +INSERT INTO t1(docid,words) VALUES(1030001,'And when Rachel saw that she bare Jacob no children, Rachel envied her sister; and said unto Jacob, Give me children, or else I die.'); +INSERT INTO t1(docid,words) VALUES(1030002,'And Jacob''s anger was kindled against Rachel: and he said, Am I in God''s stead, who hath withheld from thee the fruit of the womb?'); +INSERT INTO t1(docid,words) VALUES(1030003,'And she said, Behold my maid Bilhah, go in unto her; and she shall bear upon my knees, that I may also have children by her.'); +INSERT INTO t1(docid,words) VALUES(1030004,'And she gave him Bilhah her handmaid to wife: and Jacob went in unto her.'); +INSERT INTO t1(docid,words) VALUES(1030005,'And Bilhah conceived, and bare Jacob a son.'); +INSERT INTO t1(docid,words) VALUES(1030006,'And Rachel said, God hath judged me, and hath also heard my voice, and hath given me a son: therefore called she his name Dan.'); +INSERT INTO t1(docid,words) VALUES(1030007,'And Bilhah Rachel''s maid conceived again, and bare Jacob a second son.'); +INSERT INTO t1(docid,words) VALUES(1030008,'And Rachel said, With great wrestlings have I wrestled with my sister, and I have prevailed: and she called his name Naphtali.'); +INSERT INTO t1(docid,words) VALUES(1030009,'When Leah saw that she had left bearing, she took Zilpah her maid, and gave her Jacob to wife.'); +INSERT INTO t1(docid,words) VALUES(1030010,'And Zilpah Leah''s maid bare Jacob a son.'); +INSERT INTO t1(docid,words) VALUES(1030011,'And Leah said, A troop cometh: and she called his name Gad.'); +INSERT INTO t1(docid,words) VALUES(1030012,'And Zilpah Leah''s maid bare Jacob a second son.'); +INSERT INTO t1(docid,words) VALUES(1030013,'And Leah said, Happy am I, for the daughters will call me blessed: and she called his name Asher.'); +INSERT INTO t1(docid,words) VALUES(1030014,'And Reuben went in the days of wheat harvest, and found mandrakes in the field, and brought them unto his mother Leah. Then Rachel said to Leah, Give me, I pray thee, of thy son''s mandrakes.'); +INSERT INTO t1(docid,words) VALUES(1030015,'And she said unto her, Is it a small matter that thou hast taken my husband? and wouldest thou take away my son''s mandrakes also? And Rachel said, Therefore he shall lie with thee to night for thy son''s mandrakes.'); +INSERT INTO t1(docid,words) VALUES(1030016,'And Jacob came out of the field in the evening, and Leah went out to meet him, and said, Thou must come in unto me; for surely I have hired thee with my son''s mandrakes. And he lay with her that night.'); +INSERT INTO t1(docid,words) VALUES(1030017,'And God hearkened unto Leah, and she conceived, and bare Jacob the fifth son.'); +INSERT INTO t1(docid,words) VALUES(1030018,'And Leah said, God hath given me my hire, because I have given my maiden to my husband: and she called his name Issachar.'); +INSERT INTO t1(docid,words) VALUES(1030019,'And Leah conceived again, and bare Jacob the sixth son.'); +INSERT INTO t1(docid,words) VALUES(1030020,'And Leah said, God hath endued me with a good dowry; now will my husband dwell with me, because I have born him six sons: and she called his name Zebulun.'); +INSERT INTO t1(docid,words) VALUES(1030021,'And afterwards she bare a daughter, and called her name Dinah.'); +INSERT INTO t1(docid,words) VALUES(1030022,'And God remembered Rachel, and God hearkened to her, and opened her womb.'); +INSERT INTO t1(docid,words) VALUES(1030023,'And she conceived, and bare a son; and said, God hath taken away my reproach:'); +INSERT INTO t1(docid,words) VALUES(1030024,'And she called his name Joseph; and said, The LORD shall add to me another son.'); +INSERT INTO t1(docid,words) VALUES(1030025,'And it came to pass, when Rachel had born Joseph, that Jacob said unto Laban, Send me away, that I may go unto mine own place, and to my country.'); +INSERT INTO t1(docid,words) VALUES(1030026,'Give me my wives and my children, for whom I have served thee, and let me go: for thou knowest my service which I have done thee.'); +INSERT INTO t1(docid,words) VALUES(1030027,'And Laban said unto him, I pray thee, if I have found favour in thine eyes, tarry: for I have learned by experience that the LORD hath blessed me for thy sake.'); +INSERT INTO t1(docid,words) VALUES(1030028,'And he said, Appoint me thy wages, and I will give it.'); +INSERT INTO t1(docid,words) VALUES(1030029,'And he said unto him, Thou knowest how I have served thee, and how thy cattle was with me.'); +INSERT INTO t1(docid,words) VALUES(1030030,'For it was little which thou hadst before I came, and it is now increased unto a multitude; and the LORD hath blessed thee since my coming: and now when shall I provide for mine own house also?'); +INSERT INTO t1(docid,words) VALUES(1030031,'And he said, What shall I give thee? And Jacob said, Thou shalt not give me any thing: if thou wilt do this thing for me, I will again feed and keep thy flock.'); +INSERT INTO t1(docid,words) VALUES(1030032,'I will pass through all thy flock to day, removing from thence all the speckled and spotted cattle, and all the brown cattle among the sheep, and the spotted and speckled among the goats: and of such shall be my hire.'); +INSERT INTO t1(docid,words) VALUES(1030033,'So shall my righteousness answer for me in time to come, when it shall come for my hire before thy face: every one that is not speckled and spotted among the goats, and brown among the sheep, that shall be counted stolen with me.'); +INSERT INTO t1(docid,words) VALUES(1030034,'And Laban said, Behold, I would it might be according to thy word.'); +INSERT INTO t1(docid,words) VALUES(1030035,'And he removed that day the he goats that were ringstraked and spotted, and all the she goats that were speckled and spotted, and every one that had some white in it, and all the brown among the sheep, and gave them into the hand of his sons.'); +INSERT INTO t1(docid,words) VALUES(1030036,'And he set three days'' journey betwixt himself and Jacob: and Jacob fed the rest of Laban''s flocks.'); +INSERT INTO t1(docid,words) VALUES(1030037,'And Jacob took him rods of green poplar, and of the hazel and chesnut tree; and pilled white strakes in them, and made the white appear which was in the rods.'); +INSERT INTO t1(docid,words) VALUES(1030038,'And he set the rods which he had pilled before the flocks in the gutters in the watering troughs when the flocks came to drink, that they should conceive when they came to drink.'); +INSERT INTO t1(docid,words) VALUES(1030039,'And the flocks conceived before the rods, and brought forth cattle ringstraked, speckled, and spotted.'); +INSERT INTO t1(docid,words) VALUES(1030040,'And Jacob did separate the lambs, and set the faces of the flocks toward the ringstraked, and all the brown in the flock of Laban; and he put his own flocks by themselves, and put them not unto Laban''s cattle.'); +INSERT INTO t1(docid,words) VALUES(1030041,'And it came to pass, whensoever the stronger cattle did conceive, that Jacob laid the rods before the eyes of the cattle in the gutters, that they might conceive among the rods.'); +INSERT INTO t1(docid,words) VALUES(1030042,'But when the cattle were feeble, he put them not in: so the feebler were Laban''s, and the stronger Jacob''s.'); +INSERT INTO t1(docid,words) VALUES(1030043,'And the man increased exceedingly, and had much cattle, and maidservants, and menservants, and camels, and asses.'); +INSERT INTO t1(docid,words) VALUES(1031001,'And he heard the words of Laban''s sons, saying, Jacob hath taken away all that was our father''s; and of that which was our father''s hath he gotten all this glory.'); +INSERT INTO t1(docid,words) VALUES(1031002,'And Jacob beheld the countenance of Laban, and, behold, it was not toward him as before.'); +INSERT INTO t1(docid,words) VALUES(1031003,'And the LORD said unto Jacob, Return unto the land of thy fathers, and to thy kindred; and I will be with thee.'); +INSERT INTO t1(docid,words) VALUES(1031004,'And Jacob sent and called Rachel and Leah to the field unto his flock,'); +INSERT INTO t1(docid,words) VALUES(1031005,'And said unto them, I see your father''s countenance, that it is not toward me as before; but the God of my father hath been with me.'); +INSERT INTO t1(docid,words) VALUES(1031006,'And ye know that with all my power I have served your father.'); +INSERT INTO t1(docid,words) VALUES(1031007,'And your father hath deceived me, and changed my wages ten times; but God suffered him not to hurt me.'); +INSERT INTO t1(docid,words) VALUES(1031008,'If he said thus, The speckled shall be thy wages; then all the cattle bare speckled: and if he said thus, The ringstraked shall be thy hire; then bare all the cattle ringstraked.'); +INSERT INTO t1(docid,words) VALUES(1031009,'Thus God hath taken away the cattle of your father, and given them to me.'); +INSERT INTO t1(docid,words) VALUES(1031010,'And it came to pass at the time that the cattle conceived, that I lifted up mine eyes, and saw in a dream, and, behold, the rams which leaped upon the cattle were ringstraked, speckled, and grisled.'); +INSERT INTO t1(docid,words) VALUES(1031011,'And the angel of God spake unto me in a dream, saying, Jacob: And I said, Here am I.'); +INSERT INTO t1(docid,words) VALUES(1031012,'And he said, Lift up now thine eyes, and see, all the rams which leap upon the cattle are ringstraked, speckled, and grisled: for I have seen all that Laban doeth unto thee.'); +INSERT INTO t1(docid,words) VALUES(1031013,'I am the God of Bethel, where thou anointedst the pillar, and where thou vowedst a vow unto me: now arise, get thee out from this land, and return unto the land of thy kindred.'); +INSERT INTO t1(docid,words) VALUES(1031014,'And Rachel and Leah answered and said unto him, Is there yet any portion or inheritance for us in our father''s house?'); +INSERT INTO t1(docid,words) VALUES(1031015,'Are we not counted of him strangers? for he hath sold us, and hath quite devoured also our money.'); +INSERT INTO t1(docid,words) VALUES(1031016,'For all the riches which God hath taken from our father, that is ours, and our children''s: now then, whatsoever God hath said unto thee, do.'); +INSERT INTO t1(docid,words) VALUES(1031017,'Then Jacob rose up, and set his sons and his wives upon camels;'); +INSERT INTO t1(docid,words) VALUES(1031018,'And he carried away all his cattle, and all his goods which he had gotten, the cattle of his getting, which he had gotten in Padanaram, for to go to Isaac his father in the land of Canaan.'); +INSERT INTO t1(docid,words) VALUES(1031019,'And Laban went to shear his sheep: and Rachel had stolen the images that were her father''s.'); +INSERT INTO t1(docid,words) VALUES(1031020,'And Jacob stole away unawares to Laban the Syrian, in that he told him not that he fled.'); +INSERT INTO t1(docid,words) VALUES(1031021,'So he fled with all that he had; and he rose up, and passed over the river, and set his face toward the mount Gilead.'); +INSERT INTO t1(docid,words) VALUES(1031022,'And it was told Laban on the third day that Jacob was fled.'); +INSERT INTO t1(docid,words) VALUES(1031023,'And he took his brethren with him, and pursued after him seven days'' journey; and they overtook him in the mount Gilead.'); +INSERT INTO t1(docid,words) VALUES(1031024,'And God came to Laban the Syrian in a dream by night, and said unto him, Take heed that thou speak not to Jacob either good or bad.'); +INSERT INTO t1(docid,words) VALUES(1031025,'Then Laban overtook Jacob. Now Jacob had pitched his tent in the mount: and Laban with his brethren pitched in the mount of Gilead.'); +INSERT INTO t1(docid,words) VALUES(1031026,'And Laban said to Jacob, What hast thou done, that thou hast stolen away unawares to me, and carried away my daughters, as captives taken with the sword?'); +INSERT INTO t1(docid,words) VALUES(1031027,'Wherefore didst thou flee away secretly, and steal away from me; and didst not tell me, that I might have sent thee away with mirth, and with songs, with tabret, and with harp?'); +INSERT INTO t1(docid,words) VALUES(1031028,'And hast not suffered me to kiss my sons and my daughters? thou hast now done foolishly in so doing.'); +INSERT INTO t1(docid,words) VALUES(1031029,'It is in the power of my hand to do you hurt: but the God of your father spake unto me yesternight, saying, Take thou heed that thou speak not to Jacob either good or bad.'); +INSERT INTO t1(docid,words) VALUES(1031030,'And now, though thou wouldest needs be gone, because thou sore longedst after thy father''s house, yet wherefore hast thou stolen my gods?'); +INSERT INTO t1(docid,words) VALUES(1031031,'And Jacob answered and said to Laban, Because I was afraid: for I said, Peradventure thou wouldest take by force thy daughters from me.'); +INSERT INTO t1(docid,words) VALUES(1031032,'With whomsoever thou findest thy gods, let him not live: before our brethren discern thou what is thine with me, and take it to thee. For Jacob knew not that Rachel had stolen them.'); +INSERT INTO t1(docid,words) VALUES(1031033,'And Laban went into Jacob''s tent, and into Leah''s tent, and into the two maidservants'' tents; but he found them not. Then went he out of Leah''s tent, and entered into Rachel''s tent.'); +INSERT INTO t1(docid,words) VALUES(1031034,'Now Rachel had taken the images, and put them in the camel''s furniture, and sat upon them. And Laban searched all the tent, but found them not.'); +INSERT INTO t1(docid,words) VALUES(1031035,'And she said to her father, Let it not displease my lord that I cannot rise up before thee; for the custom of women is upon me. And he searched but found not the images.'); +INSERT INTO t1(docid,words) VALUES(1031036,'And Jacob was wroth, and chode with Laban: and Jacob answered and said to Laban, What is my trespass? what is my sin, that thou hast so hotly pursued after me?'); +INSERT INTO t1(docid,words) VALUES(1031037,'Whereas thou hast searched all my stuff, what hast thou found of all thy household stuff? set it here before my brethren and thy brethren, that they may judge betwixt us both.'); +INSERT INTO t1(docid,words) VALUES(1031038,'This twenty years have I been with thee; thy ewes and thy she goats have not cast their young, and the rams of thy flock have I not eaten.'); +INSERT INTO t1(docid,words) VALUES(1031039,'That which was torn of beasts I brought not unto thee; I bare the loss of it; of my hand didst thou require it, whether stolen by day, or stolen by night.'); +INSERT INTO t1(docid,words) VALUES(1031040,'Thus I was; in the day the drought consumed me, and the frost by night; and my sleep departed from mine eyes.'); +INSERT INTO t1(docid,words) VALUES(1031041,'Thus have I been twenty years in thy house; I served thee fourteen years for thy two daughters, and six years for thy cattle: and thou hast changed my wages ten times.'); +INSERT INTO t1(docid,words) VALUES(1031042,'Except the God of my father, the God of Abraham, and the fear of Isaac, had been with me, surely thou hadst sent me away now empty. God hath seen mine affliction and the labour of my hands, and rebuked thee yesternight.'); +INSERT INTO t1(docid,words) VALUES(1031043,'And Laban answered and said unto Jacob, These daughters are my daughters, and these children are my children, and these cattle are my cattle, and all that thou seest is mine: and what can I do this day unto these my daughters, or unto their children which they have born?'); +INSERT INTO t1(docid,words) VALUES(1031044,'Now therefore come thou, let us make a covenant, I and thou; and let it be for a witness between me and thee.'); +INSERT INTO t1(docid,words) VALUES(1031045,'And Jacob took a stone, and set it up for a pillar.'); +INSERT INTO t1(docid,words) VALUES(1031046,'And Jacob said unto his brethren, Gather stones; and they took stones, and made an heap: and they did eat there upon the heap.'); +INSERT INTO t1(docid,words) VALUES(1031047,'And Laban called it Jegarsahadutha: but Jacob called it Galeed.'); +INSERT INTO t1(docid,words) VALUES(1031048,'And Laban said, This heap is a witness between me and thee this day. Therefore was the name of it called Galeed;'); +INSERT INTO t1(docid,words) VALUES(1031049,'And Mizpah; for he said, The LORD watch between me and thee, when we are absent one from another.'); +INSERT INTO t1(docid,words) VALUES(1031050,'If thou shalt afflict my daughters, or if thou shalt take other wives beside my daughters, no man is with us; see, God is witness betwixt me and thee.'); +INSERT INTO t1(docid,words) VALUES(1031051,'And Laban said to Jacob, Behold this heap, and behold this pillar, which I have cast betwixt me and thee:'); +INSERT INTO t1(docid,words) VALUES(1031052,'This heap be witness, and this pillar be witness, that I will not pass over this heap to thee, and that thou shalt not pass over this heap and this pillar unto me, for harm.'); +INSERT INTO t1(docid,words) VALUES(1031053,'The God of Abraham, and the God of Nahor, the God of their father, judge betwixt us. And Jacob sware by the fear of his father Isaac.'); +INSERT INTO t1(docid,words) VALUES(1031054,'Then Jacob offered sacrifice upon the mount, and called his brethren to eat bread: and they did eat bread, and tarried all night in the mount.'); +INSERT INTO t1(docid,words) VALUES(1031055,'And early in the morning Laban rose up, and kissed his sons and his daughters, and blessed them: and Laban departed, and returned unto his place.'); +INSERT INTO t1(docid,words) VALUES(1032001,'And Jacob went on his way, and the angels of God met him.'); +INSERT INTO t1(docid,words) VALUES(1032002,'And when Jacob saw them, he said, This is God''s host: and he called the name of that place Mahanaim.'); +INSERT INTO t1(docid,words) VALUES(1032003,'And Jacob sent messengers before him to Esau his brother unto the land of Seir, the country of Edom.'); +INSERT INTO t1(docid,words) VALUES(1032004,'And he commanded them, saying, Thus shall ye speak unto my lord Esau; Thy servant Jacob saith thus, I have sojourned with Laban, and stayed there until now:'); +INSERT INTO t1(docid,words) VALUES(1032005,'And I have oxen, and asses, flocks, and menservants, and womenservants: and I have sent to tell my lord, that I may find grace in thy sight.'); +INSERT INTO t1(docid,words) VALUES(1032006,'And the messengers returned to Jacob, saying, We came to thy brother Esau, and also he cometh to meet thee, and four hundred men with him.'); +INSERT INTO t1(docid,words) VALUES(1032007,'Then Jacob was greatly afraid and distressed: and he divided the people that was with him, and the flocks, and herds, and the camels, into two bands;'); +INSERT INTO t1(docid,words) VALUES(1032008,'And said, If Esau come to the one company, and smite it, then the other company which is left shall escape.'); +INSERT INTO t1(docid,words) VALUES(1032009,'And Jacob said, O God of my father Abraham, and God of my father Isaac, the LORD which saidst unto me, Return unto thy country, and to thy kindred, and I will deal well with thee:'); +INSERT INTO t1(docid,words) VALUES(1032010,'I am not worthy of the least of all the mercies, and of all the truth, which thou hast shewed unto thy servant; for with my staff I passed over this Jordan; and now I am become two bands.'); +INSERT INTO t1(docid,words) VALUES(1032011,'Deliver me, I pray thee, from the hand of my brother, from the hand of Esau: for I fear him, lest he will come and smite me, and the mother with the children.'); +INSERT INTO t1(docid,words) VALUES(1032012,'And thou saidst, I will surely do thee good, and make thy seed as the sand of the sea, which cannot be numbered for multitude.'); +INSERT INTO t1(docid,words) VALUES(1032013,'And he lodged there that same night; and took of that which came to his hand a present for Esau his brother;'); +INSERT INTO t1(docid,words) VALUES(1032014,'Two hundred she goats, and twenty he goats, two hundred ewes, and twenty rams,'); +INSERT INTO t1(docid,words) VALUES(1032015,'Thirty milch camels with their colts, forty kine, and ten bulls, twenty she asses, and ten foals.'); +INSERT INTO t1(docid,words) VALUES(1032016,'And he delivered them into the hand of his servants, every drove by themselves; and said unto his servants, Pass over before me, and put a space betwixt drove and drove.'); +INSERT INTO t1(docid,words) VALUES(1032017,'And he commanded the foremost, saying, When Esau my brother meeteth thee, and asketh thee, saying, Whose art thou? and whither goest thou? and whose are these before thee?'); +INSERT INTO t1(docid,words) VALUES(1032018,'Then thou shalt say, They be thy servant Jacob''s; it is a present sent unto my lord Esau: and, behold, also he is behind us.'); +INSERT INTO t1(docid,words) VALUES(1032019,'And so commanded he the second, and the third, and all that followed the droves, saying, On this manner shall ye speak unto Esau, when ye find him.'); +INSERT INTO t1(docid,words) VALUES(1032020,'And say ye moreover, Behold, thy servant Jacob is behind us. For he said, I will appease him with the present that goeth before me, and afterward I will see his face; peradventure he will accept of me.'); +INSERT INTO t1(docid,words) VALUES(1032021,'So went the present over before him: and himself lodged that night in the company.'); +INSERT INTO t1(docid,words) VALUES(1032022,'And he rose up that night, and took his two wives, and his two womenservants, and his eleven sons, and passed over the ford Jabbok.'); +INSERT INTO t1(docid,words) VALUES(1032023,'And he took them, and sent them over the brook, and sent over that he had.'); +INSERT INTO t1(docid,words) VALUES(1032024,'And Jacob was left alone; and there wrestled a man with him until the breaking of the day.'); +INSERT INTO t1(docid,words) VALUES(1032025,'And when he saw that he prevailed not against him, he touched the hollow of his thigh; and the hollow of Jacob''s thigh was out of joint, as he wrestled with him.'); +INSERT INTO t1(docid,words) VALUES(1032026,'And he said, Let me go, for the day breaketh. And he said, I will not let thee go, except thou bless me.'); +INSERT INTO t1(docid,words) VALUES(1032027,'And he said unto him, What is thy name? And he said, Jacob.'); +INSERT INTO t1(docid,words) VALUES(1032028,'And he said, Thy name shall be called no more Jacob, but Israel: for as a prince hast thou power with God and with men, and hast prevailed.'); +INSERT INTO t1(docid,words) VALUES(1032029,'And Jacob asked him, and said, Tell me, I pray thee, thy name. And he said, Wherefore is it that thou dost ask after my name? And he blessed him there.'); +INSERT INTO t1(docid,words) VALUES(1032030,'And Jacob called the name of the place Peniel: for I have seen God face to face, and my life is preserved.'); +INSERT INTO t1(docid,words) VALUES(1032031,'And as he passed over Penuel the sun rose upon him, and he halted upon his thigh.'); +INSERT INTO t1(docid,words) VALUES(1032032,'Therefore the children of Israel eat not of the sinew which shrank, which is upon the hollow of the thigh, unto this day: because he touched the hollow of Jacob''s thigh in the sinew that shrank.'); +INSERT INTO t1(docid,words) VALUES(1033001,'And Jacob lifted up his eyes, and looked, and, behold, Esau came, and with him four hundred men. And he divided the children unto Leah, and unto Rachel, and unto the two handmaids.'); +INSERT INTO t1(docid,words) VALUES(1033002,'And he put the handmaids and their children foremost, and Leah and her children after, and Rachel and Joseph hindermost.'); +INSERT INTO t1(docid,words) VALUES(1033003,'And he passed over before them, and bowed himself to the ground seven times, until he came near to his brother.'); +INSERT INTO t1(docid,words) VALUES(1033004,'And Esau ran to meet him, and embraced him, and fell on his neck, and kissed him: and they wept.'); +INSERT INTO t1(docid,words) VALUES(1033005,'And he lifted up his eyes, and saw the women and the children; and said, Who are those with thee? And he said, The children which God hath graciously given thy servant.'); +INSERT INTO t1(docid,words) VALUES(1033006,'Then the handmaidens came near, they and their children, and they bowed themselves.'); +INSERT INTO t1(docid,words) VALUES(1033007,'And Leah also with her children came near, and bowed themselves: and after came Joseph near and Rachel, and they bowed themselves.'); +INSERT INTO t1(docid,words) VALUES(1033008,'And he said, What meanest thou by all this drove which I met? And he said, These are to find grace in the sight of my lord.'); +INSERT INTO t1(docid,words) VALUES(1033009,'And Esau said, I have enough, my brother; keep that thou hast unto thyself.'); +INSERT INTO t1(docid,words) VALUES(1033010,'And Jacob said, Nay, I pray thee, if now I have found grace in thy sight, then receive my present at my hand: for therefore I have seen thy face, as though I had seen the face of God, and thou wast pleased with me.'); +INSERT INTO t1(docid,words) VALUES(1033011,'Take, I pray thee, my blessing that is brought to thee; because God hath dealt graciously with me, and because I have enough. And he urged him, and he took it.'); +INSERT INTO t1(docid,words) VALUES(1033012,'And he said, Let us take our journey, and let us go, and I will go before thee.'); +INSERT INTO t1(docid,words) VALUES(1033013,'And he said unto him, My lord knoweth that the children are tender, and the flocks and herds with young are with me: and if men should overdrive them one day, all the flock will die.'); +INSERT INTO t1(docid,words) VALUES(1033014,'Let my lord, I pray thee, pass over before his servant: and I will lead on softly, according as the cattle that goeth before me and the children be able to endure, until I come unto my lord unto Seir.'); +INSERT INTO t1(docid,words) VALUES(1033015,'And Esau said, Let me now leave with thee some of the folk that are with me. And he said, What needeth it? let me find grace in the sight of my lord.'); +INSERT INTO t1(docid,words) VALUES(1033016,'So Esau returned that day on his way unto Seir.'); +INSERT INTO t1(docid,words) VALUES(1033017,'And Jacob journeyed to Succoth, and built him an house, and made booths for his cattle: therefore the name of the place is called Succoth.'); +INSERT INTO t1(docid,words) VALUES(1033018,'And Jacob came to Shalem, a city of Shechem, which is in the land of Canaan, when he came from Padanaram; and pitched his tent before the city.'); +INSERT INTO t1(docid,words) VALUES(1033019,'And he bought a parcel of a field, where he had spread his tent, at the hand of the children of Hamor, Shechem''s father, for an hundred pieces of money.'); +INSERT INTO t1(docid,words) VALUES(1033020,'And he erected there an altar, and called it EleloheIsrael.'); +INSERT INTO t1(docid,words) VALUES(1034001,'And Dinah the daughter of Leah, which she bare unto Jacob, went out to see the daughters of the land.'); +INSERT INTO t1(docid,words) VALUES(1034002,'And when Shechem the son of Hamor the Hivite, prince of the country, saw her, he took her, and lay with her, and defiled her.'); +INSERT INTO t1(docid,words) VALUES(1034003,'And his soul clave unto Dinah the daughter of Jacob, and he loved the damsel, and spake kindly unto the damsel.'); +INSERT INTO t1(docid,words) VALUES(1034004,'And Shechem spake unto his father Hamor, saying, Get me this damsel to wife.'); +INSERT INTO t1(docid,words) VALUES(1034005,'And Jacob heard that he had defiled Dinah his daughter: now his sons were with his cattle in the field: and Jacob held his peace until they were come.'); +INSERT INTO t1(docid,words) VALUES(1034006,'And Hamor the father of Shechem went out unto Jacob to commune with him.'); +INSERT INTO t1(docid,words) VALUES(1034007,'And the sons of Jacob came out of the field when they heard it: and the men were grieved, and they were very wroth, because he had wrought folly in Israel in lying with Jacob''s daughter: which thing ought not to be done.'); +INSERT INTO t1(docid,words) VALUES(1034008,'And Hamor communed with them, saying, The soul of my son Shechem longeth for your daughter: I pray you give her him to wife.'); +INSERT INTO t1(docid,words) VALUES(1034009,'And make ye marriages with us, and give your daughters unto us, and take our daughters unto you.'); +INSERT INTO t1(docid,words) VALUES(1034010,'And ye shall dwell with us: and the land shall be before you; dwell and trade ye therein, and get you possessions therein.'); +INSERT INTO t1(docid,words) VALUES(1034011,'And Shechem said unto her father and unto her brethren, Let me find grace in your eyes, and what ye shall say unto me I will give.'); +INSERT INTO t1(docid,words) VALUES(1034012,'Ask me never so much dowry and gift, and I will give according as ye shall say unto me: but give me the damsel to wife.'); +INSERT INTO t1(docid,words) VALUES(1034013,'And the sons of Jacob answered Shechem and Hamor his father deceitfully, and said, because he had defiled Dinah their sister:'); +INSERT INTO t1(docid,words) VALUES(1034014,'And they said unto them, We cannot do this thing, to give our sister to one that is uncircumcised; for that were a reproach unto us:'); +INSERT INTO t1(docid,words) VALUES(1034015,'But in this will we consent unto you: If ye will be as we be, that every male of you be circumcised;'); +INSERT INTO t1(docid,words) VALUES(1034016,'Then will we give our daughters unto you, and we will take your daughters to us, and we will dwell with you, and we will become one people.'); +INSERT INTO t1(docid,words) VALUES(1034017,'But if ye will not hearken unto us, to be circumcised; then will we take our daughter, and we will be gone.'); +INSERT INTO t1(docid,words) VALUES(1034018,'And their words pleased Hamor, and Shechem Hamor''s son.'); +INSERT INTO t1(docid,words) VALUES(1034019,'And the young man deferred not to do the thing, because he had delight in Jacob''s daughter: and he was more honourable than all the house of his father.'); +INSERT INTO t1(docid,words) VALUES(1034020,'And Hamor and Shechem his son came unto the gate of their city, and communed with the men of their city, saying,'); +INSERT INTO t1(docid,words) VALUES(1034021,'These men are peaceable with us; therefore let them dwell in the land, and trade therein; for the land, behold, it is large enough for them; let us take their daughters to us for wives, and let us give them our daughters.'); +INSERT INTO t1(docid,words) VALUES(1034022,'Only herein will the men consent unto us for to dwell with us, to be one people, if every male among us be circumcised, as they are circumcised.'); +INSERT INTO t1(docid,words) VALUES(1034023,'Shall not their cattle and their substance and every beast of their''s be our''s? only let us consent unto them, and they will dwell with us.'); +INSERT INTO t1(docid,words) VALUES(1034024,'And unto Hamor and unto Shechem his son hearkened all that went out of the gate of his city; and every male was circumcised, all that went out of the gate of his city.'); +INSERT INTO t1(docid,words) VALUES(1034025,'And it came to pass on the third day, when they were sore, that two of the sons of Jacob, Simeon and Levi, Dinah''s brethren, took each man his sword, and came upon the city boldly, and slew all the males.'); +INSERT INTO t1(docid,words) VALUES(1034026,'And they slew Hamor and Shechem his son with the edge of the sword, and took Dinah out of Shechem''s house, and went out.'); +INSERT INTO t1(docid,words) VALUES(1034027,'The sons of Jacob came upon the slain, and spoiled the city, because they had defiled their sister.'); +INSERT INTO t1(docid,words) VALUES(1034028,'They took their sheep, and their oxen, and their asses, and that which was in the city, and that which was in the field,'); +INSERT INTO t1(docid,words) VALUES(1034029,'And all their wealth, and all their little ones, and their wives took they captive, and spoiled even all that was in the house.'); +INSERT INTO t1(docid,words) VALUES(1034030,'And Jacob said to Simeon and Levi, Ye have troubled me to make me to stink among the inhabitants of the land, among the Canaanites and the Perizzites: and I being few in number, they shall gather themselves together against me, and slay me; and I shall be destroyed, I and my house.'); +INSERT INTO t1(docid,words) VALUES(1034031,'And they said, Should he deal with our sister as with an harlot?'); +INSERT INTO t1(docid,words) VALUES(1035001,'And God said unto Jacob, Arise, go up to Bethel, and dwell there: and make there an altar unto God, that appeared unto thee when thou fleddest from the face of Esau thy brother.'); +INSERT INTO t1(docid,words) VALUES(1035002,'Then Jacob said unto his household, and to all that were with him, Put away the strange gods that are among you, and be clean, and change your garments:'); +INSERT INTO t1(docid,words) VALUES(1035003,'And let us arise, and go up to Bethel; and I will make there an altar unto God, who answered me in the day of my distress, and was with me in the way which I went.'); +INSERT INTO t1(docid,words) VALUES(1035004,'And they gave unto Jacob all the strange gods which were in their hand, and all their earrings which were in their ears; and Jacob hid them under the oak which was by Shechem.'); +INSERT INTO t1(docid,words) VALUES(1035005,'And they journeyed: and the terror of God was upon the cities that were round about them, and they did not pursue after the sons of Jacob.'); +INSERT INTO t1(docid,words) VALUES(1035006,'So Jacob came to Luz, which is in the land of Canaan, that is, Bethel, he and all the people that were with him.'); +INSERT INTO t1(docid,words) VALUES(1035007,'And he built there an altar, and called the place Elbethel: because there God appeared unto him, when he fled from the face of his brother.'); +INSERT INTO t1(docid,words) VALUES(1035008,'But Deborah Rebekah''s nurse died, and she was buried beneath Bethel under an oak: and the name of it was called Allonbachuth.'); +INSERT INTO t1(docid,words) VALUES(1035009,'And God appeared unto Jacob again, when he came out of Padanaram, and blessed him.'); +INSERT INTO t1(docid,words) VALUES(1035010,'And God said unto him, Thy name is Jacob: thy name shall not be called any more Jacob, but Israel shall be thy name: and he called his name Israel.'); +INSERT INTO t1(docid,words) VALUES(1035011,'And God said unto him, I am God Almighty: be fruitful and multiply; a nation and a company of nations shall be of thee, and kings shall come out of thy loins;'); +INSERT INTO t1(docid,words) VALUES(1035012,'And the land which I gave Abraham and Isaac, to thee I will give it, and to thy seed after thee will I give the land.'); +INSERT INTO t1(docid,words) VALUES(1035013,'And God went up from him in the place where he talked with him.'); +INSERT INTO t1(docid,words) VALUES(1035014,'And Jacob set up a pillar in the place where he talked with him, even a pillar of stone: and he poured a drink offering thereon, and he poured oil thereon.'); +INSERT INTO t1(docid,words) VALUES(1035015,'And Jacob called the name of the place where God spake with him, Bethel.'); +INSERT INTO t1(docid,words) VALUES(1035016,'And they journeyed from Bethel; and there was but a little way to come to Ephrath: and Rachel travailed, and she had hard labour.'); +INSERT INTO t1(docid,words) VALUES(1035017,'And it came to pass, when she was in hard labour, that the midwife said unto her, Fear not; thou shalt have this son also.'); +INSERT INTO t1(docid,words) VALUES(1035018,'And it came to pass, as her soul was in departing, (for she died) that she called his name Benoni: but his father called him Benjamin.'); +INSERT INTO t1(docid,words) VALUES(1035019,'And Rachel died, and was buried in the way to Ephrath, which is Bethlehem.'); +INSERT INTO t1(docid,words) VALUES(1035020,'And Jacob set a pillar upon her grave: that is the pillar of Rachel''s grave unto this day.'); +INSERT INTO t1(docid,words) VALUES(1035021,'And Israel journeyed, and spread his tent beyond the tower of Edar.'); +INSERT INTO t1(docid,words) VALUES(1035022,'And it came to pass, when Israel dwelt in that land, that Reuben went and lay with Bilhah his father''s concubine: and Israel heard it. Now the sons of Jacob were twelve:'); +INSERT INTO t1(docid,words) VALUES(1035023,'The sons of Leah; Reuben, Jacob''s firstborn, and Simeon, and Levi, and Judah, and Issachar, and Zebulun:'); +INSERT INTO t1(docid,words) VALUES(1035024,'The sons of Rachel; Joseph, and Benjamin:'); +INSERT INTO t1(docid,words) VALUES(1035025,'And the sons of Bilhah, Rachel''s handmaid; Dan, and Naphtali:'); +INSERT INTO t1(docid,words) VALUES(1035026,'And the sons of Zilpah, Leah''s handmaid: Gad, and Asher: these are the sons of Jacob, which were born to him in Padanaram.'); +INSERT INTO t1(docid,words) VALUES(1035027,'And Jacob came unto Isaac his father unto Mamre, unto the city of Arbah, which is Hebron, where Abraham and Isaac sojourned.'); +INSERT INTO t1(docid,words) VALUES(1035028,'And the days of Isaac were an hundred and fourscore years.'); +INSERT INTO t1(docid,words) VALUES(1035029,'And Isaac gave up the ghost, and died, and was gathered unto his people, being old and full of days: and his sons Esau and Jacob buried him.'); +INSERT INTO t1(docid,words) VALUES(1036001,'Now these are the generations of Esau, who is Edom.'); +INSERT INTO t1(docid,words) VALUES(1036002,'Esau took his wives of the daughters of Canaan; Adah the daughter of Elon the Hittite, and Aholibamah the daughter of Anah the daughter of Zibeon the Hivite;'); +INSERT INTO t1(docid,words) VALUES(1036003,'And Bashemath Ishmael''s daughter, sister of Nebajoth.'); +INSERT INTO t1(docid,words) VALUES(1036004,'And Adah bare to Esau Eliphaz; and Bashemath bare Reuel;'); +INSERT INTO t1(docid,words) VALUES(1036005,'And Aholibamah bare Jeush, and Jaalam, and Korah: these are the sons of Esau, which were born unto him in the land of Canaan.'); +INSERT INTO t1(docid,words) VALUES(1036006,'And Esau took his wives, and his sons, and his daughters, and all the persons of his house, and his cattle, and all his beasts, and all his substance, which he had got in the land of Canaan; and went into the country from the face of his brother Jacob.'); +INSERT INTO t1(docid,words) VALUES(1036007,'For their riches were more than that they might dwell together; and the land wherein they were strangers could not bear them because of their cattle.'); +INSERT INTO t1(docid,words) VALUES(1036008,'Thus dwelt Esau in mount Seir: Esau is Edom.'); +INSERT INTO t1(docid,words) VALUES(1036009,'And these are the generations of Esau the father of the Edomites in mount Seir:'); +INSERT INTO t1(docid,words) VALUES(1036010,'These are the names of Esau''s sons; Eliphaz the son of Adah the wife of Esau, Reuel the son of Bashemath the wife of Esau.'); +INSERT INTO t1(docid,words) VALUES(1036011,'And the sons of Eliphaz were Teman, Omar, Zepho, and Gatam, and Kenaz.'); +INSERT INTO t1(docid,words) VALUES(1036012,'And Timna was concubine to Eliphaz Esau''s son; and she bare to Eliphaz Amalek: these were the sons of Adah Esau''s wife.'); +INSERT INTO t1(docid,words) VALUES(1036013,'And these are the sons of Reuel; Nahath, and Zerah, Shammah, and Mizzah: these were the sons of Bashemath Esau''s wife.'); +INSERT INTO t1(docid,words) VALUES(1036014,'And these were the sons of Aholibamah, the daughter of Anah the daughter of Zibeon, Esau''s wife: and she bare to Esau Jeush, and Jaalam, and Korah.'); +INSERT INTO t1(docid,words) VALUES(1036015,'These were dukes of the sons of Esau: the sons of Eliphaz the firstborn son of Esau; duke Teman, duke Omar, duke Zepho, duke Kenaz,'); +INSERT INTO t1(docid,words) VALUES(1036016,'Duke Korah, duke Gatam, and duke Amalek: these are the dukes that came of Eliphaz in the land of Edom; these were the sons of Adah.'); +INSERT INTO t1(docid,words) VALUES(1036017,'And these are the sons of Reuel Esau''s son; duke Nahath, duke Zerah, duke Shammah, duke Mizzah: these are the dukes that came of Reuel in the land of Edom; these are the sons of Bashemath Esau''s wife.'); +INSERT INTO t1(docid,words) VALUES(1036018,'And these are the sons of Aholibamah Esau''s wife; duke Jeush, duke Jaalam, duke Korah: these were the dukes that came of Aholibamah the daughter of Anah, Esau''s wife.'); +INSERT INTO t1(docid,words) VALUES(1036019,'These are the sons of Esau, who is Edom, and these are their dukes.'); +INSERT INTO t1(docid,words) VALUES(1036020,'These are the sons of Seir the Horite, who inhabited the land; Lotan, and Shobal, and Zibeon, and Anah,'); +INSERT INTO t1(docid,words) VALUES(1036021,'And Dishon, and Ezer, and Dishan: these are the dukes of the Horites, the children of Seir in the land of Edom.'); +INSERT INTO t1(docid,words) VALUES(1036022,'And the children of Lotan were Hori and Hemam; and Lotan''s sister was Timna.'); +INSERT INTO t1(docid,words) VALUES(1036023,'And the children of Shobal were these; Alvan, and Manahath, and Ebal, Shepho, and Onam.'); +INSERT INTO t1(docid,words) VALUES(1036024,'And these are the children of Zibeon; both Ajah, and Anah: this was that Anah that found the mules in the wilderness, as he fed the asses of Zibeon his father.'); +INSERT INTO t1(docid,words) VALUES(1036025,'And the children of Anah were these; Dishon, and Aholibamah the daughter of Anah.'); +INSERT INTO t1(docid,words) VALUES(1036026,'And these are the children of Dishon; Hemdan, and Eshban, and Ithran, and Cheran.'); +INSERT INTO t1(docid,words) VALUES(1036027,'The children of Ezer are these; Bilhan, and Zaavan, and Akan.'); +INSERT INTO t1(docid,words) VALUES(1036028,'The children of Dishan are these; Uz, and Aran.'); +INSERT INTO t1(docid,words) VALUES(1036029,'These are the dukes that came of the Horites; duke Lotan, duke Shobal, duke Zibeon, duke Anah,'); +INSERT INTO t1(docid,words) VALUES(1036030,'Duke Dishon, duke Ezer, duke Dishan: these are the dukes that came of Hori, among their dukes in the land of Seir.'); +INSERT INTO t1(docid,words) VALUES(1036031,'And these are the kings that reigned in the land of Edom, before there reigned any king over the children of Israel.'); +INSERT INTO t1(docid,words) VALUES(1036032,'And Bela the son of Beor reigned in Edom: and the name of his city was Dinhabah.'); +INSERT INTO t1(docid,words) VALUES(1036033,'And Bela died, and Jobab the son of Zerah of Bozrah reigned in his stead.'); +INSERT INTO t1(docid,words) VALUES(1036034,'And Jobab died, and Husham of the land of Temani reigned in his stead.'); +INSERT INTO t1(docid,words) VALUES(1036035,'And Husham died, and Hadad the son of Bedad, who smote Midian in the field of Moab, reigned in his stead: and the name of his city was Avith.'); +INSERT INTO t1(docid,words) VALUES(1036036,'And Hadad died, and Samlah of Masrekah reigned in his stead.'); +INSERT INTO t1(docid,words) VALUES(1036037,'And Samlah died, and Saul of Rehoboth by the river reigned in his stead.'); +INSERT INTO t1(docid,words) VALUES(1036038,'And Saul died, and Baalhanan the son of Achbor reigned in his stead.'); +INSERT INTO t1(docid,words) VALUES(1036039,'And Baalhanan the son of Achbor died, and Hadar reigned in his stead: and the name of his city was Pau; and his wife''s name was Mehetabel, the daughter of Matred, the daughter of Mezahab.'); +INSERT INTO t1(docid,words) VALUES(1036040,'And these are the names of the dukes that came of Esau, according to their families, after their places, by their names; duke Timnah, duke Alvah, duke Jetheth,'); +INSERT INTO t1(docid,words) VALUES(1036041,'Duke Aholibamah, duke Elah, duke Pinon,'); +INSERT INTO t1(docid,words) VALUES(1036042,'Duke Kenaz, duke Teman, duke Mibzar,'); +INSERT INTO t1(docid,words) VALUES(1036043,'Duke Magdiel, duke Iram: these be the dukes of Edom, according to their habitations in the land of their possession: he is Esau the father of the Edomites.'); +INSERT INTO t1(docid,words) VALUES(1037001,'And Jacob dwelt in the land wherein his father was a stranger, in the land of Canaan.'); +INSERT INTO t1(docid,words) VALUES(1037002,'These are the generations of Jacob. Joseph, being seventeen years old, was feeding the flock with his brethren; and the lad was with the sons of Bilhah, and with the sons of Zilpah, his father''s wives: and Joseph brought unto his father their evil report.'); +INSERT INTO t1(docid,words) VALUES(1037003,'Now Israel loved Joseph more than all his children, because he was the son of his old age: and he made him a coat of many colours.'); +INSERT INTO t1(docid,words) VALUES(1037004,'And when his brethren saw that their father loved him more than all his brethren, they hated him, and could not speak peaceably unto him.'); +INSERT INTO t1(docid,words) VALUES(1037005,'And Joseph dreamed a dream, and he told it his brethren: and they hated him yet the more.'); +INSERT INTO t1(docid,words) VALUES(1037006,'And he said unto them, Hear, I pray you, this dream which I have dreamed:'); +INSERT INTO t1(docid,words) VALUES(1037007,'For, behold, we were binding sheaves in the field, and, lo, my sheaf arose, and also stood upright; and, behold, your sheaves stood round about, and made obeisance to my sheaf.'); +INSERT INTO t1(docid,words) VALUES(1037008,'And his brethren said to him, Shalt thou indeed reign over us? or shalt thou indeed have dominion over us? And they hated him yet the more for his dreams, and for his words.'); +INSERT INTO t1(docid,words) VALUES(1037009,'And he dreamed yet another dream, and told it his brethren, and said, Behold, I have dreamed a dream more; and, behold, the sun and the moon and the eleven stars made obeisance to me.'); +INSERT INTO t1(docid,words) VALUES(1037010,'And he told it to his father, and to his brethren: and his father rebuked him, and said unto him, What is this dream that thou hast dreamed? Shall I and thy mother and thy brethren indeed come to bow down ourselves to thee to the earth?'); +INSERT INTO t1(docid,words) VALUES(1037011,'And his brethren envied him; but his father observed the saying.'); +INSERT INTO t1(docid,words) VALUES(1037012,'And his brethren went to feed their father''s flock in Shechem.'); +INSERT INTO t1(docid,words) VALUES(1037013,'And Israel said unto Joseph, Do not thy brethren feed the flock in Shechem? come, and I will send thee unto them. And he said to him, Here am I.'); +INSERT INTO t1(docid,words) VALUES(1037014,'And he said to him, Go, I pray thee, see whether it be well with thy brethren, and well with the flocks; and bring me word again. So he sent him out of the vale of Hebron, and he came to Shechem.'); +INSERT INTO t1(docid,words) VALUES(1037015,'And a certain man found him, and, behold, he was wandering in the field: and the man asked him, saying, What seekest thou?'); +INSERT INTO t1(docid,words) VALUES(1037016,'And he said, I seek my brethren: tell me, I pray thee, where they feed their flocks.'); +INSERT INTO t1(docid,words) VALUES(1037017,'And the man said, They are departed hence; for I heard them say, Let us go to Dothan. And Joseph went after his brethren, and found them in Dothan.'); +INSERT INTO t1(docid,words) VALUES(1037018,'And when they saw him afar off, even before he came near unto them, they conspired against him to slay him.'); +INSERT INTO t1(docid,words) VALUES(1037019,'And they said one to another, Behold, this dreamer cometh.'); +INSERT INTO t1(docid,words) VALUES(1037020,'Come now therefore, and let us slay him, and cast him into some pit, and we will say, Some evil beast hath devoured him: and we shall see what will become of his dreams.'); +INSERT INTO t1(docid,words) VALUES(1037021,'And Reuben heard it, and he delivered him out of their hands; and said, Let us not kill him.'); +INSERT INTO t1(docid,words) VALUES(1037022,'And Reuben said unto them, Shed no blood, but cast him into this pit that is in the wilderness, and lay no hand upon him; that he might rid him out of their hands, to deliver him to his father again.'); +INSERT INTO t1(docid,words) VALUES(1037023,'And it came to pass, when Joseph was come unto his brethren, that they stript Joseph out of his coat, his coat of many colours that was on him;'); +INSERT INTO t1(docid,words) VALUES(1037024,'And they took him, and cast him into a pit: and the pit was empty, there was no water in it.'); +INSERT INTO t1(docid,words) VALUES(1037025,'And they sat down to eat bread: and they lifted up their eyes and looked, and, behold, a company of Ishmeelites came from Gilead with their camels bearing spicery and balm and myrrh, going to carry it down to Egypt.'); +INSERT INTO t1(docid,words) VALUES(1037026,'And Judah said unto his brethren, What profit is it if we slay our brother, and conceal his blood?'); +INSERT INTO t1(docid,words) VALUES(1037027,'Come, and let us sell him to the Ishmeelites, and let not our hand be upon him; for he is our brother and our flesh. And his brethren were content.'); +INSERT INTO t1(docid,words) VALUES(1037028,'Then there passed by Midianites merchantmen; and they drew and lifted up Joseph out of the pit, and sold Joseph to the Ishmeelites for twenty pieces of silver: and they brought Joseph into Egypt.'); +INSERT INTO t1(docid,words) VALUES(1037029,'And Reuben returned unto the pit; and, behold, Joseph was not in the pit; and he rent his clothes.'); +INSERT INTO t1(docid,words) VALUES(1037030,'And he returned unto his brethren, and said, The child is not; and I, whither shall I go?'); +INSERT INTO t1(docid,words) VALUES(1037031,'And they took Joseph''s coat, and killed a kid of the goats, and dipped the coat in the blood;'); +INSERT INTO t1(docid,words) VALUES(1037032,'And they sent the coat of many colours, and they brought it to their father; and said, This have we found: know now whether it be thy son''s coat or no.'); +INSERT INTO t1(docid,words) VALUES(1037033,'And he knew it, and said, It is my son''s coat; an evil beast hath devoured him; Joseph is without doubt rent in pieces.'); +INSERT INTO t1(docid,words) VALUES(1037034,'And Jacob rent his clothes, and put sackcloth upon his loins, and mourned for his son many days.'); +INSERT INTO t1(docid,words) VALUES(1037035,'And all his sons and all his daughters rose up to comfort him; but he refused to be comforted; and he said, For I will go down into the grave unto my son mourning. Thus his father wept for him.'); +INSERT INTO t1(docid,words) VALUES(1037036,'And the Midianites sold him into Egypt unto Potiphar, an officer of Pharaoh''s, and captain of the guard.'); +INSERT INTO t1(docid,words) VALUES(1038001,'And it came to pass at that time, that Judah went down from his brethren, and turned in to a certain Adullamite, whose name was Hirah.'); +INSERT INTO t1(docid,words) VALUES(1038002,'And Judah saw there a daughter of a certain Canaanite, whose name was Shuah; and he took her, and went in unto her.'); +INSERT INTO t1(docid,words) VALUES(1038003,'And she conceived, and bare a son; and he called his name Er.'); +INSERT INTO t1(docid,words) VALUES(1038004,'And she conceived again, and bare a son; and she called his name Onan.'); +INSERT INTO t1(docid,words) VALUES(1038005,'And she yet again conceived, and bare a son; and called his name Shelah: and he was at Chezib, when she bare him.'); +INSERT INTO t1(docid,words) VALUES(1038006,'And Judah took a wife for Er his firstborn, whose name was Tamar.'); +INSERT INTO t1(docid,words) VALUES(1038007,'And Er, Judah''s firstborn, was wicked in the sight of the LORD; and the LORD slew him.'); +INSERT INTO t1(docid,words) VALUES(1038008,'And Judah said unto Onan, Go in unto thy brother''s wife, and marry her, and raise up seed to thy brother.'); +INSERT INTO t1(docid,words) VALUES(1038009,'And Onan knew that the seed should not be his; and it came to pass, when he went in unto his brother''s wife, that he spilled it on the ground, lest that he should give seed to his brother.'); +INSERT INTO t1(docid,words) VALUES(1038010,'And the thing which he did displeased the LORD: wherefore he slew him also.'); +INSERT INTO t1(docid,words) VALUES(1038011,'Then said Judah to Tamar his daughter in law, Remain a widow at thy father''s house, till Shelah my son be grown: for he said, Lest peradventure he die also, as his brethren did. And Tamar went and dwelt in her father''s house.'); +INSERT INTO t1(docid,words) VALUES(1038012,'And in process of time the daughter of Shuah Judah''s wife died; and Judah was comforted, and went up unto his sheepshearers to Timnath, he and his friend Hirah the Adullamite.'); +INSERT INTO t1(docid,words) VALUES(1038013,'And it was told Tamar, saying, Behold thy father in law goeth up to Timnath to shear his sheep.'); +INSERT INTO t1(docid,words) VALUES(1038014,'And she put her widow''s garments off from her, and covered her with a vail, and wrapped herself, and sat in an open place, which is by the way to Timnath; for she saw that Shelah was grown, and she was not given unto him to wife.'); +INSERT INTO t1(docid,words) VALUES(1038015,'When Judah saw her, he thought her to be an harlot; because she had covered her face.'); +INSERT INTO t1(docid,words) VALUES(1038016,'And he turned unto her by the way, and said, Go to, I pray thee, let me come in unto thee; (for he knew not that she was his daughter in law.) And she said, What wilt thou give me, that thou mayest come in unto me?'); +INSERT INTO t1(docid,words) VALUES(1038017,'And he said, I will send thee a kid from the flock. And she said, Wilt thou give me a pledge, till thou send it?'); +INSERT INTO t1(docid,words) VALUES(1038018,'And he said, What pledge shall I give thee? And she said, Thy signet, and thy bracelets, and thy staff that is in thine hand. And he gave it her, and came in unto her, and she conceived by him.'); +INSERT INTO t1(docid,words) VALUES(1038019,'And she arose, and went away, and laid by her vail from her, and put on the garments of her widowhood.'); +INSERT INTO t1(docid,words) VALUES(1038020,'And Judah sent the kid by the hand of his friend the Adullamite, to receive his pledge from the woman''s hand: but he found her not.'); +INSERT INTO t1(docid,words) VALUES(1038021,'Then he asked the men of that place, saying, Where is the harlot, that was openly by the way side? And they said, There was no harlot in this place.'); +INSERT INTO t1(docid,words) VALUES(1038022,'And he returned to Judah, and said, I cannot find her; and also the men of the place said, that there was no harlot in this place.'); +INSERT INTO t1(docid,words) VALUES(1038023,'And Judah said, Let her take it to her, lest we be shamed: behold, I sent this kid, and thou hast not found her.'); +INSERT INTO t1(docid,words) VALUES(1038024,'And it came to pass about three months after, that it was told Judah, saying, Tamar thy daughter in law hath played the harlot; and also, behold, she is with child by whoredom. And Judah said, Bring her forth, and let her be burnt.'); +INSERT INTO t1(docid,words) VALUES(1038025,'When she was brought forth, she sent to her father in law, saying, By the man, whose these are, am I with child: and she said, Discern, I pray thee, whose are these, the signet, and bracelets, and staff.'); +INSERT INTO t1(docid,words) VALUES(1038026,'And Judah acknowledged them, and said, She hath been more righteous than I; because that I gave her not to Shelah my son. And he knew her again no more.'); +INSERT INTO t1(docid,words) VALUES(1038027,'And it came to pass in the time of her travail, that, behold, twins were in her womb.'); +INSERT INTO t1(docid,words) VALUES(1038028,'And it came to pass, when she travailed, that the one put out his hand: and the midwife took and bound upon his hand a scarlet thread, saying, This came out first.'); +INSERT INTO t1(docid,words) VALUES(1038029,'And it came to pass, as he drew back his hand, that, behold, his brother came out: and she said, How hast thou broken forth? this breach be upon thee: therefore his name was called Pharez.'); +INSERT INTO t1(docid,words) VALUES(1038030,'And afterward came out his brother, that had the scarlet thread upon his hand: and his name was called Zarah.'); +INSERT INTO t1(docid,words) VALUES(1039001,'And Joseph was brought down to Egypt; and Potiphar, an officer of Pharaoh, captain of the guard, an Egyptian, bought him of the hands of the Ishmeelites, which had brought him down thither.'); +INSERT INTO t1(docid,words) VALUES(1039002,'And the LORD was with Joseph, and he was a prosperous man; and he was in the house of his master the Egyptian.'); +INSERT INTO t1(docid,words) VALUES(1039003,'And his master saw that the LORD was with him, and that the LORD made all that he did to prosper in his hand.'); +INSERT INTO t1(docid,words) VALUES(1039004,'And Joseph found grace in his sight, and he served him: and he made him overseer over his house, and all that he had he put into his hand.'); +INSERT INTO t1(docid,words) VALUES(1039005,'And it came to pass from the time that he had made him overseer in his house, and over all that he had, that the LORD blessed the Egyptian''s house for Joseph''s sake; and the blessing of the LORD was upon all that he had in the house, and in the field.'); +INSERT INTO t1(docid,words) VALUES(1039006,'And he left all that he had in Joseph''s hand; and he knew not ought he had, save the bread which he did eat. And Joseph was a goodly person, and well favoured.'); +INSERT INTO t1(docid,words) VALUES(1039007,'And it came to pass after these things, that his master''s wife cast her eyes upon Joseph; and she said, Lie with me.'); +INSERT INTO t1(docid,words) VALUES(1039008,'But he refused, and said unto his master''s wife, Behold, my master wotteth not what is with me in the house, and he hath committed all that he hath to my hand;'); +INSERT INTO t1(docid,words) VALUES(1039009,'There is none greater in this house than I; neither hath he kept back any thing from me but thee, because thou art his wife: how then can I do this great wickedness, and sin against God?'); +INSERT INTO t1(docid,words) VALUES(1039010,'And it came to pass, as she spake to Joseph day by day, that he hearkened not unto her, to lie by her, or to be with her.'); +INSERT INTO t1(docid,words) VALUES(1039011,'And it came to pass about this time, that Joseph went into the house to do his business; and there was none of the men of the house there within.'); +INSERT INTO t1(docid,words) VALUES(1039012,'And she caught him by his garment, saying, Lie with me: and he left his garment in her hand, and fled, and got him out.'); +INSERT INTO t1(docid,words) VALUES(1039013,'And it came to pass, when she saw that he had left his garment in her hand, and was fled forth,'); +INSERT INTO t1(docid,words) VALUES(1039014,'That she called unto the men of her house, and spake unto them, saying, See, he hath brought in an Hebrew unto us to mock us; he came in unto me to lie with me, and I cried with a loud voice:'); +INSERT INTO t1(docid,words) VALUES(1039015,'And it came to pass, when he heard that I lifted up my voice and cried, that he left his garment with me, and fled, and got him out.'); +INSERT INTO t1(docid,words) VALUES(1039016,'And she laid up his garment by her, until his lord came home.'); +INSERT INTO t1(docid,words) VALUES(1039017,'And she spake unto him according to these words, saying, The Hebrew servant, which thou hast brought unto us, came in unto me to mock me:'); +INSERT INTO t1(docid,words) VALUES(1039018,'And it came to pass, as I lifted up my voice and cried, that he left his garment with me, and fled out.'); +INSERT INTO t1(docid,words) VALUES(1039019,'And it came to pass, when his master heard the words of his wife, which she spake unto him, saying, After this manner did thy servant to me; that his wrath was kindled.'); +INSERT INTO t1(docid,words) VALUES(1039020,'And Joseph''s master took him, and put him into the prison, a place where the king''s prisoners were bound: and he was there in the prison.'); +INSERT INTO t1(docid,words) VALUES(1039021,'But the LORD was with Joseph, and shewed him mercy, and gave him favour in the sight of the keeper of the prison.'); +INSERT INTO t1(docid,words) VALUES(1039022,'And the keeper of the prison committed to Joseph''s hand all the prisoners that were in the prison; and whatsoever they did there, he was the doer of it.'); +INSERT INTO t1(docid,words) VALUES(1039023,'The keeper of the prison looked not to any thing that was under his hand; because the LORD was with him, and that which he did, the LORD made it to prosper.'); +INSERT INTO t1(docid,words) VALUES(1040001,'And it came to pass after these things, that the butler of the king of Egypt and his baker had offended their lord the king of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1040002,'And Pharaoh was wroth against two of his officers, against the chief of the butlers, and against the chief of the bakers.'); +INSERT INTO t1(docid,words) VALUES(1040003,'And he put them in ward in the house of the captain of the guard, into the prison, the place where Joseph was bound.'); +INSERT INTO t1(docid,words) VALUES(1040004,'And the captain of the guard charged Joseph with them, and he served them: and they continued a season in ward.'); +INSERT INTO t1(docid,words) VALUES(1040005,'And they dreamed a dream both of them, each man his dream in one night, each man according to the interpretation of his dream, the butler and the baker of the king of Egypt, which were bound in the prison.'); +INSERT INTO t1(docid,words) VALUES(1040006,'And Joseph came in unto them in the morning, and looked upon them, and, behold, they were sad.'); +INSERT INTO t1(docid,words) VALUES(1040007,'And he asked Pharaoh''s officers that were with him in the ward of his lord''s house, saying, Wherefore look ye so sadly to day?'); +INSERT INTO t1(docid,words) VALUES(1040008,'And they said unto him, We have dreamed a dream, and there is no interpreter of it. And Joseph said unto them, Do not interpretations belong to God? tell me them, I pray you.'); +INSERT INTO t1(docid,words) VALUES(1040009,'And the chief butler told his dream to Joseph, and said to him, In my dream, behold, a vine was before me;'); +INSERT INTO t1(docid,words) VALUES(1040010,'And in the vine were three branches: and it was as though it budded, and her blossoms shot forth; and the clusters thereof brought forth ripe grapes:'); +INSERT INTO t1(docid,words) VALUES(1040011,'And Pharaoh''s cup was in my hand: and I took the grapes, and pressed them into Pharaoh''s cup, and I gave the cup into Pharaoh''s hand.'); +INSERT INTO t1(docid,words) VALUES(1040012,'And Joseph said unto him, This is the interpretation of it: The three branches are three days:'); +INSERT INTO t1(docid,words) VALUES(1040013,'Yet within three days shall Pharaoh lift up thine head, and restore thee unto thy place: and thou shalt deliver Pharaoh''s cup into his hand, after the former manner when thou wast his butler.'); +INSERT INTO t1(docid,words) VALUES(1040014,'But think on me when it shall be well with thee, and shew kindness, I pray thee, unto me, and make mention of me unto Pharaoh, and bring me out of this house:'); +INSERT INTO t1(docid,words) VALUES(1040015,'For indeed I was stolen away out of the land of the Hebrews: and here also have I done nothing that they should put me into the dungeon.'); +INSERT INTO t1(docid,words) VALUES(1040016,'When the chief baker saw that the interpretation was good, he said unto Joseph, I also was in my dream, and, behold, I had three white baskets on my head:'); +INSERT INTO t1(docid,words) VALUES(1040017,'And in the uppermost basket there was of all manner of bakemeats for Pharaoh; and the birds did eat them out of the basket upon my head.'); +INSERT INTO t1(docid,words) VALUES(1040018,'And Joseph answered and said, This is the interpretation thereof: The three baskets are three days:'); +INSERT INTO t1(docid,words) VALUES(1040019,'Yet within three days shall Pharaoh lift up thy head from off thee, and shall hang thee on a tree; and the birds shall eat thy flesh from off thee.'); +INSERT INTO t1(docid,words) VALUES(1040020,'And it came to pass the third day, which was Pharaoh''s birthday, that he made a feast unto all his servants: and he lifted up the head of the chief butler and of the chief baker among his servants.'); +INSERT INTO t1(docid,words) VALUES(1040021,'And he restored the chief butler unto his butlership again; and he gave the cup into Pharaoh''s hand:'); +INSERT INTO t1(docid,words) VALUES(1040022,'But he hanged the chief baker: as Joseph had interpreted to them.'); +INSERT INTO t1(docid,words) VALUES(1040023,'Yet did not the chief butler remember Joseph, but forgat him.'); +INSERT INTO t1(docid,words) VALUES(1041001,'And it came to pass at the end of two full years, that Pharaoh dreamed: and, behold, he stood by the river.'); +INSERT INTO t1(docid,words) VALUES(1041002,'And, behold, there came up out of the river seven well favoured kine and fatfleshed; and they fed in a meadow.'); +INSERT INTO t1(docid,words) VALUES(1041003,'And, behold, seven other kine came up after them out of the river, ill favoured and leanfleshed; and stood by the other kine upon the brink of the river.'); +INSERT INTO t1(docid,words) VALUES(1041004,'And the ill favoured and leanfleshed kine did eat up the seven well favoured and fat kine. So Pharaoh awoke.'); +INSERT INTO t1(docid,words) VALUES(1041005,'And he slept and dreamed the second time: and, behold, seven ears of corn came up upon one stalk, rank and good.'); +INSERT INTO t1(docid,words) VALUES(1041006,'And, behold, seven thin ears and blasted with the east wind sprung up after them.'); +INSERT INTO t1(docid,words) VALUES(1041007,'And the seven thin ears devoured the seven rank and full ears. And Pharaoh awoke, and, behold, it was a dream.'); +INSERT INTO t1(docid,words) VALUES(1041008,'And it came to pass in the morning that his spirit was troubled; and he sent and called for all the magicians of Egypt, and all the wise men thereof: and Pharaoh told them his dream; but there was none that could interpret them unto Pharaoh.'); +INSERT INTO t1(docid,words) VALUES(1041009,'Then spake the chief butler unto Pharaoh, saying, I do remember my faults this day:'); +INSERT INTO t1(docid,words) VALUES(1041010,'Pharaoh was wroth with his servants, and put me in ward in the captain of the guard''s house, both me and the chief baker:'); +INSERT INTO t1(docid,words) VALUES(1041011,'And we dreamed a dream in one night, I and he; we dreamed each man according to the interpretation of his dream.'); +INSERT INTO t1(docid,words) VALUES(1041012,'And there was there with us a young man, an Hebrew, servant to the captain of the guard; and we told him, and he interpreted to us our dreams; to each man according to his dream he did interpret.'); +INSERT INTO t1(docid,words) VALUES(1041013,'And it came to pass, as he interpreted to us, so it was; me he restored unto mine office, and him he hanged.'); +INSERT INTO t1(docid,words) VALUES(1041014,'Then Pharaoh sent and called Joseph, and they brought him hastily out of the dungeon: and he shaved himself, and changed his raiment, and came in unto Pharaoh.'); +INSERT INTO t1(docid,words) VALUES(1041015,'And Pharaoh said unto Joseph, I have dreamed a dream, and there is none that can interpret it: and I have heard say of thee, that thou canst understand a dream to interpret it.'); +INSERT INTO t1(docid,words) VALUES(1041016,'And Joseph answered Pharaoh, saying, It is not in me: God shall give Pharaoh an answer of peace.'); +INSERT INTO t1(docid,words) VALUES(1041017,'And Pharaoh said unto Joseph, In my dream, behold, I stood upon the bank of the river:'); +INSERT INTO t1(docid,words) VALUES(1041018,'And, behold, there came up out of the river seven kine, fatfleshed and well favoured; and they fed in a meadow:'); +INSERT INTO t1(docid,words) VALUES(1041019,'And, behold, seven other kine came up after them, poor and very ill favoured and leanfleshed, such as I never saw in all the land of Egypt for badness:'); +INSERT INTO t1(docid,words) VALUES(1041020,'And the lean and the ill favoured kine did eat up the first seven fat kine:'); +INSERT INTO t1(docid,words) VALUES(1041021,'And when they had eaten them up, it could not be known that they had eaten them; but they were still ill favoured, as at the beginning. So I awoke.'); +INSERT INTO t1(docid,words) VALUES(1041022,'And I saw in my dream, and, behold, seven ears came up in one stalk, full and good:'); +INSERT INTO t1(docid,words) VALUES(1041023,'And, behold, seven ears, withered, thin, and blasted with the east wind, sprung up after them:'); +INSERT INTO t1(docid,words) VALUES(1041024,'And the thin ears devoured the seven good ears: and I told this unto the magicians; but there was none that could declare it to me.'); +INSERT INTO t1(docid,words) VALUES(1041025,'And Joseph said unto Pharaoh, The dream of Pharaoh is one: God hath shewed Pharaoh what he is about to do.'); +INSERT INTO t1(docid,words) VALUES(1041026,'The seven good kine are seven years; and the seven good ears are seven years: the dream is one.'); +INSERT INTO t1(docid,words) VALUES(1041027,'And the seven thin and ill favoured kine that came up after them are seven years; and the seven empty ears blasted with the east wind shall be seven years of famine.'); +INSERT INTO t1(docid,words) VALUES(1041028,'This is the thing which I have spoken unto Pharaoh: What God is about to do he sheweth unto Pharaoh.'); +INSERT INTO t1(docid,words) VALUES(1041029,'Behold, there come seven years of great plenty throughout all the land of Egypt:'); +INSERT INTO t1(docid,words) VALUES(1041030,'And there shall arise after them seven years of famine; and all the plenty shall be forgotten in the land of Egypt; and the famine shall consume the land;'); +INSERT INTO t1(docid,words) VALUES(1041031,'And the plenty shall not be known in the land by reason of that famine following; for it shall be very grievous.'); +INSERT INTO t1(docid,words) VALUES(1041032,'And for that the dream was doubled unto Pharaoh twice; it is because the thing is established by God, and God will shortly bring it to pass.'); +INSERT INTO t1(docid,words) VALUES(1041033,'Now therefore let Pharaoh look out a man discreet and wise, and set him over the land of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1041034,'Let Pharaoh do this, and let him appoint officers over the land, and take up the fifth part of the land of Egypt in the seven plenteous years.'); +INSERT INTO t1(docid,words) VALUES(1041035,'And let them gather all the food of those good years that come, and lay up corn under the hand of Pharaoh, and let them keep food in the cities.'); +INSERT INTO t1(docid,words) VALUES(1041036,'And that food shall be for store to the land against the seven years of famine, which shall be in the land of Egypt; that the land perish not through the famine.'); +INSERT INTO t1(docid,words) VALUES(1041037,'And the thing was good in the eyes of Pharaoh, and in the eyes of all his servants.'); +INSERT INTO t1(docid,words) VALUES(1041038,'And Pharaoh said unto his servants, Can we find such a one as this is, a man in whom the Spirit of God is?'); +INSERT INTO t1(docid,words) VALUES(1041039,'And Pharaoh said unto Joseph, Forasmuch as God hath shewed thee all this, there is none so discreet and wise as thou art:'); +INSERT INTO t1(docid,words) VALUES(1041040,'Thou shalt be over my house, and according unto thy word shall all my people be ruled: only in the throne will I be greater than thou.'); +INSERT INTO t1(docid,words) VALUES(1041041,'And Pharaoh said unto Joseph, See, I have set thee over all the land of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1041042,'And Pharaoh took off his ring from his hand, and put it upon Joseph''s hand, and arrayed him in vestures of fine linen, and put a gold chain about his neck;'); +INSERT INTO t1(docid,words) VALUES(1041043,'And he made him to ride in the second chariot which he had; and they cried before him, Bow the knee: and he made him ruler over all the land of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1041044,'And Pharaoh said unto Joseph, I am Pharaoh, and without thee shall no man lift up his hand or foot in all the land of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1041045,'And Pharaoh called Joseph''s name Zaphnathpaaneah; and he gave him to wife Asenath the daughter of Potipherah priest of On. And Joseph went out over all the land of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1041046,'And Joseph was thirty years old when he stood before Pharaoh king of Egypt. And Joseph went out from the presence of Pharaoh, and went throughout all the land of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1041047,'And in the seven plenteous years the earth brought forth by handfuls.'); +INSERT INTO t1(docid,words) VALUES(1041048,'And he gathered up all the food of the seven years, which were in the land of Egypt, and laid up the food in the cities: the food of the field, which was round about every city, laid he up in the same.'); +INSERT INTO t1(docid,words) VALUES(1041049,'And Joseph gathered corn as the sand of the sea, very much, until he left numbering; for it was without number.'); +INSERT INTO t1(docid,words) VALUES(1041050,'And unto Joseph were born two sons before the years of famine came, which Asenath the daughter of Potipherah priest of On bare unto him.'); +INSERT INTO t1(docid,words) VALUES(1041051,'And Joseph called the name of the firstborn Manasseh: For God, said he, hath made me forget all my toil, and all my father''s house.'); +INSERT INTO t1(docid,words) VALUES(1041052,'And the name of the second called he Ephraim: For God hath caused me to be fruitful in the land of my affliction.'); +INSERT INTO t1(docid,words) VALUES(1041053,'And the seven years of plenteousness, that was in the land of Egypt, were ended.'); +INSERT INTO t1(docid,words) VALUES(1041054,'And the seven years of dearth began to come, according as Joseph had said: and the dearth was in all lands; but in all the land of Egypt there was bread.'); +INSERT INTO t1(docid,words) VALUES(1041055,'And when all the land of Egypt was famished, the people cried to Pharaoh for bread: and Pharaoh said unto all the Egyptians, Go unto Joseph; what he saith to you, do.'); +INSERT INTO t1(docid,words) VALUES(1041056,'And the famine was over all the face of the earth: and Joseph opened all the storehouses, and sold unto the Egyptians; and the famine waxed sore in the land of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1041057,'And all countries came into Egypt to Joseph for to buy corn; because that the famine was so sore in all lands.'); +INSERT INTO t1(docid,words) VALUES(1042001,'Now when Jacob saw that there was corn in Egypt, Jacob said unto his sons, Why do ye look one upon another?'); +INSERT INTO t1(docid,words) VALUES(1042002,'And he said, Behold, I have heard that there is corn in Egypt: get you down thither, and buy for us from thence; that we may live, and not die.'); +INSERT INTO t1(docid,words) VALUES(1042003,'And Joseph''s ten brethren went down to buy corn in Egypt.'); +INSERT INTO t1(docid,words) VALUES(1042004,'But Benjamin, Joseph''s brother, Jacob sent not with his brethren; for he said, Lest peradventure mischief befall him.'); +INSERT INTO t1(docid,words) VALUES(1042005,'And the sons of Israel came to buy corn among those that came: for the famine was in the land of Canaan.'); +INSERT INTO t1(docid,words) VALUES(1042006,'And Joseph was the governor over the land, and he it was that sold to all the people of the land: and Joseph''s brethren came, and bowed down themselves before him with their faces to the earth.'); +INSERT INTO t1(docid,words) VALUES(1042007,'And Joseph saw his brethren, and he knew them, but made himself strange unto them, and spake roughly unto them; and he said unto them, Whence come ye? And they said, From the land of Canaan to buy food.'); +INSERT INTO t1(docid,words) VALUES(1042008,'And Joseph knew his brethren, but they knew not him.'); +INSERT INTO t1(docid,words) VALUES(1042009,'And Joseph remembered the dreams which he dreamed of them, and said unto them, Ye are spies; to see the nakedness of the land ye are come.'); +INSERT INTO t1(docid,words) VALUES(1042010,'And they said unto him, Nay, my lord, but to buy food are thy servants come.'); +INSERT INTO t1(docid,words) VALUES(1042011,'We are all one man''s sons; we are true men, thy servants are no spies.'); +INSERT INTO t1(docid,words) VALUES(1042012,'And he said unto them, Nay, but to see the nakedness of the land ye are come.'); +INSERT INTO t1(docid,words) VALUES(1042013,'And they said, Thy servants are twelve brethren, the sons of one man in the land of Canaan; and, behold, the youngest is this day with our father, and one is not.'); +INSERT INTO t1(docid,words) VALUES(1042014,'And Joseph said unto them, That is it that I spake unto you, saying, Ye are spies:'); +INSERT INTO t1(docid,words) VALUES(1042015,'Hereby ye shall be proved: By the life of Pharaoh ye shall not go forth hence, except your youngest brother come hither.'); +INSERT INTO t1(docid,words) VALUES(1042016,'Send one of you, and let him fetch your brother, and ye shall be kept in prison, that your words may be proved, whether there be any truth in you: or else by the life of Pharaoh surely ye are spies.'); +INSERT INTO t1(docid,words) VALUES(1042017,'And he put them all together into ward three days.'); +INSERT INTO t1(docid,words) VALUES(1042018,'And Joseph said unto them the third day, This do, and live; for I fear God:'); +INSERT INTO t1(docid,words) VALUES(1042019,'If ye be true men, let one of your brethren be bound in the house of your prison: go ye, carry corn for the famine of your houses:'); +INSERT INTO t1(docid,words) VALUES(1042020,'But bring your youngest brother unto me; so shall your words be verified, and ye shall not die. And they did so.'); +INSERT INTO t1(docid,words) VALUES(1042021,'And they said one to another, We are verily guilty concerning our brother, in that we saw the anguish of his soul, when he besought us, and we would not hear; therefore is this distress come upon us.'); +INSERT INTO t1(docid,words) VALUES(1042022,'And Reuben answered them, saying, Spake I not unto you, saying, Do not sin against the child; and ye would not hear? therefore, behold, also his blood is required.'); +INSERT INTO t1(docid,words) VALUES(1042023,'And they knew not that Joseph understood them; for he spake unto them by an interpreter.'); +INSERT INTO t1(docid,words) VALUES(1042024,'And he turned himself about from them, and wept; and returned to them again, and communed with them, and took from them Simeon, and bound him before their eyes.'); +INSERT INTO t1(docid,words) VALUES(1042025,'Then Joseph commanded to fill their sacks with corn, and to restore every man''s money into his sack, and to give them provision for the way: and thus did he unto them.'); +INSERT INTO t1(docid,words) VALUES(1042026,'And they laded their asses with the corn, and departed thence.'); +INSERT INTO t1(docid,words) VALUES(1042027,'And as one of them opened his sack to give his ass provender in the inn, he espied his money; for, behold, it was in his sack''s mouth.'); +INSERT INTO t1(docid,words) VALUES(1042028,'And he said unto his brethren, My money is restored; and, lo, it is even in my sack: and their heart failed them, and they were afraid, saying one to another, What is this that God hath done unto us?'); +INSERT INTO t1(docid,words) VALUES(1042029,'And they came unto Jacob their father unto the land of Canaan, and told him all that befell unto them; saying,'); +INSERT INTO t1(docid,words) VALUES(1042030,'The man, who is the lord of the land, spake roughly to us, and took us for spies of the country.'); +INSERT INTO t1(docid,words) VALUES(1042031,'And we said unto him, We are true men; we are no spies:'); +INSERT INTO t1(docid,words) VALUES(1042032,'We be twelve brethren, sons of our father; one is not, and the youngest is this day with our father in the land of Canaan.'); +INSERT INTO t1(docid,words) VALUES(1042033,'And the man, the lord of the country, said unto us, Hereby shall I know that ye are true men; leave one of your brethren here with me, and take food for the famine of your households, and be gone:'); +INSERT INTO t1(docid,words) VALUES(1042034,'And bring your youngest brother unto me: then shall I know that ye are no spies, but that ye are true men: so will I deliver you your brother, and ye shall traffick in the land.'); +INSERT INTO t1(docid,words) VALUES(1042035,'And it came to pass as they emptied their sacks, that, behold, every man''s bundle of money was in his sack: and when both they and their father saw the bundles of money, they were afraid.'); +INSERT INTO t1(docid,words) VALUES(1042036,'And Jacob their father said unto them, Me have ye bereaved of my children: Joseph is not, and Simeon is not, and ye will take Benjamin away: all these things are against me.'); +INSERT INTO t1(docid,words) VALUES(1042037,'And Reuben spake unto his father, saying, Slay my two sons, if I bring him not to thee: deliver him into my hand, and I will bring him to thee again.'); +INSERT INTO t1(docid,words) VALUES(1042038,'And he said, My son shall not go down with you; for his brother is dead, and he is left alone: if mischief befall him by the way in the which ye go, then shall ye bring down my gray hairs with sorrow to the grave.'); +INSERT INTO t1(docid,words) VALUES(1043001,'And the famine was sore in the land.'); +INSERT INTO t1(docid,words) VALUES(1043002,'And it came to pass, when they had eaten up the corn which they had brought out of Egypt, their father said unto them, Go again, buy us a little food.'); +INSERT INTO t1(docid,words) VALUES(1043003,'And Judah spake unto him, saying, The man did solemnly protest unto us, saying, Ye shall not see my face, except your brother be with you.'); +INSERT INTO t1(docid,words) VALUES(1043004,'If thou wilt send our brother with us, we will go down and buy thee food:'); +INSERT INTO t1(docid,words) VALUES(1043005,'But if thou wilt not send him, we will not go down: for the man said unto us, Ye shall not see my face, except your brother be with you.'); +INSERT INTO t1(docid,words) VALUES(1043006,'And Israel said, Wherefore dealt ye so ill with me, as to tell the man whether ye had yet a brother?'); +INSERT INTO t1(docid,words) VALUES(1043007,'And they said, The man asked us straitly of our state, and of our kindred, saying, Is your father yet alive? have ye another brother? and we told him according to the tenor of these words: could we certainly know that he would say, Bring your brother down?'); +INSERT INTO t1(docid,words) VALUES(1043008,'And Judah said unto Israel his father, Send the lad with me, and we will arise and go; that we may live, and not die, both we, and thou, and also our little ones.'); +INSERT INTO t1(docid,words) VALUES(1043009,'I will be surety for him; of my hand shalt thou require him: if I bring him not unto thee, and set him before thee, then let me bear the blame for ever:'); +INSERT INTO t1(docid,words) VALUES(1043010,'For except we had lingered, surely now we had returned this second time.'); +INSERT INTO t1(docid,words) VALUES(1043011,'And their father Israel said unto them, If it must be so now, do this; take of the best fruits in the land in your vessels, and carry down the man a present, a little balm, and a little honey, spices, and myrrh, nuts, and almonds:'); +INSERT INTO t1(docid,words) VALUES(1043012,'And take double money in your hand; and the money that was brought again in the mouth of your sacks, carry it again in your hand; peradventure it was an oversight:'); +INSERT INTO t1(docid,words) VALUES(1043013,'Take also your brother, and arise, go again unto the man:'); +INSERT INTO t1(docid,words) VALUES(1043014,'And God Almighty give you mercy before the man, that he may send away your other brother, and Benjamin. If I be bereaved of my children, I am bereaved.'); +INSERT INTO t1(docid,words) VALUES(1043015,'And the men took that present, and they took double money in their hand and Benjamin; and rose up, and went down to Egypt, and stood before Joseph.'); +INSERT INTO t1(docid,words) VALUES(1043016,'And when Joseph saw Benjamin with them, he said to the ruler of his house, Bring these men home, and slay, and make ready; for these men shall dine with me at noon.'); +INSERT INTO t1(docid,words) VALUES(1043017,'And the man did as Joseph bade; and the man brought the men into Joseph''s house.'); +INSERT INTO t1(docid,words) VALUES(1043018,'And the men were afraid, because they were brought into Joseph''s house; and they said, Because of the money that was returned in our sacks at the first time are we brought in; that he may seek occasion against us, and fall upon us, and take us for bondmen, and our asses.'); +INSERT INTO t1(docid,words) VALUES(1043019,'And they came near to the steward of Joseph''s house, and they communed with him at the door of the house,'); +INSERT INTO t1(docid,words) VALUES(1043020,'And said, O sir, we came indeed down at the first time to buy food:'); +INSERT INTO t1(docid,words) VALUES(1043021,'And it came to pass, when we came to the inn, that we opened our sacks, and, behold, every man''s money was in the mouth of his sack, our money in full weight: and we have brought it again in our hand.'); +INSERT INTO t1(docid,words) VALUES(1043022,'And other money have we brought down in our hands to buy food: we cannot tell who put our money in our sacks.'); +INSERT INTO t1(docid,words) VALUES(1043023,'And he said, Peace be to you, fear not: your God, and the God of your father, hath given you treasure in your sacks: I had your money. And he brought Simeon out unto them.'); +INSERT INTO t1(docid,words) VALUES(1043024,'And the man brought the men into Joseph''s house, and gave them water, and they washed their feet; and he gave their asses provender.'); +INSERT INTO t1(docid,words) VALUES(1043025,'And they made ready the present against Joseph came at noon: for they heard that they should eat bread there.'); +INSERT INTO t1(docid,words) VALUES(1043026,'And when Joseph came home, they brought him the present which was in their hand into the house, and bowed themselves to him to the earth.'); +INSERT INTO t1(docid,words) VALUES(1043027,'And he asked them of their welfare, and said, Is your father well, the old man of whom ye spake? Is he yet alive?'); +INSERT INTO t1(docid,words) VALUES(1043028,'And they answered, Thy servant our father is in good health, he is yet alive. And they bowed down their heads, and made obeisance.'); +INSERT INTO t1(docid,words) VALUES(1043029,'And he lifted up his eyes, and saw his brother Benjamin, his mother''s son, and said, Is this your younger brother, of whom ye spake unto me? And he said, God be gracious unto thee, my son.'); +INSERT INTO t1(docid,words) VALUES(1043030,'And Joseph made haste; for his bowels did yearn upon his brother: and he sought where to weep; and he entered into his chamber, and wept there.'); +INSERT INTO t1(docid,words) VALUES(1043031,'And he washed his face, and went out, and refrained himself, and said, Set on bread.'); +INSERT INTO t1(docid,words) VALUES(1043032,'And they set on for him by himself, and for them by themselves, and for the Egyptians, which did eat with him, by themselves: because the Egyptians might not eat bread with the Hebrews; for that is an abomination unto the Egyptians.'); +INSERT INTO t1(docid,words) VALUES(1043033,'And they sat before him, the firstborn according to his birthright, and the youngest according to his youth: and the men marvelled one at another.'); +INSERT INTO t1(docid,words) VALUES(1043034,'And he took and sent messes unto them from before him: but Benjamin''s mess was five times so much as any of their''s. And they drank, and were merry with him.'); +INSERT INTO t1(docid,words) VALUES(1044001,'And he commanded the steward of his house, saying, Fill the men''s sacks with food, as much as they can carry, and put every man''s money in his sack''s mouth.'); +INSERT INTO t1(docid,words) VALUES(1044002,'And put my cup, the silver cup, in the sack''s mouth of the youngest, and his corn money. And he did according to the word that Joseph had spoken.'); +INSERT INTO t1(docid,words) VALUES(1044003,'As soon as the morning was light, the men were sent away, they and their asses.'); +INSERT INTO t1(docid,words) VALUES(1044004,'And when they were gone out of the city, and not yet far off, Joseph said unto his steward, Up, follow after the men; and when thou dost overtake them, say unto them, Wherefore have ye rewarded evil for good?'); +INSERT INTO t1(docid,words) VALUES(1044005,'Is not this it in which my lord drinketh, and whereby indeed he divineth? ye have done evil in so doing.'); +INSERT INTO t1(docid,words) VALUES(1044006,'And he overtook them, and he spake unto them these same words.'); +INSERT INTO t1(docid,words) VALUES(1044007,'And they said unto him, Wherefore saith my lord these words? God forbid that thy servants should do according to this thing:'); +INSERT INTO t1(docid,words) VALUES(1044008,'Behold, the money, which we found in our sacks'' mouths, we brought again unto thee out of the land of Canaan: how then should we steal out of thy lord''s house silver or gold?'); +INSERT INTO t1(docid,words) VALUES(1044009,'With whomsoever of thy servants it be found, both let him die, and we also will be my lord''s bondmen.'); +INSERT INTO t1(docid,words) VALUES(1044010,'And he said, Now also let it be according unto your words: he with whom it is found shall be my servant; and ye shall be blameless.'); +INSERT INTO t1(docid,words) VALUES(1044011,'Then they speedily took down every man his sack to the ground, and opened every man his sack.'); +INSERT INTO t1(docid,words) VALUES(1044012,'And he searched, and began at the eldest, and left at the youngest: and the cup was found in Benjamin''s sack.'); +INSERT INTO t1(docid,words) VALUES(1044013,'Then they rent their clothes, and laded every man his ass, and returned to the city.'); +INSERT INTO t1(docid,words) VALUES(1044014,'And Judah and his brethren came to Joseph''s house; for he was yet there: and they fell before him on the ground.'); +INSERT INTO t1(docid,words) VALUES(1044015,'And Joseph said unto them, What deed is this that ye have done? wot ye not that such a man as I can certainly divine?'); +INSERT INTO t1(docid,words) VALUES(1044016,'And Judah said, What shall we say unto my lord? what shall we speak? or how shall we clear ourselves? God hath found out the iniquity of thy servants: behold, we are my lord''s servants, both we, and he also with whom the cup is found.'); +INSERT INTO t1(docid,words) VALUES(1044017,'And he said, God forbid that I should do so: but the man in whose hand the cup is found, he shall be my servant; and as for you, get you up in peace unto your father.'); +INSERT INTO t1(docid,words) VALUES(1044018,'Then Judah came near unto him, and said, Oh my lord, let thy servant, I pray thee, speak a word in my lord''s ears, and let not thine anger burn against thy servant: for thou art even as Pharaoh.'); +INSERT INTO t1(docid,words) VALUES(1044019,'My lord asked his servants, saying, Have ye a father, or a brother?'); +INSERT INTO t1(docid,words) VALUES(1044020,'And we said unto my lord, We have a father, an old man, and a child of his old age, a little one; and his brother is dead, and he alone is left of his mother, and his father loveth him.'); +INSERT INTO t1(docid,words) VALUES(1044021,'And thou saidst unto thy servants, Bring him down unto me, that I may set mine eyes upon him.'); +INSERT INTO t1(docid,words) VALUES(1044022,'And we said unto my lord, The lad cannot leave his father: for if he should leave his father, his father would die.'); +INSERT INTO t1(docid,words) VALUES(1044023,'And thou saidst unto thy servants, Except your youngest brother come down with you, ye shall see my face no more.'); +INSERT INTO t1(docid,words) VALUES(1044024,'And it came to pass when we came up unto thy servant my father, we told him the words of my lord.'); +INSERT INTO t1(docid,words) VALUES(1044025,'And our father said, Go again, and buy us a little food.'); +INSERT INTO t1(docid,words) VALUES(1044026,'And we said, We cannot go down: if our youngest brother be with us, then will we go down: for we may not see the man''s face, except our youngest brother be with us.'); +INSERT INTO t1(docid,words) VALUES(1044027,'And thy servant my father said unto us, Ye know that my wife bare me two sons:'); +INSERT INTO t1(docid,words) VALUES(1044028,'And the one went out from me, and I said, Surely he is torn in pieces; and I saw him not since:'); +INSERT INTO t1(docid,words) VALUES(1044029,'And if ye take this also from me, and mischief befall him, ye shall bring down my gray hairs with sorrow to the grave.'); +INSERT INTO t1(docid,words) VALUES(1044030,'Now therefore when I come to thy servant my father, and the lad be not with us; seeing that his life is bound up in the lad''s life;'); +INSERT INTO t1(docid,words) VALUES(1044031,'It shall come to pass, when he seeth that the lad is not with us, that he will die: and thy servants shall bring down the gray hairs of thy servant our father with sorrow to the grave.'); +INSERT INTO t1(docid,words) VALUES(1044032,'For thy servant became surety for the lad unto my father, saying, If I bring him not unto thee, then I shall bear the blame to my father for ever.'); +INSERT INTO t1(docid,words) VALUES(1044033,'Now therefore, I pray thee, let thy servant abide instead of the lad a bondman to my lord; and let the lad go up with his brethren.'); +INSERT INTO t1(docid,words) VALUES(1044034,'For how shall I go up to my father, and the lad be not with me? lest peradventure I see the evil that shall come on my father.'); +INSERT INTO t1(docid,words) VALUES(1045001,'Then Joseph could not refrain himself before all them that stood by him; and he cried, Cause every man to go out from me. And there stood no man with him, while Joseph made himself known unto his brethren.'); +INSERT INTO t1(docid,words) VALUES(1045002,'And he wept aloud: and the Egyptians and the house of Pharaoh heard.'); +INSERT INTO t1(docid,words) VALUES(1045003,'And Joseph said unto his brethren, I am Joseph; doth my father yet live? And his brethren could not answer him; for they were troubled at his presence.'); +INSERT INTO t1(docid,words) VALUES(1045004,'And Joseph said unto his brethren, Come near to me, I pray you. And they came near. And he said, I am Joseph your brother, whom ye sold into Egypt.'); +INSERT INTO t1(docid,words) VALUES(1045005,'Now therefore be not grieved, nor angry with yourselves, that ye sold me hither: for God did send me before you to preserve life.'); +INSERT INTO t1(docid,words) VALUES(1045006,'For these two years hath the famine been in the land: and yet there are five years, in the which there shall neither be earing nor harvest.'); +INSERT INTO t1(docid,words) VALUES(1045007,'And God sent me before you to preserve you a posterity in the earth, and to save your lives by a great deliverance.'); +INSERT INTO t1(docid,words) VALUES(1045008,'So now it was not you that sent me hither, but God: and he hath made me a father to Pharaoh, and lord of all his house, and a ruler throughout all the land of Egypt.'); +INSERT INTO t1(docid,words) VALUES(1045009,'Haste ye, and go up to my father, and say unto him, Thus saith thy son Joseph, God hath made me lord of all Egypt: come down unto me, tarry not:'); +INSERT INTO t1(docid,words) VALUES(1045010,'And thou shalt dwell in the land of Goshen, and thou shalt be near unto me, thou, and thy children, and thy children''s children, and thy flocks, and thy herds, and all that thou hast:'); +INSERT INTO t1(docid,words) VALUES(1045011,'And there will I nourish thee; for yet there are five years of famine; lest thou, and thy household, and all that thou hast, come to poverty.'); +INSERT INTO t1(docid,words) VALUES(1045012,'And, behold, your eyes see, and the eyes of my brother Benjamin, that it is my mouth that speaketh unto you.'); +INSERT INTO t1(docid,words) VALUES(1045013,'And ye shall tell my father of all my glory in Egypt, and of all that ye have seen; and ye shall haste and bring down my father hither.'); +INSERT INTO t1(docid,words) VALUES(1045014,'And he fell upon his brother Benjamin''s neck, and wept; and Benjamin wept upon his neck.'); +INSERT INTO t1(docid,words) VALUES(1045015,'Moreover he kissed all his brethren, and wept upon them: and after that his brethren talked with him.'); +INSERT INTO t1(docid,words) VALUES(1045016,'And the fame thereof was heard in Pharaoh''s house, saying, Joseph''s brethren are come: and it pleased Pharaoh well, and his servants.'); +INSERT INTO t1(docid,words) VALUES(1045017,'And Pharaoh said unto Joseph, Say unto thy brethren, This do ye; lade your beasts, and go, get you unto the land of Canaan;'); +INSERT INTO t1(docid,words) VALUES(1045018,'And take your father and your households, and come unto me: and I will give you the good of the land of Egypt, and ye shall eat the fat of the land.'); +INSERT INTO t1(docid,words) VALUES(1045019,'Now thou art commanded, this do ye; take you wagons out of the land of Egypt for your little ones, and for your wives, and bring your father, and come.'); +INSERT INTO t1(docid,words) VALUES(1045020,'Also regard not your stuff; for the good of all the land of Egypt is your''s.'); +INSERT INTO t1(docid,words) VALUES(1045021,'And the children of Israel did so: and Joseph gave them wagons, according to the commandment of Pharaoh, and gave them provision for the way.'); +INSERT INTO t1(docid,words) VALUES(1045022,'To all of them he gave each man changes of raiment; but to Benjamin he gave three hundred pieces of silver, and five changes of raiment.'); +INSERT INTO t1(docid,words) VALUES(1045023,'And to his father he sent after this manner; ten asses laden with the good things of Egypt, and ten she asses laden with corn and bread and meat for his father by the way.'); +INSERT INTO t1(docid,words) VALUES(1045024,'So he sent his brethren away, and they departed: and he said unto them, See that ye fall not out by the way.'); +INSERT INTO t1(docid,words) VALUES(1045025,'And they went up out of Egypt, and came into the land of Canaan unto Jacob their father,'); +INSERT INTO t1(docid,words) VALUES(1045026,'And told him, saying, Joseph is yet alive, and he is governor over all the land of Egypt. And Jacob''s heart fainted, for he believed them not.'); +INSERT INTO t1(docid,words) VALUES(1045027,'And they told him all the words of Joseph, which he had said unto them: and when he saw the wagons which Joseph had sent to carry him, the spirit of Jacob their father revived:'); +INSERT INTO t1(docid,words) VALUES(1045028,'And Israel said, It is enough; Joseph my son is yet alive: I will go and see him before I die.'); +INSERT INTO t1(docid,words) VALUES(1046001,'And Israel took his journey with all that he had, and came to Beersheba, and offered sacrifices unto the God of his father Isaac.'); +INSERT INTO t1(docid,words) VALUES(1046002,'And God spake unto Israel in the visions of the night, and said, Jacob, Jacob. And he said, Here am I.'); +INSERT INTO t1(docid,words) VALUES(1046003,'And he said, I am God, the God of thy father: fear not to go down into Egypt; for I will there make of thee a great nation:'); +INSERT INTO t1(docid,words) VALUES(1046004,'I will go down with thee into Egypt; and I will also surely bring thee up again: and Joseph shall put his hand upon thine eyes.'); +INSERT INTO t1(docid,words) VALUES(1046005,'And Jacob rose up from Beersheba: and the sons of Israel carried Jacob their father, and their little ones, and their wives, in the wagons which Pharaoh had sent to carry him.'); +INSERT INTO t1(docid,words) VALUES(1046006,'And they took their cattle, and their goods, which they had gotten in the land of Canaan, and came into Egypt, Jacob, and all his seed with him:'); +INSERT INTO t1(docid,words) VALUES(1046007,'His sons, and his sons'' sons with him, his daughters, and his sons'' daughters, and all his seed brought he with him into Egypt.'); +INSERT INTO t1(docid,words) VALUES(1046008,'And these are the names of the children of Israel, which came into Egypt, Jacob and his sons: Reuben, Jacob''s firstborn.'); +INSERT INTO t1(docid,words) VALUES(1046009,'And the sons of Reuben; Hanoch, and Phallu, and Hezron, and Carmi.'); +INSERT INTO t1(docid,words) VALUES(1046010,'And the sons of Simeon; Jemuel, and Jamin, and Ohad, and Jachin, and Zohar, and Shaul the son of a Canaanitish woman.'); +INSERT INTO t1(docid,words) VALUES(1046011,'And the sons of Levi; Gershon, Kohath, and Merari.'); +INSERT INTO t1(docid,words) VALUES(1046012,'And the sons of Judah; Er, and Onan, and Shelah, and Pharez, and Zarah: but Er and Onan died in the land of Canaan. And the sons of Pharez were Hezron and Hamul.'); +INSERT INTO t1(docid,words) VALUES(1046013,'And the sons of Issachar; Tola, and Phuvah, and Job, and Shimron.'); +INSERT INTO t1(docid,words) VALUES(1046014,'And the sons of Zebulun; Sered, and Elon, and Jahleel.'); +INSERT INTO t1(docid,words) VALUES(1046015,'These be the sons of Leah, which she bare unto Jacob in Padanaram, with his daughter Dinah: all the souls of his sons and his daughters were thirty and three.'); +INSERT INTO t1(docid,words) VALUES(1046016,'And the sons of Gad; Ziphion, and Haggi, Shuni, and Ezbon, Eri, and Arodi, and Areli.'); +INSERT INTO t1(docid,words) VALUES(1046017,'And the sons of Asher; Jimnah, and Ishuah, and Isui, and Beriah, and Serah their sister: and the sons of Beriah; Heber, and Malchiel.'); +INSERT INTO t1(docid,words) VALUES(1046018,'These are the sons of Zilpah, whom Laban gave to Leah his daughter, and these she bare unto Jacob, even sixteen souls.'); +INSERT INTO t1(docid,words) VALUES(1046019,'The sons of Rachel Jacob''s wife; Joseph, and Benjamin.'); +INSERT INTO t1(docid,words) VALUES(1046020,'And unto Joseph in the land of Egypt were born Manasseh and Ephraim, which Asenath the daughter of Potipherah priest of On bare unto him.'); +INSERT INTO t1(docid,words) VALUES(1046021,'And the sons of Benjamin were Belah, and Becher, and Ashbel, Gera, and Naaman, Ehi, and Rosh, Muppim, and Huppim, and Ard.'); +INSERT INTO t1(docid,words) VALUES(1046022,'These are the sons of Rachel, which were born to Jacob: all the souls were fourteen.'); +INSERT INTO t1(docid,words) VALUES(1046023,'And the sons of Dan; Hushim.'); +INSERT INTO t1(docid,words) VALUES(1046024,'And the sons of Naphtali; Jahzeel, and Guni, and Jezer, and Shillem.'); +INSERT INTO t1(docid,words) VALUES(1046025,'These are the sons of Bilhah, which Laban gave unto Rachel his daughter, and she bare these unto Jacob: all the souls were seven.'); +INSERT INTO t1(docid,words) VALUES(1046026,'All the souls that came with Jacob into Egypt, which came out of his loins, besides Jacob''s sons'' wives, all the souls were threescore and six;'); +INSERT INTO t1(docid,words) VALUES(1046027,'And the sons of Joseph, which were born him in Egypt, were two souls: all the souls of the house of Jacob, which came into Egypt, were threescore and ten.'); +INSERT INTO t1(docid,words) VALUES(1046028,'And he sent Judah before him unto Joseph, to direct his face unto Goshen; and they came into the land of Goshen.'); +INSERT INTO t1(docid,words) VALUES(1046029,'And Joseph made ready his chariot, and went up to meet Israel his father, to Goshen, and presented himself unto him; and he fell on his neck, and wept on his neck a good while.'); +INSERT INTO t1(docid,words) VALUES(1046030,'And Israel said unto Joseph, Now let me die, since I have seen thy face, because thou art yet alive.'); +INSERT INTO t1(docid,words) VALUES(1046031,'And Joseph said unto his brethren, and unto his father''s house, I will go up, and shew Pharaoh, and say unto him, My brethren, and my father''s house, which were in the land of Canaan, are come unto me;'); +INSERT INTO t1(docid,words) VALUES(1046032,'And the men are shepherds, for their trade hath been to feed cattle; and they have brought their flocks, and their herds, and all that they have.'); +INSERT INTO t1(docid,words) VALUES(1046033,'And it shall come to pass, when Pharaoh shall call you, and shall say, What is your occupation?'); +INSERT INTO t1(docid,words) VALUES(1046034,'That ye shall say, Thy servants'' trade hath been about cattle from our youth even until now, both we, and also our fathers: that ye may dwell in the land of Goshen; for every shepherd is an abomination unto the Egyptians.'); +INSERT INTO t1(docid,words) VALUES(1047001,'Then Joseph came and told Pharaoh, and said, My father and my brethren, and their flocks, and their herds, and all that they have, are come out of the land of Canaan; and, behold, they are in the land of Goshen.'); +INSERT INTO t1(docid,words) VALUES(1047002,'And he took some of his brethren, even five men, and presented them unto Pharaoh.'); +INSERT INTO t1(docid,words) VALUES(1047003,'And Pharaoh said unto his brethren, What is your occupation? And they said unto Pharaoh, Thy servants are shepherds, both we, and also our fathers.'); +INSERT INTO t1(docid,words) VALUES(1047004,'They said morever unto Pharaoh, For to sojourn in the land are we come; for thy servants have no pasture for their flocks; for the famine is sore in the land of Canaan: now therefore, we pray thee, let thy servants dwell in the land of Goshen.'); +INSERT INTO t1(docid,words) VALUES(1047005,'And Pharaoh spake unto Joseph, saying, Thy father and thy brethren are come unto thee:'); +INSERT INTO t1(docid,words) VALUES(1047006,'The land of Egypt is before thee; in the best of the land make thy father and brethren to dwell; in the land of Goshen let them dwell: and if thou knowest any men of activity among them, then make them rulers over my cattle.'); +INSERT INTO t1(docid,words) VALUES(1047007,'And Joseph brought in Jacob his father, and set him before Pharaoh: and Jacob blessed Pharaoh.'); +INSERT INTO t1(docid,words) VALUES(1047008,'And Pharaoh said unto Jacob, How old art thou?'); +INSERT INTO t1(docid,words) VALUES(1047009,'And Jacob said unto Pharaoh, The days of the years of my pilgrimage are an hundred and thirty years: few and evil have the days of the years of my life been, and have not attained unto the days of the years of the life of my fathers in the days of their pilgrimage.'); +INSERT INTO t1(docid,words) VALUES(1047010,'And Jacob blessed Pharaoh, and went out from before Pharaoh.'); +INSERT INTO t1(docid,words) VALUES(1047011,'And Joseph placed his father and his brethren, and gave them a possession in the land of Egypt, in the best of the land, in the land of Rameses, as Pharaoh had commanded.'); +INSERT INTO t1(docid,words) VALUES(1047012,'And Joseph nourished his father, and his brethren, and all his father''s household, with bread, according to their families.'); +INSERT INTO t1(docid,words) VALUES(1047013,'And there was no bread in all the land; for the famine was very sore, so that the land of Egypt and all the land of Canaan fainted by reason of the famine.'); +INSERT INTO t1(docid,words) VALUES(1047014,'And Joseph gathered up all the money that was found in the land of Egypt, and in the land of Canaan, for the corn which they bought: and Joseph brought the money into Pharaoh''s house.'); +INSERT INTO t1(docid,words) VALUES(1047015,'And when money failed in the land of Egypt, and in the land of Canaan, all the Egyptians came unto Joseph, and said, Give us bread: for why should we die in thy presence? for the money faileth.'); +INSERT INTO t1(docid,words) VALUES(1047016,'And Joseph said, Give your cattle; and I will give you for your cattle, if money fail.'); +INSERT INTO t1(docid,words) VALUES(1047017,'And they brought their cattle unto Joseph: and Joseph gave them bread in exchange for horses, and for the flocks, and for the cattle of the herds, and for the asses: and he fed them with bread for all their cattle for that year.'); +INSERT INTO t1(docid,words) VALUES(1047018,'When that year was ended, they came unto him the second year, and said unto him, We will not hide it from my lord, how that our money is spent; my lord also hath our herds of cattle; there is not ought left in the sight of my lord, but our bodies, and our lands:'); +INSERT INTO t1(docid,words) VALUES(1047019,'Wherefore shall we die before thine eyes, both we and our land? buy us and our land for bread, and we and our land will be servants unto Pharaoh: and give us seed, that we may live, and not die, that the land be not desolate.'); +INSERT INTO t1(docid,words) VALUES(1047020,'And Joseph bought all the land of Egypt for Pharaoh; for the Egyptians sold every man his field, because the famine prevailed over them: so the land became Pharaoh''s.'); +INSERT INTO t1(docid,words) VALUES(1047021,'And as for the people, he removed them to cities from one end of the borders of Egypt even to the other end thereof.'); +INSERT INTO t1(docid,words) VALUES(1047022,'Only the land of the priests bought he not; for the priests had a portion assigned them of Pharaoh, and did eat their portion which Pharaoh gave them: wherefore they sold not their lands.'); +INSERT INTO t1(docid,words) VALUES(1047023,'Then Joseph said unto the people, Behold, I have bought you this day and your land for Pharaoh: lo, here is seed for you, and ye shall sow the land.'); +INSERT INTO t1(docid,words) VALUES(1047024,'And it shall come to pass in the increase, that ye shall give the fifth part unto Pharaoh, and four parts shall be your own, for seed of the field, and for your food, and for them of your households, and for food for your little ones.'); +INSERT INTO t1(docid,words) VALUES(1047025,'And they said, Thou hast saved our lives: let us find grace in the sight of my lord, and we will be Pharaoh''s servants.'); +INSERT INTO t1(docid,words) VALUES(1047026,'And Joseph made it a law over the land of Egypt unto this day, that Pharaoh should have the fifth part, except the land of the priests only, which became not Pharaoh''s.'); +INSERT INTO t1(docid,words) VALUES(1047027,'And Israel dwelt in the land of Egypt, in the country of Goshen; and they had possessions therein, and grew, and multiplied exceedingly.'); +INSERT INTO t1(docid,words) VALUES(1047028,'And Jacob lived in the land of Egypt seventeen years: so the whole age of Jacob was an hundred forty and seven years.'); +INSERT INTO t1(docid,words) VALUES(1047029,'And the time drew nigh that Israel must die: and he called his son Joseph, and said unto him, If now I have found grace in thy sight, put, I pray thee, thy hand under my thigh, and deal kindly and truly with me; bury me not, I pray thee, in Egypt:'); +INSERT INTO t1(docid,words) VALUES(1047030,'But I will lie with my fathers, and thou shalt carry me out of Egypt, and bury me in their buryingplace. And he said, I will do as thou hast said.'); +INSERT INTO t1(docid,words) VALUES(1047031,'And he said, Swear unto me. And he sware unto him. And Israel bowed himself upon the bed''s head.'); +INSERT INTO t1(docid,words) VALUES(1048001,'And it came to pass after these things, that one told Joseph, Behold, thy father is sick: and he took with him his two sons, Manasseh and Ephraim.'); +INSERT INTO t1(docid,words) VALUES(1048002,'And one told Jacob, and said, Behold, thy son Joseph cometh unto thee: and Israel strengthened himself, and sat upon the bed.'); +INSERT INTO t1(docid,words) VALUES(1048003,'And Jacob said unto Joseph, God Almighty appeared unto me at Luz in the land of Canaan, and blessed me,'); +INSERT INTO t1(docid,words) VALUES(1048004,'And said unto me, Behold, I will make thee fruitful, and multiply thee, and I will make of thee a multitude of people; and will give this land to thy seed after thee for an everlasting possession.'); +INSERT INTO t1(docid,words) VALUES(1048005,'And now thy two sons, Ephraim and Manasseh, which were born unto thee in the land of Egypt before I came unto thee into Egypt, are mine; as Reuben and Simeon, they shall be mine.'); +INSERT INTO t1(docid,words) VALUES(1048006,'And thy issue, which thou begettest after them, shall be thine, and shall be called after the name of their brethren in their inheritance.'); +INSERT INTO t1(docid,words) VALUES(1048007,'And as for me, when I came from Padan, Rachel died by me in the land of Canaan in the way, when yet there was but a little way to come unto Ephrath: and I buried her there in the way of Ephrath; the same is Bethlehem.'); +INSERT INTO t1(docid,words) VALUES(1048008,'And Israel beheld Joseph''s sons, and said, Who are these?'); +INSERT INTO t1(docid,words) VALUES(1048009,'And Joseph said unto his father, They are my sons, whom God hath given me in this place. And he said, Bring them, I pray thee, unto me, and I will bless them.'); +INSERT INTO t1(docid,words) VALUES(1048010,'Now the eyes of Israel were dim for age, so that he could not see. And he brought them near unto him; and he kissed them, and embraced them.'); +INSERT INTO t1(docid,words) VALUES(1048011,'And Israel said unto Joseph, I had not thought to see thy face: and, lo, God hath shewed me also thy seed.'); +INSERT INTO t1(docid,words) VALUES(1048012,'And Joseph brought them out from between his knees, and he bowed himself with his face to the earth.'); +INSERT INTO t1(docid,words) VALUES(1048013,'And Joseph took them both, Ephraim in his right hand toward Israel''s left hand, and Manasseh in his left hand toward Israel''s right hand, and brought them near unto him.'); +INSERT INTO t1(docid,words) VALUES(1048014,'And Israel stretched out his right hand, and laid it upon Ephraim''s head, who was the younger, and his left hand upon Manasseh''s head, guiding his hands wittingly; for Manasseh was the firstborn.'); +INSERT INTO t1(docid,words) VALUES(1048015,'And he blessed Joseph, and said, God, before whom my fathers Abraham and Isaac did walk, the God which fed me all my life long unto this day,'); +INSERT INTO t1(docid,words) VALUES(1048016,'The Angel which redeemed me from all evil, bless the lads; and let my name be named on them, and the name of my fathers Abraham and Isaac; and let them grow into a multitude in the midst of the earth.'); +INSERT INTO t1(docid,words) VALUES(1048017,'And when Joseph saw that his father laid his right hand upon the head of Ephraim, it displeased him: and he held up his father''s hand, to remove it from Ephraim''s head unto Manasseh''s head.'); +INSERT INTO t1(docid,words) VALUES(1048018,'And Joseph said unto his father, Not so, my father: for this is the firstborn; put thy right hand upon his head.'); +INSERT INTO t1(docid,words) VALUES(1048019,'And his father refused, and said, I know it, my son, I know it: he also shall become a people, and he also shall be great: but truly his younger brother shall be greater than he, and his seed shall become a multitude of nations.'); +INSERT INTO t1(docid,words) VALUES(1048020,'And he blessed them that day, saying, In thee shall Israel bless, saying, God make thee as Ephraim and as Manasseh: and he set Ephraim before Manasseh.'); +INSERT INTO t1(docid,words) VALUES(1048021,'And Israel said unto Joseph, Behold, I die: but God shall be with you, and bring you again unto the land of your fathers.'); +INSERT INTO t1(docid,words) VALUES(1048022,'Moreover I have given to thee one portion above thy brethren, which I took out of the hand of the Amorite with my sword and with my bow.'); +INSERT INTO t1(docid,words) VALUES(1049001,'And Jacob called unto his sons, and said, Gather yourselves together, that I may tell you that which shall befall you in the last days.'); +INSERT INTO t1(docid,words) VALUES(1049002,'Gather yourselves together, and hear, ye sons of Jacob; and hearken unto Israel your father.'); +INSERT INTO t1(docid,words) VALUES(1049003,'Reuben, thou art my firstborn, my might, and the beginning of my strength, the excellency of dignity, and the excellency of power:'); +INSERT INTO t1(docid,words) VALUES(1049004,'Unstable as water, thou shalt not excel; because thou wentest up to thy father''s bed; then defiledst thou it: he went up to my couch.'); +INSERT INTO t1(docid,words) VALUES(1049005,'Simeon and Levi are brethren; instruments of cruelty are in their habitations.'); +INSERT INTO t1(docid,words) VALUES(1049006,'O my soul, come not thou into their secret; unto their assembly, mine honour, be not thou united: for in their anger they slew a man, and in their selfwill they digged down a wall.'); +INSERT INTO t1(docid,words) VALUES(1049007,'Cursed be their anger, for it was fierce; and their wrath, for it was cruel: I will divide them in Jacob, and scatter them in Israel.'); +INSERT INTO t1(docid,words) VALUES(1049008,'Judah, thou art he whom thy brethren shall praise: thy hand shall be in the neck of thine enemies; thy father''s children shall bow down before thee.'); +INSERT INTO t1(docid,words) VALUES(1049009,'Judah is a lion''s whelp: from the prey, my son, thou art gone up: he stooped down, he couched as a lion, and as an old lion; who shall rouse him up?'); +INSERT INTO t1(docid,words) VALUES(1049010,'The sceptre shall not depart from Judah, nor a lawgiver from between his feet, until Shiloh come; and unto him shall the gathering of the people be.'); +INSERT INTO t1(docid,words) VALUES(1049011,'Binding his foal unto the vine, and his ass''s colt unto the choice vine; he washed his garments in wine, and his clothes in the blood of grapes:'); +INSERT INTO t1(docid,words) VALUES(1049012,'His eyes shall be red with wine, and his teeth white with milk.'); +INSERT INTO t1(docid,words) VALUES(1049013,'Zebulun shall dwell at the haven of the sea; and he shall be for an haven of ships; and his border shall be unto Zidon.'); +INSERT INTO t1(docid,words) VALUES(1049014,'Issachar is a strong ass couching down between two burdens:'); +INSERT INTO t1(docid,words) VALUES(1049015,'And he saw that rest was good, and the land that it was pleasant; and bowed his shoulder to bear, and became a servant unto tribute.'); +INSERT INTO t1(docid,words) VALUES(1049016,'Dan shall judge his people, as one of the tribes of Israel.'); +INSERT INTO t1(docid,words) VALUES(1049017,'Dan shall be a serpent by the way, an adder in the path, that biteth the horse heels, so that his rider shall fall backward.'); +INSERT INTO t1(docid,words) VALUES(1049018,'I have waited for thy salvation, O LORD.'); +INSERT INTO t1(docid,words) VALUES(1049019,'Gad, a troop shall overcome him: but he shall overcome at the last.'); +INSERT INTO t1(docid,words) VALUES(1049020,'Out of Asher his bread shall be fat, and he shall yield royal dainties.'); +INSERT INTO t1(docid,words) VALUES(1049021,'Naphtali is a hind let loose: he giveth goodly words.'); +INSERT INTO t1(docid,words) VALUES(1049022,'Joseph is a fruitful bough, even a fruitful bough by a well; whose branches run over the wall:'); +INSERT INTO t1(docid,words) VALUES(1049023,'The archers have sorely grieved him, and shot at him, and hated him:'); +INSERT INTO t1(docid,words) VALUES(1049024,'But his bow abode in strength, and the arms of his hands were made strong by the hands of the mighty God of Jacob; (from thence is the shepherd, the stone of Israel:)'); +INSERT INTO t1(docid,words) VALUES(1049025,'Even by the God of thy father, who shall help thee; and by the Almighty, who shall bless thee with blessings of heaven above, blessings of the deep that lieth under, blessings of the breasts, and of the womb:'); +INSERT INTO t1(docid,words) VALUES(1049026,'The blessings of thy father have prevailed above the blessings of my progenitors unto the utmost bound of the everlasting hills: they shall be on the head of Joseph, and on the crown of the head of him that was separate from his brethren.'); +INSERT INTO t1(docid,words) VALUES(1049027,'Benjamin shall ravin as a wolf: in the morning he shall devour the prey, and at night he shall divide the spoil.'); +INSERT INTO t1(docid,words) VALUES(1049028,'All these are the twelve tribes of Israel: and this is it that their father spake unto them, and blessed them; every one according to his blessing he blessed them.'); +INSERT INTO t1(docid,words) VALUES(1049029,'And he charged them, and said unto them, I am to be gathered unto my people: bury me with my fathers in the cave that is in the field of Ephron the Hittite,'); +INSERT INTO t1(docid,words) VALUES(1049030,'In the cave that is in the field of Machpelah, which is before Mamre, in the land of Canaan, which Abraham bought with the field of Ephron the Hittite for a possession of a buryingplace.'); +INSERT INTO t1(docid,words) VALUES(1049031,'There they buried Abraham and Sarah his wife; there they buried Isaac and Rebekah his wife; and there I buried Leah.'); +INSERT INTO t1(docid,words) VALUES(1049032,'The purchase of the field and of the cave that is therein was from the children of Heth.'); +INSERT INTO t1(docid,words) VALUES(1049033,'And when Jacob had made an end of commanding his sons, he gathered up his feet into the bed, and yielded up the ghost, and was gathered unto his people.'); +INSERT INTO t1(docid,words) VALUES(1050001,'And Joseph fell upon his father''s face, and wept upon him, and kissed him.'); +INSERT INTO t1(docid,words) VALUES(1050002,'And Joseph commanded his servants the physicians to embalm his father: and the physicians embalmed Israel.'); +INSERT INTO t1(docid,words) VALUES(1050003,'And forty days were fulfilled for him; for so are fulfilled the days of those which are embalmed: and the Egyptians mourned for him threescore and ten days.'); +INSERT INTO t1(docid,words) VALUES(1050004,'And when the days of his mourning were past, Joseph spake unto the house of Pharaoh, saying, If now I have found grace in your eyes, speak, I pray you, in the ears of Pharaoh, saying,'); +INSERT INTO t1(docid,words) VALUES(1050005,'My father made me swear, saying, Lo, I die: in my grave which I have digged for me in the land of Canaan, there shalt thou bury me. Now therefore let me go up, I pray thee, and bury my father, and I will come again.'); +INSERT INTO t1(docid,words) VALUES(1050006,'And Pharaoh said, Go up, and bury thy father, according as he made thee swear.'); +INSERT INTO t1(docid,words) VALUES(1050007,'And Joseph went up to bury his father: and with him went up all the servants of Pharaoh, the elders of his house, and all the elders of the land of Egypt,'); +INSERT INTO t1(docid,words) VALUES(1050008,'And all the house of Joseph, and his brethren, and his father''s house: only their little ones, and their flocks, and their herds, they left in the land of Goshen.'); +INSERT INTO t1(docid,words) VALUES(1050009,'And there went up with him both chariots and horsemen: and it was a very great company.'); +INSERT INTO t1(docid,words) VALUES(1050010,'And they came to the threshingfloor of Atad, which is beyond Jordan, and there they mourned with a great and very sore lamentation: and he made a mourning for his father seven days.'); +INSERT INTO t1(docid,words) VALUES(1050011,'And when the inhabitants of the land, the Canaanites, saw the mourning in the floor of Atad, they said, This is a grievous mourning to the Egyptians: wherefore the name of it was called Abelmizraim, which is beyond Jordan.'); +INSERT INTO t1(docid,words) VALUES(1050012,'And his sons did unto him according as he commanded them:'); +INSERT INTO t1(docid,words) VALUES(1050013,'For his sons carried him into the land of Canaan, and buried him in the cave of the field of Machpelah, which Abraham bought with the field for a possession of a buryingplace of Ephron the Hittite, before Mamre.'); +INSERT INTO t1(docid,words) VALUES(1050014,'And Joseph returned into Egypt, he, and his brethren, and all that went up with him to bury his father, after he had buried his father.'); +INSERT INTO t1(docid,words) VALUES(1050015,'And when Joseph''s brethren saw that their father was dead, they said, Joseph will peradventure hate us, and will certainly requite us all the evil which we did unto him.'); +INSERT INTO t1(docid,words) VALUES(1050016,'And they sent a messenger unto Joseph, saying, Thy father did command before he died, saying,'); +INSERT INTO t1(docid,words) VALUES(1050017,'So shall ye say unto Joseph, Forgive, I pray thee now, the trespass of thy brethren, and their sin; for they did unto thee evil: and now, we pray thee, forgive the trespass of the servants of the God of thy father. And Joseph wept when they spake unto him.'); +INSERT INTO t1(docid,words) VALUES(1050018,'And his brethren also went and fell down before his face; and they said, Behold, we be thy servants.'); +INSERT INTO t1(docid,words) VALUES(1050019,'And Joseph said unto them, Fear not: for am I in the place of God?'); +INSERT INTO t1(docid,words) VALUES(1050020,'But as for you, ye thought evil against me; but God meant it unto good, to bring to pass, as it is this day, to save much people alive.'); +INSERT INTO t1(docid,words) VALUES(1050021,'Now therefore fear ye not: I will nourish you, and your little ones. And he comforted them, and spake kindly unto them.'); +INSERT INTO t1(docid,words) VALUES(1050022,'And Joseph dwelt in Egypt, he, and his father''s house: and Joseph lived an hundred and ten years.'); +INSERT INTO t1(docid,words) VALUES(1050023,'And Joseph saw Ephraim''s children of the third generation: the children also of Machir the son of Manasseh were brought up upon Joseph''s knees.'); +INSERT INTO t1(docid,words) VALUES(1050024,'And Joseph said unto his brethren, I die: and God will surely visit you, and bring you out of this land unto the land which he sware to Abraham, to Isaac, and to Jacob.'); +INSERT INTO t1(docid,words) VALUES(1050025,'And Joseph took an oath of the children of Israel, saying, God will surely visit you, and ye shall carry up my bones from hence.'); +INSERT INTO t1(docid,words) VALUES(1050026,'So Joseph died, being an hundred and ten years old: and they embalmed him, and he was put in a coffin in Egypt.'); +COMMIT; +} +} diff --git a/components/external/SQLite-3.8.1/test/hook.test b/components/external/SQLite-3.8.1/test/hook.test new file mode 100644 index 0000000000000000000000000000000000000000..6346cc77a7a8239611ad84a4174011f4febdd71a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/hook.test @@ -0,0 +1,393 @@ +# 2004 Jan 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for TCL interface to the +# SQLite library. +# +# The focus of the tests in this file is the following interface: +# +# sqlite_commit_hook (tests hook-1..hook-3 inclusive) +# sqlite_update_hook (tests hook-4-*) +# sqlite_rollback_hook (tests hook-5.*) +# +# $Id: hook.test,v 1.15 2009/04/07 14:14:23 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test hook-1.2 { + db commit_hook +} {} + + +do_test hook-3.1 { + set commit_cnt 0 + proc commit_hook {} { + incr ::commit_cnt + return 0 + } + db commit_hook ::commit_hook + db commit_hook +} {::commit_hook} +do_test hook-3.2 { + set commit_cnt +} {0} +do_test hook-3.3 { + execsql { + CREATE TABLE t2(a,b); + } + set commit_cnt +} {1} +do_test hook-3.4 { + execsql { + INSERT INTO t2 VALUES(1,2); + INSERT INTO t2 SELECT a+1, b+1 FROM t2; + INSERT INTO t2 SELECT a+2, b+2 FROM t2; + } + set commit_cnt +} {4} +do_test hook-3.5 { + set commit_cnt {} + proc commit_hook {} { + set ::commit_cnt [execsql {SELECT * FROM t2}] + return 0 + } + execsql { + INSERT INTO t2 VALUES(5,6); + } + set commit_cnt +} {1 2 2 3 3 4 4 5 5 6} +do_test hook-3.6 { + set commit_cnt {} + proc commit_hook {} { + set ::commit_cnt [execsql {SELECT * FROM t2}] + return 1 + } + catchsql { + INSERT INTO t2 VALUES(6,7); + } +} {1 {constraint failed}} +verify_ex_errcode hook-3.6b SQLITE_CONSTRAINT_COMMITHOOK +do_test hook-3.7 { + set ::commit_cnt +} {1 2 2 3 3 4 4 5 5 6 6 7} +do_test hook-3.8 { + execsql {SELECT * FROM t2} +} {1 2 2 3 3 4 4 5 5 6} + +# Test turnning off the commit hook +# +do_test hook-3.9 { + db commit_hook {} + set ::commit_cnt {} + execsql { + INSERT INTO t2 VALUES(7,8); + } + set ::commit_cnt +} {} + +# Ticket #3564. +# +do_test hook-3.10 { + forcedelete test2.db test2.db-journal + sqlite3 db2 test2.db + proc commit_hook {} { + set y [db2 one {SELECT y FROM t3 WHERE y>10}] + return [expr {$y>10}] + } + db2 eval {CREATE TABLE t3(x,y)} + db2 commit_hook commit_hook + catchsql {INSERT INTO t3 VALUES(1,2)} db2 + catchsql {INSERT INTO t3 VALUES(11,12)} db2 + catchsql {INSERT INTO t3 VALUES(3,4)} db2 + db2 eval { + SELECT * FROM t3 ORDER BY x; + } +} {1 2 3 4} +db2 close + + +#---------------------------------------------------------------------------- +# Tests for the update-hook. +# +# 4.1.* - Very simple tests. Test that the update hook is invoked correctly +# for INSERT, DELETE and UPDATE statements, including DELETE +# statements with no WHERE clause. +# 4.2.* - Check that the update-hook is invoked for rows modified by trigger +# bodies. Also that the database name is correctly reported when +# an attached database is modified. +# 4.3.* - Do some sorting, grouping, compound queries, population and +# depopulation of indices, to make sure the update-hook is not +# invoked incorrectly. +# + +# Simple tests +do_test hook-4.1.1 { + catchsql { + DROP TABLE t1; + } + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t1 VALUES(3, 'three'); + } + db update_hook [list lappend ::update_hook] +} {} +do_test hook-4.1.2 { + execsql { + INSERT INTO t1 VALUES(4, 'four'); + DELETE FROM t1 WHERE b = 'two'; + UPDATE t1 SET b = '' WHERE a = 1 OR a = 3; + DELETE FROM t1 WHERE 1; -- Avoid the truncate optimization (for now) + } + set ::update_hook +} [list \ + INSERT main t1 4 \ + DELETE main t1 2 \ + UPDATE main t1 1 \ + UPDATE main t1 3 \ + DELETE main t1 1 \ + DELETE main t1 3 \ + DELETE main t1 4 \ +] + +ifcapable trigger { + # Update hook is not invoked for changes to sqlite_master + # + do_test hook-4.1.3 { + set ::update_hook {} + execsql { + CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN SELECT RAISE(IGNORE); END; + } + set ::update_hook + } {} + do_test hook-4.1.4 { + set ::update_hook {} + execsql { + DROP TRIGGER r1; + } + set ::update_hook + } {} + + set ::update_hook {} + do_test hook-4.2.1 { + catchsql { + DROP TABLE t2; + } + execsql { + CREATE TABLE t2(c INTEGER PRIMARY KEY, d); + CREATE TRIGGER t1_trigger AFTER INSERT ON t1 BEGIN + INSERT INTO t2 VALUES(new.a, new.b); + UPDATE t2 SET d = d || ' via trigger' WHERE new.a = c; + DELETE FROM t2 WHERE new.a = c; + END; + } + } {} + do_test hook-4.2.2 { + execsql { + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + } + set ::update_hook + } [list \ + INSERT main t1 1 \ + INSERT main t2 1 \ + UPDATE main t2 1 \ + DELETE main t2 1 \ + INSERT main t1 2 \ + INSERT main t2 2 \ + UPDATE main t2 2 \ + DELETE main t2 2 \ + ] +} else { + execsql { + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + } +} + +# Update-hook + ATTACH +set ::update_hook {} +ifcapable attach { + do_test hook-4.2.3 { + forcedelete test2.db + execsql { + ATTACH 'test2.db' AS aux; + CREATE TABLE aux.t3(a INTEGER PRIMARY KEY, b); + INSERT INTO aux.t3 SELECT * FROM t1; + UPDATE t3 SET b = 'two or so' WHERE a = 2; + DELETE FROM t3 WHERE 1; -- Avoid the truncate optimization (for now) + } + set ::update_hook + } [list \ + INSERT aux t3 1 \ + INSERT aux t3 2 \ + UPDATE aux t3 2 \ + DELETE aux t3 1 \ + DELETE aux t3 2 \ + ] +} + +ifcapable trigger { + execsql { + DROP TRIGGER t1_trigger; + } +} + +# Test that other vdbe operations involving btree structures do not +# incorrectly invoke the update-hook. +set ::update_hook {} +do_test hook-4.3.1 { + execsql { + CREATE INDEX t1_i ON t1(b); + INSERT INTO t1 VALUES(3, 'three'); + UPDATE t1 SET b = ''; + DELETE FROM t1 WHERE a > 1; + } + set ::update_hook +} [list \ + INSERT main t1 3 \ + UPDATE main t1 1 \ + UPDATE main t1 2 \ + UPDATE main t1 3 \ + DELETE main t1 2 \ + DELETE main t1 3 \ +] +set ::update_hook {} +ifcapable compound&&attach { + do_test hook-4.3.2 { + execsql { + SELECT * FROM t1 UNION SELECT * FROM t3; + SELECT * FROM t1 UNION ALL SELECT * FROM t3; + SELECT * FROM t1 INTERSECT SELECT * FROM t3; + SELECT * FROM t1 EXCEPT SELECT * FROM t3; + SELECT * FROM t1 ORDER BY b; + SELECT * FROM t1 GROUP BY b; + } + set ::update_hook + } [list] +} + +do_test hook-4.4 { + execsql { + CREATE TABLE t4(a UNIQUE, b); + INSERT INTO t4 VALUES(1, 'a'); + INSERT INTO t4 VALUES(2, 'b'); + } + set ::update_hook [list] + execsql { + REPLACE INTO t4 VALUES(1, 'c'); + } + set ::update_hook +} [list INSERT main t4 3 ] +do_execsql_test hook-4.4.1 { + SELECT * FROM t4 ORDER BY a; +} {1 c 2 b} +do_test hook-4.4.2 { + set ::update_hook [list] + execsql { + PRAGMA recursive_triggers = on; + REPLACE INTO t4 VALUES(1, 'd'); + } + set ::update_hook +} [list INSERT main t4 4 ] +do_execsql_test hook-4.4.3 { + SELECT * FROM t4 ORDER BY a; +} {1 d 2 b} + +db update_hook {} +# +#---------------------------------------------------------------------------- + +#---------------------------------------------------------------------------- +# Test the rollback-hook. The rollback-hook is a bit more complicated than +# either the commit or update hooks because a rollback can happen +# explicitly (an sql ROLLBACK statement) or implicitly (a constraint or +# error condition). +# +# hook-5.1.* - Test explicit rollbacks. +# hook-5.2.* - Test implicit rollbacks caused by constraint failure. +# +# hook-5.3.* - Test implicit rollbacks caused by IO errors. +# hook-5.4.* - Test implicit rollbacks caused by malloc() failure. +# hook-5.5.* - Test hot-journal rollbacks. Or should the rollback hook +# not be called for these? +# + +do_test hook-5.0 { + # Configure the rollback hook to increment global variable + # $::rollback_hook each time it is invoked. + set ::rollback_hook 0 + db rollback_hook [list incr ::rollback_hook] +} {} + +# Test explicit rollbacks. Not much can really go wrong here. +# +do_test hook-5.1.1 { + set ::rollback_hook 0 + execsql { + BEGIN; + ROLLBACK; + } + set ::rollback_hook +} {1} + +# Test implicit rollbacks caused by constraints. +# +do_test hook-5.2.1 { + set ::rollback_hook 0 + catchsql { + DROP TABLE t1; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES('one', 'I'); + INSERT INTO t1 VALUES('one', 'I'); + } + set ::rollback_hook +} {1} +do_test hook-5.2.2 { + # Check that the INSERT transaction above really was rolled back. + execsql { + SELECT count(*) FROM t1; + } +} {1} + +# +# End rollback-hook testing. +#---------------------------------------------------------------------------- + +#---------------------------------------------------------------------------- +# Test that if a commit-hook returns non-zero (causing a rollback), the +# rollback-hook is invoked. +# +proc commit_hook {} { + lappend ::hooks COMMIT + return 1 +} +proc rollback_hook {} { + lappend ::hooks ROLLBACK +} +do_test hook-6.1 { + set ::hooks [list] + db commit_hook commit_hook + db rollback_hook rollback_hook + catchsql { + BEGIN; + INSERT INTO t1 VALUES('two', 'II'); + COMMIT; + } + execsql { SELECT * FROM t1 } +} {one I} +do_test hook-6.2 { + set ::hooks +} {COMMIT ROLLBACK} +unset ::hooks + +finish_test diff --git a/components/external/SQLite-3.8.1/test/icu.test b/components/external/SQLite-3.8.1/test/icu.test new file mode 100644 index 0000000000000000000000000000000000000000..73cb9b913e95b594440e861c353722ea6f05b954 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/icu.test @@ -0,0 +1,136 @@ +# 2007 May 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: icu.test,v 1.2 2008/07/12 14:52:20 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !icu { + finish_test + return +} + +# Create a table to work with. +# +execsql {CREATE TABLE test1(i1 int, i2 int, r1 real, r2 real, t1 text, t2 text)} +execsql {INSERT INTO test1 VALUES(1,2,1.1,2.2,'hello','world')} +proc test_expr {name settings expr result} { + do_test $name [format { + lindex [db eval { + BEGIN; + UPDATE test1 SET %s; + SELECT %s FROM test1; + ROLLBACK; + }] 0 + } $settings $expr] $result +} + +# Tests of the REGEXP operator. +# +test_expr icu-1.1 {i1='hello'} {i1 REGEXP 'hello'} 1 +test_expr icu-1.2 {i1='hello'} {i1 REGEXP '.ello'} 1 +test_expr icu-1.3 {i1='hello'} {i1 REGEXP '.ell'} 0 +test_expr icu-1.4 {i1='hello'} {i1 REGEXP '.ell.*'} 1 +test_expr icu-1.5 {i1=NULL} {i1 REGEXP '.ell.*'} {} + +# Some non-ascii characters with defined case mappings +# +set ::EGRAVE "\xC8" +set ::egrave "\xE8" + +set ::OGRAVE "\xD2" +set ::ograve "\xF2" + +# That German letter that looks a bit like a B. The +# upper-case version of which is "SS" (two characters). +# +set ::szlig "\xDF" + +# Tests of the upper()/lower() functions. +# +test_expr icu-2.1 {i1='HellO WorlD'} {upper(i1)} {HELLO WORLD} +test_expr icu-2.2 {i1='HellO WorlD'} {lower(i1)} {hello world} +test_expr icu-2.3 {i1=$::egrave} {lower(i1)} $::egrave +test_expr icu-2.4 {i1=$::egrave} {upper(i1)} $::EGRAVE +test_expr icu-2.5 {i1=$::ograve} {lower(i1)} $::ograve +test_expr icu-2.6 {i1=$::ograve} {upper(i1)} $::OGRAVE +test_expr icu-2.3 {i1=$::EGRAVE} {lower(i1)} $::egrave +test_expr icu-2.4 {i1=$::EGRAVE} {upper(i1)} $::EGRAVE +test_expr icu-2.5 {i1=$::OGRAVE} {lower(i1)} $::ograve +test_expr icu-2.6 {i1=$::OGRAVE} {upper(i1)} $::OGRAVE + +test_expr icu-2.7 {i1=$::szlig} {upper(i1)} "SS" +test_expr icu-2.8 {i1='SS'} {lower(i1)} "ss" + +# In turkish (locale="tr_TR"), the lower case version of I +# is "small dotless i" (code point 0x131 (decimal 305)). +# +set ::small_dotless_i "\u0131" +test_expr icu-3.1 {i1='I'} {lower(i1)} "i" +test_expr icu-3.2 {i1='I'} {lower(i1, 'tr_tr')} $::small_dotless_i +test_expr icu-3.3 {i1='I'} {lower(i1, 'en_AU')} "i" + +#-------------------------------------------------------------------- +# Test the collation sequence function. +# +do_test icu-4.1 { + execsql { + CREATE TABLE fruit(name); + INSERT INTO fruit VALUES('plum'); + INSERT INTO fruit VALUES('cherry'); + INSERT INTO fruit VALUES('apricot'); + INSERT INTO fruit VALUES('peach'); + INSERT INTO fruit VALUES('chokecherry'); + INSERT INTO fruit VALUES('yamot'); + } +} {} +do_test icu-4.2 { + execsql { + SELECT icu_load_collation('en_US', 'AmericanEnglish'); + SELECT icu_load_collation('lt_LT', 'Lithuanian'); + } + execsql { + SELECT name FROM fruit ORDER BY name COLLATE AmericanEnglish ASC; + } +} {apricot cherry chokecherry peach plum yamot} + + +# Test collation using Lithuanian rules. In the Lithuanian +# alphabet, "y" comes right after "i". +# +do_test icu-4.3 { + execsql { + SELECT name FROM fruit ORDER BY name COLLATE Lithuanian ASC; + } +} {apricot cherry chokecherry yamot peach plum} + +#------------------------------------------------------------------------- +# Test that it is not possible to call the ICU regex() function with +# anything other than exactly two arguments. See also: +# +# http://src.chromium.org/viewvc/chrome/trunk/src/third_party/sqlite/icu-regexp.patch?revision=34807&view=markup +# +do_catchsql_test icu-5.1 { SELECT regexp('a[abc]c.*', 'abc') } {0 1} +do_catchsql_test icu-5.2 { + SELECT regexp('a[abc]c.*') +} {1 {wrong number of arguments to function regexp()}} +do_catchsql_test icu-5.3 { + SELECT regexp('a[abc]c.*', 'abc', 'c') +} {1 {wrong number of arguments to function regexp()}} +do_catchsql_test icu-5.4 { + SELECT 'abc' REGEXP 'a[abc]c.*' +} {0 1} +do_catchsql_test icu-5.4 { SELECT 'abc' REGEXP } {1 {near " ": syntax error}} +do_catchsql_test icu-5.5 { SELECT 'abc' REGEXP, 1 } {1 {near ",": syntax error}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/in.test b/components/external/SQLite-3.8.1/test/in.test new file mode 100644 index 0000000000000000000000000000000000000000..3b23f04bbfe5bad2c32d0a88a50d38391f5dc981 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/in.test @@ -0,0 +1,623 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the IN and BETWEEN operator. +# +# $Id: in.test,v 1.22 2008/08/04 03:51:24 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Generate the test data we will need for the first squences of tests. +# +do_test in-1.0 { + execsql { + BEGIN; + CREATE TABLE t1(a int, b int); + } + for {set i 1} {$i<=10} {incr i} { + execsql "INSERT INTO t1 VALUES($i,[expr {1<<$i}])" + } + execsql { + COMMIT; + SELECT count(*) FROM t1; + } +} {10} + +# Do basic testing of BETWEEN. +# +do_test in-1.1 { + execsql {SELECT a FROM t1 WHERE b BETWEEN 10 AND 50 ORDER BY a} +} {4 5} +do_test in-1.2 { + execsql {SELECT a FROM t1 WHERE b NOT BETWEEN 10 AND 50 ORDER BY a} +} {1 2 3 6 7 8 9 10} +do_test in-1.3 { + execsql {SELECT a FROM t1 WHERE b BETWEEN a AND a*5 ORDER BY a} +} {1 2 3 4} +do_test in-1.4 { + execsql {SELECT a FROM t1 WHERE b NOT BETWEEN a AND a*5 ORDER BY a} +} {5 6 7 8 9 10} +do_test in-1.6 { + execsql {SELECT a FROM t1 WHERE b BETWEEN a AND a*5 OR b=512 ORDER BY a} +} {1 2 3 4 9} +do_test in-1.7 { + execsql {SELECT a+ 100*(a BETWEEN 1 and 3) FROM t1 ORDER BY b} +} {101 102 103 4 5 6 7 8 9 10} + +# The rest of this file concentrates on testing the IN operator. +# Skip this if the library is compiled with SQLITE_OMIT_SUBQUERY +# (because the IN operator is unavailable). +# +ifcapable !subquery { + finish_test + return +} + +# Testing of the IN operator using static lists on the right-hand side. +# +do_test in-2.1 { + execsql {SELECT a FROM t1 WHERE b IN (8,12,16,24,32) ORDER BY a} +} {3 4 5} +do_test in-2.2 { + execsql {SELECT a FROM t1 WHERE b NOT IN (8,12,16,24,32) ORDER BY a} +} {1 2 6 7 8 9 10} +do_test in-2.3 { + execsql {SELECT a FROM t1 WHERE b IN (8,12,16,24,32) OR b=512 ORDER BY a} +} {3 4 5 9} +do_test in-2.4 { + execsql {SELECT a FROM t1 WHERE b NOT IN (8,12,16,24,32) OR b=512 ORDER BY a} +} {1 2 6 7 8 9 10} +do_test in-2.5 { + execsql {SELECT a+100*(b IN (8,16,24)) FROM t1 ORDER BY b} +} {1 2 103 104 5 6 7 8 9 10} + +do_test in-2.6 { + execsql {SELECT a FROM t1 WHERE b IN (b+8,64)} +} {6} +do_test in-2.7 { + execsql {SELECT a FROM t1 WHERE b IN (max(5,10,b),20)} +} {4 5 6 7 8 9 10} +do_test in-2.8 { + execsql {SELECT a FROM t1 WHERE b IN (8*2,64/2) ORDER BY b} +} {4 5} +do_test in-2.9 { + execsql {SELECT a FROM t1 WHERE b IN (max(5,10),20)} +} {} +do_test in-2.10 { + execsql {SELECT a FROM t1 WHERE min(0,b IN (a,30))} +} {} +do_test in-2.11 { + set v [catch {execsql {SELECT a FROM t1 WHERE c IN (10,20)}} msg] + lappend v $msg +} {1 {no such column: c}} + +# Testing the IN operator where the right-hand side is a SELECT +# +do_test in-3.1 { + execsql { + SELECT a FROM t1 + WHERE b IN (SELECT b FROM t1 WHERE a<5) + ORDER BY a + } +} {1 2 3 4} +do_test in-3.2 { + execsql { + SELECT a FROM t1 + WHERE b IN (SELECT b FROM t1 WHERE a<5) OR b==512 + ORDER BY a + } +} {1 2 3 4 9} +do_test in-3.3 { + execsql { + SELECT a + 100*(b IN (SELECT b FROM t1 WHERE a<5)) FROM t1 ORDER BY b + } +} {101 102 103 104 5 6 7 8 9 10} + +# Make sure the UPDATE and DELETE commands work with IN-SELECT +# +do_test in-4.1 { + execsql { + UPDATE t1 SET b=b*2 + WHERE b IN (SELECT b FROM t1 WHERE a>8) + } + execsql {SELECT b FROM t1 ORDER BY b} +} {2 4 8 16 32 64 128 256 1024 2048} +do_test in-4.2 { + execsql { + DELETE FROM t1 WHERE b IN (SELECT b FROM t1 WHERE a>8) + } + execsql {SELECT a FROM t1 ORDER BY a} +} {1 2 3 4 5 6 7 8} +do_test in-4.3 { + execsql { + DELETE FROM t1 WHERE b NOT IN (SELECT b FROM t1 WHERE a>4) + } + execsql {SELECT a FROM t1 ORDER BY a} +} {5 6 7 8} + +# Do an IN with a constant RHS but where the RHS has many, many +# elements. We need to test that collisions in the hash table +# are resolved properly. +# +do_test in-5.1 { + execsql { + INSERT INTO t1 VALUES('hello', 'world'); + SELECT * FROM t1 + WHERE a IN ( + 'Do','an','IN','with','a','constant','RHS','but','where','the', + 'has','many','elements','We','need','to','test','that', + 'collisions','hash','table','are','resolved','properly', + 'This','in-set','contains','thirty','one','entries','hello'); + } +} {hello world} + +# Make sure the IN operator works with INTEGER PRIMARY KEY fields. +# +do_test in-6.1 { + execsql { + CREATE TABLE ta(a INTEGER PRIMARY KEY, b); + INSERT INTO ta VALUES(1,1); + INSERT INTO ta VALUES(2,2); + INSERT INTO ta VALUES(3,3); + INSERT INTO ta VALUES(4,4); + INSERT INTO ta VALUES(6,6); + INSERT INTO ta VALUES(8,8); + INSERT INTO ta VALUES(10, + 'This is a key that is long enough to require a malloc in the VDBE'); + SELECT * FROM ta WHERE a<10; + } +} {1 1 2 2 3 3 4 4 6 6 8 8} +do_test in-6.2 { + execsql { + CREATE TABLE tb(a INTEGER PRIMARY KEY, b); + INSERT INTO tb VALUES(1,1); + INSERT INTO tb VALUES(2,2); + INSERT INTO tb VALUES(3,3); + INSERT INTO tb VALUES(5,5); + INSERT INTO tb VALUES(7,7); + INSERT INTO tb VALUES(9,9); + INSERT INTO tb VALUES(11, + 'This is a key that is long enough to require a malloc in the VDBE'); + SELECT * FROM tb WHERE a<10; + } +} {1 1 2 2 3 3 5 5 7 7 9 9} +do_test in-6.3 { + execsql { + SELECT a FROM ta WHERE b IN (SELECT a FROM tb); + } +} {1 2 3} +do_test in-6.4 { + execsql { + SELECT a FROM ta WHERE b NOT IN (SELECT a FROM tb); + } +} {4 6 8 10} +do_test in-6.5 { + execsql { + SELECT a FROM ta WHERE b IN (SELECT b FROM tb); + } +} {1 2 3 10} +do_test in-6.6 { + execsql { + SELECT a FROM ta WHERE b NOT IN (SELECT b FROM tb); + } +} {4 6 8} +do_test in-6.7 { + execsql { + SELECT a FROM ta WHERE a IN (SELECT a FROM tb); + } +} {1 2 3} +do_test in-6.8 { + execsql { + SELECT a FROM ta WHERE a NOT IN (SELECT a FROM tb); + } +} {4 6 8 10} +do_test in-6.9 { + execsql { + SELECT a FROM ta WHERE a IN (SELECT b FROM tb); + } +} {1 2 3} +do_test in-6.10 { + execsql { + SELECT a FROM ta WHERE a NOT IN (SELECT b FROM tb); + } +} {4 6 8 10} + +# Tests of IN operator against empty sets. (Ticket #185) +# +do_test in-7.1 { + execsql { + SELECT a FROM t1 WHERE a IN (); + } +} {} +do_test in-7.2 { + execsql { + SELECT a FROM t1 WHERE a IN (5); + } +} {5} +do_test in-7.3 { + execsql { + SELECT a FROM t1 WHERE a NOT IN () ORDER BY a; + } +} {5 6 7 8 hello} +do_test in-7.4 { + execsql { + SELECT a FROM t1 WHERE a IN (5) AND b IN (); + } +} {} +do_test in-7.5 { + execsql { + SELECT a FROM t1 WHERE a IN (5) AND b NOT IN (); + } +} {5} +do_test in-7.6.1 { + execsql { + SELECT a FROM ta WHERE a IN (); + } +} {} +do_test in-7.6.2 { + db status step +} {0} +do_test in-7.7 { + execsql { + SELECT a FROM ta WHERE a NOT IN (); + } +} {1 2 3 4 6 8 10} + +do_test in-7.8.1 { + execsql { + SELECT * FROM ta LEFT JOIN tb ON (ta.b=tb.b) WHERE ta.a IN (); + } +} {} +do_test in-7.8.2 { + db status step +} {0} + +do_test in-8.1 { + execsql { + SELECT b FROM t1 WHERE a IN ('hello','there') + } +} {world} +do_test in-8.2 { + execsql { + SELECT b FROM t1 WHERE a IN ("hello",'there') + } +} {world} + +# Test constructs of the form: expr IN tablename +# +do_test in-9.1 { + execsql { + CREATE TABLE t4 AS SELECT a FROM tb; + SELECT * FROM t4; + } +} {1 2 3 5 7 9 11} +do_test in-9.2 { + execsql { + SELECT b FROM t1 WHERE a IN t4; + } +} {32 128} +do_test in-9.3 { + execsql { + SELECT b FROM t1 WHERE a NOT IN t4; + } +} {64 256 world} +do_test in-9.4 { + catchsql { + SELECT b FROM t1 WHERE a NOT IN tb; + } +} {1 {only a single result allowed for a SELECT that is part of an expression}} + +# IN clauses in CHECK constraints. Ticket #1645 +# +do_test in-10.1 { + execsql { + CREATE TABLE t5( + a INTEGER, + CHECK( a IN (111,222,333) ) + ); + INSERT INTO t5 VALUES(111); + SELECT * FROM t5; + } +} {111} +do_test in-10.2 { + catchsql { + INSERT INTO t5 VALUES(4); + } +} {1 {constraint failed}} + +# Ticket #1821 +# +# Type affinity applied to the right-hand side of an IN operator. +# +do_test in-11.1 { + execsql { + CREATE TABLE t6(a,b NUMERIC); + INSERT INTO t6 VALUES(1,2); + INSERT INTO t6 VALUES(2,3); + SELECT * FROM t6 WHERE b IN (2); + } +} {1 2} +do_test in-11.2 { + # The '2' should be coerced into 2 because t6.b is NUMERIC + execsql { + SELECT * FROM t6 WHERE b IN ('2'); + } +} {1 2} +do_test in-11.3 { + # No coercion should occur here because of the unary + before b. + execsql { + SELECT * FROM t6 WHERE +b IN ('2'); + } +} {} +do_test in-11.4 { + # No coercion because column a as affinity NONE + execsql { + SELECT * FROM t6 WHERE a IN ('2'); + } +} {} +do_test in-11.5 { + execsql { + SELECT * FROM t6 WHERE a IN (2); + } +} {2 3} +do_test in-11.6 { + # No coercion because column a as affinity NONE + execsql { + SELECT * FROM t6 WHERE +a IN ('2'); + } +} {} + +# Test error conditions with expressions of the form IN(). +# +ifcapable compound { +do_test in-12.1 { + execsql { + CREATE TABLE t2(a, b, c); + CREATE TABLE t3(a, b, c); + } +} {} +do_test in-12.2 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a, b FROM t3 UNION ALL SELECT a, b FROM t2 + ); + } +} {1 {only a single result allowed for a SELECT that is part of an expression}} +do_test in-12.3 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a, b FROM t3 UNION SELECT a, b FROM t2 + ); + } +} {1 {only a single result allowed for a SELECT that is part of an expression}} +do_test in-12.4 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a, b FROM t3 EXCEPT SELECT a, b FROM t2 + ); + } +} {1 {only a single result allowed for a SELECT that is part of an expression}} +do_test in-12.5 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a, b FROM t3 INTERSECT SELECT a, b FROM t2 + ); + } +} {1 {only a single result allowed for a SELECT that is part of an expression}} +do_test in-12.6 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a, b FROM t3 UNION ALL SELECT a FROM t2 + ); + } +} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}} +do_test in-12.7 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a, b FROM t3 UNION SELECT a FROM t2 + ); + } +} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}} +do_test in-12.8 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a, b FROM t3 EXCEPT SELECT a FROM t2 + ); + } +} {1 {SELECTs to the left and right of EXCEPT do not have the same number of result columns}} +do_test in-12.9 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a, b FROM t3 INTERSECT SELECT a FROM t2 + ); + } +} {1 {SELECTs to the left and right of INTERSECT do not have the same number of result columns}} +} + +ifcapable compound { +do_test in-12.10 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a FROM t3 UNION ALL SELECT a, b FROM t2 + ); + } +} {1 {only a single result allowed for a SELECT that is part of an expression}} +do_test in-12.11 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a FROM t3 UNION SELECT a, b FROM t2 + ); + } +} {1 {only a single result allowed for a SELECT that is part of an expression}} +do_test in-12.12 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a FROM t3 EXCEPT SELECT a, b FROM t2 + ); + } +} {1 {only a single result allowed for a SELECT that is part of an expression}} +do_test in-12.13 { + catchsql { + SELECT * FROM t2 WHERE a IN ( + SELECT a FROM t3 INTERSECT SELECT a, b FROM t2 + ); + } +} {1 {only a single result allowed for a SELECT that is part of an expression}} +}; #ifcapable compound + + +#------------------------------------------------------------------------ +# The following tests check that NULL is handled correctly when it +# appears as part of a set of values on the right-hand side of an +# IN or NOT IN operator. +# +# When it appears in such a set, NULL is handled as an "unknown value". +# If, because of the unknown value in the set, the result of the expression +# cannot be determined, then it itself evaluates to NULL. +# + +# Warm body test to demonstrate the principles being tested: +# +do_test in-13.1 { + db nullvalue "null" + execsql { SELECT + 1 IN (NULL, 1, 2), -- The value 1 is a member of the set, return true. + 3 IN (NULL, 1, 2), -- Ambiguous, return NULL. + 1 NOT IN (NULL, 1, 2), -- The value 1 is a member of the set, return false. + 3 NOT IN (NULL, 1, 2) -- Ambiguous, return NULL. + } +} {1 null 0 null} + +do_test in-13.2 { + execsql { + CREATE TABLE t7(a, b, c NOT NULL); + INSERT INTO t7 VALUES(1, 1, 1); + INSERT INTO t7 VALUES(2, 2, 2); + INSERT INTO t7 VALUES(3, 3, 3); + INSERT INTO t7 VALUES(NULL, 4, 4); + INSERT INTO t7 VALUES(NULL, 5, 5); + } +} {} + +do_test in-13.3 { + execsql { SELECT 2 IN (SELECT a FROM t7) } +} {1} +do_test in-13.4 { + execsql { SELECT 6 IN (SELECT a FROM t7) } +} {null} + +do_test in-13.5 { + execsql { SELECT 2 IN (SELECT b FROM t7) } +} {1} +do_test in-13.6 { + execsql { SELECT 6 IN (SELECT b FROM t7) } +} {0} + +do_test in-13.7 { + execsql { SELECT 2 IN (SELECT c FROM t7) } +} {1} +do_test in-13.8 { + execsql { SELECT 6 IN (SELECT c FROM t7) } +} {0} + +do_test in-13.9 { + execsql { + SELECT + 2 NOT IN (SELECT a FROM t7), + 6 NOT IN (SELECT a FROM t7), + 2 NOT IN (SELECT b FROM t7), + 6 NOT IN (SELECT b FROM t7), + 2 NOT IN (SELECT c FROM t7), + 6 NOT IN (SELECT c FROM t7) + } +} {0 null 0 1 0 1} + +do_test in-13.10 { + execsql { + SELECT b IN ( + SELECT inside.a + FROM t7 AS inside + WHERE inside.b BETWEEN outside.b+1 AND outside.b+2 + ) + FROM t7 AS outside ORDER BY b; + } +} {0 null null null 0} + +do_test in-13.11 { + execsql { + SELECT b NOT IN ( + SELECT inside.a + FROM t7 AS inside + WHERE inside.b BETWEEN outside.b+1 AND outside.b+2 + ) + FROM t7 AS outside ORDER BY b; + } +} {1 null null null 1} + +do_test in-13.12 { + execsql { + CREATE INDEX i1 ON t7(a); + CREATE INDEX i2 ON t7(b); + CREATE INDEX i3 ON t7(c); + } + execsql { + SELECT + 2 IN (SELECT a FROM t7), + 6 IN (SELECT a FROM t7), + 2 IN (SELECT b FROM t7), + 6 IN (SELECT b FROM t7), + 2 IN (SELECT c FROM t7), + 6 IN (SELECT c FROM t7) + } +} {1 null 1 0 1 0} + +do_test in-13.13 { + execsql { + SELECT + 2 NOT IN (SELECT a FROM t7), + 6 NOT IN (SELECT a FROM t7), + 2 NOT IN (SELECT b FROM t7), + 6 NOT IN (SELECT b FROM t7), + 2 NOT IN (SELECT c FROM t7), + 6 NOT IN (SELECT c FROM t7) + } +} {0 null 0 1 0 1} + +do_test in-13.14 { + execsql { + BEGIN TRANSACTION; + CREATE TABLE a(id INTEGER); + INSERT INTO a VALUES(1); + INSERT INTO a VALUES(2); + INSERT INTO a VALUES(3); + CREATE TABLE b(id INTEGER); + INSERT INTO b VALUES(NULL); + INSERT INTO b VALUES(3); + INSERT INTO b VALUES(4); + INSERT INTO b VALUES(5); + COMMIT; + SELECT * FROM a WHERE id NOT IN (SELECT id FROM b); + } +} {} +do_test in-13.14 { + execsql { + CREATE INDEX i5 ON b(id); + SELECT * FROM a WHERE id NOT IN (SELECT id FROM b); + } +} {} + + +do_test in-13.X { + db nullvalue "" +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/in2.test b/components/external/SQLite-3.8.1/test/in2.test new file mode 100644 index 0000000000000000000000000000000000000000..43240824a75280fc388373b16ac9455c970ba519 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/in2.test @@ -0,0 +1,67 @@ +# 2007 May 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file tests a special case in the b-tree code that can be +# hit by the "IN" operator (or EXISTS, NOT IN, etc.). +# +# $Id: in2.test,v 1.3 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test in2-1 { + execsql { + CREATE TABLE a(i INTEGER PRIMARY KEY, a); + } +} {} + +set ::N 2000 + +do_test in2-2 { + db transaction { + for {set ::ii 0} {$::ii < $::N} {incr ::ii} { + execsql {INSERT INTO a VALUES($::ii, $::ii)} + } + execsql {INSERT INTO a VALUES(4000, '')} + + for {set ::ii 0} {$::ii < $::N} {incr ::ii} { + set ::t [format "x%04d" $ii] + execsql {INSERT INTO a VALUES(NULL, $::t)} + } + } +} {} + +# Each iteration of this loop builds a slightly different b-tree to +# evaluate the "IN (...)" operator in the SQL statement. The contents +# of the b-tree are (in sorted order): +# +# $::ii integers. +# a string of zero length. +# $::N short strings. +# +# Records are inserted in sorted order. +# +# The string of zero-length is stored in a b-tree cell with 3 bytes +# of payload. Moving this cell from a leaf node to a internal node +# during b-tree balancing was causing an assertion failure. +# +# This bug only applied to b-trees generated to evaluate IN (..) +# clauses, as it is impossible for persistent b-trees (SQL tables + +# indices) to contain cells smaller than 4 bytes. +# +for {set ::ii 3} {$::ii < $::N} {incr ::ii} { + do_test in2-$::ii { + execsql { + SELECT 1 IN (SELECT a FROM a WHERE (i < $::ii) OR (i >= $::N)) + } + } {1} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/in3.test b/components/external/SQLite-3.8.1/test/in3.test new file mode 100644 index 0000000000000000000000000000000000000000..012c9b44526005849488bd363a65b122e2c6e0f2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/in3.test @@ -0,0 +1,289 @@ +# 2007 November 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file tests the optimisations made in November 2007 of expressions +# of the following form: +# +# IN (SELECT FROM ) +# +# $Id: in3.test,v 1.5 2008/08/04 03:51:24 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !subquery { + finish_test + return +} + +# Return the number of OpenEphemeral instructions used in the +# implementation of the sql statement passed as a an argument. +# +proc nEphemeral {sql} { + set nEph 0 + foreach op [execsql "EXPLAIN $sql"] { + if {$op eq "OpenEphemeral"} {incr nEph} + } + set nEph +} + +# This proc works the same way as execsql, except that the number +# of OpenEphemeral instructions used in the implementation of the +# statement is inserted into the start of the returned list. +# +proc exec_neph {sql} { + return [concat [nEphemeral $sql] [execsql $sql]] +} + +do_test in3-1.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t1 VALUES(5, 6); + } +} {} + +# All of these queries should avoid using a temp-table: +# +do_test in3-1.2 { + exec_neph { SELECT rowid FROM t1 WHERE rowid IN (SELECT rowid FROM t1); } +} {0 1 2 3} +do_test in3-1.3 { + exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a FROM t1); } +} {0 1 3 5} +do_test in3-1.4 { + exec_neph { SELECT rowid FROM t1 WHERE rowid+0 IN (SELECT rowid FROM t1); } +} {0 1 2 3} +do_test in3-1.5 { + exec_neph { SELECT a FROM t1 WHERE a+0 IN (SELECT a FROM t1); } +} {0 1 3 5} + +# Because none of the sub-select queries in the following statements +# match the pattern ("SELECT FROM
    "), the following do +# require a temp table. +# +do_test in3-1.6 { + exec_neph { SELECT rowid FROM t1 WHERE rowid IN (SELECT rowid+0 FROM t1); } +} {1 1 2 3} +do_test in3-1.7 { + exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a+0 FROM t1); } +} {1 1 3 5} +do_test in3-1.8 { + exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 WHERE 1); } +} {1 1 3 5} +do_test in3-1.9 { + exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 GROUP BY a); } +} {1 1 3 5} + +# This should not use a temp-table. Even though the sub-select does +# not exactly match the pattern "SELECT FROM
    ", in +# this case the ORDER BY is a no-op and can be ignored. +do_test in3-1.10 { + exec_neph { SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 ORDER BY a); } +} {0 1 3 5} + +# These do use the temp-table. Adding the LIMIT clause means the +# ORDER BY cannot be ignored. +do_test in3-1.11 { + exec_neph {SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 ORDER BY a LIMIT 1)} +} {1 1} +do_test in3-1.12 { + exec_neph { + SELECT a FROM t1 WHERE a IN (SELECT a FROM t1 ORDER BY a LIMIT 1 OFFSET 1) + } +} {1 3} + +# Has to use a temp-table because of the compound sub-select. +# +ifcapable compound { + do_test in3-1.13 { + exec_neph { + SELECT a FROM t1 WHERE a IN ( + SELECT a FROM t1 UNION ALL SELECT a FROM t1 + ) + } + } {1 1 3 5} +} + +# The first of these queries has to use the temp-table, because the +# collation sequence used for the index on "t1.a" does not match the +# collation sequence used by the "IN" comparison. The second does not +# require a temp-table, because the collation sequences match. +# +do_test in3-1.14 { + exec_neph { SELECT a FROM t1 WHERE a COLLATE nocase IN (SELECT a FROM t1) } +} {1 1 3 5} +do_test in3-1.15 { + exec_neph { SELECT a FROM t1 WHERE a COLLATE binary IN (SELECT a FROM t1) } +} {0 1 3 5} + +# Neither of these queries require a temp-table. The collation sequence +# makes no difference when using a rowid. +# +do_test in3-1.16 { + exec_neph {SELECT a FROM t1 WHERE a COLLATE nocase IN (SELECT rowid FROM t1)} +} {0 1 3} +do_test in3-1.17 { + exec_neph {SELECT a FROM t1 WHERE a COLLATE binary IN (SELECT rowid FROM t1)} +} {0 1 3} + +# The following tests - in3.2.* - test a bug that was difficult to track +# down during development. They are not particularly well focused. +# +do_test in3-2.1 { + execsql { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(w int, x int, y int); + CREATE TABLE t2(p int, q int, r int, s int); + } + for {set i 1} {$i<=100} {incr i} { + set w $i + set x [expr {int(log($i)/log(2))}] + set y [expr {$i*$i + 2*$i + 1}] + execsql "INSERT INTO t1 VALUES($w,$x,$y)" + } + set maxy [execsql {select max(y) from t1}] + db eval { INSERT INTO t2 SELECT 101-w, x, $maxy+1-y, y FROM t1 } +} {} +do_test in3-2.2 { + execsql { + SELECT rowid + FROM t1 + WHERE rowid IN (SELECT rowid FROM t1 WHERE rowid IN (1, 2)); + } +} {1 2} +do_test in3-2.3 { + execsql { + select rowid from t1 where rowid IN (-1,2,4) + } +} {2 4} +do_test in3-2.4 { + execsql { + SELECT rowid FROM t1 WHERE rowid IN + (select rowid from t1 where rowid IN (-1,2,4)) + } +} {2 4} + +#------------------------------------------------------------------------- +# This next block of tests - in3-3.* - verify that column affinity is +# correctly handled in cases where an index might be used to optimise +# an IN (SELECT) expression. +# +do_test in3-3.1 { + catch {execsql { + DROP TABLE t1; + DROP TABLE t2; + }} + + execsql { + + CREATE TABLE t1(a BLOB, b NUMBER ,c TEXT); + CREATE UNIQUE INDEX t1_i1 ON t1(a); /* no affinity */ + CREATE UNIQUE INDEX t1_i2 ON t1(b); /* numeric affinity */ + CREATE UNIQUE INDEX t1_i3 ON t1(c); /* text affinity */ + + CREATE TABLE t2(x BLOB, y NUMBER, z TEXT); + CREATE UNIQUE INDEX t2_i1 ON t2(x); /* no affinity */ + CREATE UNIQUE INDEX t2_i2 ON t2(y); /* numeric affinity */ + CREATE UNIQUE INDEX t2_i3 ON t2(z); /* text affinity */ + + INSERT INTO t1 VALUES(1, 1, 1); + INSERT INTO t2 VALUES('1', '1', '1'); + } +} {} + +do_test in3-3.2 { + # No affinity is applied before comparing "x" and "a". Therefore + # the index can be used (the comparison is false, text!=number). + exec_neph { SELECT x IN (SELECT a FROM t1) FROM t2 } +} {0 0} +do_test in3-3.3 { + # Logically, numeric affinity is applied to both sides before + # the comparison. Therefore it is possible to use index t1_i2. + exec_neph { SELECT x IN (SELECT b FROM t1) FROM t2 } +} {0 1} +do_test in3-3.4 { + # No affinity is applied before the comparison takes place. Making + # it possible to use index t1_i3. + exec_neph { SELECT x IN (SELECT c FROM t1) FROM t2 } +} {0 1} + +do_test in3-3.5 { + # Numeric affinity should be applied to each side before the comparison + # takes place. Therefore we cannot use index t1_i1, which has no affinity. + exec_neph { SELECT y IN (SELECT a FROM t1) FROM t2 } +} {1 1} +do_test in3-3.6 { + # Numeric affinity is applied to both sides before + # the comparison. Therefore it is possible to use index t1_i2. + exec_neph { SELECT y IN (SELECT b FROM t1) FROM t2 } +} {0 1} +do_test in3-3.7 { + # Numeric affinity is applied before the comparison takes place. + # Making it impossible to use index t1_i3. + exec_neph { SELECT y IN (SELECT c FROM t1) FROM t2 } +} {1 1} + +#--------------------------------------------------------------------- +# +# Test using a multi-column index. +# +do_test in3-4.1 { + execsql { + CREATE TABLE t3(a, b, c); + CREATE UNIQUE INDEX t3_i ON t3(b, a); + } + + execsql { + INSERT INTO t3 VALUES(1, 'numeric', 2); + INSERT INTO t3 VALUES(2, 'text', 2); + INSERT INTO t3 VALUES(3, 'real', 2); + INSERT INTO t3 VALUES(4, 'none', 2); + } +} {} +do_test in3-4.2 { + exec_neph { SELECT 'text' IN (SELECT b FROM t3) } +} {0 1} +do_test in3-4.3 { + exec_neph { SELECT 'TEXT' COLLATE nocase IN (SELECT b FROM t3) } +} {1 1} +do_test in3-4.4 { + # A temp table must be used because t3_i.b is not guaranteed to be unique. + exec_neph { SELECT b FROM t3 WHERE b IN (SELECT b FROM t3) } +} {1 none numeric real text} +do_test in3-4.5 { + execsql { CREATE UNIQUE INDEX t3_i2 ON t3(b) } + exec_neph { SELECT b FROM t3 WHERE b IN (SELECT b FROM t3) } +} {0 none numeric real text} +do_test in3-4.6 { + execsql { DROP INDEX t3_i2 } +} {} + +# The following two test cases verify that ticket #2991 has been fixed. +# +do_test in3-5.1 { + execsql { + CREATE TABLE Folders( + folderid INTEGER PRIMARY KEY, + parentid INTEGER, + rootid INTEGER, + path VARCHAR(255) + ); + } +} {} +do_test in3-5.2 { + catchsql { + DELETE FROM Folders WHERE folderid IN + (SELECT folderid FROM Folder WHERE path LIKE 'C:\MP3\Albums\' || '%'); + } +} {1 {no such table: Folder}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/in4.test b/components/external/SQLite-3.8.1/test/in4.test new file mode 100644 index 0000000000000000000000000000000000000000..470f4f0e346fed68ba79e4ebd5d2645a655834c1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/in4.test @@ -0,0 +1,162 @@ +# 2008 September 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: in4.test,v 1.4 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test in4-1.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a); + } +} {} +do_test in4-1.2 { + execsql { + SELECT * FROM t1 WHERE a IN ('aaa', 'bbb', 'ccc'); + } +} {} +do_test in4-1.3 { + execsql { + INSERT INTO t1 VALUES('aaa', 1); + INSERT INTO t1 VALUES('ddd', 2); + INSERT INTO t1 VALUES('ccc', 3); + INSERT INTO t1 VALUES('eee', 4); + SELECT b FROM t1 WHERE a IN ('aaa', 'bbb', 'ccc'); + } +} {1 3} +do_test in4-1.4 { + execsql { + SELECT a FROM t1 WHERE rowid IN (1, 3); + } +} {aaa ccc} +do_test in4-1.5 { + execsql { + SELECT a FROM t1 WHERE rowid IN (); + } +} {} +do_test in4-1.6 { + execsql { + SELECT a FROM t1 WHERE a IN ('ddd'); + } +} {ddd} + +do_test in4-2.1 { + execsql { + CREATE TABLE t2(a INTEGER PRIMARY KEY, b TEXT); + INSERT INTO t2 VALUES(-1, '-one'); + INSERT INTO t2 VALUES(0, 'zero'); + INSERT INTO t2 VALUES(1, 'one'); + INSERT INTO t2 VALUES(2, 'two'); + INSERT INTO t2 VALUES(3, 'three'); + } +} {} + +do_test in4-2.2 { + execsql { SELECT b FROM t2 WHERE a IN (0, 2) } +} {zero two} + +do_test in4-2.3 { + execsql { SELECT b FROM t2 WHERE a IN (2, 0) } +} {zero two} + +do_test in4-2.4 { + execsql { SELECT b FROM t2 WHERE a IN (2, -1) } +} {-one two} + +do_test in4-2.5 { + execsql { SELECT b FROM t2 WHERE a IN (NULL, 3) } +} {three} + +do_test in4-2.6 { + execsql { SELECT b FROM t2 WHERE a IN (1.0, 2.1) } +} {one} + +do_test in4-2.7 { + execsql { SELECT b FROM t2 WHERE a IN ('1', '2') } +} {one two} + +do_test in4-2.8 { + execsql { SELECT b FROM t2 WHERE a IN ('', '0.0.0', '2') } +} {two} + +# The following block of tests test expressions of the form: +# +# IN () +# +# i.e. IN expressions with a literal empty set. +# +# This has led to crashes on more than one occasion. Test case in4-3.2 +# was added in reponse to a bug reported on the mailing list on 11/7/2008. +# See also tickets #3602 and #185. +# +do_test in4-3.1 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(x, id); + CREATE TABLE t2(x, id); + INSERT INTO t1 VALUES(NULL, NULL); + INSERT INTO t1 VALUES(0, NULL); + INSERT INTO t1 VALUES(1, 3); + INSERT INTO t1 VALUES(2, 4); + INSERT INTO t1 VALUES(3, 5); + INSERT INTO t1 VALUES(4, 6); + INSERT INTO t2 VALUES(0, NULL); + INSERT INTO t2 VALUES(4, 1); + INSERT INTO t2 VALUES(NULL, 1); + INSERT INTO t2 VALUES(NULL, NULL); + } +} {} +do_test in4-3.2 { + execsql { + SELECT x FROM t1 WHERE id IN () AND x IN (SELECT x FROM t2 WHERE id=1) + } +} {} +do_test in4-3.3 { + execsql { + CREATE TABLE t3(x, y, z); + CREATE INDEX t3i1 ON t3(x, y); + INSERT INTO t3 VALUES(1, 1, 1); + INSERT INTO t3 VALUES(10, 10, 10); + } + execsql { SELECT * FROM t3 WHERE x IN () } +} {} +do_test in4-3.4 { + execsql { SELECT * FROM t3 WHERE x = 10 AND y IN () } +} {} +do_test in4-3.5 { + execsql { SELECT * FROM t3 WHERE x IN () AND y = 10 } +} {} +do_test in4-3.6 { + execsql { SELECT * FROM t3 WHERE x IN () OR x = 10 } +} {10 10 10} +do_test in4-3.7 { + execsql { SELECT * FROM t3 WHERE y IN () } +} {} +do_test in4-3.8 { + execsql { SELECT x IN() AS a FROM t3 WHERE a } +} {} +do_test in4-3.9 { + execsql { SELECT x IN() AS a FROM t3 WHERE NOT a } +} {0 0} +do_test in4-3.10 { + execsql { SELECT * FROM t3 WHERE oid IN () } +} {} +do_test in4-3.11 { + execsql { SELECT * FROM t3 WHERE x IN (1, 2) OR y IN ()} +} {1 1 1} +do_test in4-3.12 { + execsql { SELECT * FROM t3 WHERE x IN (1, 2) AND y IN ()} +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/in5.test b/components/external/SQLite-3.8.1/test/in5.test new file mode 100644 index 0000000000000000000000000000000000000000..8a43b8d44a5435758897b4c37614196ee16e29c6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/in5.test @@ -0,0 +1,138 @@ +# 2012 September 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test in5-1.1 { + execsql { + CREATE TABLE t1x(x INTEGER PRIMARY KEY); + INSERT INTO t1x VALUES(1),(3),(5),(7),(9); + CREATE TABLE t1y(y INTEGER UNIQUE); + INSERT INTO t1y VALUES(2),(4),(6),(8); + CREATE TABLE t1z(z TEXT UNIQUE); + INSERT INTO t1z VALUES('a'),('c'),('e'),('g'); + CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT, d TEXT); + INSERT INTO t2 VALUES(1,2,'a','12a'),(1,2,'b','12b'), + (2,3,'g','23g'),(3,5,'c','35c'), + (4,6,'h','46h'),(5,6,'e','56e'); + CREATE TABLE t3x AS SELECT x FROM t1x; + CREATE TABLE t3y AS SELECT y FROM t1y; + CREATE TABLE t3z AS SELECT z FROM t1z; + SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t1z ORDER BY c; + } +} {12a 56e} +do_test in5-1.2 { + execsql { + SELECT d FROM t2 WHERE a IN t1y AND b IN t1x AND c IN t1z ORDER BY d; + } +} {23g} +do_test in5-1.3 { + execsql { + SELECT d FROM t2 WHERE a IN t3x AND b IN t3y AND c IN t3z ORDER BY d; + } +} {12a 56e} + + +do_test in5-2.1 { + execsql { + CREATE INDEX t2abc ON t2(a,b,c); + SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t1z ORDER BY d; + } +} {12a 56e} +do_test in5-2.2 { + execsql { + SELECT d FROM t2 WHERE a IN t1y AND b IN t1x AND c IN t1z ORDER BY d; + } +} {23g} +do_test in5-2.3 { + regexp {OpenEphemeral} [db eval { + EXPLAIN SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t1z + }] +} {0} +do_test in5-2.4 { + execsql { + SELECT d FROM t2 WHERE a IN t3x AND b IN t3y AND c IN t3z ORDER BY d; + } +} {12a 56e} +do_test in5-2.5.1 { + regexp {OpenEphemeral} [db eval { + EXPLAIN SELECT d FROM t2 WHERE a IN t3x AND b IN t1y AND c IN t1z + }] +} {1} +do_test in5-2.5.2 { + regexp {OpenEphemeral} [db eval { + EXPLAIN SELECT d FROM t2 WHERE a IN t1x AND b IN t3y AND c IN t1z + }] +} {1} +do_test in5-2.5.3 { + regexp {OpenEphemeral} [db eval { + EXPLAIN SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t3z + }] +} {1} + +do_test in5-3.1 { + execsql { + DROP INDEX t2abc; + CREATE INDEX t2ab ON t2(a,b); + SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t1z ORDER BY d; + } +} {12a 56e} +do_test in5-3.2 { + execsql { + SELECT d FROM t2 WHERE a IN t1y AND b IN t1x AND c IN t1z ORDER BY d; + } +} {23g} +do_test in5-3.3 { + regexp {OpenEphemeral} [db eval { + EXPLAIN SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t1z + }] +} {0} + +do_test in5-4.1 { + execsql { + DROP INDEX t2ab; + CREATE INDEX t2abcd ON t2(a,b,c,d); + SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t1z ORDER BY d; + } +} {12a 56e} +do_test in5-4.2 { + execsql { + SELECT d FROM t2 WHERE a IN t1y AND b IN t1x AND c IN t1z ORDER BY d; + } +} {23g} +do_test in5-4.3 { + regexp {OpenEphemeral} [db eval { + EXPLAIN SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t1z + }] +} {0} + + +do_test in5-5.1 { + execsql { + DROP INDEX t2abcd; + CREATE INDEX t2cbad ON t2(c,b,a,d); + SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t1z ORDER BY d; + } +} {12a 56e} +do_test in5-5.2 { + execsql { + SELECT d FROM t2 WHERE a IN t1y AND b IN t1x AND c IN t1z ORDER BY d; + } +} {23g} +do_test in5-5.3 { + regexp {OpenEphemeral} [db eval { + EXPLAIN SELECT d FROM t2 WHERE a IN t1x AND b IN t1y AND c IN t1z + }] +} {0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrblob.test b/components/external/SQLite-3.8.1/test/incrblob.test new file mode 100644 index 0000000000000000000000000000000000000000..4277e5c4c1a29452843ef250dc245b039e4bf059 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrblob.test @@ -0,0 +1,688 @@ +# 2007 May 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: incrblob.test,v 1.24 2009/06/19 22:23:42 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!autovacuum || !pragma || !incrblob} { + finish_test + return +} + +do_test incrblob-1.1 { + execsql { + CREATE TABLE blobs(k PRIMARY KEY, v BLOB); + INSERT INTO blobs VALUES('one', X'0102030405060708090A'); + INSERT INTO blobs VALUES('two', X'0A090807060504030201'); + } +} {} + +do_test incrblob-1.2.1 { + set ::blob [db incrblob blobs v 1] + string match incrblob_* $::blob +} {1} +unset -nocomplain data +do_test incrblob-1.2.2 { + binary scan [read $::blob] c* data + set data +} {1 2 3 4 5 6 7 8 9 10} +do_test incrblob-1.2.3 { + seek $::blob 0 + puts -nonewline $::blob "1234567890" + flush $::blob +} {} +do_test incrblob-1.2.4 { + seek $::blob 0 + binary scan [read $::blob] c* data + set data +} {49 50 51 52 53 54 55 56 57 48} +do_test incrblob-1.2.5 { + close $::blob +} {} +do_test incrblob-1.2.6 { + execsql { + SELECT v FROM blobs WHERE rowid = 1; + } +} {1234567890} + +#-------------------------------------------------------------------- +# Test cases incrblob-1.3.X check that it is possible to read and write +# regions of a blob that lie on overflow pages. +# +do_test incrblob-1.3.1 { + set ::str "[string repeat . 10000]" + execsql { + INSERT INTO blobs(rowid, k, v) VALUES(3, 'three', $::str); + } +} {} + +do_test incrblob-1.3.2 { + set ::blob [db incrblob blobs v 3] + seek $::blob 8500 + read $::blob 10 +} {..........} +do_test incrblob-1.3.3 { + seek $::blob 8500 + puts -nonewline $::blob 1234567890 +} {} +do_test incrblob-1.3.4 { + seek $::blob 8496 + read $::blob 10 +} {....123456} +do_test incrblob-1.3.10 { + close $::blob +} {} + +#------------------------------------------------------------------------ +# incrblob-2.*: +# +# Test that the following operations use ptrmap pages to reduce +# unnecessary reads: +# +# * Reading near the end of a blob, +# * Writing near the end of a blob, and +# * SELECT a column value that is located on an overflow page. +# +proc nRead {db} { + set bt [btree_from_db $db] + db_enter $db + array set stats [btree_pager_stats $bt] + db_leave $db + return $stats(read) +} +proc nWrite {db} { + set bt [btree_from_db $db] + db_enter $db + array set stats [btree_pager_stats $bt] + db_leave $db + return $stats(write) +} + +sqlite3_soft_heap_limit 0 + +foreach AutoVacuumMode [list 0 1] { + + if {$AutoVacuumMode>0} { + ifcapable !autovacuum { + break + } + } + + db close + forcedelete test.db test.db-journal + + sqlite3 db test.db + execsql "PRAGMA mmap_size = 0" + execsql "PRAGMA auto_vacuum = $AutoVacuumMode" + + do_test incrblob-2.$AutoVacuumMode.1 { + set ::str [string repeat abcdefghij 2900] + execsql { + BEGIN; + CREATE TABLE blobs(k PRIMARY KEY, v BLOB, i INTEGER); + DELETE FROM blobs; + INSERT INTO blobs VALUES('one', $::str || randstr(500,500), 45); + COMMIT; + } + expr [file size test.db]/1024 + } [expr 31 + $AutoVacuumMode] + + ifcapable autovacuum { + do_test incrblob-2.$AutoVacuumMode.2 { + execsql { + PRAGMA auto_vacuum; + } + } $AutoVacuumMode + } + + do_test incrblob-2.$AutoVacuumMode.3 { + # Open and close the db to make sure the page cache is empty. + db close + sqlite3 db test.db + execsql "PRAGMA mmap_size = 0" + + # Read the last 20 bytes of the blob via a blob handle. + set ::blob [db incrblob blobs v 1] + seek $::blob -20 end + set ::fragment [read $::blob] + close $::blob + + # If the database is not in auto-vacuum mode, the whole of + # the overflow-chain must be scanned. In auto-vacuum mode, + # sqlite uses the ptrmap pages to avoid reading the other pages. + # + nRead db + } [expr $AutoVacuumMode ? 4 : 30] + + do_test incrblob-2.$AutoVacuumMode.4 { + string range [db one {SELECT v FROM blobs}] end-19 end + } $::fragment + + do_test incrblob-2.$AutoVacuumMode.5 { + # Open and close the db to make sure the page cache is empty. + db close + sqlite3 db test.db + execsql "PRAGMA mmap_size = 0" + + # Write the second-to-last 20 bytes of the blob via a blob handle. + # + set ::blob [db incrblob blobs v 1] + seek $::blob -40 end + puts -nonewline $::blob "1234567890abcdefghij" + flush $::blob + + # If the database is not in auto-vacuum mode, the whole of + # the overflow-chain must be scanned. In auto-vacuum mode, + # sqlite uses the ptrmap pages to avoid reading the other pages. + # + nRead db + } [expr $AutoVacuumMode ? 4 : 30] + + # Pages 1 (the write-counter) and 32 (the blob data) were written. + do_test incrblob-2.$AutoVacuumMode.6 { + close $::blob + nWrite db + } 2 + + do_test incrblob-2.$AutoVacuumMode.7 { + string range [db one {SELECT v FROM blobs}] end-39 end-20 + } "1234567890abcdefghij" + + do_test incrblob-2.$AutoVacuumMode.8 { + # Open and close the db to make sure the page cache is empty. + db close + sqlite3 db test.db + execsql { PRAGMA mmap_size = 0 } + + execsql { SELECT i FROM blobs } + } {45} + + do_test incrblob-2.$AutoVacuumMode.9 { + nRead db + } [expr $AutoVacuumMode ? 4 : 30] +} +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) + +#------------------------------------------------------------------------ +# incrblob-3.*: +# +# Test the outcome of trying to write to a read-only blob handle. +# +do_test incrblob-3.1 { + set ::blob [db incrblob -readonly blobs v 1] + seek $::blob -40 end + read $::blob 20 +} "1234567890abcdefghij" +do_test incrblob-3.2 { + seek $::blob 0 + set rc [catch { + puts -nonewline $::blob "helloworld" + } msg] + close $::blob + list $rc $msg +} "1 {channel \"$::blob\" wasn't opened for writing}" + +do_test incrblob-3.3 { + set ::blob [db incrblob -readonly blobs v 1] + seek $::blob -40 end + read $::blob 20 +} "1234567890abcdefghij" +do_test incrblob-3.4 { + set rc [catch { + sqlite3_blob_write $::blob 20 "qwertyuioplkjhgfds" + } msg] + list $rc $msg +} {1 SQLITE_READONLY} +catch {close $::blob} + +#------------------------------------------------------------------------ +# incrblob-4.*: +# +# Try a couple of error conditions: +# +# 4.1 - Attempt to open a row that does not exist. +# 4.2 - Attempt to open a column that does not exist. +# 4.3 - Attempt to open a table that does not exist. +# 4.4 - Attempt to open a database that does not exist. +# +# 4.5 - Attempt to open an integer +# 4.6 - Attempt to open a real value +# 4.7 - Attempt to open an SQL null +# +# 4.8 - Attempt to open an indexed column for writing +# 4.9 - Attempt to open an indexed column for reading (this works) +# +# 4.11 - Attempt to open a column of a view. +# 4.12 - Attempt to open a column of a virtual table. +# +do_test incrblob-4.1 { + set rc [catch { + set ::blob [db incrblob blobs v 2] + } msg ] + list $rc $msg +} {1 {no such rowid: 2}} +do_test incrblob-4.2 { + set rc [catch { + set ::blob [db incrblob blobs blue 1] + } msg ] + list $rc $msg +} {1 {no such column: "blue"}} +do_test incrblob-4.3 { + set rc [catch { + set ::blob [db incrblob nosuchtable blue 1] + } msg ] + list $rc $msg +} {1 {no such table: main.nosuchtable}} +do_test incrblob-4.4 { + set rc [catch { + set ::blob [db incrblob nosuchdb blobs v 1] + } msg ] + list $rc $msg +} {1 {no such table: nosuchdb.blobs}} + +do_test incrblob-4.5 { + set rc [catch { + set ::blob [db incrblob blobs i 1] + } msg ] + list $rc $msg +} {1 {cannot open value of type integer}} +do_test incrblob-4.6 { + execsql { + INSERT INTO blobs(k, v, i) VALUES(123, 567.765, NULL); + } + set rc [catch { + set ::blob [db incrblob blobs v 2] + } msg ] + list $rc $msg +} {1 {cannot open value of type real}} +do_test incrblob-4.7 { + set rc [catch { + set ::blob [db incrblob blobs i 2] + } msg ] + list $rc $msg +} {1 {cannot open value of type null}} + +do_test incrblob-4.8.1 { + execsql { + INSERT INTO blobs(k, v, i) VALUES(X'010203040506070809', 'hello', 'world'); + } + set rc [catch { + set ::blob [db incrblob blobs k 3] + } msg ] + list $rc $msg +} {1 {cannot open indexed column for writing}} +do_test incrblob-4.8.2 { + execsql { + CREATE TABLE t3(a INTEGER PRIMARY KEY, b); + INSERT INTO t3 VALUES(1, 2); + } + set rc [catch { + set ::blob [db incrblob -readonly t3 a 1] + } msg ] + list $rc $msg +} {1 {cannot open value of type null}} +do_test incrblob-4.8.3 { + set rc [catch { + set ::blob [db incrblob -readonly t3 rowid 1] + } msg ] + list $rc $msg +} {1 {no such column: "rowid"}} + +do_test incrblob-4.9.1 { + set rc [catch { + set ::blob [db incrblob -readonly blobs k 3] + } msg] +} {0} +do_test incrblob-4.9.2 { + binary scan [read $::blob] c* c + close $::blob + set c +} {1 2 3 4 5 6 7 8 9} + +do_test incrblob-4.10 { + set ::blob [db incrblob -readonly blobs k 3] + set rc [catch { sqlite3_blob_read $::blob 10 100 } msg] + list $rc $msg +} {1 SQLITE_ERROR} +do_test incrblob-4.10.2 { + close $::blob +} {} + +ifcapable view { + do_test incrblob-4.11 { + execsql { CREATE VIEW blobs_view AS SELECT k, v, i FROM blobs } + set rc [catch { db incrblob blobs_view v 3 } msg] + list $rc $msg + } {1 {cannot open view: blobs_view}} +} +ifcapable vtab { + register_echo_module [sqlite3_connection_pointer db] + do_test incrblob-4.12 { + execsql { CREATE VIRTUAL TABLE blobs_echo USING echo(blobs) } + set rc [catch { db incrblob blobs_echo v 3 } msg] + list $rc $msg + } {1 {cannot open virtual table: blobs_echo}} +} + + +#------------------------------------------------------------------------ +# incrblob-5.*: +# +# Test that opening a blob in an attached database works. +# +ifcapable attach { + do_test incrblob-5.1 { + forcedelete test2.db test2.db-journal + set ::size [expr [file size [info script]]] + execsql { + ATTACH 'test2.db' AS aux; + CREATE TABLE aux.files(name, text); + INSERT INTO aux.files VALUES('this one', zeroblob($::size)); + } + set fd [db incrblob aux files text 1] + fconfigure $fd -translation binary + set fd2 [open [info script]] + fconfigure $fd2 -translation binary + puts -nonewline $fd [read $fd2] + close $fd + close $fd2 + set ::text [db one {select text from aux.files}] + string length $::text + } [file size [info script]] + do_test incrblob-5.2 { + set fd2 [open [info script]] + fconfigure $fd2 -translation binary + set ::data [read $fd2] + close $fd2 + set ::data + } $::text +} + +# free memory +unset -nocomplain ::data +unset -nocomplain ::text + +#------------------------------------------------------------------------ +# incrblob-6.*: +# +# Test that opening a blob for write-access is impossible if +# another connection has the database RESERVED lock. +# +# Then test that blob writes that take place inside of a +# transaction are not visible to external connections until +# after the transaction is commited and the blob channel +# closed. +# +# This test does not work with the "memsubsys1" configuration. +# Permutation memsubsys1 configures a very small static allocation +# for use as page-cache memory. This causes SQLite to upgrade +# to an exclusive lock when writing earlier than usual, which +# makes some of these tests fail. +# +sqlite3_soft_heap_limit 0 +if {[permutation] != "memsubsys1"} { + do_test incrblob-6.1 { + sqlite3 db2 test.db + execsql { + BEGIN; + INSERT INTO blobs(k, v, i) VALUES('a', 'different', 'connection'); + } db2 + } {} + do_test incrblob-6.2 { + execsql { + SELECT rowid FROM blobs ORDER BY rowid + } + } {1 2 3} + do_test incrblob-6.3 { + set rc [catch { + db incrblob blobs v 1 + } msg] + list $rc $msg + } {1 {database is locked}} + do_test incrblob-6.4 { + set rc [catch { + db incrblob blobs v 3 + } msg] + list $rc $msg + } {1 {database is locked}} + do_test incrblob-6.5 { + set ::blob [db incrblob -readonly blobs v 3] + read $::blob + } {hello} + do_test incrblob-6.6 { + close $::blob + } {} + + do_test incrblob-6.7 { + set ::blob [db2 incrblob blobs i 4] + gets $::blob + } {connection} + do_test incrblob-6.8 { + tell $::blob + } {10} + do_test incrblob-6.9 { + seek $::blob 0 + puts -nonewline $::blob "invocation" + flush $::blob + } {} + + # At this point commit should be illegal (because + # there is an open blob channel). + # + do_test incrblob-6.11 { + catchsql { + COMMIT; + } db2 + } {1 {cannot commit transaction - SQL statements in progress}} + + do_test incrblob-6.12 { + execsql { + SELECT * FROM blobs WHERE rowid = 4; + } + } {} + do_test incrblob-6.13 { + close $::blob + } {} + do_test incrblob-6.14 { + catchsql { + COMMIT; + } db2 + } {0 {}} + do_test incrblob-6.15 { + execsql { + SELECT * FROM blobs WHERE rowid = 4; + } + } {a different invocation} + db2 close +} +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) + +#----------------------------------------------------------------------- +# The following tests verify the behavior of the incremental IO +# APIs in the following cases: +# +# 7.1 A row that containing an open blob is modified. +# +# 7.2 A CREATE TABLE requires that an overflow page that is part +# of an open blob is moved. +# +# 7.3 An INCREMENTAL VACUUM moves an overflow page that is part +# of an open blob. +# +# In the first case above, correct behavior is for all subsequent +# read/write operations on the blob-handle to return SQLITE_ABORT. +# More accurately, blob-handles are invalidated whenever the table +# they belong to is written to. +# +# The second two cases have no external effect. They are testing +# that the internal cache of overflow page numbers is correctly +# invalidated. +# +do_test incrblob-7.1.0 { + execsql { + BEGIN; + DROP TABLE blobs; + CREATE TABLE t1 (a, b, c, d BLOB); + INSERT INTO t1(a, b, c, d) VALUES(1, 2, 3, 4); + COMMIT; + } +} {} + +foreach {tn arg} {1 "" 2 -readonly} { + + execsql { + UPDATE t1 SET d = zeroblob(10000); + } + + do_test incrblob-7.1.$tn.1 { + set ::b [eval db incrblob $arg t1 d 1] + binary scan [sqlite3_blob_read $::b 5000 5] c* c + set c + } {0 0 0 0 0} + do_test incrblob-7.1.$tn.2 { + execsql { + UPDATE t1 SET d = 15; + } + } {} + do_test incrblob-7.1.$tn.3 { + set rc [catch { sqlite3_blob_read $::b 5000 5 } msg] + list $rc $msg + } {1 SQLITE_ABORT} + do_test incrblob-7.1.$tn.4 { + execsql { + SELECT d FROM t1; + } + } {15} + do_test incrblob-7.1.$tn.5 { + set rc [catch { close $::b } msg] + list $rc $msg + } {0 {}} + do_test incrblob-7.1.$tn.6 { + execsql { + SELECT d FROM t1; + } + } {15} + +} + +set fd [open [info script]] +fconfigure $fd -translation binary +set ::data [read $fd 14000] +close $fd + +db close +forcedelete test.db test.db-journal +sqlite3 db test.db + +do_test incrblob-7.2.1 { + execsql { + PRAGMA auto_vacuum = "incremental"; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); -- root@page3 + INSERT INTO t1 VALUES(123, $::data); + } + set ::b [db incrblob -readonly t1 b 123] + fconfigure $::b -translation binary + read $::b +} $::data +do_test incrblob-7.2.2 { + execsql { + CREATE TABLE t2(a INTEGER PRIMARY KEY, b); -- root@page4 + } + seek $::b 0 + read $::b +} $::data +do_test incrblob-7.2.3 { + close $::b + execsql { + SELECT rootpage FROM sqlite_master; + } +} {3 4} + +set ::otherdata "[string range $::data 0 1000][string range $::data 1001 end]" +do_test incrblob-7.3.1 { + execsql { + INSERT INTO t2 VALUES(456, $::otherdata); + } + set ::b [db incrblob -readonly t2 b 456] + fconfigure $::b -translation binary + read $::b +} $::otherdata +do_test incrblob-7.3.2 { + expr [file size test.db]/1024 +} 30 +do_test incrblob-7.3.3 { + execsql { + DELETE FROM t1 WHERE a = 123; + PRAGMA INCREMENTAL_VACUUM(0); + } + seek $::b 0 + read $::b +} $::otherdata + +# Attempt to write on a read-only blob. Make sure the error code +# gets set. Ticket #2464. +# +do_test incrblob-7.4 { + set rc [catch {sqlite3_blob_write $::b 10 HELLO} msg] + lappend rc $msg +} {1 SQLITE_READONLY} +do_test incrblob-7.5 { + sqlite3_errcode db +} {SQLITE_READONLY} +do_test incrblob-7.6 { + sqlite3_errmsg db +} {attempt to write a readonly database} + +# Test that if either the "offset" or "amount" arguments to +# sqlite3_blob_write() are less than zero, SQLITE_ERROR is returned. +# +do_test incrblob-8.1 { + execsql { INSERT INTO t1 VALUES(314159, 'sqlite') } + set ::b [db incrblob t1 b 314159] + fconfigure $::b -translation binary + set rc [catch {sqlite3_blob_write $::b 10 HELLO -1} msg] + lappend rc $msg +} {1 SQLITE_ERROR} +do_test incrblob-8.2 { + sqlite3_errcode db +} {SQLITE_ERROR} +do_test incrblob-8.3 { + set rc [catch {sqlite3_blob_write $::b -1 HELLO 5} msg] + lappend rc $msg +} {1 SQLITE_ERROR} +do_test incrblob-8.4 { + sqlite3_errcode db +} {SQLITE_ERROR} +do_test incrblob-8.5 { + execsql {SELECT b FROM t1 WHERE a = 314159} +} {sqlite} +do_test incrblob-8.6 { + set rc [catch {sqlite3_blob_write $::b 0 etilqs 6} msg] + lappend rc $msg +} {0 {}} +do_test incrblob-8.7 { + execsql {SELECT b FROM t1 WHERE a = 314159} +} {etilqs} + +# The following test case exposes an instance in the blob code where +# an error message was set using a call similar to sqlite3_mprintf(zErr), +# where zErr is an arbitrary string. This is no good if the string contains +# characters that can be mistaken for printf() formatting directives. +# +do_test incrblob-9.1 { + list [catch { db incrblob t1 "A tricky column name %s%s" 1 } msg] $msg +} {1 {no such column: "A tricky column name %s%s"}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrblob2.test b/components/external/SQLite-3.8.1/test/incrblob2.test new file mode 100644 index 0000000000000000000000000000000000000000..9046de278173234d6842c2e6af960da518a46663 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrblob2.test @@ -0,0 +1,418 @@ +# 2008 June 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test that it is possible to have two open blob handles on a single +# blob object. +# +# $Id: incrblob2.test,v 1.11 2009/06/29 06:00:37 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!autovacuum || !pragma || !incrblob} { + finish_test + return +} + +do_test incrblob2-1.0 { + execsql { + CREATE TABLE blobs(id INTEGER PRIMARY KEY, data BLOB); + INSERT INTO blobs VALUES(NULL, zeroblob(5000)); + INSERT INTO blobs VALUES(NULL, zeroblob(5000)); + INSERT INTO blobs VALUES(NULL, zeroblob(5000)); + INSERT INTO blobs VALUES(NULL, zeroblob(5000)); + } +} {} + +foreach iOffset [list 0 256 4094] { + do_test incrblob2-1.$iOffset.1 { + set fd [db incrblob blobs data 1] + puts $fd "[string repeat x $iOffset]SQLite version 3.6.0" + close $fd + } {} + + do_test incrblob2-1.$iOffset.2 { + set fd1 [db incrblob blobs data 1] + set fd2 [db incrblob blobs data 1] + fconfigure $fd1 -buffering none + fconfigure $fd2 -buffering none + if {$iOffset != 0} { + seek $fd2 $iOffset start + seek $fd1 $iOffset start + } + read $fd1 6 + } {SQLite} + + do_test incrblob2-1.$iOffset.3 { + read $fd2 6 + } {SQLite} + + do_test incrblob2-1.$iOffset.4 { + seek $fd2 $iOffset start + seek $fd1 $iOffset start + puts -nonewline $fd2 "etiLQS" + } {} + + + do_test incrblob2-1.$iOffset.5 { + seek $fd1 $iOffset start + read $fd1 6 + } {etiLQS} + + do_test incrblob2-1.$iOffset.6 { + seek $fd2 $iOffset start + read $fd2 6 + } {etiLQS} + + do_test incrblob2-1.$iOffset.7 { + seek $fd1 $iOffset start + read $fd1 6 + } {etiLQS} + + do_test incrblob2-1.$iOffset.8 { + close $fd1 + close $fd2 + } {} +} + +#-------------------------------------------------------------------------- + +foreach iOffset [list 0 256 4094] { + + do_test incrblob2-2.$iOffset.1 { + set fd1 [db incrblob blobs data 1] + seek $fd1 [expr $iOffset - 5000] end + fconfigure $fd1 -buffering none + + set fd2 [db incrblob blobs data 1] + seek $fd2 [expr $iOffset - 5000] end + fconfigure $fd2 -buffering none + + puts -nonewline $fd1 "123456" + } {} + + do_test incrblob2-2.$iOffset.2 { + read $fd2 6 + } {123456} + + do_test incrblob2-2.$iOffset.3 { + close $fd1 + close $fd2 + } {} +} + +do_test incrblob2-3.1 { + set fd1 [db incrblob blobs data 1] + fconfigure $fd1 -buffering none +} {} +do_test incrblob2-3.2 { + execsql { + INSERT INTO blobs VALUES(5, zeroblob(10240)); + } +} {} +do_test incrblob2-3.3 { + set rc [catch { read $fd1 6 } msg] + list $rc $msg +} {0 123456} +do_test incrblob2-3.4 { + close $fd1 +} {} + +#-------------------------------------------------------------------------- +# The following tests - incrblob2-4.* - test that blob handles are +# invalidated at the correct times. +# +do_test incrblob2-4.1 { + unset -nocomplain data + db eval BEGIN + db eval { CREATE TABLE t1(id INTEGER PRIMARY KEY, data BLOB); } + for {set ii 1} {$ii < 100} {incr ii} { + set data [string repeat "blob$ii" 500] + db eval { INSERT INTO t1 VALUES($ii, $data) } + } + db eval COMMIT +} {} + +proc aborted_handles {} { + global handles + + set aborted {} + for {set ii 1} {$ii < 100} {incr ii} { + set str "blob$ii" + set nByte [string length $str] + set iOffset [expr $nByte * $ii * 2] + + set rc [catch {sqlite3_blob_read $handles($ii) $iOffset $nByte} msg] + if {$rc && $msg eq "SQLITE_ABORT"} { + lappend aborted $ii + } else { + if {$rc || $msg ne $str} { + error "blob $ii: $msg" + } + } + } + set aborted +} + +do_test incrblob2-4.2 { + for {set ii 1} {$ii < 100} {incr ii} { + set handles($ii) [db incrblob t1 data $ii] + } + aborted_handles +} {} + +# Update row 3. This should abort handle 3 but leave all others untouched. +# +do_test incrblob2-4.3 { + db eval {UPDATE t1 SET data = data || '' WHERE id = 3} + aborted_handles +} {3} + +# Test that a write to handle 3 also returns SQLITE_ABORT. +# +do_test incrblob2-4.3.1 { + set rc [catch {sqlite3_blob_write $::handles(3) 10 HELLO} msg] + list $rc $msg +} {1 SQLITE_ABORT} + +# Delete row 14. This should abort handle 6 but leave all others untouched. +# +do_test incrblob2-4.4 { + db eval {DELETE FROM t1 WHERE id = 14} + aborted_handles +} {3 14} + +# Change the rowid of row 15 to 102. Should abort handle 15. +# +do_test incrblob2-4.5 { + db eval {UPDATE t1 SET id = 102 WHERE id = 15} + aborted_handles +} {3 14 15} + +# Clobber row 92 using INSERT OR REPLACE. +# +do_test incrblob2-4.6 { + db eval {INSERT OR REPLACE INTO t1 VALUES(92, zeroblob(1000))} + aborted_handles +} {3 14 15 92} + +# Clobber row 65 using UPDATE OR REPLACE on row 35. This should abort +# handles 35 and 65. +# +do_test incrblob2-4.7 { + db eval {UPDATE OR REPLACE t1 SET id = 65 WHERE id = 35} + aborted_handles +} {3 14 15 35 65 92} + +# Insert a couple of new rows. This should not invalidate any handles. +# +do_test incrblob2-4.9 { + db eval {INSERT INTO t1 SELECT NULL, data FROM t1} + aborted_handles +} {3 14 15 35 65 92} + +# Delete all rows from 1 to 25. This should abort all handles up to 25. +# +do_test incrblob2-4.9 { + db eval {DELETE FROM t1 WHERE id >=1 AND id <= 25} + aborted_handles +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 35 65 92} + +# Delete the whole table (this will use sqlite3BtreeClearTable()). All handles +# should now be aborted. +# +do_test incrblob2-4.10 { + db eval {DELETE FROM t1} + aborted_handles +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99} + +do_test incrblob2-4.1.X { + for {set ii 1} {$ii < 100} {incr ii} { + close $handles($ii) + } +} {} + +#-------------------------------------------------------------------------- +# The following tests - incrblob2-5.* - test that in shared cache an open +# blob handle counts as a read-lock on its table. +# +ifcapable shared_cache { + db close + set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + + do_test incrblob2-5.1 { + sqlite3 db test.db + sqlite3 db2 test.db + + execsql { + INSERT INTO t1 VALUES(1, 'abcde'); + } + } {} + + do_test incrblob2-5.2 { + catchsql { INSERT INTO t1 VALUES(2, 'fghij') } db2 + } {0 {}} + + do_test incrblob2-5.3 { + set blob [db incrblob t1 data 1] + catchsql { INSERT INTO t1 VALUES(3, 'klmno') } db2 + } {1 {database table is locked}} + + do_test incrblob2-5.4 { + close $blob + execsql BEGIN db2 + catchsql { INSERT INTO t1 VALUES(4, 'pqrst') } db2 + } {0 {}} + + do_test incrblob2-5.5 { + set rc [catch { db incrblob -readonly t1 data 1 } msg] + list $rc $msg + } {1 {database table is locked: t1}} + + do_test incrblob2-5.6 { + execsql { PRAGMA read_uncommitted=1 } + set blob [db incrblob -readonly t1 data 4] + read $blob + } {pqrst} + + do_test incrblob2-5.7 { + catchsql { INSERT INTO t1 VALUES(3, 'klmno') } db2 + } {0 {}} + + do_test incrblob2-5.8 { + close $blob + } {} + + db2 close + db close + sqlite3_enable_shared_cache $::enable_shared_cache +} + +#-------------------------------------------------------------------------- +# The following tests - incrblob2-6.* - test a specific scenario that might +# be causing an error. +# +sqlite3 db test.db +do_test incrblob2-6.1 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1, zeroblob(100)); + } + + set rdHandle [db incrblob -readonly t1 data 1] + set wrHandle [db incrblob t1 data 1] + + sqlite3_blob_read $rdHandle 0 100 + + sqlite3_blob_write $wrHandle 0 ABCDEF + + close $wrHandle + close $rdHandle +} {} + +do_test incrblob2-6.2 { + set rdHandle [db incrblob -readonly t1 data 1] + sqlite3_blob_read $rdHandle 0 2 +} {AB} + +do_test incrblob2-6.3 { + set wrHandle [db incrblob t1 data 1] + sqlite3_blob_write $wrHandle 0 ZZZZZZZZZZ + sqlite3_blob_read $rdHandle 2 4 +} {ZZZZ} + +do_test incrblob2-6.4 { + close $wrHandle + close $rdHandle +} {} + +sqlite3_memory_highwater 1 +do_test incrblob2-7.1 { + db eval { + CREATE TABLE t2(B BLOB); + INSERT INTO t2 VALUES(zeroblob(10 * 1024 * 1024)); + } + expr {[sqlite3_memory_highwater]<(5 * 1024 * 1024)} +} {1} + +do_test incrblob2-7.2 { + set h [db incrblob t2 B 1] + expr {[sqlite3_memory_highwater]<(5 * 1024 * 1024)} +} {1} + +do_test incrblob2-7.3 { + seek $h 0 end + tell $h +} [expr 10 * 1024 * 1024] + +do_test incrblob2-7.4 { + expr {[sqlite3_memory_highwater]<(5 * 1024 * 1024)} +} {1} + +do_test incrblob2-7.5 { + close $h +} {} + +#--------------------------------------------------------------------------- +# The following tests, incrblob2-8.*, test that nothing terrible happens +# when a statement transaction is rolled back while there are open +# incremental-blob handles. At one point an assert() was failing when +# this was attempted. +# +do_test incrblob2-8.1 { + execsql BEGIN + set h [db incrblob t2 B 1] + set rc [catch { + db eval {SELECT rowid FROM t2} { execsql "DROP TABLE t2" } + } msg] + list $rc $msg +} {1 {database table is locked}} +do_test incrblob2-8.2 { + close $h + execsql COMMIT +} {} +do_test incrblob2-8.3 { + execsql { + CREATE TABLE t3(a INTEGER UNIQUE, b TEXT); + INSERT INTO t3 VALUES(1, 'aaaaaaaaaaaaaaaaaaaa'); + INSERT INTO t3 VALUES(2, 'bbbbbbbbbbbbbbbbbbbb'); + INSERT INTO t3 VALUES(3, 'cccccccccccccccccccc'); + INSERT INTO t3 VALUES(4, 'dddddddddddddddddddd'); + INSERT INTO t3 VALUES(5, 'eeeeeeeeeeeeeeeeeeee'); + } +} {} +do_test incrblob2-8.4 { + execsql BEGIN + set h [db incrblob t3 b 3] + sqlite3_blob_read $h 0 20 +} {cccccccccccccccccccc} +do_test incrblob2-8.5 { + catchsql {UPDATE t3 SET a = 6 WHERE a > 3} +} {1 {column a is not unique}} +do_test incrblob2-8.6 { + catchsql {UPDATE t3 SET a = 6 WHERE a > 3} +} {1 {column a is not unique}} +do_test incrblob2-8.7 { + sqlite3_blob_read $h 0 20 +} {cccccccccccccccccccc} +do_test incrblob2-8.8 { + catchsql {UPDATE t3 SET a = 6 WHERE a = 3 OR a = 5} +} {1 {column a is not unique}} +do_test incrblob2-8.9 { + set rc [catch {sqlite3_blob_read $h 0 20} msg] + list $rc $msg +} {1 SQLITE_ABORT} +do_test incrblob2-8.X { + close $h +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrblob3.test b/components/external/SQLite-3.8.1/test/incrblob3.test new file mode 100644 index 0000000000000000000000000000000000000000..5f2e860d08e62fa16d5e8e7c49371a92bda8a94a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrblob3.test @@ -0,0 +1,271 @@ +# 2010 October 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +sqlite3 db test.db +sqlite3_db_config_lookaside db 0 0 0 + +do_execsql_test incrblob3-1.1 { + CREATE TABLE blobs(k INTEGER PRIMARY KEY, v BLOB); + INSERT INTO blobs VALUES(1, zeroblob(100)); + INSERT INTO blobs VALUES(2, zeroblob(100)); +} {} + +# Test the sqlite3_blob_reopen()/read()/write() functions. +# +do_test incrblob3-1.2 { + set ::blob [db incrblob blobs v 1] + puts $::blob "hello world" +} {} + +do_test incrblob3-1.3 { + sqlite3_blob_reopen $::blob 2 + puts $::blob "world hello" +} {} + +do_test incrblob3-1.4 { + sqlite3_blob_reopen $::blob 1 + gets $::blob +} {hello world} + +do_test incrblob3-1.5 { + sqlite3_blob_reopen $::blob 2 + gets $::blob +} {world hello} + +do_test incrblob3-1.6 { close $::blob } {} + +# Test some error conditions. +# +# incrblob3-2.1: Attempting to reopen a row that does not exist. +# incrblob3-2.2: Attempting to reopen a row that does not contain a blob +# or text value. +# +do_test incrblob3-2.1.1 { + set ::blob [db incrblob blobs v 1] + list [catch {sqlite3_blob_reopen $::blob 3} msg] $msg +} {1 SQLITE_ERROR} +do_test incrblob3-2.1.2 { + list [sqlite3_errcode db] [sqlite3_errmsg db] +} {SQLITE_ERROR {no such rowid: 3}} +do_test incrblob3-2.1.3 { + list [catch {sqlite3_blob_reopen $::blob 1} msg] $msg +} {1 SQLITE_ABORT} +do_test incrblob3-2.1.4 { close $::blob } {} + +do_execsql_test incrblob3-2.2.1 { + INSERT INTO blobs VALUES(3, 42); + INSERT INTO blobs VALUES(4, 54.4); + INSERT INTO blobs VALUES(5, NULL); +} +foreach {tn rowid type} { + 1 3 integer + 2 4 real + 3 5 null +} { + do_test incrblob3-2.2.$tn.1 { + set ::blob [db incrblob blobs v 1] + list [catch {sqlite3_blob_reopen $::blob $rowid} msg] $msg + } {1 SQLITE_ERROR} + do_test incrblob3-2.2.$tn.2 { + list [sqlite3_errcode db] [sqlite3_errmsg db] + } "SQLITE_ERROR {cannot open value of type $type}" + + do_test incrblob3-2.2.$tn.3 { + list [catch {sqlite3_blob_reopen $::blob 1} msg] $msg + } {1 SQLITE_ABORT} + do_test incrblob3-2.2.$tn.4 { + list [catch {sqlite3_blob_read $::blob 0 10} msg] $msg + } {1 SQLITE_ABORT} + do_test incrblob3-2.2.$tn.5 { + list [catch {sqlite3_blob_write $::blob 0 "abcd"} msg] $msg + } {1 SQLITE_ABORT} + do_test incrblob3-2.2.$tn.6 { + sqlite3_blob_bytes $::blob + } {0} + + do_test incrblob3-2.2.$tn.7 { close $::blob } {} +} + +# Test that passing NULL to sqlite3_blob_XXX() APIs returns SQLITE_MISUSE. +# +# incrblob3-3.1: sqlite3_blob_reopen() +# incrblob3-3.2: sqlite3_blob_read() +# incrblob3-3.3: sqlite3_blob_write() +# incrblob3-3.4: sqlite3_blob_bytes() +# +do_test incrblob3-3.1 { + list [catch {sqlite3_blob_reopen {} 3} msg] $msg +} {1 SQLITE_MISUSE} + +do_test incrblob3-3.2 { + list [catch {sqlite3_blob_read {} 0 10} msg] $msg +} {1 SQLITE_MISUSE} + +do_test incrblob3-3.3 { + list [catch {sqlite3_blob_write {} 0 "abcd"} msg] $msg +} {1 SQLITE_MISUSE} + +do_test incrblob3-3.4 { sqlite3_blob_bytes {} } {0} + +do_test incrblob3-3.5 { sqlite3_blob_close {} } {} + +# Test out-of-range reading and writing +# +do_test incrblob3-4.1 { + set ::blob [db incrblob blobs v 1] + sqlite3_blob_bytes $::blob +} {100} +do_test incrblob3-4.2 { + list [catch { sqlite3_blob_read $::blob -1 10 } msg] $msg +} {1 SQLITE_ERROR} +do_test incrblob3-4.3 { + list [catch { sqlite3_blob_read $::blob 0 -10 } msg] $msg +} {1 SQLITE_ERROR} +do_test incrblob3-4.4 { + list [catch { sqlite3_blob_read $::blob 95 10 } msg] $msg +} {1 SQLITE_ERROR} +do_test incrblob3-4.5 { + list [catch { sqlite3_blob_write $::blob -1 "abcdefghij" 10 } msg] $msg +} {1 SQLITE_ERROR} +do_test incrblob3-4.6 { + list [catch { sqlite3_blob_write $::blob 0 "abcdefghij" -10 } msg] $msg +} {1 SQLITE_ERROR} +do_test incrblob3-4.7 { + list [catch { sqlite3_blob_write $::blob 95 "abcdefghij" } msg] $msg +} {1 SQLITE_ERROR} + +do_test incrblob3-4.8 { close $::blob } {} + +# Test that modifying the row a blob handle points to aborts the blob. +# +do_test incrblob3-5.1 { + set ::blob [db incrblob blobs v 1] + sqlite3_blob_bytes $::blob +} {100} +do_test incrblob3-5.2 { + execsql { UPDATE blobs SET v = '123456789012345678901234567890' WHERE k = 1 } + list [catch { sqlite3_blob_read $::blob 0 10 } msg] $msg +} {1 SQLITE_ABORT} + +# Test various errors that can occur in sqlite3_blob_open(): +# +# 1. Trying to open a virtual table column. +# 2. Trying to open a view column. +# 3. Trying to open a column that does not exist. +# 4. Trying to open a read/write handle on an indexed column. +# 5. Trying to open a read/write handle on the child key of an FK constraint. +# +ifcapable fts3 { + do_test incrblob3-6.1 { + execsql { + CREATE VIRTUAL TABLE ft USING fts3; + INSERT INTO ft VALUES('rules to open a column to which'); + } + + list [catch { db incrblob ft content 1 } msg] $msg + } {1 {cannot open virtual table: ft}} +} +ifcapable view { + do_test incrblob3-6.2 { + execsql { CREATE VIEW v1 AS SELECT * FROM blobs } + list [catch { db incrblob v1 content 1 } msg] $msg + } {1 {cannot open view: v1}} +} + +do_test incrblob3-6.3 { + list [catch { db incrblob blobs content 1 } msg] $msg +} {1 {no such column: "content"}} + +do_test incrblob3-6.4.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(b); + INSERT INTO t1 VALUES(zeroblob(100), zeroblob(100)); + } + list [catch { db incrblob t1 b 1 } msg] $msg +} {1 {cannot open indexed column for writing}} +do_test incrblob3-6.4.2 { + set ::blob [db incrblob t1 a 1] + close $::blob +} {} +do_test incrblob3-6.4.3 { + set ::blob [db incrblob -readonly t1 b 1] + close $::blob +} {} + +do_test incrblob3-6.5.1 { + execsql { + CREATE TABLE p1(a PRIMARY KEY); + CREATE TABLE c1(a, b REFERENCES p1); + PRAGMA foreign_keys = 1; + INSERT INTO p1 VALUES(zeroblob(100)); + INSERT INTO c1 VALUES(zeroblob(100), zeroblob(100)); + } + list [catch { db incrblob c1 b 1 } msg] $msg +} {1 {cannot open foreign key column for writing}} + +do_test incrblob3-6.5.2 { + set ::blob [db incrblob c1 a 1] + close $::blob +} {} +do_test incrblob3-6.5.3 { + set ::blob [db incrblob -readonly c1 b 1] + close $::blob +} {} +do_test incrblob3-6.5.4 { + execsql { PRAGMA foreign_keys = 0 } + set ::blob [db incrblob c1 b 1] + close $::blob +} {} + + +# Test that sqlite3_blob_open() handles transient and persistent schema +# errors correctly. +# +do_test incrblob3-7.1 { + sqlite3 db2 test.db + sqlite3_db_config_lookaside db2 0 0 0 + execsql { CREATE TABLE t2(x) } db2 + set ::blob [db incrblob blobs v 1] + close $::blob +} {} +db2 close + +testvfs tvfs -default 1 +tvfs filter xAccess +tvfs script access_method + +proc access_method {args} { + set schemacookie [hexio_get_int [hexio_read test.db 40 4]] + incr schemacookie + hexio_write test.db 40 [hexio_render_int32 $schemacookie] + + set dbversion [hexio_get_int [hexio_read test.db 24 4]] + incr dbversion + hexio_write test.db 24 [hexio_render_int32 $dbversion] + + return "" +} + +do_test incrblob3-7.2 { + sqlite3 db test.db + sqlite3_db_config_lookaside db 0 0 0 + list [catch {db incrblob blobs v 1} msg] $msg +} {1 {database schema has changed}} +db close +tvfs delete + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrblob4.test b/components/external/SQLite-3.8.1/test/incrblob4.test new file mode 100644 index 0000000000000000000000000000000000000000..a92e373536b9d4f43efb76a7cd7443c2fd45a300 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrblob4.test @@ -0,0 +1,89 @@ +# 2012 March 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!incrblob} { finish_test ; return } +set testprefix incrblob4 + +proc create_t1 {} { + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(k INTEGER PRIMARY KEY, v); + } +} + +proc populate_t1 {} { + set data [list a b c d e f g h i j k l m n o p q r s t u v w x y z] + foreach d $data { + set blob [string repeat $d 900] + execsql { INSERT INTO t1(v) VALUES($blob) } + } +} + + +do_test 1.1 { + create_t1 + populate_t1 +} {} + +do_test 1.2 { + set blob [db incrblob t1 v 5] + read $blob 10 +} {eeeeeeeeee} + +do_test 1.3 { + execsql { DELETE FROM t1 } + populate_t1 +} {} + + + +do_test 2.1 { + reset_db + create_t1 + populate_t1 +} {} + +do_test 2.2 { + set blob [db incrblob t1 v 10] + read $blob 10 +} {jjjjjjjjjj} + +do_test 2.3 { + set new [string repeat % 900] + execsql { DELETE FROM t1 WHERE k=10 } + execsql { DELETE FROM t1 WHERE k=9 } + execsql { INSERT INTO t1(v) VALUES($new) } +} {} + + + +do_test 3.1 { + reset_db + create_t1 + populate_t1 +} {} + +do_test 3.2 { + set blob [db incrblob t1 v 20] + read $blob 10 +} {tttttttttt} + +do_test 3.3 { + set new [string repeat % 900] + execsql { UPDATE t1 SET v = $new WHERE k = 20 } + execsql { DELETE FROM t1 WHERE k=19 } + execsql { INSERT INTO t1(v) VALUES($new) } +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrblob_err.test b/components/external/SQLite-3.8.1/test/incrblob_err.test new file mode 100644 index 0000000000000000000000000000000000000000..35d37fee92012f9bbe758584b909faef990df3da --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrblob_err.test @@ -0,0 +1,139 @@ +# 2007 May 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: incrblob_err.test,v 1.14 2008/07/18 17:16:27 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!incrblob || !memdebug || !tclvar} { + finish_test + return +} + +source $testdir/malloc_common.tcl + +unset -nocomplain ::fd ::data +set ::fd [open [info script]] +set ::data [read $::fd] +close $::fd + +do_malloc_test 1 -tclprep { + set bytes [file size [info script]] + execsql { + CREATE TABLE blobs(k, v BLOB); + INSERT INTO blobs VALUES(1, zeroblob($::bytes)); + } +} -tclbody { + set ::blob [db incrblob blobs v 1] + fconfigure $::blob -translation binary + set rc [catch {puts -nonewline $::blob $::data}] + if {$rc} { error "out of memory" } +} + +do_malloc_test 2 -tclprep { + execsql { + CREATE TABLE blobs(k, v BLOB); + INSERT INTO blobs VALUES(1, $::data); + } +} -tclbody { + set ::blob [db incrblob blobs v 1] + set rc [catch {set ::r [read $::blob]}] + if {$rc} { + error "out of memory" + } elseif {$::r ne $::data} { + error "Bad data read..." + } +} + +do_malloc_test 3 -tclprep { + execsql { + CREATE TABLE blobs(k, v BLOB); + INSERT INTO blobs VALUES(1, $::data); + } +} -tclbody { + set ::blob [db incrblob blobs v 1] + set rc [catch {set ::r [read $::blob]}] + if {$rc} { + error "out of memory" + } elseif {$::r ne $::data} { + error "Bad data read..." + } + set rc [catch {close $::blob}] + if {$rc} { + error "out of memory" + } +} + +do_ioerr_test incrblob_err-4 -cksum 1 -sqlprep { + CREATE TABLE blobs(k, v BLOB); + INSERT INTO blobs VALUES(1, $::data); +} -tclbody { + set ::blob [db incrblob blobs v 1] + read $::blob +} + +do_ioerr_test incrblob_err-5 -cksum 1 -sqlprep { + CREATE TABLE blobs(k, v BLOB); + INSERT INTO blobs VALUES(1, zeroblob(length(CAST($::data AS BLOB)))); +} -tclbody { + set ::blob [db incrblob blobs v 1] + fconfigure $::blob -translation binary + puts -nonewline $::blob $::data + close $::blob +} + +do_ioerr_test incrblob_err-6 -cksum 1 -sqlprep { + CREATE TABLE blobs(k, v BLOB); + INSERT INTO blobs VALUES(1, $::data || $::data || $::data); +} -tclbody { + set ::blob [db incrblob blobs v 1] + fconfigure $::blob -translation binary + seek $::blob -20 end + puts -nonewline $::blob "12345678900987654321" + close $::blob +} + +do_ioerr_test incrblob_err-7 -cksum 1 -sqlprep { + PRAGMA auto_vacuum = 1; + CREATE TABLE blobs(k INTEGER PRIMARY KEY, v BLOB); + INSERT INTO blobs VALUES(1, zeroblob(500 * 1020)); +} -tclbody { + # Read some data from the end of the large blob inserted into table + # "blobs". This forces the IO error to occur while reading a pointer + # map page for the purposes of seeking to the end of the blob. + # + sqlite3 db2 test.db + set ::blob [db2 incrblob blobs v 1] + sqlite3_blob_read $::blob [expr 500*1020-20] 20 + close $::blob +} +catch {db2 close} + +do_ioerr_test incrblob_err-8 -cksum 1 -sqlprep { + PRAGMA auto_vacuum = 1; + CREATE TABLE blobs(k INTEGER PRIMARY KEY, v BLOB); + INSERT INTO blobs VALUES(1, zeroblob(500 * 1020)); +} -tclbody { + # Read some data from the end of the large blob inserted into table + # "blobs". This forces the IO error to occur while reading a pointer + # map page for the purposes of seeking to the end of the blob. + # + sqlite3 db2 test.db + set ::blob [db2 incrblob blobs v 1] + sqlite3_blob_write $::blob [expr 500*1020-20] 12345678900987654321 + close $::blob +} + +catch {db2 close} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrblobfault.test b/components/external/SQLite-3.8.1/test/incrblobfault.test new file mode 100644 index 0000000000000000000000000000000000000000..0c1d93d4603e1c4ea6fad8794ba4e40e3a4ef552 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrblobfault.test @@ -0,0 +1,69 @@ +# 2010 October 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set testprefix incrblobfault + +do_execsql_test 1.0 { + CREATE TABLE blob(x INTEGER PRIMARY KEY, v BLOB); + INSERT INTO blob VALUES(1, 'hello world'); + INSERT INTO blob VALUES(2, 'world hello'); + INSERT INTO blob SELECT NULL, v FROM blob; + INSERT INTO blob SELECT NULL, v FROM blob; + INSERT INTO blob SELECT NULL, v FROM blob; + INSERT INTO blob SELECT NULL, v FROM blob; + INSERT INTO blob SELECT NULL, v FROM blob; + INSERT INTO blob SELECT NULL, v FROM blob; + INSERT INTO blob SELECT NULL, v FROM blob; + INSERT INTO blob SELECT NULL, v FROM blob; + INSERT INTO blob SELECT NULL, v FROM blob; + INSERT INTO blob SELECT NULL, v FROM blob; +} + +do_faultsim_test 1 -prep { + sqlite3 db test.db + set ::blob [db incrblob blob v 1] +} -body { + if {[catch {sqlite3_blob_reopen $::blob 1000}]} { + error [sqlite3_errmsg db] + } +} -test { + faultsim_test_result {0 {}} + close $::blob +} + +do_faultsim_test 2 -prep { + sqlite3 db test.db + set ::blob [db incrblob blob v 1] +} -body { + if {[catch {sqlite3_blob_reopen $::blob -1}]} { + error [sqlite3_errmsg db] + } +} -test { + faultsim_test_result {1 {no such rowid: -1}} + close $::blob +} + +do_faultsim_test 3 -prep { + sqlite3 db test.db +} -body { + set ::blob [db incrblob blob v 1] + gets $::blob +} -test { + faultsim_test_result {0 {hello world}} + catch { close $::blob } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrvacuum.test b/components/external/SQLite-3.8.1/test/incrvacuum.test new file mode 100644 index 0000000000000000000000000000000000000000..91f5c8e1e00c7959079e191e3f0647c95f445668 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrvacuum.test @@ -0,0 +1,786 @@ +# 2007 April 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the incremental vacuum feature. +# +# Note: There are also some tests for incremental vacuum and IO +# errors in incrvacuum_ioerr.test. +# +# $Id: incrvacuum.test,v 1.23 2009/02/18 20:31:18 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If this build of the library does not support auto-vacuum, omit this +# whole file. +ifcapable {!autovacuum || !pragma} { + finish_test + return +} + +#--------------------------------------------------------------------- +# Test the pragma on an empty database. +# +do_test incrvacuum-1.1 { + execsql { + pragma auto_vacuum; + } +} $sqlite_options(default_autovacuum) +do_test incrvacuum-1.2.0 { + # File size is sometimes 1 instead of 0 due to the hack we put in + # to work around ticket #3260. Search for comments on #3260 in + # os_unix.c. + expr {[file size test.db] > 1} +} {0} +do_test incrvacuum-1.2 { + # This command will create the database. + execsql { + pragma auto_vacuum = 'full'; + pragma auto_vacuum; + } +} {1} +do_test incrvacuum-1.2.1 { + expr {[file size test.db] > 0} +} {1} +do_test incrvacuum-1.3 { + execsql { + pragma auto_vacuum = 'incremental'; + pragma auto_vacuum; + } +} {2} +do_test incrvacuum-1.4 { + # In this case the invalid value is ignored and the auto_vacuum + # setting remains unchanged. + execsql { + pragma auto_vacuum = 'invalid'; + pragma auto_vacuum; + } +} {2} +do_test incrvacuum-1.5 { + execsql { + pragma auto_vacuum = 1; + pragma auto_vacuum; + } +} {1} +do_test incrvacuum-1.6 { + execsql { + pragma auto_vacuum = '2'; + pragma auto_vacuum; + } +} {2} +do_test incrvacuum-1.7 { + # Invalid value. auto_vacuum setting remains unchanged. + execsql { + pragma auto_vacuum = 5; + pragma auto_vacuum; + } +} {2} + +#--------------------------------------------------------------------- +# Test the pragma on a non-empty database. It is possible to toggle +# the connection between "full" and "incremental" mode, but not to +# change from either of these to "none", or from "none" to "full" or +# "incremental". +# +do_test incrvacuum-2.1 { + execsql { + pragma auto_vacuum = 1; + CREATE TABLE abc(a, b, c); + } +} {} +do_test incrvacuum-2.2 { + execsql { + pragma auto_vacuum = 'none'; + pragma auto_vacuum; + } +} {1} +do_test incrvacuum-2.2.1 { + db close + sqlite3 db test.db + execsql { + pragma auto_vacuum; + } +} {1} +do_test incrvacuum-2.3 { + execsql { + pragma auto_vacuum = 'incremental'; + pragma auto_vacuum; + } +} {2} +do_test incrvacuum-2.4 { + execsql { + pragma auto_vacuum = 'full'; + pragma auto_vacuum; + } +} {1} + +#--------------------------------------------------------------------- +# Test that when the auto_vacuum mode is "incremental", the database +# does not shrink when pages are removed from it. But it does if +# the mode is set to "full". +# +do_test incrvacuum-3.1 { + execsql { + pragma auto_vacuum; + } +} {1} +do_test incrvacuum-3.2 { + set ::str [string repeat 1234567890 110] + execsql { + PRAGMA auto_vacuum = 2; + BEGIN; + CREATE TABLE tbl2(str); + INSERT INTO tbl2 VALUES($::str); + COMMIT; + } + # 5 pages: + # + # 1 -> database header + # 2 -> first back-pointer page + # 3 -> table abc + # 4 -> table tbl2 + # 5 -> table tbl2 overflow page. + # + expr {[file size test.db] / 1024} +} {5} +do_test incrvacuum-3.3 { + execsql { + DROP TABLE abc; + DELETE FROM tbl2; + } + expr {[file size test.db] / 1024} +} {5} +do_test incrvacuum-3.4 { + execsql { + PRAGMA auto_vacuum = 1; + INSERT INTO tbl2 VALUES('hello world'); + } + expr {[file size test.db] / 1024} +} {3} + +#--------------------------------------------------------------------- +# Try to run a very simple incremental vacuum. Also verify that +# PRAGMA incremental_vacuum is a harmless no-op against a database that +# does not support auto-vacuum. +# +do_test incrvacuum-4.1 { + set ::str [string repeat 1234567890 110] + execsql { + PRAGMA auto_vacuum = 2; + INSERT INTO tbl2 VALUES($::str); + CREATE TABLE tbl1(a, b, c); + } + expr {[file size test.db] / 1024} +} {5} +do_test incrvacuum-4.2 { + execsql { + DELETE FROM tbl2; + DROP TABLE tbl1; + } + expr {[file size test.db] / 1024} +} {5} +do_test incrvacuum-4.3 { + set ::nStep 0 + db eval {pragma incremental_vacuum(10)} { + incr ::nStep + } + list [expr {[file size test.db] / 1024}] $::nStep +} {3 2} + +#--------------------------------------------------------------------- +# The following tests - incrvacuum-5.* - test incremental vacuum +# from within a transaction. +# +do_test incrvacuum-5.1.1 { + expr {[file size test.db] / 1024} +} {3} +do_test incrvacuum-5.1.2 { + execsql { + BEGIN; + DROP TABLE tbl2; + PRAGMA incremental_vacuum; + COMMIT; + } + expr {[file size test.db] / 1024} +} {1} + +do_test incrvacuum-5.2.1 { + set ::str [string repeat abcdefghij 110] + execsql { + BEGIN; + CREATE TABLE tbl1(a); + INSERT INTO tbl1 VALUES($::str); + PRAGMA incremental_vacuum; -- this is a no-op. + COMMIT; + } + expr {[file size test.db] / 1024} +} {4} +do_test incrvacuum-5.2.2 { + set ::str [string repeat abcdefghij 110] + execsql { + BEGIN; + INSERT INTO tbl1 VALUES($::str); + INSERT INTO tbl1 SELECT * FROM tbl1; + DELETE FROM tbl1 WHERE oid%2; -- Put 2 overflow pages on free-list. + COMMIT; + } + expr {[file size test.db] / 1024} +} {7} +do_test incrvacuum-5.2.3 { + execsql { + BEGIN; + PRAGMA incremental_vacuum; -- Vacuum up the two pages. + CREATE TABLE tbl2(b); -- Use one free page as a table root. + INSERT INTO tbl2 VALUES('a nice string'); + COMMIT; + } + expr {[file size test.db] / 1024} +} {6} +do_test incrvacuum-5.2.4 { + execsql { + SELECT * FROM tbl2; + } +} {{a nice string}} +do_test incrvacuum-5.2.5 { + execsql { + DROP TABLE tbl1; + DROP TABLE tbl2; + PRAGMA incremental_vacuum; + } + expr {[file size test.db] / 1024} +} {1} + + +# Test cases incrvacuum-5.3.* use the following list as input data. +# Two new databases are opened, one with incremental vacuum enabled, +# the other with no auto-vacuum completely disabled. After executing +# each element of the following list on both databases, test that +# the integrity-check passes and the contents of each are identical. +# +set TestScriptList [list { + BEGIN; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + CREATE INDEX t1_i ON t1(a); + CREATE INDEX t2_i ON t2(a); +} { + INSERT INTO t1 VALUES($::str1, $::str2); + INSERT INTO t1 VALUES($::str1||$::str2, $::str2||$::str1); + INSERT INTO t2 SELECT b, a FROM t1; + INSERT INTO t2 SELECT a, b FROM t1; + INSERT INTO t1 SELECT b, a FROM t2; + UPDATE t2 SET b = ''; + PRAGMA incremental_vacuum; +} { + UPDATE t2 SET b = (SELECT b FROM t1 WHERE t1.oid = t2.oid); + PRAGMA incremental_vacuum; +} { + CREATE TABLE t3(a, b); + INSERT INTO t3 SELECT * FROM t2; + DROP TABLE t2; + PRAGMA incremental_vacuum; +} { + CREATE INDEX t3_i ON t3(a); + COMMIT; +} { + BEGIN; + DROP INDEX t3_i; + PRAGMA incremental_vacuum; + INSERT INTO t3 VALUES('hello', 'world'); + ROLLBACK; +} { + INSERT INTO t3 VALUES('hello', 'world'); +} +] + +# If this build omits subqueries, step 2 in the above list will not +# work. Replace it with "" in this case. +# +ifcapable !subquery { lset TestScriptList 2 "" } + +# Compare the contents of databases $A and $B. +# +proc compare_dbs {A B tname} { + set tbl_list [execsql { + SELECT tbl_name FROM sqlite_master WHERE type = 'table' + } $A] + + do_test ${tname}.1 [subst { + execsql { + SELECT tbl_name FROM sqlite_master WHERE type = 'table' + } $B + }] $tbl_list + + set tn 1 + foreach tbl $tbl_list { + set control [execsql "SELECT * FROM $tbl" $A] + do_test ${tname}.[incr tn] [subst { + execsql "SELECT * FROM $tbl" $B + }] $control + } +} + +set ::str1 [string repeat abcdefghij 130] +set ::str2 [string repeat 1234567890 105] + +forcedelete test1.db test1.db-journal test2.db test2.db-journal +sqlite3 db1 test1.db +sqlite3 db2 test2.db +execsql { PRAGMA auto_vacuum = 'none' } db1 +execsql { PRAGMA auto_vacuum = 'incremental' } db2 + +set tn 1 +foreach sql $::TestScriptList { + execsql $sql db1 + execsql $sql db2 + + compare_dbs db1 db2 incrvacuum-5.3.${tn} + do_test incrvacuum-5.3.${tn}.integrity1 { + execsql { PRAGMA integrity_check; } db1 + } {ok} + do_test incrvacuum-5.3.${tn}.integrity2 { + execsql { PRAGMA integrity_check; } db2 + } {ok} + incr tn +} +db1 close +db2 close +# +# End of test cases 5.3.* + +#--------------------------------------------------------------------- +# The following tests - incrvacuum-6.* - test running incremental +# vacuum while another statement (a read) is being executed. +# +for {set jj 0} {$jj < 10} {incr jj} { + # Build some test data. Two tables are created in an empty + # database. tbl1 data is a contiguous block starting at page 5 (pages + # 3 and 4 are the table roots). tbl2 is a contiguous block starting + # right after tbl1. + # + # Then drop tbl1 so that when an incr vacuum is run the pages + # of tbl2 have to be moved to fill the gap. + # + do_test incrvacuum-6.${jj}.1 { + execsql { + DROP TABLE IF EXISTS tbl1; + DROP TABLE IF EXISTS tbl2; + PRAGMA incremental_vacuum; + CREATE TABLE tbl1(a, b); + CREATE TABLE tbl2(a, b); + BEGIN; + } + for {set ii 0} {$ii < 1000} {incr ii} { + db eval {INSERT INTO tbl1 VALUES($ii, $ii || $ii)} + } + execsql { + INSERT INTO tbl2 SELECT * FROM tbl1; + COMMIT; + DROP TABLE tbl1; + } + expr {[file size test.db] / 1024} + } {36} + + # Run a linear scan query on tbl2. After reading ($jj*100) rows, + # run the incremental vacuum to shrink the database. + # + do_test incrvacuum-6.${jj}.2 { + set ::nRow 0 + db eval {SELECT a FROM tbl2} {} { + if {$a == [expr $jj*100]} { + db eval {PRAGMA incremental_vacuum} + } + incr ::nRow + } + list [expr {[file size test.db] / 1024}] $nRow + } {19 1000} +} + +#--------------------------------------------------------------------- +# This test - incrvacuum-7.* - is to check that the database can be +# written in the middle of an incremental vacuum. +# +set ::iWrite 1 +while 1 { + do_test incrvacuum-7.${::iWrite}.1 { + execsql { + DROP TABLE IF EXISTS tbl1; + DROP TABLE IF EXISTS tbl2; + PRAGMA incremental_vacuum; + CREATE TABLE tbl1(a, b); + CREATE TABLE tbl2(a, b); + BEGIN; + } + for {set ii 0} {$ii < 1000} {incr ii} { + db eval {INSERT INTO tbl1 VALUES($ii, $ii || $ii)} + } + execsql { + INSERT INTO tbl2 SELECT * FROM tbl1; + COMMIT; + DROP TABLE tbl1; + } + expr {[file size test.db] / 1024} + } {36} + + do_test incrvacuum-7.${::iWrite}.2 { + set ::nRow 0 + db eval {PRAGMA incremental_vacuum} { + incr ::nRow + if {$::nRow == $::iWrite} { + db eval { + CREATE TABLE tbl1(a, b); + INSERT INTO tbl1 VALUES('hello', 'world'); + } + } + } + list [expr {[file size test.db] / 1024}] + } {20} + + do_test incrvacuum-7.${::iWrite}.3 { + execsql { + SELECT * FROM tbl1; + } + } {hello world} + + if {$::nRow == $::iWrite} break + incr ::iWrite +} + +#--------------------------------------------------------------------- +# This test - incrvacuum-8.* - is to check that nothing goes wrong +# with an incremental-vacuum if it is the first statement executed +# after an existing database is opened. +# +# At one point, this would always return SQLITE_SCHEMA (which +# causes an infinite loop in tclsqlite.c if using the Tcl interface). +# +do_test incrvacuum-8.1 { + db close + sqlite3 db test.db + execsql { + PRAGMA incremental_vacuum(50); + } +} {} + +#--------------------------------------------------------------------- +# At one point this test case was causing an assert() to fail. +# +do_test incrvacuum-9.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + + execsql { + PRAGMA auto_vacuum = 'incremental'; + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(a, b, c); + INSERT INTO t2 VALUES(randstr(500,500),randstr(500,500),randstr(500,500)); + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1; + INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1; + INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1; + INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1; + INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1; + INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1; + INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1; + INSERT INTO t1 SELECT a||a, b||b, c||c FROM t1; + } +} {} + +do_test incrvacuum-9.2 { + execsql { + PRAGMA synchronous = 'OFF'; + BEGIN; + UPDATE t1 SET a = a, b = b, c = c; + DROP TABLE t2; + PRAGMA incremental_vacuum(10); + ROLLBACK; + } +} {} + +do_test incrvacuum-9.3 { + execsql { + PRAGMA cache_size = 10; + BEGIN; + UPDATE t1 SET a = a, b = b, c = c; + DROP TABLE t2; + PRAGMA incremental_vacuum(10); + ROLLBACK; + } +} {} + +#--------------------------------------------------------------------- +# Test that the parameter to the incremental_vacuum pragma works. That +# is, if the user executes "PRAGMA incremental_vacuum(N)", at most +# N pages are vacuumed. +# +do_test incrvacuum-10.1 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + } + expr [file size test.db] / 1024 +} {29} + +do_test incrvacuum-10.2 { + execsql { + PRAGMA incremental_vacuum(1); + } + expr [file size test.db] / 1024 +} {28} + +do_test incrvacuum-10.3 { + execsql { + PRAGMA incremental_vacuum(5); + } + expr [file size test.db] / 1024 +} {23} + +do_test incrvacuum-10.4 { + execsql { + PRAGMA incremental_vacuum('1'); + } + expr [file size test.db] / 1024 +} {22} + +do_test incrvacuum-10.5 { + execsql { + PRAGMA incremental_vacuum("+3"); + } + expr [file size test.db] / 1024 +} {19} + +do_test incrvacuum-10.6 { + execsql { + PRAGMA incremental_vacuum = 1; + } + expr [file size test.db] / 1024 +} {18} + +do_test incrvacuum-10.7 { + # Use a really big number as an argument to incremetal_vacuum. Should + # be interpreted as "free all possible space". + execsql { + PRAGMA incremental_vacuum(2147483649); + } + expr [file size test.db] / 1024 +} {1} + +do_test incrvacuum-10.8 { + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(hex(randomblob(1000))); + DROP TABLE t1; + } + # A negative number means free all possible space. + execsql { + PRAGMA incremental_vacuum=-1; + } + expr [file size test.db] / 1024 +} {1} + +#---------------------------------------------------------------- +# Test that if we set the auto_vacuum mode to 'incremental', then +# create a database, thereafter that database defaults to incremental +# vacuum mode. +# +db close +forcedelete test.db test.db-journal +sqlite3 db test.db + +ifcapable default_autovacuum { + do_test incrvacuum-11.1-av-dflt-on { + execsql { + PRAGMA auto_vacuum; + } + } $AUTOVACUUM +} else { + do_test incrvacuum-11.1-av-dflt-off { + execsql { + PRAGMA auto_vacuum; + } + } {0} +} +do_test incrvacuum-11.2 { + execsql { + PRAGMA auto_vacuum = incremental; + } +} {} +do_test incrvacuum-11.3 { + execsql { + PRAGMA auto_vacuum; + } +} {2} +do_test incrvacuum-11.4 { + # The database has now been created. + expr {[file size test.db]>0} +} {1} +do_test incrvacuum-11.5 { + # Close and reopen the connection. + db close + sqlite3 db test.db + + # Test we are still in incremental vacuum mode. + execsql { PRAGMA auto_vacuum; } +} {2} +do_test incrvacuum-11.6 { + execsql { + PRAGMA auto_vacuum = 'full'; + PRAGMA auto_vacuum; + } +} {1} +do_test incrvacuum-11.7 { + # Close and reopen the connection. + db close + sqlite3 db test.db + + # Test we are still in "full" auto-vacuum mode. + execsql { PRAGMA auto_vacuum; } +} {1} + +#---------------------------------------------------------------------- +# Special case: What happens if the database is locked when a "PRAGMA +# auto_vacuum = XXX" statement is executed. +# +db close +forcedelete test.db test.db-journal +sqlite3 db test.db + +do_test incrvacuum-12.1 { + execsql { + PRAGMA auto_vacuum = 1; + } + expr {[file size test.db]>0} +} {1} + +# Try to change the auto-vacuum from "full" to "incremental" while the +# database is locked. Nothing should change. +# +do_test incrvacuum-12.2 { + sqlite3 db2 test.db + execsql { BEGIN EXCLUSIVE; } db2 + catchsql { PRAGMA auto_vacuum = 2; } +} {1 {database is locked}} + +do_test incrvacuum-12.3 { + execsql { ROLLBACK; } db2 + execsql { PRAGMA auto_vacuum } +} {2} ;# Still 2 because PRAGMA auto_vacuum setting held in case of vacuum +do_test incrvacuum-12.4 { + db close + sqlite3 db test.db + execsql { PRAGMA auto_vacuum } +} {1} ;# Revert to 1 because the database file did not change + +do_test incrvacuum-12.5 { + execsql { SELECT * FROM sqlite_master } + execsql { PRAGMA auto_vacuum } +} {1} + +#---------------------------------------------------------------------- +# Special case #2: What if one process prepares a "PRAGMA auto_vacuum = XXX" +# statement when the database is empty, but doesn't execute it until +# after some other process has created the database. +# +db2 close +db close +forcedelete test.db test.db-journal +sqlite3 db test.db ; set ::DB [sqlite3_connection_pointer db] +sqlite3 db2 test.db + +do_test incrvacuum-13.1 { + # File size is sometimes 1 instead of 0 due to the hack we put in + # to work around ticket #3260. Search for comments on #3260 in + # os_unix.c. + expr {[file size test.db]>1} +} {0} +do_test incrvacuum-13.2 { + set ::STMT [sqlite3_prepare $::DB {PRAGMA auto_vacuum = 2} -1 DUMMY] + execsql { + PRAGMA auto_vacuum = none; + PRAGMA default_cache_size = 1024; + PRAGMA auto_vacuum; + } db2 +} {0} +do_test incrvacuum-13.3 { + expr {[file size test.db]>0} +} {1} +do_test incrvacuum-13.4 { + set rc [sqlite3_step $::STMT] + list $rc [sqlite3_finalize $::STMT] +} {SQLITE_DONE SQLITE_OK} +do_test incrvacuum-13.5 { + execsql { + PRAGMA auto_vacuum; + } +} {0} + + +# Verify that the incremental_vacuum pragma fails gracefully if it +# is used against an invalid database file. +# +if {[permutation] == ""} { + do_test incrvacuum-14.1 { + set out [open invalid.db w] + puts $out "This is not an SQLite database file" + close $out + sqlite3 db3 invalid.db + catchsql { + PRAGMA incremental_vacuum(10); + } db3 + } {1 {file is encrypted or is not a database}} + db3 close +} + +do_test incrvacuum-15.1 { + db close + db2 close + forcedelete test.db + sqlite3 db test.db + + set str [string repeat "abcdefghij" 500] + + execsql { + PRAGMA cache_size = 10; + PRAGMA auto_vacuum = incremental; + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES('a', $str); + INSERT INTO t1 VALUES('b', $str); + INSERT INTO t1 VALUES('c', $str); + INSERT INTO t1 VALUES('d', $str); + INSERT INTO t1 VALUES('e', $str); + INSERT INTO t1 VALUES('f', $str); + INSERT INTO t1 VALUES('g', $str); + INSERT INTO t1 VALUES('h', $str); + INSERT INTO t1 VALUES('i', $str); + INSERT INTO t1 VALUES('j', $str); + INSERT INTO t1 VALUES('j', $str); + + CREATE TABLE t2(x PRIMARY KEY, y); + INSERT INTO t2 VALUES('a', $str); + INSERT INTO t2 VALUES('b', $str); + INSERT INTO t2 VALUES('c', $str); + INSERT INTO t2 VALUES('d', $str); + + BEGIN; + DELETE FROM t2; + PRAGMA incremental_vacuum; + } + + catchsql {INSERT INTO t2 SELECT * FROM t1} + + execsql { + COMMIT; + PRAGMA integrity_check; + } +} {ok} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrvacuum2.test b/components/external/SQLite-3.8.1/test/incrvacuum2.test new file mode 100644 index 0000000000000000000000000000000000000000..6e8e1bed5e14854bf0c908e938606757dcca795a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrvacuum2.test @@ -0,0 +1,211 @@ +# 2007 May 04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the incremental vacuum feature. +# +# $Id: incrvacuum2.test,v 1.6 2009/07/25 13:42:50 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If this build of the library does not support auto-vacuum, omit this +# whole file. +ifcapable {!autovacuum || !pragma} { + finish_test + return +} + +set testprefix incrvacuum2 + +# Create a database in incremental vacuum mode that has many +# pages on the freelist. +# +do_test incrvacuum2-1.1 { + execsql { + PRAGMA page_size=1024; + PRAGMA auto_vacuum=incremental; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(zeroblob(30000)); + DELETE FROM t1; + } + file size test.db +} {32768} + +# Vacuum off a single page. +# +do_test incrvacuum2-1.2 { + execsql { + PRAGMA incremental_vacuum(1); + } + file size test.db +} {31744} + +# Vacuum off five pages +# +do_test incrvacuum2-1.3 { + execsql { + PRAGMA incremental_vacuum(5); + } + file size test.db +} {26624} + +# Vacuum off all the rest +# +do_test incrvacuum2-1.4 { + execsql { + PRAGMA incremental_vacuum(1000); + } + file size test.db +} {3072} + +# Make sure incremental vacuum works on attached databases. +# +ifcapable attach { + do_test incrvacuum2-2.1 { + forcedelete test2.db test2.db-journal + execsql { + ATTACH DATABASE 'test2.db' AS aux; + PRAGMA aux.auto_vacuum=incremental; + CREATE TABLE aux.t2(x); + INSERT INTO t2 VALUES(zeroblob(30000)); + INSERT INTO t1 SELECT * FROM t2; + DELETE FROM t2; + DELETE FROM t1; + } + list [file size test.db] [file size test2.db] + } {32768 32768} + do_test incrvacuum2-2.2 { + execsql { + PRAGMA aux.incremental_vacuum(1) + } + list [file size test.db] [file size test2.db] + } {32768 31744} + do_test incrvacuum2-2.3 { + execsql { + PRAGMA aux.incremental_vacuum(5) + } + list [file size test.db] [file size test2.db] + } {32768 26624} + do_test incrvacuum2-2.4 { + execsql { + PRAGMA main.incremental_vacuum(5) + } + list [file size test.db] [file size test2.db] + } {27648 26624} + do_test incrvacuum2-2.5 { + execsql { + PRAGMA aux.incremental_vacuum + } + list [file size test.db] [file size test2.db] + } {27648 3072} + do_test incrvacuum2-2.6 { + execsql { + PRAGMA incremental_vacuum(1) + } + list [file size test.db] [file size test2.db] + } {26624 3072} +} + +do_test incrvacuum2-3.1 { + execsql { + PRAGMA auto_vacuum = 'full'; + BEGIN; + CREATE TABLE abc(a); + INSERT INTO abc VALUES(randstr(1500,1500)); + COMMIT; + } +} {} +do_test incrvacuum2-3.2 { + execsql { + BEGIN; + DELETE FROM abc; + PRAGMA incremental_vacuum; + COMMIT; + } +} {} + +integrity_check incrvacuum2-3.3 + +ifcapable wal { + # At one point, when a specific page was being extracted from the b-tree + # free-list (e.g. during an incremental-vacuum), all trunk pages that + # occurred before the specific page in the free-list trunk were being + # written to the journal or wal file. This is not necessary. Only the + # extracted page and the page that contains the pointer to it need to + # be journalled. + # + # This problem was fixed by [d03d63d77e] (just before 3.7.6 release). + # + # This test case builds a database containing many free pages. Then runs + # "PRAGMA incremental_vacuum(1)" until the db contains zero free pages. + # Each "PRAGMA incremental_vacuum(1)" should modify at most 4 pages. The + # worst case is when a trunk page is removed from the end of the db file. + # In this case pages written are: + # + # 1. The previous trunk page (that contains a pointer to the recycled + # trunk page), and + # 2. The leaf page transformed into a trunk page to replace the recycled + # page, and + # 3. The trunk page that contained a pointer to the leaf page used + # in (2), and + # 4. Page 1. Page 1 is always updated, even in WAL mode, since it contains + # the "number of free-list pages" field. + # + db close + forcedelete test.db + sqlite3 db test.db + + do_execsql_test 4.1 { + PRAGMA page_size = 512; + PRAGMA auto_vacuum = 2; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(400)); + INSERT INTO t1 SELECT * FROM t1; -- 2 + INSERT INTO t1 SELECT * FROM t1; -- 4 + INSERT INTO t1 SELECT * FROM t1; -- 8 + INSERT INTO t1 SELECT * FROM t1; -- 16 + INSERT INTO t1 SELECT * FROM t1; -- 32 + INSERT INTO t1 SELECT * FROM t1; -- 128 + INSERT INTO t1 SELECT * FROM t1; -- 256 + INSERT INTO t1 SELECT * FROM t1; -- 512 + INSERT INTO t1 SELECT * FROM t1; -- 1024 + INSERT INTO t1 SELECT * FROM t1; -- 2048 + INSERT INTO t1 SELECT * FROM t1; -- 4096 + INSERT INTO t1 SELECT * FROM t1; -- 8192 + DELETE FROM t1 WHERE oid>512; + DELETE FROM t1; + } + + do_test 4.2 { + execsql { + PRAGMA journal_mode = WAL; + PRAGMA incremental_vacuum(1); + PRAGMA wal_checkpoint; + } + file size test.db-wal + } [expr {32+2*(512+24)}] + + do_test 4.3 { + db close + sqlite3 db test.db + set maxsz 0 + while {[file size test.db] > [expr 512*3]} { + execsql { PRAGMA journal_mode = WAL } + execsql { PRAGMA wal_checkpoint } + execsql { PRAGMA incremental_vacuum(1) } + set newsz [file size test.db-wal] + if {$newsz>$maxsz} {set maxsz $newsz} + } + set maxsz + } [expr {32+3*(512+24)}] +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrvacuum3.test b/components/external/SQLite-3.8.1/test/incrvacuum3.test new file mode 100644 index 0000000000000000000000000000000000000000..e901bfe1f59bd26ba083551eea08dde5f98fdd5d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrvacuum3.test @@ -0,0 +1,153 @@ +# 2013 Feb 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for the SQLite library, focusing +# on the incremental vacuum feature. +# +# The tests in this file were added at the same time as optimizations +# were made to: +# +# * Truncate the database after a rollback mode commit, and +# +# * Avoid moving pages to locations from which they may need to be moved +# a second time if an incremental-vacuum proccess is allowed to vacuum +# the entire database. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix incrvacuum3 + +# If this build of the library does not support auto-vacuum, omit this +# whole file. +ifcapable {!autovacuum || !pragma} { + finish_test + return +} + +proc check_on_disk {} { + + # Copy the wal and journal files for database "test.db" to "test2.db". + forcedelete test2.db test2.db-journal test2.db-wal + if {[file exists test.db-journal]} { + forcecopy test.db-journal test2.db-journal + } + if {[file exists test.db-wal]} { + forcecopy test.db-wal test2.db-wal + } + + # Now copy the database file itself. Do this using open/read/puts + # instead of the [file copy] command in order to avoid attempting + # to read the 512 bytes begining at offset $sqlite_pending_byte. + # + set sz [file size test.db] + set fd [open test.db] + set fd2 [open test2.db w] + fconfigure $fd -encoding binary -translation binary + fconfigure $fd2 -encoding binary -translation binary + if {$sz>$::sqlite_pending_byte} { + puts -nonewline $fd2 [read $fd $::sqlite_pending_byte] + seek $fd [expr $::sqlite_pending_byte+512] + seek $fd2 [expr $::sqlite_pending_byte+512] + } + puts -nonewline $fd2 [read $fd] + close $fd2 + close $fd + + # Open "test2.db" and check it is Ok. + sqlite3 dbcheck test2.db + set ret [dbcheck eval { PRAGMA integrity_check }] + dbcheck close + set ret +} + +# Run these tests once in rollback journal mode, and once in wal mode. +# +foreach {T jrnl_mode} { + 1 delete + 2 wal +} { + catch { db close } + forcedelete test.db test.db-journal test.db-wal + sqlite3 db test.db + db eval { + PRAGMA cache_size = 5; + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 2; + } + db eval "PRAGMA journal_mode = $jrnl_mode" + + foreach {tn sql} { + 1 { + CREATE TABLE t1(x UNIQUE); + INSERT INTO t1 VALUES(randomblob(400)); + INSERT INTO t1 VALUES(randomblob(400)); + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 256 + } + + 2 { + DELETE FROM t1 WHERE rowid%8; + } + + 3 { + BEGIN; + PRAGMA incremental_vacuum = 100; + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 256 + ROLLBACK; + } + + 4 { + BEGIN; + SAVEPOINT one; + PRAGMA incremental_vacuum = 100; + SAVEPOINT two; + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 256 + } + + 5 { ROLLBACK to two } + + 6 { ROLLBACK to one } + + 7 { + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 64 + PRAGMA incremental_vacuum = 1000; + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 256 + ROLLBACK; + } + + 8 { + BEGIN; + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 64 + PRAGMA incremental_vacuum = 1000; + INSERT INTO t1 SELECT randomblob(400) FROM t1; -- 128 + COMMIT; + } + } { + do_execsql_test $T.1.$tn.1 $sql + do_execsql_test $T.1.$tn.2 {PRAGMA integrity_check} ok + do_test $T.1.$tn.3 { check_on_disk } ok + } + + do_execsql_test $T.1.x.1 { PRAGMA freelist_count } 0 + do_execsql_test $T.1.x.2 { SELECT count(*) FROM t1 } 128 +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/incrvacuum_ioerr.test b/components/external/SQLite-3.8.1/test/incrvacuum_ioerr.test new file mode 100644 index 0000000000000000000000000000000000000000..50f7fa2029b2041ad01110e9a3ab03b1358f856e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/incrvacuum_ioerr.test @@ -0,0 +1,182 @@ +# 2001 October 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing for correct handling of I/O errors +# such as writes failing because the disk is full. +# +# The tests in this file use special facilities that are only +# available in the SQLite test fixture. +# +# $Id: incrvacuum_ioerr.test,v 1.6 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If this build of the library does not support auto-vacuum, omit this +# whole file. +ifcapable {!autovacuum} { + finish_test + return +} + +do_ioerr_test incrvacuum-ioerr-1 -cksum 1 -sqlprep { + PRAGMA auto_vacuum = 'incremental'; + CREATE TABLE abc(a); + INSERT INTO abc VALUES(randstr(1500,1500)); +} -sqlbody { + BEGIN; + CREATE TABLE abc2(a); + DELETE FROM abc; + PRAGMA incremental_vacuum; + COMMIT; +} + +# do_ioerr_test incrvacuum-ioerr-3 -start 1 -cksum 1 -tclprep { +# db eval { +# PRAGMA auto_vacuum = 'full'; +# PRAGMA cache_size = 10; +# BEGIN; +# CREATE TABLE abc(a, UNIQUE(a)); +# } +# for {set ii 0} {$ii < 25} {incr ii} { +# db eval {INSERT INTO abc VALUES(randstr(1500,1500))} +# } +# db eval COMMIT +# } -sqlbody { +# BEGIN; +# DELETE FROM abc WHERE (oid%3)==0; +# INSERT INTO abc SELECT a || '1234567890' FROM abc WHERE oid%2; +# CREATE INDEX abc_i ON abc(a); +# DELETE FROM abc WHERE (oid%2)==0; +# DROP INDEX abc_i; +# COMMIT; +# } + +do_ioerr_test incrvacuum-ioerr-2 -start 1 -cksum 1 -tclprep { + db eval { + PRAGMA auto_vacuum = 'full'; + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE abc(a, UNIQUE(a)); + } + for {set ii 0} {$ii < 25} {incr ii} { + db eval {INSERT INTO abc VALUES(randstr(1500,1500))} + } + db eval COMMIT +} -sqlbody { + BEGIN; + PRAGMA incremental_vacuum; + DELETE FROM abc WHERE (oid%3)==0; + PRAGMA incremental_vacuum; + INSERT INTO abc SELECT a || '1234567890' FROM abc WHERE oid%2; + PRAGMA incremental_vacuum; + CREATE INDEX abc_i ON abc(a); + DELETE FROM abc WHERE (oid%2)==0; + PRAGMA incremental_vacuum; + DROP INDEX abc_i; + PRAGMA incremental_vacuum; + COMMIT; +} + +do_ioerr_test incrvacuum-ioerr-3 -start 1 -cksum 1 -tclprep { + db eval { + PRAGMA auto_vacuum = 'incremental'; + BEGIN; + CREATE TABLE a(i integer, b blob); + INSERT INTO a VALUES(1, randstr(1500,1500)); + INSERT INTO a VALUES(2, randstr(1500,1500)); + } + db eval COMMIT + db eval {DELETE FROM a WHERE oid} +} -sqlbody { + PRAGMA incremental_vacuum(5); +} -cleanup { + sqlite3 db test.db + integrity_check incrvacuum-ioerr-2.$n.integritycheck + db close +} + + +ifcapable shared_cache { + + catch { db close } + forcedelete test.db + set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + + # Create two connections to a single shared-cache: + # + sqlite3 db1 test.db + sqlite3 db2 test.db + + # Create a database with around 20 free pages. + # + do_test incrvacuum-ioerr-4.0 { + execsql { + PRAGMA page_size = 1024; + PRAGMA locking_mode = exclusive; + PRAGMA auto_vacuum = 'incremental'; + BEGIN; + CREATE TABLE a(i integer, b blob); + } db1 + for {set ii 0} {$ii < 20} {incr ii} { + execsql { INSERT INTO a VALUES($ii, randstr(800,1500)); } db1 + } + execsql COMMIT db1 + execsql {DELETE FROM a WHERE oid} db1 + } {} + + set ::rc 1 + for {set iTest 1} {$::rc && $iTest<2000} {incr iTest} { + + # Figure out how big the database is and how many free pages it + # has before running incremental-vacuum. + # + set nFree [execsql {pragma freelist_count} db1] + set nPage [execsql {pragma page_count} db1] + puts "nFree=$nFree nPage=$nPage" + + # Now run incremental-vacuum to vacuum 5 pages from the db file. + # The iTest'th I/O call is set to fail. + # + set ::sqlite_io_error_pending $iTest + set ::sqlite_io_error_persist 1 + do_test incrvacuum-ioerr-4.$iTest.1 { + set ::rc [catch {execsql {pragma incremental_vacuum(5)} db1} msg] + expr {$::rc==0 || $msg eq "disk I/O error"} + } {1} + + set ::sqlite_io_error_pending 0 + set ::sqlite_io_error_persist 0 + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_hardhit 0 + + set nFree2 [execsql {pragma freelist_count} db1] + set nPage2 [execsql {pragma page_count} db1] + + do_test incrvacuum-ioerr-4.$iTest.2 { + set shrink [expr {$nPage-$nPage2}] + expr {$shrink==0 || $shrink==5 || ($nFree<5 && $shrink==$nFree)} + } {1} + + do_test incrvacuum-ioerr-4.$iTest.3 { + expr {$nPage - $nPage2} + } [expr {$nFree - $nFree2}] + } + + # Close the two database connections and restore the default + # shared-cache mode setting. + # + db1 close + db2 close + sqlite3_enable_shared_cache $::enable_shared_cache +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/index.test b/components/external/SQLite-3.8.1/test/index.test new file mode 100644 index 0000000000000000000000000000000000000000..2b95bad830025d3d88e45e17e4190e6ed2f5dd11 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/index.test @@ -0,0 +1,737 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the CREATE INDEX statement. +# +# $Id: index.test,v 1.43 2008/01/16 18:20:42 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a basic index and verify it is added to sqlite_master +# +do_test index-1.1 { + execsql {CREATE TABLE test1(f1 int, f2 int, f3 int)} + execsql {CREATE INDEX index1 ON test1(f1)} + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {index1 test1} +do_test index-1.1b { + execsql {SELECT name, sql, tbl_name, type FROM sqlite_master + WHERE name='index1'} +} {index1 {CREATE INDEX index1 ON test1(f1)} test1 index} +do_test index-1.1c { + db close + sqlite3 db test.db + execsql {SELECT name, sql, tbl_name, type FROM sqlite_master + WHERE name='index1'} +} {index1 {CREATE INDEX index1 ON test1(f1)} test1 index} +do_test index-1.1d { + db close + sqlite3 db test.db + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {index1 test1} + +# Verify that the index dies with the table +# +do_test index-1.2 { + execsql {DROP TABLE test1} + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {} + +# Try adding an index to a table that does not exist +# +do_test index-2.1 { + set v [catch {execsql {CREATE INDEX index1 ON test1(f1)}} msg] + lappend v $msg +} {1 {no such table: main.test1}} + +# Try adding an index on a column of a table where the table +# exists but the column does not. +# +do_test index-2.1 { + execsql {CREATE TABLE test1(f1 int, f2 int, f3 int)} + set v [catch {execsql {CREATE INDEX index1 ON test1(f4)}} msg] + lappend v $msg +} {1 {table test1 has no column named f4}} + +# Try an index with some columns that match and others that do now. +# +do_test index-2.2 { + set v [catch {execsql {CREATE INDEX index1 ON test1(f1, f2, f4, f3)}} msg] + execsql {DROP TABLE test1} + lappend v $msg +} {1 {table test1 has no column named f4}} + +# Try creating a bunch of indices on the same table +# +set r {} +for {set i 1} {$i<100} {incr i} { + lappend r [format index%02d $i] +} +do_test index-3.1 { + execsql {CREATE TABLE test1(f1 int, f2 int, f3 int, f4 int, f5 int)} + for {set i 1} {$i<100} {incr i} { + set sql "CREATE INDEX [format index%02d $i] ON test1(f[expr {($i%5)+1}])" + execsql $sql + } + execsql {SELECT name FROM sqlite_master + WHERE type='index' AND tbl_name='test1' + ORDER BY name} +} $r +integrity_check index-3.2.1 +ifcapable {reindex} { + do_test index-3.2.2 { + execsql REINDEX + } {} +} +integrity_check index-3.2.3 + + +# Verify that all the indices go away when we drop the table. +# +do_test index-3.3 { + execsql {DROP TABLE test1} + execsql {SELECT name FROM sqlite_master + WHERE type='index' AND tbl_name='test1' + ORDER BY name} +} {} + +# Create a table and insert values into that table. Then create +# an index on that table. Verify that we can select values +# from the table correctly using the index. +# +# Note that the index names "index9" and "indext" are chosen because +# they both have the same hash. +# +do_test index-4.1 { + execsql {CREATE TABLE test1(cnt int, power int)} + for {set i 1} {$i<20} {incr i} { + execsql "INSERT INTO test1 VALUES($i,[expr {1<<$i}])" + } + execsql {CREATE INDEX index9 ON test1(cnt)} + execsql {CREATE INDEX indext ON test1(power)} + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {index9 indext test1} +do_test index-4.2 { + execsql {SELECT cnt FROM test1 WHERE power=4} +} {2} +do_test index-4.3 { + execsql {SELECT cnt FROM test1 WHERE power=1024} +} {10} +do_test index-4.4 { + execsql {SELECT power FROM test1 WHERE cnt=6} +} {64} +do_test index-4.5 { + execsql {DROP INDEX indext} + execsql {SELECT power FROM test1 WHERE cnt=6} +} {64} +do_test index-4.6 { + execsql {SELECT cnt FROM test1 WHERE power=1024} +} {10} +do_test index-4.7 { + execsql {CREATE INDEX indext ON test1(cnt)} + execsql {SELECT power FROM test1 WHERE cnt=6} +} {64} +do_test index-4.8 { + execsql {SELECT cnt FROM test1 WHERE power=1024} +} {10} +do_test index-4.9 { + execsql {DROP INDEX index9} + execsql {SELECT power FROM test1 WHERE cnt=6} +} {64} +do_test index-4.10 { + execsql {SELECT cnt FROM test1 WHERE power=1024} +} {10} +do_test index-4.11 { + execsql {DROP INDEX indext} + execsql {SELECT power FROM test1 WHERE cnt=6} +} {64} +do_test index-4.12 { + execsql {SELECT cnt FROM test1 WHERE power=1024} +} {10} +do_test index-4.13 { + execsql {DROP TABLE test1} + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {} +integrity_check index-4.14 + +# Do not allow indices to be added to sqlite_master +# +do_test index-5.1 { + set v [catch {execsql {CREATE INDEX index1 ON sqlite_master(name)}} msg] + lappend v $msg +} {1 {table sqlite_master may not be indexed}} +do_test index-5.2 { + execsql {SELECT name FROM sqlite_master WHERE type!='meta'} +} {} + +# Do not allow indices with duplicate names to be added +# +do_test index-6.1 { + execsql {CREATE TABLE test1(f1 int, f2 int)} + execsql {CREATE TABLE test2(g1 real, g2 real)} + execsql {CREATE INDEX index1 ON test1(f1)} + set v [catch {execsql {CREATE INDEX index1 ON test2(g1)}} msg] + lappend v $msg +} {1 {index index1 already exists}} +do_test index-6.1.1 { + catchsql {CREATE INDEX [index1] ON test2(g1)} +} {1 {index index1 already exists}} +do_test index-6.1b { + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {index1 test1 test2} +do_test index-6.1c { + catchsql {CREATE INDEX IF NOT EXISTS index1 ON test1(f1)} +} {0 {}} +do_test index-6.2 { + set v [catch {execsql {CREATE INDEX test1 ON test2(g1)}} msg] + lappend v $msg +} {1 {there is already a table named test1}} +do_test index-6.2b { + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {index1 test1 test2} +do_test index-6.3 { + execsql {DROP TABLE test1} + execsql {DROP TABLE test2} + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {} +do_test index-6.4 { + execsql { + CREATE TABLE test1(a,b); + CREATE INDEX index1 ON test1(a); + CREATE INDEX index2 ON test1(b); + CREATE INDEX index3 ON test1(a,b); + DROP TABLE test1; + SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name; + } +} {} +integrity_check index-6.5 + + +# Create a primary key +# +do_test index-7.1 { + execsql {CREATE TABLE test1(f1 int, f2 int primary key)} + for {set i 1} {$i<20} {incr i} { + execsql "INSERT INTO test1 VALUES($i,[expr {1<<$i}])" + } + execsql {SELECT count(*) FROM test1} +} {19} +do_test index-7.2 { + execsql {SELECT f1 FROM test1 WHERE f2=65536} +} {16} +do_test index-7.3 { + execsql { + SELECT name FROM sqlite_master + WHERE type='index' AND tbl_name='test1' + } +} {sqlite_autoindex_test1_1} +do_test index-7.4 { + execsql {DROP table test1} + execsql {SELECT name FROM sqlite_master WHERE type!='meta'} +} {} +integrity_check index-7.5 + +# Make sure we cannot drop a non-existant index. +# +do_test index-8.1 { + set v [catch {execsql {DROP INDEX index1}} msg] + lappend v $msg +} {1 {no such index: index1}} + +# Make sure we don't actually create an index when the EXPLAIN keyword +# is used. +# +do_test index-9.1 { + execsql {CREATE TABLE tab1(a int)} + ifcapable {explain} { + execsql {EXPLAIN CREATE INDEX idx1 ON tab1(a)} + } + execsql {SELECT name FROM sqlite_master WHERE tbl_name='tab1'} +} {tab1} +do_test index-9.2 { + execsql {CREATE INDEX idx1 ON tab1(a)} + execsql {SELECT name FROM sqlite_master WHERE tbl_name='tab1' ORDER BY name} +} {idx1 tab1} +integrity_check index-9.3 + +# Allow more than one entry with the same key. +# +do_test index-10.0 { + execsql { + CREATE TABLE t1(a int, b int); + CREATE INDEX i1 ON t1(a); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(2,4); + INSERT INTO t1 VALUES(3,8); + INSERT INTO t1 VALUES(1,12); + SELECT b FROM t1 WHERE a=1 ORDER BY b; + } +} {2 12} +do_test index-10.1 { + execsql { + SELECT b FROM t1 WHERE a=2 ORDER BY b; + } +} {4} +do_test index-10.2 { + execsql { + DELETE FROM t1 WHERE b=12; + SELECT b FROM t1 WHERE a=1 ORDER BY b; + } +} {2} +do_test index-10.3 { + execsql { + DELETE FROM t1 WHERE b=2; + SELECT b FROM t1 WHERE a=1 ORDER BY b; + } +} {} +do_test index-10.4 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES (1,1); + INSERT INTO t1 VALUES (1,2); + INSERT INTO t1 VALUES (1,3); + INSERT INTO t1 VALUES (1,4); + INSERT INTO t1 VALUES (1,5); + INSERT INTO t1 VALUES (1,6); + INSERT INTO t1 VALUES (1,7); + INSERT INTO t1 VALUES (1,8); + INSERT INTO t1 VALUES (1,9); + INSERT INTO t1 VALUES (2,0); + SELECT b FROM t1 WHERE a=1 ORDER BY b; + } +} {1 2 3 4 5 6 7 8 9} +do_test index-10.5 { + ifcapable subquery { + execsql { DELETE FROM t1 WHERE b IN (2, 4, 6, 8); } + } else { + execsql { DELETE FROM t1 WHERE b = 2 OR b = 4 OR b = 6 OR b = 8; } + } + execsql { + SELECT b FROM t1 WHERE a=1 ORDER BY b; + } +} {1 3 5 7 9} +do_test index-10.6 { + execsql { + DELETE FROM t1 WHERE b>2; + SELECT b FROM t1 WHERE a=1 ORDER BY b; + } +} {1} +do_test index-10.7 { + execsql { + DELETE FROM t1 WHERE b=1; + SELECT b FROM t1 WHERE a=1 ORDER BY b; + } +} {} +do_test index-10.8 { + execsql { + SELECT b FROM t1 ORDER BY b; + } +} {0} +integrity_check index-10.9 + +# Automatically create an index when we specify a primary key. +# +do_test index-11.1 { + execsql { + CREATE TABLE t3( + a text, + b int, + c float, + PRIMARY KEY(b) + ); + } + for {set i 1} {$i<=50} {incr i} { + execsql "INSERT INTO t3 VALUES('x${i}x',$i,0.$i)" + } + set sqlite_search_count 0 + concat [execsql {SELECT c FROM t3 WHERE b==10}] $sqlite_search_count +} {0.1 2} +integrity_check index-11.2 + + +# Numeric strings should compare as if they were numbers. So even if the +# strings are not character-by-character the same, if they represent the +# same number they should compare equal to one another. Verify that this +# is true in indices. +# +# Updated for sqlite3 v3: SQLite will now store these values as numbers +# (because the affinity of column a is NUMERIC) so the quirky +# representations are not retained. i.e. '+1.0' becomes '1'. +do_test index-12.1 { + execsql { + CREATE TABLE t4(a NUM,b); + INSERT INTO t4 VALUES('0.0',1); + INSERT INTO t4 VALUES('0.00',2); + INSERT INTO t4 VALUES('abc',3); + INSERT INTO t4 VALUES('-1.0',4); + INSERT INTO t4 VALUES('+1.0',5); + INSERT INTO t4 VALUES('0',6); + INSERT INTO t4 VALUES('00000',7); + SELECT a FROM t4 ORDER BY b; + } +} {0 0 abc -1 1 0 0} +do_test index-12.2 { + execsql { + SELECT a FROM t4 WHERE a==0 ORDER BY b + } +} {0 0 0 0} +do_test index-12.3 { + execsql { + SELECT a FROM t4 WHERE a<0.5 ORDER BY b + } +} {0 0 -1 0 0} +do_test index-12.4 { + execsql { + SELECT a FROM t4 WHERE a>-0.5 ORDER BY b + } +} {0 0 abc 1 0 0} +do_test index-12.5 { + execsql { + CREATE INDEX t4i1 ON t4(a); + SELECT a FROM t4 WHERE a==0 ORDER BY b + } +} {0 0 0 0} +do_test index-12.6 { + execsql { + SELECT a FROM t4 WHERE a<0.5 ORDER BY b + } +} {0 0 -1 0 0} +do_test index-12.7 { + execsql { + SELECT a FROM t4 WHERE a>-0.5 ORDER BY b + } +} {0 0 abc 1 0 0} +integrity_check index-12.8 + +# Make sure we cannot drop an automatically created index. +# +do_test index-13.1 { + execsql { + CREATE TABLE t5( + a int UNIQUE, + b float PRIMARY KEY, + c varchar(10), + UNIQUE(a,c) + ); + INSERT INTO t5 VALUES(1,2,3); + SELECT * FROM t5; + } +} {1 2.0 3} +do_test index-13.2 { + set ::idxlist [execsql { + SELECT name FROM sqlite_master WHERE type="index" AND tbl_name="t5"; + }] + llength $::idxlist +} {3} +for {set i 0} {$i<[llength $::idxlist]} {incr i} { + do_test index-13.3.$i { + catchsql " + DROP INDEX '[lindex $::idxlist $i]'; + " + } {1 {index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped}} +} +do_test index-13.4 { + execsql { + INSERT INTO t5 VALUES('a','b','c'); + SELECT * FROM t5; + } +} {1 2.0 3 a b c} +integrity_check index-13.5 + +# Check the sort order of data in an index. +# +do_test index-14.1 { + execsql { + CREATE TABLE t6(a,b,c); + CREATE INDEX t6i1 ON t6(a,b); + INSERT INTO t6 VALUES('','',1); + INSERT INTO t6 VALUES('',NULL,2); + INSERT INTO t6 VALUES(NULL,'',3); + INSERT INTO t6 VALUES('abc',123,4); + INSERT INTO t6 VALUES(123,'abc',5); + SELECT c FROM t6 ORDER BY a,b; + } +} {3 5 2 1 4} +do_test index-14.2 { + execsql { + SELECT c FROM t6 WHERE a=''; + } +} {2 1} +do_test index-14.3 { + execsql { + SELECT c FROM t6 WHERE b=''; + } +} {1 3} +do_test index-14.4 { + execsql { + SELECT c FROM t6 WHERE a>''; + } +} {4} +do_test index-14.5 { + execsql { + SELECT c FROM t6 WHERE a>=''; + } +} {2 1 4} +do_test index-14.6 { + execsql { + SELECT c FROM t6 WHERE a>123; + } +} {2 1 4} +do_test index-14.7 { + execsql { + SELECT c FROM t6 WHERE a>=123; + } +} {5 2 1 4} +do_test index-14.8 { + execsql { + SELECT c FROM t6 WHERE a<'abc'; + } +} {5 2 1} +do_test index-14.9 { + execsql { + SELECT c FROM t6 WHERE a<='abc'; + } +} {5 2 1 4} +do_test index-14.10 { + execsql { + SELECT c FROM t6 WHERE a<=''; + } +} {5 2 1} +do_test index-14.11 { + execsql { + SELECT c FROM t6 WHERE a<''; + } +} {5} +integrity_check index-14.12 + +do_test index-15.1 { + execsql { + DELETE FROM t1; + SELECT * FROM t1; + } +} {} +do_test index-15.2 { + execsql { + INSERT INTO t1 VALUES('1.234e5',1); + INSERT INTO t1 VALUES('12.33e04',2); + INSERT INTO t1 VALUES('12.35E4',3); + INSERT INTO t1 VALUES('12.34e',4); + INSERT INTO t1 VALUES('12.32e+4',5); + INSERT INTO t1 VALUES('12.36E+04',6); + INSERT INTO t1 VALUES('12.36E+',7); + INSERT INTO t1 VALUES('+123.10000E+0003',8); + INSERT INTO t1 VALUES('+',9); + INSERT INTO t1 VALUES('+12347.E+02',10); + INSERT INTO t1 VALUES('+12347E+02',11); + INSERT INTO t1 VALUES('+.125E+04',12); + INSERT INTO t1 VALUES('-.125E+04',13); + INSERT INTO t1 VALUES('.125E+0',14); + INSERT INTO t1 VALUES('.125',15); + SELECT b FROM t1 ORDER BY a, b; + } +} {13 14 15 12 8 5 2 1 3 6 10 11 9 4 7} +do_test index-15.3 { + execsql { + SELECT b FROM t1 WHERE typeof(a) IN ('integer','real') ORDER BY b; + } +} {1 2 3 5 6 8 10 11 12 13 14 15} +integrity_check index-15.4 + +# The following tests - index-16.* - test that when a table definition +# includes qualifications that specify the same constraint twice only a +# single index is generated to enforce the constraint. +# +# For example: "CREATE TABLE abc( x PRIMARY KEY, UNIQUE(x) );" +# +do_test index-16.1 { + execsql { + CREATE TABLE t7(c UNIQUE PRIMARY KEY); + SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index'; + } +} {1} +do_test index-16.2 { + execsql { + DROP TABLE t7; + CREATE TABLE t7(c UNIQUE PRIMARY KEY); + SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index'; + } +} {1} +do_test index-16.3 { + execsql { + DROP TABLE t7; + CREATE TABLE t7(c PRIMARY KEY, UNIQUE(c) ); + SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index'; + } +} {1} +do_test index-16.4 { + execsql { + DROP TABLE t7; + CREATE TABLE t7(c, d , UNIQUE(c, d), PRIMARY KEY(c, d) ); + SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index'; + } +} {1} +do_test index-16.5 { + execsql { + DROP TABLE t7; + CREATE TABLE t7(c, d , UNIQUE(c), PRIMARY KEY(c, d) ); + SELECT count(*) FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index'; + } +} {2} + +# Test that automatically create indices are named correctly. The current +# convention is: "sqlite_autoindex_
    _" +# +# Then check that it is an error to try to drop any automtically created +# indices. +do_test index-17.1 { + execsql { + DROP TABLE t7; + CREATE TABLE t7(c, d UNIQUE, UNIQUE(c), PRIMARY KEY(c, d) ); + SELECT name FROM sqlite_master WHERE tbl_name = 't7' AND type = 'index'; + } +} {sqlite_autoindex_t7_1 sqlite_autoindex_t7_2 sqlite_autoindex_t7_3} +do_test index-17.2 { + catchsql { + DROP INDEX sqlite_autoindex_t7_1; + } +} {1 {index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped}} +do_test index-17.3 { + catchsql { + DROP INDEX IF EXISTS sqlite_autoindex_t7_1; + } +} {1 {index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped}} +do_test index-17.4 { + catchsql { + DROP INDEX IF EXISTS no_such_index; + } +} {0 {}} + + +# The following tests ensure that it is not possible to explicitly name +# a schema object with a name beginning with "sqlite_". Granted that is a +# little outside the focus of this test scripts, but this has got to be +# tested somewhere. +do_test index-18.1 { + catchsql { + CREATE TABLE sqlite_t1(a, b, c); + } +} {1 {object name reserved for internal use: sqlite_t1}} +do_test index-18.2 { + catchsql { + CREATE INDEX sqlite_i1 ON t7(c); + } +} {1 {object name reserved for internal use: sqlite_i1}} +ifcapable view { +do_test index-18.3 { + catchsql { + CREATE VIEW sqlite_v1 AS SELECT * FROM t7; + } +} {1 {object name reserved for internal use: sqlite_v1}} +} ;# ifcapable view +ifcapable {trigger} { + do_test index-18.4 { + catchsql { + CREATE TRIGGER sqlite_tr1 BEFORE INSERT ON t7 BEGIN SELECT 1; END; + } + } {1 {object name reserved for internal use: sqlite_tr1}} +} +do_test index-18.5 { + execsql { + DROP TABLE t7; + } +} {} + +# These tests ensure that if multiple table definition constraints are +# implemented by a single indice, the correct ON CONFLICT policy applies. +ifcapable conflict { + do_test index-19.1 { + execsql { + CREATE TABLE t7(a UNIQUE PRIMARY KEY); + CREATE TABLE t8(a UNIQUE PRIMARY KEY ON CONFLICT ROLLBACK); + INSERT INTO t7 VALUES(1); + INSERT INTO t8 VALUES(1); + } + } {} + do_test index-19.2 { + catchsql { + BEGIN; + INSERT INTO t7 VALUES(1); + } + } {1 {column a is not unique}} + do_test index-19.3 { + catchsql { + BEGIN; + } + } {1 {cannot start a transaction within a transaction}} + do_test index-19.4 { + catchsql { + INSERT INTO t8 VALUES(1); + } + } {1 {column a is not unique}} + do_test index-19.5 { + catchsql { + BEGIN; + COMMIT; + } + } {0 {}} + do_test index-19.6 { + catchsql { + DROP TABLE t7; + DROP TABLE t8; + CREATE TABLE t7( + a PRIMARY KEY ON CONFLICT FAIL, + UNIQUE(a) ON CONFLICT IGNORE + ); + } + } {1 {conflicting ON CONFLICT clauses specified}} +} ; # end of "ifcapable conflict" block + +ifcapable {reindex} { + do_test index-19.7 { + execsql REINDEX + } {} +} +integrity_check index-19.8 + +# Drop index with a quoted name. Ticket #695. +# +do_test index-20.1 { + execsql { + CREATE INDEX "t6i2" ON t6(c); + DROP INDEX "t6i2"; + } +} {} +do_test index-20.2 { + execsql { + DROP INDEX "t6i1"; + } +} {} + +# Try to create a TEMP index on a non-TEMP table. */ +# +do_test index-21.1 { + catchsql { + CREATE INDEX temp.i21 ON t6(c); + } +} {1 {cannot create a TEMP index on non-TEMP table "t6"}} +do_test index-21.2 { + catchsql { + CREATE TEMP TABLE t6(x); + INSERT INTO temp.t6 values(1),(5),(9); + CREATE INDEX temp.i21 ON t6(x); + SELECT x FROM t6 ORDER BY x DESC; + } +} {0 {9 5 1}} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/index2.test b/components/external/SQLite-3.8.1/test/index2.test new file mode 100644 index 0000000000000000000000000000000000000000..48d0c38e1879ad04652edab494476d4cc05f3611 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/index2.test @@ -0,0 +1,74 @@ +# 2005 January 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the CREATE INDEX statement. +# +# $Id: index2.test,v 1.3 2006/03/03 19:12:30 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table with a large number of columns +# +do_test index2-1.1 { + set sql {CREATE TABLE t1(} + for {set i 1} {$i<1000} {incr i} { + append sql "c$i," + } + append sql "c1000);" + execsql $sql +} {} +do_test index2-1.2 { + set sql {INSERT INTO t1 VALUES(} + for {set i 1} {$i<1000} {incr i} { + append sql $i, + } + append sql {1000);} + execsql $sql +} {} +do_test index2-1.3 { + execsql {SELECT c123 FROM t1} +} 123 +do_test index2-1.4 { + execsql BEGIN + for {set j 1} {$j<=100} {incr j} { + set sql {INSERT INTO t1 VALUES(} + for {set i 1} {$i<1000} {incr i} { + append sql [expr {$j*10000+$i}], + } + append sql "[expr {$j*10000+1000}]);" + execsql $sql + } + execsql COMMIT + execsql {SELECT count(*) FROM t1} +} 101 +do_test index2-1.5 { + execsql {SELECT round(sum(c1000)) FROM t1} +} {50601000.0} + +# Create indices with many columns +# +do_test index2-2.1 { + set sql "CREATE INDEX t1i1 ON t1(" + for {set i 1} {$i<1000} {incr i} { + append sql c$i, + } + append sql c1000) + execsql $sql +} {} +do_test index2-2.2 { + ifcapable explain { + execsql {EXPLAIN SELECT c9 FROM t1 ORDER BY c1, c2, c3, c4, c5} + } + execsql {SELECT c9 FROM t1 ORDER BY c1, c2, c3, c4, c5, c6 LIMIT 5} +} {9 10009 20009 30009 40009} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/index3.test b/components/external/SQLite-3.8.1/test/index3.test new file mode 100644 index 0000000000000000000000000000000000000000..161ddecc01277b2d94572fd1b0f190ad555e5cf2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/index3.test @@ -0,0 +1,56 @@ +# 2005 February 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the CREATE INDEX statement. +# +# $Id: index3.test,v 1.3 2008/03/19 13:03:34 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Ticket #1115. Make sure that when a UNIQUE index is created on a +# non-unique column (or columns) that it fails and that it leaves no +# residue behind. +# +do_test index3-1.1 { + execsql { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(1); + SELECT * FROM t1; + } +} {1 1} +do_test index3-1.2 { + catchsql { + BEGIN; + CREATE UNIQUE INDEX i1 ON t1(a); + } +} {1 {indexed columns are not unique}} +do_test index3-1.3 { + catchsql COMMIT; +} {0 {}} +integrity_check index3-1.4 + +# This test corrupts the database file so it must be the last test +# in the series. +# +do_test index3-99.1 { + execsql { + PRAGMA writable_schema=on; + UPDATE sqlite_master SET sql='nonsense'; + } + db close + catch { sqlite3 db test.db } + catchsql { DROP INDEX i1 } +} {1 {malformed database schema (t1) - near "nonsense": syntax error}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/index4.test b/components/external/SQLite-3.8.1/test/index4.test new file mode 100644 index 0000000000000000000000000000000000000000..018ed744a17b676ec38f698a22c4b88f14bf8757 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/index4.test @@ -0,0 +1,126 @@ +# 2011 July 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the CREATE INDEX statement. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set testprefix index4 + +do_execsql_test 1.1 { + BEGIN; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(102)); + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 2 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 256 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 512 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 1024 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 2048 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 4096 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 8192 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 16384 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 32768 + INSERT INTO t1 SELECT randomblob(102) FROM t1; -- 65536 + COMMIT; +} + +do_execsql_test 1.2 { + CREATE INDEX i1 ON t1(x); +} +do_execsql_test 1.3 { + PRAGMA integrity_check +} {ok} + +# The same test again - this time with limited memory. +# +ifcapable memorymanage { + set soft_limit [sqlite3_soft_heap_limit 50000] + + db close + sqlite3 db test.db + + do_execsql_test 1.4 { + PRAGMA cache_size = 10; + CREATE INDEX i2 ON t1(x); + } + do_execsql_test 1.5 { + PRAGMA integrity_check + } {ok} + + sqlite3_soft_heap_limit $soft_limit +} + + +do_execsql_test 1.6 { + BEGIN; + DROP TABLE t1; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('a'); + INSERT INTO t1 VALUES('b'); + INSERT INTO t1 VALUES('c'); + INSERT INTO t1 VALUES('d'); + INSERT INTO t1 VALUES('e'); + INSERT INTO t1 VALUES('f'); + INSERT INTO t1 VALUES('g'); + INSERT INTO t1 VALUES(NULL); + INSERT INTO t1 SELECT randomblob(1202) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(2202) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(3202) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(4202) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(5202) FROM t1; -- 256 + COMMIT; + CREATE INDEX i1 ON t1(x); + PRAGMA integrity_check +} {ok} + +do_execsql_test 1.7 { + BEGIN; + DROP TABLE t1; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('a'); + COMMIT; + CREATE INDEX i1 ON t1(x); + PRAGMA integrity_check +} {ok} + +do_execsql_test 1.8 { + BEGIN; + DROP TABLE t1; + CREATE TABLE t1(x); + COMMIT; + CREATE INDEX i1 ON t1(x); + PRAGMA integrity_check +} {ok} + +do_execsql_test 2.1 { + BEGIN; + CREATE TABLE t2(x); + INSERT INTO t2 VALUES(14); + INSERT INTO t2 VALUES(35); + INSERT INTO t2 VALUES(15); + INSERT INTO t2 VALUES(35); + INSERT INTO t2 VALUES(16); + COMMIT; +} +do_catchsql_test 2.2 { + CREATE UNIQUE INDEX i3 ON t2(x); +} {1 {indexed columns are not unique}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/index5.test b/components/external/SQLite-3.8.1/test/index5.test new file mode 100644 index 0000000000000000000000000000000000000000..7895391309de132e3129ec9e5d9de90d19e95285 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/index5.test @@ -0,0 +1,75 @@ +# 2012 August 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix index5 + +do_test 1.1 { + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(x); + BEGIN; + } + for {set i 0} {$i < 100000} {incr i} { + execsql { INSERT INTO t1 VALUES(randstr(100,100)) } + } + execsql COMMIT + execsql { + CREATE INDEX i1 ON t1(x); + DROP INDEX I1; + PRAGMA main.page_size; + } +} {1024} + +db close +testvfs tvfs +tvfs filter xWrite +tvfs script write_cb +proc write_cb {xCall file handle iOfst args} { + if {[file tail $file]=="test.db"} { + lappend ::write_list [expr $iOfst/1024] + } +} + +do_test 1.2 { + sqlite3 db test.db -vfs tvfs + set ::write_list [list] + execsql { CREATE INDEX i1 ON t1(x) } +} {} + +do_test 1.3 { + set nForward 0 + set nBackward 0 + set nNoncont 0 + set iPrev [lindex $::write_list 0] + for {set i 1} {$i < [llength $::write_list]} {incr i} { + set iNext [lindex $::write_list $i] + if {$iNext==($iPrev+1)} { + incr nForward + } elseif {$iNext==($iPrev-1)} { + incr nBackward + } else { + incr nNoncont + } + set iPrev $iNext + } + puts -nonewline \ + " (forward=$nForward, back=$nBackward, noncontiguous=$nNoncont)" + + expr {$nForward > 2*($nBackward + $nNoncont)} +} {1} +db close +tvfs delete + +finish_test diff --git a/components/external/SQLite-3.8.1/test/index6.test b/components/external/SQLite-3.8.1/test/index6.test new file mode 100644 index 0000000000000000000000000000000000000000..c427dc3df32098d38633890c24c6031b1b5b4d88 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/index6.test @@ -0,0 +1,251 @@ +# 2013-07-31 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test cases for partial indices +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +load_static_extension db wholenumber; +do_test index6-1.1 { + # Able to parse and manage partial indices + execsql { + CREATE TABLE t1(a,b,c); + CREATE INDEX t1a ON t1(a) WHERE a IS NOT NULL; + CREATE INDEX t1b ON t1(b) WHERE b>10; + CREATE VIRTUAL TABLE nums USING wholenumber; + INSERT INTO t1(a,b,c) + SELECT CASE WHEN value%3!=0 THEN value END, value, value + FROM nums WHERE value<=20; + SELECT count(a), count(b) FROM t1; + PRAGMA integrity_check; + } +} {14 20 ok} + +# Make sure the count(*) optimization works correctly with +# partial indices. Ticket [a5c8ed66cae16243be6] 2013-10-03. +# +do_execsql_test index6-1.1.1 { + SELECT count(*) FROM t1; +} {20} + +# Error conditions during parsing... +# +do_test index6-1.2 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE x IS NOT NULL; + } +} {1 {no such column: x}} +do_test index6-1.3 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE EXISTS(SELECT * FROM t1); + } +} {1 {subqueries prohibited in partial index WHERE clauses}} +do_test index6-1.4 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE a!=?1; + } +} {1 {parameters prohibited in partial index WHERE clauses}} +do_test index6-1.5 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE a!=random(); + } +} {1 {functions prohibited in partial index WHERE clauses}} +do_test index6-1.6 { + catchsql { + CREATE INDEX bad1 ON t1(a,b) WHERE a NOT LIKE 'abc%'; + } +} {1 {functions prohibited in partial index WHERE clauses}} + +do_test index6-1.10 { + execsql { + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {{} 20 t1a {14 1} t1b {10 1} ok} + +# STAT1 shows the partial indices have a reduced number of +# rows. +# +do_test index6-1.11 { + execsql { + UPDATE t1 SET a=b; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {{} 20 t1a {20 1} t1b {10 1} ok} + +do_test index6-1.11 { + execsql { + UPDATE t1 SET a=NULL WHERE b%3!=0; + UPDATE t1 SET b=b+100; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {{} 20 t1a {6 1} t1b {20 1} ok} + +do_test index6-1.12 { + execsql { + UPDATE t1 SET a=CASE WHEN b%3!=0 THEN b END; + UPDATE t1 SET b=b-100; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {{} 20 t1a {13 1} t1b {10 1} ok} + +do_test index6-1.13 { + execsql { + DELETE FROM t1 WHERE b BETWEEN 8 AND 12; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {{} 15 t1a {10 1} t1b {8 1} ok} + +do_test index6-1.14 { + execsql { + REINDEX; + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {{} 15 t1a {10 1} t1b {8 1} ok} + +do_test index6-1.15 { + execsql { + CREATE INDEX t1c ON t1(c); + ANALYZE; + SELECT idx, stat FROM sqlite_stat1 ORDER BY idx; + PRAGMA integrity_check; + } +} {t1a {10 1} t1b {8 1} t1c {15 1} ok} + +# Queries use partial indices as appropriate times. +# +do_test index6-2.1 { + execsql { + CREATE TABLE t2(a,b); + INSERT INTO t2(a,b) SELECT value, value FROM nums WHERE value<1000; + UPDATE t2 SET a=NULL WHERE b%5==0; + CREATE INDEX t2a1 ON t2(a) WHERE a IS NOT NULL; + SELECT count(*) FROM t2 WHERE a IS NOT NULL; + } +} {800} +do_test index6-2.2 { + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t2 WHERE a=5; + } +} {/.* TABLE t2 USING INDEX t2a1 .*/} +ifcapable stat4||stat3 { + do_test index6-2.3stat4 { + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t2 WHERE a IS NOT NULL; + } + } {/.* TABLE t2 USING INDEX t2a1 .*/} +} else { + do_test index6-2.3stat4 { + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t2 WHERE a IS NOT NULL AND a>0; + } + } {/.* TABLE t2 USING INDEX t2a1 .*/} +} +do_test index6-2.4 { + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t2 WHERE a IS NULL; + } +} {~/.*INDEX t2a1.*/} + +do_execsql_test index6-2.101 { + DROP INDEX t2a1; + UPDATE t2 SET a=b, b=b+10000; + SELECT b FROM t2 WHERE a=15; +} {10015} +do_execsql_test index6-2.102 { + CREATE INDEX t2a2 ON t2(a) WHERE a<100 OR a>200; + SELECT b FROM t2 WHERE a=15; + PRAGMA integrity_check; +} {10015 ok} +do_execsql_test index6-2.102eqp { + EXPLAIN QUERY PLAN + SELECT b FROM t2 WHERE a=15; +} {~/.*INDEX t2a2.*/} +do_execsql_test index6-2.103 { + SELECT b FROM t2 WHERE a=15 AND a<100; +} {10015} +do_execsql_test index6-2.103eqp { + EXPLAIN QUERY PLAN + SELECT b FROM t2 WHERE a=15 AND a<100; +} {/.*INDEX t2a2.*/} +do_execsql_test index6-2.104 { + SELECT b FROM t2 WHERE a=515 AND a>200; +} {10515} +do_execsql_test index6-2.104eqp { + EXPLAIN QUERY PLAN + SELECT b FROM t2 WHERE a=515 AND a>200; +} {/.*INDEX t2a2.*/} + +# Partial UNIQUE indices +# +do_execsql_test index6-3.1 { + CREATE TABLE t3(a,b); + INSERT INTO t3 SELECT value, value FROM nums WHERE value<200; + UPDATE t3 SET a=999 WHERE b%5!=0; + CREATE UNIQUE INDEX t3a ON t3(a) WHERE a<>999; +} {} +do_test index6-3.2 { + # unable to insert a duplicate row a-value that is not 999. + catchsql { + INSERT INTO t3(a,b) VALUES(150, 'test1'); + } +} {1 {column a is not unique}} +do_test index6-3.3 { + # can insert multiple rows with a==999 because such rows are not + # part of the unique index. + catchsql { + INSERT INTO t3(a,b) VALUES(999, 'test1'), (999, 'test2'); + } +} {0 {}} +do_execsql_test index6-3.4 { + SELECT count(*) FROM t3 WHERE a=999; +} {162} +integrity_check index6-3.5 + +do_execsql_test index6-4.0 { + VACUUM; + PRAGMA integrity_check; +} {ok} + +# Silently ignore database name qualifiers in partial indices. +# +do_execsql_test index6-5.0 { + CREATE INDEX t3b ON t3(b) WHERE xyzzy.t3.b BETWEEN 5 AND 10; + /* ^^^^^-- ignored */ + ANALYZE; + SELECT count(*) FROM t3 WHERE t3.b BETWEEN 5 AND 10; + SELECT stat+0 FROM sqlite_stat1 WHERE idx='t3b'; +} {6 6} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/indexedby.test b/components/external/SQLite-3.8.1/test/indexedby.test new file mode 100644 index 0000000000000000000000000000000000000000..f95c167f6411c0fb5f003ca4d9bc93995ec95c18 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/indexedby.test @@ -0,0 +1,324 @@ +# 2008 October 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: indexedby.test,v 1.5 2009/03/22 20:36:19 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix indexedby + +# Create a schema with some indexes. +# +do_test indexedby-1.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); + + CREATE TABLE t2(c, d); + CREATE INDEX i3 ON t2(c); + CREATE INDEX i4 ON t2(d); + + CREATE TABLE t3(e PRIMARY KEY, f); + + CREATE VIEW v1 AS SELECT * FROM t1; + } +} {} + +# Explain Query Plan +# +proc EQP {sql} { + uplevel "execsql {EXPLAIN QUERY PLAN $sql}" +} + +# These tests are to check that "EXPLAIN QUERY PLAN" is working as expected. +# +do_execsql_test indexedby-1.2 { + EXPLAIN QUERY PLAN select * from t1 WHERE a = 10; +} {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)}} +do_execsql_test indexedby-1.3 { + EXPLAIN QUERY PLAN select * from t1 ; +} {0 0 0 {SCAN TABLE t1}} +do_execsql_test indexedby-1.4 { + EXPLAIN QUERY PLAN select * from t1, t2 WHERE c = 10; +} { + 0 0 1 {SEARCH TABLE t2 USING INDEX i3 (c=?)} + 0 1 0 {SCAN TABLE t1} +} + +# Parser tests. Test that an INDEXED BY or NOT INDEX clause can be +# attached to a table in the FROM clause, but not to a sub-select or +# SQL view. Also test that specifying an index that does not exist or +# is attached to a different table is detected as an error. +# +do_test indexedby-2.1 { + execsql { SELECT * FROM t1 NOT INDEXED WHERE a = 'one' AND b = 'two'} +} {} +do_test indexedby-2.2 { + execsql { SELECT * FROM t1 INDEXED BY i1 WHERE a = 'one' AND b = 'two'} +} {} +do_test indexedby-2.3 { + execsql { SELECT * FROM t1 INDEXED BY i2 WHERE a = 'one' AND b = 'two'} +} {} + +do_test indexedby-2.4 { + catchsql { SELECT * FROM t1 INDEXED BY i3 WHERE a = 'one' AND b = 'two'} +} {1 {no such index: i3}} +do_test indexedby-2.5 { + catchsql { SELECT * FROM t1 INDEXED BY i5 WHERE a = 'one' AND b = 'two'} +} {1 {no such index: i5}} +do_test indexedby-2.6 { + catchsql { SELECT * FROM t1 INDEXED BY WHERE a = 'one' AND b = 'two'} +} {1 {near "WHERE": syntax error}} +do_test indexedby-2.7 { + catchsql { SELECT * FROM v1 INDEXED BY i1 WHERE a = 'one' } +} {1 {no such index: i1}} + +# Tests for single table cases. +# +do_execsql_test indexedby-3.1 { + EXPLAIN QUERY PLAN SELECT * FROM t1 NOT INDEXED WHERE a = 'one' AND b = 'two' +} {0 0 0 {SCAN TABLE t1}} +do_execsql_test indexedby-3.2 { + EXPLAIN QUERY PLAN + SELECT * FROM t1 INDEXED BY i1 WHERE a = 'one' AND b = 'two' +} {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)}} +do_execsql_test indexedby-3.3 { + EXPLAIN QUERY PLAN + SELECT * FROM t1 INDEXED BY i2 WHERE a = 'one' AND b = 'two' +} {0 0 0 {SEARCH TABLE t1 USING INDEX i2 (b=?)}} +do_test indexedby-3.4 { + catchsql { SELECT * FROM t1 INDEXED BY i2 WHERE a = 'one' } +} {1 {no query solution}} +do_test indexedby-3.5 { + catchsql { SELECT * FROM t1 INDEXED BY i2 ORDER BY a } +} {1 {no query solution}} +do_test indexedby-3.6 { + catchsql { SELECT * FROM t1 INDEXED BY i1 WHERE a = 'one' } +} {0 {}} +do_test indexedby-3.7 { + catchsql { SELECT * FROM t1 INDEXED BY i1 ORDER BY a } +} {0 {}} + +do_execsql_test indexedby-3.8 { + EXPLAIN QUERY PLAN + SELECT * FROM t3 INDEXED BY sqlite_autoindex_t3_1 ORDER BY e +} {0 0 0 {SCAN TABLE t3 USING INDEX sqlite_autoindex_t3_1}} +do_execsql_test indexedby-3.9 { + EXPLAIN QUERY PLAN + SELECT * FROM t3 INDEXED BY sqlite_autoindex_t3_1 WHERE e = 10 +} {0 0 0 {SEARCH TABLE t3 USING INDEX sqlite_autoindex_t3_1 (e=?)}} +do_test indexedby-3.10 { + catchsql { SELECT * FROM t3 INDEXED BY sqlite_autoindex_t3_1 WHERE f = 10 } +} {1 {no query solution}} +do_test indexedby-3.11 { + catchsql { SELECT * FROM t3 INDEXED BY sqlite_autoindex_t3_2 WHERE f = 10 } +} {1 {no such index: sqlite_autoindex_t3_2}} + +# Tests for multiple table cases. +# +do_execsql_test indexedby-4.1 { + EXPLAIN QUERY PLAN SELECT * FROM t1, t2 WHERE a = c +} { + 0 0 0 {SCAN TABLE t1} + 0 1 1 {SEARCH TABLE t2 USING INDEX i3 (c=?)} +} +do_execsql_test indexedby-4.2 { + EXPLAIN QUERY PLAN SELECT * FROM t1 INDEXED BY i1, t2 WHERE a = c +} { + 0 0 1 {SCAN TABLE t2} + 0 1 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)} +} +do_test indexedby-4.3 { + catchsql { + SELECT * FROM t1 INDEXED BY i1, t2 INDEXED BY i3 WHERE a=c + } +} {1 {no query solution}} +do_test indexedby-4.4 { + catchsql { + SELECT * FROM t2 INDEXED BY i3, t1 INDEXED BY i1 WHERE a=c + } +} {1 {no query solution}} + +# Test embedding an INDEXED BY in a CREATE VIEW statement. This block +# also tests that nothing bad happens if an index refered to by +# a CREATE VIEW statement is dropped and recreated. +# +do_execsql_test indexedby-5.1 { + CREATE VIEW v2 AS SELECT * FROM t1 INDEXED BY i1 WHERE a > 5; + EXPLAIN QUERY PLAN SELECT * FROM v2 +} {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a>?)}} +do_execsql_test indexedby-5.2 { + EXPLAIN QUERY PLAN SELECT * FROM v2 WHERE b = 10 +} {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a>?)}} +do_test indexedby-5.3 { + execsql { DROP INDEX i1 } + catchsql { SELECT * FROM v2 } +} {1 {no such index: i1}} +do_test indexedby-5.4 { + # Recreate index i1 in such a way as it cannot be used by the view query. + execsql { CREATE INDEX i1 ON t1(b) } + catchsql { SELECT * FROM v2 } +} {1 {no query solution}} +do_test indexedby-5.5 { + # Drop and recreate index i1 again. This time, create it so that it can + # be used by the query. + execsql { DROP INDEX i1 ; CREATE INDEX i1 ON t1(a) } + catchsql { SELECT * FROM v2 } +} {0 {}} + +# Test that "NOT INDEXED" may use the rowid index, but not others. +# +do_execsql_test indexedby-6.1 { + EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE b = 10 ORDER BY rowid +} {0 0 0 {SEARCH TABLE t1 USING INDEX i2 (b=?)}} +do_execsql_test indexedby-6.2 { + EXPLAIN QUERY PLAN SELECT * FROM t1 NOT INDEXED WHERE b = 10 ORDER BY rowid +} {0 0 0 {SCAN TABLE t1}} + +# Test that "INDEXED BY" can be used in a DELETE statement. +# +do_execsql_test indexedby-7.1 { + EXPLAIN QUERY PLAN DELETE FROM t1 WHERE a = 5 +} {0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i1 (a=?)}} +do_execsql_test indexedby-7.2 { + EXPLAIN QUERY PLAN DELETE FROM t1 NOT INDEXED WHERE a = 5 +} {0 0 0 {SCAN TABLE t1}} +do_execsql_test indexedby-7.3 { + EXPLAIN QUERY PLAN DELETE FROM t1 INDEXED BY i1 WHERE a = 5 +} {0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i1 (a=?)}} +do_execsql_test indexedby-7.4 { + EXPLAIN QUERY PLAN DELETE FROM t1 INDEXED BY i1 WHERE a = 5 AND b = 10 +} {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)}} +do_execsql_test indexedby-7.5 { + EXPLAIN QUERY PLAN DELETE FROM t1 INDEXED BY i2 WHERE a = 5 AND b = 10 +} {0 0 0 {SEARCH TABLE t1 USING INDEX i2 (b=?)}} +do_test indexedby-7.6 { + catchsql { DELETE FROM t1 INDEXED BY i2 WHERE a = 5} +} {1 {no query solution}} + +# Test that "INDEXED BY" can be used in an UPDATE statement. +# +do_execsql_test indexedby-8.1 { + EXPLAIN QUERY PLAN UPDATE t1 SET rowid=rowid+1 WHERE a = 5 +} {0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i1 (a=?)}} +do_execsql_test indexedby-8.2 { + EXPLAIN QUERY PLAN UPDATE t1 NOT INDEXED SET rowid=rowid+1 WHERE a = 5 +} {0 0 0 {SCAN TABLE t1}} +do_execsql_test indexedby-8.3 { + EXPLAIN QUERY PLAN UPDATE t1 INDEXED BY i1 SET rowid=rowid+1 WHERE a = 5 +} {0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i1 (a=?)}} +do_execsql_test indexedby-8.4 { + EXPLAIN QUERY PLAN + UPDATE t1 INDEXED BY i1 SET rowid=rowid+1 WHERE a = 5 AND b = 10 +} {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)}} +do_execsql_test indexedby-8.5 { + EXPLAIN QUERY PLAN + UPDATE t1 INDEXED BY i2 SET rowid=rowid+1 WHERE a = 5 AND b = 10 +} {0 0 0 {SEARCH TABLE t1 USING INDEX i2 (b=?)}} +do_test indexedby-8.6 { + catchsql { UPDATE t1 INDEXED BY i2 SET rowid=rowid+1 WHERE a = 5} +} {1 {no query solution}} + +# Test that bug #3560 is fixed. +# +do_test indexedby-9.1 { + execsql { + CREATE TABLE maintable( id integer); + CREATE TABLE joinme(id_int integer, id_text text); + CREATE INDEX joinme_id_text_idx on joinme(id_text); + CREATE INDEX joinme_id_int_idx on joinme(id_int); + } +} {} +do_test indexedby-9.2 { + catchsql { + select * from maintable as m inner join + joinme as j indexed by joinme_id_text_idx + on ( m.id = j.id_int) + } +} {1 {no query solution}} +do_test indexedby-9.3 { + catchsql { select * from maintable, joinme INDEXED by joinme_id_text_idx } +} {1 {no query solution}} + +# Make sure we can still create tables, indices, and columns whose name +# is "indexed". +# +do_test indexedby-10.1 { + execsql { + CREATE TABLE indexed(x,y); + INSERT INTO indexed VALUES(1,2); + SELECT * FROM indexed; + } +} {1 2} +do_test indexedby-10.2 { + execsql { + CREATE INDEX i10 ON indexed(x); + SELECT * FROM indexed indexed by i10 where x>0; + } +} {1 2} +do_test indexedby-10.3 { + execsql { + DROP TABLE indexed; + CREATE TABLE t10(indexed INTEGER); + INSERT INTO t10 VALUES(1); + CREATE INDEX indexed ON t10(indexed); + SELECT * FROM t10 indexed by indexed WHERE indexed>0 + } +} {1} + +#------------------------------------------------------------------------- +# Ensure that the rowid at the end of each index entry may be used +# for equality constraints in the same way as other indexed fields. +# +do_execsql_test 11.1 { + CREATE TABLE x1(a, b TEXT); + CREATE INDEX x1i ON x1(a, b); + INSERT INTO x1 VALUES(1, 1); + INSERT INTO x1 VALUES(1, 1); + INSERT INTO x1 VALUES(1, 1); + INSERT INTO x1 VALUES(1, 1); +} +do_execsql_test 11.2 { + SELECT a,b,rowid FROM x1 INDEXED BY x1i WHERE a=1 AND b=1 AND rowid=3; +} {1 1 3} +do_execsql_test 11.3 { + SELECT a,b,rowid FROM x1 INDEXED BY x1i WHERE a=1 AND b=1 AND rowid='3'; +} {1 1 3} +do_execsql_test 11.4 { + SELECT a,b,rowid FROM x1 INDEXED BY x1i WHERE a=1 AND b=1 AND rowid='3.0'; +} {1 1 3} +do_eqp_test 11.5 { + SELECT a,b,rowid FROM x1 INDEXED BY x1i WHERE a=1 AND b=1 AND rowid='3.0'; +} {0 0 0 {SEARCH TABLE x1 USING COVERING INDEX x1i (a=? AND b=? AND rowid=?)}} + +do_execsql_test 11.6 { + CREATE TABLE x2(c INTEGER PRIMARY KEY, a, b TEXT); + CREATE INDEX x2i ON x2(a, b); + INSERT INTO x2 VALUES(1, 1, 1); + INSERT INTO x2 VALUES(2, 1, 1); + INSERT INTO x2 VALUES(3, 1, 1); + INSERT INTO x2 VALUES(4, 1, 1); +} +do_execsql_test 11.7 { + SELECT a,b,c FROM x2 INDEXED BY x2i WHERE a=1 AND b=1 AND c=3; +} {1 1 3} +do_execsql_test 11.8 { + SELECT a,b,c FROM x2 INDEXED BY x2i WHERE a=1 AND b=1 AND c='3'; +} {1 1 3} +do_execsql_test 11.9 { + SELECT a,b,c FROM x2 INDEXED BY x2i WHERE a=1 AND b=1 AND c='3.0'; +} {1 1 3} +do_eqp_test 11.10 { + SELECT a,b,c FROM x2 INDEXED BY x2i WHERE a=1 AND b=1 AND c='3.0'; +} {0 0 0 {SEARCH TABLE x2 USING COVERING INDEX x2i (a=? AND b=? AND rowid=?)}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/indexfault.test b/components/external/SQLite-3.8.1/test/indexfault.test new file mode 100644 index 0000000000000000000000000000000000000000..efe493219edc907f8ef895842db7abbb8d2dea5a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/indexfault.test @@ -0,0 +1,342 @@ +# 2011 August 08 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +ifcapable !mergesort { + finish_test + return +} + +set testprefix indexfault + +# Set up the custom fault-injector. This is further configured by using +# different values for $::custom_filter and different implementations +# of Tcl proc [xCustom] for each test case. +# +proc install_custom_faultsim {} { + set ::FAULTSIM(custom) [list \ + -injectinstall custom_injectinstall \ + -injectstart custom_injectstart \ + -injectstop custom_injectstop \ + -injecterrlist {{1 {disk I/O error}}} \ + -injectuninstall custom_injectuninstall \ + ] + proc custom_injectinstall {} { + testvfs shmfault -default true + shmfault filter $::custom_filter + shmfault script xCustom + } + proc custom_injectuninstall {} { + catch {db close} + catch {db2 close} + shmfault delete + } + set ::custom_ifail -1 + set ::custom_nfail -1 + proc custom_injectstart {iFail} { + set ::custom_ifail $iFail + set ::custom_nfail 0 + } + proc custom_injectstop {} { + set ::custom_ifail -1 + return $::custom_nfail + } +} +proc uninstall_custom_faultsim {} { + unset -nocomplain ::FAULTSIM(custom) +} + + +#------------------------------------------------------------------------- +# These tests - indexfault-1.* - Build an index on a smallish table with +# all different kinds of fault-injection. The CREATE INDEX is run once +# with default options and once with a 50KB soft-heap-limit. +# +do_execsql_test 1.0 { + BEGIN; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(202)); + INSERT INTO t1 SELECT randomblob(202) FROM t1; -- 2 + INSERT INTO t1 SELECT randomblob(202) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(202) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(202) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(202) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(202) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(202) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(202) FROM t1; -- 256 + COMMIT; +} +faultsim_save_and_close + +do_faultsim_test 1.1 -prep { + faultsim_restore_and_reopen +} -body { + execsql { CREATE INDEX i1 ON t1(x) } + faultsim_test_result {0 {}} + faultsim_integrity_check +} +ifcapable memorymanage { + set soft_limit [sqlite3_soft_heap_limit 50000] + do_faultsim_test 2.1 -prep { + faultsim_restore_and_reopen + } -body { + execsql { CREATE INDEX i1 ON t1(x) } + faultsim_test_result {0 {}} + } + sqlite3_soft_heap_limit $soft_limit +} + +#------------------------------------------------------------------------- +# These are similar to the indexfault-1.* tests, except they create an +# index with more than one column. +# +sqlite3 db test.db +do_execsql_test 2.0 { + BEGIN; + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(t,u,v,w,x,y,z); + INSERT INTO t1 VALUES( + randomblob(30), randomblob(30), randomblob(30), randomblob(30), + randomblob(30), randomblob(30), randomblob(30) + ); + INSERT INTO t1 SELECT + randomblob(30), randomblob(30), randomblob(30), randomblob(30), + randomblob(30), randomblob(30), randomblob(30) FROM t1; -- 2 + INSERT INTO t1 SELECT + randomblob(30), randomblob(30), randomblob(30), randomblob(30), + randomblob(30), randomblob(30), randomblob(30) FROM t1; -- 4 + INSERT INTO t1 SELECT + randomblob(30), randomblob(30), randomblob(30), randomblob(30), + randomblob(30), randomblob(30), randomblob(30) FROM t1; -- 8 + INSERT INTO t1 SELECT + randomblob(30), randomblob(30), randomblob(30), randomblob(30), + randomblob(30), randomblob(30), randomblob(30) FROM t1; -- 16 + INSERT INTO t1 SELECT + randomblob(30), randomblob(30), randomblob(30), randomblob(30), + randomblob(30), randomblob(30), randomblob(30) FROM t1; -- 32 + INSERT INTO t1 SELECT + randomblob(30), randomblob(30), randomblob(30), randomblob(30), + randomblob(30), randomblob(30), randomblob(30) FROM t1; -- 64 + INSERT INTO t1 SELECT + randomblob(30), randomblob(30), randomblob(30), randomblob(30), + randomblob(30), randomblob(30), randomblob(30) FROM t1; -- 128 + COMMIT; +} +faultsim_save_and_close + +do_faultsim_test 2.1 -prep { + faultsim_restore_and_reopen +} -body { + execsql { CREATE INDEX i1 ON t1(t,u,v,w,x,y,z) } + faultsim_test_result {0 {}} + faultsim_integrity_check +} +ifcapable memorymanage { + set soft_limit [sqlite3_soft_heap_limit 50000] + do_faultsim_test 2.2 -prep { + faultsim_restore_and_reopen + } -body { + execsql { CREATE INDEX i1 ON t1(t,u,v,w,x,y,z) } + faultsim_test_result {0 {}} + } + sqlite3_soft_heap_limit $soft_limit +} + +#------------------------------------------------------------------------- +# The following tests - indexfault-2.* - all attempt to build a index +# on table t1 in the main database with injected IO errors. Individual +# test cases work as follows: +# +# 3.1: IO errors injected into xOpen() calls. +# 3.2: As 7.1, but with a low (50KB) soft-heap-limit. +# +# 3.3: IO errors injected into the first 200 write() calls made on the +# second temporary file. +# 3.4: As 7.3, but with a low (50KB) soft-heap-limit. +# +# 3.5: After a certain amount of data has been read from the main database +# file (and written into the temporary b-tree), sqlite3_release_memory() +# is called to free as much memory as possible. This causes the temp +# b-tree to be flushed to disk. So that before its contents can be +# transfered to a PMA they must be read back from disk - creating extra +# opportunities for IO errors. +# +install_custom_faultsim + +# Set up a table to build indexes on. Save the setup using the +# [faultsim_save_and_close] mechanism. +# +sqlite3 db test.db +do_execsql_test 3.0 { + BEGIN; + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(11000)); + INSERT INTO t1 SELECT randomblob(11001) FROM t1; -- 2 + INSERT INTO t1 SELECT randomblob(11002) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(11003) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(11004) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(11005) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(11006) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(11007) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(11008) FROM t1; -- 256 + INSERT INTO t1 SELECT randomblob(11009) FROM t1; -- 512 + COMMIT; +} +faultsim_save_and_close + +set ::custom_filter xOpen +proc xCustom {args} { + incr ::custom_ifail -1 + if {$::custom_ifail==0} { + incr ::custom_nfail + return "SQLITE_IOERR" + } + return "SQLITE_OK" +} +do_faultsim_test 3.1 -faults custom -prep { + faultsim_restore_and_reopen +} -body { + execsql { CREATE INDEX i1 ON t1(x) } + faultsim_test_result {0 {}} +} +ifcapable memorymanage { + set soft_limit [sqlite3_soft_heap_limit 50000] + do_faultsim_test 3.2 -faults custom -prep { + faultsim_restore_and_reopen + } -body { + execsql { CREATE INDEX i1 ON t1(x) } + faultsim_test_result {0 {}} + } + sqlite3_soft_heap_limit $soft_limit +} + +set ::custom_filter {xOpen xWrite} +proc xCustom {method args} { + if {$method == "xOpen"} { + if {[lindex $args 0] == ""} { + incr ::nTmpOpen 1 + if {$::nTmpOpen == 3} { return "failme" } + } + return "SQLITE_OK" + } + if {$::custom_ifail<200 && [lindex $args 1] == "failme"} { + incr ::custom_ifail -1 + if {$::custom_ifail==0} { + incr ::custom_nfail + return "SQLITE_IOERR" + } + } + return "SQLITE_OK" +} + +do_faultsim_test 3.3 -faults custom -prep { + faultsim_restore_and_reopen + set ::nTmpOpen 0 +} -body { + execsql { CREATE INDEX i1 ON t1(x) } + faultsim_test_result {0 {}} +} + +ifcapable memorymanage { + set soft_limit [sqlite3_soft_heap_limit 50000] + do_faultsim_test 3.4 -faults custom -prep { + faultsim_restore_and_reopen + set ::nTmpOpen 0 + } -body { + execsql { CREATE INDEX i1 ON t1(x) } + faultsim_test_result {0 {}} + } + sqlite3_soft_heap_limit $soft_limit +} + +uninstall_custom_faultsim + +#------------------------------------------------------------------------- +# Test 4: After a certain amount of data has been read from the main database +# file (and written into the temporary b-tree), sqlite3_release_memory() is +# called to free as much memory as possible. This causes the temp b-tree to be +# flushed to disk. So that before its contents can be transfered to a PMA they +# must be read back from disk - creating extra opportunities for IO errors. +# +install_custom_faultsim + +catch { db close } +forcedelete test.db +sqlite3 db test.db + +do_execsql_test 4.0 { + BEGIN; + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(11000)); + INSERT INTO t1 SELECT randomblob(11001) FROM t1; -- 2 + INSERT INTO t1 SELECT randomblob(11002) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(11003) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(11004) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(11005) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(11005) FROM t1; -- 64 + COMMIT; +} +faultsim_save_and_close + +testvfs tvfs +tvfs script xRead +tvfs filter xRead +set ::nRead 0 +proc xRead {method file args} { + if {[file tail $file] == "test.db"} { incr ::nRead } +} + +do_test 4.1 { + sqlite3 db test.db -vfs tvfs + execsql { CREATE INDEX i1 ON t1(x) } +} {} + +db close +tvfs delete + +set ::custom_filter xRead +proc xCustom {method file args} { + incr ::nReadCall + if {$::nReadCall >= ($::nRead/5)} { + if {$::nReadCall == ($::nRead/5)} { + set nByte [sqlite3_release_memory [expr 64*1024*1024]] + sqlite3_soft_heap_limit 20000 + } + if {$file == ""} { + incr ::custom_ifail -1 + if {$::custom_ifail==0} { + incr ::custom_nfail + return "SQLITE_IOERR" + } + } + } + return "SQLITE_OK" +} + +do_faultsim_test 4.2 -faults custom -prep { + faultsim_restore_and_reopen + set ::nReadCall 0 + sqlite3_soft_heap_limit 0 +} -body { + execsql { CREATE INDEX i1 ON t1(x) } + faultsim_test_result {0 {}} +} + +uninstall_custom_faultsim + +finish_test diff --git a/components/external/SQLite-3.8.1/test/init.test b/components/external/SQLite-3.8.1/test/init.test new file mode 100644 index 0000000000000000000000000000000000000000..7cb18f492ac142b7d1fccb89b3e7aba6b95b8abc --- /dev/null +++ b/components/external/SQLite-3.8.1/test/init.test @@ -0,0 +1,82 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this file is testing the effects of a failure in +# sqlite3_initialize(). +# +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +if {[db eval {SELECT sqlite_compileoption_used('THREADSAFE=0')}]} { + finish_test + return +} + +db close + +foreach {t failed rc started} { + 1.1 {} SQLITE_OK {mutex mem pcache} + 1.2 {mutex} SQLITE_ERROR {} + 1.3 {mem} SQLITE_ERROR {mutex} + 1.4 {pcache} SQLITE_ERROR {mutex mem} +} { + do_test init-$t.1 { + eval init_wrapper_install $failed + sqlite3_initialize + } $rc + do_test init-$t.2 { + init_wrapper_query + } $started + do_test init-$t.3 { + sqlite3_shutdown + init_wrapper_query + } {} + do_test init-$t.4 { + sqlite3_initialize + } $rc + do_test init-$t.5 { + init_wrapper_query + } $started + do_test init-$t.6 { + init_wrapper_clear + sqlite3_initialize + } SQLITE_OK + do_test init-$t.7 { + init_wrapper_query + } {mutex mem pcache} + do_test init-$t.8 { + init_wrapper_uninstall + } {} +} + +source $testdir/malloc_common.tcl +if {$MEMDEBUG} { + do_malloc_test init-2 -tclprep { + db close + init_wrapper_install + } -tclbody { + set rc [sqlite3_initialize] + if {[string match "SQLITE*NOMEM" $rc]} {error "out of memory"} + } -cleanup { + set zRepeat "transient" + if {$::iRepeat} {set zRepeat "persistent"} + do_test init-2.$zRepeat.$::n.x { + init_wrapper_clear + sqlite3_initialize + } SQLITE_OK + init_wrapper_uninstall + } +} + +autoinstall_test_functions +finish_test diff --git a/components/external/SQLite-3.8.1/test/insert.test b/components/external/SQLite-3.8.1/test/insert.test new file mode 100644 index 0000000000000000000000000000000000000000..e00b9a80289730f1c03c6fb700956418643a3e2c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/insert.test @@ -0,0 +1,408 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the INSERT statement. +# +# $Id: insert.test,v 1.31 2007/04/05 11:25:59 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Try to insert into a non-existant table. +# +do_test insert-1.1 { + set v [catch {execsql {INSERT INTO test1 VALUES(1,2,3)}} msg] + lappend v $msg +} {1 {no such table: test1}} + +# Try to insert into sqlite_master +# +do_test insert-1.2 { + set v [catch {execsql {INSERT INTO sqlite_master VALUES(1,2,3,4)}} msg] + lappend v $msg +} {1 {table sqlite_master may not be modified}} + +# Try to insert the wrong number of entries. +# +do_test insert-1.3 { + execsql {CREATE TABLE test1(one int, two int, three int)} + set v [catch {execsql {INSERT INTO test1 VALUES(1,2)}} msg] + lappend v $msg +} {1 {table test1 has 3 columns but 2 values were supplied}} +do_test insert-1.3b { + set v [catch {execsql {INSERT INTO test1 VALUES(1,2,3,4)}} msg] + lappend v $msg +} {1 {table test1 has 3 columns but 4 values were supplied}} +do_test insert-1.3c { + set v [catch {execsql {INSERT INTO test1(one,two) VALUES(1,2,3,4)}} msg] + lappend v $msg +} {1 {4 values for 2 columns}} +do_test insert-1.3d { + set v [catch {execsql {INSERT INTO test1(one,two) VALUES(1)}} msg] + lappend v $msg +} {1 {1 values for 2 columns}} + +# Try to insert into a non-existant column of a table. +# +do_test insert-1.4 { + set v [catch {execsql {INSERT INTO test1(one,four) VALUES(1,2)}} msg] + lappend v $msg +} {1 {table test1 has no column named four}} + +# Make sure the inserts actually happen +# +do_test insert-1.5 { + execsql {INSERT INTO test1 VALUES(1,2,3)} + execsql {SELECT * FROM test1} +} {1 2 3} +do_test insert-1.5b { + execsql {INSERT INTO test1 VALUES(4,5,6)} + execsql {SELECT * FROM test1 ORDER BY one} +} {1 2 3 4 5 6} +do_test insert-1.5c { + execsql {INSERT INTO test1 VALUES(7,8,9)} + execsql {SELECT * FROM test1 ORDER BY one} +} {1 2 3 4 5 6 7 8 9} + +do_test insert-1.6 { + execsql {DELETE FROM test1} + execsql {INSERT INTO test1(one,two) VALUES(1,2)} + execsql {SELECT * FROM test1 ORDER BY one} +} {1 2 {}} +do_test insert-1.6b { + execsql {INSERT INTO test1(two,three) VALUES(5,6)} + execsql {SELECT * FROM test1 ORDER BY one} +} {{} 5 6 1 2 {}} +do_test insert-1.6c { + execsql {INSERT INTO test1(three,one) VALUES(7,8)} + execsql {SELECT * FROM test1 ORDER BY one} +} {{} 5 6 1 2 {} 8 {} 7} + +# A table to use for testing default values +# +do_test insert-2.1 { + execsql { + CREATE TABLE test2( + f1 int default -111, + f2 real default +4.32, + f3 int default +222, + f4 int default 7.89 + ) + } + execsql {SELECT * from test2} +} {} +do_test insert-2.2 { + execsql {INSERT INTO test2(f1,f3) VALUES(+10,-10)} + execsql {SELECT * FROM test2} +} {10 4.32 -10 7.89} +do_test insert-2.3 { + execsql {INSERT INTO test2(f2,f4) VALUES(1.23,-3.45)} + execsql {SELECT * FROM test2 WHERE f1==-111} +} {-111 1.23 222 -3.45} +do_test insert-2.4 { + execsql {INSERT INTO test2(f1,f2,f4) VALUES(77,+1.23,3.45)} + execsql {SELECT * FROM test2 WHERE f1==77} +} {77 1.23 222 3.45} +do_test insert-2.10 { + execsql { + DROP TABLE test2; + CREATE TABLE test2( + f1 int default 111, + f2 real default -4.32, + f3 text default hi, + f4 text default 'abc-123', + f5 varchar(10) + ) + } + execsql {SELECT * from test2} +} {} +do_test insert-2.11 { + execsql {INSERT INTO test2(f2,f4) VALUES(-2.22,'hi!')} + execsql {SELECT * FROM test2} +} {111 -2.22 hi hi! {}} +do_test insert-2.12 { + execsql {INSERT INTO test2(f1,f5) VALUES(1,'xyzzy')} + execsql {SELECT * FROM test2 ORDER BY f1} +} {1 -4.32 hi abc-123 xyzzy 111 -2.22 hi hi! {}} + +# Do additional inserts with default values, but this time +# on a table that has indices. In particular we want to verify +# that the correct default values are inserted into the indices. +# +do_test insert-3.1 { + execsql { + DELETE FROM test2; + CREATE INDEX index9 ON test2(f1,f2); + CREATE INDEX indext ON test2(f4,f5); + SELECT * from test2; + } +} {} + +# Update for sqlite3 v3: +# Change the 111 to '111' in the following two test cases, because +# the default value is being inserted as a string. TODO: It shouldn't be. +do_test insert-3.2 { + execsql {INSERT INTO test2(f2,f4) VALUES(-3.33,'hum')} + execsql {SELECT * FROM test2 WHERE f1='111' AND f2=-3.33} +} {111 -3.33 hi hum {}} +do_test insert-3.3 { + execsql {INSERT INTO test2(f1,f2,f5) VALUES(22,-4.44,'wham')} + execsql {SELECT * FROM test2 WHERE f1='111' AND f2=-3.33} +} {111 -3.33 hi hum {}} +do_test insert-3.4 { + execsql {SELECT * FROM test2 WHERE f1=22 AND f2=-4.44} +} {22 -4.44 hi abc-123 wham} +ifcapable {reindex} { + do_test insert-3.5 { + execsql REINDEX + } {} +} +integrity_check insert-3.5 + +# Test of expressions in the VALUES clause +# +do_test insert-4.1 { + execsql { + CREATE TABLE t3(a,b,c); + INSERT INTO t3 VALUES(1+2+3,4,5); + SELECT * FROM t3; + } +} {6 4 5} +do_test insert-4.2 { + ifcapable subquery { + execsql {INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1,5,6);} + } else { + set maxa [execsql {SELECT max(a) FROM t3}] + execsql "INSERT INTO t3 VALUES($maxa+1,5,6);" + } + execsql { + SELECT * FROM t3 ORDER BY a; + } +} {6 4 5 7 5 6} +ifcapable subquery { + do_test insert-4.3 { + catchsql { + INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1,t3.a,6); + SELECT * FROM t3 ORDER BY a; + } + } {1 {no such column: t3.a}} +} +do_test insert-4.4 { + ifcapable subquery { + execsql {INSERT INTO t3 VALUES((SELECT b FROM t3 WHERE a=0),6,7);} + } else { + set b [execsql {SELECT b FROM t3 WHERE a = 0}] + if {$b==""} {set b NULL} + execsql "INSERT INTO t3 VALUES($b,6,7);" + } + execsql { + SELECT * FROM t3 ORDER BY a; + } +} {{} 6 7 6 4 5 7 5 6} +do_test insert-4.5 { + execsql { + SELECT b,c FROM t3 WHERE a IS NULL; + } +} {6 7} +do_test insert-4.6 { + catchsql { + INSERT INTO t3 VALUES(notafunc(2,3),2,3); + } +} {1 {no such function: notafunc}} +do_test insert-4.7 { + execsql { + INSERT INTO t3 VALUES(min(1,2,3),max(1,2,3),99); + SELECT * FROM t3 WHERE c=99; + } +} {1 3 99} + +# Test the ability to insert from a temporary table into itself. +# Ticket #275. +# +ifcapable tempdb { + do_test insert-5.1 { + execsql { + CREATE TEMP TABLE t4(x); + INSERT INTO t4 VALUES(1); + SELECT * FROM t4; + } + } {1} + do_test insert-5.2 { + execsql { + INSERT INTO t4 SELECT x+1 FROM t4; + SELECT * FROM t4; + } + } {1 2} + ifcapable {explain} { + do_test insert-5.3 { + # verify that a temporary table is used to copy t4 to t4 + set x [execsql { + EXPLAIN INSERT INTO t4 SELECT x+2 FROM t4; + }] + expr {[lsearch $x OpenEphemeral]>0} + } {1} + } + + do_test insert-5.4 { + # Verify that table "test1" begins on page 3. This should be the same + # page number used by "t4" above. + # + # Update for v3 - the first table now begins on page 2 of each file, not 3. + execsql { + SELECT rootpage FROM sqlite_master WHERE name='test1'; + } + } [expr $AUTOVACUUM?3:2] + do_test insert-5.5 { + # Verify that "t4" begins on page 3. + # + # Update for v3 - the first table now begins on page 2 of each file, not 3. + execsql { + SELECT rootpage FROM sqlite_temp_master WHERE name='t4'; + } + } {2} + do_test insert-5.6 { + # This should not use an intermediate temporary table. + execsql { + INSERT INTO t4 SELECT one FROM test1 WHERE three=7; + SELECT * FROM t4 + } + } {1 2 8} + ifcapable {explain} { + do_test insert-5.7 { + # verify that no temporary table is used to copy test1 to t4 + set x [execsql { + EXPLAIN INSERT INTO t4 SELECT one FROM test1; + }] + expr {[lsearch $x OpenTemp]>0} + } {0} + } +} + +# Ticket #334: REPLACE statement corrupting indices. +# +ifcapable conflict { + # The REPLACE command is not available if SQLITE_OMIT_CONFLICT is + # defined at compilation time. + do_test insert-6.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(2,3); + SELECT b FROM t1 WHERE b=2; + } + } {2} + do_test insert-6.2 { + execsql { + REPLACE INTO t1 VALUES(1,4); + SELECT b FROM t1 WHERE b=2; + } + } {} + do_test insert-6.3 { + execsql { + UPDATE OR REPLACE t1 SET a=2 WHERE b=4; + SELECT * FROM t1 WHERE b=4; + } + } {2 4} + do_test insert-6.4 { + execsql { + SELECT * FROM t1 WHERE b=3; + } + } {} + ifcapable {reindex} { + do_test insert-6.5 { + execsql REINDEX + } {} + } + do_test insert-6.6 { + execsql { + DROP TABLE t1; + } + } {} +} + +# Test that the special optimization for queries of the form +# "SELECT max(x) FROM tbl" where there is an index on tbl(x) works with +# INSERT statments. +do_test insert-7.1 { + execsql { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + CREATE INDEX i1 ON t1(a); + } +} {} +do_test insert-7.2 { + execsql { + INSERT INTO t1 SELECT max(a) FROM t1; + } +} {} +do_test insert-7.3 { + execsql { + SELECT a FROM t1; + } +} {1 2 2} + +# Ticket #1140: Check for an infinite loop in the algorithm that tests +# to see if the right-hand side of an INSERT...SELECT references the left-hand +# side. +# +ifcapable subquery&&compound { + do_test insert-8.1 { + execsql { + INSERT INTO t3 SELECT * FROM (SELECT * FROM t3 UNION ALL SELECT 1,2,3) + } + } {} +} + +# Make sure the rowid cache in the VDBE is reset correctly when +# an explicit rowid is given. +# +do_test insert-9.1 { + execsql { + CREATE TABLE t5(x); + INSERT INTO t5 VALUES(1); + INSERT INTO t5 VALUES(2); + INSERT INTO t5 VALUES(3); + INSERT INTO t5(rowid, x) SELECT nullif(x*2+10,14), x+100 FROM t5; + SELECT rowid, x FROM t5; + } +} {1 1 2 2 3 3 12 101 13 102 16 103} +do_test insert-9.2 { + execsql { + CREATE TABLE t6(x INTEGER PRIMARY KEY, y); + INSERT INTO t6 VALUES(1,1); + INSERT INTO t6 VALUES(2,2); + INSERT INTO t6 VALUES(3,3); + INSERT INTO t6 SELECT nullif(y*2+10,14), y+100 FROM t6; + SELECT x, y FROM t6; + } +} {1 1 2 2 3 3 12 101 13 102 16 103} + +# Multiple VALUES clauses +# +ifcapable compound { + do_test insert-10.1 { + execsql { + CREATE TABLE t10(a,b,c); + INSERT INTO t10 VALUES(1,2,3), (4,5,6), (7,8,9); + SELECT * FROM t10; + } + } {1 2 3 4 5 6 7 8 9} + do_test insert-10.2 { + catchsql { + INSERT INTO t10 VALUES(11,12,13), (14,15); + } + } {1 {all VALUES must have the same number of terms}} +} + +integrity_check insert-99.0 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/insert2.test b/components/external/SQLite-3.8.1/test/insert2.test new file mode 100644 index 0000000000000000000000000000000000000000..6876d538ae5cce42a5da56f4a86f5d92bffc488d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/insert2.test @@ -0,0 +1,278 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the INSERT statement that takes is +# result from a SELECT. +# +# $Id: insert2.test,v 1.19 2008/01/16 18:20:42 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create some tables with data that we can select against +# +do_test insert2-1.0 { + execsql {CREATE TABLE d1(n int, log int);} + for {set i 1} {$i<=20} {incr i} { + for {set j 0} {(1<<$j)<$i} {incr j} {} + execsql "INSERT INTO d1 VALUES($i,$j)" + } + execsql {SELECT * FROM d1 ORDER BY n} +} {1 0 2 1 3 2 4 2 5 3 6 3 7 3 8 3 9 4 10 4 11 4 12 4 13 4 14 4 15 4 16 4 17 5 18 5 19 5 20 5} + +# Insert into a new table from the old one. +# +do_test insert2-1.1.1 { + execsql { + CREATE TABLE t1(log int, cnt int); + PRAGMA count_changes=on; + } + ifcapable explain { + execsql { + EXPLAIN INSERT INTO t1 SELECT log, count(*) FROM d1 GROUP BY log; + } + } + execsql { + INSERT INTO t1 SELECT log, count(*) FROM d1 GROUP BY log; + } +} {6} +do_test insert2-1.1.2 { + db changes +} {6} +do_test insert2-1.1.3 { + execsql {SELECT * FROM t1 ORDER BY log} +} {0 1 1 1 2 2 3 4 4 8 5 4} + +ifcapable compound { +do_test insert2-1.2.1 { + catch {execsql {DROP TABLE t1}} + execsql { + CREATE TABLE t1(log int, cnt int); + INSERT INTO t1 + SELECT log, count(*) FROM d1 GROUP BY log + EXCEPT SELECT n-1,log FROM d1; + } +} {4} +do_test insert2-1.2.2 { + execsql { + SELECT * FROM t1 ORDER BY log; + } +} {0 1 3 4 4 8 5 4} +do_test insert2-1.3.1 { + catch {execsql {DROP TABLE t1}} + execsql { + CREATE TABLE t1(log int, cnt int); + PRAGMA count_changes=off; + INSERT INTO t1 + SELECT log, count(*) FROM d1 GROUP BY log + INTERSECT SELECT n-1,log FROM d1; + } +} {} +do_test insert2-1.3.2 { + execsql { + SELECT * FROM t1 ORDER BY log; + } +} {1 1 2 2} +} ;# ifcapable compound +execsql {PRAGMA count_changes=off;} + +do_test insert2-1.4 { + catch {execsql {DROP TABLE t1}} + set r [execsql { + CREATE TABLE t1(log int, cnt int); + CREATE INDEX i1 ON t1(log); + CREATE INDEX i2 ON t1(cnt); + INSERT INTO t1 SELECT log, count() FROM d1 GROUP BY log; + SELECT * FROM t1 ORDER BY log; + }] + lappend r [execsql {SELECT cnt FROM t1 WHERE log=3}] + lappend r [execsql {SELECT log FROM t1 WHERE cnt=4 ORDER BY log}] +} {0 1 1 1 2 2 3 4 4 8 5 4 4 {3 5}} + +do_test insert2-2.0 { + execsql { + CREATE TABLE t3(a,b,c); + CREATE TABLE t4(x,y); + INSERT INTO t4 VALUES(1,2); + SELECT * FROM t4; + } +} {1 2} +do_test insert2-2.1 { + execsql { + INSERT INTO t3(a,c) SELECT * FROM t4; + SELECT * FROM t3; + } +} {1 {} 2} +do_test insert2-2.2 { + execsql { + DELETE FROM t3; + INSERT INTO t3(c,b) SELECT * FROM t4; + SELECT * FROM t3; + } +} {{} 2 1} +do_test insert2-2.3 { + execsql { + DELETE FROM t3; + INSERT INTO t3(c,a,b) SELECT x, 'hi', y FROM t4; + SELECT * FROM t3; + } +} {hi 2 1} + +integrity_check insert2-3.0 + +# File table t4 with lots of data +# +do_test insert2-3.1 { + execsql { + SELECT * from t4; + } +} {1 2} +do_test insert2-3.2 { + set x [db total_changes] + execsql { + BEGIN; + INSERT INTO t4 VALUES(2,4); + INSERT INTO t4 VALUES(3,6); + INSERT INTO t4 VALUES(4,8); + INSERT INTO t4 VALUES(5,10); + INSERT INTO t4 VALUES(6,12); + INSERT INTO t4 VALUES(7,14); + INSERT INTO t4 VALUES(8,16); + INSERT INTO t4 VALUES(9,18); + INSERT INTO t4 VALUES(10,20); + COMMIT; + } + expr [db total_changes] - $x +} {9} +do_test insert2-3.2.1 { + execsql { + SELECT count(*) FROM t4; + } +} {10} +do_test insert2-3.3 { + ifcapable subquery { + execsql { + BEGIN; + INSERT INTO t4 SELECT x+(SELECT max(x) FROM t4),y FROM t4; + INSERT INTO t4 SELECT x+(SELECT max(x) FROM t4),y FROM t4; + INSERT INTO t4 SELECT x+(SELECT max(x) FROM t4),y FROM t4; + INSERT INTO t4 SELECT x+(SELECT max(x) FROM t4),y FROM t4; + COMMIT; + SELECT count(*) FROM t4; + } + } else { + db function max_x_t4 {execsql {SELECT max(x) FROM t4}} + execsql { + BEGIN; + INSERT INTO t4 SELECT x+max_x_t4() ,y FROM t4; + INSERT INTO t4 SELECT x+max_x_t4() ,y FROM t4; + INSERT INTO t4 SELECT x+max_x_t4() ,y FROM t4; + INSERT INTO t4 SELECT x+max_x_t4() ,y FROM t4; + COMMIT; + SELECT count(*) FROM t4; + } + } +} {160} +do_test insert2-3.4 { + execsql { + BEGIN; + UPDATE t4 SET y='lots of data for the row where x=' || x + || ' and y=' || y || ' - even more data to fill space'; + COMMIT; + SELECT count(*) FROM t4; + } +} {160} +do_test insert2-3.5 { + ifcapable subquery { + execsql { + BEGIN; + INSERT INTO t4 SELECT x+(SELECT max(x)+1 FROM t4),y FROM t4; + SELECT count(*) from t4; + ROLLBACK; + } + } else { + execsql { + BEGIN; + INSERT INTO t4 SELECT x+max_x_t4()+1,y FROM t4; + SELECT count(*) from t4; + ROLLBACK; + } + } +} {320} +do_test insert2-3.6 { + execsql { + SELECT count(*) FROM t4; + } +} {160} +do_test insert2-3.7 { + execsql { + BEGIN; + DELETE FROM t4 WHERE x!=123; + SELECT count(*) FROM t4; + ROLLBACK; + } +} {1} +do_test insert2-3.8 { + db changes +} {159} +integrity_check insert2-3.9 + +# Ticket #901 +# +ifcapable tempdb { + do_test insert2-4.1 { + execsql { + CREATE TABLE Dependencies(depId integer primary key, + class integer, name str, flag str); + CREATE TEMPORARY TABLE DepCheck(troveId INT, depNum INT, + flagCount INT, isProvides BOOL, class INTEGER, name STRING, + flag STRING); + INSERT INTO DepCheck + VALUES(-1, 0, 1, 0, 2, 'libc.so.6', 'GLIBC_2.0'); + INSERT INTO Dependencies + SELECT DISTINCT + NULL, + DepCheck.class, + DepCheck.name, + DepCheck.flag + FROM DepCheck LEFT OUTER JOIN Dependencies ON + DepCheck.class == Dependencies.class AND + DepCheck.name == Dependencies.name AND + DepCheck.flag == Dependencies.flag + WHERE + Dependencies.depId is NULL; + }; + } {} +} + +#-------------------------------------------------------------------- +# Test that the INSERT works when the SELECT statement (a) references +# the table being inserted into and (b) is optimized to use an index +# only. +do_test insert2-5.1 { + execsql { + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES(1, 2); + CREATE INDEX t2i1 ON t2(a); + INSERT INTO t2 SELECT a, 3 FROM t2 WHERE a = 1; + SELECT * FROM t2; + } +} {1 2 1 3} +ifcapable subquery { + do_test insert2-5.2 { + execsql { + INSERT INTO t2 SELECT (SELECT a FROM t2), 4; + SELECT * FROM t2; + } + } {1 2 1 3 1 4} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/insert3.test b/components/external/SQLite-3.8.1/test/insert3.test new file mode 100644 index 0000000000000000000000000000000000000000..6b253e0ab791280a2ebbd25657181b8faba1ddbf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/insert3.test @@ -0,0 +1,205 @@ +# 2005 January 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing corner cases of the INSERT statement. +# +# $Id: insert3.test,v 1.9 2009/04/23 14:58:40 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# All the tests in this file require trigger support +# +ifcapable {trigger} { + +# Create a table and a corresponding insert trigger. Do a self-insert +# into the table. +# +do_test insert3-1.0 { + execsql { + CREATE TABLE t1(a,b); + CREATE TABLE log(x UNIQUE, y); + CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN + UPDATE log SET y=y+1 WHERE x=new.a; + INSERT OR IGNORE INTO log VALUES(new.a, 1); + END; + INSERT INTO t1 VALUES('hello','world'); + INSERT INTO t1 VALUES(5,10); + SELECT * FROM log ORDER BY x; + } +} {5 1 hello 1} +do_test insert3-1.1 { + execsql { + INSERT INTO t1 SELECT a, b+10 FROM t1; + SELECT * FROM log ORDER BY x; + } +} {5 2 hello 2} +do_test insert3-1.2 { + execsql { + CREATE TABLE log2(x PRIMARY KEY,y); + CREATE TRIGGER r2 BEFORE INSERT ON t1 BEGIN + UPDATE log2 SET y=y+1 WHERE x=new.b; + INSERT OR IGNORE INTO log2 VALUES(new.b,1); + END; + INSERT INTO t1 VALUES(453,'hi'); + SELECT * FROM log ORDER BY x; + } +} {5 2 453 1 hello 2} +do_test insert3-1.3 { + execsql { + SELECT * FROM log2 ORDER BY x; + } +} {hi 1} +ifcapable compound { + do_test insert3-1.4.1 { + execsql { + INSERT INTO t1 SELECT * FROM t1; + SELECT 'a:', x, y FROM log UNION ALL + SELECT 'b:', x, y FROM log2 ORDER BY x; + } + } {a: 5 4 b: 10 2 b: 20 1 a: 453 2 a: hello 4 b: hi 2 b: world 1} + do_test insert3-1.4.2 { + execsql { + SELECT 'a:', x, y FROM log UNION ALL + SELECT 'b:', x, y FROM log2 ORDER BY x, y; + } + } {a: 5 4 b: 10 2 b: 20 1 a: 453 2 a: hello 4 b: hi 2 b: world 1} + do_test insert3-1.5 { + execsql { + INSERT INTO t1(a) VALUES('xyz'); + SELECT * FROM log ORDER BY x; + } + } {5 4 453 2 hello 4 xyz 1} +} + +do_test insert3-2.1 { + execsql { + CREATE TABLE t2( + a INTEGER PRIMARY KEY, + b DEFAULT 'b', + c DEFAULT 'c' + ); + CREATE TABLE t2dup(a,b,c); + CREATE TRIGGER t2r1 BEFORE INSERT ON t2 BEGIN + INSERT INTO t2dup(a,b,c) VALUES(new.a,new.b,new.c); + END; + INSERT INTO t2(a) VALUES(123); + INSERT INTO t2(b) VALUES(234); + INSERT INTO t2(c) VALUES(345); + SELECT * FROM t2dup; + } +} {123 b c -1 234 c -1 b 345} +do_test insert3-2.2 { + execsql { + DELETE FROM t2dup; + INSERT INTO t2(a) SELECT 1 FROM t1 LIMIT 1; + INSERT INTO t2(b) SELECT 987 FROM t1 LIMIT 1; + INSERT INTO t2(c) SELECT 876 FROM t1 LIMIT 1; + SELECT * FROM t2dup; + } +} {1 b c -1 987 c -1 b 876} + +# Test for proper detection of malformed WHEN clauses on INSERT triggers. +# +do_test insert3-3.1 { + execsql { + CREATE TABLE t3(a,b,c); + CREATE TRIGGER t3r1 BEFORE INSERT on t3 WHEN nosuchcol BEGIN + SELECT 'illegal WHEN clause'; + END; + } +} {} +do_test insert3-3.2 { + catchsql { + INSERT INTO t3 VALUES(1,2,3) + } +} {1 {no such column: nosuchcol}} +do_test insert3-3.3 { + execsql { + CREATE TABLE t4(a,b,c); + CREATE TRIGGER t4r1 AFTER INSERT on t4 WHEN nosuchcol BEGIN + SELECT 'illegal WHEN clause'; + END; + } +} {} +do_test insert3-3.4 { + catchsql { + INSERT INTO t4 VALUES(1,2,3) + } +} {1 {no such column: nosuchcol}} + +} ;# ifcapable {trigger} + +# Tests for the INSERT INTO ... DEFAULT VALUES construct +# +do_test insert3-3.5 { + execsql { + CREATE TABLE t5( + a INTEGER PRIMARY KEY, + b DEFAULT 'xyz' + ); + INSERT INTO t5 DEFAULT VALUES; + SELECT * FROM t5; + } +} {1 xyz} +do_test insert3-3.6 { + execsql { + INSERT INTO t5 DEFAULT VALUES; + SELECT * FROM t5; + } +} {1 xyz 2 xyz} + +ifcapable bloblit { + do_test insert3-3.7 { + execsql { + CREATE TABLE t6(x,y DEFAULT 4.3, z DEFAULT x'6869'); + INSERT INTO t6 DEFAULT VALUES; + SELECT * FROM t6; + } + } {{} 4.3 hi} +} + +foreach tab [db eval {SELECT name FROM sqlite_master WHERE type = 'table'}] { + db eval "DROP TABLE $tab" +} +db close +sqlite3 db test.db + +#------------------------------------------------------------------------- +# While developing tests for a different feature (savepoint) the following +# sequence was found to cause an assert() in btree.c to fail. These +# tests are included to ensure that that bug is fixed. +# +do_test insert3-4.1 { + execsql { + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(a, b); + BEGIN; + INSERT INTO t1 VALUES(randstr(10,400),randstr(10,400),randstr(10,400)); + } + set r "randstr(10,400)" + for {set ii 0} {$ii < 10} {incr ii} { + execsql "INSERT INTO t1 SELECT $r, $r, $r FROM t1" + } + execsql { COMMIT } +} {} +do_test insert3-4.2 { + execsql { + PRAGMA cache_size = 10; + BEGIN; + UPDATE t1 SET a = randstr(10,10) WHERE (rowid%4)==0; + DELETE FROM t1 WHERE rowid%2; + INSERT INTO t1 SELECT randstr(10,400), randstr(10,400), c FROM t1; + COMMIT; + } +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/insert4.test b/components/external/SQLite-3.8.1/test/insert4.test new file mode 100644 index 0000000000000000000000000000000000000000..f4a45c182cc5a90f446218890857ef53e1e6303d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/insert4.test @@ -0,0 +1,564 @@ +# 2007 January 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the INSERT transfer optimization. +# +# $Id: insert4.test,v 1.10 2008/01/21 16:22:46 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !view||!subquery { + finish_test + return +} + +# The sqlite3_xferopt_count variable is incremented whenever the +# insert transfer optimization applies. +# +# This procedure runs a test to see if the sqlite3_xferopt_count is +# set to N. +# +proc xferopt_test {testname N} { + do_test $testname {set ::sqlite3_xferopt_count} $N +} + +# Create tables used for testing. +# +execsql { + PRAGMA legacy_file_format = 0; + CREATE TABLE t1(a int, b int, check(b>a)); + CREATE TABLE t2(x int, y int); + CREATE VIEW v2 AS SELECT y, x FROM t2; + CREATE TABLE t3(a int, b int); +} + +# Ticket #2252. Make sure the an INSERT from identical tables +# does not violate constraints. +# +do_test insert4-1.1 { + set sqlite3_xferopt_count 0 + execsql { + DELETE FROM t1; + DELETE FROM t2; + INSERT INTO t2 VALUES(9,1); + } + catchsql { + INSERT INTO t1 SELECT * FROM t2; + } +} {1 {constraint failed}} +xferopt_test insert4-1.2 0 +do_test insert4-1.3 { + execsql { + SELECT * FROM t1; + } +} {} + +# Tests to make sure that the transfer optimization is not occurring +# when it is not a valid optimization. +# +# The SELECT must be against a real table. +do_test insert4-2.1.1 { + execsql { + DELETE FROM t1; + INSERT INTO t1 SELECT 4, 8; + SELECT * FROM t1; + } +} {4 8} +xferopt_test insert4-2.1.2 0 +do_test insert4-2.2.1 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 SELECT * FROM v2; + SELECT * FROM t1; + } +} {0 {1 9}} +xferopt_test insert4-2.2.2 0 + +# Do not run the transfer optimization if there is a LIMIT clause +# +do_test insert4-2.3.1 { + execsql { + DELETE FROM t2; + INSERT INTO t2 VALUES(9,1); + INSERT INTO t2 SELECT y, x FROM t2; + INSERT INTO t3 SELECT * FROM t2 LIMIT 1; + SELECT * FROM t3; + } +} {9 1} +xferopt_test insert4-2.3.2 0 +do_test insert4-2.3.3 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 SELECT * FROM t2 LIMIT 1; + SELECT * FROM t1; + } +} {1 {constraint failed}} +xferopt_test insert4-2.3.4 0 + +# Do not run the transfer optimization if there is a DISTINCT +# +do_test insert4-2.4.1 { + execsql { + DELETE FROM t3; + INSERT INTO t3 SELECT DISTINCT * FROM t2; + SELECT * FROM t3; + } +} {9 1 1 9} +xferopt_test insert4-2.4.2 0 +do_test insert4-2.4.3 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 SELECT DISTINCT * FROM t2; + } +} {1 {constraint failed}} +xferopt_test insert4-2.4.4 0 + +# The following procedure constructs two tables then tries to transfer +# data from one table to the other. Checks are made to make sure the +# transfer is successful and that the transfer optimization was used or +# not, as appropriate. +# +# xfer_check TESTID XFER-USED INIT-DATA DEST-SCHEMA SRC-SCHEMA +# +# The TESTID argument is the symbolic name for this test. The XFER-USED +# argument is true if the transfer optimization should be employed and +# false if not. INIT-DATA is a single row of data that is to be +# transfered. DEST-SCHEMA and SRC-SCHEMA are table declarations for +# the destination and source tables. +# +proc xfer_check {testid xferused initdata destschema srcschema} { + execsql "CREATE TABLE dest($destschema)" + execsql "CREATE TABLE src($srcschema)" + execsql "INSERT INTO src VALUES([join $initdata ,])" + set ::sqlite3_xferopt_count 0 + do_test $testid.1 { + execsql { + INSERT INTO dest SELECT * FROM src; + SELECT * FROM dest; + } + } $initdata + do_test $testid.2 { + set ::sqlite3_xferopt_count + } $xferused + execsql { + DROP TABLE dest; + DROP TABLE src; + } +} + + +# Do run the transfer optimization if tables have identical +# CHECK constraints. +# +xfer_check insert4-3.1 1 {1 9} \ + {a int, b int CHECK(b>a)} \ + {x int, y int CHECK(y>x)} +xfer_check insert4-3.2 1 {1 9} \ + {a int, b int CHECK(b>a)} \ + {x int CHECK(y>x), y int} + +# Do run the transfer optimization if the destination table lacks +# any CHECK constraints regardless of whether or not there are CHECK +# constraints on the source table. +# +xfer_check insert4-3.3 1 {1 9} \ + {a int, b int} \ + {x int, y int CHECK(y>x)} + +# Do run the transfer optimization if the destination table omits +# NOT NULL constraints that the source table has. +# +xfer_check insert4-3.4 0 {1 9} \ + {a int, b int CHECK(b>a)} \ + {x int, y int} + +# Do not run the optimization if the destination has NOT NULL +# constraints that the source table lacks. +# +xfer_check insert4-3.5 0 {1 9} \ + {a int, b int NOT NULL} \ + {x int, y int} +xfer_check insert4-3.6 0 {1 9} \ + {a int, b int NOT NULL} \ + {x int NOT NULL, y int} +xfer_check insert4-3.7 0 {1 9} \ + {a int NOT NULL, b int NOT NULL} \ + {x int NOT NULL, y int} +xfer_check insert4-3.8 0 {1 9} \ + {a int NOT NULL, b int} \ + {x int, y int} + + +# Do run the transfer optimization if the destination table and +# source table have the same NOT NULL constraints or if the +# source table has extra NOT NULL constraints. +# +xfer_check insert4-3.9 1 {1 9} \ + {a int, b int} \ + {x int NOT NULL, y int} +xfer_check insert4-3.10 1 {1 9} \ + {a int, b int} \ + {x int NOT NULL, y int NOT NULL} +xfer_check insert4-3.11 1 {1 9} \ + {a int NOT NULL, b int} \ + {x int NOT NULL, y int NOT NULL} +xfer_check insert4-3.12 1 {1 9} \ + {a int, b int NOT NULL} \ + {x int NOT NULL, y int NOT NULL} + +# Do not run the optimization if any corresponding table +# columns have different affinities. +# +xfer_check insert4-3.20 0 {1 9} \ + {a text, b int} \ + {x int, b int} +xfer_check insert4-3.21 0 {1 9} \ + {a int, b int} \ + {x text, b int} + +# "int" and "integer" are equivalent so the optimization should +# run here. +# +xfer_check insert4-3.22 1 {1 9} \ + {a int, b int} \ + {x integer, b int} + +# Ticket #2291. +# + +do_test insert4-4.1a { + execsql {CREATE TABLE t4(a, b, UNIQUE(a,b))} +} {} +ifcapable vacuum { + do_test insert4-4.1b { + execsql { + INSERT INTO t4 VALUES(NULL,0); + INSERT INTO t4 VALUES(NULL,1); + INSERT INTO t4 VALUES(NULL,1); + VACUUM; + } + } {} +} + +# Check some error conditions: +# +do_test insert4-5.1 { + # Table does not exist. + catchsql { INSERT INTO t2 SELECT * FROM nosuchtable } +} {1 {no such table: nosuchtable}} +do_test insert4-5.2 { + # Number of columns does not match. + catchsql { + CREATE TABLE t5(a, b, c); + INSERT INTO t4 SELECT * FROM t5; + } +} {1 {table t4 has 2 columns but 3 values were supplied}} + +do_test insert4-6.1 { + set ::sqlite3_xferopt_count 0 + execsql { + CREATE INDEX t2_i2 ON t2(x, y COLLATE nocase); + CREATE INDEX t2_i1 ON t2(x ASC, y DESC); + CREATE INDEX t3_i1 ON t3(a, b); + INSERT INTO t2 SELECT * FROM t3; + } + set ::sqlite3_xferopt_count +} {0} +do_test insert4-6.2 { + set ::sqlite3_xferopt_count 0 + execsql { + DROP INDEX t2_i2; + INSERT INTO t2 SELECT * FROM t3; + } + set ::sqlite3_xferopt_count +} {0} +do_test insert4-6.3 { + set ::sqlite3_xferopt_count 0 + execsql { + DROP INDEX t2_i1; + CREATE INDEX t2_i1 ON t2(x ASC, y ASC); + INSERT INTO t2 SELECT * FROM t3; + } + set ::sqlite3_xferopt_count +} {1} +do_test insert4-6.4 { + set ::sqlite3_xferopt_count 0 + execsql { + DROP INDEX t2_i1; + CREATE INDEX t2_i1 ON t2(x ASC, y COLLATE RTRIM); + INSERT INTO t2 SELECT * FROM t3; + } + set ::sqlite3_xferopt_count +} {0} + + +do_test insert4-6.5 { + execsql { + CREATE TABLE t6a(x CHECK( x<>'abc' )); + INSERT INTO t6a VALUES('ABC'); + SELECT * FROM t6a; + } +} {ABC} +do_test insert4-6.6 { + execsql { + CREATE TABLE t6b(x CHECK( x<>'abc' COLLATE nocase )); + } + catchsql { + INSERT INTO t6b SELECT * FROM t6a; + } +} {1 {constraint failed}} +do_test insert4-6.7 { + execsql { + DROP TABLE t6b; + CREATE TABLE t6b(x CHECK( x COLLATE nocase <>'abc' )); + } + catchsql { + INSERT INTO t6b SELECT * FROM t6a; + } +} {1 {constraint failed}} + +# Ticket [6284df89debdfa61db8073e062908af0c9b6118e] +# Disable the xfer optimization if the destination table contains +# a foreign key constraint +# +ifcapable foreignkey { + do_test insert4-7.1 { + set ::sqlite3_xferopt_count 0 + execsql { + CREATE TABLE t7a(x INTEGER PRIMARY KEY); INSERT INTO t7a VALUES(123); + CREATE TABLE t7b(y INTEGER REFERENCES t7a); + CREATE TABLE t7c(z INT); INSERT INTO t7c VALUES(234); + INSERT INTO t7b SELECT * FROM t7c; + SELECT * FROM t7b; + } + } {234} + do_test insert4-7.2 { + set ::sqlite3_xferopt_count + } {1} + do_test insert4-7.3 { + set ::sqlite3_xferopt_count 0 + execsql { + DELETE FROM t7b; + PRAGMA foreign_keys=ON; + } + catchsql { + INSERT INTO t7b SELECT * FROM t7c; + } + } {1 {foreign key constraint failed}} + do_test insert4-7.4 { + execsql {SELECT * FROM t7b} + } {} + do_test insert4-7.5 { + set ::sqlite3_xferopt_count + } {0} + do_test insert4-7.6 { + set ::sqlite3_xferopt_count 0 + execsql { + DELETE FROM t7b; DELETE FROM t7c; + INSERT INTO t7c VALUES(123); + INSERT INTO t7b SELECT * FROM t7c; + SELECT * FROM t7b; + } + } {123} + do_test insert4-7.7 { + set ::sqlite3_xferopt_count + } {0} + do_test insert4-7.7 { + set ::sqlite3_xferopt_count 0 + execsql { + PRAGMA foreign_keys=OFF; + DELETE FROM t7b; + INSERT INTO t7b SELECT * FROM t7c; + SELECT * FROM t7b; + } + } {123} + do_test insert4-7.8 { + set ::sqlite3_xferopt_count + } {1} +} + +# Ticket [676bc02b87176125635cb174d110b431581912bb] +# Make sure INTEGER PRIMARY KEY ON CONFLICT ... works with the xfer +# optimization. +# +do_test insert4-8.1 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT REPLACE, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT REPLACE, y); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(1,3); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {1 3} +do_test insert4-8.2 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT REPLACE, b); + CREATE TABLE t2(x, y); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(1,3); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {1 3} +do_test insert4-8.3 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT IGNORE, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT IGNORE, y); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(1,3); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {1 2} +do_test insert4-8.4 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT IGNORE, b); + CREATE TABLE t2(x, y); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(1,3); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {1 2} +do_test insert4-8.5 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT FAIL, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT FAIL, y); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(-99,100); + INSERT INTO t2 VALUES(1,3); + SELECT * FROM t1; + } + catchsql { + INSERT INTO t1 SELECT * FROM t2; + } +} {1 {PRIMARY KEY must be unique}} +do_test insert4-8.6 { + execsql { + SELECT * FROM t1; + } +} {-99 100 1 2} +do_test insert4-8.7 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT ABORT, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT ABORT, y); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(-99,100); + INSERT INTO t2 VALUES(1,3); + SELECT * FROM t1; + } + catchsql { + INSERT INTO t1 SELECT * FROM t2; + } +} {1 {PRIMARY KEY must be unique}} +do_test insert4-8.8 { + execsql { + SELECT * FROM t1; + } +} {1 2} +do_test insert4-8.9 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT ROLLBACK, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT ROLLBACK, y); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(-99,100); + INSERT INTO t2 VALUES(1,3); + SELECT * FROM t1; + } + catchsql { + BEGIN; + INSERT INTO t1 VALUES(2,3); + INSERT INTO t1 SELECT * FROM t2; + } +} {1 {PRIMARY KEY must be unique}} +do_test insert4-8.10 { + catchsql {COMMIT} +} {1 {cannot commit - no transaction is active}} +do_test insert4-8.11 { + execsql { + SELECT * FROM t1; + } +} {1 2} + +do_test insert4-8.21 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT REPLACE, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT REPLACE, y); + INSERT INTO t2 VALUES(1,3); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {1 3} +do_test insert4-8.22 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT IGNORE, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT IGNORE, y); + INSERT INTO t2 VALUES(1,3); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {1 3} +do_test insert4-8.23 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT ABORT, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT ABORT, y); + INSERT INTO t2 VALUES(1,3); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {1 3} +do_test insert4-8.24 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT FAIL, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT FAIL, y); + INSERT INTO t2 VALUES(1,3); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {1 3} +do_test insert4-8.25 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a INTEGER PRIMARY KEY ON CONFLICT ROLLBACK, b); + CREATE TABLE t2(x INTEGER PRIMARY KEY ON CONFLICT ROLLBACK, y); + INSERT INTO t2 VALUES(1,3); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {1 3} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/insert5.test b/components/external/SQLite-3.8.1/test/insert5.test new file mode 100644 index 0000000000000000000000000000000000000000..1e58902e078845642aae222fbeaa4f02c080613d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/insert5.test @@ -0,0 +1,117 @@ +# 2007 November 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The tests in this file ensure that a temporary table is used +# when required by an "INSERT INTO ... SELECT ..." statement. +# +# $Id: insert5.test,v 1.5 2008/08/04 03:51:24 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !subquery { + finish_test + return +} + +# Return true if the compilation of the sql passed as an argument +# includes the opcode OpenEphemeral. An "INSERT INTO ... SELECT" +# statement includes such an opcode if a temp-table is used +# to store intermediate results. +# +proc uses_temp_table {sql} { + return [expr {[lsearch [execsql "EXPLAIN $sql"] OpenEphemeral]>=0}] +} + +# Construct the sample database. +# +do_test insert5-1.0 { + forcedelete test2.db test2.db-journal + execsql { + CREATE TABLE MAIN(Id INTEGER, Id1 INTEGER); + CREATE TABLE B(Id INTEGER, Id1 INTEGER); + CREATE VIEW v1 AS SELECT * FROM B; + CREATE VIEW v2 AS SELECT * FROM MAIN; + INSERT INTO MAIN(Id,Id1) VALUES(2,3); + INSERT INTO B(Id,Id1) VALUES(2,3); + } +} {} + +# Run the query. +# +ifcapable compound { + do_test insert5-1.1 { + execsql { + INSERT INTO B + SELECT * FROM B UNION ALL + SELECT * FROM MAIN WHERE exists (select * FROM B WHERE B.Id = MAIN.Id); + SELECT * FROM B; + } + } {2 3 2 3 2 3} +} else { + do_test insert5-1.1 { + execsql { + INSERT INTO B SELECT * FROM B; + INSERT INTO B + SELECT * FROM MAIN WHERE exists (select * FROM B WHERE B.Id = MAIN.Id); + SELECT * FROM B; + } + } {2 3 2 3 2 3} +} +do_test insert5-2.1 { + uses_temp_table { INSERT INTO b SELECT * FROM main } +} {0} +do_test insert5-2.2 { + uses_temp_table { INSERT INTO b SELECT * FROM b } +} {1} +do_test insert5-2.3 { + uses_temp_table { INSERT INTO b SELECT (SELECT id FROM b), id1 FROM main } +} {1} +do_test insert5-2.4 { + uses_temp_table { INSERT INTO b SELECT id1, (SELECT id FROM b) FROM main } +} {1} +do_test insert5-2.5 { + uses_temp_table { + INSERT INTO b + SELECT * FROM main WHERE id = (SELECT id1 FROM b WHERE main.id = b.id) } +} {1} +do_test insert5-2.6 { + uses_temp_table { INSERT INTO b SELECT * FROM v1 } +} {1} +do_test insert5-2.7 { + uses_temp_table { INSERT INTO b SELECT * FROM v2 } +} {0} +do_test insert5-2.8 { + uses_temp_table { + INSERT INTO b + SELECT * FROM main WHERE id > 10 AND max(id1, (SELECT id FROM b)) > 10; + } +} {1} + +# UPDATE: Using a column from the outer query (main.id) in the GROUP BY +# or ORDER BY of a sub-query is no longer supported. +# +# do_test insert5-2.9 { +# uses_temp_table { +# INSERT INTO b +# SELECT * FROM main +# WHERE id > 10 AND (SELECT count(*) FROM v2 GROUP BY main.id) +# } +# } {} +do_test insert5-2.9 { + catchsql { + INSERT INTO b + SELECT * FROM main + WHERE id > 10 AND (SELECT count(*) FROM v2 GROUP BY main.id) + } +} {1 {no such column: main.id}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/instr.test b/components/external/SQLite-3.8.1/test/instr.test new file mode 100644 index 0000000000000000000000000000000000000000..c8be4862b930641b2c73411467b57d97e91a4370 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/instr.test @@ -0,0 +1,251 @@ +# 2012 October 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the built-in INSTR() functions. +# +# EVIDENCE-OF: R-27549-59611 The instr(X,Y) function finds the first +# occurrence of string Y within string X and returns the number of prior +# characters plus 1, or 0 if Y is nowhere found within X. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table to work with. +# +do_test instr-1.1 { + db eval {SELECT instr('abcdefg','a');} +} {1} +do_test instr-1.2 { + db eval {SELECT instr('abcdefg','b');} +} {2} +do_test instr-1.3 { + db eval {SELECT instr('abcdefg','c');} +} {3} +do_test instr-1.4 { + db eval {SELECT instr('abcdefg','d');} +} {4} +do_test instr-1.5 { + db eval {SELECT instr('abcdefg','e');} +} {5} +do_test instr-1.6 { + db eval {SELECT instr('abcdefg','f');} +} {6} +do_test instr-1.7 { + db eval {SELECT instr('abcdefg','g');} +} {7} +do_test instr-1.8 { + db eval {SELECT instr('abcdefg','h');} +} {0} +do_test instr-1.9 { + db eval {SELECT instr('abcdefg','abcdefg');} +} {1} +do_test instr-1.10 { + db eval {SELECT instr('abcdefg','abcdefgh');} +} {0} +do_test instr-1.11 { + db eval {SELECT instr('abcdefg','bcdefg');} +} {2} +do_test instr-1.12 { + db eval {SELECT instr('abcdefg','bcdefgh');} +} {0} +do_test instr-1.13 { + db eval {SELECT instr('abcdefg','cdefg');} +} {3} +do_test instr-1.14 { + db eval {SELECT instr('abcdefg','cdefgh');} +} {0} +do_test instr-1.15 { + db eval {SELECT instr('abcdefg','defg');} +} {4} +do_test instr-1.16 { + db eval {SELECT instr('abcdefg','defgh');} +} {0} +do_test instr-1.17 { + db eval {SELECT instr('abcdefg','efg');} +} {5} +do_test instr-1.18 { + db eval {SELECT instr('abcdefg','efgh');} +} {0} +do_test instr-1.19 { + db eval {SELECT instr('abcdefg','fg');} +} {6} +do_test instr-1.20 { + db eval {SELECT instr('abcdefg','fgh');} +} {0} +do_test instr-1.21 { + db eval {SELECT coalesce(instr('abcdefg',NULL),'nil');} +} {nil} +do_test instr-1.22 { + db eval {SELECT coalesce(instr(NULL,'x'),'nil');} +} {nil} +do_test instr-1.23 { + db eval {SELECT instr(12345,34);} +} {3} +do_test instr-1.24 { + db eval {SELECT instr(123456.78,34);} +} {3} +do_test instr-1.25 { + db eval {SELECT instr(123456.78,x'3334');} +} {3} +do_test instr-1.26 { + db eval {SELECT instr('äbcdefg','efg');} +} {5} +do_test instr-1.27 { + db eval {SELECT instr('€xyzzy','xyz');} +} {2} +do_test instr-1.28 { + db eval {SELECT instr('abc€xyzzy','xyz');} +} {5} +do_test instr-1.29 { + db eval {SELECT instr('abc€xyzzy','€xyz');} +} {4} +do_test instr-1.30 { + db eval {SELECT instr('abc€xyzzy','c€xyz');} +} {3} +do_test instr-1.31 { + db eval {SELECT instr(x'0102030405',x'01');} +} {1} +do_test instr-1.32 { + db eval {SELECT instr(x'0102030405',x'02');} +} {2} +do_test instr-1.33 { + db eval {SELECT instr(x'0102030405',x'03');} +} {3} +do_test instr-1.34 { + db eval {SELECT instr(x'0102030405',x'04');} +} {4} +do_test instr-1.35 { + db eval {SELECT instr(x'0102030405',x'05');} +} {5} +do_test instr-1.36 { + db eval {SELECT instr(x'0102030405',x'06');} +} {0} +do_test instr-1.37 { + db eval {SELECT instr(x'0102030405',x'0102030405');} +} {1} +do_test instr-1.38 { + db eval {SELECT instr(x'0102030405',x'02030405');} +} {2} +do_test instr-1.39 { + db eval {SELECT instr(x'0102030405',x'030405');} +} {3} +do_test instr-1.40 { + db eval {SELECT instr(x'0102030405',x'0405');} +} {4} +do_test instr-1.41 { + db eval {SELECT instr(x'0102030405',x'0506');} +} {0} +do_test instr-1.42 { + db eval {SELECT instr(x'0102030405',x'');} +} {1} +do_test instr-1.43 { + db eval {SELECT instr(x'',x'');} +} {1} +do_test instr-1.44 { + db eval {SELECT instr('','');} +} {1} +do_test instr-1.45 { + db eval {SELECT instr('abcdefg','');} +} {1} +unset -nocomplain longstr +set longstr abcdefghijklmonpqrstuvwxyz +append longstr $longstr +append longstr $longstr +append longstr $longstr +append longstr $longstr +append longstr $longstr +append longstr $longstr +append longstr $longstr +append longstr $longstr +append longstr $longstr +append longstr $longstr +append longstr $longstr +append longstr $longstr +# puts [string length $longstr] +append longstr Xabcde +do_test instr-1.46 { + db eval {SELECT instr($longstr,'X');} +} {106497} +do_test instr-1.47 { + db eval {SELECT instr($longstr,'Y');} +} {0} +do_test instr-1.48 { + db eval {SELECT instr($longstr,'Xa');} +} {106497} +do_test instr-1.49 { + db eval {SELECT instr($longstr,'zXa');} +} {106496} +set longstr [string map {a ä} $longstr] +do_test instr-1.50 { + db eval {SELECT instr($longstr,'X');} +} {106497} +do_test instr-1.51 { + db eval {SELECT instr($longstr,'Y');} +} {0} +do_test instr-1.52 { + db eval {SELECT instr($longstr,'Xä');} +} {106497} +do_test instr-1.53 { + db eval {SELECT instr($longstr,'zXä');} +} {106496} +do_test instr-1.54 { + db eval {SELECT instr(x'78c3a4e282ac79','x');} +} {1} +do_test instr-1.55 { + db eval {SELECT instr(x'78c3a4e282ac79','y');} +} {4} + +# EVIDENCE-OF: R-46421-32541 Or, if X and Y are both BLOBs, then +# instr(X,Y) returns one more than the number bytes prior to the first +# occurrence of Y, or 0 if Y does not occur anywhere within X. +# +do_test instr-1.56.1 { + db eval {SELECT instr(x'78c3a4e282ac79',x'79');} +} {7} +do_test instr-1.56.2 { + db eval {SELECT instr(x'78c3a4e282ac79',x'7a');} +} {0} +do_test instr-1.56.3 { + db eval {SELECT instr(x'78c3a4e282ac79',x'78');} +} {1} +do_test instr-1.56.3 { + db eval {SELECT instr(x'78c3a4e282ac79',x'a4');} +} {3} + +# EVIDENCE-OF: R-17329-35644 If both arguments X and Y to instr(X,Y) are +# non-NULL and are not BLOBs then both are interpreted as strings. +# +do_test instr-1.57.1 { + db eval {SELECT instr('xä€y',x'79');} +} {4} +do_test instr-1.57.2 { + db eval {SELECT instr('xä€y',x'a4');} +} {0} +do_test instr-1.57.3 { + db eval {SELECT instr(x'78c3a4e282ac79','y');} +} {4} + +# EVIDENCE-OF: R-14708-27487 If either X or Y are NULL in instr(X,Y) +# then the result is NULL. +# +do_execsql_test instr-1.60 { + SELECT coalesce(instr(NULL,'abc'), 999); +} {999} +do_execsql_test instr-1.61 { + SELECT coalesce(instr('abc',NULL), 999); +} {999} +do_execsql_test instr-1.62 { + SELECT coalesce(instr(NULL,NULL), 999); +} {999} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/intarray.test b/components/external/SQLite-3.8.1/test/intarray.test new file mode 100644 index 0000000000000000000000000000000000000000..2aba080bd4136cba72f8af56dee26e1c5127ae5e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/intarray.test @@ -0,0 +1,109 @@ +# 2009 November 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the "intarray" object implemented +# in test_intarray.c. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + return +} + +do_test intarray-1.0 { + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + } + for {set i 1} {$i<=999} {incr i} { + set b [format {x%03d} $i] + db eval {INSERT INTO t1(a,b) VALUES($i,$b)} + } + db eval { + CREATE TABLE t2(x INTEGER PRIMARY KEY, y); + INSERT INTO t2 SELECT * FROM t1; + SELECT b FROM t1 WHERE a IN (12,34,56,78) ORDER BY a + } +} {x012 x034 x056 x078} + +do_test intarray-1.1 { + set ia1 [sqlite3_intarray_create db ia1] + set ia2 [sqlite3_intarray_create db ia2] + set ia3 [sqlite3_intarray_create db ia3] + set ia4 [sqlite3_intarray_create db ia4] + db eval { + SELECT type, name FROM sqlite_temp_master + ORDER BY name + } +} {table ia1 table ia2 table ia3 table ia4} + +do_test intarray-1.2 { + db eval { + SELECT b FROM t1 WHERE a IN ia3 ORDER BY a + } +} {} + +do_test intarray-1.3 { + sqlite3_intarray_bind $ia3 45 123 678 + db eval { + SELECT b FROM t1 WHERE a IN ia3 ORDER BY a + } +} {x045 x123 x678} + +do_test intarray-1.4 { + db eval { + SELECT count(b) FROM t1 WHERE a NOT IN ia3 ORDER BY a + } +} {996} + +#explain {SELECT b FROM t1 WHERE a NOT IN ia3} + +do_test intarray-1.5 { + set cmd sqlite3_intarray_bind + lappend cmd $ia1 + for {set i 1} {$i<=999} {incr i} { + lappend cmd $i + lappend cmd [expr {$i+1000}] + lappend cmd [expr {$i+2000}] + } + eval $cmd + db eval { + REPLACE INTO t1 SELECT * FROM t2; + DELETE FROM t1 WHERE a NOT IN ia1; + SELECT count(*) FROM t1; + } +} {999} + +do_test intarray-1.6 { + db eval { + DELETE FROM t1 WHERE a IN ia1; + SELECT count(*) FROM t1; + } +} {0} + +do_test intarray-2.1 { + db eval { + CREATE TEMP TABLE t3(p,q); + INSERT INTO t3 SELECT * FROM t2; + SELECT count(*) FROM t3 WHERE p IN ia1; + } +} {999} + +do_test intarray-2.2 { + set ia5 [sqlite3_intarray_create db ia5] + db eval { + SELECT count(*) FROM t3 WHERE p IN ia1; + } +} {999} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/interrupt.test b/components/external/SQLite-3.8.1/test/interrupt.test new file mode 100644 index 0000000000000000000000000000000000000000..92ab4c32657bacabf5c9147c51d24be2886aab7e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/interrupt.test @@ -0,0 +1,185 @@ +# 2004 Feb 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is the sqlite_interrupt() API. +# +# $Id: interrupt.test,v 1.16 2008/01/16 17:46:38 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set DB [sqlite3_connection_pointer db] + +# This routine attempts to execute the sql in $sql. It triggers an +# interrupt at progressively later and later points during the processing +# and checks to make sure SQLITE_INTERRUPT is returned. Eventually, +# the routine completes successfully. +# +proc interrupt_test {testid sql result {initcnt 0}} { + set orig_sum [cksum] + set i $initcnt + while 1 { + incr i + set ::sqlite_interrupt_count $i + do_test $testid.$i.1 [format { + set ::r [catchsql %s] + set ::code [db errorcode] + expr {$::code==0 || $::code==9} + } [list $sql]] 1 + if {$::code==9} { + do_test $testid.$i.2 { + cksum + } $orig_sum + } else { + do_test $testid.$i.99 { + set ::r + } [list 0 $result] + break + } + } + set ::sqlite_interrupt_count 0 +} + +do_test interrupt-1.1 { + execsql { + CREATE TABLE t1(a,b); + SELECT name FROM sqlite_master; + } +} {t1} +interrupt_test interrupt-1.2 {DROP TABLE t1} {} +do_test interrupt-1.3 { + execsql { + SELECT name FROM sqlite_master; + } +} {} +integrity_check interrupt-1.4 + +do_test interrrupt-2.1 { + execsql { + BEGIN; + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,randstr(300,400)); + INSERT INTO t1 SELECT a+1, randstr(300,400) FROM t1; + INSERT INTO t1 SELECT a+2, a || '-' || b FROM t1; + INSERT INTO t1 SELECT a+4, a || '-' || b FROM t1; + INSERT INTO t1 SELECT a+8, a || '-' || b FROM t1; + INSERT INTO t1 SELECT a+16, a || '-' || b FROM t1; + INSERT INTO t1 SELECT a+32, a || '-' || b FROM t1; + COMMIT; + UPDATE t1 SET b=substr(b,-5,5); + SELECT count(*) from t1; + } +} 64 +set origsize [file size test.db] +set cksum [db eval {SELECT md5sum(a || b) FROM t1}] +ifcapable {vacuum} { + interrupt_test interrupt-2.2 {VACUUM} {} 100 +} +do_test interrupt-2.3 { + execsql { + SELECT md5sum(a || b) FROM t1; + } +} $cksum +ifcapable {vacuum && !default_autovacuum} { + do_test interrupt-2.4 { + expr {$::origsize>[file size test.db]} + } 1 +} +ifcapable {explain} { + do_test interrupt-2.5 { + set sql {EXPLAIN SELECT max(a,b), a, b FROM t1} + execsql $sql + set rc [catch {db eval $sql {sqlite3_interrupt $DB}} msg] + lappend rc $msg + } {1 interrupted} +} +integrity_check interrupt-2.6 + +# Ticket #594. If an interrupt occurs in the middle of a transaction +# and that transaction is later rolled back, the internal schema tables do +# not reset. +# +# UPDATE: Interrupting a DML statement in the middle of a transaction now +# causes the transaction to roll back. Leaving the transaction open after +# an SQL statement was interrupted halfway through risks database corruption. +# +ifcapable tempdb { + for {set i 1} {$i<50} {incr i 5} { + do_test interrupt-3.$i.1 { + execsql { + BEGIN; + CREATE TEMP TABLE t2(x,y); + SELECT name FROM sqlite_temp_master; + } + } {t2} + do_test interrupt-3.$i.2 { + set ::sqlite_interrupt_count $::i + catchsql { + INSERT INTO t2 SELECT * FROM t1; + } + } {1 interrupted} + do_test interrupt-3.$i.3 { + execsql { + SELECT name FROM sqlite_temp_master; + } + } {} + do_test interrupt-3.$i.4 { + catchsql { + ROLLBACK + } + } {1 {cannot rollback - no transaction is active}} + do_test interrupt-3.$i.5 { + catchsql {SELECT name FROM sqlite_temp_master}; + execsql { + SELECT name FROM sqlite_temp_master; + } + } {} + } +} + +# There are reports of a memory leak if an interrupt occurs during +# the beginning of a complex query - before the first callback. We +# will try to reproduce it here: +# +execsql { + CREATE TABLE t2(a,b,c); + INSERT INTO t2 SELECT round(a/10), randstr(50,80), randstr(50,60) FROM t1; +} +set sql { + SELECT max(min(b,c)), min(max(b,c)), a FROM t2 GROUP BY a ORDER BY a; +} +set sqlite_interrupt_count 1000000 +execsql $sql +set max_count [expr {1000000-$sqlite_interrupt_count}] +for {set i 1} {$i<$max_count-5} {incr i 1} { + do_test interrupt-4.$i.1 { + set ::sqlite_interrupt_count $::i + catchsql $sql + } {1 interrupted} +} + +if {0} { # This doesn't work anymore since the collation factor is + # no longer called during schema parsing. +# Interrupt during parsing +# +do_test interrupt-5.1 { + proc fake_interrupt {args} { + db collate fake_collation no-op + sqlite3_interrupt db + return SQLITE_OK + } + db collation_needed fake_interrupt + catchsql { + CREATE INDEX fake ON fake1(a COLLATE fake_collation, b, c DESC); + } +} {1 interrupt} +} +finish_test diff --git a/components/external/SQLite-3.8.1/test/intpkey.test b/components/external/SQLite-3.8.1/test/intpkey.test new file mode 100644 index 0000000000000000000000000000000000000000..7ed25e4a13ccd19d87644750e0c59d8d243a2742 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/intpkey.test @@ -0,0 +1,608 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the special processing associated +# with INTEGER PRIMARY KEY columns. +# +# $Id: intpkey.test,v 1.24 2007/11/29 17:43:28 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table with a primary key and a datatype other than +# integer +# +do_test intpkey-1.0 { + execsql { + CREATE TABLE t1(a TEXT PRIMARY KEY, b, c); + } +} {} + +# There should be an index associated with the primary key +# +do_test intpkey-1.1 { + execsql { + SELECT name FROM sqlite_master + WHERE type='index' AND tbl_name='t1'; + } +} {sqlite_autoindex_t1_1} + +# Now create a table with an integer primary key and verify that +# there is no associated index. +# +do_test intpkey-1.2 { + execsql { + DROP TABLE t1; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c); + SELECT name FROM sqlite_master + WHERE type='index' AND tbl_name='t1'; + } +} {} + +# Insert some records into the new table. Specify the primary key +# and verify that the key is used as the record number. +# +do_test intpkey-1.3 { + execsql { + INSERT INTO t1 VALUES(5,'hello','world'); + } + db last_insert_rowid +} {5} +do_test intpkey-1.4 { + execsql { + SELECT * FROM t1; + } +} {5 hello world} +do_test intpkey-1.5 { + execsql { + SELECT rowid, * FROM t1; + } +} {5 5 hello world} + +# Attempting to insert a duplicate primary key should give a constraint +# failure. +# +do_test intpkey-1.6 { + set r [catch {execsql { + INSERT INTO t1 VALUES(5,'second','entry'); + }} msg] + lappend r $msg +} {1 {PRIMARY KEY must be unique}} +do_test intpkey-1.7 { + execsql { + SELECT rowid, * FROM t1; + } +} {5 5 hello world} +do_test intpkey-1.8 { + set r [catch {execsql { + INSERT INTO t1 VALUES(6,'second','entry'); + }} msg] + lappend r $msg +} {0 {}} +do_test intpkey-1.8.1 { + db last_insert_rowid +} {6} +do_test intpkey-1.9 { + execsql { + SELECT rowid, * FROM t1; + } +} {5 5 hello world 6 6 second entry} + +# A ROWID is automatically generated for new records that do not specify +# the integer primary key. +# +do_test intpkey-1.10 { + execsql { + INSERT INTO t1(b,c) VALUES('one','two'); + SELECT b FROM t1 ORDER BY b; + } +} {hello one second} + +# Try to change the ROWID for the new entry. +# +do_test intpkey-1.11 { + execsql { + UPDATE t1 SET a=4 WHERE b='one'; + SELECT * FROM t1; + } +} {4 one two 5 hello world 6 second entry} + +# Make sure SELECT statements are able to use the primary key column +# as an index. +# +do_test intpkey-1.12.1 { + execsql { + SELECT * FROM t1 WHERE a==4; + } +} {4 one two} +do_test intpkey-1.12.2 { + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t1 WHERE a==4; + } +} {/SEARCH TABLE t1 /} + +# Try to insert a non-integer value into the primary key field. This +# should result in a data type mismatch. +# +do_test intpkey-1.13.1 { + set r [catch {execsql { + INSERT INTO t1 VALUES('x','y','z'); + }} msg] + lappend r $msg +} {1 {datatype mismatch}} +do_test intpkey-1.13.2 { + set r [catch {execsql { + INSERT INTO t1 VALUES('','y','z'); + }} msg] + lappend r $msg +} {1 {datatype mismatch}} +do_test intpkey-1.14 { + set r [catch {execsql { + INSERT INTO t1 VALUES(3.4,'y','z'); + }} msg] + lappend r $msg +} {1 {datatype mismatch}} +do_test intpkey-1.15 { + set r [catch {execsql { + INSERT INTO t1 VALUES(-3,'y','z'); + }} msg] + lappend r $msg +} {0 {}} +do_test intpkey-1.16 { + execsql {SELECT * FROM t1} +} {-3 y z 4 one two 5 hello world 6 second entry} + +#### INDICES +# Check to make sure indices work correctly with integer primary keys +# +do_test intpkey-2.1 { + execsql { + CREATE INDEX i1 ON t1(b); + SELECT * FROM t1 WHERE b=='y' + } +} {-3 y z} +do_test intpkey-2.1.1 { + execsql { + SELECT * FROM t1 WHERE b=='y' AND rowid<0 + } +} {-3 y z} +do_test intpkey-2.1.2 { + execsql { + SELECT * FROM t1 WHERE b=='y' AND rowid<0 AND rowid>=-20 + } +} {-3 y z} +do_test intpkey-2.1.3 { + execsql { + SELECT * FROM t1 WHERE b>='y' + } +} {-3 y z} +do_test intpkey-2.1.4 { + execsql { + SELECT * FROM t1 WHERE b>='y' AND rowid<10 + } +} {-3 y z} + +do_test intpkey-2.2 { + execsql { + UPDATE t1 SET a=8 WHERE b=='y'; + SELECT * FROM t1 WHERE b=='y'; + } +} {8 y z} +do_test intpkey-2.3 { + execsql { + SELECT rowid, * FROM t1; + } +} {4 4 one two 5 5 hello world 6 6 second entry 8 8 y z} +do_test intpkey-2.4 { + execsql { + SELECT rowid, * FROM t1 WHERE b<'second' + } +} {5 5 hello world 4 4 one two} +do_test intpkey-2.4.1 { + execsql { + SELECT rowid, * FROM t1 WHERE 'second'>b + } +} {5 5 hello world 4 4 one two} +do_test intpkey-2.4.2 { + execsql { + SELECT rowid, * FROM t1 WHERE 8>rowid AND 'second'>b + } +} {4 4 one two 5 5 hello world} +do_test intpkey-2.4.3 { + execsql { + SELECT rowid, * FROM t1 WHERE 8>rowid AND 'second'>b AND 0'a' + } +} {5 5 hello world 4 4 one two 6 6 second entry 8 8 y z} +do_test intpkey-2.6 { + execsql { + DELETE FROM t1 WHERE rowid=4; + SELECT * FROM t1 WHERE b>'a'; + } +} {5 hello world 6 second entry 8 y z} +do_test intpkey-2.7 { + execsql { + UPDATE t1 SET a=-4 WHERE rowid=8; + SELECT * FROM t1 WHERE b>'a'; + } +} {5 hello world 6 second entry -4 y z} +do_test intpkey-2.7 { + execsql { + SELECT * FROM t1 + } +} {-4 y z 5 hello world 6 second entry} + +# Do an SQL statement. Append the search count to the end of the result. +# +proc count sql { + set ::sqlite_search_count 0 + return [concat [execsql $sql] $::sqlite_search_count] +} + +# Create indices that include the integer primary key as one of their +# columns. +# +do_test intpkey-3.1 { + execsql { + CREATE INDEX i2 ON t1(a); + } +} {} +do_test intpkey-3.2 { + count { + SELECT * FROM t1 WHERE a=5; + } +} {5 hello world 0} +do_test intpkey-3.3 { + count { + SELECT * FROM t1 WHERE a>4 AND a<6; + } +} {5 hello world 2} +do_test intpkey-3.4 { + count { + SELECT * FROM t1 WHERE b>='hello' AND b<'hello2'; + } +} {5 hello world 3} +do_test intpkey-3.5 { + execsql { + CREATE INDEX i3 ON t1(c,a); + } +} {} +do_test intpkey-3.6 { + count { + SELECT * FROM t1 WHERE c=='world'; + } +} {5 hello world 3} +do_test intpkey-3.7 { + execsql {INSERT INTO t1 VALUES(11,'hello','world')} + count { + SELECT * FROM t1 WHERE c=='world'; + } +} {5 hello world 11 hello world 5} +do_test intpkey-3.8 { + count { + SELECT * FROM t1 WHERE c=='world' AND a>7; + } +} {11 hello world 4} +do_test intpkey-3.9 { + count { + SELECT * FROM t1 WHERE 7=oid; + } +} {11 hello world 1} +do_test intpkey-4.9 { + count { + SELECT * FROM t1 WHERE 11<=_rowid_ AND 12>=a; + } +} {11 hello world 1} +do_test intpkey-4.10 { + count { + SELECT * FROM t1 WHERE 0>=_rowid_; + } +} {-4 y z 1} +do_test intpkey-4.11 { + count { + SELECT * FROM t1 WHERE a<0; + } +} {-4 y z 1} +do_test intpkey-4.12 { + count { + SELECT * FROM t1 WHERE a<0 AND a>10; + } +} {1} + +# Make sure it is OK to insert a rowid of 0 +# +do_test intpkey-5.1 { + execsql { + INSERT INTO t1 VALUES(0,'zero','entry'); + } + count { + SELECT * FROM t1 WHERE a=0; + } +} {0 zero entry 0} +do_test intpkey-5.2 { + execsql { + SELECT rowid, a FROM t1 ORDER BY rowid + } +} {-4 -4 0 0 5 5 6 6 11 11} + +# Test the ability of the COPY command to put data into a +# table that contains an integer primary key. +# +# COPY command has been removed. But we retain these tests so +# that the tables will contain the right data for tests that follow. +# +do_test intpkey-6.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(20,'b-20','c-20'); + INSERT INTO t1 VALUES(21,'b-21','c-21'); + INSERT INTO t1 VALUES(22,'b-22','c-22'); + COMMIT; + SELECT * FROM t1 WHERE a>=20; + } +} {20 b-20 c-20 21 b-21 c-21 22 b-22 c-22} +do_test intpkey-6.2 { + execsql { + SELECT * FROM t1 WHERE b=='hello' + } +} {5 hello world 11 hello world} +do_test intpkey-6.3 { + execsql { + DELETE FROM t1 WHERE b='b-21'; + SELECT * FROM t1 WHERE b=='b-21'; + } +} {} +do_test intpkey-6.4 { + execsql { + SELECT * FROM t1 WHERE a>=20 + } +} {20 b-20 c-20 22 b-22 c-22} + +# Do an insert of values with the columns specified out of order. +# +do_test intpkey-7.1 { + execsql { + INSERT INTO t1(c,b,a) VALUES('row','new',30); + SELECT * FROM t1 WHERE rowid>=30; + } +} {30 new row} +do_test intpkey-7.2 { + execsql { + SELECT * FROM t1 WHERE rowid>20; + } +} {22 b-22 c-22 30 new row} + +# Do an insert from a select statement. +# +do_test intpkey-8.1 { + execsql { + CREATE TABLE t2(x INTEGER PRIMARY KEY, y, z); + INSERT INTO t2 SELECT * FROM t1; + SELECT rowid FROM t2; + } +} {-4 0 5 6 11 20 22 30} +do_test intpkey-8.2 { + execsql { + SELECT x FROM t2; + } +} {-4 0 5 6 11 20 22 30} + +do_test intpkey-9.1 { + execsql { + UPDATE t1 SET c='www' WHERE c='world'; + SELECT rowid, a, c FROM t1 WHERE c=='www'; + } +} {5 5 www 11 11 www} + + +# Check insert of NULL for primary key +# +do_test intpkey-10.1 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(x INTEGER PRIMARY KEY, y, z); + INSERT INTO t2 VALUES(NULL, 1, 2); + SELECT * from t2; + } +} {1 1 2} +do_test intpkey-10.2 { + execsql { + INSERT INTO t2 VALUES(NULL, 2, 3); + SELECT * from t2 WHERE x=2; + } +} {2 2 3} +do_test intpkey-10.3 { + execsql { + INSERT INTO t2 SELECT NULL, z, y FROM t2; + SELECT * FROM t2; + } +} {1 1 2 2 2 3 3 2 1 4 3 2} + +# This tests checks to see if a floating point number can be used +# to reference an integer primary key. +# +do_test intpkey-11.1 { + execsql { + SELECT b FROM t1 WHERE a=2.0+3.0; + } +} {hello} +do_test intpkey-11.1 { + execsql { + SELECT b FROM t1 WHERE a=2.0+3.5; + } +} {} + +integrity_check intpkey-12.1 + +# Try to use a string that looks like a floating point number as +# an integer primary key. This should actually work when the floating +# point value can be rounded to an integer without loss of data. +# +do_test intpkey-13.1 { + execsql { + SELECT * FROM t1 WHERE a=1; + } +} {} +do_test intpkey-13.2 { + execsql { + INSERT INTO t1 VALUES('1.0',2,3); + SELECT * FROM t1 WHERE a=1; + } +} {1 2 3} +do_test intpkey-13.3 { + catchsql { + INSERT INTO t1 VALUES('1.5',3,4); + } +} {1 {datatype mismatch}} +ifcapable {bloblit} { + do_test intpkey-13.4 { + catchsql { + INSERT INTO t1 VALUES(x'123456',3,4); + } + } {1 {datatype mismatch}} +} +do_test intpkey-13.5 { + catchsql { + INSERT INTO t1 VALUES('+1234567890',3,4); + } +} {0 {}} + +# Compare an INTEGER PRIMARY KEY against a TEXT expression. The INTEGER +# affinity should be applied to the text value before the comparison +# takes place. +# +do_test intpkey-14.1 { + execsql { + CREATE TABLE t3(a INTEGER PRIMARY KEY, b INTEGER, c TEXT); + INSERT INTO t3 VALUES(1, 1, 'one'); + INSERT INTO t3 VALUES(2, 2, '2'); + INSERT INTO t3 VALUES(3, 3, 3); + } +} {} +do_test intpkey-14.2 { + execsql { + SELECT * FROM t3 WHERE a>2; + } +} {3 3 3} +do_test intpkey-14.3 { + execsql { + SELECT * FROM t3 WHERE a>'2'; + } +} {3 3 3} +do_test intpkey-14.4 { + execsql { + SELECT * FROM t3 WHERE a<'2'; + } +} {1 1 one} +do_test intpkey-14.5 { + execsql { + SELECT * FROM t3 WHERE a2147483648; + } +} {} +do_test intpkey-15.2 { + execsql { + INSERT INTO t1 VALUES(NULL, 'big-2', 234); + SELECT b FROM t1 WHERE a>=2147483648; + } +} {big-2} +do_test intpkey-15.3 { + execsql { + SELECT b FROM t1 WHERE a>2147483648; + } +} {} +do_test intpkey-15.4 { + execsql { + SELECT b FROM t1 WHERE a>=2147483647; + } +} {big-1 big-2} +do_test intpkey-15.5 { + execsql { + SELECT b FROM t1 WHERE a<2147483648; + } +} {y zero 2 hello second hello b-20 b-22 new 3 big-1} +do_test intpkey-15.6 { + execsql { + SELECT b FROM t1 WHERE a<12345678901; + } +} {y zero 2 hello second hello b-20 b-22 new 3 big-1 big-2} +do_test intpkey-15.7 { + execsql { + SELECT b FROM t1 WHERE a>12345678901; + } +} {} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/io.test b/components/external/SQLite-3.8.1/test/io.test new file mode 100644 index 0000000000000000000000000000000000000000..c5086c10ecb391cb00cb53c3eb0d3f003d05f98a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/io.test @@ -0,0 +1,643 @@ +# 2007 August 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing some specific characteristics of the +# IO traffic generated by SQLite (making sure SQLite is not writing out +# more database pages than it has to, stuff like that). +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix io + +db close +sqlite3_simulate_device +sqlite3 db test.db -vfs devsym + +# Test summary: +# +# io-1.* - Test that quick-balance does not journal pages unnecessarily. +# +# io-2.* - Test the "atomic-write optimization". +# +# io-3.* - Test the IO traffic enhancements triggered when the +# IOCAP_SEQUENTIAL device capability flag is set (no +# fsync() calls on the journal file). +# +# io-4.* - Test the IO traffic enhancements triggered when the +# IOCAP_SAFE_APPEND device capability flag is set (fewer +# fsync() calls on the journal file, no need to set nRec +# field in the single journal header). +# +# io-5.* - Test that the default page size is selected and used +# correctly. +# +# io-6.* - Test that the pager-cache is not being flushed unnecessarily +# after a transaction that uses the special atomic-write path +# is committed. +# + +set ::nWrite 0 +proc nWrite {db} { + set bt [btree_from_db $db] + db_enter $db + array set stats [btree_pager_stats $bt] + db_leave $db + set res [expr $stats(write) - $::nWrite] + set ::nWrite $stats(write) + set res +} + +set ::nSync 0 +proc nSync {} { + set res [expr {$::sqlite_sync_count - $::nSync}] + set ::nSync $::sqlite_sync_count + set res +} + +do_test io-1.1 { + execsql { + PRAGMA auto_vacuum = OFF; + PRAGMA page_size = 1024; + CREATE TABLE abc(a,b); + } + nWrite db +} {2} + +# Insert into the table 4 records of aproximately 240 bytes each. +# This should completely fill the root-page of the table. Each +# INSERT causes 2 db pages to be written - the root-page of "abc" +# and page 1 (db change-counter page). +do_test io-1.2 { + set ret [list] + execsql { INSERT INTO abc VALUES(1,randstr(230,230)); } + lappend ret [nWrite db] + execsql { INSERT INTO abc VALUES(2,randstr(230,230)); } + lappend ret [nWrite db] + execsql { INSERT INTO abc VALUES(3,randstr(230,230)); } + lappend ret [nWrite db] + execsql { INSERT INTO abc VALUES(4,randstr(230,230)); } + lappend ret [nWrite db] +} {2 2 2 2} + +# Insert another 240 byte record. This causes two leaf pages +# to be added to the root page of abc. 4 pages in total +# are written to the db file - the two leaf pages, the root +# of abc and the change-counter page. +do_test io-1.3 { + execsql { INSERT INTO abc VALUES(5,randstr(230,230)); } + nWrite db +} {4} + +# Insert another 3 240 byte records. After this, the tree consists of +# the root-node, which is close to empty, and two leaf pages, both of +# which are full. +do_test io-1.4 { + set ret [list] + execsql { INSERT INTO abc VALUES(6,randstr(230,230)); } + lappend ret [nWrite db] + execsql { INSERT INTO abc VALUES(7,randstr(230,230)); } + lappend ret [nWrite db] + execsql { INSERT INTO abc VALUES(8,randstr(230,230)); } + lappend ret [nWrite db] +} {2 2 2} + +# This insert should use the quick-balance trick to add a third leaf +# to the b-tree used to store table abc. It should only be necessary to +# write to 3 pages to do this: the change-counter, the root-page and +# the new leaf page. +do_test io-1.5 { + execsql { INSERT INTO abc VALUES(9,randstr(230,230)); } + nWrite db +} {3} + +ifcapable atomicwrite { + +#---------------------------------------------------------------------- +# Test cases io-2.* test the atomic-write optimization. +# +do_test io-2.1 { + execsql { DELETE FROM abc; VACUUM; } +} {} + +# Clear the write and sync counts. +nWrite db ; nSync + +# The following INSERT updates 2 pages and requires 4 calls to fsync(): +# +# 1) The directory in which the journal file is created, +# 2) The journal file (to sync the page data), +# 3) The journal file (to sync the journal file header), +# 4) The database file. +# +do_test io-2.2 { + execsql { INSERT INTO abc VALUES(1, 2) } + list [nWrite db] [nSync] +} {2 4} + +# Set the device-characteristic mask to include the SQLITE_IOCAP_ATOMIC, +# then do another INSERT similar to the one in io-2.2. This should +# only write 1 page and require a single fsync(). +# +# The single fsync() is the database file. Only one page is reported as +# written because page 1 - the change-counter page - is written using +# an out-of-band method that bypasses the write counter. +# +# UPDATE: As of [05f98d4eec] (adding SQLITE_DBSTATUS_CACHE_WRITE), the +# second write is also counted. So this now reports two writes and a +# single fsync. +# +sqlite3_simulate_device -char atomic +do_test io-2.3 { + execsql { INSERT INTO abc VALUES(3, 4) } + list [nWrite db] [nSync] +} {2 1} + +# Test that the journal file is not created and the change-counter is +# updated when the atomic-write optimization is used. +# +do_test io-2.4.1 { + execsql { + BEGIN; + INSERT INTO abc VALUES(5, 6); + } + sqlite3 db2 test.db -vfs devsym + execsql { SELECT * FROM abc } db2 +} {1 2 3 4} +do_test io-2.4.2 { + file exists test.db-journal +} {0} +do_test io-2.4.3 { + execsql { COMMIT } + execsql { SELECT * FROM abc } db2 +} {1 2 3 4 5 6} +db2 close + +# Test that the journal file is created and sync()d if the transaction +# modifies more than one database page, even if the IOCAP_ATOMIC flag +# is set. +# +do_test io-2.5.1 { + execsql { CREATE TABLE def(d, e) } + nWrite db ; nSync + execsql { + BEGIN; + INSERT INTO abc VALUES(7, 8); + } + file exists test.db-journal +} {0} +do_test io-2.5.2 { + execsql { INSERT INTO def VALUES('a', 'b'); } + file exists test.db-journal +} {1} +do_test io-2.5.3 { + execsql { COMMIT } + list [nWrite db] [nSync] +} {3 4} + +# Test that the journal file is created and sync()d if the transaction +# modifies a single database page and also appends a page to the file. +# Internally, this case is handled differently to the one above. The +# journal file is not actually created until the 'COMMIT' statement +# is executed. +# +# Changed 2010-03-27: The size of the database is now stored in +# bytes 28..31 and so when a page is added to the database, page 1 +# is immediately modified and the journal file immediately comes into +# existence. To fix this test, the BEGIN is changed into a a +# BEGIN IMMEDIATE and the INSERT is omitted. +# +do_test io-2.6.1 { + execsql { + BEGIN IMMEDIATE; + -- INSERT INTO abc VALUES(9, randstr(1000,1000)); + } + file exists test.db-journal +} {0} +do_test io-2.6.2 { + # Create a file at "test.db-journal". This will prevent SQLite from + # opening the journal for exclusive access. As a result, the COMMIT + # should fail with SQLITE_CANTOPEN and the transaction rolled back. + # + file mkdir test.db-journal + catchsql { + INSERT INTO abc VALUES(9, randstr(1000,1000)); + COMMIT + } +} {1 {unable to open database file}} +do_test io-2.6.3 { + forcedelete test.db-journal + catchsql { COMMIT } +} {0 {}} +do_test io-2.6.4 { + execsql { SELECT * FROM abc } +} {1 2 3 4 5 6 7 8} + +# Test that if the database modification is part of multi-file commit, +# the journal file is always created. In this case, the journal file +# is created during execution of the COMMIT statement, so we have to +# use the same technique to check that it is created as in the above +# block. +forcedelete test2.db test2.db-journal +ifcapable attach { + do_test io-2.7.1 { + execsql { + ATTACH 'test2.db' AS aux; + PRAGMA aux.page_size = 1024; + CREATE TABLE aux.abc2(a, b); + BEGIN; + INSERT INTO abc VALUES(9, 10); + } + file exists test.db-journal + } {0} + do_test io-2.7.2 { + execsql { INSERT INTO abc2 SELECT * FROM abc } + file exists test2.db-journal + } {0} + do_test io-2.7.3 { + execsql { SELECT * FROM abc UNION ALL SELECT * FROM abc2 } + } {1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10} + do_test io-2.7.4 { + file mkdir test2.db-journal + catchsql { COMMIT } + } {1 {unable to open database file}} + do_test io-2.7.5 { + forcedelete test2.db-journal + catchsql { COMMIT } + } {1 {cannot commit - no transaction is active}} + do_test io-2.7.6 { + execsql { SELECT * FROM abc UNION ALL SELECT * FROM abc2 } + } {1 2 3 4 5 6 7 8} +} + +# Try an explicit ROLLBACK before the journal file is created. +# +do_test io-2.8.1 { + execsql { + BEGIN; + DELETE FROM abc; + } + file exists test.db-journal +} {0} +do_test io-2.8.2 { + execsql { SELECT * FROM abc } +} {} +do_test io-2.8.3 { + execsql { + ROLLBACK; + SELECT * FROM abc; + } +} {1 2 3 4 5 6 7 8} + +# Test that the atomic write optimisation is not enabled if the sector +# size is larger than the page-size. +# +do_test io-2.9.1 { + db close + sqlite3 db test.db + sqlite3_simulate_device -char atomic -sectorsize 2048 + execsql { + BEGIN; + INSERT INTO abc VALUES(9, 10); + } + file exists test.db-journal +} {1} +do_test io-2.9.2 { + execsql { ROLLBACK; } + db close + forcedelete test.db test.db-journal + sqlite3 db test.db -vfs devsym + execsql { + PRAGMA auto_vacuum = OFF; + PRAGMA page_size = 2048; + CREATE TABLE abc(a, b); + } + execsql { + BEGIN; + INSERT INTO abc VALUES(9, 10); + } + file exists test.db-journal +} {0} +do_test io-2.9.3 { + execsql { COMMIT } +} {} + +# Test a couple of the more specific IOCAP_ATOMIC flags +# (i.e IOCAP_ATOMIC2K etc.). +# +do_test io-2.10.1 { + sqlite3_simulate_device -char atomic1k + execsql { + BEGIN; + INSERT INTO abc VALUES(11, 12); + } + file exists test.db-journal +} {1} +do_test io-2.10.2 { + execsql { ROLLBACK } + sqlite3_simulate_device -char atomic2k + execsql { + BEGIN; + INSERT INTO abc VALUES(11, 12); + } + file exists test.db-journal +} {0} +do_test io-2.10.3 { + execsql { ROLLBACK } +} {} + +do_test io-2.11.0 { + execsql { + PRAGMA locking_mode = exclusive; + PRAGMA locking_mode; + } +} {exclusive exclusive} +do_test io-2.11.1 { + execsql { + INSERT INTO abc VALUES(11, 12); + } + file exists test.db-journal +} {0} + +do_test io-2.11.2 { + execsql { + PRAGMA locking_mode = normal; + INSERT INTO abc VALUES(13, 14); + } + file exists test.db-journal +} {0} + +} ;# /* ifcapable atomicwrite */ + +#---------------------------------------------------------------------- +# Test cases io-3.* test the IOCAP_SEQUENTIAL optimization. +# +sqlite3_simulate_device -char sequential -sectorsize 0 +ifcapable pager_pragmas { + do_test io-3.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db -vfs devsym + db eval { + PRAGMA auto_vacuum=OFF; + } + # File size might be 1 due to the hack to work around ticket #3260. + # Search for #3260 in os_unix.c for additional information. + expr {[file size test.db]>1} + } {0} + do_test io-3.2 { + execsql { CREATE TABLE abc(a, b) } + nSync + execsql { + PRAGMA temp_store = memory; + PRAGMA cache_size = 10; + BEGIN; + INSERT INTO abc VALUES('hello', 'world'); + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + } + # File has grown - showing there was a cache-spill - but there + # have been no calls to fsync(). The file is probably about 30KB. + # But some VFS implementations (symbian) buffer writes so the actual + # size may be a little less than that. So this test case just tests + # that the file is now greater than 20000 bytes in size. + list [expr [file size test.db]>20000] [nSync] + } {1 0} + do_test io-3.3 { + # The COMMIT requires a single fsync() - to the database file. + execsql { COMMIT } + list [file size test.db] [nSync] + } {39936 1} +} + +#---------------------------------------------------------------------- +# Test cases io-4.* test the IOCAP_SAFE_APPEND optimization. +# +sqlite3_simulate_device -char safe_append + +# With the SAFE_APPEND flag set, simple transactions require 3, rather +# than 4, calls to fsync(). The fsync() calls are on: +# +# 1) The directory in which the journal file is created, (unix only) +# 2) The journal file (to sync the page data), +# 3) The database file. +# +# Normally, when the SAFE_APPEND flag is not set, there is another fsync() +# on the journal file between steps (2) and (3) above. +# +set expected_sync_count 2 +if {$::tcl_platform(platform)=="unix"} { + ifcapable dirsync { + incr expected_sync_count + } +} + +do_test io-4.1 { + execsql { DELETE FROM abc } + nSync + execsql { INSERT INTO abc VALUES('a', 'b') } + nSync +} $expected_sync_count + +# With SAFE_APPEND set, the nRec field of the journal file header should +# be set to 0xFFFFFFFF before the first journal sync. The nRec field +# occupies bytes 8-11 of the journal file. +# +do_test io-4.2.1 { + execsql { BEGIN } + execsql { INSERT INTO abc VALUES('c', 'd') } + file exists test.db-journal +} {1} +if {$::tcl_platform(platform)=="unix"} { + do_test io-4.2.2 { + hexio_read test.db-journal 8 4 + } {FFFFFFFF} +} +do_test io-4.2.3 { + execsql { COMMIT } + nSync +} $expected_sync_count +sqlite3_simulate_device -char safe_append + +# With SAFE_APPEND set, there should only ever be one journal-header +# written to the database, even though the sync-mode is "full". +# +do_test io-4.3.1 { + execsql { + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + } + expr {[file size test.db]/1024} +} {43} +ifcapable pager_pragmas { + do_test io-4.3.2 { + execsql { + PRAGMA synchronous = full; + PRAGMA cache_size = 10; + PRAGMA synchronous; + } + } {2} +} +do_test io-4.3.3 { + execsql { + BEGIN; + UPDATE abc SET a = 'x'; + } + file exists test.db-journal +} {1} +if {$tcl_platform(platform) != "symbian"} { + # This test is not run on symbian because the file-buffer makes it + # difficult to predict the exact size of the file as reported by + # [file size]. + do_test io-4.3.4 { + # The UPDATE statement in the statement above modifies 41 pages + # (all pages in the database except page 1 and the root page of + # abc). Because the cache_size is set to 10, this must have required + # at least 4 cache-spills. If there were no journal headers written + # to the journal file after the cache-spill, then the size of the + # journal file is give by: + # + # = + nPage * ( + 8) + # + # If the journal file contains additional headers, this formula + # will not predict the size of the journal file. + # + file size test.db-journal + } [expr 512 + (1024+8)*41] +} + +#---------------------------------------------------------------------- +# Test cases io-5.* test that the default page size is selected and +# used correctly. +# +set tn 0 +foreach {char sectorsize pgsize} { + {} 512 1024 + {} 1024 1024 + {} 2048 2048 + {} 8192 8192 + {} 16384 8192 + {atomic} 512 8192 + {atomic512} 512 1024 + {atomic2K} 512 2048 + {atomic2K} 4096 4096 + {atomic2K atomic} 512 8192 + {atomic64K} 512 1024 +} { + incr tn + if {$pgsize>$::SQLITE_MAX_PAGE_SIZE} continue + db close + forcedelete test.db test.db-journal + sqlite3_simulate_device -char $char -sectorsize $sectorsize + sqlite3 db test.db -vfs devsym + db eval { + PRAGMA auto_vacuum=OFF; + } + ifcapable !atomicwrite { + if {[regexp {^atomic} $char]} continue + } + do_test io-5.$tn { + execsql { + CREATE TABLE abc(a, b, c); + } + expr {[file size test.db]/2} + } $pgsize +} + +#---------------------------------------------------------------------- +# +do_test io-6.1 { + db close + sqlite3_simulate_device -char atomic + forcedelete test.db + sqlite3 db test.db -vfs devsym + execsql { + PRAGMA mmap_size = 0; + PRAGMA page_size = 1024; + PRAGMA cache_size = 2000; + CREATE TABLE t1(x); + CREATE TABLE t2(x); + CREATE TABLE t3(x); + CREATE INDEX i3 ON t3(x); + INSERT INTO t3 VALUES(randomblob(100)); + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + INSERT INTO t3 SELECT randomblob(100) FROM t3; + } + + db_save_and_close +} {} + +foreach {tn sql} { + 1 { BEGIN; + INSERT INTO t1 VALUES('123'); + INSERT INTO t2 VALUES('456'); + COMMIT; + } + 2 { BEGIN; + INSERT INTO t1 VALUES('123'); + COMMIT; + } +} { + + # These tests don't work with memsubsys1, as it causes the effective page + # cache size to become too small to hold the entire db in memory. + if {[permutation] == "memsubsys1"} continue + + db_restore + sqlite3 db test.db -vfs devsym + execsql { + PRAGMA cache_size = 2000; + PRAGMA mmap_size = 0; + SELECT x FROM t3 ORDER BY rowid; + SELECT x FROM t3 ORDER BY x; + } + do_execsql_test 6.2.$tn.1 { PRAGMA integrity_check } {ok} + do_execsql_test 6.2.$tn.2 $sql + + # Corrupt the database file on disk. This should not matter for the + # purposes of the following "PRAGMA integrity_check", as the entire + # database should be cached in the pager-cache. If corruption is + # reported, it indicates that executing $sql caused the pager cache + # to be flushed. Which is a bug. + hexio_write test.db [expr 1024 * 5] [string repeat 00 2048] + do_execsql_test 6.2.$tn.3 { PRAGMA integrity_check } {ok} + db close +} + +sqlite3_simulate_device -char {} -sectorsize 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/ioerr.test b/components/external/SQLite-3.8.1/test/ioerr.test new file mode 100644 index 0000000000000000000000000000000000000000..b237439ea2956be78dc0f4dcbf9d5aab3ed14861 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/ioerr.test @@ -0,0 +1,465 @@ +# 2001 October 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing for correct handling of I/O errors +# such as writes failing because the disk is full. +# +# The tests in this file use special facilities that are only +# available in the SQLite test fixture. +# +# $Id: ioerr.test,v 1.43 2009/04/06 17:50:03 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_DEFAULT_AUTOVACUUM is set to true, then a simulated IO error +# on the 8th IO operation in the SQL script below doesn't report an error. +# +# This is because the 8th IO call attempts to read page 2 of the database +# file when the file on disk is only 1 page. The pager layer detects that +# this has happened and suppresses the error returned by the OS layer. +# +do_ioerr_test ioerr-1 -erc 1 -ckrefcount 1 -sqlprep { + SELECT * FROM sqlite_master; +} -sqlbody { + CREATE TABLE t1(a,b,c); + SELECT * FROM sqlite_master; + BEGIN TRANSACTION; + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(4,5,6); + ROLLBACK; + SELECT * FROM t1; + BEGIN TRANSACTION; + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(4,5,6); + COMMIT; + SELECT * FROM t1; + DELETE FROM t1 WHERE a<100; +} -exclude [expr [string match [execsql {pragma auto_vacuum}] 1] ? 4 : 0] + +# Test for IO errors during a VACUUM. +# +# The first IO call is excluded from the test. This call attempts to read +# the file-header of the temporary database used by VACUUM. Since the +# database doesn't exist at that point, the IO error is not detected. +# +# Additionally, if auto-vacuum is enabled, the 12th IO error is not +# detected. Same reason as the 8th in the test case above. +# +ifcapable vacuum { + do_ioerr_test ioerr-2 -cksum true -ckrefcount true -sqlprep { + BEGIN; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, randstr(50,50), randstr(50,50)); + INSERT INTO t1 SELECT a+2, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+4, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+8, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+16, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+32, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+64, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+128, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 VALUES(1, randstr(600,600), randstr(600,600)); + CREATE TABLE t2 AS SELECT * FROM t1; + CREATE TABLE t3 AS SELECT * FROM t1; + COMMIT; + DROP TABLE t2; + } -sqlbody { + VACUUM; + } -exclude [list \ + 1 [expr [string match [execsql {pragma auto_vacuum}] 1]?9:-1]] +} + +do_ioerr_test ioerr-3 -ckrefcount true -tclprep { + execsql { + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE abc(a); + INSERT INTO abc VALUES(randstr(1500,1500)); -- Page 4 is overflow + } + for {set i 0} {$i<150} {incr i} { + execsql { + INSERT INTO abc VALUES(randstr(100,100)); + } + } + execsql COMMIT +} -sqlbody { + CREATE TABLE abc2(a); + BEGIN; + DELETE FROM abc WHERE length(a)>100; + UPDATE abc SET a = randstr(90,90); + COMMIT; + CREATE TABLE abc3(a); +} + +# Test IO errors that can occur retrieving a record header that flows over +# onto an overflow page. +do_ioerr_test ioerr-4 -ckrefcount true -tclprep { + set sql "CREATE TABLE abc(a1" + for {set i 2} {$i<1300} {incr i} { + append sql ", a$i" + } + append sql ");" + execsql $sql + execsql {INSERT INTO abc (a1) VALUES(NULL)} +} -sqlbody { + SELECT * FROM abc; +} + + +# Test IO errors that may occur during a multi-file commit. +# +# Tests 8 and 17 are excluded when auto-vacuum is enabled for the same +# reason as in test cases ioerr-1.XXX +ifcapable attach { + set ex "" + if {[string match [execsql {pragma auto_vacuum}] 1]} { + set ex [list 4 17] + } + do_ioerr_test ioerr-5 -restoreprng 0 -ckrefcount true -sqlprep { + ATTACH 'test2.db' AS test2; + } -sqlbody { + BEGIN; + CREATE TABLE t1(a,b,c); + CREATE TABLE test2.t2(a,b,c); + COMMIT; + } -exclude $ex +} + +# Test IO errors when replaying two hot journals from a 2-file +# transaction. This test only runs on UNIX. +# +# It cannot be run under the "exclusive" permutation. In that case, the +# locks held by the connection in the local (this) process prevent a +# second connection from attempting the multi-file transaction. +# +ifcapable crashtest&&attach { + if {![catch {sqlite3 -has-codec} r] && !$r && [permutation]!="exclusive"} { + do_ioerr_test ioerr-6 -ckrefcount true -tclprep { + execsql { + ATTACH 'test2.db' as aux; + CREATE TABLE tx(a, b); + CREATE TABLE aux.ty(a, b); + } + set rc [crashsql -delay 2 -file test2.db-journal { + ATTACH 'test2.db' as aux; + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE aux.t2(a, b, c); + CREATE TABLE t1(a, b, c); + COMMIT; + }] + if {$rc!="1 {child process exited abnormally}"} { + error "Wrong error message: $rc" + } + } -sqlbody { + SELECT * FROM sqlite_master; + SELECT * FROM aux.sqlite_master; + } + } +} + +# Test handling of IO errors that occur while rolling back hot journal +# files. +# +# These tests can't be run on windows because the windows version of +# SQLite holds a mandatory exclusive lock on journal files it has open. +# +if {$tcl_platform(platform)!="windows"} { + do_ioerr_test ioerr-7 -tclprep { + db close + sqlite3 db2 test2.db + db2 eval { + PRAGMA synchronous = 0; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + BEGIN; + INSERT INTO t1 VALUES(3, 4); + } + forcecopy test2.db test.db + forcecopy test2.db-journal test.db-journal + db2 close + } -tclbody { + sqlite3 db test.db + db eval { + SELECT * FROM t1; + } + } -exclude 1 +} + +# For test coverage: Cause an I/O failure while trying to read a +# short field (one that fits into a Mem buffer without mallocing +# for space). +# +do_ioerr_test ioerr-8 -ckrefcount true -tclprep { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(randstr(200,200), randstr(1000,1000), 2); + } + db close + sqlite3 db test.db +} -sqlbody { + SELECT c FROM t1; +} + +# For test coverage: Cause an IO error whilst reading the master-journal +# name from a journal file. +if {$tcl_platform(platform)=="unix"} { + do_ioerr_test ioerr-9 -ckrefcount true -tclprep { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(randstr(200,200), randstr(1000,1000), 2); + BEGIN; + INSERT INTO t1 VALUES(randstr(200,200), randstr(1000,1000), 2); + } + forcecopy test.db-journal test2.db-journal + execsql { + COMMIT; + } + forcecopy test2.db-journal test.db-journal + set f [open test.db-journal a] + fconfigure $f -encoding binary + puts -nonewline $f "hello" + puts -nonewline $f "\x00\x00\x00\x05\x01\x02\x03\x04" + puts -nonewline $f "\xd9\xd5\x05\xf9\x20\xa1\x63\xd7" + close $f + } -sqlbody { + SELECT a FROM t1; + } +} + +# For test coverage: Cause an IO error during statement playback (i.e. +# a constraint). +do_ioerr_test ioerr-10 -ckrefcount true -tclprep { + execsql { + BEGIN; + CREATE TABLE t1(a PRIMARY KEY, b); + } + for {set i 0} {$i < 500} {incr i} { + execsql {INSERT INTO t1 VALUES(:i, 'hello world');} + } + execsql { + COMMIT; + } +} -tclbody { + + catch {execsql { + BEGIN; + INSERT INTO t1 VALUES('abc', 123); + INSERT INTO t1 VALUES('def', 123); + INSERT INTO t1 VALUES('ghi', 123); + INSERT INTO t1 SELECT (a+500)%900, 'good string' FROM t1; + }} msg + + if {$msg != "column a is not unique"} { + error $msg + } +} + +# Assertion fault bug reported by alex dimitrov. +# +do_ioerr_test ioerr-11 -ckrefcount true -erc 1 -sqlprep { + CREATE TABLE A(Id INTEGER, Name TEXT); + INSERT INTO A(Id, Name) VALUES(1, 'Name'); +} -sqlbody { + UPDATE A SET Id = 2, Name = 'Name2' WHERE Id = 1; +} + +# Test that an io error encountered in a sync() caused by a call to +# sqlite3_release_memory() is handled Ok. Only try this if +# memory-management is enabled. +# +ifcapable memorymanage { + do_ioerr_test memmanage-ioerr1 -ckrefcount true -sqlprep { + BEGIN; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(randstr(50,50), randstr(100,100), randstr(10,10)); + INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(9,9), randstr(90,90) FROM t1; + } -tclbody { + sqlite3_release_memory + } -sqlbody { + COMMIT; + } +} + +ifcapable pager_pragmas&&autovacuum { + do_ioerr_test ioerr-12 -ckrefcount true -erc 1 -sqlprep { + PRAGMA page_size = 512; + PRAGMA auto_vacuum = incremental; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES( randomblob(1 * (512-4)) ); + INSERT INTO t1 VALUES( randomblob(110 * (512-4)) ); + INSERT INTO t1 VALUES( randomblob(2 * (512-4)) ); + INSERT INTO t1 VALUES( randomblob(110 * (512-4)) ); + INSERT INTO t1 VALUES( randomblob(3 * (512-4)) ); + DELETE FROM t1 WHERE rowid = 3; + PRAGMA incremental_vacuum = 2; + DELETE FROM t1 WHERE rowid = 1; + } -sqlbody { + PRAGMA incremental_vacuum = 1; + } +} + +# Usually, after a new page is allocated from the end of the file, it does +# not need to be written to the journal. The exception is when the new page +# shares its sector with an existing page that does need to be journalled. +# This test case provokes this condition to test for the sake of coverage +# that an IO error while journalling the coresident page is handled correctly. +# +sqlite3_simulate_device -char {} -sectorsize 2048 +do_ioerr_test ioerr-12 -ckrefcount true -erc 1 -tclprep { + db close + sqlite3 db test.db -vfs devsym + + # Create a test database. Page 2 is the root page of table t1. The only + # row inserted into t1 has an overflow page - page 3. Page 3 will be + # coresident on the 2048 byte sector with the next page to be allocated. + # + db eval { PRAGMA page_size = 1024 } + db eval { CREATE TABLE t1(x) } + db eval { INSERT INTO t1 VALUES(randomblob(1100)); } +} -tclbody { + db eval { INSERT INTO t1 VALUES(randomblob(2000)); } +} +sqlite3_simulate_device -char {} -sectorsize 0 +catch {db close} + +do_ioerr_test ioerr-13 -ckrefcount true -erc 1 -sqlprep { + PRAGMA auto_vacuum = incremental; + CREATE TABLE t1(x); + CREATE TABLE t2(x); + INSERT INTO t2 VALUES(randomblob(1500)); + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t1 VALUES(randomblob(20)); + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; /* 64 entries in t1 */ + INSERT INTO t1 SELECT x FROM t1 LIMIT 14; /* 78 entries in t1 */ + DELETE FROM t2 WHERE rowid = 3; +} -sqlbody { + -- This statement uses the balance_quick() optimization. The new page + -- is appended to the database file. But the overflow page used by + -- the new record will be positioned near the start of the database + -- file, in the gap left by the "DELETE FROM t2 WHERE rowid=3" statement + -- above. + -- + -- The point of this is that the statement wil need to update two pointer + -- map pages. Which introduces another opportunity for an IO error. + -- + INSERT INTO t1 VALUES(randomblob(2000)); +} + +do_ioerr_test ioerr-14 -ckrefcount true -erc 1 -sqlprep { + PRAGMA auto_vacuum = incremental; + CREATE TABLE t1(x); + CREATE TABLE t2(x); + INSERT INTO t2 VALUES(randomblob(1500)); + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + INSERT INTO t2 SELECT randomblob(1500) FROM t2; + + -- This statement inserts a row into t1 with an overflow page at the + -- end of the file. A long way from its parent (the root of t1). + INSERT INTO t1 VALUES(randomblob(1500)); + DELETE FROM t2 WHERE rowid<10; +} -sqlbody { + -- This transaction will cause the root-page of table t1 to divide + -- (by calling balance_deeper()). When it does, the "parent" page of the + -- overflow page inserted in the -sqlprep block above will change and + -- the corresponding pointer map page be updated. This test case attempts + -- to cause an IO error during the pointer map page update. + -- + BEGIN; + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + COMMIT; +} + +do_ioerr_test ioerr-15 -tclprep { + db eval { + BEGIN; + PRAGMA cache_size = 10; + CREATE TABLE t1(a); + CREATE INDEX i1 ON t1(a); + CREATE TABLE t2(a); + } + for {set ii 1} {$ii < 100} {incr ii} { + set v [string range [string repeat [format %.3d $ii] 200] 0 220] + db eval {INSERT INTO t1 VALUES($v)} + } + db eval { + DELETE FROM t1 WHERE oid > 85; + COMMIT; + } +} -sqlbody { + BEGIN; + INSERT INTO t2 VALUES(randstr(22000,22000)); + DELETE FROM t1 WHERE oid = 83; + COMMIT; +} + +# This test verifies that IO errors that occur within the obscure branch +# of code executed by tkt3762.test are correctly reported. +# +ifcapable vacuum&&autovacuum&&pragma { + do_ioerr_test ioerr-16 -erc 1 -ckrefcount 1 -sqlprep { + PRAGMA auto_vacuum=INCREMENTAL; + PRAGMA page_size=1024; + BEGIN; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(zeroblob(900)); + INSERT INTO t1 VALUES(zeroblob(900)); + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + DELETE FROM t1 WHERE rowid>202; + COMMIT; + VACUUM; + PRAGMA cache_size = 10; + BEGIN; + DELETE FROM t1 WHERE rowid IN (10,11,12) ; + } -sqlbody { + PRAGMA incremental_vacuum(10); + COMMIT; + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/ioerr2.test b/components/external/SQLite-3.8.1/test/ioerr2.test new file mode 100644 index 0000000000000000000000000000000000000000..5150ace3ab5ae2264d70438549ea15f3943d819b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/ioerr2.test @@ -0,0 +1,170 @@ +# 2007 April 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing for correct handling of I/O errors +# such as writes failing because the disk is full. +# +# The tests in this file use special facilities that are only +# available in the SQLite test fixture. +# +# $Id: ioerr2.test,v 1.12 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !integrityck { + finish_test + return +} + +do_test ioerr2-1.1 { + execsql { + PRAGMA cache_size = 10; + PRAGMA default_cache_size = 10; + CREATE TABLE t1(a, b, PRIMARY KEY(a, b)); + INSERT INTO t1 VALUES(randstr(400,400),randstr(400,400)); + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 2 + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 4 + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 8 + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 16 + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) FROM t1; -- 32 + } +} {} + +set ::cksum [execsql {SELECT md5sum(a, b) FROM t1}] +proc check_db {testname} { + + # Make sure no I/O errors are simulated in this proc. + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_persist 0 + set ::sqlite_io_error_pending 0 + + # Run an integrity-check. If "disk I/O error" is returned, the + # pager must be in error state. In this case open a new database + # connection. Otherwise, try a ROLLBACK, in case a transaction + # is still active. + set rc [catch {execsql {PRAGMA integrity_check}} msg] + if {$rc && ($msg eq "disk I/O error" || $msg eq "database is locked")} { + db close + sqlite3 db test.db + set refcnt 0 + } else { + if {$rc || $msg ne "ok"} { + error $msg + } + catch {execsql ROLLBACK} + } + + # Check that the database checksum is still $::cksum, and that + # the integrity-check passes. + set ck [execsql {SELECT md5sum(a, b) FROM t1}] + do_test ${testname}.cksum [list set ck $ck] $::cksum + integrity_check ${testname}.integrity + do_test ${testname}.refcnt { + lindex [sqlite3_pager_refcounts db] 0 + } 0 +} + +check_db ioerr2-2 + +set sql { + PRAGMA cache_size = 10; + PRAGMA default_cache_size = 10; + BEGIN; + DELETE FROM t1 WHERE (oid%7)==0; + INSERT INTO t1 SELECT randstr(400,400), randstr(400,400) + WHERE (random()%7)==0; + UPDATE t1 SET a = randstr(400,400), b = randstr(400,400) + WHERE (random()%7)==0; + ROLLBACK; +} + +foreach bPersist [list 0 1] { + set ::go 1 + for {set ::N 1} {$::go} {incr ::N} { + db close + sqlite3 db test.db + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_persist $bPersist + set ::sqlite_io_error_pending $::N + + foreach {::go res} [catchsql $sql] {} + check_db ioerr2-3.$bPersist.$::N + } +} +foreach bPersist [list 0 1] { + set ::go 1 + for {set ::N 1} {$::go} {incr ::N} { + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_persist $bPersist + set ::sqlite_io_error_pending $::N + + foreach {::go res} [catchsql $sql] {} + check_db ioerr2-4.[expr {$bPersist+2}].$::N + } +} + +do_test ioerr2-5 { + execsql { + CREATE TABLE t2 AS SELECT * FROM t1; + PRAGMA temp_store = memory; + } + set ::sqlite_io_error_persist 0 + set ::go 1 + set rc [catch { + for {set ::N 2} {$::N<200} {incr ::N} { + db eval {SELECT * FROM t1 WHERE rowid IN (1, 5, 10, 15, 20)} { + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_pending $::N + set sql {UPDATE t2 SET b = randstr(400,400)} + foreach {::go res} [catchsql $sql] {} + } + } + } msg] + list $rc $msg +} {1 {abort due to ROLLBACK}} + +if {$::tcl_platform(platform) == "unix"} { + # Cause the call to xAccess used by [pragma temp_store_directory] to + # determine if the specified directory is writable to fail. This causes + # SQLite to report "not a writable directory", which is probably the + # right answer. + # + do_test ioerr2-6 { + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_pending 1 + catchsql {PRAGMA temp_store_directory = '/tmp/'} + } {1 {not a writable directory}} +} + +do_ioerr_test ioerr2-7 -persist 0 -sqlprep { + PRAGMA cache_size = 10; + PRAGMA auto_vacuum = 1; + CREATE TABLE ab(a, b); + CREATE TABLE de(d, e); + INSERT INTO ab VALUES(1, randstr(200,200)); + INSERT INTO ab SELECT a+1, randstr(200,200) FROM ab; + INSERT INTO ab SELECT a+2, randstr(200,200) FROM ab; + INSERT INTO ab SELECT a+4, randstr(200,200) FROM ab; + INSERT INTO ab SELECT a+8, randstr(200,200) FROM ab; + INSERT INTO ab SELECT a+16, randstr(200,200) FROM ab; + INSERT INTO ab SELECT a+32, randstr(200,200) FROM ab; + INSERT INTO ab SELECT a+64, randstr(200,200) FROM ab; + INSERT INTO de SELECT * FROM ab; +} -sqlbody { + BEGIN; + UPDATE ab SET b = randstr(200,200); + UPDATE de SET e = randstr(200,200) WHERE d = (SELECT max(d) FROM de); + DELETE FROM ab; + COMMIT; +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/ioerr3.test b/components/external/SQLite-3.8.1/test/ioerr3.test new file mode 100644 index 0000000000000000000000000000000000000000..4598cbffe9754515e93ed0595b55fed8eeb7d64d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/ioerr3.test @@ -0,0 +1,42 @@ +# 2007 December 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing for correct handling of I/O errors +# in conjunction with very small soft-heap-limit values. +# +# $Id: ioerr3.test,v 1.2 2008/01/19 23:50:26 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_ioerr_test ioerr3-1 -sqlprep { + CREATE TABLE t1(id INTEGER, name TEXT); +} -tclbody { + sqlite3_soft_heap_limit 8192 + db cache size 0 + execsql BEGIN + for {set ii 0} {$ii < 100} {incr ii} { + execsql { + INSERT INTO t1(id, name) VALUES (1, +'A1234567890B1234567890C1234567890D1234567890E1234567890F1234567890G1234567890H1234567890I1234567890J1234567890K1234567890L1234567890M1234567890N1234567890O1234567890P1234567890Q1234567890R1234567890' + ); + } + } + execsql COMMIT +} + +do_ioerr_test ioerr3-2 -sqlbody { + CREATE TEMP TABLE t1(x,y); +} + +sqlite3_soft_heap_limit 0 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/ioerr4.test b/components/external/SQLite-3.8.1/test/ioerr4.test new file mode 100644 index 0000000000000000000000000000000000000000..defa32686878d932a790b4cc945661dcfde5cc05 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/ioerr4.test @@ -0,0 +1,100 @@ +# 2007 December 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing for correct handling of I/O errors +# during incremental vacuum with a shared cache. +# +# $Id: ioerr4.test,v 1.2 2008/05/08 01:11:42 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# This test requires both shared cache and incremental vacuum. +# +ifcapable {!shared_cache || !autovacuum} { + finish_test + return +} + +# Enable shared cache mode and incremental vacuum. +# +do_test ioerr4-1.1 { + db close + set ::enable_shared_cache [sqlite3_enable_shared_cache 1] +} {0} +do_test ioerr4-1.2 { + forcedelete test.db test.db-journal + sqlite3 db test.db + sqlite3 db2 test.db + db eval { + PRAGMA auto_vacuum=INCREMENTAL; + CREATE TABLE a(i INTEGER, b BLOB); + } + db2 eval { + SELECT name FROM sqlite_master + } +} {a} +do_test ioerr4-1.3 { + db eval { + PRAGMA auto_vacuum; + } +} {2} + +# Insert and delete many records in order to put lots of pages +# on the freelist. +# +do_test ioerr4-1.4 { + db eval { + INSERT INTO a VALUES(1, zeroblob(2000)); + INSERT INTO a VALUES(2, zeroblob(2000)); + INSERT INTO a SELECT i+2, zeroblob(2000) FROM a; + INSERT INTO a SELECT i+4, zeroblob(2000) FROM a; + INSERT INTO a SELECT i+8, zeroblob(2000) FROM a; + INSERT INTO a SELECT i+16, zeroblob(2000) FROM a; + SELECT count(*) FROM a; + } +} {32} +do_test ioerr4-1.5 { + db eval { + PRAGMA freelist_count + } +} {0} +do_test ioerr4-1.6 { + db eval { + DELETE FROM a; + PRAGMA freelist_count; + } +} {64} + +# Set up for an I/O error on incremental vacuum +# with two connections on shared cache. +# +db close +db2 close +forcecopy test.db test.db-bu +do_ioerr_test ioerr4-2 -tclprep { + catch {db2 close} + db close + forcedelete test.db test.db-journal + forcecopy test.db-bu test.db + sqlite3_enable_shared_cache 1 + set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db] + db eval {PRAGMA auto_vacuum=INCREMENTAL} + sqlite3 db2 test.db +} -tclbody { + db eval {PRAGMA incremental_vacuum(5)} +} + +db2 close +forcedelete test.db-bu +sqlite3_enable_shared_cache $::enable_shared_cache + +finish_test diff --git a/components/external/SQLite-3.8.1/test/ioerr5.test b/components/external/SQLite-3.8.1/test/ioerr5.test new file mode 100644 index 0000000000000000000000000000000000000000..a430f534074207047eaf7c8ad1af10adf1850173 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/ioerr5.test @@ -0,0 +1,216 @@ +# 2008 May 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests that if sqlite3_release_memory() is called to reclaim +# memory from a pager that is in the error-state, SQLite does not +# incorrectly write dirty pages out to the database (not safe to do +# once the pager is in error state). +# +# $Id: ioerr5.test,v 1.5 2008/08/28 18:35:34 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !memorymanage||!shared_cache { + finish_test + return +} + +db close + +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] +set ::soft_limit [sqlite3_soft_heap_limit 1048576] + +# This procedure prepares, steps and finalizes an SQL statement via the +# UTF-16 APIs. The text representation of an SQLite error code is returned +# ("SQLITE_OK", "SQLITE_IOERR" etc.). The actual results returned by the +# SQL statement, if it is a SELECT, are not available. +# +# This can be useful for testing because it forces SQLite to make an extra +# call to sqlite3_malloc() when translating from the supplied UTF-16 to +# the UTF-8 encoding used internally. +# +proc dosql16 {zSql {db db}} { + set sql [encoding convertto unicode $zSql] + append sql "\00\00" + set stmt [sqlite3_prepare16 $db $sql -1 {}] + sqlite3_step $stmt + set rc [sqlite3_finalize $stmt] +} + +proc compilesql16 {zSql {db db}} { + set sql [encoding convertto unicode $zSql] + append sql "\00\00" + set stmt [sqlite3_prepare16 $db $sql -1 {}] + set rc [sqlite3_finalize $stmt] +} + +# Open two database connections (handle db and db2) to database "test.db". +# +proc opendatabases {} { + catch {db close} + catch {db2 close} + sqlite3 db test.db + sqlite3 db2 test.db + db2 cache size 0 + db cache size 0 + execsql { + pragma page_size=512; + pragma auto_vacuum=2; + pragma cache_size=16; + } +} + +# Open two database connections and create a single table in the db. +# +do_test ioerr5-1.0 { + opendatabases + execsql { CREATE TABLE A(Id INTEGER, Name TEXT) } +} {} + +foreach locking_mode {normal exclusive} { + set nPage 2 + for {set iFail 1} {$iFail<200} {incr iFail} { + sqlite3_soft_heap_limit 1048576 + opendatabases + execsql { pragma locking_mode=exclusive } + set nRow [db one {SELECT count(*) FROM a}] + + # Dirty (at least) one of the pages in the cache. + do_test ioerr5-1.$locking_mode-$iFail.1 { + execsql { + BEGIN EXCLUSIVE; + INSERT INTO a VALUES(1, 'ABCDEFGHIJKLMNOP'); + } + } {} + + # Open a read-only cursor on table "a". If the COMMIT below is + # interrupted by a persistent IO error, the pager will transition to + # PAGER_ERROR state. If there are no other read-only cursors open, + # from there the pager immediately discards all cached data and + # switches to PAGER_OPEN state. This read-only cursor stops that + # from happening, leaving the pager stuck in PAGER_ERROR state. + # + set channel [db incrblob -readonly a Name [db last_insert_rowid]] + + # Now try to commit the transaction. Cause an IO error to occur + # within this operation, which moves the pager into the error state. + # + set ::sqlite_io_error_persist 1 + set ::sqlite_io_error_pending $iFail + do_test ioerr5-1.$locking_mode-$iFail.2 { + set rc [catchsql {COMMIT}] + list + } {} + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_persist 0 + set ::sqlite_io_error_pending 0 + + # Read the contents of the database file into a Tcl variable. + # + set fd [open test.db] + fconfigure $fd -translation binary -encoding binary + set zDatabase [read $fd] + close $fd + + # Set a very low soft-limit and then try to compile an SQL statement + # from UTF-16 text. To do this, SQLite will need to reclaim memory + # from the pager that is in error state. Including that associated + # with the dirty page. + # + do_test ioerr5-1.$locking_mode-$iFail.3 { + sqlite3_soft_heap_limit 1024 + compilesql16 "SELECT 10" + } {SQLITE_OK} + + close $channel + + # Ensure that nothing was written to the database while reclaiming + # memory from the pager in error state. + # + do_test ioerr5-1.$locking_mode-$iFail.4 { + set fd [open test.db] + fconfigure $fd -translation binary -encoding binary + set zDatabase2 [read $fd] + close $fd + expr {$zDatabase eq $zDatabase2} + } {1} + + if {$rc eq [list 0 {}]} { + do_test ioerr5.1-$locking_mode-$iFail.3 { + execsql { SELECT count(*) FROM a } + } [expr $nRow+1] + break + } + } +} + +# Make sure this test script doesn't leave any files open. +# +do_test ioerr5-1.X { + catch { db close } + catch { db2 close } + set sqlite_open_file_count +} 0 + +do_test ioerr5-2.0 { + sqlite3 db test.db + execsql { CREATE INDEX i1 ON a(id, name); } +} {} + +foreach locking_mode {exclusive normal} { + for {set iFail 1} {$iFail<200} {incr iFail} { + sqlite3_soft_heap_limit 1048576 + opendatabases + execsql { pragma locking_mode=exclusive } + set nRow [db one {SELECT count(*) FROM a}] + + do_test ioerr5-2.$locking_mode-$iFail.1 { + execsql { + BEGIN EXCLUSIVE; + INSERT INTO a VALUES(1, 'ABCDEFGHIJKLMNOP'); + } + } {} + + set ::sqlite_io_error_persist 1 + set ::sqlite_io_error_pending $iFail + + sqlite3_release_memory 10000 + + set error_hit $::sqlite_io_error_hit + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_persist 0 + set ::sqlite_io_error_pending 0 + if {$error_hit} { + do_test ioerr5-2.$locking_mode-$iFail.3a { + catchsql COMMIT + } {1 {disk I/O error}} + } else { + do_test ioerr5-2.$locking_mode-$iFail.3b { + execsql COMMIT + } {} + break + } + } +} + +# Make sure this test script doesn't leave any files open. +# +do_test ioerr5-2.X { + catch { db close } + catch { db2 close } + set sqlite_open_file_count +} 0 + +sqlite3_enable_shared_cache $::enable_shared_cache +sqlite3_soft_heap_limit $::soft_limit + +finish_test diff --git a/components/external/SQLite-3.8.1/test/ioerr6.test b/components/external/SQLite-3.8.1/test/ioerr6.test new file mode 100644 index 0000000000000000000000000000000000000000..d1847b2877b71e439be717d2987b3e332795b3b9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/ioerr6.test @@ -0,0 +1,91 @@ +# 2012 December 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +set ::testprefix ioerr6 + +ifcapable !atomicwrite { + puts "skipping tests - not compiled with SQLITE_ENABLE_ATOMIC_WRITE..." + finish_test + return +} + +if {[permutation]=="inmemory_journal"} { + # These tests will not work with in-memory journals (as persistent VFS + # errors commencing after a transaction has started to write to the db + # cannot be recovered from). + finish_test + return +} + +faultsim_save_and_close + +do_test 1.1 { + testvfs shmfault -default true + shmfault devchar atomic + sqlite3 db test.db + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(2, 4); + INSERT INTO t1 VALUES(3, 6); + INSERT INTO t1 VALUES(4, 8); + } + + # Cause the first call to xWrite() to fail with SQLITE_FULL. + shmfault full 2 1 + catchsql { INSERT INTO t1 VALUES(5, 10) } +} {1 {database or disk is full}} + +do_test 1.2 { + execsql { PRAGMA integrity_check } +} {ok} + +db close +shmfault delete + +do_faultsim_test 2 -faults full* -prep { + shmfault devchar atomic + faultsim_restore + sqlite3 db test.db +} -body { + db eval { + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES('abc'); + } +} -test { + set res [db one { PRAGMA integrity_check }] + if {$res != "ok"} { + error "integrity check: $res" + } +} + +do_faultsim_test 3 -faults full* -prep { + shmfault devchar atomic + faultsim_restore + sqlite3 db test.db +} -body { + db eval { + CREATE TABLE t1(x); + CREATE TABLE t2(x); + } +} -test { + db eval { CREATE TABLE t3(x) } + if {[db one { PRAGMA integrity_check }] != "ok"} { + error "integrity check failed" + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/join.test b/components/external/SQLite-3.8.1/test/join.test new file mode 100644 index 0000000000000000000000000000000000000000..88ac04f950a0ab88ed40e4f5ec5c816126c62e95 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/join.test @@ -0,0 +1,644 @@ +# 2002 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for joins, including outer joins. +# +# $Id: join.test,v 1.27 2009/07/01 16:12:08 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test join-1.1 { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(2,3,4); + INSERT INTO t1 VALUES(3,4,5); + SELECT * FROM t1; + } +} {1 2 3 2 3 4 3 4 5} +do_test join-1.2 { + execsql { + CREATE TABLE t2(b,c,d); + INSERT INTO t2 VALUES(1,2,3); + INSERT INTO t2 VALUES(2,3,4); + INSERT INTO t2 VALUES(3,4,5); + SELECT * FROM t2; + } +} {1 2 3 2 3 4 3 4 5} + +do_test join-1.3 { + execsql2 { + SELECT * FROM t1 NATURAL JOIN t2; + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test join-1.3.1 { + execsql2 { + SELECT * FROM t2 NATURAL JOIN t1; + } +} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2} +do_test join-1.3.2 { + execsql2 { + SELECT * FROM t2 AS x NATURAL JOIN t1; + } +} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2} +do_test join-1.3.3 { + execsql2 { + SELECT * FROM t2 NATURAL JOIN t1 AS y; + } +} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2} +do_test join-1.3.4 { + execsql { + SELECT b FROM t1 NATURAL JOIN t2; + } +} {2 3} + +# ticket #3522 +do_test join-1.3.5 { + execsql2 { + SELECT t2.* FROM t2 NATURAL JOIN t1 + } +} {b 2 c 3 d 4 b 3 c 4 d 5} +do_test join-1.3.6 { + execsql2 { + SELECT xyzzy.* FROM t2 AS xyzzy NATURAL JOIN t1 + } +} {b 2 c 3 d 4 b 3 c 4 d 5} +do_test join-1.3.7 { + execsql2 { + SELECT t1.* FROM t2 NATURAL JOIN t1 + } +} {a 1 b 2 c 3 a 2 b 3 c 4} +do_test join-1.3.8 { + execsql2 { + SELECT xyzzy.* FROM t2 NATURAL JOIN t1 AS xyzzy + } +} {a 1 b 2 c 3 a 2 b 3 c 4} +do_test join-1.3.9 { + execsql2 { + SELECT aaa.*, bbb.* FROM t2 AS aaa NATURAL JOIN t1 AS bbb + } +} {b 2 c 3 d 4 a 1 b 2 c 3 b 3 c 4 d 5 a 2 b 3 c 4} +do_test join-1.3.10 { + execsql2 { + SELECT t1.*, t2.* FROM t2 NATURAL JOIN t1 + } +} {a 1 b 2 c 3 b 2 c 3 d 4 a 2 b 3 c 4 b 3 c 4 d 5} + + +do_test join-1.4.1 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 USING(b,c); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test join-1.4.2 { + execsql2 { + SELECT * FROM t1 AS x INNER JOIN t2 USING(b,c); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test join-1.4.3 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 AS y USING(b,c); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test join-1.4.4 { + execsql2 { + SELECT * FROM t1 AS x INNER JOIN t2 AS y USING(b,c); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test join-1.4.5 { + execsql { + SELECT b FROM t1 JOIN t2 USING(b); + } +} {2 3} + +# Ticket #3522 +do_test join-1.4.6 { + execsql2 { + SELECT t1.* FROM t1 JOIN t2 USING(b); + } +} {a 1 b 2 c 3 a 2 b 3 c 4} +do_test join-1.4.7 { + execsql2 { + SELECT t2.* FROM t1 JOIN t2 USING(b); + } +} {b 2 c 3 d 4 b 3 c 4 d 5} + +do_test join-1.5 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 USING(b); + } +} {a 1 b 2 c 3 c 3 d 4 a 2 b 3 c 4 c 4 d 5} +do_test join-1.6 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 USING(c); + } +} {a 1 b 2 c 3 b 2 d 4 a 2 b 3 c 4 b 3 d 5} +do_test join-1.7 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 USING(c,b); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} + +do_test join-1.8 { + execsql { + SELECT * FROM t1 NATURAL CROSS JOIN t2; + } +} {1 2 3 4 2 3 4 5} +do_test join-1.9 { + execsql { + SELECT * FROM t1 CROSS JOIN t2 USING(b,c); + } +} {1 2 3 4 2 3 4 5} +do_test join-1.10 { + execsql { + SELECT * FROM t1 NATURAL INNER JOIN t2; + } +} {1 2 3 4 2 3 4 5} +do_test join-1.11 { + execsql { + SELECT * FROM t1 INNER JOIN t2 USING(b,c); + } +} {1 2 3 4 2 3 4 5} +do_test join-1.12 { + execsql { + SELECT * FROM t1 natural inner join t2; + } +} {1 2 3 4 2 3 4 5} + +ifcapable subquery { + do_test join-1.13 { + execsql2 { + SELECT * FROM t1 NATURAL JOIN + (SELECT b as 'c', c as 'd', d as 'e' FROM t2) as t3 + } + } {a 1 b 2 c 3 d 4 e 5} + do_test join-1.14 { + execsql2 { + SELECT * FROM (SELECT b as 'c', c as 'd', d as 'e' FROM t2) as 'tx' + NATURAL JOIN t1 + } + } {c 3 d 4 e 5 a 1 b 2} +} + +do_test join-1.15 { + execsql { + CREATE TABLE t3(c,d,e); + INSERT INTO t3 VALUES(2,3,4); + INSERT INTO t3 VALUES(3,4,5); + INSERT INTO t3 VALUES(4,5,6); + SELECT * FROM t3; + } +} {2 3 4 3 4 5 4 5 6} +do_test join-1.16 { + execsql { + SELECT * FROM t1 natural join t2 natural join t3; + } +} {1 2 3 4 5 2 3 4 5 6} +do_test join-1.17 { + execsql2 { + SELECT * FROM t1 natural join t2 natural join t3; + } +} {a 1 b 2 c 3 d 4 e 5 a 2 b 3 c 4 d 5 e 6} +do_test join-1.18 { + execsql { + CREATE TABLE t4(d,e,f); + INSERT INTO t4 VALUES(2,3,4); + INSERT INTO t4 VALUES(3,4,5); + INSERT INTO t4 VALUES(4,5,6); + SELECT * FROM t4; + } +} {2 3 4 3 4 5 4 5 6} +do_test join-1.19.1 { + execsql { + SELECT * FROM t1 natural join t2 natural join t4; + } +} {1 2 3 4 5 6} +do_test join-1.19.2 { + execsql2 { + SELECT * FROM t1 natural join t2 natural join t4; + } +} {a 1 b 2 c 3 d 4 e 5 f 6} +do_test join-1.20 { + execsql { + SELECT * FROM t1 natural join t2 natural join t3 WHERE t1.a=1 + } +} {1 2 3 4 5} + +do_test join-2.1 { + execsql { + SELECT * FROM t1 NATURAL LEFT JOIN t2; + } +} {1 2 3 4 2 3 4 5 3 4 5 {}} + +# ticket #3522 +do_test join-2.1.1 { + execsql2 { + SELECT * FROM t1 NATURAL LEFT JOIN t2; + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5 a 3 b 4 c 5 d {}} +do_test join-2.1.2 { + execsql2 { + SELECT t1.* FROM t1 NATURAL LEFT JOIN t2; + } +} {a 1 b 2 c 3 a 2 b 3 c 4 a 3 b 4 c 5} +do_test join-2.1.3 { + execsql2 { + SELECT t2.* FROM t1 NATURAL LEFT JOIN t2; + } +} {b 2 c 3 d 4 b 3 c 4 d 5 b {} c {} d {}} + +do_test join-2.2 { + execsql { + SELECT * FROM t2 NATURAL LEFT OUTER JOIN t1; + } +} {1 2 3 {} 2 3 4 1 3 4 5 2} +do_test join-2.3 { + catchsql { + SELECT * FROM t1 NATURAL RIGHT OUTER JOIN t2; + } +} {1 {RIGHT and FULL OUTER JOINs are not currently supported}} +do_test join-2.4 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d + } +} {1 2 3 {} {} {} 2 3 4 {} {} {} 3 4 5 1 2 3} +do_test join-2.5 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d WHERE t1.a>1 + } +} {2 3 4 {} {} {} 3 4 5 1 2 3} +do_test join-2.6 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d WHERE t2.b IS NULL OR t2.b>1 + } +} {1 2 3 {} {} {} 2 3 4 {} {} {}} + +do_test join-3.1 { + catchsql { + SELECT * FROM t1 NATURAL JOIN t2 ON t1.a=t2.b; + } +} {1 {a NATURAL join may not have an ON or USING clause}} +do_test join-3.2 { + catchsql { + SELECT * FROM t1 NATURAL JOIN t2 USING(b); + } +} {1 {a NATURAL join may not have an ON or USING clause}} +do_test join-3.3 { + catchsql { + SELECT * FROM t1 JOIN t2 ON t1.a=t2.b USING(b); + } +} {1 {cannot have both ON and USING clauses in the same join}} +do_test join-3.4.1 { + catchsql { + SELECT * FROM t1 JOIN t2 USING(a); + } +} {1 {cannot join using column a - column not present in both tables}} +do_test join-3.4.2 { + catchsql { + SELECT * FROM t1 JOIN t2 USING(d); + } +} {1 {cannot join using column d - column not present in both tables}} +do_test join-3.5 { + catchsql { SELECT * FROM t1 USING(a) } +} {1 {a JOIN clause is required before USING}} +do_test join-3.6 { + catchsql { + SELECT * FROM t1 JOIN t2 ON t3.a=t2.b; + } +} {1 {no such column: t3.a}} +do_test join-3.7 { + catchsql { + SELECT * FROM t1 INNER OUTER JOIN t2; + } +} {1 {unknown or unsupported join type: INNER OUTER}} +do_test join-3.8 { + catchsql { + SELECT * FROM t1 INNER OUTER CROSS JOIN t2; + } +} {1 {unknown or unsupported join type: INNER OUTER CROSS}} +do_test join-3.9 { + catchsql { + SELECT * FROM t1 OUTER NATURAL INNER JOIN t2; + } +} {1 {unknown or unsupported join type: OUTER NATURAL INNER}} +do_test join-3.10 { + catchsql { + SELECT * FROM t1 LEFT BOGUS JOIN t2; + } +} {1 {unknown or unsupported join type: LEFT BOGUS}} +do_test join-3.11 { + catchsql { + SELECT * FROM t1 INNER BOGUS CROSS JOIN t2; + } +} {1 {unknown or unsupported join type: INNER BOGUS CROSS}} +do_test join-3.12 { + catchsql { + SELECT * FROM t1 NATURAL AWK SED JOIN t2; + } +} {1 {unknown or unsupported join type: NATURAL AWK SED}} + +do_test join-4.1 { + execsql { + BEGIN; + CREATE TABLE t5(a INTEGER PRIMARY KEY); + CREATE TABLE t6(a INTEGER); + INSERT INTO t6 VALUES(NULL); + INSERT INTO t6 VALUES(NULL); + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + COMMIT; + } + execsql { + SELECT * FROM t6 NATURAL JOIN t5; + } +} {} +do_test join-4.2 { + execsql { + SELECT * FROM t6, t5 WHERE t6.at5.a; + } +} {} +do_test join-4.4 { + execsql { + UPDATE t6 SET a='xyz'; + SELECT * FROM t6 NATURAL JOIN t5; + } +} {} +do_test join-4.6 { + execsql { + SELECT * FROM t6, t5 WHERE t6.at5.a; + } +} {} +do_test join-4.8 { + execsql { + UPDATE t6 SET a=1; + SELECT * FROM t6 NATURAL JOIN t5; + } +} {} +do_test join-4.9 { + execsql { + SELECT * FROM t6, t5 WHERE t6.at5.a; + } +} {} + +do_test join-5.1 { + execsql { + BEGIN; + create table centros (id integer primary key, centro); + INSERT INTO centros VALUES(1,'xxx'); + create table usuarios (id integer primary key, nombre, apellidos, + idcentro integer); + INSERT INTO usuarios VALUES(1,'a','aa',1); + INSERT INTO usuarios VALUES(2,'b','bb',1); + INSERT INTO usuarios VALUES(3,'c','cc',NULL); + create index idcentro on usuarios (idcentro); + END; + select usuarios.id, usuarios.nombre, centros.centro from + usuarios left outer join centros on usuarios.idcentro = centros.id; + } +} {1 a xxx 2 b xxx 3 c {}} + +# A test for ticket #247. +# +do_test join-7.1 { + execsql { + CREATE TABLE t7 (x, y); + INSERT INTO t7 VALUES ("pa1", 1); + INSERT INTO t7 VALUES ("pa2", NULL); + INSERT INTO t7 VALUES ("pa3", NULL); + INSERT INTO t7 VALUES ("pa4", 2); + INSERT INTO t7 VALUES ("pa30", 131); + INSERT INTO t7 VALUES ("pa31", 130); + INSERT INTO t7 VALUES ("pa28", NULL); + + CREATE TABLE t8 (a integer primary key, b); + INSERT INTO t8 VALUES (1, "pa1"); + INSERT INTO t8 VALUES (2, "pa4"); + INSERT INTO t8 VALUES (3, NULL); + INSERT INTO t8 VALUES (4, NULL); + INSERT INTO t8 VALUES (130, "pa31"); + INSERT INTO t8 VALUES (131, "pa30"); + + SELECT coalesce(t8.a,999) from t7 LEFT JOIN t8 on y=a; + } +} {1 999 999 2 131 130 999} + +# Make sure a left join where the right table is really a view that +# is itself a join works right. Ticket #306. +# +ifcapable view { +do_test join-8.1 { + execsql { + BEGIN; + CREATE TABLE t9(a INTEGER PRIMARY KEY, b); + INSERT INTO t9 VALUES(1,11); + INSERT INTO t9 VALUES(2,22); + CREATE TABLE t10(x INTEGER PRIMARY KEY, y); + INSERT INTO t10 VALUES(1,2); + INSERT INTO t10 VALUES(3,3); + CREATE TABLE t11(p INTEGER PRIMARY KEY, q); + INSERT INTO t11 VALUES(2,111); + INSERT INTO t11 VALUES(3,333); + CREATE VIEW v10_11 AS SELECT x, q FROM t10, t11 WHERE t10.y=t11.p; + COMMIT; + SELECT * FROM t9 LEFT JOIN v10_11 ON( a=x ); + } +} {1 11 1 111 2 22 {} {}} +ifcapable subquery { + do_test join-8.2 { + execsql { + SELECT * FROM t9 LEFT JOIN (SELECT x, q FROM t10, t11 WHERE t10.y=t11.p) + ON( a=x); + } + } {1 11 1 111 2 22 {} {}} +} +do_test join-8.3 { + execsql { + SELECT * FROM v10_11 LEFT JOIN t9 ON( a=x ); + } +} {1 111 1 11 3 333 {} {}} +ifcapable subquery { + # Constant expressions in a subquery that is the right element of a + # LEFT JOIN evaluate to NULL for rows where the LEFT JOIN does not + # match. Ticket #3300 + do_test join-8.4 { + execsql { + SELECT * FROM t9 LEFT JOIN (SELECT 44, p, q FROM t11) AS sub1 ON p=a + } + } {1 11 {} {} {} 2 22 44 2 111} +} +} ;# ifcapable view + +# Ticket #350 describes a scenario where LEFT OUTER JOIN does not +# function correctly if the right table in the join is really +# subquery. +# +# To test the problem, we generate the same LEFT OUTER JOIN in two +# separate selects but with on using a subquery and the other calling +# the table directly. Then connect the two SELECTs using an EXCEPT. +# Both queries should generate the same results so the answer should +# be an empty set. +# +ifcapable compound { +do_test join-9.1 { + execsql { + BEGIN; + CREATE TABLE t12(a,b); + INSERT INTO t12 VALUES(1,11); + INSERT INTO t12 VALUES(2,22); + CREATE TABLE t13(b,c); + INSERT INTO t13 VALUES(22,222); + COMMIT; + } +} {} + +ifcapable subquery { + do_test join-9.1.1 { + execsql { + SELECT * FROM t12 NATURAL LEFT JOIN t13 + EXCEPT + SELECT * FROM t12 NATURAL LEFT JOIN (SELECT * FROM t13 WHERE b>0); + } + } {} +} +ifcapable view { + do_test join-9.2 { + execsql { + CREATE VIEW v13 AS SELECT * FROM t13 WHERE b>0; + SELECT * FROM t12 NATURAL LEFT JOIN t13 + EXCEPT + SELECT * FROM t12 NATURAL LEFT JOIN v13; + } + } {} +} ;# ifcapable view +} ;# ifcapable compound + +ifcapable subquery { + # Ticket #1697: Left Join WHERE clause terms that contain an + # aggregate subquery. + # + do_test join-10.1 { + execsql { + CREATE TABLE t21(a,b,c); + CREATE TABLE t22(p,q); + CREATE INDEX i22 ON t22(q); + SELECT a FROM t21 LEFT JOIN t22 ON b=p WHERE q= + (SELECT max(m.q) FROM t22 m JOIN t21 n ON n.b=m.p WHERE n.c=1); + } + } {} + + # Test a LEFT JOIN when the right-hand side of hte join is an empty + # sub-query. Seems fine. + # + do_test join-10.2 { + execsql { + CREATE TABLE t23(a, b, c); + CREATE TABLE t24(a, b, c); + INSERT INTO t23 VALUES(1, 2, 3); + } + execsql { + SELECT * FROM t23 LEFT JOIN t24; + } + } {1 2 3 {} {} {}} + do_test join-10.3 { + execsql { + SELECT * FROM t23 LEFT JOIN (SELECT * FROM t24); + } + } {1 2 3 {} {} {}} + +} ;# ifcapable subquery + +#------------------------------------------------------------------------- +# The following tests are to ensure that bug b73fb0bd64 is fixed. +# +do_test join-11.1 { + drop_all_tables + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT); + CREATE TABLE t2(a INTEGER PRIMARY KEY, b TEXT); + INSERT INTO t1 VALUES(1,'abc'); + INSERT INTO t1 VALUES(2,'def'); + INSERT INTO t2 VALUES(1,'abc'); + INSERT INTO t2 VALUES(2,'def'); + SELECT * FROM t1 NATURAL JOIN t2; + } +} {1 abc 2 def} + +do_test join-11.2 { + execsql { SELECT a FROM t1 JOIN t1 USING (a)} +} {1 2} +do_test join-11.3 { + execsql { SELECT a FROM t1 JOIN t1 AS t2 USING (a)} +} {1 2} +do_test join-11.3 { + execsql { SELECT * FROM t1 NATURAL JOIN t1 AS t2} +} {1 abc 2 def} +do_test join-11.4 { + execsql { SELECT * FROM t1 NATURAL JOIN t1 } +} {1 abc 2 def} + +do_test join-11.5 { + drop_all_tables + execsql { + CREATE TABLE t1(a COLLATE nocase, b); + CREATE TABLE t2(a, b); + INSERT INTO t1 VALUES('ONE', 1); + INSERT INTO t1 VALUES('two', 2); + INSERT INTO t2 VALUES('one', 1); + INSERT INTO t2 VALUES('two', 2); + } +} {} +do_test join-11.6 { + execsql { SELECT * FROM t1 NATURAL JOIN t2 } +} {ONE 1 two 2} +do_test join-11.7 { + execsql { SELECT * FROM t2 NATURAL JOIN t1 } +} {two 2} + +do_test join-11.8 { + drop_all_tables + execsql { + CREATE TABLE t1(a, b TEXT); + CREATE TABLE t2(b INTEGER, a); + INSERT INTO t1 VALUES('one', '1.0'); + INSERT INTO t1 VALUES('two', '2'); + INSERT INTO t2 VALUES(1, 'one'); + INSERT INTO t2 VALUES(2, 'two'); + } +} {} +do_test join-11.9 { + execsql { SELECT * FROM t1 NATURAL JOIN t2 } +} {one 1.0 two 2} +do_test join-11.10 { + execsql { SELECT * FROM t2 NATURAL JOIN t1 } +} {1 one 2 two} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/join2.test b/components/external/SQLite-3.8.1/test/join2.test new file mode 100644 index 0000000000000000000000000000000000000000..0f558c5a3df6dc027c3c0c54a06d6927cd98528f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/join2.test @@ -0,0 +1,75 @@ +# 2002 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for joins, including outer joins. +# +# $Id: join2.test,v 1.2 2005/01/21 03:12:16 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test join2-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,11); + INSERT INTO t1 VALUES(2,22); + INSERT INTO t1 VALUES(3,33); + SELECT * FROM t1; + } +} {1 11 2 22 3 33} +do_test join2-1.2 { + execsql { + CREATE TABLE t2(b,c); + INSERT INTO t2 VALUES(11,111); + INSERT INTO t2 VALUES(33,333); + INSERT INTO t2 VALUES(44,444); + SELECT * FROM t2; + } +} {11 111 33 333 44 444}; +do_test join2-1.3 { + execsql { + CREATE TABLE t3(c,d); + INSERT INTO t3 VALUES(111,1111); + INSERT INTO t3 VALUES(444,4444); + INSERT INTO t3 VALUES(555,5555); + SELECT * FROM t3; + } +} {111 1111 444 4444 555 5555} + +do_test join2-1.4 { + execsql { + SELECT * FROM + t1 NATURAL JOIN t2 NATURAL JOIN t3 + } +} {1 11 111 1111} +do_test join2-1.5 { + execsql { + SELECT * FROM + t1 NATURAL JOIN t2 NATURAL LEFT OUTER JOIN t3 + } +} {1 11 111 1111 3 33 333 {}} +do_test join2-1.6 { + execsql { + SELECT * FROM + t1 NATURAL LEFT OUTER JOIN t2 NATURAL JOIN t3 + } +} {1 11 111 1111} +ifcapable subquery { + do_test join2-1.7 { + execsql { + SELECT * FROM + t1 NATURAL LEFT OUTER JOIN (t2 NATURAL JOIN t3) + } + } {1 11 111 1111 2 22 {} {} 3 33 {} {}} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/join3.test b/components/external/SQLite-3.8.1/test/join3.test new file mode 100644 index 0000000000000000000000000000000000000000..f1c273d1d0060f1adccd7cac432dd62390fe74d7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/join3.test @@ -0,0 +1,62 @@ +# 2002 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for joins, including outer joins, where +# there are a large number of tables involved in the join. +# +# $Id: join3.test,v 1.4 2005/01/19 23:24:51 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# An unrestricted join +# +catch {unset ::result} +set result {} +for {set N 1} {$N<=$bitmask_size} {incr N} { + lappend result $N + do_test join3-1.$N { + execsql "CREATE TABLE t${N}(x);" + execsql "INSERT INTO t$N VALUES($N)" + set sql "SELECT * FROM t1" + for {set i 2} {$i<=$N} {incr i} {append sql ", t$i"} + execsql $sql + } $result +} + +# Joins with a comparison +# +set result {} +for {set N 1} {$N<=$bitmask_size} {incr N} { + lappend result $N + do_test join3-2.$N { + set sql "SELECT * FROM t1" + for {set i 2} {$i<=$N} {incr i} {append sql ", t$i"} + set sep WHERE + for {set i 1} {$i<$N} {incr i} { + append sql " $sep t[expr {$i+1}].x==t$i.x+1" + set sep AND + } + execsql $sql + } $result +} + +# Error of too many tables in the join +# +do_test join3-3.1 { + set sql "SELECT * FROM t1 AS t0, t1" + for {set i 2} {$i<=$bitmask_size} {incr i} {append sql ", t$i"} + catchsql $sql +} [list 1 "at most $bitmask_size tables in a join"] + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/join4.test b/components/external/SQLite-3.8.1/test/join4.test new file mode 100644 index 0000000000000000000000000000000000000000..77db25ffb02827137d204a5736be9ff915dad686 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/join4.test @@ -0,0 +1,98 @@ +# 2002 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for left outer joins containing WHERE +# clauses that restrict the scope of the left term of the join. +# +# $Id: join4.test,v 1.4 2005/03/29 03:11:00 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable tempdb { + do_test join4-1.1 { + execsql { + create temp table t1(a integer, b varchar(10)); + insert into t1 values(1,'one'); + insert into t1 values(2,'two'); + insert into t1 values(3,'three'); + insert into t1 values(4,'four'); + + create temp table t2(x integer, y varchar(10), z varchar(10)); + insert into t2 values(2,'niban','ok'); + insert into t2 values(4,'yonban','err'); + } + execsql { + select * from t1 left outer join t2 on t1.a=t2.x where t2.z='ok' + } + } {2 two 2 niban ok} +} else { + do_test join4-1.1 { + execsql { + create table t1(a integer, b varchar(10)); + insert into t1 values(1,'one'); + insert into t1 values(2,'two'); + insert into t1 values(3,'three'); + insert into t1 values(4,'four'); + + create table t2(x integer, y varchar(10), z varchar(10)); + insert into t2 values(2,'niban','ok'); + insert into t2 values(4,'yonban','err'); + } + execsql { + select * from t1 left outer join t2 on t1.a=t2.x where t2.z='ok' + } + } {2 two 2 niban ok} +} +do_test join4-1.2 { + execsql { + select * from t1 left outer join t2 on t1.a=t2.x and t2.z='ok' + } +} {1 one {} {} {} 2 two 2 niban ok 3 three {} {} {} 4 four {} {} {}} +do_test join4-1.3 { + execsql { + create index i2 on t2(z); + } + execsql { + select * from t1 left outer join t2 on t1.a=t2.x where t2.z='ok' + } +} {2 two 2 niban ok} +do_test join4-1.4 { + execsql { + select * from t1 left outer join t2 on t1.a=t2.x and t2.z='ok' + } +} {1 one {} {} {} 2 two 2 niban ok 3 three {} {} {} 4 four {} {} {}} +do_test join4-1.5 { + execsql { + select * from t1 left outer join t2 on t1.a=t2.x where t2.z>='ok' + } +} {2 two 2 niban ok} +do_test join4-1.4 { + execsql { + select * from t1 left outer join t2 on t1.a=t2.x and t2.z>='ok' + } +} {1 one {} {} {} 2 two 2 niban ok 3 three {} {} {} 4 four {} {} {}} +ifcapable subquery { + do_test join4-1.6 { + execsql { + select * from t1 left outer join t2 on t1.a=t2.x where t2.z IN ('ok') + } + } {2 two 2 niban ok} + do_test join4-1.7 { + execsql { + select * from t1 left outer join t2 on t1.a=t2.x and t2.z IN ('ok') + } + } {1 one {} {} {} 2 two 2 niban ok 3 three {} {} {} 4 four {} {} {}} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/join5.test b/components/external/SQLite-3.8.1/test/join5.test new file mode 100644 index 0000000000000000000000000000000000000000..45d8a31596acaab568295adb19db845d661b98ae --- /dev/null +++ b/components/external/SQLite-3.8.1/test/join5.test @@ -0,0 +1,110 @@ +# 2005 September 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for left outer joins containing ON +# clauses that restrict the scope of the left term of the join. +# +# $Id: join5.test,v 1.2 2007/06/08 00:20:48 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +do_test join5-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a integer primary key, b integer, c integer); + CREATE TABLE t2(x integer primary key, y); + CREATE TABLE t3(p integer primary key, q); + INSERT INTO t3 VALUES(11,'t3-11'); + INSERT INTO t3 VALUES(12,'t3-12'); + INSERT INTO t2 VALUES(11,'t2-11'); + INSERT INTO t2 VALUES(12,'t2-12'); + INSERT INTO t1 VALUES(1, 5, 0); + INSERT INTO t1 VALUES(2, 11, 2); + INSERT INTO t1 VALUES(3, 12, 1); + COMMIT; + } +} {} +do_test join5-1.2 { + execsql { + select * from t1 left join t2 on t1.b=t2.x and t1.c=1 + } +} {1 5 0 {} {} 2 11 2 {} {} 3 12 1 12 t2-12} +do_test join5-1.3 { + execsql { + select * from t1 left join t2 on t1.b=t2.x where t1.c=1 + } +} {3 12 1 12 t2-12} +do_test join5-1.4 { + execsql { + select * from t1 left join t2 on t1.b=t2.x and t1.c=1 + left join t3 on t1.b=t3.p and t1.c=2 + } +} {1 5 0 {} {} {} {} 2 11 2 {} {} 11 t3-11 3 12 1 12 t2-12 {} {}} +do_test join5-1.5 { + execsql { + select * from t1 left join t2 on t1.b=t2.x and t1.c=1 + left join t3 on t1.b=t3.p where t1.c=2 + } +} {2 11 2 {} {} 11 t3-11} + +# Ticket #2403 +# +do_test join5-2.1 { + execsql { + CREATE TABLE ab(a,b); + INSERT INTO "ab" VALUES(1,2); + INSERT INTO "ab" VALUES(3,NULL); + + CREATE TABLE xy(x,y); + INSERT INTO "xy" VALUES(2,3); + INSERT INTO "xy" VALUES(NULL,1); + } + execsql {SELECT * FROM xy LEFT JOIN ab ON 0} +} {2 3 {} {} {} 1 {} {}} +do_test join5-2.2 { + execsql {SELECT * FROM xy LEFT JOIN ab ON 1} +} {2 3 1 2 2 3 3 {} {} 1 1 2 {} 1 3 {}} +do_test join5-2.3 { + execsql {SELECT * FROM xy LEFT JOIN ab ON NULL} +} {2 3 {} {} {} 1 {} {}} +do_test join5-2.4 { + execsql {SELECT * FROM xy LEFT JOIN ab ON 0 WHERE 0} +} {} +do_test join5-2.5 { + execsql {SELECT * FROM xy LEFT JOIN ab ON 1 WHERE 0} +} {} +do_test join5-2.6 { + execsql {SELECT * FROM xy LEFT JOIN ab ON NULL WHERE 0} +} {} +do_test join5-2.7 { + execsql {SELECT * FROM xy LEFT JOIN ab ON 0 WHERE 1} +} {2 3 {} {} {} 1 {} {}} +do_test join5-2.8 { + execsql {SELECT * FROM xy LEFT JOIN ab ON 1 WHERE 1} +} {2 3 1 2 2 3 3 {} {} 1 1 2 {} 1 3 {}} +do_test join5-2.9 { + execsql {SELECT * FROM xy LEFT JOIN ab ON NULL WHERE 1} +} {2 3 {} {} {} 1 {} {}} +do_test join5-2.10 { + execsql {SELECT * FROM xy LEFT JOIN ab ON 0 WHERE NULL} +} {} +do_test join5-2.11 { + execsql {SELECT * FROM xy LEFT JOIN ab ON 1 WHERE NULL} +} {} +do_test join5-2.12 { + execsql {SELECT * FROM xy LEFT JOIN ab ON NULL WHERE NULL} +} {} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/join6.test b/components/external/SQLite-3.8.1/test/join6.test new file mode 100644 index 0000000000000000000000000000000000000000..7fbf508e57f6ab6bb25eabcc77826fb3c5380d1b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/join6.test @@ -0,0 +1,160 @@ +# 2009 December 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for N-way joins (N>2) which make +# use of USING or NATURAL JOIN. For such joins, the USING and +# NATURAL JOIN processing needs to search all tables to the left +# of the join looking for a match. See ticket [f74beaabde] +# for additional information. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +# The problem as initially reported on the mailing list: +# +do_test join6-1.1 { + execsql { + CREATE TABLE t1(a); + CREATE TABLE t2(a); + CREATE TABLE t3(a,b); + INSERT INTO t1 VALUES(1); + INSERT INTO t3 VALUES(1,2); + + SELECT * FROM t1 LEFT JOIN t2 USING(a) LEFT JOIN t3 USING(a); + } +} {1 2} +do_test join6-1.2 { + execsql { + SELECT t1.a, t3.b + FROM t1 LEFT JOIN t2 ON t1.a=t2.a LEFT JOIN t3 ON t2.a=t3.a; + } +} {1 {}} +do_test join6-1.3 { + execsql { + SELECT t1.a, t3.b + FROM t1 LEFT JOIN t2 ON t1.a=t2.a LEFT JOIN t3 ON t1.a=t3.a; + } +} {1 2} + + +do_test join6-2.1 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + + CREATE TABLE t1(x,y); + CREATE TABLE t2(y,z); + CREATE TABLE t3(x,z); + + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + + INSERT INTO t2 VALUES(2,3); + INSERT INTO t2 VALUES(4,5); + + INSERT INTO t3 VALUES(1,3); + INSERT INTO t3 VALUES(3,5); + + SELECT * FROM t1 JOIN t2 USING (y) JOIN t3 USING(x); + } +} {1 2 3 3 3 4 5 5} +do_test join6-2.2 { + execsql { + SELECT * FROM t1 NATURAL JOIN t2 NATURAL JOIN t3; + } +} {1 2 3 3 4 5} + + +do_test join6-3.1 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + + CREATE TABLE t1(a,x,y); + INSERT INTO t1 VALUES(1,91,92); + INSERT INTO t1 VALUES(2,93,94); + + CREATE TABLE t2(b,y,z); + INSERT INTO t2 VALUES(3,92,93); + INSERT INTO t2 VALUES(4,94,95); + + CREATE TABLE t3(c,x,z); + INSERT INTO t3 VALUES(5,91,93); + INSERT INTO t3 VALUES(6,99,95); + + SELECT * FROM t1 NATURAL JOIN t2 NATURAL JOIN t3; + } +} {1 91 92 3 93 5} +do_test join6-3.2 { + execsql { + SELECT * FROM t1 JOIN t2 NATURAL JOIN t3; + } +} {1 91 92 3 92 93 5} +do_test join6-3.3 { + execsql { + SELECT * FROM t1 JOIN t2 USING(y) NATURAL JOIN t3; + } +} {1 91 92 3 93 5} +do_test join6-3.4 { + execsql { + SELECT * FROM t1 NATURAL JOIN t2 JOIN t3 USING(x,z); + } +} {1 91 92 3 93 5} +do_test join6-3.5 { + execsql { + SELECT * FROM t1 NATURAL JOIN t2 JOIN t3 USING(x); + } +} {1 91 92 3 93 5 93} +do_test join6-3.6 { + execsql { + SELECT * FROM t1 NATURAL JOIN t2 JOIN t3 USING(z); + } +} {1 91 92 3 93 5 91 2 93 94 4 95 6 99} + +ifcapable compound { + do_test join6-4.1 { + execsql { + SELECT * FROM + (SELECT 1 AS a, 91 AS x, 92 AS y UNION SELECT 2, 93, 94) + NATURAL JOIN t2 NATURAL JOIN t3 + } + } {1 91 92 3 93 5} + do_test join6-4.2 { + execsql { + SELECT * FROM t1 NATURAL JOIN + (SELECT 3 AS b, 92 AS y, 93 AS z UNION SELECT 4, 94, 95) + NATURAL JOIN t3 + } + } {1 91 92 3 93 5} + do_test join6-4.3 { + execsql { + SELECT * FROM t1 NATURAL JOIN t2 NATURAL JOIN + (SELECT 5 AS c, 91 AS x, 93 AS z UNION SELECT 6, 99, 95) + } + } {1 91 92 3 93 5} +} + + + + + + + + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/journal1.test b/components/external/SQLite-3.8.1/test/journal1.test new file mode 100644 index 0000000000000000000000000000000000000000..c89dd2b4c9e073951c2c6af796e17f11e49a5097 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/journal1.test @@ -0,0 +1,67 @@ +# 2005 March 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure that leftover journals from +# prior databases do not try to rollback into new databases. +# +# $Id: journal1.test,v 1.2 2005/03/20 22:54:56 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# These tests will not work on windows because windows uses +# manditory file locking which breaks the copy_file command. +# +if {$tcl_platform(platform)=="windows"} { + finish_test + return +} + +# Create a smaple database +# +do_test journal1-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,randstr(10,400)); + INSERT INTO t1 VALUES(2,randstr(10,400)); + INSERT INTO t1 SELECT a+2, a||b FROM t1; + INSERT INTO t1 SELECT a+4, a||b FROM t1; + SELECT count(*) FROM t1; + } +} 8 + +# Make changes to the database and save the journal file. +# Then delete the database. Replace the journal file +# and try to create a new database with the same name. The +# old journal should not attempt to rollback into the new +# database. +# +do_test journal1-1.2 { + execsql { + BEGIN; + DELETE FROM t1; + } + forcecopy test.db-journal test.db-journal-bu + execsql { + ROLLBACK; + } + db close + delete_file test.db + copy_file test.db-journal-bu test.db-journal + sqlite3 db test.db + catchsql { + SELECT * FROM sqlite_master + } +} {0 {}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/journal2.test b/components/external/SQLite-3.8.1/test/journal2.test new file mode 100644 index 0000000000000000000000000000000000000000..8f9b4d0b71418b9988d17064adfed2b1bebaead9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/journal2.test @@ -0,0 +1,233 @@ +# 2010 June 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests SQLite when using a VFS that claims the SAFE_DELETE property. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl +db close + +if {[permutation] == "inmemory_journal"} { + finish_test + return +} + +set a_string_counter 1 +proc a_string {n} { + global a_string_counter + incr a_string_counter + string range [string repeat "${a_string_counter}." $n] 1 $n +} + +# Create a [testvfs] and install it as the default VFS. Set the device +# characteristics flags to "SAFE_DELETE". +# +testvfs tvfs -default 1 +tvfs devchar {undeletable_when_open powersafe_overwrite} + +# Set up a hook so that each time a journal file is opened, closed or +# deleted, the method name ("xOpen", "xClose" or "xDelete") and the final +# segment of the journal file-name (i.e. "test.db-journal") are appended to +# global list variable $::oplog. +# +tvfs filter {xOpen xClose xDelete} +tvfs script journal_op_catcher +proc journal_op_catcher {method filename args} { + + # If global variable ::tvfs_error_on_write is defined, then return an + # IO error to every attempt to modify the file-system. Otherwise, return + # SQLITE_OK. + # + if {[info exists ::tvfs_error_on_write]} { + if {[lsearch {xDelete xWrite xTruncate} $method]>=0} { + return SQLITE_IOERR + } + } + + # The rest of this command only deals with xOpen(), xClose() and xDelete() + # operations on journal files. If this invocation does not represent such + # an operation, return with no further ado. + # + set f [file tail $filename] + if {[string match *journal $f]==0} return + if {[lsearch {xOpen xDelete xClose} $method]<0} return + + # Append a record of this operation to global list variable $::oplog. + # + lappend ::oplog $method $f + + # If this is an attempt to delete a journal file for which there exists + # one ore more open handles, return an error. The code in test_vfs.c + # will not invoke the xDelete method of the "real" VFS in this case. + # + if {[info exists ::open_journals($f)]==0} { set ::open_journals($f) 0 } + switch -- $method { + xOpen { incr ::open_journals($f) +1 } + xClose { incr ::open_journals($f) -1 } + xDelete { if {$::open_journals($f)>0} { return SQLITE_IOERR } } + } + + return "" +} + + +do_test journal2-1.1 { + set ::oplog [list] + sqlite3 db test.db + execsql { CREATE TABLE t1(a, b) } + set ::oplog +} {xOpen test.db-journal xClose test.db-journal xDelete test.db-journal} +do_test journal2-1.2 { + set ::oplog [list] + execsql { + PRAGMA journal_mode = truncate; + INSERT INTO t1 VALUES(1, 2); + } + set ::oplog +} {xOpen test.db-journal} +do_test journal2-1.3 { + set ::oplog [list] + execsql { INSERT INTO t1 VALUES(3, 4) } + set ::oplog +} {} +do_test journal2-1.4 { execsql { SELECT * FROM t1 } } {1 2 3 4} + +# Add a second connection. This connection attempts to commit data in +# journal_mode=DELETE mode. When it tries to delete the journal file, +# the VFS layer returns an IO error. +# +do_test journal2-1.5 { + set ::oplog [list] + sqlite3 db2 test.db + execsql { PRAGMA journal_mode = delete } db2 + catchsql { INSERT INTO t1 VALUES(5, 6) } db2 +} {1 {disk I/O error}} +do_test journal2-1.6 { file exists test.db-journal } 1 +do_test journal2-1.7 { execsql { SELECT * FROM t1 } } {1 2 3 4} +do_test journal2-1.8 { + execsql { PRAGMA journal_mode = truncate } db2 + execsql { INSERT INTO t1 VALUES(5, 6) } db2 +} {} +do_test journal2-1.9 { execsql { SELECT * FROM t1 } } {1 2 3 4 5 6} + +# Grow the database until it is reasonably large. +# +do_test journal2-1.10 { + db2 close + db func a_string a_string + execsql { + CREATE TABLE t2(a UNIQUE, b UNIQUE); + INSERT INTO t2 VALUES(a_string(200), a_string(300)); + INSERT INTO t2 SELECT a_string(200), a_string(300) FROM t2; -- 2 + INSERT INTO t2 SELECT a_string(200), a_string(300) FROM t2; -- 4 + INSERT INTO t2 SELECT a_string(200), a_string(300) FROM t2; -- 8 + INSERT INTO t2 SELECT a_string(200), a_string(300) FROM t2; -- 16 + INSERT INTO t2 SELECT a_string(200), a_string(300) FROM t2; -- 32 + INSERT INTO t2 SELECT a_string(200), a_string(300) FROM t2; -- 64 + } + file size test.db-journal +} {0} +do_test journal2-1.11 { + set sz [expr [file size test.db] / 1024] + expr {$sz>120 && $sz<200} +} 1 + +# Using new connection [db2] (with journal_mode=DELETE), write a lot of +# data to the database. So that many pages within the database file are +# modified before the transaction is committed. +# +# Then, enable simulated IO errors in all calls to xDelete, xWrite +# and xTruncate before committing the transaction and closing the +# database file. From the point of view of other file-system users, it +# appears as if the process hosting [db2] unexpectedly exited. +# +do_test journal2-1.12 { + sqlite3 db2 test.db + execsql { + PRAGMA cache_size = 10; + BEGIN; + INSERT INTO t2 SELECT randomblob(200), randomblob(300) FROM t2; -- 128 + } db2 +} {} +do_test journal2-1.13 { + tvfs filter {xOpen xClose xDelete xWrite xTruncate} + set ::tvfs_error_on_write 1 + catchsql { COMMIT } db2 +} {1 {disk I/O error}} +db2 close +unset ::tvfs_error_on_write +forcecopy test.db testX.db + +do_test journal2-1.14 { file exists test.db-journal } 1 +do_test journal2-1.15 { + execsql { + SELECT count(*) FROM t2; + PRAGMA integrity_check; + } +} {64 ok} + +# This block checks that in the test case above, connection [db2] really +# did begin writing to the database file before it hit IO errors. If +# this is true, then the copy of the database file made before [db] +# rolled back the hot journal should fail the integrity-check. +# +do_test journal2-1.16 { + set sz [expr [file size testX.db] / 1024] + expr {$sz>240 && $sz<400} +} 1 +do_test journal2-1.17 { + expr {[catchsql { PRAGMA integrity_check } db] == "0 ok"} +} {1} +do_test journal2-1.20 { + sqlite3 db2 testX.db + expr {[catchsql { PRAGMA integrity_check } db2] == "0 ok"} +} {0} +do_test journal2-1.21 { + db2 close +} {} +db close + +#------------------------------------------------------------------------- +# Test that it is possible to switch from journal_mode=truncate to +# journal_mode=WAL on a SAFE_DELETE file-system. SQLite should close and +# delete the journal file when committing the transaction that switches +# the system to WAL mode. +# +ifcapable wal { + do_test journal2-2.1 { + faultsim_delete_and_reopen + set ::oplog [list] + execsql { PRAGMA journal_mode = persist } + set ::oplog + } {} + do_test journal2-2.2 { + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(3.14159); + } + set ::oplog + } {xOpen test.db-journal} + do_test journal2-2.3 { + expr {[file size test.db-journal] > 512} + } {1} + do_test journal2-2.4 { + set ::oplog [list] + execsql { PRAGMA journal_mode = WAL } + set ::oplog + } {xClose test.db-journal xDelete test.db-journal} + db close +} + +tvfs delete +finish_test diff --git a/components/external/SQLite-3.8.1/test/journal3.test b/components/external/SQLite-3.8.1/test/journal3.test new file mode 100644 index 0000000000000000000000000000000000000000..939cc27c7084b029a8173d69e9881b5b5bcd2609 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/journal3.test @@ -0,0 +1,63 @@ +# 2010 July 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +#------------------------------------------------------------------------- +# If a connection is required to create a journal file, it creates it with +# the same file-system permissions as the database file itself. Test this. +# +if {$::tcl_platform(platform) == "unix"} { + + # Changed on 2012-02-13: umask is deliberately ignored for -wal, -journal, + # and -shm files. + #set umask [exec /bin/sh -c umask] + faultsim_delete_and_reopen + do_test journal3-1.1 { execsql { CREATE TABLE tx(y, z) } } {} + + foreach {tn permissions} { + 1 00644 + 2 00666 + 3 00600 + 4 00755 + } { + db close + #set effective [format %.5o [expr $permissions & ~$umask]] + set effective $permissions + do_test journal3-1.2.$tn.1 { + catch { forcedelete test.db-journal } + file attributes test.db -permissions $permissions + file attributes test.db -permissions + } $permissions + do_test journal3-1.2.$tn.2 { file exists test.db-journal } {0} + do_test journal3-1.2.$tn.3 { + sqlite3 db test.db + execsql { + BEGIN; + INSERT INTO tx DEFAULT VALUES; + } + file exists test.db-journal + } {1} + do_test journal3-1.2.$tn.4 { + file attr test.db-journal -perm + } $effective + do_execsql_test journal3-1.2.$tn.5 { ROLLBACK } {} + } + + +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/jrnlmode.test b/components/external/SQLite-3.8.1/test/jrnlmode.test new file mode 100644 index 0000000000000000000000000000000000000000..b1007c490819e00546d7b5db8ceb2273842ec0b1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/jrnlmode.test @@ -0,0 +1,558 @@ +# 2008 April 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus +# of these tests is the journal mode pragma. +# +# $Id: jrnlmode.test,v 1.16 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!pager_pragmas} { + finish_test + return +} + +if {[info exists TEMP_STORE] && $TEMP_STORE>=2} { + set temp_persist memory + set temp_delete memory + set temp_truncate memory + set temp_off off +} else { + set temp_persist persist + set temp_delete delete + set temp_truncate truncate + set temp_off off +} + +proc temp_journal_mode {newmode} { + if {[info exists ::TEMP_STORE] && $::TEMP_STORE>=2} { + if {$newmode ne "off" && $newmode ne "memory"} { + execsql {PRAGMA temp.journal_mode} + set newmode [db one {PRAGMA temp.journal_mode}] + } + } + set newmode +} + +#---------------------------------------------------------------------- +# Test cases jrnlmode-1.X test the PRAGMA logic. +# +do_test jrnlmode-1.0 { + execsql { + PRAGMA journal_mode; + PRAGMA main.journal_mode; + PRAGMA temp.journal_mode; + } +} [list delete delete [temp_journal_mode delete]] +do_test jrnlmode-1.1 { + execsql { + PRAGMA journal_mode = persist; + } +} {persist} +do_test jrnlmode-1.2 { + execsql { + PRAGMA journal_mode; + PRAGMA main.journal_mode; + PRAGMA temp.journal_mode; + } +} [list persist persist [temp_journal_mode persist]] +do_test jrnlmode-1.4 { + execsql { + PRAGMA journal_mode = off; + } +} {off} +do_test jrnlmode-1.5 { + execsql { + PRAGMA journal_mode; + PRAGMA main.journal_mode; + PRAGMA temp.journal_mode; + } +} [list off off [temp_journal_mode off]] +do_test jrnlmode-1.6 { + execsql { + PRAGMA journal_mode = delete; + } +} {delete} +do_test jrnlmode-1.7 { + execsql { + PRAGMA journal_mode; + PRAGMA main.journal_mode; + PRAGMA Temp.journal_mode; + } +} [list delete delete [temp_journal_mode delete]] +do_test jrnlmode-1.7.1 { + execsql { + PRAGMA journal_mode = truncate; + } +} {truncate} +do_test jrnlmode-1.7.2 { + execsql { + PRAGMA journal_mode; + PRAGMA main.journal_mode; + PRAGMA temp.journal_mode; + } +} [list truncate truncate [temp_journal_mode truncate]] +do_test jrnlmode-1.8 { + execsql { + PRAGMA journal_mode = off; + PRAGMA journal_mode = invalid; + } +} {off off} +ifcapable attach { + do_test jrnlmode-1.9 { + execsql { + PRAGMA journal_mode = PERSIST; + ATTACH ':memory:' as aux1; + } + execsql { + PRAGMA main.journal_mode; + PRAGMA aux1.journal_mode; + } + } {persist memory} + do_test jrnlmode-1.10 { + execsql { + PRAGMA main.journal_mode = OFF; + } + execsql { + PRAGMA main.journal_mode; + PRAGMA temp.journal_mode; + PRAGMA aux1.journal_mode; + } + } [list off [temp_journal_mode persist] memory] + do_test jrnlmode-1.11 { + execsql { + PRAGMA journal_mode; + } + } {off} + do_test jrnlmode-1.12 { + execsql { + ATTACH ':memory:' as aux2; + } + execsql { + PRAGMA main.journal_mode; + PRAGMA aux1.journal_mode; + PRAGMA aux2.journal_mode; + } + } {off memory memory} + do_test jrnlmode-1.13 { + # The journal-mode used by in-memory databases cannot be changed. + execsql { + PRAGMA aux1.journal_mode = DELETE; + } + execsql { + PRAGMA main.journal_mode; + PRAGMA aux1.journal_mode; + PRAGMA aux2.journal_mode; + } + } {off memory memory} + do_test jrnlmode-1.14 { + execsql { + PRAGMA journal_mode = delete; + } + execsql { + PRAGMA main.journal_mode; + PRAGMA temp.journal_mode; + PRAGMA aux1.journal_mode; + PRAGMA aux2.journal_mode; + } + } [list delete [temp_journal_mode delete] memory memory] + do_test jrnlmode-1.15 { + execsql { + ATTACH ':memory:' as aux3; + } + execsql { + PRAGMA main.journal_mode; + PRAGMA temp.journal_mode; + PRAGMA aux1.journal_mode; + PRAGMA aux2.journal_mode; + PRAGMA aux3.journal_mode; + } + } [list delete [temp_journal_mode delete] memory memory memory] + do_test jrnlmode-1.16 { + execsql { + PRAGMA journal_mode = TRUNCATE; + } + execsql { + PRAGMA main.journal_mode; + PRAGMA temp.journal_mode; + PRAGMA aux1.journal_mode; + PRAGMA aux2.journal_mode; + PRAGMA aux3.journal_mode; + } + } [list truncate [temp_journal_mode truncate] memory memory memory] + + do_test jrnlmode-1.99 { + execsql { + DETACH aux1; + DETACH aux2; + DETACH aux3; + } + } {} +} + +ifcapable attach { + forcedelete test2.db + do_test jrnlmode-2.1 { + execsql { + ATTACH 'test2.db' AS aux; + PRAGMA main.journal_mode = persist; + PRAGMA aux.journal_mode = persist; + CREATE TABLE abc(a, b, c); + CREATE TABLE aux.def(d, e, f); + } + execsql { + BEGIN; + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO def VALUES(4, 5, 6); + COMMIT; + } + list [file exists test.db-journal] [file exists test2.db-journal] + } {1 1} + + do_test jrnlmode-2.2 { + file size test.db-journal + } {0} + + do_test jrnlmode-2.3 { + execsql { + SELECT * FROM abc; + } + } {1 2 3} + + do_test jrnlmode-2.4 { + file size test.db-journal + } {0} + + do_test jrnlmode-2.5 { + execsql { + SELECT * FROM def; + } + } {4 5 6} + +#---------------------------------------------------------------------- +# Test caes jrnlmode-3.X verify that ticket #3127 has been fixed. +# + db close + forcedelete test2.db + forcedelete test.db + sqlite3 db test.db + + do_test jrnlmode-3.1 { + execsql { + CREATE TABLE x(n INTEGER); + ATTACH 'test2.db' AS a; + create table a.x ( n integer ); + insert into a.x values(1); + insert into a.x values (2); + insert into a.x values (3); + insert into a.x values (4); + } + } {} + + do_test jrnlmode-3.2 { + execsql { PRAGMA journal_mode=off; } + execsql { + BEGIN IMMEDIATE; + INSERT OR IGNORE INTO main.x SELECT * FROM a.x; + COMMIT; + } + } {} +} + +ifcapable autovacuum&&pragma { + db close + forcedelete test.db + sqlite3 db test.db + do_test jrnlmode-4.1 { + execsql { + PRAGMA cache_size = 1; + PRAGMA auto_vacuum = 1; + CREATE TABLE abc(a, b, c); + } + execsql { PRAGMA page_count } + } {3} + + do_test jrnlmode-4.2 { + execsql { PRAGMA journal_mode = off } + } {off} + + do_test jrnlmode-4.3 { + execsql { INSERT INTO abc VALUES(1, 2, randomblob(2000)) } + } {} + + # This will attempt to truncate the database file. Check that this + # is not a problem when journal_mode=off. + do_test jrnlmode-4.4 { + execsql { DELETE FROM abc } + } {} + + integrity_check jrnlmode-4.5 +} + +#------------------------------------------------------------------------ +# The following test caes, jrnlmode-5.*, test the journal_size_limit +# pragma. +ifcapable pragma { + db close + forcedelete test.db test2.db test3.db + sqlite3 db test.db + + do_test jrnlmode-5.1 { + execsql {pragma page_size=1024} + execsql {pragma journal_mode=persist} + } {persist} + + do_test jrnlmode-5.2 { + execsql { PRAGMA journal_size_limit } + } {-1} + do_test jrnlmode-5.3 { + execsql { + ATTACH 'test2.db' AS aux; + PRAGMA aux.journal_mode=persist; + PRAGMA aux.journal_size_limit; + } + } {persist -1} + do_test jrnlmode-5.4.1 { + execsql { PRAGMA aux.journal_size_limit = 999999999999 } + } {999999999999} + do_test jrnlmode-5.4.2 { + execsql { PRAGMA aux.journal_size_limit = 10240 } + } {10240} + do_test jrnlmode-5.5 { + execsql { PRAGMA main.journal_size_limit = 20480 } + } {20480} + do_test jrnlmode-5.6 { + execsql { PRAGMA journal_size_limit } + } {20480} + do_test jrnlmode-5.7 { + execsql { PRAGMA aux.journal_size_limit } + } {10240} + + do_test jrnlmode-5.8 { + execsql { + ATTACH 'test3.db' AS aux2; + PRAGMA aux2.journal_mode=persist; + } + } {persist} + + do_test jrnlmode-5.9 { + execsql { + CREATE TABLE main.t1(a, b, c); + CREATE TABLE aux.t2(a, b, c); + CREATE TABLE aux2.t3(a, b, c); + } + } {} + do_test jrnlmode-5.10 { + list \ + [file exists test.db-journal] \ + [file exists test2.db-journal] \ + [file exists test3.db-journal] + } {1 1 1} + do_test jrnlmode-5.11 { + execsql { + BEGIN; + INSERT INTO t3 VALUES(randomblob(1000),randomblob(1000),randomblob(1000)); + INSERT INTO t3 + SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3; + INSERT INTO t3 + SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3; + INSERT INTO t3 + SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3; + INSERT INTO t3 + SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3; + INSERT INTO t3 + SELECT randomblob(1000),randomblob(1000),randomblob(1000) FROM t3; + INSERT INTO t2 SELECT * FROM t3; + INSERT INTO t1 SELECT * FROM t2; + COMMIT; + } + list \ + [file exists test.db-journal] \ + [file exists test2.db-journal] \ + [file exists test3.db-journal] \ + [file size test.db-journal] \ + [file size test2.db-journal] \ + [file size test3.db-journal] + } {1 1 1 0 0 0} + + do_test jrnlmode-5.12 { + execsql { + BEGIN; + UPDATE t1 SET a = randomblob(1000); + } + expr {[file size test.db-journal]>30000} + } {1} + do_test jrnlmode-5.13 { + execsql COMMIT + file size test.db-journal + } {20480} + + do_test jrnlmode-5.14 { + execsql { + BEGIN; + UPDATE t2 SET a = randomblob(1000); + } + expr {[file size test2.db-journal]>30000} + } {1} + do_test jrnlmode-5.15 { + execsql COMMIT + file size test2.db-journal + } {10240} + + do_test jrnlmode-5.16 { + execsql { + BEGIN; + UPDATE t3 SET a = randomblob(1000); + } + set journalsize [file size test3.db-journal] + expr {$journalsize>30000} + } {1} + do_test jrnlmode-5.17 { + execsql COMMIT + set sz [file size test3.db-journal] + expr {$sz>=$journalsize} + } {1} + + do_test jrnlmode-5.18 { + execsql { + PRAGMA journal_size_limit = -4; + BEGIN; + UPDATE t1 SET a = randomblob(1000); + } + set journalsize [file size test.db-journal] + expr {$journalsize>30000} + } {1} + do_test jrnlmode-5.19 { + execsql COMMIT + set sz [file size test.db-journal] + expr {$sz>=$journalsize} + } {1} + + # Test a size-limit of 0. + # + do_test jrnlmode-5.20 { + execsql { + PRAGMA journal_size_limit = 0; + BEGIN; + UPDATE t1 SET a = randomblob(1000); + } + } {0} + do_test jrnlmode-5.21 { + expr {[file size test.db-journal] > 1024} + } {1} + do_test jrnlmode-5.22 { + execsql COMMIT + list [file exists test.db-journal] [file size test.db-journal] + } {1 0} +} + +ifcapable pragma { + # These tests are not run as part of the "journaltest" permutation, + # as the test_journal.c layer is incompatible with in-memory journaling. + if {[permutation] ne "journaltest"} { + + do_test jrnlmode-6.1 { + execsql { + PRAGMA journal_mode = truncate; + CREATE TABLE t4(a, b); + BEGIN; + INSERT INTO t4 VALUES(1, 2); + PRAGMA journal_mode = memory; + } + } {truncate truncate} + do_test jrnlmode-6.2 { + file exists test.db-journal + } {1} + do_test jrnlmode-6.3 { + execsql { + COMMIT; + SELECT * FROM t4; + } + } {1 2} + do_test jrnlmode-6.4 { + file exists test.db-journal + } {1} + do_test jrnlmode-6.5 { + execsql { + PRAGMA journal_mode = MEMORY; + BEGIN; + INSERT INTO t4 VALUES(3, 4); + } + file exists test.db-journal + } {0} + do_test jrnlmode-6.7 { + execsql { + COMMIT; + SELECT * FROM t4; + } + } {1 2 3 4} + do_test jrnlmode-6.8 { + file exists test.db-journal + } {0} + do_test jrnlmode-6.9 { + execsql { + PRAGMA journal_mode = DELETE; + BEGIN IMMEDIATE; INSERT INTO t4 VALUES(1,2); COMMIT; + } + file exists test.db-journal + } {0} + } +} + +ifcapable pragma { + catch { db close } + do_test jrnlmode-7.1 { + foreach f [glob -nocomplain test.db*] { forcedelete $f } + sqlite3 db test.db + execsql { + PRAGMA journal_mode = memory; + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 1024; + PRAGMA user_version = 5; + PRAGMA user_version; + } + } {memory 5} + do_test jrnlmode-7.2 { file size test.db } {1024} +} + +do_execsql_test jrnlmode-8.1 { PRAGMA locking_mode=EXCLUSIVE } {exclusive} +do_execsql_test jrnlmode-8.2 { CREATE TABLE t1(x) } {} +do_execsql_test jrnlmode-8.3 { INSERT INTO t1 VALUES(123) } {} +do_execsql_test jrnlmode-8.4 { SELECT * FROM t1 } {123} +do_execsql_test jrnlmode-8.5 { PRAGMA journal_mode=PERSIST } {persist} +do_execsql_test jrnlmode-8.6 { PRAGMA journal_mode=DELETE } {delete} +do_execsql_test jrnlmode-8.7 { PRAGMA journal_mode=TRUNCATE } {truncate} +do_execsql_test jrnlmode-8.8 { PRAGMA journal_mode=DELETE } {delete} +do_execsql_test jrnlmode-8.9 { CREATE TABLE t2(y) } {} +do_execsql_test jrnlmode-8.10 { INSERT INTO t2 VALUES(456) } {} +do_execsql_test jrnlmode-8.11 { SELECT * FROM t1, t2 } {123 456} +do_execsql_test jrnlmode-8.12 { PRAGMA locking_mode=NORMAL } {normal} +do_execsql_test jrnlmode-8.13 { PRAGMA journal_mode=PERSIST } {persist} +do_execsql_test jrnlmode-8.14 { PRAGMA journal_mode=TRUNCATE } {truncate} +do_execsql_test jrnlmode-8.15 { PRAGMA journal_mode=PERSIST } {persist} +do_execsql_test jrnlmode-8.16 { PRAGMA journal_mode=DELETE } {delete} +do_execsql_test jrnlmode-8.17 { PRAGMA journal_mode=TRUNCATE } {truncate} +do_execsql_test jrnlmode-8.18 { PRAGMA locking_mode=EXCLUSIVE } {exclusive} +do_execsql_test jrnlmode-8.19 { CREATE TABLE t3(z) } {} +do_execsql_test jrnlmode-8.20 { BEGIN IMMEDIATE } {} +do_execsql_test jrnlmode-8.21 { PRAGMA journal_mode=DELETE } {delete} +do_execsql_test jrnlmode-8.22 { COMMIT } {} +do_execsql_test jrnlmode-8.23 { PRAGMA journal_mode=DELETE } {delete} +do_execsql_test jrnlmode-8.24 { PRAGMA journal_mode=TRUNCATE } {truncate} +do_execsql_test jrnlmode-8.25 { PRAGMA locking_mode=NORMAL } {normal} +do_execsql_test jrnlmode-8.26 { CREATE TABLE t4(w) } {} +do_execsql_test jrnlmode-8.27 { BEGIN IMMEDIATE } {} +do_execsql_test jrnlmode-8.28 { PRAGMA journal_mode=DELETE } {delete} +do_execsql_test jrnlmode-8.29 { COMMIT } {} +do_execsql_test jrnlmode-8.30 { PRAGMA journal_mode=DELETE } {delete} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/jrnlmode2.test b/components/external/SQLite-3.8.1/test/jrnlmode2.test new file mode 100644 index 0000000000000000000000000000000000000000..6ea87d704b3f8c933dd1958fdce501c752cb8bc0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/jrnlmode2.test @@ -0,0 +1,123 @@ +# 2009 March 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!pager_pragmas} { + finish_test + return +} + +#------------------------------------------------------------------------- +# The tests in this file check that the following two bugs (both now fixed) +# do not reappear. +# +# jrnlmode2-1.*: Demonstrate bug #3745: +# +# In persistent journal mode, if: +# +# * There is a persistent journal in the file-system, AND +# * there exists a connection with a shared lock on the db file, +# +# then a second connection cannot open a read-transaction on the database. +# The reason is because while determining that the persistent-journal is +# not a hot-journal, SQLite currently grabs an exclusive lock on the +# database file. If this fails because another connection has a shared +# lock, then SQLITE_BUSY is returned to the user. +# +# jrnlmode2-2.*: Demonstrate bug #3751: +# +# If a connection is opened in SQLITE_OPEN_READONLY mode, the underlying +# unix file descriptor on the database file is opened in O_RDONLY mode. +# +# When SQLite queries the database file for the schema in order to compile +# the SELECT statement, it sees the empty journal in the file system, it +# attempts to obtain an exclusive lock on the database file (this is a +# bug). The attempt to obtain an exclusive (write) lock on a read-only file +# fails at the OS level. Under unix, fcntl() reports an EBADF - "Bad file +# descriptor" - error. +# + +do_test jrnlmode2-1.1 { + execsql { + PRAGMA journal_mode = persist; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } +} {persist} + +do_test jrnlmode2-1.2 { + file exists test.db-journal +} {1} + +do_test jrnlmode2-1.3 { + sqlite3 db2 test.db + execsql { SELECT * FROM t1 } db2 +} {1 2} + +do_test jrnlmode2-1.4 { + execsql { + INSERT INTO t1 VALUES(3, 4); + } + execsql { + BEGIN; + SELECT * FROM t1; + } + execsql { PRAGMA lock_status } +} {main shared temp closed} + +do_test jrnlmode2-1.5 { + file exists test.db-journal +} {1} + +do_test jrnlmode2-1.6 { + catchsql { SELECT * FROM t1 } db2 +} {0 {1 2 3 4}} + +do_test jrnlmode2-1.7 { + execsql { COMMIT } + catchsql { SELECT * FROM t1 } db2 +} {0 {1 2 3 4}} + + + +do_test jrnlmode2-2.1 { + db2 close + execsql { PRAGMA journal_mode = truncate } + execsql { INSERT INTO t1 VALUES(5, 6) } +} {} + +do_test jrnlmode2-2.2 { + file exists test.db-journal +} {1} + +do_test jrnlmode2-2.3 { + file size test.db-journal +} {0} + +do_test jrnlmode2-2.4 { + sqlite3 db2 test.db -readonly 1 + catchsql { SELECT * FROM t1 } db2 +} {0 {1 2 3 4 5 6}} + +do_test jrnlmode2-2.5 { + db close + delete_file test.db-journal +} {} +do_test jrnlmode2-2.6 { + sqlite3 db2 test.db -readonly 1 + catchsql { SELECT * FROM t1 } db2 +} {0 {1 2 3 4 5 6}} + +catch { db2 close } +finish_test diff --git a/components/external/SQLite-3.8.1/test/jrnlmode3.test b/components/external/SQLite-3.8.1/test/jrnlmode3.test new file mode 100644 index 0000000000000000000000000000000000000000..43da6579abc1c032053ffc64c1917e6b08754b61 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/jrnlmode3.test @@ -0,0 +1,149 @@ +# 2009 April 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test cases inspired by ticket #3811. Tests to make sure that +# the journal_mode can only be changed at appropriate times and that +# all reported changes are effective. +# +# $Id: jrnlmode3.test,v 1.5 2009/04/20 17:43:03 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!pager_pragmas} { + finish_test + return +} + +# +# Verify that journal_mode=OFF works as long as it occurs before the first +# transaction, even if locking_mode=EXCLUSIVE is enabled. The behavior if +# journal_mode is changed after the first transaction is undefined and hence +# untested. +# +do_test jrnlmode3-1.1 { + db eval { + PRAGMA journal_mode=OFF; + PRAGMA locking_mode=EXCLUSIVE; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + SELECT * FROM t1; + } +} {off exclusive 1} +do_test jrnlmode3-1.2 { + db eval { + BEGIN; + INSERT INTO t1 VALUES(2); + ROLLBACK; + SELECT * FROM t1; + } +} {1} + +db close +forcedelete test.db test.db-journal +sqlite3 db test.db + +do_test jrnlmode3-2.1 { + db eval { + PRAGMA locking_mode=EXCLUSIVE; + PRAGMA journal_mode=OFF; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + SELECT * FROM t1; + } +} {exclusive off 1} +do_test jrnlmode3-2.2 { + db eval { + BEGIN; + INSERT INTO t1 VALUES(2); + ROLLBACK; + SELECT * FROM t1; + } +} {1} + +# Test cases to verify that we can move from any journal_mode +# to any other, as long as we are not in a transaction. Verify +# that we cannot change journal_mode while a transaction is active. +# +set all_journal_modes {delete persist truncate memory off} +set cnt 0 +foreach fromjmode $all_journal_modes { + foreach tojmode $all_journal_modes { + + # Skip the no-change cases + if {$fromjmode==$tojmode} continue + incr cnt + + # Start with a fresh database connection an empty database file. + # + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + + # Initialize the journal mode. + # + do_test jrnlmode3-3.$cnt.1-($fromjmode-to-$tojmode) { + db eval "PRAGMA journal_mode = $fromjmode;" + } $fromjmode + + # Verify that the initial journal mode takes. + # + do_test jrnlmode3-3.$cnt.2 { + db eval {PRAGMA main.journal_mode} + } $fromjmode + + # Start a transaction and try to change the journal mode within + # the transaction. This should fail. + # + do_test jrnlmode3-3.$cnt.3 { + db eval { + CREATE TABLE t1(x); + BEGIN; + INSERT INTO t1 VALUES($cnt); + } + db eval "PRAGMA journal_mode=$tojmode" + } $fromjmode + + # Rollback the transaction. + # + do_test jrnlmode3-3.$cnt.4 { + db eval { + ROLLBACK; + SELECT * FROM t1; + } + } {} + + # Now change the journal mode again. This time the new mode + # should take. + # + do_test jrnlmode3-3.$cnt.5 { + db eval "PRAGMA journal_mode=$tojmode" + } $tojmode + + # Do a the transaction. Verify that the rollback occurred + # if journal_mode!=OFF. + # + do_test jrnlmode3-3.$cnt.6 { + db eval { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(x); + BEGIN; + INSERT INTO t1 VALUES(1); + } + db eval ROLLBACK + db eval { + SELECT * FROM t1; + } + } {} + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/keyword1.test b/components/external/SQLite-3.8.1/test/keyword1.test new file mode 100644 index 0000000000000000000000000000000000000000..94831201cea4630c90e29cefcd9a5de129b447b2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/keyword1.test @@ -0,0 +1,118 @@ +# 2009 January 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Verify that certain keywords can be used as identifiers. +# +# $Id: keyword1.test,v 1.1 2009/01/29 19:27:47 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +db eval { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t1 VALUES(3, 'three'); +} + +set kwlist { + abort + after + analyze + asc + attach + before + begin + by + cascade + cast + column + conflict + current_date + current_time + current_timestamp + database + deferred + desc + detach + end + each + exclusive + explain + fail + for + glob + if + ignore + immediate + initially + instead + key + like + match + of + offset + plan + pragma + query + raise + regexp + reindex + release + rename + replace + restrict + rollback + row + savepoint + temp + temporary + trigger + vacuum + view + virtual +}; +set exprkw { + cast + current_date + current_time + current_timestamp + raise +} +foreach kw $kwlist { + do_test keyword1-$kw.1 { + if {$kw=="if"} { + db eval "CREATE TABLE \"$kw\"($kw $kw)" + } else { + db eval "CREATE TABLE ${kw}($kw $kw)" + } + db eval "INSERT INTO $kw VALUES(99)" + db eval "INSERT INTO $kw SELECT a FROM t1" + if {[lsearch $exprkw $kw]<0} { + db eval "SELECT * FROM $kw ORDER BY $kw ASC" + } else { + db eval "SELECT * FROM $kw ORDER BY \"$kw\" ASC" + } + } {1 2 3 99} + do_test keyword1-$kw.2 { + if {$kw=="if"} { + db eval "DROP TABLE \"$kw\"" + db eval "CREATE INDEX \"$kw\" ON t1(a)" + } else { + db eval "DROP TABLE $kw" + db eval "CREATE INDEX $kw ON t1(a)" + } + db eval "SELECT b FROM t1 INDEXED BY $kw WHERE a=2" + } {two} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/lastinsert.test b/components/external/SQLite-3.8.1/test/lastinsert.test new file mode 100644 index 0000000000000000000000000000000000000000..adeb79860b1dc56a8e25a053e9bd78a7510059aa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lastinsert.test @@ -0,0 +1,366 @@ +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests to make sure that value returned by last_insert_rowid() (LIRID) +# is updated properly, especially inside triggers +# +# Note 1: insert into table is now the only statement which changes LIRID +# Note 2: upon entry into before or instead of triggers, +# LIRID is unchanged (rather than -1) +# Note 3: LIRID is changed within the context of a trigger, +# but is restored once the trigger exits +# Note 4: LIRID is not changed by an insert into a view (since everything +# is done within instead of trigger context) +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# ---------------------------------------------------------------------------- +# 1.x - basic tests (no triggers) + +# LIRID changed properly after an insert into a table +do_test lastinsert-1.1 { + catchsql { + create table t1 (k integer primary key); + insert into t1 values (1); + insert into t1 values (NULL); + insert into t1 values (NULL); + select last_insert_rowid(); + } +} {0 3} + +# LIRID unchanged after an update on a table +do_test lastinsert-1.2 { + catchsql { + update t1 set k=4 where k=2; + select last_insert_rowid(); + } +} {0 3} + +# LIRID unchanged after a delete from a table +do_test lastinsert-1.3 { + catchsql { + delete from t1 where k=4; + select last_insert_rowid(); + } +} {0 3} + +# LIRID unchanged after create table/view statements +do_test lastinsert-1.4.1 { + catchsql { + create table t2 (k integer primary key, val1, val2, val3); + select last_insert_rowid(); + } +} {0 3} +ifcapable view { +do_test lastinsert-1.4.2 { + catchsql { + create view v as select * from t1; + select last_insert_rowid(); + } +} {0 3} +} ;# ifcapable view + +# All remaining tests involve triggers. Skip them if triggers are not +# supported in this build. +# +ifcapable {!trigger} { + finish_test + return +} + +# ---------------------------------------------------------------------------- +# 2.x - tests with after insert trigger + +# LIRID changed properly after an insert into table containing an after trigger +do_test lastinsert-2.1 { + catchsql { + delete from t2; + create trigger r1 after insert on t1 for each row begin + insert into t2 values (NEW.k*2, last_insert_rowid(), NULL, NULL); + update t2 set k=k+10, val2=100+last_insert_rowid(); + update t2 set val3=1000+last_insert_rowid(); + end; + insert into t1 values (13); + select last_insert_rowid(); + } +} {0 13} + +# LIRID equals NEW.k upon entry into after insert trigger +do_test lastinsert-2.2 { + catchsql { + select val1 from t2; + } +} {0 13} + +# LIRID changed properly by insert within context of after insert trigger +do_test lastinsert-2.3 { + catchsql { + select val2 from t2; + } +} {0 126} + +# LIRID unchanged by update within context of after insert trigger +do_test lastinsert-2.4 { + catchsql { + select val3 from t2; + } +} {0 1026} + +# ---------------------------------------------------------------------------- +# 3.x - tests with after update trigger + +# LIRID not changed after an update onto a table containing an after trigger +do_test lastinsert-3.1 { + catchsql { + delete from t2; + drop trigger r1; + create trigger r1 after update on t1 for each row begin + insert into t2 values (NEW.k*2, last_insert_rowid(), NULL, NULL); + update t2 set k=k+10, val2=100+last_insert_rowid(); + update t2 set val3=1000+last_insert_rowid(); + end; + update t1 set k=14 where k=3; + select last_insert_rowid(); + } +} {0 13} + +# LIRID unchanged upon entry into after update trigger +do_test lastinsert-3.2 { + catchsql { + select val1 from t2; + } +} {0 13} + +# LIRID changed properly by insert within context of after update trigger +do_test lastinsert-3.3 { + catchsql { + select val2 from t2; + } +} {0 128} + +# LIRID unchanged by update within context of after update trigger +do_test lastinsert-3.4 { + catchsql { + select val3 from t2; + } +} {0 1028} + +# ---------------------------------------------------------------------------- +# 4.x - tests with instead of insert trigger +# These may not be run if either views or triggers were disabled at +# compile-time + +ifcapable {view && trigger} { +# LIRID not changed after an insert into view containing an instead of trigger +do_test lastinsert-4.1 { + catchsql { + delete from t2; + drop trigger r1; + create trigger r1 instead of insert on v for each row begin + insert into t2 values (NEW.k*2, last_insert_rowid(), NULL, NULL); + update t2 set k=k+10, val2=100+last_insert_rowid(); + update t2 set val3=1000+last_insert_rowid(); + end; + insert into v values (15); + select last_insert_rowid(); + } +} {0 13} + +# LIRID unchanged upon entry into instead of trigger +do_test lastinsert-4.2 { + catchsql { + select val1 from t2; + } +} {0 13} + +# LIRID changed properly by insert within context of instead of trigger +do_test lastinsert-4.3 { + catchsql { + select val2 from t2; + } +} {0 130} + +# LIRID unchanged by update within context of instead of trigger +do_test lastinsert-4.4 { + catchsql { + select val3 from t2; + } +} {0 1030} +} ;# ifcapable (view && trigger) + +# ---------------------------------------------------------------------------- +# 5.x - tests with before delete trigger + +# LIRID not changed after a delete on a table containing a before trigger +do_test lastinsert-5.1 { + catchsql { + drop trigger r1; -- This was not created if views are disabled. + } + catchsql { + delete from t2; + create trigger r1 before delete on t1 for each row begin + insert into t2 values (77, last_insert_rowid(), NULL, NULL); + update t2 set k=k+10, val2=100+last_insert_rowid(); + update t2 set val3=1000+last_insert_rowid(); + end; + delete from t1 where k=1; + select last_insert_rowid(); + } +} {0 13} + +# LIRID unchanged upon entry into delete trigger +do_test lastinsert-5.2 { + catchsql { + select val1 from t2; + } +} {0 13} + +# LIRID changed properly by insert within context of delete trigger +do_test lastinsert-5.3 { + catchsql { + select val2 from t2; + } +} {0 177} + +# LIRID unchanged by update within context of delete trigger +do_test lastinsert-5.4 { + catchsql { + select val3 from t2; + } +} {0 1077} + +# ---------------------------------------------------------------------------- +# 6.x - tests with instead of update trigger +# These tests may not run if either views or triggers are disabled. + +ifcapable {view && trigger} { +# LIRID not changed after an update on a view containing an instead of trigger +do_test lastinsert-6.1 { + catchsql { + delete from t2; + drop trigger r1; + create trigger r1 instead of update on v for each row begin + insert into t2 values (NEW.k*2, last_insert_rowid(), NULL, NULL); + update t2 set k=k+10, val2=100+last_insert_rowid(); + update t2 set val3=1000+last_insert_rowid(); + end; + update v set k=16 where k=14; + select last_insert_rowid(); + } +} {0 13} + +# LIRID unchanged upon entry into instead of trigger +do_test lastinsert-6.2 { + catchsql { + select val1 from t2; + } +} {0 13} + +# LIRID changed properly by insert within context of instead of trigger +do_test lastinsert-6.3 { + catchsql { + select val2 from t2; + } +} {0 132} + +# LIRID unchanged by update within context of instead of trigger +do_test lastinsert-6.4 { + catchsql { + select val3 from t2; + } +} {0 1032} +} ;# ifcapable (view && trigger) + +# ---------------------------------------------------------------------------- +# 7.x - complex tests with temporary tables and nested instead of triggers +# These do not run if views or triggers are disabled. + +ifcapable {trigger && view && tempdb} { +do_test lastinsert-7.1 { + catchsql { + drop table t1; drop table t2; drop trigger r1; + create temp table t1 (k integer primary key); + create temp table t2 (k integer primary key); + create temp view v1 as select * from t1; + create temp view v2 as select * from t2; + create temp table rid (k integer primary key, rin, rout); + insert into rid values (1, NULL, NULL); + insert into rid values (2, NULL, NULL); + create temp trigger r1 instead of insert on v1 for each row begin + update rid set rin=last_insert_rowid() where k=1; + insert into t1 values (100+NEW.k); + insert into v2 values (100+last_insert_rowid()); + update rid set rout=last_insert_rowid() where k=1; + end; + create temp trigger r2 instead of insert on v2 for each row begin + update rid set rin=last_insert_rowid() where k=2; + insert into t2 values (1000+NEW.k); + update rid set rout=last_insert_rowid() where k=2; + end; + insert into t1 values (77); + select last_insert_rowid(); + } +} {0 77} + +do_test lastinsert-7.2 { + catchsql { + insert into v1 values (5); + select last_insert_rowid(); + } +} {0 77} + +do_test lastinsert-7.3 { + catchsql { + select rin from rid where k=1; + } +} {0 77} + +do_test lastinsert-7.4 { + catchsql { + select rout from rid where k=1; + } +} {0 105} + +do_test lastinsert-7.5 { + catchsql { + select rin from rid where k=2; + } +} {0 105} + +do_test lastinsert-7.6 { + catchsql { + select rout from rid where k=2; + } +} {0 1205} + +do_test lastinsert-8.1 { + db close + sqlite3 db test.db + execsql { + CREATE TABLE t2(x INTEGER PRIMARY KEY, y); + CREATE TABLE t3(a, b); + CREATE TRIGGER after_t2 AFTER INSERT ON t2 BEGIN + INSERT INTO t3 VALUES(new.x, new.y); + END; + INSERT INTO t2 VALUES(5000000000, 1); + SELECT last_insert_rowid(); + } +} 5000000000 + +do_test lastinsert-9.1 { + db eval {INSERT INTO t2 VALUES(123456789012345,0)} + db last_insert_rowid +} {123456789012345} + + +} ;# ifcapable (view && trigger) + +finish_test diff --git a/components/external/SQLite-3.8.1/test/laststmtchanges.test b/components/external/SQLite-3.8.1/test/laststmtchanges.test new file mode 100644 index 0000000000000000000000000000000000000000..ea4c3892b75d257cf51a3f71864c537b93a4ba67 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/laststmtchanges.test @@ -0,0 +1,331 @@ +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests to make sure that values returned by changes() and total_changes() +# are updated properly, especially inside triggers +# +# Note 1: changes() remains constant within a statement and only updates +# once the statement is finished (triggers count as part of +# statement). +# Note 2: changes() is changed within the context of a trigger much like +# last_insert_rowid() (see lastinsert.test), but is restored once +# the trigger exits. +# Note 3: changes() is not changed by a change to a view (since everything +# is done within instead of trigger context). +# +# $Id: laststmtchanges.test,v 1.7 2008/10/27 13:59:34 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# ---------------------------------------------------------------------------- +# 1.x - basic tests (no triggers) + +# changes() set properly after insert +do_test laststmtchanges-1.1 { + catchsql { + create table t0 (x); + insert into t0 values (1); + insert into t0 values (1); + insert into t0 values (2); + insert into t0 values (2); + insert into t0 values (1); + insert into t0 values (1); + insert into t0 values (1); + insert into t0 values (2); + select changes(), total_changes(); + } +} {0 {1 8}} + +# changes() set properly after update +do_test laststmtchanges-1.2 { + catchsql { + update t0 set x=3 where x=1; + select changes(), total_changes(); + } +} {0 {5 13}} + +# There was some goofy change-counting logic in sqlite3_exec() that +# appears to have been left over from SQLite version 2. This test +# makes sure it has been removed. +# +do_test laststmtchanges-1.2.1 { + db cache flush + sqlite3_exec_printf db {update t0 set x=4 where x=3; select 1;} {} + execsql {select changes()} +} {5} + +# changes() unchanged within an update statement +do_test laststmtchanges-1.3 { + execsql {update t0 set x=3 where x=4} + catchsql { + update t0 set x=x+changes() where x=3; + select count() from t0 where x=8; + } +} {0 5} + +# changes() set properly after update on table where no rows changed +do_test laststmtchanges-1.4 { + catchsql { + update t0 set x=77 where x=88; + select changes(); + } +} {0 0} + +# changes() set properly after delete from table +do_test laststmtchanges-1.5 { + catchsql { + delete from t0 where x=2; + select changes(); + } +} {0 3} + +# All remaining tests involve triggers. Skip them if triggers are not +# supported in this build. +# +ifcapable {!trigger} { + finish_test + return +} + + +# ---------------------------------------------------------------------------- +# 2.x - tests with after insert trigger + +# changes() changed properly after insert into table containing after trigger +do_test laststmtchanges-2.1 { + set ::tc [db total_changes] + catchsql { + create table t1 (k integer primary key); + create table t2 (k integer primary key, v1, v2); + create trigger r1 after insert on t1 for each row begin + insert into t2 values (NULL, changes(), NULL); + update t0 set x=x; + update t2 set v2=changes(); + end; + insert into t1 values (77); + select changes(); + } +} {0 1} + +# changes() unchanged upon entry into after insert trigger +do_test laststmtchanges-2.2 { + catchsql { + select v1 from t2; + } +} {0 3} + +# changes() changed properly by update within context of after insert trigger +do_test laststmtchanges-2.3 { + catchsql { + select v2 from t2; + } +} {0 5} + +# Total changes caused by firing the trigger above: +# +# 1 from "insert into t1 values(77)" + +# 1 from "insert into t2 values (NULL, changes(), NULL);" + +# 5 from "update t0 set x=x;" + +# 1 from "update t2 set v2=changes();" +# +do_test laststmtchanges-2.4 { + expr [db total_changes] - $::tc +} {8} + +# ---------------------------------------------------------------------------- +# 3.x - tests with after update trigger + +# changes() changed properly after update into table containing after trigger +do_test laststmtchanges-3.1 { + catchsql { + drop trigger r1; + delete from t2; delete from t2; + create trigger r1 after update on t1 for each row begin + insert into t2 values (NULL, changes(), NULL); + delete from t0 where oid=1 or oid=2; + update t2 set v2=changes(); + end; + update t1 set k=k; + select changes(); + } +} {0 1} + +# changes() unchanged upon entry into after update trigger +do_test laststmtchanges-3.2 { + catchsql { + select v1 from t2; + } +} {0 0} + +# changes() changed properly by delete within context of after update trigger +do_test laststmtchanges-3.3 { + catchsql { + select v2 from t2; + } +} {0 2} + +# ---------------------------------------------------------------------------- +# 4.x - tests with before delete trigger + +# changes() changed properly on delete from table containing before trigger +do_test laststmtchanges-4.1 { + catchsql { + drop trigger r1; + delete from t2; delete from t2; + create trigger r1 before delete on t1 for each row begin + insert into t2 values (NULL, changes(), NULL); + insert into t0 values (5); + update t2 set v2=changes(); + end; + delete from t1; + select changes(); + } +} {0 1} + +# changes() unchanged upon entry into before delete trigger +do_test laststmtchanges-4.2 { + catchsql { + select v1 from t2; + } +} {0 0} + +# changes() changed properly by insert within context of before delete trigger +do_test laststmtchanges-4.3 { + catchsql { + select v2 from t2; + } +} {0 1} + +# ---------------------------------------------------------------------------- +# 5.x - complex tests with temporary tables and nested instead of triggers +# These tests cannot run if the library does not have view support enabled. + +ifcapable view&&tempdb { + +do_test laststmtchanges-5.1 { + catchsql { + drop table t0; drop table t1; drop table t2; + create temp table t0(x); + create temp table t1 (k integer primary key); + create temp table t2 (k integer primary key); + create temp view v1 as select * from t1; + create temp view v2 as select * from t2; + create temp table n1 (k integer primary key, n); + create temp table n2 (k integer primary key, n); + insert into t0 values (1); + insert into t0 values (2); + insert into t0 values (1); + insert into t0 values (1); + insert into t0 values (1); + insert into t0 values (2); + insert into t0 values (2); + insert into t0 values (1); + create temp trigger r1 instead of insert on v1 for each row begin + insert into n1 values (NULL, changes()); + update t0 set x=x*10 where x=1; + insert into n1 values (NULL, changes()); + insert into t1 values (NEW.k); + insert into n1 values (NULL, changes()); + update t0 set x=x*10 where x=0; + insert into v2 values (100+NEW.k); + insert into n1 values (NULL, changes()); + end; + create temp trigger r2 instead of insert on v2 for each row begin + insert into n2 values (NULL, changes()); + insert into t2 values (1000+NEW.k); + insert into n2 values (NULL, changes()); + update t0 set x=x*100 where x=0; + insert into n2 values (NULL, changes()); + delete from t0 where x=2; + insert into n2 values (NULL, changes()); + end; + insert into t1 values (77); + select changes(); + } +} {0 1} + +do_test laststmtchanges-5.2 { + catchsql { + delete from t1 where k=88; + select changes(); + } +} {0 0} + +do_test laststmtchanges-5.3 { + catchsql { + insert into v1 values (5); + select changes(); + } +} {0 0} + +do_test laststmtchanges-5.4 { + catchsql { + select n from n1; + } +} {0 {0 5 1 0}} + +do_test laststmtchanges-5.5 { + catchsql { + select n from n2; + } +} {0 {0 1 0 3}} + +} ;# ifcapable view + + +# ---------------------------------------------------------------------------- +# 6.x - Test "DELETE FROM
    " in the absence of triggers +# +do_test laststmtchanges-6.1 { + execsql { + CREATE TABLE t3(a, b, c); + INSERT INTO t3 VALUES(1, 2, 3); + INSERT INTO t3 VALUES(4, 5, 6); + } +} {} +do_test laststmtchanges-6.2 { + execsql { + BEGIN; + DELETE FROM t3; + SELECT changes(); + } +} {2} +do_test laststmtchanges-6.3 { + execsql { + ROLLBACK; + BEGIN; + DELETE FROM t3 WHERE a IS NOT NULL; + SELECT changes(); + } +} {2} +do_test laststmtchanges-6.4 { + execsql { + ROLLBACK; + CREATE INDEX t3_i1 ON t3(a); + BEGIN; + DELETE FROM t3; + SELECT changes(); + } +} {2} +do_test laststmtchanges-6.5 { + execsql { ROLLBACK } + set nTotalChange [execsql {SELECT total_changes()}] + expr 0 +} {0} +do_test laststmtchanges-6.6 { + execsql { + SELECT total_changes(); + DELETE FROM t3; + SELECT total_changes(); + } +} [list $nTotalChange [expr $nTotalChange+2]] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/like.test b/components/external/SQLite-3.8.1/test/like.test new file mode 100644 index 0000000000000000000000000000000000000000..230dc74fed09fbaf69a9f3b68723ee2813bda60c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/like.test @@ -0,0 +1,897 @@ +# 2005 August 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the LIKE and GLOB operators and +# in particular the optimizations that occur to help those operators +# run faster. +# +# $Id: like.test,v 1.13 2009/06/07 23:45:11 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create some sample data to work with. +# +do_test like-1.0 { + execsql { + CREATE TABLE t1(x TEXT); + } + foreach str { + a + ab + abc + abcd + + acd + abd + bc + bcd + + xyz + ABC + CDE + {ABC abc xyz} + } { + db eval {INSERT INTO t1 VALUES(:str)} + } + execsql { + SELECT count(*) FROM t1; + } +} {12} + +# Test that both case sensitive and insensitive version of LIKE work. +# +do_test like-1.1 { + execsql { + SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1; + } +} {ABC abc} +do_test like-1.2 { + execsql { + SELECT x FROM t1 WHERE x GLOB 'abc' ORDER BY 1; + } +} {abc} +do_test like-1.3 { + execsql { + SELECT x FROM t1 WHERE x LIKE 'ABC' ORDER BY 1; + } +} {ABC abc} +do_test like-1.4 { + execsql { + SELECT x FROM t1 WHERE x LIKE 'aBc' ORDER BY 1; + } +} {ABC abc} +do_test like-1.5.1 { + # Use sqlite3_exec() to verify fix for ticket [25ee81271091] 2011-06-26 + sqlite3_exec db {PRAGMA case_sensitive_like=on} +} {0 {}} +do_test like-1.5.2 { + execsql { + SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1; + } +} {abc} +do_test like-1.5.3 { + execsql { + PRAGMA case_sensitive_like; -- no argument; does not change setting + SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1; + } +} {abc} +do_test like-1.6 { + execsql { + SELECT x FROM t1 WHERE x GLOB 'abc' ORDER BY 1; + } +} {abc} +do_test like-1.7 { + execsql { + SELECT x FROM t1 WHERE x LIKE 'ABC' ORDER BY 1; + } +} {ABC} +do_test like-1.8 { + execsql { + SELECT x FROM t1 WHERE x LIKE 'aBc' ORDER BY 1; + } +} {} +do_test like-1.9 { + execsql { + PRAGMA case_sensitive_like=off; + SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1; + } +} {ABC abc} +do_test like-1.10 { + execsql { + PRAGMA case_sensitive_like; -- No argument, does not change setting. + SELECT x FROM t1 WHERE x LIKE 'abc' ORDER BY 1; + } +} {ABC abc} + +# Tests of the REGEXP operator +# +do_test like-2.1 { + proc test_regexp {a b} { + return [regexp $a $b] + } + db function regexp -argcount 2 test_regexp + execsql { + SELECT x FROM t1 WHERE x REGEXP 'abc' ORDER BY 1; + } +} {{ABC abc xyz} abc abcd} +do_test like-2.2 { + execsql { + SELECT x FROM t1 WHERE x REGEXP '^abc' ORDER BY 1; + } +} {abc abcd} + +# Tests of the MATCH operator +# +do_test like-2.3 { + proc test_match {a b} { + return [string match $a $b] + } + db function match -argcount 2 test_match + execsql { + SELECT x FROM t1 WHERE x MATCH '*abc*' ORDER BY 1; + } +} {{ABC abc xyz} abc abcd} +do_test like-2.4 { + execsql { + SELECT x FROM t1 WHERE x MATCH 'abc*' ORDER BY 1; + } +} {abc abcd} + +# For the remaining tests, we need to have the like optimizations +# enabled. +# +ifcapable !like_opt { + finish_test + return +} + +# This procedure executes the SQL. Then it appends to the result the +# "sort" or "nosort" keyword (as in the cksort procedure above) then +# it appends the names of the table and index used. +# +proc queryplan {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + if {$::sqlite_sort_count} {set x sort} {set x nosort} + lappend data $x + set eqp [execsql "EXPLAIN QUERY PLAN $sql"] + # puts eqp=$eqp + foreach {a b c x} $eqp { + if {[regexp { TABLE (\w+ AS )?(\w+) USING COVERING INDEX (\w+)\y} \ + $x all as tab idx]} { + lappend data {} $idx + } elseif {[regexp { TABLE (\w+ AS )?(\w+) USING.* INDEX (\w+)\y} \ + $x all as tab idx]} { + lappend data $tab $idx + } elseif {[regexp { TABLE (\w+ AS )?(\w+)\y} $x all as tab]} { + lappend data $tab * + } + } + return $data +} + +# Perform tests on the like optimization. +# +# With no index on t1.x and with case sensitivity turned off, no optimization +# is performed. +# +do_test like-3.1 { + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1; + } +} {ABC {ABC abc xyz} abc abcd sort t1 *} +do_test like-3.2 { + set sqlite_like_count +} {12} + +# With an index on t1.x and case sensitivity on, optimize completely. +# +do_test like-3.3 { + set sqlite_like_count 0 + execsql { + PRAGMA case_sensitive_like=on; + CREATE INDEX i1 ON t1(x); + } + queryplan { + SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1; + } +} {abc abcd nosort {} i1} +do_test like-3.4 { + set sqlite_like_count +} 0 + +# The LIKE optimization still works when the RHS is a string with no +# wildcard. Ticket [e090183531fc2747] +# +do_test like-3.4.2 { + queryplan { + SELECT x FROM t1 WHERE x LIKE 'a' ORDER BY 1; + } +} {a nosort {} i1} +do_test like-3.4.3 { + queryplan { + SELECT x FROM t1 WHERE x LIKE 'ab' ORDER BY 1; + } +} {ab nosort {} i1} +do_test like-3.4.4 { + queryplan { + SELECT x FROM t1 WHERE x LIKE 'abcd' ORDER BY 1; + } +} {abcd nosort {} i1} +do_test like-3.4.5 { + queryplan { + SELECT x FROM t1 WHERE x LIKE 'abcde' ORDER BY 1; + } +} {nosort {} i1} + + +# Partial optimization when the pattern does not end in '%' +# +do_test like-3.5 { + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x LIKE 'a_c' ORDER BY 1; + } +} {abc nosort {} i1} +do_test like-3.6 { + set sqlite_like_count +} 6 +do_test like-3.7 { + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x LIKE 'ab%d' ORDER BY 1; + } +} {abcd abd nosort {} i1} +do_test like-3.8 { + set sqlite_like_count +} 4 +do_test like-3.9 { + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x LIKE 'a_c%' ORDER BY 1; + } +} {abc abcd nosort {} i1} +do_test like-3.10 { + set sqlite_like_count +} 6 + +# No optimization when the pattern begins with a wildcard. +# Note that the index is still used but only for sorting. +# +do_test like-3.11 { + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x LIKE '%bcd' ORDER BY 1; + } +} {abcd bcd nosort {} i1} +do_test like-3.12 { + set sqlite_like_count +} 12 + +# No optimization for case insensitive LIKE +# +do_test like-3.13 { + set sqlite_like_count 0 + db eval {PRAGMA case_sensitive_like=off;} + queryplan { + SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1; + } +} {ABC {ABC abc xyz} abc abcd nosort {} i1} +do_test like-3.14 { + set sqlite_like_count +} 12 + +# No optimization without an index. +# +do_test like-3.15 { + set sqlite_like_count 0 + db eval { + PRAGMA case_sensitive_like=on; + DROP INDEX i1; + } + queryplan { + SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1; + } +} {abc abcd sort t1 *} +do_test like-3.16 { + set sqlite_like_count +} 12 + +# No GLOB optimization without an index. +# +do_test like-3.17 { + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x GLOB 'abc*' ORDER BY 1; + } +} {abc abcd sort t1 *} +do_test like-3.18 { + set sqlite_like_count +} 12 + +# GLOB is optimized regardless of the case_sensitive_like setting. +# +do_test like-3.19 { + set sqlite_like_count 0 + db eval {CREATE INDEX i1 ON t1(x);} + queryplan { + SELECT x FROM t1 WHERE x GLOB 'abc*' ORDER BY 1; + } +} {abc abcd nosort {} i1} +do_test like-3.20 { + set sqlite_like_count +} 0 +do_test like-3.21 { + set sqlite_like_count 0 + db eval {PRAGMA case_sensitive_like=on;} + queryplan { + SELECT x FROM t1 WHERE x GLOB 'abc*' ORDER BY 1; + } +} {abc abcd nosort {} i1} +do_test like-3.22 { + set sqlite_like_count +} 0 +do_test like-3.23 { + set sqlite_like_count 0 + db eval {PRAGMA case_sensitive_like=off;} + queryplan { + SELECT x FROM t1 WHERE x GLOB 'a[bc]d' ORDER BY 1; + } +} {abd acd nosort {} i1} +do_test like-3.24 { + set sqlite_like_count +} 6 + +# GLOB optimization when there is no wildcard. Ticket [e090183531fc2747] +# +do_test like-3.25 { + queryplan { + SELECT x FROM t1 WHERE x GLOB 'a' ORDER BY 1; + } +} {a nosort {} i1} +do_test like-3.26 { + queryplan { + SELECT x FROM t1 WHERE x GLOB 'abcd' ORDER BY 1; + } +} {abcd nosort {} i1} +do_test like-3.27 { + queryplan { + SELECT x FROM t1 WHERE x GLOB 'abcde' ORDER BY 1; + } +} {nosort {} i1} + + + +# No optimization if the LHS of the LIKE is not a column name or +# if the RHS is not a string. +# +do_test like-4.1 { + execsql {PRAGMA case_sensitive_like=on} + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1 + } +} {abc abcd nosort {} i1} +do_test like-4.2 { + set sqlite_like_count +} 0 +do_test like-4.3 { + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE +x LIKE 'abc%' ORDER BY 1 + } +} {abc abcd nosort {} i1} +do_test like-4.4 { + set sqlite_like_count +} 12 +do_test like-4.5 { + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x LIKE ('ab' || 'c%') ORDER BY 1 + } +} {abc abcd nosort {} i1} +do_test like-4.6 { + set sqlite_like_count +} 12 + +# Collating sequences on the index disable the LIKE optimization. +# Or if the NOCASE collating sequence is used, the LIKE optimization +# is enabled when case_sensitive_like is OFF. +# +do_test like-5.1 { + execsql {PRAGMA case_sensitive_like=off} + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x LIKE 'abc%' ORDER BY 1 + } +} {ABC {ABC abc xyz} abc abcd nosort {} i1} +do_test like-5.2 { + set sqlite_like_count +} 12 +do_test like-5.3 { + execsql { + CREATE TABLE t2(x TEXT COLLATE NOCASE); + INSERT INTO t2 SELECT * FROM t1 ORDER BY rowid; + CREATE INDEX i2 ON t2(x COLLATE NOCASE); + } + set sqlite_like_count 0 + queryplan { + SELECT x FROM t2 WHERE x LIKE 'abc%' ORDER BY 1 + } +} {abc ABC {ABC abc xyz} abcd nosort {} i2} +do_test like-5.4 { + set sqlite_like_count +} 0 +do_test like-5.5 { + execsql { + PRAGMA case_sensitive_like=on; + } + set sqlite_like_count 0 + queryplan { + SELECT x FROM t2 WHERE x LIKE 'abc%' ORDER BY 1 + } +} {abc abcd nosort {} i2} +do_test like-5.6 { + set sqlite_like_count +} 12 +do_test like-5.7 { + execsql { + PRAGMA case_sensitive_like=off; + } + set sqlite_like_count 0 + queryplan { + SELECT x FROM t2 WHERE x GLOB 'abc*' ORDER BY 1 + } +} {abc abcd nosort {} i2} +do_test like-5.8 { + set sqlite_like_count +} 12 +do_test like-5.11 { + execsql {PRAGMA case_sensitive_like=off} + set sqlite_like_count 0 + queryplan { + SELECT x FROM t1 WHERE x LIKE 'ABC%' ORDER BY 1 + } +} {ABC {ABC abc xyz} abc abcd nosort {} i1} +do_test like-5.12 { + set sqlite_like_count +} 12 +do_test like-5.13 { + set sqlite_like_count 0 + queryplan { + SELECT x FROM t2 WHERE x LIKE 'ABC%' ORDER BY 1 + } +} {abc ABC {ABC abc xyz} abcd nosort {} i2} +do_test like-5.14 { + set sqlite_like_count +} 0 +do_test like-5.15 { + execsql { + PRAGMA case_sensitive_like=on; + } + set sqlite_like_count 0 + queryplan { + SELECT x FROM t2 WHERE x LIKE 'ABC%' ORDER BY 1 + } +} {ABC {ABC abc xyz} nosort {} i2} +do_test like-5.16 { + set sqlite_like_count +} 12 +do_test like-5.17 { + execsql { + PRAGMA case_sensitive_like=off; + } + set sqlite_like_count 0 + queryplan { + SELECT x FROM t2 WHERE x GLOB 'ABC*' ORDER BY 1 + } +} {ABC {ABC abc xyz} nosort {} i2} +do_test like-5.18 { + set sqlite_like_count +} 12 + +# Boundary case. The prefix for a LIKE comparison is rounded up +# when constructing the comparison. Example: "ab" becomes "ac". +# In other words, the last character is increased by one. +# +# Make sure this happens correctly when the last character is a +# "z" and we are doing case-insensitive comparisons. +# +# Ticket #2959 +# +do_test like-5.21 { + execsql { + PRAGMA case_sensitive_like=off; + INSERT INTO t2 VALUES('ZZ-upper-upper'); + INSERT INTO t2 VALUES('zZ-lower-upper'); + INSERT INTO t2 VALUES('Zz-upper-lower'); + INSERT INTO t2 VALUES('zz-lower-lower'); + } + queryplan { + SELECT x FROM t2 WHERE x LIKE 'zz%'; + } +} {zz-lower-lower zZ-lower-upper Zz-upper-lower ZZ-upper-upper nosort {} i2} +do_test like-5.22 { + queryplan { + SELECT x FROM t2 WHERE x LIKE 'zZ%'; + } +} {zz-lower-lower zZ-lower-upper Zz-upper-lower ZZ-upper-upper nosort {} i2} +do_test like-5.23 { + queryplan { + SELECT x FROM t2 WHERE x LIKE 'Zz%'; + } +} {zz-lower-lower zZ-lower-upper Zz-upper-lower ZZ-upper-upper nosort {} i2} +do_test like-5.24 { + queryplan { + SELECT x FROM t2 WHERE x LIKE 'ZZ%'; + } +} {zz-lower-lower zZ-lower-upper Zz-upper-lower ZZ-upper-upper nosort {} i2} +do_test like-5.25 { + db eval { + PRAGMA case_sensitive_like=on; + CREATE TABLE t3(x TEXT); + CREATE INDEX i3 ON t3(x); + INSERT INTO t3 VALUES('ZZ-upper-upper'); + INSERT INTO t3 VALUES('zZ-lower-upper'); + INSERT INTO t3 VALUES('Zz-upper-lower'); + INSERT INTO t3 VALUES('zz-lower-lower'); + } + queryplan { + SELECT x FROM t3 WHERE x LIKE 'zz%'; + } +} {zz-lower-lower nosort {} i3} +do_test like-5.26 { + queryplan { + SELECT x FROM t3 WHERE x LIKE 'zZ%'; + } +} {zZ-lower-upper nosort {} i3} +do_test like-5.27 { + queryplan { + SELECT x FROM t3 WHERE x LIKE 'Zz%'; + } +} {Zz-upper-lower nosort {} i3} +do_test like-5.28 { + queryplan { + SELECT x FROM t3 WHERE x LIKE 'ZZ%'; + } +} {ZZ-upper-upper nosort {} i3} + + +# ticket #2407 +# +# Make sure the LIKE prefix optimization does not strip off leading +# characters of the like pattern that happen to be quote characters. +# +do_test like-6.1 { + foreach x { 'abc 'bcd 'def 'ax } { + set x2 '[string map {' ''} $x]' + db eval "INSERT INTO t2 VALUES($x2)" + } + execsql { + SELECT * FROM t2 WHERE x LIKE '''a%' + } +} {'abc 'ax} + +do_test like-7.1 { + execsql { + SELECT rowid, * FROM t1 WHERE rowid GLOB '1*' ORDER BY rowid; + } +} {1 a 10 ABC 11 CDE 12 {ABC abc xyz}} + +# ticket #3345. +# +# Overloading the LIKE function with -1 for the number of arguments +# will overload both the 2-argument and the 3-argument LIKE. +# +do_test like-8.1 { + db eval { + CREATE TABLE t8(x); + INSERT INTO t8 VALUES('abcdef'); + INSERT INTO t8 VALUES('ghijkl'); + INSERT INTO t8 VALUES('mnopqr'); + SELECT 1, x FROM t8 WHERE x LIKE '%h%'; + SELECT 2, x FROM t8 WHERE x LIKE '%h%' ESCAPE 'x'; + } +} {1 ghijkl 2 ghijkl} +do_test like-8.2 { + proc newlike {args} {return 1} ;# Alternative LIKE is always return TRUE + db function like newlike ;# Uses -1 for nArg in sqlite3_create_function + db cache flush + db eval { + SELECT 1, x FROM t8 WHERE x LIKE '%h%'; + SELECT 2, x FROM t8 WHERE x LIKE '%h%' ESCAPE 'x'; + } +} {1 ghijkl 2 ghijkl} +do_test like-8.3 { + db function like -argcount 2 newlike + db eval { + SELECT 1, x FROM t8 WHERE x LIKE '%h%'; + SELECT 2, x FROM t8 WHERE x LIKE '%h%' ESCAPE 'x'; + } +} {1 abcdef 1 ghijkl 1 mnopqr 2 ghijkl} +do_test like-8.4 { + db function like -argcount 3 newlike + db eval { + SELECT 1, x FROM t8 WHERE x LIKE '%h%'; + SELECT 2, x FROM t8 WHERE x LIKE '%h%' ESCAPE 'x'; + } +} {1 abcdef 1 ghijkl 1 mnopqr 2 abcdef 2 ghijkl 2 mnopqr} + + +ifcapable like_opt&&!icu { + # Evaluate SQL. Return the result set followed by the + # and the number of full-scan steps. + # + db close + sqlite3 db test.db + proc count_steps {sql} { + set r [db eval $sql] + lappend r scan [db status step] sort [db status sort] + } + do_test like-9.1 { + count_steps { + SELECT x FROM t2 WHERE x LIKE 'x%' + } + } {xyz scan 0 sort 0} + do_test like-9.2 { + count_steps { + SELECT x FROM t2 WHERE x LIKE '_y%' + } + } {xyz scan 19 sort 0} + do_test like-9.3.1 { + set res [sqlite3_exec_hex db { + SELECT x FROM t2 WHERE x LIKE '%78%25' + }] + } {0 {x xyz}} + ifcapable explain { + do_test like-9.3.2 { + set res [sqlite3_exec_hex db { + EXPLAIN QUERY PLAN SELECT x FROM t2 WHERE x LIKE '%78%25' + }] + regexp {INDEX i2} $res + } {1} + } + do_test like-9.4.1 { + sqlite3_exec_hex db {INSERT INTO t2 VALUES('%ffhello')} + set res [sqlite3_exec_hex db { + SELECT substr(x,2) AS x FROM t2 WHERE +x LIKE '%ff%25' + }] + } {0 {x hello}} + do_test like-9.4.2 { + set res [sqlite3_exec_hex db { + SELECT substr(x,2) AS x FROM t2 WHERE x LIKE '%ff%25' + }] + } {0 {x hello}} + ifcapable explain { + do_test like-9.4.3 { + set res [sqlite3_exec_hex db { + EXPLAIN QUERY PLAN SELECT x FROM t2 WHERE x LIKE '%ff%25' + }] + regexp {SCAN TABLE t2} $res + } {1} + } + do_test like-9.5.1 { + set res [sqlite3_exec_hex db { + SELECT x FROM t2 WHERE x LIKE '%fe%25' + }] + } {0 {}} + ifcapable explain { + do_test like-9.5.2 { + set res [sqlite3_exec_hex db { + EXPLAIN QUERY PLAN SELECT x FROM t2 WHERE x LIKE '%fe%25' + }] + regexp {INDEX i2} $res + } {1} + } + + # Do an SQL statement. Append the search count to the end of the result. + # + proc count sql { + set ::sqlite_search_count 0 + set ::sqlite_like_count 0 + return [concat [execsql $sql] scan $::sqlite_search_count \ + like $::sqlite_like_count] + } + + # The LIKE and GLOB optimizations do not work on columns with + # affinity other than TEXT. + # Ticket #3901 + # + do_test like-10.1 { + db close + sqlite3 db test.db + execsql { + CREATE TABLE t10( + a INTEGER PRIMARY KEY, + b INTEGER COLLATE nocase UNIQUE, + c NUMBER COLLATE nocase UNIQUE, + d BLOB COLLATE nocase UNIQUE, + e COLLATE nocase UNIQUE, + f TEXT COLLATE nocase UNIQUE + ); + INSERT INTO t10 VALUES(1,1,1,1,1,1); + INSERT INTO t10 VALUES(12,12,12,12,12,12); + INSERT INTO t10 VALUES(123,123,123,123,123,123); + INSERT INTO t10 VALUES(234,234,234,234,234,234); + INSERT INTO t10 VALUES(345,345,345,345,345,345); + INSERT INTO t10 VALUES(45,45,45,45,45,45); + } + count { + SELECT a FROM t10 WHERE b LIKE '12%' ORDER BY +a; + } + } {12 123 scan 5 like 6} + do_test like-10.2 { + count { + SELECT a FROM t10 WHERE c LIKE '12%' ORDER BY +a; + } + } {12 123 scan 5 like 6} + do_test like-10.3 { + count { + SELECT a FROM t10 WHERE d LIKE '12%' ORDER BY +a; + } + } {12 123 scan 5 like 6} + do_test like-10.4 { + count { + SELECT a FROM t10 WHERE e LIKE '12%' ORDER BY +a; + } + } {12 123 scan 5 like 6} + do_test like-10.5 { + count { + SELECT a FROM t10 WHERE f LIKE '12%' ORDER BY +a; + } + } {12 123 scan 3 like 0} + do_test like-10.6 { + count { + SELECT a FROM t10 WHERE a LIKE '12%' ORDER BY +a; + } + } {12 123 scan 5 like 6} + do_test like-10.10 { + execsql { + CREATE TABLE t10b( + a INTEGER PRIMARY KEY, + b INTEGER UNIQUE, + c NUMBER UNIQUE, + d BLOB UNIQUE, + e UNIQUE, + f TEXT UNIQUE + ); + INSERT INTO t10b SELECT * FROM t10; + } + count { + SELECT a FROM t10b WHERE b GLOB '12*' ORDER BY +a; + } + } {12 123 scan 5 like 6} + do_test like-10.11 { + count { + SELECT a FROM t10b WHERE c GLOB '12*' ORDER BY +a; + } + } {12 123 scan 5 like 6} + do_test like-10.12 { + count { + SELECT a FROM t10b WHERE d GLOB '12*' ORDER BY +a; + } + } {12 123 scan 5 like 6} + do_test like-10.13 { + count { + SELECT a FROM t10b WHERE e GLOB '12*' ORDER BY +a; + } + } {12 123 scan 5 like 6} + do_test like-10.14 { + count { + SELECT a FROM t10b WHERE f GLOB '12*' ORDER BY +a; + } + } {12 123 scan 3 like 0} + do_test like-10.15 { + count { + SELECT a FROM t10b WHERE a GLOB '12*' ORDER BY +a; + } + } {12 123 scan 5 like 6} +} + +# LIKE and GLOB where the default collating sequence is not appropriate +# but an index with the appropriate collating sequence exists. +# +do_test like-11.0 { + execsql { + CREATE TABLE t11( + a INTEGER PRIMARY KEY, + b TEXT COLLATE nocase, + c TEXT COLLATE binary + ); + INSERT INTO t11 VALUES(1, 'a','a'); + INSERT INTO t11 VALUES(2, 'ab','ab'); + INSERT INTO t11 VALUES(3, 'abc','abc'); + INSERT INTO t11 VALUES(4, 'abcd','abcd'); + INSERT INTO t11 VALUES(5, 'A','A'); + INSERT INTO t11 VALUES(6, 'AB','AB'); + INSERT INTO t11 VALUES(7, 'ABC','ABC'); + INSERT INTO t11 VALUES(8, 'ABCD','ABCD'); + INSERT INTO t11 VALUES(9, 'x','x'); + INSERT INTO t11 VALUES(10, 'yz','yz'); + INSERT INTO t11 VALUES(11, 'X','X'); + INSERT INTO t11 VALUES(12, 'YZ','YZ'); + SELECT count(*) FROM t11; + } +} {12} +do_test like-11.1 { + db eval {PRAGMA case_sensitive_like=OFF;} + queryplan { + SELECT b FROM t11 WHERE b LIKE 'abc%' ORDER BY a; + } +} {abc abcd ABC ABCD nosort t11 *} +do_test like-11.2 { + db eval {PRAGMA case_sensitive_like=ON;} + queryplan { + SELECT b FROM t11 WHERE b LIKE 'abc%' ORDER BY a; + } +} {abc abcd nosort t11 *} +do_test like-11.3 { + db eval { + PRAGMA case_sensitive_like=OFF; + CREATE INDEX t11b ON t11(b); + } + queryplan { + SELECT b FROM t11 WHERE b LIKE 'abc%' ORDER BY +a; + } +} {abc abcd ABC ABCD sort {} t11b} +do_test like-11.4 { + db eval {PRAGMA case_sensitive_like=ON;} + queryplan { + SELECT b FROM t11 WHERE b LIKE 'abc%' ORDER BY a; + } +} {abc abcd nosort t11 *} +do_test like-11.5 { + db eval { + PRAGMA case_sensitive_like=OFF; + DROP INDEX t11b; + CREATE INDEX t11bnc ON t11(b COLLATE nocase); + } + queryplan { + SELECT b FROM t11 WHERE b LIKE 'abc%' ORDER BY +a; + } +} {abc abcd ABC ABCD sort {} t11bnc} +do_test like-11.6 { + db eval {CREATE INDEX t11bb ON t11(b COLLATE binary);} + queryplan { + SELECT b FROM t11 WHERE b LIKE 'abc%' ORDER BY +a; + } +} {abc abcd ABC ABCD sort {} t11bnc} +do_test like-11.7 { + db eval {PRAGMA case_sensitive_like=ON;} + queryplan { + SELECT b FROM t11 WHERE b LIKE 'abc%' ORDER BY +a; + } +} {abc abcd sort {} t11bb} +do_test like-11.8 { + db eval {PRAGMA case_sensitive_like=OFF;} + queryplan { + SELECT b FROM t11 WHERE b GLOB 'abc*' ORDER BY +a; + } +} {abc abcd sort {} t11bb} +do_test like-11.9 { + db eval { + CREATE INDEX t11cnc ON t11(c COLLATE nocase); + CREATE INDEX t11cb ON t11(c COLLATE binary); + } + queryplan { + SELECT c FROM t11 WHERE c LIKE 'abc%' ORDER BY +a; + } +} {abc abcd ABC ABCD sort {} t11cnc} +do_test like-11.10 { + queryplan { + SELECT c FROM t11 WHERE c GLOB 'abc*' ORDER BY +a; + } +} {abc abcd sort {} t11cb} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/like2.test b/components/external/SQLite-3.8.1/test/like2.test new file mode 100644 index 0000000000000000000000000000000000000000..4fd16420ade772538e9e351566bf9b3bdafda474 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/like2.test @@ -0,0 +1,1009 @@ +# 2008 May 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the LIKE and GLOB operators and +# in particular the optimizations that occur to help those operators +# run faster. +# +# $Id: like2.test,v 1.1 2008/05/26 18:33:41 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test like2-1.1 { + db eval { + CREATE TABLE t1(x INT, y COLLATE NOCASE); + INSERT INTO t1(x,y) VALUES(1,CAST(x'01' AS TEXT)); + INSERT INTO t1(x,y) VALUES(2,CAST(x'02' AS TEXT)); + INSERT INTO t1(x,y) VALUES(3,CAST(x'03' AS TEXT)); + INSERT INTO t1(x,y) VALUES(4,CAST(x'04' AS TEXT)); + INSERT INTO t1(x,y) VALUES(5,CAST(x'05' AS TEXT)); + INSERT INTO t1(x,y) VALUES(6,CAST(x'06' AS TEXT)); + INSERT INTO t1(x,y) VALUES(7,CAST(x'07' AS TEXT)); + INSERT INTO t1(x,y) VALUES(8,CAST(x'08' AS TEXT)); + INSERT INTO t1(x,y) VALUES(9,CAST(x'09' AS TEXT)); + INSERT INTO t1(x,y) VALUES(10,CAST(x'0a' AS TEXT)); + INSERT INTO t1(x,y) VALUES(11,CAST(x'0b' AS TEXT)); + INSERT INTO t1(x,y) VALUES(12,CAST(x'0c' AS TEXT)); + INSERT INTO t1(x,y) VALUES(13,CAST(x'0d' AS TEXT)); + INSERT INTO t1(x,y) VALUES(14,CAST(x'0e' AS TEXT)); + INSERT INTO t1(x,y) VALUES(15,CAST(x'0f' AS TEXT)); + INSERT INTO t1(x,y) VALUES(16,CAST(x'10' AS TEXT)); + INSERT INTO t1(x,y) VALUES(17,CAST(x'11' AS TEXT)); + INSERT INTO t1(x,y) VALUES(18,CAST(x'12' AS TEXT)); + INSERT INTO t1(x,y) VALUES(19,CAST(x'13' AS TEXT)); + INSERT INTO t1(x,y) VALUES(20,CAST(x'14' AS TEXT)); + INSERT INTO t1(x,y) VALUES(21,CAST(x'15' AS TEXT)); + INSERT INTO t1(x,y) VALUES(22,CAST(x'16' AS TEXT)); + INSERT INTO t1(x,y) VALUES(23,CAST(x'17' AS TEXT)); + INSERT INTO t1(x,y) VALUES(24,CAST(x'18' AS TEXT)); + INSERT INTO t1(x,y) VALUES(25,CAST(x'19' AS TEXT)); + INSERT INTO t1(x,y) VALUES(26,CAST(x'1a' AS TEXT)); + INSERT INTO t1(x,y) VALUES(27,CAST(x'1b' AS TEXT)); + INSERT INTO t1(x,y) VALUES(28,CAST(x'1c' AS TEXT)); + INSERT INTO t1(x,y) VALUES(29,CAST(x'1d' AS TEXT)); + INSERT INTO t1(x,y) VALUES(30,CAST(x'1e' AS TEXT)); + INSERT INTO t1(x,y) VALUES(31,CAST(x'1f' AS TEXT)); + INSERT INTO t1(x,y) VALUES(32,' '); + INSERT INTO t1(x,y) VALUES(33,'!'); + INSERT INTO t1(x,y) VALUES(34,'"'); + INSERT INTO t1(x,y) VALUES(35,'#'); + INSERT INTO t1(x,y) VALUES(36,'$'); + INSERT INTO t1(x,y) VALUES(37,'%'); + INSERT INTO t1(x,y) VALUES(38,'&'); + INSERT INTO t1(x,y) VALUES(39,''''); + INSERT INTO t1(x,y) VALUES(40,'('); + INSERT INTO t1(x,y) VALUES(41,')'); + INSERT INTO t1(x,y) VALUES(42,'*'); + INSERT INTO t1(x,y) VALUES(43,'+'); + INSERT INTO t1(x,y) VALUES(44,','); + INSERT INTO t1(x,y) VALUES(45,'-'); + INSERT INTO t1(x,y) VALUES(46,'.'); + INSERT INTO t1(x,y) VALUES(47,'/'); + INSERT INTO t1(x,y) VALUES(48,'0'); + INSERT INTO t1(x,y) VALUES(49,'1'); + INSERT INTO t1(x,y) VALUES(50,'2'); + INSERT INTO t1(x,y) VALUES(51,'3'); + INSERT INTO t1(x,y) VALUES(52,'4'); + INSERT INTO t1(x,y) VALUES(53,'5'); + INSERT INTO t1(x,y) VALUES(54,'6'); + INSERT INTO t1(x,y) VALUES(55,'7'); + INSERT INTO t1(x,y) VALUES(56,'8'); + INSERT INTO t1(x,y) VALUES(57,'9'); + INSERT INTO t1(x,y) VALUES(58,':'); + INSERT INTO t1(x,y) VALUES(59,';'); + INSERT INTO t1(x,y) VALUES(60,'<'); + INSERT INTO t1(x,y) VALUES(61,'='); + INSERT INTO t1(x,y) VALUES(62,'>'); + INSERT INTO t1(x,y) VALUES(63,'?'); + INSERT INTO t1(x,y) VALUES(64,'@'); + INSERT INTO t1(x,y) VALUES(65,'A'); + INSERT INTO t1(x,y) VALUES(66,'B'); + INSERT INTO t1(x,y) VALUES(67,'C'); + INSERT INTO t1(x,y) VALUES(68,'D'); + INSERT INTO t1(x,y) VALUES(69,'E'); + INSERT INTO t1(x,y) VALUES(70,'F'); + INSERT INTO t1(x,y) VALUES(71,'G'); + INSERT INTO t1(x,y) VALUES(72,'H'); + INSERT INTO t1(x,y) VALUES(73,'I'); + INSERT INTO t1(x,y) VALUES(74,'J'); + INSERT INTO t1(x,y) VALUES(75,'K'); + INSERT INTO t1(x,y) VALUES(76,'L'); + INSERT INTO t1(x,y) VALUES(77,'M'); + INSERT INTO t1(x,y) VALUES(78,'N'); + INSERT INTO t1(x,y) VALUES(79,'O'); + INSERT INTO t1(x,y) VALUES(80,'P'); + INSERT INTO t1(x,y) VALUES(81,'Q'); + INSERT INTO t1(x,y) VALUES(82,'R'); + INSERT INTO t1(x,y) VALUES(83,'S'); + INSERT INTO t1(x,y) VALUES(84,'T'); + INSERT INTO t1(x,y) VALUES(85,'U'); + INSERT INTO t1(x,y) VALUES(86,'V'); + INSERT INTO t1(x,y) VALUES(87,'W'); + INSERT INTO t1(x,y) VALUES(88,'X'); + INSERT INTO t1(x,y) VALUES(89,'Y'); + INSERT INTO t1(x,y) VALUES(90,'Z'); + INSERT INTO t1(x,y) VALUES(91,'['); + INSERT INTO t1(x,y) VALUES(92,'\'); + INSERT INTO t1(x,y) VALUES(93,']'); + INSERT INTO t1(x,y) VALUES(94,'^'); + INSERT INTO t1(x,y) VALUES(95,'_'); + INSERT INTO t1(x,y) VALUES(96,'`'); + INSERT INTO t1(x,y) VALUES(97,'a'); + INSERT INTO t1(x,y) VALUES(98,'b'); + INSERT INTO t1(x,y) VALUES(99,'c'); + INSERT INTO t1(x,y) VALUES(100,'d'); + INSERT INTO t1(x,y) VALUES(101,'e'); + INSERT INTO t1(x,y) VALUES(102,'f'); + INSERT INTO t1(x,y) VALUES(103,'g'); + INSERT INTO t1(x,y) VALUES(104,'h'); + INSERT INTO t1(x,y) VALUES(105,'i'); + INSERT INTO t1(x,y) VALUES(106,'j'); + INSERT INTO t1(x,y) VALUES(107,'k'); + INSERT INTO t1(x,y) VALUES(108,'l'); + INSERT INTO t1(x,y) VALUES(109,'m'); + INSERT INTO t1(x,y) VALUES(110,'n'); + INSERT INTO t1(x,y) VALUES(111,'o'); + INSERT INTO t1(x,y) VALUES(112,'p'); + INSERT INTO t1(x,y) VALUES(113,'q'); + INSERT INTO t1(x,y) VALUES(114,'r'); + INSERT INTO t1(x,y) VALUES(115,'s'); + INSERT INTO t1(x,y) VALUES(116,'t'); + INSERT INTO t1(x,y) VALUES(117,'u'); + INSERT INTO t1(x,y) VALUES(118,'v'); + INSERT INTO t1(x,y) VALUES(119,'w'); + INSERT INTO t1(x,y) VALUES(120,'x'); + INSERT INTO t1(x,y) VALUES(121,'y'); + INSERT INTO t1(x,y) VALUES(122,'z'); + INSERT INTO t1(x,y) VALUES(123,'{'); + INSERT INTO t1(x,y) VALUES(124,'|'); + INSERT INTO t1(x,y) VALUES(125,'}'); + INSERT INTO t1(x,y) VALUES(126,'~'); + INSERT INTO t1(x,y) VALUES(127,CAST(x'7f' AS TEXT)); + SELECT count(*) FROM t1; + } +} {127} +do_test like2-1.2 { + db eval { + CREATE TABLE t2(x INT, y COLLATE NOCASE); + INSERT INTO t2 SELECT * FROM t1; + CREATE INDEX i2 ON t2(y); + SELECT count(*) FROM t2; + } +} {127} +do_test like2-1.3 { + db eval { + CREATE TABLE t3(x INT, y COLLATE NOCASE); + INSERT INTO t3 SELECT x, 'abc' || y || 'xyz' FROM t1; + CREATE INDEX i3 ON t3(y); + SELECT count(*) FROM t2; + } +} {127} +do_test like-2.32.1 { + db eval "SELECT x FROM t1 WHERE y LIKE ' %'" +} {32} +do_test like-2.32.2 { + db eval "SELECT x FROM t2 WHERE y LIKE ' %'" +} {32} +do_test like-2.32.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc %'" +} {32} +do_test like-2.33.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '!%'" +} {33} +do_test like-2.33.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '!%'" +} {33} +do_test like-2.33.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc!%'" +} {33} +do_test like-2.34.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '\"%'" +} {34} +do_test like-2.34.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '\"%'" +} {34} +do_test like-2.34.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc\"%'" +} {34} +do_test like-2.35.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '#%'" +} {35} +do_test like-2.35.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '#%'" +} {35} +do_test like-2.35.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc#%'" +} {35} +do_test like-2.36.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '\$%'" +} {36} +do_test like-2.36.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '\$%'" +} {36} +do_test like-2.36.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc\$%'" +} {36} +do_test like-2.38.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '&%'" +} {38} +do_test like-2.38.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '&%'" +} {38} +do_test like-2.38.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc&%'" +} {38} +do_test like-2.39.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '''%'" +} {39} +do_test like-2.39.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '''%'" +} {39} +do_test like-2.39.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc''%'" +} {39} +do_test like-2.40.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '(%'" +} {40} +do_test like-2.40.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '(%'" +} {40} +do_test like-2.40.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc(%'" +} {40} +do_test like-2.41.1 { + db eval "SELECT x FROM t1 WHERE y LIKE ')%'" +} {41} +do_test like-2.41.2 { + db eval "SELECT x FROM t2 WHERE y LIKE ')%'" +} {41} +do_test like-2.41.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc)%'" +} {41} +do_test like-2.42.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '*%'" +} {42} +do_test like-2.42.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '*%'" +} {42} +do_test like-2.42.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc*%'" +} {42} +do_test like-2.43.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '+%'" +} {43} +do_test like-2.43.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '+%'" +} {43} +do_test like-2.43.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc+%'" +} {43} +do_test like-2.44.1 { + db eval "SELECT x FROM t1 WHERE y LIKE ',%'" +} {44} +do_test like-2.44.2 { + db eval "SELECT x FROM t2 WHERE y LIKE ',%'" +} {44} +do_test like-2.44.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc,%'" +} {44} +do_test like-2.45.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '-%'" +} {45} +do_test like-2.45.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '-%'" +} {45} +do_test like-2.45.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc-%'" +} {45} +do_test like-2.46.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '.%'" +} {46} +do_test like-2.46.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '.%'" +} {46} +do_test like-2.46.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc.%'" +} {46} +do_test like-2.47.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '/%'" +} {47} +do_test like-2.47.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '/%'" +} {47} +do_test like-2.47.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc/%'" +} {47} +do_test like-2.48.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '0%'" +} {48} +do_test like-2.48.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '0%'" +} {48} +do_test like-2.48.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc0%'" +} {48} +do_test like-2.49.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '1%'" +} {49} +do_test like-2.49.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '1%'" +} {49} +do_test like-2.49.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc1%'" +} {49} +do_test like-2.50.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '2%'" +} {50} +do_test like-2.50.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '2%'" +} {50} +do_test like-2.50.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc2%'" +} {50} +do_test like-2.51.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '3%'" +} {51} +do_test like-2.51.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '3%'" +} {51} +do_test like-2.51.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc3%'" +} {51} +do_test like-2.52.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '4%'" +} {52} +do_test like-2.52.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '4%'" +} {52} +do_test like-2.52.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc4%'" +} {52} +do_test like-2.53.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '5%'" +} {53} +do_test like-2.53.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '5%'" +} {53} +do_test like-2.53.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc5%'" +} {53} +do_test like-2.54.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '6%'" +} {54} +do_test like-2.54.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '6%'" +} {54} +do_test like-2.54.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc6%'" +} {54} +do_test like-2.55.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '7%'" +} {55} +do_test like-2.55.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '7%'" +} {55} +do_test like-2.55.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc7%'" +} {55} +do_test like-2.56.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '8%'" +} {56} +do_test like-2.56.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '8%'" +} {56} +do_test like-2.56.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc8%'" +} {56} +do_test like-2.57.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '9%'" +} {57} +do_test like-2.57.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '9%'" +} {57} +do_test like-2.57.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc9%'" +} {57} +do_test like-2.58.1 { + db eval "SELECT x FROM t1 WHERE y LIKE ':%'" +} {58} +do_test like-2.58.2 { + db eval "SELECT x FROM t2 WHERE y LIKE ':%'" +} {58} +do_test like-2.58.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc:%'" +} {58} +do_test like-2.59.1 { + db eval "SELECT x FROM t1 WHERE y LIKE ';%'" +} {59} +do_test like-2.59.2 { + db eval "SELECT x FROM t2 WHERE y LIKE ';%'" +} {59} +do_test like-2.59.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc;%'" +} {59} +do_test like-2.60.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '<%'" +} {60} +do_test like-2.60.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '<%'" +} {60} +do_test like-2.60.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc<%'" +} {60} +do_test like-2.61.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '=%'" +} {61} +do_test like-2.61.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '=%'" +} {61} +do_test like-2.61.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc=%'" +} {61} +do_test like-2.62.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '>%'" +} {62} +do_test like-2.62.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '>%'" +} {62} +do_test like-2.62.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc>%'" +} {62} +do_test like-2.63.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '?%'" +} {63} +do_test like-2.63.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '?%'" +} {63} +do_test like-2.63.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc?%'" +} {63} +do_test like-2.64.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '@%'" +} {64} +do_test like-2.64.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '@%'" +} {64} +do_test like-2.64.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc@%'" +} {64} +do_test like-2.65.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'A%'" +} {65 97} +do_test like-2.65.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'A%'" +} {65 97} +do_test like-2.65.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcA%'" +} {65 97} +do_test like-2.66.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'B%'" +} {66 98} +do_test like-2.66.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'B%'" +} {66 98} +do_test like-2.66.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcB%'" +} {66 98} +do_test like-2.67.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'C%'" +} {67 99} +do_test like-2.67.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'C%'" +} {67 99} +do_test like-2.67.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcC%'" +} {67 99} +do_test like-2.68.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'D%'" +} {68 100} +do_test like-2.68.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'D%'" +} {68 100} +do_test like-2.68.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcD%'" +} {68 100} +do_test like-2.69.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'E%'" +} {69 101} +do_test like-2.69.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'E%'" +} {69 101} +do_test like-2.69.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcE%'" +} {69 101} +do_test like-2.70.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'F%'" +} {70 102} +do_test like-2.70.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'F%'" +} {70 102} +do_test like-2.70.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcF%'" +} {70 102} +do_test like-2.71.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'G%'" +} {71 103} +do_test like-2.71.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'G%'" +} {71 103} +do_test like-2.71.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcG%'" +} {71 103} +do_test like-2.72.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'H%'" +} {72 104} +do_test like-2.72.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'H%'" +} {72 104} +do_test like-2.72.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcH%'" +} {72 104} +do_test like-2.73.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'I%'" +} {73 105} +do_test like-2.73.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'I%'" +} {73 105} +do_test like-2.73.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcI%'" +} {73 105} +do_test like-2.74.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'J%'" +} {74 106} +do_test like-2.74.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'J%'" +} {74 106} +do_test like-2.74.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcJ%'" +} {74 106} +do_test like-2.75.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'K%'" +} {75 107} +do_test like-2.75.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'K%'" +} {75 107} +do_test like-2.75.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcK%'" +} {75 107} +do_test like-2.76.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'L%'" +} {76 108} +do_test like-2.76.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'L%'" +} {76 108} +do_test like-2.76.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcL%'" +} {76 108} +do_test like-2.77.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'M%'" +} {77 109} +do_test like-2.77.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'M%'" +} {77 109} +do_test like-2.77.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcM%'" +} {77 109} +do_test like-2.78.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'N%'" +} {78 110} +do_test like-2.78.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'N%'" +} {78 110} +do_test like-2.78.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcN%'" +} {78 110} +do_test like-2.79.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'O%'" +} {79 111} +do_test like-2.79.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'O%'" +} {79 111} +do_test like-2.79.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcO%'" +} {79 111} +do_test like-2.80.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'P%'" +} {80 112} +do_test like-2.80.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'P%'" +} {80 112} +do_test like-2.80.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcP%'" +} {80 112} +do_test like-2.81.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'Q%'" +} {81 113} +do_test like-2.81.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'Q%'" +} {81 113} +do_test like-2.81.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcQ%'" +} {81 113} +do_test like-2.82.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'R%'" +} {82 114} +do_test like-2.82.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'R%'" +} {82 114} +do_test like-2.82.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcR%'" +} {82 114} +do_test like-2.83.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'S%'" +} {83 115} +do_test like-2.83.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'S%'" +} {83 115} +do_test like-2.83.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcS%'" +} {83 115} +do_test like-2.84.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'T%'" +} {84 116} +do_test like-2.84.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'T%'" +} {84 116} +do_test like-2.84.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcT%'" +} {84 116} +do_test like-2.85.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'U%'" +} {85 117} +do_test like-2.85.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'U%'" +} {85 117} +do_test like-2.85.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcU%'" +} {85 117} +do_test like-2.86.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'V%'" +} {86 118} +do_test like-2.86.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'V%'" +} {86 118} +do_test like-2.86.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcV%'" +} {86 118} +do_test like-2.87.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'W%'" +} {87 119} +do_test like-2.87.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'W%'" +} {87 119} +do_test like-2.87.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcW%'" +} {87 119} +do_test like-2.88.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'X%'" +} {88 120} +do_test like-2.88.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'X%'" +} {88 120} +do_test like-2.88.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcX%'" +} {88 120} +do_test like-2.89.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'Y%'" +} {89 121} +do_test like-2.89.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'Y%'" +} {89 121} +do_test like-2.89.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcY%'" +} {89 121} +do_test like-2.90.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'Z%'" +} {90 122} +do_test like-2.90.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'Z%'" +} {90 122} +do_test like-2.90.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcZ%'" +} {90 122} +do_test like-2.91.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '\[%'" +} {91} +do_test like-2.91.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '\[%'" +} {91} +do_test like-2.91.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc\[%'" +} {91} +do_test like-2.92.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '\\%'" +} {92} +do_test like-2.92.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '\\%'" +} {92} +do_test like-2.92.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc\\%'" +} {92} +do_test like-2.93.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '\]%'" +} {93} +do_test like-2.93.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '\]%'" +} {93} +do_test like-2.93.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc\]%'" +} {93} +do_test like-2.94.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '^%'" +} {94} +do_test like-2.94.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '^%'" +} {94} +do_test like-2.94.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc^%'" +} {94} +do_test like-2.96.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '`%'" +} {96} +do_test like-2.96.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '`%'" +} {96} +do_test like-2.96.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc`%'" +} {96} +do_test like-2.97.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'a%'" +} {65 97} +do_test like-2.97.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'a%'" +} {65 97} +do_test like-2.97.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abca%'" +} {65 97} +do_test like-2.98.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'b%'" +} {66 98} +do_test like-2.98.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'b%'" +} {66 98} +do_test like-2.98.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcb%'" +} {66 98} +do_test like-2.99.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'c%'" +} {67 99} +do_test like-2.99.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'c%'" +} {67 99} +do_test like-2.99.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcc%'" +} {67 99} +do_test like-2.100.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'd%'" +} {68 100} +do_test like-2.100.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'd%'" +} {68 100} +do_test like-2.100.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcd%'" +} {68 100} +do_test like-2.101.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'e%'" +} {69 101} +do_test like-2.101.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'e%'" +} {69 101} +do_test like-2.101.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abce%'" +} {69 101} +do_test like-2.102.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'f%'" +} {70 102} +do_test like-2.102.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'f%'" +} {70 102} +do_test like-2.102.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcf%'" +} {70 102} +do_test like-2.103.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'g%'" +} {71 103} +do_test like-2.103.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'g%'" +} {71 103} +do_test like-2.103.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcg%'" +} {71 103} +do_test like-2.104.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'h%'" +} {72 104} +do_test like-2.104.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'h%'" +} {72 104} +do_test like-2.104.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abch%'" +} {72 104} +do_test like-2.105.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'i%'" +} {73 105} +do_test like-2.105.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'i%'" +} {73 105} +do_test like-2.105.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abci%'" +} {73 105} +do_test like-2.106.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'j%'" +} {74 106} +do_test like-2.106.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'j%'" +} {74 106} +do_test like-2.106.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcj%'" +} {74 106} +do_test like-2.107.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'k%'" +} {75 107} +do_test like-2.107.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'k%'" +} {75 107} +do_test like-2.107.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abck%'" +} {75 107} +do_test like-2.108.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'l%'" +} {76 108} +do_test like-2.108.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'l%'" +} {76 108} +do_test like-2.108.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcl%'" +} {76 108} +do_test like-2.109.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'm%'" +} {77 109} +do_test like-2.109.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'm%'" +} {77 109} +do_test like-2.109.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcm%'" +} {77 109} +do_test like-2.110.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'n%'" +} {78 110} +do_test like-2.110.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'n%'" +} {78 110} +do_test like-2.110.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcn%'" +} {78 110} +do_test like-2.111.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'o%'" +} {79 111} +do_test like-2.111.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'o%'" +} {79 111} +do_test like-2.111.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abco%'" +} {79 111} +do_test like-2.112.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'p%'" +} {80 112} +do_test like-2.112.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'p%'" +} {80 112} +do_test like-2.112.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcp%'" +} {80 112} +do_test like-2.113.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'q%'" +} {81 113} +do_test like-2.113.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'q%'" +} {81 113} +do_test like-2.113.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcq%'" +} {81 113} +do_test like-2.114.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'r%'" +} {82 114} +do_test like-2.114.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'r%'" +} {82 114} +do_test like-2.114.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcr%'" +} {82 114} +do_test like-2.115.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 's%'" +} {83 115} +do_test like-2.115.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 's%'" +} {83 115} +do_test like-2.115.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcs%'" +} {83 115} +do_test like-2.116.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 't%'" +} {84 116} +do_test like-2.116.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 't%'" +} {84 116} +do_test like-2.116.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abct%'" +} {84 116} +do_test like-2.117.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'u%'" +} {85 117} +do_test like-2.117.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'u%'" +} {85 117} +do_test like-2.117.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcu%'" +} {85 117} +do_test like-2.118.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'v%'" +} {86 118} +do_test like-2.118.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'v%'" +} {86 118} +do_test like-2.118.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcv%'" +} {86 118} +do_test like-2.119.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'w%'" +} {87 119} +do_test like-2.119.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'w%'" +} {87 119} +do_test like-2.119.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcw%'" +} {87 119} +do_test like-2.120.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'x%'" +} {88 120} +do_test like-2.120.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'x%'" +} {88 120} +do_test like-2.120.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcx%'" +} {88 120} +do_test like-2.121.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'y%'" +} {89 121} +do_test like-2.121.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'y%'" +} {89 121} +do_test like-2.121.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcy%'" +} {89 121} +do_test like-2.122.1 { + db eval "SELECT x FROM t1 WHERE y LIKE 'z%'" +} {90 122} +do_test like-2.122.2 { + db eval "SELECT x FROM t2 WHERE y LIKE 'z%'" +} {90 122} +do_test like-2.122.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abcz%'" +} {90 122} +do_test like-2.123.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '\173%'" +} {123} +do_test like-2.123.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '\173%'" +} {123} +do_test like-2.123.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc\173%'" +} {123} +do_test like-2.124.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '|%'" +} {124} +do_test like-2.124.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '|%'" +} {124} +do_test like-2.124.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc|%'" +} {124} +do_test like-2.125.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '\175%'" +} {125} +do_test like-2.125.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '\175%'" +} {125} +do_test like-2.125.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc\175%'" +} {125} +do_test like-2.126.1 { + db eval "SELECT x FROM t1 WHERE y LIKE '~%'" +} {126} +do_test like-2.126.2 { + db eval "SELECT x FROM t2 WHERE y LIKE '~%'" +} {126} +do_test like-2.126.3 { + db eval "SELECT x FROM t3 WHERE y LIKE 'abc~%'" +} {126} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/limit.test b/components/external/SQLite-3.8.1/test/limit.test new file mode 100644 index 0000000000000000000000000000000000000000..c5b75c2b6916cfcc0d7fe88111a61f5cfebf4990 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/limit.test @@ -0,0 +1,619 @@ +# 2001 November 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the LIMIT ... OFFSET ... clause +# of SELECT statements. +# +# $Id: limit.test,v 1.32 2008/08/02 03:50:39 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build some test data +# +execsql { + CREATE TABLE t1(x int, y int); + BEGIN; +} +for {set i 1} {$i<=32} {incr i} { + for {set j 0} {(1<<$j)<$i} {incr j} {} + execsql "INSERT INTO t1 VALUES([expr {32-$i}],[expr {10-$j}])" +} +execsql { + COMMIT; +} + +do_test limit-1.0 { + execsql {SELECT count(*) FROM t1} +} {32} +do_test limit-1.1 { + execsql {SELECT count(*) FROM t1 LIMIT 5} +} {32} +do_test limit-1.2.1 { + execsql {SELECT x FROM t1 ORDER BY x LIMIT 5} +} {0 1 2 3 4} +do_test limit-1.2.2 { + execsql {SELECT x FROM t1 ORDER BY x LIMIT 5 OFFSET 2} +} {2 3 4 5 6} +do_test limit-1.2.3 { + execsql {SELECT x FROM t1 ORDER BY x+1 LIMIT 5 OFFSET -2} +} {0 1 2 3 4} +do_test limit-1.2.4 { + execsql {SELECT x FROM t1 ORDER BY x+1 LIMIT 2, -5} +} {2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31} +do_test limit-1.2.5 { + execsql {SELECT x FROM t1 ORDER BY x+1 LIMIT -2, 5} +} {0 1 2 3 4} +do_test limit-1.2.6 { + execsql {SELECT x FROM t1 ORDER BY x+1 LIMIT -2, -5} +} {0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31} +do_test limit-1.2.7 { + execsql {SELECT x FROM t1 ORDER BY x LIMIT 2, 5} +} {2 3 4 5 6} +do_test limit-1.3 { + execsql {SELECT x FROM t1 ORDER BY x LIMIT 5 OFFSET 5} +} {5 6 7 8 9} +do_test limit-1.4.1 { + execsql {SELECT x FROM t1 ORDER BY x LIMIT 50 OFFSET 30} +} {30 31} +do_test limit-1.4.2 { + execsql {SELECT x FROM t1 ORDER BY x LIMIT 30, 50} +} {30 31} +do_test limit-1.5 { + execsql {SELECT x FROM t1 ORDER BY x LIMIT 50 OFFSET 50} +} {} +do_test limit-1.6 { + execsql {SELECT * FROM t1 AS a, t1 AS b ORDER BY a.x, b.x LIMIT 5} +} {0 5 0 5 0 5 1 5 0 5 2 5 0 5 3 5 0 5 4 5} +do_test limit-1.7 { + execsql {SELECT * FROM t1 AS a, t1 AS b ORDER BY a.x, b.x LIMIT 5 OFFSET 32} +} {1 5 0 5 1 5 1 5 1 5 2 5 1 5 3 5 1 5 4 5} + +ifcapable {view && subquery} { + do_test limit-2.1 { + execsql { + CREATE VIEW v1 AS SELECT * FROM t1 LIMIT 2; + SELECT count(*) FROM (SELECT * FROM v1); + } + } 2 +} ;# ifcapable view +do_test limit-2.2 { + execsql { + CREATE TABLE t2 AS SELECT * FROM t1 LIMIT 2; + SELECT count(*) FROM t2; + } +} 2 +ifcapable subquery { + do_test limit-2.3 { + execsql { + SELECT count(*) FROM t1 WHERE rowid IN (SELECT rowid FROM t1 LIMIT 2); + } + } 2 +} + +ifcapable subquery { + do_test limit-3.1 { + execsql { + SELECT z FROM (SELECT y*10+x AS z FROM t1 ORDER BY x LIMIT 10) + ORDER BY z LIMIT 5; + } + } {50 51 52 53 54} +} + +do_test limit-4.1 { + ifcapable subquery { + execsql { + BEGIN; + CREATE TABLE t3(x); + INSERT INTO t3 SELECT x FROM t1 ORDER BY x LIMIT 10 OFFSET 1; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + INSERT INTO t3 SELECT x+(SELECT max(x) FROM t3) FROM t3; + END; + SELECT count(*) FROM t3; + } + } else { + execsql { + BEGIN; + CREATE TABLE t3(x); + INSERT INTO t3 SELECT x FROM t1 ORDER BY x LIMIT 10 OFFSET 1; + } + for {set i 0} {$i<10} {incr i} { + set max_x_t3 [execsql {SELECT max(x) FROM t3}] + execsql "INSERT INTO t3 SELECT x+$max_x_t3 FROM t3;" + } + execsql { + END; + SELECT count(*) FROM t3; + } + } +} {10240} +do_test limit-4.2 { + execsql { + SELECT x FROM t3 LIMIT 2 OFFSET 10000 + } +} {10001 10002} +do_test limit-4.3 { + execsql { + CREATE TABLE t4 AS SELECT x, + 'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x || + 'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x || + 'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x || + 'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x || + 'abcdefghijklmnopqrstuvwyxz ABCDEFGHIJKLMNOPQRSTUVWYXZ' || x AS y + FROM t3 LIMIT 1000; + SELECT x FROM t4 ORDER BY y DESC LIMIT 1 OFFSET 999; + } +} {1000} + +do_test limit-5.1 { + execsql { + CREATE TABLE t5(x,y); + INSERT INTO t5 SELECT x-y, x+y FROM t1 WHERE x BETWEEN 10 AND 15 + ORDER BY x LIMIT 2; + SELECT * FROM t5 ORDER BY x; + } +} {5 15 6 16} +do_test limit-5.2 { + execsql { + DELETE FROM t5; + INSERT INTO t5 SELECT x-y, x+y FROM t1 WHERE x BETWEEN 10 AND 15 + ORDER BY x DESC LIMIT 2; + SELECT * FROM t5 ORDER BY x; + } +} {9 19 10 20} +do_test limit-5.3 { + execsql { + DELETE FROM t5; + INSERT INTO t5 SELECT x-y, x+y FROM t1 WHERE x ORDER BY x DESC LIMIT 31; + SELECT * FROM t5 ORDER BY x LIMIT 2; + } +} {-4 6 -3 7} +do_test limit-5.4 { + execsql { + SELECT * FROM t5 ORDER BY x DESC, y DESC LIMIT 2; + } +} {21 41 21 39} +do_test limit-5.5 { + execsql { + DELETE FROM t5; + INSERT INTO t5 SELECT a.x*100+b.x, a.y*100+b.y FROM t1 AS a, t1 AS b + ORDER BY 1, 2 LIMIT 1000; + SELECT count(*), sum(x), sum(y), min(x), max(x), min(y), max(y) FROM t5; + } +} {1000 1528204 593161 0 3107 505 1005} + +# There is some contraversy about whether LIMIT 0 should be the same as +# no limit at all or if LIMIT 0 should result in zero output rows. +# +do_test limit-6.1 { + execsql { + BEGIN; + CREATE TABLE t6(a); + INSERT INTO t6 VALUES(1); + INSERT INTO t6 VALUES(2); + INSERT INTO t6 SELECT a+2 FROM t6; + COMMIT; + SELECT * FROM t6; + } +} {1 2 3 4} +do_test limit-6.2 { + execsql { + SELECT * FROM t6 LIMIT -1 OFFSET -1; + } +} {1 2 3 4} +do_test limit-6.3 { + execsql { + SELECT * FROM t6 LIMIT 2 OFFSET -123; + } +} {1 2} +do_test limit-6.4 { + execsql { + SELECT * FROM t6 LIMIT -432 OFFSET 2; + } +} {3 4} +do_test limit-6.5 { + execsql { + SELECT * FROM t6 LIMIT -1 + } +} {1 2 3 4} +do_test limit-6.6 { + execsql { + SELECT * FROM t6 LIMIT -1 OFFSET 1 + } +} {2 3 4} +do_test limit-6.7 { + execsql { + SELECT * FROM t6 LIMIT 0 + } +} {} +do_test limit-6.8 { + execsql { + SELECT * FROM t6 LIMIT 0 OFFSET 1 + } +} {} + +# Make sure LIMIT works well with compound SELECT statements. +# Ticket #393 +# +ifcapable compound { +do_test limit-7.1.1 { + catchsql { + SELECT x FROM t2 LIMIT 5 UNION ALL SELECT a FROM t6; + } +} {1 {LIMIT clause should come after UNION ALL not before}} +do_test limit-7.1.2 { + catchsql { + SELECT x FROM t2 LIMIT 5 UNION SELECT a FROM t6; + } +} {1 {LIMIT clause should come after UNION not before}} +do_test limit-7.1.3 { + catchsql { + SELECT x FROM t2 LIMIT 5 EXCEPT SELECT a FROM t6 LIMIT 3; + } +} {1 {LIMIT clause should come after EXCEPT not before}} +do_test limit-7.1.4 { + catchsql { + SELECT x FROM t2 LIMIT 0,5 INTERSECT SELECT a FROM t6; + } +} {1 {LIMIT clause should come after INTERSECT not before}} +do_test limit-7.2 { + execsql { + SELECT x FROM t2 UNION ALL SELECT a FROM t6 LIMIT 5; + } +} {31 30 1 2 3} +do_test limit-7.3 { + execsql { + SELECT x FROM t2 UNION ALL SELECT a FROM t6 LIMIT 3 OFFSET 1; + } +} {30 1 2} +do_test limit-7.4 { + execsql { + SELECT x FROM t2 UNION ALL SELECT a FROM t6 ORDER BY 1 LIMIT 3 OFFSET 1; + } +} {2 3 4} +do_test limit-7.5 { + execsql { + SELECT x FROM t2 UNION SELECT x+2 FROM t2 LIMIT 2 OFFSET 1; + } +} {31 32} +do_test limit-7.6 { + execsql { + SELECT x FROM t2 UNION SELECT x+2 FROM t2 ORDER BY 1 DESC LIMIT 2 OFFSET 1; + } +} {32 31} +do_test limit-7.7 { + execsql { + SELECT a+9 FROM t6 EXCEPT SELECT y FROM t2 LIMIT 2; + } +} {11 12} +do_test limit-7.8 { + execsql { + SELECT a+9 FROM t6 EXCEPT SELECT y FROM t2 ORDER BY 1 DESC LIMIT 2; + } +} {13 12} +do_test limit-7.9 { + execsql { + SELECT a+26 FROM t6 INTERSECT SELECT x FROM t2 LIMIT 1; + } +} {30} +do_test limit-7.10 { + execsql { + SELECT a+27 FROM t6 INTERSECT SELECT x FROM t2 LIMIT 1; + } +} {30} +do_test limit-7.11 { + execsql { + SELECT a+27 FROM t6 INTERSECT SELECT x FROM t2 LIMIT 1 OFFSET 1; + } +} {31} +do_test limit-7.12 { + execsql { + SELECT a+27 FROM t6 INTERSECT SELECT x FROM t2 + ORDER BY 1 DESC LIMIT 1 OFFSET 1; + } +} {30} +} ;# ifcapable compound + +# Tests for limit in conjunction with distinct. The distinct should +# occur before both the limit and the offset. Ticket #749. +# +do_test limit-8.1 { + execsql { + SELECT DISTINCT cast(round(x/100) as integer) FROM t3 LIMIT 5; + } +} {0 1 2 3 4} +do_test limit-8.2 { + execsql { + SELECT DISTINCT cast(round(x/100) as integer) FROM t3 LIMIT 5 OFFSET 5; + } +} {5 6 7 8 9} +do_test limit-8.3 { + execsql { + SELECT DISTINCT cast(round(x/100) as integer) FROM t3 LIMIT 5 OFFSET 25; + } +} {25 26 27 28 29} + +# Make sure limits on multiple subqueries work correctly. +# Ticket #1035 +# +ifcapable subquery { + do_test limit-9.1 { + execsql { + SELECT * FROM (SELECT * FROM t6 LIMIT 3); + } + } {1 2 3} +} +do_test limit-9.2.1 { + execsql { + CREATE TABLE t7 AS SELECT * FROM t6; + } +} {} +ifcapable subquery { + do_test limit-9.2.2 { + execsql { + SELECT * FROM (SELECT * FROM t7 LIMIT 3); + } + } {1 2 3} +} +ifcapable compound { + ifcapable subquery { + do_test limit-9.3 { + execsql { + SELECT * FROM (SELECT * FROM t6 LIMIT 3) + UNION + SELECT * FROM (SELECT * FROM t7 LIMIT 3) + ORDER BY 1 + } + } {1 2 3} + do_test limit-9.4 { + execsql { + SELECT * FROM (SELECT * FROM t6 LIMIT 3) + UNION + SELECT * FROM (SELECT * FROM t7 LIMIT 3) + ORDER BY 1 + LIMIT 2 + } + } {1 2} + } + do_test limit-9.5 { + catchsql { + SELECT * FROM t6 LIMIT 3 + UNION + SELECT * FROM t7 LIMIT 3 + } + } {1 {LIMIT clause should come after UNION not before}} +} + +# Test LIMIT and OFFSET using SQL variables. +do_test limit-10.1 { + set limit 10 + db eval { + SELECT x FROM t1 LIMIT :limit; + } +} {31 30 29 28 27 26 25 24 23 22} +do_test limit-10.2 { + set limit 5 + set offset 5 + db eval { + SELECT x FROM t1 LIMIT :limit OFFSET :offset; + } +} {26 25 24 23 22} +do_test limit-10.3 { + set limit -1 + db eval { + SELECT x FROM t1 WHERE x<10 LIMIT :limit; + } +} {9 8 7 6 5 4 3 2 1 0} +do_test limit-10.4 { + set limit 1.5 + set rc [catch { + db eval { + SELECT x FROM t1 WHERE x<10 LIMIT :limit; + } } msg] + list $rc $msg +} {1 {datatype mismatch}} +do_test limit-10.5 { + set limit "hello world" + set rc [catch { + db eval { + SELECT x FROM t1 WHERE x<10 LIMIT :limit; + } } msg] + list $rc $msg +} {1 {datatype mismatch}} + +ifcapable subquery { +do_test limit-11.1 { + db eval { + SELECT x FROM (SELECT x FROM t1 ORDER BY x LIMIT 0) ORDER BY x + } +} {} +} ;# ifcapable subquery + +# Test error processing. +# +do_test limit-12.1 { + catchsql { + SELECT * FROM t1 LIMIT replace(1) + } +} {1 {wrong number of arguments to function replace()}} +do_test limit-12.2 { + catchsql { + SELECT * FROM t1 LIMIT 5 OFFSET replace(1) + } +} {1 {wrong number of arguments to function replace()}} +do_test limit-12.3 { + catchsql { + SELECT * FROM t1 LIMIT x + } +} {1 {no such column: x}} +do_test limit-12.4 { + catchsql { + SELECT * FROM t1 LIMIT 1 OFFSET x + } +} {1 {no such column: x}} + +# Ticket [db4d96798da8b] +# LIMIT does not work with nested views containing UNION ALL +# +do_test limit-13.1 { + db eval { + CREATE TABLE t13(x); + INSERT INTO t13 VALUES(1),(2); + CREATE VIEW v13a AS SELECT x AS y FROM t13; + CREATE VIEW v13b AS SELECT y AS z FROM v13a UNION ALL SELECT y+10 FROM v13a; + CREATE VIEW v13c AS SELECT z FROM v13b UNION ALL SELECT z+20 FROM v13b; + } +} {} +do_test limit-13.2 { + db eval {SELECT z FROM v13c LIMIT 1} +} {1} +do_test limit-13.3 { + db eval {SELECT z FROM v13c LIMIT 2} +} {1 2} +do_test limit-13.4 { + db eval {SELECT z FROM v13c LIMIT 3} +} {1 2 11} +do_test limit-13.5 { + db eval {SELECT z FROM v13c LIMIT 4} +} {1 2 11 12} +do_test limit-13.6 { + db eval {SELECT z FROM v13c LIMIT 5} +} {1 2 11 12 21} +do_test limit-13.7 { + db eval {SELECT z FROM v13c LIMIT 6} +} {1 2 11 12 21 22} +do_test limit-13.8 { + db eval {SELECT z FROM v13c LIMIT 7} +} {1 2 11 12 21 22 31} +do_test limit-13.9 { + db eval {SELECT z FROM v13c LIMIT 8} +} {1 2 11 12 21 22 31 32} +do_test limit-13.10 { + db eval {SELECT z FROM v13c LIMIT 9} +} {1 2 11 12 21 22 31 32} +do_test limit-13.11 { + db eval {SELECT z FROM v13c LIMIT 1 OFFSET 1} +} {2} +do_test limit-13.12 { + db eval {SELECT z FROM v13c LIMIT 2 OFFSET 1} +} {2 11} +do_test limit-13.13 { + db eval {SELECT z FROM v13c LIMIT 3 OFFSET 1} +} {2 11 12} +do_test limit-13.14 { + db eval {SELECT z FROM v13c LIMIT 4 OFFSET 1} +} {2 11 12 21} +do_test limit-13.15 { + db eval {SELECT z FROM v13c LIMIT 5 OFFSET 1} +} {2 11 12 21 22} +do_test limit-13.16 { + db eval {SELECT z FROM v13c LIMIT 6 OFFSET 1} +} {2 11 12 21 22 31} +do_test limit-13.17 { + db eval {SELECT z FROM v13c LIMIT 7 OFFSET 1} +} {2 11 12 21 22 31 32} +do_test limit-13.18 { + db eval {SELECT z FROM v13c LIMIT 8 OFFSET 1} +} {2 11 12 21 22 31 32} +do_test limit-13.21 { + db eval {SELECT z FROM v13c LIMIT 1 OFFSET 2} +} {11} +do_test limit-13.22 { + db eval {SELECT z FROM v13c LIMIT 2 OFFSET 2} +} {11 12} +do_test limit-13.23 { + db eval {SELECT z FROM v13c LIMIT 3 OFFSET 2} +} {11 12 21} +do_test limit-13.24 { + db eval {SELECT z FROM v13c LIMIT 4 OFFSET 2} +} {11 12 21 22} +do_test limit-13.25 { + db eval {SELECT z FROM v13c LIMIT 5 OFFSET 2} +} {11 12 21 22 31} +do_test limit-13.26 { + db eval {SELECT z FROM v13c LIMIT 6 OFFSET 2} +} {11 12 21 22 31 32} +do_test limit-13.27 { + db eval {SELECT z FROM v13c LIMIT 7 OFFSET 2} +} {11 12 21 22 31 32} +do_test limit-13.31 { + db eval {SELECT z FROM v13c LIMIT 1 OFFSET 3} +} {12} +do_test limit-13.32 { + db eval {SELECT z FROM v13c LIMIT 2 OFFSET 3} +} {12 21} +do_test limit-13.33 { + db eval {SELECT z FROM v13c LIMIT 3 OFFSET 3} +} {12 21 22} +do_test limit-13.34 { + db eval {SELECT z FROM v13c LIMIT 4 OFFSET 3} +} {12 21 22 31} +do_test limit-13.35 { + db eval {SELECT z FROM v13c LIMIT 5 OFFSET 3} +} {12 21 22 31 32} +do_test limit-13.36 { + db eval {SELECT z FROM v13c LIMIT 6 OFFSET 3} +} {12 21 22 31 32} +do_test limit-13.41 { + db eval {SELECT z FROM v13c LIMIT 1 OFFSET 4} +} {21} +do_test limit-13.42 { + db eval {SELECT z FROM v13c LIMIT 2 OFFSET 4} +} {21 22} +do_test limit-13.43 { + db eval {SELECT z FROM v13c LIMIT 3 OFFSET 4} +} {21 22 31} +do_test limit-13.44 { + db eval {SELECT z FROM v13c LIMIT 4 OFFSET 4} +} {21 22 31 32} +do_test limit-13.45 { + db eval {SELECT z FROM v13c LIMIT 5 OFFSET 4} +} {21 22 31 32} +do_test limit-13.51 { + db eval {SELECT z FROM v13c LIMIT 1 OFFSET 5} +} {22} +do_test limit-13.52 { + db eval {SELECT z FROM v13c LIMIT 2 OFFSET 5} +} {22 31} +do_test limit-13.53 { + db eval {SELECT z FROM v13c LIMIT 3 OFFSET 5} +} {22 31 32} +do_test limit-13.54 { + db eval {SELECT z FROM v13c LIMIT 4 OFFSET 5} +} {22 31 32} +do_test limit-13.61 { + db eval {SELECT z FROM v13c LIMIT 1 OFFSET 6} +} {31} +do_test limit-13.62 { + db eval {SELECT z FROM v13c LIMIT 2 OFFSET 6} +} {31 32} +do_test limit-13.63 { + db eval {SELECT z FROM v13c LIMIT 3 OFFSET 6} +} {31 32} +do_test limit-13.71 { + db eval {SELECT z FROM v13c LIMIT 1 OFFSET 7} +} {32} +do_test limit-13.72 { + db eval {SELECT z FROM v13c LIMIT 2 OFFSET 7} +} {32} +do_test limit-13.81 { + db eval {SELECT z FROM v13c LIMIT 1 OFFSET 8} +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/loadext.test b/components/external/SQLite-3.8.1/test/loadext.test new file mode 100644 index 0000000000000000000000000000000000000000..0d5b84198087725a1ffe2b249c977532e7be5d73 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/loadext.test @@ -0,0 +1,276 @@ +# 2006 July 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is extension loading. +# +# $Id: loadext.test,v 1.17 2009/03/20 09:09:37 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !load_ext { + finish_test + return +} + +# The name of the test extension varies by operating system. +# +if {$::tcl_platform(platform) eq "windows"} { + set testextension ./testloadext.dll +} else { + set testextension ./libtestloadext.so +} +set gcc_shared "-shared -fPIC" +if {$::tcl_platform(os) eq "Darwin"} { + set gcc_shared -dynamiclib +} + +# The error messages tested by this file are operating system dependent +# (because they are returned by sqlite3OsDlError()). For now, they only +# work with UNIX (and probably only certain kinds of UNIX). +# +# When a shared-object cannot be opened because it does not exist, the +# format of the message returned is: +# +# [format $dlerror_nosuchfile ] +# +# When a shared-object cannot be opened because it consists of the 4 +# characters "blah" only, we expect the error message to be: +# +# [format $dlerror_notadll ] +# +# When a symbol cannot be found within an open shared-object, the error +# message should be: +# +# [format $dlerror_nosymbol ] +# +# The exact error messages are not important. The important bit is +# that SQLite is correctly copying the message from xDlError(). +# +set dlerror_nosuchfile \ + {%s: cannot open shared object file: No such file or directory} +set dlerror_notadll {%s: file too short} +set dlerror_nosymbol {%s: undefined symbol: %s} + +if {$::tcl_platform(os) eq "Darwin"} { + set dlerror_nosuchfile {dlopen(%s, 10): image not found} + set dlerror_notadll {dlopen(%1$s, 10): no suitable image found.*} + set dlerror_nosymbol {dlsym(XXX, %2$s): symbol not found} +} + +# Make sure the test extension actually exists. If it does not +# exist, try to create it. If unable to create it, then skip this +# test file. +# +if {![file exists $testextension]} { + set srcdir [file dir $testdir]/src + set testextsrc $srcdir/test_loadext.c + + set cmdline [concat exec gcc $gcc_shared] + lappend cmdline -Wall -I$srcdir -I. -g $testextsrc -o $testextension + + if {[catch $cmdline msg]} { + puts "Skipping loadext tests: Test extension not built..." + puts $msg + finish_test + return + } +} + +# Test that loading the extension produces the expected results - adding +# the half() function to the specified database handle. +# +do_test loadext-1.1 { + catchsql { + SELECT half(1.0); + } +} {1 {no such function: half}} +do_test loadext-1.2 { + db enable_load_extension 1 + sqlite3_load_extension db $testextension testloadext_init + catchsql { + SELECT half(1.0); + } +} {0 0.5} + +# Test that a second database connection (db2) can load the extension also. +# +do_test loadext-1.3 { + sqlite3 db2 test.db + sqlite3_enable_load_extension db2 1 + catchsql { + SELECT half(1.0); + } db2 +} {1 {no such function: half}} +do_test loadext-1.4 { + sqlite3_load_extension db2 $testextension testloadext_init + catchsql { + SELECT half(1.0); + } db2 +} {0 0.5} + +# Close the first database connection. Then check that the second database +# can still use the half() function without a problem. +# +do_test loadext-1.5 { + db close + catchsql { + SELECT half(1.0); + } db2 +} {0 0.5} + +db2 close +sqlite3 db test.db +sqlite3_enable_load_extension db 1 + +# Try to load an extension for which the file does not exist. +# +do_test loadext-2.1 { + forcedelete ${testextension}xx + set rc [catch { + sqlite3_load_extension db "${testextension}xx" + } msg] + list $rc $msg +} /[list 1 [format $dlerror_nosuchfile ${testextension}xx.*]]/ + +# Try to load an extension for which the file is not a shared object +# +do_test loadext-2.2 { + set fd [open "./notasharedlib.so" w] + puts $fd blah + close $fd + set fd [open "./notasharedlib.dll" w] + puts $fd blah + close $fd + set rc [catch { + sqlite3_load_extension db "./notasharedlib" + } msg] + list $rc $msg +} /[list 1 [format $dlerror_notadll ./notasharedlib.*]]/ + +# Try to load an extension for which the file is present but the +# entry point is not. +# +do_test loadext-2.3 { + set rc [catch { + sqlite3_load_extension db $testextension icecream + } msg] + if {$::tcl_platform(os) eq "Darwin"} { + regsub {0x[1234567890abcdefABCDEF]*} $msg XXX msg + } + list $rc $msg +} [list 1 [format $dlerror_nosymbol $testextension icecream]] + +# Try to load an extension for which the entry point fails (returns non-zero) +# +do_test loadext-2.4 { + set rc [catch { + sqlite3_load_extension db $testextension testbrokenext_init + } msg] + list $rc $msg +} {1 {error during initialization: broken!}} + +############################################################################ +# Tests for the load_extension() SQL function +# + +db close +sqlite3 db test.db +sqlite3_enable_load_extension db 1 +do_test loadext-3.1 { + catchsql { + SELECT half(5); + } +} {1 {no such function: half}} +do_test loadext-3.2 { + set res [catchsql { + SELECT load_extension($::testextension) + }] + if {$::tcl_platform(os) eq "Darwin"} { + regsub {0x[1234567890abcdefABCDEF]*} $res XXX res + } + set res +} /[list 1 [format $dlerror_nosymbol $testextension sqlite3_.*_init]]/ +do_test loadext-3.3 { + catchsql { + SELECT load_extension($::testextension,'testloadext_init') + } +} {0 {{}}} +do_test loadext-3.4 { + catchsql { + SELECT half(5); + } +} {0 2.5} +do_test loadext-3.5 { + db eval { + SELECT sqlite3_status('MEMORY_USED') AS mused + } break + puts -nonewline " (memory_used=$mused) " + expr {$mused>0} +} {1} +do_test loadext-3.6 { + catchsql { + SELECT sqlite3_status('MEMORY_USED_X') AS mused + } +} {1 {unknown status property: MEMORY_USED_X}} +do_test loadext-3.7 { + catchsql { + SELECT sqlite3_status(4.53) AS mused + } +} {1 {unknown status type}} +do_test loadext-3.8 { + catchsql { + SELECT sqlite3_status(23) AS mused + } +} {1 {sqlite3_status(23,...) returns 21}} + +# Ticket #1863 +# Make sure the extension loading mechanism will not work unless it +# is explicitly enabled. +# +db close +sqlite3 db test.db +do_test loadext-4.1 { + catchsql { + SELECT load_extension($::testextension,'testloadext_init') + } +} {1 {not authorized}} +do_test loadext-4.2 { + sqlite3_enable_load_extension db 1 + catchsql { + SELECT load_extension($::testextension,'testloadext_init') + } +} {0 {{}}} + +do_test loadext-4.3 { + sqlite3_enable_load_extension db 0 + catchsql { + SELECT load_extension($::testextension,'testloadext_init') + } +} {1 {not authorized}} + +source $testdir/malloc_common.tcl + + +# Malloc failure in sqlite3_auto_extension and sqlite3_load_extension +# +do_malloc_test loadext-5 -tclprep { + sqlite3_reset_auto_extension +} -tclbody { + if {[autoinstall_test_functions]==7} {error "out of memory"} +} +do_malloc_test loadext-6 -tclbody { + db enable_load_extension 1 + sqlite3_load_extension db $::testextension testloadext_init +} +autoinstall_test_functions + +finish_test diff --git a/components/external/SQLite-3.8.1/test/loadext2.test b/components/external/SQLite-3.8.1/test/loadext2.test new file mode 100644 index 0000000000000000000000000000000000000000..d5b6ea8d7f809e1ecd4ae8d596de34bdcc2fd334 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/loadext2.test @@ -0,0 +1,168 @@ +# 2006 August 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is automatic extension loading and the +# sqlite3_auto_extension() API. +# +# $Id: loadext2.test,v 1.3 2008/03/19 16:08:54 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Only run these tests if the approriate APIs are defined +# in the system under test. +# +ifcapable !load_ext { + finish_test + return +} +if {[info command sqlite3_auto_extension_sqr]==""} { + finish_test + return +} + + +# None of the extension are loaded by default. +# +do_test loadext2-1.1 { + catchsql { + SELECT sqr(2) + } +} {1 {no such function: sqr}} +do_test loadext2-1.2 { + catchsql { + SELECT cube(2) + } +} {1 {no such function: cube}} + +# Extensions loaders not currently registered +# +do_test loadext2-1.2.1 { + sqlite3_cancel_auto_extension_sqr +} {0} +do_test loadext2-1.2.2 { + sqlite3_cancel_auto_extension_sqr +} {0} +do_test loadext2-1.2.3 { + sqlite3_cancel_auto_extension_sqr +} {0} + + +# Register auto-loaders. Still functions do not exist. +# +do_test loadext2-1.3 { + sqlite3_auto_extension_sqr + sqlite3_auto_extension_cube + catchsql { + SELECT sqr(2) + } +} {1 {no such function: sqr}} +do_test loadext2-1.4 { + catchsql { + SELECT cube(2) + } +} {1 {no such function: cube}} + + +# Functions do exist in a new database connection +# +do_test loadext2-1.5 { + sqlite3 db test.db + catchsql { + SELECT sqr(2) + } +} {0 4.0} +do_test loadext2-1.6 { + catchsql { + SELECT cube(2) + } +} {0 8.0} + + +# Reset extension auto loading. Existing extensions still exist. +# +do_test loadext2-1.7.1 { + sqlite3_cancel_auto_extension_sqr +} {1} +do_test loadext2-1.7.2 { + sqlite3_cancel_auto_extension_sqr +} {0} +do_test loadext2-1.7.3 { + sqlite3_cancel_auto_extension_cube +} {1} +do_test loadext2-1.7.4 { + sqlite3_cancel_auto_extension_cube +} {0} +do_test loadext2-1.7.5 { + catchsql { + SELECT sqr(2) + } +} {0 4.0} +do_test loadext2-1.8 { + catchsql { + SELECT cube(2) + } +} {0 8.0} + + +# Register only the sqr() function. +# +do_test loadext2-1.9 { + sqlite3_auto_extension_sqr + sqlite3 db test.db + catchsql { + SELECT sqr(2) + } +} {0 4.0} +do_test loadext2-1.10 { + catchsql { + SELECT cube(2) + } +} {1 {no such function: cube}} + +# Register only the cube() function. +# +do_test loadext2-1.11 { + sqlite3_reset_auto_extension + sqlite3_auto_extension_cube + sqlite3 db test.db + catchsql { + SELECT sqr(2) + } +} {1 {no such function: sqr}} +do_test loadext2-1.12 { + catchsql { + SELECT cube(2) + } +} {0 8.0} + +# Register a broken entry point. +# +do_test loadext2-1.13 { + sqlite3_auto_extension_broken + set rc [catch {sqlite3 db test.db} errmsg] + lappend rc $errmsg +} {1 {automatic extension loading failed: broken autoext!}} +do_test loadext2-1.14 { + catchsql { + SELECT sqr(2) + } +} {1 {no such function: sqr}} +do_test loadext2-1.15 { + catchsql { + SELECT cube(2) + } +} {0 8.0} + + +sqlite3_reset_auto_extension +autoinstall_test_functions +finish_test diff --git a/components/external/SQLite-3.8.1/test/lock.test b/components/external/SQLite-3.8.1/test/lock.test new file mode 100644 index 0000000000000000000000000000000000000000..6ec85eea3cef5fdc2b67c13776ad7ef871d26cf0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lock.test @@ -0,0 +1,449 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is database locks. +# +# $Id: lock.test,v 1.40 2009/06/16 17:49:36 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create an alternative connection to the database +# +do_test lock-1.0 { + # Give a complex pathname to stress the path simplification logic in + # the vxworks driver and in test_async. + file mkdir tempdir/t1/t2 + sqlite3 db2 ./tempdir/../tempdir/t1/.//t2/../../..//test.db + set dummy {} +} {} +do_test lock-1.1 { + execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name} +} {} +do_test lock-1.2 { + execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name} db2 +} {} +do_test lock-1.3 { + execsql {CREATE TABLE t1(a int, b int)} + execsql {SELECT name FROM sqlite_master WHERE type='table' ORDER BY name} +} {t1} +do_test lock-1.5 { + catchsql { + SELECT name FROM sqlite_master WHERE type='table' ORDER BY name + } db2 +} {0 t1} + +do_test lock-1.6 { + execsql {INSERT INTO t1 VALUES(1,2)} + execsql {SELECT * FROM t1} +} {1 2} +# Update: The schema is now brought up to date by test lock-1.5. +# do_test lock-1.7.1 { +# catchsql {SELECT * FROM t1} db2 +# } {1 {no such table: t1}} +do_test lock-1.7.2 { + catchsql {SELECT * FROM t1} db2 +} {0 {1 2}} +do_test lock-1.8 { + execsql {UPDATE t1 SET a=b, b=a} db2 + execsql {SELECT * FROM t1} db2 +} {2 1} +do_test lock-1.9 { + execsql {SELECT * FROM t1} +} {2 1} +do_test lock-1.10 { + execsql {BEGIN TRANSACTION} + execsql {UPDATE t1 SET a = 0 WHERE 0} + execsql {SELECT * FROM t1} +} {2 1} +do_test lock-1.11 { + catchsql {SELECT * FROM t1} db2 +} {0 {2 1}} +do_test lock-1.12 { + execsql {ROLLBACK} + catchsql {SELECT * FROM t1} +} {0 {2 1}} + +do_test lock-1.13 { + execsql {CREATE TABLE t2(x int, y int)} + execsql {INSERT INTO t2 VALUES(8,9)} + execsql {SELECT * FROM t2} +} {8 9} +do_test lock-1.14.1 { + catchsql {SELECT * FROM t2} db2 +} {0 {8 9}} +do_test lock-1.14.2 { + catchsql {SELECT * FROM t1} db2 +} {0 {2 1}} +do_test lock-1.15 { + catchsql {SELECT * FROM t2} db2 +} {0 {8 9}} + +do_test lock-1.16 { + db eval {SELECT * FROM t1} qv { + set x [db eval {SELECT * FROM t1}] + } + set x +} {2 1} +do_test lock-1.17 { + db eval {SELECT * FROM t1} qv { + set x [db eval {SELECT * FROM t2}] + } + set x +} {8 9} + +# You cannot UPDATE a table from within the callback of a SELECT +# on that same table because the SELECT has the table locked. +# +# 2006-08-16: Reads no longer block writes within the same +# database connection. +# +#do_test lock-1.18 { +# db eval {SELECT * FROM t1} qv { +# set r [catch {db eval {UPDATE t1 SET a=b, b=a}} msg] +# lappend r $msg +# } +# set r +#} {1 {database table is locked}} + +# But you can UPDATE a different table from the one that is used in +# the SELECT. +# +do_test lock-1.19 { + db eval {SELECT * FROM t1} qv { + set r [catch {db eval {UPDATE t2 SET x=y, y=x}} msg] + lappend r $msg + } + set r +} {0 {}} +do_test lock-1.20 { + execsql {SELECT * FROM t2} +} {9 8} + +# It is possible to do a SELECT of the same table within the +# callback of another SELECT on that same table because two +# or more read-only cursors can be open at once. +# +do_test lock-1.21 { + db eval {SELECT * FROM t1} qv { + set r [catch {db eval {SELECT a FROM t1}} msg] + lappend r $msg + } + set r +} {0 2} + +# Under UNIX you can do two SELECTs at once with different database +# connections, because UNIX supports reader/writer locks. Under windows, +# this is not possible. +# +if {$::tcl_platform(platform)=="unix"} { + do_test lock-1.22 { + db eval {SELECT * FROM t1} qv { + set r [catch {db2 eval {SELECT a FROM t1}} msg] + lappend r $msg + } + set r + } {0 2} +} +integrity_check lock-1.23 + +# If one thread has a transaction another thread cannot start +# a transaction. -> Not true in version 3.0. But if one thread +# as a RESERVED lock another thread cannot acquire one. +# +do_test lock-2.1 { + execsql {BEGIN TRANSACTION} + execsql {UPDATE t1 SET a = 0 WHERE 0} + execsql {BEGIN TRANSACTION} db2 + set r [catch {execsql {UPDATE t1 SET a = 0 WHERE 0} db2} msg] + execsql {ROLLBACK} db2 + lappend r $msg +} {1 {database is locked}} + +# A thread can read when another has a RESERVED lock. +# +do_test lock-2.2 { + catchsql {SELECT * FROM t2} db2 +} {0 {9 8}} + +# If the other thread (the one that does not hold the transaction with +# a RESERVED lock) tries to get a RESERVED lock, we do get a busy callback +# as long as we were not orginally holding a READ lock. +# +do_test lock-2.3.1 { + proc callback {count} { + set ::callback_value $count + break + } + set ::callback_value {} + db2 busy callback + # db2 does not hold a lock so we should get a busy callback here + set r [catch {execsql {UPDATE t1 SET a=b, b=a} db2} msg] + lappend r $msg + lappend r $::callback_value +} {1 {database is locked} 0} +do_test lock-2.3.2 { + set ::callback_value {} + execsql {BEGIN; SELECT rowid FROM sqlite_master LIMIT 1} db2 + # This time db2 does hold a read lock. No busy callback this time. + set r [catch {execsql {UPDATE t1 SET a=b, b=a} db2} msg] + lappend r $msg + lappend r $::callback_value +} {1 {database is locked} {}} +catch {execsql {ROLLBACK} db2} +do_test lock-2.4.1 { + proc callback {count} { + lappend ::callback_value $count + if {$count>4} break + } + set ::callback_value {} + db2 busy callback + # We get a busy callback because db2 is not holding a lock + set r [catch {execsql {UPDATE t1 SET a=b, b=a} db2} msg] + lappend r $msg + lappend r $::callback_value +} {1 {database is locked} {0 1 2 3 4 5}} +do_test lock-2.4.2 { + proc callback {count} { + lappend ::callback_value $count + if {$count>4} break + } + set ::callback_value {} + db2 busy callback + execsql {BEGIN; SELECT rowid FROM sqlite_master LIMIT 1} db2 + # No busy callback this time because we are holding a lock + set r [catch {execsql {UPDATE t1 SET a=b, b=a} db2} msg] + lappend r $msg + lappend r $::callback_value +} {1 {database is locked} {}} +catch {execsql {ROLLBACK} db2} +do_test lock-2.5 { + proc callback {count} { + lappend ::callback_value $count + if {$count>4} break + } + set ::callback_value {} + db2 busy callback + set r [catch {execsql {SELECT * FROM t1} db2} msg] + lappend r $msg + lappend r $::callback_value +} {0 {2 1} {}} +execsql {ROLLBACK} + +# Test the built-in busy timeout handler +# +do_test lock-2.8 { + db2 timeout 400 + execsql BEGIN + execsql {UPDATE t1 SET a = 0 WHERE 0} + catchsql {BEGIN EXCLUSIVE;} db2 +} {1 {database is locked}} +do_test lock-2.8b { + db2 eval {PRAGMA busy_timeout} +} {400} +do_test lock-2.9 { + db2 timeout 0 + execsql COMMIT +} {} +do_test lock-2.9b { + db2 eval {PRAGMA busy_timeout} +} {0} +integrity_check lock-2.10 +do_test lock-2.11 { + db2 eval {PRAGMA busy_timeout(400)} + execsql BEGIN + execsql {UPDATE t1 SET a = 0 WHERE 0} + catchsql {BEGIN EXCLUSIVE;} db2 +} {1 {database is locked}} +do_test lock-2.11b { + db2 eval {PRAGMA busy_timeout} +} {400} +do_test lock-2.12 { + db2 eval {PRAGMA busy_timeout(0)} + execsql COMMIT +} {} +do_test lock-2.12b { + db2 eval {PRAGMA busy_timeout} +} {0} +integrity_check lock-2.13 + +# Try to start two transactions in a row +# +do_test lock-3.1 { + execsql {BEGIN TRANSACTION} + set r [catch {execsql {BEGIN TRANSACTION}} msg] + execsql {ROLLBACK} + lappend r $msg +} {1 {cannot start a transaction within a transaction}} +integrity_check lock-3.2 + +# Make sure the busy handler and error messages work when +# opening a new pointer to the database while another pointer +# has the database locked. +# +do_test lock-4.1 { + db2 close + catch {db eval ROLLBACK} + db eval BEGIN + db eval {UPDATE t1 SET a=0 WHERE 0} + sqlite3 db2 ./test.db + catchsql {UPDATE t1 SET a=0} db2 +} {1 {database is locked}} +do_test lock-4.2 { + set ::callback_value {} + set rc [catch {db2 eval {UPDATE t1 SET a=0}} msg] + lappend rc $msg $::callback_value +} {1 {database is locked} {}} +do_test lock-4.3 { + proc callback {count} { + lappend ::callback_value $count + if {$count>4} break + } + db2 busy callback + set rc [catch {db2 eval {UPDATE t1 SET a=0}} msg] + lappend rc $msg $::callback_value +} {1 {database is locked} {0 1 2 3 4 5}} +execsql {ROLLBACK} + +# When one thread is writing, other threads cannot read. Except if the +# writing thread is writing to its temporary tables, the other threads +# can still read. -> Not so in 3.0. One thread can read while another +# holds a RESERVED lock. +# +proc tx_exec {sql} { + db2 eval $sql +} +do_test lock-5.1 { + execsql { + SELECT * FROM t1 + } +} {2 1} +do_test lock-5.2 { + db function tx_exec tx_exec + catchsql { + INSERT INTO t1(a,b) SELECT 3, tx_exec('SELECT y FROM t2 LIMIT 1'); + } +} {0 {}} + +ifcapable tempdb { + do_test lock-5.3 { + execsql { + CREATE TEMP TABLE t3(x); + SELECT * FROM t3; + } + } {} + do_test lock-5.4 { + catchsql { + INSERT INTO t3 SELECT tx_exec('SELECT y FROM t2 LIMIT 1'); + } + } {0 {}} + do_test lock-5.5 { + execsql { + SELECT * FROM t3; + } + } {8} + do_test lock-5.6 { + catchsql { + UPDATE t1 SET a=tx_exec('SELECT x FROM t2'); + } + } {0 {}} + do_test lock-5.7 { + execsql { + SELECT * FROM t1; + } + } {9 1 9 8} + do_test lock-5.8 { + catchsql { + UPDATE t3 SET x=tx_exec('SELECT x FROM t2'); + } + } {0 {}} + do_test lock-5.9 { + execsql { + SELECT * FROM t3; + } + } {9} +} + +do_test lock-6.1 { + execsql { + CREATE TABLE t4(a PRIMARY KEY, b); + INSERT INTO t4 VALUES(1, 'one'); + INSERT INTO t4 VALUES(2, 'two'); + INSERT INTO t4 VALUES(3, 'three'); + } + + set STMT [sqlite3_prepare $DB "SELECT * FROM sqlite_master" -1 TAIL] + sqlite3_step $STMT + + execsql { DELETE FROM t4 } + execsql { SELECT * FROM sqlite_master } db2 + execsql { SELECT * FROM t4 } db2 +} {} + +do_test lock-6.2 { + execsql { + BEGIN; + INSERT INTO t4 VALUES(1, 'one'); + INSERT INTO t4 VALUES(2, 'two'); + INSERT INTO t4 VALUES(3, 'three'); + COMMIT; + } + + execsql { SELECT * FROM t4 } db2 +} {1 one 2 two 3 three} + +do_test lock-6.3 { + execsql { SELECT a FROM t4 ORDER BY a } db2 +} {1 2 3} + +do_test lock-6.4 { + execsql { PRAGMA integrity_check } db2 +} {ok} + +do_test lock-6.5 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +# At one point the following set of conditions would cause SQLite to +# retain a RESERVED or EXCLUSIVE lock after the transaction was committed: +# +# * The journal-mode is set to something other than 'delete', and +# * there exists one or more active read-only statements, and +# * a transaction that modified zero database pages is committed. +# +set temp_status unlocked +if {$TEMP_STORE>=2} {set temp_status unknown} +do_test lock-7.1 { + set STMT [sqlite3_prepare $DB "SELECT * FROM sqlite_master" -1 TAIL] + sqlite3_step $STMT +} {SQLITE_ROW} +do_test lock-7.2 { + execsql { PRAGMA lock_status } +} [list main shared temp $temp_status] +do_test lock-7.3 { + execsql { + PRAGMA journal_mode = truncate; + BEGIN; + UPDATE t4 SET a = 10 WHERE 0; + COMMIT; + } + execsql { PRAGMA lock_status } +} [list main shared temp $temp_status] +do_test lock-7.4 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +do_test lock-999.1 { + rename db2 {} +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/lock2.test b/components/external/SQLite-3.8.1/test/lock2.test new file mode 100644 index 0000000000000000000000000000000000000000..ea2e5573a9c101879d57144e9ad224149c6074d5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lock2.test @@ -0,0 +1,111 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is database locks between competing processes. +# +# $Id: lock2.test,v 1.11 2009/05/01 10:55:34 danielk1977 Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl + + +# Simple locking test case: +# +# lock2-1.1: Connect a second process to the database. +# lock2-1.2: Establish a RESERVED lock with this process. +# lock2-1.3: Get a SHARED lock with the second process. +# lock2-1.4: Try for a RESERVED lock with process 2. This fails. +# lock2-1.5: Try to upgrade the first process to EXCLUSIVE, this fails so +# it gets PENDING. +# lock2-1.6: Release the SHARED lock held by the second process. +# lock2-1.7: Attempt to reaquire a SHARED lock with the second process. +# this fails due to the PENDING lock. +# lock2-1.8: Ensure the first process can now upgrade to EXCLUSIVE. +# +do_test lock2-1.1 { + set ::tf1 [launch_testfixture] + testfixture $::tf1 { + sqlite3 db test.db -key xyzzy + db eval {select * from sqlite_master} + } +} {} +do_test lock2-1.1.1 { + execsql {pragma lock_status} +} {main unlocked temp closed} +sqlite3_soft_heap_limit 0 +do_test lock2-1.2 { + execsql { + BEGIN; + CREATE TABLE abc(a, b, c); + } +} {} +do_test lock2-1.3 { + testfixture $::tf1 { + db eval { + BEGIN; + SELECT * FROM sqlite_master; + } + } +} {} +do_test lock2-1.4 { + testfixture $::tf1 { + catch { db eval { CREATE TABLE def(d, e, f) } } msg + set msg + } +} {database is locked} +do_test lock2-1.5 { + catchsql { + COMMIT; + } +} {1 {database is locked}} +do_test lock2-1.6 { + testfixture $::tf1 { + db eval { + SELECT * FROM sqlite_master; + COMMIT; + } + } +} {} +do_test lock2-1.7 { + testfixture $::tf1 { + catch { db eval { + BEGIN; + SELECT * FROM sqlite_master; + } } msg + set msg + } +} {database is locked} +do_test lock2-1.8 { + catchsql { + COMMIT; + } +} {0 {}} +do_test lock2-1.9 { + execsql { + SELECT * FROM sqlite_master; + } +} "table abc abc [expr $AUTOVACUUM?3:2] {CREATE TABLE abc(a, b, c)}" +catch flush_async_queue +do_test lock2-1.10 { + testfixture $::tf1 { + db eval { + SELECT * FROM sqlite_master; + } + } +} "table abc abc [expr $AUTOVACUUM?3:2] {CREATE TABLE abc(a, b, c)}" + +catch {testfixture $::tf1 {db close}} +catch {close $::tf1} +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) + +finish_test diff --git a/components/external/SQLite-3.8.1/test/lock3.test b/components/external/SQLite-3.8.1/test/lock3.test new file mode 100644 index 0000000000000000000000000000000000000000..f771a193705a03f06d315565a38cc9b9ca25fd81 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lock3.test @@ -0,0 +1,79 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is database locks and the operation of the +# DEFERRED, IMMEDIATE, and EXCLUSIVE keywords as modifiers to the +# BEGIN command. +# +# $Id: lock3.test,v 1.4 2009/03/28 15:04:24 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Establish two connections to the same database. Put some +# sample data into the database. +# +do_test lock3-1.1 { + file mkdir tempdir/t1/t2/t3 + sqlite3 db2 ./tempdir/t1//t2/./t3//./../..//./../../tempdir/..//test.db// + execsql { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + } + execsql { + SELECT * FROM t1 + } db2 +} 1 + +# Get a deferred lock on the database using one connection. The +# other connection should still be able to write. +# +do_test lock3-2.1 { + execsql {BEGIN DEFERRED TRANSACTION} + execsql {INSERT INTO t1 VALUES(2)} db2 + execsql {END TRANSACTION} + execsql {SELECT * FROM t1} +} {1 2} + +# Get an immediate lock on the database using one connection. The +# other connection should be able to read the database but not write +# it. +# +do_test lock3-3.1 { + execsql {BEGIN IMMEDIATE TRANSACTION} + catchsql {SELECT * FROM t1} db2 +} {0 {1 2}} +do_test lock3-3.2 { + catchsql {INSERT INTO t1 VALUES(3)} db2 +} {1 {database is locked}} +do_test lock3-3.3 { + execsql {END TRANSACTION} +} {} + + +# Get an exclusive lock on the database using one connection. The +# other connection should be unable to read or write the database. +# +do_test lock3-4.1 { + execsql {BEGIN EXCLUSIVE TRANSACTION} + catchsql {SELECT * FROM t1} db2 +} {1 {database is locked}} +do_test lock3-4.2 { + catchsql {INSERT INTO t1 VALUES(3)} db2 +} {1 {database is locked}} +do_test lock3-4.3 { + execsql {END TRANSACTION} +} {} + +catch {db2 close} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/lock4.test b/components/external/SQLite-3.8.1/test/lock4.test new file mode 100644 index 0000000000000000000000000000000000000000..b0b1c74fbec6186ec5277efabc3a79e7c30fa761 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lock4.test @@ -0,0 +1,118 @@ +# 2007 April 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is database locks. +# +# $Id: lock4.test,v 1.10 2009/05/06 00:52:41 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_not_use_codec + +# Initialize the test.db database so that it is non-empty +# +do_test lock4-1.1 { + db eval { + PRAGMA auto_vacuum=OFF; + CREATE TABLE t1(x); + } + forcedelete test2.db test2.db-journal + sqlite3 db2 test2.db + db2 eval { + PRAGMA auto_vacuum=OFF; + CREATE TABLE t2(x) + } + db2 close + list [file size test.db] [file size test2.db] +} {2048 2048} + +# Create a script to drive a separate process that will +# +# 1. Create a second database test2.db +# 2. Get an exclusive lock on test2.db +# 3. Add an entry to test.db in table t1, waiting as necessary. +# 4. Commit the change to test2.db. +# +# Meanwhile, this process will: +# +# A. Get an exclusive lock on test.db +# B. Attempt to read from test2.db but get an SQLITE_BUSY error. +# C. Commit the changes to test.db thus alloing the other process +# to continue. +# +do_test lock4-1.2 { + + # Create a script for the second process to run. + # + set out [open test2-script.tcl w] + puts $out "sqlite3_test_control_pending_byte [set sqlite_pending_byte]" + puts $out { + sqlite3 db2 test2.db + db2 eval { + BEGIN; + INSERT INTO t2 VALUES(2); + } + sqlite3 db test.db + db timeout 1000000 + db eval { + INSERT INTO t1 VALUES(2); + } + db close + db2 eval COMMIT + exit + } + close $out + + # Begin a transaction on test.db. + db eval { + BEGIN EXCLUSIVE; + INSERT INTO t1 VALUES(1); + } + + # Kick off the second process. + exec [info nameofexec] ./test2-script.tcl & + + # Wait until the second process has started its transaction on test2.db. + while {![file exists test2.db-journal]} { + after 10 + } + + # Try to write to test2.db. We are locked out. + sqlite3 db2 test2.db + catchsql { + INSERT INTO t2 VALUES(1) + } db2 +} {1 {database is locked}} +do_test lock4-1.3 { + db eval { + COMMIT; + } + while {[file exists test2.db-journal]} { + after 10 + } + # The other process has committed its transaction on test2.db by + # deleting the journal file. But it might retain the lock for a + # fraction longer + # + after 25 + db2 eval { + SELECT * FROM t2 + } +} {2} + + +do_test lock4-999.1 { + rename db2 {} +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/lock5.test b/components/external/SQLite-3.8.1/test/lock5.test new file mode 100644 index 0000000000000000000000000000000000000000..f0d495508ae10793704ae2ffae7776e464e669af --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lock5.test @@ -0,0 +1,195 @@ +# 2008 June 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is database locks. +# +# $Id: lock5.test,v 1.6 2008/12/04 12:34:16 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# This file is only run if using the unix backend compiled with the +# SQLITE_ENABLE_LOCKING_STYLE macro. +db close +if {[catch {sqlite3 db test.db -vfs unix-none} msg]} { + finish_test + return +} +db close +forcedelete test.db.lock + +ifcapable lock_proxy_pragmas { + set ::using_proxy 0 + foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] { + set ::using_proxy $value + } + # Disable the proxy locking for these tests + set env(SQLITE_FORCE_PROXY_LOCKING) "0" +} + + +do_test lock5-dotfile.1 { + sqlite3 db test.db -vfs unix-dotfile + execsql { + BEGIN; + CREATE TABLE t1(a, b); + } +} {} + +do_test lock5-dotfile.2 { + file exists test.db.lock +} {1} + +do_test lock5-dotfile.3 { + execsql COMMIT + file exists test.db.lock +} {0} + +do_test lock5-dotfile.4 { + sqlite3 db2 test.db -vfs unix-dotfile + execsql { + INSERT INTO t1 VALUES('a', 'b'); + SELECT * FROM t1; + } db2 +} {a b} + +do_test lock5-dotfile.5 { + execsql { + BEGIN; + SELECT * FROM t1; + } db2 +} {a b} + +do_test lock5-dotfile.6 { + file exists test.db.lock +} {1} + +do_test lock5-dotfile.7 { + catchsql { SELECT * FROM t1; } +} {1 {database is locked}} + +do_test lock5-dotfile.8 { + execsql { + SELECT * FROM t1; + ROLLBACK; + } db2 +} {a b} + +do_test lock5-dotfile.9 { + catchsql { SELECT * FROM t1; } +} {0 {a b}} + +do_test lock5-dotfile.10 { + file exists test.db.lock +} {0} + +do_test lock5-dotfile.X { + db2 close + execsql {BEGIN EXCLUSIVE} + db close + file exists test.db.lock +} {0} + +##################################################################### + +forcedelete test.db +if {[catch {sqlite3 db test.db -vfs unix-flock} msg]} { + finish_test + return +} + +do_test lock5-flock.1 { + sqlite3 db test.db -vfs unix-flock + execsql { + CREATE TABLE t1(a, b); + BEGIN; + INSERT INTO t1 VALUES(1, 2); + } +} {} + +# Make sure we are not accidentally using the dotfile locking scheme. +do_test lock5-flock.2 { + file exists test.db.lock +} {0} + +do_test lock5-flock.3 { + catch { sqlite3 db2 test.db -vfs unix-flock } + catchsql { SELECT * FROM t1 } db2 +} {1 {database is locked}} + +do_test lock5-flock.4 { + execsql COMMIT + catchsql { SELECT * FROM t1 } db2 +} {0 {1 2}} + +do_test lock5-flock.5 { + execsql BEGIN + catchsql { SELECT * FROM t1 } db2 +} {0 {1 2}} + +do_test lock5-flock.6 { + execsql {SELECT * FROM t1} + catchsql { SELECT * FROM t1 } db2 +} {1 {database is locked}} + +do_test lock5-flock.7 { + db close + catchsql { SELECT * FROM t1 } db2 +} {0 {1 2}} + +do_test lock5-flock.8 { + db2 close +} {} + +##################################################################### + +do_test lock5-none.1 { + sqlite3 db test.db -vfs unix-none + sqlite3 db2 test.db -vfs unix-none + execsql { + BEGIN; + INSERT INTO t1 VALUES(3, 4); + } +} {} +do_test lock5-none.2 { + execsql { SELECT * FROM t1 } +} {1 2 3 4} +do_test lock5-flock.3 { + execsql { SELECT * FROM t1 } db2 +} {1 2} +do_test lock5-none.4 { + execsql { + BEGIN; + SELECT * FROM t1; + } db2 +} {1 2} +do_test lock5-none.5 { + execsql COMMIT + execsql {SELECT * FROM t1} db2 +} {1 2} + +ifcapable memorymanage { + do_test lock5-none.6 { + sqlite3_release_memory 1000000 + execsql {SELECT * FROM t1} db2 + } {1 2 3 4} +} + +do_test lock5-flock.X { + db close + db2 close +} {} + +ifcapable lock_proxy_pragmas { + set env(SQLITE_FORCE_PROXY_LOCKING) $::using_proxy +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/lock6.test b/components/external/SQLite-3.8.1/test/lock6.test new file mode 100644 index 0000000000000000000000000000000000000000..b47d18f7a9acfb294a93d0dd5b3232d8c851894e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lock6.test @@ -0,0 +1,167 @@ +# 2008 October 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is database locks. +# +# $Id: lock6.test,v 1.3 2009/02/05 16:31:46 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Launch another testfixture process to be controlled by this one. A +# channel name is returned that may be passed as the first argument to proc +# 'testfixture' to execute a command. The child testfixture process is shut +# down by closing the channel. +proc launch_testfixture {} { + set prg [info nameofexec] + if {$prg eq ""} { + set prg [file join . testfixture] + } + set chan [open "|$prg tf_main2.tcl" r+] + fconfigure $chan -buffering line + return $chan +} + +# Execute a command in a child testfixture process, connected by two-way +# channel $chan. Return the result of the command, or an error message. +proc testfixture {chan cmd} { + puts $chan $cmd + puts $chan OVER + set r "" + while { 1 } { + set line [gets $chan] + if { $line == "OVER" } { + return $r + } + append r $line + } +} + +# Write the main loop for the child testfixture processes into file +# tf_main2.tcl. The parent (this script) interacts with the child processes +# via a two way pipe. The parent writes a script to the stdin of the child +# process, followed by the word "OVER" on a line of its own. The child +# process evaluates the script and writes the results to stdout, followed +# by an "OVER" of its own. +set f [open tf_main2.tcl w] +puts $f { + set l [open log w] + set script "" + while {![eof stdin]} { + flush stdout + set line [gets stdin] + puts $l "READ $line" + if { $line == "OVER" } { + catch {eval $script} result + puts $result + puts $l "WRITE $result" + puts OVER + puts $l "WRITE OVER" + flush stdout + set script "" + } else { + append script $line + append script " ; " + } + } + close $l +} +close $f + + +ifcapable lock_proxy_pragmas&&prefer_proxy_locking { + set sqlite_hostid_num 1 + + set using_proxy 0 + foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] { + set using_proxy $value + } + + # Test the lock_proxy_file pragmas. + # + set env(SQLITE_FORCE_PROXY_LOCKING) "1" + + do_test lock6-1.1 { + set ::tf1 [launch_testfixture] + testfixture $::tf1 "sqlite3_test_control_pending_byte $::sqlite_pending_byte" + testfixture $::tf1 { + set sqlite_hostid_num 2 + sqlite3 db test.db -key xyzzy + set lockpath [db eval { + PRAGMA lock_proxy_file=":auto:"; + select * from sqlite_master; + PRAGMA lock_proxy_file; + }] + string match "*test.db:auto:" $lockpath + } + } {1} + + set sqlite_hostid_num 3 + do_test lock6-1.2 { + execsql {pragma lock_status} + } {main unlocked temp closed} + + sqlite3_soft_heap_limit 0 + do_test lock6-1.3 { + list [catch { + sqlite3 db test.db + execsql { select * from sqlite_master } + } msg] $msg + } {1 {database is locked}} + + do_test lock6-1.4 { + set lockpath [execsql { + PRAGMA lock_proxy_file=":auto:"; + PRAGMA lock_proxy_file; + } db] + set lockpath + } {{:auto: (not held)}} + + do_test lock6-1.4.1 { + catchsql { + PRAGMA lock_proxy_file="notmine"; + select * from sqlite_master; + } db + } {1 {database is locked}} + + do_test lock6-1.4.2 { + execsql { + PRAGMA lock_proxy_file; + } db + } {notmine} + + do_test lock6-1.5 { + testfixture $::tf1 { + db eval { + BEGIN; + SELECT * FROM sqlite_master; + } + } + } {} + + catch {testfixture $::tf1 {db close}} + + do_test lock6-1.6 { + execsql { + PRAGMA lock_proxy_file="mine"; + select * from sqlite_master; + } db + } {} + + catch {close $::tf1} + set env(SQLITE_FORCE_PROXY_LOCKING) $using_proxy + set sqlite_hostid_num 0 + + sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/lock7.test b/components/external/SQLite-3.8.1/test/lock7.test new file mode 100644 index 0000000000000000000000000000000000000000..02f2c6c6305079d7f1e5dcc17a7c4e4a1ce108f4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lock7.test @@ -0,0 +1,60 @@ +# 2009 August 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Check that reading the database schema from within an active transaction +# does not establish a SHARED lock on the database file if one is not +# already held (or, more accurately, that the SHARED lock is released after +# reading the database schema). +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test lock7-1.1 { + execsql { CREATE TABLE t1(a, b) } + db close + + sqlite3 db1 test.db + sqlite3 db2 test.db + + db1 eval {BEGIN} + db2 eval {BEGIN} +} {} + +do_test lock7-1.2 { + execsql { PRAGMA lock_status } db1 +} {main unlocked temp closed} +do_test lock7-1.3 { + execsql { PRAGMA lock_status } db2 +} {main unlocked temp closed} + +do_test lock7-1.4 { + catchsql { INSERT INTO t1 VALUES(1, 1) } db1 +} {0 {}} +do_test lock7-1.5 { + catchsql { INSERT INTO t1 VALUES(2, 2) } db2 +} {1 {database is locked}} + +do_test lock7-1.6 { + execsql { PRAGMA lock_status } db1 +} {main reserved temp closed} +do_test lock7-1.7 { + execsql { PRAGMA lock_status } db2 +} {main unlocked temp closed} + +do_test lock7-1.8 { + execsql { COMMIT } db1 +} {} + +db1 close +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/lock_common.tcl b/components/external/SQLite-3.8.1/test/lock_common.tcl new file mode 100644 index 0000000000000000000000000000000000000000..bc1eb86bdc2b8e4757431a51fe4b3b19fab1687f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lock_common.tcl @@ -0,0 +1,174 @@ +# 2010 April 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file contains code used by several different test scripts. The +# code in this file allows testfixture to control another process (or +# processes) to test locking. +# + +proc do_multiclient_test {varname script} { + + foreach code [list { + if {[info exists ::G(valgrind)]} { db close ; continue } + set ::code2_chan [launch_testfixture] + set ::code3_chan [launch_testfixture] + proc code2 {tcl} { testfixture $::code2_chan $tcl } + proc code3 {tcl} { testfixture $::code3_chan $tcl } + set tn 1 + } { + proc code2 {tcl} { uplevel #0 $tcl } + proc code3 {tcl} { uplevel #0 $tcl } + set tn 2 + }] { + faultsim_delete_and_reopen + + proc code1 {tcl} { uplevel #0 $tcl } + + # Open connections [db2] and [db3]. Depending on which iteration this + # is, the connections may be created in this interpreter, or in + # interpreters running in other OS processes. As such, the [db2] and [db3] + # commands should only be accessed within [code2] and [code3] blocks, + # respectively. + # + eval $code + code2 { sqlite3 db2 test.db } + code3 { sqlite3 db3 test.db } + + # Shorthand commands. Execute SQL using database connection [db2] or + # [db3]. Return the results. + # + proc sql1 {sql} { db eval $sql } + proc sql2 {sql} { code2 [list db2 eval $sql] } + proc sql3 {sql} { code3 [list db3 eval $sql] } + + proc csql1 {sql} { list [catch { sql1 $sql } msg] $msg } + proc csql2 {sql} { list [catch { sql2 $sql } msg] $msg } + proc csql3 {sql} { list [catch { sql3 $sql } msg] $msg } + + uplevel set $varname $tn + uplevel $script + + catch { code2 { db2 close } } + catch { code3 { db3 close } } + catch { close $::code2_chan } + catch { close $::code3_chan } + catch { db close } + } +} + +# Launch another testfixture process to be controlled by this one. A +# channel name is returned that may be passed as the first argument to proc +# 'testfixture' to execute a command. The child testfixture process is shut +# down by closing the channel. +proc launch_testfixture {{prg ""}} { + write_main_loop + if {$prg eq ""} { set prg [info nameofexec] } + if {$prg eq ""} { set prg testfixture } + if {[file tail $prg]==$prg} { set prg [file join . $prg] } + set chan [open "|$prg tf_main.tcl" r+] + fconfigure $chan -buffering line + set rc [catch { + testfixture $chan "sqlite3_test_control_pending_byte $::sqlite_pending_byte" + }] + if {$rc} { + testfixture $chan "set ::sqlite_pending_byte $::sqlite_pending_byte" + } + return $chan +} + +# Execute a command in a child testfixture process, connected by two-way +# channel $chan. Return the result of the command, or an error message. +# +proc testfixture {chan cmd} { + puts $chan $cmd + puts $chan OVER + set r "" + while { 1 } { + set line [gets $chan] + if { $line == "OVER" } { + set res [lindex $r 1] + if { [lindex $r 0] } { error $res } + return $res + } + if {[eof $chan]} { + return "ERROR: Child process hung up" + } + append r $line + } +} + +proc testfixture_nb_cb {varname chan} { + if {[eof $chan]} { + append ::tfnb($chan) "ERROR: Child process hung up" + set line "OVER" + } else { + set line [gets $chan] + } + + if { $line == "OVER" } { + set $varname [lindex $::tfnb($chan) 1] + unset ::tfnb($chan) + close $chan + } else { + append ::tfnb($chan) $line + } +} + +proc testfixture_nb {varname cmd} { + set chan [launch_testfixture] + set ::tfnb($chan) "" + fconfigure $chan -blocking 0 -buffering none + puts $chan $cmd + puts $chan OVER + fileevent $chan readable [list testfixture_nb_cb $varname $chan] + return "" +} + +# Write the main loop for the child testfixture processes into file +# tf_main.tcl. The parent (this script) interacts with the child processes +# via a two way pipe. The parent writes a script to the stdin of the child +# process, followed by the word "OVER" on a line of its own. The child +# process evaluates the script and writes the results to stdout, followed +# by an "OVER" of its own. +# +set main_loop_written 0 +proc write_main_loop {} { + if {$::main_loop_written} return + set wrapper "" + if {[sqlite3 -has-codec] && [info exists ::do_not_use_codec]==0} { + set wrapper " + rename sqlite3 sqlite_orig + proc sqlite3 {args} {[info body sqlite3]} + " + } + + set fd [open tf_main.tcl w] + puts $fd [string map [list %WRAPPER% $wrapper] { + %WRAPPER% + set script "" + while {![eof stdin]} { + flush stdout + set line [gets stdin] + if { $line == "OVER" } { + set rc [catch {eval $script} result] + puts [list $rc $result] + puts OVER + flush stdout + set script "" + } else { + append script $line + append script "\n" + } + } + }] + close $fd + set main_loop_written 1 +} + diff --git a/components/external/SQLite-3.8.1/test/lookaside.test b/components/external/SQLite-3.8.1/test/lookaside.test new file mode 100644 index 0000000000000000000000000000000000000000..0b239a04d5e1c0bd57b73e24d2c05cfe379f922e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/lookaside.test @@ -0,0 +1,132 @@ +# 2008 August 01 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests for the lookaside memory allocator. +# +# $Id: lookaside.test,v 1.10 2009/04/09 01:23:49 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !lookaside { + finish_test + return +} + +# The tests in this file configure the lookaside allocator after a +# connection is opened. This will not work if there is any "presql" +# configured (SQL run within the [sqlite3] wrapper in tester.tcl). +if {[info exists ::G(perm:presql)]} { + finish_test + return +} + +catch {db close} +sqlite3_shutdown +sqlite3_config_pagecache 0 0 +sqlite3_config_scratch 0 0 +sqlite3_initialize +autoinstall_test_functions +sqlite3 db test.db + +# Make sure sqlite3_db_config() and sqlite3_db_status are working. +# +do_test lookaside-1.1 { + catch {sqlite3_config_error db} +} {0} + +do_test lookaside-1.2 { + sqlite3_db_config_lookaside db 1 18 18 +} {0} +do_test lookaside-1.3.1 { + sqlite3_db_status db DBSTATUS_LOOKASIDE_USED 0 +} {0 0 0} +do_test lookaside-1.3.2 { + sqlite3_db_status db DBSTATUS_LOOKASIDE_HIT 0 +} {0 0 0} +do_test lookaside-1.3.3 { + sqlite3_db_status db DBSTATUS_LOOKASIDE_MISS_SIZE 0 +} {0 0 0} +do_test lookaside-1.3.4 { + sqlite3_db_status db DBSTATUS_LOOKASIDE_MISS_FULL 0 +} {0 0 0} + +do_test lookaside-1.4 { + db eval {CREATE TABLE t1(w,x,y,z);} + foreach {x y z} [sqlite3_db_status db DBSTATUS_LOOKASIDE_USED 0] break + set p [lindex [sqlite3_db_status db DBSTATUS_LOOKASIDE_HIT 0] 2] + set q [lindex [sqlite3_db_status db DBSTATUS_LOOKASIDE_MISS_SIZE 0] 2] + set r [lindex [sqlite3_db_status db DBSTATUS_LOOKASIDE_MISS_FULL 0] 2] + expr {$x==0 && $y<$z && $z==18 && $p>0 && $q>0 && $r>0} +} {0} +do_test lookaside-1.5 { + foreach {x y z} [sqlite3_db_status db DBSTATUS_LOOKASIDE_USED 1] break + expr {$x==0 && $y<$z && $z==18} +} {0} +do_test lookaside-1.6 { + foreach {x y z} [sqlite3_db_status db DBSTATUS_LOOKASIDE_USED 0] break + expr {$x==0 && $y==$z && $y<18} +} {1} +do_test lookaside-1.7 { + db cache flush + foreach {x y z} [sqlite3_db_status db DBSTATUS_LOOKASIDE_USED 0] break + expr {$x==0 && $y==0 && $z<18} +} {1} +do_test lookaside-1.8 { + db cache flush + foreach {x y z} [sqlite3_db_status db DBSTATUS_LOOKASIDE_USED 1] break + expr {$x==0 && $y==0 && $z<18} +} {1} +do_test lookaside-1.9 { + db cache flush + sqlite3_db_status db DBSTATUS_LOOKASIDE_USED 0 +} {0 0 0} + +do_test lookaside-2.1 { + sqlite3_db_config_lookaside db 0 100 1000 +} {0} +do_test lookaside-2.2 { + db eval {CREATE TABLE t2(x);} + foreach {x y z} [sqlite3_db_status db DBSTATUS_LOOKASIDE_USED 0] break + expr {$x==0 && $y<$z && $z>10 && $z<100} +} {1} +do_test lookaside-2.3 { + sqlite3_db_config_lookaside db 0 50 50 +} {5} ;# SQLITE_BUSY +do_test lookaside-2.4 { + db cache flush + sqlite3_db_config_lookaside db 0 50 50 +} {0} ;# SQLITE_OK +do_test lookaside-2.5 { + sqlite3_db_config_lookaside db 0 -1 50 +} {0} ;# SQLITE_OK +do_test lookaside-2.6 { + sqlite3_db_config_lookaside db 0 50 -1 +} {0} ;# SQLITE_OK + +# sqlite3_db_status() with an invalid verb returns an error. +# +do_test lookaside-3.1 { + sqlite3_db_status db 99999 0 +} {1 0 0} + +# Test that an invalid verb on sqlite3_config() is detected and +# reported as an error. +# +do_test lookaside-4.1 { + db close + sqlite3_shutdown + catch sqlite3_config_error +} {0} +sqlite3_initialize +autoinstall_test_functions + +finish_test diff --git a/components/external/SQLite-3.8.1/test/main.test b/components/external/SQLite-3.8.1/test/main.test new file mode 100644 index 0000000000000000000000000000000000000000..5bbc52b84509b901f460459c6e63ff807b81e5f6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/main.test @@ -0,0 +1,518 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is exercising the code in main.c. +# +# $Id: main.test,v 1.32 2009/04/28 04:51:29 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Only do the next group of tests if the sqlite3_complete API is available +# +ifcapable {complete} { + +# Tests of the sqlite_complete() function. +# +do_test main-1.1 { + db complete {This is a test} +} {0} +do_test main-1.2.0 { + db complete { + } +} {0} +do_test main-1.2.1 { + db complete {} +} {0} +do_test main-1.3.0 { + db complete { + -- a comment ; + } +} {0} +do_test main-1.3.1 { + db complete { + /* a comment ; */ + } +} {0} +do_test main-1.4.0 { + db complete { + -- a comment ; + ; + } +} {1} +do_test main-1.4.1 { + db complete { + /* a comment ; */ + ; + } +} {1} +do_test main-1.4.2 { + db complete { + /* a comment ; */ ; + } +} {1} +do_test main-1.5 { + db complete {DROP TABLE 'xyz;} +} {0} +do_test main-1.6 { + db complete {DROP TABLE 'xyz';} +} {1} +do_test main-1.7 { + db complete {DROP TABLE "xyz;} +} {0} +do_test main-1.8 { + db complete {DROP TABLE "xyz';} +} {0} +do_test main-1.9 { + db complete {DROP TABLE "xyz";} +} {1} +do_test main-1.10 { + db complete {DROP TABLE xyz; hi} +} {0} +do_test main-1.11 { + db complete {DROP TABLE xyz; } +} {1} +do_test main-1.12 { + db complete {DROP TABLE xyz; -- hi } +} {1} +do_test main-1.13 { + db complete {DROP TABLE xyz; -- hi + } +} {1} +do_test main-1.14 { + db complete {SELECT a-b FROM t1; } +} {1} +do_test main-1.15 { + db complete {SELECT a/e FROM t1 } +} {0} +do_test main-1.16 { + db complete { + CREATE TABLE abc(x,y); + } +} {1} +ifcapable {trigger} { + do_test main-1.17 { + db complete { + CREATE TRIGGER xyz AFTER DELETE abc BEGIN UPDATE pqr; + } + } {0} + do_test main-1.17.2 { + db complete { + EXPLAIN CREATE TRIGGER xyz AFTER DELETE abc BEGIN UPDATE pqr; + } + } {0} + do_test main-1.17.3 { + db complete { + EXPLAIN QUERY PLAN CREATE TRIGGER xyz AFTER DELETE abc BEGIN UPDATE pqr; + } + } {0} + do_test main-1.18 { + db complete { + CREATE TRIGGER xyz AFTER DELETE abc BEGIN UPDATE pqr; END; + } + } {1} + do_test main-1.19 { + db complete { + CREATE TRIGGER xyz AFTER DELETE abc BEGIN + UPDATE pqr; + unknown command; + } + } {0} + do_test main-1.20 { + db complete { + CREATE TRIGGER xyz AFTER DELETE backend BEGIN + UPDATE pqr; + } + } {0} + do_test main-1.21 { + db complete { + CREATE TRIGGER xyz AFTER DELETE end BEGIN + SELECT a, b FROM end; + } + } {0} + do_test main-1.22 { + db complete { + CREATE TRIGGER xyz AFTER DELETE end BEGIN + SELECT a, b FROM end; + END; + } + } {1} + do_test main-1.23 { + db complete { + CREATE TRIGGER xyz AFTER DELETE end BEGIN + SELECT a, b FROM end; + END; + SELECT a, b FROM end; + } + } {1} + do_test main-1.24 { + db complete { + CREATE TRIGGER xyz AFTER DELETE [;end;] BEGIN + UPDATE pqr; + } + } {0} + do_test main-1.25 { + db complete { + CREATE TRIGGER xyz AFTER DELETE backend BEGIN + UPDATE cantor SET a=[;end;];;; + } + } {0} + do_test main-1.26 { + db complete { + CREATE -- a comment + TRIGGER exy AFTER DELETE backend BEGIN + UPDATE pqr SET a=5; + } + } {0} + do_test main-1.27.1 { + db complete { + CREATE -- a comment + TRIGGERX tangentxx AFTER DELETE backend BEGIN + UPDATE pqr SET a=5; + } + } {1} + do_test main-1.27.2 { + db complete { + CREATE/**/TRIGGER tiger00 AFTER DELETE backend BEGIN + UPDATE pqr SET a=5; + } + } {0} + ifcapable {explain} { + do_test main-1.27.3 { + db complete { + /* */ EXPLAIN -- A comment + CREATE/**/TRIGGER ezxyz12 AFTER DELETE backend BEGIN + UPDATE pqr SET a=5; + } + } {0} + } + do_test main-1.27.4 { + db complete { + BOGUS token + CREATE TRIGGER xyz AFTER DELETE backend BEGIN + UPDATE pqr SET a=5; + } + } {1} + ifcapable {explain} { + do_test main-1.27.5 { + db complete { + EXPLAIN + CREATE TEMP TRIGGER xyz AFTER DELETE backend BEGIN + UPDATE pqr SET a=5; + } + } {0} + } + do_test main-1.28 { + db complete { + CREATE TEMPORARY TRIGGER xyz AFTER DELETE backend BEGIN + UPDATE pqr SET a=5; + } + } {0} + do_test main-1.29 { + db complete { + CREATE TRIGGER xyz AFTER DELETE backend BEGIN + UPDATE pqr SET a=5; + EXPLAIN select * from xyz; + } + } {0} + +} ;# end ifcapable {complete} + +} +do_test main-1.30 { + db complete { + CREATE TABLE /* In comment ; */ + } +} {0} +do_test main-1.31 { + db complete { + CREATE TABLE /* In comment ; */ hi; + } +} {1} +do_test main-1.31 { + db complete { + CREATE TABLE /* In comment ; */; + } +} {1} +do_test main-1.32 { + db complete { + stuff; + /* + CREATE TABLE + multiple lines + of text + */ + } +} {1} +do_test main-1.33 { + db complete { + /* + CREATE TABLE + multiple lines + of text; + } +} {0} +do_test main-1.34 { + db complete { + /* + CREATE TABLE + multiple lines "*/ + of text; + } +} {1} +do_test main-1.35 { + db complete {hi /**/ there;} +} {1} +do_test main-1.36 { + db complete {hi there/***/;} +} {1} +do_test main-1.37 { + db complete {hi there/**} +} {0} +do_test main-1.38 { + db complete {hi [there} +} {0} + +ifcapable {trigger} { + # Characters less than \040 can never be part of an identifier. + # Characters greater than \u177 are always identifier characters. + do_test main-1.100 { + db complete "create \037\036\035\034trigger\001\002;" + } {1} + do_test main-1.101 { + db complete "create trigger\200;" + } {1} + do_test main-1.102 { + db complete "create \200trigger;" + } {1} +} + + +# Try to open a database with a corrupt database file. +# +if {[permutation] == ""} { + do_test main-2.0 { + catch {db close} + forcedelete test.db + set fd [open test.db w] + puts $fd hi! + close $fd + set v [catch {sqlite3 db test.db} msg] + if {$v} {lappend v $msg} {lappend v {}} + } {0 {}} +} + +# Here are some tests for tokenize.c. +# +do_test main-3.1 { + catch {db close} + foreach f [glob -nocomplain testdb/*] {forcedelete $f} + forcedelete testdb + sqlite3 db testdb + set v [catch {execsql {SELECT * from T1 where x!!5}} msg] + lappend v $msg +} {1 {unrecognized token: "!!"}} +do_test main-3.2 { + catch {db close} + foreach f [glob -nocomplain testdb/*] {forcedelete $f} + forcedelete testdb + sqlite3 db testdb + set v [catch {execsql {SELECT * from T1 where ^x}} msg] + lappend v $msg +} {1 {unrecognized token: "^"}} +do_test main-3.2.2 { + catchsql {select 'abc} +} {1 {unrecognized token: "'abc"}} +do_test main-3.2.3 { + catchsql {select "abc} +} {1 {unrecognized token: ""abc"}} +do_test main-3.2.4 { + catchsql {select [abc} +} {1 {unrecognized token: "[abc"}} +do_test main-3.2.5 { + catchsql {select x'4869} +} {1 {unrecognized token: "x'4869"}} +do_test main-3.2.6 { + catchsql {select x'4869'} +} {0 Hi} +do_test main-3.2.7 { + catchsql {select x'48695'} +} {1 {unrecognized token: "x'48695'"}} +do_test main-3.2.8 { + catchsql {select x'486x'} +} {1 {unrecognized token: "x'486x'"}} +do_test main-3.2.9 { + catchsql {select $abc(} +} {1 {unrecognized token: "$abc("}} +do_test main-3.2.10 { + catchsql {select $abc(x} +} {1 {unrecognized token: "$abc(x"}} +set xyz 123 +do_test main-3.2.11 { + catchsql {select $::xyz} +} {0 123} +namespace eval ::testnamespace { + variable xyz 321 +} +do_test main-3.2.12 { + catchsql {select $testnamespace::xyz} +} {0 321} +do_test main-3.2.13 { + catchsql {select $(abc)} +} {1 {unrecognized token: "$"}} +do_test main-3.2.14 { + set hi\u1234x 987 + db eval "select \$hi\u1234x" +} {987} +do_test main-3.2.15 { + catchsql "select 456\u1234" +} [list 1 "unrecognized token: \"456\u1234\""] +do_test main-3.2.16 { + catchsql {select cast(3.14e+4 AS integer)} +} {0 31400} +do_test main-3.2.17 { + catchsql {select cast(3.14e+04 AS integer)} +} {0 31400} +do_test main-3.2.18 { + catchsql {select cast(3.14e+004 AS integer)} +} {0 31400} +do_test main-3.2.19 { + catchsql {select cast(3.14e4 AS integer)} +} {0 31400} +do_test main-3.2.20 { + catchsql {select cast(3.14e04 AS integer)} +} {0 31400} +do_test main-3.2.21 { + catchsql {select cast(3.14e004 AS integer)} +} {0 31400} +do_test main-3.2.16 { + catchsql {select cast(3.14E+4 AS integer)} +} {0 31400} +do_test main-3.2.17 { + catchsql {select cast(3.14E+04 AS integer)} +} {0 31400} +do_test main-3.2.18 { + catchsql {select cast(3.14E+004 AS integer)} +} {0 31400} +do_test main-3.2.19 { + catchsql {select cast(3.14E4 AS integer)} +} {0 31400} +do_test main-3.2.20 { + catchsql {select cast(3.14E04 AS integer)} +} {0 31400} +do_test main-3.2.21 { + catchsql {select cast(3.14E004 AS integer)} +} {0 31400} +do_test main-3.2.22 { + catchsql {select cast(3.14e-4 * 1e8 AS integer)} +} {0 31400} +do_test main-3.2.23 { + catchsql {select cast(3.14E-04 * 1E08 AS integer)} +} {0 31400} +do_test main-3.2.24 { + catchsql {select cast(3.14e-004 * 01.0E+8 AS integer)} +} {0 31400} +do_test main-3.2.25 { + catchsql {select 123/*abc} +} {0 123} +do_test main-3.2.26 { + catchsql {select 123/***abc} +} {0 123} +do_test main-3.2.27 { + catchsql {select 123/*/*2} +} {0 123} +do_test main-3.2.28 { + catchsql {select 123/**/*2} +} {0 246} +do_test main-3.2.29 { + catchsql {select 123/} +} {1 {near "/": syntax error}} +do_test main-3.2.30 { + catchsql {select 123--5} +} {0 123} + + +do_test main-3.3 { + catch {db close} + foreach f [glob -nocomplain testdb/*] {forcedelete $f} + forcedelete testdb + sqlite3 db testdb + execsql { + create table T1(X REAL); /* C-style comments allowed */ + insert into T1 values(0.5); + insert into T1 values(0.5e2); + insert into T1 values(0.5e-002); + insert into T1 values(5e-002); + insert into T1 values(-5.0e-2); + insert into T1 values(-5.1e-2); + insert into T1 values(0.5e2); + insert into T1 values(0.5E+02); + insert into T1 values(5E+02); + insert into T1 values(5.0E+03); + select x*10 from T1 order by x*5; + } +} {-0.51 -0.5 0.05 0.5 5.0 500.0 500.0 500.0 5000.0 50000.0} +do_test main-3.4 { + set v [catch {execsql {create bogus}} msg] + lappend v $msg +} {1 {near "bogus": syntax error}} +do_test main-3.5 { + set v [catch {execsql {create}} msg] + lappend v $msg +} {1 {near "create": syntax error}} +do_test main-3.6 { + catchsql {SELECT 'abc' + #9} +} {1 {near "#9": syntax error}} + +# The following test-case tests the linked list code used to manage +# sqlite3_vfs structures. +if {$::tcl_platform(platform)=="unix" + && [info command sqlite3async_initialize]!=""} { + ifcapable threadsafe { + do_test main-4.1 { + sqlite3_crash_enable 1 + sqlite3_crash_enable 0 + + sqlite3async_initialize "" 1 + sqlite3async_shutdown + + sqlite3_crash_enable 1 + sqlite3async_initialize "" 1 + sqlite3_crash_enable 0 + sqlite3async_shutdown + + sqlite3_crash_enable 1 + sqlite3async_initialize "" 1 + sqlite3async_shutdown + sqlite3_crash_enable 0 + + sqlite3async_initialize "" 1 + sqlite3_crash_enable 1 + sqlite3_crash_enable 0 + sqlite3async_shutdown + + sqlite3async_initialize "" 1 + sqlite3_crash_enable 1 + sqlite3async_shutdown + sqlite3_crash_enable 0 + } {} + do_test main-4.2 { + set rc [catch {sqlite3 db test.db -vfs crash} msg] + list $rc $msg + } {1 {no such vfs: crash}} + do_test main-4.3 { + set rc [catch {sqlite3 db test.db -vfs async} msg] + list $rc $msg + } {1 {no such vfs: async}} + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/make-where7.tcl b/components/external/SQLite-3.8.1/test/make-where7.tcl new file mode 100644 index 0000000000000000000000000000000000000000..706f18451c27124ff88e8d93bc6470e3ece7d63c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/make-where7.tcl @@ -0,0 +1,120 @@ +#!/usr/bin/tclsh +# +# Run this script to generate randomized test cases for the where7.test +# script. The output will need to be manually copied and pasted into +# the where7.test script. +# +puts "do_test where7-2.1 \173" +puts " db eval \173" +puts " CREATE TABLE t2(a INTEGER PRIMARY KEY,b,c,d,e,f,g);" +set NA 100 +for {set a 1} {$a<=$NA} {incr a} { + set b [expr {$a*11}] + set div3 [expr {int(($a+2)/3)}] + set c [expr {$div3*1001}] + set d [expr {$a*1.001}] + set e [expr {$div3*100.1}] + set x [expr {$a%26}] + set f [string range {abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz} \ + $x [expr {$x+8}]] + set div5 [expr {int(($a+7)/5)}] + set x [expr {$div5%26}] + set g [string range {zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba} \ + $x [expr {$x+6}]] + puts " INSERT INTO t2 VALUES($a,$b,$c,$d,$e,'$f','$g');" + lappend fidx($f) $a + lappend gidx($g) $a + set gof($a) $g + set fof($a) $f + + set expr "a=$a" + set term($expr) $a + set expr "((a BETWEEN [expr {$a-1}] AND [expr {$a+1}]) AND a!=$a)" + set x {} + if {$a>1} {set x [expr {$a-1}]} + if {$a<$NA} {lappend x [expr {$a+1}]} + set term($expr) $x + set expr "b=$b" + set term($expr) $a + set expr "b=[expr {$a*11+3}]" + set term($expr) {} + set expr "c=$c" + lappend term($expr) $a + set expr "(d>=$a.0 AND d<[expr {$a+1.0}] AND d NOT NULL)" + lappend term($expr) $a + set expr "f='$f'" + lappend term($expr) $a + set expr \ + "(f GLOB '?[string range $f 1 4]*' AND f GLOB '[string range $f 0 3]*')" + lappend term($expr) $a + set expr "(g='$g' AND f GLOB '[string range $f 0 4]*')" + lappend term($expr) $a +} +puts " CREATE INDEX t2b ON t2(b);" +puts " CREATE INDEX t2c ON t2(c);" +puts " CREATE INDEX t2d ON t2(d);" +puts " CREATE INDEX t2e ON t2(e);" +puts " CREATE INDEX t2f ON t2(f);" +puts " CREATE INDEX t2g ON t2(g);" +puts " CREATE TABLE t3(a INTEGER PRIMARY KEY,b,c,d,e,f,g);" +puts " INSERT INTO t3 SELECT * FROM t2;" +puts " CREATE INDEX t3b ON t3(b,c);" +puts " CREATE INDEX t3c ON t3(c,e);" +puts " CREATE INDEX t3d ON t3(d,g);" +puts " CREATE INDEX t3e ON t3(e,f,g);" +puts " CREATE INDEX t3f ON t3(f,b,d,c);" +puts " CREATE INDEX t3g ON t3(g,f);" + +puts " \175" +puts "\175 {}" + +set term(b<0) {} +set term(1000000=[expr {int(($NA+2)/3)*1001+1}]) {} +set term(d<0.0) {} +set term(d>1e10) {} +set expr {e IS NULL} +set term($expr) {} +set expr {f IS NULL} +set term($expr) {} +set expr {g IS NULL} +set term($expr) {} + +set NT 1000 +set termlist [array names term] +set nterm [llength $termlist] +for {set i 2} {$i<=$NT+1} {incr i} { + set n [expr {int(rand()*10)+2}] + set w {} + unset -nocomplain r + for {set j 0} {$j<$n} {incr j} { + set k [expr {int(rand()*$nterm)}] + set t [lindex $termlist $k] + lappend w $t + foreach a $term($t) { + set r($a) 1 + } + } + if {[info exists seen($w)]} { + incr i -1 + continue + } + set seen($w) 1 + set result [lsort -int [array names r]] + puts "do_test where7-2.$i.1 \173" + puts " count_steps_sort \173" + puts " SELECT a FROM t2" + set wc [join $w "\n OR "] + puts " WHERE $wc" + puts " \175" + puts "\175 {$result scan 0 sort 0}" + puts "do_test where7-2.$i.2 \173" + puts " count_steps_sort \173" + puts " SELECT a FROM t3" + set wc [join $w "\n OR "] + puts " WHERE $wc" + puts " \175" + puts "\175 {$result scan 0 sort 0}" +} +puts "finish_test" diff --git a/components/external/SQLite-3.8.1/test/malloc.test b/components/external/SQLite-3.8.1/test/malloc.test new file mode 100644 index 0000000000000000000000000000000000000000..5d03aa8fe89e51026e4acfceb35962574c4ce0d3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/malloc.test @@ -0,0 +1,890 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file attempts to check the behavior of the SQLite library in +# an out-of-memory situation. When compiled with -DSQLITE_DEBUG=1, +# the SQLite library accepts a special command (sqlite3_memdebug_fail N C) +# which causes the N-th malloc to fail. This special feature is used +# to see what happens in the library if a malloc were to really fail +# due to an out-of-memory situation. +# +# $Id: malloc.test,v 1.81 2009/06/24 13:13:45 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +# Only run these tests if memory debugging is turned on. +# +source $testdir/malloc_common.tcl +if {!$MEMDEBUG} { + puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + +# Do a couple of memory dumps just to exercise the memory dump logic +# that that we can say that we have. +# +puts stderr "This is a test. Ignore the error that follows:" +sqlite3_memdebug_dump $testdir +puts "Memory dump to file memdump.txt..." +sqlite3_memdebug_dump memdump.txt + +ifcapable bloblit&&subquery { + do_malloc_test 1 -tclprep { + db close + } -tclbody { + if {[catch {sqlite3 db test.db}]} { + error "out of memory" + } + sqlite3_extended_result_codes db 1 + } -sqlbody { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1( + a int, b float, c double, d text, e varchar(20), + primary key(a,b,c) + ); + CREATE INDEX i1 ON t1(a,b); + INSERT INTO t1 VALUES(1,2.3,4.5,'hi',x'746865726500'); + INSERT INTO t1 VALUES(6,7.0,0.8,'hello','out yonder'); + SELECT * FROM t1; + SELECT avg(b) FROM t1 GROUP BY a HAVING b>20.0; + DELETE FROM t1 WHERE a IN (SELECT min(a) FROM t1); + SELECT count(*), group_concat(e) FROM t1; + SELECT b FROM t1 ORDER BY 1 COLLATE nocase; + } +} + +# Ensure that no file descriptors were leaked. +do_test malloc-1.X { + catch {db close} + set sqlite_open_file_count +} {0} + +ifcapable subquery { + do_malloc_test 2 -sqlbody { + CREATE TABLE t1(a int, b int default 'abc', c int default 1); + CREATE INDEX i1 ON t1(a,b); + INSERT INTO t1 VALUES(1,1,'99 abcdefghijklmnopqrstuvwxyz'); + INSERT INTO t1 VALUES(2,4,'98 abcdefghijklmnopqrstuvwxyz'); + INSERT INTO t1 VALUES(3,9,'97 abcdefghijklmnopqrstuvwxyz'); + INSERT INTO t1 VALUES(4,16,'96 abcdefghijklmnopqrstuvwxyz'); + INSERT INTO t1 VALUES(5,25,'95 abcdefghijklmnopqrstuvwxyz'); + INSERT INTO t1 VALUES(6,36,'94 abcdefghijklmnopqrstuvwxyz'); + SELECT 'stuff', count(*) as 'other stuff', max(a+10) FROM t1; + UPDATE t1 SET b=b||b||b||b; + UPDATE t1 SET b=a WHERE a in (10,12,22); + INSERT INTO t1(c,b,a) VALUES(20,10,5); + INSERT INTO t1 SELECT * FROM t1 + WHERE a IN (SELECT a FROM t1 WHERE a<10); + DELETE FROM t1 WHERE a>=10; + DROP INDEX i1; + DELETE FROM t1; + } +} + +# Ensure that no file descriptors were leaked. +do_test malloc-2.X { + catch {db close} + set sqlite_open_file_count +} {0} + +do_malloc_test 3 -sqlbody { + BEGIN TRANSACTION; + CREATE TABLE t1(a int, b int, c int); + CREATE INDEX i1 ON t1(a,b); + INSERT INTO t1 VALUES(1,1,99); + INSERT INTO t1 VALUES(2,4,98); + INSERT INTO t1 VALUES(3,9,97); + INSERT INTO t1 VALUES(4,16,96); + INSERT INTO t1 VALUES(5,25,95); + INSERT INTO t1 VALUES(6,36,94); + INSERT INTO t1(c,b,a) VALUES(20,10,5); + DELETE FROM t1 WHERE a>=10; + DROP INDEX i1; + DELETE FROM t1; + ROLLBACK; +} + + +# Ensure that no file descriptors were leaked. +do_test malloc-3.X { + catch {db close} + set sqlite_open_file_count +} {0} + +ifcapable subquery { + do_malloc_test 4 -sqlbody { + BEGIN TRANSACTION; + CREATE TABLE t1(a int, b int, c int); + CREATE INDEX i1 ON t1(a,b); + INSERT INTO t1 VALUES(1,1,99); + INSERT INTO t1 VALUES(2,4,98); + INSERT INTO t1 VALUES(3,9,97); + INSERT INTO t1 VALUES(4,16,96); + INSERT INTO t1 VALUES(5,25,95); + INSERT INTO t1 VALUES(6,36,94); + UPDATE t1 SET b=a WHERE a in (10,12,22); + INSERT INTO t1 SELECT * FROM t1 + WHERE a IN (SELECT a FROM t1 WHERE a<10); + DROP INDEX i1; + DELETE FROM t1; + COMMIT; + } +} + +# Ensure that no file descriptors were leaked. +do_test malloc-4.X { + catch {db close} + set sqlite_open_file_count +} {0} + +ifcapable trigger { + do_malloc_test 5 -sqlbody { + BEGIN TRANSACTION; + CREATE TABLE t1(a,b); + CREATE TABLE t2(x,y); + CREATE TRIGGER r1 AFTER INSERT ON t1 WHEN new.a = 2 BEGIN + INSERT INTO t2(x,y) VALUES(new.rowid,1); + INSERT INTO t2(x,y) SELECT * FROM t2; + INSERT INTO t2 SELECT * FROM t2; + UPDATE t2 SET y=y+1 WHERE x=new.rowid; + SELECT 123; + DELETE FROM t2 WHERE x=new.rowid; + END; + INSERT INTO t1(a,b) VALUES(2,3); + COMMIT; + } +} + +# Ensure that no file descriptors were leaked. +do_test malloc-5.X { + catch {db close} + set sqlite_open_file_count +} {0} + +ifcapable vacuum { + do_malloc_test 6 -sqlprep { + BEGIN TRANSACTION; + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 SELECT a*2 FROM t1; + INSERT INTO t1 SELECT a*2 FROM t1; + INSERT INTO t1 SELECT a*2 FROM t1; + INSERT INTO t1 SELECT a*2 FROM t1; + INSERT INTO t1 SELECT a*2 FROM t1; + INSERT INTO t1 SELECT a*2 FROM t1; + INSERT INTO t1 SELECT a*2 FROM t1; + INSERT INTO t1 SELECT a*2 FROM t1; + INSERT INTO t1 SELECT a*2 FROM t1; + INSERT INTO t1 SELECT a*2 FROM t1; + DELETE FROM t1 where rowid%5 = 0; + COMMIT; + } -sqlbody { + VACUUM; + } +} + +autoinstall_test_functions +do_malloc_test 7 -sqlprep { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t1 VALUES(5, 6); + INSERT INTO t1 VALUES(7, randstr(1200,1200)); +} -sqlbody { + SELECT min(a) FROM t1 WHERE a<6 GROUP BY b; + SELECT a FROM t1 WHERE a<6 ORDER BY a; + SELECT b FROM t1 WHERE a>6; +} + +# This block is designed to test that some malloc failures that may +# occur in vdbeapi.c. Specifically, if a malloc failure that occurs +# when converting UTF-16 text to integers and real numbers is handled +# correctly. +# +# This is done by retrieving a string from the database engine and +# manipulating it using the sqlite3_column_*** APIs. This doesn't +# actually return an error to the user when a malloc() fails.. That +# could be viewed as a bug. +# +# These tests only run if UTF-16 support is compiled in. +# +ifcapable utf16 { + set ::STMT {} + do_malloc_test 8 -tclprep { + set sql "SELECT '[string repeat abc 20]', '[string repeat def 20]', ?" + set ::STMT [sqlite3_prepare db $sql -1 X] + sqlite3_step $::STMT + if { $::tcl_platform(byteOrder)=="littleEndian" } { + set ::bomstr "\xFF\xFE" + } else { + set ::bomstr "\xFE\xFF" + } + append ::bomstr [encoding convertto unicode "123456789_123456789_123456789"] + } -tclbody { + sqlite3_column_text16 $::STMT 0 + sqlite3_column_int $::STMT 0 + sqlite3_column_text16 $::STMT 1 + sqlite3_column_double $::STMT 1 + set rc [sqlite3_reset $::STMT] + if {$rc eq "SQLITE_NOMEM"} {error "out of memory"} + sqlite3_bind_text16 $::STMT 1 $::bomstr 60 + #catch {sqlite3_finalize $::STMT} + #if {[lindex [sqlite_malloc_stat] 2]<=0} { + # error "out of memory" + #} + } -cleanup { + if {$::STMT!=""} { + sqlite3_finalize $::STMT + set ::STMT {} + } + } +} + +# This block tests that malloc() failures that occur whilst commiting +# a multi-file transaction are handled correctly. +# +do_malloc_test 9 -sqlprep { + ATTACH 'test2.db' as test2; + CREATE TABLE abc1(a, b, c); + CREATE TABLE test2.abc2(a, b, c); +} -sqlbody { + BEGIN; + INSERT INTO abc1 VALUES(1, 2, 3); + INSERT INTO abc2 VALUES(1, 2, 3); + COMMIT; +} + +# This block tests malloc() failures that occur while opening a +# connection to a database. +do_malloc_test 10 -tclprep { + catch {db2 close} + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + sqlite3_extended_result_codes db 1 + db eval {CREATE TABLE abc(a, b, c)} +} -tclbody { + db close + sqlite3 db2 test.db + sqlite3_extended_result_codes db2 1 + db2 eval {SELECT * FROM sqlite_master} + db2 close +} + +# This block tests malloc() failures that occur within calls to +# sqlite3_create_function(). +do_malloc_test 11 -tclbody { + set rc [sqlite3_create_function db] + if {[string match $rc SQLITE_OK]} { + set rc [sqlite3_create_aggregate db] + } + if {[string match $rc SQLITE_NOMEM]} { + error "out of memory" + } +} + +do_malloc_test 12 -tclbody { + set sql16 [encoding convertto unicode "SELECT * FROM sqlite_master"] + append sql16 "\00\00" + set ::STMT [sqlite3_prepare16 db $sql16 -1 DUMMY] + sqlite3_finalize $::STMT +} + +# Test malloc errors when replaying two hot journals from a 2-file +# transaction. +ifcapable crashtest&&attach { + do_malloc_test 13 -tclprep { + set rc [crashsql -delay 1 -file test2.db { + ATTACH 'test2.db' as aux; + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE aux.t2(a, b, c); + CREATE TABLE t1(a, b, c); + COMMIT; + }] + if {$rc!="1 {child process exited abnormally}"} { + error "Wrong error message: $rc" + } + } -tclbody { + db eval {ATTACH 'test2.db' as aux;} + set rc [catch {db eval { + SELECT * FROM t1; + SELECT * FROM t2; + }} err] + if {$rc && $err!="no such table: t1"} { + error $err + } + } +} + +if {$tcl_platform(platform)!="windows"} { + do_malloc_test 14 -tclprep { + catch {db close} + sqlite3 db2 test2.db + sqlite3_extended_result_codes db2 1 + db2 eval { + PRAGMA journal_mode = DELETE; /* For inmemory_journal permutation */ + PRAGMA synchronous = 0; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + BEGIN; + INSERT INTO t1 VALUES(3, 4); + } + forcecopy test2.db test.db + forcecopy test2.db-journal test.db-journal + db2 close + } -tclbody { + sqlite3 db test.db + sqlite3_extended_result_codes db 1 + + # If an out-of-memory occurs within a call to a VFS layer function during + # hot-journal rollback, sqlite will report SQLITE_CORRUPT. See commit + # [5668] for details. + set rc [catch {db eval { SELECT * FROM t1 }} msg] + if {$msg eq "database disk image is malformed"} { set msg "out of memory" } + if {$rc} { error $msg } + set msg + } +} + +proc string_compare {a b} { + return [string compare $a $b] +} + +# Test for malloc() failures in sqlite3_create_collation() and +# sqlite3_create_collation16(). +# +ifcapable utf16 { + do_malloc_test 15 -start 4 -tclbody { + db collate string_compare string_compare + if {[catch {add_test_collate db 1 1 1} msg]} { + if {$msg=="SQLITE_NOMEM"} {set msg "out of memory"} + error $msg + } + + db complete {SELECT "hello """||'world"' [microsoft], * FROM anicetable;} + db complete {-- Useful comment} + + execsql { + CREATE TABLE t1(a, b COLLATE string_compare); + INSERT INTO t1 VALUES(10, 'string'); + INSERT INTO t1 VALUES(10, 'string2'); + } + } +} + +# Also test sqlite3_complete(). There are (currently) no malloc() +# calls in this function, but test anyway against future changes. +# +do_malloc_test 16 -tclbody { + db complete {SELECT "hello """||'world"' [microsoft], * FROM anicetable;} + db complete {-- Useful comment} + db eval { + SELECT * FROM sqlite_master; + } +} + +# Test handling of malloc() failures in sqlite3_open16(). +# +ifcapable utf16 { + do_malloc_test 17 -tclbody { + set DB2 0 + set STMT 0 + + # open database using sqlite3_open16() + set filename [encoding convertto unicode test.db] + append filename "\x00\x00" + set DB2 [sqlite3_open16 $filename -unused] + if {0==$DB2} { + error "out of memory" + } + sqlite3_extended_result_codes $DB2 1 + + # Prepare statement + set rc [catch {sqlite3_prepare $DB2 {SELECT * FROM sqlite_master} -1 X} msg] + if {[sqlite3_errcode $DB2] eq "SQLITE_IOERR+12"} { + error "out of memory" + } + if {[regexp ".*automatic extension loading.*" [sqlite3_errmsg $DB2]]} { + error "out of memory" + } + if {$rc} { + error [string range $msg 4 end] + } + set STMT $msg + + # Finalize statement + set rc [sqlite3_finalize $STMT] + if {$rc!="SQLITE_OK"} { + error [sqlite3_errmsg $DB2] + } + set STMT 0 + + # Close database + set rc [sqlite3_close $DB2] + if {$rc!="SQLITE_OK"} { + error [sqlite3_errmsg $DB2] + } + set DB2 0 + } -cleanup { + if {$STMT!="0"} { + sqlite3_finalize $STMT + } + if {$DB2!="0"} { + set rc [sqlite3_close $DB2] + } + } +} + +# Test handling of malloc() failures in sqlite3_errmsg16(). +# +ifcapable utf16 { + do_malloc_test 18 -tclprep { + catch { + db eval "SELECT [string repeat longcolumnname 10] FROM sqlite_master" + } + } -tclbody { + set utf16 [sqlite3_errmsg16 [sqlite3_connection_pointer db]] + binary scan $utf16 c* bytes + if {[llength $bytes]==0} { + error "out of memory" + } + } +} + +# This test is aimed at coverage testing. Specificly, it is supposed to +# cause a malloc() only used when converting between the two utf-16 +# encodings to fail (i.e. little-endian->big-endian). It only actually +# hits this malloc() on little-endian hosts. +# +set static_string "\x00h\x00e\x00l\x00l\x00o" +for {set l 0} {$l<10} {incr l} { + append static_string $static_string +} +append static_string "\x00\x00" +do_malloc_test 19 -tclprep { + execsql { + PRAGMA encoding = "UTF16be"; + CREATE TABLE abc(a, b, c); + } +} -tclbody { + unset -nocomplain ::STMT + set r [catch { + set ::STMT [sqlite3_prepare db {SELECT ?} -1 DUMMY] + sqlite3_bind_text16 -static $::STMT 1 $static_string 112 + } msg] + if {$r} {error [string range $msg 4 end]} + set msg +} -cleanup { + if {[info exists ::STMT]} { + sqlite3_finalize $::STMT + } +} +unset static_string + +# Make sure SQLITE_NOMEM is reported out on an ATTACH failure even +# when the malloc failure occurs within the nested parse. +# +ifcapable attach { + do_malloc_test 20 -tclprep { + db close + forcedelete test2.db test2.db-journal + sqlite3 db test2.db + sqlite3_extended_result_codes db 1 + db eval {CREATE TABLE t1(x);} + db close + } -tclbody { + if {[catch {sqlite3 db test.db}]} { + error "out of memory" + } + sqlite3_extended_result_codes db 1 + } -sqlbody { + ATTACH DATABASE 'test2.db' AS t2; + SELECT * FROM t1; + DETACH DATABASE t2; + } +} + +# Test malloc failure whilst installing a foreign key. +# +ifcapable foreignkey { + do_malloc_test 21 -sqlbody { + CREATE TABLE abc(a, b, c, FOREIGN KEY(a) REFERENCES abc(b)) + } +} + +# Test malloc failure in an sqlite3_prepare_v2() call. +# +do_malloc_test 22 -tclbody { + set ::STMT "" + set r [catch { + set ::STMT [ + sqlite3_prepare_v2 db "SELECT * FROM sqlite_master" -1 DUMMY + ] + } msg] + if {$r} {error [string range $msg 4 end]} +} -cleanup { + if {$::STMT ne ""} { + sqlite3_finalize $::STMT + set ::STMT "" + } +} + +ifcapable {pager_pragmas} { + # This tests a special case - that an error that occurs while the pager + # is trying to recover from error-state in exclusive-access mode works. + # + do_malloc_test 23 -tclprep { + db eval { + PRAGMA cache_size = 10; + PRAGMA locking_mode = exclusive; + BEGIN; + CREATE TABLE abc(a, b, c); + CREATE INDEX abc_i ON abc(a, b, c); + INSERT INTO abc + VALUES(randstr(100,100), randstr(100,100), randstr(100,100)); + INSERT INTO abc + SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc + SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc + SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc + SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc + SELECT randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + COMMIT; + } + + # This puts the pager into error state. + # + db eval BEGIN + db eval {UPDATE abc SET a = 0 WHERE oid%2} + set ::sqlite_io_error_pending 10 + catch {db eval {ROLLBACK}} msg + + } -tclbody { + # If an out-of-memory occurs within a call to a VFS layer function during + # hot-journal rollback, sqlite will report SQLITE_CORRUPT. See commit + # [5668] for details. + set rc [catch {db eval { SELECT * FROM abc LIMIT 10 }} msg] + if {$msg eq "database disk image is malformed"} { set msg "out of memory" } + if {$rc} { error $msg } + set msg + } -cleanup { + set e [db eval {PRAGMA integrity_check}] + if {$e ne "ok"} {error $e} + } +} + +ifcapable compound { + do_malloc_test 24 -sqlprep { + CREATE TABLE t1(a, b, c) + } -sqlbody { + SELECT 1 FROM t1 UNION SELECT 2 FROM t1 ORDER BY 1 + } +} + +ifcapable view&&trigger { + do_malloc_test 25 -sqlprep { + CREATE TABLE t1(a, b, c); + CREATE VIEW v1 AS SELECT * FROM t1; + CREATE TRIGGER v1t1 INSTEAD OF DELETE ON v1 BEGIN SELECT 1; END; + CREATE TRIGGER v1t2 INSTEAD OF INSERT ON v1 BEGIN SELECT 1; END; + CREATE TRIGGER v1t3 INSTEAD OF UPDATE ON v1 BEGIN SELECT 1; END; + } -sqlbody { + DELETE FROM v1 WHERE a = 1; + INSERT INTO v1 VALUES(1, 2, 3); + UPDATE v1 SET a = 1 WHERE b = 2; + } +} + +do_malloc_test 25 -sqlprep { + CREATE TABLE abc(a, b, c); + CREATE INDEX i1 ON abc(a, b); + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, 6); +} -tclbody { + # For each UPDATE executed, the cursor used for the SELECT statement + # must be "saved". Because the cursor is open on an index, this requires + # a malloc() to allocate space to save the index key. This test case is + # aimed at testing the response of the library to a failure in that + # particular malloc() call. + db eval {SELECT a FROM abc ORDER BY a} { + db eval {UPDATE abc SET b = b - 1 WHERE a = $a} + } +} + +# This test is designed to test a specific juncture in the sqlite code. +# The database set up by -sqlprep script contains a single table B-Tree +# of height 2. In the -tclbody script, the existing database connection +# is closed and a new one opened and used to insert a new row into the +# table B-Tree. By using a new connection, the outcome of a malloc() +# failure while seeking to the right-hand side of the B-Tree to insert +# a new record can be tested. +# +do_malloc_test 26 -sqlprep { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, randomblob(210)); + INSERT INTO t1 VALUES(1, randomblob(210)); + INSERT INTO t1 VALUES(1, randomblob(210)); + INSERT INTO t1 VALUES(1, randomblob(210)); + INSERT INTO t1 VALUES(1, randomblob(210)); + COMMIT; +} -tclbody { + db close + sqlite3 db test.db + db eval { INSERT INTO t1 VALUES(1, randomblob(210)) } +} + +# Test that no memory is leaked following a malloc() failure in +# sqlite3_initialize(). +# +do_malloc_test 27 -tclprep { + db close + sqlite3_shutdown +} -tclbody { + set rc [sqlite3_initialize] + if {$rc == "SQLITE_NOMEM"} { + error "out of memory" + } +} +autoinstall_test_functions + +# Test that malloc failures that occur while processing INDEXED BY +# clauses are handled correctly. +do_malloc_test 28 -sqlprep { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a); + CREATE VIEW v1 AS SELECT * FROM t1 INDEXED BY i1 WHERE a = 10; +} -sqlbody { + SELECT * FROM t1 INDEXED BY i1 ORDER BY a; + SELECT * FROM v1; +} + +do_malloc_test 29 -sqlprep { + CREATE TABLE t1(a TEXT, b TEXT); +} -sqlbody { + INSERT INTO t1 VALUES(1, -234); + INSERT INTO t1 SELECT * FROM t1 UNION ALL SELECT * FROM t1; +} + +do_malloc_test 30 -tclprep { + db eval { + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(randstr(500,500)); + INSERT INTO t1 VALUES(randstr(500,500)); + INSERT INTO t1 VALUES(randstr(500,500)); + } + db close + sqlite3 db test.db + + # The DELETE command in the following block moves the overflow pages that + # are part of the primary key index to the free-list. But it does not + # actually load the content of the pages. This leads to the peculiar + # situation where cache entries exist, but are not populated with data. + # They are populated next time they are requested by the b-tree layer. + # + db eval { + BEGIN; + DELETE FROM t1; + ROLLBACK; + } +} -sqlbody { + -- This statement requires the 'no-content' pages loaded by the DELETE + -- statement above. When requesting the pages, the content is loaded + -- from the database file. The point of this test case is to test handling + -- of malloc errors (including SQLITE_IOERR_NOMEM errors) when loading + -- the content. + SELECT * FROM t1 ORDER BY x; +} + +# After committing a transaction in persistent-journal mode, if a journal +# size limit is configured SQLite may attempt to truncate the journal file. +# This test verifies the libraries response to a malloc() failure during +# this operation. +# +do_malloc_test 31 -sqlprep { + PRAGMA journal_mode = persist; + PRAGMA journal_size_limit = 1024; + CREATE TABLE t1(a PRIMARY KEY, b); +} -sqlbody { + INSERT INTO t1 VALUES(1, 2); +} + +# When written, this test provoked an obscure change-counter bug. +# +# If, when running in exclusive mode, a malloc() failure occurs +# after the database file change-counter has been written but +# before the transaction has been committed, then the transaction +# is automatically rolled back. However, internally the +# Pager.changeCounterDone flag was being left set. This means +# that if the same connection attempts another transaction following +# the malloc failure and rollback, the change counter will not +# be updated. This could corrupt another processes cache. +# +do_malloc_test 32 -tclprep { + # Build a small database containing an indexed table. + # + db eval { + PRAGMA locking_mode = normal; + BEGIN; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t1 VALUES(3, 'three'); + COMMIT; + PRAGMA locking_mode = exclusive; + } + + # Open a second database connection. Load the table (but not index) + # into the second connections pager cache. + # + sqlite3 db2 test.db + db2 eval { + PRAGMA locking_mode = normal; + SELECT b FROM t1; + } + +} -tclbody { + # Running in exclusive mode, perform a database transaction that + # modifies both the database table and index. For iterations where + # the malloc failure occurs after updating the change counter but + # before committing the transaction, this should result in the + # transaction being rolled back but the changeCounterDone flag + # left set. + # + db eval { UPDATE t1 SET a = a + 3 } +} -cleanup { + + # Perform another transaction using the first connection. Unlock + # the database after doing so. If this is one of the right iterations, + # then this should result in the database contents being updated but + # the change-counter left as it is. + # + db eval { + PRAGMA locking_mode = normal; + UPDATE t1 SET a = a + 3; + } + + # Now do an integrity check with the second connection. The second + # connection still has the database table in its cache. If this is + # one of the magic iterations and the change counter was not modified, + # then it won't realize that the cached data is out of date. Since + # the cached data won't match the up to date index data read from + # the database file, the integrity check should fail. + # + set zRepeat "transient" + if {$::iRepeat} {set zRepeat "persistent"} + do_test malloc-32.$zRepeat.${::n}.integrity { + execsql {PRAGMA integrity_check} db2 + } {ok} + db2 close +} + +# The following two OOM tests verify that OOM handling works in the +# code used to optimize "SELECT count(*) FROM ". +# +do_malloc_test 33 -tclprep { + db eval { PRAGMA cache_size = 10 } + db transaction { + db eval { CREATE TABLE abc(a, b) } + for {set i 0} {$i<500} {incr i} { + db eval {INSERT INTO abc VALUES(randstr(100,100), randstr(1000,1000))} + } + } +} -sqlbody { + SELECT count(*) FROM abc; +} +do_malloc_test 34 -tclprep { + db eval { PRAGMA cache_size = 10 } + db transaction { + db eval { CREATE TABLE abc(a PRIMARY KEY, b) } + for {set i 0} {$i<500} {incr i} { + db eval {INSERT INTO abc VALUES(randstr(100,100), randstr(1000,1000))} + } + } +} -sqlbody { + SELECT count(*) FROM abc; +} + +proc f {args} { error "Quite a long error!" } +do_malloc_test 35 -tclprep { + db func f f + set ::STMT [sqlite3_prepare db "SELECT f()" -1 DUMMY] + sqlite3_step $::STMT +} -tclbody { + sqlite3_finalize $::STMT +} -cleanup { + # At one point an assert( !db->mallocFailed ) could fail in the following + # call to sqlite3_errmsg(). Because sqlite3_finalize() had failed to clear + # the flag before returning. + sqlite3_errmsg16 db +} + +do_malloc_test 36 -sqlprep { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); +} -sqlbody { + SELECT test_agg_errmsg16(), group_concat(a) FROM t1 +} + +# At one point, if an OOM occurred immediately after obtaining a shared lock +# on the database file, the file remained locked. This test case ensures +# that bug has been fixed.i +if {[db eval {PRAGMA locking_mode}]!="exclusive"} { + do_malloc_test 37 -tclprep { + sqlite3 db2 test.db + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } db2 + } -sqlbody { + SELECT * FROM t1; + } -cleanup { + # Try to write to the database using connection [db2]. If connection [db] + # has correctly released the shared lock, this write attempt should + # succeed. If [db] has not released the lock, this should hit an + # SQLITE_BUSY error. + do_test malloc-36.$zRepeat.${::n}.unlocked { + execsql {INSERT INTO t1 VALUES(3, 4)} db2 + } {} + db2 close + } + catch { db2 close } +} + + +# Test that if an OOM error occurs, aux-data is still correctly destroyed. +# This test case was causing either a memory-leak or an assert() failure +# at one point, depending on the configuration. +# +do_malloc_test 39 -tclprep { + sqlite3 db test.db +} -sqlbody { + SELECT test_auxdata('abc', 'def'); +} -cleanup { + db close +} + +# Ensure that no file descriptors were leaked. +do_test malloc-99.X { + catch {db close} + set sqlite_open_file_count +} {0} + +puts open-file-count=$sqlite_open_file_count +finish_test diff --git a/components/external/SQLite-3.8.1/test/malloc3.test b/components/external/SQLite-3.8.1/test/malloc3.test new file mode 100644 index 0000000000000000000000000000000000000000..f4a6c3bbe90873390c72dbcb8c2d2f580f43b9dc --- /dev/null +++ b/components/external/SQLite-3.8.1/test/malloc3.test @@ -0,0 +1,692 @@ +# 2005 November 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests to ensure that the library handles malloc() failures +# correctly. The emphasis of these tests are the _prepare(), _step() and +# _finalize() calls. +# +# $Id: malloc3.test,v 1.24 2008/10/14 15:54:08 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping malloc3 tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + + +# Do not run these tests with an in-memory journal. +# +# In the pager layer, if an IO or OOM error occurs during a ROLLBACK, or +# when flushing a page to disk due to cache-stress, the pager enters an +# "error state". The only way out of the error state is to unlock the +# database file and end the transaction, leaving whatever journal and +# database files happen to be on disk in place. The next time the current +# (or any other) connection opens a read transaction, hot-journal rollback +# is performed if necessary. +# +# Of course, this doesn't work with an in-memory journal. +# +if {[permutation]=="inmemory_journal"} { + finish_test + return +} + +#-------------------------------------------------------------------------- +# NOTES ON RECOVERING FROM A MALLOC FAILURE +# +# The tests in this file test the behaviours described in the following +# paragraphs. These tests test the behaviour of the system when malloc() fails +# inside of a call to _prepare(), _step(), _finalize() or _reset(). The +# handling of malloc() failures within ancillary procedures is tested +# elsewhere. +# +# Overview: +# +# Executing a statement is done in three stages (prepare, step and finalize). A +# malloc() failure may occur within any stage. If a memory allocation fails +# during statement preparation, no statement handle is returned. From the users +# point of view the system state is as if _prepare() had never been called. +# +# If the memory allocation fails during the _step() or _finalize() calls, then +# the database may be left in one of two states (after finalize() has been +# called): +# +# * As if the neither _step() nor _finalize() had ever been called on +# the statement handle (i.e. any changes made by the statement are +# rolled back). +# * The current transaction may be rolled back. In this case a hot-journal +# may or may not actually be present in the filesystem. +# +# The caller can tell the difference between these two scenarios by invoking +# _get_autocommit(). +# +# +# Handling of sqlite3_reset(): +# +# If a malloc() fails while executing an sqlite3_reset() call, this is handled +# in the same way as a failure within _finalize(). The statement handle +# is not deleted and must be passed to _finalize() for resource deallocation. +# Attempting to _step() or _reset() the statement after a failed _reset() will +# always return SQLITE_NOMEM. +# +# +# Other active SQL statements: +# +# The effect of a malloc failure on concurrently executing SQL statements, +# particularly when the statement is executing with READ_UNCOMMITTED set and +# the malloc() failure mandates statement rollback only. Currently, if +# transaction rollback is required, all other vdbe's are aborted. +# +# Non-transient mallocs in btree.c: +# * The Btree structure itself +# * Each BtCursor structure +# +# Mallocs in pager.c: +# readMasterJournal() - Space to read the master journal name +# pager_delmaster() - Space for the entire master journal file +# +# sqlite3pager_open() - The pager structure itself +# sqlite3_pagerget() - Space for a new page +# pager_open_journal() - Pager.aInJournal[] bitmap +# sqlite3pager_write() - For in-memory databases only: history page and +# statement history page. +# pager_stmt_begin() - Pager.aInStmt[] bitmap +# +# None of the above are a huge problem. The most troublesome failures are the +# transient malloc() calls in btree.c, which can occur during the tree-balance +# operation. This means the tree being balanced will be internally inconsistent +# after the malloc() fails. To avoid the corrupt tree being read by a +# READ_UNCOMMITTED query, we have to make sure the transaction or statement +# rollback occurs before sqlite3_step() returns, not during a subsequent +# sqlite3_finalize(). +#-------------------------------------------------------------------------- + +#-------------------------------------------------------------------------- +# NOTES ON TEST IMPLEMENTATION +# +# The tests in this file are implemented differently from those in other +# files. Instead, tests are specified using three primitives: SQL, PREP and +# TEST. Each primitive has a single argument. Primitives are processed in +# the order they are specified in the file. +# +# A TEST primitive specifies a TCL script as its argument. When a TEST +# directive is encountered the Tcl script is evaluated. Usually, this Tcl +# script contains one or more calls to [do_test]. +# +# A PREP primitive specifies an SQL script as its argument. When a PREP +# directive is encountered the SQL is evaluated using database connection +# [db]. +# +# The SQL primitives are where the action happens. An SQL primitive must +# contain a single, valid SQL statement as its argument. When an SQL +# primitive is encountered, it is evaluated one or more times to test the +# behaviour of the system when malloc() fails during preparation or +# execution of said statement. The Nth time the statement is executed, +# the Nth malloc is said to fail. The statement is executed until it +# succeeds, i.e. (M+1) times, where M is the number of mallocs() required +# to prepare and execute the statement. +# +# Each time an SQL statement fails, the driver program (see proc [run_test] +# below) figures out if a transaction has been automatically rolled back. +# If not, it executes any TEST block immediately proceeding the SQL +# statement, then reexecutes the SQL statement with the next value of N. +# +# If a transaction has been automatically rolled back, then the driver +# program executes all the SQL specified as part of SQL or PREP primitives +# between the current SQL statement and the most recent "BEGIN". Any +# TEST block immediately proceeding the SQL statement is evaluated, and +# then the SQL statement reexecuted with the incremented N value. +# +# That make any sense? If not, read the code in [run_test] and it might. +# +# Extra restriction imposed by the implementation: +# +# * If a PREP block starts a transaction, it must finish it. +# * A PREP block may not close a transaction it did not start. +# +#-------------------------------------------------------------------------- + + +# These procs are used to build up a "program" in global variable +# ::run_test_script. At the end of this file, the proc [run_test] is used +# to execute the program (and all test cases contained therein). +# +set ::run_test_sql_id 0 +set ::run_test_script [list] +proc TEST {id t} {lappend ::run_test_script -test [list $id $t]} +proc PREP {p} {lappend ::run_test_script -prep [string trim $p]} +proc DEBUG {s} {lappend ::run_test_script -debug $s} + +# SQL -- +# +# SQL ?-norollback? +# +# Add an 'SQL' primitive to the program (see notes above). If the -norollback +# switch is present, then the statement is not allowed to automatically roll +# back any active transaction if malloc() fails. It must rollback the statement +# transaction only. +# +proc SQL {a1 {a2 ""}} { + # An SQL primitive parameter is a list of three elements, an id, a boolean + # value indicating if the statement may cause transaction rollback when + # malloc() fails, and the sql statement itself. + set id [incr ::run_test_sql_id] + if {$a2 == ""} { + lappend ::run_test_script -sql [list $id true [string trim $a1]] + } else { + lappend ::run_test_script -sql [list $id false [string trim $a2]] + } +} + +# TEST_AUTOCOMMIT -- +# +# A shorthand test to see if a transaction is active or not. The first +# argument - $id - is the integer number of the test case. The second +# argument is either 1 or 0, the expected value of the auto-commit flag. +# +proc TEST_AUTOCOMMIT {id a} { + TEST $id "do_test \$testid { sqlite3_get_autocommit \$::DB } {$a}" +} + +#-------------------------------------------------------------------------- +# Start of test program declaration +# + + +# Warm body test. A malloc() fails in the middle of a CREATE TABLE statement +# in a single-statement transaction on an empty database. Not too much can go +# wrong here. +# +TEST 1 { + do_test $testid { + execsql {SELECT tbl_name FROM sqlite_master;} + } {} +} +SQL { + CREATE TABLE IF NOT EXISTS abc(a, b, c); +} +TEST 2 { + do_test $testid.1 { + execsql {SELECT tbl_name FROM sqlite_master;} + } {abc} +} + +# Insert a couple of rows into the table. each insert is in its own +# transaction. test that the table is unpopulated before running the inserts +# (and hence after each failure of the first insert), and that it has been +# populated correctly after the final insert succeeds. +# +TEST 3 { + do_test $testid.2 { + execsql {SELECT * FROM abc} + } {} +} +SQL {INSERT INTO abc VALUES(1, 2, 3);} +SQL {INSERT INTO abc VALUES(4, 5, 6);} +SQL {INSERT INTO abc VALUES(7, 8, 9);} +TEST 4 { + do_test $testid { + execsql {SELECT * FROM abc} + } {1 2 3 4 5 6 7 8 9} +} + +# Test a CREATE INDEX statement. Because the table 'abc' is so small, the index +# will all fit on a single page, so this doesn't test too much that the CREATE +# TABLE statement didn't test. A few of the transient malloc()s in btree.c +# perhaps. +# +SQL {CREATE INDEX abc_i ON abc(a, b, c);} +TEST 4 { + do_test $testid { + execsql { + SELECT * FROM abc ORDER BY a DESC; + } + } {7 8 9 4 5 6 1 2 3} +} + +# Test a DELETE statement. Also create a trigger and a view, just to make sure +# these statements don't have any obvious malloc() related bugs in them. Note +# that the test above will be executed each time the DELETE fails, so we're +# also testing rollback of a DELETE from a table with an index on it. +# +SQL {DELETE FROM abc WHERE a > 2;} +SQL {CREATE TRIGGER abc_t AFTER INSERT ON abc BEGIN SELECT 'trigger!'; END;} +SQL {CREATE VIEW abc_v AS SELECT * FROM abc;} +TEST 5 { + do_test $testid { + execsql { + SELECT name, tbl_name FROM sqlite_master ORDER BY name; + SELECT * FROM abc; + } + } {abc abc abc_i abc abc_t abc abc_v abc_v 1 2 3} +} + +set sql { + BEGIN;DELETE FROM abc; +} +for {set i 1} {$i < 100} {incr i} { + set a $i + set b "String value $i" + set c [string repeat X $i] + append sql "INSERT INTO abc VALUES ($a, '$b', '$c');" +} +append sql {COMMIT;} +PREP $sql + +SQL { + DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5); +} +TEST 6 { + do_test $testid.1 { + execsql {SELECT count(*) FROM abc} + } {94} + do_test $testid.2 { + execsql { + SELECT min( + (oid == a) AND 'String value ' || a == b AND a == length(c) + ) FROM abc; + } + } {1} +} +SQL { + DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5); +} +TEST 7 { + do_test $testid { + execsql {SELECT count(*) FROM abc} + } {89} + do_test $testid { + execsql { + SELECT min( + (oid == a) AND 'String value ' || a == b AND a == length(c) + ) FROM abc; + } + } {1} +} +SQL { + DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5); +} +TEST 9 { + do_test $testid { + execsql {SELECT count(*) FROM abc} + } {84} + do_test $testid { + execsql { + SELECT min( + (oid == a) AND 'String value ' || a == b AND a == length(c) + ) FROM abc; + } + } {1} +} + +set padding [string repeat X 500] +PREP [subst { + DROP TABLE abc; + CREATE TABLE abc(a PRIMARY KEY, padding, b, c); + INSERT INTO abc VALUES(0, '$padding', 2, 2); + INSERT INTO abc VALUES(3, '$padding', 5, 5); + INSERT INTO abc VALUES(6, '$padding', 8, 8); +}] + +TEST 10 { + do_test $testid { + execsql {SELECT a, b, c FROM abc} + } {0 2 2 3 5 5 6 8 8} +} + +SQL {BEGIN;} +SQL {INSERT INTO abc VALUES(9, 'XXXXX', 11, 12);} +TEST_AUTOCOMMIT 11 0 +SQL -norollback {UPDATE abc SET a = a + 1, c = c + 1;} +TEST_AUTOCOMMIT 12 0 +SQL {DELETE FROM abc WHERE a = 10;} +TEST_AUTOCOMMIT 13 0 +SQL {COMMIT;} + +TEST 14 { + do_test $testid.1 { + sqlite3_get_autocommit $::DB + } {1} + do_test $testid.2 { + execsql {SELECT a, b, c FROM abc} + } {1 2 3 4 5 6 7 8 9} +} + +PREP [subst { + DROP TABLE abc; + CREATE TABLE abc(a, padding, b, c); + INSERT INTO abc VALUES(1, '$padding', 2, 3); + INSERT INTO abc VALUES(4, '$padding', 5, 6); + INSERT INTO abc VALUES(7, '$padding', 8, 9); + CREATE INDEX abc_i ON abc(a, padding, b, c); +}] + +TEST 15 { + db eval {PRAGMA cache_size = 10} +} + +SQL {BEGIN;} +SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} +TEST 16 { + do_test $testid { + execsql {SELECT a, count(*) FROM abc GROUP BY a;} + } {1 2 4 2 7 2} +} +SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} +TEST 17 { + do_test $testid { + execsql {SELECT a, count(*) FROM abc GROUP BY a;} + } {1 4 4 4 7 4} +} +SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} +TEST 18 { + do_test $testid { + execsql {SELECT a, count(*) FROM abc GROUP BY a;} + } {1 8 4 8 7 8} +} +SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} +TEST 19 { + do_test $testid { + execsql {SELECT a, count(*) FROM abc GROUP BY a;} + } {1 16 4 16 7 16} +} +SQL {COMMIT;} +TEST 21 { + do_test $testid { + execsql {SELECT a, count(*) FROM abc GROUP BY a;} + } {1 16 4 16 7 16} +} + +SQL {BEGIN;} +SQL {DELETE FROM abc WHERE oid %2} +TEST 22 { + do_test $testid { + execsql {SELECT a, count(*) FROM abc GROUP BY a;} + } {1 8 4 8 7 8} +} +SQL {DELETE FROM abc} +TEST 23 { + do_test $testid { + execsql {SELECT * FROM abc} + } {} +} +SQL {ROLLBACK;} +TEST 24 { + do_test $testid { + execsql {SELECT a, count(*) FROM abc GROUP BY a;} + } {1 16 4 16 7 16} +} + +# Test some schema modifications inside of a transaction. These should all +# cause transaction rollback if they fail. Also query a view, to cover a bit +# more code. +# +PREP {DROP VIEW abc_v;} +TEST 25 { + do_test $testid { + execsql { + SELECT name, tbl_name FROM sqlite_master; + } + } {abc abc abc_i abc} +} +SQL {BEGIN;} +SQL {CREATE TABLE def(d, e, f);} +SQL {CREATE TABLE ghi(g, h, i);} +TEST 26 { + do_test $testid { + execsql { + SELECT name, tbl_name FROM sqlite_master; + } + } {abc abc abc_i abc def def ghi ghi} +} +SQL {CREATE VIEW v1 AS SELECT * FROM def, ghi} +SQL {CREATE UNIQUE INDEX ghi_i1 ON ghi(g);} +TEST 27 { + do_test $testid { + execsql { + SELECT name, tbl_name FROM sqlite_master; + } + } {abc abc abc_i abc def def ghi ghi v1 v1 ghi_i1 ghi} +} +SQL {INSERT INTO def VALUES('a', 'b', 'c')} +SQL {INSERT INTO def VALUES(1, 2, 3)} +SQL -norollback {INSERT INTO ghi SELECT * FROM def} +TEST 28 { + do_test $testid { + execsql { + SELECT * FROM def, ghi WHERE d = g; + } + } {a b c a b c 1 2 3 1 2 3} +} +SQL {COMMIT} +TEST 29 { + do_test $testid { + execsql { + SELECT * FROM v1 WHERE d = g; + } + } {a b c a b c 1 2 3 1 2 3} +} + +# Test a simple multi-file transaction +# +forcedelete test2.db +ifcapable attach { + SQL {ATTACH 'test2.db' AS aux;} + SQL {BEGIN} + SQL {CREATE TABLE aux.tbl2(x, y, z)} + SQL {INSERT INTO tbl2 VALUES(1, 2, 3)} + SQL {INSERT INTO def VALUES(4, 5, 6)} + TEST 30 { + do_test $testid { + execsql { + SELECT * FROM tbl2, def WHERE d = x; + } + } {1 2 3 1 2 3} + } + SQL {COMMIT} + TEST 31 { + do_test $testid { + execsql { + SELECT * FROM tbl2, def WHERE d = x; + } + } {1 2 3 1 2 3} + } +} + +# Test what happens when a malloc() fails while there are other active +# statements. This changes the way sqlite3VdbeHalt() works. +TEST 32 { + if {![info exists ::STMT32]} { + set sql "SELECT name FROM sqlite_master" + set ::STMT32 [sqlite3_prepare $::DB $sql -1 DUMMY] + do_test $testid { + sqlite3_step $::STMT32 + } {SQLITE_ROW} + } +} +SQL BEGIN +TEST 33 { + do_test $testid { + execsql {SELECT * FROM ghi} + } {a b c 1 2 3} +} +SQL -norollback { + -- There is a unique index on ghi(g), so this statement may not cause + -- an automatic ROLLBACK. Hence the "-norollback" switch. + INSERT INTO ghi SELECT '2'||g, h, i FROM ghi; +} +TEST 34 { + if {[info exists ::STMT32]} { + do_test $testid { + sqlite3_finalize $::STMT32 + } {SQLITE_OK} + unset ::STMT32 + } +} +SQL COMMIT + +# +# End of test program declaration +#-------------------------------------------------------------------------- + +proc run_test {arglist iRepeat {pcstart 0} {iFailStart 1}} { + if {[llength $arglist] %2} { + error "Uneven number of arguments to TEST" + } + + for {set i 0} {$i < $pcstart} {incr i} { + set k2 [lindex $arglist [expr {2 * $i}]] + set v2 [lindex $arglist [expr {2 * $i + 1}]] + set ac [sqlite3_get_autocommit $::DB] ;# Auto-Commit + switch -- $k2 { + -sql {db eval [lindex $v2 2]} + -prep {db eval $v2} + -debug {eval $v2} + } + set nac [sqlite3_get_autocommit $::DB] ;# New Auto-Commit + if {$ac && !$nac} {set begin_pc $i} + } + + db rollback_hook [list incr ::rollback_hook_count] + + set iFail $iFailStart + set pc $pcstart + while {$pc*2 < [llength $arglist]} { + # Fetch the current instruction type and payload. + set k [lindex $arglist [expr {2 * $pc}]] + set v [lindex $arglist [expr {2 * $pc + 1}]] + + # Id of this iteration: + set iterid "pc=$pc.iFail=$iFail$k" + + switch -- $k { + + -test { + foreach {id script} $v {} + set testid "malloc3-(test $id).$iterid" + eval $script + incr pc + } + + -sql { + set ::rollback_hook_count 0 + + set id [lindex $v 0] + set testid "malloc3-(integrity $id).$iterid" + + set ac [sqlite3_get_autocommit $::DB] ;# Auto-Commit + sqlite3_memdebug_fail $iFail -repeat 0 + set rc [catch {db eval [lindex $v 2]} msg] ;# True error occurs + set nac [sqlite3_get_autocommit $::DB] ;# New Auto-Commit + + if {$rc != 0 && $nac && !$ac} { + # Before [db eval] the auto-commit flag was clear. Now it + # is set. Since an error occurred we assume this was not a + # commit - therefore a rollback occurred. Check that the + # rollback-hook was invoked. + do_test malloc3-rollback_hook_count.$iterid { + set ::rollback_hook_count + } {1} + } + + set nFail [sqlite3_memdebug_fail -1 -benigncnt nBenign] + if {$rc == 0} { + # Successful execution of sql. The number of failed malloc() + # calls should be equal to the number of benign failures. + # Otherwise a malloc() failed and the error was not reported. + # + set expr {$nFail!=$nBenign} + if {[expr $expr]} { + error "Unreported malloc() failure, test \"$testid\", $expr" + } + + if {$ac && !$nac} { + # Before the [db eval] the auto-commit flag was set, now it + # is clear. We can deduce that a "BEGIN" statement has just + # been successfully executed. + set begin_pc $pc + } + + incr pc + set iFail 1 + integrity_check $testid + } elseif {[regexp {.*out of memory} $msg] || [db errorcode] == 3082} { + # Out of memory error, as expected. + # + integrity_check $testid + incr iFail + if {$nac && !$ac} { + if {![lindex $v 1] && [db errorcode] != 3082} { + # error "Statement \"[lindex $v 2]\" caused a rollback" + } + + for {set i $begin_pc} {$i < $pc} {incr i} { + set k2 [lindex $arglist [expr {2 * $i}]] + set v2 [lindex $arglist [expr {2 * $i + 1}]] + set catchupsql "" + switch -- $k2 { + -sql {set catchupsql [lindex $v2 2]} + -prep {set catchupsql $v2} + } + db eval $catchupsql + } + } + } else { + error $msg + } + + # back up to the previous "-test" block. + while {[lindex $arglist [expr {2 * ($pc - 1)}]] == "-test"} { + incr pc -1 + } + } + + -prep { + db eval $v + incr pc + } + + -debug { + eval $v + incr pc + } + + default { error "Unknown switch: $k" } + } + } +} + +# Turn off the Tcl interface's prepared statement caching facility. Then +# run the tests with "persistent" malloc failures. +sqlite3_extended_result_codes db 1 +db cache size 0 +run_test $::run_test_script 1 + +# Close and reopen the db. +db close +forcedelete test.db test.db-journal test2.db test2.db-journal +sqlite3 db test.db +sqlite3_extended_result_codes db 1 +set ::DB [sqlite3_connection_pointer db] + +# Turn off the Tcl interface's prepared statement caching facility in +# the new connnection. Then run the tests with "transient" malloc failures. +db cache size 0 +run_test $::run_test_script 0 + +sqlite3_memdebug_fail -1 +finish_test diff --git a/components/external/SQLite-3.8.1/test/malloc4.test b/components/external/SQLite-3.8.1/test/malloc4.test new file mode 100644 index 0000000000000000000000000000000000000000..e2a616a5896c61b51bb176da7baab2fab4d60cbe --- /dev/null +++ b/components/external/SQLite-3.8.1/test/malloc4.test @@ -0,0 +1,194 @@ +# 2005 November 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests to ensure that the library handles malloc() failures +# correctly. The emphasis in this file is on sqlite3_column_XXX() APIs. +# +# $Id: malloc4.test,v 1.10 2008/02/18 22:24:58 drh Exp $ + +#--------------------------------------------------------------------------- +# NOTES ON EXPECTED BEHAVIOUR +# +# [193] When a memory allocation failure occurs during sqlite3_column_name(), +# sqlite3_column_name16(), sqlite3_column_decltype(), or +# sqlite3_column_decltype16() the function shall return NULL. +# +#--------------------------------------------------------------------------- + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +if {!$MEMDEBUG} { + puts "Skipping malloc4 tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + +ifcapable !utf16 { + finish_test + return +} + +proc do_stmt_test {id sql} { + set ::sql $sql + set go 1 + for {set n 0} {$go} {incr n} { + set testid "malloc4-$id.$n" + + # Prepare the statement + do_test ${testid}.1 { + set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL] + expr [string length $::STMT] > 0 + } {1} + + # Set the Nth malloc() to fail. + sqlite3_memdebug_fail $n -repeat 0 + + # Test malloc failure in the _name(), _name16(), decltype() and + # decltype16() APIs. Calls that occur after the malloc() failure should + # return NULL. No error is raised though. + # + # ${testid}.2.1 - Call _name() + # ${testid}.2.2 - Call _name16() + # ${testid}.2.3 - Call _name() + # ${testid}.2.4 - Check that the return values of the above three calls are + # consistent with each other and with the simulated + # malloc() failures. + # + # Because the code that implements the _decltype() and _decltype16() APIs + # is the same as the _name() and _name16() implementations, we don't worry + # about explicitly testing them. + # + do_test ${testid}.2.1 { + set mf1 [expr [sqlite3_memdebug_pending] < 0] + set ::name8 [sqlite3_column_name $::STMT 0] + set mf2 [expr [sqlite3_memdebug_pending] < 0] + expr {$mf1 == $mf2 || $::name8 == ""} + } {1} + do_test ${testid}.2.2 { + set mf1 [expr [sqlite3_memdebug_pending] < 0] + set ::name16 [sqlite3_column_name16 $::STMT 0] + set ::name16 [encoding convertfrom unicode $::name16] + set ::name16 [string range $::name16 0 end-1] + set mf2 [expr [sqlite3_memdebug_pending] < 0] + expr {$mf1 == $mf2 || $::name16 == ""} + } {1} + do_test ${testid}.2.3 { + set mf1 [expr [sqlite3_memdebug_pending] < 0] + set ::name8_2 [sqlite3_column_name $::STMT 0] + set mf2 [expr [sqlite3_memdebug_pending] < 0] + expr {$mf1 == $mf2 || $::name8_2 == ""} + } {1} + set ::mallocFailed [expr [sqlite3_memdebug_pending] < 0] + do_test ${testid}.2.4 { + expr { + $::name8 == $::name8_2 && $::name16 == $::name8 && !$::mallocFailed || + $::name8 == $::name8_2 && $::name16 == "" && $::mallocFailed || + $::name8 == $::name16 && $::name8_2 == "" && $::mallocFailed || + $::name8_2 == $::name16 && $::name8 == "" && $::mallocFailed + } + } {1} + + # Step the statement so that we can call _text() and _text16(). Before + # running sqlite3_step(), make sure that malloc() is not about to fail. + # Memory allocation failures that occur within sqlite3_step() are tested + # elsewhere. + set mf [sqlite3_memdebug_pending] + sqlite3_memdebug_fail -1 + do_test ${testid}.3 { + sqlite3_step $::STMT + } {SQLITE_ROW} + sqlite3_memdebug_fail $mf + + # Test for malloc() failures within _text() and _text16(). + # + do_test ${testid}.4.1 { + set ::text8 [sqlite3_column_text $::STMT 0] + set mf [expr [sqlite3_memdebug_pending] < 0 && !$::mallocFailed] + expr {$mf==0 || $::text8 == ""} + } {1} + do_test ${testid}.4.2 { + set ::text16 [sqlite3_column_text16 $::STMT 0] + set ::text16 [encoding convertfrom unicode $::text16] + set ::text16 [string range $::text16 0 end-1] + set mf [expr [sqlite3_memdebug_pending] < 0 && !$::mallocFailed] + expr {$mf==0 || $::text16 == ""} + } {1} + do_test ${testid}.4.3 { + set ::text8_2 [sqlite3_column_text $::STMT 0] + set mf [expr [sqlite3_memdebug_pending] < 0 && !$::mallocFailed] + expr {$mf==0 || $::text8_2 == "" || ($::text16 == "" && $::text8 != "")} + } {1} + + # Test for malloc() failures within _int(), _int64() and _real(). The only + # way this can occur is if the string has to be translated from UTF-16 to + # UTF-8 before being converted to a numeric value. + do_test ${testid}.4.4.1 { + set mf [sqlite3_memdebug_pending] + sqlite3_memdebug_fail -1 + sqlite3_column_text16 $::STMT 0 + sqlite3_memdebug_fail $mf + sqlite3_column_int $::STMT 0 + } {0} + do_test ${testid}.4.5 { + set mf [sqlite3_memdebug_pending] + sqlite3_memdebug_fail -1 + sqlite3_column_text16 $::STMT 0 + sqlite3_memdebug_fail $mf + sqlite3_column_int64 $::STMT 0 + } {0} + + do_test ${testid}.4.6 { + set mf [sqlite3_memdebug_pending] + sqlite3_memdebug_fail -1 + sqlite3_column_text16 $::STMT 0 + sqlite3_memdebug_fail $mf + sqlite3_column_double $::STMT 0 + } {0.0} + + set mallocFailedAfterStep [expr \ + [sqlite3_memdebug_pending] < 0 && !$::mallocFailed + ] + + sqlite3_memdebug_fail -1 + # Test that if a malloc() failed the next call to sqlite3_step() returns + # SQLITE_ERROR. If malloc() did not fail, it should return SQLITE_DONE. + # + do_test ${testid}.5 { + sqlite3_step $::STMT + } [expr {$mallocFailedAfterStep ? "SQLITE_ERROR" : "SQLITE_DONE"}] + + do_test ${testid}.6 { + sqlite3_finalize $::STMT + } [expr {$mallocFailedAfterStep ? "SQLITE_NOMEM" : "SQLITE_OK"}] + + if {$::mallocFailed == 0 && $mallocFailedAfterStep == 0} { + sqlite3_memdebug_fail -1 + set go 0 + } + } +} + +execsql { + CREATE TABLE tbl( + the_first_reasonably_long_column_name that_also_has_quite_a_lengthy_type + ); + INSERT INTO tbl VALUES( + 'An extra long string. Far too long to be stored in NBFS bytes.' + ); +} + +do_stmt_test 1 "SELECT * FROM tbl" + +sqlite3_memdebug_fail -1 +finish_test diff --git a/components/external/SQLite-3.8.1/test/malloc5.test b/components/external/SQLite-3.8.1/test/malloc5.test new file mode 100644 index 0000000000000000000000000000000000000000..6abedf79e1c438c1302955074884b144c83c3c8b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/malloc5.test @@ -0,0 +1,395 @@ +# 2005 November 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains test cases focused on the two memory-management APIs, +# sqlite3_soft_heap_limit() and sqlite3_release_memory(). +# +# Prior to version 3.6.2, calling sqlite3_release_memory() or exceeding +# the configured soft heap limit could cause sqlite to upgrade database +# locks and flush dirty pages to the file system. As of 3.6.2, this is +# no longer the case. In version 3.6.2, sqlite3_release_memory() only +# reclaims clean pages. This test file has been updated accordingly. +# +# $Id: malloc5.test,v 1.22 2009/04/11 19:09:54 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +db close + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping malloc5 tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + +# Skip these tests if OMIT_MEMORY_MANAGEMENT was defined at compile time. +ifcapable !memorymanage { + finish_test + return +} + +sqlite3_soft_heap_limit 0 +sqlite3 db test.db + +do_test malloc5-1.1 { + # Simplest possible test. Call sqlite3_release_memory when there is exactly + # one unused page in a single pager cache. The page cannot be freed, as + # it is dirty. So sqlite3_release_memory() returns 0. + # + execsql { + PRAGMA auto_vacuum=OFF; + BEGIN; + CREATE TABLE abc(a, b, c); + } + sqlite3_release_memory +} {0} + +do_test malloc5-1.2 { + # Test that the transaction started in the above test is still active. + # The lock on the database file should not have been upgraded (this was + # not the case before version 3.6.2). + # + sqlite3 db2 test.db + execsql { SELECT * FROM sqlite_master } db2 +} {} +do_test malloc5-1.3 { + # Call [sqlite3_release_memory] when there is exactly one unused page + # in the cache belonging to db2. + # + set ::pgalloc [sqlite3_release_memory] + expr $::pgalloc > 0 +} {1} + +do_test malloc5-1.4 { + # Commit the transaction and open a new one. Read 1 page into the cache. + # Because the page is not dirty, it is eligible for collection even + # before the transaction is concluded. + # + execsql { + COMMIT; + BEGIN; + SELECT * FROM abc; + } + sqlite3_release_memory +} $::pgalloc + +do_test malloc5-1.5 { + # Conclude the transaction opened in the previous [do_test] block. This + # causes another page (page 1) to become eligible for recycling. + # + execsql { COMMIT } + sqlite3_release_memory +} $::pgalloc + +do_test malloc5-1.6 { + # Manipulate the cache so that it contains two unused pages. One requires + # a journal-sync to free, the other does not. + db2 close + execsql { + BEGIN; + SELECT * FROM abc; + CREATE TABLE def(d, e, f); + } + sqlite3_release_memory 500 +} $::pgalloc + +do_test malloc5-1.7 { + # Database should not be locked this time. + sqlite3 db2 test.db + catchsql { SELECT * FROM abc } db2 +} {0 {}} +do_test malloc5-1.8 { + # Try to release another block of memory. This will fail as the only + # pages currently in the cache are dirty (page 3) or pinned (page 1). + db2 close + sqlite3_release_memory 500 +} 0 +do_test malloc5-1.8 { + # Database is still not locked. + # + sqlite3 db2 test.db + catchsql { SELECT * FROM abc } db2 +} {0 {}} +do_test malloc5-1.9 { + execsql { + COMMIT; + } +} {} + +do_test malloc5-2.1 { + # Put some data in tables abc and def. Both tables are still wholly + # contained within their root pages. + execsql { + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, 6); + INSERT INTO def VALUES(7, 8, 9); + INSERT INTO def VALUES(10,11,12); + } +} {} +do_test malloc5-2.2 { + # Load the root-page for table def into the cache. Then query table abc. + # Halfway through the query call sqlite3_release_memory(). The goal of this + # test is to make sure we don't free pages that are in use (specifically, + # the root of table abc). + sqlite3_release_memory + set nRelease 0 + execsql { + BEGIN; + SELECT * FROM def; + } + set data [list] + db eval {SELECT * FROM abc} { + incr nRelease [sqlite3_release_memory] + lappend data $a $b $c + } + execsql { + COMMIT; + } + list $nRelease $data +} [list $pgalloc [list 1 2 3 4 5 6]] + +do_test malloc5-3.1 { + # Simple test to show that if two pagers are opened from within this + # thread, memory is freed from both when sqlite3_release_memory() is + # called. + execsql { + BEGIN; + SELECT * FROM abc; + } + execsql { + SELECT * FROM sqlite_master; + BEGIN; + SELECT * FROM def; + } db2 + sqlite3_release_memory +} [expr $::pgalloc * 2] +do_test malloc5-3.2 { + concat \ + [execsql {SELECT * FROM abc; COMMIT}] \ + [execsql {SELECT * FROM def; COMMIT} db2] +} {1 2 3 4 5 6 7 8 9 10 11 12} + +db2 close +puts "Highwater mark: [sqlite3_memory_highwater]" + +# The following two test cases each execute a transaction in which +# 10000 rows are inserted into table abc. The first test case is used +# to ensure that more than 1MB of dynamic memory is used to perform +# the transaction. +# +# The second test case sets the "soft-heap-limit" to 100,000 bytes (0.1 MB) +# and tests to see that this limit is not exceeded at any point during +# transaction execution. +# +# Before executing malloc5-4.* we save the value of the current soft heap +# limit in variable ::soft_limit. The original value is restored after +# running the tests. +# +set ::soft_limit [sqlite3_soft_heap_limit -1] +execsql {PRAGMA cache_size=2000} +do_test malloc5-4.1 { + execsql {BEGIN;} + execsql {DELETE FROM abc;} + for {set i 0} {$i < 10000} {incr i} { + execsql "INSERT INTO abc VALUES($i, $i, '[string repeat X 100]');" + } + execsql {COMMIT;} + db cache flush + sqlite3_release_memory + sqlite3_memory_highwater 1 + execsql {SELECT * FROM abc} + set nMaxBytes [sqlite3_memory_highwater 1] + puts -nonewline " (Highwater mark: $nMaxBytes) " + expr $nMaxBytes > 1000000 +} {1} +do_test malloc5-4.2 { + db cache flush + sqlite3_release_memory + sqlite3_soft_heap_limit 100000 + sqlite3_memory_highwater 1 + execsql {SELECT * FROM abc} + set nMaxBytes [sqlite3_memory_highwater 1] + puts -nonewline " (Highwater mark: $nMaxBytes) " + expr $nMaxBytes <= 110000 +} {1} +do_test malloc5-4.3 { + # Check that the content of table abc is at least roughly as expected. + execsql { + SELECT count(*), sum(a), sum(b) FROM abc; + } +} [list 10000 [expr int(10000.0 * 4999.5)] [expr int(10000.0 * 4999.5)]] + +# Restore the soft heap limit. +sqlite3_soft_heap_limit $::soft_limit + +# Test that there are no problems calling sqlite3_release_memory when +# there are open in-memory databases. +# +# At one point these tests would cause a seg-fault. +# +do_test malloc5-5.1 { + db close + sqlite3 db :memory: + execsql { + BEGIN; + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES('abcdefghi', 1234567890, NULL); + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + INSERT INTO abc SELECT * FROM abc; + } + sqlite3_release_memory +} 0 +do_test malloc5-5.2 { + sqlite3_soft_heap_limit 5000 + execsql { + COMMIT; + PRAGMA temp_store = memory; + SELECT * FROM abc ORDER BY a; + } + expr 1 +} {1} +sqlite3_soft_heap_limit $::soft_limit + +#------------------------------------------------------------------------- +# The following test cases (malloc5-6.*) test the new global LRU list +# used to determine the pages to recycle when sqlite3_release_memory is +# called and there is more than one pager open. +# +proc nPage {db} { + set bt [btree_from_db $db] + array set stats [btree_pager_stats $bt] + set stats(page) +} +db close +forcedelete test.db test.db-journal test2.db test2.db-journal + +# This block of test-cases (malloc5-6.1.*) prepares two database files +# for the subsequent tests. +do_test malloc5-6.1.1 { + sqlite3 db test.db + execsql { + PRAGMA page_size=1024; + PRAGMA default_cache_size=10; + } + execsql { + PRAGMA temp_store = memory; + BEGIN; + CREATE TABLE abc(a PRIMARY KEY, b, c); + INSERT INTO abc VALUES(randstr(50,50), randstr(75,75), randstr(100,100)); + INSERT INTO abc + SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc; + INSERT INTO abc + SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc; + INSERT INTO abc + SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc; + INSERT INTO abc + SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc; + INSERT INTO abc + SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc; + INSERT INTO abc + SELECT randstr(50,50), randstr(75,75), randstr(100,100) FROM abc; + COMMIT; + } + forcecopy test.db test2.db + sqlite3 db2 test2.db + list \ + [expr ([file size test.db]/1024)>20] [expr ([file size test2.db]/1024)>20] +} {1 1} +do_test malloc5-6.1.2 { + list [execsql {PRAGMA cache_size}] [execsql {PRAGMA cache_size} db2] +} {10 10} + +do_test malloc5-6.2.1 { + execsql {SELECT * FROM abc} db2 + execsql {SELECT * FROM abc} db + expr [nPage db] + [nPage db2] +} {20} + +do_test malloc5-6.2.2 { + # If we now try to reclaim some memory, it should come from the db2 cache. + sqlite3_release_memory 3000 + expr [nPage db] + [nPage db2] +} {17} +do_test malloc5-6.2.3 { + # Access the db2 cache again, so that all the db2 pages have been used + # more recently than all the db pages. Then try to reclaim 3000 bytes. + # This time, 3 pages should be pulled from the db cache. + execsql { SELECT * FROM abc } db2 + sqlite3_release_memory 3000 + expr [nPage db] + [nPage db2] +} {17} + +do_test malloc5-6.3.1 { + # Now open a transaction and update 2 pages in the db2 cache. Then + # do a SELECT on the db cache so that all the db pages are more recently + # used than the db2 pages. When we try to free memory, SQLite should + # free the non-dirty db2 pages, then the db pages, then finally use + # sync() to free up the dirty db2 pages. The only page that cannot be + # freed is page1 of db2. Because there is an open transaction, the + # btree layer holds a reference to page 1 in the db2 cache. + execsql { + BEGIN; + UPDATE abc SET c = randstr(100,100) + WHERE rowid = 1 OR rowid = (SELECT max(rowid) FROM abc); + } db2 + execsql { SELECT * FROM abc } db + expr [nPage db] + [nPage db2] +} {20} +do_test malloc5-6.3.2 { + # Try to release 7700 bytes. This should release all the + # non-dirty pages held by db2. + sqlite3_release_memory [expr 7*1132] + list [nPage db] [nPage db2] +} {10 3} +do_test malloc5-6.3.3 { + # Try to release another 1000 bytes. This should come fromt the db + # cache, since all three pages held by db2 are either in-use or diry. + sqlite3_release_memory 1000 + list [nPage db] [nPage db2] +} {9 3} +do_test malloc5-6.3.4 { + # Now release 9900 more (about 9 pages worth). This should expunge + # the rest of the db cache. But the db2 cache remains intact, because + # SQLite tries to avoid calling sync(). + if {$::tcl_platform(wordSize)==8} { + sqlite3_release_memory 10500 + } else { + sqlite3_release_memory 9900 + } + list [nPage db] [nPage db2] +} {0 3} +do_test malloc5-6.3.5 { + # But if we are really insistent, SQLite will consent to call sync() + # if there is no other option. UPDATE: As of 3.6.2, SQLite will not + # call sync() in this scenario. So no further memory can be reclaimed. + sqlite3_release_memory 1000 + list [nPage db] [nPage db2] +} {0 3} +do_test malloc5-6.3.6 { + # The referenced page (page 1 of the db2 cache) will not be freed no + # matter how much memory we ask for: + sqlite3_release_memory 31459 + list [nPage db] [nPage db2] +} {0 3} + +db2 close + +sqlite3_soft_heap_limit $::soft_limit +finish_test +catch {db close} diff --git a/components/external/SQLite-3.8.1/test/malloc6.test b/components/external/SQLite-3.8.1/test/malloc6.test new file mode 100644 index 0000000000000000000000000000000000000000..ded3d1e63347d96bc94511d6b72bc926ee712418 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/malloc6.test @@ -0,0 +1,55 @@ +# 2006 June 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file attempts to check the library in an out-of-memory situation. +# +# $Id: malloc6.test,v 1.5 2008/02/18 22:24:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping malloc6 tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + + +set sqlite_os_trace 0 +do_malloc_test malloc6-1 -tclprep { + db close +} -tclbody { + if {[catch {sqlite3 db test.db}]} { + error "out of memory" + } + sqlite3_extended_result_codes db 1 +} -sqlbody { + DROP TABLE IF EXISTS t1; + CREATE TABLE IF NOT EXISTS t1( + a int, b float, c double, d text, e varchar(20), + primary key(a,b,c) + ); + CREATE TABLE IF NOT EXISTS t1( + a int, b float, c double, d text, e varchar(20), + primary key(a,b,c) + ); + DROP TABLE IF EXISTS t1; +} + +# Ensure that no file descriptors were leaked. +do_test malloc6-1.X { + catch {db close} + set sqlite_open_file_count +} {0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/malloc7.test b/components/external/SQLite-3.8.1/test/malloc7.test new file mode 100644 index 0000000000000000000000000000000000000000..3e301c8018efd249592e72d3356023db04d2ddef --- /dev/null +++ b/components/external/SQLite-3.8.1/test/malloc7.test @@ -0,0 +1,48 @@ +# 2006 July 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file contains additional out-of-memory checks (see malloc.tcl) +# added to expose a bug in out-of-memory handling for sqlite3_prepare16(). +# +# $Id: malloc7.test,v 1.5 2008/02/18 22:24:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping malloc7 tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + + +do_malloc_test malloc7-1 -sqlprep { + CREATE TABLE t1(a,b,c,d); + CREATE INDEX i1 ON t1(b,c); +} -tclbody { + set sql16 [encoding convertto unicode "SELECT * FROM sqlite_master"] + append sql16 "\00\00" + set nbyte [string length $sql16] + set ::STMT [sqlite3_prepare16 db $sql16 $nbyte DUMMY] + sqlite3_finalize $::STMT +} + + +# Ensure that no file descriptors were leaked. +do_test malloc-99.X { + catch {db close} + set sqlite_open_file_count +} {0} + +puts open-file-count=$sqlite_open_file_count +finish_test diff --git a/components/external/SQLite-3.8.1/test/malloc8.test b/components/external/SQLite-3.8.1/test/malloc8.test new file mode 100644 index 0000000000000000000000000000000000000000..9192eaf512ddea412f3f868e299fc678691471e1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/malloc8.test @@ -0,0 +1,95 @@ +# 2007 April 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file contains additional out-of-memory checks (see malloc.tcl) +# added to expose a bug in out-of-memory handling for sqlite3_value_text() +# +# $Id: malloc8.test,v 1.7 2008/02/18 22:24:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping malloc8 tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + + +# The setup is a database with UTF-16 encoding that contains a single +# large string. We will be running lots of queries against this +# database. Because we will be extracting the string as UTF-8, there +# is a type conversion that occurs and thus an opportunity for malloc() +# to fail and for sqlite3_value_text() to return 0 even though +# sqlite3_value_type() returns SQLITE_TEXT. +# + +do_malloc_test malloc8-1 -sqlprep { + PRAGMA encoding='UTF-16'; + CREATE TABLE t1(a); + INSERT INTO t1 + VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'); +} -sqlbody { + SELECT lower(a), upper(a), quote(a), trim(a), trim('x',a) FROM t1; +} +do_malloc_test malloc8-2 -sqlprep { + PRAGMA encoding='UTF-16'; + CREATE TABLE t1(a); + INSERT INTO t1 + VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'); +} -sqlbody { + SELECT replace(a,'x','y'), replace('x',a,'y'), replace('x','y',a) + FROM t1; +} +do_malloc_test malloc8-3 -sqlprep { + PRAGMA encoding='UTF-16'; + CREATE TABLE t1(a); + INSERT INTO t1 + VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'); +} -sqlbody { + SELECT length(a), substr(a, 4, 4) FROM t1; +} +ifcapable datetime { + do_malloc_test malloc8-4 -sqlprep { + PRAGMA encoding='UTF-16'; + CREATE TABLE t1(a); + INSERT INTO t1 + VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'); + } -sqlbody { + SELECT julianday(a,a) FROM t1; + } +} +do_malloc_test malloc8-5 -sqlprep { + PRAGMA encoding='UTF-16'; + CREATE TABLE t1(a); + INSERT INTO t1 + VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'); +} -sqlbody { + SELECT 1 FROM t1 WHERE a LIKE 'hello' ESCAPE NULL; +} +do_malloc_test malloc8-6 -sqlprep { + PRAGMA encoding='UTF-16'; + CREATE TABLE t1(a); + INSERT INTO t1 + VALUES('0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'); +} -sqlbody { + SELECT hex(randomblob(100)); +} + +# Ensure that no file descriptors were leaked. +do_test malloc-99.X { + catch {db close} + set sqlite_open_file_count +} {0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/malloc9.test b/components/external/SQLite-3.8.1/test/malloc9.test new file mode 100644 index 0000000000000000000000000000000000000000..e142345bfa22f13b6fe057224bd83adf25b2e829 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/malloc9.test @@ -0,0 +1,51 @@ +# 2007 April 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file contains additional out-of-memory checks (see malloc.tcl) +# added to expose a bug in out-of-memory handling for sqlite3_prepare(). +# +# $Id: malloc9.test,v 1.5 2008/04/04 12:21:26 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping malloc9 tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + + +do_malloc_test malloc-9.1 -tclprep { + set sql {CREATE TABLE t1(x)} + set sqlbytes [string length $sql] + append sql {; INSERT INTO t1 VALUES(1)} +} -tclbody { + if {[catch {sqlite3_prepare db $sql $sqlbytes TAIL} STMT]} { + set msg $STMT + set STMT {} + error $msg + } +} -cleanup { + if {$STMT!=""} { + sqlite3_finalize $STMT + } +} + +# Ensure that no file descriptors were leaked. +do_test malloc9-99.X { + catch {db close} + set sqlite_open_file_count +} {0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocA.test b/components/external/SQLite-3.8.1/test/mallocA.test new file mode 100644 index 0000000000000000000000000000000000000000..61e88a61e721be812905257fc809ec5cbd19d862 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocA.test @@ -0,0 +1,126 @@ +# 2007 April 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file contains additional out-of-memory checks (see malloc.tcl). +# +# $Id: mallocA.test,v 1.8 2008/02/18 22:24:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +set testprefix mallocA + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping mallocA tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + + +# Construct a test database +# +forcedelete test.db.bu +db eval { + CREATE TABLE t1(a COLLATE NOCASE,b,c); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(1,2,4); + INSERT INTO t1 VALUES(2,3,4); + CREATE INDEX t1i1 ON t1(a); + CREATE INDEX t1i2 ON t1(b,c); + CREATE TABLE t2(x,y,z); +} +db close +copy_file test.db test.db.bu + +do_malloc_test mallocA-1 -testdb test.db.bu -sqlbody { + ANALYZE +} +do_malloc_test mallocA-1.1 -testdb test.db.bu -sqlbody { + ANALYZE t1 +} +do_malloc_test mallocA-1.2 -testdb test.db.bu -sqlbody { + ANALYZE main +} +do_malloc_test mallocA-1.3 -testdb test.db.bu -sqlbody { + ANALYZE main.t1 +} + +ifcapable reindex { + do_malloc_test mallocA-2 -testdb test.db.bu -sqlbody { + REINDEX; + } + do_malloc_test mallocA-3 -testdb test.db.bu -sqlbody { + REINDEX t1; + } + do_malloc_test mallocA-4 -testdb test.db.bu -sqlbody { + REINDEX main.t1; + } + do_malloc_test mallocA-5 -testdb test.db.bu -sqlbody { + REINDEX nocase; + } +} + +reset_db +sqlite3_db_config_lookaside db 0 0 0 +do_execsql_test 6-prep { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES('abc', 'w'); -- rowid=1 + INSERT INTO t1 VALUES('abc', 'x'); -- rowid=2 + INSERT INTO t1 VALUES('abc', 'y'); -- rowid=3 + INSERT INTO t1 VALUES('abc', 'z'); -- rowid=4 + + INSERT INTO t1 VALUES('def', 'w'); -- rowid=5 + INSERT INTO t1 VALUES('def', 'x'); -- rowid=6 + INSERT INTO t1 VALUES('def', 'y'); -- rowid=7 + INSERT INTO t1 VALUES('def', 'z'); -- rowid=8 + + ANALYZE; +} + +do_faultsim_test 6.1 -faults oom* -body { + execsql { SELECT rowid FROM t1 WHERE a='abc' AND b='x' } +} -test { + faultsim_test_result [list 0 2] +} +do_faultsim_test 6.2 -faults oom* -body { + execsql { SELECT rowid FROM t1 WHERE a='abc' AND b<'y' } +} -test { + faultsim_test_result [list 0 {1 2}] +} +ifcapable stat3 { + do_test 6.3-prep { + execsql { + PRAGMA writable_schema = 1; + CREATE TABLE sqlite_stat4 AS + SELECT tbl, idx, neq, nlt, ndlt, sqlite_record(sample) AS sample + FROM sqlite_stat3; + } + } {} + do_faultsim_test 6.3 -faults oom* -body { + execsql { + ANALYZE sqlite_master; + SELECT rowid FROM t1 WHERE a='abc' AND b<'y'; + } + } -test { + faultsim_test_result [list 0 {1 2}] + } +} + +# Ensure that no file descriptors were leaked. +do_test malloc-99.X { + catch {db close} + set sqlite_open_file_count +} {0} + +forcedelete test.db.bu +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocAll.test b/components/external/SQLite-3.8.1/test/mallocAll.test new file mode 100644 index 0000000000000000000000000000000000000000..b1c94ea23aeafc353ec016b7ffc05454a8fa63ce --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocAll.test @@ -0,0 +1,66 @@ +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs all out-of-memory tests. +# +# $Id: mallocAll.test,v 1.1 2007/11/26 13:36:00 drh Exp $ + +proc lshift {lvar} { + upvar $lvar l + set ret [lindex $l 0] + set l [lrange $l 1 end] + return $ret +} +while {[set arg [lshift argv]] != ""} { + switch -- $arg { + -sharedpagercache { + sqlite3_enable_shared_cache 1 + } + default { + set argv [linsert $argv 0 $arg] + break + } + } +} + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +rename finish_test really_finish_test +proc finish_test {} {} +set G(isquick) 1 + +set EXCLUDE { + mallocAll.test +} + +if {[sqlite3 -has-codec]} { + # lappend EXCLUDE \ + # conflict.test +} + + +# Files to include in the test. If this list is empty then everything +# that is not in the EXCLUDE list is run. +# +set INCLUDE { +} + +foreach testfile [lsort -dictionary [glob $testdir/*malloc*.test]] { + set tail [file tail $testfile] + if {[lsearch -exact $EXCLUDE $tail]>=0} continue + if {[llength $INCLUDE]>0 && [lsearch -exact $INCLUDE $tail]<0} continue + source $testfile + catch {db close} + if {$sqlite_open_file_count>0} { + puts "$tail did not close all files: $sqlite_open_file_count" + fail_test $tail + set sqlite_open_file_count 0 + } +} +source $testdir/misuse.test + +set sqlite_open_file_count 0 +really_finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocB.test b/components/external/SQLite-3.8.1/test/mallocB.test new file mode 100644 index 0000000000000000000000000000000000000000..73468b5099f2967d2f34af11602fe9109489c1a1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocB.test @@ -0,0 +1,51 @@ +# 2007 May 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file contains additional out-of-memory checks (see malloc.tcl). +# These were all discovered by fuzzy generation of SQL. Apart from +# that they have little in common. +# +# +# $Id: mallocB.test,v 1.9 2008/02/18 22:24:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping mallocB tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} +source $testdir/malloc_common.tcl + +do_malloc_test mallocB-1 -sqlbody {SELECT - 456} +do_malloc_test mallocB-2 -sqlbody {SELECT - 456.1} +do_malloc_test mallocB-3 -sqlbody {SELECT random()} +do_malloc_test mallocB-4 -sqlbody {SELECT length(zeroblob(1000))} +ifcapable subquery { + do_malloc_test mallocB-5 -sqlbody {SELECT * FROM (SELECT 1) GROUP BY 1;} +} + +# The following test checks that there are no resource leaks following a +# malloc() failure in sqlite3_set_auxdata(). +# +# Note: This problem was not discovered by fuzzy generation of SQL. Not +# that it really matters. +# +do_malloc_test mallocB-6 -sqlbody { SELECT test_auxdata('hello world'); } + +do_malloc_test mallocB-7 -sqlbody { + SELECT strftime(hex(randomblob(50)) || '%Y', 'now') +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocC.test b/components/external/SQLite-3.8.1/test/mallocC.test new file mode 100644 index 0000000000000000000000000000000000000000..7943353cc7562863a17db061ec40e8464c255272 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocC.test @@ -0,0 +1,122 @@ +# 2007 Aug 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests aspects of the malloc failure while parsing +# CREATE TABLE statements in auto_vacuum mode. +# +# $Id: mallocC.test,v 1.10 2009/04/11 16:27:50 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping mallocC tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + +proc do_mallocC_test {tn args} { + array set ::mallocopts $args + #set sum [allcksum db] + + for {set ::n 1} {true} {incr ::n} { + + # Run the SQL. Malloc number $::n is set to fail. A malloc() failure + # may or may not be reported. + sqlite3_memdebug_fail $::n -repeat 1 + do_test mallocC-$tn.$::n.1 { + set res [catchsql [string trim $::mallocopts(-sql)]] + set rc [expr { + 0==[string compare $res {1 {out of memory}}] || + [db errorcode] == 3082 || + 0==[lindex $res 0] + }] + if {$rc!=1} { + puts "Error: $res" + } + set rc + } {1} + + # If $::n is greater than the number of malloc() calls required to + # execute the SQL, then this test is finished. Break out of the loop. + set nFail [sqlite3_memdebug_fail -1] + if {$nFail==0} { + break + } + + # Recover from the malloc failure. + # + # Update: The new malloc() failure handling means that a transaction may + # still be active even if a malloc() has failed. But when these tests were + # written this was not the case. So do a manual ROLLBACK here so that the + # tests pass. + do_test mallocC-$tn.$::n.2 { + catch { + execsql { + ROLLBACK; + } + } + expr 0 + } {0} + + # Checksum the database. + #do_test mallocC-$tn.$::n.3 { + # allcksum db + #} $sum + + #integrity_check mallocC-$tn.$::n.4 + } + unset ::mallocopts +} + +sqlite3_extended_result_codes db 1 + +execsql { + PRAGMA auto_vacuum=1; + CREATE TABLE t0(a, b, c); +} + +# The number of memory allocation failures is different on 64-bit +# and 32-bit systems due to larger structures on 64-bit systems +# overflowing the lookaside more often. To debug problems, it is +# sometimes helpful to reduce the size of the lookaside allocation +# blocks. But this is normally disabled. +# +if {0} { + db close + sqlite3_shutdown + sqlite3_config_lookaside 50 500 + sqlite3_initialize + autoinstall_test_functions + sqlite3 db test.db +} + +do_mallocC_test 1 -sql { + BEGIN; + -- Allocate 32 new root pages. This will exercise the 'extract specific + -- page from the freelist' code when in auto-vacuum mode (see the + -- allocatePage() routine in btree.c). + CREATE TABLE t1(a UNIQUE, b UNIQUE, c UNIQUE); + CREATE TABLE t2(a UNIQUE, b UNIQUE, c UNIQUE); + CREATE TABLE t3(a UNIQUE, b UNIQUE, c UNIQUE); + CREATE TABLE t4(a UNIQUE, b UNIQUE, c UNIQUE); + CREATE TABLE t5(a UNIQUE, b UNIQUE, c UNIQUE); + CREATE TABLE t6(a UNIQUE, b UNIQUE, c UNIQUE); + CREATE TABLE t7(a UNIQUE, b UNIQUE, c UNIQUE); + CREATE TABLE t8(a UNIQUE, b UNIQUE, c UNIQUE); + + ROLLBACK; +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocD.test b/components/external/SQLite-3.8.1/test/mallocD.test new file mode 100644 index 0000000000000000000000000000000000000000..08a2ba439967a07867fc1cc0f3c1527ec786ba15 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocD.test @@ -0,0 +1,65 @@ +# 2007 Aug 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: mallocD.test,v 1.6 2008/02/18 22:24:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping mallocD tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + +db close +sqlite3_simulate_device -char atomic +sqlite3 db test.db -vfs devsym + +set PREP { + PRAGMA page_size = 1024; + CREATE TABLE abc(a, b, c); +} + +do_malloc_test mallocD-1 -sqlprep $PREP -sqlbody { + INSERT INTO abc VALUES(1, 2, 3); +} + +do_malloc_test mallocD-2 -sqlprep $PREP -sqlbody { + BEGIN; + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, 6); + ROLLBACK; +} + +do_malloc_test mallocD-3 -sqlprep $PREP -sqlbody { + BEGIN; + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, randstr(1500,1500)); + COMMIT; +} + +ifcapable attach { + do_malloc_test mallocD-4 -sqlprep $PREP -sqlbody { + ATTACH 'test2.db' AS aux; + BEGIN; + CREATE TABLE aux.def(d, e, f); + INSERT INTO abc VALUES(4, 5, 6); + COMMIT; + } +} + +sqlite3_simulate_device -char {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocE.test b/components/external/SQLite-3.8.1/test/mallocE.test new file mode 100644 index 0000000000000000000000000000000000000000..e87bc8b3afc3b86dc2483e392e47e3fe73571cf9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocE.test @@ -0,0 +1,48 @@ +# 2007 Aug 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test script checks that tickets #2784 and #2789 have been fixed. +# +# $Id: mallocE.test,v 1.3 2008/02/18 22:24:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping mallocE tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + +# ticket #2784 +# +set PREP { + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(x, y, z); +} +do_malloc_test mallocE-1 -sqlprep $PREP -sqlbody { + SELECT p, q FROM (SELECT a+b AS p, b+c AS q FROM t1, t2 WHERE c>5) + LEFT JOIN t2 ON p=x; +} + +# Ticket #2789 +# +do_malloc_test mallocE-2 -sqlprep $PREP -sqlbody { + SELECT x, y2 FROM (SELECT a+b AS x, b+c AS y2 FROM t1, t2 WHERE c>5) + LEFT JOIN t2 USING(x) WHERE y2>11; +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocF.test b/components/external/SQLite-3.8.1/test/mallocF.test new file mode 100644 index 0000000000000000000000000000000000000000..0015005fec91a191bcd338f79e8e193d30aeb796 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocF.test @@ -0,0 +1,76 @@ +# 2007 Aug 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test script checks that tickets #2794, #2795, #2796, and #2797 +# have been fixed. +# +# $Id: mallocF.test,v 1.4 2008/02/18 22:24:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping mallocF tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + +# tickets #2794 and #2795 and #2797 +# +set PREP { + CREATE TABLE t1(x,y); + INSERT INTO t1 VALUES('abc123', 5); + INSERT INTO t1 VALUES('xyz987', 42); +} +do_malloc_test malloeF-1 -sqlprep $PREP -sqlbody { + SELECT * FROM t1 WHERE x GLOB 'abc*' +} + +# ticket #2796 +# +set PREP { + CREATE TABLE t1(x PRIMARY KEY,y UNIQUE); + INSERT INTO t1 VALUES('abc123', 5); + INSERT INTO t1 VALUES('xyz987', 42); +} +do_malloc_test malloeF-2 -sqlprep $PREP -sqlbody { + SELECT x FROM t1 + WHERE y=1 OR y=2 OR y=3 OR y=4 OR y=5 + OR y=6 OR y=7 OR y=8 OR y=9 OR y=10 + OR y=11 OR y=12 OR y=13 OR y=14 OR y=15 + OR y=x +} + +set PREP { + CREATE TABLE t1(x PRIMARY KEY,y UNIQUE); + INSERT INTO t1 VALUES('abc123', 5); + INSERT INTO t1 VALUES('xyz987', 42); +} +do_malloc_test malloeF-3 -sqlprep $PREP -sqlbody { + SELECT x FROM t1 WHERE y BETWEEN 10 AND 29 +} + +# Ticket #2843 +# +set PREP { + CREATE TABLE t1(x); + CREATE TRIGGER r1 BEFORE INSERT ON t1 BEGIN + SELECT 'hello'; + END; +} +do_malloc_test mallocF-4 -sqlprep $PREP -sqlbody { + INSERT INTO t1 VALUES(random()); +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocG.test b/components/external/SQLite-3.8.1/test/mallocG.test new file mode 100644 index 0000000000000000000000000000000000000000..4f2395db9cdf1b4340ee236ce863876822b223cd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocG.test @@ -0,0 +1,73 @@ +# 2007 Aug 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test script checks malloc failures in various obscure operations. +# +# $Id: mallocG.test,v 1.5 2008/08/01 18:47:02 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Only run these tests if memory debugging is turned on. +# +if {!$MEMDEBUG} { + puts "Skipping mallocG tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} + +# Malloc failures while opening a database connection. +# +do_malloc_test mallocG-1 -tclbody { + db close + sqlite3 db test.db +} + +do_malloc_test mallocG-2 -sqlprep { + CREATE TABLE t1(x, y); + CREATE TABLE t2(x INTEGER PRIMARY KEY); +} -sqlbody { + SELECT y FROM t1 WHERE x IN t2; +} + +do_malloc_test mallocG-3 -sqlprep { + CREATE TABLE t1(x UNIQUE); + INSERT INTO t1 VALUES ('hello'); + INSERT INTO t1 VALUES ('out there'); +} -sqlbody { + SELECT * FROM t1 + WHERE x BETWEEN 'a' AND 'z' + AND x BETWEEN 'c' AND 'w' + AND x BETWEEN 'e' AND 'u' + AND x BETWEEN 'g' AND 'r' + AND x BETWEEN 'i' AND 'q' + AND x BETWEEN 'i' AND 'm' +} + +ifcapable !utf16 { + finish_test + return +} + +proc utf16 {utf8} { + set utf16 [encoding convertto unicode $utf8] + append utf16 "\x00\x00" + return $utf16 +} + +do_malloc_test mallocG-4 -tclbody { + set rc [sqlite3_complete16 [utf16 "SELECT * FROM t1;"]] + if {$rc==1} {set rc 0} {error "out of memory"} + set rc +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocH.test b/components/external/SQLite-3.8.1/test/mallocH.test new file mode 100644 index 0000000000000000000000000000000000000000..7017b381ab1d8595648ab3be0d28423072878350 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocH.test @@ -0,0 +1,73 @@ +# 2008 August 01 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test script checks malloc failures in various obscure operations. +# +# $Id: mallocH.test,v 1.2 2008/08/01 20:10:09 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Malloc failures in journaling of in-memory databases. +# +do_malloc_test mallocH-1 -tclprep { + db close + sqlite3 db :memory: + db eval { + CREATE TABLE t1(x UNIQUE, y); + INSERT INTO t1 VALUES(1,2); + } +} -sqlbody { + INSERT INTO t1 SELECT x+1, y+100 FROM t1; +} + +# Malloc failures while parsing a CASE expression. +# +do_malloc_test mallocH-2 -sqlbody { + SELECT CASE WHEN 1 THEN 1 END; +} + +# Malloc failures while parsing a EXISTS(SELECT ...) +# +do_malloc_test mallocH-3 -sqlbody { + SELECT 3+EXISTS(SELECT * FROM sqlite_master); +} + +# Malloc failures within the replace() function. +# +do_malloc_test mallocH-3 -sqlbody { + SELECT replace('ababa','a','xyzzy'); +} + +# Malloc failures during EXPLAIN. +# +ifcapable explain { + do_malloc_test mallocH-4 -sqlprep { + CREATE TABLE abc(a PRIMARY KEY, b, c); + } -sqlbody { + EXPLAIN SELECT * FROM abc AS t2 WHERE rowid=1; + EXPLAIN QUERY PLAN SELECT * FROM abc AS t2 WHERE rowid=1; + } +} + +# Malloc failure during integrity_check pragma. +# +do_malloc_test mallocH-5 -sqlprep { + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + CREATE TABLE t2(x,y); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 SELECT * FROM t1; +} -sqlbody { + PRAGMA integrity_check; +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocI.test b/components/external/SQLite-3.8.1/test/mallocI.test new file mode 100644 index 0000000000000000000000000000000000000000..122945550516863d9fde3e7522944fca44f06ed3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocI.test @@ -0,0 +1,64 @@ +# 2008 August 01 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test script checks malloc failures in various obscure operations. +# +# $Id: mallocI.test,v 1.3 2009/08/10 04:26:39 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# Malloc failures in a view. +# +do_malloc_test mallocI-1 -sqlprep { + CREATE TABLE t1(a,b,c,d); + CREATE VIEW v1 AS SELECT a*b, c*d FROM t1 ORDER BY b-d; +} -sqlbody { + SELECT * FROM v1 +} + +# Malloc failure while trying to service a pragma on a TEMP database. +# +do_malloc_test mallocI-2 -sqlbody { + PRAGMA temp.page_size +} + +# Malloc failure while creating a table from a SELECT statement. +# +do_malloc_test mallocI-3 -sqlprep { + CREATE TABLE t1(a,b,c); +} -sqlbody { + CREATE TABLE t2 AS SELECT b,c FROM t1; +} + +# This tests that a malloc failure that occurs while passing the schema +# does not result in a SHARED lock being left on the database file. +# +do_malloc_test mallocI-4 -tclprep { + sqlite3 db2 test.db + db2 eval { + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(a, b, c); + } +} -sqlbody { + SELECT * FROM t1 +} -cleanup { + do_test mallocI-4.$::n.2 { + # If this INSERT is possible then [db] does not hold a shared lock + # on the database file. + catchsql { INSERT INTO t1 VALUES(1, 2, 3) } db2 + } {0 {}} + catch {db2 close} +} +catch { db2 close } + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocJ.test b/components/external/SQLite-3.8.1/test/mallocJ.test new file mode 100644 index 0000000000000000000000000000000000000000..e63f6b794a7e541bd8838e4722c236ac1f99b390 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocJ.test @@ -0,0 +1,73 @@ +# 2008 August 01 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test script checks malloc failures in LIMIT operations for +# UPDATE/DELETE statements. +# +# $Id: mallocJ.test,v 1.6 2009/01/09 02:49:32 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +ifcapable {update_delete_limit} { + + do_malloc_test mallocJ-1 -sqlprep { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(x int, y int); + INSERT INTO t1 VALUES(1,1); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(2,1); + INSERT INTO t1 VALUES(2,2); + INSERT INTO t1 VALUES(2,3); + } -sqlbody { + UPDATE t1 SET x=1 ORDER BY y LIMIT 2 OFFSET 2; + UPDATE t1 SET x=2 WHERE y=1 ORDER BY y LIMIT 2 OFFSET 2; + DELETE FROM t1 WHERE x=1 ORDER BY y LIMIT 2 OFFSET 2; + DELETE FROM t1 ORDER BY y LIMIT 2 OFFSET 2; + } + +} + +# ticket #3467 +do_malloc_test mallocJ-2 -sqlprep { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + PRAGMA vdbe_trace=ON; +} -sqlbody { + SELECT a, b, 'abc' FROM t1 + UNION + SELECT b, a, 'xyz' FROM t1 + ORDER BY 2, 3; +} + +# ticket #3478 +do_malloc_test mallocJ-3 -sqlbody { + EXPLAIN COMMIT +} + +# ticket #3485 +do_malloc_test mallocJ-4 -sqlprep { + CREATE TABLE t1(a,b,c); + CREATE TABLE t2(x,y,z); +} -sqlbody { + SELECT * FROM (SELECT a,b FROM t1 UNION ALL SELECT x, y FROM t2) ORDER BY 1 +} + +# coverage testing +do_malloc_test mallocJ-5 -sqlprep { + CREATE TABLE t1(["a"]); +} -sqlbody { + SELECT * FROM t1 +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mallocK.test b/components/external/SQLite-3.8.1/test/mallocK.test new file mode 100644 index 0000000000000000000000000000000000000000..971bd561377182112945623332d134fe7122b441 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mallocK.test @@ -0,0 +1,72 @@ +# 2008 August 01 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test script checks malloc failures in WHERE clause analysis. +# +# $Id: mallocK.test,v 1.3 2009/01/08 21:00:03 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +set sql {SELECT * FROM t1, t2 WHERE (a=1 OR a=2)} +for {set x 1} {$x<5} {incr x} { + append sql " AND b=y" + do_malloc_test mallocK-1.$x -sqlbody $sql -sqlprep { + CREATE TABLE t1(a,b); + CREATE TABLE t2(x,y); + } +} + +set sql {SELECT * FROM t1 WHERE a GLOB 'xyz*' AND (a=1 OR a=2)} +for {set x 1} {$x<5} {incr x} { + append sql " AND b!=$x" + do_malloc_test mallocK-2.$x -sqlbody $sql -sqlprep { + CREATE TABLE t1(a,b); + } +} + +set sql {SELECT * FROM t1 WHERE a BETWEEN 5 AND 10} +for {set x 1} {$x<5} {incr x} { + append sql " AND b=$x" + do_malloc_test mallocK-3.$x -sqlbody $sql -sqlprep { + CREATE TABLE t1(a,b); + } +} + +set sql {SELECT * FROM t1 WHERE b=0} +for {set x 1} {$x<5} {incr x} { + set term "(b=$x" + for {set y 0} {$y<$x} {incr y} { + append term " AND a!=$y" + } + append sql " OR $term)" + do_malloc_test mallocK-4.$x -sqlbody $sql -sqlprep { + CREATE TABLE t1(a,b); + } +} + +ifcapable vtab { + set sql {SELECT * FROM t2 WHERE a MATCH 'xyz'} + for {set x 1} {$x<5} {incr x} { + append sql " AND b!=$x" + do_malloc_test mallocK-5.$x -sqlbody $sql -tclprep { + register_echo_module [sqlite3_connection_pointer db] + db eval { + CREATE TABLE t1(a,b); + CREATE VIRTUAL TABLE t2 USING echo(t1); + } + } + } +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/malloc_common.tcl b/components/external/SQLite-3.8.1/test/malloc_common.tcl new file mode 100644 index 0000000000000000000000000000000000000000..160897057af0ae0df656f80572e5b529ae7a2c83 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/malloc_common.tcl @@ -0,0 +1,686 @@ +# 2007 May 05 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains common code used by many different malloc tests +# within the test suite. +# +# $Id: malloc_common.tcl,v 1.22 2008/09/23 16:41:30 danielk1977 Exp $ + +# If we did not compile with malloc testing enabled, then do nothing. +# +ifcapable builtin_test { + set MEMDEBUG 1 +} else { + set MEMDEBUG 0 + return 0 +} + +# Transient and persistent OOM errors: +# +set FAULTSIM(oom-transient) [list \ + -injectstart {oom_injectstart 0} \ + -injectstop oom_injectstop \ + -injecterrlist {{1 {out of memory}}} \ +] +set FAULTSIM(oom-persistent) [list \ + -injectstart {oom_injectstart 1000000} \ + -injectstop oom_injectstop \ + -injecterrlist {{1 {out of memory}}} \ +] + +# Transient and persistent IO errors: +# +set FAULTSIM(ioerr-transient) [list \ + -injectstart {ioerr_injectstart 0} \ + -injectstop ioerr_injectstop \ + -injecterrlist {{1 {disk I/O error}}} \ +] +set FAULTSIM(ioerr-persistent) [list \ + -injectstart {ioerr_injectstart 1} \ + -injectstop ioerr_injectstop \ + -injecterrlist {{1 {disk I/O error}}} \ +] + +# SQLITE_FULL errors (always persistent): +# +set FAULTSIM(full) [list \ + -injectinstall fullerr_injectinstall \ + -injectstart fullerr_injectstart \ + -injectstop fullerr_injectstop \ + -injecterrlist {{1 {database or disk is full}}} \ + -injectuninstall fullerr_injectuninstall \ +] + +# Transient and persistent SHM errors: +# +set FAULTSIM(shmerr-transient) [list \ + -injectinstall shmerr_injectinstall \ + -injectstart {shmerr_injectstart 0} \ + -injectstop shmerr_injectstop \ + -injecterrlist {{1 {disk I/O error}}} \ + -injectuninstall shmerr_injectuninstall \ +] +set FAULTSIM(shmerr-persistent) [list \ + -injectinstall shmerr_injectinstall \ + -injectstart {shmerr_injectstart 1} \ + -injectstop shmerr_injectstop \ + -injecterrlist {{1 {disk I/O error}}} \ + -injectuninstall shmerr_injectuninstall \ +] + +# Transient and persistent CANTOPEN errors: +# +set FAULTSIM(cantopen-transient) [list \ + -injectinstall cantopen_injectinstall \ + -injectstart {cantopen_injectstart 0} \ + -injectstop cantopen_injectstop \ + -injecterrlist {{1 {unable to open database file}}} \ + -injectuninstall cantopen_injectuninstall \ +] +set FAULTSIM(cantopen-persistent) [list \ + -injectinstall cantopen_injectinstall \ + -injectstart {cantopen_injectstart 1} \ + -injectstop cantopen_injectstop \ + -injecterrlist {{1 {unable to open database file}}} \ + -injectuninstall cantopen_injectuninstall \ +] + +set FAULTSIM(interrupt) [list \ + -injectinstall interrupt_injectinstall \ + -injectstart interrupt_injectstart \ + -injectstop interrupt_injectstop \ + -injecterrlist {{1 interrupted} {1 interrupt}} \ + -injectuninstall interrupt_injectuninstall \ +] + + + +#-------------------------------------------------------------------------- +# Usage do_faultsim_test NAME ?OPTIONS...? +# +# -faults List of fault types to simulate. +# +# -prep Script to execute before -body. +# +# -body Script to execute (with fault injection). +# +# -test Script to execute after -body. +# +# -install Script to execute after faultsim -injectinstall +# +# -uninstall Script to execute after faultsim -uninjectinstall +# +proc do_faultsim_test {name args} { + global FAULTSIM + + foreach n [array names FAULTSIM] { + if {$n != "interrupt"} {lappend DEFAULT(-faults) $n} + } + set DEFAULT(-prep) "" + set DEFAULT(-body) "" + set DEFAULT(-test) "" + set DEFAULT(-install) "" + set DEFAULT(-uninstall) "" + + fix_testname name + + array set O [array get DEFAULT] + array set O $args + foreach o [array names O] { + if {[info exists DEFAULT($o)]==0} { error "unknown option: $o" } + } + + set faultlist [list] + foreach f $O(-faults) { + set flist [array names FAULTSIM $f] + if {[llength $flist]==0} { error "unknown fault: $f" } + set faultlist [concat $faultlist $flist] + } + + set testspec [list -prep $O(-prep) -body $O(-body) \ + -test $O(-test) -install $O(-install) -uninstall $O(-uninstall) + ] + foreach f [lsort -unique $faultlist] { + eval do_one_faultsim_test "$name-$f" $FAULTSIM($f) $testspec + } +} + + +#------------------------------------------------------------------------- +# Procedures to save and restore the current file-system state: +# +# faultsim_save +# faultsim_restore +# faultsim_save_and_close +# faultsim_restore_and_reopen +# faultsim_delete_and_reopen +# +proc faultsim_save {args} { uplevel db_save $args } +proc faultsim_save_and_close {args} { uplevel db_save_and_close $args } +proc faultsim_restore {args} { uplevel db_restore $args } +proc faultsim_restore_and_reopen {args} { + uplevel db_restore_and_reopen $args + sqlite3_extended_result_codes db 1 + sqlite3_db_config_lookaside db 0 0 0 +} +proc faultsim_delete_and_reopen {args} { + uplevel db_delete_and_reopen $args + sqlite3_extended_result_codes db 1 + sqlite3_db_config_lookaside db 0 0 0 +} + +proc faultsim_integrity_check {{db db}} { + set ic [$db eval { PRAGMA integrity_check }] + if {$ic != "ok"} { error "Integrity check: $ic" } +} + + +# The following procs are used as [do_one_faultsim_test] callbacks when +# injecting OOM faults into test cases. +# +proc oom_injectstart {nRepeat iFail} { + sqlite3_memdebug_fail [expr $iFail-1] -repeat $nRepeat +} +proc oom_injectstop {} { + sqlite3_memdebug_fail -1 +} + +# The following procs are used as [do_one_faultsim_test] callbacks when +# injecting IO error faults into test cases. +# +proc ioerr_injectstart {persist iFail} { + set ::sqlite_io_error_persist $persist + set ::sqlite_io_error_pending $iFail +} +proc ioerr_injectstop {} { + set sv $::sqlite_io_error_hit + set ::sqlite_io_error_persist 0 + set ::sqlite_io_error_pending 0 + set ::sqlite_io_error_hardhit 0 + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_pending 0 + return $sv +} + +# The following procs are used as [do_one_faultsim_test] callbacks when +# injecting shared-memory related error faults into test cases. +# +proc shmerr_injectinstall {} { + testvfs shmfault -default true + shmfault filter {xShmOpen xShmMap xShmLock} +} +proc shmerr_injectuninstall {} { + catch {db close} + catch {db2 close} + shmfault delete +} +proc shmerr_injectstart {persist iFail} { + shmfault ioerr $iFail $persist +} +proc shmerr_injectstop {} { + shmfault ioerr +} + +# The following procs are used as [do_one_faultsim_test] callbacks when +# injecting SQLITE_FULL error faults into test cases. +# +proc fullerr_injectinstall {} { + testvfs shmfault -default true +} +proc fullerr_injectuninstall {} { + catch {db close} + catch {db2 close} + shmfault delete +} +proc fullerr_injectstart {iFail} { + shmfault full $iFail 1 +} +proc fullerr_injectstop {} { + shmfault full +} + +# The following procs are used as [do_one_faultsim_test] callbacks when +# injecting SQLITE_CANTOPEN error faults into test cases. +# +proc cantopen_injectinstall {} { + testvfs shmfault -default true +} +proc cantopen_injectuninstall {} { + catch {db close} + catch {db2 close} + shmfault delete +} +proc cantopen_injectstart {persist iFail} { + shmfault cantopen $iFail $persist +} +proc cantopen_injectstop {} { + shmfault cantopen +} + +# The following procs are used as [do_one_faultsim_test] callbacks +# when injecting SQLITE_INTERRUPT error faults into test cases. +# +proc interrupt_injectinstall {} { +} +proc interrupt_injectuninstall {} { +} +proc interrupt_injectstart {iFail} { + set ::sqlite_interrupt_count $iFail +} +proc interrupt_injectstop {} { + set res [expr $::sqlite_interrupt_count<=0] + set ::sqlite_interrupt_count 0 + set res +} + +# This command is not called directly. It is used by the +# [faultsim_test_result] command created by [do_faultsim_test] and used +# by -test scripts. +# +proc faultsim_test_result_int {args} { + upvar testrc testrc testresult testresult testnfail testnfail + set t [list $testrc $testresult] + set r $args + if { ($testnfail==0 && $t != [lindex $r 0]) || [lsearch $r $t]<0 } { + error "nfail=$testnfail rc=$testrc result=$testresult list=$r" + } +} + +#-------------------------------------------------------------------------- +# Usage do_one_faultsim_test NAME ?OPTIONS...? +# +# The first argument, , is used as a prefix of the test names +# taken by tests executed by this command. Options are as follows. All +# options take a single argument. +# +# -injectstart Script to enable fault-injection. +# +# -injectstop Script to disable fault-injection. +# +# -injecterrlist List of generally acceptable test results (i.e. error +# messages). Example: [list {1 {out of memory}}] +# +# -injectinstall +# +# -injectuninstall +# +# -prep Script to execute before -body. +# +# -body Script to execute (with fault injection). +# +# -test Script to execute after -body. +# +proc do_one_faultsim_test {testname args} { + + set DEFAULT(-injectstart) "expr" + set DEFAULT(-injectstop) "expr 0" + set DEFAULT(-injecterrlist) [list] + set DEFAULT(-injectinstall) "" + set DEFAULT(-injectuninstall) "" + set DEFAULT(-prep) "" + set DEFAULT(-body) "" + set DEFAULT(-test) "" + set DEFAULT(-install) "" + set DEFAULT(-uninstall) "" + + array set O [array get DEFAULT] + array set O $args + foreach o [array names O] { + if {[info exists DEFAULT($o)]==0} { error "unknown option: $o" } + } + + proc faultsim_test_proc {testrc testresult testnfail} $O(-test) + proc faultsim_test_result {args} " + uplevel faultsim_test_result_int \$args [list $O(-injecterrlist)] + " + + eval $O(-injectinstall) + eval $O(-install) + + set stop 0 + for {set iFail 1} {!$stop} {incr iFail} { + + # Evaluate the -prep script. + # + eval $O(-prep) + + # Start the fault-injection. Run the -body script. Stop the fault + # injection. Local var $nfail is set to the total number of faults + # injected into the system this trial. + # + eval $O(-injectstart) $iFail + set rc [catch $O(-body) res] + set nfail [eval $O(-injectstop)] + + # Run the -test script. If it throws no error, consider this trial + # sucessful. If it does throw an error, cause a [do_test] test to + # fail (and print out the unexpected exception thrown by the -test + # script at the same time). + # + set rc [catch [list faultsim_test_proc $rc $res $nfail] res] + if {$rc == 0} {set res ok} + do_test $testname.$iFail [list list $rc $res] {0 ok} + + # If no faults where injected this trial, don't bother running + # any more. This test is finished. + # + if {$nfail==0} { set stop 1 } + } + + eval $O(-uninstall) + eval $O(-injectuninstall) +} + +# Usage: do_malloc_test +# +# The first argument, , is an integer used to name the +# tests executed by this proc. Options are as follows: +# +# -tclprep TCL script to run to prepare test. +# -sqlprep SQL script to run to prepare test. +# -tclbody TCL script to run with malloc failure simulation. +# -sqlbody TCL script to run with malloc failure simulation. +# -cleanup TCL script to run after the test. +# +# This command runs a series of tests to verify SQLite's ability +# to handle an out-of-memory condition gracefully. It is assumed +# that if this condition occurs a malloc() call will return a +# NULL pointer. Linux, for example, doesn't do that by default. See +# the "BUGS" section of malloc(3). +# +# Each iteration of a loop, the TCL commands in any argument passed +# to the -tclbody switch, followed by the SQL commands in any argument +# passed to the -sqlbody switch are executed. Each iteration the +# Nth call to sqliteMalloc() is made to fail, where N is increased +# each time the loop runs starting from 1. When all commands execute +# successfully, the loop ends. +# +proc do_malloc_test {tn args} { + array unset ::mallocopts + array set ::mallocopts $args + + if {[string is integer $tn]} { + set tn malloc-$tn + } + if {[info exists ::mallocopts(-start)]} { + set start $::mallocopts(-start) + } else { + set start 0 + } + if {[info exists ::mallocopts(-end)]} { + set end $::mallocopts(-end) + } else { + set end 50000 + } + save_prng_state + + foreach ::iRepeat {0 10000000} { + set ::go 1 + for {set ::n $start} {$::go && $::n <= $end} {incr ::n} { + + # If $::iRepeat is 0, then the malloc() failure is transient - it + # fails and then subsequent calls succeed. If $::iRepeat is 1, + # then the failure is persistent - once malloc() fails it keeps + # failing. + # + set zRepeat "transient" + if {$::iRepeat} {set zRepeat "persistent"} + restore_prng_state + foreach file [glob -nocomplain test.db-mj*] {forcedelete $file} + + do_test ${tn}.${zRepeat}.${::n} { + + # Remove all traces of database files test.db and test2.db + # from the file-system. Then open (empty database) "test.db" + # with the handle [db]. + # + catch {db close} + catch {db2 close} + forcedelete test.db + forcedelete test.db-journal + forcedelete test.db-wal + forcedelete test2.db + forcedelete test2.db-journal + forcedelete test2.db-wal + if {[info exists ::mallocopts(-testdb)]} { + copy_file $::mallocopts(-testdb) test.db + } + catch { sqlite3 db test.db } + if {[info commands db] ne ""} { + sqlite3_extended_result_codes db 1 + } + sqlite3_db_config_lookaside db 0 0 0 + + # Execute any -tclprep and -sqlprep scripts. + # + if {[info exists ::mallocopts(-tclprep)]} { + eval $::mallocopts(-tclprep) + } + if {[info exists ::mallocopts(-sqlprep)]} { + execsql $::mallocopts(-sqlprep) + } + + # Now set the ${::n}th malloc() to fail and execute the -tclbody + # and -sqlbody scripts. + # + sqlite3_memdebug_fail $::n -repeat $::iRepeat + set ::mallocbody {} + if {[info exists ::mallocopts(-tclbody)]} { + append ::mallocbody "$::mallocopts(-tclbody)\n" + } + if {[info exists ::mallocopts(-sqlbody)]} { + append ::mallocbody "db eval {$::mallocopts(-sqlbody)}" + } + + # The following block sets local variables as follows: + # + # isFail - True if an error (any error) was reported by sqlite. + # nFail - The total number of simulated malloc() failures. + # nBenign - The number of benign simulated malloc() failures. + # + set isFail [catch $::mallocbody msg] + set nFail [sqlite3_memdebug_fail -1 -benigncnt nBenign] + # puts -nonewline " (isFail=$isFail nFail=$nFail nBenign=$nBenign) " + + # If one or more mallocs failed, run this loop body again. + # + set go [expr {$nFail>0}] + + if {($nFail-$nBenign)==0} { + if {$isFail} { + set v2 $msg + } else { + set isFail 1 + set v2 1 + } + } elseif {!$isFail} { + set v2 $msg + } elseif { + [info command db]=="" || + [db errorcode]==7 || + $msg=="out of memory" + } { + set v2 1 + } else { + set v2 $msg + puts [db errorcode] + } + lappend isFail $v2 + } {1 1} + + if {[info exists ::mallocopts(-cleanup)]} { + catch [list uplevel #0 $::mallocopts(-cleanup)] msg + } + } + } + unset ::mallocopts + sqlite3_memdebug_fail -1 +} + + +#------------------------------------------------------------------------- +# This proc is used to test a single SELECT statement. Parameter $name is +# passed a name for the test case (i.e. "fts3_malloc-1.4.1") and parameter +# $sql is passed the text of the SELECT statement. Parameter $result is +# set to the expected output if the SELECT statement is successfully +# executed using [db eval]. +# +# Example: +# +# do_select_test testcase-1.1 "SELECT 1+1, 1+2" {1 2} +# +# If global variable DO_MALLOC_TEST is set to a non-zero value, or if +# it is not defined at all, then OOM testing is performed on the SELECT +# statement. Each OOM test case is said to pass if either (a) executing +# the SELECT statement succeeds and the results match those specified +# by parameter $result, or (b) TCL throws an "out of memory" error. +# +# If DO_MALLOC_TEST is defined and set to zero, then the SELECT statement +# is executed just once. In this case the test case passes if the results +# match the expected results passed via parameter $result. +# +proc do_select_test {name sql result} { + uplevel [list doPassiveTest 0 $name $sql [list 0 [list {*}$result]]] +} + +proc do_restart_select_test {name sql result} { + uplevel [list doPassiveTest 1 $name $sql [list 0 $result]] +} + +proc do_error_test {name sql error} { + uplevel [list doPassiveTest 0 $name $sql [list 1 $error]] +} + +proc doPassiveTest {isRestart name sql catchres} { + if {![info exists ::DO_MALLOC_TEST]} { set ::DO_MALLOC_TEST 1 } + + if {[info exists ::testprefix] + && [string is integer [string range $name 0 0]] + } { + set name $::testprefix.$name + } + + switch $::DO_MALLOC_TEST { + 0 { # No malloc failures. + do_test $name [list set {} [uplevel [list catchsql $sql]]] $catchres + return + } + 1 { # Simulate transient failures. + set nRepeat 1 + set zName "transient" + set nStartLimit 100000 + set nBackup 1 + } + 2 { # Simulate persistent failures. + set nRepeat 1 + set zName "persistent" + set nStartLimit 100000 + set nBackup 1 + } + 3 { # Simulate transient failures with extra brute force. + set nRepeat 100000 + set zName "ridiculous" + set nStartLimit 1 + set nBackup 10 + } + } + + # The set of acceptable results from running [catchsql $sql]. + # + set answers [list {1 {out of memory}} $catchres] + set str [join $answers " OR "] + + set nFail 1 + for {set iLimit $nStartLimit} {$nFail} {incr iLimit} { + for {set iFail 1} {$nFail && $iFail<=$iLimit} {incr iFail} { + for {set iTest 0} {$iTest<$nBackup && ($iFail-$iTest)>0} {incr iTest} { + + if {$isRestart} { sqlite3 db test.db } + + sqlite3_memdebug_fail [expr $iFail-$iTest] -repeat $nRepeat + set res [uplevel [list catchsql $sql]] + if {[lsearch -exact $answers $res]>=0} { set res $str } + set testname "$name.$zName.$iFail" + do_test "$name.$zName.$iLimit.$iFail" [list set {} $res] $str + + set nFail [sqlite3_memdebug_fail -1 -benigncnt nBenign] + } + } + } +} + + +#------------------------------------------------------------------------- +# Test a single write to the database. In this case a "write" is a +# DELETE, UPDATE or INSERT statement. +# +# If OOM testing is performed, there are several acceptable outcomes: +# +# 1) The write succeeds. No error is returned. +# +# 2) An "out of memory" exception is thrown and: +# +# a) The statement has no effect, OR +# b) The current transaction is rolled back, OR +# c) The statement succeeds. This can only happen if the connection +# is in auto-commit mode (after the statement is executed, so this +# includes COMMIT statements). +# +# If the write operation eventually succeeds, zero is returned. If a +# transaction is rolled back, non-zero is returned. +# +# Parameter $name is the name to use for the test case (or test cases). +# The second parameter, $tbl, should be the name of the database table +# being modified. Parameter $sql contains the SQL statement to test. +# +proc do_write_test {name tbl sql} { + if {![info exists ::DO_MALLOC_TEST]} { set ::DO_MALLOC_TEST 1 } + + # Figure out an statement to get a checksum for table $tbl. + db eval "SELECT * FROM $tbl" V break + set cksumsql "SELECT md5sum([join [concat rowid $V(*)] ,]) FROM $tbl" + + # Calculate the initial table checksum. + set cksum1 [db one $cksumsql] + + if {$::DO_MALLOC_TEST } { + set answers [list {1 {out of memory}} {0 {}}] + if {$::DO_MALLOC_TEST==1} { + set modes {100000 persistent} + } else { + set modes {1 transient} + } + } else { + set answers [list {0 {}}] + set modes [list 0 nofail] + } + set str [join $answers " OR "] + + foreach {nRepeat zName} $modes { + for {set iFail 1} 1 {incr iFail} { + if {$::DO_MALLOC_TEST} {sqlite3_memdebug_fail $iFail -repeat $nRepeat} + + set res [uplevel [list catchsql $sql]] + set nFail [sqlite3_memdebug_fail -1 -benigncnt nBenign] + if {$nFail==0} { + do_test $name.$zName.$iFail [list set {} $res] {0 {}} + return + } else { + if {[lsearch $answers $res]>=0} { + set res $str + } + do_test $name.$zName.$iFail [list set {} $res] $str + set cksum2 [db one $cksumsql] + if {$cksum1 != $cksum2} return + } + } + } +} diff --git a/components/external/SQLite-3.8.1/test/manydb.test b/components/external/SQLite-3.8.1/test/manydb.test new file mode 100644 index 0000000000000000000000000000000000000000..974a5b8ebe7b8faee295e41f71f678382e8c5d3c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/manydb.test @@ -0,0 +1,102 @@ +# 2005 October 3 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests the ability of the library to open +# many different databases at the same time without leaking memory. +# +# $Id: manydb.test,v 1.4 2008/11/21 00:10:35 aswift Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set N 300 +# if we're using proxy locks, we use 5 filedescriptors for a db +# that is open and in the middle of writing changes, normally +# sqlite uses 3 (proxy locking adds the conch and the local lock) +set using_proxy 0 +foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] { + set using_proxy value +} +set num_fd_per_openwrite_db 3 +if {$using_proxy>0} { + set num_fd_per_openwrite_db 5 +} + +# First test how many file descriptors are available for use. To open a +# database for writing SQLite requires 3 file descriptors (the database, the +# journal and the directory). +set filehandles {} +catch { + for {set i 0} {$i<($N * 3)} {incr i} { + lappend filehandles [open testfile.1 w] + } +} +foreach fd $filehandles { + close $fd +} +catch { + forcedelete testfile.1 +} +set N [expr $i / $num_fd_per_openwrite_db] + +# Create a bunch of random database names +# +unset -nocomplain dbname +unset -nocomplain used +for {set i 0} {$i<$N} {incr i} { + while 1 { + set name test-[format %08x [expr {int(rand()*0x7fffffff)}]].db + if {[info exists used($name)]} continue + set dbname($i) $name + set used($name) $i + break + } +} + +# Create a bunch of databases +# +for {set i 0} {$i<$N} {incr i} { + do_test manydb-1.$i { + sqlite3 db$i $dbname($i) + execsql { + CREATE TABLE t1(a,b); + BEGIN; + INSERT INTO t1 VALUES(1,2); + } db$i + } {} +} + +# Finish the transactions +# +for {set i 0} {$i<$N} {incr i} { + do_test manydb-2.$i { + execsql { + COMMIT; + SELECT * FROM t1; + } db$i + } {1 2} +} + + +# Close the databases and erase the files. +# +for {set i 0} {$i<$N} {incr i} { + do_test manydb-3.$i { + db$i close + forcedelete $dbname($i) + } {} +} + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mem5.test b/components/external/SQLite-3.8.1/test/mem5.test new file mode 100644 index 0000000000000000000000000000000000000000..6365f1c64b290da445b3f5cb08bf785decfa7921 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mem5.test @@ -0,0 +1,66 @@ +# 2011 March 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests of the mem5 allocation subsystem. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !mem5 { + finish_test + return +} + +# The tests in this file configure the lookaside allocator after a +# connection is opened. This will not work if there is any "presql" +# configured (SQL run within the [sqlite3] wrapper in tester.tcl). +if {[info exists ::G(perm:presql)]} { + finish_test + return +} + +do_test mem5-1.1 { + catch {db close} + sqlite3_shutdown + sqlite3_config_heap 25000000 0 + sqlite3_config_lookaside 0 0 + sqlite3_initialize +} {SQLITE_OK} + +# try with min request size = 2^30 +do_test mem5-1.2 { + catch {db close} + sqlite3_shutdown + sqlite3_config_heap 1 1073741824 + sqlite3_config_lookaside 0 0 + sqlite3_initialize +} {SQLITE_NOMEM} + +# try with min request size = 2^30+1 +# previously this was causing the memsys5Log() func to infinitely loop. +do_test mem5-1.3 { + catch {db close} + sqlite3_shutdown + sqlite3_config_heap 1 1073741825 + sqlite3_config_lookaside 0 0 + sqlite3_initialize +} {SQLITE_NOMEM} + +do_test mem5-1.4 { + catch {db close} + sqlite3_shutdown + sqlite3_config_heap 0 0 + sqlite3_config_lookaside 0 0 + sqlite3_initialize +} {SQLITE_OK} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/memdb.test b/components/external/SQLite-3.8.1/test/memdb.test new file mode 100644 index 0000000000000000000000000000000000000000..802fb1a5c4c60e4dc99ef08fffbc0ad808d072c6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/memdb.test @@ -0,0 +1,432 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is in-memory database backend. +# +# $Id: memdb.test,v 1.19 2009/05/18 16:04:38 danielk1977 Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable memorydb { + +# In the following sequence of tests, compute the MD5 sum of the content +# of a table, make lots of modifications to that table, then do a rollback. +# Verify that after the rollback, the MD5 checksum is unchanged. +# +# These tests were browed from trans.tcl. +# +do_test memdb-1.1 { + db close + sqlite3 db :memory: + # sqlite3 db test.db + execsql { + BEGIN; + CREATE TABLE t3(x TEXT); + INSERT INTO t3 VALUES(randstr(10,400)); + INSERT INTO t3 VALUES(randstr(10,400)); + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + COMMIT; + SELECT count(*) FROM t3; + } +} {1024} + +# The following procedure computes a "signature" for table "t3". If +# T3 changes in any way, the signature should change. +# +# This is used to test ROLLBACK. We gather a signature for t3, then +# make lots of changes to t3, then rollback and take another signature. +# The two signatures should be the same. +# +proc signature {{fn {}}} { + set rx [db eval {SELECT x FROM t3}] + # set r1 [md5 $rx\n] + if {$fn!=""} { + # set fd [open $fn w] + # puts $fd $rx + # close $fd + } + # set r [db eval {SELECT count(*), md5sum(x) FROM t3}] + # puts "SIG($fn)=$r1" + return [list [string length $rx] $rx] +} + +# Do rollbacks. Make sure the signature does not change. +# +set limit 10 +for {set i 2} {$i<=$limit} {incr i} { + set ::sig [signature one] + # puts "sig=$sig" + set cnt [lindex $::sig 0] + if {$i%2==0} { + execsql {PRAGMA synchronous=FULL} + } else { + execsql {PRAGMA synchronous=NORMAL} + } + do_test memdb-1.$i.1-$cnt { + execsql { + BEGIN; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + ROLLBACK; + } + set sig2 [signature two] + } $sig + # puts "sig2=$sig2" + # if {$sig2!=$sig} exit + do_test memdb-1.$i.2-$cnt { + execsql { + BEGIN; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + ROLLBACK; + } + signature + } $sig + if {$i<$limit} { + do_test memdb-1.$i.9-$cnt { + execsql { + INSERT INTO t3 SELECT randstr(10,400) FROM t3 WHERE random()%10==0; + } + } {} + } + set ::pager_old_format 0 +} + +integrity_check memdb-2.1 + +do_test memdb-3.1 { + execsql { + CREATE TABLE t4(a,b,c,d); + BEGIN; + INSERT INTO t4 VALUES(1,2,3,4); + SELECT * FROM t4; + } +} {1 2 3 4} +do_test memdb-3.2 { + execsql { + SELECT name FROM sqlite_master WHERE type='table'; + } +} {t3 t4} +do_test memdb-3.3 { + execsql { + DROP TABLE t4; + SELECT name FROM sqlite_master WHERE type='table'; + } +} {t3} +do_test memdb-3.4 { + execsql { + ROLLBACK; + SELECT name FROM sqlite_master WHERE type='table'; + } +} {t3 t4} + +# Create tables for the first group of tests. +# +do_test memdb-4.0 { + execsql { + CREATE TABLE t1(a, b, c, UNIQUE(a,b)); + CREATE TABLE t2(x); + SELECT c FROM t1 ORDER BY c; + } +} {} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# conf The conflict resolution algorithm on the BEGIN statement +# cmd An INSERT or REPLACE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "c" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t2 +# +foreach {i conf cmd t0 t1 t2} { + 1 {} INSERT 1 {} 1 + 2 {} {INSERT OR IGNORE} 0 3 1 + 3 {} {INSERT OR REPLACE} 0 4 1 + 4 {} REPLACE 0 4 1 + 5 {} {INSERT OR FAIL} 1 {} 1 + 6 {} {INSERT OR ABORT} 1 {} 1 + 7 {} {INSERT OR ROLLBACK} 1 {} {} +} { + + # All tests after test 1 depend on conflict resolution. So end the + # loop if that is not available in this build. + ifcapable !conflict {if {$i>1} break} + + do_test memdb-4.$i { + if {$conf!=""} {set conf "ON CONFLICT $conf"} + set r0 [catch {execsql [subst { + DELETE FROM t1; + DELETE FROM t2; + INSERT INTO t1 VALUES(1,2,3); + BEGIN $conf; + INSERT INTO t2 VALUES(1); + $cmd INTO t1 VALUES(1,2,4); + }]} r1] + catch {execsql {COMMIT}} + if {$r0} {set r1 {}} {set r1 [execsql {SELECT c FROM t1}]} + set r2 [execsql {SELECT x FROM t2}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +do_test memdb-5.0 { + execsql { + DROP TABLE t2; + DROP TABLE t3; + CREATE TABLE t2(a,b,c); + INSERT INTO t2 VALUES(1,2,1); + INSERT INTO t2 VALUES(2,3,2); + INSERT INTO t2 VALUES(3,4,1); + INSERT INTO t2 VALUES(4,5,4); + SELECT c FROM t2 ORDER BY b; + CREATE TABLE t3(x); + INSERT INTO t3 VALUES(1); + } +} {1 2 1 4} + +# Six columns of configuration data as follows: +# +# i The reference number of the test +# conf1 The conflict resolution algorithm on the UNIQUE constraint +# conf2 The conflict resolution algorithm on the BEGIN statement +# cmd An UPDATE command to execute against table t1 +# t0 True if there is an error from $cmd +# t1 Content of "b" column of t1 assuming no error in $cmd +# t2 Content of "x" column of t3 +# +foreach {i conf1 conf2 cmd t0 t1 t2} { + 1 {} {} UPDATE 1 {6 7 8 9} 1 + 2 REPLACE {} UPDATE 0 {7 6 9} 1 + 3 IGNORE {} UPDATE 0 {6 7 3 9} 1 + 4 FAIL {} UPDATE 1 {6 7 3 4} 1 + 5 ABORT {} UPDATE 1 {1 2 3 4} 1 + 6 ROLLBACK {} UPDATE 1 {1 2 3 4} 0 + 7 REPLACE {} {UPDATE OR IGNORE} 0 {6 7 3 9} 1 + 8 IGNORE {} {UPDATE OR REPLACE} 0 {7 6 9} 1 + 9 FAIL {} {UPDATE OR IGNORE} 0 {6 7 3 9} 1 + 10 ABORT {} {UPDATE OR REPLACE} 0 {7 6 9} 1 + 11 ROLLBACK {} {UPDATE OR IGNORE} 0 {6 7 3 9} 1 + 12 {} {} {UPDATE OR IGNORE} 0 {6 7 3 9} 1 + 13 {} {} {UPDATE OR REPLACE} 0 {7 6 9} 1 + 14 {} {} {UPDATE OR FAIL} 1 {6 7 3 4} 1 + 15 {} {} {UPDATE OR ABORT} 1 {1 2 3 4} 1 + 16 {} {} {UPDATE OR ROLLBACK} 1 {1 2 3 4} 0 +} { + # All tests after test 1 depend on conflict resolution. So end the + # loop if that is not available in this build. + ifcapable !conflict { + if {$i>1} break + } + + if {$t0} {set t1 {column a is not unique}} + do_test memdb-5.$i { + if {$conf1!=""} {set conf1 "ON CONFLICT $conf1"} + if {$conf2!=""} {set conf2 "ON CONFLICT $conf2"} + set r0 [catch {execsql " + DROP TABLE t1; + CREATE TABLE t1(a,b,c, UNIQUE(a) $conf1); + INSERT INTO t1 SELECT * FROM t2; + UPDATE t3 SET x=0; + BEGIN $conf2; + $cmd t3 SET x=1; + $cmd t1 SET b=b*2; + $cmd t1 SET a=c+5; + "} r1] + catch {execsql {COMMIT}} + if {!$r0} {set r1 [execsql {SELECT a FROM t1 ORDER BY b}]} + set r2 [execsql {SELECT x FROM t3}] + list $r0 $r1 $r2 + } [list $t0 $t1 $t2] +} + +do_test memdb-6.1 { + execsql { + SELECT * FROM t2; + } +} {1 2 1 2 3 2 3 4 1 4 5 4} +do_test memdb-6.2 { + execsql { + BEGIN; + DROP TABLE t2; + SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1; + } +} {t1 t3 t4} +do_test memdb-6.3 { + execsql { + ROLLBACK; + SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1; + } +} {t1 t2 t3 t4} +do_test memdb-6.4 { + execsql { + SELECT * FROM t2; + } +} {1 2 1 2 3 2 3 4 1 4 5 4} +ifcapable compound { +do_test memdb-6.5 { + execsql { + SELECT a FROM t2 UNION SELECT b FROM t2 ORDER BY 1; + } +} {1 2 3 4 5} +} ;# ifcapable compound +do_test memdb-6.6 { + execsql { + CREATE INDEX i2 ON t2(c); + SELECT a FROM t2 ORDER BY c; + } +} {1 3 2 4} +do_test memdb-6.6 { + execsql { + SELECT a FROM t2 ORDER BY c DESC; + } +} {4 2 3 1} +do_test memdb-6.7 { + execsql { + BEGIN; + CREATE TABLE t5(x,y); + INSERT INTO t5 VALUES(1,2); + SELECT * FROM t5; + } +} {1 2} +do_test memdb-6.8 { + execsql { + SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1; + } +} {t1 t2 t3 t4 t5} +do_test memdb-6.9 { + execsql { + ROLLBACK; + SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1; + } +} {t1 t2 t3 t4} +do_test memdb-6.10 { + execsql { + CREATE TABLE t5(x PRIMARY KEY, y UNIQUE); + SELECT * FROM t5; + } +} {} +do_test memdb-6.11 { + execsql { + SELECT * FROM t5 ORDER BY y DESC; + } +} {} + +ifcapable conflict { + do_test memdb-6.12 { + execsql { + INSERT INTO t5 VALUES(1,2); + INSERT INTO t5 VALUES(3,4); + REPLACE INTO t5 VALUES(1,4); + SELECT rowid,* FROM t5; + } + } {3 1 4} + do_test memdb-6.13 { + execsql { + DELETE FROM t5 WHERE x>5; + SELECT * FROM t5; + } + } {1 4} + do_test memdb-6.14 { + execsql { + DELETE FROM t5 WHERE y<3; + SELECT * FROM t5; + } + } {1 4} +} + +do_test memdb-6.15 { + execsql { + DELETE FROM t5 WHERE x>0; + SELECT * FROM t5; + } +} {} + +ifcapable subquery&&vtab { + do_test memdb-7.1 { + load_static_extension db wholenumber + execsql { + CREATE TABLE t6(x); + CREATE VIRTUAL TABLE nums USING wholenumber; + INSERT INTO t6 SELECT value FROM nums WHERE value BETWEEN 1 AND 256; + SELECT count(*) FROM (SELECT DISTINCT x FROM t6); + } + } {256} + for {set i 1} {$i<=256} {incr i} { + do_test memdb-7.2.$i { + execsql "DELETE FROM t6 WHERE x=\ + (SELECT x FROM t6 ORDER BY random() LIMIT 1)" + execsql {SELECT count(*) FROM t6} + } [expr {256-$i}] + } +} + +# Ticket #1524 +# +do_test memdb-8.1 { + db close + sqlite3 db {:memory:} + execsql { + PRAGMA auto_vacuum=TRUE; + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(randstr(5000,6000)); + INSERT INTO t1 VALUES(randstr(5000,6000)); + INSERT INTO t1 VALUES(randstr(5000,6000)); + INSERT INTO t1 VALUES(randstr(5000,6000)); + INSERT INTO t1 VALUES(randstr(5000,6000)); + SELECT count(*) FROM t1; + } +} 5 +do_test memdb-8.2 { + execsql { + DELETE FROM t1; + SELECT count(*) FROM t1; + } +} 0 + +# Test that auto-vacuum works with in-memory databases. +# +ifcapable autovacuum { + do_test memdb-9.1 { + db close + sqlite3 db test.db + db cache size 0 + execsql { + PRAGMA auto_vacuum = full; + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(randstr(1000,1000)); + INSERT INTO t1 VALUES(randstr(1000,1000)); + INSERT INTO t1 VALUES(randstr(1000,1000)); + } + set memused [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + set pgovfl [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 1] + execsql { DELETE FROM t1 } + set memused2 [lindex [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] 1] + expr {($memused2 + 2048 < $memused) || $pgovfl==0} + } {1} +} + +} ;# ifcapable memorydb + +finish_test diff --git a/components/external/SQLite-3.8.1/test/memleak.test b/components/external/SQLite-3.8.1/test/memleak.test new file mode 100644 index 0000000000000000000000000000000000000000..a24a901f50748e743dd202daf1ae8fd4118fc74c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/memleak.test @@ -0,0 +1,97 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs all tests. +# +# $Id: memleak.test,v 1.10 2007/03/30 17:17:52 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +rename finish_test memleak_finish_test +proc finish_test {} { + catch {db close} + memleak_check +} + +if {[file exists ./sqlite_test_count]} { + set COUNT [exec cat ./sqlite_test_count] +} else { + set COUNT 3 +} + +# LeakList will hold a list of the number of unfreed mallocs after +# each round of the test. This number should be constant. If it +# grows, it may mean there is a memory leak in the library. +# +set LeakList {} + +set EXCLUDE { + all.test + quick.test + misuse.test + memleak.test + btree2.test + async.test + async2.test + trans.test + crash.test + autovacuum_crash.test +} +# Test files btree2.test and btree4.test don't work if the +# SQLITE_DEFAULT_AUTOVACUUM macro is defined to true (because they depend +# on tables being allocated starting at page 2). +# +ifcapable default_autovacuum { + lappend EXCLUDE btree2.test + lappend EXCLUDE btree4.test +} + +if {[sqlite3 -has-codec]} { + # lappend EXCLUDE +} +if {[llength $argv]>0} { + set FILELIST $argv + set argv {} +} else { + set FILELIST [lsort -dictionary [glob $testdir/*.test]] +} + +foreach testfile $FILELIST { + set tail [file tail $testfile] + if {[lsearch -exact $EXCLUDE $tail]>=0} continue + set LeakList {} + for {set COUNTER 0} {$COUNTER<$COUNT} {incr COUNTER} { + source $testfile + if {[info exists Leak]} { + lappend LeakList $Leak + } + } + if {$LeakList!=""} { + puts -nonewline memory-leak-test-$tail... + incr_ntest + foreach x $LeakList { + if {$x!=[lindex $LeakList 0]} { + puts " failed! ($LeakList)" + fail_test memory-leak-test-$tail + break + } + } + puts " Ok" + } +} +memleak_finish_test + +# Run the malloc tests and the misuse test after memory leak detection. +# Both tests leak memory. +# +#catch {source $testdir/misuse.test} +#catch {source $testdir/malloc.test} + +memleak_finish_test diff --git a/components/external/SQLite-3.8.1/test/memsubsys1.test b/components/external/SQLite-3.8.1/test/memsubsys1.test new file mode 100644 index 0000000000000000000000000000000000000000..76b79d00f6484bd9cb0e08acc8067a942df11886 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/memsubsys1.test @@ -0,0 +1,311 @@ +# 2008 June 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests of the memory allocation subsystem +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +sqlite3_reset_auto_extension + +# This test assumes that no page-cache or scratch buffers are installed +# by default when a new database connection is opened. As a result, it +# will not work with the "memsubsys1" permutation. +# +if {[permutation] == "memsubsys1"} { + finish_test + return +} + +# This procedure constructs a new database in test.db. It fills +# this database with many small records (enough to force multiple +# rebalance operations in the btree-layer and to require a large +# page cache), verifies correct results, then returns. +# +proc build_test_db {testname pragmas} { + catch {db close} + forcedelete test.db test.db-journal + sqlite3 db test.db + sqlite3_db_config_lookaside db 0 0 0 + db eval $pragmas + db eval { + CREATE TABLE t1(x, y); + CREATE TABLE t2(a, b); + CREATE INDEX i1 ON t1(x,y); + INSERT INTO t1 VALUES(1, 100); + INSERT INTO t1 VALUES(2, 200); + } + for {set i 2} {$i<5000} {incr i $i} { + db eval {INSERT INTO t2 SELECT * FROM t1} + db eval {INSERT INTO t1 SELECT a+$i, a+b*100 FROM t2} + db eval {DELETE FROM t2} + } + do_test $testname.1 { + db eval {SELECT count(*) FROM t1} + } 8192 + integrity_check $testname.2 +} + +# Reset all of the highwater marks. +# +proc reset_highwater_marks {} { + sqlite3_status SQLITE_STATUS_MEMORY_USED 1 + sqlite3_status SQLITE_STATUS_MALLOC_SIZE 1 + sqlite3_status SQLITE_STATUS_PAGECACHE_USED 1 + sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 1 + sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 1 + sqlite3_status SQLITE_STATUS_SCRATCH_USED 1 + sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 1 + sqlite3_status SQLITE_STATUS_SCRATCH_SIZE 1 + sqlite3_status SQLITE_STATUS_PARSER_STACK 1 +} + +set xtra_size 290 + +# Test 1: Both PAGECACHE and SCRATCH are shut down. +# +db close +sqlite3_shutdown +sqlite3_config_lookaside 0 0 +sqlite3_initialize +reset_highwater_marks +build_test_db memsubsys1-1 {PRAGMA page_size=1024} +do_test memsubsys1-1.3 { + set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2] +} 0 +do_test memsubsys1-1.4 { + set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2] +} 0 +set max_pagecache [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2] +#show_memstats + +# Test 2: Activate PAGECACHE with 20 pages +# +db close +sqlite3_shutdown +sqlite3_config_pagecache [expr 1024+$xtra_size] 20 +sqlite3_initialize +reset_highwater_marks +build_test_db memsubsys1-2 {PRAGMA page_size=1024; PRAGMA mmap_size=0} +#show_memstats +set MEMORY_MANAGEMENT $sqlite_options(memorymanage) +ifcapable !malloc_usable_size { + do_test memsubsys1-2.3 { + set pg_ovfl [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2] + } [expr ($TEMP_STORE>1 || $MEMORY_MANAGEMENT==0)*1024] +} +do_test memsubsys1-2.4 { + set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2] +} 20 +do_test memsubsys1-2.5 { + set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2] +} 0 + +# Test 3: Activate PAGECACHE with 20 pages but use the wrong page size +# so that PAGECACHE is not used. +# +db close +sqlite3_shutdown +sqlite3_config_pagecache [expr 512+$xtra_size] 20 +sqlite3_initialize +reset_highwater_marks +build_test_db memsubsys1-3.1 {PRAGMA page_size=1024} +#show_memstats +do_test memsubsys1-3.1.3 { + set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2] +} 0 +do_test memsubsys1-3.1.4 { + set overflow [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2] +} $max_pagecache +do_test memsubsys1-3.1.5 { + set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2] +} 0 +db close +sqlite3_shutdown +sqlite3_config_pagecache [expr 2048+$xtra_size] 20 +sqlite3_initialize +reset_highwater_marks +build_test_db memsubsys1-3.2 {PRAGMA page_size=2048} +#show_memstats +do_test memsubsys1-3.2.3 { + db eval {PRAGMA page_size} +} 2048 +do_test memsubsys1-3.2.4 { + set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2] +} 20 +do_test memsubsys1-3.2.5 { + set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2] +} 0 + +# Test 4: Activate both PAGECACHE and SCRATCH. +# +db close +sqlite3_shutdown +sqlite3_config_pagecache [expr 1024+$xtra_size] 50 +sqlite3_config_scratch 6000 2 +sqlite3_initialize +reset_highwater_marks +build_test_db memsubsys1-4 {PRAGMA page_size=1024} +#show_memstats +do_test memsubsys1-4.3 { + set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2] + expr {$pg_used>=45 && $pg_used<=50} +} 1 +do_test memsubsys1-4.4 { + set pg_ovfl [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2] +} 0 +do_test memsubsys1-4.5 { + set maxreq [lindex [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0] 2] + expr {$maxreq<7000} +} 1 +do_test memsubsys1-4.6 { + set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2] +} 1 + +# Test 5: Activate both PAGECACHE and SCRATCH. But make the page size +# such that the SCRATCH allocations are too small. +# +db close +sqlite3_shutdown +sqlite3_config_pagecache [expr 4096+$xtra_size] 24 +sqlite3_config_scratch 6000 2 +sqlite3_initialize +reset_highwater_marks +build_test_db memsubsys1-5 {PRAGMA page_size=4096} +#show_memstats +do_test memsubsys1-5.3 { + set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2] +} 24 +do_test memsubsys1-5.4 { + set maxreq [lindex [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0] 2] + expr {$maxreq>4096} +} 1 +do_test memsubsys1-5.5 { + set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2] +} 0 +do_test memsubsys1-5.6 { + set s_ovfl [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2] + expr {$s_ovfl>6000} +} 1 + +# Test 6: Activate both PAGECACHE and SCRATCH with a 4k page size. +# Make it so that SCRATCH is large enough +# +db close +sqlite3_shutdown +sqlite3_config_pagecache [expr 4096+$xtra_size] 24 +sqlite3_config_scratch 25300 1 +sqlite3_initialize +reset_highwater_marks +build_test_db memsubsys1-6 {PRAGMA page_size=4096} +#show_memstats +do_test memsubsys1-6.3 { + set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2] +} 24 +#do_test memsubsys1-6.4 { +# set maxreq [lindex [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0] 2] +# expr {$maxreq>4096 && $maxreq<=(4096+$xtra_size)} +#} 1 +do_test memsubsys1-6.5 { + set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2] +} 1 +do_test memsubsys1-6.6 { + set s_ovfl [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2] +} 0 + +# Test 7: Activate both PAGECACHE and SCRATCH with a 4k page size. +# Set cache_size small so that no PAGECACHE overflow occurs. Verify +# that maximum allocation size is small. +# +db close +sqlite3_shutdown +sqlite3_config_pagecache [expr 4096+$xtra_size] 24 +sqlite3_config_scratch 25300 1 +sqlite3_initialize +reset_highwater_marks +build_test_db memsubsys1-7 { + PRAGMA page_size=4096; + PRAGMA cache_size=10; + PRAGMA temp_store=memory; +} +#show_memstats +do_test memsubsys1-7.3 { + set pg_used [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 2] + expr {$pg_used<24} +} 1 +do_test memsubsys1-7.4 { + set pg_ovfl [lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] 2] +} 0 +do_test memsubsys1-7.5 { + set maxreq [lindex [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0] 2] + expr {$maxreq<4100} +} 1 +do_test memsubsys1-7.6 { + set s_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2] +} 1 +do_test memsubsys1-7.7 { + set s_ovfl [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2] +} 0 + +# Test 8: Disable PAGECACHE. Make available SCRATCH zero. Verify that +# the SCRATCH overflow logic works. +# +db close +sqlite3_shutdown +sqlite3_config_pagecache 0 0 +sqlite3_config_scratch 25000 0 +sqlite3_initialize +reset_highwater_marks +do_test memsubsys1-8.1 { + set pg_used [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] 2] +} 0 +do_test memsubsys1-8.2 { + set s_ovfl [lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2] +} 0 +do_test memsubsys1-8.3 { + sqlite3 db :memory: + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(zeroblob(400)); + INSERT INTO t1 VALUES(zeroblob(400)); + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + } + expr {[lindex [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] 2]>0} +} 1 +db close +sqlite3_shutdown +sqlite3_config_memstatus 0 +sqlite3_initialize +do_test memsubsys1-8.4 { + sqlite3 db :memory: + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(zeroblob(400)); + INSERT INTO t1 VALUES(zeroblob(400)); + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + SELECT rowid FROM t1; + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} + + +db close +sqlite3_shutdown +sqlite3_config_memstatus 1 +sqlite3_config_pagecache 0 0 +sqlite3_config_scratch 0 0 +sqlite3_config_lookaside 100 500 +sqlite3_initialize +autoinstall_test_functions +finish_test diff --git a/components/external/SQLite-3.8.1/test/memsubsys2.test b/components/external/SQLite-3.8.1/test/memsubsys2.test new file mode 100644 index 0000000000000000000000000000000000000000..a40f4e4f03d44b518288725eac8767cc868619c6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/memsubsys2.test @@ -0,0 +1,173 @@ +# 2008 June 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests of the memory allocation subsystem. +# +# $Id: memsubsys2.test,v 1.2 2008/08/12 15:21:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +sqlite3_reset_auto_extension + +# This procedure constructs a new database in test.db. It fills +# this database with many small records (enough to force multiple +# rebalance operations in the btree-layer and to require a large +# page cache), verifies correct results, then returns. +# +proc build_test_db {testname pragmas} { + catch {db close} + forcedelete test.db test.db-journal + sqlite3 db test.db + db eval $pragmas + db eval { + CREATE TABLE t1(x, y); + CREATE TABLE t2(a, b); + CREATE INDEX i1 ON t1(x,y); + INSERT INTO t1 VALUES(1, 100); + INSERT INTO t1 VALUES(2, 200); + } + for {set i 2} {$i<5000} {incr i $i} { + db eval {INSERT INTO t2 SELECT * FROM t1} + db eval {INSERT INTO t1 SELECT a+$i, a+b*100 FROM t2} + db eval {DELETE FROM t2} + } + do_test $testname.1 { + db eval {SELECT count(*) FROM t1} + } 8192 + integrity_check $testname.2 +} + +# Reset all of the highwater marks. +# +proc reset_highwater_marks {} { + sqlite3_status SQLITE_STATUS_MEMORY_USED 1 + sqlite3_status SQLITE_STATUS_MALLOC_SIZE 1 + sqlite3_status SQLITE_STATUS_PAGECACHE_USED 1 + sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 1 + sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 1 + sqlite3_status SQLITE_STATUS_SCRATCH_USED 1 + sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 1 + sqlite3_status SQLITE_STATUS_SCRATCH_SIZE 1 + sqlite3_status SQLITE_STATUS_PARSER_STACK 1 +} + +# Test 1: Verify that calling sqlite3_malloc(0) returns a NULL +# pointer. +# +set highwater [sqlite3_memory_highwater 0] +do_test memsubsys2-1.1 { + sqlite3_malloc 0 +} {0} +do_test memsubsys2-1.2 { + sqlite3_memory_highwater 0 +} $highwater + + +# Test 2: Verify that the highwater mark increases after a large +# allocation. +# +sqlite3_memory_highwater 1 +set highwater [sqlite3_memory_highwater 0] +do_test memsubsys2-2.1 { + sqlite3_free [set x [sqlite3_malloc 100000]] + expr {$x!="0"} +} {1} +do_test memsubsys2-2.2 { + expr {[sqlite3_memory_highwater 0]>=[sqlite3_memory_used]+$highwater} +} {1} + +# Test 3: Verify that turning of memstatus disables the statistics +# tracking. +# +db close +sqlite3_shutdown +sqlite3_config_memstatus 0 +sqlite3_initialize +reset_highwater_marks +set highwater [sqlite3_memory_highwater 0] +do_test memsubsys2-3.1 { + set highwater +} {0} +do_test memsubsys2-3.2 { + sqlite3_malloc 0 +} {0} +do_test memsubsys2-3.3 { + sqlite3_memory_highwater 0 +} {0} +do_test memsubsys2-3.4 { + sqlite3_memory_used +} {0} +do_test memsubsys2-3.5 { + set ::allocation [sqlite3_malloc 100000] + expr {$::allocation!="0"} +} {1} +do_test memsubsys2-3.6 { + sqlite3_memory_highwater 0 +} {0} +do_test memsubsys2-3.7 { + sqlite3_memory_used +} {0} +do_test memsubsys2-3.8 { + sqlite3_free $::allocation +} {} +do_test memsubsys2-3.9 { + sqlite3_free 0 +} {} + + +# Test 4: Verify that turning on memstatus reenables the statistics +# tracking. +# +sqlite3_shutdown +sqlite3_config_memstatus 1 +sqlite3_initialize +reset_highwater_marks +set highwater [sqlite3_memory_highwater 0] +do_test memsubsys2-4.1 { + set highwater +} {0} +do_test memsubsys2-4.2 { + sqlite3_malloc 0 +} {0} +do_test memsubsys2-4.3 { + sqlite3_memory_highwater 0 +} {0} +do_test memsubsys2-4.4 { + sqlite3_memory_used +} {0} +do_test memsubsys2-4.5 { + set ::allocation [sqlite3_malloc 100000] + expr {$::allocation!="0"} +} {1} +do_test memsubsys2-4.6 { + expr {[sqlite3_memory_highwater 0]>=100000} +} {1} +do_test memsubsys2-4.7 { + expr {[sqlite3_memory_used]>=100000} +} {1} +do_test memsubsys2-4.8 { + sqlite3_free $::allocation +} {} +do_test memsubsys2-4.9 { + sqlite3_free 0 +} {} +do_test memsubsys2-4.10 { + expr {[sqlite3_memory_highwater 0]>=100000} +} {1} +do_test memsubsys2-4.11 { + sqlite3_memory_used +} {0} + + + + +autoinstall_test_functions +finish_test diff --git a/components/external/SQLite-3.8.1/test/minmax.test b/components/external/SQLite-3.8.1/test/minmax.test new file mode 100644 index 0000000000000000000000000000000000000000..fb9bbb383a74e2427a35fe7ee221ba151626a35d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/minmax.test @@ -0,0 +1,632 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing SELECT statements that contain +# aggregate min() and max() functions and which are handled as +# as a special case. +# +# $Id: minmax.test,v 1.21 2008/07/08 18:05:26 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix minmax + +do_test minmax-1.0 { + execsql { + BEGIN; + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(1,1); + INSERT INTO t1 VALUES(2,2); + INSERT INTO t1 VALUES(3,2); + INSERT INTO t1 VALUES(4,3); + INSERT INTO t1 VALUES(5,3); + INSERT INTO t1 VALUES(6,3); + INSERT INTO t1 VALUES(7,3); + INSERT INTO t1 VALUES(8,4); + INSERT INTO t1 VALUES(9,4); + INSERT INTO t1 VALUES(10,4); + INSERT INTO t1 VALUES(11,4); + INSERT INTO t1 VALUES(12,4); + INSERT INTO t1 VALUES(13,4); + INSERT INTO t1 VALUES(14,4); + INSERT INTO t1 VALUES(15,4); + INSERT INTO t1 VALUES(16,5); + INSERT INTO t1 VALUES(17,5); + INSERT INTO t1 VALUES(18,5); + INSERT INTO t1 VALUES(19,5); + INSERT INTO t1 VALUES(20,5); + COMMIT; + SELECT DISTINCT y FROM t1 ORDER BY y; + } +} {1 2 3 4 5} + +do_test minmax-1.1 { + set sqlite_search_count 0 + execsql {SELECT min(x) FROM t1} +} {1} +do_test minmax-1.2 { + set sqlite_search_count +} {19} +do_test minmax-1.3 { + set sqlite_search_count 0 + execsql {SELECT max(x) FROM t1} +} {20} +do_test minmax-1.4 { + set sqlite_search_count +} {19} +do_test minmax-1.5 { + execsql {CREATE INDEX t1i1 ON t1(x)} + set sqlite_search_count 0 + execsql {SELECT min(x) FROM t1} +} {1} +do_test minmax-1.6 { + set sqlite_search_count +} {1} +do_test minmax-1.7 { + set sqlite_search_count 0 + execsql {SELECT max(x) FROM t1} +} {20} +do_test minmax-1.8 { + set sqlite_search_count +} {0} +do_test minmax-1.9 { + set sqlite_search_count 0 + execsql {SELECT max(y) FROM t1} +} {5} +do_test minmax-1.10 { + set sqlite_search_count +} {19} + +do_test minmax-1.21 { + execsql {SELECT min(x) FROM t1 WHERE x=5} +} {5} +do_test minmax-1.22 { + execsql {SELECT min(x) FROM t1 WHERE x>=5} +} {5} +do_test minmax-1.23 { + execsql {SELECT min(x) FROM t1 WHERE x>=4.5} +} {5} +do_test minmax-1.24 { + execsql {SELECT min(x) FROM t1 WHERE x<4.5} +} {1} + +do_test minmax-2.0 { + execsql { + CREATE TABLE t2(a INTEGER PRIMARY KEY, b); + INSERT INTO t2 SELECT * FROM t1; + } + set sqlite_search_count 0 + execsql {SELECT min(a) FROM t2} +} {1} +do_test minmax-2.1 { + set sqlite_search_count +} {0} +do_test minmax-2.2 { + set sqlite_search_count 0 + execsql {SELECT max(a) FROM t2} +} {20} +do_test minmax-2.3 { + set sqlite_search_count +} {0} + +do_test minmax-3.0 { + ifcapable subquery { + execsql {INSERT INTO t2 VALUES((SELECT max(a) FROM t2)+1,999)} + } else { + db function max_a_t2 {execsql {SELECT max(a) FROM t2}} + execsql {INSERT INTO t2 VALUES(max_a_t2()+1,999)} + } + set sqlite_search_count 0 + execsql {SELECT max(a) FROM t2} +} {21} +do_test minmax-3.1 { + set sqlite_search_count +} {0} +do_test minmax-3.2 { + ifcapable subquery { + execsql {INSERT INTO t2 VALUES((SELECT max(a) FROM t2)+1,999)} + } else { + db function max_a_t2 {execsql {SELECT max(a) FROM t2}} + execsql {INSERT INTO t2 VALUES(max_a_t2()+1,999)} + } + set sqlite_search_count 0 + ifcapable subquery { + execsql { SELECT b FROM t2 WHERE a=(SELECT max(a) FROM t2) } + } else { + execsql { SELECT b FROM t2 WHERE a=max_a_t2() } + } +} {999} +do_test minmax-3.3 { + set sqlite_search_count +} {0} + +ifcapable {compound && subquery} { + do_test minmax-4.1 { + execsql { + SELECT coalesce(min(x+0),-1), coalesce(max(x+0),-1) FROM + (SELECT * FROM t1 UNION SELECT NULL as 'x', NULL as 'y') + } + } {1 20} + do_test minmax-4.2 { + execsql { + SELECT y, coalesce(sum(x),0) FROM + (SELECT null AS x, y+1 AS y FROM t1 UNION SELECT * FROM t1) + GROUP BY y ORDER BY y; + } + } {1 1 2 5 3 22 4 92 5 90 6 0} + do_test minmax-4.3 { + execsql { + SELECT y, count(x), count(*) FROM + (SELECT null AS x, y+1 AS y FROM t1 UNION SELECT * FROM t1) + GROUP BY y ORDER BY y; + } + } {1 1 1 2 2 3 3 4 5 4 8 9 5 5 6 6 0 1} +} ;# ifcapable compound + +# Make sure the min(x) and max(x) optimizations work on empty tables +# including empty tables with indices. Ticket #296. +# +do_test minmax-5.1 { + execsql { + CREATE TABLE t3(x INTEGER UNIQUE NOT NULL); + SELECT coalesce(min(x),999) FROM t3; + } +} {999} +do_test minmax-5.2 { + execsql { + SELECT coalesce(min(rowid),999) FROM t3; + } +} {999} +do_test minmax-5.3 { + execsql { + SELECT coalesce(max(x),999) FROM t3; + } +} {999} +do_test minmax-5.4 { + execsql { + SELECT coalesce(max(rowid),999) FROM t3; + } +} {999} +do_test minmax-5.5 { + execsql { + SELECT coalesce(max(rowid),999) FROM t3 WHERE rowid<25; + } +} {999} + +# Make sure the min(x) and max(x) optimizations work when there +# is a LIMIT clause. Ticket #396. +# +do_test minmax-6.1 { + execsql { + SELECT min(a) FROM t2 LIMIT 1 + } +} {1} +do_test minmax-6.2 { + execsql { + SELECT max(a) FROM t2 LIMIT 3 + } +} {22} +do_test minmax-6.3 { + execsql { + SELECT min(a) FROM t2 LIMIT 0,100 + } +} {1} +do_test minmax-6.4 { + execsql { + SELECT max(a) FROM t2 LIMIT 1,100 + } +} {} +do_test minmax-6.5 { + execsql { + SELECT min(x) FROM t3 LIMIT 1 + } +} {{}} +do_test minmax-6.6 { + execsql { + SELECT max(x) FROM t3 LIMIT 0 + } +} {} +do_test minmax-6.7 { + execsql { + SELECT max(a) FROM t2 LIMIT 0 + } +} {} + +# Make sure the max(x) and min(x) optimizations work for nested +# queries. Ticket #587. +# +do_test minmax-7.1 { + execsql { + SELECT max(x) FROM t1; + } +} 20 +ifcapable subquery { + do_test minmax-7.2 { + execsql { + SELECT * FROM (SELECT max(x) FROM t1); + } + } 20 +} +do_test minmax-7.3 { + execsql { + SELECT min(x) FROM t1; + } +} 1 +ifcapable subquery { + do_test minmax-7.4 { + execsql { + SELECT * FROM (SELECT min(x) FROM t1); + } + } 1 +} + +# Make sure min(x) and max(x) work correctly when the datatype is +# TEXT instead of NUMERIC. Ticket #623. +# +do_test minmax-8.1 { + execsql { + CREATE TABLE t4(a TEXT); + INSERT INTO t4 VALUES('1234'); + INSERT INTO t4 VALUES('234'); + INSERT INTO t4 VALUES('34'); + SELECT min(a), max(a) FROM t4; + } +} {1234 34} +do_test minmax-8.2 { + execsql { + CREATE TABLE t5(a INTEGER); + INSERT INTO t5 VALUES('1234'); + INSERT INTO t5 VALUES('234'); + INSERT INTO t5 VALUES('34'); + SELECT min(a), max(a) FROM t5; + } +} {34 1234} + +# Ticket #658: Test the min()/max() optimization when the FROM clause +# is a subquery. +# +ifcapable {compound && subquery} { + do_test minmax-9.1 { + execsql { + SELECT max(rowid) FROM ( + SELECT max(rowid) FROM t4 UNION SELECT max(rowid) FROM t5 + ) + } + } {{}} + do_test minmax-9.2 { + execsql { + SELECT max(rowid) FROM ( + SELECT max(rowid) FROM t4 EXCEPT SELECT max(rowid) FROM t5 + ) + } + } {{}} +} ;# ifcapable compound&&subquery + +# If there is a NULL in an aggregate max() or min(), ignore it. An +# aggregate min() or max() will only return NULL if all values are NULL. +# +do_test minmax-10.1 { + execsql { + CREATE TABLE t6(x); + INSERT INTO t6 VALUES(1); + INSERT INTO t6 VALUES(2); + INSERT INTO t6 VALUES(NULL); + SELECT coalesce(min(x),-1) FROM t6; + } +} {1} +do_test minmax-10.2 { + execsql { + SELECT max(x) FROM t6; + } +} {2} +do_test minmax-10.3 { + execsql { + CREATE INDEX i6 ON t6(x); + SELECT coalesce(min(x),-1) FROM t6; + } +} {1} +do_test minmax-10.4 { + execsql { + SELECT max(x) FROM t6; + } +} {2} +do_test minmax-10.5 { + execsql { + DELETE FROM t6 WHERE x NOT NULL; + SELECT count(*) FROM t6; + } +} 1 +do_test minmax-10.6 { + execsql { + SELECT count(x) FROM t6; + } +} 0 +ifcapable subquery { + do_test minmax-10.7 { + execsql { + SELECT (SELECT min(x) FROM t6), (SELECT max(x) FROM t6); + } + } {{} {}} +} +do_test minmax-10.8 { + execsql { + SELECT min(x), max(x) FROM t6; + } +} {{} {}} +do_test minmax-10.9 { + execsql { + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + SELECT count(*) FROM t6; + } +} 1024 +do_test minmax-10.10 { + execsql { + SELECT count(x) FROM t6; + } +} 0 +ifcapable subquery { + do_test minmax-10.11 { + execsql { + SELECT (SELECT min(x) FROM t6), (SELECT max(x) FROM t6); + } + } {{} {}} +} +do_test minmax-10.12 { + execsql { + SELECT min(x), max(x) FROM t6; + } +} {{} {}} + + +do_test minmax-11.1 { + execsql { + CREATE INDEX t1i2 ON t1(y,x); + SELECT min(x) FROM t1 WHERE y=5; + } +} {16} +do_test minmax-11.2 { + execsql { + SELECT max(x) FROM t1 WHERE y=5; + } +} {20} +do_test minmax-11.3 { + execsql { + SELECT min(x) FROM t1 WHERE y=6; + } +} {{}} +do_test minmax-11.4 { + execsql { + SELECT max(x) FROM t1 WHERE y=6; + } +} {{}} +do_test minmax-11.5 { + execsql { + SELECT min(x) FROM t1 WHERE y=1; + } +} {1} +do_test minmax-11.6 { + execsql { + SELECT max(x) FROM t1 WHERE y=1; + } +} {1} +do_test minmax-11.7 { + execsql { + SELECT min(x) FROM t1 WHERE y=0; + } +} {{}} +do_test minmax-11.8 { + execsql { + SELECT max(x) FROM t1 WHERE y=0; + } +} {{}} +do_test minmax-11.9 { + execsql { + SELECT min(x) FROM t1 WHERE y=5 AND x>=17.5; + } +} {18} +do_test minmax-11.10 { + execsql { + SELECT max(x) FROM t1 WHERE y=5 AND x>=17.5; + } +} {20} + +do_test minmax-12.1 { + execsql { + CREATE TABLE t7(a,b,c); + INSERT INTO t7 SELECT y, x, x*y FROM t1; + INSERT INTO t7 SELECT y, x, x*y+1000 FROM t1; + CREATE INDEX t7i1 ON t7(a,b,c); + SELECT min(a) FROM t7; + } +} {1} +do_test minmax-12.2 { + execsql { + SELECT max(a) FROM t7; + } +} {5} +do_test minmax-12.3 { + execsql { + SELECT max(a) FROM t7 WHERE a=5; + } +} {5} +do_test minmax-12.4 { + execsql { + SELECT min(b) FROM t7 WHERE a=5; + } +} {16} +do_test minmax-12.5 { + execsql { + SELECT max(b) FROM t7 WHERE a=5; + } +} {20} +do_test minmax-12.6 { + execsql { + SELECT min(b) FROM t7 WHERE a=4; + } +} {8} +do_test minmax-12.7 { + execsql { + SELECT max(b) FROM t7 WHERE a=4; + } +} {15} +do_test minmax-12.8 { + execsql { + SELECT min(c) FROM t7 WHERE a=4 AND b=10; + } +} {40} +do_test minmax-12.9 { + execsql { + SELECT max(c) FROM t7 WHERE a=4 AND b=10; + } +} {1040} +do_test minmax-12.10 { + execsql { + SELECT min(rowid) FROM t7; + } +} {1} +do_test minmax-12.11 { + execsql { + SELECT max(rowid) FROM t7; + } +} {40} +do_test minmax-12.12 { + execsql { + SELECT min(rowid) FROM t7 WHERE a=3; + } +} {4} +do_test minmax-12.13 { + execsql { + SELECT max(rowid) FROM t7 WHERE a=3; + } +} {27} +do_test minmax-12.14 { + execsql { + SELECT min(rowid) FROM t7 WHERE a=3 AND b=5; + } +} {5} +do_test minmax-12.15 { + execsql { + SELECT max(rowid) FROM t7 WHERE a=3 AND b=5; + } +} {25} +do_test minmax-12.16 { + execsql { + SELECT min(rowid) FROM t7 WHERE a=3 AND b=5 AND c=1015; + } +} {25} +do_test minmax-12.17 { + execsql { + SELECT max(rowid) FROM t7 WHERE a=3 AND b=5 AND c=15; + } +} {5} + +#------------------------------------------------------------------------- +reset_db + +proc do_test_13 {op name sql1 sql2 res} { + set ::sqlite_search_count 0 + uplevel [list do_execsql_test $name.1 $sql1 $res] + set a $::sqlite_search_count + + set ::sqlite_search_count 0 + uplevel [list do_execsql_test $name.2 $sql2 $res] + set b $::sqlite_search_count + + uplevel [list do_test $name.3 [list expr "$a $op $b"] 1] +} + +# Run a test named $name. Check that SQL statements $sql1 and $sql2 both +# return the same result, but that $sql2 increments the $sqlite_search_count +# variable more often (indicating that it is visiting more rows to determine +# the result). +# +proc do_test_13_opt {name sql1 sql2 res} { + uplevel [list do_test_13 < $name $sql1 $sql2 $res] +} + +# Like [do_test_13_noopt], except this time check that the $sqlite_search_count +# variable is incremented the same number of times by both SQL statements. +# +proc do_test_13_noopt {name sql1 sql2 res} { + uplevel [list do_test_13 == $name $sql1 $sql2 $res] +} + +do_execsql_test 13.1 { + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES('a', 1, 1); + INSERT INTO t1 VALUES('b', 6, 6); + INSERT INTO t1 VALUES('c', 5, 5); + INSERT INTO t1 VALUES('a', 4, 4); + INSERT INTO t1 VALUES('a', 5, 5); + INSERT INTO t1 VALUES('c', 6, 6); + INSERT INTO t1 VALUES('b', 4, 4); + INSERT INTO t1 VALUES('c', 7, 7); + INSERT INTO t1 VALUES('b', 2, 2); + INSERT INTO t1 VALUES('b', 3, 3); + INSERT INTO t1 VALUES('a', 3, 3); + INSERT INTO t1 VALUES('b', 5, 5); + INSERT INTO t1 VALUES('c', 4, 4); + INSERT INTO t1 VALUES('c', 3, 3); + INSERT INTO t1 VALUES('a', 2, 2); + SELECT * FROM t1 ORDER BY a, b, c; +} {a 1 1 a 2 2 a 3 3 a 4 4 a 5 5 + b 2 2 b 3 3 b 4 4 b 5 5 b 6 6 + c 3 3 c 4 4 c 5 5 c 6 6 c 7 7 +} +do_execsql_test 13.2 { CREATE INDEX i1 ON t1(a, b, c) } + +do_test_13_opt 13.3 { + SELECT min(b) FROM t1 WHERE a='b' +} { + SELECT min(c) FROM t1 WHERE a='b' +} {2} + +do_test_13_opt 13.4 { + SELECT a, min(b) FROM t1 WHERE a='b' +} { + SELECT a, min(c) FROM t1 WHERE a='b' +} {b 2} + +do_test_13_opt 13.4 { + SELECT a||c, max(b)+4 FROM t1 WHERE a='c' +} { + SELECT a||c, max(c)+4 FROM t1 WHERE a='c' +} {c7 11} + +do_test_13_noopt 13.5 { + SELECT a||c, max(b+1) FROM t1 WHERE a='c' +} { + SELECT a||c, max(c+1) FROM t1 WHERE a='c' +} {c7 8} + +do_test_13_noopt 13.6 { + SELECT count(b) FROM t1 WHERE a='c' +} { + SELECT count(c) FROM t1 WHERE a='c' +} {5} + +do_test_13_noopt 13.7 { + SELECT min(b), count(b) FROM t1 WHERE a='a'; +} { + SELECT min(c), count(c) FROM t1 WHERE a='a'; +} {1 5} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/minmax2.test b/components/external/SQLite-3.8.1/test/minmax2.test new file mode 100644 index 0000000000000000000000000000000000000000..da8fec30ce0827c173b0cd7472d56244c77d4f52 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/minmax2.test @@ -0,0 +1,387 @@ +# 2007 July 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing SELECT statements that contain +# aggregate min() and max() functions and which are handled as +# as a special case. This file makes sure that the min/max +# optimization works right in the presence of descending +# indices. Ticket #2514. +# +# $Id: minmax2.test,v 1.2 2008/01/05 17:39:30 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test minmax2-1.0 { + execsql { + PRAGMA legacy_file_format=0; + BEGIN; + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(1,1); + INSERT INTO t1 VALUES(2,2); + INSERT INTO t1 VALUES(3,2); + INSERT INTO t1 VALUES(4,3); + INSERT INTO t1 VALUES(5,3); + INSERT INTO t1 VALUES(6,3); + INSERT INTO t1 VALUES(7,3); + INSERT INTO t1 VALUES(8,4); + INSERT INTO t1 VALUES(9,4); + INSERT INTO t1 VALUES(10,4); + INSERT INTO t1 VALUES(11,4); + INSERT INTO t1 VALUES(12,4); + INSERT INTO t1 VALUES(13,4); + INSERT INTO t1 VALUES(14,4); + INSERT INTO t1 VALUES(15,4); + INSERT INTO t1 VALUES(16,5); + INSERT INTO t1 VALUES(17,5); + INSERT INTO t1 VALUES(18,5); + INSERT INTO t1 VALUES(19,5); + INSERT INTO t1 VALUES(20,5); + COMMIT; + SELECT DISTINCT y FROM t1 ORDER BY y; + } +} {1 2 3 4 5} + +do_test minmax2-1.1 { + set sqlite_search_count 0 + execsql {SELECT min(x) FROM t1} +} {1} +do_test minmax2-1.2 { + set sqlite_search_count +} {19} +do_test minmax2-1.3 { + set sqlite_search_count 0 + execsql {SELECT max(x) FROM t1} +} {20} +do_test minmax2-1.4 { + set sqlite_search_count +} {19} +do_test minmax2-1.5 { + execsql {CREATE INDEX t1i1 ON t1(x DESC)} + set sqlite_search_count 0 + execsql {SELECT min(x) FROM t1} +} {1} +do_test minmax2-1.6 { + set sqlite_search_count +} {1} +do_test minmax2-1.7 { + set sqlite_search_count 0 + execsql {SELECT max(x) FROM t1} +} {20} +do_test minmax2-1.8 { + set sqlite_search_count +} {0} +do_test minmax2-1.9 { + set sqlite_search_count 0 + execsql {SELECT max(y) FROM t1} +} {5} +do_test minmax2-1.10 { + set sqlite_search_count +} {19} + +do_test minmax2-2.0 { + execsql { + CREATE TABLE t2(a INTEGER PRIMARY KEY, b); + INSERT INTO t2 SELECT * FROM t1; + } + set sqlite_search_count 0 + execsql {SELECT min(a) FROM t2} +} {1} +do_test minmax2-2.1 { + set sqlite_search_count +} {0} +do_test minmax2-2.2 { + set sqlite_search_count 0 + execsql {SELECT max(a) FROM t2} +} {20} +do_test minmax2-2.3 { + set sqlite_search_count +} {0} + +do_test minmax2-3.0 { + ifcapable subquery { + execsql {INSERT INTO t2 VALUES((SELECT max(a) FROM t2)+1,999)} + } else { + db function max_a_t2 {execsql {SELECT max(a) FROM t2}} + execsql {INSERT INTO t2 VALUES(max_a_t2()+1,999)} + } + set sqlite_search_count 0 + execsql {SELECT max(a) FROM t2} +} {21} +do_test minmax2-3.1 { + set sqlite_search_count +} {0} +do_test minmax2-3.2 { + ifcapable subquery { + execsql {INSERT INTO t2 VALUES((SELECT max(a) FROM t2)+1,999)} + } else { + db function max_a_t2 {execsql {SELECT max(a) FROM t2}} + execsql {INSERT INTO t2 VALUES(max_a_t2()+1,999)} + } + set sqlite_search_count 0 + ifcapable subquery { + execsql { SELECT b FROM t2 WHERE a=(SELECT max(a) FROM t2) } + } else { + execsql { SELECT b FROM t2 WHERE a=max_a_t2() } + } +} {999} +do_test minmax2-3.3 { + set sqlite_search_count +} {0} + +ifcapable {compound && subquery} { + do_test minmax2-4.1 { + execsql { + SELECT coalesce(min(x+0),-1), coalesce(max(x+0),-1) FROM + (SELECT * FROM t1 UNION SELECT NULL as 'x', NULL as 'y') + } + } {1 20} + do_test minmax2-4.2 { + execsql { + SELECT y, coalesce(sum(x),0) FROM + (SELECT null AS x, y+1 AS y FROM t1 UNION SELECT * FROM t1) + GROUP BY y ORDER BY y; + } + } {1 1 2 5 3 22 4 92 5 90 6 0} + do_test minmax2-4.3 { + execsql { + SELECT y, count(x), count(*) FROM + (SELECT null AS x, y+1 AS y FROM t1 UNION SELECT * FROM t1) + GROUP BY y ORDER BY y; + } + } {1 1 1 2 2 3 3 4 5 4 8 9 5 5 6 6 0 1} +} ;# ifcapable compound + +# Make sure the min(x) and max(x) optimizations work on empty tables +# including empty tables with indices. Ticket #296. +# +do_test minmax2-5.1 { + execsql { + CREATE TABLE t3(x INTEGER UNIQUE NOT NULL); + SELECT coalesce(min(x),999) FROM t3; + } +} {999} +do_test minmax2-5.2 { + execsql { + SELECT coalesce(min(rowid),999) FROM t3; + } +} {999} +do_test minmax2-5.3 { + execsql { + SELECT coalesce(max(x),999) FROM t3; + } +} {999} +do_test minmax2-5.4 { + execsql { + SELECT coalesce(max(rowid),999) FROM t3; + } +} {999} +do_test minmax2-5.5 { + execsql { + SELECT coalesce(max(rowid),999) FROM t3 WHERE rowid<25; + } +} {999} + +# Make sure the min(x) and max(x) optimizations work when there +# is a LIMIT clause. Ticket #396. +# +do_test minmax2-6.1 { + execsql { + SELECT min(a) FROM t2 LIMIT 1 + } +} {1} +do_test minmax2-6.2 { + execsql { + SELECT max(a) FROM t2 LIMIT 3 + } +} {22} +do_test minmax2-6.3 { + execsql { + SELECT min(a) FROM t2 LIMIT 0,100 + } +} {1} +do_test minmax2-6.4 { + execsql { + SELECT max(a) FROM t2 LIMIT 1,100 + } +} {} +do_test minmax2-6.5 { + execsql { + SELECT min(x) FROM t3 LIMIT 1 + } +} {{}} +do_test minmax2-6.6 { + execsql { + SELECT max(x) FROM t3 LIMIT 0 + } +} {} +do_test minmax2-6.7 { + execsql { + SELECT max(a) FROM t2 LIMIT 0 + } +} {} + +# Make sure the max(x) and min(x) optimizations work for nested +# queries. Ticket #587. +# +do_test minmax2-7.1 { + execsql { + SELECT max(x) FROM t1; + } +} 20 +ifcapable subquery { + do_test minmax2-7.2 { + execsql { + SELECT * FROM (SELECT max(x) FROM t1); + } + } 20 +} +do_test minmax2-7.3 { + execsql { + SELECT min(x) FROM t1; + } +} 1 +ifcapable subquery { + do_test minmax2-7.4 { + execsql { + SELECT * FROM (SELECT min(x) FROM t1); + } + } 1 +} + +# Make sure min(x) and max(x) work correctly when the datatype is +# TEXT instead of NUMERIC. Ticket #623. +# +do_test minmax2-8.1 { + execsql { + CREATE TABLE t4(a TEXT); + INSERT INTO t4 VALUES('1234'); + INSERT INTO t4 VALUES('234'); + INSERT INTO t4 VALUES('34'); + SELECT min(a), max(a) FROM t4; + } +} {1234 34} +do_test minmax2-8.2 { + execsql { + CREATE TABLE t5(a INTEGER); + INSERT INTO t5 VALUES('1234'); + INSERT INTO t5 VALUES('234'); + INSERT INTO t5 VALUES('34'); + SELECT min(a), max(a) FROM t5; + } +} {34 1234} + +# Ticket #658: Test the min()/max() optimization when the FROM clause +# is a subquery. +# +ifcapable {compound && subquery} { + do_test minmax2-9.1 { + execsql { + SELECT max(rowid) FROM ( + SELECT max(rowid) FROM t4 UNION SELECT max(rowid) FROM t5 + ) + } + } {{}} + do_test minmax2-9.2 { + execsql { + SELECT max(rowid) FROM ( + SELECT max(rowid) FROM t4 EXCEPT SELECT max(rowid) FROM t5 + ) + } + } {{}} +} ;# ifcapable compound&&subquery + +# If there is a NULL in an aggregate max() or min(), ignore it. An +# aggregate min() or max() will only return NULL if all values are NULL. +# +do_test minmax2-10.1 { + execsql { + CREATE TABLE t6(x); + INSERT INTO t6 VALUES(1); + INSERT INTO t6 VALUES(2); + INSERT INTO t6 VALUES(NULL); + SELECT coalesce(min(x),-1) FROM t6; + } +} {1} +do_test minmax2-10.2 { + execsql { + SELECT max(x) FROM t6; + } +} {2} +do_test minmax2-10.3 { + execsql { + CREATE INDEX i6 ON t6(x DESC); + SELECT coalesce(min(x),-1) FROM t6; + } +} {1} +do_test minmax2-10.4 { + execsql { + SELECT max(x) FROM t6; + } +} {2} +do_test minmax2-10.5 { + execsql { + DELETE FROM t6 WHERE x NOT NULL; + SELECT count(*) FROM t6; + } +} 1 +do_test minmax2-10.6 { + execsql { + SELECT count(x) FROM t6; + } +} 0 +ifcapable subquery { + do_test minmax2-10.7 { + execsql { + SELECT (SELECT min(x) FROM t6), (SELECT max(x) FROM t6); + } + } {{} {}} +} +do_test minmax2-10.8 { + execsql { + SELECT min(x), max(x) FROM t6; + } +} {{} {}} +do_test minmax2-10.9 { + execsql { + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + SELECT count(*) FROM t6; + } +} 1024 +do_test minmax2-10.10 { + execsql { + SELECT count(x) FROM t6; + } +} 0 +ifcapable subquery { + do_test minmax2-10.11 { + execsql { + SELECT (SELECT min(x) FROM t6), (SELECT max(x) FROM t6); + } + } {{} {}} +} +do_test minmax2-10.12 { + execsql { + SELECT min(x), max(x) FROM t6; + } +} {{} {}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/minmax3.test b/components/external/SQLite-3.8.1/test/minmax3.test new file mode 100644 index 0000000000000000000000000000000000000000..483fa612d27d41f2c2fdb6c84cbf491f04279d16 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/minmax3.test @@ -0,0 +1,288 @@ +# 2008 January 5 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# $Id: minmax3.test,v 1.5 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Do an SQL statement. Append the search count to the end of the result. +# +proc count sql { + set ::sqlite_search_count 0 + return [concat [execsql $sql] $::sqlite_search_count] +} + +# This procedure sets the value of the file-format in file 'test.db' +# to $newval. Also, the schema cookie is incremented. +# +proc set_file_format {newval} { + hexio_write test.db 44 [hexio_render_int32 $newval] + set schemacookie [hexio_get_int [hexio_read test.db 40 4]] + incr schemacookie + hexio_write test.db 40 [hexio_render_int32 $schemacookie] + return {} +} + +do_test minmax3-1.0 { + execsql { + CREATE TABLE t1(x, y, z); + } + db close + set_file_format 4 + sqlite3 db test.db + execsql { + BEGIN; + INSERT INTO t1 VALUES('1', 'I', 'one'); + INSERT INTO t1 VALUES('2', 'IV', 'four'); + INSERT INTO t1 VALUES('2', NULL, 'three'); + INSERT INTO t1 VALUES('2', 'II', 'two'); + INSERT INTO t1 VALUES('2', 'V', 'five'); + INSERT INTO t1 VALUES('3', 'VI', 'six'); + COMMIT; + PRAGMA automatic_index=OFF; + } +} {} +do_test minmax3-1.1.1 { + # Linear scan. + count { SELECT max(y) FROM t1 WHERE x = '2'; } +} {V 5} +do_test minmax3-1.1.2 { + # Index optimizes the WHERE x='2' constraint. + execsql { CREATE INDEX i1 ON t1(x) } + count { SELECT max(y) FROM t1 WHERE x = '2'; } +} {V 9} +do_test minmax3-1.1.3 { + # Index optimizes the WHERE x='2' constraint and the MAX(y). + execsql { CREATE INDEX i2 ON t1(x,y) } + count { SELECT max(y) FROM t1 WHERE x = '2'; } +} {V 1} +do_test minmax3-1.1.4 { + # Index optimizes the WHERE x='2' constraint and the MAX(y). + execsql { DROP INDEX i2 ; CREATE INDEX i2 ON t1(x, y DESC) } + count { SELECT max(y) FROM t1 WHERE x = '2'; } +} {V 1} +do_test minmax3-1.1.5 { + count { SELECT max(y) FROM t1 WHERE x = '2' AND y != 'V'; } +} {IV 2} +do_test minmax3-1.1.6 { + count { SELECT max(y) FROM t1 WHERE x = '2' AND y < 'V'; } +} {IV 1} +do_test minmax3-1.1.6 { + count { SELECT max(y) FROM t1 WHERE x = '2' AND z != 'five'; } +} {IV 4} + +do_test minmax3-1.2.1 { + # Linear scan of t1. + execsql { DROP INDEX i1 ; DROP INDEX i2 } + count { SELECT min(y) FROM t1 WHERE x = '2'; } +} {II 5} +do_test minmax3-1.2.2 { + # Index i1 optimizes the WHERE x='2' constraint. + execsql { CREATE INDEX i1 ON t1(x) } + count { SELECT min(y) FROM t1 WHERE x = '2'; } +} {II 9} +do_test minmax3-1.2.3 { + # Index i2 optimizes the WHERE x='2' constraint and the min(y). + execsql { CREATE INDEX i2 ON t1(x,y) } + count { SELECT min(y) FROM t1 WHERE x = '2'; } +} {II 1} +do_test minmax3-1.2.4 { + # Index optimizes the WHERE x='2' constraint and the MAX(y). + execsql { DROP INDEX i2 ; CREATE INDEX i2 ON t1(x, y DESC) } + count { SELECT min(y) FROM t1 WHERE x = '2'; } +} {II 1} + +do_test minmax3-1.3.1 { + # Linear scan + execsql { DROP INDEX i1 ; DROP INDEX i2 } + count { SELECT min(y) FROM t1; } +} {I 5} +do_test minmax3-1.3.2 { + # Index i1 optimizes the min(y) + execsql { CREATE INDEX i1 ON t1(y) } + count { SELECT min(y) FROM t1; } +} {I 1} +do_test minmax3-1.3.3 { + # Index i1 optimizes the min(y) + execsql { DROP INDEX i1 ; CREATE INDEX i1 ON t1(y DESC) } + count { SELECT min(y) FROM t1; } +} {I 1} + +do_test minmax3-1.4.1 { + # Linear scan + execsql { DROP INDEX i1 } + count { SELECT max(y) FROM t1; } +} {VI 5} +do_test minmax3-1.4.2 { + # Index i1 optimizes the max(y) + execsql { CREATE INDEX i1 ON t1(y) } + count { SELECT max(y) FROM t1; } +} {VI 0} +do_test minmax3-1.4.3 { + # Index i1 optimizes the max(y) + execsql { DROP INDEX i1 ; CREATE INDEX i1 ON t1(y DESC) } + execsql { SELECT y from t1} + count { SELECT max(y) FROM t1; } +} {VI 0} +do_test minmax3-1.4.4 { + execsql { DROP INDEX i1 } +} {} + +do_test minmax3-2.1 { + execsql { + CREATE TABLE t2(a, b); + CREATE INDEX i3 ON t2(a, b); + INSERT INTO t2 VALUES(1, NULL); + INSERT INTO t2 VALUES(1, 1); + INSERT INTO t2 VALUES(1, 2); + INSERT INTO t2 VALUES(1, 3); + INSERT INTO t2 VALUES(2, NULL); + INSERT INTO t2 VALUES(2, 1); + INSERT INTO t2 VALUES(2, 2); + INSERT INTO t2 VALUES(2, 3); + INSERT INTO t2 VALUES(3, 1); + INSERT INTO t2 VALUES(3, 2); + INSERT INTO t2 VALUES(3, 3); + } +} {} +do_test minmax3-2.2 { + execsql { SELECT min(b) FROM t2 WHERE a = 1; } +} {1} +do_test minmax3-2.3 { + execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b>1; } +} {2} +do_test minmax3-2.4 { + execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b>-1; } +} {1} +do_test minmax3-2.5 { + execsql { SELECT min(b) FROM t2 WHERE a = 1; } +} {1} +do_test minmax3-2.6 { + execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b<2; } +} {1} +do_test minmax3-2.7 { + execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b<1; } +} {{}} +do_test minmax3-2.8 { + execsql { SELECT min(b) FROM t2 WHERE a = 3 AND b<1; } +} {{}} + +do_test minmax3-3.1 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(a, b); + CREATE INDEX i3 ON t2(a, b DESC); + INSERT INTO t2 VALUES(1, NULL); + INSERT INTO t2 VALUES(1, 1); + INSERT INTO t2 VALUES(1, 2); + INSERT INTO t2 VALUES(1, 3); + INSERT INTO t2 VALUES(2, NULL); + INSERT INTO t2 VALUES(2, 1); + INSERT INTO t2 VALUES(2, 2); + INSERT INTO t2 VALUES(2, 3); + INSERT INTO t2 VALUES(3, 1); + INSERT INTO t2 VALUES(3, 2); + INSERT INTO t2 VALUES(3, 3); + } +} {} +do_test minmax3-3.2 { + execsql { SELECT min(b) FROM t2 WHERE a = 1; } +} {1} +do_test minmax3-3.3 { + execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b>1; } +} {2} +do_test minmax3-3.4 { + execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b>-1; } +} {1} +do_test minmax3-3.5 { + execsql { SELECT min(b) FROM t2 WHERE a = 1; } +} {1} +do_test minmax3-3.6 { + execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b<2; } +} {1} +do_test minmax3-3.7 { + execsql { SELECT min(b) FROM t2 WHERE a = 1 AND b<1; } +} {{}} +do_test minmax3-3.8 { + execsql { SELECT min(b) FROM t2 WHERE a = 3 AND b<1; } +} {{}} + +do_test minmax3-4.1 { + execsql { + CREATE TABLE t4(x); + INSERT INTO t4 VALUES('abc'); + INSERT INTO t4 VALUES('BCD'); + SELECT max(x) FROM t4; + } +} {abc} +do_test minmax3-4.2 { + execsql { + SELECT max(x COLLATE nocase) FROM t4; + } +} {BCD} +do_test minmax3-4.3 { + execsql { + SELECT max(x), max(x COLLATE nocase) FROM t4; + } +} {abc BCD} +do_test minmax3-4.4 { + execsql { + SELECT max(x COLLATE binary), max(x COLLATE nocase) FROM t4; + } +} {abc BCD} +do_test minmax3-4.5 { + execsql { + SELECT max(x COLLATE nocase), max(x COLLATE rtrim) FROM t4; + } +} {BCD abc} +do_test minmax3-4.6 { + execsql { + SELECT max(x COLLATE nocase), max(x) FROM t4; + } +} {BCD abc} +do_test minmax3-4.10 { + execsql { + SELECT min(x) FROM t4; + } +} {BCD} +do_test minmax3-4.11 { + execsql { + SELECT min(x COLLATE nocase) FROM t4; + } +} {abc} +do_test minmax3-4.12 { + execsql { + SELECT min(x), min(x COLLATE nocase) FROM t4; + } +} {BCD abc} +do_test minmax3-4.13 { + execsql { + SELECT min(x COLLATE binary), min(x COLLATE nocase) FROM t4; + } +} {BCD abc} +do_test minmax3-4.14 { + execsql { + SELECT min(x COLLATE nocase), min(x COLLATE rtrim) FROM t4; + } +} {abc BCD} +do_test minmax3-4.15 { + execsql { + SELECT min(x COLLATE nocase), min(x) FROM t4; + } +} {abc BCD} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/minmax4.test b/components/external/SQLite-3.8.1/test/minmax4.test new file mode 100644 index 0000000000000000000000000000000000000000..0d8305b5ff3779d45fff92ff4d8eeb72105845c3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/minmax4.test @@ -0,0 +1,150 @@ +# 2012 February 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test for queries of the form: +# +# SELECT p, max(q) FROM t1; +# +# Demonstration that the value returned for p is on the same row as +# the maximum q. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_test minmax4-1.1 { + db eval { + CREATE TABLE t1(p,q); + SELECT p, max(q) FROM t1; + } +} {{} {}} +do_test minmax4-1.2 { + db eval { + SELECT p, min(q) FROM t1; + } +} {{} {}} +do_test minmax4-1.3 { + db eval { + INSERT INTO t1 VALUES(1,2); + SELECT p, max(q) FROM t1; + } +} {1 2} +do_test minmax4-1.4 { + db eval { + SELECT p, min(q) FROM t1; + } +} {1 2} +do_test minmax4-1.5 { + db eval { + INSERT INTO t1 VALUES(3,4); + SELECT p, max(q) FROM t1; + } +} {3 4} +do_test minmax4-1.6 { + db eval { + SELECT p, min(q) FROM t1; + } +} {1 2} +do_test minmax4-1.7 { + db eval { + INSERT INTO t1 VALUES(5,0); + SELECT p, max(q) FROM t1; + } +} {3 4} +do_test minmax4-1.8 { + db eval { + SELECT p, min(q) FROM t1; + } +} {5 0} +do_test minmax4-1.9 { + db eval { + INSERT INTO t1 VALUES(6,1); + SELECT p, max(q) FROM t1; + } +} {3 4} +do_test minmax4-1.10 { + db eval { + SELECT p, min(q) FROM t1; + } +} {5 0} +do_test minmax4-1.11 { + db eval { + INSERT INTO t1 VALUES(7,NULL); + SELECT p, max(q) FROM t1; + } +} {3 4} +do_test minmax4-1.12 { + db eval { + SELECT p, min(q) FROM t1; + } +} {5 0} +do_test minmax4-1.13 { + db eval { + DELETE FROM t1 WHERE q IS NOT NULL; + SELECT p, max(q) FROM t1; + } +} {7 {}} +do_test minmax4-1.14 { + db eval { + SELECT p, min(q) FROM t1; + } +} {7 {}} + +do_test minmax4-2.1 { + db eval { + CREATE TABLE t2(a,b,c); + INSERT INTO t2 VALUES + (1,null,2), + (1,2,3), + (1,1,4), + (2,3,5); + SELECT a, max(b), c FROM t2 GROUP BY a ORDER BY a; + } +} {1 2 3 2 3 5} +do_test minmax4-2.2 { + db eval { + SELECT a, min(b), c FROM t2 GROUP BY a ORDER BY a; + } +} {1 1 4 2 3 5} +do_test minmax4-2.3 { + db eval { + SELECT a, min(b), avg(b), count(b), c FROM t2 GROUP BY a ORDER BY a DESC; + } +} {2 3 3.0 1 5 1 1 1.5 2 4} +do_test minmax4-2.4 { + db eval { + SELECT a, min(b), max(b), c FROM t2 GROUP BY a ORDER BY a; + } +} {1 1 2 3 2 3 3 5} +do_test minmax4-2.5 { + db eval { + SELECT a, max(b), min(b), c FROM t2 GROUP BY a ORDER BY a; + } +} {1 2 1 4 2 3 3 5} +do_test minmax4-2.6 { + db eval { + SELECT a, max(b), b, max(c), c FROM t2 GROUP BY a ORDER BY a; + } +} {1 2 1 4 4 2 3 3 5 5} +do_test minmax4-2.7 { + db eval { + SELECT a, min(b), b, min(c), c FROM t2 GROUP BY a ORDER BY a; + } +} {1 1 {} 2 2 2 3 3 5 5} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/misc1.test b/components/external/SQLite-3.8.1/test/misc1.test new file mode 100644 index 0000000000000000000000000000000000000000..188a2837ba323dd1e8bced704b7ed73d5be9e399 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/misc1.test @@ -0,0 +1,595 @@ +# 2001 September 15. +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for miscellanous features that were +# left out of other test files. +# +# $Id: misc1.test,v 1.42 2007/11/05 14:58:23 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Mimic the SQLite 2 collation type NUMERIC. +db collate numeric numeric_collate +proc numeric_collate {lhs rhs} { + if {$lhs == $rhs} {return 0} + return [expr ($lhs>$rhs)?1:-1] +} + +# Mimic the SQLite 2 collation type TEXT. +db collate text text_collate +proc numeric_collate {lhs rhs} { + return [string compare $lhs $rhs] +} + +# Test the creation and use of tables that have a large number +# of columns. +# +do_test misc1-1.1 { + set cmd "CREATE TABLE manycol(x0 text" + for {set i 1} {$i<=99} {incr i} { + append cmd ",x$i text" + } + append cmd ")"; + execsql $cmd + set cmd "INSERT INTO manycol VALUES(0" + for {set i 1} {$i<=99} {incr i} { + append cmd ",$i" + } + append cmd ")"; + execsql $cmd + execsql "SELECT x99 FROM manycol" +} 99 +do_test misc1-1.2 { + execsql {SELECT x0, x10, x25, x50, x75 FROM manycol} +} {0 10 25 50 75} +do_test misc1-1.3.1 { + for {set j 100} {$j<=1000} {incr j 100} { + set cmd "INSERT INTO manycol VALUES($j" + for {set i 1} {$i<=99} {incr i} { + append cmd ",[expr {$i+$j}]" + } + append cmd ")" + execsql $cmd + } + execsql {SELECT x50 FROM manycol ORDER BY x80+0} +} {50 150 250 350 450 550 650 750 850 950 1050} +do_test misc1-1.3.2 { + execsql {SELECT x50 FROM manycol ORDER BY x80} +} {1050 150 250 350 450 550 650 750 50 850 950} +do_test misc1-1.4 { + execsql {SELECT x75 FROM manycol WHERE x50=350} +} 375 +do_test misc1-1.5 { + execsql {SELECT x50 FROM manycol WHERE x99=599} +} 550 +do_test misc1-1.6 { + execsql {CREATE INDEX manycol_idx1 ON manycol(x99)} + execsql {SELECT x50 FROM manycol WHERE x99=899} +} 850 +do_test misc1-1.7 { + execsql {SELECT count(*) FROM manycol} +} 11 +do_test misc1-1.8 { + execsql {DELETE FROM manycol WHERE x98=1234} + execsql {SELECT count(*) FROM manycol} +} 11 +do_test misc1-1.9 { + execsql {DELETE FROM manycol WHERE x98=998} + execsql {SELECT count(*) FROM manycol} +} 10 +do_test misc1-1.10 { + execsql {DELETE FROM manycol WHERE x99=500} + execsql {SELECT count(*) FROM manycol} +} 10 +do_test misc1-1.11 { + execsql {DELETE FROM manycol WHERE x99=599} + execsql {SELECT count(*) FROM manycol} +} 9 + +# Check GROUP BY expressions that name two or more columns. +# +do_test misc1-2.1 { + execsql { + BEGIN TRANSACTION; + CREATE TABLE agger(one text, two text, three text, four text); + INSERT INTO agger VALUES(1, 'one', 'hello', 'yes'); + INSERT INTO agger VALUES(2, 'two', 'howdy', 'no'); + INSERT INTO agger VALUES(3, 'thr', 'howareya', 'yes'); + INSERT INTO agger VALUES(4, 'two', 'lothere', 'yes'); + INSERT INTO agger VALUES(5, 'one', 'atcha', 'yes'); + INSERT INTO agger VALUES(6, 'two', 'hello', 'no'); + COMMIT + } + execsql {SELECT count(*) FROM agger} +} 6 +do_test misc1-2.2 { + execsql {SELECT sum(one), two, four FROM agger + GROUP BY two, four ORDER BY sum(one) desc} +} {8 two no 6 one yes 4 two yes 3 thr yes} +do_test misc1-2.3 { + execsql {SELECT sum((one)), (two), (four) FROM agger + GROUP BY (two), (four) ORDER BY sum(one) desc} +} {8 two no 6 one yes 4 two yes 3 thr yes} + +# Here's a test for a bug found by Joel Lucsy. The code below +# was causing an assertion failure. +# +do_test misc1-3.1 { + set r [execsql { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES('hi'); + PRAGMA full_column_names=on; + SELECT rowid, * FROM t1; + }] + lindex $r 1 +} {hi} + +# Here's a test for yet another bug found by Joel Lucsy. The code +# below was causing an assertion failure. +# +do_test misc1-4.1 { + execsql { + BEGIN; + CREATE TABLE t2(a); + INSERT INTO t2 VALUES('This is a long string to use up a lot of disk -'); + UPDATE t2 SET a=a||a||a||a; + INSERT INTO t2 SELECT '1 - ' || a FROM t2; + INSERT INTO t2 SELECT '2 - ' || a FROM t2; + INSERT INTO t2 SELECT '3 - ' || a FROM t2; + INSERT INTO t2 SELECT '4 - ' || a FROM t2; + INSERT INTO t2 SELECT '5 - ' || a FROM t2; + INSERT INTO t2 SELECT '6 - ' || a FROM t2; + COMMIT; + SELECT count(*) FROM t2; + } +} {64} + +# Make sure we actually see a semicolon or end-of-file in the SQL input +# before executing a command. Thus if "WHERE" is misspelled on an UPDATE, +# the user won't accidently update every record. +# +do_test misc1-5.1 { + catchsql { + CREATE TABLE t3(a,b); + INSERT INTO t3 VALUES(1,2); + INSERT INTO t3 VALUES(3,4); + UPDATE t3 SET a=0 WHEREwww b=2; + } +} {1 {near "WHEREwww": syntax error}} +do_test misc1-5.2 { + execsql { + SELECT * FROM t3 ORDER BY a; + } +} {1 2 3 4} + +# Certain keywords (especially non-standard keywords like "REPLACE") can +# also be used as identifiers. The way this works in the parser is that +# the parser first detects a syntax error, the error handling routine +# sees that the special keyword caused the error, then replaces the keyword +# with "ID" and tries again. +# +# Check the operation of this logic. +# +do_test misc1-6.1 { + catchsql { + CREATE TABLE t4( + abort, asc, begin, cluster, conflict, copy, delimiters, desc, end, + explain, fail, ignore, key, offset, pragma, replace, temp, + vacuum, view + ); + } +} {0 {}} +do_test misc1-6.2 { + catchsql { + INSERT INTO t4 + VALUES(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19); + } +} {0 {}} +do_test misc1-6.3 { + execsql { + SELECT * FROM t4 + } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19} +do_test misc1-6.4 { + execsql { + SELECT abort+asc,max(key,pragma,temp) FROM t4 + } +} {3 17} + +# Test for multi-column primary keys, and for multiple primary keys. +# +do_test misc1-7.1 { + catchsql { + CREATE TABLE error1( + a TYPE PRIMARY KEY, + b TYPE PRIMARY KEY + ); + } +} {1 {table "error1" has more than one primary key}} +do_test misc1-7.2 { + catchsql { + CREATE TABLE error1( + a INTEGER PRIMARY KEY, + b TYPE PRIMARY KEY + ); + } +} {1 {table "error1" has more than one primary key}} +do_test misc1-7.3 { + execsql { + CREATE TABLE t5(a,b,c,PRIMARY KEY(a,b)); + INSERT INTO t5 VALUES(1,2,3); + SELECT * FROM t5 ORDER BY a; + } +} {1 2 3} +do_test misc1-7.4 { + catchsql { + INSERT INTO t5 VALUES(1,2,4); + } +} {1 {columns a, b are not unique}} +do_test misc1-7.5 { + catchsql { + INSERT INTO t5 VALUES(0,2,4); + } +} {0 {}} +do_test misc1-7.6 { + execsql { + SELECT * FROM t5 ORDER BY a; + } +} {0 2 4 1 2 3} + +do_test misc1-8.1 { + catchsql { + SELECT *; + } +} {1 {no tables specified}} +do_test misc1-8.2 { + catchsql { + SELECT t1.*; + } +} {1 {no such table: t1}} + +execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + DROP TABLE t4; +} + +# 64-bit integers are represented exactly. +# +do_test misc1-9.1 { + catchsql { + CREATE TABLE t1(a unique not null, b unique not null); + INSERT INTO t1 VALUES('a',1234567890123456789); + INSERT INTO t1 VALUES('b',1234567891123456789); + INSERT INTO t1 VALUES('c',1234567892123456789); + SELECT * FROM t1; + } +} {0 {a 1234567890123456789 b 1234567891123456789 c 1234567892123456789}} + +# A WHERE clause is not allowed to contain more than 99 terms. Check to +# make sure this limit is enforced. +# +# 2005-07-16: There is no longer a limit on the number of terms in a +# WHERE clause. But keep these tests just so that we have some tests +# that use a large number of terms in the WHERE clause. +# +do_test misc1-10.0 { + execsql {SELECT count(*) FROM manycol} +} {9} +do_test misc1-10.1 { + set ::where {WHERE x0>=0} + for {set i 1} {$i<=99} {incr i} { + append ::where " AND x$i<>0" + } + catchsql "SELECT count(*) FROM manycol $::where" +} {0 9} +do_test misc1-10.2 { + catchsql "SELECT count(*) FROM manycol $::where AND rowid>0" +} {0 9} +do_test misc1-10.3 { + regsub "x0>=0" $::where "x0=0" ::where + catchsql "DELETE FROM manycol $::where" +} {0 {}} +do_test misc1-10.4 { + execsql {SELECT count(*) FROM manycol} +} {8} +do_test misc1-10.5 { + catchsql "DELETE FROM manycol $::where AND rowid>0" +} {0 {}} +do_test misc1-10.6 { + execsql {SELECT x1 FROM manycol WHERE x0=100} +} {101} +do_test misc1-10.7 { + regsub "x0=0" $::where "x0=100" ::where + catchsql "UPDATE manycol SET x1=x1+1 $::where" +} {0 {}} +do_test misc1-10.8 { + execsql {SELECT x1 FROM manycol WHERE x0=100} +} {102} +do_test misc1-10.9 { + catchsql "UPDATE manycol SET x1=x1+1 $::where AND rowid>0" +} {0 {}} +do_test misc1-10.10 { + execsql {SELECT x1 FROM manycol WHERE x0=100} +} {103} + +# Make sure the initialization works even if a database is opened while +# another process has the database locked. +# +# Update for v3: The BEGIN doesn't lock the database so the schema is read +# and the SELECT returns successfully. +do_test misc1-11.1 { + execsql {BEGIN} + execsql {UPDATE t1 SET a=0 WHERE 0} + sqlite3 db2 test.db + set rc [catch {db2 eval {SELECT count(*) FROM t1}} msg] + lappend rc $msg +# v2 result: {1 {database is locked}} +} {0 3} +do_test misc1-11.2 { + execsql {COMMIT} + set rc [catch {db2 eval {SELECT count(*) FROM t1}} msg] + db2 close + lappend rc $msg +} {0 3} + +# Make sure string comparisons really do compare strings in format4+. +# Similar tests in the format3.test file show that for format3 and earlier +# all comparisions where numeric if either operand looked like a number. +# +do_test misc1-12.1 { + execsql {SELECT '0'=='0.0'} +} {0} +do_test misc1-12.2 { + execsql {SELECT '0'==0.0} +} {0} +do_test misc1-12.3 { + execsql {SELECT '12345678901234567890'=='12345678901234567891'} +} {0} +do_test misc1-12.4 { + execsql { + CREATE TABLE t6(a INT UNIQUE, b TEXT UNIQUE); + INSERT INTO t6 VALUES('0','0.0'); + SELECT * FROM t6; + } +} {0 0.0} +ifcapable conflict { + do_test misc1-12.5 { + execsql { + INSERT OR IGNORE INTO t6 VALUES(0.0,'x'); + SELECT * FROM t6; + } + } {0 0.0} + do_test misc1-12.6 { + execsql { + INSERT OR IGNORE INTO t6 VALUES('y',0); + SELECT * FROM t6; + } + } {0 0.0 y 0} +} +do_test misc1-12.7 { + execsql { + CREATE TABLE t7(x INTEGER, y TEXT, z); + INSERT INTO t7 VALUES(0,0,1); + INSERT INTO t7 VALUES(0.0,0,2); + INSERT INTO t7 VALUES(0,0.0,3); + INSERT INTO t7 VALUES(0.0,0.0,4); + SELECT DISTINCT x, y FROM t7 ORDER BY z; + } +} {0 0 0 0.0} +do_test misc1-12.8 { + execsql { + SELECT min(z), max(z), count(z) FROM t7 GROUP BY x ORDER BY 1; + } +} {1 4 4} +do_test misc1-12.9 { + execsql { + SELECT min(z), max(z), count(z) FROM t7 GROUP BY y ORDER BY 1; + } +} {1 2 2 3 4 2} + +# This used to be an error. But we changed the code so that arbitrary +# identifiers can be used as a collating sequence. Collation is by text +# if the identifier contains "text", "blob", or "clob" and is numeric +# otherwise. +# +# Update: In v3, it is an error again. +# +#do_test misc1-12.10 { +# catchsql { +# SELECT * FROM t6 ORDER BY a COLLATE unknown; +# } +#} {0 {0 0 y 0}} +do_test misc1-12.11 { + execsql { + CREATE TABLE t8(x TEXT COLLATE numeric, y INTEGER COLLATE text, z); + INSERT INTO t8 VALUES(0,0,1); + INSERT INTO t8 VALUES(0.0,0,2); + INSERT INTO t8 VALUES(0,0.0,3); + INSERT INTO t8 VALUES(0.0,0.0,4); + SELECT DISTINCT x, y FROM t8 ORDER BY z; + } +} {0 0 0.0 0} +do_test misc1-12.12 { + execsql { + SELECT min(z), max(z), count(z) FROM t8 GROUP BY x ORDER BY 1; + } +} {1 3 2 2 4 2} +do_test misc1-12.13 { + execsql { + SELECT min(z), max(z), count(z) FROM t8 GROUP BY y ORDER BY 1; + } +} {1 4 4} + +# There was a problem with realloc() in the OP_MemStore operation of +# the VDBE. A buffer was being reallocated but some pointers into +# the old copy of the buffer were not being moved over to the new copy. +# The following code tests for the problem. +# +ifcapable subquery { + do_test misc1-13.1 { + execsql { + CREATE TABLE t9(x,y); + INSERT INTO t9 VALUES('one',1); + INSERT INTO t9 VALUES('two',2); + INSERT INTO t9 VALUES('three',3); + INSERT INTO t9 VALUES('four',4); + INSERT INTO t9 VALUES('five',5); + INSERT INTO t9 VALUES('six',6); + INSERT INTO t9 VALUES('seven',7); + INSERT INTO t9 VALUES('eight',8); + INSERT INTO t9 VALUES('nine',9); + INSERT INTO t9 VALUES('ten',10); + INSERT INTO t9 VALUES('eleven',11); + SELECT y FROM t9 + WHERE x=(SELECT x FROM t9 WHERE y=1) + OR x=(SELECT x FROM t9 WHERE y=2) + OR x=(SELECT x FROM t9 WHERE y=3) + OR x=(SELECT x FROM t9 WHERE y=4) + OR x=(SELECT x FROM t9 WHERE y=5) + OR x=(SELECT x FROM t9 WHERE y=6) + OR x=(SELECT x FROM t9 WHERE y=7) + OR x=(SELECT x FROM t9 WHERE y=8) + OR x=(SELECT x FROM t9 WHERE y=9) + OR x=(SELECT x FROM t9 WHERE y=10) + OR x=(SELECT x FROM t9 WHERE y=11) + OR x=(SELECT x FROM t9 WHERE y=12) + OR x=(SELECT x FROM t9 WHERE y=13) + OR x=(SELECT x FROM t9 WHERE y=14) + ; + } + } {1 2 3 4 5 6 7 8 9 10 11} +} + +# +# The following tests can only work if the current SQLite VFS has the concept +# of a current directory. +# +ifcapable curdir { +# Make sure a database connection still works after changing the +# working directory. +# +do_test misc1-14.1 { + file mkdir tempdir + cd tempdir + execsql {BEGIN} + file exists ./test.db-journal +} {0} +do_test misc1-14.2a { + execsql {UPDATE t1 SET a=a||'x' WHERE 0} + file exists ../test.db-journal +} {0} +do_test misc1-14.2b { + execsql {UPDATE t1 SET a=a||'y' WHERE 1} + file exists ../test.db-journal +} {1} +do_test misc1-14.3 { + cd .. + forcedelete tempdir + execsql {COMMIT} + file exists ./test.db-journal +} {0} +} + +# A failed create table should not leave the table in the internal +# data structures. Ticket #238. +# +do_test misc1-15.1.1 { + catchsql { + CREATE TABLE t10 AS SELECT c1; + } +} {1 {no such column: c1}} +do_test misc1-15.1.2 { + catchsql { + CREATE TABLE t10 AS SELECT t9.c1; + } +} {1 {no such column: t9.c1}} +do_test misc1-15.1.3 { + catchsql { + CREATE TABLE t10 AS SELECT main.t9.c1; + } +} {1 {no such column: main.t9.c1}} +do_test misc1-15.2 { + catchsql { + CREATE TABLE t10 AS SELECT 1; + } + # The bug in ticket #238 causes the statement above to fail with + # the error "table t10 alread exists" +} {0 {}} + +# Test for memory leaks when a CREATE TABLE containing a primary key +# fails. Ticket #249. +# +do_test misc1-16.1 { + catchsql {SELECT name FROM sqlite_master LIMIT 1} + catchsql { + CREATE TABLE test(a integer, primary key(a)); + } +} {0 {}} +do_test misc1-16.2 { + catchsql { + CREATE TABLE test(a integer, primary key(a)); + } +} {1 {table test already exists}} +do_test misc1-16.3 { + catchsql { + CREATE TABLE test2(a text primary key, b text, primary key(a,b)); + } +} {1 {table "test2" has more than one primary key}} +do_test misc1-16.4 { + execsql { + INSERT INTO test VALUES(1); + SELECT rowid, a FROM test; + } +} {1 1} +do_test misc1-16.5 { + execsql { + INSERT INTO test VALUES(5); + SELECT rowid, a FROM test; + } +} {1 1 5 5} +do_test misc1-16.6 { + execsql { + INSERT INTO test VALUES(NULL); + SELECT rowid, a FROM test; + } +} {1 1 5 5 6 6} + +ifcapable trigger&&tempdb { +# Ticket #333: Temp triggers that modify persistent tables. +# +do_test misc1-17.1 { + execsql { + BEGIN; + CREATE TABLE RealTable(TestID INTEGER PRIMARY KEY, TestString TEXT); + CREATE TEMP TABLE TempTable(TestID INTEGER PRIMARY KEY, TestString TEXT); + CREATE TEMP TRIGGER trigTest_1 AFTER UPDATE ON TempTable BEGIN + INSERT INTO RealTable(TestString) + SELECT new.TestString FROM TempTable LIMIT 1; + END; + INSERT INTO TempTable(TestString) VALUES ('1'); + INSERT INTO TempTable(TestString) VALUES ('2'); + UPDATE TempTable SET TestString = TestString + 1 WHERE TestID=1 OR TestId=2; + COMMIT; + SELECT TestString FROM RealTable ORDER BY 1; + } +} {2 3} +} + +do_test misc1-18.1 { + set n [sqlite3_sleep 100] + expr {$n>=100} +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/misc2.test b/components/external/SQLite-3.8.1/test/misc2.test new file mode 100644 index 0000000000000000000000000000000000000000..bb544c5fbb57891289967080c805341e2a157d55 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/misc2.test @@ -0,0 +1,441 @@ +# 2003 June 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for miscellanous features that were +# left out of other test files. +# +# $Id: misc2.test,v 1.28 2007/09/12 17:01:45 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# The tests in this file were written before SQLite supported recursive +# trigger invocation, and some tests depend on that to pass. So disable +# recursive triggers for this file. +catchsql { pragma recursive_triggers = off } + +ifcapable {trigger} { +# Test for ticket #360 +# +do_test misc2-1.1 { + catchsql { + CREATE TABLE FOO(bar integer); + CREATE TRIGGER foo_insert BEFORE INSERT ON foo BEGIN + SELECT CASE WHEN (NOT new.bar BETWEEN 0 AND 20) + THEN raise(rollback, 'aiieee') END; + END; + INSERT INTO foo(bar) VALUES (1); + } +} {0 {}} +do_test misc2-1.2 { + catchsql { + INSERT INTO foo(bar) VALUES (111); + } +} {1 aiieee} +} ;# endif trigger + +# Make sure ROWID works on a view and a subquery. Ticket #364 +# +do_test misc2-2.1 { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(1,2,3); + CREATE TABLE t2(a,b,c); + INSERT INTO t2 VALUES(7,8,9); + } +} {} +ifcapable subquery { + do_test misc2-2.2 { + execsql { + SELECT rowid, * FROM (SELECT * FROM t1, t2); + } + } {{} 1 2 3 7 8 9} +} +ifcapable view { + do_test misc2-2.3 { + execsql { + CREATE VIEW v1 AS SELECT * FROM t1, t2; + SELECT rowid, * FROM v1; + } + } {{} 1 2 3 7 8 9} +} ;# ifcapable view + +# Ticket #2002 and #1952. +ifcapable subquery { + do_test misc2-2.4 { + execsql2 { + SELECT * FROM (SELECT a, b AS 'a', c AS 'a', 4 AS 'a' FROM t1) + } + } {a 1 a:1 2 a:2 3 a:3 4} +} + +# Check name binding precedence. Ticket #387 +# +do_test misc2-3.1 { + catchsql { + SELECT t1.b+t2.b AS a, t1.a, t2.a FROM t1, t2 WHERE a==10 + } +} {1 {ambiguous column name: a}} + +# Make sure 32-bit integer overflow is handled properly in queries. +# ticket #408 +# +do_test misc2-4.1 { + execsql { + INSERT INTO t1 VALUES(4000000000,'a','b'); + SELECT a FROM t1 WHERE a>1; + } +} {4000000000} +do_test misc2-4.2 { + execsql { + INSERT INTO t1 VALUES(2147483648,'b2','c2'); + INSERT INTO t1 VALUES(2147483647,'b3','c3'); + SELECT a FROM t1 WHERE a>2147483647; + } +} {4000000000 2147483648} +do_test misc2-4.3 { + execsql { + SELECT a FROM t1 WHERE a<2147483648; + } +} {1 2147483647} +do_test misc2-4.4 { + execsql { + SELECT a FROM t1 WHERE a<=2147483648; + } +} {1 2147483648 2147483647} +do_test misc2-4.5 { + execsql { + SELECT a FROM t1 WHERE a<10000000000; + } +} {1 4000000000 2147483648 2147483647} +do_test misc2-4.6 { + execsql { + SELECT a FROM t1 WHERE a<1000000000000 ORDER BY 1; + } +} {1 2147483647 2147483648 4000000000} + +# There were some issues with expanding a SrcList object using a call +# to sqliteSrcListAppend() if the SrcList had previously been duplicated +# using a call to sqliteSrcListDup(). Ticket #416. The following test +# makes sure the problem has been fixed. +# +ifcapable view { +do_test misc2-5.1 { + execsql { + CREATE TABLE x(a,b); + CREATE VIEW y AS + SELECT x1.b AS p, x2.b AS q FROM x AS x1, x AS x2 WHERE x1.a=x2.a; + CREATE VIEW z AS + SELECT y1.p, y2.p FROM y AS y1, y AS y2 WHERE y1.q=y2.q; + SELECT * from z; + } +} {} +} + +# Make sure we can open a database with an empty filename. What this +# does is store the database in a temporary file that is deleted when +# the database is closed. Ticket #432. +# +do_test misc2-6.1 { + db close + sqlite3 db {} + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + SELECT * FROM t1; + } +} {1 2} + +# Make sure we get an error message (not a segfault) on an attempt to +# update a table from within the callback of a select on that same +# table. +# +# 2006-08-16: This has changed. It is now permitted to update +# the table being SELECTed from within the callback of the query. +# +ifcapable tclvar { + do_test misc2-7.1 { + db close + forcedelete test.db + sqlite3 db test.db + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + SELECT * FROM t1; + } + } {1 2 3} + do_test misc2-7.2 { + set rc [catch { + db eval {SELECT rowid FROM t1} {} { + db eval "DELETE FROM t1 WHERE rowid=$rowid" + } + } msg] + lappend rc $msg + } {0 {}} + do_test misc2-7.3 { + execsql {SELECT * FROM t1} + } {} + do_test misc2-7.4 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + } + db eval {SELECT rowid, x FROM t1} { + if {$x & 1} { + db eval {DELETE FROM t1 WHERE rowid=$rowid} + } + } + execsql {SELECT * FROM t1} + } {2 4} + do_test misc2-7.5 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + } + db eval {SELECT rowid, x FROM t1} { + if {$x & 1} { + db eval {DELETE FROM t1 WHERE rowid=$rowid+1} + } + } + execsql {SELECT * FROM t1} + } {1 3} + do_test misc2-7.6 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + } + db eval {SELECT rowid, x FROM t1} { + if {$x & 1} { + db eval {DELETE FROM t1} + } + } + execsql {SELECT * FROM t1} + } {} + do_test misc2-7.7 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + } + db eval {SELECT rowid, x FROM t1} { + if {$x & 1} { + db eval {UPDATE t1 SET x=x+100 WHERE rowid=$rowid} + } + } + execsql {SELECT * FROM t1} + } {101 2 103 4} + do_test misc2-7.8 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1); + } + db eval {SELECT rowid, x FROM t1} { + if {$x<10} { + db eval {INSERT INTO t1 VALUES($x+1)} + } + } + execsql {SELECT * FROM t1} + } {1 2 3 4 5 6 7 8 9 10} + + # Repeat the tests 7.1 through 7.8 about but this time do the SELECTs + # in reverse order so that we exercise the sqlite3BtreePrev() routine + # instead of sqlite3BtreeNext() + # + do_test misc2-7.11 { + db close + forcedelete test.db + sqlite3 db test.db + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + SELECT * FROM t1; + } + } {1 2 3} + do_test misc2-7.12 { + set rc [catch { + db eval {SELECT rowid FROM t1 ORDER BY rowid DESC} {} { + db eval "DELETE FROM t1 WHERE rowid=$rowid" + } + } msg] + lappend rc $msg + } {0 {}} + do_test misc2-7.13 { + execsql {SELECT * FROM t1} + } {} + do_test misc2-7.14 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + } + db eval {SELECT rowid, x FROM t1 ORDER BY rowid DESC} { + if {$x & 1} { + db eval {DELETE FROM t1 WHERE rowid=$rowid} + } + } + execsql {SELECT * FROM t1} + } {2 4} + do_test misc2-7.15 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + } + db eval {SELECT rowid, x FROM t1} { + if {$x & 1} { + db eval {DELETE FROM t1 WHERE rowid=$rowid+1} + } + } + execsql {SELECT * FROM t1} + } {1 3} + do_test misc2-7.16 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + } + db eval {SELECT rowid, x FROM t1 ORDER BY rowid DESC} { + if {$x & 1} { + db eval {DELETE FROM t1} + } + } + execsql {SELECT * FROM t1} + } {} + do_test misc2-7.17 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + } + db eval {SELECT rowid, x FROM t1 ORDER BY rowid DESC} { + if {$x & 1} { + db eval {UPDATE t1 SET x=x+100 WHERE rowid=$rowid} + } + } + execsql {SELECT * FROM t1} + } {101 2 103 4} + do_test misc2-7.18 { + execsql { + DELETE FROM t1; + INSERT INTO t1(rowid,x) VALUES(10,10); + } + db eval {SELECT rowid, x FROM t1 ORDER BY rowid DESC} { + if {$x>1} { + db eval {INSERT INTO t1(rowid,x) VALUES($x-1,$x-1)} + } + } + execsql {SELECT * FROM t1} + } {1 2 3 4 5 6 7 8 9 10} +} + +db close +forcedelete test.db +sqlite3 db test.db +catchsql { pragma recursive_triggers = off } + +# Ticket #453. If the SQL ended with "-", the tokenizer was calling that +# an incomplete token, which caused problem. The solution was to just call +# it a minus sign. +# +do_test misc2-8.1 { + catchsql {-} +} {1 {near "-": syntax error}} + +# Ticket #513. Make sure the VDBE stack does not grow on a 3-way join. +# +ifcapable tempdb { + do_test misc2-9.1 { + execsql { + BEGIN; + CREATE TABLE counts(n INTEGER PRIMARY KEY); + INSERT INTO counts VALUES(0); + INSERT INTO counts VALUES(1); + INSERT INTO counts SELECT n+2 FROM counts; + INSERT INTO counts SELECT n+4 FROM counts; + INSERT INTO counts SELECT n+8 FROM counts; + COMMIT; + + CREATE TEMP TABLE x AS + SELECT dim1.n, dim2.n, dim3.n + FROM counts AS dim1, counts AS dim2, counts AS dim3 + WHERE dim1.n<10 AND dim2.n<10 AND dim3.n<10; + + SELECT count(*) FROM x; + } + } {1000} + do_test misc2-9.2 { + execsql { + DROP TABLE x; + CREATE TEMP TABLE x AS + SELECT dim1.n, dim2.n, dim3.n + FROM counts AS dim1, counts AS dim2, counts AS dim3 + WHERE dim1.n>=6 AND dim2.n>=6 AND dim3.n>=6; + + SELECT count(*) FROM x; + } + } {1000} + do_test misc2-9.3 { + execsql { + DROP TABLE x; + CREATE TEMP TABLE x AS + SELECT dim1.n, dim2.n, dim3.n, dim4.n + FROM counts AS dim1, counts AS dim2, counts AS dim3, counts AS dim4 + WHERE dim1.n<5 AND dim2.n<5 AND dim3.n<5 AND dim4.n<5; + + SELECT count(*) FROM x; + } + } [expr 5*5*5*5] +} + +# Ticket #1229. Sometimes when a "NEW.X" appears in a SELECT without +# a FROM clause deep within a trigger, the code generator is unable to +# trace the NEW.X back to an original table and thus figure out its +# declared datatype. +# +# The SQL code below was causing a segfault. +# +ifcapable subquery&&trigger { + do_test misc2-10.1 { + execsql { + CREATE TABLE t1229(x); + CREATE TRIGGER r1229 BEFORE INSERT ON t1229 BEGIN + INSERT INTO t1229 SELECT y FROM (SELECT new.x y); + END; + INSERT INTO t1229 VALUES(1); + } + } {} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/misc3.test b/components/external/SQLite-3.8.1/test/misc3.test new file mode 100644 index 0000000000000000000000000000000000000000..81a8266b9c6875be62fe42daf377d666f0a8b8f1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/misc3.test @@ -0,0 +1,355 @@ +# 2003 December 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for miscellanous features that were +# left out of other test files. +# +# $Id: misc3.test,v 1.20 2009/05/06 00:49:01 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {integrityck} { + # Ticket #529. Make sure an ABORT does not damage the in-memory cache + # that will be used by subsequent statements in the same transaction. + # + do_test misc3-1.1 { + execsql { + CREATE TABLE t1(a UNIQUE,b); + INSERT INTO t1 + VALUES(1,'a23456789_b23456789_c23456789_d23456789_e23456789_'); + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + UPDATE t1 SET b=b||b; + INSERT INTO t1 VALUES(2,'x'); + UPDATE t1 SET b=substr(b,1,500); + BEGIN; + } + catchsql {UPDATE t1 SET a=CASE a WHEN 2 THEN 1 ELSE a END, b='y';} + execsql { + CREATE TABLE t2(x,y); + COMMIT; + PRAGMA integrity_check; + } + } ok +} +ifcapable {integrityck} { + do_test misc3-1.2 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + } + ifcapable {vacuum} {execsql VACUUM} + execsql { + CREATE TABLE t1(a UNIQUE,b); + INSERT INTO t1 + VALUES(1,'a23456789_b23456789_c23456789_d23456789_e23456789_'); + INSERT INTO t1 SELECT a+1, b||b FROM t1; + INSERT INTO t1 SELECT a+2, b||b FROM t1; + INSERT INTO t1 SELECT a+4, b FROM t1; + INSERT INTO t1 SELECT a+8, b FROM t1; + INSERT INTO t1 SELECT a+16, b FROM t1; + INSERT INTO t1 SELECT a+32, b FROM t1; + INSERT INTO t1 SELECT a+64, b FROM t1; + BEGIN; + } + catchsql {UPDATE t1 SET a=CASE a WHEN 128 THEN 127 ELSE a END, b='';} + execsql { + INSERT INTO t1 VALUES(200,'hello out there'); + COMMIT; + PRAGMA integrity_check; + } + } ok +} + +# Tests of the sqliteAtoF() function in util.c +# +do_test misc3-2.1 { + execsql {SELECT 2e-25*0.5e25} +} 1.0 +do_test misc3-2.2 { + execsql {SELECT 2.0e-25*000000.500000000000000000000000000000e+00025} +} 1.0 +do_test misc3-2.3 { + execsql {SELECT 000000000002e-0000000025*0.5e25} +} 1.0 +do_test misc3-2.4 { + execsql {SELECT 2e-25*0.5e250} +} 1e+225 +do_test misc3-2.5 { + execsql {SELECT 2.0e-250*0.5e25} +} 1e-225 +do_test misc3-2.6 { + execsql {SELECT '-2.0e-127' * '-0.5e27'} +} 1e-100 +do_test misc3-2.7 { + execsql {SELECT '+2.0e-127' * '-0.5e27'} +} -1e-100 +do_test misc3-2.8 { + execsql {SELECT 2.0e-27 * '+0.5e+127'} +} 1e+100 +do_test misc3-2.9 { + execsql {SELECT 2.0e-27 * '+0.000005e+132'} +} 1e+100 + +# Ticket #522. Make sure integer overflow is handled properly in +# indices. +# +integrity_check misc3-3.1 +do_test misc3-3.2 { + execsql { + CREATE TABLE t2(a INT UNIQUE); + } +} {} +integrity_check misc3-3.2.1 +do_test misc3-3.3 { + execsql { + INSERT INTO t2 VALUES(2147483648); + } +} {} +integrity_check misc3-3.3.1 +do_test misc3-3.4 { + execsql { + INSERT INTO t2 VALUES(-2147483649); + } +} {} +integrity_check misc3-3.4.1 +do_test misc3-3.5 { + execsql { + INSERT INTO t2 VALUES(+2147483649); + } +} {} +integrity_check misc3-3.5.1 +do_test misc3-3.6 { + execsql { + INSERT INTO t2 VALUES(+2147483647); + INSERT INTO t2 VALUES(-2147483648); + INSERT INTO t2 VALUES(-2147483647); + INSERT INTO t2 VALUES(2147483646); + SELECT * FROM t2 ORDER BY a; + } +} {-2147483649 -2147483648 -2147483647 2147483646 2147483647 2147483648 2147483649} +do_test misc3-3.7 { + execsql { + SELECT * FROM t2 WHERE a>=-2147483648 ORDER BY a; + } +} {-2147483648 -2147483647 2147483646 2147483647 2147483648 2147483649} +do_test misc3-3.8 { + execsql { + SELECT * FROM t2 WHERE a>-2147483648 ORDER BY a; + } +} {-2147483647 2147483646 2147483647 2147483648 2147483649} +do_test misc3-3.9 { + execsql { + SELECT * FROM t2 WHERE a>-2147483649 ORDER BY a; + } +} {-2147483648 -2147483647 2147483646 2147483647 2147483648 2147483649} +do_test misc3-3.10 { + execsql { + SELECT * FROM t2 WHERE a>=0 AND a<2147483649 ORDER BY a DESC; + } +} {2147483648 2147483647 2147483646} +do_test misc3-3.11 { + execsql { + SELECT * FROM t2 WHERE a>=0 AND a<=2147483648 ORDER BY a DESC; + } +} {2147483648 2147483647 2147483646} +do_test misc3-3.12 { + execsql { + SELECT * FROM t2 WHERE a>=0 AND a<2147483648 ORDER BY a DESC; + } +} {2147483647 2147483646} +do_test misc3-3.13 { + execsql { + SELECT * FROM t2 WHERE a>=0 AND a<=2147483647 ORDER BY a DESC; + } +} {2147483647 2147483646} +do_test misc3-3.14 { + execsql { + SELECT * FROM t2 WHERE a>=0 AND a<2147483647 ORDER BY a DESC; + } +} {2147483646} + +# Ticket #565. A stack overflow is occurring when the subquery to the +# right of an IN operator contains many NULLs +# +do_test misc3-4.1 { + execsql { + CREATE TABLE t3(a INTEGER PRIMARY KEY, b); + INSERT INTO t3(b) VALUES('abc'); + INSERT INTO t3(b) VALUES('xyz'); + INSERT INTO t3(b) VALUES(NULL); + INSERT INTO t3(b) VALUES(NULL); + INSERT INTO t3(b) SELECT b||'d' FROM t3; + INSERT INTO t3(b) SELECT b||'e' FROM t3; + INSERT INTO t3(b) SELECT b||'f' FROM t3; + INSERT INTO t3(b) SELECT b||'g' FROM t3; + INSERT INTO t3(b) SELECT b||'h' FROM t3; + SELECT count(a), count(b) FROM t3; + } +} {128 64} +ifcapable subquery { +do_test misc3-4.2 { + execsql { + SELECT count(a) FROM t3 WHERE b IN (SELECT b FROM t3); + } + } {64} + do_test misc3-4.3 { + execsql { + SELECT count(a) FROM t3 WHERE b IN (SELECT b FROM t3 ORDER BY a+1); + } + } {64} +} + +# Ticket #601: Putting a left join inside "SELECT * FROM ()" +# gives different results that if the outer "SELECT * FROM ..." is omitted. +# +ifcapable subquery { + do_test misc3-5.1 { + execsql { + CREATE TABLE x1 (b, c); + INSERT INTO x1 VALUES('dog',3); + INSERT INTO x1 VALUES('cat',1); + INSERT INTO x1 VALUES('dog',4); + CREATE TABLE x2 (c, e); + INSERT INTO x2 VALUES(1,'one'); + INSERT INTO x2 VALUES(2,'two'); + INSERT INTO x2 VALUES(3,'three'); + INSERT INTO x2 VALUES(4,'four'); + SELECT x2.c AS c, e, b FROM x2 LEFT JOIN + (SELECT b, max(c)+0 AS c FROM x1 GROUP BY b) + USING(c); + } + } {1 one cat 2 two {} 3 three {} 4 four dog} + do_test misc3-5.2 { + execsql { + SELECT * FROM ( + SELECT x2.c AS c, e, b FROM x2 LEFT JOIN + (SELECT b, max(c)+0 AS c FROM x1 GROUP BY b) + USING(c) + ); + } + } {1 one cat 2 two {} 3 three {} 4 four dog} +} + +ifcapable {explain} { + # Ticket #626: make sure EXPLAIN prevents BEGIN and COMMIT from working. + # + do_test misc3-6.1 { + execsql {EXPLAIN BEGIN} + catchsql {BEGIN} + } {0 {}} + do_test misc3-6.2 { + execsql {EXPLAIN COMMIT} + catchsql {COMMIT} + } {0 {}} + do_test misc3-6.3 { + execsql {BEGIN; EXPLAIN ROLLBACK} + catchsql {ROLLBACK} + } {0 {}} + + # Do some additional EXPLAIN operations to exercise the displayP4 logic. + do_test misc3-6.10 { + set x [execsql { + CREATE TABLE ex1( + a INTEGER DEFAULT 54321, + b TEXT DEFAULT "hello", + c REAL DEFAULT 3.1415926 + ); + CREATE UNIQUE INDEX ex1i1 ON ex1(a); + EXPLAIN REINDEX; + }] + ifcapable mergesort { + regexp { SorterCompare \d+ \d+ \d+ } $x + } else { + regexp { IsUnique \d+ \d+ \d+ \d+ } $x + } + } {1} + if {[regexp {16} [db one {PRAGMA encoding}]]} { + do_test misc3-6.11-utf16 { + set x [execsql { + EXPLAIN SELECT a+123456789012, b*4.5678, c FROM ex1 ORDER BY +a, b DESC + }] + set y [regexp { 123456789012 } $x] + lappend y [regexp { 4.5678 } $x] + lappend y [regexp {,-BINARY} $x] + } {1 1 1} + } else { + do_test misc3-6.11-utf8 { + set x [execsql { + EXPLAIN SELECT a+123456789012, b*4.5678, c FROM ex1 ORDER BY +a, b DESC + }] + set y [regexp { 123456789012 } $x] + lappend y [regexp { 4.5678 } $x] + lappend y [regexp { hello } $x] + lappend y [regexp {,-BINARY} $x] + } {1 1 1 1} + } +} + +ifcapable {trigger} { +# Ticket #640: vdbe stack overflow with a LIMIT clause on a SELECT inside +# of a trigger. +# +do_test misc3-7.1 { + execsql { + BEGIN; + CREATE TABLE y1(a); + CREATE TABLE y2(b); + CREATE TABLE y3(c); + CREATE TRIGGER r1 AFTER DELETE ON y1 FOR EACH ROW BEGIN + INSERT INTO y3(c) SELECT b FROM y2 ORDER BY b LIMIT 1; + END; + INSERT INTO y1 VALUES(1); + INSERT INTO y1 VALUES(2); + INSERT INTO y1 SELECT a+2 FROM y1; + INSERT INTO y1 SELECT a+4 FROM y1; + INSERT INTO y1 SELECT a+8 FROM y1; + INSERT INTO y1 SELECT a+16 FROM y1; + INSERT INTO y2 SELECT a FROM y1; + COMMIT; + SELECT count(*) FROM y1; + } +} 32 +do_test misc3-7.2 { + execsql { + DELETE FROM y1; + SELECT count(*) FROM y1; + } +} 0 +do_test misc3-7.3 { + execsql { + SELECT count(*) FROM y3; + } +} 32 +} ;# endif trigger + +# Ticket #668: VDBE stack overflow occurs when the left-hand side +# of an IN expression is NULL and the result is used as an integer, not +# as a jump. +# +ifcapable subquery { + do_test misc-8.1 { + execsql { + SELECT count(CASE WHEN b IN ('abc','xyz') THEN 'x' END) FROM t3 + } + } {2} + do_test misc-8.2 { + execsql { + SELECT count(*) FROM t3 WHERE 1+(b IN ('abc','xyz'))==2 + } + } {2} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/misc4.test b/components/external/SQLite-3.8.1/test/misc4.test new file mode 100644 index 0000000000000000000000000000000000000000..59c1d118ac7c5f785b5f4cd7101b0078c1f7f2b2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/misc4.test @@ -0,0 +1,211 @@ +# 2004 Jun 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for miscellanous features that were +# left out of other test files. +# +# $Id: misc4.test,v 1.23 2007/12/08 18:01:31 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Prepare a statement that will create a temporary table. Then do +# a rollback. Then try to execute the prepared statement. +# +do_test misc4-1.1 { + set DB [sqlite3_connection_pointer db] + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + } +} {} + +ifcapable tempdb { + do_test misc4-1.2 { + set sql {CREATE TEMP TABLE t2 AS SELECT * FROM t1} + set stmt [sqlite3_prepare $DB $sql -1 TAIL] + execsql { + BEGIN; + CREATE TABLE t3(a,b,c); + INSERT INTO t1 SELECT * FROM t1; + ROLLBACK; + } + } {} + + # Because the previous transaction included a DDL statement and + # was rolled back, statement $stmt was marked as expired. Executing it + # now returns SQLITE_SCHEMA. + do_test misc4-1.2.1 { + list [sqlite3_step $stmt] [sqlite3_finalize $stmt] + } {SQLITE_ERROR SQLITE_SCHEMA} + do_test misc4-1.2.2 { + set stmt [sqlite3_prepare $DB $sql -1 TAIL] + set TAIL + } {} + + do_test misc4-1.3 { + sqlite3_step $stmt + } SQLITE_DONE + do_test misc4-1.4 { + execsql { + SELECT * FROM temp.t2; + } + } {1} + + # Drop the temporary table, then rerun the prepared statement to + # recreate it again. This recreates ticket #807. + # + do_test misc4-1.5 { + execsql {DROP TABLE t2} + sqlite3_reset $stmt + sqlite3_step $stmt + } {SQLITE_ERROR} + do_test misc4-1.6 { + sqlite3_finalize $stmt + } {SQLITE_SCHEMA} +} + +# Prepare but do not execute various CREATE statements. Then before +# those statements are executed, try to use the tables, indices, views, +# are triggers that were created. +# +do_test misc4-2.1 { + set stmt [sqlite3_prepare $DB {CREATE TABLE t3(x);} -1 TAIL] + catchsql { + INSERT INTO t3 VALUES(1); + } +} {1 {no such table: t3}} +do_test misc4-2.2 { + sqlite3_step $stmt +} SQLITE_DONE +do_test misc4-2.3 { + sqlite3_finalize $stmt +} SQLITE_OK +do_test misc4-2.4 { + catchsql { + INSERT INTO t3 VALUES(1); + } +} {0 {}} + +# Ticket #966 +# +do_test misc4-3.1 { + execsql { + CREATE TABLE Table1(ID integer primary key, Value TEXT); + INSERT INTO Table1 VALUES(1, 'x'); + CREATE TABLE Table2(ID integer NOT NULL, Value TEXT); + INSERT INTO Table2 VALUES(1, 'z'); + INSERT INTO Table2 VALUES (1, 'a'); + } + catchsql { + SELECT ID, max(Value) FROM Table2 GROUP BY 1, 2 ORDER BY 1, 2; + } +} {1 {aggregate functions are not allowed in the GROUP BY clause}} +ifcapable compound { + do_test misc4-3.2 { + execsql { + SELECT ID, Value FROM Table1 + UNION SELECT ID, max(Value) FROM Table2 GROUP BY 1 + ORDER BY 1, 2; + } + } {1 x 1 z} + do_test misc4-3.3 { + catchsql { + SELECT ID, Value FROM Table1 + UNION SELECT ID, max(Value) FROM Table2 GROUP BY 1, 2 + ORDER BY 1, 2; + } + } {1 {aggregate functions are not allowed in the GROUP BY clause}} + do_test misc4-3.4 { + catchsql { + SELECT ID, max(Value) FROM Table2 GROUP BY 1, 2 + UNION SELECT ID, Value FROM Table1 + ORDER BY 1, 2; + } + } {1 {aggregate functions are not allowed in the GROUP BY clause}} +} ;# ifcapable compound + +# Ticket #1047. Make sure column types are preserved in subqueries. +# +ifcapable subquery { + do_test misc4-4.1 { + execsql { + create table a(key varchar, data varchar); + create table b(key varchar, period integer); + insert into a values('01','data01'); + insert into a values('+1','data+1'); + + insert into b values ('01',1); + insert into b values ('01',2); + insert into b values ('+1',3); + insert into b values ('+1',4); + + select a.*, x.* + from a, (select key,sum(period) from b group by key) as x + where a.key=x.key order by 1 desc; + } + } {01 data01 01 3 +1 data+1 +1 7} + + # This test case tests the same property as misc4-4.1, but it is + # a bit smaller which makes it easier to work with while debugging. + do_test misc4-4.2 { + execsql { + CREATE TABLE ab(a TEXT, b TEXT); + INSERT INTO ab VALUES('01', '1'); + } + execsql { + select * from ab, (select b from ab) as x where x.b = ab.a; + } + } {} +} + + +# Ticket #1036. When creating tables from a SELECT on a view, use the +# short names of columns. +# +ifcapable view { + do_test misc4-5.1 { + execsql { + create table t4(a,b); + create table t5(a,c); + insert into t4 values (1,2); + insert into t5 values (1,3); + create view myview as select t4.a a from t4 inner join t5 on t4.a=t5.a; + create table problem as select * from myview; + } + execsql2 { + select * FROM problem; + } + } {a 1} + do_test misc4-5.2 { + execsql2 { + create table t6 as select * from t4, t5; + select * from t6; + } + } {a 1 b 2 a:1 1 c 3} +} + +# Ticket #1086 +do_test misc4-6.1 { + execsql { + CREATE TABLE abc(a); + INSERT INTO abc VALUES(1); + CREATE TABLE def(d, e, f, PRIMARY KEY(d, e)); + } +} {} +do_test misc4-6.2 { + execsql { + SELECT a FROM abc LEFT JOIN def ON (abc.a=def.d); + } +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/misc5.test b/components/external/SQLite-3.8.1/test/misc5.test new file mode 100644 index 0000000000000000000000000000000000000000..14ba44ead0a1d239c2e81c5bcfa0e02416b28222 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/misc5.test @@ -0,0 +1,1874 @@ +# 2005 Mar 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for miscellanous features that were +# left out of other test files. +# +# $Id: misc5.test,v 1.22 2008/07/29 10:26:45 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build records using the MakeRecord opcode such that the size of the +# header is at the transition point in the size of a varint. +# +# This test causes an assertion failure or a buffer overrun in version +# 3.1.5 and earlier. +# +for {set i 120} {$i<140} {incr i} { + do_test misc5-1.$i { + catchsql {DROP TABLE t1} + set sql1 {CREATE TABLE t1} + set sql2 {INSERT INTO t1 VALUES} + set sep ( + for {set j 0} {$j<$i} {incr j} { + append sql1 ${sep}a$j + append sql2 ${sep}$j + set sep , + } + append sql1 {);} + append sql2 {);} + execsql $sql1$sql2 + } {} +} + +# Make sure large integers are stored correctly. +# +ifcapable conflict { + do_test misc5-2.1 { + execsql { + create table t2(x unique); + insert into t2 values(1); + insert or ignore into t2 select x*2 from t2; + insert or ignore into t2 select x*4 from t2; + insert or ignore into t2 select x*16 from t2; + insert or ignore into t2 select x*256 from t2; + insert or ignore into t2 select x*65536 from t2; + insert or ignore into t2 select x*2147483648 from t2; + insert or ignore into t2 select x-1 from t2; + insert or ignore into t2 select x+1 from t2; + insert or ignore into t2 select -x from t2; + select count(*) from t2; + } + } 371 +} else { + do_test misc5-2.1 { + execsql { + BEGIN; + create table t2(x unique); + create table t2_temp(x); + insert into t2_temp values(1); + insert into t2_temp select x*2 from t2_temp; + insert into t2_temp select x*4 from t2_temp; + insert into t2_temp select x*16 from t2_temp; + insert into t2_temp select x*256 from t2_temp; + insert into t2_temp select x*65536 from t2_temp; + insert into t2_temp select x*2147483648 from t2_temp; + insert into t2_temp select x-1 from t2_temp; + insert into t2_temp select x+1 from t2_temp; + insert into t2_temp select -x from t2_temp; + INSERT INTO t2 SELECT DISTINCT(x) FROM t2_temp; + DROP TABLE t2_temp; + COMMIT; + select count(*) from t2; + } + } 371 +} +do_test misc5-2.2 { + execsql { + select x from t2 order by x; + } +} \ +"-4611686018427387905\ +-4611686018427387904\ +-4611686018427387903\ +-2305843009213693953\ +-2305843009213693952\ +-2305843009213693951\ +-1152921504606846977\ +-1152921504606846976\ +-1152921504606846975\ +-576460752303423489\ +-576460752303423488\ +-576460752303423487\ +-288230376151711745\ +-288230376151711744\ +-288230376151711743\ +-144115188075855873\ +-144115188075855872\ +-144115188075855871\ +-72057594037927937\ +-72057594037927936\ +-72057594037927935\ +-36028797018963969\ +-36028797018963968\ +-36028797018963967\ +-18014398509481985\ +-18014398509481984\ +-18014398509481983\ +-9007199254740993\ +-9007199254740992\ +-9007199254740991\ +-4503599627370497\ +-4503599627370496\ +-4503599627370495\ +-2251799813685249\ +-2251799813685248\ +-2251799813685247\ +-1125899906842625\ +-1125899906842624\ +-1125899906842623\ +-562949953421313\ +-562949953421312\ +-562949953421311\ +-281474976710657\ +-281474976710656\ +-281474976710655\ +-140737488355329\ +-140737488355328\ +-140737488355327\ +-70368744177665\ +-70368744177664\ +-70368744177663\ +-35184372088833\ +-35184372088832\ +-35184372088831\ +-17592186044417\ +-17592186044416\ +-17592186044415\ +-8796093022209\ +-8796093022208\ +-8796093022207\ +-4398046511105\ +-4398046511104\ +-4398046511103\ +-2199023255553\ +-2199023255552\ +-2199023255551\ +-1099511627777\ +-1099511627776\ +-1099511627775\ +-549755813889\ +-549755813888\ +-549755813887\ +-274877906945\ +-274877906944\ +-274877906943\ +-137438953473\ +-137438953472\ +-137438953471\ +-68719476737\ +-68719476736\ +-68719476735\ +-34359738369\ +-34359738368\ +-34359738367\ +-17179869185\ +-17179869184\ +-17179869183\ +-8589934593\ +-8589934592\ +-8589934591\ +-4294967297\ +-4294967296\ +-4294967295\ +-2147483649\ +-2147483648\ +-2147483647\ +-1073741825\ +-1073741824\ +-1073741823\ +-536870913\ +-536870912\ +-536870911\ +-268435457\ +-268435456\ +-268435455\ +-134217729\ +-134217728\ +-134217727\ +-67108865\ +-67108864\ +-67108863\ +-33554433\ +-33554432\ +-33554431\ +-16777217\ +-16777216\ +-16777215\ +-8388609\ +-8388608\ +-8388607\ +-4194305\ +-4194304\ +-4194303\ +-2097153\ +-2097152\ +-2097151\ +-1048577\ +-1048576\ +-1048575\ +-524289\ +-524288\ +-524287\ +-262145\ +-262144\ +-262143\ +-131073\ +-131072\ +-131071\ +-65537\ +-65536\ +-65535\ +-32769\ +-32768\ +-32767\ +-16385\ +-16384\ +-16383\ +-8193\ +-8192\ +-8191\ +-4097\ +-4096\ +-4095\ +-2049\ +-2048\ +-2047\ +-1025\ +-1024\ +-1023\ +-513\ +-512\ +-511\ +-257\ +-256\ +-255\ +-129\ +-128\ +-127\ +-65\ +-64\ +-63\ +-33\ +-32\ +-31\ +-17\ +-16\ +-15\ +-9\ +-8\ +-7\ +-5\ +-4\ +-3\ +-2\ +-1\ +0\ +1\ +2\ +3\ +4\ +5\ +7\ +8\ +9\ +15\ +16\ +17\ +31\ +32\ +33\ +63\ +64\ +65\ +127\ +128\ +129\ +255\ +256\ +257\ +511\ +512\ +513\ +1023\ +1024\ +1025\ +2047\ +2048\ +2049\ +4095\ +4096\ +4097\ +8191\ +8192\ +8193\ +16383\ +16384\ +16385\ +32767\ +32768\ +32769\ +65535\ +65536\ +65537\ +131071\ +131072\ +131073\ +262143\ +262144\ +262145\ +524287\ +524288\ +524289\ +1048575\ +1048576\ +1048577\ +2097151\ +2097152\ +2097153\ +4194303\ +4194304\ +4194305\ +8388607\ +8388608\ +8388609\ +16777215\ +16777216\ +16777217\ +33554431\ +33554432\ +33554433\ +67108863\ +67108864\ +67108865\ +134217727\ +134217728\ +134217729\ +268435455\ +268435456\ +268435457\ +536870911\ +536870912\ +536870913\ +1073741823\ +1073741824\ +1073741825\ +2147483647\ +2147483648\ +2147483649\ +4294967295\ +4294967296\ +4294967297\ +8589934591\ +8589934592\ +8589934593\ +17179869183\ +17179869184\ +17179869185\ +34359738367\ +34359738368\ +34359738369\ +68719476735\ +68719476736\ +68719476737\ +137438953471\ +137438953472\ +137438953473\ +274877906943\ +274877906944\ +274877906945\ +549755813887\ +549755813888\ +549755813889\ +1099511627775\ +1099511627776\ +1099511627777\ +2199023255551\ +2199023255552\ +2199023255553\ +4398046511103\ +4398046511104\ +4398046511105\ +8796093022207\ +8796093022208\ +8796093022209\ +17592186044415\ +17592186044416\ +17592186044417\ +35184372088831\ +35184372088832\ +35184372088833\ +70368744177663\ +70368744177664\ +70368744177665\ +140737488355327\ +140737488355328\ +140737488355329\ +281474976710655\ +281474976710656\ +281474976710657\ +562949953421311\ +562949953421312\ +562949953421313\ +1125899906842623\ +1125899906842624\ +1125899906842625\ +2251799813685247\ +2251799813685248\ +2251799813685249\ +4503599627370495\ +4503599627370496\ +4503599627370497\ +9007199254740991\ +9007199254740992\ +9007199254740993\ +18014398509481983\ +18014398509481984\ +18014398509481985\ +36028797018963967\ +36028797018963968\ +36028797018963969\ +72057594037927935\ +72057594037927936\ +72057594037927937\ +144115188075855871\ +144115188075855872\ +144115188075855873\ +288230376151711743\ +288230376151711744\ +288230376151711745\ +576460752303423487\ +576460752303423488\ +576460752303423489\ +1152921504606846975\ +1152921504606846976\ +1152921504606846977\ +2305843009213693951\ +2305843009213693952\ +2305843009213693953\ +4611686018427387903\ +4611686018427387904\ +4611686018427387905" + +# Ticket #1210. Do proper reference counting of Table structures +# so that deeply nested SELECT statements can be flattened correctly. +# +ifcapable subquery { + do_test misc5-3.1 { + execsql { + CREATE TABLE songs(songid, artist, timesplayed); + INSERT INTO songs VALUES(1,'one',1); + INSERT INTO songs VALUES(2,'one',2); + INSERT INTO songs VALUES(3,'two',3); + INSERT INTO songs VALUES(4,'three',5); + INSERT INTO songs VALUES(5,'one',7); + INSERT INTO songs VALUES(6,'two',11); + SELECT DISTINCT artist + FROM ( + SELECT DISTINCT artist + FROM songs + WHERE songid IN ( + SELECT songid + FROM songs + WHERE LOWER(artist) = ( + -- This sub-query is indeterminate. Because there is no ORDER BY, + -- it may return 'one', 'two' or 'three'. Because of this, the + -- outermost parent query may correctly return any of 'one', 'two' + -- or 'three' as well. + SELECT DISTINCT LOWER(artist) + FROM ( + -- This sub-query returns the table: + -- + -- two 14 + -- one 10 + -- three 5 + -- + SELECT DISTINCT artist,sum(timesplayed) AS total + FROM songs + GROUP BY LOWER(artist) + ORDER BY total DESC + LIMIT 10 + ) + WHERE artist <> '' + ) + ) + ) + ORDER BY LOWER(artist) ASC; + } + } {two} +} + +# Ticket #1370. Do not overwrite small files (less than 1024 bytes) +# when trying to open them as a database. +# +if {[permutation] == ""} { + do_test misc5-4.1 { + db close + forcedelete test.db + set fd [open test.db w] + puts $fd "This is not really a database" + close $fd + sqlite3 db test.db + catchsql { + CREATE TABLE t1(a,b,c); + } + } {1 {file is encrypted or is not a database}} +} + +# Ticket #1371. Allow floating point numbers of the form .N or N. +# +do_test misc5-5.1 { + execsql {SELECT .1 } +} 0.1 +do_test misc5-5.2 { + execsql {SELECT 2. } +} 2.0 +do_test misc5-5.3 { + execsql {SELECT 3.e0 } +} 3.0 +do_test misc5-5.4 { + execsql {SELECT .4e+1} +} 4.0 + +# Ticket #1582. Ensure that an unknown table in a LIMIT clause applied to +# a UNION ALL query causes an error, not a crash. +# +db close +forcedelete test.db +sqlite3 db test.db +ifcapable subquery&&compound { + do_test misc5-6.1 { + catchsql { + SELECT * FROM sqlite_master + UNION ALL + SELECT * FROM sqlite_master + LIMIT (SELECT count(*) FROM blah); + } + } {1 {no such table: blah}} + do_test misc5-6.2 { + execsql { + CREATE TABLE logs(msg TEXT, timestamp INTEGER, dbtime TEXT); + } + catchsql { + SELECT * FROM logs WHERE logs.oid >= (SELECT head FROM logs_base) + UNION ALL + SELECT * FROM logs + LIMIT (SELECT lmt FROM logs_base) ; + } + } {1 {no such table: logs_base}} +} + +# Overflow the lemon parser stack by providing an overly complex +# expression. Make sure that the overflow is detected and reported. +# +do_test misc5-7.1 { + execsql {CREATE TABLE t1(x)} + set sql "INSERT INTO t1 VALUES(" + set tail "" + for {set i 0} {$i<200} {incr i} { + append sql "(1+" + append tail ")" + } + append sql 2$tail + catchsql $sql +} {1 {parser stack overflow}} + +# Ticket #1911 +# +ifcapable compound { + do_test misc5-9.1 { + execsql { + SELECT name, type FROM sqlite_master WHERE name IS NULL + UNION + SELECT type, name FROM sqlite_master WHERE type IS NULL + ORDER BY 1, 2, 1, 2, 1, 2 + } + } {} + do_test misc5-9.2 { + execsql { + SELECT name, type FROM sqlite_master WHERE name IS NULL + UNION + SELECT type, name FROM sqlite_master WHERE type IS NULL + ORDER BY 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 + } + } {} +} + +# Ticket #1912. Make the tokenizer require a space after a numeric +# literal. +# +do_test misc5-10.1 { + catchsql { + SELECT 123abc + } +} {1 {unrecognized token: "123abc"}} +do_test misc5-10.2 { + catchsql { + SELECT 1*123.4e5ghi; + } +} {1 {unrecognized token: "123.4e5ghi"}} + + +# Additional integer encoding tests. +# +do_test misc5-11.1 { + db eval { + CREATE TABLE t3(x); + INSERT INTO t3 VALUES(-18); + INSERT INTO t3 VALUES(-17); + INSERT INTO t3 VALUES(-16); + INSERT INTO t3 VALUES(-15); + INSERT INTO t3 VALUES(-14); + INSERT INTO t3 VALUES(-13); + INSERT INTO t3 VALUES(-12); + INSERT INTO t3 VALUES(-11); + INSERT INTO t3 VALUES(-10); + INSERT INTO t3 VALUES(-9); + INSERT INTO t3 VALUES(-8); + INSERT INTO t3 VALUES(-7); + INSERT INTO t3 VALUES(-6); + INSERT INTO t3 VALUES(-5); + INSERT INTO t3 VALUES(-4); + INSERT INTO t3 VALUES(-3); + INSERT INTO t3 VALUES(-2); + INSERT INTO t3 VALUES(-1); + INSERT INTO t3 VALUES(0); + INSERT INTO t3 VALUES(1); + INSERT INTO t3 VALUES(2); + INSERT INTO t3 VALUES(3); + INSERT INTO t3 VALUES(4); + INSERT INTO t3 VALUES(5); + INSERT INTO t3 VALUES(6); + INSERT INTO t3 VALUES(7); + INSERT INTO t3 VALUES(8); + INSERT INTO t3 VALUES(9); + INSERT INTO t3 VALUES(10); + INSERT INTO t3 VALUES(11); + INSERT INTO t3 VALUES(12); + INSERT INTO t3 VALUES(13); + INSERT INTO t3 VALUES(14); + INSERT INTO t3 VALUES(15); + INSERT INTO t3 VALUES(16); + INSERT INTO t3 VALUES(17); + INSERT INTO t3 VALUES(18); + INSERT INTO t3 VALUES(30); + INSERT INTO t3 VALUES(31); + INSERT INTO t3 VALUES(32); + INSERT INTO t3 VALUES(33); + INSERT INTO t3 VALUES(34); + INSERT INTO t3 VALUES(-30); + INSERT INTO t3 VALUES(-31); + INSERT INTO t3 VALUES(-32); + INSERT INTO t3 VALUES(-33); + INSERT INTO t3 VALUES(-34); + INSERT INTO t3 VALUES(62); + INSERT INTO t3 VALUES(63); + INSERT INTO t3 VALUES(64); + INSERT INTO t3 VALUES(65); + INSERT INTO t3 VALUES(66); + INSERT INTO t3 VALUES(-62); + INSERT INTO t3 VALUES(-63); + INSERT INTO t3 VALUES(-64); + INSERT INTO t3 VALUES(-65); + INSERT INTO t3 VALUES(-66); + INSERT INTO t3 VALUES(126); + INSERT INTO t3 VALUES(127); + INSERT INTO t3 VALUES(128); + INSERT INTO t3 VALUES(129); + INSERT INTO t3 VALUES(130); + INSERT INTO t3 VALUES(-126); + INSERT INTO t3 VALUES(-127); + INSERT INTO t3 VALUES(-128); + INSERT INTO t3 VALUES(-129); + INSERT INTO t3 VALUES(-130); + INSERT INTO t3 VALUES(254); + INSERT INTO t3 VALUES(255); + INSERT INTO t3 VALUES(256); + INSERT INTO t3 VALUES(257); + INSERT INTO t3 VALUES(258); + INSERT INTO t3 VALUES(-254); + INSERT INTO t3 VALUES(-255); + INSERT INTO t3 VALUES(-256); + INSERT INTO t3 VALUES(-257); + INSERT INTO t3 VALUES(-258); + INSERT INTO t3 VALUES(510); + INSERT INTO t3 VALUES(511); + INSERT INTO t3 VALUES(512); + INSERT INTO t3 VALUES(513); + INSERT INTO t3 VALUES(514); + INSERT INTO t3 VALUES(-510); + INSERT INTO t3 VALUES(-511); + INSERT INTO t3 VALUES(-512); + INSERT INTO t3 VALUES(-513); + INSERT INTO t3 VALUES(-514); + INSERT INTO t3 VALUES(1022); + INSERT INTO t3 VALUES(1023); + INSERT INTO t3 VALUES(1024); + INSERT INTO t3 VALUES(1025); + INSERT INTO t3 VALUES(1026); + INSERT INTO t3 VALUES(-1022); + INSERT INTO t3 VALUES(-1023); + INSERT INTO t3 VALUES(-1024); + INSERT INTO t3 VALUES(-1025); + INSERT INTO t3 VALUES(-1026); + INSERT INTO t3 VALUES(2046); + INSERT INTO t3 VALUES(2047); + INSERT INTO t3 VALUES(2048); + INSERT INTO t3 VALUES(2049); + INSERT INTO t3 VALUES(2050); + INSERT INTO t3 VALUES(-2046); + INSERT INTO t3 VALUES(-2047); + INSERT INTO t3 VALUES(-2048); + INSERT INTO t3 VALUES(-2049); + INSERT INTO t3 VALUES(-2050); + INSERT INTO t3 VALUES(4094); + INSERT INTO t3 VALUES(4095); + INSERT INTO t3 VALUES(4096); + INSERT INTO t3 VALUES(4097); + INSERT INTO t3 VALUES(4098); + INSERT INTO t3 VALUES(-4094); + INSERT INTO t3 VALUES(-4095); + INSERT INTO t3 VALUES(-4096); + INSERT INTO t3 VALUES(-4097); + INSERT INTO t3 VALUES(-4098); + INSERT INTO t3 VALUES(8190); + INSERT INTO t3 VALUES(8191); + INSERT INTO t3 VALUES(8192); + INSERT INTO t3 VALUES(8193); + INSERT INTO t3 VALUES(8194); + INSERT INTO t3 VALUES(-8190); + INSERT INTO t3 VALUES(-8191); + INSERT INTO t3 VALUES(-8192); + INSERT INTO t3 VALUES(-8193); + INSERT INTO t3 VALUES(-8194); + INSERT INTO t3 VALUES(16382); + INSERT INTO t3 VALUES(16383); + INSERT INTO t3 VALUES(16384); + INSERT INTO t3 VALUES(16385); + INSERT INTO t3 VALUES(16386); + INSERT INTO t3 VALUES(-16382); + INSERT INTO t3 VALUES(-16383); + INSERT INTO t3 VALUES(-16384); + INSERT INTO t3 VALUES(-16385); + INSERT INTO t3 VALUES(-16386); + INSERT INTO t3 VALUES(32766); + INSERT INTO t3 VALUES(32767); + INSERT INTO t3 VALUES(32768); + INSERT INTO t3 VALUES(32769); + INSERT INTO t3 VALUES(32770); + INSERT INTO t3 VALUES(-32766); + INSERT INTO t3 VALUES(-32767); + INSERT INTO t3 VALUES(-32768); + INSERT INTO t3 VALUES(-32769); + INSERT INTO t3 VALUES(-32770); + INSERT INTO t3 VALUES(65534); + INSERT INTO t3 VALUES(65535); + INSERT INTO t3 VALUES(65536); + INSERT INTO t3 VALUES(65537); + INSERT INTO t3 VALUES(65538); + INSERT INTO t3 VALUES(-65534); + INSERT INTO t3 VALUES(-65535); + INSERT INTO t3 VALUES(-65536); + INSERT INTO t3 VALUES(-65537); + INSERT INTO t3 VALUES(-65538); + INSERT INTO t3 VALUES(131070); + INSERT INTO t3 VALUES(131071); + INSERT INTO t3 VALUES(131072); + INSERT INTO t3 VALUES(131073); + INSERT INTO t3 VALUES(131074); + INSERT INTO t3 VALUES(-131070); + INSERT INTO t3 VALUES(-131071); + INSERT INTO t3 VALUES(-131072); + INSERT INTO t3 VALUES(-131073); + INSERT INTO t3 VALUES(-131074); + INSERT INTO t3 VALUES(262142); + INSERT INTO t3 VALUES(262143); + INSERT INTO t3 VALUES(262144); + INSERT INTO t3 VALUES(262145); + INSERT INTO t3 VALUES(262146); + INSERT INTO t3 VALUES(-262142); + INSERT INTO t3 VALUES(-262143); + INSERT INTO t3 VALUES(-262144); + INSERT INTO t3 VALUES(-262145); + INSERT INTO t3 VALUES(-262146); + INSERT INTO t3 VALUES(524286); + INSERT INTO t3 VALUES(524287); + INSERT INTO t3 VALUES(524288); + INSERT INTO t3 VALUES(524289); + INSERT INTO t3 VALUES(524290); + INSERT INTO t3 VALUES(-524286); + INSERT INTO t3 VALUES(-524287); + INSERT INTO t3 VALUES(-524288); + INSERT INTO t3 VALUES(-524289); + INSERT INTO t3 VALUES(-524290); + INSERT INTO t3 VALUES(1048574); + INSERT INTO t3 VALUES(1048575); + INSERT INTO t3 VALUES(1048576); + INSERT INTO t3 VALUES(1048577); + INSERT INTO t3 VALUES(1048578); + INSERT INTO t3 VALUES(-1048574); + INSERT INTO t3 VALUES(-1048575); + INSERT INTO t3 VALUES(-1048576); + INSERT INTO t3 VALUES(-1048577); + INSERT INTO t3 VALUES(-1048578); + INSERT INTO t3 VALUES(2097150); + INSERT INTO t3 VALUES(2097151); + INSERT INTO t3 VALUES(2097152); + INSERT INTO t3 VALUES(2097153); + INSERT INTO t3 VALUES(2097154); + INSERT INTO t3 VALUES(-2097150); + INSERT INTO t3 VALUES(-2097151); + INSERT INTO t3 VALUES(-2097152); + INSERT INTO t3 VALUES(-2097153); + INSERT INTO t3 VALUES(-2097154); + INSERT INTO t3 VALUES(4194302); + INSERT INTO t3 VALUES(4194303); + INSERT INTO t3 VALUES(4194304); + INSERT INTO t3 VALUES(4194305); + INSERT INTO t3 VALUES(4194306); + INSERT INTO t3 VALUES(-4194302); + INSERT INTO t3 VALUES(-4194303); + INSERT INTO t3 VALUES(-4194304); + INSERT INTO t3 VALUES(-4194305); + INSERT INTO t3 VALUES(-4194306); + INSERT INTO t3 VALUES(8388606); + INSERT INTO t3 VALUES(8388607); + INSERT INTO t3 VALUES(8388608); + INSERT INTO t3 VALUES(8388609); + INSERT INTO t3 VALUES(8388610); + INSERT INTO t3 VALUES(-8388606); + INSERT INTO t3 VALUES(-8388607); + INSERT INTO t3 VALUES(-8388608); + INSERT INTO t3 VALUES(-8388609); + INSERT INTO t3 VALUES(-8388610); + INSERT INTO t3 VALUES(16777214); + INSERT INTO t3 VALUES(16777215); + INSERT INTO t3 VALUES(16777216); + INSERT INTO t3 VALUES(16777217); + INSERT INTO t3 VALUES(16777218); + INSERT INTO t3 VALUES(-16777214); + INSERT INTO t3 VALUES(-16777215); + INSERT INTO t3 VALUES(-16777216); + INSERT INTO t3 VALUES(-16777217); + INSERT INTO t3 VALUES(-16777218); + INSERT INTO t3 VALUES(33554430); + INSERT INTO t3 VALUES(33554431); + INSERT INTO t3 VALUES(33554432); + INSERT INTO t3 VALUES(33554433); + INSERT INTO t3 VALUES(33554434); + INSERT INTO t3 VALUES(-33554430); + INSERT INTO t3 VALUES(-33554431); + INSERT INTO t3 VALUES(-33554432); + INSERT INTO t3 VALUES(-33554433); + INSERT INTO t3 VALUES(-33554434); + INSERT INTO t3 VALUES(67108862); + INSERT INTO t3 VALUES(67108863); + INSERT INTO t3 VALUES(67108864); + INSERT INTO t3 VALUES(67108865); + INSERT INTO t3 VALUES(67108866); + INSERT INTO t3 VALUES(-67108862); + INSERT INTO t3 VALUES(-67108863); + INSERT INTO t3 VALUES(-67108864); + INSERT INTO t3 VALUES(-67108865); + INSERT INTO t3 VALUES(-67108866); + INSERT INTO t3 VALUES(134217726); + INSERT INTO t3 VALUES(134217727); + INSERT INTO t3 VALUES(134217728); + INSERT INTO t3 VALUES(134217729); + INSERT INTO t3 VALUES(134217730); + INSERT INTO t3 VALUES(-134217726); + INSERT INTO t3 VALUES(-134217727); + INSERT INTO t3 VALUES(-134217728); + INSERT INTO t3 VALUES(-134217729); + INSERT INTO t3 VALUES(-134217730); + INSERT INTO t3 VALUES(268435454); + INSERT INTO t3 VALUES(268435455); + INSERT INTO t3 VALUES(268435456); + INSERT INTO t3 VALUES(268435457); + INSERT INTO t3 VALUES(268435458); + INSERT INTO t3 VALUES(-268435454); + INSERT INTO t3 VALUES(-268435455); + INSERT INTO t3 VALUES(-268435456); + INSERT INTO t3 VALUES(-268435457); + INSERT INTO t3 VALUES(-268435458); + INSERT INTO t3 VALUES(536870910); + INSERT INTO t3 VALUES(536870911); + INSERT INTO t3 VALUES(536870912); + INSERT INTO t3 VALUES(536870913); + INSERT INTO t3 VALUES(536870914); + INSERT INTO t3 VALUES(-536870910); + INSERT INTO t3 VALUES(-536870911); + INSERT INTO t3 VALUES(-536870912); + INSERT INTO t3 VALUES(-536870913); + INSERT INTO t3 VALUES(-536870914); + INSERT INTO t3 VALUES(1073741822); + INSERT INTO t3 VALUES(1073741823); + INSERT INTO t3 VALUES(1073741824); + INSERT INTO t3 VALUES(1073741825); + INSERT INTO t3 VALUES(1073741826); + INSERT INTO t3 VALUES(-1073741822); + INSERT INTO t3 VALUES(-1073741823); + INSERT INTO t3 VALUES(-1073741824); + INSERT INTO t3 VALUES(-1073741825); + INSERT INTO t3 VALUES(-1073741826); + INSERT INTO t3 VALUES(2147483646); + INSERT INTO t3 VALUES(2147483647); + INSERT INTO t3 VALUES(2147483648); + INSERT INTO t3 VALUES(2147483649); + INSERT INTO t3 VALUES(2147483650); + INSERT INTO t3 VALUES(-2147483646); + INSERT INTO t3 VALUES(-2147483647); + INSERT INTO t3 VALUES(-2147483648); + INSERT INTO t3 VALUES(-2147483649); + INSERT INTO t3 VALUES(-2147483650); + INSERT INTO t3 VALUES(4294967294); + INSERT INTO t3 VALUES(4294967295); + INSERT INTO t3 VALUES(4294967296); + INSERT INTO t3 VALUES(4294967297); + INSERT INTO t3 VALUES(4294967298); + INSERT INTO t3 VALUES(-4294967294); + INSERT INTO t3 VALUES(-4294967295); + INSERT INTO t3 VALUES(-4294967296); + INSERT INTO t3 VALUES(-4294967297); + INSERT INTO t3 VALUES(-4294967298); + INSERT INTO t3 VALUES(8589934590); + INSERT INTO t3 VALUES(8589934591); + INSERT INTO t3 VALUES(8589934592); + INSERT INTO t3 VALUES(8589934593); + INSERT INTO t3 VALUES(8589934594); + INSERT INTO t3 VALUES(-8589934590); + INSERT INTO t3 VALUES(-8589934591); + INSERT INTO t3 VALUES(-8589934592); + INSERT INTO t3 VALUES(-8589934593); + INSERT INTO t3 VALUES(-8589934594); + INSERT INTO t3 VALUES(17179869182); + INSERT INTO t3 VALUES(17179869183); + INSERT INTO t3 VALUES(17179869184); + INSERT INTO t3 VALUES(17179869185); + INSERT INTO t3 VALUES(17179869186); + INSERT INTO t3 VALUES(-17179869182); + INSERT INTO t3 VALUES(-17179869183); + INSERT INTO t3 VALUES(-17179869184); + INSERT INTO t3 VALUES(-17179869185); + INSERT INTO t3 VALUES(-17179869186); + INSERT INTO t3 VALUES(34359738366); + INSERT INTO t3 VALUES(34359738367); + INSERT INTO t3 VALUES(34359738368); + INSERT INTO t3 VALUES(34359738369); + INSERT INTO t3 VALUES(34359738370); + INSERT INTO t3 VALUES(-34359738366); + INSERT INTO t3 VALUES(-34359738367); + INSERT INTO t3 VALUES(-34359738368); + INSERT INTO t3 VALUES(-34359738369); + INSERT INTO t3 VALUES(-34359738370); + INSERT INTO t3 VALUES(68719476734); + INSERT INTO t3 VALUES(68719476735); + INSERT INTO t3 VALUES(68719476736); + INSERT INTO t3 VALUES(68719476737); + INSERT INTO t3 VALUES(68719476738); + INSERT INTO t3 VALUES(-68719476734); + INSERT INTO t3 VALUES(-68719476735); + INSERT INTO t3 VALUES(-68719476736); + INSERT INTO t3 VALUES(-68719476737); + INSERT INTO t3 VALUES(-68719476738); + INSERT INTO t3 VALUES(137438953470); + INSERT INTO t3 VALUES(137438953471); + INSERT INTO t3 VALUES(137438953472); + INSERT INTO t3 VALUES(137438953473); + INSERT INTO t3 VALUES(137438953474); + INSERT INTO t3 VALUES(-137438953470); + INSERT INTO t3 VALUES(-137438953471); + INSERT INTO t3 VALUES(-137438953472); + INSERT INTO t3 VALUES(-137438953473); + INSERT INTO t3 VALUES(-137438953474); + INSERT INTO t3 VALUES(274877906942); + INSERT INTO t3 VALUES(274877906943); + INSERT INTO t3 VALUES(274877906944); + INSERT INTO t3 VALUES(274877906945); + INSERT INTO t3 VALUES(274877906946); + INSERT INTO t3 VALUES(-274877906942); + INSERT INTO t3 VALUES(-274877906943); + INSERT INTO t3 VALUES(-274877906944); + INSERT INTO t3 VALUES(-274877906945); + INSERT INTO t3 VALUES(-274877906946); + INSERT INTO t3 VALUES(549755813886); + INSERT INTO t3 VALUES(549755813887); + INSERT INTO t3 VALUES(549755813888); + INSERT INTO t3 VALUES(549755813889); + INSERT INTO t3 VALUES(549755813890); + INSERT INTO t3 VALUES(-549755813886); + INSERT INTO t3 VALUES(-549755813887); + INSERT INTO t3 VALUES(-549755813888); + INSERT INTO t3 VALUES(-549755813889); + INSERT INTO t3 VALUES(-549755813890); + INSERT INTO t3 VALUES(1099511627774); + INSERT INTO t3 VALUES(1099511627775); + INSERT INTO t3 VALUES(1099511627776); + INSERT INTO t3 VALUES(1099511627777); + INSERT INTO t3 VALUES(1099511627778); + INSERT INTO t3 VALUES(-1099511627774); + INSERT INTO t3 VALUES(-1099511627775); + INSERT INTO t3 VALUES(-1099511627776); + INSERT INTO t3 VALUES(-1099511627777); + INSERT INTO t3 VALUES(-1099511627778); + INSERT INTO t3 VALUES(2199023255550); + INSERT INTO t3 VALUES(2199023255551); + INSERT INTO t3 VALUES(2199023255552); + INSERT INTO t3 VALUES(2199023255553); + INSERT INTO t3 VALUES(2199023255554); + INSERT INTO t3 VALUES(-2199023255550); + INSERT INTO t3 VALUES(-2199023255551); + INSERT INTO t3 VALUES(-2199023255552); + INSERT INTO t3 VALUES(-2199023255553); + INSERT INTO t3 VALUES(-2199023255554); + INSERT INTO t3 VALUES(4398046511102); + INSERT INTO t3 VALUES(4398046511103); + INSERT INTO t3 VALUES(4398046511104); + INSERT INTO t3 VALUES(4398046511105); + INSERT INTO t3 VALUES(4398046511106); + INSERT INTO t3 VALUES(-4398046511102); + INSERT INTO t3 VALUES(-4398046511103); + INSERT INTO t3 VALUES(-4398046511104); + INSERT INTO t3 VALUES(-4398046511105); + INSERT INTO t3 VALUES(-4398046511106); + INSERT INTO t3 VALUES(8796093022206); + INSERT INTO t3 VALUES(8796093022207); + INSERT INTO t3 VALUES(8796093022208); + INSERT INTO t3 VALUES(8796093022209); + INSERT INTO t3 VALUES(8796093022210); + INSERT INTO t3 VALUES(-8796093022206); + INSERT INTO t3 VALUES(-8796093022207); + INSERT INTO t3 VALUES(-8796093022208); + INSERT INTO t3 VALUES(-8796093022209); + INSERT INTO t3 VALUES(-8796093022210); + INSERT INTO t3 VALUES(17592186044414); + INSERT INTO t3 VALUES(17592186044415); + INSERT INTO t3 VALUES(17592186044416); + INSERT INTO t3 VALUES(17592186044417); + INSERT INTO t3 VALUES(17592186044418); + INSERT INTO t3 VALUES(-17592186044414); + INSERT INTO t3 VALUES(-17592186044415); + INSERT INTO t3 VALUES(-17592186044416); + INSERT INTO t3 VALUES(-17592186044417); + INSERT INTO t3 VALUES(-17592186044418); + INSERT INTO t3 VALUES(35184372088830); + INSERT INTO t3 VALUES(35184372088831); + INSERT INTO t3 VALUES(35184372088832); + INSERT INTO t3 VALUES(35184372088833); + INSERT INTO t3 VALUES(35184372088834); + INSERT INTO t3 VALUES(-35184372088830); + INSERT INTO t3 VALUES(-35184372088831); + INSERT INTO t3 VALUES(-35184372088832); + INSERT INTO t3 VALUES(-35184372088833); + INSERT INTO t3 VALUES(-35184372088834); + INSERT INTO t3 VALUES(70368744177662); + INSERT INTO t3 VALUES(70368744177663); + INSERT INTO t3 VALUES(70368744177664); + INSERT INTO t3 VALUES(70368744177665); + INSERT INTO t3 VALUES(70368744177666); + INSERT INTO t3 VALUES(-70368744177662); + INSERT INTO t3 VALUES(-70368744177663); + INSERT INTO t3 VALUES(-70368744177664); + INSERT INTO t3 VALUES(-70368744177665); + INSERT INTO t3 VALUES(-70368744177666); + INSERT INTO t3 VALUES(140737488355326); + INSERT INTO t3 VALUES(140737488355327); + INSERT INTO t3 VALUES(140737488355328); + INSERT INTO t3 VALUES(140737488355329); + INSERT INTO t3 VALUES(140737488355330); + INSERT INTO t3 VALUES(-140737488355326); + INSERT INTO t3 VALUES(-140737488355327); + INSERT INTO t3 VALUES(-140737488355328); + INSERT INTO t3 VALUES(-140737488355329); + INSERT INTO t3 VALUES(-140737488355330); + INSERT INTO t3 VALUES(281474976710654); + INSERT INTO t3 VALUES(281474976710655); + INSERT INTO t3 VALUES(281474976710656); + INSERT INTO t3 VALUES(281474976710657); + INSERT INTO t3 VALUES(281474976710658); + INSERT INTO t3 VALUES(-281474976710654); + INSERT INTO t3 VALUES(-281474976710655); + INSERT INTO t3 VALUES(-281474976710656); + INSERT INTO t3 VALUES(-281474976710657); + INSERT INTO t3 VALUES(-281474976710658); + INSERT INTO t3 VALUES(562949953421310); + INSERT INTO t3 VALUES(562949953421311); + INSERT INTO t3 VALUES(562949953421312); + INSERT INTO t3 VALUES(562949953421313); + INSERT INTO t3 VALUES(562949953421314); + INSERT INTO t3 VALUES(-562949953421310); + INSERT INTO t3 VALUES(-562949953421311); + INSERT INTO t3 VALUES(-562949953421312); + INSERT INTO t3 VALUES(-562949953421313); + INSERT INTO t3 VALUES(-562949953421314); + INSERT INTO t3 VALUES(1125899906842622); + INSERT INTO t3 VALUES(1125899906842623); + INSERT INTO t3 VALUES(1125899906842624); + INSERT INTO t3 VALUES(1125899906842625); + INSERT INTO t3 VALUES(1125899906842626); + INSERT INTO t3 VALUES(-1125899906842622); + INSERT INTO t3 VALUES(-1125899906842623); + INSERT INTO t3 VALUES(-1125899906842624); + INSERT INTO t3 VALUES(-1125899906842625); + INSERT INTO t3 VALUES(-1125899906842626); + INSERT INTO t3 VALUES(2251799813685246); + INSERT INTO t3 VALUES(2251799813685247); + INSERT INTO t3 VALUES(2251799813685248); + INSERT INTO t3 VALUES(2251799813685249); + INSERT INTO t3 VALUES(2251799813685250); + INSERT INTO t3 VALUES(-2251799813685246); + INSERT INTO t3 VALUES(-2251799813685247); + INSERT INTO t3 VALUES(-2251799813685248); + INSERT INTO t3 VALUES(-2251799813685249); + INSERT INTO t3 VALUES(-2251799813685250); + INSERT INTO t3 VALUES(4503599627370494); + INSERT INTO t3 VALUES(4503599627370495); + INSERT INTO t3 VALUES(4503599627370496); + INSERT INTO t3 VALUES(4503599627370497); + INSERT INTO t3 VALUES(4503599627370498); + INSERT INTO t3 VALUES(-4503599627370494); + INSERT INTO t3 VALUES(-4503599627370495); + INSERT INTO t3 VALUES(-4503599627370496); + INSERT INTO t3 VALUES(-4503599627370497); + INSERT INTO t3 VALUES(-4503599627370498); + INSERT INTO t3 VALUES(9007199254740990); + INSERT INTO t3 VALUES(9007199254740991); + INSERT INTO t3 VALUES(9007199254740992); + INSERT INTO t3 VALUES(9007199254740993); + INSERT INTO t3 VALUES(9007199254740994); + INSERT INTO t3 VALUES(-9007199254740990); + INSERT INTO t3 VALUES(-9007199254740991); + INSERT INTO t3 VALUES(-9007199254740992); + INSERT INTO t3 VALUES(-9007199254740993); + INSERT INTO t3 VALUES(-9007199254740994); + INSERT INTO t3 VALUES(18014398509481982); + INSERT INTO t3 VALUES(18014398509481983); + INSERT INTO t3 VALUES(18014398509481984); + INSERT INTO t3 VALUES(18014398509481985); + INSERT INTO t3 VALUES(18014398509481986); + INSERT INTO t3 VALUES(-18014398509481982); + INSERT INTO t3 VALUES(-18014398509481983); + INSERT INTO t3 VALUES(-18014398509481984); + INSERT INTO t3 VALUES(-18014398509481985); + INSERT INTO t3 VALUES(-18014398509481986); + INSERT INTO t3 VALUES(36028797018963966); + INSERT INTO t3 VALUES(36028797018963967); + INSERT INTO t3 VALUES(36028797018963968); + INSERT INTO t3 VALUES(36028797018963969); + INSERT INTO t3 VALUES(36028797018963970); + INSERT INTO t3 VALUES(-36028797018963966); + INSERT INTO t3 VALUES(-36028797018963967); + INSERT INTO t3 VALUES(-36028797018963968); + INSERT INTO t3 VALUES(-36028797018963969); + INSERT INTO t3 VALUES(-36028797018963970); + INSERT INTO t3 VALUES(72057594037927934); + INSERT INTO t3 VALUES(72057594037927935); + INSERT INTO t3 VALUES(72057594037927936); + INSERT INTO t3 VALUES(72057594037927937); + INSERT INTO t3 VALUES(72057594037927938); + INSERT INTO t3 VALUES(-72057594037927934); + INSERT INTO t3 VALUES(-72057594037927935); + INSERT INTO t3 VALUES(-72057594037927936); + INSERT INTO t3 VALUES(-72057594037927937); + INSERT INTO t3 VALUES(-72057594037927938); + INSERT INTO t3 VALUES(144115188075855870); + INSERT INTO t3 VALUES(144115188075855871); + INSERT INTO t3 VALUES(144115188075855872); + INSERT INTO t3 VALUES(144115188075855873); + INSERT INTO t3 VALUES(144115188075855874); + INSERT INTO t3 VALUES(-144115188075855870); + INSERT INTO t3 VALUES(-144115188075855871); + INSERT INTO t3 VALUES(-144115188075855872); + INSERT INTO t3 VALUES(-144115188075855873); + INSERT INTO t3 VALUES(-144115188075855874); + INSERT INTO t3 VALUES(288230376151711742); + INSERT INTO t3 VALUES(288230376151711743); + INSERT INTO t3 VALUES(288230376151711744); + INSERT INTO t3 VALUES(288230376151711745); + INSERT INTO t3 VALUES(288230376151711746); + INSERT INTO t3 VALUES(-288230376151711742); + INSERT INTO t3 VALUES(-288230376151711743); + INSERT INTO t3 VALUES(-288230376151711744); + INSERT INTO t3 VALUES(-288230376151711745); + INSERT INTO t3 VALUES(-288230376151711746); + INSERT INTO t3 VALUES(576460752303423486); + INSERT INTO t3 VALUES(576460752303423487); + INSERT INTO t3 VALUES(576460752303423488); + INSERT INTO t3 VALUES(576460752303423489); + INSERT INTO t3 VALUES(576460752303423490); + INSERT INTO t3 VALUES(-576460752303423486); + INSERT INTO t3 VALUES(-576460752303423487); + INSERT INTO t3 VALUES(-576460752303423488); + INSERT INTO t3 VALUES(-576460752303423489); + INSERT INTO t3 VALUES(-576460752303423490); + INSERT INTO t3 VALUES(1152921504606846974); + INSERT INTO t3 VALUES(1152921504606846975); + INSERT INTO t3 VALUES(1152921504606846976); + INSERT INTO t3 VALUES(1152921504606846977); + INSERT INTO t3 VALUES(1152921504606846978); + INSERT INTO t3 VALUES(-1152921504606846974); + INSERT INTO t3 VALUES(-1152921504606846975); + INSERT INTO t3 VALUES(-1152921504606846976); + INSERT INTO t3 VALUES(-1152921504606846977); + INSERT INTO t3 VALUES(-1152921504606846978); + INSERT INTO t3 VALUES(2305843009213693950); + INSERT INTO t3 VALUES(2305843009213693951); + INSERT INTO t3 VALUES(2305843009213693952); + INSERT INTO t3 VALUES(2305843009213693953); + INSERT INTO t3 VALUES(2305843009213693954); + INSERT INTO t3 VALUES(-2305843009213693950); + INSERT INTO t3 VALUES(-2305843009213693951); + INSERT INTO t3 VALUES(-2305843009213693952); + INSERT INTO t3 VALUES(-2305843009213693953); + INSERT INTO t3 VALUES(-2305843009213693954); + INSERT INTO t3 VALUES(4611686018427387902); + INSERT INTO t3 VALUES(4611686018427387903); + INSERT INTO t3 VALUES(4611686018427387904); + INSERT INTO t3 VALUES(4611686018427387905); + INSERT INTO t3 VALUES(4611686018427387906); + INSERT INTO t3 VALUES(-4611686018427387902); + INSERT INTO t3 VALUES(-4611686018427387903); + INSERT INTO t3 VALUES(-4611686018427387904); + INSERT INTO t3 VALUES(-4611686018427387905); + INSERT INTO t3 VALUES(-4611686018427387906); + INSERT INTO t3 VALUES(9223372036854775806); + INSERT INTO t3 VALUES(9223372036854775807); + INSERT INTO t3 VALUES(-9223372036854775806); + INSERT INTO t3 VALUES(-9223372036854775807); + INSERT INTO t3 VALUES(-9223372036854775808); + SELECT x FROM t3 ORDER BY x; + } +} {-9223372036854775808\ +-9223372036854775807\ +-9223372036854775806\ +-4611686018427387906\ +-4611686018427387905\ +-4611686018427387904\ +-4611686018427387903\ +-4611686018427387902\ +-2305843009213693954\ +-2305843009213693953\ +-2305843009213693952\ +-2305843009213693951\ +-2305843009213693950\ +-1152921504606846978\ +-1152921504606846977\ +-1152921504606846976\ +-1152921504606846975\ +-1152921504606846974\ +-576460752303423490\ +-576460752303423489\ +-576460752303423488\ +-576460752303423487\ +-576460752303423486\ +-288230376151711746\ +-288230376151711745\ +-288230376151711744\ +-288230376151711743\ +-288230376151711742\ +-144115188075855874\ +-144115188075855873\ +-144115188075855872\ +-144115188075855871\ +-144115188075855870\ +-72057594037927938\ +-72057594037927937\ +-72057594037927936\ +-72057594037927935\ +-72057594037927934\ +-36028797018963970\ +-36028797018963969\ +-36028797018963968\ +-36028797018963967\ +-36028797018963966\ +-18014398509481986\ +-18014398509481985\ +-18014398509481984\ +-18014398509481983\ +-18014398509481982\ +-9007199254740994\ +-9007199254740993\ +-9007199254740992\ +-9007199254740991\ +-9007199254740990\ +-4503599627370498\ +-4503599627370497\ +-4503599627370496\ +-4503599627370495\ +-4503599627370494\ +-2251799813685250\ +-2251799813685249\ +-2251799813685248\ +-2251799813685247\ +-2251799813685246\ +-1125899906842626\ +-1125899906842625\ +-1125899906842624\ +-1125899906842623\ +-1125899906842622\ +-562949953421314\ +-562949953421313\ +-562949953421312\ +-562949953421311\ +-562949953421310\ +-281474976710658\ +-281474976710657\ +-281474976710656\ +-281474976710655\ +-281474976710654\ +-140737488355330\ +-140737488355329\ +-140737488355328\ +-140737488355327\ +-140737488355326\ +-70368744177666\ +-70368744177665\ +-70368744177664\ +-70368744177663\ +-70368744177662\ +-35184372088834\ +-35184372088833\ +-35184372088832\ +-35184372088831\ +-35184372088830\ +-17592186044418\ +-17592186044417\ +-17592186044416\ +-17592186044415\ +-17592186044414\ +-8796093022210\ +-8796093022209\ +-8796093022208\ +-8796093022207\ +-8796093022206\ +-4398046511106\ +-4398046511105\ +-4398046511104\ +-4398046511103\ +-4398046511102\ +-2199023255554\ +-2199023255553\ +-2199023255552\ +-2199023255551\ +-2199023255550\ +-1099511627778\ +-1099511627777\ +-1099511627776\ +-1099511627775\ +-1099511627774\ +-549755813890\ +-549755813889\ +-549755813888\ +-549755813887\ +-549755813886\ +-274877906946\ +-274877906945\ +-274877906944\ +-274877906943\ +-274877906942\ +-137438953474\ +-137438953473\ +-137438953472\ +-137438953471\ +-137438953470\ +-68719476738\ +-68719476737\ +-68719476736\ +-68719476735\ +-68719476734\ +-34359738370\ +-34359738369\ +-34359738368\ +-34359738367\ +-34359738366\ +-17179869186\ +-17179869185\ +-17179869184\ +-17179869183\ +-17179869182\ +-8589934594\ +-8589934593\ +-8589934592\ +-8589934591\ +-8589934590\ +-4294967298\ +-4294967297\ +-4294967296\ +-4294967295\ +-4294967294\ +-2147483650\ +-2147483649\ +-2147483648\ +-2147483647\ +-2147483646\ +-1073741826\ +-1073741825\ +-1073741824\ +-1073741823\ +-1073741822\ +-536870914\ +-536870913\ +-536870912\ +-536870911\ +-536870910\ +-268435458\ +-268435457\ +-268435456\ +-268435455\ +-268435454\ +-134217730\ +-134217729\ +-134217728\ +-134217727\ +-134217726\ +-67108866\ +-67108865\ +-67108864\ +-67108863\ +-67108862\ +-33554434\ +-33554433\ +-33554432\ +-33554431\ +-33554430\ +-16777218\ +-16777217\ +-16777216\ +-16777215\ +-16777214\ +-8388610\ +-8388609\ +-8388608\ +-8388607\ +-8388606\ +-4194306\ +-4194305\ +-4194304\ +-4194303\ +-4194302\ +-2097154\ +-2097153\ +-2097152\ +-2097151\ +-2097150\ +-1048578\ +-1048577\ +-1048576\ +-1048575\ +-1048574\ +-524290\ +-524289\ +-524288\ +-524287\ +-524286\ +-262146\ +-262145\ +-262144\ +-262143\ +-262142\ +-131074\ +-131073\ +-131072\ +-131071\ +-131070\ +-65538\ +-65537\ +-65536\ +-65535\ +-65534\ +-32770\ +-32769\ +-32768\ +-32767\ +-32766\ +-16386\ +-16385\ +-16384\ +-16383\ +-16382\ +-8194\ +-8193\ +-8192\ +-8191\ +-8190\ +-4098\ +-4097\ +-4096\ +-4095\ +-4094\ +-2050\ +-2049\ +-2048\ +-2047\ +-2046\ +-1026\ +-1025\ +-1024\ +-1023\ +-1022\ +-514\ +-513\ +-512\ +-511\ +-510\ +-258\ +-257\ +-256\ +-255\ +-254\ +-130\ +-129\ +-128\ +-127\ +-126\ +-66\ +-65\ +-64\ +-63\ +-62\ +-34\ +-33\ +-32\ +-31\ +-30\ +-18\ +-17\ +-16\ +-15\ +-14\ +-13\ +-12\ +-11\ +-10\ +-9\ +-8\ +-7\ +-6\ +-5\ +-4\ +-3\ +-2\ +-1\ +0\ +1\ +2\ +3\ +4\ +5\ +6\ +7\ +8\ +9\ +10\ +11\ +12\ +13\ +14\ +15\ +16\ +17\ +18\ +30\ +31\ +32\ +33\ +34\ +62\ +63\ +64\ +65\ +66\ +126\ +127\ +128\ +129\ +130\ +254\ +255\ +256\ +257\ +258\ +510\ +511\ +512\ +513\ +514\ +1022\ +1023\ +1024\ +1025\ +1026\ +2046\ +2047\ +2048\ +2049\ +2050\ +4094\ +4095\ +4096\ +4097\ +4098\ +8190\ +8191\ +8192\ +8193\ +8194\ +16382\ +16383\ +16384\ +16385\ +16386\ +32766\ +32767\ +32768\ +32769\ +32770\ +65534\ +65535\ +65536\ +65537\ +65538\ +131070\ +131071\ +131072\ +131073\ +131074\ +262142\ +262143\ +262144\ +262145\ +262146\ +524286\ +524287\ +524288\ +524289\ +524290\ +1048574\ +1048575\ +1048576\ +1048577\ +1048578\ +2097150\ +2097151\ +2097152\ +2097153\ +2097154\ +4194302\ +4194303\ +4194304\ +4194305\ +4194306\ +8388606\ +8388607\ +8388608\ +8388609\ +8388610\ +16777214\ +16777215\ +16777216\ +16777217\ +16777218\ +33554430\ +33554431\ +33554432\ +33554433\ +33554434\ +67108862\ +67108863\ +67108864\ +67108865\ +67108866\ +134217726\ +134217727\ +134217728\ +134217729\ +134217730\ +268435454\ +268435455\ +268435456\ +268435457\ +268435458\ +536870910\ +536870911\ +536870912\ +536870913\ +536870914\ +1073741822\ +1073741823\ +1073741824\ +1073741825\ +1073741826\ +2147483646\ +2147483647\ +2147483648\ +2147483649\ +2147483650\ +4294967294\ +4294967295\ +4294967296\ +4294967297\ +4294967298\ +8589934590\ +8589934591\ +8589934592\ +8589934593\ +8589934594\ +17179869182\ +17179869183\ +17179869184\ +17179869185\ +17179869186\ +34359738366\ +34359738367\ +34359738368\ +34359738369\ +34359738370\ +68719476734\ +68719476735\ +68719476736\ +68719476737\ +68719476738\ +137438953470\ +137438953471\ +137438953472\ +137438953473\ +137438953474\ +274877906942\ +274877906943\ +274877906944\ +274877906945\ +274877906946\ +549755813886\ +549755813887\ +549755813888\ +549755813889\ +549755813890\ +1099511627774\ +1099511627775\ +1099511627776\ +1099511627777\ +1099511627778\ +2199023255550\ +2199023255551\ +2199023255552\ +2199023255553\ +2199023255554\ +4398046511102\ +4398046511103\ +4398046511104\ +4398046511105\ +4398046511106\ +8796093022206\ +8796093022207\ +8796093022208\ +8796093022209\ +8796093022210\ +17592186044414\ +17592186044415\ +17592186044416\ +17592186044417\ +17592186044418\ +35184372088830\ +35184372088831\ +35184372088832\ +35184372088833\ +35184372088834\ +70368744177662\ +70368744177663\ +70368744177664\ +70368744177665\ +70368744177666\ +140737488355326\ +140737488355327\ +140737488355328\ +140737488355329\ +140737488355330\ +281474976710654\ +281474976710655\ +281474976710656\ +281474976710657\ +281474976710658\ +562949953421310\ +562949953421311\ +562949953421312\ +562949953421313\ +562949953421314\ +1125899906842622\ +1125899906842623\ +1125899906842624\ +1125899906842625\ +1125899906842626\ +2251799813685246\ +2251799813685247\ +2251799813685248\ +2251799813685249\ +2251799813685250\ +4503599627370494\ +4503599627370495\ +4503599627370496\ +4503599627370497\ +4503599627370498\ +9007199254740990\ +9007199254740991\ +9007199254740992\ +9007199254740993\ +9007199254740994\ +18014398509481982\ +18014398509481983\ +18014398509481984\ +18014398509481985\ +18014398509481986\ +36028797018963966\ +36028797018963967\ +36028797018963968\ +36028797018963969\ +36028797018963970\ +72057594037927934\ +72057594037927935\ +72057594037927936\ +72057594037927937\ +72057594037927938\ +144115188075855870\ +144115188075855871\ +144115188075855872\ +144115188075855873\ +144115188075855874\ +288230376151711742\ +288230376151711743\ +288230376151711744\ +288230376151711745\ +288230376151711746\ +576460752303423486\ +576460752303423487\ +576460752303423488\ +576460752303423489\ +576460752303423490\ +1152921504606846974\ +1152921504606846975\ +1152921504606846976\ +1152921504606846977\ +1152921504606846978\ +2305843009213693950\ +2305843009213693951\ +2305843009213693952\ +2305843009213693953\ +2305843009213693954\ +4611686018427387902\ +4611686018427387903\ +4611686018427387904\ +4611686018427387905\ +4611686018427387906\ +9223372036854775806\ +9223372036854775807} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/misc6.test b/components/external/SQLite-3.8.1/test/misc6.test new file mode 100644 index 0000000000000000000000000000000000000000..9840dd9db8880a1e3b62c1e7fa3fb662975cef6e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/misc6.test @@ -0,0 +1,48 @@ +# 2006 September 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure sqlite3_value_text() +# always returns a null-terminated string. +# +# $Id: misc6.test,v 1.3 2007/04/23 23:56:32 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test misc6-1.1 { + set DB [sqlite3_connection_pointer db] + sqlite3_create_function $DB + set STMT [sqlite3_prepare $DB {SELECT hex8(?)} -1 DUMMY] + set sqlite_static_bind_value {0123456789} + set sqlite_static_bind_nbyte 5 + sqlite_bind $STMT 1 {} static-nbytes + sqlite3_step $STMT +} SQLITE_ROW +do_test misc6-1.2 { + sqlite3_column_text $STMT 0 +} {3031323334} +ifcapable utf16 { + do_test misc6-1.3 { + sqlite3_finalize $STMT + set STMT [sqlite3_prepare $DB {SELECT hex16(?)} -1 DUMMY] + set sqlite_static_bind_value {0123456789} + set sqlite_static_bind_nbyte 5 + sqlite_bind $STMT 1 {} static-nbytes + sqlite3_step $STMT + } SQLITE_ROW + do_test misc6-1.4 { + sqlite3_column_text $STMT 0 + } {00300031003200330034} +} +sqlite3_finalize $STMT + +finish_test diff --git a/components/external/SQLite-3.8.1/test/misc7.test b/components/external/SQLite-3.8.1/test/misc7.test new file mode 100644 index 0000000000000000000000000000000000000000..96062a93b972bfc65e1044c0e2ad47305f79e6f9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/misc7.test @@ -0,0 +1,523 @@ +# 2006 September 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# $Id: misc7.test,v 1.29 2009/07/16 18:21:18 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test misc7-1-misuse { + c_misuse_test +} {} + +do_test misc7-2 { + c_realloc_test +} {} + +do_test misc7-3 { + c_collation_test +} {} + +# Try to open a directory: +# +do_test misc7-4 { + delete_file mydir + file mkdir mydir + set rc [catch { + sqlite3 db2 ./mydir + } msg] + list $rc $msg +} {1 {unable to open database file}} + +# Try to open a file with a directory where its journal file should be. +# +do_test misc7-5 { + delete_file mydir + file mkdir mydir-journal + sqlite3 db2 ./mydir + catchsql { + CREATE TABLE abc(a, b, c); + } db2 +} {1 {unable to open database file}} +db2 close + +#-------------------------------------------------------------------- +# The following tests, misc7-6.* test the libraries behaviour when +# it cannot open a file. To force this condition, we use up all the +# file-descriptors before running sqlite. This probably only works +# on unix. +# + +proc use_up_files {} { + set ret [list] + catch { + while 1 { lappend ret [open test.db] } + } + return $ret +} + +proc do_fileopen_test {prefix sql} { + set fd_list [use_up_files] + set ::go 1 + set ::n 1 + set ::sql $sql + while {$::go} { + catch {db close} + do_test ${prefix}.${::n} { + set rc [catch { + sqlite db test.db + db eval $::sql + } msg] + if {$rc == 0} {set ::go 0} + + expr {$rc == 0 || ($rc == 1 && [string first unable $msg]==0)} + } 1 + + close [lindex $fd_list 0] + set fd_list [lrange $fd_list 1 end] + incr ::n + } + foreach fd $fd_list { + close $fd + } + db close +} + +execsql { CREATE TABLE abc(a PRIMARY KEY, b, c); } +db close + +if {$tcl_platform(platform)!="windows"} { + do_fileopen_test misc7-6.1 { + BEGIN; + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(2, 3, 4); + INSERT INTO abc SELECT a+2, b, c FROM abc; + COMMIT; + } + + do_fileopen_test misc7-6.2 { + PRAGMA temp.cache_size = 1000; + } +} + +# +# End of tests for out-of-file-descriptors condition. +#-------------------------------------------------------------------- + +sqlite3 db test.db +execsql { + DELETE FROM abc; + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(2, 3, 4); + INSERT INTO abc SELECT a+2, b, c FROM abc; +} + + +#-------------------------------------------------------------------- +# Test that the sqlite3_busy_timeout call seems to delay approximately +# the right amount of time. +# +do_test misc7-7.0 { + sqlite3 db2 test.db + sqlite3_busy_timeout [sqlite3_connection_pointer db] 2000 + execsql { + BEGIN EXCLUSIVE; + } db2 + + # Now db2 has an exclusive lock on the database file, and db has + # a busy-timeout of 2000 milliseconds. So check that trying to + # access the database using connection db delays for at least 1500 ms. + # + set tm [time { + set result [catchsql { + SELECT * FROM sqlite_master; + } db] + }] + set delay [lindex $tm 0] ;# In microseconds + lappend result [expr {$delay>1500000 && $delay<4000000}] +} {1 {database is locked} 1} +db2 close + +#-------------------------------------------------------------------- +# Test that nothing goes horribly wrong when attaching a database +# after the omit_readlock pragma has been exercised. +# +# Note: The PRAGMA omit_readlock was an early hack to disable the +# fcntl() calls for read-only databases so that read-only databases could +# be read on broken NFS systems. That pragma has now been removed. +# (Use the unix-none VFS as a replacement, if needed.) But these tests +# do not really depend on omit_readlock, so we left them in place. +# +do_test misc7-7.1 { + forcedelete test2.db + forcedelete test2.db-journal + execsql { + PRAGMA omit_readlock = 1; + ATTACH 'test2.db' AS aux; + CREATE TABLE aux.hello(world); + SELECT name FROM aux.sqlite_master; + } +} {hello} +do_test misc7-7.2 { + execsql { + DETACH aux; + } +} {} +do_test misc7-7.3 { + db close + sqlite3 db test.db -readonly 1 + execsql { + PRAGMA omit_readlock = 1; + ATTACH 'test2.db' AS aux; + SELECT name FROM aux.sqlite_master; + SELECT name FROM aux.sqlite_master; + } +} {hello hello} +do_test misc7-7.3 { + db close + sqlite3 db test.db + set ::DB [sqlite3_connection_pointer db] + list +} {} + +# Test the UTF-16 version of the "out of memory" message (used when +# malloc fails during sqlite3_open() ). +# +ifcapable utf16 { + do_test misc7-8 { + encoding convertfrom unicode [sqlite3_errmsg16 0x00000000] + } {out of memory} +} + +do_test misc7-9 { + execsql { + SELECT * + FROM (SELECT name+1 AS one FROM sqlite_master LIMIT 1 OFFSET 1) + WHERE one LIKE 'hello%'; + } +} {} + +#-------------------------------------------------------------------- +# Improve coverage for vtab code. +# +ifcapable vtab { + # Run some debug code to improve reported coverage + # + + # set sqlite_where_trace 1 + do_test misc7-10 { + register_echo_module [sqlite3_connection_pointer db] + execsql { + CREATE VIRTUAL TABLE t1 USING echo(abc); + SELECT a FROM t1 WHERE a = 1 ORDER BY b; + } + } {1} + set sqlite_where_trace 0 + + # Specify an ORDER BY clause that cannot be indexed. + do_test misc7-11 { + execsql { + SELECT t1.a, t2.a FROM t1, t1 AS t2 ORDER BY 2 LIMIT 1; + } + } {1 1} + + # The whole point of this is to test an error code other than + # SQLITE_NOMEM from the vtab xBestIndex callback. + # + do_ioerr_test misc7-12 -tclprep { + sqlite3 db2 test.db + register_echo_module [sqlite3_connection_pointer db2] + db2 eval { + CREATE TABLE abc(a PRIMARY KEY, b, c); + INSERT INTO abc VALUES(1, 2, 3); + CREATE VIRTUAL TABLE t1 USING echo(abc); + } + db2 close + } -tclbody { + register_echo_module [sqlite3_connection_pointer db] + execsql {SELECT * FROM t1 WHERE a = 1;} + } + + # The case where the virtual table module returns a very large number + # as the cost of a scan (greater than SQLITE_BIG_DOUBLE in the code). + # + do_test misc7-13 { + sqlite3 db test.db + register_echo_module [sqlite3_connection_pointer db] + set ::echo_module_cost 2.0e+99 + execsql {SELECT * FROM t1 WHERE a = 1;} + } {1 2 3} + unset ::echo_module_cost +} + +db close +forcedelete test.db +forcedelete test.db-journal +sqlite3 db test.db + +ifcapable explain { + do_execsql_test misc7-14.1 { + CREATE TABLE abc(a PRIMARY KEY, b, c); + EXPLAIN QUERY PLAN SELECT * FROM abc AS t2 WHERE rowid = 1; + } { + 0 0 0 {SEARCH TABLE abc AS t2 USING INTEGER PRIMARY KEY (rowid=?)} + } + do_execsql_test misc7-14.2 { + EXPLAIN QUERY PLAN SELECT * FROM abc AS t2 WHERE a = 1; + } {0 0 0 + {SEARCH TABLE abc AS t2 USING INDEX sqlite_autoindex_abc_1 (a=?)} + } + do_execsql_test misc7-14.3 { + EXPLAIN QUERY PLAN SELECT * FROM abc AS t2 ORDER BY a; + } {0 0 0 + {SCAN TABLE abc AS t2 USING INDEX sqlite_autoindex_abc_1} + } +} + +db close +forcedelete test.db +forcedelete test.db-journal +sqlite3 db test.db + +#-------------------------------------------------------------------- +# This is all to force the pager_remove_from_stmt_list() function +# (inside pager.c) to remove a pager from the middle of the +# statement-list. +# +do_test misc7-15.1 { + execsql { + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE abc(a PRIMARY KEY, b, c); + INSERT INTO abc + VALUES(randstr(100,100), randstr(100,100), randstr(100,100)); + INSERT INTO abc SELECT + randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc SELECT + randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc SELECT + randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc SELECT + randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc SELECT + randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc SELECT + randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc SELECT + randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + INSERT INTO abc SELECT + randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + COMMIT; + } + expr {[file size test.db]>10240} +} {1} +do_test misc7-15.2 { + execsql { + DELETE FROM abc WHERE rowid > 12; + INSERT INTO abc SELECT + randstr(100,100), randstr(100,100), randstr(100,100) FROM abc; + } +} {} + +db close +forcedelete test.db +forcedelete test.db-journal +sqlite3 db test.db + +do_ioerr_test misc7-16 -sqlprep { + PRAGMA cache_size = 10; + PRAGMA default_cache_size = 10; + CREATE TABLE t3(a, b, UNIQUE(a, b)); + INSERT INTO t3 VALUES( randstr(100, 100), randstr(100, 100) ); + INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; + INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; + INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; + INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; + INSERT INTO t3 SELECT randstr(100, 100), randstr(100, 100) FROM t3; + UPDATE t3 + SET b = 'hello world' + WHERE rowid >= (SELECT max(rowid)-1 FROM t3); +} -tclbody { + set rc [catch {db eval { + BEGIN; + PRAGMA cache_size = 10; + INSERT INTO t3 VALUES( randstr(100, 100), randstr(100, 100) ); + UPDATE t3 SET a = b; + COMMIT; + }} msg] + + if {!$rc || ($rc && [string first "columns" $msg]==0)} { + set msg + } else { + error $msg + } +} + +sqlite3 db test.db + +do_test misc7-16.X { + execsql { + SELECT count(*) FROM t3; + } +} {32} + +#---------------------------------------------------------------------- +# Test the situation where a hot-journal is discovered but write-access +# to it is denied. This should return SQLITE_BUSY. +# +# These tests do not work on windows due to restrictions in the +# windows file system. +# +if {$tcl_platform(platform)!="windows"} { + + # Some network filesystems (ex: AFP) do not support setting read-only + # permissions. Only run these tests if full unix permission setting + # capabilities are supported. + # + file attributes test.db -permissions rw-r--r-- + if {[file attributes test.db -permissions]==0644} { + + do_test misc7-17.1 { + execsql { + BEGIN; + DELETE FROM t3 WHERE (oid%3)==0; + } + forcecopy test.db bak.db + forcecopy test.db-journal bak.db-journal + execsql { + COMMIT; + } + + db close + forcecopy bak.db test.db + forcecopy bak.db-journal test.db-journal + sqlite3 db test.db + + catch {file attributes test.db-journal -permissions r--------} + catch {file attributes test.db-journal -readonly 1} + catchsql { + SELECT count(*) FROM t3; + } + } {1 {unable to open database file}} + do_test misc7-17.2 { + # Note that the -readonly flag must be cleared before the -permissions + # are set. Otherwise, when using tcl 8.5 on mac, the fact that the + # -readonly flag is set causes the attempt to set the permissions + # to fail. + catch {file attributes test.db-journal -readonly 0} + catch {file attributes test.db-journal -permissions rw-------} + catchsql { + SELECT count(*) FROM t3; + } + } {0 32} + + # sqlite3_test_control_pending_page [expr ($::sqlite_pending_byte / 1024) + 1] + set ::pending_byte_page [expr ($::sqlite_pending_byte / 1024) + 1] + sqlite3_test_control_pending_byte $::sqlite_pending_byte + do_test misc7-17.3 { + db eval { + pragma writable_schema = true; + UPDATE sqlite_master + SET rootpage = $pending_byte_page + WHERE type = 'table' AND name = 't3'; + } + execsql { + SELECT rootpage FROM sqlite_master WHERE type = 'table' AND name = 't3'; + } + } $::pending_byte_page + + do_test misc7-17.4 { + db close + sqlite3 db test.db + catchsql { + SELECT count(*) FROM t3; + } + } {1 {database disk image is malformed}} + } +} + +# Ticket #2470 +# +do_test misc7-18.1 { + execsql { + CREATE TABLE table_1 (col_10); + CREATE TABLE table_2 ( + col_1, col_2, col_3, col_4, col_5, + col_6, col_7, col_8, col_9, col_10 + ); + SELECT a.col_10 + FROM + (SELECT table_1.col_10 AS col_10 FROM table_1) a, + (SELECT table_1.col_10, table_2.col_9 AS qcol_9 + FROM table_1, table_2 + GROUP BY table_1.col_10, qcol_9); + } +} {} + +# Testing boundary conditions on sqlite3_status() +# +do_test misc7-19.1 { + sqlite3_status -1 0 +} {21 0 0} +do_test misc7-19.2 { + sqlite3_status 1000 0 +} {21 0 0} + + +# sqlite3_global_recover() is a no-op. But we might as well test it +# if only to get the test coverage. +# +do_test misc7-20.1 { + sqlite3_global_recover +} {SQLITE_OK} + +# Try to open a really long file name. +# +do_test misc7-21.1 { + set zFile [file join [get_pwd] "[string repeat abcde 104].db"] + set rc [catch {sqlite3 db2 $zFile} msg] + list $rc $msg +} {1 {unable to open database file}} + +# Try to do hot-journal rollback with a read-only connection. The +# error code should be SQLITE_READONLY_ROLLBACK. +# +do_test misc7-22.1 { + db close + forcedelete test.db copy.db-journal + sqlite3 db test.db + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + } + db close + sqlite3 db test.db -readonly 1 + catchsql { + INSERT INTO t1 VALUES(5, 6); + } +} {1 {attempt to write a readonly database}} +do_test misc7-22.2 { execsql { SELECT * FROM t1 } } {1 2 3 4} +do_test misc7-22.3 { + set fd [open test.db-journal w] + puts $fd [string repeat abc 1000] + close $fd + catchsql { SELECT * FROM t1 } +} {1 {attempt to write a readonly database}} +do_test misc7-22.4 { + sqlite3_extended_errcode db +} SQLITE_READONLY_ROLLBACK + +db close +forcedelete test.db + +finish_test diff --git a/components/external/SQLite-3.8.1/test/misuse.test b/components/external/SQLite-3.8.1/test/misuse.test new file mode 100644 index 0000000000000000000000000000000000000000..71ee0118c8b6ef9f9fb884798fd756c92d3238e1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/misuse.test @@ -0,0 +1,207 @@ +# 2002 May 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the SQLITE_MISUSE detection logic. +# This test file leaks memory and file descriptors. +# +# $Id: misuse.test,v 1.11 2006/01/03 00:33:50 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc catchsql2 {sql} { + set r [ + catch { + set res [list] + db eval $sql data { + if { $res==[list] } { + foreach f $data(*) {lappend res $f} + } + foreach f $data(*) {lappend res $data($f)} + } + set res + } msg + ] + lappend r $msg +} + + +# Make sure the test logic works +# +do_test misuse-1.1 { + db close + catch {forcedelete test2.db} + catch {forcedelete test2.db-journal} + sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db] + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + } + catchsql2 { + SELECT * FROM t1 + } +} {0 {a b 1 2}} +do_test misuse-1.2 { + catchsql2 { + SELECT x_coalesce(NULL,a) AS 'xyz' FROM t1 + } +} {1 {no such function: x_coalesce}} +do_test misuse-1.3 { + sqlite3_create_function $::DB + catchsql2 { + SELECT x_coalesce(NULL,a) AS 'xyz' FROM t1 + } +} {0 {xyz 1}} + +# Use the x_sqlite_exec() SQL function to simulate the effect of two +# threads trying to use the same database at the same time. +# +# It used to be prohibited to invoke sqlite_exec() from within a function, +# but that has changed. The following tests used to cause errors but now +# they do not. +# +ifcapable {utf16} { + do_test misuse-1.4 { + catchsql2 { + SELECT x_sqlite_exec('SELECT * FROM t1') AS xyz; + } + } {0 {xyz {1 2}}} +} +do_test misuse-1.5 { + catchsql2 {SELECT * FROM t1} +} {0 {a b 1 2}} +do_test misuse-1.6 { + catchsql { + SELECT * FROM t1 + } +} {0 {1 2}} + +# Attempt to register a new SQL function while an sqlite_exec() is active. +# +do_test misuse-2.1 { + db close + sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db] + execsql { + SELECT * FROM t1 + } +} {1 2} +do_test misuse-2.2 { + catchsql2 {SELECT * FROM t1} +} {0 {a b 1 2}} + +# We used to disallow creating new function from within an exec(). +# But now this is acceptable. +do_test misuse-2.3 { + set v [catch { + db eval {SELECT * FROM t1} {} { + sqlite3_create_function $::DB + } + } msg] + lappend v $msg +} {0 {}} +do_test misuse-2.4 { + catchsql2 {SELECT * FROM t1} +} {0 {a b 1 2}} +do_test misuse-2.5 { + catchsql { + SELECT * FROM t1 + } +} {0 {1 2}} + +# Attempt to register a new SQL aggregate while an sqlite_exec() is active. +# +do_test misuse-3.1 { + db close + sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db] + execsql { + SELECT * FROM t1 + } +} {1 2} +do_test misuse-3.2 { + catchsql2 {SELECT * FROM t1} +} {0 {a b 1 2}} + +# We used to disallow creating new function from within an exec(). +# But now this is acceptable. +do_test misuse-3.3 { + set v [catch { + db eval {SELECT * FROM t1} {} { + sqlite3_create_aggregate $::DB + } + } msg] + lappend v $msg +} {0 {}} +do_test misuse-3.4 { + catchsql2 {SELECT * FROM t1} +} {0 {a b 1 2}} +do_test misuse-3.5 { + catchsql { + SELECT * FROM t1 + } +} {0 {1 2}} + +# Attempt to close the database from an sqlite_exec callback. +# +# Update for v3: The db cannot be closed because there are active +# VMs. The sqlite3_close call would return SQLITE_BUSY. +do_test misuse-4.1 { + db close + sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db] + execsql { + SELECT * FROM t1 + } +} {1 2} +do_test misuse-4.2 { + catchsql2 {SELECT * FROM t1} +} {0 {a b 1 2}} +do_test misuse-4.3 { + set v [catch { + db eval {SELECT * FROM t1} {} { + set r [sqlite3_close $::DB] + } + } msg] + lappend v $msg $r +} {0 {} SQLITE_BUSY} +do_test misuse-4.4 { + # Flush the TCL statement cache here, otherwise the sqlite3_close() will + # fail because there are still un-finalized() VDBEs. + db cache flush + sqlite3_close $::DB + catchsql2 {SELECT * FROM t1} +} {1 {library routine called out of sequence}} +do_test misuse-4.5 { + catchsql { + SELECT * FROM t1 + } +} {1 {library routine called out of sequence}} + +# Attempt to use a database after it has been closed. +# +do_test misuse-5.1 { + db close + sqlite3 db test2.db; set ::DB [sqlite3_connection_pointer db] + execsql { + SELECT * FROM t1 + } +} {1 2} +do_test misuse-5.2 { + catchsql2 {SELECT * FROM t1} +} {0 {a b 1 2}} +do_test misuse-5.3 { + db close + set r [catch { + sqlite3_prepare $::DB {SELECT * FROM t1} -1 TAIL + } msg] + lappend r $msg +} {1 {(21) library routine called out of sequence}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mmap1.test b/components/external/SQLite-3.8.1/test/mmap1.test new file mode 100644 index 0000000000000000000000000000000000000000..ece3e0201ed2aceb86cfc48e0adf7d9266a8c4bc --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mmap1.test @@ -0,0 +1,331 @@ +# 2013 March 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !mmap { + finish_test + return +} +source $testdir/lock_common.tcl +set testprefix mmap1 + +proc nRead {db} { + set bt [btree_from_db $db] + db_enter $db + array set stats [btree_pager_stats $bt] + db_leave $db + # puts [array get stats] + return $stats(read) +} + +proc register_rblob_code {dbname seed} { + return [subst -nocommands { + set ::rcnt $seed + proc rblob {n} { + set ::rcnt [expr (([set ::rcnt] << 3) + [set ::rcnt] + 456) & 0xFFFFFFFF] + set str [format %.8x [expr [set ::rcnt] ^ 0xbdf20da3]] + string range [string repeat [set str] [expr [set n]/4]] 1 [set n] + } + $dbname func rblob rblob + }] +} + +# For cases 1.1 and 1.4, the number of pages read using xRead() is 4 on +# unix and 9 on windows. The difference is that windows only ever maps +# an integer number of OS pages (i.e. creates mappings that are a multiple +# of 4KB in size). Whereas on unix any sized mapping may be created. +# +foreach {t mmap_size nRead c2init} { + 1.1 { PRAGMA mmap_size = 67108864 } /[49]/ {PRAGMA mmap_size = 0} + 1.2 { PRAGMA mmap_size = 53248 } 150 {PRAGMA mmap_size = 0} + 1.3 { PRAGMA mmap_size = 0 } 344 {PRAGMA mmap_size = 0} + 1.4 { PRAGMA mmap_size = 67108864 } /[49]/ {PRAGMA mmap_size = 67108864 } + 1.5 { PRAGMA mmap_size = 53248 } 150 {PRAGMA mmap_size = 67108864 } + 1.6 { PRAGMA mmap_size = 0 } 344 {PRAGMA mmap_size = 67108864 } +} { + + do_multiclient_test tn { + sql1 {PRAGMA cache_size=2000} + sql2 {PRAGMA cache_size=2000} + + sql1 {PRAGMA page_size=1024} + sql1 $mmap_size + sql2 $c2init + + code2 [register_rblob_code db2 0] + + sql2 { + PRAGMA page_size=1024; + PRAGMA auto_vacuum = 1; + CREATE TABLE t1(a, b, UNIQUE(a, b)); + INSERT INTO t1 VALUES(rblob(500), rblob(500)); + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 2 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 4 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 8 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 16 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 32 + } + do_test $t.$tn.1 { + sql1 "SELECT count(*) FROM t1; PRAGMA integrity_check ; PRAGMA page_count" + } {32 ok 77} + + # Have connection 2 shrink the file. Check connection 1 can still read it. + sql2 { DELETE FROM t1 WHERE rowid%2; } + do_test $t.$tn.2 { + sql1 "SELECT count(*) FROM t1; PRAGMA integrity_check ; PRAGMA page_count" + } {16 ok 42} + + # Have connection 2 grow the file. Check connection 1 can still read it. + sql2 { INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1 } + do_test $t.$tn.3 { + sql1 "SELECT count(*) FROM t1; PRAGMA integrity_check ; PRAGMA page_count" + } {32 ok 79} + + # Have connection 2 grow the file again. Check connection 1 is still ok. + sql2 { INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1 } + do_test $t.$tn.4 { + sql1 "SELECT count(*) FROM t1; PRAGMA integrity_check ; PRAGMA page_count" + } {64 ok 149} + + # Check that the number of pages read by connection 1 indicates that the + # "PRAGMA mmap_size" command worked. + do_test $t.$tn.5 { nRead db } $nRead + } +} + +set ::rcnt 0 +proc rblob {n} { + set ::rcnt [expr (($::rcnt << 3) + $::rcnt + 456) & 0xFFFFFFFF] + set str [format %.8x [expr $::rcnt ^ 0xbdf20da3]] + string range [string repeat $str [expr $n/4]] 1 $n +} + +reset_db +db func rblob rblob + +do_execsql_test 2.1 { + PRAGMA auto_vacuum = 1; + PRAGMA mmap_size = 67108864; + PRAGMA journal_mode = wal; + CREATE TABLE t1(a, b, UNIQUE(a, b)); + INSERT INTO t1 VALUES(rblob(500), rblob(500)); + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 2 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 4 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 8 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 16 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 32 + PRAGMA wal_checkpoint; +} {67108864 wal 0 103 103} + +do_execsql_test 2.2 { + PRAGMA auto_vacuum; + SELECT count(*) FROM t1; +} {1 32} + +if {[permutation] != "inmemory_journal"} { + do_test 2.3 { + sqlite3 db2 test.db + db2 func rblob rblob + db2 eval { + DELETE FROM t1 WHERE (rowid%4); + PRAGMA wal_checkpoint; + } + db2 eval { + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 16 + SELECT count(*) FROM t1; + } + } {16} + + do_execsql_test 2.4 { + PRAGMA wal_checkpoint; + } {0 24 24} + db2 close +} + +reset_db +execsql { PRAGMA mmap_size = 67108864; } +db func rblob rblob +do_execsql_test 3.1 { + PRAGMA auto_vacuum = 1; + + CREATE TABLE t1(a, b, UNIQUE(a, b)); + INSERT INTO t1 VALUES(rblob(500), rblob(500)); + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 2 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 4 + INSERT INTO t1 SELECT rblob(500), rblob(500) FROM t1; -- 8 + + CREATE TABLE t2(a, b, UNIQUE(a, b)); + INSERT INTO t2 SELECT * FROM t1; +} {} + +do_test 3.2 { + set nRow 0 + db eval {SELECT * FROM t2 ORDER BY a, b} { + if {$nRow==4} { db eval { DELETE FROM t1 } } + incr nRow + } + set nRow +} {8} + +#------------------------------------------------------------------------- +# Ensure that existing cursors using xFetch() pages see changes made +# to rows using the incrblob API. +# +reset_db +execsql { PRAGMA mmap_size = 67108864; } +set aaa [string repeat a 400] +set bbb [string repeat b 400] +set ccc [string repeat c 400] +set ddd [string repeat d 400] +set eee [string repeat e 400] + +do_execsql_test 4.1 { + PRAGMA page_size = 1024; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES($aaa); + INSERT INTO t1 VALUES($bbb); + INSERT INTO t1 VALUES($ccc); + INSERT INTO t1 VALUES($ddd); + SELECT * FROM t1; + BEGIN; +} [list $aaa $bbb $ccc $ddd] + +do_test 4.2 { + set ::STMT [sqlite3_prepare db "SELECT * FROM t1 ORDER BY rowid" -1 dummy] + sqlite3_step $::STMT + sqlite3_column_text $::STMT 0 +} $aaa + +do_test 4.3 { + foreach r {2 3 4} { + set fd [db incrblob t1 x $r] + puts -nonewline $fd $eee + close $fd + } + + set res [list] + while {"SQLITE_ROW" == [sqlite3_step $::STMT]} { + lappend res [sqlite3_column_text $::STMT 0] + } + set res +} [list $eee $eee $eee] + +do_test 4.4 { + sqlite3_finalize $::STMT +} SQLITE_OK + +do_execsql_test 4.5 { COMMIT } + +#------------------------------------------------------------------------- +# Ensure that existing cursors holding xFetch() references are not +# confused if those pages are moved to make way for the root page of a +# new table or index. +# +reset_db +execsql { PRAGMA mmap_size = 67108864; } +do_execsql_test 5.1 { + PRAGMA auto_vacuum = 2; + PRAGMA page_size = 1024; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES($aaa); + INSERT INTO t1 VALUES($bbb); + INSERT INTO t1 VALUES($ccc); + INSERT INTO t1 VALUES($ddd); + + PRAGMA auto_vacuum; + SELECT * FROM t1; +} [list 2 $aaa $bbb $ccc $ddd] + +do_test 5.2 { + set ::STMT [sqlite3_prepare db "SELECT * FROM t1 ORDER BY rowid" -1 dummy] + sqlite3_step $::STMT + sqlite3_column_text $::STMT 0 +} $aaa + +do_execsql_test 5.3 { + CREATE TABLE t2(x); + INSERT INTO t2 VALUES('tricked you!'); + INSERT INTO t2 VALUES('tricked you!'); +} + +do_test 5.4 { + sqlite3_step $::STMT + sqlite3_column_text $::STMT 0 +} $bbb + +do_test 5.5 { + sqlite3_finalize $::STMT +} SQLITE_OK + +#------------------------------------------------------------------------- +# Test various mmap_size settings. +# +foreach {tn1 mmap1 mmap2} { + 1 6144 167773 + 2 18432 140399 + 3 43008 401302 + 4 92160 253899 + 5 190464 2 + 6 387072 752431 + 7 780288 291143 + 8 1566720 594306 + 9 3139584 829137 + 10 6285312 793963 + 11 12576768 1015590 +} { + do_multiclient_test tn { + sql1 { + CREATE TABLE t1(a PRIMARY KEY); + CREATE TABLE t2(x); + INSERT INTO t2 VALUES(''); + } + + code1 [register_rblob_code db 0] + code2 [register_rblob_code db2 444] + + sql1 "PRAGMA mmap_size = $mmap1" + sql2 "PRAGMA mmap_size = $mmap2" + + do_test $tn1.$tn { + for {set i 1} {$i <= 100} {incr i} { + if {$i % 2} { + set c1 sql1 + set c2 sql2 + } else { + set c1 sql2 + set c2 sql1 + } + + $c1 { + INSERT INTO t1 VALUES( rblob(5000) ); + UPDATE t2 SET x = (SELECT md5sum(a) FROM t1); + } + + set res [$c2 { + SELECT count(*) FROM t1; + SELECT x == (SELECT md5sum(a) FROM t1) FROM t2; + PRAGMA integrity_check; + }] + if {$res != [list $i 1 ok]} { + do_test $tn1.$tn.$i { + set ::res + } [list $i 1 ok] + } + } + set res 1 + } {1} + } +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mmap2.test b/components/external/SQLite-3.8.1/test/mmap2.test new file mode 100644 index 0000000000000000000000000000000000000000..1f8346b915eac5b29d5d4a51d27bf9d793ec2bc0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mmap2.test @@ -0,0 +1,87 @@ +# 2013 March 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests the effect of the mmap() or mremap() system calls +# returning an error on the library. +# +# If either mmap() or mremap() fails, SQLite should log an error +# message, then continue accessing the database using read() and +# write() exclusively. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix mmap2 + +if {$::tcl_platform(platform)!="unix" || [test_syscall defaultvfs] != "unix"} { + finish_test + return +} +ifcapable !mmap { + finish_test + return +} + +db close +sqlite3_shutdown +test_sqlite3_log xLog +proc xLog {error_code msg} { + if {[string match os_unix.c* $msg]} { + lappend ::log $msg + } +} + +foreach syscall {mmap mremap} { + test_syscall uninstall + if {[catch {test_syscall install $syscall}]} continue + + for {set i 1} {$i < 20} {incr i} { + reset_db + execsql { PRAGMA mmap_size = 8000000 } + + test_syscall fault $i 1 + test_syscall errno $syscall ENOMEM + set ::log "" + + do_execsql_test 1.$syscall.$i.1 { + CREATE TABLE t1(a, b, UNIQUE(a, b)); + INSERT INTO t1 VALUES(randomblob(1000), randomblob(1000)); + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + INSERT INTO t1 SELECT randomblob(1000), randomblob(1000) FROM t1; + } + + set nFail [test_syscall fault 0 0] + + do_execsql_test 1.$syscall.$i.2 { + SELECT count(*) FROM t1; + PRAGMA integrity_check; + } {64 ok} + + do_test 1.$syscall.$i.3 { + expr {$nFail==0 || $nFail==1} + } {1} + + do_test 1.$syscall.$i.4.nFail=$nFail { + regexp ".*${syscall}.*" $::log + } [expr $nFail>0] + } +} + +db close +test_syscall uninstall +sqlite3_shutdown +test_sqlite3_log +sqlite3_initialize +finish_test diff --git a/components/external/SQLite-3.8.1/test/mmap3.test b/components/external/SQLite-3.8.1/test/mmap3.test new file mode 100644 index 0000000000000000000000000000000000000000..07b5152968f8f4ab03cd36598ba744c36e360f42 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mmap3.test @@ -0,0 +1,98 @@ +# 2013-05-23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !mmap||!vtab { + finish_test + return +} +source $testdir/lock_common.tcl +set testprefix mmap3 + +do_test mmap3-1.0 { + load_static_extension db wholenumber + db eval { + PRAGMA mmap_size=100000; + CREATE TABLE t1(x, y); + CREATE VIRTUAL TABLE nums USING wholenumber; + INSERT INTO t1 SELECT value, randomblob(value) FROM nums + WHERE value BETWEEN 1 and 1000; + SELECT sum(x), sum(length(y)) from t1; + PRAGMA mmap_size; + } +} {100000 500500 500500 100000} +do_test mmap3-1.2 { + db eval { + PRAGMA mmap_size=50000; + CREATE TABLE t2(a,b); + SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1; + PRAGMA quick_check; + PRAGMA mmap_size; + } +} {50000 nums t1 t2 ok 50000} +do_test mmap3-1.3 { + db eval { + PRAGMA mmap_size=250000; + DROP TABLE t2; + SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1; + PRAGMA quick_check; + PRAGMA mmap_size; + } +} {250000 nums t1 ok 250000} +do_test mmap3-1.4 { + db eval {SELECT x FROM t1 WHERE +x BETWEEN 10 AND 15} { + db eval {PRAGMA mmap_size=150000} + } + db eval { + PRAGMA quick_check; + PRAGMA mmap_size; + } +} {ok 250000} +do_test mmap3-1.5 { + db eval {SELECT x FROM t1 WHERE +x BETWEEN 10 AND 15} { + db eval {PRAGMA mmap_size=0} + } + db eval { + PRAGMA quick_check; + PRAGMA mmap_size; + } +} {ok 250000} +do_test mmap3-1.6 { + db eval {SELECT x FROM t1 WHERE +x BETWEEN 10 AND 15} { + set x [db one {PRAGMA mmap_size}] + } + set x [concat $x [db eval { + PRAGMA quick_check; + PRAGMA mmap_size; + }]] +} {250000 ok 250000} +do_test mmap3-1.7 { + db eval { + PRAGMA mmap_size(0); + CREATE TABLE t3(a,b,c); + SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1; + PRAGMA quick_check; + PRAGMA mmap_size; + } +} {0 nums t1 t3 ok 0} +do_test mmap3-1.8 { + db eval {SELECT x FROM t1 WHERE +x BETWEEN 10 AND 15} { + db eval {PRAGMA mmap_size=75000} + } + db eval { + PRAGMA quick_check; + PRAGMA mmap_size; + } +} {ok 75000} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/mmapfault.test b/components/external/SQLite-3.8.1/test/mmapfault.test new file mode 100644 index 0000000000000000000000000000000000000000..248b5bad082faec8a06dd67e703579df05ef31bc --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mmapfault.test @@ -0,0 +1,77 @@ +# 2013-05-23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +ifcapable !mmap { + finish_test + return +} +set testprefix mmapfault + +set a_string_counter 1 +proc a_string {n} { + global a_string_counter + incr a_string_counter + string range [string repeat "${a_string_counter}." $n] 1 $n +} +db func a_string a_string + +do_test 1-pre { + execsql { + CREATE TABLE t1(a UNIQUE, b UNIQUE); + INSERT INTO t1 VALUES(a_string(200), a_string(300)); + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + } + faultsim_save_and_close +} {} + + +do_faultsim_test 1 -prep { + faultsim_restore_and_reopen + db func a_string a_string + breakpoint + execsql { + PRAGMA mmap_size = 1000000; + PRAGMA cache_size = 5; + BEGIN; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + } +} -body { + execsql { INSERT INTO t1 VALUES(a_string(200), a_string(300)) } +} -test { + faultsim_test_result {0 {}} + + if {[sqlite3_get_autocommit db]} { + sqlite3 db2 test.db + set nRow [db2 one {SELECT count(*) FROM t1}] + if {$nRow!=4} { error "Database content appears incorrect (1)" } + db2 close + } + + execsql { INSERT INTO t1 VALUES(a_string(201), a_string(301)) } + set nRow [db one {SELECT count(*) FROM t1}] + if {$nRow!=5 && $nRow!=66 && $nRow!=65} { + error "Database content appears incorrect (2) ($nRow)" + } + + catch { execsql COMMIT } +} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/multiplex.test b/components/external/SQLite-3.8.1/test/multiplex.test new file mode 100644 index 0000000000000000000000000000000000000000..32c87d9a52ac92915d2962ce4e6904500c8c661a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/multiplex.test @@ -0,0 +1,587 @@ +# 2010 October 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# The tests in this file assume that SQLite is compiled without +# ENABLE_8_3_NAMES. +# +ifcapable 8_3_names { + puts -nonewline "SQLite compiled with SQLITE_ENABLE_8_3_NAMES. " + puts "Skipping tests multiplex-*." + finish_test + return +} + +set g_chunk_size [ expr ($::SQLITE_MAX_PAGE_SIZE*16384) ] +set g_max_chunks 32 + +# This handles appending the chunk number +# to the end of the filename. if +# SQLITE_MULTIPLEX_EXT_OVWR is defined, then +# it overwrites the last 2 bytes of the +# file name with the chunk number. +proc multiplex_name {name chunk} { + if {$chunk==0} { return $name } + set num [format "%03d" $chunk] + ifcapable {multiplex_ext_overwrite} { + set name [string range $name 0 [expr [string length $name]-2-1]] + } + return $name$num +} + +# This saves off the parameters and calls the +# underlying sqlite3_multiplex_control() API. +proc multiplex_set {db name chunk_size max_chunks} { + global g_chunk_size + global g_max_chunks + set g_chunk_size [ expr (($chunk_size+($::SQLITE_MAX_PAGE_SIZE-1)) & ~($::SQLITE_MAX_PAGE_SIZE-1)) ] + set g_max_chunks $max_chunks + set rc [catch {sqlite3_multiplex_control $db $name chunk_size $chunk_size} msg] + if { $rc==0 } { + set rc [catch {sqlite3_multiplex_control $db $name max_chunks $max_chunks} msg] + } + list $msg +} + +# This attempts to delete the base file and +# and files with the chunk extension. +proc multiplex_delete {name} { + global g_max_chunks + forcedelete $name + for {set i 0} {$i<$g_max_chunks} {incr i} { + forcedelete [multiplex_name $name $i] + forcedelete [multiplex_name $name-journal $i] + forcedelete [multiplex_name $name-wal $i] + } +} + +db close + +multiplex_delete test.db +multiplex_delete test2.db + +#------------------------------------------------------------------------- +# multiplex-1.1.*: Test initialize and shutdown. + +do_test multiplex-1.1 { sqlite3_multiplex_initialize nosuchvfs 1 } {SQLITE_ERROR} +do_test multiplex-1.2 { sqlite3_multiplex_initialize "" 1 } {SQLITE_OK} +do_test multiplex-1.3 { sqlite3_multiplex_initialize "" 1 } {SQLITE_MISUSE} +do_test multiplex-1.4 { sqlite3_multiplex_shutdown } {SQLITE_OK} + +do_test multiplex-1.5 { sqlite3_multiplex_initialize "" 0 } {SQLITE_OK} +do_test multiplex-1.6 { sqlite3_multiplex_shutdown } {SQLITE_OK} +do_test multiplex-1.7 { sqlite3_multiplex_initialize "" 1 } {SQLITE_OK} +do_test multiplex-1.8 { sqlite3_multiplex_shutdown } {SQLITE_OK} + + +do_test multiplex-1.9.1 { sqlite3_multiplex_initialize "" 1 } {SQLITE_OK} +do_test multiplex-1.9.2 { sqlite3 db test.db } {} +do_test multiplex-1.9.3 { multiplex_set db main 32768 16 } {SQLITE_OK} +do_test multiplex-1.9.4 { multiplex_set db main 32768 -1 } {SQLITE_OK} +do_test multiplex-1.9.6 { multiplex_set db main 31 16 } {SQLITE_OK} +do_test multiplex-1.9.7 { multiplex_set db main 32768 100 } {SQLITE_OK} +do_test multiplex-1.9.8 { multiplex_set db main 1073741824 1 } {SQLITE_OK} +do_test multiplex-1.9.9 { db close } {} +do_test multiplex-1.9.10 { sqlite3_multiplex_shutdown } {SQLITE_OK} + +do_test multiplex-1.10.1 { sqlite3_multiplex_initialize "" 1 } {SQLITE_OK} +do_test multiplex-1.10.2 { sqlite3 db test.db } {} +do_test multiplex-1.10.3 { lindex [ catchsql { SELECT multiplex_control(2, 32768); } ] 0 } {0} +do_test multiplex-1.10.4 { lindex [ catchsql { SELECT multiplex_control(3, -1); } ] 0 } {0} +do_test multiplex-1.10.6 { lindex [ catchsql { SELECT multiplex_control(2, 31); } ] 0 } {0} +do_test multiplex-1.10.7 { lindex [ catchsql { SELECT multiplex_control(3, 100); } ] 0 } {0} +do_test multiplex-1.10.8 { lindex [ catchsql { SELECT multiplex_control(2, 1073741824); } ] 0 } {0} +do_test multiplex-1.10.9 { db close } {} +do_test multiplex-1.10.10 { sqlite3_multiplex_shutdown } {SQLITE_OK} + +do_test multiplex-1.11.1 { sqlite3_multiplex_initialize "" 1 } {SQLITE_OK} +do_test multiplex-1.11.2 { sqlite3 db test.db } {} +do_test multiplex-1.11.3 { sqlite3_multiplex_control db main enable 0 } {SQLITE_OK} +do_test multiplex-1.11.4 { sqlite3_multiplex_control db main enable 1 } {SQLITE_OK} +do_test multiplex-1.11.5 { sqlite3_multiplex_control db main enable -1 } {SQLITE_OK} +do_test multiplex-1.11.6 { db close } {} +do_test multiplex-1.11.7 { sqlite3_multiplex_shutdown } {SQLITE_OK} + +do_test multiplex-1.12.1 { sqlite3_multiplex_initialize "" 1 } {SQLITE_OK} +do_test multiplex-1.12.2 { sqlite3 db test.db } {} +do_test multiplex-1.12.3 { lindex [ catchsql { SELECT multiplex_control(1, 0); } ] 0 } {0} +do_test multiplex-1.12.4 { lindex [ catchsql { SELECT multiplex_control(1, 1); } ] 0 } {0} +do_test multiplex-1.12.5 { lindex [ catchsql { SELECT multiplex_control(1, -1); } ] 0 } {0} +do_test multiplex-1.12.6 { db close } {} +do_test multiplex-1.12.7 { sqlite3_multiplex_shutdown } {SQLITE_OK} + +do_test multiplex-1.13.1 { sqlite3_multiplex_initialize "" 1 } {SQLITE_OK} +do_test multiplex-1.13.2 { sqlite3 db test.db } {} +do_test multiplex-1.13.3 { lindex [ catchsql { SELECT multiplex_control(-1, 0); } ] 0 } {1} +do_test multiplex-1.13.4 { lindex [ catchsql { SELECT multiplex_control(4, 1); } ] 0 } {1} +do_test multiplex-1.13.6 { db close } {} +do_test multiplex-1.13.7 { sqlite3_multiplex_shutdown } {SQLITE_OK} + +#------------------------------------------------------------------------- +# Some simple warm-body tests with a single database file in rollback +# mode: +# +# multiplex-2.1.*: Test simple writing to a multiplex file. +# +# multiplex-2.2.*: More writing. +# +# multiplex-2.3.*: Open and close a second db. +# +# multiplex-2.4.*: Try to shutdown the multiplex system before closing the db +# file. Check that this fails and the multiplex system still works +# afterwards. Then close the database and successfully shut +# down the multiplex system. +# +# multiplex-2.5.*: More reading/writing. +# +# multiplex-2.6.*: More reading/writing with varying small chunk sizes, as +# well as varying journal mode. +# +# multiplex-2.7.*: Disable/enable tests. +# + +sqlite3_multiplex_initialize "" 1 +multiplex_set db main 32768 16 + +forcedelete test.x +foreach f [glob -nocomplain {test.x*[0-9][0-9][0-9]}] { + forcedelete $f +} +do_test multiplex-2.1.2 { + sqlite3 db test.x + execsql { + PRAGMA page_size=1024; + PRAGMA auto_vacuum=OFF; + PRAGMA journal_mode=DELETE; + } + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, randomblob(1100)); + INSERT INTO t1 VALUES(2, randomblob(1100)); + } +} {} +do_test multiplex-2.1.3 { file size [multiplex_name test.x 0] } {4096} +do_test multiplex-2.1.4 { + execsql { INSERT INTO t1 VALUES(3, randomblob(1100)) } +} {} + +do_test multiplex-2.2.1 { + execsql { INSERT INTO t1 VALUES(3, randomblob(1100)) } +} {} +do_test multiplex-2.2.3 { file size [multiplex_name test.x 0] } {6144} + +do_test multiplex-2.3.1 { + sqlite3 db2 test2.x + db2 close +} {} + + +do_test multiplex-2.4.1 { + sqlite3_multiplex_shutdown +} {SQLITE_MISUSE} +do_test multiplex-2.4.2 { + execsql { INSERT INTO t1 VALUES(3, randomblob(1100)) } +} {} +do_test multiplex-2.4.4 { file size [multiplex_name test.x 0] } {7168} +do_test multiplex-2.4.5 { + db close + sqlite3 db test.x + db eval vacuum + db close + glob test.x* +} {test.x} +do_test multiplex-2.4.99 { + sqlite3_multiplex_shutdown +} {SQLITE_OK} + +do_test multiplex-2.5.1 { + multiplex_delete test.x + sqlite3_multiplex_initialize "" 1 + sqlite3 db test.x + multiplex_set db main 4096 16 +} {SQLITE_OK} + +do_test multiplex-2.5.2 { + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = delete; + PRAGMA auto_vacuum = off; + CREATE TABLE t1(a PRIMARY KEY, b); + } +} {delete} + +do_test multiplex-2.5.3 { + execsql { + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, randomblob(4000)); + INSERT INTO t1 VALUES(3, 'three'); + INSERT INTO t1 VALUES(4, randomblob(4000)); + INSERT INTO t1 VALUES(5, 'five'); + INSERT INTO t1 VALUES(6, randomblob($g_chunk_size)); + INSERT INTO t1 VALUES(7, randomblob($g_chunk_size)); + } +} {} + +do_test multiplex-2.5.4 { + db eval {SELECT * FROM t1 WHERE a=1} +} {1 one} + +do_test multiplex-2.5.5 { + db eval {SELECT * FROM t1 WHERE a=3} +} {3 three} + +do_test multiplex-2.5.6 { + db eval {SELECT * FROM t1 WHERE a=5} +} {5 five} + +do_test multiplex-2.5.7 { + db eval {SELECT a,length(b) FROM t1 WHERE a=2} +} {2 4000} + +do_test multiplex-2.5.8 { + db eval {SELECT a,length(b) FROM t1 WHERE a=4} +} {4 4000} + +do_test multiplex-2.5.9 { file size [multiplex_name test.x 0] } [list $g_chunk_size] +do_test multiplex-2.5.10 { file size [multiplex_name test.x 1] } [list $g_chunk_size] + +do_test multiplex-2.5.99 { + db close + sqlite3_multiplex_shutdown +} {SQLITE_OK} + + +set all_journal_modes {delete persist truncate memory off} +foreach jmode $all_journal_modes { + for {set sz 151} {$sz<8000} {set sz [expr $sz+419]} { + + do_test multiplex-2.6.1.$sz.$jmode { + multiplex_delete test.db + sqlite3_multiplex_initialize "" 1 + sqlite3 db test.db + multiplex_set db main $sz 32 + } {SQLITE_OK} + + do_test multiplex-2.6.2.$sz.$jmode { + db eval { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = off; + } + db eval "PRAGMA journal_mode = $jmode;" + } $jmode + + do_test multiplex-2.6.3.$sz.$jmode { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, randomblob($g_chunk_size)); + } + } {} + + do_test multiplex-2.6.4.$sz.$jmode { + db eval {SELECT b FROM t1 WHERE a=1} + } {one} + + do_test multiplex-2.6.5.$sz.$jmode { + db eval {SELECT length(b) FROM t1 WHERE a=2} + } [list $g_chunk_size] + + do_test multiplex-2.6.6.$sz.$jmode { file size [multiplex_name test.db 0] } [list $g_chunk_size] + + do_test multiplex-2.6.99.$sz.$jmode { + db close + sqlite3_multiplex_shutdown + } {SQLITE_OK} + + } +} + +do_test multiplex-2.7.1 { multiplex_delete test.db } {} +do_test multiplex-2.7.2 { sqlite3_multiplex_initialize "" 1 } {SQLITE_OK} +do_test multiplex-2.7.3 { sqlite3 db test.db } {} +do_test multiplex-2.7.4 { lindex [ catchsql { SELECT multiplex_control(2, 65536); } ] 0 } {0} +do_test multiplex-2.7.5 { lindex [ catchsql { SELECT multiplex_control(1, 0); } ] 0 } {0} +do_test multiplex-2.7.6 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, randomblob(1000)); + } +} {} +# verify only one file, and file size is less than chunks size +do_test multiplex-2.7.7 { expr ([file size [multiplex_name test.db 0]] < 65536) } {1} +do_test multiplex-2.7.8 { file exists [multiplex_name test.db 1] } {0} +do_test multiplex-2.7.9 { + execsql { + INSERT INTO t1 VALUES(2, randomblob(65536)); + } +} {} +# verify only one file, and file size exceeds chunks size +do_test multiplex-2.7.10 { expr ([file size [multiplex_name test.db 0]] > 65536) } {1} +do_test multiplex-2.7.11 { file exists [multiplex_name test.db 1] } {0} +do_test multiplex-2.7.12 { db close } {} +do_test multiplex-2.7.13 { sqlite3_multiplex_shutdown } {SQLITE_OK} + +#------------------------------------------------------------------------- +# Try some tests with more than one connection to a database file. Still +# in rollback mode. +# +# multiplex-3.1.*: Two connections to a single database file. +# +# multiplex-3.2.*: Two connections to each of several database files (that +# are in the same multiplex group). +# +do_test multiplex-3.1.1 { + multiplex_delete test.db + sqlite3_multiplex_initialize "" 1 + sqlite3 db test.db + multiplex_set db main 32768 16 +} {SQLITE_OK} +do_test multiplex-3.1.2 { + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = delete; + PRAGMA auto_vacuum = off; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 'one'); + } + file size [multiplex_name test.db 0] +} {3072} +do_test multiplex-3.1.3 { + sqlite3 db2 test.db + execsql { CREATE TABLE t2(a, b) } db2 +} {} +do_test multiplex-3.1.4 { + execsql { CREATE TABLE t3(a, b) } +} {} +do_test multiplex-3.1.5 { + catchsql { CREATE TABLE t3(a, b) } +} {1 {table t3 already exists}} +do_test multiplex-3.1.6 { + db close + db2 close +} {} + +do_test multiplex-3.2.1a { + + multiplex_delete test.db + multiplex_delete test2.db + + sqlite3 db1a test.db + sqlite3 db2a test2.db + + foreach db {db1a db2a} { + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = delete; + PRAGMA auto_vacuum = off; + CREATE TABLE t1(a, b); + } $db + } + + list [file size [multiplex_name test.db 0]] [file size [multiplex_name test2.db 0]] +} {2048 2048} + +do_test multiplex-3.2.1b { + sqlite3 db1b test.db + sqlite3 db2b test2.db +} {} + +do_test multiplex-3.2.2 { execsql { INSERT INTO t1 VALUES('x', 'y') } db1a } {} +do_test multiplex-3.2.3 { execsql { INSERT INTO t1 VALUES('v', 'w') } db1b } {} +do_test multiplex-3.2.4 { execsql { INSERT INTO t1 VALUES('t', 'u') } db2a } {} +do_test multiplex-3.2.5 { execsql { INSERT INTO t1 VALUES('r', 's') } db2b } {} + +do_test multiplex-3.2.6 { + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db1a +} {} +do_test multiplex-3.2.7 { + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db1b +} {} +do_test multiplex-3.2.8 { + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db2a +} {} +do_test multiplex-3.2.9 { + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db2b +} {} + +do_test multiplex-3.3.1 { + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db1a + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db1b + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db2a + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db2b +} {} + +do_test multiplex-3.2.X { + foreach db {db1a db2a db2b db1b} { catch { $db close } } +} {} + +#------------------------------------------------------------------------- +# + +sqlite3_multiplex_initialize "" 1 +multiplex_set db main 32768 16 + +# Return a list of all currently defined multiplexs. +proc multiplex_list {} { + set allq {} + foreach q [sqlite3_multiplex_dump] { + lappend allq [lindex $q 0] + } + return [lsort $allq] +} + +do_test multiplex-4.1.6 { + multiplex_delete test2.db + sqlite3 db test2.db + db eval {CREATE TABLE t2(x); INSERT INTO t2 VALUES('tab-t2');} + set res [multiplex_list] + list [regexp {test2.db} $res] +} {1} +do_test multiplex-4.1.6a { + sqlite3 db2 test2.db + db2 eval {SELECT * FROM t2} +} {tab-t2} +do_test multiplex-4.1.7 { + execsql {INSERT INTO t2 VALUES(zeroblob(200000))} +} {} +do_test multiplex-4.1.8 { + sqlite3 db2 test2.db + db2 eval {SELECT count(*) FROM t2} +} {2} +do_test multiplex-4.1.8a { + db2 eval { DELETE FROM t2 WHERE x = 'tab-t2' } +} {} +do_test multiplex-4.1.8b { + sqlite3 db2 test2.db + db2 eval {SELECT count(*) FROM t2} +} {1} + + +do_test multiplex-4.1.9 { + execsql {INSERT INTO t2 VALUES(zeroblob(200000))} +} {} +do_test multiplex-4.1.10 { + set res [multiplex_list] + list [regexp {test2.db} $res] +} {1} +do_test multiplex-4.1.11 { + db2 close + set res [multiplex_list] + list [regexp {test2.db} $res] +} {1} +do_test multiplex-4.1.12 { + db close + multiplex_list +} {} + + +#------------------------------------------------------------------------- +# The following tests test that the multiplex VFS handles malloc and IO +# errors. +# + +sqlite3_multiplex_initialize "" 1 +multiplex_set db main 32768 16 + +do_faultsim_test multiplex-5.1 -prep { + catch {db close} +} -body { + sqlite3 db test2.db +} +do_faultsim_test multiplex-5.2 -prep { + catch {db close} +} -body { + sqlite3 db test.db +} + +catch { db close } +multiplex_delete test.db +multiplex_delete test2.db + +do_test multiplex-5.3.prep { + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum = 1; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(10, zeroblob(1200)); + } + faultsim_save_and_close +} {} +do_faultsim_test multiplex-5.3 -prep { + faultsim_restore_and_reopen +} -body { + execsql { DELETE FROM t1 } +} + +do_test multiplex-5.4.1 { + catch { db close } + multiplex_delete test.db + file mkdir test.db + list [catch { sqlite3 db test.db } msg] $msg +} {1 {unable to open database file}} +catch { delete_file test.db } + +do_faultsim_test multiplex-5.5 -prep { + catch { sqlite3_multiplex_shutdown } +} -body { + sqlite3_multiplex_initialize "" 1 + multiplex_set db main 32768 16 +} + +#------------------------------------------------------------------------- +# Test that you can vacuum a multiplex'ed DB. + +ifcapable vacuum { + +sqlite3_multiplex_shutdown +do_test multiplex-6.0.0 { + multiplex_delete test.db + multiplex_delete test.x + sqlite3_multiplex_initialize "" 1 + sqlite3 db test.x + multiplex_set db main 4096 16 +} {SQLITE_OK} + +do_test multiplex-6.1.0 { + execsql { + PRAGMA page_size=1024; + PRAGMA journal_mode=DELETE; + PRAGMA auto_vacuum=OFF; + } + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, randomblob($g_chunk_size)); + INSERT INTO t1 VALUES(2, randomblob($g_chunk_size)); + } +} {} +do_test multiplex-6.2.1 { file size [multiplex_name test.x 0] } [list $g_chunk_size] +do_test multiplex-6.2.2 { file size [multiplex_name test.x 1] } [list $g_chunk_size] + +do_test multiplex-6.3.0 { + execsql { VACUUM } +} {} + +do_test multiplex-6.99 { + db close + multiplex_delete test.x + sqlite3_multiplex_shutdown +} {SQLITE_OK} + +} + + +catch { sqlite3_multiplex_shutdown } +finish_test diff --git a/components/external/SQLite-3.8.1/test/multiplex2.test b/components/external/SQLite-3.8.1/test/multiplex2.test new file mode 100644 index 0000000000000000000000000000000000000000..bdfc05b82f6379cb5c483685ce852a09ff64ed58 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/multiplex2.test @@ -0,0 +1,70 @@ +# 2010 October 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +source $testdir/lock_common.tcl + + +do_multiclient_test tn { + code1 { catch { sqlite3_multiplex_initialize "" 0 } } + code2 { catch { sqlite3_multiplex_initialize "" 0 } } + + code1 { db close } + code2 { db2 close } + + code1 { sqlite3 db test.db -vfs multiplex } + code2 { sqlite3 db2 test.db -vfs multiplex } + + code1 { sqlite3_multiplex_control db main chunk_size [expr 1024*1024] } + code2 { sqlite3_multiplex_control db2 main chunk_size [expr 1024*1024] } + + sql1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(randomblob(10), randomblob(4000)); -- 1 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 2 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 256 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 512 + SELECT count(*) FROM t1; + } + + do_test multiplex-1.$tn.1 { sql1 { SELECT count(*) FROM t1 } } 512 + do_test multiplex-1.$tn.2 { sql2 { SELECT count(*) FROM t1 } } 512 + sql2 { DELETE FROM t1 ; VACUUM } + do_test multiplex-1.$tn.3 { sql1 { SELECT count(*) FROM t1 } } 0 + + sql1 { + INSERT INTO t1 VALUES(randomblob(10), randomblob(4000)); -- 1 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 2 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 256 + INSERT INTO t1 SELECT randomblob(10), randomblob(4000) FROM t1; -- 512 + SELECT count(*) FROM t1; + } + + do_test multiplex-1.$tn.4 { sql2 { SELECT count(*) FROM t1 } } 512 +} + +catch { sqlite3_multiplex_shutdown } +finish_test diff --git a/components/external/SQLite-3.8.1/test/multiplex3.test b/components/external/SQLite-3.8.1/test/multiplex3.test new file mode 100644 index 0000000000000000000000000000000000000000..c1e741acdb33d6fd864241aecd2029fedb3170bc --- /dev/null +++ b/components/external/SQLite-3.8.1/test/multiplex3.test @@ -0,0 +1,166 @@ + +# 2011 December 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests for error (IO, OOM etc.) handling when using +# the multiplexor extension with 8.3 filenames. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +set ::testprefix multiplex3 + +ifcapable !8_3_names { + puts -nonewline "SQLite compiled without SQLITE_ENABLE_8_3_NAMES. " + puts "Skipping tests multiplex3-*." + finish_test + return +} + +db close +sqlite3_shutdown +sqlite3_config_uri 1 +autoinstall_test_functions + +sqlite3_multiplex_initialize "" 1 + +proc destroy_vfs_stack {} { + generic_unregister stack + sqlite3_multiplex_shutdown +} + +proc multiplex_delete_db {} { + forcedelete test.db + for {set i 1} {$i <= 1000} {incr i} { + forcedelete test.[format %03d $i] + } +} + +# Procs to save and restore the current muliplexed database. +# +proc multiplex_save_db {} { + foreach f [glob -nocomplain sv_test.*] { forcedelete $f } + foreach f [glob -nocomplain test.*] { forcecopy $f "sv_$f" } +} +proc multiplex_restore_db {} { + foreach f [glob -nocomplain test.*] {forcedelete $f} + foreach f [glob -nocomplain sv_test.*] {forcecopy $f [string range $f 3 end]} } + +proc setup_and_save_db {} { + multiplex_delete_db + sqlite3 db file:test.db?8_3_names=1 + sqlite3_multiplex_control db main chunk_size [expr 256*1024] + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(randomblob(15), randomblob(2000)); + INSERT INTO t1 SELECT randomblob(15), randomblob(2000) FROM t1; -- 2 + INSERT INTO t1 SELECT randomblob(15), randomblob(2000) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(15), randomblob(2000) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(15), randomblob(2000) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(15), randomblob(2000) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(15), randomblob(2000) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(15), randomblob(2000) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(15), randomblob(2000) FROM t1; -- 256 + INSERT INTO t1 SELECT randomblob(15), randomblob(2000) FROM t1; -- 512 + } + set ::cksum1 [execsql {SELECT md5sum(a, b) FROM t1 ORDER BY a}] + db close + multiplex_save_db +} + +do_test 1.0 { setup_and_save_db } {} +do_faultsim_test 1 -prep { + multiplex_restore_db + sqlite3 db file:test.db?8_3_names=1 + sqlite3_multiplex_control db main chunk_size [expr 256*1024] +} -body { + execsql { + UPDATE t1 SET a=randomblob(12), b=randomblob(1500) WHERE (rowid%32)=0 + } +} -test { + faultsim_test_result {0 {}} + if {$testrc!=0} { + set cksum2 [execsql {SELECT md5sum(a, b) FROM t1 ORDER BY a}] + if {$cksum2 != $::cksum1} { error "data mismatch" } + } +} + +#------------------------------------------------------------------------- +# The following tests verify that hot-journal rollback works. As follows: +# +# 1. Create a large database. +# 2. Set the pager cache to be very small. +# 3. Open a transaction. +# 4. Run the following 100 times: +# a. Update a row. +# b. Copy all files on disk to a new db location, including the journal. +# c. Verify that the new db can be opened and that the content matches +# the database created in step 1 (proving the journal was rolled +# back). + +do_test 2.0 { + setup_and_save_db + multiplex_restore_db + sqlite3 db file:test.db?8_3_names=1 + execsql { PRAGMA cache_size = 10 } + execsql { BEGIN } +} {} + +for {set iTest 1} {$iTest<=100} {incr iTest} { + do_test 2.$iTest { + execsql { + UPDATE t1 SET a=randomblob(12), b=randomblob(1400) WHERE rowid=5*$iTest + } + foreach f [glob -nocomplain test.*] {forcecopy $f "xx_$f"} + sqlite3 db2 file:xx_test.db?8_3_names=1 + execsql {SELECT md5sum(a, b) FROM t1 ORDER BY a} db2 + } $::cksum1 + + db2 close +} +catch { db close } + + +do_test 3.0 { setup_and_save_db } {} +do_faultsim_test 3 -faults ioerr-trans* -prep { + + forcedelete test2.db + set fd [open test2.wal w] + seek $fd 4095 + puts -nonewline $fd x + close $fd + + multiplex_restore_db + sqlite3 db file:test.db?8_3_names=1 + sqlite3 db2 file:test2.db?8_3_names=1 + sqlite3_multiplex_control db main chunk_size [expr 256*1024] + sqlite3_multiplex_control db2 main chunk_size [expr 256*1024] +} -body { + sqlite3_backup B db2 main db main + B step 100000 + set rc [B finish] + if { [string match SQLITE_IOERR_* $rc] } {error "disk I/O error"} + set rc +} -test { + faultsim_test_result {0 SQLITE_OK} + if {$testrc==0} { + set cksum2 [execsql {SELECT md5sum(a, b) FROM t1 ORDER BY a} db2] + if {$cksum2 != $::cksum1} { error "data mismatch" } + } + catch { B finish } + catch { db close } + catch { db2 close } +} + +catch { db close } +sqlite3_multiplex_shutdown +finish_test diff --git a/components/external/SQLite-3.8.1/test/mutex1.test b/components/external/SQLite-3.8.1/test/mutex1.test new file mode 100644 index 0000000000000000000000000000000000000000..4bdf769ad302c7c777de58d7b03a5f7c21061c2d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mutex1.test @@ -0,0 +1,192 @@ +# 2008 June 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: mutex1.test,v 1.20 2009/04/23 14:58:40 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !mutex { + finish_test + return +} +if {[info exists tester_do_binarylog]} { + finish_test + return +} + +sqlite3_reset_auto_extension +clear_mutex_counters + +proc mutex_counters {varname} { + upvar $varname var + set var(total) 0 + foreach {name value} [read_mutex_counters] { + set var($name) $value + incr var(total) $value + } +} + +#------------------------------------------------------------------------- +# Tests mutex1-1.* test that sqlite3_config() returns SQLITE_MISUSE if +# is called at the wrong time. And that the first time sqlite3_initialize +# is called it obtains the 'static_master' mutex 3 times and a recursive +# mutex (sqlite3Config.pInitMutex) twice. Subsequent calls are no-ops +# that do not require any mutexes. +# +do_test mutex1-1.0 { + install_mutex_counters 1 +} {SQLITE_MISUSE} + +do_test mutex1-1.1 { + db close + install_mutex_counters 1 +} {SQLITE_MISUSE} + +do_test mutex1-1.2 { + sqlite3_shutdown + install_mutex_counters 1 +} {SQLITE_OK} + +do_test mutex1-1.3 { + install_mutex_counters 0 +} {SQLITE_OK} + +do_test mutex1-1.4 { + install_mutex_counters 1 +} {SQLITE_OK} + +do_test mutex1-1.5 { + mutex_counters counters + set counters(total) +} {0} + +do_test mutex1-1.6 { + sqlite3_initialize +} {SQLITE_OK} + +do_test mutex1-1.7 { + mutex_counters counters + # list $counters(total) $counters(static_master) + expr {$counters(total)>0} +} {1} + +do_test mutex1-1.8 { + clear_mutex_counters + sqlite3_initialize +} {SQLITE_OK} + +do_test mutex1-1.9 { + mutex_counters counters + list $counters(total) $counters(static_master) +} {0 0} + +#------------------------------------------------------------------------- +# Tests mutex1-2.* test the three thread-safety related modes that +# can be selected using sqlite3_config: +# +# * Serialized mode, +# * Multi-threaded mode, +# * Single-threaded mode. +# +ifcapable threadsafe&&shared_cache { + set enable_shared_cache [sqlite3_enable_shared_cache 1] + foreach {mode mutexes} { + singlethread {} + multithread { + fast static_lru static_master static_mem static_open static_prng + static_pmem + } + serialized { + fast recursive static_lru static_master static_mem static_open + static_prng static_pmem + } + } { + + do_test mutex1.2.$mode.1 { + catch {db close} + sqlite3_shutdown + sqlite3_config $mode + } SQLITE_OK + + do_test mutex1.2.$mode.2 { + sqlite3_initialize + clear_mutex_counters + sqlite3 db test.db -nomutex 0 -fullmutex 0 + catchsql { CREATE TABLE abc(a, b, c) } + db eval { + INSERT INTO abc VALUES(1, 2, 3); + } + } {} + ifcapable !memorymanage { + regsub { static_lru} $mutexes {} mutexes + } + do_test mutex1.2.$mode.3 { + mutex_counters counters + + set res [list] + foreach {key value} [array get counters] { + if {$key ne "total" && $value > 0} { + lappend res $key + } + } + lsort $res + } [lsort $mutexes] + } + sqlite3_enable_shared_cache $enable_shared_cache + + # Open and use a connection in "nomutex" mode. Test that no recursive + # mutexes are obtained. + do_test mutex1.3.1 { + catch {db close} + clear_mutex_counters + sqlite3 db test.db -nomutex 1 + execsql { SELECT * FROM abc } + } {1 2 3 1 2 3 1 2 3} + do_test mutex1.3.2 { + mutex_counters counters + set counters(recursive) + } {0} +} + +# Test the sqlite3_db_mutex() function. +# +do_test mutex1.4.1 { + catch {db close} + sqlite3 db test.db + enter_db_mutex db + db eval {SELECT 1, 2, 3} +} {1 2 3} +do_test mutex1.4.2 { + leave_db_mutex db + db eval {SELECT 1, 2, 3} +} {1 2 3} +do_test mutex1.4.3 { + catch {db close} + sqlite3 db test.db -nomutex 1 + enter_db_mutex db + db eval {SELECT 1, 2, 3} +} {1 2 3} +do_test mutex1.4.4 { + leave_db_mutex db + db eval {SELECT 1, 2, 3} +} {1 2 3} + +do_test mutex1-X { + catch {db close} + sqlite3_shutdown + clear_mutex_counters + install_mutex_counters 0 + sqlite3_initialize +} {SQLITE_OK} + +autoinstall_test_functions +finish_test diff --git a/components/external/SQLite-3.8.1/test/mutex2.test b/components/external/SQLite-3.8.1/test/mutex2.test new file mode 100644 index 0000000000000000000000000000000000000000..9dfb03e0dea1b9dd6c2a294c46735b134d656000 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/mutex2.test @@ -0,0 +1,105 @@ +# 2008 July 7 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test scripts for deliberate failures of mutex routines. +# +# $Id: mutex2.test,v 1.9 2008/10/07 15:25:49 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !mutex { + finish_test + return +} + +# deinitialize +# +catch {db close} +sqlite3_reset_auto_extension +sqlite3_shutdown +install_mutex_counters 1 + +# Fix the mutex subsystem so that it will not initialize. In other words, +# make it so that sqlite3_initialize() always fails. +# +do_test mutex2-1.1 { + set ::disable_mutex_init 10 + sqlite3_initialize +} {SQLITE_IOERR} +do_test mutex2-1.1 { + set ::disable_mutex_init 7 + sqlite3_initialize +} {SQLITE_NOMEM} + +proc utf16 {str} { + set r [encoding convertto unicode $str] + append r "\x00\x00" + return $r +} + +# Now that sqlite3_initialize() is failing, try to run various APIs that +# require that SQLite be initialized. Verify that they fail. +# +do_test mutex2-2.1 { + set ::disable_mutex_init 7 + set rc [catch {sqlite db test.db} msg] + lappend rc $msg +} {1 {}} +ifcapable utf16 { + do_test mutex2-2.2 { + set db2 [sqlite3_open16 [utf16 test.db] {}] + } {0} + do_test mutex2-2.3 { + sqlite3_complete16 [utf16 {SELECT * FROM t1;}] + } {7} +} +do_test mutex2-2.4 { + sqlite3_mprintf_int {This is a test %d,%d,%d} 1 2 3 +} {} +ifcapable load_ext { + do_test mutex2-2.5 { + sqlite3_auto_extension_sqr + } {7} +} +do_test mutex2-2.6 { + sqlite3_reset_auto_extension +} {} +do_test mutex2-2.7 { + sqlite3_malloc 10000 +} {0} +do_test mutex2-2.8 { + sqlite3_realloc 0 10000 +} {0} +ifcapable threadsafe { + do_test mutex2-2.9 { + alloc_dealloc_mutex + } {0} +} +do_test mutex2-2.10 { + vfs_initfail_test +} {} + +# Restore the system to a functional state +# +install_mutex_counters 0 +set disable_mutex_init 0 +autoinstall_test_functions + +# Mutex allocation works now. +# + +do_test mutex2-3.1 { + set ptr [alloc_dealloc_mutex] + expr {$ptr!=0} +} {1} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/nan.test b/components/external/SQLite-3.8.1/test/nan.test new file mode 100644 index 0000000000000000000000000000000000000000..df3f65b8e6229bcbe7744949ac34ef4f5df4c3a4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/nan.test @@ -0,0 +1,371 @@ +# 2008 April 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3060 +# +# Make sure IEEE floating point NaN values are handled properly. +# SQLite should always convert NaN into NULL. +# +# Also verify that the decimal to IEEE754 binary conversion routines +# correctly generate 0.0, +Inf, and -Inf as appropriate for numbers +# out of range. +# +# $Id: nan.test,v 1.5 2008/09/18 11:30:13 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +do_test nan-1.1.1 { + db eval { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size=1024; + CREATE TABLE t1(x FLOAT); + } + set ::STMT [sqlite3_prepare db "INSERT INTO t1 VALUES(?)" -1 TAIL] + sqlite3_bind_double $::STMT 1 NaN + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT x, typeof(x) FROM t1} +} {{} null} +if {$tcl_platform(platform) != "symbian"} { + do_realnum_test nan-1.1.2 { + sqlite3_bind_double $::STMT 1 +Inf + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT x, typeof(x) FROM t1} + } {{} null inf real} + do_realnum_test nan-1.1.3 { + sqlite3_bind_double $::STMT 1 -Inf + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT x, typeof(x) FROM t1} + } {{} null inf real -inf real} + do_realnum_test nan-1.1.4 { + sqlite3_bind_double $::STMT 1 -NaN + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT x, typeof(x) FROM t1} + } {{} null inf real -inf real {} null} + do_realnum_test nan-1.1.5 { + sqlite3_bind_double $::STMT 1 NaN0 + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT x, typeof(x) FROM t1} + } {{} null inf real -inf real {} null {} null} + do_realnum_test nan-1.1.6 { + sqlite3_bind_double $::STMT 1 -NaN0 + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT x, typeof(x) FROM t1} + } {{} null inf real -inf real {} null {} null {} null} + do_test nan-1.1.7 { + db eval { + UPDATE t1 SET x=x-x; + SELECT x, typeof(x) FROM t1; + } + } {{} null {} null {} null {} null {} null {} null} +} + +# The following block of tests, nan-1.2.*, are the same as the nan-1.1.* +# tests above, except that the SELECT queries used to validate data +# convert floating point values to text internally before returning them +# to Tcl. This allows the tests to be run on platforms where Tcl has +# problems converting "inf" and "-inf" from floating point to text format. +# It also tests the internal float->text conversion routines a bit. +# +do_test nan-1.2.1 { + db eval { + DELETE FROM T1; + } + sqlite3_bind_double $::STMT 1 NaN + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {{} null} +do_test nan-1.2.2 { + sqlite3_bind_double $::STMT 1 +Inf + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {{} null Inf real} +do_test nan-1.2.3 { + sqlite3_bind_double $::STMT 1 -Inf + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {{} null Inf real -Inf real} +do_test nan-1.2.4 { + sqlite3_bind_double $::STMT 1 -NaN + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {{} null Inf real -Inf real {} null} +do_test nan-1.2.5 { + sqlite3_bind_double $::STMT 1 NaN0 + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {{} null Inf real -Inf real {} null {} null} +do_test nan-1.2.6 { + sqlite3_bind_double $::STMT 1 -NaN0 + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {{} null Inf real -Inf real {} null {} null {} null} +do_test nan-1.2.7 { + db eval { + UPDATE t1 SET x=x-x; + SELECT CAST(x AS text), typeof(x) FROM t1; + } +} {{} null {} null {} null {} null {} null {} null} + +do_test nan-2.1 { + db eval { + DELETE FROM T1; + } + sqlite3_bind_double $::STMT 1 NaN + sqlite3_step $::STMT + sqlite3_reset $::STMT + db eval {SELECT x, typeof(x) FROM t1} +} {{} null} +sqlite3_finalize $::STMT + +# SQLite always converts NaN into NULL so it is not possible to write +# a NaN value into the database file using SQLite. The following series +# of tests writes a normal floating point value (0.5) into the database, +# then writes directly into the database file to change the 0.5 into NaN. +# Then it reads the value of the database to verify it is converted into +# NULL. +# +do_test nan-3.1 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES(0.5); + PRAGMA auto_vacuum=OFF; + PRAGMA page_size=1024; + VACUUM; + } + hexio_read test.db 2040 8 +} {3FE0000000000000} +do_test nan-3.2 { + db eval { + SELECT x, typeof(x) FROM t1 + } +} {0.5 real} +do_test nan-3.3 { + db close + hexio_write test.db 2040 FFF8000000000000 + sqlite3 db test.db + db eval {SELECT x, typeof(x) FROM t1} +} {{} null} +do_test nan-3.4 { + db close + hexio_write test.db 2040 7FF8000000000000 + sqlite3 db test.db + db eval {SELECT x, typeof(x) FROM t1} +} {{} null} +do_test nan-3.5 { + db close + hexio_write test.db 2040 FFFFFFFFFFFFFFFF + sqlite3 db test.db + db eval {SELECT x, typeof(x) FROM t1} +} {{} null} +do_test nan-3.6 { + db close + hexio_write test.db 2040 7FFFFFFFFFFFFFFF + sqlite3 db test.db + db eval {SELECT x, typeof(x) FROM t1} +} {{} null} + +# Verify that the sqlite3AtoF routine is able to handle extreme +# numbers. +# +do_test nan-4.1 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES([string repeat 9 307].0)" + db eval {SELECT x, typeof(x) FROM t1} +} {1e+307 real} +do_test nan-4.2 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES([string repeat 9 308].0)" + db eval {SELECT x, typeof(x) FROM t1} +} {1e+308 real} +do_test nan-4.3 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES(-[string repeat 9 307].0)" + db eval {SELECT x, typeof(x) FROM t1} +} {-1e+307 real} +do_test nan-4.4 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES(-[string repeat 9 308].0)" + db eval {SELECT x, typeof(x) FROM t1} +} {-1e+308 real} +do_test nan-4.5 { + db eval {DELETE FROM t1} + set big -[string repeat 0 10000][string repeat 9 308].[string repeat 0 10000] + db eval "INSERT INTO t1 VALUES($big)" + db eval {SELECT x, typeof(x) FROM t1} +} {-1e+308 real} +do_test nan-4.6 { + db eval {DELETE FROM t1} + set big [string repeat 0 10000][string repeat 9 308].[string repeat 0 10000] + db eval "INSERT INTO t1 VALUES($big)" + db eval {SELECT x, typeof(x) FROM t1} +} {1e+308 real} + +if {$tcl_platform(platform) != "symbian"} { + # Do not run these tests on Symbian, as the Tcl port doesn't like to + # convert from floating point value "-inf" to a string. + # + do_realnum_test nan-4.7 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES([string repeat 9 309].0)" + db eval {SELECT x, typeof(x) FROM t1} + } {inf real} + do_realnum_test nan-4.8 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES(-[string repeat 9 309].0)" + db eval {SELECT x, typeof(x) FROM t1} + } {-inf real} +} +do_test nan-4.9 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES([string repeat 9 309].0)" + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {Inf real} +do_test nan-4.10 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES(-[string repeat 9 309].0)" + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {-Inf real} + +do_test nan-4.11 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES(1234.5[string repeat 0 10000]12345)" + db eval {SELECT x, typeof(x) FROM t1} +} {1234.5 real} +do_test nan-4.12 { + db eval {DELETE FROM t1} + db eval "INSERT INTO t1 VALUES(-1234.5[string repeat 0 10000]12345)" + db eval {SELECT x, typeof(x) FROM t1} +} {-1234.5 real} +do_test nan-4.13 { + db eval {DELETE FROM t1} + set small [string repeat 0 10000].[string repeat 0 324][string repeat 9 10000] + db eval "INSERT INTO t1 VALUES($small)" + db eval {SELECT x, typeof(x) FROM t1} +} {0.0 real} +do_test nan-4.14 { + db eval {DELETE FROM t1} + set small \ + -[string repeat 0 10000].[string repeat 0 324][string repeat 9 10000] + db eval "INSERT INTO t1 VALUES($small)" + db eval {SELECT x, typeof(x) FROM t1} +} {0.0 real} + +# These tests test some really, really small floating point numbers. +# +if {$tcl_platform(platform) != "symbian"} { + # These two are not run on symbian because tcl has trouble converting + # the very small numbers back to text form (probably due to a difference + # in the sprintf() implementation). + # + do_test nan-4.15 { + db eval {DELETE FROM t1} + set small \ + [string repeat 0 10000].[string repeat 0 323][string repeat 9 10000] + db eval "INSERT INTO t1 VALUES($small)" + db eval {SELECT x, typeof(x) FROM t1} + } {9.88131291682493e-324 real} + do_test nan-4.16 { + db eval {DELETE FROM t1} + set small \ + -[string repeat 0 10000].[string repeat 0 323][string repeat 9 10000] + db eval "INSERT INTO t1 VALUES($small)" + db eval {SELECT x, typeof(x) FROM t1} + } {-9.88131291682493e-324 real} +} +do_test nan-4.17 { + db eval {DELETE FROM t1} + set small [string repeat 0 10000].[string repeat 0 323][string repeat 9 10000] + db eval "INSERT INTO t1 VALUES($small)" + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {9.88131291682493e-324 real} +do_test nan-4.18 { + db eval {DELETE FROM t1} + set small \ + -[string repeat 0 10000].[string repeat 0 323][string repeat 9 10000] + db eval "INSERT INTO t1 VALUES($small)" + db eval {SELECT CAST(x AS text), typeof(x) FROM t1} +} {-9.88131291682493e-324 real} + +do_realnum_test nan-4.20 { + db eval {DELETE FROM t1} + set big [string repeat 9 10000].0e-9000 + db eval "INSERT INTO t1 VALUES($big)" + db eval {SELECT x, typeof(x) FROM t1} +} {inf real} + +do_realnum_test nan-4.30 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES('2.5e+9999'); + SELECT x, typeof(x) FROM t1; + } +} {inf real} +do_realnum_test nan-4.31 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES('2.5e+10000'); + SELECT x, typeof(x) FROM t1; + } +} {inf real} + +do_realnum_test nan-4.32 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES('2.5e-9999'); + SELECT x, typeof(x) FROM t1; + } +} {0.0 real} +do_realnum_test nan-4.33 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES('2.5e-10000'); + SELECT x, typeof(x) FROM t1; + } +} {0.0 real} +do_realnum_test nan-4.34 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES('2.5e2147483650'); + SELECT x, typeof(x) FROM t1; + } +} {inf real} +do_realnum_test nan-4.35 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES('2.5e-2147483650'); + SELECT x, typeof(x) FROM t1; + } +} {0.0 real} + + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/notify1.test b/components/external/SQLite-3.8.1/test/notify1.test new file mode 100644 index 0000000000000000000000000000000000000000..be6a122585da99e1ccecdad95b242f8651109d44 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/notify1.test @@ -0,0 +1,500 @@ +# 2009 March 04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the sqlite3_unlock_notify() API. +# +# $Id: notify1.test,v 1.4 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !unlock_notify||!shared_cache { + finish_test + return +} +db close +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +#------------------------------------------------------------------------- +# Warm body test. Test that an unlock-notify callback can be registered +# and that it is invoked. +# +do_test notify1-1.1 { + sqlite3 db test.db + sqlite3 db2 test.db + execsql { CREATE TABLE t1(a, b) } +} {} +do_test notify1-1.2 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(1, 2); + } + catchsql { INSERT INTO t1 VALUES(3, 4) } db2 +} {1 {database table is locked}} +do_test notify1-1.3 { + set zScript "" + db2 unlock_notify { + set zScript "db2 eval { INSERT INTO t1 VALUES(3, 4) }" + } + execsql { SELECT * FROM t1 } +} {1 2} +do_test notify1-1.4 { + set zScript +} {} +do_test notify1-1.5 { + execsql { COMMIT } + eval $zScript + execsql { SELECT * FROM t1 } +} {1 2 3 4} + +#------------------------------------------------------------------------- +# Verify that invoking the "unlock_notify" method with no arguments +# (which is the equivalent of invoking sqlite3_unlock_notify() with +# a NULL xNotify argument) cancels a pending notify callback. +# +do_test notify1-1.11 { + execsql { DROP TABLE t1; CREATE TABLE t1(a, b) } +} {} +do_test notify1-1.12 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(1, 2); + } + catchsql { INSERT INTO t1 VALUES(3, 4) } db2 +} {1 {database table is locked}} +do_test notify1-1.13 { + set zScript "" + db2 unlock_notify { + set zScript "db2 eval { INSERT INTO t1 VALUES(3, 4) }" + } + execsql { SELECT * FROM t1 } +} {1 2} +do_test notify1-1.14 { + set zScript +} {} +do_test notify1-1.15 { + db2 unlock_notify + execsql { COMMIT } + eval $zScript + execsql { SELECT * FROM t1 } +} {1 2} + +#------------------------------------------------------------------------- +# The following tests, notify1-2.*, test that deadlock is detected +# correctly. +# +do_test notify1-2.1 { + execsql { + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES('I', 'II'); + } +} {} + +# +# Test for simple deadlock involving two database connections. +# +# 1. Grab a write-lock on t1 with [db]. Then grab a read-lock on t2 with [db2]. +# 2. Try to grab a read-lock on t1 with [db2] (fails). +# 3. Have [db2] wait on the read-lock it failed to obtain in step 2. +# 4. Try to grab a write-lock on t2 with [db] (fails). +# 5. Try to have [db] wait on the lock from step 4. Fails, as the system +# would be deadlocked (since [db2] is already waiting on [db], and this +# operation would have [db] wait on [db2]). +# +do_test notify1-2.2.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(5, 6); + } + execsql { + BEGIN; + SELECT * FROM t2; + } db2 +} {I II} +do_test notify1-2.2.2 { + catchsql { SELECT * FROM t1 } db2 +} {1 {database table is locked: t1}} +do_test notify1-2.2.3 { + db2 unlock_notify {lappend unlock_notify db2} +} {} +do_test notify1-2.2.4 { + catchsql { INSERT INTO t2 VALUES('III', 'IV') } +} {1 {database table is locked: t2}} +do_test notify1-2.2.5 { + set rc [catch { db unlock_notify {lappend unlock_notify db} } msg] + list $rc $msg +} {1 {database is deadlocked}} + +# +# Test for slightly more complex deadlock involving three database +# connections: db, db2 and db3. +# +do_test notify1-2.3.1 { + db close + db2 close + forcedelete test.db test2.db test3.db + foreach con {db db2 db3} { + sqlite3 $con test.db + $con eval { ATTACH 'test2.db' AS aux2 } + $con eval { ATTACH 'test3.db' AS aux3 } + } + execsql { + CREATE TABLE main.t1(a, b); + CREATE TABLE aux2.t2(a, b); + CREATE TABLE aux3.t3(a, b); + } +} {} +do_test notify1-2.3.2 { + execsql { BEGIN ; INSERT INTO t1 VALUES(1, 2) } db + execsql { BEGIN ; INSERT INTO t2 VALUES(1, 2) } db2 + execsql { BEGIN ; INSERT INTO t3 VALUES(1, 2) } db3 +} {} +do_test notify1-2.3.3 { + catchsql { SELECT * FROM t2 } db +} {1 {database table is locked: t2}} +do_test notify1-2.3.4 { + catchsql { SELECT * FROM t3 } db2 +} {1 {database table is locked: t3}} +do_test notify1-2.3.5 { + catchsql { SELECT * FROM t1 } db3 +} {1 {database table is locked: t1}} +do_test notify1-2.3.6 { + set lUnlock [list] + db unlock_notify {lappend lUnlock db} + db2 unlock_notify {lappend lUnlock db2} +} {} +do_test notify1-2.3.7 { + set rc [catch { db3 unlock_notify {lappend lUnlock db3} } msg] + list $rc $msg +} {1 {database is deadlocked}} +do_test notify1-2.3.8 { + execsql { COMMIT } + set lUnlock +} {} +do_test notify1-2.3.9 { + db3 unlock_notify {lappend lUnlock db3} + set lUnlock +} {db3} +do_test notify1-2.3.10 { + execsql { COMMIT } db2 + set lUnlock +} {db3 db} +do_test notify1-2.3.11 { + execsql { COMMIT } db3 + set lUnlock +} {db3 db db2} +catch { db3 close } +catch { db2 close } +catch { db close } + +#------------------------------------------------------------------------- +# The following tests, notify1-3.* and notify1-4.*, test that callbacks +# can be issued when there are many (>16) connections waiting on a single +# unlock event. +# +foreach {tn nConn} {3 20 4 76} { + do_test notify1-$tn.1 { + sqlite3 db test.db + execsql { + BEGIN; + INSERT INTO t1 VALUES('a', 'b'); + } + } {} + set lUnlock [list] + set lUnlockFinal [list] + for {set ii 1} {$ii <= $nConn} {incr ii} { + do_test notify1-$tn.2.$ii.1 { + set cmd "db$ii" + sqlite3 $cmd test.db + catchsql { SELECT * FROM t1 } $cmd + } {1 {database table is locked: t1}} + do_test notify1-$tn.2.$ii.2 { + $cmd unlock_notify "lappend lUnlock $ii" + } {} + lappend lUnlockFinal $ii + } + do_test notify1-$tn.3 { + set lUnlock + } {} + do_test notify1-$tn.4 { + execsql {COMMIT} + lsort -integer $lUnlock + } $lUnlockFinal + do_test notify1-$tn.5 { + for {set ii 1} {$ii <= $nConn} {incr ii} { + "db$ii" close + } + } {} +} +db close + +#------------------------------------------------------------------------- +# These tests, notify1-5.*, test that a malloc() failure that occurs while +# allocating an array to use as an argument to an unlock-notify callback +# is handled correctly. +# +source $testdir/malloc_common.tcl +do_malloc_test notify1-5 -tclprep { + set ::lUnlock [list] + execsql { + CREATE TABLE t1(a, b); + BEGIN; + INSERT INTO t1 VALUES('a', 'b'); + } + for {set ii 1} {$ii <= 60} {incr ii} { + set cmd "db$ii" + sqlite3 $cmd test.db + catchsql { SELECT * FROM t1 } $cmd + $cmd unlock_notify "lappend ::lUnlock $ii" + } +} -sqlbody { + COMMIT; +} -cleanup { + # One of two things should have happened: + # + # 1) The transaction opened by [db] was not committed. No unlock-notify + # callbacks were invoked, OR + # 2) The transaction opened by [db] was committed and 60 unlock-notify + # callbacks were invoked. + # + do_test notify1-5.systemstate { + expr { ([llength $::lUnlock]==0 && [sqlite3_get_autocommit db]==0) + || ([llength $::lUnlock]==60 && [sqlite3_get_autocommit db]==1) + } + } {1} + for {set ii 1} {$ii <= 60} {incr ii} { "db$ii" close } +} + +#------------------------------------------------------------------------- +# Test cases notify1-6.* test cases where the following occur: +# +# notify1-6.1.*: Test encountering an SQLITE_LOCKED error when the +# "blocking connection" has already been set by a previous +# SQLITE_LOCKED. +# +# notify1-6.2.*: Test encountering an SQLITE_LOCKED error when already +# waiting on an unlock-notify callback. +# +# notify1-6.3.*: Test that if an SQLITE_LOCKED error is encountered while +# already waiting on an unlock-notify callback, and then +# the blocker that caused the SQLITE_LOCKED commits its +# transaction, the unlock-notify callback is not invoked. +# +# notify1-6.4.*: Like 6.3.*, except that instead of the second blocker +# committing its transaction, the first does. The +# unlock-notify callback is therefore invoked. +# +db close +do_test notify1-6.1.1 { + forcedelete test.db test2.db + foreach conn {db db2 db3} { + sqlite3 $conn test.db + execsql { ATTACH 'test2.db' AS two } $conn + } + execsql { + CREATE TABLE t1(a, b); + CREATE TABLE two.t2(a, b); + } + execsql { + BEGIN; + INSERT INTO t1 VALUES(1, 2); + } db2 + execsql { + BEGIN; + INSERT INTO t2 VALUES(1, 2); + } db3 +} {} +do_test notify1-6.1.2 { + catchsql { SELECT * FROM t2 } +} {1 {database table is locked: t2}} +do_test notify1-6.1.3 { + catchsql { SELECT * FROM t1 } +} {1 {database table is locked: t1}} + +do_test notify1-6.2.1 { + set unlocked 0 + db unlock_notify {set unlocked 1} + set unlocked +} {0} +do_test notify1-6.2.2 { + catchsql { SELECT * FROM t2 } +} {1 {database table is locked: t2}} +do_test notify1-6.2.3 { + execsql { COMMIT } db2 + set unlocked +} {1} + +do_test notify1-6.3.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(3, 4); + } db2 +} {} +do_test notify1-6.3.2 { + catchsql { SELECT * FROM t1 } +} {1 {database table is locked: t1}} +do_test notify1-6.3.3 { + set unlocked 0 + db unlock_notify {set unlocked 1} + set unlocked +} {0} +do_test notify1-6.3.4 { + catchsql { SELECT * FROM t2 } +} {1 {database table is locked: t2}} +do_test notify1-6.3.5 { + execsql { COMMIT } db3 + set unlocked +} {0} + +do_test notify1-6.4.1 { + execsql { + BEGIN; + INSERT INTO t2 VALUES(3, 4); + } db3 + catchsql { SELECT * FROM t2 } +} {1 {database table is locked: t2}} +do_test notify1-6.4.2 { + execsql { COMMIT } db2 + set unlocked +} {1} +do_test notify1-6.4.3 { + execsql { COMMIT } db3 +} {} +db close +db2 close +db3 close + +#------------------------------------------------------------------------- +# Test cases notify1-7.* tests that when more than one distinct +# unlock-notify function is registered, all are invoked correctly. +# +proc unlock_notify {} { + incr ::unlock_notify +} +do_test notify1-7.1 { + foreach conn {db db2 db3} { + sqlite3 $conn test.db + } + execsql { + BEGIN; + INSERT INTO t1 VALUES(5, 6); + } +} {} +do_test notify1-7.2 { + catchsql { SELECT * FROM t1 } db2 +} {1 {database table is locked: t1}} +do_test notify1-7.3 { + catchsql { SELECT * FROM t1 } db3 +} {1 {database table is locked: t1}} +do_test notify1-7.4 { + set unlock_notify 0 + db2 unlock_notify unlock_notify + sqlite3_unlock_notify db3 +} {SQLITE_OK} +do_test notify1-7.5 { + set unlock_notify +} {0} +do_test notify1-7.6 { + execsql { COMMIT } + set unlock_notify +} {2} + +#------------------------------------------------------------------------- +# Test cases notify1-8.* tests that the correct SQLITE_LOCKED extended +# error code is returned in various scenarios. +# +do_test notify1-8.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(7, 8); + } + catchsql { SELECT * FROM t1 } db2 +} {1 {database table is locked: t1}} +do_test notify1-8.2 { + sqlite3_extended_errcode db2 +} {SQLITE_LOCKED_SHAREDCACHE} + +do_test notify1-8.3 { + execsql { + COMMIT; + BEGIN EXCLUSIVE; + } + catchsql { SELECT * FROM t1 } db2 +} {1 {database schema is locked: main}} +do_test notify1-8.4 { + sqlite3_extended_errcode db2 +} {SQLITE_LOCKED_SHAREDCACHE} + +do_test notify1-8.X { + execsql { COMMIT } +} {} + +#------------------------------------------------------------------------- +# Test cases notify1-9.* test the shared-cache 'pending-lock' feature. +# +do_test notify1-9.1 { + execsql { + CREATE TABLE t2(a, b); + BEGIN; + SELECT * FROM t1; + } db2 +} {1 2 3 4 5 6 7 8} +do_test notify1-9.2 { + execsql { SELECT * FROM t1 } db3 +} {1 2 3 4 5 6 7 8} +do_test notify1-9.3 { + catchsql { + BEGIN; + INSERT INTO t1 VALUES(9, 10); + } +} {1 {database table is locked: t1}} +do_test notify1-9.4 { + catchsql { SELECT * FROM t2 } db3 +} {1 {database table is locked}} +do_test notify1-9.5 { + execsql { COMMIT } db2 + execsql { SELECT * FROM t2 } db3 +} {} +do_test notify1-9.6 { + execsql { COMMIT } +} {} + +do_test notify1-9.7 { + execsql { + BEGIN; + SELECT * FROM t1; + } db2 +} {1 2 3 4 5 6 7 8} +do_test notify1-9.8 { + execsql { SELECT * FROM t1 } db3 +} {1 2 3 4 5 6 7 8} +do_test notify1-9.9 { + catchsql { + BEGIN; + INSERT INTO t1 VALUES(9, 10); + } +} {1 {database table is locked: t1}} +do_test notify1-9.10 { + catchsql { SELECT * FROM t2 } db3 +} {1 {database table is locked}} +do_test notify1-9.11 { + execsql { COMMIT } + execsql { SELECT * FROM t2 } db3 +} {} +do_test notify1-9.12 { + execsql { COMMIT } db2 +} {} + +db close +db2 close +db3 close +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/notify2.test b/components/external/SQLite-3.8.1/test/notify2.test new file mode 100644 index 0000000000000000000000000000000000000000..9e40ed695b3911d529685ede2deb643efa5b78e8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/notify2.test @@ -0,0 +1,242 @@ +# 2009 March 04 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: notify2.test,v 1.7 2009/03/30 11:59:31 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +if {[run_thread_tests]==0} { finish_test ; return } +ifcapable !unlock_notify||!shared_cache { finish_test ; return } + +# The tests in this file test the sqlite3_blocking_step() function in +# test_thread.c. sqlite3_blocking_step() is not an SQLite API function, +# it is just a demonstration of how the sqlite3_unlock_notify() function +# can be used to synchronize multi-threaded access to SQLite databases +# in shared-cache mode. +# +# Since the implementation of sqlite3_blocking_step() is included on the +# website as example code, it is important to test that it works. +# +# notify2-1.*: +# +# This test uses $nThread threads. Each thread opens the main database +# and attaches two other databases. Each database contains a single table. +# +# Each thread repeats transactions over and over for 20 seconds. Each +# transaction consists of 3 operations. Each operation is either a read +# or a write of one of the tables. The read operations verify an invariant +# to make sure that things are working as expected. If an SQLITE_LOCKED +# error is returned the current transaction is rolled back immediately. +# +# This exercise is repeated twice, once using sqlite3_step(), and the +# other using sqlite3_blocking_step(). The results are compared to ensure +# that sqlite3_blocking_step() resulted in higher transaction throughput. +# + +db close +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +# Number of threads to run simultaneously. +# +set nThread 6 +set nSecond 5 + +# The Tcl script executed by each of the $nThread threads used by this test. +# +set ThreadProgram { + + # Proc used by threads to execute SQL. + # + proc execsql_blocking {db zSql} { + set lRes [list] + set rc SQLITE_OK + +set sql $zSql + + while {$rc=="SQLITE_OK" && $zSql ne ""} { + set STMT [$::xPrepare $db $zSql -1 zSql] + while {[set rc [$::xStep $STMT]] eq "SQLITE_ROW"} { + for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} { + lappend lRes [sqlite3_column_text $STMT 0] + } + } + set rc [sqlite3_finalize $STMT] + } + + if {$rc != "SQLITE_OK"} { error "$rc $sql [sqlite3_errmsg $db]" } + return $lRes + } + + proc execsql_retry {db sql} { + set msg "SQLITE_LOCKED blah..." + while { [string match SQLITE_LOCKED* $msg] } { + catch { execsql_blocking $db $sql } msg + } + } + + proc select_one {args} { + set n [llength $args] + lindex $args [expr int($n*rand())] + } + + proc opendb {} { + # Open a database connection. Attach the two auxillary databases. + set ::DB [sqlite3_open test.db] + execsql_retry $::DB { ATTACH 'test2.db' AS aux2; } + execsql_retry $::DB { ATTACH 'test3.db' AS aux3; } + } + + opendb + + #after 2000 + + # This loop runs for ~20 seconds. + # + set iStart [clock_seconds] + while { ([clock_seconds]-$iStart) < $nSecond } { + + # Each transaction does 3 operations. Each operation is either a read + # or write of a randomly selected table (t1, t2 or t3). Set the variables + # $SQL(1), $SQL(2) and $SQL(3) to the SQL commands used to implement + # each operation. + # + for {set ii 1} {$ii <= 3} {incr ii} { + foreach {tbl database} [select_one {t1 main} {t2 aux2} {t3 aux3}] {} + + set SQL($ii) [string map [list xxx $tbl yyy $database] [select_one { + SELECT + (SELECT b FROM xxx WHERE a=(SELECT max(a) FROM xxx))==total(a) + FROM xxx WHERE a!=(SELECT max(a) FROM xxx); + } { + DELETE FROM xxx WHERE a<(SELECT max(a)-100 FROM xxx); + INSERT INTO xxx SELECT NULL, total(a) FROM xxx; + } { + CREATE INDEX IF NOT EXISTS yyy.xxx_i ON xxx(b); + } { + DROP INDEX IF EXISTS yyy.xxx_i; + } + ]] + } + + # Execute the SQL transaction. + # + set rc [catch { execsql_blocking $::DB " + BEGIN; + $SQL(1); + $SQL(2); + $SQL(3); + COMMIT; + " + } msg] + + if {$rc && [string match "SQLITE_LOCKED*" $msg] + || [string match "SQLITE_SCHEMA*" $msg] + } { + # Hit an SQLITE_LOCKED error. Rollback the current transaction. + set rc [catch { execsql_blocking $::DB ROLLBACK } msg] + if {$rc && [string match "SQLITE_LOCKED*" $msg]} { + sqlite3_close $::DB + opendb + } + } elseif {$rc} { + # Hit some other kind of error. This is a malfunction. + error $msg + } else { + # No error occurred. Check that any SELECT statements in the transaction + # returned "1". Otherwise, the invariant was false, indicating that + # some malfunction has occurred. + foreach r $msg { if {$r != 1} { puts "Invariant check failed: $msg" } } + } + } + + # Close the database connection and return 0. + # + sqlite3_close $::DB + expr 0 +} + +foreach {iTest xStep xPrepare} { + 1 sqlite3_blocking_step sqlite3_blocking_prepare_v2 + 2 sqlite3_step sqlite3_nonblocking_prepare_v2 +} { + forcedelete test.db test2.db test3.db + + set ThreadSetup "set xStep $xStep;set xPrepare $xPrepare;set nSecond $nSecond" + + # Set up the database schema used by this test. Each thread opens file + # test.db as the main database, then attaches files test2.db and test3.db + # as auxillary databases. Each file contains a single table (t1, t2 and t3, in + # files test.db, test2.db and test3.db, respectively). + # + do_test notify2-$iTest.1.1 { + sqlite3 db test.db + execsql { + ATTACH 'test2.db' AS aux2; + ATTACH 'test3.db' AS aux3; + CREATE TABLE main.t1(a INTEGER PRIMARY KEY, b); + CREATE TABLE aux2.t2(a INTEGER PRIMARY KEY, b); + CREATE TABLE aux3.t3(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 SELECT NULL, 0; + INSERT INTO t2 SELECT NULL, 0; + INSERT INTO t3 SELECT NULL, 0; + } + } {} + do_test notify2-$iTest.1.2 { + db close + } {} + + + # Launch $nThread threads. Then wait for them to finish. + # + puts "Running $xStep test for $nSecond seconds" + unset -nocomplain finished + for {set ii 0} {$ii < $nThread} {incr ii} { + thread_spawn finished($ii) $ThreadSetup $ThreadProgram + } + for {set ii 0} {$ii < $nThread} {incr ii} { + do_test notify2-$iTest.2.$ii { + if {![info exists finished($ii)]} { vwait finished($ii) } + set finished($ii) + } {0} + } + + # Count the total number of succesful writes. + do_test notify2-$iTest.3.1 { + sqlite3 db test.db + execsql { + ATTACH 'test2.db' AS aux2; + ATTACH 'test3.db' AS aux3; + } + set anWrite($xStep) [execsql { + SELECT (SELECT max(a) FROM t1) + + (SELECT max(a) FROM t2) + + (SELECT max(a) FROM t3) + }] + db close + } {} +} + +# The following tests checks to make sure sqlite3_blocking_step() is +# faster than sqlite3_step(). blocking_step() is always faster on +# multi-core and is usually faster on single-core. But sometimes, by +# chance, step() will be faster on a single core, in which case the +# following test will fail. +# +puts "The following test seeks to demonstrate that the sqlite3_unlock_notify()" +puts "interface helps multi-core systems to run faster. This test sometimes" +puts "fails on single-core machines." +puts [array get anWrite] +do_test notify2-3 { + expr {$anWrite(sqlite3_blocking_step) > $anWrite(sqlite3_step)} +} {1} + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/notify3.test b/components/external/SQLite-3.8.1/test/notify3.test new file mode 100644 index 0000000000000000000000000000000000000000..4b5e8016b4d7037a83231b12a6919ada5c732802 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/notify3.test @@ -0,0 +1,152 @@ +# 2010 June 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the sqlite3_unlock_notify() API. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# This script only runs if shared-cache and unlock-notify are available. +# +ifcapable !unlock_notify||!shared_cache { + finish_test + return +} + +set esc [sqlite3_enable_shared_cache 1] + +sqlite3 db test.db +forcedelete test.db2 test.db2-journal test.db2-wal +sqlite3 db2 test.db2 + +do_test notify3-1.1 { + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('t1 A', 't1 B'); + } +} {} +do_test notify3-1.2 { + execsql { + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES('t2 A', 't2 B'); + } db2 +} {} + +do_test notify3-1.3 { + execsql { + BEGIN EXCLUSIVE; + INSERT INTO t2 VALUES('t2 C', 't2 D'); + } db2 +} {} +do_test notify3-1.4 { + catchsql { ATTACH 'test.db2' AS aux } +} {0 {}} + +do_test notify3-1.5 { + catchsql { SELECT * FROM t2 } +} {1 {database schema is locked: aux}} + +do_test notify3-1.6 { + list [sqlite3_errcode db] [sqlite3_extended_errcode db] +} {SQLITE_LOCKED SQLITE_LOCKED_SHAREDCACHE} + +do_test notify3-1.7 { + sqlite3_extended_result_codes db 1 + catch { set ::stmt [sqlite3_prepare_v2 db "SELECT * FROM t2" -1 tail] } msg + set msg +} {(262) database schema is locked: aux} + +do_test notify3-1.8 { + set ::when 1 + db unlock_notify { set ::res $::when } + set ::when 2 + execsql { COMMIT } db2 + set ::res +} {2} +do_test notify3-1.9 { + catchsql { SELECT * FROM t2 } +} {0 {{t2 A} {t2 B} {t2 C} {t2 D}}} +db close + + +set err {{1 {unable to open database: test.db2}}} +set noerr {{0 {}}} + +# When a new database is attached, the connection doing the attaching +# tries to load any unloaded schemas for both the new database and any +# already attached databases (including the main database). If it is +# unable to load any such schemas, then the ATTACH statement fails. +# +# This block tests that if the loading of schemas as a result of an +# ATTACH fails due to locks on the schema table held by other shared-cache +# connections the extended error code is SQLITE_LOCKED_SHAREDCACHE and +# it is possible to use the unlock-notify mechanism to determine when +# the ATTACH might succeed. +# +# This test does not work for test-permutations that specify SQL to +# be executed as part of the [sqlite3] command that opens the database. +# Executing such SQL causes SQLite to load the database schema into memory +# earlier than expected, causing test cases to fail. +# +if {[presql] == ""} { + foreach { + tn + db1_loaded + db2_loaded + enable_extended_errors + result + error1 error2 + } " + 0 0 0 0 $err SQLITE_LOCKED SQLITE_LOCKED_SHAREDCACHE + 1 0 0 1 $err SQLITE_LOCKED_SHAREDCACHE SQLITE_LOCKED_SHAREDCACHE + 2 0 1 0 $err SQLITE_LOCKED SQLITE_LOCKED_SHAREDCACHE + 3 0 1 1 $err SQLITE_LOCKED_SHAREDCACHE SQLITE_LOCKED_SHAREDCACHE + 4 1 0 0 $err SQLITE_LOCKED SQLITE_LOCKED_SHAREDCACHE + 5 1 0 1 $err SQLITE_LOCKED_SHAREDCACHE SQLITE_LOCKED_SHAREDCACHE + 6 1 1 0 $noerr SQLITE_OK SQLITE_OK + 7 1 1 1 $noerr SQLITE_OK SQLITE_OK + " { + + do_test notify3-2.$tn.1 { + catch { db1 close } + catch { db2 close } + sqlite3 db1 test.db + sqlite3 db2 test.db2 + + sqlite3_extended_result_codes db1 $enable_extended_errors + sqlite3_extended_result_codes db2 $enable_extended_errors + + if { $db1_loaded } { db1 eval "SELECT * FROM sqlite_master" } + if { $db2_loaded } { db2 eval "SELECT * FROM sqlite_master" } + + db2 eval "BEGIN EXCLUSIVE" + catchsql "ATTACH 'test.db2' AS two" db1 + } $result + + do_test notify3-2.$tn.2 { + list [sqlite3_errcode db1] [sqlite3_extended_errcode db1] + } [list $error1 $error2] + + do_test notify3-2.$tn.3 { + db1 unlock_notify {set invoked 1} + set invoked 0 + db2 eval commit + set invoked + } [lindex $result 0] + } +} +catch { db1 close } +catch { db2 close } + + +sqlite3_enable_shared_cache $esc +finish_test diff --git a/components/external/SQLite-3.8.1/test/notnull.test b/components/external/SQLite-3.8.1/test/notnull.test new file mode 100644 index 0000000000000000000000000000000000000000..01738a4551cb5bd226d05dff17dd73c798a2c65a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/notnull.test @@ -0,0 +1,564 @@ +# 2002 January 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the NOT NULL constraint. +# +# $Id: notnull.test,v 1.4 2006/01/17 09:35:02 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !conflict { + finish_test + return +} + +do_test notnull-1.0 { + execsql { + CREATE TABLE t1 ( + a NOT NULL, + b NOT NULL DEFAULT 5, + c NOT NULL ON CONFLICT REPLACE DEFAULT 6, + d NOT NULL ON CONFLICT IGNORE DEFAULT 7, + e NOT NULL ON CONFLICT ABORT DEFAULT 8 + ); + SELECT * FROM t1; + } +} {} +do_test notnull-1.1 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 2 3 4 5}} +do_test notnull-1.2 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(b,c,d,e) VALUES(2,3,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-1.2b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-1.3 { + catchsql { + DELETE FROM t1; + INSERT OR IGNORE INTO t1(b,c,d,e) VALUES(2,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {}} +do_test notnull-1.4 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(b,c,d,e) VALUES(2,3,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-1.4b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-1.5 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(b,c,d,e) VALUES(2,3,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-1.5b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-1.6 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,c,d,e) VALUES(1,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-1.7 { + catchsql { + DELETE FROM t1; + INSERT OR IGNORE INTO t1(a,c,d,e) VALUES(1,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-1.8 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(a,c,d,e) VALUES(1,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-1.9 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(a,c,d,e) VALUES(1,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-1.10 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.b may not be NULL}} +verify_ex_errcode notnull-1.10b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-1.11 { + catchsql { + DELETE FROM t1; + INSERT OR IGNORE INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {}} +do_test notnull-1.12 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-1.13 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 2 6 4 5}} +do_test notnull-1.14 { + catchsql { + DELETE FROM t1; + INSERT OR IGNORE INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); + SELECT * FROM t1 order by a; + } +} {0 {}} +do_test notnull-1.15 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 2 6 4 5}} +do_test notnull-1.16 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.c may not be NULL}} +verify_ex_errcode notnull-1.16b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-1.17 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,3,null,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.d may not be NULL}} +verify_ex_errcode notnull-1.17b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-1.18 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(a,b,c,e) VALUES(1,2,3,5); + SELECT * FROM t1 order by a; + } +} {0 {1 2 3 7 5}} +do_test notnull-1.19 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d) VALUES(1,2,3,4); + SELECT * FROM t1 order by a; + } +} {0 {1 2 3 4 8}} +do_test notnull-1.20 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,null); + SELECT * FROM t1 order by a; + } +} {1 {t1.e may not be NULL}} +verify_ex_errcode notnull-1.20b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-1.21 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(e,d,c,b,a) VALUES(1,2,3,null,5); + SELECT * FROM t1 order by a; + } +} {0 {5 5 3 2 1}} + +do_test notnull-2.1 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET a=null; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-2.1b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-2.2 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR REPLACE t1 SET a=null; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-2.2b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-2.3 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR IGNORE t1 SET a=null; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 2 3 4 5}} +do_test notnull-2.4 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR ABORT t1 SET a=null; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-2.4b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-2.5 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET b=null; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.b may not be NULL}} +verify_ex_errcode notnull-2.6b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-2.6 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR REPLACE t1 SET b=null, d=e, e=d; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 5 3 5 4}} +do_test notnull-2.7 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR IGNORE t1 SET b=null, d=e, e=d; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 2 3 4 5}} +do_test notnull-2.8 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET c=null, d=e, e=d; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 2 6 5 4}} +do_test notnull-2.9 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET d=null, a=b, b=a; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 2 3 4 5}} +do_test notnull-2.10 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET e=null, a=b, b=a; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.e may not be NULL}} +verify_ex_errcode notnull-2.10b SQLITE_CONSTRAINT_NOTNULL + +do_test notnull-3.0 { + execsql { + CREATE INDEX t1a ON t1(a); + CREATE INDEX t1b ON t1(b); + CREATE INDEX t1c ON t1(c); + CREATE INDEX t1d ON t1(d); + CREATE INDEX t1e ON t1(e); + CREATE INDEX t1abc ON t1(a,b,c); + } +} {} +do_test notnull-3.1 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 2 3 4 5}} +do_test notnull-3.2 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(b,c,d,e) VALUES(2,3,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-3.2b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-3.3 { + catchsql { + DELETE FROM t1; + INSERT OR IGNORE INTO t1(b,c,d,e) VALUES(2,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {}} +do_test notnull-3.4 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(b,c,d,e) VALUES(2,3,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-3.4b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-3.5 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(b,c,d,e) VALUES(2,3,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-3.5b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-3.6 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,c,d,e) VALUES(1,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-3.7 { + catchsql { + DELETE FROM t1; + INSERT OR IGNORE INTO t1(a,c,d,e) VALUES(1,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-3.8 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(a,c,d,e) VALUES(1,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-3.9 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(a,c,d,e) VALUES(1,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-3.10 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.b may not be NULL}} +verify_ex_errcode notnull-3.10b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-3.11 { + catchsql { + DELETE FROM t1; + INSERT OR IGNORE INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {}} +do_test notnull-3.12 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(a,b,c,d,e) VALUES(1,null,3,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 5 3 4 5}} +do_test notnull-3.13 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 2 6 4 5}} +do_test notnull-3.14 { + catchsql { + DELETE FROM t1; + INSERT OR IGNORE INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); + SELECT * FROM t1 order by a; + } +} {0 {}} +do_test notnull-3.15 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); + SELECT * FROM t1 order by a; + } +} {0 {1 2 6 4 5}} +do_test notnull-3.16 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,null,4,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.c may not be NULL}} +verify_ex_errcode notnull-3.16b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-3.17 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(a,b,c,d,e) VALUES(1,2,3,null,5); + SELECT * FROM t1 order by a; + } +} {1 {t1.d may not be NULL}} +verify_ex_errcode notnull-3.17b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-3.18 { + catchsql { + DELETE FROM t1; + INSERT OR ABORT INTO t1(a,b,c,e) VALUES(1,2,3,5); + SELECT * FROM t1 order by a; + } +} {0 {1 2 3 7 5}} +do_test notnull-3.19 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d) VALUES(1,2,3,4); + SELECT * FROM t1 order by a; + } +} {0 {1 2 3 4 8}} +do_test notnull-3.20 { + catchsql { + DELETE FROM t1; + INSERT INTO t1(a,b,c,d,e) VALUES(1,2,3,4,null); + SELECT * FROM t1 order by a; + } +} {1 {t1.e may not be NULL}} +verify_ex_errcode notnull-3.20b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-3.21 { + catchsql { + DELETE FROM t1; + INSERT OR REPLACE INTO t1(e,d,c,b,a) VALUES(1,2,3,null,5); + SELECT * FROM t1 order by a; + } +} {0 {5 5 3 2 1}} + +do_test notnull-4.1 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET a=null; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-4.1b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-4.2 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR REPLACE t1 SET a=null; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-4.2b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-4.3 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR IGNORE t1 SET a=null; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 2 3 4 5}} +do_test notnull-4.4 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR ABORT t1 SET a=null; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.a may not be NULL}} +verify_ex_errcode notnull-4.4b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-4.5 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET b=null; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.b may not be NULL}} +verify_ex_errcode notnull-4.5b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-4.6 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR REPLACE t1 SET b=null, d=e, e=d; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 5 3 5 4}} +do_test notnull-4.7 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE OR IGNORE t1 SET b=null, d=e, e=d; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 2 3 4 5}} +do_test notnull-4.8 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET c=null, d=e, e=d; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 2 6 5 4}} +do_test notnull-4.9 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET d=null, a=b, b=a; + SELECT * FROM t1 ORDER BY a; + } +} {0 {1 2 3 4 5}} +do_test notnull-4.10 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 VALUES(1,2,3,4,5); + UPDATE t1 SET e=null, a=b, b=a; + SELECT * FROM t1 ORDER BY a; + } +} {1 {t1.e may not be NULL}} +verify_ex_errcode notnull-4.10b SQLITE_CONSTRAINT_NOTNULL + +# Test that bug 29ab7be99f is fixed. +# +do_test notnull-5.1 { + execsql { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(a, b NOT NULL); + CREATE TABLE t2(c, d); + INSERT INTO t2 VALUES(3, 4); + INSERT INTO t2 VALUES(5, NULL); + } +} {} +do_test notnull-5.2 { + catchsql { + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 SELECT * FROM t2; + } +} {1 {t1.b may not be NULL}} +verify_ex_errcode notnull-5.2b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-5.3 { + execsql { SELECT * FROM t1 } +} {1 2} +do_test notnull-5.4 { + catchsql { + DELETE FROM t1; + BEGIN; + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 SELECT * FROM t2; + COMMIT; + } +} {1 {t1.b may not be NULL}} +verify_ex_errcode notnull-5.4b SQLITE_CONSTRAINT_NOTNULL +do_test notnull-5.5 { + execsql { SELECT * FROM t1 } +} {1 2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/null.test b/components/external/SQLite-3.8.1/test/null.test new file mode 100644 index 0000000000000000000000000000000000000000..f3782a7531bc0d09c00cba36c9bcb26a1bc1176f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/null.test @@ -0,0 +1,283 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for proper treatment of the special +# value NULL. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table and some data to work with. +# +do_test null-1.0 { + execsql { + begin; + create table t1(a,b,c); + insert into t1 values(1,0,0); + insert into t1 values(2,0,1); + insert into t1 values(3,1,0); + insert into t1 values(4,1,1); + insert into t1 values(5,null,0); + insert into t1 values(6,null,1); + insert into t1 values(7,null,null); + commit; + select * from t1; + } +} {1 0 0 2 0 1 3 1 0 4 1 1 5 {} 0 6 {} 1 7 {} {}} + +# Check for how arithmetic expressions handle NULL +# +do_test null-1.1 { + execsql { + select ifnull(a+b,99) from t1; + } +} {1 2 4 5 99 99 99} +do_test null-1.2 { + execsql { + select ifnull(b*c,99) from t1; + } +} {0 0 0 1 99 99 99} + +# Check to see how the CASE expression handles NULL values. The +# first WHEN for which the test expression is TRUE is selected. +# FALSE and UNKNOWN test expressions are skipped. +# +do_test null-2.1 { + execsql { + select ifnull(case when b<>0 then 1 else 0 end, 99) from t1; + } +} {0 0 1 1 0 0 0} +do_test null-2.2 { + execsql { + select ifnull(case when not b<>0 then 1 else 0 end, 99) from t1; + } +} {1 1 0 0 0 0 0} +do_test null-2.3 { + execsql { + select ifnull(case when b<>0 and c<>0 then 1 else 0 end, 99) from t1; + } +} {0 0 0 1 0 0 0} +do_test null-2.4 { + execsql { + select ifnull(case when not (b<>0 and c<>0) then 1 else 0 end, 99) from t1; + } +} {1 1 1 0 1 0 0} +do_test null-2.5 { + execsql { + select ifnull(case when b<>0 or c<>0 then 1 else 0 end, 99) from t1; + } +} {0 1 1 1 0 1 0} +do_test null-2.6 { + execsql { + select ifnull(case when not (b<>0 or c<>0) then 1 else 0 end, 99) from t1; + } +} {1 0 0 0 0 0 0} +do_test null-2.7 { + execsql { + select ifnull(case b when c then 1 else 0 end, 99) from t1; + } +} {1 0 0 1 0 0 0} +do_test null-2.8 { + execsql { + select ifnull(case c when b then 1 else 0 end, 99) from t1; + } +} {1 0 0 1 0 0 0} + +# Check to see that NULL values are ignored in aggregate functions. +# +do_test null-3.1 { + execsql { + select count(*), count(b), count(c), sum(b), sum(c), + avg(b), avg(c), min(b), max(b) from t1; + } +} {7 4 6 2 3 0.5 0.5 0 1} + +# The sum of zero entries is a NULL, but the total of zero entries is 0. +# +do_test null-3.2 { + execsql { + SELECT sum(b), total(b) FROM t1 WHERE b<0 + } +} {{} 0.0} + +# Check to see how WHERE clauses handle NULL values. A NULL value +# is the same as UNKNOWN. The WHERE clause should only select those +# rows that are TRUE. FALSE and UNKNOWN rows are rejected. +# +do_test null-4.1 { + execsql { + select a from t1 where b<10 + } +} {1 2 3 4} +do_test null-4.2 { + execsql { + select a from t1 where not b>10 + } +} {1 2 3 4} +do_test null-4.3 { + execsql { + select a from t1 where b<10 or c=1; + } +} {1 2 3 4 6} +do_test null-4.4 { + execsql { + select a from t1 where b<10 and c=1; + } +} {2 4} +do_test null-4.5 { + execsql { + select a from t1 where not (b<10 and c=1); + } +} {1 3 5} + +# The DISTINCT keyword on a SELECT statement should treat NULL values +# as distinct +# +do_test null-5.1 { + execsql { + select distinct b from t1 order by b; + } +} {{} 0 1} + +# A UNION to two queries should treat NULL values +# as distinct. +# +# (Later:) We also take this opportunity to test the ability +# of an ORDER BY clause to bind to either SELECT of a UNION. +# The left-most SELECT is preferred. In standard SQL, only +# the left SELECT can be used. The ability to match an ORDER +# BY term to the right SELECT is an SQLite extension. +# +ifcapable compound { + do_test null-6.1 { + execsql { + select b from t1 union select c from t1 order by b; + } + } {{} 0 1} + do_test null-6.2 { + execsql { + select b from t1 union select c from t1 order by 1; + } + } {{} 0 1} + do_test null-6.3 { + execsql { + select b from t1 union select c from t1 order by t1.b; + } + } {{} 0 1} + do_test null-6.4 { + execsql { + select b from t1 union select c from t1 order by main.t1.b; + } + } {{} 0 1} + do_test null-6.5 { + catchsql { + select b from t1 union select c from t1 order by t1.a; + } + } {1 {1st ORDER BY term does not match any column in the result set}} + do_test null-6.6 { + catchsql { + select b from t1 union select c from t1 order by main.t1.a; + } + } {1 {1st ORDER BY term does not match any column in the result set}} +} ;# ifcapable compound + +# The UNIQUE constraint only applies to non-null values +# +ifcapable conflict { +do_test null-7.1 { + execsql { + create table t2(a, b unique on conflict ignore); + insert into t2 values(1,1); + insert into t2 values(2,null); + insert into t2 values(3,null); + insert into t2 values(4,1); + select a from t2; + } + } {1 2 3} + do_test null-7.2 { + execsql { + create table t3(a, b, c, unique(b,c) on conflict ignore); + insert into t3 values(1,1,1); + insert into t3 values(2,null,1); + insert into t3 values(3,null,1); + insert into t3 values(4,1,1); + select a from t3; + } + } {1 2 3} +} + +# Ticket #461 - Make sure nulls are handled correctly when doing a +# lookup using an index. +# +do_test null-8.1 { + execsql { + CREATE TABLE t4(x,y); + INSERT INTO t4 VALUES(1,11); + INSERT INTO t4 VALUES(2,NULL); + SELECT x FROM t4 WHERE y=NULL; + } +} {} +ifcapable subquery { + do_test null-8.2 { + execsql { + SELECT x FROM t4 WHERE y IN (33,NULL); + } + } {} +} +do_test null-8.3 { + execsql { + SELECT x FROM t4 WHERE y<33 ORDER BY x; + } +} {1} +do_test null-8.4 { + execsql { + SELECT x FROM t4 WHERE y>6 ORDER BY x; + } +} {1} +do_test null-8.5 { + execsql { + SELECT x FROM t4 WHERE y!=33 ORDER BY x; + } +} {1} +do_test null-8.11 { + execsql { + CREATE INDEX t4i1 ON t4(y); + SELECT x FROM t4 WHERE y=NULL; + } +} {} +ifcapable subquery { + do_test null-8.12 { + execsql { + SELECT x FROM t4 WHERE y IN (33,NULL); + } + } {} +} +do_test null-8.13 { + execsql { + SELECT x FROM t4 WHERE y<33 ORDER BY x; + } +} {1} +do_test null-8.14 { + execsql { + SELECT x FROM t4 WHERE y>6 ORDER BY x; + } +} {1} +do_test null-8.15 { + execsql { + SELECT x FROM t4 WHERE y!=33 ORDER BY x; + } +} {1} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/numcast.test b/components/external/SQLite-3.8.1/test/numcast.test new file mode 100644 index 0000000000000000000000000000000000000000..926bbe4b21b3f305c396359b249815cf1e66c167 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/numcast.test @@ -0,0 +1,46 @@ +# 2013 March 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# This particular file does testing of casting strings into numeric +# values. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +foreach enc {utf8 utf16le utf16be} { + do_test numcast-$enc.0 { + db close + sqlite3 db :memory: + db eval "PRAGMA encoding='$enc'" + set x [db eval {PRAGMA encoding}] + string map {- {}} [string tolower $x] + } $enc + foreach {idx str rval ival} { + 1 12345.0 12345.0 12345 + 2 12345.0e0 12345.0 12345 + 3 -12345.0e0 -12345.0 -12345 + 4 -12345.25 -12345.25 -12345 + 5 { -12345.0} -12345.0 -12345 + 6 { 876xyz} 876.0 876 + 7 { 456Ä·89} 456.0 456 + 8 { Ä  321.5} 0.0 0 + } { + do_test numcast-$enc.$idx.1 { + db eval {SELECT CAST($str AS real)} + } $rval + do_test numcast-$enc.$idx.2 { + db eval {SELECT CAST($str AS integer)} + } $ival + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/openv2.test b/components/external/SQLite-3.8.1/test/openv2.test new file mode 100644 index 0000000000000000000000000000000000000000..2a9e22d6b0de69a313c94bd1bf0659a42af63864 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/openv2.test @@ -0,0 +1,55 @@ +# 2007 Sep 3 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests on the sqlite3_open_v2() interface. +# +# $Id: openv2.test,v 1.2 2009/06/11 17:32:45 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +db close +forcedelete test.db test.db-journal +do_test openv2-1.1 { + set rc [catch {sqlite3 db test.db -create 0} msg] + lappend rc $msg +} {1 {unable to open database file}} +do_test openv2-1.2 { + info commands db +} {} +do_test openv2-1.3 { + sqlite3 db test.db + db eval {CREATE TABLE t1(x)} + db close + sqlite3 db test.db -readonly 1 + db eval {SELECT name FROM sqlite_master} +} {t1} +do_test openv2-1.4 { + catchsql { + INSERT INTO t1 VALUES(123) + } +} {1 {attempt to write a readonly database}} + +# Ticket #3908 +# Honor SQLITE_OPEN_READONLY even on an in-memory database, even though +# this is pointless. +# +do_test openv2-2.1 { + db close + sqlite3 db :memory: -readonly 1 + db eval {SELECT * FROM sqlite_master} +} {} +do_test openv2-2.2 { + catchsql {CREATE TABLE t1(x)} +} {1 {attempt to write a readonly database}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/orderby1.test b/components/external/SQLite-3.8.1/test/orderby1.test new file mode 100644 index 0000000000000000000000000000000000000000..d4795671ddb013d4fe893eba02058e455591a422 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/orderby1.test @@ -0,0 +1,457 @@ +# 2012 Sept 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that the optimizations that disable +# ORDER BY clauses when the natural order of a query is correct. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix orderby1 + +# Generate test data for a join. Verify that the join gets the +# correct answer. +# +do_test 1.0 { + db eval { + BEGIN; + CREATE TABLE album( + aid INTEGER PRIMARY KEY, + title TEXT UNIQUE NOT NULL + ); + CREATE TABLE track( + tid INTEGER PRIMARY KEY, + aid INTEGER NOT NULL REFERENCES album, + tn INTEGER NOT NULL, + name TEXT, + UNIQUE(aid, tn) + ); + INSERT INTO album VALUES(1, '1-one'), (2, '2-two'), (3, '3-three'); + INSERT INTO track VALUES + (NULL, 1, 1, 'one-a'), + (NULL, 2, 2, 'two-b'), + (NULL, 3, 3, 'three-c'), + (NULL, 1, 3, 'one-c'), + (NULL, 2, 1, 'two-a'), + (NULL, 3, 1, 'three-a'); + COMMIT; + } +} {} +do_test 1.1a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn + } +} {one-a one-c two-a two-b three-a three-c} + +# Verify that the ORDER BY clause is optimized out +# +do_test 1.1b { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album CROSS JOIN track USING (aid) ORDER BY title, tn + } +} {~/ORDER BY/} ;# ORDER BY optimized out + +# The same query with ORDER BY clause optimization disabled via + operators +# should give exactly the same answer. +# +do_test 1.2a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title, +tn + } +} {one-a one-c two-a two-b three-a three-c} + +# The output is sorted manually in this case. +# +do_test 1.2b { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY +title, +tn + } +} {/ORDER BY/} ;# separate sorting pass due to "+" on ORDER BY terms + +# The same query with ORDER BY optimizations turned off via built-in test. +# +do_test 1.3a { + optimization_control db order-by-idx-join 0 + db cache flush + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn + } +} {one-a one-c two-a two-b three-a three-c} +do_test 1.3b { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn + } +} {/ORDER BY/} ;# separate sorting pass due to disabled optimization +optimization_control db all 1 +db cache flush + +# Reverse order sorts +# +do_test 1.4a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title DESC, tn + } +} {three-a three-c two-a two-b one-a one-c} +do_test 1.4b { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title DESC, +tn + } +} {three-a three-c two-a two-b one-a one-c} ;# verify same order after sorting +do_test 1.4c { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title DESC, tn + } +} {~/ORDER BY/} ;# ORDER BY suppressed due to uniqueness constraints + +do_test 1.5a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn DESC + } +} {one-c one-a two-b two-a three-c three-a} +do_test 1.5b { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title, +tn DESC + } +} {one-c one-a two-b two-a three-c three-a} ;# verify same order after sorting +do_test 1.5c { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn DESC + } +} {~/ORDER BY/} ;# ORDER BY suppressed due to uniqueness constraints + +do_test 1.6a { + db eval { + SELECT name FROM album CROSS JOIN track USING (aid) + ORDER BY title DESC, tn DESC + } +} {three-c three-a two-b two-a one-c one-a} +do_test 1.6b { + db eval { + SELECT name FROM album CROSS JOIN track USING (aid) + ORDER BY +title DESC, +tn DESC + } +} {three-c three-a two-b two-a one-c one-a} ;# verify same order after sorting +do_test 1.6c { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album CROSS JOIN track USING (aid) + ORDER BY title DESC, tn DESC + } +} {~/ORDER BY/} ;# ORDER BY + + +# Reconstruct the test data to use indices rather than integer primary keys. +# +do_test 2.0 { + db eval { + BEGIN; + DROP TABLE album; + DROP TABLE track; + CREATE TABLE album( + aid INT PRIMARY KEY, + title TEXT NOT NULL + ); + CREATE INDEX album_i1 ON album(title, aid); + CREATE TABLE track( + aid INTEGER NOT NULL REFERENCES album, + tn INTEGER NOT NULL, + name TEXT, + UNIQUE(aid, tn) + ); + INSERT INTO album VALUES(1, '1-one'), (20, '2-two'), (3, '3-three'); + INSERT INTO track VALUES + (1, 1, 'one-a'), + (20, 2, 'two-b'), + (3, 3, 'three-c'), + (1, 3, 'one-c'), + (20, 1, 'two-a'), + (3, 1, 'three-a'); + COMMIT; + } +} {} +do_test 2.1a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn + } +} {one-a one-c two-a two-b three-a three-c} + +# Verify that the ORDER BY clause is optimized out +# +do_test 2.1b { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn + } +} {/ORDER BY/} ;# ORDER BY required because of missing aid term in ORDER BY + +do_test 2.1c { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title, aid, tn + } +} {one-a one-c two-a two-b three-a three-c} +do_test 2.1d { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title, aid, tn + } +} {/ORDER BY/} ;# ORDER BY required in this case + +# The same query with ORDER BY clause optimization disabled via + operators +# should give exactly the same answer. +# +do_test 2.2a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title, +tn + } +} {one-a one-c two-a two-b three-a three-c} + +# The output is sorted manually in this case. +# +do_test 2.2b { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY +title, +tn + } +} {/ORDER BY/} ;# separate sorting pass due to "+" on ORDER BY terms + +# The same query with ORDER BY optimizations turned off via built-in test. +# +do_test 2.3a { + optimization_control db order-by-idx-join 0 + db cache flush + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn + } +} {one-a one-c two-a two-b three-a three-c} +do_test 2.3b { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn + } +} {/ORDER BY/} ;# separate sorting pass due to disabled optimization +optimization_control db all 1 +db cache flush + +# Reverse order sorts +# +do_test 2.4a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title DESC, tn + } +} {three-a three-c two-a two-b one-a one-c} +do_test 2.4b { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title DESC, +tn + } +} {three-a three-c two-a two-b one-a one-c} ;# verify same order after sorting +do_test 2.4c { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title DESC, tn + } +} {/ORDER BY/} ;# separate sorting pass due to mixed DESC/ASC + + +do_test 2.5a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn DESC + } +} {one-c one-a two-b two-a three-c three-a} +do_test 2.5b { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title, +tn DESC + } +} {one-c one-a two-b two-a three-c three-a} ;# verify same order after sorting +do_test 2.5c { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn DESC + } +} {/ORDER BY/} ;# separate sorting pass due to mixed ASC/DESC + +do_test 2.6a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title DESC, tn DESC + } +} {three-c three-a two-b two-a one-c one-a} +do_test 2.6b { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title DESC, +tn DESC + } +} {three-c three-a two-b two-a one-c one-a} ;# verify same order after sorting +do_test 2.6c { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title DESC, tn DESC + } +} {/ORDER BY/} ;# ORDER BY required + + +# Generate another test dataset, but this time using mixed ASC/DESC indices. +# +do_test 3.0 { + db eval { + BEGIN; + DROP TABLE album; + DROP TABLE track; + CREATE TABLE album( + aid INTEGER PRIMARY KEY, + title TEXT UNIQUE NOT NULL + ); + CREATE TABLE track( + tid INTEGER PRIMARY KEY, + aid INTEGER NOT NULL REFERENCES album, + tn INTEGER NOT NULL, + name TEXT, + UNIQUE(aid ASC, tn DESC) + ); + INSERT INTO album VALUES(1, '1-one'), (2, '2-two'), (3, '3-three'); + INSERT INTO track VALUES + (NULL, 1, 1, 'one-a'), + (NULL, 2, 2, 'two-b'), + (NULL, 3, 3, 'three-c'), + (NULL, 1, 3, 'one-c'), + (NULL, 2, 1, 'two-a'), + (NULL, 3, 1, 'three-a'); + COMMIT; + } +} {} +do_test 3.1a { + db eval { + SELECT name FROM album CROSS JOIN track USING (aid) ORDER BY title, tn DESC + } +} {one-c one-a two-b two-a three-c three-a} + +# Verify that the ORDER BY clause is optimized out +# +do_test 3.1b { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album CROSS JOIN track USING (aid) ORDER BY title, tn DESC + } +} {~/ORDER BY/} ;# ORDER BY optimized out + +# The same query with ORDER BY clause optimization disabled via + operators +# should give exactly the same answer. +# +do_test 3.2a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title, +tn DESC + } +} {one-c one-a two-b two-a three-c three-a} + +# The output is sorted manually in this case. +# +do_test 3.2b { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY +title, +tn DESC + } +} {/ORDER BY/} ;# separate sorting pass due to "+" on ORDER BY terms + +# The same query with ORDER BY optimizations turned off via built-in test. +# +do_test 3.3a { + optimization_control db order-by-idx-join 0 + db cache flush + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn DESC + } +} {one-c one-a two-b two-a three-c three-a} +do_test 3.3b { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn DESC + } +} {/ORDER BY/} ;# separate sorting pass due to disabled optimization +optimization_control db all 1 +db cache flush + +# Without the mixed ASC/DESC on ORDER BY +# +do_test 3.4a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn + } +} {one-a one-c two-a two-b three-a three-c} +do_test 3.4b { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title, +tn + } +} {one-a one-c two-a two-b three-a three-c} ;# verify same order after sorting +do_test 3.4c { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title, tn + } +} {~/ORDER BY/} ;# ORDER BY suppressed by uniqueness constraints + +do_test 3.5a { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY title DESC, tn DESC + } +} {three-c three-a two-b two-a one-c one-a} +do_test 3.5b { + db eval { + SELECT name FROM album JOIN track USING (aid) ORDER BY +title DESC, +tn DESC + } +} {three-c three-a two-b two-a one-c one-a} ;# verify same order after sorting +do_test 3.5c { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album JOIN track USING (aid) ORDER BY title DESC, tn DESC + } +} {~/ORDER BY/} ;# ORDER BY suppressed by uniqueness constraints + + +do_test 3.6a { + db eval { + SELECT name FROM album CROSS JOIN track USING (aid) ORDER BY title DESC, tn + } +} {three-a three-c two-a two-b one-a one-c} +do_test 3.6b { + db eval { + SELECT name FROM album CROSS JOIN track USING (aid) + ORDER BY +title DESC, +tn + } +} {three-a three-c two-a two-b one-a one-c} ;# verify same order after sorting +do_test 3.6c { + db eval { + EXPLAIN QUERY PLAN + SELECT name FROM album CROSS JOIN track USING (aid) ORDER BY title DESC, tn + } +} {~/ORDER BY/} ;# inverted ASC/DESC is optimized out + +# Ticket 5ed1772895bf3deeab78c5e3519b1da9165c541b (2013-06-04) +# Incorrect ORDER BY on an indexed JOIN +# +do_test 4.0 { + db eval { + CREATE TABLE t41(a INT UNIQUE NOT NULL, b INT NOT NULL); + CREATE INDEX t41ba ON t41(b,a); + CREATE TABLE t42(x INT NOT NULL REFERENCES t41(a), y INT NOT NULL); + CREATE UNIQUE INDEX t42xy ON t42(x,y); + INSERT INTO t41 VALUES(1,1),(3,1); + INSERT INTO t42 VALUES(1,13),(1,15),(3,14),(3,16); + + SELECT b, y FROM t41 CROSS JOIN t42 ON x=a ORDER BY b, y; + } +} {1 13 1 14 1 15 1 16} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/orderby2.test b/components/external/SQLite-3.8.1/test/orderby2.test new file mode 100644 index 0000000000000000000000000000000000000000..cfd647715244a8e252ebb51e2a627e9646c999f5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/orderby2.test @@ -0,0 +1,117 @@ +# 2012 Sept 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that the optimizations that disable +# ORDER BY clauses when the natural order of a query is correct. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix orderby2 + +# Generate test data for a join. Verify that the join gets the +# correct answer. +# +do_test 1.0 { + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(1,11), (2,22); + CREATE TABLE t2(d, e, UNIQUE(d,e)); + INSERT INTO t2 VALUES(10, 'ten'), (11,'eleven'), (12,'twelve'), + (11, 'oneteen'); + } +} {} + +do_test 1.1a { + db eval { + SELECT e FROM t1, t2 WHERE a=1 AND d=b ORDER BY d, e; + } +} {eleven oneteen} +do_test 1.1b { + db eval { + EXPLAIN QUERY PLAN + SELECT e FROM t1, t2 WHERE a=1 AND d=b ORDER BY d, e; + } +} {~/ORDER BY/} + +do_test 1.2a { + db eval { + SELECT e FROM t1, t2 WHERE a=1 AND d=b ORDER BY e; + } +} {eleven oneteen} +do_test 1.2b { + db eval { + EXPLAIN QUERY PLAN + SELECT e FROM t1, t2 WHERE a=1 AND d=b ORDER BY e; + } +} {~/ORDER BY/} + +do_test 1.3a { + db eval { + SELECT e, b FROM t1, t2 WHERE a=1 ORDER BY d, e; + } +} {ten 11 eleven 11 oneteen 11 twelve 11} +do_test 1.3b { + db eval { + EXPLAIN QUERY PLAN + SELECT e, b FROM t1, t2 WHERE a=1 ORDER BY d, e; + } +} {~/ORDER BY/} + +# The following tests derived from TH3 test module cov1/where34.test +# +do_test 2.0 { + db eval { + CREATE TABLE t31(a,b); CREATE INDEX t31ab ON t31(a,b); + CREATE TABLE t32(c,d); CREATE INDEX t32cd ON t32(c,d); + CREATE TABLE t33(e,f); CREATE INDEX t33ef ON t33(e,f); + CREATE TABLE t34(g,h); CREATE INDEX t34gh ON t34(g,h); + + INSERT INTO t31 VALUES(1,4), (2,3), (1,3); + INSERT INTO t32 VALUES(4,5), (3,6), (3,7), (4,8); + INSERT INTO t33 VALUES(5,9), (7,10), (6,11), (8,12), (8,13), (7,14); + INSERT INTO t34 VALUES(11,20), (10,21), (12,22), (9,23), (13,24), + (14,25), (12,26); + SELECT a||','||c||','||e||','||g FROM t31, t32, t33, t34 + WHERE c=b AND e=d AND g=f + ORDER BY a ASC, c ASC, e DESC, g ASC; + } +} {1,3,7,10 1,3,7,14 1,3,6,11 1,4,8,12 1,4,8,12 1,4,8,13 1,4,5,9 2,3,7,10 2,3,7,14 2,3,6,11} +do_test 2.1 { + db eval { + SELECT a||','||c||','||e||','||g FROM t31, t32, t33, t34 + WHERE c=b AND e=d AND g=f + ORDER BY +a ASC, +c ASC, +e DESC, +g ASC; + } +} {1,3,7,10 1,3,7,14 1,3,6,11 1,4,8,12 1,4,8,12 1,4,8,13 1,4,5,9 2,3,7,10 2,3,7,14 2,3,6,11} +do_test 2.2 { + db eval { + SELECT a||','||c||','||e||','||g FROM t31, t32, t33, t34 + WHERE c=b AND e=d AND g=f + ORDER BY a ASC, c ASC, e ASC, g ASC; + } +} {1,3,6,11 1,3,7,10 1,3,7,14 1,4,5,9 1,4,8,12 1,4,8,12 1,4,8,13 2,3,6,11 2,3,7,10 2,3,7,14} +do_test 2.3 { + optimization_control db cover-idx-scan off + db cache flush + db eval { + SELECT a||','||c||','||e||','||g FROM t31, t32, t33, t34 + WHERE c=b AND e=d AND g=f + ORDER BY a ASC, c ASC, e ASC, g ASC; + } +} {1,3,6,11 1,3,7,10 1,3,7,14 1,4,5,9 1,4,8,12 1,4,8,12 1,4,8,13 2,3,6,11 2,3,7,10 2,3,7,14} +optimization_control db all on +db cache flush + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/orderby3.test b/components/external/SQLite-3.8.1/test/orderby3.test new file mode 100644 index 0000000000000000000000000000000000000000..f005f0d2e8b76ec9c141c5cc9c40994587f1c737 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/orderby3.test @@ -0,0 +1,123 @@ +# 2013 January 09 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that the optimizations that disable +# ORDER BY clauses work correctly on a 3-way join. See ticket +# http://www.sqlite.org/src/956e4d7f89 +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix orderby3 + +# Generate test data for a join. Verify that the join gets the +# correct answer. +# +do_execsql_test 1.0 { + CREATE TABLE t1(a INTEGER PRIMARY KEY); + CREATE TABLE t2(b INTEGER PRIMARY KEY, c INTEGER); + CREATE TABLE t3(d INTEGER); + + INSERT INTO t1 VALUES(1),(2),(3); + + INSERT INTO t2 VALUES(3, 1); + INSERT INTO t2 VALUES(4, 2); + INSERT INTO t2 VALUES(5, 3); + + INSERT INTO t3 VALUES(4),(3),(5); +} {} +do_execsql_test 1.1.asc { + SELECT t1.a + FROM t1, t2, t3 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a; +} {1 2 3} +do_execsql_test 1.1.desc { + SELECT t1.a + FROM t1, t2, t3 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a DESC; +} {3 2 1} +do_execsql_test 1.123.asc { + SELECT t1.a + FROM t1 CROSS JOIN t2 CROSS JOIN t3 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a; +} {1 2 3} +do_execsql_test 1.123.desc { + SELECT t1.a + FROM t1 CROSS JOIN t2 CROSS JOIN t3 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a DESC; +} {3 2 1} +do_execsql_test 1.132.asc { + SELECT t1.a + FROM t1 CROSS JOIN t3 CROSS JOIN t2 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a; +} {1 2 3} +do_execsql_test 1.132.desc { + SELECT t1.a + FROM t1 CROSS JOIN t3 CROSS JOIN t2 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a DESC; +} {3 2 1} +do_execsql_test 1.213.asc { + SELECT t1.a + FROM t2 CROSS JOIN t1 CROSS JOIN t3 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a; +} {1 2 3} +do_execsql_test 1.213.desc { + SELECT t1.a + FROM t2 CROSS JOIN t1 CROSS JOIN t3 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a DESC; +} {3 2 1} +do_execsql_test 1.231.asc { + SELECT t1.a + FROM t2 CROSS JOIN t3 CROSS JOIN t1 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a; +} {1 2 3} +do_execsql_test 1.231.desc { + SELECT t1.a + FROM t2 CROSS JOIN t3 CROSS JOIN t1 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a DESC; +} {3 2 1} +do_execsql_test 1.312.asc { + SELECT t1.a + FROM t3 CROSS JOIN t1 CROSS JOIN t2 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a; +} {1 2 3} +do_execsql_test 1.312.desc { + SELECT t1.a + FROM t3 CROSS JOIN t1 CROSS JOIN t2 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a DESC; +} {3 2 1} +do_execsql_test 1.321.asc { + SELECT t1.a + FROM t3 CROSS JOIN t2 CROSS JOIN t1 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a; +} {1 2 3} +do_execsql_test 1.321.desc { + SELECT t1.a + FROM t3 CROSS JOIN t2 CROSS JOIN t1 + WHERE t1.a=t2.c AND t2.b=t3.d + ORDER BY t1.a DESC; +} {3 2 1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/orderby4.test b/components/external/SQLite-3.8.1/test/orderby4.test new file mode 100644 index 0000000000000000000000000000000000000000..ec6eb041f63042ed966d2373f5916d4bea9c8a4e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/orderby4.test @@ -0,0 +1,56 @@ +# 2013 March 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that the optimizations that disable +# ORDER BY clauses work correctly on multi-value primary keys and +# unique indices when only some prefix of the terms in the key are +# used. See ticket http://www.sqlite.org/src/info/a179fe74659 +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix orderby4 + +# Generate test data for a join. Verify that the join gets the +# correct answer. +# +do_execsql_test 1.1 { + CREATE TABLE t1(a, b, PRIMARY KEY(a,b)); + INSERT INTO t1 VALUES(1,1),(1,2); + CREATE TABLE t2(x, y, PRIMARY KEY(x,y)); + INSERT INTO t2 VALUES(3,3),(4,4); + SELECT a, x FROM t1, t2 ORDER BY 1, 2; +} {1 3 1 3 1 4 1 4} +do_execsql_test 1.2 { + SELECT a, x FROM t1 CROSS JOIN t2 ORDER BY 1, 2; +} {1 3 1 3 1 4 1 4} +do_execsql_test 1.3 { + SELECT a, x FROM t2 CROSS JOIN t1 ORDER BY 1, 2; +} {1 3 1 3 1 4 1 4} + +do_execsql_test 2.1 { + CREATE TABLE t3(a); + INSERT INTO t3 VALUES(1),(1); + CREATE INDEX t3a ON t3(a); + CREATE TABLE t4(x); + INSERT INTO t4 VALUES(3),(4); + CREATE INDEX t4x ON t4(x); + SELECT a, x FROM t3, t4 ORDER BY 1, 2; +} {1 3 1 3 1 4 1 4} +do_execsql_test 2.2 { + SELECT a, x FROM t3 CROSS JOIN t4 ORDER BY 1, 2; +} {1 3 1 3 1 4 1 4} +do_execsql_test 2.3 { + SELECT a, x FROM t4 CROSS JOIN t3 ORDER BY 1, 2; +} {1 3 1 3 1 4 1 4} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/orderby5.test b/components/external/SQLite-3.8.1/test/orderby5.test new file mode 100644 index 0000000000000000000000000000000000000000..5bae5db7175a8bfb1f8ad608b7a34a7408d95915 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/orderby5.test @@ -0,0 +1,97 @@ +# 2013-06-14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that the optimizations that disable +# ORDER BY clauses work correctly +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix orderby5 + +# Generate test data for a join. Verify that the join gets the +# correct answer. +# +do_execsql_test 1.1 { + CREATE TABLE t1(a,b,c); + CREATE INDEX t1bc ON t1(b,c); + + EXPLAIN QUERY PLAN + SELECT DISTINCT a, b, c FROM t1 WHERE a=0; +} {~/B-TREE/} +do_execsql_test 1.2.1 { + EXPLAIN QUERY PLAN + SELECT DISTINCT a, c, b FROM t1 WHERE a=0; +} {~/B-TREE/} +do_execsql_test 1.2.2 { + EXPLAIN QUERY PLAN + SELECT DISTINCT a, c, b FROM t1 WHERE a='xyz' COLLATE nocase; +} {/B-TREE/} +do_execsql_test 1.2.3 { + EXPLAIN QUERY PLAN + SELECT DISTINCT a COLLATE nocase, c, b FROM t1 WHERE a='xyz'; +} {/B-TREE/} +do_execsql_test 1.2.4 { + EXPLAIN QUERY PLAN + SELECT DISTINCT a COLLATE nocase, c, b FROM t1 WHERE a='xyz' COLLATE nocase; +} {~/B-TREE/} +do_execsql_test 1.3 { + EXPLAIN QUERY PLAN + SELECT DISTINCT b, a, c FROM t1 WHERE a=0; +} {~/B-TREE/} +do_execsql_test 1.4 { + EXPLAIN QUERY PLAN + SELECT DISTINCT b, c, a FROM t1 WHERE a=0; +} {~/B-TREE/} +do_execsql_test 1.5 { + EXPLAIN QUERY PLAN + SELECT DISTINCT c, a, b FROM t1 WHERE a=0; +} {~/B-TREE/} +do_execsql_test 1.6 { + EXPLAIN QUERY PLAN + SELECT DISTINCT c, b, a FROM t1 WHERE a=0; +} {~/B-TREE/} +do_execsql_test 1.7 { + EXPLAIN QUERY PLAN + SELECT DISTINCT c, b, a FROM t1 WHERE +a=0; +} {/B-TREE/} +do_execsql_test 2.1 { + EXPLAIN QUERY PLAN + SELECT * FROM t1 WHERE a=0 ORDER BY a, b, c; +} {~/B-TREE/} +do_execsql_test 2.2 { + EXPLAIN QUERY PLAN + SELECT * FROM t1 WHERE +a=0 ORDER BY a, b, c; +} {/B-TREE/} +do_execsql_test 2.3 { + EXPLAIN QUERY PLAN + SELECT * FROM t1 WHERE a=0 ORDER BY b, a, c; +} {~/B-TREE/} +do_execsql_test 2.4 { + EXPLAIN QUERY PLAN + SELECT * FROM t1 WHERE a=0 ORDER BY b, c, a; +} {~/B-TREE/} +do_execsql_test 2.5 { + EXPLAIN QUERY PLAN + SELECT * FROM t1 WHERE a=0 ORDER BY a, c, b; +} {/B-TREE/} +do_execsql_test 2.6 { + EXPLAIN QUERY PLAN + SELECT * FROM t1 WHERE a=0 ORDER BY c, a, b; +} {/B-TREE/} +do_execsql_test 2.7 { + EXPLAIN QUERY PLAN + SELECT * FROM t1 WHERE a=0 ORDER BY c, b, a; +} {/B-TREE/} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/oserror.test b/components/external/SQLite-3.8.1/test/oserror.test new file mode 100644 index 0000000000000000000000000000000000000000..40d2966bcca57409fdb25aeb58375261c9a4d6d3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/oserror.test @@ -0,0 +1,125 @@ +# 2011 February 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that error messages are logged via the +# sqlite3_log() mechanism when certain errors are encountered in the +# default unix or windows VFS modules. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +if {$::tcl_platform(platform)!="unix"} { finish_test ; return } +set ::testprefix oserror + +db close +sqlite3_shutdown +test_sqlite3_log xLog +proc xLog {error_code msg} { + if {[string match os_* $msg]} { + lappend ::log $msg + } +} + +proc do_re_test {tn script expression} { + uplevel do_test $tn [list [subst -nocommands { + set res [eval { $script }] + if {[regexp {$expression} [set res]]} { + set {} {$expression} + } else { + set res + } + }]] [list $expression] + +} + +#-------------------------------------------------------------------------- +# Tests oserror-1.* test failures in the open() system call. +# + +# Test a failure in open() due to too many files. +# +# The xOpen() method of the unix VFS calls getcwd() as well as open(). +# Although this does not appear to be documented in the man page, on OSX +# a call to getcwd() may fail if there are no free file descriptors. So +# an error may be reported for either open() or getcwd() here. +# +puts "Possible valgrind error about invalid file descriptor follows:" +do_test 1.1.1 { + set ::log [list] + list [catch { + for {set i 0} {$i < 2000} {incr i} { sqlite3 dbh_$i test.db -readonly 1 } + } msg] $msg +} {1 {unable to open database file}} +do_test 1.1.2 { + catch { for {set i 0} {$i < 2000} {incr i} { dbh_$i close } } +} {1} +do_re_test 1.1.3 { + lindex $::log 0 +} {^os_unix.c:\d+: \(\d+\) (open|getcwd)\(.*test.db\) - } + + +# Test a failure in open() due to the path being a directory. +# +do_test 1.2.1 { + file mkdir dir.db + set ::log [list] + list [catch { sqlite3 dbh dir.db } msg] $msg +} {1 {unable to open database file}} + +do_re_test 1.2.2 { lindex $::log 0 } {^os_unix.c:\d+: \(\d+\) open\(.*dir.db\) - } + +# Test a failure in open() due to the path not existing. +# +do_test 1.3.1 { + set ::log [list] + list [catch { sqlite3 dbh /x/y/z/test.db } msg] $msg +} {1 {unable to open database file}} + +do_re_test 1.3.2 { lindex $::log 0 } {^os_unix.c:\d+: \(\d+\) open\(.*test.db\) - } + +# Test a failure in open() due to the path not existing. +# +do_test 1.4.1 { + set ::log [list] + list [catch { sqlite3 dbh /root/test.db } msg] $msg +} {1 {unable to open database file}} + +do_re_test 1.4.2 { lindex $::log 0 } {^os_unix.c:\d*: \(\d+\) open\(.*test.db\) - } + +#-------------------------------------------------------------------------- +# Tests oserror-1.* test failures in the unlink() system call. +# +ifcapable wal { + do_test 2.1.1 { + set ::log [list] + file mkdir test.db-wal + forcedelete test.db + list [catch { + sqlite3 dbh test.db + execsql { SELECT * FROM sqlite_master } dbh + } msg] $msg + } {1 {disk I/O error}} + + do_re_test 2.1.2 { + lindex $::log 0 + } {^os_unix.c:\d+: \(\d+\) unlink\(.*test.db-wal\) - } + do_test 2.1.3 { + catch { dbh close } + forcedelete test.db-wal + } {} +} + + +test_syscall reset +sqlite3_shutdown +test_sqlite3_log +sqlite3_initialize +finish_test diff --git a/components/external/SQLite-3.8.1/test/pager1.test b/components/external/SQLite-3.8.1/test/pager1.test new file mode 100644 index 0000000000000000000000000000000000000000..4a3b6fa2d81538ad0cb127d7b43bb4bcbc6d26ad --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pager1.test @@ -0,0 +1,2817 @@ +# 2010 June 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl +source $testdir/wal_common.tcl +set testprefix pager1 + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# +# pager1-1.*: Test inter-process locking (clients in multiple processes). +# +# pager1-2.*: Test intra-process locking (multiple clients in this process). +# +# pager1-3.*: Savepoint related tests. +# +# pager1-4.*: Hot-journal related tests. +# +# pager1-5.*: Cases related to multi-file commits. +# +# pager1-6.*: Cases related to "PRAGMA max_page_count" +# +# pager1-7.*: Cases specific to "PRAGMA journal_mode=TRUNCATE" +# +# pager1-8.*: Cases using temporary and in-memory databases. +# +# pager1-9.*: Tests related to the backup API. +# +# pager1-10.*: Test that the assumed file-system sector-size is limited to +# 64KB. +# +# pager1-12.*: Tests involving "PRAGMA page_size" +# +# pager1-13.*: Cases specific to "PRAGMA journal_mode=PERSIST" +# +# pager1-14.*: Cases specific to "PRAGMA journal_mode=OFF" +# +# pager1-15.*: Varying sqlite3_vfs.szOsFile +# +# pager1-16.*: Varying sqlite3_vfs.mxPathname +# +# pager1-17.*: Tests related to "PRAGMA omit_readlock" +# (The omit_readlock pragma has been removed and so have +# these tests.) +# +# pager1-18.*: Test that the pager layer responds correctly if the b-tree +# requests an invalid page number (due to db corruption). +# + +proc recursive_select {id table {script {}}} { + set cnt 0 + db eval "SELECT rowid, * FROM $table WHERE rowid = ($id-1)" { + recursive_select $rowid $table $script + incr cnt + } + if {$cnt==0} { eval $script } +} + +set a_string_counter 1 +proc a_string {n} { + global a_string_counter + incr a_string_counter + string range [string repeat "${a_string_counter}." $n] 1 $n +} +db func a_string a_string + +do_multiclient_test tn { + + # Create and populate a database table using connection [db]. Check + # that connections [db2] and [db3] can see the schema and content. + # + do_test pager1-$tn.1 { + sql1 { + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE INDEX i1 ON t1(b); + INSERT INTO t1 VALUES(1, 'one'); INSERT INTO t1 VALUES(2, 'two'); + } + } {} + do_test pager1-$tn.2 { sql2 { SELECT * FROM t1 } } {1 one 2 two} + do_test pager1-$tn.3 { sql3 { SELECT * FROM t1 } } {1 one 2 two} + + # Open a transaction and add a row using [db]. This puts [db] in + # RESERVED state. Check that connections [db2] and [db3] can still + # read the database content as it was before the transaction was + # opened. [db] should see the inserted row. + # + do_test pager1-$tn.4 { + sql1 { + BEGIN; + INSERT INTO t1 VALUES(3, 'three'); + } + } {} + do_test pager1-$tn.5 { sql2 { SELECT * FROM t1 } } {1 one 2 two} + do_test pager1-$tn.7 { sql1 { SELECT * FROM t1 } } {1 one 2 two 3 three} + + # [db] still has an open write transaction. Check that this prevents + # other connections (specifically [db2]) from writing to the database. + # + # Even if [db2] opens a transaction first, it may not write to the + # database. After the attempt to write the db within a transaction, + # [db2] is left with an open transaction, but not a read-lock on + # the main database. So it does not prevent [db] from committing. + # + do_test pager1-$tn.8 { + csql2 { UPDATE t1 SET a = a + 10 } + } {1 {database is locked}} + do_test pager1-$tn.9 { + csql2 { + BEGIN; + UPDATE t1 SET a = a + 10; + } + } {1 {database is locked}} + + # Have [db] commit its transactions. Check the other connections can + # now see the new database content. + # + do_test pager1-$tn.10 { sql1 { COMMIT } } {} + do_test pager1-$tn.11 { sql1 { SELECT * FROM t1 } } {1 one 2 two 3 three} + do_test pager1-$tn.12 { sql2 { SELECT * FROM t1 } } {1 one 2 two 3 three} + do_test pager1-$tn.13 { sql3 { SELECT * FROM t1 } } {1 one 2 two 3 three} + + # Check that, as noted above, [db2] really did keep an open transaction + # after the attempt to write the database failed. + # + do_test pager1-$tn.14 { + csql2 { BEGIN } + } {1 {cannot start a transaction within a transaction}} + do_test pager1-$tn.15 { sql2 { ROLLBACK } } {} + + # Have [db2] open a transaction and take a read-lock on the database. + # Check that this prevents [db] from writing to the database (outside + # of any transaction). After this fails, check that [db3] can read + # the db (showing that [db] did not take a PENDING lock etc.) + # + do_test pager1-$tn.15 { + sql2 { BEGIN; SELECT * FROM t1; } + } {1 one 2 two 3 three} + do_test pager1-$tn.16 { + csql1 { UPDATE t1 SET a = a + 10 } + } {1 {database is locked}} + do_test pager1-$tn.17 { sql3 { SELECT * FROM t1 } } {1 one 2 two 3 three} + + # This time, have [db] open a transaction before writing the database. + # This works - [db] gets a RESERVED lock which does not conflict with + # the SHARED lock [db2] is holding. + # + do_test pager1-$tn.18 { + sql1 { + BEGIN; + UPDATE t1 SET a = a + 10; + } + } {} + do_test pager1-$tn-19 { + sql1 { PRAGMA lock_status } + } {main reserved temp closed} + do_test pager1-$tn-20 { + sql2 { PRAGMA lock_status } + } {main shared temp closed} + + # Check that all connections can still read the database. Only [db] sees + # the updated content (as the transaction has not been committed yet). + # + do_test pager1-$tn.21 { sql1 { SELECT * FROM t1 } } {11 one 12 two 13 three} + do_test pager1-$tn.22 { sql2 { SELECT * FROM t1 } } {1 one 2 two 3 three} + do_test pager1-$tn.23 { sql3 { SELECT * FROM t1 } } {1 one 2 two 3 three} + + # Because [db2] still has the SHARED lock, [db] is unable to commit the + # transaction. If it tries, an error is returned and the connection + # upgrades to a PENDING lock. + # + # Once this happens, [db] can read the database and see the new content, + # [db2] (still holding SHARED) can still read the old content, but [db3] + # (not holding any lock) is prevented by [db]'s PENDING from reading + # the database. + # + do_test pager1-$tn.24 { csql1 { COMMIT } } {1 {database is locked}} + do_test pager1-$tn-25 { + sql1 { PRAGMA lock_status } + } {main pending temp closed} + do_test pager1-$tn.26 { sql1 { SELECT * FROM t1 } } {11 one 12 two 13 three} + do_test pager1-$tn.27 { sql2 { SELECT * FROM t1 } } {1 one 2 two 3 three} + do_test pager1-$tn.28 { csql3 { SELECT * FROM t1 } } {1 {database is locked}} + + # Have [db2] commit its read transaction, releasing the SHARED lock it + # is holding. Now, neither [db2] nor [db3] may read the database (as [db] + # is still holding a PENDING). + # + do_test pager1-$tn.29 { sql2 { COMMIT } } {} + do_test pager1-$tn.30 { csql2 { SELECT * FROM t1 } } {1 {database is locked}} + do_test pager1-$tn.31 { csql3 { SELECT * FROM t1 } } {1 {database is locked}} + + # [db] is now able to commit the transaction. Once the transaction is + # committed, all three connections can read the new content. + # + do_test pager1-$tn.25 { sql1 { UPDATE t1 SET a = a+10 } } {} + do_test pager1-$tn.26 { sql1 { COMMIT } } {} + do_test pager1-$tn.27 { sql1 { SELECT * FROM t1 } } {21 one 22 two 23 three} + do_test pager1-$tn.27 { sql2 { SELECT * FROM t1 } } {21 one 22 two 23 three} + do_test pager1-$tn.28 { sql3 { SELECT * FROM t1 } } {21 one 22 two 23 three} + + # Install a busy-handler for connection [db]. + # + set ::nbusy [list] + proc busy {n} { + lappend ::nbusy $n + if {$n>5} { sql2 COMMIT } + return 0 + } + db busy busy + + do_test pager1-$tn.29 { + sql1 { BEGIN ; INSERT INTO t1 VALUES('x', 'y') } + } {} + do_test pager1-$tn.30 { + sql2 { BEGIN ; SELECT * FROM t1 } + } {21 one 22 two 23 three} + do_test pager1-$tn.31 { sql1 COMMIT } {} + do_test pager1-$tn.32 { set ::nbusy } {0 1 2 3 4 5 6} +} + +#------------------------------------------------------------------------- +# Savepoint related test cases. +# +# pager1-3.1.2.*: Force a savepoint rollback to cause the database file +# to grow. +# +# pager1-3.1.3.*: Use a journal created in synchronous=off mode as part +# of a savepoint rollback. +# +do_test pager1-3.1.1 { + faultsim_delete_and_reopen + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TABLE counter( + i CHECK (i<5), + u CHECK (u<10) + ); + INSERT INTO counter VALUES(0, 0); + CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN + UPDATE counter SET i = i+1; + END; + CREATE TRIGGER tr2 AFTER UPDATE ON t1 BEGIN + UPDATE counter SET u = u+1; + END; + } + execsql { SELECT * FROM counter } +} {0 0} + +do_execsql_test pager1-3.1.2 { + PRAGMA cache_size = 10; + BEGIN; + INSERT INTO t1 VALUES(1, randomblob(1500)); + INSERT INTO t1 VALUES(2, randomblob(1500)); + INSERT INTO t1 VALUES(3, randomblob(1500)); + SELECT * FROM counter; +} {3 0} +do_catchsql_test pager1-3.1.3 { + INSERT INTO t1 SELECT a+3, randomblob(1500) FROM t1 +} {1 {constraint failed}} +do_execsql_test pager1-3.4 { SELECT * FROM counter } {3 0} +do_execsql_test pager1-3.5 { SELECT a FROM t1 } {1 2 3} +do_execsql_test pager1-3.6 { COMMIT } {} + +foreach {tn sql tcl} { + 7 { PRAGMA synchronous = NORMAL ; PRAGMA temp_store = 0 } { + testvfs tv -default 1 + tv devchar safe_append + } + 8 { PRAGMA synchronous = NORMAL ; PRAGMA temp_store = 2 } { + testvfs tv -default 1 + tv devchar sequential + } + 9 { PRAGMA synchronous = FULL } { } + 10 { PRAGMA synchronous = NORMAL } { } + 11 { PRAGMA synchronous = OFF } { } + 12 { PRAGMA synchronous = FULL ; PRAGMA fullfsync = 1 } { } + 13 { PRAGMA synchronous = FULL } { + testvfs tv -default 1 + tv devchar sequential + } + 14 { PRAGMA locking_mode = EXCLUSIVE } { + } +} { + do_test pager1-3.$tn.1 { + eval $tcl + faultsim_delete_and_reopen + db func a_string a_string + execsql $sql + execsql { + PRAGMA auto_vacuum = 2; + PRAGMA cache_size = 10; + CREATE TABLE z(x INTEGER PRIMARY KEY, y); + BEGIN; + INSERT INTO z VALUES(NULL, a_string(800)); + INSERT INTO z SELECT NULL, a_string(800) FROM z; -- 2 + INSERT INTO z SELECT NULL, a_string(800) FROM z; -- 4 + INSERT INTO z SELECT NULL, a_string(800) FROM z; -- 8 + INSERT INTO z SELECT NULL, a_string(800) FROM z; -- 16 + INSERT INTO z SELECT NULL, a_string(800) FROM z; -- 32 + INSERT INTO z SELECT NULL, a_string(800) FROM z; -- 64 + INSERT INTO z SELECT NULL, a_string(800) FROM z; -- 128 + INSERT INTO z SELECT NULL, a_string(800) FROM z; -- 256 + COMMIT; + } + execsql { PRAGMA auto_vacuum } + } {2} + do_execsql_test pager1-3.$tn.2 { + BEGIN; + INSERT INTO z VALUES(NULL, a_string(800)); + INSERT INTO z VALUES(NULL, a_string(800)); + SAVEPOINT one; + UPDATE z SET y = NULL WHERE x>256; + PRAGMA incremental_vacuum; + SELECT count(*) FROM z WHERE x < 100; + ROLLBACK TO one; + COMMIT; + } {99} + + do_execsql_test pager1-3.$tn.3 { + BEGIN; + SAVEPOINT one; + UPDATE z SET y = y||x; + ROLLBACK TO one; + COMMIT; + SELECT count(*) FROM z; + } {258} + + do_execsql_test pager1-3.$tn.4 { + SAVEPOINT one; + UPDATE z SET y = y||x; + ROLLBACK TO one; + } {} + do_execsql_test pager1-3.$tn.5 { + SELECT count(*) FROM z; + RELEASE one; + PRAGMA integrity_check; + } {258 ok} + + do_execsql_test pager1-3.$tn.6 { + SAVEPOINT one; + RELEASE one; + } {} + + db close + catch { tv delete } +} + +#------------------------------------------------------------------------- +# Hot journal rollback related test cases. +# +# pager1.4.1.*: Test that the pager module deletes very small invalid +# journal files. +# +# pager1.4.2.*: Test that if the master journal pointer at the end of a +# hot-journal file appears to be corrupt (checksum does not +# compute) the associated journal is rolled back (and no +# xAccess() call to check for the presence of any master +# journal file is made). +# +# pager1.4.3.*: Test that the contents of a hot-journal are ignored if the +# page-size or sector-size in the journal header appear to +# be invalid (too large, too small or not a power of 2). +# +# pager1.4.4.*: Test hot-journal rollback of journal file with a master +# journal pointer generated in various "PRAGMA synchronous" +# modes. +# +# pager1.4.5.*: Test that hot-journal rollback stops if it encounters a +# journal-record for which the checksum fails. +# +# pager1.4.6.*: Test that when rolling back a hot-journal that contains a +# master journal pointer, the master journal file is deleted +# after all the hot-journals that refer to it are deleted. +# +# pager1.4.7.*: Test that if a hot-journal file exists but a client can +# open it for reading only, the database cannot be accessed and +# SQLITE_CANTOPEN is returned. +# +do_test pager1.4.1.1 { + faultsim_delete_and_reopen + execsql { + CREATE TABLE x(y, z); + INSERT INTO x VALUES(1, 2); + } + set fd [open test.db-journal w] + puts -nonewline $fd "helloworld" + close $fd + file exists test.db-journal +} {1} +do_test pager1.4.1.2 { execsql { SELECT * FROM x } } {1 2} +do_test pager1.4.1.3 { file exists test.db-journal } {0} + +# Set up a [testvfs] to snapshot the file-system just before SQLite +# deletes the master-journal to commit a multi-file transaction. +# +# In subsequent test cases, invoking [faultsim_restore_and_reopen] sets +# up the file system to contain two databases, two hot-journal files and +# a master-journal. +# +do_test pager1.4.2.1 { + testvfs tstvfs -default 1 + tstvfs filter xDelete + tstvfs script xDeleteCallback + proc xDeleteCallback {method file args} { + set file [file tail $file] + if { [string match *mj* $file] } { faultsim_save } + } + faultsim_delete_and_reopen + db func a_string a_string + execsql { + ATTACH 'test.db2' AS aux; + PRAGMA journal_mode = DELETE; + PRAGMA main.cache_size = 10; + PRAGMA aux.cache_size = 10; + CREATE TABLE t1(a UNIQUE, b UNIQUE); + CREATE TABLE aux.t2(a UNIQUE, b UNIQUE); + INSERT INTO t1 VALUES(a_string(200), a_string(300)); + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t2 SELECT * FROM t1; + BEGIN; + INSERT INTO t1 SELECT a_string(201), a_string(301) FROM t1; + INSERT INTO t1 SELECT a_string(202), a_string(302) FROM t1; + INSERT INTO t1 SELECT a_string(203), a_string(303) FROM t1; + INSERT INTO t1 SELECT a_string(204), a_string(304) FROM t1; + REPLACE INTO t2 SELECT * FROM t1; + COMMIT; + } + db close + tstvfs delete +} {} + +if {$::tcl_platform(platform)!="windows"} { +do_test pager1.4.2.2 { + faultsim_restore_and_reopen + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check; + } +} {4 ok} +do_test pager1.4.2.3 { + faultsim_restore_and_reopen + foreach f [glob test.db-mj*] { forcedelete $f } + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check; + } +} {64 ok} +do_test pager1.4.2.4 { + faultsim_restore_and_reopen + hexio_write test.db-journal [expr [file size test.db-journal]-30] 123456 + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check; + } +} {4 ok} +do_test pager1.4.2.5 { + faultsim_restore_and_reopen + hexio_write test.db-journal [expr [file size test.db-journal]-30] 123456 + foreach f [glob test.db-mj*] { forcedelete $f } + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check; + } +} {4 ok} +} + +do_test pager1.4.3.1 { + testvfs tstvfs -default 1 + tstvfs filter xSync + tstvfs script xSyncCallback + proc xSyncCallback {method file args} { + set file [file tail $file] + if { 0==[string match *journal $file] } { faultsim_save } + } + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = DELETE; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + } + db close + tstvfs delete +} {} + +foreach {tn ofst value result} { + 2 20 31 {1 2 3 4} + 3 20 32 {1 2 3 4} + 4 20 33 {1 2 3 4} + 5 20 65536 {1 2 3 4} + 6 20 131072 {1 2 3 4} + + 7 24 511 {1 2 3 4} + 8 24 513 {1 2 3 4} + 9 24 131072 {1 2 3 4} + + 10 32 65536 {1 2} +} { + do_test pager1.4.3.$tn { + faultsim_restore_and_reopen + hexio_write test.db-journal $ofst [format %.8x $value] + execsql { SELECT * FROM t1 } + } $result +} +db close + +# Set up a VFS that snapshots the file-system just before a master journal +# file is deleted to commit a multi-file transaction. Specifically, the +# file-system is saved just before the xDelete() call to remove the +# master journal file from the file-system. +# +set pwd [get_pwd] +testvfs tv -default 1 +tv script copy_on_mj_delete +set ::mj_filename_length 0 +proc copy_on_mj_delete {method filename args} { + if {[string match *mj* [file tail $filename]]} { + # + # NOTE: Is the file name relative? If so, add the length of the current + # directory. + # + if {[is_relative_file $filename]} { + set ::mj_filename_length \ + [expr {[string length $filename] + [string length $::pwd]}] + } else { + set ::mj_filename_length [string length $filename] + } + faultsim_save + } + return SQLITE_OK +} + +foreach {tn1 tcl} { + 1 { set prefix "test.db" } + 2 { + # This test depends on the underlying VFS being able to open paths + # 512 bytes in length. The idea is to create a hot-journal file that + # contains a master-journal pointer so large that it could contain + # a valid page record (if the file page-size is 512 bytes). So as to + # make sure SQLite doesn't get confused by this. + # + set nPadding [expr 511 - $::mj_filename_length] + if {$tcl_platform(platform)=="windows"} { + # TBD need to figure out how to do this correctly for Windows!!! + set nPadding [expr 255 - $::mj_filename_length] + } + + # We cannot just create a really long database file name to open, as + # Linux limits a single component of a path to 255 bytes by default + # (and presumably other systems have limits too). So create a directory + # hierarchy to work in. + # + set dirname "d123456789012345678901234567890/" + set nDir [expr $nPadding / 32] + if { $nDir } { + set p [string repeat $dirname $nDir] + file mkdir $p + cd $p + } + + set padding [string repeat x [expr $nPadding %32]] + set prefix "test.db${padding}" + } +} { + eval $tcl + foreach {tn2 sql} { + o { + PRAGMA main.synchronous=OFF; + PRAGMA aux.synchronous=OFF; + PRAGMA journal_mode = DELETE; + } + o512 { + PRAGMA main.synchronous=OFF; + PRAGMA aux.synchronous=OFF; + PRAGMA main.page_size = 512; + PRAGMA aux.page_size = 512; + PRAGMA journal_mode = DELETE; + } + n { + PRAGMA main.synchronous=NORMAL; + PRAGMA aux.synchronous=NORMAL; + PRAGMA journal_mode = DELETE; + } + f { + PRAGMA main.synchronous=FULL; + PRAGMA aux.synchronous=FULL; + PRAGMA journal_mode = DELETE; + } + } { + + set tn "${tn1}.${tn2}" + + # Set up a connection to have two databases, test.db (main) and + # test.db2 (aux). Then run a multi-file transaction on them. The + # VFS will snapshot the file-system just before the master-journal + # file is deleted to commit the transaction. + # + tv filter xDelete + do_test pager1-4.4.$tn.1 { + faultsim_delete_and_reopen $prefix + execsql " + ATTACH '${prefix}2' AS aux; + $sql + CREATE TABLE a(x); + CREATE TABLE aux.b(x); + INSERT INTO a VALUES('double-you'); + INSERT INTO a VALUES('why'); + INSERT INTO a VALUES('zed'); + INSERT INTO b VALUES('won'); + INSERT INTO b VALUES('too'); + INSERT INTO b VALUES('free'); + " + execsql { + BEGIN; + INSERT INTO a SELECT * FROM b WHERE rowid<=3; + INSERT INTO b SELECT * FROM a WHERE rowid<=3; + COMMIT; + } + } {} + tv filter {} + + # Check that the transaction was committed successfully. + # + do_execsql_test pager1-4.4.$tn.2 { + SELECT * FROM a + } {double-you why zed won too free} + do_execsql_test pager1-4.4.$tn.3 { + SELECT * FROM b + } {won too free double-you why zed} + + # Restore the file-system and reopen the databases. Check that it now + # appears that the transaction was not committed (because the file-system + # was restored to the state where it had not been). + # + do_test pager1-4.4.$tn.4 { + faultsim_restore_and_reopen $prefix + execsql "ATTACH '${prefix}2' AS aux" + } {} + do_execsql_test pager1-4.4.$tn.5 {SELECT * FROM a} {double-you why zed} + do_execsql_test pager1-4.4.$tn.6 {SELECT * FROM b} {won too free} + + # Restore the file-system again. This time, before reopening the databases, + # delete the master-journal file from the file-system. It now appears that + # the transaction was committed (no master-journal file == no rollback). + # + do_test pager1-4.4.$tn.7 { + faultsim_restore_and_reopen $prefix + foreach f [glob ${prefix}-mj*] { forcedelete $f } + execsql "ATTACH '${prefix}2' AS aux" + } {} + do_execsql_test pager1-4.4.$tn.8 { + SELECT * FROM a + } {double-you why zed won too free} + do_execsql_test pager1-4.4.$tn.9 { + SELECT * FROM b + } {won too free double-you why zed} + } + + cd $pwd +} +db close +tv delete +forcedelete $dirname + + +# Set up a VFS to make a copy of the file-system just before deleting a +# journal file to commit a transaction. The transaction modifies exactly +# two database pages (and page 1 - the change counter). +# +testvfs tv -default 1 +tv sectorsize 512 +tv script copy_on_journal_delete +tv filter xDelete +proc copy_on_journal_delete {method filename args} { + if {[string match *journal $filename]} faultsim_save + return SQLITE_OK +} +faultsim_delete_and_reopen +do_execsql_test pager1.4.5.1 { + PRAGMA journal_mode = DELETE; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + INSERT INTO t1 VALUES('I', 'II'); + INSERT INTO t2 VALUES('III', 'IV'); + BEGIN; + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t2 VALUES(3, 4); + COMMIT; +} {delete} +tv filter {} + +# Check the transaction was committed: +# +do_execsql_test pager1.4.5.2 { + SELECT * FROM t1; + SELECT * FROM t2; +} {I II 1 2 III IV 3 4} + +# Now try four tests: +# +# pager1-4.5.3: Restore the file-system. Check that the whole transaction +# is rolled back. +# +# pager1-4.5.4: Restore the file-system. Corrupt the first record in the +# journal. Check the transaction is not rolled back. +# +# pager1-4.5.5: Restore the file-system. Corrupt the second record in the +# journal. Check that the first record in the transaction is +# played back, but not the second. +# +# pager1-4.5.6: Restore the file-system. Try to open the database with a +# readonly connection. This should fail, as a read-only +# connection cannot roll back the database file. +# +faultsim_restore_and_reopen +do_execsql_test pager1.4.5.3 { + SELECT * FROM t1; + SELECT * FROM t2; +} {I II III IV} +faultsim_restore_and_reopen +hexio_write test.db-journal [expr 512+4+1024 - 202] 0123456789ABCDEF +do_execsql_test pager1.4.5.4 { + SELECT * FROM t1; + SELECT * FROM t2; +} {I II 1 2 III IV 3 4} +faultsim_restore_and_reopen +hexio_write test.db-journal [expr 512+4+1024+4+4+1024 - 202] 0123456789ABCDEF +do_execsql_test pager1.4.5.5 { + SELECT * FROM t1; + SELECT * FROM t2; +} {I II III IV 3 4} + +faultsim_restore_and_reopen +db close +sqlite3 db test.db -readonly 1 +do_catchsql_test pager1.4.5.6 { + SELECT * FROM t1; + SELECT * FROM t2; +} {1 {attempt to write a readonly database}} +db close + +# Snapshot the file-system just before multi-file commit. Save the name +# of the master journal file in $::mj_filename. +# +tv script copy_on_mj_delete +tv filter xDelete +proc copy_on_mj_delete {method filename args} { + if {[string match *mj* [file tail $filename]]} { + set ::mj_filename $filename + faultsim_save + } + return SQLITE_OK +} +do_test pager1.4.6.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = DELETE; + ATTACH 'test.db2' AS two; + CREATE TABLE t1(a, b); + CREATE TABLE two.t2(a, b); + INSERT INTO t1 VALUES(1, 't1.1'); + INSERT INTO t2 VALUES(1, 't2.1'); + BEGIN; + UPDATE t1 SET b = 't1.2'; + UPDATE t2 SET b = 't2.2'; + COMMIT; + } + tv filter {} + db close +} {} + +faultsim_restore_and_reopen +do_execsql_test pager1.4.6.2 { SELECT * FROM t1 } {1 t1.1} +do_test pager1.4.6.3 { file exists $::mj_filename } {1} +do_execsql_test pager1.4.6.4 { + ATTACH 'test.db2' AS two; + SELECT * FROM t2; +} {1 t2.1} +do_test pager1.4.6.5 { file exists $::mj_filename } {0} + +faultsim_restore_and_reopen +db close +do_test pager1.4.6.8 { + set ::mj_filename1 $::mj_filename + tv filter xDelete + sqlite3 db test.db2 + execsql { + PRAGMA journal_mode = DELETE; + ATTACH 'test.db3' AS three; + CREATE TABLE three.t3(a, b); + INSERT INTO t3 VALUES(1, 't3.1'); + BEGIN; + UPDATE t2 SET b = 't2.3'; + UPDATE t3 SET b = 't3.3'; + COMMIT; + } + expr {$::mj_filename1 != $::mj_filename} +} {1} +faultsim_restore_and_reopen +tv filter {} + +# The file-system now contains: +# +# * three databases +# * three hot-journal files +# * two master-journal files. +# +# The hot-journals associated with test.db2 and test.db3 point to +# master journal $::mj_filename. The hot-journal file associated with +# test.db points to master journal $::mj_filename1. So reading from +# test.db should delete $::mj_filename1. +# +do_test pager1.4.6.9 { + lsort [glob test.db*] +} [lsort [list \ + test.db test.db2 test.db3 \ + test.db-journal test.db2-journal test.db3-journal \ + [file tail $::mj_filename] [file tail $::mj_filename1] +]] + +# The master-journal $::mj_filename1 contains pointers to test.db and +# test.db2. However the hot-journal associated with test.db2 points to +# a different master-journal. Therefore, reading from test.db only should +# be enough to cause SQLite to delete $::mj_filename1. +# +do_test pager1.4.6.10 { file exists $::mj_filename } {1} +do_test pager1.4.6.11 { file exists $::mj_filename1 } {1} +do_execsql_test pager1.4.6.12 { SELECT * FROM t1 } {1 t1.1} +do_test pager1.4.6.13 { file exists $::mj_filename } {1} +do_test pager1.4.6.14 { file exists $::mj_filename1 } {0} + +do_execsql_test pager1.4.6.12 { + ATTACH 'test.db2' AS two; + SELECT * FROM t2; +} {1 t2.1} +do_test pager1.4.6.13 { file exists $::mj_filename } {1} +do_execsql_test pager1.4.6.14 { + ATTACH 'test.db3' AS three; + SELECT * FROM t3; +} {1 t3.1} +do_test pager1.4.6.15 { file exists $::mj_filename } {0} + +db close +tv delete + +testvfs tv -default 1 +tv sectorsize 512 +tv script copy_on_journal_delete +tv filter xDelete +proc copy_on_journal_delete {method filename args} { + if {[string match *journal $filename]} faultsim_save + return SQLITE_OK +} +faultsim_delete_and_reopen +do_execsql_test pager1.4.7.1 { + PRAGMA journal_mode = DELETE; + CREATE TABLE t1(x PRIMARY KEY, y); + CREATE INDEX i1 ON t1(y); + INSERT INTO t1 VALUES('I', 'one'); + INSERT INTO t1 VALUES('II', 'four'); + INSERT INTO t1 VALUES('III', 'nine'); + BEGIN; + INSERT INTO t1 VALUES('IV', 'sixteen'); + INSERT INTO t1 VALUES('V' , 'twentyfive'); + COMMIT; +} {delete} +tv filter {} +db close +tv delete +catch { + test_syscall install fchmod + test_syscall fault 1 1 +} +do_test pager1.4.7.2 { + faultsim_restore_and_reopen + catch {file attributes test.db-journal -permissions r--------} + catch {file attributes test.db-journal -readonly 1} + catchsql { SELECT * FROM t1 } +} {1 {unable to open database file}} +catch { + test_syscall reset + test_syscall fault 0 0 +} +do_test pager1.4.7.3 { + db close + catch {file attributes test.db-journal -permissions rw-rw-rw-} + catch {file attributes test.db-journal -readonly 0} + delete_file test.db-journal + file exists test.db-journal +} {0} +do_test pager1.4.8.1 { + catch {file attributes test.db -permissions r--------} + catch {file attributes test.db -readonly 1} + sqlite3 db test.db + db eval { SELECT * FROM t1 } + sqlite3_db_readonly db main +} {1} +do_test pager1.4.8.2 { + sqlite3_db_readonly db xyz +} {-1} +do_test pager1.4.8.3 { + db close + catch {file attributes test.db -readonly 0} + catch {file attributes test.db -permissions rw-rw-rw-} msg + sqlite3 db test.db + db eval { SELECT * FROM t1 } + sqlite3_db_readonly db main +} {0} + +#------------------------------------------------------------------------- +# The following tests deal with multi-file commits. +# +# pager1-5.1.*: The case where a multi-file cannot be committed because +# another connection is holding a SHARED lock on one of the +# files. After the SHARED lock is removed, the COMMIT succeeds. +# +# pager1-5.2.*: Multi-file commits with journal_mode=memory. +# +# pager1-5.3.*: Multi-file commits with journal_mode=memory. +# +# pager1-5.4.*: Check that with synchronous=normal, the master-journal file +# name is added to a journal file immediately after the last +# journal record. But with synchronous=full, extra unused space +# is allocated between the last journal record and the +# master-journal file name so that the master-journal file +# name does not lie on the same sector as the last journal file +# record. +# +# pager1-5.5.*: Check that in journal_mode=PERSIST mode, a journal file is +# truncated to zero bytes when a multi-file transaction is +# committed (instead of the first couple of bytes being zeroed). +# +# +do_test pager1-5.1.1 { + faultsim_delete_and_reopen + execsql { + ATTACH 'test.db2' AS aux; + CREATE TABLE t1(a, b); + CREATE TABLE aux.t2(a, b); + INSERT INTO t1 VALUES(17, 'Lenin'); + INSERT INTO t1 VALUES(22, 'Stalin'); + INSERT INTO t1 VALUES(53, 'Khrushchev'); + } +} {} +do_test pager1-5.1.2 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(64, 'Brezhnev'); + INSERT INTO t2 SELECT * FROM t1; + } + sqlite3 db2 test.db2 + execsql { + BEGIN; + SELECT * FROM t2; + } db2 +} {} +do_test pager1-5.1.3 { + catchsql COMMIT +} {1 {database is locked}} +do_test pager1-5.1.4 { + execsql COMMIT db2 + execsql COMMIT + execsql { SELECT * FROM t2 } db2 +} {17 Lenin 22 Stalin 53 Khrushchev 64 Brezhnev} +do_test pager1-5.1.5 { + db2 close +} {} + +do_test pager1-5.2.1 { + execsql { + PRAGMA journal_mode = memory; + BEGIN; + INSERT INTO t1 VALUES(84, 'Andropov'); + INSERT INTO t2 VALUES(84, 'Andropov'); + COMMIT; + } +} {memory} +do_test pager1-5.3.1 { + execsql { + PRAGMA journal_mode = off; + BEGIN; + INSERT INTO t1 VALUES(85, 'Gorbachev'); + INSERT INTO t2 VALUES(85, 'Gorbachev'); + COMMIT; + } +} {off} + +do_test pager1-5.4.1 { + db close + testvfs tv + sqlite3 db test.db -vfs tv + execsql { ATTACH 'test.db2' AS aux } + + tv filter xDelete + tv script max_journal_size + tv sectorsize 512 + set ::max_journal 0 + proc max_journal_size {method args} { + set sz 0 + catch { set sz [file size test.db-journal] } + if {$sz > $::max_journal} { + set ::max_journal $sz + } + return SQLITE_OK + } + execsql { + PRAGMA journal_mode = DELETE; + PRAGMA synchronous = NORMAL; + BEGIN; + INSERT INTO t1 VALUES(85, 'Gorbachev'); + INSERT INTO t2 VALUES(85, 'Gorbachev'); + COMMIT; + } + + # The size of the journal file is now: + # + # 1) 512 byte header + + # 2) 2 * (1024+8) byte records + + # 3) 20+N bytes of master-journal pointer, where N is the size of + # the master-journal name encoded as utf-8 with no nul term. + # + set mj_pointer [expr { + 20 + [string length "test.db-mjXXXXXX9XX"] + }] + # + # NOTE: For item 3 above, if the current SQLite VFS lacks the concept of a + # current directory, the length of the current directory name plus 1 + # character for the directory separator character are NOT counted as + # part of the total size; otherwise, they are. + # + ifcapable curdir { + set mj_pointer [expr {$mj_pointer + [string length [get_pwd]] + 1}] + } + expr {$::max_journal==(512+2*(1024+8)+$mj_pointer)} +} 1 +do_test pager1-5.4.2 { + set ::max_journal 0 + execsql { + PRAGMA synchronous = full; + BEGIN; + DELETE FROM t1 WHERE b = 'Lenin'; + DELETE FROM t2 WHERE b = 'Lenin'; + COMMIT; + } + + # In synchronous=full mode, the master-journal pointer is not written + # directly after the last record in the journal file. Instead, it is + # written starting at the next (in this case 512 byte) sector boundary. + # + set mj_pointer [expr { + 20 + [string length "test.db-mjXXXXXX9XX"] + }] + # + # NOTE: If the current SQLite VFS lacks the concept of a current directory, + # the length of the current directory name plus 1 character for the + # directory separator character are NOT counted as part of the total + # size; otherwise, they are. + # + ifcapable curdir { + set mj_pointer [expr {$mj_pointer + [string length [get_pwd]] + 1}] + } + expr {$::max_journal==(((512+2*(1024+8)+511)/512)*512 + $mj_pointer)} +} 1 +db close +tv delete + +do_test pager1-5.5.1 { + sqlite3 db test.db + execsql { + ATTACH 'test.db2' AS aux; + PRAGMA journal_mode = PERSIST; + CREATE TABLE t3(a, b); + INSERT INTO t3 SELECT randomblob(1500), randomblob(1500) FROM t1; + UPDATE t3 SET b = randomblob(1500); + } + expr [file size test.db-journal] > 15000 +} {1} +do_test pager1-5.5.2 { + execsql { + PRAGMA synchronous = full; + BEGIN; + DELETE FROM t1 WHERE b = 'Stalin'; + DELETE FROM t2 WHERE b = 'Stalin'; + COMMIT; + } + file size test.db-journal +} {0} + + +#------------------------------------------------------------------------- +# The following tests work with "PRAGMA max_page_count" +# +do_test pager1-6.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA auto_vacuum = none; + PRAGMA max_page_count = 10; + CREATE TABLE t2(a, b); + CREATE TABLE t3(a, b); + CREATE TABLE t4(a, b); + CREATE TABLE t5(a, b); + CREATE TABLE t6(a, b); + CREATE TABLE t7(a, b); + CREATE TABLE t8(a, b); + CREATE TABLE t9(a, b); + CREATE TABLE t10(a, b); + } +} {10} +do_catchsql_test pager1-6.2 { + CREATE TABLE t11(a, b) +} {1 {database or disk is full}} +do_execsql_test pager1-6.4 { PRAGMA max_page_count } {10} +do_execsql_test pager1-6.5 { PRAGMA max_page_count = 15 } {15} +do_execsql_test pager1-6.6 { CREATE TABLE t11(a, b) } {} +do_execsql_test pager1-6.7 { + BEGIN; + INSERT INTO t11 VALUES(1, 2); + PRAGMA max_page_count = 13; +} {13} +do_execsql_test pager1-6.8 { + INSERT INTO t11 VALUES(3, 4); + PRAGMA max_page_count = 10; +} {11} +do_execsql_test pager1-6.9 { COMMIT } {} + +do_execsql_test pager1-6.10 { PRAGMA max_page_count = 10 } {11} +do_execsql_test pager1-6.11 { SELECT * FROM t11 } {1 2 3 4} +do_execsql_test pager1-6.12 { PRAGMA max_page_count } {11} + + +#------------------------------------------------------------------------- +# The following tests work with "PRAGMA journal_mode=TRUNCATE" and +# "PRAGMA locking_mode=EXCLUSIVE". +# +# Each test is specified with 5 variables. As follows: +# +# $tn: Test Number. Used as part of the [do_test] test names. +# $sql: SQL to execute. +# $res: Expected result of executing $sql. +# $js: The expected size of the journal file, in bytes, after executing +# the SQL script. Or -1 if the journal is not expected to exist. +# $ws: The expected size of the WAL file, in bytes, after executing +# the SQL script. Or -1 if the WAL is not expected to exist. +# +ifcapable wal { + faultsim_delete_and_reopen + foreach {tn sql res js ws} [subst { + + 1 { + CREATE TABLE t1(a, b); + PRAGMA auto_vacuum=OFF; + PRAGMA synchronous=NORMAL; + PRAGMA page_size=1024; + PRAGMA locking_mode=EXCLUSIVE; + PRAGMA journal_mode=TRUNCATE; + INSERT INTO t1 VALUES(1, 2); + } {exclusive truncate} 0 -1 + + 2 { + BEGIN IMMEDIATE; + SELECT * FROM t1; + COMMIT; + } {1 2} 0 -1 + + 3 { + BEGIN; + SELECT * FROM t1; + COMMIT; + } {1 2} 0 -1 + + 4 { PRAGMA journal_mode = WAL } wal -1 -1 + 5 { INSERT INTO t1 VALUES(3, 4) } {} -1 [wal_file_size 1 1024] + 6 { PRAGMA locking_mode = NORMAL } exclusive -1 [wal_file_size 1 1024] + 7 { INSERT INTO t1 VALUES(5, 6); } {} -1 [wal_file_size 2 1024] + + 8 { PRAGMA journal_mode = TRUNCATE } truncate 0 -1 + 9 { INSERT INTO t1 VALUES(7, 8) } {} 0 -1 + 10 { SELECT * FROM t1 } {1 2 3 4 5 6 7 8} 0 -1 + + }] { + do_execsql_test pager1-7.1.$tn.1 $sql $res + catch { set J -1 ; set J [file size test.db-journal] } + catch { set W -1 ; set W [file size test.db-wal] } + do_test pager1-7.1.$tn.2 { list $J $W } [list $js $ws] + } +} + +do_test pager1-7.2.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA locking_mode = EXCLUSIVE; + CREATE TABLE t1(a, b); + BEGIN; + PRAGMA journal_mode = delete; + PRAGMA journal_mode = truncate; + } +} {exclusive delete truncate} +do_test pager1-7.2.2 { + execsql { INSERT INTO t1 VALUES(1, 2) } + execsql { PRAGMA journal_mode = persist } +} {truncate} +do_test pager1-7.2.3 { + execsql { COMMIT } + execsql { + PRAGMA journal_mode = persist; + PRAGMA journal_size_limit; + } +} {persist -1} + +#------------------------------------------------------------------------- +# The following tests, pager1-8.*, test that the special filenames +# ":memory:" and "" open temporary databases. +# +foreach {tn filename} { + 1 :memory: + 2 "" +} { + do_test pager1-8.$tn.1 { + faultsim_delete_and_reopen + db close + sqlite3 db $filename + execsql { + PRAGMA auto_vacuum = 1; + CREATE TABLE x1(x); + INSERT INTO x1 VALUES('Charles'); + INSERT INTO x1 VALUES('James'); + INSERT INTO x1 VALUES('Mary'); + SELECT * FROM x1; + } + } {Charles James Mary} + + do_test pager1-8.$tn.2 { + sqlite3 db2 $filename + catchsql { SELECT * FROM x1 } db2 + } {1 {no such table: x1}} + + do_execsql_test pager1-8.$tn.3 { + BEGIN; + INSERT INTO x1 VALUES('William'); + INSERT INTO x1 VALUES('Anne'); + ROLLBACK; + } {} +} + +#------------------------------------------------------------------------- +# The next block of tests - pager1-9.* - deal with interactions between +# the pager and the backup API. Test cases: +# +# pager1-9.1.*: Test that a backup completes successfully even if the +# source db is written to during the backup op. +# +# pager1-9.2.*: Test that a backup completes successfully even if the +# source db is written to and then rolled back during a +# backup operation. +# +do_test pager1-9.0.1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE ab(a, b, UNIQUE(a, b)); + INSERT INTO ab VALUES( a_string(200), a_string(300) ); + INSERT INTO ab SELECT a_string(200), a_string(300) FROM ab; + INSERT INTO ab SELECT a_string(200), a_string(300) FROM ab; + INSERT INTO ab SELECT a_string(200), a_string(300) FROM ab; + INSERT INTO ab SELECT a_string(200), a_string(300) FROM ab; + INSERT INTO ab SELECT a_string(200), a_string(300) FROM ab; + INSERT INTO ab SELECT a_string(200), a_string(300) FROM ab; + INSERT INTO ab SELECT a_string(200), a_string(300) FROM ab; + COMMIT; + } +} {} +do_test pager1-9.0.2 { + sqlite3 db2 test.db2 + db2 eval { PRAGMA cache_size = 10 } + sqlite3_backup B db2 main db main + list [B step 10000] [B finish] +} {SQLITE_DONE SQLITE_OK} +do_test pager1-9.0.3 { + db one {SELECT md5sum(a, b) FROM ab} +} [db2 one {SELECT md5sum(a, b) FROM ab}] + +do_test pager1-9.1.1 { + execsql { UPDATE ab SET a = a_string(201) } + sqlite3_backup B db2 main db main + B step 30 +} {SQLITE_OK} +do_test pager1-9.1.2 { + execsql { UPDATE ab SET b = a_string(301) } + list [B step 10000] [B finish] +} {SQLITE_DONE SQLITE_OK} +do_test pager1-9.1.3 { + db one {SELECT md5sum(a, b) FROM ab} +} [db2 one {SELECT md5sum(a, b) FROM ab}] +do_test pager1-9.1.4 { execsql { SELECT count(*) FROM ab } } {128} + +do_test pager1-9.2.1 { + execsql { UPDATE ab SET a = a_string(202) } + sqlite3_backup B db2 main db main + B step 30 +} {SQLITE_OK} +do_test pager1-9.2.2 { + execsql { + BEGIN; + UPDATE ab SET b = a_string(301); + ROLLBACK; + } + list [B step 10000] [B finish] +} {SQLITE_DONE SQLITE_OK} +do_test pager1-9.2.3 { + db one {SELECT md5sum(a, b) FROM ab} +} [db2 one {SELECT md5sum(a, b) FROM ab}] +do_test pager1-9.2.4 { execsql { SELECT count(*) FROM ab } } {128} +db close +db2 close + +do_test pager1-9.3.1 { + testvfs tv -default 1 + tv sectorsize 4096 + faultsim_delete_and_reopen + + execsql { PRAGMA page_size = 1024 } + for {set ii 0} {$ii < 4} {incr ii} { execsql "CREATE TABLE t${ii}(a, b)" } +} {} +do_test pager1-9.3.2 { + sqlite3 db2 test.db2 + + execsql { + PRAGMA page_size = 4096; + PRAGMA synchronous = OFF; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + } db2 + + sqlite3_backup B db2 main db main + B step 30 + list [B step 10000] [B finish] +} {SQLITE_DONE SQLITE_OK} +do_test pager1-9.3.3 { + db2 close + db close + tv delete + file size test.db2 +} [file size test.db] + +do_test pager1-9.4.1 { + faultsim_delete_and_reopen + sqlite3 db2 test.db2 + execsql { + PRAGMA page_size = 4096; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + } db2 + sqlite3_backup B db2 main db main + list [B step 10000] [B finish] +} {SQLITE_DONE SQLITE_OK} +do_test pager1-9.4.2 { + list [file size test.db2] [file size test.db] +} {1024 0} +db2 close + +#------------------------------------------------------------------------- +# Test that regardless of the value returned by xSectorSize(), the +# minimum effective sector-size is 512 and the maximum 65536 bytes. +# +testvfs tv -default 1 +foreach sectorsize { + 16 + 32 64 128 256 512 1024 2048 + 4096 8192 16384 32768 65536 131072 262144 +} { + tv sectorsize $sectorsize + tv devchar {} + set eff $sectorsize + if {$sectorsize < 512} { set eff 512 } + if {$sectorsize > 65536} { set eff 65536 } + + do_test pager1-10.$sectorsize.1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA journal_mode = PERSIST; + PRAGMA page_size = 1024; + BEGIN; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + CREATE TABLE t3(a, b); + COMMIT; + } + file size test.db-journal + } [expr $sectorsize > 65536 ? 65536 : ($sectorsize<32 ? 512 : $sectorsize)] + + do_test pager1-10.$sectorsize.2 { + execsql { + INSERT INTO t3 VALUES(a_string(300), a_string(300)); + INSERT INTO t3 SELECT * FROM t3; /* 2 */ + INSERT INTO t3 SELECT * FROM t3; /* 4 */ + INSERT INTO t3 SELECT * FROM t3; /* 8 */ + INSERT INTO t3 SELECT * FROM t3; /* 16 */ + INSERT INTO t3 SELECT * FROM t3; /* 32 */ + } + } {} + + do_test pager1-10.$sectorsize.3 { + db close + sqlite3 db test.db + execsql { + PRAGMA cache_size = 10; + BEGIN; + } + recursive_select 32 t3 {db eval "INSERT INTO t2 VALUES(1, 2)"} + execsql { + COMMIT; + SELECT * FROM t2; + } + } {1 2} + + do_test pager1-10.$sectorsize.4 { + execsql { + CREATE TABLE t6(a, b); + CREATE TABLE t7(a, b); + CREATE TABLE t5(a, b); + DROP TABLE t6; + DROP TABLE t7; + } + execsql { + BEGIN; + CREATE TABLE t6(a, b); + } + recursive_select 32 t3 {db eval "INSERT INTO t5 VALUES(1, 2)"} + execsql { + COMMIT; + SELECT * FROM t5; + } + } {1 2} + +} +db close + +tv sectorsize 4096 +do_test pager1.10.x.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA auto_vacuum = none; + PRAGMA page_size = 1024; + CREATE TABLE t1(x); + } + for {set i 0} {$i<30} {incr i} { + execsql { INSERT INTO t1 VALUES(zeroblob(900)) } + } + file size test.db +} {32768} +do_test pager1.10.x.2 { + execsql { + CREATE TABLE t2(x); + DROP TABLE t2; + } + file size test.db +} {33792} +do_test pager1.10.x.3 { + execsql { + BEGIN; + CREATE TABLE t2(x); + } + recursive_select 30 t1 + execsql { + CREATE TABLE t3(x); + COMMIT; + } +} {} + +db close +tv delete + +testvfs tv -default 1 +faultsim_delete_and_reopen +db func a_string a_string +do_execsql_test pager1-11.1 { + PRAGMA journal_mode = DELETE; + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE zz(top PRIMARY KEY); + INSERT INTO zz VALUES(a_string(222)); + INSERT INTO zz SELECT a_string((SELECT 222+max(rowid) FROM zz)) FROM zz; + INSERT INTO zz SELECT a_string((SELECT 222+max(rowid) FROM zz)) FROM zz; + INSERT INTO zz SELECT a_string((SELECT 222+max(rowid) FROM zz)) FROM zz; + INSERT INTO zz SELECT a_string((SELECT 222+max(rowid) FROM zz)) FROM zz; + INSERT INTO zz SELECT a_string((SELECT 222+max(rowid) FROM zz)) FROM zz; + COMMIT; + BEGIN; + UPDATE zz SET top = a_string(345); +} {delete} + +proc lockout {method args} { return SQLITE_IOERR } +tv script lockout +tv filter {xWrite xTruncate xSync} +do_catchsql_test pager1-11.2 { COMMIT } {1 {disk I/O error}} + +tv script {} +do_test pager1-11.3 { + sqlite3 db2 test.db + execsql { + PRAGMA journal_mode = TRUNCATE; + PRAGMA integrity_check; + } db2 +} {truncate ok} +do_test pager1-11.4 { + db2 close + file exists test.db-journal +} {0} +do_execsql_test pager1-11.5 { SELECT count(*) FROM zz } {32} +db close +tv delete + +#------------------------------------------------------------------------- +# Test "PRAGMA page_size" +# +testvfs tv -default 1 +tv sectorsize 1024 +foreach pagesize { + 512 1024 2048 4096 8192 16384 32768 +} { + faultsim_delete_and_reopen + + # The sector-size (according to the VFS) is 1024 bytes. So if the + # page-size requested using "PRAGMA page_size" is greater than the + # compile time value of SQLITE_MAX_PAGE_SIZE, then the effective + # page-size remains 1024 bytes. + # + set eff $pagesize + if {$eff > $::SQLITE_MAX_PAGE_SIZE} { set eff 1024 } + + do_test pager1-12.$pagesize.1 { + sqlite3 db2 test.db + execsql " + PRAGMA page_size = $pagesize; + CREATE VIEW v AS SELECT * FROM sqlite_master; + " db2 + file size test.db + } $eff + do_test pager1-12.$pagesize.2 { + sqlite3 db2 test.db + execsql { + SELECT count(*) FROM v; + PRAGMA main.page_size; + } db2 + } [list 1 $eff] + do_test pager1-12.$pagesize.3 { + execsql { + SELECT count(*) FROM v; + PRAGMA main.page_size; + } + } [list 1 $eff] + db2 close +} +db close +tv delete + +#------------------------------------------------------------------------- +# Test specal "PRAGMA journal_mode=PERSIST" test cases. +# +# pager1-13.1.*: This tests a special case encountered in persistent +# journal mode: If the journal associated with a transaction +# is smaller than the journal file (because a previous +# transaction left a very large non-hot journal file in the +# file-system), then SQLite has to be careful that there is +# not a journal-header left over from a previous transaction +# immediately following the journal content just written. +# If there is, and the process crashes so that the journal +# becomes a hot-journal and must be rolled back by another +# process, there is a danger that the other process may roll +# back the aborted transaction, then continue copying data +# from an older transaction from the remainder of the journal. +# See the syncJournal() function for details. +# +# pager1-13.2.*: Same test as the previous. This time, throw an index into +# the mix to make the integrity-check more likely to catch +# errors. +# +testvfs tv -default 1 +tv script xSyncCb +tv filter xSync +proc xSyncCb {method filename args} { + set t [file tail $filename] + if {$t == "test.db"} faultsim_save + return SQLITE_OK +} +faultsim_delete_and_reopen +db func a_string a_string + +# The UPDATE statement at the end of this test case creates a really big +# journal. Since the cache-size is only 10 pages, the journal contains +# frequent journal headers. +# +do_execsql_test pager1-13.1.1 { + PRAGMA page_size = 1024; + PRAGMA journal_mode = PERSIST; + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b BLOB); + INSERT INTO t1 VALUES(NULL, a_string(400)); + INSERT INTO t1 SELECT NULL, a_string(400) FROM t1; /* 2 */ + INSERT INTO t1 SELECT NULL, a_string(400) FROM t1; /* 4 */ + INSERT INTO t1 SELECT NULL, a_string(400) FROM t1; /* 8 */ + INSERT INTO t1 SELECT NULL, a_string(400) FROM t1; /* 16 */ + INSERT INTO t1 SELECT NULL, a_string(400) FROM t1; /* 32 */ + INSERT INTO t1 SELECT NULL, a_string(400) FROM t1; /* 64 */ + INSERT INTO t1 SELECT NULL, a_string(400) FROM t1; /* 128 */ + COMMIT; + UPDATE t1 SET b = a_string(400); +} {persist} + +if {$::tcl_platform(platform)!="windows"} { +# Run transactions of increasing sizes. Eventually, one (or more than one) +# of these will write just enough content that one of the old headers created +# by the transaction in the block above lies immediately after the content +# journalled by the current transaction. +# +for {set nUp 1} {$nUp<64} {incr nUp} { + do_execsql_test pager1-13.1.2.$nUp.1 { + UPDATE t1 SET b = a_string(399) WHERE a <= $nUp + } {} + do_execsql_test pager1-13.1.2.$nUp.2 { PRAGMA integrity_check } {ok} + + # Try to access the snapshot of the file-system. + # + sqlite3 db2 sv_test.db + do_test pager1-13.1.2.$nUp.3 { + execsql { SELECT sum(length(b)) FROM t1 } db2 + } [expr {128*400 - ($nUp-1)}] + do_test pager1-13.1.2.$nUp.4 { + execsql { PRAGMA integrity_check } db2 + } {ok} + db2 close +} +} + +if {$::tcl_platform(platform)!="windows"} { +# Same test as above. But this time with an index on the table. +# +do_execsql_test pager1-13.2.1 { + CREATE INDEX i1 ON t1(b); + UPDATE t1 SET b = a_string(400); +} {} +for {set nUp 1} {$nUp<64} {incr nUp} { + do_execsql_test pager1-13.2.2.$nUp.1 { + UPDATE t1 SET b = a_string(399) WHERE a <= $nUp + } {} + do_execsql_test pager1-13.2.2.$nUp.2 { PRAGMA integrity_check } {ok} + sqlite3 db2 sv_test.db + do_test pager1-13.2.2.$nUp.3 { + execsql { SELECT sum(length(b)) FROM t1 } db2 + } [expr {128*400 - ($nUp-1)}] + do_test pager1-13.2.2.$nUp.4 { + execsql { PRAGMA integrity_check } db2 + } {ok} + db2 close +} +} + +db close +tv delete + +#------------------------------------------------------------------------- +# Test specal "PRAGMA journal_mode=OFF" test cases. +# +faultsim_delete_and_reopen +do_execsql_test pager1-14.1.1 { + PRAGMA journal_mode = OFF; + CREATE TABLE t1(a, b); + BEGIN; + INSERT INTO t1 VALUES(1, 2); + COMMIT; + SELECT * FROM t1; +} {off 1 2} +do_catchsql_test pager1-14.1.2 { + BEGIN; + INSERT INTO t1 VALUES(3, 4); + ROLLBACK; +} {0 {}} +do_execsql_test pager1-14.1.3 { + SELECT * FROM t1; +} {1 2} +do_catchsql_test pager1-14.1.4 { + BEGIN; + INSERT INTO t1(rowid, a, b) SELECT a+3, b, b FROM t1; + INSERT INTO t1(rowid, a, b) SELECT a+3, b, b FROM t1; +} {1 {PRIMARY KEY must be unique}} +do_execsql_test pager1-14.1.5 { + COMMIT; + SELECT * FROM t1; +} {1 2 2 2} + +#------------------------------------------------------------------------- +# Test opening and closing the pager sub-system with different values +# for the sqlite3_vfs.szOsFile variable. +# +faultsim_delete_and_reopen +do_execsql_test pager1-15.0 { + CREATE TABLE tx(y, z); + INSERT INTO tx VALUES('Ayutthaya', 'Beijing'); + INSERT INTO tx VALUES('London', 'Tokyo'); +} {} +db close +for {set i 0} {$i<513} {incr i 3} { + testvfs tv -default 1 -szosfile $i + sqlite3 db test.db + do_execsql_test pager1-15.$i.1 { + SELECT * FROM tx; + } {Ayutthaya Beijing London Tokyo} + db close + tv delete +} + +#------------------------------------------------------------------------- +# Check that it is not possible to open a database file if the full path +# to the associated journal file will be longer than sqlite3_vfs.mxPathname. +# +testvfs tv -default 1 +tv script xOpenCb +tv filter xOpen +proc xOpenCb {method filename args} { + set ::file_len [string length $filename] +} +sqlite3 db test.db +db close +tv delete + +for {set ii [expr $::file_len-5]} {$ii < [expr $::file_len+20]} {incr ii} { + testvfs tv -default 1 -mxpathname $ii + + # The length of the full path to file "test.db-journal" is ($::file_len+8). + # If the configured sqlite3_vfs.mxPathname value greater than or equal to + # this, then the file can be opened. Otherwise, it cannot. + # + if {$ii >= [expr $::file_len+8]} { + set res {0 {}} + } else { + set res {1 {unable to open database file}} + } + + do_test pager1-16.1.$ii { + list [catch { sqlite3 db test.db } msg] $msg + } $res + + catch {db close} + tv delete +} + + +#------------------------------------------------------------------------- +# Test the pagers response to the b-tree layer requesting illegal page +# numbers: +# +# + The locking page, +# + Page 0, +# + A page with a page number greater than (2^31-1). +# +# These tests will not work if SQLITE_DIRECT_OVERFLOW_READ is defined. In +# that case IO errors are sometimes reported instead of SQLITE_CORRUPT. +# +ifcapable !direct_read { +do_test pager1-18.1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(a_string(500), a_string(200)); + INSERT INTO t1 SELECT a_string(500), a_string(200) FROM t1; + INSERT INTO t1 SELECT a_string(500), a_string(200) FROM t1; + INSERT INTO t1 SELECT a_string(500), a_string(200) FROM t1; + INSERT INTO t1 SELECT a_string(500), a_string(200) FROM t1; + INSERT INTO t1 SELECT a_string(500), a_string(200) FROM t1; + INSERT INTO t1 SELECT a_string(500), a_string(200) FROM t1; + INSERT INTO t1 SELECT a_string(500), a_string(200) FROM t1; + } +} {} +do_test pager1-18.2 { + set root [db one "SELECT rootpage FROM sqlite_master"] + set lockingpage [expr (0x10000/1024) + 1] + execsql { + PRAGMA writable_schema = 1; + UPDATE sqlite_master SET rootpage = $lockingpage; + } + sqlite3 db2 test.db + catchsql { SELECT count(*) FROM t1 } db2 +} {1 {database disk image is malformed}} +db2 close +do_test pager1-18.3.1 { + execsql { + CREATE TABLE t2(x); + INSERT INTO t2 VALUES(a_string(5000)); + } + set pgno [expr ([file size test.db] / 1024)-2] + hexio_write test.db [expr ($pgno-1)*1024] 00000000 + sqlite3 db2 test.db + # even though x is malformed, because typeof() does + # not load the content of x, the error is not noticed. + catchsql { SELECT typeof(x) FROM t2 } db2 +} {0 text} +do_test pager1-18.3.2 { + # in this case, the value of x is loaded and so the error is + # detected + catchsql { SELECT length(x||'') FROM t2 } db2 +} {1 {database disk image is malformed}} +db2 close +do_test pager1-18.3.3 { + execsql { + DELETE FROM t2; + INSERT INTO t2 VALUES(randomblob(5000)); + } + set pgno [expr ([file size test.db] / 1024)-2] + hexio_write test.db [expr ($pgno-1)*1024] 00000000 + sqlite3 db2 test.db + # even though x is malformed, because length() and typeof() do + # not load the content of x, the error is not noticed. + catchsql { SELECT length(x), typeof(x) FROM t2 } db2 +} {0 {5000 blob}} +do_test pager1-18.3.4 { + # in this case, the value of x is loaded and so the error is + # detected + catchsql { SELECT length(x||'') FROM t2 } db2 +} {1 {database disk image is malformed}} +db2 close +do_test pager1-18.4 { + hexio_write test.db [expr ($pgno-1)*1024] 90000000 + sqlite3 db2 test.db + catchsql { SELECT length(x||'') FROM t2 } db2 +} {1 {database disk image is malformed}} +db2 close +do_test pager1-18.5 { + sqlite3 db "" + execsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + PRAGMA writable_schema = 1; + UPDATE sqlite_master SET rootpage=5 WHERE tbl_name = 't1'; + PRAGMA writable_schema = 0; + ALTER TABLE t1 RENAME TO x1; + } + catchsql { SELECT * FROM x1 } +} {1 {database disk image is malformed}} +db close + +do_test pager1-18.6 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(a_string(800)); + INSERT INTO t1 VALUES(a_string(800)); + } + + set root [db one "SELECT rootpage FROM sqlite_master"] + db close + + hexio_write test.db [expr ($root-1)*1024 + 8] 00000000 + sqlite3 db test.db + catchsql { SELECT length(x) FROM t1 } +} {1 {database disk image is malformed}} +} + +do_test pager1-19.1 { + sqlite3 db "" + db func a_string a_string + execsql { + PRAGMA page_size = 512; + PRAGMA auto_vacuum = 1; + CREATE TABLE t1(aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am, an, + ba, bb, bc, bd, be, bf, bg, bh, bi, bj, bk, bl, bm, bn, + ca, cb, cc, cd, ce, cf, cg, ch, ci, cj, ck, cl, cm, cn, + da, db, dc, dd, de, df, dg, dh, di, dj, dk, dl, dm, dn, + ea, eb, ec, ed, ee, ef, eg, eh, ei, ej, ek, el, em, en, + fa, fb, fc, fd, fe, ff, fg, fh, fi, fj, fk, fl, fm, fn, + ga, gb, gc, gd, ge, gf, gg, gh, gi, gj, gk, gl, gm, gn, + ha, hb, hc, hd, he, hf, hg, hh, hi, hj, hk, hl, hm, hn, + ia, ib, ic, id, ie, if, ig, ih, ii, ij, ik, il, im, ix, + ja, jb, jc, jd, je, jf, jg, jh, ji, jj, jk, jl, jm, jn, + ka, kb, kc, kd, ke, kf, kg, kh, ki, kj, kk, kl, km, kn, + la, lb, lc, ld, le, lf, lg, lh, li, lj, lk, ll, lm, ln, + ma, mb, mc, md, me, mf, mg, mh, mi, mj, mk, ml, mm, mn + ); + CREATE TABLE t2(aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am, an, + ba, bb, bc, bd, be, bf, bg, bh, bi, bj, bk, bl, bm, bn, + ca, cb, cc, cd, ce, cf, cg, ch, ci, cj, ck, cl, cm, cn, + da, db, dc, dd, de, df, dg, dh, di, dj, dk, dl, dm, dn, + ea, eb, ec, ed, ee, ef, eg, eh, ei, ej, ek, el, em, en, + fa, fb, fc, fd, fe, ff, fg, fh, fi, fj, fk, fl, fm, fn, + ga, gb, gc, gd, ge, gf, gg, gh, gi, gj, gk, gl, gm, gn, + ha, hb, hc, hd, he, hf, hg, hh, hi, hj, hk, hl, hm, hn, + ia, ib, ic, id, ie, if, ig, ih, ii, ij, ik, il, im, ix, + ja, jb, jc, jd, je, jf, jg, jh, ji, jj, jk, jl, jm, jn, + ka, kb, kc, kd, ke, kf, kg, kh, ki, kj, kk, kl, km, kn, + la, lb, lc, ld, le, lf, lg, lh, li, lj, lk, ll, lm, ln, + ma, mb, mc, md, me, mf, mg, mh, mi, mj, mk, ml, mm, mn + ); + INSERT INTO t1(aa) VALUES( a_string(100000) ); + INSERT INTO t2(aa) VALUES( a_string(100000) ); + VACUUM; + } +} {} + +#------------------------------------------------------------------------- +# Test a couple of special cases that come up while committing +# transactions: +# +# pager1-20.1.*: Committing an in-memory database transaction when the +# database has not been modified at all. +# +# pager1-20.2.*: As above, but with a normal db in exclusive-locking mode. +# +# pager1-20.3.*: Committing a transaction in WAL mode where the database has +# been modified, but all dirty pages have been flushed to +# disk before the commit. +# +do_test pager1-20.1.1 { + catch {db close} + sqlite3 db :memory: + execsql { + CREATE TABLE one(two, three); + INSERT INTO one VALUES('a', 'b'); + } +} {} +do_test pager1-20.1.2 { + execsql { + BEGIN EXCLUSIVE; + COMMIT; + } +} {} + +do_test pager1-20.2.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA locking_mode = exclusive; + PRAGMA journal_mode = persist; + CREATE TABLE one(two, three); + INSERT INTO one VALUES('a', 'b'); + } +} {exclusive persist} +do_test pager1-20.2.2 { + execsql { + BEGIN EXCLUSIVE; + COMMIT; + } +} {} + +ifcapable wal { + do_test pager1-20.3.1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA cache_size = 10; + PRAGMA journal_mode = wal; + BEGIN; + CREATE TABLE t1(x); + CREATE TABLE t2(y); + INSERT INTO t1 VALUES(a_string(800)); + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 2 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 4 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 8 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 16 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 32 */ + COMMIT; + } + } {wal} + do_test pager1-20.3.2 { + execsql { + BEGIN; + INSERT INTO t2 VALUES('xxxx'); + } + recursive_select 32 t1 + execsql COMMIT + } {} +} + +#------------------------------------------------------------------------- +# Test that a WAL database may not be opened if: +# +# pager1-21.1.*: The VFS has an iVersion less than 2, or +# pager1-21.2.*: The VFS does not provide xShmXXX() methods. +# +ifcapable wal { + do_test pager1-21.0 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE ko(c DEFAULT 'abc', b DEFAULT 'def'); + INSERT INTO ko DEFAULT VALUES; + } + } {wal} + do_test pager1-21.1 { + testvfs tv -noshm 1 + sqlite3 db2 test.db -vfs tv + catchsql { SELECT * FROM ko } db2 + } {1 {unable to open database file}} + db2 close + tv delete + do_test pager1-21.2 { + testvfs tv -iversion 1 + sqlite3 db2 test.db -vfs tv + catchsql { SELECT * FROM ko } db2 + } {1 {unable to open database file}} + db2 close + tv delete +} + +#------------------------------------------------------------------------- +# Test that a "PRAGMA wal_checkpoint": +# +# pager1-22.1.*: is a no-op on a non-WAL db, and +# pager1-22.2.*: does not cause xSync calls with a synchronous=off db. +# +ifcapable wal { + do_test pager1-22.1.1 { + faultsim_delete_and_reopen + execsql { + CREATE TABLE ko(c DEFAULT 'abc', b DEFAULT 'def'); + INSERT INTO ko DEFAULT VALUES; + } + execsql { PRAGMA wal_checkpoint } + } {0 -1 -1} + do_test pager1-22.2.1 { + testvfs tv -default 1 + tv filter xSync + tv script xSyncCb + proc xSyncCb {args} {incr ::synccount} + set ::synccount 0 + sqlite3 db test.db + execsql { + PRAGMA synchronous = off; + PRAGMA journal_mode = WAL; + INSERT INTO ko DEFAULT VALUES; + } + execsql { PRAGMA wal_checkpoint } + set synccount + } {0} + db close + tv delete +} + +#------------------------------------------------------------------------- +# Tests for changing journal mode. +# +# pager1-23.1.*: Test that when changing from PERSIST to DELETE mode, +# the journal file is deleted. +# +# pager1-23.2.*: Same test as above, but while a shared lock is held +# on the database file. +# +# pager1-23.3.*: Same test as above, but while a reserved lock is held +# on the database file. +# +# pager1-23.4.*: And, for fun, while holding an exclusive lock. +# +# pager1-23.5.*: Try to set various different journal modes with an +# in-memory database (only MEMORY and OFF should work). +# +# pager1-23.6.*: Try to set locking_mode=normal on an in-memory database +# (doesn't work - in-memory databases always use +# locking_mode=exclusive). +# +do_test pager1-23.1.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = PERSIST; + CREATE TABLE t1(a, b); + } + file exists test.db-journal +} {1} +do_test pager1-23.1.2 { + execsql { PRAGMA journal_mode = DELETE } + file exists test.db-journal +} {0} + +do_test pager1-23.2.1 { + execsql { + PRAGMA journal_mode = PERSIST; + INSERT INTO t1 VALUES('Canberra', 'ACT'); + } + db eval { SELECT * FROM t1 } { + db eval { PRAGMA journal_mode = DELETE } + } + execsql { PRAGMA journal_mode } +} {delete} +do_test pager1-23.2.2 { + file exists test.db-journal +} {0} + +do_test pager1-23.3.1 { + execsql { + PRAGMA journal_mode = PERSIST; + INSERT INTO t1 VALUES('Darwin', 'NT'); + BEGIN IMMEDIATE; + } + db eval { PRAGMA journal_mode = DELETE } + execsql { PRAGMA journal_mode } +} {delete} +do_test pager1-23.3.2 { + file exists test.db-journal +} {0} +do_test pager1-23.3.3 { + execsql COMMIT +} {} + +do_test pager1-23.4.1 { + execsql { + PRAGMA journal_mode = PERSIST; + INSERT INTO t1 VALUES('Adelaide', 'SA'); + BEGIN EXCLUSIVE; + } + db eval { PRAGMA journal_mode = DELETE } + execsql { PRAGMA journal_mode } +} {delete} +do_test pager1-23.4.2 { + file exists test.db-journal +} {0} +do_test pager1-23.4.3 { + execsql COMMIT +} {} + +do_test pager1-23.5.1 { + faultsim_delete_and_reopen + sqlite3 db :memory: +} {} +foreach {tn mode possible} { + 2 off 1 + 3 memory 1 + 4 persist 0 + 5 delete 0 + 6 wal 0 + 7 truncate 0 +} { + do_test pager1-23.5.$tn.1 { + execsql "PRAGMA journal_mode = off" + execsql "PRAGMA journal_mode = $mode" + } [if $possible {list $mode} {list off}] + do_test pager1-23.5.$tn.2 { + execsql "PRAGMA journal_mode = memory" + execsql "PRAGMA journal_mode = $mode" + } [if $possible {list $mode} {list memory}] +} +do_test pager1-23.6.1 { + execsql {PRAGMA locking_mode = normal} +} {exclusive} +do_test pager1-23.6.2 { + execsql {PRAGMA locking_mode = exclusive} +} {exclusive} +do_test pager1-23.6.3 { + execsql {PRAGMA locking_mode} +} {exclusive} +do_test pager1-23.6.4 { + execsql {PRAGMA main.locking_mode} +} {exclusive} + +#------------------------------------------------------------------------- +# +do_test pager1-24.1.1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA cache_size = 10; + PRAGMA auto_vacuum = FULL; + CREATE TABLE x1(x, y, z, PRIMARY KEY(y, z)); + CREATE TABLE x2(x, y, z, PRIMARY KEY(y, z)); + INSERT INTO x2 VALUES(a_string(400), a_string(500), a_string(600)); + INSERT INTO x2 SELECT a_string(600), a_string(400), a_string(500) FROM x2; + INSERT INTO x2 SELECT a_string(500), a_string(600), a_string(400) FROM x2; + INSERT INTO x2 SELECT a_string(400), a_string(500), a_string(600) FROM x2; + INSERT INTO x2 SELECT a_string(600), a_string(400), a_string(500) FROM x2; + INSERT INTO x2 SELECT a_string(500), a_string(600), a_string(400) FROM x2; + INSERT INTO x2 SELECT a_string(400), a_string(500), a_string(600) FROM x2; + INSERT INTO x1 SELECT * FROM x2; + } +} {} +do_test pager1-24.1.2 { + execsql { + BEGIN; + DELETE FROM x1 WHERE rowid<32; + } + recursive_select 64 x2 +} {} +do_test pager1-24.1.3 { + execsql { + UPDATE x1 SET z = a_string(300) WHERE rowid>40; + COMMIT; + PRAGMA integrity_check; + SELECT count(*) FROM x1; + } +} {ok 33} + +do_test pager1-24.1.4 { + execsql { + DELETE FROM x1; + INSERT INTO x1 SELECT * FROM x2; + BEGIN; + DELETE FROM x1 WHERE rowid<32; + UPDATE x1 SET z = a_string(299) WHERE rowid>40; + } + recursive_select 64 x2 {db eval COMMIT} + execsql { + PRAGMA integrity_check; + SELECT count(*) FROM x1; + } +} {ok 33} + +do_test pager1-24.1.5 { + execsql { + DELETE FROM x1; + INSERT INTO x1 SELECT * FROM x2; + } + recursive_select 64 x2 { db eval {CREATE TABLE x3(x, y, z)} } + execsql { SELECT * FROM x3 } +} {} + +#------------------------------------------------------------------------- +# +do_test pager1-25-1 { + faultsim_delete_and_reopen + execsql { + BEGIN; + SAVEPOINT abc; + CREATE TABLE t1(a, b); + ROLLBACK TO abc; + COMMIT; + } + db close +} {} +do_test pager1-25-2 { + faultsim_delete_and_reopen + execsql { + SAVEPOINT abc; + CREATE TABLE t1(a, b); + ROLLBACK TO abc; + COMMIT; + } + db close +} {} + +#------------------------------------------------------------------------- +# Sector-size tests. +# +do_test pager1-26.1 { + testvfs tv -default 1 + tv sectorsize 4096 + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA page_size = 512; + CREATE TABLE tbl(a PRIMARY KEY, b UNIQUE); + BEGIN; + INSERT INTO tbl VALUES(a_string(25), a_string(600)); + INSERT INTO tbl SELECT a_string(25), a_string(600) FROM tbl; + INSERT INTO tbl SELECT a_string(25), a_string(600) FROM tbl; + INSERT INTO tbl SELECT a_string(25), a_string(600) FROM tbl; + INSERT INTO tbl SELECT a_string(25), a_string(600) FROM tbl; + INSERT INTO tbl SELECT a_string(25), a_string(600) FROM tbl; + INSERT INTO tbl SELECT a_string(25), a_string(600) FROM tbl; + INSERT INTO tbl SELECT a_string(25), a_string(600) FROM tbl; + COMMIT; + } +} {} +do_execsql_test pager1-26.1 { + UPDATE tbl SET b = a_string(550); +} {} +db close +tv delete + +#------------------------------------------------------------------------- +# +do_test pager1.27.1 { + faultsim_delete_and_reopen + sqlite3_pager_refcounts db + execsql { + BEGIN; + CREATE TABLE t1(a, b); + } + sqlite3_pager_refcounts db + execsql COMMIT +} {} + +#------------------------------------------------------------------------- +# Test that attempting to open a write-transaction with +# locking_mode=exclusive in WAL mode fails if there are other clients on +# the same database. +# +catch { db close } +ifcapable wal { + do_multiclient_test tn { + do_test pager1-28.$tn.1 { + sql1 { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('a', 'b'); + } + } {wal} + do_test pager1-28.$tn.2 { sql2 { SELECT * FROM t1 } } {a b} + + do_test pager1-28.$tn.3 { sql1 { PRAGMA locking_mode=exclusive } } {exclusive} + do_test pager1-28.$tn.4 { + csql1 { BEGIN; INSERT INTO t1 VALUES('c', 'd'); } + } {1 {database is locked}} + code2 { db2 close ; sqlite3 db2 test.db } + do_test pager1-28.$tn.4 { + sql1 { INSERT INTO t1 VALUES('c', 'd'); COMMIT } + } {} + } +} + +#------------------------------------------------------------------------- +# Normally, when changing from journal_mode=PERSIST to DELETE the pager +# attempts to delete the journal file. However, if it cannot obtain a +# RESERVED lock on the database file, this step is skipped. +# +do_multiclient_test tn { + do_test pager1-28.$tn.1 { + sql1 { + PRAGMA journal_mode = PERSIST; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('a', 'b'); + } + } {persist} + do_test pager1-28.$tn.2 { file exists test.db-journal } 1 + do_test pager1-28.$tn.3 { sql1 { PRAGMA journal_mode = DELETE } } delete + do_test pager1-28.$tn.4 { file exists test.db-journal } 0 + + do_test pager1-28.$tn.5 { + sql1 { + PRAGMA journal_mode = PERSIST; + INSERT INTO t1 VALUES('c', 'd'); + } + } {persist} + do_test pager1-28.$tn.6 { file exists test.db-journal } 1 + do_test pager1-28.$tn.7 { + sql2 { BEGIN; INSERT INTO t1 VALUES('e', 'f'); } + } {} + do_test pager1-28.$tn.8 { file exists test.db-journal } 1 + do_test pager1-28.$tn.9 { sql1 { PRAGMA journal_mode = DELETE } } delete + do_test pager1-28.$tn.10 { file exists test.db-journal } 1 + + do_test pager1-28.$tn.11 { sql2 COMMIT } {} + do_test pager1-28.$tn.12 { file exists test.db-journal } 0 + + do_test pager1-28-$tn.13 { + code1 { set channel [db incrblob -readonly t1 a 2] } + sql1 { + PRAGMA journal_mode = PERSIST; + INSERT INTO t1 VALUES('g', 'h'); + } + } {persist} + do_test pager1-28.$tn.14 { file exists test.db-journal } 1 + do_test pager1-28.$tn.15 { + sql2 { BEGIN; INSERT INTO t1 VALUES('e', 'f'); } + } {} + do_test pager1-28.$tn.16 { sql1 { PRAGMA journal_mode = DELETE } } delete + do_test pager1-28.$tn.17 { file exists test.db-journal } 1 + + do_test pager1-28.$tn.17 { csql2 { COMMIT } } {1 {database is locked}} + do_test pager1-28-$tn.18 { code1 { read $channel } } c + do_test pager1-28-$tn.19 { code1 { close $channel } } {} + do_test pager1-28.$tn.20 { sql2 { COMMIT } } {} +} + +do_test pager1-29.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = full; + PRAGMA locking_mode=exclusive; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } + file size test.db +} [expr 1024*3] +do_test pager1-29.2 { + execsql { + PRAGMA page_size = 4096; + VACUUM; + } + file size test.db +} [expr 4096*3] + +#------------------------------------------------------------------------- +# Test that if an empty database file (size 0 bytes) is opened in +# exclusive-locking mode, any journal file is deleted from the file-system +# without being rolled back. And that the RESERVED lock obtained while +# doing this is not released. +# +do_test pager1-30.1 { + db close + delete_file test.db + delete_file test.db-journal + set fd [open test.db-journal w] + seek $fd [expr 512+1032*2] + puts -nonewline $fd x + close $fd + + sqlite3 db test.db + execsql { + PRAGMA locking_mode=EXCLUSIVE; + SELECT count(*) FROM sqlite_master; + PRAGMA lock_status; + } +} {exclusive 0 main reserved temp closed} + +#------------------------------------------------------------------------- +# Test that if the "page-size" field in a journal-header is 0, the journal +# file can still be rolled back. This is required for backward compatibility - +# versions of SQLite prior to 3.5.8 always set this field to zero. +# +if {$tcl_platform(platform)=="unix"} { +do_test pager1-31.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA cache_size = 10; + PRAGMA page_size = 1024; + CREATE TABLE t1(x, y, UNIQUE(x, y)); + INSERT INTO t1 VALUES(randomblob(1500), randomblob(1500)); + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + INSERT INTO t1 SELECT randomblob(1500), randomblob(1500) FROM t1; + BEGIN; + UPDATE t1 SET y = randomblob(1499); + } + copy_file test.db test.db2 + copy_file test.db-journal test.db2-journal + + hexio_write test.db2-journal 24 00000000 + sqlite3 db2 test.db2 + execsql { PRAGMA integrity_check } db2 +} {ok} +} + +#------------------------------------------------------------------------- +# Test that a database file can be "pre-hinted" to a certain size and that +# subsequent spilling of the pager cache does not result in the database +# file being shrunk. +# +catch {db close} +forcedelete test.db + +do_test pager1-32.1 { + sqlite3 db test.db + execsql { + CREATE TABLE t1(x, y); + } + db close + sqlite3 db test.db + execsql { + BEGIN; + INSERT INTO t1 VALUES(1, randomblob(10000)); + } + file_control_chunksize_test db main 1024 + file_control_sizehint_test db main 20971520; # 20MB + execsql { + PRAGMA cache_size = 10; + INSERT INTO t1 VALUES(1, randomblob(10000)); + INSERT INTO t1 VALUES(2, randomblob(10000)); + INSERT INTO t1 SELECT x+2, randomblob(10000) from t1; + INSERT INTO t1 SELECT x+4, randomblob(10000) from t1; + INSERT INTO t1 SELECT x+8, randomblob(10000) from t1; + INSERT INTO t1 SELECT x+16, randomblob(10000) from t1; + SELECT count(*) FROM t1; + COMMIT; + } + db close + file size test.db +} {20971520} + +# Cleanup 20MB file left by the previous test. +forcedelete test.db + +#------------------------------------------------------------------------- +# Test that if a transaction is committed in journal_mode=DELETE mode, +# and the call to unlink() returns an ENOENT error, the COMMIT does not +# succeed. +# +if {$::tcl_platform(platform)=="unix"} { + do_test pager1-33.1 { + sqlite3 db test.db + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('one'); + INSERT INTO t1 VALUES('two'); + BEGIN; + INSERT INTO t1 VALUES('three'); + INSERT INTO t1 VALUES('four'); + } + forcedelete bak-journal + file rename test.db-journal bak-journal + + catchsql COMMIT + } {1 {disk I/O error}} + + do_test pager1-33.2 { + file rename bak-journal test.db-journal + execsql { SELECT * FROM t1 } + } {one two} +} + +#------------------------------------------------------------------------- +# Test that appending pages to the database file then moving those pages +# to the free-list before the transaction is committed does not cause +# an error. +# +foreach {tn pragma strsize} { + 1 { PRAGMA mmap_size = 0 } 2400 + 2 { } 2400 + 3 { PRAGMA mmap_size = 0 } 4400 + 4 { } 4400 +} { + reset_db + db func a_string a_string + db eval $pragma + do_execsql_test 34.$tn.1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } + do_execsql_test 34.$tn.2 { + BEGIN; + INSERT INTO t1 VALUES(2, a_string($strsize)); + DELETE FROM t1 WHERE oid=2; + COMMIT; + PRAGMA integrity_check; + } {ok} +} + +#------------------------------------------------------------------------- +# +reset_db +do_test 35 { + sqlite3 db test.db + + execsql { + CREATE TABLE t1(x, y); + PRAGMA journal_mode = WAL; + INSERT INTO t1 VALUES(1, 2); + } + + execsql { + BEGIN; + CREATE TABLE t2(a, b); + } + + hexio_write test.db-shm [expr 16*1024] [string repeat 0055 8192] + catchsql ROLLBACK +} {0 {}} + +do_multiclient_test tn { + sql1 { + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(1, 2); + } + + do_test 36.$tn.1 { + sql2 { PRAGMA max_page_count = 2 } + list [catch { sql2 { CREATE TABLE t2(x) } } msg] $msg + } {1 {database or disk is full}} + + sql1 { PRAGMA checkpoint_fullfsync = 1 } + sql1 { CREATE TABLE t2(x) } + + do_test 36.$tn.2 { + sql2 { INSERT INTO t2 VALUES('xyz') } + list [catch { sql2 { CREATE TABLE t3(x) } } msg] $msg + } {1 {database or disk is full}} +} + +forcedelete test1 test2 +foreach {tn uri} { + 1 {file:?mode=memory&cache=shared} + 2 {file:one?mode=memory&cache=shared} + 3 {file:test1?cache=shared} + 4 {file:test2?another=parameter&yet=anotherone} +} { + do_test 37.$tn { + catch { db close } + sqlite3_shutdown + sqlite3_config_uri 1 + sqlite3 db $uri + + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + SELECT * FROM t1; + } + } {1} + + do_execsql_test 37.$tn.2 { + VACUUM; + SELECT * FROM t1; + } {1} + + db close + sqlite3_shutdown + sqlite3_config_uri 0 +} + +do_test 38.1 { + catch { db close } + forcedelete test.db + set fd [open test.db w] + puts $fd "hello world" + close $fd + sqlite3 db test.db + catchsql { CREATE TABLE t1(x) } +} {1 {file is encrypted or is not a database}} +do_test 38.2 { + catch { db close } + forcedelete test.db +} {} + +do_test 39.1 { + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum = 1; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('xxx'); + INSERT INTO t1 VALUES('two'); + INSERT INTO t1 VALUES(randomblob(400)); + INSERT INTO t1 VALUES(randomblob(400)); + INSERT INTO t1 VALUES(randomblob(400)); + INSERT INTO t1 VALUES(randomblob(400)); + BEGIN; + UPDATE t1 SET x = 'one' WHERE rowid=1; + } + set ::stmt [sqlite3_prepare db "SELECT * FROM t1 ORDER BY rowid" -1 dummy] + sqlite3_step $::stmt + sqlite3_column_text $::stmt 0 +} {one} +do_test 39.2 { + execsql { CREATE TABLE t2(x) } + sqlite3_step $::stmt + sqlite3_column_text $::stmt 0 +} {two} +do_test 39.3 { + sqlite3_finalize $::stmt + execsql COMMIT +} {} + +do_execsql_test 39.4 { + PRAGMA auto_vacuum = 2; + CREATE TABLE t3(x); + CREATE TABLE t4(x); + + DROP TABLE t2; + DROP TABLE t3; + DROP TABLE t4; +} +do_test 39.5 { + db close + sqlite3 db test.db + execsql { + PRAGMA cache_size = 1; + PRAGMA incremental_vacuum; + PRAGMA integrity_check; + } +} {ok} + +do_test 40.1 { + reset_db + execsql { + PRAGMA auto_vacuum = 1; + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(randomblob(1200)); + PRAGMA page_count; + } +} {6} +do_test 40.2 { + execsql { + INSERT INTO t1 VALUES(randomblob(1200)); + INSERT INTO t1 VALUES(randomblob(1200)); + INSERT INTO t1 VALUES(randomblob(1200)); + } +} {} +do_test 40.3 { + db close + sqlite3 db test.db + execsql { + PRAGMA cache_size = 1; + CREATE TABLE t2(x); + PRAGMA integrity_check; + } +} {ok} + +do_test 41.1 { + reset_db + execsql { + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(randomblob(200)); + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200) FROM t1; + } +} {} +do_test 41.2 { + testvfs tv -default 1 + tv sectorsize 16384; + tv devchar [list] + db close + sqlite3 db test.db + execsql { + PRAGMA cache_size = 1; + DELETE FROM t1 WHERE rowid%4; + PRAGMA integrity_check; + } +} {ok} +db close +tv delete + +set pending_prev [sqlite3_test_control_pending_byte 0x1000000] +do_test 42.1 { + reset_db + execsql { + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(randomblob(200), randomblob(200)); + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + } + db close + sqlite3_test_control_pending_byte 0x0010000 + sqlite3 db test.db + db eval { PRAGMA mmap_size = 0 } + catchsql { SELECT sum(length(y)) FROM t1 } +} {1 {database disk image is malformed}} +do_test 42.2 { + reset_db + execsql { + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(randomblob(200), randomblob(200)); + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + } + db close + + testvfs tv -default 1 + tv sectorsize 16384; + tv devchar [list] + sqlite3 db test.db -vfs tv + execsql { UPDATE t1 SET x = randomblob(200) } +} {} +db close +tv delete +sqlite3_test_control_pending_byte $pending_prev + +do_test 43.1 { + reset_db + execsql { + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(1, 2); + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES(1, 2); + CREATE TABLE t3(x, y); + INSERT INTO t3 VALUES(1, 2); + } + db close + sqlite3 db test.db + + db eval { PRAGMA mmap_size = 0 } + db eval { SELECT * FROM t1 } + sqlite3_db_status db CACHE_MISS 0 +} {0 2 0} + +do_test 43.2 { + db eval { SELECT * FROM t2 } + sqlite3_db_status db CACHE_MISS 1 +} {0 3 0} + +do_test 43.3 { + db eval { SELECT * FROM t3 } + sqlite3_db_status db CACHE_MISS 0 +} {0 1 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/pager2.test b/components/external/SQLite-3.8.1/test/pager2.test new file mode 100644 index 0000000000000000000000000000000000000000..0e2b33b8339562fb2c7ccf4339123296e464c6c8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pager2.test @@ -0,0 +1,168 @@ +# 2010 June 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +set otn 0 +testvfs tv -default 1 +foreach code [list { + set s 512 +} { + set s 1024 + set sql { PRAGMA journal_mode = memory } +} { + set s 1024 + set sql { + PRAGMA journal_mode = memory; + PRAGMA locking_mode = exclusive; + } +} { + set s 2048 + tv devchar safe_append +} { + set s 4096 +} { + set s 4096 + set sql { PRAGMA journal_mode = WAL } +} { + set s 4096 + set sql { PRAGMA auto_vacuum = 1 } +} { + set s 8192 + set sql { PRAGMA synchronous = off } +}] { + + incr otn + set sql "" + tv devchar {} + eval $code + tv sectorsize $s + + do_test pager2-1.$otn.0 { + faultsim_delete_and_reopen + execsql $sql + execsql { + PRAGMA cache_size = 10; + CREATE TABLE t1(i INTEGER PRIMARY KEY, j blob); + } + } {} + + set tn 0 + set lowpoint 0 + foreach x { + 100 x 0 100 + x + 70 22 96 59 96 50 22 56 21 16 37 64 43 40 0 38 22 38 55 0 6 + 43 62 32 93 54 18 13 29 45 66 29 25 61 31 53 82 75 25 96 86 10 69 + 2 29 6 60 80 95 42 82 85 50 68 96 90 39 78 69 87 97 48 74 65 43 + x + 86 34 26 50 41 85 58 44 89 22 6 51 45 46 58 32 97 6 1 12 32 2 + 69 39 48 71 33 31 5 58 90 43 24 54 12 9 18 57 4 38 91 42 27 45 + 50 38 56 29 10 0 26 37 83 1 78 15 47 30 75 62 46 29 68 5 30 4 + 27 96 33 95 79 75 56 10 29 70 32 75 52 88 5 36 50 57 46 63 88 65 + x + 44 95 64 20 24 35 69 61 61 2 35 92 42 46 23 98 78 1 38 72 79 35 + 94 37 13 59 5 93 27 58 80 75 58 7 67 13 10 76 84 4 8 70 81 45 + 8 41 98 5 60 26 92 29 91 90 2 62 40 4 5 22 80 15 83 76 52 88 + 29 5 68 73 72 7 54 17 89 32 81 94 51 28 53 71 8 42 54 59 70 79 + x + } { + incr tn + set now [db one {SELECT count(i) FROM t1}] + if {$x == "x"} { + execsql { COMMIT ; BEGIN } + set lowpoint $now + do_test pager2.1.$otn.$tn { + sqlite3 db2 test.db + execsql { + SELECT COALESCE(max(i), 0) FROM t1; + PRAGMA integrity_check; + } + } [list $lowpoint ok] + db2 close + } else { + if {$now > $x } { + if { $x>=$lowpoint } { + execsql "ROLLBACK TO sp_$x" + } else { + execsql "DELETE FROM t1 WHERE i>$x" + set lowpoint $x + } + } elseif {$now < $x} { + for {set k $now} {$k < $x} {incr k} { + execsql "SAVEPOINT sp_$k" + execsql { INSERT INTO t1(j) VALUES(randomblob(1500)) } + } + } + do_execsql_test pager2.1.$otn.$tn { + SELECT COALESCE(max(i), 0) FROM t1; + PRAGMA integrity_check; + } [list $x ok] + } + } +} +db close +tv delete + + +#------------------------------------------------------------------------- +# pager2-2.1: Test a ROLLBACK with journal_mode=off. +# pager2-2.2: Test shrinking the database (auto-vacuum) with +# journal_mode=off +# +do_test pager2-2.1 { + faultsim_delete_and_reopen + execsql { + CREATE TABLE t1(a, b); + PRAGMA journal_mode = off; + BEGIN; + INSERT INTO t1 VALUES(1, 2); + ROLLBACK; + SELECT * FROM t1; + } +} {off} +do_test pager2-2.2 { + faultsim_delete_and_reopen + execsql { + PRAGMA auto_vacuum = incremental; + PRAGMA page_size = 1024; + PRAGMA journal_mode = off; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(zeroblob(5000), zeroblob(5000)); + DELETE FROM t1; + PRAGMA incremental_vacuum; + } + file size test.db +} {3072} + +#------------------------------------------------------------------------- +# Test that shared in-memory databases seem to work. +# +db close +do_test pager2-3.1 { + forcedelete test.db + sqlite3_shutdown + sqlite3_config_uri 1 + + sqlite3 db1 {file:test.db?mode=memory&cache=shared} + sqlite3 db2 {file:test.db?mode=memory&cache=shared} + sqlite3 db3 test.db + + db1 eval { CREATE TABLE t1(a, b) } + db2 eval { INSERT INTO t1 VALUES(1, 2) } + list [catch { db3 eval { INSERT INTO t1 VALUES(3, 4) } } msg] $msg +} {1 {no such table: t1}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/pager3.test b/components/external/SQLite-3.8.1/test/pager3.test new file mode 100644 index 0000000000000000000000000000000000000000..23435a79b759ec999cf56ce1f28f24a321154645 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pager3.test @@ -0,0 +1,33 @@ +# 2010 June 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl +source $testdir/wal_common.tcl + + +foreach {tn sql res j} { + 1 "PRAGMA journal_mode = DELETE" delete 0 + 2 "CREATE TABLE t1(a, b)" {} 0 + 3 "PRAGMA locking_mode=EXCLUSIVE" {exclusive} 0 + 4 "INSERT INTO t1 VALUES(1, 2)" {} 1 + 5 "PRAGMA locking_mode=NORMAL" {normal} 1 + 6 "SELECT * FROM t1" {1 2} 0 +} { + do_execsql_test pager3-1.$tn.1 $sql $res + do_test pager3-1.$tn.2 { file exists test.db-journal } $j +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/pagerfault.test b/components/external/SQLite-3.8.1/test/pagerfault.test new file mode 100644 index 0000000000000000000000000000000000000000..796f531c37b7179f92a3873f7690f76cbc2a165c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pagerfault.test @@ -0,0 +1,1548 @@ +# 2010 June 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +if {[permutation] == "inmemory_journal"} { + finish_test + return +} + +if {$::tcl_platform(platform)=="windows"} { + finish_test + return +} + +set a_string_counter 1 +proc a_string {n} { + global a_string_counter + incr a_string_counter + string range [string repeat "${a_string_counter}." $n] 1 $n +} +db func a_string a_string + +#------------------------------------------------------------------------- +# Test fault-injection while rolling back a hot-journal file. +# +do_test pagerfault-1-pre1 { + execsql { + PRAGMA journal_mode = DELETE; + PRAGMA cache_size = 10; + CREATE TABLE t1(a UNIQUE, b UNIQUE); + INSERT INTO t1 VALUES(a_string(200), a_string(300)); + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + BEGIN; + INSERT INTO t1 SELECT a_string(201), a_string(301) FROM t1; + INSERT INTO t1 SELECT a_string(202), a_string(302) FROM t1; + INSERT INTO t1 SELECT a_string(203), a_string(303) FROM t1; + INSERT INTO t1 SELECT a_string(204), a_string(304) FROM t1; + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-1 -prep { + faultsim_restore_and_reopen +} -body { + execsql { SELECT count(*) FROM t1 } +} -test { + faultsim_test_result {0 4} + faultsim_integrity_check + if {[db one { SELECT count(*) FROM t1 }] != 4} { + error "Database content appears incorrect" + } +} + +#------------------------------------------------------------------------- +# Test fault-injection while rolling back a hot-journal file with a +# page-size different from the current value stored on page 1 of the +# database file. +# +do_test pagerfault-2-pre1 { + testvfs tv -default 1 + tv filter xSync + tv script xSyncCb + proc xSyncCb {filename args} { + if {[string match *journal filename]==0} faultsim_save + } + faultsim_delete_and_reopen + execsql { + PRAGMA page_size = 4096; + BEGIN; + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES('o', 't', 't'); + INSERT INTO abc VALUES('f', 'f', 's'); + INSERT INTO abc SELECT * FROM abc; -- 4 + INSERT INTO abc SELECT * FROM abc; -- 8 + INSERT INTO abc SELECT * FROM abc; -- 16 + INSERT INTO abc SELECT * FROM abc; -- 32 + INSERT INTO abc SELECT * FROM abc; -- 64 + INSERT INTO abc SELECT * FROM abc; -- 128 + INSERT INTO abc SELECT * FROM abc; -- 256 + COMMIT; + PRAGMA page_size = 1024; + VACUUM; + } + db close + tv delete +} {} +do_faultsim_test pagerfault-2 -prep { + faultsim_restore_and_reopen +} -body { + execsql { SELECT * FROM abc } +} -test { + set answer [split [string repeat "ottffs" 128] ""] + faultsim_test_result [list 0 $answer] + faultsim_integrity_check + set res [db eval { SELECT * FROM abc }] + if {$res != $answer} { error "Database content appears incorrect ($res)" } +} + +#------------------------------------------------------------------------- +# Test fault-injection while rolling back hot-journals that were created +# as part of a multi-file transaction. +# +do_test pagerfault-3-pre1 { + testvfs tstvfs -default 1 + tstvfs filter xDelete + tstvfs script xDeleteCallback + + proc xDeleteCallback {method file args} { + set file [file tail $file] + if { [string match *mj* $file] } { faultsim_save } + } + + faultsim_delete_and_reopen + db func a_string a_string + + execsql { + ATTACH 'test.db2' AS aux; + PRAGMA journal_mode = DELETE; + PRAGMA main.cache_size = 10; + PRAGMA aux.cache_size = 10; + + CREATE TABLE t1(a UNIQUE, b UNIQUE); + CREATE TABLE aux.t2(a UNIQUE, b UNIQUE); + INSERT INTO t1 VALUES(a_string(200), a_string(300)); + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t2 SELECT * FROM t1; + + BEGIN; + INSERT INTO t1 SELECT a_string(201), a_string(301) FROM t1; + INSERT INTO t1 SELECT a_string(202), a_string(302) FROM t1; + INSERT INTO t1 SELECT a_string(203), a_string(303) FROM t1; + INSERT INTO t1 SELECT a_string(204), a_string(304) FROM t1; + REPLACE INTO t2 SELECT * FROM t1; + COMMIT; + } + + db close + tstvfs delete +} {} +do_faultsim_test pagerfault-3 -prep { + faultsim_restore_and_reopen +} -body { + execsql { + ATTACH 'test.db2' AS aux; + SELECT count(*) FROM t2; + SELECT count(*) FROM t1; + } +} -test { + faultsim_test_result {0 {4 4}} {1 {unable to open database: test.db2}} + faultsim_integrity_check + catchsql { ATTACH 'test.db2' AS aux } + if {[db one { SELECT count(*) FROM t1 }] != 4 + || [db one { SELECT count(*) FROM t2 }] != 4 + } { + error "Database content appears incorrect" + } +} + +#------------------------------------------------------------------------- +# Test fault-injection as part of a vanilla, no-transaction, INSERT +# statement. +# +do_faultsim_test pagerfault-4 -prep { + faultsim_delete_and_reopen +} -body { + execsql { + CREATE TABLE x(y); + INSERT INTO x VALUES('z'); + SELECT * FROM x; + } +} -test { + faultsim_test_result {0 z} + faultsim_integrity_check +} + +#------------------------------------------------------------------------- +# Test fault-injection as part of a commit when using journal_mode=PERSIST. +# Three different cases: +# +# pagerfault-5.1: With no journal_size_limit configured. +# pagerfault-5.2: With a journal_size_limit configured. +# pagerfault-5.4: Multi-file transaction. One connection has a +# journal_size_limit of 0, the other has no limit. +# +do_test pagerfault-5-pre1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + CREATE TABLE t1(a UNIQUE, b UNIQUE); + INSERT INTO t1 VALUES(a_string(200), a_string(300)); + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-5.1 -prep { + faultsim_restore_and_reopen + db func a_string a_string + execsql { PRAGMA journal_mode = PERSIST } +} -body { + execsql { INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1 } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} +do_faultsim_test pagerfault-5.2 -prep { + faultsim_restore_and_reopen + db func a_string a_string + execsql { + PRAGMA journal_mode = PERSIST; + PRAGMA journal_size_limit = 2048; + } +} -body { + execsql { INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1 } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} +do_faultsim_test pagerfault-5.3 -faults oom-transient -prep { + faultsim_restore_and_reopen + db func a_string a_string + forcedelete test2.db test2.db-journal test2.db-wal + execsql { + PRAGMA journal_mode = PERSIST; + ATTACH 'test2.db' AS aux; + PRAGMA aux.journal_mode = PERSIST; + PRAGMA aux.journal_size_limit = 0; + } +} -body { + execsql { + BEGIN; + INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1; + CREATE TABLE aux.t2 AS SELECT * FROM t1; + COMMIT; + } +} -test { + faultsim_test_result {0 {}} + + catchsql { COMMIT } + catchsql { ROLLBACK } + + faultsim_integrity_check + set res "" + set rc [catch { set res [db one { PRAGMA aux.integrity_check }] }] + if {$rc!=0 || $res != "ok"} {error "integrity-check problem:$rc $res"} +} + +#------------------------------------------------------------------------- +# Test fault-injection as part of a commit when using +# journal_mode=TRUNCATE. +# +do_test pagerfault-6-pre1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + CREATE TABLE t1(a UNIQUE, b UNIQUE); + INSERT INTO t1 VALUES(a_string(200), a_string(300)); + } + faultsim_save_and_close +} {} + +do_faultsim_test pagerfault-6.1 -prep { + faultsim_restore_and_reopen + db func a_string a_string + execsql { PRAGMA journal_mode = TRUNCATE } +} -body { + execsql { INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1 } + execsql { INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1 } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + +# The unix vfs xAccess() method considers a file zero bytes in size to +# "not exist". This proc overrides that behaviour so that a zero length +# file is considered to exist. +# +proc xAccess {method filename op args} { + if {$op != "SQLITE_ACCESS_EXISTS"} { return "" } + return [file exists $filename] +} +do_faultsim_test pagerfault-6.2 -faults cantopen-* -prep { + shmfault filter xAccess + shmfault script xAccess + + faultsim_restore_and_reopen + db func a_string a_string + execsql { PRAGMA journal_mode = TRUNCATE } +} -body { + execsql { INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1 } + execsql { INSERT INTO t1 SELECT a_string(200), a_string(300) FROM t1 } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + +# The following was an attempt to get a bitvec malloc to fail. Didn't work. +# +# do_test pagerfault-6-pre1 { +# faultsim_delete_and_reopen +# execsql { +# CREATE TABLE t1(x, y, UNIQUE(x, y)); +# INSERT INTO t1 VALUES(1, randomblob(1501)); +# INSERT INTO t1 VALUES(2, randomblob(1502)); +# INSERT INTO t1 VALUES(3, randomblob(1503)); +# INSERT INTO t1 VALUES(4, randomblob(1504)); +# INSERT INTO t1 +# SELECT x, randomblob(1500+oid+(SELECT max(oid) FROM t1)) FROM t1; +# INSERT INTO t1 +# SELECT x, randomblob(1500+oid+(SELECT max(oid) FROM t1)) FROM t1; +# INSERT INTO t1 +# SELECT x, randomblob(1500+oid+(SELECT max(oid) FROM t1)) FROM t1; +# INSERT INTO t1 +# SELECT x, randomblob(1500+oid+(SELECT max(oid) FROM t1)) FROM t1; +# } +# faultsim_save_and_close +# } {} +# do_faultsim_test pagerfault-6 -prep { +# faultsim_restore_and_reopen +# } -body { +# execsql { +# BEGIN; +# UPDATE t1 SET x=x+4 WHERE x=1; +# SAVEPOINT one; +# UPDATE t1 SET x=x+4 WHERE x=2; +# SAVEPOINT three; +# UPDATE t1 SET x=x+4 WHERE x=3; +# SAVEPOINT four; +# UPDATE t1 SET x=x+4 WHERE x=4; +# RELEASE three; +# COMMIT; +# SELECT DISTINCT x FROM t1; +# } +# } -test { +# faultsim_test_result {0 {5 6 7 8}} +# faultsim_integrity_check +# } +# + +# This is designed to provoke a special case in the pager code: +# +# If an error (specifically, a FULL or IOERR error) occurs while writing a +# dirty page to the file-system in order to free up memory, the pager enters +# the "error state". An IO error causes SQLite to roll back the current +# transaction (exiting the error state). A FULL error, however, may only +# rollback the current statement. +# +# This block tests that nothing goes wrong if a FULL error occurs while +# writing a dirty page out to free memory from within a statement that has +# opened a statement transaction. +# +do_test pagerfault-7-pre1 { + faultsim_delete_and_reopen + execsql { + CREATE TABLE t2(a INTEGER PRIMARY KEY, b); + BEGIN; + INSERT INTO t2 VALUES(NULL, randomblob(1500)); + INSERT INTO t2 VALUES(NULL, randomblob(1500)); + INSERT INTO t2 SELECT NULL, randomblob(1500) FROM t2; -- 4 + INSERT INTO t2 SELECT NULL, randomblob(1500) FROM t2; -- 8 + INSERT INTO t2 SELECT NULL, randomblob(1500) FROM t2; -- 16 + INSERT INTO t2 SELECT NULL, randomblob(1500) FROM t2; -- 32 + INSERT INTO t2 SELECT NULL, randomblob(1500) FROM t2; -- 64 + COMMIT; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 SELECT * FROM t2; + DROP TABLE t2; + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-7 -prep { + faultsim_restore_and_reopen + execsql { + PRAGMA cache_size = 10; + BEGIN; + UPDATE t1 SET b = randomblob(1500); + } +} -body { + execsql { UPDATE t1 SET a = 65, b = randomblob(1500) WHERE (a+1)>200 } + execsql COMMIT +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + +do_test pagerfault-8-pre1 { + faultsim_delete_and_reopen + execsql { + PRAGMA auto_vacuum = 1; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + BEGIN; + INSERT INTO t1 VALUES(NULL, randomblob(1500)); + INSERT INTO t1 VALUES(NULL, randomblob(1500)); + INSERT INTO t1 SELECT NULL, randomblob(1500) FROM t1; -- 4 + INSERT INTO t1 SELECT NULL, randomblob(1500) FROM t1; -- 8 + INSERT INTO t1 SELECT NULL, randomblob(1500) FROM t1; -- 16 + INSERT INTO t1 SELECT NULL, randomblob(1500) FROM t1; -- 32 + INSERT INTO t1 SELECT NULL, randomblob(1500) FROM t1; -- 64 + COMMIT; + } + faultsim_save_and_close + set filesize [file size test.db] + set {} {} +} {} +do_test pagerfault-8-pre2 { + faultsim_restore_and_reopen + execsql { DELETE FROM t1 WHERE a>32 } + expr {[file size test.db] < $filesize} +} {1} +do_faultsim_test pagerfault-8 -prep { + faultsim_restore_and_reopen + execsql { + BEGIN; + DELETE FROM t1 WHERE a>32; + } +} -body { + execsql COMMIT +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + +#------------------------------------------------------------------------- +# This test case is specially designed so that during a savepoint +# rollback, a new cache entry must be allocated (see comments surrounding +# the call to sqlite3PagerAcquire() from within pager_playback_one_page() +# for details). Test the effects of injecting an OOM at this point. +# +do_test pagerfault-9-pre1 { + faultsim_delete_and_reopen + execsql { + PRAGMA auto_vacuum = incremental; + CREATE TABLE t1(x); + CREATE TABLE t2(y); + CREATE TABLE t3(z); + + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 VALUES(randomblob(900)); + DELETE FROM t1; + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-9.1 -prep { + faultsim_restore_and_reopen + execsql { + BEGIN; + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 VALUES(randomblob(900)); + DROP TABLE t3; + DROP TABLE t2; + SAVEPOINT abc; + PRAGMA incremental_vacuum; + } +} -body { + execsql { + ROLLBACK TO abc; + COMMIT; + PRAGMA freelist_count + } +} -test { + faultsim_test_result {0 2} + faultsim_integrity_check + + set sl [db one { SELECT COALESCE(sum(length(x)), 'null') FROM t1 }] + if {$sl!="null" && $sl!=1800} { + error "Content looks no good... ($sl)" + } +} + +#------------------------------------------------------------------------- +# Test fault injection with a temporary database file. +# +foreach v {a b} { + do_faultsim_test pagerfault-10$v -prep { + sqlite3 db "" + db func a_string a_string; + execsql { + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE xx(a, b, UNIQUE(a, b)); + INSERT INTO xx VALUES(a_string(200), a_string(200)); + INSERT INTO xx SELECT a_string(200), a_string(200) FROM xx; + INSERT INTO xx SELECT a_string(200), a_string(200) FROM xx; + INSERT INTO xx SELECT a_string(200), a_string(200) FROM xx; + INSERT INTO xx SELECT a_string(200), a_string(200) FROM xx; + COMMIT; + } + } -body { + execsql { UPDATE xx SET a = a_string(300) } + } -test { + faultsim_test_result {0 {}} + if {$::v == "b"} { execsql { PRAGMA journal_mode = TRUNCATE } } + faultsim_integrity_check + faultsim_integrity_check + } +} + +#------------------------------------------------------------------------- +# Test fault injection with transaction savepoints (savepoints created +# when a SAVEPOINT command is executed outside of any other savepoint +# or transaction context). +# +do_test pagerfault-9-pre1 { + faultsim_delete_and_reopen + db func a_string a_string; + execsql { + PRAGMA auto_vacuum = on; + CREATE TABLE t1(x UNIQUE); + CREATE TABLE t2(y UNIQUE); + CREATE TABLE t3(z UNIQUE); + BEGIN; + INSERT INTO t1 VALUES(a_string(202)); + INSERT INTO t2 VALUES(a_string(203)); + INSERT INTO t3 VALUES(a_string(204)); + INSERT INTO t1 SELECT a_string(202) FROM t1; + INSERT INTO t1 SELECT a_string(203) FROM t1; + INSERT INTO t1 SELECT a_string(204) FROM t1; + INSERT INTO t1 SELECT a_string(205) FROM t1; + INSERT INTO t2 SELECT a_string(length(x)) FROM t1; + INSERT INTO t3 SELECT a_string(length(x)) FROM t1; + COMMIT; + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-11 -prep { + faultsim_restore_and_reopen + execsql { PRAGMA cache_size = 10 } +} -body { + execsql { + SAVEPOINT trans; + UPDATE t2 SET y = y||'2'; + INSERT INTO t3 SELECT * FROM t2; + DELETE FROM t1; + ROLLBACK TO trans; + UPDATE t1 SET x = x||'3'; + INSERT INTO t2 SELECT * FROM t1; + DELETE FROM t3; + RELEASE trans; + } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + + +#------------------------------------------------------------------------- +# Test fault injection when writing to a database file that resides on +# a file-system with a sector-size larger than the database page-size. +# +do_test pagerfault-12-pre1 { + testvfs ss_layer -default 1 + ss_layer sectorsize 4096 + faultsim_delete_and_reopen + db func a_string a_string; + + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = PERSIST; + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE t1(x, y UNIQUE); + INSERT INTO t1 VALUES(a_string(333), a_string(444)); + INSERT INTO t1 SELECT a_string(333+rowid), a_string(444+rowid) FROM t1; + INSERT INTO t1 SELECT a_string(333+rowid), a_string(444+rowid) FROM t1; + INSERT INTO t1 SELECT a_string(333+rowid), a_string(444+rowid) FROM t1; + INSERT INTO t1 SELECT a_string(333+rowid), a_string(444+rowid) FROM t1; + INSERT INTO t1 SELECT a_string(44), a_string(55) FROM t1 LIMIT 13; + COMMIT; + } + faultsim_save_and_close +} {} + +do_faultsim_test pagerfault-12a -prep { + faultsim_restore_and_reopen + execsql { PRAGMA cache_size = 10 } + db func a_string a_string; +} -body { + execsql { + UPDATE t1 SET x = a_string(length(x)), y = a_string(length(y)); + } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + +do_test pagerfault-12-pre2 { + faultsim_restore_and_reopen + execsql { + CREATE TABLE t2 AS SELECT * FROM t1 LIMIT 10; + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-12b -prep { + faultsim_restore_and_reopen + db func a_string a_string; + execsql { SELECT * FROM t1 } +} -body { + set sql(1) { UPDATE t2 SET x = a_string(280) } + set sql(2) { UPDATE t1 SET x = a_string(280) WHERE rowid = 5 } + + db eval { SELECT rowid FROM t1 LIMIT 2 } { db eval $sql($rowid) } + +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + +catch { db close } +ss_layer delete + + +#------------------------------------------------------------------------- +# Test fault injection when SQLite opens a database where the size of the +# database file is zero bytes but the accompanying journal file is larger +# than that. In this scenario SQLite should delete the journal file +# without rolling it back, even if it is in all other respects a valid +# hot-journal file. +# +do_test pagerfault-13-pre1 { + faultsim_delete_and_reopen + db func a_string a_string; + execsql { + PRAGMA journal_mode = PERSIST; + BEGIN; + CREATE TABLE t1(x, y UNIQUE); + INSERT INTO t1 VALUES(a_string(333), a_string(444)); + COMMIT; + } + db close + forcedelete test.db + faultsim_save +} {} +do_faultsim_test pagerfault-13 -prep { + faultsim_restore_and_reopen +} -body { + execsql { CREATE TABLE xx(a, b) } +} -test { + faultsim_test_result {0 {}} +} + +#--------------------------------------------------------------------------- +# Test fault injection into a small backup operation. +# +do_test pagerfault-14-pre1 { + faultsim_delete_and_reopen + db func a_string a_string; + execsql { + PRAGMA journal_mode = PERSIST; + ATTACH 'test.db2' AS two; + BEGIN; + CREATE TABLE t1(x, y UNIQUE); + CREATE TABLE two.t2(x, y UNIQUE); + INSERT INTO t1 VALUES(a_string(333), a_string(444)); + INSERT INTO t2 VALUES(a_string(333), a_string(444)); + COMMIT; + } + faultsim_save_and_close +} {} + +do_faultsim_test pagerfault-14a -prep { + faultsim_restore_and_reopen +} -body { + if {[catch {db backup test.db2} msg]} { error [regsub {.*: } $msg {}] } +} -test { + faultsim_test_result {0 {}} {1 {}} {1 {SQL logic error or missing database}} +} + +# If TEMP_STORE is 2 or greater, then the database [db2] will be created +# as an in-memory database. This test will not work in that case, as it +# is not possible to change the page-size of an in-memory database. Even +# using the backup API. +# +if {$TEMP_STORE<2} { + do_faultsim_test pagerfault-14b -prep { + catch { db2 close } + faultsim_restore_and_reopen + sqlite3 db2 "" + db2 eval { PRAGMA page_size = 4096; CREATE TABLE xx(a) } + } -body { + sqlite3_backup B db2 main db main + B step 200 + set rc [B finish] + if {[string match SQLITE_IOERR_* $rc]} {set rc SQLITE_IOERR} + if {$rc != "SQLITE_OK"} { error [sqlite3_test_errstr $rc] } + set {} {} + } -test { + faultsim_test_result {0 {}} {1 {sqlite3_backup_init() failed}} + } +} + +do_faultsim_test pagerfault-14c -prep { + catch { db2 close } + faultsim_restore_and_reopen + sqlite3 db2 test.db2 + db2 eval { + PRAGMA synchronous = off; + PRAGMA page_size = 4096; + CREATE TABLE xx(a); + } +} -body { + sqlite3_backup B db2 main db main + B step 200 + set rc [B finish] + if {[string match SQLITE_IOERR_* $rc]} {set rc SQLITE_IOERR} + if {$rc != "SQLITE_OK"} { error [sqlite3_test_errstr $rc] } + set {} {} +} -test { + faultsim_test_result {0 {}} {1 {sqlite3_backup_init() failed}} +} + +do_test pagerfault-15-pre1 { + faultsim_delete_and_reopen + db func a_string a_string; + execsql { + BEGIN; + CREATE TABLE t1(x, y UNIQUE); + INSERT INTO t1 VALUES(a_string(11), a_string(22)); + INSERT INTO t1 VALUES(a_string(11), a_string(22)); + COMMIT; + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-15 -prep { + faultsim_restore_and_reopen + db func a_string a_string; +} -body { + db eval { SELECT * FROM t1 LIMIT 1 } { + execsql { + BEGIN; INSERT INTO t1 VALUES(a_string(333), a_string(555)); COMMIT; + BEGIN; INSERT INTO t1 VALUES(a_string(333), a_string(555)); COMMIT; + } + } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + + +do_test pagerfault-16-pre1 { + faultsim_delete_and_reopen + execsql { CREATE TABLE t1(x, y UNIQUE) } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-16 -prep { + faultsim_restore_and_reopen +} -body { + execsql { + PRAGMA locking_mode = exclusive; + PRAGMA journal_mode = wal; + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + PRAGMA journal_mode = delete; + INSERT INTO t1 VALUES(4, 5); + PRAGMA journal_mode = wal; + INSERT INTO t1 VALUES(6, 7); + PRAGMA journal_mode = persist; + INSERT INTO t1 VALUES(8, 9); + } +} -test { + faultsim_test_result {0 {exclusive wal delete wal persist}} + faultsim_integrity_check +} + + +#------------------------------------------------------------------------- +# Test fault injection while changing into and out of WAL mode. +# +do_test pagerfault-17-pre1 { + faultsim_delete_and_reopen + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1862, 'Botha'); + INSERT INTO t1 VALUES(1870, 'Smuts'); + INSERT INTO t1 VALUES(1866, 'Hertzog'); + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-17a -prep { + faultsim_restore_and_reopen +} -body { + execsql { + PRAGMA journal_mode = wal; + PRAGMA journal_mode = delete; + } +} -test { + faultsim_test_result {0 {wal delete}} + faultsim_integrity_check +} +do_faultsim_test pagerfault-17b -prep { + faultsim_restore_and_reopen + execsql { PRAGMA synchronous = OFF } +} -body { + execsql { + PRAGMA journal_mode = wal; + INSERT INTO t1 VALUES(22, 'Clarke'); + PRAGMA journal_mode = delete; + } +} -test { + faultsim_test_result {0 {wal delete}} + faultsim_integrity_check +} +do_faultsim_test pagerfault-17c -prep { + faultsim_restore_and_reopen + execsql { + PRAGMA locking_mode = exclusive; + PRAGMA journal_mode = wal; + } +} -body { + execsql { PRAGMA journal_mode = delete } +} -test { + faultsim_test_result {0 delete} + faultsim_integrity_check +} +do_faultsim_test pagerfault-17d -prep { + catch { db2 close } + faultsim_restore_and_reopen + sqlite3 db2 test.db + execsql { PRAGMA journal_mode = delete } + execsql { PRAGMA journal_mode = wal } + execsql { INSERT INTO t1 VALUES(99, 'Bradman') } db2 +} -body { + execsql { PRAGMA journal_mode = delete } +} -test { + faultsim_test_result {1 {database is locked}} + faultsim_integrity_check +} +do_faultsim_test pagerfault-17e -prep { + catch { db2 close } + faultsim_restore_and_reopen + sqlite3 db2 test.db + execsql { PRAGMA journal_mode = delete } + execsql { PRAGMA journal_mode = wal } + set ::chan [launch_testfixture] + testfixture $::chan { + sqlite3 db test.db + db eval { INSERT INTO t1 VALUES(101, 'Latham') } + } + catch { testfixture $::chan sqlite_abort } + catch { close $::chan } +} -body { + execsql { PRAGMA journal_mode = delete } +} -test { + faultsim_test_result {0 delete} + faultsim_integrity_check +} + +#------------------------------------------------------------------------- +# Test fault-injection when changing from journal_mode=persist to +# journal_mode=delete (this involves deleting the journal file). +# +do_test pagerfault-18-pre1 { + faultsim_delete_and_reopen + execsql { + CREATE TABLE qq(x); + INSERT INTO qq VALUES('Herbert'); + INSERT INTO qq VALUES('Macalister'); + INSERT INTO qq VALUES('Mackenzie'); + INSERT INTO qq VALUES('Lilley'); + INSERT INTO qq VALUES('Palmer'); + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-18 -prep { + faultsim_restore_and_reopen + execsql { + PRAGMA journal_mode = PERSIST; + INSERT INTO qq VALUES('Beatty'); + } +} -body { + execsql { PRAGMA journal_mode = delete } +} -test { + faultsim_test_result {0 delete} + faultsim_integrity_check +} + +do_faultsim_test pagerfault-19a -prep { + sqlite3 db :memory: + db func a_string a_string + execsql { + PRAGMA auto_vacuum = FULL; + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(a_string(5000), a_string(6000)); + COMMIT; + } +} -body { + execsql { + CREATE TABLE t2(a, b); + INSERT INTO t2 SELECT * FROM t1; + DELETE FROM t1; + } +} -test { + faultsim_test_result {0 {}} +} + +do_test pagerfault-19-pre1 { + faultsim_delete_and_reopen + execsql { + PRAGMA auto_vacuum = FULL; + CREATE TABLE t1(x); INSERT INTO t1 VALUES(1); + CREATE TABLE t2(x); INSERT INTO t2 VALUES(2); + CREATE TABLE t3(x); INSERT INTO t3 VALUES(3); + CREATE TABLE t4(x); INSERT INTO t4 VALUES(4); + CREATE TABLE t5(x); INSERT INTO t5 VALUES(5); + CREATE TABLE t6(x); INSERT INTO t6 VALUES(6); + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-19b -prep { + faultsim_restore_and_reopen +} -body { + execsql { + BEGIN; + UPDATE t4 SET x = x+1; + UPDATE t6 SET x = x+1; + SAVEPOINT one; + UPDATE t3 SET x = x+1; + SAVEPOINT two; + DROP TABLE t2; + ROLLBACK TO one; + COMMIT; + SELECT * FROM t3; + SELECT * FROM t4; + SELECT * FROM t6; + } +} -test { + faultsim_test_result {0 {3 5 7}} +} + +#------------------------------------------------------------------------- +# This tests fault-injection in a special case in the auto-vacuum code. +# +do_test pagerfault-20-pre1 { + faultsim_delete_and_reopen + execsql { + PRAGMA cache_size = 10; + PRAGMA auto_vacuum = FULL; + CREATE TABLE t0(a, b); + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-20 -prep { + faultsim_restore_and_reopen +} -body { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + DROP TABLE t1; + COMMIT; + } +} -test { + faultsim_test_result {0 {}} +} + +do_test pagerfault-21-pre1 { + faultsim_delete_and_reopen + execsql { + PRAGMA cache_size = 10; + CREATE TABLE t0(a PRIMARY KEY, b); + INSERT INTO t0 VALUES(1, 2); + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-21 -prep { + faultsim_restore_and_reopen +} -body { + db eval { SELECT * FROM t0 LIMIT 1 } { + db eval { INSERT INTO t0 SELECT a+1, b FROM t0 } + db eval { INSERT INTO t0 SELECT a+2, b FROM t0 } + } +} -test { + faultsim_test_result {0 {}} +} + + +#------------------------------------------------------------------------- +# Test fault-injection and rollback when the nReserve header value +# is non-zero. +# +do_test pagerfault-21-pre1 { + faultsim_delete_and_reopen + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + PRAGMA journal_mode = DELETE; + } + db close + hexio_write test.db 20 10 + hexio_write test.db 105 03F0 + sqlite3 db test.db + db func a_string a_string + execsql { + CREATE TABLE t0(a PRIMARY KEY, b UNIQUE); + INSERT INTO t0 VALUES(a_string(222), a_string(333)); + INSERT INTO t0 VALUES(a_string(223), a_string(334)); + INSERT INTO t0 VALUES(a_string(224), a_string(335)); + INSERT INTO t0 VALUES(a_string(225), a_string(336)); + } + faultsim_save_and_close +} {} + +do_faultsim_test pagerfault-21 -prep { + faultsim_restore_and_reopen +} -body { + execsql { INSERT INTO t0 SELECT a||'x', b||'x' FROM t0 } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} +ifcapable crashtest { + faultsim_delete_and_reopen + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + PRAGMA journal_mode = DELETE; + } + db close + hexio_write test.db 20 10 + hexio_write test.db 105 03F0 + + sqlite3 db test.db + db func a_string a_string + execsql { + CREATE TABLE t0(a PRIMARY KEY, b UNIQUE); + INSERT INTO t0 VALUES(a_string(222), a_string(333)); + INSERT INTO t0 VALUES(a_string(223), a_string(334)); + } + faultsim_save_and_close + + for {set iTest 1} {$iTest<50} {incr iTest} { + do_test pagerfault-21.crash.$iTest.1 { + crashsql -delay 1 -file test.db -seed $iTest { + BEGIN; + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + INSERT INTO t1 SELECT a, b FROM t0; + COMMIT; + } + } {1 {child process exited abnormally}} + do_test pagerfault-22.$iTest.2 { + sqlite3 db test.db + execsql { PRAGMA integrity_check } + } {ok} + db close + } +} + + +#------------------------------------------------------------------------- +# When a 3.7.0 client opens a write-transaction on a database file that +# has been appended to or truncated by a pre-370 client, it updates +# the db-size in the file header immediately. This test case provokes +# errors during that operation. +# +do_test pagerfault-22-pre1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(a); + CREATE INDEX i1 ON t1(a); + INSERT INTO t1 VALUES(a_string(3000)); + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(1); + } + db close + sql36231 { INSERT INTO t1 VALUES(a_string(3000)) } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-22 -prep { + faultsim_restore_and_reopen +} -body { + execsql { INSERT INTO t2 VALUES(2) } + execsql { SELECT * FROM t2 } +} -test { + faultsim_test_result {0 {1 2}} + faultsim_integrity_check +} + +#------------------------------------------------------------------------- +# Provoke an OOM error during a commit of multi-file transaction. One of +# the databases written during the transaction is an in-memory database. +# This test causes rollback of the in-memory database after CommitPhaseOne() +# has successfully returned. i.e. the series of calls for the aborted commit +# is: +# +# PagerCommitPhaseOne() -> SQLITE_OK +# PagerCommitPhaseOne() -> SQLITE_IOERR +# PagerRollback() +# PagerRollback() +# +do_faultsim_test pagerfault-23 -prep { + sqlite3 db :memory: + foreach f [glob -nocomplain test.db*] { forcedelete $f } + db eval { + ATTACH 'test.db2' AS aux; + CREATE TABLE t1(a, b); + CREATE TABLE aux.t2(a, b); + } +} -body { + execsql { + BEGIN; + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(3,4); + COMMIT; + } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + +do_faultsim_test pagerfault-24 -prep { + faultsim_delete_and_reopen + db eval { PRAGMA temp_store = file } + execsql { CREATE TABLE x(a, b) } +} -body { + execsql { CREATE TEMP TABLE t1(a, b) } +} -test { + faultsim_test_result {0 {}} \ + {1 {unable to open a temporary database file for storing temporary tables}} + set ic [db eval { PRAGMA temp.integrity_check }] + if {$ic != "ok"} { error "Integrity check: $ic" } +} + +proc lockrows {n} { + if {$n==0} { return "" } + db eval { SELECT * FROM t1 WHERE oid = $n } { + return [lockrows [expr {$n-1}]] + } +} + + +do_test pagerfault-25-pre1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(a_string(500)); + INSERT INTO t1 SELECT a_string(500) FROM t1; + INSERT INTO t1 SELECT a_string(500) FROM t1; + INSERT INTO t1 SELECT a_string(500) FROM t1; + INSERT INTO t1 SELECT a_string(500) FROM t1; + INSERT INTO t1 SELECT a_string(500) FROM t1; + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-25 -prep { + faultsim_restore_and_reopen + db func a_string a_string + set ::channel [db incrblob -readonly t1 a 1] + execsql { + PRAGMA cache_size = 10; + BEGIN; + INSERT INTO t1 VALUES(a_string(3000)); + INSERT INTO t1 VALUES(a_string(3000)); + } +} -body { + lockrows 30 +} -test { + catch { lockrows 30 } + catch { db eval COMMIT } + close $::channel + faultsim_test_result {0 {}} +} + +do_faultsim_test pagerfault-26 -prep { + faultsim_delete_and_reopen + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = truncate; + PRAGMA auto_vacuum = full; + PRAGMA locking_mode=exclusive; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + PRAGMA page_size = 4096; + } +} -body { + execsql { + VACUUM; + } +} -test { + faultsim_test_result {0 {}} + + set contents [db eval {SELECT * FROM t1}] + if {$contents != "1 2"} { error "Bad database contents ($contents)" } + + set sz [file size test.db] + if {$testrc!=0 && $sz!=1024*3 && $sz!=4096*3} { + error "Expected file size to be 3072 or 12288 bytes - actual size $sz bytes" + } + if {$testrc==0 && $sz!=4096*3} { + error "Expected file size to be 12288 bytes - actual size $sz bytes" + } +} + +do_test pagerfault-27-pre { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a UNIQUE, b UNIQUE); + INSERT INTO t2 VALUES( a_string(800), a_string(800) ); + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t1 VALUES (a_string(20000), a_string(20000)); + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-27 -faults ioerr-persistent -prep { + faultsim_restore_and_reopen + db func a_string a_string + execsql { + PRAGMA cache_size = 10; + BEGIN EXCLUSIVE; + } + set ::channel [db incrblob t1 a 1] +} -body { + puts $::channel [string repeat abc 6000] + flush $::channel +} -test { + catchsql { UPDATE t2 SET a = a_string(800), b = a_string(800) } + catch { close $::channel } + catchsql { ROLLBACK } + faultsim_integrity_check +} + + +#------------------------------------------------------------------------- +# +do_test pagerfault-28-pre { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA page_size = 512; + + PRAGMA journal_mode = wal; + PRAGMA wal_autocheckpoint = 0; + PRAGMA cache_size = 100000; + + BEGIN; + CREATE TABLE t2(a UNIQUE, b UNIQUE); + INSERT INTO t2 VALUES( a_string(800), a_string(800) ); + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + COMMIT; + CREATE TABLE t1(a PRIMARY KEY, b); + } + expr {[file size test.db-shm] >= 96*1024} +} {1} +faultsim_save_and_close + +do_faultsim_test pagerfault-28a -faults oom* -prep { + faultsim_restore_and_reopen + execsql { PRAGMA mmap_size=0 } + + sqlite3 db2 test.db + db2 eval { SELECT count(*) FROM t2 } + + db func a_string a_string + execsql { + BEGIN; + INSERT INTO t1 VALUES(a_string(2000), a_string(2000)); + INSERT INTO t1 VALUES(a_string(2000), a_string(2000)); + } + set ::STMT [sqlite3_prepare db "SELECT * FROM t1 ORDER BY a" -1 DUMMY] + sqlite3_step $::STMT +} -body { + execsql { ROLLBACK } +} -test { + db2 close + sqlite3_finalize $::STMT + catchsql { ROLLBACK } + faultsim_integrity_check +} + +faultsim_restore_and_reopen +sqlite3 db2 test.db +db2 eval {SELECT count(*) FROM t2} +db close + +do_faultsim_test pagerfault-28b -faults oom* -prep { + sqlite3 db test.db +} -body { + execsql { SELECT count(*) FROM t2 } +} -test { + faultsim_test_result {0 2048} + db close +} + +db2 close + +#------------------------------------------------------------------------- +# Try this: +# +# 1) Put the pager in ERROR state (error during rollback) +# +# 2) Next time the connection is used inject errors into all xWrite() and +# xUnlock() calls. This causes the hot-journal rollback to fail and +# the pager to declare its locking state UNKNOWN. +# +# 3) Same again. +# +# 4a) Stop injecting errors. Allow the rollback to succeed. Check that +# the database is Ok. Or, +# +# 4b) Close and reopen the db. Check that the db is Ok. +# +proc custom_injectinstall {} { + testvfs custom -default true + custom filter {xWrite xUnlock} +} +proc custom_injectuninstall {} { + catch {db close} + catch {db2 close} + custom delete +} +proc custom_injectstart {iFail} { + custom ioerr $iFail 1 +} +proc custom_injectstop {} { + custom ioerr +} +set ::FAULTSIM(custom) [list \ + -injectinstall custom_injectinstall \ + -injectstart custom_injectstart \ + -injectstop custom_injectstop \ + -injecterrlist {{1 {disk I/O error}}} \ + -injectuninstall custom_injectuninstall \ +] + +do_test pagerfault-29-pre { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA page_size = 1024; + PRAGMA cache_size = 5; + + BEGIN; + CREATE TABLE t2(a UNIQUE, b UNIQUE); + INSERT INTO t2 VALUES( a_string(800), a_string(800) ); + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + INSERT INTO t2 SELECT a_string(800), a_string(800) FROM t2; + COMMIT; + } + expr {[file size test.db] >= 50*1024} +} {1} +faultsim_save_and_close +foreach {tn tt} { + 29 { catchsql ROLLBACK } + 30 { db close ; sqlite3 db test.db } +} { + do_faultsim_test pagerfault-$tn -faults custom -prep { + faultsim_restore_and_reopen + db func a_string a_string + execsql { + PRAGMA cache_size = 5; + BEGIN; + UPDATE t2 SET a = a_string(799); + } + } -body { + catchsql ROLLBACK + catchsql ROLLBACK + catchsql ROLLBACK + } -test { + eval $::tt + if {"ok" != [db one {PRAGMA integrity_check}]} { + error "integrity check failed" + } + } +} + +do_test pagerfault-31-pre { + sqlite3_shutdown + sqlite3_config_uri 1 +} {SQLITE_OK} +do_faultsim_test pagerfault-31 -faults oom* -body { + sqlite3 db {file:one?mode=memory&cache=shared} + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + SELECT * FROM t1; + } +} -test { + faultsim_test_result {0 1} {1 {}} + catch { db close } +} +sqlite3_shutdown +sqlite3_config_uri 0 + +do_test pagerfault-32-pre { + reset_db + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('one'); + } +} {} +faultsim_save_and_close + +do_faultsim_test pagerfault-32 -prep { + faultsim_restore_and_reopen + db eval { SELECT * FROM t1; } +} -body { + execsql { SELECT * FROM t1; } +} -test { + faultsim_test_result {0 one} +} +sqlite3_shutdown +sqlite3_config_uri 0 + +do_faultsim_test pagerfault-33a -prep { + sqlite3 db :memory: + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } +} -body { + execsql { VACUUM } +} -test { + faultsim_test_result {0 {}} +} +do_faultsim_test pagerfault-33b -prep { + sqlite3 db "" + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } +} -body { + execsql { VACUUM } +} -test { + faultsim_test_result {0 {}} +} + +do_test pagerfault-34-pre { + reset_db + execsql { + CREATE TABLE t1(x PRIMARY KEY); + } +} {} +faultsim_save_and_close +do_faultsim_test pagerfault-34 -prep { + faultsim_restore_and_reopen + execsql { + BEGIN; + INSERT INTO t1 VALUES( randomblob(4000) ); + DELETE FROM t1; + } +} -body { + execsql COMMIT +} -test { + faultsim_test_result {0 {}} +} + +do_test pagerfault-35-pre { + faultsim_delete_and_reopen + execsql { + CREATE TABLE t1(x PRIMARY KEY, y); + INSERT INTO t1 VALUES(randomblob(200), randomblob(200)); + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + } + faultsim_save_and_close +} {} +testvfs tv -default 1 +tv sectorsize 8192; +tv devchar [list] +do_faultsim_test pagerfault-35 -prep { + faultsim_restore_and_reopen +} -body { + execsql { UPDATE t1 SET x=randomblob(200) } +} -test { + faultsim_test_result {0 {}} +} +catch {db close} +tv delete + +sqlite3_shutdown +sqlite3_config_uri 1 +do_test pagerfault-36-pre { + faultsim_delete_and_reopen + execsql { + CREATE TABLE t1(x PRIMARY KEY, y); + INSERT INTO t1 VALUES(randomblob(200), randomblob(200)); + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(200), randomblob(200) FROM t1; + } + faultsim_save_and_close +} {} +do_faultsim_test pagerfault-36 -prep { + faultsim_restore + sqlite3 db file:test.db?cache=shared + sqlite3 db2 file:test.db?cache=shared + db2 eval { + BEGIN; + SELECT count(*) FROM sqlite_master; + } + db eval { + PRAGMA cache_size = 1; + BEGIN; + UPDATE t1 SET x = randomblob(200); + } +} -body { + execsql ROLLBACK db +} -test { + catch { db eval {UPDATE t1 SET x = randomblob(200)} } + faultsim_test_result {0 {}} + catch { db close } + catch { db2 close } +} + +sqlite3_shutdown +sqlite3_config_uri 0 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/pagerfault2.test b/components/external/SQLite-3.8.1/test/pagerfault2.test new file mode 100644 index 0000000000000000000000000000000000000000..7f6c995efd603f6dcc76a83df701cf1b3907bfc2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pagerfault2.test @@ -0,0 +1,98 @@ +# 2010 June 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The tests in this file test the pager modules response to various +# fault conditions (OOM, IO error, disk full etc.). They are similar +# to those in file pagerfault1.test. +# +# More specifically, the tests in this file are those deemed too slow to +# run as part of pagerfault1.test. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +if {[permutation] == "inmemory_journal"} { + finish_test + return +} + +sqlite3_memdebug_vfs_oom_test 0 + +set a_string_counter 1 +proc a_string {n} { + global a_string_counter + incr a_string_counter + string range [string repeat "${a_string_counter}." $n] 1 $n +} +db func a_string a_string + +do_test pagerfault2-1-pre1 { + faultsim_delete_and_reopen + db func a_string a_string + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = DELETE; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(a_string(401), a_string(402)); + } + for {set ii 0} {$ii < 13} {incr ii} { + execsql { INSERT INTO t1 SELECT a_string(401), a_string(402) FROM t1 } + } + faultsim_save_and_close + file size test.db +} [expr 1024 * 8268] + +do_faultsim_test pagerfault2-1 -faults oom-transient -prep { + faultsim_restore_and_reopen + sqlite3_db_config_lookaside db 0 256 4096 + execsql { + BEGIN; + SELECT * FROM t1; + INSERT INTO t1 VALUES(5, 6); + SAVEPOINT abc; + UPDATE t1 SET a = a||'x' WHERE rowid<3700; + } +} -body { + execsql { UPDATE t1 SET a = a||'x' WHERE rowid>=3700 AND rowid<=4200 } + execsql { ROLLBACK TO abc } +} -test { + faultsim_test_result {0 {}} +} + +do_test pagerfault2-2-pre1 { + faultsim_restore_and_reopen + execsql { DELETE FROM t1 } + faultsim_save_and_close +} {} + +do_faultsim_test pagerfault2-2 -faults oom-transient -prep { + faultsim_restore_and_reopen + sqlite3_db_config_lookaside db 0 256 4096 + db func a_string a_string + + execsql { + PRAGMA cache_size = 20; + BEGIN; + INSERT INTO t1 VALUES(a_string(401), a_string(402)); + SAVEPOINT abc; + } +} -body { + execsql { INSERT INTO t1 VALUES (a_string(2000000), a_string(2500000)) } +} -test { + faultsim_test_result {0 {}} +} + +sqlite3_memdebug_vfs_oom_test 1 +finish_test diff --git a/components/external/SQLite-3.8.1/test/pagerfault3.test b/components/external/SQLite-3.8.1/test/pagerfault3.test new file mode 100644 index 0000000000000000000000000000000000000000..a4301cd17d2b3fcfb4a538f681f14dc6757249a2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pagerfault3.test @@ -0,0 +1,63 @@ +# 2011 January 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +if {[permutation] == "inmemory_journal"} { + finish_test + return +} + +# Create a database with page-size 2048 bytes that uses 2 pages. Populate +# it so that if the page-size is changed to 1024 bytes and the db vacuumed, +# the new db size is 3 pages. +# +do_test pagerfault3-pre1 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 2048; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(1200)); + PRAGMA page_count; + } +} {2} +do_test pagerfault3-pre2 { + faultsim_save_and_close + faultsim_restore_and_reopen + execsql { + PRAGMA page_size = 1024; + VACUUM; + PRAGMA page_count; + } +} {3} + +# Now do the page-size change and VACUUM with IO error injection. When +# an IO error is injected into the final xSync() of the commit, the pager +# will have to extend the db file from 3072 to 4096 byts when rolling +# back the hot-journal file. This is a special case in pager_truncate(). +# +do_faultsim_test pagerfault3-1 -faults ioerr-transient -prep { + faultsim_restore_and_reopen +} -body { + execsql { + PRAGMA page_size = 1024; + VACUUM; + } +} -test { + faultsim_test_result {0 {}} + faultsim_integrity_check +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/pageropt.test b/components/external/SQLite-3.8.1/test/pageropt.test new file mode 100644 index 0000000000000000000000000000000000000000..7191661ba5d7cd4e599c9129bbda142b87f4d9d5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pageropt.test @@ -0,0 +1,204 @@ +# 2007 April 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# The focus of the tests in this file are to verify that the +# pager optimizations implemented in version 3.3.14 work. +# +# $Id: pageropt.test,v 1.5 2008/08/20 14:49:25 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!pager_pragmas||secure_delete||direct_read} { + finish_test + return +} + +# Run the SQL statement supplied by the argument and return +# the results. Prepend four integers to the beginning of the +# result which are +# +# (1) The number of page reads from the database +# (2) The number of page writes to the database +# (3) The number of page writes to the journal +# (4) The number of cache pages freed +# +proc pagercount_sql {sql {db db}} { + global sqlite3_pager_readdb_count + global sqlite3_pager_writedb_count + global sqlite3_pager_writej_count + global sqlite3_pager_pgfree_count + set sqlite3_pager_readdb_count 0 + set sqlite3_pager_writedb_count 0 + set sqlite3_pager_writej_count 0 + set r [$db eval $sql] + set cnt [list $sqlite3_pager_readdb_count \ + $sqlite3_pager_writedb_count \ + $sqlite3_pager_writej_count ] + return [concat $cnt $r] +} + +# Setup the test database +# +do_test pageropt-1.1 { + sqlite3_soft_heap_limit 0 + execsql { + PRAGMA auto_vacuum = OFF; + PRAGMA page_size = 1024; + } + pagercount_sql { + CREATE TABLE t1(x); + } +} {0 2 0} +do_test pageropt-1.2 { + pagercount_sql { + INSERT INTO t1 VALUES(randomblob(5000)); + } +} {0 6 2} + +# Verify that values remain in cache on for subsequent reads. +# We should not have to go back to disk. +# +do_test pageropt-1.3 { + pagercount_sql { + SELECT length(x) FROM t1 + } +} {0 0 0 5000} + +# If another thread reads the database, the original cache +# remains valid. +# +sqlite3 db2 test.db +set blobcontent [db2 one {SELECT hex(x) FROM t1}] +do_test pageropt-1.4 { + pagercount_sql { + SELECT hex(x) FROM t1 + } +} [list 0 0 0 $blobcontent] + +# But if the other thread modifies the database, then the cache +# must refill. +# +ifcapable mmap { + set x [expr {[permutation]=="mmap" ? 1 : 6}] +} else { + set x 6 +} +do_test pageropt-1.5 { + db2 eval {CREATE TABLE t2(y)} + pagercount_sql { + SELECT hex(x) FROM t1 + } +} [list $x 0 0 $blobcontent] +do_test pageropt-1.6 { + pagercount_sql { + SELECT hex(x) FROM t1 + } +} [list 0 0 0 $blobcontent] + +# Verify that the last page of an overflow chain is not read from +# disk when deleting a row. The one row of t1(x) has four pages +# of overflow. So deleting that row from t1 should involve reading +# the sqlite_master table (1 page) the main page of t1 (1 page) and +# the three overflow pages of t1 for a total of 5 pages. +# +# Pages written are page 1 (for the freelist pointer), the root page +# of the table, and one of the overflow chain pointers because it +# becomes the trunk of the freelist. Total 3. +# +do_test pageropt-2.1 { + db close + sqlite3 db test.db + pagercount_sql { + DELETE FROM t1 WHERE rowid=1 + } +} {5 3 3} + +# When pulling pages off of the freelist, there is no reason +# to actually bring in the old content. +# +do_test pageropt-2.2 { + db close + sqlite3 db test.db + pagercount_sql { + INSERT INTO t1 VALUES(randomblob(1500)); + } +} {3 4 3} +do_test pageropt-2.3 { + pagercount_sql { + INSERT INTO t1 VALUES(randomblob(1500)); + } +} {0 4 3} + +# Note the new optimization that when pulling the very last page off of the +# freelist we do not read the content of that page. +# +do_test pageropt-2.4 { + pagercount_sql { + INSERT INTO t1 VALUES(randomblob(1500)); + } +} {0 5 3} + +# Appending a large quantity of data does not involve writing much +# to the journal file. +# +do_test pageropt-3.1 { + pagercount_sql { + INSERT INTO t2 SELECT * FROM t1; + } +} {1 7 2} + +# Once again, we do not need to read the last page of an overflow chain +# while deleting. +# +do_test pageropt-3.2 { + pagercount_sql { + DROP TABLE t2; + } +} {0 2 3} +do_test pageropt-3.3 { + pagercount_sql { + DELETE FROM t1; + } +} {0 3 3} + +# There are now 11 pages on the freelist. Move them all into an +# overflow chain by inserting a single large record. Starting from +# a cold cache, only page 1, the root page of table t1, and the trunk +# of the freelist need to be read (3 pages). And only those three +# pages need to be journalled. But 13 pages need to be written: +# page1, the root page of table t1, and an 11 page overflow chain. +# +do_test pageropt-4.1 { + db close + sqlite3 db test.db + pagercount_sql { + INSERT INTO t1 VALUES(randomblob(11300)) + } +} {3 13 3} + +# Now we delete that big entries starting from a cold cache and an +# empty freelist. The first 10 of the 11 pages overflow chain have +# to be read, together with page1 and the root of the t1 table. 12 +# reads total. But only page1, the t1 root, and the trunk of the +# freelist need to be journalled and written back. +# +do_test pageropt-4.2 { + db close + sqlite3 db test.db + pagercount_sql { + DELETE FROM t1 + } +} {12 3 3} + +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) +catch {db2 close} +finish_test diff --git a/components/external/SQLite-3.8.1/test/pagesize.test b/components/external/SQLite-3.8.1/test/pagesize.test new file mode 100644 index 0000000000000000000000000000000000000000..0eebbbb7c9a9dc5e21d2572666d6df9062a5a574 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pagesize.test @@ -0,0 +1,219 @@ +# 2004 September 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# This file implements tests for the page_size PRAGMA. +# +# $Id: pagesize.test,v 1.13 2008/08/26 21:07:27 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# This test script depends entirely on "PRAGMA page_size". So if this +# pragma is not available, omit the whole file. +ifcapable !pager_pragmas { + finish_test + return +} + +do_test pagesize-1.1 { + execsql {PRAGMA page_size} +} 1024 +ifcapable {explain} { + do_test pagesize-1.2 { + catch {execsql {EXPLAIN PRAGMA page_size}} + } 0 +} +do_test pagesize-1.3 { + execsql { + CREATE TABLE t1(a); + PRAGMA page_size=2048; + PRAGMA page_size; + } +} 1024 + +do_test pagesize-1.4 { + db close + forcedelete test.db + sqlite3 db test.db + execsql { + PRAGMA page_size=511; + PRAGMA page_size; + } +} 1024 +do_test pagesize-1.5 { + execsql { + PRAGMA page_size=512; + PRAGMA page_size; + } +} 512 +if {![info exists SQLITE_MAX_PAGE_SIZE] || $SQLITE_MAX_PAGE_SIZE>=8192} { + do_test pagesize-1.6 { + execsql { + PRAGMA page_size=8192; + PRAGMA page_size; + } + } 8192 + do_test pagesize-1.7 { + execsql { + PRAGMA page_size=65537; + PRAGMA page_size; + } + } 8192 + do_test pagesize-1.8 { + execsql { + PRAGMA page_size=1234; + PRAGMA page_size + } + } 8192 +} +foreach PGSZ {512 2048 4096 8192} { + if {[info exists SQLITE_MAX_PAGE_SIZE] + && $SQLITE_MAX_PAGE_SIZE<$PGSZ} continue + ifcapable memorydb { + do_test pagesize-2.$PGSZ.0.1 { + db close + sqlite3 db :memory: + execsql "PRAGMA page_size=$PGSZ;" + execsql {PRAGMA page_size} + } $PGSZ + do_test pagesize-2.$PGSZ.0.2 { + execsql {CREATE TABLE t1(x UNIQUE, y UNIQUE, z UNIQUE)} + execsql {PRAGMA page_size} + } $PGSZ + do_test pagesize-2.$PGSZ.0.3 { + execsql { + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(2,3,4); + SELECT * FROM t1; + } + } {1 2 3 2 3 4} + } + do_test pagesize-2.$PGSZ.1 { + db close + forcedelete test.db + sqlite3 db test.db + execsql "PRAGMA page_size=$PGSZ" + execsql { + CREATE TABLE t1(x); + PRAGMA page_size; + } + } $PGSZ + do_test pagesize-2.$PGSZ.2 { + db close + sqlite3 db test.db + execsql { + PRAGMA page_size + } + } $PGSZ + do_test pagesize-2.$PGSZ.3 { + file size test.db + } [expr {$PGSZ*($AUTOVACUUM?3:2)}] + ifcapable {vacuum} { + do_test pagesize-2.$PGSZ.4 { + execsql {VACUUM} + } {} + } + integrity_check pagesize-2.$PGSZ.5 + do_test pagesize-2.$PGSZ.6 { + db close + sqlite3 db test.db + execsql {PRAGMA page_size} + } $PGSZ + do_test pagesize-2.$PGSZ.7 { + execsql { + INSERT INTO t1 VALUES(randstr(10,9000)); + INSERT INTO t1 VALUES(randstr(10,9000)); + INSERT INTO t1 VALUES(randstr(10,9000)); + BEGIN; + INSERT INTO t1 SELECT x||x FROM t1; + INSERT INTO t1 SELECT x||x FROM t1; + INSERT INTO t1 SELECT x||x FROM t1; + INSERT INTO t1 SELECT x||x FROM t1; + SELECT count(*) FROM t1; + } + } 48 + do_test pagesize-2.$PGSZ.8 { + execsql { + ROLLBACK; + SELECT count(*) FROM t1; + } + } 3 + integrity_check pagesize-2.$PGSZ.9 + do_test pagesize-2.$PGSZ.10 { + db close + sqlite3 db test.db + execsql {PRAGMA page_size} + } $PGSZ + do_test pagesize-2.$PGSZ.11 { + execsql { + INSERT INTO t1 SELECT x||x FROM t1; + INSERT INTO t1 SELECT x||x FROM t1; + INSERT INTO t1 SELECT x||x FROM t1; + INSERT INTO t1 SELECT x||x FROM t1; + INSERT INTO t1 SELECT x||x FROM t1; + INSERT INTO t1 SELECT x||x FROM t1; + SELECT count(*) FROM t1; + } + } 192 + do_test pagesize-2.$PGSZ.12 { + execsql { + BEGIN; + DELETE FROM t1 WHERE rowid%5!=0; + SELECT count(*) FROM t1; + } + } 38 + do_test pagesize-2.$PGSZ.13 { + execsql { + ROLLBACK; + SELECT count(*) FROM t1; + } + } 192 + integrity_check pagesize-2.$PGSZ.14 + do_test pagesize-2.$PGSZ.15 { + execsql {DELETE FROM t1 WHERE rowid%5!=0} + ifcapable {vacuum} {execsql VACUUM} + execsql {SELECT count(*) FROM t1} + } 38 + do_test pagesize-2.$PGSZ.16 { + execsql {DROP TABLE t1} + ifcapable {vacuum} {execsql VACUUM} + } {} + integrity_check pagesize-2.$PGSZ.17 + + db close + forcedelete test.db + sqlite3 db test.db + do_test pagesize-2.$PGSZ.30 { + execsql " + CREATE TABLE t1(x); + PRAGMA temp.page_size=$PGSZ; + CREATE TEMP TABLE t2(y); + PRAGMA main.page_size; + PRAGMA temp.page_size; + " + } [list 1024 $PGSZ] + + db close + forcedelete test.db + sqlite3 db test.db + do_test pagesize-2.$PGSZ.40 { + execsql " + PRAGMA page_size=$PGSZ; + CREATE TABLE t1(x); + CREATE TEMP TABLE t2(y); + PRAGMA main.page_size; + PRAGMA temp.page_size; + " + } [list $PGSZ $PGSZ] +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/pcache.test b/components/external/SQLite-3.8.1/test/pcache.test new file mode 100644 index 0000000000000000000000000000000000000000..0766fce0880afba0f38795bb303598b2206ab11e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pcache.test @@ -0,0 +1,182 @@ +# 2008 August 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file is focused on testing the pcache module. +# +# $Id: pcache.test,v 1.5 2009/05/08 06:52:48 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Only works with a mode-2 pcache where all pcaches share a single set +# of pages. +# +ifcapable {!memorymanage && threadsafe} { + finish_test + return +} + +# The pcache module limits the number of pages available to purgeable +# caches to the sum of the 'cache_size' values for the set of open +# caches. This block of tests, pcache-1.*, test that the library behaves +# corrctly when it is forced to exceed this limit. +# +do_test pcache-1.1 { + db close + pcache_stats +} {current 0 max 0 min 0 recyclable 0} + +do_test pcache-1.2 { + sqlite3 db test.db + execsql { + PRAGMA cache_size=12; + PRAGMA auto_vacuum=0; + PRAGMA mmap_size=0; + } + pcache_stats +} {current 1 max 12 min 10 recyclable 1} + +do_test pcache-1.3 { + execsql { + BEGIN; + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(a, b, c); + CREATE TABLE t3(a, b, c); + CREATE TABLE t4(a, b, c); + CREATE TABLE t5(a, b, c); + } + pcache_stats +} {current 6 max 12 min 10 recyclable 0} + +do_test pcache-1.4 { + execsql { + CREATE TABLE t6(a, b, c); + CREATE TABLE t7(a, b, c); + CREATE TABLE t8(a, b, c); + CREATE TABLE t9(a, b, c); + } + pcache_stats +} {current 10 max 12 min 10 recyclable 0} + +do_test pcache-1.5 { + sqlite3 db2 test.db + execsql "PRAGMA cache_size=10" db2 + pcache_stats +} {current 11 max 22 min 20 recyclable 1} + +do_test pcache-1.6.1 { + execsql { + BEGIN; + SELECT * FROM sqlite_master; + } db2 + pcache_stats +} {current 11 max 22 min 20 recyclable 0} + +# At this point connection db2 has a read lock on the database file and a +# single pinned page in its cache. Connection [db] is holding 10 dirty +# pages. It cannot recycle them because of the read lock held by db2. +# +do_test pcache-1.6.2 { + execsql { + CREATE INDEX i1 ON t1(a, b); + CREATE INDEX i2 ON t2(a, b); + CREATE INDEX i3 ON t3(a, b); + CREATE INDEX i4 ON t4(a, b); + CREATE INDEX i5 ON t5(a, b); + CREATE INDEX i6 ON t6(a, b); + CREATE INDEX i7 ON t7(a, b); + CREATE INDEX i8 ON t8(a, b); + CREATE INDEX i9 ON t9(a, b); + CREATE INDEX i10 ON t9(a, b); + CREATE INDEX i11 ON t9(a, b); + } + pcache_stats +} {current 23 max 22 min 20 recyclable 0} + +do_test pcache-1.7 { + execsql { + CREATE TABLE t10(a, b, c); + } + pcache_stats +} {current 24 max 22 min 20 recyclable 0} + +# Rolling back the transaction held by db2 at this point releases a pinned +# page. Because the number of allocated pages is greater than the +# configured maximum, this page should be freed immediately instead of +# recycled. +# +do_test pcache-1.8 { + execsql {ROLLBACK} db2 + pcache_stats +} {current 23 max 22 min 20 recyclable 0} + +do_test pcache-1.9 { + execsql COMMIT + pcache_stats +} {current 22 max 22 min 20 recyclable 22} + +do_test pcache-1.10 { + db2 close + pcache_stats +} {current 12 max 12 min 10 recyclable 12} + +do_test pcache-1.11 { + execsql { PRAGMA cache_size = 20 } + pcache_stats +} {current 12 max 20 min 10 recyclable 12} + +do_test pcache-1.12 { + execsql { + SELECT * FROM t1 ORDER BY a; SELECT * FROM t1; + SELECT * FROM t2 ORDER BY a; SELECT * FROM t2; + SELECT * FROM t3 ORDER BY a; SELECT * FROM t3; + SELECT * FROM t4 ORDER BY a; SELECT * FROM t4; + SELECT * FROM t5 ORDER BY a; SELECT * FROM t5; + SELECT * FROM t6 ORDER BY a; SELECT * FROM t6; + SELECT * FROM t7 ORDER BY a; SELECT * FROM t7; + SELECT * FROM t8 ORDER BY a; SELECT * FROM t8; + SELECT * FROM t9 ORDER BY a; SELECT * FROM t9; + } + pcache_stats +} {current 19 max 20 min 10 recyclable 19} + +do_test pcache-1.13 { + execsql { PRAGMA cache_size = 15 } + pcache_stats +} {current 15 max 15 min 10 recyclable 15} + +do_test pcache-1.14 { + hexio_write test.db 24 [hexio_render_int32 1000] + execsql { SELECT * FROM sqlite_master } + pcache_stats +} {current 2 max 15 min 10 recyclable 2} + +do_test pcache-1.15 { + execsql { + SELECT * FROM t1 ORDER BY a; SELECT * FROM t1; + SELECT * FROM t2 ORDER BY a; SELECT * FROM t2; + SELECT * FROM t3 ORDER BY a; SELECT * FROM t3; + SELECT * FROM t4 ORDER BY a; SELECT * FROM t4; + SELECT * FROM t5 ORDER BY a; SELECT * FROM t5; + SELECT * FROM t6 ORDER BY a; SELECT * FROM t6; + SELECT * FROM t7 ORDER BY a; SELECT * FROM t7; + SELECT * FROM t8 ORDER BY a; SELECT * FROM t8; + SELECT * FROM t9 ORDER BY a; SELECT * FROM t9; + } + pcache_stats +} {current 14 max 15 min 10 recyclable 14} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/pcache2.test b/components/external/SQLite-3.8.1/test/pcache2.test new file mode 100644 index 0000000000000000000000000000000000000000..77e7a2613273030c10ba4a76e0825804444d3f8b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pcache2.test @@ -0,0 +1,79 @@ +# 2008 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file is focused on testing the pcache module. +# +# $Id: pcache2.test,v 1.5 2009/07/18 14:36:24 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Set up a pcache memory pool so that we can easily track how many +# pages are being used for cache. +# +do_test pcache2-1.1 { + db close + sqlite3_reset_auto_extension + sqlite3_shutdown + sqlite3_config_pagecache 6000 100 + sqlite3_initialize + autoinstall_test_functions + sqlite3_status SQLITE_STATUS_PAGECACHE_USED 1 + sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0 +} {0 0 0} + +# Open up two database connections to separate files. +# +do_test pcache2-1.2 { + forcedelete test.db test.db-journal + sqlite3 db test.db + db eval {PRAGMA cache_size=10} + lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 1 +} {2} +do_test pcache2-1.3 { + forcedelete test2.db test2.db-journal + sqlite3 db2 test2.db + db2 eval {PRAGMA cache_size=50} + lindex [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] 1 +} {4} + + +# Make lots of changes on the first connection. Verify that the +# page cache usage does not grow to consume the page space set aside +# for the second connection. +# +do_test pcache2-1.4 { + db eval { + CREATE TABLE t1(a,b); + CREATE TABLE t2(x,y); + INSERT INTO t1 VALUES(1, zeroblob(800)); + INSERT INTO t1 VALUES(2, zeroblob(800)); + INSERT INTO t2 SELECT * FROM t1; + INSERT INTO t1 SELECT x+2, y FROM t2; + INSERT INTO t2 SELECT a+10, b FROM t1; + INSERT INTO t1 SELECT x+10, y FROM t2; + INSERT INTO t2 SELECT a+100, b FROM t1; + INSERT INTO t1 SELECT x+100, y FROM t2; + INSERT INTO t2 SELECT a+1000, b FROM t1; + INSERT INTO t1 SELECT x+1000, y FROM t2; + } + sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0 +} {0 13 13} + +db close +catch {db2 close} +sqlite3_reset_auto_extension +sqlite3_shutdown +sqlite3_config_pagecache 0 0 +sqlite3_initialize +autoinstall_test_functions + +finish_test diff --git a/components/external/SQLite-3.8.1/test/percentile.test b/components/external/SQLite-3.8.1/test/percentile.test new file mode 100644 index 0000000000000000000000000000000000000000..9d471dfcde1ac921d562b21076a48ec89f527e38 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/percentile.test @@ -0,0 +1,209 @@ +# 2013-05-28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is percentile.c extension +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Basic test of the percentile() function. +# +do_test percentile-1.0 { + load_static_extension db percentile + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1),(4),(6),(7),(8),(9),(11),(11),(11); + } + execsql {SELECT percentile(x,0) FROM t1} +} {1.0} +foreach {in out} { + 100 11.0 + 50 8.0 + 12.5 4.0 + 15 4.4 + 20 5.2 + 80 11.0 + 89 11.0 +} { + do_test percentile-1.1.$in { + execsql {SELECT percentile(x,$in) FROM t1} + } $out +} + +# Add some NULL values. +# +do_test percentile-1.2 { + execsql {INSERT INTO t1 VALUES(NULL),(NULL);} +} {} +foreach {in out} { + 100 11.0 + 50 8.0 + 12.5 4.0 + 15 4.4 + 20 5.2 + 80 11.0 + 89 11.0 +} { + do_test percentile-1.3.$in { + execsql {SELECT percentile(x,$in) FROM t1} + } $out +} + +# The second argument to percentile can change some, but not much. +# +do_test percentile-1.4 { + catchsql {SELECT round(percentile(x, 15+0.000001*rowid),1) FROM t1} +} {0 4.4} +do_test percentile-1.5 { + catchsql {SELECT round(percentile(x, 15+0.1*rowid),1) FROM t1} +} {1 {2nd argument to percentile() is not the same for all input rows}} + +# Input values in a random order +# +do_test percentile-1.6 { + execsql { + CREATE TABLE t2(x); + INSERT INTO t2 SELECT x+0.0 FROM t1 ORDER BY random(); + } +} {} +foreach {in out} { + 100 11.0 + 50 8.0 + 12.5 4.0 + 15 4.4 + 20 5.2 + 80 11.0 + 89 11.0 +} { + do_test percentile-1.7.$in { + execsql {SELECT percentile(x,$in) FROM t2} + } $out +} + +# Wrong number of arguments +# +do_test percentile-1.8 { + catchsql {SELECT percentile(x,0,1) FROM t1} +} {1 {wrong number of arguments to function percentile()}} +do_test percentile-1.9 { + catchsql {SELECT percentile(x) FROM t1} +} {1 {wrong number of arguments to function percentile()}} + +# Second argument must be numeric +# +do_test percentile-1.10 { + catchsql {SELECT percentile(x,null) FROM t1} +} {1 {2nd argument to percentile() is not a number between 0.0 and 100.0}} +do_test percentile-1.11 { + catchsql {SELECT percentile(x,'fifty') FROM t1} +} {1 {2nd argument to percentile() is not a number between 0.0 and 100.0}} +do_test percentile-1.12 { + catchsql {SELECT percentile(x,x'3530') FROM t1} +} {1 {2nd argument to percentile() is not a number between 0.0 and 100.0}} + +# Second argument is out of range +# +do_test percentile-1.13 { + catchsql {SELECT percentile(x,-0.0000001) FROM t1} +} {1 {2nd argument to percentile() is not a number between 0.0 and 100.0}} +do_test percentile-1.14 { + catchsql {SELECT percentile(x,100.0000001) FROM t1} +} {1 {2nd argument to percentile() is not a number between 0.0 and 100.0}} + +# First argument is not NULL and is not NUMERIC +# +do_test percentile-1.15 { + catchsql { + BEGIN; + UPDATE t1 SET x='50' WHERE x IS NULL; + SELECT percentile(x, 50) FROM t1; + } +} {1 {1st argument to percentile() is not numeric}} +do_test percentile-1.16 { + catchsql { + ROLLBACK; + BEGIN; + UPDATE t1 SET x=x'3530' WHERE x IS NULL; + SELECT percentile(x, 50) FROM t1; + } +} {1 {1st argument to percentile() is not numeric}} +do_test percentile-1.17 { + catchsql { + ROLLBACK; + SELECT percentile(x, 50) FROM t1; + } +} {0 8.0} + +# No non-NULL entries. +# +do_test percentile-1.18 { + execsql { + UPDATE t1 SET x=NULL; + SELECT ifnull(percentile(x, 50),'NULL') FROM t1 + } +} {NULL} + +# Exactly one non-NULL entry +# +do_test percentile-1.19 { + execsql { + UPDATE t1 SET x=12345 WHERE rowid=5; + SELECT percentile(x, 0), percentile(x, 50), percentile(x,100) FROM t1 + } +} {12345.0 12345.0 12345.0} + +# Infinity as an input +# +do_test percentile-1.20 { + catchsql { + DELETE FROM t1; + INSERT INTO t1 SELECT x+0.0 FROM t2; + UPDATE t1 SET x=1.0e300*1.0e300 WHERE rowid=5; + SELECT percentile(x,50) from t1; + } +} {1 {Inf input to percentile()}} +do_test percentile-1.21 { + catchsql { + UPDATE t1 SET x=-1.0e300*1.0e300 WHERE rowid=5; + SELECT percentile(x,50) from t1; + } +} {1 {Inf input to percentile()}} + +# Million-row Inputs +# +ifcapable vtab { + do_test percentile-2.0 { + load_static_extension db wholenumber + execsql { + CREATE VIRTUAL TABLE nums USING wholenumber; + CREATE TABLE t3(x); + INSERT INTO t3 SELECT value-1 FROM nums WHERE value BETWEEN 1 AND 500000; + INSERT INTO t3 SELECT value*10 FROM nums + WHERE value BETWEEN 500000 AND 999999; + SELECT count(*) FROM t3; + } + } {1000000} + foreach {in out} { + 0 0.0 + 100 9999990.0 + 50 2749999.5 + 10 99999.9 + } { + do_test percentile-2.1.$in { + execsql { + SELECT percentile(x, $in) from t3; + } + } $out + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/permutations.test b/components/external/SQLite-3.8.1/test/permutations.test new file mode 100644 index 0000000000000000000000000000000000000000..54e9ede0be5bae157757956ae1dbeb163be0e40b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/permutations.test @@ -0,0 +1,996 @@ +# 2008 June 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +db close + +#------------------------------------------------------------------------- +# test_suite NAME OPTIONS +# +# where available options are: +# +# -description TITLE (default "") +# -initialize SCRIPT (default "") +# -shutdown SCRIPT (default "") +# -presql SQL (default "") +# -files LIST-OF-FILES (default $::ALLTESTS) +# -prefix NAME (default "$::NAME.") +# -dbconfig SCRIPT (default "") +# +proc test_suite {name args} { + + set default(-shutdown) "" + set default(-initialize) "" + set default(-presql) "" + set default(-description) "no description supplied (fixme)" + set default(-files) "" + set default(-prefix) "${name}." + set default(-dbconfig) "" + + array set options [array get default] + if {[llength $args]%2} { + error "uneven number of options/switches passed to test_suite" + } + foreach {k v} $args { + set o [array names options ${k}*] + if {[llength $o]>1} { error "ambiguous option: $k" } + if {[llength $o]==0} { error "unknown option: $k" } + set options([lindex $o 0]) $v + } + + set ::testspec($name) [array get options] + lappend ::testsuitelist $name +} + +#------------------------------------------------------------------------- +# test_set ARGS... +# +proc test_set {args} { + set isExclude 0 + foreach a $args { + if {[string match -* $a]} { + switch -- $a { + -include { set isExclude 0 } + -exclude { set isExclude 1 } + default { + error "Unknown switch: $a" + } + } + } elseif {$isExclude == 0} { + foreach f $a { set t($f) 1 } + } else { + foreach f $a { array unset t $f } + foreach f $a { array unset t */$f } + } + } + + return [array names t] +} + +#------------------------------------------------------------------------- +# Set up the following global list variables containing the names of +# various test scripts: +# +# $alltests +# $allquicktests +# +set alltests [list] +foreach f [glob $testdir/*.test] { lappend alltests [file tail $f] } +foreach f [glob -nocomplain $testdir/../ext/rtree/*.test] { + lappend alltests $f +} + +if {$::tcl_platform(platform)!="unix"} { + set alltests [test_set $alltests -exclude crash.test crash2.test] +} +set alltests [test_set $alltests -exclude { + all.test async.test quick.test veryquick.test + memleak.test permutations.test soak.test fts3.test + mallocAll.test rtree.test full.test +}] + +set allquicktests [test_set $alltests -exclude { + async2.test async3.test backup_ioerr.test corrupt.test + corruptC.test crash.test crash2.test crash3.test crash4.test crash5.test + crash6.test crash7.test delete3.test e_fts3.test fts3rnd.test + fkey_malloc.test fuzz.test fuzz3.test fuzz_malloc.test in2.test loadext.test + misc7.test mutex2.test notify2.test onefile.test pagerfault2.test + savepoint4.test savepoint6.test select9.test + speed1.test speed1p.test speed2.test speed3.test speed4.test + speed4p.test sqllimits1.test tkt2686.test thread001.test thread002.test + thread003.test thread004.test thread005.test trans2.test vacuum3.test + incrvacuum_ioerr.test autovacuum_crash.test btree8.test shared_err.test + vtab_err.test walslow.test walcrash.test walcrash3.test + walthread.test rtree3.test indexfault.test securedel2.test +}] +if {[info exists ::env(QUICKTEST_INCLUDE)]} { + set allquicktests [concat $allquicktests $::env(QUICKTEST_INCLUDE)] +} + +############################################################################# +# Start of tests +# + +#------------------------------------------------------------------------- +# Define the generic test suites: +# +# veryquick +# quick +# full +# +lappend ::testsuitelist xxx + +test_suite "veryquick" -prefix "" -description { + "Very" quick test suite. Runs in less than 5 minutes on a workstation. + This test suite is the same as the "quick" tests, except that some files + that test malloc and IO errors are omitted. +} -files [ + test_set $allquicktests -exclude *malloc* *ioerr* *fault* +] + +test_suite "mmap" -prefix "mm-" -description { + Similar to veryquick. Except with memory mapping disabled. +} -presql { + pragma mmap_size = 268435456; +} -files [ + test_set $allquicktests -exclude *malloc* *ioerr* *fault* -include malloc.test +] + +test_suite "valgrind" -prefix "" -description { + Run the "veryquick" test suite with a couple of multi-process tests (that + fail under valgrind) omitted. +} -files [ + test_set $allquicktests -exclude *malloc* *ioerr* *fault* wal.test atof1.test +] -initialize { + set ::G(valgrind) 1 +} -shutdown { + unset -nocomplain ::G(valgrind) +} + +test_suite "quick" -prefix "" -description { + Quick test suite. Runs in around 10 minutes on a workstation. +} -files [ + test_set $allquicktests +] + +test_suite "full" -prefix "" -description { + Full test suite. Takes a long time. +} -files [ + test_set $alltests +] -initialize { + unset -nocomplain ::G(isquick) +} + +test_suite "threads" -prefix "" -description { + All multi-threaded tests. +} -files { + notify2.test thread001.test thread002.test thread003.test + thread004.test thread005.test walthread.test +} + +test_suite "fts3" -prefix "" -description { + All FTS3 tests except fts3rnd.test. +} -files { + fts3aa.test fts3ab.test fts3ac.test fts3ad.test fts3ae.test + fts3af.test fts3ag.test fts3ah.test fts3ai.test fts3aj.test + fts3ak.test fts3al.test fts3am.test fts3an.test fts3ao.test + fts3atoken.test fts3b.test fts3c.test fts3cov.test fts3d.test + fts3defer.test fts3defer2.test fts3e.test fts3expr.test fts3expr2.test + fts3expr3.test + fts3near.test fts3query.test fts3shared.test fts3snippet.test + fts3sort.test + fts3fault.test fts3malloc.test fts3matchinfo.test + fts3aux1.test fts3comp1.test fts3auto.test + fts4aa.test fts4content.test + fts3conf.test fts3prefix.test fts3fault2.test fts3corrupt.test + fts3corrupt2.test fts3first.test fts4langid.test fts4merge.test + fts4check.test fts4unicode.test fts4noti.test +} + +test_suite "nofaultsim" -prefix "" -description { + "Very" quick test suite. Runs in less than 5 minutes on a workstation. + This test suite is the same as the "quick" tests, except that some files + that test malloc and IO errors are omitted. +} -files [ + test_set $allquicktests -exclude *malloc* *ioerr* *fault* +] -initialize { + catch {db close} + sqlite3_shutdown + install_malloc_faultsim 0 + sqlite3_initialize + autoinstall_test_functions +} -shutdown { + unset -nocomplain ::G(valgrind) +} + +test_suite "queryplanner" -prefix "" -description { + Tests of the query planner and query optimizer +} -files { + alter2.test alter3.test alter4.test alter.test analyze3.test + analyze4.test analyze5.test analyze6.test analyze7.test analyze8.test + analyze.test attach2.test attach3.test attach4.test + attach.test autoinc.test autoindex1.test between.test cast.test + check.test closure01.test coalesce.test collate1.test collate2.test + collate3.test collate4.test collate5.test collate6.test collate7.test + collate8.test collate9.test collateA.test colmeta.test colname.test + conflict.test count.test coveridxscan.test createtab.test cse.test + date.test dbstatus2.test dbstatus.test default.test delete2.test + delete3.test delete.test descidx1.test descidx2.test descidx3.test + distinctagg.test distinct.test e_createtable.test e_delete.test + e_droptrigger.test e_dropview.test e_expr.test e_insert.test + eqp.test e_reindex.test e_resolve.test e_select2.test e_select.test + e_update.test exists.test expr.test fkey1.test fkey2.test fkey3.test + fkey4.test fkey5.test func2.test func3.test func.test + in3.test in4.test in5.test index2.test index3.test + index4.test index5.test indexedby.test index.test + insert2.test insert3.test insert4.test insert5.test insert.test + instr.test in.test intpkey.test join2.test join3.test join4.test + join5.test join6.test join.test like2.test like.test limit.test + minmax2.test minmax3.test minmax4.test minmax.test misc1.test misc2.test + misc3.test misc4.test misc5.test misc6.test misc7.test orderby1.test + orderby2.test orderby3.test orderby4.test randexpr1.test regexp1.test + reindex.test rowhash.test rowid.test schema2.test schema3.test + schema4.test schema5.test schema.test + select1.test select2.test select3.test select4.test select5.test + select6.test select7.test select8.test select9.test selectA.test + selectB.test selectC.test selectD.test selectE.test sidedelete.test + sort.test spellfix.test subquery2.test subquery.test subselect.test + substr.test tkt-02a8e81d44.test tkt1435.test tkt1443.test tkt1444.test + tkt1449.test tkt1473.test tkt1501.test tkt1512.test tkt1514.test + tkt1536.test tkt1537.test tkt1567.test tkt1644.test tkt1667.test + tkt1873.test tkt2141.test tkt2192.test tkt2213.test tkt2251.test + tkt2285.test tkt2332.test tkt2339.test tkt2391.test tkt2409.test + tkt2450.test tkt2565.test tkt2640.test tkt2643.test tkt2686.test + tkt-26ff0c2d1e.test tkt2767.test tkt2817.test tkt2820.test tkt2822.test + tkt2832.test tkt2854.test tkt2920.test tkt2927.test tkt2942.test + tkt-2a5629202f.test tkt-2d1a5c67d.test tkt-2ea2425d34.test tkt3080.test + tkt3093.test tkt3121.test tkt-31338dca7e.test tkt-313723c356.test + tkt3201.test tkt3292.test tkt3298.test tkt3334.test tkt3346.test + tkt3357.test tkt3419.test tkt3424.test tkt3442.test tkt3457.test + tkt3461.test tkt3493.test tkt3508.test tkt3522.test tkt3527.test + tkt3541.test tkt3554.test tkt3581.test tkt35xx.test tkt3630.test + tkt3718.test tkt3731.test tkt3757.test tkt3761.test tkt3762.test + tkt3773.test tkt3791.test tkt3793.test tkt3810.test tkt3824.test + tkt3832.test tkt3838.test tkt3841.test tkt-385a5b56b9.test tkt3871.test + tkt3879.test tkt-38cb5df375.test tkt3911.test tkt3918.test tkt3922.test + tkt3929.test tkt3935.test tkt3992.test tkt3997.test tkt-3998683a16.test + tkt-3a77c9714e.test tkt-3fe897352e.test tkt4018.test tkt-4a03edc4c8.test + tkt-4dd95f6943.test tkt-54844eea3f.test tkt-5d863f876e.test + tkt-5e10420e8d.test tkt-5ee23731f.test tkt-6bfb98dfc0.test + tkt-752e1646fc.test tkt-78e04e52ea.test tkt-7a31705a7e6.test + tkt-7bbfb7d442.test tkt-80ba201079.test tkt-80e031a00f.test + tkt-8454a207b9.test tkt-91e2e8ba6f.test tkt-94c04eaadb.test + tkt-9d68c883.test tkt-a7b7803e.test tkt-b1d3a2e531.test + tkt-b351d95f9.test tkt-b72787b1.test tkt-bd484a090c.test + tkt-bdc6bbbb38.test tkt-c48d99d690.test tkt-cbd054fa6b.test + tkt-d11f09d36e.test tkt-d635236375.test tkt-d82e3f3721.test + tkt-f3e5abed55.test tkt-f777251dc7a.test tkt-f7b4edec.test + tkt-f973c7ac31.test tkt-fa7bf5ec.test tkt-fc62af4523.test + tkt-fc7bd6358f.test trigger1.test trigger2.test trigger3.test + trigger4.test trigger5.test trigger6.test trigger7.test trigger8.test + trigger9.test triggerA.test triggerB.test triggerC.test triggerD.test + types2.test types3.test types.test unique.test unordered.test + update.test view.test vtab1.test vtab2.test vtab3.test vtab4.test + vtab5.test vtab6.test vtab7.test vtab8.test vtab9.test vtab_alter.test + vtabA.test vtabB.test vtabC.test vtabD.test vtabE.test + vtabF.test where2.test where3.test where4.test where5.test where6.test + where7.test where8m.test where8.test where9.test whereA.test whereB.test + whereC.test whereD.test whereE.test whereF.test wherelimit.test + where.test +} + +test_suite "vfslog" -prefix "" -description { + "Vfslog" quick test suite. Like "veryquick" except does not omits + a few tests that do not work with a version 1 VFS. And the quota* tests, + which do not work with a VFS that uses the pVfs argument passed to + sqlite3_vfs methods. +} -files [ + test_set $allquicktests -exclude *malloc* *ioerr* *fault* oserror.test \ + pager1.test syscall.test sysfault.test tkt3457.test quota* superlock* \ + wal* mmap* +] + +lappend ::testsuitelist xxx +#------------------------------------------------------------------------- +# Define the coverage related test suites: +# +# coverage-wal +# +test_suite "coverage-wal" -description { + Coverage tests for file wal.c. +} -files { + wal.test wal2.test wal3.test walmode.test + walbak.test walhook.test walcrash2.test walcksum.test + walfault.test walbig.test walnoshm.test + wal5.test +} + +test_suite "coverage-pager" -description { + Coverage tests for file pager.c. +} -files { + pager1.test pager2.test pagerfault.test pagerfault2.test + walfault.test walbak.test journal2.test tkt-9d68c883.test +} + +test_suite "coverage-analyze" -description { + Coverage tests for file analyze.c. +} -files { + analyze3.test analyze4.test analyze5.test analyze6.test + analyze7.test analyze8.test analyze9.test analyzeA.test + analyze.test analyzeB.test mallocA.test +} + + +lappend ::testsuitelist xxx +#------------------------------------------------------------------------- +# Define the permutation test suites: +# + +# Run some tests using pre-allocated page and scratch blocks. +# +# mmap1.test is excluded because a good number of its tests depend on +# the page-cache being larger than the database. But this permutation +# causes the effective limit on the page-cache to be just 24 pages. +# +test_suite "memsubsys1" -description { + Tests using pre-allocated page and scratch blocks +} -files [ + test_set $::allquicktests -exclude ioerr5.test malloc5.test mmap1.test +] -initialize { + catch {db close} + sqlite3_shutdown + sqlite3_config_pagecache 4096 24 + sqlite3_config_scratch 25000 1 + sqlite3_initialize + autoinstall_test_functions +} -shutdown { + catch {db close} + sqlite3_shutdown + sqlite3_config_pagecache 0 0 + sqlite3_config_scratch 0 0 + sqlite3_initialize + autoinstall_test_functions +} + +# Run some tests using pre-allocated page and scratch blocks. This time +# the allocations are too small to use in most cases. +# +# Both ioerr5.test and malloc5.test are excluded because they test the +# sqlite3_soft_heap_limit() and sqlite3_release_memory() functionality. +# This functionality is disabled if a pre-allocated page block is provided. +# +test_suite "memsubsys2" -description { + Tests using small pre-allocated page and scratch blocks +} -files [ + test_set $::allquicktests -exclude ioerr5.test malloc5.test +] -initialize { + catch {db close} + sqlite3_shutdown + sqlite3_config_pagecache 512 5 + sqlite3_config_scratch 1000 1 + sqlite3_initialize + autoinstall_test_functions +} -shutdown { + catch {db close} + sqlite3_shutdown + sqlite3_config_pagecache 0 0 + sqlite3_config_scratch 0 0 + sqlite3_initialize + autoinstall_test_functions +} + +# Run all tests with the lookaside allocator disabled. +# +test_suite "nolookaside" -description { + OOM tests with lookaside disabled +} -initialize { + catch {db close} + sqlite3_shutdown + sqlite3_config_lookaside 0 0 + sqlite3_initialize + autoinstall_test_functions +} -shutdown { + catch {db close} + sqlite3_shutdown + sqlite3_config_lookaside 100 500 + sqlite3_initialize + autoinstall_test_functions +} -files $::allquicktests + +# Run some tests in SQLITE_CONFIG_SINGLETHREAD mode. +# +test_suite "singlethread" -description { + Tests run in SQLITE_CONFIG_SINGLETHREAD mode +} -initialize { + catch {db close} + sqlite3_shutdown + catch {sqlite3_config singlethread} + sqlite3_initialize + autoinstall_test_functions +} -files { + delete.test delete2.test insert.test rollback.test select1.test + select2.test trans.test update.test vacuum.test types.test + types2.test types3.test +} -shutdown { + catch {db close} + sqlite3_shutdown + catch {sqlite3_config serialized} + sqlite3_initialize + autoinstall_test_functions +} + +test_suite "nomutex" -description { + Tests run with the SQLITE_OPEN_MULTITHREADED flag passed to sqlite3_open(). +} -initialize { + rename sqlite3 sqlite3_nomutex + proc sqlite3 {args} { + if {[string range [lindex $args 0] 0 0] ne "-"} { + lappend args -fullmutex 0 -nomutex 1 + } + uplevel [concat sqlite3_nomutex $args] + } +} -files { + delete.test delete2.test insert.test rollback.test select1.test + select2.test trans.test update.test vacuum.test types.test + types2.test types3.test +} -shutdown { + rename sqlite3 {} + rename sqlite3_nomutex sqlite3 +} + +# Run some tests in SQLITE_CONFIG_MULTITHREAD mode. +# +test_suite "multithread" -description { + Tests run in SQLITE_CONFIG_MULTITHREAD mode +} -initialize { + catch {db close} + sqlite3_shutdown + catch {sqlite3_config multithread} + sqlite3_initialize + autoinstall_test_functions +} -files { + delete.test delete2.test insert.test rollback.test select1.test + select2.test trans.test update.test vacuum.test types.test + types2.test types3.test +} -shutdown { + catch {db close} + sqlite3_shutdown + catch {sqlite3_config serialized} + sqlite3_initialize + autoinstall_test_functions +} + +# Run some tests in SQLITE_OPEN_FULLMUTEX mode. +# +test_suite "fullmutex" -description { + Tests run in SQLITE_OPEN_FULLMUTEX mode +} -initialize { + rename sqlite3 sqlite3_fullmutex + proc sqlite3 {args} { + if {[string range [lindex $args 0] 0 0] ne "-"} { + lappend args -nomutex 0 -fullmutex 1 + } + uplevel [concat sqlite3_fullmutex $args] + } +} -files { + delete.test delete2.test insert.test rollback.test select1.test + select2.test trans.test update.test vacuum.test types.test + types2.test types3.test +} -shutdown { + rename sqlite3 {} + rename sqlite3_fullmutex sqlite3 +} + +# Run some tests using the "onefile" demo. +# +test_suite "onefile" -description { + Run some tests using the "test_onefile.c" demo +} -initialize { + rename sqlite3 sqlite3_onefile + proc sqlite3 {args} { + if {[string range [lindex $args 0] 0 0] ne "-"} { + lappend args -vfs fs + } + uplevel [concat sqlite3_onefile $args] + } +} -files { + conflict.test insert.test insert2.test insert3.test + rollback.test select1.test select2.test select3.test +} -shutdown { + rename sqlite3 {} + rename sqlite3_onefile sqlite3 +} + +# Run some tests using UTF-16 databases. +# +test_suite "utf16" -description { + Run tests using UTF-16 databases +} -presql { + pragma encoding = 'UTF-16' +} -files { + alter.test alter3.test + analyze.test analyze3.test analyze4.test analyze5.test analyze6.test + analyze7.test analyze8.test analyze9.test analyzeA.test analyzeB.test + auth.test bind.test blob.test capi2.test capi3.test collate1.test + collate2.test collate3.test collate4.test collate5.test collate6.test + conflict.test date.test delete.test expr.test fkey1.test func.test + hook.test index.test insert2.test insert.test interrupt.test in.test + intpkey.test ioerr.test join2.test join.test lastinsert.test + laststmtchanges.test limit.test lock2.test lock.test main.test + memdb.test minmax.test misc1.test misc2.test misc3.test notnull.test + null.test progress.test quote.test rowid.test select1.test select2.test + select3.test select4.test select5.test select6.test sort.test + subselect.test tableapi.test table.test temptable.test + trace.test trigger1.test trigger2.test trigger3.test + trigger4.test types2.test types.test unique.test update.test + vacuum.test view.test where.test +} + +# Run some tests in exclusive locking mode. +# +test_suite "exclusive" -description { + Run tests in exclusive locking mode. +} -presql { + pragma locking_mode = 'exclusive' +} -files { + rollback.test select1.test select2.test + malloc.test ioerr.test +} + +# Run some tests in exclusive locking mode with truncated journals. +# +test_suite "exclusive-truncate" -description { + Run tests in exclusive locking mode and truncate journal mode. +} -presql { + pragma locking_mode = 'exclusive'; + pragma journal_mode = TRUNCATE; +} -files { + delete.test delete2.test insert.test rollback.test select1.test + select2.test update.test malloc.test ioerr.test +} + +# Run some tests in persistent journal mode. +# +test_suite "persistent_journal" -description { + Run tests in persistent-journal mode. +} -presql { + pragma journal_mode = persist +} -files { + delete.test delete2.test insert.test rollback.test select1.test + select2.test trans.test update.test vacuum.test +} + +# Run some tests in truncating journal mode. +# +test_suite "truncate_journal" -description { + Run tests in persistent-journal mode. +} -presql { + pragma journal_mode = truncate +} -files { + delete.test delete2.test insert.test rollback.test select1.test + select2.test trans.test update.test vacuum.test + malloc.test ioerr.test +} + +# Run some error tests in persistent journal mode. +# +test_suite "persistent_journal_error" -description { + Run malloc.test and ioerr.test in persistent-journal mode. +} -presql { + pragma journal_mode = persist +} -files { + malloc.test ioerr.test +} + +# Run some tests in no journal mode. +# +test_suite "no_journal" -description { + Run tests in no-journal mode. +} -presql { + pragma journal_mode = persist +} -files { + delete.test delete2.test insert.test rollback.test select1.test + select2.test trans.test update.test vacuum.test +} + +# Run some error tests in no journal mode. +# +test_suite "no_journal_error" -description { + Run malloc.test and ioerr.test in no-journal mode. +} -presql { + pragma journal_mode = persist +} -files { + malloc.test ioerr.test +} + +# Run some crash-tests in autovacuum mode. +# +test_suite "autovacuum_crash" -description { + Run crash.test in autovacuum mode. +} -presql { + pragma auto_vacuum = 1 +} -files crash.test + +# Run some ioerr-tests in autovacuum mode. +# +test_suite "autovacuum_ioerr" -description { + Run ioerr.test in autovacuum mode. +} -presql { + pragma auto_vacuum = 1 +} -files ioerr.test + +# Run tests with an in-memory journal. +# +test_suite "inmemory_journal" -description { + Run tests with an in-memory journal file. +} -presql { + pragma journal_mode = 'memory' +} -files [test_set $::allquicktests -exclude { + # Exclude all tests that simulate IO errors. + autovacuum_ioerr2.test incrvacuum_ioerr.test ioerr.test + ioerr.test ioerr2.test ioerr3.test ioerr4.test ioerr5.test + vacuum3.test incrblob_err.test diskfull.test backup_ioerr.test + e_fts3.test fts3cov.test fts3malloc.test fts3rnd.test + fts3snippet.test + + # Exclude test scripts that use tcl IO to access journal files or count + # the number of fsync() calls. + pager.test exclusive.test jrnlmode.test sync.test misc1.test + journal1.test conflict.test crash8.test tkt3457.test io.test + journal3.test 8_3_names.test + + pager1.test async4.test corrupt.test filefmt.test pager2.test + corrupt5.test corruptA.test pageropt.test + + # Exclude stmt.test, which expects sub-journals to use temporary files. + stmt.test + + zerodamage.test + + # WAL mode is different. + wal* tkt-2d1a5c67d.test backcompat.test +}] + +ifcapable mem3 { + test_suite "memsys3" -description { + Run tests using the allocator in mem3.c. + } -files [test_set $::allquicktests -exclude { + autovacuum.test delete3.test manydb.test + bigrow.test incrblob2.test memdb.test + bitvec.test index2.test memsubsys1.test + capi3c.test ioerr.test memsubsys2.test + capi3.test join3.test pagesize.test + collate5.test limit.test backup_ioerr.test + backup_malloc.test + }] -initialize { + catch {db close} + sqlite3_reset_auto_extension + sqlite3_shutdown + sqlite3_config_heap 25000000 0 + sqlite3_config_lookaside 0 0 + ifcapable mem5 { + # If both memsys3 and memsys5 are enabled in the build, the call to + # [sqlite3_config_heap] will initialize the system to use memsys5. + # The following overrides this preference and installs the memsys3 + # allocator. + sqlite3_install_memsys3 + } + install_malloc_faultsim 1 + sqlite3_initialize + autoinstall_test_functions + } -shutdown { + catch {db close} + sqlite3_shutdown + sqlite3_config_heap 0 0 + sqlite3_config_lookaside 100 500 + install_malloc_faultsim 1 + sqlite3_initialize + autoinstall_test_functions + } +} + +ifcapable mem5 { + test_suite "memsys5" -description { + Run tests using the allocator in mem5.c. + } -files [test_set $::allquicktests -exclude { + autovacuum.test delete3.test manydb.test + bigrow.test incrblob2.test memdb.test + bitvec.test index2.test memsubsys1.test + capi3c.test ioerr.test memsubsys2.test + capi3.test join3.test pagesize.test + collate5.test limit.test zeroblob.test + }] -initialize { + catch {db close} + sqlite3_shutdown + sqlite3_config_heap 25000000 64 + sqlite3_config_lookaside 0 0 + install_malloc_faultsim 1 + sqlite3_initialize + autoinstall_test_functions + } -shutdown { + catch {db close} + sqlite3_shutdown + sqlite3_config_heap 0 0 + sqlite3_config_lookaside 100 500 + install_malloc_faultsim 1 + sqlite3_initialize + autoinstall_test_functions + } + + test_suite "memsys5-2" -description { + Run tests using the allocator in mem5.c in a different configuration. + } -files { + select1.test + } -initialize { + catch {db close} + sqlite3_shutdown + sqlite3_config_memstatus 0 + sqlite3_config_heap 40000000 16 + sqlite3_config_lookaside 0 0 + install_malloc_faultsim 1 + sqlite3_initialize + autoinstall_test_functions + } -shutdown { + catch {db close} + sqlite3_shutdown + sqlite3_config_heap 0 0 + sqlite3_config_lookaside 100 500 + install_malloc_faultsim 1 + sqlite3_initialize + autoinstall_test_functions + } +} + +ifcapable threadsafe { + test_suite "no_mutex_try" -description { + The sqlite3_mutex_try() interface always fails + } -files [ + test_set $::allquicktests -exclude mutex1.test mutex2.test + ] -initialize { + catch {db close} + sqlite3_shutdown + install_mutex_counters 1 + set ::disable_mutex_try 1 + sqlite3_initialize + autoinstall_test_functions + } -shutdown { + catch {db close} + sqlite3_shutdown + install_mutex_counters 0 + sqlite3_initialize + autoinstall_test_functions + } +} + +# run_tests "crash_safe_append" -description { +# Run crash.test with persistent journals on a SAFE_APPEND file-system. +# } -initialize { +# rename crashsql sa_crashsql +# proc crashsql {args} { +# set options [lrange $args 0 [expr {[llength $args]-2}]] +# lappend options -char safe_append +# set sql [lindex $args end] +# lappend options " +# PRAGMA journal_mode=persistent; +# $sql +# " +# set fd [open test.db-journal w] +# puts $fd [string repeat 1234567890 100000] +# close $fd +# eval sa_crashsql $options +# } +# } -shutdown { +# rename crashsql {} +# rename sa_crashsql crashsql +# } -files crash.test + +test_suite "safe_append" -description { + Run some tests on a SAFE_APPEND file-system. +} -initialize { + rename sqlite3 sqlite3_safeappend + proc sqlite3 {args} { + if {[string range [lindex $args 0] 0 0] ne "-"} { + lappend args -vfs devsym + } + uplevel [concat sqlite3_safeappend $args] + } + sqlite3_simulate_device -char safe_append +} -shutdown { + rename sqlite3 {} + rename sqlite3_shutdown sqlite3 +} -files [ + test_set $::allquicktests shared_err.test -exclude async3.test +] + +# The set of tests to run on the alternative-pcache +set perm-alt-pcache-testset { + async.test + attach.test + delete.test delete2.test + index.test + insert.test insert2.test + join.test join2.test + rollback.test + select1.test select2.test + trans.test + update.test +} + +foreach discard_rate {0 10 50 90 100} { + test_suite "pcache${discard_rate}" -description " + Alternative pcache implementation with ${discard_rate}% random discard + " -initialize " + catch {db close} + sqlite3_shutdown + sqlite3_config_alt_pcache 1 $discard_rate 1 + sqlite3_initialize + autoinstall_test_functions + " -shutdown { + catch {db close} + sqlite3_shutdown + sqlite3_config_alt_pcache 0 0 0 + sqlite3_config_lookaside 100 500 + install_malloc_faultsim 1 + sqlite3_initialize + autoinstall_test_functions + } -files ${perm-alt-pcache-testset} +} + +test_suite "journaltest" -description { + Check that pages are synced before being written (test_journal.c). +} -initialize { + catch {db close} + register_jt_vfs -default "" +} -shutdown { + unregister_jt_vfs +} -files [test_set $::allquicktests -exclude { + wal* incrvacuum.test ioerr.test corrupt4.test io.test crash8.test + async4.test bigfile.test backcompat.test +}] + +if {[info commands register_demovfs] != ""} { + test_suite "demovfs" -description { + Check that the demovfs (code in test_demovfs.c) more or less works. + } -initialize { + register_demovfs + } -shutdown { + unregister_demovfs + } -files { + insert.test insert2.test insert3.test rollback.test + select1.test select2.test select3.test + } +} + +test_suite "wal" -description { + Run tests with journal_mode=WAL +} -initialize { + set ::G(savepoint6_iterations) 100 +} -shutdown { + unset -nocomplain ::G(savepoint6_iterations) +} -files { + savepoint.test savepoint2.test savepoint6.test + trans.test avtrans.test + + fts3aa.test fts3ab.test fts3ac.test fts3ad.test + fts3ae.test fts3af.test fts3ag.test fts3ah.test + fts3ai.test fts3aj.test fts3ak.test fts3al.test + fts3am.test fts3an.test fts3ao.test fts3b.test + fts3c.test fts3d.test fts3e.test fts3query.test +} + +test_suite "rtree" -description { + All R-tree related tests. Provides coverage of source file rtree.c. +} -files [glob -nocomplain $::testdir/../ext/rtree/*.test] + +test_suite "no_optimization" -description { + Run test scripts with optimizations disabled using the + sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS) interface. +} -files { + where.test where2.test where3.test where4.test where5.test + where6.test where7.test where8.test where9.test + whereA.test whereB.test wherelimit.test + select1.test select2.test select3.test select4.test select5.test + select7.test select8.test selectA.test selectC.test +} -dbconfig { + optimization_control $::dbhandle all 0 +} + +test_suite "prepare" -description { + Run tests with the db connection using sqlite3_prepare() instead of _v2(). +} -dbconfig { + db_use_legacy_prepare $::dbhandle 1 + #$::dbhandle cache size 0 +} -files [ + test_set $allquicktests -exclude *malloc* *ioerr* *fault* +] + +# End of tests +############################################################################# + +# run_tests NAME OPTIONS +# +# where available options are: +# +# -description TITLE +# -initialize SCRIPT +# -shutdown SCRIPT +# -presql SQL +# -files LIST-OF-FILES +# -prefix NAME +# +proc run_tests {name args} { + array set options $args + + set ::G(perm:name) $name + set ::G(perm:prefix) $options(-prefix) + set ::G(perm:presql) $options(-presql) + set ::G(isquick) 1 + set ::G(perm:dbconfig) $options(-dbconfig) + + uplevel $options(-initialize) + + foreach file [lsort $options(-files)] { + if {[file tail $file] == $file} { set file [file join $::testdir $file] } + slave_test_file $file + } + + uplevel $options(-shutdown) + + unset ::G(perm:name) + unset ::G(perm:prefix) + unset ::G(perm:presql) + unset ::G(perm:dbconfig) +} + +proc run_test_suite {name} { + if {[info exists ::testspec($name)]==0} { + error "No such test suite: $name" + } + uplevel run_tests $name $::testspec($name) +} + +proc help {} { + puts "Usage: $::argv0 TESTSUITE ?TESTFILE?" + puts "" + puts "Available test-suites are:" + foreach k $::testsuitelist { + if {[info exists ::testspec($k)]==0} { + puts " ----------------------------------------" + puts "" + } else { + array set o $::testspec($k) + puts "Test suite: \"$k\"" + set d [string trim $o(-description)] + set d [regsub {\n *} $d "\n "] + puts " $d" + puts "" + } + } + exit -1 +} + +if {[info script] == $argv0} { + proc main {argv} { + if {[llength $argv]==0} { + help + } else { + set suite [lindex $argv 0] + if {[info exists ::testspec($suite)]==0} help + set extra "" + if {[llength $argv]>1} { set extra [list -files [lrange $argv 1 end]] } + eval run_tests $suite $::testspec($suite) $extra + } + } + main $argv + finish_test +} diff --git a/components/external/SQLite-3.8.1/test/pragma.test b/components/external/SQLite-3.8.1/test/pragma.test new file mode 100644 index 0000000000000000000000000000000000000000..a6d198eb692ae422ec84bebf255fd682fdaa09d7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pragma.test @@ -0,0 +1,1683 @@ +# 2002 March 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the PRAGMA command. +# +# $Id: pragma.test,v 1.73 2009/01/12 14:01:45 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix pragma + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Test organization: +# +# pragma-1.*: Test cache_size, default_cache_size and synchronous on main db. +# pragma-2.*: Test synchronous on attached db. +# pragma-3.*: Test detection of table/index inconsistency by integrity_check. +# pragma-4.*: Test cache_size and default_cache_size on attached db. +# pragma-5.*: Test that pragma synchronous may not be used inside of a +# transaction. +# pragma-6.*: Test schema-query pragmas. +# pragma-7.*: Miscellaneous tests. +# pragma-8.*: Test user_version and schema_version pragmas. +# pragma-9.*: Test temp_store and temp_store_directory. +# pragma-10.*: Test the count_changes pragma in the presence of triggers. +# pragma-11.*: Test the collation_list pragma. +# pragma-14.*: Test the page_count pragma. +# pragma-15.*: Test that the value set using the cache_size pragma is not +# reset when the schema is reloaded. +# pragma-16.*: Test proxy locking +# pragma-20.*: Test data_store_directory. +# pragma-22.*: Test that "PRAGMA [db].integrity_check" respects the "db" +# directive - if it is present. +# + +ifcapable !pragma { + finish_test + return +} + +# Delete the preexisting database to avoid the special setup +# that the "all.test" script does. +# +db close +delete_file test.db test.db-journal +delete_file test3.db test3.db-journal +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] + + +ifcapable pager_pragmas { +set DFLT_CACHE_SZ [db one {PRAGMA default_cache_size}] +set TEMP_CACHE_SZ [db one {PRAGMA temp.default_cache_size}] +do_test pragma-1.1 { + execsql { + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ 2] +do_test pragma-1.2 { + execsql { + PRAGMA synchronous=OFF; + PRAGMA cache_size=1234; + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} [list 1234 $DFLT_CACHE_SZ 0] +do_test pragma-1.3 { + db close + sqlite3 db test.db + execsql { + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ 2] +do_test pragma-1.4 { + execsql { + PRAGMA synchronous=OFF; + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ 0] +do_test pragma-1.5 { + execsql { + PRAGMA cache_size=-4321; + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} [list -4321 $DFLT_CACHE_SZ 0] +do_test pragma-1.6 { + execsql { + PRAGMA synchronous=ON; + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} [list -4321 $DFLT_CACHE_SZ 1] +do_test pragma-1.7 { + db close + sqlite3 db test.db + execsql { + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ 2] +do_test pragma-1.8 { + execsql { + PRAGMA default_cache_size=-123; + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} {123 123 2} +do_test pragma-1.9.1 { + db close + sqlite3 db test.db; set ::DB [sqlite3_connection_pointer db] + execsql { + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} {123 123 2} +ifcapable vacuum { + do_test pragma-1.9.2 { + execsql { + VACUUM; + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } + } {123 123 2} +} +do_test pragma-1.10 { + execsql { + PRAGMA synchronous=NORMAL; + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} {123 123 1} +do_test pragma-1.11 { + execsql { + PRAGMA synchronous=FULL; + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} {123 123 2} +do_test pragma-1.12 { + db close + sqlite3 db test.db; set ::DB [sqlite3_connection_pointer db] + execsql { + PRAGMA cache_size; + PRAGMA default_cache_size; + PRAGMA synchronous; + } +} {123 123 2} + +# Make sure the pragma handler understands numeric values in addition +# to keywords like "off" and "full". +# +do_test pragma-1.13 { + execsql { + PRAGMA synchronous=0; + PRAGMA synchronous; + } +} {0} +do_test pragma-1.14 { + execsql { + PRAGMA synchronous=2; + PRAGMA synchronous; + } +} {2} +} ;# ifcapable pager_pragmas + +# Test turning "flag" pragmas on and off. +# +ifcapable debug { + # Pragma "vdbe_listing" is only available if compiled with SQLITE_DEBUG + # + do_test pragma-1.15 { + execsql { + PRAGMA vdbe_listing=YES; + PRAGMA vdbe_listing; + } + } {1} + do_test pragma-1.16 { + execsql { + PRAGMA vdbe_listing=NO; + PRAGMA vdbe_listing; + } + } {0} +} + +do_test pragma-1.17 { + execsql { + PRAGMA parser_trace=ON; + PRAGMA parser_trace=OFF; + } +} {} +do_test pragma-1.18 { + execsql { + PRAGMA bogus = -1234; -- Parsing of negative values + } +} {} + +# Test modifying the safety_level of an attached database. +ifcapable pager_pragmas&&attach { + do_test pragma-2.1 { + forcedelete test2.db + forcedelete test2.db-journal + execsql { + ATTACH 'test2.db' AS aux; + } + } {} + do_test pragma-2.2 { + execsql { + pragma aux.synchronous; + } + } {2} + do_test pragma-2.3 { + execsql { + pragma aux.synchronous = OFF; + pragma aux.synchronous; + pragma synchronous; + } + } {0 2} + do_test pragma-2.4 { + execsql { + pragma aux.synchronous = ON; + pragma synchronous; + pragma aux.synchronous; + } + } {2 1} +} ;# ifcapable pager_pragmas + +# Construct a corrupted index and make sure the integrity_check +# pragma finds it. +# +# These tests won't work if the database is encrypted +# +do_test pragma-3.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum=OFF; + BEGIN; + CREATE TABLE t2(a,b,c); + CREATE INDEX i2 ON t2(a); + INSERT INTO t2 VALUES(11,2,3); + INSERT INTO t2 VALUES(22,3,4); + COMMIT; + SELECT rowid, * from t2; + } +} {1 11 2 3 2 22 3 4} +ifcapable attach { + if {![sqlite3 -has-codec] && $sqlite_options(integrityck)} { + do_test pragma-3.2 { + db eval {SELECT rootpage FROM sqlite_master WHERE name='i2'} break + set pgsz [db eval {PRAGMA page_size}] + # overwrite the header on the rootpage of the index in order to + # make the index appear to be empty. + # + set offset [expr {$pgsz*($rootpage-1)}] + hexio_write test.db $offset 0a00000000040000000000 + db close + sqlite3 db test.db + execsql {PRAGMA integrity_check} + } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + do_test pragma-3.3 { + execsql {PRAGMA integrity_check=1} + } {{rowid 1 missing from index i2}} + do_test pragma-3.4 { + execsql { + ATTACH DATABASE 'test.db' AS t2; + PRAGMA integrity_check + } + } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + do_test pragma-3.5 { + execsql { + PRAGMA integrity_check=4 + } + } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2}} + do_test pragma-3.6 { + execsql { + PRAGMA integrity_check=xyz + } + } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + do_test pragma-3.7 { + execsql { + PRAGMA integrity_check=0 + } + } {{rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + + # Add additional corruption by appending unused pages to the end of + # the database file testerr.db + # + do_test pragma-3.8 { + execsql {DETACH t2} + forcedelete testerr.db testerr.db-journal + set out [open testerr.db w] + fconfigure $out -translation binary + set in [open test.db r] + fconfigure $in -translation binary + puts -nonewline $out [read $in] + seek $in 0 + puts -nonewline $out [read $in] + close $in + close $out + hexio_write testerr.db 28 00000000 + execsql {REINDEX t2} + execsql {PRAGMA integrity_check} + } {ok} + do_test pragma-3.8.1 { + execsql {PRAGMA quick_check} + } {ok} + do_test pragma-3.8.2 { + execsql {PRAGMA QUICK_CHECK} + } {ok} + do_test pragma-3.9 { + execsql { + ATTACH 'testerr.db' AS t2; + PRAGMA integrity_check + } + } {{*** in database t2 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + do_test pragma-3.10 { + execsql { + PRAGMA integrity_check=1 + } + } {{*** in database t2 *** +Page 4 is never used}} + do_test pragma-3.11 { + execsql { + PRAGMA integrity_check=5 + } + } {{*** in database t2 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2}} + do_test pragma-3.12 { + execsql { + PRAGMA integrity_check=4 + } + } {{*** in database t2 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used} {rowid 1 missing from index i2}} + do_test pragma-3.13 { + execsql { + PRAGMA integrity_check=3 + } + } {{*** in database t2 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used}} + do_test pragma-3.14 { + execsql { + PRAGMA integrity_check(2) + } + } {{*** in database t2 *** +Page 4 is never used +Page 5 is never used}} + do_test pragma-3.15 { + execsql { + ATTACH 'testerr.db' AS t3; + PRAGMA integrity_check + } + } {{*** in database t2 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2}} + do_test pragma-3.16 { + execsql { + PRAGMA integrity_check(10) + } + } {{*** in database t2 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used} {rowid 1 missing from index i2}} + do_test pragma-3.17 { + execsql { + PRAGMA integrity_check=8 + } + } {{*** in database t2 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used} {rowid 1 missing from index i2} {rowid 2 missing from index i2} {wrong # of entries in index i2} {*** in database t3 *** +Page 4 is never used +Page 5 is never used}} + do_test pragma-3.18 { + execsql { + PRAGMA integrity_check=4 + } + } {{*** in database t2 *** +Page 4 is never used +Page 5 is never used +Page 6 is never used} {rowid 1 missing from index i2}} + } + do_test pragma-3.19 { + catch {db close} + forcedelete test.db test.db-journal + sqlite3 db test.db + db eval {PRAGMA integrity_check} + } {ok} +} +#exit + +# Test modifying the cache_size of an attached database. +ifcapable pager_pragmas&&attach { +do_test pragma-4.1 { + execsql { + ATTACH 'test2.db' AS aux; + pragma aux.cache_size; + pragma aux.default_cache_size; + } +} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ] +do_test pragma-4.2 { + execsql { + pragma aux.cache_size = 50; + pragma aux.cache_size; + pragma aux.default_cache_size; + } +} [list 50 $DFLT_CACHE_SZ] +do_test pragma-4.3 { + execsql { + pragma aux.default_cache_size = 456; + pragma aux.cache_size; + pragma aux.default_cache_size; + } +} {456 456} +do_test pragma-4.4 { + execsql { + pragma cache_size; + pragma default_cache_size; + } +} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ] +do_test pragma-4.5 { + execsql { + DETACH aux; + ATTACH 'test3.db' AS aux; + pragma aux.cache_size; + pragma aux.default_cache_size; + } +} [list $DFLT_CACHE_SZ $DFLT_CACHE_SZ] +do_test pragma-4.6 { + execsql { + DETACH aux; + ATTACH 'test2.db' AS aux; + pragma aux.cache_size; + pragma aux.default_cache_size; + } +} {456 456} +} ;# ifcapable pager_pragmas + +# Test that modifying the sync-level in the middle of a transaction is +# disallowed. +ifcapable pager_pragmas { +do_test pragma-5.0 { + execsql { + pragma synchronous; + } +} {2} +do_test pragma-5.1 { + catchsql { + BEGIN; + pragma synchronous = OFF; + } +} {1 {Safety level may not be changed inside a transaction}} +do_test pragma-5.2 { + execsql { + pragma synchronous; + } +} {2} +catchsql {COMMIT;} +} ;# ifcapable pager_pragmas + +# Test schema-query pragmas +# +ifcapable schema_pragmas { +ifcapable tempdb&&attach { + do_test pragma-6.1 { + set res {} + execsql {SELECT * FROM sqlite_temp_master} + foreach {idx name file} [execsql {pragma database_list}] { + lappend res $idx $name + } + set res + } {0 main 1 temp 2 aux} +} +do_test pragma-6.2 { + execsql { + CREATE TABLE t2(a,b,c); + pragma table_info(t2) + } +} {0 a {} 0 {} 0 1 b {} 0 {} 0 2 c {} 0 {} 0} +do_test pragma-6.2.1 { + execsql { + pragma table_info; + } +} {} +db nullvalue <> +do_test pragma-6.2.2 { + execsql { + CREATE TABLE t5( + a TEXT DEFAULT CURRENT_TIMESTAMP, + b DEFAULT (5+3), + c TEXT, + d INTEGER DEFAULT NULL, + e TEXT DEFAULT '', + UNIQUE(b,c,d), + PRIMARY KEY(e,b,c) + ); + PRAGMA table_info(t5); + } +} {0 a TEXT 0 CURRENT_TIMESTAMP 0 1 b {} 0 5+3 2 2 c TEXT 0 <> 3 3 d INTEGER 0 NULL 0 4 e TEXT 0 '' 1} +db nullvalue {} +do_test pragma-6.2.3 { + execsql { + CREATE TABLE t2_3(a,b INTEGER PRIMARY KEY,c); + pragma table_info(t2_3) + } +} {0 a {} 0 {} 0 1 b INTEGER 0 {} 1 2 c {} 0 {} 0} +ifcapable {foreignkey} { + do_test pragma-6.3.1 { + execsql { + CREATE TABLE t3(a int references t2(b), b UNIQUE); + pragma foreign_key_list(t3); + } + } {0 0 t2 a b {NO ACTION} {NO ACTION} NONE} + do_test pragma-6.3.2 { + execsql { + pragma foreign_key_list; + } + } {} + do_test pragma-6.3.3 { + execsql { + pragma foreign_key_list(t3_bogus); + } + } {} + do_test pragma-6.3.4 { + execsql { + pragma foreign_key_list(t5); + } + } {} + do_test pragma-6.4 { + execsql { + pragma index_list(t3); + } + } {0 sqlite_autoindex_t3_1 1} +} +ifcapable {!foreignkey} { + execsql {CREATE TABLE t3(a,b UNIQUE)} +} +do_test pragma-6.5.1 { + execsql { + CREATE INDEX t3i1 ON t3(a,b); + pragma index_info(t3i1); + } +} {0 0 a 1 1 b} +do_test pragma-6.5.2 { + execsql { + pragma index_info(t3i1_bogus); + } +} {} + +ifcapable tempdb { + # Test for ticket #3320. When a temp table of the same name exists, make + # sure the schema of the main table can still be queried using + # "pragma table_info": + do_test pragma-6.6.1 { + execsql { + CREATE TABLE trial(col_main); + CREATE TEMP TABLE trial(col_temp); + } + } {} + do_test pragma-6.6.2 { + execsql { + PRAGMA table_info(trial); + } + } {0 col_temp {} 0 {} 0} + do_test pragma-6.6.3 { + execsql { + PRAGMA temp.table_info(trial); + } + } {0 col_temp {} 0 {} 0} + do_test pragma-6.6.4 { + execsql { + PRAGMA main.table_info(trial); + } + } {0 col_main {} 0 {} 0} +} + +do_test pragma-6.7 { + execsql { + CREATE TABLE test_table( + one INT NOT NULL DEFAULT -1, + two text, + three VARCHAR(45, 65) DEFAULT 'abcde', + four REAL DEFAULT X'abcdef', + five DEFAULT CURRENT_TIME + ); + PRAGMA table_info(test_table); + } +} [concat \ + {0 one INT 1 -1 0} \ + {1 two text 0 {} 0} \ + {2 three {VARCHAR(45, 65)} 0 'abcde' 0} \ + {3 four REAL 0 X'abcdef' 0} \ + {4 five {} 0 CURRENT_TIME 0} \ +] +} ;# ifcapable schema_pragmas +# Miscellaneous tests +# +ifcapable schema_pragmas { +do_test pragma-7.1.1 { + # Make sure a pragma knows to read the schema if it needs to + db close + sqlite3 db test.db + execsql { + pragma index_list(t3); + } +} {0 t3i1 0 1 sqlite_autoindex_t3_1 1} +do_test pragma-7.1.2 { + execsql { + pragma index_list(t3_bogus); + } +} {} +} ;# ifcapable schema_pragmas +ifcapable {utf16} { + if {[permutation] == ""} { + do_test pragma-7.2 { + db close + sqlite3 db test.db + catchsql { + pragma encoding=bogus; + } + } {1 {unsupported encoding: bogus}} + } +} +ifcapable tempdb { + do_test pragma-7.3 { + db close + sqlite3 db test.db + execsql { + pragma lock_status; + } + } {main unlocked temp closed} +} else { + do_test pragma-7.3 { + db close + sqlite3 db test.db + execsql { + pragma lock_status; + } + } {main unlocked} +} + + +#---------------------------------------------------------------------- +# Test cases pragma-8.* test the "PRAGMA schema_version" and "PRAGMA +# user_version" statements. +# +# pragma-8.1: PRAGMA schema_version +# pragma-8.2: PRAGMA user_version +# + +ifcapable schema_version { + +# First check that we can set the schema version and then retrieve the +# same value. +do_test pragma-8.1.1 { + execsql { + PRAGMA schema_version = 105; + } +} {} +do_test pragma-8.1.2 { + execsql2 { + PRAGMA schema_version; + } +} {schema_version 105} +do_test pragma-8.1.3 { + execsql { + PRAGMA schema_version = 106; + } +} {} +do_test pragma-8.1.4 { + execsql { + PRAGMA schema_version; + } +} 106 + +# Check that creating a table modifies the schema-version (this is really +# to verify that the value being read is in fact the schema version). +do_test pragma-8.1.5 { + execsql { + CREATE TABLE t4(a, b, c); + INSERT INTO t4 VALUES(1, 2, 3); + SELECT * FROM t4; + } +} {1 2 3} +do_test pragma-8.1.6 { + execsql { + PRAGMA schema_version; + } +} 107 + +# Now open a second connection to the database. Ensure that changing the +# schema-version using the first connection forces the second connection +# to reload the schema. This has to be done using the C-API test functions, +# because the TCL API accounts for SCHEMA_ERROR and retries the query. +do_test pragma-8.1.7 { + sqlite3 db2 test.db; set ::DB2 [sqlite3_connection_pointer db2] + execsql { + SELECT * FROM t4; + } db2 +} {1 2 3} +do_test pragma-8.1.8 { + execsql { + PRAGMA schema_version = 108; + } +} {} +do_test pragma-8.1.9 { + set ::STMT [sqlite3_prepare $::DB2 "SELECT * FROM t4" -1 DUMMY] + sqlite3_step $::STMT +} SQLITE_ERROR +do_test pragma-8.1.10 { + sqlite3_finalize $::STMT +} SQLITE_SCHEMA + +# Make sure the schema-version can be manipulated in an attached database. +forcedelete test2.db +forcedelete test2.db-journal +ifcapable attach { + do_test pragma-8.1.11 { + execsql { + ATTACH 'test2.db' AS aux; + CREATE TABLE aux.t1(a, b, c); + PRAGMA aux.schema_version = 205; + } + } {} + do_test pragma-8.1.12 { + execsql { + PRAGMA aux.schema_version; + } + } 205 +} +do_test pragma-8.1.13 { + execsql { + PRAGMA schema_version; + } +} 108 + +# And check that modifying the schema-version in an attached database +# forces the second connection to reload the schema. +ifcapable attach { + do_test pragma-8.1.14 { + sqlite3 db2 test.db; set ::DB2 [sqlite3_connection_pointer db2] + execsql { + ATTACH 'test2.db' AS aux; + SELECT * FROM aux.t1; + } db2 + } {} + do_test pragma-8.1.15 { + execsql { + PRAGMA aux.schema_version = 206; + } + } {} + do_test pragma-8.1.16 { + set ::STMT [sqlite3_prepare $::DB2 "SELECT * FROM aux.t1" -1 DUMMY] + sqlite3_step $::STMT + } SQLITE_ERROR + do_test pragma-8.1.17 { + sqlite3_finalize $::STMT + } SQLITE_SCHEMA + do_test pragma-8.1.18 { + db2 close + } {} +} + +# Now test that the user-version can be read and written (and that we aren't +# accidentally manipulating the schema-version instead). +do_test pragma-8.2.1 { + execsql2 { + PRAGMA user_version; + } +} {user_version 0} +do_test pragma-8.2.2 { + execsql { + PRAGMA user_version = 2; + } +} {} +do_test pragma-8.2.3.1 { + execsql2 { + PRAGMA user_version; + } +} {user_version 2} +do_test pragma-8.2.3.2 { + db close + sqlite3 db test.db + execsql { + PRAGMA user_version; + } +} {2} +do_test pragma-8.2.4.1 { + execsql { + PRAGMA schema_version; + } +} {108} +ifcapable vacuum { + do_test pragma-8.2.4.2 { + execsql { + VACUUM; + PRAGMA user_version; + } + } {2} + do_test pragma-8.2.4.3 { + execsql { + PRAGMA schema_version; + } + } {109} +} + +ifcapable attach { + db eval {ATTACH 'test2.db' AS aux} + + # Check that the user-version in the auxilary database can be manipulated ( + # and that we aren't accidentally manipulating the same in the main db). + do_test pragma-8.2.5 { + execsql { + PRAGMA aux.user_version; + } + } {0} + do_test pragma-8.2.6 { + execsql { + PRAGMA aux.user_version = 3; + } + } {} + do_test pragma-8.2.7 { + execsql { + PRAGMA aux.user_version; + } + } {3} + do_test pragma-8.2.8 { + execsql { + PRAGMA main.user_version; + } + } {2} + + # Now check that a ROLLBACK resets the user-version if it has been modified + # within a transaction. + do_test pragma-8.2.9 { + execsql { + BEGIN; + PRAGMA aux.user_version = 10; + PRAGMA user_version = 11; + } + } {} + do_test pragma-8.2.10 { + execsql { + PRAGMA aux.user_version; + } + } {10} + do_test pragma-8.2.11 { + execsql { + PRAGMA main.user_version; + } + } {11} + do_test pragma-8.2.12 { + execsql { + ROLLBACK; + PRAGMA aux.user_version; + } + } {3} + do_test pragma-8.2.13 { + execsql { + PRAGMA main.user_version; + } + } {2} +} + +# Try a negative value for the user-version +do_test pragma-8.2.14 { + execsql { + PRAGMA user_version = -450; + } +} {} +do_test pragma-8.2.15 { + execsql { + PRAGMA user_version; + } +} {-450} +} ; # ifcapable schema_version + +# Check to see if TEMP_STORE is memory or disk. Return strings +# "memory" or "disk" as appropriate. +# +proc check_temp_store {} { + db eval {CREATE TEMP TABLE IF NOT EXISTS a(b)} + db eval {PRAGMA database_list} { + if {$name=="temp"} { + set bt [btree_from_db db 1] + if {[btree_ismemdb $bt]} { + return "memory" + } + return "disk" + } + } + return "unknown" +} + +# Application_ID +# +do_test pragma-8.3.1 { + execsql { + PRAGMA application_id; + } +} {0} +do_test pragma-8.3.2 { + execsql {PRAGMA Application_ID(12345); PRAGMA application_id;} +} {12345} + +# Test temp_store and temp_store_directory pragmas +# +ifcapable pager_pragmas { +do_test pragma-9.1 { + db close + sqlite3 db test.db + execsql { + PRAGMA temp_store; + } +} {0} +if {$TEMP_STORE<=1} { + do_test pragma-9.1.1 { + check_temp_store + } {disk} +} else { + do_test pragma-9.1.1 { + check_temp_store + } {memory} +} + +do_test pragma-9.2 { + db close + sqlite3 db test.db + execsql { + PRAGMA temp_store=file; + PRAGMA temp_store; + } +} {1} +if {$TEMP_STORE==3} { + # When TEMP_STORE is 3, always use memory regardless of pragma settings. + do_test pragma-9.2.1 { + check_temp_store + } {memory} +} else { + do_test pragma-9.2.1 { + check_temp_store + } {disk} +} + +do_test pragma-9.3 { + db close + sqlite3 db test.db + execsql { + PRAGMA temp_store=memory; + PRAGMA temp_store; + } +} {2} +if {$TEMP_STORE==0} { + # When TEMP_STORE is 0, always use the disk regardless of pragma settings. + do_test pragma-9.3.1 { + check_temp_store + } {disk} +} else { + do_test pragma-9.3.1 { + check_temp_store + } {memory} +} + +do_test pragma-9.4 { + execsql { + PRAGMA temp_store_directory; + } +} {} +ifcapable wsd { + do_test pragma-9.5 { + set pwd [string map {' ''} [file nativename [get_pwd]]] + execsql " + PRAGMA temp_store_directory='$pwd'; + " + } {} + do_test pragma-9.6 { + execsql { + PRAGMA temp_store_directory; + } + } [list [file nativename [get_pwd]]] + do_test pragma-9.7 { + catchsql { + PRAGMA temp_store_directory='/NON/EXISTENT/PATH/FOOBAR'; + } + } {1 {not a writable directory}} + do_test pragma-9.8 { + execsql { + PRAGMA temp_store_directory=''; + } + } {} + if {![info exists TEMP_STORE] || $TEMP_STORE<=1} { + ifcapable tempdb { + do_test pragma-9.9 { + execsql { + PRAGMA temp_store_directory; + PRAGMA temp_store=FILE; + CREATE TEMP TABLE temp_store_directory_test(a integer); + INSERT INTO temp_store_directory_test values (2); + SELECT * FROM temp_store_directory_test; + } + } {2} + do_test pragma-9.10 { + catchsql " + PRAGMA temp_store_directory='$pwd'; + SELECT * FROM temp_store_directory_test; + " + } {1 {no such table: temp_store_directory_test}} + } + } +} +do_test pragma-9.11 { + execsql { + PRAGMA temp_store = 0; + PRAGMA temp_store; + } +} {0} +do_test pragma-9.12 { + execsql { + PRAGMA temp_store = 1; + PRAGMA temp_store; + } +} {1} +do_test pragma-9.13 { + execsql { + PRAGMA temp_store = 2; + PRAGMA temp_store; + } +} {2} +do_test pragma-9.14 { + execsql { + PRAGMA temp_store = 3; + PRAGMA temp_store; + } +} {0} +do_test pragma-9.15 { + catchsql { + BEGIN EXCLUSIVE; + CREATE TEMP TABLE temp_table(t); + INSERT INTO temp_table VALUES('valuable data'); + PRAGMA temp_store = 1; + } +} {1 {temporary storage cannot be changed from within a transaction}} +do_test pragma-9.16 { + execsql { + SELECT * FROM temp_table; + COMMIT; + } +} {{valuable data}} + +do_test pragma-9.17 { + execsql { + INSERT INTO temp_table VALUES('valuable data II'); + SELECT * FROM temp_table; + } +} {{valuable data} {valuable data II}} + +do_test pragma-9.18 { + set rc [catch { + db eval {SELECT t FROM temp_table} { + execsql {pragma temp_store = 1} + } + } msg] + list $rc $msg +} {1 {temporary storage cannot be changed from within a transaction}} + +} ;# ifcapable pager_pragmas + +ifcapable trigger { + +do_test pragma-10.0 { + catchsql { + DROP TABLE main.t1; + } + execsql { + PRAGMA count_changes = 1; + + CREATE TABLE t1(a PRIMARY KEY); + CREATE TABLE t1_mirror(a); + CREATE TABLE t1_mirror2(a); + CREATE TRIGGER t1_bi BEFORE INSERT ON t1 BEGIN + INSERT INTO t1_mirror VALUES(new.a); + END; + CREATE TRIGGER t1_ai AFTER INSERT ON t1 BEGIN + INSERT INTO t1_mirror2 VALUES(new.a); + END; + CREATE TRIGGER t1_bu BEFORE UPDATE ON t1 BEGIN + UPDATE t1_mirror SET a = new.a WHERE a = old.a; + END; + CREATE TRIGGER t1_au AFTER UPDATE ON t1 BEGIN + UPDATE t1_mirror2 SET a = new.a WHERE a = old.a; + END; + CREATE TRIGGER t1_bd BEFORE DELETE ON t1 BEGIN + DELETE FROM t1_mirror WHERE a = old.a; + END; + CREATE TRIGGER t1_ad AFTER DELETE ON t1 BEGIN + DELETE FROM t1_mirror2 WHERE a = old.a; + END; + } +} {} + +do_test pragma-10.1 { + execsql { + INSERT INTO t1 VALUES(randstr(10,10)); + } +} {1} +do_test pragma-10.2 { + execsql { + UPDATE t1 SET a = randstr(10,10); + } +} {1} +do_test pragma-10.3 { + execsql { + DELETE FROM t1; + } +} {1} + +} ;# ifcapable trigger + +ifcapable schema_pragmas { + do_test pragma-11.1 { + execsql2 { + pragma collation_list; + } + } {seq 0 name NOCASE seq 1 name RTRIM seq 2 name BINARY} + do_test pragma-11.2 { + db collate New_Collation blah... + execsql { + pragma collation_list; + } + } {0 New_Collation 1 NOCASE 2 RTRIM 3 BINARY} +} + +ifcapable schema_pragmas&&tempdb { + do_test pragma-12.1 { + sqlite3 db2 test.db + execsql { + PRAGMA temp.table_info('abc'); + } db2 + } {} + db2 close + + do_test pragma-12.2 { + sqlite3 db2 test.db + execsql { + PRAGMA temp.default_cache_size = 200; + PRAGMA temp.default_cache_size; + } db2 + } {200} + db2 close + + do_test pragma-12.3 { + sqlite3 db2 test.db + execsql { + PRAGMA temp.cache_size = 400; + PRAGMA temp.cache_size; + } db2 + } {400} + db2 close +} + +ifcapable bloblit { + +do_test pragma-13.1 { + execsql { + DROP TABLE IF EXISTS t4; + PRAGMA vdbe_trace=on; + PRAGMA vdbe_listing=on; + PRAGMA sql_trace=on; + CREATE TABLE t4(a INTEGER PRIMARY KEY,b); + INSERT INTO t4(b) VALUES(x'0123456789abcdef0123456789abcdef0123456789'); + INSERT INTO t4(b) VALUES(randstr(30,30)); + INSERT INTO t4(b) VALUES(1.23456); + INSERT INTO t4(b) VALUES(NULL); + INSERT INTO t4(b) VALUES(0); + INSERT INTO t4(b) SELECT b||b||b||b FROM t4; + SELECT * FROM t4; + } + execsql { + PRAGMA vdbe_trace=off; + PRAGMA vdbe_listing=off; + PRAGMA sql_trace=off; + } +} {} + +} ;# ifcapable bloblit + +ifcapable pager_pragmas { + db close + forcedelete test.db + sqlite3 db test.db + + do_test pragma-14.1 { + execsql { pragma auto_vacuum = 0 } + execsql { pragma page_count } + } {0} + + do_test pragma-14.2 { + execsql { + CREATE TABLE abc(a, b, c); + PRAGMA page_count; + } + } {2} + do_test pragma-14.2uc { + execsql {pragma PAGE_COUNT} + } {2} + + do_test pragma-14.3 { + execsql { + BEGIN; + CREATE TABLE def(a, b, c); + PRAGMA page_count; + } + } {3} + do_test pragma-14.3uc { + execsql {pragma PAGE_COUNT} + } {3} + + do_test pragma-14.4 { + set page_size [db one {pragma page_size}] + expr [file size test.db] / $page_size + } {2} + + do_test pragma-14.5 { + execsql { + ROLLBACK; + PRAGMA page_count; + } + } {2} + + do_test pragma-14.6 { + forcedelete test2.db + sqlite3 db2 test2.db + execsql { + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(a, b, c); + CREATE TABLE t3(a, b, c); + CREATE TABLE t4(a, b, c); + } db2 + db2 close + execsql { + ATTACH 'test2.db' AS aux; + PRAGMA aux.page_count; + } + } {5} + do_test pragma-14.6uc { + execsql {pragma AUX.PAGE_COUNT} + } {5} +} + +# Test that the value set using the cache_size pragma is not reset when the +# schema is reloaded. +# +ifcapable pager_pragmas { + db close + sqlite3 db test.db + do_test pragma-15.1 { + execsql { + PRAGMA cache_size=59; + PRAGMA cache_size; + } + } {59} + do_test pragma-15.2 { + sqlite3 db2 test.db + execsql { + CREATE TABLE newtable(a, b, c); + } db2 + db2 close + } {} + do_test pragma-15.3 { + # Evaluating this statement will cause the schema to be reloaded (because + # the schema was changed by another connection in pragma-15.2). At one + # point there was a bug that reset the cache_size to its default value + # when this happened. + execsql { SELECT * FROM sqlite_master } + execsql { PRAGMA cache_size } + } {59} +} + +# Reset the sqlite3_temp_directory variable for the next run of tests: +sqlite3 dbX :memory: +dbX eval {PRAGMA temp_store_directory = ""} +dbX close + +ifcapable lock_proxy_pragmas&&prefer_proxy_locking { + set sqlite_hostid_num 1 + + set using_proxy 0 + foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] { + set using_proxy $value + } + + # Test the lock_proxy_file pragmas. + # + db close + set env(SQLITE_FORCE_PROXY_LOCKING) "0" + + sqlite3 db test.db + do_test pragma-16.1 { + execsql { + PRAGMA lock_proxy_file="mylittleproxy"; + select * from sqlite_master; + } + execsql { + PRAGMA lock_proxy_file; + } + } {mylittleproxy} + + do_test pragma-16.2 { + sqlite3 db2 test.db + execsql { + PRAGMA lock_proxy_file="mylittleproxy"; + } db2 + } {} + + db2 close + do_test pragma-16.2.1 { + sqlite3 db2 test.db + execsql { + PRAGMA lock_proxy_file=":auto:"; + select * from sqlite_master; + } db2 + execsql { + PRAGMA lock_proxy_file; + } db2 + } {mylittleproxy} + + db2 close + do_test pragma-16.3 { + sqlite3 db2 test.db + execsql { + PRAGMA lock_proxy_file="myotherproxy"; + } db2 + catchsql { + select * from sqlite_master; + } db2 + } {1 {database is locked}} + + do_test pragma-16.4 { + db2 close + db close + sqlite3 db2 test.db + execsql { + PRAGMA lock_proxy_file="myoriginalproxy"; + PRAGMA lock_proxy_file="myotherproxy"; + PRAGMA lock_proxy_file; + } db2 + } {myotherproxy} + + db2 close + set env(SQLITE_FORCE_PROXY_LOCKING) "1" + do_test pragma-16.5 { + sqlite3 db2 test.db + execsql { + PRAGMA lock_proxy_file=":auto:"; + PRAGMA lock_proxy_file; + } db2 + } {myotherproxy} + + do_test pragma-16.6 { + db2 close + sqlite3 db2 test2.db + set lockpath [execsql { + PRAGMA lock_proxy_file=":auto:"; + PRAGMA lock_proxy_file; + } db2] + string match "*test2.db:auto:" $lockpath + } {1} + + set sqlite_hostid_num 2 + do_test pragma-16.7 { + list [catch { + sqlite3 db test2.db + execsql { + PRAGMA lock_proxy_file=":auto:"; + select * from sqlite_master; + } + } msg] $msg + } {1 {database is locked}} + db close + + do_test pragma-16.8 { + list [catch { + sqlite3 db test2.db + execsql { select * from sqlite_master } + } msg] $msg + } {1 {database is locked}} + + db2 close + do_test pragma-16.8.1 { + execsql { + PRAGMA lock_proxy_file="yetanotherproxy"; + PRAGMA lock_proxy_file; + } + } {yetanotherproxy} + do_test pragma-16.8.2 { + execsql { + create table mine(x); + } + } {} + + db close + do_test pragma-16.9 { + sqlite3 db proxytest.db + set lockpath2 [execsql { + PRAGMA lock_proxy_file=":auto:"; + PRAGMA lock_proxy_file; + } db] + string match "*proxytest.db:auto:" $lockpath2 + } {1} + + set env(SQLITE_FORCE_PROXY_LOCKING) $using_proxy + set sqlite_hostid_num 0 +} + +# Parsing of auto_vacuum settings. +# +foreach {autovac_setting val} { + 0 0 + 1 1 + 2 2 + 3 0 + -1 0 + none 0 + NONE 0 + NoNe 0 + full 1 + FULL 1 + incremental 2 + INCREMENTAL 2 + -1234 0 + 1234 0 +} { + do_test pragma-17.1.$autovac_setting { + catch {db close} + sqlite3 db :memory: + execsql " + PRAGMA auto_vacuum=$::autovac_setting; + PRAGMA auto_vacuum; + " + } $val +} + +# Parsing of temp_store settings. +# +foreach {temp_setting val} { + 0 0 + 1 1 + 2 2 + 3 0 + -1 0 + file 1 + FILE 1 + fIlE 1 + memory 2 + MEMORY 2 + MeMoRy 2 +} { + do_test pragma-18.1.$temp_setting { + catch {db close} + sqlite3 db :memory: + execsql " + PRAGMA temp_store=$::temp_setting; + PRAGMA temp_store=$::temp_setting; + PRAGMA temp_store; + " + } $val +} + +# The SQLITE_FCNTL_PRAGMA logic, with error handling. +# +db close +testvfs tvfs +sqlite3 db test.db -vfs tvfs +do_test pragma-19.1 { + catchsql {PRAGMA error} +} {1 {SQL logic error or missing database}} +do_test pragma-19.2 { + catchsql {PRAGMA error='This is the error message'} +} {1 {This is the error message}} +do_test pragma-19.3 { + catchsql {PRAGMA error='7 This is the error message'} +} {1 {This is the error message}} +do_test pragma-19.4 { + catchsql {PRAGMA error=7} +} {1 {out of memory}} +do_test pragma-19.5 { + file tail [lindex [execsql {PRAGMA filename}] 0] +} {test.db} + +if {$tcl_platform(platform)=="windows"} { +# Test data_store_directory pragma +# +db close +sqlite3 db test.db +file mkdir data_dir +do_test pragma-20.1 { + catchsql {PRAGMA data_store_directory} +} {0 {}} +do_test pragma-20.2 { + set pwd [string map {' ''} [file nativename [get_pwd]]] + catchsql "PRAGMA data_store_directory='$pwd';" +} {0 {}} +do_test pragma-20.3 { + catchsql {PRAGMA data_store_directory} +} [list 0 [list [file nativename [get_pwd]]]] +do_test pragma-20.4 { + set pwd [string map {' ''} [file nativename \ + [file join [get_pwd] data_dir]]] + catchsql "PRAGMA data_store_directory='$pwd';" +} {0 {}} +do_test pragma-20.5 { + sqlite3 db2 test2.db + catchsql "PRAGMA database_list;" db2 +} [list 0 [list 0 main [file nativename \ + [file join [get_pwd] data_dir test2.db]]]] +catch {db2 close} +do_test pragma-20.6 { + sqlite3 db2 [file join [get_pwd] test2.db] + catchsql "PRAGMA database_list;" db2 +} [list 0 [list 0 main [file nativename \ + [file join [get_pwd] test2.db]]]] +catch {db2 close} +do_test pragma-20.7 { + catchsql "PRAGMA data_store_directory='';" +} {0 {}} +do_test pragma-20.8 { + catchsql {PRAGMA data_store_directory} +} {0 {}} + +forcedelete data_dir +} ;# endif windows + +do_test 21.1 { + # Create a corrupt database in testerr.db. And a non-corrupt at test.db. + # + db close + forcedelete test.db + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 1); + } + for {set i 0} {$i < 10} {incr i} { + execsql { INSERT INTO t1 SELECT a + (1 << $i), b + (1 << $i) FROM t1 } + } + db close + forcecopy test.db testerr.db + hexio_write testerr.db 15000 [string repeat 55 100] +} {100} + +set mainerr {*** in database main *** +Multiple uses for byte 672 of page 15} +set auxerr {*** in database aux *** +Multiple uses for byte 672 of page 15} + +do_test 22.2 { + catch { db close } + sqlite3 db testerr.db + execsql { PRAGMA integrity_check } +} [list $mainerr] + +do_test 22.3.1 { + catch { db close } + sqlite3 db test.db + execsql { + ATTACH 'testerr.db' AS 'aux'; + PRAGMA integrity_check; + } +} [list $auxerr] +do_test 22.3.2 { + execsql { PRAGMA main.integrity_check; } +} {ok} +do_test 22.3.3 { + execsql { PRAGMA aux.integrity_check; } +} [list $auxerr] + +do_test 22.4.1 { + catch { db close } + sqlite3 db testerr.db + execsql { + ATTACH 'test.db' AS 'aux'; + PRAGMA integrity_check; + } +} [list $mainerr] +do_test 22.4.2 { + execsql { PRAGMA main.integrity_check; } +} [list $mainerr] +do_test 22.4.3 { + execsql { PRAGMA aux.integrity_check; } +} {ok} + +db close +forcedelete test.db test.db-wal test.db-journal +sqlite3 db test.db +sqlite3 db2 test.db +do_test 23.1 { + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY,b,c,d); + CREATE INDEX i1 ON t1(b,c); + CREATE INDEX i2 ON t1(c,d); + CREATE TABLE t2(x INTEGER REFERENCES t1); + } + db2 eval {SELECT name FROM sqlite_master} +} {t1 i1 i2 t2} +do_test 23.2 { + db eval { + DROP INDEX i2; + CREATE INDEX i2 ON t1(c,d,b); + } + db2 eval {PRAGMA index_info(i2)} +} {0 2 c 1 3 d 2 1 b} +do_test 23.3 { + db eval { + CREATE INDEX i3 ON t1(d,b,c); + } + db2 eval {PRAGMA index_list(t1)} +} {0 i3 0 1 i2 0 2 i1 0} +do_test 23.4 { + db eval { + ALTER TABLE t1 ADD COLUMN e; + } + db2 eval { + PRAGMA table_info(t1); + } +} {/4 e {} 0 {} 0/} +do_test 23.5 { + db eval { + DROP TABLE t2; + CREATE TABLE t2(x, y INTEGER REFERENCES t1); + } + db2 eval { + PRAGMA foreign_key_list(t2); + } +} {0 0 t1 y {} {NO ACTION} {NO ACTION} NONE} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/pragma2.test b/components/external/SQLite-3.8.1/test/pragma2.test new file mode 100644 index 0000000000000000000000000000000000000000..0dbc9777d261ffe8d7d770f3bf395fc1df9cd150 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/pragma2.test @@ -0,0 +1,208 @@ +# 2002 March 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for the PRAGMA command. +# +# $Id: pragma2.test,v 1.4 2007/10/09 08:29:33 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Test organization: +# +# pragma2-1.*: Test freelist_count pragma on the main database. +# pragma2-2.*: Test freelist_count pragma on an attached database. +# pragma2-3.*: Test trying to write to the freelist_count is a no-op. +# pragma2-4.*: Tests for PRAGMA cache_spill +# + +ifcapable !pragma||!schema_pragmas { + finish_test + return +} + +# Delete the preexisting database to avoid the special setup +# that the "all.test" script does. +# +db close +delete_file test.db test.db-journal +delete_file test3.db test3.db-journal +sqlite3 db test.db; set DB [sqlite3_connection_pointer db] +db eval {PRAGMA auto_vacuum=0} + +do_test pragma2-1.1 { + execsql { + PRAGMA freelist_count; + } +} {0} +do_test pragma2-1.2 { + execsql { + CREATE TABLE abc(a, b, c); + PRAGMA freelist_count; + } +} {0} +do_test pragma2-1.3 { + execsql { + DROP TABLE abc; + PRAGMA freelist_count; + } +} {1} +do_test pragma2-1.4 { + execsql { + PRAGMA main.freelist_count; + } +} {1} + +forcedelete test2.db +forcedelete test2.db-journal + +ifcapable attach { + do_test pragma2-2.1 { + execsql { + ATTACH 'test2.db' AS aux; + PRAGMA aux.auto_vacuum=OFF; + PRAGMA aux.freelist_count; + } + } {0} + do_test pragma2-2.2 { + execsql { + CREATE TABLE aux.abc(a, b, c); + PRAGMA aux.freelist_count; + } + } {0} + do_test pragma2-2.3 { + set ::val [string repeat 0123456789 1000] + execsql { + INSERT INTO aux.abc VALUES(1, 2, $::val); + PRAGMA aux.freelist_count; + } + } {0} + do_test pragma2-2.4 { + expr {[file size test2.db] / 1024} + } {11} + do_test pragma2-2.5 { + execsql { + DELETE FROM aux.abc; + PRAGMA aux.freelist_count; + } + } {9} + + do_test pragma2-3.1 { + execsql { + PRAGMA aux.freelist_count; + PRAGMA main.freelist_count; + PRAGMA freelist_count; + } + } {9 1 1} + do_test pragma2-3.2 { + execsql { + PRAGMA freelist_count = 500; + PRAGMA freelist_count; + } + } {1 1} + do_test pragma2-3.3 { + execsql { + PRAGMA aux.freelist_count = 500; + PRAGMA aux.freelist_count; + } + } {9 9} +} + +# Default setting of PRAGMA cache_spill is always ON +# +# EVIDENCE-OF: R-51036-62828 PRAGMA cache_spill; PRAGMA +# cache_spill=boolean; +# +# EVIDENCE-OF: R-23955-02765 Cache_spill is enabled by default +# +db close +delete_file test.db test.db-journal +delete_file test2.db test2.db-journal +sqlite3 db test.db +do_execsql_test pragma2-4.1 { + PRAGMA cache_spill; + PRAGMA main.cache_spill; + PRAGMA temp.cache_spill; +} {1 1 1} +do_execsql_test pragma2-4.2 { + PRAGMA cache_spill=OFF; + PRAGMA cache_spill; + PRAGMA main.cache_spill; + PRAGMA temp.cache_spill; +} {0 0 0} +do_execsql_test pragma2-4.3 { + PRAGMA page_size=1024; + PRAGMA cache_size=50; + BEGIN; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, d); + INSERT INTO t1 VALUES(1, randomblob(400), 1, randomblob(400)); + INSERT INTO t1 SELECT a+1, randomblob(400), a+1, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+2, randomblob(400), a+2, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+4, randomblob(400), a+4, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+8, randomblob(400), a+8, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+16, randomblob(400), a+16, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+32, randomblob(400), a+32, randomblob(400) FROM t1; + INSERT INTO t1 SELECT a+64, randomblob(400), a+64, randomblob(400) FROM t1; + COMMIT; + ATTACH 'test2.db' AS aux1; + CREATE TABLE aux1.t2(a INTEGER PRIMARY KEY, b, c, d); + INSERT INTO t2 SELECT * FROM t1; + DETACH aux1; + PRAGMA cache_spill=ON; +} {} +sqlite3_release_memory +# +# EVIDENCE-OF: R-07634-40532 The cache_spill pragma enables or disables +# the ability of the pager to spill dirty cache pages to the database +# file in the middle of a transaction. +# +do_test pragma2-4.4 { + db eval { + BEGIN; + UPDATE t1 SET c=c+1; + PRAGMA lock_status; + } +} {main exclusive temp unknown} ;# EXCLUSIVE lock due to cache spill +do_test pragma2-4.5 { + db eval { + COMMIT; + PRAGMA cache_spill=OFF; + BEGIN; + UPDATE t1 SET c=c-1; + PRAGMA lock_status; + } +} {main reserved temp unknown} ;# No cache spill, so no exclusive lock + +# Verify that newly attached databases inherit the cache_spill=OFF +# setting. +# +do_execsql_test pragma2-4.6 { + COMMIT; + ATTACH 'test2.db' AS aux1; + PRAGMA aux1.cache_size=50; + BEGIN; + UPDATE t2 SET c=c+1; + PRAGMA lock_status; +} {main unlocked temp unknown aux1 reserved} +do_execsql_test pragma2-4.7 { + COMMIT; +} +sqlite3_release_memory +do_execsql_test pragma2-4.8 { + PRAGMA cache_spill=ON; -- Applies to all databases + BEGIN; + UPDATE t2 SET c=c-1; + PRAGMA lock_status; +} {main unlocked temp unknown aux1 exclusive} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/printf.test b/components/external/SQLite-3.8.1/test/printf.test new file mode 100644 index 0000000000000000000000000000000000000000..73222720abad5c8da656d0f01858e0bf03ec541c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/printf.test @@ -0,0 +1,3755 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the sqlite_*_printf() interface. +# +# $Id: printf.test,v 1.31 2009/02/01 00:21:10 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +do_test printf-1.1.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 1 1 1 +} {abc: 1 1 1 :xyz} +do_test printf-1.1.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 1 1 1 +} {abc: ( 1) ( 1) ( 1) :xyz} +do_test printf-1.1.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 1 1 1 +} {abc: (1 ) (1 ) (1 ) :xyz} +do_test printf-1.1.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 1 1 1 +} {abc: ( +1) ( 1) ( 1) :xyz} +do_test printf-1.1.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 1 1 1 +} {abc: (000001) (000001) (000001) :xyz} +do_test printf-1.1.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 1 1 1 +} {abc: ( 1) ( 1) ( 1) :xyz} +do_test printf-1.1.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 1 1 1 +} {abc: ( 1) ( 0x1) ( 01) :xyz} +do_test printf-1.2.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 2 2 2 +} {abc: 2 2 2 :xyz} +do_test printf-1.2.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 2 2 2 +} {abc: ( 2) ( 2) ( 2) :xyz} +do_test printf-1.2.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 2 2 2 +} {abc: (2 ) (2 ) (2 ) :xyz} +do_test printf-1.2.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 2 2 2 +} {abc: ( +2) ( 2) ( 2) :xyz} +do_test printf-1.2.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 2 2 2 +} {abc: (000002) (000002) (000002) :xyz} +do_test printf-1.2.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 2 2 2 +} {abc: ( 2) ( 2) ( 2) :xyz} +do_test printf-1.2.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 2 2 2 +} {abc: ( 2) ( 0x2) ( 02) :xyz} +do_test printf-1.3.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 5 5 5 +} {abc: 5 5 5 :xyz} +do_test printf-1.3.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 5 5 5 +} {abc: ( 5) ( 5) ( 5) :xyz} +do_test printf-1.3.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 5 5 5 +} {abc: (5 ) (5 ) (5 ) :xyz} +do_test printf-1.3.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 5 5 5 +} {abc: ( +5) ( 5) ( 5) :xyz} +do_test printf-1.3.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 5 5 5 +} {abc: (000005) (000005) (000005) :xyz} +do_test printf-1.3.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 5 5 5 +} {abc: ( 5) ( 5) ( 5) :xyz} +do_test printf-1.3.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 5 5 5 +} {abc: ( 5) ( 0x5) ( 05) :xyz} +do_test printf-1.4.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 10 10 10 +} {abc: 10 a 12 :xyz} +do_test printf-1.4.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 10 10 10 +} {abc: ( 10) ( a) ( 12) :xyz} +do_test printf-1.4.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 10 10 10 +} {abc: (10 ) (a ) (12 ) :xyz} +do_test printf-1.4.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 10 10 10 +} {abc: ( +10) ( a) ( 12) :xyz} +do_test printf-1.4.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 10 10 10 +} {abc: (000010) (00000a) (000012) :xyz} +do_test printf-1.4.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 10 10 10 +} {abc: ( 10) ( a) ( 12) :xyz} +do_test printf-1.4.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 10 10 10 +} {abc: ( 10) ( 0xa) ( 012) :xyz} +do_test printf-1.5.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 99 99 99 +} {abc: 99 63 143 :xyz} +do_test printf-1.5.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 99 99 99 +} {abc: ( 99) ( 63) ( 143) :xyz} +do_test printf-1.5.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 99 99 99 +} {abc: (99 ) (63 ) (143 ) :xyz} +do_test printf-1.5.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 99 99 99 +} {abc: ( +99) ( 63) ( 143) :xyz} +do_test printf-1.5.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 99 99 99 +} {abc: (000099) (000063) (000143) :xyz} +do_test printf-1.5.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 99 99 99 +} {abc: ( 99) ( 63) ( 143) :xyz} +do_test printf-1.5.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 99 99 99 +} {abc: ( 99) ( 0x63) ( 0143) :xyz} +do_test printf-1.6.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 100 100 100 +} {abc: 100 64 144 :xyz} +do_test printf-1.6.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 100 100 100 +} {abc: ( 100) ( 64) ( 144) :xyz} +do_test printf-1.6.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 100 100 100 +} {abc: (100 ) (64 ) (144 ) :xyz} +do_test printf-1.6.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 100 100 100 +} {abc: ( +100) ( 64) ( 144) :xyz} +do_test printf-1.6.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 100 100 100 +} {abc: (000100) (000064) (000144) :xyz} +do_test printf-1.6.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 100 100 100 +} {abc: ( 100) ( 64) ( 144) :xyz} +do_test printf-1.6.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 100 100 100 +} {abc: ( 100) ( 0x64) ( 0144) :xyz} +do_test printf-1.7.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 1000000 1000000 1000000 +} {abc: 1000000 f4240 3641100 :xyz} +do_test printf-1.7.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 1000000 1000000 1000000 +} {abc: (1000000) ( f4240) (3641100) :xyz} +do_test printf-1.7.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 1000000 1000000 1000000 +} {abc: (1000000) (f4240 ) (3641100) :xyz} +do_test printf-1.7.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 1000000 1000000 1000000 +} {abc: (+1000000) ( f4240) (3641100) :xyz} +do_test printf-1.7.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 1000000 1000000 1000000 +} {abc: (1000000) (0f4240) (3641100) :xyz} +do_test printf-1.7.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 1000000 1000000 1000000 +} {abc: ( 1000000) ( f4240) (3641100) :xyz} +do_test printf-1.7.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 1000000 1000000 1000000 +} {abc: (1000000) (0xf4240) (03641100) :xyz} +do_test printf-1.8.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 999999999 999999999 999999999 +} {abc: 999999999 3b9ac9ff 7346544777 :xyz} +do_test printf-1.8.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 999999999 999999999 999999999 +} {abc: (999999999) (3b9ac9ff) (7346544777) :xyz} +do_test printf-1.8.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 999999999 999999999 999999999 +} {abc: (999999999) (3b9ac9ff) (7346544777) :xyz} +do_test printf-1.8.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 999999999 999999999 999999999 +} {abc: (+999999999) (3b9ac9ff) (7346544777) :xyz} +do_test printf-1.8.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 999999999 999999999 999999999 +} {abc: (999999999) (3b9ac9ff) (7346544777) :xyz} +do_test printf-1.8.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 999999999 999999999 999999999 +} {abc: ( 999999999) (3b9ac9ff) (7346544777) :xyz} +do_test printf-1.8.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 999999999 999999999 999999999 +} {abc: (999999999) (0x3b9ac9ff) (07346544777) :xyz} +do_test printf-1.9.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 0 0 0 +} {abc: 0 0 0 :xyz} +do_test printf-1.9.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 0 0 0 +} {abc: ( 0) ( 0) ( 0) :xyz} +do_test printf-1.9.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 0 0 0 +} {abc: (0 ) (0 ) (0 ) :xyz} +do_test printf-1.9.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 0 0 0 +} {abc: ( +0) ( 0) ( 0) :xyz} +do_test printf-1.9.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 0 0 0 +} {abc: (000000) (000000) (000000) :xyz} +do_test printf-1.9.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 0 0 0 +} {abc: ( 0) ( 0) ( 0) :xyz} +do_test printf-1.9.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 0 0 0 +} {abc: ( 0) ( 0) ( 0) :xyz} +# 0xffffffff == -1 +do_test printf-1.10.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 0xffffffff 0xffffffff 0xffffffff +} {abc: -1 ffffffff 37777777777 :xyz} +do_test printf-1.10.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 0xffffffff 0xffffffff 0xffffffff +} {abc: ( -1) (ffffffff) (37777777777) :xyz} +do_test printf-1.10.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 0xffffffff 0xffffffff 0xffffffff +} {abc: (-1 ) (ffffffff) (37777777777) :xyz} +do_test printf-1.10.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 0xffffffff 0xffffffff 0xffffffff +} {abc: ( -1) (ffffffff) (37777777777) :xyz} +do_test printf-1.10.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 0xffffffff 0xffffffff 0xffffffff +} {abc: (-00001) (ffffffff) (37777777777) :xyz} +do_test printf-1.10.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 0xffffffff 0xffffffff 0xffffffff +} {abc: ( -1) (ffffffff) (37777777777) :xyz} +do_test printf-1.10.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 0xffffffff 0xffffffff 0xffffffff +} {abc: ( -1) (0xffffffff) (037777777777) :xyz} +# 0xfffffffe == -2 +do_test printf-1.11.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 0xfffffffe 0xfffffffe 0xfffffffe +} {abc: -2 fffffffe 37777777776 :xyz} +do_test printf-1.11.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 0xfffffffe 0xfffffffe 0xfffffffe +} {abc: ( -2) (fffffffe) (37777777776) :xyz} +do_test printf-1.11.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 0xfffffffe 0xfffffffe 0xfffffffe +} {abc: (-2 ) (fffffffe) (37777777776) :xyz} +do_test printf-1.11.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 0xfffffffe 0xfffffffe 0xfffffffe +} {abc: ( -2) (fffffffe) (37777777776) :xyz} +do_test printf-1.11.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 0xfffffffe 0xfffffffe 0xfffffffe +} {abc: (-00002) (fffffffe) (37777777776) :xyz} +do_test printf-1.11.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 0xfffffffe 0xfffffffe 0xfffffffe +} {abc: ( -2) (fffffffe) (37777777776) :xyz} +do_test printf-1.11.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 0xfffffffe 0xfffffffe 0xfffffffe +} {abc: ( -2) (0xfffffffe) (037777777776) :xyz} +# 0xfffffffb == -5 +do_test printf-1.12.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 0xfffffffb 0xfffffffb 0xfffffffb +} {abc: -5 fffffffb 37777777773 :xyz} +do_test printf-1.12.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 0xfffffffb 0xfffffffb 0xfffffffb +} {abc: ( -5) (fffffffb) (37777777773) :xyz} +do_test printf-1.12.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 0xfffffffb 0xfffffffb 0xfffffffb +} {abc: (-5 ) (fffffffb) (37777777773) :xyz} +do_test printf-1.12.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 0xfffffffb 0xfffffffb 0xfffffffb +} {abc: ( -5) (fffffffb) (37777777773) :xyz} +do_test printf-1.12.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 0xfffffffb 0xfffffffb 0xfffffffb +} {abc: (-00005) (fffffffb) (37777777773) :xyz} +do_test printf-1.12.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 0xfffffffb 0xfffffffb 0xfffffffb +} {abc: ( -5) (fffffffb) (37777777773) :xyz} +do_test printf-1.12.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 0xfffffffb 0xfffffffb 0xfffffffb +} {abc: ( -5) (0xfffffffb) (037777777773) :xyz} +# 0xfffffff6 == -10 +do_test printf-1.13.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 0xfffffff6 0xfffffff6 0xfffffff6 +} {abc: -10 fffffff6 37777777766 :xyz} +do_test printf-1.13.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 0xfffffff6 0xfffffff6 0xfffffff6 +} {abc: ( -10) (fffffff6) (37777777766) :xyz} +do_test printf-1.13.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 0xfffffff6 0xfffffff6 0xfffffff6 +} {abc: (-10 ) (fffffff6) (37777777766) :xyz} +do_test printf-1.13.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 0xfffffff6 0xfffffff6 0xfffffff6 +} {abc: ( -10) (fffffff6) (37777777766) :xyz} +do_test printf-1.13.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 0xfffffff6 0xfffffff6 0xfffffff6 +} {abc: (-00010) (fffffff6) (37777777766) :xyz} +do_test printf-1.13.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 0xfffffff6 0xfffffff6 0xfffffff6 +} {abc: ( -10) (fffffff6) (37777777766) :xyz} +do_test printf-1.13.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 0xfffffff6 0xfffffff6 0xfffffff6 +} {abc: ( -10) (0xfffffff6) (037777777766) :xyz} +# 0xffffff9d == -99 +do_test printf-1.14.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 0xffffff9d 0xffffff9d 0xffffff9d +} {abc: -99 ffffff9d 37777777635 :xyz} +do_test printf-1.14.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 0xffffff9d 0xffffff9d 0xffffff9d +} {abc: ( -99) (ffffff9d) (37777777635) :xyz} +do_test printf-1.14.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 0xffffff9d 0xffffff9d 0xffffff9d +} {abc: (-99 ) (ffffff9d) (37777777635) :xyz} +do_test printf-1.14.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 0xffffff9d 0xffffff9d 0xffffff9d +} {abc: ( -99) (ffffff9d) (37777777635) :xyz} +do_test printf-1.14.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 0xffffff9d 0xffffff9d 0xffffff9d +} {abc: (-00099) (ffffff9d) (37777777635) :xyz} +do_test printf-1.14.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 0xffffff9d 0xffffff9d 0xffffff9d +} {abc: ( -99) (ffffff9d) (37777777635) :xyz} +do_test printf-1.14.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 0xffffff9d 0xffffff9d 0xffffff9d +} {abc: ( -99) (0xffffff9d) (037777777635) :xyz} +# 0xffffff9c == -100 +do_test printf-1.15.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 0xffffff9c 0xffffff9c 0xffffff9c +} {abc: -100 ffffff9c 37777777634 :xyz} +do_test printf-1.15.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 0xffffff9c 0xffffff9c 0xffffff9c +} {abc: ( -100) (ffffff9c) (37777777634) :xyz} +do_test printf-1.15.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 0xffffff9c 0xffffff9c 0xffffff9c +} {abc: (-100 ) (ffffff9c) (37777777634) :xyz} +do_test printf-1.15.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 0xffffff9c 0xffffff9c 0xffffff9c +} {abc: ( -100) (ffffff9c) (37777777634) :xyz} +do_test printf-1.15.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 0xffffff9c 0xffffff9c 0xffffff9c +} {abc: (-00100) (ffffff9c) (37777777634) :xyz} +do_test printf-1.15.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 0xffffff9c 0xffffff9c 0xffffff9c +} {abc: ( -100) (ffffff9c) (37777777634) :xyz} +do_test printf-1.15.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 0xffffff9c 0xffffff9c 0xffffff9c +} {abc: ( -100) (0xffffff9c) (037777777634) :xyz} +# 0xff676981 == -9999999 +do_test printf-1.16.1 { + sqlite3_mprintf_int {abc: %d %x %o :xyz}\ + 0xff676981 0xff676981 0xff676981 +} {abc: -9999999 ff676981 37731664601 :xyz} +do_test printf-1.16.2 { + sqlite3_mprintf_int {abc: (%6d) (%6x) (%6o) :xyz}\ + 0xff676981 0xff676981 0xff676981 +} {abc: (-9999999) (ff676981) (37731664601) :xyz} +do_test printf-1.16.3 { + sqlite3_mprintf_int {abc: (%-6d) (%-6x) (%-6o) :xyz}\ + 0xff676981 0xff676981 0xff676981 +} {abc: (-9999999) (ff676981) (37731664601) :xyz} +do_test printf-1.16.4 { + sqlite3_mprintf_int {abc: (%+6d) (%+6x) (%+6o) :xyz}\ + 0xff676981 0xff676981 0xff676981 +} {abc: (-9999999) (ff676981) (37731664601) :xyz} +do_test printf-1.16.5 { + sqlite3_mprintf_int {abc: (%06d) (%06x) (%06o) :xyz}\ + 0xff676981 0xff676981 0xff676981 +} {abc: (-9999999) (ff676981) (37731664601) :xyz} +do_test printf-1.16.6 { + sqlite3_mprintf_int {abc: (% 6d) (% 6x) (% 6o) :xyz}\ + 0xff676981 0xff676981 0xff676981 +} {abc: (-9999999) (ff676981) (37731664601) :xyz} +do_test printf-1.16.7 { + sqlite3_mprintf_int {abc: (%#6d) (%#6x) (%#6o) :xyz}\ + 0xff676981 0xff676981 0xff676981 +} {abc: (-9999999) (0xff676981) (037731664601) :xyz} +do_test printf-2.1.1.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 0.001 +} {abc: (0.0) :xyz} +do_test printf-2.1.1.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 0.001 +} {abc: (1.0e-03) :xyz} +do_test printf-2.1.1.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 0.001 +} {abc: (0.001) :xyz} +do_test printf-2.1.1.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 0.001 +} {abc: 1 1 (0.001) :xyz} +do_test printf-2.1.1.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 0.001 +} {abc: 1 1 (0.00100000) :xyz} +do_test printf-2.1.1.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 0.001 +} {abc: 1 1 (000000.001) :xyz} +do_test printf-2.1.1.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 0.001 +} {abc: 1 1 (0.0) :xyz} +do_test printf-2.1.1.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 0.001 +} {abc: 1 1 (1.0e-03) :xyz} +do_test printf-2.1.1.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 0.001 +} {abc: 1 1 (0.001) :xyz} +do_test printf-2.1.2.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 1.0e-20 +} {abc: (0.0) :xyz} +do_test printf-2.1.2.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 1.0e-20 +} {abc: (1.0e-20) :xyz} +do_test printf-2.1.2.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 1.0e-20 +} {abc: (1e-20) :xyz} +do_test printf-2.1.2.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 1.0e-20 +} {abc: 1 1 (1e-20) :xyz} +do_test printf-2.1.2.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 1.0e-20 +} {abc: 1 1 (1.00000e-20) :xyz} +do_test printf-2.1.2.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 1.0e-20 +} {abc: 1 1 (000001e-20) :xyz} +do_test printf-2.1.2.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 1.0e-20 +} {abc: 1 1 (0.0) :xyz} +do_test printf-2.1.2.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 1.0e-20 +} {abc: 1 1 (1.0e-20) :xyz} +do_test printf-2.1.2.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 1.0e-20 +} {abc: 1 1 (1e-20) :xyz} +do_test printf-2.1.3.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 1.0 +} {abc: (1.0) :xyz} +do_test printf-2.1.3.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 1.0 +} {abc: (1.0e+00) :xyz} +do_test printf-2.1.3.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 1.0 +} {abc: (1) :xyz} +do_test printf-2.1.3.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 1.0 +} {abc: 1 1 (1) :xyz} +do_test printf-2.1.3.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 1.0 +} {abc: 1 1 (1.00000) :xyz} +do_test printf-2.1.3.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 1.0 +} {abc: 1 1 (0000000001) :xyz} +do_test printf-2.1.3.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 1.0 +} {abc: 1 1 (1.0) :xyz} +do_test printf-2.1.3.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 1.0 +} {abc: 1 1 (1.0e+00) :xyz} +do_test printf-2.1.3.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 1.0 +} {abc: 1 1 (1) :xyz} +do_test printf-2.1.4.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 0.0 +} {abc: (0.0) :xyz} +do_test printf-2.1.4.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 0.0 +} {abc: (0.0e+00) :xyz} +do_test printf-2.1.4.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 0.0 +} {abc: (0) :xyz} +do_test printf-2.1.4.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 0.0 +} {abc: 1 1 (0) :xyz} +do_test printf-2.1.4.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 0.0 +} {abc: 1 1 (0.00000) :xyz} +do_test printf-2.1.4.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 0.0 +} {abc: 1 1 (0000000000) :xyz} +do_test printf-2.1.4.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 0.0 +} {abc: 1 1 (0.0) :xyz} +do_test printf-2.1.4.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 0.0 +} {abc: 1 1 (0.0e+00) :xyz} +do_test printf-2.1.4.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 0.0 +} {abc: 1 1 (0) :xyz} +do_test printf-2.1.5.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 100.0 +} {abc: (100.0) :xyz} +do_test printf-2.1.5.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 100.0 +} {abc: (1.0e+02) :xyz} +do_test printf-2.1.5.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 100.0 +} {abc: (1e+02) :xyz} +do_test printf-2.1.5.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 100.0 +} {abc: 1 1 (100) :xyz} +do_test printf-2.1.5.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 100.0 +} {abc: 1 1 (100.000) :xyz} +do_test printf-2.1.5.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 100.0 +} {abc: 1 1 (0000000100) :xyz} +do_test printf-2.1.5.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 100.0 +} {abc: 1 1 (100.0) :xyz} +do_test printf-2.1.5.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 100.0 +} {abc: 1 1 (1.0e+02) :xyz} +do_test printf-2.1.5.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 100.0 +} {abc: 1 1 (1e+02) :xyz} +do_test printf-2.1.6.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 9.99999 +} {abc: (10.0) :xyz} +do_test printf-2.1.6.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 9.99999 +} {abc: (1.0e+01) :xyz} +do_test printf-2.1.6.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 9.99999 +} {abc: (1e+01) :xyz} +do_test printf-2.1.6.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 9.99999 +} {abc: 1 1 (9.99999) :xyz} +do_test printf-2.1.6.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 9.99999 +} {abc: 1 1 (9.99999) :xyz} +do_test printf-2.1.6.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 9.99999 +} {abc: 1 1 (0009.99999) :xyz} +do_test printf-2.1.6.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 9.99999 +} {abc: 1 1 (10.0) :xyz} +do_test printf-2.1.6.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 9.99999 +} {abc: 1 1 (1.0e+01) :xyz} +do_test printf-2.1.6.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 9.99999 +} {abc: 1 1 (1e+01) :xyz} +do_test printf-2.1.7.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 -0.00543 +} {abc: (-0.0) :xyz} +do_test printf-2.1.7.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -0.00543 +} {abc: (-5.4e-03) :xyz} +do_test printf-2.1.7.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -0.00543 +} {abc: (-0.005) :xyz} +do_test printf-2.1.7.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -0.00543 +} {abc: 1 1 (-0.00543) :xyz} +do_test printf-2.1.7.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -0.00543 +} {abc: 1 1 (-0.00543000) :xyz} +do_test printf-2.1.7.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -0.00543 +} {abc: 1 1 (-000.00543) :xyz} +do_test printf-2.1.7.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 -0.00543 +} {abc: 1 1 (-0.0) :xyz} +do_test printf-2.1.7.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -0.00543 +} {abc: 1 1 (-5.4e-03) :xyz} +do_test printf-2.1.7.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -0.00543 +} {abc: 1 1 (-0.005) :xyz} +do_test printf-2.1.8.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 -1.0 +} {abc: (-1.0) :xyz} +do_test printf-2.1.8.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -1.0 +} {abc: (-1.0e+00) :xyz} +do_test printf-2.1.8.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -1.0 +} {abc: (-1) :xyz} +do_test printf-2.1.8.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -1.0 +} {abc: 1 1 (-1) :xyz} +do_test printf-2.1.8.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -1.0 +} {abc: 1 1 (-1.00000) :xyz} +do_test printf-2.1.8.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -1.0 +} {abc: 1 1 (-000000001) :xyz} +do_test printf-2.1.8.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 -1.0 +} {abc: 1 1 (-1.0) :xyz} +do_test printf-2.1.8.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -1.0 +} {abc: 1 1 (-1.0e+00) :xyz} +do_test printf-2.1.8.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -1.0 +} {abc: 1 1 (-1) :xyz} +do_test printf-2.1.9.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 -99.99999 +} {abc: (-100.0) :xyz} +do_test printf-2.1.9.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -99.99999 +} {abc: (-1.0e+02) :xyz} +do_test printf-2.1.9.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -99.99999 +} {abc: (-1e+02) :xyz} +do_test printf-2.1.9.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -99.99999 +} {abc: 1 1 (-100) :xyz} +do_test printf-2.1.9.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -99.99999 +} {abc: 1 1 (-100.000) :xyz} +do_test printf-2.1.9.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -99.99999 +} {abc: 1 1 (-000000100) :xyz} +do_test printf-2.1.9.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 -99.99999 +} {abc: 1 1 (-100.0) :xyz} +do_test printf-2.1.9.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -99.99999 +} {abc: 1 1 (-1.0e+02) :xyz} +do_test printf-2.1.9.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -99.99999 +} {abc: 1 1 (-1e+02) :xyz} +do_test printf-2.1.10.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 3.14e+9 +} {abc: (3140000000.0) :xyz} +do_test printf-2.1.10.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 3.14e+9 +} {abc: (3.1e+09) :xyz} +do_test printf-2.1.10.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 3.14e+9 +} {abc: (3e+09) :xyz} +do_test printf-2.1.10.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 3.14e+9 +} {abc: 1 1 (3.14e+09) :xyz} +do_test printf-2.1.10.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 3.14e+9 +} {abc: 1 1 (3.14000e+09) :xyz} +do_test printf-2.1.10.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 3.14e+9 +} {abc: 1 1 (003.14e+09) :xyz} +do_test printf-2.1.10.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 3.14e+9 +} {abc: 1 1 (3140000000.0) :xyz} +do_test printf-2.1.10.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 3.14e+9 +} {abc: 1 1 (3.1e+09) :xyz} +do_test printf-2.1.10.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 3.14e+9 +} {abc: 1 1 (3e+09) :xyz} +do_test printf-2.1.11.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -4.72732e+88 +} {abc: (-4.7e+88) :xyz} +do_test printf-2.1.11.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -4.72732e+88 +} {abc: (-5e+88) :xyz} +do_test printf-2.1.11.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -4.72732e+88 +} {abc: 1 1 (-4.72732e+88) :xyz} +do_test printf-2.1.11.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -4.72732e+88 +} {abc: 1 1 (-4.72732e+88) :xyz} +do_test printf-2.1.11.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -4.72732e+88 +} {abc: 1 1 (-4.72732e+88) :xyz} +do_test printf-2.1.11.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -4.72732e+88 +} {abc: 1 1 (-4.7e+88) :xyz} +do_test printf-2.1.11.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -4.72732e+88 +} {abc: 1 1 (-5e+88) :xyz} +do_test printf-2.1.12.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 9.87991e+143 +} {abc: (9.9e+143) :xyz} +do_test printf-2.1.12.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 9.87991e+143 +} {abc: (1e+144) :xyz} +do_test printf-2.1.12.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 9.87991e+143 +} {abc: 1 1 (9.87991e+143) :xyz} +do_test printf-2.1.12.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 9.87991e+143 +} {abc: 1 1 (9.87991e+143) :xyz} +do_test printf-2.1.12.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 9.87991e+143 +} {abc: 1 1 (9.87991e+143) :xyz} +do_test printf-2.1.12.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 9.87991e+143 +} {abc: 1 1 (9.9e+143) :xyz} +do_test printf-2.1.12.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 9.87991e+143 +} {abc: 1 1 (1e+144) :xyz} +do_test printf-2.1.13.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 -6.287291e-9 +} {abc: (-0.0) :xyz} +do_test printf-2.1.13.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 -6.287291e-9 +} {abc: (-6.3e-09) :xyz} +do_test printf-2.1.13.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 -6.287291e-9 +} {abc: (-6e-09) :xyz} +do_test printf-2.1.13.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 -6.287291e-9 +} {abc: 1 1 (-6.28729e-09) :xyz} +do_test printf-2.1.13.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 -6.287291e-9 +} {abc: 1 1 (-6.28729e-09) :xyz} +do_test printf-2.1.13.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 -6.287291e-9 +} {abc: 1 1 (-6.28729e-09) :xyz} +do_test printf-2.1.13.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 -6.287291e-9 +} {abc: 1 1 (-0.0) :xyz} +do_test printf-2.1.13.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 -6.287291e-9 +} {abc: 1 1 (-6.3e-09) :xyz} +do_test printf-2.1.13.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 -6.287291e-9 +} {abc: 1 1 (-6e-09) :xyz} +do_test printf-2.1.14.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 1 1 3.38826392e-110 +} {abc: (0.0) :xyz} +do_test printf-2.1.14.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 1 1 3.38826392e-110 +} {abc: (3.4e-110) :xyz} +do_test printf-2.1.14.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 1 1 3.38826392e-110 +} {abc: (3e-110) :xyz} +do_test printf-2.1.14.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 1 1 3.38826392e-110 +} {abc: 1 1 (3.38826e-110) :xyz} +do_test printf-2.1.14.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 1 1 3.38826392e-110 +} {abc: 1 1 (3.38826e-110) :xyz} +do_test printf-2.1.14.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 1 1 3.38826392e-110 +} {abc: 1 1 (3.38826e-110) :xyz} +do_test printf-2.1.14.7 { + sqlite3_mprintf_double {abc: %d %d (%1.1f) :xyz} 1 1 3.38826392e-110 +} {abc: 1 1 (0.0) :xyz} +do_test printf-2.1.14.8 { + sqlite3_mprintf_double {abc: %d %d (%1.1e) :xyz} 1 1 3.38826392e-110 +} {abc: 1 1 (3.4e-110) :xyz} +do_test printf-2.1.14.9 { + sqlite3_mprintf_double {abc: %d %d (%1.1g) :xyz} 1 1 3.38826392e-110 +} {abc: 1 1 (3e-110) :xyz} +do_test printf-2.2.1.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 0.001 +} {abc: (0.00100) :xyz} +do_test printf-2.2.1.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 0.001 +} {abc: (1.00000e-03) :xyz} +do_test printf-2.2.1.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 0.001 +} {abc: (0.001) :xyz} +do_test printf-2.2.1.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 0.001 +} {abc: 5 5 (0.001) :xyz} +do_test printf-2.2.1.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 0.001 +} {abc: 5 5 (0.00100000) :xyz} +do_test printf-2.2.1.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 0.001 +} {abc: 5 5 (000000.001) :xyz} +do_test printf-2.2.1.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 0.001 +} {abc: 5 5 (0.00100) :xyz} +do_test printf-2.2.1.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 0.001 +} {abc: 5 5 (1.00000e-03) :xyz} +do_test printf-2.2.1.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 0.001 +} {abc: 5 5 (0.001) :xyz} +do_test printf-2.2.2.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 1.0e-20 +} {abc: (0.00000) :xyz} +do_test printf-2.2.2.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 1.0e-20 +} {abc: (1.00000e-20) :xyz} +do_test printf-2.2.2.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 1.0e-20 +} {abc: (1e-20) :xyz} +do_test printf-2.2.2.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 1.0e-20 +} {abc: 5 5 (1e-20) :xyz} +do_test printf-2.2.2.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 1.0e-20 +} {abc: 5 5 (1.00000e-20) :xyz} +do_test printf-2.2.2.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 1.0e-20 +} {abc: 5 5 (000001e-20) :xyz} +do_test printf-2.2.2.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 1.0e-20 +} {abc: 5 5 (0.00000) :xyz} +do_test printf-2.2.2.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 1.0e-20 +} {abc: 5 5 (1.00000e-20) :xyz} +do_test printf-2.2.2.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 1.0e-20 +} {abc: 5 5 (1e-20) :xyz} +do_test printf-2.2.3.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 1.0 +} {abc: (1.00000) :xyz} +do_test printf-2.2.3.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 1.0 +} {abc: (1.00000e+00) :xyz} +do_test printf-2.2.3.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 1.0 +} {abc: ( 1) :xyz} +do_test printf-2.2.3.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 1.0 +} {abc: 5 5 (1) :xyz} +do_test printf-2.2.3.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 1.0 +} {abc: 5 5 (1.00000) :xyz} +do_test printf-2.2.3.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 1.0 +} {abc: 5 5 (0000000001) :xyz} +do_test printf-2.2.3.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 1.0 +} {abc: 5 5 (1.00000) :xyz} +do_test printf-2.2.3.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 1.0 +} {abc: 5 5 (1.00000e+00) :xyz} +do_test printf-2.2.3.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 1.0 +} {abc: 5 5 ( 1) :xyz} +do_test printf-2.2.4.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 0.0 +} {abc: (0.00000) :xyz} +do_test printf-2.2.4.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 0.0 +} {abc: (0.00000e+00) :xyz} +do_test printf-2.2.4.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 0.0 +} {abc: ( 0) :xyz} +do_test printf-2.2.4.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 0.0 +} {abc: 5 5 (0) :xyz} +do_test printf-2.2.4.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 0.0 +} {abc: 5 5 (0.00000) :xyz} +do_test printf-2.2.4.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 0.0 +} {abc: 5 5 (0000000000) :xyz} +do_test printf-2.2.4.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 0.0 +} {abc: 5 5 (0.00000) :xyz} +do_test printf-2.2.4.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 0.0 +} {abc: 5 5 (0.00000e+00) :xyz} +do_test printf-2.2.4.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 0.0 +} {abc: 5 5 ( 0) :xyz} +do_test printf-2.2.5.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 100.0 +} {abc: (100.00000) :xyz} +do_test printf-2.2.5.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 100.0 +} {abc: (1.00000e+02) :xyz} +do_test printf-2.2.5.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 100.0 +} {abc: ( 100) :xyz} +do_test printf-2.2.5.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 100.0 +} {abc: 5 5 (100) :xyz} +do_test printf-2.2.5.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 100.0 +} {abc: 5 5 (100.000) :xyz} +do_test printf-2.2.5.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 100.0 +} {abc: 5 5 (0000000100) :xyz} +do_test printf-2.2.5.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 100.0 +} {abc: 5 5 (100.00000) :xyz} +do_test printf-2.2.5.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 100.0 +} {abc: 5 5 (1.00000e+02) :xyz} +do_test printf-2.2.5.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 100.0 +} {abc: 5 5 ( 100) :xyz} +do_test printf-2.2.6.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 9.99999 +} {abc: (9.99999) :xyz} +do_test printf-2.2.6.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 9.99999 +} {abc: (9.99999e+00) :xyz} +do_test printf-2.2.6.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 9.99999 +} {abc: ( 10) :xyz} +do_test printf-2.2.6.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 9.99999 +} {abc: 5 5 (9.99999) :xyz} +do_test printf-2.2.6.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 9.99999 +} {abc: 5 5 (9.99999) :xyz} +do_test printf-2.2.6.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 9.99999 +} {abc: 5 5 (0009.99999) :xyz} +do_test printf-2.2.6.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 9.99999 +} {abc: 5 5 (9.99999) :xyz} +do_test printf-2.2.6.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 9.99999 +} {abc: 5 5 (9.99999e+00) :xyz} +do_test printf-2.2.6.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 9.99999 +} {abc: 5 5 ( 10) :xyz} +do_test printf-2.2.7.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 -0.00543 +} {abc: (-0.00543) :xyz} +do_test printf-2.2.7.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -0.00543 +} {abc: (-5.43000e-03) :xyz} +do_test printf-2.2.7.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -0.00543 +} {abc: (-0.00543) :xyz} +do_test printf-2.2.7.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -0.00543 +} {abc: 5 5 (-0.00543) :xyz} +do_test printf-2.2.7.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -0.00543 +} {abc: 5 5 (-0.00543000) :xyz} +do_test printf-2.2.7.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -0.00543 +} {abc: 5 5 (-000.00543) :xyz} +do_test printf-2.2.7.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 -0.00543 +} {abc: 5 5 (-0.00543) :xyz} +do_test printf-2.2.7.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -0.00543 +} {abc: 5 5 (-5.43000e-03) :xyz} +do_test printf-2.2.7.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -0.00543 +} {abc: 5 5 (-0.00543) :xyz} +do_test printf-2.2.8.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 -1.0 +} {abc: (-1.00000) :xyz} +do_test printf-2.2.8.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -1.0 +} {abc: (-1.00000e+00) :xyz} +do_test printf-2.2.8.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -1.0 +} {abc: ( -1) :xyz} +do_test printf-2.2.8.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -1.0 +} {abc: 5 5 (-1) :xyz} +do_test printf-2.2.8.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -1.0 +} {abc: 5 5 (-1.00000) :xyz} +do_test printf-2.2.8.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -1.0 +} {abc: 5 5 (-000000001) :xyz} +do_test printf-2.2.8.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 -1.0 +} {abc: 5 5 (-1.00000) :xyz} +do_test printf-2.2.8.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -1.0 +} {abc: 5 5 (-1.00000e+00) :xyz} +do_test printf-2.2.8.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -1.0 +} {abc: 5 5 ( -1) :xyz} +do_test printf-2.2.9.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 -99.99999 +} {abc: (-99.99999) :xyz} +do_test printf-2.2.9.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -99.99999 +} {abc: (-1.00000e+02) :xyz} +do_test printf-2.2.9.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -99.99999 +} {abc: ( -100) :xyz} +do_test printf-2.2.9.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -99.99999 +} {abc: 5 5 (-100) :xyz} +do_test printf-2.2.9.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -99.99999 +} {abc: 5 5 (-100.000) :xyz} +do_test printf-2.2.9.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -99.99999 +} {abc: 5 5 (-000000100) :xyz} +do_test printf-2.2.9.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 -99.99999 +} {abc: 5 5 (-99.99999) :xyz} +do_test printf-2.2.9.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -99.99999 +} {abc: 5 5 (-1.00000e+02) :xyz} +do_test printf-2.2.9.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -99.99999 +} {abc: 5 5 ( -100) :xyz} +do_test printf-2.2.10.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 3.14e+9 +} {abc: (3140000000.00000) :xyz} +do_test printf-2.2.10.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 3.14e+9 +} {abc: (3.14000e+09) :xyz} +do_test printf-2.2.10.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 3.14e+9 +} {abc: (3.14e+09) :xyz} +do_test printf-2.2.10.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 3.14e+9 +} {abc: 5 5 (3.14e+09) :xyz} +do_test printf-2.2.10.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 3.14e+9 +} {abc: 5 5 (3.14000e+09) :xyz} +do_test printf-2.2.10.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 3.14e+9 +} {abc: 5 5 (003.14e+09) :xyz} +do_test printf-2.2.10.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 3.14e+9 +} {abc: 5 5 (3140000000.00000) :xyz} +do_test printf-2.2.10.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 3.14e+9 +} {abc: 5 5 (3.14000e+09) :xyz} +do_test printf-2.2.10.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 3.14e+9 +} {abc: 5 5 (3.14e+09) :xyz} +do_test printf-2.2.11.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -4.72732e+88 +} {abc: (-4.72732e+88) :xyz} +do_test printf-2.2.11.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -4.72732e+88 +} {abc: (-4.7273e+88) :xyz} +do_test printf-2.2.11.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -4.72732e+88 +} {abc: 5 5 (-4.72732e+88) :xyz} +do_test printf-2.2.11.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -4.72732e+88 +} {abc: 5 5 (-4.72732e+88) :xyz} +do_test printf-2.2.11.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -4.72732e+88 +} {abc: 5 5 (-4.72732e+88) :xyz} +do_test printf-2.2.11.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -4.72732e+88 +} {abc: 5 5 (-4.72732e+88) :xyz} +do_test printf-2.2.11.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -4.72732e+88 +} {abc: 5 5 (-4.7273e+88) :xyz} +do_test printf-2.2.12.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 9.87991e+143 +} {abc: (9.87991e+143) :xyz} +do_test printf-2.2.12.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 9.87991e+143 +} {abc: (9.8799e+143) :xyz} +do_test printf-2.2.12.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 9.87991e+143 +} {abc: 5 5 (9.87991e+143) :xyz} +do_test printf-2.2.12.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 9.87991e+143 +} {abc: 5 5 (9.87991e+143) :xyz} +do_test printf-2.2.12.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 9.87991e+143 +} {abc: 5 5 (9.87991e+143) :xyz} +do_test printf-2.2.12.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 9.87991e+143 +} {abc: 5 5 (9.87991e+143) :xyz} +do_test printf-2.2.12.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 9.87991e+143 +} {abc: 5 5 (9.8799e+143) :xyz} +do_test printf-2.2.13.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 -6.287291e-9 +} {abc: (-0.00000) :xyz} +do_test printf-2.2.13.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 -6.287291e-9 +} {abc: (-6.28729e-09) :xyz} +do_test printf-2.2.13.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 -6.287291e-9 +} {abc: (-6.2873e-09) :xyz} +do_test printf-2.2.13.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 -6.287291e-9 +} {abc: 5 5 (-6.28729e-09) :xyz} +do_test printf-2.2.13.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 -6.287291e-9 +} {abc: 5 5 (-6.28729e-09) :xyz} +do_test printf-2.2.13.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 -6.287291e-9 +} {abc: 5 5 (-6.28729e-09) :xyz} +do_test printf-2.2.13.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 -6.287291e-9 +} {abc: 5 5 (-0.00000) :xyz} +do_test printf-2.2.13.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 -6.287291e-9 +} {abc: 5 5 (-6.28729e-09) :xyz} +do_test printf-2.2.13.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 -6.287291e-9 +} {abc: 5 5 (-6.2873e-09) :xyz} +do_test printf-2.2.14.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 5 5 3.38826392e-110 +} {abc: (0.00000) :xyz} +do_test printf-2.2.14.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 5 5 3.38826392e-110 +} {abc: (3.38826e-110) :xyz} +do_test printf-2.2.14.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 5 5 3.38826392e-110 +} {abc: (3.3883e-110) :xyz} +do_test printf-2.2.14.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 5 5 3.38826392e-110 +} {abc: 5 5 (3.38826e-110) :xyz} +do_test printf-2.2.14.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 5 5 3.38826392e-110 +} {abc: 5 5 (3.38826e-110) :xyz} +do_test printf-2.2.14.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 5 5 3.38826392e-110 +} {abc: 5 5 (3.38826e-110) :xyz} +do_test printf-2.2.14.7 { + sqlite3_mprintf_double {abc: %d %d (%5.5f) :xyz} 5 5 3.38826392e-110 +} {abc: 5 5 (0.00000) :xyz} +do_test printf-2.2.14.8 { + sqlite3_mprintf_double {abc: %d %d (%5.5e) :xyz} 5 5 3.38826392e-110 +} {abc: 5 5 (3.38826e-110) :xyz} +do_test printf-2.2.14.9 { + sqlite3_mprintf_double {abc: %d %d (%5.5g) :xyz} 5 5 3.38826392e-110 +} {abc: 5 5 (3.3883e-110) :xyz} +do_test printf-2.3.1.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 0.001 +} {abc: (0.0010000000) :xyz} +do_test printf-2.3.1.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 0.001 +} {abc: (1.0000000000e-03) :xyz} +do_test printf-2.3.1.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 0.001 +} {abc: ( 0.001) :xyz} +do_test printf-2.3.1.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 0.001 +} {abc: 10 10 (0.001) :xyz} +do_test printf-2.3.1.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 0.001 +} {abc: 10 10 (0.00100000) :xyz} +do_test printf-2.3.1.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 0.001 +} {abc: 10 10 (000000.001) :xyz} +do_test printf-2.3.1.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 0.001 +} {abc: 10 10 (0.0010000000) :xyz} +do_test printf-2.3.1.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 0.001 +} {abc: 10 10 (1.0000000000e-03) :xyz} +do_test printf-2.3.1.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 0.001 +} {abc: 10 10 ( 0.001) :xyz} +do_test printf-2.3.2.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 1.0e-20 +} {abc: (0.0000000000) :xyz} +do_test printf-2.3.2.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 1.0e-20 +} {abc: (1.0000000000e-20) :xyz} +do_test printf-2.3.2.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 1.0e-20 +} {abc: ( 1e-20) :xyz} +do_test printf-2.3.2.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 1.0e-20 +} {abc: 10 10 (1e-20) :xyz} +do_test printf-2.3.2.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 1.0e-20 +} {abc: 10 10 (1.00000e-20) :xyz} +do_test printf-2.3.2.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 1.0e-20 +} {abc: 10 10 (000001e-20) :xyz} +do_test printf-2.3.2.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 1.0e-20 +} {abc: 10 10 (0.0000000000) :xyz} +do_test printf-2.3.2.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 1.0e-20 +} {abc: 10 10 (1.0000000000e-20) :xyz} +do_test printf-2.3.2.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 1.0e-20 +} {abc: 10 10 ( 1e-20) :xyz} +do_test printf-2.3.3.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 1.0 +} {abc: (1.0000000000) :xyz} +do_test printf-2.3.3.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 1.0 +} {abc: (1.0000000000e+00) :xyz} +do_test printf-2.3.3.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 1.0 +} {abc: ( 1) :xyz} +do_test printf-2.3.3.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 1.0 +} {abc: 10 10 (1) :xyz} +do_test printf-2.3.3.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 1.0 +} {abc: 10 10 (1.00000) :xyz} +do_test printf-2.3.3.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 1.0 +} {abc: 10 10 (0000000001) :xyz} +do_test printf-2.3.3.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 1.0 +} {abc: 10 10 (1.0000000000) :xyz} +do_test printf-2.3.3.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 1.0 +} {abc: 10 10 (1.0000000000e+00) :xyz} +do_test printf-2.3.3.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 1.0 +} {abc: 10 10 ( 1) :xyz} +do_test printf-2.3.4.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 0.0 +} {abc: (0.0000000000) :xyz} +do_test printf-2.3.4.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 0.0 +} {abc: (0.0000000000e+00) :xyz} +do_test printf-2.3.4.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 0.0 +} {abc: ( 0) :xyz} +do_test printf-2.3.4.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 0.0 +} {abc: 10 10 (0) :xyz} +do_test printf-2.3.4.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 0.0 +} {abc: 10 10 (0.00000) :xyz} +do_test printf-2.3.4.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 0.0 +} {abc: 10 10 (0000000000) :xyz} +do_test printf-2.3.4.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 0.0 +} {abc: 10 10 (0.0000000000) :xyz} +do_test printf-2.3.4.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 0.0 +} {abc: 10 10 (0.0000000000e+00) :xyz} +do_test printf-2.3.4.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 0.0 +} {abc: 10 10 ( 0) :xyz} +do_test printf-2.3.5.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 100.0 +} {abc: (100.0000000000) :xyz} +do_test printf-2.3.5.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 100.0 +} {abc: (1.0000000000e+02) :xyz} +do_test printf-2.3.5.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 100.0 +} {abc: ( 100) :xyz} +do_test printf-2.3.5.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 100.0 +} {abc: 10 10 (100) :xyz} +do_test printf-2.3.5.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 100.0 +} {abc: 10 10 (100.000) :xyz} +do_test printf-2.3.5.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 100.0 +} {abc: 10 10 (0000000100) :xyz} +do_test printf-2.3.5.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 100.0 +} {abc: 10 10 (100.0000000000) :xyz} +do_test printf-2.3.5.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 100.0 +} {abc: 10 10 (1.0000000000e+02) :xyz} +do_test printf-2.3.5.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 100.0 +} {abc: 10 10 ( 100) :xyz} +do_test printf-2.3.6.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 9.99999 +} {abc: (9.9999900000) :xyz} +do_test printf-2.3.6.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 9.99999 +} {abc: (9.9999900000e+00) :xyz} +do_test printf-2.3.6.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 9.99999 +} {abc: ( 9.99999) :xyz} +do_test printf-2.3.6.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 9.99999 +} {abc: 10 10 (9.99999) :xyz} +do_test printf-2.3.6.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 9.99999 +} {abc: 10 10 (9.99999) :xyz} +do_test printf-2.3.6.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 9.99999 +} {abc: 10 10 (0009.99999) :xyz} +do_test printf-2.3.6.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 9.99999 +} {abc: 10 10 (9.9999900000) :xyz} +do_test printf-2.3.6.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 9.99999 +} {abc: 10 10 (9.9999900000e+00) :xyz} +do_test printf-2.3.6.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 9.99999 +} {abc: 10 10 ( 9.99999) :xyz} +do_test printf-2.3.7.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 -0.00543 +} {abc: (-0.0054300000) :xyz} +do_test printf-2.3.7.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -0.00543 +} {abc: (-5.4300000000e-03) :xyz} +do_test printf-2.3.7.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -0.00543 +} {abc: ( -0.00543) :xyz} +do_test printf-2.3.7.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -0.00543 +} {abc: 10 10 (-0.00543) :xyz} +do_test printf-2.3.7.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -0.00543 +} {abc: 10 10 (-0.00543000) :xyz} +do_test printf-2.3.7.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -0.00543 +} {abc: 10 10 (-000.00543) :xyz} +do_test printf-2.3.7.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 -0.00543 +} {abc: 10 10 (-0.0054300000) :xyz} +do_test printf-2.3.7.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -0.00543 +} {abc: 10 10 (-5.4300000000e-03) :xyz} +do_test printf-2.3.7.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -0.00543 +} {abc: 10 10 ( -0.00543) :xyz} +do_test printf-2.3.8.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 -1.0 +} {abc: (-1.0000000000) :xyz} +do_test printf-2.3.8.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -1.0 +} {abc: (-1.0000000000e+00) :xyz} +do_test printf-2.3.8.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -1.0 +} {abc: ( -1) :xyz} +do_test printf-2.3.8.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -1.0 +} {abc: 10 10 (-1) :xyz} +do_test printf-2.3.8.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -1.0 +} {abc: 10 10 (-1.00000) :xyz} +do_test printf-2.3.8.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -1.0 +} {abc: 10 10 (-000000001) :xyz} +do_test printf-2.3.8.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 -1.0 +} {abc: 10 10 (-1.0000000000) :xyz} +do_test printf-2.3.8.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -1.0 +} {abc: 10 10 (-1.0000000000e+00) :xyz} +do_test printf-2.3.8.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -1.0 +} {abc: 10 10 ( -1) :xyz} +do_test printf-2.3.9.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 -99.99999 +} {abc: (-99.9999900000) :xyz} +do_test printf-2.3.9.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -99.99999 +} {abc: (-9.9999990000e+01) :xyz} +do_test printf-2.3.9.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -99.99999 +} {abc: ( -99.99999) :xyz} +do_test printf-2.3.9.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -99.99999 +} {abc: 10 10 (-100) :xyz} +do_test printf-2.3.9.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -99.99999 +} {abc: 10 10 (-100.000) :xyz} +do_test printf-2.3.9.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -99.99999 +} {abc: 10 10 (-000000100) :xyz} +do_test printf-2.3.9.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 -99.99999 +} {abc: 10 10 (-99.9999900000) :xyz} +do_test printf-2.3.9.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -99.99999 +} {abc: 10 10 (-9.9999990000e+01) :xyz} +do_test printf-2.3.9.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -99.99999 +} {abc: 10 10 ( -99.99999) :xyz} +do_test printf-2.3.10.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 3.14e+9 +} {abc: (3140000000.0000000000) :xyz} +do_test printf-2.3.10.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 3.14e+9 +} {abc: (3.1400000000e+09) :xyz} +do_test printf-2.3.10.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 3.14e+9 +} {abc: (3140000000) :xyz} +do_test printf-2.3.10.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 3.14e+9 +} {abc: 10 10 (3.14e+09) :xyz} +do_test printf-2.3.10.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 3.14e+9 +} {abc: 10 10 (3.14000e+09) :xyz} +do_test printf-2.3.10.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 3.14e+9 +} {abc: 10 10 (003.14e+09) :xyz} +do_test printf-2.3.10.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 3.14e+9 +} {abc: 10 10 (3140000000.0000000000) :xyz} +do_test printf-2.3.10.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 3.14e+9 +} {abc: 10 10 (3.1400000000e+09) :xyz} +do_test printf-2.3.10.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 3.14e+9 +} {abc: 10 10 (3140000000) :xyz} +do_test printf-2.3.11.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -4.72732e+88 +} {abc: (-4.7273200000e+88) :xyz} +do_test printf-2.3.11.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -4.72732e+88 +} {abc: (-4.72732e+88) :xyz} +do_test printf-2.3.11.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -4.72732e+88 +} {abc: 10 10 (-4.72732e+88) :xyz} +do_test printf-2.3.11.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -4.72732e+88 +} {abc: 10 10 (-4.72732e+88) :xyz} +do_test printf-2.3.11.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -4.72732e+88 +} {abc: 10 10 (-4.72732e+88) :xyz} +do_test printf-2.3.11.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -4.72732e+88 +} {abc: 10 10 (-4.7273200000e+88) :xyz} +do_test printf-2.3.11.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -4.72732e+88 +} {abc: 10 10 (-4.72732e+88) :xyz} +do_test printf-2.3.12.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 9.87991e+143 +} {abc: (9.8799100000e+143) :xyz} +do_test printf-2.3.12.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 9.87991e+143 +} {abc: (9.87991e+143) :xyz} +do_test printf-2.3.12.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 9.87991e+143 +} {abc: 10 10 (9.87991e+143) :xyz} +do_test printf-2.3.12.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 9.87991e+143 +} {abc: 10 10 (9.87991e+143) :xyz} +do_test printf-2.3.12.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 9.87991e+143 +} {abc: 10 10 (9.87991e+143) :xyz} +do_test printf-2.3.12.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 9.87991e+143 +} {abc: 10 10 (9.8799100000e+143) :xyz} +do_test printf-2.3.12.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 9.87991e+143 +} {abc: 10 10 (9.87991e+143) :xyz} +do_test printf-2.3.13.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 -6.287291e-9 +} {abc: (-0.0000000063) :xyz} +do_test printf-2.3.13.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 -6.287291e-9 +} {abc: (-6.2872910000e-09) :xyz} +do_test printf-2.3.13.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 -6.287291e-9 +} {abc: (-6.287291e-09) :xyz} +do_test printf-2.3.13.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 -6.287291e-9 +} {abc: 10 10 (-6.28729e-09) :xyz} +do_test printf-2.3.13.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 -6.287291e-9 +} {abc: 10 10 (-6.28729e-09) :xyz} +do_test printf-2.3.13.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 -6.287291e-9 +} {abc: 10 10 (-6.28729e-09) :xyz} +do_test printf-2.3.13.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 -6.287291e-9 +} {abc: 10 10 (-0.0000000063) :xyz} +do_test printf-2.3.13.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 -6.287291e-9 +} {abc: 10 10 (-6.2872910000e-09) :xyz} +do_test printf-2.3.13.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 -6.287291e-9 +} {abc: 10 10 (-6.287291e-09) :xyz} +do_test printf-2.3.14.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 10 3.38826392e-110 +} {abc: (0.0000000000) :xyz} +do_test printf-2.3.14.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 10 3.38826392e-110 +} {abc: (3.3882639200e-110) :xyz} +do_test printf-2.3.14.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 10 3.38826392e-110 +} {abc: (3.38826392e-110) :xyz} +do_test printf-2.3.14.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 10 3.38826392e-110 +} {abc: 10 10 (3.38826e-110) :xyz} +do_test printf-2.3.14.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 10 3.38826392e-110 +} {abc: 10 10 (3.38826e-110) :xyz} +do_test printf-2.3.14.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 10 3.38826392e-110 +} {abc: 10 10 (3.38826e-110) :xyz} +do_test printf-2.3.14.7 { + sqlite3_mprintf_double {abc: %d %d (%10.10f) :xyz} 10 10 3.38826392e-110 +} {abc: 10 10 (0.0000000000) :xyz} +do_test printf-2.3.14.8 { + sqlite3_mprintf_double {abc: %d %d (%10.10e) :xyz} 10 10 3.38826392e-110 +} {abc: 10 10 (3.3882639200e-110) :xyz} +do_test printf-2.3.14.9 { + sqlite3_mprintf_double {abc: %d %d (%10.10g) :xyz} 10 10 3.38826392e-110 +} {abc: 10 10 (3.38826392e-110) :xyz} +do_test printf-2.4.1.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 0.001 +} {abc: ( 0.00100) :xyz} +do_test printf-2.4.1.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 0.001 +} {abc: (1.00000e-03) :xyz} +do_test printf-2.4.1.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 0.001 +} {abc: ( 0.001) :xyz} +do_test printf-2.4.1.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 0.001 +} {abc: 10 5 (0.001) :xyz} +do_test printf-2.4.1.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 0.001 +} {abc: 10 5 (0.00100000) :xyz} +do_test printf-2.4.1.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 0.001 +} {abc: 10 5 (000000.001) :xyz} +do_test printf-2.4.1.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 0.001 +} {abc: 10 5 ( 0.00100) :xyz} +do_test printf-2.4.1.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 0.001 +} {abc: 10 5 (1.00000e-03) :xyz} +do_test printf-2.4.1.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 0.001 +} {abc: 10 5 ( 0.001) :xyz} +do_test printf-2.4.2.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 1.0e-20 +} {abc: ( 0.00000) :xyz} +do_test printf-2.4.2.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 1.0e-20 +} {abc: (1.00000e-20) :xyz} +do_test printf-2.4.2.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 1.0e-20 +} {abc: ( 1e-20) :xyz} +do_test printf-2.4.2.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 1.0e-20 +} {abc: 10 5 (1e-20) :xyz} +do_test printf-2.4.2.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 1.0e-20 +} {abc: 10 5 (1.00000e-20) :xyz} +do_test printf-2.4.2.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 1.0e-20 +} {abc: 10 5 (000001e-20) :xyz} +do_test printf-2.4.2.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 1.0e-20 +} {abc: 10 5 ( 0.00000) :xyz} +do_test printf-2.4.2.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 1.0e-20 +} {abc: 10 5 (1.00000e-20) :xyz} +do_test printf-2.4.2.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 1.0e-20 +} {abc: 10 5 ( 1e-20) :xyz} +do_test printf-2.4.3.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 1.0 +} {abc: ( 1.00000) :xyz} +do_test printf-2.4.3.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 1.0 +} {abc: (1.00000e+00) :xyz} +do_test printf-2.4.3.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 1.0 +} {abc: ( 1) :xyz} +do_test printf-2.4.3.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 1.0 +} {abc: 10 5 (1) :xyz} +do_test printf-2.4.3.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 1.0 +} {abc: 10 5 (1.00000) :xyz} +do_test printf-2.4.3.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 1.0 +} {abc: 10 5 (0000000001) :xyz} +do_test printf-2.4.3.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 1.0 +} {abc: 10 5 ( 1.00000) :xyz} +do_test printf-2.4.3.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 1.0 +} {abc: 10 5 (1.00000e+00) :xyz} +do_test printf-2.4.3.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 1.0 +} {abc: 10 5 ( 1) :xyz} +do_test printf-2.4.4.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 0.0 +} {abc: ( 0.00000) :xyz} +do_test printf-2.4.4.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 0.0 +} {abc: (0.00000e+00) :xyz} +do_test printf-2.4.4.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 0.0 +} {abc: ( 0) :xyz} +do_test printf-2.4.4.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 0.0 +} {abc: 10 5 (0) :xyz} +do_test printf-2.4.4.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 0.0 +} {abc: 10 5 (0.00000) :xyz} +do_test printf-2.4.4.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 0.0 +} {abc: 10 5 (0000000000) :xyz} +do_test printf-2.4.4.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 0.0 +} {abc: 10 5 ( 0.00000) :xyz} +do_test printf-2.4.4.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 0.0 +} {abc: 10 5 (0.00000e+00) :xyz} +do_test printf-2.4.4.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 0.0 +} {abc: 10 5 ( 0) :xyz} +do_test printf-2.4.5.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 100.0 +} {abc: ( 100.00000) :xyz} +do_test printf-2.4.5.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 100.0 +} {abc: (1.00000e+02) :xyz} +do_test printf-2.4.5.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 100.0 +} {abc: ( 100) :xyz} +do_test printf-2.4.5.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 100.0 +} {abc: 10 5 (100) :xyz} +do_test printf-2.4.5.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 100.0 +} {abc: 10 5 (100.000) :xyz} +do_test printf-2.4.5.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 100.0 +} {abc: 10 5 (0000000100) :xyz} +do_test printf-2.4.5.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 100.0 +} {abc: 10 5 ( 100.00000) :xyz} +do_test printf-2.4.5.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 100.0 +} {abc: 10 5 (1.00000e+02) :xyz} +do_test printf-2.4.5.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 100.0 +} {abc: 10 5 ( 100) :xyz} +do_test printf-2.4.6.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 9.99999 +} {abc: ( 9.99999) :xyz} +do_test printf-2.4.6.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 9.99999 +} {abc: (9.99999e+00) :xyz} +do_test printf-2.4.6.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 9.99999 +} {abc: ( 10) :xyz} +do_test printf-2.4.6.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 9.99999 +} {abc: 10 5 (9.99999) :xyz} +do_test printf-2.4.6.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 9.99999 +} {abc: 10 5 (9.99999) :xyz} +do_test printf-2.4.6.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 9.99999 +} {abc: 10 5 (0009.99999) :xyz} +do_test printf-2.4.6.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 9.99999 +} {abc: 10 5 ( 9.99999) :xyz} +do_test printf-2.4.6.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 9.99999 +} {abc: 10 5 (9.99999e+00) :xyz} +do_test printf-2.4.6.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 9.99999 +} {abc: 10 5 ( 10) :xyz} +do_test printf-2.4.7.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 -0.00543 +} {abc: ( -0.00543) :xyz} +do_test printf-2.4.7.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -0.00543 +} {abc: (-5.43000e-03) :xyz} +do_test printf-2.4.7.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -0.00543 +} {abc: ( -0.00543) :xyz} +do_test printf-2.4.7.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -0.00543 +} {abc: 10 5 (-0.00543) :xyz} +do_test printf-2.4.7.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -0.00543 +} {abc: 10 5 (-0.00543000) :xyz} +do_test printf-2.4.7.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -0.00543 +} {abc: 10 5 (-000.00543) :xyz} +do_test printf-2.4.7.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 -0.00543 +} {abc: 10 5 ( -0.00543) :xyz} +do_test printf-2.4.7.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -0.00543 +} {abc: 10 5 (-5.43000e-03) :xyz} +do_test printf-2.4.7.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -0.00543 +} {abc: 10 5 ( -0.00543) :xyz} +do_test printf-2.4.8.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 -1.0 +} {abc: ( -1.00000) :xyz} +do_test printf-2.4.8.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -1.0 +} {abc: (-1.00000e+00) :xyz} +do_test printf-2.4.8.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -1.0 +} {abc: ( -1) :xyz} +do_test printf-2.4.8.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -1.0 +} {abc: 10 5 (-1) :xyz} +do_test printf-2.4.8.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -1.0 +} {abc: 10 5 (-1.00000) :xyz} +do_test printf-2.4.8.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -1.0 +} {abc: 10 5 (-000000001) :xyz} +do_test printf-2.4.8.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 -1.0 +} {abc: 10 5 ( -1.00000) :xyz} +do_test printf-2.4.8.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -1.0 +} {abc: 10 5 (-1.00000e+00) :xyz} +do_test printf-2.4.8.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -1.0 +} {abc: 10 5 ( -1) :xyz} +do_test printf-2.4.9.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 -99.99999 +} {abc: ( -99.99999) :xyz} +do_test printf-2.4.9.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -99.99999 +} {abc: (-1.00000e+02) :xyz} +do_test printf-2.4.9.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -99.99999 +} {abc: ( -100) :xyz} +do_test printf-2.4.9.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -99.99999 +} {abc: 10 5 (-100) :xyz} +do_test printf-2.4.9.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -99.99999 +} {abc: 10 5 (-100.000) :xyz} +do_test printf-2.4.9.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -99.99999 +} {abc: 10 5 (-000000100) :xyz} +do_test printf-2.4.9.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 -99.99999 +} {abc: 10 5 ( -99.99999) :xyz} +do_test printf-2.4.9.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -99.99999 +} {abc: 10 5 (-1.00000e+02) :xyz} +do_test printf-2.4.9.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -99.99999 +} {abc: 10 5 ( -100) :xyz} +do_test printf-2.4.10.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 3.14e+9 +} {abc: (3140000000.00000) :xyz} +do_test printf-2.4.10.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 3.14e+9 +} {abc: (3.14000e+09) :xyz} +do_test printf-2.4.10.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 3.14e+9 +} {abc: ( 3.14e+09) :xyz} +do_test printf-2.4.10.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 3.14e+9 +} {abc: 10 5 (3.14e+09) :xyz} +do_test printf-2.4.10.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 3.14e+9 +} {abc: 10 5 (3.14000e+09) :xyz} +do_test printf-2.4.10.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 3.14e+9 +} {abc: 10 5 (003.14e+09) :xyz} +do_test printf-2.4.10.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 3.14e+9 +} {abc: 10 5 (3140000000.00000) :xyz} +do_test printf-2.4.10.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 3.14e+9 +} {abc: 10 5 (3.14000e+09) :xyz} +do_test printf-2.4.10.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 3.14e+9 +} {abc: 10 5 ( 3.14e+09) :xyz} +do_test printf-2.4.11.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -4.72732e+88 +} {abc: (-4.72732e+88) :xyz} +do_test printf-2.4.11.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -4.72732e+88 +} {abc: (-4.7273e+88) :xyz} +do_test printf-2.4.11.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -4.72732e+88 +} {abc: 10 5 (-4.72732e+88) :xyz} +do_test printf-2.4.11.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -4.72732e+88 +} {abc: 10 5 (-4.72732e+88) :xyz} +do_test printf-2.4.11.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -4.72732e+88 +} {abc: 10 5 (-4.72732e+88) :xyz} +do_test printf-2.4.11.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -4.72732e+88 +} {abc: 10 5 (-4.72732e+88) :xyz} +do_test printf-2.4.11.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -4.72732e+88 +} {abc: 10 5 (-4.7273e+88) :xyz} +do_test printf-2.4.12.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 9.87991e+143 +} {abc: (9.87991e+143) :xyz} +do_test printf-2.4.12.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 9.87991e+143 +} {abc: (9.8799e+143) :xyz} +do_test printf-2.4.12.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 9.87991e+143 +} {abc: 10 5 (9.87991e+143) :xyz} +do_test printf-2.4.12.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 9.87991e+143 +} {abc: 10 5 (9.87991e+143) :xyz} +do_test printf-2.4.12.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 9.87991e+143 +} {abc: 10 5 (9.87991e+143) :xyz} +do_test printf-2.4.12.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 9.87991e+143 +} {abc: 10 5 (9.87991e+143) :xyz} +do_test printf-2.4.12.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 9.87991e+143 +} {abc: 10 5 (9.8799e+143) :xyz} +do_test printf-2.4.13.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 -6.287291e-9 +} {abc: ( -0.00000) :xyz} +do_test printf-2.4.13.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 -6.287291e-9 +} {abc: (-6.28729e-09) :xyz} +do_test printf-2.4.13.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 -6.287291e-9 +} {abc: (-6.2873e-09) :xyz} +do_test printf-2.4.13.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 -6.287291e-9 +} {abc: 10 5 (-6.28729e-09) :xyz} +do_test printf-2.4.13.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 -6.287291e-9 +} {abc: 10 5 (-6.28729e-09) :xyz} +do_test printf-2.4.13.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 -6.287291e-9 +} {abc: 10 5 (-6.28729e-09) :xyz} +do_test printf-2.4.13.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 -6.287291e-9 +} {abc: 10 5 ( -0.00000) :xyz} +do_test printf-2.4.13.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 -6.287291e-9 +} {abc: 10 5 (-6.28729e-09) :xyz} +do_test printf-2.4.13.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 -6.287291e-9 +} {abc: 10 5 (-6.2873e-09) :xyz} +do_test printf-2.4.14.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 10 5 3.38826392e-110 +} {abc: ( 0.00000) :xyz} +do_test printf-2.4.14.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 10 5 3.38826392e-110 +} {abc: (3.38826e-110) :xyz} +do_test printf-2.4.14.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 10 5 3.38826392e-110 +} {abc: (3.3883e-110) :xyz} +do_test printf-2.4.14.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 10 5 3.38826392e-110 +} {abc: 10 5 (3.38826e-110) :xyz} +do_test printf-2.4.14.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 10 5 3.38826392e-110 +} {abc: 10 5 (3.38826e-110) :xyz} +do_test printf-2.4.14.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 10 5 3.38826392e-110 +} {abc: 10 5 (3.38826e-110) :xyz} +do_test printf-2.4.14.7 { + sqlite3_mprintf_double {abc: %d %d (%10.5f) :xyz} 10 5 3.38826392e-110 +} {abc: 10 5 ( 0.00000) :xyz} +do_test printf-2.4.14.8 { + sqlite3_mprintf_double {abc: %d %d (%10.5e) :xyz} 10 5 3.38826392e-110 +} {abc: 10 5 (3.38826e-110) :xyz} +do_test printf-2.4.14.9 { + sqlite3_mprintf_double {abc: %d %d (%10.5g) :xyz} 10 5 3.38826392e-110 +} {abc: 10 5 (3.3883e-110) :xyz} +do_test printf-2.5.1.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 0.001 +} {abc: (0.00) :xyz} +do_test printf-2.5.1.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 0.001 +} {abc: (1.00e-03) :xyz} +do_test printf-2.5.1.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 0.001 +} {abc: (0.001) :xyz} +do_test printf-2.5.1.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 0.001 +} {abc: 2 2 (0.001) :xyz} +do_test printf-2.5.1.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 0.001 +} {abc: 2 2 (0.00100000) :xyz} +do_test printf-2.5.1.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 0.001 +} {abc: 2 2 (000000.001) :xyz} +do_test printf-2.5.1.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 0.001 +} {abc: 2 2 (0.00) :xyz} +do_test printf-2.5.1.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 0.001 +} {abc: 2 2 (1.00e-03) :xyz} +do_test printf-2.5.1.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 0.001 +} {abc: 2 2 (0.001) :xyz} +do_test printf-2.5.2.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 1.0e-20 +} {abc: (0.00) :xyz} +do_test printf-2.5.2.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 1.0e-20 +} {abc: (1.00e-20) :xyz} +do_test printf-2.5.2.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 1.0e-20 +} {abc: (1e-20) :xyz} +do_test printf-2.5.2.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 1.0e-20 +} {abc: 2 2 (1e-20) :xyz} +do_test printf-2.5.2.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 1.0e-20 +} {abc: 2 2 (1.00000e-20) :xyz} +do_test printf-2.5.2.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 1.0e-20 +} {abc: 2 2 (000001e-20) :xyz} +do_test printf-2.5.2.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 1.0e-20 +} {abc: 2 2 (0.00) :xyz} +do_test printf-2.5.2.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 1.0e-20 +} {abc: 2 2 (1.00e-20) :xyz} +do_test printf-2.5.2.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 1.0e-20 +} {abc: 2 2 (1e-20) :xyz} +do_test printf-2.5.3.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 1.0 +} {abc: (1.00) :xyz} +do_test printf-2.5.3.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 1.0 +} {abc: (1.00e+00) :xyz} +do_test printf-2.5.3.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 1.0 +} {abc: ( 1) :xyz} +do_test printf-2.5.3.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 1.0 +} {abc: 2 2 (1) :xyz} +do_test printf-2.5.3.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 1.0 +} {abc: 2 2 (1.00000) :xyz} +do_test printf-2.5.3.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 1.0 +} {abc: 2 2 (0000000001) :xyz} +do_test printf-2.5.3.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 1.0 +} {abc: 2 2 (1.00) :xyz} +do_test printf-2.5.3.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 1.0 +} {abc: 2 2 (1.00e+00) :xyz} +do_test printf-2.5.3.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 1.0 +} {abc: 2 2 ( 1) :xyz} +do_test printf-2.5.4.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 0.0 +} {abc: (0.00) :xyz} +do_test printf-2.5.4.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 0.0 +} {abc: (0.00e+00) :xyz} +do_test printf-2.5.4.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 0.0 +} {abc: ( 0) :xyz} +do_test printf-2.5.4.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 0.0 +} {abc: 2 2 (0) :xyz} +do_test printf-2.5.4.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 0.0 +} {abc: 2 2 (0.00000) :xyz} +do_test printf-2.5.4.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 0.0 +} {abc: 2 2 (0000000000) :xyz} +do_test printf-2.5.4.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 0.0 +} {abc: 2 2 (0.00) :xyz} +do_test printf-2.5.4.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 0.0 +} {abc: 2 2 (0.00e+00) :xyz} +do_test printf-2.5.4.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 0.0 +} {abc: 2 2 ( 0) :xyz} +do_test printf-2.5.5.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 100.0 +} {abc: (100.00) :xyz} +do_test printf-2.5.5.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 100.0 +} {abc: (1.00e+02) :xyz} +do_test printf-2.5.5.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 100.0 +} {abc: (1e+02) :xyz} +do_test printf-2.5.5.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 100.0 +} {abc: 2 2 (100) :xyz} +do_test printf-2.5.5.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 100.0 +} {abc: 2 2 (100.000) :xyz} +do_test printf-2.5.5.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 100.0 +} {abc: 2 2 (0000000100) :xyz} +do_test printf-2.5.5.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 100.0 +} {abc: 2 2 (100.00) :xyz} +do_test printf-2.5.5.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 100.0 +} {abc: 2 2 (1.00e+02) :xyz} +do_test printf-2.5.5.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 100.0 +} {abc: 2 2 (1e+02) :xyz} +do_test printf-2.5.6.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 9.99999 +} {abc: (10.00) :xyz} +do_test printf-2.5.6.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 9.99999 +} {abc: (1.00e+01) :xyz} +do_test printf-2.5.6.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 9.99999 +} {abc: (10) :xyz} +do_test printf-2.5.6.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 9.99999 +} {abc: 2 2 (9.99999) :xyz} +do_test printf-2.5.6.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 9.99999 +} {abc: 2 2 (9.99999) :xyz} +do_test printf-2.5.6.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 9.99999 +} {abc: 2 2 (0009.99999) :xyz} +do_test printf-2.5.6.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 9.99999 +} {abc: 2 2 (10.00) :xyz} +do_test printf-2.5.6.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 9.99999 +} {abc: 2 2 (1.00e+01) :xyz} +do_test printf-2.5.6.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 9.99999 +} {abc: 2 2 (10) :xyz} +do_test printf-2.5.7.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 -0.00543 +} {abc: (-0.01) :xyz} +do_test printf-2.5.7.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -0.00543 +} {abc: (-5.43e-03) :xyz} +do_test printf-2.5.7.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -0.00543 +} {abc: (-0.0054) :xyz} +do_test printf-2.5.7.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -0.00543 +} {abc: 2 2 (-0.00543) :xyz} +do_test printf-2.5.7.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -0.00543 +} {abc: 2 2 (-0.00543000) :xyz} +do_test printf-2.5.7.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -0.00543 +} {abc: 2 2 (-000.00543) :xyz} +do_test printf-2.5.7.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 -0.00543 +} {abc: 2 2 (-0.01) :xyz} +do_test printf-2.5.7.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -0.00543 +} {abc: 2 2 (-5.43e-03) :xyz} +do_test printf-2.5.7.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -0.00543 +} {abc: 2 2 (-0.0054) :xyz} +do_test printf-2.5.8.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 -1.0 +} {abc: (-1.00) :xyz} +do_test printf-2.5.8.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -1.0 +} {abc: (-1.00e+00) :xyz} +do_test printf-2.5.8.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -1.0 +} {abc: (-1) :xyz} +do_test printf-2.5.8.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -1.0 +} {abc: 2 2 (-1) :xyz} +do_test printf-2.5.8.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -1.0 +} {abc: 2 2 (-1.00000) :xyz} +do_test printf-2.5.8.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -1.0 +} {abc: 2 2 (-000000001) :xyz} +do_test printf-2.5.8.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 -1.0 +} {abc: 2 2 (-1.00) :xyz} +do_test printf-2.5.8.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -1.0 +} {abc: 2 2 (-1.00e+00) :xyz} +do_test printf-2.5.8.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -1.0 +} {abc: 2 2 (-1) :xyz} +do_test printf-2.5.9.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 -99.99999 +} {abc: (-100.00) :xyz} +do_test printf-2.5.9.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -99.99999 +} {abc: (-1.00e+02) :xyz} +do_test printf-2.5.9.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -99.99999 +} {abc: (-1e+02) :xyz} +do_test printf-2.5.9.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -99.99999 +} {abc: 2 2 (-100) :xyz} +do_test printf-2.5.9.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -99.99999 +} {abc: 2 2 (-100.000) :xyz} +do_test printf-2.5.9.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -99.99999 +} {abc: 2 2 (-000000100) :xyz} +do_test printf-2.5.9.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 -99.99999 +} {abc: 2 2 (-100.00) :xyz} +do_test printf-2.5.9.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -99.99999 +} {abc: 2 2 (-1.00e+02) :xyz} +do_test printf-2.5.9.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -99.99999 +} {abc: 2 2 (-1e+02) :xyz} +do_test printf-2.5.10.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 3.14e+9 +} {abc: (3140000000.00) :xyz} +do_test printf-2.5.10.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 3.14e+9 +} {abc: (3.14e+09) :xyz} +do_test printf-2.5.10.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 3.14e+9 +} {abc: (3.1e+09) :xyz} +do_test printf-2.5.10.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 3.14e+9 +} {abc: 2 2 (3.14e+09) :xyz} +do_test printf-2.5.10.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 3.14e+9 +} {abc: 2 2 (3.14000e+09) :xyz} +do_test printf-2.5.10.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 3.14e+9 +} {abc: 2 2 (003.14e+09) :xyz} +do_test printf-2.5.10.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 3.14e+9 +} {abc: 2 2 (3140000000.00) :xyz} +do_test printf-2.5.10.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 3.14e+9 +} {abc: 2 2 (3.14e+09) :xyz} +do_test printf-2.5.10.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 3.14e+9 +} {abc: 2 2 (3.1e+09) :xyz} +do_test printf-2.5.11.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -4.72732e+88 +} {abc: (-4.73e+88) :xyz} +do_test printf-2.5.11.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -4.72732e+88 +} {abc: (-4.7e+88) :xyz} +do_test printf-2.5.11.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -4.72732e+88 +} {abc: 2 2 (-4.72732e+88) :xyz} +do_test printf-2.5.11.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -4.72732e+88 +} {abc: 2 2 (-4.72732e+88) :xyz} +do_test printf-2.5.11.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -4.72732e+88 +} {abc: 2 2 (-4.72732e+88) :xyz} +do_test printf-2.5.11.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -4.72732e+88 +} {abc: 2 2 (-4.73e+88) :xyz} +do_test printf-2.5.11.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -4.72732e+88 +} {abc: 2 2 (-4.7e+88) :xyz} +do_test printf-2.5.12.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 9.87991e+143 +} {abc: (9.88e+143) :xyz} +do_test printf-2.5.12.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 9.87991e+143 +} {abc: (9.9e+143) :xyz} +do_test printf-2.5.12.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 9.87991e+143 +} {abc: 2 2 (9.87991e+143) :xyz} +do_test printf-2.5.12.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 9.87991e+143 +} {abc: 2 2 (9.87991e+143) :xyz} +do_test printf-2.5.12.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 9.87991e+143 +} {abc: 2 2 (9.87991e+143) :xyz} +do_test printf-2.5.12.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 9.87991e+143 +} {abc: 2 2 (9.88e+143) :xyz} +do_test printf-2.5.12.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 9.87991e+143 +} {abc: 2 2 (9.9e+143) :xyz} +do_test printf-2.5.13.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 -6.287291e-9 +} {abc: (-0.00) :xyz} +do_test printf-2.5.13.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 -6.287291e-9 +} {abc: (-6.29e-09) :xyz} +do_test printf-2.5.13.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 -6.287291e-9 +} {abc: (-6.3e-09) :xyz} +do_test printf-2.5.13.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 -6.287291e-9 +} {abc: 2 2 (-6.28729e-09) :xyz} +do_test printf-2.5.13.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 -6.287291e-9 +} {abc: 2 2 (-6.28729e-09) :xyz} +do_test printf-2.5.13.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 -6.287291e-9 +} {abc: 2 2 (-6.28729e-09) :xyz} +do_test printf-2.5.13.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 -6.287291e-9 +} {abc: 2 2 (-0.00) :xyz} +do_test printf-2.5.13.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 -6.287291e-9 +} {abc: 2 2 (-6.29e-09) :xyz} +do_test printf-2.5.13.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 -6.287291e-9 +} {abc: 2 2 (-6.3e-09) :xyz} +do_test printf-2.5.14.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 2 3.38826392e-110 +} {abc: (0.00) :xyz} +do_test printf-2.5.14.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 2 3.38826392e-110 +} {abc: (3.39e-110) :xyz} +do_test printf-2.5.14.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 2 3.38826392e-110 +} {abc: (3.4e-110) :xyz} +do_test printf-2.5.14.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 2 3.38826392e-110 +} {abc: 2 2 (3.38826e-110) :xyz} +do_test printf-2.5.14.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 2 3.38826392e-110 +} {abc: 2 2 (3.38826e-110) :xyz} +do_test printf-2.5.14.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 2 3.38826392e-110 +} {abc: 2 2 (3.38826e-110) :xyz} +do_test printf-2.5.14.7 { + sqlite3_mprintf_double {abc: %d %d (%2.2f) :xyz} 2 2 3.38826392e-110 +} {abc: 2 2 (0.00) :xyz} +do_test printf-2.5.14.8 { + sqlite3_mprintf_double {abc: %d %d (%2.2e) :xyz} 2 2 3.38826392e-110 +} {abc: 2 2 (3.39e-110) :xyz} +do_test printf-2.5.14.9 { + sqlite3_mprintf_double {abc: %d %d (%2.2g) :xyz} 2 2 3.38826392e-110 +} {abc: 2 2 (3.4e-110) :xyz} +do_test printf-2.6.1.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 0.001 +} {abc: (0.001) :xyz} +do_test printf-2.6.1.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 0.001 +} {abc: (1.000e-03) :xyz} +do_test printf-2.6.1.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 0.001 +} {abc: (0.001) :xyz} +do_test printf-2.6.1.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 0.001 +} {abc: 2 3 (0.001) :xyz} +do_test printf-2.6.1.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 0.001 +} {abc: 2 3 (0.00100000) :xyz} +do_test printf-2.6.1.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 0.001 +} {abc: 2 3 (000000.001) :xyz} +do_test printf-2.6.1.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 0.001 +} {abc: 2 3 (0.001) :xyz} +do_test printf-2.6.1.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 0.001 +} {abc: 2 3 (1.000e-03) :xyz} +do_test printf-2.6.1.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 0.001 +} {abc: 2 3 (0.001) :xyz} +do_test printf-2.6.2.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 1.0e-20 +} {abc: (0.000) :xyz} +do_test printf-2.6.2.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 1.0e-20 +} {abc: (1.000e-20) :xyz} +do_test printf-2.6.2.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 1.0e-20 +} {abc: (1e-20) :xyz} +do_test printf-2.6.2.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 1.0e-20 +} {abc: 2 3 (1e-20) :xyz} +do_test printf-2.6.2.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 1.0e-20 +} {abc: 2 3 (1.00000e-20) :xyz} +do_test printf-2.6.2.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 1.0e-20 +} {abc: 2 3 (000001e-20) :xyz} +do_test printf-2.6.2.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 1.0e-20 +} {abc: 2 3 (0.000) :xyz} +do_test printf-2.6.2.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 1.0e-20 +} {abc: 2 3 (1.000e-20) :xyz} +do_test printf-2.6.2.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 1.0e-20 +} {abc: 2 3 (1e-20) :xyz} +do_test printf-2.6.3.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 1.0 +} {abc: (1.000) :xyz} +do_test printf-2.6.3.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 1.0 +} {abc: (1.000e+00) :xyz} +do_test printf-2.6.3.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 1.0 +} {abc: ( 1) :xyz} +do_test printf-2.6.3.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 1.0 +} {abc: 2 3 (1) :xyz} +do_test printf-2.6.3.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 1.0 +} {abc: 2 3 (1.00000) :xyz} +do_test printf-2.6.3.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 1.0 +} {abc: 2 3 (0000000001) :xyz} +do_test printf-2.6.3.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 1.0 +} {abc: 2 3 (1.000) :xyz} +do_test printf-2.6.3.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 1.0 +} {abc: 2 3 (1.000e+00) :xyz} +do_test printf-2.6.3.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 1.0 +} {abc: 2 3 ( 1) :xyz} +do_test printf-2.6.4.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 0.0 +} {abc: (0.000) :xyz} +do_test printf-2.6.4.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 0.0 +} {abc: (0.000e+00) :xyz} +do_test printf-2.6.4.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 0.0 +} {abc: ( 0) :xyz} +do_test printf-2.6.4.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 0.0 +} {abc: 2 3 (0) :xyz} +do_test printf-2.6.4.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 0.0 +} {abc: 2 3 (0.00000) :xyz} +do_test printf-2.6.4.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 0.0 +} {abc: 2 3 (0000000000) :xyz} +do_test printf-2.6.4.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 0.0 +} {abc: 2 3 (0.000) :xyz} +do_test printf-2.6.4.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 0.0 +} {abc: 2 3 (0.000e+00) :xyz} +do_test printf-2.6.4.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 0.0 +} {abc: 2 3 ( 0) :xyz} +do_test printf-2.6.5.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 100.0 +} {abc: (100.000) :xyz} +do_test printf-2.6.5.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 100.0 +} {abc: (1.000e+02) :xyz} +do_test printf-2.6.5.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 100.0 +} {abc: (100) :xyz} +do_test printf-2.6.5.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 100.0 +} {abc: 2 3 (100) :xyz} +do_test printf-2.6.5.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 100.0 +} {abc: 2 3 (100.000) :xyz} +do_test printf-2.6.5.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 100.0 +} {abc: 2 3 (0000000100) :xyz} +do_test printf-2.6.5.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 100.0 +} {abc: 2 3 (100.000) :xyz} +do_test printf-2.6.5.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 100.0 +} {abc: 2 3 (1.000e+02) :xyz} +do_test printf-2.6.5.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 100.0 +} {abc: 2 3 (100) :xyz} +do_test printf-2.6.6.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 9.99999 +} {abc: (10.000) :xyz} +do_test printf-2.6.6.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 9.99999 +} {abc: (1.000e+01) :xyz} +do_test printf-2.6.6.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 9.99999 +} {abc: (10) :xyz} +do_test printf-2.6.6.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 9.99999 +} {abc: 2 3 (9.99999) :xyz} +do_test printf-2.6.6.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 9.99999 +} {abc: 2 3 (9.99999) :xyz} +do_test printf-2.6.6.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 9.99999 +} {abc: 2 3 (0009.99999) :xyz} +do_test printf-2.6.6.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 9.99999 +} {abc: 2 3 (10.000) :xyz} +do_test printf-2.6.6.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 9.99999 +} {abc: 2 3 (1.000e+01) :xyz} +do_test printf-2.6.6.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 9.99999 +} {abc: 2 3 (10) :xyz} +do_test printf-2.6.7.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 -0.00543 +} {abc: (-0.005) :xyz} +do_test printf-2.6.7.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -0.00543 +} {abc: (-5.430e-03) :xyz} +do_test printf-2.6.7.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -0.00543 +} {abc: (-0.00543) :xyz} +do_test printf-2.6.7.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -0.00543 +} {abc: 2 3 (-0.00543) :xyz} +do_test printf-2.6.7.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -0.00543 +} {abc: 2 3 (-0.00543000) :xyz} +do_test printf-2.6.7.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -0.00543 +} {abc: 2 3 (-000.00543) :xyz} +do_test printf-2.6.7.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 -0.00543 +} {abc: 2 3 (-0.005) :xyz} +do_test printf-2.6.7.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -0.00543 +} {abc: 2 3 (-5.430e-03) :xyz} +do_test printf-2.6.7.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -0.00543 +} {abc: 2 3 (-0.00543) :xyz} +do_test printf-2.6.8.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 -1.0 +} {abc: (-1.000) :xyz} +do_test printf-2.6.8.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -1.0 +} {abc: (-1.000e+00) :xyz} +do_test printf-2.6.8.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -1.0 +} {abc: (-1) :xyz} +do_test printf-2.6.8.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -1.0 +} {abc: 2 3 (-1) :xyz} +do_test printf-2.6.8.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -1.0 +} {abc: 2 3 (-1.00000) :xyz} +do_test printf-2.6.8.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -1.0 +} {abc: 2 3 (-000000001) :xyz} +do_test printf-2.6.8.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 -1.0 +} {abc: 2 3 (-1.000) :xyz} +do_test printf-2.6.8.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -1.0 +} {abc: 2 3 (-1.000e+00) :xyz} +do_test printf-2.6.8.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -1.0 +} {abc: 2 3 (-1) :xyz} +do_test printf-2.6.9.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 -99.99999 +} {abc: (-100.000) :xyz} +do_test printf-2.6.9.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -99.99999 +} {abc: (-1.000e+02) :xyz} +do_test printf-2.6.9.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -99.99999 +} {abc: (-100) :xyz} +do_test printf-2.6.9.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -99.99999 +} {abc: 2 3 (-100) :xyz} +do_test printf-2.6.9.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -99.99999 +} {abc: 2 3 (-100.000) :xyz} +do_test printf-2.6.9.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -99.99999 +} {abc: 2 3 (-000000100) :xyz} +do_test printf-2.6.9.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 -99.99999 +} {abc: 2 3 (-100.000) :xyz} +do_test printf-2.6.9.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -99.99999 +} {abc: 2 3 (-1.000e+02) :xyz} +do_test printf-2.6.9.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -99.99999 +} {abc: 2 3 (-100) :xyz} +do_test printf-2.6.10.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 3.14e+9 +} {abc: (3140000000.000) :xyz} +do_test printf-2.6.10.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 3.14e+9 +} {abc: (3.140e+09) :xyz} +do_test printf-2.6.10.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 3.14e+9 +} {abc: (3.14e+09) :xyz} +do_test printf-2.6.10.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 3.14e+9 +} {abc: 2 3 (3.14e+09) :xyz} +do_test printf-2.6.10.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 3.14e+9 +} {abc: 2 3 (3.14000e+09) :xyz} +do_test printf-2.6.10.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 3.14e+9 +} {abc: 2 3 (003.14e+09) :xyz} +do_test printf-2.6.10.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 3.14e+9 +} {abc: 2 3 (3140000000.000) :xyz} +do_test printf-2.6.10.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 3.14e+9 +} {abc: 2 3 (3.140e+09) :xyz} +do_test printf-2.6.10.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 3.14e+9 +} {abc: 2 3 (3.14e+09) :xyz} +do_test printf-2.6.11.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -4.72732e+88 +} {abc: (-4.727e+88) :xyz} +do_test printf-2.6.11.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -4.72732e+88 +} {abc: (-4.73e+88) :xyz} +do_test printf-2.6.11.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -4.72732e+88 +} {abc: 2 3 (-4.72732e+88) :xyz} +do_test printf-2.6.11.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -4.72732e+88 +} {abc: 2 3 (-4.72732e+88) :xyz} +do_test printf-2.6.11.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -4.72732e+88 +} {abc: 2 3 (-4.72732e+88) :xyz} +do_test printf-2.6.11.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -4.72732e+88 +} {abc: 2 3 (-4.727e+88) :xyz} +do_test printf-2.6.11.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -4.72732e+88 +} {abc: 2 3 (-4.73e+88) :xyz} +do_test printf-2.6.12.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 9.87991e+143 +} {abc: (9.880e+143) :xyz} +do_test printf-2.6.12.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 9.87991e+143 +} {abc: (9.88e+143) :xyz} +do_test printf-2.6.12.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 9.87991e+143 +} {abc: 2 3 (9.87991e+143) :xyz} +do_test printf-2.6.12.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 9.87991e+143 +} {abc: 2 3 (9.87991e+143) :xyz} +do_test printf-2.6.12.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 9.87991e+143 +} {abc: 2 3 (9.87991e+143) :xyz} +do_test printf-2.6.12.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 9.87991e+143 +} {abc: 2 3 (9.880e+143) :xyz} +do_test printf-2.6.12.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 9.87991e+143 +} {abc: 2 3 (9.88e+143) :xyz} +do_test printf-2.6.13.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 -6.287291e-9 +} {abc: (-0.000) :xyz} +do_test printf-2.6.13.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 -6.287291e-9 +} {abc: (-6.287e-09) :xyz} +do_test printf-2.6.13.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 -6.287291e-9 +} {abc: (-6.29e-09) :xyz} +do_test printf-2.6.13.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 -6.287291e-9 +} {abc: 2 3 (-6.28729e-09) :xyz} +do_test printf-2.6.13.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 -6.287291e-9 +} {abc: 2 3 (-6.28729e-09) :xyz} +do_test printf-2.6.13.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 -6.287291e-9 +} {abc: 2 3 (-6.28729e-09) :xyz} +do_test printf-2.6.13.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 -6.287291e-9 +} {abc: 2 3 (-0.000) :xyz} +do_test printf-2.6.13.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 -6.287291e-9 +} {abc: 2 3 (-6.287e-09) :xyz} +do_test printf-2.6.13.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 -6.287291e-9 +} {abc: 2 3 (-6.29e-09) :xyz} +do_test printf-2.6.14.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 2 3 3.38826392e-110 +} {abc: (0.000) :xyz} +do_test printf-2.6.14.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 2 3 3.38826392e-110 +} {abc: (3.388e-110) :xyz} +do_test printf-2.6.14.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 2 3 3.38826392e-110 +} {abc: (3.39e-110) :xyz} +do_test printf-2.6.14.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 2 3 3.38826392e-110 +} {abc: 2 3 (3.38826e-110) :xyz} +do_test printf-2.6.14.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 2 3 3.38826392e-110 +} {abc: 2 3 (3.38826e-110) :xyz} +do_test printf-2.6.14.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 2 3 3.38826392e-110 +} {abc: 2 3 (3.38826e-110) :xyz} +do_test printf-2.6.14.7 { + sqlite3_mprintf_double {abc: %d %d (%2.3f) :xyz} 2 3 3.38826392e-110 +} {abc: 2 3 (0.000) :xyz} +do_test printf-2.6.14.8 { + sqlite3_mprintf_double {abc: %d %d (%2.3e) :xyz} 2 3 3.38826392e-110 +} {abc: 2 3 (3.388e-110) :xyz} +do_test printf-2.6.14.9 { + sqlite3_mprintf_double {abc: %d %d (%2.3g) :xyz} 2 3 3.38826392e-110 +} {abc: 2 3 (3.39e-110) :xyz} +do_test printf-2.7.1.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 0.001 +} {abc: (0.001) :xyz} +do_test printf-2.7.1.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 0.001 +} {abc: (1.000e-03) :xyz} +do_test printf-2.7.1.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 0.001 +} {abc: (0.001) :xyz} +do_test printf-2.7.1.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 0.001 +} {abc: 3 3 (0.001) :xyz} +do_test printf-2.7.1.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 0.001 +} {abc: 3 3 (0.00100000) :xyz} +do_test printf-2.7.1.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 0.001 +} {abc: 3 3 (000000.001) :xyz} +do_test printf-2.7.1.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 0.001 +} {abc: 3 3 (0.001) :xyz} +do_test printf-2.7.1.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 0.001 +} {abc: 3 3 (1.000e-03) :xyz} +do_test printf-2.7.1.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 0.001 +} {abc: 3 3 (0.001) :xyz} +do_test printf-2.7.2.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 1.0e-20 +} {abc: (0.000) :xyz} +do_test printf-2.7.2.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 1.0e-20 +} {abc: (1.000e-20) :xyz} +do_test printf-2.7.2.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 1.0e-20 +} {abc: (1e-20) :xyz} +do_test printf-2.7.2.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 1.0e-20 +} {abc: 3 3 (1e-20) :xyz} +do_test printf-2.7.2.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 1.0e-20 +} {abc: 3 3 (1.00000e-20) :xyz} +do_test printf-2.7.2.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 1.0e-20 +} {abc: 3 3 (000001e-20) :xyz} +do_test printf-2.7.2.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 1.0e-20 +} {abc: 3 3 (0.000) :xyz} +do_test printf-2.7.2.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 1.0e-20 +} {abc: 3 3 (1.000e-20) :xyz} +do_test printf-2.7.2.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 1.0e-20 +} {abc: 3 3 (1e-20) :xyz} +do_test printf-2.7.3.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 1.0 +} {abc: (1.000) :xyz} +do_test printf-2.7.3.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 1.0 +} {abc: (1.000e+00) :xyz} +do_test printf-2.7.3.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 1.0 +} {abc: ( 1) :xyz} +do_test printf-2.7.3.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 1.0 +} {abc: 3 3 (1) :xyz} +do_test printf-2.7.3.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 1.0 +} {abc: 3 3 (1.00000) :xyz} +do_test printf-2.7.3.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 1.0 +} {abc: 3 3 (0000000001) :xyz} +do_test printf-2.7.3.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 1.0 +} {abc: 3 3 (1.000) :xyz} +do_test printf-2.7.3.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 1.0 +} {abc: 3 3 (1.000e+00) :xyz} +do_test printf-2.7.3.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 1.0 +} {abc: 3 3 ( 1) :xyz} +do_test printf-2.7.4.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 0.0 +} {abc: (0.000) :xyz} +do_test printf-2.7.4.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 0.0 +} {abc: (0.000e+00) :xyz} +do_test printf-2.7.4.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 0.0 +} {abc: ( 0) :xyz} +do_test printf-2.7.4.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 0.0 +} {abc: 3 3 (0) :xyz} +do_test printf-2.7.4.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 0.0 +} {abc: 3 3 (0.00000) :xyz} +do_test printf-2.7.4.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 0.0 +} {abc: 3 3 (0000000000) :xyz} +do_test printf-2.7.4.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 0.0 +} {abc: 3 3 (0.000) :xyz} +do_test printf-2.7.4.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 0.0 +} {abc: 3 3 (0.000e+00) :xyz} +do_test printf-2.7.4.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 0.0 +} {abc: 3 3 ( 0) :xyz} +do_test printf-2.7.5.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 100.0 +} {abc: (100.000) :xyz} +do_test printf-2.7.5.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 100.0 +} {abc: (1.000e+02) :xyz} +do_test printf-2.7.5.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 100.0 +} {abc: (100) :xyz} +do_test printf-2.7.5.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 100.0 +} {abc: 3 3 (100) :xyz} +do_test printf-2.7.5.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 100.0 +} {abc: 3 3 (100.000) :xyz} +do_test printf-2.7.5.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 100.0 +} {abc: 3 3 (0000000100) :xyz} +do_test printf-2.7.5.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 100.0 +} {abc: 3 3 (100.000) :xyz} +do_test printf-2.7.5.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 100.0 +} {abc: 3 3 (1.000e+02) :xyz} +do_test printf-2.7.5.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 100.0 +} {abc: 3 3 (100) :xyz} +do_test printf-2.7.6.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 9.99999 +} {abc: (10.000) :xyz} +do_test printf-2.7.6.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 9.99999 +} {abc: (1.000e+01) :xyz} +do_test printf-2.7.6.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 9.99999 +} {abc: ( 10) :xyz} +do_test printf-2.7.6.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 9.99999 +} {abc: 3 3 (9.99999) :xyz} +do_test printf-2.7.6.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 9.99999 +} {abc: 3 3 (9.99999) :xyz} +do_test printf-2.7.6.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 9.99999 +} {abc: 3 3 (0009.99999) :xyz} +do_test printf-2.7.6.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 9.99999 +} {abc: 3 3 (10.000) :xyz} +do_test printf-2.7.6.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 9.99999 +} {abc: 3 3 (1.000e+01) :xyz} +do_test printf-2.7.6.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 9.99999 +} {abc: 3 3 ( 10) :xyz} +do_test printf-2.7.7.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 -0.00543 +} {abc: (-0.005) :xyz} +do_test printf-2.7.7.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -0.00543 +} {abc: (-5.430e-03) :xyz} +do_test printf-2.7.7.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -0.00543 +} {abc: (-0.00543) :xyz} +do_test printf-2.7.7.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -0.00543 +} {abc: 3 3 (-0.00543) :xyz} +do_test printf-2.7.7.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -0.00543 +} {abc: 3 3 (-0.00543000) :xyz} +do_test printf-2.7.7.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -0.00543 +} {abc: 3 3 (-000.00543) :xyz} +do_test printf-2.7.7.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 -0.00543 +} {abc: 3 3 (-0.005) :xyz} +do_test printf-2.7.7.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -0.00543 +} {abc: 3 3 (-5.430e-03) :xyz} +do_test printf-2.7.7.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -0.00543 +} {abc: 3 3 (-0.00543) :xyz} +do_test printf-2.7.8.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 -1.0 +} {abc: (-1.000) :xyz} +do_test printf-2.7.8.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -1.0 +} {abc: (-1.000e+00) :xyz} +do_test printf-2.7.8.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -1.0 +} {abc: ( -1) :xyz} +do_test printf-2.7.8.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -1.0 +} {abc: 3 3 (-1) :xyz} +do_test printf-2.7.8.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -1.0 +} {abc: 3 3 (-1.00000) :xyz} +do_test printf-2.7.8.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -1.0 +} {abc: 3 3 (-000000001) :xyz} +do_test printf-2.7.8.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 -1.0 +} {abc: 3 3 (-1.000) :xyz} +do_test printf-2.7.8.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -1.0 +} {abc: 3 3 (-1.000e+00) :xyz} +do_test printf-2.7.8.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -1.0 +} {abc: 3 3 ( -1) :xyz} +do_test printf-2.7.9.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 -99.99999 +} {abc: (-100.000) :xyz} +do_test printf-2.7.9.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -99.99999 +} {abc: (-1.000e+02) :xyz} +do_test printf-2.7.9.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -99.99999 +} {abc: (-100) :xyz} +do_test printf-2.7.9.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -99.99999 +} {abc: 3 3 (-100) :xyz} +do_test printf-2.7.9.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -99.99999 +} {abc: 3 3 (-100.000) :xyz} +do_test printf-2.7.9.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -99.99999 +} {abc: 3 3 (-000000100) :xyz} +do_test printf-2.7.9.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 -99.99999 +} {abc: 3 3 (-100.000) :xyz} +do_test printf-2.7.9.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -99.99999 +} {abc: 3 3 (-1.000e+02) :xyz} +do_test printf-2.7.9.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -99.99999 +} {abc: 3 3 (-100) :xyz} +do_test printf-2.7.10.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 3.14e+9 +} {abc: (3140000000.000) :xyz} +do_test printf-2.7.10.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 3.14e+9 +} {abc: (3.140e+09) :xyz} +do_test printf-2.7.10.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 3.14e+9 +} {abc: (3.14e+09) :xyz} +do_test printf-2.7.10.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 3.14e+9 +} {abc: 3 3 (3.14e+09) :xyz} +do_test printf-2.7.10.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 3.14e+9 +} {abc: 3 3 (3.14000e+09) :xyz} +do_test printf-2.7.10.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 3.14e+9 +} {abc: 3 3 (003.14e+09) :xyz} +do_test printf-2.7.10.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 3.14e+9 +} {abc: 3 3 (3140000000.000) :xyz} +do_test printf-2.7.10.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 3.14e+9 +} {abc: 3 3 (3.140e+09) :xyz} +do_test printf-2.7.10.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 3.14e+9 +} {abc: 3 3 (3.14e+09) :xyz} +do_test printf-2.7.11.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -4.72732e+88 +} {abc: (-4.727e+88) :xyz} +do_test printf-2.7.11.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -4.72732e+88 +} {abc: (-4.73e+88) :xyz} +do_test printf-2.7.11.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -4.72732e+88 +} {abc: 3 3 (-4.72732e+88) :xyz} +do_test printf-2.7.11.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -4.72732e+88 +} {abc: 3 3 (-4.72732e+88) :xyz} +do_test printf-2.7.11.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -4.72732e+88 +} {abc: 3 3 (-4.72732e+88) :xyz} +do_test printf-2.7.11.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -4.72732e+88 +} {abc: 3 3 (-4.727e+88) :xyz} +do_test printf-2.7.11.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -4.72732e+88 +} {abc: 3 3 (-4.73e+88) :xyz} +do_test printf-2.7.12.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 9.87991e+143 +} {abc: (9.880e+143) :xyz} +do_test printf-2.7.12.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 9.87991e+143 +} {abc: (9.88e+143) :xyz} +do_test printf-2.7.12.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 9.87991e+143 +} {abc: 3 3 (9.87991e+143) :xyz} +do_test printf-2.7.12.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 9.87991e+143 +} {abc: 3 3 (9.87991e+143) :xyz} +do_test printf-2.7.12.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 9.87991e+143 +} {abc: 3 3 (9.87991e+143) :xyz} +do_test printf-2.7.12.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 9.87991e+143 +} {abc: 3 3 (9.880e+143) :xyz} +do_test printf-2.7.12.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 9.87991e+143 +} {abc: 3 3 (9.88e+143) :xyz} +do_test printf-2.7.13.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 -6.287291e-9 +} {abc: (-0.000) :xyz} +do_test printf-2.7.13.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 -6.287291e-9 +} {abc: (-6.287e-09) :xyz} +do_test printf-2.7.13.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 -6.287291e-9 +} {abc: (-6.29e-09) :xyz} +do_test printf-2.7.13.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 -6.287291e-9 +} {abc: 3 3 (-6.28729e-09) :xyz} +do_test printf-2.7.13.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 -6.287291e-9 +} {abc: 3 3 (-6.28729e-09) :xyz} +do_test printf-2.7.13.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 -6.287291e-9 +} {abc: 3 3 (-6.28729e-09) :xyz} +do_test printf-2.7.13.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 -6.287291e-9 +} {abc: 3 3 (-0.000) :xyz} +do_test printf-2.7.13.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 -6.287291e-9 +} {abc: 3 3 (-6.287e-09) :xyz} +do_test printf-2.7.13.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 -6.287291e-9 +} {abc: 3 3 (-6.29e-09) :xyz} +do_test printf-2.7.14.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 3 3.38826392e-110 +} {abc: (0.000) :xyz} +do_test printf-2.7.14.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 3 3.38826392e-110 +} {abc: (3.388e-110) :xyz} +do_test printf-2.7.14.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 3 3.38826392e-110 +} {abc: (3.39e-110) :xyz} +do_test printf-2.7.14.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 3 3.38826392e-110 +} {abc: 3 3 (3.38826e-110) :xyz} +do_test printf-2.7.14.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 3 3.38826392e-110 +} {abc: 3 3 (3.38826e-110) :xyz} +do_test printf-2.7.14.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 3 3.38826392e-110 +} {abc: 3 3 (3.38826e-110) :xyz} +do_test printf-2.7.14.7 { + sqlite3_mprintf_double {abc: %d %d (%3.3f) :xyz} 3 3 3.38826392e-110 +} {abc: 3 3 (0.000) :xyz} +do_test printf-2.7.14.8 { + sqlite3_mprintf_double {abc: %d %d (%3.3e) :xyz} 3 3 3.38826392e-110 +} {abc: 3 3 (3.388e-110) :xyz} +do_test printf-2.7.14.9 { + sqlite3_mprintf_double {abc: %d %d (%3.3g) :xyz} 3 3 3.38826392e-110 +} {abc: 3 3 (3.39e-110) :xyz} +do_test printf-2.8.1.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 0.001 +} {abc: (0.00) :xyz} +do_test printf-2.8.1.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 0.001 +} {abc: (1.00e-03) :xyz} +do_test printf-2.8.1.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 0.001 +} {abc: (0.001) :xyz} +do_test printf-2.8.1.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 0.001 +} {abc: 3 2 (0.001) :xyz} +do_test printf-2.8.1.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 0.001 +} {abc: 3 2 (0.00100000) :xyz} +do_test printf-2.8.1.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 0.001 +} {abc: 3 2 (000000.001) :xyz} +do_test printf-2.8.1.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 0.001 +} {abc: 3 2 (0.00) :xyz} +do_test printf-2.8.1.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 0.001 +} {abc: 3 2 (1.00e-03) :xyz} +do_test printf-2.8.1.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 0.001 +} {abc: 3 2 (0.001) :xyz} +do_test printf-2.8.2.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 1.0e-20 +} {abc: (0.00) :xyz} +do_test printf-2.8.2.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 1.0e-20 +} {abc: (1.00e-20) :xyz} +do_test printf-2.8.2.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 1.0e-20 +} {abc: (1e-20) :xyz} +do_test printf-2.8.2.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 1.0e-20 +} {abc: 3 2 (1e-20) :xyz} +do_test printf-2.8.2.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 1.0e-20 +} {abc: 3 2 (1.00000e-20) :xyz} +do_test printf-2.8.2.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 1.0e-20 +} {abc: 3 2 (000001e-20) :xyz} +do_test printf-2.8.2.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 1.0e-20 +} {abc: 3 2 (0.00) :xyz} +do_test printf-2.8.2.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 1.0e-20 +} {abc: 3 2 (1.00e-20) :xyz} +do_test printf-2.8.2.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 1.0e-20 +} {abc: 3 2 (1e-20) :xyz} +do_test printf-2.8.3.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 1.0 +} {abc: (1.00) :xyz} +do_test printf-2.8.3.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 1.0 +} {abc: (1.00e+00) :xyz} +do_test printf-2.8.3.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 1.0 +} {abc: ( 1) :xyz} +do_test printf-2.8.3.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 1.0 +} {abc: 3 2 (1) :xyz} +do_test printf-2.8.3.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 1.0 +} {abc: 3 2 (1.00000) :xyz} +do_test printf-2.8.3.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 1.0 +} {abc: 3 2 (0000000001) :xyz} +do_test printf-2.8.3.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 1.0 +} {abc: 3 2 (1.00) :xyz} +do_test printf-2.8.3.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 1.0 +} {abc: 3 2 (1.00e+00) :xyz} +do_test printf-2.8.3.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 1.0 +} {abc: 3 2 ( 1) :xyz} +do_test printf-2.8.4.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 0.0 +} {abc: (0.00) :xyz} +do_test printf-2.8.4.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 0.0 +} {abc: (0.00e+00) :xyz} +do_test printf-2.8.4.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 0.0 +} {abc: ( 0) :xyz} +do_test printf-2.8.4.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 0.0 +} {abc: 3 2 (0) :xyz} +do_test printf-2.8.4.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 0.0 +} {abc: 3 2 (0.00000) :xyz} +do_test printf-2.8.4.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 0.0 +} {abc: 3 2 (0000000000) :xyz} +do_test printf-2.8.4.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 0.0 +} {abc: 3 2 (0.00) :xyz} +do_test printf-2.8.4.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 0.0 +} {abc: 3 2 (0.00e+00) :xyz} +do_test printf-2.8.4.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 0.0 +} {abc: 3 2 ( 0) :xyz} +do_test printf-2.8.5.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 100.0 +} {abc: (100.00) :xyz} +do_test printf-2.8.5.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 100.0 +} {abc: (1.00e+02) :xyz} +do_test printf-2.8.5.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 100.0 +} {abc: (1e+02) :xyz} +do_test printf-2.8.5.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 100.0 +} {abc: 3 2 (100) :xyz} +do_test printf-2.8.5.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 100.0 +} {abc: 3 2 (100.000) :xyz} +do_test printf-2.8.5.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 100.0 +} {abc: 3 2 (0000000100) :xyz} +do_test printf-2.8.5.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 100.0 +} {abc: 3 2 (100.00) :xyz} +do_test printf-2.8.5.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 100.0 +} {abc: 3 2 (1.00e+02) :xyz} +do_test printf-2.8.5.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 100.0 +} {abc: 3 2 (1e+02) :xyz} +do_test printf-2.8.6.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 9.99999 +} {abc: (10.00) :xyz} +do_test printf-2.8.6.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 9.99999 +} {abc: (1.00e+01) :xyz} +do_test printf-2.8.6.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 9.99999 +} {abc: ( 10) :xyz} +do_test printf-2.8.6.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 9.99999 +} {abc: 3 2 (9.99999) :xyz} +do_test printf-2.8.6.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 9.99999 +} {abc: 3 2 (9.99999) :xyz} +do_test printf-2.8.6.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 9.99999 +} {abc: 3 2 (0009.99999) :xyz} +do_test printf-2.8.6.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 9.99999 +} {abc: 3 2 (10.00) :xyz} +do_test printf-2.8.6.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 9.99999 +} {abc: 3 2 (1.00e+01) :xyz} +do_test printf-2.8.6.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 9.99999 +} {abc: 3 2 ( 10) :xyz} +do_test printf-2.8.7.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 -0.00543 +} {abc: (-0.01) :xyz} +do_test printf-2.8.7.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -0.00543 +} {abc: (-5.43e-03) :xyz} +do_test printf-2.8.7.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -0.00543 +} {abc: (-0.0054) :xyz} +do_test printf-2.8.7.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -0.00543 +} {abc: 3 2 (-0.00543) :xyz} +do_test printf-2.8.7.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -0.00543 +} {abc: 3 2 (-0.00543000) :xyz} +do_test printf-2.8.7.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -0.00543 +} {abc: 3 2 (-000.00543) :xyz} +do_test printf-2.8.7.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 -0.00543 +} {abc: 3 2 (-0.01) :xyz} +do_test printf-2.8.7.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -0.00543 +} {abc: 3 2 (-5.43e-03) :xyz} +do_test printf-2.8.7.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -0.00543 +} {abc: 3 2 (-0.0054) :xyz} +do_test printf-2.8.8.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 -1.0 +} {abc: (-1.00) :xyz} +do_test printf-2.8.8.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -1.0 +} {abc: (-1.00e+00) :xyz} +do_test printf-2.8.8.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -1.0 +} {abc: ( -1) :xyz} +do_test printf-2.8.8.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -1.0 +} {abc: 3 2 (-1) :xyz} +do_test printf-2.8.8.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -1.0 +} {abc: 3 2 (-1.00000) :xyz} +do_test printf-2.8.8.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -1.0 +} {abc: 3 2 (-000000001) :xyz} +do_test printf-2.8.8.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 -1.0 +} {abc: 3 2 (-1.00) :xyz} +do_test printf-2.8.8.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -1.0 +} {abc: 3 2 (-1.00e+00) :xyz} +do_test printf-2.8.8.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -1.0 +} {abc: 3 2 ( -1) :xyz} +do_test printf-2.8.9.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 -99.99999 +} {abc: (-100.00) :xyz} +do_test printf-2.8.9.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -99.99999 +} {abc: (-1.00e+02) :xyz} +do_test printf-2.8.9.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -99.99999 +} {abc: (-1e+02) :xyz} +do_test printf-2.8.9.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -99.99999 +} {abc: 3 2 (-100) :xyz} +do_test printf-2.8.9.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -99.99999 +} {abc: 3 2 (-100.000) :xyz} +do_test printf-2.8.9.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -99.99999 +} {abc: 3 2 (-000000100) :xyz} +do_test printf-2.8.9.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 -99.99999 +} {abc: 3 2 (-100.00) :xyz} +do_test printf-2.8.9.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -99.99999 +} {abc: 3 2 (-1.00e+02) :xyz} +do_test printf-2.8.9.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -99.99999 +} {abc: 3 2 (-1e+02) :xyz} +do_test printf-2.8.10.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 3.14e+9 +} {abc: (3140000000.00) :xyz} +do_test printf-2.8.10.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 3.14e+9 +} {abc: (3.14e+09) :xyz} +do_test printf-2.8.10.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 3.14e+9 +} {abc: (3.1e+09) :xyz} +do_test printf-2.8.10.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 3.14e+9 +} {abc: 3 2 (3.14e+09) :xyz} +do_test printf-2.8.10.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 3.14e+9 +} {abc: 3 2 (3.14000e+09) :xyz} +do_test printf-2.8.10.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 3.14e+9 +} {abc: 3 2 (003.14e+09) :xyz} +do_test printf-2.8.10.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 3.14e+9 +} {abc: 3 2 (3140000000.00) :xyz} +do_test printf-2.8.10.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 3.14e+9 +} {abc: 3 2 (3.14e+09) :xyz} +do_test printf-2.8.10.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 3.14e+9 +} {abc: 3 2 (3.1e+09) :xyz} +do_test printf-2.8.11.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -4.72732e+88 +} {abc: (-4.73e+88) :xyz} +do_test printf-2.8.11.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -4.72732e+88 +} {abc: (-4.7e+88) :xyz} +do_test printf-2.8.11.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -4.72732e+88 +} {abc: 3 2 (-4.72732e+88) :xyz} +do_test printf-2.8.11.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -4.72732e+88 +} {abc: 3 2 (-4.72732e+88) :xyz} +do_test printf-2.8.11.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -4.72732e+88 +} {abc: 3 2 (-4.72732e+88) :xyz} +do_test printf-2.8.11.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -4.72732e+88 +} {abc: 3 2 (-4.73e+88) :xyz} +do_test printf-2.8.11.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -4.72732e+88 +} {abc: 3 2 (-4.7e+88) :xyz} +do_test printf-2.8.12.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 9.87991e+143 +} {abc: (9.88e+143) :xyz} +do_test printf-2.8.12.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 9.87991e+143 +} {abc: (9.9e+143) :xyz} +do_test printf-2.8.12.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 9.87991e+143 +} {abc: 3 2 (9.87991e+143) :xyz} +do_test printf-2.8.12.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 9.87991e+143 +} {abc: 3 2 (9.87991e+143) :xyz} +do_test printf-2.8.12.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 9.87991e+143 +} {abc: 3 2 (9.87991e+143) :xyz} +do_test printf-2.8.12.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 9.87991e+143 +} {abc: 3 2 (9.88e+143) :xyz} +do_test printf-2.8.12.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 9.87991e+143 +} {abc: 3 2 (9.9e+143) :xyz} +do_test printf-2.8.13.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 -6.287291e-9 +} {abc: (-0.00) :xyz} +do_test printf-2.8.13.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 -6.287291e-9 +} {abc: (-6.29e-09) :xyz} +do_test printf-2.8.13.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 -6.287291e-9 +} {abc: (-6.3e-09) :xyz} +do_test printf-2.8.13.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 -6.287291e-9 +} {abc: 3 2 (-6.28729e-09) :xyz} +do_test printf-2.8.13.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 -6.287291e-9 +} {abc: 3 2 (-6.28729e-09) :xyz} +do_test printf-2.8.13.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 -6.287291e-9 +} {abc: 3 2 (-6.28729e-09) :xyz} +do_test printf-2.8.13.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 -6.287291e-9 +} {abc: 3 2 (-0.00) :xyz} +do_test printf-2.8.13.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 -6.287291e-9 +} {abc: 3 2 (-6.29e-09) :xyz} +do_test printf-2.8.13.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 -6.287291e-9 +} {abc: 3 2 (-6.3e-09) :xyz} +do_test printf-2.8.14.1 { + sqlite3_mprintf_double {abc: (%*.*f) :xyz} 3 2 3.38826392e-110 +} {abc: (0.00) :xyz} +do_test printf-2.8.14.2 { + sqlite3_mprintf_double {abc: (%*.*e) :xyz} 3 2 3.38826392e-110 +} {abc: (3.39e-110) :xyz} +do_test printf-2.8.14.3 { + sqlite3_mprintf_double {abc: (%*.*g) :xyz} 3 2 3.38826392e-110 +} {abc: (3.4e-110) :xyz} +do_test printf-2.8.14.4 { + sqlite3_mprintf_double {abc: %d %d (%g) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 (3.38826e-110) :xyz} +do_test printf-2.8.14.5 { + sqlite3_mprintf_double {abc: %d %d (%#g) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 (3.38826e-110) :xyz} +do_test printf-2.8.14.6 { + sqlite3_mprintf_double {abc: %d %d (%010g) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 (3.38826e-110) :xyz} +do_test printf-2.8.14.7 { + sqlite3_mprintf_double {abc: %d %d (%3.2f) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 (0.00) :xyz} +do_test printf-2.8.14.8 { + sqlite3_mprintf_double {abc: %d %d (%3.2e) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 (3.39e-110) :xyz} +do_test printf-2.8.14.9 { + sqlite3_mprintf_double {abc: %d %d (%3.2g) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 (3.4e-110) :xyz} +do_test printf-2.8.15.1 { + sqlite3_mprintf_double {abc: (% *.*f) :xyz} 3 2 3.38826392e-110 +} {abc: ( 0.00) :xyz} +do_test printf-2.8.15.2 { + sqlite3_mprintf_double {abc: (% *.*e) :xyz} 3 2 3.38826392e-110 +} {abc: ( 3.39e-110) :xyz} +do_test printf-2.8.15.3 { + sqlite3_mprintf_double {abc: (% *.*g) :xyz} 3 2 3.38826392e-110 +} {abc: ( 3.4e-110) :xyz} +do_test printf-2.8.15.4 { + sqlite3_mprintf_double {abc: %d %d (% g) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 ( 3.38826e-110) :xyz} +do_test printf-2.8.15.5 { + sqlite3_mprintf_double {abc: %d %d (% #g) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 ( 3.38826e-110) :xyz} +do_test printf-2.8.15.6 { + sqlite3_mprintf_double {abc: %d %d (%0 10g) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 ( 3.38826e-110) :xyz} +do_test printf-2.8.15.7 { + sqlite3_mprintf_double {abc: %d %d (% 3.2f) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 ( 0.00) :xyz} +do_test printf-2.8.15.8 { + sqlite3_mprintf_double {abc: %d %d (% 3.2e) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 ( 3.39e-110) :xyz} +do_test printf-2.8.15.9 { + sqlite3_mprintf_double {abc: %d %d (% 3.2g) :xyz} 3 2 3.38826392e-110 +} {abc: 3 2 ( 3.4e-110) :xyz} + +do_test printf-2.9.1 { + sqlite3_mprintf_double {abc: %d %d (%5.0g) :xyz} 0 0 1.234 +} {abc: 0 0 ( 1) :xyz} +do_test printf-2.9.2 { + sqlite3_mprintf_double {abc: %d %d (%+5.0g) :xyz} 0 0 1.234 +} {abc: 0 0 ( +1) :xyz} +do_test printf-2.9.3 { + sqlite3_mprintf_double {abc: %d %d (%+-5.0g) :xyz} 0 0 1.234 +} {abc: 0 0 (+1 ) :xyz} + +do_test printf-2.10.1 { + sqlite3_mprintf_double {abc: %d %d (%-010.5f) :xyz} 0 0 1.234 +} {abc: 0 0 (1.23400 ) :xyz} +do_test printf-2.10.2 { + sqlite3_mprintf_double {abc: %d %d (%010.5f) :xyz} 0 0 1.234 +} {abc: 0 0 (0001.23400) :xyz} +do_test printf-2.10.3 { + sqlite3_mprintf_double {abc: %d %d (%+010.5f) :xyz} 0 0 1.234 +} {abc: 0 0 (+001.23400) :xyz} + +do_test printf-3.1 { + sqlite3_mprintf_str {A String: (%*.*s)} 10 10 {This is the string} +} [format {A String: (%*.*s)} 10 10 {This is the string}] +do_test printf-3.2 { + sqlite3_mprintf_str {A String: (%*.*s)} 10 5 {This is the string} +} [format {A String: (%*.*s)} 10 5 {This is the string}] +do_test printf-3.3 { + sqlite3_mprintf_str {A String: (%*.*s)} -10 5 {This is the string} +} [format {A String: (%*.*s)} -10 5 {This is the string}] +do_test printf-3.4 { + sqlite3_mprintf_str {%d %d A String: (%s)} 1 2 {This is the string} +} [format {%d %d A String: (%s)} 1 2 {This is the string}] +do_test printf-3.5 { + sqlite3_mprintf_str {%d %d A String: (%30s)} 1 2 {This is the string} +} [format {%d %d A String: (%30s)} 1 2 {This is the string}] +do_test printf-3.6 { + sqlite3_mprintf_str {%d %d A String: (%-30s)} 1 2 {This is the string} +} [format {%d %d A String: (%-30s)} 1 2 {This is the string}] +do_test snprintf-3.11 { + sqlite3_snprintf_str 2 {x%d %d %s} 10 10 {This is the string} +} {x} +do_test snprintf-3.12 { + sqlite3_snprintf_str 3 {x%d %d %s} 10 10 {This is the string} +} {x1} +do_test snprintf-3.13 { + sqlite3_snprintf_str 4 {x%d %d %s} 10 10 {This is the string} +} {x10} +do_test snprintf-3.14 { + sqlite3_snprintf_str 5 {x%d %d %s} 10 10 {This is the string} +} {x10 } +do_test snprintf-3.15 { + sqlite3_snprintf_str 6 {x%d %d %s} 10 10 {This is the string} +} {x10 1} +do_test snprintf-3.16 { + sqlite3_snprintf_str 7 {x%d %d %s} 10 10 {This is the string} +} {x10 10} +do_test snprintf-3.17 { + sqlite3_snprintf_str 8 {x%d %d %s} 10 10 {This is the string} +} {x10 10 } +do_test snprintf-3.18 { + sqlite3_snprintf_str 9 {x%d %d %s} 10 10 {This is the string} +} {x10 10 T} +do_test snprintf-3.19 { + sqlite3_snprintf_str 100 {x%d %d %s} 10 10 {This is the string} +} {x10 10 This is the string} + +do_test printf-4.1 { + sqlite3_mprintf_str {%d %d A quoted string: '%q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi Y''all'} +do_test printf-4.2 { + sqlite3_mprintf_str {%d %d A NULL pointer in %%q: '%q'} 1 2 +} {1 2 A NULL pointer in %q: '(NULL)'} +do_test printf-4.3 { + sqlite3_mprintf_str {%d %d A quoted string: %Q} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi Y''all'} +do_test printf-4.4 { + sqlite3_mprintf_str {%d %d A NULL pointer in %%Q: %Q} 1 2 +} {1 2 A NULL pointer in %Q: NULL} +do_test printf-4.5 { + sqlite3_mprintf_str {%d %d A quoted string: '%.10q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi Y''all'} +do_test printf-4.6 { + sqlite3_mprintf_str {%d %d A quoted string: '%.9q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi Y''all'} +do_test printf-4.7 { + sqlite3_mprintf_str {%d %d A quoted string: '%.8q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi Y''all'} +do_test printf-4.8 { + sqlite3_mprintf_str {%d %d A quoted string: '%.7q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi Y''al'} +do_test printf-4.9 { + sqlite3_mprintf_str {%d %d A quoted string: '%.6q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi Y''a'} +do_test printf-4.10 { + sqlite3_mprintf_str {%d %d A quoted string: '%.5q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi Y'''} +do_test printf-4.11 { + sqlite3_mprintf_str {%d %d A quoted string: '%.4q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi Y'} +do_test printf-4.12 { + sqlite3_mprintf_str {%d %d A quoted string: '%.3q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi '} +do_test printf-4.13 { + sqlite3_mprintf_str {%d %d A quoted string: '%.2q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'Hi'} +do_test printf-4.14 { + sqlite3_mprintf_str {%d %d A quoted string: '%.1q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: 'H'} +do_test printf-4.15 { + sqlite3_mprintf_str {%d %d A quoted string: '%.0q'} 1 2 {Hi Y'all} +} {1 2 A quoted string: ''} +do_test printf-4.16 { + sqlite3_mprintf_str {%d A quoted string: '%.*q'} 1 6 {Hi Y'all} +} {1 A quoted string: 'Hi Y''a'} + + +do_test printf-5.1 { + set x [sqlite3_mprintf_str {%d %d %100000s} 0 0 {Hello}] + string length $x +} {100004} +do_test printf-5.2 { + sqlite3_mprintf_str {%d %d (%-10.10s) %} -9 -10 {HelloHelloHello} +} {-9 -10 (HelloHello) %} + +do_test printf-6.1 { + sqlite3_mprintf_z_test , one two three four five six +} {,one,two,three,four,five,six} + + +do_test printf-7.1 { + sqlite3_mprintf_scaled {A double: %g} 1.0e307 1.0 +} {A double: 1e+307} +do_test printf-7.2 { + sqlite3_mprintf_scaled {A double: %g} 1.0e307 10.0 +} {A double: 1e+308} +do_test printf-7.3 { + sqlite3_mprintf_scaled {A double: %g} 1.0e307 100.0 +} {A double: Inf} +do_test printf-7.4 { + sqlite3_mprintf_scaled {A double: %g} -1.0e307 100.0 +} {A double: -Inf} +do_test printf-7.5 { + sqlite3_mprintf_scaled {A double: %+g} 1.0e307 100.0 +} {A double: +Inf} + +do_test printf-8.1 { + sqlite3_mprintf_int {%u %u %u} 0x7fffffff 0x80000000 0xffffffff +} {2147483647 2147483648 4294967295} +do_test printf-8.2 { + sqlite3_mprintf_long {%lu %lu %lu} 0x7fffffff 0x80000000 0xffffffff +} {2147483647 2147483648 4294967295} +do_test printf-8.3 { + sqlite3_mprintf_int64 {%llu %llu %llu} 2147483647 2147483648 4294967296 +} {2147483647 2147483648 4294967296} +do_test printf-8.4 { + sqlite3_mprintf_int64 {%lld %lld %lld} 2147483647 2147483648 4294967296 +} {2147483647 2147483648 4294967296} +do_test printf-8.5 { + sqlite3_mprintf_int64 {%llx %llx %llx} 2147483647 2147483648 4294967296 +} {7fffffff 80000000 100000000} +do_test printf-8.6 { + sqlite3_mprintf_int64 {%llx %llo %lld} -1 -1 -1 +} {ffffffffffffffff 1777777777777777777777 -1} +do_test printf-8.7 { + sqlite3_mprintf_int64 {%llx %llx %llx} +2147483647 +2147483648 +4294967296 +} {7fffffff 80000000 100000000} + +do_test printf-9.1 { + sqlite3_mprintf_int {%*.*c} 4 4 65 +} {AAAA} +do_test printf-9.2 { + sqlite3_mprintf_int {%*.*c} -4 1 66 +} {B } +do_test printf-9.3 { + sqlite3_mprintf_int {%*.*c} 4 1 67 +} { C} +do_test printf-9.4 { + sqlite3_mprintf_int {%d %d %c} 4 1 67 +} {4 1 C} +set ten { } +set fifty $ten$ten$ten$ten$ten +do_test printf-9.5 { + sqlite3_mprintf_int {%d %*c} 1 -201 67 +} "1 C$fifty$fifty$fifty$fifty" +do_test printf-9.6 { + sqlite3_mprintf_int {hi%12345.12346yhello} 0 0 0 +} {hi} + +# Ticket #812 +# +do_test printf-10.1 { + sqlite3_mprintf_stronly %s {} +} {} + +# Ticket #831 +# +do_test printf-10.2 { + sqlite3_mprintf_stronly %q {} +} {} + +# Ticket #1340: Test for loss of precision on large positive exponents +# +do_test printf-10.3 { + sqlite3_mprintf_double {%d %d %f} 1 1 1e300 +} {1 1 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000} + +# The non-standard '!' flag on a 'g' conversion forces a decimal point +# and at least one digit on either side of the decimal point. +# +do_test printf-11.1 { + sqlite3_mprintf_double {%d %d %!g} 1 1 1 +} {1 1 1.0} +do_test printf-11.2 { + sqlite3_mprintf_double {%d %d %!g} 1 1 123 +} {1 1 123.0} +do_test printf-11.3 { + sqlite3_mprintf_double {%d %d %!g} 1 1 12.3 +} {1 1 12.3} +do_test printf-11.4 { + sqlite3_mprintf_double {%d %d %!g} 1 1 0.123 +} {1 1 0.123} +do_test printf-11.5 { + sqlite3_mprintf_double {%d %d %!.15g} 1 1 1 +} {1 1 1.0} +do_test printf-11.6 { + sqlite3_mprintf_double {%d %d %!.15g} 1 1 1e10 +} {1 1 10000000000.0} +do_test printf-11.7 { + sqlite3_mprintf_double {%d %d %!.15g} 1 1 1e300 +} {1 1 1.0e+300} + +# Additional tests for coverage +# +do_test printf-12.1 { + sqlite3_mprintf_double {%d %d %.2000g} 1 1 1.0 +} {1 1 1} + +# Floating point boundary cases +# +do_test printf-13.1 { + sqlite3_mprintf_hexdouble %.20f 4024000000000000 +} {10.00000000000000000000} +do_test printf-13.2 { + sqlite3_mprintf_hexdouble %.20f 4197d78400000000 +} {100000000.00000000000000000000} +do_test printf-13.3 { + sqlite3_mprintf_hexdouble %.20f 4693b8b5b5056e17 +} {100000000000000000000000000000000.00000000000000000000} +do_test printf-13.4 { + sqlite3_mprintf_hexdouble %.20f 7ff0000000000000 +} {Inf} +do_test printf-13.5 { + sqlite3_mprintf_hexdouble %.20f fff0000000000000 +} {-Inf} +do_test printf-13.6 { + sqlite3_mprintf_hexdouble %.20f fff8000000000000 +} {NaN} + +do_test printf-14.1 { + sqlite3_mprintf_str {abc-%y-123} 0 0 {not used} +} {abc-} +do_test printf-14.2 { + sqlite3_mprintf_n_test {xyzzy} +} 5 +do_test printf-14.3 { + sqlite3_mprintf_str {abc-%T-123} 0 0 {not used} +} {abc-} +do_test printf-14.4 { + sqlite3_mprintf_str {abc-%#} 0 0 {not used} +} {abc-} +do_test printf-14.5 { + sqlite3_mprintf_str {abc-%*.*s-xyz} 10 -10 {a_very_long_string} +} {abc-a_very_lon-xyz} +do_test printf-14.6 { + sqlite3_mprintf_str {abc-%5.10/} 0 0 {not used} +} {abc-} +do_test printf-14.7 { + sqlite3_mprintf_str {abc-%05.5d} 123 0 {not used} +} {abc-00123} +do_test printf-14.8 { + sqlite3_mprintf_str {abc-%05.5d} 1234567 0 {not used} +} {abc-1234567} + +for {set i 2} {$i<200} {incr i} { + set res [string repeat { } [expr {$i-1}]]x + do_test printf-14.90.$i " + sqlite3_mprintf_str {%*.*s} $i 500 x + " $res +} + +do_test printf-15.1 { + sqlite3_snprintf_int 5 {12345} 0 +} {1234} +do_test printf-15.2 { + sqlite3_snprintf_int 5 {} 0 +} {} +do_test printf-15.3 { + sqlite3_snprintf_int 0 {} 0 +} {abcdefghijklmnopqrstuvwxyz} + +# Now test malloc() failure within a sqlite3_mprintf(): +# +ifcapable memdebug { + foreach var {a b c d} { + set $var [string repeat $var 400] + } + set str1 "[string repeat A 360]%d%d%s" + set str2 [string repeat B 5000] + set zSuccess "[string repeat A 360]11[string repeat B 5000]" + foreach ::iRepeat {0 1} { + set nTestNum 1 + while {1} { + sqlite3_memdebug_fail $nTestNum -repeat $::iRepeat + set z [sqlite3_mprintf_str $str1 1 1 $str2] + set nFail [sqlite3_memdebug_fail -1 -benign nBenign] + do_test printf-malloc-$::iRepeat.$nTestNum { + expr {($nFail>0 && $z eq "") || ($nFail==$nBenign && $z eq $zSuccess)} + } {1} + if {$nFail == 0} break + incr nTestNum + } + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/progress.test b/components/external/SQLite-3.8.1/test/progress.test new file mode 100644 index 0000000000000000000000000000000000000000..993426aa2b438ed0ef3ecaf01cc1f8763e4564fb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/progress.test @@ -0,0 +1,179 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the 'progress callback'. +# +# $Id: progress.test,v 1.8 2007/06/15 14:53:53 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If the progress callback is not available in this build, skip this +# whole file. +ifcapable !progress { + finish_test + return +} + +# Build some test data +# +execsql { + BEGIN; + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + INSERT INTO t1 VALUES(5); + INSERT INTO t1 VALUES(6); + INSERT INTO t1 VALUES(7); + INSERT INTO t1 VALUES(8); + INSERT INTO t1 VALUES(9); + INSERT INTO t1 VALUES(10); + COMMIT; +} + + +# Test that the progress callback is invoked. +do_test progress-1.0 { + set counter 0 + db progress 1 "[namespace code {incr counter}] ; expr 0" + execsql { + SELECT * FROM t1 + } + expr $counter > 1 +} 1 +do_test progress-1.0.1 { + db progress +} {::namespace inscope :: {incr counter} ; expr 0} +do_test progress-1.0.2 { + set v [catch {db progress xyz bogus} msg] + lappend v $msg +} {1 {expected integer but got "xyz"}} + +# Test that the query is abandoned when the progress callback returns non-zero +do_test progress-1.1 { + set counter 0 + db progress 1 "[namespace code {incr counter}] ; expr 1" + set rc [catch {execsql { + SELECT * FROM t1 + }}] + list $counter $rc +} {1 1} + +# Test that the query is rolled back when the progress callback returns +# non-zero. +do_test progress-1.2 { + + # This figures out how many opcodes it takes to copy 5 extra rows into t1. + db progress 1 "[namespace code {incr five_rows}] ; expr 0" + set five_rows 0 + execsql { + INSERT INTO t1 SELECT a+10 FROM t1 WHERE a < 6 + } + db progress 0 "" + execsql { + DELETE FROM t1 WHERE a > 10 + } + + # Now set up the progress callback to abandon the query after the number of + # opcodes to copy 5 rows. That way, when we try to copy 6 rows, we know + # some data will have been inserted into the table by the time the progress + # callback abandons the query. + db progress $five_rows "expr 1" + catchsql { + INSERT INTO t1 SELECT a+10 FROM t1 WHERE a < 9 + } + execsql { + SELECT count(*) FROM t1 + } +} 10 + +# Test that an active transaction remains active and not rolled back +# after the progress query abandons a query. +# +# UPDATE: It is now recognised that this is a sure route to database +# corruption. So the transaction is rolled back. +do_test progress-1.3 { + + db progress 0 "" + execsql BEGIN + execsql { + INSERT INTO t1 VALUES(11) + } + db progress 1 "expr 1" + catchsql { + INSERT INTO t1 VALUES(12) + } + db progress 0 "" + catchsql COMMIT +} {1 {cannot commit - no transaction is active}} +do_test progress-1.3.1 { + execsql { + SELECT count(*) FROM t1 + } +} 10 + +# Check that a value of 0 for N means no progress callback +do_test progress-1.4 { + set counter 0 + db progress 0 "[namespace code {incr counter}] ; expr 0" + execsql { + SELECT * FROM t1; + } + set counter +} 0 + +db progress 0 "" + +# Make sure other queries can be run from within the progress +# handler. Ticket #1827 +# +do_test progress-1.5 { + set rx 0 + proc set_rx {args} { + db progress 0 {} + set ::rx [db eval {SELECT count(*) FROM t1}] + return [expr 0] + } + db progress 10 set_rx + db eval { + SELECT sum(a) FROM t1 + } +} {55} +do_test progress-1.6 { + set ::rx +} {10} + +# Check that abandoning a query using the progress handler does +# not cause other queries to abort. Ticket #2415. +do_test progress-1.7 { + execsql { + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, 6); + INSERT INTO abc VALUES(7, 8, 9); + } + + set ::res [list] + explain {SELECT a, b, c FROM abc} + db eval {SELECT a, b, c FROM abc} { + lappend ::res $a $b $c + db progress 5 "expr 1" + catch {db eval {SELECT a, b, c FROM abc} { }} msg + db progress 5 "expr 0" + lappend ::res $msg + } + + set ::res +} {1 2 3 interrupted 4 5 6 interrupted 7 8 9 interrupted} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/ptrchng.test b/components/external/SQLite-3.8.1/test/ptrchng.test new file mode 100644 index 0000000000000000000000000000000000000000..75525f981c5755ad13cbd5896bcd010abd7dfc2c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/ptrchng.test @@ -0,0 +1,223 @@ +# 2007 April 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# The focus of the tests in this file are to verify that the +# underlying TEXT or BLOB representation of an sqlite3_value +# changes appropriately when APIs from the following set are +# called: +# +# sqlite3_value_text() +# sqlite3_value_text16() +# sqlite3_value_blob() +# sqlite3_value_bytes() +# sqlite3_value_bytes16() +# +# $Id: ptrchng.test,v 1.5 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !bloblit { + finish_test + return +} + +# Register the "pointer_change" SQL function. +# +sqlite3_create_function db + +do_test ptrchng-1.1 { + execsql { + CREATE TABLE t1(x INTEGER PRIMARY KEY, y BLOB); + INSERT INTO t1 VALUES(1, 'abc'); + INSERT INTO t1 VALUES(2, + 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234356789'); + INSERT INTO t1 VALUES(3, x'626c6f62'); + INSERT INTO t1 VALUES(4, + x'000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021222324' + ); + SELECT count(*) FROM t1; + } +} {4} + +# For the short entries that fit in the Mem.zBuf[], the pointer should +# never change regardless of what type conversions occur. +# +# UPDATE: No longer true, as Mem.zBuf[] has been removed. +# +do_test ptrchng-2.1 { + execsql { + SELECT pointer_change(y, 'text', 'noop', 'blob') FROM t1 WHERE x=1 + } +} {0} +do_test ptrchng-2.2 { + execsql { + SELECT pointer_change(y, 'blob', 'noop', 'text') FROM t1 WHERE x=1 + } +} {0} +ifcapable utf16 { + do_test ptrchng-2.3 { + execsql { + SELECT pointer_change(y, 'text', 'noop', 'text16') FROM t1 WHERE x=1 + } + } {1} + do_test ptrchng-2.4 { + execsql { + SELECT pointer_change(y, 'blob', 'noop', 'text16') FROM t1 WHERE x=1 + } + } {1} + do_test ptrchng-2.5 { + execsql { + SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1 WHERE x=1 + } + } {0} + do_test ptrchng-2.6 { + execsql { + SELECT pointer_change(y, 'text16', 'noop', 'text') FROM t1 WHERE x=1 + } + } {1} +} +do_test ptrchng-2.11 { + execsql { + SELECT pointer_change(y, 'text', 'noop', 'blob') FROM t1 WHERE x=3 + } +} {0} +do_test ptrchng-2.12 { + execsql { + SELECT pointer_change(y, 'blob', 'noop', 'text') FROM t1 WHERE x=3 + } +} {0} +ifcapable utf16 { + do_test ptrchng-2.13 { + execsql { + SELECT pointer_change(y, 'text', 'noop', 'text16') FROM t1 WHERE x=3 + } + } {1} + do_test ptrchng-2.14 { + execsql { + SELECT pointer_change(y, 'blob', 'noop', 'text16') FROM t1 WHERE x=3 + } + } {1} + do_test ptrchng-2.15 { + execsql { + SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1 WHERE x=3 + } + } {0} + do_test ptrchng-2.16 { + execsql { + SELECT pointer_change(y, 'text16', 'noop', 'text') FROM t1 WHERE x=3 + } + } {1} +} + +# For the long entries that do not fit in the Mem.zBuf[], the pointer +# should change sometimes. +# +do_test ptrchng-3.1 { + execsql { + SELECT pointer_change(y, 'text', 'noop', 'blob') FROM t1 WHERE x=2 + } +} {0} +do_test ptrchng-3.2 { + execsql { + SELECT pointer_change(y, 'blob', 'noop', 'text') FROM t1 WHERE x=2 + } +} {0} +ifcapable utf16 { + do_test ptrchng-3.3 { + execsql { + SELECT pointer_change(y, 'text', 'noop', 'text16') FROM t1 WHERE x=2 + } + } {1} + do_test ptrchng-3.4 { + execsql { + SELECT pointer_change(y, 'blob', 'noop', 'text16') FROM t1 WHERE x=2 + } + } {1} + do_test ptrchng-3.5 { + execsql { + SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1 WHERE x=2 + } + } {0} + do_test ptrchng-3.6 { + execsql { + SELECT pointer_change(y, 'text16', 'noop', 'text') FROM t1 WHERE x=2 + } + } {1} +} +do_test ptrchng-3.11 { + execsql { + SELECT pointer_change(y, 'text', 'noop', 'blob') FROM t1 WHERE x=4 + } +} {0} +do_test ptrchng-3.12 { + execsql { + SELECT pointer_change(y, 'blob', 'noop', 'text') FROM t1 WHERE x=4 + } +} {0} +ifcapable utf16 { + do_test ptrchng-3.13 { + execsql { + SELECT pointer_change(y, 'text', 'noop', 'text16') FROM t1 WHERE x=4 + } + } {1} + do_test ptrchng-3.14 { + execsql { + SELECT pointer_change(y, 'blob', 'noop', 'text16') FROM t1 WHERE x=4 + } + } {1} + do_test ptrchng-3.15 { + execsql { + SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1 WHERE x=4 + } + } {0} + do_test ptrchng-3.16 { + execsql { + SELECT pointer_change(y, 'text16', 'noop', 'text') FROM t1 WHERE x=4 + } + } {1} +} + +# A call to _bytes() should never reformat a _text() or _blob(). +# +do_test ptrchng-4.1 { + execsql { + SELECT pointer_change(y, 'text', 'bytes', 'text') FROM t1 + } +} {0 0 0 0} +do_test ptrchng-4.2 { + execsql { + SELECT pointer_change(y, 'blob', 'bytes', 'blob') FROM t1 + } +} {0 0 0 0} + +# A call to _blob() should never trigger a reformat +# +do_test ptrchng-5.1 { + execsql { + SELECT pointer_change(y, 'text', 'bytes', 'blob') FROM t1 + } +} {0 0 0 0} +ifcapable utf16 { + do_test ptrchng-5.2 { + execsql { + SELECT pointer_change(y, 'text16', 'noop', 'blob') FROM t1 + } + } {0 0 0 0} + do_test ptrchng-5.3 { + execsql { + SELECT pointer_change(y, 'text16', 'bytes16', 'blob') FROM t1 + } + } {0 0 0 0} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/queryonly.test b/components/external/SQLite-3.8.1/test/queryonly.test new file mode 100644 index 0000000000000000000000000000000000000000..2774e5d4360614efca93a22fa961c0912a3ae667 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/queryonly.test @@ -0,0 +1,72 @@ +# 2013-07-11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file tests the "query_only" pragma. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_execsql_test queryonly-1.1 { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(123),(456); + SELECT a FROM t1 ORDER BY a; +} {123 456} +do_execsql_test queryonly-1.2 { + PRAGMA query_only; +} {0} +do_execsql_test queryonly-1.3 { + PRAGMA query_only=ON; + PRAGMA query_only; +} {1} +do_test queryonly-1.4 { + catchsql {INSERT INTO t1 VALUES(789);} +} {1 {attempt to write a readonly database}} +do_test queryonly-1.5 { + catchsql {DELETE FROM t1;} +} {1 {attempt to write a readonly database}} +do_test queryonly-1.6 { + catchsql {UPDATE t1 SET a=a+1;} +} {1 {attempt to write a readonly database}} +do_test queryonly-1.7 { + catchsql {CREATE TABLE t2(b);} +} {1 {attempt to write a readonly database}} +do_test queryonly-1.8 { + catchsql {CREATE INDEX t1a ON t1(a);} +} {1 {attempt to write a readonly database}} +do_test queryonly-1.9 { + catchsql {DROP TABLE t1;} +} {1 {attempt to write a readonly database}} +do_test queryonly-1.10 { + catchsql {ANALYZE;} +} {1 {attempt to write a readonly database}} +do_execsql_test queryonly-1.11 { + SELECT a FROM t1 ORDER BY a; +} {123 456} + +do_execsql_test queryonly-2.2 { + PRAGMA query_only; +} {1} +do_execsql_test queryonly-2.3 { + PRAGMA query_only=OFF; + PRAGMA query_only; +} {0} +do_execsql_test queryonly-2.4 { + INSERT INTO t1 VALUES(789); + SELECT a FROM t1 ORDER BY a; +} {123 456 789} +do_execsql_test queryonly-2.5 { + UPDATE t1 SET a=a+1; + SELECT a FROM t1 ORDER BY a; +} {124 457 790} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/quick.test b/components/external/SQLite-3.8.1/test/quick.test new file mode 100644 index 0000000000000000000000000000000000000000..974b02de97de2af4468b92991026e5200c67d905 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/quick.test @@ -0,0 +1,15 @@ +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs all tests. +# + +set testdir [file dirname $argv0] +source $testdir/permutations.test + +run_test_suite quick + +finish_test diff --git a/components/external/SQLite-3.8.1/test/quota-glob.test b/components/external/SQLite-3.8.1/test/quota-glob.test new file mode 100644 index 0000000000000000000000000000000000000000..28c813c30f27b71b2f50c012e5dd57d725c8fc69 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/quota-glob.test @@ -0,0 +1,87 @@ +# 2011 December 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests for the glob-style string compare operator embedded in the +# quota shim. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +catch { unset testnum } +catch { unset pattern } +catch { unset text } +catch { unset ans } + +foreach {testnum pattern text ans} { + 1 abcdefg abcdefg 1 + 2 abcdefG abcdefg 0 + 3 abcdef abcdefg 0 + 4 abcdefgh abcdefg 0 + 5 abcdef? abcdefg 1 + 6 abcdef? abcdef 0 + 7 abcdef? abcdefgh 0 + 8 abcdefg abcdef? 0 + 9 abcdef? abcdef? 1 + 10 abc/def abc/def 1 + 11 abc//def abc/def 0 + 12 */abc/* x/abc/y 1 + 13 */abc/* /abc/ 1 + 16 */abc/* x///a/ab/abc 0 + 17 */abc/* x//a/ab/abc/ 1 + 16 */abc/* x///a/ab/abc 0 + 17 */abc/* x//a/ab/abc/ 1 + 18 **/abc/** x//a/ab/abc/ 1 + 19 *?/abc/*? x//a/ab/abc/y 1 + 20 ?*/abc/?* x//a/ab/abc/y 1 + 21 {abc[cde]efg} abcbefg 0 + 22 {abc[cde]efg} abccefg 1 + 23 {abc[cde]efg} abcdefg 1 + 24 {abc[cde]efg} abceefg 1 + 25 {abc[cde]efg} abcfefg 0 + 26 {abc[^cde]efg} abcbefg 1 + 27 {abc[^cde]efg} abccefg 0 + 28 {abc[^cde]efg} abcdefg 0 + 29 {abc[^cde]efg} abceefg 0 + 30 {abc[^cde]efg} abcfefg 1 + 31 {abc[c-e]efg} abcbefg 0 + 32 {abc[c-e]efg} abccefg 1 + 33 {abc[c-e]efg} abcdefg 1 + 34 {abc[c-e]efg} abceefg 1 + 35 {abc[c-e]efg} abcfefg 0 + 36 {abc[^c-e]efg} abcbefg 1 + 37 {abc[^c-e]efg} abccefg 0 + 38 {abc[^c-e]efg} abcdefg 0 + 39 {abc[^c-e]efg} abceefg 0 + 40 {abc[^c-e]efg} abcfefg 1 + 41 {abc[c-e]efg} abc-efg 0 + 42 {abc[-ce]efg} abc-efg 1 + 43 {abc[ce-]efg} abc-efg 1 + 44 {abc[][*?]efg} {abc]efg} 1 + 45 {abc[][*?]efg} {abc*efg} 1 + 46 {abc[][*?]efg} {abc?efg} 1 + 47 {abc[][*?]efg} {abc[efg} 1 + 48 {abc[^][*?]efg} {abc]efg} 0 + 49 {abc[^][*?]efg} {abc*efg} 0 + 50 {abc[^][*?]efg} {abc?efg} 0 + 51 {abc[^][*?]efg} {abc[efg} 0 + 52 {abc[^][*?]efg} {abcdefg} 1 + 53 {*[xyz]efg} {abcxefg} 1 + 54 {*[xyz]efg} {abcwefg} 0 +} { + do_test quota-glob-$testnum.1 { + sqlite3_quota_glob $::pattern $::text + } $::ans + do_test quota-glob-$testnum.2 { + sqlite3_quota_glob $::pattern [string map {/ \\} $::text] + } $::ans +} +finish_test diff --git a/components/external/SQLite-3.8.1/test/quota.test b/components/external/SQLite-3.8.1/test/quota.test new file mode 100644 index 0000000000000000000000000000000000000000..f9655fb8c0ad0e40c54d246318f4acfabcd16393 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/quota.test @@ -0,0 +1,529 @@ +# 2010 September 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_CURDIR is not defined, omit this file. +ifcapable !curdir { + finish_test + return +} + +source $testdir/malloc_common.tcl + +unset -nocomplain defaultVfs +set defaultVfs [file_control_vfsname db] +db close + +do_test quota-1.1 { sqlite3_quota_initialize nosuchvfs 1 } {SQLITE_ERROR} +do_test quota-1.2 { sqlite3_quota_initialize "" 1 } {SQLITE_OK} +do_test quota-1.3 { sqlite3_quota_initialize "" 1 } {SQLITE_MISUSE} +do_test quota-1.4 { sqlite3_quota_shutdown } {SQLITE_OK} + +do_test quota-1.5 { sqlite3_quota_initialize "" 0 } {SQLITE_OK} +do_test quota-1.6 { sqlite3_quota_shutdown } {SQLITE_OK} +do_test quota-1.7 { sqlite3_quota_initialize "" 1 } {SQLITE_OK} +do_test quota-1.8 { sqlite3_quota_shutdown } {SQLITE_OK} + + +#------------------------------------------------------------------------- +# Some simple warm-body tests with a single database file in rollback +# mode: +# +# quota-2.1.*: Test that SQLITE_FULL is returned if the database would +# exceed the configured quota. +# +# quota-2.2.*: Test that SQLITE_FULL is not returned and the database +# grows if the callback extends the quota when the database +# attempts to grow beyond the configured quota. +# +# quota-2.3.*: Open and close a db that is not part of any quota group. At +# one point this was causing mutex refs to be leaked. +# +# quota-2.4.*: Try to shutdown the quota system before closing the db +# file. Check that this fails and the quota system still works +# afterwards. Then close the database and successfully shut +# down the quota system. +# +sqlite3_quota_initialize "" 1 + +unset -nocomplain quota_request_ok +proc quota_check {filename limitvar size} { + upvar $limitvar limit + + lappend ::quota [set limit] $size + if {[info exists ::quota_request_ok]} { set limit $size } +} + +do_test quota-2.1.1 { + sqlite3_quota_set *test.db 4096 quota_check +} {SQLITE_OK} +do_test quota-2.1.2 { + sqlite3 db test.db + execsql { + PRAGMA page_size=1024; + PRAGMA auto_vacuum=OFF; + PRAGMA journal_mode=DELETE; + } + set ::quota [list] + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, randomblob(1100)); + INSERT INTO t1 VALUES(2, randomblob(1100)); + } + set ::quota +} {} +do_test quota-2.1.2.1 { + file_control_vfsname db +} quota/$defaultVfs +do_test quota-2.1.3 { file size test.db } {4096} +do_test quota-2.1.4 { + catchsql { INSERT INTO t1 VALUES(3, randomblob(1100)) } +} {1 {database or disk is full}} +do_test quota-2.1.5 { set ::quota } {4096 5120} + +set ::quota_request_ok 1 +set ::quota [list] +do_test quota-2.2.1 { + execsql { INSERT INTO t1 VALUES(3, randomblob(1100)) } +} {} +do_test quota-2.2.2 { set ::quota } {4096 5120} +do_test quota-2.2.3 { file size test.db } {5120} +unset ::quota_request_ok + +do_test quota-2.3.1 { + sqlite3 db2 bak.db + db2 close +} {} + +do_test quota-2.4.1 { + sqlite3_quota_shutdown +} {SQLITE_MISUSE} +set ::quota [list] +do_test quota-2.4.2 { + catchsql { INSERT INTO t1 VALUES(3, randomblob(1100)) } +} {1 {database or disk is full}} +do_test quota-2.4.3 { set ::quota } {5120 6144} +do_test quota-2.4.4 { file size test.db } {5120} +do_test quota-2.4.99 { + db close + sqlite3_quota_shutdown +} {SQLITE_OK} + +#------------------------------------------------------------------------- +# Try some tests with more than one connection to a database file. Still +# in rollback mode. +# +# quota-3.1.*: Two connections to a single database file. +# +# quota-3.2.*: Two connections to each of several database files (that +# are in the same quota group). +# +proc quota_check {filename limitvar size} { + upvar $limitvar limit + lappend ::quota [set limit] $size + if {[info exists ::quota_request_ok]} { set limit $size } +} + +do_test quota-3.1.1 { + forcedelete test.db + sqlite3_quota_initialize "" 1 + sqlite3_quota_set *test.db 4096 quota_check +} {SQLITE_OK} +do_test quota-3.1.2 { + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = delete; + PRAGMA auto_vacuum = off; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 'one'); + } + file size test.db +} {3072} +do_test quota-3.1.3 { + sqlite3 db2 test.db + set ::quota [list] + execsql { CREATE TABLE t2(a, b) } db2 + set ::quota +} {} +do_test quota-3.1.4 { + catchsql { CREATE TABLE t3(a, b) } +} {1 {database or disk is full}} +do_test quota-3.1.5 { + set ::quota_request_ok 1 + execsql { CREATE TABLE t3(a, b) } +} {} +do_test quota-3.1.6 { + db close + db2 close + sqlite3_quota_set *test.db 0 {} +} {SQLITE_OK} + +do_test quota-3.2.1 { + delete_file force test.db test2.db + + sqlite3_quota_set * 4096 {} + sqlite3 db1a test.db + sqlite3 db2a test2.db + + foreach db {db1a db2a} { + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = delete; + PRAGMA auto_vacuum = off; + CREATE TABLE t1(a, b); + } $db + } + + sqlite3 db1b test.db + sqlite3 db2b test2.db + + list [file size test.db] [file size test2.db] +} {2048 2048} + +catch { unset ::quota_request_ok } + +do_test quota-3.2.2 { execsql { INSERT INTO t1 VALUES('x', 'y') } db1a } {} +do_test quota-3.2.3 { execsql { INSERT INTO t1 VALUES('v', 'w') } db1b } {} +do_test quota-3.2.4 { execsql { INSERT INTO t1 VALUES('t', 'u') } db2a } {} +do_test quota-3.2.5 { execsql { INSERT INTO t1 VALUES('r', 's') } db2b } {} + +do_test quota-3.2.6 { + catchsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db1a +} {1 {database or disk is full}} +do_test quota-3.2.7 { + catchsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db1b +} {1 {database or disk is full}} +do_test quota-3.2.8 { + catchsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db2a +} {1 {database or disk is full}} +do_test quota-3.2.9 { + catchsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db2b +} {1 {database or disk is full}} + +set ::quota [list] +proc quota_callback {file limitvar size} { + upvar $limitvar limit + if {$::tcl_platform(platform)=="windows"} { + set file [ lindex [string map {\\ \/} $file] 0 ] + } + lappend ::quota $file $size + set limit 0 +} +sqlite3_quota_set * 4096 quota_callback +do_test quota-3.3.1 { + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db1a + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db1b + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db2a + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } db2b + set ::quota +} [list [file join [get_pwd] test.db] 5120] + +do_test quota-3.2.X { + foreach db {db1a db2a db2b db1b} { catch { $db close } } + sqlite3_quota_set * 0 {} +} {SQLITE_OK} + +#------------------------------------------------------------------------- +# Quotas are deleted when unused and when their limit is set to zero +# + +# Return a list of all currently defined quotas. Each quota is identified +# by its pattern. +proc quota_list {} { + set allq {} + foreach q [sqlite3_quota_dump] { + lappend allq [lindex $q 0] + } + return [lsort $allq] +} +proc quota_size {name} { + set allq {} + foreach q [sqlite3_quota_dump] { + if {[lindex $q 0]==$name} {return [lindex $q 2]} + } + return 0 +} + +do_test quota-4.1.1 { + sqlite3_quota_set *test.db 0 {} + quota_list +} {} +do_test quota-4.1.2 { + sqlite3_quota_set *test.db 4096 {} + quota_list +} {*test.db} +do_test quota-4.1.3 { + sqlite3_quota_set *test2.db 0 {} + quota_list +} {*test.db} +do_test quota-4.1.4 { + sqlite3_quota_set *test2.db 100000 {} + quota_list +} {*test.db *test2.db} +do_test quota-4.1.5 { + sqlite3_quota_set *test.db 0 {} + quota_list +} {*test2.db} +do_test quota-4.1.6 { + forcedelete test2.db test2.db-journal test2.db-wal + sqlite3 db test2.db + db eval {CREATE TABLE t2(x); INSERT INTO t2 VALUES('tab-t2');} + quota_list +} {*test2.db} +do_test quota-4.1.7 { + catchsql {INSERT INTO t2 VALUES(zeroblob(200000))} +} {1 {database or disk is full}} +do_test quota-4.1.8 { + sqlite3 db2 test2.db + db2 eval {SELECT * FROM t2} +} {tab-t2} +do_test quota-4.1.9 { + sqlite3_quota_set *test2.db 0 {} + catchsql {INSERT INTO t2 VALUES(zeroblob(200000))} +} {0 {}} +do_test quota-4.1.10 { + quota_list +} {*test2.db} +do_test quota-4.1.11 { + db2 close + quota_list +} {*test2.db} +do_test quota-4.1.12 { + db close + quota_list +} {} + +do_test quota-4.2.1 { + sqlite3_quota_set A 1000 {} + sqlite3_quota_set B 1000 {} + sqlite3_quota_set C 1000 {} + sqlite3_quota_set D 1000 {} + quota_list +} {A B C D} +do_test quota-4.2.2 { + sqlite3_quota_set C 0 {} + sqlite3_quota_set B 0 {} + quota_list +} {A D} +do_test quota-4.2.3 { + sqlite3_quota_set A 0 {} + sqlite3_quota_set D 0 {} + quota_list +} {} +do_test quota-4.2.4 { + sqlite3_quota_set A 1000 {} + sqlite3_quota_set B 1000 {} + sqlite3_quota_set C 1000 {} + sqlite3_quota_set A 0 {} + sqlite3_quota_set B 0 {} + sqlite3_quota_set C 0 {} + quota_list +} {} +do_test quota-4.2.5 { + sqlite3_quota_set A 1000 {} + sqlite3_quota_set B 1000 {} + sqlite3_quota_set C 1000 {} + sqlite3_quota_set C 0 {} + sqlite3_quota_set B 0 {} + sqlite3_quota_set A 0 {} + quota_list +} {} + +do_test quota-4.3.1 { + sqlite3_quota_set A 1000 quota_callback + sqlite3 db A + sqlite3_quota_set A 0 quota_callback + db close + quota_list +} {} + +unset -nocomplain quotagroup +if {$tcl_platform(platform)=="windows"} { + set quotagroup *\\quota-test-A?.db +} else { + set quotagroup */quota-test-A?.db +} +foreach file [glob -nocomplain quota-test-A*] { + forcedelete $file +} +do_test quota-4.4.1 { + set ::quota {} + sqlite3_quota_set $::quotagroup 10000 quota_callback + forcedelete ./quota-test-A1.db ./quota-test-A2.db + sqlite3 db ./quota-test-A1.db + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(5000)); + } + quota_list +} [list $quotagroup] +do_test quota-4.4.2 { + expr {$::quota==""} +} {1} +do_test quota-4.4.3 { + db close + sqlite3 db ./quota-test-A2.db + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(5000)); + } + quota_list +} [list $quotagroup] +do_test quota-4.4.4 { + expr {$::quota!=""} +} {1} +do_test quota-4.4.5 { + db close + sqlite3_quota_set $::quotagroup 0 {} + sqlite3_quota_dump +} {} +do_test quota-4.4.6 { + sqlite3_quota_set $quotagroup 10000 quota_callback + sqlite3 db quota-test-A1.db + db eval {SELECT count(*) FROM sqlite_master} + quota_size $quotagroup +} [file size quota-test-A1.db] +do_test quota-4.4.7 { + sqlite3_quota_file quota-test-A2.db + quota_size $::quotagroup +} [expr {[file size quota-test-A1.db]+[file size quota-test-A2.db]}] + +unset -nocomplain quotagroup +if {$tcl_platform(platform)=="windows"} { + set quotagroup *\\quota-test-B* +} else { + set quotagroup */quota-test-B* +} +foreach file [glob -nocomplain quota-test-B*] { + forcedelete $file +} +do_test quota-4.5.1 { + sqlite3_quota_set $::quotagroup 100000 quota_callback + quota_size $::quotagroup +} {0} +do_test quota-4.5.2 { + sqlite3_quota_file quota-test-B1.txt + quota_size $::quotagroup +} {0} +proc add_to_file {name n} { + set out [open $name a] + fconfigure $out -translation binary + puts -nonewline $out [string repeat x $n] + close $out +} +do_test quota-4.5.3 { + add_to_file quota-test-B1.txt 123 + sqlite3_quota_file quota-test-B1.txt + quota_size $::quotagroup +} {123} +do_test quota-4.5.4 { + add_to_file quota-test-B2.txt 234 + sqlite3_quota_file quota-test-B2.txt + quota_size $::quotagroup +} {357} +do_test quota-4.5.5 { + add_to_file quota-test-B1.txt 2000 + sqlite3_quota_file quota-test-B1.txt + quota_size $::quotagroup +} {2357} +do_test quota-4.5.6 { + forcedelete quota-test-B1.txt + sqlite3_quota_file quota-test-B1.txt + quota_size $::quotagroup +} {234} +do_test quota-4.5.7 { + forcedelete quota-test-B2.txt + sqlite3_quota_file quota-test-B2.txt + quota_size $::quotagroup +} {0} +do_test quota-4.5.8 { + add_to_file quota-test-B3.txt 1234 + sqlite3_quota_file quota-test-B3.txt + quota_size $::quotagroup +} {1234} +do_test quota-4.5.9 { + sqlite3_quota_set $quotagroup 0 {} + quota_size $::quotagroup +} {0} + +do_test quota-4.9.1 { + db close + sqlite3_quota_set A 1000 quota_callback + sqlite3_quota_shutdown +} {SQLITE_OK} +do_test quota-4.9.2 { + quota_list +} {} + +#------------------------------------------------------------------------- +# The following tests test that the quota VFS handles malloc and IO +# errors. +# + +sqlite3_quota_initialize "" 1 +sqlite3_quota_set *test.db 4096 {} + +do_faultsim_test quota-5.1 -prep { + catch {db close} +} -body { + sqlite3 db test2.db +} +do_faultsim_test quota-5.2 -prep { + catch {db close} +} -body { + sqlite3 db test.db +} + +catch { db close } +forcedelete test.db + +do_test quota-5.3.prep { + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum = 1; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(10, zeroblob(1200)); + } + faultsim_save_and_close +} {} +do_faultsim_test quota-5.3 -prep { + faultsim_restore_and_reopen +} -body { + execsql { DELETE FROM t1 } +} + +do_test quota-5.4.1 { + catch { db close } + forcedelete test.db + file mkdir test.db + list [catch { sqlite3 db test.db } msg] $msg +} {1 {unable to open database file}} + +do_faultsim_test quota-5.5 -prep { + catch { sqlite3_quota_shutdown } +} -body { + sqlite3_quota_initialize "" 1 +} + +do_faultsim_test quota-5.6 -prep { + catch { sqlite3_quota_shutdown } + sqlite3_quota_initialize "" 1 +} -body { + sqlite3_quota_set * 4096 {} +} + +catch { sqlite3_quota_shutdown } +finish_test diff --git a/components/external/SQLite-3.8.1/test/quota2.test b/components/external/SQLite-3.8.1/test/quota2.test new file mode 100644 index 0000000000000000000000000000000000000000..8682bd86a331441e1b496b0201bd88b4600ba3db --- /dev/null +++ b/components/external/SQLite-3.8.1/test/quota2.test @@ -0,0 +1,302 @@ +# 2011 December 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If SQLITE_CURDIR is not defined, omit this file. +ifcapable !curdir { + finish_test + return +} + +source $testdir/malloc_common.tcl + +db close +sqlite3_quota_initialize "" 1 + +foreach dir {quota2a/x1 quota2a/x2 quota2a quota2b quota2c} { + forcedelete $dir +} +foreach dir {quota2a quota2a/x1 quota2a/x2 quota2b quota2c} { + file mkdir $dir +} + +# The standard_path procedure converts a pathname into a standard format +# that is the same across platforms. +# +unset -nocomplain ::quota_pwd ::quota_mapping +set ::quota_pwd [string map {\\ /} [get_pwd]] +set ::quota_mapping [list $::quota_pwd PWD] +proc standard_path {x} { + set x [string map {\\ /} $x] + return [string map $::quota_mapping $x] +} + +# The quota_check procedure is a callback from the quota handler. +# It has three arguments which are (1) the full pathname of the file +# that has gone over quota, (2) the quota limit, (3) the requested +# new quota size to cover the last write. These three values are +# appended to the global variable $::quota. The filename is processed +# to convert every \ character into / and to change the name of the +# working directory to PWD. +# +# The quota is increased to the request if the ::quota_request_ok +# global variable is true. +# +set ::quota {} +set ::quota_request_ok 0 + +proc quota_check {filename limitvar size} { + upvar $limitvar limit + lappend ::quota [standard_path $filename] [set limit] $size + if {$::quota_request_ok} {set limit $size} +} + +sqlite3_quota_set */quota2a/* 4000 quota_check +sqlite3_quota_set */quota2b/* 5000 quota_check + +unset -nocomplain bigtext +for {set i 1} {$i<=1000} {incr i} { + if {$i%10==0} { + append bigtext [format "%06d\n" $i] + } else { + append bigtext [format "%06d " $i] + } +} + +catch { unset h1 } +catch { unset x } +do_test quota2-1.1 { + set ::h1 [sqlite3_quota_fopen quota2a/xyz.txt w+b] + sqlite3_quota_fwrite $::h1 1 7000 $bigtext +} {4000} +do_test quota2-1.2 { + set ::quota +} {PWD/quota2a/xyz.txt 4000 7000} +do_test quota2-1.2.1 { + sqlite3_quota_file_size $::h1 +} {4000} +do_test quota2-1.2.2 { + sqlite3_quota_fflush $::h1 1 + sqlite3_quota_file_truesize $::h1 +} {4000} +do_test quota2-1.3 { + sqlite3_quota_rewind $::h1 + set ::x [sqlite3_quota_fread $::h1 1001 7] + string length $::x +} {3003} +do_test quota2-1.4 { + string match $::x [string range $::bigtext 0 3002] +} {1} +do_test quota2-1.5 { + sqlite3_quota_fseek $::h1 0 SEEK_END + sqlite3_quota_ftell $::h1 +} {4000} +do_test quota2-1.6 { + sqlite3_quota_fseek $::h1 -100 SEEK_END + sqlite3_quota_ftell $::h1 +} {3900} +do_test quota2-1.7 { + sqlite3_quota_fseek $::h1 -100 SEEK_CUR + sqlite3_quota_ftell $::h1 +} {3800} +do_test quota2-1.8 { + sqlite3_quota_fseek $::h1 50 SEEK_CUR + sqlite3_quota_ftell $::h1 +} {3850} +do_test quota2-1.9 { + sqlite3_quota_fseek $::h1 50 SEEK_SET + sqlite3_quota_ftell $::h1 +} {50} +do_test quota2-1.10 { + sqlite3_quota_rewind $::h1 + sqlite3_quota_ftell $::h1 +} {0} +do_test quota2-1.11 { + standard_path [sqlite3_quota_dump] +} {{*/quota2b/* 5000 0} {*/quota2a/* 4000 4000 {PWD/quota2a/xyz.txt 4000 1 0}}} +do_test quota2-1.12 { + sqlite3_quota_ftruncate $::h1 3500 + sqlite3_quota_file_size $::h1 +} {3500} +do_test quota2-1.13 { + sqlite3_quota_file_truesize $::h1 +} {3500} +do_test quota2-1.14 { + standard_path [sqlite3_quota_dump] +} {{*/quota2b/* 5000 0} {*/quota2a/* 4000 3500 {PWD/quota2a/xyz.txt 3500 1 0}}} +do_test quota2-1.15 { + sqlite3_quota_fseek $::h1 0 SEEK_END + sqlite3_quota_ftell $::h1 +} {3500} +do_test quota2-1.16 { + sqlite3_quota_fwrite $::h1 1 7000 $bigtext +} {500} +do_test quota2-1.17 { + sqlite3_quota_ftell $::h1 +} {4000} +do_test quota2-1.18 { + sqlite3_quota_file_size $::h1 +} {4000} +do_test quota2-1.19 { + sqlite3_quota_fflush $::h1 1 + sqlite3_quota_file_truesize $::h1 +} {4000} +do_test quota2-1.20 { + sqlite3_quota_fclose $::h1 + standard_path [sqlite3_quota_dump] +} {{*/quota2b/* 5000 0} {*/quota2a/* 4000 4000 {PWD/quota2a/xyz.txt 4000 0 0}}} +do_test quota2-1.21 { + sqlite3_quota_remove quota2a/xyz.txt + standard_path [sqlite3_quota_dump] +} {{*/quota2b/* 5000 0} {*/quota2a/* 4000 0}} + + + +set quota {} +do_test quota2-2.1 { + set ::h1 [sqlite3_quota_fopen quota2c/xyz.txt w+b] + sqlite3_quota_fwrite $::h1 1 7000 $bigtext +} {7000} +do_test quota2-2.2 { + set ::quota +} {} +do_test quota2-2.3.1 { + sqlite3_quota_rewind $::h1 + sqlite3_quota_file_available $::h1 +} {7000} +do_test quota2-2.3.2 { + set ::x [sqlite3_quota_fread $::h1 1001 7] + string length $::x +} {6006} +do_test quota2-2.3.3 { + sqlite3_quota_file_available $::h1 +} {0} +do_test quota2-2.4 { + string match $::x [string range $::bigtext 0 6005] +} {1} +do_test quota2-2.5 { + sqlite3_quota_fseek $::h1 0 SEEK_END + sqlite3_quota_ftell $::h1 +} {7000} +do_test quota2-2.6 { + sqlite3_quota_fseek $::h1 -100 SEEK_END + sqlite3_quota_ftell $::h1 +} {6900} +do_test quota2-2.6.1 { + sqlite3_quota_file_available $::h1 +} {100} +do_test quota2-2.7 { + sqlite3_quota_fseek $::h1 -100 SEEK_CUR + sqlite3_quota_ftell $::h1 +} {6800} +do_test quota2-2.7.1 { + sqlite3_quota_file_available $::h1 +} {200} +do_test quota2-2.8 { + sqlite3_quota_fseek $::h1 50 SEEK_CUR + sqlite3_quota_ftell $::h1 +} {6850} +do_test quota2-2.8.1 { + sqlite3_quota_file_available $::h1 +} {150} +do_test quota2-2.9 { + sqlite3_quota_fseek $::h1 50 SEEK_SET + sqlite3_quota_ftell $::h1 +} {50} +do_test quota2-2.9.1 { + sqlite3_quota_file_available $::h1 +} {6950} +do_test quota2-2.10 { + sqlite3_quota_rewind $::h1 + sqlite3_quota_ftell $::h1 +} {0} +do_test quota2-2.10.1 { + sqlite3_quota_file_available $::h1 +} {7000} +do_test quota2-2.10.2 { + sqlite3_quota_ferror $::h1 +} {0} +do_test quota2-2.11 { + standard_path [sqlite3_quota_dump] +} {{*/quota2b/* 5000 0} {*/quota2a/* 4000 0}} +do_test quota2-2.12 { + sqlite3_quota_fclose $::h1 + standard_path [sqlite3_quota_dump] +} {{*/quota2b/* 5000 0} {*/quota2a/* 4000 0}} + +do_test quota2-3.1 { + sqlite3_quota_set */quota2b/* 0 quota_check + set ::h1 [sqlite3_quota_fopen quota2a/x1/a.txt a] + sqlite3_quota_fwrite $::h1 10 10 $bigtext +} {10} +do_test quota2-3.2 { + standard_path [sqlite3_quota_dump] +} {{*/quota2a/* 4000 100 {PWD/quota2a/x1/a.txt 100 1 0}}} +do_test quota2-3.3a { + sqlite3_quota_fflush $::h1 0 + standard_path [sqlite3_quota_dump] +} {{*/quota2a/* 4000 100 {PWD/quota2a/x1/a.txt 100 1 0}}} +do_test quota2-3.3b { + sqlite3_quota_fflush $::h1 1 + standard_path [sqlite3_quota_dump] +} {{*/quota2a/* 4000 100 {PWD/quota2a/x1/a.txt 100 1 0}}} +do_test quota2-3.3c { + sqlite3_quota_fflush $::h1 + standard_path [sqlite3_quota_dump] +} {{*/quota2a/* 4000 100 {PWD/quota2a/x1/a.txt 100 1 0}}} +do_test quota2-3.4 { + sqlite3_quota_fclose $::h1 + standard_path [sqlite3_quota_dump] +} {{*/quota2a/* 4000 100 {PWD/quota2a/x1/a.txt 100 0 0}}} +do_test quota2-3.5 { + set ::h2 [sqlite3_quota_fopen quota2a/x2/b.txt a] + sqlite3_quota_fwrite $::h2 10 20 $bigtext + standard_path [sqlite3_quota_dump] +} {{*/quota2a/* 4000 300 {PWD/quota2a/x2/b.txt 200 1 0} {PWD/quota2a/x1/a.txt 100 0 0}}} +do_test quota2-3.6 { + set ::h3 [sqlite3_quota_fopen quota2a/x1/c.txt a] + sqlite3_quota_fwrite $::h3 10 50 $bigtext + standard_path [sqlite3_quota_dump] +} {{*/quota2a/* 4000 800 {PWD/quota2a/x1/c.txt 500 1 0} {PWD/quota2a/x2/b.txt 200 1 0} {PWD/quota2a/x1/a.txt 100 0 0}}} +do_test quota2-3.7 { + file exists quota2a/x1/a.txt +} {1} +do_test quota2-3.8 { + file exists quota2a/x2/b.txt +} {1} +do_test quota2-3.9 { + file exists quota2a/x1/c.txt +} {1} +do_test quota2-3.10 { + sqlite3_quota_remove quota2a/x1 + standard_path [sqlite3_quota_dump] +} {{*/quota2a/* 4000 700 {PWD/quota2a/x1/c.txt 500 1 1} {PWD/quota2a/x2/b.txt 200 1 0}}} +do_test quota2-3.11 { + sqlite3_quota_fclose $::h2 + sqlite3_quota_fclose $::h3 + standard_path [sqlite3_quota_dump] +} {{*/quota2a/* 4000 200 {PWD/quota2a/x2/b.txt 200 0 0}}} +do_test quota2-3.12 { + file exists quota2a/x1/a.txt +} {0} +do_test quota2-3.13 { + file exists quota2a/x2/b.txt +} {1} +do_test quota2-3.14 { + file exists quota2a/x1/c.txt +} {0} + +catch { sqlite3_quota_shutdown } +catch { unset quota_request_ok } +finish_test diff --git a/components/external/SQLite-3.8.1/test/quote.test b/components/external/SQLite-3.8.1/test/quote.test new file mode 100644 index 0000000000000000000000000000000000000000..f13d6f9ee9485e28fd986bba226896fa9cca4d92 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/quote.test @@ -0,0 +1,89 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is the ability to specify table and column names +# as quoted strings. +# +# $Id: quote.test,v 1.7 2007/04/25 11:32:30 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table with a strange name and with strange column names. +# +do_test quote-1.0 { + catchsql {CREATE TABLE '@abc' ( '#xyz' int, '!pqr' text );} +} {0 {}} + +# Insert, update and query the table. +# +do_test quote-1.1 { + catchsql {INSERT INTO '@abc' VALUES(5,'hello')} +} {0 {}} +do_test quote-1.2.1 { + catchsql {SELECT * FROM '@abc'} +} {0 {5 hello}} +do_test quote-1.2.2 { + catchsql {SELECT * FROM [@abc]} ;# SqlServer compatibility +} {0 {5 hello}} +do_test quote-1.2.3 { + catchsql {SELECT * FROM `@abc`} ;# MySQL compatibility +} {0 {5 hello}} +do_test quote-1.3 { + catchsql { + SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc' + } +} {0 {hello 10}} +do_test quote-1.3.1 { + catchsql { + SELECT '!pqr', '#xyz'+5 FROM '@abc' + } +} {0 {!pqr 5}} +do_test quote-1.3.2 { + catchsql { + SELECT "!pqr", "#xyz"+5 FROM '@abc' + } +} {0 {hello 10}} +do_test quote-1.3.3 { + catchsql { + SELECT [!pqr], `#xyz`+5 FROM '@abc' + } +} {0 {hello 10}} +do_test quote-1.3.4 { + set r [catch { + execsql {SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc'} + } msg ] + lappend r $msg +} {0 {hello 10}} +do_test quote-1.4 { + set r [catch { + execsql {UPDATE '@abc' SET '#xyz'=11} + } msg ] + lappend r $msg +} {0 {}} +do_test quote-1.5 { + set r [catch { + execsql {SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc'} + } msg ] + lappend r $msg +} {0 {hello 16}} + +# Drop the table with the strange name. +# +do_test quote-1.6 { + set r [catch { + execsql {DROP TABLE '@abc'} + } msg ] + lappend r $msg +} {0 {}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/randexpr1.tcl b/components/external/SQLite-3.8.1/test/randexpr1.tcl new file mode 100644 index 0000000000000000000000000000000000000000..37ebf531e8509ebd61fa8498a1ab4f8b0e743977 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/randexpr1.tcl @@ -0,0 +1,342 @@ +# Run this TCL script to generate thousands of test cases containing +# complicated expressions. +# +# The generated tests are intended to verify expression evaluation +# in SQLite against expression evaluation TCL. +# + +# Terms of the $intexpr list each contain two sub-terms. +# +# * An SQL expression template +# * The equivalent TCL expression +# +# EXPR is replaced by an integer subexpression. BOOL is replaced +# by a boolean subexpression. +# +set intexpr { + {11 wide(11)} + {13 wide(13)} + {17 wide(17)} + {19 wide(19)} + {a $a} + {b $b} + {c $c} + {d $d} + {e $e} + {f $f} + {t1.a $a} + {t1.b $b} + {t1.c $c} + {t1.d $d} + {t1.e $e} + {t1.f $f} + {(EXPR) (EXPR)} + {{ -EXPR} {-EXPR}} + {+EXPR +EXPR} + {~EXPR ~EXPR} + {EXPR+EXPR EXPR+EXPR} + {EXPR-EXPR EXPR-EXPR} + {EXPR*EXPR EXPR*EXPR} + {EXPR+EXPR EXPR+EXPR} + {EXPR-EXPR EXPR-EXPR} + {EXPR*EXPR EXPR*EXPR} + {EXPR+EXPR EXPR+EXPR} + {EXPR-EXPR EXPR-EXPR} + {EXPR*EXPR EXPR*EXPR} + {{EXPR | EXPR} {EXPR | EXPR}} + {(abs(EXPR)/abs(EXPR)) (abs(EXPR)/abs(EXPR))} + { + {case when BOOL then EXPR else EXPR end} + {((BOOL)?EXPR:EXPR)} + } + { + {case when BOOL then EXPR when BOOL then EXPR else EXPR end} + {((BOOL)?EXPR:((BOOL)?EXPR:EXPR))} + } + { + {case EXPR when EXPR then EXPR else EXPR end} + {(((EXPR)==(EXPR))?EXPR:EXPR)} + } + { + {(select AGG from t1)} + {(AGG)} + } + { + {coalesce((select max(EXPR) from t1 where BOOL),EXPR)} + {[coalesce_subquery [expr {EXPR}] [expr {BOOL}] [expr {EXPR}]]} + } + { + {coalesce((select EXPR from t1 where BOOL),EXPR)} + {[coalesce_subquery [expr {EXPR}] [expr {BOOL}] [expr {EXPR}]]} + } +} + +# The $boolexpr list contains terms that show both an SQL boolean +# expression and its equivalent TCL. +# +set boolexpr { + {EXPR=EXPR ((EXPR)==(EXPR))} + {EXPREXPR ((EXPR)>(EXPR))} + {EXPR<=EXPR ((EXPR)<=(EXPR))} + {EXPR>=EXPR ((EXPR)>=(EXPR))} + {EXPR<>EXPR ((EXPR)!=(EXPR))} + { + {EXPR between EXPR and EXPR} + {[betweenop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]]} + } + { + {EXPR not between EXPR and EXPR} + {(![betweenop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]])} + } + { + {EXPR in (EXPR,EXPR,EXPR)} + {([inop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]])} + } + { + {EXPR not in (EXPR,EXPR,EXPR)} + {(![inop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]])} + } + { + {EXPR in (select EXPR from t1 union select EXPR from t1)} + {[inop [expr {EXPR}] [expr {EXPR}] [expr {EXPR}]]} + } + { + {EXPR in (select AGG from t1 union select AGG from t1)} + {[inop [expr {EXPR}] [expr {AGG}] [expr {AGG}]]} + } + { + {exists(select 1 from t1 where BOOL)} + {(BOOL)} + } + { + {not exists(select 1 from t1 where BOOL)} + {!(BOOL)} + } + {{not BOOL} !BOOL} + {{BOOL and BOOL} {BOOL tcland BOOL}} + {{BOOL or BOOL} {BOOL || BOOL}} + {{BOOL and BOOL} {BOOL tcland BOOL}} + {{BOOL or BOOL} {BOOL || BOOL}} + {(BOOL) (BOOL)} + {(BOOL) (BOOL)} +} + +# Aggregate expressions +# +set aggexpr { + {count(*) wide(1)} + {{count(distinct EXPR)} {[one {EXPR}]}} + {{cast(avg(EXPR) AS integer)} (EXPR)} + {min(EXPR) (EXPR)} + {max(EXPR) (EXPR)} + {(AGG) (AGG)} + {{ -AGG} {-AGG}} + {+AGG +AGG} + {~AGG ~AGG} + {abs(AGG) abs(AGG)} + {AGG+AGG AGG+AGG} + {AGG-AGG AGG-AGG} + {AGG*AGG AGG*AGG} + {{AGG | AGG} {AGG | AGG}} + { + {case AGG when AGG then AGG else AGG end} + {(((AGG)==(AGG))?AGG:AGG)} + } +} + +# Convert a string containing EXPR, AGG, and BOOL into a string +# that contains nothing but X, Y, and Z. +# +proc extract_vars {a} { + regsub -all {EXPR} $a X a + regsub -all {AGG} $a Y a + regsub -all {BOOL} $a Z a + regsub -all {[^XYZ]} $a {} a + return $a +} + + +# Test all templates to make sure the number of EXPR, AGG, and BOOL +# expressions match. +# +foreach term [concat $aggexpr $intexpr $boolexpr] { + foreach {a b} $term break + if {[extract_vars $a]!=[extract_vars $b]} { + error "mismatch: $term" + } +} + +# Generate a random expression according to the templates given above. +# If the argument is EXPR or omitted, then an integer expression is +# generated. If the argument is BOOL then a boolean expression is +# produced. +# +proc generate_expr {{e EXPR}} { + set tcle $e + set ne [llength $::intexpr] + set nb [llength $::boolexpr] + set na [llength $::aggexpr] + set div 2 + set mx 50 + set i 0 + while {1} { + set cnt 0 + set re [lindex $::intexpr [expr {int(rand()*$ne)}]] + incr cnt [regsub {EXPR} $e [lindex $re 0] e] + regsub {EXPR} $tcle [lindex $re 1] tcle + set rb [lindex $::boolexpr [expr {int(rand()*$nb)}]] + incr cnt [regsub {BOOL} $e [lindex $rb 0] e] + regsub {BOOL} $tcle [lindex $rb 1] tcle + set ra [lindex $::aggexpr [expr {int(rand()*$na)}]] + incr cnt [regsub {AGG} $e [lindex $ra 0] e] + regsub {AGG} $tcle [lindex $ra 1] tcle + + if {$cnt==0} break + incr i $cnt + + set v1 [extract_vars $e] + if {$v1!=[extract_vars $tcle]} { + exit + } + + if {$i+[string length $v1]>=$mx} { + set ne [expr {$ne/$div}] + set nb [expr {$nb/$div}] + set na [expr {$na/$div}] + set div 1 + set mx [expr {$mx*1000}] + } + } + regsub -all { tcland } $tcle { \&\& } tcle + return [list $e $tcle] +} + +# Implementation of routines used to implement the IN and BETWEEN +# operators. +proc inop {lhs args} { + foreach a $args { + if {$a==$lhs} {return 1} + } + return 0 +} +proc betweenop {lhs first second} { + return [expr {$lhs>=$first && $lhs<=$second}] +} +proc coalesce_subquery {a b e} { + if {$b} { + return $a + } else { + return $e + } +} +proc one {args} { + return 1 +} + +# Begin generating the test script: +# +puts {# 2008 December 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file tests randomly generated SQL expressions. The expressions +# are generated by a TCL script. The same TCL script also computes the +# correct value of the expression. So, from one point of view, this +# file verifies the expression evaluation logic of SQLite against the +# expression evaluation logic of TCL. +# +# An early version of this script is how bug #3541 was detected. +# +# $Id: randexpr1.tcl,v 1.1 2008/12/15 16:33:30 drh Exp $ +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create test data +# +do_test randexpr1-1.1 { + db eval { + CREATE TABLE t1(a,b,c,d,e,f); + INSERT INTO t1 VALUES(100,200,300,400,500,600); + SELECT * FROM t1 + } +} {100 200 300 400 500 600} +} + +# Test data for TCL evaluation. +# +set a [expr {wide(100)}] +set b [expr {wide(200)}] +set c [expr {wide(300)}] +set d [expr {wide(400)}] +set e [expr {wide(500)}] +set f [expr {wide(600)}] + +# A procedure to generate a test case. +# +set tn 0 +proc make_test_case {sql result} { + global tn + incr tn + puts "do_test randexpr-2.$tn {\n db eval {$sql}\n} {$result}" +} + +# Generate many random test cases. +# +expr srand(0) +for {set i 0} {$i<1000} {incr i} { + while {1} { + foreach {sqle tcle} [generate_expr EXPR] break; + if {[catch {expr $tcle} ans]} { + #puts stderr [list $tcle] + #puts stderr ans=$ans + if {![regexp {divide by zero} $ans]} exit + continue + } + set len [string length $sqle] + if {$len<100 || $len>2000} continue + if {[info exists seen($sqle)]} continue + set seen($sqle) 1 + break + } + while {1} { + foreach {sqlb tclb} [generate_expr BOOL] break; + if {[catch {expr $tclb} bans]} { + #puts stderr [list $tclb] + #puts stderr bans=$bans + if {![regexp {divide by zero} $bans]} exit + continue + } + break + } + if {$bans} { + make_test_case "SELECT $sqle FROM t1 WHERE $sqlb" $ans + make_test_case "SELECT $sqle FROM t1 WHERE NOT ($sqlb)" {} + } else { + make_test_case "SELECT $sqle FROM t1 WHERE $sqlb" {} + make_test_case "SELECT $sqle FROM t1 WHERE NOT ($sqlb)" $ans + } + if {[regexp { \| } $sqle]} { + regsub -all { \| } $sqle { \& } sqle + regsub -all { \| } $tcle { \& } tcle + if {[catch {expr $tcle} ans]==0} { + if {$bans} { + make_test_case "SELECT $sqle FROM t1 WHERE $sqlb" $ans + } else { + make_test_case "SELECT $sqle FROM t1 WHERE NOT ($sqlb)" $ans + } + } + } +} + +# Terminate the test script +# +puts {finish_test} diff --git a/components/external/SQLite-3.8.1/test/randexpr1.test b/components/external/SQLite-3.8.1/test/randexpr1.test new file mode 100644 index 0000000000000000000000000000000000000000..7a98f0be0fdbce4aabda03d21709a3d4f3821205 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/randexpr1.test @@ -0,0 +1,7837 @@ +# 2008 December 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file tests randomly generated SQL expressions. The expressions +# are generated by a TCL script. The same TCL script also computes the +# correct value of the expression. So, from one point of view, this +# file verifies the expression evaluation logic of SQLite against the +# expression evaluation logic of TCL. +# +# An early version of this script is how bug #3541 was detected. +# +# $Id: randexpr1.test,v 1.1 2008/12/15 16:33:30 drh Exp $ +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +# Create test data +# +do_test randexpr1-1.1 { + db eval { + CREATE TABLE t1(a,b,c,d,e,f); + INSERT INTO t1 VALUES(100,200,300,400,500,600); + SELECT * FROM t1 + } +} {100 200 300 400 500 600} + +do_test randexpr-2.1 { + db eval {SELECT coalesce((select 11 from t1 where 19 in (t1.b,+11,coalesce((select max((abs(17)/abs(t1.f))) from t1 where ((abs(t1.f)/abs(t1.b)) in (select case (min(t1.a | d*d)+(abs(count(*)-count(*)+ -count(*)*max( -t1.c))-max(f))) when -count(distinct 19) then ((count(*))) else max(13) end from t1 union select count(distinct b) from t1)) or 19 in (t1.a,t1.c,17)),17) | 17)),13) FROM t1 WHERE not not c=a-+(select case ~case -~+count(distinct (select count(distinct t1.a)*max(13) from t1))+max( -19*f)*max(f)*max(f)* -count(distinct d)-(count(distinct 11)) | max(t1.f)*count(*) when count(distinct b) then count(distinct t1.b) else -min(t1.f) end*cast(avg(11) AS integer) when max(t1.f) then max(c) else count(*) end from t1)+d} +} {} +do_test randexpr-2.2 { + db eval {SELECT coalesce((select 11 from t1 where 19 in (t1.b,+11,coalesce((select max((abs(17)/abs(t1.f))) from t1 where ((abs(t1.f)/abs(t1.b)) in (select case (min(t1.a | d*d)+(abs(count(*)-count(*)+ -count(*)*max( -t1.c))-max(f))) when -count(distinct 19) then ((count(*))) else max(13) end from t1 union select count(distinct b) from t1)) or 19 in (t1.a,t1.c,17)),17) | 17)),13) FROM t1 WHERE NOT (not not c=a-+(select case ~case -~+count(distinct (select count(distinct t1.a)*max(13) from t1))+max( -19*f)*max(f)*max(f)* -count(distinct d)-(count(distinct 11)) | max(t1.f)*count(*) when count(distinct b) then count(distinct t1.b) else -min(t1.f) end*cast(avg(11) AS integer) when max(t1.f) then max(c) else count(*) end from t1)+d)} +} {13} +do_test randexpr-2.3 { + db eval {SELECT coalesce((select 11 from t1 where 19 in (t1.b,+11,coalesce((select max((abs(17)/abs(t1.f))) from t1 where ((abs(t1.f)/abs(t1.b)) in (select case (min(t1.a & d*d)+(abs(count(*)-count(*)+ -count(*)*max( -t1.c))-max(f))) when -count(distinct 19) then ((count(*))) else max(13) end from t1 union select count(distinct b) from t1)) or 19 in (t1.a,t1.c,17)),17) & 17)),13) FROM t1 WHERE NOT (not not c=a-+(select case ~case -~+count(distinct (select count(distinct t1.a)*max(13) from t1))+max( -19*f)*max(f)*max(f)* -count(distinct d)-(count(distinct 11)) | max(t1.f)*count(*) when count(distinct b) then count(distinct t1.b) else -min(t1.f) end*cast(avg(11) AS integer) when max(t1.f) then max(c) else count(*) end from t1)+d)} +} {13} +do_test randexpr-2.4 { + db eval {SELECT t1.c*19-t1.f*19+coalesce((select 17 from t1 where e in (f,case (select cast(avg(t1.a) AS integer) from t1)-t1.d when coalesce((select +case when not exists(select 1 from t1 where 17<>t1.f and ((a))=a) and t1.b between f and 13),t1.a))+case abs(+(max(19))) | count(distinct t1.e) | count(distinct 19) when count(*) then (max(a)) else count(distinct d) end from t1 union select (count(*)) from t1) and t1.b>=19 then d when t1.b in (select d from t1 union select c from t1) then t1.e else a end} +} {-2900} +do_test randexpr-2.5 { + db eval {SELECT t1.c*19-t1.f*19+coalesce((select 17 from t1 where e in (f,case (select cast(avg(t1.a) AS integer) from t1)-t1.d when coalesce((select +case when not exists(select 1 from t1 where 17<>t1.f and ((a))=a) and t1.b between f and 13),t1.a))+case abs(+(max(19))) | count(distinct t1.e) | count(distinct 19) when count(*) then (max(a)) else count(distinct d) end from t1 union select (count(*)) from t1) and t1.b>=19 then d when t1.b in (select d from t1 union select c from t1) then t1.e else a end)} +} {} +do_test randexpr-2.6 { + db eval {SELECT case when case when not exists(select 1 from t1 where e not in (~t1.d,+case when t1.cd) then 17 else t1.e end in (a,t1.e,17) or (not exists(select 1 from t1 where a in (f,t1.c,t1.a))) then 11 else 13 end FROM t1 WHERE t1.bd) then 17 else t1.e end in (a,t1.e,17) or (not exists(select 1 from t1 where a in (f,t1.c,t1.a))) then 11 else 13 end FROM t1 WHERE NOT (t1.bd) then 17 else t1.e end in (a,t1.e,17) or (not exists(select 1 from t1 where a in (f,t1.c,t1.a))) then 11 else 13 end FROM t1 WHERE t1.bb), -11) | f+t1.f not in (((c)),b,13))),f) FROM t1 WHERE case when 19+c>=t1.a then t1.c when not case when not exists(select 1 from t1 where +f | b*b*19+19*13-a | case when t1.e not in (t1.f,t1.c,b) then 11 when 17>t1.c then a else e end<>e) then b when 17=t1.e then b else e end<>t1.b then a else d end-t1.b=(13)} +} {} +do_test randexpr-2.10 { + db eval {SELECT coalesce((select max(11- -19-f-t1.b+a) from t1 where exists(select 1 from t1 where 11-~(d)-c*a*~t1.a-t1.e-t1.e+coalesce((select coalesce((select t1.c from t1 where case (c) when d then e else 11 end=t1.f),t1.d) from t1 where (t1.d)>b), -11) | f+t1.f not in (((c)),b,13))),f) FROM t1 WHERE NOT (case when 19+c>=t1.a then t1.c when not case when not exists(select 1 from t1 where +f | b*b*19+19*13-a | case when t1.e not in (t1.f,t1.c,b) then 11 when 17>t1.c then a else e end<>e) then b when 17=t1.e then b else e end<>t1.b then a else d end-t1.b=(13))} +} {-670} +do_test randexpr-2.11 { + db eval {SELECT coalesce((select max(11- -19-f-t1.b+a) from t1 where exists(select 1 from t1 where 11-~(d)-c*a*~t1.a-t1.e-t1.e+coalesce((select coalesce((select t1.c from t1 where case (c) when d then e else 11 end=t1.f),t1.d) from t1 where (t1.d)>b), -11) & f+t1.f not in (((c)),b,13))),f) FROM t1 WHERE NOT (case when 19+c>=t1.a then t1.c when not case when not exists(select 1 from t1 where +f | b*b*19+19*13-a | case when t1.e not in (t1.f,t1.c,b) then 11 when 17>t1.c then a else e end<>e) then b when 17=t1.e then b else e end<>t1.b then a else d end-t1.b=(13))} +} {-670} +do_test randexpr-2.12 { + db eval {SELECT (abs(17)/abs(~case when (abs(t1.c* -(abs(case b | coalesce((select max(17*e*case when 11 in (select t1.b from t1 union select t1.c from t1) then 19 when d between f and t1.e then t1.e else t1.e end | b) from t1 where (13 not in (11,t1.d,e))),e)*a*d when 11 then e else d end*17)/abs(19)))/abs(t1.e))<>e then t1.b else t1.d end*(19))) FROM t1 WHERE exists(select 1 from t1 where t1.d+11 in (case t1.b++c when +a*(+case (select count(*) from t1) when 19 then t1.c else a end) then t1.a else case when (t1.b> -d) and not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs( -f*a+c*11))<>a)) then 13 else 19 end end,17,a)) or c=t1.d} +} {} +do_test randexpr-2.13 { + db eval {SELECT (abs(17)/abs(~case when (abs(t1.c* -(abs(case b | coalesce((select max(17*e*case when 11 in (select t1.b from t1 union select t1.c from t1) then 19 when d between f and t1.e then t1.e else t1.e end | b) from t1 where (13 not in (11,t1.d,e))),e)*a*d when 11 then e else d end*17)/abs(19)))/abs(t1.e))<>e then t1.b else t1.d end*(19))) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d+11 in (case t1.b++c when +a*(+case (select count(*) from t1) when 19 then t1.c else a end) then t1.a else case when (t1.b> -d) and not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs( -f*a+c*11))<>a)) then 13 else 19 end end,17,a)) or c=t1.d)} +} {0} +do_test randexpr-2.14 { + db eval {SELECT (abs(17)/abs(~case when (abs(t1.c* -(abs(case b & coalesce((select max(17*e*case when 11 in (select t1.b from t1 union select t1.c from t1) then 19 when d between f and t1.e then t1.e else t1.e end & b) from t1 where (13 not in (11,t1.d,e))),e)*a*d when 11 then e else d end*17)/abs(19)))/abs(t1.e))<>e then t1.b else t1.d end*(19))) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d+11 in (case t1.b++c when +a*(+case (select count(*) from t1) when 19 then t1.c else a end) then t1.a else case when (t1.b> -d) and not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs( -f*a+c*11))<>a)) then 13 else 19 end end,17,a)) or c=t1.d)} +} {0} +do_test randexpr-2.15 { + db eval {SELECT coalesce((select t1.c from t1 where e not between 19 and b*d or not exists(select 1 from t1 where t1.a not in (case when d not between b+~(t1.d)-case when ((t1.f<=t1.e) and -11e),17))/abs( - -17)) then 17 else t1.d end-t1.b-d) | -f,c)) then 11-t1.f when ( -1313 or t1.e in (select (count(*)) from t1 union select cast(avg(t1.e) AS integer) from t1) or 19>17 and 13 not between 19 and 17 then (t1.f) when not t1.b<>t1.f or d<>b then t1.e else a end and c} +} {} +do_test randexpr-2.20 { + db eval {SELECT case when (a not in (t1.e,(+case when t1.b<=(abs(coalesce((select max(a+(select count(distinct (select max(((abs( -t1.d)/abs(a))) | t1.c)*min(t1.e) from t1)) from t1)) from t1 where +t1.f>e),17))/abs( - -17)) then 17 else t1.d end-t1.b-d) | -f,c)) then 11-t1.f when ( -1313 or t1.e in (select (count(*)) from t1 union select cast(avg(t1.e) AS integer) from t1) or 19>17 and 13 not between 19 and 17 then (t1.f) when not t1.b<>t1.f or d<>b then t1.e else a end and c)} +} {-589} +do_test randexpr-2.21 { + db eval {SELECT case when (a not in (t1.e,(+case when t1.b<=(abs(coalesce((select max(a+(select count(distinct (select max(((abs( -t1.d)/abs(a))) & t1.c)*min(t1.e) from t1)) from t1)) from t1 where +t1.f>e),17))/abs( - -17)) then 17 else t1.d end-t1.b-d) & -f,c)) then 11-t1.f when ( -1313 or t1.e in (select (count(*)) from t1 union select cast(avg(t1.e) AS integer) from t1) or 19>17 and 13 not between 19 and 17 then (t1.f) when not t1.b<>t1.f or d<>b then t1.e else a end and c)} +} {-589} +do_test randexpr-2.22 { + db eval {SELECT t1.a | case when e in (select (13) from t1 union select d from t1) then (17) when c*~case (17) when coalesce((select max(case when case when 19 in (13,t1.f,11) then t1.b else t1.b end | 11>t1.a then 11 else t1.b end-b) from t1 where (13 not in (a,19,b)) and t1.a not between -11 and t1.f),f) then e else t1.c end | a in (select 11 from t1 union select t1.d from t1) then 17 else t1.a end | f FROM t1 WHERE coalesce((select t1.a*t1.a from t1 where ~ -(abs((select abs(count(*))-count(distinct t1.d*11) from t1)*+b)/abs(~t1.c))+c not in (coalesce((select ~13*t1.a from t1 where f+(abs(d* -t1.f)/abs(t1.c))<=t1.b or not t1.a<=t1.c),t1.c),e,(t1.e))),(a))+11<>11} +} {636} +do_test randexpr-2.23 { + db eval {SELECT t1.a | case when e in (select (13) from t1 union select d from t1) then (17) when c*~case (17) when coalesce((select max(case when case when 19 in (13,t1.f,11) then t1.b else t1.b end | 11>t1.a then 11 else t1.b end-b) from t1 where (13 not in (a,19,b)) and t1.a not between -11 and t1.f),f) then e else t1.c end | a in (select 11 from t1 union select t1.d from t1) then 17 else t1.a end | f FROM t1 WHERE NOT (coalesce((select t1.a*t1.a from t1 where ~ -(abs((select abs(count(*))-count(distinct t1.d*11) from t1)*+b)/abs(~t1.c))+c not in (coalesce((select ~13*t1.a from t1 where f+(abs(d* -t1.f)/abs(t1.c))<=t1.b or not t1.a<=t1.c),t1.c),e,(t1.e))),(a))+11<>11)} +} {} +do_test randexpr-2.24 { + db eval {SELECT t1.a & case when e in (select (13) from t1 union select d from t1) then (17) when c*~case (17) when coalesce((select max(case when case when 19 in (13,t1.f,11) then t1.b else t1.b end & 11>t1.a then 11 else t1.b end-b) from t1 where (13 not in (a,19,b)) and t1.a not between -11 and t1.f),f) then e else t1.c end & a in (select 11 from t1 union select t1.d from t1) then 17 else t1.a end & f FROM t1 WHERE coalesce((select t1.a*t1.a from t1 where ~ -(abs((select abs(count(*))-count(distinct t1.d*11) from t1)*+b)/abs(~t1.c))+c not in (coalesce((select ~13*t1.a from t1 where f+(abs(d* -t1.f)/abs(t1.c))<=t1.b or not t1.a<=t1.c),t1.c),e,(t1.e))),(a))+11<>11} +} {64} +do_test randexpr-2.25 { + db eval {SELECT c*coalesce((select ~19-e from t1 where not exists(select 1 from t1 where case when t1.b<>(d) then case when exists(select 1 from t1 where not exists(select 1 from t1 where case t1.e when e*(11) then 13 else 11 end in (select t1.a from t1 union select 13 from t1))) then coalesce((select case when f in (select t1.c from t1 union select (t1.b) from t1) then f else a end from t1 where t1.f not between 17 and f), -f) else 11 end else (a) end*d not in (e,t1.c,t1.e))),t1.e)-a FROM t1 WHERE 19+(select cast(avg((abs(t1.d)/abs(coalesce((select max(+b-(t1.e+b+ -c)*19) from t1 where 11 not between t1.b and f), -17)))*(11)) AS integer) from t1)*f in (select count(*) from t1 union select case max(t1.d)-( -min(t1.d)*(+max(e))) when max(t1.a) then cast(avg(t1.d) AS integer)-(count(distinct t1.f))-( -cast(avg(f) AS integer)) else max(t1.e) end from t1)} +} {} +do_test randexpr-2.26 { + db eval {SELECT c*coalesce((select ~19-e from t1 where not exists(select 1 from t1 where case when t1.b<>(d) then case when exists(select 1 from t1 where not exists(select 1 from t1 where case t1.e when e*(11) then 13 else 11 end in (select t1.a from t1 union select 13 from t1))) then coalesce((select case when f in (select t1.c from t1 union select (t1.b) from t1) then f else a end from t1 where t1.f not between 17 and f), -f) else 11 end else (a) end*d not in (e,t1.c,t1.e))),t1.e)-a FROM t1 WHERE NOT (19+(select cast(avg((abs(t1.d)/abs(coalesce((select max(+b-(t1.e+b+ -c)*19) from t1 where 11 not between t1.b and f), -17)))*(11)) AS integer) from t1)*f in (select count(*) from t1 union select case max(t1.d)-( -min(t1.d)*(+max(e))) when max(t1.a) then cast(avg(t1.d) AS integer)-(count(distinct t1.f))-( -cast(avg(f) AS integer)) else max(t1.e) end from t1))} +} {149900} +do_test randexpr-2.27 { + db eval {SELECT (abs((select (case abs(min(t1.f)) | count(distinct e) when (~+count(*)+max(e)++abs(cast(avg(~19) AS integer))) then +cast(avg(c) AS integer) else ~ -max(+t1.b)+~max(19)*count(distinct a)*min(17) | max(t1.d) end) from t1))/abs(~c+(select -(count(distinct t1.e)) from t1)-11+t1.e)) FROM t1 WHERE 11>=t1.f} +} {} +do_test randexpr-2.28 { + db eval {SELECT (abs((select (case abs(min(t1.f)) | count(distinct e) when (~+count(*)+max(e)++abs(cast(avg(~19) AS integer))) then +cast(avg(c) AS integer) else ~ -max(+t1.b)+~max(19)*count(distinct a)*min(17) | max(t1.d) end) from t1))/abs(~c+(select -(count(distinct t1.e)) from t1)-11+t1.e)) FROM t1 WHERE NOT (11>=t1.f)} +} {0} +do_test randexpr-2.29 { + db eval {SELECT (abs((select (case abs(min(t1.f)) & count(distinct e) when (~+count(*)+max(e)++abs(cast(avg(~19) AS integer))) then +cast(avg(c) AS integer) else ~ -max(+t1.b)+~max(19)*count(distinct a)*min(17) & max(t1.d) end) from t1))/abs(~c+(select -(count(distinct t1.e)) from t1)-11+t1.e)) FROM t1 WHERE NOT (11>=t1.f)} +} {1} +do_test randexpr-2.30 { + db eval {SELECT (select +count(distinct case when 11=a or e<+t1.f+t1.c and not exists(select 1 from t1 where not t1.a-t1.b=~a and f<=coalesce((select max((e)) from t1 where +t1.f>=b),t1.d)*13) and t1.c>t1.e and t1.a<17 then f when a=b),t1.d)*13) and t1.c>t1.e and t1.a<17 then f when a(c)),b)*t1.b-t1.b) then d else t1.e end | f* -13-c) from t1) from t1 where not ~aa} +} {} +do_test randexpr-2.33 { + db eval {SELECT coalesce((select (select max(t1.a)*(max(a))*max(t1.f*~11*case when b not in ((select min(19) from t1),b,coalesce((select max((t1.f)) from t1 where t1.c in (c,t1.b,(t1.f)) or t1.a<>(c)),b)*t1.b-t1.b) then d else t1.e end | f* -13-c) from t1) from t1 where not ~aa)} +} {581} +do_test randexpr-2.34 { + db eval {SELECT coalesce((select (select max(t1.a)*(max(a))*max(t1.f*~11*case when b not in ((select min(19) from t1),b,coalesce((select max((t1.f)) from t1 where t1.c in (c,t1.b,(t1.f)) or t1.a<>(c)),b)*t1.b-t1.b) then d else t1.e end & f* -13-c) from t1) from t1 where not ~aa)} +} {581} +do_test randexpr-2.35 { + db eval {SELECT case when t1.d not in (t1.d,coalesce((select max(11) from t1 where f not between 13 and c-coalesce((select max(d) from t1 where 19 not in ((t1.f),f,11)),t1.d)*t1.e | a),13), -(t1.e)) then t1.b when t1.f=t1.a and exists(select 1 from t1 where b in (select c from t1 union select 11 from t1) and t1.c=b and not -d in (t1.d,t1.d,t1.b) and d between 11 and c) or d<=17 or a not in (e,19,(t1.b)) then 17 else 11 end FROM t1 WHERE a<>f+f} +} {17} +do_test randexpr-2.36 { + db eval {SELECT case when t1.d not in (t1.d,coalesce((select max(11) from t1 where f not between 13 and c-coalesce((select max(d) from t1 where 19 not in ((t1.f),f,11)),t1.d)*t1.e | a),13), -(t1.e)) then t1.b when t1.f=t1.a and exists(select 1 from t1 where b in (select c from t1 union select 11 from t1) and t1.c=b and not -d in (t1.d,t1.d,t1.b) and d between 11 and c) or d<=17 or a not in (e,19,(t1.b)) then 17 else 11 end FROM t1 WHERE NOT (a<>f+f)} +} {} +do_test randexpr-2.37 { + db eval {SELECT case when t1.d not in (t1.d,coalesce((select max(11) from t1 where f not between 13 and c-coalesce((select max(d) from t1 where 19 not in ((t1.f),f,11)),t1.d)*t1.e & a),13), -(t1.e)) then t1.b when t1.f=t1.a and exists(select 1 from t1 where b in (select c from t1 union select 11 from t1) and t1.c=b and not -d in (t1.d,t1.d,t1.b) and d between 11 and c) or d<=17 or a not in (e,19,(t1.b)) then 17 else 11 end FROM t1 WHERE a<>f+f} +} {17} +do_test randexpr-2.38 { + db eval {SELECT case 13 when coalesce((select t1.a*d+++b | b+(abs(t1.e)/abs(c))+(select count(*) from t1) from t1 where not exists(select 1 from t1 where 17 in (select d from t1 union select t1.f from t1))),t1.b) then ~t1.c-(select case min(case when 17 not in (19,19,t1.c) then c when 13 between (19) and t1.e then e else 19 end-19) when cast(avg( -11) AS integer) then max(t1.c)* -min(t1.d) else (count(distinct t1.f)) end from t1) | +t1.f else t1.c end FROM t1 WHERE coalesce((select max(t1.c) from t1 where (abs(t1.b)/abs(a))>=(e)),+ -case when (11<17) then t1.a when t1.a*e=19* -11 and not exists(select 1 from t1 where -t1.d not between coalesce((select a from t1 where -t1.c>t1.e), -19) and t1.d and not exists(select 1 from t1 where (t1.e) in (select d from t1 union select t1.c from t1))) then c else a end*a)-t1.b* -(b) in (e,d,b)} +} {} +do_test randexpr-2.39 { + db eval {SELECT case 13 when coalesce((select t1.a*d+++b | b+(abs(t1.e)/abs(c))+(select count(*) from t1) from t1 where not exists(select 1 from t1 where 17 in (select d from t1 union select t1.f from t1))),t1.b) then ~t1.c-(select case min(case when 17 not in (19,19,t1.c) then c when 13 between (19) and t1.e then e else 19 end-19) when cast(avg( -11) AS integer) then max(t1.c)* -min(t1.d) else (count(distinct t1.f)) end from t1) | +t1.f else t1.c end FROM t1 WHERE NOT (coalesce((select max(t1.c) from t1 where (abs(t1.b)/abs(a))>=(e)),+ -case when (11<17) then t1.a when t1.a*e=19* -11 and not exists(select 1 from t1 where -t1.d not between coalesce((select a from t1 where -t1.c>t1.e), -19) and t1.d and not exists(select 1 from t1 where (t1.e) in (select d from t1 union select t1.c from t1))) then c else a end*a)-t1.b* -(b) in (e,d,b))} +} {300} +do_test randexpr-2.40 { + db eval {SELECT case 13 when coalesce((select t1.a*d+++b & b+(abs(t1.e)/abs(c))+(select count(*) from t1) from t1 where not exists(select 1 from t1 where 17 in (select d from t1 union select t1.f from t1))),t1.b) then ~t1.c-(select case min(case when 17 not in (19,19,t1.c) then c when 13 between (19) and t1.e then e else 19 end-19) when cast(avg( -11) AS integer) then max(t1.c)* -min(t1.d) else (count(distinct t1.f)) end from t1) & +t1.f else t1.c end FROM t1 WHERE NOT (coalesce((select max(t1.c) from t1 where (abs(t1.b)/abs(a))>=(e)),+ -case when (11<17) then t1.a when t1.a*e=19* -11 and not exists(select 1 from t1 where -t1.d not between coalesce((select a from t1 where -t1.c>t1.e), -19) and t1.d and not exists(select 1 from t1 where (t1.e) in (select d from t1 union select t1.c from t1))) then c else a end*a)-t1.b* -(b) in (e,d,b))} +} {300} +do_test randexpr-2.41 { + db eval {SELECT case when not exists(select 1 from t1 where ( -case when b in ((11),coalesce((select f from t1 where (not exists(select 1 from t1 where coalesce((select (t1.a) from t1 where e<=a),11) in (select t1.f from t1 union select 13 from t1)) or t1.a>d)),t1.a),t1.e) or not not exists(select 1 from t1 where (t1.f<=(t1.a))) then e*t1.a else t1.c end)<=d and not (t1.e)>=t1.e) then coalesce((select max( -t1.e) from t1 where t1.d between t1.b and t1.c),t1.d) else t1.c end+13*13 FROM t1 WHERE t1.b=t1.f | 19+coalesce((select max(a) from t1 where case t1.e when case when (11<=11 | t1.f and b>=b or t1.f<=a) then case when c between t1.e and b then e else +t1.f end else -t1.c end then t1.b else 13 end*13 between t1.f and c and exists(select 1 from t1 where (b not between 11 and a)) and f>=t1.b), -t1.b)-c} +} {} +do_test randexpr-2.42 { + db eval {SELECT case when not exists(select 1 from t1 where ( -case when b in ((11),coalesce((select f from t1 where (not exists(select 1 from t1 where coalesce((select (t1.a) from t1 where e<=a),11) in (select t1.f from t1 union select 13 from t1)) or t1.a>d)),t1.a),t1.e) or not not exists(select 1 from t1 where (t1.f<=(t1.a))) then e*t1.a else t1.c end)<=d and not (t1.e)>=t1.e) then coalesce((select max( -t1.e) from t1 where t1.d between t1.b and t1.c),t1.d) else t1.c end+13*13 FROM t1 WHERE NOT (t1.b=t1.f | 19+coalesce((select max(a) from t1 where case t1.e when case when (11<=11 | t1.f and b>=b or t1.f<=a) then case when c between t1.e and b then e else +t1.f end else -t1.c end then t1.b else 13 end*13 between t1.f and c and exists(select 1 from t1 where (b not between 11 and a)) and f>=t1.b), -t1.b)-c)} +} {569} +do_test randexpr-2.43 { + db eval {SELECT coalesce((select c from t1 where t1.a=case when a=t1.b+~(select case cast(avg( -b*13) AS integer) when max(f*13* -c) then (cast(avg(t1.d) AS integer)) else count(distinct t1.e*c) end from t1) then t1.d | t1.a else case when t1.a-b not between e and -t1.c* -13 then 19 else d end end),d) | t1.d FROM t1 WHERE +13 in (f,t1.f+t1.f, -coalesce((select max(t1.f) from t1 where (t1.a-13)<=(case (select count(*) from t1) when 13 then -+t1.e | -(coalesce((select max(~coalesce((select ( -13) from t1 where -c<(11) or 11 between a and t1.d),13)*t1.d) from t1 where d not between b and 13),19))*t1.a else 13 end-b-c)),t1.e)-19)} +} {} +do_test randexpr-2.44 { + db eval {SELECT coalesce((select c from t1 where t1.a=case when a=t1.b+~(select case cast(avg( -b*13) AS integer) when max(f*13* -c) then (cast(avg(t1.d) AS integer)) else count(distinct t1.e*c) end from t1) then t1.d | t1.a else case when t1.a-b not between e and -t1.c* -13 then 19 else d end end),d) | t1.d FROM t1 WHERE NOT (+13 in (f,t1.f+t1.f, -coalesce((select max(t1.f) from t1 where (t1.a-13)<=(case (select count(*) from t1) when 13 then -+t1.e | -(coalesce((select max(~coalesce((select ( -13) from t1 where -c<(11) or 11 between a and t1.d),13)*t1.d) from t1 where d not between b and 13),19))*t1.a else 13 end-b-c)),t1.e)-19))} +} {400} +do_test randexpr-2.45 { + db eval {SELECT coalesce((select c from t1 where t1.a=case when a=t1.b+~(select case cast(avg( -b*13) AS integer) when max(f*13* -c) then (cast(avg(t1.d) AS integer)) else count(distinct t1.e*c) end from t1) then t1.d & t1.a else case when t1.a-b not between e and -t1.c* -13 then 19 else d end end),d) & t1.d FROM t1 WHERE NOT (+13 in (f,t1.f+t1.f, -coalesce((select max(t1.f) from t1 where (t1.a-13)<=(case (select count(*) from t1) when 13 then -+t1.e | -(coalesce((select max(~coalesce((select ( -13) from t1 where -c<(11) or 11 between a and t1.d),13)*t1.d) from t1 where d not between b and 13),19))*t1.a else 13 end-b-c)),t1.e)-19))} +} {400} +do_test randexpr-2.46 { + db eval {SELECT case ~11-13 when 11-d-case when t1.f*+a-t1.a-t1.f=t1.a then a when t1.f between 19-t1.a+coalesce((select a from t1 where e in (select case -max(t1.c) when count(*) then max(t1.d) else -(cast(avg((t1.e)) AS integer)) end from t1 union select (max(t1.b)) from t1)), -b) and e or ((11=t1.d then t1.b else a end+13+(t1.c) then a else -d end FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where (not +t1.b-~a*(d*t1.e | + -coalesce((select t1.c from t1 where t1.b*case t1.b when f then -a*b else e end<>a+t1.a),17))+e*t1.e*11 | t1.a not between 13 and -t1.a and b between d and -f)))} +} {-400} +do_test randexpr-2.47 { + db eval {SELECT case ~11-13 when 11-d-case when t1.f*+a-t1.a-t1.f=t1.a then a when t1.f between 19-t1.a+coalesce((select a from t1 where e in (select case -max(t1.c) when count(*) then max(t1.d) else -(cast(avg((t1.e)) AS integer)) end from t1 union select (max(t1.b)) from t1)), -b) and e or ((11=t1.d then t1.b else a end+13+(t1.c) then a else -d end FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where (not +t1.b-~a*(d*t1.e | + -coalesce((select t1.c from t1 where t1.b*case t1.b when f then -a*b else e end<>a+t1.a),17))+e*t1.e*11 | t1.a not between 13 and -t1.a and b between d and -f))))} +} {} +do_test randexpr-2.48 { + db eval {SELECT 11++(case 19 when t1.c-19-coalesce((select t1.b from t1 where e*19-t1.e<=+case when c in (select 19 | 17 from t1 union select 11 from t1) then (abs(a)/abs(19)) when a*t1.d>19 or (11) not in (b,t1.a,t1.a) then b else b end-11),f) then 13 else 11 end-t1.e*a) FROM t1 WHERE f in (17,t1.f | coalesce((select max(t1.e) from t1 where not 17 in (select f from t1 union select +17 from t1)),b+coalesce((select max(b) from t1 where 19 in (select case min(t1.d) when (count(*)) then min(d) else -min(d) end from t1 union select max(d) from t1)),f)*f-17+19),b) or d<=f or t1.f>=11 or t1.b<=11 or t1.c<=11 or t1.b<=b} +} {-49978} +do_test randexpr-2.49 { + db eval {SELECT 11++(case 19 when t1.c-19-coalesce((select t1.b from t1 where e*19-t1.e<=+case when c in (select 19 | 17 from t1 union select 11 from t1) then (abs(a)/abs(19)) when a*t1.d>19 or (11) not in (b,t1.a,t1.a) then b else b end-11),f) then 13 else 11 end-t1.e*a) FROM t1 WHERE NOT (f in (17,t1.f | coalesce((select max(t1.e) from t1 where not 17 in (select f from t1 union select +17 from t1)),b+coalesce((select max(b) from t1 where 19 in (select case min(t1.d) when (count(*)) then min(d) else -min(d) end from t1 union select max(d) from t1)),f)*f-17+19),b) or d<=f or t1.f>=11 or t1.b<=11 or t1.c<=11 or t1.b<=b)} +} {} +do_test randexpr-2.50 { + db eval {SELECT 11++(case 19 when t1.c-19-coalesce((select t1.b from t1 where e*19-t1.e<=+case when c in (select 19 & 17 from t1 union select 11 from t1) then (abs(a)/abs(19)) when a*t1.d>19 or (11) not in (b,t1.a,t1.a) then b else b end-11),f) then 13 else 11 end-t1.e*a) FROM t1 WHERE f in (17,t1.f | coalesce((select max(t1.e) from t1 where not 17 in (select f from t1 union select +17 from t1)),b+coalesce((select max(b) from t1 where 19 in (select case min(t1.d) when (count(*)) then min(d) else -min(d) end from t1 union select max(d) from t1)),f)*f-17+19),b) or d<=f or t1.f>=11 or t1.b<=11 or t1.c<=11 or t1.b<=b} +} {-49978} +do_test randexpr-2.51 { + db eval {SELECT -c-coalesce((select max(t1.a) from t1 where (a>17-t1.a) and (select abs(min(t1.a))*case abs(case (((min((t1.c))))+min(a)) when count(distinct f) then min(11) else count(distinct b) end) when min(t1.f) then (count(distinct t1.b)) else -count(*) end from t1)<>case d when +(select ((min(t1.a))) from t1)-(abs(c)/abs(f)) then b else 17 end+t1.c),coalesce((select t1.d from t1 where d>19),t1.a)) FROM t1 WHERE b+(coalesce((select max(a) from t1 where exists(select 1 from t1 where t1.b<=c-(select ~~max((abs(e)/abs(13 | (t1.e)-c-19))) from t1) or d in (select t1.b from t1 union select d from t1)) or 13 in (select cast(avg(19) AS integer) from t1 union select ( -cast(avg(19) AS integer) | count(*)*min(19)) from t1) or 19<=11),t1.c))-t1.d-c>f} +} {} +do_test randexpr-2.52 { + db eval {SELECT -c-coalesce((select max(t1.a) from t1 where (a>17-t1.a) and (select abs(min(t1.a))*case abs(case (((min((t1.c))))+min(a)) when count(distinct f) then min(11) else count(distinct b) end) when min(t1.f) then (count(distinct t1.b)) else -count(*) end from t1)<>case d when +(select ((min(t1.a))) from t1)-(abs(c)/abs(f)) then b else 17 end+t1.c),coalesce((select t1.d from t1 where d>19),t1.a)) FROM t1 WHERE NOT (b+(coalesce((select max(a) from t1 where exists(select 1 from t1 where t1.b<=c-(select ~~max((abs(e)/abs(13 | (t1.e)-c-19))) from t1) or d in (select t1.b from t1 union select d from t1)) or 13 in (select cast(avg(19) AS integer) from t1 union select ( -cast(avg(19) AS integer) | count(*)*min(19)) from t1) or 19<=11),t1.c))-t1.d-c>f)} +} {-400} +do_test randexpr-2.53 { + db eval {SELECT case when t1.b+coalesce((select max(a) from t1 where exists(select 1 from t1 where not not t1.d>19)),13) | case when f in (select a from t1 union select case when (a)<>t1.c then c when not exists(select 1 from t1 where t1.c not between 17 and -(t1.d)) then f else (11) end from t1) then t1.c when (not exists(select 1 from t1 where 17 not between t1.f and a)) and d=b then t1.c else d end<=19 and (t1.c<>c and (13) not between t1.d and t1.c) and a>= -b or 11>13 and c<>13 then -f else d end FROM t1 WHERE (case when (17 not in (f*11,+coalesce((select max(b-b) from t1 where t1.c+f not between 11 and t1.d),13),c)) or (t1.e in (select ~min(t1.f) from t1 union select ~count(*) from t1) and exists(select 1 from t1 where (not f>=19 and 17 not between a and t1.e)) or (e) not in (e,d,13) or t1.d>=f) then e when 17 between t1.c and 13 then case when 11<>19 then t1.d else t1.a end else b end in (select -t1.a from t1 union select a from t1))} +} {} +do_test randexpr-2.54 { + db eval {SELECT case when t1.b+coalesce((select max(a) from t1 where exists(select 1 from t1 where not not t1.d>19)),13) | case when f in (select a from t1 union select case when (a)<>t1.c then c when not exists(select 1 from t1 where t1.c not between 17 and -(t1.d)) then f else (11) end from t1) then t1.c when (not exists(select 1 from t1 where 17 not between t1.f and a)) and d=b then t1.c else d end<=19 and (t1.c<>c and (13) not between t1.d and t1.c) and a>= -b or 11>13 and c<>13 then -f else d end FROM t1 WHERE NOT ((case when (17 not in (f*11,+coalesce((select max(b-b) from t1 where t1.c+f not between 11 and t1.d),13),c)) or (t1.e in (select ~min(t1.f) from t1 union select ~count(*) from t1) and exists(select 1 from t1 where (not f>=19 and 17 not between a and t1.e)) or (e) not in (e,d,13) or t1.d>=f) then e when 17 between t1.c and 13 then case when 11<>19 then t1.d else t1.a end else b end in (select -t1.a from t1 union select a from t1)))} +} {400} +do_test randexpr-2.55 { + db eval {SELECT case when t1.b+coalesce((select max(a) from t1 where exists(select 1 from t1 where not not t1.d>19)),13) & case when f in (select a from t1 union select case when (a)<>t1.c then c when not exists(select 1 from t1 where t1.c not between 17 and -(t1.d)) then f else (11) end from t1) then t1.c when (not exists(select 1 from t1 where 17 not between t1.f and a)) and d=b then t1.c else d end<=19 and (t1.c<>c and (13) not between t1.d and t1.c) and a>= -b or 11>13 and c<>13 then -f else d end FROM t1 WHERE NOT ((case when (17 not in (f*11,+coalesce((select max(b-b) from t1 where t1.c+f not between 11 and t1.d),13),c)) or (t1.e in (select ~min(t1.f) from t1 union select ~count(*) from t1) and exists(select 1 from t1 where (not f>=19 and 17 not between a and t1.e)) or (e) not in (e,d,13) or t1.d>=f) then e when 17 between t1.c and 13 then case when 11<>19 then t1.d else t1.a end else b end in (select -t1.a from t1 union select a from t1)))} +} {400} +do_test randexpr-2.56 { + db eval {SELECT t1.e+case when d not between f and case when a in (select t1.c from t1 union select t1.e from t1) or coalesce((select 19 from t1 where 17<=t1.d or 19*t1.f*t1.b<>t1.d | t1.d | t1.a),t1.b)*case when (t1.a) in (t1.d,t1.a,a) then -c when 17<13 then t1.f else 17 end-t1.f*e not in (19,t1.d,17) then 19 else t1.e end then -b else t1.b end FROM t1 WHERE (coalesce((select t1.d-coalesce((select max(coalesce((select max(c+13) from t1 where ~13*t1.b in (select abs(abs(abs((cast(avg( -e) AS integer)))))- -count(distinct (13))*max(13) from t1 union select count(distinct 19) from t1)), -t1.f)) from t1 where exists(select 1 from t1 where 17 in (t1.b,13,b))),b)+d+t1.a from t1 where d not in (13,t1.b,b)),17) not between 11 and e or not 17 between d and d)} +} {300} +do_test randexpr-2.57 { + db eval {SELECT t1.e+case when d not between f and case when a in (select t1.c from t1 union select t1.e from t1) or coalesce((select 19 from t1 where 17<=t1.d or 19*t1.f*t1.b<>t1.d | t1.d | t1.a),t1.b)*case when (t1.a) in (t1.d,t1.a,a) then -c when 17<13 then t1.f else 17 end-t1.f*e not in (19,t1.d,17) then 19 else t1.e end then -b else t1.b end FROM t1 WHERE NOT ((coalesce((select t1.d-coalesce((select max(coalesce((select max(c+13) from t1 where ~13*t1.b in (select abs(abs(abs((cast(avg( -e) AS integer)))))- -count(distinct (13))*max(13) from t1 union select count(distinct 19) from t1)), -t1.f)) from t1 where exists(select 1 from t1 where 17 in (t1.b,13,b))),b)+d+t1.a from t1 where d not in (13,t1.b,b)),17) not between 11 and e or not 17 between d and d))} +} {} +do_test randexpr-2.58 { + db eval {SELECT t1.e+case when d not between f and case when a in (select t1.c from t1 union select t1.e from t1) or coalesce((select 19 from t1 where 17<=t1.d or 19*t1.f*t1.b<>t1.d & t1.d & t1.a),t1.b)*case when (t1.a) in (t1.d,t1.a,a) then -c when 17<13 then t1.f else 17 end-t1.f*e not in (19,t1.d,17) then 19 else t1.e end then -b else t1.b end FROM t1 WHERE (coalesce((select t1.d-coalesce((select max(coalesce((select max(c+13) from t1 where ~13*t1.b in (select abs(abs(abs((cast(avg( -e) AS integer)))))- -count(distinct (13))*max(13) from t1 union select count(distinct 19) from t1)), -t1.f)) from t1 where exists(select 1 from t1 where 17 in (t1.b,13,b))),b)+d+t1.a from t1 where d not in (13,t1.b,b)),17) not between 11 and e or not 17 between d and d)} +} {300} +do_test randexpr-2.59 { + db eval {SELECT coalesce((select max(t1.f*case when not exists(select 1 from t1 where exists(select 1 from t1 where (select count(distinct 11) from t1) between coalesce((select max(c) from t1 where t1.e=t1.a+17),a) and t1.b) or c not in (t1.e,19,t1.e)) then 13 when exists(select 1 from t1 where t1.a between 19 and -c) then coalesce((select coalesce((select max((( -d))) from t1 where 17 not in (t1.d,e,t1.e)),e) from t1 where c= -f),( -c)) else t1.f end) from t1 where not (11 between a and t1.e)),19) FROM t1 WHERE case c when case when (exists(select 1 from t1 where t1.d<>coalesce((select 13 from t1 where (t1.b>+e)),(17))+coalesce((select 13 from t1 where exists(select 1 from t1 where 13 in (t1.b+c,case when f between t1.f and b then t1.b else f end,(11)))),f)-17-17)) then -c-(c) when 11 in (b,f,(t1.d)) then t1.c else t1.b end then t1.d else 11 end in (select -count(*) from t1 union select count(*) from t1)} +} {} +do_test randexpr-2.60 { + db eval {SELECT coalesce((select max(t1.f*case when not exists(select 1 from t1 where exists(select 1 from t1 where (select count(distinct 11) from t1) between coalesce((select max(c) from t1 where t1.e=t1.a+17),a) and t1.b) or c not in (t1.e,19,t1.e)) then 13 when exists(select 1 from t1 where t1.a between 19 and -c) then coalesce((select coalesce((select max((( -d))) from t1 where 17 not in (t1.d,e,t1.e)),e) from t1 where c= -f),( -c)) else t1.f end) from t1 where not (11 between a and t1.e)),19) FROM t1 WHERE NOT (case c when case when (exists(select 1 from t1 where t1.d<>coalesce((select 13 from t1 where (t1.b>+e)),(17))+coalesce((select 13 from t1 where exists(select 1 from t1 where 13 in (t1.b+c,case when f between t1.f and b then t1.b else f end,(11)))),f)-17-17)) then -c-(c) when 11 in (b,f,(t1.d)) then t1.c else t1.b end then t1.d else 11 end in (select -count(*) from t1 union select count(*) from t1))} +} {360000} +do_test randexpr-2.61 { + db eval {SELECT case when t1.a-coalesce((select t1.b from t1 where (d<=~a)),t1.b+t1.d | 19+13)-t1.a | ~coalesce((select ~17 from t1 where not exists(select 1 from t1 where ~case when 13 in (select +(cast(avg(b) AS integer)) from t1 union select count(*) from t1) then 17 when 11 not in (c,t1.a,t1.a) then e else e end*a not between 11 and c)),t1.c) in (11,t1.a,e) then t1.f when 19 in (select ~count(distinct d) from t1 union select cast(avg(19) AS integer) from t1) then t1.d else 19 end FROM t1 WHERE not exists(select 1 from t1 where (select count(*) from t1)+coalesce((select max(a) from t1 where t1.a between (abs(case when exists(select 1 from t1 where case when t1.e=case when 19 between 11 and e then t1.f else a end then t1.e else t1.b end in (select count(distinct d) | max(11)*abs(case count(*) when max(f) then cast(avg(e) AS integer) else count(distinct t1.e) end) from t1 union select -cast(avg(c) AS integer) from t1)) then (select -min(e) from t1) when (c>e) then t1.d else f end)/abs(b)) and (17)),e) not between t1.a and d)} +} {} +do_test randexpr-2.62 { + db eval {SELECT case when t1.a-coalesce((select t1.b from t1 where (d<=~a)),t1.b+t1.d | 19+13)-t1.a | ~coalesce((select ~17 from t1 where not exists(select 1 from t1 where ~case when 13 in (select +(cast(avg(b) AS integer)) from t1 union select count(*) from t1) then 17 when 11 not in (c,t1.a,t1.a) then e else e end*a not between 11 and c)),t1.c) in (11,t1.a,e) then t1.f when 19 in (select ~count(distinct d) from t1 union select cast(avg(19) AS integer) from t1) then t1.d else 19 end FROM t1 WHERE NOT (not exists(select 1 from t1 where (select count(*) from t1)+coalesce((select max(a) from t1 where t1.a between (abs(case when exists(select 1 from t1 where case when t1.e=case when 19 between 11 and e then t1.f else a end then t1.e else t1.b end in (select count(distinct d) | max(11)*abs(case count(*) when max(f) then cast(avg(e) AS integer) else count(distinct t1.e) end) from t1 union select -cast(avg(c) AS integer) from t1)) then (select -min(e) from t1) when (c>e) then t1.d else f end)/abs(b)) and (17)),e) not between t1.a and d))} +} {400} +do_test randexpr-2.63 { + db eval {SELECT case when t1.a-coalesce((select t1.b from t1 where (d<=~a)),t1.b+t1.d & 19+13)-t1.a & ~coalesce((select ~17 from t1 where not exists(select 1 from t1 where ~case when 13 in (select +(cast(avg(b) AS integer)) from t1 union select count(*) from t1) then 17 when 11 not in (c,t1.a,t1.a) then e else e end*a not between 11 and c)),t1.c) in (11,t1.a,e) then t1.f when 19 in (select ~count(distinct d) from t1 union select cast(avg(19) AS integer) from t1) then t1.d else 19 end FROM t1 WHERE NOT (not exists(select 1 from t1 where (select count(*) from t1)+coalesce((select max(a) from t1 where t1.a between (abs(case when exists(select 1 from t1 where case when t1.e=case when 19 between 11 and e then t1.f else a end then t1.e else t1.b end in (select count(distinct d) | max(11)*abs(case count(*) when max(f) then cast(avg(e) AS integer) else count(distinct t1.e) end) from t1 union select -cast(avg(c) AS integer) from t1)) then (select -min(e) from t1) when (c>e) then t1.d else f end)/abs(b)) and (17)),e) not between t1.a and d))} +} {400} +do_test randexpr-2.64 { + db eval {SELECT case when 11 in (select max(f) from t1 union select min(19++13) | min(t1.c) from t1) and (e in (select t1.d from t1 union select t1.a | 17*case e when coalesce((select max(a) from t1 where b not in (b,f,d) or t1.a<=f),11) then t1.a else t1.b end from t1) and -a not between b and d) then d when -t1.f=b or t1.b between -f and -d then 19 else d end+d FROM t1 WHERE case when (coalesce((select case (select max(t1.b) from t1) when (b* -t1.e+e*e-t1.a) then c else a end from t1 where 17 in (select min(t1.d)-abs(count(*)) from t1 union select count(distinct c) from t1)),t1.d)=(t1.d)) and e in (select -min(t1.b) from t1 union select count(distinct 11) from t1) and a< - -17 then t1.d | 11 else 19 end in (select 17 from t1 union select d from t1)} +} {} +do_test randexpr-2.65 { + db eval {SELECT case when 11 in (select max(f) from t1 union select min(19++13) | min(t1.c) from t1) and (e in (select t1.d from t1 union select t1.a | 17*case e when coalesce((select max(a) from t1 where b not in (b,f,d) or t1.a<=f),11) then t1.a else t1.b end from t1) and -a not between b and d) then d when -t1.f=b or t1.b between -f and -d then 19 else d end+d FROM t1 WHERE NOT (case when (coalesce((select case (select max(t1.b) from t1) when (b* -t1.e+e*e-t1.a) then c else a end from t1 where 17 in (select min(t1.d)-abs(count(*)) from t1 union select count(distinct c) from t1)),t1.d)=(t1.d)) and e in (select -min(t1.b) from t1 union select count(distinct 11) from t1) and a< - -17 then t1.d | 11 else 19 end in (select 17 from t1 union select d from t1))} +} {800} +do_test randexpr-2.66 { + db eval {SELECT case when 11 in (select max(f) from t1 union select min(19++13) & min(t1.c) from t1) and (e in (select t1.d from t1 union select t1.a & 17*case e when coalesce((select max(a) from t1 where b not in (b,f,d) or t1.a<=f),11) then t1.a else t1.b end from t1) and -a not between b and d) then d when -t1.f=b or t1.b between -f and -d then 19 else d end+d FROM t1 WHERE NOT (case when (coalesce((select case (select max(t1.b) from t1) when (b* -t1.e+e*e-t1.a) then c else a end from t1 where 17 in (select min(t1.d)-abs(count(*)) from t1 union select count(distinct c) from t1)),t1.d)=(t1.d)) and e in (select -min(t1.b) from t1 union select count(distinct 11) from t1) and a< - -17 then t1.d | 11 else 19 end in (select 17 from t1 union select d from t1))} +} {800} +do_test randexpr-2.67 { + db eval {SELECT (abs((select min(13) from t1))/abs(coalesce((select t1.e from t1 where coalesce((select t1.f from t1 where -11<=b-t1.c*case when (d)-t1.f+t1.e-13<>t1.b then 11 when exists(select 1 from t1 where t1.d<>((t1.b)) or t1.a not between d and 13) or t1.b<>t1.c then t1.e else -t1.d end+t1.a or t1.c not between f and d),e)<>e), -f))) FROM t1 WHERE t1.c<>(select min((abs(( -19-t1.b*13- -++~t1.f*d-17*19*11))/abs(17))) from t1)} +} {0} +do_test randexpr-2.68 { + db eval {SELECT (abs((select min(13) from t1))/abs(coalesce((select t1.e from t1 where coalesce((select t1.f from t1 where -11<=b-t1.c*case when (d)-t1.f+t1.e-13<>t1.b then 11 when exists(select 1 from t1 where t1.d<>((t1.b)) or t1.a not between d and 13) or t1.b<>t1.c then t1.e else -t1.d end+t1.a or t1.c not between f and d),e)<>e), -f))) FROM t1 WHERE NOT (t1.c<>(select min((abs(( -19-t1.b*13- -++~t1.f*d-17*19*11))/abs(17))) from t1))} +} {} +do_test randexpr-2.69 { + db eval {SELECT case d-case when c< -case when b<=f or coalesce((select t1.e from t1 where 11e then 19 when not exists(select 1 from t1 where not exists(select 1 from t1 where t1.d>=d)) then t1.f else 17 end then e when not exists(select 1 from t1 where d=b) then t1.c else f end when 17 then 19 else t1.f end FROM t1 WHERE coalesce((select max(+t1.d) from t1 where e<>e or not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs(f))++t1.b in (select case abs(cast(avg(e) AS integer)) when cast(avg(17) AS integer) | max(d) | cast(avg(t1.e) AS integer) | min(t1.e) then (cast(avg(19) AS integer)) else cast(avg(c) AS integer) end from t1 union select cast(avg(t1.f) AS integer) from t1))) and t1.a between t1.f and b or not 17<13 or -11= -t1.f or t1.f between c and 19),d)+(t1.d) not between b and e} +} {600} +do_test randexpr-2.70 { + db eval {SELECT case d-case when c< -case when b<=f or coalesce((select t1.e from t1 where 11e then 19 when not exists(select 1 from t1 where not exists(select 1 from t1 where t1.d>=d)) then t1.f else 17 end then e when not exists(select 1 from t1 where d=b) then t1.c else f end when 17 then 19 else t1.f end FROM t1 WHERE NOT (coalesce((select max(+t1.d) from t1 where e<>e or not exists(select 1 from t1 where not exists(select 1 from t1 where (abs(f)/abs(f))++t1.b in (select case abs(cast(avg(e) AS integer)) when cast(avg(17) AS integer) | max(d) | cast(avg(t1.e) AS integer) | min(t1.e) then (cast(avg(19) AS integer)) else cast(avg(c) AS integer) end from t1 union select cast(avg(t1.f) AS integer) from t1))) and t1.a between t1.f and b or not 17<13 or -11= -t1.f or t1.f between c and 19),d)+(t1.d) not between b and e)} +} {} +do_test randexpr-2.71 { + db eval {SELECT case when t1.e in (select abs(max(case a+case when t1.a>=e+ -c then a else t1.b end+t1.a when t1.f then 19 else -19 end)+abs( -count(distinct t1.c))+~(count(distinct t1.b)))-min(b) from t1 union select max(f) from t1) and case t1.e when -t1.c then 19 else b end=t1.e))) or c in (select f from t1 union select 13 from t1) and (b)< -t1.c and f in (select max(13) from t1 union select ~+abs(count(distinct e)*abs(((count(*)))*((max(f))))) from t1)} +} {} +do_test randexpr-2.72 { + db eval {SELECT case when t1.e in (select abs(max(case a+case when t1.a>=e+ -c then a else t1.b end+t1.a when t1.f then 19 else -19 end)+abs( -count(distinct t1.c))+~(count(distinct t1.b)))-min(b) from t1 union select max(f) from t1) and case t1.e when -t1.c then 19 else b end=t1.e))) or c in (select f from t1 union select 13 from t1) and (b)< -t1.c and f in (select max(13) from t1 union select ~+abs(count(distinct e)*abs(((count(*)))*((max(f))))) from t1))} +} {-19} +do_test randexpr-2.73 { + db eval {SELECT c*case when t1.a in (select ~count(*) from t1 union select -count(distinct ~case (abs(11)/abs(b-(coalesce((select 17-t1.a from t1 where not t1.d=t1.d),(abs(11)/abs(a)))))) when case when t1.d between 19 and c and t1.b between 11 and t1.a then 13 else (13) end then (13) else 19 end-19*13+11) from t1) then t1.a when t1.f<=t1.e then f else b end-19-c+f FROM t1 WHERE t1.b>=c+case when exists(select 1 from t1 where a>=+f- -c*e+coalesce((select max(b) from t1 where (b not between (t1.b) and 19) or t1.f<11),d)*f | t1.e+t1.b) then ( -t1.e)-19 when ((t1.a in (select 19 from t1 union select t1.f from t1) or b -17)) then f else f end | d} +} {} +do_test randexpr-2.74 { + db eval {SELECT c*case when t1.a in (select ~count(*) from t1 union select -count(distinct ~case (abs(11)/abs(b-(coalesce((select 17-t1.a from t1 where not t1.d=t1.d),(abs(11)/abs(a)))))) when case when t1.d between 19 and c and t1.b between 11 and t1.a then 13 else (13) end then (13) else 19 end-19*13+11) from t1) then t1.a when t1.f<=t1.e then f else b end-19-c+f FROM t1 WHERE NOT (t1.b>=c+case when exists(select 1 from t1 where a>=+f- -c*e+coalesce((select max(b) from t1 where (b not between (t1.b) and 19) or t1.f<11),d)*f | t1.e+t1.b) then ( -t1.e)-19 when ((t1.a in (select 19 from t1 union select t1.f from t1) or b -17)) then f else f end | d)} +} {60281} +do_test randexpr-2.75 { + db eval {SELECT (abs(case when a>=b then t1.c-case when not exists(select 1 from t1 where case d when +17 then 19+c else 11 end-(abs((select - -cast(avg(case when (11- -(abs(e)/abs(13))-t1.f11} +} {0} +do_test randexpr-2.76 { + db eval {SELECT (abs(case when a>=b then t1.c-case when not exists(select 1 from t1 where case d when +17 then 19+c else 11 end-(abs((select - -cast(avg(case when (11- -(abs(e)/abs(13))-t1.f11)} +} {} +do_test randexpr-2.77 { + db eval {SELECT -coalesce((select max(e-t1.b) from t1 where t1.e<11 and t1.b | e in ((abs(13)/abs(t1.b)),(abs((+17-case when t1.c | 13*(d) | b<>a or ((t1.e)>=a) then t1.b-t1.e when not exists(select 1 from t1 where 17<13) then -(13) else 17 end*13))/abs(13)),t1.c)),t1.e) | c FROM t1 WHERE not exists(select 1 from t1 where 17<=(select (case (~+abs(cast(avg((t1.e)-17 | b) AS integer))-((case -cast(avg(case when ~t1.b in (select d from t1 union select 19 from t1) then b when 13 in (t1.f,c,t1.b) then c else f end) AS integer)+count(distinct t1.f)+count(distinct t1.d) when count(*) then ((max(c))) else count(*) end)*cast(avg(t1.e) AS integer))) when ((cast(avg(a) AS integer))) then -max(d) else ((count(*))) end) from t1))} +} {-212} +do_test randexpr-2.78 { + db eval {SELECT -coalesce((select max(e-t1.b) from t1 where t1.e<11 and t1.b | e in ((abs(13)/abs(t1.b)),(abs((+17-case when t1.c | 13*(d) | b<>a or ((t1.e)>=a) then t1.b-t1.e when not exists(select 1 from t1 where 17<13) then -(13) else 17 end*13))/abs(13)),t1.c)),t1.e) | c FROM t1 WHERE NOT (not exists(select 1 from t1 where 17<=(select (case (~+abs(cast(avg((t1.e)-17 | b) AS integer))-((case -cast(avg(case when ~t1.b in (select d from t1 union select 19 from t1) then b when 13 in (t1.f,c,t1.b) then c else f end) AS integer)+count(distinct t1.f)+count(distinct t1.d) when count(*) then ((max(c))) else count(*) end)*cast(avg(t1.e) AS integer))) when ((cast(avg(a) AS integer))) then -max(d) else ((count(*))) end) from t1)))} +} {} +do_test randexpr-2.79 { + db eval {SELECT -coalesce((select max(e-t1.b) from t1 where t1.e<11 and t1.b & e in ((abs(13)/abs(t1.b)),(abs((+17-case when t1.c & 13*(d) & b<>a or ((t1.e)>=a) then t1.b-t1.e when not exists(select 1 from t1 where 17<13) then -(13) else 17 end*13))/abs(13)),t1.c)),t1.e) & c FROM t1 WHERE not exists(select 1 from t1 where 17<=(select (case (~+abs(cast(avg((t1.e)-17 | b) AS integer))-((case -cast(avg(case when ~t1.b in (select d from t1 union select 19 from t1) then b when 13 in (t1.f,c,t1.b) then c else f end) AS integer)+count(distinct t1.f)+count(distinct t1.d) when count(*) then ((max(c))) else count(*) end)*cast(avg(t1.e) AS integer))) when ((cast(avg(a) AS integer))) then -max(d) else ((count(*))) end) from t1))} +} {12} +do_test randexpr-2.80 { + db eval {SELECT 17-coalesce((select c+t1.f from t1 where (select count(distinct d)-abs(min((select case - -count(*) when -max(19) then -count(*) else count(*) end from t1))-count(*)) from t1)-t1.a+case when (abs(t1.e)/abs(t1.e)) not in (a,t1.a,19) and (b between 19 and -t1.c) then 17 else c end-19+t1.e*13<= -(t1.a)),11)-t1.d-c FROM t1 WHERE ((t1.d in ((select +cast(avg(coalesce((select max(coalesce((select max(a) from t1 where not a in (b,~(select ~count(*) from t1),case (select +max(11) | -count(*) from t1) when 17*t1.f*17 then b else (t1.b) end+f | 17)),e)) from t1 where not exists(select 1 from t1 where 17 between a and a)),(19))) AS integer) from t1),coalesce((select max(e) from t1 where t1.e<>11),b),t1.d)))} +} {-694} +do_test randexpr-2.81 { + db eval {SELECT 17-coalesce((select c+t1.f from t1 where (select count(distinct d)-abs(min((select case - -count(*) when -max(19) then -count(*) else count(*) end from t1))-count(*)) from t1)-t1.a+case when (abs(t1.e)/abs(t1.e)) not in (a,t1.a,19) and (b between 19 and -t1.c) then 17 else c end-19+t1.e*13<= -(t1.a)),11)-t1.d-c FROM t1 WHERE NOT (((t1.d in ((select +cast(avg(coalesce((select max(coalesce((select max(a) from t1 where not a in (b,~(select ~count(*) from t1),case (select +max(11) | -count(*) from t1) when 17*t1.f*17 then b else (t1.b) end+f | 17)),e)) from t1 where not exists(select 1 from t1 where 17 between a and a)),(19))) AS integer) from t1),coalesce((select max(e) from t1 where t1.e<>11),b),t1.d))))} +} {} +do_test randexpr-2.82 { + db eval {SELECT case (t1.a) when e then t1.a else t1.d end+(b)*t1.c | (select ~count(distinct (select count(distinct t1.f) from t1)) from t1)* -case c*t1.b when 19 then t1.d else (t1.b) | case when not (e)*f in (select count(distinct a)-count(distinct c) | min(a) from t1 union select -count(*) from t1) and (t1.f in (d, -t1.c,f)) then e when t1.c not in (t1.b,t1.e,b) then t1.e else f end end FROM t1 WHERE t1.d<>coalesce((select max(case when exists(select 1 from t1 where f<=e | b) then (select min(+t1.f) from t1) else 11 end) from t1 where +case when t1.e=c then -t1.c else t1.a end-t1.a-11-f in (select (case -min(a) when count(*)*(( -+abs(cast(avg(a) AS integer))*max((17))) | max(19)) then min(11) else min(a) end | count(distinct -d)) from t1 union select min(t1.e) from t1)),t1.c)} +} {60408} +do_test randexpr-2.83 { + db eval {SELECT case (t1.a) when e then t1.a else t1.d end+(b)*t1.c | (select ~count(distinct (select count(distinct t1.f) from t1)) from t1)* -case c*t1.b when 19 then t1.d else (t1.b) | case when not (e)*f in (select count(distinct a)-count(distinct c) | min(a) from t1 union select -count(*) from t1) and (t1.f in (d, -t1.c,f)) then e when t1.c not in (t1.b,t1.e,b) then t1.e else f end end FROM t1 WHERE NOT (t1.d<>coalesce((select max(case when exists(select 1 from t1 where f<=e | b) then (select min(+t1.f) from t1) else 11 end) from t1 where +case when t1.e=c then -t1.c else t1.a end-t1.a-11-f in (select (case -min(a) when count(*)*(( -+abs(cast(avg(a) AS integer))*max((17))) | max(19)) then min(11) else min(a) end | count(distinct -d)) from t1 union select min(t1.e) from t1)),t1.c))} +} {} +do_test randexpr-2.84 { + db eval {SELECT case (t1.a) when e then t1.a else t1.d end+(b)*t1.c & (select ~count(distinct (select count(distinct t1.f) from t1)) from t1)* -case c*t1.b when 19 then t1.d else (t1.b) & case when not (e)*f in (select count(distinct a)-count(distinct c) & min(a) from t1 union select -count(*) from t1) and (t1.f in (d, -t1.c,f)) then e when t1.c not in (t1.b,t1.e,b) then t1.e else f end end FROM t1 WHERE t1.d<>coalesce((select max(case when exists(select 1 from t1 where f<=e | b) then (select min(+t1.f) from t1) else 11 end) from t1 where +case when t1.e=c then -t1.c else t1.a end-t1.a-11-f in (select (case -min(a) when count(*)*(( -+abs(cast(avg(a) AS integer))*max((17))) | max(19)) then min(11) else min(a) end | count(distinct -d)) from t1 union select min(t1.e) from t1)),t1.c)} +} {384} +do_test randexpr-2.85 { + db eval {SELECT (select abs(max((select (case cast(avg(t1.a) AS integer) when +~abs(cast(avg( -17+case when t1.a in (c,(e),t1.f) and f in (c,t1.d,t1.a) then d when d between c and t1.d then f else e end) AS integer))-(abs(~max((b)))-min(t1.f)) then cast(avg(t1.f) AS integer) else count(*) end) from t1)+case when (exists(select 1 from t1 where t1.a in (select -max(e) from t1 union select -count(*) from t1)) or e in (t1.b*d,a, - -d)) then 17*t1.c else c end)) from t1) FROM t1 WHERE ~t1.e>case 13 when e then a else coalesce((select ~t1.d from t1 where exists(select 1 from t1 where t1.f between coalesce((select t1.a from t1 where ((select min(d-d- -t1.d+a) from t1)) not between f and t1.c or exists(select 1 from t1 where b<>17)),(a)) and -d) or not exists(select 1 from t1 where e in (select min(19)*(count(*))*cast(avg(11) AS integer) | min(b) from t1 union select (cast(avg(t1.e) AS integer)) from t1))),c) end-t1.c} +} {} +do_test randexpr-2.86 { + db eval {SELECT (select abs(max((select (case cast(avg(t1.a) AS integer) when +~abs(cast(avg( -17+case when t1.a in (c,(e),t1.f) and f in (c,t1.d,t1.a) then d when d between c and t1.d then f else e end) AS integer))-(abs(~max((b)))-min(t1.f)) then cast(avg(t1.f) AS integer) else count(*) end) from t1)+case when (exists(select 1 from t1 where t1.a in (select -max(e) from t1 union select -count(*) from t1)) or e in (t1.b*d,a, - -d)) then 17*t1.c else c end)) from t1) FROM t1 WHERE NOT (~t1.e>case 13 when e then a else coalesce((select ~t1.d from t1 where exists(select 1 from t1 where t1.f between coalesce((select t1.a from t1 where ((select min(d-d- -t1.d+a) from t1)) not between f and t1.c or exists(select 1 from t1 where b<>17)),(a)) and -d) or not exists(select 1 from t1 where e in (select min(19)*(count(*))*cast(avg(11) AS integer) | min(b) from t1 union select (cast(avg(t1.e) AS integer)) from t1))),c) end-t1.c)} +} {301} +do_test randexpr-2.87 { + db eval {SELECT t1.c+(abs(t1.b*t1.b)/abs(++t1.a-t1.e-(abs(t1.b)/abs(d))*11*t1.f)) | 19-b-t1.e | t1.e-+~t1.d*13+a+case case when (d)+17-c=d then a else t1.b end when e then t1.a else 19 end FROM t1 WHERE not coalesce((select (abs(case t1.b when coalesce((select case when exists(select 1 from t1 where f between 17 and f) then 11 else f end from t1 where not exists(select 1 from t1 where c>=t1.d)),17)*t1.a then t1.e else 13 end)/abs(17)) from t1 where ((13 in (select abs(~min(d)*count(distinct -(f)) | count(*)*cast(avg(11) AS integer)) from t1 union select count(*) from t1) and a<=13) and c<> -(t1.c))), -t1.a)*t1.e*f+d not in (11,d,t1.c)} +} {} +do_test randexpr-2.88 { + db eval {SELECT t1.c+(abs(t1.b*t1.b)/abs(++t1.a-t1.e-(abs(t1.b)/abs(d))*11*t1.f)) | 19-b-t1.e | t1.e-+~t1.d*13+a+case case when (d)+17-c=d then a else t1.b end when e then t1.a else 19 end FROM t1 WHERE NOT (not coalesce((select (abs(case t1.b when coalesce((select case when exists(select 1 from t1 where f between 17 and f) then 11 else f end from t1 where not exists(select 1 from t1 where c>=t1.d)),17)*t1.a then t1.e else 13 end)/abs(17)) from t1 where ((13 in (select abs(~min(d)*count(distinct -(f)) | count(*)*cast(avg(11) AS integer)) from t1 union select count(*) from t1) and a<=13) and c<> -(t1.c))), -t1.a)*t1.e*f+d not in (11,d,t1.c))} +} {-33} +do_test randexpr-2.89 { + db eval {SELECT t1.c+(abs(t1.b*t1.b)/abs(++t1.a-t1.e-(abs(t1.b)/abs(d))*11*t1.f)) & 19-b-t1.e & t1.e-+~t1.d*13+a+case case when (d)+17-c=d then a else t1.b end when e then t1.a else 19 end FROM t1 WHERE NOT (not coalesce((select (abs(case t1.b when coalesce((select case when exists(select 1 from t1 where f between 17 and f) then 11 else f end from t1 where not exists(select 1 from t1 where c>=t1.d)),17)*t1.a then t1.e else 13 end)/abs(17)) from t1 where ((13 in (select abs(~min(d)*count(distinct -(f)) | count(*)*cast(avg(11) AS integer)) from t1 union select count(*) from t1) and a<=13) and c<> -(t1.c))), -t1.a)*t1.e*f+d not in (11,d,t1.c))} +} {0} +do_test randexpr-2.90 { + db eval {SELECT case when t1.f>t1.d then (select abs(+count(distinct c)+(abs(min((abs(+11)/abs(b)))* -count(*)))) from t1)-t1.a when d+case when (select cast(avg(t1.f) AS integer)-count(distinct 19) from t1)<>17 then c when t1.e in (select cast(avg(t1.a) AS integer) from t1 union select count(distinct f) from t1) and d>t1.c and t1.f not in (11,19,t1.b) then a else (c) end+(17)=c then t1.d else t1.c end-c FROM t1 WHERE 13 not in (e,t1.b,+coalesce((select max(b) from t1 where 13*b-t1.d-case when 11>=a then t1.a-t1.d else (t1.d)*e+19 end*t1.a+19+(11) | t1.c*t1.a-17t1.d then (select abs(+count(distinct c)+(abs(min((abs(+11)/abs(b)))* -count(*)))) from t1)-t1.a when d+case when (select cast(avg(t1.f) AS integer)-count(distinct 19) from t1)<>17 then c when t1.e in (select cast(avg(t1.a) AS integer) from t1 union select count(distinct f) from t1) and d>t1.c and t1.f not in (11,19,t1.b) then a else (c) end+(17)=c then t1.d else t1.c end-c FROM t1 WHERE NOT (13 not in (e,t1.b,+coalesce((select max(b) from t1 where 13*b-t1.d-case when 11>=a then t1.a-t1.d else (t1.d)*e+19 end*t1.a+19+(11) | t1.c*t1.a-17(abs(t1.a)/abs(e)) then d else ~(t1.e)-e+d+13-t1.b+b*19 end) from t1 where (select max(19)-cast(avg(a) AS integer) from t1)> -t1.e),17)+e+t1.e-t1.c+(c))*17) from t1) between -17 and t1.c} +} {} +do_test randexpr-2.93 { + db eval {SELECT coalesce((select +19 from t1 where 19-c+t1.c-f not in (coalesce((select 19 from t1 where (t1.b between t1.c*t1.a*t1.b | a-e | 13-(abs(19)/abs((select max(t1.d | coalesce((select max( -t1.c) from t1 where b in (select e from t1 union select (f) from t1)),t1.d)+(e)) from t1)+c)) and f)),11),f,17)),f) FROM t1 WHERE NOT ((select count(distinct 11)+min((coalesce((select max(case when t1.d<>(abs(t1.a)/abs(e)) then d else ~(t1.e)-e+d+13-t1.b+b*19 end) from t1 where (select max(19)-cast(avg(a) AS integer) from t1)> -t1.e),17)+e+t1.e-t1.c+(c))*17) from t1) between -17 and t1.c)} +} {19} +do_test randexpr-2.94 { + db eval {SELECT coalesce((select +19 from t1 where 19-c+t1.c-f not in (coalesce((select 19 from t1 where (t1.b between t1.c*t1.a*t1.b & a-e & 13-(abs(19)/abs((select max(t1.d & coalesce((select max( -t1.c) from t1 where b in (select e from t1 union select (f) from t1)),t1.d)+(e)) from t1)+c)) and f)),11),f,17)),f) FROM t1 WHERE NOT ((select count(distinct 11)+min((coalesce((select max(case when t1.d<>(abs(t1.a)/abs(e)) then d else ~(t1.e)-e+d+13-t1.b+b*19 end) from t1 where (select max(19)-cast(avg(a) AS integer) from t1)> -t1.e),17)+e+t1.e-t1.c+(c))*17) from t1) between -17 and t1.c)} +} {19} +do_test randexpr-2.95 { + db eval {SELECT (case t1.a when (select (count(distinct t1.f)) from t1)-e then 11 else t1.c+17-f*~f | f+~e-a*t1.b+13 end | 13) FROM t1 WHERE (coalesce((select max(f) from t1 where (c+t1.f | (select count(distinct t1.d) from t1)>=coalesce((select b+(abs(case when t1.f>=(select case max(f) when max(19) then cast(avg(t1.a) AS integer) else count(distinct 13) end from t1) | t1.b and (a in (select (b) from t1 union select t1.b from t1)) then (a)-b when not exists(select 1 from t1 where c between t1.c and t1.a) then a else t1.a end)/abs(t1.b))- -f from t1 where b not in (t1.b,t1.f,c)),t1.d)-t1.d)), -17) between 13 and t1.f)} +} {-19491} +do_test randexpr-2.96 { + db eval {SELECT (case t1.a when (select (count(distinct t1.f)) from t1)-e then 11 else t1.c+17-f*~f | f+~e-a*t1.b+13 end | 13) FROM t1 WHERE NOT ((coalesce((select max(f) from t1 where (c+t1.f | (select count(distinct t1.d) from t1)>=coalesce((select b+(abs(case when t1.f>=(select case max(f) when max(19) then cast(avg(t1.a) AS integer) else count(distinct 13) end from t1) | t1.b and (a in (select (b) from t1 union select t1.b from t1)) then (a)-b when not exists(select 1 from t1 where c between t1.c and t1.a) then a else t1.a end)/abs(t1.b))- -f from t1 where b not in (t1.b,t1.f,c)),t1.d)-t1.d)), -17) between 13 and t1.f))} +} {} +do_test randexpr-2.97 { + db eval {SELECT (case t1.a when (select (count(distinct t1.f)) from t1)-e then 11 else t1.c+17-f*~f & f+~e-a*t1.b+13 end & 13) FROM t1 WHERE (coalesce((select max(f) from t1 where (c+t1.f | (select count(distinct t1.d) from t1)>=coalesce((select b+(abs(case when t1.f>=(select case max(f) when max(19) then cast(avg(t1.a) AS integer) else count(distinct 13) end from t1) | t1.b and (a in (select (b) from t1 union select t1.b from t1)) then (a)-b when not exists(select 1 from t1 where c between t1.c and t1.a) then a else t1.a end)/abs(t1.b))- -f from t1 where b not in (t1.b,t1.f,c)),t1.d)-t1.d)), -17) between 13 and t1.f)} +} {0} +do_test randexpr-2.98 { + db eval {SELECT case when ((select -abs(min(coalesce((select max(11 | t1.f) from t1 where coalesce((select f from t1 where e+c in (select 19 from t1 union select f from t1)),b) not in (t1.a,+case when 13>=t1.e then t1.a when 17 not in (t1.d,b,t1.e) then 13 else t1.b end-t1.e,t1.f)),t1.f))*count(*)*min(t1.c)) from t1)<17) and 13* -f+a not between (a) and f then c-11+b else 19 end FROM t1 WHERE e+case case when a<>c then (abs(case when coalesce((select (abs( -19+11)/abs(t1.c)) from t1 where (17) in (a,13,11) and 17 in (select 11 from t1 union select t1.f from t1)),t1.a) between t1.f and c then t1.d when not exists(select 1 from t1 where not exists(select 1 from t1 where 19=f)) then f else (b) end-19)/abs(e)) else 11 end when 17 then a else t1.f end-13 | e between -t1.e and 13} +} {} +do_test randexpr-2.99 { + db eval {SELECT case when ((select -abs(min(coalesce((select max(11 | t1.f) from t1 where coalesce((select f from t1 where e+c in (select 19 from t1 union select f from t1)),b) not in (t1.a,+case when 13>=t1.e then t1.a when 17 not in (t1.d,b,t1.e) then 13 else t1.b end-t1.e,t1.f)),t1.f))*count(*)*min(t1.c)) from t1)<17) and 13* -f+a not between (a) and f then c-11+b else 19 end FROM t1 WHERE NOT (e+case case when a<>c then (abs(case when coalesce((select (abs( -19+11)/abs(t1.c)) from t1 where (17) in (a,13,11) and 17 in (select 11 from t1 union select t1.f from t1)),t1.a) between t1.f and c then t1.d when not exists(select 1 from t1 where not exists(select 1 from t1 where 19=f)) then f else (b) end-19)/abs(e)) else 11 end when 17 then a else t1.f end-13 | e between -t1.e and 13)} +} {489} +do_test randexpr-2.100 { + db eval {SELECT case when ((select -abs(min(coalesce((select max(11 & t1.f) from t1 where coalesce((select f from t1 where e+c in (select 19 from t1 union select f from t1)),b) not in (t1.a,+case when 13>=t1.e then t1.a when 17 not in (t1.d,b,t1.e) then 13 else t1.b end-t1.e,t1.f)),t1.f))*count(*)*min(t1.c)) from t1)<17) and 13* -f+a not between (a) and f then c-11+b else 19 end FROM t1 WHERE NOT (e+case case when a<>c then (abs(case when coalesce((select (abs( -19+11)/abs(t1.c)) from t1 where (17) in (a,13,11) and 17 in (select 11 from t1 union select t1.f from t1)),t1.a) between t1.f and c then t1.d when not exists(select 1 from t1 where not exists(select 1 from t1 where 19=f)) then f else (b) end-19)/abs(e)) else 11 end when 17 then a else t1.f end-13 | e between -t1.e and 13)} +} {489} +do_test randexpr-2.101 { + db eval {SELECT case when t1.b-t1.e*c<>c then coalesce((select -17 from t1 where (t1.f+((select case count(*) when -cast(avg(19) AS integer)+count(distinct (t1.c)) | (cast(avg(19) AS integer))*max(t1.c)*count(*)-((count(*))) then cast(avg(b) AS integer) else (count(*)) end-min(a) from t1)) | case when t1.b | a in (select t1.a from t1 union select (select count(distinct e) from t1) from t1) then t1.e else b end+t1.a)c then coalesce((select -17 from t1 where (t1.f+((select case count(*) when -cast(avg(19) AS integer)+count(distinct (t1.c)) | (cast(avg(19) AS integer))*max(t1.c)*count(*)-((count(*))) then cast(avg(b) AS integer) else (count(*)) end-min(a) from t1)) | case when t1.b | a in (select t1.a from t1 union select (select count(distinct e) from t1) from t1) then t1.e else b end+t1.a)c then coalesce((select -17 from t1 where (t1.f+((select case count(*) when -cast(avg(19) AS integer)+count(distinct (t1.c)) & (cast(avg(19) AS integer))*max(t1.c)*count(*)-((count(*))) then cast(avg(b) AS integer) else (count(*)) end-min(a) from t1)) & case when t1.b & a in (select t1.a from t1 union select (select count(distinct e) from t1) from t1) then t1.e else b end+t1.a)~t1.a then f else +~11 end) from t1 where ((select case ~abs(count(distinct t1.e)+(count(*)+count(*)+(abs( -~count(*) | max((t1.b))))))*(cast(avg(t1.a) AS integer)) when (count(*)) then min(19) else -(min(b)) end from t1))+11<>t1.f), -c-f) FROM t1 WHERE ~e>coalesce((select max(case case case coalesce((select max(coalesce((select c from t1 where t1.a-t1.c>13),13)) from t1 where -b not in (case d when ~t1.f | t1.c then 13 else 11 end,19,19)),t1.d) when c then t1.a else t1.b end+f-e*b when f then 19 else -t1.b end when t1.b then 11 else 13 end) from t1 where c in (select 19 from t1 union select e from t1)),t1.d)} +} {} +do_test randexpr-2.105 { + db eval {SELECT coalesce((select max(case when (select ~cast(avg(a) AS integer) from t1)>~t1.a then f else +~11 end) from t1 where ((select case ~abs(count(distinct t1.e)+(count(*)+count(*)+(abs( -~count(*) | max((t1.b))))))*(cast(avg(t1.a) AS integer)) when (count(*)) then min(19) else -(min(b)) end from t1))+11<>t1.f), -c-f) FROM t1 WHERE NOT (~e>coalesce((select max(case case case coalesce((select max(coalesce((select c from t1 where t1.a-t1.c>13),13)) from t1 where -b not in (case d when ~t1.f | t1.c then 13 else 11 end,19,19)),t1.d) when c then t1.a else t1.b end+f-e*b when f then 19 else -t1.b end when t1.b then 11 else 13 end) from t1 where c in (select 19 from t1 union select e from t1)),t1.d))} +} {-12} +do_test randexpr-2.106 { + db eval {SELECT coalesce((select max(case when (select ~cast(avg(a) AS integer) from t1)>~t1.a then f else +~11 end) from t1 where ((select case ~abs(count(distinct t1.e)+(count(*)+count(*)+(abs( -~count(*) & max((t1.b))))))*(cast(avg(t1.a) AS integer)) when (count(*)) then min(19) else -(min(b)) end from t1))+11<>t1.f), -c-f) FROM t1 WHERE NOT (~e>coalesce((select max(case case case coalesce((select max(coalesce((select c from t1 where t1.a-t1.c>13),13)) from t1 where -b not in (case d when ~t1.f | t1.c then 13 else 11 end,19,19)),t1.d) when c then t1.a else t1.b end+f-e*b when f then 19 else -t1.b end when t1.b then 11 else 13 end) from t1 where c in (select 19 from t1 union select e from t1)),t1.d))} +} {-12} +do_test randexpr-2.107 { + db eval {SELECT coalesce((select a from t1 where b>=~11-coalesce((select max((abs(19)/abs(t1.e))+19+t1.d) from t1 where (select abs(count(*) | count(*) | case count(*) when cast(avg(17) AS integer) then -cast(avg(b) AS integer) else count(*) end*min(b))*(min(t1.e)) from t1) in (11*(select count(*) from t1)*17*t1.e-e*t1.b,t1.e,t1.f)),a)*t1.d),13)-f FROM t1 WHERE ~((case when not 13-+t1.c>=17 then -~ -b+t1.f+case when t1.ct1.d then 11 else t1.e end)) else t1.b end when d>a then (a) else t1.b end))+t1.c in (13,t1.a,13) or t1.e>c} +} {-500} +do_test randexpr-2.108 { + db eval {SELECT coalesce((select a from t1 where b>=~11-coalesce((select max((abs(19)/abs(t1.e))+19+t1.d) from t1 where (select abs(count(*) | count(*) | case count(*) when cast(avg(17) AS integer) then -cast(avg(b) AS integer) else count(*) end*min(b))*(min(t1.e)) from t1) in (11*(select count(*) from t1)*17*t1.e-e*t1.b,t1.e,t1.f)),a)*t1.d),13)-f FROM t1 WHERE NOT (~((case when not 13-+t1.c>=17 then -~ -b+t1.f+case when t1.ct1.d then 11 else t1.e end)) else t1.b end when d>a then (a) else t1.b end))+t1.c in (13,t1.a,13) or t1.e>c)} +} {} +do_test randexpr-2.109 { + db eval {SELECT coalesce((select a from t1 where b>=~11-coalesce((select max((abs(19)/abs(t1.e))+19+t1.d) from t1 where (select abs(count(*) & count(*) & case count(*) when cast(avg(17) AS integer) then -cast(avg(b) AS integer) else count(*) end*min(b))*(min(t1.e)) from t1) in (11*(select count(*) from t1)*17*t1.e-e*t1.b,t1.e,t1.f)),a)*t1.d),13)-f FROM t1 WHERE ~((case when not 13-+t1.c>=17 then -~ -b+t1.f+case when t1.ct1.d then 11 else t1.e end)) else t1.b end when d>a then (a) else t1.b end))+t1.c in (13,t1.a,13) or t1.e>c} +} {-500} +do_test randexpr-2.110 { + db eval {SELECT case when 13>=~t1.a or (exists(select 1 from t1 where 11 not in (17,t1.f,17))) then f when not exists(select 1 from t1 where exists(select 1 from t1 where 13 not between e and ~+case b when t1.f then case -case f when 11 then -17 else 19 end+17 when b then b else 13 end else 13 end- -t1.a and t1.c not in (t1.f,a,c) or t1.f<11)) then t1.c else 11 end FROM t1 WHERE +t1.e in (select cast(avg(t1.c*t1.a*(abs(13)/abs(t1.e))) AS integer) from t1 union select min(c+13) from t1)} +} {} +do_test randexpr-2.111 { + db eval {SELECT case when 13>=~t1.a or (exists(select 1 from t1 where 11 not in (17,t1.f,17))) then f when not exists(select 1 from t1 where exists(select 1 from t1 where 13 not between e and ~+case b when t1.f then case -case f when 11 then -17 else 19 end+17 when b then b else 13 end else 13 end- -t1.a and t1.c not in (t1.f,a,c) or t1.f<11)) then t1.c else 11 end FROM t1 WHERE NOT (+t1.e in (select cast(avg(t1.c*t1.a*(abs(13)/abs(t1.e))) AS integer) from t1 union select min(c+13) from t1))} +} {600} +do_test randexpr-2.112 { + db eval {SELECT case when coalesce((select max(13) from t1 where coalesce((select max(c) from t1 where coalesce((select max(17) from t1 where 11 in (select ~d | case when t1.a>+19 then 11 when t1.d not in ( -e,e,c) or 13d or t1.e<>b),t1.b)*13<=f then -t1.e when 19 between -t1.f and t1.a then -t1.b else t1.f end FROM t1 WHERE exists(select 1 from t1 where t1.f between a and coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where coalesce((select 19 from t1 where t1.c=b),a)= -t1.b and not exists(select 1 from t1 where b between e and b) and a<= -17 or exists(select 1 from t1 where 17<=f)) or t1.a>=t1.c),13)*~13*t1.c*13 or t1.d>13 and 11>=t1.d and 11 not between c and c and t1.f>=17 and (d)=f)} +} {} +do_test randexpr-2.113 { + db eval {SELECT case when coalesce((select max(13) from t1 where coalesce((select max(c) from t1 where coalesce((select max(17) from t1 where 11 in (select ~d | case when t1.a>+19 then 11 when t1.d not in ( -e,e,c) or 13d or t1.e<>b),t1.b)*13<=f then -t1.e when 19 between -t1.f and t1.a then -t1.b else t1.f end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.f between a and coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where coalesce((select 19 from t1 where t1.c=b),a)= -t1.b and not exists(select 1 from t1 where b between e and b) and a<= -17 or exists(select 1 from t1 where 17<=f)) or t1.a>=t1.c),13)*~13*t1.c*13 or t1.d>13 and 11>=t1.d and 11 not between c and c and t1.f>=17 and (d)=f))} +} {-500} +do_test randexpr-2.114 { + db eval {SELECT case when coalesce((select max(13) from t1 where coalesce((select max(c) from t1 where coalesce((select max(17) from t1 where 11 in (select ~d & case when t1.a>+19 then 11 when t1.d not in ( -e,e,c) or 13d or t1.e<>b),t1.b)*13<=f then -t1.e when 19 between -t1.f and t1.a then -t1.b else t1.f end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.f between a and coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where coalesce((select 19 from t1 where t1.c=b),a)= -t1.b and not exists(select 1 from t1 where b between e and b) and a<= -17 or exists(select 1 from t1 where 17<=f)) or t1.a>=t1.c),13)*~13*t1.c*13 or t1.d>13 and 11>=t1.d and 11 not between c and c and t1.f>=17 and (d)=f))} +} {-500} +do_test randexpr-2.115 { + db eval {SELECT case when coalesce((select +case when not exists(select 1 from t1 where 19*t1.e< -~11*a or t1.b>=t1.c and t1.a<>e) then coalesce((select max(13) from t1 where 11>11), -(e)) | t1.a when (t1.d) in (select f from t1 union select b from t1) then a else e end from t1 where t1.f<> -t1.d),t1.b) not in (d,t1.d,t1.c) then 19 when (t1.b<>t1.e or -t1.b>=t1.b) then (f) else d end FROM t1 WHERE t1.e=a and b>=(abs(case when 19 not between ~+17 and +case when ((b+e-f=t1.d or b not in (t1.a,t1.f,t1.b) or t1.a not between 19 and e or b>=(t1.d) or t1.b not in (d,t1.a,t1.b))) then e-f else t1.e*t1.f end | f then d else -d end)/abs(11))} +} {} +do_test randexpr-2.116 { + db eval {SELECT case when coalesce((select +case when not exists(select 1 from t1 where 19*t1.e< -~11*a or t1.b>=t1.c and t1.a<>e) then coalesce((select max(13) from t1 where 11>11), -(e)) | t1.a when (t1.d) in (select f from t1 union select b from t1) then a else e end from t1 where t1.f<> -t1.d),t1.b) not in (d,t1.d,t1.c) then 19 when (t1.b<>t1.e or -t1.b>=t1.b) then (f) else d end FROM t1 WHERE NOT (t1.e=a and b>=(abs(case when 19 not between ~+17 and +case when ((b+e-f=t1.d or b not in (t1.a,t1.f,t1.b) or t1.a not between 19 and e or b>=(t1.d) or t1.b not in (d,t1.a,t1.b))) then e-f else t1.e*t1.f end | f then d else -d end)/abs(11)))} +} {19} +do_test randexpr-2.117 { + db eval {SELECT case when coalesce((select +case when not exists(select 1 from t1 where 19*t1.e< -~11*a or t1.b>=t1.c and t1.a<>e) then coalesce((select max(13) from t1 where 11>11), -(e)) & t1.a when (t1.d) in (select f from t1 union select b from t1) then a else e end from t1 where t1.f<> -t1.d),t1.b) not in (d,t1.d,t1.c) then 19 when (t1.b<>t1.e or -t1.b>=t1.b) then (f) else d end FROM t1 WHERE NOT (t1.e=a and b>=(abs(case when 19 not between ~+17 and +case when ((b+e-f=t1.d or b not in (t1.a,t1.f,t1.b) or t1.a not between 19 and e or b>=(t1.d) or t1.b not in (d,t1.a,t1.b))) then e-f else t1.e*t1.f end | f then d else -d end)/abs(11)))} +} {19} +do_test randexpr-2.118 { + db eval {SELECT (select (cast(avg(b) AS integer) | count(distinct case when coalesce((select 13 from t1 where (+(abs(e)/abs(t1.b))) in ( -b, -(a),13)),t1.e)>=b then 11 else - -19 end-17+19) | abs(~case count(distinct t1.b) when +min(e) then +abs(~ - -count(distinct 11)-count(distinct t1.b))-count(distinct a) else -min(b) end)*count(distinct 19)-count(distinct t1.b)) from t1) FROM t1 WHERE 11<=t1.a-t1.f-19*t1.b+19+coalesce((select e from t1 where d not between (select count(distinct coalesce((select t1.a from t1 where (select cast(avg(t1.e) AS integer)-+count(distinct c)+max((abs(t1.c)/abs(t1.f))-a)-(count(*)-cast(avg((17)) AS integer)) from t1) in (t1.e, -e | d,b)),c)) from t1) and t1.a),t1.d)-t1.d} +} {} +do_test randexpr-2.119 { + db eval {SELECT (select (cast(avg(b) AS integer) | count(distinct case when coalesce((select 13 from t1 where (+(abs(e)/abs(t1.b))) in ( -b, -(a),13)),t1.e)>=b then 11 else - -19 end-17+19) | abs(~case count(distinct t1.b) when +min(e) then +abs(~ - -count(distinct 11)-count(distinct t1.b))-count(distinct a) else -min(b) end)*count(distinct 19)-count(distinct t1.b)) from t1) FROM t1 WHERE NOT (11<=t1.a-t1.f-19*t1.b+19+coalesce((select e from t1 where d not between (select count(distinct coalesce((select t1.a from t1 where (select cast(avg(t1.e) AS integer)-+count(distinct c)+max((abs(t1.c)/abs(t1.f))-a)-(count(*)-cast(avg((17)) AS integer)) from t1) in (t1.e, -e | d,b)),c)) from t1) and t1.a),t1.d)-t1.d)} +} {207} +do_test randexpr-2.120 { + db eval {SELECT (select (cast(avg(b) AS integer) & count(distinct case when coalesce((select 13 from t1 where (+(abs(e)/abs(t1.b))) in ( -b, -(a),13)),t1.e)>=b then 11 else - -19 end-17+19) & abs(~case count(distinct t1.b) when +min(e) then +abs(~ - -count(distinct 11)-count(distinct t1.b))-count(distinct a) else -min(b) end)*count(distinct 19)-count(distinct t1.b)) from t1) FROM t1 WHERE NOT (11<=t1.a-t1.f-19*t1.b+19+coalesce((select e from t1 where d not between (select count(distinct coalesce((select t1.a from t1 where (select cast(avg(t1.e) AS integer)-+count(distinct c)+max((abs(t1.c)/abs(t1.f))-a)-(count(*)-cast(avg((17)) AS integer)) from t1) in (t1.e, -e | d,b)),c)) from t1) and t1.a),t1.d)-t1.d)} +} {0} +do_test randexpr-2.121 { + db eval {SELECT 11+a*case t1.a*t1.e when 17 then coalesce((select +t1.b from t1 where t1.c<>t1.c and e between +(abs(case b+f*coalesce((select c from t1 where t1.d>17), -t1.c)+(19) when b then t1.f else t1.d end)/abs(t1.d)) and t1.c and t1.a>b or t1.fc or t1.d | 11 in (select t1.e from t1 union select d from t1))) then 17 else (abs(coalesce((select max(f) from t1 where not (c)t1.c and e between +(abs(case b+f*coalesce((select c from t1 where t1.d>17), -t1.c)+(19) when b then t1.f else t1.d end)/abs(t1.d)) and t1.c and t1.a>b or t1.fc or t1.d | 11 in (select t1.e from t1 union select d from t1))) then 17 else (abs(coalesce((select max(f) from t1 where not (c)e then t1.f else t1.b+case when b between coalesce((select max(t1.d-~(abs(a)/abs(c))+t1.c) from t1 where f in (select -min(t1.f)-+cast(avg(e) AS integer) from t1 union select -(cast(avg(13) AS integer)) from t1) and f<=a and not exists(select 1 from t1 where f not between t1.d and t1.d or (f)<=a) and (t1.f) between 11 and d),t1.a) and t1.f then e when (1113),case when c<=11 then t1.e when t1.e<=b then t1.d else t1.e end)-11,11,17)} +} {} +do_test randexpr-2.124 { + db eval {SELECT (e)+case when t1.a>e then t1.f else t1.b+case when b between coalesce((select max(t1.d-~(abs(a)/abs(c))+t1.c) from t1 where f in (select -min(t1.f)-+cast(avg(e) AS integer) from t1 union select -(cast(avg(13) AS integer)) from t1) and f<=a and not exists(select 1 from t1 where f not between t1.d and t1.d or (f)<=a) and (t1.f) between 11 and d),t1.a) and t1.f then e when (1113),case when c<=11 then t1.e when t1.e<=b then t1.d else t1.e end)-11,11,17))} +} {1524} +do_test randexpr-2.125 { + db eval {SELECT (e)+case when t1.a>e then t1.f else t1.b+case when b between coalesce((select max(t1.d-~(abs(a)/abs(c))+t1.c) from t1 where f in (select -min(t1.f)-+cast(avg(e) AS integer) from t1 union select -(cast(avg(13) AS integer)) from t1) and f<=a and not exists(select 1 from t1 where f not between t1.d and t1.d or (f)<=a) and (t1.f) between 11 and d),t1.a) and t1.f then e when (1113),case when c<=11 then t1.e when t1.e<=b then t1.d else t1.e end)-11,11,17))} +} {176} +do_test randexpr-2.126 { + db eval {SELECT coalesce((select max(~d-t1.f+b-13) from t1 where t1.c not between case when +f=t1.b then 13 when ~f not in (~t1.a,coalesce((select max(t1.b) from t1 where b between c-t1.c+e and (t1.b)),coalesce((select max(t1.d) from t1 where not e in (select 17 from t1 union select t1.c+e | a from t1)),b)),t1.e) then t1.b else a end and c),t1.a) FROM t1 WHERE (select (++ -count(*) | cast(avg(t1.b) AS integer) | ++(max(t1.d))+count(*)+max(t1.b)-count(distinct t1.e)-+abs( -+~max((abs(t1.c)/abs((select min(a) from t1)))))+count(distinct t1.a-t1.b)) from t1) between e and c} +} {} +do_test randexpr-2.127 { + db eval {SELECT coalesce((select max(~d-t1.f+b-13) from t1 where t1.c not between case when +f=t1.b then 13 when ~f not in (~t1.a,coalesce((select max(t1.b) from t1 where b between c-t1.c+e and (t1.b)),coalesce((select max(t1.d) from t1 where not e in (select 17 from t1 union select t1.c+e | a from t1)),b)),t1.e) then t1.b else a end and c),t1.a) FROM t1 WHERE NOT ((select (++ -count(*) | cast(avg(t1.b) AS integer) | ++(max(t1.d))+count(*)+max(t1.b)-count(distinct t1.e)-+abs( -+~max((abs(t1.c)/abs((select min(a) from t1)))))+count(distinct t1.a-t1.b)) from t1) between e and c)} +} {100} +do_test randexpr-2.128 { + db eval {SELECT coalesce((select max(~d-t1.f+b-13) from t1 where t1.c not between case when +f=t1.b then 13 when ~f not in (~t1.a,coalesce((select max(t1.b) from t1 where b between c-t1.c+e and (t1.b)),coalesce((select max(t1.d) from t1 where not e in (select 17 from t1 union select t1.c+e & a from t1)),b)),t1.e) then t1.b else a end and c),t1.a) FROM t1 WHERE NOT ((select (++ -count(*) | cast(avg(t1.b) AS integer) | ++(max(t1.d))+count(*)+max(t1.b)-count(distinct t1.e)-+abs( -+~max((abs(t1.c)/abs((select min(a) from t1)))))+count(distinct t1.a-t1.b)) from t1) between e and c)} +} {100} +do_test randexpr-2.129 { + db eval {SELECT a+case when exists(select 1 from t1 where 19>=e) then b*b+coalesce((select max( -coalesce((select max(19 | t1.e) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where +case t1.a when a then a else (17) end*19 in (select max(d) from t1 union select max(t1.a) from t1) and not exists(select 1 from t1 where t1.a<=11)) or 11>(19))),11* -a)) from t1 where t1.e<>17),f) else t1.e end-11 FROM t1 WHERE (t1.a>=(abs(coalesce((select +13*t1.a | c from t1 where 11+case when exists(select 1 from t1 where case when +t1.d in (select case +count(*) when count(distinct 11) then count(*) else (min(11)) end from t1 union select max( -11) from t1) or 11<> -t1.f then t1.d when t1.b in (13,a,d) then c else c end+t1.b=b) then e-c else (t1.d) end>t1.d),d))/abs(t1.f)) and 11 in (select -t1.a from t1 union select 13 from t1))} +} {} +do_test randexpr-2.130 { + db eval {SELECT a+case when exists(select 1 from t1 where 19>=e) then b*b+coalesce((select max( -coalesce((select max(19 | t1.e) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where +case t1.a when a then a else (17) end*19 in (select max(d) from t1 union select max(t1.a) from t1) and not exists(select 1 from t1 where t1.a<=11)) or 11>(19))),11* -a)) from t1 where t1.e<>17),f) else t1.e end-11 FROM t1 WHERE NOT ((t1.a>=(abs(coalesce((select +13*t1.a | c from t1 where 11+case when exists(select 1 from t1 where case when +t1.d in (select case +count(*) when count(distinct 11) then count(*) else (min(11)) end from t1 union select max( -11) from t1) or 11<> -t1.f then t1.d when t1.b in (13,a,d) then c else c end+t1.b=b) then e-c else (t1.d) end>t1.d),d))/abs(t1.f)) and 11 in (select -t1.a from t1 union select 13 from t1)))} +} {589} +do_test randexpr-2.131 { + db eval {SELECT a+case when exists(select 1 from t1 where 19>=e) then b*b+coalesce((select max( -coalesce((select max(19 & t1.e) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where +case t1.a when a then a else (17) end*19 in (select max(d) from t1 union select max(t1.a) from t1) and not exists(select 1 from t1 where t1.a<=11)) or 11>(19))),11* -a)) from t1 where t1.e<>17),f) else t1.e end-11 FROM t1 WHERE NOT ((t1.a>=(abs(coalesce((select +13*t1.a | c from t1 where 11+case when exists(select 1 from t1 where case when +t1.d in (select case +count(*) when count(distinct 11) then count(*) else (min(11)) end from t1 union select max( -11) from t1) or 11<> -t1.f then t1.d when t1.b in (13,a,d) then c else c end+t1.b=b) then e-c else (t1.d) end>t1.d),d))/abs(t1.f)) and 11 in (select -t1.a from t1 union select 13 from t1)))} +} {589} +do_test randexpr-2.132 { + db eval {SELECT case ~13 when t1.e then e else (select case case (abs(count(*))-~count(*)+count(*) | count(*)-count(*)+max(t1.b)* -(cast(avg(13) AS integer)) | -(count(distinct t1.c))) when min(e) then (min(13)) else count(*) end*count(*) when max(e) then count(distinct -d) else count(*) end from t1) end-t1.d*case (abs(e | t1.b)/abs((select cast(avg(t1.c) AS integer) from t1))) when (select cast(avg(a) AS integer) from t1) then t1.c else f+13 end FROM t1 WHERE not exists(select 1 from t1 where coalesce((select case when t1.a>t1.f-~case when ~t1.d+c+t1.f>11 then t1.a when (f between t1.f and t1.c) then t1.f else 13 end*t1.a then t1.d when c19 then c else t1.e end from t1 where e<>a and 19<>t1.f),t1.b)+t1.f-t1.et1.f-~case when ~t1.d+c+t1.f>11 then t1.a when (f between t1.f and t1.c) then t1.f else 13 end*t1.a then t1.d when c19 then c else t1.e end from t1 where e<>a and 19<>t1.f),t1.b)+t1.f-t1.et1.f-~case when ~t1.d+c+t1.f>11 then t1.a when (f between t1.f and t1.c) then t1.f else 13 end*t1.a then t1.d when c19 then c else t1.e end from t1 where e<>a and 19<>t1.f),t1.b)+t1.f-t1.et1.c and 11<>e then 13 else a end-(a))-max(t1.e)*count(distinct t1.f) | case max((f)) when (count(distinct f)) then count(*) else min(t1.c) end+min(19) from t1) not in (11,19,t1.e)),t1.f*17))/abs(a)))/abs(c)) in (select t1.c from t1 union select t1.a from t1)) or ( -t1.f=e)} +} {} +do_test randexpr-2.136 { + db eval {SELECT 11-case when 17<=c and (select ( -abs(case count(*)+~case -min(e) when count(distinct t1.a) then -count(*) else min(a) end+max(t1.c) when count(*) then max(b) else -count(distinct 19) end)*cast(avg(17) AS integer)) from t1) not in (case f when e then 19 | 11 else (t1.d) end,d, -t1.b) then +t1.c when t1.d not in (11,c,t1.a) then 13 else a end-t1.d*t1.d FROM t1 WHERE NOT (((abs((abs(coalesce((select a from t1 where (select max(case when t1.f=b then e when 11>t1.c and 11<>e then 13 else a end-(a))-max(t1.e)*count(distinct t1.f) | case max((f)) when (count(distinct f)) then count(*) else min(t1.c) end+min(19) from t1) not in (11,19,t1.e)),t1.f*17))/abs(a)))/abs(c)) in (select t1.c from t1 union select t1.a from t1)) or ( -t1.f=e))} +} {-160289} +do_test randexpr-2.137 { + db eval {SELECT 11-case when 17<=c and (select ( -abs(case count(*)+~case -min(e) when count(distinct t1.a) then -count(*) else min(a) end+max(t1.c) when count(*) then max(b) else -count(distinct 19) end)*cast(avg(17) AS integer)) from t1) not in (case f when e then 19 & 11 else (t1.d) end,d, -t1.b) then +t1.c when t1.d not in (11,c,t1.a) then 13 else a end-t1.d*t1.d FROM t1 WHERE NOT (((abs((abs(coalesce((select a from t1 where (select max(case when t1.f=b then e when 11>t1.c and 11<>e then 13 else a end-(a))-max(t1.e)*count(distinct t1.f) | case max((f)) when (count(distinct f)) then count(*) else min(t1.c) end+min(19) from t1) not in (11,19,t1.e)),t1.f*17))/abs(a)))/abs(c)) in (select t1.c from t1 union select t1.a from t1)) or ( -t1.f=e))} +} {-160289} +do_test randexpr-2.138 { + db eval {SELECT (f+case +t1.e when t1.d then 17 else f*19 end | -(abs( -coalesce((select 17* -c+19 from t1 where (abs(case 19*e*d when (select +(cast(avg( -11) AS integer)) | -count(*)*max( -13) from t1) then 11 | case t1.b when a then a else t1.f end else t1.a end)/abs(a)) in (select t1.b from t1 union select (a) from t1)),t1.b))/abs( -13))) FROM t1 WHERE +b in (select case case case when not ((~coalesce((select t1.e+d from t1 where (19 between f and t1.b)),(select cast(avg(c+t1.b) AS integer)++cast(avg(b) AS integer) from t1))) not in (t1.c+c,b,e)) or (13 not between d and t1.d) then 13 else b end when -11 then 13 else 19 end*t1.e when (f) then 19 else 19 end from t1 union select f from t1)} +} {} +do_test randexpr-2.139 { + db eval {SELECT (f+case +t1.e when t1.d then 17 else f*19 end | -(abs( -coalesce((select 17* -c+19 from t1 where (abs(case 19*e*d when (select +(cast(avg( -11) AS integer)) | -count(*)*max( -13) from t1) then 11 | case t1.b when a then a else t1.f end else t1.a end)/abs(a)) in (select t1.b from t1 union select (a) from t1)),t1.b))/abs( -13))) FROM t1 WHERE NOT (+b in (select case case case when not ((~coalesce((select t1.e+d from t1 where (19 between f and t1.b)),(select cast(avg(c+t1.b) AS integer)++cast(avg(b) AS integer) from t1))) not in (t1.c+c,b,e)) or (13 not between d and t1.d) then 13 else b end when -11 then 13 else 19 end*t1.e when (f) then 19 else 19 end from t1 union select f from t1))} +} {-15} +do_test randexpr-2.140 { + db eval {SELECT (f+case +t1.e when t1.d then 17 else f*19 end & -(abs( -coalesce((select 17* -c+19 from t1 where (abs(case 19*e*d when (select +(cast(avg( -11) AS integer)) & -count(*)*max( -13) from t1) then 11 & case t1.b when a then a else t1.f end else t1.a end)/abs(a)) in (select t1.b from t1 union select (a) from t1)),t1.b))/abs( -13))) FROM t1 WHERE NOT (+b in (select case case case when not ((~coalesce((select t1.e+d from t1 where (19 between f and t1.b)),(select cast(avg(c+t1.b) AS integer)++cast(avg(b) AS integer) from t1))) not in (t1.c+c,b,e)) or (13 not between d and t1.d) then 13 else b end when -11 then 13 else 19 end*t1.e when (f) then 19 else 19 end from t1 union select f from t1))} +} {12000} +do_test randexpr-2.141 { + db eval {SELECT 11*coalesce((select max(t1.f) from t1 where a-case t1.c when +coalesce((select t1.a-t1.b from t1 where (abs(19)/abs(b)) in (17-case when a17),d)*(t1.e) FROM t1 WHERE (coalesce((select max(~t1.b) from t1 where t1.c in (select ~+case count(distinct a) when (max(t1.a)) then (count(*)) else ~+abs(cast(avg(d | t1.a) AS integer)+case (cast(avg(13) AS integer)) when cast(avg(b) AS integer) then cast(avg(t1.f) AS integer) else min(t1.a) end) | count(distinct c)*( -( -max(t1.f)))*count(*) end from t1 union select count(distinct -e) from t1)),~a-11)<19 or t1.a*13<>t1.d and not exists(select 1 from t1 where t1.e=e))} +} {3300000} +do_test randexpr-2.142 { + db eval {SELECT 11*coalesce((select max(t1.f) from t1 where a-case t1.c when +coalesce((select t1.a-t1.b from t1 where (abs(19)/abs(b)) in (17-case when a17),d)*(t1.e) FROM t1 WHERE NOT ((coalesce((select max(~t1.b) from t1 where t1.c in (select ~+case count(distinct a) when (max(t1.a)) then (count(*)) else ~+abs(cast(avg(d | t1.a) AS integer)+case (cast(avg(13) AS integer)) when cast(avg(b) AS integer) then cast(avg(t1.f) AS integer) else min(t1.a) end) | count(distinct c)*( -( -max(t1.f)))*count(*) end from t1 union select count(distinct -e) from t1)),~a-11)<19 or t1.a*13<>t1.d and not exists(select 1 from t1 where t1.e=e)))} +} {} +do_test randexpr-2.143 { + db eval {SELECT 11+t1.b+17+case when 13 not between t1.d*(17)+d-t1.f and 13 then t1.d when case when case when t1.f not in (t1.b,c,t1.f) and -d between d and 11 then d else 19 end not between a and e then t1.b when t1.d in (17,13,11) then 19 else t1.e end*a>e then t1.a else t1.d end*f*e FROM t1 WHERE not exists(select 1 from t1 where (t1.f) in (b-b,(select +(max( -13*t1.c*c+t1.e+case t1.a when +t1.d-(c) then -t1.a else t1.c end | 19* -17)*count(distinct a) | (count(distinct t1.f)))++cast(avg(f) AS integer)-max(13) | cast(avg(b) AS integer) from t1),t1.f))} +} {} +do_test randexpr-2.144 { + db eval {SELECT 11+t1.b+17+case when 13 not between t1.d*(17)+d-t1.f and 13 then t1.d when case when case when t1.f not in (t1.b,c,t1.f) and -d between d and 11 then d else 19 end not between a and e then t1.b when t1.d in (17,13,11) then 19 else t1.e end*a>e then t1.a else t1.d end*f*e FROM t1 WHERE NOT (not exists(select 1 from t1 where (t1.f) in (b-b,(select +(max( -13*t1.c*c+t1.e+case t1.a when +t1.d-(c) then -t1.a else t1.c end | 19* -17)*count(distinct a) | (count(distinct t1.f)))++cast(avg(f) AS integer)-max(13) | cast(avg(b) AS integer) from t1),t1.f)))} +} {120000228} +do_test randexpr-2.145 { + db eval {SELECT ((abs(+((select count(*)*abs(min((abs(case (abs(c)/abs(f)) | e when case when 19>=d then 13 when a=f then 13 else f end then b else a end+t1.a)/abs(11))*t1.c*17))-cast(avg(e) AS integer)*count(*) from t1)))/abs(coalesce((select max(case when t1.a in (select t1.c from t1 union select 19 from t1) then e else t1.e end) from t1 where (t1.a<= -t1.e)),17)+c*13))) FROM t1 WHERE exists(select 1 from t1 where ~coalesce((select max(c) from t1 where exists(select 1 from t1 where case when not case coalesce((select max(coalesce((select d from t1 where exists(select 1 from t1 where a<(t1.c))),19)) from t1 where e=t1.e),13) when t1.e then t1.b else f end in (select abs((min(e))*(max(t1.d))+min(t1.e)*(( -((max(t1.a)))))) from t1 union select count(distinct t1.a) from t1) then coalesce((select t1.c from t1 where t1.a< -t1.c and a in (t1.b,t1.f,t1.c)),17) else 17 end>=t1.f)),t1.f)+t1.a*b in (select c from t1 union select 19 from t1)) or exists(select 1 from t1 where not t1.f not in (t1.f,11,t1.d) and 19<=19)} +} {23} +do_test randexpr-2.146 { + db eval {SELECT ((abs(+((select count(*)*abs(min((abs(case (abs(c)/abs(f)) | e when case when 19>=d then 13 when a=f then 13 else f end then b else a end+t1.a)/abs(11))*t1.c*17))-cast(avg(e) AS integer)*count(*) from t1)))/abs(coalesce((select max(case when t1.a in (select t1.c from t1 union select 19 from t1) then e else t1.e end) from t1 where (t1.a<= -t1.e)),17)+c*13))) FROM t1 WHERE NOT (exists(select 1 from t1 where ~coalesce((select max(c) from t1 where exists(select 1 from t1 where case when not case coalesce((select max(coalesce((select d from t1 where exists(select 1 from t1 where a<(t1.c))),19)) from t1 where e=t1.e),13) when t1.e then t1.b else f end in (select abs((min(e))*(max(t1.d))+min(t1.e)*(( -((max(t1.a)))))) from t1 union select count(distinct t1.a) from t1) then coalesce((select t1.c from t1 where t1.a< -t1.c and a in (t1.b,t1.f,t1.c)),17) else 17 end>=t1.f)),t1.f)+t1.a*b in (select c from t1 union select 19 from t1)) or exists(select 1 from t1 where not t1.f not in (t1.f,11,t1.d) and 19<=19))} +} {} +do_test randexpr-2.147 { + db eval {SELECT ((abs(+((select count(*)*abs(min((abs(case (abs(c)/abs(f)) & e when case when 19>=d then 13 when a=f then 13 else f end then b else a end+t1.a)/abs(11))*t1.c*17))-cast(avg(e) AS integer)*count(*) from t1)))/abs(coalesce((select max(case when t1.a in (select t1.c from t1 union select 19 from t1) then e else t1.e end) from t1 where (t1.a<= -t1.e)),17)+c*13))) FROM t1 WHERE exists(select 1 from t1 where ~coalesce((select max(c) from t1 where exists(select 1 from t1 where case when not case coalesce((select max(coalesce((select d from t1 where exists(select 1 from t1 where a<(t1.c))),19)) from t1 where e=t1.e),13) when t1.e then t1.b else f end in (select abs((min(e))*(max(t1.d))+min(t1.e)*(( -((max(t1.a)))))) from t1 union select count(distinct t1.a) from t1) then coalesce((select t1.c from t1 where t1.a< -t1.c and a in (t1.b,t1.f,t1.c)),17) else 17 end>=t1.f)),t1.f)+t1.a*b in (select c from t1 union select 19 from t1)) or exists(select 1 from t1 where not t1.f not in (t1.f,11,t1.d) and 19<=19)} +} {23} +do_test randexpr-2.148 { + db eval {SELECT coalesce((select max(case when t1.f between 17 and 11+case when not coalesce((select max(11) from t1 where t1.f in (select max(t1.d) from t1 union select -count(*) from t1) or 17=(13) or f in (( -t1.b),13,a)),case when d>13 then 13 else 11 end) between 19 and 19 then 19 when t1.c=d then e else 17 end then t1.e else t1.d end) from t1 where e in (select -(+max(11)-max((t1.a))+ -count(distinct d) | cast(avg(t1.a) AS integer)*count(distinct b))-count(*)* -count(distinct t1.e) from t1 union select cast(avg(d) AS integer) from t1)),d)+b FROM t1 WHERE (select +~abs( -min(t1.a)-abs(count(*)))+ -abs(+ -+case (cast(avg(a) AS integer)) when min(e+t1.d) then +case cast(avg(coalesce((select max(t1.f+ -t1.e) from t1 where t1.c between 13 and t1.b),19)) AS integer) when ~~min(t1.f) then count(distinct 13) else cast(avg(t1.b) AS integer) end+count(distinct t1.e) else -count(*) end | max(a)+max(t1.e)) from t1)+e13 then 13 else 11 end) between 19 and 19 then 19 when t1.c=d then e else 17 end then t1.e else t1.d end) from t1 where e in (select -(+max(11)-max((t1.a))+ -count(distinct d) | cast(avg(t1.a) AS integer)*count(distinct b))-count(*)* -count(distinct t1.e) from t1 union select cast(avg(d) AS integer) from t1)),d)+b FROM t1 WHERE NOT ((select +~abs( -min(t1.a)-abs(count(*)))+ -abs(+ -+case (cast(avg(a) AS integer)) when min(e+t1.d) then +case cast(avg(coalesce((select max(t1.f+ -t1.e) from t1 where t1.c between 13 and t1.b),19)) AS integer) when ~~min(t1.f) then count(distinct 13) else cast(avg(t1.b) AS integer) end+count(distinct t1.e) else -count(*) end | max(a)+max(t1.e)) from t1)+e13 then 13 else 11 end) between 19 and 19 then 19 when t1.c=d then e else 17 end then t1.e else t1.d end) from t1 where e in (select -(+max(11)-max((t1.a))+ -count(distinct d) & cast(avg(t1.a) AS integer)*count(distinct b))-count(*)* -count(distinct t1.e) from t1 union select cast(avg(d) AS integer) from t1)),d)+b FROM t1 WHERE (select +~abs( -min(t1.a)-abs(count(*)))+ -abs(+ -+case (cast(avg(a) AS integer)) when min(e+t1.d) then +case cast(avg(coalesce((select max(t1.f+ -t1.e) from t1 where t1.c between 13 and t1.b),19)) AS integer) when ~~min(t1.f) then count(distinct 13) else cast(avg(t1.b) AS integer) end+count(distinct t1.e) else -count(*) end | max(a)+max(t1.e)) from t1)+ed or t1.a not between b and 13 or f<> -19 and t1.b>a} +} {11} +do_test randexpr-2.152 { + db eval {SELECT case when ((+b in (select min(coalesce((select c from t1 where t1.b-t1.c+coalesce((select max(case when 13 in (select -count(distinct b)*max(c) from t1 union select (( - -cast(avg(d) AS integer))) from t1) then b else t1.f end) from t1 where t1.fd or t1.a not between b and 13 or f<> -19 and t1.b>a)} +} {} +do_test randexpr-2.153 { + db eval {SELECT case when ((+b in (select min(coalesce((select c from t1 where t1.b-t1.c+coalesce((select max(case when 13 in (select -count(distinct b)*max(c) from t1 union select (( - -cast(avg(d) AS integer))) from t1) then b else t1.f end) from t1 where t1.fd or t1.a not between b and 13 or f<> -19 and t1.b>a} +} {11} +do_test randexpr-2.154 { + db eval {SELECT case when t1.a | (abs(case when -t1.e in (17,11,(abs(t1.b)/abs(b+case when (17 in (select f-c from t1 union select -a from t1)) or t1.b<=a then d when t1.e in (select -(count(*)) from t1 union select max(t1.b) from t1) then c else c end*a-t1.f))) then t1.b else t1.e end)/abs(t1.f))>=11 and not exists(select 1 from t1 where exists(select 1 from t1 where t1.d in (select t1.d from t1 union select 17 from t1))) then c else t1.c end FROM t1 WHERE (coalesce((select f from t1 where case a-e+a when (abs(t1.d)/abs((coalesce((select ~t1.e*+t1.a+b*a*(abs(19)/abs(a))*a+e from t1 where 13=13 or t1.b<= -19),t1.f)+17* -t1.c=11 and not exists(select 1 from t1 where exists(select 1 from t1 where t1.d in (select t1.d from t1 union select 17 from t1))) then c else t1.c end FROM t1 WHERE NOT ((coalesce((select f from t1 where case a-e+a when (abs(t1.d)/abs((coalesce((select ~t1.e*+t1.a+b*a*(abs(19)/abs(a))*a+e from t1 where 13=13 or t1.b<= -19),t1.f)+17* -t1.c=11 and not exists(select 1 from t1 where exists(select 1 from t1 where t1.d in (select t1.d from t1 union select 17 from t1))) then c else t1.c end FROM t1 WHERE (coalesce((select f from t1 where case a-e+a when (abs(t1.d)/abs((coalesce((select ~t1.e*+t1.a+b*a*(abs(19)/abs(a))*a+e from t1 where 13=13 or t1.b<= -19),t1.f)+17* -t1.c~a-11),t1.f) end)} +} {100} +do_test randexpr-2.158 { + db eval {SELECT coalesce((select max(~t1.b) from t1 where b in (select count(distinct b) from t1 union select max(case coalesce((select max(b) from t1 where d in (select t1.f from t1 union select d from t1) and t1.a=d),t1.a) when -t1.a then d*t1.e+t1.c-11+b | e-t1.a+e+t1.f else c end) from t1)),t1.a) FROM t1 WHERE NOT ((e~a-11),t1.f) end))} +} {} +do_test randexpr-2.159 { + db eval {SELECT coalesce((select max(~t1.b) from t1 where b in (select count(distinct b) from t1 union select max(case coalesce((select max(b) from t1 where d in (select t1.f from t1 union select d from t1) and t1.a=d),t1.a) when -t1.a then d*t1.e+t1.c-11+b & e-t1.a+e+t1.f else c end) from t1)),t1.a) FROM t1 WHERE (e~a-11),t1.f) end)} +} {100} +do_test randexpr-2.160 { + db eval {SELECT case when not t1.c not in (13,d,~case when coalesce((select max((abs(t1.c)/abs(t1.e))) from t1 where b-t1.d+b+t1.f>a),t1.a) in (select 19 from t1 union select t1.a from t1) then -b else a end*b | d) and -(t1.b)>=e and 11 -t1.c then t1.f else t1.f end+(t1.b)+a FROM t1 WHERE e>e} +} {} +do_test randexpr-2.161 { + db eval {SELECT case when not t1.c not in (13,d,~case when coalesce((select max((abs(t1.c)/abs(t1.e))) from t1 where b-t1.d+b+t1.f>a),t1.a) in (select 19 from t1 union select t1.a from t1) then -b else a end*b | d) and -(t1.b)>=e and 11 -t1.c then t1.f else t1.f end+(t1.b)+a FROM t1 WHERE NOT (e>e)} +} {900} +do_test randexpr-2.162 { + db eval {SELECT case when not t1.c not in (13,d,~case when coalesce((select max((abs(t1.c)/abs(t1.e))) from t1 where b-t1.d+b+t1.f>a),t1.a) in (select 19 from t1 union select t1.a from t1) then -b else a end*b & d) and -(t1.b)>=e and 11 -t1.c then t1.f else t1.f end+(t1.b)+a FROM t1 WHERE NOT (e>e)} +} {900} +do_test randexpr-2.163 { + db eval {SELECT coalesce((select t1.c*c from t1 where (select (abs(cast(avg(b*13) AS integer))) from t1) in (select 11 from t1 union select e | a-17 from t1)), -case t1.c when t1.b++(select cast(avg(e) AS integer) from t1) then 17 else t1.b end)-d FROM t1 WHERE b<=t1.d} +} {-600} +do_test randexpr-2.164 { + db eval {SELECT coalesce((select t1.c*c from t1 where (select (abs(cast(avg(b*13) AS integer))) from t1) in (select 11 from t1 union select e | a-17 from t1)), -case t1.c when t1.b++(select cast(avg(e) AS integer) from t1) then 17 else t1.b end)-d FROM t1 WHERE NOT (b<=t1.d)} +} {} +do_test randexpr-2.165 { + db eval {SELECT coalesce((select t1.c*c from t1 where (select (abs(cast(avg(b*13) AS integer))) from t1) in (select 11 from t1 union select e & a-17 from t1)), -case t1.c when t1.b++(select cast(avg(e) AS integer) from t1) then 17 else t1.b end)-d FROM t1 WHERE b<=t1.d} +} {-600} +do_test randexpr-2.166 { + db eval {SELECT coalesce((select max((case (abs(t1.b)/abs(e)) when 13 then ((select +case count(*)*count(distinct coalesce((select max((11)+b) from t1 where exists(select 1 from t1 where t1.e=(t1.b))), -13)) when count(distinct -c) then count(*)*max( -d) else max((a)) end+min(c) from t1)) else t1.a end-(abs(case when a=17 and e<=b then a when a>=e then t1.c else t1.c end+13)/abs(e))*(e))) from t1 where t1.a in (select d from t1 union select -t1.e from t1)),13) FROM t1 WHERE not coalesce((select max(case when f<=d | b | case when case when (t1.c in (f,19,c)) then t1.f when d>t1.b then t1.f else t1.f end<=c then 11 else c end- -t1.c-13 and t1.c in (select b from t1 union select -17 from t1) then t1.b else a end) from t1 where 11 between d and a), -17) not between t1.f and t1.f and t1.f>11 or (not exists(select 1 from t1 where t1.b in (select min(t1.d) from t1 union select min(c) from t1)))} +} {13} +do_test randexpr-2.167 { + db eval {SELECT coalesce((select max((case (abs(t1.b)/abs(e)) when 13 then ((select +case count(*)*count(distinct coalesce((select max((11)+b) from t1 where exists(select 1 from t1 where t1.e=(t1.b))), -13)) when count(distinct -c) then count(*)*max( -d) else max((a)) end+min(c) from t1)) else t1.a end-(abs(case when a=17 and e<=b then a when a>=e then t1.c else t1.c end+13)/abs(e))*(e))) from t1 where t1.a in (select d from t1 union select -t1.e from t1)),13) FROM t1 WHERE NOT (not coalesce((select max(case when f<=d | b | case when case when (t1.c in (f,19,c)) then t1.f when d>t1.b then t1.f else t1.f end<=c then 11 else c end- -t1.c-13 and t1.c in (select b from t1 union select -17 from t1) then t1.b else a end) from t1 where 11 between d and a), -17) not between t1.f and t1.f and t1.f>11 or (not exists(select 1 from t1 where t1.b in (select min(t1.d) from t1 union select min(c) from t1))))} +} {} +do_test randexpr-2.168 { + db eval {SELECT case when ((t1.e | (select min( -t1.f) from t1)*((abs(b)/abs(19)))-b<=t1.b and not e>13 or -f in (select count(distinct e)-min(t1.a) from t1 union select count(distinct f) from t1))) then 13 when 17 between f and 19 or 11 between b and 19 or not t1.f>e then t1.d else d | f end FROM t1 WHERE not case when t1.a=t1.a then c when ~case when case when t1.e in (select + -count(distinct t1.d) from t1 union select cast(avg(t1.a) AS integer) from t1) then (t1.e) when 17 in (13, -f,a) then t1.d else d end<17 then e else f end+17+a* -e+b+b>t1.e then t1.e else t1.a end13 or -f in (select count(distinct e)-min(t1.a) from t1 union select count(distinct f) from t1))) then 13 when 17 between f and 19 or 11 between b and 19 or not t1.f>e then t1.d else d | f end FROM t1 WHERE NOT (not case when t1.a=t1.a then c when ~case when case when t1.e in (select + -count(distinct t1.d) from t1 union select cast(avg(t1.a) AS integer) from t1) then (t1.e) when 17 in (13, -f,a) then t1.d else d end<17 then e else f end+17+a* -e+b+b>t1.e then t1.e else t1.a end13 or -f in (select count(distinct e)-min(t1.a) from t1 union select count(distinct f) from t1))) then 13 when 17 between f and 19 or 11 between b and 19 or not t1.f>e then t1.d else d & f end FROM t1 WHERE NOT (not case when t1.a=t1.a then c when ~case when case when t1.e in (select + -count(distinct t1.d) from t1 union select cast(avg(t1.a) AS integer) from t1) then (t1.e) when 17 in (13, -f,a) then t1.d else d end<17 then e else f end+17+a* -e+b+b>t1.e then t1.e else t1.a enda and 19 between 11 and b and 11 between a and b)),t1.f) | c in ( -t1.c,13,b) then 11 when f in (select min(t1.d) from t1 union select cast(avg(f) AS integer) from t1) then t1.b else a end and t1.a),t1.c))/abs(11))+ -f} +} {} +do_test randexpr-2.172 { + db eval {SELECT coalesce((select (select cast(avg(~13) AS integer)-count(distinct ~19-coalesce((select d-17 from t1 where case when (case 17 when b then d else (select min(11) | min(17) from t1)++t1.a end in (d, -c,t1.d)) then b else t1.c end between t1.a and (t1.e)),19)-t1.f) from t1) | (abs(t1.e)/abs(t1.e)) from t1 where (t1.c not in (( -t1.d),(t1.b),(d)))),t1.e) FROM t1 WHERE NOT (13 between 19 and ~ -(abs( -t1.d | coalesce((select t1.f from t1 where 19 not between + -case when ~~b+coalesce((select max(t1.d) from t1 where exists(select 1 from t1 where (select cast(avg(19) AS integer)-cast(avg(b) AS integer) from t1)<>a and 19 between 11 and b and 11 between a and b)),t1.f) | c in ( -t1.c,13,b) then 11 when f in (select min(t1.d) from t1 union select cast(avg(f) AS integer) from t1) then t1.b else a end and t1.a),t1.c))/abs(11))+ -f)} +} {-15} +do_test randexpr-2.173 { + db eval {SELECT coalesce((select (select cast(avg(~13) AS integer)-count(distinct ~19-coalesce((select d-17 from t1 where case when (case 17 when b then d else (select min(11) & min(17) from t1)++t1.a end in (d, -c,t1.d)) then b else t1.c end between t1.a and (t1.e)),19)-t1.f) from t1) & (abs(t1.e)/abs(t1.e)) from t1 where (t1.c not in (( -t1.d),(t1.b),(d)))),t1.e) FROM t1 WHERE NOT (13 between 19 and ~ -(abs( -t1.d | coalesce((select t1.f from t1 where 19 not between + -case when ~~b+coalesce((select max(t1.d) from t1 where exists(select 1 from t1 where (select cast(avg(19) AS integer)-cast(avg(b) AS integer) from t1)<>a and 19 between 11 and b and 11 between a and b)),t1.f) | c in ( -t1.c,13,b) then 11 when f in (select min(t1.d) from t1 union select cast(avg(f) AS integer) from t1) then t1.b else a end and t1.a),t1.c))/abs(11))+ -f)} +} {1} +do_test randexpr-2.174 { + db eval {SELECT coalesce((select max(+(d+a)*b) from t1 where (case e-t1.b when 17+11*13 then t1.a else 17 end-(17)<>(select cast(avg(t1.f) AS integer) from t1))),case when case when 11+13<>19 then 13 else t1.f end*e in (a,t1.f,t1.c) and not exists(select 1 from t1 where t1.b in (select - -count(distinct t1.b)*( -count(*)) from t1 union select count(distinct t1.e) from t1)) then t1.c else a end) FROM t1 WHERE case when t1.d in (select count(*)-count(*)+ -min(case d when t1.c then 19 else 11 end)*count(*) | min(19)-(max((e))) from t1 union select count(*) from t1) then c when exists(select 1 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (abs(b)/abs(t1.c))>coalesce((select max(f) from t1 where f<=t1.a),t1.d)))) then f*t1.c+11 else t1.f end+e-e*t1.f<=17} +} {100000} +do_test randexpr-2.175 { + db eval {SELECT coalesce((select max(+(d+a)*b) from t1 where (case e-t1.b when 17+11*13 then t1.a else 17 end-(17)<>(select cast(avg(t1.f) AS integer) from t1))),case when case when 11+13<>19 then 13 else t1.f end*e in (a,t1.f,t1.c) and not exists(select 1 from t1 where t1.b in (select - -count(distinct t1.b)*( -count(*)) from t1 union select count(distinct t1.e) from t1)) then t1.c else a end) FROM t1 WHERE NOT (case when t1.d in (select count(*)-count(*)+ -min(case d when t1.c then 19 else 11 end)*count(*) | min(19)-(max((e))) from t1 union select count(*) from t1) then c when exists(select 1 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (abs(b)/abs(t1.c))>coalesce((select max(f) from t1 where f<=t1.a),t1.d)))) then f*t1.c+11 else t1.f end+e-e*t1.f<=17)} +} {} +do_test randexpr-2.176 { + db eval {SELECT t1.c*case when t1.e>(select +cast(avg(13) AS integer)*min((11)* - -d | - -coalesce((select max(b) from t1 where (select cast(avg((abs(a)/abs(b-(e)))) AS integer) from t1)+11*c=a then t1.b else t1.b end | 19+a-c)*count(distinct t1.d)-+count(distinct t1.d) from t1) not in (19,d,b) and t1.f not between b and t1.f)))))} +} {} +do_test randexpr-2.177 { + db eval {SELECT t1.c*case when t1.e>(select +cast(avg(13) AS integer)*min((11)* - -d | - -coalesce((select max(b) from t1 where (select cast(avg((abs(a)/abs(b-(e)))) AS integer) from t1)+11*c=a then t1.b else t1.b end | 19+a-c)*count(distinct t1.d)-+count(distinct t1.d) from t1) not in (19,d,b) and t1.f not between b and t1.f))))))} +} {90000} +do_test randexpr-2.178 { + db eval {SELECT t1.c*case when t1.e>(select +cast(avg(13) AS integer)*min((11)* - -d & - -coalesce((select max(b) from t1 where (select cast(avg((abs(a)/abs(b-(e)))) AS integer) from t1)+11*c=a then t1.b else t1.b end | 19+a-c)*count(distinct t1.d)-+count(distinct t1.d) from t1) not in (19,d,b) and t1.f not between b and t1.f))))))} +} {120000} +do_test randexpr-2.179 { + db eval {SELECT case when not exists(select 1 from t1 where (not exists(select 1 from t1 where not exists(select 1 from t1 where not d*19=b))) or t1.a-a-t1.d*t1.f in (select ~case cast(avg(t1.d) AS integer) | count(*)+max(t1.c) when max(17) then cast(avg( -f) AS integer) else -min(e) end from t1 union select max( -13) from t1)) then (select abs((+ -min(a)) | min(t1.a)-cast(avg(t1.f) AS integer)) | max(e) from t1) else 11 end*a | t1.a*f FROM t1 WHERE t1.c in (c,t1.b,~e) and 13+19-t1.b | coalesce((select max(case d when +t1.e+13*13 then coalesce((select case when f=e or -f<=e and t1.d<>19),d) else d end) from t1 where t1.d=e or -f<=e and t1.d<>19),d) else d end) from t1 where t1.d=e or -f<=e and t1.d<>19),d) else d end) from t1 where t1.dt1.b then d*t1.f*17 else (b) end)+t1.f*13 when c then t1.a else t1.e end- -t1.f FROM t1 WHERE b-case when t1.b=t1.b and (coalesce((select max(t1.e) from t1 where t1.b in (select ~cast(avg(19) AS integer)+max(t1.b)+min(t1.e) from t1 union select max(t1.a) from t1) or exists(select 1 from t1 where 11 in (select max(t1.e) from t1 union select max(t1.f) from t1))),(abs(17)/abs(17)))) not between c and t1.a then 13 else 13 end | t1.c in (select ++cast(avg(f) AS integer)-(+(count(distinct 13) | max(19))-count(*) | -max(t1.e)) from t1 union select count(*) from t1)} +} {} +do_test randexpr-2.185 { + db eval {SELECT ~case +~c+(case when not exists(select 1 from t1 where t1.d in (select abs( -abs(max(t1.f)-count(distinct e)* -cast(avg(11) AS integer) | count(*))+min(f)*min( -17)*cast(avg(19) AS integer)) from t1 union select count(*) from t1)) or (t1.f)<>t1.b then d*t1.f*17 else (b) end)+t1.f*13 when c then t1.a else t1.e end- -t1.f FROM t1 WHERE NOT (b-case when t1.b=t1.b and (coalesce((select max(t1.e) from t1 where t1.b in (select ~cast(avg(19) AS integer)+max(t1.b)+min(t1.e) from t1 union select max(t1.a) from t1) or exists(select 1 from t1 where 11 in (select max(t1.e) from t1 union select max(t1.f) from t1))),(abs(17)/abs(17)))) not between c and t1.a then 13 else 13 end | t1.c in (select ++cast(avg(f) AS integer)-(+(count(distinct 13) | max(19))-count(*) | -max(t1.e)) from t1 union select count(*) from t1))} +} {99} +do_test randexpr-2.186 { + db eval {SELECT ~case +~c+(case when not exists(select 1 from t1 where t1.d in (select abs( -abs(max(t1.f)-count(distinct e)* -cast(avg(11) AS integer) & count(*))+min(f)*min( -17)*cast(avg(19) AS integer)) from t1 union select count(*) from t1)) or (t1.f)<>t1.b then d*t1.f*17 else (b) end)+t1.f*13 when c then t1.a else t1.e end- -t1.f FROM t1 WHERE NOT (b-case when t1.b=t1.b and (coalesce((select max(t1.e) from t1 where t1.b in (select ~cast(avg(19) AS integer)+max(t1.b)+min(t1.e) from t1 union select max(t1.a) from t1) or exists(select 1 from t1 where 11 in (select max(t1.e) from t1 union select max(t1.f) from t1))),(abs(17)/abs(17)))) not between c and t1.a then 13 else 13 end | t1.c in (select ++cast(avg(f) AS integer)-(+(count(distinct 13) | max(19))-count(*) | -max(t1.e)) from t1 union select count(*) from t1))} +} {99} +do_test randexpr-2.187 { + db eval {SELECT case when t1.c in (select c from t1 union select a from t1) then 11 when ((select max(19) from t1) | t1.a+e not between (case -19 when b*e-b-case when b<>~d*t1.d+t1.c*d then t1.d when t1.c=19 then f else d end-f*t1.d then t1.d else 13 end) and 13) then 11 else t1.b end FROM t1 WHERE t1.b*coalesce((select max(t1.d) from t1 where -f<=(select max(t1.e) from t1)*e),case when case when t1.e- -13>t1.b+t1.f+c then 13 else -d end in (select 19 from t1 union select t1.f from t1) then e when t1.b in (select ~count(distinct t1.a)+count(*) from t1 union select abs( - -((cast(avg(c) AS integer)))*(cast(avg(t1.b) AS integer))) from t1) then 17 else d end)+ -17 | t1.a-t1.d in (t1.e,f,f)} +} {} +do_test randexpr-2.188 { + db eval {SELECT case when t1.c in (select c from t1 union select a from t1) then 11 when ((select max(19) from t1) | t1.a+e not between (case -19 when b*e-b-case when b<>~d*t1.d+t1.c*d then t1.d when t1.c=19 then f else d end-f*t1.d then t1.d else 13 end) and 13) then 11 else t1.b end FROM t1 WHERE NOT (t1.b*coalesce((select max(t1.d) from t1 where -f<=(select max(t1.e) from t1)*e),case when case when t1.e- -13>t1.b+t1.f+c then 13 else -d end in (select 19 from t1 union select t1.f from t1) then e when t1.b in (select ~count(distinct t1.a)+count(*) from t1 union select abs( - -((cast(avg(c) AS integer)))*(cast(avg(t1.b) AS integer))) from t1) then 17 else d end)+ -17 | t1.a-t1.d in (t1.e,f,f))} +} {11} +do_test randexpr-2.189 { + db eval {SELECT case when t1.c in (select c from t1 union select a from t1) then 11 when ((select max(19) from t1) & t1.a+e not between (case -19 when b*e-b-case when b<>~d*t1.d+t1.c*d then t1.d when t1.c=19 then f else d end-f*t1.d then t1.d else 13 end) and 13) then 11 else t1.b end FROM t1 WHERE NOT (t1.b*coalesce((select max(t1.d) from t1 where -f<=(select max(t1.e) from t1)*e),case when case when t1.e- -13>t1.b+t1.f+c then 13 else -d end in (select 19 from t1 union select t1.f from t1) then e when t1.b in (select ~count(distinct t1.a)+count(*) from t1 union select abs( - -((cast(avg(c) AS integer)))*(cast(avg(t1.b) AS integer))) from t1) then 17 else d end)+ -17 | t1.a-t1.d in (t1.e,f,f))} +} {11} +do_test randexpr-2.190 { + db eval {SELECT ~(d)-(select case case cast(avg(t1.b- -~b) AS integer) when max(coalesce((select e from t1 where 11<>e),coalesce((select c from t1 where c not in (t1.e,a,(17)) or t1.b in ((b),t1.c,t1.f)),13))) then +cast(avg(d) AS integer) | case max(t1.c) when min((e)) then max(e)+cast(avg(t1.d) AS integer) else min(t1.f) end+max(d) else count(*) end | -cast(avg(t1.f) AS integer) | - -count(distinct c)*max(b) when count(distinct t1.d) then - -min(a) else count(*) end from t1) FROM t1 WHERE t1.c+a=t1.e+t1.c*t1.e | case t1.d when case when 13 in (select min(c) from t1 union select max(d) from t1) or t1.f>=13 then 19 when t1.c<=11 then -t1.b else 13 end then 13 else t1.e end or f in (select t1.a from t1 union select t1.f from t1) or (t1.at1.b and (((t1.d not between -a and t1.f))) or t1.a not in ( -t1.d,13,a) and de),coalesce((select c from t1 where c not in (t1.e,a,(17)) or t1.b in ((b),t1.c,t1.f)),13))) then +cast(avg(d) AS integer) | case max(t1.c) when min((e)) then max(e)+cast(avg(t1.d) AS integer) else min(t1.f) end+max(d) else count(*) end | -cast(avg(t1.f) AS integer) | - -count(distinct c)*max(b) when count(distinct t1.d) then - -min(a) else count(*) end from t1) FROM t1 WHERE NOT (t1.c+a=t1.e+t1.c*t1.e | case t1.d when case when 13 in (select min(c) from t1 union select max(d) from t1) or t1.f>=13 then 19 when t1.c<=11 then -t1.b else 13 end then 13 else t1.e end or f in (select t1.a from t1 union select t1.f from t1) or (t1.at1.b and (((t1.d not between -a and t1.f))) or t1.a not in ( -t1.d,13,a) and de),coalesce((select c from t1 where c not in (t1.e,a,(17)) or t1.b in ((b),t1.c,t1.f)),13))) then +cast(avg(d) AS integer) & case max(t1.c) when min((e)) then max(e)+cast(avg(t1.d) AS integer) else min(t1.f) end+max(d) else count(*) end & -cast(avg(t1.f) AS integer) & - -count(distinct c)*max(b) when count(distinct t1.d) then - -min(a) else count(*) end from t1) FROM t1 WHERE t1.c+a=t1.e+t1.c*t1.e | case t1.d when case when 13 in (select min(c) from t1 union select max(d) from t1) or t1.f>=13 then 19 when t1.c<=11 then -t1.b else 13 end then 13 else t1.e end or f in (select t1.a from t1 union select t1.f from t1) or (t1.at1.b and (((t1.d not between -a and t1.f))) or t1.a not in ( -t1.d,13,a) and dt1.c or ((t1.f>e)) and t1.e-19+c+ -d*t1.d+11<>17+coalesce((select max(t1.d) from t1 where 17+t1.c11))),11) | case e when c then a else t1.b end+a FROM t1 WHERE case when d not in (a,11,(13)) then a when exists(select 1 from t1 where case when case when case when (t1.c) in (c,e,b) then f else (19) end-t1.f=t1.a then 11 else t1.c end in (select abs(~~max(t1.c)) from t1 union select cast(avg(c) AS integer) from t1)) then 11 else t1.f end in (select (~~count(*)*cast(avg(19) AS integer)) from t1 union select min(t1.d)+ -count(distinct f) from t1)} +} {} +do_test randexpr-2.197 { + db eval {SELECT coalesce((select max(~t1.d) from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where c>t1.c or ((t1.f>e)) and t1.e-19+c+ -d*t1.d+11<>17+coalesce((select max(t1.d) from t1 where 17+t1.c11))),11) | case e when c then a else t1.b end+a FROM t1 WHERE NOT (case when d not in (a,11,(13)) then a when exists(select 1 from t1 where case when case when case when (t1.c) in (c,e,b) then f else (19) end-t1.f=t1.a then 11 else t1.c end in (select abs(~~max(t1.c)) from t1 union select cast(avg(c) AS integer) from t1)) then 11 else t1.f end in (select (~~count(*)*cast(avg(19) AS integer)) from t1 union select min(t1.d)+ -count(distinct f) from t1))} +} {303} +do_test randexpr-2.198 { + db eval {SELECT coalesce((select max(~t1.d) from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where c>t1.c or ((t1.f>e)) and t1.e-19+c+ -d*t1.d+11<>17+coalesce((select max(t1.d) from t1 where 17+t1.c11))),11) & case e when c then a else t1.b end+a FROM t1 WHERE NOT (case when d not in (a,11,(13)) then a when exists(select 1 from t1 where case when case when case when (t1.c) in (c,e,b) then f else (19) end-t1.f=t1.a then 11 else t1.c end in (select abs(~~max(t1.c)) from t1 union select cast(avg(c) AS integer) from t1)) then 11 else t1.f end in (select (~~count(*)*cast(avg(19) AS integer)) from t1 union select min(t1.d)+ -count(distinct f) from t1))} +} {8} +do_test randexpr-2.199 { + db eval {SELECT case when t1.e*t1.b<>e then 19 else -11-b+coalesce((select max(t1.e+t1.f) from t1 where 11+f*t1.c<>t1.a*(~f+case when t1.f in (t1.f, -((13)),19) then t1.a when t1.e>17 then a else a end+b-t1.e-(f))),13)+d end+t1.b* -c FROM t1 WHERE exists(select 1 from t1 where coalesce((select max(t1.a*t1.e+13) from t1 where 13 in ((abs(e)/abs(t1.a)),a+t1.c,17*t1.c)),(select -case max(c) | cast(avg(e) AS integer) when ~+ -count(distinct coalesce((select d from t1 where exists(select 1 from t1 where -17e then 19 else -11-b+coalesce((select max(t1.e+t1.f) from t1 where 11+f*t1.c<>t1.a*(~f+case when t1.f in (t1.f, -((13)),19) then t1.a when t1.e>17 then a else a end+b-t1.e-(f))),13)+d end+t1.b* -c FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select max(t1.a*t1.e+13) from t1 where 13 in ((abs(e)/abs(t1.a)),a+t1.c,17*t1.c)),(select -case max(c) | cast(avg(e) AS integer) when ~+ -count(distinct coalesce((select d from t1 where exists(select 1 from t1 where -17c then t1.b when 17 not between t1.e and c then 11 else f end in (select a from t1 union select 13 from t1))),11)) from t1 where not exists(select 1 from t1 where f=17)),e) FROM t1 WHERE ( -13 in (13,b,case when 19=11 then t1.d else case when (d | b-case when t1.f-(select +abs(cast(avg( -17* -17) AS integer)*count(*)+max(t1.e)) from t1)*t1.f not in (f,a,c) then t1.a else t1.b end between 19 and e) then a else 13 end end-t1.a) or t1.c<19)} +} {} +do_test randexpr-2.202 { + db eval {SELECT coalesce((select max(coalesce((select 19 from t1 where (case when ((abs(coalesce((select max(case when t1.a between (t1.c)+ -b and d then e else d end) from t1 where t1.e in (select (count(*)) from t1 union select max( -a)-count(distinct t1.c)-((min(13))) | max((t1.f)) from t1)),11))/abs(19)))+d>c then t1.b when 17 not between t1.e and c then 11 else f end in (select a from t1 union select 13 from t1))),11)) from t1 where not exists(select 1 from t1 where f=17)),e) FROM t1 WHERE NOT (( -13 in (13,b,case when 19=11 then t1.d else case when (d | b-case when t1.f-(select +abs(cast(avg( -17* -17) AS integer)*count(*)+max(t1.e)) from t1)*t1.f not in (f,a,c) then t1.a else t1.b end between 19 and e) then a else 13 end end-t1.a) or t1.c<19))} +} {11} +do_test randexpr-2.203 { + db eval {SELECT coalesce((select max(coalesce((select 19 from t1 where (case when ((abs(coalesce((select max(case when t1.a between (t1.c)+ -b and d then e else d end) from t1 where t1.e in (select (count(*)) from t1 union select max( -a)-count(distinct t1.c)-((min(13))) & max((t1.f)) from t1)),11))/abs(19)))+d>c then t1.b when 17 not between t1.e and c then 11 else f end in (select a from t1 union select 13 from t1))),11)) from t1 where not exists(select 1 from t1 where f=17)),e) FROM t1 WHERE NOT (( -13 in (13,b,case when 19=11 then t1.d else case when (d | b-case when t1.f-(select +abs(cast(avg( -17* -17) AS integer)*count(*)+max(t1.e)) from t1)*t1.f not in (f,a,c) then t1.a else t1.b end between 19 and e) then a else 13 end end-t1.a) or t1.c<19))} +} {11} +do_test randexpr-2.204 { + db eval {SELECT -~d*19-a-c | t1.c+(abs(case -19 | ~case t1.d when c then t1.f else c end when +t1.d then 17 else case case when b>case case when t1.c=d or -t1.a=17 then ((a)) when t1.a<>d then (t1.c) else a end+19+11 when 19 then t1.a else b end-(t1.e) then f else t1.c end when 17 then t1.b else a end end)/abs(d))+t1.b FROM t1 WHERE t1.f+13<>19} +} {7671} +do_test randexpr-2.205 { + db eval {SELECT -~d*19-a-c | t1.c+(abs(case -19 | ~case t1.d when c then t1.f else c end when +t1.d then 17 else case case when b>case case when t1.c=d or -t1.a=17 then ((a)) when t1.a<>d then (t1.c) else a end+19+11 when 19 then t1.a else b end-(t1.e) then f else t1.c end when 17 then t1.b else a end end)/abs(d))+t1.b FROM t1 WHERE NOT (t1.f+13<>19)} +} {} +do_test randexpr-2.206 { + db eval {SELECT -~d*19-a-c & t1.c+(abs(case -19 & ~case t1.d when c then t1.f else c end when +t1.d then 17 else case case when b>case case when t1.c=d or -t1.a=17 then ((a)) when t1.a<>d then (t1.c) else a end+19+11 when 19 then t1.a else b end-(t1.e) then f else t1.c end when 17 then t1.b else a end end)/abs(d))+t1.b FROM t1 WHERE t1.f+13<>19} +} {48} +do_test randexpr-2.207 { + db eval {SELECT (abs(coalesce((select b from t1 where t1.a>(abs(t1.f)/abs(coalesce((select 13 from t1 where not coalesce((select (select cast(avg(case when case when t1.e not between t1.c and 19 then t1.d when d in (11,t1.b,13) then e else 17 end*b between 13 and (t1.b) then t1.f when a<>19 and t1.c not in (a,t1.f,b) then t1.e else t1.f end) AS integer) from t1)+t1.c-b* -a*f from t1 where (t1.d in (select c from t1 union select t1.b from t1))),t1.e)-c<>c),t1.c)))),e))/abs(t1.e)) FROM t1 WHERE (t1.a-t1.c-case when eb then f else d end | t1.d) AS integer) from t1 union select count(distinct 11) from t1)),c) else t1.f end when f then 19 else t1.b end(abs(t1.f)/abs(coalesce((select 13 from t1 where not coalesce((select (select cast(avg(case when case when t1.e not between t1.c and 19 then t1.d when d in (11,t1.b,13) then e else 17 end*b between 13 and (t1.b) then t1.f when a<>19 and t1.c not in (a,t1.f,b) then t1.e else t1.f end) AS integer) from t1)+t1.c-b* -a*f from t1 where (t1.d in (select c from t1 union select t1.b from t1))),t1.e)-c<>c),t1.c)))),e))/abs(t1.e)) FROM t1 WHERE NOT ((t1.a-t1.c-case when eb then f else d end | t1.d) AS integer) from t1 union select count(distinct 11) from t1)),c) else t1.f end when f then 19 else t1.b endd then case 11 when ~+case t1.a when (abs(t1.a)/abs( -c))*t1.c+ -a+coalesce((select t1.c from t1 where ((abs(e)/abs((case when (11>=e) then -17 when (11)<=a then e else b end)+t1.f))>19)),b)-d then c else 17 end+ -b then ( -t1.a) else c end when 11<=t1.f then 11 else 17 end FROM t1 WHERE (coalesce((select max(17) from t1 where ~case ((select min( -e-a)*+cast(avg(11) AS integer)*count(*)-(count(*))*max(b)*min( -13)+count(*)-min( -13) from t1)+19)+a when e then (select min(f) from t1) else coalesce((select t1.f from t1 where 17>t1.c),19) end=11 and f=t1.b),19) not between -a and t1.a)} +} {} +do_test randexpr-2.210 { + db eval {SELECT case when t1.d<>d then case 11 when ~+case t1.a when (abs(t1.a)/abs( -c))*t1.c+ -a+coalesce((select t1.c from t1 where ((abs(e)/abs((case when (11>=e) then -17 when (11)<=a then e else b end)+t1.f))>19)),b)-d then c else 17 end+ -b then ( -t1.a) else c end when 11<=t1.f then 11 else 17 end FROM t1 WHERE NOT ((coalesce((select max(17) from t1 where ~case ((select min( -e-a)*+cast(avg(11) AS integer)*count(*)-(count(*))*max(b)*min( -13)+count(*)-min( -13) from t1)+19)+a when e then (select min(f) from t1) else coalesce((select t1.f from t1 where 17>t1.c),19) end=11 and f=t1.b),19) not between -a and t1.a))} +} {11} +do_test randexpr-2.211 { + db eval {SELECT coalesce((select max(t1.e) from t1 where not d in (select (abs(t1.f)/abs(~case when (abs(t1.e)/abs( -t1.a))+t1.b-t1.e*t1.a-t1.c between b and t1.e then f else a end+19)) from t1 union select 13 from t1) or (t1.e=(a)) and -11 in (select t1.f from t1 union select c from t1)),a)*coalesce((select max(f) from t1 where d=f),f)*c+(t1.c) FROM t1 WHERE case when +(abs(19)/abs(13*t1.e))<>11 then 19 when coalesce((select max(c) from t1 where t1.e+t1.a between t1.f and f),t1.a)=(a) then d else -19 end<=f or (((e in (b,t1.b,13)))) or b<(f) and t1.a<>11 or exists(select 1 from t1 where t1.d=d) or (t1.a)<>a or t1.a<>e} +} {90000300} +do_test randexpr-2.212 { + db eval {SELECT coalesce((select max(t1.e) from t1 where not d in (select (abs(t1.f)/abs(~case when (abs(t1.e)/abs( -t1.a))+t1.b-t1.e*t1.a-t1.c between b and t1.e then f else a end+19)) from t1 union select 13 from t1) or (t1.e=(a)) and -11 in (select t1.f from t1 union select c from t1)),a)*coalesce((select max(f) from t1 where d=f),f)*c+(t1.c) FROM t1 WHERE NOT (case when +(abs(19)/abs(13*t1.e))<>11 then 19 when coalesce((select max(c) from t1 where t1.e+t1.a between t1.f and f),t1.a)=(a) then d else -19 end<=f or (((e in (b,t1.b,13)))) or b<(f) and t1.a<>11 or exists(select 1 from t1 where t1.d=d) or (t1.a)<>a or t1.a<>e)} +} {} +do_test randexpr-2.213 { + db eval {SELECT case (select abs(count(distinct -17+(abs(c)/abs(case when exists(select 1 from t1 where (17<>(f))) then e when t1.c not between 11 and t1.d then +11 else t1.e end | b))+d)*+ -(min(f)*max(t1.e))*+cast(avg(t1.f) AS integer) | count(distinct (f))- - -count(*)-cast(avg((e)) AS integer)) from t1) when (abs(11)/abs(t1.e)) then 13 else b end FROM t1 WHERE case when t1.e not between coalesce((select (select count(*)+case max(17) when count(distinct 19-t1.c*t1.c-e) then -min(b)-cast(avg((13)) AS integer)*count(*) else min(19) end from t1)*a*t1.d-17*a+17 from t1 where t1.d not in (13,t1.f, -c)),t1.c) and e then ( -b) when (13)>=(e) then t1.c else e end in (t1.d,t1.c, -11)} +} {} +do_test randexpr-2.214 { + db eval {SELECT case (select abs(count(distinct -17+(abs(c)/abs(case when exists(select 1 from t1 where (17<>(f))) then e when t1.c not between 11 and t1.d then +11 else t1.e end | b))+d)*+ -(min(f)*max(t1.e))*+cast(avg(t1.f) AS integer) | count(distinct (f))- - -count(*)-cast(avg((e)) AS integer)) from t1) when (abs(11)/abs(t1.e)) then 13 else b end FROM t1 WHERE NOT (case when t1.e not between coalesce((select (select count(*)+case max(17) when count(distinct 19-t1.c*t1.c-e) then -min(b)-cast(avg((13)) AS integer)*count(*) else min(19) end from t1)*a*t1.d-17*a+17 from t1 where t1.d not in (13,t1.f, -c)),t1.c) and e then ( -b) when (13)>=(e) then t1.c else e end in (t1.d,t1.c, -11))} +} {200} +do_test randexpr-2.215 { + db eval {SELECT case (select abs(count(distinct -17+(abs(c)/abs(case when exists(select 1 from t1 where (17<>(f))) then e when t1.c not between 11 and t1.d then +11 else t1.e end & b))+d)*+ -(min(f)*max(t1.e))*+cast(avg(t1.f) AS integer) & count(distinct (f))- - -count(*)-cast(avg((e)) AS integer)) from t1) when (abs(11)/abs(t1.e)) then 13 else b end FROM t1 WHERE NOT (case when t1.e not between coalesce((select (select count(*)+case max(17) when count(distinct 19-t1.c*t1.c-e) then -min(b)-cast(avg((13)) AS integer)*count(*) else min(19) end from t1)*a*t1.d-17*a+17 from t1 where t1.d not in (13,t1.f, -c)),t1.c) and e then ( -b) when (13)>=(e) then t1.c else e end in (t1.d,t1.c, -11))} +} {200} +do_test randexpr-2.216 { + db eval {SELECT -case when dt1.d))) then case +coalesce((select case when 13>t1.b then 17+t1.d+d when 17 in (t1.b,b,b) and 17<=t1.e then (c) else t1.d end from t1 where 17b+t1.a*t1.a-coalesce((select max(d) from t1 where (17 between (t1.d) and (f))),t1.e)-t1.c and t1.d>11)} +} {} +do_test randexpr-2.217 { + db eval {SELECT -case when dt1.d))) then case +coalesce((select case when 13>t1.b then 17+t1.d+d when 17 in (t1.b,b,b) and 17<=t1.e then (c) else t1.d end from t1 where 17b+t1.a*t1.a-coalesce((select max(d) from t1 where (17 between (t1.d) and (f))),t1.e)-t1.c and t1.d>11))} +} {-447} +do_test randexpr-2.218 { + db eval {SELECT (select + -max(t1.c)*abs(min(t1.b) | case (abs(min(13)))+count(*)-max(t1.a) when max(~13) then abs( -~min(t1.b)+abs(count(distinct (select +++cast(avg(t1.b) AS integer)-case -count(*) when -count(*) then -count(distinct b) else count(distinct c) end from t1)))) else count(*) end-max((e))) | -cast(avg(t1.e) AS integer) from t1) FROM t1 WHERE exists(select 1 from t1 where -f-d*t1.f-c-coalesce((select max(t1.a) from t1 where 11 not in ((select count(*) from t1),coalesce((select max(t1.f+e) from t1 where t1.b in (select count(distinct t1.c) from t1 union select -case abs(abs(count(distinct 13))) when max(t1.b) then abs(cast(avg(11) AS integer)) else -cast(avg(17) AS integer) end from t1)),case t1.f when -b then 17 else 17 end)- -t1.f,b)),a)+f+c-t1.ce then 19 else t1.c-t1.d end else b end),(e))-t1.a+(13)-19)) FROM t1 WHERE (not t1.e not in (case when exists(select 1 from t1 where 17<=t1.f*17*t1.b) then f+coalesce((select max(t1.b-c-11+t1.c-a) from t1 where 13 in (select t1.e from t1 union select case when a not between t1.f and d or fe then 19 else t1.c-t1.d end else b end),(e))-t1.a+(13)-19)) FROM t1 WHERE NOT ((not t1.e not in (case when exists(select 1 from t1 where 17<=t1.f*17*t1.b) then f+coalesce((select max(t1.b-c-11+t1.c-a) from t1 where 13 in (select t1.e from t1 union select case when a not between t1.f and d or f=t1.b) and (t1.e<>( -t1.d)) and (t1.c<=13)) then c else d+11 end<=case when (t1.c)>=19 then (t1.e) when (f) not between 11 and f then coalesce((select 13 from t1 where -t1.b>=d),13) else b end} +} {203} +do_test randexpr-2.227 { + db eval {SELECT (select min(b) | case case cast(avg(c) AS integer) when ~+~count(distinct -19*f*f) then count(distinct (select cast(avg(d-case when t1.a<=19 then 19 else 11 end+f+a) AS integer) from t1))+count(distinct t1.c)+ -+ -count(*) | - -max((17))*min(t1.b)*min((e)) else max(t1.c) end when ( - - -min(a)) then ( -min(c)) else max((11)) end from t1) FROM t1 WHERE NOT (case when (((exists(select 1 from t1 where ~t1.d-t1.f between -+t1.f*c and f and not t1.e in (19,a,13))) or -e>=t1.b) and (t1.e<>( -t1.d)) and (t1.c<=13)) then c else d+11 end<=case when (t1.c)>=19 then (t1.e) when (f) not between 11 and f then coalesce((select 13 from t1 where -t1.b>=d),13) else b end)} +} {} +do_test randexpr-2.228 { + db eval {SELECT (select min(b) & case case cast(avg(c) AS integer) when ~+~count(distinct -19*f*f) then count(distinct (select cast(avg(d-case when t1.a<=19 then 19 else 11 end+f+a) AS integer) from t1))+count(distinct t1.c)+ -+ -count(*) & - -max((17))*min(t1.b)*min((e)) else max(t1.c) end when ( - - -min(a)) then ( -min(c)) else max((11)) end from t1) FROM t1 WHERE case when (((exists(select 1 from t1 where ~t1.d-t1.f between -+t1.f*c and f and not t1.e in (19,a,13))) or -e>=t1.b) and (t1.e<>( -t1.d)) and (t1.c<=13)) then c else d+11 end<=case when (t1.c)>=19 then (t1.e) when (f) not between 11 and f then coalesce((select 13 from t1 where -t1.b>=d),13) else b end} +} {8} +do_test randexpr-2.229 { + db eval {SELECT case when 19-b in (select (min(case coalesce((select e from t1 where (c not between c and e)),(select abs(count(distinct coalesce((select max( -coalesce((select max(17) from t1 where (d)>17 and c not between d and b),11)-d) from t1 where ((11)) not in (d,d,e)), - -e))) from t1)+t1.e+t1.a) when f then t1.e else t1.a end)) from t1 union select max(11) from t1) then c else f end+t1.e FROM t1 WHERE coalesce((select max(d) from t1 where coalesce((select max(case when (a++19=case t1.d when t1.e then t1.b else t1.a end*f) and -13=a then case t1.d+13 when t1.f then 17 else t1.f end when (11 not in (d,17,t1.f)) then e else 11 end+b*t1.b) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where t1.f in (select t1.e from t1 union select b from t1)))),(d))<=c),a) between t1.f and d} +} {} +do_test randexpr-2.230 { + db eval {SELECT case when 19-b in (select (min(case coalesce((select e from t1 where (c not between c and e)),(select abs(count(distinct coalesce((select max( -coalesce((select max(17) from t1 where (d)>17 and c not between d and b),11)-d) from t1 where ((11)) not in (d,d,e)), - -e))) from t1)+t1.e+t1.a) when f then t1.e else t1.a end)) from t1 union select max(11) from t1) then c else f end+t1.e FROM t1 WHERE NOT (coalesce((select max(d) from t1 where coalesce((select max(case when (a++19=case t1.d when t1.e then t1.b else t1.a end*f) and -13=a then case t1.d+13 when t1.f then 17 else t1.f end when (11 not in (d,17,t1.f)) then e else 11 end+b*t1.b) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where t1.f in (select t1.e from t1 union select b from t1)))),(d))<=c),a) between t1.f and d)} +} {1100} +do_test randexpr-2.231 { + db eval {SELECT -t1.e*coalesce((select max(17) from t1 where (11*(select case -abs( -+count(*)) when -case +(cast(avg( -f) AS integer)) | (abs(cast(avg(c) AS integer))) when min(d) then -max(t1.f) else count(*) end then cast(avg( -t1.f) AS integer) else max(b) end from t1)*~t1.e*case (select min(e) from t1) when 17-t1.b then (e) else t1.f+t1.f end) in (select t1.d from t1 union select 19 from t1)), -t1.a) FROM t1 WHERE (select min(19) from t1) in (select 17 from t1 union select -11+t1.d+t1.c from t1)} +} {} +do_test randexpr-2.232 { + db eval {SELECT -t1.e*coalesce((select max(17) from t1 where (11*(select case -abs( -+count(*)) when -case +(cast(avg( -f) AS integer)) | (abs(cast(avg(c) AS integer))) when min(d) then -max(t1.f) else count(*) end then cast(avg( -t1.f) AS integer) else max(b) end from t1)*~t1.e*case (select min(e) from t1) when 17-t1.b then (e) else t1.f+t1.f end) in (select t1.d from t1 union select 19 from t1)), -t1.a) FROM t1 WHERE NOT ((select min(19) from t1) in (select 17 from t1 union select -11+t1.d+t1.c from t1))} +} {50000} +do_test randexpr-2.233 { + db eval {SELECT -t1.e*coalesce((select max(17) from t1 where (11*(select case -abs( -+count(*)) when -case +(cast(avg( -f) AS integer)) & (abs(cast(avg(c) AS integer))) when min(d) then -max(t1.f) else count(*) end then cast(avg( -t1.f) AS integer) else max(b) end from t1)*~t1.e*case (select min(e) from t1) when 17-t1.b then (e) else t1.f+t1.f end) in (select t1.d from t1 union select 19 from t1)), -t1.a) FROM t1 WHERE NOT ((select min(19) from t1) in (select 17 from t1 union select -11+t1.d+t1.c from t1))} +} {50000} +do_test randexpr-2.234 { + db eval {SELECT (coalesce((select max(case when t1.e>= -e | 13-19*d then case when c not in (+(select count(*) from t1),coalesce((select max(t1.a) from t1 where 13 in (select case count(distinct t1.a) | count(*) when cast(avg(t1.b) AS integer) then count(distinct a) else min(11) end from t1 union select count(*) from t1)),19),t1.a) then t1.c else c end when t1.f in (select t1.f from t1 union select t1.e from t1) then t1.e else -t1.e end) from t1 where (17 in (e,d,a))),t1.d)* -19) FROM t1 WHERE (((abs(t1.f)/abs(d)) in (select case (case max(coalesce((select max(e*(t1.d*13+t1.b)-t1.b) from t1 where t1.a=13),(t1.c))) when (case max(t1.a) when -abs(max(17))-count(distinct 19) then cast(avg(t1.d) AS integer) else max(13) end)*count(distinct t1.c) then (max((t1.b))) else min(19) end) when max(f) then -(count(distinct t1.f)) else min(t1.b) end from t1 union select cast(avg(13) AS integer) from t1) and (13 in (select ((min(b))) from t1 union select - -count(*) from t1))))} +} {} +do_test randexpr-2.235 { + db eval {SELECT (coalesce((select max(case when t1.e>= -e | 13-19*d then case when c not in (+(select count(*) from t1),coalesce((select max(t1.a) from t1 where 13 in (select case count(distinct t1.a) | count(*) when cast(avg(t1.b) AS integer) then count(distinct a) else min(11) end from t1 union select count(*) from t1)),19),t1.a) then t1.c else c end when t1.f in (select t1.f from t1 union select t1.e from t1) then t1.e else -t1.e end) from t1 where (17 in (e,d,a))),t1.d)* -19) FROM t1 WHERE NOT ((((abs(t1.f)/abs(d)) in (select case (case max(coalesce((select max(e*(t1.d*13+t1.b)-t1.b) from t1 where t1.a=13),(t1.c))) when (case max(t1.a) when -abs(max(17))-count(distinct 19) then cast(avg(t1.d) AS integer) else max(13) end)*count(distinct t1.c) then (max((t1.b))) else min(19) end) when max(f) then -(count(distinct t1.f)) else min(t1.b) end from t1 union select cast(avg(13) AS integer) from t1) and (13 in (select ((min(b))) from t1 union select - -count(*) from t1)))))} +} {-7600} +do_test randexpr-2.236 { + db eval {SELECT (coalesce((select max(case when t1.e>= -e & 13-19*d then case when c not in (+(select count(*) from t1),coalesce((select max(t1.a) from t1 where 13 in (select case count(distinct t1.a) & count(*) when cast(avg(t1.b) AS integer) then count(distinct a) else min(11) end from t1 union select count(*) from t1)),19),t1.a) then t1.c else c end when t1.f in (select t1.f from t1 union select t1.e from t1) then t1.e else -t1.e end) from t1 where (17 in (e,d,a))),t1.d)* -19) FROM t1 WHERE NOT ((((abs(t1.f)/abs(d)) in (select case (case max(coalesce((select max(e*(t1.d*13+t1.b)-t1.b) from t1 where t1.a=13),(t1.c))) when (case max(t1.a) when -abs(max(17))-count(distinct 19) then cast(avg(t1.d) AS integer) else max(13) end)*count(distinct t1.c) then (max((t1.b))) else min(19) end) when max(f) then -(count(distinct t1.f)) else min(t1.b) end from t1 union select cast(avg(13) AS integer) from t1) and (13 in (select ((min(b))) from t1 union select - -count(*) from t1)))))} +} {-7600} +do_test randexpr-2.237 { + db eval {SELECT case when case when b in (select abs(abs( -max(case c+d when f then f else 19 end | c)-( -case min(c) when -(cast(avg((t1.f)) AS integer)) then count(*) else ((cast(avg(t1.b) AS integer))) end))+count(*)+(max(17))) from t1 union select count(*) from t1) then t1.a when ~13*t1.a- -c not in (b,e,19) then t1.c else (t1.d) end<=(b) and 13 between t1.f and 11 then t1.f else -19 end FROM t1 WHERE d>=case when t1.d+case when ( -17)-c>11 or b in ((select min(13)+ -cast(avg(11) AS integer) from t1)+~t1.f, -c,(13)) and e in (select (d) from t1 union select f from t1) then t1.a when d= -t1.d then a- -17 else 17 end-t1.c>d then 11 when exists(select 1 from t1 where 17 not between t1.b and t1.b) then t1.b else (t1.a) end} +} {-19} +do_test randexpr-2.238 { + db eval {SELECT case when case when b in (select abs(abs( -max(case c+d when f then f else 19 end | c)-( -case min(c) when -(cast(avg((t1.f)) AS integer)) then count(*) else ((cast(avg(t1.b) AS integer))) end))+count(*)+(max(17))) from t1 union select count(*) from t1) then t1.a when ~13*t1.a- -c not in (b,e,19) then t1.c else (t1.d) end<=(b) and 13 between t1.f and 11 then t1.f else -19 end FROM t1 WHERE NOT (d>=case when t1.d+case when ( -17)-c>11 or b in ((select min(13)+ -cast(avg(11) AS integer) from t1)+~t1.f, -c,(13)) and e in (select (d) from t1 union select f from t1) then t1.a when d= -t1.d then a- -17 else 17 end-t1.c>d then 11 when exists(select 1 from t1 where 17 not between t1.b and t1.b) then t1.b else (t1.a) end)} +} {} +do_test randexpr-2.239 { + db eval {SELECT case when case when b in (select abs(abs( -max(case c+d when f then f else 19 end & c)-( -case min(c) when -(cast(avg((t1.f)) AS integer)) then count(*) else ((cast(avg(t1.b) AS integer))) end))+count(*)+(max(17))) from t1 union select count(*) from t1) then t1.a when ~13*t1.a- -c not in (b,e,19) then t1.c else (t1.d) end<=(b) and 13 between t1.f and 11 then t1.f else -19 end FROM t1 WHERE d>=case when t1.d+case when ( -17)-c>11 or b in ((select min(13)+ -cast(avg(11) AS integer) from t1)+~t1.f, -c,(13)) and e in (select (d) from t1 union select f from t1) then t1.a when d= -t1.d then a- -17 else 17 end-t1.c>d then 11 when exists(select 1 from t1 where 17 not between t1.b and t1.b) then t1.b else (t1.a) end} +} {-19} +do_test randexpr-2.240 { + db eval {SELECT e-coalesce((select coalesce((select max(19) from t1 where (coalesce((select max(case 11 when b then 13 else t1.a end) from t1 where 19 not in (c,t1.f,b)),t1.a)+t1.d in (select 17 from t1 union select 19 from t1) and 11 in (13,t1.c,17) or 19 not in (t1.f,a,17) or t1.e not between 13 and f and a>=d)),(a)-17+t1.f)+t1.a+17 from t1 where not exists(select 1 from t1 where a>t1.f)),t1.b) FROM t1 WHERE t1.a-17 in (select (abs(count(*)))-case case case abs(abs(count(*))) when min(t1.f) then count(*) else cast(avg(+t1.a+(e) | 19*e+t1.f) AS integer) end when abs(+cast(avg(b) AS integer) | count(distinct (13))*+~ -(min(e)) | cast(avg(19) AS integer)) then cast(avg(19) AS integer) else count(distinct t1.c) end | min(t1.d) when count(*) then (count(distinct d)) else (min(11)) end from t1 union select (cast(avg(t1.a) AS integer)) from t1)} +} {} +do_test randexpr-2.241 { + db eval {SELECT e-coalesce((select coalesce((select max(19) from t1 where (coalesce((select max(case 11 when b then 13 else t1.a end) from t1 where 19 not in (c,t1.f,b)),t1.a)+t1.d in (select 17 from t1 union select 19 from t1) and 11 in (13,t1.c,17) or 19 not in (t1.f,a,17) or t1.e not between 13 and f and a>=d)),(a)-17+t1.f)+t1.a+17 from t1 where not exists(select 1 from t1 where a>t1.f)),t1.b) FROM t1 WHERE NOT (t1.a-17 in (select (abs(count(*)))-case case case abs(abs(count(*))) when min(t1.f) then count(*) else cast(avg(+t1.a+(e) | 19*e+t1.f) AS integer) end when abs(+cast(avg(b) AS integer) | count(distinct (13))*+~ -(min(e)) | cast(avg(19) AS integer)) then cast(avg(19) AS integer) else count(distinct t1.c) end | min(t1.d) when count(*) then (count(distinct d)) else (min(11)) end from t1 union select (cast(avg(t1.a) AS integer)) from t1))} +} {364} +do_test randexpr-2.242 { + db eval {SELECT -coalesce((select case when b>19 | f-(select abs(max(t1.b+case when e>17 then 11 else f end)+count(*)) from t1) and case when (19<11*t1.d*t1.b) then 13 else t1.e end not between c and b then d+17 else c end-f from t1 where t1.b>=f),t1.c)+17-a FROM t1 WHERE +c in (+~a+case when ((case t1.d when coalesce((select f from t1 where e in (select count(distinct t1.e) from t1 union select min((abs(t1.c)/abs(e | b)) | d* -t1.d) from t1)),t1.e)+a then c else b end in (select -cast(avg(t1.c) AS integer)-~cast(avg(11) AS integer) from t1 union select -count(distinct 19) from t1))) then -e*19 else 13 end,t1.a,d)} +} {} +do_test randexpr-2.243 { + db eval {SELECT -coalesce((select case when b>19 | f-(select abs(max(t1.b+case when e>17 then 11 else f end)+count(*)) from t1) and case when (19<11*t1.d*t1.b) then 13 else t1.e end not between c and b then d+17 else c end-f from t1 where t1.b>=f),t1.c)+17-a FROM t1 WHERE NOT (+c in (+~a+case when ((case t1.d when coalesce((select f from t1 where e in (select count(distinct t1.e) from t1 union select min((abs(t1.c)/abs(e | b)) | d* -t1.d) from t1)),t1.e)+a then c else b end in (select -cast(avg(t1.c) AS integer)-~cast(avg(11) AS integer) from t1 union select -count(distinct 19) from t1))) then -e*19 else 13 end,t1.a,d))} +} {-383} +do_test randexpr-2.244 { + db eval {SELECT -coalesce((select case when b>19 & f-(select abs(max(t1.b+case when e>17 then 11 else f end)+count(*)) from t1) and case when (19<11*t1.d*t1.b) then 13 else t1.e end not between c and b then d+17 else c end-f from t1 where t1.b>=f),t1.c)+17-a FROM t1 WHERE NOT (+c in (+~a+case when ((case t1.d when coalesce((select f from t1 where e in (select count(distinct t1.e) from t1 union select min((abs(t1.c)/abs(e | b)) | d* -t1.d) from t1)),t1.e)+a then c else b end in (select -cast(avg(t1.c) AS integer)-~cast(avg(11) AS integer) from t1 union select -count(distinct 19) from t1))) then -e*19 else 13 end,t1.a,d))} +} {-383} +do_test randexpr-2.245 { + db eval {SELECT case when t1.b>=+(abs(t1.e)/abs(coalesce((select c from t1 where 17<=+(e)),(e)-+~11*17+t1.d-e | +coalesce((select max(t1.d) from t1 where f>e),t1.a)*b | (e))))-t1.a and c>=t1.d or (17 not between e and b) then t1.e else d end FROM t1 WHERE exists(select 1 from t1 where (19-((17))+(b) in (select d*e*a from t1 union select ~19 from t1)) and case b-(abs(case a when coalesce((select max(19) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where b not between e and (t1.f) or a not in (t1.c,17,t1.d)))),case t1.b when -d then 13 else 13 end)*a+t1.c then e else a end)/abs(t1.d))*t1.e when -13 then t1.c else 19 end in (select +count(distinct e) from t1 union select count(*) from t1))} +} {} +do_test randexpr-2.246 { + db eval {SELECT case when t1.b>=+(abs(t1.e)/abs(coalesce((select c from t1 where 17<=+(e)),(e)-+~11*17+t1.d-e | +coalesce((select max(t1.d) from t1 where f>e),t1.a)*b | (e))))-t1.a and c>=t1.d or (17 not between e and b) then t1.e else d end FROM t1 WHERE NOT (exists(select 1 from t1 where (19-((17))+(b) in (select d*e*a from t1 union select ~19 from t1)) and case b-(abs(case a when coalesce((select max(19) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where b not between e and (t1.f) or a not in (t1.c,17,t1.d)))),case t1.b when -d then 13 else 13 end)*a+t1.c then e else a end)/abs(t1.d))*t1.e when -13 then t1.c else 19 end in (select +count(distinct e) from t1 union select count(*) from t1)))} +} {500} +do_test randexpr-2.247 { + db eval {SELECT case when t1.b>=+(abs(t1.e)/abs(coalesce((select c from t1 where 17<=+(e)),(e)-+~11*17+t1.d-e & +coalesce((select max(t1.d) from t1 where f>e),t1.a)*b & (e))))-t1.a and c>=t1.d or (17 not between e and b) then t1.e else d end FROM t1 WHERE NOT (exists(select 1 from t1 where (19-((17))+(b) in (select d*e*a from t1 union select ~19 from t1)) and case b-(abs(case a when coalesce((select max(19) from t1 where exists(select 1 from t1 where exists(select 1 from t1 where b not between e and (t1.f) or a not in (t1.c,17,t1.d)))),case t1.b when -d then 13 else 13 end)*a+t1.c then e else a end)/abs(t1.d))*t1.e when -13 then t1.c else 19 end in (select +count(distinct e) from t1 union select count(*) from t1)))} +} {500} +do_test randexpr-2.248 { + db eval {SELECT case when 11 in (select min(+t1.e)* -max(a)+count(distinct d*11*c)*(count(distinct (e))) | ( -min(t1.b)) | count(distinct 19) | (max(t1.f))-max(t1.b) from t1 union select (min(19)) from t1) then coalesce((select max(17) from t1 where -17=13 or c in (select t1.d from t1 union select d from t1)),b)*t1.b-a+19 when t1.d<(d) then (d) else 19 end FROM t1 WHERE case when case when t1.c not in (f,19,b) then t1.d-t1.c-case when 17<>t1.a then -(abs((select cast(avg(b) AS integer)- -max(t1.c) from t1))/abs(t1.c)) else t1.f end-17 | 19 when exists(select 1 from t1 where exists(select 1 from t1 where (e between 13 and (t1.a))) and e<=t1.c) then f else t1.a end>=11 then c when ft1.a then -(abs((select cast(avg(b) AS integer)- -max(t1.c) from t1))/abs(t1.c)) else t1.f end-17 | 19 when exists(select 1 from t1 where exists(select 1 from t1 where (e between 13 and (t1.a))) and e<=t1.c) then f else t1.a end>=11 then c when ft1.a then -(abs((select cast(avg(b) AS integer)- -max(t1.c) from t1))/abs(t1.c)) else t1.f end-17 | 19 when exists(select 1 from t1 where exists(select 1 from t1 where (e between 13 and (t1.a))) and e<=t1.c) then f else t1.a end>=11 then c when f=c then t1.b else t1.f end)) and 17<>f) then case when (e) not in (t1.a,t1.f,e) then case case t1.c when 13 then 19 else t1.d end-19 when t1.d then -t1.b else t1.f end when t1.d not in (17,t1.a,t1.d) or c in (d,(19),t1.b) then -t1.b else c end else 19 end+t1.b-f+t1.e FROM t1 WHERE t1.f-case when (coalesce((select 13*(abs(~11)/abs(t1.b)) from t1 where ~a between +f+~+17 and t1.e),e) not between coalesce((select 19-(abs(11)/abs(t1.b)) from t1 where f<>c),t1.b) and t1.f or t1.d between (select case min(a) when cast(avg(e) AS integer) then -((count(*))) else cast(avg(t1.a) AS integer) end | count(*) from t1) and (t1.a)) then 19 else f end=f} +} {} +do_test randexpr-2.252 { + db eval {SELECT c*~17+~case when (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(e)/abs(c))=case when t1.c not in (a,13,11) and t1.b>=c then t1.b else t1.f end)) and 17<>f) then case when (e) not in (t1.a,t1.f,e) then case case t1.c when 13 then 19 else t1.d end-19 when t1.d then -t1.b else t1.f end when t1.d not in (17,t1.a,t1.d) or c in (d,(19),t1.b) then -t1.b else c end else 19 end+t1.b-f+t1.e FROM t1 WHERE NOT (t1.f-case when (coalesce((select 13*(abs(~11)/abs(t1.b)) from t1 where ~a between +f+~+17 and t1.e),e) not between coalesce((select 19-(abs(11)/abs(t1.b)) from t1 where f<>c),t1.b) and t1.f or t1.d between (select case min(a) when cast(avg(e) AS integer) then -((count(*))) else cast(avg(t1.a) AS integer) end | count(*) from t1) and (t1.a)) then 19 else f end=f)} +} {-5601} +do_test randexpr-2.253 { + db eval {SELECT coalesce((select c-t1.a | 17 | b-~t1.e-11 from t1 where not exists(select 1 from t1 where t1.c<=t1.b)),17) FROM t1 WHERE (((coalesce((select max((abs(b-t1.d-19*t1.a*e+~case when t1.e=t1.f-e then (select abs(abs(cast(avg((f)) AS integer))) from t1) else ((abs(t1.b)/abs(t1.a))) end-t1.b-t1.c)/abs(t1.b))) from t1 where not t1.c in (select count(distinct c) from t1 union select count(*) from t1) and 17< -t1.e),(c)) | -(c))<>e))} +} {763} +do_test randexpr-2.254 { + db eval {SELECT coalesce((select c-t1.a | 17 | b-~t1.e-11 from t1 where not exists(select 1 from t1 where t1.c<=t1.b)),17) FROM t1 WHERE NOT ((((coalesce((select max((abs(b-t1.d-19*t1.a*e+~case when t1.e=t1.f-e then (select abs(abs(cast(avg((f)) AS integer))) from t1) else ((abs(t1.b)/abs(t1.a))) end-t1.b-t1.c)/abs(t1.b))) from t1 where not t1.c in (select count(distinct c) from t1 union select count(*) from t1) and 17< -t1.e),(c)) | -(c))<>e)))} +} {} +do_test randexpr-2.255 { + db eval {SELECT coalesce((select c-t1.a & 17 & b-~t1.e-11 from t1 where not exists(select 1 from t1 where t1.c<=t1.b)),17) FROM t1 WHERE (((coalesce((select max((abs(b-t1.d-19*t1.a*e+~case when t1.e=t1.f-e then (select abs(abs(cast(avg((f)) AS integer))) from t1) else ((abs(t1.b)/abs(t1.a))) end-t1.b-t1.c)/abs(t1.b))) from t1 where not t1.c in (select count(distinct c) from t1 union select count(*) from t1) and 17< -t1.e),(c)) | -(c))<>e))} +} {0} +do_test randexpr-2.256 { + db eval {SELECT case case +(select case count(distinct case when case when (abs(f | t1.d)/abs(13))<= -c then t1.a else t1.b end+t1.b<=19 then c when 19=a then 17 else 11 end+13) when ~+case (cast(avg(t1.b) AS integer) | ((count(*)))-max(t1.d)) when count(distinct d) then count(*) else cast(avg(t1.c) AS integer) end then count(*) else count(*) end from t1) when c*t1.a then 13 else t1.a end when a then -f else t1.a end+d FROM t1 WHERE case when coalesce((select t1.c | c*t1.e-11 from t1 where exists(select 1 from t1 where t1.d-t1.d*d between - -t1.e and a)), -13)<=e and 11 not in (d,t1.a,f) and t1.a not between 11 and 19 or t1.e<>t1.e and t1.e=t1.a or -t1.e>=b then b when 17 not between t1.f and t1.b then a else b end in (select 11 from t1 union select f from t1)} +} {} +do_test randexpr-2.257 { + db eval {SELECT case case +(select case count(distinct case when case when (abs(f | t1.d)/abs(13))<= -c then t1.a else t1.b end+t1.b<=19 then c when 19=a then 17 else 11 end+13) when ~+case (cast(avg(t1.b) AS integer) | ((count(*)))-max(t1.d)) when count(distinct d) then count(*) else cast(avg(t1.c) AS integer) end then count(*) else count(*) end from t1) when c*t1.a then 13 else t1.a end when a then -f else t1.a end+d FROM t1 WHERE NOT (case when coalesce((select t1.c | c*t1.e-11 from t1 where exists(select 1 from t1 where t1.d-t1.d*d between - -t1.e and a)), -13)<=e and 11 not in (d,t1.a,f) and t1.a not between 11 and 19 or t1.e<>t1.e and t1.e=t1.a or -t1.e>=b then b when 17 not between t1.f and t1.b then a else b end in (select 11 from t1 union select f from t1))} +} {-200} +do_test randexpr-2.258 { + db eval {SELECT case case +(select case count(distinct case when case when (abs(f & t1.d)/abs(13))<= -c then t1.a else t1.b end+t1.b<=19 then c when 19=a then 17 else 11 end+13) when ~+case (cast(avg(t1.b) AS integer) & ((count(*)))-max(t1.d)) when count(distinct d) then count(*) else cast(avg(t1.c) AS integer) end then count(*) else count(*) end from t1) when c*t1.a then 13 else t1.a end when a then -f else t1.a end+d FROM t1 WHERE NOT (case when coalesce((select t1.c | c*t1.e-11 from t1 where exists(select 1 from t1 where t1.d-t1.d*d between - -t1.e and a)), -13)<=e and 11 not in (d,t1.a,f) and t1.a not between 11 and 19 or t1.e<>t1.e and t1.e=t1.a or -t1.e>=b then b when 17 not between t1.f and t1.b then a else b end in (select 11 from t1 union select f from t1))} +} {-200} +do_test randexpr-2.259 { + db eval {SELECT f*coalesce((select max((select count(*) from t1)) from t1 where ~case when t1.e<=case when 17>=+case when c*a in (c,t1.b,13) then t1.e when a>t1.b and a<=19 then c else t1.e end then t1.c else 17 end-f*17 or a between b and 19 then t1.c when -f<=11 then c else -11 end*t1.c+d>=e),17) FROM t1 WHERE (19 not between t1.b and ~e)} +} {10200} +do_test randexpr-2.260 { + db eval {SELECT f*coalesce((select max((select count(*) from t1)) from t1 where ~case when t1.e<=case when 17>=+case when c*a in (c,t1.b,13) then t1.e when a>t1.b and a<=19 then c else t1.e end then t1.c else 17 end-f*17 or a between b and 19 then t1.c when -f<=11 then c else -11 end*t1.c+d>=e),17) FROM t1 WHERE NOT ((19 not between t1.b and ~e))} +} {} +do_test randexpr-2.261 { + db eval {SELECT coalesce((select max(t1.c- -case when (~(select max(b*t1.a)*~((min(t1.e))-min((a))) | -cast(avg(t1.e+t1.a) AS integer) from t1))c or (t1.b)> -(11)),11)) from t1 where -11 in ((d),f,t1.d)),t1.a) FROM t1 WHERE c<>e+t1.c} +} {100} +do_test randexpr-2.262 { + db eval {SELECT coalesce((select max(t1.c- -case when (~(select max(b*t1.a)*~((min(t1.e))-min((a))) | -cast(avg(t1.e+t1.a) AS integer) from t1))c or (t1.b)> -(11)),11)) from t1 where -11 in ((d),f,t1.d)),t1.a) FROM t1 WHERE NOT (c<>e+t1.c)} +} {} +do_test randexpr-2.263 { + db eval {SELECT coalesce((select max(t1.c- -case when (~(select max(b*t1.a)*~((min(t1.e))-min((a))) & -cast(avg(t1.e+t1.a) AS integer) from t1))c or (t1.b)> -(11)),11)) from t1 where -11 in ((d),f,t1.d)),t1.a) FROM t1 WHERE c<>e+t1.c} +} {100} +do_test randexpr-2.264 { + db eval {SELECT -case when (not exists(select 1 from t1 where e*d*case 17 when case t1.c-t1.f when t1.a then t1.a else 11 end then t1.c else t1.b end-e+(t1.a)-e not in (e,e,t1.a) and (t1.f not between 19 and t1.e))) and t1.be),c) between t1.e and f then t1.e when -f> - -b then c else t1.c end) from t1 where not 11 in (select f from t1 union select a from t1)),t1.d)-t1.a-13 from t1 where t1.d between -t1.e and t1.a),f) FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where c in (select (abs(f)/abs(13)) from t1 union select t1.a+b from t1)))} +} {} +do_test randexpr-2.267 { + db eval {SELECT coalesce((select 17+coalesce((select max(case when -coalesce((select max((abs( -(abs(t1.a)/abs(t1.d))+11)/abs(e))-b) from t1 where t1.b not between f and t1.c and t1.f<>e),c) between t1.e and f then t1.e when -f> - -b then c else t1.c end) from t1 where not 11 in (select f from t1 union select a from t1)),t1.d)-t1.a-13 from t1 where t1.d between -t1.e and t1.a),f) FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where c in (select (abs(f)/abs(13)) from t1 union select t1.a+b from t1))))} +} {600} +do_test randexpr-2.268 { + db eval {SELECT coalesce((select max(t1.d) from t1 where exists(select 1 from t1 where t1.d in (select case (abs(((count(distinct t1.d-c))* -cast(avg(11) AS integer)+max(t1.c)))) when (cast(avg(t1.c+a) AS integer)*+min(a)*max(c)-max(t1.a)+cast(avg(f) AS integer))+cast(avg(t1.e) AS integer) then min(11) else (((min(11)))) end from t1 union select count(*) from t1))),coalesce((select max(b+13) from t1 where exists(select 1 from t1 where f in (select 11 from t1 union select t1.b from t1))),t1.e)) FROM t1 WHERE b>11} +} {500} +do_test randexpr-2.269 { + db eval {SELECT coalesce((select max(t1.d) from t1 where exists(select 1 from t1 where t1.d in (select case (abs(((count(distinct t1.d-c))* -cast(avg(11) AS integer)+max(t1.c)))) when (cast(avg(t1.c+a) AS integer)*+min(a)*max(c)-max(t1.a)+cast(avg(f) AS integer))+cast(avg(t1.e) AS integer) then min(11) else (((min(11)))) end from t1 union select count(*) from t1))),coalesce((select max(b+13) from t1 where exists(select 1 from t1 where f in (select 11 from t1 union select t1.b from t1))),t1.e)) FROM t1 WHERE NOT (b>11)} +} {} +do_test randexpr-2.270 { + db eval {SELECT coalesce((select max( -(select count(*)-case min(19)-abs(count(*))+(max( -b)-+count(distinct (t1.e))) when max(a) then (count(distinct 19)) else count(*) end from t1)) from t1 where exists(select 1 from t1 where a<(abs(case when a-t1.c+ -19+t1.d between 11 and f then t1.f else d end+t1.a+d)/abs(c))) or t1.c>t1.c),17)*f FROM t1 WHERE not f<>t1.b} +} {} +do_test randexpr-2.271 { + db eval {SELECT coalesce((select max( -(select count(*)-case min(19)-abs(count(*))+(max( -b)-+count(distinct (t1.e))) when max(a) then (count(distinct 19)) else count(*) end from t1)) from t1 where exists(select 1 from t1 where a<(abs(case when a-t1.c+ -19+t1.d between 11 and f then t1.f else d end+t1.a+d)/abs(c))) or t1.c>t1.c),17)*f FROM t1 WHERE NOT (not f<>t1.b)} +} {10200} +do_test randexpr-2.272 { + db eval {SELECT case when coalesce((select f-coalesce((select +coalesce((select t1.c from t1 where (t1.c=(abs(t1.e)/abs(+t1.c+f+(f))))),13+17)+t1.b | t1.c from t1 where case when t1.a not in (d,17,t1.c) then f else f end | -13 in (select cast(avg(t1.e) AS integer) from t1 union select min(t1.a) from t1)),c) from t1 where 17>c), -t1.b)>t1.c then 17 when t1.b<>11 then e else t1.f end FROM t1 WHERE case when t1.f in (t1.a+(abs(17)/abs((t1.d))),coalesce((select max(c) from t1 where (not (d- -case f when 17 then d else (17) end+e*t1.d) not in ((t1.d),t1.f,f))),coalesce((select c from t1 where 13 not in (19,d,b)),f)),17) then t1.b when e<=f then 17 else c end -19} +} {500} +do_test randexpr-2.273 { + db eval {SELECT case when coalesce((select f-coalesce((select +coalesce((select t1.c from t1 where (t1.c=(abs(t1.e)/abs(+t1.c+f+(f))))),13+17)+t1.b | t1.c from t1 where case when t1.a not in (d,17,t1.c) then f else f end | -13 in (select cast(avg(t1.e) AS integer) from t1 union select min(t1.a) from t1)),c) from t1 where 17>c), -t1.b)>t1.c then 17 when t1.b<>11 then e else t1.f end FROM t1 WHERE NOT (case when t1.f in (t1.a+(abs(17)/abs((t1.d))),coalesce((select max(c) from t1 where (not (d- -case f when 17 then d else (17) end+e*t1.d) not in ((t1.d),t1.f,f))),coalesce((select c from t1 where 13 not in (19,d,b)),f)),17) then t1.b when e<=f then 17 else c end -19)} +} {} +do_test randexpr-2.274 { + db eval {SELECT case when coalesce((select f-coalesce((select +coalesce((select t1.c from t1 where (t1.c=(abs(t1.e)/abs(+t1.c+f+(f))))),13+17)+t1.b & t1.c from t1 where case when t1.a not in (d,17,t1.c) then f else f end & -13 in (select cast(avg(t1.e) AS integer) from t1 union select min(t1.a) from t1)),c) from t1 where 17>c), -t1.b)>t1.c then 17 when t1.b<>11 then e else t1.f end FROM t1 WHERE case when t1.f in (t1.a+(abs(17)/abs((t1.d))),coalesce((select max(c) from t1 where (not (d- -case f when 17 then d else (17) end+e*t1.d) not in ((t1.d),t1.f,f))),coalesce((select c from t1 where 13 not in (19,d,b)),f)),17) then t1.b when e<=f then 17 else c end -19} +} {500} +do_test randexpr-2.275 { + db eval {SELECT case when d*t1.c*a<>t1.b*~t1.b*t1.f-b then e else 17 end*t1.e+case when a not between t1.a and t1.d or (select - -cast(avg(c) AS integer) from t1)<>17+c then case 11 when t1.f then -t1.b else t1.b end when 13 not in (c,t1.f,19) or not exists(select 1 from t1 where 13=t1.d or t1.e<>a) then (17) else -t1.f end FROM t1 WHERE (not (case e when e then +case when e>=a and 13<>e*t1.e or t1.d<>11 then t1.c else t1.b end else 17 end) in (select cast(avg( -t1.c) AS integer) from t1 union select case min(13) when -+count(distinct 13) then case (+(cast(avg(e) AS integer))+((cast(avg(13) AS integer)))* - -count(distinct c)*count(*)) | count(*) when min(t1.c) then (min(11)) else max(f) end else cast(avg(17) AS integer) end from t1))} +} {250200} +do_test randexpr-2.276 { + db eval {SELECT case when d*t1.c*a<>t1.b*~t1.b*t1.f-b then e else 17 end*t1.e+case when a not between t1.a and t1.d or (select - -cast(avg(c) AS integer) from t1)<>17+c then case 11 when t1.f then -t1.b else t1.b end when 13 not in (c,t1.f,19) or not exists(select 1 from t1 where 13=t1.d or t1.e<>a) then (17) else -t1.f end FROM t1 WHERE NOT ((not (case e when e then +case when e>=a and 13<>e*t1.e or t1.d<>11 then t1.c else t1.b end else 17 end) in (select cast(avg( -t1.c) AS integer) from t1 union select case min(13) when -+count(distinct 13) then case (+(cast(avg(e) AS integer))+((cast(avg(13) AS integer)))* - -count(distinct c)*count(*)) | count(*) when min(t1.c) then (min(11)) else max(f) end else cast(avg(17) AS integer) end from t1)))} +} {} +do_test randexpr-2.277 { + db eval {SELECT (select max(t1.a)*abs(count(distinct f-t1.a-(abs(t1.a)/abs(case e when case t1.f when e*(b)-19 then 11 else t1.d end then t1.f else 11 end)))) | case +~cast(avg(t1.a) AS integer)-+abs(count(distinct 17)) when case count(distinct t1.b)*cast(avg(t1.a) AS integer)+count(distinct t1.c) when count(*) then min(t1.f) else count(distinct e) end then max((t1.e)) else max(d) end-count(*) from t1) FROM t1 WHERE e not between (select min(t1.a) from t1) and d+t1.d} +} {} +do_test randexpr-2.278 { + db eval {SELECT (select max(t1.a)*abs(count(distinct f-t1.a-(abs(t1.a)/abs(case e when case t1.f when e*(b)-19 then 11 else t1.d end then t1.f else 11 end)))) | case +~cast(avg(t1.a) AS integer)-+abs(count(distinct 17)) when case count(distinct t1.b)*cast(avg(t1.a) AS integer)+count(distinct t1.c) when count(*) then min(t1.f) else count(distinct e) end then max((t1.e)) else max(d) end-count(*) from t1) FROM t1 WHERE NOT (e not between (select min(t1.a) from t1) and d+t1.d)} +} {495} +do_test randexpr-2.279 { + db eval {SELECT (select max(t1.a)*abs(count(distinct f-t1.a-(abs(t1.a)/abs(case e when case t1.f when e*(b)-19 then 11 else t1.d end then t1.f else 11 end)))) & case +~cast(avg(t1.a) AS integer)-+abs(count(distinct 17)) when case count(distinct t1.b)*cast(avg(t1.a) AS integer)+count(distinct t1.c) when count(*) then min(t1.f) else count(distinct e) end then max((t1.e)) else max(d) end-count(*) from t1) FROM t1 WHERE NOT (e not between (select min(t1.a) from t1) and d+t1.d)} +} {4} +do_test randexpr-2.280 { + db eval {SELECT e*c-t1.e*t1.c++(select abs(case abs(max(coalesce((select f from t1 where (b*coalesce((select max(b) from t1 where 17>f),t1.e) not between c and f or t1.a>d and t1.a<11 or a<> -f)),(t1.a)))) when -+count(distinct e) then -+(count(distinct 19))+min(t1.c) else -min(t1.f) end) from t1)+t1.b-19 FROM t1 WHERE d-coalesce((select max(t1.d*c+c) from t1 where t1.f between (select count(distinct t1.b-e)+abs(~case case ~cast(avg(t1.f) AS integer)-count(distinct t1.a) when count(*) then count(distinct e) else count(*) end when min(e) then min( -t1.c) else max(a) end) from t1)+17 and -case when d>=d-11 then t1.c else t1.a end),t1.a)*t1.a not in (t1.f,t1.f,d)} +} {781} +do_test randexpr-2.281 { + db eval {SELECT e*c-t1.e*t1.c++(select abs(case abs(max(coalesce((select f from t1 where (b*coalesce((select max(b) from t1 where 17>f),t1.e) not between c and f or t1.a>d and t1.a<11 or a<> -f)),(t1.a)))) when -+count(distinct e) then -+(count(distinct 19))+min(t1.c) else -min(t1.f) end) from t1)+t1.b-19 FROM t1 WHERE NOT (d-coalesce((select max(t1.d*c+c) from t1 where t1.f between (select count(distinct t1.b-e)+abs(~case case ~cast(avg(t1.f) AS integer)-count(distinct t1.a) when count(*) then count(distinct e) else count(*) end when min(e) then min( -t1.c) else max(a) end) from t1)+17 and -case when d>=d-11 then t1.c else t1.a end),t1.a)*t1.a not in (t1.f,t1.f,d))} +} {} +do_test randexpr-2.282 { + db eval {SELECT coalesce((select a from t1 where (exists(select 1 from t1 where 11-case when ((select count(distinct t1.e+d) from t1))<>t1.d*f then -13 when t1.b in (select abs(cast(avg(c) AS integer)) from t1 union select count(distinct e)*count(distinct c)-cast(avg(e) AS integer) from t1) or c in (select t1.d from t1 union select 17 from t1) then a else t1.b end>=t1.c) and f>=d and d>=t1.f)),case when 11=19 and t1.a between t1.d and e then t1.d-b else t1.b end) FROM t1 WHERE 19 not in ( -t1.f,+19,t1.b)} +} {} +do_test randexpr-2.283 { + db eval {SELECT coalesce((select a from t1 where (exists(select 1 from t1 where 11-case when ((select count(distinct t1.e+d) from t1))<>t1.d*f then -13 when t1.b in (select abs(cast(avg(c) AS integer)) from t1 union select count(distinct e)*count(distinct c)-cast(avg(e) AS integer) from t1) or c in (select t1.d from t1 union select 17 from t1) then a else t1.b end>=t1.c) and f>=d and d>=t1.f)),case when 11=19 and t1.a between t1.d and e then t1.d-b else t1.b end) FROM t1 WHERE NOT (19 not in ( -t1.f,+19,t1.b))} +} {200} +do_test randexpr-2.284 { + db eval {SELECT (~case when t1.f>(abs(t1.c)/abs(13-coalesce((select max(t1.a) from t1 where case when e not in (c,t1.a,~11) then 19+( -c) else a end in (select (19) from t1 union select t1.c from t1)),t1.b)+a)) and e>d and (t1.a)=e then t1.e when (not exists(select 1 from t1 where -t1.d=e) and -d in (select d from t1 union select e from t1)) then t1.b else a end) FROM t1 WHERE (t1.f in (select coalesce((select max(coalesce((select c from t1 where coalesce((select max(coalesce((select max(++13*t1.d) from t1 where case when case when e<>13 or b<= -t1.a then t1.c when t1.a not in ( - -13,t1.a,13) then a else c end not in ( -e,d,(11)) or t1.d -b then t1.e else t1.d endt1.b),c) not in (t1.e,c,b)),13)) from t1 where ((t1.f) in (select max(a) from t1 union select abs(abs(min(13))) from t1))),11) from t1 union select b from t1))} +} {} +do_test randexpr-2.285 { + db eval {SELECT (~case when t1.f>(abs(t1.c)/abs(13-coalesce((select max(t1.a) from t1 where case when e not in (c,t1.a,~11) then 19+( -c) else a end in (select (19) from t1 union select t1.c from t1)),t1.b)+a)) and e>d and (t1.a)=e then t1.e when (not exists(select 1 from t1 where -t1.d=e) and -d in (select d from t1 union select e from t1)) then t1.b else a end) FROM t1 WHERE NOT ((t1.f in (select coalesce((select max(coalesce((select c from t1 where coalesce((select max(coalesce((select max(++13*t1.d) from t1 where case when case when e<>13 or b<= -t1.a then t1.c when t1.a not in ( - -13,t1.a,13) then a else c end not in ( -e,d,(11)) or t1.d -b then t1.e else t1.d endt1.b),c) not in (t1.e,c,b)),13)) from t1 where ((t1.f) in (select max(a) from t1 union select abs(abs(min(13))) from t1))),11) from t1 union select b from t1)))} +} {-101} +do_test randexpr-2.286 { + db eval {SELECT (select count(distinct case b when 13 then (select (+(cast(avg(+(d)*case t1.f-c*(abs(case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (d<=t1.e) or d between c and t1.b)) then 11 else 19 end in ((t1.d),t1.a,t1.f) then t1.f when c<=t1.e then t1.c else b end | a)/abs(c))+t1.b when t1.c then a else d end) AS integer))) from t1) else t1.b*(e) end) from t1) FROM t1 WHERE not t1.a+t1.b | t1.f-11*(select max(+case when case ~e-(abs(d*t1.d+t1.d)/abs( -f)) when t1.a then t1.e else t1.c end in (select cast(avg((f)) AS integer) from t1 union select +~(min(t1.d)) from t1) then (t1.d) when not exists(select 1 from t1 where a not in (17,a,d)) then 19 else -t1.a end* -t1.d) from t1)* -17>13} +} {1} +do_test randexpr-2.287 { + db eval {SELECT (select count(distinct case b when 13 then (select (+(cast(avg(+(d)*case t1.f-c*(abs(case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (d<=t1.e) or d between c and t1.b)) then 11 else 19 end in ((t1.d),t1.a,t1.f) then t1.f when c<=t1.e then t1.c else b end | a)/abs(c))+t1.b when t1.c then a else d end) AS integer))) from t1) else t1.b*(e) end) from t1) FROM t1 WHERE NOT (not t1.a+t1.b | t1.f-11*(select max(+case when case ~e-(abs(d*t1.d+t1.d)/abs( -f)) when t1.a then t1.e else t1.c end in (select cast(avg((f)) AS integer) from t1 union select +~(min(t1.d)) from t1) then (t1.d) when not exists(select 1 from t1 where a not in (17,a,d)) then 19 else -t1.a end* -t1.d) from t1)* -17>13)} +} {} +do_test randexpr-2.288 { + db eval {SELECT (select count(distinct case b when 13 then (select (+(cast(avg(+(d)*case t1.f-c*(abs(case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (d<=t1.e) or d between c and t1.b)) then 11 else 19 end in ((t1.d),t1.a,t1.f) then t1.f when c<=t1.e then t1.c else b end & a)/abs(c))+t1.b when t1.c then a else d end) AS integer))) from t1) else t1.b*(e) end) from t1) FROM t1 WHERE not t1.a+t1.b | t1.f-11*(select max(+case when case ~e-(abs(d*t1.d+t1.d)/abs( -f)) when t1.a then t1.e else t1.c end in (select cast(avg((f)) AS integer) from t1 union select +~(min(t1.d)) from t1) then (t1.d) when not exists(select 1 from t1 where a not in (17,a,d)) then 19 else -t1.a end* -t1.d) from t1)* -17>13} +} {1} +do_test randexpr-2.289 { + db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where ((~t1.f) between b and (abs(e)/abs(f)))),13+(select case abs((+count(*)*max(19))) when (~min(b)) then -min(a) | min( -a) else (max(t1.c)) end from t1)+17*f+11)) from t1 where not 19<=coalesce((select e from t1 where t1.d-d not between 19 and 19),11)),13) FROM t1 WHERE t1.f+t1.d=t1.f+17-case when (abs(t1.a*(case when not exists(select 1 from t1 where not exists(select 1 from t1 where (b) between d and t1.f)) then (t1.b | -(t1.c)) | 19 when d=t1.a then 13 else d end)+ -t1.d)/abs(d)) not in (d,e,t1.d) then t1.f when 19 in (select t1.f from t1 union select t1.e from t1) then e else -t1.a end- - -t1.e*17-t1.d-t1.d} +} {} +do_test randexpr-2.290 { + db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where ((~t1.f) between b and (abs(e)/abs(f)))),13+(select case abs((+count(*)*max(19))) when (~min(b)) then -min(a) | min( -a) else (max(t1.c)) end from t1)+17*f+11)) from t1 where not 19<=coalesce((select e from t1 where t1.d-d not between 19 and 19),11)),13) FROM t1 WHERE NOT (t1.f+t1.d=t1.f+17-case when (abs(t1.a*(case when not exists(select 1 from t1 where not exists(select 1 from t1 where (b) between d and t1.f)) then (t1.b | -(t1.c)) | 19 when d=t1.a then 13 else d end)+ -t1.d)/abs(d)) not in (d,e,t1.d) then t1.f when 19 in (select t1.f from t1 union select t1.e from t1) then e else -t1.a end- - -t1.e*17-t1.d-t1.d)} +} {13} +do_test randexpr-2.291 { + db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where ((~t1.f) between b and (abs(e)/abs(f)))),13+(select case abs((+count(*)*max(19))) when (~min(b)) then -min(a) & min( -a) else (max(t1.c)) end from t1)+17*f+11)) from t1 where not 19<=coalesce((select e from t1 where t1.d-d not between 19 and 19),11)),13) FROM t1 WHERE NOT (t1.f+t1.d=t1.f+17-case when (abs(t1.a*(case when not exists(select 1 from t1 where not exists(select 1 from t1 where (b) between d and t1.f)) then (t1.b | -(t1.c)) | 19 when d=t1.a then 13 else d end)+ -t1.d)/abs(d)) not in (d,e,t1.d) then t1.f when 19 in (select t1.f from t1 union select t1.e from t1) then e else -t1.a end- - -t1.e*17-t1.d-t1.d)} +} {13} +do_test randexpr-2.292 { + db eval {SELECT case when -t1.b=c and ((t1.c>t1.b)) and not exists(select 1 from t1 where (abs((select max(t1.d) from t1))/abs((abs(c+t1.b)/abs(t1.d))-t1.e))+c in (select cast(avg((t1.a)) AS integer) | abs(count(distinct t1.d))+count(*) | count(*)+count(*) from t1 union select (min(t1.d)) from t1)) then (abs(t1.b)/abs(t1.f)) when t1.b not in (a,t1.f,(a)) then t1.b else t1.d end-11 FROM t1 WHERE case when ~e in (coalesce((select 13 from t1 where 17 between t1.a and b or not exists(select 1 from t1 where (c in (11,e,a)))),t1.e),c,e) then e else t1.f end in (select ++abs(case case count(*) when (max(t1.d)) then cast(avg(t1.c) AS integer) else count(distinct b) end | count(*) when max(e) then min(c) else max(13) end | count(*)*count(*)) | max(t1.a) from t1 union select count(distinct t1.c) from t1) or b in (select cast(avg(t1.b) AS integer) from t1 union select cast(avg( -t1.a) AS integer) from t1)} +} {189} +do_test randexpr-2.293 { + db eval {SELECT case when -t1.b=c and ((t1.c>t1.b)) and not exists(select 1 from t1 where (abs((select max(t1.d) from t1))/abs((abs(c+t1.b)/abs(t1.d))-t1.e))+c in (select cast(avg((t1.a)) AS integer) | abs(count(distinct t1.d))+count(*) | count(*)+count(*) from t1 union select (min(t1.d)) from t1)) then (abs(t1.b)/abs(t1.f)) when t1.b not in (a,t1.f,(a)) then t1.b else t1.d end-11 FROM t1 WHERE NOT (case when ~e in (coalesce((select 13 from t1 where 17 between t1.a and b or not exists(select 1 from t1 where (c in (11,e,a)))),t1.e),c,e) then e else t1.f end in (select ++abs(case case count(*) when (max(t1.d)) then cast(avg(t1.c) AS integer) else count(distinct b) end | count(*) when max(e) then min(c) else max(13) end | count(*)*count(*)) | max(t1.a) from t1 union select count(distinct t1.c) from t1) or b in (select cast(avg(t1.b) AS integer) from t1 union select cast(avg( -t1.a) AS integer) from t1))} +} {} +do_test randexpr-2.294 { + db eval {SELECT case when -t1.b=c and ((t1.c>t1.b)) and not exists(select 1 from t1 where (abs((select max(t1.d) from t1))/abs((abs(c+t1.b)/abs(t1.d))-t1.e))+c in (select cast(avg((t1.a)) AS integer) & abs(count(distinct t1.d))+count(*) & count(*)+count(*) from t1 union select (min(t1.d)) from t1)) then (abs(t1.b)/abs(t1.f)) when t1.b not in (a,t1.f,(a)) then t1.b else t1.d end-11 FROM t1 WHERE case when ~e in (coalesce((select 13 from t1 where 17 between t1.a and b or not exists(select 1 from t1 where (c in (11,e,a)))),t1.e),c,e) then e else t1.f end in (select ++abs(case case count(*) when (max(t1.d)) then cast(avg(t1.c) AS integer) else count(distinct b) end | count(*) when max(e) then min(c) else max(13) end | count(*)*count(*)) | max(t1.a) from t1 union select count(distinct t1.c) from t1) or b in (select cast(avg(t1.b) AS integer) from t1 union select cast(avg( -t1.a) AS integer) from t1)} +} {189} +do_test randexpr-2.295 { + db eval {SELECT case when (((abs(11 | e)/abs(17-d))+t1.b | a<>11)) and t1.d in (13,t1.c,11) or 17 between t1.f and b or not f in (select 19 from t1 union select t1.e from t1) and b<>19 or e between 19 and t1.d or b<=d or d<17 or t1.a<>t1.f then 17 when t1.e=t1.b then 11 else coalesce((select t1.e from t1 where (b) between - -d and e),t1.b) end FROM t1 WHERE t1.a between d and +17-17*coalesce((select ~ -19-13-19 from t1 where 19>(select abs(count(distinct t1.d-17))+count(distinct case when 19>17 then t1.f else t1.e end+b) | max(t1.b)+count(distinct 13) from t1)-coalesce((select 13 from t1 where t1.e not in (19,17,e) and 11<=t1.d),c)),t1.f)} +} {} +do_test randexpr-2.296 { + db eval {SELECT case when (((abs(11 | e)/abs(17-d))+t1.b | a<>11)) and t1.d in (13,t1.c,11) or 17 between t1.f and b or not f in (select 19 from t1 union select t1.e from t1) and b<>19 or e between 19 and t1.d or b<=d or d<17 or t1.a<>t1.f then 17 when t1.e=t1.b then 11 else coalesce((select t1.e from t1 where (b) between - -d and e),t1.b) end FROM t1 WHERE NOT (t1.a between d and +17-17*coalesce((select ~ -19-13-19 from t1 where 19>(select abs(count(distinct t1.d-17))+count(distinct case when 19>17 then t1.f else t1.e end+b) | max(t1.b)+count(distinct 13) from t1)-coalesce((select 13 from t1 where t1.e not in (19,17,e) and 11<=t1.d),c)),t1.f))} +} {17} +do_test randexpr-2.297 { + db eval {SELECT case when (((abs(11 & e)/abs(17-d))+t1.b & a<>11)) and t1.d in (13,t1.c,11) or 17 between t1.f and b or not f in (select 19 from t1 union select t1.e from t1) and b<>19 or e between 19 and t1.d or b<=d or d<17 or t1.a<>t1.f then 17 when t1.e=t1.b then 11 else coalesce((select t1.e from t1 where (b) between - -d and e),t1.b) end FROM t1 WHERE NOT (t1.a between d and +17-17*coalesce((select ~ -19-13-19 from t1 where 19>(select abs(count(distinct t1.d-17))+count(distinct case when 19>17 then t1.f else t1.e end+b) | max(t1.b)+count(distinct 13) from t1)-coalesce((select 13 from t1 where t1.e not in (19,17,e) and 11<=t1.d),c)),t1.f))} +} {17} +do_test randexpr-2.298 { + db eval {SELECT case when 19=13 or 13+a | 19*11+b<>b and ((19<=b+(select count(*) from t1))) then t1.d when t1.e<= -19 then d-t1.e+(select ~max(19)*+(count(distinct b)) from t1)+t1.d*t1.d+f else t1.c end FROM t1 WHERE (13*case when 19*case when 19 not between 17 and t1.e then t1.e when ((case when case case when e<>11 or t1.b not in (t1.a, -c,17) then b else a end when -e then b else a end*a in (select 19 from t1 union select 13 from t1) then e else t1.c end in (select -abs(+count(*)) from t1 union select count(distinct f) from t1))) then 19 else d end>=f then t1.a when t1.e>=b then a else c end>=t1.d)} +} {400} +do_test randexpr-2.299 { + db eval {SELECT case when 19=13 or 13+a | 19*11+b<>b and ((19<=b+(select count(*) from t1))) then t1.d when t1.e<= -19 then d-t1.e+(select ~max(19)*+(count(distinct b)) from t1)+t1.d*t1.d+f else t1.c end FROM t1 WHERE NOT ((13*case when 19*case when 19 not between 17 and t1.e then t1.e when ((case when case case when e<>11 or t1.b not in (t1.a, -c,17) then b else a end when -e then b else a end*a in (select 19 from t1 union select 13 from t1) then e else t1.c end in (select -abs(+count(*)) from t1 union select count(distinct f) from t1))) then 19 else d end>=f then t1.a when t1.e>=b then a else c end>=t1.d))} +} {} +do_test randexpr-2.300 { + db eval {SELECT case when 19=13 or 13+a & 19*11+b<>b and ((19<=b+(select count(*) from t1))) then t1.d when t1.e<= -19 then d-t1.e+(select ~max(19)*+(count(distinct b)) from t1)+t1.d*t1.d+f else t1.c end FROM t1 WHERE (13*case when 19*case when 19 not between 17 and t1.e then t1.e when ((case when case case when e<>11 or t1.b not in (t1.a, -c,17) then b else a end when -e then b else a end*a in (select 19 from t1 union select 13 from t1) then e else t1.c end in (select -abs(+count(*)) from t1 union select count(distinct f) from t1))) then 19 else d end>=f then t1.a when t1.e>=b then a else c end>=t1.d)} +} {400} +do_test randexpr-2.301 { + db eval {SELECT +coalesce((select t1.d from t1 where coalesce((select t1.c+t1.b-case (19) when t1.c then 13+13+17 else t1.e end from t1 where (not exists(select 1 from t1 where t1.f<13)) and d not in (t1.e,11,19) and not 19>=t1.f or e in (select min(t1.c) from t1 union select cast(avg(t1.c) AS integer) from t1)), -a)-b*(13)(+b))} +} {500} +do_test randexpr-2.302 { + db eval {SELECT +coalesce((select t1.d from t1 where coalesce((select t1.c+t1.b-case (19) when t1.c then 13+13+17 else t1.e end from t1 where (not exists(select 1 from t1 where t1.f<13)) and d not in (t1.e,11,19) and not 19>=t1.f or e in (select min(t1.c) from t1 union select cast(avg(t1.c) AS integer) from t1)), -a)-b*(13)(+b)))} +} {} +do_test randexpr-2.303 { + db eval {SELECT +coalesce((select t1.d from t1 where coalesce((select t1.c+t1.b-case (19) when t1.c then 13+13+17 else t1.e end from t1 where (not exists(select 1 from t1 where t1.f<13)) and d not in (t1.e,11,19) and not 19>=t1.f or e in (select min(t1.c) from t1 union select cast(avg(t1.c) AS integer) from t1)), -a)-b*(13)(+b))} +} {400} +do_test randexpr-2.304 { + db eval {SELECT case when (((t1.c)<=a-11*t1.e)) then t1.b else a end | ((abs(b*(abs(t1.e | +c)/abs(11)))/abs(t1.a))) FROM t1 WHERE case when t1.e in (select t1.a-e from t1 union select t1.e from t1) then 19*coalesce((select a*t1.c-19+f+t1.d-case case when 11>=d then f when not f<>17 then t1.d else t1.f end+t1.e-t1.c when d then b else t1.f end from t1 where t1.f>a), -t1.a)- -(t1.c)-t1.e+b else 11 end=d then f when not f<>17 then t1.d else t1.f end+t1.e-t1.c when d then b else t1.f end from t1 where t1.f>a), -t1.a)- -(t1.c)-t1.e+b else 11 end=d then f when not f<>17 then t1.d else t1.f end+t1.e-t1.c when d then b else t1.f end from t1 where t1.f>a), -t1.a)- -(t1.c)-t1.e+b else 11 enda),13)*11)-t1.c from t1 where 11 between t1.a and -13+t1.f*~coalesce((select max(b-f) from t1 where t1.a<=13 or a not in (13,f,17)),b) or (t1.d<19 or b> -t1.c)),b) FROM t1 WHERE 11 not between d and coalesce((select -(select (cast(avg(d) AS integer)) from t1) from t1 where case when 1713 then e when 19 between t1.a and t1.b then b else b end end*13<=c),t1.c) end in (select t1.e from t1 union select d from t1)),t1.b)} +} {300} +do_test randexpr-2.311 { + db eval {SELECT t1.f+coalesce((select t1.b-13-(coalesce((select 17 from t1 where b>a),13)*11)-t1.c from t1 where 11 between t1.a and -13+t1.f*~coalesce((select max(b-f) from t1 where t1.a<=13 or a not in (13,f,17)),b) or (t1.d<19 or b> -t1.c)),b) FROM t1 WHERE NOT (11 not between d and coalesce((select -(select (cast(avg(d) AS integer)) from t1) from t1 where case when 1713 then e when 19 between t1.a and t1.b then b else b end end*13<=c),t1.c) end in (select t1.e from t1 union select d from t1)),t1.b))} +} {} +do_test randexpr-2.312 { + db eval {SELECT (abs(13)/abs((select min(case when case when exists(select 1 from t1 where not exists(select 1 from t1 where (select count(distinct (t1.e)) from t1)+t1.f>t1.e) and t1.a>=13 or f in (select t1.e from t1 union select t1.e from t1)) then b when f not in (13,13,13) then coalesce((select max(d*f) from t1 where t1.e in (t1.d,t1.e,(e))),t1.e) else a end>=t1.f then b when t1.c in (e,f,t1.e) then b else t1.c end)*abs(count(*))-abs(~count(*)-min(e))-cast(avg(17) AS integer) from t1))) FROM t1 WHERE t1.b not in (a*17-17-case when -17-t1.f in (select coalesce((select t1.a from t1 where (d)=t1.a),d) from t1 union select 19 from t1) or 13 not between 17 and 13 and (19 between (t1.e) and t1.f) or ( -t1.e)>=17 then b when t1.d not in (19,f,t1.f) then a else case when t1.a=t1.d then e when 17 in (t1.e,t1.b,t1.d) then t1.a else a end end,e,11)} +} {0} +do_test randexpr-2.313 { + db eval {SELECT (abs(13)/abs((select min(case when case when exists(select 1 from t1 where not exists(select 1 from t1 where (select count(distinct (t1.e)) from t1)+t1.f>t1.e) and t1.a>=13 or f in (select t1.e from t1 union select t1.e from t1)) then b when f not in (13,13,13) then coalesce((select max(d*f) from t1 where t1.e in (t1.d,t1.e,(e))),t1.e) else a end>=t1.f then b when t1.c in (e,f,t1.e) then b else t1.c end)*abs(count(*))-abs(~count(*)-min(e))-cast(avg(17) AS integer) from t1))) FROM t1 WHERE NOT (t1.b not in (a*17-17-case when -17-t1.f in (select coalesce((select t1.a from t1 where (d)=t1.a),d) from t1 union select 19 from t1) or 13 not between 17 and 13 and (19 between (t1.e) and t1.f) or ( -t1.e)>=17 then b when t1.d not in (19,f,t1.f) then a else case when t1.a=t1.d then e when 17 in (t1.e,t1.b,t1.d) then t1.a else a end end,e,11))} +} {} +do_test randexpr-2.314 { + db eval {SELECT (abs(case coalesce((select t1.d* -case when d in (select cast(avg(13) AS integer)*abs(((cast(avg(d) AS integer)))+ -count(distinct c))-max(t1.c) from t1 union select min(e) from t1) then (abs(19)/abs(case when b not in (19,d,13) or t1.b not in (b,17,17) then e else b end)) else 19 end from t1 where a>=t1.c and 17 not in (t1.c,17,t1.f)),13)*t1.f when e then (11) else 17 end+19 | b)/abs(f))-t1.e FROM t1 WHERE not exists(select 1 from t1 where case a when coalesce((select max(case 19 when 17 then b-d else t1.e end) from t1 where ( -coalesce((select max(t1.a) from t1 where e between t1.b and (abs(e)/abs(17))),(abs(case when case when 13 between e and (t1.b) and 11 not in (t1.f,t1.e,c) then (t1.d) else -c end< -e then 11 when 13>t1.b then 11 else t1.a end*13)/abs((f)))-t1.a) not in (e,(b),t1.c))),19) then t1.b else 13 end not between t1.b and 11)} +} {} +do_test randexpr-2.315 { + db eval {SELECT (abs(case coalesce((select t1.d* -case when d in (select cast(avg(13) AS integer)*abs(((cast(avg(d) AS integer)))+ -count(distinct c))-max(t1.c) from t1 union select min(e) from t1) then (abs(19)/abs(case when b not in (19,d,13) or t1.b not in (b,17,17) then e else b end)) else 19 end from t1 where a>=t1.c and 17 not in (t1.c,17,t1.f)),13)*t1.f when e then (11) else 17 end+19 | b)/abs(f))-t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where case a when coalesce((select max(case 19 when 17 then b-d else t1.e end) from t1 where ( -coalesce((select max(t1.a) from t1 where e between t1.b and (abs(e)/abs(17))),(abs(case when case when 13 between e and (t1.b) and 11 not in (t1.f,t1.e,c) then (t1.d) else -c end< -e then 11 when 13>t1.b then 11 else t1.a end*13)/abs((f)))-t1.a) not in (e,(b),t1.c))),19) then t1.b else 13 end not between t1.b and 11))} +} {-500} +do_test randexpr-2.316 { + db eval {SELECT (abs(case coalesce((select t1.d* -case when d in (select cast(avg(13) AS integer)*abs(((cast(avg(d) AS integer)))+ -count(distinct c))-max(t1.c) from t1 union select min(e) from t1) then (abs(19)/abs(case when b not in (19,d,13) or t1.b not in (b,17,17) then e else b end)) else 19 end from t1 where a>=t1.c and 17 not in (t1.c,17,t1.f)),13)*t1.f when e then (11) else 17 end+19 & b)/abs(f))-t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where case a when coalesce((select max(case 19 when 17 then b-d else t1.e end) from t1 where ( -coalesce((select max(t1.a) from t1 where e between t1.b and (abs(e)/abs(17))),(abs(case when case when 13 between e and (t1.b) and 11 not in (t1.f,t1.e,c) then (t1.d) else -c end< -e then 11 when 13>t1.b then 11 else t1.a end*13)/abs((f)))-t1.a) not in (e,(b),t1.c))),19) then t1.b else 13 end not between t1.b and 11))} +} {-500} +do_test randexpr-2.317 { + db eval {SELECT -(+case when ~t1.d-f-case coalesce((select max((select (min((abs(t1.f)/abs(t1.b))-17)) from t1)) from t1 where e<=17),f) when t1.f then (select case -( -count(distinct b)) when cast(avg( -13) AS integer) then cast(avg(13) AS integer) else max(19) end from t1)-t1.e else 13 end*b between t1.c and t1.d then t1.d when et1.f),d)*t1.e)+max(t1.f)+cast(avg(e) AS integer) | (abs((count(distinct 17)))) from t1 union select max(t1.b) from t1) or 17 in (select -t1.b from t1 union select t1.a from t1) and exists(select 1 from t1 where t1.e=t1.c))),f+(t1.e)) FROM t1 WHERE exists(select 1 from t1 where +t1.d between (abs((abs(t1.c)/abs(case when not exists(select 1 from t1 where d*~(select abs(min(13))-( -(max(t1.f))*( -(count(distinct a)))-max(17)*min(t1.a) | (cast(avg(t1.b) AS integer))) from t1)>case when a in (select max(c) from t1 union select count(distinct -t1.a) from t1) or +17 in (select -count(distinct t1.f) from t1 union select cast(avg(t1.f) AS integer) from t1) then c else t1.a end) then -t1.f else t1.f end)))/abs(c+a)) and d)} +} {17} +do_test randexpr-2.323 { + db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where 11 in (select count(distinct d-coalesce((select t1.c-t1.f from t1 where 13 in (19,e,t1.b) and e in (select ( -count(*)) from t1 union select max(e) from t1) or t1.a>t1.f),d)*t1.e)+max(t1.f)+cast(avg(e) AS integer) | (abs((count(distinct 17)))) from t1 union select max(t1.b) from t1) or 17 in (select -t1.b from t1 union select t1.a from t1) and exists(select 1 from t1 where t1.e=t1.c))),f+(t1.e)) FROM t1 WHERE NOT (exists(select 1 from t1 where +t1.d between (abs((abs(t1.c)/abs(case when not exists(select 1 from t1 where d*~(select abs(min(13))-( -(max(t1.f))*( -(count(distinct a)))-max(17)*min(t1.a) | (cast(avg(t1.b) AS integer))) from t1)>case when a in (select max(c) from t1 union select count(distinct -t1.a) from t1) or +17 in (select -count(distinct t1.f) from t1 union select cast(avg(t1.f) AS integer) from t1) then c else t1.a end) then -t1.f else t1.f end)))/abs(c+a)) and d))} +} {} +do_test randexpr-2.324 { + db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where 11 in (select count(distinct d-coalesce((select t1.c-t1.f from t1 where 13 in (19,e,t1.b) and e in (select ( -count(*)) from t1 union select max(e) from t1) or t1.a>t1.f),d)*t1.e)+max(t1.f)+cast(avg(e) AS integer) & (abs((count(distinct 17)))) from t1 union select max(t1.b) from t1) or 17 in (select -t1.b from t1 union select t1.a from t1) and exists(select 1 from t1 where t1.e=t1.c))),f+(t1.e)) FROM t1 WHERE exists(select 1 from t1 where +t1.d between (abs((abs(t1.c)/abs(case when not exists(select 1 from t1 where d*~(select abs(min(13))-( -(max(t1.f))*( -(count(distinct a)))-max(17)*min(t1.a) | (cast(avg(t1.b) AS integer))) from t1)>case when a in (select max(c) from t1 union select count(distinct -t1.a) from t1) or +17 in (select -count(distinct t1.f) from t1 union select cast(avg(t1.f) AS integer) from t1) then c else t1.a end) then -t1.f else t1.f end)))/abs(c+a)) and d)} +} {17} +do_test randexpr-2.325 { + db eval {SELECT t1.d*17- -case when case (b) when t1.c then (abs(t1.f)/abs((select + -~abs(min(f) | +cast(avg(++t1.e+t1.d) AS integer) | ((count(distinct t1.a)-count(*)))) from t1))) else c*case t1.b when t1.d then (t1.c) else t1.c end*(b)-c end=t1.d then t1.c when -17=c then t1.e else t1.c end FROM t1 WHERE t1.b in (f,b,a)} +} {7100} +do_test randexpr-2.326 { + db eval {SELECT t1.d*17- -case when case (b) when t1.c then (abs(t1.f)/abs((select + -~abs(min(f) | +cast(avg(++t1.e+t1.d) AS integer) | ((count(distinct t1.a)-count(*)))) from t1))) else c*case t1.b when t1.d then (t1.c) else t1.c end*(b)-c end=t1.d then t1.c when -17=c then t1.e else t1.c end FROM t1 WHERE NOT (t1.b in (f,b,a))} +} {} +do_test randexpr-2.327 { + db eval {SELECT t1.d*17- -case when case (b) when t1.c then (abs(t1.f)/abs((select + -~abs(min(f) & +cast(avg(++t1.e+t1.d) AS integer) & ((count(distinct t1.a)-count(*)))) from t1))) else c*case t1.b when t1.d then (t1.c) else t1.c end*(b)-c end=t1.d then t1.c when -17=c then t1.e else t1.c end FROM t1 WHERE t1.b in (f,b,a)} +} {7100} +do_test randexpr-2.328 { + db eval {SELECT coalesce((select e-t1.d-+b*coalesce((select 11 from t1 where (t1.a<=coalesce((select - -coalesce((select max(case case 19 when t1.d then t1.e else t1.a end when b then 13 else t1.e end) from t1 where (c)>=(b)),t1.c)+t1.b from t1 where t1.e>e and exists(select 1 from t1 where b in (t1.b,e,t1.c) or e not between a and d) and 13(coalesce((select (f)+t1.c from t1 where a>t1.c),b))),t1.e)) then 19 else e end when t1.d then t1.e else b end from t1 where t1.b>=f),13)-b*17) from t1 where 11<>e),t1.b)<(c))} +} {500} +do_test randexpr-2.329 { + db eval {SELECT coalesce((select e-t1.d-+b*coalesce((select 11 from t1 where (t1.a<=coalesce((select - -coalesce((select max(case case 19 when t1.d then t1.e else t1.a end when b then 13 else t1.e end) from t1 where (c)>=(b)),t1.c)+t1.b from t1 where t1.e>e and exists(select 1 from t1 where b in (t1.b,e,t1.c) or e not between a and d) and 13(coalesce((select (f)+t1.c from t1 where a>t1.c),b))),t1.e)) then 19 else e end when t1.d then t1.e else b end from t1 where t1.b>=f),13)-b*17) from t1 where 11<>e),t1.b)<(c)))} +} {} +do_test randexpr-2.330 { + db eval {SELECT (abs(case when ++e not in (~c-(19)*+case t1.c when t1.d-coalesce((select max(t1.f) from t1 where (select count(*) from t1)>case when exists(select 1 from t1 where not exists(select 1 from t1 where (not not exists(select 1 from t1 where 19e),t1.e) when 13 then b else t1.c end end+f),c)*t1.c then t1.e else t1.b end,11,b) then -(t1.b) else a end)/abs(13)) FROM t1 WHERE a*t1.a<=17 and exists(select 1 from t1 where (+case coalesce((select max(f) from t1 where d in (select ((+count(*)-( -max(b))))*min(t1.c)* -max(11) from t1 union select count(distinct (19)) from t1)),t1.c) when 13 then 19 else coalesce((select t1.a from t1 where t1.c not in (t1.c,f,13)),b) end)>t1.c) and ( -( -19) between 13 and b or b in (select 11 from t1 union select a from t1) and 19 in (t1.d,t1.d,19))} +} {} +do_test randexpr-2.331 { + db eval {SELECT (abs(case when ++e not in (~c-(19)*+case t1.c when t1.d-coalesce((select max(t1.f) from t1 where (select count(*) from t1)>case when exists(select 1 from t1 where not exists(select 1 from t1 where (not not exists(select 1 from t1 where 19e),t1.e) when 13 then b else t1.c end end+f),c)*t1.c then t1.e else t1.b end,11,b) then -(t1.b) else a end)/abs(13)) FROM t1 WHERE NOT (a*t1.a<=17 and exists(select 1 from t1 where (+case coalesce((select max(f) from t1 where d in (select ((+count(*)-( -max(b))))*min(t1.c)* -max(11) from t1 union select count(distinct (19)) from t1)),t1.c) when 13 then 19 else coalesce((select t1.a from t1 where t1.c not in (t1.c,f,13)),b) end)>t1.c) and ( -( -19) between 13 and b or b in (select 11 from t1 union select a from t1) and 19 in (t1.d,t1.d,19)))} +} {15} +do_test randexpr-2.332 { + db eval {SELECT case when a>=f then -t1.a-11*t1.c when ((t1.e-t1.e+17 between (select max(c) from t1)-13 and coalesce((select t1.d from t1 where ((coalesce((select max(case when (not b>17) then t1.b-b when -e in (c,a,13) then 11 else t1.a end) from t1 where 19<=11),t1.e)>=e))),t1.a))) then c else t1.b end | 17 FROM t1 WHERE 11-t1.d+d-13+(t1.f*case when exists(select 1 from t1 where ( -coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where 19 in (select d from t1 union select t1.f from t1)))),t1.d)<=case when 13*11+11 in (select abs(+~abs( -min(c))) from t1 union select (min(t1.e)) from t1) then t1.f else 19 end)) then t1.c else (abs(e)/abs(19)) end*t1.f*f)<(t1.d)} +} {} +do_test randexpr-2.333 { + db eval {SELECT case when a>=f then -t1.a-11*t1.c when ((t1.e-t1.e+17 between (select max(c) from t1)-13 and coalesce((select t1.d from t1 where ((coalesce((select max(case when (not b>17) then t1.b-b when -e in (c,a,13) then 11 else t1.a end) from t1 where 19<=11),t1.e)>=e))),t1.a))) then c else t1.b end | 17 FROM t1 WHERE NOT (11-t1.d+d-13+(t1.f*case when exists(select 1 from t1 where ( -coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where 19 in (select d from t1 union select t1.f from t1)))),t1.d)<=case when 13*11+11 in (select abs(+~abs( -min(c))) from t1 union select (min(t1.e)) from t1) then t1.f else 19 end)) then t1.c else (abs(e)/abs(19)) end*t1.f*f)<(t1.d))} +} {217} +do_test randexpr-2.334 { + db eval {SELECT case when a>=f then -t1.a-11*t1.c when ((t1.e-t1.e+17 between (select max(c) from t1)-13 and coalesce((select t1.d from t1 where ((coalesce((select max(case when (not b>17) then t1.b-b when -e in (c,a,13) then 11 else t1.a end) from t1 where 19<=11),t1.e)>=e))),t1.a))) then c else t1.b end & 17 FROM t1 WHERE NOT (11-t1.d+d-13+(t1.f*case when exists(select 1 from t1 where ( -coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where 19 in (select d from t1 union select t1.f from t1)))),t1.d)<=case when 13*11+11 in (select abs(+~abs( -min(c))) from t1 union select (min(t1.e)) from t1) then t1.f else 19 end)) then t1.c else (abs(e)/abs(19)) end*t1.f*f)<(t1.d))} +} {0} +do_test randexpr-2.335 { + db eval {SELECT case ~13*c-t1.f- -t1.f when coalesce((select max(coalesce((select max(t1.c) from t1 where coalesce((select t1.d from t1 where 11*f-a=a),t1.e) in (select case ~count(distinct 11) | min(c) when (count(*))-count(*) then max( -17) else (min(13)) end from t1 union select - -cast(avg(b) AS integer) from t1)),19)-t1.c) from t1 where exists(select 1 from t1 where t1.b not between t1.e and 11 and ((a<>t1.f)) and (t1.a)=t1.d)),17) then t1.d else -b end FROM t1 WHERE case when ~13+t1.e-19>=13 then 17 else t1.c end>=a*19 and (f in (select case min(t1.e*+(abs(11)/abs(13))) when count(distinct t1.c) | abs((min(t1.b)-(max(t1.d)))+abs(max(a))+count(*)) | cast(avg(e) AS integer) then max(c) else max(c) end from t1 union select min(t1.c) from t1))} +} {} +do_test randexpr-2.336 { + db eval {SELECT case ~13*c-t1.f- -t1.f when coalesce((select max(coalesce((select max(t1.c) from t1 where coalesce((select t1.d from t1 where 11*f-a=a),t1.e) in (select case ~count(distinct 11) | min(c) when (count(*))-count(*) then max( -17) else (min(13)) end from t1 union select - -cast(avg(b) AS integer) from t1)),19)-t1.c) from t1 where exists(select 1 from t1 where t1.b not between t1.e and 11 and ((a<>t1.f)) and (t1.a)=t1.d)),17) then t1.d else -b end FROM t1 WHERE NOT (case when ~13+t1.e-19>=13 then 17 else t1.c end>=a*19 and (f in (select case min(t1.e*+(abs(11)/abs(13))) when count(distinct t1.c) | abs((min(t1.b)-(max(t1.d)))+abs(max(a))+count(*)) | cast(avg(e) AS integer) then max(c) else max(c) end from t1 union select min(t1.c) from t1)))} +} {-200} +do_test randexpr-2.337 { + db eval {SELECT case ~13*c-t1.f- -t1.f when coalesce((select max(coalesce((select max(t1.c) from t1 where coalesce((select t1.d from t1 where 11*f-a=a),t1.e) in (select case ~count(distinct 11) & min(c) when (count(*))-count(*) then max( -17) else (min(13)) end from t1 union select - -cast(avg(b) AS integer) from t1)),19)-t1.c) from t1 where exists(select 1 from t1 where t1.b not between t1.e and 11 and ((a<>t1.f)) and (t1.a)=t1.d)),17) then t1.d else -b end FROM t1 WHERE NOT (case when ~13+t1.e-19>=13 then 17 else t1.c end>=a*19 and (f in (select case min(t1.e*+(abs(11)/abs(13))) when count(distinct t1.c) | abs((min(t1.b)-(max(t1.d)))+abs(max(a))+count(*)) | cast(avg(e) AS integer) then max(c) else max(c) end from t1 union select min(t1.c) from t1)))} +} {-200} +do_test randexpr-2.338 { + db eval {SELECT f*13-t1.f*(abs(19*t1.a*c-(select ~max(t1.c)- -( -cast(avg(f) AS integer))+(max(d))*cast(avg(t1.d) AS integer)*(count(*)) from t1))/abs(case when coalesce((select (coalesce((select max(t1.c) from t1 where -(b)<> -t1.a),b)+11) from t1 where not (11)<=t1.e and c not between 17 and t1.e and b not in (f,(t1.a),t1.e)),t1.f) in (select t1.d from t1 union select 19 from t1) then t1.a when f>13 then t1.e else a end)) FROM t1 WHERE -b<>b*t1.e} +} {-484800} +do_test randexpr-2.339 { + db eval {SELECT f*13-t1.f*(abs(19*t1.a*c-(select ~max(t1.c)- -( -cast(avg(f) AS integer))+(max(d))*cast(avg(t1.d) AS integer)*(count(*)) from t1))/abs(case when coalesce((select (coalesce((select max(t1.c) from t1 where -(b)<> -t1.a),b)+11) from t1 where not (11)<=t1.e and c not between 17 and t1.e and b not in (f,(t1.a),t1.e)),t1.f) in (select t1.d from t1 union select 19 from t1) then t1.a when f>13 then t1.e else a end)) FROM t1 WHERE NOT ( -b<>b*t1.e)} +} {} +do_test randexpr-2.340 { + db eval {SELECT case when coalesce((select c from t1 where (13-(11-t1.e | t1.b) in (select +min(c)*+case +min(t1.e) when min(coalesce((select t1.e*t1.a from t1 where t1.f in (t1.d,11,t1.d) or t1.e>11 or t1.d>=c),17))+max(11)-count(distinct -a) | max(11)+min(t1.c)-max(13) then count(distinct c) else (max(13)) end from t1 union select (( -cast(avg(11) AS integer))) from t1))),d) in (select f from t1 union select t1.a from t1) then 17 else 19 end FROM t1 WHERE not exists(select 1 from t1 where (select +min(case when not (f*e between (select min(~~t1.d) from t1)*(abs(c)/abs(d)) and case when f=b then t1.f when not c>=17 then ~t1.b else 11 end else 19 end) from t1)-19 not in (d,t1.a,d))} +} {} +do_test randexpr-2.341 { + db eval {SELECT case when coalesce((select c from t1 where (13-(11-t1.e | t1.b) in (select +min(c)*+case +min(t1.e) when min(coalesce((select t1.e*t1.a from t1 where t1.f in (t1.d,11,t1.d) or t1.e>11 or t1.d>=c),17))+max(11)-count(distinct -a) | max(11)+min(t1.c)-max(13) then count(distinct c) else (max(13)) end from t1 union select (( -cast(avg(11) AS integer))) from t1))),d) in (select f from t1 union select t1.a from t1) then 17 else 19 end FROM t1 WHERE NOT (not exists(select 1 from t1 where (select +min(case when not (f*e between (select min(~~t1.d) from t1)*(abs(c)/abs(d)) and case when f=b then t1.f when not c>=17 then ~t1.b else 11 end else 19 end) from t1)-19 not in (d,t1.a,d)))} +} {19} +do_test randexpr-2.342 { + db eval {SELECT case when coalesce((select c from t1 where (13-(11-t1.e & t1.b) in (select +min(c)*+case +min(t1.e) when min(coalesce((select t1.e*t1.a from t1 where t1.f in (t1.d,11,t1.d) or t1.e>11 or t1.d>=c),17))+max(11)-count(distinct -a) & max(11)+min(t1.c)-max(13) then count(distinct c) else (max(13)) end from t1 union select (( -cast(avg(11) AS integer))) from t1))),d) in (select f from t1 union select t1.a from t1) then 17 else 19 end FROM t1 WHERE NOT (not exists(select 1 from t1 where (select +min(case when not (f*e between (select min(~~t1.d) from t1)*(abs(c)/abs(d)) and case when f=b then t1.f when not c>=17 then ~t1.b else 11 end else 19 end) from t1)-19 not in (d,t1.a,d)))} +} {19} +do_test randexpr-2.343 { + db eval {SELECT t1.c*a+(case when t1.b+11 | case when exists(select 1 from t1 where b<>17 or not exists(select 1 from t1 where t1.f in (19,t1.f,c)) or (t1.d)<>b) then e else d end+t1.b+t1.a*b=t1.d or d=b then t1.e when not exists(select 1 from t1 where b>t1.c or 17 between t1.f and e and d>=t1.c) then t1.d else c end) FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where (abs(c)/abs(b)) in (t1.a, -e*~e*17,17)))} +} {30400} +do_test randexpr-2.344 { + db eval {SELECT t1.c*a+(case when t1.b+11 | case when exists(select 1 from t1 where b<>17 or not exists(select 1 from t1 where t1.f in (19,t1.f,c)) or (t1.d)<>b) then e else d end+t1.b+t1.a*b=t1.d or d=b then t1.e when not exists(select 1 from t1 where b>t1.c or 17 between t1.f and e and d>=t1.c) then t1.d else c end) FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(c)/abs(b)) in (t1.a, -e*~e*17,17))))} +} {} +do_test randexpr-2.345 { + db eval {SELECT t1.c*a+(case when t1.b+11 & case when exists(select 1 from t1 where b<>17 or not exists(select 1 from t1 where t1.f in (19,t1.f,c)) or (t1.d)<>b) then e else d end+t1.b+t1.a*b=t1.d or d=b then t1.e when not exists(select 1 from t1 where b>t1.c or 17 between t1.f and e and d>=t1.c) then t1.d else c end) FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where (abs(c)/abs(b)) in (t1.a, -e*~e*17,17)))} +} {30400} +do_test randexpr-2.346 { + db eval {SELECT coalesce((select -b from t1 where t1.f=d),case when case -17-t1.b*t1.d+d when b then t1.a else t1.e end not in (t1.c,13,19) and e>f and 13 not between 17 and -f and e not between d and a then 13 when c<=a then 13 else 19 | e end)*a-d*t1.e FROM t1 WHERE (abs(+t1.f)/abs(coalesce((select max(coalesce((select max(e) from t1 where t1.a in (select (abs( -t1.b)/abs(a)) from t1 union select e from t1)),(abs(case t1.f when c then (select (~cast(avg(b*d) AS integer))*abs(min(11)) from t1) else coalesce((select f from t1 where d in (select ( -min(e)) from t1 union select -count(*) from t1)),t1.c) end*t1.b)/abs(c))+17)) from t1 where exists(select 1 from t1 where d not between t1.f and t1.b)),(t1.c))))*t1.d between t1.f and t1.a} +} {} +do_test randexpr-2.347 { + db eval {SELECT coalesce((select -b from t1 where t1.f=d),case when case -17-t1.b*t1.d+d when b then t1.a else t1.e end not in (t1.c,13,19) and e>f and 13 not between 17 and -f and e not between d and a then 13 when c<=a then 13 else 19 | e end)*a-d*t1.e FROM t1 WHERE NOT ((abs(+t1.f)/abs(coalesce((select max(coalesce((select max(e) from t1 where t1.a in (select (abs( -t1.b)/abs(a)) from t1 union select e from t1)),(abs(case t1.f when c then (select (~cast(avg(b*d) AS integer))*abs(min(11)) from t1) else coalesce((select f from t1 where d in (select ( -min(e)) from t1 union select -count(*) from t1)),t1.c) end*t1.b)/abs(c))+17)) from t1 where exists(select 1 from t1 where d not between t1.f and t1.b)),(t1.c))))*t1.d between t1.f and t1.a)} +} {-149700} +do_test randexpr-2.348 { + db eval {SELECT coalesce((select -b from t1 where t1.f=d),case when case -17-t1.b*t1.d+d when b then t1.a else t1.e end not in (t1.c,13,19) and e>f and 13 not between 17 and -f and e not between d and a then 13 when c<=a then 13 else 19 & e end)*a-d*t1.e FROM t1 WHERE NOT ((abs(+t1.f)/abs(coalesce((select max(coalesce((select max(e) from t1 where t1.a in (select (abs( -t1.b)/abs(a)) from t1 union select e from t1)),(abs(case t1.f when c then (select (~cast(avg(b*d) AS integer))*abs(min(11)) from t1) else coalesce((select f from t1 where d in (select ( -min(e)) from t1 union select -count(*) from t1)),t1.c) end*t1.b)/abs(c))+17)) from t1 where exists(select 1 from t1 where d not between t1.f and t1.b)),(t1.c))))*t1.d between t1.f and t1.a)} +} {-198400} +do_test randexpr-2.349 { + db eval {SELECT coalesce((select t1.b*19 from t1 where ~f in (select 19 from t1 union select ~b-+case 13 when coalesce((select max(a) from t1 where (abs(d)/abs(t1.d)) | t1.e-c-t1.d-t1.c+11*f-c+t1.a>17), -a) then f else t1.d end+17 | a*f | t1.c-d from t1)),19) FROM t1 WHERE t1.e*t1.c>coalesce((select 13 from t1 where ~t1.a<>case when exists(select 1 from t1 where e<>~d and not +17 not between a+case 13 when d then case t1.d when t1.a then b else 13 end else 13 end and 13) or 13 not in (t1.e,t1.f,t1.c) then 19-e+19 when f<=t1.f then b else 11 end),e)-13} +} {19} +do_test randexpr-2.350 { + db eval {SELECT coalesce((select t1.b*19 from t1 where ~f in (select 19 from t1 union select ~b-+case 13 when coalesce((select max(a) from t1 where (abs(d)/abs(t1.d)) | t1.e-c-t1.d-t1.c+11*f-c+t1.a>17), -a) then f else t1.d end+17 | a*f | t1.c-d from t1)),19) FROM t1 WHERE NOT (t1.e*t1.c>coalesce((select 13 from t1 where ~t1.a<>case when exists(select 1 from t1 where e<>~d and not +17 not between a+case 13 when d then case t1.d when t1.a then b else 13 end else 13 end and 13) or 13 not in (t1.e,t1.f,t1.c) then 19-e+19 when f<=t1.f then b else 11 end),e)-13)} +} {} +do_test randexpr-2.351 { + db eval {SELECT coalesce((select t1.b*19 from t1 where ~f in (select 19 from t1 union select ~b-+case 13 when coalesce((select max(a) from t1 where (abs(d)/abs(t1.d)) & t1.e-c-t1.d-t1.c+11*f-c+t1.a>17), -a) then f else t1.d end+17 & a*f & t1.c-d from t1)),19) FROM t1 WHERE t1.e*t1.c>coalesce((select 13 from t1 where ~t1.a<>case when exists(select 1 from t1 where e<>~d and not +17 not between a+case 13 when d then case t1.d when t1.a then b else 13 end else 13 end and 13) or 13 not in (t1.e,t1.f,t1.c) then 19-e+19 when f<=t1.f then b else 11 end),e)-13} +} {19} +do_test randexpr-2.352 { + db eval {SELECT (abs( -coalesce((select max((t1.f)) from t1 where not exists(select 1 from t1 where -b-~b not between t1.c and f and t1.d*( -(select abs(+count(*)) from t1))-d>=a) and case when +case when ((f)) in (select -count(distinct t1.a) from t1 union select count(*) from t1) then t1.b else d end in (select min(17) from t1 union select min(t1.e) from t1) then d else 17 end+c not between 11 and a),f)*11)/abs(a)) FROM t1 WHERE t1.f*t1.a*(+c)+case case when t1.d=f and (t1.a<>~+a*a*e*t1.e+case when t1.c between 11 and b and t1.a<>e then 13 when ( -t1.e)<>(t1.a) then (t1.b) else 13 end-t1.b-e+f) then t1.f+a else 17 end when d then 17 else d end-t1.e not in (13,t1.a,11)} +} {66} +do_test randexpr-2.353 { + db eval {SELECT (abs( -coalesce((select max((t1.f)) from t1 where not exists(select 1 from t1 where -b-~b not between t1.c and f and t1.d*( -(select abs(+count(*)) from t1))-d>=a) and case when +case when ((f)) in (select -count(distinct t1.a) from t1 union select count(*) from t1) then t1.b else d end in (select min(17) from t1 union select min(t1.e) from t1) then d else 17 end+c not between 11 and a),f)*11)/abs(a)) FROM t1 WHERE NOT (t1.f*t1.a*(+c)+case case when t1.d=f and (t1.a<>~+a*a*e*t1.e+case when t1.c between 11 and b and t1.a<>e then 13 when ( -t1.e)<>(t1.a) then (t1.b) else 13 end-t1.b-e+f) then t1.f+a else 17 end when d then 17 else d end-t1.e not in (13,t1.a,11))} +} {} +do_test randexpr-2.354 { + db eval {SELECT case t1.b- -t1.d+t1.d+t1.f when t1.f then 19+~13 else d end-case when not exists(select 1 from t1 where (f not between coalesce((select b from t1 where d in (17,13,t1.a) and 13 between c and 13 and 19>=f),13) and e or d not between 13 and f) or f>=d) then t1.f else coalesce((select max(~e-11) from t1 where t1.b in (f,13,13)),t1.a) end FROM t1 WHERE a=f),13) and e or d not between 13 and f) or f>=d) then t1.f else coalesce((select max(~e-11) from t1 where t1.b in (f,13,13)),t1.a) end FROM t1 WHERE NOT (a=t1.c and exists(select 1 from t1 where t1.f>=13) then t1.d when d between t1.d and t1.a then 19 else a end | e when (a) then e else a end between b and t1.c and not exists(select 1 from t1 where 13 in (t1.d,t1.a,13)) or t1.a>= -13),c) FROM t1 WHERE t1.e not in ( -coalesce((select max(13) from t1 where exists(select 1 from t1 where not t1.d>a) and t1.a not in (d*+case when t1.b in (select max(e*11+t1.a)+ -count(*)-( -max(t1.e))-min(11)-count(distinct t1.a) from t1 union select - -min(t1.b) from t1) then t1.e when e in (select count(distinct t1.a) from t1 union select (max(d)) from t1) then e else -(19) end+ -t1.d, -17,f)),case c when a then f else 17 end),d,11)} +} {-13} +do_test randexpr-2.357 { + db eval {SELECT -coalesce((select max(13) from t1 where case case when f in (select e from t1 union select coalesce((select max(e) from t1 where (select -max(e) from t1)*t1.e=t1.c and exists(select 1 from t1 where t1.f>=13) then t1.d when d between t1.d and t1.a then 19 else a end | e when (a) then e else a end between b and t1.c and not exists(select 1 from t1 where 13 in (t1.d,t1.a,13)) or t1.a>= -13),c) FROM t1 WHERE NOT (t1.e not in ( -coalesce((select max(13) from t1 where exists(select 1 from t1 where not t1.d>a) and t1.a not in (d*+case when t1.b in (select max(e*11+t1.a)+ -count(*)-( -max(t1.e))-min(11)-count(distinct t1.a) from t1 union select - -min(t1.b) from t1) then t1.e when e in (select count(distinct t1.a) from t1 union select (max(d)) from t1) then e else -(19) end+ -t1.d, -17,f)),case c when a then f else 17 end),d,11))} +} {} +do_test randexpr-2.358 { + db eval {SELECT -coalesce((select max(13) from t1 where case case when f in (select e from t1 union select coalesce((select max(e) from t1 where (select -max(e) from t1)*t1.e=t1.c and exists(select 1 from t1 where t1.f>=13) then t1.d when d between t1.d and t1.a then 19 else a end & e when (a) then e else a end between b and t1.c and not exists(select 1 from t1 where 13 in (t1.d,t1.a,13)) or t1.a>= -13),c) FROM t1 WHERE t1.e not in ( -coalesce((select max(13) from t1 where exists(select 1 from t1 where not t1.d>a) and t1.a not in (d*+case when t1.b in (select max(e*11+t1.a)+ -count(*)-( -max(t1.e))-min(11)-count(distinct t1.a) from t1 union select - -min(t1.b) from t1) then t1.e when e in (select count(distinct t1.a) from t1 union select (max(d)) from t1) then e else -(19) end+ -t1.d, -17,f)),case c when a then f else 17 end),d,11)} +} {-13} +do_test randexpr-2.359 { + db eval {SELECT case d when -e+coalesce((select max(case (select +abs((~case case count(distinct b) when -count(*) then count(*) else max(t1.e) end when max(e) then min(t1.c) else count(*) end-min(c))) from t1) when t1.c then t1.a else -11 end) from t1 where case ~t1.b when e then d else 11 end in (b,t1.e,t1.b) or not t1.f>=b or (t1.f in (a,e,t1.e)) or f=b or (t1.f in (a,e,t1.e)) or ft1.b) or t1.a not in (f,t1.b,t1.e) or t1.d<=t1.b and 19 not in (t1.d,11,t1.f) then t1.d else 19 end+e+17 end | -t1.c*d end-13 FROM t1 WHERE e not in (e,t1.b,t1.d)} +} {} +do_test randexpr-2.362 { + db eval {SELECT case a when ~c then e+17-d else case t1.a when c then t1.b else case when ((case t1.e when c then d-11 else t1.f end not in (e,(17),t1.d))) or not exists(select 1 from t1 where e not in (d,t1.f,11) and -t1.a>t1.b) or t1.a not in (f,t1.b,t1.e) or t1.d<=t1.b and 19 not in (t1.d,11,t1.f) then t1.d else 19 end+e+17 end | -t1.c*d end-13 FROM t1 WHERE NOT (e not in (e,t1.b,t1.d))} +} {-119864} +do_test randexpr-2.363 { + db eval {SELECT case a when ~c then e+17-d else case t1.a when c then t1.b else case when ((case t1.e when c then d-11 else t1.f end not in (e,(17),t1.d))) or not exists(select 1 from t1 where e not in (d,t1.f,11) and -t1.a>t1.b) or t1.a not in (f,t1.b,t1.e) or t1.d<=t1.b and 19 not in (t1.d,11,t1.f) then t1.d else 19 end+e+17 end & -t1.c*d end-13 FROM t1 WHERE NOT (e not in (e,t1.b,t1.d))} +} {755} +do_test randexpr-2.364 { + db eval {SELECT coalesce((select max(case t1.a when d then ~11 else t1.e end) from t1 where (t1.f*17=a or t1.e=t1.a and -c>=t1.b)),t1.b) FROM t1 WHERE a+( -t1.c) between case when case a when t1.f then ~t1.b*t1.c+17 else -case when f not in (e,f,17) then a when 11=13 then t1.c else t1.d end end>=t1.b then b when t1.d in (select +max(19) from t1 union select abs(cast(avg(t1.f) AS integer))+case ~count(*)-max(t1.a)+max(11) when (max(a)) then (max(t1.d)) else count(distinct 11) end from t1) and e in (t1.d,17,11) then (11) else b end and a} +} {} +do_test randexpr-2.365 { + db eval {SELECT coalesce((select max(case t1.a when d then ~11 else t1.e end) from t1 where (t1.f*17=a or t1.e=t1.a and -c>=t1.b)),t1.b) FROM t1 WHERE NOT (a+( -t1.c) between case when case a when t1.f then ~t1.b*t1.c+17 else -case when f not in (e,f,17) then a when 11=13 then t1.c else t1.d end end>=t1.b then b when t1.d in (select +max(19) from t1 union select abs(cast(avg(t1.f) AS integer))+case ~count(*)-max(t1.a)+max(11) when (max(a)) then (max(t1.d)) else count(distinct 11) end from t1) and e in (t1.d,17,11) then (11) else b end and a)} +} {200} +do_test randexpr-2.366 { + db eval {SELECT t1.f+case when c*f | (t1.a) in (select b*f from t1 union select -case when d not between ~13 | 13+case a when a then e else a end and f then 11 else e-t1.d end from t1) then -(abs(case when ((case t1.f when t1.b then t1.f else a end*f+t1.c)) in (select d from t1 union select (t1.e) from t1) then d else (t1.f) end)/abs(b)) else t1.a end FROM t1 WHERE ~(f+17-(select +max(t1.f)-case count(distinct d-19) when ~count(distinct (abs(b)/abs(a))) then cast(avg(17) AS integer) else ~count(distinct e)*count(*) end from t1)-f-coalesce((select t1.f from t1 where t1.a>=t1.c or t1.b between -t1.a and 19 or exists(select 1 from t1 where t1.e not in (13,t1.c,e)) and d>a),t1.d)) not between d and c} +} {700} +do_test randexpr-2.367 { + db eval {SELECT t1.f+case when c*f | (t1.a) in (select b*f from t1 union select -case when d not between ~13 | 13+case a when a then e else a end and f then 11 else e-t1.d end from t1) then -(abs(case when ((case t1.f when t1.b then t1.f else a end*f+t1.c)) in (select d from t1 union select (t1.e) from t1) then d else (t1.f) end)/abs(b)) else t1.a end FROM t1 WHERE NOT (~(f+17-(select +max(t1.f)-case count(distinct d-19) when ~count(distinct (abs(b)/abs(a))) then cast(avg(17) AS integer) else ~count(distinct e)*count(*) end from t1)-f-coalesce((select t1.f from t1 where t1.a>=t1.c or t1.b between -t1.a and 19 or exists(select 1 from t1 where t1.e not in (13,t1.c,e)) and d>a),t1.d)) not between d and c)} +} {} +do_test randexpr-2.368 { + db eval {SELECT t1.f+case when c*f & (t1.a) in (select b*f from t1 union select -case when d not between ~13 & 13+case a when a then e else a end and f then 11 else e-t1.d end from t1) then -(abs(case when ((case t1.f when t1.b then t1.f else a end*f+t1.c)) in (select d from t1 union select (t1.e) from t1) then d else (t1.f) end)/abs(b)) else t1.a end FROM t1 WHERE ~(f+17-(select +max(t1.f)-case count(distinct d-19) when ~count(distinct (abs(b)/abs(a))) then cast(avg(17) AS integer) else ~count(distinct e)*count(*) end from t1)-f-coalesce((select t1.f from t1 where t1.a>=t1.c or t1.b between -t1.a and 19 or exists(select 1 from t1 where t1.e not in (13,t1.c,e)) and d>a),t1.d)) not between d and c} +} {700} +do_test randexpr-2.369 { + db eval {SELECT case when coalesce((select d from t1 where not coalesce((select f*t1.b from t1 where exists(select 1 from t1 where (t1.f*t1.a)-19-13 in (select ~(cast(avg(t1.b) AS integer)) from t1 union select min(t1.a)+case min( -t1.a) when cast(avg(19) AS integer) then cast(avg(19) AS integer) else min(13) end+( -min(a)) from t1))),(t1.f)) between 17 and d),11)=19 then t1.b when 17<11 or exists(select 1 from t1 where d in (select 13 from t1 union select f from t1)) then 11 else t1.c end FROM t1 WHERE case c when 13 then +t1.d else t1.a end in (select abs(case + -count(*)+count(distinct coalesce((select (abs(~case when t1.c=19 | 13 then t1.c when not e>(13) then f else d end)/abs(a)) from t1 where 17>=t1.b),t1.b))+min(t1.a)*count(*) | (((max(a)))-cast(avg((17)) AS integer)) when max(d) then count(*) else cast(avg(t1.e) AS integer) end) from t1 union select count(*) from t1)} +} {} +do_test randexpr-2.370 { + db eval {SELECT case when coalesce((select d from t1 where not coalesce((select f*t1.b from t1 where exists(select 1 from t1 where (t1.f*t1.a)-19-13 in (select ~(cast(avg(t1.b) AS integer)) from t1 union select min(t1.a)+case min( -t1.a) when cast(avg(19) AS integer) then cast(avg(19) AS integer) else min(13) end+( -min(a)) from t1))),(t1.f)) between 17 and d),11)=19 then t1.b when 17<11 or exists(select 1 from t1 where d in (select 13 from t1 union select f from t1)) then 11 else t1.c end FROM t1 WHERE NOT (case c when 13 then +t1.d else t1.a end in (select abs(case + -count(*)+count(distinct coalesce((select (abs(~case when t1.c=19 | 13 then t1.c when not e>(13) then f else d end)/abs(a)) from t1 where 17>=t1.b),t1.b))+min(t1.a)*count(*) | (((max(a)))-cast(avg((17)) AS integer)) when max(d) then count(*) else cast(avg(t1.e) AS integer) end) from t1 union select count(*) from t1))} +} {300} +do_test randexpr-2.371 { + db eval {SELECT -(select count(*) from t1)*(select (+(cast(avg(+f) AS integer))+++case +max(t1.b-case when t1.e+t1.e>=11 then -a else t1.e end)-abs(min(e)+ -max(c) | ((max(11)))) when max(11) then (min(b)) else cast(avg( -b) AS integer) end-cast(avg(b) AS integer)-count(*)+count(*)) from t1)+~17- -t1.a FROM t1 WHERE f between 19*t1.d and 19} +} {} +do_test randexpr-2.372 { + db eval {SELECT -(select count(*) from t1)*(select (+(cast(avg(+f) AS integer))+++case +max(t1.b-case when t1.e+t1.e>=11 then -a else t1.e end)-abs(min(e)+ -max(c) | ((max(11)))) when max(11) then (min(b)) else cast(avg( -b) AS integer) end-cast(avg(b) AS integer)-count(*)+count(*)) from t1)+~17- -t1.a FROM t1 WHERE NOT (f between 19*t1.d and 19)} +} {-118} +do_test randexpr-2.373 { + db eval {SELECT -(select count(*) from t1)*(select (+(cast(avg(+f) AS integer))+++case +max(t1.b-case when t1.e+t1.e>=11 then -a else t1.e end)-abs(min(e)+ -max(c) & ((max(11)))) when max(11) then (min(b)) else cast(avg( -b) AS integer) end-cast(avg(b) AS integer)-count(*)+count(*)) from t1)+~17- -t1.a FROM t1 WHERE NOT (f between 19*t1.d and 19)} +} {-118} +do_test randexpr-2.374 { + db eval {SELECT case when not t1.a< -~~e then b when c*(select +case max((abs( -a)/abs(a))) when min(t1.b) then case ~min(t1.d)-cast(avg(e) AS integer) | max(e) when count(distinct 11) then count(*) else max(b) end else count(*) end from t1) not between 13 and case when exists(select 1 from t1 where exists(select 1 from t1 where f not in (19,t1.f,19)) and 11 between t1.b and t1.b) then (13) else -t1.d end then f else e end FROM t1 WHERE d>11} +} {200} +do_test randexpr-2.375 { + db eval {SELECT case when not t1.a< -~~e then b when c*(select +case max((abs( -a)/abs(a))) when min(t1.b) then case ~min(t1.d)-cast(avg(e) AS integer) | max(e) when count(distinct 11) then count(*) else max(b) end else count(*) end from t1) not between 13 and case when exists(select 1 from t1 where exists(select 1 from t1 where f not in (19,t1.f,19)) and 11 between t1.b and t1.b) then (13) else -t1.d end then f else e end FROM t1 WHERE NOT (d>11)} +} {} +do_test randexpr-2.376 { + db eval {SELECT case when not t1.a< -~~e then b when c*(select +case max((abs( -a)/abs(a))) when min(t1.b) then case ~min(t1.d)-cast(avg(e) AS integer) & max(e) when count(distinct 11) then count(*) else max(b) end else count(*) end from t1) not between 13 and case when exists(select 1 from t1 where exists(select 1 from t1 where f not in (19,t1.f,19)) and 11 between t1.b and t1.b) then (13) else -t1.d end then f else e end FROM t1 WHERE d>11} +} {200} +do_test randexpr-2.377 { + db eval {SELECT coalesce((select max(t1.c | ~17) from t1 where exists(select 1 from t1 where t1.f<>b-(abs(13)/abs(e)))),13) FROM t1 WHERE case when case (abs(c+a+19+coalesce((select max(t1.a) from t1 where coalesce((select coalesce((select (f) from t1 where t1.d between 19 and b),t1.a) from t1 where 13=(c)),f) in (select ~case count(*) when max(t1.b) then ((count(distinct 11))) else count(*) end- -count(distinct a) from t1 union select count(distinct 13) from t1)),t1.c) | t1.b+t1.d)/abs(e)) when t1.d then a else 17 end not between 19 and t1.f then t1.b else d end in (select t1.c from t1 union select (t1.a) from t1)} +} {} +do_test randexpr-2.378 { + db eval {SELECT coalesce((select max(t1.c | ~17) from t1 where exists(select 1 from t1 where t1.f<>b-(abs(13)/abs(e)))),13) FROM t1 WHERE NOT (case when case (abs(c+a+19+coalesce((select max(t1.a) from t1 where coalesce((select coalesce((select (f) from t1 where t1.d between 19 and b),t1.a) from t1 where 13=(c)),f) in (select ~case count(*) when max(t1.b) then ((count(distinct 11))) else count(*) end- -count(distinct a) from t1 union select count(distinct 13) from t1)),t1.c) | t1.b+t1.d)/abs(e)) when t1.d then a else 17 end not between 19 and t1.f then t1.b else d end in (select t1.c from t1 union select (t1.a) from t1))} +} {-18} +do_test randexpr-2.379 { + db eval {SELECT coalesce((select max(t1.c & ~17) from t1 where exists(select 1 from t1 where t1.f<>b-(abs(13)/abs(e)))),13) FROM t1 WHERE NOT (case when case (abs(c+a+19+coalesce((select max(t1.a) from t1 where coalesce((select coalesce((select (f) from t1 where t1.d between 19 and b),t1.a) from t1 where 13=(c)),f) in (select ~case count(*) when max(t1.b) then ((count(distinct 11))) else count(*) end- -count(distinct a) from t1 union select count(distinct 13) from t1)),t1.c) | t1.b+t1.d)/abs(e)) when t1.d then a else 17 end not between 19 and t1.f then t1.b else d end in (select t1.c from t1 union select (t1.a) from t1))} +} {300} +do_test randexpr-2.380 { + db eval {SELECT (coalesce((select (coalesce((select d from t1 where not exists(select 1 from t1 where 17>t1.c)),d))*c from t1 where t1.b between t1.d | (select count(distinct coalesce((select max(t1.e) from t1 where case when -e>t1.b then f when t1.a(abs(19*case when coalesce((select b*case when 11 not between 19 and (abs(13)/abs(t1.b-t1.d-e+b-f+19*t1.a)) then -t1.a else f end from t1 where (b=17)),f)= -t1.d then 17 when 11<>19 then f else t1.d end)/abs(t1.b)) then d else 19 end} +} {} +do_test randexpr-2.381 { + db eval {SELECT (coalesce((select (coalesce((select d from t1 where not exists(select 1 from t1 where 17>t1.c)),d))*c from t1 where t1.b between t1.d | (select count(distinct coalesce((select max(t1.e) from t1 where case when -e>t1.b then f when t1.a(abs(19*case when coalesce((select b*case when 11 not between 19 and (abs(13)/abs(t1.b-t1.d-e+b-f+19*t1.a)) then -t1.a else f end from t1 where (b=17)),f)= -t1.d then 17 when 11<>19 then f else t1.d end)/abs(t1.b)) then d else 19 end)} +} {-120289} +do_test randexpr-2.382 { + db eval {SELECT (coalesce((select (coalesce((select d from t1 where not exists(select 1 from t1 where 17>t1.c)),d))*c from t1 where t1.b between t1.d & (select count(distinct coalesce((select max(t1.e) from t1 where case when -e>t1.b then f when t1.a(abs(19*case when coalesce((select b*case when 11 not between 19 and (abs(13)/abs(t1.b-t1.d-e+b-f+19*t1.a)) then -t1.a else f end from t1 where (b=17)),f)= -t1.d then 17 when 11<>19 then f else t1.d end)/abs(t1.b)) then d else 19 end)} +} {-489} +do_test randexpr-2.383 { + db eval {SELECT 19*case when coalesce((select max(t1.e-c) from t1 where f=(abs(coalesce((select t1.c from t1 where not (not exists(select 1 from t1 where a in (select b from t1 union select c from t1)))),13))/abs(coalesce((select 13 from t1 where t1.b in (d,t1.d,a)), -t1.b)))),c) in (select ~min(t1.c) from t1 union select count(*) from t1) and -f<>t1.c then t1.a-t1.e when not t1.a in (select cast(avg(a) AS integer) from t1 union select min(13) from t1) then -19 else f end FROM t1 WHERE 11<>13} +} {11400} +do_test randexpr-2.384 { + db eval {SELECT 19*case when coalesce((select max(t1.e-c) from t1 where f=(abs(coalesce((select t1.c from t1 where not (not exists(select 1 from t1 where a in (select b from t1 union select c from t1)))),13))/abs(coalesce((select 13 from t1 where t1.b in (d,t1.d,a)), -t1.b)))),c) in (select ~min(t1.c) from t1 union select count(*) from t1) and -f<>t1.c then t1.a-t1.e when not t1.a in (select cast(avg(a) AS integer) from t1 union select min(13) from t1) then -19 else f end FROM t1 WHERE NOT (11<>13)} +} {} +do_test randexpr-2.385 { + db eval {SELECT t1.b*(select max(t1.b*coalesce((select max(t1.f*(t1.b)) from t1 where 17 not in (d,(a),(t1.b)+13)),t1.c)-t1.a) | cast(avg(t1.d) AS integer) | ~+case abs(abs(count(distinct t1.b))) when ~count(distinct e)-(count(*)) then max(t1.e) else max(d) end | max((19)) | min(19) from t1)-t1.d-t1.d*17 FROM t1 WHERE t1.f-case t1.d+19+13*case when (abs(e)/abs((select count(*)+cast(avg(a) AS integer)*count(*) from t1)-c*(abs(d)/abs(c*t1.e-19)))) not in (17,17,t1.a) then t1.f when t1.d<>t1.f then b else d end+ - -f*t1.b*d when b then 11 else -13 end<=(t1.b)} +} {} +do_test randexpr-2.386 { + db eval {SELECT t1.b*(select max(t1.b*coalesce((select max(t1.f*(t1.b)) from t1 where 17 not in (d,(a),(t1.b)+13)),t1.c)-t1.a) | cast(avg(t1.d) AS integer) | ~+case abs(abs(count(distinct t1.b))) when ~count(distinct e)-(count(*)) then max(t1.e) else max(d) end | max((19)) | min(19) from t1)-t1.d-t1.d*17 FROM t1 WHERE NOT (t1.f-case t1.d+19+13*case when (abs(e)/abs((select count(*)+cast(avg(a) AS integer)*count(*) from t1)-c*(abs(d)/abs(c*t1.e-19)))) not in (17,17,t1.a) then t1.f when t1.d<>t1.f then b else d end+ - -f*t1.b*d when b then 11 else -13 end<=(t1.b))} +} {-7400} +do_test randexpr-2.387 { + db eval {SELECT t1.b*(select max(t1.b*coalesce((select max(t1.f*(t1.b)) from t1 where 17 not in (d,(a),(t1.b)+13)),t1.c)-t1.a) & cast(avg(t1.d) AS integer) & ~+case abs(abs(count(distinct t1.b))) when ~count(distinct e)-(count(*)) then max(t1.e) else max(d) end & max((19)) & min(19) from t1)-t1.d-t1.d*17 FROM t1 WHERE NOT (t1.f-case t1.d+19+13*case when (abs(e)/abs((select count(*)+cast(avg(a) AS integer)*count(*) from t1)-c*(abs(d)/abs(c*t1.e-19)))) not in (17,17,t1.a) then t1.f when t1.d<>t1.f then b else d end+ - -f*t1.b*d when b then 11 else -13 end<=(t1.b))} +} {-7200} +do_test randexpr-2.388 { + db eval {SELECT (select abs(count(distinct t1.e) | min(b))-cast(avg(c) AS integer) | case +~+max(t1.a)*abs(+~ - -+cast(avg(19*f) AS integer) | count(*) | ~max(b) | ((max(t1.e)))-count(distinct t1.d)+ -(count(distinct t1.c)))* -count(distinct 17) | count(distinct a) when ((count(distinct t1.d))) then -min(t1.c) else count(distinct t1.c) end- -min(d) from t1) FROM t1 WHERE ((not exists(select 1 from t1 where c=f)) and case when not 19+t1.c- -11+11+e>=a or t1.d>b then f else t1.e end<> -t1.c) or (t1.a in (select +count(*) from t1 union select abs((case max(d) when count(distinct d) then min( -t1.e) else count(distinct a) end-count(distinct -t1.f)))*count(*) from t1) or not exists(select 1 from t1 where t1.d not in (c,17,e)))} +} {-99} +do_test randexpr-2.389 { + db eval {SELECT (select abs(count(distinct t1.e) | min(b))-cast(avg(c) AS integer) | case +~+max(t1.a)*abs(+~ - -+cast(avg(19*f) AS integer) | count(*) | ~max(b) | ((max(t1.e)))-count(distinct t1.d)+ -(count(distinct t1.c)))* -count(distinct 17) | count(distinct a) when ((count(distinct t1.d))) then -min(t1.c) else count(distinct t1.c) end- -min(d) from t1) FROM t1 WHERE NOT (((not exists(select 1 from t1 where c=f)) and case when not 19+t1.c- -11+11+e>=a or t1.d>b then f else t1.e end<> -t1.c) or (t1.a in (select +count(*) from t1 union select abs((case max(d) when count(distinct d) then min( -t1.e) else count(distinct a) end-count(distinct -t1.f)))*count(*) from t1) or not exists(select 1 from t1 where t1.d not in (c,17,e))))} +} {} +do_test randexpr-2.390 { + db eval {SELECT (select abs(count(distinct t1.e) & min(b))-cast(avg(c) AS integer) & case +~+max(t1.a)*abs(+~ - -+cast(avg(19*f) AS integer) & count(*) & ~max(b) & ((max(t1.e)))-count(distinct t1.d)+ -(count(distinct t1.c)))* -count(distinct 17) & count(distinct a) when ((count(distinct t1.d))) then -min(t1.c) else count(distinct t1.c) end- -min(d) from t1) FROM t1 WHERE ((not exists(select 1 from t1 where c=f)) and case when not 19+t1.c- -11+11+e>=a or t1.d>b then f else t1.e end<> -t1.c) or (t1.a in (select +count(*) from t1 union select abs((case max(d) when count(distinct d) then min( -t1.e) else count(distinct a) end-count(distinct -t1.f)))*count(*) from t1) or not exists(select 1 from t1 where t1.d not in (c,17,e)))} +} {144} +do_test randexpr-2.391 { + db eval {SELECT case when exists(select 1 from t1 where coalesce((select b from t1 where case when (b -11 then -t1.c else -b end then d else t1.a end) not in (t1.b,d,t1.b)} +} {300} +do_test randexpr-2.392 { + db eval {SELECT case when exists(select 1 from t1 where coalesce((select b from t1 where case when (b -11 then -t1.c else -b end then d else t1.a end) not in (t1.b,d,t1.b))} +} {} +do_test randexpr-2.393 { + db eval {SELECT t1.f+coalesce((select t1.a-t1.d*f-coalesce((select max(coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where a=~t1.d+case when (c in (select abs(~( -cast(avg(e) AS integer))) from t1 union select -min(19) from t1)) and 19<>t1.e or t1.e<11 and c in (t1.b,t1.b,t1.d) or 17 between -t1.d and t1.d then 11 else d end)),c-f)) from t1 where t1.a<=t1.c),11)-t1.c from t1 where f between t1.a and d),19) FROM t1 WHERE exists(select 1 from t1 where case +t1.d when d then f else t1.e end in (t1.e,17,11) or 13*e-t1.b in (select t1.e from t1 union select 17 from t1)) and 11<=case -case when not exists(select 1 from t1 where (17 | t1.e in (11,11,11) and b<(19))) then case t1.c+t1.f+c when t1.b then c else 19 end else 17 end when d then t1.b else t1.a end} +} {} +do_test randexpr-2.394 { + db eval {SELECT t1.f+coalesce((select t1.a-t1.d*f-coalesce((select max(coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where a=~t1.d+case when (c in (select abs(~( -cast(avg(e) AS integer))) from t1 union select -min(19) from t1)) and 19<>t1.e or t1.e<11 and c in (t1.b,t1.b,t1.d) or 17 between -t1.d and t1.d then 11 else d end)),c-f)) from t1 where t1.a<=t1.c),11)-t1.c from t1 where f between t1.a and d),19) FROM t1 WHERE NOT (exists(select 1 from t1 where case +t1.d when d then f else t1.e end in (t1.e,17,11) or 13*e-t1.b in (select t1.e from t1 union select 17 from t1)) and 11<=case -case when not exists(select 1 from t1 where (17 | t1.e in (11,11,11) and b<(19))) then case t1.c+t1.f+c when t1.b then c else 19 end else 17 end when d then t1.b else t1.a end)} +} {619} +do_test randexpr-2.395 { + db eval {SELECT case when (coalesce((select coalesce((select max( -11) from t1 where not case t1.c*case when exists(select 1 from t1 where (t1.d) in (select case count(*) when count(distinct t1.c) then count(*) else count(*) end from t1 union select cast(avg(t1.c) AS integer) from t1)) then +e when f=19 then 17 else t1.e end when t1.a then 19 else c end=e),t1.a)- -d*f-a from t1 where (t1.e)<>13),19)*(a)=19) then (c) when (exists(select 1 from t1 where 17=t1.d)) then 19 else c end FROM t1 WHERE t1.d*c*(select cast(avg(((abs(t1.d*13)/abs(f)))) AS integer) from t1)+t1.d=case when +(coalesce((select t1.a from t1 where case when not exists(select 1 from t1 where not exists(select 1 from t1 where c=t1.e)) then 19 | -17 else 13 end not in (t1.f,b,t1.b)),t1.f))*t1.a-t1.c-13 in (e,11,t1.c) then t1.a when (d between -t1.f and f) then t1.d else t1.a end} +} {} +do_test randexpr-2.396 { + db eval {SELECT case when (coalesce((select coalesce((select max( -11) from t1 where not case t1.c*case when exists(select 1 from t1 where (t1.d) in (select case count(*) when count(distinct t1.c) then count(*) else count(*) end from t1 union select cast(avg(t1.c) AS integer) from t1)) then +e when f=19 then 17 else t1.e end when t1.a then 19 else c end=e),t1.a)- -d*f-a from t1 where (t1.e)<>13),19)*(a)=19) then (c) when (exists(select 1 from t1 where 17=t1.d)) then 19 else c end FROM t1 WHERE NOT (t1.d*c*(select cast(avg(((abs(t1.d*13)/abs(f)))) AS integer) from t1)+t1.d=case when +(coalesce((select t1.a from t1 where case when not exists(select 1 from t1 where not exists(select 1 from t1 where c=t1.e)) then 19 | -17 else 13 end not in (t1.f,b,t1.b)),t1.f))*t1.a-t1.c-13 in (e,11,t1.c) then t1.a when (d between -t1.f and f) then t1.d else t1.a end)} +} {300} +do_test randexpr-2.397 { + db eval {SELECT coalesce((select d from t1 where f in (select max(19) from t1 union select ~+max(t1.e) from t1)),b-case -11 when 13 then t1.a-e else case when not exists(select 1 from t1 where c not in ( -t1.c,(t1.e),19)) and d+t1.b-t1.b in (select t1.a from t1 union select t1.d from t1) then 19+19*(t1.f) when t1.b<=a then 17 else t1.a end end+t1.b)*t1.a FROM t1 WHERE (select +cast(avg(~13+(select count(*) from t1)) AS integer)++min(case when (not d<>a) then coalesce((select t1.b from t1 where t1.f not between e and t1.d),13)+13 when t1.d not between 11 and t1.d then 17 else f end) | count(*) | ~count(distinct t1.e) | cast(avg(e) AS integer)-max(t1.d) from t1) not between coalesce((select case t1.a when a then e else 17 end from t1 where t1.a in (t1.e,11,( -t1.d))), -(b)) and t1.a} +} {} +do_test randexpr-2.398 { + db eval {SELECT coalesce((select d from t1 where f in (select max(19) from t1 union select ~+max(t1.e) from t1)),b-case -11 when 13 then t1.a-e else case when not exists(select 1 from t1 where c not in ( -t1.c,(t1.e),19)) and d+t1.b-t1.b in (select t1.a from t1 union select t1.d from t1) then 19+19*(t1.f) when t1.b<=a then 17 else t1.a end end+t1.b)*t1.a FROM t1 WHERE NOT ((select +cast(avg(~13+(select count(*) from t1)) AS integer)++min(case when (not d<>a) then coalesce((select t1.b from t1 where t1.f not between e and t1.d),13)+13 when t1.d not between 11 and t1.d then 17 else f end) | count(*) | ~count(distinct t1.e) | cast(avg(e) AS integer)-max(t1.d) from t1) not between coalesce((select case t1.a when a then e else 17 end from t1 where t1.a in (t1.e,11,( -t1.d))), -(b)) and t1.a)} +} {30000} +do_test randexpr-2.399 { + db eval {SELECT (abs(c)/abs((coalesce((select t1.d from t1 where ((19) in (select count(distinct - -(abs(coalesce((select max(t1.e) from t1 where t1.c*t1.a | t1.d=t1.d or t1.f in (select min(t1.f)-cast(avg(e) AS integer) from t1 union select -count(*) from t1)),c))/abs(a))) from t1 union select case cast(avg(c) AS integer)-abs( -((count(*))))*(count(*))*min(d) when cast(avg(a) AS integer) then count(distinct 11) else count(*) end-(count(distinct 17)) from t1))),a))))*t1.e FROM t1 WHERE case when a between -t1.a+(t1.c) and c-case when (~+t1.b-~case when t1.a not between 19*11 and 11 then t1.a when 11=f and -t1.d not between t1.a and d then e else b end in (select min(19) from t1 union select case count(distinct 17) when count(*) then count(distinct t1.f) else min(c) end from t1)) then t1.f else 17 end then 17 else 13 end in (t1.a,t1.d,a)} +} {} +do_test randexpr-2.400 { + db eval {SELECT (abs(c)/abs((coalesce((select t1.d from t1 where ((19) in (select count(distinct - -(abs(coalesce((select max(t1.e) from t1 where t1.c*t1.a | t1.d=t1.d or t1.f in (select min(t1.f)-cast(avg(e) AS integer) from t1 union select -count(*) from t1)),c))/abs(a))) from t1 union select case cast(avg(c) AS integer)-abs( -((count(*))))*(count(*))*min(d) when cast(avg(a) AS integer) then count(distinct 11) else count(*) end-(count(distinct 17)) from t1))),a))))*t1.e FROM t1 WHERE NOT (case when a between -t1.a+(t1.c) and c-case when (~+t1.b-~case when t1.a not between 19*11 and 11 then t1.a when 11=f and -t1.d not between t1.a and d then e else b end in (select min(19) from t1 union select case count(distinct 17) when count(*) then count(distinct t1.f) else min(c) end from t1)) then t1.f else 17 end then 17 else 13 end in (t1.a,t1.d,a))} +} {1500} +do_test randexpr-2.401 { + db eval {SELECT (abs(c)/abs((coalesce((select t1.d from t1 where ((19) in (select count(distinct - -(abs(coalesce((select max(t1.e) from t1 where t1.c*t1.a & t1.d=t1.d or t1.f in (select min(t1.f)-cast(avg(e) AS integer) from t1 union select -count(*) from t1)),c))/abs(a))) from t1 union select case cast(avg(c) AS integer)-abs( -((count(*))))*(count(*))*min(d) when cast(avg(a) AS integer) then count(distinct 11) else count(*) end-(count(distinct 17)) from t1))),a))))*t1.e FROM t1 WHERE NOT (case when a between -t1.a+(t1.c) and c-case when (~+t1.b-~case when t1.a not between 19*11 and 11 then t1.a when 11=f and -t1.d not between t1.a and d then e else b end in (select min(19) from t1 union select case count(distinct 17) when count(*) then count(distinct t1.f) else min(c) end from t1)) then t1.f else 17 end then 17 else 13 end in (t1.a,t1.d,a))} +} {1500} +do_test randexpr-2.402 { + db eval {SELECT case when d=c-(select (~max(t1.f*t1.c-11)) from t1) then coalesce((select max(19) from t1 where 13d then t1.e when not not exists(select 1 from t1 where t1.c not in (a,a,t1.d) and d not between b and 19) then t1.a else 11 end*f-f from t1 where t1.f between e and e and d between 19 and t1.e or 11<>t1.a),t1.c)),d) else 17 end FROM t1 WHERE (t1.e=11)} +} {} +do_test randexpr-2.403 { + db eval {SELECT case when d=c-(select (~max(t1.f*t1.c-11)) from t1) then coalesce((select max(19) from t1 where 13d then t1.e when not not exists(select 1 from t1 where t1.c not in (a,a,t1.d) and d not between b and 19) then t1.a else 11 end*f-f from t1 where t1.f between e and e and d between 19 and t1.e or 11<>t1.a),t1.c)),d) else 17 end FROM t1 WHERE NOT ((t1.e=11))} +} {17} +do_test randexpr-2.404 { + db eval {SELECT case when t1.a-t1.a | case when (abs(t1.d)/abs(t1.c | t1.a))<>t1.e then e*+t1.c-t1.d*coalesce((select t1.b from t1 where b>=+d+ -e*11),11)+t1.b | t1.f when not exists(select 1 from t1 where d not in (17,e,d)) then 11 else t1.d end>=13 then 11 when d=c then a else f end FROM t1 WHERE (abs(case when not t1.d<=t1.f and not t1.d not between -f and -17-11*t1.d and (13d then t1.d*coalesce((select max(t1.a) from t1 where (17) not between (t1.b) and 11),d) else t1.d end)/abs(f)) not between 13 and 19} +} {11} +do_test randexpr-2.405 { + db eval {SELECT case when t1.a-t1.a | case when (abs(t1.d)/abs(t1.c | t1.a))<>t1.e then e*+t1.c-t1.d*coalesce((select t1.b from t1 where b>=+d+ -e*11),11)+t1.b | t1.f when not exists(select 1 from t1 where d not in (17,e,d)) then 11 else t1.d end>=13 then 11 when d=c then a else f end FROM t1 WHERE NOT ((abs(case when not t1.d<=t1.f and not t1.d not between -f and -17-11*t1.d and (13d then t1.d*coalesce((select max(t1.a) from t1 where (17) not between (t1.b) and 11),d) else t1.d end)/abs(f)) not between 13 and 19)} +} {} +do_test randexpr-2.406 { + db eval {SELECT case when t1.a-t1.a & case when (abs(t1.d)/abs(t1.c & t1.a))<>t1.e then e*+t1.c-t1.d*coalesce((select t1.b from t1 where b>=+d+ -e*11),11)+t1.b & t1.f when not exists(select 1 from t1 where d not in (17,e,d)) then 11 else t1.d end>=13 then 11 when d=c then a else f end FROM t1 WHERE (abs(case when not t1.d<=t1.f and not t1.d not between -f and -17-11*t1.d and (13d then t1.d*coalesce((select max(t1.a) from t1 where (17) not between (t1.b) and 11),d) else t1.d end)/abs(f)) not between 13 and 19} +} {600} +do_test randexpr-2.407 { + db eval {SELECT coalesce((select t1.f*13 from t1 where exists(select 1 from t1 where 13<=t1.e)),(abs(+ -17)/abs(c))) FROM t1 WHERE coalesce((select 17 from t1 where 11>++a-~t1.a+d | (19)),(abs(t1.c)/abs(case when case t1.c*17-case when b not between t1.b and f then t1.a when f>=a then 19 else 13 end when 19 then 13 else t1.f end not between c and a then c else 13 end)))> -e or 13 between f and c and t1.e>=b} +} {7800} +do_test randexpr-2.408 { + db eval {SELECT coalesce((select t1.f*13 from t1 where exists(select 1 from t1 where 13<=t1.e)),(abs(+ -17)/abs(c))) FROM t1 WHERE NOT (coalesce((select 17 from t1 where 11>++a-~t1.a+d | (19)),(abs(t1.c)/abs(case when case t1.c*17-case when b not between t1.b and f then t1.a when f>=a then 19 else 13 end when 19 then 13 else t1.f end not between c and a then c else 13 end)))> -e or 13 between f and c and t1.e>=b)} +} {} +do_test randexpr-2.409 { + db eval {SELECT ~+coalesce((select (select count(distinct +coalesce((select c from t1 where e>=13),+c)-t1.c) from t1) from t1 where case a when t1.d*(select cast(avg(case when t1.b*coalesce((select 17 from t1 where case -a when t1.b then d else (t1.f) end not in ((t1.e),a,t1.f)),t1.c)-c in (d,a,t1.c) then c else b end) AS integer) from t1)+t1.d then 13 else t1.e end not in (19,a,17)),13) FROM t1 WHERE +c in (a,17,t1.d)} +} {} +do_test randexpr-2.410 { + db eval {SELECT ~+coalesce((select (select count(distinct +coalesce((select c from t1 where e>=13),+c)-t1.c) from t1) from t1 where case a when t1.d*(select cast(avg(case when t1.b*coalesce((select 17 from t1 where case -a when t1.b then d else (t1.f) end not in ((t1.e),a,t1.f)),t1.c)-c in (d,a,t1.c) then c else b end) AS integer) from t1)+t1.d then 13 else t1.e end not in (19,a,17)),13) FROM t1 WHERE NOT (+c in (a,17,t1.d))} +} {-2} +do_test randexpr-2.411 { + db eval {SELECT f-coalesce((select t1.d from t1 where t1.a>11+t1.d),coalesce((select coalesce((select t1.d from t1 where 17>=d or (case c when t1.c then (t1.c) else t1.e end in (b,17,17) or t1.b>=t1.a) or t1.b<=e),case d when (19) then t1.d else t1.a end)-t1.d from t1 where 13 in (select ( -count(distinct (e)) | cast(avg(t1.d) AS integer)*count(*))+max( -11) | max( -c) from t1 union select count(distinct 11) from t1)),a)) FROM t1 WHERE not b<=13 or (coalesce((select max(t1.b) from t1 where b in (case when not a<>13 then 17 when -(select ~abs( -(max(f))+count(distinct t1.a)) from t1)+13>=t1.b then case c when t1.a then d else f end-c else t1.d end-19, -t1.d,f)),19)) not in (t1.a,c,t1.d) or t1.e>t1.f} +} {500} +do_test randexpr-2.412 { + db eval {SELECT f-coalesce((select t1.d from t1 where t1.a>11+t1.d),coalesce((select coalesce((select t1.d from t1 where 17>=d or (case c when t1.c then (t1.c) else t1.e end in (b,17,17) or t1.b>=t1.a) or t1.b<=e),case d when (19) then t1.d else t1.a end)-t1.d from t1 where 13 in (select ( -count(distinct (e)) | cast(avg(t1.d) AS integer)*count(*))+max( -11) | max( -c) from t1 union select count(distinct 11) from t1)),a)) FROM t1 WHERE NOT (not b<=13 or (coalesce((select max(t1.b) from t1 where b in (case when not a<>13 then 17 when -(select ~abs( -(max(f))+count(distinct t1.a)) from t1)+13>=t1.b then case c when t1.a then d else f end-c else t1.d end-19, -t1.d,f)),19)) not in (t1.a,c,t1.d) or t1.e>t1.f)} +} {} +do_test randexpr-2.413 { + db eval {SELECT f-coalesce((select t1.d from t1 where t1.a>11+t1.d),coalesce((select coalesce((select t1.d from t1 where 17>=d or (case c when t1.c then (t1.c) else t1.e end in (b,17,17) or t1.b>=t1.a) or t1.b<=e),case d when (19) then t1.d else t1.a end)-t1.d from t1 where 13 in (select ( -count(distinct (e)) & cast(avg(t1.d) AS integer)*count(*))+max( -11) & max( -c) from t1 union select count(distinct 11) from t1)),a)) FROM t1 WHERE not b<=13 or (coalesce((select max(t1.b) from t1 where b in (case when not a<>13 then 17 when -(select ~abs( -(max(f))+count(distinct t1.a)) from t1)+13>=t1.b then case c when t1.a then d else f end-c else t1.d end-19, -t1.d,f)),19)) not in (t1.a,c,t1.d) or t1.e>t1.f} +} {500} +do_test randexpr-2.414 { + db eval {SELECT coalesce((select e from t1 where (coalesce((select max(+e+e*11*t1.c-e) from t1 where exists(select 1 from t1 where (19<=~t1.f))),case (abs(t1.c)/abs(case t1.c when 19 then f*~case when t1.e+t1.d between -t1.f and (d) then b when (d=a) then t1.e else e end else c end*t1.a)) | f when (d) then 17 else t1.f end)coalesce((select coalesce((select e from t1 where case when -d+t1.e>e then coalesce((select d+b from t1 where exists(select 1 from t1 where not 13-b not in (f,a,d)) and (t1.b between (a) and t1.c)),c) when a=13 then t1.e else a end in (select t1.d from t1 union select t1.d from t1) and e not in (d, -19,11)),d) from t1 where not f in (t1.a,19,t1.d)),t1.d)} +} {} +do_test randexpr-2.415 { + db eval {SELECT coalesce((select e from t1 where (coalesce((select max(+e+e*11*t1.c-e) from t1 where exists(select 1 from t1 where (19<=~t1.f))),case (abs(t1.c)/abs(case t1.c when 19 then f*~case when t1.e+t1.d between -t1.f and (d) then b when (d=a) then t1.e else e end else c end*t1.a)) | f when (d) then 17 else t1.f end)coalesce((select coalesce((select e from t1 where case when -d+t1.e>e then coalesce((select d+b from t1 where exists(select 1 from t1 where not 13-b not in (f,a,d)) and (t1.b between (a) and t1.c)),c) when a=13 then t1.e else a end in (select t1.d from t1 union select t1.d from t1) and e not in (d, -19,11)),d) from t1 where not f in (t1.a,19,t1.d)),t1.d))} +} {13} +do_test randexpr-2.416 { + db eval {SELECT coalesce((select e from t1 where (coalesce((select max(+e+e*11*t1.c-e) from t1 where exists(select 1 from t1 where (19<=~t1.f))),case (abs(t1.c)/abs(case t1.c when 19 then f*~case when t1.e+t1.d between -t1.f and (d) then b when (d=a) then t1.e else e end else c end*t1.a)) & f when (d) then 17 else t1.f end)coalesce((select coalesce((select e from t1 where case when -d+t1.e>e then coalesce((select d+b from t1 where exists(select 1 from t1 where not 13-b not in (f,a,d)) and (t1.b between (a) and t1.c)),c) when a=13 then t1.e else a end in (select t1.d from t1 union select t1.d from t1) and e not in (d, -19,11)),d) from t1 where not f in (t1.a,19,t1.d)),t1.d))} +} {13} +do_test randexpr-2.417 { + db eval {SELECT (select count(distinct 11-17-11) from t1)-coalesce((select (abs(13)/abs(t1.b-c*11+coalesce((select max(f) from t1 where t1.a>t1.a),(e))*case when (abs(e)/abs(t1.b)) not between ~f and t1.e then c else (abs(t1.b)/abs(t1.d)) end | 13+b | b+t1.e)) from t1 where t1.c in (select t1.c from t1 union select (a) from t1)),19) FROM t1 WHERE t1.f>=19} +} {1} +do_test randexpr-2.418 { + db eval {SELECT (select count(distinct 11-17-11) from t1)-coalesce((select (abs(13)/abs(t1.b-c*11+coalesce((select max(f) from t1 where t1.a>t1.a),(e))*case when (abs(e)/abs(t1.b)) not between ~f and t1.e then c else (abs(t1.b)/abs(t1.d)) end | 13+b | b+t1.e)) from t1 where t1.c in (select t1.c from t1 union select (a) from t1)),19) FROM t1 WHERE NOT (t1.f>=19)} +} {} +do_test randexpr-2.419 { + db eval {SELECT (select count(distinct 11-17-11) from t1)-coalesce((select (abs(13)/abs(t1.b-c*11+coalesce((select max(f) from t1 where t1.a>t1.a),(e))*case when (abs(e)/abs(t1.b)) not between ~f and t1.e then c else (abs(t1.b)/abs(t1.d)) end & 13+b & b+t1.e)) from t1 where t1.c in (select t1.c from t1 union select (a) from t1)),19) FROM t1 WHERE t1.f>=19} +} {1} +do_test randexpr-2.420 { + db eval {SELECT coalesce((select max(case when 11+(select +abs(count(*)) from t1) not in (case when (case when not exists(select 1 from t1 where t1.d=f) then a else a end+11 in (select ((13)) from t1 union select t1.d from t1)) then (abs(t1.c)/abs(t1.b)) when a>=t1.c then b else f end,t1.a,c) then t1.a when b in (select cast(avg(t1.a) AS integer) | ~ -count(distinct 17) from t1 union select min(c) from t1) then b else -t1.e end) from t1 where d not between c and -t1.b and b=d and b between 13 and t1.c),(17)) FROM t1 WHERE t1.a in (coalesce((select max(e) from t1 where case case (select count(*) from t1)-~19 when t1.f*t1.d+coalesce((select max((select + -(((min(t1.b)))) | -(count(distinct t1.c)) | count(*) from t1)*11) from t1 where f>=case when d in ((d),t1.d,13) then 19 when 17=17 then 11 else a end),t1.e) then c else t1.f end when t1.e then f else t1.d end in (13,(13),c)),t1.d),t1.e,a)} +} {17} +do_test randexpr-2.421 { + db eval {SELECT coalesce((select max(case when 11+(select +abs(count(*)) from t1) not in (case when (case when not exists(select 1 from t1 where t1.d=f) then a else a end+11 in (select ((13)) from t1 union select t1.d from t1)) then (abs(t1.c)/abs(t1.b)) when a>=t1.c then b else f end,t1.a,c) then t1.a when b in (select cast(avg(t1.a) AS integer) | ~ -count(distinct 17) from t1 union select min(c) from t1) then b else -t1.e end) from t1 where d not between c and -t1.b and b=d and b between 13 and t1.c),(17)) FROM t1 WHERE NOT (t1.a in (coalesce((select max(e) from t1 where case case (select count(*) from t1)-~19 when t1.f*t1.d+coalesce((select max((select + -(((min(t1.b)))) | -(count(distinct t1.c)) | count(*) from t1)*11) from t1 where f>=case when d in ((d),t1.d,13) then 19 when 17=17 then 11 else a end),t1.e) then c else t1.f end when t1.e then f else t1.d end in (13,(13),c)),t1.d),t1.e,a))} +} {} +do_test randexpr-2.422 { + db eval {SELECT coalesce((select max(case when 11+(select +abs(count(*)) from t1) not in (case when (case when not exists(select 1 from t1 where t1.d=f) then a else a end+11 in (select ((13)) from t1 union select t1.d from t1)) then (abs(t1.c)/abs(t1.b)) when a>=t1.c then b else f end,t1.a,c) then t1.a when b in (select cast(avg(t1.a) AS integer) & ~ -count(distinct 17) from t1 union select min(c) from t1) then b else -t1.e end) from t1 where d not between c and -t1.b and b=d and b between 13 and t1.c),(17)) FROM t1 WHERE t1.a in (coalesce((select max(e) from t1 where case case (select count(*) from t1)-~19 when t1.f*t1.d+coalesce((select max((select + -(((min(t1.b)))) | -(count(distinct t1.c)) | count(*) from t1)*11) from t1 where f>=case when d in ((d),t1.d,13) then 19 when 17=17 then 11 else a end),t1.e) then c else t1.f end when t1.e then f else t1.d end in (13,(13),c)),t1.d),t1.e,a)} +} {17} +do_test randexpr-2.423 { + db eval {SELECT coalesce((select t1.a-case t1.a when c then coalesce((select case (abs(11-(abs(t1.b)/abs(t1.a)))/abs((abs(t1.c)/abs(t1.a))))-t1.f when t1.d then f else 19 end from t1 where +t1.b*a in (select t1.e from t1 union select c from t1) and e between d and 11),t1.b) else a end from t1 where exists(select 1 from t1 where ((a in (13,c,d)))) and -t1.e in ((t1.d),t1.a,t1.b)),t1.c) FROM t1 WHERE ++e*19 in (case when case when not (d<>case when -case when (t1.a not between b and -e) then 17 when f<>a then -t1.d else t1.a end not in (a,a,c) then b when b<=c then e else b end) then 19 when (t1.b not in ( -13,t1.a,a)) then t1.b | 13 else e end* -19*t1.acase when -case when (t1.a not between b and -e) then 17 when f<>a then -t1.d else t1.a end not in (a,a,c) then b when b<=c then e else b end) then 19 when (t1.b not in ( -13,t1.a,a)) then t1.b | 13 else e end* -19*t1.a~19)),f) when a- -t1.a | t1.f then t1.a*11-t1.e else coalesce((select max(t1.b) from t1 where not exists(select 1 from t1 where 17=t1.a or b>=f)),c) | t1.b end>19),t1.a))+c)-t1.c*e)/abs(t1.d)) FROM t1 WHERE a-t1.b not in (a,a-19-c | t1.d-d | e*t1.c*b,t1.e+t1.a)} +} {375} +do_test randexpr-2.426 { + db eval {SELECT (abs(e-((coalesce((select max(t1.c) from t1 where t1.f-a-case coalesce((select max(d) from t1 where (13<>~19)),f) when a- -t1.a | t1.f then t1.a*11-t1.e else coalesce((select max(t1.b) from t1 where not exists(select 1 from t1 where 17=t1.a or b>=f)),c) | t1.b end>19),t1.a))+c)-t1.c*e)/abs(t1.d)) FROM t1 WHERE NOT (a-t1.b not in (a,a-19-c | t1.d-d | e*t1.c*b,t1.e+t1.a))} +} {} +do_test randexpr-2.427 { + db eval {SELECT (abs(e-((coalesce((select max(t1.c) from t1 where t1.f-a-case coalesce((select max(d) from t1 where (13<>~19)),f) when a- -t1.a & t1.f then t1.a*11-t1.e else coalesce((select max(t1.b) from t1 where not exists(select 1 from t1 where 17=t1.a or b>=f)),c) & t1.b end>19),t1.a))+c)-t1.c*e)/abs(t1.d)) FROM t1 WHERE a-t1.b not in (a,a-19-c | t1.d-d | e*t1.c*b,t1.e+t1.a)} +} {375} +do_test randexpr-2.428 { + db eval {SELECT t1.b-coalesce((select t1.a from t1 where (d<=f)),~~case b when coalesce((select coalesce((select t1.c from t1 where a+~+~(abs(t1.d)/abs(17)) | -d*a*(b++ -13)*b>=b),17) | a from t1 where a=coalesce((select t1.d+(select case min(a) | max(t1.b) when max(e) then count(*) else -count(distinct f) end from t1)-t1.f+( - - -19) from t1 where t1.c in (select 19 from t1 union select 17 from t1)),11))),19)+11 not in ((b),e,e) or t1.e in (select min(t1.f) from t1 union select count(*)- -(cast(avg(17) AS integer)) from t1) or e>=t1.c} +} {100} +do_test randexpr-2.429 { + db eval {SELECT t1.b-coalesce((select t1.a from t1 where (d<=f)),~~case b when coalesce((select coalesce((select t1.c from t1 where a+~+~(abs(t1.d)/abs(17)) | -d*a*(b++ -13)*b>=b),17) | a from t1 where a=coalesce((select t1.d+(select case min(a) | max(t1.b) when max(e) then count(*) else -count(distinct f) end from t1)-t1.f+( - - -19) from t1 where t1.c in (select 19 from t1 union select 17 from t1)),11))),19)+11 not in ((b),e,e) or t1.e in (select min(t1.f) from t1 union select count(*)- -(cast(avg(17) AS integer)) from t1) or e>=t1.c)} +} {} +do_test randexpr-2.430 { + db eval {SELECT t1.b-coalesce((select t1.a from t1 where (d<=f)),~~case b when coalesce((select coalesce((select t1.c from t1 where a+~+~(abs(t1.d)/abs(17)) & -d*a*(b++ -13)*b>=b),17) & a from t1 where a=coalesce((select t1.d+(select case min(a) | max(t1.b) when max(e) then count(*) else -count(distinct f) end from t1)-t1.f+( - - -19) from t1 where t1.c in (select 19 from t1 union select 17 from t1)),11))),19)+11 not in ((b),e,e) or t1.e in (select min(t1.f) from t1 union select count(*)- -(cast(avg(17) AS integer)) from t1) or e>=t1.c} +} {100} +do_test randexpr-2.431 { + db eval {SELECT coalesce((select max(case when e<=t1.d then f*+case 17 when 17 then (abs((select abs(cast(avg(13) AS integer)+min(t1.b)) from t1))/abs(t1.c)) else d end*t1.c else a end) from t1 where coalesce((select t1.c from t1 where a<>t1.e+f-t1.c-a),+t1.a)+t1.d*case when d in (select t1.c from t1 union select 11 from t1) then a when 19 not in (d,e,b) then 11 else 19 end | t1.b in (select 19 from t1 union select t1.a from t1)),17)*11 FROM t1 WHERE 17>=t1.b} +} {} +do_test randexpr-2.432 { + db eval {SELECT coalesce((select max(case when e<=t1.d then f*+case 17 when 17 then (abs((select abs(cast(avg(13) AS integer)+min(t1.b)) from t1))/abs(t1.c)) else d end*t1.c else a end) from t1 where coalesce((select t1.c from t1 where a<>t1.e+f-t1.c-a),+t1.a)+t1.d*case when d in (select t1.c from t1 union select 11 from t1) then a when 19 not in (d,e,b) then 11 else 19 end | t1.b in (select 19 from t1 union select t1.a from t1)),17)*11 FROM t1 WHERE NOT (17>=t1.b)} +} {187} +do_test randexpr-2.433 { + db eval {SELECT coalesce((select max(case when e<=t1.d then f*+case 17 when 17 then (abs((select abs(cast(avg(13) AS integer)+min(t1.b)) from t1))/abs(t1.c)) else d end*t1.c else a end) from t1 where coalesce((select t1.c from t1 where a<>t1.e+f-t1.c-a),+t1.a)+t1.d*case when d in (select t1.c from t1 union select 11 from t1) then a when 19 not in (d,e,b) then 11 else 19 end & t1.b in (select 19 from t1 union select t1.a from t1)),17)*11 FROM t1 WHERE NOT (17>=t1.b)} +} {187} +do_test randexpr-2.434 { + db eval {SELECT case when coalesce((select max(case f when (abs(t1.d)/abs(case when +~e not in (t1.d,c,t1.a) or 17 in (select count(distinct -b) from t1 union select count(distinct d) from t1) and d<=t1.b or b>(f) then coalesce((select c from t1 where t1.ff or t1.b<> -t1.c), -t1.d)<11 then c else f end FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where case -case when case t1.c-t1.b-e when t1.b then t1.e else -t1.c+~17 | coalesce((select max(t1.c) from t1 where 19 not between -(a)-t1.c and 17),t1.c) end in (select (t1.f) from t1 union select b from t1) then e when c<>19 then t1.b else f end when -11 then 11 else 19 end in ( -19,t1.a,d)) and not 17(f) then coalesce((select c from t1 where t1.ff or t1.b<> -t1.c), -t1.d)<11 then c else f end FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where case -case when case t1.c-t1.b-e when t1.b then t1.e else -t1.c+~17 | coalesce((select max(t1.c) from t1 where 19 not between -(a)-t1.c and 17),t1.c) end in (select (t1.f) from t1 union select b from t1) then e when c<>19 then t1.b else f end when -11 then 11 else 19 end in ( -19,t1.a,d)) and not 17a) then t1.f else t1.c end FROM t1 WHERE case when (((case coalesce((select -t1.b-t1.b*19*c | 19 from t1 where (exists(select 1 from t1 where e>=t1.a))),t1.a)+11 when d then t1.e else t1.c end=t1.d))) then t1.b when not not exists(select 1 from t1 where t1.f<(t1.a)) and t1.d>=f or t1.c>t1.a or t1.b between t1.f and 19 then t1.c else ~t1.c end=11 or (t1.e) not between 13 and t1.c} +} {600} +do_test randexpr-2.440 { + db eval {SELECT case when (ba) then t1.f else t1.c end FROM t1 WHERE NOT (case when (((case coalesce((select -t1.b-t1.b*19*c | 19 from t1 where (exists(select 1 from t1 where e>=t1.a))),t1.a)+11 when d then t1.e else t1.c end=t1.d))) then t1.b when not not exists(select 1 from t1 where t1.f<(t1.a)) and t1.d>=f or t1.c>t1.a or t1.b between t1.f and 19 then t1.c else ~t1.c end=11 or (t1.e) not between 13 and t1.c)} +} {} +do_test randexpr-2.441 { + db eval {SELECT case when (ba) then t1.f else t1.c end FROM t1 WHERE case when (((case coalesce((select -t1.b-t1.b*19*c | 19 from t1 where (exists(select 1 from t1 where e>=t1.a))),t1.a)+11 when d then t1.e else t1.c end=t1.d))) then t1.b when not not exists(select 1 from t1 where t1.f<(t1.a)) and t1.d>=f or t1.c>t1.a or t1.b between t1.f and 19 then t1.c else ~t1.c end=11 or (t1.e) not between 13 and t1.c} +} {300} +do_test randexpr-2.442 { + db eval {SELECT case when not t1.d not in (coalesce((select 17 | -coalesce((select (select min(a-t1.a+t1.a-t1.c*t1.e) from t1) from t1 where t1.d<=a),11) | 19 from t1 where not ( -13 in ( -t1.d,t1.d,19))),e)+11,11,13) then e when ((t1.bt1.f and a>=17))} +} {} +do_test randexpr-2.443 { + db eval {SELECT case when not t1.d not in (coalesce((select 17 | -coalesce((select (select min(a-t1.a+t1.a-t1.c*t1.e) from t1) from t1 where t1.d<=a),11) | 19 from t1 where not ( -13 in ( -t1.d,t1.d,19))),e)+11,11,13) then e when ((t1.bt1.f and a>=17)))} +} {100} +do_test randexpr-2.444 { + db eval {SELECT case when not t1.d not in (coalesce((select 17 & -coalesce((select (select min(a-t1.a+t1.a-t1.c*t1.e) from t1) from t1 where t1.d<=a),11) & 19 from t1 where not ( -13 in ( -t1.d,t1.d,19))),e)+11,11,13) then e when ((t1.bt1.f and a>=17)))} +} {100} +do_test randexpr-2.445 { + db eval {SELECT e+c-(c)+t1.e*(abs(case when 13 in (select abs(max(17)*case -count(*) when cast(avg(a) AS integer) then count(distinct b) else -max(f) end | (cast(avg(t1.e) AS integer)) | -min(f)) from t1 union select count(distinct d) from t1) and case when (t1.e+a> -(a)) then e when not c=e)),coalesce((select max(case t1.e when t1.c then t1.a else a end) from t1 where b>=t1.c and b<>t1.c),13)) then t1.b else a end<11 then b when (11 in (select a from t1 union select t1.b from t1)) or t1.b=e or a between a and 13 then t1.b else b end>19} +} {1500} +do_test randexpr-2.446 { + db eval {SELECT e+c-(c)+t1.e*(abs(case when 13 in (select abs(max(17)*case -count(*) when cast(avg(a) AS integer) then count(distinct b) else -max(f) end | (cast(avg(t1.e) AS integer)) | -min(f)) from t1 union select count(distinct d) from t1) and case when (t1.e+a> -(a)) then e when not c=e)),coalesce((select max(case t1.e when t1.c then t1.a else a end) from t1 where b>=t1.c and b<>t1.c),13)) then t1.b else a end<11 then b when (11 in (select a from t1 union select t1.b from t1)) or t1.b=e or a between a and 13 then t1.b else b end>19)} +} {} +do_test randexpr-2.447 { + db eval {SELECT e+c-(c)+t1.e*(abs(case when 13 in (select abs(max(17)*case -count(*) when cast(avg(a) AS integer) then count(distinct b) else -max(f) end & (cast(avg(t1.e) AS integer)) & -min(f)) from t1 union select count(distinct d) from t1) and case when (t1.e+a> -(a)) then e when not c=e)),coalesce((select max(case t1.e when t1.c then t1.a else a end) from t1 where b>=t1.c and b<>t1.c),13)) then t1.b else a end<11 then b when (11 in (select a from t1 union select t1.b from t1)) or t1.b=e or a between a and 13 then t1.b else b end>19} +} {1500} +do_test randexpr-2.448 { + db eval {SELECT 13-coalesce((select t1.a*a from t1 where not exists(select 1 from t1 where 17 not between case +coalesce((select -case 19 when a*b then 19 else f end from t1 where (t1.d-t1.e between case f when (select abs(case abs( -min(13)) when min(t1.b) then -(count(distinct f)) else min(t1.b) end) from t1) then 17*( -13) | f else t1.e end and -t1.a)),d)*c when 13 then 11 else t1.a end and c)),t1.a)*19 FROM t1 WHERE ((not f-c<=(abs(a)/abs(+t1.a)) or t1.e not between coalesce((select 11 from t1 where - -a*t1.d*case coalesce((select max(d) from t1 where ((t1.b<=t1.c))),case when f>t1.d or t1.d=t1.a or t1.c<=c then a else -c end*t1.b) when (f) then 11 else 19 end-t1.a<=b),c) and 13))} +} {-1887} +do_test randexpr-2.449 { + db eval {SELECT 13-coalesce((select t1.a*a from t1 where not exists(select 1 from t1 where 17 not between case +coalesce((select -case 19 when a*b then 19 else f end from t1 where (t1.d-t1.e between case f when (select abs(case abs( -min(13)) when min(t1.b) then -(count(distinct f)) else min(t1.b) end) from t1) then 17*( -13) | f else t1.e end and -t1.a)),d)*c when 13 then 11 else t1.a end and c)),t1.a)*19 FROM t1 WHERE NOT (((not f-c<=(abs(a)/abs(+t1.a)) or t1.e not between coalesce((select 11 from t1 where - -a*t1.d*case coalesce((select max(d) from t1 where ((t1.b<=t1.c))),case when f>t1.d or t1.d=t1.a or t1.c<=c then a else -c end*t1.b) when (f) then 11 else 19 end-t1.a<=b),c) and 13)))} +} {} +do_test randexpr-2.450 { + db eval {SELECT 13-coalesce((select t1.a*a from t1 where not exists(select 1 from t1 where 17 not between case +coalesce((select -case 19 when a*b then 19 else f end from t1 where (t1.d-t1.e between case f when (select abs(case abs( -min(13)) when min(t1.b) then -(count(distinct f)) else min(t1.b) end) from t1) then 17*( -13) & f else t1.e end and -t1.a)),d)*c when 13 then 11 else t1.a end and c)),t1.a)*19 FROM t1 WHERE ((not f-c<=(abs(a)/abs(+t1.a)) or t1.e not between coalesce((select 11 from t1 where - -a*t1.d*case coalesce((select max(d) from t1 where ((t1.b<=t1.c))),case when f>t1.d or t1.d=t1.a or t1.c<=c then a else -c end*t1.b) when (f) then 11 else 19 end-t1.a<=b),c) and 13))} +} {-1887} +do_test randexpr-2.451 { + db eval {SELECT ~case when (t1.d | 17 in (b*t1.e,19*case when t1.d<= -a then t1.d*~t1.c*e*t1.c-19 else ~t1.b+17 end-d,(t1.c))) then +t1.d else (abs( -case t1.e when t1.c then (t1.b) else t1.f end-11+ -a)/abs(f))+a end FROM t1 WHERE not exists(select 1 from t1 where not c in (select case count(distinct (f)-19) when ~( -+~cast(avg(c) AS integer) | count(distinct 11)-max(d)+min(t1.a)+ -( -count(distinct b))+(count(*)))-count(*)+cast(avg(c) AS integer) then count(distinct d) else ((max(t1.b))) end-min(b) from t1 union select min(t1.c) from t1)) and t1.c in (select +d from t1 union select case when c+b=17 then a else 13 end+11 from t1)} +} {} +do_test randexpr-2.452 { + db eval {SELECT ~case when (t1.d | 17 in (b*t1.e,19*case when t1.d<= -a then t1.d*~t1.c*e*t1.c-19 else ~t1.b+17 end-d,(t1.c))) then +t1.d else (abs( -case t1.e when t1.c then (t1.b) else t1.f end-11+ -a)/abs(f))+a end FROM t1 WHERE NOT (not exists(select 1 from t1 where not c in (select case count(distinct (f)-19) when ~( -+~cast(avg(c) AS integer) | count(distinct 11)-max(d)+min(t1.a)+ -( -count(distinct b))+(count(*)))-count(*)+cast(avg(c) AS integer) then count(distinct d) else ((max(t1.b))) end-min(b) from t1 union select min(t1.c) from t1)) and t1.c in (select +d from t1 union select case when c+b=17 then a else 13 end+11 from t1))} +} {-102} +do_test randexpr-2.453 { + db eval {SELECT ~case when (t1.d & 17 in (b*t1.e,19*case when t1.d<= -a then t1.d*~t1.c*e*t1.c-19 else ~t1.b+17 end-d,(t1.c))) then +t1.d else (abs( -case t1.e when t1.c then (t1.b) else t1.f end-11+ -a)/abs(f))+a end FROM t1 WHERE NOT (not exists(select 1 from t1 where not c in (select case count(distinct (f)-19) when ~( -+~cast(avg(c) AS integer) | count(distinct 11)-max(d)+min(t1.a)+ -( -count(distinct b))+(count(*)))-count(*)+cast(avg(c) AS integer) then count(distinct d) else ((max(t1.b))) end-min(b) from t1 union select min(t1.c) from t1)) and t1.c in (select +d from t1 union select case when c+b=17 then a else 13 end+11 from t1))} +} {-102} +do_test randexpr-2.454 { + db eval {SELECT (select case case min(d) when abs(cast(avg((abs(a)/abs(coalesce((select (select abs(cast(avg(t1.f) AS integer)) from t1) from t1 where (case when t1.e in (select 11 from t1 union select 17 from t1) then -t1.e- -t1.e else a end<>a) and not not exists(select 1 from t1 where t1.b in (select ~+max( -t1.b) | max(t1.c) from t1 union select count(distinct -t1.a) from t1))),t1.a)))) AS integer)) then (count(*) | ((count(distinct b)))-count(*)) else min(11) end when max(a) then count(distinct f) else (min(17)) end from t1) FROM t1 WHERE coalesce((select max(13) from t1 where t1.b not in ( -case when 13 not between 17 and b then f when t1.e+~+e between coalesce((select max(case 19 when e then 17 else coalesce((select coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.b not between t1.a and a)),e)*b*t1.f from t1 where t1.f>=t1.c),c) end) from t1 where e>b),t1.f) | f and f then c else 11 end,(c),t1.e)),19)-t1.c in (select t1.a from t1 union select e from t1)} +} {} +do_test randexpr-2.455 { + db eval {SELECT (select case case min(d) when abs(cast(avg((abs(a)/abs(coalesce((select (select abs(cast(avg(t1.f) AS integer)) from t1) from t1 where (case when t1.e in (select 11 from t1 union select 17 from t1) then -t1.e- -t1.e else a end<>a) and not not exists(select 1 from t1 where t1.b in (select ~+max( -t1.b) | max(t1.c) from t1 union select count(distinct -t1.a) from t1))),t1.a)))) AS integer)) then (count(*) | ((count(distinct b)))-count(*)) else min(11) end when max(a) then count(distinct f) else (min(17)) end from t1) FROM t1 WHERE NOT (coalesce((select max(13) from t1 where t1.b not in ( -case when 13 not between 17 and b then f when t1.e+~+e between coalesce((select max(case 19 when e then 17 else coalesce((select coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.b not between t1.a and a)),e)*b*t1.f from t1 where t1.f>=t1.c),c) end) from t1 where e>b),t1.f) | f and f then c else 11 end,(c),t1.e)),19)-t1.c in (select t1.a from t1 union select e from t1))} +} {17} +do_test randexpr-2.456 { + db eval {SELECT (select case case min(d) when abs(cast(avg((abs(a)/abs(coalesce((select (select abs(cast(avg(t1.f) AS integer)) from t1) from t1 where (case when t1.e in (select 11 from t1 union select 17 from t1) then -t1.e- -t1.e else a end<>a) and not not exists(select 1 from t1 where t1.b in (select ~+max( -t1.b) & max(t1.c) from t1 union select count(distinct -t1.a) from t1))),t1.a)))) AS integer)) then (count(*) & ((count(distinct b)))-count(*)) else min(11) end when max(a) then count(distinct f) else (min(17)) end from t1) FROM t1 WHERE NOT (coalesce((select max(13) from t1 where t1.b not in ( -case when 13 not between 17 and b then f when t1.e+~+e between coalesce((select max(case 19 when e then 17 else coalesce((select coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.b not between t1.a and a)),e)*b*t1.f from t1 where t1.f>=t1.c),c) end) from t1 where e>b),t1.f) | f and f then c else 11 end,(c),t1.e)),19)-t1.c in (select t1.a from t1 union select e from t1))} +} {17} +do_test randexpr-2.457 { + db eval {SELECT (a*f+c | ~b*(select cast(avg(19) AS integer) from t1)+17*(select max(a*b-d) from t1)+(abs((select count(distinct b) from t1))/abs(case when -13*c between t1.f and t1.c then c when not 17 between 17 and 11 and 17<=((t1.c)) then c else a end*t1.c))-a*a)-c FROM t1 WHERE exists(select 1 from t1 where t1.e-11+t1.d*e+(abs(coalesce((select max(t1.b) from t1 where 19-13- -coalesce((select c*t1.e+t1.f*f from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (17<=d or -11 in (select cast(avg(c) AS integer) from t1 union select +count(*) from t1))))),t1.b)=t1.c or t1.b>t1.c or 19 not between c and t1.e then 17 else t1.b end) from t1 where (e<=t1.b)),11) FROM t1 WHERE t1.a in (f,t1.d*+a,t1.c* -(select (abs(case +(max(coalesce((select max((select count(*)-cast(avg(b) AS integer) from t1)) from t1 where (c=t1.c or t1.b>t1.c or 19 not between c and t1.e then 17 else t1.b end) from t1 where (e<=t1.b)),11) FROM t1 WHERE NOT (t1.a in (f,t1.d*+a,t1.c* -(select (abs(case +(max(coalesce((select max((select count(*)-cast(avg(b) AS integer) from t1)) from t1 where (ce then case t1.d when 13 then t1.c else 19 end-13 else t1.e+coalesce((select max(19) from t1 where case when e in (+b,coalesce((select a+(11) from t1 where b not between c and d or t1.b not in (a,11,17)),b),11) then 19 when (c) not in (t1.c,t1.b,d) then t1.c else t1.d end*f not between t1.a and d),13) end when c then 11 else c end) FROM t1 WHERE 19 not between coalesce((select max(d*t1.c) from t1 where (select cast(avg((b)) AS integer) from t1) in (select ( - -(abs(case max(b) when cast(avg( -13-11) AS integer) then count(distinct a-e) else ~ -cast(avg((c)) AS integer)-min(17)+count(*) end) | (min(e)))-min((19))) from t1 union select count(distinct 13) from t1)),case when -e | 19 between -11 and f then 19 else 19 end) and (f)} +} {} +do_test randexpr-2.463 { + db eval {SELECT (case case when +c>e then case t1.d when 13 then t1.c else 19 end-13 else t1.e+coalesce((select max(19) from t1 where case when e in (+b,coalesce((select a+(11) from t1 where b not between c and d or t1.b not in (a,11,17)),b),11) then 19 when (c) not in (t1.c,t1.b,d) then t1.c else t1.d end*f not between t1.a and d),13) end when c then 11 else c end) FROM t1 WHERE NOT (19 not between coalesce((select max(d*t1.c) from t1 where (select cast(avg((b)) AS integer) from t1) in (select ( - -(abs(case max(b) when cast(avg( -13-11) AS integer) then count(distinct a-e) else ~ -cast(avg((c)) AS integer)-min(17)+count(*) end) | (min(e)))-min((19))) from t1 union select count(distinct 13) from t1)),case when -e | 19 between -11 and f then 19 else 19 end) and (f))} +} {300} +do_test randexpr-2.464 { + db eval {SELECT (abs((select abs(case -max(e)+max(t1.f)+(count(*)* -count(distinct case e when 19 then c else 13 end))*~min(t1.a) when cast(avg(t1.a) AS integer) then -min(e) else -count(*) end) from t1)*coalesce((select (t1.a) from t1 where case when c+t1.b-b | d in (select max(d) from t1 union select -max(19) from t1) then t1.b else f end=t1.d),t1.b)*(t1.d) | e+t1.a)/abs(t1.d)) FROM t1 WHERE t1.f in (19,d*t1.d,(select min((select count(*)*min((17)+(abs(11)/abs(+~coalesce((select max(f) from t1 where 13 not between t1.c and t1.a),t1.e)-11))) from t1)) from t1)+17)} +} {} +do_test randexpr-2.465 { + db eval {SELECT (abs((select abs(case -max(e)+max(t1.f)+(count(*)* -count(distinct case e when 19 then c else 13 end))*~min(t1.a) when cast(avg(t1.a) AS integer) then -min(e) else -count(*) end) from t1)*coalesce((select (t1.a) from t1 where case when c+t1.b-b | d in (select max(d) from t1 union select -max(19) from t1) then t1.b else f end=t1.d),t1.b)*(t1.d) | e+t1.a)/abs(t1.d)) FROM t1 WHERE NOT (t1.f in (19,d*t1.d,(select min((select count(*)*min((17)+(abs(11)/abs(+~coalesce((select max(f) from t1 where 13 not between t1.c and t1.a),t1.e)-11))) from t1)) from t1)+17))} +} {201} +do_test randexpr-2.466 { + db eval {SELECT (abs((select abs(case -max(e)+max(t1.f)+(count(*)* -count(distinct case e when 19 then c else 13 end))*~min(t1.a) when cast(avg(t1.a) AS integer) then -min(e) else -count(*) end) from t1)*coalesce((select (t1.a) from t1 where case when c+t1.b-b & d in (select max(d) from t1 union select -max(19) from t1) then t1.b else f end=t1.d),t1.b)*(t1.d) & e+t1.a)/abs(t1.d)) FROM t1 WHERE NOT (t1.f in (19,d*t1.d,(select min((select count(*)*min((17)+(abs(11)/abs(+~coalesce((select max(f) from t1 where 13 not between t1.c and t1.a),t1.e)-11))) from t1)) from t1)+17))} +} {0} +do_test randexpr-2.467 { + db eval {SELECT d+case when (coalesce((select max(t1.a) from t1 where t1.a not in (t1.d,f*(select count(distinct t1.d) from t1)+t1.f,c)),b)-c-17-t1.c)-case when 13*t1.a-19*e<>11 then f when t1.f not between 11 and t1.d then b else f end=t1.d then t1.f when not e>t1.f then 17 else b end FROM t1 WHERE exists(select 1 from t1 where 11* -d>=e) or t1.c<+ -e*11 or (17 not between t1.d and case t1.a when t1.a then t1.d+f-b else 11 end | t1.e)} +} {417} +do_test randexpr-2.468 { + db eval {SELECT d+case when (coalesce((select max(t1.a) from t1 where t1.a not in (t1.d,f*(select count(distinct t1.d) from t1)+t1.f,c)),b)-c-17-t1.c)-case when 13*t1.a-19*e<>11 then f when t1.f not between 11 and t1.d then b else f end=t1.d then t1.f when not e>t1.f then 17 else b end FROM t1 WHERE NOT (exists(select 1 from t1 where 11* -d>=e) or t1.c<+ -e*11 or (17 not between t1.d and case t1.a when t1.a then t1.d+f-b else 11 end | t1.e))} +} {} +do_test randexpr-2.469 { + db eval {SELECT t1.f-coalesce((select max(+e | b) from t1 where case when -(abs(11)/abs(~(19 | t1.d)))-~c*e not in (19,b*t1.b,b) then 11 when f<=13 then d else t1.d end in (select (count(*))-cast(avg(11 | 17*t1.b) AS integer) from t1 union select count(distinct a-17) from t1)),t1.c)-c FROM t1 WHERE case when (t1.f*a<=11+d+coalesce((select max(19+19) from t1 where 13 in (select min(f)+cast(avg((abs(t1.e)/abs((select count(distinct c) from t1)))) AS integer)+(~cast(avg(e) AS integer))-min(c) from t1 union select count(*) from t1)),b)) then (a) else t1.b end-t1.b<=t1.b and 13 in (select t1.e from t1 union select t1.e from t1) and a=t1.d or (exists(select 1 from t1 where (t1.e=t1.c)))),t1.c)-11 FROM t1 WHERE (not exists(select 1 from t1 where 11+t1.c-13>=t1.c or not exists(select 1 from t1 where a in (select b from t1 union select 19-d from t1) and ((abs(a+(abs(coalesce((select t1.d from t1 where exists(select 1 from t1 where case when t1.e>= -13 or -e<>f then d when t1.c=13 then (b) else t1.c end not between 13 and b)),d))/abs(t1.d))-b)/abs(t1.a))<> -13 and exists(select 1 from t1 where 19<>e) or 13>=19))))} +} {} +do_test randexpr-2.473 { + db eval {SELECT coalesce((select max(t1.c) from t1 where case when (t1.e*19*f-t1.b in (select cast(avg(d-~d) AS integer) from t1 union select +( -case +~count(*)*count(distinct (c)) when cast(avg(19) AS integer) then min(c) else count(distinct 17) end*cast(avg((13)) AS integer)-max(11)+(count(distinct b))) from t1)) then +11 else t1.b end>=t1.d or (exists(select 1 from t1 where (t1.e=t1.c)))),t1.c)-11 FROM t1 WHERE NOT ((not exists(select 1 from t1 where 11+t1.c-13>=t1.c or not exists(select 1 from t1 where a in (select b from t1 union select 19-d from t1) and ((abs(a+(abs(coalesce((select t1.d from t1 where exists(select 1 from t1 where case when t1.e>= -13 or -e<>f then d when t1.c=13 then (b) else t1.c end not between 13 and b)),d))/abs(t1.d))-b)/abs(t1.a))<> -13 and exists(select 1 from t1 where 19<>e) or 13>=19)))))} +} {289} +do_test randexpr-2.474 { + db eval {SELECT +coalesce((select max(11) from t1 where not case d+t1.c*coalesce((select max(coalesce((select d | e from t1 where 17 not between coalesce((select (t1.d) from t1 where t1.a between (select max(t1.b+d+t1.a) from t1)-t1.e and 17),t1.a) and 11),19)) from t1 where t1.dt1.d*a) then (abs(~a)/abs(+11))*f when (c-(coalesce((select 11 from t1 where t1.d in (case when (19)+11>=c then 19 when e<>b then 13 else c end,a,13)),17))+13) not between 11 and t1.c then (t1.b) else 17 end+b FROM t1 WHERE a*b*11 in (select case when not coalesce((select max(~13 | (select abs((count(distinct t1.f))*cast(avg(t1.f) AS integer)+(max(t1.e))) from t1)) from t1 where coalesce((select max(11) from t1 where t1.b=19),b) in (f,11,19) and t1.f between a and t1.c or 19=t1.a and d=17 or c>=t1.f or t1.d<>t1.c),11)*c in (select f from t1 union select -t1.b from t1) then t1.c when c not between f and 13 then e else -e end from t1 union select e from t1)} +} {} +do_test randexpr-2.478 { + db eval {SELECT case when ((select -min(e)+cast(avg(t1.a) AS integer) from t1)>t1.d*a) then (abs(~a)/abs(+11))*f when (c-(coalesce((select 11 from t1 where t1.d in (case when (19)+11>=c then 19 when e<>b then 13 else c end,a,13)),17))+13) not between 11 and t1.c then (t1.b) else 17 end+b FROM t1 WHERE NOT (a*b*11 in (select case when not coalesce((select max(~13 | (select abs((count(distinct t1.f))*cast(avg(t1.f) AS integer)+(max(t1.e))) from t1)) from t1 where coalesce((select max(11) from t1 where t1.b=19),b) in (f,11,19) and t1.f between a and t1.c or 19=t1.a and d=17 or c>=t1.f or t1.d<>t1.c),11)*c in (select f from t1 union select -t1.b from t1) then t1.c when c not between f and 13 then e else -e end from t1 union select e from t1))} +} {217} +do_test randexpr-2.479 { + db eval {SELECT t1.d-coalesce((select -t1.c from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.d<=case t1.d+e when case when d>19 then 11+t1.c else t1.b end-t1.f-t1.e then (abs(t1.d-19*t1.b)/abs(13+case when t1.f in (select count(*)-count(distinct t1.b) from t1 union select (max((t1.f))) from t1) then (((t1.d))) when t1.b not in (t1.d,13,a) then t1.d else 19 end*t1.c))-t1.d else e end))),13)+c*t1.a FROM t1 WHERE exists(select 1 from t1 where ~coalesce((select a+t1.a from t1 where ~(abs(c)/abs(17 | +13))-t1.f in (select f from t1 union select case when t1.b between 11*e and f then e when a in (e* -t1.f-f,coalesce((select 17 from t1 where t1.e in (select (cast(avg(e) AS integer)) from t1 union select max(b) from t1)),a),d) then t1.c else (f) end from t1)),f) between -19 and (13) or t1.f<>t1.a)} +} {30700} +do_test randexpr-2.480 { + db eval {SELECT t1.d-coalesce((select -t1.c from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.d<=case t1.d+e when case when d>19 then 11+t1.c else t1.b end-t1.f-t1.e then (abs(t1.d-19*t1.b)/abs(13+case when t1.f in (select count(*)-count(distinct t1.b) from t1 union select (max((t1.f))) from t1) then (((t1.d))) when t1.b not in (t1.d,13,a) then t1.d else 19 end*t1.c))-t1.d else e end))),13)+c*t1.a FROM t1 WHERE NOT (exists(select 1 from t1 where ~coalesce((select a+t1.a from t1 where ~(abs(c)/abs(17 | +13))-t1.f in (select f from t1 union select case when t1.b between 11*e and f then e when a in (e* -t1.f-f,coalesce((select 17 from t1 where t1.e in (select (cast(avg(e) AS integer)) from t1 union select max(b) from t1)),a),d) then t1.c else (f) end from t1)),f) between -19 and (13) or t1.f<>t1.a))} +} {} +do_test randexpr-2.481 { + db eval {SELECT (abs((abs(t1.b*t1.b*t1.f+a)/abs(t1.f))*t1.a-case -(abs(coalesce((select (case when 11*19 in (select count(*) from t1 union select -min(13)-(max(t1.a)) from t1) then 19 else -17 end) from t1 where t1.e between 13 and (a)),t1.b)+d)/abs(t1.f))-t1.b-t1.c | d when -t1.f then c else 17 end)/abs(13))-b*t1.d FROM t1 WHERE 13 in (t1.b,17*e+c*a,coalesce((select max(d) from t1 where +f+b not in (a,t1.a*~t1.c | t1.b-case when t1.a<=case when t1.f in (b,11,e) then d else t1.e end+f then 19 else (f) end-b*13- -t1.f-17,t1.c)),17))} +} {} +do_test randexpr-2.482 { + db eval {SELECT (abs((abs(t1.b*t1.b*t1.f+a)/abs(t1.f))*t1.a-case -(abs(coalesce((select (case when 11*19 in (select count(*) from t1 union select -min(13)-(max(t1.a)) from t1) then 19 else -17 end) from t1 where t1.e between 13 and (a)),t1.b)+d)/abs(t1.f))-t1.b-t1.c | d when -t1.f then c else 17 end)/abs(13))-b*t1.d FROM t1 WHERE NOT (13 in (t1.b,17*e+c*a,coalesce((select max(d) from t1 where +f+b not in (a,t1.a*~t1.c | t1.b-case when t1.a<=case when t1.f in (b,11,e) then d else t1.e end+f then 19 else (f) end-b*13- -t1.f-17,t1.c)),17)))} +} {227691} +do_test randexpr-2.483 { + db eval {SELECT (abs((abs(t1.b*t1.b*t1.f+a)/abs(t1.f))*t1.a-case -(abs(coalesce((select (case when 11*19 in (select count(*) from t1 union select -min(13)-(max(t1.a)) from t1) then 19 else -17 end) from t1 where t1.e between 13 and (a)),t1.b)+d)/abs(t1.f))-t1.b-t1.c & d when -t1.f then c else 17 end)/abs(13))-b*t1.d FROM t1 WHERE NOT (13 in (t1.b,17*e+c*a,coalesce((select max(d) from t1 where +f+b not in (a,t1.a*~t1.c | t1.b-case when t1.a<=case when t1.f in (b,11,e) then d else t1.e end+f then 19 else (f) end-b*13- -t1.f-17,t1.c)),17)))} +} {227691} +do_test randexpr-2.484 { + db eval {SELECT coalesce((select t1.c*f from t1 where t1.f-+coalesce((select max(t1.d) from t1 where - -t1.e in (select f from t1 union select t1.e from t1)),a)+case when 19 not in (t1.e,case when ~t1.a<>e+a then -t1.d else t1.e end,f) then t1.b when -(t1.e) in (e,(19),t1.c) then t1.f else e end+17*t1.c+d>b),t1.c)+a FROM t1 WHERE t1.b>=~b} +} {180100} +do_test randexpr-2.485 { + db eval {SELECT coalesce((select t1.c*f from t1 where t1.f-+coalesce((select max(t1.d) from t1 where - -t1.e in (select f from t1 union select t1.e from t1)),a)+case when 19 not in (t1.e,case when ~t1.a<>e+a then -t1.d else t1.e end,f) then t1.b when -(t1.e) in (e,(19),t1.c) then t1.f else e end+17*t1.c+d>b),t1.c)+a FROM t1 WHERE NOT (t1.b>=~b)} +} {} +do_test randexpr-2.486 { + db eval {SELECT case case when case when 13 between coalesce((select max(t1.f) from t1 where b+f in (b+(coalesce((select t1.f from t1 where (t1.c)>=17 or 19 not in (11,t1.e,c)),13)),b,t1.e) and c<=e and not t1.b<>13 and 19 not between t1.c and a or c between f and f),t1.c) and b then t1.b when 13<>t1.a then 11 else d end in (select 13 from t1 union select 19 from t1) then t1.c when t1.f not in (17,b,b) then t1.f else e end when t1.e then t1.e else -d end FROM t1 WHERE case when not exists(select 1 from t1 where t1.f not between coalesce((select coalesce((select max(+case t1.a when f then t1.a else t1.e end+case when t1.f>t1.d or 11 in (t1.e,11,b) then b else a end) from t1 where t1.f in (select a from t1 union select d from t1)),t1.d) from t1 where t1.a=b),(t1.c)) and d) then (select case max(t1.a) when ~min((11)) | min(e) then max(t1.e) else abs(max(t1.c)*count(distinct 19)) end from t1) else t1.b end<>b} +} {} +do_test randexpr-2.487 { + db eval {SELECT case case when case when 13 between coalesce((select max(t1.f) from t1 where b+f in (b+(coalesce((select t1.f from t1 where (t1.c)>=17 or 19 not in (11,t1.e,c)),13)),b,t1.e) and c<=e and not t1.b<>13 and 19 not between t1.c and a or c between f and f),t1.c) and b then t1.b when 13<>t1.a then 11 else d end in (select 13 from t1 union select 19 from t1) then t1.c when t1.f not in (17,b,b) then t1.f else e end when t1.e then t1.e else -d end FROM t1 WHERE NOT (case when not exists(select 1 from t1 where t1.f not between coalesce((select coalesce((select max(+case t1.a when f then t1.a else t1.e end+case when t1.f>t1.d or 11 in (t1.e,11,b) then b else a end) from t1 where t1.f in (select a from t1 union select d from t1)),t1.d) from t1 where t1.a=b),(t1.c)) and d) then (select case max(t1.a) when ~min((11)) | min(e) then max(t1.e) else abs(max(t1.c)*count(distinct 19)) end from t1) else t1.b end<>b)} +} {-400} +do_test randexpr-2.488 { + db eval {SELECT case -coalesce((select max(case when case when t1.e in (11*t1.e*17,(select (min(b) | - -+cast(avg(17) AS integer)*max((t1.c))+cast(avg(t1.a) AS integer))+(( -(min(t1.c))))*count(*) from t1), -~b*t1.d+t1.d) then d else t1.a end<(t1.c) then t1.f else e end) from t1 where 13<>c),e)-(t1.b) when t1.a then 17 else t1.f end FROM t1 WHERE coalesce((select max(t1.e) from t1 where (not exists(select 1 from t1 where b<+c))),case when b | ~case t1.a when -t1.b then -t1.f else t1.f end*f+f in (select t1.b from t1 union select t1.c from t1) then -(t1.f) when a<>11 then (d) else 11 end) in (select abs(~(abs(case (min(t1.b)*abs(count(distinct a)+count(*) | -count(distinct a)))- -max(19) when max(t1.e) then min(d) else (max(a)) end))) from t1 union select count(*) from t1)} +} {} +do_test randexpr-2.489 { + db eval {SELECT case -coalesce((select max(case when case when t1.e in (11*t1.e*17,(select (min(b) | - -+cast(avg(17) AS integer)*max((t1.c))+cast(avg(t1.a) AS integer))+(( -(min(t1.c))))*count(*) from t1), -~b*t1.d+t1.d) then d else t1.a end<(t1.c) then t1.f else e end) from t1 where 13<>c),e)-(t1.b) when t1.a then 17 else t1.f end FROM t1 WHERE NOT (coalesce((select max(t1.e) from t1 where (not exists(select 1 from t1 where b<+c))),case when b | ~case t1.a when -t1.b then -t1.f else t1.f end*f+f in (select t1.b from t1 union select t1.c from t1) then -(t1.f) when a<>11 then (d) else 11 end) in (select abs(~(abs(case (min(t1.b)*abs(count(distinct a)+count(*) | -count(distinct a)))- -max(19) when max(t1.e) then min(d) else (max(a)) end))) from t1 union select count(*) from t1))} +} {600} +do_test randexpr-2.490 { + db eval {SELECT case -coalesce((select max(case when case when t1.e in (11*t1.e*17,(select (min(b) & - -+cast(avg(17) AS integer)*max((t1.c))+cast(avg(t1.a) AS integer))+(( -(min(t1.c))))*count(*) from t1), -~b*t1.d+t1.d) then d else t1.a end<(t1.c) then t1.f else e end) from t1 where 13<>c),e)-(t1.b) when t1.a then 17 else t1.f end FROM t1 WHERE NOT (coalesce((select max(t1.e) from t1 where (not exists(select 1 from t1 where b<+c))),case when b | ~case t1.a when -t1.b then -t1.f else t1.f end*f+f in (select t1.b from t1 union select t1.c from t1) then -(t1.f) when a<>11 then (d) else 11 end) in (select abs(~(abs(case (min(t1.b)*abs(count(distinct a)+count(*) | -count(distinct a)))- -max(19) when max(t1.e) then min(d) else (max(a)) end))) from t1 union select count(*) from t1))} +} {600} +do_test randexpr-2.491 { + db eval {SELECT +case when case when ~t1.b<=case when ~17*19 | 11*11*f between t1.c and b then t1.a when e in (t1.a,t1.e,e) then t1.c else 19 end-t1.c-17+a then (t1.d) when 13 not between 13 and 19 then c else c end=(f) or d -coalesce((select t1.b from t1 where c*13+c<>t1.f),a)),t1.e)+t1.f=t1.f then - - -f else b end then -11 else -d end from t1 where ( -t1.c -coalesce((select t1.b from t1 where c*13+c<>t1.f),a)),t1.e)+t1.f=t1.f then - - -f else b end then -11 else -d end from t1 where ( -t1.c -coalesce((select t1.b from t1 where c*13+c<>t1.f),a)),t1.e)+t1.f=t1.f then - - -f else b end then -11 else -d end from t1 where ( -t1.ccase when b between ~11 and (abs(case when (coalesce((select max(+13) from t1 where not not exists(select 1 from t1 where t1.b+e in (b,t1.b,t1.d)) and 13 not in (d,f,17)),t1.a) not in (t1.f,17,17)) then coalesce((select max(19) from t1 where (17) in (t1.a,17,a)),t1.b) when b in (13,t1.a,b) then t1.c else d end)/abs(11)) then t1.f when t1.d>19 then d else d end)} +} {39800} +do_test randexpr-2.495 { + db eval {SELECT case when case when 19 in (select abs(abs(count(distinct f))*~~~count(*)-abs(+abs(count(*))* -cast(avg(17) AS integer) | cast(avg(t1.d) AS integer))+count(distinct -t1.a)+count(*)) from t1 union select -cast(avg(19) AS integer) from t1) then b* -b-c else t1.e*c end=17 then d else coalesce((select -11 from t1 where ecase when b between ~11 and (abs(case when (coalesce((select max(+13) from t1 where not not exists(select 1 from t1 where t1.b+e in (b,t1.b,t1.d)) and 13 not in (d,f,17)),t1.a) not in (t1.f,17,17)) then coalesce((select max(19) from t1 where (17) in (t1.a,17,a)),t1.b) when b in (13,t1.a,b) then t1.c else d end)/abs(11)) then t1.f when t1.d>19 then d else d end))} +} {} +do_test randexpr-2.496 { + db eval {SELECT case when case when 19 in (select abs(abs(count(distinct f))*~~~count(*)-abs(+abs(count(*))* -cast(avg(17) AS integer) & cast(avg(t1.d) AS integer))+count(distinct -t1.a)+count(*)) from t1 union select -cast(avg(19) AS integer) from t1) then b* -b-c else t1.e*c end=17 then d else coalesce((select -11 from t1 where ecase when b between ~11 and (abs(case when (coalesce((select max(+13) from t1 where not not exists(select 1 from t1 where t1.b+e in (b,t1.b,t1.d)) and 13 not in (d,f,17)),t1.a) not in (t1.f,17,17)) then coalesce((select max(19) from t1 where (17) in (t1.a,17,a)),t1.b) when b in (13,t1.a,b) then t1.c else d end)/abs(11)) then t1.f when t1.d>19 then d else d end)} +} {39800} +do_test randexpr-2.497 { + db eval {SELECT t1.a-coalesce((select t1.e from t1 where not exists(select 1 from t1 where a in (select min(d-11) | cast(avg((select -case count(*) when count(*) then +abs(+case ~min((abs(13- -a)/abs(t1.c))) when ~~count(*)+min((13)) then max(t1.e) else cast(avg(t1.a) AS integer) end | max(c))+count(*) else count(*) end*max(t1.d) from t1)) AS integer)+max(t1.c)*count(distinct f) from t1 union select -count(*) from t1))),~17) FROM t1 WHERE case 11 when coalesce((select coalesce((select 19 from t1 where t1.b not between t1.e and e and not not exists(select 1 from t1 where (e in ((abs(c)/abs(17)),(d) | e,(select count(distinct t1.b) from t1)-b)))),case d when a then f else t1.c end) | (t1.d) | b from t1 where t1.c not in (t1.a,19,11)),t1.b)-d then t1.e else t1.d end*t1.d<>f} +} {-400} +do_test randexpr-2.498 { + db eval {SELECT t1.a-coalesce((select t1.e from t1 where not exists(select 1 from t1 where a in (select min(d-11) | cast(avg((select -case count(*) when count(*) then +abs(+case ~min((abs(13- -a)/abs(t1.c))) when ~~count(*)+min((13)) then max(t1.e) else cast(avg(t1.a) AS integer) end | max(c))+count(*) else count(*) end*max(t1.d) from t1)) AS integer)+max(t1.c)*count(distinct f) from t1 union select -count(*) from t1))),~17) FROM t1 WHERE NOT (case 11 when coalesce((select coalesce((select 19 from t1 where t1.b not between t1.e and e and not not exists(select 1 from t1 where (e in ((abs(c)/abs(17)),(d) | e,(select count(distinct t1.b) from t1)-b)))),case d when a then f else t1.c end) | (t1.d) | b from t1 where t1.c not in (t1.a,19,11)),t1.b)-d then t1.e else t1.d end*t1.d<>f)} +} {} +do_test randexpr-2.499 { + db eval {SELECT t1.a-coalesce((select t1.e from t1 where not exists(select 1 from t1 where a in (select min(d-11) & cast(avg((select -case count(*) when count(*) then +abs(+case ~min((abs(13- -a)/abs(t1.c))) when ~~count(*)+min((13)) then max(t1.e) else cast(avg(t1.a) AS integer) end & max(c))+count(*) else count(*) end*max(t1.d) from t1)) AS integer)+max(t1.c)*count(distinct f) from t1 union select -count(*) from t1))),~17) FROM t1 WHERE case 11 when coalesce((select coalesce((select 19 from t1 where t1.b not between t1.e and e and not not exists(select 1 from t1 where (e in ((abs(c)/abs(17)),(d) | e,(select count(distinct t1.b) from t1)-b)))),case d when a then f else t1.c end) | (t1.d) | b from t1 where t1.c not in (t1.a,19,11)),t1.b)-d then t1.e else t1.d end*t1.d<>f} +} {-400} +do_test randexpr-2.500 { + db eval {SELECT case b*coalesce((select coalesce((select max(coalesce((select t1.b from t1 where t1.a<>11),17+~19)) from t1 where (t1.e<>e)),case 13 when 17 then 13 else c-coalesce((select max(case when (select min(d) from t1) in (select max(13) from t1 union select min(t1.f) from t1) then 13 else t1.a end*c) from t1 where t1.b<(t1.b)),f) end) from t1 where 19<=t1.e),(t1.b)) when t1.b then e else t1.d end+t1.c FROM t1 WHERE b+coalesce((select max((d)) from t1 where e=b),t1.c)*((select -(min(coalesce((select 19+(abs((abs((t1.a)*case f when c then t1.b else t1.d end-e)/abs((t1.f))))/abs( -t1.e))+b from t1 where 13 not between d and t1.c),t1.f))) from t1))*case e when 19 then t1.d else t1.b end+t1.e not in (t1.d,t1.a,17)} +} {700} +do_test randexpr-2.501 { + db eval {SELECT case b*coalesce((select coalesce((select max(coalesce((select t1.b from t1 where t1.a<>11),17+~19)) from t1 where (t1.e<>e)),case 13 when 17 then 13 else c-coalesce((select max(case when (select min(d) from t1) in (select max(13) from t1 union select min(t1.f) from t1) then 13 else t1.a end*c) from t1 where t1.b<(t1.b)),f) end) from t1 where 19<=t1.e),(t1.b)) when t1.b then e else t1.d end+t1.c FROM t1 WHERE NOT (b+coalesce((select max((d)) from t1 where e=b),t1.c)*((select -(min(coalesce((select 19+(abs((abs((t1.a)*case f when c then t1.b else t1.d end-e)/abs((t1.f))))/abs( -t1.e))+b from t1 where 13 not between d and t1.c),t1.f))) from t1))*case e when 19 then t1.d else t1.b end+t1.e not in (t1.d,t1.a,17))} +} {} +do_test randexpr-2.502 { + db eval {SELECT case when case when exists(select 1 from t1 where 17 in (select b from t1 union select 13 from t1)) and 19+a in (select count(distinct -(select min(t1.a-f) from t1)) from t1 union select min(case when 11 between coalesce((select max(t1.b) from t1 where case when t1.d<>c or t1.b>=t1.a then ( -11) else t1.d end>=t1.a),t1.c) and -17 then -t1.f else e end) from t1) then a else 19 end+t1.e in (select e from t1 union select -t1.b from t1) then t1.b when not (f) between f and t1.c then t1.e else e end FROM t1 WHERE 17>coalesce((select t1.b from t1 where t1.a+case when b in (19,t1.c,case t1.e when d-(b) then t1.f else 13 end) then 13 when d in (select count(distinct t1.a) from t1 union select case ~max(f) when cast(avg(b) AS integer) then max(d) else min(t1.f) end*min(e) from t1) or (t1.c=t1.e} +} {} +do_test randexpr-2.503 { + db eval {SELECT case when case when exists(select 1 from t1 where 17 in (select b from t1 union select 13 from t1)) and 19+a in (select count(distinct -(select min(t1.a-f) from t1)) from t1 union select min(case when 11 between coalesce((select max(t1.b) from t1 where case when t1.d<>c or t1.b>=t1.a then ( -11) else t1.d end>=t1.a),t1.c) and -17 then -t1.f else e end) from t1) then a else 19 end+t1.e in (select e from t1 union select -t1.b from t1) then t1.b when not (f) between f and t1.c then t1.e else e end FROM t1 WHERE NOT (17>coalesce((select t1.b from t1 where t1.a+case when b in (19,t1.c,case t1.e when d-(b) then t1.f else 13 end) then 13 when d in (select count(distinct t1.a) from t1 union select case ~max(f) when cast(avg(b) AS integer) then max(d) else min(t1.f) end*min(e) from t1) or (t1.c=t1.e)} +} {500} +do_test randexpr-2.504 { + db eval {SELECT c*(select (count(distinct (abs(case when t1.c<>e then e else 19 end)/abs(case when case when +case when a | t1.e+t1.e in (select -count(*) from t1 union select (max(case when 11 not in (t1.f,11,f) then c when c not in (d,t1.f,t1.f) then -t1.a else 13 end)) from t1) then 17 else 13 end>=t1.e then -11 when (t1.f)>c then 11 else 11 end<=11 and not exists(select 1 from t1 where t1.a between t1.e and e) then 19 else (17) end)))) from t1) FROM t1 WHERE ((select -case min(a-13*17+c*coalesce((select 19 from t1 where 19>=t1.d),(t1.b))+t1.e) when +(min(17)) then min(17) else +min(b) end* -cast(avg(19) AS integer)*count(*) from t1) not between a and d) and +c in (c,t1.d,d) or d<>t1.f} +} {300} +do_test randexpr-2.505 { + db eval {SELECT c*(select (count(distinct (abs(case when t1.c<>e then e else 19 end)/abs(case when case when +case when a | t1.e+t1.e in (select -count(*) from t1 union select (max(case when 11 not in (t1.f,11,f) then c when c not in (d,t1.f,t1.f) then -t1.a else 13 end)) from t1) then 17 else 13 end>=t1.e then -11 when (t1.f)>c then 11 else 11 end<=11 and not exists(select 1 from t1 where t1.a between t1.e and e) then 19 else (17) end)))) from t1) FROM t1 WHERE NOT (((select -case min(a-13*17+c*coalesce((select 19 from t1 where 19>=t1.d),(t1.b))+t1.e) when +(min(17)) then min(17) else +min(b) end* -cast(avg(19) AS integer)*count(*) from t1) not between a and d) and +c in (c,t1.d,d) or d<>t1.f)} +} {} +do_test randexpr-2.506 { + db eval {SELECT c*(select (count(distinct (abs(case when t1.c<>e then e else 19 end)/abs(case when case when +case when a & t1.e+t1.e in (select -count(*) from t1 union select (max(case when 11 not in (t1.f,11,f) then c when c not in (d,t1.f,t1.f) then -t1.a else 13 end)) from t1) then 17 else 13 end>=t1.e then -11 when (t1.f)>c then 11 else 11 end<=11 and not exists(select 1 from t1 where t1.a between t1.e and e) then 19 else (17) end)))) from t1) FROM t1 WHERE ((select -case min(a-13*17+c*coalesce((select 19 from t1 where 19>=t1.d),(t1.b))+t1.e) when +(min(17)) then min(17) else +min(b) end* -cast(avg(19) AS integer)*count(*) from t1) not between a and d) and +c in (c,t1.d,d) or d<>t1.f} +} {300} +do_test randexpr-2.507 { + db eval {SELECT a*coalesce((select t1.d+17 from t1 where 13*case a when t1.a then 11 else -t1.a-d-11-coalesce((select max(e-coalesce((select d from t1 where a<=t1.d*(coalesce((select max( -t1.d) from t1 where t1.f not in (11, -t1.d,17) and t1.a between (13) and c and e not in (t1.b,t1.b,b)),b))), -17)) from t1 where t1.b<>a),19)+t1.d+t1.c end<13),t1.e) FROM t1 WHERE t1.e not between f and 19} +} {50000} +do_test randexpr-2.508 { + db eval {SELECT a*coalesce((select t1.d+17 from t1 where 13*case a when t1.a then 11 else -t1.a-d-11-coalesce((select max(e-coalesce((select d from t1 where a<=t1.d*(coalesce((select max( -t1.d) from t1 where t1.f not in (11, -t1.d,17) and t1.a between (13) and c and e not in (t1.b,t1.b,b)),b))), -17)) from t1 where t1.b<>a),19)+t1.d+t1.c end<13),t1.e) FROM t1 WHERE NOT (t1.e not between f and 19)} +} {} +do_test randexpr-2.509 { + db eval {SELECT 17 | case case when exists(select 1 from t1 where (not t1.d between a and f)) then t1.e when not (b=coalesce((select ~t1.c-case when (select (count(*))*(count(distinct t1.f)) from t1)>=11 then b else 19 end from t1 where not not (13<=e) and t1.b=t1.b),13)) then coalesce((select max((abs(11)/abs(t1.b))) from t1 where t1.a not between t1.e and t1.b),(t1.a)) else t1.a end when c then 13 else 19 end+b FROM t1 WHERE ~t1.a+t1.d+c*17 | (select max(t1.d)*abs(case (max(t1.f)+count(distinct t1.b))*(count(distinct f)) when count(distinct e) then -min(t1.e) else min(t1.f) end)+max(b)+count(distinct t1.d) from t1) in (select max(t1.d*(19)) from t1 union select count(distinct case when t1.c+b in (select max(e) from t1 union select cast(avg(f) AS integer) from t1) then (17) when e not in (c,d,19) or 11=19 then (19) else t1.e end+t1.a) from t1)} +} {} +do_test randexpr-2.510 { + db eval {SELECT 17 | case case when exists(select 1 from t1 where (not t1.d between a and f)) then t1.e when not (b=coalesce((select ~t1.c-case when (select (count(*))*(count(distinct t1.f)) from t1)>=11 then b else 19 end from t1 where not not (13<=e) and t1.b=t1.b),13)) then coalesce((select max((abs(11)/abs(t1.b))) from t1 where t1.a not between t1.e and t1.b),(t1.a)) else t1.a end when c then 13 else 19 end+b FROM t1 WHERE NOT (~t1.a+t1.d+c*17 | (select max(t1.d)*abs(case (max(t1.f)+count(distinct t1.b))*(count(distinct f)) when count(distinct e) then -min(t1.e) else min(t1.f) end)+max(b)+count(distinct t1.d) from t1) in (select max(t1.d*(19)) from t1 union select count(distinct case when t1.c+b in (select max(e) from t1 union select cast(avg(f) AS integer) from t1) then (17) when e not in (c,d,19) or 11=19 then (19) else t1.e end+t1.a) from t1))} +} {219} +do_test randexpr-2.511 { + db eval {SELECT 17 & case case when exists(select 1 from t1 where (not t1.d between a and f)) then t1.e when not (b=coalesce((select ~t1.c-case when (select (count(*))*(count(distinct t1.f)) from t1)>=11 then b else 19 end from t1 where not not (13<=e) and t1.b=t1.b),13)) then coalesce((select max((abs(11)/abs(t1.b))) from t1 where t1.a not between t1.e and t1.b),(t1.a)) else t1.a end when c then 13 else 19 end+b FROM t1 WHERE NOT (~t1.a+t1.d+c*17 | (select max(t1.d)*abs(case (max(t1.f)+count(distinct t1.b))*(count(distinct f)) when count(distinct e) then -min(t1.e) else min(t1.f) end)+max(b)+count(distinct t1.d) from t1) in (select max(t1.d*(19)) from t1 union select count(distinct case when t1.c+b in (select max(e) from t1 union select cast(avg(f) AS integer) from t1) then (17) when e not in (c,d,19) or 11=19 then (19) else t1.e end+t1.a) from t1))} +} {17} +do_test randexpr-2.512 { + db eval {SELECT case when coalesce((select max((+t1.a+17+11+case when (abs(19)/abs(t1.a)) in (select ~(case count(*) when min( -c) then count(distinct b) else count(*) end) from t1 union select -min(t1.e) from t1) or 13>=t1.a then case c when 13 then t1.d else e end when -t1.e<=t1.a then t1.c else t1.c end)) from t1 where not t1.c= -t1.f),b)=f and t1.e<=(t1.f) then ~(t1.a) when 17=e then 19 else t1.b end FROM t1 WHERE case when -t1.f in (select (13) from t1 union select coalesce((select max(coalesce((select (~13) from t1 where t1.b>(11)),e*t1.c)) from t1 where (not (abs(t1.c)/abs(a))>=c)),t1.d) from t1) then -t1.e+ -a-coalesce((select t1.d from t1 where not exists(select 1 from t1 where -b=t1.f-f)),t1.c)*17 when 19<=11 then 19 else t1.d end>=b} +} {200} +do_test randexpr-2.513 { + db eval {SELECT case when coalesce((select max((+t1.a+17+11+case when (abs(19)/abs(t1.a)) in (select ~(case count(*) when min( -c) then count(distinct b) else count(*) end) from t1 union select -min(t1.e) from t1) or 13>=t1.a then case c when 13 then t1.d else e end when -t1.e<=t1.a then t1.c else t1.c end)) from t1 where not t1.c= -t1.f),b)=f and t1.e<=(t1.f) then ~(t1.a) when 17=e then 19 else t1.b end FROM t1 WHERE NOT (case when -t1.f in (select (13) from t1 union select coalesce((select max(coalesce((select (~13) from t1 where t1.b>(11)),e*t1.c)) from t1 where (not (abs(t1.c)/abs(a))>=c)),t1.d) from t1) then -t1.e+ -a-coalesce((select t1.d from t1 where not exists(select 1 from t1 where -b=t1.f-f)),t1.c)*17 when 19<=11 then 19 else t1.d end>=b)} +} {} +do_test randexpr-2.514 { + db eval {SELECT +(case when t1.a<=a then t1.d when ((abs(t1.a)/abs((coalesce((select t1.e from t1 where t1.f>=t1.c),e))))) between coalesce((select case when not 19> -11 then (case when t1.d in (select e from t1 union select f from t1) then -d when t1.b not between 11 and t1.d then (19) else c end) else t1.e end from t1 where not exists(select 1 from t1 where e not in (t1.d,a, -a)) and t1.d>t1.b),a) and t1.a then d else b end)-17 FROM t1 WHERE (+e*t1.d in (select (+abs(abs(min(~+b)-min(a)-case -case abs(max(t1.c)) when max(e) then count(*) else count(distinct 19) end- -max(t1.a) when count(distinct t1.a) then (count(*)) else min(t1.f) end)))-(count(*)) from t1 union select max(t1.f) from t1) or ~c*case when not exists(select 1 from t1 where t1.f in (t1.f,t1.a,d)) then t1.c when t1.c=t1.c),e))))) between coalesce((select case when not 19> -11 then (case when t1.d in (select e from t1 union select f from t1) then -d when t1.b not between 11 and t1.d then (19) else c end) else t1.e end from t1 where not exists(select 1 from t1 where e not in (t1.d,a, -a)) and t1.d>t1.b),a) and t1.a then d else b end)-17 FROM t1 WHERE NOT ((+e*t1.d in (select (+abs(abs(min(~+b)-min(a)-case -case abs(max(t1.c)) when max(e) then count(*) else count(distinct 19) end- -max(t1.a) when count(distinct t1.a) then (count(*)) else min(t1.f) end)))-(count(*)) from t1 union select max(t1.f) from t1) or ~c*case when not exists(select 1 from t1 where t1.f in (t1.f,t1.a,d)) then t1.c when t1.ct1.e then t1.a when -d=t1.e or t1.c not between t1.c and e then c else t1.d end)- -17 in (select a from t1 union select -t1.e from t1) then 19 else a end) from t1 where t1.a in (select -a from t1 union select 19 from t1)),t1.a)<>t1.d then 13 when a in (19,d,c) and a<11 then t1.a else b end+t1.a-t1.b FROM t1 WHERE c>=t1.e} +} {} +do_test randexpr-2.517 { + db eval {SELECT -case when coalesce((select max(case when ~(+case when t1.b*t1.b>t1.e then t1.a when -d=t1.e or t1.c not between t1.c and e then c else t1.d end)- -17 in (select a from t1 union select -t1.e from t1) then 19 else a end) from t1 where t1.a in (select -a from t1 union select 19 from t1)),t1.a)<>t1.d then 13 when a in (19,d,c) and a<11 then t1.a else b end+t1.a-t1.b FROM t1 WHERE NOT (c>=t1.e)} +} {-113} +do_test randexpr-2.518 { + db eval {SELECT coalesce((select case coalesce((select max(19) from t1 where +case when exists(select 1 from t1 where not exists(select 1 from t1 where not c in (case when e>=c then b else t1.b end,t1.b,t1.e))) then a-f+13-t1.f+19 when f>=t1.e then t1.e else t1.c end+17 in (select count(distinct 19) from t1 union select cast(avg(b) AS integer) | count(distinct 11)-count(*) from t1)),a) when b then 17 else c end from t1 where t1.f<=t1.e),t1.e) FROM t1 WHERE ~~+d-d*19*case ~(select count(*) from t1)-11 when 19 then -+(abs(t1.a)/abs(a)) | (f)-(abs(+t1.c)/abs((select ~+max(13*e)+min(f)*count(distinct 13) from t1)))*t1.a else -t1.f-t1.b end*t1.a not between -e and t1.e} +} {500} +do_test randexpr-2.519 { + db eval {SELECT coalesce((select case coalesce((select max(19) from t1 where +case when exists(select 1 from t1 where not exists(select 1 from t1 where not c in (case when e>=c then b else t1.b end,t1.b,t1.e))) then a-f+13-t1.f+19 when f>=t1.e then t1.e else t1.c end+17 in (select count(distinct 19) from t1 union select cast(avg(b) AS integer) | count(distinct 11)-count(*) from t1)),a) when b then 17 else c end from t1 where t1.f<=t1.e),t1.e) FROM t1 WHERE NOT (~~+d-d*19*case ~(select count(*) from t1)-11 when 19 then -+(abs(t1.a)/abs(a)) | (f)-(abs(+t1.c)/abs((select ~+max(13*e)+min(f)*count(distinct 13) from t1)))*t1.a else -t1.f-t1.b end*t1.a not between -e and t1.e)} +} {} +do_test randexpr-2.520 { + db eval {SELECT coalesce((select case coalesce((select max(19) from t1 where +case when exists(select 1 from t1 where not exists(select 1 from t1 where not c in (case when e>=c then b else t1.b end,t1.b,t1.e))) then a-f+13-t1.f+19 when f>=t1.e then t1.e else t1.c end+17 in (select count(distinct 19) from t1 union select cast(avg(b) AS integer) & count(distinct 11)-count(*) from t1)),a) when b then 17 else c end from t1 where t1.f<=t1.e),t1.e) FROM t1 WHERE ~~+d-d*19*case ~(select count(*) from t1)-11 when 19 then -+(abs(t1.a)/abs(a)) | (f)-(abs(+t1.c)/abs((select ~+max(13*e)+min(f)*count(distinct 13) from t1)))*t1.a else -t1.f-t1.b end*t1.a not between -e and t1.e} +} {500} +do_test randexpr-2.521 { + db eval {SELECT a*17+ -case when not exists(select 1 from t1 where 11=t1.d) then 11-b when case when t1.c<>t1.c++t1.a or t1.c*t1.a+d-f between 19 and case when not t1.e>=11 and t1.b<=t1.c then coalesce((select max(a) from t1 where 19=11),f) when f not in (t1.b,13,b) then f else -d end then d else t1.c end in (select 17 from t1 union select d from t1) then 17 else b end FROM t1 WHERE -(+~ -d++c+b)>=t1.a-case when coalesce((select t1.a-(select max(t1.e) from t1)-(abs(11)/abs(17))+t1.d from t1 where not (not exists(select 1 from t1 where c=t1.c)) or t1.b in (select abs(max(11)+count(*)) from t1 union select ((max(a))) from t1)),f)>=a then t1.f when d not in (11,c,17) then a else 19 end} +} {} +do_test randexpr-2.522 { + db eval {SELECT a*17+ -case when not exists(select 1 from t1 where 11=t1.d) then 11-b when case when t1.c<>t1.c++t1.a or t1.c*t1.a+d-f between 19 and case when not t1.e>=11 and t1.b<=t1.c then coalesce((select max(a) from t1 where 19=11),f) when f not in (t1.b,13,b) then f else -d end then d else t1.c end in (select 17 from t1 union select d from t1) then 17 else b end FROM t1 WHERE NOT ( -(+~ -d++c+b)>=t1.a-case when coalesce((select t1.a-(select max(t1.e) from t1)-(abs(11)/abs(17))+t1.d from t1 where not (not exists(select 1 from t1 where c=t1.c)) or t1.b in (select abs(max(11)+count(*)) from t1 union select ((max(a))) from t1)),f)>=a then t1.f when d not in (11,c,17) then a else 19 end)} +} {1889} +do_test randexpr-2.523 { + db eval {SELECT coalesce((select max(t1.b+a) from t1 where case (select count(distinct b*case when t1.f*+~a | b+17*13+a+11 in (select c from t1 union select d from t1) then t1.f else t1.b end) from t1) when t1.a then f else t1.c end+ -f between 17 and d and b in (13,t1.e,t1.e) and d not between t1.f and d),13) FROM t1 WHERE coalesce((select max(t1.d) from t1 where (coalesce((select ~t1.c from t1 where -t1.a<=c*+d or not (case when (t1.b)>=t1.d then t1.e when 17a and a<>e and t1.e=19)),19)<>t1.c} +} {13} +do_test randexpr-2.524 { + db eval {SELECT coalesce((select max(t1.b+a) from t1 where case (select count(distinct b*case when t1.f*+~a | b+17*13+a+11 in (select c from t1 union select d from t1) then t1.f else t1.b end) from t1) when t1.a then f else t1.c end+ -f between 17 and d and b in (13,t1.e,t1.e) and d not between t1.f and d),13) FROM t1 WHERE NOT (coalesce((select max(t1.d) from t1 where (coalesce((select ~t1.c from t1 where -t1.a<=c*+d or not (case when (t1.b)>=t1.d then t1.e when 17a and a<>e and t1.e=19)),19)<>t1.c)} +} {} +do_test randexpr-2.525 { + db eval {SELECT coalesce((select max(t1.b+a) from t1 where case (select count(distinct b*case when t1.f*+~a & b+17*13+a+11 in (select c from t1 union select d from t1) then t1.f else t1.b end) from t1) when t1.a then f else t1.c end+ -f between 17 and d and b in (13,t1.e,t1.e) and d not between t1.f and d),13) FROM t1 WHERE coalesce((select max(t1.d) from t1 where (coalesce((select ~t1.c from t1 where -t1.a<=c*+d or not (case when (t1.b)>=t1.d then t1.e when 17a and a<>e and t1.e=19)),19)<>t1.c} +} {13} +do_test randexpr-2.526 { + db eval {SELECT coalesce((select (t1.b-(abs(t1.b-~17 | 13+13)/abs(t1.e))* -t1.a- -19+t1.d) from t1 where exists(select 1 from t1 where 19 in (select t1.a from t1 union select -19 from t1) and a in (c,e,13) and 19 in (select t1.a from t1 union select b from t1) or 13 in (select 19 from t1 union select d from t1) and not t1.c=t1.f or ( -t1.d between e and 19) or -((17))<>c)),e) FROM t1 WHERE ((abs(a)/abs(f-a)) between -(abs(++t1.b)/abs(13)) and t1.c)} +} {619} +do_test randexpr-2.527 { + db eval {SELECT coalesce((select (t1.b-(abs(t1.b-~17 | 13+13)/abs(t1.e))* -t1.a- -19+t1.d) from t1 where exists(select 1 from t1 where 19 in (select t1.a from t1 union select -19 from t1) and a in (c,e,13) and 19 in (select t1.a from t1 union select b from t1) or 13 in (select 19 from t1 union select d from t1) and not t1.c=t1.f or ( -t1.d between e and 19) or -((17))<>c)),e) FROM t1 WHERE NOT (((abs(a)/abs(f-a)) between -(abs(++t1.b)/abs(13)) and t1.c))} +} {} +do_test randexpr-2.528 { + db eval {SELECT coalesce((select (t1.b-(abs(t1.b-~17 & 13+13)/abs(t1.e))* -t1.a- -19+t1.d) from t1 where exists(select 1 from t1 where 19 in (select t1.a from t1 union select -19 from t1) and a in (c,e,13) and 19 in (select t1.a from t1 union select b from t1) or 13 in (select 19 from t1 union select d from t1) and not t1.c=t1.f or ( -t1.d between e and 19) or -((17))<>c)),e) FROM t1 WHERE ((abs(a)/abs(f-a)) between -(abs(++t1.b)/abs(13)) and t1.c)} +} {619} +do_test randexpr-2.529 { + db eval {SELECT case when coalesce((select max(c- -b-t1.c) from t1 where t1.d between 11 and case when b | ~t1.e*(t1.f)>t1.f then a when (19<13) and not exists(select 1 from t1 where f not in (t1.a,((b)),17)) or d in ((a),t1.c,19) or (f)>13 then t1.e else f end*t1.a),t1.a)>=e then t1.d when t1.e>=c then 13 else f end FROM t1 WHERE +11 between case when t1.f>t1.c then t1.b else t1.b end and ((select count(distinct case when t1.a between (abs(coalesce((select t1.b from t1 where case when t1.d<=(abs((c))/abs(coalesce((select max(17) from t1 where 11=b),13))) then 17 when b=t1.e then d else e end-13>=(e)), -d))/abs(b)) and b then t1.d when (b) in (13,t1.b,t1.a) then f else 19 end) from t1))-d} +} {} +do_test randexpr-2.530 { + db eval {SELECT case when coalesce((select max(c- -b-t1.c) from t1 where t1.d between 11 and case when b | ~t1.e*(t1.f)>t1.f then a when (19<13) and not exists(select 1 from t1 where f not in (t1.a,((b)),17)) or d in ((a),t1.c,19) or (f)>13 then t1.e else f end*t1.a),t1.a)>=e then t1.d when t1.e>=c then 13 else f end FROM t1 WHERE NOT (+11 between case when t1.f>t1.c then t1.b else t1.b end and ((select count(distinct case when t1.a between (abs(coalesce((select t1.b from t1 where case when t1.d<=(abs((c))/abs(coalesce((select max(17) from t1 where 11=b),13))) then 17 when b=t1.e then d else e end-13>=(e)), -d))/abs(b)) and b then t1.d when (b) in (13,t1.b,t1.a) then f else 19 end) from t1))-d)} +} {13} +do_test randexpr-2.531 { + db eval {SELECT case when coalesce((select max(c- -b-t1.c) from t1 where t1.d between 11 and case when b & ~t1.e*(t1.f)>t1.f then a when (19<13) and not exists(select 1 from t1 where f not in (t1.a,((b)),17)) or d in ((a),t1.c,19) or (f)>13 then t1.e else f end*t1.a),t1.a)>=e then t1.d when t1.e>=c then 13 else f end FROM t1 WHERE NOT (+11 between case when t1.f>t1.c then t1.b else t1.b end and ((select count(distinct case when t1.a between (abs(coalesce((select t1.b from t1 where case when t1.d<=(abs((c))/abs(coalesce((select max(17) from t1 where 11=b),13))) then 17 when b=t1.e then d else e end-13>=(e)), -d))/abs(b)) and b then t1.d when (b) in (13,t1.b,t1.a) then f else 19 end) from t1))-d)} +} {13} +do_test randexpr-2.532 { + db eval {SELECT (select ~abs(max(case when (case when ( -t1.a>e) then t1.a else (select (~count(*) | max(case when t1.d<>c then -+13 else case when b between 19 and 17 or (t1.a)>=13 then 19 else t1.c end end)) from t1) end<>t1.e) then 19 when c*e+t1.b<=19 then f else (t1.d) end | b)) from t1)+c FROM t1 WHERE f | t1.a+b>=t1.d} +} {80} +do_test randexpr-2.533 { + db eval {SELECT (select ~abs(max(case when (case when ( -t1.a>e) then t1.a else (select (~count(*) | max(case when t1.d<>c then -+13 else case when b between 19 and 17 or (t1.a)>=13 then 19 else t1.c end end)) from t1) end<>t1.e) then 19 when c*e+t1.b<=19 then f else (t1.d) end | b)) from t1)+c FROM t1 WHERE NOT (f | t1.a+b>=t1.d)} +} {} +do_test randexpr-2.534 { + db eval {SELECT (select ~abs(max(case when (case when ( -t1.a>e) then t1.a else (select (~count(*) & max(case when t1.d<>c then -+13 else case when b between 19 and 17 or (t1.a)>=13 then 19 else t1.c end end)) from t1) end<>t1.e) then 19 when c*e+t1.b<=19 then f else (t1.d) end & b)) from t1)+c FROM t1 WHERE f | t1.a+b>=t1.d} +} {299} +do_test randexpr-2.535 { + db eval {SELECT -case when ~case t1.f+13+t1.a when coalesce((select max(17) from t1 where coalesce((select max(( -11)) from t1 where not exists(select 1 from t1 where case case when not exists(select 1 from t1 where (a in (select f from t1 union select b from t1))) then d when (a) in (f,t1.a, -f) then t1.a else b end when t1.d then c else t1.b end<>a and 11= -t1.a and 19=a)),11) in (select c from t1 union select 17 from t1)),t1.c) then e else 11 end=t1.d then 17 else 17 end FROM t1 WHERE not exists(select 1 from t1 where fa and 11= -t1.a and 19=a)),11) in (select c from t1 union select 17 from t1)),t1.c) then e else 11 end=t1.d then 17 else 17 end FROM t1 WHERE NOT (not exists(select 1 from t1 where fcoalesce((select max(case when (17> -t1.e) then f when 19=t1.a then t1.a else a end) from t1 where t1.c<=t1.e or (t1.d)>=t1.d),t1.a)+a then f when b not in (e,t1.e,t1.b) or t1.f not in (f,t1.c, -d) or e<=13 then f else (17) end-t1.d+t1.f*13 when (t1.c) then b else -t1.e end) from t1)) from t1 where t1.b in (t1.b,t1.f,(t1.e))),t1.e)*(a) FROM t1 WHERE t1.f<=a} +} {} +do_test randexpr-2.538 { + db eval {SELECT t1.f-t1.b | coalesce((select max((select max(case -case when t1.f>coalesce((select max(case when (17> -t1.e) then f when 19=t1.a then t1.a else a end) from t1 where t1.c<=t1.e or (t1.d)>=t1.d),t1.a)+a then f when b not in (e,t1.e,t1.b) or t1.f not in (f,t1.c, -d) or e<=13 then f else (17) end-t1.d+t1.f*13 when (t1.c) then b else -t1.e end) from t1)) from t1 where t1.b in (t1.b,t1.f,(t1.e))),t1.e)*(a) FROM t1 WHERE NOT (t1.f<=a)} +} {-49744} +do_test randexpr-2.539 { + db eval {SELECT t1.f-t1.b & coalesce((select max((select max(case -case when t1.f>coalesce((select max(case when (17> -t1.e) then f when 19=t1.a then t1.a else a end) from t1 where t1.c<=t1.e or (t1.d)>=t1.d),t1.a)+a then f when b not in (e,t1.e,t1.b) or t1.f not in (f,t1.c, -d) or e<=13 then f else (17) end-t1.d+t1.f*13 when (t1.c) then b else -t1.e end) from t1)) from t1 where t1.b in (t1.b,t1.f,(t1.e))),t1.e)*(a) FROM t1 WHERE NOT (t1.f<=a)} +} {144} +do_test randexpr-2.540 { + db eval {SELECT t1.e+t1.a*case when not t1.f<=d-(c)*13 then t1.e+13*(abs(case when exists(select 1 from t1 where (select -count(*)* -max(t1.a) | ((((cast(avg((e)) AS integer))))) from t1)>=+c+b) then +11 when t1.a not between t1.c and c then t1.b else -19 end)/abs(b)) | (19) when not exists(select 1 from t1 where t1.c between t1.e and t1.c) then d else t1.f end FROM t1 WHERE b in (+c,case b when f*~19-t1.b*t1.f then t1.f else a end,a | t1.a)} +} {} +do_test randexpr-2.541 { + db eval {SELECT t1.e+t1.a*case when not t1.f<=d-(c)*13 then t1.e+13*(abs(case when exists(select 1 from t1 where (select -count(*)* -max(t1.a) | ((((cast(avg((e)) AS integer))))) from t1)>=+c+b) then +11 when t1.a not between t1.c and c then t1.b else -19 end)/abs(b)) | (19) when not exists(select 1 from t1 where t1.c between t1.e and t1.c) then d else t1.f end FROM t1 WHERE NOT (b in (+c,case b when f*~19-t1.b*t1.f then t1.f else a end,a | t1.a))} +} {50800} +do_test randexpr-2.542 { + db eval {SELECT t1.e+t1.a*case when not t1.f<=d-(c)*13 then t1.e+13*(abs(case when exists(select 1 from t1 where (select -count(*)* -max(t1.a) & ((((cast(avg((e)) AS integer))))) from t1)>=+c+b) then +11 when t1.a not between t1.c and c then t1.b else -19 end)/abs(b)) & (19) when not exists(select 1 from t1 where t1.c between t1.e and t1.c) then d else t1.f end FROM t1 WHERE NOT (b in (+c,case b when f*~19-t1.b*t1.f then t1.f else a end,a | t1.a))} +} {600} +do_test randexpr-2.543 { + db eval {SELECT t1.e++a-c-a+coalesce((select t1.e from t1 where 11=case when t1.f not between 13 and t1.b+a*t1.c then 17 when (select min((select cast(avg(17) AS integer)*max(d)-(cast(avg(c) AS integer))*count(distinct t1.b) from t1)) from t1)>=case coalesce((select t1.b | e from t1 where t1.d in (t1.c,17,t1.c)),a) when 13 then t1.a else 19 end then t1.a else e end),t1.d) FROM t1 WHERE +t1.a*t1.c between case when case coalesce((select max(+t1.f-t1.b*(select min((b))+count(distinct c) from t1)) from t1 where -b between 11 and t1.b or b in (select -max(19) from t1 union select -count(*)+ -count(*) from t1) and 17=d),13)-t1.b*a when t1.b then (17) else c end>b then e else 11 end and ( -b) or t1.e not between a and 11} +} {600} +do_test randexpr-2.544 { + db eval {SELECT t1.e++a-c-a+coalesce((select t1.e from t1 where 11=case when t1.f not between 13 and t1.b+a*t1.c then 17 when (select min((select cast(avg(17) AS integer)*max(d)-(cast(avg(c) AS integer))*count(distinct t1.b) from t1)) from t1)>=case coalesce((select t1.b | e from t1 where t1.d in (t1.c,17,t1.c)),a) when 13 then t1.a else 19 end then t1.a else e end),t1.d) FROM t1 WHERE NOT (+t1.a*t1.c between case when case coalesce((select max(+t1.f-t1.b*(select min((b))+count(distinct c) from t1)) from t1 where -b between 11 and t1.b or b in (select -max(19) from t1 union select -count(*)+ -count(*) from t1) and 17=d),13)-t1.b*a when t1.b then (17) else c end>b then e else 11 end and ( -b) or t1.e not between a and 11)} +} {} +do_test randexpr-2.545 { + db eval {SELECT t1.e++a-c-a+coalesce((select t1.e from t1 where 11=case when t1.f not between 13 and t1.b+a*t1.c then 17 when (select min((select cast(avg(17) AS integer)*max(d)-(cast(avg(c) AS integer))*count(distinct t1.b) from t1)) from t1)>=case coalesce((select t1.b & e from t1 where t1.d in (t1.c,17,t1.c)),a) when 13 then t1.a else 19 end then t1.a else e end),t1.d) FROM t1 WHERE +t1.a*t1.c between case when case coalesce((select max(+t1.f-t1.b*(select min((b))+count(distinct c) from t1)) from t1 where -b between 11 and t1.b or b in (select -max(19) from t1 union select -count(*)+ -count(*) from t1) and 17=d),13)-t1.b*a when t1.b then (17) else c end>b then e else 11 end and ( -b) or t1.e not between a and 11} +} {600} +do_test randexpr-2.546 { + db eval {SELECT (select case ~case count(*) when (count(distinct d)*min(17)+min(13)+min(11))-max(t1.a) then count(distinct -13) else min(t1.c) end-max( - -t1.d)*count(*) when -count(*) then count(*) else (cast(avg(e) AS integer)) end from t1)-case when a>b then t1.d+case when (e= -t1.a) and c=(13) and t1.e<=c then 11 else t1.f end | t1.a)))-abs(abs(count(*)))-+~min(t1.e)+~count(distinct 11)* -count(*) | max(t1.d)-( -cast(avg(13) AS integer))*(min(e)) else -min(t1.a) end from t1 union select max(t1.f) from t1)} +} {} +do_test randexpr-2.547 { + db eval {SELECT (select case ~case count(*) when (count(distinct d)*min(17)+min(13)+min(11))-max(t1.a) then count(distinct -13) else min(t1.c) end-max( - -t1.d)*count(*) when -count(*) then count(*) else (cast(avg(e) AS integer)) end from t1)-case when a>b then t1.d+case when (e= -t1.a) and c=(13) and t1.e<=c then 11 else t1.f end | t1.a)))-abs(abs(count(*)))-+~min(t1.e)+~count(distinct 11)* -count(*) | max(t1.d)-( -cast(avg(13) AS integer))*(min(e)) else -min(t1.a) end from t1 union select max(t1.f) from t1))} +} {481} +do_test randexpr-2.548 { + db eval {SELECT case ~case 19 when t1.e then f else 19*f end*case when exists(select 1 from t1 where t1.e not between t1.f-~case case -e when f then t1.d else case when t1.b in (t1.e,f,11) then e when 11<=d then -t1.d else 17 end end when 13 then 19 else c end and 19) then coalesce((select t1.b from t1 where not exists(select 1 from t1 where (a<>b))),b) else t1.c end | e+t1.b when a then f else 19 end FROM t1 WHERE 17 in (select count(distinct t1.f)+~min(coalesce((select max(e*f-case when case when 11<>e and t1.e<=t1.d or (t1.d)<=t1.e then d when ( -17) not between -t1.c and t1.a then coalesce((select max((19)) from t1 where -b between e and 11), -a) else d end in (b,t1.d,a) and 19 in (13,13,t1.c) or b not in (f,(t1.e),19) then t1.c when 17 not in ((19),(t1.b),f) then +t1.d else f end) from t1 where (not a between 19 and d and (d>a))),d)) from t1 union select cast(avg(f) AS integer) from t1)} +} {} +do_test randexpr-2.549 { + db eval {SELECT case ~case 19 when t1.e then f else 19*f end*case when exists(select 1 from t1 where t1.e not between t1.f-~case case -e when f then t1.d else case when t1.b in (t1.e,f,11) then e when 11<=d then -t1.d else 17 end end when 13 then 19 else c end and 19) then coalesce((select t1.b from t1 where not exists(select 1 from t1 where (a<>b))),b) else t1.c end | e+t1.b when a then f else 19 end FROM t1 WHERE NOT (17 in (select count(distinct t1.f)+~min(coalesce((select max(e*f-case when case when 11<>e and t1.e<=t1.d or (t1.d)<=t1.e then d when ( -17) not between -t1.c and t1.a then coalesce((select max((19)) from t1 where -b between e and 11), -a) else d end in (b,t1.d,a) and 19 in (13,13,t1.c) or b not in (f,(t1.e),19) then t1.c when 17 not in ((19),(t1.b),f) then +t1.d else f end) from t1 where (not a between 19 and d and (d>a))),d)) from t1 union select cast(avg(f) AS integer) from t1))} +} {19} +do_test randexpr-2.550 { + db eval {SELECT case ~case 19 when t1.e then f else 19*f end*case when exists(select 1 from t1 where t1.e not between t1.f-~case case -e when f then t1.d else case when t1.b in (t1.e,f,11) then e when 11<=d then -t1.d else 17 end end when 13 then 19 else c end and 19) then coalesce((select t1.b from t1 where not exists(select 1 from t1 where (a<>b))),b) else t1.c end & e+t1.b when a then f else 19 end FROM t1 WHERE NOT (17 in (select count(distinct t1.f)+~min(coalesce((select max(e*f-case when case when 11<>e and t1.e<=t1.d or (t1.d)<=t1.e then d when ( -17) not between -t1.c and t1.a then coalesce((select max((19)) from t1 where -b between e and 11), -a) else d end in (b,t1.d,a) and 19 in (13,13,t1.c) or b not in (f,(t1.e),19) then t1.c when 17 not in ((19),(t1.b),f) then +t1.d else f end) from t1 where (not a between 19 and d and (d>a))),d)) from t1 union select cast(avg(f) AS integer) from t1))} +} {19} +do_test randexpr-2.551 { + db eval {SELECT (abs(11*coalesce((select max(t1.a) from t1 where d>=case when coalesce((select case when not exists(select 1 from t1 where -d in (select b-(abs(13)/abs(t1.e)) from t1 union select e from t1)) then ~c when not exists(select 1 from t1 where not exists(select 1 from t1 where -t1.d in (select cast(avg(c) AS integer) | count(distinct e)+max( -t1.d)-(max(f)) from t1 union select count(*) from t1))) then t1.a else e end from t1 where exists(select 1 from t1 where t1.f between d and t1.b) or 17 in (11,17,d)),11) not between t1.c and t1.d then 17 when 13=t1.a then 19 else (13) end), -t1.b)-e)/abs(a)) FROM t1 WHERE t1.c+t1.c=t1.f} +} {6} +do_test randexpr-2.552 { + db eval {SELECT (abs(11*coalesce((select max(t1.a) from t1 where d>=case when coalesce((select case when not exists(select 1 from t1 where -d in (select b-(abs(13)/abs(t1.e)) from t1 union select e from t1)) then ~c when not exists(select 1 from t1 where not exists(select 1 from t1 where -t1.d in (select cast(avg(c) AS integer) | count(distinct e)+max( -t1.d)-(max(f)) from t1 union select count(*) from t1))) then t1.a else e end from t1 where exists(select 1 from t1 where t1.f between d and t1.b) or 17 in (11,17,d)),11) not between t1.c and t1.d then 17 when 13=t1.a then 19 else (13) end), -t1.b)-e)/abs(a)) FROM t1 WHERE NOT (t1.c+t1.c=t1.f)} +} {} +do_test randexpr-2.553 { + db eval {SELECT (abs(11*coalesce((select max(t1.a) from t1 where d>=case when coalesce((select case when not exists(select 1 from t1 where -d in (select b-(abs(13)/abs(t1.e)) from t1 union select e from t1)) then ~c when not exists(select 1 from t1 where not exists(select 1 from t1 where -t1.d in (select cast(avg(c) AS integer) & count(distinct e)+max( -t1.d)-(max(f)) from t1 union select count(*) from t1))) then t1.a else e end from t1 where exists(select 1 from t1 where t1.f between d and t1.b) or 17 in (11,17,d)),11) not between t1.c and t1.d then 17 when 13=t1.a then 19 else (13) end), -t1.b)-e)/abs(a)) FROM t1 WHERE t1.c+t1.c=t1.f} +} {6} +do_test randexpr-2.554 { + db eval {SELECT -t1.a*coalesce((select max(c) from t1 where -(17 | case when (select cast(avg(17+coalesce((select max(c) from t1 where exists(select 1 from t1 where (coalesce((select max( -f) from t1 where (t1.b<=t1.b)),t1.e)<>e))),f | -t1.a)) AS integer) from t1) in (13,e,t1.c) then f when (f>e) then b else t1.a end)*c*e not between 19 and t1.b),11)+13-19*(19) FROM t1 WHERE (c<=t1.e)} +} {-30348} +do_test randexpr-2.555 { + db eval {SELECT -t1.a*coalesce((select max(c) from t1 where -(17 | case when (select cast(avg(17+coalesce((select max(c) from t1 where exists(select 1 from t1 where (coalesce((select max( -f) from t1 where (t1.b<=t1.b)),t1.e)<>e))),f | -t1.a)) AS integer) from t1) in (13,e,t1.c) then f when (f>e) then b else t1.a end)*c*e not between 19 and t1.b),11)+13-19*(19) FROM t1 WHERE NOT ((c<=t1.e))} +} {} +do_test randexpr-2.556 { + db eval {SELECT -t1.a*coalesce((select max(c) from t1 where -(17 & case when (select cast(avg(17+coalesce((select max(c) from t1 where exists(select 1 from t1 where (coalesce((select max( -f) from t1 where (t1.b<=t1.b)),t1.e)<>e))),f & -t1.a)) AS integer) from t1) in (13,e,t1.c) then f when (f>e) then b else t1.a end)*c*e not between 19 and t1.b),11)+13-19*(19) FROM t1 WHERE (c<=t1.e)} +} {-30348} +do_test randexpr-2.557 { + db eval {SELECT 19-coalesce((select max(case when 17 | t1.a in (select case case coalesce((select max(t1.b) from t1 where t1.f not between case when -b in (13,f,a) then a else a end and t1.f or (a not in (d,d,t1.c))),c) when a then t1.e else f end when 13 then 13 else b end from t1 union select 17 from t1) then c when not b not in (d, -t1.e,c) then 17 else b end) from t1 where e not in (17,t1.e,b)),t1.e) FROM t1 WHERE t1.a in (select -count(*) from t1 union select min((select (cast(avg((select +max(t1.b) from t1)) AS integer)) from t1)+17*c) from t1)} +} {} +do_test randexpr-2.558 { + db eval {SELECT 19-coalesce((select max(case when 17 | t1.a in (select case case coalesce((select max(t1.b) from t1 where t1.f not between case when -b in (13,f,a) then a else a end and t1.f or (a not in (d,d,t1.c))),c) when a then t1.e else f end when 13 then 13 else b end from t1 union select 17 from t1) then c when not b not in (d, -t1.e,c) then 17 else b end) from t1 where e not in (17,t1.e,b)),t1.e) FROM t1 WHERE NOT (t1.a in (select -count(*) from t1 union select min((select (cast(avg((select +max(t1.b) from t1)) AS integer)) from t1)+17*c) from t1))} +} {-481} +do_test randexpr-2.559 { + db eval {SELECT 19-coalesce((select max(case when 17 & t1.a in (select case case coalesce((select max(t1.b) from t1 where t1.f not between case when -b in (13,f,a) then a else a end and t1.f or (a not in (d,d,t1.c))),c) when a then t1.e else f end when 13 then 13 else b end from t1 union select 17 from t1) then c when not b not in (d, -t1.e,c) then 17 else b end) from t1 where e not in (17,t1.e,b)),t1.e) FROM t1 WHERE NOT (t1.a in (select -count(*) from t1 union select min((select (cast(avg((select +max(t1.b) from t1)) AS integer)) from t1)+17*c) from t1))} +} {-481} +do_test randexpr-2.560 { + db eval {SELECT -f-coalesce((select max(case a-t1.a when t1.f then 13 else +t1.a-t1.f end) from t1 where (select count(distinct a) from t1)>d),( -~t1.a+17+case when (not exists(select 1 from t1 where c=t1.b and c>t1.d)) then ~coalesce((select t1.f from t1 where t1.e not between t1.b and t1.e),11)+a when b<=t1.d then t1.c else 11 end+t1.b)*d)*17+d FROM t1 WHERE +t1.c in (select max(~case when 17>t1.f then 19 else -case when d=11 or t1.b> -t1.e or d not in (b,t1.a,t1.e) then e-( -13)+d else 11 end end-t1.d) from t1 union select max(17)+case min(t1.a) | case + -case abs(cast(avg(t1.d) AS integer)) when -count(*) then count(*) else max(19) end when min(e) then count(*) else cast(avg(t1.c) AS integer) end when min(t1.f) then count(*) else min(b) end from t1)} +} {} +do_test randexpr-2.561 { + db eval {SELECT -f-coalesce((select max(case a-t1.a when t1.f then 13 else +t1.a-t1.f end) from t1 where (select count(distinct a) from t1)>d),( -~t1.a+17+case when (not exists(select 1 from t1 where c=t1.b and c>t1.d)) then ~coalesce((select t1.f from t1 where t1.e not between t1.b and t1.e),11)+a when b<=t1.d then t1.c else 11 end+t1.b)*d)*17+d FROM t1 WHERE NOT (+t1.c in (select max(~case when 17>t1.f then 19 else -case when d=11 or t1.b> -t1.e or d not in (b,t1.a,t1.e) then e-( -13)+d else 11 end end-t1.d) from t1 union select max(17)+case min(t1.a) | case + -case abs(cast(avg(t1.d) AS integer)) when -count(*) then count(*) else max(19) end when min(e) then count(*) else cast(avg(t1.c) AS integer) end when min(t1.f) then count(*) else min(b) end from t1))} +} {-2761000} +do_test randexpr-2.562 { + db eval {SELECT coalesce((select 11 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not (select +count(*)* -count(distinct case when exists(select 1 from t1 where 13+a=t1.b) then d else 13 end-t1.b) from t1)<=17 | e-13)) or not exists(select 1 from t1 where not t1.e in ((13),17,19) and not t1.d>a and t1.e not between t1.e and b)),coalesce((select max(coalesce((select max(b) from t1 where (b)>11),d)) from t1 where 11> -19),f)-c) FROM t1 WHERE case when -13 not in (b,(abs(coalesce((select max(case when -17<>t1.f then b when coalesce((select t1.b from t1 where t1.c in (select (a) from t1 union select c from t1)),17)<=t1.e then b else f end) from t1 where b<=11),t1.c))/abs((d))),19) then t1.b when (exists(select 1 from t1 where not exists(select 1 from t1 where ((13)=e and t1.f between 17 and t1.a) or t1.f between (a) and -(t1.f)))) and t1.e between b and 13 or b<>(f) then t1.f else d end>=a or d>=13} +} {11} +do_test randexpr-2.563 { + db eval {SELECT coalesce((select 11 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not (select +count(*)* -count(distinct case when exists(select 1 from t1 where 13+a=t1.b) then d else 13 end-t1.b) from t1)<=17 | e-13)) or not exists(select 1 from t1 where not t1.e in ((13),17,19) and not t1.d>a and t1.e not between t1.e and b)),coalesce((select max(coalesce((select max(b) from t1 where (b)>11),d)) from t1 where 11> -19),f)-c) FROM t1 WHERE NOT (case when -13 not in (b,(abs(coalesce((select max(case when -17<>t1.f then b when coalesce((select t1.b from t1 where t1.c in (select (a) from t1 union select c from t1)),17)<=t1.e then b else f end) from t1 where b<=11),t1.c))/abs((d))),19) then t1.b when (exists(select 1 from t1 where not exists(select 1 from t1 where ((13)=e and t1.f between 17 and t1.a) or t1.f between (a) and -(t1.f)))) and t1.e between b and 13 or b<>(f) then t1.f else d end>=a or d>=13)} +} {} +do_test randexpr-2.564 { + db eval {SELECT coalesce((select 11 from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not (select +count(*)* -count(distinct case when exists(select 1 from t1 where 13+a=t1.b) then d else 13 end-t1.b) from t1)<=17 & e-13)) or not exists(select 1 from t1 where not t1.e in ((13),17,19) and not t1.d>a and t1.e not between t1.e and b)),coalesce((select max(coalesce((select max(b) from t1 where (b)>11),d)) from t1 where 11> -19),f)-c) FROM t1 WHERE case when -13 not in (b,(abs(coalesce((select max(case when -17<>t1.f then b when coalesce((select t1.b from t1 where t1.c in (select (a) from t1 union select c from t1)),17)<=t1.e then b else f end) from t1 where b<=11),t1.c))/abs((d))),19) then t1.b when (exists(select 1 from t1 where not exists(select 1 from t1 where ((13)=e and t1.f between 17 and t1.a) or t1.f between (a) and -(t1.f)))) and t1.e between b and 13 or b<>(f) then t1.f else d end>=a or d>=13} +} {11} +do_test randexpr-2.565 { + db eval {SELECT coalesce((select max(coalesce((select max(13+f | c+a) from t1 where 17d then 13 else c end-c then e else t1.e end),c) FROM t1 WHERE exists(select 1 from t1 where t1.a+( -case when exists(select 1 from t1 where exists(select 1 from t1 where b | c-c+t1.d not between 19 and 11)) then coalesce((select t1.c from t1 where c+17 in (f,13,c) or t1.e*coalesce((select case when (not exists(select 1 from t1 where 17>e)) then t1.d else ~t1.e end from t1 where (t1.f not in (19,a,t1.b) or c=f)),c)=c), -11) else e end)<=t1.b)} +} {300} +do_test randexpr-2.566 { + db eval {SELECT coalesce((select max(coalesce((select max(13+f | c+a) from t1 where 17d then 13 else c end-c then e else t1.e end),c) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.a+( -case when exists(select 1 from t1 where exists(select 1 from t1 where b | c-c+t1.d not between 19 and 11)) then coalesce((select t1.c from t1 where c+17 in (f,13,c) or t1.e*coalesce((select case when (not exists(select 1 from t1 where 17>e)) then t1.d else ~t1.e end from t1 where (t1.f not in (19,a,t1.b) or c=f)),c)=c), -11) else e end)<=t1.b))} +} {} +do_test randexpr-2.567 { + db eval {SELECT coalesce((select max(coalesce((select max(13+f & c+a) from t1 where 17d then 13 else c end-c then e else t1.e end),c) FROM t1 WHERE exists(select 1 from t1 where t1.a+( -case when exists(select 1 from t1 where exists(select 1 from t1 where b | c-c+t1.d not between 19 and 11)) then coalesce((select t1.c from t1 where c+17 in (f,13,c) or t1.e*coalesce((select case when (not exists(select 1 from t1 where 17>e)) then t1.d else ~t1.e end from t1 where (t1.f not in (19,a,t1.b) or c=f)),c)=c), -11) else e end)<=t1.b)} +} {300} +do_test randexpr-2.568 { + db eval {SELECT case when ((coalesce((select max((select ~cast(avg((~d*f)) AS integer) from t1)) from t1 where - -t1.f<>d),e) in (select cast(avg(+13) AS integer)*~count(*) | case count(*) when -abs(abs(max(f))) then cast(avg(e) AS integer) else (count(distinct b)) end from t1 union select count(*) from t1) and b>= -t1.d)) then (17) when b between 13 and t1.d then -e+t1.a else t1.f end FROM t1 WHERE (case when +t1.f-(select abs(count(distinct d)) from t1)*case when c in (select min(b) from t1 union select max(c+f*case 11*t1.b when b then t1.c else c end | t1.a) from t1) then d else f end | t1.a*b in (t1.d,17,a) then -t1.a else t1.d end) in (e,t1.c,f) and -((t1.c)) in (11,t1.e,t1.c)} +} {} +do_test randexpr-2.569 { + db eval {SELECT case when ((coalesce((select max((select ~cast(avg((~d*f)) AS integer) from t1)) from t1 where - -t1.f<>d),e) in (select cast(avg(+13) AS integer)*~count(*) | case count(*) when -abs(abs(max(f))) then cast(avg(e) AS integer) else (count(distinct b)) end from t1 union select count(*) from t1) and b>= -t1.d)) then (17) when b between 13 and t1.d then -e+t1.a else t1.f end FROM t1 WHERE NOT ((case when +t1.f-(select abs(count(distinct d)) from t1)*case when c in (select min(b) from t1 union select max(c+f*case 11*t1.b when b then t1.c else c end | t1.a) from t1) then d else f end | t1.a*b in (t1.d,17,a) then -t1.a else t1.d end) in (e,t1.c,f) and -((t1.c)) in (11,t1.e,t1.c))} +} {-400} +do_test randexpr-2.570 { + db eval {SELECT case when ((coalesce((select max((select ~cast(avg((~d*f)) AS integer) from t1)) from t1 where - -t1.f<>d),e) in (select cast(avg(+13) AS integer)*~count(*) & case count(*) when -abs(abs(max(f))) then cast(avg(e) AS integer) else (count(distinct b)) end from t1 union select count(*) from t1) and b>= -t1.d)) then (17) when b between 13 and t1.d then -e+t1.a else t1.f end FROM t1 WHERE NOT ((case when +t1.f-(select abs(count(distinct d)) from t1)*case when c in (select min(b) from t1 union select max(c+f*case 11*t1.b when b then t1.c else c end | t1.a) from t1) then d else f end | t1.a*b in (t1.d,17,a) then -t1.a else t1.d end) in (e,t1.c,f) and -((t1.c)) in (11,t1.e,t1.c))} +} {-400} +do_test randexpr-2.571 { + db eval {SELECT t1.d-case when e in (17,coalesce((select max((select count(*) from t1)) from t1 where (~t1.f++19*t1.f+b in (a,t1.b, -t1.e)) and b in (select count(distinct t1.a) from t1 union select (abs(abs(abs(max(t1.e)*max(t1.d))-min(11)* -count(*)))) from t1)),17),13) and t1.f in (select t1.b from t1 union select f from t1) then t1.c else c end+f FROM t1 WHERE not (select (abs(abs((+count(*)*~ -cast(avg(+t1.f-c) AS integer)*count(distinct +coalesce((select max((abs(c)/abs(t1.e))) from t1 where coalesce((select coalesce((select max(f) from t1 where t1.d<=t1.d),e)*c from t1 where t1.f<>f),c) not between t1.a and c),t1.e)+13)-count(distinct f) | abs(cast(avg(t1.b) AS integer)))))) from t1)-13f),c) not between t1.a and c),t1.e)+13)-count(distinct f) | abs(cast(avg(t1.b) AS integer)))))) from t1)-13=c or f<>e),+d))) | t1.c*b+t1.d)- -f)/abs(13))<>t1.e then -t1.e when t1.e not between f and t1.a then t1.c else t1.c end)/abs(t1.e)) FROM t1 WHERE (abs(b*t1.e+t1.a)/abs(t1.c))=c or f<>e),+d))) | t1.c*b+t1.d)- -f)/abs(13))<>t1.e then -t1.e when t1.e not between f and t1.a then t1.c else t1.c end)/abs(t1.e)) FROM t1 WHERE NOT ((abs(b*t1.e+t1.a)/abs(t1.c))=c or f<>e),+d))) & t1.c*b+t1.d)- -f)/abs(13))<>t1.e then -t1.e when t1.e not between f and t1.a then t1.c else t1.c end)/abs(t1.e)) FROM t1 WHERE NOT ((abs(b*t1.e+t1.a)/abs(t1.c))case when (17) in (select + -abs(count(distinct t1.e*17*c+f)-max(19)) from t1 union select count(*)-max(case t1.f when a then (11+19*t1.b+t1.f) else (19) end*t1.c) from t1) then (abs(b- -f)/abs(f)) else t1.f end} +} {0} +do_test randexpr-2.577 { + db eval {SELECT (abs(t1.c-case when +coalesce((select max(coalesce((select max(a-a*t1.f) from t1 where ~t1.a*t1.a-t1.b+f* -19 not in (t1.d,e,b)),11)*t1.a) from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (c) in (b,c,t1.c))) or t1.e between -b and b),a)+a<=e then t1.d else 17 end)/abs(f)) FROM t1 WHERE NOT (t1.d-t1.c+~t1.c<>case when (17) in (select + -abs(count(distinct t1.e*17*c+f)-max(19)) from t1 union select count(*)-max(case t1.f when a then (11+19*t1.b+t1.f) else (19) end*t1.c) from t1) then (abs(b- -f)/abs(f)) else t1.f end)} +} {} +do_test randexpr-2.578 { + db eval {SELECT (abs( -coalesce((select 11 from t1 where (case f when (19+ -(select count(*) from t1)) then (select ++~count(distinct 17+t1.f*(17)) | cast(avg(c) AS integer) from t1) else 13-t1.b*t1.b end*t1.c*(select max(e)*cast(avg(t1.b) AS integer) from t1) | 13) | 17 between 11 and 17),(e))+d)/abs(t1.b))-t1.d FROM t1 WHERE 11<>t1.b} +} {-400} +do_test randexpr-2.579 { + db eval {SELECT (abs( -coalesce((select 11 from t1 where (case f when (19+ -(select count(*) from t1)) then (select ++~count(distinct 17+t1.f*(17)) | cast(avg(c) AS integer) from t1) else 13-t1.b*t1.b end*t1.c*(select max(e)*cast(avg(t1.b) AS integer) from t1) | 13) | 17 between 11 and 17),(e))+d)/abs(t1.b))-t1.d FROM t1 WHERE NOT (11<>t1.b)} +} {} +do_test randexpr-2.580 { + db eval {SELECT (abs( -coalesce((select 11 from t1 where (case f when (19+ -(select count(*) from t1)) then (select ++~count(distinct 17+t1.f*(17)) & cast(avg(c) AS integer) from t1) else 13-t1.b*t1.b end*t1.c*(select max(e)*cast(avg(t1.b) AS integer) from t1) & 13) & 17 between 11 and 17),(e))+d)/abs(t1.b))-t1.d FROM t1 WHERE 11<>t1.b} +} {-400} +do_test randexpr-2.581 { + db eval {SELECT ( -13)-case when (13)+19 between (select cast(avg(11+coalesce((select d from t1 where t1.a in (select b from t1 union select c from t1)),11)+t1.e*d) AS integer)*+(max(t1.c))+cast(avg((c)) AS integer)*count(*) | max( -t1.b) from t1)-t1.d and t1.a then t1.b when b<>t1.f then t1.c else a end-b-t1.b FROM t1 WHERE 11<=t1.e+19*+t1.d} +} {-613} +do_test randexpr-2.582 { + db eval {SELECT ( -13)-case when (13)+19 between (select cast(avg(11+coalesce((select d from t1 where t1.a in (select b from t1 union select c from t1)),11)+t1.e*d) AS integer)*+(max(t1.c))+cast(avg((c)) AS integer)*count(*) | max( -t1.b) from t1)-t1.d and t1.a then t1.b when b<>t1.f then t1.c else a end-b-t1.b FROM t1 WHERE NOT (11<=t1.e+19*+t1.d)} +} {} +do_test randexpr-2.583 { + db eval {SELECT ( -13)-case when (13)+19 between (select cast(avg(11+coalesce((select d from t1 where t1.a in (select b from t1 union select c from t1)),11)+t1.e*d) AS integer)*+(max(t1.c))+cast(avg((c)) AS integer)*count(*) & max( -t1.b) from t1)-t1.d and t1.a then t1.b when b<>t1.f then t1.c else a end-b-t1.b FROM t1 WHERE 11<=t1.e+19*+t1.d} +} {-713} +do_test randexpr-2.584 { + db eval {SELECT coalesce((select max(t1.e++case ~t1.c when t1.f-c then t1.b*+coalesce((select max(+t1.c) from t1 where 19-19-13 | t1.d+(select ~min(17) from t1) not in (case when t1.a<>b then e else -e end,(t1.d),t1.a)),b)+((e))* -t1.e else t1.d end | b) from t1 where a not between 13 and c),t1.e) FROM t1 WHERE not case when (exists(select 1 from t1 where (((abs(19)/abs((case when exists(select 1 from t1 where +t1.f>c) then 19 when f in (t1.d,t1.a,13) and b=t1.e then t1.f else t1.a end))) in (e, -t1.c,t1.b))))) then -t1.f when b in (d,11, -d) then t1.e*t1.a else a end+d<>t1.f and (t1.f=( -17))} +} {} +do_test randexpr-2.585 { + db eval {SELECT coalesce((select max(t1.e++case ~t1.c when t1.f-c then t1.b*+coalesce((select max(+t1.c) from t1 where 19-19-13 | t1.d+(select ~min(17) from t1) not in (case when t1.a<>b then e else -e end,(t1.d),t1.a)),b)+((e))* -t1.e else t1.d end | b) from t1 where a not between 13 and c),t1.e) FROM t1 WHERE NOT (not case when (exists(select 1 from t1 where (((abs(19)/abs((case when exists(select 1 from t1 where +t1.f>c) then 19 when f in (t1.d,t1.a,13) and b=t1.e then t1.f else t1.a end))) in (e, -t1.c,t1.b))))) then -t1.f when b in (d,11, -d) then t1.e*t1.a else a end+d<>t1.f and (t1.f=( -17)))} +} {500} +do_test randexpr-2.586 { + db eval {SELECT coalesce((select max(t1.e++case ~t1.c when t1.f-c then t1.b*+coalesce((select max(+t1.c) from t1 where 19-19-13 & t1.d+(select ~min(17) from t1) not in (case when t1.a<>b then e else -e end,(t1.d),t1.a)),b)+((e))* -t1.e else t1.d end & b) from t1 where a not between 13 and c),t1.e) FROM t1 WHERE NOT (not case when (exists(select 1 from t1 where (((abs(19)/abs((case when exists(select 1 from t1 where +t1.f>c) then 19 when f in (t1.d,t1.a,13) and b=t1.e then t1.f else t1.a end))) in (e, -t1.c,t1.b))))) then -t1.f when b in (d,11, -d) then t1.e*t1.a else a end+d<>t1.f and (t1.f=( -17)))} +} {500} +do_test randexpr-2.587 { + db eval {SELECT case when t1.d-~case t1.b when coalesce((select max(b) from t1 where exists(select 1 from t1 where t1.c<>b)),case when 17 in (select min(c+17) from t1 union select ~ -count(distinct 11) | max(d) from t1) then d when ((t1.a not between t1.f and t1.f)) then t1.a else t1.b end) then (c) else (t1.c) end=d then -13 when b in (select cast(avg((a)) AS integer) from t1 union select -~abs(count(*))*min(t1.f) from t1) then d else 19 end)/abs(19)) when 11 then 11 else t1.f end+13-t1.d else t1.b end+b>=d and not exists(select 1 from t1 where e>=19)} +} {} +do_test randexpr-2.588 { + db eval {SELECT case when t1.d-~case t1.b when coalesce((select max(b) from t1 where exists(select 1 from t1 where t1.c<>b)),case when 17 in (select min(c+17) from t1 union select ~ -count(distinct 11) | max(d) from t1) then d when ((t1.a not between t1.f and t1.f)) then t1.a else t1.b end) then (c) else (t1.c) end=d then -13 when b in (select cast(avg((a)) AS integer) from t1 union select -~abs(count(*))*min(t1.f) from t1) then d else 19 end)/abs(19)) when 11 then 11 else t1.f end+13-t1.d else t1.b end+b>=d and not exists(select 1 from t1 where e>=19))} +} {-5489} +do_test randexpr-2.589 { + db eval {SELECT case when t1.d-~case t1.b when coalesce((select max(b) from t1 where exists(select 1 from t1 where t1.c<>b)),case when 17 in (select min(c+17) from t1 union select ~ -count(distinct 11) & max(d) from t1) then d when ((t1.a not between t1.f and t1.f)) then t1.a else t1.b end) then (c) else (t1.c) end=d then -13 when b in (select cast(avg((a)) AS integer) from t1 union select -~abs(count(*))*min(t1.f) from t1) then d else 19 end)/abs(19)) when 11 then 11 else t1.f end+13-t1.d else t1.b end+b>=d and not exists(select 1 from t1 where e>=19))} +} {-5489} +do_test randexpr-2.590 { + db eval {SELECT b+coalesce((select (t1.e) from t1 where coalesce((select max((select abs(cast(avg( -t1.f*17) AS integer))+count(*) from t1)-19*coalesce((select b*+~(t1.c)*(abs(c)/abs(a))+t1.e from t1 where 11 in (t1.a,17,b* -t1.f)),t1.e)*t1.b) from t1 where t1.f<>17),17) in (11,11, -t1.f)),t1.e) FROM t1 WHERE coalesce((select max(coalesce((select 19-e from t1 where t1.b not in (coalesce((select max(t1.e+coalesce((select 11+ -coalesce((select max(t1.a) from t1 where t1.a in (select cast(avg( -11) AS integer) from t1 union select -max(c) from t1)),11)*t1.a from t1 where exists(select 1 from t1 where a= -e)),e)-t1.c | t1.d) from t1 where t1.e=t1.a),17),(t1.e),c)),t1.b)) from t1 where not exists(select 1 from t1 where (13>=a) or exists(select 1 from t1 where d<>11))), -19)<=t1.b} +} {700} +do_test randexpr-2.591 { + db eval {SELECT b+coalesce((select (t1.e) from t1 where coalesce((select max((select abs(cast(avg( -t1.f*17) AS integer))+count(*) from t1)-19*coalesce((select b*+~(t1.c)*(abs(c)/abs(a))+t1.e from t1 where 11 in (t1.a,17,b* -t1.f)),t1.e)*t1.b) from t1 where t1.f<>17),17) in (11,11, -t1.f)),t1.e) FROM t1 WHERE NOT (coalesce((select max(coalesce((select 19-e from t1 where t1.b not in (coalesce((select max(t1.e+coalesce((select 11+ -coalesce((select max(t1.a) from t1 where t1.a in (select cast(avg( -11) AS integer) from t1 union select -max(c) from t1)),11)*t1.a from t1 where exists(select 1 from t1 where a= -e)),e)-t1.c | t1.d) from t1 where t1.e=t1.a),17),(t1.e),c)),t1.b)) from t1 where not exists(select 1 from t1 where (13>=a) or exists(select 1 from t1 where d<>11))), -19)<=t1.b)} +} {} +do_test randexpr-2.592 { + db eval {SELECT (select count(distinct t1.a)-cast(avg(~c+coalesce((select e from t1 where e in (select t1.f from t1 union select d from t1) or t1.d not in (case when a not in (t1.d,t1.c,t1.b) then a-case when ~t1.b+t1.e | -t1.e not in (a,(b),19) then t1.d else 11 end*b when 13 in (c,13,t1.a) then -t1.a else 17 end,c,d)),t1.e)) AS integer) from t1) FROM t1 WHERE ~e<=(a-(select count(*) from t1)+c+(select -abs(abs( -(max((abs(coalesce((select a*(abs(b-b)/abs((c*a*b)-11+coalesce((select max(b) from t1 where ae),e))/abs(11))*t1.e)))) | abs((count(*))) from t1))} +} {-198} +do_test randexpr-2.593 { + db eval {SELECT (select count(distinct t1.a)-cast(avg(~c+coalesce((select e from t1 where e in (select t1.f from t1 union select d from t1) or t1.d not in (case when a not in (t1.d,t1.c,t1.b) then a-case when ~t1.b+t1.e | -t1.e not in (a,(b),19) then t1.d else 11 end*b when 13 in (c,13,t1.a) then -t1.a else 17 end,c,d)),t1.e)) AS integer) from t1) FROM t1 WHERE NOT (~e<=(a-(select count(*) from t1)+c+(select -abs(abs( -(max((abs(coalesce((select a*(abs(b-b)/abs((c*a*b)-11+coalesce((select max(b) from t1 where ae),e))/abs(11))*t1.e)))) | abs((count(*))) from t1)))} +} {} +do_test randexpr-2.594 { + db eval {SELECT (select count(distinct t1.a)-cast(avg(~c+coalesce((select e from t1 where e in (select t1.f from t1 union select d from t1) or t1.d not in (case when a not in (t1.d,t1.c,t1.b) then a-case when ~t1.b+t1.e & -t1.e not in (a,(b),19) then t1.d else 11 end*b when 13 in (c,13,t1.a) then -t1.a else 17 end,c,d)),t1.e)) AS integer) from t1) FROM t1 WHERE ~e<=(a-(select count(*) from t1)+c+(select -abs(abs( -(max((abs(coalesce((select a*(abs(b-b)/abs((c*a*b)-11+coalesce((select max(b) from t1 where ae),e))/abs(11))*t1.e)))) | abs((count(*))) from t1))} +} {-198} +do_test randexpr-2.595 { + db eval {SELECT 13-(select cast(avg(t1.c-13) AS integer) from t1) | 11+t1.b | coalesce((select max(case when b in (select case -case max(17) when ~cast(avg(13-t1.a) AS integer) then count(distinct 13) else - -((cast(avg(e) AS integer))) end when cast(avg(t1.c) AS integer) then count(distinct d) else count(*) end from t1 union select count(*) from t1) then case when t1.d<>~13 then b when t1.c<>13 then t1.a else a end else t1.a end) from t1 where t1.f<>( -(17))),t1.e)+c FROM t1 WHERE (~coalesce((select (11+t1.d) from t1 where 17 in (select f+a from t1 union select case when 11>coalesce((select -case when (11 not in (t1.f,(abs(t1.a)/abs((select count(distinct -case when 13<=e then c when d between (t1.d) and t1.d then a else 11 end) from t1)-f)),c)) then f when (t1.f>t1.d) then 17 else 13 end from t1 where t1.e>a),17) then f else t1.b end from t1)),b)*13>e)} +} {} +do_test randexpr-2.596 { + db eval {SELECT 13-(select cast(avg(t1.c-13) AS integer) from t1) | 11+t1.b | coalesce((select max(case when b in (select case -case max(17) when ~cast(avg(13-t1.a) AS integer) then count(distinct 13) else - -((cast(avg(e) AS integer))) end when cast(avg(t1.c) AS integer) then count(distinct d) else count(*) end from t1 union select count(*) from t1) then case when t1.d<>~13 then b when t1.c<>13 then t1.a else a end else t1.a end) from t1 where t1.f<>( -(17))),t1.e)+c FROM t1 WHERE NOT ((~coalesce((select (11+t1.d) from t1 where 17 in (select f+a from t1 union select case when 11>coalesce((select -case when (11 not in (t1.f,(abs(t1.a)/abs((select count(distinct -case when 13<=e then c when d between (t1.d) and t1.d then a else 11 end) from t1)-f)),c)) then f when (t1.f>t1.d) then 17 else 13 end from t1 where t1.e>a),17) then f else t1.b end from t1)),b)*13>e))} +} {-1} +do_test randexpr-2.597 { + db eval {SELECT 13-(select cast(avg(t1.c-13) AS integer) from t1) & 11+t1.b & coalesce((select max(case when b in (select case -case max(17) when ~cast(avg(13-t1.a) AS integer) then count(distinct 13) else - -((cast(avg(e) AS integer))) end when cast(avg(t1.c) AS integer) then count(distinct d) else count(*) end from t1 union select count(*) from t1) then case when t1.d<>~13 then b when t1.c<>13 then t1.a else a end else t1.a end) from t1 where t1.f<>( -(17))),t1.e)+c FROM t1 WHERE NOT ((~coalesce((select (11+t1.d) from t1 where 17 in (select f+a from t1 union select case when 11>coalesce((select -case when (11 not in (t1.f,(abs(t1.a)/abs((select count(distinct -case when 13<=e then c when d between (t1.d) and t1.d then a else 11 end) from t1)-f)),c)) then f when (t1.f>t1.d) then 17 else 13 end from t1 where t1.e>a),17) then f else t1.b end from t1)),b)*13>e))} +} {128} +do_test randexpr-2.598 { + db eval {SELECT f+coalesce((select case when ~case when coalesce((select max(b) from t1 where not exists(select 1 from t1 where 11*t1.b>case t1.b when 13 then 11 else b end)),t1.b) not in (a,b,+t1.e | case when t1.a<>17 then 17 else t1.e end) then c when (t1.e)<>d then 11 else f end*(e) not between d and e then 17 else 17 end from t1 where 13 not between 19 and f),t1.b)*11 FROM t1 WHERE not exists(select 1 from t1 where 11 between c and b and -case when 13 between -f | case when t1.b<+c then b when t1.f>13 then a else (d) end and d then t1.d when t1.a in (select 19 from t1 union select 11 from t1) or not exists(select 1 from t1 where exists(select 1 from t1 where not b=t1.b)) then -19 else t1.b end in (select max(17) from t1 union select count(distinct a)+count(distinct 11) from t1) and t1.fcase t1.b when 13 then 11 else b end)),t1.b) not in (a,b,+t1.e | case when t1.a<>17 then 17 else t1.e end) then c when (t1.e)<>d then 11 else f end*(e) not between d and e then 17 else 17 end from t1 where 13 not between 19 and f),t1.b)*11 FROM t1 WHERE NOT (not exists(select 1 from t1 where 11 between c and b and -case when 13 between -f | case when t1.b<+c then b when t1.f>13 then a else (d) end and d then t1.d when t1.a in (select 19 from t1 union select 11 from t1) or not exists(select 1 from t1 where exists(select 1 from t1 where not b=t1.b)) then -19 else t1.b end in (select max(17) from t1 union select count(distinct a)+count(distinct 11) from t1) and t1.fcase t1.b when 13 then 11 else b end)),t1.b) not in (a,b,+t1.e & case when t1.a<>17 then 17 else t1.e end) then c when (t1.e)<>d then 11 else f end*(e) not between d and e then 17 else 17 end from t1 where 13 not between 19 and f),t1.b)*11 FROM t1 WHERE NOT (not exists(select 1 from t1 where 11 between c and b and -case when 13 between -f | case when t1.b<+c then b when t1.f>13 then a else (d) end and d then t1.d when t1.a in (select 19 from t1 union select 11 from t1) or not exists(select 1 from t1 where exists(select 1 from t1 where not b=t1.b)) then -19 else t1.b end in (select max(17) from t1 union select count(distinct a)+count(distinct 11) from t1) and t1.f=t1.a-11),11))/abs(17))=t1.f and ((t1.f)=t1.e) then t1.a+t1.d when not exists(select 1 from t1 where -b>c) or t1.a>=11 then t1.e else e end*13*t1.f | d>=19),t1.b)+t1.a FROM t1 WHERE t1.e not in (t1.f+case when f-d not between coalesce((select max(d) from t1 where (coalesce((select max(17) from t1 where not 19 in (select cast(avg(c) AS integer)-~count(distinct f- -e)+cast(avg(19) AS integer) from t1 union select cast(avg(d) AS integer) from t1)),b) not in (13,t1.c,13))),17)+ -e+t1.f and -(t1.b) then (t1.d) when t1.b in (select min(a) from t1 union select min(17) from t1) then c else 11 end,c, -13)} +} {600} +do_test randexpr-2.602 { + db eval {SELECT coalesce((select max(e) from t1 where e*~t1.b*e+c*case when +(abs(coalesce((select max(t1.b) from t1 where t1.b>=t1.a-11),11))/abs(17))=t1.f and ((t1.f)=t1.e) then t1.a+t1.d when not exists(select 1 from t1 where -b>c) or t1.a>=11 then t1.e else e end*13*t1.f | d>=19),t1.b)+t1.a FROM t1 WHERE NOT (t1.e not in (t1.f+case when f-d not between coalesce((select max(d) from t1 where (coalesce((select max(17) from t1 where not 19 in (select cast(avg(c) AS integer)-~count(distinct f- -e)+cast(avg(19) AS integer) from t1 union select cast(avg(d) AS integer) from t1)),b) not in (13,t1.c,13))),17)+ -e+t1.f and -(t1.b) then (t1.d) when t1.b in (select min(a) from t1 union select min(17) from t1) then c else 11 end,c, -13))} +} {} +do_test randexpr-2.603 { + db eval {SELECT coalesce((select max(e) from t1 where e*~t1.b*e+c*case when +(abs(coalesce((select max(t1.b) from t1 where t1.b>=t1.a-11),11))/abs(17))=t1.f and ((t1.f)=t1.e) then t1.a+t1.d when not exists(select 1 from t1 where -b>c) or t1.a>=11 then t1.e else e end*13*t1.f & d>=19),t1.b)+t1.a FROM t1 WHERE t1.e not in (t1.f+case when f-d not between coalesce((select max(d) from t1 where (coalesce((select max(17) from t1 where not 19 in (select cast(avg(c) AS integer)-~count(distinct f- -e)+cast(avg(19) AS integer) from t1 union select cast(avg(d) AS integer) from t1)),b) not in (13,t1.c,13))),17)+ -e+t1.f and -(t1.b) then (t1.d) when t1.b in (select min(a) from t1 union select min(17) from t1) then c else 11 end,c, -13)} +} {600} +do_test randexpr-2.604 { + db eval {SELECT case when exists(select 1 from t1 where f in (select cast(avg(t1.c) AS integer) from t1 union select min(t1.b) from t1)) then c+d-d when (coalesce((select a from t1 where a<(select abs(count(*)) from t1)),(select count(distinct t1.e) | abs(+ -count(distinct t1.e)*min(t1.b) | count(distinct 11)) from t1))) not in (17,(abs(t1.d)/abs(coalesce((select max(t1.f) from t1 where t1.a*t1.f>=t1.c),t1.f))),t1.e) then t1.c else t1.e end-f FROM t1 WHERE 13*~~(abs(b)/abs(coalesce((select max(t1.a) from t1 where t1.e in ( -(13-17)-b+(e | (abs(t1.e)/abs(case when ~t1.d between t1.e and c and t1.b in (select t1.c from t1 union select b from t1) then 11+t1.b when a=t1.d then b else c end)))*17,t1.c, -17)),13)))-e+b-19>19} +} {} +do_test randexpr-2.605 { + db eval {SELECT case when exists(select 1 from t1 where f in (select cast(avg(t1.c) AS integer) from t1 union select min(t1.b) from t1)) then c+d-d when (coalesce((select a from t1 where a<(select abs(count(*)) from t1)),(select count(distinct t1.e) | abs(+ -count(distinct t1.e)*min(t1.b) | count(distinct 11)) from t1))) not in (17,(abs(t1.d)/abs(coalesce((select max(t1.f) from t1 where t1.a*t1.f>=t1.c),t1.f))),t1.e) then t1.c else t1.e end-f FROM t1 WHERE NOT (13*~~(abs(b)/abs(coalesce((select max(t1.a) from t1 where t1.e in ( -(13-17)-b+(e | (abs(t1.e)/abs(case when ~t1.d between t1.e and c and t1.b in (select t1.c from t1 union select b from t1) then 11+t1.b when a=t1.d then b else c end)))*17,t1.c, -17)),13)))-e+b-19>19)} +} {-300} +do_test randexpr-2.606 { + db eval {SELECT case when exists(select 1 from t1 where f in (select cast(avg(t1.c) AS integer) from t1 union select min(t1.b) from t1)) then c+d-d when (coalesce((select a from t1 where a<(select abs(count(*)) from t1)),(select count(distinct t1.e) & abs(+ -count(distinct t1.e)*min(t1.b) & count(distinct 11)) from t1))) not in (17,(abs(t1.d)/abs(coalesce((select max(t1.f) from t1 where t1.a*t1.f>=t1.c),t1.f))),t1.e) then t1.c else t1.e end-f FROM t1 WHERE NOT (13*~~(abs(b)/abs(coalesce((select max(t1.a) from t1 where t1.e in ( -(13-17)-b+(e | (abs(t1.e)/abs(case when ~t1.d between t1.e and c and t1.b in (select t1.c from t1 union select b from t1) then 11+t1.b when a=t1.d then b else c end)))*17,t1.c, -17)),13)))-e+b-19>19)} +} {-100} +do_test randexpr-2.607 { + db eval {SELECT case when t1.f=17 then t1.d-19-11*f*t1.a*t1.b-case (select +cast(avg(a) AS integer) from t1) when 19 then 17 else a end when t1.a between case t1.c when t1.c*t1.c then (d) else t1.c end and c then e else t1.a end FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where (abs(+f-( -~(select count(distinct ~a*e | (select max(f)*count(distinct t1.f) from t1)) | -max(17)+(count(*))+max(11)+count(distinct t1.e)- - -count(distinct f) from t1)+b*b-t1.c) | t1.e)/abs(17))*c*b in (17,19,t1.e)))} +} {-131999719} +do_test randexpr-2.608 { + db eval {SELECT case when t1.f=17 then t1.d-19-11*f*t1.a*t1.b-case (select +cast(avg(a) AS integer) from t1) when 19 then 17 else a end when t1.a between case t1.c when t1.c*t1.c then (d) else t1.c end and c then e else t1.a end FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where (abs(+f-( -~(select count(distinct ~a*e | (select max(f)*count(distinct t1.f) from t1)) | -max(17)+(count(*))+max(11)+count(distinct t1.e)- - -count(distinct f) from t1)+b*b-t1.c) | t1.e)/abs(17))*c*b in (17,19,t1.e))))} +} {} +do_test randexpr-2.609 { + db eval {SELECT f-~+17*(abs(t1.f)/abs(a*case when case when (case when d>=t1.b or t1.b>=11 then t1.c when t1.b>t1.d then t1.d else t1.a end+17) not in (11,t1.e,17) then c when (t1.b>=a and b>b) then t1.d else d end in (select +abs( -max(t1.e)) from t1 union select count(*) | max(17) from t1) then (t1.a) else a end+(t1.e)))*(11)-f | t1.a-f FROM t1 WHERE ((t1.d>=t1.c))} +} {-500} +do_test randexpr-2.610 { + db eval {SELECT f-~+17*(abs(t1.f)/abs(a*case when case when (case when d>=t1.b or t1.b>=11 then t1.c when t1.b>t1.d then t1.d else t1.a end+17) not in (11,t1.e,17) then c when (t1.b>=a and b>b) then t1.d else d end in (select +abs( -max(t1.e)) from t1 union select count(*) | max(17) from t1) then (t1.a) else a end+(t1.e)))*(11)-f | t1.a-f FROM t1 WHERE NOT (((t1.d>=t1.c)))} +} {} +do_test randexpr-2.611 { + db eval {SELECT f-~+17*(abs(t1.f)/abs(a*case when case when (case when d>=t1.b or t1.b>=11 then t1.c when t1.b>t1.d then t1.d else t1.a end+17) not in (11,t1.e,17) then c when (t1.b>=a and b>b) then t1.d else d end in (select +abs( -max(t1.e)) from t1 union select count(*) & max(17) from t1) then (t1.a) else a end+(t1.e)))*(11)-f & t1.a-f FROM t1 WHERE ((t1.d>=t1.c))} +} {0} +do_test randexpr-2.612 { + db eval {SELECT e+ -((abs(f)/abs(17))) | t1.e*11-coalesce((select max(f) from t1 where ((abs(~+t1.b-coalesce((select coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where ((f) not in (11,19,t1.b)))),11* -t1.b) from t1 where -a<=c),t1.f))/abs( -b)) between t1.c and e and not exists(select 1 from t1 where f not in ( -t1.f,19,t1.e)))),case t1.c when 19 then (11) else (t1.a) end) | (13) FROM t1 WHERE d<>13 or t1.c in (select count(distinct -c*11-( -e)-t1.e)-( -case +max(t1.c)-min((select +cast(avg(19*17) AS integer) from t1)* -t1.f)+~(~count(distinct f))+count(*)-cast(avg(t1.c) AS integer) when count(distinct t1.f) then count(distinct e) else -count(*) end-count(*)) from t1 union select count(distinct 11) from t1)} +} {5597} +do_test randexpr-2.613 { + db eval {SELECT e+ -((abs(f)/abs(17))) | t1.e*11-coalesce((select max(f) from t1 where ((abs(~+t1.b-coalesce((select coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where ((f) not in (11,19,t1.b)))),11* -t1.b) from t1 where -a<=c),t1.f))/abs( -b)) between t1.c and e and not exists(select 1 from t1 where f not in ( -t1.f,19,t1.e)))),case t1.c when 19 then (11) else (t1.a) end) | (13) FROM t1 WHERE NOT (d<>13 or t1.c in (select count(distinct -c*11-( -e)-t1.e)-( -case +max(t1.c)-min((select +cast(avg(19*17) AS integer) from t1)* -t1.f)+~(~count(distinct f))+count(*)-cast(avg(t1.c) AS integer) when count(distinct t1.f) then count(distinct e) else -count(*) end-count(*)) from t1 union select count(distinct 11) from t1))} +} {} +do_test randexpr-2.614 { + db eval {SELECT e+ -((abs(f)/abs(17))) & t1.e*11-coalesce((select max(f) from t1 where ((abs(~+t1.b-coalesce((select coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where ((f) not in (11,19,t1.b)))),11* -t1.b) from t1 where -a<=c),t1.f))/abs( -b)) between t1.c and e and not exists(select 1 from t1 where f not in ( -t1.f,19,t1.e)))),case t1.c when 19 then (11) else (t1.a) end) & (13) FROM t1 WHERE d<>13 or t1.c in (select count(distinct -c*11-( -e)-t1.e)-( -case +max(t1.c)-min((select +cast(avg(19*17) AS integer) from t1)* -t1.f)+~(~count(distinct f))+count(*)-cast(avg(t1.c) AS integer) when count(distinct t1.f) then count(distinct e) else -count(*) end-count(*)) from t1 union select count(distinct 11) from t1)} +} {0} +do_test randexpr-2.615 { + db eval {SELECT coalesce((select case t1.e when t1.d then -t1.b else b | t1.f end from t1 where case e when case 11 when t1.f then 13 else c end-19 then case -(select count(distinct 19+ - -d*t1.f+d) from t1)*(abs(c)/abs(coalesce((select max(e) from t1 where not t1.c>t1.d),(17-t1.a)))) when 11 then t1.f else t1.a end else a end<>t1.c),t1.e) FROM t1 WHERE (select case count(*)* -+abs(+count(*)+min(t1.d)) | max(+(17)) when ~count(*)*(count(*))-(count(distinct t1.b)) then count(distinct 11) else max(t1.e) end from t1)>=(abs(coalesce((select t1.b from t1 where (at1.d),(17-t1.a)))) when 11 then t1.f else t1.a end else a end<>t1.c),t1.e) FROM t1 WHERE NOT ((select case count(*)* -+abs(+count(*)+min(t1.d)) | max(+(17)) when ~count(*)*(count(*))-(count(distinct t1.b)) then count(distinct 11) else max(t1.e) end from t1)>=(abs(coalesce((select t1.b from t1 where (at1.d),(17-t1.a)))) when 11 then t1.f else t1.a end else a end<>t1.c),t1.e) FROM t1 WHERE (select case count(*)* -+abs(+count(*)+min(t1.d)) | max(+(17)) when ~count(*)*(count(*))-(count(distinct t1.b)) then count(distinct 11) else max(t1.e) end from t1)>=(abs(coalesce((select t1.b from t1 where (a(t1.c) then t1.d else t1.d end FROM t1 WHERE case when 17-t1.f in (select case -~max(c-~e+19)*max(c)*count(*)+~count(distinct f)+case count(distinct d) when max(t1.b) then cast(avg(t1.d) AS integer) else count(distinct d) end-count(distinct d)*max(f)+ -count(distinct 13) when count(*) then ( -min(t1.c)) else min(( -d)) end from t1 union select -min(c) from t1) then 13 else case t1.c when t1.c then f else d end end-e-(17) in (select c from t1 union select c from t1)} +} {} +do_test randexpr-2.619 { + db eval {SELECT case when 13<11 then 19 when -(abs(f)/abs(13))*17-13 | case t1.b when ~((select (count(*)-abs(case cast(avg(19) AS integer) when count(distinct 19)*(count(*))-count(*) then count(distinct t1.d) else -count(distinct 17) end)+max(17)) from t1)) then t1.c else d end+11*t1.e*t1.a | e>(t1.c) then t1.d else t1.d end FROM t1 WHERE NOT (case when 17-t1.f in (select case -~max(c-~e+19)*max(c)*count(*)+~count(distinct f)+case count(distinct d) when max(t1.b) then cast(avg(t1.d) AS integer) else count(distinct d) end-count(distinct d)*max(f)+ -count(distinct 13) when count(*) then ( -min(t1.c)) else min(( -d)) end from t1 union select -min(c) from t1) then 13 else case t1.c when t1.c then f else d end end-e-(17) in (select c from t1 union select c from t1))} +} {400} +do_test randexpr-2.620 { + db eval {SELECT case when 13<11 then 19 when -(abs(f)/abs(13))*17-13 & case t1.b when ~((select (count(*)-abs(case cast(avg(19) AS integer) when count(distinct 19)*(count(*))-count(*) then count(distinct t1.d) else -count(distinct 17) end)+max(17)) from t1)) then t1.c else d end+11*t1.e*t1.a & e>(t1.c) then t1.d else t1.d end FROM t1 WHERE NOT (case when 17-t1.f in (select case -~max(c-~e+19)*max(c)*count(*)+~count(distinct f)+case count(distinct d) when max(t1.b) then cast(avg(t1.d) AS integer) else count(distinct d) end-count(distinct d)*max(f)+ -count(distinct 13) when count(*) then ( -min(t1.c)) else min(( -d)) end from t1 union select -min(c) from t1) then 13 else case t1.c when t1.c then f else d end end-e-(17) in (select c from t1 union select c from t1))} +} {400} +do_test randexpr-2.621 { + db eval {SELECT coalesce((select case ~(case when -f between t1.e and f then coalesce((select max(t1.a-t1.d) from t1 where d=b),case when (f*11-a-t1.d-c>t1.e and b>=19) then -+d when t1.b>= -13 then 17 else t1.f end) else (19) end) when 11 then b else f end from t1 where -t1.e<=t1.d),a) FROM t1 WHERE (+coalesce((select max((abs(19*a-t1.b+t1.a*a)/abs(19))) from t1 where not t1.f in (select case -count(*)-cast(avg(c) AS integer)+cast(avg(e) AS integer)*count(*) when min(t1.d) then -(cast(avg(t1.f) AS integer)) else max(13) end+min(t1.d)+count(*) | count(*) | min(11) | count(distinct f) from t1 union select -count(*) from t1)),e))-t1.e*d | f in (t1.d,e,e)} +} {} +do_test randexpr-2.622 { + db eval {SELECT coalesce((select case ~(case when -f between t1.e and f then coalesce((select max(t1.a-t1.d) from t1 where d=b),case when (f*11-a-t1.d-c>t1.e and b>=19) then -+d when t1.b>= -13 then 17 else t1.f end) else (19) end) when 11 then b else f end from t1 where -t1.e<=t1.d),a) FROM t1 WHERE NOT ((+coalesce((select max((abs(19*a-t1.b+t1.a*a)/abs(19))) from t1 where not t1.f in (select case -count(*)-cast(avg(c) AS integer)+cast(avg(e) AS integer)*count(*) when min(t1.d) then -(cast(avg(t1.f) AS integer)) else max(13) end+min(t1.d)+count(*) | count(*) | min(11) | count(distinct f) from t1 union select -count(*) from t1)),e))-t1.e*d | f in (t1.d,e,e))} +} {600} +do_test randexpr-2.623 { + db eval {SELECT case d*t1.f when -t1.a then t1.c+(coalesce((select max(13+case when -t1.d*13*c*d | case t1.e when t1.e then t1.b+t1.d else (abs(t1.b)/abs(case when c>b or d in (t1.e,a,d) then d else e end))+f end=t1.f then a when t1.a<=19 then 17 else d end) from t1 where (t1.f>t1.b)),(f))) else f end+t1.a FROM t1 WHERE t1.f+case d when 19 then +t1.c else 19-(abs((t1.b)*~coalesce((select f from t1 where (case when +case when t1.d>13 then t1.e else (t1.a) end<13 then f when t1.c<=e then d else t1.a end*t1.d in (select +case ~min(b) when -max(13) then cast(avg( -(11)) AS integer) else -cast(avg(17) AS integer) end+count(distinct t1.a) from t1 union select min(t1.f) from t1))),t1.a))/abs(f)) end+(a) in (b,t1.c,t1.a)} +} {} +do_test randexpr-2.624 { + db eval {SELECT case d*t1.f when -t1.a then t1.c+(coalesce((select max(13+case when -t1.d*13*c*d | case t1.e when t1.e then t1.b+t1.d else (abs(t1.b)/abs(case when c>b or d in (t1.e,a,d) then d else e end))+f end=t1.f then a when t1.a<=19 then 17 else d end) from t1 where (t1.f>t1.b)),(f))) else f end+t1.a FROM t1 WHERE NOT (t1.f+case d when 19 then +t1.c else 19-(abs((t1.b)*~coalesce((select f from t1 where (case when +case when t1.d>13 then t1.e else (t1.a) end<13 then f when t1.c<=e then d else t1.a end*t1.d in (select +case ~min(b) when -max(13) then cast(avg( -(11)) AS integer) else -cast(avg(17) AS integer) end+count(distinct t1.a) from t1 union select min(t1.f) from t1))),t1.a))/abs(f)) end+(a) in (b,t1.c,t1.a))} +} {700} +do_test randexpr-2.625 { + db eval {SELECT case d*t1.f when -t1.a then t1.c+(coalesce((select max(13+case when -t1.d*13*c*d & case t1.e when t1.e then t1.b+t1.d else (abs(t1.b)/abs(case when c>b or d in (t1.e,a,d) then d else e end))+f end=t1.f then a when t1.a<=19 then 17 else d end) from t1 where (t1.f>t1.b)),(f))) else f end+t1.a FROM t1 WHERE NOT (t1.f+case d when 19 then +t1.c else 19-(abs((t1.b)*~coalesce((select f from t1 where (case when +case when t1.d>13 then t1.e else (t1.a) end<13 then f when t1.c<=e then d else t1.a end*t1.d in (select +case ~min(b) when -max(13) then cast(avg( -(11)) AS integer) else -cast(avg(17) AS integer) end+count(distinct t1.a) from t1 union select min(t1.f) from t1))),t1.a))/abs(f)) end+(a) in (b,t1.c,t1.a))} +} {700} +do_test randexpr-2.626 { + db eval {SELECT case case when (not exists(select 1 from t1 where -e in (select t1.c from t1 union select b from t1))) then coalesce((select max(t1.d) from t1 where (17+~t1.c in (select min(t1.b) from t1 union select min(13) from t1))),t1.d)*t1.a+d when not a=a and t1.b not in (b,13,d) or d<13 or t1.f not between t1.c and f or t1.c<>c then t1.e else t1.d end when t1.c then (t1.d) else -f end FROM t1 WHERE (abs(case when (t1.e in (17,19+t1.b,t1.a)) or (t1.d-19)+(t1.d)+t1.d in (select t1.f from t1 union select t1.e from t1) and 13 in (select t1.c from t1 union select c from t1) or 11 not between e and 17 then -17-a else d end*13)/abs((b)))*d-f-13 between t1.d and (b)} +} {} +do_test randexpr-2.627 { + db eval {SELECT case case when (not exists(select 1 from t1 where -e in (select t1.c from t1 union select b from t1))) then coalesce((select max(t1.d) from t1 where (17+~t1.c in (select min(t1.b) from t1 union select min(13) from t1))),t1.d)*t1.a+d when not a=a and t1.b not in (b,13,d) or d<13 or t1.f not between t1.c and f or t1.c<>c then t1.e else t1.d end when t1.c then (t1.d) else -f end FROM t1 WHERE NOT ((abs(case when (t1.e in (17,19+t1.b,t1.a)) or (t1.d-19)+(t1.d)+t1.d in (select t1.f from t1 union select t1.e from t1) and 13 in (select t1.c from t1 union select c from t1) or 11 not between e and 17 then -17-a else d end*13)/abs((b)))*d-f-13 between t1.d and (b))} +} {-600} +do_test randexpr-2.628 { + db eval {SELECT a+a+(f)-(t1.f+d+t1.e | case when case (13) when t1.c then case coalesce((select -t1.b-t1.f-13 from t1 where t1.f between t1.d and (a)),t1.b) when b then 13 else t1.f end-f else t1.d end>=e then 19 else t1.c end*t1.c)*f-(t1.d)-b FROM t1 WHERE (t1.b)=t1.a+t1.d-13 | +~f+13 | e+t1.c+coalesce((select t1.a+e from t1 where b in (select (~max(b-t1.b-coalesce((select ((a)) from t1 where e=d or b not between b and t1.e),t1.b)))++~case case count(*) when -max(t1.c) then min(b) else min(17) end when max( -t1.a) then (min(t1.f)) else max((a)) end*cast(avg(f) AS integer)+max(19) from t1 union select count(distinct f) from t1)),(t1.e)) | t1.b} +} {} +do_test randexpr-2.629 { + db eval {SELECT a+a+(f)-(t1.f+d+t1.e | case when case (13) when t1.c then case coalesce((select -t1.b-t1.f-13 from t1 where t1.f between t1.d and (a)),t1.b) when b then 13 else t1.f end-f else t1.d end>=e then 19 else t1.c end*t1.c)*f-(t1.d)-b FROM t1 WHERE NOT ((t1.b)=t1.a+t1.d-13 | +~f+13 | e+t1.c+coalesce((select t1.a+e from t1 where b in (select (~max(b-t1.b-coalesce((select ((a)) from t1 where e=d or b not between b and t1.e),t1.b)))++~case case count(*) when -max(t1.c) then min(b) else min(17) end when max( -t1.a) then (min(t1.f)) else max((a)) end*cast(avg(f) AS integer)+max(19) from t1 union select count(distinct f) from t1)),(t1.e)) | t1.b)} +} {-54045400} +do_test randexpr-2.630 { + db eval {SELECT a+a+(f)-(t1.f+d+t1.e & case when case (13) when t1.c then case coalesce((select -t1.b-t1.f-13 from t1 where t1.f between t1.d and (a)),t1.b) when b then 13 else t1.f end-f else t1.d end>=e then 19 else t1.c end*t1.c)*f-(t1.d)-b FROM t1 WHERE NOT ((t1.b)=t1.a+t1.d-13 | +~f+13 | e+t1.c+coalesce((select t1.a+e from t1 where b in (select (~max(b-t1.b-coalesce((select ((a)) from t1 where e=d or b not between b and t1.e),t1.b)))++~case case count(*) when -max(t1.c) then min(b) else min(17) end when max( -t1.a) then (min(t1.f)) else max((a)) end*cast(avg(f) AS integer)+max(19) from t1 union select count(distinct f) from t1)),(t1.e)) | t1.b)} +} {-854200} +do_test randexpr-2.631 { + db eval {SELECT 19-e+t1.d | 19-(abs(11)/abs(t1.b-(select case cast(avg(t1.f) AS integer)-count(*)-count(distinct t1.c)-abs(count(*))-(cast(avg(case when 11b),t1.d) else ~11 end+t1.b,11,19) then t1.a else -t1.d-case d*a when t1.d then t1.e else 13 end end+e+b>19 then t1.a else t1.f end not between t1.d and e} +} {-1} +do_test randexpr-2.632 { + db eval {SELECT 19-e+t1.d | 19-(abs(11)/abs(t1.b-(select case cast(avg(t1.f) AS integer)-count(*)-count(distinct t1.c)-abs(count(*))-(cast(avg(case when 11b),t1.d) else ~11 end+t1.b,11,19) then t1.a else -t1.d-case d*a when t1.d then t1.e else 13 end end+e+b>19 then t1.a else t1.f end not between t1.d and e)} +} {} +do_test randexpr-2.633 { + db eval {SELECT 19-e+t1.d & 19-(abs(11)/abs(t1.b-(select case cast(avg(t1.f) AS integer)-count(*)-count(distinct t1.c)-abs(count(*))-(cast(avg(case when 11b),t1.d) else ~11 end+t1.b,11,19) then t1.a else -t1.d-case d*a when t1.d then t1.e else 13 end end+e+b>19 then t1.a else t1.f end not between t1.d and e} +} {-348} +do_test randexpr-2.634 { + db eval {SELECT (select abs(abs(~ -min(case t1.a-d when (abs(f)/abs(f+t1.b)) then ~e-11-+ -13*t1.a else 13 end)-count(*)*case + -count(*) when (count(distinct t1.e)) then max(t1.f) else (count(*)* - -+count(*) | min(17)) end+(cast(avg(t1.f) AS integer))+min(d))) from t1) FROM t1 WHERE not t1.f>=t1.a or not exists(select 1 from t1 where 19=17) and 13 in (select abs(count(*) | ((count(*)))) from t1 union select count(distinct -t1.c | t1.a) | abs(abs(min(d+c))) from t1)} +} {} +do_test randexpr-2.635 { + db eval {SELECT (select abs(abs(~ -min(case t1.a-d when (abs(f)/abs(f+t1.b)) then ~e-11-+ -13*t1.a else 13 end)-count(*)*case + -count(*) when (count(distinct t1.e)) then max(t1.f) else (count(*)* - -+count(*) | min(17)) end+(cast(avg(t1.f) AS integer))+min(d))) from t1) FROM t1 WHERE NOT (not t1.f>=t1.a or not exists(select 1 from t1 where 19=17) and 13 in (select abs(count(*) | ((count(*)))) from t1 union select count(distinct -t1.c | t1.a) | abs(abs(min(d+c))) from t1))} +} {995} +do_test randexpr-2.636 { + db eval {SELECT (select abs(abs(~ -min(case t1.a-d when (abs(f)/abs(f+t1.b)) then ~e-11-+ -13*t1.a else 13 end)-count(*)*case + -count(*) when (count(distinct t1.e)) then max(t1.f) else (count(*)* - -+count(*) & min(17)) end+(cast(avg(t1.f) AS integer))+min(d))) from t1) FROM t1 WHERE NOT (not t1.f>=t1.a or not exists(select 1 from t1 where 19=17) and 13 in (select abs(count(*) | ((count(*)))) from t1 union select count(distinct -t1.c | t1.a) | abs(abs(min(d+c))) from t1))} +} {1011} +do_test randexpr-2.637 { + db eval {SELECT (case when not exists(select 1 from t1 where ((not t1.f in (b,17-d,t1.a) and f=t1.a))} +} {} +do_test randexpr-2.638 { + db eval {SELECT (case when not exists(select 1 from t1 where ((not t1.f in (b,17-d,t1.a) and f=t1.a)))} +} {-12} +do_test randexpr-2.639 { + db eval {SELECT (case when not exists(select 1 from t1 where ((not t1.f in (b,17-d,t1.a) and f=t1.a)))} +} {6212} +do_test randexpr-2.640 { + db eval {SELECT coalesce((select t1.a from t1 where case when +(abs(e)/abs(19))+(abs(coalesce((select max(b) from t1 where 19 not in (f,(c),11) or -c not in (t1.f,e,d)),13)*e+t1.f)/abs((d)))<>t1.b then t1.e when t1.d not in (t1.f,17,t1.b) or t1.f not between t1.d and 13 then t1.a else t1.e end>e or not exists(select 1 from t1 where a>=e or not exists(select 1 from t1 where d<>t1.b))),f)+19 FROM t1 WHERE 13 in (case when (select +max( -t1.b+a*case when not 13*13t1.f and ~e>= -t1.b then t1.c when 11 not between t1.d and e and (dt1.b then t1.e when t1.d not in (t1.f,17,t1.b) or t1.f not between t1.d and 13 then t1.a else t1.e end>e or not exists(select 1 from t1 where a>=e or not exists(select 1 from t1 where d<>t1.b))),f)+19 FROM t1 WHERE NOT (13 in (case when (select +max( -t1.b+a*case when not 13*13t1.f and ~e>= -t1.b then t1.c when 11 not between t1.d and e and (d+(t1.e*(d))-t1.d then t1.f else 11 end,17,f)),e) | 19-13=t1.b) then (select max(11)-(count(distinct f)) from t1) else t1.a end+c in (t1.d,e,f) or e in (11,11,11)))),b)*t1.b*11))) and t1.b>=a} +} {} +do_test randexpr-2.643 { + db eval {SELECT +coalesce((select case when coalesce((select f+t1.e from t1 where b not in (case when not exists(select 1 from t1 where (f not in (t1.f-t1.b,t1.d,t1.d))) then t1.a when t1.f*t1.c*17>+(t1.e*(d))-t1.d then t1.f else 11 end,17,f)),e) | 19-13=t1.b) then (select max(11)-(count(distinct f)) from t1) else t1.a end+c in (t1.d,e,f) or e in (11,11,11)))),b)*t1.b*11))) and t1.b>=a)} +} {19} +do_test randexpr-2.644 { + db eval {SELECT +coalesce((select case when coalesce((select f+t1.e from t1 where b not in (case when not exists(select 1 from t1 where (f not in (t1.f-t1.b,t1.d,t1.d))) then t1.a when t1.f*t1.c*17>+(t1.e*(d))-t1.d then t1.f else 11 end,17,f)),e) & 19-13=t1.b) then (select max(11)-(count(distinct f)) from t1) else t1.a end+c in (t1.d,e,f) or e in (11,11,11)))),b)*t1.b*11))) and t1.b>=a)} +} {19} +do_test randexpr-2.645 { + db eval {SELECT (case when case 19 when b then 13 else t1.e end in (select (c) from t1 union select a from t1) then 11 else (d*coalesce((select t1.b from t1 where 19 | (t1.c)+case when -17>t1.a then t1.a when (19>=13) then t1.a else t1.e end=f and (e)>a or 11 in (select e from t1 union select t1.b from t1)),t1.d*t1.e))+c+a end) FROM t1 WHERE case case when case when not (abs(t1.d | f)/abs(a)) in (d,a,t1.c) then -d when (not exists(select 1 from t1 where f>=c)) then t1.a else e end+t1.d not in (t1.b,(t1.f),11) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b in (19,t1.c,13))) then b+t1.c when t1.d>=t1.a then t1.c else (c) end when (13) then t1.e else b end in (t1.a,t1.b,13)} +} {80000400} +do_test randexpr-2.646 { + db eval {SELECT (case when case 19 when b then 13 else t1.e end in (select (c) from t1 union select a from t1) then 11 else (d*coalesce((select t1.b from t1 where 19 | (t1.c)+case when -17>t1.a then t1.a when (19>=13) then t1.a else t1.e end=f and (e)>a or 11 in (select e from t1 union select t1.b from t1)),t1.d*t1.e))+c+a end) FROM t1 WHERE NOT (case case when case when not (abs(t1.d | f)/abs(a)) in (d,a,t1.c) then -d when (not exists(select 1 from t1 where f>=c)) then t1.a else e end+t1.d not in (t1.b,(t1.f),11) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b in (19,t1.c,13))) then b+t1.c when t1.d>=t1.a then t1.c else (c) end when (13) then t1.e else b end in (t1.a,t1.b,13))} +} {} +do_test randexpr-2.647 { + db eval {SELECT (case when case 19 when b then 13 else t1.e end in (select (c) from t1 union select a from t1) then 11 else (d*coalesce((select t1.b from t1 where 19 & (t1.c)+case when -17>t1.a then t1.a when (19>=13) then t1.a else t1.e end=f and (e)>a or 11 in (select e from t1 union select t1.b from t1)),t1.d*t1.e))+c+a end) FROM t1 WHERE case case when case when not (abs(t1.d | f)/abs(a)) in (d,a,t1.c) then -d when (not exists(select 1 from t1 where f>=c)) then t1.a else e end+t1.d not in (t1.b,(t1.f),11) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b in (19,t1.c,13))) then b+t1.c when t1.d>=t1.a then t1.c else (c) end when (13) then t1.e else b end in (t1.a,t1.b,13)} +} {80000400} +do_test randexpr-2.648 { + db eval {SELECT case when 19<=19 then d when not exists(select 1 from t1 where case case when case when (select -min(((t1.f)))*((cast(avg(t1.d) AS integer))) from t1) in (select t1.a-b from t1 union select 17 from t1) then f when (19 not between t1.c and 13 and f>13) then d else a end | b-t1.b in (t1.e,t1.f, -d) then t1.e when c=17) then t1.e else t1.e end FROM t1 WHERE coalesce((select +a- -t1.d*b*coalesce((select t1.c from t1 where t1.a in (select (abs(11)/abs(case when not exists(select 1 from t1 where +e=t1.e) then case t1.b when a-c then b else b end when (not exists(select 1 from t1 where 19 in (select 13 from t1 union select t1.b from t1))) and e in (t1.e, -f,e) then 19 else t1.a end)) from t1 union select b from t1)),17)*d from t1 where t1.f not in (t1.a,(t1.b),t1.d)),13)<=(13)} +} {} +do_test randexpr-2.649 { + db eval {SELECT case when 19<=19 then d when not exists(select 1 from t1 where case case when case when (select -min(((t1.f)))*((cast(avg(t1.d) AS integer))) from t1) in (select t1.a-b from t1 union select 17 from t1) then f when (19 not between t1.c and 13 and f>13) then d else a end | b-t1.b in (t1.e,t1.f, -d) then t1.e when c=17) then t1.e else t1.e end FROM t1 WHERE NOT (coalesce((select +a- -t1.d*b*coalesce((select t1.c from t1 where t1.a in (select (abs(11)/abs(case when not exists(select 1 from t1 where +e=t1.e) then case t1.b when a-c then b else b end when (not exists(select 1 from t1 where 19 in (select 13 from t1 union select t1.b from t1))) and e in (t1.e, -f,e) then 19 else t1.a end)) from t1 union select b from t1)),17)*d from t1 where t1.f not in (t1.a,(t1.b),t1.d)),13)<=(13))} +} {400} +do_test randexpr-2.650 { + db eval {SELECT case when 19<=19 then d when not exists(select 1 from t1 where case case when case when (select -min(((t1.f)))*((cast(avg(t1.d) AS integer))) from t1) in (select t1.a-b from t1 union select 17 from t1) then f when (19 not between t1.c and 13 and f>13) then d else a end & b-t1.b in (t1.e,t1.f, -d) then t1.e when c=17) then t1.e else t1.e end FROM t1 WHERE NOT (coalesce((select +a- -t1.d*b*coalesce((select t1.c from t1 where t1.a in (select (abs(11)/abs(case when not exists(select 1 from t1 where +e=t1.e) then case t1.b when a-c then b else b end when (not exists(select 1 from t1 where 19 in (select 13 from t1 union select t1.b from t1))) and e in (t1.e, -f,e) then 19 else t1.a end)) from t1 union select b from t1)),17)*d from t1 where t1.f not in (t1.a,(t1.b),t1.d)),13)<=(13))} +} {400} +do_test randexpr-2.651 { + db eval {SELECT case when c<=t1.b*e+case when not exists(select 1 from t1 where a+ -t1.f= -t1.e*(17)+f and 19 in (select -13 from t1 union select t1.f from t1) and 19>=t1.a or -11 in (select a from t1 union select 17 from t1)) then t1.f else 19 end+t1.d or ((c))<>a then t1.f-t1.c when c not between ((t1.b)) and f then a else d end FROM t1 WHERE coalesce((select t1.e from t1 where t1.c in (t1.a,f,coalesce((select max( -f) from t1 where t1.f=(abs(13)/abs(~19+(abs((select count(distinct t1.f) from t1))/abs(coalesce((select 13 from t1 where d | 17*c*a*b+d<>t1.a),b)-(b)))))),b)),19))),t1.e)*c<>t1.e} +} {300} +do_test randexpr-2.652 { + db eval {SELECT case when c<=t1.b*e+case when not exists(select 1 from t1 where a+ -t1.f= -t1.e*(17)+f and 19 in (select -13 from t1 union select t1.f from t1) and 19>=t1.a or -11 in (select a from t1 union select 17 from t1)) then t1.f else 19 end+t1.d or ((c))<>a then t1.f-t1.c when c not between ((t1.b)) and f then a else d end FROM t1 WHERE NOT (coalesce((select t1.e from t1 where t1.c in (t1.a,f,coalesce((select max( -f) from t1 where t1.f=(abs(13)/abs(~19+(abs((select count(distinct t1.f) from t1))/abs(coalesce((select 13 from t1 where d | 17*c*a*b+d<>t1.a),b)-(b)))))),b)),19))),t1.e)*c<>t1.e)} +} {} +do_test randexpr-2.653 { + db eval {SELECT case when t1.c>=13 or d in (select case ((case min(t1.f)+min(f) when max( -11) then min(19) else cast(avg( -t1.d) AS integer) end | count(*))) when count(distinct 13) then -cast(avg( -t1.e) AS integer) else min(e) end from t1 union select max( -a) from t1) then case when +c-11+(t1.d)13 then d when not exists(select 1 from t1 where t1.c in (f,t1.b,t1.b)) then a else 19 end*t1.c and t1.d>=19)} +} {600} +do_test randexpr-2.654 { + db eval {SELECT case when t1.c>=13 or d in (select case ((case min(t1.f)+min(f) when max( -11) then min(19) else cast(avg( -t1.d) AS integer) end | count(*))) when count(distinct 13) then -cast(avg( -t1.e) AS integer) else min(e) end from t1 union select max( -a) from t1) then case when +c-11+(t1.d)13 then d when not exists(select 1 from t1 where t1.c in (f,t1.b,t1.b)) then a else 19 end*t1.c and t1.d>=19))} +} {} +do_test randexpr-2.655 { + db eval {SELECT case when t1.c>=13 or d in (select case ((case min(t1.f)+min(f) when max( -11) then min(19) else cast(avg( -t1.d) AS integer) end & count(*))) when count(distinct 13) then -cast(avg( -t1.e) AS integer) else min(e) end from t1 union select max( -a) from t1) then case when +c-11+(t1.d)13 then d when not exists(select 1 from t1 where t1.c in (f,t1.b,t1.b)) then a else 19 end*t1.c and t1.d>=19)} +} {600} +do_test randexpr-2.656 { + db eval {SELECT t1.a+(e*a)*t1.d+(abs(d)/abs(case when case f when t1.a then t1.f else d end*t1.f*t1.e*c*17+coalesce((select t1.d from t1 where c<=~t1.f | 13),e)*t1.a=t1.d then t1.d when (t1.b)<>17 or t1.b<=t1.c then a else (e) end in (select min(t1.e) from t1 union select abs( -max((17))) from t1) then c when 19<>17 then 13 else -d end>t1.d))) then 17 when t1.a<=13 then coalesce((select (17) | t1.c from t1 where t1.e>d),b) else 13 end in (select min(f) from t1 union select count(*) from t1) then 19 else t1.f end)) then t1.f else f end FROM t1 WHERE coalesce((select max(11 | e+case c*t1.b+13 when 19 | ~t1.f+case when d>11 then t1.f-(case t1.d when a then 19+t1.f else t1.b end) else d-case e when c+t1.a then 13 else case when not exists(select 1 from t1 where (t1.d)<>17) then d when b in ( -f,11,17) then 11 else t1.f end end end+d then e else t1.a end) from t1 where t1.a>= -11),b)>t1.c} +} {600} +do_test randexpr-2.660 { + db eval {SELECT case f when (abs(t1.f)/abs(case when d+case when exists(select 1 from t1 where exists(select 1 from t1 where exists(select 1 from t1 where case when not case when +11>=t1.d then t1.d when (t1.b)<>17 or t1.b<=t1.c then a else (e) end in (select min(t1.e) from t1 union select abs( -max((17))) from t1) then c when 19<>17 then 13 else -d end>t1.d))) then 17 when t1.a<=13 then coalesce((select (17) | t1.c from t1 where t1.e>d),b) else 13 end in (select min(f) from t1 union select count(*) from t1) then 19 else t1.f end)) then t1.f else f end FROM t1 WHERE NOT (coalesce((select max(11 | e+case c*t1.b+13 when 19 | ~t1.f+case when d>11 then t1.f-(case t1.d when a then 19+t1.f else t1.b end) else d-case e when c+t1.a then 13 else case when not exists(select 1 from t1 where (t1.d)<>17) then d when b in ( -f,11,17) then 11 else t1.f end end end+d then e else t1.a end) from t1 where t1.a>= -11),b)>t1.c)} +} {} +do_test randexpr-2.661 { + db eval {SELECT case f when (abs(t1.f)/abs(case when d+case when exists(select 1 from t1 where exists(select 1 from t1 where exists(select 1 from t1 where case when not case when +11>=t1.d then t1.d when (t1.b)<>17 or t1.b<=t1.c then a else (e) end in (select min(t1.e) from t1 union select abs( -max((17))) from t1) then c when 19<>17 then 13 else -d end>t1.d))) then 17 when t1.a<=13 then coalesce((select (17) & t1.c from t1 where t1.e>d),b) else 13 end in (select min(f) from t1 union select count(*) from t1) then 19 else t1.f end)) then t1.f else f end FROM t1 WHERE coalesce((select max(11 | e+case c*t1.b+13 when 19 | ~t1.f+case when d>11 then t1.f-(case t1.d when a then 19+t1.f else t1.b end) else d-case e when c+t1.a then 13 else case when not exists(select 1 from t1 where (t1.d)<>17) then d when b in ( -f,11,17) then 11 else t1.f end end end+d then e else t1.a end) from t1 where t1.a>= -11),b)>t1.c} +} {600} +do_test randexpr-2.662 { + db eval {SELECT (select abs(case max(t1.b)-(min(17))* -count(distinct case when case t1.f when t1.b then case e when c then t1.c else c end else t1.b end>=t1.e then d else e end) | ~+count(distinct t1.c)-(abs( -count(*))- -max(c)) | count(distinct t1.c) when count(distinct ( -t1.c)) then count(*) else max(t1.b) end* -count(*))-cast(avg( -11) AS integer)*min(19)+max(e) from t1) FROM t1 WHERE t1.a+t1.a>13} +} {909} +do_test randexpr-2.663 { + db eval {SELECT (select abs(case max(t1.b)-(min(17))* -count(distinct case when case t1.f when t1.b then case e when c then t1.c else c end else t1.b end>=t1.e then d else e end) | ~+count(distinct t1.c)-(abs( -count(*))- -max(c)) | count(distinct t1.c) when count(distinct ( -t1.c)) then count(*) else max(t1.b) end* -count(*))-cast(avg( -11) AS integer)*min(19)+max(e) from t1) FROM t1 WHERE NOT (t1.a+t1.a>13)} +} {} +do_test randexpr-2.664 { + db eval {SELECT (select abs(case max(t1.b)-(min(17))* -count(distinct case when case t1.f when t1.b then case e when c then t1.c else c end else t1.b end>=t1.e then d else e end) & ~+count(distinct t1.c)-(abs( -count(*))- -max(c)) & count(distinct t1.c) when count(distinct ( -t1.c)) then count(*) else max(t1.b) end* -count(*))-cast(avg( -11) AS integer)*min(19)+max(e) from t1) FROM t1 WHERE t1.a+t1.a>13} +} {710} +do_test randexpr-2.665 { + db eval {SELECT (t1.d- -c+e-f++case when a between case f when case when ~~~11-coalesce((select b from t1 where coalesce((select max(e) from t1 where not t1.d>= -11),a)+a between 11 and t1.a), -d)*17-a-13 | 13>=17 then a else 11 end then t1.a else t1.d end and t1.f then 19 else t1.a end) FROM t1 WHERE t1.f<> -13} +} {700} +do_test randexpr-2.666 { + db eval {SELECT (t1.d- -c+e-f++case when a between case f when case when ~~~11-coalesce((select b from t1 where coalesce((select max(e) from t1 where not t1.d>= -11),a)+a between 11 and t1.a), -d)*17-a-13 | 13>=17 then a else 11 end then t1.a else t1.d end and t1.f then 19 else t1.a end) FROM t1 WHERE NOT (t1.f<> -13)} +} {} +do_test randexpr-2.667 { + db eval {SELECT (t1.d- -c+e-f++case when a between case f when case when ~~~11-coalesce((select b from t1 where coalesce((select max(e) from t1 where not t1.d>= -11),a)+a between 11 and t1.a), -d)*17-a-13 & 13>=17 then a else 11 end then t1.a else t1.d end and t1.f then 19 else t1.a end) FROM t1 WHERE t1.f<> -13} +} {700} +do_test randexpr-2.668 { + db eval {SELECT (abs(case when (c<=b+t1.b) then -11+t1.a-d when b*(select count(distinct e)*+max(~t1.a*case when (select count(*)*+min(t1.b)+max(t1.a) from t1) in (c,t1.d,t1.d) then (select -(count(*)) from t1) else e end) from t1)<=a-11 then 11 else t1.e end)/abs(t1.e))+c FROM t1 WHERE a<+coalesce((select t1.f from t1 where exists(select 1 from t1 where ~case when (e not between t1.a-~case d when b then -c else 13 end and d) then 11 else a end+17-f-a*19*t1.f not in (f, -t1.d,11))),c)-t1.f and (t1.d<17) and t1.f=c or f<= -e} +} {} +do_test randexpr-2.669 { + db eval {SELECT (abs(case when (c<=b+t1.b) then -11+t1.a-d when b*(select count(distinct e)*+max(~t1.a*case when (select count(*)*+min(t1.b)+max(t1.a) from t1) in (c,t1.d,t1.d) then (select -(count(*)) from t1) else e end) from t1)<=a-11 then 11 else t1.e end)/abs(t1.e))+c FROM t1 WHERE NOT (a<+coalesce((select t1.f from t1 where exists(select 1 from t1 where ~case when (e not between t1.a-~case d when b then -c else 13 end and d) then 11 else a end+17-f-a*19*t1.f not in (f, -t1.d,11))),c)-t1.f and (t1.d<17) and t1.f=c or f<= -e)} +} {300} +do_test randexpr-2.670 { + db eval {SELECT case when case when c in (select abs((max(d*case t1.b when t1.b+t1.f then d else b end+d))- - -~count(*)*cast(avg(t1.b) AS integer)-min(d)*cast(avg(b) AS integer)*count(*)) from t1 union select -count(distinct t1.f) from t1) then case when 17 between t1.f and 11 then c else d end when t1.c>=13 then a else a end<=c then t1.d else 13 end+e FROM t1 WHERE t1.f between -11 and b} +} {} +do_test randexpr-2.671 { + db eval {SELECT case when case when c in (select abs((max(d*case t1.b when t1.b+t1.f then d else b end+d))- - -~count(*)*cast(avg(t1.b) AS integer)-min(d)*cast(avg(b) AS integer)*count(*)) from t1 union select -count(distinct t1.f) from t1) then case when 17 between t1.f and 11 then c else d end when t1.c>=13 then a else a end<=c then t1.d else 13 end+e FROM t1 WHERE NOT (t1.f between -11 and b)} +} {900} +do_test randexpr-2.672 { + db eval {SELECT b*~~t1.b*(a-t1.c+t1.b)+13-+~case t1.b when d then case 17*13 when t1.e then case when case when t1.c<>~(11) then t1.e else coalesce((select max( -c) from t1 where (f<>e)),t1.f) end<=a then (t1.c) else t1.c end else -f end else 13 end*t1.e-t1.f | 13 FROM t1 WHERE b between (d) and t1.c*(abs(t1.c-13 | t1.d+t1.a)/abs(13))} +} {} +do_test randexpr-2.673 { + db eval {SELECT b*~~t1.b*(a-t1.c+t1.b)+13-+~case t1.b when d then case 17*13 when t1.e then case when case when t1.c<>~(11) then t1.e else coalesce((select max( -c) from t1 where (f<>e)),t1.f) end<=a then (t1.c) else t1.c end else -f end else 13 end*t1.e-t1.f | 13 FROM t1 WHERE NOT (b between (d) and t1.c*(abs(t1.c-13 | t1.d+t1.a)/abs(13)))} +} {6413} +do_test randexpr-2.674 { + db eval {SELECT b*~~t1.b*(a-t1.c+t1.b)+13-+~case t1.b when d then case 17*13 when t1.e then case when case when t1.c<>~(11) then t1.e else coalesce((select max( -c) from t1 where (f<>e)),t1.f) end<=a then (t1.c) else t1.c end else -f end else 13 end*t1.e-t1.f & 13 FROM t1 WHERE NOT (b between (d) and t1.c*(abs(t1.c-13 | t1.d+t1.a)/abs(13)))} +} {13} +do_test randexpr-2.675 { + db eval {SELECT case when t1.b in (select case 13 when 13 | t1.e then case +(select (min((e)))-case count(*) | max(t1.b*d+17+e) when abs(count(distinct (11))*count(*)-cast(avg(a) AS integer) | max( -t1.a)) then (count(distinct 13)) else -(cast(avg(t1.b) AS integer)) end from t1) when (select count(distinct e) from t1) then t1.e else a+(t1.b) end-d-t1.d else t1.e end from t1 union select (f) from t1) then t1.b else (b) end FROM t1 WHERE b in (select a from t1 union select 11+t1.e from t1)} +} {} +do_test randexpr-2.676 { + db eval {SELECT case when t1.b in (select case 13 when 13 | t1.e then case +(select (min((e)))-case count(*) | max(t1.b*d+17+e) when abs(count(distinct (11))*count(*)-cast(avg(a) AS integer) | max( -t1.a)) then (count(distinct 13)) else -(cast(avg(t1.b) AS integer)) end from t1) when (select count(distinct e) from t1) then t1.e else a+(t1.b) end-d-t1.d else t1.e end from t1 union select (f) from t1) then t1.b else (b) end FROM t1 WHERE NOT (b in (select a from t1 union select 11+t1.e from t1))} +} {200} +do_test randexpr-2.677 { + db eval {SELECT case when t1.b in (select case 13 when 13 & t1.e then case +(select (min((e)))-case count(*) & max(t1.b*d+17+e) when abs(count(distinct (11))*count(*)-cast(avg(a) AS integer) & max( -t1.a)) then (count(distinct 13)) else -(cast(avg(t1.b) AS integer)) end from t1) when (select count(distinct e) from t1) then t1.e else a+(t1.b) end-d-t1.d else t1.e end from t1 union select (f) from t1) then t1.b else (b) end FROM t1 WHERE NOT (b in (select a from t1 union select 11+t1.e from t1))} +} {200} +do_test randexpr-2.678 { + db eval {SELECT coalesce((select 17 from t1 where d between 17 and 13),case when t1.f in (select c+a from t1 union select a from t1) and (abs(f)/abs(t1.b))-t1.e>=case when not exists(select 1 from t1 where t1.e>(select count(distinct t1.f) from t1)) then t1.f when (11)-~t1.fe),b)) from t1 where (t1.f) in (13,e,t1.c) or t1.c>13),t1.b))/abs(13)) then t1.b else d end)/abs(13)) in (t1.f,t1.e,t1.a) or 17 between 13 and f or (f>11 and t1.f=t1.e} +} {} +do_test randexpr-2.679 { + db eval {SELECT coalesce((select 17 from t1 where d between 17 and 13),case when t1.f in (select c+a from t1 union select a from t1) and (abs(f)/abs(t1.b))-t1.e>=case when not exists(select 1 from t1 where t1.e>(select count(distinct t1.f) from t1)) then t1.f when (11)-~t1.fe),b)) from t1 where (t1.f) in (13,e,t1.c) or t1.c>13),t1.b))/abs(13)) then t1.b else d end)/abs(13)) in (t1.f,t1.e,t1.a) or 17 between 13 and f or (f>11 and t1.f=t1.e)} +} {200} +do_test randexpr-2.680 { + db eval {SELECT (select min(19-case 19 when -t1.a+13 then coalesce((select c from t1 where (abs(13)/abs(11))>=coalesce((select f+b*+t1.c from t1 where t1.c=+11+t1.e),11) or (e in (a,a,13) and t1.a=f or t1.a=t1.e),t1.f)*t1.a+t1.f)*19)) end*f-t1.f in (select d from t1 union select t1.c from t1) and b in (t1.f,t1.d,c)} +} {} +do_test randexpr-2.681 { + db eval {SELECT (select min(19-case 19 when -t1.a+13 then coalesce((select c from t1 where (abs(13)/abs(11))>=coalesce((select f+b*+t1.c from t1 where t1.c=+11+t1.e),11) or (e in (a,a,13) and t1.a=f or t1.a=t1.e),t1.f)*t1.a+t1.f)*19)) end*f-t1.f in (select d from t1 union select t1.c from t1) and b in (t1.f,t1.d,c))} +} {-165} +do_test randexpr-2.682 { + db eval {SELECT (select min(19-case 19 when -t1.a+13 then coalesce((select c from t1 where (abs(13)/abs(11))>=coalesce((select f+b*+t1.c from t1 where t1.c=+11+t1.e),11) or (e in (a,a,13) and t1.a=f or t1.a=t1.e),t1.f)*t1.a+t1.f)*19)) end*f-t1.f in (select d from t1 union select t1.c from t1) and b in (t1.f,t1.d,c))} +} {584} +do_test randexpr-2.683 { + db eval {SELECT ~case when exists(select 1 from t1 where t1.c not between case case ~t1.b*19 when b then t1.c*t1.e else t1.d end when c then case ++13 when case when a+d+~~11 not between e and -19 then 19 else b end then t1.d else 19 end else t1.a end and d) then 19 when c in (select abs(count(distinct 17)) from t1 union select max(t1.b) from t1) then (d) else t1.e end | 19 FROM t1 WHERE t1.d between 11 and ~19-coalesce((select d from t1 where (d>=c)),t1.d)*+t1.e+t1.e} +} {} +do_test randexpr-2.684 { + db eval {SELECT ~case when exists(select 1 from t1 where t1.c not between case case ~t1.b*19 when b then t1.c*t1.e else t1.d end when c then case ++13 when case when a+d+~~11 not between e and -19 then 19 else b end then t1.d else 19 end else t1.a end and d) then 19 when c in (select abs(count(distinct 17)) from t1 union select max(t1.b) from t1) then (d) else t1.e end | 19 FROM t1 WHERE NOT (t1.d between 11 and ~19-coalesce((select d from t1 where (d>=c)),t1.d)*+t1.e+t1.e)} +} {-485} +do_test randexpr-2.685 { + db eval {SELECT ~case when exists(select 1 from t1 where t1.c not between case case ~t1.b*19 when b then t1.c*t1.e else t1.d end when c then case ++13 when case when a+d+~~11 not between e and -19 then 19 else b end then t1.d else 19 end else t1.a end and d) then 19 when c in (select abs(count(distinct 17)) from t1 union select max(t1.b) from t1) then (d) else t1.e end & 19 FROM t1 WHERE NOT (t1.d between 11 and ~19-coalesce((select d from t1 where (d>=c)),t1.d)*+t1.e+t1.e)} +} {3} +do_test randexpr-2.686 { + db eval {SELECT +t1.b-17*11-coalesce((select coalesce((select max(t1.f+a-t1.c+b) from t1 where 17* -b+t1.e=13),coalesce((select +t1.f*coalesce((select b from t1 where 19 between -a and c),t1.d) from t1 where 17<>b),17)*11) from t1 where fb),17)*11) from t1 where fb),17)*11) from t1 where f=case when b not between -t1.f and c then e else f end or a<=11 or t1.e between a and 11 or t1.d not in (b,d,d) then case when f>=c then t1.c else 19 end when t1.e=a then e else t1.e end) | f)/abs(t1.a))) from t1)+e* -t1.a+f+d FROM t1 WHERE t1.b<=t1.c+ -(abs(t1.b)/abs(case t1.b+t1.e when 11 then t1.c else 17 end))*coalesce((select coalesce((select coalesce((select 13 from t1 where b=t1.b),f) | t1.f-11 from t1 where (t1.c) in (select +min(19)*(~max(b)-max(11))*max(11) from t1 union select min(f) from t1)),t1.f) from t1 where f in (select case count(distinct 19) when max(t1.b) then -cast(avg(t1.e) AS integer) else cast(avg(b) AS integer) end from t1 union select count(*) from t1)),t1.a)} +} {} +do_test randexpr-2.690 { + db eval {SELECT -d+t1.d-t1.a-+t1.c-(select +min((abs(+(case when b>=case when b not between -t1.f and c then e else f end or a<=11 or t1.e between a and 11 or t1.d not in (b,d,d) then case when f>=c then t1.c else 19 end when t1.e=a then e else t1.e end) | f)/abs(t1.a))) from t1)+e* -t1.a+f+d FROM t1 WHERE NOT (t1.b<=t1.c+ -(abs(t1.b)/abs(case t1.b+t1.e when 11 then t1.c else 17 end))*coalesce((select coalesce((select coalesce((select 13 from t1 where b=t1.b),f) | t1.f-11 from t1 where (t1.c) in (select +min(19)*(~max(b)-max(11))*max(11) from t1 union select min(f) from t1)),t1.f) from t1 where f in (select case count(distinct 19) when max(t1.b) then -cast(avg(t1.e) AS integer) else cast(avg(b) AS integer) end from t1 union select count(*) from t1)),t1.a))} +} {-49410} +do_test randexpr-2.691 { + db eval {SELECT -d+t1.d-t1.a-+t1.c-(select +min((abs(+(case when b>=case when b not between -t1.f and c then e else f end or a<=11 or t1.e between a and 11 or t1.d not in (b,d,d) then case when f>=c then t1.c else 19 end when t1.e=a then e else t1.e end) & f)/abs(t1.a))) from t1)+e* -t1.a+f+d FROM t1 WHERE NOT (t1.b<=t1.c+ -(abs(t1.b)/abs(case t1.b+t1.e when 11 then t1.c else 17 end))*coalesce((select coalesce((select coalesce((select 13 from t1 where b=t1.b),f) | t1.f-11 from t1 where (t1.c) in (select +min(19)*(~max(b)-max(11))*max(11) from t1 union select min(f) from t1)),t1.f) from t1 where f in (select case count(distinct 19) when max(t1.b) then -cast(avg(t1.e) AS integer) else cast(avg(b) AS integer) end from t1 union select count(*) from t1)),t1.a))} +} {-49400} +do_test randexpr-2.692 { + db eval {SELECT ~case +t1.a when t1.a then 19 else coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where t1.b*f<>e and e not in (17,t1.c-case when t1.e<19 then t1.c else (abs(t1.c)/abs(d*coalesce((select t1.e from t1 where exists(select 1 from t1 where t1.c in (select t1.f from t1 union select 11 from t1)) or t1.a<=t1.d),a))) end*t1.e,t1.e))),coalesce((select max(a) from t1 where (b) in ((11),e,b)),17)) end FROM t1 WHERE not (c)+c*d>t1.e and exists(select 1 from t1 where d*coalesce((select +case when ((select cast(avg((c)) AS integer)- -cast(avg(a) AS integer) from t1) in (select min(b)-count(*) from t1 union select count(distinct 19) from t1)) or not t1.b between 19 and 19 then t1.c else coalesce((select e from t1 where t1.e>=e),c) end from t1 where ( -f)19) and 17<> -t1.e and b>=a} +} {} +do_test randexpr-2.693 { + db eval {SELECT ~case +t1.a when t1.a then 19 else coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where t1.b*f<>e and e not in (17,t1.c-case when t1.e<19 then t1.c else (abs(t1.c)/abs(d*coalesce((select t1.e from t1 where exists(select 1 from t1 where t1.c in (select t1.f from t1 union select 11 from t1)) or t1.a<=t1.d),a))) end*t1.e,t1.e))),coalesce((select max(a) from t1 where (b) in ((11),e,b)),17)) end FROM t1 WHERE NOT (not (c)+c*d>t1.e and exists(select 1 from t1 where d*coalesce((select +case when ((select cast(avg((c)) AS integer)- -cast(avg(a) AS integer) from t1) in (select min(b)-count(*) from t1 union select count(distinct 19) from t1)) or not t1.b between 19 and 19 then t1.c else coalesce((select e from t1 where t1.e>=e),c) end from t1 where ( -f)19) and 17<> -t1.e and b>=a)} +} {-20} +do_test randexpr-2.694 { + db eval {SELECT coalesce((select max(t1.d-t1.e) from t1 where not exists(select 1 from t1 where c*+19<=(d)) or c+e not between a and ~f*t1.f*case when t1.e<> -coalesce((select case when ((e between t1.d and f)) then -(17) | b else t1.d end from t1 where b in (select t1.c from t1 union select 11 from t1)),d) then t1.d when e not in ( -t1.b,t1.c,(t1.e)) then t1.c else d end), -b) FROM t1 WHERE t1.d<>d} +} {} +do_test randexpr-2.695 { + db eval {SELECT coalesce((select max(t1.d-t1.e) from t1 where not exists(select 1 from t1 where c*+19<=(d)) or c+e not between a and ~f*t1.f*case when t1.e<> -coalesce((select case when ((e between t1.d and f)) then -(17) | b else t1.d end from t1 where b in (select t1.c from t1 union select 11 from t1)),d) then t1.d when e not in ( -t1.b,t1.c,(t1.e)) then t1.c else d end), -b) FROM t1 WHERE NOT (t1.d<>d)} +} {-100} +do_test randexpr-2.696 { + db eval {SELECT coalesce((select max(t1.d-t1.e) from t1 where not exists(select 1 from t1 where c*+19<=(d)) or c+e not between a and ~f*t1.f*case when t1.e<> -coalesce((select case when ((e between t1.d and f)) then -(17) & b else t1.d end from t1 where b in (select t1.c from t1 union select 11 from t1)),d) then t1.d when e not in ( -t1.b,t1.c,(t1.e)) then t1.c else d end), -b) FROM t1 WHERE NOT (t1.d<>d)} +} {-100} +do_test randexpr-2.697 { + db eval {SELECT case when a in (select max(17) from t1 union select abs(count(*)) from t1) then t1.a- -e-t1.d | e- -t1.f*19+(select -abs(max(a))*count(distinct e)*max(19) from t1)-11-13-d*11+t1.a else d end-b FROM t1 WHERE t1.e in (select (abs(case when (abs(f)/abs((select ~min(a) from t1)+coalesce((select t1.f from t1 where 11<>t1.b),19)))*t1.e+ -t1.d | e<=t1.f then -e when (b)>t1.a then t1.d else t1.a end)/abs(11)) from t1 union select 13 from t1) and f not between t1.b and e or not exists(select 1 from t1 where not exists(select 1 from t1 where 19t1.b),19)))*t1.e+ -t1.d | e<=t1.f then -e when (b)>t1.a then t1.d else t1.a end)/abs(11)) from t1 union select 13 from t1) and f not between t1.b and e or not exists(select 1 from t1 where not exists(select 1 from t1 where 19t1.b),19)))*t1.e+ -t1.d | e<=t1.f then -e when (b)>t1.a then t1.d else t1.a end)/abs(11)) from t1 union select 13 from t1) and f not between t1.b and e or not exists(select 1 from t1 where not exists(select 1 from t1 where 19t1.d),c) then 19 else 17 end between t1.b and t1.f and t1.d not in (c,e,(17)))),11) FROM t1 WHERE (((select min(t1.f) from t1)<=e))} +} {} +do_test randexpr-2.701 { + db eval {SELECT coalesce((select f from t1 where (case t1.a*t1.b*c when t1.d*coalesce((select max(coalesce((select 19 from t1 where t1.b in (select max(~case -e when c+coalesce((select max(e) from t1 where (t1.d) not between c and t1.f),17) then c else 13 end) from t1 union select count(distinct a) from t1)),t1.f)) from t1 where f>t1.d),c) then 19 else 17 end between t1.b and t1.f and t1.d not in (c,e,(17)))),11) FROM t1 WHERE NOT ((((select min(t1.f) from t1)<=e)))} +} {11} +do_test randexpr-2.702 { + db eval {SELECT case t1.a when e*t1.e then case when exists(select 1 from t1 where (coalesce((select max(17) from t1 where (not (case when not a>=13*c then t1.f else (11)*t1.b end between 11 and t1.f or t1.c>(t1.c)))),t1.b*~t1.c)*b*d>=13)) then (abs(17)/abs(e)) else b end else t1.f end | t1.c+t1.f FROM t1 WHERE coalesce((select max(11) from t1 where c-d not between ~case when (select +~count(distinct t1.f)*cast(avg(t1.e) AS integer) from t1)+19 not in (t1.e,t1.f,t1.a) then t1.a when a in (e,t1.d,d) then t1.b else t1.e end and t1.b and c>=e or (t1.d<>b) and not exists(select 1 from t1 where (t1.f between 13 and a))),t1.a)-e<=t1.e} +} {988} +do_test randexpr-2.703 { + db eval {SELECT case t1.a when e*t1.e then case when exists(select 1 from t1 where (coalesce((select max(17) from t1 where (not (case when not a>=13*c then t1.f else (11)*t1.b end between 11 and t1.f or t1.c>(t1.c)))),t1.b*~t1.c)*b*d>=13)) then (abs(17)/abs(e)) else b end else t1.f end | t1.c+t1.f FROM t1 WHERE NOT (coalesce((select max(11) from t1 where c-d not between ~case when (select +~count(distinct t1.f)*cast(avg(t1.e) AS integer) from t1)+19 not in (t1.e,t1.f,t1.a) then t1.a when a in (e,t1.d,d) then t1.b else t1.e end and t1.b and c>=e or (t1.d<>b) and not exists(select 1 from t1 where (t1.f between 13 and a))),t1.a)-e<=t1.e)} +} {} +do_test randexpr-2.704 { + db eval {SELECT case t1.a when e*t1.e then case when exists(select 1 from t1 where (coalesce((select max(17) from t1 where (not (case when not a>=13*c then t1.f else (11)*t1.b end between 11 and t1.f or t1.c>(t1.c)))),t1.b*~t1.c)*b*d>=13)) then (abs(17)/abs(e)) else b end else t1.f end & t1.c+t1.f FROM t1 WHERE coalesce((select max(11) from t1 where c-d not between ~case when (select +~count(distinct t1.f)*cast(avg(t1.e) AS integer) from t1)+19 not in (t1.e,t1.f,t1.a) then t1.a when a in (e,t1.d,d) then t1.b else t1.e end and t1.b and c>=e or (t1.d<>b) and not exists(select 1 from t1 where (t1.f between 13 and a))),t1.a)-e<=t1.e} +} {512} +do_test randexpr-2.705 { + db eval {SELECT coalesce((select max(t1.e+(t1.b)) from t1 where 17<=t1.d-(select ~+cast(avg(b) AS integer) | case -case cast(avg(t1.e) AS integer) when min((abs((a))/abs(t1.e))) then cast(avg(t1.c) AS integer)+count(*) else min(d) end when max(t1.e) then count(*) else ( -count(*)) end-min(t1.b)-count(distinct -a)*count(*) from t1) | c+coalesce((select f from t1 where (19=t1.c-t1.b)),t1.f+17)),f) FROM t1 WHERE c not between (abs(t1.f)/abs(case when t1.f+e<=t1.c+t1.d then case when d in (select +count(distinct case when -t1.a*19-t1.c not between 11 and c then t1.e when (19<>19) then t1.d else d end) from t1 union select cast(avg(e) AS integer) from t1) then t1.e when c in (select count(*) from t1 union select cast(avg(f) AS integer)* - - -cast(avg(t1.e) AS integer) from t1) then b else (t1.b) end when not (11>=11) then -t1.e else b end)) and t1.f} +} {} +do_test randexpr-2.706 { + db eval {SELECT coalesce((select max(t1.e+(t1.b)) from t1 where 17<=t1.d-(select ~+cast(avg(b) AS integer) | case -case cast(avg(t1.e) AS integer) when min((abs((a))/abs(t1.e))) then cast(avg(t1.c) AS integer)+count(*) else min(d) end when max(t1.e) then count(*) else ( -count(*)) end-min(t1.b)-count(distinct -a)*count(*) from t1) | c+coalesce((select f from t1 where (19=t1.c-t1.b)),t1.f+17)),f) FROM t1 WHERE NOT (c not between (abs(t1.f)/abs(case when t1.f+e<=t1.c+t1.d then case when d in (select +count(distinct case when -t1.a*19-t1.c not between 11 and c then t1.e when (19<>19) then t1.d else d end) from t1 union select cast(avg(e) AS integer) from t1) then t1.e when c in (select count(*) from t1 union select cast(avg(f) AS integer)* - - -cast(avg(t1.e) AS integer) from t1) then b else (t1.b) end when not (11>=11) then -t1.e else b end)) and t1.f)} +} {700} +do_test randexpr-2.707 { + db eval {SELECT coalesce((select max(t1.e+(t1.b)) from t1 where 17<=t1.d-(select ~+cast(avg(b) AS integer) & case -case cast(avg(t1.e) AS integer) when min((abs((a))/abs(t1.e))) then cast(avg(t1.c) AS integer)+count(*) else min(d) end when max(t1.e) then count(*) else ( -count(*)) end-min(t1.b)-count(distinct -a)*count(*) from t1) & c+coalesce((select f from t1 where (19=t1.c-t1.b)),t1.f+17)),f) FROM t1 WHERE NOT (c not between (abs(t1.f)/abs(case when t1.f+e<=t1.c+t1.d then case when d in (select +count(distinct case when -t1.a*19-t1.c not between 11 and c then t1.e when (19<>19) then t1.d else d end) from t1 union select cast(avg(e) AS integer) from t1) then t1.e when c in (select count(*) from t1 union select cast(avg(f) AS integer)* - - -cast(avg(t1.e) AS integer) from t1) then b else (t1.b) end when not (11>=11) then -t1.e else b end)) and t1.f)} +} {700} +do_test randexpr-2.708 { + db eval {SELECT 17-(abs(case when t1.e<+(select count(distinct -f) from t1)+t1.b then +case when t1.b not in (coalesce((select max(coalesce((select case when 17=a and 13 not in (b,t1.f,d)),b),t1.d, -13) then (e) else (13) end-19 when not exists(select 1 from t1 where 19<>f) then c else t1.e end | t1.d)/abs((13)))*f FROM t1 WHERE coalesce((select f from t1 where coalesce((select ~d*19-d*~case c when case a when t1.e*19 then (select - -( -max(t1.f))*cast(avg(t1.c) AS integer) from t1) else 13 end*13-11 then -11 else t1.f end | t1.e | t1.f*19 from t1 where t1.f>t1.a),b)*b not in (17,17,t1.e)),t1.a)-b*d>=11} +} {} +do_test randexpr-2.709 { + db eval {SELECT 17-(abs(case when t1.e<+(select count(distinct -f) from t1)+t1.b then +case when t1.b not in (coalesce((select max(coalesce((select case when 17=a and 13 not in (b,t1.f,d)),b),t1.d, -13) then (e) else (13) end-19 when not exists(select 1 from t1 where 19<>f) then c else t1.e end | t1.d)/abs((13)))*f FROM t1 WHERE NOT (coalesce((select f from t1 where coalesce((select ~d*19-d*~case c when case a when t1.e*19 then (select - -( -max(t1.f))*cast(avg(t1.c) AS integer) from t1) else 13 end*13-11 then -11 else t1.f end | t1.e | t1.f*19 from t1 where t1.f>t1.a),b)*b not in (17,17,t1.e)),t1.a)-b*d>=11)} +} {-22783} +do_test randexpr-2.710 { + db eval {SELECT 17-(abs(case when t1.e<+(select count(distinct -f) from t1)+t1.b then +case when t1.b not in (coalesce((select max(coalesce((select case when 17=a and 13 not in (b,t1.f,d)),b),t1.d, -13) then (e) else (13) end-19 when not exists(select 1 from t1 where 19<>f) then c else t1.e end & t1.d)/abs((13)))*f FROM t1 WHERE NOT (coalesce((select f from t1 where coalesce((select ~d*19-d*~case c when case a when t1.e*19 then (select - -( -max(t1.f))*cast(avg(t1.c) AS integer) from t1) else 13 end*13-11 then -11 else t1.f end | t1.e | t1.f*19 from t1 where t1.f>t1.a),b)*b not in (17,17,t1.e)),t1.a)-b*d>=11)} +} {-17983} +do_test randexpr-2.711 { + db eval {SELECT (select cast(avg(case when (e=case when e>d and case coalesce((select ((t1.b)) from t1 where 17<=t1.c),a) when t1.b then f else d end*b>t1.d then (t1.a) else 11 end or 17 not in (19,f,d) or not not exists(select 1 from t1 where - -e>=13)) and 17 in ( -t1.b,c,t1.f) then t1.c when t1.c not between t1.f and 17 then t1.c else d end) AS integer) from t1)+b+a FROM t1 WHERE (((coalesce((select coalesce((select max(19) from t1 where d between ~t1.a and 11),c+d-coalesce((select e from t1 where (abs(b)/abs(coalesce((select 13 from t1 where case when (17) not in (19,t1.c,t1.b) or 17 not in (t1.b,t1.f,t1.e) then 11 else 19 end<>t1.c),11)*17))=t1.b),d)) from t1 where d not in (b,b,d)),t1.a) not between b and b) and d>=t1.d) and t1.d in (13,c,t1.b))} +} {} +do_test randexpr-2.712 { + db eval {SELECT (select cast(avg(case when (e=case when e>d and case coalesce((select ((t1.b)) from t1 where 17<=t1.c),a) when t1.b then f else d end*b>t1.d then (t1.a) else 11 end or 17 not in (19,f,d) or not not exists(select 1 from t1 where - -e>=13)) and 17 in ( -t1.b,c,t1.f) then t1.c when t1.c not between t1.f and 17 then t1.c else d end) AS integer) from t1)+b+a FROM t1 WHERE NOT ((((coalesce((select coalesce((select max(19) from t1 where d between ~t1.a and 11),c+d-coalesce((select e from t1 where (abs(b)/abs(coalesce((select 13 from t1 where case when (17) not in (19,t1.c,t1.b) or 17 not in (t1.b,t1.f,t1.e) then 11 else 19 end<>t1.c),11)*17))=t1.b),d)) from t1 where d not in (b,b,d)),t1.a) not between b and b) and d>=t1.d) and t1.d in (13,c,t1.b)))} +} {600} +do_test randexpr-2.713 { + db eval {SELECT (abs((select +abs(+max(b) | abs(~~count(distinct -19))) from t1))/abs(coalesce((select max(19*11*d) from t1 where (t1.e<=t1.e)),t1.f)))+case e when (t1.e) then d else c*13 | 11 end FROM t1 WHERE t1.d>=(case when (select count(*) from t1)*t1.c*t1.e+e<>t1.e*13 | f+(select (min(13+t1.b) | ~+~count(*)) from t1)*e*coalesce((select max(19+t1.a) from t1 where t1.e in (select +(count(distinct b))+count(*) from t1 union select ( -min(17)) from t1)),t1.a)-t1.d* -t1.e then e else -a end)} +} {} +do_test randexpr-2.714 { + db eval {SELECT (abs((select +abs(+max(b) | abs(~~count(distinct -19))) from t1))/abs(coalesce((select max(19*11*d) from t1 where (t1.e<=t1.e)),t1.f)))+case e when (t1.e) then d else c*13 | 11 end FROM t1 WHERE NOT (t1.d>=(case when (select count(*) from t1)*t1.c*t1.e+e<>t1.e*13 | f+(select (min(13+t1.b) | ~+~count(*)) from t1)*e*coalesce((select max(19+t1.a) from t1 where t1.e in (select +(count(distinct b))+count(*) from t1 union select ( -min(17)) from t1)),t1.a)-t1.d* -t1.e then e else -a end))} +} {400} +do_test randexpr-2.715 { + db eval {SELECT (abs((select +abs(+max(b) & abs(~~count(distinct -19))) from t1))/abs(coalesce((select max(19*11*d) from t1 where (t1.e<=t1.e)),t1.f)))+case e when (t1.e) then d else c*13 & 11 end FROM t1 WHERE NOT (t1.d>=(case when (select count(*) from t1)*t1.c*t1.e+e<>t1.e*13 | f+(select (min(13+t1.b) | ~+~count(*)) from t1)*e*coalesce((select max(19+t1.a) from t1 where t1.e in (select +(count(distinct b))+count(*) from t1 union select ( -min(17)) from t1)),t1.a)-t1.d* -t1.e then e else -a end))} +} {400} +do_test randexpr-2.716 { + db eval {SELECT -17+c-(abs(t1.a)/abs(t1.c))-case when t1.a<>c then case when exists(select 1 from t1 where 11 not between + -d and d and 13 not between 13 and 17 or not -f<=19 or (t1.a)(11)) and 11=t1.f then b else a end from t1 where t1.e in (e,t1.c,b)),11) end else -17 end FROM t1 WHERE not exists(select 1 from t1 where t1.a>=coalesce((select t1.f from t1 where + -19*t1.c<~+t1.a*13),a))} +} {-217} +do_test randexpr-2.717 { + db eval {SELECT -17+c-(abs(t1.a)/abs(t1.c))-case when t1.a<>c then case when exists(select 1 from t1 where 11 not between + -d and d and 13 not between 13 and 17 or not -f<=19 or (t1.a)(11)) and 11=t1.f then b else a end from t1 where t1.e in (e,t1.c,b)),11) end else -17 end FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a>=coalesce((select t1.f from t1 where + -19*t1.c<~+t1.a*13),a)))} +} {} +do_test randexpr-2.718 { + db eval {SELECT f*19+17*(select max(b)+count(*)- -~count(*)-min(case when (e<=b-t1.b) then case when t1.b>t1.a or f not in (c, -c,f) or f in (e,13,13) then t1.b else t1.b end else a end*a) from t1)+t1.f*(abs(case b | t1.c+t1.a when ((f)) then f else c end+b)/abs(17))-(c) FROM t1 WHERE t1.e>11} +} {-138117} +do_test randexpr-2.719 { + db eval {SELECT f*19+17*(select max(b)+count(*)- -~count(*)-min(case when (e<=b-t1.b) then case when t1.b>t1.a or f not in (c, -c,f) or f in (e,13,13) then t1.b else t1.b end else a end*a) from t1)+t1.f*(abs(case b | t1.c+t1.a when ((f)) then f else c end+b)/abs(17))-(c) FROM t1 WHERE NOT (t1.e>11)} +} {} +do_test randexpr-2.720 { + db eval {SELECT f*19+17*(select max(b)+count(*)- -~count(*)-min(case when (e<=b-t1.b) then case when t1.b>t1.a or f not in (c, -c,f) or f in (e,13,13) then t1.b else t1.b end else a end*a) from t1)+t1.f*(abs(case b & t1.c+t1.a when ((f)) then f else c end+b)/abs(17))-(c) FROM t1 WHERE t1.e>11} +} {-138117} +do_test randexpr-2.721 { + db eval {SELECT -case when case when (case (abs(13)/abs(t1.e-13*t1.f)) when b- -13+t1.d then 11 else a end) not between t1.b and b then t1.c when d not between t1.e and t1.c or t1.f in (select 11 from t1 union select f from t1) and 17=d then 13 else t1.a end+11>=f then a when f>b then t1.d else 17 end-t1.e FROM t1 WHERE (case when not exists(select 1 from t1 where exists(select 1 from t1 where (abs(b*d-t1.e)/abs(t1.b))>c)) and t1.d in (13,t1.f,17) then e else ( - -t1.a)+11+c end*t1.b in (select (case -+min(17) when +count(*) | min(t1.a) | cast(avg(11) AS integer) then cast(avg(11) AS integer) else cast(avg(a) AS integer) end)-cast(avg(t1.a) AS integer) from t1 union select (min(t1.e)) from t1) or not t1.c in ((f),t1.c,(t1.e)))} +} {} +do_test randexpr-2.722 { + db eval {SELECT -case when case when (case (abs(13)/abs(t1.e-13*t1.f)) when b- -13+t1.d then 11 else a end) not between t1.b and b then t1.c when d not between t1.e and t1.c or t1.f in (select 11 from t1 union select f from t1) and 17=d then 13 else t1.a end+11>=f then a when f>b then t1.d else 17 end-t1.e FROM t1 WHERE NOT ((case when not exists(select 1 from t1 where exists(select 1 from t1 where (abs(b*d-t1.e)/abs(t1.b))>c)) and t1.d in (13,t1.f,17) then e else ( - -t1.a)+11+c end*t1.b in (select (case -+min(17) when +count(*) | min(t1.a) | cast(avg(11) AS integer) then cast(avg(11) AS integer) else cast(avg(a) AS integer) end)-cast(avg(t1.a) AS integer) from t1 union select (min(t1.e)) from t1) or not t1.c in ((f),t1.c,(t1.e))))} +} {-900} +do_test randexpr-2.723 { + db eval {SELECT case t1.a when a then t1.c else -case coalesce((select t1.e from t1 where (abs(case when not (a*case when f>=f*13-19 then t1.e else +t1.a end=t1.a) then (select min(a)+min(+19) from t1) else case when t1.a=(f) then c else c end+17 end)/abs(t1.e)) between 17 and 13),e) when 17 then 13 else t1.d end end FROM t1 WHERE 17 in (select case cast(avg(b+b) AS integer) when abs(abs(count(*))) then min(case t1.c+t1.b+t1.e+17+case case when t1.b<>17 and t1.e>=t1.b then b else -t1.f end when 11 then 13 else f end*t1.f*b when 19 then -11 else t1.d end- -t1.f) else min(t1.c) end from t1 union select abs(abs(count(distinct b)*max(t1.d))+count(distinct 13)-count(*)) from t1)} +} {} +do_test randexpr-2.724 { + db eval {SELECT case t1.a when a then t1.c else -case coalesce((select t1.e from t1 where (abs(case when not (a*case when f>=f*13-19 then t1.e else +t1.a end=t1.a) then (select min(a)+min(+19) from t1) else case when t1.a=(f) then c else c end+17 end)/abs(t1.e)) between 17 and 13),e) when 17 then 13 else t1.d end end FROM t1 WHERE NOT (17 in (select case cast(avg(b+b) AS integer) when abs(abs(count(*))) then min(case t1.c+t1.b+t1.e+17+case case when t1.b<>17 and t1.e>=t1.b then b else -t1.f end when 11 then 13 else f end*t1.f*b when 19 then -11 else t1.d end- -t1.f) else min(t1.c) end from t1 union select abs(abs(count(distinct b)*max(t1.d))+count(distinct 13)-count(*)) from t1))} +} {300} +do_test randexpr-2.725 { + db eval {SELECT case when coalesce((select e from t1 where coalesce((select coalesce((select max( -coalesce((select max(case when exists(select 1 from t1 where not exists(select 1 from t1 where b in (select e+d from t1 union select t1.e from t1))) then t1.d else t1.f end) from t1 where exists(select 1 from t1 where f not in ((c),a,11))),e)) from t1 where t1.b=t1.f and et1.b),t1.b) from t1 where t1.a in (select a from t1 union select -f from t1)),17)>=17),((b))) not in (t1.e,b,e) then 19 when not -a<=f then t1.f else t1.b end FROM t1 WHERE 13=t1.d} +} {} +do_test randexpr-2.726 { + db eval {SELECT case when coalesce((select e from t1 where coalesce((select coalesce((select max( -coalesce((select max(case when exists(select 1 from t1 where not exists(select 1 from t1 where b in (select e+d from t1 union select t1.e from t1))) then t1.d else t1.f end) from t1 where exists(select 1 from t1 where f not in ((c),a,11))),e)) from t1 where t1.b=t1.f and et1.b),t1.b) from t1 where t1.a in (select a from t1 union select -f from t1)),17)>=17),((b))) not in (t1.e,b,e) then 19 when not -a<=f then t1.f else t1.b end FROM t1 WHERE NOT (13=t1.d)} +} {200} +do_test randexpr-2.727 { + db eval {SELECT 19*13+((abs(case when 17*d in ((abs((case (abs((abs((select abs(min(d))+cast(avg(19) AS integer) from t1) | t1.d | 11 | b)/abs(19)))/abs(b)) when 11 then a else e end))/abs(13)),t1.f,b) then t1.b when t1.c>=t1.d then (t1.c) else c end*d)/abs(f))) | t1.a-a-17 FROM t1 WHERE ( -t1.d+coalesce((select max(11) from t1 where t1.c between 13 and t1.d and case d when b then 13+ -~t1.a else +case when coalesce((select max((select +case (cast(avg(e) AS integer)) when count(distinct t1.a) then count(*) else min(( -d)) end from t1)-+a+d) from t1 where (e in (17,t1.e, -a))),b)<>f then a else 11 end end<(t1.e)),t1.d) in (select t1.a from t1 union select b from t1))} +} {} +do_test randexpr-2.728 { + db eval {SELECT 19*13+((abs(case when 17*d in ((abs((case (abs((abs((select abs(min(d))+cast(avg(19) AS integer) from t1) | t1.d | 11 | b)/abs(19)))/abs(b)) when 11 then a else e end))/abs(13)),t1.f,b) then t1.b when t1.c>=t1.d then (t1.c) else c end*d)/abs(f))) | t1.a-a-17 FROM t1 WHERE NOT (( -t1.d+coalesce((select max(11) from t1 where t1.c between 13 and t1.d and case d when b then 13+ -~t1.a else +case when coalesce((select max((select +case (cast(avg(e) AS integer)) when count(distinct t1.a) then count(*) else min(( -d)) end from t1)-+a+d) from t1 where (e in (17,t1.e, -a))),b)<>f then a else 11 end end<(t1.e)),t1.d) in (select t1.a from t1 union select b from t1)))} +} {-1} +do_test randexpr-2.729 { + db eval {SELECT 19*13+((abs(case when 17*d in ((abs((case (abs((abs((select abs(min(d))+cast(avg(19) AS integer) from t1) & t1.d & 11 & b)/abs(19)))/abs(b)) when 11 then a else e end))/abs(13)),t1.f,b) then t1.b when t1.c>=t1.d then (t1.c) else c end*d)/abs(f))) & t1.a-a-17 FROM t1 WHERE NOT (( -t1.d+coalesce((select max(11) from t1 where t1.c between 13 and t1.d and case d when b then 13+ -~t1.a else +case when coalesce((select max((select +case (cast(avg(e) AS integer)) when count(distinct t1.a) then count(*) else min(( -d)) end from t1)-+a+d) from t1 where (e in (17,t1.e, -a))),b)<>f then a else 11 end end<(t1.e)),t1.d) in (select t1.a from t1 union select b from t1)))} +} {431} +do_test randexpr-2.730 { + db eval {SELECT case when (19*b)+11*~f-coalesce((select max(11) from t1 where f<>case when case 17 when 11 then 17 else c end-11 in (t1.c,c,t1.e) and 19=t1.a or 17<=e or e<=19 then 19 | c when t1.b=t1.f then d else 19 end or t1.e not in (13,19,c)),b) | -c not between -e and -a then (t1.c) else t1.d end FROM t1 WHERE c in (select case abs((count(*))) when -max(t1.c) | abs(abs(+count(*)))-~case (case -max(e) when max(11)- -count(*) then ((max(t1.e))) else count(*) end) when count(distinct t1.e) then cast(avg(f) AS integer) else cast(avg(t1.c) AS integer) end* -cast(avg(f) AS integer) then max(f) else (max(b)) end from t1 union select (max(13)) from t1) and not exists(select 1 from t1 where case when t1.e<=19-b then c else c end in (select c from t1 union select (select -((count(distinct t1.d))) from t1)-t1.b from t1))} +} {} +do_test randexpr-2.731 { + db eval {SELECT case when (19*b)+11*~f-coalesce((select max(11) from t1 where f<>case when case 17 when 11 then 17 else c end-11 in (t1.c,c,t1.e) and 19=t1.a or 17<=e or e<=19 then 19 | c when t1.b=t1.f then d else 19 end or t1.e not in (13,19,c)),b) | -c not between -e and -a then (t1.c) else t1.d end FROM t1 WHERE NOT (c in (select case abs((count(*))) when -max(t1.c) | abs(abs(+count(*)))-~case (case -max(e) when max(11)- -count(*) then ((max(t1.e))) else count(*) end) when count(distinct t1.e) then cast(avg(f) AS integer) else cast(avg(t1.c) AS integer) end* -cast(avg(f) AS integer) then max(f) else (max(b)) end from t1 union select (max(13)) from t1) and not exists(select 1 from t1 where case when t1.e<=19-b then c else c end in (select c from t1 union select (select -((count(distinct t1.d))) from t1)-t1.b from t1)))} +} {400} +do_test randexpr-2.732 { + db eval {SELECT case when (19*b)+11*~f-coalesce((select max(11) from t1 where f<>case when case 17 when 11 then 17 else c end-11 in (t1.c,c,t1.e) and 19=t1.a or 17<=e or e<=19 then 19 & c when t1.b=t1.f then d else 19 end or t1.e not in (13,19,c)),b) & -c not between -e and -a then (t1.c) else t1.d end FROM t1 WHERE NOT (c in (select case abs((count(*))) when -max(t1.c) | abs(abs(+count(*)))-~case (case -max(e) when max(11)- -count(*) then ((max(t1.e))) else count(*) end) when count(distinct t1.e) then cast(avg(f) AS integer) else cast(avg(t1.c) AS integer) end* -cast(avg(f) AS integer) then max(f) else (max(b)) end from t1 union select (max(13)) from t1) and not exists(select 1 from t1 where case when t1.e<=19-b then c else c end in (select c from t1 union select (select -((count(distinct t1.d))) from t1)-t1.b from t1)))} +} {300} +do_test randexpr-2.733 { + db eval {SELECT case when t1.e not between e and 13 then (select count(*) from t1) when f>=case when c in (select a from t1 union select t1.e+coalesce((select 11 from t1 where (select count(distinct t1.b) from t1)+17 not in (b,t1.c,t1.f-(select ~count(distinct 17) from t1)+ -e)),13) from t1) or 19 between d and t1.f then (select min(19) from t1) when not (e not between c and a) then d else a end then d else (t1.c) end FROM t1 WHERE f not in (17,f+d | f+case when -f=19 then (select max((select +abs(abs(max(((select ((max(t1.d))+count(distinct t1.e))-min(t1.a) from t1))+t1.e)-abs(count(distinct -t1.b)-count(distinct 11)))*min(a)-count(*))-min(t1.a) from t1)) from t1) else t1.f end,c-a) and c<>11} +} {1} +do_test randexpr-2.734 { + db eval {SELECT case when t1.e not between e and 13 then (select count(*) from t1) when f>=case when c in (select a from t1 union select t1.e+coalesce((select 11 from t1 where (select count(distinct t1.b) from t1)+17 not in (b,t1.c,t1.f-(select ~count(distinct 17) from t1)+ -e)),13) from t1) or 19 between d and t1.f then (select min(19) from t1) when not (e not between c and a) then d else a end then d else (t1.c) end FROM t1 WHERE NOT (f not in (17,f+d | f+case when -f=19 then (select max((select +abs(abs(max(((select ((max(t1.d))+count(distinct t1.e))-min(t1.a) from t1))+t1.e)-abs(count(distinct -t1.b)-count(distinct 11)))*min(a)-count(*))-min(t1.a) from t1)) from t1) else t1.f end,c-a) and c<>11)} +} {} +do_test randexpr-2.735 { + db eval {SELECT case c-+case when t1.f in (t1.a,t1.e,19) then t1.b else case when a<>t1.a then case ~(t1.d) when t1.e then (select max(t1.f) from t1)-(select +(cast(avg(b) AS integer))*cast(avg(t1.a) AS integer)+max(d)*count(*)+count(*) from t1)* -t1.f else 13 end else t1.a+a end*t1.f-t1.b*(e) end when d then d else 17 end FROM t1 WHERE case when not exists(select 1 from t1 where not exists(select 1 from t1 where c in (select t1.a*t1.b from t1 union select t1.d | e from t1))) and (coalesce((select (abs(11)/abs(13-17*c)) from t1 where b in (select 13 from t1 union select (t1.c) from t1)),11) not in (17,b,b)) then (abs(+t1.f)/abs(c)) when exists(select 1 from t1 where not exists(select 1 from t1 where not (not exists(select 1 from t1 where e<=19 and e>19)))) then c else t1.e end not between t1.f and c} +} {17} +do_test randexpr-2.736 { + db eval {SELECT case c-+case when t1.f in (t1.a,t1.e,19) then t1.b else case when a<>t1.a then case ~(t1.d) when t1.e then (select max(t1.f) from t1)-(select +(cast(avg(b) AS integer))*cast(avg(t1.a) AS integer)+max(d)*count(*)+count(*) from t1)* -t1.f else 13 end else t1.a+a end*t1.f-t1.b*(e) end when d then d else 17 end FROM t1 WHERE NOT (case when not exists(select 1 from t1 where not exists(select 1 from t1 where c in (select t1.a*t1.b from t1 union select t1.d | e from t1))) and (coalesce((select (abs(11)/abs(13-17*c)) from t1 where b in (select 13 from t1 union select (t1.c) from t1)),11) not in (17,b,b)) then (abs(+t1.f)/abs(c)) when exists(select 1 from t1 where not exists(select 1 from t1 where not (not exists(select 1 from t1 where e<=19 and e>19)))) then c else t1.e end not between t1.f and c)} +} {} +do_test randexpr-2.737 { + db eval {SELECT 11+a+(select count(distinct coalesce((select -coalesce((select case when (t1.a<=a) then (case when 17=t1.c then (select count(distinct e)-min(11) from t1) else f end) when f>=t1.f and t1.c not in (t1.e,a,17) and 17=t1.f then -t1.d else 11 end*t1.d from t1 where t1.a<=t1.b),t1.b) from t1 where t1.e not between d and 13),t1.a)) | +max(t1.c) from t1) FROM t1 WHERE 11 in (t1.a,+t1.c* -t1.f | t1.d*+t1.c-b-(abs((select min(case when 19 in (select abs(count(distinct c)) from t1 union select ~ -min(t1.c) from t1) then case (11) when a then t1.c else t1.d end when (f)<=t1.b then t1.b else t1.a end)+min((t1.d)) | min(b) from t1))/abs(t1.e))+case 13 when t1.b then b else - -t1.b end*b-11, -f)} +} {} +do_test randexpr-2.738 { + db eval {SELECT 11+a+(select count(distinct coalesce((select -coalesce((select case when (t1.a<=a) then (case when 17=t1.c then (select count(distinct e)-min(11) from t1) else f end) when f>=t1.f and t1.c not in (t1.e,a,17) and 17=t1.f then -t1.d else 11 end*t1.d from t1 where t1.a<=t1.b),t1.b) from t1 where t1.e not between d and 13),t1.a)) | +max(t1.c) from t1) FROM t1 WHERE NOT (11 in (t1.a,+t1.c* -t1.f | t1.d*+t1.c-b-(abs((select min(case when 19 in (select abs(count(distinct c)) from t1 union select ~ -min(t1.c) from t1) then case (11) when a then t1.c else t1.d end when (f)<=t1.b then t1.b else t1.a end)+min((t1.d)) | min(b) from t1))/abs(t1.e))+case 13 when t1.b then b else - -t1.b end*b-11, -f))} +} {412} +do_test randexpr-2.739 { + db eval {SELECT 11+a+(select count(distinct coalesce((select -coalesce((select case when (t1.a<=a) then (case when 17=t1.c then (select count(distinct e)-min(11) from t1) else f end) when f>=t1.f and t1.c not in (t1.e,a,17) and 17=t1.f then -t1.d else 11 end*t1.d from t1 where t1.a<=t1.b),t1.b) from t1 where t1.e not between d and 13),t1.a)) & +max(t1.c) from t1) FROM t1 WHERE NOT (11 in (t1.a,+t1.c* -t1.f | t1.d*+t1.c-b-(abs((select min(case when 19 in (select abs(count(distinct c)) from t1 union select ~ -min(t1.c) from t1) then case (11) when a then t1.c else t1.d end when (f)<=t1.b then t1.b else t1.a end)+min((t1.d)) | min(b) from t1))/abs(t1.e))+case 13 when t1.b then b else - -t1.b end*b-11, -f))} +} {111} +do_test randexpr-2.740 { + db eval {SELECT -c-case 11 when ++e*(select cast(avg( -t1.f+case when case when 19=t1.e+((select min(17 | a) from t1)) then t1.f else t1.b end>=t1.e then t1.e when (((exists(select 1 from t1 where b in (select case -count(*) when (count(distinct d)) then count(*) else (cast(avg(t1.b) AS integer)) end from t1 union select -count(*) from t1))))) then t1.a else a end+t1.a*d) AS integer) from t1) then 13 else f end*e FROM t1 WHERE (select cast(avg(case when +d>=e+17 and (not case when 13>=(select case -count(distinct t1.e) when cast(avg(c) AS integer) then cast(avg(19) AS integer) else count(distinct t1.a) end from t1) then t1.e else t1.f end in (select t1.b from t1 union select 13 from t1)) or t1.a<=e and e in (select count(*) from t1 union select -count(*) from t1) and b>=t1.b or t1.e between c and 19 then c when f between 19 and b then coalesce((select max(t1.d) from t1 where a<>t1.b),13)* -(d) else t1.e end) AS integer) from t1)<=19} +} {} +do_test randexpr-2.741 { + db eval {SELECT -c-case 11 when ++e*(select cast(avg( -t1.f+case when case when 19=t1.e+((select min(17 | a) from t1)) then t1.f else t1.b end>=t1.e then t1.e when (((exists(select 1 from t1 where b in (select case -count(*) when (count(distinct d)) then count(*) else (cast(avg(t1.b) AS integer)) end from t1 union select -count(*) from t1))))) then t1.a else a end+t1.a*d) AS integer) from t1) then 13 else f end*e FROM t1 WHERE NOT ((select cast(avg(case when +d>=e+17 and (not case when 13>=(select case -count(distinct t1.e) when cast(avg(c) AS integer) then cast(avg(19) AS integer) else count(distinct t1.a) end from t1) then t1.e else t1.f end in (select t1.b from t1 union select 13 from t1)) or t1.a<=e and e in (select count(*) from t1 union select -count(*) from t1) and b>=t1.b or t1.e between c and 19 then c when f between 19 and b then coalesce((select max(t1.d) from t1 where a<>t1.b),13)* -(d) else t1.e end) AS integer) from t1)<=19)} +} {-300300} +do_test randexpr-2.742 { + db eval {SELECT -c-case 11 when ++e*(select cast(avg( -t1.f+case when case when 19=t1.e+((select min(17 & a) from t1)) then t1.f else t1.b end>=t1.e then t1.e when (((exists(select 1 from t1 where b in (select case -count(*) when (count(distinct d)) then count(*) else (cast(avg(t1.b) AS integer)) end from t1 union select -count(*) from t1))))) then t1.a else a end+t1.a*d) AS integer) from t1) then 13 else f end*e FROM t1 WHERE NOT ((select cast(avg(case when +d>=e+17 and (not case when 13>=(select case -count(distinct t1.e) when cast(avg(c) AS integer) then cast(avg(19) AS integer) else count(distinct t1.a) end from t1) then t1.e else t1.f end in (select t1.b from t1 union select 13 from t1)) or t1.a<=e and e in (select count(*) from t1 union select -count(*) from t1) and b>=t1.b or t1.e between c and 19 then c when f between 19 and b then coalesce((select max(t1.d) from t1 where a<>t1.b),13)* -(d) else t1.e end) AS integer) from t1)<=19)} +} {-300300} +do_test randexpr-2.743 { + db eval {SELECT case d when 11 then t1.d-(abs(t1.d)/abs(19))+coalesce((select d*d from t1 where (select cast(avg(case when f | c+case when e in (select min(coalesce((select t1.f from t1 where 11 not between t1.b and 19),t1.f)) from t1 union select (max(t1.b)) from t1) then 19 when t1.b=b or t1.c>=c then 13 else e end*19 in (select 17 from t1 union select 11 from t1) then -c else t1.d end) AS integer) from t1)<13),d) else 11 end FROM t1 WHERE (b>~t1.c-+(abs(case when 11>(c) and t1.a>13 then t1.d else (b) end)/abs(t1.d))-13 or t1.f between t1.a and 19 and 11 in (select (min(t1.e))-~( -+count(*)) from t1 union select count(distinct t1.c) from t1)) and 17 not in (f,(t1.b),t1.c) and (t1.f<>t1.e) or d in (f,t1.a,t1.d) or (d)<=t1.e} +} {11} +do_test randexpr-2.744 { + db eval {SELECT case d when 11 then t1.d-(abs(t1.d)/abs(19))+coalesce((select d*d from t1 where (select cast(avg(case when f | c+case when e in (select min(coalesce((select t1.f from t1 where 11 not between t1.b and 19),t1.f)) from t1 union select (max(t1.b)) from t1) then 19 when t1.b=b or t1.c>=c then 13 else e end*19 in (select 17 from t1 union select 11 from t1) then -c else t1.d end) AS integer) from t1)<13),d) else 11 end FROM t1 WHERE NOT ((b>~t1.c-+(abs(case when 11>(c) and t1.a>13 then t1.d else (b) end)/abs(t1.d))-13 or t1.f between t1.a and 19 and 11 in (select (min(t1.e))-~( -+count(*)) from t1 union select count(distinct t1.c) from t1)) and 17 not in (f,(t1.b),t1.c) and (t1.f<>t1.e) or d in (f,t1.a,t1.d) or (d)<=t1.e)} +} {} +do_test randexpr-2.745 { + db eval {SELECT case d when 11 then t1.d-(abs(t1.d)/abs(19))+coalesce((select d*d from t1 where (select cast(avg(case when f & c+case when e in (select min(coalesce((select t1.f from t1 where 11 not between t1.b and 19),t1.f)) from t1 union select (max(t1.b)) from t1) then 19 when t1.b=b or t1.c>=c then 13 else e end*19 in (select 17 from t1 union select 11 from t1) then -c else t1.d end) AS integer) from t1)<13),d) else 11 end FROM t1 WHERE (b>~t1.c-+(abs(case when 11>(c) and t1.a>13 then t1.d else (b) end)/abs(t1.d))-13 or t1.f between t1.a and 19 and 11 in (select (min(t1.e))-~( -+count(*)) from t1 union select count(distinct t1.c) from t1)) and 17 not in (f,(t1.b),t1.c) and (t1.f<>t1.e) or d in (f,t1.a,t1.d) or (d)<=t1.e} +} {11} +do_test randexpr-2.746 { + db eval {SELECT (select -~count(distinct ~+case when c<>coalesce((select max(case when ~13 in (t1.a,t1.f,13+t1.d+(19)*t1.d*f-e) then 13 else a end) from t1 where -t1.d<>19),(a))*d+a then t1.d when exists(select 1 from t1 where b=d) then t1.f else 17 end*11) | count(*)-max(t1.e) from t1) FROM t1 WHERE 19 in (select max(b) from t1 union select count(*) from t1) and +t1.b+c*d+coalesce((select max(17) from t1 where case when t1.a=coalesce((select max((select (min(t1.f)) from t1)) from t1 where not case when not exists(select 1 from t1 where ( -t1.b)=13 and d in (f,c,e)) or 17 between 17 and e then t1.e-t1.c else 11 end>=d),19)-11 then 11 else 17 end<=t1.a),t1.f)+t1.f-f<>17} +} {} +do_test randexpr-2.747 { + db eval {SELECT (select -~count(distinct ~+case when c<>coalesce((select max(case when ~13 in (t1.a,t1.f,13+t1.d+(19)*t1.d*f-e) then 13 else a end) from t1 where -t1.d<>19),(a))*d+a then t1.d when exists(select 1 from t1 where b=d) then t1.f else 17 end*11) | count(*)-max(t1.e) from t1) FROM t1 WHERE NOT (19 in (select max(b) from t1 union select count(*) from t1) and +t1.b+c*d+coalesce((select max(17) from t1 where case when t1.a=coalesce((select max((select (min(t1.f)) from t1)) from t1 where not case when not exists(select 1 from t1 where ( -t1.b)=13 and d in (f,c,e)) or 17 between 17 and e then t1.e-t1.c else 11 end>=d),19)-11 then 11 else 17 end<=t1.a),t1.f)+t1.f-f<>17)} +} {-497} +do_test randexpr-2.748 { + db eval {SELECT (select -~count(distinct ~+case when c<>coalesce((select max(case when ~13 in (t1.a,t1.f,13+t1.d+(19)*t1.d*f-e) then 13 else a end) from t1 where -t1.d<>19),(a))*d+a then t1.d when exists(select 1 from t1 where b=d) then t1.f else 17 end*11) & count(*)-max(t1.e) from t1) FROM t1 WHERE NOT (19 in (select max(b) from t1 union select count(*) from t1) and +t1.b+c*d+coalesce((select max(17) from t1 where case when t1.a=coalesce((select max((select (min(t1.f)) from t1)) from t1 where not case when not exists(select 1 from t1 where ( -t1.b)=13 and d in (f,c,e)) or 17 between 17 and e then t1.e-t1.c else 11 end>=d),19)-11 then 11 else 17 end<=t1.a),t1.f)+t1.f-f<>17)} +} {0} +do_test randexpr-2.749 { + db eval {SELECT coalesce((select max(a) from t1 where exists(select 1 from t1 where (abs(t1.f)/abs(case when (t1.a+case when exists(select 1 from t1 where t1.e>=(abs(coalesce((select f from t1 where (((b>=t1.d) or t1.e= -a) or 17=a)),case when t1.d between t1.a and b then t1.b when e in (e,t1.a,t1.e) then 13 else (f) end))/abs(13))) then 11 else t1.d end* - -t1.f)<=c then d else t1.d end))-t1.c-19>=t1.a)),((t1.b))) FROM t1 WHERE case when t1.f in (e,19,(abs(t1.e)/abs(t1.e))) and (17 between 11+(select +max(case case when f=(t1.b) then e when t1.e in (13,19,c) then c else -t1.b end- -c when (13) then d else t1.f end) from t1) and 17 and (19 in (b,t1.d,11))) and f not between 19 and b then e when 13 not between (t1.e) and t1.a then 11 else 11 end not between d and t1.a} +} {200} +do_test randexpr-2.750 { + db eval {SELECT coalesce((select max(a) from t1 where exists(select 1 from t1 where (abs(t1.f)/abs(case when (t1.a+case when exists(select 1 from t1 where t1.e>=(abs(coalesce((select f from t1 where (((b>=t1.d) or t1.e= -a) or 17=a)),case when t1.d between t1.a and b then t1.b when e in (e,t1.a,t1.e) then 13 else (f) end))/abs(13))) then 11 else t1.d end* - -t1.f)<=c then d else t1.d end))-t1.c-19>=t1.a)),((t1.b))) FROM t1 WHERE NOT (case when t1.f in (e,19,(abs(t1.e)/abs(t1.e))) and (17 between 11+(select +max(case case when f=(t1.b) then e when t1.e in (13,19,c) then c else -t1.b end- -c when (13) then d else t1.f end) from t1) and 17 and (19 in (b,t1.d,11))) and f not between 19 and b then e when 13 not between (t1.e) and t1.a then 11 else 11 end not between d and t1.a)} +} {} +do_test randexpr-2.751 { + db eval {SELECT 11-17 | case when 11=c or 11 in (select cast(avg(t1.c) AS integer)-case cast(avg(t1.b) AS integer) when count(distinct e) then min(t1.a) else -count(distinct 19) end from t1 union select count(*) from t1) or e in (t1.e,t1.b,b) or 13=t1.f and e>=t1.a then e else e end when ( -19<=e) then 13 else e end+a FROM t1 WHERE t1.c*d not in ( -t1.a,coalesce((select d from t1 where coalesce((select c from t1 where ((d<=11))),(17)+(abs(coalesce((select (select ( -+count(*))+count(distinct d) from t1) from t1 where (coalesce((select b from t1 where ~a<>13),(t1.c))) not between d and t1.d),17))/abs(d)))*f17),e),t1.b)} +} {-1} +do_test randexpr-2.752 { + db eval {SELECT 11-17 | case when 11=c or 11 in (select cast(avg(t1.c) AS integer)-case cast(avg(t1.b) AS integer) when count(distinct e) then min(t1.a) else -count(distinct 19) end from t1 union select count(*) from t1) or e in (t1.e,t1.b,b) or 13=t1.f and e>=t1.a then e else e end when ( -19<=e) then 13 else e end+a FROM t1 WHERE NOT (t1.c*d not in ( -t1.a,coalesce((select d from t1 where coalesce((select c from t1 where ((d<=11))),(17)+(abs(coalesce((select (select ( -+count(*))+count(distinct d) from t1) from t1 where (coalesce((select b from t1 where ~a<>13),(t1.c))) not between d and t1.d),17))/abs(d)))*f17),e),t1.b))} +} {} +do_test randexpr-2.753 { + db eval {SELECT 11-17 & case when 11=c or 11 in (select cast(avg(t1.c) AS integer)-case cast(avg(t1.b) AS integer) when count(distinct e) then min(t1.a) else -count(distinct 19) end from t1 union select count(*) from t1) or e in (t1.e,t1.b,b) or 13=t1.f and e>=t1.a then e else e end when ( -19<=e) then 13 else e end+a FROM t1 WHERE t1.c*d not in ( -t1.a,coalesce((select d from t1 where coalesce((select c from t1 where ((d<=11))),(17)+(abs(coalesce((select (select ( -+count(*))+count(distinct d) from t1) from t1 where (coalesce((select b from t1 where ~a<>13),(t1.c))) not between d and t1.d),17))/abs(d)))*f17),e),t1.b)} +} {112} +do_test randexpr-2.754 { + db eval {SELECT (abs(f-case when +(t1.f)-c13 and -ft1.c then 11 else -11 end<>t1.c and t1.f not between (11) and (t1.f) then b else 11 end)*b+t1.f,a,t1.d)) then 11 else t1.d end=e) or e<(t1.f)} +} {99} +do_test randexpr-2.755 { + db eval {SELECT (abs(f-case when +(t1.f)-c13 and -ft1.c then 11 else -11 end<>t1.c and t1.f not between (11) and (t1.f) then b else 11 end)*b+t1.f,a,t1.d)) then 11 else t1.d end=e) or e<(t1.f))} +} {} +do_test randexpr-2.756 { + db eval {SELECT (abs(f-case when +(t1.f)-c13 and -ft1.c then 11 else -11 end<>t1.c and t1.f not between (11) and (t1.f) then b else 11 end)*b+t1.f,a,t1.d)) then 11 else t1.d end=e) or e<(t1.f)} +} {99} +do_test randexpr-2.757 { + db eval {SELECT +(select (max(case when not (((exists(select 1 from t1 where b not between t1.a and t1.d) or t1.a>=coalesce((select max(17) from t1 where -t1.e between t1.e and a),f)-11) or 11<=t1.c)) then b when 19 between 19 and b then t1.f else +d+ -t1.a-t1.f-e end | f-t1.b+ -t1.b)+min(t1.b)) from t1)*t1.c FROM t1 WHERE b in (t1.b-b,coalesce((select max(e) from t1 where t1.d not between 11 and case when d>=+13 then case when t1.a between e and a then t1.c else (t1.f)+(t1.b) end else case (d)*e when b then f else a end end or t1.d in (select cast(avg(d) AS integer) from t1 union select +abs( -max(e))*max(19) | max(d) from t1)),11),t1.c)} +} {} +do_test randexpr-2.758 { + db eval {SELECT +(select (max(case when not (((exists(select 1 from t1 where b not between t1.a and t1.d) or t1.a>=coalesce((select max(17) from t1 where -t1.e between t1.e and a),f)-11) or 11<=t1.c)) then b when 19 between 19 and b then t1.f else +d+ -t1.a-t1.f-e end | f-t1.b+ -t1.b)+min(t1.b)) from t1)*t1.c FROM t1 WHERE NOT (b in (t1.b-b,coalesce((select max(e) from t1 where t1.d not between 11 and case when d>=+13 then case when t1.a between e and a then t1.c else (t1.f)+(t1.b) end else case (d)*e when b then f else a end end or t1.d in (select cast(avg(d) AS integer) from t1 union select +abs( -max(e))*max(19) | max(d) from t1)),11),t1.c))} +} {278400} +do_test randexpr-2.759 { + db eval {SELECT +(select (max(case when not (((exists(select 1 from t1 where b not between t1.a and t1.d) or t1.a>=coalesce((select max(17) from t1 where -t1.e between t1.e and a),f)-11) or 11<=t1.c)) then b when 19 between 19 and b then t1.f else +d+ -t1.a-t1.f-e end & f-t1.b+ -t1.b)+min(t1.b)) from t1)*t1.c FROM t1 WHERE NOT (b in (t1.b-b,coalesce((select max(e) from t1 where t1.d not between 11 and case when d>=+13 then case when t1.a between e and a then t1.c else (t1.f)+(t1.b) end else case (d)*e when b then f else a end end or t1.d in (select cast(avg(d) AS integer) from t1 union select +abs( -max(e))*max(19) | max(d) from t1)),11),t1.c))} +} {81600} +do_test randexpr-2.760 { + db eval {SELECT t1.e*t1.c*(select count(*)+abs(cast(avg(case t1.a when (select -count(*)-(min(t1.a)) | +(abs(case max(a) when abs(min(17)) then +cast(avg(a) AS integer) | count(distinct d) else count(*) end)) from t1) then a else -+b-coalesce((select max(f*19) from t1 where ~~c in (a,13,t1.a)),t1.b) end) AS integer)) from t1) FROM t1 WHERE 19-(abs(b)/abs(t1.b)) | case when t1.e in (select case (+cast(avg(t1.c+a) AS integer) | (cast(avg(t1.d) AS integer) | -cast(avg( -d) AS integer)* -( -count(*))+min(17))) when min(13) then max( -11) else count(*) end from t1 union select min(17) from t1) or 13 in (case when t1.e between e and coalesce((select c from t1 where not exists(select 1 from t1 where (b)>=t1.e)),t1.b) then 19 else 11 end,17,f) then 11 else b end in (select c from t1 union select 19 from t1)} +} {} +do_test randexpr-2.761 { + db eval {SELECT t1.e*t1.c*(select count(*)+abs(cast(avg(case t1.a when (select -count(*)-(min(t1.a)) | +(abs(case max(a) when abs(min(17)) then +cast(avg(a) AS integer) | count(distinct d) else count(*) end)) from t1) then a else -+b-coalesce((select max(f*19) from t1 where ~~c in (a,13,t1.a)),t1.b) end) AS integer)) from t1) FROM t1 WHERE NOT (19-(abs(b)/abs(t1.b)) | case when t1.e in (select case (+cast(avg(t1.c+a) AS integer) | (cast(avg(t1.d) AS integer) | -cast(avg( -d) AS integer)* -( -count(*))+min(17))) when min(13) then max( -11) else count(*) end from t1 union select min(17) from t1) or 13 in (case when t1.e between e and coalesce((select c from t1 where not exists(select 1 from t1 where (b)>=t1.e)),t1.b) then 19 else 11 end,17,f) then 11 else b end in (select c from t1 union select 19 from t1))} +} {60150000} +do_test randexpr-2.762 { + db eval {SELECT t1.e*t1.c*(select count(*)+abs(cast(avg(case t1.a when (select -count(*)-(min(t1.a)) & +(abs(case max(a) when abs(min(17)) then +cast(avg(a) AS integer) & count(distinct d) else count(*) end)) from t1) then a else -+b-coalesce((select max(f*19) from t1 where ~~c in (a,13,t1.a)),t1.b) end) AS integer)) from t1) FROM t1 WHERE NOT (19-(abs(b)/abs(t1.b)) | case when t1.e in (select case (+cast(avg(t1.c+a) AS integer) | (cast(avg(t1.d) AS integer) | -cast(avg( -d) AS integer)* -( -count(*))+min(17))) when min(13) then max( -11) else count(*) end from t1 union select min(17) from t1) or 13 in (case when t1.e between e and coalesce((select c from t1 where not exists(select 1 from t1 where (b)>=t1.e)),t1.b) then 19 else 11 end,17,f) then 11 else b end in (select c from t1 union select 19 from t1))} +} {60150000} +do_test randexpr-2.763 { + db eval {SELECT t1.b+case when e+(select abs(abs(min(d+case 11 when t1.d+19 | b | case when e<=b+coalesce((select 11 from t1 where 11<>13),17)-17 then t1.d else d end+19 then 11 else d end))) from t1)- -d-(t1.e) in (select 17 from t1 union select 11 from t1) then t1.e when exists(select 1 from t1 where e>t1.c) then t1.b else 13 end FROM t1 WHERE e in (select count(*) from t1 union select min(case when (select abs(cast(avg(+17) AS integer)) from t1) not between t1.e and 17+t1.f then f when ((case when ((select cast(avg(t1.d) AS integer) from t1)=17) then 19 else t1.f end)<>t1.c or t1.a in (select -+abs(cast(avg(t1.b) AS integer)) from t1 union select +((cast(avg(11) AS integer)))+ -min(b) from t1)) or not exists(select 1 from t1 where ((t1.d in (b,a,17)) and f<=t1.a)) and t1.f<> - -t1.a then d else - -t1.d end) from t1)} +} {} +do_test randexpr-2.764 { + db eval {SELECT t1.b+case when e+(select abs(abs(min(d+case 11 when t1.d+19 | b | case when e<=b+coalesce((select 11 from t1 where 11<>13),17)-17 then t1.d else d end+19 then 11 else d end))) from t1)- -d-(t1.e) in (select 17 from t1 union select 11 from t1) then t1.e when exists(select 1 from t1 where e>t1.c) then t1.b else 13 end FROM t1 WHERE NOT (e in (select count(*) from t1 union select min(case when (select abs(cast(avg(+17) AS integer)) from t1) not between t1.e and 17+t1.f then f when ((case when ((select cast(avg(t1.d) AS integer) from t1)=17) then 19 else t1.f end)<>t1.c or t1.a in (select -+abs(cast(avg(t1.b) AS integer)) from t1 union select +((cast(avg(11) AS integer)))+ -min(b) from t1)) or not exists(select 1 from t1 where ((t1.d in (b,a,17)) and f<=t1.a)) and t1.f<> - -t1.a then d else - -t1.d end) from t1))} +} {400} +do_test randexpr-2.765 { + db eval {SELECT t1.b+case when e+(select abs(abs(min(d+case 11 when t1.d+19 & b & case when e<=b+coalesce((select 11 from t1 where 11<>13),17)-17 then t1.d else d end+19 then 11 else d end))) from t1)- -d-(t1.e) in (select 17 from t1 union select 11 from t1) then t1.e when exists(select 1 from t1 where e>t1.c) then t1.b else 13 end FROM t1 WHERE NOT (e in (select count(*) from t1 union select min(case when (select abs(cast(avg(+17) AS integer)) from t1) not between t1.e and 17+t1.f then f when ((case when ((select cast(avg(t1.d) AS integer) from t1)=17) then 19 else t1.f end)<>t1.c or t1.a in (select -+abs(cast(avg(t1.b) AS integer)) from t1 union select +((cast(avg(11) AS integer)))+ -min(b) from t1)) or not exists(select 1 from t1 where ((t1.d in (b,a,17)) and f<=t1.a)) and t1.f<> - -t1.a then d else - -t1.d end) from t1))} +} {400} +do_test randexpr-2.766 { + db eval {SELECT (select cast(avg( -coalesce((select max(+(abs(t1.d)/abs(~d))*+c*t1.c) from t1 where e in (select coalesce((select f from t1 where t1.f<> -11),17)+c*19 from t1 union select f from t1)),t1.c)) AS integer)-~case ~count(distinct 17)*count(distinct 19) when count(distinct t1.c)*count(*)-count(distinct 19) then +(max(a)+case - - - -min(t1.f) when max(c) then count(distinct (f)) else min(13) end) else ( -cast(avg( -t1.b) AS integer)) end from t1) FROM t1 WHERE exists(select 1 from t1 where (abs(e*coalesce((select (abs(b*(t1.b)+f)/abs(d)) from t1 where t1.c in (select min(a | t1.b) from t1 union select abs(case -case ~ -~cast(avg(e) AS integer) when ++min(17)+( -cast(avg(a) AS integer))-max(t1.c) then cast(avg(t1.b) AS integer) else cast(avg(f) AS integer) end when - -max((t1.d)) then -min(t1.b) else cast(avg(t1.c) AS integer) end) from t1)),b))/abs(t1.d)) in (select min(t1.c)-cast(avg( -e) AS integer)- -cast(avg(t1.f) AS integer) from t1 union select (max((19))) from t1))} +} {} +do_test randexpr-2.767 { + db eval {SELECT (select cast(avg( -coalesce((select max(+(abs(t1.d)/abs(~d))*+c*t1.c) from t1 where e in (select coalesce((select f from t1 where t1.f<> -11),17)+c*19 from t1 union select f from t1)),t1.c)) AS integer)-~case ~count(distinct 17)*count(distinct 19) when count(distinct t1.c)*count(*)-count(distinct 19) then +(max(a)+case - - - -min(t1.f) when max(c) then count(distinct (f)) else min(13) end) else ( -cast(avg( -t1.b) AS integer)) end from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where (abs(e*coalesce((select (abs(b*(t1.b)+f)/abs(d)) from t1 where t1.c in (select min(a | t1.b) from t1 union select abs(case -case ~ -~cast(avg(e) AS integer) when ++min(17)+( -cast(avg(a) AS integer))-max(t1.c) then cast(avg(t1.b) AS integer) else cast(avg(f) AS integer) end when - -max((t1.d)) then -min(t1.b) else cast(avg(t1.c) AS integer) end) from t1)),b))/abs(t1.d)) in (select min(t1.c)-cast(avg( -e) AS integer)- -cast(avg(t1.f) AS integer) from t1 union select (max((19))) from t1)))} +} {-99} +do_test randexpr-2.768 { + db eval {SELECT t1.a+11*coalesce((select max( -t1.e-coalesce((select max((abs(t1.c)/abs((13*e+t1.c)-t1.f))) from t1 where exists(select 1 from t1 where d<>a) or ~(select case abs(count(distinct f)) when (count(*)) then count(*) else min(t1.f) end from t1)+coalesce((select f from t1 where d in (select min(t1.d) from t1 union select count(*) from t1)),c) in (11,t1.a,t1.b)),11)- -11) from t1 where 13<11),t1.b) FROM t1 WHERE not ++coalesce((select t1.f from t1 where not exists(select 1 from t1 where ((select min(b) from t1)<>case t1.d when coalesce((select max(case e-t1.c when 19-t1.c+f+(t1.c*coalesce((select max(17) from t1 where 17 between 11 and t1.a),t1.d)+b) then -17 else d end-a) from t1 where t1.d>11),b) then 11 else c end))),b | t1.d)*17 not between t1.e and 17} +} {} +do_test randexpr-2.769 { + db eval {SELECT t1.a+11*coalesce((select max( -t1.e-coalesce((select max((abs(t1.c)/abs((13*e+t1.c)-t1.f))) from t1 where exists(select 1 from t1 where d<>a) or ~(select case abs(count(distinct f)) when (count(*)) then count(*) else min(t1.f) end from t1)+coalesce((select f from t1 where d in (select min(t1.d) from t1 union select count(*) from t1)),c) in (11,t1.a,t1.b)),11)- -11) from t1 where 13<11),t1.b) FROM t1 WHERE NOT (not ++coalesce((select t1.f from t1 where not exists(select 1 from t1 where ((select min(b) from t1)<>case t1.d when coalesce((select max(case e-t1.c when 19-t1.c+f+(t1.c*coalesce((select max(17) from t1 where 17 between 11 and t1.a),t1.d)+b) then -17 else d end-a) from t1 where t1.d>11),b) then 11 else c end))),b | t1.d)*17 not between t1.e and 17)} +} {2300} +do_test randexpr-2.770 { + db eval {SELECT coalesce((select max(coalesce((select ((abs(coalesce((select max((select ~(count(distinct e-11)-cast(avg(t1.a) AS integer) | count(*)) from t1)) from t1 where t1.fb or t1.c in (select c from t1 union select 19 from t1)),e | b))/abs(t1.f))) from t1 where e in (select -(b) from t1 union select 13 from t1)),t1.a)) from t1 where f<>11),t1.e) FROM t1 WHERE -11 in (a,case when exists(select 1 from t1 where 11 in (select 13 from t1 union select t1.d from t1)) and exists(select 1 from t1 where exists(select 1 from t1 where (t1.a) not between t1.c and t1.c)) then ~case when ~t1.f not between +t1.b-11 and e or not b in (c,17,e) and (not exists(select 1 from t1 where b in (( -t1.e), -t1.c,t1.c))) or 17 not in (t1.e,t1.c,t1.f) then c when 19= - -11 then t1.b else t1.c end when (13) between t1.f and ( -t1.e) then t1.d else -t1.d end*c,d)} +} {} +do_test randexpr-2.771 { + db eval {SELECT coalesce((select max(coalesce((select ((abs(coalesce((select max((select ~(count(distinct e-11)-cast(avg(t1.a) AS integer) | count(*)) from t1)) from t1 where t1.fb or t1.c in (select c from t1 union select 19 from t1)),e | b))/abs(t1.f))) from t1 where e in (select -(b) from t1 union select 13 from t1)),t1.a)) from t1 where f<>11),t1.e) FROM t1 WHERE NOT ( -11 in (a,case when exists(select 1 from t1 where 11 in (select 13 from t1 union select t1.d from t1)) and exists(select 1 from t1 where exists(select 1 from t1 where (t1.a) not between t1.c and t1.c)) then ~case when ~t1.f not between +t1.b-11 and e or not b in (c,17,e) and (not exists(select 1 from t1 where b in (( -t1.e), -t1.c,t1.c))) or 17 not in (t1.e,t1.c,t1.f) then c when 19= - -11 then t1.b else t1.c end when (13) between t1.f and ( -t1.e) then t1.d else -t1.d end*c,d))} +} {100} +do_test randexpr-2.772 { + db eval {SELECT coalesce((select max(coalesce((select ((abs(coalesce((select max((select ~(count(distinct e-11)-cast(avg(t1.a) AS integer) & count(*)) from t1)) from t1 where t1.fb or t1.c in (select c from t1 union select 19 from t1)),e & b))/abs(t1.f))) from t1 where e in (select -(b) from t1 union select 13 from t1)),t1.a)) from t1 where f<>11),t1.e) FROM t1 WHERE NOT ( -11 in (a,case when exists(select 1 from t1 where 11 in (select 13 from t1 union select t1.d from t1)) and exists(select 1 from t1 where exists(select 1 from t1 where (t1.a) not between t1.c and t1.c)) then ~case when ~t1.f not between +t1.b-11 and e or not b in (c,17,e) and (not exists(select 1 from t1 where b in (( -t1.e), -t1.c,t1.c))) or 17 not in (t1.e,t1.c,t1.f) then c when 19= - -11 then t1.b else t1.c end when (13) between t1.f and ( -t1.e) then t1.d else -t1.d end*c,d))} +} {100} +do_test randexpr-2.773 { + db eval {SELECT 17-13-case 19 when 17+case case t1.b when t1.b then coalesce((select coalesce((select 11 from t1 where (coalesce((select t1.a from t1 where (abs(f)/abs(case t1.e when 11 then a else t1.c end))19 or d not between f and t1.e),(t1.c)) else 11 end when -a then 13 else e end then t1.b else b end+t1.c FROM t1 WHERE not exists(select 1 from t1 where coalesce((select e from t1 where case when not exists(select 1 from t1 where not not exists(select 1 from t1 where f<> -t1.e-t1.c)) or coalesce((select max(17+t1.c) from t1 where t1.f in (select cast(avg(17) AS integer) from t1 union select cast(avg(t1.c) AS integer) from t1)),t1.d)<>19 then 19 else t1.a+ -(b)+t1.c end<=t1.c),t1.b)>t1.d) or (e) in (t1.c,f,13) or d in (select +count(*) from t1 union select count(*) from t1)} +} {} +do_test randexpr-2.774 { + db eval {SELECT 17-13-case 19 when 17+case case t1.b when t1.b then coalesce((select coalesce((select 11 from t1 where (coalesce((select t1.a from t1 where (abs(f)/abs(case t1.e when 11 then a else t1.c end))19 or d not between f and t1.e),(t1.c)) else 11 end when -a then 13 else e end then t1.b else b end+t1.c FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select e from t1 where case when not exists(select 1 from t1 where not not exists(select 1 from t1 where f<> -t1.e-t1.c)) or coalesce((select max(17+t1.c) from t1 where t1.f in (select cast(avg(17) AS integer) from t1 union select cast(avg(t1.c) AS integer) from t1)),t1.d)<>19 then 19 else t1.a+ -(b)+t1.c end<=t1.c),t1.b)>t1.d) or (e) in (t1.c,f,13) or d in (select +count(*) from t1 union select count(*) from t1))} +} {104} +do_test randexpr-2.775 { + db eval {SELECT t1.e*(abs(coalesce((select max(case when t1.c in (select (case when d>13 then t1.c else 11 end+e) from t1 union select t1.a from t1) or t1.a between 17 and c then c when t1.d>=a then t1.c else t1.e end-t1.e*t1.b-d) from t1 where b<>(t1.c) or not exists(select 1 from t1 where b in (t1.d,13,a))),11)*t1.a)/abs(t1.a))+t1.c FROM t1 WHERE a>c} +} {} +do_test randexpr-2.776 { + db eval {SELECT t1.e*(abs(coalesce((select max(case when t1.c in (select (case when d>13 then t1.c else 11 end+e) from t1 union select t1.a from t1) or t1.a between 17 and c then c when t1.d>=a then t1.c else t1.e end-t1.e*t1.b-d) from t1 where b<>(t1.c) or not exists(select 1 from t1 where b in (t1.d,13,a))),11)*t1.a)/abs(t1.a))+t1.c FROM t1 WHERE NOT (a>c)} +} {50050300} +do_test randexpr-2.777 { + db eval {SELECT t1.d*(+coalesce((select max(case when coalesce((select (abs(f)/abs((abs(d)/abs((select cast(avg(19+11) AS integer) from t1)))+t1.b)) from t1 where exists(select 1 from t1 where t1.d not between t1.f and t1.e)),17) not in (17,t1.f, -t1.b) then 19 else -19 end) from t1 where exists(select 1 from t1 where 11 in (select abs(count(distinct t1.f)) from t1 union select cast(avg(t1.e) AS integer) from t1) and exists(select 1 from t1 where t1.f -11),(17)) | b-19*d FROM t1 WHERE b>coalesce((select max(13+d) from t1 where 17>=11),t1.b)} +} {} +do_test randexpr-2.780 { + db eval {SELECT coalesce((select max(coalesce((select (select cast(avg(d) AS integer) | case max(~f) | count(distinct t1.d) when count(*) then count(*) else -min(17) end from t1) from t1 where b=t1.e+ -e or t1.a not in (t1.f,t1.d,t1.d) or f not in (t1.a, -t1.b,f)),t1.c)+b | 13-d) from t1 where t1.b> -11),(17)) | b-19*d FROM t1 WHERE NOT (b>coalesce((select max(13+d) from t1 where 17>=11),t1.b))} +} {-1} +do_test randexpr-2.781 { + db eval {SELECT coalesce((select max(coalesce((select (select cast(avg(d) AS integer) & case max(~f) & count(distinct t1.d) when count(*) then count(*) else -min(17) end from t1) from t1 where b=t1.e+ -e or t1.a not in (t1.f,t1.d,t1.d) or f not in (t1.a, -t1.b,f)),t1.c)+b & 13-d) from t1 where t1.b> -11),(17)) & b-19*d FROM t1 WHERE NOT (b>coalesce((select max(13+d) from t1 where 17>=11),t1.b))} +} {8} +do_test randexpr-2.782 { + db eval {SELECT (d+f*t1.c-t1.e+coalesce((select c from t1 where c>=a),case when (c in (select e from t1 union select 13 from t1)) then 11+a else f end))-13 FROM t1 WHERE c not between c and b+coalesce((select c from t1 where t1.d=a),case when (c in (select e from t1 union select 13 from t1)) then 11+a else f end))-13 FROM t1 WHERE NOT (c not between c and b+coalesce((select c from t1 where t1.d=d then (abs(13)/abs(t1.f)) when (d in ((select abs(min(19)) from t1), -(select count(*)-abs( -count(*)) from t1),t1.e)) then coalesce((select max(19) from t1 where (c)>t1.f),17) else 13 end<>a then 11 when b<(d) then b else c end,d) then 17 when (17 in (13,t1.a,t1.c)) then e else c end+t1.c FROM t1 WHERE t1.a+t1.e in (select 19 from t1 union select t1.c from t1)} +} {} +do_test randexpr-2.785 { + db eval {SELECT case when t1.e not in (t1.a,~case when case when 17>=d then (abs(13)/abs(t1.f)) when (d in ((select abs(min(19)) from t1), -(select count(*)-abs( -count(*)) from t1),t1.e)) then coalesce((select max(19) from t1 where (c)>t1.f),17) else 13 end<>a then 11 when b<(d) then b else c end,d) then 17 when (17 in (13,t1.a,t1.c)) then e else c end+t1.c FROM t1 WHERE NOT (t1.a+t1.e in (select 19 from t1 union select t1.c from t1))} +} {317} +do_test randexpr-2.786 { + db eval {SELECT (select ~cast(avg(t1.c) AS integer)*case count(*) | +min(case +case when a<13 or case t1.f when c then 17 else t1.d end in (11,a,(t1.a)) and a<>a then t1.b+f when f not in (d,t1.a,c) then t1.f else t1.e end when t1.f then 17 else f end)+abs(++count(distinct 19))*(count(distinct 13))-count(distinct t1.e)-(count(*))*max(19) when max(11) then cast(avg(a) AS integer) else min(t1.f) end from t1) FROM t1 WHERE t1.a not between 17 and d} +} {} +do_test randexpr-2.787 { + db eval {SELECT (select ~cast(avg(t1.c) AS integer)*case count(*) | +min(case +case when a<13 or case t1.f when c then 17 else t1.d end in (11,a,(t1.a)) and a<>a then t1.b+f when f not in (d,t1.a,c) then t1.f else t1.e end when t1.f then 17 else f end)+abs(++count(distinct 19))*(count(distinct 13))-count(distinct t1.e)-(count(*))*max(19) when max(11) then cast(avg(a) AS integer) else min(t1.f) end from t1) FROM t1 WHERE NOT (t1.a not between 17 and d)} +} {-180600} +do_test randexpr-2.788 { + db eval {SELECT (select ~cast(avg(t1.c) AS integer)*case count(*) & +min(case +case when a<13 or case t1.f when c then 17 else t1.d end in (11,a,(t1.a)) and a<>a then t1.b+f when f not in (d,t1.a,c) then t1.f else t1.e end when t1.f then 17 else f end)+abs(++count(distinct 19))*(count(distinct 13))-count(distinct t1.e)-(count(*))*max(19) when max(11) then cast(avg(a) AS integer) else min(t1.f) end from t1) FROM t1 WHERE NOT (t1.a not between 17 and d)} +} {-180600} +do_test randexpr-2.789 { + db eval {SELECT case t1.a when c then -~t1.d*t1.e-coalesce((select max((abs(d+e+d)/abs(case when 11-t1.d in (select t1.d from t1 union select coalesce((select t1.c from t1 where 17<=t1.d and e between 11 and a),c) from t1) or 11 in (select ( -+(count(*))) from t1 union select count(distinct -t1.a) from t1) then (f) when b=a then c else t1.b end))) from t1 where t1.c not between 17 and t1.b),13)+t1.f else d end FROM t1 WHERE not exists(select 1 from t1 where f<=a)} +} {400} +do_test randexpr-2.790 { + db eval {SELECT case t1.a when c then -~t1.d*t1.e-coalesce((select max((abs(d+e+d)/abs(case when 11-t1.d in (select t1.d from t1 union select coalesce((select t1.c from t1 where 17<=t1.d and e between 11 and a),c) from t1) or 11 in (select ( -+(count(*))) from t1 union select count(distinct -t1.a) from t1) then (f) when b=a then c else t1.b end))) from t1 where t1.c not between 17 and t1.b),13)+t1.f else d end FROM t1 WHERE NOT (not exists(select 1 from t1 where f<=a))} +} {} +do_test randexpr-2.791 { + db eval {SELECT (select -max(d) from t1)+coalesce((select max(t1.e*t1.d*f) from t1 where t1.b-coalesce((select -a*d from t1 where t1.c not in (t1.f,coalesce((select b+t1.b from t1 where t1.a not between f and t1.b),coalesce((select -b from t1 where (t1.d>=t1.c) and 19<>t1.f),t1.a))-e*a,e)),(t1.a))+t1.f between 19 and e),t1.a)*a FROM t1 WHERE exists(select 1 from t1 where not exists(select 1 from t1 where case when t1.d-t1.b-t1.d*(case when t1.b>= -t1.d then c when t1.d not between c and t1.d then (19) else d end*e)+t1.d | 19>t1.c then e when exists(select 1 from t1 where t1.e not between d and t1.b or (17 in (t1.e, - -a,t1.d))) then t1.f else (e) end between 13 and e or 11>t1.b))} +} {9600} +do_test randexpr-2.792 { + db eval {SELECT (select -max(d) from t1)+coalesce((select max(t1.e*t1.d*f) from t1 where t1.b-coalesce((select -a*d from t1 where t1.c not in (t1.f,coalesce((select b+t1.b from t1 where t1.a not between f and t1.b),coalesce((select -b from t1 where (t1.d>=t1.c) and 19<>t1.f),t1.a))-e*a,e)),(t1.a))+t1.f between 19 and e),t1.a)*a FROM t1 WHERE NOT (exists(select 1 from t1 where not exists(select 1 from t1 where case when t1.d-t1.b-t1.d*(case when t1.b>= -t1.d then c when t1.d not between c and t1.d then (19) else d end*e)+t1.d | 19>t1.c then e when exists(select 1 from t1 where t1.e not between d and t1.b or (17 in (t1.e, - -a,t1.d))) then t1.f else (e) end between 13 and e or 11>t1.b)))} +} {} +do_test randexpr-2.793 { + db eval {SELECT 11-t1.d-t1.e-case when (select count(distinct t1.b+coalesce((select max((abs(19)/abs(case when coalesce((select t1.f from t1 where e not between t1.f and t1.f),f)*( -11)=((e)) then 11 else d end))) from t1 where e in (17,t1.b,t1.b)), -t1.a)-(t1.c)) from t1)>t1.f then t1.b when 11>13 and a>=f then 11 else d end-t1.f FROM t1 WHERE (select min(d)-case cast(avg(case (d-~t1.c+~(select max(+d-coalesce((select max(t1.f) from t1 where c<>e),t1.a))-(( - -(cast(avg(13) AS integer)))-count(distinct e))*max(17) from t1) | 19-13*b) when -t1.d then 13 else -13 end) AS integer) when min(t1.c) then cast(avg(e) AS integer) else ~count(*) end from t1)t1.f then t1.b when 11>13 and a>=f then 11 else d end-t1.f FROM t1 WHERE NOT ((select min(d)-case cast(avg(case (d-~t1.c+~(select max(+d-coalesce((select max(t1.f) from t1 where c<>e),t1.a))-(( - -(cast(avg(13) AS integer)))-count(distinct e))*max(17) from t1) | 19-13*b) when -t1.d then 13 else -13 end) AS integer) when min(t1.c) then cast(avg(e) AS integer) else ~count(*) end from t1)(c) then t1.d else 13 end end FROM t1 WHERE not ((abs(f)/abs(t1.b))<=(select min(+t1.d)+~+case count(distinct (abs(case d when 11 then coalesce((select coalesce((select max(t1.a) from t1 where t1.b=t1.e),t1.f) | a from t1 where 13<>(a)),d) else 17 end*f)/abs(t1.f))) when cast(avg(t1.c) AS integer) then case count(*) when min(t1.b) | cast(avg(t1.c) AS integer) then count(distinct f) else max(17) end else cast(avg((c)) AS integer) end from t1))} +} {} +do_test randexpr-2.796 { + db eval {SELECT case f when 13 then 19 else case when (case when c not between b and d then t1.c when +~t1.d+(select -+cast(avg(t1.a) AS integer) | ((max(t1.d)))*(max(e)) from t1)-19+t1.a*t1.d in (select ~max(c) from t1 union select count(distinct d)-count(distinct b) from t1) then f else -11 end not between 11 and 11) or 17>(c) then t1.d else 13 end end FROM t1 WHERE NOT (not ((abs(f)/abs(t1.b))<=(select min(+t1.d)+~+case count(distinct (abs(case d when 11 then coalesce((select coalesce((select max(t1.a) from t1 where t1.b=t1.e),t1.f) | a from t1 where 13<>(a)),d) else 17 end*f)/abs(t1.f))) when cast(avg(t1.c) AS integer) then case count(*) when min(t1.b) | cast(avg(t1.c) AS integer) then count(distinct f) else max(17) end else cast(avg((c)) AS integer) end from t1)))} +} {400} +do_test randexpr-2.797 { + db eval {SELECT case f when 13 then 19 else case when (case when c not between b and d then t1.c when +~t1.d+(select -+cast(avg(t1.a) AS integer) & ((max(t1.d)))*(max(e)) from t1)-19+t1.a*t1.d in (select ~max(c) from t1 union select count(distinct d)-count(distinct b) from t1) then f else -11 end not between 11 and 11) or 17>(c) then t1.d else 13 end end FROM t1 WHERE NOT (not ((abs(f)/abs(t1.b))<=(select min(+t1.d)+~+case count(distinct (abs(case d when 11 then coalesce((select coalesce((select max(t1.a) from t1 where t1.b=t1.e),t1.f) | a from t1 where 13<>(a)),d) else 17 end*f)/abs(t1.f))) when cast(avg(t1.c) AS integer) then case count(*) when min(t1.b) | cast(avg(t1.c) AS integer) then count(distinct f) else max(17) end else cast(avg((c)) AS integer) end from t1)))} +} {400} +do_test randexpr-2.798 { + db eval {SELECT f+case when (not exists(select 1 from t1 where ((17<>+t1.b+t1.f or b between t1.e and t1.e)))) then (abs( -(abs(case when exists(select 1 from t1 where not exists(select 1 from t1 where d in (select (select cast(avg((t1.b)) AS integer)-count(*) from t1) from t1 union select t1.e+(11) from t1))) then c when not t1.d between f and 11 or d>a then (a) else 13 end+t1.e+e)/abs(d)))/abs(t1.b)) else f end-13 FROM t1 WHERE case when 17< - -t1.b-case when not exists(select 1 from t1 where 19<>t1.d) then 13+coalesce((select max((abs((case case when - -t1.c*11 in (select +max(t1.d)*count(distinct -t1.c) from t1 union select max(t1.b) from t1) then 13 else 19 end when f then 19 else (t1.d) end)+e)/abs(f))) from t1 where (13 between t1.d and 19)),t1.b) else 13 end then a else t1.a end-13 not in (t1.d,d,(t1.f))} +} {1187} +do_test randexpr-2.799 { + db eval {SELECT f+case when (not exists(select 1 from t1 where ((17<>+t1.b+t1.f or b between t1.e and t1.e)))) then (abs( -(abs(case when exists(select 1 from t1 where not exists(select 1 from t1 where d in (select (select cast(avg((t1.b)) AS integer)-count(*) from t1) from t1 union select t1.e+(11) from t1))) then c when not t1.d between f and 11 or d>a then (a) else 13 end+t1.e+e)/abs(d)))/abs(t1.b)) else f end-13 FROM t1 WHERE NOT (case when 17< - -t1.b-case when not exists(select 1 from t1 where 19<>t1.d) then 13+coalesce((select max((abs((case case when - -t1.c*11 in (select +max(t1.d)*count(distinct -t1.c) from t1 union select max(t1.b) from t1) then 13 else 19 end when f then 19 else (t1.d) end)+e)/abs(f))) from t1 where (13 between t1.d and 19)),t1.b) else 13 end then a else t1.a end-13 not in (t1.d,d,(t1.f)))} +} {} +do_test randexpr-2.800 { + db eval {SELECT +~t1.a-(abs(+case when (((t1.d*t1.c+11 in (select cast(avg(17) AS integer) from t1 union select -(count(*)) from t1)))) then -coalesce((select t1.e-b from t1 where not exists(select 1 from t1 where t1.c in (select max(f) from t1 union select max(e) | max( -t1.e)-count(*) from t1))),f) else f end)/abs(t1.f))-e+11+t1.b+t1.a- -17 FROM t1 WHERE +b between case when c<=t1.a then t1.b when case when -t1.a*d-17+17*~e- -13 in (select + -max(19) | +cast(avg(19) AS integer) from t1 union select (count(distinct -19)*case max((13)) when max(e)*count(*) then min(t1.d) else count(*) end) from t1) then t1.f else (d) end in (select e from t1 union select d from t1) then f else -t1.b end and b} +} {} +do_test randexpr-2.801 { + db eval {SELECT +~t1.a-(abs(+case when (((t1.d*t1.c+11 in (select cast(avg(17) AS integer) from t1 union select -(count(*)) from t1)))) then -coalesce((select t1.e-b from t1 where not exists(select 1 from t1 where t1.c in (select max(f) from t1 union select max(e) | max( -t1.e)-count(*) from t1))),f) else f end)/abs(t1.f))-e+11+t1.b+t1.a- -17 FROM t1 WHERE NOT (+b between case when c<=t1.a then t1.b when case when -t1.a*d-17+17*~e- -13 in (select + -max(19) | +cast(avg(19) AS integer) from t1 union select (count(distinct -19)*case max((13)) when max(e)*count(*) then min(t1.d) else count(*) end) from t1) then t1.f else (d) end in (select e from t1 union select d from t1) then f else -t1.b end and b)} +} {-274} +do_test randexpr-2.802 { + db eval {SELECT +~t1.a-(abs(+case when (((t1.d*t1.c+11 in (select cast(avg(17) AS integer) from t1 union select -(count(*)) from t1)))) then -coalesce((select t1.e-b from t1 where not exists(select 1 from t1 where t1.c in (select max(f) from t1 union select max(e) & max( -t1.e)-count(*) from t1))),f) else f end)/abs(t1.f))-e+11+t1.b+t1.a- -17 FROM t1 WHERE NOT (+b between case when c<=t1.a then t1.b when case when -t1.a*d-17+17*~e- -13 in (select + -max(19) | +cast(avg(19) AS integer) from t1 union select (count(distinct -19)*case max((13)) when max(e)*count(*) then min(t1.d) else count(*) end) from t1) then t1.f else (d) end in (select e from t1 union select d from t1) then f else -t1.b end and b)} +} {-274} +do_test randexpr-2.803 { + db eval {SELECT case when 19=(select ( -count(*)* -(cast(avg(t1.e) AS integer))+count(distinct 13)*min(t1.f)) | cast(avg(t1.e) AS integer) | -cast(avg(13) AS integer)-(min(d)) from t1) then 13*a when t1.a+((select min((t1.d)) from t1)) in (select t1.b from t1 union select 11 from t1) or not exists(select 1 from t1 where not exists(select 1 from t1 where - -e in (select t1.e from t1 union select t1.d from t1) or t1.d in (select count(distinct t1.a) from t1 union select count(*) from t1)) or -b=(19) and 1117 and t1.a>= -t1.b),t1.f) when t1.d then c else t1.d end end in (select count(*) from t1 union select ~abs(min(t1.a)) | count(*) from t1) then 17 when t1.f not between (e) and t1.c then f else b end+c+a end FROM t1 WHERE t1.f in (case when ~(select max(d) from t1)*t1.f>=case when 17*d17 and t1.a>= -t1.b),t1.f) when t1.d then c else t1.d end end in (select count(*) from t1 union select ~abs(min(t1.a)) | count(*) from t1) then 17 when t1.f not between (e) and t1.c then f else b end+c+a end FROM t1 WHERE NOT (t1.f in (case when ~(select max(d) from t1)*t1.f>=case when 17*d17 and t1.a>= -t1.b),t1.f) when t1.d then c else t1.d end end in (select count(*) from t1 union select ~abs(min(t1.a)) & count(*) from t1) then 17 when t1.f not between (e) and t1.c then f else b end+c+a end FROM t1 WHERE NOT (t1.f in (case when ~(select max(d) from t1)*t1.f>=case when 17*d=(select cast(avg(13) AS integer) from t1)) and (exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select t1.c from t1 where (b between d and 13)),t1.e)>13))) then case when b not between 19 and t1.c then a else 13 end+t1.b when t1.c>11 then c else b end then 13 else t1.d end*t1.f)/abs(17)) FROM t1 WHERE c not in (coalesce((select max(d) from t1 where (select min(t1.e) from t1)-17<=coalesce((select t1.c from t1 where exists(select 1 from t1 where 17<19 or coalesce((select 13 from t1 where t1.e not in (a+t1.c,t1.e*t1.a+t1.d* -a*(a)*f,((b)))),19) not in (c,t1.f,t1.b))),(select abs( -max(19)) from t1))),t1.f)-t1.b, -f,17)} +} {458} +do_test randexpr-2.812 { + db eval {SELECT (abs(case when a*case when e<+(t1.e) then e else d end+t1.f=(select cast(avg(13) AS integer) from t1)) and (exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select t1.c from t1 where (b between d and 13)),t1.e)>13))) then case when b not between 19 and t1.c then a else 13 end+t1.b when t1.c>11 then c else b end then 13 else t1.d end*t1.f)/abs(17)) FROM t1 WHERE NOT (c not in (coalesce((select max(d) from t1 where (select min(t1.e) from t1)-17<=coalesce((select t1.c from t1 where exists(select 1 from t1 where 17<19 or coalesce((select 13 from t1 where t1.e not in (a+t1.c,t1.e*t1.a+t1.d* -a*(a)*f,((b)))),19) not in (c,t1.f,t1.b))),(select abs( -max(19)) from t1))),t1.f)-t1.b, -f,17))} +} {} +do_test randexpr-2.813 { + db eval {SELECT t1.c*case when (t1.f in (select case (coalesce((select t1.d from t1 where not (coalesce((select d from t1 where f<=(11)),19)*e in (select ((min((17)) | -min(t1.b))) from t1 union select -cast(avg(t1.f) AS integer) from t1))),19)+11)*t1.a when t1.d then t1.a else f end-e-t1.a*( -17) from t1 union select c from t1) or 13 not between t1.e and b) then d+19-t1.f else t1.c end-e FROM t1 WHERE t1.f in (~t1.b,13,+e) and 11<>d-case when t1.e<>t1.b or f>t1.f and 19 not between 17 and case when (b not in (b,t1.d,a)) then e else (abs(11)/abs(d)) end and not exists(select 1 from t1 where t1.a<>c) then t1.f when not (t1.b) in (select t1.d from t1 union select t1.c from t1) then 13 else t1.b+a end} +} {} +do_test randexpr-2.814 { + db eval {SELECT t1.c*case when (t1.f in (select case (coalesce((select t1.d from t1 where not (coalesce((select d from t1 where f<=(11)),19)*e in (select ((min((17)) | -min(t1.b))) from t1 union select -cast(avg(t1.f) AS integer) from t1))),19)+11)*t1.a when t1.d then t1.a else f end-e-t1.a*( -17) from t1 union select c from t1) or 13 not between t1.e and b) then d+19-t1.f else t1.c end-e FROM t1 WHERE NOT (t1.f in (~t1.b,13,+e) and 11<>d-case when t1.e<>t1.b or f>t1.f and 19 not between 17 and case when (b not in (b,t1.d,a)) then e else (abs(11)/abs(d)) end and not exists(select 1 from t1 where t1.a<>c) then t1.f when not (t1.b) in (select t1.d from t1 union select t1.c from t1) then 13 else t1.b+a end)} +} {-54800} +do_test randexpr-2.815 { + db eval {SELECT t1.c*case when (t1.f in (select case (coalesce((select t1.d from t1 where not (coalesce((select d from t1 where f<=(11)),19)*e in (select ((min((17)) & -min(t1.b))) from t1 union select -cast(avg(t1.f) AS integer) from t1))),19)+11)*t1.a when t1.d then t1.a else f end-e-t1.a*( -17) from t1 union select c from t1) or 13 not between t1.e and b) then d+19-t1.f else t1.c end-e FROM t1 WHERE NOT (t1.f in (~t1.b,13,+e) and 11<>d-case when t1.e<>t1.b or f>t1.f and 19 not between 17 and case when (b not in (b,t1.d,a)) then e else (abs(11)/abs(d)) end and not exists(select 1 from t1 where t1.a<>c) then t1.f when not (t1.b) in (select t1.d from t1 union select t1.c from t1) then 13 else t1.b+a end)} +} {-54800} +do_test randexpr-2.816 { + db eval {SELECT e-t1.e+a*f*11*c*case when ~f*t1.d-t1.c*b-13*19+(abs(t1.d)/abs(case when t1.c=13 then 17 else 19 end))*a between b*(select abs(cast(avg(( -13)) AS integer)) from t1)-19+19 and t1.b then t1.d else t1.d end+13 FROM t1 WHERE t1.b not between a and e} +} {} +do_test randexpr-2.817 { + db eval {SELECT e-t1.e+a*f*11*c*case when ~f*t1.d-t1.c*b-13*19+(abs(t1.d)/abs(case when t1.c=13 then 17 else 19 end))*a between b*(select abs(cast(avg(( -13)) AS integer)) from t1)-19+19 and t1.b then t1.d else t1.d end+13 FROM t1 WHERE NOT (t1.b not between a and e)} +} {79200000013} +do_test randexpr-2.818 { + db eval {SELECT case case when coalesce((select b from t1 where not exists(select 1 from t1 where d-e+coalesce((select max(b) from t1 where case case when t1.d-t1.e not between t1.f and e then 11 else t1.d end when t1.e then f else b end+t1.e=13),t1.c) not in (( -c),c,t1.d))),t1.f)<>a and c not in (t1.b,c,t1.a) then (select count(*) from t1) else c end-11 when t1.d then t1.e else c end FROM t1 WHERE ~b | coalesce((select case (select +count(distinct b) from t1) when coalesce((select case when coalesce((select e from t1 where c>b),t1.c) between 11 and (b) then t1.d else t1.b end-e from t1 where t1.d in (13,t1.a,f)),17) then e else 17 end from t1 where not b=t1.c or t1.d in (select abs(abs( -min(13)*(cast(avg(t1.c) AS integer)))) from t1 union select (max(c)) from t1) and b>t1.a),t1.f) in (select 11 from t1 union select c from t1)} +} {} +do_test randexpr-2.819 { + db eval {SELECT case case when coalesce((select b from t1 where not exists(select 1 from t1 where d-e+coalesce((select max(b) from t1 where case case when t1.d-t1.e not between t1.f and e then 11 else t1.d end when t1.e then f else b end+t1.e=13),t1.c) not in (( -c),c,t1.d))),t1.f)<>a and c not in (t1.b,c,t1.a) then (select count(*) from t1) else c end-11 when t1.d then t1.e else c end FROM t1 WHERE NOT (~b | coalesce((select case (select +count(distinct b) from t1) when coalesce((select case when coalesce((select e from t1 where c>b),t1.c) between 11 and (b) then t1.d else t1.b end-e from t1 where t1.d in (13,t1.a,f)),17) then e else 17 end from t1 where not b=t1.c or t1.d in (select abs(abs( -min(13)*(cast(avg(t1.c) AS integer)))) from t1 union select (max(c)) from t1) and b>t1.a),t1.f) in (select 11 from t1 union select c from t1))} +} {300} +do_test randexpr-2.820 { + db eval {SELECT case t1.c when t1.e then 19 else -case when not exists(select 1 from t1 where t1.b in (select (t1.b) from t1 union select +13 from t1)) then coalesce((select max(c*t1.b) from t1 where 17>=19*e),coalesce((select (select abs(~min(coalesce((select max(t1.a) from t1 where -19 in (f,a,13)),f)))+min(e) | ( -(min(13))) from t1) from t1 where f between -a and t1.c),t1.e)) when 19<>a then 13 else c end end FROM t1 WHERE t1.e<>f} +} {-13} +do_test randexpr-2.821 { + db eval {SELECT case t1.c when t1.e then 19 else -case when not exists(select 1 from t1 where t1.b in (select (t1.b) from t1 union select +13 from t1)) then coalesce((select max(c*t1.b) from t1 where 17>=19*e),coalesce((select (select abs(~min(coalesce((select max(t1.a) from t1 where -19 in (f,a,13)),f)))+min(e) | ( -(min(13))) from t1) from t1 where f between -a and t1.c),t1.e)) when 19<>a then 13 else c end end FROM t1 WHERE NOT (t1.e<>f)} +} {} +do_test randexpr-2.822 { + db eval {SELECT case t1.c when t1.e then 19 else -case when not exists(select 1 from t1 where t1.b in (select (t1.b) from t1 union select +13 from t1)) then coalesce((select max(c*t1.b) from t1 where 17>=19*e),coalesce((select (select abs(~min(coalesce((select max(t1.a) from t1 where -19 in (f,a,13)),f)))+min(e) & ( -(min(13))) from t1) from t1 where f between -a and t1.c),t1.e)) when 19<>a then 13 else c end end FROM t1 WHERE t1.e<>f} +} {-13} +do_test randexpr-2.823 { + db eval {SELECT 13- -(abs(coalesce((select max(17) from t1 where f*b in (select count(*)*case -min(~t1.f)+min(coalesce((select -(select min(17) from t1) from t1 where (t1.b in (select abs(min(t1.f)) from t1 union select -max(t1.e) from t1))),17)+d) when count(distinct a) then abs(count(*)) else count(*) end from t1 union select min(t1.c) from t1)),coalesce((select max(f) from t1 where d in (select t1.b from t1 union select t1.e from t1)),17)) | t1.a)/abs(c)) | t1.f FROM t1 WHERE (abs(t1.f*11++ -f)/abs(19 | (abs(((abs(f)/abs(17))))/abs(case when a not in (t1.d,(c)-~c*f | -13-t1.b+ -d,13) then t1.f when 11=11 then c else d end))*d+t1.c))+e+ -(t1.d) in (select t1.a from t1 union select 19 from t1)} +} {} +do_test randexpr-2.824 { + db eval {SELECT 13- -(abs(coalesce((select max(17) from t1 where f*b in (select count(*)*case -min(~t1.f)+min(coalesce((select -(select min(17) from t1) from t1 where (t1.b in (select abs(min(t1.f)) from t1 union select -max(t1.e) from t1))),17)+d) when count(distinct a) then abs(count(*)) else count(*) end from t1 union select min(t1.c) from t1)),coalesce((select max(f) from t1 where d in (select t1.b from t1 union select t1.e from t1)),17)) | t1.a)/abs(c)) | t1.f FROM t1 WHERE NOT ((abs(t1.f*11++ -f)/abs(19 | (abs(((abs(f)/abs(17))))/abs(case when a not in (t1.d,(c)-~c*f | -13-t1.b+ -d,13) then t1.f when 11=11 then c else d end))*d+t1.c))+e+ -(t1.d) in (select t1.a from t1 union select 19 from t1))} +} {605} +do_test randexpr-2.825 { + db eval {SELECT 13- -(abs(coalesce((select max(17) from t1 where f*b in (select count(*)*case -min(~t1.f)+min(coalesce((select -(select min(17) from t1) from t1 where (t1.b in (select abs(min(t1.f)) from t1 union select -max(t1.e) from t1))),17)+d) when count(distinct a) then abs(count(*)) else count(*) end from t1 union select min(t1.c) from t1)),coalesce((select max(f) from t1 where d in (select t1.b from t1 union select t1.e from t1)),17)) & t1.a)/abs(c)) & t1.f FROM t1 WHERE NOT ((abs(t1.f*11++ -f)/abs(19 | (abs(((abs(f)/abs(17))))/abs(case when a not in (t1.d,(c)-~c*f | -13-t1.b+ -d,13) then t1.f when 11=11 then c else d end))*d+t1.c))+e+ -(t1.d) in (select t1.a from t1 union select 19 from t1))} +} {8} +do_test randexpr-2.826 { + db eval {SELECT (a+case when (exists(select 1 from t1 where not exists(select 1 from t1 where not t1.e*13=13-f or (e)=t1.c or -d not between t1.b and t1.a or e not between 17 and (a) and 11 not in (a,(t1.f),a) or t1.e<>13 or t1.d between t1.e and t1.c or t1.d=17 or a>=b))) and a between t1.e and t1.b then case when e not between (17) and t1.d then ~c*coalesce((select t1.a | 13+d from t1 where t1.e not between b and 11),t1.a) else t1.f end else t1.f end-11) FROM t1 WHERE case when case case when case when -(select +min(11) from t1)*(13)>11 then t1.e when 13t1.a then t1.d else -t1.e end when (a) then a else t1.e end>t1.a then 13 when t1.a not in (t1.f,t1.b,t1.a) then a else t1.c end in (select cast(avg(13) AS integer) from t1 union select (max(t1.e)+min(17)) from t1)} +} {689} +do_test randexpr-2.827 { + db eval {SELECT (a+case when (exists(select 1 from t1 where not exists(select 1 from t1 where not t1.e*13=13-f or (e)=t1.c or -d not between t1.b and t1.a or e not between 17 and (a) and 11 not in (a,(t1.f),a) or t1.e<>13 or t1.d between t1.e and t1.c or t1.d=17 or a>=b))) and a between t1.e and t1.b then case when e not between (17) and t1.d then ~c*coalesce((select t1.a | 13+d from t1 where t1.e not between b and 11),t1.a) else t1.f end else t1.f end-11) FROM t1 WHERE NOT (case when case case when case when -(select +min(11) from t1)*(13)>11 then t1.e when 13t1.a then t1.d else -t1.e end when (a) then a else t1.e end>t1.a then 13 when t1.a not in (t1.f,t1.b,t1.a) then a else t1.c end in (select cast(avg(13) AS integer) from t1 union select (max(t1.e)+min(17)) from t1))} +} {} +do_test randexpr-2.828 { + db eval {SELECT (a+case when (exists(select 1 from t1 where not exists(select 1 from t1 where not t1.e*13=13-f or (e)=t1.c or -d not between t1.b and t1.a or e not between 17 and (a) and 11 not in (a,(t1.f),a) or t1.e<>13 or t1.d between t1.e and t1.c or t1.d=17 or a>=b))) and a between t1.e and t1.b then case when e not between (17) and t1.d then ~c*coalesce((select t1.a & 13+d from t1 where t1.e not between b and 11),t1.a) else t1.f end else t1.f end-11) FROM t1 WHERE case when case case when case when -(select +min(11) from t1)*(13)>11 then t1.e when 13t1.a then t1.d else -t1.e end when (a) then a else t1.e end>t1.a then 13 when t1.a not in (t1.f,t1.b,t1.a) then a else t1.c end in (select cast(avg(13) AS integer) from t1 union select (max(t1.e)+min(17)) from t1)} +} {689} +do_test randexpr-2.829 { + db eval {SELECT ~b-t1.a-f*+case when exists(select 1 from t1 where 17<>t1.d-f or not exists(select 1 from t1 where (select (min(a)+count(distinct d)) from t1)+( -f)- -cf and not exists(select 1 from t1 where t1.ct1.d-f or not exists(select 1 from t1 where (select (min(a)+count(distinct d)) from t1)+( -f)- -cf and not exists(select 1 from t1 where t1.c19 then 13 else c end*d+t1.c then f else 17 end) from t1 where d<=e), -d) then 19 else 17 end in (t1.b,19,c) then 19 when t1.a in (select a from t1 union select 13 from t1) then t1.d else t1.d end FROM t1 WHERE (select abs(cast(avg(t1.d*t1.f) AS integer))-cast(avg(b) AS integer) from t1)-~coalesce((select max(t1.a+t1.d-coalesce((select max(a*case when t1.e<=e then f when t1.d<>a then 11 else 11 end*t1.a*11) from t1 where t1.d>=d),t1.f)) from t1 where 11 not between (13) and 17),f)*t1.b+17-e not in (t1.d,t1.f,t1.f)} +} {400} +do_test randexpr-2.834 { + db eval {SELECT case when case ~( -t1.e)-a when coalesce((select max(case +t1.e when t1.b*~19 | t1.a*case when c-c<>19 then 13 else c end*d+t1.c then f else 17 end) from t1 where d<=e), -d) then 19 else 17 end in (t1.b,19,c) then 19 when t1.a in (select a from t1 union select 13 from t1) then t1.d else t1.d end FROM t1 WHERE NOT ((select abs(cast(avg(t1.d*t1.f) AS integer))-cast(avg(b) AS integer) from t1)-~coalesce((select max(t1.a+t1.d-coalesce((select max(a*case when t1.e<=e then f when t1.d<>a then 11 else 11 end*t1.a*11) from t1 where t1.d>=d),t1.f)) from t1 where 11 not between (13) and 17),f)*t1.b+17-e not in (t1.d,t1.f,t1.f))} +} {} +do_test randexpr-2.835 { + db eval {SELECT case when case ~( -t1.e)-a when coalesce((select max(case +t1.e when t1.b*~19 & t1.a*case when c-c<>19 then 13 else c end*d+t1.c then f else 17 end) from t1 where d<=e), -d) then 19 else 17 end in (t1.b,19,c) then 19 when t1.a in (select a from t1 union select 13 from t1) then t1.d else t1.d end FROM t1 WHERE (select abs(cast(avg(t1.d*t1.f) AS integer))-cast(avg(b) AS integer) from t1)-~coalesce((select max(t1.a+t1.d-coalesce((select max(a*case when t1.e<=e then f when t1.d<>a then 11 else 11 end*t1.a*11) from t1 where t1.d>=d),t1.f)) from t1 where 11 not between (13) and 17),f)*t1.b+17-e not in (t1.d,t1.f,t1.f)} +} {400} +do_test randexpr-2.836 { + db eval {SELECT t1.d+case when case when case when (19 not between ~(t1.a)*b and t1.c) then (select (abs(case count(distinct t1.e) when min( -f) then -max(t1.d) else cast(avg(19) AS integer) end-(count(distinct t1.e)))) from t1) when a<>t1.f then -19 else 11 end>f or b in ((13),f,11) then t1.a when t1.e in (e,f,t1.f) then (t1.d) else t1.d end in (17,t1.c,17) then 13 when b not between t1.a and (19) then t1.e else -11 end+a+((f)) FROM t1 WHERE t1.f in (select case +cast(avg(t1.f+c) AS integer)++count(*) when count(*) then ~~(count(distinct 11+t1.a)) else +(case max(e-f) | ~ -max(t1.f) | -abs(abs(min(e-19+e))-abs(count(*)))-abs(cast(avg(f) AS integer)) when (min(f)) then cast(avg(a) AS integer) else min(13) end) end from t1 union select -count(distinct 13) from t1)} +} {} +do_test randexpr-2.837 { + db eval {SELECT t1.d+case when case when case when (19 not between ~(t1.a)*b and t1.c) then (select (abs(case count(distinct t1.e) when min( -f) then -max(t1.d) else cast(avg(19) AS integer) end-(count(distinct t1.e)))) from t1) when a<>t1.f then -19 else 11 end>f or b in ((13),f,11) then t1.a when t1.e in (e,f,t1.f) then (t1.d) else t1.d end in (17,t1.c,17) then 13 when b not between t1.a and (19) then t1.e else -11 end+a+((f)) FROM t1 WHERE NOT (t1.f in (select case +cast(avg(t1.f+c) AS integer)++count(*) when count(*) then ~~(count(distinct 11+t1.a)) else +(case max(e-f) | ~ -max(t1.f) | -abs(abs(min(e-19+e))-abs(count(*)))-abs(cast(avg(f) AS integer)) when (min(f)) then cast(avg(a) AS integer) else min(13) end) end from t1 union select -count(distinct 13) from t1))} +} {1600} +do_test randexpr-2.838 { + db eval {SELECT (select (min(case when b+b*(select cast(avg(e+19-t1.f*case when case when not (c) in (select (e) from t1 union select f from t1) or t1.b not in (t1.e,t1.b,11) or 19= -t1.a then 17 else -d end13 then 13 else t1.f end+11*19) AS integer) from t1)+d not between 11 and c then t1.c else t1.c end)) from t1) FROM t1 WHERE 13 not between +b* -f and coalesce((select f*19-case when not a=~f+t1.d then case when d*b not in (case when d not between -c and t1.d then e else 13 end+17,c,t1.a) then b when t1.e>t1.f then b else -d end else f end-e+(d) from t1 where 17 between t1.a and t1.e),t1.d) | t1.b} +} {} +do_test randexpr-2.839 { + db eval {SELECT (select (min(case when b+b*(select cast(avg(e+19-t1.f*case when case when not (c) in (select (e) from t1 union select f from t1) or t1.b not in (t1.e,t1.b,11) or 19= -t1.a then 17 else -d end13 then 13 else t1.f end+11*19) AS integer) from t1)+d not between 11 and c then t1.c else t1.c end)) from t1) FROM t1 WHERE NOT (13 not between +b* -f and coalesce((select f*19-case when not a=~f+t1.d then case when d*b not in (case when d not between -c and t1.d then e else 13 end+17,c,t1.a) then b when t1.e>t1.f then b else -d end else f end-e+(d) from t1 where 17 between t1.a and t1.e),t1.d) | t1.b)} +} {300} +do_test randexpr-2.840 { + db eval {SELECT t1.c-(abs((select (case abs(count(distinct 11-c*11)) when count(*) then count(*) else -min(+e+~e+coalesce((select d-a*t1.d+t1.e from t1 where (t1.f>=17) and t1.e in (11,a,e)),13)*t1.d) end) from t1)-(a-t1.f)-t1.d)/abs(d)) FROM t1 WHERE t1.c in (select d from t1 union select ( -t1.e) from t1)} +} {} +do_test randexpr-2.841 { + db eval {SELECT t1.c-(abs((select (case abs(count(distinct 11-c*11)) when count(*) then count(*) else -min(+e+~e+coalesce((select d-a*t1.d+t1.e from t1 where (t1.f>=17) and t1.e in (11,a,e)),13)*t1.d) end) from t1)-(a-t1.f)-t1.d)/abs(d)) FROM t1 WHERE NOT (t1.c in (select d from t1 union select ( -t1.e) from t1))} +} {300} +do_test randexpr-2.842 { + db eval {SELECT case when coalesce((select max(t1.a-case when not (coalesce((select d+c from t1 where c between ( -(a)) and b or 17 between 11 and (c)),(t1.f)))=f then b | d when f not in (t1.b,f,a) then t1.a else f end-t1.f) from t1 where 19<=11 and t1.c between 19 and t1.a or t1.f>11), -t1.e)*e between b and 17 then -t1.f when -a<=19 or -11<>t1.f then -19 else d end FROM t1 WHERE ((13 in (t1.b,f,b)))} +} {} +do_test randexpr-2.843 { + db eval {SELECT case when coalesce((select max(t1.a-case when not (coalesce((select d+c from t1 where c between ( -(a)) and b or 17 between 11 and (c)),(t1.f)))=f then b | d when f not in (t1.b,f,a) then t1.a else f end-t1.f) from t1 where 19<=11 and t1.c between 19 and t1.a or t1.f>11), -t1.e)*e between b and 17 then -t1.f when -a<=19 or -11<>t1.f then -19 else d end FROM t1 WHERE NOT (((13 in (t1.b,f,b))))} +} {-19} +do_test randexpr-2.844 { + db eval {SELECT case when coalesce((select max(t1.a-case when not (coalesce((select d+c from t1 where c between ( -(a)) and b or 17 between 11 and (c)),(t1.f)))=f then b & d when f not in (t1.b,f,a) then t1.a else f end-t1.f) from t1 where 19<=11 and t1.c between 19 and t1.a or t1.f>11), -t1.e)*e between b and 17 then -t1.f when -a<=19 or -11<>t1.f then -19 else d end FROM t1 WHERE NOT (((13 in (t1.b,f,b))))} +} {-19} +do_test randexpr-2.845 { + db eval {SELECT case -(abs(t1.b-13*d*b*t1.e- -11)/abs(+d-t1.f*(11+ -13)-t1.c))+c+(e*t1.c)+f*17*a | t1.e-13+f when t1.d then t1.e else f end-t1.f FROM t1 WHERE -b*t1.c>13} +} {} +do_test randexpr-2.846 { + db eval {SELECT case -(abs(t1.b-13*d*b*t1.e- -11)/abs(+d-t1.f*(11+ -13)-t1.c))+c+(e*t1.c)+f*17*a | t1.e-13+f when t1.d then t1.e else f end-t1.f FROM t1 WHERE NOT ( -b*t1.c>13)} +} {0} +do_test randexpr-2.847 { + db eval {SELECT case -(abs(t1.b-13*d*b*t1.e- -11)/abs(+d-t1.f*(11+ -13)-t1.c))+c+(e*t1.c)+f*17*a & t1.e-13+f when t1.d then t1.e else f end-t1.f FROM t1 WHERE NOT ( -b*t1.c>13)} +} {0} +do_test randexpr-2.848 { + db eval {SELECT case when t1.c between t1.e and ~t1.d+(abs(~d*case t1.b-19 when t1.e then e else e end)/abs(case case t1.b when c then t1.d else 13+17 | e end when (select abs(abs(min(11) | max((a)))) from t1) then d else ~t1.f end)) | t1.b then t1.c when (not (11>=b)) then 13 else e end-a FROM t1 WHERE +13*case when +11*t1.f=f+t1.b then t1.f else t1.b end not between coalesce((select max(f) from t1 where (not exists(select 1 from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where t1.c in (select abs(min(e)) from t1 union select ~ -case cast(avg(~17) AS integer) when min(e | 17) then min(e) else cast(avg(c) AS integer) end from t1)))) or f>e*t1.a+e)),t1.c) and 17} +} {-87} +do_test randexpr-2.849 { + db eval {SELECT case when t1.c between t1.e and ~t1.d+(abs(~d*case t1.b-19 when t1.e then e else e end)/abs(case case t1.b when c then t1.d else 13+17 | e end when (select abs(abs(min(11) | max((a)))) from t1) then d else ~t1.f end)) | t1.b then t1.c when (not (11>=b)) then 13 else e end-a FROM t1 WHERE NOT (+13*case when +11*t1.f=f+t1.b then t1.f else t1.b end not between coalesce((select max(f) from t1 where (not exists(select 1 from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where t1.c in (select abs(min(e)) from t1 union select ~ -case cast(avg(~17) AS integer) when min(e | 17) then min(e) else cast(avg(c) AS integer) end from t1)))) or f>e*t1.a+e)),t1.c) and 17)} +} {} +do_test randexpr-2.850 { + db eval {SELECT case when t1.c between t1.e and ~t1.d+(abs(~d*case t1.b-19 when t1.e then e else e end)/abs(case case t1.b when c then t1.d else 13+17 & e end when (select abs(abs(min(11) & max((a)))) from t1) then d else ~t1.f end)) & t1.b then t1.c when (not (11>=b)) then 13 else e end-a FROM t1 WHERE +13*case when +11*t1.f=f+t1.b then t1.f else t1.b end not between coalesce((select max(f) from t1 where (not exists(select 1 from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where t1.c in (select abs(min(e)) from t1 union select ~ -case cast(avg(~17) AS integer) when min(e | 17) then min(e) else cast(avg(c) AS integer) end from t1)))) or f>e*t1.a+e)),t1.c) and 17} +} {-87} +do_test randexpr-2.851 { + db eval {SELECT coalesce((select +case when case d when b then e else (select min(case b when 17 then b else t1.c end)+ -+ -(abs(max(t1.e))-min(t1.d)+max( -d)) | count(distinct t1.e)+( -cast(avg(13) AS integer)) | max(t1.f)+min(e)+count(*) from t1) end<>b then t1.a else 19*~t1.e-c | t1.c end from t1 where b in ( -c,t1.f,t1.c)),19) FROM t1 WHERE (abs(d)/abs(coalesce((select max(coalesce((select d*c from t1 where ((abs(t1.b)/abs(t1.d))-(abs(t1.f)/abs(t1.c))+(t1.a)*13-t1.e not between t1.e and ~f*11+t1.f-11 | t1.a+13+d)),19)) from t1 where c not in (+ -11,a,c)),t1.c))) in (b,b,a)} +} {} +do_test randexpr-2.852 { + db eval {SELECT coalesce((select +case when case d when b then e else (select min(case b when 17 then b else t1.c end)+ -+ -(abs(max(t1.e))-min(t1.d)+max( -d)) | count(distinct t1.e)+( -cast(avg(13) AS integer)) | max(t1.f)+min(e)+count(*) from t1) end<>b then t1.a else 19*~t1.e-c | t1.c end from t1 where b in ( -c,t1.f,t1.c)),19) FROM t1 WHERE NOT ((abs(d)/abs(coalesce((select max(coalesce((select d*c from t1 where ((abs(t1.b)/abs(t1.d))-(abs(t1.f)/abs(t1.c))+(t1.a)*13-t1.e not between t1.e and ~f*11+t1.f-11 | t1.a+13+d)),19)) from t1 where c not in (+ -11,a,c)),t1.c))) in (b,b,a))} +} {19} +do_test randexpr-2.853 { + db eval {SELECT coalesce((select +case when case d when b then e else (select min(case b when 17 then b else t1.c end)+ -+ -(abs(max(t1.e))-min(t1.d)+max( -d)) & count(distinct t1.e)+( -cast(avg(13) AS integer)) & max(t1.f)+min(e)+count(*) from t1) end<>b then t1.a else 19*~t1.e-c & t1.c end from t1 where b in ( -c,t1.f,t1.c)),19) FROM t1 WHERE NOT ((abs(d)/abs(coalesce((select max(coalesce((select d*c from t1 where ((abs(t1.b)/abs(t1.d))-(abs(t1.f)/abs(t1.c))+(t1.a)*13-t1.e not between t1.e and ~f*11+t1.f-11 | t1.a+13+d)),19)) from t1 where c not in (+ -11,a,c)),t1.c))) in (b,b,a))} +} {19} +do_test randexpr-2.854 { + db eval {SELECT a-a-(abs(f)/abs(coalesce((select 17+19 from t1 where (select min(t1.e*e) from t1)>t1.b+case when not exists(select 1 from t1 where e not between 11 and t1.f-e) then coalesce((select max(f*case when t1.f not in (19,t1.c,(t1.a)) and c<=17 then 11 when 17 not between 11 and 17 then c else 17 end) from t1 where d not between t1.a and 13),t1.c) else t1.b end-13 and a=t1.e),17)+t1.c))-f FROM t1 WHERE +(select cast(avg(13-t1.a-t1.b++t1.a-(select count(*) from t1)+case b-(select +~ -min(case when exists(select 1 from t1 where ((select count(*)+ -(min(13)) from t1)) not between 13 and 13) then d else e end) from t1) when f*t1.b*t1.b then t1.a else b end*t1.a) AS integer) from t1)*t1.b in (t1.f,17,f)} +} {} +do_test randexpr-2.855 { + db eval {SELECT a-a-(abs(f)/abs(coalesce((select 17+19 from t1 where (select min(t1.e*e) from t1)>t1.b+case when not exists(select 1 from t1 where e not between 11 and t1.f-e) then coalesce((select max(f*case when t1.f not in (19,t1.c,(t1.a)) and c<=17 then 11 when 17 not between 11 and 17 then c else 17 end) from t1 where d not between t1.a and 13),t1.c) else t1.b end-13 and a=t1.e),17)+t1.c))-f FROM t1 WHERE NOT (+(select cast(avg(13-t1.a-t1.b++t1.a-(select count(*) from t1)+case b-(select +~ -min(case when exists(select 1 from t1 where ((select count(*)+ -(min(13)) from t1)) not between 13 and 13) then d else e end) from t1) when f*t1.b*t1.b then t1.a else b end*t1.a) AS integer) from t1)*t1.b in (t1.f,17,f))} +} {-601} +do_test randexpr-2.856 { + db eval {SELECT case when (11+19 | t1.e-e*17=t1.e*~d+t1.a+ -d | a-~(abs((abs((case when 13 not in (b,((t1.a)),f) then t1.d else t1.a end+e))/abs(t1.f))*b+t1.b)/abs(17))+t1.e+t1.a) then 11 else t1.a end FROM t1 WHERE case (case when (select +~ -~ -cast(avg(b*e*case when t1.a between t1.c and a and d<13 then b else 19 end* -f*d) AS integer) | count(*)++~+min((11))*max(19)-min((b)) from t1) in (select 13 from t1 union select (select min(19) from t1) from t1) then t1.f+t1.d else 13 end-t1.e) when t1.e then t1.f else a end -t1.b then t1.f else t1.e end)*min(t1.a)+ -count(*) | +max(e)*(min(t1.e)) | count(distinct t1.d) | (count(*)) when count(distinct ((19))) then count(*) else max(t1.f) end from t1)} +} {} +do_test randexpr-2.860 { + db eval {SELECT coalesce((select max(+t1.a) from t1 where c in (select -max(d | coalesce((select max(t1.b) from t1 where (abs(case d when t1.f then t1.e else t1.c end-t1.f)/abs(13))<=11), -a)) | min(t1.c) | (max(f))++abs(case max(b) when (count(distinct e)) then count(*) else min(17) end) from t1 union select (min(19)) from t1) or not exists(select 1 from t1 where coalesce((select c from t1 where b in (select - - - -count(*) from t1 union select -min((a)) from t1)),13) -t1.b then t1.f else t1.e end)*min(t1.a)+ -count(*) | +max(e)*(min(t1.e)) | count(distinct t1.d) | (count(*)) when count(distinct ((19))) then count(*) else max(t1.f) end from t1))} +} {17} +do_test randexpr-2.861 { + db eval {SELECT coalesce((select max(+t1.a) from t1 where c in (select -max(d & coalesce((select max(t1.b) from t1 where (abs(case d when t1.f then t1.e else t1.c end-t1.f)/abs(13))<=11), -a)) & min(t1.c) & (max(f))++abs(case max(b) when (count(distinct e)) then count(*) else min(17) end) from t1 union select (min(19)) from t1) or not exists(select 1 from t1 where coalesce((select c from t1 where b in (select - - - -count(*) from t1 union select -min((a)) from t1)),13) -t1.b then t1.f else t1.e end)*min(t1.a)+ -count(*) | +max(e)*(min(t1.e)) | count(distinct t1.d) | (count(*)) when count(distinct ((19))) then count(*) else max(t1.f) end from t1))} +} {17} +do_test randexpr-2.862 { + db eval {SELECT case 17 when (select ~count(distinct t1.d) from t1) then e else case when not not exists(select 1 from t1 where (abs(~coalesce((select (coalesce((select max(13) from t1 where e>a),19)) from t1 where (not exists(select 1 from t1 where t1.c in (f,b,c)))),c)*t1.c | 17-(e))/abs(t1.f)) | 17*17*a in (select e from t1 union select f from t1)) then 13 when t1.a not between (b) and t1.c then (abs(17)/abs(17)) else t1.d end*f end FROM t1 WHERE t1.a>t1.c-19} +} {} +do_test randexpr-2.863 { + db eval {SELECT case 17 when (select ~count(distinct t1.d) from t1) then e else case when not not exists(select 1 from t1 where (abs(~coalesce((select (coalesce((select max(13) from t1 where e>a),19)) from t1 where (not exists(select 1 from t1 where t1.c in (f,b,c)))),c)*t1.c | 17-(e))/abs(t1.f)) | 17*17*a in (select e from t1 union select f from t1)) then 13 when t1.a not between (b) and t1.c then (abs(17)/abs(17)) else t1.d end*f end FROM t1 WHERE NOT (t1.a>t1.c-19)} +} {600} +do_test randexpr-2.864 { + db eval {SELECT case 17 when (select ~count(distinct t1.d) from t1) then e else case when not not exists(select 1 from t1 where (abs(~coalesce((select (coalesce((select max(13) from t1 where e>a),19)) from t1 where (not exists(select 1 from t1 where t1.c in (f,b,c)))),c)*t1.c & 17-(e))/abs(t1.f)) & 17*17*a in (select e from t1 union select f from t1)) then 13 when t1.a not between (b) and t1.c then (abs(17)/abs(17)) else t1.d end*f end FROM t1 WHERE NOT (t1.a>t1.c-19)} +} {600} +do_test randexpr-2.865 { + db eval {SELECT case when f>=t1.c then t1.d when coalesce((select max(+11-b) from t1 where a-t1.d in (select +case when f in (13,b | 11,t1.b) then -t1.d when f in (select ~count(distinct 17) from t1 union select count(distinct t1.a) from t1) then 19 else c end-d+b from t1 union select a from t1) and (17) in (t1.f,11,t1.c)),f)< -a then d else t1.c end-11 FROM t1 WHERE a<(select count(distinct +11*coalesce((select max(coalesce((select max(t1.d) from t1 where t1.e>t1.b),b)*t1.f) from t1 where case 11 when t1.a then -t1.e else a end<=17),e)-11+c-19) | count(distinct 19)*count(*)* -(count(distinct t1.f))+cast(avg(17) AS integer)-(~~(count(*)))-cast(avg(11) AS integer) | cast(avg((19)) AS integer) from t1)-t1.c} +} {} +do_test randexpr-2.866 { + db eval {SELECT case when f>=t1.c then t1.d when coalesce((select max(+11-b) from t1 where a-t1.d in (select +case when f in (13,b | 11,t1.b) then -t1.d when f in (select ~count(distinct 17) from t1 union select count(distinct t1.a) from t1) then 19 else c end-d+b from t1 union select a from t1) and (17) in (t1.f,11,t1.c)),f)< -a then d else t1.c end-11 FROM t1 WHERE NOT (a<(select count(distinct +11*coalesce((select max(coalesce((select max(t1.d) from t1 where t1.e>t1.b),b)*t1.f) from t1 where case 11 when t1.a then -t1.e else a end<=17),e)-11+c-19) | count(distinct 19)*count(*)* -(count(distinct t1.f))+cast(avg(17) AS integer)-(~~(count(*)))-cast(avg(11) AS integer) | cast(avg((19)) AS integer) from t1)-t1.c)} +} {389} +do_test randexpr-2.867 { + db eval {SELECT case when f>=t1.c then t1.d when coalesce((select max(+11-b) from t1 where a-t1.d in (select +case when f in (13,b & 11,t1.b) then -t1.d when f in (select ~count(distinct 17) from t1 union select count(distinct t1.a) from t1) then 19 else c end-d+b from t1 union select a from t1) and (17) in (t1.f,11,t1.c)),f)< -a then d else t1.c end-11 FROM t1 WHERE NOT (a<(select count(distinct +11*coalesce((select max(coalesce((select max(t1.d) from t1 where t1.e>t1.b),b)*t1.f) from t1 where case 11 when t1.a then -t1.e else a end<=17),e)-11+c-19) | count(distinct 19)*count(*)* -(count(distinct t1.f))+cast(avg(17) AS integer)-(~~(count(*)))-cast(avg(11) AS integer) | cast(avg((19)) AS integer) from t1)-t1.c)} +} {389} +do_test randexpr-2.868 { + db eval {SELECT coalesce((select max(17) from t1 where -coalesce((select t1.b+coalesce((select case when case t1.f when c then (e) else a end+t1.c+(f)>17 and e>=f and (13>t1.f) then (select ~(cast(avg(t1.e) AS integer)) | min(t1.a) from t1) when -c>c then 19 else t1.f end from t1 where (1717 and e>=f and (13>t1.f) then (select ~(cast(avg(t1.e) AS integer)) | min(t1.a) from t1) when -c>c then 19 else t1.f end from t1 where (1717 and e>=f and (13>t1.f) then (select ~(cast(avg(t1.e) AS integer)) & min(t1.a) from t1) when -c>c then 19 else t1.f end from t1 where (17=a then 13 when ((case when t1.d=a)) then 19 else t1.b end-t1.f) when 19 then - -13 else 17 end from t1 union select -17 from t1) and 19 in (select d from t1 union select e from t1) then (select abs(min(t1.f)) from t1) else c end FROM t1 WHERE case coalesce((select 19 from t1 where 13=e then d when (case when not exists(select 1 from t1 where (a>d and d not between e and ((19)) and c in (e,t1.b,(b)) and e not in (t1.f,t1.a,t1.b))) then t1.b when f not between 11 and d then t1.d else d end<=11) then (abs(13)/abs(11)) else -11 end from t1 where (t1.b)=a then 13 when ((case when t1.d=a)) then 19 else t1.b end-t1.f) when 19 then - -13 else 17 end from t1 union select -17 from t1) and 19 in (select d from t1 union select e from t1) then (select abs(min(t1.f)) from t1) else c end FROM t1 WHERE NOT (case coalesce((select 19 from t1 where 13=e then d when (case when not exists(select 1 from t1 where (a>d and d not between e and ((19)) and c in (e,t1.b,(b)) and e not in (t1.f,t1.a,t1.b))) then t1.b when f not between 11 and d then t1.d else d end<=11) then (abs(13)/abs(11)) else -11 end from t1 where (t1.b)t1.c and e not between 13 and t1.d and t1.e in (t1.d,17,t1.c) then c+t1.e*t1.d when t1.f>=t1.d then t1.a else t1.c end else t1.e end-e) from t1 where t1.b not in (t1.b,t1.d,d)), -c)*13 FROM t1 WHERE (abs(e+17)/abs((select count(distinct 11-t1.b)*cast(avg(case c when coalesce((select max(19-coalesce((select max(f) from t1 where 19 in (17,t1.f,11)),t1.d)) from t1 where c in (t1.a,11,13) and t1.a<=t1.c),t1.c) then t1.c else e end) AS integer) | max(e) | (+~case case cast(avg(t1.d) AS integer) when -min(13) then count(*) else count(*) end when max(t1.c) then count(distinct f) else count(*) end-count(distinct 19)) from t1)))>=t1.e | f} +} {} +do_test randexpr-2.876 { + db eval {SELECT +17+(11)-coalesce((select max(case (11) when f then +e+case when +11< -13-f or b between (b) and t1.b and e<>t1.c and e not between 13 and t1.d and t1.e in (t1.d,17,t1.c) then c+t1.e*t1.d when t1.f>=t1.d then t1.a else t1.c end else t1.e end-e) from t1 where t1.b not in (t1.b,t1.d,d)), -c)*13 FROM t1 WHERE NOT ((abs(e+17)/abs((select count(distinct 11-t1.b)*cast(avg(case c when coalesce((select max(19-coalesce((select max(f) from t1 where 19 in (17,t1.f,11)),t1.d)) from t1 where c in (t1.a,11,13) and t1.a<=t1.c),t1.c) then t1.c else e end) AS integer) | max(e) | (+~case case cast(avg(t1.d) AS integer) when -min(13) then count(*) else count(*) end when max(t1.c) then count(distinct f) else count(*) end-count(distinct 19)) from t1)))>=t1.e | f)} +} {3928} +do_test randexpr-2.877 { + db eval {SELECT case when case when d*c not in (13,a,d) then (t1.b-f)+coalesce((select max((select count(distinct 13)-case max(11) when count(*) then count(*) else min(t1.b) end*min(17)+(min(t1.c)) from t1)) from t1 where not exists(select 1 from t1 where t1.c between 17-d | d and t1.e)),b) else t1.e end<=d then e when f in (a,13,d) or t1.b between f and -b then c else t1.a end FROM t1 WHERE t1.d<>t1.a} +} {500} +do_test randexpr-2.878 { + db eval {SELECT case when case when d*c not in (13,a,d) then (t1.b-f)+coalesce((select max((select count(distinct 13)-case max(11) when count(*) then count(*) else min(t1.b) end*min(17)+(min(t1.c)) from t1)) from t1 where not exists(select 1 from t1 where t1.c between 17-d | d and t1.e)),b) else t1.e end<=d then e when f in (a,13,d) or t1.b between f and -b then c else t1.a end FROM t1 WHERE NOT (t1.d<>t1.a)} +} {} +do_test randexpr-2.879 { + db eval {SELECT case when case when d*c not in (13,a,d) then (t1.b-f)+coalesce((select max((select count(distinct 13)-case max(11) when count(*) then count(*) else min(t1.b) end*min(17)+(min(t1.c)) from t1)) from t1 where not exists(select 1 from t1 where t1.c between 17-d & d and t1.e)),b) else t1.e end<=d then e when f in (a,13,d) or t1.b between f and -b then c else t1.a end FROM t1 WHERE t1.d<>t1.a} +} {500} +do_test randexpr-2.880 { + db eval {SELECT case case c when -b then (abs(b)/abs(c)) else (select count(distinct f) | (~abs(min(c-+case 11 when case when t1.a between b and t1.e-case when (13<=b) then (select -count(*) from t1) else a end then t1.e when e>=11 then (19) else b end then d else 17 end | e))) from t1) end when -13 then t1.f else +17 end FROM t1 WHERE 17 in (select +(count(*) | case abs( -abs(abs( -min(d)))) | max(+11) when -+~count(distinct -(abs(coalesce((select max(f) from t1 where t1.e in (select e from t1 union select t1.a from t1)),f) | t1.c-t1.b)/abs(13))) | +abs(case max(b) when count(*) then -min(t1.e) else (cast(avg(t1.f) AS integer)) end)- -count(*) then -count(*) else max(19) end* -cast(avg(t1.b) AS integer))+(max(t1.f)) from t1 union select count(distinct b) from t1)} +} {} +do_test randexpr-2.881 { + db eval {SELECT case case c when -b then (abs(b)/abs(c)) else (select count(distinct f) | (~abs(min(c-+case 11 when case when t1.a between b and t1.e-case when (13<=b) then (select -count(*) from t1) else a end then t1.e when e>=11 then (19) else b end then d else 17 end | e))) from t1) end when -13 then t1.f else +17 end FROM t1 WHERE NOT (17 in (select +(count(*) | case abs( -abs(abs( -min(d)))) | max(+11) when -+~count(distinct -(abs(coalesce((select max(f) from t1 where t1.e in (select e from t1 union select t1.a from t1)),f) | t1.c-t1.b)/abs(13))) | +abs(case max(b) when count(*) then -min(t1.e) else (cast(avg(t1.f) AS integer)) end)- -count(*) then -count(*) else max(19) end* -cast(avg(t1.b) AS integer))+(max(t1.f)) from t1 union select count(distinct b) from t1))} +} {17} +do_test randexpr-2.882 { + db eval {SELECT case case c when -b then (abs(b)/abs(c)) else (select count(distinct f) & (~abs(min(c-+case 11 when case when t1.a between b and t1.e-case when (13<=b) then (select -count(*) from t1) else a end then t1.e when e>=11 then (19) else b end then d else 17 end & e))) from t1) end when -13 then t1.f else +17 end FROM t1 WHERE NOT (17 in (select +(count(*) | case abs( -abs(abs( -min(d)))) | max(+11) when -+~count(distinct -(abs(coalesce((select max(f) from t1 where t1.e in (select e from t1 union select t1.a from t1)),f) | t1.c-t1.b)/abs(13))) | +abs(case max(b) when count(*) then -min(t1.e) else (cast(avg(t1.f) AS integer)) end)- -count(*) then -count(*) else max(19) end* -cast(avg(t1.b) AS integer))+(max(t1.f)) from t1 union select count(distinct b) from t1))} +} {17} +do_test randexpr-2.883 { + db eval {SELECT case 11 when (case when t1.e in (select +cast(avg(coalesce((select max(13) from t1 where case when exists(select 1 from t1 where t1.b in ((a),d,(t1.e))) then case when 19 in (select -max(17) from t1 union select min(t1.f) from t1) then t1.b else 17 end when a not in ((t1.f),11,t1.e) then 17 else t1.c end(19)),c)) and c and (11 in (select t1.b from t1 union select 13 from t1) and ( -t1.d)=d)),e | 19*t1.a))) and t1.a then t1.a when 19>=t1.a then e else c end> -e} +} {500} +do_test randexpr-2.884 { + db eval {SELECT case 11 when (case when t1.e in (select +cast(avg(coalesce((select max(13) from t1 where case when exists(select 1 from t1 where t1.b in ((a),d,(t1.e))) then case when 19 in (select -max(17) from t1 union select min(t1.f) from t1) then t1.b else 17 end when a not in ((t1.f),11,t1.e) then 17 else t1.c end(19)),c)) and c and (11 in (select t1.b from t1 union select 13 from t1) and ( -t1.d)=d)),e | 19*t1.a))) and t1.a then t1.a when 19>=t1.a then e else c end> -e)} +} {} +do_test randexpr-2.885 { + db eval {SELECT case 11 when (case when t1.e in (select +cast(avg(coalesce((select max(13) from t1 where case when exists(select 1 from t1 where t1.b in ((a),d,(t1.e))) then case when 19 in (select -max(17) from t1 union select min(t1.f) from t1) then t1.b else 17 end when a not in ((t1.f),11,t1.e) then 17 else t1.c end(19)),c)) and c and (11 in (select t1.b from t1 union select 13 from t1) and ( -t1.d)=d)),e | 19*t1.a))) and t1.a then t1.a when 19>=t1.a then e else c end> -e} +} {500} +do_test randexpr-2.886 { + db eval {SELECT case a*t1.a when ~++a*(abs(e)/abs(19)) | t1.d+(select count(*) from t1) then b else t1.a end*coalesce((select max(f) from t1 where f<>t1.d),b) FROM t1 WHERE (abs(c-~t1.b)/abs(d))-((+coalesce((select max(c) from t1 where -+(select ~ -(cast(avg((13+case 11*t1.c when t1.b then f else ~e-coalesce((select max((f)) from t1 where t1.ft1.d),b) FROM t1 WHERE NOT ((abs(c-~t1.b)/abs(d))-((+coalesce((select max(c) from t1 where -+(select ~ -(cast(avg((13+case 11*t1.c when t1.b then f else ~e-coalesce((select max((f)) from t1 where t1.ft1.d),b) FROM t1 WHERE NOT ((abs(c-~t1.b)/abs(d))-((+coalesce((select max(c) from t1 where -+(select ~ -(cast(avg((13+case 11*t1.c when t1.b then f else ~e-coalesce((select max((f)) from t1 where t1.f=+t1.b then f when t1.c+f13 then t1.d else t1.a end)/abs(t1.d))) from t1 where t1.c not between t1.c and 11 and e>d),f)*t1.e+d,a,13)),e) | t1.b FROM t1 WHERE (abs(+(+t1.a)+case a-case when c>=d then 13 when t1.c not in (17,17,e) then a else t1.d end when c then -f else b end*d)/abs(17))<=11 and 11 in (select cast(avg(17) AS integer) from t1 union select min( -19)+(case max(a) when abs(count(*)) then -abs(count(*)*min(t1.e)+max(11)) else min(c) end) from t1)} +} {} +do_test randexpr-2.890 { + db eval {SELECT t1.c-t1.f-coalesce((select max(a) from t1 where e in ((abs(a)/abs(t1.d))*coalesce((select max((abs(case when e>=+t1.b then f when t1.c+f13 then t1.d else t1.a end)/abs(t1.d))) from t1 where t1.c not between t1.c and 11 and e>d),f)*t1.e+d,a,13)),e) | t1.b FROM t1 WHERE NOT ((abs(+(+t1.a)+case a-case when c>=d then 13 when t1.c not in (17,17,e) then a else t1.d end when c then -f else b end*d)/abs(17))<=11 and 11 in (select cast(avg(17) AS integer) from t1 union select min( -19)+(case max(a) when abs(count(*)) then -abs(count(*)*min(t1.e)+max(11)) else min(c) end) from t1))} +} {-792} +do_test randexpr-2.891 { + db eval {SELECT t1.c-t1.f-coalesce((select max(a) from t1 where e in ((abs(a)/abs(t1.d))*coalesce((select max((abs(case when e>=+t1.b then f when t1.c+f13 then t1.d else t1.a end)/abs(t1.d))) from t1 where t1.c not between t1.c and 11 and e>d),f)*t1.e+d,a,13)),e) & t1.b FROM t1 WHERE NOT ((abs(+(+t1.a)+case a-case when c>=d then 13 when t1.c not in (17,17,e) then a else t1.d end when c then -f else b end*d)/abs(17))<=11 and 11 in (select cast(avg(17) AS integer) from t1 union select min( -19)+(case max(a) when abs(count(*)) then -abs(count(*)*min(t1.e)+max(11)) else min(c) end) from t1))} +} {192} +do_test randexpr-2.892 { + db eval {SELECT coalesce((select (select count(*) from t1)*a*b from t1 where ((~b*a-t1.d+11*e-(select -count(*) | count(*) | count(*) from t1)*(select min((abs(coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where -17 in (t1.b,t1.f,t1.d))),11))/abs(t1.d))) from t1)-17+(abs(11)/abs(11)) | b+d | 11 in (select t1.a from t1 union select 13 from t1)))),t1.a) FROM t1 WHERE f>case when f-case when not exists(select 1 from t1 where case when b in (select abs(max(coalesce((select max(~t1.c) from t1 where t1.f<=13),17))) from t1 union select cast(avg(t1.c) AS integer) from t1) then t1.e else (13) end> -t1.e) or d<>19 then coalesce((select max((select abs(max(d)+cast(avg(d) AS integer)) from t1)) from t1 where t1.e19 then b when t1.a<=11 then 11 else t1.d end} +} {100} +do_test randexpr-2.893 { + db eval {SELECT coalesce((select (select count(*) from t1)*a*b from t1 where ((~b*a-t1.d+11*e-(select -count(*) | count(*) | count(*) from t1)*(select min((abs(coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where -17 in (t1.b,t1.f,t1.d))),11))/abs(t1.d))) from t1)-17+(abs(11)/abs(11)) | b+d | 11 in (select t1.a from t1 union select 13 from t1)))),t1.a) FROM t1 WHERE NOT (f>case when f-case when not exists(select 1 from t1 where case when b in (select abs(max(coalesce((select max(~t1.c) from t1 where t1.f<=13),17))) from t1 union select cast(avg(t1.c) AS integer) from t1) then t1.e else (13) end> -t1.e) or d<>19 then coalesce((select max((select abs(max(d)+cast(avg(d) AS integer)) from t1)) from t1 where t1.e19 then b when t1.a<=11 then 11 else t1.d end)} +} {} +do_test randexpr-2.894 { + db eval {SELECT coalesce((select (select count(*) from t1)*a*b from t1 where ((~b*a-t1.d+11*e-(select -count(*) & count(*) & count(*) from t1)*(select min((abs(coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where -17 in (t1.b,t1.f,t1.d))),11))/abs(t1.d))) from t1)-17+(abs(11)/abs(11)) & b+d & 11 in (select t1.a from t1 union select 13 from t1)))),t1.a) FROM t1 WHERE f>case when f-case when not exists(select 1 from t1 where case when b in (select abs(max(coalesce((select max(~t1.c) from t1 where t1.f<=13),17))) from t1 union select cast(avg(t1.c) AS integer) from t1) then t1.e else (13) end> -t1.e) or d<>19 then coalesce((select max((select abs(max(d)+cast(avg(d) AS integer)) from t1)) from t1 where t1.e19 then b when t1.a<=11 then 11 else t1.d end} +} {100} +do_test randexpr-2.895 { + db eval {SELECT coalesce((select e from t1 where ((abs((select case (~max(f) | ~max(19-t1.d) | cast(avg(11) AS integer)) when min(+t1.d*c) then max(case when 19+13 not between 13 and t1.c or t1.c not in ((b),11,(e)) then d else t1.d end+ -t1.d) else min(a) end from t1))/abs(11)))<17),t1.b)+17 FROM t1 WHERE (13 in (a,t1.a,~+(e)+t1.c*t1.c | t1.c- -t1.b-t1.b+e*b | t1.e-t1.e-e*coalesce((select max(t1.b) from t1 where t1.a*d<>coalesce((select max(t1.e-t1.b) from t1 where exists(select 1 from t1 where coalesce((select e from t1 where (17 not between 13 and t1.c)),t1.c)>=t1.c)),b)),t1.f)+17))} +} {} +do_test randexpr-2.896 { + db eval {SELECT coalesce((select e from t1 where ((abs((select case (~max(f) | ~max(19-t1.d) | cast(avg(11) AS integer)) when min(+t1.d*c) then max(case when 19+13 not between 13 and t1.c or t1.c not in ((b),11,(e)) then d else t1.d end+ -t1.d) else min(a) end from t1))/abs(11)))<17),t1.b)+17 FROM t1 WHERE NOT ((13 in (a,t1.a,~+(e)+t1.c*t1.c | t1.c- -t1.b-t1.b+e*b | t1.e-t1.e-e*coalesce((select max(t1.b) from t1 where t1.a*d<>coalesce((select max(t1.e-t1.b) from t1 where exists(select 1 from t1 where coalesce((select e from t1 where (17 not between 13 and t1.c)),t1.c)>=t1.c)),b)),t1.f)+17)))} +} {517} +do_test randexpr-2.897 { + db eval {SELECT coalesce((select e from t1 where ((abs((select case (~max(f) & ~max(19-t1.d) & cast(avg(11) AS integer)) when min(+t1.d*c) then max(case when 19+13 not between 13 and t1.c or t1.c not in ((b),11,(e)) then d else t1.d end+ -t1.d) else min(a) end from t1))/abs(11)))<17),t1.b)+17 FROM t1 WHERE NOT ((13 in (a,t1.a,~+(e)+t1.c*t1.c | t1.c- -t1.b-t1.b+e*b | t1.e-t1.e-e*coalesce((select max(t1.b) from t1 where t1.a*d<>coalesce((select max(t1.e-t1.b) from t1 where exists(select 1 from t1 where coalesce((select e from t1 where (17 not between 13 and t1.c)),t1.c)>=t1.c)),b)),t1.f)+17)))} +} {517} +do_test randexpr-2.898 { + db eval {SELECT c | coalesce((select max(~b*case +coalesce((select max( -(abs(c)/abs(11))+case when t1.c*17 not in (a,a,c) then t1.e when t1.b in (select 13 from t1 union select (c) from t1) then -(t1.c) else d end* -t1.c+a) from t1 where t1.f>=11),17) | t1.b when t1.b then c else t1.a end) from t1 where t1.f>t1.a),t1.c)+13*17 FROM t1 WHERE t1.e=11),17) | t1.b when t1.b then c else t1.a end) from t1 where t1.f>t1.a),t1.c)+13*17 FROM t1 WHERE NOT (t1.e=11),17) & t1.b when t1.b then c else t1.a end) from t1 where t1.f>t1.a),t1.c)+13*17 FROM t1 WHERE t1.ee) and not exists(select 1 from t1 where (19)=t1.e))),19*t1.e)-t1.c)) | 17))*t1.b)/abs(17))) from t1 where (t1.b) between d and t1.b),t1.c)) | t1.f-c-d) FROM t1 WHERE 13 not in (f,t1.c+11*c,coalesce((select e from t1 where case t1.b when c- -case (select cast(avg(+t1.c*t1.f) AS integer) from t1) when 13*case when not case when -17 in (select (t1.c) from t1 union select t1.c from t1) or t1.f in (t1.b,t1.d,t1.b) then t1.a when 11<>t1.c then e else a end>=(11) and a=d or -t1.f between c and b then e else t1.f end then 19 else t1.d end then t1.c else t1.b end<>13),d))} +} {-35} +do_test randexpr-2.902 { + db eval {SELECT coalesce((select max(a) from t1 where t1.be) and not exists(select 1 from t1 where (19)=t1.e))),19*t1.e)-t1.c)) | 17))*t1.b)/abs(17))) from t1 where (t1.b) between d and t1.b),t1.c)) | t1.f-c-d) FROM t1 WHERE NOT (13 not in (f,t1.c+11*c,coalesce((select e from t1 where case t1.b when c- -case (select cast(avg(+t1.c*t1.f) AS integer) from t1) when 13*case when not case when -17 in (select (t1.c) from t1 union select t1.c from t1) or t1.f in (t1.b,t1.d,t1.b) then t1.a when 11<>t1.c then e else a end>=(11) and a=d or -t1.f between c and b then e else t1.f end then 19 else t1.d end then t1.c else t1.b end<>13),d)))} +} {} +do_test randexpr-2.903 { + db eval {SELECT f+b+(t1.a+c)+(case when (select (cast(avg(coalesce((select max(t1.b) from t1 where case -(select +cast(avg(b-t1.e) AS integer)-abs(cast(avg(~(abs(f)/abs(f))) AS integer)) from t1)+d when 11 then d else 13 end+t1.e<>t1.e),(t1.e))-13+13) AS integer)) from t1)-t1.b<>a then t1.e else e end) FROM t1 WHERE c in (select abs((max(t1.d))) from t1 union select count(*) from t1) and (coalesce((select max(+ -(t1.f-d)* -b) from t1 where not exists(select 1 from t1 where (b not in (coalesce((select t1.e-a from t1 where not t1.a between 13 and f or t1.b in (t1.e,e,17)),11),17,t1.a) and (b<>d)))),b) in (select -min(17) from t1 union select abs(max(e)) from t1))} +} {} +do_test randexpr-2.904 { + db eval {SELECT f+b+(t1.a+c)+(case when (select (cast(avg(coalesce((select max(t1.b) from t1 where case -(select +cast(avg(b-t1.e) AS integer)-abs(cast(avg(~(abs(f)/abs(f))) AS integer)) from t1)+d when 11 then d else 13 end+t1.e<>t1.e),(t1.e))-13+13) AS integer)) from t1)-t1.b<>a then t1.e else e end) FROM t1 WHERE NOT (c in (select abs((max(t1.d))) from t1 union select count(*) from t1) and (coalesce((select max(+ -(t1.f-d)* -b) from t1 where not exists(select 1 from t1 where (b not in (coalesce((select t1.e-a from t1 where not t1.a between 13 and f or t1.b in (t1.e,e,17)),11),17,t1.a) and (b<>d)))),b) in (select -min(17) from t1 union select abs(max(e)) from t1)))} +} {1700} +do_test randexpr-2.905 { + db eval {SELECT case when case when not exists(select 1 from t1 where not exists(select 1 from t1 where (case when (select -min(t1.e) from t1) in (select f from t1 union select d from t1) then +e else d end | t1.e not between t1.a and t1.b))) and not exists(select 1 from t1 where a>=t1.e) and b=e then 13 else coalesce((select 19 from t1 where t1.d>=t1.e),13) end<11*t1.b then 17 when 17 in (19,t1.e, -t1.c) or 17=t1.e) and b=e then 13 else coalesce((select 19 from t1 where t1.d>=t1.e),13) end<11*t1.b then 17 when 17 in (19,t1.e, -t1.c) or 17=t1.e) and b=e then 13 else coalesce((select 19 from t1 where t1.d>=t1.e),13) end<11*t1.b then 17 when 17 in (19,t1.e, -t1.c) or 17t1.a then c else 19 end when t1.c then e else t1.d end when 17 then t1.d else -d end between e and t1.e then 13 when (13<>13) then t1.c else 17 end when exists(select 1 from t1 where (t1.c between b and 11)) then e else f end FROM t1 WHERE ~a* -b+11-case when coalesce((select max(case when (t1.c in (case t1.b when t1.c then 13 else 17 end,17,19)) then case e when a then c else 13 end else c end) from t1 where a between b and t1.c),t1.a)=c or (17>d) then case when f= -t1.a then t1.b when (t1.d)t1.a then c else 19 end when t1.c then e else t1.d end when 17 then t1.d else -d end between e and t1.e then 13 when (13<>13) then t1.c else 17 end when exists(select 1 from t1 where (t1.c between b and 11)) then e else f end FROM t1 WHERE NOT (~a* -b+11-case when coalesce((select max(case when (t1.c in (case t1.b when t1.c then 13 else 17 end,17,19)) then case e when a then c else 13 end else c end) from t1 where a between b and t1.c),t1.a)=c or (17>d) then case when f= -t1.a then t1.b when (t1.d)=t1.f)) and t1.f>t1.a or e<>c then 17 else d end)/abs(a))) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (t1.f) in (t1.c,(t1.e),17)))),t1.a) end+e FROM t1 WHERE exists(select 1 from t1 where 17>(case coalesce((select max((abs(+t1.f-case when 11=(abs((select count(*) from t1)-13*13)/abs(t1.d)) then coalesce((select max(t1.c) from t1 where 19 in (select ((max(19))) from t1 union select min(t1.d) from t1) or -t1.a=t1.a and f<17),t1.e-d) when not exists(select 1 from t1 where t1.b not between (d) and -t1.f) then 11 else t1.a end)/abs(t1.a))) from t1 where t1.e not in ((f),11,t1.f)),t1.c) when b then -t1.a else 13 end)-t1.c)} +} {947} +do_test randexpr-2.911 { + db eval {SELECT +case when e in (13, -b,11) then d else coalesce((select max(13 | d | d+19+(abs(case when (19) between (abs(case f when t1.f then (13) else 17 end)/abs(a)) and d then 19 when (not exists(select 1 from t1 where t1.a>=t1.f)) and t1.f>t1.a or e<>c then 17 else d end)/abs(a))) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (t1.f) in (t1.c,(t1.e),17)))),t1.a) end+e FROM t1 WHERE NOT (exists(select 1 from t1 where 17>(case coalesce((select max((abs(+t1.f-case when 11=(abs((select count(*) from t1)-13*13)/abs(t1.d)) then coalesce((select max(t1.c) from t1 where 19 in (select ((max(19))) from t1 union select min(t1.d) from t1) or -t1.a=t1.a and f<17),t1.e-d) when not exists(select 1 from t1 where t1.b not between (d) and -t1.f) then 11 else t1.a end)/abs(t1.a))) from t1 where t1.e not in ((f),11,t1.f)),t1.c) when b then -t1.a else 13 end)-t1.c))} +} {} +do_test randexpr-2.912 { + db eval {SELECT +case when e in (13, -b,11) then d else coalesce((select max(13 & d & d+19+(abs(case when (19) between (abs(case f when t1.f then (13) else 17 end)/abs(a)) and d then 19 when (not exists(select 1 from t1 where t1.a>=t1.f)) and t1.f>t1.a or e<>c then 17 else d end)/abs(a))) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (t1.f) in (t1.c,(t1.e),17)))),t1.a) end+e FROM t1 WHERE exists(select 1 from t1 where 17>(case coalesce((select max((abs(+t1.f-case when 11=(abs((select count(*) from t1)-13*13)/abs(t1.d)) then coalesce((select max(t1.c) from t1 where 19 in (select ((max(19))) from t1 union select min(t1.d) from t1) or -t1.a=t1.a and f<17),t1.e-d) when not exists(select 1 from t1 where t1.b not between (d) and -t1.f) then 11 else t1.a end)/abs(t1.a))) from t1 where t1.e not in ((f),11,t1.f)),t1.c) when b then -t1.a else 13 end)-t1.c)} +} {500} +do_test randexpr-2.913 { + db eval {SELECT (13*case when exists(select 1 from t1 where exists(select 1 from t1 where coalesce((select max(b) from t1 where t1.b=e),a)<(b-a)+13)) then 11 else t1.e end*coalesce((select 17 from t1 where not ((select cast(avg(13) AS integer) from t1)< -t1.c) and 17 between 13 and 13),case when f=case when exists(select 1 from t1 where (13 in ( -(b)*(select count(*)* -cast(avg(case t1.e when t1.b then (f)-f-f else e end) AS integer)*cast(avg(17) AS integer) | cast(avg((17)) AS integer) | min(d) | count(distinct e) from t1),19+(abs(19)/abs(17))*f,t1.b))) then 11 when 17>t1.f then +a else t1.d end)} +} {28600411} +do_test randexpr-2.914 { + db eval {SELECT (13*case when exists(select 1 from t1 where exists(select 1 from t1 where coalesce((select max(b) from t1 where t1.b=e),a)<(b-a)+13)) then 11 else t1.e end*coalesce((select 17 from t1 where not ((select cast(avg(13) AS integer) from t1)< -t1.c) and 17 between 13 and 13),case when f=case when exists(select 1 from t1 where (13 in ( -(b)*(select count(*)* -cast(avg(case t1.e when t1.b then (f)-f-f else e end) AS integer)*cast(avg(17) AS integer) | cast(avg((17)) AS integer) | min(d) | count(distinct e) from t1),19+(abs(19)/abs(17))*f,t1.b))) then 11 when 17>t1.f then +a else t1.d end))} +} {} +do_test randexpr-2.915 { + db eval {SELECT case when +11 | (select min(case 13+a when e then d else 17-t1.b-~b*a end) from t1)-f*t1.f=(coalesce((select e from t1 where a<=f and not exists(select 1 from t1 where d-case 19 when 11 then (b) else t1.e end not between -t1.a and (t1.c))),e)) then t1.e when -17>=d then t1.f else t1.b end*t1.a FROM t1 WHERE e<=19} +} {} +do_test randexpr-2.916 { + db eval {SELECT case when +11 | (select min(case 13+a when e then d else 17-t1.b-~b*a end) from t1)-f*t1.f=(coalesce((select e from t1 where a<=f and not exists(select 1 from t1 where d-case 19 when 11 then (b) else t1.e end not between -t1.a and (t1.c))),e)) then t1.e when -17>=d then t1.f else t1.b end*t1.a FROM t1 WHERE NOT (e<=19)} +} {20000} +do_test randexpr-2.917 { + db eval {SELECT case when +11 & (select min(case 13+a when e then d else 17-t1.b-~b*a end) from t1)-f*t1.f=(coalesce((select e from t1 where a<=f and not exists(select 1 from t1 where d-case 19 when 11 then (b) else t1.e end not between -t1.a and (t1.c))),e)) then t1.e when -17>=d then t1.f else t1.b end*t1.a FROM t1 WHERE NOT (e<=19)} +} {20000} +do_test randexpr-2.918 { + db eval {SELECT 11-coalesce((select max(coalesce((select max((select abs(case +max((e)) when abs(abs( -count(distinct e))) then +cast(avg(f) AS integer) else count(*) end+count(*)+min( -e)) from t1)) from t1 where t1.b in (select count(distinct (17 | case case when e in (13,t1.a,e) or t1.d>=t1.e then 17 else a end when t1.e then 17 else t1.d end*t1.c)) from t1 union select cast(avg(t1.a) AS integer) from t1)),17)) from t1 where t1.c in (select ~cast(avg(t1.b) AS integer) from t1 union select -(cast(avg(t1.c) AS integer)) from t1)),(t1.c)) FROM t1 WHERE t1.b not in (case when 11 in (select case +min(t1.f) when (+cast(avg((case t1.c when a then f else a end-f)) AS integer)) then +count(distinct (t1.f))-count(distinct t1.f) else count(*) end-count(*) | count(*) from t1 union select min(e) from t1) then (abs(b | 13-f | c)/abs(t1.f)) else t1.c end,f,t1.b) or not -t1.a=11} +} {-289} +do_test randexpr-2.919 { + db eval {SELECT 11-coalesce((select max(coalesce((select max((select abs(case +max((e)) when abs(abs( -count(distinct e))) then +cast(avg(f) AS integer) else count(*) end+count(*)+min( -e)) from t1)) from t1 where t1.b in (select count(distinct (17 | case case when e in (13,t1.a,e) or t1.d>=t1.e then 17 else a end when t1.e then 17 else t1.d end*t1.c)) from t1 union select cast(avg(t1.a) AS integer) from t1)),17)) from t1 where t1.c in (select ~cast(avg(t1.b) AS integer) from t1 union select -(cast(avg(t1.c) AS integer)) from t1)),(t1.c)) FROM t1 WHERE NOT (t1.b not in (case when 11 in (select case +min(t1.f) when (+cast(avg((case t1.c when a then f else a end-f)) AS integer)) then +count(distinct (t1.f))-count(distinct t1.f) else count(*) end-count(*) | count(*) from t1 union select min(e) from t1) then (abs(b | 13-f | c)/abs(t1.f)) else t1.c end,f,t1.b) or not -t1.a=11)} +} {} +do_test randexpr-2.920 { + db eval {SELECT 11-coalesce((select max(coalesce((select max((select abs(case +max((e)) when abs(abs( -count(distinct e))) then +cast(avg(f) AS integer) else count(*) end+count(*)+min( -e)) from t1)) from t1 where t1.b in (select count(distinct (17 & case case when e in (13,t1.a,e) or t1.d>=t1.e then 17 else a end when t1.e then 17 else t1.d end*t1.c)) from t1 union select cast(avg(t1.a) AS integer) from t1)),17)) from t1 where t1.c in (select ~cast(avg(t1.b) AS integer) from t1 union select -(cast(avg(t1.c) AS integer)) from t1)),(t1.c)) FROM t1 WHERE t1.b not in (case when 11 in (select case +min(t1.f) when (+cast(avg((case t1.c when a then f else a end-f)) AS integer)) then +count(distinct (t1.f))-count(distinct t1.f) else count(*) end-count(*) | count(*) from t1 union select min(e) from t1) then (abs(b | 13-f | c)/abs(t1.f)) else t1.c end,f,t1.b) or not -t1.a=11} +} {-289} +do_test randexpr-2.921 { + db eval {SELECT (select -abs(max(+(select +count(*) from t1)))-max(case when b in (select (abs(13)/abs(b)) from t1 union select case when exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(coalesce((select max(+19*t1.e+case t1.f when (abs(f)/abs(t1.f)) then t1.f else e end) from t1 where 19<17),t1.a)))+11 in (select b from t1 union select t1.e from t1))) then d else t1.c end from t1) then f when 13=d then -a else t1.a end) from t1) FROM t1 WHERE ~(select ~ -(min(f)- -cast(avg(f) AS integer)-abs(count(distinct case when t1.d=b then d when e in (select +cast(avg(e) AS integer) from t1 union select count(*) from t1) then t1.f else c end*17*f))) | (count(*)) from t1)-f<>case when (select + -max(t1.e) from t1)+(select -min(17) from t1)*13 between 17 and 19 then t1.b else t1.d end} +} {-101} +do_test randexpr-2.922 { + db eval {SELECT (select -abs(max(+(select +count(*) from t1)))-max(case when b in (select (abs(13)/abs(b)) from t1 union select case when exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(coalesce((select max(+19*t1.e+case t1.f when (abs(f)/abs(t1.f)) then t1.f else e end) from t1 where 19<17),t1.a)))+11 in (select b from t1 union select t1.e from t1))) then d else t1.c end from t1) then f when 13=d then -a else t1.a end) from t1) FROM t1 WHERE NOT (~(select ~ -(min(f)- -cast(avg(f) AS integer)-abs(count(distinct case when t1.d=b then d when e in (select +cast(avg(e) AS integer) from t1 union select count(*) from t1) then t1.f else c end*17*f))) | (count(*)) from t1)-f<>case when (select + -max(t1.e) from t1)+(select -min(17) from t1)*13 between 17 and 19 then t1.b else t1.d end)} +} {} +do_test randexpr-2.923 { + db eval {SELECT case (select ( - - -(+max(c))+min(e)-(count(*))+cast(avg(t1.e) AS integer)-min(t1.a)*(cast(avg(11) AS integer))) from t1) when t1.d then t1.c else case (select max(a) from t1) when -t1.b then case when not 17<>case when t1.e<=t1.d or ((t1.e))=t1.e then t1.f when e>=t1.b then 11 else t1.d end or d in (t1.f,t1.a,t1.a) then c | 17 when t1.f between t1.a and -t1.e then d else t1.c end else t1.c end end-t1.c FROM t1 WHERE not (exists(select 1 from t1 where a<>11+t1.d-t1.a+(select count(distinct t1.d)++max(case e when coalesce((select 11 from t1 where a>=case when coalesce((select f from t1 where exists(select 1 from t1 where 13 in (t1.c,13,t1.a))),(d))+f not between d and t1.e then d else (t1.c) end-13),(d))-t1.d then t1.a else 17 end) from t1)) and not a<(d)*19)} +} {0} +do_test randexpr-2.924 { + db eval {SELECT case (select ( - - -(+max(c))+min(e)-(count(*))+cast(avg(t1.e) AS integer)-min(t1.a)*(cast(avg(11) AS integer))) from t1) when t1.d then t1.c else case (select max(a) from t1) when -t1.b then case when not 17<>case when t1.e<=t1.d or ((t1.e))=t1.e then t1.f when e>=t1.b then 11 else t1.d end or d in (t1.f,t1.a,t1.a) then c | 17 when t1.f between t1.a and -t1.e then d else t1.c end else t1.c end end-t1.c FROM t1 WHERE NOT (not (exists(select 1 from t1 where a<>11+t1.d-t1.a+(select count(distinct t1.d)++max(case e when coalesce((select 11 from t1 where a>=case when coalesce((select f from t1 where exists(select 1 from t1 where 13 in (t1.c,13,t1.a))),(d))+f not between d and t1.e then d else (t1.c) end-13),(d))-t1.d then t1.a else 17 end) from t1)) and not a<(d)*19))} +} {} +do_test randexpr-2.925 { + db eval {SELECT case (select ( - - -(+max(c))+min(e)-(count(*))+cast(avg(t1.e) AS integer)-min(t1.a)*(cast(avg(11) AS integer))) from t1) when t1.d then t1.c else case (select max(a) from t1) when -t1.b then case when not 17<>case when t1.e<=t1.d or ((t1.e))=t1.e then t1.f when e>=t1.b then 11 else t1.d end or d in (t1.f,t1.a,t1.a) then c & 17 when t1.f between t1.a and -t1.e then d else t1.c end else t1.c end end-t1.c FROM t1 WHERE not (exists(select 1 from t1 where a<>11+t1.d-t1.a+(select count(distinct t1.d)++max(case e when coalesce((select 11 from t1 where a>=case when coalesce((select f from t1 where exists(select 1 from t1 where 13 in (t1.c,13,t1.a))),(d))+f not between d and t1.e then d else (t1.c) end-13),(d))-t1.d then t1.a else 17 end) from t1)) and not a<(d)*19)} +} {0} +do_test randexpr-2.926 { + db eval {SELECT case t1.b when c*(case when ((select ++case abs(cast(avg(a) AS integer))*min(c) when min(t1.c) then cast(avg(t1.b) AS integer) else count(*) end | (count(distinct t1.c)) | ((max(t1.a))) | count(distinct b) from t1) not between t1.e and 11 and coalesce((select max(e) from t1 where a between t1.c and c+b),e) in (select t1.d from t1 union select t1.b from t1) or (not exists(select 1 from t1 where 13<>t1.a))) then 11*b else t1.b end) then t1.c else e end FROM t1 WHERE exists(select 1 from t1 where t1.d>=f)} +} {} +do_test randexpr-2.927 { + db eval {SELECT case t1.b when c*(case when ((select ++case abs(cast(avg(a) AS integer))*min(c) when min(t1.c) then cast(avg(t1.b) AS integer) else count(*) end | (count(distinct t1.c)) | ((max(t1.a))) | count(distinct b) from t1) not between t1.e and 11 and coalesce((select max(e) from t1 where a between t1.c and c+b),e) in (select t1.d from t1 union select t1.b from t1) or (not exists(select 1 from t1 where 13<>t1.a))) then 11*b else t1.b end) then t1.c else e end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d>=f))} +} {500} +do_test randexpr-2.928 { + db eval {SELECT case t1.b when c*(case when ((select ++case abs(cast(avg(a) AS integer))*min(c) when min(t1.c) then cast(avg(t1.b) AS integer) else count(*) end & (count(distinct t1.c)) & ((max(t1.a))) & count(distinct b) from t1) not between t1.e and 11 and coalesce((select max(e) from t1 where a between t1.c and c+b),e) in (select t1.d from t1 union select t1.b from t1) or (not exists(select 1 from t1 where 13<>t1.a))) then 11*b else t1.b end) then t1.c else e end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d>=f))} +} {500} +do_test randexpr-2.929 { + db eval {SELECT d-coalesce((select d from t1 where case when ~11*a*c>=17 then coalesce((select (abs(t1.e+c+(abs(f*(select abs((min(e))) from t1)-t1.f)/abs( - -a))-a)/abs(t1.d)) from t1 where f not in (e,b,t1.f) and c<>f),f)*19 else f end in (b,e,17)),13)-19 FROM t1 WHERE not f>=11} +} {} +do_test randexpr-2.930 { + db eval {SELECT d-coalesce((select d from t1 where case when ~11*a*c>=17 then coalesce((select (abs(t1.e+c+(abs(f*(select abs((min(e))) from t1)-t1.f)/abs( - -a))-a)/abs(t1.d)) from t1 where f not in (e,b,t1.f) and c<>f),f)*19 else f end in (b,e,17)),13)-19 FROM t1 WHERE NOT (not f>=11)} +} {368} +do_test randexpr-2.931 { + db eval {SELECT f*t1.d+coalesce((select a+17-t1.e from t1 where 13=t1.f and not (t1.f | b*t1.d-t1.c*coalesce((select max(coalesce((select t1.f from t1 where f not in (13,a,d)),d)) from t1 where t1.a in (select cast(avg(c) AS integer) from t1 union select count(distinct b)*count(distinct t1.c) from t1)),((17)))+ -b+19+13)=t1.f and 19>=t1.a or - -a>=t1.b),a) FROM t1 WHERE f not in (coalesce((select max(19) from t1 where (t1.e<=+t1.f*case when ~(abs(b)/abs(b)) in (f,t1.d,17) then (abs(t1.e-11 | d)/abs(coalesce((select d from t1 where not coalesce((select t1.a from t1 where not exists(select 1 from t1 where c>=t1.c)),d) in (select count(distinct f)*cast(avg(19) AS integer) from t1 union select count(distinct d) from t1)),13))) when not 11<=t1.a then t1.f else 19 end-19)),f)-17, -a,e)} +} {240100} +do_test randexpr-2.932 { + db eval {SELECT f*t1.d+coalesce((select a+17-t1.e from t1 where 13=t1.f and not (t1.f | b*t1.d-t1.c*coalesce((select max(coalesce((select t1.f from t1 where f not in (13,a,d)),d)) from t1 where t1.a in (select cast(avg(c) AS integer) from t1 union select count(distinct b)*count(distinct t1.c) from t1)),((17)))+ -b+19+13)=t1.f and 19>=t1.a or - -a>=t1.b),a) FROM t1 WHERE NOT (f not in (coalesce((select max(19) from t1 where (t1.e<=+t1.f*case when ~(abs(b)/abs(b)) in (f,t1.d,17) then (abs(t1.e-11 | d)/abs(coalesce((select d from t1 where not coalesce((select t1.a from t1 where not exists(select 1 from t1 where c>=t1.c)),d) in (select count(distinct f)*cast(avg(19) AS integer) from t1 union select count(distinct d) from t1)),13))) when not 11<=t1.a then t1.f else 19 end-19)),f)-17, -a,e))} +} {} +do_test randexpr-2.933 { + db eval {SELECT f*t1.d+coalesce((select a+17-t1.e from t1 where 13=t1.f and not (t1.f & b*t1.d-t1.c*coalesce((select max(coalesce((select t1.f from t1 where f not in (13,a,d)),d)) from t1 where t1.a in (select cast(avg(c) AS integer) from t1 union select count(distinct b)*count(distinct t1.c) from t1)),((17)))+ -b+19+13)=t1.f and 19>=t1.a or - -a>=t1.b),a) FROM t1 WHERE f not in (coalesce((select max(19) from t1 where (t1.e<=+t1.f*case when ~(abs(b)/abs(b)) in (f,t1.d,17) then (abs(t1.e-11 | d)/abs(coalesce((select d from t1 where not coalesce((select t1.a from t1 where not exists(select 1 from t1 where c>=t1.c)),d) in (select count(distinct f)*cast(avg(19) AS integer) from t1 union select count(distinct d) from t1)),13))) when not 11<=t1.a then t1.f else 19 end-19)),f)-17, -a,e)} +} {240100} +do_test randexpr-2.934 { + db eval {SELECT coalesce((select case e*+(abs(t1.f-t1.b)/abs(e))-d when coalesce((select t1.e from t1 where exists(select 1 from t1 where +d+ -t1.e not between case when (abs(b)/abs(t1.b)) between a and 17 then t1.b when not 11 not between b and d then 19 else 19 end and t1.f and t1.a between 17 and b)), -13) then (t1.a) else 13 end from t1 where 17 between b and 13), -19) | c FROM t1 WHERE case when t1.e*t1.b | f+d | f+11+(a)-+a+ -t1.c-t1.f | coalesce((select case t1.e when 17 then e else t1.a end from t1 where t1.ab then e else t1.d end end-11>=13),e) | 13 FROM t1 WHERE not exists(select 1 from t1 where t1.c< -d or t1.e between c and -t1.d or d<=17)} +} {10143} +do_test randexpr-2.940 { + db eval {SELECT d*(select - - -max( -(abs(e)/abs(~t1.c))) from t1)-13 | coalesce((select max(+t1.a*a) from t1 where t1.e+case e when a then t1.f+(select case ~ -max(d)* - -cast(avg(c) AS integer) when -min( -t1.b) then min(t1.b) else count(distinct 13) end from t1)-a else ~case when t1.f not in (b,b,a) or c between d and t1.a then c when t1.b>b then e else t1.d end end-11>=13),e) | 13 FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.c< -d or t1.e between c and -t1.d or d<=17))} +} {} +do_test randexpr-2.941 { + db eval {SELECT d*(select - - -max( -(abs(e)/abs(~t1.c))) from t1)-13 & coalesce((select max(+t1.a*a) from t1 where t1.e+case e when a then t1.f+(select case ~ -max(d)* - -cast(avg(c) AS integer) when -min( -t1.b) then min(t1.b) else count(distinct 13) end from t1)-a else ~case when t1.f not in (b,b,a) or c between d and t1.a then c when t1.b>b then e else t1.d end end-11>=13),e) & 13 FROM t1 WHERE not exists(select 1 from t1 where t1.c< -d or t1.e between c and -t1.d or d<=17)} +} {0} +do_test randexpr-2.942 { + db eval {SELECT t1.c*+case when a<>+case when b>t1.e or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e in (select coalesce((select b from t1 where (d( -t1.d)),(( -b))) from t1 union select t1.d from t1))) then (select -max(t1.e)-count(*) from t1) else (t1.c) end+b+(t1.f) | f | e then t1.d when t1.f not in (19,13,e) then 13 else 11 end FROM t1 WHERE (f<>coalesce((select max(a) from t1 where (exists(select 1 from t1 where c between t1.b and case when (abs(19)/abs(t1.f)) in (t1.f,17,t1.a) then t1.b when t1.d<=t1.a then t1.a else c end or c=b and c>=t1.d and t1.d between c and t1.c)),e+case (select count(distinct case 19 when 13 then t1.b else 11 end) from t1) when 13 then b else t1.b end)-17-17)} +} {120000} +do_test randexpr-2.943 { + db eval {SELECT t1.c*+case when a<>+case when b>t1.e or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e in (select coalesce((select b from t1 where (d( -t1.d)),(( -b))) from t1 union select t1.d from t1))) then (select -max(t1.e)-count(*) from t1) else (t1.c) end+b+(t1.f) | f | e then t1.d when t1.f not in (19,13,e) then 13 else 11 end FROM t1 WHERE NOT ((f<>coalesce((select max(a) from t1 where (exists(select 1 from t1 where c between t1.b and case when (abs(19)/abs(t1.f)) in (t1.f,17,t1.a) then t1.b when t1.d<=t1.a then t1.a else c end or c=b and c>=t1.d and t1.d between c and t1.c)),e+case (select count(distinct case 19 when 13 then t1.b else 11 end) from t1) when 13 then b else t1.b end)-17-17))} +} {} +do_test randexpr-2.944 { + db eval {SELECT t1.c*+case when a<>+case when b>t1.e or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e in (select coalesce((select b from t1 where (d( -t1.d)),(( -b))) from t1 union select t1.d from t1))) then (select -max(t1.e)-count(*) from t1) else (t1.c) end+b+(t1.f) & f & e then t1.d when t1.f not in (19,13,e) then 13 else 11 end FROM t1 WHERE (f<>coalesce((select max(a) from t1 where (exists(select 1 from t1 where c between t1.b and case when (abs(19)/abs(t1.f)) in (t1.f,17,t1.a) then t1.b when t1.d<=t1.a then t1.a else c end or c=b and c>=t1.d and t1.d between c and t1.c)),e+case (select count(distinct case 19 when 13 then t1.b else 11 end) from t1) when 13 then b else t1.b end)-17-17)} +} {120000} +do_test randexpr-2.945 { + db eval {SELECT case when (e)- -((select case min(case when e in (select coalesce((select max(d) from t1 where 13<>(t1.d-e)),e) from t1 union select c from t1) then d else -11 end+a) when count(distinct -f) then count(*) else -(case cast(avg(17) AS integer)- -count(distinct t1.c)+cast(avg(b) AS integer) when -max(11) then count(*) else cast(avg(t1.e) AS integer) end+max(t1.f)) end from t1))<=t1.b | t1.e then t1.d when not exists(select 1 from t1 where c<>13) then 11 else d end FROM t1 WHERE (select max(t1.a*case f when b then ~case when not exists(select 1 from t1 where f-d>(select abs(cast(avg(~17+b+d) AS integer)) from t1) or f-e in (select b from t1 union select t1.d from t1) or exists(select 1 from t1 where 13<>b)) then (abs(a)/abs( -d)) when (d(t1.d-e)),e) from t1 union select c from t1) then d else -11 end+a) when count(distinct -f) then count(*) else -(case cast(avg(17) AS integer)- -count(distinct t1.c)+cast(avg(b) AS integer) when -max(11) then count(*) else cast(avg(t1.e) AS integer) end+max(t1.f)) end from t1))<=t1.b | t1.e then t1.d when not exists(select 1 from t1 where c<>13) then 11 else d end FROM t1 WHERE NOT ((select max(t1.a*case f when b then ~case when not exists(select 1 from t1 where f-d>(select abs(cast(avg(~17+b+d) AS integer)) from t1) or f-e in (select b from t1 union select t1.d from t1) or exists(select 1 from t1 where 13<>b)) then (abs(a)/abs( -d)) when (d(t1.d-e)),e) from t1 union select c from t1) then d else -11 end+a) when count(distinct -f) then count(*) else -(case cast(avg(17) AS integer)- -count(distinct t1.c)+cast(avg(b) AS integer) when -max(11) then count(*) else cast(avg(t1.e) AS integer) end+max(t1.f)) end from t1))<=t1.b & t1.e then t1.d when not exists(select 1 from t1 where c<>13) then 11 else d end FROM t1 WHERE NOT ((select max(t1.a*case f when b then ~case when not exists(select 1 from t1 where f-d>(select abs(cast(avg(~17+b+d) AS integer)) from t1) or f-e in (select b from t1 union select t1.d from t1) or exists(select 1 from t1 where 13<>b)) then (abs(a)/abs( -d)) when (d=e and d between d and a then t1.c when (t1.c>19) then -11 else a end from t1 where ac then t1.e else -d end-t1.e) between b and 11 then b when exists(select 1 from t1 where a<=d) then 11 else 13 end) then cast(avg(t1.b) AS integer)-(cast(avg(11) AS integer)-min(a))-count(distinct -e) else cast(avg(13) AS integer) end*max(b) from t1) or (t1.f not between t1.d and 17 | 19*e)} +} {} +do_test randexpr-2.949 { + db eval {SELECT (t1.b+coalesce((select case when e-13+11 | f+case when not t1.b not between t1.f and t1.f then e else (t1.e) end-c-b+c>=e and d between d and a then t1.c when (t1.c>19) then -11 else a end from t1 where ac then t1.e else -d end-t1.e) between b and 11 then b when exists(select 1 from t1 where a<=d) then 11 else 13 end) then cast(avg(t1.b) AS integer)-(cast(avg(11) AS integer)-min(a))-count(distinct -e) else cast(avg(13) AS integer) end*max(b) from t1) or (t1.f not between t1.d and 17 | 19*e))} +} {3413413} +do_test randexpr-2.950 { + db eval {SELECT (t1.b+coalesce((select case when e-13+11 & f+case when not t1.b not between t1.f and t1.f then e else (t1.e) end-c-b+c>=e and d between d and a then t1.c when (t1.c>19) then -11 else a end from t1 where ac then t1.e else -d end-t1.e) between b and 11 then b when exists(select 1 from t1 where a<=d) then 11 else 13 end) then cast(avg(t1.b) AS integer)-(cast(avg(11) AS integer)-min(a))-count(distinct -e) else cast(avg(13) AS integer) end*max(b) from t1) or (t1.f not between t1.d and 17 | 19*e))} +} {3413413} +do_test randexpr-2.951 { + db eval {SELECT coalesce((select max(+19) from t1 where t1.f>=(abs(19)/abs(t1.c*(select count(distinct (abs(t1.f)/abs(t1.c))*coalesce((select max(case when (select count(*) from t1)*t1.f in (t1.b,17,t1.f) then d when t1.e not in (t1.b,t1.a,t1.b) then -17 else t1.d end) from t1 where (11 not in (t1.b,(f),t1.c)) and t1.c>=t1.f),e)) from t1))) or ((t1.d<=t1.b))),13) FROM t1 WHERE t1.a<>(coalesce((select coalesce((select max(t1.a) from t1 where case -t1.c when t1.b then coalesce((select t1.b from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where ((select count(*)++count(distinct a) from t1) not between b and +(17))))),19)*t1.e else f end<=(t1.b)),t1.c) from t1 where d<>b),13)-17+a)+d+(19)+a or d between 11 and -11} +} {19} +do_test randexpr-2.952 { + db eval {SELECT coalesce((select max(+19) from t1 where t1.f>=(abs(19)/abs(t1.c*(select count(distinct (abs(t1.f)/abs(t1.c))*coalesce((select max(case when (select count(*) from t1)*t1.f in (t1.b,17,t1.f) then d when t1.e not in (t1.b,t1.a,t1.b) then -17 else t1.d end) from t1 where (11 not in (t1.b,(f),t1.c)) and t1.c>=t1.f),e)) from t1))) or ((t1.d<=t1.b))),13) FROM t1 WHERE NOT (t1.a<>(coalesce((select coalesce((select max(t1.a) from t1 where case -t1.c when t1.b then coalesce((select t1.b from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where ((select count(*)++count(distinct a) from t1) not between b and +(17))))),19)*t1.e else f end<=(t1.b)),t1.c) from t1 where d<>b),13)-17+a)+d+(19)+a or d between 11 and -11)} +} {} +do_test randexpr-2.953 { + db eval {SELECT t1.b-coalesce((select max(~t1.a) from t1 where coalesce((select max(t1.d) from t1 where coalesce((select max(coalesce((select t1.c*t1.d from t1 where not f>=a-t1.c+ -coalesce((select t1.f*e from t1 where (not exists(select 1 from t1 where d<=19))),b)-d),13)* -e) from t1 where (d<19 or 13 not between t1.f and t1.d)),11) between 17 and 19),t1.c)< -b),d) FROM t1 WHERE +case when b in (b+~b+t1.f,coalesce((select max(13) from t1 where exists(select 1 from t1 where 17<>+a or not exists(select 1 from t1 where e+19=f))),(e)),case when c>case when coalesce((select 13 from t1 where f>=t1.b and c not between t1.e and t1.d),11) in (select (case max(11) when (min(b)) then min( -d) else cast(avg(t1.e) AS integer) end) from t1 union select max(19) from t1) then t1.d else 13 end then t1.f else t1.e end) or b>=(t1.f) then t1.e else t1.e end*b>f} +} {-200} +do_test randexpr-2.954 { + db eval {SELECT t1.b-coalesce((select max(~t1.a) from t1 where coalesce((select max(t1.d) from t1 where coalesce((select max(coalesce((select t1.c*t1.d from t1 where not f>=a-t1.c+ -coalesce((select t1.f*e from t1 where (not exists(select 1 from t1 where d<=19))),b)-d),13)* -e) from t1 where (d<19 or 13 not between t1.f and t1.d)),11) between 17 and 19),t1.c)< -b),d) FROM t1 WHERE NOT (+case when b in (b+~b+t1.f,coalesce((select max(13) from t1 where exists(select 1 from t1 where 17<>+a or not exists(select 1 from t1 where e+19=f))),(e)),case when c>case when coalesce((select 13 from t1 where f>=t1.b and c not between t1.e and t1.d),11) in (select (case max(11) when (min(b)) then min( -d) else cast(avg(t1.e) AS integer) end) from t1 union select max(19) from t1) then t1.d else 13 end then t1.f else t1.e end) or b>=(t1.f) then t1.e else t1.e end*b>f)} +} {} +do_test randexpr-2.955 { + db eval {SELECT (select count(distinct + - -f-c-17*a+(t1.d)-+((select abs( - - -count(distinct 13)-count(*)*count(distinct t1.d)*count(*))-cast(avg(f) AS integer) from t1))-~19+13- -d*t1.e*(19)+ -f- -b) from t1)-e FROM t1 WHERE not t1.c between t1.f and coalesce((select coalesce((select case when exists(select 1 from t1 where +~f=case when d<>t1.d then t1.f else -d end and d between 17 and t1.c) then ~case when a in (d,c,t1.d) then 17 else t1.f end when f=f then d else -b end from t1 where c>f),e) from t1 where not exists(select 1 from t1 where t1.d<=c) and 19=(11) and t1.e<>19),a)} +} {-499} +do_test randexpr-2.956 { + db eval {SELECT (select count(distinct + - -f-c-17*a+(t1.d)-+((select abs( - - -count(distinct 13)-count(*)*count(distinct t1.d)*count(*))-cast(avg(f) AS integer) from t1))-~19+13- -d*t1.e*(19)+ -f- -b) from t1)-e FROM t1 WHERE NOT (not t1.c between t1.f and coalesce((select coalesce((select case when exists(select 1 from t1 where +~f=case when d<>t1.d then t1.f else -d end and d between 17 and t1.c) then ~case when a in (d,c,t1.d) then 17 else t1.f end when f=f then d else -b end from t1 where c>f),e) from t1 where not exists(select 1 from t1 where t1.d<=c) and 19=(11) and t1.e<>19),a))} +} {} +do_test randexpr-2.957 { + db eval {SELECT case when f-t1.b*coalesce((select max(11) from t1 where exists(select 1 from t1 where (abs(t1.b)/abs(13-11))=(19+c))),coalesce((select t1.c | f from t1 where (abs(c*19)/abs(17))=t1.e),19))-e between t1.f and -((19)) and 13 not between t1.c and 11 and not exists(select 1 from t1 where t1.b>b) then t1.d when t1.c>=13 then c else f end FROM t1 WHERE e-t1.c=+e*~coalesce((select max(t1.f) from t1 where (t1.f in (coalesce((select max(11) from t1 where -13<>(13)-(select (count(*)) from t1)*t1.f and ( -11+t1.b+b*b-(select max(13) from t1)) in (t1.f,a,f)),d),17,13))),t1.f)-e} +} {} +do_test randexpr-2.958 { + db eval {SELECT case when f-t1.b*coalesce((select max(11) from t1 where exists(select 1 from t1 where (abs(t1.b)/abs(13-11))=(19+c))),coalesce((select t1.c | f from t1 where (abs(c*19)/abs(17))=t1.e),19))-e between t1.f and -((19)) and 13 not between t1.c and 11 and not exists(select 1 from t1 where t1.b>b) then t1.d when t1.c>=13 then c else f end FROM t1 WHERE NOT (e-t1.c=+e*~coalesce((select max(t1.f) from t1 where (t1.f in (coalesce((select max(11) from t1 where -13<>(13)-(select (count(*)) from t1)*t1.f and ( -11+t1.b+b*b-(select max(13) from t1)) in (t1.f,a,f)),d),17,13))),t1.f)-e)} +} {300} +do_test randexpr-2.959 { + db eval {SELECT case when f-t1.b*coalesce((select max(11) from t1 where exists(select 1 from t1 where (abs(t1.b)/abs(13-11))=(19+c))),coalesce((select t1.c & f from t1 where (abs(c*19)/abs(17))=t1.e),19))-e between t1.f and -((19)) and 13 not between t1.c and 11 and not exists(select 1 from t1 where t1.b>b) then t1.d when t1.c>=13 then c else f end FROM t1 WHERE NOT (e-t1.c=+e*~coalesce((select max(t1.f) from t1 where (t1.f in (coalesce((select max(11) from t1 where -13<>(13)-(select (count(*)) from t1)*t1.f and ( -11+t1.b+b*b-(select max(13) from t1)) in (t1.f,a,f)),d),17,13))),t1.f)-e)} +} {300} +do_test randexpr-2.960 { + db eval {SELECT t1.e+case when coalesce((select -(abs(t1.e)/abs(t1.c-t1.e)) from t1 where d | d between -t1.d and ~case t1.d when t1.f then ((abs((select ((min(b)+abs(cast(avg(t1.a) AS integer)*(max(19))))-(cast(avg(t1.d) AS integer))) from t1)*~f)/abs(t1.a*t1.c)))*17 else 19 end),f)- -c<>t1.c then f else t1.f end FROM t1 WHERE 19*coalesce((select max(a) from t1 where not (select count(distinct ~t1.b | t1.d) from t1)t1.e then c when -b<11 then t1.c else -t1.e end and not d in ( -t1.d,t1.a,f) and c=t1.f and f<>t1.a),t1.b) between t1.a and b} +} {} +do_test randexpr-2.961 { + db eval {SELECT t1.e+case when coalesce((select -(abs(t1.e)/abs(t1.c-t1.e)) from t1 where d | d between -t1.d and ~case t1.d when t1.f then ((abs((select ((min(b)+abs(cast(avg(t1.a) AS integer)*(max(19))))-(cast(avg(t1.d) AS integer))) from t1)*~f)/abs(t1.a*t1.c)))*17 else 19 end),f)- -c<>t1.c then f else t1.f end FROM t1 WHERE NOT (19*coalesce((select max(a) from t1 where not (select count(distinct ~t1.b | t1.d) from t1)t1.e then c when -b<11 then t1.c else -t1.e end and not d in ( -t1.d,t1.a,f) and c=t1.f and f<>t1.a),t1.b) between t1.a and b)} +} {1100} +do_test randexpr-2.962 { + db eval {SELECT t1.e+case when coalesce((select -(abs(t1.e)/abs(t1.c-t1.e)) from t1 where d & d between -t1.d and ~case t1.d when t1.f then ((abs((select ((min(b)+abs(cast(avg(t1.a) AS integer)*(max(19))))-(cast(avg(t1.d) AS integer))) from t1)*~f)/abs(t1.a*t1.c)))*17 else 19 end),f)- -c<>t1.c then f else t1.f end FROM t1 WHERE NOT (19*coalesce((select max(a) from t1 where not (select count(distinct ~t1.b | t1.d) from t1)t1.e then c when -b<11 then t1.c else -t1.e end and not d in ( -t1.d,t1.a,f) and c=t1.f and f<>t1.a),t1.b) between t1.a and b)} +} {1100} +do_test randexpr-2.963 { + db eval {SELECT t1.b*coalesce((select max(e) from t1 where ((t1.d))<=case case when +coalesce((select (abs(t1.a)/abs(c))-(abs( -e)/abs(11* -t1.b+t1.d* -c))-t1.c from t1 where not exists(select 1 from t1 where t1.c=(11))), -11) between 17 and t1.a then t1.a when t1.b>t1.e then (b) else b end-c when d then d else t1.f end),((t1.e))) FROM t1 WHERE ~ -case when not exists(select 1 from t1 where t1.b between b and 11 | d) then -(abs(17+d)/abs(e)) else case when not (t1.d>=case when case a when case t1.f when (e) then 17 else 19 end then 13 else 19 end in (t1.e,b,((t1.b))) then d when t1.d not in (19,t1.a, -c) then 11 else -a end) then 11 else c end end*17*t1.b not in (a,b,13)} +} {100000} +do_test randexpr-2.964 { + db eval {SELECT t1.b*coalesce((select max(e) from t1 where ((t1.d))<=case case when +coalesce((select (abs(t1.a)/abs(c))-(abs( -e)/abs(11* -t1.b+t1.d* -c))-t1.c from t1 where not exists(select 1 from t1 where t1.c=(11))), -11) between 17 and t1.a then t1.a when t1.b>t1.e then (b) else b end-c when d then d else t1.f end),((t1.e))) FROM t1 WHERE NOT (~ -case when not exists(select 1 from t1 where t1.b between b and 11 | d) then -(abs(17+d)/abs(e)) else case when not (t1.d>=case when case a when case t1.f when (e) then 17 else 19 end then 13 else 19 end in (t1.e,b,((t1.b))) then d when t1.d not in (19,t1.a, -c) then 11 else -a end) then 11 else c end end*17*t1.b not in (a,b,13))} +} {} +do_test randexpr-2.965 { + db eval {SELECT e*case +case when not (select max(17) from t1)>=case when not d=c+t1.c then 11 else 11 end or (c in (select t1.c from t1 union select c from t1) or 11<=t1.a) or d<=11 or 19 in ( -13,d,19) or a not between 13 and (t1.c) then case when t1.f<=(t1.a) then t1.e+13*e when (t1.b) not between f and a then c else 11 end*11 else a end when 19 then t1.a else 17 end FROM t1 WHERE b<>17} +} {8500} +do_test randexpr-2.966 { + db eval {SELECT e*case +case when not (select max(17) from t1)>=case when not d=c+t1.c then 11 else 11 end or (c in (select t1.c from t1 union select c from t1) or 11<=t1.a) or d<=11 or 19 in ( -13,d,19) or a not between 13 and (t1.c) then case when t1.f<=(t1.a) then t1.e+13*e when (t1.b) not between f and a then c else 11 end*11 else a end when 19 then t1.a else 17 end FROM t1 WHERE NOT (b<>17)} +} {} +do_test randexpr-2.967 { + db eval {SELECT (abs(case when (13+e in (select min(a) | case abs(min(case when t1.e in (select b from t1 union select a from t1) then t1.e when t1.b=t1.c then t1.b else c end-f)) when ~(cast(avg(c) AS integer)) then min(t1.e) else count(*) end from t1 union select min(f) from t1)) and t1.d not between c and 13 then coalesce((select t1.d from t1 where t1.e<>a),19)-t1.d else 19 end)/abs(c))-c+11+c FROM t1 WHERE t1.ea),19)-t1.d else 19 end)/abs(c))-c+11+c FROM t1 WHERE NOT (t1.ea),19)-t1.d else 19 end)/abs(c))-c+11+c FROM t1 WHERE NOT (t1.e=t1.f)} +} {600} +do_test randexpr-2.971 { + db eval {SELECT case when case when not exists(select 1 from t1 where (11 not between ~~t1.d-case c when coalesce((select case f when coalesce((select max(t1.f) from t1 where 11 not in (((13)),d,t1.d)),11) then f else a end from t1 where 11 not between (t1.a) and 17),t1.c)-c*17 then (17) else t1.b end+t1.d+t1.a and d)) then t1.e-11+19 else (d) end*d<=11 then t1.b else f end FROM t1 WHERE NOT (not exists(select 1 from t1 where d>=t1.f))} +} {} +do_test randexpr-2.972 { + db eval {SELECT 13 | t1.c+case when (not t1.d-c between +t1.b and -coalesce((select (select count(distinct 17) from t1)*a from t1 where -case when not t1.f in (select count(distinct 13) from t1 union select min( -t1.a) from t1) then case when (t1.e)< -11 then -c else t1.a end else d end-c*t1.a-d+ -e-t1.a not in (17,e,t1.a)),b) | t1.f) then c else 11 end FROM t1 WHERE case when (+e | (t1.e) | 11)<>b then t1.b when t1.e<>~(case when (t1.a*b) in (select d from t1 union select b from t1) or t1.c not in (t1.a,t1.d,13) and t1.f in (select case min(19) when min(17) then min(19) else count(distinct t1.e) end from t1 union select (count(*)) from t1) then t1.f else b end)+11 then b else 13 end+t1.d between b and 17} +} {} +do_test randexpr-2.973 { + db eval {SELECT 13 | t1.c+case when (not t1.d-c between +t1.b and -coalesce((select (select count(distinct 17) from t1)*a from t1 where -case when not t1.f in (select count(distinct 13) from t1 union select min( -t1.a) from t1) then case when (t1.e)< -11 then -c else t1.a end else d end-c*t1.a-d+ -e-t1.a not in (17,e,t1.a)),b) | t1.f) then c else 11 end FROM t1 WHERE NOT (case when (+e | (t1.e) | 11)<>b then t1.b when t1.e<>~(case when (t1.a*b) in (select d from t1 union select b from t1) or t1.c not in (t1.a,t1.d,13) and t1.f in (select case min(19) when min(17) then min(19) else count(distinct t1.e) end from t1 union select (count(*)) from t1) then t1.f else b end)+11 then b else 13 end+t1.d between b and 17)} +} {605} +do_test randexpr-2.974 { + db eval {SELECT 13 & t1.c+case when (not t1.d-c between +t1.b and -coalesce((select (select count(distinct 17) from t1)*a from t1 where -case when not t1.f in (select count(distinct 13) from t1 union select min( -t1.a) from t1) then case when (t1.e)< -11 then -c else t1.a end else d end-c*t1.a-d+ -e-t1.a not in (17,e,t1.a)),b) & t1.f) then c else 11 end FROM t1 WHERE NOT (case when (+e | (t1.e) | 11)<>b then t1.b when t1.e<>~(case when (t1.a*b) in (select d from t1 union select b from t1) or t1.c not in (t1.a,t1.d,13) and t1.f in (select case min(19) when min(17) then min(19) else count(distinct t1.e) end from t1 union select (count(*)) from t1) then t1.f else b end)+11 then b else 13 end+t1.d between b and 17)} +} {8} +do_test randexpr-2.975 { + db eval {SELECT case when case when t1.a<>t1.d then d*t1.a*11-e-(+11+d)-e else (select case -count(distinct t1.e) when cast(avg(b) AS integer) then count(distinct t1.d) else cast(avg(13) AS integer) end*cast(avg(19) AS integer) from t1) end<>case e when e then t1.e else (t1.f) end or not exists(select 1 from t1 where 19=f) and -t1.d>t1.e then t1.e+e*e when 11=t1.c then e else c end FROM t1 WHERE ~c>(case when t1.e<=e then case when case when 17+f in (d,t1.d | t1.c,t1.b) and 13<>19 or not t1.ct1.d then d*t1.a*11-e-(+11+d)-e else (select case -count(distinct t1.e) when cast(avg(b) AS integer) then count(distinct t1.d) else cast(avg(13) AS integer) end*cast(avg(19) AS integer) from t1) end<>case e when e then t1.e else (t1.f) end or not exists(select 1 from t1 where 19=f) and -t1.d>t1.e then t1.e+e*e when 11=t1.c then e else c end FROM t1 WHERE NOT (~c>(case when t1.e<=e then case when case when 17+f in (d,t1.d | t1.c,t1.b) and 13<>19 or not t1.c=t1.f))) and t1.c not in (17,b,e) then a else (select count(distinct t1.d) from t1) end FROM t1 WHERE (select (count(*)) from t1) between 11 and t1.d} +} {} +do_test randexpr-2.981 { + db eval {SELECT ~case when exists(select 1 from t1 where ((coalesce((select d from t1 where t1.e-f | +t1.d between t1.c and t1.a or exists(select 1 from t1 where 19 in (11,11,13)) and 17 in (select case min(d) when count(*) then (min(13)) else -(cast(avg( -c) AS integer)) end*count(distinct 19) from t1 union select count(distinct e) from t1)),f) | c*b<= -b or not not t1.c<13 or (t1.f)>=t1.f))) and t1.c not in (17,b,e) then a else (select count(distinct t1.d) from t1) end FROM t1 WHERE NOT ((select (count(*)) from t1) between 11 and t1.d)} +} {-101} +do_test randexpr-2.982 { + db eval {SELECT ~case when exists(select 1 from t1 where ((coalesce((select d from t1 where t1.e-f & +t1.d between t1.c and t1.a or exists(select 1 from t1 where 19 in (11,11,13)) and 17 in (select case min(d) when count(*) then (min(13)) else -(cast(avg( -c) AS integer)) end*count(distinct 19) from t1 union select count(distinct e) from t1)),f) & c*b<= -b or not not t1.c<13 or (t1.f)>=t1.f))) and t1.c not in (17,b,e) then a else (select count(distinct t1.d) from t1) end FROM t1 WHERE NOT ((select (count(*)) from t1) between 11 and t1.d)} +} {-101} +do_test randexpr-2.983 { + db eval {SELECT coalesce((select max(b) from t1 where not not c*t1.e>=19 or case when 17<=t1.b and case when 13 not between d and -f then case e when 11 then case when e in (select ( -d) from t1 union select e from t1) and 19<=(a) then t1.a else (19) end else f end else t1.a end+t1.a<19 then ~d when e in (a,11, -b) then b else e end not between f and 13),a) FROM t1 WHERE t1.a>=+a} +} {200} +do_test randexpr-2.984 { + db eval {SELECT coalesce((select max(b) from t1 where not not c*t1.e>=19 or case when 17<=t1.b and case when 13 not between d and -f then case e when 11 then case when e in (select ( -d) from t1 union select e from t1) and 19<=(a) then t1.a else (19) end else f end else t1.a end+t1.a<19 then ~d when e in (a,11, -b) then b else e end not between f and 13),a) FROM t1 WHERE NOT (t1.a>=+a)} +} {} +do_test randexpr-2.985 { + db eval {SELECT case when case when 11 between a+a+t1.b and b then c*e-t1.c*t1.a when +b<= -t1.c-t1.e-19*t1.b+c*t1.b then e else d end-(11)-e=11) or t1.c not between t1.d and - -11 then t1.a when 11 not between -t1.e and t1.a then 11 else t1.b end when (d not in (a,c,19)) then f else c end*17 from t1 where -11<=t1.c),t1.c)+f not in (t1.f, -d,19))} +} {} +do_test randexpr-2.988 { + db eval {SELECT c-case 17 when c+b-t1.a-a*coalesce((select max(t1.c) from t1 where t1.b- -(abs(13)/abs(t1.e)) in (case t1.f when f then coalesce((select max(coalesce((select 13 from t1 where exists(select 1 from t1 where f not between e and c)),e)) from t1 where d not between t1.a and 13),d)-b else a end, -13,(t1.f)) and 13 between e and 17),a) | a then t1.d else e end+ -t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select -+t1.c | case when a in (select case max(+b) when ~count(*) then count(*) else (abs((max(f)))) end from t1 union select -max(e) from t1) then case when (t1.d>=11) or t1.c not between t1.d and - -11 then t1.a when 11 not between -t1.e and t1.a then 11 else t1.b end when (d not in (a,c,19)) then f else c end*17 from t1 where -11<=t1.c),t1.c)+f not in (t1.f, -d,19)))} +} {-700} +do_test randexpr-2.989 { + db eval {SELECT c-case 17 when c+b-t1.a-a*coalesce((select max(t1.c) from t1 where t1.b- -(abs(13)/abs(t1.e)) in (case t1.f when f then coalesce((select max(coalesce((select 13 from t1 where exists(select 1 from t1 where f not between e and c)),e)) from t1 where d not between t1.a and 13),d)-b else a end, -13,(t1.f)) and 13 between e and 17),a) & a then t1.d else e end+ -t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select -+t1.c | case when a in (select case max(+b) when ~count(*) then count(*) else (abs((max(f)))) end from t1 union select -max(e) from t1) then case when (t1.d>=11) or t1.c not between t1.d and - -11 then t1.a when 11 not between -t1.e and t1.a then 11 else t1.b end when (d not in (a,c,19)) then f else c end*17 from t1 where -11<=t1.c),t1.c)+f not in (t1.f, -d,19)))} +} {-700} +do_test randexpr-2.990 { + db eval {SELECT (select ( -count(distinct case case a when e then c*case when e<=t1.d+b then a when (abs(t1.f)/abs(case when b-coalesce((select max(t1.f-t1.b) from t1 where not exists(select 1 from t1 where 17 in (b,13,(b)) or b in (d,c,t1.e))),t1.b) not in (d,((c)),t1.b) then -19 when c between a and 13 then 19 else t1.f end))=13 then f else 13 end else 17 end when 13 then t1.f else t1.b end-t1.c)) from t1) FROM t1 WHERE coalesce((select max(t1.d) from t1 where t1.c<>t1.c-13),t1.a)>=d or b*coalesce((select max((d)) from t1 where c not between +coalesce((select max(13) from t1 where e between -(abs(( -coalesce((select max(case f when t1.f then e else -t1.c end) from t1 where 11>e and t1.bt1.c-13),t1.a)>=d or b*coalesce((select max((d)) from t1 where c not between +coalesce((select max(13) from t1 where e between -(abs(( -coalesce((select max(case f when t1.f then e else -t1.c end) from t1 where 11>e and t1.bb then t1.a else e end | f from t1 where 13 in (select abs(~max((17))) from t1 union select cast(avg(t1.b) AS integer)-min(19) from t1)), -t1.a) when c+case ~e+~t1.d | 13 when case when t1.c<=t1.c or (11)=t1.a then 11 when -11 in (17,11, -d) then t1.a else t1.b end then 19 else 13 end* -t1.c} +} {100500} +do_test randexpr-2.993 { + db eval {SELECT case when (11=(t1.b)) then t1.c-coalesce((select case when t1.f*c-b<>b then t1.a else e end | f from t1 where 13 in (select abs(~max((17))) from t1 union select cast(avg(t1.b) AS integer)-min(19) from t1)), -t1.a) when c+case ~e+~t1.d | 13 when case when t1.c<=t1.c or (11)=t1.a then 11 when -11 in (17,11, -d) then t1.a else t1.b end then 19 else 13 end* -t1.c)} +} {} +do_test randexpr-2.994 { + db eval {SELECT case when (11=(t1.b)) then t1.c-coalesce((select case when t1.f*c-b<>b then t1.a else e end & f from t1 where 13 in (select abs(~max((17))) from t1 union select cast(avg(t1.b) AS integer)-min(19) from t1)), -t1.a) when c+case ~e+~t1.d | 13 when case when t1.c<=t1.c or (11)=t1.a then 11 when -11 in (17,11, -d) then t1.a else t1.b end then 19 else 13 end* -t1.c} +} {100500} +do_test randexpr-2.995 { + db eval {SELECT case when (f in (select count(distinct 17) from t1 union select count(distinct t1.b) from t1)) then d when e in (coalesce((select max(e+e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where 11-t1.a in (select case -max(11)-max(b) when min(t1.f) then count(distinct f) else count(distinct t1.c) end | count(*) from t1 union select min( -a) from t1)) and t1.e in (select count(distinct -t1.e) from t1 union select count(distinct a) from t1) and d not in (b,f,t1.d)) and a between t1.c and t1.e),f),c,11) then c else t1.f end | a FROM t1 WHERE coalesce((select a from t1 where t1.a | (17-coalesce((select t1.b from t1 where ~t1.f | t1.e=d and a<=19+(select (cast(avg(c) AS integer)) from t1)),t1.c))+t1.e*t1.d+t1.c not between t1.d and 19), -t1.d) in (select (count(*)) from t1 union select (++~min(c)*+max(t1.a)+cast(avg( -(t1.e)) AS integer)) from t1)} +} {} +do_test randexpr-2.996 { + db eval {SELECT case when (f in (select count(distinct 17) from t1 union select count(distinct t1.b) from t1)) then d when e in (coalesce((select max(e+e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where 11-t1.a in (select case -max(11)-max(b) when min(t1.f) then count(distinct f) else count(distinct t1.c) end | count(*) from t1 union select min( -a) from t1)) and t1.e in (select count(distinct -t1.e) from t1 union select count(distinct a) from t1) and d not in (b,f,t1.d)) and a between t1.c and t1.e),f),c,11) then c else t1.f end | a FROM t1 WHERE NOT (coalesce((select a from t1 where t1.a | (17-coalesce((select t1.b from t1 where ~t1.f | t1.e=d and a<=19+(select (cast(avg(c) AS integer)) from t1)),t1.c))+t1.e*t1.d+t1.c not between t1.d and 19), -t1.d) in (select (count(*)) from t1 union select (++~min(c)*+max(t1.a)+cast(avg( -(t1.e)) AS integer)) from t1))} +} {636} +do_test randexpr-2.997 { + db eval {SELECT case when (f in (select count(distinct 17) from t1 union select count(distinct t1.b) from t1)) then d when e in (coalesce((select max(e+e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where 11-t1.a in (select case -max(11)-max(b) when min(t1.f) then count(distinct f) else count(distinct t1.c) end & count(*) from t1 union select min( -a) from t1)) and t1.e in (select count(distinct -t1.e) from t1 union select count(distinct a) from t1) and d not in (b,f,t1.d)) and a between t1.c and t1.e),f),c,11) then c else t1.f end & a FROM t1 WHERE NOT (coalesce((select a from t1 where t1.a | (17-coalesce((select t1.b from t1 where ~t1.f | t1.e=d and a<=19+(select (cast(avg(c) AS integer)) from t1)),t1.c))+t1.e*t1.d+t1.c not between t1.d and 19), -t1.d) in (select (count(*)) from t1 union select (++~min(c)*+max(t1.a)+cast(avg( -(t1.e)) AS integer)) from t1))} +} {64} +do_test randexpr-2.998 { + db eval {SELECT case when coalesce((select t1.b from t1 where a not in (19,coalesce((select max(t1.f) from t1 where (select count(distinct t1.b) from t1) in (t1.e,t1.f*13-11,d)),(t1.f))-17*c,c) or t1.c<=11),19)>13 and f not in (t1.a,11,t1.d) then (((e))) when f=11 or f not in (a,19,17) then 13 else e end FROM t1 WHERE c in (select min(t1.a*a+(select count(distinct t1.b+(t1.a)- - -c) from t1)-t1.e) from t1 union select count(*) from t1) and c in (select min(t1.d) from t1 union select cast(avg(d) AS integer)+abs(case count(*) when count(distinct 11) then -count(distinct 19) else count(distinct (t1.b)) end) | cast(avg((t1.c)) AS integer)+count(*) from t1) and e=13 and t1.d>c or 13 not in (17,(t1.f),t1.a) or (11)=t1.b and t1.e>=a or 11<=t1.b or d<=17} +} {500} +do_test randexpr-2.999 { + db eval {SELECT case when coalesce((select t1.b from t1 where a not in (19,coalesce((select max(t1.f) from t1 where (select count(distinct t1.b) from t1) in (t1.e,t1.f*13-11,d)),(t1.f))-17*c,c) or t1.c<=11),19)>13 and f not in (t1.a,11,t1.d) then (((e))) when f=11 or f not in (a,19,17) then 13 else e end FROM t1 WHERE NOT (c in (select min(t1.a*a+(select count(distinct t1.b+(t1.a)- - -c) from t1)-t1.e) from t1 union select count(*) from t1) and c in (select min(t1.d) from t1 union select cast(avg(d) AS integer)+abs(case count(*) when count(distinct 11) then -count(distinct 19) else count(distinct (t1.b)) end) | cast(avg((t1.c)) AS integer)+count(*) from t1) and e=13 and t1.d>c or 13 not in (17,(t1.f),t1.a) or (11)=t1.b and t1.e>=a or 11<=t1.b or d<=17)} +} {} +do_test randexpr-2.1000 { + db eval {SELECT case when t1.d not between (abs(d)/abs(t1.e))+t1.f*t1.a*a and 17*e then case when 11 between a and coalesce((select max(t1.b) from t1 where (case when t1.e+(t1.b) not in (t1.e,d,f) or 13<>17 then 17 when a>e then 11 else a end in (select count(*) from t1 union select min(a) from t1))),17) then 19 when -11 in (select t1.c from t1 union select -19 from t1) or - - -t1.e=t1.a then 17 else t1.a end else t1.e end FROM t1 WHERE (select +count(distinct f) from t1)-t1.f between t1.f and c} +} {} +do_test randexpr-2.1001 { + db eval {SELECT case when t1.d not between (abs(d)/abs(t1.e))+t1.f*t1.a*a and 17*e then case when 11 between a and coalesce((select max(t1.b) from t1 where (case when t1.e+(t1.b) not in (t1.e,d,f) or 13<>17 then 17 when a>e then 11 else a end in (select count(*) from t1 union select min(a) from t1))),17) then 19 when -11 in (select t1.c from t1 union select -19 from t1) or - - -t1.e=t1.a then 17 else t1.a end else t1.e end FROM t1 WHERE NOT ((select +count(distinct f) from t1)-t1.f between t1.f and c)} +} {100} +do_test randexpr-2.1002 { + db eval {SELECT case when (case when e between t1.b and c+(select cast(avg( -case c when a then t1.f+c else 17 end) AS integer) from t1) then t1.e when not 19>=t1.a then 17 else d end in (select cast(avg(13) AS integer)-max(11) | +count(*) from t1 union select case (cast(avg(d) AS integer)) when min(a) then abs( -max(19)) else count(*) end from t1)) then (t1.a) else c end | -e*a FROM t1 WHERE f*t1.d*(abs(case d when coalesce((select max((abs(t1.e)/abs(t1.f))) from t1 where ((e between (b) and 13) or t1.d=(c)) and t1.f between 17 and t1.e),a) then -b else -e end+ -t1.e)/abs(t1.c))+f<=17 or t1.f not between f and t1.e or (t1.c in (select 17 from t1 union select f from t1)) or exists(select 1 from t1 where (a not in (d,t1.a,t1.e) and t1.a in (t1.a,c,19))) and f not in (t1.d,t1.c,c)} +} {-49732} +do_test randexpr-2.1003 { + db eval {SELECT case when (case when e between t1.b and c+(select cast(avg( -case c when a then t1.f+c else 17 end) AS integer) from t1) then t1.e when not 19>=t1.a then 17 else d end in (select cast(avg(13) AS integer)-max(11) | +count(*) from t1 union select case (cast(avg(d) AS integer)) when min(a) then abs( -max(19)) else count(*) end from t1)) then (t1.a) else c end | -e*a FROM t1 WHERE NOT (f*t1.d*(abs(case d when coalesce((select max((abs(t1.e)/abs(t1.f))) from t1 where ((e between (b) and 13) or t1.d=(c)) and t1.f between 17 and t1.e),a) then -b else -e end+ -t1.e)/abs(t1.c))+f<=17 or t1.f not between f and t1.e or (t1.c in (select 17 from t1 union select f from t1)) or exists(select 1 from t1 where (a not in (d,t1.a,t1.e) and t1.a in (t1.a,c,19))) and f not in (t1.d,t1.c,c))} +} {} +do_test randexpr-2.1004 { + db eval {SELECT case when (case when e between t1.b and c+(select cast(avg( -case c when a then t1.f+c else 17 end) AS integer) from t1) then t1.e when not 19>=t1.a then 17 else d end in (select cast(avg(13) AS integer)-max(11) & +count(*) from t1 union select case (cast(avg(d) AS integer)) when min(a) then abs( -max(19)) else count(*) end from t1)) then (t1.a) else c end & -e*a FROM t1 WHERE f*t1.d*(abs(case d when coalesce((select max((abs(t1.e)/abs(t1.f))) from t1 where ((e between (b) and 13) or t1.d=(c)) and t1.f between 17 and t1.e),a) then -b else -e end+ -t1.e)/abs(t1.c))+f<=17 or t1.f not between f and t1.e or (t1.c in (select 17 from t1 union select f from t1)) or exists(select 1 from t1 where (a not in (d,t1.a,t1.e) and t1.a in (t1.a,c,19))) and f not in (t1.d,t1.c,c)} +} {32} +do_test randexpr-2.1005 { + db eval {SELECT -case coalesce((select case when f<>t1.d | c-(e)*t1.b and 17 in (select t1.b from t1 union select -(t1.c) from t1) or t1.e>=11 and t1.f not between b and f or e not in (11,19,t1.e) and t1.c<=a then coalesce((select max(t1.f+t1.f) from t1 where -t1.a=13),e) when t1.e then c else t1.a end FROM t1 WHERE coalesce((select t1.f from t1 where (t1.e>=case (abs(11)/abs(t1.a)) when 11 then case t1.c when t1.a then t1.e else a end else t1.f end+t1.d) and (exists(select 1 from t1 where t1.b not in (t1.b,a,19))) or t1.a>=11),(select abs((~cast(avg(t1.b) AS integer)-~cast(avg((t1.b)) AS integer)* -count(*))+ -count(distinct t1.b)) from t1)*19)<=f and b in (select count(*) from t1 union select -min(d) from t1)} +} {} +do_test randexpr-2.1006 { + db eval {SELECT -case coalesce((select case when f<>t1.d | c-(e)*t1.b and 17 in (select t1.b from t1 union select -(t1.c) from t1) or t1.e>=11 and t1.f not between b and f or e not in (11,19,t1.e) and t1.c<=a then coalesce((select max(t1.f+t1.f) from t1 where -t1.a=13),e) when t1.e then c else t1.a end FROM t1 WHERE NOT (coalesce((select t1.f from t1 where (t1.e>=case (abs(11)/abs(t1.a)) when 11 then case t1.c when t1.a then t1.e else a end else t1.f end+t1.d) and (exists(select 1 from t1 where t1.b not in (t1.b,a,19))) or t1.a>=11),(select abs((~cast(avg(t1.b) AS integer)-~cast(avg((t1.b)) AS integer)* -count(*))+ -count(distinct t1.b)) from t1)*19)<=f and b in (select count(*) from t1 union select -min(d) from t1))} +} {-100} +do_test randexpr-2.1007 { + db eval {SELECT -case coalesce((select case when f<>t1.d & c-(e)*t1.b and 17 in (select t1.b from t1 union select -(t1.c) from t1) or t1.e>=11 and t1.f not between b and f or e not in (11,19,t1.e) and t1.c<=a then coalesce((select max(t1.f+t1.f) from t1 where -t1.a=13),e) when t1.e then c else t1.a end FROM t1 WHERE NOT (coalesce((select t1.f from t1 where (t1.e>=case (abs(11)/abs(t1.a)) when 11 then case t1.c when t1.a then t1.e else a end else t1.f end+t1.d) and (exists(select 1 from t1 where t1.b not in (t1.b,a,19))) or t1.a>=11),(select abs((~cast(avg(t1.b) AS integer)-~cast(avg((t1.b)) AS integer)* -count(*))+ -count(distinct t1.b)) from t1)*19)<=f and b in (select count(*) from t1 union select -min(d) from t1))} +} {-100} +do_test randexpr-2.1008 { + db eval {SELECT case when exists(select 1 from t1 where exists(select 1 from t1 where -case when t1.d<=coalesce((select t1.d | (f)*t1.a from t1 where not exists(select 1 from t1 where t1.f not in ((e),t1.e,13) or t1.a not between a and -t1.d or (f) not between f and 13)),19) then e when (t1.f)<19 or e<=d then b else d end in (select case ~ -(cast(avg(b) AS integer)*cast(avg(t1.b) AS integer)*min(t1.f)) | count(*) when min(t1.c) then ( - -count(distinct -d)) else count(*) end from t1 union select cast(avg(f) AS integer) from t1) and bt1.b or 19<>t1.f} +} {400} +do_test randexpr-2.1009 { + db eval {SELECT case when exists(select 1 from t1 where exists(select 1 from t1 where -case when t1.d<=coalesce((select t1.d | (f)*t1.a from t1 where not exists(select 1 from t1 where t1.f not in ((e),t1.e,13) or t1.a not between a and -t1.d or (f) not between f and 13)),19) then e when (t1.f)<19 or e<=d then b else d end in (select case ~ -(cast(avg(b) AS integer)*cast(avg(t1.b) AS integer)*min(t1.f)) | count(*) when min(t1.c) then ( - -count(distinct -d)) else count(*) end from t1 union select cast(avg(f) AS integer) from t1) and bt1.b or 19<>t1.f)} +} {} +do_test randexpr-2.1010 { + db eval {SELECT case when exists(select 1 from t1 where exists(select 1 from t1 where -case when t1.d<=coalesce((select t1.d & (f)*t1.a from t1 where not exists(select 1 from t1 where t1.f not in ((e),t1.e,13) or t1.a not between a and -t1.d or (f) not between f and 13)),19) then e when (t1.f)<19 or e<=d then b else d end in (select case ~ -(cast(avg(b) AS integer)*cast(avg(t1.b) AS integer)*min(t1.f)) & count(*) when min(t1.c) then ( - -count(distinct -d)) else count(*) end from t1 union select cast(avg(f) AS integer) from t1) and bt1.b or 19<>t1.f} +} {400} +do_test randexpr-2.1011 { + db eval {SELECT case when ~+11<>f then case e when 11 then coalesce((select case d when t1.e-coalesce((select a+t1.c from t1 where (d) in (select +min(t1.f)+count(*) from t1 union select count(distinct t1.e) from t1)),t1.f) then t1.c else d end from t1 where t1.f in (select t1.f from t1 union select b from t1) or (t1.a not in ( -a,t1.a,t1.b))),t1.c) else t1.f end-t1.f when not exists(select 1 from t1 where b between f and t1.a) then t1.c else t1.f end FROM t1 WHERE t1.a<=coalesce((select max(b) from t1 where coalesce((select t1.c*case when coalesce((select max((select count(*) from t1)) from t1 where not not exists(select 1 from t1 where case t1.b | a when t1.f then c else 11 end<>f and 13>=13 and f between t1.b and c)),13)=case e when a then 19 else d end then t1.b when t1.a not in (a,t1.b,a) then e else b end-d from t1 where t1.f between t1.d and t1.e),e)>t1.f),17)+t1.f} +} {0} +do_test randexpr-2.1012 { + db eval {SELECT case when ~+11<>f then case e when 11 then coalesce((select case d when t1.e-coalesce((select a+t1.c from t1 where (d) in (select +min(t1.f)+count(*) from t1 union select count(distinct t1.e) from t1)),t1.f) then t1.c else d end from t1 where t1.f in (select t1.f from t1 union select b from t1) or (t1.a not in ( -a,t1.a,t1.b))),t1.c) else t1.f end-t1.f when not exists(select 1 from t1 where b between f and t1.a) then t1.c else t1.f end FROM t1 WHERE NOT (t1.a<=coalesce((select max(b) from t1 where coalesce((select t1.c*case when coalesce((select max((select count(*) from t1)) from t1 where not not exists(select 1 from t1 where case t1.b | a when t1.f then c else 11 end<>f and 13>=13 and f between t1.b and c)),13)=case e when a then 19 else d end then t1.b when t1.a not in (a,t1.b,a) then e else b end-d from t1 where t1.f between t1.d and t1.e),e)>t1.f),17)+t1.f)} +} {} +do_test randexpr-2.1013 { + db eval {SELECT (abs(d)/abs(t1.f++(select cast(avg(coalesce((select max(b) from t1 where case when t1.a*+(abs( -t1.b)/abs((select cast(avg(13) AS integer) from t1)))<=(t1.c-t1.d- -t1.c) then case d when 17 then -t1.d else f end when t1.b between t1.b and t1.b then a else t1.d end in (select count(*) from t1 union select abs(cast(avg(13) AS integer)) | min(t1.c) from t1) or ((13))>=b),17)) AS integer) from t1)+13)) FROM t1 WHERE coalesce((select +t1.a from t1 where not exists(select 1 from t1 where (select cast(avg(13) AS integer) from t1)<=(abs( -11)/abs(t1.f))*coalesce((select t1.e from t1 where not t1.f in (select max(+b-t1.d) from t1 union select + -(abs(cast(avg((t1.b)) AS integer)))-+count(*)-(min(13)) from t1)),d+t1.d*t1.d) | (17)-t1.b)),f) in (select max(t1.c) from t1 union select count(distinct f) from t1)} +} {} +do_test randexpr-2.1014 { + db eval {SELECT (abs(d)/abs(t1.f++(select cast(avg(coalesce((select max(b) from t1 where case when t1.a*+(abs( -t1.b)/abs((select cast(avg(13) AS integer) from t1)))<=(t1.c-t1.d- -t1.c) then case d when 17 then -t1.d else f end when t1.b between t1.b and t1.b then a else t1.d end in (select count(*) from t1 union select abs(cast(avg(13) AS integer)) | min(t1.c) from t1) or ((13))>=b),17)) AS integer) from t1)+13)) FROM t1 WHERE NOT (coalesce((select +t1.a from t1 where not exists(select 1 from t1 where (select cast(avg(13) AS integer) from t1)<=(abs( -11)/abs(t1.f))*coalesce((select t1.e from t1 where not t1.f in (select max(+b-t1.d) from t1 union select + -(abs(cast(avg((t1.b)) AS integer)))-+count(*)-(min(13)) from t1)),d+t1.d*t1.d) | (17)-t1.b)),f) in (select max(t1.c) from t1 union select count(distinct f) from t1))} +} {0} +do_test randexpr-2.1015 { + db eval {SELECT (abs(d)/abs(t1.f++(select cast(avg(coalesce((select max(b) from t1 where case when t1.a*+(abs( -t1.b)/abs((select cast(avg(13) AS integer) from t1)))<=(t1.c-t1.d- -t1.c) then case d when 17 then -t1.d else f end when t1.b between t1.b and t1.b then a else t1.d end in (select count(*) from t1 union select abs(cast(avg(13) AS integer)) & min(t1.c) from t1) or ((13))>=b),17)) AS integer) from t1)+13)) FROM t1 WHERE NOT (coalesce((select +t1.a from t1 where not exists(select 1 from t1 where (select cast(avg(13) AS integer) from t1)<=(abs( -11)/abs(t1.f))*coalesce((select t1.e from t1 where not t1.f in (select max(+b-t1.d) from t1 union select + -(abs(cast(avg((t1.b)) AS integer)))-+count(*)-(min(13)) from t1)),d+t1.d*t1.d) | (17)-t1.b)),f) in (select max(t1.c) from t1 union select count(distinct f) from t1))} +} {0} +do_test randexpr-2.1016 { + db eval {SELECT case t1.a when (select ~max(coalesce((select (t1.b-a*+t1.c-t1.e) from t1 where not 11*t1.f++t1.f-t1.a*f*+t1.e*t1.b>17 and 19+e not in (t1.c,t1.b,a)),19)) from t1) then 19*11 else d end | (17) | t1.d FROM t1 WHERE exists(select 1 from t1 where coalesce((select max(13) from t1 where t1.e not in (d,13-19,17) or e*19=d or ((t1.a< -t1.a or 11- -t1.d-case when 13<( -t1.e) then a else e end*t1.b+t1.e in (select t1.d from t1 union select t1.e from t1) and 19<>d))),b)+11*11=t1.e)} +} {} +do_test randexpr-2.1017 { + db eval {SELECT case t1.a when (select ~max(coalesce((select (t1.b-a*+t1.c-t1.e) from t1 where not 11*t1.f++t1.f-t1.a*f*+t1.e*t1.b>17 and 19+e not in (t1.c,t1.b,a)),19)) from t1) then 19*11 else d end | (17) | t1.d FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select max(13) from t1 where t1.e not in (d,13-19,17) or e*19=d or ((t1.a< -t1.a or 11- -t1.d-case when 13<( -t1.e) then a else e end*t1.b+t1.e in (select t1.d from t1 union select t1.e from t1) and 19<>d))),b)+11*11=t1.e))} +} {401} +do_test randexpr-2.1018 { + db eval {SELECT case t1.a when (select ~max(coalesce((select (t1.b-a*+t1.c-t1.e) from t1 where not 11*t1.f++t1.f-t1.a*f*+t1.e*t1.b>17 and 19+e not in (t1.c,t1.b,a)),19)) from t1) then 19*11 else d end & (17) & t1.d FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select max(13) from t1 where t1.e not in (d,13-19,17) or e*19=d or ((t1.a< -t1.a or 11- -t1.d-case when 13<( -t1.e) then a else e end*t1.b+t1.e in (select t1.d from t1 union select t1.e from t1) and 19<>d))),b)+11*11=t1.e))} +} {16} +do_test randexpr-2.1019 { + db eval {SELECT t1.a-coalesce((select 11-case when 11<19-f+t1.a then a | (t1.a+++(select cast(avg((abs(t1.d | e)/abs((abs(t1.a)/abs(13))))) AS integer)-max(a) from t1)+e+13*19+t1.a-c) else 13 end+t1.e-19 from t1 where 13>t1.f),e) FROM t1 WHERE ~(abs((select max( -case when d+(11)*d between coalesce((select 11 from t1 where (t1.f)=e),d*f) and t1.e then d-case when a<> -17+(abs(t1.d)/abs(t1.f)) then t1.f else t1.e end*11+c-(c) else d end) from t1)*t1.e)/abs((t1.f)))-f<>11} +} {-400} +do_test randexpr-2.1020 { + db eval {SELECT t1.a-coalesce((select 11-case when 11<19-f+t1.a then a | (t1.a+++(select cast(avg((abs(t1.d | e)/abs((abs(t1.a)/abs(13))))) AS integer)-max(a) from t1)+e+13*19+t1.a-c) else 13 end+t1.e-19 from t1 where 13>t1.f),e) FROM t1 WHERE NOT (~(abs((select max( -case when d+(11)*d between coalesce((select 11 from t1 where (t1.f)=e),d*f) and t1.e then d-case when a<> -17+(abs(t1.d)/abs(t1.f)) then t1.f else t1.e end*11+c-(c) else d end) from t1)*t1.e)/abs((t1.f)))-f<>11)} +} {} +do_test randexpr-2.1021 { + db eval {SELECT t1.a-coalesce((select 11-case when 11<19-f+t1.a then a & (t1.a+++(select cast(avg((abs(t1.d & e)/abs((abs(t1.a)/abs(13))))) AS integer)-max(a) from t1)+e+13*19+t1.a-c) else 13 end+t1.e-19 from t1 where 13>t1.f),e) FROM t1 WHERE ~(abs((select max( -case when d+(11)*d between coalesce((select 11 from t1 where (t1.f)=e),d*f) and t1.e then d-case when a<> -17+(abs(t1.d)/abs(t1.f)) then t1.f else t1.e end*11+c-(c) else d end) from t1)*t1.e)/abs((t1.f)))-f<>11} +} {-400} +do_test randexpr-2.1022 { + db eval {SELECT d | (select (cast(avg((abs(case when b*(abs((abs(case f when 17 then t1.e else t1.c end)/abs( -d)))/abs(t1.c)) in (d,a,a) then 19 when (exists(select 1 from t1 where t1.c=t1.a) or a<>d) then a else c end)/abs(t1.e))-17) AS integer)* -min(19)-count(distinct a)-+count(distinct 17)*min(t1.a)+ -cast(avg(t1.a) AS integer)- -max(17) | max(e)) from t1) FROM t1 WHERE -f-t1.f++e+case when not (((select abs(count(*)) from t1)) not in ((case when (t1.b>t1.c) then t1.b else f end),e,13)) and not exists(select 1 from t1 where 11 in (select t1.f from t1 union select ((t1.f)) from t1)) then (t1.e)+c-c+c when -b in (13,19,t1.c) then 17 else 13 end-d | t1.a not in (a,b,b)} +} {511} +do_test randexpr-2.1023 { + db eval {SELECT d | (select (cast(avg((abs(case when b*(abs((abs(case f when 17 then t1.e else t1.c end)/abs( -d)))/abs(t1.c)) in (d,a,a) then 19 when (exists(select 1 from t1 where t1.c=t1.a) or a<>d) then a else c end)/abs(t1.e))-17) AS integer)* -min(19)-count(distinct a)-+count(distinct 17)*min(t1.a)+ -cast(avg(t1.a) AS integer)- -max(17) | max(e)) from t1) FROM t1 WHERE NOT ( -f-t1.f++e+case when not (((select abs(count(*)) from t1)) not in ((case when (t1.b>t1.c) then t1.b else f end),e,13)) and not exists(select 1 from t1 where 11 in (select t1.f from t1 union select ((t1.f)) from t1)) then (t1.e)+c-c+c when -b in (13,19,t1.c) then 17 else 13 end-d | t1.a not in (a,b,b))} +} {} +do_test randexpr-2.1024 { + db eval {SELECT d & (select (cast(avg((abs(case when b*(abs((abs(case f when 17 then t1.e else t1.c end)/abs( -d)))/abs(t1.c)) in (d,a,a) then 19 when (exists(select 1 from t1 where t1.c=t1.a) or a<>d) then a else c end)/abs(t1.e))-17) AS integer)* -min(19)-count(distinct a)-+count(distinct 17)*min(t1.a)+ -cast(avg(t1.a) AS integer)- -max(17) & max(e)) from t1) FROM t1 WHERE -f-t1.f++e+case when not (((select abs(count(*)) from t1)) not in ((case when (t1.b>t1.c) then t1.b else f end),e,13)) and not exists(select 1 from t1 where 11 in (select t1.f from t1 union select ((t1.f)) from t1)) then (t1.e)+c-c+c when -b in (13,19,t1.c) then 17 else 13 end-d | t1.a not in (a,b,b)} +} {128} +do_test randexpr-2.1025 { + db eval {SELECT 11-(select min((abs(e)/abs(f*t1.e*c+17+~case when f | 11 between (select case -max(19) when (cast(avg(t1.a) AS integer)) then count(distinct t1.f) else count(*) end from t1) and coalesce((select 13 from t1 where a<=(t1.d)),f)-a then t1.a when f in (select 17 from t1 union select -b from t1) and t1.d(17) or 19>=d then (f) else 11 end))) from t1) FROM t1 WHERE e in (e, -17*t1.c*17,e)} +} {11} +do_test randexpr-2.1026 { + db eval {SELECT 11-(select min((abs(e)/abs(f*t1.e*c+17+~case when f | 11 between (select case -max(19) when (cast(avg(t1.a) AS integer)) then count(distinct t1.f) else count(*) end from t1) and coalesce((select 13 from t1 where a<=(t1.d)),f)-a then t1.a when f in (select 17 from t1 union select -b from t1) and t1.d(17) or 19>=d then (f) else 11 end))) from t1) FROM t1 WHERE NOT (e in (e, -17*t1.c*17,e))} +} {} +do_test randexpr-2.1027 { + db eval {SELECT 11-(select min((abs(e)/abs(f*t1.e*c+17+~case when f & 11 between (select case -max(19) when (cast(avg(t1.a) AS integer)) then count(distinct t1.f) else count(*) end from t1) and coalesce((select 13 from t1 where a<=(t1.d)),f)-a then t1.a when f in (select 17 from t1 union select -b from t1) and t1.d(17) or 19>=d then (f) else 11 end))) from t1) FROM t1 WHERE e in (e, -17*t1.c*17,e)} +} {11} +do_test randexpr-2.1028 { + db eval {SELECT coalesce((select max( -t1.d-f+~t1.d*t1.b) from t1 where (select ~+min(t1.f)+abs(min(+(select cast(avg((b)) AS integer) from t1)-d*d))-max(f)-count(distinct 19) | count(*)*count(*) from t1)>c),case 13 when +t1.c-t1.c-t1.a then c else c end*d) FROM t1 WHERE ((t1.b>=case when not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where e>=t1.a or (coalesce((select max(coalesce((select case when a in (select t1.d from t1 union select t1.c from t1) then a when -b in (17,c,t1.f) then f else b end from t1 where not exists(select 1 from t1 where f<=13)),17)) from t1 where t1.f>=t1.b),d) between t1.f and 11) or t1.b between 13 and t1.b))) then a when e<=17 then t1.b+ -~11 else a end and not e>= - -b or 13 not in (c,f,11)) and d not between 11 and t1.a)} +} {-81200} +do_test randexpr-2.1029 { + db eval {SELECT coalesce((select max( -t1.d-f+~t1.d*t1.b) from t1 where (select ~+min(t1.f)+abs(min(+(select cast(avg((b)) AS integer) from t1)-d*d))-max(f)-count(distinct 19) | count(*)*count(*) from t1)>c),case 13 when +t1.c-t1.c-t1.a then c else c end*d) FROM t1 WHERE NOT (((t1.b>=case when not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where e>=t1.a or (coalesce((select max(coalesce((select case when a in (select t1.d from t1 union select t1.c from t1) then a when -b in (17,c,t1.f) then f else b end from t1 where not exists(select 1 from t1 where f<=13)),17)) from t1 where t1.f>=t1.b),d) between t1.f and 11) or t1.b between 13 and t1.b))) then a when e<=17 then t1.b+ -~11 else a end and not e>= - -b or 13 not in (c,f,11)) and d not between 11 and t1.a))} +} {} +do_test randexpr-2.1030 { + db eval {SELECT coalesce((select max( -t1.d-f+~t1.d*t1.b) from t1 where (select ~+min(t1.f)+abs(min(+(select cast(avg((b)) AS integer) from t1)-d*d))-max(f)-count(distinct 19) & count(*)*count(*) from t1)>c),case 13 when +t1.c-t1.c-t1.a then c else c end*d) FROM t1 WHERE ((t1.b>=case when not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where e>=t1.a or (coalesce((select max(coalesce((select case when a in (select t1.d from t1 union select t1.c from t1) then a when -b in (17,c,t1.f) then f else b end from t1 where not exists(select 1 from t1 where f<=13)),17)) from t1 where t1.f>=t1.b),d) between t1.f and 11) or t1.b between 13 and t1.b))) then a when e<=17 then t1.b+ -~11 else a end and not e>= - -b or 13 not in (c,f,11)) and d not between 11 and t1.a)} +} {120000} +do_test randexpr-2.1031 { + db eval {SELECT case when t1.d<>coalesce((select 13 from t1 where (d in (select case when (13<>t1.a*d-19-+11*13-t1.c) then case when t1.c=d then e else t1.b end when not exists(select 1 from t1 where 17<>t1.b) then t1.e else t1.e end | t1.a+t1.e from t1 union select t1.d from t1))),t1.f) or a> -t1.e then 11 else 17 end*d FROM t1 WHERE t1.a-d<=d-(abs(coalesce((select b from t1 where ~e=13 then t1.d else (t1.c) end not between t1.a and 13 then a when (17) not between 11 and t1.c then a else a end) not between 13 and t1.d then 13 else a end),19))/abs(t1.e))+t1.c+t1.e*b+c or ((17 in (select f from t1 union select t1.e from t1)))} +} {4400} +do_test randexpr-2.1032 { + db eval {SELECT case when t1.d<>coalesce((select 13 from t1 where (d in (select case when (13<>t1.a*d-19-+11*13-t1.c) then case when t1.c=d then e else t1.b end when not exists(select 1 from t1 where 17<>t1.b) then t1.e else t1.e end | t1.a+t1.e from t1 union select t1.d from t1))),t1.f) or a> -t1.e then 11 else 17 end*d FROM t1 WHERE NOT (t1.a-d<=d-(abs(coalesce((select b from t1 where ~e=13 then t1.d else (t1.c) end not between t1.a and 13 then a when (17) not between 11 and t1.c then a else a end) not between 13 and t1.d then 13 else a end),19))/abs(t1.e))+t1.c+t1.e*b+c or ((17 in (select f from t1 union select t1.e from t1))))} +} {} +do_test randexpr-2.1033 { + db eval {SELECT case when t1.d<>coalesce((select 13 from t1 where (d in (select case when (13<>t1.a*d-19-+11*13-t1.c) then case when t1.c=d then e else t1.b end when not exists(select 1 from t1 where 17<>t1.b) then t1.e else t1.e end & t1.a+t1.e from t1 union select t1.d from t1))),t1.f) or a> -t1.e then 11 else 17 end*d FROM t1 WHERE t1.a-d<=d-(abs(coalesce((select b from t1 where ~e=13 then t1.d else (t1.c) end not between t1.a and 13 then a when (17) not between 11 and t1.c then a else a end) not between 13 and t1.d then 13 else a end),19))/abs(t1.e))+t1.c+t1.e*b+c or ((17 in (select f from t1 union select t1.e from t1)))} +} {4400} +do_test randexpr-2.1034 { + db eval {SELECT coalesce((select (abs(c)/abs(case when 13<=11 then t1.a when case t1.d when (11) then coalesce((select coalesce((select d-17 from t1 where t1.e=a),11) from t1 where 13 in (select t1.e from t1 union select c from t1)),19) else d end>=t1.f or 11 in (select cast(avg(t1.f) AS integer) from t1 union select ( - -count(*)) from t1) and t1.c between 13 and -b then f else e end)) from t1 where d<=(19)),d)-t1.b FROM t1 WHERE 17>=case when t1.c not in (f,t1.a,c*17*a | t1.c-~t1.d+(+coalesce((select max(case when exists(select 1 from t1 where (t1.e in (select -t1.e from t1 union select t1.c from t1))) then t1.b else t1.b*t1.b end) from t1 where not exists(select 1 from t1 where 17=t1.a)),d))+t1.e | (13)*t1.e+c) and e in (select -c from t1 union select 17 from t1) then t1.d*13 else c end- -e} +} {} +do_test randexpr-2.1035 { + db eval {SELECT coalesce((select (abs(c)/abs(case when 13<=11 then t1.a when case t1.d when (11) then coalesce((select coalesce((select d-17 from t1 where t1.e=a),11) from t1 where 13 in (select t1.e from t1 union select c from t1)),19) else d end>=t1.f or 11 in (select cast(avg(t1.f) AS integer) from t1 union select ( - -count(*)) from t1) and t1.c between 13 and -b then f else e end)) from t1 where d<=(19)),d)-t1.b FROM t1 WHERE NOT (17>=case when t1.c not in (f,t1.a,c*17*a | t1.c-~t1.d+(+coalesce((select max(case when exists(select 1 from t1 where (t1.e in (select -t1.e from t1 union select t1.c from t1))) then t1.b else t1.b*t1.b end) from t1 where not exists(select 1 from t1 where 17=t1.a)),d))+t1.e | (13)*t1.e+c) and e in (select -c from t1 union select 17 from t1) then t1.d*13 else c end- -e)} +} {200} +do_test randexpr-2.1036 { + db eval {SELECT (abs(case when t1.a in (select case when d=(select ~cast(avg(t1.a) AS integer) | ~+min(17*(abs(19)/abs(t1.a))) from t1) or 13 in (select count(distinct t1.b | 11) from t1 union select count(*) | count(distinct c) | count(distinct 17) from t1) and not b<=17 then t1.a when 11=t1.f then (abs(t1.c)/abs(11)) else f end from t1 union select c from t1) then t1.c else a end)/abs(t1.d))-t1.d FROM t1 WHERE ((abs(e)/abs(t1.a* -(coalesce((select max(t1.b-t1.d) from t1 where f>=13),~a+ -a)) | case when not exists(select 1 from t1 where coalesce((select max(c) from t1 where 19-t1.a | e<=17),~( -t1.a)) in (select f from t1 union select t1.d from t1)) then t1.d else (t1.c) end)) in (17,f,t1.a)) or 19=13 or 19=17} +} {} +do_test randexpr-2.1037 { + db eval {SELECT (abs(case when t1.a in (select case when d=(select ~cast(avg(t1.a) AS integer) | ~+min(17*(abs(19)/abs(t1.a))) from t1) or 13 in (select count(distinct t1.b | 11) from t1 union select count(*) | count(distinct c) | count(distinct 17) from t1) and not b<=17 then t1.a when 11=t1.f then (abs(t1.c)/abs(11)) else f end from t1 union select c from t1) then t1.c else a end)/abs(t1.d))-t1.d FROM t1 WHERE NOT (((abs(e)/abs(t1.a* -(coalesce((select max(t1.b-t1.d) from t1 where f>=13),~a+ -a)) | case when not exists(select 1 from t1 where coalesce((select max(c) from t1 where 19-t1.a | e<=17),~( -t1.a)) in (select f from t1 union select t1.d from t1)) then t1.d else (t1.c) end)) in (17,f,t1.a)) or 19=13 or 19=17)} +} {-400} +do_test randexpr-2.1038 { + db eval {SELECT (abs(case when t1.a in (select case when d=(select ~cast(avg(t1.a) AS integer) & ~+min(17*(abs(19)/abs(t1.a))) from t1) or 13 in (select count(distinct t1.b & 11) from t1 union select count(*) & count(distinct c) & count(distinct 17) from t1) and not b<=17 then t1.a when 11=t1.f then (abs(t1.c)/abs(11)) else f end from t1 union select c from t1) then t1.c else a end)/abs(t1.d))-t1.d FROM t1 WHERE NOT (((abs(e)/abs(t1.a* -(coalesce((select max(t1.b-t1.d) from t1 where f>=13),~a+ -a)) | case when not exists(select 1 from t1 where coalesce((select max(c) from t1 where 19-t1.a | e<=17),~( -t1.a)) in (select f from t1 union select t1.d from t1)) then t1.d else (t1.c) end)) in (17,f,t1.a)) or 19=13 or 19=17)} +} {-400} +do_test randexpr-2.1039 { + db eval {SELECT case when f>coalesce((select c from t1 where coalesce((select max(c+c) from t1 where t1.f in (select - -abs(max(19))+(min(a)) from t1 union select count(distinct -t1.d) from t1)),e)>=e),t1.f) | t1.a | 19 or (t1.c) not in (19, - -t1.f,t1.c) or exists(select 1 from t1 where t1.b not between t1.a and -11) then coalesce((select -b from t1 where -t1.a in (select c from t1 union select 17 from t1)),t1.d) when t1.a=c then c else t1.e end FROM t1 WHERE t1.e in (select +cast(avg(f) AS integer) from t1 union select case +max(19) | count(*) when count(*)*+count(*) then ~+count(*) else count(*) end from t1)} +} {} +do_test randexpr-2.1040 { + db eval {SELECT case when f>coalesce((select c from t1 where coalesce((select max(c+c) from t1 where t1.f in (select - -abs(max(19))+(min(a)) from t1 union select count(distinct -t1.d) from t1)),e)>=e),t1.f) | t1.a | 19 or (t1.c) not in (19, - -t1.f,t1.c) or exists(select 1 from t1 where t1.b not between t1.a and -11) then coalesce((select -b from t1 where -t1.a in (select c from t1 union select 17 from t1)),t1.d) when t1.a=c then c else t1.e end FROM t1 WHERE NOT (t1.e in (select +cast(avg(f) AS integer) from t1 union select case +max(19) | count(*) when count(*)*+count(*) then ~+count(*) else count(*) end from t1))} +} {400} +do_test randexpr-2.1041 { + db eval {SELECT case when f>coalesce((select c from t1 where coalesce((select max(c+c) from t1 where t1.f in (select - -abs(max(19))+(min(a)) from t1 union select count(distinct -t1.d) from t1)),e)>=e),t1.f) & t1.a & 19 or (t1.c) not in (19, - -t1.f,t1.c) or exists(select 1 from t1 where t1.b not between t1.a and -11) then coalesce((select -b from t1 where -t1.a in (select c from t1 union select 17 from t1)),t1.d) when t1.a=c then c else t1.e end FROM t1 WHERE NOT (t1.e in (select +cast(avg(f) AS integer) from t1 union select case +max(19) | count(*) when count(*)*+count(*) then ~+count(*) else count(*) end from t1))} +} {400} +do_test randexpr-2.1042 { + db eval {SELECT +case t1.d when d then t1.f else +t1.b+(select -count(distinct coalesce((select max(c) from t1 where exists(select 1 from t1 where 17 not between d and e)),case when t1.f+f-~17<>d then case when exists(select 1 from t1 where t1.d=(13)) then t1.e when c=t1.e then -a else f end when not 17>11 then t1.b else e end))-max(t1.d) from t1)+ -e-(t1.d) end-11-b FROM t1 WHERE e-case +t1.e when e*e then t1.d else case (abs(case when (abs(case when t1.a+11+t1.a>11-t1.e then +t1.f when e<=a then (c) else b end)/abs(13))*b between b and t1.f then -a else t1.c end+d)/abs(a)) when d then 13 else t1.e end end+e+t1.d<=c} +} {} +do_test randexpr-2.1043 { + db eval {SELECT +case t1.d when d then t1.f else +t1.b+(select -count(distinct coalesce((select max(c) from t1 where exists(select 1 from t1 where 17 not between d and e)),case when t1.f+f-~17<>d then case when exists(select 1 from t1 where t1.d=(13)) then t1.e when c=t1.e then -a else f end when not 17>11 then t1.b else e end))-max(t1.d) from t1)+ -e-(t1.d) end-11-b FROM t1 WHERE NOT (e-case +t1.e when e*e then t1.d else case (abs(case when (abs(case when t1.a+11+t1.a>11-t1.e then +t1.f when e<=a then (c) else b end)/abs(13))*b between b and t1.f then -a else t1.c end+d)/abs(a)) when d then 13 else t1.e end end+e+t1.d<=c)} +} {389} +do_test randexpr-2.1044 { + db eval {SELECT + -(select count(*) from t1)*(t1.b)-a-t1.e+17*coalesce((select max(13) from t1 where not exists(select 1 from t1 where case when t1.ft1.d then 17 else -17 end* -(t1.f)=(t1.a))), -d)*t1.f*t1.a* -e FROM t1 WHERE not exists(select 1 from t1 where ~case when d+ -t1.c+11*t1.e-t1.c*a*(t1.b)<=~~t1.b then f else case b when t1.b*t1.c-t1.d then c-b else -t1.c end end-13+f>=case when d not between t1.c and (t1.b) then t1.e else t1.c end) or t1.d in (d,t1.c,t1.c)} +} {-6630000800} +do_test randexpr-2.1045 { + db eval {SELECT + -(select count(*) from t1)*(t1.b)-a-t1.e+17*coalesce((select max(13) from t1 where not exists(select 1 from t1 where case when t1.ft1.d then 17 else -17 end* -(t1.f)=(t1.a))), -d)*t1.f*t1.a* -e FROM t1 WHERE NOT (not exists(select 1 from t1 where ~case when d+ -t1.c+11*t1.e-t1.c*a*(t1.b)<=~~t1.b then f else case b when t1.b*t1.c-t1.d then c-b else -t1.c end end-13+f>=case when d not between t1.c and (t1.b) then t1.e else t1.c end) or t1.d in (d,t1.c,t1.c))} +} {} +do_test randexpr-2.1046 { + db eval {SELECT (abs((select -~~ -count(*)+++count(distinct c) from t1))/abs(coalesce((select e from t1 where (case when case when b not between case t1.d when f then -t1.c else t1.e end and c then d when b=19 then t1.c else d end in (select max(13) from t1 union select count(distinct b) from t1) and t1.d not in (a,t1.b,a) or -t1.d between 13 and e then 17+t1.e when 19 not between t1.f and 17 then t1.b else t1.a end in (17,(t1.e),t1.a))),b) | 17)) FROM t1 WHERE 11>t1.b} +} {} +do_test randexpr-2.1047 { + db eval {SELECT (abs((select -~~ -count(*)+++count(distinct c) from t1))/abs(coalesce((select e from t1 where (case when case when b not between case t1.d when f then -t1.c else t1.e end and c then d when b=19 then t1.c else d end in (select max(13) from t1 union select count(distinct b) from t1) and t1.d not in (a,t1.b,a) or -t1.d between 13 and e then 17+t1.e when 19 not between t1.f and 17 then t1.b else t1.a end in (17,(t1.e),t1.a))),b) | 17)) FROM t1 WHERE NOT (11>t1.b)} +} {0} +do_test randexpr-2.1048 { + db eval {SELECT coalesce((select max(t1.d) from t1 where coalesce((select e from t1 where case when (c)<>11+case f when t1.a then (select abs( -cast(avg(t1.c) AS integer)) | max((17)) | cast(avg(t1.d) AS integer)-count(distinct e) from t1) else 17*(abs(case t1.d when t1.b then a else b end)/abs(b)) end- -c-17+c*t1.c- -t1.d then t1.c else e end>=f),d)<>t1.a), -t1.f) FROM t1 WHERE not a<=17-t1.f} +} {400} +do_test randexpr-2.1049 { + db eval {SELECT coalesce((select max(t1.d) from t1 where coalesce((select e from t1 where case when (c)<>11+case f when t1.a then (select abs( -cast(avg(t1.c) AS integer)) | max((17)) | cast(avg(t1.d) AS integer)-count(distinct e) from t1) else 17*(abs(case t1.d when t1.b then a else b end)/abs(b)) end- -c-17+c*t1.c- -t1.d then t1.c else e end>=f),d)<>t1.a), -t1.f) FROM t1 WHERE NOT (not a<=17-t1.f)} +} {} +do_test randexpr-2.1050 { + db eval {SELECT coalesce((select max(t1.d) from t1 where coalesce((select e from t1 where case when (c)<>11+case f when t1.a then (select abs( -cast(avg(t1.c) AS integer)) & max((17)) & cast(avg(t1.d) AS integer)-count(distinct e) from t1) else 17*(abs(case t1.d when t1.b then a else b end)/abs(b)) end- -c-17+c*t1.c- -t1.d then t1.c else e end>=f),d)<>t1.a), -t1.f) FROM t1 WHERE not a<=17-t1.f} +} {400} +do_test randexpr-2.1051 { + db eval {SELECT coalesce((select coalesce((select ~d from t1 where t1.b-t1.c+13 not between t1.b and (abs(t1.a-case t1.c when t1.c | (select max((abs(case when (select count(*) from t1)<>(~t1.e-13*+d+d) then -t1.e else -t1.f end*13)/abs(f))-t1.f) from t1) then t1.f else t1.c end)/abs(c))),t1.e) from t1 where t1.f=f), - -11) FROM t1 WHERE case ((abs(t1.e)/abs(case b when ~17 then 19+(t1.d)+13 else case t1.a*17 when c then 19*case when c<>coalesce((select max(~a) from t1 where 19<>case case when t1.d in (select +count(distinct 11) from t1 union select ( -max(a)) from t1) then t1.f else b end when t1.f then d else t1.a end-t1.b),11) then t1.b else t1.d end else 11 end end))) when t1.b then 11 else t1.d end*t1.c= -t1.f} +} {} +do_test randexpr-2.1052 { + db eval {SELECT coalesce((select coalesce((select ~d from t1 where t1.b-t1.c+13 not between t1.b and (abs(t1.a-case t1.c when t1.c | (select max((abs(case when (select count(*) from t1)<>(~t1.e-13*+d+d) then -t1.e else -t1.f end*13)/abs(f))-t1.f) from t1) then t1.f else t1.c end)/abs(c))),t1.e) from t1 where t1.f=f), - -11) FROM t1 WHERE NOT (case ((abs(t1.e)/abs(case b when ~17 then 19+(t1.d)+13 else case t1.a*17 when c then 19*case when c<>coalesce((select max(~a) from t1 where 19<>case case when t1.d in (select +count(distinct 11) from t1 union select ( -max(a)) from t1) then t1.f else b end when t1.f then d else t1.a end-t1.b),11) then t1.b else t1.d end else 11 end end))) when t1.b then 11 else t1.d end*t1.c= -t1.f)} +} {-401} +do_test randexpr-2.1053 { + db eval {SELECT coalesce((select coalesce((select ~d from t1 where t1.b-t1.c+13 not between t1.b and (abs(t1.a-case t1.c when t1.c & (select max((abs(case when (select count(*) from t1)<>(~t1.e-13*+d+d) then -t1.e else -t1.f end*13)/abs(f))-t1.f) from t1) then t1.f else t1.c end)/abs(c))),t1.e) from t1 where t1.f=f), - -11) FROM t1 WHERE NOT (case ((abs(t1.e)/abs(case b when ~17 then 19+(t1.d)+13 else case t1.a*17 when c then 19*case when c<>coalesce((select max(~a) from t1 where 19<>case case when t1.d in (select +count(distinct 11) from t1 union select ( -max(a)) from t1) then t1.f else b end when t1.f then d else t1.a end-t1.b),11) then t1.b else t1.d end else 11 end end))) when t1.b then 11 else t1.d end*t1.c= -t1.f)} +} {-401} +do_test randexpr-2.1054 { + db eval {SELECT -13-case when (not d<=11-t1.c*t1.e+t1.b) then case when t1.f | coalesce((select +d from t1 where t1.d= -c),(t1.a)) not between b and t1.a then t1.f+a when t1.a<11 and exists(select 1 from t1 where t1.f in (t1.b,17,11)) then b else 19 end when (t1.b between t1.d and e) then b else -t1.c end FROM t1 WHERE case when b between case when coalesce((select t1.c-t1.c from t1 where 13*(select case min(11) when cast(avg(t1.c) AS integer) then (count(*)) else count(distinct 11) end+cast(avg( -f) AS integer) from t1)>=t1.a),t1.c) in ( -t1.c,d,b) then t1.e when f in (select e from t1 union select t1.d from t1) then f else c end and a and 13<>c and exists(select 1 from t1 where f<>c) then case when c in (11,b, -11) then t1.e else e end else 13 end<=t1.c} +} {-713} +do_test randexpr-2.1055 { + db eval {SELECT -13-case when (not d<=11-t1.c*t1.e+t1.b) then case when t1.f | coalesce((select +d from t1 where t1.d= -c),(t1.a)) not between b and t1.a then t1.f+a when t1.a<11 and exists(select 1 from t1 where t1.f in (t1.b,17,11)) then b else 19 end when (t1.b between t1.d and e) then b else -t1.c end FROM t1 WHERE NOT (case when b between case when coalesce((select t1.c-t1.c from t1 where 13*(select case min(11) when cast(avg(t1.c) AS integer) then (count(*)) else count(distinct 11) end+cast(avg( -f) AS integer) from t1)>=t1.a),t1.c) in ( -t1.c,d,b) then t1.e when f in (select e from t1 union select t1.d from t1) then f else c end and a and 13<>c and exists(select 1 from t1 where f<>c) then case when c in (11,b, -11) then t1.e else e end else 13 end<=t1.c)} +} {} +do_test randexpr-2.1056 { + db eval {SELECT -13-case when (not d<=11-t1.c*t1.e+t1.b) then case when t1.f & coalesce((select +d from t1 where t1.d= -c),(t1.a)) not between b and t1.a then t1.f+a when t1.a<11 and exists(select 1 from t1 where t1.f in (t1.b,17,11)) then b else 19 end when (t1.b between t1.d and e) then b else -t1.c end FROM t1 WHERE case when b between case when coalesce((select t1.c-t1.c from t1 where 13*(select case min(11) when cast(avg(t1.c) AS integer) then (count(*)) else count(distinct 11) end+cast(avg( -f) AS integer) from t1)>=t1.a),t1.c) in ( -t1.c,d,b) then t1.e when f in (select e from t1 union select t1.d from t1) then f else c end and a and 13<>c and exists(select 1 from t1 where f<>c) then case when c in (11,b, -11) then t1.e else e end else 13 end<=t1.c} +} {-713} +do_test randexpr-2.1057 { + db eval {SELECT t1.b | (abs( -(select ~ -~abs(case ~min((c* -b+c))+min(f) when ~abs(count(distinct 13))+(min(13)) then max(11) else count(*) end) from t1)-11 | +(abs(t1.d-t1.e)/abs(t1.b))-t1.f*19+t1.c*17)/abs(f))+t1.b FROM t1 WHERE (a between t1.e and -13)} +} {} +do_test randexpr-2.1058 { + db eval {SELECT t1.b | (abs( -(select ~ -~abs(case ~min((c* -b+c))+min(f) when ~abs(count(distinct 13))+(min(13)) then max(11) else count(*) end) from t1)-11 | +(abs(t1.d-t1.e)/abs(t1.b))-t1.f*19+t1.c*17)/abs(f))+t1.b FROM t1 WHERE NOT ((a between t1.e and -13))} +} {200} +do_test randexpr-2.1059 { + db eval {SELECT t1.b & (abs( -(select ~ -~abs(case ~min((c* -b+c))+min(f) when ~abs(count(distinct 13))+(min(13)) then max(11) else count(*) end) from t1)-11 & +(abs(t1.d-t1.e)/abs(t1.b))-t1.f*19+t1.c*17)/abs(f))+t1.b FROM t1 WHERE NOT ((a between t1.e and -13))} +} {192} +do_test randexpr-2.1060 { + db eval {SELECT t1.c-case t1.b when t1.f-t1.b-f then +coalesce((select b from t1 where (t1.d in (select (select count(*)+abs(count(*)) | ~cast(avg(b | case when 11 between b and (f) then b when (19)>19 then 17 else t1.e end) AS integer) | min(d) from t1) from t1 union select 19 from t1))),(abs(c*c)/abs(11))-a-t1.c+t1.f-t1.c)+b else b end FROM t1 WHERE (t1.d)+t1.b<( -t1.b)} +} {} +do_test randexpr-2.1061 { + db eval {SELECT t1.c-case t1.b when t1.f-t1.b-f then +coalesce((select b from t1 where (t1.d in (select (select count(*)+abs(count(*)) | ~cast(avg(b | case when 11 between b and (f) then b when (19)>19 then 17 else t1.e end) AS integer) | min(d) from t1) from t1 union select 19 from t1))),(abs(c*c)/abs(11))-a-t1.c+t1.f-t1.c)+b else b end FROM t1 WHERE NOT ((t1.d)+t1.b<( -t1.b))} +} {100} +do_test randexpr-2.1062 { + db eval {SELECT t1.c-case t1.b when t1.f-t1.b-f then +coalesce((select b from t1 where (t1.d in (select (select count(*)+abs(count(*)) & ~cast(avg(b & case when 11 between b and (f) then b when (19)>19 then 17 else t1.e end) AS integer) & min(d) from t1) from t1 union select 19 from t1))),(abs(c*c)/abs(11))-a-t1.c+t1.f-t1.c)+b else b end FROM t1 WHERE NOT ((t1.d)+t1.b<( -t1.b))} +} {100} +do_test randexpr-2.1063 { + db eval {SELECT 17*(select (case case min(t1.d+( -d | case 11* -11*11 when 13 then t1.c else -17 end)-d*t1.d)-count(*)-abs( -max(17)+~max(t1.b)) | +abs(cast(avg((a)) AS integer))+(count(*)) when -max(17) then -max(19) else (cast(avg(d) AS integer)) end when count(distinct t1.c) then min(b) else count(*) end) from t1) FROM t1 WHERE d>=(abs(coalesce((select max(d) from t1 where not not case when a in (select count(*)* -case +min(case when t1.e=(abs(coalesce((select max(d) from t1 where not not case when a in (select count(*)* -case +min(case when t1.e=(abs(coalesce((select max(d) from t1 where not not case when a in (select count(*)* -case +min(case when t1.ef),t1.f) and 11 not between 13 and 13 and ( -11<>c and t1.b>c) or 19<>t1.e and t1.b<=t1.f then +f*b when t1.d>=e then -13 else t1.c end when b then (17) else t1.d end+a+f*a FROM t1 WHERE not exists(select 1 from t1 where a between t1.f and 17 or e>=(d)*19+t1.e*c)} +} {59707} +do_test randexpr-2.1067 { + db eval {SELECT 11 | ~case case when e between 17 and coalesce((select max(((f-t1.f))) from t1 where d<>f),t1.f) and 11 not between 13 and 13 and ( -11<>c and t1.b>c) or 19<>t1.e and t1.b<=t1.f then +f*b when t1.d>=e then -13 else t1.c end when b then (17) else t1.d end+a+f*a FROM t1 WHERE NOT (not exists(select 1 from t1 where a between t1.f and 17 or e>=(d)*19+t1.e*c))} +} {} +do_test randexpr-2.1068 { + db eval {SELECT 11 & ~case case when e between 17 and coalesce((select max(((f-t1.f))) from t1 where d<>f),t1.f) and 11 not between 13 and 13 and ( -11<>c and t1.b>c) or 19<>t1.e and t1.b<=t1.f then +f*b when t1.d>=e then -13 else t1.c end when b then (17) else t1.d end+a+f*a FROM t1 WHERE not exists(select 1 from t1 where a between t1.f and 17 or e>=(d)*19+t1.e*c)} +} {3} +do_test randexpr-2.1069 { + db eval {SELECT -case when t1.d | ~b<>coalesce((select max(t1.c) from t1 where t1.c not between coalesce((select max(coalesce((select max(e) from t1 where 11 not in (case when 13 not between d and c then 17 when (t1.a) not in (e,b,b) then 19 else c end,a,t1.d)),b)+f) from t1 where t1.d not in (11,f,t1.e)),t1.b) and f),11) or 11<>(d) then -f* -d else (e) end*f FROM t1 WHERE case f when 11 then coalesce((select b from t1 where 19+case when 17*t1.d-t1.f+t1.f between t1.d-case when +d=coalesce((select max(f) from t1 where e>t1.f),17) and c=t1.e and b not in (17,11,(t1.f)) then -17 else t1.c end and c then -t1.a else t1.d end+11*e not between t1.f and d),13)+t1.d else -13 end=c} +} {} +do_test randexpr-2.1070 { + db eval {SELECT -case when t1.d | ~b<>coalesce((select max(t1.c) from t1 where t1.c not between coalesce((select max(coalesce((select max(e) from t1 where 11 not in (case when 13 not between d and c then 17 when (t1.a) not in (e,b,b) then 19 else c end,a,t1.d)),b)+f) from t1 where t1.d not in (11,f,t1.e)),t1.b) and f),11) or 11<>(d) then -f* -d else (e) end*f FROM t1 WHERE NOT (case f when 11 then coalesce((select b from t1 where 19+case when 17*t1.d-t1.f+t1.f between t1.d-case when +d=coalesce((select max(f) from t1 where e>t1.f),17) and c=t1.e and b not in (17,11,(t1.f)) then -17 else t1.c end and c then -t1.a else t1.d end+11*e not between t1.f and d),13)+t1.d else -13 end=c)} +} {-144000000} +do_test randexpr-2.1071 { + db eval {SELECT -case when t1.d & ~b<>coalesce((select max(t1.c) from t1 where t1.c not between coalesce((select max(coalesce((select max(e) from t1 where 11 not in (case when 13 not between d and c then 17 when (t1.a) not in (e,b,b) then 19 else c end,a,t1.d)),b)+f) from t1 where t1.d not in (11,f,t1.e)),t1.b) and f),11) or 11<>(d) then -f* -d else (e) end*f FROM t1 WHERE NOT (case f when 11 then coalesce((select b from t1 where 19+case when 17*t1.d-t1.f+t1.f between t1.d-case when +d=coalesce((select max(f) from t1 where e>t1.f),17) and c=t1.e and b not in (17,11,(t1.f)) then -17 else t1.c end and c then -t1.a else t1.d end+11*e not between t1.f and d),13)+t1.d else -13 end=c)} +} {-144000000} +do_test randexpr-2.1072 { + db eval {SELECT coalesce((select t1.b from t1 where not (t1.c>19) and 11<=+(abs(t1.b-19)/abs(a))+case when ((coalesce((select 13 from t1 where c in (b,t1.b,t1.d)),e))<>13) or f in ((t1.b),t1.e, -b) then 11+(c) else b end or b<>d),t1.f+t1.f+13) | - -a FROM t1 WHERE 13 between t1.c and 13+~19+c+(select min(f-(abs(17)/abs((t1.e)))) from t1)} +} {} +do_test randexpr-2.1073 { + db eval {SELECT coalesce((select t1.b from t1 where not (t1.c>19) and 11<=+(abs(t1.b-19)/abs(a))+case when ((coalesce((select 13 from t1 where c in (b,t1.b,t1.d)),e))<>13) or f in ((t1.b),t1.e, -b) then 11+(c) else b end or b<>d),t1.f+t1.f+13) | - -a FROM t1 WHERE NOT (13 between t1.c and 13+~19+c+(select min(f-(abs(17)/abs((t1.e)))) from t1))} +} {236} +do_test randexpr-2.1074 { + db eval {SELECT coalesce((select t1.b from t1 where not (t1.c>19) and 11<=+(abs(t1.b-19)/abs(a))+case when ((coalesce((select 13 from t1 where c in (b,t1.b,t1.d)),e))<>13) or f in ((t1.b),t1.e, -b) then 11+(c) else b end or b<>d),t1.f+t1.f+13) & - -a FROM t1 WHERE NOT (13 between t1.c and 13+~19+c+(select min(f-(abs(17)/abs((t1.e)))) from t1))} +} {64} +do_test randexpr-2.1075 { + db eval {SELECT -(coalesce((select max(coalesce((select t1.f from t1 where not exists(select 1 from t1 where (abs(+b+19+19)/abs(t1.b))=(select -max(19) from t1)+t1.f),t1.e+t1.f)* -t1.e+19-f) from t1 where (( -t1.c<19) or d>=c)),t1.c))*c*((t1.b))-17 FROM t1 WHERE t1.e not between t1.f*c and t1.f+ -d} +} {18034859983} +do_test randexpr-2.1076 { + db eval {SELECT -(coalesce((select max(coalesce((select t1.f from t1 where not exists(select 1 from t1 where (abs(+b+19+19)/abs(t1.b))=(select -max(19) from t1)+t1.f),t1.e+t1.f)* -t1.e+19-f) from t1 where (( -t1.c<19) or d>=c)),t1.c))*c*((t1.b))-17 FROM t1 WHERE NOT (t1.e not between t1.f*c and t1.f+ -d)} +} {} +do_test randexpr-2.1077 { + db eval {SELECT case 17 when (t1.d)*coalesce((select (select case (cast(avg(c) AS integer)+max(case when (not d+ -t1.e not between 11 and -f) then f when b<(11) then t1.b else 11 end))+count(distinct t1.c)*max(b) when -min(e) | -count(distinct t1.c) then cast(avg(e) AS integer) else count(*) end from t1) from t1 where case c when a then a else t1.d end-11<>19),t1.a)+t1.b then f else t1.f end FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where (abs(d)/abs((f*+coalesce((select -~case when exists(select 1 from t1 where bt1.c or ((t1.c))<>e),(t1.e)))) from t1)*17 when e then a else t1.e end-t1.b-19 from t1 where t1.e in (select abs(+min(f)+cast(avg( -a) AS integer)) from t1 union select count(distinct c) from t1)),d))))<>f))} +} {} +do_test randexpr-2.1078 { + db eval {SELECT case 17 when (t1.d)*coalesce((select (select case (cast(avg(c) AS integer)+max(case when (not d+ -t1.e not between 11 and -f) then f when b<(11) then t1.b else 11 end))+count(distinct t1.c)*max(b) when -min(e) | -count(distinct t1.c) then cast(avg(e) AS integer) else count(*) end from t1) from t1 where case c when a then a else t1.d end-11<>19),t1.a)+t1.b then f else t1.f end FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where (abs(d)/abs((f*+coalesce((select -~case when exists(select 1 from t1 where bt1.c or ((t1.c))<>e),(t1.e)))) from t1)*17 when e then a else t1.e end-t1.b-19 from t1 where t1.e in (select abs(+min(f)+cast(avg( -a) AS integer)) from t1 union select count(distinct c) from t1)),d))))<>f)))} +} {600} +do_test randexpr-2.1079 { + db eval {SELECT case 17 when (t1.d)*coalesce((select (select case (cast(avg(c) AS integer)+max(case when (not d+ -t1.e not between 11 and -f) then f when b<(11) then t1.b else 11 end))+count(distinct t1.c)*max(b) when -min(e) & -count(distinct t1.c) then cast(avg(e) AS integer) else count(*) end from t1) from t1 where case c when a then a else t1.d end-11<>19),t1.a)+t1.b then f else t1.f end FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where (abs(d)/abs((f*+coalesce((select -~case when exists(select 1 from t1 where bt1.c or ((t1.c))<>e),(t1.e)))) from t1)*17 when e then a else t1.e end-t1.b-19 from t1 where t1.e in (select abs(+min(f)+cast(avg( -a) AS integer)) from t1 union select count(distinct c) from t1)),d))))<>f)))} +} {600} +do_test randexpr-2.1080 { + db eval {SELECT ((select -case min(17 | (abs(a)/abs(case (select max(a) from t1)+13+t1.c when c then (abs(case when 17<>a and t1.c=d then ((17)) else e end)/abs(t1.b)) else 17 end)) | f*a) when abs(~(count(distinct t1.e))-abs((~max(c)))-count(*) | min(t1.f)+max(11)) then -cast(avg((b)) AS integer) else min(b) end from t1))*a FROM t1 WHERE (13)-(t1.a*17-t1.b)-coalesce((select (select -cast(avg(t1.c) AS integer)+case - -count(*) | (count(distinct t1.a)) when -min(t1.e) then (max(t1.d)) else count(distinct t1.b) end from t1)-e+(abs(17)/abs(e)) from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (d)>=13 and (t1.b not in (c,a, -t1.d) or t1.e in (select c from t1 union select t1.c from t1)) or 11<=t1.d))),17) in (select e from t1 union select e from t1)} +} {} +do_test randexpr-2.1081 { + db eval {SELECT ((select -case min(17 | (abs(a)/abs(case (select max(a) from t1)+13+t1.c when c then (abs(case when 17<>a and t1.c=d then ((17)) else e end)/abs(t1.b)) else 17 end)) | f*a) when abs(~(count(distinct t1.e))-abs((~max(c)))-count(*) | min(t1.f)+max(11)) then -cast(avg((b)) AS integer) else min(b) end from t1))*a FROM t1 WHERE NOT ((13)-(t1.a*17-t1.b)-coalesce((select (select -cast(avg(t1.c) AS integer)+case - -count(*) | (count(distinct t1.a)) when -min(t1.e) then (max(t1.d)) else count(distinct t1.b) end from t1)-e+(abs(17)/abs(e)) from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (d)>=13 and (t1.b not in (c,a, -t1.d) or t1.e in (select c from t1 union select t1.c from t1)) or 11<=t1.d))),17) in (select e from t1 union select e from t1))} +} {-20000} +do_test randexpr-2.1082 { + db eval {SELECT ((select -case min(17 & (abs(a)/abs(case (select max(a) from t1)+13+t1.c when c then (abs(case when 17<>a and t1.c=d then ((17)) else e end)/abs(t1.b)) else 17 end)) & f*a) when abs(~(count(distinct t1.e))-abs((~max(c)))-count(*) & min(t1.f)+max(11)) then -cast(avg((b)) AS integer) else min(b) end from t1))*a FROM t1 WHERE NOT ((13)-(t1.a*17-t1.b)-coalesce((select (select -cast(avg(t1.c) AS integer)+case - -count(*) | (count(distinct t1.a)) when -min(t1.e) then (max(t1.d)) else count(distinct t1.b) end from t1)-e+(abs(17)/abs(e)) from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where (d)>=13 and (t1.b not in (c,a, -t1.d) or t1.e in (select c from t1 union select t1.c from t1)) or 11<=t1.d))),17) in (select e from t1 union select e from t1))} +} {-20000} +do_test randexpr-2.1083 { + db eval {SELECT case when (select -min(11) from t1)<>(abs(17)/abs(t1.d | e)) then case 11+case 11 when b | e-e then 19+e else b end*(abs(t1.a)/abs(b | a)) | coalesce((select case when a in (select cast(avg(d) AS integer) from t1 union select - - -max(c) from t1) or e not in (c,d,a) then +13 when t1.a>a then 19 else f end from t1 where t1.c=13 or f<>t1.e),a) when f then f else c end else t1.e end FROM t1 WHERE ~17 in (11,t1.c,19)} +} {} +do_test randexpr-2.1084 { + db eval {SELECT case when (select -min(11) from t1)<>(abs(17)/abs(t1.d | e)) then case 11+case 11 when b | e-e then 19+e else b end*(abs(t1.a)/abs(b | a)) | coalesce((select case when a in (select cast(avg(d) AS integer) from t1 union select - - -max(c) from t1) or e not in (c,d,a) then +13 when t1.a>a then 19 else f end from t1 where t1.c=13 or f<>t1.e),a) when f then f else c end else t1.e end FROM t1 WHERE NOT (~17 in (11,t1.c,19))} +} {300} +do_test randexpr-2.1085 { + db eval {SELECT case when (select -min(11) from t1)<>(abs(17)/abs(t1.d & e)) then case 11+case 11 when b & e-e then 19+e else b end*(abs(t1.a)/abs(b & a)) & coalesce((select case when a in (select cast(avg(d) AS integer) from t1 union select - - -max(c) from t1) or e not in (c,d,a) then +13 when t1.a>a then 19 else f end from t1 where t1.c=13 or f<>t1.e),a) when f then f else c end else t1.e end FROM t1 WHERE NOT (~17 in (11,t1.c,19))} +} {300} +do_test randexpr-2.1086 { + db eval {SELECT (select case +cast(avg(+19) AS integer) when (abs(count(*))) then (cast(avg(e*t1.b) AS integer)) else cast(avg(t1.a) AS integer) end+count(*) | +max(f-t1.e*t1.e | (f)* -19+ -b*d) | count(*)*count(*)* -count(*) | ~count(distinct -b)*cast(avg(t1.f) AS integer)+count(*) from t1)-t1.c+t1.b FROM t1 WHERE ((select -count(*)+min(case ~coalesce((select max(d) from t1 where (not not exists(select 1 from t1 where t1.b not in ((select -max(a)+(count(*)) from t1) | c+case when t1.e not in (13,e,c) then (t1.f) else t1.c end+17*c+19,c,e)))),t1.f) when (f) then t1.a else t1.f end | b | t1.a) from t1) in (c,t1.c+ -a,f))} +} {} +do_test randexpr-2.1087 { + db eval {SELECT (select case +cast(avg(+19) AS integer) when (abs(count(*))) then (cast(avg(e*t1.b) AS integer)) else cast(avg(t1.a) AS integer) end+count(*) | +max(f-t1.e*t1.e | (f)* -19+ -b*d) | count(*)*count(*)* -count(*) | ~count(distinct -b)*cast(avg(t1.f) AS integer)+count(*) from t1)-t1.c+t1.b FROM t1 WHERE NOT (((select -count(*)+min(case ~coalesce((select max(d) from t1 where (not not exists(select 1 from t1 where t1.b not in ((select -max(a)+(count(*)) from t1) | c+case when t1.e not in (13,e,c) then (t1.f) else t1.c end+17*c+19,c,e)))),t1.f) when (f) then t1.a else t1.f end | b | t1.a) from t1) in (c,t1.c+ -a,f)))} +} {-101} +do_test randexpr-2.1088 { + db eval {SELECT (select case +cast(avg(+19) AS integer) when (abs(count(*))) then (cast(avg(e*t1.b) AS integer)) else cast(avg(t1.a) AS integer) end+count(*) & +max(f-t1.e*t1.e & (f)* -19+ -b*d) & count(*)*count(*)* -count(*) & ~count(distinct -b)*cast(avg(t1.f) AS integer)+count(*) from t1)-t1.c+t1.b FROM t1 WHERE NOT (((select -count(*)+min(case ~coalesce((select max(d) from t1 where (not not exists(select 1 from t1 where t1.b not in ((select -max(a)+(count(*)) from t1) | c+case when t1.e not in (13,e,c) then (t1.f) else t1.c end+17*c+19,c,e)))),t1.f) when (f) then t1.a else t1.f end | b | t1.a) from t1) in (c,t1.c+ -a,f)))} +} {-36} +do_test randexpr-2.1089 { + db eval {SELECT (coalesce((select (select -~+ -abs(case cast(avg(a*t1.d) AS integer) when case ~case count(distinct ((abs(t1.a)/abs(d)))) when case cast(avg(17) AS integer)-count(*) when -count(*) then count(distinct d) else (max(t1.d)) end*count(*) then count(distinct t1.c) else min(19) end-count(*) when cast(avg(t1.a) AS integer) then ((count(*))) else min(a) end then (count(*)) else max(e) end)*(count(*))*max(a) from t1) from t1 where (19>=(17))),d)) FROM t1 WHERE exists(select 1 from t1 where 19 in (t1.a*coalesce((select a from t1 where (11t1.b),t1.e)) from t1 where e not between 13 and t1.c),(a))-t1.d and 13),13*b)-17, -b,17))} +} {} +do_test randexpr-2.1090 { + db eval {SELECT (coalesce((select (select -~+ -abs(case cast(avg(a*t1.d) AS integer) when case ~case count(distinct ((abs(t1.a)/abs(d)))) when case cast(avg(17) AS integer)-count(*) when -count(*) then count(distinct d) else (max(t1.d)) end*count(*) then count(distinct t1.c) else min(19) end-count(*) when cast(avg(t1.a) AS integer) then ((count(*))) else min(a) end then (count(*)) else max(e) end)*(count(*))*max(a) from t1) from t1 where (19>=(17))),d)) FROM t1 WHERE NOT (exists(select 1 from t1 where 19 in (t1.a*coalesce((select a from t1 where (11t1.b),t1.e)) from t1 where e not between 13 and t1.c),(a))-t1.d and 13),13*b)-17, -b,17)))} +} {-49900} +do_test randexpr-2.1091 { + db eval {SELECT case when (coalesce((select max((select +max(c) from t1)) from t1 where t1.c<>t1.a),d) not in (t1.d,+case when 17>19 then e when t1.b<>+(select count(*) from t1) then t1.e else t1.d end,t1.c)) then (select count(*)-count(distinct t1.d)+ -max( -t1.c-a)*case cast(avg((f)) AS integer) when count(distinct d) then max((13)) else max(t1.d) end from t1)*t1.b else t1.c end | -13*t1.d*t1.c FROM t1 WHERE c in (select case count(distinct ~(abs( -a)/abs(d))) when ~count(*) then ~min(coalesce((select max((abs(e)/abs(d))) from t1 where not exists(select 1 from t1 where t1.e>( -+t1.a-t1.e*17))),19))+count(*) else case ~ -cast(avg((11)) AS integer) | +cast(avg(d) AS integer) | (cast(avg(c) AS integer))+min(t1.e) when min(t1.c) then max(11) else -count(*) end end+max(t1.c) from t1 union select -count(*) from t1)} +} {} +do_test randexpr-2.1092 { + db eval {SELECT case when (coalesce((select max((select +max(c) from t1)) from t1 where t1.c<>t1.a),d) not in (t1.d,+case when 17>19 then e when t1.b<>+(select count(*) from t1) then t1.e else t1.d end,t1.c)) then (select count(*)-count(distinct t1.d)+ -max( -t1.c-a)*case cast(avg((f)) AS integer) when count(distinct d) then max((13)) else max(t1.d) end from t1)*t1.b else t1.c end | -13*t1.d*t1.c FROM t1 WHERE NOT (c in (select case count(distinct ~(abs( -a)/abs(d))) when ~count(*) then ~min(coalesce((select max((abs(e)/abs(d))) from t1 where not exists(select 1 from t1 where t1.e>( -+t1.a-t1.e*17))),19))+count(*) else case ~ -cast(avg((11)) AS integer) | +cast(avg(d) AS integer) | (cast(avg(c) AS integer))+min(t1.e) when min(t1.c) then max(11) else -count(*) end end+max(t1.c) from t1 union select -count(*) from t1))} +} {-1559700} +do_test randexpr-2.1093 { + db eval {SELECT case when (coalesce((select max((select +max(c) from t1)) from t1 where t1.c<>t1.a),d) not in (t1.d,+case when 17>19 then e when t1.b<>+(select count(*) from t1) then t1.e else t1.d end,t1.c)) then (select count(*)-count(distinct t1.d)+ -max( -t1.c-a)*case cast(avg((f)) AS integer) when count(distinct d) then max((13)) else max(t1.d) end from t1)*t1.b else t1.c end & -13*t1.d*t1.c FROM t1 WHERE NOT (c in (select case count(distinct ~(abs( -a)/abs(d))) when ~count(*) then ~min(coalesce((select max((abs(e)/abs(d))) from t1 where not exists(select 1 from t1 where t1.e>( -+t1.a-t1.e*17))),19))+count(*) else case ~ -cast(avg((11)) AS integer) | +cast(avg(d) AS integer) | (cast(avg(c) AS integer))+min(t1.e) when min(t1.c) then max(11) else -count(*) end end+max(t1.c) from t1 union select -count(*) from t1))} +} {0} +do_test randexpr-2.1094 { + db eval {SELECT coalesce((select max(t1.c+t1.b-t1.b+(abs(d++t1.f)/abs(t1.a)) | 13*17) from t1 where coalesce((select 11 from t1 where case case case c when d then t1.d else 13 end when b then -11 else t1.b end when 13 then (t1.a) else d end not in (c,13,a)),t1.c) | f not in (t1.a,t1.c,13) and not exists(select 1 from t1 where t1.c in (select e from t1 union select -11 from t1))),t1.f) FROM t1 WHERE (((13+coalesce((select max(13) from t1 where not exists(select 1 from t1 where ((abs(c-case when not exists(select 1 from t1 where ((f) between c and 13)) then (select case min(f) when max(17) then min(13) else min(b) end from t1) when 17 in (t1.e,13,f) then -13 else 11 end)/abs(t1.f)) in (select min(c) from t1 union select -count(*) | + -min(19) from t1))) and f<13),t1.e+t1.c) in (select count(distinct c)-count(*) from t1 union select -case min((e))+cast(avg(t1.a) AS integer) when ((min(t1.c))) then count(distinct e) else -cast(avg(t1.d) AS integer) end from t1))))} +} {} +do_test randexpr-2.1095 { + db eval {SELECT coalesce((select max(t1.c+t1.b-t1.b+(abs(d++t1.f)/abs(t1.a)) | 13*17) from t1 where coalesce((select 11 from t1 where case case case c when d then t1.d else 13 end when b then -11 else t1.b end when 13 then (t1.a) else d end not in (c,13,a)),t1.c) | f not in (t1.a,t1.c,13) and not exists(select 1 from t1 where t1.c in (select e from t1 union select -11 from t1))),t1.f) FROM t1 WHERE NOT ((((13+coalesce((select max(13) from t1 where not exists(select 1 from t1 where ((abs(c-case when not exists(select 1 from t1 where ((f) between c and 13)) then (select case min(f) when max(17) then min(13) else min(b) end from t1) when 17 in (t1.e,13,f) then -13 else 11 end)/abs(t1.f)) in (select min(c) from t1 union select -count(*) | + -min(19) from t1))) and f<13),t1.e+t1.c) in (select count(distinct c)-count(*) from t1 union select -case min((e))+cast(avg(t1.a) AS integer) when ((min(t1.c))) then count(distinct e) else -cast(avg(t1.d) AS integer) end from t1)))))} +} {511} +do_test randexpr-2.1096 { + db eval {SELECT coalesce((select max(t1.c+t1.b-t1.b+(abs(d++t1.f)/abs(t1.a)) & 13*17) from t1 where coalesce((select 11 from t1 where case case case c when d then t1.d else 13 end when b then -11 else t1.b end when 13 then (t1.a) else d end not in (c,13,a)),t1.c) & f not in (t1.a,t1.c,13) and not exists(select 1 from t1 where t1.c in (select e from t1 union select -11 from t1))),t1.f) FROM t1 WHERE NOT ((((13+coalesce((select max(13) from t1 where not exists(select 1 from t1 where ((abs(c-case when not exists(select 1 from t1 where ((f) between c and 13)) then (select case min(f) when max(17) then min(13) else min(b) end from t1) when 17 in (t1.e,13,f) then -13 else 11 end)/abs(t1.f)) in (select min(c) from t1 union select -count(*) | + -min(19) from t1))) and f<13),t1.e+t1.c) in (select count(distinct c)-count(*) from t1 union select -case min((e))+cast(avg(t1.a) AS integer) when ((min(t1.c))) then count(distinct e) else -cast(avg(t1.d) AS integer) end from t1)))))} +} {20} +do_test randexpr-2.1097 { + db eval {SELECT case when t1.a in (select t1.e*case when t1.b between t1.d and 11 or c-case when (t1.e=13) then ~e when e<>a then t1.d else t1.f end in (11,t1.e,t1.c) and 11 not between t1.a and 13 and 19<11 then 11 else t1.e end*t1.d from t1 union select t1.c from t1) then a when e between e and b then ((19)) else 11 end FROM t1 WHERE coalesce((select (select count(distinct t1.f) from t1) from t1 where case coalesce((select max(t1.d) from t1 where 17<>19),t1.d) when a then coalesce((select ~t1.f- - -c-c*17-f-c-t1.a from t1 where (t1.f) in (select max(11) from t1 union select ~cast(avg(17) AS integer) | ~count(*)+max(f)- -cast(avg(11) AS integer) from t1)),13) else e end in (a,t1.c,11)),c)>=t1.e} +} {} +do_test randexpr-2.1098 { + db eval {SELECT case when t1.a in (select t1.e*case when t1.b between t1.d and 11 or c-case when (t1.e=13) then ~e when e<>a then t1.d else t1.f end in (11,t1.e,t1.c) and 11 not between t1.a and 13 and 19<11 then 11 else t1.e end*t1.d from t1 union select t1.c from t1) then a when e between e and b then ((19)) else 11 end FROM t1 WHERE NOT (coalesce((select (select count(distinct t1.f) from t1) from t1 where case coalesce((select max(t1.d) from t1 where 17<>19),t1.d) when a then coalesce((select ~t1.f- - -c-c*17-f-c-t1.a from t1 where (t1.f) in (select max(11) from t1 union select ~cast(avg(17) AS integer) | ~count(*)+max(f)- -cast(avg(11) AS integer) from t1)),13) else e end in (a,t1.c,11)),c)>=t1.e)} +} {11} +do_test randexpr-2.1099 { + db eval {SELECT coalesce((select max(case t1.b+(select ~((cast(avg(17) AS integer)))*min(a)+ -count(distinct b)*cast(avg(t1.b) AS integer)-count(*)+max(19) from t1)-(e) when d then 13 else 13*c end+t1.c) from t1 where t1.b in (select +cast(avg(e) AS integer)*case count(*) when cast(avg(13) AS integer) then count(distinct t1.b) else count(*) end-(count(distinct 19))*min(t1.d) from t1 union select max(a) from t1)),(f))*e+t1.f*19 FROM t1 WHERE 17 not between -t1.e and d} +} {} +do_test randexpr-2.1100 { + db eval {SELECT coalesce((select max(case t1.b+(select ~((cast(avg(17) AS integer)))*min(a)+ -count(distinct b)*cast(avg(t1.b) AS integer)-count(*)+max(19) from t1)-(e) when d then 13 else 13*c end+t1.c) from t1 where t1.b in (select +cast(avg(e) AS integer)*case count(*) when cast(avg(13) AS integer) then count(distinct t1.b) else count(*) end-(count(distinct 19))*min(t1.d) from t1 union select max(a) from t1)),(f))*e+t1.f*19 FROM t1 WHERE NOT (17 not between -t1.e and d)} +} {311400} +do_test randexpr-2.1101 { + db eval {SELECT coalesce((select max(~19) from t1 where 11 in (select t1.b-11*coalesce((select max(b) from t1 where coalesce((select max(e) from t1 where c*case 19*19+coalesce((select 19 from t1 where (11 not in (13+t1.d,b,(11)))),13)*d when t1.e then t1.b else t1.b end+t1.e between d and t1.b),t1.b) | (f)<>13), - -17)+c from t1 union select -19 from t1)),17) FROM t1 WHERE ~t1.d not between 11*13-+t1.d-11-f and t1.d} +} {} +do_test randexpr-2.1102 { + db eval {SELECT coalesce((select max(~19) from t1 where 11 in (select t1.b-11*coalesce((select max(b) from t1 where coalesce((select max(e) from t1 where c*case 19*19+coalesce((select 19 from t1 where (11 not in (13+t1.d,b,(11)))),13)*d when t1.e then t1.b else t1.b end+t1.e between d and t1.b),t1.b) | (f)<>13), - -17)+c from t1 union select -19 from t1)),17) FROM t1 WHERE NOT (~t1.d not between 11*13-+t1.d-11-f and t1.d)} +} {17} +do_test randexpr-2.1103 { + db eval {SELECT coalesce((select max(~19) from t1 where 11 in (select t1.b-11*coalesce((select max(b) from t1 where coalesce((select max(e) from t1 where c*case 19*19+coalesce((select 19 from t1 where (11 not in (13+t1.d,b,(11)))),13)*d when t1.e then t1.b else t1.b end+t1.e between d and t1.b),t1.b) & (f)<>13), - -17)+c from t1 union select -19 from t1)),17) FROM t1 WHERE NOT (~t1.d not between 11*13-+t1.d-11-f and t1.d)} +} {17} +do_test randexpr-2.1104 { + db eval {SELECT case t1.b when coalesce((select max(17+coalesce((select max(coalesce((select (select count(distinct case f when 19 then coalesce((select coalesce((select max(11-(abs(d)/abs(11))) from t1 where not -a in (19,t1.b,17)),17) from t1 where (f in (b,f,t1.a))),b) else b end) from t1) from t1 where 17 between e and t1.f),t1.a)) from t1 where 13>=e),b)) from t1 where t1.f>t1.f),t1.b) then 17 else t1.f end FROM t1 WHERE not exists(select 1 from t1 where 13 between a+17 and (t1.c))} +} {17} +do_test randexpr-2.1105 { + db eval {SELECT case t1.b when coalesce((select max(17+coalesce((select max(coalesce((select (select count(distinct case f when 19 then coalesce((select coalesce((select max(11-(abs(d)/abs(11))) from t1 where not -a in (19,t1.b,17)),17) from t1 where (f in (b,f,t1.a))),b) else b end) from t1) from t1 where 17 between e and t1.f),t1.a)) from t1 where 13>=e),b)) from t1 where t1.f>t1.f),t1.b) then 17 else t1.f end FROM t1 WHERE NOT (not exists(select 1 from t1 where 13 between a+17 and (t1.c)))} +} {} +do_test randexpr-2.1106 { + db eval {SELECT case when coalesce((select max(d) from t1 where t1.a in (select a-a from t1 union select a from t1)),t1.b)*(select max(t1.b) from t1)>=case when t1.b=t1.a} +} {300} +do_test randexpr-2.1107 { + db eval {SELECT case when coalesce((select max(d) from t1 where t1.a in (select a-a from t1 union select a from t1)),t1.b)*(select max(t1.b) from t1)>=case when t1.b=t1.a)} +} {} +do_test randexpr-2.1108 { + db eval {SELECT case when case when f*~case when t1.c*t1.f in (c,t1.b,(17)) then 17 when 11>t1.c then 13 else t1.e end+t1.f in (select +max(e)+case (count(distinct a)*count(*))+max(19) when -max(11) then count(distinct a) else ((count(distinct t1.d))) end from t1 union select count(distinct c) from t1) then 17 else d end+(t1.c)<17 then b when not exists(select 1 from t1 where 11>t1.b) then t1.d else t1.a end FROM t1 WHERE t1.b< -f} +} {} +do_test randexpr-2.1109 { + db eval {SELECT case when case when f*~case when t1.c*t1.f in (c,t1.b,(17)) then 17 when 11>t1.c then 13 else t1.e end+t1.f in (select +max(e)+case (count(distinct a)*count(*))+max(19) when -max(11) then count(distinct a) else ((count(distinct t1.d))) end from t1 union select count(distinct c) from t1) then 17 else d end+(t1.c)<17 then b when not exists(select 1 from t1 where 11>t1.b) then t1.d else t1.a end FROM t1 WHERE NOT (t1.b< -f)} +} {400} +do_test randexpr-2.1110 { + db eval {SELECT (select cast(avg(f) AS integer) | ~++cast(avg((abs(17)/abs( -f+(c-coalesce((select case when c=d and t1.e=t1.b then e when e in (t1.b,19,t1.c) then 17 else d end from t1 where e between t1.a and t1.c),a))+a))) AS integer)-abs( -min(t1.c))-abs(max((t1.b)) | -~(count(*))+max(17))+cast(avg(t1.a) AS integer) | min(a)*(count(*))*min(17) from t1) FROM t1 WHERE b-(t1.e*t1.e)-t1.d=t1.c} +} {} +do_test randexpr-2.1111 { + db eval {SELECT (select cast(avg(f) AS integer) | ~++cast(avg((abs(17)/abs( -f+(c-coalesce((select case when c=d and t1.e=t1.b then e when e in (t1.b,19,t1.c) then 17 else d end from t1 where e between t1.a and t1.c),a))+a))) AS integer)-abs( -min(t1.c))-abs(max((t1.b)) | -~(count(*))+max(17))+cast(avg(t1.a) AS integer) | min(a)*(count(*))*min(17) from t1) FROM t1 WHERE NOT (b-(t1.e*t1.e)-t1.d=t1.c)} +} {-260} +do_test randexpr-2.1112 { + db eval {SELECT (select cast(avg(f) AS integer) & ~++cast(avg((abs(17)/abs( -f+(c-coalesce((select case when c=d and t1.e=t1.b then e when e in (t1.b,19,t1.c) then 17 else d end from t1 where e between t1.a and t1.c),a))+a))) AS integer)-abs( -min(t1.c))-abs(max((t1.b)) & -~(count(*))+max(17))+cast(avg(t1.a) AS integer) & min(a)*(count(*))*min(17) from t1) FROM t1 WHERE NOT (b-(t1.e*t1.e)-t1.d=t1.c)} +} {512} +do_test randexpr-2.1113 { + db eval {SELECT ~+coalesce((select case when t1.f>d then b when (abs(t1.a)/abs((abs(f)/abs(t1.c))))*case ~b when e then (select cast(avg( -+t1.f) AS integer) from t1) else c end+coalesce((select max(17*case t1.a+b when t1.b then t1.d else t1.f end) from t1 where d=e),t1.f)+13>=17 then 19 else f end from t1 where t1.a in (select d from t1 union select e from t1)),b) FROM t1 WHERE 17<>f-~t1.a-case when -b in (t1.b,(select min( -coalesce((select max(coalesce((select a- -t1.b from t1 where 11 in (t1.b,13, -t1.e) and f not between -13 and t1.b),c)) from t1 where b not in (a,11,17)),t1.e)) from t1),e) or not exists(select 1 from t1 where t1.c in (select t1.b from t1 union select t1.b from t1)) then coalesce((select -t1.e from t1 where e<>t1.e),f) when not t1.e<>t1.c then 19 else e end} +} {-201} +do_test randexpr-2.1114 { + db eval {SELECT ~+coalesce((select case when t1.f>d then b when (abs(t1.a)/abs((abs(f)/abs(t1.c))))*case ~b when e then (select cast(avg( -+t1.f) AS integer) from t1) else c end+coalesce((select max(17*case t1.a+b when t1.b then t1.d else t1.f end) from t1 where d=e),t1.f)+13>=17 then 19 else f end from t1 where t1.a in (select d from t1 union select e from t1)),b) FROM t1 WHERE NOT (17<>f-~t1.a-case when -b in (t1.b,(select min( -coalesce((select max(coalesce((select a- -t1.b from t1 where 11 in (t1.b,13, -t1.e) and f not between -13 and t1.b),c)) from t1 where b not in (a,11,17)),t1.e)) from t1),e) or not exists(select 1 from t1 where t1.c in (select t1.b from t1 union select t1.b from t1)) then coalesce((select -t1.e from t1 where e<>t1.e),f) when not t1.e<>t1.c then 19 else e end)} +} {} +do_test randexpr-2.1115 { + db eval {SELECT d- -e*(abs(t1.c)/abs(d)) | t1.a+ -coalesce((select max(t1.e) from t1 where case when case when (a in (13,b,t1.b)) and d in (t1.c,17,a) then 17+t1.e when 19>=t1.b then a else 11 end=t1.f and d between c and (d) then (abs(17)/abs(d)) else t1.d end*f>e and not f<=13 and -t1.f>=t1.e and t1.be then t1.b else c end FROM t1 WHERE b-coalesce((select (coalesce((select max((coalesce((select d from t1 where not -case when case 13 when +~(select case count(*) when -max(t1.b) then max(a) else min(c) end from t1) then c else -a end in (17,t1.b,(b)) then f else b end-f+17<=t1.a),t1.f)-d)) from t1 where t1.e=b),t1.b)) from t1 where (t1.a=t1.c)), -t1.a) not between 19 and 19} +} {-584} +do_test randexpr-2.1116 { + db eval {SELECT d- -e*(abs(t1.c)/abs(d)) | t1.a+ -coalesce((select max(t1.e) from t1 where case when case when (a in (13,b,t1.b)) and d in (t1.c,17,a) then 17+t1.e when 19>=t1.b then a else 11 end=t1.f and d between c and (d) then (abs(17)/abs(d)) else t1.d end*f>e and not f<=13 and -t1.f>=t1.e and t1.be then t1.b else c end FROM t1 WHERE NOT (b-coalesce((select (coalesce((select max((coalesce((select d from t1 where not -case when case 13 when +~(select case count(*) when -max(t1.b) then max(a) else min(c) end from t1) then c else -a end in (17,t1.b,(b)) then f else b end-f+17<=t1.a),t1.f)-d)) from t1 where t1.e=b),t1.b)) from t1 where (t1.a=t1.c)), -t1.a) not between 19 and 19)} +} {} +do_test randexpr-2.1117 { + db eval {SELECT d- -e*(abs(t1.c)/abs(d)) & t1.a+ -coalesce((select max(t1.e) from t1 where case when case when (a in (13,b,t1.b)) and d in (t1.c,17,a) then 17+t1.e when 19>=t1.b then a else 11 end=t1.f and d between c and (d) then (abs(17)/abs(d)) else t1.d end*f>e and not f<=13 and -t1.f>=t1.e and t1.be then t1.b else c end FROM t1 WHERE b-coalesce((select (coalesce((select max((coalesce((select d from t1 where not -case when case 13 when +~(select case count(*) when -max(t1.b) then max(a) else min(c) end from t1) then c else -a end in (17,t1.b,(b)) then f else b end-f+17<=t1.a),t1.f)-d)) from t1 where t1.e=b),t1.b)) from t1 where (t1.a=t1.c)), -t1.a) not between 19 and 19} +} {384} +do_test randexpr-2.1118 { + db eval {SELECT 19-case 13-f when b then t1.a*11-t1.d-+17*t1.b-coalesce((select 17 from t1 where 13<=f),+coalesce((select (abs(17+~coalesce((select a from t1 where 11<>t1.b and 11 not between t1.e and 19),17)+t1.e+t1.d | b)/abs(c))+f from t1 where 19 not between 19 and c),d)) else 19 end*t1.e+b FROM t1 WHERE 11+11 not in (t1.c,t1.e,19) and f+19*19*case when ~t1.a+19*b between t1.a-case case when f=(t1.d) then ((t1.d)) else -d end*e when c then e else t1.a end*t1.e and c then t1.e else b end in (select d from t1 union select t1.a from t1) or t1.d>=t1.f or not exists(select 1 from t1 where a<=13)} +} {-9281} +do_test randexpr-2.1119 { + db eval {SELECT 19-case 13-f when b then t1.a*11-t1.d-+17*t1.b-coalesce((select 17 from t1 where 13<=f),+coalesce((select (abs(17+~coalesce((select a from t1 where 11<>t1.b and 11 not between t1.e and 19),17)+t1.e+t1.d | b)/abs(c))+f from t1 where 19 not between 19 and c),d)) else 19 end*t1.e+b FROM t1 WHERE NOT (11+11 not in (t1.c,t1.e,19) and f+19*19*case when ~t1.a+19*b between t1.a-case case when f=(t1.d) then ((t1.d)) else -d end*e when c then e else t1.a end*t1.e and c then t1.e else b end in (select d from t1 union select t1.a from t1) or t1.d>=t1.f or not exists(select 1 from t1 where a<=13))} +} {} +do_test randexpr-2.1120 { + db eval {SELECT 19-case 13-f when b then t1.a*11-t1.d-+17*t1.b-coalesce((select 17 from t1 where 13<=f),+coalesce((select (abs(17+~coalesce((select a from t1 where 11<>t1.b and 11 not between t1.e and 19),17)+t1.e+t1.d & b)/abs(c))+f from t1 where 19 not between 19 and c),d)) else 19 end*t1.e+b FROM t1 WHERE 11+11 not in (t1.c,t1.e,19) and f+19*19*case when ~t1.a+19*b between t1.a-case case when f=(t1.d) then ((t1.d)) else -d end*e when c then e else t1.a end*t1.e and c then t1.e else b end in (select d from t1 union select t1.a from t1) or t1.d>=t1.f or not exists(select 1 from t1 where a<=13)} +} {-9281} +do_test randexpr-2.1121 { + db eval {SELECT case 19 when e then t1.b-t1.d else 11+coalesce((select 19 from t1 where not (t1.a)+(abs(case coalesce((select coalesce((select t1.e from t1 where 11=d),a) from t1 where t1.d<=13),a) when 17 then 13 else t1.a end)/abs(t1.b))-t1.d*e+t1.d not between b and b or e in (select -min(c) from t1 union select min(t1.b) from t1)),(abs(e)/abs(t1.b)))+t1.c end FROM t1 WHERE exists(select 1 from t1 where c in (select t1.a from t1 union select f from t1))} +} {} +do_test randexpr-2.1122 { + db eval {SELECT case 19 when e then t1.b-t1.d else 11+coalesce((select 19 from t1 where not (t1.a)+(abs(case coalesce((select coalesce((select t1.e from t1 where 11=d),a) from t1 where t1.d<=13),a) when 17 then 13 else t1.a end)/abs(t1.b))-t1.d*e+t1.d not between b and b or e in (select -min(c) from t1 union select min(t1.b) from t1)),(abs(e)/abs(t1.b)))+t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where c in (select t1.a from t1 union select f from t1)))} +} {313} +do_test randexpr-2.1123 { + db eval {SELECT 17 | t1.d-(select +max(case when not exists(select 1 from t1 where (a<=t1.f)) then -19 else -t1.d end)- -min(t1.f+t1.f-(select (count(*)) from t1)) from t1)- -19 | b-d+coalesce((select max(d) from t1 where e-t1.a in (19,b,11) or e in (19,t1.b,c)),11) FROM t1 WHERE (11<=11 and case coalesce((select max((f)) from t1 where t1.b | case 11 when t1.e*t1.e then e else case when ~b-case when 19 not in (t1.d,13,e) then 13 when c between t1.e and b then 19 else t1.c end-(c) in (select -t1.f from t1 union select d from t1) then c else t1.b end end*t1.a in (19,e,c)),t1.a) when t1.d then t1.a else -a end not in (t1.c,b,t1.f))} +} {-41} +do_test randexpr-2.1124 { + db eval {SELECT 17 | t1.d-(select +max(case when not exists(select 1 from t1 where (a<=t1.f)) then -19 else -t1.d end)- -min(t1.f+t1.f-(select (count(*)) from t1)) from t1)- -19 | b-d+coalesce((select max(d) from t1 where e-t1.a in (19,b,11) or e in (19,t1.b,c)),11) FROM t1 WHERE NOT ((11<=11 and case coalesce((select max((f)) from t1 where t1.b | case 11 when t1.e*t1.e then e else case when ~b-case when 19 not in (t1.d,13,e) then 13 when c between t1.e and b then 19 else t1.c end-(c) in (select -t1.f from t1 union select d from t1) then c else t1.b end end*t1.a in (19,e,c)),t1.a) when t1.d then t1.a else -a end not in (t1.c,b,t1.f)))} +} {} +do_test randexpr-2.1125 { + db eval {SELECT 17 & t1.d-(select +max(case when not exists(select 1 from t1 where (a<=t1.f)) then -19 else -t1.d end)- -min(t1.f+t1.f-(select (count(*)) from t1)) from t1)- -19 & b-d+coalesce((select max(d) from t1 where e-t1.a in (19,b,11) or e in (19,t1.b,c)),11) FROM t1 WHERE (11<=11 and case coalesce((select max((f)) from t1 where t1.b | case 11 when t1.e*t1.e then e else case when ~b-case when 19 not in (t1.d,13,e) then 13 when c between t1.e and b then 19 else t1.c end-(c) in (select -t1.f from t1 union select d from t1) then c else t1.b end end*t1.a in (19,e,c)),t1.a) when t1.d then t1.a else -a end not in (t1.c,b,t1.f))} +} {0} +do_test randexpr-2.1126 { + db eval {SELECT case t1.e-d+b when coalesce((select (select max(t1.a | a | -(select (count(*))+( - - -count(*)) from t1)*19+ -f+t1.e) from t1) from t1 where not exists(select 1 from t1 where (d not between a and 11) or not d>=11 and exists(select 1 from t1 where not t1.a<>13)) or 19 not in (17,t1.c,t1.c)),19)*t1.c+d then b else c end-b FROM t1 WHERE c<17} +} {} +do_test randexpr-2.1127 { + db eval {SELECT case t1.e-d+b when coalesce((select (select max(t1.a | a | -(select (count(*))+( - - -count(*)) from t1)*19+ -f+t1.e) from t1) from t1 where not exists(select 1 from t1 where (d not between a and 11) or not d>=11 and exists(select 1 from t1 where not t1.a<>13)) or 19 not in (17,t1.c,t1.c)),19)*t1.c+d then b else c end-b FROM t1 WHERE NOT (c<17)} +} {100} +do_test randexpr-2.1128 { + db eval {SELECT case t1.e-d+b when coalesce((select (select max(t1.a & a & -(select (count(*))+( - - -count(*)) from t1)*19+ -f+t1.e) from t1) from t1 where not exists(select 1 from t1 where (d not between a and 11) or not d>=11 and exists(select 1 from t1 where not t1.a<>13)) or 19 not in (17,t1.c,t1.c)),19)*t1.c+d then b else c end-b FROM t1 WHERE NOT (c<17)} +} {100} +do_test randexpr-2.1129 { + db eval {SELECT f*f*(abs(case when (17-coalesce((select max(11) from t1 where coalesce((select max(t1.c-11*t1.a) from t1 where +e=(abs(d)/abs(11))+ -13),t1.b)t1.e) then e else 17 end)/abs(c)) FROM t1 WHERE (t1.a in ((t1.f-t1.c)+b,11,t1.a+f))} +} {} +do_test randexpr-2.1130 { + db eval {SELECT f*f*(abs(case when (17-coalesce((select max(11) from t1 where coalesce((select max(t1.c-11*t1.a) from t1 where +e=(abs(d)/abs(11))+ -13),t1.b)t1.e) then e else 17 end)/abs(c)) FROM t1 WHERE NOT ((t1.a in ((t1.f-t1.c)+b,11,t1.a+f)))} +} {0} +do_test randexpr-2.1131 { + db eval {SELECT f*f*(abs(case when (17-coalesce((select max(11) from t1 where coalesce((select max(t1.c-11*t1.a) from t1 where +e=(abs(d)/abs(11))+ -13),t1.b)t1.e) then e else 17 end)/abs(c)) FROM t1 WHERE NOT ((t1.a in ((t1.f-t1.c)+b,11,t1.a+f)))} +} {0} +do_test randexpr-2.1132 { + db eval {SELECT ( -19-f+coalesce((select max( -~case when case 11 when ~coalesce((select max(13) from t1 where not (e)<>(t1.c)),19)+11 | -19-f then -13 else t1.c end-e<=t1.a then 11 when not exists(select 1 from t1 where (not t1.c<19) and not (13<>17)) then -e else f end) from t1 where (b)<=t1.e),t1.d)+ -t1.c) | b FROM t1 WHERE (~(select (max(f)-count(distinct c)) from t1) | case when e>=t1.c then t1.b+(select abs(count(*)+max(c)*abs(count(distinct e)+max(t1.f))+cast(avg(c) AS integer)) | cast(avg(t1.d) AS integer)*min(11) from t1)-t1.c else c end in (select case -t1.b when 17 then 17 else -case when not t1.c not in (17,t1.d,17) then 19 else a end end from t1 union select a from t1)) or (11)<=t1.b} +} {-771} +do_test randexpr-2.1133 { + db eval {SELECT ( -19-f+coalesce((select max( -~case when case 11 when ~coalesce((select max(13) from t1 where not (e)<>(t1.c)),19)+11 | -19-f then -13 else t1.c end-e<=t1.a then 11 when not exists(select 1 from t1 where (not t1.c<19) and not (13<>17)) then -e else f end) from t1 where (b)<=t1.e),t1.d)+ -t1.c) | b FROM t1 WHERE NOT ((~(select (max(f)-count(distinct c)) from t1) | case when e>=t1.c then t1.b+(select abs(count(*)+max(c)*abs(count(distinct e)+max(t1.f))+cast(avg(c) AS integer)) | cast(avg(t1.d) AS integer)*min(11) from t1)-t1.c else c end in (select case -t1.b when 17 then 17 else -case when not t1.c not in (17,t1.d,17) then 19 else a end end from t1 union select a from t1)) or (11)<=t1.b)} +} {} +do_test randexpr-2.1134 { + db eval {SELECT ( -19-f+coalesce((select max( -~case when case 11 when ~coalesce((select max(13) from t1 where not (e)<>(t1.c)),19)+11 & -19-f then -13 else t1.c end-e<=t1.a then 11 when not exists(select 1 from t1 where (not t1.c<19) and not (13<>17)) then -e else f end) from t1 where (b)<=t1.e),t1.d)+ -t1.c) & b FROM t1 WHERE (~(select (max(f)-count(distinct c)) from t1) | case when e>=t1.c then t1.b+(select abs(count(*)+max(c)*abs(count(distinct e)+max(t1.f))+cast(avg(c) AS integer)) | cast(avg(t1.d) AS integer)*min(11) from t1)-t1.c else c end in (select case -t1.b when 17 then 17 else -case when not t1.c not in (17,t1.d,17) then 19 else a end end from t1 union select a from t1)) or (11)<=t1.b} +} {64} +do_test randexpr-2.1135 { + db eval {SELECT +case when (not exists(select 1 from t1 where (abs(t1.a+coalesce((select max(b+ -case when e=t1.f then (abs(d)/abs(t1.e)) when not exists(select 1 from t1 where 17t1.c) then e else e end FROM t1 WHERE not t1.d-d+case b when t1.a+t1.a then t1.f+ -t1.e else 11+b*coalesce((select max(t1.f) from t1 where 11>= -f+t1.d),t1.c)*19 end not between d and t1.c-(11)+17} +} {} +do_test randexpr-2.1136 { + db eval {SELECT +case when (not exists(select 1 from t1 where (abs(t1.a+coalesce((select max(b+ -case when e=t1.f then (abs(d)/abs(t1.e)) when not exists(select 1 from t1 where 17t1.c) then e else e end FROM t1 WHERE NOT (not t1.d-d+case b when t1.a+t1.a then t1.f+ -t1.e else 11+b*coalesce((select max(t1.f) from t1 where 11>= -f+t1.d),t1.c)*19 end not between d and t1.c-(11)+17)} +} {500} +do_test randexpr-2.1137 { + db eval {SELECT +case when (not exists(select 1 from t1 where (abs(t1.a+coalesce((select max(b+ -case when e=t1.f then (abs(d)/abs(t1.e)) when not exists(select 1 from t1 where 17t1.c) then e else e end FROM t1 WHERE NOT (not t1.d-d+case b when t1.a+t1.a then t1.f+ -t1.e else 11+b*coalesce((select max(t1.f) from t1 where 11>= -f+t1.d),t1.c)*19 end not between d and t1.c-(11)+17)} +} {500} +do_test randexpr-2.1138 { + db eval {SELECT t1.d+case when (t1.a)<=11 then ~t1.a else ~19 end-+~ -coalesce((select t1.d from t1 where ~t1.f in (select (cast(avg(t1.e+c) AS integer)) from t1 union select count(distinct (abs(coalesce((select max(19) from t1 where not ~11-t1.a=t1.c+case when t1.d between c and t1.d then 11 when t1.f>=17 then f else 19 end*t1.c),17)+f)/abs(f))) from t1)),11) FROM t1 WHERE e>c} +} {370} +do_test randexpr-2.1139 { + db eval {SELECT t1.d+case when (t1.a)<=11 then ~t1.a else ~19 end-+~ -coalesce((select t1.d from t1 where ~t1.f in (select (cast(avg(t1.e+c) AS integer)) from t1 union select count(distinct (abs(coalesce((select max(19) from t1 where not ~11-t1.a=t1.c+case when t1.d between c and t1.d then 11 when t1.f>=17 then f else 19 end*t1.c),17)+f)/abs(f))) from t1)),11) FROM t1 WHERE NOT (e>c)} +} {} +do_test randexpr-2.1140 { + db eval {SELECT case when coalesce((select max(case b | d*(abs(t1.e)/abs(a))-f | t1.b when t1.e then coalesce((select max(t1.e) from t1 where t1.e between (select ~count(*)*cast(avg(19) AS integer) from t1) and case c when a then 13 else a end),t1.f)+e*c else t1.d end) from t1 where t1.a in (select t1.d from t1 union select 17 from t1)),e)+17<19 then t1.a else 19 end | 11+e-17*19 FROM t1 WHERE d*t1.c-case when case when ((13 in (17+e,b,11)) or 19>(13)) then (abs(coalesce((select t1.a from t1 where t1.a not in (13,c,t1.f)),11))/abs(t1.e))-f when t1.b not between t1.b and f then t1.d else t1.a end in (a,e,t1.d) then t1.f else t1.f end+f+t1.e in (t1.d,e,b)} +} {} +do_test randexpr-2.1141 { + db eval {SELECT case when coalesce((select max(case b | d*(abs(t1.e)/abs(a))-f | t1.b when t1.e then coalesce((select max(t1.e) from t1 where t1.e between (select ~count(*)*cast(avg(19) AS integer) from t1) and case c when a then 13 else a end),t1.f)+e*c else t1.d end) from t1 where t1.a in (select t1.d from t1 union select 17 from t1)),e)+17<19 then t1.a else 19 end | 11+e-17*19 FROM t1 WHERE NOT (d*t1.c-case when case when ((13 in (17+e,b,11)) or 19>(13)) then (abs(coalesce((select t1.a from t1 where t1.a not in (13,c,t1.f)),11))/abs(t1.e))-f when t1.b not between t1.b and f then t1.d else t1.a end in (a,e,t1.d) then t1.f else t1.f end+f+t1.e in (t1.d,e,b))} +} {191} +do_test randexpr-2.1142 { + db eval {SELECT case when coalesce((select max(case b & d*(abs(t1.e)/abs(a))-f & t1.b when t1.e then coalesce((select max(t1.e) from t1 where t1.e between (select ~count(*)*cast(avg(19) AS integer) from t1) and case c when a then 13 else a end),t1.f)+e*c else t1.d end) from t1 where t1.a in (select t1.d from t1 union select 17 from t1)),e)+17<19 then t1.a else 19 end & 11+e-17*19 FROM t1 WHERE NOT (d*t1.c-case when case when ((13 in (17+e,b,11)) or 19>(13)) then (abs(coalesce((select t1.a from t1 where t1.a not in (13,c,t1.f)),11))/abs(t1.e))-f when t1.b not between t1.b and f then t1.d else t1.a end in (a,e,t1.d) then t1.f else t1.f end+f+t1.e in (t1.d,e,b))} +} {16} +do_test randexpr-2.1143 { + db eval {SELECT ((select (count(*) | +~(case ++(min(t1.f+17+(11-case when b between d and d and t1.a not in (13,c,t1.c) and e< -t1.b then 17+(11) else t1.e end+ -b))) when case min(e) when min( -13) | ~max(t1.f) then count(distinct t1.f) | ~count(distinct t1.d) else count(*) end then min(t1.c) else -cast(avg(11) AS integer) end)+count(distinct (f))) from t1)+e) FROM t1 WHERE (a in (11*a-t1.a | t1.b+e*13,(f | a | (select min((select min(13)-min(17)*((count(distinct t1.d))) from t1)) from t1)+t1.a- -11)+(11),t1.c) and (a) between t1.d and t1.f or t1.d not between t1.c and f or d not in (t1.c,t1.f,c))} +} {511} +do_test randexpr-2.1144 { + db eval {SELECT ((select (count(*) | +~(case ++(min(t1.f+17+(11-case when b between d and d and t1.a not in (13,c,t1.c) and e< -t1.b then 17+(11) else t1.e end+ -b))) when case min(e) when min( -13) | ~max(t1.f) then count(distinct t1.f) | ~count(distinct t1.d) else count(*) end then min(t1.c) else -cast(avg(11) AS integer) end)+count(distinct (f))) from t1)+e) FROM t1 WHERE NOT ((a in (11*a-t1.a | t1.b+e*13,(f | a | (select min((select min(13)-min(17)*((count(distinct t1.d))) from t1)) from t1)+t1.a- -11)+(11),t1.c) and (a) between t1.d and t1.f or t1.d not between t1.c and f or d not in (t1.c,t1.f,c)))} +} {} +do_test randexpr-2.1145 { + db eval {SELECT ((select (count(*) & +~(case ++(min(t1.f+17+(11-case when b between d and d and t1.a not in (13,c,t1.c) and e< -t1.b then 17+(11) else t1.e end+ -b))) when case min(e) when min( -13) & ~max(t1.f) then count(distinct t1.f) & ~count(distinct t1.d) else count(*) end then min(t1.c) else -cast(avg(11) AS integer) end)+count(distinct (f))) from t1)+e) FROM t1 WHERE (a in (11*a-t1.a | t1.b+e*13,(f | a | (select min((select min(13)-min(17)*((count(distinct t1.d))) from t1)) from t1)+t1.a- -11)+(11),t1.c) and (a) between t1.d and t1.f or t1.d not between t1.c and f or d not in (t1.c,t1.f,c))} +} {501} +do_test randexpr-2.1146 { + db eval {SELECT coalesce((select max(13) from t1 where d in (select (max(19)*count(distinct case when t1.f between ~e and -b-t1.f then b else d end)-count(distinct f)) from t1 union select cast(avg(case e when case t1.b when -a | t1.e*19 then t1.a else -t1.c end then -d else t1.e end) AS integer) from t1)),case when t1.d in (select t1.e from t1 union select b from t1) then t1.f when t1.f between 13 and f then f else f end) FROM t1 WHERE c in (select (t1.a) from t1 union select e from t1)} +} {} +do_test randexpr-2.1147 { + db eval {SELECT coalesce((select max(13) from t1 where d in (select (max(19)*count(distinct case when t1.f between ~e and -b-t1.f then b else d end)-count(distinct f)) from t1 union select cast(avg(case e when case t1.b when -a | t1.e*19 then t1.a else -t1.c end then -d else t1.e end) AS integer) from t1)),case when t1.d in (select t1.e from t1 union select b from t1) then t1.f when t1.f between 13 and f then f else f end) FROM t1 WHERE NOT (c in (select (t1.a) from t1 union select e from t1))} +} {600} +do_test randexpr-2.1148 { + db eval {SELECT coalesce((select max(13) from t1 where d in (select (max(19)*count(distinct case when t1.f between ~e and -b-t1.f then b else d end)-count(distinct f)) from t1 union select cast(avg(case e when case t1.b when -a & t1.e*19 then t1.a else -t1.c end then -d else t1.e end) AS integer) from t1)),case when t1.d in (select t1.e from t1 union select b from t1) then t1.f when t1.f between 13 and f then f else f end) FROM t1 WHERE NOT (c in (select (t1.a) from t1 union select e from t1))} +} {600} +do_test randexpr-2.1149 { + db eval {SELECT (abs(t1.d+b)/abs(~t1.f+case when t1.f=t1.c or exists(select 1 from t1 where c>=+~t1.c*17) or exists(select 1 from t1 where (select -cast(avg(case when 19<>t1.f then -c when c<>b then t1.e else t1.d end) AS integer) from t1) in (d-t1.f,b,19)) then d+b when 11(19) then c else -case when 11>b or t1.c<=c then f when t1.f>t1.a then t1.a else t1.e end*d-11 end+d*t1.b>t1.e),d)>t1.b and c<>d and not exists(select 1 from t1 where 17>=(t1.f)) and t1.e not in (f,t1.b,t1.b))} +} {} +do_test randexpr-2.1150 { + db eval {SELECT (abs(t1.d+b)/abs(~t1.f+case when t1.f=t1.c or exists(select 1 from t1 where c>=+~t1.c*17) or exists(select 1 from t1 where (select -cast(avg(case when 19<>t1.f then -c when c<>b then t1.e else t1.d end) AS integer) from t1) in (d-t1.f,b,19)) then d+b when 11(19) then c else -case when 11>b or t1.c<=c then f when t1.f>t1.a then t1.a else t1.e end*d-11 end+d*t1.b>t1.e),d)>t1.b and c<>d and not exists(select 1 from t1 where 17>=(t1.f)) and t1.e not in (f,t1.b,t1.b)))} +} {0} +do_test randexpr-2.1151 { + db eval {SELECT t1.b-~case when +a in (select ~min(11) from t1 union select -count(*)+count(distinct ~coalesce((select coalesce((select t1.b-19+c from t1 where a<>13 or 13 in (t1.b,d,t1.e)),11) from t1 where 19 in (19,e,17)),e)) from t1) then (select -min(19)+cast(avg(t1.d) AS integer) from t1) else d end | 17 | t1.e FROM t1 WHERE c-b+e*11+(c+13+11)+(13)+(select cast(avg((abs(e-d+a)/abs(t1.f))) AS integer) from t1)-t1.d+~13<=t1.e-c-17} +} {} +do_test randexpr-2.1152 { + db eval {SELECT t1.b-~case when +a in (select ~min(11) from t1 union select -count(*)+count(distinct ~coalesce((select coalesce((select t1.b-19+c from t1 where a<>13 or 13 in (t1.b,d,t1.e)),11) from t1 where 19 in (19,e,17)),e)) from t1) then (select -min(19)+cast(avg(t1.d) AS integer) from t1) else d end | 17 | t1.e FROM t1 WHERE NOT (c-b+e*11+(c+13+11)+(13)+(select cast(avg((abs(e-d+a)/abs(t1.f))) AS integer) from t1)-t1.d+~13<=t1.e-c-17)} +} {1021} +do_test randexpr-2.1153 { + db eval {SELECT t1.b-~case when +a in (select ~min(11) from t1 union select -count(*)+count(distinct ~coalesce((select coalesce((select t1.b-19+c from t1 where a<>13 or 13 in (t1.b,d,t1.e)),11) from t1 where 19 in (19,e,17)),e)) from t1) then (select -min(19)+cast(avg(t1.d) AS integer) from t1) else d end & 17 & t1.e FROM t1 WHERE NOT (c-b+e*11+(c+13+11)+(13)+(select cast(avg((abs(e-d+a)/abs(t1.f))) AS integer) from t1)-t1.d+~13<=t1.e-c-17)} +} {16} +do_test randexpr-2.1154 { + db eval {SELECT coalesce((select max(b) from t1 where t1.et1.e then 17 when 19 not between 11 and b then t1.e else 19 end*t1.c),t1.c) FROM t1 WHERE not t1.f*(abs(case when ~19-17*e>=t1.d then t1.b when (select cast(avg(t1.e) AS integer) from t1) in ((abs(t1.e)/abs(t1.e))-case when f not in (t1.d,13,c) then c else t1.e end-t1.b-t1.a | b-(t1.c), -a,e) then t1.e else e end+a)/abs(t1.d)) | b not between b and t1.d} +} {} +do_test randexpr-2.1155 { + db eval {SELECT coalesce((select max(b) from t1 where t1.et1.e then 17 when 19 not between 11 and b then t1.e else 19 end*t1.c),t1.c) FROM t1 WHERE NOT (not t1.f*(abs(case when ~19-17*e>=t1.d then t1.b when (select cast(avg(t1.e) AS integer) from t1) in ((abs(t1.e)/abs(t1.e))-case when f not in (t1.d,13,c) then c else t1.e end-t1.b-t1.a | b-(t1.c), -a,e) then t1.e else e end+a)/abs(t1.d)) | b not between b and t1.d)} +} {300} +do_test randexpr-2.1156 { + db eval {SELECT -f+( - -case when 13-b not between case when (a<>t1.f or case when not exists(select 1 from t1 where 11<>t1.a) then b when c<=t1.b then t1.f else 11 end in (select 17 from t1 union select t1.b from t1)) then b-c-b when t1.f=13 then a else 19 end | t1.d and t1.e and not exists(select 1 from t1 where 19=t1.f) then -c else 19 end+17) FROM t1 WHERE not not exists(select 1 from t1 where ~(select cast(avg(t1.d) AS integer) from t1) | +~~case case when f-case when exists(select 1 from t1 where 13 not in (d,11,case when not exists(select 1 from t1 where f between t1.d and e) then 13 when t1.e<>19 then f else 11 end) or b in ( -d,t1.c,17)) then b else f end-(t1.d) in (t1.c,t1.c,b) then t1.b else e end when 11 then t1.e else -c end-c<>t1.b)} +} {-883} +do_test randexpr-2.1157 { + db eval {SELECT -f+( - -case when 13-b not between case when (a<>t1.f or case when not exists(select 1 from t1 where 11<>t1.a) then b when c<=t1.b then t1.f else 11 end in (select 17 from t1 union select t1.b from t1)) then b-c-b when t1.f=13 then a else 19 end | t1.d and t1.e and not exists(select 1 from t1 where 19=t1.f) then -c else 19 end+17) FROM t1 WHERE NOT (not not exists(select 1 from t1 where ~(select cast(avg(t1.d) AS integer) from t1) | +~~case case when f-case when exists(select 1 from t1 where 13 not in (d,11,case when not exists(select 1 from t1 where f between t1.d and e) then 13 when t1.e<>19 then f else 11 end) or b in ( -d,t1.c,17)) then b else f end-(t1.d) in (t1.c,t1.c,b) then t1.b else e end when 11 then t1.e else -c end-c<>t1.b))} +} {} +do_test randexpr-2.1158 { + db eval {SELECT -f+( - -case when 13-b not between case when (a<>t1.f or case when not exists(select 1 from t1 where 11<>t1.a) then b when c<=t1.b then t1.f else 11 end in (select 17 from t1 union select t1.b from t1)) then b-c-b when t1.f=13 then a else 19 end & t1.d and t1.e and not exists(select 1 from t1 where 19=t1.f) then -c else 19 end+17) FROM t1 WHERE not not exists(select 1 from t1 where ~(select cast(avg(t1.d) AS integer) from t1) | +~~case case when f-case when exists(select 1 from t1 where 13 not in (d,11,case when not exists(select 1 from t1 where f between t1.d and e) then 13 when t1.e<>19 then f else 11 end) or b in ( -d,t1.c,17)) then b else f end-(t1.d) in (t1.c,t1.c,b) then t1.b else e end when 11 then t1.e else -c end-c<>t1.b)} +} {-883} +do_test randexpr-2.1159 { + db eval {SELECT +(abs(d+d+a+b+t1.d)/abs(coalesce((select (select abs(cast(avg(17-11+e*t1.d) AS integer)++cast(avg(coalesce((select max(11-+t1.f- -e-a* -19+t1.a) from t1 where -a in (select 11 from t1 union select -11 from t1)),e)) AS integer)) from t1) from t1 where f=17),t1.b)*a)) FROM t1 WHERE t1.b in (select t1.e from t1 union select coalesce((select max(11) from t1 where dt1.e then t1.a+e-a when 19>t1.c then c else t1.c end+c not between b and t1.d),t1.f) and -(t1.b) between t1.e and -t1.d or b<>19 then (select ~(min(13))+max(f) from t1) else (t1.b) end*t1.b FROM t1 WHERE b in (b,e,case coalesce((select max(t1.b) from t1 where e>13 or ( -(select case -~count(distinct 17)-cast(avg((t1.f)) AS integer)*cast(avg(d) AS integer) when -cast(avg(f) AS integer) then max(17) else -(count(*)) end from t1)-(coalesce((select (b) from t1 where t1.b>=t1.e),t1.c)) in (17,t1.e,b)) or (exists(select 1 from t1 where (t1.d=(d))))),t1.c) when b then c else (e) end)} +} {117200} +do_test randexpr-2.1162 { + db eval {SELECT case when t1.b*t1.c=coalesce((select t1.f from t1 where case when exists(select 1 from t1 where t1.d in (select e from t1 union select 19 from t1)) or t1.e>t1.e then t1.a+e-a when 19>t1.c then c else t1.c end+c not between b and t1.d),t1.f) and -(t1.b) between t1.e and -t1.d or b<>19 then (select ~(min(13))+max(f) from t1) else (t1.b) end*t1.b FROM t1 WHERE NOT (b in (b,e,case coalesce((select max(t1.b) from t1 where e>13 or ( -(select case -~count(distinct 17)-cast(avg((t1.f)) AS integer)*cast(avg(d) AS integer) when -cast(avg(f) AS integer) then max(17) else -(count(*)) end from t1)-(coalesce((select (b) from t1 where t1.b>=t1.e),t1.c)) in (17,t1.e,b)) or (exists(select 1 from t1 where (t1.d=(d))))),t1.c) when b then c else (e) end))} +} {} +do_test randexpr-2.1163 { + db eval {SELECT +t1.c+case when t1.e not in ((e)-(case when 17<11 then 19 when (t1.d in (d,coalesce((select max(t1.a) from t1 where not b<>t1.b),case t1.b when coalesce((select max(t1.a) from t1 where exists(select 1 from t1 where e not in (t1.f,11,17))),(19))*t1.f then c else t1.c end+ -t1.d)-t1.b+t1.e,d)) then 19 else b end)-e,t1.c, -13) then e else 17 end FROM t1 WHERE t1.e*t1.b | t1.b<>17*+coalesce((select max(t1.b) from t1 where case when coalesce((select max(b) from t1 where case when (b between 17 and d) then t1.f when t1.c between b and t1.a then t1.e else t1.a end not in (11,19,13)),11) in (t1.d,17,17) then t1.f when d<>13 then 11 else t1.a end+a<17),t1.a)-17+t1.f*d-a} +} {800} +do_test randexpr-2.1164 { + db eval {SELECT +t1.c+case when t1.e not in ((e)-(case when 17<11 then 19 when (t1.d in (d,coalesce((select max(t1.a) from t1 where not b<>t1.b),case t1.b when coalesce((select max(t1.a) from t1 where exists(select 1 from t1 where e not in (t1.f,11,17))),(19))*t1.f then c else t1.c end+ -t1.d)-t1.b+t1.e,d)) then 19 else b end)-e,t1.c, -13) then e else 17 end FROM t1 WHERE NOT (t1.e*t1.b | t1.b<>17*+coalesce((select max(t1.b) from t1 where case when coalesce((select max(b) from t1 where case when (b between 17 and d) then t1.f when t1.c between b and t1.a then t1.e else t1.a end not in (11,19,13)),11) in (t1.d,17,17) then t1.f when d<>13 then 11 else t1.a end+a<17),t1.a)-17+t1.f*d-a)} +} {} +do_test randexpr-2.1165 { + db eval {SELECT 11+case when case case f when (abs(t1.a)/abs(19))+t1.e then (abs(19)/abs(b+e)) else 13 end | 11 when (select ~~+min(t1.e) from t1) then t1.c else -e end<>case t1.a when 17 then case when (c not between 19 and t1.b) and t1.b<>t1.d then coalesce((select a from t1 where t1.d in (t1.e,t1.f,f)),t1.e) else 13 end else d end or t1.cf)} +} {} +do_test randexpr-2.1166 { + db eval {SELECT 11+case when case case f when (abs(t1.a)/abs(19))+t1.e then (abs(19)/abs(b+e)) else 13 end | 11 when (select ~~+min(t1.e) from t1) then t1.c else -e end<>case t1.a when 17 then case when (c not between 19 and t1.b) and t1.b<>t1.d then coalesce((select a from t1 where t1.d in (t1.e,t1.f,f)),t1.e) else 13 end else d end or t1.cf))} +} {11} +do_test randexpr-2.1167 { + db eval {SELECT 11+case when case case f when (abs(t1.a)/abs(19))+t1.e then (abs(19)/abs(b+e)) else 13 end & 11 when (select ~~+min(t1.e) from t1) then t1.c else -e end<>case t1.a when 17 then case when (c not between 19 and t1.b) and t1.b<>t1.d then coalesce((select a from t1 where t1.d in (t1.e,t1.f,f)),t1.e) else 13 end else d end or t1.cf))} +} {11} +do_test randexpr-2.1168 { + db eval {SELECT d-case when ~c<>case when not exists(select 1 from t1 where -t1.b<>19) then coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where (t1.c in (select ~~+~max(~case when 13 not between t1.d and t1.d or c between c and f then t1.f else t1.a end)*abs(count(*)+(min( -t1.e))) from t1 union select cast(avg(e) AS integer) from t1) and (abs(t1.f*f-t1.a)/abs(d))>t1.b)) and (17) not in ( -t1.f,13,17)),19) else a end then b else f end FROM t1 WHERE f=(select case ~ -~count(distinct t1.b)+count(distinct d) | -count(distinct t1.e)*count(*)* -cast(avg(b) AS integer)*(cast(avg(13) AS integer)) when -min(19) then min(t1.e) else ((cast(avg(17) AS integer))) end from t1) or 19>=(19) and not exists(select 1 from t1 where (select count(*) from t1)*t1.d not between 19+11 and d) and -t1.e not in (e,t1.a, -a) and t1.e between t1.f and (t1.b) or c in ( -11,17,t1.c) or t1.a in (a,11,t1.d)} +} {200} +do_test randexpr-2.1169 { + db eval {SELECT d-case when ~c<>case when not exists(select 1 from t1 where -t1.b<>19) then coalesce((select max(t1.f) from t1 where exists(select 1 from t1 where (t1.c in (select ~~+~max(~case when 13 not between t1.d and t1.d or c between c and f then t1.f else t1.a end)*abs(count(*)+(min( -t1.e))) from t1 union select cast(avg(e) AS integer) from t1) and (abs(t1.f*f-t1.a)/abs(d))>t1.b)) and (17) not in ( -t1.f,13,17)),19) else a end then b else f end FROM t1 WHERE NOT (f=(select case ~ -~count(distinct t1.b)+count(distinct d) | -count(distinct t1.e)*count(*)* -cast(avg(b) AS integer)*(cast(avg(13) AS integer)) when -min(19) then min(t1.e) else ((cast(avg(17) AS integer))) end from t1) or 19>=(19) and not exists(select 1 from t1 where (select count(*) from t1)*t1.d not between 19+11 and d) and -t1.e not in (e,t1.a, -a) and t1.e between t1.f and (t1.b) or c in ( -11,17,t1.c) or t1.a in (a,11,t1.d))} +} {} +do_test randexpr-2.1170 { + db eval {SELECT case when a in (select t1.b from t1 union select coalesce((select ~19 from t1 where e>13*t1.d or c in (select b from t1 union select case a*t1.f when e then (t1.c) else (t1.b) end from t1)),t1.a) from t1) and t1.d>b or not exists(select 1 from t1 where t1.e in (select count(*)*min(t1.b)*~count(*) from t1 union select case -min((19)) when -max(b) then (min(t1.a)) else (count(distinct t1.d)) end from t1)) then (t1.c) when exists(select 1 from t1 where f not between 19 and f) then 19 else t1.c end-a FROM t1 WHERE a=coalesce((select f from t1 where t1.c in (11,(abs(coalesce((select max(t1.d) from t1 where (abs(t1.c | 13)/abs(11)) not in (b+case when coalesce((select max(b) from t1 where 11 between d and t1.a),b)=t1.b))),c) and f between 19 and t1.d or c>(f)} +} {} +do_test randexpr-2.1171 { + db eval {SELECT case when a in (select t1.b from t1 union select coalesce((select ~19 from t1 where e>13*t1.d or c in (select b from t1 union select case a*t1.f when e then (t1.c) else (t1.b) end from t1)),t1.a) from t1) and t1.d>b or not exists(select 1 from t1 where t1.e in (select count(*)*min(t1.b)*~count(*) from t1 union select case -min((19)) when -max(b) then (min(t1.a)) else (count(distinct t1.d)) end from t1)) then (t1.c) when exists(select 1 from t1 where f not between 19 and f) then 19 else t1.c end-a FROM t1 WHERE NOT (a=coalesce((select f from t1 where t1.c in (11,(abs(coalesce((select max(t1.d) from t1 where (abs(t1.c | 13)/abs(11)) not in (b+case when coalesce((select max(b) from t1 where 11 between d and t1.a),b)=t1.b))),c) and f between 19 and t1.d or c>(f))} +} {200} +do_test randexpr-2.1172 { + db eval {SELECT case when -(t1.f)- -case when t1.e not in ((t1.d)+a-t1.a,t1.c, - -a) then t1.b when (not exists(select 1 from t1 where t1.d>= -t1.f)) then -19 else f end-t1.f in (select cast(avg(19) AS integer)*case count(*) when abs((++min( -11))*max(13)-count(distinct 13)) then min(t1.a) else count(distinct 17) end from t1 union select count(distinct t1.a) from t1) then t1.c when b not between t1.f and 13 then e else t1.a end FROM t1 WHERE 11 not between ~17+d and ~case when t1.b in (c*((abs(case 13 when -(select abs(count(distinct coalesce((select max(coalesce((select t1.b from t1 where not exists(select 1 from t1 where (t1.c) in (t1.a,e,13))),t1.d)) from t1 where not t1.d>c),b))) from t1) then t1.f else t1.b end- -t1.c)/abs(c))+a),t1.d,t1.a) then (t1.c) else (d) end-13 or -t1.a in (17,a,f)} +} {500} +do_test randexpr-2.1173 { + db eval {SELECT case when -(t1.f)- -case when t1.e not in ((t1.d)+a-t1.a,t1.c, - -a) then t1.b when (not exists(select 1 from t1 where t1.d>= -t1.f)) then -19 else f end-t1.f in (select cast(avg(19) AS integer)*case count(*) when abs((++min( -11))*max(13)-count(distinct 13)) then min(t1.a) else count(distinct 17) end from t1 union select count(distinct t1.a) from t1) then t1.c when b not between t1.f and 13 then e else t1.a end FROM t1 WHERE NOT (11 not between ~17+d and ~case when t1.b in (c*((abs(case 13 when -(select abs(count(distinct coalesce((select max(coalesce((select t1.b from t1 where not exists(select 1 from t1 where (t1.c) in (t1.a,e,13))),t1.d)) from t1 where not t1.d>c),b))) from t1) then t1.f else t1.b end- -t1.c)/abs(c))+a),t1.d,t1.a) then (t1.c) else (d) end-13 or -t1.a in (17,a,f))} +} {} +do_test randexpr-2.1174 { + db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where (t1.b- -b+(select +case max(b)-~count(distinct e*(select case max(c) when abs((count(*))) then max(t1.f) else max(t1.c) end+cast(avg(t1.b) AS integer) from t1)) when abs(count(distinct e*19)) then max(b) else max(t1.c) end | count(distinct t1.e) from t1)-b*+t1.b not in ((11),17,13)))),t1.e) FROM t1 WHERE t1.c in (select min(coalesce((select 17 from t1 where t1.c | 17>=(abs(t1.a)/abs(case when t1.e not in (19,t1.d,19) then a when 13<=case when not exists(select 1 from t1 where (abs(e)/abs(t1.c)) in (select 19 from t1 union select d from t1) and t1.c>=17 or 19=t1.a) then f else a end then t1.d else e end))-f),e))*min(f) | ++min(a) from t1 union select cast(avg(f) AS integer) from t1)} +} {} +do_test randexpr-2.1175 { + db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where (t1.b- -b+(select +case max(b)-~count(distinct e*(select case max(c) when abs((count(*))) then max(t1.f) else max(t1.c) end+cast(avg(t1.b) AS integer) from t1)) when abs(count(distinct e*19)) then max(b) else max(t1.c) end | count(distinct t1.e) from t1)-b*+t1.b not in ((11),17,13)))),t1.e) FROM t1 WHERE NOT (t1.c in (select min(coalesce((select 17 from t1 where t1.c | 17>=(abs(t1.a)/abs(case when t1.e not in (19,t1.d,19) then a when 13<=case when not exists(select 1 from t1 where (abs(e)/abs(t1.c)) in (select 19 from t1 union select d from t1) and t1.c>=17 or 19=t1.a) then f else a end then t1.d else e end))-f),e))*min(f) | ++min(a) from t1 union select cast(avg(f) AS integer) from t1))} +} {500} +do_test randexpr-2.1176 { + db eval {SELECT coalesce((select 17 from t1 where not exists(select 1 from t1 where (t1.b- -b+(select +case max(b)-~count(distinct e*(select case max(c) when abs((count(*))) then max(t1.f) else max(t1.c) end+cast(avg(t1.b) AS integer) from t1)) when abs(count(distinct e*19)) then max(b) else max(t1.c) end & count(distinct t1.e) from t1)-b*+t1.b not in ((11),17,13)))),t1.e) FROM t1 WHERE NOT (t1.c in (select min(coalesce((select 17 from t1 where t1.c | 17>=(abs(t1.a)/abs(case when t1.e not in (19,t1.d,19) then a when 13<=case when not exists(select 1 from t1 where (abs(e)/abs(t1.c)) in (select 19 from t1 union select d from t1) and t1.c>=17 or 19=t1.a) then f else a end then t1.d else e end))-f),e))*min(f) | ++min(a) from t1 union select cast(avg(f) AS integer) from t1))} +} {500} +do_test randexpr-2.1177 { + db eval {SELECT case coalesce((select t1.e from t1 where +coalesce((select a from t1 where 13 | b | t1.b<=11*a*case when exists(select 1 from t1 where (a-t1.d+t1.e-f<17 and -17 between 19 and a)) then c when 17 between f and t1.c then a*11 else t1.d end),t1.e) not in (b,t1.f,t1.d)),a) when c then -c else t1.b end FROM t1 WHERE (exists(select 1 from t1 where case when not exists(select 1 from t1 where (select cast(avg(d) AS integer) from t1) in (select a from t1 union select case case when t1.e>t1.d or t1.b in (select c from t1 union select e from t1) or t1.a>=f and b>=11 then t1.c-(t1.c)*19 when b not in (e,c,t1.d) then t1.b else t1.c end when 13 then f else -t1.f end from t1)) then 17 when not exists(select 1 from t1 where not exists(select 1 from t1 where f not in (t1.d,f, -t1.b)) or -19<=t1.c) or t1.e between 13 and t1.a then f else d end<>t1.f) and f between 11 and t1.c and t1.e not in (t1.d,c,t1.e)) or d not between t1.b and t1.d} +} {} +do_test randexpr-2.1178 { + db eval {SELECT case coalesce((select t1.e from t1 where +coalesce((select a from t1 where 13 | b | t1.b<=11*a*case when exists(select 1 from t1 where (a-t1.d+t1.e-f<17 and -17 between 19 and a)) then c when 17 between f and t1.c then a*11 else t1.d end),t1.e) not in (b,t1.f,t1.d)),a) when c then -c else t1.b end FROM t1 WHERE NOT ((exists(select 1 from t1 where case when not exists(select 1 from t1 where (select cast(avg(d) AS integer) from t1) in (select a from t1 union select case case when t1.e>t1.d or t1.b in (select c from t1 union select e from t1) or t1.a>=f and b>=11 then t1.c-(t1.c)*19 when b not in (e,c,t1.d) then t1.b else t1.c end when 13 then f else -t1.f end from t1)) then 17 when not exists(select 1 from t1 where not exists(select 1 from t1 where f not in (t1.d,f, -t1.b)) or -19<=t1.c) or t1.e between 13 and t1.a then f else d end<>t1.f) and f between 11 and t1.c and t1.e not in (t1.d,c,t1.e)) or d not between t1.b and t1.d)} +} {200} +do_test randexpr-2.1179 { + db eval {SELECT case coalesce((select t1.e from t1 where +coalesce((select a from t1 where 13 & b & t1.b<=11*a*case when exists(select 1 from t1 where (a-t1.d+t1.e-f<17 and -17 between 19 and a)) then c when 17 between f and t1.c then a*11 else t1.d end),t1.e) not in (b,t1.f,t1.d)),a) when c then -c else t1.b end FROM t1 WHERE NOT ((exists(select 1 from t1 where case when not exists(select 1 from t1 where (select cast(avg(d) AS integer) from t1) in (select a from t1 union select case case when t1.e>t1.d or t1.b in (select c from t1 union select e from t1) or t1.a>=f and b>=11 then t1.c-(t1.c)*19 when b not in (e,c,t1.d) then t1.b else t1.c end when 13 then f else -t1.f end from t1)) then 17 when not exists(select 1 from t1 where not exists(select 1 from t1 where f not in (t1.d,f, -t1.b)) or -19<=t1.c) or t1.e between 13 and t1.a then f else d end<>t1.f) and f between 11 and t1.c and t1.e not in (t1.d,c,t1.e)) or d not between t1.b and t1.d)} +} {200} +do_test randexpr-2.1180 { + db eval {SELECT case when exists(select 1 from t1 where b<>coalesce((select (select + - -count(*)-~count(*)+~+case - -count(distinct (t1.d)) when max(t1.d) then count(*) else max(a) end+(cast(avg(17) AS integer)) from t1) | d from t1 where not exists(select 1 from t1 where (abs(f)/abs(t1.c)) between 13+a and -t1.d)),19) or (coalesce((select t1.d from t1 where (( - -19)>a)),t1.f) in (e,e,t1.e))) then t1.b*t1.f when t1.d not between (a) and a then e else b end FROM t1 WHERE not exists(select 1 from t1 where a in (select 13 from t1 union select 17 from t1))} +} {120000} +do_test randexpr-2.1181 { + db eval {SELECT case when exists(select 1 from t1 where b<>coalesce((select (select + - -count(*)-~count(*)+~+case - -count(distinct (t1.d)) when max(t1.d) then count(*) else max(a) end+(cast(avg(17) AS integer)) from t1) | d from t1 where not exists(select 1 from t1 where (abs(f)/abs(t1.c)) between 13+a and -t1.d)),19) or (coalesce((select t1.d from t1 where (( - -19)>a)),t1.f) in (e,e,t1.e))) then t1.b*t1.f when t1.d not between (a) and a then e else b end FROM t1 WHERE NOT (not exists(select 1 from t1 where a in (select 13 from t1 union select 17 from t1)))} +} {} +do_test randexpr-2.1182 { + db eval {SELECT case when exists(select 1 from t1 where b<>coalesce((select (select + - -count(*)-~count(*)+~+case - -count(distinct (t1.d)) when max(t1.d) then count(*) else max(a) end+(cast(avg(17) AS integer)) from t1) & d from t1 where not exists(select 1 from t1 where (abs(f)/abs(t1.c)) between 13+a and -t1.d)),19) or (coalesce((select t1.d from t1 where (( - -19)>a)),t1.f) in (e,e,t1.e))) then t1.b*t1.f when t1.d not between (a) and a then e else b end FROM t1 WHERE not exists(select 1 from t1 where a in (select 13 from t1 union select 17 from t1))} +} {120000} +do_test randexpr-2.1183 { + db eval {SELECT coalesce((select case when f>17-t1.f then (select +max(coalesce((select +11 from t1 where coalesce((select max(d) from t1 where +t1.c between (f) and c),t1.f) not in (c, -f,t1.e)),d)) from t1) else 17+19 end from t1 where not not exists(select 1 from t1 where t1.a in (select a from t1 union select t1.a from t1) and 17=d or (17)<=(( -19)) and t1.f in (select d from t1 union select 13 from t1) or 19>13 or t1.b not in (t1.b,17,d))), -(t1.c)) FROM t1 WHERE +t1.a-13+(select count(distinct a) from t1)-e*e*case when coalesce((select max(coalesce((select a from t1 where ((case b+t1.c-t1.c*d*17 when t1.a then t1.a else f end<>c))),t1.b+13)) from t1 where t1.f between 17 and t1.d),t1.c)<=(b) then f else t1.e end-13<>t1.f} +} {11} +do_test randexpr-2.1184 { + db eval {SELECT coalesce((select case when f>17-t1.f then (select +max(coalesce((select +11 from t1 where coalesce((select max(d) from t1 where +t1.c between (f) and c),t1.f) not in (c, -f,t1.e)),d)) from t1) else 17+19 end from t1 where not not exists(select 1 from t1 where t1.a in (select a from t1 union select t1.a from t1) and 17=d or (17)<=(( -19)) and t1.f in (select d from t1 union select 13 from t1) or 19>13 or t1.b not in (t1.b,17,d))), -(t1.c)) FROM t1 WHERE NOT (+t1.a-13+(select count(distinct a) from t1)-e*e*case when coalesce((select max(coalesce((select a from t1 where ((case b+t1.c-t1.c*d*17 when t1.a then t1.a else f end<>c))),t1.b+13)) from t1 where t1.f between 17 and t1.d),t1.c)<=(b) then f else t1.e end-13<>t1.f)} +} {} +do_test randexpr-2.1185 { + db eval {SELECT coalesce((select 13 from t1 where ~(select max(b) from t1)<= -+d*f+t1.b*f or coalesce((select max(case when d=(abs(19)/abs(t1.f)) then case b+d when (abs(coalesce((select 11 from t1 where t1.f between -d and c),t1.f))/abs(t1.a)) then b else t1.d end when a=t1.e),17)+ -c FROM t1 WHERE t1.b-+(t1.b) in (select a from t1 union select 19 from t1)} +} {} +do_test randexpr-2.1186 { + db eval {SELECT coalesce((select 13 from t1 where ~(select max(b) from t1)<= -+d*f+t1.b*f or coalesce((select max(case when d=(abs(19)/abs(t1.f)) then case b+d when (abs(coalesce((select 11 from t1 where t1.f between -d and c),t1.f))/abs(t1.a)) then b else t1.d end when a=t1.e),17)+ -c FROM t1 WHERE NOT (t1.b-+(t1.b) in (select a from t1 union select 19 from t1))} +} {-283} +do_test randexpr-2.1187 { + db eval {SELECT case when (abs((abs(d)/abs(t1.f-c)))/abs( -t1.f))*case when (t1.c not in (case when t1.b>case t1.d when t1.b then e else 11 end then t1.a when ( -t1.d in (select -count(*)-cast(avg(f) AS integer) from t1 union select count(*) from t1)) or 11 in (e,t1.e,c) then a else b end,t1.a,11) or t1.a in (17,t1.a,t1.d) and b>(t1.a)) then 11 when ct1.b then t1.c else 17 end FROM t1 WHERE t1.b>f} +} {} +do_test randexpr-2.1188 { + db eval {SELECT case when (abs((abs(d)/abs(t1.f-c)))/abs( -t1.f))*case when (t1.c not in (case when t1.b>case t1.d when t1.b then e else 11 end then t1.a when ( -t1.d in (select -count(*)-cast(avg(f) AS integer) from t1 union select count(*) from t1)) or 11 in (e,t1.e,c) then a else b end,t1.a,11) or t1.a in (17,t1.a,t1.d) and b>(t1.a)) then 11 when ct1.b then t1.c else 17 end FROM t1 WHERE NOT (t1.b>f)} +} {17} +do_test randexpr-2.1189 { + db eval {SELECT t1.e-case when case when ((exists(select 1 from t1 where not exists(select 1 from t1 where case when not 13<=13 or (t1.c<>t1.e) then t1.d else +13 end+13 in (select max(13) | max((t1.b)) from t1 union select max(f) from t1))))) then t1.f else ~t1.e | t1.d*t1.b end+11 not between t1.c and 13 then b when (t1.f not in (19,t1.f,t1.d)) then c else -b end FROM t1 WHERE ( -(select -min(13-t1.b) from t1)-coalesce((select case when -d>=t1.e or 11 between 17 and -t1.e then 19+f when t1.f=11 then -t1.c else t1.b end from t1 where t1.a not in (11,t1.e,t1.a)),t1.c)*11 in (select -case abs((abs(min(t1.d)))) when max(19) then cast(avg(f) AS integer) else case count(*) when count(*) then (count(distinct t1.f)) else cast(avg(11) AS integer) end end from t1 union select min(d) from t1)) or b in (select (count(*)) from t1 union select max(t1.a) from t1)} +} {} +do_test randexpr-2.1190 { + db eval {SELECT t1.e-case when case when ((exists(select 1 from t1 where not exists(select 1 from t1 where case when not 13<=13 or (t1.c<>t1.e) then t1.d else +13 end+13 in (select max(13) | max((t1.b)) from t1 union select max(f) from t1))))) then t1.f else ~t1.e | t1.d*t1.b end+11 not between t1.c and 13 then b when (t1.f not in (19,t1.f,t1.d)) then c else -b end FROM t1 WHERE NOT (( -(select -min(13-t1.b) from t1)-coalesce((select case when -d>=t1.e or 11 between 17 and -t1.e then 19+f when t1.f=11 then -t1.c else t1.b end from t1 where t1.a not in (11,t1.e,t1.a)),t1.c)*11 in (select -case abs((abs(min(t1.d)))) when max(19) then cast(avg(f) AS integer) else case count(*) when count(*) then (count(distinct t1.f)) else cast(avg(11) AS integer) end end from t1 union select min(d) from t1)) or b in (select (count(*)) from t1 union select max(t1.a) from t1))} +} {300} +do_test randexpr-2.1191 { + db eval {SELECT t1.e-case when case when ((exists(select 1 from t1 where not exists(select 1 from t1 where case when not 13<=13 or (t1.c<>t1.e) then t1.d else +13 end+13 in (select max(13) & max((t1.b)) from t1 union select max(f) from t1))))) then t1.f else ~t1.e & t1.d*t1.b end+11 not between t1.c and 13 then b when (t1.f not in (19,t1.f,t1.d)) then c else -b end FROM t1 WHERE NOT (( -(select -min(13-t1.b) from t1)-coalesce((select case when -d>=t1.e or 11 between 17 and -t1.e then 19+f when t1.f=11 then -t1.c else t1.b end from t1 where t1.a not in (11,t1.e,t1.a)),t1.c)*11 in (select -case abs((abs(min(t1.d)))) when max(19) then cast(avg(f) AS integer) else case count(*) when count(*) then (count(distinct t1.f)) else cast(avg(11) AS integer) end end from t1 union select min(d) from t1)) or b in (select (count(*)) from t1 union select max(t1.a) from t1))} +} {300} +do_test randexpr-2.1192 { + db eval {SELECT (coalesce((select c*(select +~count(distinct 19)-cast(avg(~ -c) AS integer)-max( -f)-cast(avg(t1.d) AS integer) from t1)+t1.a*t1.f+t1.e-a*b from t1 where not t1.ed and 11<=t1.e and (not exists(select 1 from t1 where exists(select 1 from t1 where (13=a)) or t1.e>t1.b))),19)) FROM t1 WHERE coalesce((select max(t1.f*11) from t1 where not exists(select 1 from t1 where t1.a<>17) and t1.b>case (abs(b* -t1.a)/abs(11)) when b*case case when f>=t1.e then 11 when t1.b<=d then 17 else a end* -a when e then 11 else c end then (t1.b) else 19 end or t1.f<13), -b)>=e and ((d in (select f from t1 union select f from t1)))} +} {} +do_test randexpr-2.1193 { + db eval {SELECT (coalesce((select c*(select +~count(distinct 19)-cast(avg(~ -c) AS integer)-max( -f)-cast(avg(t1.d) AS integer) from t1)+t1.a*t1.f+t1.e-a*b from t1 where not t1.ed and 11<=t1.e and (not exists(select 1 from t1 where exists(select 1 from t1 where (13=a)) or t1.e>t1.b))),19)) FROM t1 WHERE NOT (coalesce((select max(t1.f*11) from t1 where not exists(select 1 from t1 where t1.a<>17) and t1.b>case (abs(b* -t1.a)/abs(11)) when b*case case when f>=t1.e then 11 when t1.b<=d then 17 else a end* -a when e then 11 else c end then (t1.b) else 19 end or t1.f<13), -b)>=e and ((d in (select f from t1 union select f from t1))))} +} {10200} +do_test randexpr-2.1194 { + db eval {SELECT b-b+case when d+e between 17 and case when exists(select 1 from t1 where coalesce((select max(coalesce((select 11 from t1 where t1.e not between 13 and case when t1.e<>c then c | 19+t1.a else 17 end),t1.a)) from t1 where t1.d<=17 or a not in (b,11,a)),(t1.b))+b>=t1.a) then 11 else a end then d else a end+11*f FROM t1 WHERE (t1.b*19<=17)} +} {} +do_test randexpr-2.1195 { + db eval {SELECT b-b+case when d+e between 17 and case when exists(select 1 from t1 where coalesce((select max(coalesce((select 11 from t1 where t1.e not between 13 and case when t1.e<>c then c | 19+t1.a else 17 end),t1.a)) from t1 where t1.d<=17 or a not in (b,11,a)),(t1.b))+b>=t1.a) then 11 else a end then d else a end+11*f FROM t1 WHERE NOT ((t1.b*19<=17))} +} {6700} +do_test randexpr-2.1196 { + db eval {SELECT b-b+case when d+e between 17 and case when exists(select 1 from t1 where coalesce((select max(coalesce((select 11 from t1 where t1.e not between 13 and case when t1.e<>c then c & 19+t1.a else 17 end),t1.a)) from t1 where t1.d<=17 or a not in (b,11,a)),(t1.b))+b>=t1.a) then 11 else a end then d else a end+11*f FROM t1 WHERE NOT ((t1.b*19<=17))} +} {6700} +do_test randexpr-2.1197 { + db eval {SELECT +(abs(13)/abs(+~~case t1.e | +11-b-coalesce((select max(c) from t1 where 19 in (select cast(avg(coalesce((select max(case when t1.ae*c then 11 else 13 end from t1 where -t1.c not between t1.f and 11),t1.e)) AS integer) when case max( -d) when ((min(17))) then cast(avg(t1.a) AS integer) else min(e) end+cast(avg((t1.b)) AS integer) then cast(avg(t1.d) AS integer) else -(max(c)) end from t1)-f | b*13+e when t1.b then (f) else t1.a end in (select d from t1 union select 17 from t1)),d) FROM t1 WHERE t1.e*c>13-+t1.f | (abs((select abs(min(b)-abs( - -count(distinct 17-d-13+ -e-(t1.d)*e)+max(t1.e)) | (~abs((max(c)))+cast(avg(17) AS integer)-count(*)*cast(avg(11) AS integer))) from t1))/abs(t1.f))} +} {400} +do_test randexpr-2.1201 { + db eval {SELECT coalesce((select t1.f from t1 where case d-(select case cast(avg(coalesce((select case when not 11<>e*c then 11 else 13 end from t1 where -t1.c not between t1.f and 11),t1.e)) AS integer) when case max( -d) when ((min(17))) then cast(avg(t1.a) AS integer) else min(e) end+cast(avg((t1.b)) AS integer) then cast(avg(t1.d) AS integer) else -(max(c)) end from t1)-f | b*13+e when t1.b then (f) else t1.a end in (select d from t1 union select 17 from t1)),d) FROM t1 WHERE NOT (t1.e*c>13-+t1.f | (abs((select abs(min(b)-abs( - -count(distinct 17-d-13+ -e-(t1.d)*e)+max(t1.e)) | (~abs((max(c)))+cast(avg(17) AS integer)-count(*)*cast(avg(11) AS integer))) from t1))/abs(t1.f)))} +} {} +do_test randexpr-2.1202 { + db eval {SELECT coalesce((select t1.f from t1 where case d-(select case cast(avg(coalesce((select case when not 11<>e*c then 11 else 13 end from t1 where -t1.c not between t1.f and 11),t1.e)) AS integer) when case max( -d) when ((min(17))) then cast(avg(t1.a) AS integer) else min(e) end+cast(avg((t1.b)) AS integer) then cast(avg(t1.d) AS integer) else -(max(c)) end from t1)-f & b*13+e when t1.b then (f) else t1.a end in (select d from t1 union select 17 from t1)),d) FROM t1 WHERE t1.e*c>13-+t1.f | (abs((select abs(min(b)-abs( - -count(distinct 17-d-13+ -e-(t1.d)*e)+max(t1.e)) | (~abs((max(c)))+cast(avg(17) AS integer)-count(*)*cast(avg(11) AS integer))) from t1))/abs(t1.f))} +} {400} +do_test randexpr-2.1203 { + db eval {SELECT t1.b-~case when ~(abs(17)/abs(t1.a))+17+t1.b in (select count(distinct d) | count(*) from t1 union select case count(*) | count(distinct e) when count(*) then -count(*) else cast(avg(11) AS integer) end from t1) and t1.e>b or e not between (e) and c and 17 in (t1.c,b,b) and t1.a not between a and (t1.f) then coalesce((select t1.a*t1.c from t1 where -11 in (t1.a,(t1.f), -f)),13)*t1.c else t1.f end FROM t1 WHERE (t1.e<>t1.a+~~c-t1.a+13*e-17+t1.b)} +} {801} +do_test randexpr-2.1204 { + db eval {SELECT t1.b-~case when ~(abs(17)/abs(t1.a))+17+t1.b in (select count(distinct d) | count(*) from t1 union select case count(*) | count(distinct e) when count(*) then -count(*) else cast(avg(11) AS integer) end from t1) and t1.e>b or e not between (e) and c and 17 in (t1.c,b,b) and t1.a not between a and (t1.f) then coalesce((select t1.a*t1.c from t1 where -11 in (t1.a,(t1.f), -f)),13)*t1.c else t1.f end FROM t1 WHERE NOT ((t1.e<>t1.a+~~c-t1.a+13*e-17+t1.b))} +} {} +do_test randexpr-2.1205 { + db eval {SELECT t1.b-~case when ~(abs(17)/abs(t1.a))+17+t1.b in (select count(distinct d) & count(*) from t1 union select case count(*) & count(distinct e) when count(*) then -count(*) else cast(avg(11) AS integer) end from t1) and t1.e>b or e not between (e) and c and 17 in (t1.c,b,b) and t1.a not between a and (t1.f) then coalesce((select t1.a*t1.c from t1 where -11 in (t1.a,(t1.f), -f)),13)*t1.c else t1.f end FROM t1 WHERE (t1.e<>t1.a+~~c-t1.a+13*e-17+t1.b)} +} {801} +do_test randexpr-2.1206 { + db eval {SELECT ((abs(b)/abs(t1.e+coalesce((select max((abs(coalesce((select max(11) from t1 where t1.a<=coalesce((select case when t1.a in (case t1.b when t1.d then t1.d else a end,17,11) then 13 when t1.a>b then 19 else d end from t1 where c in (select (~case count(*) when min(f) then -min(d) else count(distinct (t1.f)) end)*(count(*)) from t1 union select -min((t1.c)) from t1)),11) and (b<=t1.c)),t1.f))/abs(e))-13) from t1 where b not in (d,( -e),e)),c)-t1.c))) FROM t1 WHERE (exists(select 1 from t1 where b in (select +( -abs(max(19+((select case -+cast(avg(e) AS integer) when -max(19)-min(t1.c) | count(*) then count(distinct t1.e) else min(f) end-cast(avg( -19) AS integer)*count(*) | count(*) from t1))-17)) | +cast(avg((select cast(avg(a) AS integer) from t1)*f) AS integer)-cast(avg(13-t1.a+b) AS integer))+ -max(t1.a) from t1 union select cast(avg( -f) AS integer) from t1)))} +} {} +do_test randexpr-2.1207 { + db eval {SELECT ((abs(b)/abs(t1.e+coalesce((select max((abs(coalesce((select max(11) from t1 where t1.a<=coalesce((select case when t1.a in (case t1.b when t1.d then t1.d else a end,17,11) then 13 when t1.a>b then 19 else d end from t1 where c in (select (~case count(*) when min(f) then -min(d) else count(distinct (t1.f)) end)*(count(*)) from t1 union select -min((t1.c)) from t1)),11) and (b<=t1.c)),t1.f))/abs(e))-13) from t1 where b not in (d,( -e),e)),c)-t1.c))) FROM t1 WHERE NOT ((exists(select 1 from t1 where b in (select +( -abs(max(19+((select case -+cast(avg(e) AS integer) when -max(19)-min(t1.c) | count(*) then count(distinct t1.e) else min(f) end-cast(avg( -19) AS integer)*count(*) | count(*) from t1))-17)) | +cast(avg((select cast(avg(a) AS integer) from t1)*f) AS integer)-cast(avg(13-t1.a+b) AS integer))+ -max(t1.a) from t1 union select cast(avg( -f) AS integer) from t1))))} +} {1} +do_test randexpr-2.1208 { + db eval {SELECT t1.f-17+(abs(case when ~e*coalesce((select max(coalesce((select d from t1 where not -(19*t1.d*17) not in (t1.a*t1.c,b,b)),f)) from t1 where 13 between t1.d and 19),11* -t1.e)-(t1.a)>d then 17 when (e in (select -(t1.d) from t1 union select -(t1.b) from t1)) then e else -t1.d end)/abs(17))*a FROM t1 WHERE 17 in (select 19 from t1 union select -17 | d from t1)} +} {} +do_test randexpr-2.1209 { + db eval {SELECT t1.f-17+(abs(case when ~e*coalesce((select max(coalesce((select d from t1 where not -(19*t1.d*17) not in (t1.a*t1.c,b,b)),f)) from t1 where 13 between t1.d and 19),11* -t1.e)-(t1.a)>d then 17 when (e in (select -(t1.d) from t1 union select -(t1.b) from t1)) then e else -t1.d end)/abs(17))*a FROM t1 WHERE NOT (17 in (select 19 from t1 union select -17 | d from t1))} +} {683} +do_test randexpr-2.1210 { + db eval {SELECT case t1.a when case when 13+( -f-b)*c-t1.d-t1.c | c+d>=d*case when not ++c+t1.d<>+b- -a*t1.e then -f else 17 end+t1.f then t1.e when 11<>19 then c else 11 end then e else f end FROM t1 WHERE (case when (abs(t1.f+case f-case when exists(select 1 from t1 where t1.c>13) then t1.e when t1.f>= -f then b else e end when 13 then t1.e else t1.c end)/abs(c)) in (select max(f)*max(f)*( -max( -17)) | min(t1.a) | cast(avg(13) AS integer)+count(*) from t1 union select ( -max(e)) from t1) then ( -d) when c not between f and ( -c) then 13 else b end between t1.a and e) and 19 not between 19 and c} +} {} +do_test randexpr-2.1211 { + db eval {SELECT case t1.a when case when 13+( -f-b)*c-t1.d-t1.c | c+d>=d*case when not ++c+t1.d<>+b- -a*t1.e then -f else 17 end+t1.f then t1.e when 11<>19 then c else 11 end then e else f end FROM t1 WHERE NOT ((case when (abs(t1.f+case f-case when exists(select 1 from t1 where t1.c>13) then t1.e when t1.f>= -f then b else e end when 13 then t1.e else t1.c end)/abs(c)) in (select max(f)*max(f)*( -max( -17)) | min(t1.a) | cast(avg(13) AS integer)+count(*) from t1 union select ( -max(e)) from t1) then ( -d) when c not between f and ( -c) then 13 else b end between t1.a and e) and 19 not between 19 and c)} +} {600} +do_test randexpr-2.1212 { + db eval {SELECT case t1.a when case when 13+( -f-b)*c-t1.d-t1.c & c+d>=d*case when not ++c+t1.d<>+b- -a*t1.e then -f else 17 end+t1.f then t1.e when 11<>19 then c else 11 end then e else f end FROM t1 WHERE NOT ((case when (abs(t1.f+case f-case when exists(select 1 from t1 where t1.c>13) then t1.e when t1.f>= -f then b else e end when 13 then t1.e else t1.c end)/abs(c)) in (select max(f)*max(f)*( -max( -17)) | min(t1.a) | cast(avg(13) AS integer)+count(*) from t1 union select ( -max(e)) from t1) then ( -d) when c not between f and ( -c) then 13 else b end between t1.a and e) and 19 not between 19 and c)} +} {600} +do_test randexpr-2.1213 { + db eval {SELECT case when 19=t1.e or (abs(t1.f)/abs(((select -count(distinct f+~t1.e-t1.b-coalesce((select max(b*c) from t1 where 17<>b),b))+~cast(avg(d) AS integer) from t1)))) not between f and d then coalesce((select max( -a) from t1 where 13<=11 or t1.d>=f),t1.d) when 17 in (select 11 from t1 union select t1.a from t1) then t1.d else t1.c end | 19 FROM t1 WHERE (case t1.d when ~a then coalesce((select max((abs( -~+b)/abs(t1.c))) from t1 where case t1.e when (abs((abs(case t1.a++t1.d | 19-coalesce((select e from t1 where b not between t1.f+b+c and t1.b), -t1.f) when t1.e then t1.a else f end)/abs(t1.b)))/abs(t1.e)) then t1.d else t1.d end>t1.f),t1.d)*t1.b else t1.f end not between a and e)} +} {403} +do_test randexpr-2.1214 { + db eval {SELECT case when 19=t1.e or (abs(t1.f)/abs(((select -count(distinct f+~t1.e-t1.b-coalesce((select max(b*c) from t1 where 17<>b),b))+~cast(avg(d) AS integer) from t1)))) not between f and d then coalesce((select max( -a) from t1 where 13<=11 or t1.d>=f),t1.d) when 17 in (select 11 from t1 union select t1.a from t1) then t1.d else t1.c end | 19 FROM t1 WHERE NOT ((case t1.d when ~a then coalesce((select max((abs( -~+b)/abs(t1.c))) from t1 where case t1.e when (abs((abs(case t1.a++t1.d | 19-coalesce((select e from t1 where b not between t1.f+b+c and t1.b), -t1.f) when t1.e then t1.a else f end)/abs(t1.b)))/abs(t1.e)) then t1.d else t1.d end>t1.f),t1.d)*t1.b else t1.f end not between a and e))} +} {} +do_test randexpr-2.1215 { + db eval {SELECT case when 19=t1.e or (abs(t1.f)/abs(((select -count(distinct f+~t1.e-t1.b-coalesce((select max(b*c) from t1 where 17<>b),b))+~cast(avg(d) AS integer) from t1)))) not between f and d then coalesce((select max( -a) from t1 where 13<=11 or t1.d>=f),t1.d) when 17 in (select 11 from t1 union select t1.a from t1) then t1.d else t1.c end & 19 FROM t1 WHERE (case t1.d when ~a then coalesce((select max((abs( -~+b)/abs(t1.c))) from t1 where case t1.e when (abs((abs(case t1.a++t1.d | 19-coalesce((select e from t1 where b not between t1.f+b+c and t1.b), -t1.f) when t1.e then t1.a else f end)/abs(t1.b)))/abs(t1.e)) then t1.d else t1.d end>t1.f),t1.d)*t1.b else t1.f end not between a and e)} +} {16} +do_test randexpr-2.1216 { + db eval {SELECT coalesce((select t1.c from t1 where -a in (select e from t1 union select 13 from t1)),(select count(distinct coalesce((select max((17)) from t1 where c not between case 19-t1.b when a then ~+(abs((select count(distinct (t1.a)) from t1)+(t1.b))/abs((t1.a)*a+13 | t1.d | t1.a)) else a end and 13 or d in (a,a,t1.f)),d)) from t1) | t1.d) FROM t1 WHERE et1.a then (select +abs(count(distinct t1.f)*max(13)) from t1) else +d end>=b+t1.c and b not in (f,13,b) then t1.d when b>b then d else t1.d end*11 FROM t1 WHERE d<>b} +} {4400} +do_test randexpr-2.1220 { + db eval {SELECT case when case when t1.b<=f+coalesce((select max(11) from t1 where not e in (select count(distinct f) from t1 union select count(*) from t1)),t1.d) or 19 between (e) and 19 and f not in (t1.d,(19),t1.e) and exists(select 1 from t1 where t1.e<=19) or t1.e>t1.a then (select +abs(count(distinct t1.f)*max(13)) from t1) else +d end>=b+t1.c and b not in (f,13,b) then t1.d when b>b then d else t1.d end*11 FROM t1 WHERE NOT (d<>b)} +} {} +do_test randexpr-2.1221 { + db eval {SELECT ~(abs(case when t1.a not between -t1.d*(b) and 17 then f when e<=t1.f then b*t1.d else 13*(a) end)/abs((coalesce((select d from t1 where +(abs((select (min(a)) from t1))/abs((select count(distinct a) from t1)))- -t1.a in (select -case max(e)+count(distinct d) when cast(avg(( -t1.e)) AS integer) then ( -(count(*))) else -min(d) end+max(t1.f) from t1 union select max(t1.a) from t1)),t1.d)))) FROM t1 WHERE (t1.a=13 then 11 else a end then -17 else a end and (t1.c) and (b=17)) then (+(t1.c)) when t1.a<=t1.f then t1.d else 11 end FROM t1 WHERE c<>~13} +} {1000} +do_test randexpr-2.1224 { + db eval {SELECT f+case when (~t1.c between case when +d between (select -abs(count(distinct t1.a+17+t1.f))+case min(19)*count(distinct -t1.a) when (count(*)) then ((count(*))) else ((max(t1.e))) end from t1) and case when -t1.b>=13 then 11 else a end then -17 else a end and (t1.c) and (b=17)) then (+(t1.c)) when t1.a<=t1.f then t1.d else 11 end FROM t1 WHERE NOT (c<>~13)} +} {} +do_test randexpr-2.1225 { + db eval {SELECT case when ~(abs((select count(*) from t1))/abs(c))<>case when 17*case when coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.f=t1.e)),t1.a) in (select min(t1.f) from t1 union select -min(t1.d) from t1) then 11 when 11<=(a) then f else -e end | -t1.b< -c then d else f end then ((t1.a)) when t1.f in (select ~(++(count(*))+cast(avg(t1.f) AS integer))+max(( -t1.d)) from t1 union select cast(avg(e) AS integer) from t1) then 11 else d end FROM t1 WHERE t1.a between case when t1.d=t1.a*11 | (select (cast(avg(t1.a) AS integer)+abs( -count(distinct e)) | ~count(distinct coalesce((select max(b) from t1 where not exists(select 1 from t1 where -e>=13)),(t1.e)))- -( -max(d))* -count(*)) from t1)+(abs(t1.f)/abs((select cast(avg(11) AS integer) from t1))) then t1.a else coalesce((select max(c) from t1 where 11>=t1.e or 11 in (t1.b,t1.b,t1.d) or t1.a>=t1.a),13)*a end and t1.c} +} {} +do_test randexpr-2.1226 { + db eval {SELECT case when ~(abs((select count(*) from t1))/abs(c))<>case when 17*case when coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.f=t1.e)),t1.a) in (select min(t1.f) from t1 union select -min(t1.d) from t1) then 11 when 11<=(a) then f else -e end | -t1.b< -c then d else f end then ((t1.a)) when t1.f in (select ~(++(count(*))+cast(avg(t1.f) AS integer))+max(( -t1.d)) from t1 union select cast(avg(e) AS integer) from t1) then 11 else d end FROM t1 WHERE NOT (t1.a between case when t1.d=t1.a*11 | (select (cast(avg(t1.a) AS integer)+abs( -count(distinct e)) | ~count(distinct coalesce((select max(b) from t1 where not exists(select 1 from t1 where -e>=13)),(t1.e)))- -( -max(d))* -count(*)) from t1)+(abs(t1.f)/abs((select cast(avg(11) AS integer) from t1))) then t1.a else coalesce((select max(c) from t1 where 11>=t1.e or 11 in (t1.b,t1.b,t1.d) or t1.a>=t1.a),13)*a end and t1.c)} +} {100} +do_test randexpr-2.1227 { + db eval {SELECT case when ~(abs((select count(*) from t1))/abs(c))<>case when 17*case when coalesce((select max(f) from t1 where exists(select 1 from t1 where t1.f=t1.e)),t1.a) in (select min(t1.f) from t1 union select -min(t1.d) from t1) then 11 when 11<=(a) then f else -e end & -t1.b< -c then d else f end then ((t1.a)) when t1.f in (select ~(++(count(*))+cast(avg(t1.f) AS integer))+max(( -t1.d)) from t1 union select cast(avg(e) AS integer) from t1) then 11 else d end FROM t1 WHERE NOT (t1.a between case when t1.d=t1.a*11 | (select (cast(avg(t1.a) AS integer)+abs( -count(distinct e)) | ~count(distinct coalesce((select max(b) from t1 where not exists(select 1 from t1 where -e>=13)),(t1.e)))- -( -max(d))* -count(*)) from t1)+(abs(t1.f)/abs((select cast(avg(11) AS integer) from t1))) then t1.a else coalesce((select max(c) from t1 where 11>=t1.e or 11 in (t1.b,t1.b,t1.d) or t1.a>=t1.a),13)*a end and t1.c)} +} {100} +do_test randexpr-2.1228 { + db eval {SELECT (coalesce((select 19 from t1 where - -t1.d | t1.c+~(select max(11) | -~count(*)+count(*)-cast(avg(case when t1.e in (select a from t1 union select f from t1) then c else 11 end) AS integer) from t1)*coalesce((select t1.b from t1 where ((abs(t1.b)/abs(coalesce((select (b)-f from t1 where t1.f not in ( -e, -t1.b, -t1.d) and t1.d>=a or 19 not in (a,13,t1.f)),b))))=a or 19 not in (a,13,t1.f)),b))))=a or 19 not in (a,13,t1.f)),b))))t1.d then (17) else e end+t1.d-19 FROM t1 WHERE not -t1.e+t1.c not between case when -case case when exists(select 1 from t1 where 17 in (select min(19) from t1 union select -min(19) from t1) and 13 not in (17,a,t1.e)) then case when f>=19 then (c) when t1.f>13 then 19 else 19 end | t1.a else e end when b then t1.c else b end in (select -max(13) from t1 union select count(distinct 17) from t1) and 11 not in (11,t1.a,f) and t1.c=f then ~(abs(t1.e)/abs(t1.d)) when f<13 then 17 else 19 end*b and t1.e} +} {} +do_test randexpr-2.1234 { + db eval {SELECT ~case when exists(select 1 from t1 where t1.c in (t1.a,e+t1.b+e-19 | coalesce((select max(t1.f | t1.a+11*a) from t1 where (abs((abs(f)/abs(d)))/abs(coalesce((select max(t1.a) from t1 where (13 between (f) and f and t1.e between e and t1.b)),t1.c)))<=(f)),e)+f+13, -t1.c)) then t1.b when t1.d<>t1.d then (17) else e end+t1.d-19 FROM t1 WHERE NOT (not -t1.e+t1.c not between case when -case case when exists(select 1 from t1 where 17 in (select min(19) from t1 union select -min(19) from t1) and 13 not in (17,a,t1.e)) then case when f>=19 then (c) when t1.f>13 then 19 else 19 end | t1.a else e end when b then t1.c else b end in (select -max(13) from t1 union select count(distinct 17) from t1) and 11 not in (11,t1.a,f) and t1.c=f then ~(abs(t1.e)/abs(t1.d)) when f<13 then 17 else 19 end*b and t1.e)} +} {-120} +do_test randexpr-2.1235 { + db eval {SELECT ~case when exists(select 1 from t1 where t1.c in (t1.a,e+t1.b+e-19 & coalesce((select max(t1.f & t1.a+11*a) from t1 where (abs((abs(f)/abs(d)))/abs(coalesce((select max(t1.a) from t1 where (13 between (f) and f and t1.e between e and t1.b)),t1.c)))<=(f)),e)+f+13, -t1.c)) then t1.b when t1.d<>t1.d then (17) else e end+t1.d-19 FROM t1 WHERE NOT (not -t1.e+t1.c not between case when -case case when exists(select 1 from t1 where 17 in (select min(19) from t1 union select -min(19) from t1) and 13 not in (17,a,t1.e)) then case when f>=19 then (c) when t1.f>13 then 19 else 19 end | t1.a else e end when b then t1.c else b end in (select -max(13) from t1 union select count(distinct 17) from t1) and 11 not in (11,t1.a,f) and t1.c=f then ~(abs(t1.e)/abs(t1.d)) when f<13 then 17 else 19 end*b and t1.e)} +} {-120} +do_test randexpr-2.1236 { + db eval {SELECT ((select min(e+case when b not between coalesce((select t1.d | b from t1 where not exists(select 1 from t1 where 17>11)), -c) and (t1.a) or ed then a when 19>11 then -13 else t1.b end+13)+count(distinct d)+count(*)* -count(distinct t1.f)-((count(distinct t1.c)))+min(a) | max(c) from t1)*t1.e*19*11) FROM t1 WHERE b<>(select count(distinct f) from t1)} +} {104918000} +do_test randexpr-2.1237 { + db eval {SELECT ((select min(e+case when b not between coalesce((select t1.d | b from t1 where not exists(select 1 from t1 where 17>11)), -c) and (t1.a) or ed then a when 19>11 then -13 else t1.b end+13)+count(distinct d)+count(*)* -count(distinct t1.f)-((count(distinct t1.c)))+min(a) | max(c) from t1)*t1.e*19*11) FROM t1 WHERE NOT (b<>(select count(distinct f) from t1))} +} {} +do_test randexpr-2.1238 { + db eval {SELECT ((select min(e+case when b not between coalesce((select t1.d & b from t1 where not exists(select 1 from t1 where 17>11)), -c) and (t1.a) or ed then a when 19>11 then -13 else t1.b end+13)+count(distinct d)+count(*)* -count(distinct t1.f)-((count(distinct t1.c)))+min(a) & max(c) from t1)*t1.e*19*11) FROM t1 WHERE b<>(select count(distinct f) from t1)} +} {836000} +do_test randexpr-2.1239 { + db eval {SELECT coalesce((select max(t1.a) from t1 where +b-b+t1.e<>(case when (case when ((select case -cast(avg(17) AS integer) when max(17) then count(*) else count(distinct t1.d) end from t1))-case 19 when 11 then e else t1.f end<=e then 19 when b not between t1.c and 13 then e else 17 end+t1.c in (select 19 from t1 union select a from t1)) then e-t1.c else t1.f end*t1.b)-e),a) FROM t1 WHERE coalesce((select 13 from t1 where t1.c<>t1.b | t1.e*19-e),f+t1.d) not in (13,(c)*a,e)} +} {} +do_test randexpr-2.1240 { + db eval {SELECT coalesce((select max(t1.a) from t1 where +b-b+t1.e<>(case when (case when ((select case -cast(avg(17) AS integer) when max(17) then count(*) else count(distinct t1.d) end from t1))-case 19 when 11 then e else t1.f end<=e then 19 when b not between t1.c and 13 then e else 17 end+t1.c in (select 19 from t1 union select a from t1)) then e-t1.c else t1.f end*t1.b)-e),a) FROM t1 WHERE NOT (coalesce((select 13 from t1 where t1.c<>t1.b | t1.e*19-e),f+t1.d) not in (13,(c)*a,e))} +} {100} +do_test randexpr-2.1241 { + db eval {SELECT t1.d-case when (11) not between coalesce((select max(a) from t1 where f in (select cast(avg(t1.c+(select case case case max(a) when -count(*) then min(b) else - -(min((t1.a))) end when (max((19))) then max(t1.f) else count(*) end when max(t1.a) then -min(t1.c) else count(*) end from t1)+c+t1.d) AS integer)-min(a) | -cast(avg(f) AS integer)*(cast(avg(f) AS integer))-( -count(*)) from t1 union select min( -c) from t1)),t1.a) and -c then (d) when t1.f<=((t1.c)) then - -13 else c end FROM t1 WHERE 13-e>(abs(t1.f)/abs((t1.d)*d))} +} {} +do_test randexpr-2.1242 { + db eval {SELECT t1.d-case when (11) not between coalesce((select max(a) from t1 where f in (select cast(avg(t1.c+(select case case case max(a) when -count(*) then min(b) else - -(min((t1.a))) end when (max((19))) then max(t1.f) else count(*) end when max(t1.a) then -min(t1.c) else count(*) end from t1)+c+t1.d) AS integer)-min(a) | -cast(avg(f) AS integer)*(cast(avg(f) AS integer))-( -count(*)) from t1 union select min( -c) from t1)),t1.a) and -c then (d) when t1.f<=((t1.c)) then - -13 else c end FROM t1 WHERE NOT (13-e>(abs(t1.f)/abs((t1.d)*d)))} +} {0} +do_test randexpr-2.1243 { + db eval {SELECT t1.d-case when (11) not between coalesce((select max(a) from t1 where f in (select cast(avg(t1.c+(select case case case max(a) when -count(*) then min(b) else - -(min((t1.a))) end when (max((19))) then max(t1.f) else count(*) end when max(t1.a) then -min(t1.c) else count(*) end from t1)+c+t1.d) AS integer)-min(a) & -cast(avg(f) AS integer)*(cast(avg(f) AS integer))-( -count(*)) from t1 union select min( -c) from t1)),t1.a) and -c then (d) when t1.f<=((t1.c)) then - -13 else c end FROM t1 WHERE NOT (13-e>(abs(t1.f)/abs((t1.d)*d)))} +} {0} +do_test randexpr-2.1244 { + db eval {SELECT (abs(coalesce((select max(b) from t1 where not exists(select 1 from t1 where 19>(t1.c))),(11+(abs(c)/abs(19)))+b)+coalesce((select max(t1.c) from t1 where t1.a<=13),t1.d+t1.b+case when exists(select 1 from t1 where -t1.b in (select min(t1.a-+13) from t1 union select max(t1.c) from t1)) then (select ++(cast(avg(11) AS integer)) | cast(avg(b) AS integer)*cast(avg(d) AS integer) from t1) when f>=b then 19 else 19 end))/abs(b)) FROM t1 WHERE not b in (select case when t1.e in (select +cast(avg(d) AS integer)-count(*)*count(*)-(case ~count(distinct d)*cast(avg(t1.b) AS integer) when count(distinct t1.e) then max(19) else cast(avg(t1.b) AS integer) end+(count(distinct t1.c))) from t1 union select -min(t1.f) from t1) or 19<=+11 then ((select (min(t1.b)) from t1)*a-19+17*13) | a when (11 in (select d from t1 union select t1.e from t1)) then 19 else t1.b end from t1 union select t1.c from t1)} +} {} +do_test randexpr-2.1245 { + db eval {SELECT (abs(coalesce((select max(b) from t1 where not exists(select 1 from t1 where 19>(t1.c))),(11+(abs(c)/abs(19)))+b)+coalesce((select max(t1.c) from t1 where t1.a<=13),t1.d+t1.b+case when exists(select 1 from t1 where -t1.b in (select min(t1.a-+13) from t1 union select max(t1.c) from t1)) then (select ++(cast(avg(11) AS integer)) | cast(avg(b) AS integer)*cast(avg(d) AS integer) from t1) when f>=b then 19 else 19 end))/abs(b)) FROM t1 WHERE NOT (not b in (select case when t1.e in (select +cast(avg(d) AS integer)-count(*)*count(*)-(case ~count(distinct d)*cast(avg(t1.b) AS integer) when count(distinct t1.e) then max(19) else cast(avg(t1.b) AS integer) end+(count(distinct t1.c))) from t1 union select -min(t1.f) from t1) or 19<=+11 then ((select (min(t1.b)) from t1)*a-19+17*13) | a when (11 in (select d from t1 union select t1.e from t1)) then 19 else t1.b end from t1 union select t1.c from t1))} +} {4} +do_test randexpr-2.1246 { + db eval {SELECT (abs(coalesce((select max(b) from t1 where not exists(select 1 from t1 where 19>(t1.c))),(11+(abs(c)/abs(19)))+b)+coalesce((select max(t1.c) from t1 where t1.a<=13),t1.d+t1.b+case when exists(select 1 from t1 where -t1.b in (select min(t1.a-+13) from t1 union select max(t1.c) from t1)) then (select ++(cast(avg(11) AS integer)) & cast(avg(b) AS integer)*cast(avg(d) AS integer) from t1) when f>=b then 19 else 19 end))/abs(b)) FROM t1 WHERE NOT (not b in (select case when t1.e in (select +cast(avg(d) AS integer)-count(*)*count(*)-(case ~count(distinct d)*cast(avg(t1.b) AS integer) when count(distinct t1.e) then max(19) else cast(avg(t1.b) AS integer) end+(count(distinct t1.c))) from t1 union select -min(t1.f) from t1) or 19<=+11 then ((select (min(t1.b)) from t1)*a-19+17*13) | a when (11 in (select d from t1 union select t1.e from t1)) then 19 else t1.b end from t1 union select t1.c from t1))} +} {4} +do_test randexpr-2.1247 { + db eval {SELECT +case ~t1.d when case when b*f in (select b from t1 union select 17 from t1) and ((case when t1.f | e in (select ~abs(~(case cast(avg(t1.f) AS integer) when min(b) then min(t1.d) else - -count(distinct e) end | count(*)*( -cast(avg(t1.b) AS integer)))) from t1 union select (count(distinct t1.b)) from t1) then t1.f else t1.f*17+a end-13+e<>t1.c)) then d else t1.c end then t1.f else t1.e end+19 FROM t1 WHERE b>=+t1.e or f<=t1.b and -c*17-t1.d*19 not in (c+coalesce((select (abs(~+d*t1.f)/abs(11)) from t1 where +case when t1.d+ -t1.e in (select max(t1.d)*count(distinct b) from t1 union select count(distinct 11) from t1) then (17) when (t1.e>t1.a) then e else e end not in (e,f,t1.a)),t1.f),t1.a,b)} +} {} +do_test randexpr-2.1248 { + db eval {SELECT +case ~t1.d when case when b*f in (select b from t1 union select 17 from t1) and ((case when t1.f | e in (select ~abs(~(case cast(avg(t1.f) AS integer) when min(b) then min(t1.d) else - -count(distinct e) end | count(*)*( -cast(avg(t1.b) AS integer)))) from t1 union select (count(distinct t1.b)) from t1) then t1.f else t1.f*17+a end-13+e<>t1.c)) then d else t1.c end then t1.f else t1.e end+19 FROM t1 WHERE NOT (b>=+t1.e or f<=t1.b and -c*17-t1.d*19 not in (c+coalesce((select (abs(~+d*t1.f)/abs(11)) from t1 where +case when t1.d+ -t1.e in (select max(t1.d)*count(distinct b) from t1 union select count(distinct 11) from t1) then (17) when (t1.e>t1.a) then e else e end not in (e,f,t1.a)),t1.f),t1.a,b))} +} {519} +do_test randexpr-2.1249 { + db eval {SELECT +case ~t1.d when case when b*f in (select b from t1 union select 17 from t1) and ((case when t1.f & e in (select ~abs(~(case cast(avg(t1.f) AS integer) when min(b) then min(t1.d) else - -count(distinct e) end & count(*)*( -cast(avg(t1.b) AS integer)))) from t1 union select (count(distinct t1.b)) from t1) then t1.f else t1.f*17+a end-13+e<>t1.c)) then d else t1.c end then t1.f else t1.e end+19 FROM t1 WHERE NOT (b>=+t1.e or f<=t1.b and -c*17-t1.d*19 not in (c+coalesce((select (abs(~+d*t1.f)/abs(11)) from t1 where +case when t1.d+ -t1.e in (select max(t1.d)*count(distinct b) from t1 union select count(distinct 11) from t1) then (17) when (t1.e>t1.a) then e else e end not in (e,f,t1.a)),t1.f),t1.a,b))} +} {519} +do_test randexpr-2.1250 { + db eval {SELECT (abs((abs(t1.a)/abs(~17 | coalesce((select ~coalesce((select (d) from t1 where t1.b>=t1.a),case when t1.e-(select ~max( -19*c | e+t1.c) from t1) not between (abs(c)/abs(e)) and t1.e then a else 17 end*17)+13 from t1 where a in (select max(t1.f) from t1 union select ~count(distinct b) from t1)),b) | 13)))/abs(e)) FROM t1 WHERE exists(select 1 from t1 where t1.a+t1.d-11<=t1.e)} +} {0} +do_test randexpr-2.1251 { + db eval {SELECT (abs((abs(t1.a)/abs(~17 | coalesce((select ~coalesce((select (d) from t1 where t1.b>=t1.a),case when t1.e-(select ~max( -19*c | e+t1.c) from t1) not between (abs(c)/abs(e)) and t1.e then a else 17 end*17)+13 from t1 where a in (select max(t1.f) from t1 union select ~count(distinct b) from t1)),b) | 13)))/abs(e)) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.a+t1.d-11<=t1.e))} +} {} +do_test randexpr-2.1252 { + db eval {SELECT (abs((abs(t1.a)/abs(~17 & coalesce((select ~coalesce((select (d) from t1 where t1.b>=t1.a),case when t1.e-(select ~max( -19*c & e+t1.c) from t1) not between (abs(c)/abs(e)) and t1.e then a else 17 end*17)+13 from t1 where a in (select max(t1.f) from t1 union select ~count(distinct b) from t1)),b) & 13)))/abs(e)) FROM t1 WHERE exists(select 1 from t1 where t1.a+t1.d-11<=t1.e)} +} {0} +do_test randexpr-2.1253 { + db eval {SELECT coalesce((select max(d) from t1 where not exists(select 1 from t1 where t1.e not in (13,e,coalesce((select f from t1 where (abs(case -t1.e when ~f then (t1.c)*13-t1.b+a-d+ -t1.a else a end)/abs(11))*19*t1.d>=a),(t1.b)))) or d not in (f,e,19)),coalesce((select max(17) from t1 where e in (select t1.e from t1 union select 17 from t1)),t1.c)) | t1.f FROM t1 WHERE t1.e not in (13,(select +count(*)+abs(cast(avg(case t1.d when 17 then -t1.e+13 else (abs( -c)/abs(case when t1.e*+coalesce((select max(13) from t1 where a>t1.b),t1.f)>=(13) then -f else t1.a end)) end) AS integer)) from t1)*(13),(select ((max(t1.d))) from t1)) and not exists(select 1 from t1 where e+b not in (b,t1.c,t1.e))} +} {} +do_test randexpr-2.1254 { + db eval {SELECT coalesce((select max(d) from t1 where not exists(select 1 from t1 where t1.e not in (13,e,coalesce((select f from t1 where (abs(case -t1.e when ~f then (t1.c)*13-t1.b+a-d+ -t1.a else a end)/abs(11))*19*t1.d>=a),(t1.b)))) or d not in (f,e,19)),coalesce((select max(17) from t1 where e in (select t1.e from t1 union select 17 from t1)),t1.c)) | t1.f FROM t1 WHERE NOT (t1.e not in (13,(select +count(*)+abs(cast(avg(case t1.d when 17 then -t1.e+13 else (abs( -c)/abs(case when t1.e*+coalesce((select max(13) from t1 where a>t1.b),t1.f)>=(13) then -f else t1.a end)) end) AS integer)) from t1)*(13),(select ((max(t1.d))) from t1)) and not exists(select 1 from t1 where e+b not in (b,t1.c,t1.e)))} +} {984} +do_test randexpr-2.1255 { + db eval {SELECT coalesce((select max(d) from t1 where not exists(select 1 from t1 where t1.e not in (13,e,coalesce((select f from t1 where (abs(case -t1.e when ~f then (t1.c)*13-t1.b+a-d+ -t1.a else a end)/abs(11))*19*t1.d>=a),(t1.b)))) or d not in (f,e,19)),coalesce((select max(17) from t1 where e in (select t1.e from t1 union select 17 from t1)),t1.c)) & t1.f FROM t1 WHERE NOT (t1.e not in (13,(select +count(*)+abs(cast(avg(case t1.d when 17 then -t1.e+13 else (abs( -c)/abs(case when t1.e*+coalesce((select max(13) from t1 where a>t1.b),t1.f)>=(13) then -f else t1.a end)) end) AS integer)) from t1)*(13),(select ((max(t1.d))) from t1)) and not exists(select 1 from t1 where e+b not in (b,t1.c,t1.e)))} +} {16} +do_test randexpr-2.1256 { + db eval {SELECT (abs(case when (t1.d*coalesce((select max(case coalesce((select max(e) from t1 where t1.a not in (coalesce((select (select count(distinct t1.e) from t1) from t1 where c>=t1.c),f),19,a)),t1.a) when t1.c then t1.a else b end-a) from t1 where c>t1.d),b)<= -11) then t1.a when not exists(select 1 from t1 where not (t1.d=e) or t1.f between t1.a and -e and (t1.c)=f and a not in (t1.c,a,c)) then t1.a else t1.a end)/abs( -13))+e-d FROM t1 WHERE 17 not in (13,19,t1.c)} +} {107} +do_test randexpr-2.1257 { + db eval {SELECT (abs(case when (t1.d*coalesce((select max(case coalesce((select max(e) from t1 where t1.a not in (coalesce((select (select count(distinct t1.e) from t1) from t1 where c>=t1.c),f),19,a)),t1.a) when t1.c then t1.a else b end-a) from t1 where c>t1.d),b)<= -11) then t1.a when not exists(select 1 from t1 where not (t1.d=e) or t1.f between t1.a and -e and (t1.c)=f and a not in (t1.c,a,c)) then t1.a else t1.a end)/abs( -13))+e-d FROM t1 WHERE NOT (17 not in (13,19,t1.c))} +} {} +do_test randexpr-2.1258 { + db eval {SELECT ~ -coalesce((select c from t1 where (case when b<= -e*t1.f then +coalesce((select case when (select count(*) from t1)=e then t1.f | c else f end from t1 where e>=(select ~case count(*) when -abs(max(11)-count(distinct -t1.d)) then count(distinct e) else max(f) end*count(*) from t1)),13) else 19 end>=t1.e)),case when t1.c=(select ~case count(*) when -abs(max(11)-count(distinct -t1.d)) then count(distinct e) else max(f) end*count(*) from t1)),13) else 19 end>=t1.e)),case when t1.c=(select ~case count(*) when -abs(max(11)-count(distinct -t1.d)) then count(distinct e) else max(f) end*count(*) from t1)),13) else 19 end>=t1.e)),case when t1.ct1.e | case when exists(select 1 from t1 where not ~+11<=coalesce((select max(a) from t1 where ~17*case when a=+(select cast(avg(t1.a*e) AS integer) from t1) then t1.e when c<11 then b else f end+c not between t1.e and -17), -t1.c)) then e+c when not exists(select 1 from t1 where t1.c not between 13 and -f) then 17 else -t1.d end or (f)<=c} +} {300} +do_test randexpr-2.1262 { + db eval {SELECT case t1.b when coalesce((select t1.b from t1 where not exists(select 1 from t1 where +case ( -case f when 13 then (abs(t1.b+f)/abs(c)) else t1.d end) when f*t1.f+t1.d then e else coalesce((select coalesce((select max(b) from t1 where t1.a<=t1.a or t1.d+f<=19 or t1.b in (select (11) from t1 union select (19) from t1)),t1.d) from t1 where not exists(select 1 from t1 where 17=b)),c)+e end between t1.c and b)),d) then c else t1.d end FROM t1 WHERE NOT (b>t1.e | case when exists(select 1 from t1 where not ~+11<=coalesce((select max(a) from t1 where ~17*case when a=+(select cast(avg(t1.a*e) AS integer) from t1) then t1.e when c<11 then b else f end+c not between t1.e and -17), -t1.c)) then e+c when not exists(select 1 from t1 where t1.c not between 13 and -f) then 17 else -t1.d end or (f)<=c)} +} {} +do_test randexpr-2.1263 { + db eval {SELECT case when case when case when exists(select 1 from t1 where exists(select 1 from t1 where t1.a+t1.a | case when t1.b between f and 19 and t1.c=t1.e then t1.e else 19 end | a FROM t1 WHERE t1.b not in ((a),t1.d,b)} +} {} +do_test randexpr-2.1264 { + db eval {SELECT case when case when case when exists(select 1 from t1 where exists(select 1 from t1 where t1.a+t1.a | case when t1.b between f and 19 and t1.c=t1.e then t1.e else 19 end | a FROM t1 WHERE NOT (t1.b not in ((a),t1.d,b))} +} {500} +do_test randexpr-2.1265 { + db eval {SELECT case when case when case when exists(select 1 from t1 where exists(select 1 from t1 where t1.a+t1.a & case when t1.b between f and 19 and t1.c=t1.e then t1.e else 19 end & a FROM t1 WHERE NOT (t1.b not in ((a),t1.d,b))} +} {100} +do_test randexpr-2.1266 { + db eval {SELECT case when exists(select 1 from t1 where a between 13+t1.e and t1.e and (abs((abs(case when not 19 between t1.e and b and not exists(select 1 from t1 where (abs(17)/abs(f-c)) not between (d) and t1.e) then t1.e else 19 end)/abs(11)))/abs(19))=f) or t1.e<= -a then t1.b when exists(select 1 from t1 where t1.d>t1.c) and t1.b<19 then a else 11 end*d FROM t1 WHERE exists(select 1 from t1 where t1.e<>(select count(distinct ((coalesce((select coalesce((select max( -coalesce((select max( -e) from t1 where ((abs(t1.a)/abs(d)) in (select ~~count(*) from t1 union select count(*) from t1) or a in (d,t1.f,d) and -c in (b,e,t1.d))),t1.c)-19 | 11-t1.e) from t1 where exists(select 1 from t1 where a<=e) and f not in (17,t1.b,t1.c) or (t1.a)>=t1.d),e)-t1.c from t1 where bt1.c) and t1.b<19 then a else 11 end*d FROM t1 WHERE NOT (exists(select 1 from t1 where t1.e<>(select count(distinct ((coalesce((select coalesce((select max( -coalesce((select max( -e) from t1 where ((abs(t1.a)/abs(d)) in (select ~~count(*) from t1 union select count(*) from t1) or a in (d,t1.f,d) and -c in (b,e,t1.d))),t1.c)-19 | 11-t1.e) from t1 where exists(select 1 from t1 where a<=e) and f not in (17,t1.b,t1.c) or (t1.a)>=t1.d),e)-t1.c from t1 where b=t1.f) or 11+t1.a between (select -cast(avg( -t1.b | 19) AS integer)+case min(t1.d) when -max(t1.e) then -count(distinct 11) else - -max((t1.c)) end from t1) and f),(e)),13) then t1.a else d end* -t1.f,13)),d)>=e then 17 else -11 end FROM t1 WHERE t1.d*b<=+~t1.c-t1.d+d*~b | e} +} {} +do_test randexpr-2.1272 { + db eval {SELECT case when coalesce((select b from t1 where t1.d not in (t1.c,case when t1.d not in (d,coalesce((select (select count(distinct d) from t1)*e from t1 where not exists(select 1 from t1 where t1.d>=t1.f) or 11+t1.a between (select -cast(avg( -t1.b | 19) AS integer)+case min(t1.d) when -max(t1.e) then -count(distinct 11) else - -max((t1.c)) end from t1) and f),(e)),13) then t1.a else d end* -t1.f,13)),d)>=e then 17 else -11 end FROM t1 WHERE NOT (t1.d*b<=+~t1.c-t1.d+d*~b | e)} +} {-11} +do_test randexpr-2.1273 { + db eval {SELECT case when coalesce((select b from t1 where t1.d not in (t1.c,case when t1.d not in (d,coalesce((select (select count(distinct d) from t1)*e from t1 where not exists(select 1 from t1 where t1.d>=t1.f) or 11+t1.a between (select -cast(avg( -t1.b & 19) AS integer)+case min(t1.d) when -max(t1.e) then -count(distinct 11) else - -max((t1.c)) end from t1) and f),(e)),13) then t1.a else d end* -t1.f,13)),d)>=e then 17 else -11 end FROM t1 WHERE NOT (t1.d*b<=+~t1.c-t1.d+d*~b | e)} +} {-11} +do_test randexpr-2.1274 { + db eval {SELECT t1.a*a+11-case when exists(select 1 from t1 where (t1.d)b) and (19 not in ((t1.a),11,a)) then ~t1.b when t1.c -coalesce((select (select max(e) | min(coalesce((select coalesce((select t1.d from t1 where ab) and (19 not in ((t1.a),11,a)) then ~t1.b when t1.c -coalesce((select (select max(e) | min(coalesce((select coalesce((select t1.d from t1 where ac then 19 else b end- -11 in (select case case count(distinct t1.f) | (max(17)) when (count(*)) then count(distinct b) else count(distinct 19) end when min(t1.f) then (count(distinct t1.f)) else count(*) end-min(13) from t1 union select cast(avg( -t1.c) AS integer) from t1) or f<>t1.a then coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where t1.e>=t1.e)), -t1.a) when exists(select 1 from t1 where 17 between t1.f and t1.d) then t1.c else c end FROM t1 WHERE t1.b=t1.b} +} {200} +do_test randexpr-2.1277 { + db eval {SELECT case when case when case (abs(t1.b)/abs(t1.a)) when e then f else t1.a end>c then 19 else b end- -11 in (select case case count(distinct t1.f) | (max(17)) when (count(*)) then count(distinct b) else count(distinct 19) end when min(t1.f) then (count(distinct t1.f)) else count(*) end-min(13) from t1 union select cast(avg( -t1.c) AS integer) from t1) or f<>t1.a then coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where t1.e>=t1.e)), -t1.a) when exists(select 1 from t1 where 17 between t1.f and t1.d) then t1.c else c end FROM t1 WHERE NOT (t1.b=t1.b)} +} {} +do_test randexpr-2.1278 { + db eval {SELECT case when case when case (abs(t1.b)/abs(t1.a)) when e then f else t1.a end>c then 19 else b end- -11 in (select case case count(distinct t1.f) & (max(17)) when (count(*)) then count(distinct b) else count(distinct 19) end when min(t1.f) then (count(distinct t1.f)) else count(*) end-min(13) from t1 union select cast(avg( -t1.c) AS integer) from t1) or f<>t1.a then coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where t1.e>=t1.e)), -t1.a) when exists(select 1 from t1 where 17 between t1.f and t1.d) then t1.c else c end FROM t1 WHERE t1.b=t1.b} +} {200} +do_test randexpr-2.1279 { + db eval {SELECT (abs(b)/abs(case 19 when case e+13*~t1.c*11 when case when (select ~min(t1.a) from t1)>t1.c then (case when 11 between (a) and (19) then d else d+t1.c end) else f end then (abs((e+t1.d)*e*19-t1.d)/abs(c)) else t1.b end then 11 else ( -t1.b) end*13)) FROM t1 WHERE case when ((select min( -case when b in (d-t1.e,case when e in (select d from t1 union select 17 from t1) then 11 else c end,( -t1.d)) then t1.b when b>e then c else -t1.f end)+ -((min(t1.f)))-+min(f) | ( -(cast(avg(a) AS integer))) from t1)) in (select 11 from t1 union select 19 from t1) then 19 when not exists(select 1 from t1 where -17>t1.f and t1.e in (select t1.e from t1 union select d from t1)) then 11 else d end=t1.d} +} {} +do_test randexpr-2.1280 { + db eval {SELECT (abs(b)/abs(case 19 when case e+13*~t1.c*11 when case when (select ~min(t1.a) from t1)>t1.c then (case when 11 between (a) and (19) then d else d+t1.c end) else f end then (abs((e+t1.d)*e*19-t1.d)/abs(c)) else t1.b end then 11 else ( -t1.b) end*13)) FROM t1 WHERE NOT (case when ((select min( -case when b in (d-t1.e,case when e in (select d from t1 union select 17 from t1) then 11 else c end,( -t1.d)) then t1.b when b>e then c else -t1.f end)+ -((min(t1.f)))-+min(f) | ( -(cast(avg(a) AS integer))) from t1)) in (select 11 from t1 union select 19 from t1) then 19 when not exists(select 1 from t1 where -17>t1.f and t1.e in (select t1.e from t1 union select d from t1)) then 11 else d end=t1.d)} +} {0} +do_test randexpr-2.1281 { + db eval {SELECT coalesce((select max(11) from t1 where not not exists(select 1 from t1 where ((abs(b)/abs(t1.f))-19+f-case ~11 when 19 then c else t1.a end)> -c+t1.a)),(11))- -b FROM t1 WHERE b*case when 19 not in (t1.e,a*+t1.d,(abs(+c)/abs(case 11 when b then +case when (not exists(select 1 from t1 where d<=c or c -c+t1.a)),(11))- -b FROM t1 WHERE NOT (b*case when 19 not in (t1.e,a*+t1.d,(abs(+c)/abs(case 11 when b then +case when (not exists(select 1 from t1 where d<=c or c=11*t1.d} +} {} +do_test randexpr-2.1287 { + db eval {SELECT case coalesce((select t1.e from t1 where 19 in (select 13 from t1 union select 11 | coalesce((select -(t1.c) from t1 where t1.a<=t1.c),case when ~case when t1.e not between 11 and t1.e then d else 19 end+t1.a+f in (select -(count(distinct -c))-max(d)+count(distinct t1.d) from t1 union select cast(avg((b)) AS integer) from t1) then (t1.d) when not (t1.a not in ( -t1.e,t1.b,17) and 11=11*t1.d)} +} {-100} +do_test randexpr-2.1288 { + db eval {SELECT case coalesce((select t1.e from t1 where 19 in (select 13 from t1 union select 11 & coalesce((select -(t1.c) from t1 where t1.a<=t1.c),case when ~case when t1.e not between 11 and t1.e then d else 19 end+t1.a+f in (select -(count(distinct -c))-max(d)+count(distinct t1.d) from t1 union select cast(avg((b)) AS integer) from t1) then (t1.d) when not (t1.a not in ( -t1.e,t1.b,17) and 11=11*t1.d)} +} {-100} +do_test randexpr-2.1289 { + db eval {SELECT (select min(coalesce((select max(case (b | case -e when 11 then +(abs(17)/abs((19))) else 13 end) when t1.f then 17 else a end) from t1 where 17 not between e and -a and 19=13 or t1.f=19 and t1.ct1.b} +} {149900} +do_test randexpr-2.1290 { + db eval {SELECT (select min(coalesce((select max(case (b | case -e when 11 then +(abs(17)/abs((19))) else 13 end) when t1.f then 17 else a end) from t1 where 17 not between e and -a and 19=13 or t1.f=19 and t1.ct1.b)} +} {} +do_test randexpr-2.1291 { + db eval {SELECT (select min(coalesce((select max(case (b & case -e when 11 then +(abs(17)/abs((19))) else 13 end) when t1.f then 17 else a end) from t1 where 17 not between e and -a and 19=13 or t1.f=19 and t1.ct1.b} +} {149900} +do_test randexpr-2.1292 { + db eval {SELECT t1.f*b | coalesce((select max(t1.f) from t1 where (case when (select cast(avg((select (count(distinct e+t1.c)) from t1)) AS integer) from t1)=t1.d then case when not exists(select 1 from t1 where (b)+t1.e+t1.f in (select min(e) from t1 union select case count(distinct t1.c) when count(distinct f) then cast(avg((t1.f)) AS integer) else (cast(avg(13) AS integer)) end from t1)) and not exists(select 1 from t1 where (d=b)) then t1.d when 13 in (f,c,c) then case t1.c when 11 then -a else t1.b end else 13 end else 19 end)<17),19)-t1.a FROM t1 WHERE c>=case when d=case when d=case when d=t1.a),t1.e))/abs(13)) when t1.b then b else -a end=11 then 13 else a end<>t1.f or 19 not in (b,(t1.b), -19) then b else e end<>e) then t1.f else c end | t1.a+d- -f+f FROM t1 WHERE a in (13+17,case when (t1.a>t1.e) then ~t1.c+d*case coalesce((select coalesce((select d from t1 where 11 not between t1.e and coalesce((select t1.b from t1 where -coalesce((select max(t1.b) from t1 where t1.d in (a,11,d) and b=c),c) between b and d),(t1.e))),t1.f) from t1 where t1.e=a),t1.a) when 17 then (t1.f) else t1.d end+b+c when a>=t1.d then t1.a else f end,b)} +} {} +do_test randexpr-2.1296 { + db eval {SELECT +case when b in (13,(t1.f),19+a) and not exists(select 1 from t1 where -case when case when case (abs(coalesce((select b from t1 where t1.b>=t1.a),t1.e))/abs(13)) when t1.b then b else -a end=11 then 13 else a end<>t1.f or 19 not in (b,(t1.b), -19) then b else e end<>e) then t1.f else c end | t1.a+d- -f+f FROM t1 WHERE NOT (a in (13+17,case when (t1.a>t1.e) then ~t1.c+d*case coalesce((select coalesce((select d from t1 where 11 not between t1.e and coalesce((select t1.b from t1 where -coalesce((select max(t1.b) from t1 where t1.d in (a,11,d) and b=c),c) between b and d),(t1.e))),t1.f) from t1 where t1.e=a),t1.a) when 17 then (t1.f) else t1.d end+b+c when a>=t1.d then t1.a else f end,b))} +} {1964} +do_test randexpr-2.1297 { + db eval {SELECT +case when b in (13,(t1.f),19+a) and not exists(select 1 from t1 where -case when case when case (abs(coalesce((select b from t1 where t1.b>=t1.a),t1.e))/abs(13)) when t1.b then b else -a end=11 then 13 else a end<>t1.f or 19 not in (b,(t1.b), -19) then b else e end<>e) then t1.f else c end & t1.a+d- -f+f FROM t1 WHERE NOT (a in (13+17,case when (t1.a>t1.e) then ~t1.c+d*case coalesce((select coalesce((select d from t1 where 11 not between t1.e and coalesce((select t1.b from t1 where -coalesce((select max(t1.b) from t1 where t1.d in (a,11,d) and b=c),c) between b and d),(t1.e))),t1.f) from t1 where t1.e=a),t1.a) when 17 then (t1.f) else t1.d end+b+c when a>=t1.d then t1.a else f end,b))} +} {36} +do_test randexpr-2.1298 { + db eval {SELECT coalesce((select t1.b from t1 where 17+13+t1.b in (e,19,case when 17 in (select case max(b*17-d*t1.b*t1.d)+case max((19)) when ~ -max(t1.f) then +count(*) else cast(avg(13) AS integer) end when count(distinct 11) then min(e) else max(t1.c) end from t1 union select min(d) from t1) then t1.a* -(t1.a) when t1.c=19 then (t1.c) else t1.f end) and t1.f<=13),17) FROM t1 WHERE t1.e<>~t1.b} +} {17} +do_test randexpr-2.1299 { + db eval {SELECT coalesce((select t1.b from t1 where 17+13+t1.b in (e,19,case when 17 in (select case max(b*17-d*t1.b*t1.d)+case max((19)) when ~ -max(t1.f) then +count(*) else cast(avg(13) AS integer) end when count(distinct 11) then min(e) else max(t1.c) end from t1 union select min(d) from t1) then t1.a* -(t1.a) when t1.c=19 then (t1.c) else t1.f end) and t1.f<=13),17) FROM t1 WHERE NOT (t1.e<>~t1.b)} +} {} +do_test randexpr-2.1300 { + db eval {SELECT (abs(coalesce((select -~(abs(t1.d)/abs(a)) from t1 where case when f in (select ~~(+abs( - -count(*)) | cast(avg(d) AS integer)) from t1 union select (min(f)) from t1) then (abs(t1.c)/abs( -13)) | f-13+d*17 when a in (t1.f,t1.c,11) then f else -(f) end*c not in (13,d,d) and 19 in (t1.d,t1.d,b)),13))/abs(17)) FROM t1 WHERE exists(select 1 from t1 where t1.d<>case case when not exists(select 1 from t1 where t1.b(abs(c)/abs(t1.a))) then t1.b else 17 end when +~(e- -coalesce((select e from t1 where not (b) in (select max(t1.b) from t1 union select case max(t1.e)-max(17)-count(distinct (13)) when -cast(avg( -t1.b) AS integer) then count(distinct d) else min(t1.f) end from t1)),c*d))*a*13 | f then (13) else c end)} +} {0} +do_test randexpr-2.1301 { + db eval {SELECT (abs(coalesce((select -~(abs(t1.d)/abs(a)) from t1 where case when f in (select ~~(+abs( - -count(*)) | cast(avg(d) AS integer)) from t1 union select (min(f)) from t1) then (abs(t1.c)/abs( -13)) | f-13+d*17 when a in (t1.f,t1.c,11) then f else -(f) end*c not in (13,d,d) and 19 in (t1.d,t1.d,b)),13))/abs(17)) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.d<>case case when not exists(select 1 from t1 where t1.b(abs(c)/abs(t1.a))) then t1.b else 17 end when +~(e- -coalesce((select e from t1 where not (b) in (select max(t1.b) from t1 union select case max(t1.e)-max(17)-count(distinct (13)) when -cast(avg( -t1.b) AS integer) then count(distinct d) else min(t1.f) end from t1)),c*d))*a*13 | f then (13) else c end))} +} {} +do_test randexpr-2.1302 { + db eval {SELECT (abs(coalesce((select -~(abs(t1.d)/abs(a)) from t1 where case when f in (select ~~(+abs( - -count(*)) & cast(avg(d) AS integer)) from t1 union select (min(f)) from t1) then (abs(t1.c)/abs( -13)) & f-13+d*17 when a in (t1.f,t1.c,11) then f else -(f) end*c not in (13,d,d) and 19 in (t1.d,t1.d,b)),13))/abs(17)) FROM t1 WHERE exists(select 1 from t1 where t1.d<>case case when not exists(select 1 from t1 where t1.b(abs(c)/abs(t1.a))) then t1.b else 17 end when +~(e- -coalesce((select e from t1 where not (b) in (select max(t1.b) from t1 union select case max(t1.e)-max(17)-count(distinct (13)) when -cast(avg( -t1.b) AS integer) then count(distinct d) else min(t1.f) end from t1)),c*d))*a*13 | f then (13) else c end)} +} {0} +do_test randexpr-2.1303 { + db eval {SELECT t1.f*+case when ( -17-a*t1.f | case when (coalesce((select max((case a when +13*19* -b then a else 17 end)) from t1 where (t1.b) not between 13 and t1.a),e))-t1.b=t1.f then f else 17 end-b*a*d)<>11 then f else t1.c end-t1.c*e FROM t1 WHERE (select +cast(avg(case when 13*a in (select 11 from t1 union select b from t1) then e when t1.f in (select ~count(distinct f) | count(*) from t1 union select count(distinct 13*t1.a+coalesce((select max(e) from t1 where ~(abs(t1.e)/abs(a)) not in (t1.a+e-c,t1.e,case when t1.f>t1.c or f>t1.c then 13 when t1.c>c then t1.a else -t1.d end)),f)*19) from t1) then d else d end) AS integer) from t1)=d} +} {210000} +do_test randexpr-2.1304 { + db eval {SELECT t1.f*+case when ( -17-a*t1.f | case when (coalesce((select max((case a when +13*19* -b then a else 17 end)) from t1 where (t1.b) not between 13 and t1.a),e))-t1.b=t1.f then f else 17 end-b*a*d)<>11 then f else t1.c end-t1.c*e FROM t1 WHERE NOT ((select +cast(avg(case when 13*a in (select 11 from t1 union select b from t1) then e when t1.f in (select ~count(distinct f) | count(*) from t1 union select count(distinct 13*t1.a+coalesce((select max(e) from t1 where ~(abs(t1.e)/abs(a)) not in (t1.a+e-c,t1.e,case when t1.f>t1.c or f>t1.c then 13 when t1.c>c then t1.a else -t1.d end)),f)*19) from t1) then d else d end) AS integer) from t1)=d)} +} {} +do_test randexpr-2.1305 { + db eval {SELECT t1.f*+case when ( -17-a*t1.f & case when (coalesce((select max((case a when +13*19* -b then a else 17 end)) from t1 where (t1.b) not between 13 and t1.a),e))-t1.b=t1.f then f else 17 end-b*a*d)<>11 then f else t1.c end-t1.c*e FROM t1 WHERE (select +cast(avg(case when 13*a in (select 11 from t1 union select b from t1) then e when t1.f in (select ~count(distinct f) | count(*) from t1 union select count(distinct 13*t1.a+coalesce((select max(e) from t1 where ~(abs(t1.e)/abs(a)) not in (t1.a+e-c,t1.e,case when t1.f>t1.c or f>t1.c then 13 when t1.c>c then t1.a else -t1.d end)),f)*19) from t1) then d else d end) AS integer) from t1)=d} +} {210000} +do_test randexpr-2.1306 { + db eval {SELECT t1.c+case when t1.a in (select max(coalesce((select coalesce((select coalesce((select max(19+case t1.f when a then e else t1.d end) from t1 where t1.d> -c),b) from t1 where (t1.c=e) and t1.f=17), -a) from t1 where (e not between e and 11)),t1.f)) | cast(avg(t1.a) AS integer)*max(t1.c) from t1 union select count(distinct c)-max(a) | min(t1.b) | (count(*))* -min(f) from t1) then t1.a when exists(select 1 from t1 where not exists(select 1 from t1 where -17>11)) then (13) else 13 end FROM t1 WHERE 19=case when exists(select 1 from t1 where t1.f not between 11 and ~c+b-t1.c*case when t1.f<13+(t1.d) and -t1.f<17 or (b<>b) then ~d else t1.b end) or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e=19)) then c+f*17 else t1.a end and t1.e<13} +} {} +do_test randexpr-2.1307 { + db eval {SELECT t1.c+case when t1.a in (select max(coalesce((select coalesce((select coalesce((select max(19+case t1.f when a then e else t1.d end) from t1 where t1.d> -c),b) from t1 where (t1.c=e) and t1.f=17), -a) from t1 where (e not between e and 11)),t1.f)) | cast(avg(t1.a) AS integer)*max(t1.c) from t1 union select count(distinct c)-max(a) | min(t1.b) | (count(*))* -min(f) from t1) then t1.a when exists(select 1 from t1 where not exists(select 1 from t1 where -17>11)) then (13) else 13 end FROM t1 WHERE NOT (19=case when exists(select 1 from t1 where t1.f not between 11 and ~c+b-t1.c*case when t1.f<13+(t1.d) and -t1.f<17 or (b<>b) then ~d else t1.b end) or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e=19)) then c+f*17 else t1.a end and t1.e<13)} +} {313} +do_test randexpr-2.1308 { + db eval {SELECT t1.c+case when t1.a in (select max(coalesce((select coalesce((select coalesce((select max(19+case t1.f when a then e else t1.d end) from t1 where t1.d> -c),b) from t1 where (t1.c=e) and t1.f=17), -a) from t1 where (e not between e and 11)),t1.f)) & cast(avg(t1.a) AS integer)*max(t1.c) from t1 union select count(distinct c)-max(a) & min(t1.b) & (count(*))* -min(f) from t1) then t1.a when exists(select 1 from t1 where not exists(select 1 from t1 where -17>11)) then (13) else 13 end FROM t1 WHERE NOT (19=case when exists(select 1 from t1 where t1.f not between 11 and ~c+b-t1.c*case when t1.f<13+(t1.d) and -t1.f<17 or (b<>b) then ~d else t1.b end) or exists(select 1 from t1 where not exists(select 1 from t1 where t1.e=19)) then c+f*17 else t1.a end and t1.e<13)} +} {313} +do_test randexpr-2.1309 { + db eval {SELECT 13-case when exists(select 1 from t1 where f+b>t1.f+t1.c) or +17 | -coalesce((select case coalesce((select 13-(select (cast(avg(13) AS integer))-max(t1.b) from t1) from t1 where -c in (select max(17) from t1 union select max(t1.b) from t1)),t1.a) when t1.d then 19 else d end from t1 where d>=11),b) between 13 and 11 and 17<=13 then a | t1.c+t1.f else c end FROM t1 WHERE (case when a not in (t1.d+t1.f,b,t1.b) then case when case f | t1.c when t1.e then e else (t1.a)-d | 13 end<>f then t1.e when (((13) in (select min(t1.a) from t1 union select max( -e) from t1) or t1.f between 13 and -t1.b or (f>=f) or 19t1.f+t1.c) or +17 | -coalesce((select case coalesce((select 13-(select (cast(avg(13) AS integer))-max(t1.b) from t1) from t1 where -c in (select max(17) from t1 union select max(t1.b) from t1)),t1.a) when t1.d then 19 else d end from t1 where d>=11),b) between 13 and 11 and 17<=13 then a | t1.c+t1.f else c end FROM t1 WHERE NOT ((case when a not in (t1.d+t1.f,b,t1.b) then case when case f | t1.c when t1.e then e else (t1.a)-d | 13 end<>f then t1.e when (((13) in (select min(t1.a) from t1 union select max( -e) from t1) or t1.f between 13 and -t1.b or (f>=f) or 19t1.f+t1.c) or +17 & -coalesce((select case coalesce((select 13-(select (cast(avg(13) AS integer))-max(t1.b) from t1) from t1 where -c in (select max(17) from t1 union select max(t1.b) from t1)),t1.a) when t1.d then 19 else d end from t1 where d>=11),b) between 13 and 11 and 17<=13 then a & t1.c+t1.f else c end FROM t1 WHERE NOT ((case when a not in (t1.d+t1.f,b,t1.b) then case when case f | t1.c when t1.e then e else (t1.a)-d | 13 end<>f then t1.e when (((13) in (select min(t1.a) from t1 union select max( -e) from t1) or t1.f between 13 and -t1.b or (f>=f) or 19t1.e or f between b and 13 then t1.c else c end | -b from t1 where 17<=17),t1.e) from t1 where 11=d) and t1.e>17))) then t1.a | (select ~ - -cast(avg( -c) AS integer) from t1) else c end FROM t1 WHERE t1.f>=e and t1.f in (select 17 from t1 union select case when (not exists(select 1 from t1 where case when coalesce((select max(19+t1.c) from t1 where 17>=t1.f),c)+19+t1.c< -d then t1.d when t1.c not in (c,t1.f,e) then 17 else t1.d end11 then d else 13 end from t1)} +} {} +do_test randexpr-2.1313 { + db eval {SELECT a+case when ((~t1.d*13<=e or (coalesce((select coalesce((select case when -t1.e<>t1.e or f between b and 13 then t1.c else c end | -b from t1 where 17<=17),t1.e) from t1 where 11=d) and t1.e>17))) then t1.a | (select ~ - -cast(avg( -c) AS integer) from t1) else c end FROM t1 WHERE NOT (t1.f>=e and t1.f in (select 17 from t1 union select case when (not exists(select 1 from t1 where case when coalesce((select max(19+t1.c) from t1 where 17>=t1.f),c)+19+t1.c< -d then t1.d when t1.c not in (c,t1.f,e) then 17 else t1.d end11 then d else 13 end from t1))} +} {467} +do_test randexpr-2.1314 { + db eval {SELECT a+case when ((~t1.d*13<=e or (coalesce((select coalesce((select case when -t1.e<>t1.e or f between b and 13 then t1.c else c end & -b from t1 where 17<=17),t1.e) from t1 where 11=d) and t1.e>17))) then t1.a & (select ~ - -cast(avg( -c) AS integer) from t1) else c end FROM t1 WHERE NOT (t1.f>=e and t1.f in (select 17 from t1 union select case when (not exists(select 1 from t1 where case when coalesce((select max(19+t1.c) from t1 where 17>=t1.f),c)+19+t1.c< -d then t1.d when t1.c not in (c,t1.f,e) then 17 else t1.d end11 then d else 13 end from t1))} +} {132} +do_test randexpr-2.1315 { + db eval {SELECT case when t1.b not in (17 | t1.e*t1.a,11,(select +case max((select -+case (max(t1.f)) when count(*) then count(distinct d) else -( -(cast(avg(f) AS integer))) end-count(distinct t1.a) from t1)) | count(distinct (t1.e)) when -min(c) then count(*) else -count(distinct e) end | cast(avg(17) AS integer) from t1)) then case when d<=t1.c and (exists(select 1 from t1 where (select count(distinct (e)) from t1)=(abs(17)/abs(d)))) then (abs(t1.f)/abs(t1.c)) when t1.f<>e or t1.c<=d and t1.e<=t1.d then 19 else - -d end-t1.e else (t1.f) end FROM t1 WHERE not t1.b=coalesce((select (abs(c)/abs(11)) from t1 where exists(select 1 from t1 where -coalesce((select max(((abs(coalesce((select max(case (select min((abs(19)/abs(19))+19)*count(*)- -cast(avg(t1.d) AS integer)-max(17)+min( -11) from t1) when e then t1.e else f end) from t1 where t1.d<=t1.f), -f)- -t1.e)/abs(d))-t1.b)) from t1 where c<11),t1.b)*a not in (d,d,f))),c)} +} {-481} +do_test randexpr-2.1316 { + db eval {SELECT case when t1.b not in (17 | t1.e*t1.a,11,(select +case max((select -+case (max(t1.f)) when count(*) then count(distinct d) else -( -(cast(avg(f) AS integer))) end-count(distinct t1.a) from t1)) | count(distinct (t1.e)) when -min(c) then count(*) else -count(distinct e) end | cast(avg(17) AS integer) from t1)) then case when d<=t1.c and (exists(select 1 from t1 where (select count(distinct (e)) from t1)=(abs(17)/abs(d)))) then (abs(t1.f)/abs(t1.c)) when t1.f<>e or t1.c<=d and t1.e<=t1.d then 19 else - -d end-t1.e else (t1.f) end FROM t1 WHERE NOT (not t1.b=coalesce((select (abs(c)/abs(11)) from t1 where exists(select 1 from t1 where -coalesce((select max(((abs(coalesce((select max(case (select min((abs(19)/abs(19))+19)*count(*)- -cast(avg(t1.d) AS integer)-max(17)+min( -11) from t1) when e then t1.e else f end) from t1 where t1.d<=t1.f), -f)- -t1.e)/abs(d))-t1.b)) from t1 where c<11),t1.b)*a not in (d,d,f))),c))} +} {} +do_test randexpr-2.1317 { + db eval {SELECT case when t1.b not in (17 & t1.e*t1.a,11,(select +case max((select -+case (max(t1.f)) when count(*) then count(distinct d) else -( -(cast(avg(f) AS integer))) end-count(distinct t1.a) from t1)) & count(distinct (t1.e)) when -min(c) then count(*) else -count(distinct e) end & cast(avg(17) AS integer) from t1)) then case when d<=t1.c and (exists(select 1 from t1 where (select count(distinct (e)) from t1)=(abs(17)/abs(d)))) then (abs(t1.f)/abs(t1.c)) when t1.f<>e or t1.c<=d and t1.e<=t1.d then 19 else - -d end-t1.e else (t1.f) end FROM t1 WHERE not t1.b=coalesce((select (abs(c)/abs(11)) from t1 where exists(select 1 from t1 where -coalesce((select max(((abs(coalesce((select max(case (select min((abs(19)/abs(19))+19)*count(*)- -cast(avg(t1.d) AS integer)-max(17)+min( -11) from t1) when e then t1.e else f end) from t1 where t1.d<=t1.f), -f)- -t1.e)/abs(d))-t1.b)) from t1 where c<11),t1.b)*a not in (d,d,f))),c)} +} {-481} +do_test randexpr-2.1318 { + db eval {SELECT -t1.a*(select (cast(avg((select count(*)-abs(count(*)*count(*)) from t1)) AS integer)++max(t1.d))*cast(avg(t1.a) AS integer) from t1)+t1.c+t1.c+d-e | 11+t1.b-coalesce((select max(case when exists(select 1 from t1 where t1.a+11=t1.b) then c when t1.a not between t1.f and t1.d or 13<11 then -b else 19 end) from t1 where c>=t1.f),t1.f) FROM t1 WHERE exists(select 1 from t1 where (f=(d)*e))} +} {} +do_test randexpr-2.1319 { + db eval {SELECT -t1.a*(select (cast(avg((select count(*)-abs(count(*)*count(*)) from t1)) AS integer)++max(t1.d))*cast(avg(t1.a) AS integer) from t1)+t1.c+t1.c+d-e | 11+t1.b-coalesce((select max(case when exists(select 1 from t1 where t1.a+11=t1.b) then c when t1.a not between t1.f and t1.d or 13<11 then -b else 19 end) from t1 where c>=t1.f),t1.f) FROM t1 WHERE NOT (exists(select 1 from t1 where (f=(d)*e)))} +} {-257} +do_test randexpr-2.1320 { + db eval {SELECT -t1.a*(select (cast(avg((select count(*)-abs(count(*)*count(*)) from t1)) AS integer)++max(t1.d))*cast(avg(t1.a) AS integer) from t1)+t1.c+t1.c+d-e & 11+t1.b-coalesce((select max(case when exists(select 1 from t1 where t1.a+11=t1.b) then c when t1.a not between t1.f and t1.d or 13<11 then -b else 19 end) from t1 where c>=t1.f),t1.f) FROM t1 WHERE NOT (exists(select 1 from t1 where (f=(d)*e)))} +} {-3999632} +do_test randexpr-2.1321 { + db eval {SELECT -case when t1.a+ -c+coalesce((select d from t1 where (t1.d between a and case when t1.c*t1.b*a between a and 13 then t1.d else 11 end) or not t1.e in (select max(d) from t1 union select max(t1.e)-( -count(distinct t1.e)) from t1) or t1.c>=t1.b or a not in (c,t1.f,t1.d) and b<=t1.c),13)+d-(17) | t1.c*17<=t1.a then t1.c else d end FROM t1 WHERE case a when e then f else case when -t1.c not between e*f | b and t1.d then case (select max((b)) from t1)+coalesce((select max(case when 19 in (b,e,17) then 13 when 11 in (t1.a,t1.a,t1.a) then t1.e else 19 end) from t1 where a<=e and 13 between t1.e and -t1.f),13) when 17 then a else t1.d end when e in (select f from t1 union select -t1.d from t1) then t1.a else c end*d end-13*a not in (19,t1.d,19)} +} {-400} +do_test randexpr-2.1322 { + db eval {SELECT -case when t1.a+ -c+coalesce((select d from t1 where (t1.d between a and case when t1.c*t1.b*a between a and 13 then t1.d else 11 end) or not t1.e in (select max(d) from t1 union select max(t1.e)-( -count(distinct t1.e)) from t1) or t1.c>=t1.b or a not in (c,t1.f,t1.d) and b<=t1.c),13)+d-(17) | t1.c*17<=t1.a then t1.c else d end FROM t1 WHERE NOT (case a when e then f else case when -t1.c not between e*f | b and t1.d then case (select max((b)) from t1)+coalesce((select max(case when 19 in (b,e,17) then 13 when 11 in (t1.a,t1.a,t1.a) then t1.e else 19 end) from t1 where a<=e and 13 between t1.e and -t1.f),13) when 17 then a else t1.d end when e in (select f from t1 union select -t1.d from t1) then t1.a else c end*d end-13*a not in (19,t1.d,19))} +} {} +do_test randexpr-2.1323 { + db eval {SELECT -case when t1.a+ -c+coalesce((select d from t1 where (t1.d between a and case when t1.c*t1.b*a between a and 13 then t1.d else 11 end) or not t1.e in (select max(d) from t1 union select max(t1.e)-( -count(distinct t1.e)) from t1) or t1.c>=t1.b or a not in (c,t1.f,t1.d) and b<=t1.c),13)+d-(17) & t1.c*17<=t1.a then t1.c else d end FROM t1 WHERE case a when e then f else case when -t1.c not between e*f | b and t1.d then case (select max((b)) from t1)+coalesce((select max(case when 19 in (b,e,17) then 13 when 11 in (t1.a,t1.a,t1.a) then t1.e else 19 end) from t1 where a<=e and 13 between t1.e and -t1.f),13) when 17 then a else t1.d end when e in (select f from t1 union select -t1.d from t1) then t1.a else c end*d end-13*a not in (19,t1.d,19)} +} {-400} +do_test randexpr-2.1324 { + db eval {SELECT coalesce((select (abs(t1.a)/abs(13)) from t1 where a<>(select max(b)-abs(+min(f+13*17+~coalesce((select case when 11-t1.c<>19 then t1.c when (c) not between t1.e and d and 11 in (t1.f,13,((c))) then 19 else 11 end from t1 where ( -d)f),11)+c-t1.c)) | - - -+max(19) from t1)-f),b) FROM t1 WHERE t1.b-t1.a+case ((t1.a)) when t1.f then (abs(e*e-(e)*c)/abs(t1.f)) else (abs(t1.a)/abs(t1.b)) end between f and (select case cast(avg(13) AS integer) when (count(*)) then (~abs( -case count(*) when abs((count(*))) then count(distinct 13) else count(*) end)-(count(distinct 11)))-count(distinct 19)*((max(t1.c)))-cast(avg(11) AS integer) else (max(19)) end from t1)} +} {} +do_test randexpr-2.1325 { + db eval {SELECT coalesce((select (abs(t1.a)/abs(13)) from t1 where a<>(select max(b)-abs(+min(f+13*17+~coalesce((select case when 11-t1.c<>19 then t1.c when (c) not between t1.e and d and 11 in (t1.f,13,((c))) then 19 else 11 end from t1 where ( -d)f),11)+c-t1.c)) | - - -+max(19) from t1)-f),b) FROM t1 WHERE NOT (t1.b-t1.a+case ((t1.a)) when t1.f then (abs(e*e-(e)*c)/abs(t1.f)) else (abs(t1.a)/abs(t1.b)) end between f and (select case cast(avg(13) AS integer) when (count(*)) then (~abs( -case count(*) when abs((count(*))) then count(distinct 13) else count(*) end)-(count(distinct 11)))-count(distinct 19)*((max(t1.c)))-cast(avg(11) AS integer) else (max(19)) end from t1))} +} {7} +do_test randexpr-2.1326 { + db eval {SELECT coalesce((select (abs(t1.a)/abs(13)) from t1 where a<>(select max(b)-abs(+min(f+13*17+~coalesce((select case when 11-t1.c<>19 then t1.c when (c) not between t1.e and d and 11 in (t1.f,13,((c))) then 19 else 11 end from t1 where ( -d)f),11)+c-t1.c)) & - - -+max(19) from t1)-f),b) FROM t1 WHERE NOT (t1.b-t1.a+case ((t1.a)) when t1.f then (abs(e*e-(e)*c)/abs(t1.f)) else (abs(t1.a)/abs(t1.b)) end between f and (select case cast(avg(13) AS integer) when (count(*)) then (~abs( -case count(*) when abs((count(*))) then count(distinct 13) else count(*) end)-(count(distinct 11)))-count(distinct 19)*((max(t1.c)))-cast(avg(11) AS integer) else (max(19)) end from t1))} +} {7} +do_test randexpr-2.1327 { + db eval {SELECT t1.d*coalesce((select d from t1 where coalesce((select max(t1.c) from t1 where 11<>13),e)<=(select ~min(13) from t1)*t1.a),c)-coalesce((select (t1.b+17) | (abs( -~17)/abs(t1.d)) from t1 where not exists(select 1 from t1 where case t1.d when case when t1.f not in (t1.e,e,17) then f when t1.c not between 11 and -t1.a then b else 17 end+13 then t1.f else t1.b end+13+t1.b between 17 and 13)),t1.b)+t1.a FROM t1 WHERE (not d in (t1.d,(select max(e) from t1),case d*case when not exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where t1.b<=11-d+(select -max(13-t1.f) from t1)*t1.a),19)>t1.c) and c not between d and 19) then 11+~ -t1.a when t1.e13),e)<=(select ~min(13) from t1)*t1.a),c)-coalesce((select (t1.b+17) | (abs( -~17)/abs(t1.d)) from t1 where not exists(select 1 from t1 where case t1.d when case when t1.f not in (t1.e,e,17) then f when t1.c not between 11 and -t1.a then b else 17 end+13 then t1.f else t1.b end+13+t1.b between 17 and 13)),t1.b)+t1.a FROM t1 WHERE NOT ((not d in (t1.d,(select max(e) from t1),case d*case when not exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where t1.b<=11-d+(select -max(13-t1.f) from t1)*t1.a),19)>t1.c) and c not between d and 19) then 11+~ -t1.a when t1.e13),e)<=(select ~min(13) from t1)*t1.a),c)-coalesce((select (t1.b+17) & (abs( -~17)/abs(t1.d)) from t1 where not exists(select 1 from t1 where case t1.d when case when t1.f not in (t1.e,e,17) then f when t1.c not between 11 and -t1.a then b else 17 end+13 then t1.f else t1.b end+13+t1.b between 17 and 13)),t1.b)+t1.a FROM t1 WHERE NOT ((not d in (t1.d,(select max(e) from t1),case d*case when not exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where t1.b<=11-d+(select -max(13-t1.f) from t1)*t1.a),19)>t1.c) and c not between d and 19) then 11+~ -t1.a when t1.e=f then t1.b else t1.a end*a+19-13 FROM t1 WHERE not exists(select 1 from t1 where exists(select 1 from t1 where (select min(case when 13 not in (19,e-t1.a*17,17- -case 19 when 17+17 then a else t1.d end+f-t1.a*11) then 17 else t1.b end*17+11-b) from t1) between 11 and f or t1.e<>t1.d)) or c not in (t1.c,17,d)} +} {} +do_test randexpr-2.1331 { + db eval {SELECT d+~e-case when exists(select 1 from t1 where -a in (select max( -(select -count(*)-min(e)++cast(avg(case when d in (select +max(c) from t1 union select ((count(distinct (e)))) from t1) then (c) when t1.c=f then t1.b else t1.a end*a+19-13 FROM t1 WHERE NOT (not exists(select 1 from t1 where exists(select 1 from t1 where (select min(case when 13 not in (19,e-t1.a*17,17- -case 19 when 17+17 then a else t1.d end+f-t1.a*11) then 17 else t1.b end*17+11-b) from t1) between 11 and f or t1.e<>t1.d)) or c not in (t1.c,17,d))} +} {-20095} +do_test randexpr-2.1332 { + db eval {SELECT case coalesce((select 11*19*t1.a+(abs(t1.e*(select count(distinct -d) from t1)*case t1.f when +c then d else c end+b)/abs(d)) from t1 where t1.b*13=(e)),13) when (t1.d)*b-19*(e)*e-19+(t1.d) then 13 else b end*a FROM t1 WHERE not d=19 and (abs(t1.c)/abs(17))-ab))) then case when 13 not between t1.e and t1.a then c when t1.c>t1.c then 13 else a end | 19 else (19) end*f*13) from t1 where 17=t1.d and (b<>11)),t1.b)+t1.a | d} +} {20000} +do_test randexpr-2.1333 { + db eval {SELECT case coalesce((select 11*19*t1.a+(abs(t1.e*(select count(distinct -d) from t1)*case t1.f when +c then d else c end+b)/abs(d)) from t1 where t1.b*13=(e)),13) when (t1.d)*b-19*(e)*e-19+(t1.d) then 13 else b end*a FROM t1 WHERE NOT (not d=19 and (abs(t1.c)/abs(17))-ab))) then case when 13 not between t1.e and t1.a then c when t1.c>t1.c then 13 else a end | 19 else (19) end*f*13) from t1 where 17=t1.d and (b<>11)),t1.b)+t1.a | d)} +} {} +do_test randexpr-2.1334 { + db eval {SELECT (c*(abs(coalesce((select t1.b from t1 where (select ~~count(*)+ -count(distinct coalesce((select max(case coalesce((select max(a+(t1.e)) from t1 where -(a)>=t1.e or t1.e<17),c) when t1.d then t1.a else 17 end) from t1 where t1.b not in (e,(c),t1.a)),f)) from t1) between t1.a and b),case when exists(select 1 from t1 where t1.c>=t1.a) then 19 else t1.e end+t1.c))/abs(b))-11 | 19) FROM t1 WHERE not t1.e<=d or not exists(select 1 from t1 where exists(select 1 from t1 where ( -t1.c+d)>t1.a+case when f | -b not between 17 and e then -t1.d else (19) end) or 11 not between 17 and t1.f) or a in (select -cast(avg(13) AS integer)*count(distinct 17)-min(b)- -max(11) | (count(*)) from t1 union select ((((max(b))))) from t1) and t1.e in (13,(13),b)} +} {307} +do_test randexpr-2.1335 { + db eval {SELECT (c*(abs(coalesce((select t1.b from t1 where (select ~~count(*)+ -count(distinct coalesce((select max(case coalesce((select max(a+(t1.e)) from t1 where -(a)>=t1.e or t1.e<17),c) when t1.d then t1.a else 17 end) from t1 where t1.b not in (e,(c),t1.a)),f)) from t1) between t1.a and b),case when exists(select 1 from t1 where t1.c>=t1.a) then 19 else t1.e end+t1.c))/abs(b))-11 | 19) FROM t1 WHERE NOT (not t1.e<=d or not exists(select 1 from t1 where exists(select 1 from t1 where ( -t1.c+d)>t1.a+case when f | -b not between 17 and e then -t1.d else (19) end) or 11 not between 17 and t1.f) or a in (select -cast(avg(13) AS integer)*count(distinct 17)-min(b)- -max(11) | (count(*)) from t1 union select ((((max(b))))) from t1) and t1.e in (13,(13),b))} +} {} +do_test randexpr-2.1336 { + db eval {SELECT (c*(abs(coalesce((select t1.b from t1 where (select ~~count(*)+ -count(distinct coalesce((select max(case coalesce((select max(a+(t1.e)) from t1 where -(a)>=t1.e or t1.e<17),c) when t1.d then t1.a else 17 end) from t1 where t1.b not in (e,(c),t1.a)),f)) from t1) between t1.a and b),case when exists(select 1 from t1 where t1.c>=t1.a) then 19 else t1.e end+t1.c))/abs(b))-11 & 19) FROM t1 WHERE not t1.e<=d or not exists(select 1 from t1 where exists(select 1 from t1 where ( -t1.c+d)>t1.a+case when f | -b not between 17 and e then -t1.d else (19) end) or 11 not between 17 and t1.f) or a in (select -cast(avg(13) AS integer)*count(distinct 17)-min(b)- -max(11) | (count(*)) from t1 union select ((((max(b))))) from t1) and t1.e in (13,(13),b)} +} {1} +do_test randexpr-2.1337 { + db eval {SELECT (select cast(avg(13*13* -coalesce((select b from t1 where case +(abs(17)/abs(d))*e+c-case -case when not a in (d,13,t1.b) then t1.b when t1.f<=b then e else -f end-17 when t1.e then t1.d else a end when c then b else f end<>e or ee or et1.d) or (t1.f in (select 11 from t1 union select t1.c from t1) or c>t1.e and b not in (t1.b, -t1.e,t1.a)) or c<>b),(a))-19*t1.c-c*t1.d and exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (t1.b,e,19) or not exists(select 1 from t1 where t1.c=19)))} +} {} +do_test randexpr-2.1340 { + db eval {SELECT b | t1.d- -coalesce((select case coalesce((select max((select (abs(cast(avg(coalesce((select max(coalesce((select 17 from t1 where -11=t1.e),a)) from t1 where not exists(select 1 from t1 where 13 between t1.f and 13)),11)-c) AS integer)))+min( -b) from t1)+b) from t1 where t1.d not in (b*19,t1.a,a)),t1.e) when t1.e then t1.b else t1.d end from t1 where (e not in (b,t1.a,(a)))),13) FROM t1 WHERE NOT (t1.c=coalesce((select t1.d*(select count(*) from t1) from t1 where ((abs(e)/abs(case 13 when t1.d then t1.e else 11 end+13))>t1.d) or (t1.f in (select 11 from t1 union select t1.c from t1) or c>t1.e and b not in (t1.b, -t1.e,t1.a)) or c<>b),(a))-19*t1.c-c*t1.d and exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (t1.b,e,19) or not exists(select 1 from t1 where t1.c=19))))} +} {1000} +do_test randexpr-2.1341 { + db eval {SELECT b & t1.d- -coalesce((select case coalesce((select max((select (abs(cast(avg(coalesce((select max(coalesce((select 17 from t1 where -11=t1.e),a)) from t1 where not exists(select 1 from t1 where 13 between t1.f and 13)),11)-c) AS integer)))+min( -b) from t1)+b) from t1 where t1.d not in (b*19,t1.a,a)),t1.e) when t1.e then t1.b else t1.d end from t1 where (e not in (b,t1.a,(a)))),13) FROM t1 WHERE NOT (t1.c=coalesce((select t1.d*(select count(*) from t1) from t1 where ((abs(e)/abs(case 13 when t1.d then t1.e else 11 end+13))>t1.d) or (t1.f in (select 11 from t1 union select t1.c from t1) or c>t1.e and b not in (t1.b, -t1.e,t1.a)) or c<>b),(a))-19*t1.c-c*t1.d and exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (t1.b,e,19) or not exists(select 1 from t1 where t1.c=19))))} +} {0} +do_test randexpr-2.1342 { + db eval {SELECT coalesce((select 19 from t1 where not exists(select 1 from t1 where 11+d between b and 19-case when t1.e>e*f+case when 13 in (select count(*) from t1 union select ~min(a*t1.d)+count(*) from t1) then c when (select min(d) from t1) in (select cast(avg(17) AS integer) from t1 union select min(t1.a) from t1) and 11<>(f) then -f else 19 end | c then 13 else 19 end*b*t1.b)),a) FROM t1 WHERE (coalesce((select d from t1 where coalesce((select ~(coalesce((select max(t1.a) from t1 where 13+t1.c-c*coalesce((select t1.a from t1 where ( -t1.d not between a and d)),t1.e)+t1.e- - -11-t1.d*11<17),d)) from t1 where f between t1.a and t1.a),t1.c)<>e),t1.d)*(19)-t1.e- -17-a>=d or t1.c between f and a)} +} {19} +do_test randexpr-2.1343 { + db eval {SELECT coalesce((select 19 from t1 where not exists(select 1 from t1 where 11+d between b and 19-case when t1.e>e*f+case when 13 in (select count(*) from t1 union select ~min(a*t1.d)+count(*) from t1) then c when (select min(d) from t1) in (select cast(avg(17) AS integer) from t1 union select min(t1.a) from t1) and 11<>(f) then -f else 19 end | c then 13 else 19 end*b*t1.b)),a) FROM t1 WHERE NOT ((coalesce((select d from t1 where coalesce((select ~(coalesce((select max(t1.a) from t1 where 13+t1.c-c*coalesce((select t1.a from t1 where ( -t1.d not between a and d)),t1.e)+t1.e- - -11-t1.d*11<17),d)) from t1 where f between t1.a and t1.a),t1.c)<>e),t1.d)*(19)-t1.e- -17-a>=d or t1.c between f and a))} +} {} +do_test randexpr-2.1344 { + db eval {SELECT coalesce((select 19 from t1 where not exists(select 1 from t1 where 11+d between b and 19-case when t1.e>e*f+case when 13 in (select count(*) from t1 union select ~min(a*t1.d)+count(*) from t1) then c when (select min(d) from t1) in (select cast(avg(17) AS integer) from t1 union select min(t1.a) from t1) and 11<>(f) then -f else 19 end & c then 13 else 19 end*b*t1.b)),a) FROM t1 WHERE (coalesce((select d from t1 where coalesce((select ~(coalesce((select max(t1.a) from t1 where 13+t1.c-c*coalesce((select t1.a from t1 where ( -t1.d not between a and d)),t1.e)+t1.e- - -11-t1.d*11<17),d)) from t1 where f between t1.a and t1.a),t1.c)<>e),t1.d)*(19)-t1.e- -17-a>=d or t1.c between f and a)} +} {19} +do_test randexpr-2.1345 { + db eval {SELECT coalesce((select +case case when f>t1.d then a+t1.b-f when coalesce((select max(t1.b-case f when 13*t1.a then 11 else 11 end*c) from t1 where f in (select min(t1.d) from t1 union select +count(distinct f) from t1)),17) not in (e,b,t1.a) then f else t1.b end-e*t1.a when -11 then 19 else (t1.d) end from t1 where 17 not between -13 and t1.e),19) FROM t1 WHERE not t1.b*coalesce((select max(17 | coalesce((select coalesce((select +coalesce((select max(case when (b not in (a,t1.b, -t1.a)) and t1.f=t1.b then t1.c-t1.f when 11>d then 17 else 11 end+f) from t1 where t1.e<>b), -t1.e) from t1 where t1.f in (select min(b) from t1 union select max(19)+count(distinct e)+(count(distinct e)) | - -count(distinct 17)*count(*) from t1)),13) from t1 where t1.f>=t1.f),t1.f)) from t1 where t1.f>=b),c)t1.d then a+t1.b-f when coalesce((select max(t1.b-case f when 13*t1.a then 11 else 11 end*c) from t1 where f in (select min(t1.d) from t1 union select +count(distinct f) from t1)),17) not in (e,b,t1.a) then f else t1.b end-e*t1.a when -11 then 19 else (t1.d) end from t1 where 17 not between -13 and t1.e),19) FROM t1 WHERE NOT (not t1.b*coalesce((select max(17 | coalesce((select coalesce((select +coalesce((select max(case when (b not in (a,t1.b, -t1.a)) and t1.f=t1.b then t1.c-t1.f when 11>d then 17 else 11 end+f) from t1 where t1.e<>b), -t1.e) from t1 where t1.f in (select min(b) from t1 union select max(19)+count(distinct e)+(count(distinct e)) | - -count(distinct 17)*count(*) from t1)),13) from t1 where t1.f>=t1.f),t1.f)) from t1 where t1.f>=b),c)11 then t1.a when 17 not between d and 13 or t1.f in (b,b,t1.a) then t1.d else c end)) then -t1.e else b end*t1.a FROM t1 WHERE a in ((abs(t1.c*+(abs(17-(abs(19)/abs(b-coalesce((select max(t1.c) from t1 where c>t1.f),t1.e))))/abs(t1.e))+t1.b | t1.d*t1.a)/abs(coalesce((select case when t1.f in (case when -e<=t1.a then f else 17 end,f,b) then b else t1.c end from t1 where not a in (t1.d,t1.a,c)),t1.f))),b,t1.b) and e in (select f from t1 union select e from t1)} +} {} +do_test randexpr-2.1348 { + db eval {SELECT -11* -t1.b-t1.b+ -case when t1.e-(select max((select abs((cast(avg(t1.f) AS integer)+++ -cast(avg(a | a) AS integer))) from t1))+(( -max( -b))) from t1)<=(abs(11)/abs((select count(distinct t1.e) from t1)-b*case when t1.a<>11 then t1.a when 17 not between d and 13 or t1.f in (b,b,t1.a) then t1.d else c end)) then -t1.e else b end*t1.a FROM t1 WHERE NOT (a in ((abs(t1.c*+(abs(17-(abs(19)/abs(b-coalesce((select max(t1.c) from t1 where c>t1.f),t1.e))))/abs(t1.e))+t1.b | t1.d*t1.a)/abs(coalesce((select case when t1.f in (case when -e<=t1.a then f else 17 end,f,b) then b else t1.c end from t1 where not a in (t1.d,t1.a,c)),t1.f))),b,t1.b) and e in (select f from t1 union select e from t1))} +} {52000} +do_test randexpr-2.1349 { + db eval {SELECT -11* -t1.b-t1.b+ -case when t1.e-(select max((select abs((cast(avg(t1.f) AS integer)+++ -cast(avg(a & a) AS integer))) from t1))+(( -max( -b))) from t1)<=(abs(11)/abs((select count(distinct t1.e) from t1)-b*case when t1.a<>11 then t1.a when 17 not between d and 13 or t1.f in (b,b,t1.a) then t1.d else c end)) then -t1.e else b end*t1.a FROM t1 WHERE NOT (a in ((abs(t1.c*+(abs(17-(abs(19)/abs(b-coalesce((select max(t1.c) from t1 where c>t1.f),t1.e))))/abs(t1.e))+t1.b | t1.d*t1.a)/abs(coalesce((select case when t1.f in (case when -e<=t1.a then f else 17 end,f,b) then b else t1.c end from t1 where not a in (t1.d,t1.a,c)),t1.f))),b,t1.b) and e in (select f from t1 union select e from t1))} +} {52000} +do_test randexpr-2.1350 { + db eval {SELECT case when ((select count(*) | min(case when (a*e in (select -+ -min(a) | cast(avg(11) AS integer) from t1 union select count(distinct t1.e) from t1) and exists(select 1 from t1 where not 13 in (select count(distinct 11) from t1 union select (max(19)) from t1) or (t1.f) between t1.e and (t1.e)) or t1.a<=f) or t1.et1.c then t1.e else t1.b end FROM t1 WHERE (c not between +(select + -~~max(coalesce((select case when t1.b<=t1.d*a then t1.c else t1.e end*t1.e from t1 where t1.d>=t1.b and c=(f) or t1.e>t1.d and bt1.c then t1.e else t1.b end FROM t1 WHERE NOT ((c not between +(select + -~~max(coalesce((select case when t1.b<=t1.d*a then t1.c else t1.e end*t1.e from t1 where t1.d>=t1.b and c=(f) or t1.e>t1.d and bt1.c then t1.e else t1.b end FROM t1 WHERE NOT ((c not between +(select + -~~max(coalesce((select case when t1.b<=t1.d*a then t1.c else t1.e end*t1.e from t1 where t1.d>=t1.b and c=(f) or t1.e>t1.d and bt1.c),t1.d)) from t1 where b not in (t1.e, -13,f)),f) FROM t1 WHERE d*a | 19<> -t1.d} +} {-500} +do_test randexpr-2.1354 { + db eval {SELECT coalesce((select max(coalesce((select max((abs((11))/abs(13))-e) from t1 where 11 not in (c,f,(select count(distinct -17+t1.a) from t1)) or (d*coalesce((select b | coalesce((select max(17) from t1 where e in (d,t1.c,t1.c)),+b) from t1 where d in (d-13,t1.c,f)),13))<>t1.c),t1.d)) from t1 where b not in (t1.e, -13,f)),f) FROM t1 WHERE NOT (d*a | 19<> -t1.d)} +} {} +do_test randexpr-2.1355 { + db eval {SELECT coalesce((select max(coalesce((select max((abs((11))/abs(13))-e) from t1 where 11 not in (c,f,(select count(distinct -17+t1.a) from t1)) or (d*coalesce((select b & coalesce((select max(17) from t1 where e in (d,t1.c,t1.c)),+b) from t1 where d in (d-13,t1.c,f)),13))<>t1.c),t1.d)) from t1 where b not in (t1.e, -13,f)),f) FROM t1 WHERE d*a | 19<> -t1.d} +} {-500} +do_test randexpr-2.1356 { + db eval {SELECT coalesce((select t1.f from t1 where case when 19<>(c*case when 19 | -t1.e in (select ~+(max(c)) from t1 union select min(19) from t1) then -t1.f else 13 end-f) then ( -17) else -19 end-b in (t1.b,t1.f,b) or c in (select ~case max( -t1.d) | count(*)*cast(avg(b) AS integer) when count(distinct t1.f) then cast(avg(t1.f) AS integer) else cast(avg(f) AS integer) end | (cast(avg( -t1.e) AS integer)) from t1 union select max(c) from t1) and t1.f in (select max(17) from t1 union select max(11) from t1)),e) FROM t1 WHERE not 13 in (select (t1.b)*(coalesce((select (abs(t1.f)/abs( -t1.f-d))-coalesce((select 19 from t1 where not exists(select 1 from t1 where (select count(distinct t1.f+19-(abs(e)/abs(e))) from t1)- -e<>d)),t1.e)* -t1.a-t1.a-(t1.f)*t1.e*t1.d-t1.b from t1 where t1.e between t1.a and b),11)) from t1 union select d from t1)} +} {500} +do_test randexpr-2.1357 { + db eval {SELECT coalesce((select t1.f from t1 where case when 19<>(c*case when 19 | -t1.e in (select ~+(max(c)) from t1 union select min(19) from t1) then -t1.f else 13 end-f) then ( -17) else -19 end-b in (t1.b,t1.f,b) or c in (select ~case max( -t1.d) | count(*)*cast(avg(b) AS integer) when count(distinct t1.f) then cast(avg(t1.f) AS integer) else cast(avg(f) AS integer) end | (cast(avg( -t1.e) AS integer)) from t1 union select max(c) from t1) and t1.f in (select max(17) from t1 union select max(11) from t1)),e) FROM t1 WHERE NOT (not 13 in (select (t1.b)*(coalesce((select (abs(t1.f)/abs( -t1.f-d))-coalesce((select 19 from t1 where not exists(select 1 from t1 where (select count(distinct t1.f+19-(abs(e)/abs(e))) from t1)- -e<>d)),t1.e)* -t1.a-t1.a-(t1.f)*t1.e*t1.d-t1.b from t1 where t1.e between t1.a and b),11)) from t1 union select d from t1))} +} {} +do_test randexpr-2.1358 { + db eval {SELECT coalesce((select t1.f from t1 where case when 19<>(c*case when 19 & -t1.e in (select ~+(max(c)) from t1 union select min(19) from t1) then -t1.f else 13 end-f) then ( -17) else -19 end-b in (t1.b,t1.f,b) or c in (select ~case max( -t1.d) & count(*)*cast(avg(b) AS integer) when count(distinct t1.f) then cast(avg(t1.f) AS integer) else cast(avg(f) AS integer) end & (cast(avg( -t1.e) AS integer)) from t1 union select max(c) from t1) and t1.f in (select max(17) from t1 union select max(11) from t1)),e) FROM t1 WHERE not 13 in (select (t1.b)*(coalesce((select (abs(t1.f)/abs( -t1.f-d))-coalesce((select 19 from t1 where not exists(select 1 from t1 where (select count(distinct t1.f+19-(abs(e)/abs(e))) from t1)- -e<>d)),t1.e)* -t1.a-t1.a-(t1.f)*t1.e*t1.d-t1.b from t1 where t1.e between t1.a and b),11)) from t1 union select d from t1)} +} {500} +do_test randexpr-2.1359 { + db eval {SELECT ~ -case when t1.d in (17,t1.e,case t1.b*c when -c+f-11 | coalesce((select 11 from t1 where (select (min(13)-max(t1.c))+count(*) from t1)+13<=(( -(t1.f)))),b)+17 then t1.d else b end) then c when c between 13 and f and b>17 then f else t1.a end-t1.f FROM t1 WHERE t1.e>= -f} +} {-1} +do_test randexpr-2.1360 { + db eval {SELECT ~ -case when t1.d in (17,t1.e,case t1.b*c when -c+f-11 | coalesce((select 11 from t1 where (select (min(13)-max(t1.c))+count(*) from t1)+13<=(( -(t1.f)))),b)+17 then t1.d else b end) then c when c between 13 and f and b>17 then f else t1.a end-t1.f FROM t1 WHERE NOT (t1.e>= -f)} +} {} +do_test randexpr-2.1361 { + db eval {SELECT ~ -case when t1.d in (17,t1.e,case t1.b*c when -c+f-11 & coalesce((select 11 from t1 where (select (min(13)-max(t1.c))+count(*) from t1)+13<=(( -(t1.f)))),b)+17 then t1.d else b end) then c when c between 13 and f and b>17 then f else t1.a end-t1.f FROM t1 WHERE t1.e>= -f} +} {-1} +do_test randexpr-2.1362 { + db eval {SELECT ((abs(13)/abs( -b | coalesce((select 17 | t1.e from t1 where (d in (select coalesce((select 17 | (a) | c*case when case when t1.c in (select max(13) | cast(avg(t1.b) AS integer) from t1 union select count(*) from t1) then t1.c when 13>=17 then (11) else t1.e end>t1.d and t1.b>=t1.f then 13 when 11 not in (t1.d, -f,13) then f else 11 end from t1 where b<>11),d) from t1 union select t1.e from t1) or b not in (t1.e,b,e))),t1.e)))) FROM t1 WHERE 11<=coalesce((select max(t1.d) from t1 where coalesce((select ~d+t1.d-case when c not in (t1.b-f,19+~coalesce((select t1.a from t1 where t1.f<=b),case when not (e not between f and t1.e) then (t1.e)-d else b end), -t1.d) then 17 when t1.d not between 13 and t1.d then d else (c) end from t1 where c>t1.a),t1.b)=17 then (11) else t1.e end>t1.d and t1.b>=t1.f then 13 when 11 not in (t1.d, -f,13) then f else 11 end from t1 where b<>11),d) from t1 union select t1.e from t1) or b not in (t1.e,b,e))),t1.e)))) FROM t1 WHERE NOT (11<=coalesce((select max(t1.d) from t1 where coalesce((select ~d+t1.d-case when c not in (t1.b-f,19+~coalesce((select t1.a from t1 where t1.f<=b),case when not (e not between f and t1.e) then (t1.e)-d else b end), -t1.d) then 17 when t1.d not between 13 and t1.d then d else (c) end from t1 where c>t1.a),t1.b)=17 then (11) else t1.e end>t1.d and t1.b>=t1.f then 13 when 11 not in (t1.d, -f,13) then f else 11 end from t1 where b<>11),d) from t1 union select t1.e from t1) or b not in (t1.e,b,e))),t1.e)))) FROM t1 WHERE 11<=coalesce((select max(t1.d) from t1 where coalesce((select ~d+t1.d-case when c not in (t1.b-f,19+~coalesce((select t1.a from t1 where t1.f<=b),case when not (e not between f and t1.e) then (t1.e)-d else b end), -t1.d) then 17 when t1.d not between 13 and t1.d then d else (c) end from t1 where c>t1.a),t1.b)t1.d and a between d and d) then c else d end when exists(select 1 from t1 where (11)>19) or a in (t1.b,(t1.c),(a)) and - -11<>13 and t1.b not between -b and d then 19 else a end FROM t1 WHERE 19 | t1.d not between (select ~case case count(distinct t1.c) when (count(*)) then ~~~count(*) else -count(*)- -max(coalesce((select max(19) from t1 where (abs(t1.b-b)/abs(d))+11=t1.a),11))*max(t1.e) | count(*)-abs(max((c)))*max(t1.d) end when -count(*) then cast(avg(f) AS integer) else -(max(c)) end from t1) and t1.c} +} {400} +do_test randexpr-2.1366 { + db eval {SELECT case when (c between 11 and t1.e*t1.a | c) then case when (case when (b=(select max((t1.c))-min(t1.d) from t1)*b) then t1.c else 17 end-e>t1.d and a between d and d) then c else d end when exists(select 1 from t1 where (11)>19) or a in (t1.b,(t1.c),(a)) and - -11<>13 and t1.b not between -b and d then 19 else a end FROM t1 WHERE NOT (19 | t1.d not between (select ~case case count(distinct t1.c) when (count(*)) then ~~~count(*) else -count(*)- -max(coalesce((select max(19) from t1 where (abs(t1.b-b)/abs(d))+11=t1.a),11))*max(t1.e) | count(*)-abs(max((c)))*max(t1.d) end when -count(*) then cast(avg(f) AS integer) else -(max(c)) end from t1) and t1.c)} +} {} +do_test randexpr-2.1367 { + db eval {SELECT case when (c between 11 and t1.e*t1.a & c) then case when (case when (b=(select max((t1.c))-min(t1.d) from t1)*b) then t1.c else 17 end-e>t1.d and a between d and d) then c else d end when exists(select 1 from t1 where (11)>19) or a in (t1.b,(t1.c),(a)) and - -11<>13 and t1.b not between -b and d then 19 else a end FROM t1 WHERE 19 | t1.d not between (select ~case case count(distinct t1.c) when (count(*)) then ~~~count(*) else -count(*)- -max(coalesce((select max(19) from t1 where (abs(t1.b-b)/abs(d))+11=t1.a),11))*max(t1.e) | count(*)-abs(max((c)))*max(t1.d) end when -count(*) then cast(avg(f) AS integer) else -(max(c)) end from t1) and t1.c} +} {100} +do_test randexpr-2.1368 { + db eval {SELECT case when not exists(select 1 from t1 where t1.c not in (t1.d,17,t1.c | coalesce((select t1.f from t1 where t1.c*t1.c-t1.e not in (t1.e*(case when (f) not between c and +f then (a) else t1.e end)+17,13, -((t1.a))) and f not between f and t1.d), -t1.e))) then (abs(e)/abs(a)) when 17<17 or 13<>a then f else (f) end FROM t1 WHERE t1.f in (e,(19),case when not exists(select 1 from t1 where coalesce((select max( -(abs(case -t1.d when t1.d*13+coalesce((select a from t1 where d>19),t1.c) then f else b end)/abs(t1.b))) from t1 where f in (t1.a,t1.d,(c))),t1.d)+c+17a then f else (f) end FROM t1 WHERE NOT (t1.f in (e,(19),case when not exists(select 1 from t1 where coalesce((select max( -(abs(case -t1.d when t1.d*13+coalesce((select a from t1 where d>19),t1.c) then f else b end)/abs(t1.b))) from t1 where f in (t1.a,t1.d,(c))),t1.d)+c+17a then f else (f) end FROM t1 WHERE NOT (t1.f in (e,(19),case when not exists(select 1 from t1 where coalesce((select max( -(abs(case -t1.d when t1.d*13+coalesce((select a from t1 where d>19),t1.c) then f else b end)/abs(t1.b))) from t1 where f in (t1.a,t1.d,(c))),t1.d)+c+17coalesce((select max(coalesce((select max(case when case case when 19 in (select case min(11) when - -cast(avg(c) AS integer) then count(*) else count(*) end-cast(avg(19) AS integer) | cast(avg(17) AS integer) from t1 union select min(t1.d) from t1) then t1.b*t1.a else -t1.a end when t1.f then e else t1.d endd),t1.d)) from t1 where t1.c<>e and -17<=a),t1.d))} +} {413} +do_test randexpr-2.1372 { + db eval {SELECT case +b when coalesce((select max(b) from t1 where exists(select 1 from t1 where (((+~13) in (select case cast(avg(t1.e+(11)+t1.b*e) AS integer) when max(((t1.e))) then min(b)-case -cast(avg(17) AS integer) when min(e) then cast(avg(t1.c) AS integer) else (max(d)) end-count(distinct t1.f) else count(distinct d) end+count(*) from t1 union select max(d) from t1))))),(abs(~d)/abs(11))) then -e else - -13 end+d | t1.d FROM t1 WHERE NOT (((a)>coalesce((select max(coalesce((select max(case when case case when 19 in (select case min(11) when - -cast(avg(c) AS integer) then count(*) else count(*) end-cast(avg(19) AS integer) | cast(avg(17) AS integer) from t1 union select min(t1.d) from t1) then t1.b*t1.a else -t1.a end when t1.f then e else t1.d endd),t1.d)) from t1 where t1.c<>e and -17<=a),t1.d)))} +} {} +do_test randexpr-2.1373 { + db eval {SELECT case +b when coalesce((select max(b) from t1 where exists(select 1 from t1 where (((+~13) in (select case cast(avg(t1.e+(11)+t1.b*e) AS integer) when max(((t1.e))) then min(b)-case -cast(avg(17) AS integer) when min(e) then cast(avg(t1.c) AS integer) else (max(d)) end-count(distinct t1.f) else count(distinct d) end+count(*) from t1 union select max(d) from t1))))),(abs(~d)/abs(11))) then -e else - -13 end+d & t1.d FROM t1 WHERE ((a)>coalesce((select max(coalesce((select max(case when case case when 19 in (select case min(11) when - -cast(avg(c) AS integer) then count(*) else count(*) end-cast(avg(19) AS integer) | cast(avg(17) AS integer) from t1 union select min(t1.d) from t1) then t1.b*t1.a else -t1.a end when t1.f then e else t1.d endd),t1.d)) from t1 where t1.c<>e and -17<=a),t1.d))} +} {400} +do_test randexpr-2.1374 { + db eval {SELECT +c+case when (~t1.e in (+(select case cast(avg(17) AS integer)+min(19)+count(*) when -max(c) then count(distinct t1.c) else - - -(max(13)) end*count(distinct ( -17)) from t1)-case when d+case when f<>d or t1.d<=t1.e then t1.a else -11 end in (select cast(avg(t1.e) AS integer) from t1 union select cast(avg(b) AS integer) from t1) then 19 when ((t1.c) between e and a and -13 not in (d,f,e)) then t1.e else d end,a,t1.b)) then case when t1.b<19 then 13 else 19 end else t1.c end FROM t1 WHERE not exists(select 1 from t1 where 19>t1.f+coalesce((select 13 from t1 where t1.d in (coalesce((select max(e) from t1 where c=t1.c),t1.d) between t1.b and c))) then -f+(t1.b)-t1.e-t1.c+t1.c when c in (select -( -f) from t1 union select 13 from t1) then t1.e else t1.a end),t1.b,a)),11))} +} {600} +do_test randexpr-2.1375 { + db eval {SELECT +c+case when (~t1.e in (+(select case cast(avg(17) AS integer)+min(19)+count(*) when -max(c) then count(distinct t1.c) else - - -(max(13)) end*count(distinct ( -17)) from t1)-case when d+case when f<>d or t1.d<=t1.e then t1.a else -11 end in (select cast(avg(t1.e) AS integer) from t1 union select cast(avg(b) AS integer) from t1) then 19 when ((t1.c) between e and a and -13 not in (d,f,e)) then t1.e else d end,a,t1.b)) then case when t1.b<19 then 13 else 19 end else t1.c end FROM t1 WHERE NOT (not exists(select 1 from t1 where 19>t1.f+coalesce((select 13 from t1 where t1.d in (coalesce((select max(e) from t1 where c=t1.c),t1.d) between t1.b and c))) then -f+(t1.b)-t1.e-t1.c+t1.c when c in (select -( -f) from t1 union select 13 from t1) then t1.e else t1.a end),t1.b,a)),11)))} +} {} +do_test randexpr-2.1376 { + db eval {SELECT (17-t1.e-17*t1.d+coalesce((select -(abs(t1.a)/abs(t1.e))-t1.e*13*c*c-c from t1 where coalesce((select max(t1.a) from t1 where +case when t1.a not in (e,(t1.b),t1.f) then 11 when t1.b not between t1.c and t1.c then d else b end not in (13,t1.c,b)),f) between f and 11),d)-t1.d)-f+13 FROM t1 WHERE t1.f<>case when 11 in (coalesce((select e from t1 where not exists(select 1 from t1 where not case when t1.c between 11 and f then +t1.d else (((abs(coalesce((select -t1.c from t1 where (c in (b,b,t1.e))),13) | t1.e*t1.d)/abs(c))-t1.f)) end-t1.d=c)),t1.e),d,t1.e) or t1.bcase when 11 in (coalesce((select e from t1 where not exists(select 1 from t1 where not case when t1.c between 11 and f then +t1.d else (((abs(coalesce((select -t1.c from t1 where (c in (b,b,t1.e))),13) | t1.e*t1.d)/abs(c))-t1.f)) end-t1.d=c)),t1.e),d,t1.e) or t1.b=e or t1.a not in (t1.c,e,t1.f)),t1.b)+19<=t1.a) then ((b)) when d>=b or d not between 19 and t1.e then t1.c else t1.b end-t1.a*f) from t1 where 13 between t1.f and t1.b or e not in (t1.e,b,19)),t1.a) then d else t1.a end FROM t1 WHERE -b>=(select max(19) from t1)} +} {} +do_test randexpr-2.1379 { + db eval {SELECT case +c when 19*t1.b*coalesce((select t1.b-(19* -case when (coalesce((select t1.a from t1 where c>=e or t1.a not in (t1.c,e,t1.f)),t1.b)+19<=t1.a) then ((b)) when d>=b or d not between 19 and t1.e then t1.c else t1.b end-t1.a*f) from t1 where 13 between t1.f and t1.b or e not in (t1.e,b,19)),t1.a) then d else t1.a end FROM t1 WHERE NOT ( -b>=(select max(19) from t1))} +} {100} +do_test randexpr-2.1380 { + db eval {SELECT d+(abs(case t1.e when e*(abs(17)/abs(b)) then f else case when not not 13=c then coalesce((select t1.b from t1 where ((e-11 in (select 19 from t1 union select 17 from t1))) or f>=f),d) else case when c in (t1.a,t1.c,d) then t1.e when -11 in (t1.a,e,t1.d) then t1.a else 19 end end-t1.e end*19)/abs(t1.c))-t1.e+d*t1.f FROM t1 WHERE t1.d+t1.c*coalesce((select e from t1 where coalesce((select max(t1.f) from t1 where not f in (select abs(case min(case when a not between a and f then 17 when e>17 then t1.d else 13 end) when abs(case cast(avg(t1.a) AS integer) when -min(t1.b) then count(distinct 17) else (count(distinct t1.a)) end)-count(distinct -b) then count(distinct d) else max(t1.f) end)+count(*)*max(e) from t1 union select (cast(avg(t1.c) AS integer)) from t1)),b*case 19 when t1.a then 11 else e end)<=f),17)=c} +} {} +do_test randexpr-2.1381 { + db eval {SELECT d+(abs(case t1.e when e*(abs(17)/abs(b)) then f else case when not not 13=c then coalesce((select t1.b from t1 where ((e-11 in (select 19 from t1 union select 17 from t1))) or f>=f),d) else case when c in (t1.a,t1.c,d) then t1.e when -11 in (t1.a,e,t1.d) then t1.a else 19 end end-t1.e end*19)/abs(t1.c))-t1.e+d*t1.f FROM t1 WHERE NOT (t1.d+t1.c*coalesce((select e from t1 where coalesce((select max(t1.f) from t1 where not f in (select abs(case min(case when a not between a and f then 17 when e>17 then t1.d else 13 end) when abs(case cast(avg(t1.a) AS integer) when -min(t1.b) then count(distinct 17) else (count(distinct t1.a)) end)-count(distinct -b) then count(distinct d) else max(t1.f) end)+count(*)*max(e) from t1 union select (cast(avg(t1.c) AS integer)) from t1)),b*case 19 when t1.a then 11 else e end)<=f),17)=c)} +} {239900} +do_test randexpr-2.1382 { + db eval {SELECT case when ~t1.b=t1.b-coalesce((select 17 from t1 where t1.d-a>=(abs(case when c*11 between 19+(select cast(avg(13*b) AS integer) from t1) and case t1.e-t1.f when t1.a then 11 else a end then 19 else 17 end-c+a)/abs(t1.a))),e) then (f) when exists(select 1 from t1 where (11) in (c,t1.c,t1.b)) then f else 19 end*t1.f FROM t1 WHERE case 19 when t1.b then b*case t1.a when +t1.f then e else 17+t1.a end-11++(select ~~abs(~count(*))+count(distinct 13) from t1)*t1.b-t1.c- -a else 17 end>=t1.e} +} {} +do_test randexpr-2.1383 { + db eval {SELECT case when ~t1.b=t1.b-coalesce((select 17 from t1 where t1.d-a>=(abs(case when c*11 between 19+(select cast(avg(13*b) AS integer) from t1) and case t1.e-t1.f when t1.a then 11 else a end then 19 else 17 end-c+a)/abs(t1.a))),e) then (f) when exists(select 1 from t1 where (11) in (c,t1.c,t1.b)) then f else 19 end*t1.f FROM t1 WHERE NOT (case 19 when t1.b then b*case t1.a when +t1.f then e else 17+t1.a end-11++(select ~~abs(~count(*))+count(distinct 13) from t1)*t1.b-t1.c- -a else 17 end>=t1.e)} +} {11400} +do_test randexpr-2.1384 { + db eval {SELECT case when t1.a<=e and d*(t1.d)+t1.d++a-t1.f-a<=e or c not between b and d and 19 not between t1.e and 11 or -t1.b in (select b from t1 union select 17 from t1) and t1.d<>t1.e or t1.d in (select t1.c from t1 union select t1.d from t1) then t1.e else 17 end+f+t1.b FROM t1 WHERE t1.c*~case 19+coalesce((select 19 from t1 where e>11-d),t1.e) when coalesce((select max(11) from t1 where not t1.f in (select ~abs(cast(avg(coalesce((select max(b+f) from t1 where -f=(t1.b) and a between t1.c and t1.b),a)) AS integer))+ -count(distinct t1.b)- -max(f)*max((f)) from t1 union select min(t1.e) from t1) or a in (select +d*d from t1 union select t1.c from t1)),t1.e) then t1.d else t1.c end*t1.bt1.e or t1.d in (select t1.c from t1 union select t1.d from t1) then t1.e else 17 end+f+t1.b FROM t1 WHERE NOT (t1.c*~case 19+coalesce((select 19 from t1 where e>11-d),t1.e) when coalesce((select max(11) from t1 where not t1.f in (select ~abs(cast(avg(coalesce((select max(b+f) from t1 where -f=(t1.b) and a between t1.c and t1.b),a)) AS integer))+ -count(distinct t1.b)- -max(f)*max((f)) from t1 union select min(t1.e) from t1) or a in (select +d*d from t1 union select t1.c from t1)),t1.e) then t1.d else t1.c end*t1.bb)),e)-13)/abs(t1.e))+17)),t1.a)*t1.d+b FROM t1 WHERE not exists(select 1 from t1 where t1.b=case 19 when f then d+case when t1.c not between 13 and d | (select abs((min(17) | (min(t1.f)))) from t1) and coalesce((select max(11*19) from t1 where not exists(select 1 from t1 where (e>=t1.b))),11) not in (t1.c,19,t1.c) or t1.a in (select count(*) from t1 union select max(c)+cast(avg(11) AS integer) from t1) and (c) not between t1.a and t1.d and t1.b between 11 and a then t1.d else c end else (t1.f) end)} +} {40200} +do_test randexpr-2.1387 { + db eval {SELECT coalesce((select 17 from t1 where (~f=(abs(coalesce((select t1.d from t1 where case (select count(distinct c | 13)- -(cast(avg(11) AS integer)) from t1)+coalesce((select 19 from t1 where d in (select t1.c from t1 union select 17 from t1)),t1.f) when e then t1.c else t1.d end*d<=19 and not exists(select 1 from t1 where (e)<>b)),e)-13)/abs(t1.e))+17)),t1.a)*t1.d+b FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.b=case 19 when f then d+case when t1.c not between 13 and d | (select abs((min(17) | (min(t1.f)))) from t1) and coalesce((select max(11*19) from t1 where not exists(select 1 from t1 where (e>=t1.b))),11) not in (t1.c,19,t1.c) or t1.a in (select count(*) from t1 union select max(c)+cast(avg(11) AS integer) from t1) and (c) not between t1.a and t1.d and t1.b between 11 and a then t1.d else c end else (t1.f) end))} +} {} +do_test randexpr-2.1388 { + db eval {SELECT coalesce((select 17 from t1 where (~f=(abs(coalesce((select t1.d from t1 where case (select count(distinct c & 13)- -(cast(avg(11) AS integer)) from t1)+coalesce((select 19 from t1 where d in (select t1.c from t1 union select 17 from t1)),t1.f) when e then t1.c else t1.d end*d<=19 and not exists(select 1 from t1 where (e)<>b)),e)-13)/abs(t1.e))+17)),t1.a)*t1.d+b FROM t1 WHERE not exists(select 1 from t1 where t1.b=case 19 when f then d+case when t1.c not between 13 and d | (select abs((min(17) | (min(t1.f)))) from t1) and coalesce((select max(11*19) from t1 where not exists(select 1 from t1 where (e>=t1.b))),11) not in (t1.c,19,t1.c) or t1.a in (select count(*) from t1 union select max(c)+cast(avg(11) AS integer) from t1) and (c) not between t1.a and t1.d and t1.b between 11 and a then t1.d else c end else (t1.f) end)} +} {40200} +do_test randexpr-2.1389 { + db eval {SELECT coalesce((select max(t1.f+19+case -d when t1.f then t1.e else e end+case when +d in (select case when exists(select 1 from t1 where coalesce((select max( -17-d+t1.b-t1.d) from t1 where e not in (f,t1.e,11)),c) | t1.e>=c) then b else d end from t1 union select c from t1) then t1.b else d end-e*b+11) from t1 where f<>t1.b),d) FROM t1 WHERE (exists(select 1 from t1 where f> -t1.a*11 or e in (a-~ -t1.e,+a | e*case when coalesce((select t1.c from t1 where t1.f in (select (count(*)) from t1 union select ((count(*))) from t1)),a)-t1.e not in (e,t1.a,d) or 19 in (t1.b,t1.c,13) and c>19 then b*d else ( -t1.d) end-t1.a*t1.b*19,b)))} +} {-98470} +do_test randexpr-2.1390 { + db eval {SELECT coalesce((select max(t1.f+19+case -d when t1.f then t1.e else e end+case when +d in (select case when exists(select 1 from t1 where coalesce((select max( -17-d+t1.b-t1.d) from t1 where e not in (f,t1.e,11)),c) | t1.e>=c) then b else d end from t1 union select c from t1) then t1.b else d end-e*b+11) from t1 where f<>t1.b),d) FROM t1 WHERE NOT ((exists(select 1 from t1 where f> -t1.a*11 or e in (a-~ -t1.e,+a | e*case when coalesce((select t1.c from t1 where t1.f in (select (count(*)) from t1 union select ((count(*))) from t1)),a)-t1.e not in (e,t1.a,d) or 19 in (t1.b,t1.c,13) and c>19 then b*d else ( -t1.d) end-t1.a*t1.b*19,b))))} +} {} +do_test randexpr-2.1391 { + db eval {SELECT coalesce((select max(t1.f+19+case -d when t1.f then t1.e else e end+case when +d in (select case when exists(select 1 from t1 where coalesce((select max( -17-d+t1.b-t1.d) from t1 where e not in (f,t1.e,11)),c) & t1.e>=c) then b else d end from t1 union select c from t1) then t1.b else d end-e*b+11) from t1 where f<>t1.b),d) FROM t1 WHERE (exists(select 1 from t1 where f> -t1.a*11 or e in (a-~ -t1.e,+a | e*case when coalesce((select t1.c from t1 where t1.f in (select (count(*)) from t1 union select ((count(*))) from t1)),a)-t1.e not in (e,t1.a,d) or 19 in (t1.b,t1.c,13) and c>19 then b*d else ( -t1.d) end-t1.a*t1.b*19,b)))} +} {-98670} +do_test randexpr-2.1392 { + db eval {SELECT case t1.b* -(abs(e)/abs(d+b)) when ~a-11 then coalesce((select max(case when (~~19- -t1.d=f) then +(abs(t1.c)/abs(t1.e)) when (t1.d>e or t1.a>=t1.a) then 19 else t1.a end*b-(19)-a-t1.c) from t1 where t1.f>=11),13) else b end FROM t1 WHERE (not exists(select 1 from t1 where t1.e<=t1.f) or c- -e*17 in (t1.c+c, -b-17, -coalesce((select case when +coalesce((select max(coalesce((select t1.f from t1 where t1.d in (select max(t1.d)-count(*) from t1 union select max( -t1.a) from t1)),e)+11) from t1 where ( -19)>=t1.a),t1.e)-13 not between t1.a and d then t1.d else 19 end+t1.b from t1 where t1.d<>19),11)))} +} {} +do_test randexpr-2.1393 { + db eval {SELECT case t1.b* -(abs(e)/abs(d+b)) when ~a-11 then coalesce((select max(case when (~~19- -t1.d=f) then +(abs(t1.c)/abs(t1.e)) when (t1.d>e or t1.a>=t1.a) then 19 else t1.a end*b-(19)-a-t1.c) from t1 where t1.f>=11),13) else b end FROM t1 WHERE NOT ((not exists(select 1 from t1 where t1.e<=t1.f) or c- -e*17 in (t1.c+c, -b-17, -coalesce((select case when +coalesce((select max(coalesce((select t1.f from t1 where t1.d in (select max(t1.d)-count(*) from t1 union select max( -t1.a) from t1)),e)+11) from t1 where ( -19)>=t1.a),t1.e)-13 not between t1.a and d then t1.d else 19 end+t1.b from t1 where t1.d<>19),11))))} +} {200} +do_test randexpr-2.1394 { + db eval {SELECT (select case case min(d-t1.c)-max(t1.a) when ~count(distinct d+case -f*t1.d+11 when b then b else b end)-min(c) then case +max(t1.a)*~abs(count(*)) when -min(13) then max(17) else count(*) end else -max(e) end when max(t1.a) then max(d) else max(17) end-count(distinct t1.b) from t1)-(d) FROM t1 WHERE +19 between b*11 and (select max(d-13) | ~+~+~((count(*)))*cast(avg(b) AS integer) from t1)+b} +} {} +do_test randexpr-2.1395 { + db eval {SELECT (select case case min(d-t1.c)-max(t1.a) when ~count(distinct d+case -f*t1.d+11 when b then b else b end)-min(c) then case +max(t1.a)*~abs(count(*)) when -min(13) then max(17) else count(*) end else -max(e) end when max(t1.a) then max(d) else max(17) end-count(distinct t1.b) from t1)-(d) FROM t1 WHERE NOT (+19 between b*11 and (select max(d-13) | ~+~+~((count(*)))*cast(avg(b) AS integer) from t1)+b)} +} {-384} +do_test randexpr-2.1396 { + db eval {SELECT (abs(case when +a*t1.e+(abs(t1.e | 11+coalesce((select max(d) from t1 where (not not b19),17)) and t1.b>13 and d=t1.a and 13 in (d,t1.a,11)),t1.e)*d)/abs(11+t1.a-19))=c or b<>c then t1.e when b<>19 then 17 else b end)/abs(11)) FROM t1 WHERE (coalesce((select max(case when exists(select 1 from t1 where coalesce((select a from t1 where not 19-~(coalesce((select t1.d from t1 where d between e and 17),t1.a)-t1.a-17) in (t1.d,t1.e,19)),19)*11*d in (select d from t1 union select t1.b from t1)) then c when d between t1.a and -19 then t1.e else 19 end-d*c) from t1 where (t1.f>=t1.c)),11)) not in (17,17,a)} +} {45} +do_test randexpr-2.1397 { + db eval {SELECT (abs(case when +a*t1.e+(abs(t1.e | 11+coalesce((select max(d) from t1 where (not not b19),17)) and t1.b>13 and d=t1.a and 13 in (d,t1.a,11)),t1.e)*d)/abs(11+t1.a-19))=c or b<>c then t1.e when b<>19 then 17 else b end)/abs(11)) FROM t1 WHERE NOT ((coalesce((select max(case when exists(select 1 from t1 where coalesce((select a from t1 where not 19-~(coalesce((select t1.d from t1 where d between e and 17),t1.a)-t1.a-17) in (t1.d,t1.e,19)),19)*11*d in (select d from t1 union select t1.b from t1)) then c when d between t1.a and -19 then t1.e else 19 end-d*c) from t1 where (t1.f>=t1.c)),11)) not in (17,17,a))} +} {} +do_test randexpr-2.1398 { + db eval {SELECT (abs(case when +a*t1.e+(abs(t1.e & 11+coalesce((select max(d) from t1 where (not not b19),17)) and t1.b>13 and d=t1.a and 13 in (d,t1.a,11)),t1.e)*d)/abs(11+t1.a-19))=c or b<>c then t1.e when b<>19 then 17 else b end)/abs(11)) FROM t1 WHERE (coalesce((select max(case when exists(select 1 from t1 where coalesce((select a from t1 where not 19-~(coalesce((select t1.d from t1 where d between e and 17),t1.a)-t1.a-17) in (t1.d,t1.e,19)),19)*11*d in (select d from t1 union select t1.b from t1)) then c when d between t1.a and -19 then t1.e else 19 end-d*c) from t1 where (t1.f>=t1.c)),11)) not in (17,17,a)} +} {45} +do_test randexpr-2.1399 { + db eval {SELECT 19+(t1.f)*case coalesce((select max(b) from t1 where not f not between coalesce((select (select (count(distinct t1.c))+ -max( -(f)) from t1)+t1.c from t1 where t1.c<=d),17)-c-19 and 17 or f<>13),case when not exists(select 1 from t1 where ((a)) between b and t1.f) then c when not ( -f not in (t1.b,t1.a,t1.c)) then -t1.b else 19 end)-t1.d-t1.e when t1.e then 11 else 19 end FROM t1 WHERE not not exists(select 1 from t1 where not 11=c and a*e between coalesce((select max(t1.e) from t1 where f=t1.b*19+case when (e not in (t1.d,t1.d, -c) or t1.a13),case when not exists(select 1 from t1 where ((a)) between b and t1.f) then c when not ( -f not in (t1.b,t1.a,t1.c)) then -t1.b else 19 end)-t1.d-t1.e when t1.e then 11 else 19 end FROM t1 WHERE NOT (not not exists(select 1 from t1 where not 11=c and a*e between coalesce((select max(t1.e) from t1 where f=t1.b*19+case when (e not in (t1.d,t1.d, -c) or t1.a19) or t1.d=a)),19) FROM t1 WHERE t1.c not between f and d} +} {19} +do_test randexpr-2.1402 { + db eval {SELECT coalesce((select max(19) from t1 where e-coalesce((select 13 from t1 where exists(select 1 from t1 where ((+(case when d*t1.b not in (t1.d,t1.f,e) then 11 else t1.c end))+19*11+e<=11))),19+t1.d) between t1.c and -e and exists(select 1 from t1 where t1.d=c and exists(select 1 from t1 where exists(select 1 from t1 where t1.f=b and a in (19,t1.b,d) or t1.b=11) or t1.c>19) or t1.d=a)),19) FROM t1 WHERE NOT (t1.c not between f and d)} +} {} +do_test randexpr-2.1403 { + db eval {SELECT case e when (t1.e+case when t1.e not between t1.c and case when d+coalesce((select t1.d+13+case case a when t1.a then t1.b else t1.c end when 17 then t1.b else f end+19 from t1 where exists(select 1 from t1 where t1.f< -17)),11)>=d then 13 else 13 end*(t1.c) then -c when t1.e not between t1.f and t1.d then t1.a else ( - -t1.a) end-d) then t1.a else t1.d end FROM t1 WHERE t1.d between case when -(t1.e-c)+a between -+coalesce((select max(+t1.c) from t1 where (coalesce((select max(case when d>~t1.e then t1.c when t1.f in (select t1.d from t1 union select t1.e from t1) then (19) else t1.e end) from t1 where not exists(select 1 from t1 where t1.e< -(11))),t1.f) in (select min(t1.f) from t1 union select count(distinct 13) from t1))),t1.e) and t1.d then a when 13<=c then b else t1.c end-c and f} +} {400} +do_test randexpr-2.1404 { + db eval {SELECT case e when (t1.e+case when t1.e not between t1.c and case when d+coalesce((select t1.d+13+case case a when t1.a then t1.b else t1.c end when 17 then t1.b else f end+19 from t1 where exists(select 1 from t1 where t1.f< -17)),11)>=d then 13 else 13 end*(t1.c) then -c when t1.e not between t1.f and t1.d then t1.a else ( - -t1.a) end-d) then t1.a else t1.d end FROM t1 WHERE NOT (t1.d between case when -(t1.e-c)+a between -+coalesce((select max(+t1.c) from t1 where (coalesce((select max(case when d>~t1.e then t1.c when t1.f in (select t1.d from t1 union select t1.e from t1) then (19) else t1.e end) from t1 where not exists(select 1 from t1 where t1.e< -(11))),t1.f) in (select min(t1.f) from t1 union select count(distinct 13) from t1))),t1.e) and t1.d then a when 13<=c then b else t1.c end-c and f)} +} {} +do_test randexpr-2.1405 { + db eval {SELECT (select abs(min(case when d not between coalesce((select max(case case t1.e when e-t1.f-a then case when (not exists(select 1 from t1 where coalesce((select max(t1.f) from t1 where 19<>17 and e not between -13 and t1.a),t1.c)>=t1.e)) then (select abs(cast(avg(17) AS integer)) from t1) when c between e and 17 then (select (count(*)) from t1) else 11 end else 11 end when e then 11 else a end) from t1 where t1.b>t1.b),t1.e) and 13 then t1.d else 17 end))*min(b) | -count(distinct t1.f) from t1) FROM t1 WHERE (e) in (select +t1.f from t1 union select t1.f+coalesce((select t1.d+e from t1 where t1.f not in (t1.b,t1.f,e)),(19))*case when t1.a<=a and t1.e<=e then t1.d else t1.c end from t1) and (t1.c not between 11 and e) or d in (select count(*)-cast(avg(t1.a) AS integer) from t1 union select max(19) from t1) and not t1.a not in (11,t1.d,b) or 17>=t1.a} +} {} +do_test randexpr-2.1406 { + db eval {SELECT (select abs(min(case when d not between coalesce((select max(case case t1.e when e-t1.f-a then case when (not exists(select 1 from t1 where coalesce((select max(t1.f) from t1 where 19<>17 and e not between -13 and t1.a),t1.c)>=t1.e)) then (select abs(cast(avg(17) AS integer)) from t1) when c between e and 17 then (select (count(*)) from t1) else 11 end else 11 end when e then 11 else a end) from t1 where t1.b>t1.b),t1.e) and 13 then t1.d else 17 end))*min(b) | -count(distinct t1.f) from t1) FROM t1 WHERE NOT ((e) in (select +t1.f from t1 union select t1.f+coalesce((select t1.d+e from t1 where t1.f not in (t1.b,t1.f,e)),(19))*case when t1.a<=a and t1.e<=e then t1.d else t1.c end from t1) and (t1.c not between 11 and e) or d in (select count(*)-cast(avg(t1.a) AS integer) from t1 union select max(19) from t1) and not t1.a not in (11,t1.d,b) or 17>=t1.a)} +} {-1} +do_test randexpr-2.1407 { + db eval {SELECT (select abs(min(case when d not between coalesce((select max(case case t1.e when e-t1.f-a then case when (not exists(select 1 from t1 where coalesce((select max(t1.f) from t1 where 19<>17 and e not between -13 and t1.a),t1.c)>=t1.e)) then (select abs(cast(avg(17) AS integer)) from t1) when c between e and 17 then (select (count(*)) from t1) else 11 end else 11 end when e then 11 else a end) from t1 where t1.b>t1.b),t1.e) and 13 then t1.d else 17 end))*min(b) & -count(distinct t1.f) from t1) FROM t1 WHERE NOT ((e) in (select +t1.f from t1 union select t1.f+coalesce((select t1.d+e from t1 where t1.f not in (t1.b,t1.f,e)),(19))*case when t1.a<=a and t1.e<=e then t1.d else t1.c end from t1) and (t1.c not between 11 and e) or d in (select count(*)-cast(avg(t1.a) AS integer) from t1 union select max(19) from t1) and not t1.a not in (11,t1.d,b) or 17>=t1.a)} +} {80000} +do_test randexpr-2.1408 { + db eval {SELECT case when ++coalesce((select (abs(a)/abs((select max((abs(13*f)/abs(t1.d))-t1.d*t1.e) from t1)))+b-t1.c+(select +(cast(avg(c) AS integer))*count(*) from t1)-t1.d-b*t1.e+19 from t1 where t1.c not between 11 and t1.d),19)<=t1.d then t1.d when not exists(select 1 from t1 where -11=t1.a) then e else 11 end FROM t1 WHERE (coalesce((select max(coalesce((select a-19 | ~~t1.b from t1 where (abs(t1.f)/abs(b)) not between case when t1.d<=case when not exists(select 1 from t1 where 19<=t1.d) then case when t1.a<=c then f else t1.d end when d>=17 then t1.c else (b) end*t1.c then - -t1.c when c<>t1.a then t1.f else 11 end and e),t1.e)-(t1.a)) from t1 where e<=a),17)<=t1.e) and t1.d=(f)} +} {} +do_test randexpr-2.1409 { + db eval {SELECT case when ++coalesce((select (abs(a)/abs((select max((abs(13*f)/abs(t1.d))-t1.d*t1.e) from t1)))+b-t1.c+(select +(cast(avg(c) AS integer))*count(*) from t1)-t1.d-b*t1.e+19 from t1 where t1.c not between 11 and t1.d),19)<=t1.d then t1.d when not exists(select 1 from t1 where -11=t1.a) then e else 11 end FROM t1 WHERE NOT ((coalesce((select max(coalesce((select a-19 | ~~t1.b from t1 where (abs(t1.f)/abs(b)) not between case when t1.d<=case when not exists(select 1 from t1 where 19<=t1.d) then case when t1.a<=c then f else t1.d end when d>=17 then t1.c else (b) end*t1.c then - -t1.c when c<>t1.a then t1.f else 11 end and e),t1.e)-(t1.a)) from t1 where e<=a),17)<=t1.e) and t1.d=(f))} +} {400} +do_test randexpr-2.1410 { + db eval {SELECT c*t1.c*(abs(case 11 when case when 11*11 not between b and t1.a then t1.d else -coalesce((select t1.c from t1 where (not exists(select 1 from t1 where e*~13 not in (a*t1.c, -t1.a,case when 13=t1.c or 13 between 11 and a then - -a when e<=t1.e then 13 else 11 end)))),t1.b+t1.b) end then t1.c else ((e)) end)/abs(t1.a))+t1.a-e-13 FROM t1 WHERE t1.a*13+case when (select count(distinct b++(select case count(distinct 19*(select -+min((13*f))-count(distinct t1.c)-max(t1.e) | (count(distinct 11)) from t1)*(f)) when count(*) then min(a)+(cast(avg(t1.d) AS integer)) else -min(17) end from t1) | t1.c-f) from t1)>t1.b then 19 else c end+17t1.b then 19 else c end+17=t1.c and e between d and t1.f),case when (13)<>(t1.e) then d when t1.a<=t1.e then 13 else d end) not in (17,b,17) then t1.d else t1.a end+a),t1.d) FROM t1 WHERE case t1.f when 11 then t1.e | f*case when ((select max(17) from t1) | 11>17+~coalesce((select max(t1.b) from t1 where (coalesce((select max(t1.e) from t1 where t1.e in (select (cast(avg( -t1.a) AS integer)) from t1 union select count(*) from t1)),a)) in (t1.f,a,t1.e)),f)+17) then t1.a when 19 in (t1.c, -e,11) or not exists(select 1 from t1 where t1.e between d and a) then 13 else 19 end+t1.f else 11 end<17} +} {-401} +do_test randexpr-2.1413 { + db eval {SELECT ~coalesce((select b from t1 where b between e and case when t1.c+coalesce((select 11 from t1 where (a in (+d-11,t1.f-a,b)) and t1.c in (select t1.f from t1 union select c from t1) or b between 13 and t1.b and t1.e<(c) and a>=t1.c and e between d and t1.f),case when (13)<>(t1.e) then d when t1.a<=t1.e then 13 else d end) not in (17,b,17) then t1.d else t1.a end+a),t1.d) FROM t1 WHERE NOT (case t1.f when 11 then t1.e | f*case when ((select max(17) from t1) | 11>17+~coalesce((select max(t1.b) from t1 where (coalesce((select max(t1.e) from t1 where t1.e in (select (cast(avg( -t1.a) AS integer)) from t1 union select count(*) from t1)),a)) in (t1.f,a,t1.e)),f)+17) then t1.a when 19 in (t1.c, -e,11) or not exists(select 1 from t1 where t1.e between d and a) then 13 else 19 end+t1.f else 11 end<17)} +} {} +do_test randexpr-2.1414 { + db eval {SELECT ~case when (a<> -++ -11) then e+case when c*t1.ad then t1.a else b end else a end | case when not exists(select 1 from t1 where not exists(select 1 from t1 where 13 | d in (select a from t1 union select d from t1))) or t1.f not between c and 19 then +t1.a else c-a end-17*c FROM t1 WHERE (case when (case when b in (select 11*coalesce((select 11 from t1 where (d not between 13 and 13+17)),coalesce((select max(13) from t1 where t1.c in (select max(e) from t1 union select count(*) from t1)),t1.b)) from t1 union select -t1.e from t1) then 13 when t1.f in ( -f, -(f),c) then 19 else f end in (select t1.a from t1 union select (t1.c) from t1)) then (abs(19)/abs(t1.b)) when (e in (b,11,19)) and t1.a -++ -11) then e+case when c*t1.ad then t1.a else b end else a end | case when not exists(select 1 from t1 where not exists(select 1 from t1 where 13 | d in (select a from t1 union select d from t1))) or t1.f not between c and 19 then +t1.a else c-a end-17*c FROM t1 WHERE NOT ((case when (case when b in (select 11*coalesce((select 11 from t1 where (d not between 13 and 13+17)),coalesce((select max(13) from t1 where t1.c in (select max(e) from t1 union select count(*) from t1)),t1.b)) from t1 union select -t1.e from t1) then 13 when t1.f in ( -f, -(f),c) then 19 else f end in (select t1.a from t1 union select (t1.c) from t1)) then (abs(19)/abs(t1.b)) when (e in (b,11,19)) and t1.a -++ -11) then e+case when c*t1.ad then t1.a else b end else a end & case when not exists(select 1 from t1 where not exists(select 1 from t1 where 13 & d in (select a from t1 union select d from t1))) or t1.f not between c and 19 then +t1.a else c-a end-17*c FROM t1 WHERE NOT ((case when (case when b in (select 11*coalesce((select 11 from t1 where (d not between 13 and 13+17)),coalesce((select max(13) from t1 where t1.c in (select max(e) from t1 union select count(*) from t1)),t1.b)) from t1 union select -t1.e from t1) then 13 when t1.f in ( -f, -(f),c) then 19 else f end in (select t1.a from t1 union select (t1.c) from t1)) then (abs(19)/abs(t1.b)) when (e in (b,11,19)) and t1.a19) then -d when ~c in (select min(e) from t1 union select cast(avg(case when c not between b and t1.a then b else 13-e+t1.e end) AS integer) from t1) then 13-coalesce((select max(coalesce((select max(19) from t1 where (17=a)),13)) from t1 where t1.a>=c),a) else t1.d end*(t1.c) from t1 union select (11) from t1) then a when b not in (e,t1.f,13) then t1.f else 13 end FROM t1 WHERE 13<>e or t1.a in (select f from t1 union select f from t1)} +} {600} +do_test randexpr-2.1418 { + db eval {SELECT case when t1.d in (select case when exists(select 1 from t1 where 13>19) then -d when ~c in (select min(e) from t1 union select cast(avg(case when c not between b and t1.a then b else 13-e+t1.e end) AS integer) from t1) then 13-coalesce((select max(coalesce((select max(19) from t1 where (17=a)),13)) from t1 where t1.a>=c),a) else t1.d end*(t1.c) from t1 union select (11) from t1) then a when b not in (e,t1.f,13) then t1.f else 13 end FROM t1 WHERE NOT (13<>e or t1.a in (select f from t1 union select f from t1))} +} {} +do_test randexpr-2.1419 { + db eval {SELECT 17-(select case max(t1.f*~case when 17>=b then t1.d else t1.a end) when (count(distinct t1.c)) then count(distinct t1.d+~13*19) else -min((select +case abs(count(*)) when abs(+count(*)) then ~case count(distinct a) when max(t1.c) then max(t1.c) else min(t1.f) end+max(17) else count(*) end from t1))- -cast(avg(f) AS integer)-min(a) end from t1) FROM t1 WHERE (select count(*) from t1) in (select abs(min(coalesce((select t1.d from t1 where coalesce((select max((t1.d)) from t1 where not b+t1.e*(select min(t1.a+t1.e) from t1)<=(abs(t1.d)/abs(t1.c))+t1.d),f*17+d+case when f between e and d and t1.c= -c then ~13 when b not between 11 and e then (11) else e end+t1.d)=13),t1.e))) from t1 union select (cast(avg(b) AS integer)) from t1)} +} {} +do_test randexpr-2.1420 { + db eval {SELECT 17-(select case max(t1.f*~case when 17>=b then t1.d else t1.a end) when (count(distinct t1.c)) then count(distinct t1.d+~13*19) else -min((select +case abs(count(*)) when abs(+count(*)) then ~case count(distinct a) when max(t1.c) then max(t1.c) else min(t1.f) end+max(17) else count(*) end from t1))- -cast(avg(f) AS integer)-min(a) end from t1) FROM t1 WHERE NOT ((select count(*) from t1) in (select abs(min(coalesce((select t1.d from t1 where coalesce((select max((t1.d)) from t1 where not b+t1.e*(select min(t1.a+t1.e) from t1)<=(abs(t1.d)/abs(t1.c))+t1.d),f*17+d+case when f between e and d and t1.c= -c then ~13 when b not between 11 and e then (11) else e end+t1.d)=13),t1.e))) from t1 union select (cast(avg(b) AS integer)) from t1))} +} {-1067} +do_test randexpr-2.1421 { + db eval {SELECT case when +coalesce((select 19 from t1 where c between f and 13),t1.f)<>t1.c*t1.d then coalesce((select max(d) from t1 where t1.d between t1.a and t1.a),t1.f-f)-(13 | case when 11 in (select abs(max(t1.b)*cast(avg(t1.c) AS integer))+count(*) from t1 union select count(distinct b) from t1) and t1.a not in (b,t1.a,e) or a not in (e,19,(t1.e)) then t1.b else 17+t1.a end*t1.a) when 13 in (select e from t1 union select c from t1) then a else e end FROM t1 WHERE (select -count(*) from t1)*case when not coalesce((select max(11) from t1 where t1.f<>a),t1.a)<>b then c else ~case when not 19+13-t1.d=t1.d or c>c or (t1.a=t1.d) or 13>=a then a when t1.c not between 13 and 17 then (abs(13+t1.d-t1.a)/abs(b)) else d end end+a | 11<=e} +} {-20013} +do_test randexpr-2.1422 { + db eval {SELECT case when +coalesce((select 19 from t1 where c between f and 13),t1.f)<>t1.c*t1.d then coalesce((select max(d) from t1 where t1.d between t1.a and t1.a),t1.f-f)-(13 | case when 11 in (select abs(max(t1.b)*cast(avg(t1.c) AS integer))+count(*) from t1 union select count(distinct b) from t1) and t1.a not in (b,t1.a,e) or a not in (e,19,(t1.e)) then t1.b else 17+t1.a end*t1.a) when 13 in (select e from t1 union select c from t1) then a else e end FROM t1 WHERE NOT ((select -count(*) from t1)*case when not coalesce((select max(11) from t1 where t1.f<>a),t1.a)<>b then c else ~case when not 19+13-t1.d=t1.d or c>c or (t1.a=t1.d) or 13>=a then a when t1.c not between 13 and 17 then (abs(13+t1.d-t1.a)/abs(b)) else d end end+a | 11<=e)} +} {} +do_test randexpr-2.1423 { + db eval {SELECT case when +coalesce((select 19 from t1 where c between f and 13),t1.f)<>t1.c*t1.d then coalesce((select max(d) from t1 where t1.d between t1.a and t1.a),t1.f-f)-(13 & case when 11 in (select abs(max(t1.b)*cast(avg(t1.c) AS integer))+count(*) from t1 union select count(distinct b) from t1) and t1.a not in (b,t1.a,e) or a not in (e,19,(t1.e)) then t1.b else 17+t1.a end*t1.a) when 13 in (select e from t1 union select c from t1) then a else e end FROM t1 WHERE (select -count(*) from t1)*case when not coalesce((select max(11) from t1 where t1.f<>a),t1.a)<>b then c else ~case when not 19+13-t1.d=t1.d or c>c or (t1.a=t1.d) or 13>=a then a when t1.c not between 13 and 17 then (abs(13+t1.d-t1.a)/abs(b)) else d end end+a | 11<=e} +} {0} +do_test randexpr-2.1424 { + db eval {SELECT case t1.d | t1.f+(e)+case when +t1.e-d*t1.a+17-b*(abs(t1.f)/abs( -a))-case when 19>=e then ~t1.a*case when t1.e>19 and t1.f<>d then t1.a else t1.d end | b*e else 17 end+t1.a=17 then t1.c else t1.b end when 17 then t1.b else t1.b end FROM t1 WHERE case when c<=13*t1.a then 11 else -case when t1.f*e>= -((19)) then case when a>=t1.c then t1.d*e else b end else coalesce((select t1.b from t1 where 11+d-17-t1.d-t1.b not in (case d-17 when f then t1.d else t1.b end,e,t1.c)),t1.c) end*19 end<>b} +} {200} +do_test randexpr-2.1425 { + db eval {SELECT case t1.d | t1.f+(e)+case when +t1.e-d*t1.a+17-b*(abs(t1.f)/abs( -a))-case when 19>=e then ~t1.a*case when t1.e>19 and t1.f<>d then t1.a else t1.d end | b*e else 17 end+t1.a=17 then t1.c else t1.b end when 17 then t1.b else t1.b end FROM t1 WHERE NOT (case when c<=13*t1.a then 11 else -case when t1.f*e>= -((19)) then case when a>=t1.c then t1.d*e else b end else coalesce((select t1.b from t1 where 11+d-17-t1.d-t1.b not in (case d-17 when f then t1.d else t1.b end,e,t1.c)),t1.c) end*19 end<>b)} +} {} +do_test randexpr-2.1426 { + db eval {SELECT case t1.d & t1.f+(e)+case when +t1.e-d*t1.a+17-b*(abs(t1.f)/abs( -a))-case when 19>=e then ~t1.a*case when t1.e>19 and t1.f<>d then t1.a else t1.d end & b*e else 17 end+t1.a=17 then t1.c else t1.b end when 17 then t1.b else t1.b end FROM t1 WHERE case when c<=13*t1.a then 11 else -case when t1.f*e>= -((19)) then case when a>=t1.c then t1.d*e else b end else coalesce((select t1.b from t1 where 11+d-17-t1.d-t1.b not in (case d-17 when f then t1.d else t1.b end,e,t1.c)),t1.c) end*19 end<>b} +} {200} +do_test randexpr-2.1427 { + db eval {SELECT (coalesce((select max(~t1.d*19*t1.f) from t1 where (abs(17)/abs(t1.f-case when not exists(select 1 from t1 where case when a in (f,t1.a,c) then c when t1.a not in (13,t1.c,a) then e else t1.a end in (select abs(abs(min(t1.e))) from t1 union select cast(avg(11) AS integer) from t1)) or c13 or t1.e in (e,t1.c,d)),t1.e) | 13)-d*e FROM t1 WHERE 11 in (select max(+(select max(d | b) from t1)*17-e) from t1 union select (cast(avg(+a-+((coalesce((select t1.e from t1 where exists(select 1 from t1 where (abs( -case when coalesce((select max(b-17) from t1 where not exists(select 1 from t1 where t1.f not between a and 11)),t1.c) in (select t1.d from t1 union select (17) from t1) then t1.c else ( - -t1.d) end)/abs(t1.f))+11>f)),b)))*19) AS integer))-count(distinct t1.f) from t1)} +} {} +do_test randexpr-2.1428 { + db eval {SELECT (coalesce((select max(~t1.d*19*t1.f) from t1 where (abs(17)/abs(t1.f-case when not exists(select 1 from t1 where case when a in (f,t1.a,c) then c when t1.a not in (13,t1.c,a) then e else t1.a end in (select abs(abs(min(t1.e))) from t1 union select cast(avg(11) AS integer) from t1)) or c13 or t1.e in (e,t1.c,d)),t1.e) | 13)-d*e FROM t1 WHERE NOT (11 in (select max(+(select max(d | b) from t1)*17-e) from t1 union select (cast(avg(+a-+((coalesce((select t1.e from t1 where exists(select 1 from t1 where (abs( -case when coalesce((select max(b-17) from t1 where not exists(select 1 from t1 where t1.f not between a and 11)),t1.c) in (select t1.d from t1 union select (17) from t1) then t1.c else ( - -t1.d) end)/abs(t1.f))+11>f)),b)))*19) AS integer))-count(distinct t1.f) from t1))} +} {-4771395} +do_test randexpr-2.1429 { + db eval {SELECT (coalesce((select max(~t1.d*19*t1.f) from t1 where (abs(17)/abs(t1.f-case when not exists(select 1 from t1 where case when a in (f,t1.a,c) then c when t1.a not in (13,t1.c,a) then e else t1.a end in (select abs(abs(min(t1.e))) from t1 union select cast(avg(11) AS integer) from t1)) or c13 or t1.e in (e,t1.c,d)),t1.e) & 13)-d*e FROM t1 WHERE NOT (11 in (select max(+(select max(d | b) from t1)*17-e) from t1 union select (cast(avg(+a-+((coalesce((select t1.e from t1 where exists(select 1 from t1 where (abs( -case when coalesce((select max(b-17) from t1 where not exists(select 1 from t1 where t1.f not between a and 11)),t1.c) in (select t1.d from t1 union select (17) from t1) then t1.c else ( - -t1.d) end)/abs(t1.f))+11>f)),b)))*19) AS integer))-count(distinct t1.f) from t1))} +} {-199992} +do_test randexpr-2.1430 { + db eval {SELECT coalesce((select t1.e from t1 where +~case when d-(abs(+t1.b)/abs( -19*t1.c-(select (abs( -cast(avg((abs(d)/abs(t1.d))) AS integer))) from t1)))+11<19 then t1.a-19-a-f when not (c in (case f when t1.a then 17 else 11 end-a,t1.d, -e)) then 17 else (t1.b) end(t1.b) then t1.d when (not exists(select 1 from t1 where t1.f<>t1.c)) then t1.b else 17 end-e)-19)} +} {500} +do_test randexpr-2.1431 { + db eval {SELECT coalesce((select t1.e from t1 where +~case when d-(abs(+t1.b)/abs( -19*t1.c-(select (abs( -cast(avg((abs(d)/abs(t1.d))) AS integer))) from t1)))+11<19 then t1.a-19-a-f when not (c in (case f when t1.a then 17 else 11 end-a,t1.d, -e)) then 17 else (t1.b) end(t1.b) then t1.d when (not exists(select 1 from t1 where t1.f<>t1.c)) then t1.b else 17 end-e)-19))} +} {} +do_test randexpr-2.1432 { + db eval {SELECT case when (abs(17)/abs(t1.e))=case when (exists(select 1 from t1 where not exists(select 1 from t1 where t1.f<>19))) then coalesce((select 11 from t1 where not exists(select 1 from t1 where t1.e not in ( -t1.d,(b),t1.d))),t1.a)+t1.f*11 else t1.a end then b else e end)),17)) from t1) not in (13,e,17) then t1.e else 11 end FROM t1 WHERE not (t1.e<>coalesce((select (case t1.c when (coalesce((select 19 from t1 where (case when not exists(select 1 from t1 where e not in (c,e,t1.f)) then t1.f | t1.a else t1.a end in (d,19,t1.a)) or t1.f<=t1.c),+13))*t1.b-t1.d then -t1.c else b end) from t1 where 17=case when (exists(select 1 from t1 where not exists(select 1 from t1 where t1.f<>19))) then coalesce((select 11 from t1 where not exists(select 1 from t1 where t1.e not in ( -t1.d,(b),t1.d))),t1.a)+t1.f*11 else t1.a end then b else e end)),17)) from t1) not in (13,e,17) then t1.e else 11 end FROM t1 WHERE NOT (not (t1.e<>coalesce((select (case t1.c when (coalesce((select 19 from t1 where (case when not exists(select 1 from t1 where e not in (c,e,t1.f)) then t1.f | t1.a else t1.a end in (d,19,t1.a)) or t1.f<=t1.c),+13))*t1.b-t1.d then -t1.c else b end) from t1 where 17 -19 then e when a in (17,d,t1.f) then -t1.f else f end)+count(*)-max(t1.f) | count(distinct t1.a) | cast(avg(t1.c) AS integer)) | -max(a) from t1) end end FROM t1 WHERE a | t1.c in (select f from t1 union select case -t1.c when (abs(c | t1.c)/abs(17)) then (abs(t1.e)/abs(t1.c))+~19 else coalesce((select b from t1 where 11<=case d+coalesce((select max((select ( -(cast(avg(17) AS integer)))*max(t1.e)-max(t1.d)*cast(avg(t1.e) AS integer) from t1)) from t1 where (abs(case t1.f when 19 then b else t1.c end)/abs(t1.e))=b),d)*t1.f when -t1.b then t1.d else 19 end),a) end+d+e from t1)} +} {} +do_test randexpr-2.1435 { + db eval {SELECT (select max(t1.c) from t1) | case when d=(abs(t1.d)/abs(t1.b)) then 19 else case b when a then b+17+c-t1.d+d-a*t1.c else e+t1.f+ -(select abs(~+count(distinct case when b -19 then e when a in (17,d,t1.f) then -t1.f else f end)+count(*)-max(t1.f) | count(distinct t1.a) | cast(avg(t1.c) AS integer)) | -max(a) from t1) end end FROM t1 WHERE NOT (a | t1.c in (select f from t1 union select case -t1.c when (abs(c | t1.c)/abs(17)) then (abs(t1.e)/abs(t1.c))+~19 else coalesce((select b from t1 where 11<=case d+coalesce((select max((select ( -(cast(avg(17) AS integer)))*max(t1.e)-max(t1.d)*cast(avg(t1.e) AS integer) from t1)) from t1 where (abs(case t1.f when 19 then b else t1.c end)/abs(t1.e))=b),d)*t1.f when -t1.b then t1.d else 19 end),a) end+d+e from t1))} +} {1391} +do_test randexpr-2.1436 { + db eval {SELECT (select max(t1.c) from t1) & case when d=(abs(t1.d)/abs(t1.b)) then 19 else case b when a then b+17+c-t1.d+d-a*t1.c else e+t1.f+ -(select abs(~+count(distinct case when b -19 then e when a in (17,d,t1.f) then -t1.f else f end)+count(*)-max(t1.f) & count(distinct t1.a) & cast(avg(t1.c) AS integer)) & -max(a) from t1) end end FROM t1 WHERE NOT (a | t1.c in (select f from t1 union select case -t1.c when (abs(c | t1.c)/abs(17)) then (abs(t1.e)/abs(t1.c))+~19 else coalesce((select b from t1 where 11<=case d+coalesce((select max((select ( -(cast(avg(17) AS integer)))*max(t1.e)-max(t1.d)*cast(avg(t1.e) AS integer) from t1)) from t1 where (abs(case t1.f when 19 then b else t1.c end)/abs(t1.e))=b),d)*t1.f when -t1.b then t1.d else 19 end),a) end+d+e from t1))} +} {12} +do_test randexpr-2.1437 { + db eval {SELECT case e*case when case coalesce((select max(13) from t1 where exists(select 1 from t1 where t1.a in (17,b,17))),t1.e)-t1.c when c then 19 else -t1.d end+17 in (t1.d,c,11) or b<= -( - -a) then ~(a) when f in (select case case (max(e)) when count(*) then max(17) else (max(17)) end+count(distinct e)- -count(distinct d) when -count(*) then -count(distinct d) else ((min(t1.f))) end from t1 union select min( -19) from t1) then c else (13) end when b then t1.b else f end FROM t1 WHERE t1.b17 or (t1.c in (19,c,a))) then 13 else c end-11+11*11) then t1.e when (11)<13 then - -t1.c else t1.d end FROM t1 WHERE ((t1.c+17 not between case b*(11-coalesce((select max(t1.a) from t1 where ~case when (not t1.d*17=f) then t1.c-13+c else t1.d end+t1.c>=(b)),b)*e) when t1.f then b else f end-f- -17 and d or t1.d not in (t1.c,11,b)))} +} {300} +do_test randexpr-2.1440 { + db eval {SELECT case when d in (c,t1.a*19,+++case when exists(select 1 from t1 where case 17 when ~t1.b then f-e*~b-17+ -t1.c else c end<>17 or (t1.c in (19,c,a))) then 13 else c end-11+11*11) then t1.e when (11)<13 then - -t1.c else t1.d end FROM t1 WHERE NOT (((t1.c+17 not between case b*(11-coalesce((select max(t1.a) from t1 where ~case when (not t1.d*17=f) then t1.c-13+c else t1.d end+t1.c>=(b)),b)*e) when t1.f then b else f end-f- -17 and d or t1.d not in (t1.c,11,b))))} +} {} +do_test randexpr-2.1441 { + db eval {SELECT t1.e*coalesce((select 17 from t1 where (19>(abs(case coalesce((select coalesce((select ~11 from t1 where b not between (13) and b),17) from t1 where 19 not between e+b+13 and -t1.d),t1.f) when d then t1.e else t1.d end-e | f)/abs((e)))) and (t1.b<=a and 11<> - -t1.e) and t1.dt1.a | t1.c} +} {} +do_test randexpr-2.1442 { + db eval {SELECT t1.e*coalesce((select 17 from t1 where (19>(abs(case coalesce((select coalesce((select ~11 from t1 where b not between (13) and b),17) from t1 where 19 not between e+b+13 and -t1.d),t1.f) when d then t1.e else t1.d end-e | f)/abs((e)))) and (t1.b<=a and 11<> - -t1.e) and t1.dt1.a | t1.c)} +} {150000} +do_test randexpr-2.1443 { + db eval {SELECT t1.e*coalesce((select 17 from t1 where (19>(abs(case coalesce((select coalesce((select ~11 from t1 where b not between (13) and b),17) from t1 where 19 not between e+b+13 and -t1.d),t1.f) when d then t1.e else t1.d end-e & f)/abs((e)))) and (t1.b<=a and 11<> - -t1.e) and t1.dt1.a | t1.c)} +} {150000} +do_test randexpr-2.1444 { + db eval {SELECT ~coalesce((select max(t1.a) from t1 where ((t1.c)<=case 11-~t1.b++(t1.a+ -c)*t1.d-b | d when ~e then 17 else (abs(f)/abs(t1.f-t1.c)) end-19 | b-~t1.e*a-t1.b | +c)),b)*a FROM t1 WHERE not exists(select 1 from t1 where t1.a=((abs(coalesce((select coalesce((select max(+d) from t1 where not exists(select 1 from t1 where -t1.d in (select -max(13)-(min((t1.a))) from t1 union select count(distinct f) from t1)) and 11 in (select f from t1 union select 17 from t1) and a<>13),case when e>(11) then -c else d end) from t1 where e<>11 and et1.e))))} +} {} +do_test randexpr-2.1445 { + db eval {SELECT ~coalesce((select max(t1.a) from t1 where ((t1.c)<=case 11-~t1.b++(t1.a+ -c)*t1.d-b | d when ~e then 17 else (abs(f)/abs(t1.f-t1.c)) end-19 | b-~t1.e*a-t1.b | +c)),b)*a FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a=((abs(coalesce((select coalesce((select max(+d) from t1 where not exists(select 1 from t1 where -t1.d in (select -max(13)-(min((t1.a))) from t1 union select count(distinct f) from t1)) and 11 in (select f from t1 union select 17 from t1) and a<>13),case when e>(11) then -c else d end) from t1 where e<>11 and et1.e)))))} +} {-20100} +do_test randexpr-2.1446 { + db eval {SELECT ~coalesce((select max(t1.a) from t1 where ((t1.c)<=case 11-~t1.b++(t1.a+ -c)*t1.d-b & d when ~e then 17 else (abs(f)/abs(t1.f-t1.c)) end-19 & b-~t1.e*a-t1.b & +c)),b)*a FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a=((abs(coalesce((select coalesce((select max(+d) from t1 where not exists(select 1 from t1 where -t1.d in (select -max(13)-(min((t1.a))) from t1 union select count(distinct f) from t1)) and 11 in (select f from t1 union select 17 from t1) and a<>13),case when e>(11) then -c else d end) from t1 where e<>11 and et1.e)))))} +} {-20100} +do_test randexpr-2.1447 { + db eval {SELECT (select count(distinct ~(((abs(b-a)/abs(case (select min((select case cast(avg(11+t1.e) AS integer) when case min( -~coalesce((select 13 from t1 where case t1.e when f then d else 17 end>=b),e)) when case max(t1.b) when (~ -count(*)+(( -max( -t1.a)))-(count(*))) then -count(distinct (t1.c)) else min( -t1.e) end then count(*) else cast(avg( -(e)) AS integer) end then cast(avg(13) AS integer) else max(17) end from t1)) from t1) when 13 then c else (d) end))))) from t1)*t1.b FROM t1 WHERE not t1.c>=t1.b} +} {} +do_test randexpr-2.1448 { + db eval {SELECT (select count(distinct ~(((abs(b-a)/abs(case (select min((select case cast(avg(11+t1.e) AS integer) when case min( -~coalesce((select 13 from t1 where case t1.e when f then d else 17 end>=b),e)) when case max(t1.b) when (~ -count(*)+(( -max( -t1.a)))-(count(*))) then -count(distinct (t1.c)) else min( -t1.e) end then count(*) else cast(avg( -(e)) AS integer) end then cast(avg(13) AS integer) else max(17) end from t1)) from t1) when 13 then c else (d) end))))) from t1)*t1.b FROM t1 WHERE NOT (not t1.c>=t1.b)} +} {200} +do_test randexpr-2.1449 { + db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where t1.b in (select e from t1 union select t1.e from t1)),t1.a)) from t1 where case when t1.d=case when d not between t1.a and case when not t1.c in ((t1.e),a,t1.c) then 19 | t1.c when a not between 19 and b then (19) else 13 end then t1.d else b end-11 and not t1.f=t1.c or 19 not in (t1.d,c, -t1.f) and 17< -t1.d then e when t1.b not between 17 and t1.b then f else d end<11),t1.c)*f FROM t1 WHERE t1.b<=(coalesce((select c from t1 where e in (t1.a,t1.c,case when 17 not between 19 and (19)-t1.a-(abs(coalesce((select d from t1 where case (t1.b+e*b*t1.c) when 13 then t1.b else 19 end<>19),17))/abs(a))*t1.a then 17 when exists(select 1 from t1 where ( -e)=a) or 13>=d then 17 else t1.f end)),c))} +} {180000} +do_test randexpr-2.1450 { + db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where t1.b in (select e from t1 union select t1.e from t1)),t1.a)) from t1 where case when t1.d=case when d not between t1.a and case when not t1.c in ((t1.e),a,t1.c) then 19 | t1.c when a not between 19 and b then (19) else 13 end then t1.d else b end-11 and not t1.f=t1.c or 19 not in (t1.d,c, -t1.f) and 17< -t1.d then e when t1.b not between 17 and t1.b then f else d end<11),t1.c)*f FROM t1 WHERE NOT (t1.b<=(coalesce((select c from t1 where e in (t1.a,t1.c,case when 17 not between 19 and (19)-t1.a-(abs(coalesce((select d from t1 where case (t1.b+e*b*t1.c) when 13 then t1.b else 19 end<>19),17))/abs(a))*t1.a then 17 when exists(select 1 from t1 where ( -e)=a) or 13>=d then 17 else t1.f end)),c)))} +} {} +do_test randexpr-2.1451 { + db eval {SELECT coalesce((select max(coalesce((select max(13) from t1 where t1.b in (select e from t1 union select t1.e from t1)),t1.a)) from t1 where case when t1.d=case when d not between t1.a and case when not t1.c in ((t1.e),a,t1.c) then 19 & t1.c when a not between 19 and b then (19) else 13 end then t1.d else b end-11 and not t1.f=t1.c or 19 not in (t1.d,c, -t1.f) and 17< -t1.d then e when t1.b not between 17 and t1.b then f else d end<11),t1.c)*f FROM t1 WHERE t1.b<=(coalesce((select c from t1 where e in (t1.a,t1.c,case when 17 not between 19 and (19)-t1.a-(abs(coalesce((select d from t1 where case (t1.b+e*b*t1.c) when 13 then t1.b else 19 end<>19),17))/abs(a))*t1.a then 17 when exists(select 1 from t1 where ( -e)=a) or 13>=d then 17 else t1.f end)),c))} +} {180000} +do_test randexpr-2.1452 { + db eval {SELECT (d)+(select -abs(+cast(avg((select max((coalesce((select d from t1 where case when 13>=e then t1.c else 19 end>=d),coalesce((select 19-(select count(distinct 19 | (abs(19)/abs(~13))) from t1) | t1.d from t1 where coalesce((select max(11) from t1 where t1.a in (select t1.d from t1 union select c from t1)),19)>t1.d),e)+t1.b))) from t1)) AS integer)+abs( -max(b))) from t1) FROM t1 WHERE c-t1.c not between t1.c and +case when +case -case when 17 not in (17,(e),t1.c) then a else 19 end-13 when t1.e then b else 13 end>19 or 17 in (select b from t1 union select t1.c from t1) then case c when t1.c then d else c end when not t1.f in (select -cast(avg(a) AS integer)*count(distinct (17))+min(f)* - - -cast(avg(b) AS integer) from t1 union select (count(*)) from t1) then d else a end} +} {-500} +do_test randexpr-2.1453 { + db eval {SELECT (d)+(select -abs(+cast(avg((select max((coalesce((select d from t1 where case when 13>=e then t1.c else 19 end>=d),coalesce((select 19-(select count(distinct 19 | (abs(19)/abs(~13))) from t1) | t1.d from t1 where coalesce((select max(11) from t1 where t1.a in (select t1.d from t1 union select c from t1)),19)>t1.d),e)+t1.b))) from t1)) AS integer)+abs( -max(b))) from t1) FROM t1 WHERE NOT (c-t1.c not between t1.c and +case when +case -case when 17 not in (17,(e),t1.c) then a else 19 end-13 when t1.e then b else 13 end>19 or 17 in (select b from t1 union select t1.c from t1) then case c when t1.c then d else c end when not t1.f in (select -cast(avg(a) AS integer)*count(distinct (17))+min(f)* - - -cast(avg(b) AS integer) from t1 union select (count(*)) from t1) then d else a end)} +} {} +do_test randexpr-2.1454 { + db eval {SELECT (d)+(select -abs(+cast(avg((select max((coalesce((select d from t1 where case when 13>=e then t1.c else 19 end>=d),coalesce((select 19-(select count(distinct 19 & (abs(19)/abs(~13))) from t1) & t1.d from t1 where coalesce((select max(11) from t1 where t1.a in (select t1.d from t1 union select c from t1)),19)>t1.d),e)+t1.b))) from t1)) AS integer)+abs( -max(b))) from t1) FROM t1 WHERE c-t1.c not between t1.c and +case when +case -case when 17 not in (17,(e),t1.c) then a else 19 end-13 when t1.e then b else 13 end>19 or 17 in (select b from t1 union select t1.c from t1) then case c when t1.c then d else c end when not t1.f in (select -cast(avg(a) AS integer)*count(distinct (17))+min(f)* - - -cast(avg(b) AS integer) from t1 union select (count(*)) from t1) then d else a end} +} {-500} +do_test randexpr-2.1455 { + db eval {SELECT case when 19 in (case when coalesce((select max(case when e*t1.b in (coalesce((select t1.a from t1 where (abs(f)/abs(coalesce((select f from t1 where t1.f in (a,b,t1.d)),13))) in (b,b,11)),c),t1.a,17) then b else d end) from t1 where f>=13 and a>=17 and not exists(select 1 from t1 where (b<>f))), -t1.c) between d and 11 then d else t1.f end,t1.c,11) then 13 else 17 end FROM t1 WHERE t1.d in (select (abs(t1.a)/abs(t1.f)) from t1 union select e from t1) and ((b*coalesce((select -11 from t1 where (coalesce((select max( -t1.e+ -coalesce((select d from t1 where t1.c<= - -t1.d),t1.c)) from t1 where b in (select -count(distinct d)+count(distinct d)- -((min(e))) from t1 union select count(*) from t1)),(t1.e))-19*d<>t1.e)),a)*t1.f)=b)} +} {} +do_test randexpr-2.1456 { + db eval {SELECT case when 19 in (case when coalesce((select max(case when e*t1.b in (coalesce((select t1.a from t1 where (abs(f)/abs(coalesce((select f from t1 where t1.f in (a,b,t1.d)),13))) in (b,b,11)),c),t1.a,17) then b else d end) from t1 where f>=13 and a>=17 and not exists(select 1 from t1 where (b<>f))), -t1.c) between d and 11 then d else t1.f end,t1.c,11) then 13 else 17 end FROM t1 WHERE NOT (t1.d in (select (abs(t1.a)/abs(t1.f)) from t1 union select e from t1) and ((b*coalesce((select -11 from t1 where (coalesce((select max( -t1.e+ -coalesce((select d from t1 where t1.c<= - -t1.d),t1.c)) from t1 where b in (select -count(distinct d)+count(distinct d)- -((min(e))) from t1 union select count(*) from t1)),(t1.e))-19*d<>t1.e)),a)*t1.f)=b))} +} {17} +do_test randexpr-2.1457 { + db eval {SELECT coalesce((select max((select count(*) from t1)) from t1 where coalesce((select max(t1.a-coalesce((select t1.d+case when exists(select 1 from t1 where exists(select 1 from t1 where t1.f between t1.a and f)) or d | b between 19 and 19 then f+17 else (t1.b) end from t1 where t1.e not between -t1.d and (19)),(17))) from t1 where not exists(select 1 from t1 where 19 between t1.b and 13 or t1.b>t1.c) or 19>=19),b) between 13 and f), -t1.a) FROM t1 WHERE exists(select 1 from t1 where +t1.f+t1.e<(abs(t1.b)/abs( -f*e))) or case t1.c when case when 19 not between 17 and case when t1.e<>e then t1.b when not exists(select 1 from t1 where coalesce((select max(b) from t1 where (et1.d or (t1.d<>t1.e)) then t1.c else 17 end then t1.c when e<>b then 17 else e end then t1.d else t1.e end between d and b} +} {} +do_test randexpr-2.1458 { + db eval {SELECT coalesce((select max((select count(*) from t1)) from t1 where coalesce((select max(t1.a-coalesce((select t1.d+case when exists(select 1 from t1 where exists(select 1 from t1 where t1.f between t1.a and f)) or d | b between 19 and 19 then f+17 else (t1.b) end from t1 where t1.e not between -t1.d and (19)),(17))) from t1 where not exists(select 1 from t1 where 19 between t1.b and 13 or t1.b>t1.c) or 19>=19),b) between 13 and f), -t1.a) FROM t1 WHERE NOT (exists(select 1 from t1 where +t1.f+t1.e<(abs(t1.b)/abs( -f*e))) or case t1.c when case when 19 not between 17 and case when t1.e<>e then t1.b when not exists(select 1 from t1 where coalesce((select max(b) from t1 where (et1.d or (t1.d<>t1.e)) then t1.c else 17 end then t1.c when e<>b then 17 else e end then t1.d else t1.e end between d and b)} +} {-100} +do_test randexpr-2.1459 { + db eval {SELECT coalesce((select max((select count(*) from t1)) from t1 where coalesce((select max(t1.a-coalesce((select t1.d+case when exists(select 1 from t1 where exists(select 1 from t1 where t1.f between t1.a and f)) or d & b between 19 and 19 then f+17 else (t1.b) end from t1 where t1.e not between -t1.d and (19)),(17))) from t1 where not exists(select 1 from t1 where 19 between t1.b and 13 or t1.b>t1.c) or 19>=19),b) between 13 and f), -t1.a) FROM t1 WHERE NOT (exists(select 1 from t1 where +t1.f+t1.e<(abs(t1.b)/abs( -f*e))) or case t1.c when case when 19 not between 17 and case when t1.e<>e then t1.b when not exists(select 1 from t1 where coalesce((select max(b) from t1 where (et1.d or (t1.d<>t1.e)) then t1.c else 17 end then t1.c when e<>b then 17 else e end then t1.d else t1.e end between d and b)} +} {-100} +do_test randexpr-2.1460 { + db eval {SELECT case when not case 11 when t1.e*coalesce((select max(t1.b) from t1 where (abs(t1.c)/abs(~11)) not between coalesce((select max((abs(a)/abs(c))) from t1 where t1.b>=t1.a or b= -e),t1.f) and e and c not in (t1.a,t1.f,t1.c) and not (a)17 then c else a end | t1.b,a) or not (t1.d<11)),d) from t1 union select t1.a from t1) and f in (select b from t1 union select b from t1))} +} {100} +do_test randexpr-2.1461 { + db eval {SELECT case when not case 11 when t1.e*coalesce((select max(t1.b) from t1 where (abs(t1.c)/abs(~11)) not between coalesce((select max((abs(a)/abs(c))) from t1 where t1.b>=t1.a or b= -e),t1.f) and e and c not in (t1.a,t1.f,t1.c) and not (a)17 then c else a end | t1.b,a) or not (t1.d<11)),d) from t1 union select t1.a from t1) and f in (select b from t1 union select b from t1)))} +} {} +do_test randexpr-2.1462 { + db eval {SELECT case when case when coalesce((select max(case when ((a<=case t1.a+t1.a when t1.d then -c else b end or t1.b<>e)) then 17 else 19*19*a end*13) from t1 where d<>t1.d),d)<=a or 11<=t1.e then t1.c when 17<11 then 17 else e end<=t1.a then t1.d when e= -e then t1.d else 19 end FROM t1 WHERE t1.e<=t1.a or (abs(+a+coalesce((select max(t1.b) from t1 where (select ~count(distinct 17) from t1)-b in (select t1.b+t1.b from t1 union select 19 from t1)), -11))/abs(case when not exists(select 1 from t1 where t1.d not between 17 and c- -c+e) or t1.e>t1.f then t1.d when t1.d not in (17,e,d) then a else 17 end)) in (c,d,11)} +} {} +do_test randexpr-2.1463 { + db eval {SELECT case when case when coalesce((select max(case when ((a<=case t1.a+t1.a when t1.d then -c else b end or t1.b<>e)) then 17 else 19*19*a end*13) from t1 where d<>t1.d),d)<=a or 11<=t1.e then t1.c when 17<11 then 17 else e end<=t1.a then t1.d when e= -e then t1.d else 19 end FROM t1 WHERE NOT (t1.e<=t1.a or (abs(+a+coalesce((select max(t1.b) from t1 where (select ~count(distinct 17) from t1)-b in (select t1.b+t1.b from t1 union select 19 from t1)), -11))/abs(case when not exists(select 1 from t1 where t1.d not between 17 and c- -c+e) or t1.e>t1.f then t1.d when t1.d not in (17,e,d) then a else 17 end)) in (c,d,11))} +} {19} +do_test randexpr-2.1464 { + db eval {SELECT ~case when t1.e<=t1.a then b else (11) end+(select -((cast(avg(coalesce((select a from t1 where (select cast(avg(t1.d) AS integer) | case case min((t1.e)) when cast(avg(t1.b) AS integer) then max(t1.c) else max(19) end*count(*) when -count(distinct e) then count(*) else max( - -17) end from t1) not between c and -t1.e-f+f),11)-11) AS integer)))*max(e) from t1)+e* - -a-t1.d*e FROM t1 WHERE coalesce((select max(case when 11 between d and d then e | b else case (select (case count(distinct coalesce((select -coalesce((select max(t1.f) from t1 where t1.b in (select 11 from t1 union select 19 from t1)),t1.e) from t1 where 13<>17),17)) when (max( -t1.e)) then max(17)+max(11) else ((count(*))) end)*(count(*)) from t1) when 11 then -13+19 else t1.e end end) from t1 where ((t1.a not between d and -t1.c))),t1.a)<11} +} {} +do_test randexpr-2.1465 { + db eval {SELECT ~case when t1.e<=t1.a then b else (11) end+(select -((cast(avg(coalesce((select a from t1 where (select cast(avg(t1.d) AS integer) | case case min((t1.e)) when cast(avg(t1.b) AS integer) then max(t1.c) else max(19) end*count(*) when -count(distinct e) then count(*) else max( - -17) end from t1) not between c and -t1.e-f+f),11)-11) AS integer)))*max(e) from t1)+e* - -a-t1.d*e FROM t1 WHERE NOT (coalesce((select max(case when 11 between d and d then e | b else case (select (case count(distinct coalesce((select -coalesce((select max(t1.f) from t1 where t1.b in (select 11 from t1 union select 19 from t1)),t1.e) from t1 where 13<>17),17)) when (max( -t1.e)) then max(17)+max(11) else ((count(*))) end)*(count(*)) from t1) when 11 then -13+19 else t1.e end end) from t1 where ((t1.a not between d and -t1.c))),t1.a)<11)} +} {-194512} +do_test randexpr-2.1466 { + db eval {SELECT ~case when t1.e<=t1.a then b else (11) end+(select -((cast(avg(coalesce((select a from t1 where (select cast(avg(t1.d) AS integer) & case case min((t1.e)) when cast(avg(t1.b) AS integer) then max(t1.c) else max(19) end*count(*) when -count(distinct e) then count(*) else max( - -17) end from t1) not between c and -t1.e-f+f),11)-11) AS integer)))*max(e) from t1)+e* - -a-t1.d*e FROM t1 WHERE NOT (coalesce((select max(case when 11 between d and d then e | b else case (select (case count(distinct coalesce((select -coalesce((select max(t1.f) from t1 where t1.b in (select 11 from t1 union select 19 from t1)),t1.e) from t1 where 13<>17),17)) when (max( -t1.e)) then max(17)+max(11) else ((count(*))) end)*(count(*)) from t1) when 11 then -13+19 else t1.e end end) from t1 where ((t1.a not between d and -t1.c))),t1.a)<11)} +} {-194512} +do_test randexpr-2.1467 { + db eval {SELECT t1.e*~13-t1.a-~case when (abs(t1.a)/abs(coalesce((select max(t1.a) from t1 where e not between f and e-t1.b+13),case when (a in (select ( -c) from t1 union select 11 from t1) or exists(select 1 from t1 where 11 between f and t1.f)) then t1.b-a else -t1.e end)+13*t1.f)) | 13 -19-a then (a)-coalesce((select max(case when a in (13,t1.b,11) then t1.b else (13) end) from t1 where not exists(select 1 from t1 where t1.b>=b)),t1.c) else -13 end)*(a)<17)} +} {} +do_test randexpr-2.1468 { + db eval {SELECT t1.e*~13-t1.a-~case when (abs(t1.a)/abs(coalesce((select max(t1.a) from t1 where e not between f and e-t1.b+13),case when (a in (select ( -c) from t1 union select 11 from t1) or exists(select 1 from t1 where 11 between f and t1.f)) then t1.b-a else -t1.e end)+13*t1.f)) | 13 -19-a then (a)-coalesce((select max(case when a in (13,t1.b,11) then t1.b else (13) end) from t1 where not exists(select 1 from t1 where t1.b>=b)),t1.c) else -13 end)*(a)<17))} +} {-6499} +do_test randexpr-2.1469 { + db eval {SELECT t1.e*~13-t1.a-~case when (abs(t1.a)/abs(coalesce((select max(t1.a) from t1 where e not between f and e-t1.b+13),case when (a in (select ( -c) from t1 union select 11 from t1) or exists(select 1 from t1 where 11 between f and t1.f)) then t1.b-a else -t1.e end)+13*t1.f)) & 13 -19-a then (a)-coalesce((select max(case when a in (13,t1.b,11) then t1.b else (13) end) from t1 where not exists(select 1 from t1 where t1.b>=b)),t1.c) else -13 end)*(a)<17))} +} {-6499} +do_test randexpr-2.1470 { + db eval {SELECT coalesce((select max(f*b | case when f in (t1.b,t1.b*(select count(*) from t1)+(select -count(*) from t1), -b) and +13<(abs( -~d-case when t1.a in (select -f from t1 union select t1.c from t1) then (t1.a) when t1.a=a),coalesce((select 11 from t1 where 11 not between 19 and t1.c),t1.a))-19 when t1.e then t1.f else e end)) from t1 union select -d from t1) then d when t1.f between 17 and d then t1.d else t1.d end and (f) or d<17} +} {} +do_test randexpr-2.1471 { + db eval {SELECT coalesce((select max(f*b | case when f in (t1.b,t1.b*(select count(*) from t1)+(select -count(*) from t1), -b) and +13<(abs( -~d-case when t1.a in (select -f from t1 union select t1.c from t1) then (t1.a) when t1.a=a),coalesce((select 11 from t1 where 11 not between 19 and t1.c),t1.a))-19 when t1.e then t1.f else e end)) from t1 union select -d from t1) then d when t1.f between 17 and d then t1.d else t1.d end and (f) or d<17)} +} {0} +do_test randexpr-2.1472 { + db eval {SELECT coalesce((select max(f*b & case when f in (t1.b,t1.b*(select count(*) from t1)+(select -count(*) from t1), -b) and +13<(abs( -~d-case when t1.a in (select -f from t1 union select t1.c from t1) then (t1.a) when t1.a=a),coalesce((select 11 from t1 where 11 not between 19 and t1.c),t1.a))-19 when t1.e then t1.f else e end)) from t1 union select -d from t1) then d when t1.f between 17 and d then t1.d else t1.d end and (f) or d<17)} +} {0} +do_test randexpr-2.1473 { + db eval {SELECT case when (t1.b+case when a in (select coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where 11=case e when (e) then t1.b else t1.c end or c in (t1.f,f,11))),t1.f) from t1 union select t1.d from t1) and t1.e<>e then t1.f when t1.a in (t1.d,a,13) then 17 else t1.d end not in (t1.f,t1.d,17)) or c<> -19 then b when fa-e then b else 19 end from t1 where 11<>t1.b),a) from t1 where not 19 in (select max(19)*count(distinct a) from t1 union select cast(avg(11) AS integer) from t1)),11) from t1 where t1.e<>a),17) then d else 19 end from t1 union select f from t1) and c in (select count(distinct c) from t1 union select -+max(d) | abs(count(*)) from t1)} +} {} +do_test randexpr-2.1474 { + db eval {SELECT case when (t1.b+case when a in (select coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where 11=case e when (e) then t1.b else t1.c end or c in (t1.f,f,11))),t1.f) from t1 union select t1.d from t1) and t1.e<>e then t1.f when t1.a in (t1.d,a,13) then 17 else t1.d end not in (t1.f,t1.d,17)) or c<> -19 then b when fa-e then b else 19 end from t1 where 11<>t1.b),a) from t1 where not 19 in (select max(19)*count(distinct a) from t1 union select cast(avg(11) AS integer) from t1)),11) from t1 where t1.e<>a),17) then d else 19 end from t1 union select f from t1) and c in (select count(distinct c) from t1 union select -+max(d) | abs(count(*)) from t1))} +} {200} +do_test randexpr-2.1475 { + db eval {SELECT 17+coalesce((select max(19) from t1 where -(select max(t1.d) from t1)>coalesce((select max((13)) from t1 where (coalesce((select 11 from t1 where -e-t1.d-b-(abs(t1.b)/abs(11))*t1.f*b-e not between (f) and t1.e or 11 in (t1.b,t1.e, -e)),t1.a) in (select t1.b from t1 union select 19 from t1)) and exists(select 1 from t1 where 13<19)),t1.e)),e) FROM t1 WHERE t1.a<>t1.d or not exists(select 1 from t1 where t1.a>=coalesce((select case t1.e*d when -case d*11 when t1.f then t1.e else t1.c end then 13*coalesce((select max(f*b*t1.e*t1.c) from t1 where t1.d in (select t1.c from t1 union select f from t1) or ((t1.ecoalesce((select max((13)) from t1 where (coalesce((select 11 from t1 where -e-t1.d-b-(abs(t1.b)/abs(11))*t1.f*b-e not between (f) and t1.e or 11 in (t1.b,t1.e, -e)),t1.a) in (select t1.b from t1 union select 19 from t1)) and exists(select 1 from t1 where 13<19)),t1.e)),e) FROM t1 WHERE NOT (t1.a<>t1.d or not exists(select 1 from t1 where t1.a>=coalesce((select case t1.e*d when -case d*11 when t1.f then t1.e else t1.c end then 13*coalesce((select max(f*b*t1.e*t1.c) from t1 where t1.d in (select t1.c from t1 union select f from t1) or ((t1.e=t1.a then f-coalesce((select -(select max((select min(a)-count(distinct c) from t1)) from t1) from t1 where a between f and d),c) else d end) and c or not exists(select 1 from t1 where 11<=13)),f)) then (e) else t1.b end FROM t1 WHERE not -c between -d+f | 17+t1.a and 11 or 11*e=(+case when c>=d then coalesce((select max(d-t1.f*f) from t1 where 11 in (select count(distinct t1.e) from t1 union select (~case count(*) when -max(t1.f) then count(distinct t1.d) else (cast(avg(t1.f) AS integer)) end) from t1)),t1.c) else d end+t1.b-t1.c+b)+t1.c- -(13)} +} {200} +do_test randexpr-2.1478 { + db eval {SELECT case +a when (coalesce((select d*f*t1.d from t1 where t1.f between (case when e* -13<~ - -t1.e then e when 13>=t1.a then f-coalesce((select -(select max((select min(a)-count(distinct c) from t1)) from t1) from t1 where a between f and d),c) else d end) and c or not exists(select 1 from t1 where 11<=13)),f)) then (e) else t1.b end FROM t1 WHERE NOT (not -c between -d+f | 17+t1.a and 11 or 11*e=(+case when c>=d then coalesce((select max(d-t1.f*f) from t1 where 11 in (select count(distinct t1.e) from t1 union select (~case count(*) when -max(t1.f) then count(distinct t1.d) else (cast(avg(t1.f) AS integer)) end) from t1)),t1.c) else d end+t1.b-t1.c+b)+t1.c- -(13))} +} {} +do_test randexpr-2.1479 { + db eval {SELECT case when case when not exists(select 1 from t1 where a between +d-case when t1.c+e not between case 11 when +t1.b+11 then 19 else -t1.f end+(11) and d and exists(select 1 from t1 where (a)>b) and not exists(select 1 from t1 where 11 in (a,11,t1.c)) then 19 else t1.a end and t1.a) then 17 when t1.d<>e then (t1.a) else e end-a<=e then c else 11 end FROM t1 WHERE coalesce((select a from t1 where not exists(select 1 from t1 where -t1.c not between b and t1.a)),case when t1.d<=19-13 then coalesce((select max((select count(*)*cast(avg(~t1.a-e*~17+t1.e) AS integer) from t1)) from t1 where (exists(select 1 from t1 where + - -e-11*a-t1.d in (11,(t1.b),c)))),19+e)* -b else c end)>=17} +} {300} +do_test randexpr-2.1480 { + db eval {SELECT case when case when not exists(select 1 from t1 where a between +d-case when t1.c+e not between case 11 when +t1.b+11 then 19 else -t1.f end+(11) and d and exists(select 1 from t1 where (a)>b) and not exists(select 1 from t1 where 11 in (a,11,t1.c)) then 19 else t1.a end and t1.a) then 17 when t1.d<>e then (t1.a) else e end-a<=e then c else 11 end FROM t1 WHERE NOT (coalesce((select a from t1 where not exists(select 1 from t1 where -t1.c not between b and t1.a)),case when t1.d<=19-13 then coalesce((select max((select count(*)*cast(avg(~t1.a-e*~17+t1.e) AS integer) from t1)) from t1 where (exists(select 1 from t1 where + - -e-11*a-t1.d in (11,(t1.b),c)))),19+e)* -b else c end)>=17)} +} {} +do_test randexpr-2.1481 { + db eval {SELECT coalesce((select t1.c-~t1.e*19++case t1.b when coalesce((select 17 from t1 where t1.f not between t1.c-+coalesce((select max(a+ -t1.c) from t1 where (select count(distinct 11) from t1) in (select -+case when a not between f and b or b>=t1.d then (t1.d) when a in (t1.e,b,13) then t1.d else t1.c end*a from t1 union select t1.f from t1)),f) and 17),a) | 17*c then 19 else d end+t1.c from t1 where e<>t1.b),19) FROM t1 WHERE not (t1.e not between ~17 and +t1.e*(~b)*e)} +} {} +do_test randexpr-2.1482 { + db eval {SELECT coalesce((select t1.c-~t1.e*19++case t1.b when coalesce((select 17 from t1 where t1.f not between t1.c-+coalesce((select max(a+ -t1.c) from t1 where (select count(distinct 11) from t1) in (select -+case when a not between f and b or b>=t1.d then (t1.d) when a in (t1.e,b,13) then t1.d else t1.c end*a from t1 union select t1.f from t1)),f) and 17),a) | 17*c then 19 else d end+t1.c from t1 where e<>t1.b),19) FROM t1 WHERE NOT (not (t1.e not between ~17 and +t1.e*(~b)*e))} +} {10519} +do_test randexpr-2.1483 { + db eval {SELECT coalesce((select t1.c-~t1.e*19++case t1.b when coalesce((select 17 from t1 where t1.f not between t1.c-+coalesce((select max(a+ -t1.c) from t1 where (select count(distinct 11) from t1) in (select -+case when a not between f and b or b>=t1.d then (t1.d) when a in (t1.e,b,13) then t1.d else t1.c end*a from t1 union select t1.f from t1)),f) and 17),a) & 17*c then 19 else d end+t1.c from t1 where e<>t1.b),19) FROM t1 WHERE NOT (not (t1.e not between ~17 and +t1.e*(~b)*e))} +} {10519} +do_test randexpr-2.1484 { + db eval {SELECT ~case when b<=(t1.c | (abs(d)/abs(a*f)))+case when (13*(t1.b) not in (19,b,t1.d)) and exists(select 1 from t1 where 19 between t1.d and 11) then (select case count(distinct t1.f) when +( -count(distinct c) | cast(avg(t1.d) AS integer)) then cast(avg(t1.c) AS integer) else min(f) end from t1) else 13 end*t1.c or exists(select 1 from t1 where -f in (select e from t1 union select -t1.a from t1)) then t1.d else t1.c end FROM t1 WHERE exists(select 1 from t1 where t1.c+b-t1.d between 11 and 17)} +} {} +do_test randexpr-2.1485 { + db eval {SELECT ~case when b<=(t1.c | (abs(d)/abs(a*f)))+case when (13*(t1.b) not in (19,b,t1.d)) and exists(select 1 from t1 where 19 between t1.d and 11) then (select case count(distinct t1.f) when +( -count(distinct c) | cast(avg(t1.d) AS integer)) then cast(avg(t1.c) AS integer) else min(f) end from t1) else 13 end*t1.c or exists(select 1 from t1 where -f in (select e from t1 union select -t1.a from t1)) then t1.d else t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.c+b-t1.d between 11 and 17))} +} {-401} +do_test randexpr-2.1486 { + db eval {SELECT ~case when b<=(t1.c & (abs(d)/abs(a*f)))+case when (13*(t1.b) not in (19,b,t1.d)) and exists(select 1 from t1 where 19 between t1.d and 11) then (select case count(distinct t1.f) when +( -count(distinct c) & cast(avg(t1.d) AS integer)) then cast(avg(t1.c) AS integer) else min(f) end from t1) else 13 end*t1.c or exists(select 1 from t1 where -f in (select e from t1 union select -t1.a from t1)) then t1.d else t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where t1.c+b-t1.d between 11 and 17))} +} {-401} +do_test randexpr-2.1487 { + db eval {SELECT coalesce((select max(~coalesce((select 19+~coalesce((select (abs((19)*c+~t1.a-t1.a*19)/abs(case when t1.d<>t1.b then t1.f when 13<>19 then (11) else t1.c end)) from t1 where f= -t1.a or t1.d not between t1.d and -f),t1.f) from t1 where not exists(select 1 from t1 where -19 not between d and f)),d)*t1.a-f) from t1 where c not in (c,c,c)),t1.b) FROM t1 WHERE (coalesce((select max( -t1.d+19+11+coalesce((select a from t1 where 11 not between e and t1.d),t1.d)) from t1 where not ( -t1.f not between b and f) and t1.e in (b,11,f)),f)+t1.e<=19) or c>t1.d or e in (a,19,11) or t1.f>b or -t1.f<=13 and a between 11 and t1.a} +} {200} +do_test randexpr-2.1488 { + db eval {SELECT coalesce((select max(~coalesce((select 19+~coalesce((select (abs((19)*c+~t1.a-t1.a*19)/abs(case when t1.d<>t1.b then t1.f when 13<>19 then (11) else t1.c end)) from t1 where f= -t1.a or t1.d not between t1.d and -f),t1.f) from t1 where not exists(select 1 from t1 where -19 not between d and f)),d)*t1.a-f) from t1 where c not in (c,c,c)),t1.b) FROM t1 WHERE NOT ((coalesce((select max( -t1.d+19+11+coalesce((select a from t1 where 11 not between e and t1.d),t1.d)) from t1 where not ( -t1.f not between b and f) and t1.e in (b,11,f)),f)+t1.e<=19) or c>t1.d or e in (a,19,11) or t1.f>b or -t1.f<=13 and a between 11 and t1.a)} +} {} +do_test randexpr-2.1489 { + db eval {SELECT case t1.d when 17 then 11 | t1.a-17+13+t1.f*t1.e+t1.e-case when d | t1.e in (t1.b,t1.a,c) then -13 else (b*19) end-(select cast(avg(coalesce((select a from t1 where e in (t1.f,t1.b,f)), -e)) AS integer) from t1)*d-11-t1.e-t1.a else t1.f end FROM t1 WHERE d*13 in (select abs(min(d)) from t1 union select cast(avg(d) AS integer) from t1)} +} {} +do_test randexpr-2.1490 { + db eval {SELECT case t1.d when 17 then 11 | t1.a-17+13+t1.f*t1.e+t1.e-case when d | t1.e in (t1.b,t1.a,c) then -13 else (b*19) end-(select cast(avg(coalesce((select a from t1 where e in (t1.f,t1.b,f)), -e)) AS integer) from t1)*d-11-t1.e-t1.a else t1.f end FROM t1 WHERE NOT (d*13 in (select abs(min(d)) from t1 union select cast(avg(d) AS integer) from t1))} +} {600} +do_test randexpr-2.1491 { + db eval {SELECT case t1.d when 17 then 11 & t1.a-17+13+t1.f*t1.e+t1.e-case when d & t1.e in (t1.b,t1.a,c) then -13 else (b*19) end-(select cast(avg(coalesce((select a from t1 where e in (t1.f,t1.b,f)), -e)) AS integer) from t1)*d-11-t1.e-t1.a else t1.f end FROM t1 WHERE NOT (d*13 in (select abs(min(d)) from t1 union select cast(avg(d) AS integer) from t1))} +} {600} +do_test randexpr-2.1492 { + db eval {SELECT coalesce((select max(19-(abs(t1.c)/abs( -13))-(select count(*)*abs(max(t1.a-b)) from t1)-t1.d) from t1 where (case coalesce((select max(~(select ~count(*) from t1)) from t1 where b=(abs(17)/abs(d))),11*case when not t1.c>=e or 17=c then d else 17*b end*t1.d) when 13 then 11 else t1.c end) in (select c from t1 union select t1.c from t1)),13) FROM t1 WHERE case t1.a*(select -case count(distinct ~(case 13-+t1.d-f when d then c else (19) end)*19)* -max(19) | -count(*)+abs(min(19)) | cast(avg(d) AS integer) when min(a) then count(distinct 11) else count(*) end from t1)*(abs(t1.a)/abs(11))-f-t1.b+(t1.f) when 11 then 17 else 19 end<>d} +} {-504} +do_test randexpr-2.1493 { + db eval {SELECT coalesce((select max(19-(abs(t1.c)/abs( -13))-(select count(*)*abs(max(t1.a-b)) from t1)-t1.d) from t1 where (case coalesce((select max(~(select ~count(*) from t1)) from t1 where b=(abs(17)/abs(d))),11*case when not t1.c>=e or 17=c then d else 17*b end*t1.d) when 13 then 11 else t1.c end) in (select c from t1 union select t1.c from t1)),13) FROM t1 WHERE NOT (case t1.a*(select -case count(distinct ~(case 13-+t1.d-f when d then c else (19) end)*19)* -max(19) | -count(*)+abs(min(19)) | cast(avg(d) AS integer) when min(a) then count(distinct 11) else count(*) end from t1)*(abs(t1.a)/abs(11))-f-t1.b+(t1.f) when 11 then 17 else 19 end<>d)} +} {} +do_test randexpr-2.1494 { + db eval {SELECT +(select abs( -abs(count(distinct case when (abs(t1.f)/abs(t1.a-t1.d)) in (select count(distinct 19) from t1 union select +abs(+ -cast(avg(c) AS integer)) from t1) then -(f) else e end-17)) | case count(distinct b) when count(*) then cast(avg(13) AS integer) else ( -count(distinct d)) end-count(*)* - -cast(avg(a) AS integer)) from t1)+case when t1.f in (select d*b | t1.d from t1 union select d from t1) then t1.f when 19<>t1.e then t1.b else 11 end+11 FROM t1 WHERE ft1.e then t1.b else 11 end+11 FROM t1 WHERE NOT (ft1.e then t1.b else 11 end+11 FROM t1 WHERE f17 or 17 between 13 and a and exists(select 1 from t1 where c not between t1.f and t1.d) then coalesce((select max(d) from t1 where t1.e<>19),17) else a end*(( -f))+t1.d FROM t1 WHERE exists(select 1 from t1 where exists(select 1 from t1 where t1.c between case when (a13 or b>=e or 19 between t1.d and -t1.e then t1.f else f end and f) and c>((t1.c))) and not exists(select 1 from t1 where 1717 or 17 between 13 and a and exists(select 1 from t1 where c not between t1.f and t1.d) then coalesce((select max(d) from t1 where t1.e<>19),17) else a end*(( -f))+t1.d FROM t1 WHERE NOT (exists(select 1 from t1 where exists(select 1 from t1 where t1.c between case when (a13 or b>=e or 19 between t1.d and -t1.e then t1.f else f end and f) and c>((t1.c))) and not exists(select 1 from t1 where 17=13 then t1.e else t1.c end)/abs(19)) | (t1.d) FROM t1 WHERE d>=(case when ((t1.a)) between t1.f and a then case when 11 between 19-case when (~coalesce((select t1.e from t1 where d>t1.c and e<>t1.f),e))>=13 then t1.b when t1.d in (select (count(*)-min(19)) from t1 union select cast(avg(t1.e) AS integer) from t1) then 17 else (t1.d) end*t1.a and (13) then 11 when not exists(select 1 from t1 where not 19<>(t1.e) and t1.a between d and d and t1.c=a) then 17 else t1.a end-17 else e end)} +} {} +do_test randexpr-2.1500 { + db eval {SELECT 17+11+d+t1.d | t1.c+(abs(case when 11 in (select count(distinct 11*+t1.d) from t1 union select ~cast(avg(t1.c) AS integer)*case (count(distinct 19)) when (cast(avg(t1.c) AS integer) | min(t1.a-f)) then cast(avg(a) AS integer) else cast(avg(t1.b) AS integer) end+max( - -d) from t1) then t1.a-13 when (11)>=13 then t1.e else t1.c end)/abs(19)) | (t1.d) FROM t1 WHERE NOT (d>=(case when ((t1.a)) between t1.f and a then case when 11 between 19-case when (~coalesce((select t1.e from t1 where d>t1.c and e<>t1.f),e))>=13 then t1.b when t1.d in (select (count(*)-min(19)) from t1 union select cast(avg(t1.e) AS integer) from t1) then 17 else (t1.d) end*t1.a and (13) then 11 when not exists(select 1 from t1 where not 19<>(t1.e) and t1.a between d and d and t1.c=a) then 17 else t1.a end-17 else e end))} +} {959} +do_test randexpr-2.1501 { + db eval {SELECT 17+11+d+t1.d & t1.c+(abs(case when 11 in (select count(distinct 11*+t1.d) from t1 union select ~cast(avg(t1.c) AS integer)*case (count(distinct 19)) when (cast(avg(t1.c) AS integer) & min(t1.a-f)) then cast(avg(a) AS integer) else cast(avg(t1.b) AS integer) end+max( - -d) from t1) then t1.a-13 when (11)>=13 then t1.e else t1.c end)/abs(19)) & (t1.d) FROM t1 WHERE NOT (d>=(case when ((t1.a)) between t1.f and a then case when 11 between 19-case when (~coalesce((select t1.e from t1 where d>t1.c and e<>t1.f),e))>=13 then t1.b when t1.d in (select (count(*)-min(19)) from t1 union select cast(avg(t1.e) AS integer) from t1) then 17 else (t1.d) end*t1.a and (13) then 11 when not exists(select 1 from t1 where not 19<>(t1.e) and t1.a between d and d and t1.c=a) then 17 else t1.a end-17 else e end))} +} {272} +do_test randexpr-2.1502 { + db eval {SELECT coalesce((select 17 from t1 where ((abs(19)/abs(case when ((f+17<(d))) and (abs(t1.c)/abs((t1.b)))>11 then ~a+11 when (t1.f)>t1.d then 19 else c end))<>t1.b) or (b in (( -t1.d),b,e) and (t1.a)<>c) and (17) not in (t1.f,11,17) or (f) not between t1.c and -t1.c),t1.a) FROM t1 WHERE 17 between -t1.b+f-19 | 17 and t1.e+t1.c} +} {} +do_test randexpr-2.1503 { + db eval {SELECT coalesce((select 17 from t1 where ((abs(19)/abs(case when ((f+17<(d))) and (abs(t1.c)/abs((t1.b)))>11 then ~a+11 when (t1.f)>t1.d then 19 else c end))<>t1.b) or (b in (( -t1.d),b,e) and (t1.a)<>c) and (17) not in (t1.f,11,17) or (f) not between t1.c and -t1.c),t1.a) FROM t1 WHERE NOT (17 between -t1.b+f-19 | 17 and t1.e+t1.c)} +} {17} +do_test randexpr-2.1504 { + db eval {SELECT +(11)-19-case when 19+13-19+f*19*c not in (coalesce((select max((select ~min(t1.b)+(count(distinct t1.d)) | min(13)*count(distinct t1.a)*max(a) from t1)) from t1 where not 19 in (select t1.d from t1 union select 19 from t1) or 19<=t1.c),t1.b | f) | e-f,d,d) then t1.a else d end FROM t1 WHERE t1.d in (select case when t1.e>(case coalesce((select (11)-t1.e from t1 where case t1.e when t1.c then (coalesce((select max(+t1.b) from t1 where (a in (case when 19 in (select cast(avg((t1.b)) AS integer) from t1 union select cast(avg( - -17) AS integer) from t1) then a when 17>=13 then c else t1.e end,11,11) or not 19 between t1.b and t1.a)),t1.e)) else d end<=t1.c),13) when e then a else d end) then a when 19 in (select (11) from t1 union select t1.e from t1) then (e) else t1.d end from t1 union select t1.d from t1)} +} {-108} +do_test randexpr-2.1505 { + db eval {SELECT +(11)-19-case when 19+13-19+f*19*c not in (coalesce((select max((select ~min(t1.b)+(count(distinct t1.d)) | min(13)*count(distinct t1.a)*max(a) from t1)) from t1 where not 19 in (select t1.d from t1 union select 19 from t1) or 19<=t1.c),t1.b | f) | e-f,d,d) then t1.a else d end FROM t1 WHERE NOT (t1.d in (select case when t1.e>(case coalesce((select (11)-t1.e from t1 where case t1.e when t1.c then (coalesce((select max(+t1.b) from t1 where (a in (case when 19 in (select cast(avg((t1.b)) AS integer) from t1 union select cast(avg( - -17) AS integer) from t1) then a when 17>=13 then c else t1.e end,11,11) or not 19 between t1.b and t1.a)),t1.e)) else d end<=t1.c),13) when e then a else d end) then a when 19 in (select (11) from t1 union select t1.e from t1) then (e) else t1.d end from t1 union select t1.d from t1))} +} {} +do_test randexpr-2.1506 { + db eval {SELECT +(11)-19-case when 19+13-19+f*19*c not in (coalesce((select max((select ~min(t1.b)+(count(distinct t1.d)) & min(13)*count(distinct t1.a)*max(a) from t1)) from t1 where not 19 in (select t1.d from t1 union select 19 from t1) or 19<=t1.c),t1.b & f) & e-f,d,d) then t1.a else d end FROM t1 WHERE t1.d in (select case when t1.e>(case coalesce((select (11)-t1.e from t1 where case t1.e when t1.c then (coalesce((select max(+t1.b) from t1 where (a in (case when 19 in (select cast(avg((t1.b)) AS integer) from t1 union select cast(avg( - -17) AS integer) from t1) then a when 17>=13 then c else t1.e end,11,11) or not 19 between t1.b and t1.a)),t1.e)) else d end<=t1.c),13) when e then a else d end) then a when 19 in (select (11) from t1 union select t1.e from t1) then (e) else t1.d end from t1 union select t1.d from t1)} +} {-108} +do_test randexpr-2.1507 { + db eval {SELECT (abs(case t1.f when (abs((abs( -t1.b+t1.f | case when t1.e-b*19<=17 then 13 when t1.d<>c-coalesce((select max(coalesce((select t1.d from t1 where (not exists(select 1 from t1 where (19)<=a) or 11 between t1.e and f)),d | t1.f)) from t1 where (t1.a between 19 and t1.a)),13) then 19 else f end)/abs(t1.f))-t1.a)/abs(e))+t1.e then t1.b else b end)/abs(19))+t1.a FROM t1 WHERE 17 in (select f*f from t1 union select a+d from t1)} +} {} +do_test randexpr-2.1508 { + db eval {SELECT (abs(case t1.f when (abs((abs( -t1.b+t1.f | case when t1.e-b*19<=17 then 13 when t1.d<>c-coalesce((select max(coalesce((select t1.d from t1 where (not exists(select 1 from t1 where (19)<=a) or 11 between t1.e and f)),d | t1.f)) from t1 where (t1.a between 19 and t1.a)),13) then 19 else f end)/abs(t1.f))-t1.a)/abs(e))+t1.e then t1.b else b end)/abs(19))+t1.a FROM t1 WHERE NOT (17 in (select f*f from t1 union select a+d from t1))} +} {110} +do_test randexpr-2.1509 { + db eval {SELECT (abs(case t1.f when (abs((abs( -t1.b+t1.f & case when t1.e-b*19<=17 then 13 when t1.d<>c-coalesce((select max(coalesce((select t1.d from t1 where (not exists(select 1 from t1 where (19)<=a) or 11 between t1.e and f)),d & t1.f)) from t1 where (t1.a between 19 and t1.a)),13) then 19 else f end)/abs(t1.f))-t1.a)/abs(e))+t1.e then t1.b else b end)/abs(19))+t1.a FROM t1 WHERE NOT (17 in (select f*f from t1 union select a+d from t1))} +} {110} +do_test randexpr-2.1510 { + db eval {SELECT (coalesce((select t1.e from t1 where +case when t1.c+f<>d-17 then t1.a when not (abs(t1.c)/abs(case case -f when f then a else t1.b end-t1.e-t1.f when t1.b then -e else t1.c end))>e or t1.b=a or exists(select 1 from t1 where 19>=t1.b) and t1.c< -e then t1.e else 13 end<=t1.b),b)) | d FROM t1 WHERE case 13 when 13 then 17-f else a end=e and (exists(select 1 from t1 where b in (select t1.f from t1 union select coalesce((select case when (abs(t1.c)/abs(17)) in (a,f*c,11) then c when ( -t1.d) in (select ~count(distinct t1.b) from t1 union select min((t1.c)) from t1) then t1.a else t1.e end from t1 where exists(select 1 from t1 where (t1.f) in (t1.d,17, -11))),b)-d*11*c+a from t1)))} +} {} +do_test randexpr-2.1511 { + db eval {SELECT (coalesce((select t1.e from t1 where +case when t1.c+f<>d-17 then t1.a when not (abs(t1.c)/abs(case case -f when f then a else t1.b end-t1.e-t1.f when t1.b then -e else t1.c end))>e or t1.b=a or exists(select 1 from t1 where 19>=t1.b) and t1.c< -e then t1.e else 13 end<=t1.b),b)) | d FROM t1 WHERE NOT (case 13 when 13 then 17-f else a end=e and (exists(select 1 from t1 where b in (select t1.f from t1 union select coalesce((select case when (abs(t1.c)/abs(17)) in (a,f*c,11) then c when ( -t1.d) in (select ~count(distinct t1.b) from t1 union select min((t1.c)) from t1) then t1.a else t1.e end from t1 where exists(select 1 from t1 where (t1.f) in (t1.d,17, -11))),b)-d*11*c+a from t1))))} +} {500} +do_test randexpr-2.1512 { + db eval {SELECT (coalesce((select t1.e from t1 where +case when t1.c+f<>d-17 then t1.a when not (abs(t1.c)/abs(case case -f when f then a else t1.b end-t1.e-t1.f when t1.b then -e else t1.c end))>e or t1.b=a or exists(select 1 from t1 where 19>=t1.b) and t1.c< -e then t1.e else 13 end<=t1.b),b)) & d FROM t1 WHERE NOT (case 13 when 13 then 17-f else a end=e and (exists(select 1 from t1 where b in (select t1.f from t1 union select coalesce((select case when (abs(t1.c)/abs(17)) in (a,f*c,11) then c when ( -t1.d) in (select ~count(distinct t1.b) from t1 union select min((t1.c)) from t1) then t1.a else t1.e end from t1 where exists(select 1 from t1 where (t1.f) in (t1.d,17, -11))),b)-d*11*c+a from t1))))} +} {400} +do_test randexpr-2.1513 { + db eval {SELECT (abs( -case when exists(select 1 from t1 where (abs(e++11-(abs(c)/abs(t1.f)))/abs(19+t1.b))+t1.b-c=(b)) or d in (~d, -f,c) then (select min(13) from t1)+11+~t1.a*t1.a else d end-t1.d)/abs((select (max(d))+count(*)-min(t1.c) from t1))) FROM t1 WHERE (select +min(c+d) | (max(13)+min(case when t1.e not in (t1.d,t1.d,19*t1.d) then t1.a when 17=d then t1.b else a end)+ - -max(t1.a)*count(distinct f) | count(*)+max(t1.d) | count(distinct d))-count(distinct 17)-count(*) from t1) not in (e,d+11,(t1.a+t1.f))} +} {7} +do_test randexpr-2.1514 { + db eval {SELECT (abs( -case when exists(select 1 from t1 where (abs(e++11-(abs(c)/abs(t1.f)))/abs(19+t1.b))+t1.b-c=(b)) or d in (~d, -f,c) then (select min(13) from t1)+11+~t1.a*t1.a else d end-t1.d)/abs((select (max(d))+count(*)-min(t1.c) from t1))) FROM t1 WHERE NOT ((select +min(c+d) | (max(13)+min(case when t1.e not in (t1.d,t1.d,19*t1.d) then t1.a when 17=d then t1.b else a end)+ - -max(t1.a)*count(distinct f) | count(*)+max(t1.d) | count(distinct d))-count(distinct 17)-count(*) from t1) not in (e,d+11,(t1.a+t1.f)))} +} {} +do_test randexpr-2.1515 { + db eval {SELECT case when not exists(select 1 from t1 where (not case t1.b when d then c else coalesce((select max(b+case c+c when t1.c then coalesce((select ((e)) from t1 where c in (e,t1.f,t1.d)),t1.a) else t1.f end+t1.e) from t1 where not t1.e not between t1.f and t1.a),19) end+f<>b)) then e when f in (19,t1.d, -c) then 19 else case when e>=t1.f then 19 else 19 end end FROM t1 WHERE 19 between e+case when d>(select ~max(t1.d)+max(t1.d*t1.c)-~count(distinct c)-count(*)-count(distinct t1.b)* -(count(*)) from t1) then ~a when not exists(select 1 from t1 where t1.c>=13) or (t1.f=t1.a or c in ((f), -c,t1.e)) and b=b and e not between t1.b and -11 or t1.c in (t1.c,17,t1.c) and t1.f=t1.d then t1.a*t1.d*t1.c else d end and e} +} {} +do_test randexpr-2.1516 { + db eval {SELECT case when not exists(select 1 from t1 where (not case t1.b when d then c else coalesce((select max(b+case c+c when t1.c then coalesce((select ((e)) from t1 where c in (e,t1.f,t1.d)),t1.a) else t1.f end+t1.e) from t1 where not t1.e not between t1.f and t1.a),19) end+f<>b)) then e when f in (19,t1.d, -c) then 19 else case when e>=t1.f then 19 else 19 end end FROM t1 WHERE NOT (19 between e+case when d>(select ~max(t1.d)+max(t1.d*t1.c)-~count(distinct c)-count(*)-count(distinct t1.b)* -(count(*)) from t1) then ~a when not exists(select 1 from t1 where t1.c>=13) or (t1.f=t1.a or c in ((f), -c,t1.e)) and b=b and e not between t1.b and -11 or t1.c in (t1.c,17,t1.c) and t1.f=t1.d then t1.a*t1.d*t1.c else d end and e)} +} {500} +do_test randexpr-2.1517 { + db eval {SELECT (select -+case -(case -max(d) when ~+ -+(count(*)) then abs(max(case 17+t1.a-11-t1.c when 19 then f else e end*((t1.c))+b)) else (min(d)*count(distinct t1.e)) end)++abs(count(*))- -cast(avg(c) AS integer)+max(d) when count(distinct c) then min(f) else (count(distinct a)) end from t1) FROM t1 WHERE ((case -a when case when f between 11 and t1.d then d else c+17 end then b else a end+11-c between -a and t1.a) or b>t1.f and t1.at1.f and t1.a=f) or f in (t1.a,(t1.a),a)) then -~c-d else t1.e end)/abs(13))) FROM t1 WHERE (select (+~max(case when t1.e>=coalesce((select max(t1.d) from t1 where +f not in (coalesce((select 11 from t1 where 13 | c in (select c from t1 union select b from t1)),f),t1.c, -a)),13) then e else 19 end)-min(t1.a)) from t1)+((coalesce((select t1.e from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.c=t1.a))),a)))+13 in (select d from t1 union select t1.a from t1) and e>=b} +} {} +do_test randexpr-2.1520 { + db eval {SELECT -coalesce((select max((select case +count(*)+(case min((abs(d)/abs(b))) when +count(*) | (min(b)) then -min((t1.a)) else max( -t1.a) end*max( -t1.e))+max(f) when (count(*)) then count(distinct 17) else cast(avg((t1.c)) AS integer) end from t1)) from t1 where t1.d in (select 13 from t1 union select t1.c from t1)),(abs(case when ((c>=f) or f in (t1.a,(t1.a),a)) then -~c-d else t1.e end)/abs(13))) FROM t1 WHERE NOT ((select (+~max(case when t1.e>=coalesce((select max(t1.d) from t1 where +f not in (coalesce((select 11 from t1 where 13 | c in (select c from t1 union select b from t1)),f),t1.c, -a)),13) then e else 19 end)-min(t1.a)) from t1)+((coalesce((select t1.e from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.c=t1.a))),a)))+13 in (select d from t1 union select t1.a from t1) and e>=b)} +} {-38} +do_test randexpr-2.1521 { + db eval {SELECT -coalesce((select max((select case +count(*)+(case min((abs(d)/abs(b))) when +count(*) & (min(b)) then -min((t1.a)) else max( -t1.a) end*max( -t1.e))+max(f) when (count(*)) then count(distinct 17) else cast(avg((t1.c)) AS integer) end from t1)) from t1 where t1.d in (select 13 from t1 union select t1.c from t1)),(abs(case when ((c>=f) or f in (t1.a,(t1.a),a)) then -~c-d else t1.e end)/abs(13))) FROM t1 WHERE NOT ((select (+~max(case when t1.e>=coalesce((select max(t1.d) from t1 where +f not in (coalesce((select 11 from t1 where 13 | c in (select c from t1 union select b from t1)),f),t1.c, -a)),13) then e else 19 end)-min(t1.a)) from t1)+((coalesce((select t1.e from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where t1.c=t1.a))),a)))+13 in (select d from t1 union select t1.a from t1) and e>=b)} +} {-38} +do_test randexpr-2.1522 { + db eval {SELECT +(select +abs(+cast(avg(t1.b) AS integer)*abs(case -max( -(t1.a*t1.f)+t1.e* -t1.f*13 | 17 | f+t1.c) when abs(cast(avg(d) AS integer))-(++~min(t1.f) | count(*)-cast(avg(f) AS integer)) then count(*) else cast(avg(13) AS integer) end+ -min(b)))+min(a) from t1) FROM t1 WHERE case t1.a-t1.e*+t1.f-(select abs(count(*)) from t1)+coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where ~t1.b in (select +count(*) | count(distinct case b when t1.a then f else case when (t1.d-t1.b)<11 then t1.d else f end end) from t1 union select +cast(avg(( -d)) AS integer) from t1))),t1.d*t1.a) | e when t1.f then (t1.d) else t1.f end not in (d,f,e)} +} {} +do_test randexpr-2.1523 { + db eval {SELECT +(select +abs(+cast(avg(t1.b) AS integer)*abs(case -max( -(t1.a*t1.f)+t1.e* -t1.f*13 | 17 | f+t1.c) when abs(cast(avg(d) AS integer))-(++~min(t1.f) | count(*)-cast(avg(f) AS integer)) then count(*) else cast(avg(13) AS integer) end+ -min(b)))+min(a) from t1) FROM t1 WHERE NOT (case t1.a-t1.e*+t1.f-(select abs(count(*)) from t1)+coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where ~t1.b in (select +count(*) | count(distinct case b when t1.a then f else case when (t1.d-t1.b)<11 then t1.d else f end end) from t1 union select +cast(avg(( -d)) AS integer) from t1))),t1.d*t1.a) | e when t1.f then (t1.d) else t1.f end not in (d,f,e))} +} {37500} +do_test randexpr-2.1524 { + db eval {SELECT +(select +abs(+cast(avg(t1.b) AS integer)*abs(case -max( -(t1.a*t1.f)+t1.e* -t1.f*13 & 17 & f+t1.c) when abs(cast(avg(d) AS integer))-(++~min(t1.f) & count(*)-cast(avg(f) AS integer)) then count(*) else cast(avg(13) AS integer) end+ -min(b)))+min(a) from t1) FROM t1 WHERE NOT (case t1.a-t1.e*+t1.f-(select abs(count(*)) from t1)+coalesce((select max(t1.c) from t1 where not exists(select 1 from t1 where ~t1.b in (select +count(*) | count(distinct case b when t1.a then f else case when (t1.d-t1.b)<11 then t1.d else f end end) from t1 union select +cast(avg(( -d)) AS integer) from t1))),t1.d*t1.a) | e when t1.f then (t1.d) else t1.f end not in (d,f,e))} +} {37500} +do_test randexpr-2.1525 { + db eval {SELECT t1.d+case when coalesce((select b from t1 where case when (select max(t1.a*(select case count(distinct c) when max(17+c) then - -max(d)-count(*) else cast(avg((e)) AS integer) end from t1)) from t1) not between t1.d and t1.d then t1.d when t1.c not between c and t1.f then ( -t1.d) else t1.d end not between e and t1.e),d)<>17 then (t1.f) when 11=t1.c then 11 else t1.f end*c*t1.a-c FROM t1 WHERE (case when coalesce((select ~coalesce((select max(a) from t1 where 11 in (select ~case -count(*) when cast(avg(d) AS integer) then -max(t1.f) else (count(distinct 11)) end+cast(avg( - -13) AS integer) | count(*)-min(f) from t1 union select count(*) from t1)),t1.b*t1.f*17) from t1 where not exists(select 1 from t1 where t1.a not between d and 11)),b)-17*t1.d+t1.a in ( -t1.c,t1.e,11) then b else t1.d end in (select 17 from t1 union select 13 from t1)) and -t1.a in (select (d) from t1 union select t1.b from t1)} +} {} +do_test randexpr-2.1526 { + db eval {SELECT t1.d+case when coalesce((select b from t1 where case when (select max(t1.a*(select case count(distinct c) when max(17+c) then - -max(d)-count(*) else cast(avg((e)) AS integer) end from t1)) from t1) not between t1.d and t1.d then t1.d when t1.c not between c and t1.f then ( -t1.d) else t1.d end not between e and t1.e),d)<>17 then (t1.f) when 11=t1.c then 11 else t1.f end*c*t1.a-c FROM t1 WHERE NOT ((case when coalesce((select ~coalesce((select max(a) from t1 where 11 in (select ~case -count(*) when cast(avg(d) AS integer) then -max(t1.f) else (count(distinct 11)) end+cast(avg( - -13) AS integer) | count(*)-min(f) from t1 union select count(*) from t1)),t1.b*t1.f*17) from t1 where not exists(select 1 from t1 where t1.a not between d and 11)),b)-17*t1.d+t1.a in ( -t1.c,t1.e,11) then b else t1.d end in (select 17 from t1 union select 13 from t1)) and -t1.a in (select (d) from t1 union select t1.b from t1))} +} {18000100} +do_test randexpr-2.1527 { + db eval {SELECT coalesce((select (abs(b+t1.c)/abs(coalesce((select max( -~t1.d) from t1 where coalesce((select max(11) from t1 where not t1.d>=(select count(*) from t1)),case b-coalesce((select t1.e-f from t1 where coalesce((select max(case a when t1.e then t1.f else 11 end) from t1 where t1.b>=t1.f),t1.d) not in (f,e,13)),t1.f) when -11 then t1.c else 19 end)-d not in (f,f,b)),f))) from t1 where d<=t1.d),f) FROM t1 WHERE c+case when coalesce((select d from t1 where coalesce((select max(17) from t1 where c>17-11),17)=(select count(*) from t1)),case b-coalesce((select t1.e-f from t1 where coalesce((select max(case a when t1.e then t1.f else 11 end) from t1 where t1.b>=t1.f),t1.d) not in (f,e,13)),t1.f) when -11 then t1.c else 19 end)-d not in (f,f,b)),f))) from t1 where d<=t1.d),f) FROM t1 WHERE NOT (c+case when coalesce((select d from t1 where coalesce((select max(17) from t1 where c>17-11),17)f and (exists(select 1 from t1 where (17 in (e, -t1.f,c)) and t1.f<=19))),d))) FROM t1 WHERE f*t1.c<>t1.b} +} {0} +do_test randexpr-2.1530 { + db eval {SELECT (abs(19)/abs(coalesce((select max((abs((abs(t1.a)/abs(e)))/abs(b))) from t1 where not t1.f<13 and 17-(abs(b-13*f*(abs(+17-f+t1.a)/abs(t1.d)))/abs(t1.e))+e-17>f and (exists(select 1 from t1 where (17 in (e, -t1.f,c)) and t1.f<=19))),d))) FROM t1 WHERE NOT (f*t1.c<>t1.b)} +} {} +do_test randexpr-2.1531 { + db eval {SELECT case when t1.d in (select count(distinct 11) from t1 union select case abs(++cast(avg(t1.b) AS integer)+count(*) | -(count(*))) when count(*) then count(distinct t1.b) else count(distinct -t1.a) end | max(t1.c) from t1) and t1.f<=case when exists(select 1 from t1 where t1.f+t1.f<>17 and t1.b>d) then 19 when t1.e=a then coalesce((select b from t1 where 13 not in (t1.b,t1.a,t1.a)),t1.c) else t1.d end and t1.d>(t1.b) and c in (e,t1.d,t1.b) then b | c when f=t1.e then e else 19 end FROM t1 WHERE t1.f between (c-t1.d+t1.f*t1.f) and 11+t1.e*coalesce((select max(coalesce((select max(t1.e) from t1 where exists(select 1 from t1 where (c-13 between t1.e*a and 11 or (t1.f>f) or t1.c>=t1.f))),t1.b-b-11)) from t1 where (f>t1.f)),11)-t1.b*e} +} {} +do_test randexpr-2.1532 { + db eval {SELECT case when t1.d in (select count(distinct 11) from t1 union select case abs(++cast(avg(t1.b) AS integer)+count(*) | -(count(*))) when count(*) then count(distinct t1.b) else count(distinct -t1.a) end | max(t1.c) from t1) and t1.f<=case when exists(select 1 from t1 where t1.f+t1.f<>17 and t1.b>d) then 19 when t1.e=a then coalesce((select b from t1 where 13 not in (t1.b,t1.a,t1.a)),t1.c) else t1.d end and t1.d>(t1.b) and c in (e,t1.d,t1.b) then b | c when f=t1.e then e else 19 end FROM t1 WHERE NOT (t1.f between (c-t1.d+t1.f*t1.f) and 11+t1.e*coalesce((select max(coalesce((select max(t1.e) from t1 where exists(select 1 from t1 where (c-13 between t1.e*a and 11 or (t1.f>f) or t1.c>=t1.f))),t1.b-b-11)) from t1 where (f>t1.f)),11)-t1.b*e)} +} {19} +do_test randexpr-2.1533 { + db eval {SELECT case when t1.d in (select count(distinct 11) from t1 union select case abs(++cast(avg(t1.b) AS integer)+count(*) & -(count(*))) when count(*) then count(distinct t1.b) else count(distinct -t1.a) end & max(t1.c) from t1) and t1.f<=case when exists(select 1 from t1 where t1.f+t1.f<>17 and t1.b>d) then 19 when t1.e=a then coalesce((select b from t1 where 13 not in (t1.b,t1.a,t1.a)),t1.c) else t1.d end and t1.d>(t1.b) and c in (e,t1.d,t1.b) then b & c when f=t1.e then e else 19 end FROM t1 WHERE NOT (t1.f between (c-t1.d+t1.f*t1.f) and 11+t1.e*coalesce((select max(coalesce((select max(t1.e) from t1 where exists(select 1 from t1 where (c-13 between t1.e*a and 11 or (t1.f>f) or t1.c>=t1.f))),t1.b-b-11)) from t1 where (f>t1.f)),11)-t1.b*e)} +} {19} +do_test randexpr-2.1534 { + db eval {SELECT coalesce((select t1.e from t1 where (case when 19>=t1.c then t1.d else coalesce((select max(11*t1.b) from t1 where case ~t1.c-(select max(11) from t1)*~t1.b+f*~coalesce((select max(d) from t1 where d>=b),d)-t1.a*t1.c*t1.d when -t1.c then 13 else f end in (select b from t1 union select 13 from t1)),t1.f) end | b<>a)),t1.e) FROM t1 WHERE not exists(select 1 from t1 where not (t1.et1.b+case (select count(distinct e)*cast(avg(case c when e then case a when f then b else d end-a-13 else 13 end*t1.a+ -t1.d) AS integer) from t1)+c | (t1.f)*f when -c then d else 19 end) and -17 in (select min(t1.b) from t1 union select count(distinct f) from t1))} +} {500} +do_test randexpr-2.1535 { + db eval {SELECT coalesce((select t1.e from t1 where (case when 19>=t1.c then t1.d else coalesce((select max(11*t1.b) from t1 where case ~t1.c-(select max(11) from t1)*~t1.b+f*~coalesce((select max(d) from t1 where d>=b),d)-t1.a*t1.c*t1.d when -t1.c then 13 else f end in (select b from t1 union select 13 from t1)),t1.f) end | b<>a)),t1.e) FROM t1 WHERE NOT (not exists(select 1 from t1 where not (t1.et1.b+case (select count(distinct e)*cast(avg(case c when e then case a when f then b else d end-a-13 else 13 end*t1.a+ -t1.d) AS integer) from t1)+c | (t1.f)*f when -c then d else 19 end) and -17 in (select min(t1.b) from t1 union select count(distinct f) from t1)))} +} {} +do_test randexpr-2.1536 { + db eval {SELECT coalesce((select t1.e from t1 where (case when 19>=t1.c then t1.d else coalesce((select max(11*t1.b) from t1 where case ~t1.c-(select max(11) from t1)*~t1.b+f*~coalesce((select max(d) from t1 where d>=b),d)-t1.a*t1.c*t1.d when -t1.c then 13 else f end in (select b from t1 union select 13 from t1)),t1.f) end & b<>a)),t1.e) FROM t1 WHERE not exists(select 1 from t1 where not (t1.et1.b+case (select count(distinct e)*cast(avg(case c when e then case a when f then b else d end-a-13 else 13 end*t1.a+ -t1.d) AS integer) from t1)+c | (t1.f)*f when -c then d else 19 end) and -17 in (select min(t1.b) from t1 union select count(distinct f) from t1))} +} {500} +do_test randexpr-2.1537 { + db eval {SELECT coalesce((select t1.c from t1 where f between case when (abs(coalesce((select 11* -~coalesce((select a*case coalesce((select max(a) from t1 where exists(select 1 from t1 where e in (17,t1.b,13))), -t1.e) when -a then d else c end from t1 where t1.a>=t1.e),17)+t1.a-t1.d from t1 where exists(select 1 from t1 where -b>t1.b)),e))/abs(d))<>17 then t1.d when 11< -f then d else d end*d and 17),b)-f-t1.d FROM t1 WHERE case when e=(abs(t1.b)/abs((abs(t1.f)/abs( -case b when 19 then ((abs((case when (+case when f between e and c then t1.f when t1.b>19 then t1.e else t1.f end+11+t1.a in (select t1.c from t1 union select f from t1)) then e-(13) when not exists(select 1 from t1 where not exists(select 1 from t1 where (13)>t1.f)) then t1.c else t1.f end))/abs(t1.d))) else c end)))) then b else (t1.d) end not between t1.a and t1.a} +} {-800} +do_test randexpr-2.1538 { + db eval {SELECT coalesce((select t1.c from t1 where f between case when (abs(coalesce((select 11* -~coalesce((select a*case coalesce((select max(a) from t1 where exists(select 1 from t1 where e in (17,t1.b,13))), -t1.e) when -a then d else c end from t1 where t1.a>=t1.e),17)+t1.a-t1.d from t1 where exists(select 1 from t1 where -b>t1.b)),e))/abs(d))<>17 then t1.d when 11< -f then d else d end*d and 17),b)-f-t1.d FROM t1 WHERE NOT (case when e=(abs(t1.b)/abs((abs(t1.f)/abs( -case b when 19 then ((abs((case when (+case when f between e and c then t1.f when t1.b>19 then t1.e else t1.f end+11+t1.a in (select t1.c from t1 union select f from t1)) then e-(13) when not exists(select 1 from t1 where not exists(select 1 from t1 where (13)>t1.f)) then t1.c else t1.f end))/abs(t1.d))) else c end)))) then b else (t1.d) end not between t1.a and t1.a)} +} {} +do_test randexpr-2.1539 { + db eval {SELECT case when not exists(select 1 from t1 where (coalesce((select max(coalesce((select 11 from t1 where t1.b*t1.d<=+case t1.c when (select max(case when not exists(select 1 from t1 where e=t1.b) then t1.a else f end) from t1)*t1.b | t1.a then 17 else 13 end-f | t1.e),13)) from t1 where a in (t1.b,t1.b,(t1.e))),11)*11 not in (d,t1.a,17))) then 13 when c in (select e from t1 union select t1.d from t1) then 19 else 13 end FROM t1 WHERE not exists(select 1 from t1 where case when -b*13>+d then t1.e else coalesce((select case when not exists(select 1 from t1 where 11 in (c,+case when (case when e between t1.b and f then t1.a when t1.c not in (a,(c),t1.a) then -t1.b else t1.a end<>d or f>e) then t1.e else t1.c end,t1.b)) then 19 else -17 end*t1.d from t1 where (17 in (19,17,t1.f))),(t1.e)) end between 11 and t1.b and t1.a<>b)} +} {13} +do_test randexpr-2.1540 { + db eval {SELECT case when not exists(select 1 from t1 where (coalesce((select max(coalesce((select 11 from t1 where t1.b*t1.d<=+case t1.c when (select max(case when not exists(select 1 from t1 where e=t1.b) then t1.a else f end) from t1)*t1.b | t1.a then 17 else 13 end-f | t1.e),13)) from t1 where a in (t1.b,t1.b,(t1.e))),11)*11 not in (d,t1.a,17))) then 13 when c in (select e from t1 union select t1.d from t1) then 19 else 13 end FROM t1 WHERE NOT (not exists(select 1 from t1 where case when -b*13>+d then t1.e else coalesce((select case when not exists(select 1 from t1 where 11 in (c,+case when (case when e between t1.b and f then t1.a when t1.c not in (a,(c),t1.a) then -t1.b else t1.a end<>d or f>e) then t1.e else t1.c end,t1.b)) then 19 else -17 end*t1.d from t1 where (17 in (19,17,t1.f))),(t1.e)) end between 11 and t1.b and t1.a<>b))} +} {} +do_test randexpr-2.1541 { + db eval {SELECT case when not exists(select 1 from t1 where (coalesce((select max(coalesce((select 11 from t1 where t1.b*t1.d<=+case t1.c when (select max(case when not exists(select 1 from t1 where e=t1.b) then t1.a else f end) from t1)*t1.b & t1.a then 17 else 13 end-f & t1.e),13)) from t1 where a in (t1.b,t1.b,(t1.e))),11)*11 not in (d,t1.a,17))) then 13 when c in (select e from t1 union select t1.d from t1) then 19 else 13 end FROM t1 WHERE not exists(select 1 from t1 where case when -b*13>+d then t1.e else coalesce((select case when not exists(select 1 from t1 where 11 in (c,+case when (case when e between t1.b and f then t1.a when t1.c not in (a,(c),t1.a) then -t1.b else t1.a end<>d or f>e) then t1.e else t1.c end,t1.b)) then 19 else -17 end*t1.d from t1 where (17 in (19,17,t1.f))),(t1.e)) end between 11 and t1.b and t1.a<>b)} +} {13} +do_test randexpr-2.1542 { + db eval {SELECT a-coalesce((select max(++19) from t1 where (select count(distinct coalesce((select max(t1.c) from t1 where not (t1.c+t1.c)-case when (not coalesce((select max(t1.a-t1.a) from t1 where t1.d>t1.b),e) in (t1.d,19,(t1.e))) then b when exists(select 1 from t1 where t1.e> -13) then c else e end<>c),17)) from t1) not between 19 and t1.f),t1.b) | 19-t1.d*f+b FROM t1 WHERE t1.f | coalesce((select case when c>=t1.f then t1.e+t1.e when -19 | (a)+t1.f in (b,coalesce((select t1.c | (f+e)-e*17 from t1 where -c not in (t1.d,c,(13))),19),t1.e) then t1.c else 17 end+b from t1 where t1.a not in (17,d,c)),17) in (select f from t1 union select f from t1)} +} {} +do_test randexpr-2.1543 { + db eval {SELECT a-coalesce((select max(++19) from t1 where (select count(distinct coalesce((select max(t1.c) from t1 where not (t1.c+t1.c)-case when (not coalesce((select max(t1.a-t1.a) from t1 where t1.d>t1.b),e) in (t1.d,19,(t1.e))) then b when exists(select 1 from t1 where t1.e> -13) then c else e end<>c),17)) from t1) not between 19 and t1.f),t1.b) | 19-t1.d*f+b FROM t1 WHERE NOT (t1.f | coalesce((select case when c>=t1.f then t1.e+t1.e when -19 | (a)+t1.f in (b,coalesce((select t1.c | (f+e)-e*17 from t1 where -c not in (t1.d,c,(13))),19),t1.e) then t1.c else 17 end+b from t1 where t1.a not in (17,d,c)),17) in (select f from t1 union select f from t1))} +} {-239781} +do_test randexpr-2.1544 { + db eval {SELECT a-coalesce((select max(++19) from t1 where (select count(distinct coalesce((select max(t1.c) from t1 where not (t1.c+t1.c)-case when (not coalesce((select max(t1.a-t1.a) from t1 where t1.d>t1.b),e) in (t1.d,19,(t1.e))) then b when exists(select 1 from t1 where t1.e> -13) then c else e end<>c),17)) from t1) not between 19 and t1.f),t1.b) & 19-t1.d*f+b FROM t1 WHERE NOT (t1.f | coalesce((select case when c>=t1.f then t1.e+t1.e when -19 | (a)+t1.f in (b,coalesce((select t1.c | (f+e)-e*17 from t1 where -c not in (t1.d,c,(13))),19),t1.e) then t1.c else 17 end+b from t1 where t1.a not in (17,d,c)),17) in (select f from t1 union select f from t1))} +} {81} +do_test randexpr-2.1545 { + db eval {SELECT coalesce((select (t1.d) from t1 where not not case when c=case when f<>( -t1.c) then c when 19<>t1.d then t1.f else d end) then e-f when c in (select d from t1 union select f from t1) then a else t1.b end | t1.a-f from t1 union select -19 from t1)),19) then 19 when 11 between f and t1.f then t1.c else 19 end=a),t1.f) FROM t1 WHERE coalesce((select t1.d from t1 where (case when exists(select 1 from t1 where not - -19 in (17,f,t1.b)) and 19>c or t1.c in (select t1.e from t1 union select 17 from t1) then a when exists(select 1 from t1 where (t1.c<>d)) and -t1.c not between b and e then 11 else (select cast(avg((abs(b)/abs(d))) AS integer) from t1) end+t1.d not in (t1.f,11,b) and f not between 17 and t1.d)),t1.e)=t1.a} +} {} +do_test randexpr-2.1546 { + db eval {SELECT coalesce((select (t1.d) from t1 where not not case when c=case when f<>( -t1.c) then c when 19<>t1.d then t1.f else d end) then e-f when c in (select d from t1 union select f from t1) then a else t1.b end | t1.a-f from t1 union select -19 from t1)),19) then 19 when 11 between f and t1.f then t1.c else 19 end=a),t1.f) FROM t1 WHERE NOT (coalesce((select t1.d from t1 where (case when exists(select 1 from t1 where not - -19 in (17,f,t1.b)) and 19>c or t1.c in (select t1.e from t1 union select 17 from t1) then a when exists(select 1 from t1 where (t1.c<>d)) and -t1.c not between b and e then 11 else (select cast(avg((abs(b)/abs(d))) AS integer) from t1) end+t1.d not in (t1.f,11,b) and f not between 17 and t1.d)),t1.e)=t1.a)} +} {600} +do_test randexpr-2.1547 { + db eval {SELECT coalesce((select (t1.d) from t1 where not not case when c=case when f<>( -t1.c) then c when 19<>t1.d then t1.f else d end) then e-f when c in (select d from t1 union select f from t1) then a else t1.b end & t1.a-f from t1 union select -19 from t1)),19) then 19 when 11 between f and t1.f then t1.c else 19 end=a),t1.f) FROM t1 WHERE NOT (coalesce((select t1.d from t1 where (case when exists(select 1 from t1 where not - -19 in (17,f,t1.b)) and 19>c or t1.c in (select t1.e from t1 union select 17 from t1) then a when exists(select 1 from t1 where (t1.c<>d)) and -t1.c not between b and e then 11 else (select cast(avg((abs(b)/abs(d))) AS integer) from t1) end+t1.d not in (t1.f,11,b) and f not between 17 and t1.d)),t1.e)=t1.a)} +} {600} +do_test randexpr-2.1548 { + db eval {SELECT coalesce((select max(case when -++t1.c++(abs(case when t1.bb then 11 else b end) from t1 where ((t1.b)) between e and e),t1.e) FROM t1 WHERE not ~t1.c-(coalesce((select max(~case t1.e | b*11+d+19 when t1.a then t1.b else t1.d end) from t1 where (13 not in (t1.a,t1.a,13))),e)) not between t1.a and 11 or exists(select 1 from t1 where (t1.d) not in (11,13,t1.a) and (c<>b or -13<>t1.b and c in (t1.f, -c,t1.d)))} +} {500} +do_test randexpr-2.1549 { + db eval {SELECT coalesce((select max(case when -++t1.c++(abs(case when t1.bb then 11 else b end) from t1 where ((t1.b)) between e and e),t1.e) FROM t1 WHERE NOT (not ~t1.c-(coalesce((select max(~case t1.e | b*11+d+19 when t1.a then t1.b else t1.d end) from t1 where (13 not in (t1.a,t1.a,13))),e)) not between t1.a and 11 or exists(select 1 from t1 where (t1.d) not in (11,13,t1.a) and (c<>b or -13<>t1.b and c in (t1.f, -c,t1.d))))} +} {} +do_test randexpr-2.1550 { + db eval {SELECT case 19*d-+t1.a | coalesce((select f from t1 where +b between coalesce((select +t1.f from t1 where not exists(select 1 from t1 where case 17 when b then f else f end>=~13)),t1.f) and t1.d),c+11)- -t1.e | 17+case t1.b when t1.a then 17 else t1.f end*t1.c+a when f then -f else t1.f end | t1.b FROM t1 WHERE t1.f=f and not exists(select 1 from t1 where case when t1.b>e then (abs(13)/abs(t1.f | 17))+(t1.f) else ~t1.a-(~e) end in (select count(distinct coalesce((select max(coalesce((select 11 from t1 where t1.a=~13)),t1.f) and t1.d),c+11)- -t1.e | 17+case t1.b when t1.a then 17 else t1.f end*t1.c+a when f then -f else t1.f end | t1.b FROM t1 WHERE NOT (t1.f=f and not exists(select 1 from t1 where case when t1.b>e then (abs(13)/abs(t1.f | 17))+(t1.f) else ~t1.a-(~e) end in (select count(distinct coalesce((select max(coalesce((select 11 from t1 where t1.a=~13)),t1.f) and t1.d),c+11)- -t1.e & 17+case t1.b when t1.a then 17 else t1.f end*t1.c+a when f then -f else t1.f end & t1.b FROM t1 WHERE t1.f=f and not exists(select 1 from t1 where case when t1.b>e then (abs(13)/abs(t1.f | 17))+(t1.f) else ~t1.a-(~e) end in (select count(distinct coalesce((select max(coalesce((select 11 from t1 where t1.a=t1.e and e>f then 11 | 19 else t1.c end | b in (select a from t1 union select 13 from t1)),b)+t1.b | (d)*11)/abs(e)) from t1 where a=19),t1.e)*13) from t1 where 13>f),t1.f)) FROM t1 WHERE coalesce((select max(~t1.a*t1.f*t1.b+f+a) from t1 where case when d in (select -+count(distinct (t1.c))*max(t1.e+b)-(( -count(distinct 17))) from t1 union select -count(distinct t1.d) from t1) then t1.d else (abs(case when t1.e in (select t1.c from t1 union select c from t1) then c else d end)/abs(f)) end in (select max( -c) from t1 union select abs(count(distinct 19)) from t1)), -a) not in (d,t1.f,13)} +} {600} +do_test randexpr-2.1554 { + db eval {SELECT (coalesce((select max(coalesce((select (abs(t1.e* -b*coalesce((select max( -t1.e*t1.e+t1.f) from t1 where -case when b>=t1.e and e>f then 11 | 19 else t1.c end | b in (select a from t1 union select 13 from t1)),b)+t1.b | (d)*11)/abs(e)) from t1 where a=19),t1.e)*13) from t1 where 13>f),t1.f)) FROM t1 WHERE NOT (coalesce((select max(~t1.a*t1.f*t1.b+f+a) from t1 where case when d in (select -+count(distinct (t1.c))*max(t1.e+b)-(( -count(distinct 17))) from t1 union select -count(distinct t1.d) from t1) then t1.d else (abs(case when t1.e in (select t1.c from t1 union select c from t1) then c else d end)/abs(f)) end in (select max( -c) from t1 union select abs(count(distinct 19)) from t1)), -a) not in (d,t1.f,13))} +} {} +do_test randexpr-2.1555 { + db eval {SELECT (coalesce((select max(coalesce((select (abs(t1.e* -b*coalesce((select max( -t1.e*t1.e+t1.f) from t1 where -case when b>=t1.e and e>f then 11 & 19 else t1.c end & b in (select a from t1 union select 13 from t1)),b)+t1.b & (d)*11)/abs(e)) from t1 where a=19),t1.e)*13) from t1 where 13>f),t1.f)) FROM t1 WHERE coalesce((select max(~t1.a*t1.f*t1.b+f+a) from t1 where case when d in (select -+count(distinct (t1.c))*max(t1.e+b)-(( -count(distinct 17))) from t1 union select -count(distinct t1.d) from t1) then t1.d else (abs(case when t1.e in (select t1.c from t1 union select c from t1) then c else d end)/abs(f)) end in (select max( -c) from t1 union select abs(count(distinct 19)) from t1)), -a) not in (d,t1.f,13)} +} {600} +do_test randexpr-2.1556 { + db eval {SELECT +(abs(17*(abs(a | t1.a)/abs(11)) | f)/abs(coalesce((select +t1.b+~a from t1 where case when a=t1.b then c when t1.d=t1.e then t1.b else 17 end<=t1.f and (b<>13) or t1.a<>a or t1.d>d and 11 between 17 and t1.a and t1.b<> -e and -13<(17)),a)+ -t1.e))*(t1.c) FROM t1 WHERE not a not between t1.a and 11+ -coalesce((select -c*coalesce((select max(~f*a+11-t1.a | -a+t1.a*t1.b*f) from t1 where 11=11),t1.a)+d from t1 where 13>=e),d) | t1.b or t1.a not between -b and f or 17<>13} +} {300} +do_test randexpr-2.1557 { + db eval {SELECT +(abs(17*(abs(a | t1.a)/abs(11)) | f)/abs(coalesce((select +t1.b+~a from t1 where case when a=t1.b then c when t1.d=t1.e then t1.b else 17 end<=t1.f and (b<>13) or t1.a<>a or t1.d>d and 11 between 17 and t1.a and t1.b<> -e and -13<(17)),a)+ -t1.e))*(t1.c) FROM t1 WHERE NOT (not a not between t1.a and 11+ -coalesce((select -c*coalesce((select max(~f*a+11-t1.a | -a+t1.a*t1.b*f) from t1 where 11=11),t1.a)+d from t1 where 13>=e),d) | t1.b or t1.a not between -b and f or 17<>13)} +} {} +do_test randexpr-2.1558 { + db eval {SELECT +(abs(17*(abs(a & t1.a)/abs(11)) & f)/abs(coalesce((select +t1.b+~a from t1 where case when a=t1.b then c when t1.d=t1.e then t1.b else 17 end<=t1.f and (b<>13) or t1.a<>a or t1.d>d and 11 between 17 and t1.a and t1.b<> -e and -13<(17)),a)+ -t1.e))*(t1.c) FROM t1 WHERE not a not between t1.a and 11+ -coalesce((select -c*coalesce((select max(~f*a+11-t1.a | -a+t1.a*t1.b*f) from t1 where 11=11),t1.a)+d from t1 where 13>=e),d) | t1.b or t1.a not between -b and f or 17<>13} +} {0} +do_test randexpr-2.1559 { + db eval {SELECT b-case e*13+case when not not t1.d in (select t1.b from t1 union select f from t1) then t1.c when coalesce((select max(coalesce((select (select ~min(coalesce((select max(a*f) from t1 where t1.f<=t1.b or a<=f),t1.a)) | -(count(distinct 19)) from t1) from t1 where f between (t1.f) and 11),a)) from t1 where 11 not in (f, -11,19)),e)>=d then t1.f else t1.c end when -a then 11 else t1.e end FROM t1 WHERE coalesce((select case case when case when (coalesce((select max(t1.e) from t1 where c>c and -19>= -a),d) not in (11,t1.b,t1.a)) then d else a end between 11 and t1.c then b else a end+13-t1.a when t1.d then (b) else t1.d end from t1 where b between e and t1.f),11) in (select (+abs(count(*)+case -count(distinct t1.e) when -(max(19)) then (count(distinct 19)) else -count(distinct e) end-max(t1.b)) | count(distinct t1.e) | (cast(avg(11) AS integer))) from t1 union select cast(avg(c) AS integer) from t1)} +} {} +do_test randexpr-2.1560 { + db eval {SELECT b-case e*13+case when not not t1.d in (select t1.b from t1 union select f from t1) then t1.c when coalesce((select max(coalesce((select (select ~min(coalesce((select max(a*f) from t1 where t1.f<=t1.b or a<=f),t1.a)) | -(count(distinct 19)) from t1) from t1 where f between (t1.f) and 11),a)) from t1 where 11 not in (f, -11,19)),e)>=d then t1.f else t1.c end when -a then 11 else t1.e end FROM t1 WHERE NOT (coalesce((select case case when case when (coalesce((select max(t1.e) from t1 where c>c and -19>= -a),d) not in (11,t1.b,t1.a)) then d else a end between 11 and t1.c then b else a end+13-t1.a when t1.d then (b) else t1.d end from t1 where b between e and t1.f),11) in (select (+abs(count(*)+case -count(distinct t1.e) when -(max(19)) then (count(distinct 19)) else -count(distinct e) end-max(t1.b)) | count(distinct t1.e) | (cast(avg(11) AS integer))) from t1 union select cast(avg(c) AS integer) from t1))} +} {-300} +do_test randexpr-2.1561 { + db eval {SELECT b-case e*13+case when not not t1.d in (select t1.b from t1 union select f from t1) then t1.c when coalesce((select max(coalesce((select (select ~min(coalesce((select max(a*f) from t1 where t1.f<=t1.b or a<=f),t1.a)) & -(count(distinct 19)) from t1) from t1 where f between (t1.f) and 11),a)) from t1 where 11 not in (f, -11,19)),e)>=d then t1.f else t1.c end when -a then 11 else t1.e end FROM t1 WHERE NOT (coalesce((select case case when case when (coalesce((select max(t1.e) from t1 where c>c and -19>= -a),d) not in (11,t1.b,t1.a)) then d else a end between 11 and t1.c then b else a end+13-t1.a when t1.d then (b) else t1.d end from t1 where b between e and t1.f),11) in (select (+abs(count(*)+case -count(distinct t1.e) when -(max(19)) then (count(distinct 19)) else -count(distinct e) end-max(t1.b)) | count(distinct t1.e) | (cast(avg(11) AS integer))) from t1 union select cast(avg(c) AS integer) from t1))} +} {-300} +do_test randexpr-2.1562 { + db eval {SELECT coalesce((select case when a not in (~17,a,c) then b when t1.c<>t1.f-13 then +f else 11 end+t1.e*t1.a+case when ((a-c)>case when (exists(select 1 from t1 where (c) between d and -t1.b)) then a+t1.f else f end) or e between t1.c and 13 then -t1.c else t1.e end-t1.d from t1 where ( -17=a)),e) FROM t1 WHERE +case when not exists(select 1 from t1 where f+(select ~ -min(b) | abs(+max(+c)) from t1)+b not between 13-a*17 and t1.e-t1.b) then t1.a when b not between ((11)) and 11 then 13 else 17 end+ - -t1.f in (f,t1.d,f) or t1.b>t1.a and not exists(select 1 from t1 where t1.d in (t1.c,d,t1.c))} +} {} +do_test randexpr-2.1563 { + db eval {SELECT coalesce((select case when a not in (~17,a,c) then b when t1.c<>t1.f-13 then +f else 11 end+t1.e*t1.a+case when ((a-c)>case when (exists(select 1 from t1 where (c) between d and -t1.b)) then a+t1.f else f end) or e between t1.c and 13 then -t1.c else t1.e end-t1.d from t1 where ( -17=a)),e) FROM t1 WHERE NOT (+case when not exists(select 1 from t1 where f+(select ~ -min(b) | abs(+max(+c)) from t1)+b not between 13-a*17 and t1.e-t1.b) then t1.a when b not between ((11)) and 11 then 13 else 17 end+ - -t1.f in (f,t1.d,f) or t1.b>t1.a and not exists(select 1 from t1 where t1.d in (t1.c,d,t1.c)))} +} {500} +do_test randexpr-2.1564 { + db eval {SELECT case coalesce((select 19-case when case when f in (select t1.c from t1 union select (select count(*) from t1) from t1) then a+e else 19 end*19-19-13 not in (11,19,a) then f when (13<>(t1.c) or d>e and b=b) then t1.a else 13 end from t1 where (not exists(select 1 from t1 where not exists(select 1 from t1 where t1.a=17)))),a) when t1.d then 19 else e end FROM t1 WHERE 13-coalesce((select (abs(19)/abs(11)) from t1 where case when a in (select d from t1 union select case when -11-11<>d or t1.e between (t1.d) and b then t1.f else f end from t1) then t1.e else -a end not between 13 and 19 or exists(select 1 from t1 where f< -( -t1.d)) and t1.a not between -e and t1.e or t1.f(t1.f)),t1.d)=11} +} {} +do_test randexpr-2.1565 { + db eval {SELECT case coalesce((select 19-case when case when f in (select t1.c from t1 union select (select count(*) from t1) from t1) then a+e else 19 end*19-19-13 not in (11,19,a) then f when (13<>(t1.c) or d>e and b=b) then t1.a else 13 end from t1 where (not exists(select 1 from t1 where not exists(select 1 from t1 where t1.a=17)))),a) when t1.d then 19 else e end FROM t1 WHERE NOT (13-coalesce((select (abs(19)/abs(11)) from t1 where case when a in (select d from t1 union select case when -11-11<>d or t1.e between (t1.d) and b then t1.f else f end from t1) then t1.e else -a end not between 13 and 19 or exists(select 1 from t1 where f< -( -t1.d)) and t1.a not between -e and t1.e or t1.f(t1.f)),t1.d)=11)} +} {500} +do_test randexpr-2.1566 { + db eval {SELECT (select -count(distinct -case (select (max( -c-t1.b+~f)*count(distinct 11) | +cast(avg(11) AS integer)-min(t1.f)+ -(cast(avg(( -11)) AS integer))-count(distinct t1.d)*(max(13))*(max(d))-(count(*))-min(e)) from t1) when + -c then t1.d else t1.b*19 end-a | t1.d+t1.d) from t1) FROM t1 WHERE not 11-t1.a=a+11} +} {-1} +do_test randexpr-2.1567 { + db eval {SELECT (select -count(distinct -case (select (max( -c-t1.b+~f)*count(distinct 11) | +cast(avg(11) AS integer)-min(t1.f)+ -(cast(avg(( -11)) AS integer))-count(distinct t1.d)*(max(13))*(max(d))-(count(*))-min(e)) from t1) when + -c then t1.d else t1.b*19 end-a | t1.d+t1.d) from t1) FROM t1 WHERE NOT (not 11-t1.a=a+11)} +} {} +do_test randexpr-2.1568 { + db eval {SELECT (select -count(distinct -case (select (max( -c-t1.b+~f)*count(distinct 11) & +cast(avg(11) AS integer)-min(t1.f)+ -(cast(avg(( -11)) AS integer))-count(distinct t1.d)*(max(13))*(max(d))-(count(*))-min(e)) from t1) when + -c then t1.d else t1.b*19 end-a & t1.d+t1.d) from t1) FROM t1 WHERE not 11-t1.a=a+11} +} {-1} +do_test randexpr-2.1569 { + db eval {SELECT (select ~count(distinct t1.d*e+19)+abs(+cast(avg((select (count(*)) from t1)) AS integer)-cast(avg(t1.c) AS integer) | min(case when d | f* -19 in (select min(c) from t1 union select ~count(*)-max(17) from t1) then t1.e when (t1.b between 17 and (b)) then t1.d else t1.d end)*cast(avg(e) AS integer))-count(distinct t1.f) | cast(avg( -d) AS integer)*cast(avg(f) AS integer) from t1)*t1.e FROM t1 WHERE coalesce((select 17 from t1 where coalesce((select max(case when 13-b+coalesce((select case when (f>a) then t1.f when t1.c<=19 then a else a end from t1 where c in (select (e) from t1 union select 13 from t1)),13)<13 then 13 else t1.b end) from t1 where (13)<>13),17) in (select +min(b) from t1 union select ~max(t1.d)*max( -t1.b)*min(t1.e) from t1) and e>c),f) between ((t1.f)) and b and t1.a=19} +} {} +do_test randexpr-2.1570 { + db eval {SELECT (select ~count(distinct t1.d*e+19)+abs(+cast(avg((select (count(*)) from t1)) AS integer)-cast(avg(t1.c) AS integer) | min(case when d | f* -19 in (select min(c) from t1 union select ~count(*)-max(17) from t1) then t1.e when (t1.b between 17 and (b)) then t1.d else t1.d end)*cast(avg(e) AS integer))-count(distinct t1.f) | cast(avg( -d) AS integer)*cast(avg(f) AS integer) from t1)*t1.e FROM t1 WHERE NOT (coalesce((select 17 from t1 where coalesce((select max(case when 13-b+coalesce((select case when (f>a) then t1.f when t1.c<=19 then a else a end from t1 where c in (select (e) from t1 union select 13 from t1)),13)<13 then 13 else t1.b end) from t1 where (13)<>13),17) in (select +min(b) from t1 union select ~max(t1.d)*max( -t1.b)*min(t1.e) from t1) and e>c),f) between ((t1.f)) and b and t1.a=19)} +} {-119980000} +do_test randexpr-2.1571 { + db eval {SELECT (select ~count(distinct t1.d*e+19)+abs(+cast(avg((select (count(*)) from t1)) AS integer)-cast(avg(t1.c) AS integer) & min(case when d & f* -19 in (select min(c) from t1 union select ~count(*)-max(17) from t1) then t1.e when (t1.b between 17 and (b)) then t1.d else t1.d end)*cast(avg(e) AS integer))-count(distinct t1.f) & cast(avg( -d) AS integer)*cast(avg(f) AS integer) from t1)*t1.e FROM t1 WHERE NOT (coalesce((select 17 from t1 where coalesce((select max(case when 13-b+coalesce((select case when (f>a) then t1.f when t1.c<=19 then a else a end from t1 where c in (select (e) from t1 union select 13 from t1)),13)<13 then 13 else t1.b end) from t1 where (13)<>13),17) in (select +min(b) from t1 union select ~max(t1.d)*max( -t1.b)*min(t1.e) from t1) and e>c),f) between ((t1.f)) and b and t1.a=19)} +} {512000} +do_test randexpr-2.1572 { + db eval {SELECT coalesce((select d from t1 where case when (17 between c+t1.d-t1.a and b and t1.b in (13,t1.d,19)) then case when t1.c<(a) then t1.c when t1.e not in (a,11,(t1.d)) then t1.d else d end else t1.a end in (select abs(min(a) | ~~count(distinct t1.e)+min(b)-count(*)) from t1 union select count(*) from t1) and not exists(select 1 from t1 where (t1.a) between t1.a and t1.d)),t1.f)-t1.a FROM t1 WHERE case when t1.e not in (coalesce((select max(coalesce((select max(b+t1.c-19*(e)-~11) from t1 where t1.a in (select ~cast(avg(~t1.a) AS integer) from t1 union select abs(~cast(avg(f) AS integer)) from t1)),e)* -c-c-b-t1.d-f) from t1 where t1.f>=t1.c),((t1.d)))- - -19,17,t1.b) then b else t1.f end=t1.c),((t1.d)))- - -19,17,t1.b) then b else t1.f end=t1.c),((t1.d)))- - -19,17,t1.b) then b else t1.f end=(t1.f)+a then t1.d else 19 end and t1.c or exists(select 1 from t1 where (b in (13,13,b)) and (t1.f<>t1.e)) or (13)<>17 and e<=f and e<= -c) and t1.f>f then t1.e*19-t1.e-b else 17 end from t1)} +} {} +do_test randexpr-2.1576 { + db eval {SELECT (abs((select min(t1.a)*~+ -count(*)-max(t1.f) from t1))/abs((abs(13*~t1.c- -e-( -19) | case 17*~13 when t1.c+case when not 19 between 13 and a then t1.c when -11 not between e and 17 then 19 else a end then 19 else 17 end*19)/abs(t1.d)))) FROM t1 WHERE NOT (t1.e in (select d from t1 union select case when not exists(select 1 from t1 where c+a*17 not between case when t1.f>=(t1.f)+a then t1.d else 19 end and t1.c or exists(select 1 from t1 where (b in (13,13,b)) and (t1.f<>t1.e)) or (13)<>17 and e<=f and e<= -c) and t1.f>f then t1.e*19-t1.e-b else 17 end from t1))} +} {85} +do_test randexpr-2.1577 { + db eval {SELECT b-t1.b-coalesce((select (abs(case t1.c+coalesce((select +17*case when b in (select abs(max(19) | count(distinct t1.e)) | cast(avg(t1.d) AS integer) from t1 union select (count(*)) from t1) then +11+t1.a when 11e)),d) FROM t1 WHERE t1.a<> -a} +} {0} +do_test randexpr-2.1578 { + db eval {SELECT b-t1.b-coalesce((select (abs(case t1.c+coalesce((select +17*case when b in (select abs(max(19) | count(distinct t1.e)) | cast(avg(t1.d) AS integer) from t1 union select (count(*)) from t1) then +11+t1.a when 11e)),d) FROM t1 WHERE NOT (t1.a<> -a)} +} {} +do_test randexpr-2.1579 { + db eval {SELECT b-t1.b-coalesce((select (abs(case t1.c+coalesce((select +17*case when b in (select abs(max(19) & count(distinct t1.e)) & cast(avg(t1.d) AS integer) from t1 union select (count(*)) from t1) then +11+t1.a when 11e)),d) FROM t1 WHERE t1.a<> -a} +} {0} +do_test randexpr-2.1580 { + db eval {SELECT ~(abs(b*t1.b)/abs(case when coalesce((select max((abs(a)/abs(case t1.e when t1.e then c*(t1.d) else t1.a end))) from t1 where b in (select min((t1.a)) from t1 union select + -max(b) from t1)),19)+a not between t1.e and -19 and 13<=a then (select case cast(avg((a)) AS integer) when min(e)*max(f) then -(count(distinct 13)) else cast(avg(13) AS integer) end-count(*) | count(distinct d) | -count(*) from t1) else b end)) FROM t1 WHERE f not between t1.d and b} +} {-40001} +do_test randexpr-2.1581 { + db eval {SELECT ~(abs(b*t1.b)/abs(case when coalesce((select max((abs(a)/abs(case t1.e when t1.e then c*(t1.d) else t1.a end))) from t1 where b in (select min((t1.a)) from t1 union select + -max(b) from t1)),19)+a not between t1.e and -19 and 13<=a then (select case cast(avg((a)) AS integer) when min(e)*max(f) then -(count(distinct 13)) else cast(avg(13) AS integer) end-count(*) | count(distinct d) | -count(*) from t1) else b end)) FROM t1 WHERE NOT (f not between t1.d and b)} +} {} +do_test randexpr-2.1582 { + db eval {SELECT +(abs(19)/abs(d | 11*t1.f))*t1.e-coalesce((select t1.b from t1 where not ((f*case when a>=17 then t1.c else (a) end-b not in (t1.b,t1.f,t1.f) or not exists(select 1 from t1 where t1.c>t1.a) and c not in (t1.d,t1.b,c)))),e) | coalesce((select ( - -f) from t1 where 19 not between 17 and 17),(a))-17*d*c FROM t1 WHERE t1.b>=e} +} {} +do_test randexpr-2.1583 { + db eval {SELECT +(abs(19)/abs(d | 11*t1.f))*t1.e-coalesce((select t1.b from t1 where not ((f*case when a>=17 then t1.c else (a) end-b not in (t1.b,t1.f,t1.f) or not exists(select 1 from t1 where t1.c>t1.a) and c not in (t1.d,t1.b,c)))),e) | coalesce((select ( - -f) from t1 where 19 not between 17 and 17),(a))-17*d*c FROM t1 WHERE NOT (t1.b>=e)} +} {-100} +do_test randexpr-2.1584 { + db eval {SELECT +(abs(19)/abs(d & 11*t1.f))*t1.e-coalesce((select t1.b from t1 where not ((f*case when a>=17 then t1.c else (a) end-b not in (t1.b,t1.f,t1.f) or not exists(select 1 from t1 where t1.c>t1.a) and c not in (t1.d,t1.b,c)))),e) & coalesce((select ( - -f) from t1 where 19 not between 17 and 17),(a))-17*d*c FROM t1 WHERE NOT (t1.b>=e)} +} {-2039800} +do_test randexpr-2.1585 { + db eval {SELECT (abs((abs(a)/abs(~17+t1.b-e+(abs(a)/abs(coalesce((select max(13) from t1 where c not in (c-(abs(+coalesce((select max(t1.b-f) from t1 where (abs(13+case ~t1.f when t1.c then t1.b else b end-e)/abs(c))-t1.e>t1.c),t1.c))/abs(11))+t1.b,t1.a,11)),t1.a)))))+19)/abs( - -t1.c)) FROM t1 WHERE ~t1.e+t1.a+(abs(case when d+e+17*~t1.a-t1.a-a*~(abs(~f)/abs( -13))*+(t1.c | a)*t1.b=e then t1.d when ( -e) not between c and -d then -(t1.f) else t1.b end)/abs(19))>t1.f and 11<(11)} +} {} +do_test randexpr-2.1586 { + db eval {SELECT (abs((abs(a)/abs(~17+t1.b-e+(abs(a)/abs(coalesce((select max(13) from t1 where c not in (c-(abs(+coalesce((select max(t1.b-f) from t1 where (abs(13+case ~t1.f when t1.c then t1.b else b end-e)/abs(c))-t1.e>t1.c),t1.c))/abs(11))+t1.b,t1.a,11)),t1.a)))))+19)/abs( - -t1.c)) FROM t1 WHERE NOT (~t1.e+t1.a+(abs(case when d+e+17*~t1.a-t1.a-a*~(abs(~f)/abs( -13))*+(t1.c | a)*t1.b=e then t1.d when ( -e) not between c and -d then -(t1.f) else t1.b end)/abs(19))>t1.f and 11<(11))} +} {0} +do_test randexpr-2.1587 { + db eval {SELECT (abs((abs( -t1.e)/abs(~17+b)))/abs((case 19 when case when t1.b in (select ~cast(avg(19) AS integer) from t1 union select max(t1.b) from t1) then case when case when exists(select 1 from t1 where t1.c not between d and e) then (11) when t1.d<11 then ( -t1.f) else c end in (select count(distinct 17) from t1 union select ~min(a) | max( -t1.a)- -min(b) from t1) then d else 17 end when 13> -t1.b then f else d end then (t1.b) else c end))) FROM t1 WHERE d in (b,+(abs(t1.b | t1.e)/abs(coalesce((select max(t1.b) from t1 where t1.f=(e*+t1.b-t1.d+b-t1.f-t1.a-case case a*t1.b when coalesce((select max(f) from t1 where c<11),(a)) then -t1.b else t1.f end when e then d else 19 end*t1.e+19)*d),t1.b))),t1.b)} +} {} +do_test randexpr-2.1588 { + db eval {SELECT (abs((abs( -t1.e)/abs(~17+b)))/abs((case 19 when case when t1.b in (select ~cast(avg(19) AS integer) from t1 union select max(t1.b) from t1) then case when case when exists(select 1 from t1 where t1.c not between d and e) then (11) when t1.d<11 then ( -t1.f) else c end in (select count(distinct 17) from t1 union select ~min(a) | max( -t1.a)- -min(b) from t1) then d else 17 end when 13> -t1.b then f else d end then (t1.b) else c end))) FROM t1 WHERE NOT (d in (b,+(abs(t1.b | t1.e)/abs(coalesce((select max(t1.b) from t1 where t1.f=(e*+t1.b-t1.d+b-t1.f-t1.a-case case a*t1.b when coalesce((select max(f) from t1 where c<11),(a)) then -t1.b else t1.f end when e then d else 19 end*t1.e+19)*d),t1.b))),t1.b))} +} {0} +do_test randexpr-2.1589 { + db eval {SELECT (abs((abs( -t1.e)/abs(~17+b)))/abs((case 19 when case when t1.b in (select ~cast(avg(19) AS integer) from t1 union select max(t1.b) from t1) then case when case when exists(select 1 from t1 where t1.c not between d and e) then (11) when t1.d<11 then ( -t1.f) else c end in (select count(distinct 17) from t1 union select ~min(a) & max( -t1.a)- -min(b) from t1) then d else 17 end when 13> -t1.b then f else d end then (t1.b) else c end))) FROM t1 WHERE NOT (d in (b,+(abs(t1.b | t1.e)/abs(coalesce((select max(t1.b) from t1 where t1.f=(e*+t1.b-t1.d+b-t1.f-t1.a-case case a*t1.b when coalesce((select max(f) from t1 where c<11),(a)) then -t1.b else t1.f end when e then d else 19 end*t1.e+19)*d),t1.b))),t1.b))} +} {0} +do_test randexpr-2.1590 { + db eval {SELECT c | case when e<=(abs(case when case when not exists(select 1 from t1 where case when t1.f>case when 19>=17 or f in (19,c,t1.d) then t1.b else b end then t1.e else -t1.b end*t1.d in (select t1.e from t1 union select c from t1)) then e else f end<>t1.d then -a when (11 in (select b from t1 union select a from t1)) then 19 else t1.a end-(c))/abs(c))+t1.d | t1.a then -19 else 17 end+t1.d-(t1.a) FROM t1 WHERE coalesce((select 13 from t1 where not exists(select 1 from t1 where t1.e*t1.d*t1.f>=(11) and d in (13,coalesce((select t1.f+t1.b from t1 where coalesce((select max(t1.a) from t1 where not (t1.d)<=t1.c),c) not in (t1.e,t1.d,b)),b)+f,d)) or (t1.f>f) or 11<=t1.d and 17<>13),a)<(t1.a)} +} {317} +do_test randexpr-2.1591 { + db eval {SELECT c | case when e<=(abs(case when case when not exists(select 1 from t1 where case when t1.f>case when 19>=17 or f in (19,c,t1.d) then t1.b else b end then t1.e else -t1.b end*t1.d in (select t1.e from t1 union select c from t1)) then e else f end<>t1.d then -a when (11 in (select b from t1 union select a from t1)) then 19 else t1.a end-(c))/abs(c))+t1.d | t1.a then -19 else 17 end+t1.d-(t1.a) FROM t1 WHERE NOT (coalesce((select 13 from t1 where not exists(select 1 from t1 where t1.e*t1.d*t1.f>=(11) and d in (13,coalesce((select t1.f+t1.b from t1 where coalesce((select max(t1.a) from t1 where not (t1.d)<=t1.c),c) not in (t1.e,t1.d,b)),b)+f,d)) or (t1.f>f) or 11<=t1.d and 17<>13),a)<(t1.a))} +} {} +do_test randexpr-2.1592 { + db eval {SELECT c & case when e<=(abs(case when case when not exists(select 1 from t1 where case when t1.f>case when 19>=17 or f in (19,c,t1.d) then t1.b else b end then t1.e else -t1.b end*t1.d in (select t1.e from t1 union select c from t1)) then e else f end<>t1.d then -a when (11 in (select b from t1 union select a from t1)) then 19 else t1.a end-(c))/abs(c))+t1.d & t1.a then -19 else 17 end+t1.d-(t1.a) FROM t1 WHERE coalesce((select 13 from t1 where not exists(select 1 from t1 where t1.e*t1.d*t1.f>=(11) and d in (13,coalesce((select t1.f+t1.b from t1 where coalesce((select max(t1.a) from t1 where not (t1.d)<=t1.c),c) not in (t1.e,t1.d,b)),b)+f,d)) or (t1.f>f) or 11<=t1.d and 17<>13),a)<(t1.a)} +} {300} +do_test randexpr-2.1593 { + db eval {SELECT -+t1.f*coalesce((select 17 from t1 where b in (coalesce((select f- -11 from t1 where not exists(select 1 from t1 where t1.d*a<=(case when -17=d-coalesce((select a from t1 where coalesce((select max(19) from t1 where case when 13 between coalesce((select max(b) from t1 where t1.e in (c,t1.a,17)),(a)) and ((17)) then t1.b when f=t1.b then t1.f else 17 end>t1.b),e)+b*a>=t1.a),c))} +} {} +do_test randexpr-2.1594 { + db eval {SELECT -+t1.f*coalesce((select 17 from t1 where b in (coalesce((select f- -11 from t1 where not exists(select 1 from t1 where t1.d*a<=(case when -17=d-coalesce((select a from t1 where coalesce((select max(19) from t1 where case when 13 between coalesce((select max(b) from t1 where t1.e in (c,t1.a,17)),(a)) and ((17)) then t1.b when f=t1.b then t1.f else 17 end>t1.b),e)+b*a>=t1.a),c)))} +} {-360489} +do_test randexpr-2.1595 { + db eval {SELECT -+t1.f*coalesce((select 17 from t1 where b in (coalesce((select f- -11 from t1 where not exists(select 1 from t1 where t1.d*a<=(case when -17=d-coalesce((select a from t1 where coalesce((select max(19) from t1 where case when 13 between coalesce((select max(b) from t1 where t1.e in (c,t1.a,17)),(a)) and ((17)) then t1.b when f=t1.b then t1.f else 17 end>t1.b),e)+b*a>=t1.a),c)))} +} {-360489} +do_test randexpr-2.1596 { + db eval {SELECT ~f+coalesce((select max(17+~a+t1.b) from t1 where 17>t1.c),c+case when t1.f*d not between t1.f-13 and ~t1.b then 19 when t1.a between case coalesce((select 17 from t1 where (e in (f,e,t1.b))),13) | t1.a* - -c*t1.f-a+a when e then t1.a else 13 end and b then b else e end)-11 FROM t1 WHERE 17=19*~d-case when (exists(select 1 from t1 where 17-e not between t1.b and f) or -f not in ( -13,b,c) and t1.f not between t1.f and 13) then 13 else coalesce((select t1.f from t1 where 11 not in (a,(e),t1.f)),(t1.c)) end+t1.c or 17 in (select +(count(*)) from t1 union select ~+case -min(t1.b) when case case max(19) when cast(avg((b)) AS integer) then (count(distinct t1.b)) else -cast(avg(t1.b) AS integer) end when ( -max(t1.e)) then max(17) else -count(distinct t1.f) end then cast(avg(19) AS integer) else count(*) end-count(*) | -cast(avg(11) AS integer) from t1)} +} {} +do_test randexpr-2.1597 { + db eval {SELECT ~f+coalesce((select max(17+~a+t1.b) from t1 where 17>t1.c),c+case when t1.f*d not between t1.f-13 and ~t1.b then 19 when t1.a between case coalesce((select 17 from t1 where (e in (f,e,t1.b))),13) | t1.a* - -c*t1.f-a+a when e then t1.a else 13 end and b then b else e end)-11 FROM t1 WHERE NOT (17=19*~d-case when (exists(select 1 from t1 where 17-e not between t1.b and f) or -f not in ( -13,b,c) and t1.f not between t1.f and 13) then 13 else coalesce((select t1.f from t1 where 11 not in (a,(e),t1.f)),(t1.c)) end+t1.c or 17 in (select +(count(*)) from t1 union select ~+case -min(t1.b) when case case max(19) when cast(avg((b)) AS integer) then (count(distinct t1.b)) else -cast(avg(t1.b) AS integer) end when ( -max(t1.e)) then max(17) else -count(distinct t1.f) end then cast(avg(19) AS integer) else count(*) end-count(*) | -cast(avg(11) AS integer) from t1))} +} {-293} +do_test randexpr-2.1598 { + db eval {SELECT ~f+coalesce((select max(17+~a+t1.b) from t1 where 17>t1.c),c+case when t1.f*d not between t1.f-13 and ~t1.b then 19 when t1.a between case coalesce((select 17 from t1 where (e in (f,e,t1.b))),13) & t1.a* - -c*t1.f-a+a when e then t1.a else 13 end and b then b else e end)-11 FROM t1 WHERE NOT (17=19*~d-case when (exists(select 1 from t1 where 17-e not between t1.b and f) or -f not in ( -13,b,c) and t1.f not between t1.f and 13) then 13 else coalesce((select t1.f from t1 where 11 not in (a,(e),t1.f)),(t1.c)) end+t1.c or 17 in (select +(count(*)) from t1 union select ~+case -min(t1.b) when case case max(19) when cast(avg((b)) AS integer) then (count(distinct t1.b)) else -cast(avg(t1.b) AS integer) end when ( -max(t1.e)) then max(17) else -count(distinct t1.f) end then cast(avg(19) AS integer) else count(*) end-count(*) | -cast(avg(11) AS integer) from t1))} +} {-293} +do_test randexpr-2.1599 { + db eval {SELECT (case when (select count(*) from t1)++t1.d+b*t1.e | t1.a+coalesce((select max(t1.d) from t1 where d-19<>c),t1.a)+t1.f in (select coalesce((select max(b) from t1 where t1.c-case when t1.c in (select c from t1 union select t1.f from t1) then f when t1.c not in ( -e,t1.e,11) then (t1.e) else 13 end in (f,t1.e,t1.f) or t1.a not between 19 and 17),t1.c) from t1 union select e from t1) then -t1.e else t1.a end) FROM t1 WHERE 11*b+~ -coalesce((select t1.e from t1 where not exists(select 1 from t1 where 19=t1.f)),t1.d+(abs( -a)/abs(t1.d)))-t1.d-19<=11} +} {} +do_test randexpr-2.1600 { + db eval {SELECT (case when (select count(*) from t1)++t1.d+b*t1.e | t1.a+coalesce((select max(t1.d) from t1 where d-19<>c),t1.a)+t1.f in (select coalesce((select max(b) from t1 where t1.c-case when t1.c in (select c from t1 union select t1.f from t1) then f when t1.c not in ( -e,t1.e,11) then (t1.e) else 13 end in (f,t1.e,t1.f) or t1.a not between 19 and 17),t1.c) from t1 union select e from t1) then -t1.e else t1.a end) FROM t1 WHERE NOT (11*b+~ -coalesce((select t1.e from t1 where not exists(select 1 from t1 where 19=t1.f)),t1.d+(abs( -a)/abs(t1.d)))-t1.d-19<=11)} +} {100} +do_test randexpr-2.1601 { + db eval {SELECT (case when (select count(*) from t1)++t1.d+b*t1.e & t1.a+coalesce((select max(t1.d) from t1 where d-19<>c),t1.a)+t1.f in (select coalesce((select max(b) from t1 where t1.c-case when t1.c in (select c from t1 union select t1.f from t1) then f when t1.c not in ( -e,t1.e,11) then (t1.e) else 13 end in (f,t1.e,t1.f) or t1.a not between 19 and 17),t1.c) from t1 union select e from t1) then -t1.e else t1.a end) FROM t1 WHERE NOT (11*b+~ -coalesce((select t1.e from t1 where not exists(select 1 from t1 where 19=t1.f)),t1.d+(abs( -a)/abs(t1.d)))-t1.d-19<=11)} +} {100} +do_test randexpr-2.1602 { + db eval {SELECT 19+~case when not not (select + - -min(f | f)-count(*)+count(*)-min(b)+count(distinct a) from t1)<=13-case when +13 between t1.a and a then 11 else 11 end and (11 not in (17, -t1.d,(f))) then t1.b | a-t1.f when t1.d<>17 then e else 17 end FROM t1 WHERE +t1.e-c<>case when c in (select d from t1 union select f from t1) then case (case when 13 in (select +c*a*13-11 from t1 union select b from t1) then t1.a when t1.f in ( -t1.f,11,a) or t1.a<=f or (exists(select 1 from t1 where 13>=d)) then t1.c else b end) when t1.d then 11 else e end when t1.b in (19,t1.d,(19)) then c else a end} +} {-482} +do_test randexpr-2.1603 { + db eval {SELECT 19+~case when not not (select + - -min(f | f)-count(*)+count(*)-min(b)+count(distinct a) from t1)<=13-case when +13 between t1.a and a then 11 else 11 end and (11 not in (17, -t1.d,(f))) then t1.b | a-t1.f when t1.d<>17 then e else 17 end FROM t1 WHERE NOT (+t1.e-c<>case when c in (select d from t1 union select f from t1) then case (case when 13 in (select +c*a*13-11 from t1 union select b from t1) then t1.a when t1.f in ( -t1.f,11,a) or t1.a<=f or (exists(select 1 from t1 where 13>=d)) then t1.c else b end) when t1.d then 11 else e end when t1.b in (19,t1.d,(19)) then c else a end)} +} {} +do_test randexpr-2.1604 { + db eval {SELECT 19+~case when not not (select + - -min(f & f)-count(*)+count(*)-min(b)+count(distinct a) from t1)<=13-case when +13 between t1.a and a then 11 else 11 end and (11 not in (17, -t1.d,(f))) then t1.b & a-t1.f when t1.d<>17 then e else 17 end FROM t1 WHERE +t1.e-c<>case when c in (select d from t1 union select f from t1) then case (case when 13 in (select +c*a*13-11 from t1 union select b from t1) then t1.a when t1.f in ( -t1.f,11,a) or t1.a<=f or (exists(select 1 from t1 where 13>=d)) then t1.c else b end) when t1.d then 11 else e end when t1.b in (19,t1.d,(19)) then c else a end} +} {-482} +do_test randexpr-2.1605 { + db eval {SELECT (case when e not between 19 and t1.a then case coalesce((select t1.e from t1 where (exists(select 1 from t1 where c in (select case count(distinct t1.b) when max(b) then min((t1.d)) else count(distinct 11) end+ -count(*) | - -count(distinct t1.e) from t1 union select min(f) from t1))) or (select min(17) from t1) not between 13 and b and - -c=17 and 17 between t1.e and 13 or 13>d or 11>= -t1.d then a else 13 end)+t1.f FROM t1 WHERE b<=13} +} {} +do_test randexpr-2.1606 { + db eval {SELECT (case when e not between 19 and t1.a then case coalesce((select t1.e from t1 where (exists(select 1 from t1 where c in (select case count(distinct t1.b) when max(b) then min((t1.d)) else count(distinct 11) end+ -count(*) | - -count(distinct t1.e) from t1 union select min(f) from t1))) or (select min(17) from t1) not between 13 and b and - -c=17 and 17 between t1.e and 13 or 13>d or 11>= -t1.d then a else 13 end)+t1.f FROM t1 WHERE NOT (b<=13)} +} {619} +do_test randexpr-2.1607 { + db eval {SELECT (case when e not between 19 and t1.a then case coalesce((select t1.e from t1 where (exists(select 1 from t1 where c in (select case count(distinct t1.b) when max(b) then min((t1.d)) else count(distinct 11) end+ -count(*) & - -count(distinct t1.e) from t1 union select min(f) from t1))) or (select min(17) from t1) not between 13 and b and - -c=17 and 17 between t1.e and 13 or 13>d or 11>= -t1.d then a else 13 end)+t1.f FROM t1 WHERE NOT (b<=13)} +} {619} +do_test randexpr-2.1608 { + db eval {SELECT case c when d then +e else 17-e+case when exists(select 1 from t1 where not -f<19) then (a) when t1.a between case when t1.d- -~t1.a+(select case min(t1.a) when count(distinct t1.e) then max(f) else max(t1.f) end-min(t1.b) from t1)*(select max(17) from t1)+e*13-f in (t1.d,f,d) then f else t1.b end and b then t1.d else d end end FROM t1 WHERE b<>c*f} +} {-83} +do_test randexpr-2.1609 { + db eval {SELECT case c when d then +e else 17-e+case when exists(select 1 from t1 where not -f<19) then (a) when t1.a between case when t1.d- -~t1.a+(select case min(t1.a) when count(distinct t1.e) then max(f) else max(t1.f) end-min(t1.b) from t1)*(select max(17) from t1)+e*13-f in (t1.d,f,d) then f else t1.b end and b then t1.d else d end end FROM t1 WHERE NOT (b<>c*f)} +} {} +do_test randexpr-2.1610 { + db eval {SELECT -(select min(coalesce((select max(case when d>=t1.c then f-t1.c else t1.b end) from t1 where case when (17)-13<=(abs(a-e)/abs(19-t1.a)) then (select -max(c++t1.d | +case when 19 in (select b from t1 union select t1.c from t1) then t1.d else f end) from t1) else 11-19 end not in (e,t1.e,17)),c)+t1.b) from t1) FROM t1 WHERE -case when case when e=case when not 17>+t1.d and b*b in (e, -d,13) then -b*c else t1.e end then t1.f when e>=a then c else 19 end+t1.e<> -t1.d then 11 when not 11<>13 then 13 else e end*17*t1.d+t1.f in (select e from t1 union select t1.b from t1)} +} {} +do_test randexpr-2.1611 { + db eval {SELECT -(select min(coalesce((select max(case when d>=t1.c then f-t1.c else t1.b end) from t1 where case when (17)-13<=(abs(a-e)/abs(19-t1.a)) then (select -max(c++t1.d | +case when 19 in (select b from t1 union select t1.c from t1) then t1.d else f end) from t1) else 11-19 end not in (e,t1.e,17)),c)+t1.b) from t1) FROM t1 WHERE NOT ( -case when case when e=case when not 17>+t1.d and b*b in (e, -d,13) then -b*c else t1.e end then t1.f when e>=a then c else 19 end+t1.e<> -t1.d then 11 when not 11<>13 then 13 else e end*17*t1.d+t1.f in (select e from t1 union select t1.b from t1))} +} {-500} +do_test randexpr-2.1612 { + db eval {SELECT -(select min(coalesce((select max(case when d>=t1.c then f-t1.c else t1.b end) from t1 where case when (17)-13<=(abs(a-e)/abs(19-t1.a)) then (select -max(c++t1.d & +case when 19 in (select b from t1 union select t1.c from t1) then t1.d else f end) from t1) else 11-19 end not in (e,t1.e,17)),c)+t1.b) from t1) FROM t1 WHERE NOT ( -case when case when e=case when not 17>+t1.d and b*b in (e, -d,13) then -b*c else t1.e end then t1.f when e>=a then c else 19 end+t1.e<> -t1.d then 11 when not 11<>13 then 13 else e end*17*t1.d+t1.f in (select e from t1 union select t1.b from t1))} +} {-500} +do_test randexpr-2.1613 { + db eval {SELECT case when b<=(abs(19)/abs(t1.a)) | 13-b then +f | ~d else ~case when case case when t1.c in (select 13+19 from t1 union select t1.a from t1) then -c when 13 between t1.a and b then 17 else c end when t1.c then e else 11 end between t1.e and 11 or f in (select 17 from t1 union select (a) from t1) then t1.f-d when t1.b in (select t1.f from t1 union select t1.f from t1) then t1.c else t1.b end end FROM t1 WHERE (t1.e in (select +17 from t1 union select 11 from t1))} +} {} +do_test randexpr-2.1614 { + db eval {SELECT case when b<=(abs(19)/abs(t1.a)) | 13-b then +f | ~d else ~case when case case when t1.c in (select 13+19 from t1 union select t1.a from t1) then -c when 13 between t1.a and b then 17 else c end when t1.c then e else 11 end between t1.e and 11 or f in (select 17 from t1 union select (a) from t1) then t1.f-d when t1.b in (select t1.f from t1 union select t1.f from t1) then t1.c else t1.b end end FROM t1 WHERE NOT ((t1.e in (select +17 from t1 union select 11 from t1)))} +} {-201} +do_test randexpr-2.1615 { + db eval {SELECT case when b<=(abs(19)/abs(t1.a)) & 13-b then +f & ~d else ~case when case case when t1.c in (select 13+19 from t1 union select t1.a from t1) then -c when 13 between t1.a and b then 17 else c end when t1.c then e else 11 end between t1.e and 11 or f in (select 17 from t1 union select (a) from t1) then t1.f-d when t1.b in (select t1.f from t1 union select t1.f from t1) then t1.c else t1.b end end FROM t1 WHERE NOT ((t1.e in (select +17 from t1 union select 11 from t1)))} +} {-201} +do_test randexpr-2.1616 { + db eval {SELECT coalesce((select coalesce((select coalesce((select ~e+coalesce((select -e-+17 from t1 where (select cast(avg(11) AS integer) from t1) between case when +13+13 between 19 and t1.c then t1.d else 13 end and 13),t1.c)* -(19)+17-t1.a+e from t1 where t1.b>=t1.f),t1.b) | t1.f from t1 where f in (select d from t1 union select 11 from t1)),t1.b) from t1 where t1.b=13),t1.d) FROM t1 WHERE t1.f<>(abs(t1.c)/abs(t1.a))} +} {400} +do_test randexpr-2.1617 { + db eval {SELECT coalesce((select coalesce((select coalesce((select ~e+coalesce((select -e-+17 from t1 where (select cast(avg(11) AS integer) from t1) between case when +13+13 between 19 and t1.c then t1.d else 13 end and 13),t1.c)* -(19)+17-t1.a+e from t1 where t1.b>=t1.f),t1.b) | t1.f from t1 where f in (select d from t1 union select 11 from t1)),t1.b) from t1 where t1.b=13),t1.d) FROM t1 WHERE NOT (t1.f<>(abs(t1.c)/abs(t1.a)))} +} {} +do_test randexpr-2.1618 { + db eval {SELECT coalesce((select coalesce((select coalesce((select ~e+coalesce((select -e-+17 from t1 where (select cast(avg(11) AS integer) from t1) between case when +13+13 between 19 and t1.c then t1.d else 13 end and 13),t1.c)* -(19)+17-t1.a+e from t1 where t1.b>=t1.f),t1.b) & t1.f from t1 where f in (select d from t1 union select 11 from t1)),t1.b) from t1 where t1.b=13),t1.d) FROM t1 WHERE t1.f<>(abs(t1.c)/abs(t1.a))} +} {400} +do_test randexpr-2.1619 { + db eval {SELECT (abs(a)/abs(coalesce((select case when coalesce((select d from t1 where d+case (coalesce((select max(e) from t1 where 17+f*13-(case 19 when t1.f then 17 else t1.e end)<>b),17)) when t1.e then t1.e else t1.a end- -13+ -t1.f between b and f),11)+t1.d between 13 and t1.d then b else (19) end-t1.c from t1 where c in (select t1.e from t1 union select f from t1)),b))) FROM t1 WHERE d>t1.a} +} {0} +do_test randexpr-2.1620 { + db eval {SELECT (abs(a)/abs(coalesce((select case when coalesce((select d from t1 where d+case (coalesce((select max(e) from t1 where 17+f*13-(case 19 when t1.f then 17 else t1.e end)<>b),17)) when t1.e then t1.e else t1.a end- -13+ -t1.f between b and f),11)+t1.d between 13 and t1.d then b else (19) end-t1.c from t1 where c in (select t1.e from t1 union select f from t1)),b))) FROM t1 WHERE NOT (d>t1.a)} +} {} +do_test randexpr-2.1621 { + db eval {SELECT coalesce((select case when coalesce((select max(coalesce((select max(e-c-coalesce((select max(c) from t1 where 19 between 13 and 13),(abs(case when c<=17 or f in (t1.a, -17,t1.f) then b else t1.c end)/abs(e))+t1.b)) from t1 where not exists(select 1 from t1 where t1.e>=b)),e)) from t1 where not exists(select 1 from t1 where 13<=t1.b or t1.f in (select d from t1 union select t1.d from t1))),17) in (select 11 from t1 union select t1.d from t1) then c else t1.e end from t1 where t1.c in (select b from t1 union select b from t1)),f) | t1.c FROM t1 WHERE c<=e} +} {892} +do_test randexpr-2.1622 { + db eval {SELECT coalesce((select case when coalesce((select max(coalesce((select max(e-c-coalesce((select max(c) from t1 where 19 between 13 and 13),(abs(case when c<=17 or f in (t1.a, -17,t1.f) then b else t1.c end)/abs(e))+t1.b)) from t1 where not exists(select 1 from t1 where t1.e>=b)),e)) from t1 where not exists(select 1 from t1 where 13<=t1.b or t1.f in (select d from t1 union select t1.d from t1))),17) in (select 11 from t1 union select t1.d from t1) then c else t1.e end from t1 where t1.c in (select b from t1 union select b from t1)),f) | t1.c FROM t1 WHERE NOT (c<=e)} +} {} +do_test randexpr-2.1623 { + db eval {SELECT coalesce((select case when coalesce((select max(coalesce((select max(e-c-coalesce((select max(c) from t1 where 19 between 13 and 13),(abs(case when c<=17 or f in (t1.a, -17,t1.f) then b else t1.c end)/abs(e))+t1.b)) from t1 where not exists(select 1 from t1 where t1.e>=b)),e)) from t1 where not exists(select 1 from t1 where 13<=t1.b or t1.f in (select d from t1 union select t1.d from t1))),17) in (select 11 from t1 union select t1.d from t1) then c else t1.e end from t1 where t1.c in (select b from t1 union select b from t1)),f) & t1.c FROM t1 WHERE c<=e} +} {8} +do_test randexpr-2.1624 { + db eval {SELECT (select +max(case when t1.a in (f,case when f in (t1.b,+ -(select count(*)-min(17) from t1)+19,11) then -19 else 19 end*(abs(b)/abs(a)),a) then t1.b when (case a when 17 then c | t1.d else t1.c end+11)-13 in (b,11,f) then b else 17 end*17) from t1) FROM t1 WHERE c between (abs(case when (abs(d+19)/abs(19))-c*t1.d+t1.e+case when -(abs(case when exists(select 1 from t1 where exists(select 1 from t1 where 13 in (select cast(avg(t1.b) AS integer) from t1 union select max(d) from t1))) then ~c when t1.d not between 13 and d then -t1.b else -f end)/abs(t1.b))+d in (t1.e,(13),e) then e when (b)<>d then t1.b else 19 end in (select 17 from t1 union select e from t1) then t1.e else t1.e end)/abs(t1.f)) and t1.e} +} {3400} +do_test randexpr-2.1625 { + db eval {SELECT (select +max(case when t1.a in (f,case when f in (t1.b,+ -(select count(*)-min(17) from t1)+19,11) then -19 else 19 end*(abs(b)/abs(a)),a) then t1.b when (case a when 17 then c | t1.d else t1.c end+11)-13 in (b,11,f) then b else 17 end*17) from t1) FROM t1 WHERE NOT (c between (abs(case when (abs(d+19)/abs(19))-c*t1.d+t1.e+case when -(abs(case when exists(select 1 from t1 where exists(select 1 from t1 where 13 in (select cast(avg(t1.b) AS integer) from t1 union select max(d) from t1))) then ~c when t1.d not between 13 and d then -t1.b else -f end)/abs(t1.b))+d in (t1.e,(13),e) then e when (b)<>d then t1.b else 19 end in (select 17 from t1 union select e from t1) then t1.e else t1.e end)/abs(t1.f)) and t1.e)} +} {} +do_test randexpr-2.1626 { + db eval {SELECT (select +max(case when t1.a in (f,case when f in (t1.b,+ -(select count(*)-min(17) from t1)+19,11) then -19 else 19 end*(abs(b)/abs(a)),a) then t1.b when (case a when 17 then c & t1.d else t1.c end+11)-13 in (b,11,f) then b else 17 end*17) from t1) FROM t1 WHERE c between (abs(case when (abs(d+19)/abs(19))-c*t1.d+t1.e+case when -(abs(case when exists(select 1 from t1 where exists(select 1 from t1 where 13 in (select cast(avg(t1.b) AS integer) from t1 union select max(d) from t1))) then ~c when t1.d not between 13 and d then -t1.b else -f end)/abs(t1.b))+d in (t1.e,(13),e) then e when (b)<>d then t1.b else 19 end in (select 17 from t1 union select e from t1) then t1.e else t1.e end)/abs(t1.f)) and t1.e} +} {3400} +do_test randexpr-2.1627 { + db eval {SELECT case when c between f and t1.f*t1.f then (coalesce((select max(d | coalesce((select 19+t1.c from t1 where t1.a between d and (b)),(t1.f))*t1.f*t1.b) from t1 where 11>13 or 19 not between 13 and 11 or t1.a>=b or b>t1.e or 11=a and t1.b<=d),f)) when a in (select min(t1.b)-abs(count(distinct 11)) from t1 union select cast(avg(t1.d) AS integer) from t1) then f else c end-t1.e FROM t1 WHERE (t1.f+a)*t1.b+(abs(b)/abs(b)) in (t1.e,case when 11-t1.a+e+case 19 when +11+ -t1.b then case ~t1.f*(f)-b when d then a else ( -c) end*(c) else t1.a end+t1.a not in (17,11,t1.e) then t1.b else (d) end*19,t1.a)} +} {} +do_test randexpr-2.1628 { + db eval {SELECT case when c between f and t1.f*t1.f then (coalesce((select max(d | coalesce((select 19+t1.c from t1 where t1.a between d and (b)),(t1.f))*t1.f*t1.b) from t1 where 11>13 or 19 not between 13 and 11 or t1.a>=b or b>t1.e or 11=a and t1.b<=d),f)) when a in (select min(t1.b)-abs(count(distinct 11)) from t1 union select cast(avg(t1.d) AS integer) from t1) then f else c end-t1.e FROM t1 WHERE NOT ((t1.f+a)*t1.b+(abs(b)/abs(b)) in (t1.e,case when 11-t1.a+e+case 19 when +11+ -t1.b then case ~t1.f*(f)-b when d then a else ( -c) end*(c) else t1.a end+t1.a not in (17,11,t1.e) then t1.b else (d) end*19,t1.a))} +} {-200} +do_test randexpr-2.1629 { + db eval {SELECT case when c between f and t1.f*t1.f then (coalesce((select max(d & coalesce((select 19+t1.c from t1 where t1.a between d and (b)),(t1.f))*t1.f*t1.b) from t1 where 11>13 or 19 not between 13 and 11 or t1.a>=b or b>t1.e or 11=a and t1.b<=d),f)) when a in (select min(t1.b)-abs(count(distinct 11)) from t1 union select cast(avg(t1.d) AS integer) from t1) then f else c end-t1.e FROM t1 WHERE NOT ((t1.f+a)*t1.b+(abs(b)/abs(b)) in (t1.e,case when 11-t1.a+e+case 19 when +11+ -t1.b then case ~t1.f*(f)-b when d then a else ( -c) end*(c) else t1.a end+t1.a not in (17,11,t1.e) then t1.b else (d) end*19,t1.a))} +} {-200} +do_test randexpr-2.1630 { + db eval {SELECT coalesce((select max(f) from t1 where (a+13>19*t1.e+a | a | 17*e or ~c not between 17 and 19*(select +(~count(distinct e)*(cast(avg(t1.b) AS integer))) | count(distinct t1.c) from t1)-f and t1.a*t1.f+c not between t1.f and f)),t1.c*(t1.e)*e) FROM t1 WHERE case case t1.f when ~17 then 11 else t1.d end when a then t1.a else e end>d*11} +} {} +do_test randexpr-2.1631 { + db eval {SELECT coalesce((select max(f) from t1 where (a+13>19*t1.e+a | a | 17*e or ~c not between 17 and 19*(select +(~count(distinct e)*(cast(avg(t1.b) AS integer))) | count(distinct t1.c) from t1)-f and t1.a*t1.f+c not between t1.f and f)),t1.c*(t1.e)*e) FROM t1 WHERE NOT (case case t1.f when ~17 then 11 else t1.d end when a then t1.a else e end>d*11)} +} {600} +do_test randexpr-2.1632 { + db eval {SELECT coalesce((select max(f) from t1 where (a+13>19*t1.e+a & a & 17*e or ~c not between 17 and 19*(select +(~count(distinct e)*(cast(avg(t1.b) AS integer))) & count(distinct t1.c) from t1)-f and t1.a*t1.f+c not between t1.f and f)),t1.c*(t1.e)*e) FROM t1 WHERE NOT (case case t1.f when ~17 then 11 else t1.d end when a then t1.a else e end>d*11)} +} {600} +do_test randexpr-2.1633 { + db eval {SELECT case when e<11 then (case case t1.a when coalesce((select max(11) from t1 where t1.c<=case when exists(select 1 from t1 where 13=e) then case when c not in (t1.f,t1.e,c) then c else ~(c)+d*f end when a>b then 11 else 11 end),(t1.c)) | 11 then b else t1.a end when 11 then t1.f else t1.d end) when db then 11 else 11 end),(t1.c)) | 11 then b else t1.a end when 11 then t1.f else t1.d end) when db then 11 else 11 end),(t1.c)) & 11 then b else t1.a end when 11 then t1.f else t1.d end) when df)),17) when coalesce((select max((b)) from t1 where not case (abs(t1.b)/abs(t1.d+t1.b)) when t1.d then f-coalesce((select max(a) from t1 where case t1.e when c then c else 11 end not between b and -t1.b),t1.e) else t1.a end-17 between t1.e and f and (t1.e17), -e)*19 then t1.b else t1.c end FROM t1 WHERE not -coalesce((select d from t1 where exists(select 1 from t1 where coalesce((select max(case when 11 not in (case when d*11<>17-(t1.e) then 13 else c end,t1.d,t1.c) then e else t1.c end) from t1 where t1.d<= - -d),11) in (select + -case (+ -cast(avg(19) AS integer)+ - -(count(*))* -count(distinct ((t1.e)))*max(d)) when count(*) then max(b) else count(*) end from t1 union select count(*) from t1))),t1.d)+13>a} +} {300} +do_test randexpr-2.1637 { + db eval {SELECT case coalesce((select a from t1 where exists(select 1 from t1 where t1.e>f)),17) when coalesce((select max((b)) from t1 where not case (abs(t1.b)/abs(t1.d+t1.b)) when t1.d then f-coalesce((select max(a) from t1 where case t1.e when c then c else 11 end not between b and -t1.b),t1.e) else t1.a end-17 between t1.e and f and (t1.e17), -e)*19 then t1.b else t1.c end FROM t1 WHERE NOT (not -coalesce((select d from t1 where exists(select 1 from t1 where coalesce((select max(case when 11 not in (case when d*11<>17-(t1.e) then 13 else c end,t1.d,t1.c) then e else t1.c end) from t1 where t1.d<= - -d),11) in (select + -case (+ -cast(avg(19) AS integer)+ - -(count(*))* -count(distinct ((t1.e)))*max(d)) when count(*) then max(b) else count(*) end from t1 union select count(*) from t1))),t1.d)+13>a)} +} {} +do_test randexpr-2.1638 { + db eval {SELECT ~coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.e-t1.e in (select t1.c+case d when case when not case when t1.f between ( -t1.a) and (b) or 11<>19 then (abs(t1.e)/abs(t1.f)) else e end between t1.b and e then t1.d | t1.e when 19>b then 13 else t1.a end*e*13 | 11+t1.f then t1.b else 17 end from t1 union select e from t1))),t1.a-t1.b)*t1.d*e FROM t1 WHERE d in (select 11 from t1 union select +11 from t1) or coalesce((select max(coalesce((select b-e*case when (c) | e | b in (select 19*t1.d from t1 union select t1.e from t1) then t1.d else e end from t1 where t1.a<11),d)) from t1 where (not ((17 not in ( -t1.a,e,d) and 13<11) and f>=11))),t1.b)<11} +} {} +do_test randexpr-2.1639 { + db eval {SELECT ~coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.e-t1.e in (select t1.c+case d when case when not case when t1.f between ( -t1.a) and (b) or 11<>19 then (abs(t1.e)/abs(t1.f)) else e end between t1.b and e then t1.d | t1.e when 19>b then 13 else t1.a end*e*13 | 11+t1.f then t1.b else 17 end from t1 union select e from t1))),t1.a-t1.b)*t1.d*e FROM t1 WHERE NOT (d in (select 11 from t1 union select +11 from t1) or coalesce((select max(coalesce((select b-e*case when (c) | e | b in (select 19*t1.d from t1 union select t1.e from t1) then t1.d else e end from t1 where t1.a<11),d)) from t1 where (not ((17 not in ( -t1.a,e,d) and 13<11) and f>=11))),t1.b)<11)} +} {-3600000} +do_test randexpr-2.1640 { + db eval {SELECT ~coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.e-t1.e in (select t1.c+case d when case when not case when t1.f between ( -t1.a) and (b) or 11<>19 then (abs(t1.e)/abs(t1.f)) else e end between t1.b and e then t1.d & t1.e when 19>b then 13 else t1.a end*e*13 & 11+t1.f then t1.b else 17 end from t1 union select e from t1))),t1.a-t1.b)*t1.d*e FROM t1 WHERE NOT (d in (select 11 from t1 union select +11 from t1) or coalesce((select max(coalesce((select b-e*case when (c) | e | b in (select 19*t1.d from t1 union select t1.e from t1) then t1.d else e end from t1 where t1.a<11),d)) from t1 where (not ((17 not in ( -t1.a,e,d) and 13<11) and f>=11))),t1.b)<11)} +} {-3600000} +do_test randexpr-2.1641 { + db eval {SELECT case b-f when t1.a then -case when not (case t1.a when (select case cast(avg(c) AS integer) when count(distinct t1.f) then +max(t1.e) | -((( -(count(*))))) else cast(avg(f) AS integer) end from t1)-b then a else coalesce((select t1.a from t1 where (e=a and e>c) or c not between a and 19 then 11 when t1.b not between e and t1.a then 17 else 11 end) from t1)) AS integer) from t1 union select cast(avg((abs(b)/abs(t1.f))) AS integer) from t1) then 17 else t1.e end>=a} +} {} +do_test randexpr-2.1642 { + db eval {SELECT case b-f when t1.a then -case when not (case t1.a when (select case cast(avg(c) AS integer) when count(distinct t1.f) then +max(t1.e) | -((( -(count(*))))) else cast(avg(f) AS integer) end from t1)-b then a else coalesce((select t1.a from t1 where (e=a and e>c) or c not between a and 19 then 11 when t1.b not between e and t1.a then 17 else 11 end) from t1)) AS integer) from t1 union select cast(avg((abs(b)/abs(t1.f))) AS integer) from t1) then 17 else t1.e end>=a)} +} {17} +do_test randexpr-2.1643 { + db eval {SELECT case b-f when t1.a then -case when not (case t1.a when (select case cast(avg(c) AS integer) when count(distinct t1.f) then +max(t1.e) & -((( -(count(*))))) else cast(avg(f) AS integer) end from t1)-b then a else coalesce((select t1.a from t1 where (e=a and e>c) or c not between a and 19 then 11 when t1.b not between e and t1.a then 17 else 11 end) from t1)) AS integer) from t1 union select cast(avg((abs(b)/abs(t1.f))) AS integer) from t1) then 17 else t1.e end>=a)} +} {17} +do_test randexpr-2.1644 { + db eval {SELECT coalesce((select max((abs(t1.b*t1.d*case when f*t1.db),t1.d*19)*e+c+t1.d then t1.c when exists(select 1 from t1 where 13>=e) then t1.e else f end-f*e)/abs(13))) from t1 where (a)<=t1.d),13) | e FROM t1 WHERE +t1.c>t1.d} +} {} +do_test randexpr-2.1645 { + db eval {SELECT coalesce((select max((abs(t1.b*t1.d*case when f*t1.db),t1.d*19)*e+c+t1.d then t1.c when exists(select 1 from t1 where 13>=e) then t1.e else f end-f*e)/abs(13))) from t1 where (a)<=t1.d),13) | e FROM t1 WHERE NOT (+t1.c>t1.d)} +} {1823220} +do_test randexpr-2.1646 { + db eval {SELECT coalesce((select max((abs(t1.b*t1.d*case when f*t1.db),t1.d*19)*e+c+t1.d then t1.c when exists(select 1 from t1 where 13>=e) then t1.e else f end-f*e)/abs(13))) from t1 where (a)<=t1.d),13) & e FROM t1 WHERE NOT (+t1.c>t1.d)} +} {356} +do_test randexpr-2.1647 { + db eval {SELECT case when not exists(select 1 from t1 where 17>=19) or t1.c in (select min(19)-(cast(avg(f) AS integer)) from t1 union select cast(avg(19) AS integer) from t1) and e in (select ~+count(distinct 19)*max(13) from t1 union select min(17+d) from t1) or t1.f in (select count(*) from t1 union select (max(a)) from t1) then coalesce((select -d- -t1.d from t1 where b in (select cast(avg(c) AS integer) from t1 union select (count(*)) from t1) or b<=11),e) else t1.e end FROM t1 WHERE a< -13} +} {} +do_test randexpr-2.1648 { + db eval {SELECT case when not exists(select 1 from t1 where 17>=19) or t1.c in (select min(19)-(cast(avg(f) AS integer)) from t1 union select cast(avg(19) AS integer) from t1) and e in (select ~+count(distinct 19)*max(13) from t1 union select min(17+d) from t1) or t1.f in (select count(*) from t1 union select (max(a)) from t1) then coalesce((select -d- -t1.d from t1 where b in (select cast(avg(c) AS integer) from t1 union select (count(*)) from t1) or b<=11),e) else t1.e end FROM t1 WHERE NOT (a< -13)} +} {500} +do_test randexpr-2.1649 { + db eval {SELECT f+case when 17-t1.f in (select ~count(distinct (abs((abs(c)/abs(c)))/abs((abs(11)/abs(+case -t1.a when t1.d then -13 else 17 end))))-t1.c) from t1 union select ~case cast(avg(t1.c) AS integer) when -~ -count(*)*max((t1.f))+count(*) then (min(d)) else max(a) end-count(distinct t1.a)+ -count(*)-count(*) from t1) then d when b not between t1.f and t1.e then a else 11 end+t1.a FROM t1 WHERE (exists(select 1 from t1 where case when exists(select 1 from t1 where case when (t1.e+case (t1.b) when f then case t1.c when 11 | -13-coalesce((select max(d) from t1 where c not in ( -t1.e,t1.c,17) and t1.c<17),e)*17+t1.a then t1.b else 11 end else d end)+t1.f not in (d,13,d) then f else t1.d end not between (c) and f) then t1.e else f end-t1.c in (t1.b,t1.a,f)))} +} {} +do_test randexpr-2.1650 { + db eval {SELECT f+case when 17-t1.f in (select ~count(distinct (abs((abs(c)/abs(c)))/abs((abs(11)/abs(+case -t1.a when t1.d then -13 else 17 end))))-t1.c) from t1 union select ~case cast(avg(t1.c) AS integer) when -~ -count(*)*max((t1.f))+count(*) then (min(d)) else max(a) end-count(distinct t1.a)+ -count(*)-count(*) from t1) then d when b not between t1.f and t1.e then a else 11 end+t1.a FROM t1 WHERE NOT ((exists(select 1 from t1 where case when exists(select 1 from t1 where case when (t1.e+case (t1.b) when f then case t1.c when 11 | -13-coalesce((select max(d) from t1 where c not in ( -t1.e,t1.c,17) and t1.c<17),e)*17+t1.a then t1.b else 11 end else d end)+t1.f not in (d,13,d) then f else t1.d end not between (c) and f) then t1.e else f end-t1.c in (t1.b,t1.a,f))))} +} {800} +do_test randexpr-2.1651 { + db eval {SELECT case ~t1.d when case when c in (select count(*) from t1 union select +(( -min(17)-~cast(avg(t1.c) AS integer)))* -min(t1.f)-max(t1.d)*count(*) | cast(avg(17) AS integer) from t1) then 17*e*t1.f | t1.e else 19-coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where t1.c>=e)),t1.f) end | 13+13 then 17 else t1.f end FROM t1 WHERE (not exists(select 1 from t1 where +c-19 in (select (~((min(b)))-+count(*) | cast(avg(case when 11 in (select (abs((t1.b))/abs(e)) from t1 union select (17) from t1) then t1.c when -a<=b then t1.a else t1.e end) AS integer)++case max(t1.b) when cast(avg(c) AS integer) then count(*) else cast(avg(f) AS integer) end | -count(*)-(count(*))*max(t1.e)*count(*)*cast(avg(a) AS integer))+min(11) from t1 union select max((d)) from t1)))} +} {600} +do_test randexpr-2.1652 { + db eval {SELECT case ~t1.d when case when c in (select count(*) from t1 union select +(( -min(17)-~cast(avg(t1.c) AS integer)))* -min(t1.f)-max(t1.d)*count(*) | cast(avg(17) AS integer) from t1) then 17*e*t1.f | t1.e else 19-coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where t1.c>=e)),t1.f) end | 13+13 then 17 else t1.f end FROM t1 WHERE NOT ((not exists(select 1 from t1 where +c-19 in (select (~((min(b)))-+count(*) | cast(avg(case when 11 in (select (abs((t1.b))/abs(e)) from t1 union select (17) from t1) then t1.c when -a<=b then t1.a else t1.e end) AS integer)++case max(t1.b) when cast(avg(c) AS integer) then count(*) else cast(avg(f) AS integer) end | -count(*)-(count(*))*max(t1.e)*count(*)*cast(avg(a) AS integer))+min(11) from t1 union select max((d)) from t1))))} +} {} +do_test randexpr-2.1653 { + db eval {SELECT case ~t1.d when case when c in (select count(*) from t1 union select +(( -min(17)-~cast(avg(t1.c) AS integer)))* -min(t1.f)-max(t1.d)*count(*) & cast(avg(17) AS integer) from t1) then 17*e*t1.f & t1.e else 19-coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where t1.c>=e)),t1.f) end & 13+13 then 17 else t1.f end FROM t1 WHERE (not exists(select 1 from t1 where +c-19 in (select (~((min(b)))-+count(*) | cast(avg(case when 11 in (select (abs((t1.b))/abs(e)) from t1 union select (17) from t1) then t1.c when -a<=b then t1.a else t1.e end) AS integer)++case max(t1.b) when cast(avg(c) AS integer) then count(*) else cast(avg(f) AS integer) end | -count(*)-(count(*))*max(t1.e)*count(*)*cast(avg(a) AS integer))+min(11) from t1 union select max((d)) from t1)))} +} {600} +do_test randexpr-2.1654 { + db eval {SELECT 19 | case when not (select min(17) from t1)>t1.e then coalesce((select max(coalesce((select b from t1 where (t1.a not in (a | t1.c,t1.d,19) or not exists(select 1 from t1 where t1.b in (select t1.d from t1 union select a from t1)) and (a in (select count(*) from t1 union select max(t1.b) from t1) and t1.c in (t1.b,f,t1.d)))),t1.c)) from t1 where f=d and -b>c),t1.f)-t1.c when c in ((a),11,t1.c) then 13 else 13 end-c FROM t1 WHERE (t1.e)*case when +a*t1.f*t1.e>=+d*a+b-t1.f*~13 | t1.d*11-f-~f+17-coalesce((select max( -f) from t1 where bt1.e then coalesce((select max(coalesce((select b from t1 where (t1.a not in (a | t1.c,t1.d,19) or not exists(select 1 from t1 where t1.b in (select t1.d from t1 union select a from t1)) and (a in (select count(*) from t1 union select max(t1.b) from t1) and t1.c in (t1.b,f,t1.d)))),t1.c)) from t1 where f=d and -b>c),t1.f)-t1.c when c in ((a),11,t1.c) then 13 else 13 end-c FROM t1 WHERE NOT ((t1.e)*case when +a*t1.f*t1.e>=+d*a+b-t1.f*~13 | t1.d*11-f-~f+17-coalesce((select max( -f) from t1 where bt1.e then coalesce((select max(coalesce((select b from t1 where (t1.a not in (a & t1.c,t1.d,19) or not exists(select 1 from t1 where t1.b in (select t1.d from t1 union select a from t1)) and (a in (select count(*) from t1 union select max(t1.b) from t1) and t1.c in (t1.b,f,t1.d)))),t1.c)) from t1 where f=d and -b>c),t1.f)-t1.c when c in ((a),11,t1.c) then 13 else 13 end-c FROM t1 WHERE NOT ((t1.e)*case when +a*t1.f*t1.e>=+d*a+b-t1.f*~13 | t1.d*11-f-~f+17-coalesce((select max( -f) from t1 where bt1.c),11)*e*t1.e from t1 where e<=t1.d),t1.a)*f=11 then e when t1.a in (select e from t1 union select b from t1) then t1.b-t1.a else e end from t1 where a=t1.a), -17) else e end FROM t1 WHERE not exists(select 1 from t1 where t1.e in (select max((abs(~+t1.a-t1.c*a)/abs(17))) from t1 union select min(11*t1.c+t1.f) from t1))} +} {500} +do_test randexpr-2.1658 { + db eval {SELECT case when not exists(select 1 from t1 where not not not d=17) then t1.b when (not coalesce((select coalesce((select max(d) from t1 where c+c>t1.c),11)*e*t1.e from t1 where e<=t1.d),t1.a)*f=11 then e when t1.a in (select e from t1 union select b from t1) then t1.b-t1.a else e end from t1 where a=t1.a), -17) else e end FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.e in (select max((abs(~+t1.a-t1.c*a)/abs(17))) from t1 union select min(11*t1.c+t1.f) from t1)))} +} {} +do_test randexpr-2.1659 { + db eval {SELECT coalesce((select coalesce((select max(case when not a not in ((abs(11)/abs(coalesce((select t1.d from t1 where 17 in (select count(*) from t1 union select count(distinct t1.a) from t1)),b)*t1.e*c)),t1.a,t1.b) or t1.c<=t1.f or (t1.d>= -a) then (select cast(avg(~t1.f-t1.f) AS integer) from t1) else 17 end) from t1 where t1.b<=c and t1.b<=a),11) from t1 where exists(select 1 from t1 where e=(select min(coalesce((select max(19) from t1 where not exists(select 1 from t1 where (select count(distinct +case when coalesce((select max(case when et1.d),t1.d) in (select abs(cast(avg(t1.d) AS integer)-min(t1.c)) from t1 union select -cast(avg(19) AS integer) from t1) then b when t1.e< -t1.c then t1.b else t1.c end-19*e) from t1)<=a)),17))+ -(max(a))- -cast(avg(11) AS integer)+ -count(distinct c) from t1)-11} +} {100} +do_test randexpr-2.1660 { + db eval {SELECT coalesce((select coalesce((select max(case when not a not in ((abs(11)/abs(coalesce((select t1.d from t1 where 17 in (select count(*) from t1 union select count(distinct t1.a) from t1)),b)*t1.e*c)),t1.a,t1.b) or t1.c<=t1.f or (t1.d>= -a) then (select cast(avg(~t1.f-t1.f) AS integer) from t1) else 17 end) from t1 where t1.b<=c and t1.b<=a),11) from t1 where exists(select 1 from t1 where e=(select min(coalesce((select max(19) from t1 where not exists(select 1 from t1 where (select count(distinct +case when coalesce((select max(case when et1.d),t1.d) in (select abs(cast(avg(t1.d) AS integer)-min(t1.c)) from t1 union select -cast(avg(19) AS integer) from t1) then b when t1.e< -t1.c then t1.b else t1.c end-19*e) from t1)<=a)),17))+ -(max(a))- -cast(avg(11) AS integer)+ -count(distinct c) from t1)-11)} +} {} +do_test randexpr-2.1661 { + db eval {SELECT e*(case when +t1.c+t1.e+f<=13 then (select case cast(avg(coalesce((select (t1.f*a)*11 from t1 where c<>t1.a),b)) AS integer)+cast(avg(b) AS integer)+max( -b)-min(e) when max(11) then cast(avg(t1.e) AS integer) else cast(avg(t1.b) AS integer) end from t1) when ~11*t1.d<=t1.b or (t1.e=t1.a) then t1.b else -19 end)+e FROM t1 WHERE a>13*d+t1.e+c} +} {} +do_test randexpr-2.1662 { + db eval {SELECT e*(case when +t1.c+t1.e+f<=13 then (select case cast(avg(coalesce((select (t1.f*a)*11 from t1 where c<>t1.a),b)) AS integer)+cast(avg(b) AS integer)+max( -b)-min(e) when max(11) then cast(avg(t1.e) AS integer) else cast(avg(t1.b) AS integer) end from t1) when ~11*t1.d<=t1.b or (t1.e=t1.a) then t1.b else -19 end)+e FROM t1 WHERE NOT (a>13*d+t1.e+c)} +} {100500} +do_test randexpr-2.1663 { + db eval {SELECT (abs(t1.d-t1.b)/abs(t1.c))+t1.a*coalesce((select max(coalesce((select max(~11+11) from t1 where e-a>=case when 11*t1.d+13+(select cast(avg(t1.d+f) AS integer) from t1)-d+t1.d-b not between a and a then e else coalesce((select e from t1 where d>b and b between 11 and t1.d),t1.b) end), -t1.b)) from t1 where t1.e<=c),17)+ -t1.d FROM t1 WHERE case when (19>b) then case (abs(t1.d+case when not exists(select 1 from t1 where f in (19,d,11) and f not between t1.e and a) then (19) when a<=t1.d then 17 else t1.c end* -c*13)/abs(d))*f when 19 then t1.c else - - -t1.d end when c in (select max(t1.e) from t1 union select ( - -abs(cast(avg(t1.f) AS integer))-case cast(avg(a) AS integer) when (min(t1.f)) then max(13) else max(11) end | -((min(11)))+max((a))) from t1) then c else -b end*t1.d>d} +} {} +do_test randexpr-2.1664 { + db eval {SELECT (abs(t1.d-t1.b)/abs(t1.c))+t1.a*coalesce((select max(coalesce((select max(~11+11) from t1 where e-a>=case when 11*t1.d+13+(select cast(avg(t1.d+f) AS integer) from t1)-d+t1.d-b not between a and a then e else coalesce((select e from t1 where d>b and b between 11 and t1.d),t1.b) end), -t1.b)) from t1 where t1.e<=c),17)+ -t1.d FROM t1 WHERE NOT (case when (19>b) then case (abs(t1.d+case when not exists(select 1 from t1 where f in (19,d,11) and f not between t1.e and a) then (19) when a<=t1.d then 17 else t1.c end* -c*13)/abs(d))*f when 19 then t1.c else - - -t1.d end when c in (select max(t1.e) from t1 union select ( - -abs(cast(avg(t1.f) AS integer))-case cast(avg(a) AS integer) when (min(t1.f)) then max(13) else max(11) end | -((min(11)))+max((a))) from t1) then c else -b end*t1.d>d)} +} {1300} +do_test randexpr-2.1665 { + db eval {SELECT ~t1.a*(case when not not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where (select count(distinct b | case 13 | case when -11<>a then t1.a else b end when t1.e then t1.b else d end*t1.f) from t1)<>17 or t1.a not between c and t1.a),11) in (t1.e,c,c)) and -11>f then t1.d else f end-17)+ -(t1.b) FROM t1 WHERE (13-coalesce((select -case when 19+c=a then f else 11 end*(e) from t1 where (t1.b in (select t1.a from t1 union select 11 from t1))),(t1.f))*e+f*(t1.f)=a and not 17 in (select max(f) from t1 union select max(19) from t1) or 19<>t1.f) and 13 between f and f and d<>b} +} {} +do_test randexpr-2.1666 { + db eval {SELECT ~t1.a*(case when not not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where (select count(distinct b | case 13 | case when -11<>a then t1.a else b end when t1.e then t1.b else d end*t1.f) from t1)<>17 or t1.a not between c and t1.a),11) in (t1.e,c,c)) and -11>f then t1.d else f end-17)+ -(t1.b) FROM t1 WHERE NOT ((13-coalesce((select -case when 19+c=a then f else 11 end*(e) from t1 where (t1.b in (select t1.a from t1 union select 11 from t1))),(t1.f))*e+f*(t1.f)=a and not 17 in (select max(f) from t1 union select max(19) from t1) or 19<>t1.f) and 13 between f and f and d<>b)} +} {-59083} +do_test randexpr-2.1667 { + db eval {SELECT ~t1.a*(case when not not exists(select 1 from t1 where coalesce((select max(t1.c) from t1 where (select count(distinct b & case 13 & case when -11<>a then t1.a else b end when t1.e then t1.b else d end*t1.f) from t1)<>17 or t1.a not between c and t1.a),11) in (t1.e,c,c)) and -11>f then t1.d else f end-17)+ -(t1.b) FROM t1 WHERE NOT ((13-coalesce((select -case when 19+c=a then f else 11 end*(e) from t1 where (t1.b in (select t1.a from t1 union select 11 from t1))),(t1.f))*e+f*(t1.f)=a and not 17 in (select max(f) from t1 union select max(19) from t1) or 19<>t1.f) and 13 between f and f and d<>b)} +} {-59083} +do_test randexpr-2.1668 { + db eval {SELECT ~13+case when (t1.e-~b+13*case when b>(select max(case when (19*f in (select ~count(distinct a)+count(distinct (e)) from t1 union select (cast(avg(t1.c) AS integer)) from t1)) then coalesce((select -19 from t1 where t1.f<=c or 19 not in (t1.c, -b,19)),t1.e) when t1.e>c then e else 13 end | f) from t1) then 13 else d end in (select t1.f from t1 union select c from t1)) then t1.f when not exists(select 1 from t1 where a between f and f) then (d) else t1.c end FROM t1 WHERE exists(select 1 from t1 where case when 19 in (19,+(abs(case t1.f when e then case (select +cast(avg(a) AS integer)*min(e) from t1) when case when 19 not between -t1.c and d then 11 else t1.f end then f else t1.c end else e end+17+b)/abs(t1.d))*13,t1.f) then a when t1.d not in (f,d, -c) then t1.c else t1.b end not between d and c and t1.b not between t1.b and f)} +} {} +do_test randexpr-2.1669 { + db eval {SELECT ~13+case when (t1.e-~b+13*case when b>(select max(case when (19*f in (select ~count(distinct a)+count(distinct (e)) from t1 union select (cast(avg(t1.c) AS integer)) from t1)) then coalesce((select -19 from t1 where t1.f<=c or 19 not in (t1.c, -b,19)),t1.e) when t1.e>c then e else 13 end | f) from t1) then 13 else d end in (select t1.f from t1 union select c from t1)) then t1.f when not exists(select 1 from t1 where a between f and f) then (d) else t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where case when 19 in (19,+(abs(case t1.f when e then case (select +cast(avg(a) AS integer)*min(e) from t1) when case when 19 not between -t1.c and d then 11 else t1.f end then f else t1.c end else e end+17+b)/abs(t1.d))*13,t1.f) then a when t1.d not in (f,d, -c) then t1.c else t1.b end not between d and c and t1.b not between t1.b and f))} +} {386} +do_test randexpr-2.1670 { + db eval {SELECT ~13+case when (t1.e-~b+13*case when b>(select max(case when (19*f in (select ~count(distinct a)+count(distinct (e)) from t1 union select (cast(avg(t1.c) AS integer)) from t1)) then coalesce((select -19 from t1 where t1.f<=c or 19 not in (t1.c, -b,19)),t1.e) when t1.e>c then e else 13 end & f) from t1) then 13 else d end in (select t1.f from t1 union select c from t1)) then t1.f when not exists(select 1 from t1 where a between f and f) then (d) else t1.c end FROM t1 WHERE NOT (exists(select 1 from t1 where case when 19 in (19,+(abs(case t1.f when e then case (select +cast(avg(a) AS integer)*min(e) from t1) when case when 19 not between -t1.c and d then 11 else t1.f end then f else t1.c end else e end+17+b)/abs(t1.d))*13,t1.f) then a when t1.d not in (f,d, -c) then t1.c else t1.b end not between d and c and t1.b not between t1.b and f))} +} {386} +do_test randexpr-2.1671 { + db eval {SELECT -case coalesce((select max((case when a>t1.c | t1.a then (select abs(count(distinct a)) from t1) when (e not in (coalesce((select c from t1 where exists(select 1 from t1 where c<=11) and t1.a>e),e),d,a)) or t1.d<>e then t1.c else c end)- -11*b) from t1 where not exists(select 1 from t1 where not (c in ((t1.e),d,19)))),(t1.c))*b when 17 then t1.b else 19 end FROM t1 WHERE e<=coalesce((select t1.b from t1 where coalesce((select c*19 | (a) from t1 where not exists(select 1 from t1 where 19>=13 or case when coalesce((select max(19) from t1 where t1.e=t1.d or t1.f<>e),t1.f)>19 and t1.f=t1.d then 11+ -t1.d when -t1.f not between f and f then t1.a else d end not in ((t1.a),13,t1.a) and c in (select (13) from t1 union select f from t1) and 17<(f)) and t1.a<>t1.e),t1.d)>=t1.c),t1.f)} +} {} +do_test randexpr-2.1672 { + db eval {SELECT -case coalesce((select max((case when a>t1.c | t1.a then (select abs(count(distinct a)) from t1) when (e not in (coalesce((select c from t1 where exists(select 1 from t1 where c<=11) and t1.a>e),e),d,a)) or t1.d<>e then t1.c else c end)- -11*b) from t1 where not exists(select 1 from t1 where not (c in ((t1.e),d,19)))),(t1.c))*b when 17 then t1.b else 19 end FROM t1 WHERE NOT (e<=coalesce((select t1.b from t1 where coalesce((select c*19 | (a) from t1 where not exists(select 1 from t1 where 19>=13 or case when coalesce((select max(19) from t1 where t1.e=t1.d or t1.f<>e),t1.f)>19 and t1.f=t1.d then 11+ -t1.d when -t1.f not between f and f then t1.a else d end not in ((t1.a),13,t1.a) and c in (select (13) from t1 union select f from t1) and 17<(f)) and t1.a<>t1.e),t1.d)>=t1.c),t1.f))} +} {-19} +do_test randexpr-2.1673 { + db eval {SELECT -case coalesce((select max((case when a>t1.c & t1.a then (select abs(count(distinct a)) from t1) when (e not in (coalesce((select c from t1 where exists(select 1 from t1 where c<=11) and t1.a>e),e),d,a)) or t1.d<>e then t1.c else c end)- -11*b) from t1 where not exists(select 1 from t1 where not (c in ((t1.e),d,19)))),(t1.c))*b when 17 then t1.b else 19 end FROM t1 WHERE NOT (e<=coalesce((select t1.b from t1 where coalesce((select c*19 | (a) from t1 where not exists(select 1 from t1 where 19>=13 or case when coalesce((select max(19) from t1 where t1.e=t1.d or t1.f<>e),t1.f)>19 and t1.f=t1.d then 11+ -t1.d when -t1.f not between f and f then t1.a else d end not in ((t1.a),13,t1.a) and c in (select (13) from t1 union select f from t1) and 17<(f)) and t1.a<>t1.e),t1.d)>=t1.c),t1.f))} +} {-19} +do_test randexpr-2.1674 { + db eval {SELECT coalesce((select (11) from t1 where not e in (select -min(d*13) from t1 union select count(distinct f) from t1)),t1.f*t1.d | t1.f) FROM t1 WHERE -t1.c*d>case d when ~coalesce((select max(e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not e=c))),+coalesce((select +t1.e from t1 where not exists(select 1 from t1 where c>=t1.b)),(abs( -t1.c+case t1.c when ~~t1.c+a-t1.c then coalesce((select max(case when t1.b<=c then 19 else f end) from t1 where 13case d when ~coalesce((select max(e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not e=c))),+coalesce((select +t1.e from t1 where not exists(select 1 from t1 where c>=t1.b)),(abs( -t1.c+case t1.c when ~~t1.c+a-t1.c then coalesce((select max(case when t1.b<=c then 19 else f end) from t1 where 13case d when ~coalesce((select max(e) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where not e=c))),+coalesce((select +t1.e from t1 where not exists(select 1 from t1 where c>=t1.b)),(abs( -t1.c+case t1.c when ~~t1.c+a-t1.c then coalesce((select max(case when t1.b<=c then 19 else f end) from t1 where 13=(select max(17) from t1) then case 11 when e then coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.d in (select t1.a from t1 union select e from t1) and e=case when 11<19 and t1.e<19 then t1.e when t1.c in (t1.b,t1.e,t1.d) then 13 else 13 end and e<=d or b between 19 and t1.a or t1.a<=(13))),t1.a) else t1.e-t1.d end*t1.a when -11 not in (17,t1.d,a) then t1.c else b end*19 FROM t1 WHERE not t1.b>t1.e or t1.d not in (~t1.f,d+case when (b+(abs(19*~t1.c | t1.b*d*(b)-t1.e-t1.e+a)/abs(t1.c)) not in (17,b,t1.e)) then 13+f else b end-t1.f,t1.e) or t1.e not in (f,a,t1.d)} +} {190000} +do_test randexpr-2.1678 { + db eval {SELECT +case when t1.e>=(select max(17) from t1) then case 11 when e then coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.d in (select t1.a from t1 union select e from t1) and e=case when 11<19 and t1.e<19 then t1.e when t1.c in (t1.b,t1.e,t1.d) then 13 else 13 end and e<=d or b between 19 and t1.a or t1.a<=(13))),t1.a) else t1.e-t1.d end*t1.a when -11 not in (17,t1.d,a) then t1.c else b end*19 FROM t1 WHERE NOT (not t1.b>t1.e or t1.d not in (~t1.f,d+case when (b+(abs(19*~t1.c | t1.b*d*(b)-t1.e-t1.e+a)/abs(t1.c)) not in (17,b,t1.e)) then 13+f else b end-t1.f,t1.e) or t1.e not in (f,a,t1.d))} +} {} +do_test randexpr-2.1679 { + db eval {SELECT t1.e | t1.b+a*coalesce((select t1.a from t1 where ~(d)-f<>e-c or 17+f in (select -(~case max(t1.c) when abs(count(*)) then abs( - -cast(avg(b) AS integer)*count(*)) else cast(avg(t1.c) AS integer) end) from t1 union select count(distinct (11)) from t1) and exists(select 1 from t1 where not 13>t1.e) or t1.ce-c or 17+f in (select -(~case max(t1.c) when abs(count(*)) then abs( - -cast(avg(b) AS integer)*count(*)) else cast(avg(t1.c) AS integer) end) from t1 union select count(distinct (11)) from t1) and exists(select 1 from t1 where not 13>t1.e) or t1.ce-c or 17+f in (select -(~case max(t1.c) when abs(count(*)) then abs( - -cast(avg(b) AS integer)*count(*)) else cast(avg(t1.c) AS integer) end) from t1 union select count(distinct (11)) from t1) and exists(select 1 from t1 where not 13>t1.e) or t1.ct1.b then 19 when case when case (select ( -max(c)) from t1) when 11 then d else e end*t1.d<>d then a else 11 end=t1.b or 17=d then b else t1.e end+11+t1.a*a-e FROM t1 WHERE coalesce((select coalesce((select max(c) from t1 where -+ -e-t1.d*case when coalesce((select d from t1 where (c=a)),f) between t1.b and t1.b or (13)<>c and e in (t1.e,e,(t1.a)) then b*t1.c else b end+t1.c in (select t1.f from t1 union select t1.b from t1)),19) from t1 where t1.f in (select count(*) from t1 union select cast(avg(t1.e) AS integer)*min((a))*+(max(t1.b))+max(17) from t1)),t1.d)< -e} +} {} +do_test randexpr-2.1683 { + db eval {SELECT ~(select +~count(distinct 17)*count(distinct t1.e) from t1)-t1.e+a*11-case when 13<>t1.b then 19 when case when case (select ( -max(c)) from t1) when 11 then d else e end*t1.d<>d then a else 11 end=t1.b or 17=d then b else t1.e end+11+t1.a*a-e FROM t1 WHERE NOT (coalesce((select coalesce((select max(c) from t1 where -+ -e-t1.d*case when coalesce((select d from t1 where (c=a)),f) between t1.b and t1.b or (13)<>c and e in (t1.e,e,(t1.a)) then b*t1.c else b end+t1.c in (select t1.f from t1 union select t1.b from t1)),19) from t1 where t1.f in (select count(*) from t1 union select cast(avg(t1.e) AS integer)*min((a))*+(max(t1.b))+max(17) from t1)),t1.d)< -e)} +} {10093} +do_test randexpr-2.1684 { + db eval {SELECT coalesce((select max(case when f<=(17-coalesce((select ~t1.e+11 from t1 where t1.f in (select c from t1 union select b from t1)),f)) then -case when e>case when 17+ -t1.b in (select cast(avg(f) AS integer) from t1 union select min(c-17+a) from t1) then -17 else t1.d end then a when 19<11 then t1.a else t1.b end | t1.f else a end) from t1 where e between a and d),19) FROM t1 WHERE case 19 when ((select max(f) from t1)) then 13 else t1.d end-t1.c>a-b-t1.d} +} {19} +do_test randexpr-2.1685 { + db eval {SELECT coalesce((select max(case when f<=(17-coalesce((select ~t1.e+11 from t1 where t1.f in (select c from t1 union select b from t1)),f)) then -case when e>case when 17+ -t1.b in (select cast(avg(f) AS integer) from t1 union select min(c-17+a) from t1) then -17 else t1.d end then a when 19<11 then t1.a else t1.b end | t1.f else a end) from t1 where e between a and d),19) FROM t1 WHERE NOT (case 19 when ((select max(f) from t1)) then 13 else t1.d end-t1.c>a-b-t1.d)} +} {} +do_test randexpr-2.1686 { + db eval {SELECT coalesce((select max(case when f<=(17-coalesce((select ~t1.e+11 from t1 where t1.f in (select c from t1 union select b from t1)),f)) then -case when e>case when 17+ -t1.b in (select cast(avg(f) AS integer) from t1 union select min(c-17+a) from t1) then -17 else t1.d end then a when 19<11 then t1.a else t1.b end & t1.f else a end) from t1 where e between a and d),19) FROM t1 WHERE case 19 when ((select max(f) from t1)) then 13 else t1.d end-t1.c>a-b-t1.d} +} {19} +do_test randexpr-2.1687 { + db eval {SELECT case when (select case min(t1.b) when max(13) | +max(t1.e)*max(f) then abs( -+count(*)) else max(t1.f) end from t1)*t1.a+(abs(case 19 when 19 then d else ((13)) end)/abs(13))+(19) between f and 13 or (not not 17~17),t1.e+(select count(*) from t1) | 11-coalesce((select 13 from t1 where 11 not in ( -t1.f,t1.e,t1.f)),t1.b))+ -(t1.c)) from t1) from t1 where t1.a=(13)), -a)*e FROM t1 WHERE not exists(select 1 from t1 where (select count(distinct t1.e) from t1)<=coalesce((select case when not exists(select 1 from t1 where e=t1.b*coalesce((select max(+b) from t1 where exists(select 1 from t1 where not (not not exists(select 1 from t1 where t1.c in (select 11 from t1 union select 19+13 from t1)))) and not t1.b~17),t1.e+(select count(*) from t1) | 11-coalesce((select 13 from t1 where 11 not in ( -t1.f,t1.e,t1.f)),t1.b))+ -(t1.c)) from t1) from t1 where t1.a=(13)), -a)*e FROM t1 WHERE NOT (not exists(select 1 from t1 where (select count(distinct t1.e) from t1)<=coalesce((select case when not exists(select 1 from t1 where e=t1.b*coalesce((select max(+b) from t1 where exists(select 1 from t1 where not (not not exists(select 1 from t1 where t1.c in (select 11 from t1 union select 19+13 from t1)))) and not t1.b~17),t1.e+(select count(*) from t1) & 11-coalesce((select 13 from t1 where 11 not in ( -t1.f,t1.e,t1.f)),t1.b))+ -(t1.c)) from t1) from t1 where t1.a=(13)), -a)*e FROM t1 WHERE not exists(select 1 from t1 where (select count(distinct t1.e) from t1)<=coalesce((select case when not exists(select 1 from t1 where e=t1.b*coalesce((select max(+b) from t1 where exists(select 1 from t1 where not (not not exists(select 1 from t1 where t1.c in (select 11 from t1 union select 19+13 from t1)))) and not t1.be) then t1.e*c else c end-13+t1.a),f)+t1.d- -t1.a)*t1.c<>f) and t1.b not between (e) and t1.c),f)+11*t1.f FROM t1 WHERE (17 in (select 13 from t1 union select case coalesce((select max( -case when not b in ((select -+case max((b)) when cast(avg(13) AS integer) then count(*) else max(a) end+min(b)-max(d) from t1),coalesce((select t1.d from t1 where case when -13 in ( -t1.e,f,t1.e) then t1.c else e end | 11<=(t1.b)),t1.c)-11,t1.e) then t1.f else 13 end) from t1 where b>=t1.e),f) when e then t1.c else c end from t1))} +} {} +do_test randexpr-2.1694 { + db eval {SELECT ~~t1.b | 11+d*coalesce((select max(t1.f-a) from t1 where not exists(select 1 from t1 where (a-coalesce((select b from t1 where t1.fe) then t1.e*c else c end-13+t1.a),f)+t1.d- -t1.a)*t1.c<>f) and t1.b not between (e) and t1.c),f)+11*t1.f FROM t1 WHERE NOT ((17 in (select 13 from t1 union select case coalesce((select max( -case when not b in ((select -+case max((b)) when cast(avg(13) AS integer) then count(*) else max(a) end+min(b)-max(d) from t1),coalesce((select t1.d from t1 where case when -13 in ( -t1.e,f,t1.e) then t1.c else e end | 11<=(t1.b)),t1.c)-11,t1.e) then t1.f else 13 end) from t1 where b>=t1.e),f) when e then t1.c else c end from t1)))} +} {246747} +do_test randexpr-2.1695 { + db eval {SELECT ~~t1.b & 11+d*coalesce((select max(t1.f-a) from t1 where not exists(select 1 from t1 where (a-coalesce((select b from t1 where t1.fe) then t1.e*c else c end-13+t1.a),f)+t1.d- -t1.a)*t1.c<>f) and t1.b not between (e) and t1.c),f)+11*t1.f FROM t1 WHERE NOT ((17 in (select 13 from t1 union select case coalesce((select max( -case when not b in ((select -+case max((b)) when cast(avg(13) AS integer) then count(*) else max(a) end+min(b)-max(d) from t1),coalesce((select t1.d from t1 where case when -13 in ( -t1.e,f,t1.e) then t1.c else e end | 11<=(t1.b)),t1.c)-11,t1.e) then t1.f else 13 end) from t1 where b>=t1.e),f) when e then t1.c else c end from t1)))} +} {64} +do_test randexpr-2.1696 { + db eval {SELECT case case when not ++b+~e-11-d-f*e*case when (t1.f) not between t1.c and t1.e or (13>e) then (abs(17)/abs(d)) when 11 not between 17 and (t1.b) then c else 13 end-(f)-f between t1.c and t1.f then t1.c when a between t1.d and 13 then t1.e else t1.a end when a then f else 13 end FROM t1 WHERE t1.a in (select case when (+e*t1.f not in ( -(select (case max(+t1.e-case when not exists(select 1 from t1 where 19 in (select 13 from t1 union select ((t1.d)) from t1)) then 13-t1.b else 19 end) when count(*)-(cast(avg(t1.b) AS integer)-cast(avg(b) AS integer)) then count(distinct t1.b) else count(distinct t1.c) end | cast(avg((19)) AS integer)) from t1),~17-f,c)) then (select count(*) from t1) when t1.a>t1.a then b else t1.d end+(f) from t1 union select b from t1)} +} {} +do_test randexpr-2.1697 { + db eval {SELECT case case when not ++b+~e-11-d-f*e*case when (t1.f) not between t1.c and t1.e or (13>e) then (abs(17)/abs(d)) when 11 not between 17 and (t1.b) then c else 13 end-(f)-f between t1.c and t1.f then t1.c when a between t1.d and 13 then t1.e else t1.a end when a then f else 13 end FROM t1 WHERE NOT (t1.a in (select case when (+e*t1.f not in ( -(select (case max(+t1.e-case when not exists(select 1 from t1 where 19 in (select 13 from t1 union select ((t1.d)) from t1)) then 13-t1.b else 19 end) when count(*)-(cast(avg(t1.b) AS integer)-cast(avg(b) AS integer)) then count(distinct t1.b) else count(distinct t1.c) end | cast(avg((19)) AS integer)) from t1),~17-f,c)) then (select count(*) from t1) when t1.a>t1.a then b else t1.d end+(f) from t1 union select b from t1))} +} {13} +do_test randexpr-2.1698 { + db eval {SELECT 13-case when a<=case when e not between t1.b*(abs(t1.c)/abs(e | 19-(select -~count(distinct t1.b)+min(t1.a-t1.c-f+t1.d+t1.d+t1.d) from t1)))-t1.e and coalesce((select 11 from t1 where ct1.c)} +} {596} +do_test randexpr-2.1699 { + db eval {SELECT 13-case when a<=case when e not between t1.b*(abs(t1.c)/abs(e | 19-(select -~count(distinct t1.b)+min(t1.a-t1.c-f+t1.d+t1.d+t1.d) from t1)))-t1.e and coalesce((select 11 from t1 where ct1.c))} +} {} +do_test randexpr-2.1700 { + db eval {SELECT 13-case when a<=case when e not between t1.b*(abs(t1.c)/abs(e & 19-(select -~count(distinct t1.b)+min(t1.a-t1.c-f+t1.d+t1.d+t1.d) from t1)))-t1.e and coalesce((select 11 from t1 where ct1.c)} +} {596} +do_test randexpr-2.1701 { + db eval {SELECT (case when coalesce((select max(~case coalesce((select max(b) from t1 where case (select count(distinct 17) from t1)-e when b then d else t1.b end<13),f) when c then (( -c)) else 13 end) from t1 where t1.e between a and b),t1.b) in (select -min(t1.f) from t1 union select case cast(avg(t1.d) AS integer) when count(distinct b) then case +~ -cast(avg(b) AS integer) when max(t1.f) then count(*) else (max(e)) end else count(*) end from t1) then c when 13<=t1.f then ( -17) else t1.b end) FROM t1 WHERE (select min(19*coalesce((select max(t1.e) from t1 where ~coalesce((select t1.a-coalesce((select max((abs(a)/abs(d))) from t1 where -13 not in ((d)*t1.a+t1.e,13,t1.c) or 17 not in (a,b,t1.d)), -t1.a) from t1 where c<>t1.e),a) | 11+17 between b and 17),c))*~ -max(e) from t1)<>11} +} {-17} +do_test randexpr-2.1702 { + db eval {SELECT (case when coalesce((select max(~case coalesce((select max(b) from t1 where case (select count(distinct 17) from t1)-e when b then d else t1.b end<13),f) when c then (( -c)) else 13 end) from t1 where t1.e between a and b),t1.b) in (select -min(t1.f) from t1 union select case cast(avg(t1.d) AS integer) when count(distinct b) then case +~ -cast(avg(b) AS integer) when max(t1.f) then count(*) else (max(e)) end else count(*) end from t1) then c when 13<=t1.f then ( -17) else t1.b end) FROM t1 WHERE NOT ((select min(19*coalesce((select max(t1.e) from t1 where ~coalesce((select t1.a-coalesce((select max((abs(a)/abs(d))) from t1 where -13 not in ((d)*t1.a+t1.e,13,t1.c) or 17 not in (a,b,t1.d)), -t1.a) from t1 where c<>t1.e),a) | 11+17 between b and 17),c))*~ -max(e) from t1)<>11)} +} {} +do_test randexpr-2.1703 { + db eval {SELECT t1.f* -t1.e-c | b++19*(select (case max(t1.c) when +abs(count(distinct case when e=13 then coalesce((select max(t1.c) from t1 where not -c+b-t1.f<>d),a) else b end FROM t1 WHERE d in (select 11 from t1 union select -d*~t1.b from t1)} +} {} +do_test randexpr-2.1704 { + db eval {SELECT t1.f* -t1.e-c | b++19*(select (case max(t1.c) when +abs(count(distinct case when e=13 then coalesce((select max(t1.c) from t1 where not -c+b-t1.f<>d),a) else b end FROM t1 WHERE NOT (d in (select 11 from t1 union select -d*~t1.b from t1))} +} {-295178} +do_test randexpr-2.1705 { + db eval {SELECT t1.f* -t1.e-c & b++19*(select (case max(t1.c) when +abs(count(distinct case when e=13 then coalesce((select max(t1.c) from t1 where not -c+b-t1.f<>d),a) else b end FROM t1 WHERE NOT (d in (select 11 from t1 union select -d*~t1.b from t1))} +} {52} +do_test randexpr-2.1706 { + db eval {SELECT 11-t1.e+d+case case when (b between -+case when f not between case coalesce((select t1.a from t1 where e not between (t1.d) and t1.a or 17<11),t1.d) when 17 then t1.f else t1.e end and d then 17 when e>=t1.f then t1.b else t1.b end and t1.e) then case f when t1.d then t1.c else -e end when (not exists(select 1 from t1 where -(11)>a) or t1.ct1.e} +} {} +do_test randexpr-2.1707 { + db eval {SELECT 11-t1.e+d+case case when (b between -+case when f not between case coalesce((select t1.a from t1 where e not between (t1.d) and t1.a or 17<11),t1.d) when 17 then t1.f else t1.e end and d then 17 when e>=t1.f then t1.b else t1.b end and t1.e) then case f when t1.d then t1.c else -e end when (not exists(select 1 from t1 where -(11)>a) or t1.ct1.e)} +} {411} +do_test randexpr-2.1708 { + db eval {SELECT coalesce((select max(case when f>11 then 13 when 19*e+(select -count(distinct t1.c)-max(c) | count(distinct 13) from t1) between coalesce((select max(case when t1.ae),17) FROM t1 WHERE case case 13+coalesce((select max( -t1.b*t1.c) from t1 where t1.c*c<>(select -(count(distinct e)) from t1)-t1.c | t1.d*t1.e+11*t1.a+11-t1.a*b),d)+t1.d+e when t1.f then e else -11 end-d when t1.e then 11 else f end+f=19} +} {} +do_test randexpr-2.1709 { + db eval {SELECT coalesce((select max(case when f>11 then 13 when 19*e+(select -count(distinct t1.c)-max(c) | count(distinct 13) from t1) between coalesce((select max(case when t1.ae),17) FROM t1 WHERE NOT (case case 13+coalesce((select max( -t1.b*t1.c) from t1 where t1.c*c<>(select -(count(distinct e)) from t1)-t1.c | t1.d*t1.e+11*t1.a+11-t1.a*b),d)+t1.d+e when t1.f then e else -11 end-d when t1.e then 11 else f end+f=19)} +} {17} +do_test randexpr-2.1710 { + db eval {SELECT coalesce((select max(case when f>11 then 13 when 19*e+(select -count(distinct t1.c)-max(c) & count(distinct 13) from t1) between coalesce((select max(case when t1.ae),17) FROM t1 WHERE NOT (case case 13+coalesce((select max( -t1.b*t1.c) from t1 where t1.c*c<>(select -(count(distinct e)) from t1)-t1.c | t1.d*t1.e+11*t1.a+11-t1.a*b),d)+t1.d+e when t1.f then e else -11 end-d when t1.e then 11 else f end+f=19)} +} {17} +do_test randexpr-2.1711 { + db eval {SELECT 13+coalesce((select -(abs(b)/abs(coalesce((select (abs(e+t1.a)/abs(13)) from t1 where a17 and t1.d<>t1.f),17)+a- -t1.d then t1.d else -t1.b end,b)} +} {413} +do_test randexpr-2.1712 { + db eval {SELECT 13+coalesce((select -(abs(b)/abs(coalesce((select (abs(e+t1.a)/abs(13)) from t1 where a17 and t1.d<>t1.f),17)+a- -t1.d then t1.d else -t1.b end,b))} +} {} +do_test randexpr-2.1713 { + db eval {SELECT (~(abs(case when t1.f*17 not in (coalesce((select 13 from t1 where d in (select count(distinct t1.e- -t1.e+t1.e*11) from t1 union select (abs(~~(cast(avg(d) AS integer))* -(min(13))+max(d) | min(13))) from t1)),d),a,t1.e) then c else t1.c end-c)/abs((t1.d)))*t1.c)*t1.d+t1.b-b FROM t1 WHERE (abs(case when (t1.e+case when t1.f+t1.d*t1.c<=t1.f or t1.c>=a and a not between 19 and t1.e then e else b end-t1.c) | t1.b<>19 then t1.f when 19<=t1.d and not -t1.c>=11 and t1.a between t1.f and (19) then b else t1.c end)/abs(b))+11>=t1.f and t1.f not between f and t1.a} +} {} +do_test randexpr-2.1714 { + db eval {SELECT (~(abs(case when t1.f*17 not in (coalesce((select 13 from t1 where d in (select count(distinct t1.e- -t1.e+t1.e*11) from t1 union select (abs(~~(cast(avg(d) AS integer))* -(min(13))+max(d) | min(13))) from t1)),d),a,t1.e) then c else t1.c end-c)/abs((t1.d)))*t1.c)*t1.d+t1.b-b FROM t1 WHERE NOT ((abs(case when (t1.e+case when t1.f+t1.d*t1.c<=t1.f or t1.c>=a and a not between 19 and t1.e then e else b end-t1.c) | t1.b<>19 then t1.f when 19<=t1.d and not -t1.c>=11 and t1.a between t1.f and (19) then b else t1.c end)/abs(b))+11>=t1.f and t1.f not between f and t1.a)} +} {-120000} +do_test randexpr-2.1715 { + db eval {SELECT (~(abs(case when t1.f*17 not in (coalesce((select 13 from t1 where d in (select count(distinct t1.e- -t1.e+t1.e*11) from t1 union select (abs(~~(cast(avg(d) AS integer))* -(min(13))+max(d) & min(13))) from t1)),d),a,t1.e) then c else t1.c end-c)/abs((t1.d)))*t1.c)*t1.d+t1.b-b FROM t1 WHERE NOT ((abs(case when (t1.e+case when t1.f+t1.d*t1.c<=t1.f or t1.c>=a and a not between 19 and t1.e then e else b end-t1.c) | t1.b<>19 then t1.f when 19<=t1.d and not -t1.c>=11 and t1.a between t1.f and (19) then b else t1.c end)/abs(b))+11>=t1.f and t1.f not between f and t1.a)} +} {-120000} +do_test randexpr-2.1716 { + db eval {SELECT (abs(a)/abs(case when (not t1.f in (select count(*) from t1 union select - -min(c) | min(13*t1.d) from t1)) and ( -t1.a*t1.d)>=d or (t1.a in (a,11,f)) or (c>=t1.a) then 17+case when not exists(select 1 from t1 where e=d or (t1.a in (a,11,f)) or (c>=t1.a) then 17+case when not exists(select 1 from t1 where e=d or (t1.a in (a,11,f)) or (c>=t1.a) then 17+case when not exists(select 1 from t1 where ec)) and 13 between t1.c and 17 or a=13),coalesce((select a from t1 where (t1.d) in (c,11,t1.c)),t1.d)) | c | coalesce((select max(d) from t1 where t1.b>b),t1.a)=19 then e else 13 end between t1.a and t1.f and 17>=c then a when d in (e,13,c) or t1.b<> -19 then (17) else 17 end FROM t1 WHERE -b in (t1.b,t1.f,case when a in (select case +(min(t1.c)*+~cast(avg(+t1.f) AS integer)*cast(avg(d) AS integer) | abs(count(*))+count(*)*count(distinct 17)) when count(distinct e) then -cast(avg(t1.a) AS integer) else min(11) end from t1 union select ((min(13))) from t1) then (abs(t1.d)/abs(case when -19c)) and 13 between t1.c and 17 or a=13),coalesce((select a from t1 where (t1.d) in (c,11,t1.c)),t1.d)) | c | coalesce((select max(d) from t1 where t1.b>b),t1.a)=19 then e else 13 end between t1.a and t1.f and 17>=c then a when d in (e,13,c) or t1.b<> -19 then (17) else 17 end FROM t1 WHERE NOT ( -b in (t1.b,t1.f,case when a in (select case +(min(t1.c)*+~cast(avg(+t1.f) AS integer)*cast(avg(d) AS integer) | abs(count(*))+count(*)*count(distinct 17)) when count(distinct e) then -cast(avg(t1.a) AS integer) else min(11) end from t1 union select ((min(13))) from t1) then (abs(t1.d)/abs(case when -19c)) and 13 between t1.c and 17 or a=13),coalesce((select a from t1 where (t1.d) in (c,11,t1.c)),t1.d)) & c & coalesce((select max(d) from t1 where t1.b>b),t1.a)=19 then e else 13 end between t1.a and t1.f and 17>=c then a when d in (e,13,c) or t1.b<> -19 then (17) else 17 end FROM t1 WHERE NOT ( -b in (t1.b,t1.f,case when a in (select case +(min(t1.c)*+~cast(avg(+t1.f) AS integer)*cast(avg(d) AS integer) | abs(count(*))+count(*)*count(distinct 17)) when count(distinct e) then -cast(avg(t1.a) AS integer) else min(11) end from t1 union select ((min(13))) from t1) then (abs(t1.d)/abs(case when -19e)} +} {} +do_test randexpr-2.1723 { + db eval {SELECT coalesce((select t1.b from t1 where not exists(select 1 from t1 where 13 in (select count(*) | ~min((select max((abs(d)/abs(t1.e+t1.e))) from t1)* -case when f*case e*~a when case e when (d) then 19 else (b) end then d else 17 end*t1.b between 11 and 13 then e when d in (a,(19),e) then c else 13 end-e*17) from t1 union select (count(*)) from t1))),f) FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a<>e))} +} {200} +do_test randexpr-2.1724 { + db eval {SELECT coalesce((select t1.b from t1 where not exists(select 1 from t1 where 13 in (select count(*) & ~min((select max((abs(d)/abs(t1.e+t1.e))) from t1)* -case when f*case e*~a when case e when (d) then 19 else (b) end then d else 17 end*t1.b between 11 and 13 then e when d in (a,(19),e) then c else 13 end-e*17) from t1 union select (count(*)) from t1))),f) FROM t1 WHERE NOT (not exists(select 1 from t1 where t1.a<>e))} +} {200} +do_test randexpr-2.1725 { + db eval {SELECT - -case b when +~coalesce((select max(coalesce((select c from t1 where coalesce((select max(t1.a+f) from t1 where (t1.a not between t1.a and t1.e)),t1.a)-b not between e and -t1.d),d)+19) from t1 where (f in (select ( -count(*) | count(*)+cast(avg(11) AS integer)) from t1 union select count(distinct 13) from t1) or -b<>19 or 17>=t1.a)),t1.e)-c-t1.d then t1.a else 19 end- - -11 FROM t1 WHERE d+a*~coalesce((select max((select count(distinct t1.e)-max(t1.d) from t1)) from t1 where not exists(select 1 from t1 where t1.e in (11-f*19,a,c-b)) and 11=t1.b),t1.a)=(t1.b) and -t1.b19 or 17>=t1.a)),t1.e)-c-t1.d then t1.a else 19 end- - -11 FROM t1 WHERE NOT (d+a*~coalesce((select max((select count(distinct t1.e)-max(t1.d) from t1)) from t1 where not exists(select 1 from t1 where t1.e in (11-f*19,a,c-b)) and 11=t1.b),t1.a)=(t1.b) and -t1.b19 or 17>=t1.a)),t1.e)-c-t1.d then t1.a else 19 end- - -11 FROM t1 WHERE NOT (d+a*~coalesce((select max((select count(distinct t1.e)-max(t1.d) from t1)) from t1 where not exists(select 1 from t1 where t1.e in (11-f*19,a,c-b)) and 11=t1.b),t1.a)=(t1.b) and -t1.bcoalesce((select max(coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where e | t1.f-19 between t1.e-a and b and e>=t1.d)),+d)) from t1 where (exists(select 1 from t1 where t1.b in (select 19 from t1 union select 17 from t1) or 11 between t1.b and d))),c)),t1.e)*t1.a<=c then b else t1.d end)) FROM t1 WHERE (select abs( -abs(abs(case count(*) when ~ -min(f)+case - -abs(+cast(avg(c*17) AS integer)) when count(*) then max(t1.a) else max(11) end+(cast(avg(e) AS integer)) then min(17) else count(*) end-cast(avg(a) AS integer)-count(*))))+ -cast(avg(t1.a) AS integer) | ((count(*))) from t1)+f in (select max((abs(+11*t1.a)/abs(t1.f))) from t1 union select max(d)-(( -count(distinct 11))) from t1)} +} {} +do_test randexpr-2.1729 { + db eval {SELECT -(abs(t1.a)/abs(case when coalesce((select max( -c) from t1 where t1.a*e>coalesce((select max(coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where e | t1.f-19 between t1.e-a and b and e>=t1.d)),+d)) from t1 where (exists(select 1 from t1 where t1.b in (select 19 from t1 union select 17 from t1) or 11 between t1.b and d))),c)),t1.e)*t1.a<=c then b else t1.d end)) FROM t1 WHERE NOT ((select abs( -abs(abs(case count(*) when ~ -min(f)+case - -abs(+cast(avg(c*17) AS integer)) when count(*) then max(t1.a) else max(11) end+(cast(avg(e) AS integer)) then min(17) else count(*) end-cast(avg(a) AS integer)-count(*))))+ -cast(avg(t1.a) AS integer) | ((count(*))) from t1)+f in (select max((abs(+11*t1.a)/abs(t1.f))) from t1 union select max(d)-(( -count(distinct 11))) from t1))} +} {0} +do_test randexpr-2.1730 { + db eval {SELECT -(abs(t1.a)/abs(case when coalesce((select max( -c) from t1 where t1.a*e>coalesce((select max(coalesce((select max(t1.d) from t1 where not exists(select 1 from t1 where e & t1.f-19 between t1.e-a and b and e>=t1.d)),+d)) from t1 where (exists(select 1 from t1 where t1.b in (select 19 from t1 union select 17 from t1) or 11 between t1.b and d))),c)),t1.e)*t1.a<=c then b else t1.d end)) FROM t1 WHERE NOT ((select abs( -abs(abs(case count(*) when ~ -min(f)+case - -abs(+cast(avg(c*17) AS integer)) when count(*) then max(t1.a) else max(11) end+(cast(avg(e) AS integer)) then min(17) else count(*) end-cast(avg(a) AS integer)-count(*))))+ -cast(avg(t1.a) AS integer) | ((count(*))) from t1)+f in (select max((abs(+11*t1.a)/abs(t1.f))) from t1 union select max(d)-(( -count(distinct 11))) from t1))} +} {0} +do_test randexpr-2.1731 { + db eval {SELECT case when ((select (+~~max(13)*count(distinct t1.c)) from t1)<>(select (+ -count(*)) from t1)) then +(17) else 19 end+~(abs(13)/abs(d))-t1.d FROM t1 WHERE coalesce((select (select -+ -count(distinct a)*count(*)+max(t1.b) from t1) from t1 where exists(select 1 from t1 where t1.b=c)),t1.c)+f<>t1.f} +} {-384} +do_test randexpr-2.1732 { + db eval {SELECT case when ((select (+~~max(13)*count(distinct t1.c)) from t1)<>(select (+ -count(*)) from t1)) then +(17) else 19 end+~(abs(13)/abs(d))-t1.d FROM t1 WHERE NOT (coalesce((select (select -+ -count(distinct a)*count(*)+max(t1.b) from t1) from t1 where exists(select 1 from t1 where t1.b=c)),t1.c)+f<>t1.f)} +} {} +do_test randexpr-2.1733 { + db eval {SELECT case t1.f when case when 17<=c and coalesce((select case when e in (case when (t1.a=c) then b else -13 end,t1.d,t1.a) then 13 else t1.b end from t1 where (b)=13),t1.d) in ((t1.e),b,t1.b) and d not between 19 and 11 then +(select ~ -~max(e)+count(*)+cast(avg((t1.c)) AS integer) from t1) when t1.f<>e and t1.ee and t1.et1.e then t1.d else (d) end in (select count(*) from t1 union select -abs(~abs(count(distinct d)) | min(t1.e))*count(*) from t1)),t1.f)) from t1 where a>13),d) not between t1.d and c)} +} {60000} +do_test randexpr-2.1738 { + db eval {SELECT +case + -(+t1.a)-~13+t1.b*t1.b+ -c+(select abs(case ~max(t1.c)++min( -13)+ -count(*)+(count(*)) | ((cast(avg(t1.e) AS integer))) when min(t1.c) then min(t1.d) else min(b) end)+min(13) | count(distinct f) | min(t1.a) from t1) when t1.e then 11-17 else t1.b*c end FROM t1 WHERE NOT ((~coalesce((select max(coalesce((select max(19) from t1 where case when case f-(coalesce((select ~11 from t1 where -19= -t1.f or b=t1.b),13)) when 19 then t1.d else t1.b end<=17 then 17 when t1.b>t1.e then t1.d else (d) end in (select count(*) from t1 union select -abs(~abs(count(distinct d)) | min(t1.e))*count(*) from t1)),t1.f)) from t1 where a>13),d) not between t1.d and c))} +} {} +do_test randexpr-2.1739 { + db eval {SELECT +case + -(+t1.a)-~13+t1.b*t1.b+ -c+(select abs(case ~max(t1.c)++min( -13)+ -count(*)+(count(*)) & ((cast(avg(t1.e) AS integer))) when min(t1.c) then min(t1.d) else min(b) end)+min(13) & count(distinct f) & min(t1.a) from t1) when t1.e then 11-17 else t1.b*c end FROM t1 WHERE (~coalesce((select max(coalesce((select max(19) from t1 where case when case f-(coalesce((select ~11 from t1 where -19= -t1.f or b=t1.b),13)) when 19 then t1.d else t1.b end<=17 then 17 when t1.b>t1.e then t1.d else (d) end in (select count(*) from t1 union select -abs(~abs(count(distinct d)) | min(t1.e))*count(*) from t1)),t1.f)) from t1 where a>13),d) not between t1.d and c)} +} {60000} +do_test randexpr-2.1740 { + db eval {SELECT (abs(e)/abs((+b)*coalesce((select c+c+t1.a+t1.e+t1.a+t1.a | 17+e*(t1.c) from t1 where a in (select count(distinct t1.c)-+count(*) from t1 union select - -( -max(t1.f))-count(distinct t1.b)+min(t1.b)*count(*)+count(distinct a) from t1)),t1.a)+e))*19 FROM t1 WHERE coalesce((select 11 from t1 where case t1.e-(t1.a) when (f) then ((19)) else t1.f end+ -t1.b+a+coalesce((select coalesce((select d from t1 where exists(select 1 from t1 where 13+(t1.a)<>19 or 17 not in (c,e,t1.c) or f not in (t1.e,t1.a, -f))),~ -13+e) from t1 where b between (11) and t1.f),t1.a)<=t1.d), -c)<=11} +} {0} +do_test randexpr-2.1741 { + db eval {SELECT (abs(e)/abs((+b)*coalesce((select c+c+t1.a+t1.e+t1.a+t1.a | 17+e*(t1.c) from t1 where a in (select count(distinct t1.c)-+count(*) from t1 union select - -( -max(t1.f))-count(distinct t1.b)+min(t1.b)*count(*)+count(distinct a) from t1)),t1.a)+e))*19 FROM t1 WHERE NOT (coalesce((select 11 from t1 where case t1.e-(t1.a) when (f) then ((19)) else t1.f end+ -t1.b+a+coalesce((select coalesce((select d from t1 where exists(select 1 from t1 where 13+(t1.a)<>19 or 17 not in (c,e,t1.c) or f not in (t1.e,t1.a, -f))),~ -13+e) from t1 where b between (11) and t1.f),t1.a)<=t1.d), -c)<=11)} +} {} +do_test randexpr-2.1742 { + db eval {SELECT (abs(e)/abs((+b)*coalesce((select c+c+t1.a+t1.e+t1.a+t1.a & 17+e*(t1.c) from t1 where a in (select count(distinct t1.c)-+count(*) from t1 union select - -( -max(t1.f))-count(distinct t1.b)+min(t1.b)*count(*)+count(distinct a) from t1)),t1.a)+e))*19 FROM t1 WHERE coalesce((select 11 from t1 where case t1.e-(t1.a) when (f) then ((19)) else t1.f end+ -t1.b+a+coalesce((select coalesce((select d from t1 where exists(select 1 from t1 where 13+(t1.a)<>19 or 17 not in (c,e,t1.c) or f not in (t1.e,t1.a, -f))),~ -13+e) from t1 where b between (11) and t1.f),t1.a)<=t1.d), -c)<=11} +} {0} +do_test randexpr-2.1743 { + db eval {SELECT case coalesce((select t1.f from t1 where not exists(select 1 from t1 where coalesce((select max(d) from t1 where 13 not in (11,coalesce((select max((+f)) from t1 where not d>=f or e in (select 11-t1.b from t1 union select t1.d from t1) or not exists(select 1 from t1 where -b in (select t1.d from t1 union select b from t1) or t1.a<>b or t1.d>e) or t1.a not between (t1.f) and t1.e),+f),t1.e)),t1.f)*t1.b not in (13,t1.b,t1.f))),t1.a)*b when c then b else t1.f end FROM t1 WHERE case when c*coalesce((select max(19+t1.e*~case case t1.e when t1.f then -t1.a else 11 end when 11 then t1.a else (select cast(avg(a) AS integer) from t1) end- -t1.b*coalesce((select 19 from t1 where t1.f in ((a),t1.d,t1.c)),a)) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where t1.a not in (t1.b,t1.a,17)))),13)>=a then b when t1.c>t1.a then d else 17 end not in (a,17,t1.b)} +} {600} +do_test randexpr-2.1744 { + db eval {SELECT case coalesce((select t1.f from t1 where not exists(select 1 from t1 where coalesce((select max(d) from t1 where 13 not in (11,coalesce((select max((+f)) from t1 where not d>=f or e in (select 11-t1.b from t1 union select t1.d from t1) or not exists(select 1 from t1 where -b in (select t1.d from t1 union select b from t1) or t1.a<>b or t1.d>e) or t1.a not between (t1.f) and t1.e),+f),t1.e)),t1.f)*t1.b not in (13,t1.b,t1.f))),t1.a)*b when c then b else t1.f end FROM t1 WHERE NOT (case when c*coalesce((select max(19+t1.e*~case case t1.e when t1.f then -t1.a else 11 end when 11 then t1.a else (select cast(avg(a) AS integer) from t1) end- -t1.b*coalesce((select 19 from t1 where t1.f in ((a),t1.d,t1.c)),a)) from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where t1.a not in (t1.b,t1.a,17)))),13)>=a then b when t1.c>t1.a then d else 17 end not in (a,17,t1.b))} +} {} +do_test randexpr-2.1745 { + db eval {SELECT (abs(case when (c*+~t1.d++t1.b+a-case when (select +case count(*)+min(d) when -count(distinct 17) then max(t1.b) else -cast(avg(d) AS integer) end from t1) in (select cast(avg(c) AS integer) from t1 union select ((count(*))) from t1) then t1.a* -f else f end*c*19-(f)-t1.c-t1.f+t1.d>=f) then (t1.d) else d end)/abs(t1.b)) FROM t1 WHERE coalesce((select a from t1 where t1.d not in ( -13*d,19,t1.a)),(abs(coalesce((select case when c>=t1.e then b else case ~t1.d+a-+t1.b+17 when case when t1.e+t1.e not between e and (c) then t1.d when d>a then t1.d else t1.c end | t1.a-(d) then t1.f else c end end from t1 where d>=t1.c),13))/abs(t1.c)))=t1.e} +} {} +do_test randexpr-2.1746 { + db eval {SELECT (abs(case when (c*+~t1.d++t1.b+a-case when (select +case count(*)+min(d) when -count(distinct 17) then max(t1.b) else -cast(avg(d) AS integer) end from t1) in (select cast(avg(c) AS integer) from t1 union select ((count(*))) from t1) then t1.a* -f else f end*c*19-(f)-t1.c-t1.f+t1.d>=f) then (t1.d) else d end)/abs(t1.b)) FROM t1 WHERE NOT (coalesce((select a from t1 where t1.d not in ( -13*d,19,t1.a)),(abs(coalesce((select case when c>=t1.e then b else case ~t1.d+a-+t1.b+17 when case when t1.e+t1.e not between e and (c) then t1.d when d>a then t1.d else t1.c end | t1.a-(d) then t1.f else c end end from t1 where d>=t1.c),13))/abs(t1.c)))=t1.e)} +} {2} +do_test randexpr-2.1747 { + db eval {SELECT d+coalesce((select max(coalesce((select f from t1 where coalesce((select 17 | t1.b from t1 where 11 not in ((t1.e),+a-f,t1.c | b+17*t1.e-c)), -c) in (select -count(distinct e)-+max(t1.b) from t1 union select count(distinct c)+cast(avg(t1.b) AS integer) from t1)),17)) from t1 where not t1.c(select ~~+(min(11-11)) | ~ -(count(*)) from t1)*(case when t1.d=19 then a when not t1.a in (11,t1.e,c) or t1.a not between t1.f and e then t1.a else t1.e end+19) then 13 when 19 between -17 and t1.a then t1.a else 19 end end>=t1.f and t1.e>t1.a} +} {} +do_test randexpr-2.1748 { + db eval {SELECT d+coalesce((select max(coalesce((select f from t1 where coalesce((select 17 | t1.b from t1 where 11 not in ((t1.e),+a-f,t1.c | b+17*t1.e-c)), -c) in (select -count(distinct e)-+max(t1.b) from t1 union select count(distinct c)+cast(avg(t1.b) AS integer) from t1)),17)) from t1 where not t1.c(select ~~+(min(11-11)) | ~ -(count(*)) from t1)*(case when t1.d=19 then a when not t1.a in (11,t1.e,c) or t1.a not between t1.f and e then t1.a else t1.e end+19) then 13 when 19 between -17 and t1.a then t1.a else 19 end end>=t1.f and t1.e>t1.a)} +} {1117} +do_test randexpr-2.1749 { + db eval {SELECT d+coalesce((select max(coalesce((select f from t1 where coalesce((select 17 & t1.b from t1 where 11 not in ((t1.e),+a-f,t1.c & b+17*t1.e-c)), -c) in (select -count(distinct e)-+max(t1.b) from t1 union select count(distinct c)+cast(avg(t1.b) AS integer) from t1)),17)) from t1 where not t1.c(select ~~+(min(11-11)) | ~ -(count(*)) from t1)*(case when t1.d=19 then a when not t1.a in (11,t1.e,c) or t1.a not between t1.f and e then t1.a else t1.e end+19) then 13 when 19 between -17 and t1.a then t1.a else 19 end end>=t1.f and t1.e>t1.a)} +} {1117} +do_test randexpr-2.1750 { + db eval {SELECT (select case ~ -(~case case cast(avg(t1.e) AS integer) when min(case when t1.c between coalesce((select t1.b from t1 where d in (select f from t1 union select t1.e from t1)),(e)) and t1.d and (19=(11)) then 17 else b end) | max((13))-min(t1.c) | -count(distinct t1.d)*max(11) then count(*) else max(f) end*count(*)-(( -count(distinct f))) when min(t1.c) then (count(distinct (13))) else max((b)) end)+max(t1.a) when (max(t1.c)) then -cast(avg(a) AS integer) else cast(avg(t1.c) AS integer) end from t1) FROM t1 WHERE (f) not between c and 17 | t1.b | coalesce((select t1.d from t1 where t1.d*~case when a<=f or (case t1.f when d+17+17 then e else +case when (11<>17) then 11 when -t1.b not in (e,19,(f)) then t1.c else a end+13 end>= -t1.f) then ~ -t1.c else c end*t1.f*a*17<=t1.f),17)} +} {300} +do_test randexpr-2.1751 { + db eval {SELECT (select case ~ -(~case case cast(avg(t1.e) AS integer) when min(case when t1.c between coalesce((select t1.b from t1 where d in (select f from t1 union select t1.e from t1)),(e)) and t1.d and (19=(11)) then 17 else b end) | max((13))-min(t1.c) | -count(distinct t1.d)*max(11) then count(*) else max(f) end*count(*)-(( -count(distinct f))) when min(t1.c) then (count(distinct (13))) else max((b)) end)+max(t1.a) when (max(t1.c)) then -cast(avg(a) AS integer) else cast(avg(t1.c) AS integer) end from t1) FROM t1 WHERE NOT ((f) not between c and 17 | t1.b | coalesce((select t1.d from t1 where t1.d*~case when a<=f or (case t1.f when d+17+17 then e else +case when (11<>17) then 11 when -t1.b not in (e,19,(f)) then t1.c else a end+13 end>= -t1.f) then ~ -t1.c else c end*t1.f*a*17<=t1.f),17))} +} {} +do_test randexpr-2.1752 { + db eval {SELECT (select case ~ -(~case case cast(avg(t1.e) AS integer) when min(case when t1.c between coalesce((select t1.b from t1 where d in (select f from t1 union select t1.e from t1)),(e)) and t1.d and (19=(11)) then 17 else b end) & max((13))-min(t1.c) & -count(distinct t1.d)*max(11) then count(*) else max(f) end*count(*)-(( -count(distinct f))) when min(t1.c) then (count(distinct (13))) else max((b)) end)+max(t1.a) when (max(t1.c)) then -cast(avg(a) AS integer) else cast(avg(t1.c) AS integer) end from t1) FROM t1 WHERE (f) not between c and 17 | t1.b | coalesce((select t1.d from t1 where t1.d*~case when a<=f or (case t1.f when d+17+17 then e else +case when (11<>17) then 11 when -t1.b not in (e,19,(f)) then t1.c else a end+13 end>= -t1.f) then ~ -t1.c else c end*t1.f*a*17<=t1.f),17)} +} {300} +do_test randexpr-2.1753 { + db eval {SELECT (select abs(min(t1.b)) from t1)-f | case when +t1.d*d not in (t1.f,t1.a,case when ~t1.f-17*c<>t1.a then 11 when 19 in (select (+count(distinct b)) | cast(avg(19) AS integer)*count(*) from t1 union select count(distinct t1.d) from t1) then d else d end+19+b) then (a) else 17 end*13+d FROM t1 WHERE t1.f<>(abs(t1.a)/abs(coalesce((select max(case when coalesce((select max((select count(*) from t1)) from t1 where f<>t1.a),coalesce((select max(11) from t1 where 17+coalesce((select t1.a from t1 where a in (select +~cast(avg(d+11) AS integer) from t1 union select count(distinct coalesce((select max((13)) from t1 where not (t1.f)<>19),f)*d) from t1)),19)+t1.e between 13 and (t1.b)),e))>=e then d else t1.f end) from t1 where ((not f>= -t1.b))),t1.c)))} +} {-268} +do_test randexpr-2.1754 { + db eval {SELECT (select abs(min(t1.b)) from t1)-f | case when +t1.d*d not in (t1.f,t1.a,case when ~t1.f-17*c<>t1.a then 11 when 19 in (select (+count(distinct b)) | cast(avg(19) AS integer)*count(*) from t1 union select count(distinct t1.d) from t1) then d else d end+19+b) then (a) else 17 end*13+d FROM t1 WHERE NOT (t1.f<>(abs(t1.a)/abs(coalesce((select max(case when coalesce((select max((select count(*) from t1)) from t1 where f<>t1.a),coalesce((select max(11) from t1 where 17+coalesce((select t1.a from t1 where a in (select +~cast(avg(d+11) AS integer) from t1 union select count(distinct coalesce((select max((13)) from t1 where not (t1.f)<>19),f)*d) from t1)),19)+t1.e between 13 and (t1.b)),e))>=e then d else t1.f end) from t1 where ((not f>= -t1.b))),t1.c))))} +} {} +do_test randexpr-2.1755 { + db eval {SELECT (select abs(min(t1.b)) from t1)-f & case when +t1.d*d not in (t1.f,t1.a,case when ~t1.f-17*c<>t1.a then 11 when 19 in (select (+count(distinct b)) & cast(avg(19) AS integer)*count(*) from t1 union select count(distinct t1.d) from t1) then d else d end+19+b) then (a) else 17 end*13+d FROM t1 WHERE t1.f<>(abs(t1.a)/abs(coalesce((select max(case when coalesce((select max((select count(*) from t1)) from t1 where f<>t1.a),coalesce((select max(11) from t1 where 17+coalesce((select t1.a from t1 where a in (select +~cast(avg(d+11) AS integer) from t1 union select count(distinct coalesce((select max((13)) from t1 where not (t1.f)<>19),f)*d) from t1)),19)+t1.e between 13 and (t1.b)),e))>=e then d else t1.f end) from t1 where ((not f>= -t1.b))),t1.c)))} +} {1568} +do_test randexpr-2.1756 { + db eval {SELECT coalesce((select max(a) from t1 where a>a*(((t1.d)) | a)-+case t1.a-t1.d-19+coalesce((select max(t1.c) from t1 where ~(select -cast(avg(a+d) AS integer) from t1) not in (~((17)),t1.a,(t1.e))),b)+a*(c) when t1.f then a else t1.f end-17+c),13)*t1.a FROM t1 WHERE t1.b*t1.d*11*case 13 | t1.a when (case when not exists(select 1 from t1 where t1.a not between coalesce((select f-a from t1 where a not in (11,d,(a)) or e<=d and 11=t1.e),d)+e and t1.c) and (t1.a>=t1.f or (t1.a)>=t1.a) then (c)+t1.d else a end)* -t1.a then e else t1.f end | 13>=b} +} {1300} +do_test randexpr-2.1757 { + db eval {SELECT coalesce((select max(a) from t1 where a>a*(((t1.d)) | a)-+case t1.a-t1.d-19+coalesce((select max(t1.c) from t1 where ~(select -cast(avg(a+d) AS integer) from t1) not in (~((17)),t1.a,(t1.e))),b)+a*(c) when t1.f then a else t1.f end-17+c),13)*t1.a FROM t1 WHERE NOT (t1.b*t1.d*11*case 13 | t1.a when (case when not exists(select 1 from t1 where t1.a not between coalesce((select f-a from t1 where a not in (11,d,(a)) or e<=d and 11=t1.e),d)+e and t1.c) and (t1.a>=t1.f or (t1.a)>=t1.a) then (c)+t1.d else a end)* -t1.a then e else t1.f end | 13>=b)} +} {} +do_test randexpr-2.1758 { + db eval {SELECT coalesce((select max(a) from t1 where a>a*(((t1.d)) & a)-+case t1.a-t1.d-19+coalesce((select max(t1.c) from t1 where ~(select -cast(avg(a+d) AS integer) from t1) not in (~((17)),t1.a,(t1.e))),b)+a*(c) when t1.f then a else t1.f end-17+c),13)*t1.a FROM t1 WHERE t1.b*t1.d*11*case 13 | t1.a when (case when not exists(select 1 from t1 where t1.a not between coalesce((select f-a from t1 where a not in (11,d,(a)) or e<=d and 11=t1.e),d)+e and t1.c) and (t1.a>=t1.f or (t1.a)>=t1.a) then (c)+t1.d else a end)* -t1.a then e else t1.f end | 13>=b} +} {10000} +do_test randexpr-2.1759 { + db eval {SELECT (abs(t1.f)/abs(11*19 | case when (e+t1.b*t1.d+(abs(case -13+t1.d*t1.a-+coalesce((select t1.d from t1 where t1.b not between b and d and d in (select c from t1 union select d from t1)),(19)) when d then 13 else d end*t1.e)/abs(d))+f not between e and t1.a) then ( -f) else d end*a)) FROM t1 WHERE a in (select abs(max(b))-count(distinct case when d not between coalesce((select max(13) from t1 where a+a<+(19)), -f*case (select -cast(avg(t1.c) AS integer)*cast(avg(c) AS integer)-cast(avg(13) AS integer) from t1)*coalesce((select d from t1 where (e=(f))),t1.d) when t1.a then 17 else 19 end) and d then t1.f when (19 between t1.e and -a) then t1.a else (t1.c) end) from t1 union select max(t1.e)+~min(t1.c) from t1)} +} {} +do_test randexpr-2.1760 { + db eval {SELECT (abs(t1.f)/abs(11*19 | case when (e+t1.b*t1.d+(abs(case -13+t1.d*t1.a-+coalesce((select t1.d from t1 where t1.b not between b and d and d in (select c from t1 union select d from t1)),(19)) when d then 13 else d end*t1.e)/abs(d))+f not between e and t1.a) then ( -f) else d end*a)) FROM t1 WHERE NOT (a in (select abs(max(b))-count(distinct case when d not between coalesce((select max(13) from t1 where a+a<+(19)), -f*case (select -cast(avg(t1.c) AS integer)*cast(avg(c) AS integer)-cast(avg(13) AS integer) from t1)*coalesce((select d from t1 where (e=(f))),t1.d) when t1.a then 17 else 19 end) and d then t1.f when (19 between t1.e and -a) then t1.a else (t1.c) end) from t1 union select max(t1.e)+~min(t1.c) from t1))} +} {0} +do_test randexpr-2.1761 { + db eval {SELECT (abs(t1.f)/abs(11*19 & case when (e+t1.b*t1.d+(abs(case -13+t1.d*t1.a-+coalesce((select t1.d from t1 where t1.b not between b and d and d in (select c from t1 union select d from t1)),(19)) when d then 13 else d end*t1.e)/abs(d))+f not between e and t1.a) then ( -f) else d end*a)) FROM t1 WHERE NOT (a in (select abs(max(b))-count(distinct case when d not between coalesce((select max(13) from t1 where a+a<+(19)), -f*case (select -cast(avg(t1.c) AS integer)*cast(avg(c) AS integer)-cast(avg(13) AS integer) from t1)*coalesce((select d from t1 where (e=(f))),t1.d) when t1.a then 17 else 19 end) and d then t1.f when (19 between t1.e and -a) then t1.a else (t1.c) end) from t1 union select max(t1.e)+~min(t1.c) from t1))} +} {4} +do_test randexpr-2.1762 { + db eval {SELECT +t1.d | (d)*t1.e | (select case abs((max(t1.e)-abs(+case min(a) | (~(min(~t1.c)))*(abs(abs(count(*))+count(distinct b)*count(distinct 17)))*max(c) when max(t1.c) then max(t1.d) else cast(avg(d) AS integer) end | max(t1.a))))*cast(avg(11) AS integer) when (cast(avg( -a) AS integer)) then min(19) else -count(distinct 13) end from t1)+t1.b FROM t1 WHERE not exists(select 1 from t1 where e13) or t1.a*t1.f- -a>=t1.d or d in (select -case cast(avg(b) AS integer) when max(19) then count(distinct -t1.f) else count(distinct f) end* -max(t1.d) from t1 union select -cast(avg(13) AS integer) from t1) and 11 between t1.f and d then case when t1.f not between b and 13 then f else t1.e end-t1.c when t1.d in (t1.e,b,d) then t1.f else -t1.d end-t1.d)*d*f>=a} +} {} +do_test randexpr-2.1766 { + db eval {SELECT coalesce((select max(e) from t1 where -(abs(~(t1.f+b))/abs(t1.f)) not in (~case 11+c*case when -t1.d not between coalesce((select max(d) from t1 where f- -t1.f+t1.f-13-e13) or t1.a*t1.f- -a>=t1.d or d in (select -case cast(avg(b) AS integer) when max(19) then count(distinct -t1.f) else count(distinct f) end* -max(t1.d) from t1 union select -cast(avg(13) AS integer) from t1) and 11 between t1.f and d then case when t1.f not between b and 13 then f else t1.e end-t1.c when t1.d in (t1.e,b,d) then t1.f else -t1.d end-t1.d)*d*f>=a)} +} {500} +do_test randexpr-2.1767 { + db eval {SELECT case when ~case when t1.a | case when exists(select 1 from t1 where 19 in (select (count(*))-count(*) from t1 union select -min(b) from t1) or t1.f not in (17,11,t1.c) and t1.d in (a,19,t1.a)) then ~c | 11 else 17 end* -19 in (select count(*) from t1 union select abs( - -case ~cast(avg(t1.b) AS integer) when min(b) then max(a) else (max( -d)) end | count(*)) from t1) then t1.a else t1.c end | b in (select f from t1 union select 13 from t1) then t1.b when t1.a<>(17) then c else t1.a end FROM t1 WHERE exists(select 1 from t1 where d<>13)} +} {300} +do_test randexpr-2.1768 { + db eval {SELECT case when ~case when t1.a | case when exists(select 1 from t1 where 19 in (select (count(*))-count(*) from t1 union select -min(b) from t1) or t1.f not in (17,11,t1.c) and t1.d in (a,19,t1.a)) then ~c | 11 else 17 end* -19 in (select count(*) from t1 union select abs( - -case ~cast(avg(t1.b) AS integer) when min(b) then max(a) else (max( -d)) end | count(*)) from t1) then t1.a else t1.c end | b in (select f from t1 union select 13 from t1) then t1.b when t1.a<>(17) then c else t1.a end FROM t1 WHERE NOT (exists(select 1 from t1 where d<>13))} +} {} +do_test randexpr-2.1769 { + db eval {SELECT case when ~case when t1.a & case when exists(select 1 from t1 where 19 in (select (count(*))-count(*) from t1 union select -min(b) from t1) or t1.f not in (17,11,t1.c) and t1.d in (a,19,t1.a)) then ~c & 11 else 17 end* -19 in (select count(*) from t1 union select abs( - -case ~cast(avg(t1.b) AS integer) when min(b) then max(a) else (max( -d)) end & count(*)) from t1) then t1.a else t1.c end & b in (select f from t1 union select 13 from t1) then t1.b when t1.a<>(17) then c else t1.a end FROM t1 WHERE exists(select 1 from t1 where d<>13)} +} {300} +do_test randexpr-2.1770 { + db eval {SELECT coalesce((select a+t1.d from t1 where t1.d+coalesce((select max(case when e not between 11 and case when (abs(f)/abs(t1.f+19*t1.b))>e then ~d when not not 17 in (13,17,t1.a) then f else t1.f end then 11 when b<17 then t1.b else f end) from t1 where exists(select 1 from t1 where (c<>c))), -f)+t1.c in (select (t1.e) from t1 union select c from t1)),c) FROM t1 WHERE not (t1.a)<=case a when t1.f then +coalesce((select max(c) from t1 where (abs(d-11)/abs(t1.a))+t1.f<=d*d*t1.a+coalesce((select 19 from t1 where (select cast(avg(f) AS integer) from t1)*t1.f+19+ -13 in ((t1.d),c,t1.a)),t1.c) or ((not exists(select 1 from t1 where 19 in (select e from t1 union select -11 from t1))))),c) else e end} +} {} +do_test randexpr-2.1771 { + db eval {SELECT coalesce((select a+t1.d from t1 where t1.d+coalesce((select max(case when e not between 11 and case when (abs(f)/abs(t1.f+19*t1.b))>e then ~d when not not 17 in (13,17,t1.a) then f else t1.f end then 11 when b<17 then t1.b else f end) from t1 where exists(select 1 from t1 where (c<>c))), -f)+t1.c in (select (t1.e) from t1 union select c from t1)),c) FROM t1 WHERE NOT (not (t1.a)<=case a when t1.f then +coalesce((select max(c) from t1 where (abs(d-11)/abs(t1.a))+t1.f<=d*d*t1.a+coalesce((select 19 from t1 where (select cast(avg(f) AS integer) from t1)*t1.f+19+ -13 in ((t1.d),c,t1.a)),t1.c) or ((not exists(select 1 from t1 where 19 in (select e from t1 union select -11 from t1))))),c) else e end)} +} {300} +do_test randexpr-2.1772 { + db eval {SELECT (abs( -c+b)/abs(case when ~11 in (select t1.c from t1 union select coalesce((select t1.f from t1 where coalesce((select max(17) from t1 where coalesce((select case -t1.d when t1.e then a else b end-(t1.d) from t1 where t1.a not between -a and t1.b or t1.f=t1.b) and (f)>= -13),t1.b) from t1) then t1.c when t1.b<=t1.f then 13 else t1.e end)) FROM t1 WHERE (d-coalesce((select max(case 11 when +13-17 | 13 | coalesce((select t1.b from t1 where ((abs(t1.b)/abs((abs(b)/abs(+(19)))*t1.c)) | a in ( -t1.c,t1.a,t1.b))),d)* -d then 13 else 11 end) from t1 where e not in (d,11,11) or t1.e>t1.e),17)+t1.a>b)} +} {7} +do_test randexpr-2.1773 { + db eval {SELECT (abs( -c+b)/abs(case when ~11 in (select t1.c from t1 union select coalesce((select t1.f from t1 where coalesce((select max(17) from t1 where coalesce((select case -t1.d when t1.e then a else b end-(t1.d) from t1 where t1.a not between -a and t1.b or t1.f=t1.b) and (f)>= -13),t1.b) from t1) then t1.c when t1.b<=t1.f then 13 else t1.e end)) FROM t1 WHERE NOT ((d-coalesce((select max(case 11 when +13-17 | 13 | coalesce((select t1.b from t1 where ((abs(t1.b)/abs((abs(b)/abs(+(19)))*t1.c)) | a in ( -t1.c,t1.a,t1.b))),d)* -d then 13 else 11 end) from t1 where e not in (d,11,11) or t1.e>t1.e),17)+t1.a>b))} +} {} +do_test randexpr-2.1774 { + db eval {SELECT coalesce((select max(17) from t1 where (e* -t1.f*e*c-coalesce((select max(t1.f) from t1 where t1.c between case when e+~ -t1.e+11 in (select c from t1 union select t1.a from t1) and t1.d>=c then 19 else ( - -(t1.a)) end*c+f and t1.b),13) not in (t1.b,e,t1.c) and (11) not in (b,( -t1.b),13))),19) FROM t1 WHERE d>e+f} +} {} +do_test randexpr-2.1775 { + db eval {SELECT coalesce((select max(17) from t1 where (e* -t1.f*e*c-coalesce((select max(t1.f) from t1 where t1.c between case when e+~ -t1.e+11 in (select c from t1 union select t1.a from t1) and t1.d>=c then 19 else ( - -(t1.a)) end*c+f and t1.b),13) not in (t1.b,e,t1.c) and (11) not in (b,( -t1.b),13))),19) FROM t1 WHERE NOT (d>e+f)} +} {17} +do_test randexpr-2.1776 { + db eval {SELECT case when t1.b in (select case 13-(select case count(*) when count(distinct (abs(19)/abs(t1.d)))*~count(distinct 13)*(max((abs(t1.e*d*f)/abs(17)))) then -case - -count(distinct e) when min(19) then (cast(avg(17) AS integer)) else count(distinct t1.a) end*max(t1.b)-cast(avg(a) AS integer) else count(distinct t1.d) end from t1)+t1.b*d when t1.c+t1.a then f else t1.f end from t1 union select t1.c from t1) then t1.a when a in (select 11 from t1 union select a from t1) then a else e end FROM t1 WHERE (case when case 11+case f when e then d else (abs(e)/abs(19))*a end when 19 then b else d end= -19 then 13 else t1.e end between 17 and t1.a or b>=17 and ((( -t1.f))>=t1.c and 17 between t1.c and 19 and t1.c between t1.d and a or t1.d=17) or c in (b,13,17))} +} {} +do_test randexpr-2.1777 { + db eval {SELECT case when t1.b in (select case 13-(select case count(*) when count(distinct (abs(19)/abs(t1.d)))*~count(distinct 13)*(max((abs(t1.e*d*f)/abs(17)))) then -case - -count(distinct e) when min(19) then (cast(avg(17) AS integer)) else count(distinct t1.a) end*max(t1.b)-cast(avg(a) AS integer) else count(distinct t1.d) end from t1)+t1.b*d when t1.c+t1.a then f else t1.f end from t1 union select t1.c from t1) then t1.a when a in (select 11 from t1 union select a from t1) then a else e end FROM t1 WHERE NOT ((case when case 11+case f when e then d else (abs(e)/abs(19))*a end when 19 then b else d end= -19 then 13 else t1.e end between 17 and t1.a or b>=17 and ((( -t1.f))>=t1.c and 17 between t1.c and 19 and t1.c between t1.d and a or t1.d=17) or c in (b,13,17)))} +} {100} +do_test randexpr-2.1778 { + db eval {SELECT case when coalesce((select case when (not exists(select 1 from t1 where t1.f<>t1.f)) then case when d-t1.e*t1.d=((select (count(distinct t1.a)) from t1)) then t1.a when 13 not in ( -b,13,19) then t1.b else e end when t1.e=13 then e else 17 end-17*b from t1 where (t1.d in (d,t1.e,t1.f))),( -f)) not in (d,t1.e,c) then t1.d else -t1.f end* -t1.b FROM t1 WHERE not exists(select 1 from t1 where 11 in (select max(coalesce((select max(case when e+coalesce((select max(d) from t1 where not at1.f)) then case when d-t1.e*t1.d=((select (count(distinct t1.a)) from t1)) then t1.a when 13 not in ( -b,13,19) then t1.b else e end when t1.e=13 then e else 17 end-17*b from t1 where (t1.d in (d,t1.e,t1.f))),( -f)) not in (d,t1.e,c) then t1.d else -t1.f end* -t1.b FROM t1 WHERE NOT (not exists(select 1 from t1 where 11 in (select max(coalesce((select max(case when e+coalesce((select max(d) from t1 where not ab or not t1.f in (11,t1.a,t1.e)),t1.a) | e then c else e end from t1 where -t1.a<11),13))/abs(t1.b))-t1.b*17 from t1 where c=t1.c),17) FROM t1 WHERE t1.e+e>=coalesce((select max(t1.d) from t1 where +(t1.f) not between c and f),case when exists(select 1 from t1 where t1.e+t1.c<>(abs(e*(select -count(*) from t1))/abs(t1.e*coalesce((select max((select cast(avg(13) AS integer) from t1)) from t1 where not (a) not between -c and -17), -d)+ -a+t1.f))) then case when e between 17 and d then a else 19 end when not c between e and 11 then 13 else t1.a end)} +} {-3051} +do_test randexpr-2.1781 { + db eval {SELECT coalesce((select (abs(~c*t1.a+t1.b*coalesce((select case c when b+coalesce((select t1.b-case e when 19 then b else b end*11 from t1 where t1.b<>b or not t1.f in (11,t1.a,t1.e)),t1.a) | e then c else e end from t1 where -t1.a<11),13))/abs(t1.b))-t1.b*17 from t1 where c=t1.c),17) FROM t1 WHERE NOT (t1.e+e>=coalesce((select max(t1.d) from t1 where +(t1.f) not between c and f),case when exists(select 1 from t1 where t1.e+t1.c<>(abs(e*(select -count(*) from t1))/abs(t1.e*coalesce((select max((select cast(avg(13) AS integer) from t1)) from t1 where not (a) not between -c and -17), -d)+ -a+t1.f))) then case when e between 17 and d then a else 19 end when not c between e and 11 then 13 else t1.a end))} +} {} +do_test randexpr-2.1782 { + db eval {SELECT coalesce((select (abs(~c*t1.a+t1.b*coalesce((select case c when b+coalesce((select t1.b-case e when 19 then b else b end*11 from t1 where t1.b<>b or not t1.f in (11,t1.a,t1.e)),t1.a) & e then c else e end from t1 where -t1.a<11),13))/abs(t1.b))-t1.b*17 from t1 where c=t1.c),17) FROM t1 WHERE t1.e+e>=coalesce((select max(t1.d) from t1 where +(t1.f) not between c and f),case when exists(select 1 from t1 where t1.e+t1.c<>(abs(e*(select -count(*) from t1))/abs(t1.e*coalesce((select max((select cast(avg(13) AS integer) from t1)) from t1 where not (a) not between -c and -17), -d)+ -a+t1.f))) then case when e between 17 and d then a else 19 end when not c between e and 11 then 13 else t1.a end)} +} {-3051} +do_test randexpr-2.1783 { + db eval {SELECT t1.a-~17-t1.c+t1.c | (c) | (13)*coalesce((select max((case when 11 in (case when (19 in (select abs(max(c)) from t1 union select ( -cast(avg(19) AS integer)) from t1)) then 13 when t1.a= -t1.a then t1.b else c end,a,13) then t1.e when t1.b in (t1.a,13, -19) then d else t1.a end)) from t1 where t1.d between t1.d and t1.b and t1.d<=17),t1.d)*11 | t1.e FROM t1 WHERE e in (select 11 from t1 union select a from t1)} +} {} +do_test randexpr-2.1784 { + db eval {SELECT t1.a-~17-t1.c+t1.c | (c) | (13)*coalesce((select max((case when 11 in (case when (19 in (select abs(max(c)) from t1 union select ( -cast(avg(19) AS integer)) from t1)) then 13 when t1.a= -t1.a then t1.b else c end,a,13) then t1.e when t1.b in (t1.a,13, -19) then d else t1.a end)) from t1 where t1.d between t1.d and t1.b and t1.d<=17),t1.d)*11 | t1.e FROM t1 WHERE NOT (e in (select 11 from t1 union select a from t1))} +} {57342} +do_test randexpr-2.1785 { + db eval {SELECT t1.a-~17-t1.c+t1.c & (c) & (13)*coalesce((select max((case when 11 in (case when (19 in (select abs(max(c)) from t1 union select ( -cast(avg(19) AS integer)) from t1)) then 13 when t1.a= -t1.a then t1.b else c end,a,13) then t1.e when t1.b in (t1.a,13, -19) then d else t1.a end)) from t1 where t1.d between t1.d and t1.b and t1.d<=17),t1.d)*11 & t1.e FROM t1 WHERE NOT (e in (select 11 from t1 union select a from t1))} +} {32} +do_test randexpr-2.1786 { + db eval {SELECT (abs(case when 11 not between t1.d and case coalesce((select case c+case when b in (case when a<=t1.b then (t1.a) when f not in (d,t1.f, -(a)) then (t1.a) else c end,t1.a,b) then 11 when (t1.c not between 17 and -d) then t1.d else e end+e*t1.a when 19 then b else t1.e end from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where -(19)=d))),t1.d) when c then a else -17 end or a>=19 then 17 else b end+ -13)/abs(b)) FROM t1 WHERE not exists(select 1 from t1 where not e+case 13 when 11 then +t1.d else t1.f+11 end*a-19+t1.c+a in (~e | coalesce((select ~a*+(abs( -case case b*e when f then e else -13 end when t1.d then t1.b else t1.b end)/abs(17))+t1.b from t1 where t1.a=e),d),e,e))} +} {} +do_test randexpr-2.1787 { + db eval {SELECT (abs(case when 11 not between t1.d and case coalesce((select case c+case when b in (case when a<=t1.b then (t1.a) when f not in (d,t1.f, -(a)) then (t1.a) else c end,t1.a,b) then 11 when (t1.c not between 17 and -d) then t1.d else e end+e*t1.a when 19 then b else t1.e end from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where -(19)=d))),t1.d) when c then a else -17 end or a>=19 then 17 else b end+ -13)/abs(b)) FROM t1 WHERE NOT (not exists(select 1 from t1 where not e+case 13 when 11 then +t1.d else t1.f+11 end*a-19+t1.c+a in (~e | coalesce((select ~a*+(abs( -case case b*e when f then e else -13 end when t1.d then t1.b else t1.b end)/abs(17))+t1.b from t1 where t1.a=e),d),e,e)))} +} {0} +do_test randexpr-2.1788 { + db eval {SELECT t1.c-coalesce((select t1.e from t1 where not 17 | (select abs(min((t1.c) | +case 19 when d then f else t1.c end*(13)+a)- -count(*)) from t1)>t1.c and (exists(select 1 from t1 where c in (select f from t1 union select a from t1))) or t1.e>t1.c),coalesce((select e*(e) from t1 where not exists(select 1 from t1 where b not in (f,a,19))),c)) FROM t1 WHERE t1.f*t1.e*b+coalesce((select case when 17 not in (case e++t1.d+19*11 when case when 11 in (select -min(t1.a)*min(t1.e)+cast(avg(t1.a) AS integer) from t1 union select -count(*) from t1) then 13 else 11 end*17 then a else t1.a end,(t1.b),t1.d) then t1.f else -b end from t1 where t1.b not between 17 and (a)),d)-t1.d-c*bt1.c and (exists(select 1 from t1 where c in (select f from t1 union select a from t1))) or t1.e>t1.c),coalesce((select e*(e) from t1 where not exists(select 1 from t1 where b not in (f,a,19))),c)) FROM t1 WHERE NOT (t1.f*t1.e*b+coalesce((select case when 17 not in (case e++t1.d+19*11 when case when 11 in (select -min(t1.a)*min(t1.e)+cast(avg(t1.a) AS integer) from t1 union select -count(*) from t1) then 13 else 11 end*17 then a else t1.a end,(t1.b),t1.d) then t1.f else -b end from t1 where t1.b not between 17 and (a)),d)-t1.d-c*bt1.c and (exists(select 1 from t1 where c in (select f from t1 union select a from t1))) or t1.e>t1.c),coalesce((select e*(e) from t1 where not exists(select 1 from t1 where b not in (f,a,19))),c)) FROM t1 WHERE NOT (t1.f*t1.e*b+coalesce((select case when 17 not in (case e++t1.d+19*11 when case when 11 in (select -min(t1.a)*min(t1.e)+cast(avg(t1.a) AS integer) from t1 union select -count(*) from t1) then 13 else 11 end*17 then a else t1.a end,(t1.b),t1.d) then t1.f else -b end from t1 where t1.b not between 17 and (a)),d)-t1.d-c*b= -b+t1.f | 19 then t1.d else 11 end else t1.a end-t1.e else d end not between f and t1.f) then c else e end) from t1 where f>=t1.b and t1.c between t1.f and t1.a),e)*d*b FROM t1 WHERE t1.b in (select 11-case when (t1.a+19<=case when c>=(19) then 11 else t1.e+t1.a*c end*e and t1.f in (select case abs(+abs( -count(*) | count(*)*count(distinct c)+max(13))) when min(d) then min(b) else min(t1.b) end | cast(avg(t1.e) AS integer) from t1 union select count(distinct t1.e) from t1)) then t1.a else t1.f end*17 from t1 union select t1.a from t1)} +} {} +do_test randexpr-2.1792 { + db eval {SELECT c-coalesce((select max(case when (case t1.a when a then case f when e*e then ~c | case when +c>= -b+t1.f | 19 then t1.d else 11 end else t1.a end-t1.e else d end not between f and t1.f) then c else e end) from t1 where f>=t1.b and t1.c between t1.f and t1.a),e)*d*b FROM t1 WHERE NOT (t1.b in (select 11-case when (t1.a+19<=case when c>=(19) then 11 else t1.e+t1.a*c end*e and t1.f in (select case abs(+abs( -count(*) | count(*)*count(distinct c)+max(13))) when min(d) then min(b) else min(t1.b) end | cast(avg(t1.e) AS integer) from t1 union select count(distinct t1.e) from t1)) then t1.a else t1.f end*17 from t1 union select t1.a from t1))} +} {-39999700} +do_test randexpr-2.1793 { + db eval {SELECT c-coalesce((select max(case when (case t1.a when a then case f when e*e then ~c & case when +c>= -b+t1.f & 19 then t1.d else 11 end else t1.a end-t1.e else d end not between f and t1.f) then c else e end) from t1 where f>=t1.b and t1.c between t1.f and t1.a),e)*d*b FROM t1 WHERE NOT (t1.b in (select 11-case when (t1.a+19<=case when c>=(19) then 11 else t1.e+t1.a*c end*e and t1.f in (select case abs(+abs( -count(*) | count(*)*count(distinct c)+max(13))) when min(d) then min(b) else min(t1.b) end | cast(avg(t1.e) AS integer) from t1 union select count(distinct t1.e) from t1)) then t1.a else t1.f end*17 from t1 union select t1.a from t1))} +} {-39999700} +do_test randexpr-2.1794 { + db eval {SELECT coalesce((select f from t1 where ~coalesce((select max(b-e) from t1 where 13 in (select d from t1 union select d from t1)),(abs(t1.f)/abs(t1.f)))-t1.d+case a when t1.b then 13 else case when 19>case a when t1.a then 13 else -d end or e<>c then coalesce((select max(a) from t1 where t1.e not between (13) and t1.d),11) when b in (select t1.a from t1 union select t1.f from t1) then 19 else a end end-b>11),17) FROM t1 WHERE b in (select e-17 from t1 union select d from t1)} +} {} +do_test randexpr-2.1795 { + db eval {SELECT coalesce((select f from t1 where ~coalesce((select max(b-e) from t1 where 13 in (select d from t1 union select d from t1)),(abs(t1.f)/abs(t1.f)))-t1.d+case a when t1.b then 13 else case when 19>case a when t1.a then 13 else -d end or e<>c then coalesce((select max(a) from t1 where t1.e not between (13) and t1.d),11) when b in (select t1.a from t1 union select t1.f from t1) then 19 else a end end-b>11),17) FROM t1 WHERE NOT (b in (select e-17 from t1 union select d from t1))} +} {17} +do_test randexpr-2.1796 { + db eval {SELECT coalesce((select case case when 13<>((abs(t1.b)/abs(f+t1.c))) then 11 else coalesce((select max(b) from t1 where (b=(abs((select min((select case -min(11) when count(distinct d) then count(*) else min(t1.c) end from t1)) from t1))/abs(t1.f))-c)), -19)*e end*d* -e+t1.d when 13 then c else c end+b from t1 where d>13 or (b between t1.e and 19)),a) FROM t1 WHERE not exists(select 1 from t1 where ((not not exists(select 1 from t1 where ((case when coalesce((select max(19) from t1 where case when b>=e and f between t1.d and t1.c or ( -t1.b)=t1.f then b+a else 11 end in (d,t1.d,(17))),t1.d)>t1.b then (t1.f) else d end*e*t1.e<=t1.b)) or 13<>13)) or 17((abs(t1.b)/abs(f+t1.c))) then 11 else coalesce((select max(b) from t1 where (b=(abs((select min((select case -min(11) when count(distinct d) then count(*) else min(t1.c) end from t1)) from t1))/abs(t1.f))-c)), -19)*e end*d* -e+t1.d when 13 then c else c end+b from t1 where d>13 or (b between t1.e and 19)),a) FROM t1 WHERE NOT (not exists(select 1 from t1 where ((not not exists(select 1 from t1 where ((case when coalesce((select max(19) from t1 where case when b>=e and f between t1.d and t1.c or ( -t1.b)=t1.f then b+a else 11 end in (d,t1.d,(17))),t1.d)>t1.b then (t1.f) else d end*e*t1.e<=t1.b)) or 13<>13)) or 17t1.d then e+t1.c when 19 between t1.f and t1.f then 11 else e end between t1.e and 17) and c=t1.f),t1.c) not between t1.a and (19) then c else t1.b end*a-19 and b then b when a not in (a,t1.f,11) then a else a end FROM t1 WHERE (select abs((+min(t1.c)*min(t1.d)*count(*)))*count(*)++count(distinct ~13*11+t1.f) | case abs(+count(*)) when min(t1.e) then count(*) else max(13) end from t1)*t1.b between d and a++19 and t1.c in (select ~((abs(17)/abs(c)))-d from t1 union select t1.f from t1)} +} {} +do_test randexpr-2.1799 { + db eval {SELECT ~case when 19 not between ~case when coalesce((select max(t1.c*(select cast(avg(13) AS integer) from t1)) from t1 where exists(select 1 from t1 where case when (t1.b in (d,b,t1.c)) and 13>t1.d then e+t1.c when 19 between t1.f and t1.f then 11 else e end between t1.e and 17) and c=t1.f),t1.c) not between t1.a and (19) then c else t1.b end*a-19 and b then b when a not in (a,t1.f,11) then a else a end FROM t1 WHERE NOT ((select abs((+min(t1.c)*min(t1.d)*count(*)))*count(*)++count(distinct ~13*11+t1.f) | case abs(+count(*)) when min(t1.e) then count(*) else max(13) end from t1)*t1.b between d and a++19 and t1.c in (select ~((abs(17)/abs(c)))-d from t1 union select t1.f from t1))} +} {-101} +do_test randexpr-2.1800 { + db eval {SELECT (t1.d)+(abs(coalesce((select ((abs(case t1.e when a+(abs(11)/abs(b)) then t1.f else case coalesce((select max(d+c) from t1 where +19+11t1.c),d))/abs(t1.d))-11 | (17) | b FROM t1 WHERE (select ~min(b)+count(distinct 17) from t1)>(select max((abs((13))/abs(coalesce((select case when b*13 in (case when e=t1.b then c when 11<>e then f else t1.b end,t1.f,t1.a) then d when not exists(select 1 from t1 where t1.f<>e) then t1.a else c end from t1 where t1.e=13),t1.f) | b)))+(~~cast(avg(f) AS integer)-min((13))) from t1)} +} {} +do_test randexpr-2.1801 { + db eval {SELECT (t1.d)+(abs(coalesce((select ((abs(case t1.e when a+(abs(11)/abs(b)) then t1.f else case coalesce((select max(d+c) from t1 where +19+11t1.c),d))/abs(t1.d))-11 | (17) | b FROM t1 WHERE NOT ((select ~min(b)+count(distinct 17) from t1)>(select max((abs((13))/abs(coalesce((select case when b*13 in (case when e=t1.b then c when 11<>e then f else t1.b end,t1.f,t1.a) then d when not exists(select 1 from t1 where t1.f<>e) then t1.a else c end from t1 where t1.e=13),t1.f) | b)))+(~~cast(avg(f) AS integer)-min((13))) from t1))} +} {477} +do_test randexpr-2.1802 { + db eval {SELECT (t1.d)+(abs(coalesce((select ((abs(case t1.e when a+(abs(11)/abs(b)) then t1.f else case coalesce((select max(d+c) from t1 where +19+11t1.c),d))/abs(t1.d))-11 & (17) & b FROM t1 WHERE NOT ((select ~min(b)+count(distinct 17) from t1)>(select max((abs((13))/abs(coalesce((select case when b*13 in (case when e=t1.b then c when 11<>e then f else t1.b end,t1.f,t1.a) then d when not exists(select 1 from t1 where t1.f<>e) then t1.a else c end from t1 where t1.e=13),t1.f) | b)))+(~~cast(avg(f) AS integer)-min((13))) from t1))} +} {0} +do_test randexpr-2.1803 { + db eval {SELECT d+case coalesce((select t1.f from t1 where coalesce((select max((11)) from t1 where (coalesce((select d from t1 where ((case b when ( -a) then 19 else e end)) not in ( -d,t1.c,13)),b))>t1.b and ((c in (select ~~cast(avg(t1.b) AS integer)+ -(max(t1.e)) from t1 union select max(c) from t1) and (e) in (select -count(distinct 17) from t1 union select count(*) from t1) or 11<>t1.c))),t1.b) not between (f) and 11),t1.d) when (19) then e else 13 end-t1.f FROM t1 WHERE exists(select 1 from t1 where (t1.a between case when e | b*c-19 | at1.b and ((c in (select ~~cast(avg(t1.b) AS integer)+ -(max(t1.e)) from t1 union select max(c) from t1) and (e) in (select -count(distinct 17) from t1 union select count(*) from t1) or 11<>t1.c))),t1.b) not between (f) and 11),t1.d) when (19) then e else 13 end-t1.f FROM t1 WHERE NOT (exists(select 1 from t1 where (t1.a between case when e | b*c-19 | a=f or (select -count(*) from t1) in (select t1.c from t1 union select 17 from t1)),b)*e not between case coalesce((select max(~case when 17>t1.e then d else 13 end) from t1 where not t1.c<=17),t1.c) when 13 then c else t1.e end+t1.c-t1.e and t1.e),t1.e) FROM t1 WHERE case ~case when not exists(select 1 from t1 where f<=~t1.d) then (abs(coalesce((select ~19 from t1 where d+t1.f=b),d))/abs(e)) when d in (select +min(11) from t1 union select ( -abs(count(distinct e)))+count(distinct t1.a) from t1) then e else t1.d end when -d then t1.e else t1.b end=t1.f or t1.d not in (t1.c,t1.e,t1.e) and t1.c not in (17,t1.a,e)} +} {300} +do_test randexpr-2.1806 { + db eval {SELECT coalesce((select c from t1 where - -19-coalesce((select t1.e from t1 where not f<=b-17 or not -13>=f or (select -count(*) from t1) in (select t1.c from t1 union select 17 from t1)),b)*e not between case coalesce((select max(~case when 17>t1.e then d else 13 end) from t1 where not t1.c<=17),t1.c) when 13 then c else t1.e end+t1.c-t1.e and t1.e),t1.e) FROM t1 WHERE NOT (case ~case when not exists(select 1 from t1 where f<=~t1.d) then (abs(coalesce((select ~19 from t1 where d+t1.f=b),d))/abs(e)) when d in (select +min(11) from t1 union select ( -abs(count(distinct e)))+count(distinct t1.a) from t1) then e else t1.d end when -d then t1.e else t1.b end=t1.f or t1.d not in (t1.c,t1.e,t1.e) and t1.c not in (17,t1.a,e))} +} {} +do_test randexpr-2.1807 { + db eval {SELECT case when t1.e<=~d then case when t1.d-e in (~t1.c-case e*case when t1.e not in (t1.d,19,f) then e else b end*e when (19) then t1.a else -e end,19,17) then t1.f when t1.d not in (t1.b,b,17) then t1.b else 19 end when 13= -t1.f and not (19=t1.d) then t1.f else (d) end FROM t1 WHERE 19<>d} +} {400} +do_test randexpr-2.1808 { + db eval {SELECT case when t1.e<=~d then case when t1.d-e in (~t1.c-case e*case when t1.e not in (t1.d,19,f) then e else b end*e when (19) then t1.a else -e end,19,17) then t1.f when t1.d not in (t1.b,b,17) then t1.b else 19 end when 13= -t1.f and not (19=t1.d) then t1.f else (d) end FROM t1 WHERE NOT (19<>d)} +} {} +do_test randexpr-2.1809 { + db eval {SELECT (select max(case when (t1.d<=t1.a*t1.b) then t1.e else case when t1.a> -t1.c*t1.f then b else b*(a) end end)*min(+ -19-(select min(a) from t1)-+17*case when not exists(select 1 from t1 where (select abs(cast(avg(a) AS integer)) from t1)=t1.a) then e when 19>=a then 13 else t1.a end*19-e) from t1) FROM t1 WHERE t1.e in (select max(t1.e)-cast(avg(e) AS integer) from t1 union select (~+count(*) | count(*) | cast(avg((abs(coalesce((select max(case f+c-17 when t1.b then t1.e else t1.d end) from t1 where 17 in (select a from t1 union select t1.b from t1)),a))/abs( -t1.e))) AS integer)+~case count(*) when cast(avg(t1.d) AS integer) then -cast(avg(t1.e) AS integer) else count(distinct d) end-max(13)+ -min(t1.a) | min((17)) | count(distinct d))-min(e) from t1)} +} {} +do_test randexpr-2.1810 { + db eval {SELECT (select max(case when (t1.d<=t1.a*t1.b) then t1.e else case when t1.a> -t1.c*t1.f then b else b*(a) end end)*min(+ -19-(select min(a) from t1)-+17*case when not exists(select 1 from t1 where (select abs(cast(avg(a) AS integer)) from t1)=t1.a) then e when 19>=a then 13 else t1.a end*19-e) from t1) FROM t1 WHERE NOT (t1.e in (select max(t1.e)-cast(avg(e) AS integer) from t1 union select (~+count(*) | count(*) | cast(avg((abs(coalesce((select max(case f+c-17 when t1.b then t1.e else t1.d end) from t1 where 17 in (select a from t1 union select t1.b from t1)),a))/abs( -t1.e))) AS integer)+~case count(*) when cast(avg(t1.d) AS integer) then -cast(avg(t1.e) AS integer) else count(distinct d) end-max(13)+ -min(t1.a) | min((17)) | count(distinct d))-min(e) from t1))} +} {-16459500} +do_test randexpr-2.1811 { + db eval {SELECT case when case (select max(t1.b)*min(case when (abs(t1.e)/abs(d)) in (select 19 from t1 union select +t1.d from t1) then t1.d when t1.d=d or 11 in (t1.c,b,t1.b) and 13 in (select max(b)-count(distinct b) from t1 union select count(distinct -t1.c) from t1) then f else 17 end) from t1) when t1.a then 11 else t1.d end+t1.a>c or t1.c between 13 and a then f when (t1.b)>=t1.a then d else b end FROM t1 WHERE (not exists(select 1 from t1 where coalesce((select max(e) from t1 where -b+a-(abs(c)/abs(b))-( -t1.a)-t1.c>=d),d) in (select count(distinct a) from t1 union select cast(avg(t1.b) AS integer) from t1) and exists(select 1 from t1 where not t1.d<>f) and t1.a in (select min(t1.a)+max(a)*max(19)*count(distinct c) from t1 union select ((count(distinct 11))) from t1) or t1.c>(13) and a between (t1.f) and 13))} +} {600} +do_test randexpr-2.1812 { + db eval {SELECT case when case (select max(t1.b)*min(case when (abs(t1.e)/abs(d)) in (select 19 from t1 union select +t1.d from t1) then t1.d when t1.d=d or 11 in (t1.c,b,t1.b) and 13 in (select max(b)-count(distinct b) from t1 union select count(distinct -t1.c) from t1) then f else 17 end) from t1) when t1.a then 11 else t1.d end+t1.a>c or t1.c between 13 and a then f when (t1.b)>=t1.a then d else b end FROM t1 WHERE NOT ((not exists(select 1 from t1 where coalesce((select max(e) from t1 where -b+a-(abs(c)/abs(b))-( -t1.a)-t1.c>=d),d) in (select count(distinct a) from t1 union select cast(avg(t1.b) AS integer) from t1) and exists(select 1 from t1 where not t1.d<>f) and t1.a in (select min(t1.a)+max(a)*max(19)*count(distinct c) from t1 union select ((count(distinct 11))) from t1) or t1.c>(13) and a between (t1.f) and 13)))} +} {} +do_test randexpr-2.1813 { + db eval {SELECT f*~13*(abs(13*d- -(abs(case when ~coalesce((select max(c) from t1 where b>case when not exists(select 1 from t1 where f not in ( - -(t1.b),t1.b,t1.f)) then e when t1.c<>f then c else 13 end),17) | -19 not in (f,b,f) then -b when not 13 in (select max((19)) from t1 union select count(*) | count(*) from t1) and 11 not between t1.b and e or 13 in (t1.a, -e,(t1.c)) then a else 11 end)/abs(t1.c))*b | t1.b)/abs(f))*f*f FROM t1 WHERE ~case f when coalesce((select max(17) from t1 where b+t1.f*case 11 when coalesce((select max(t1.f) from t1 where 17>t1.f),19)-t1.b-t1.b | d then b else c end+t1.d*11-t1.c<=case when b>=a then 19 else f end | t1.a),13) then f else t1.e end*t1.e*17-d in (select 13 from t1 union select t1.e from t1)} +} {} +do_test randexpr-2.1814 { + db eval {SELECT f*~13*(abs(13*d- -(abs(case when ~coalesce((select max(c) from t1 where b>case when not exists(select 1 from t1 where f not in ( - -(t1.b),t1.b,t1.f)) then e when t1.c<>f then c else 13 end),17) | -19 not in (f,b,f) then -b when not 13 in (select max((19)) from t1 union select count(*) | count(*) from t1) and 11 not between t1.b and e or 13 in (t1.a, -e,(t1.c)) then a else 11 end)/abs(t1.c))*b | t1.b)/abs(f))*f*f FROM t1 WHERE NOT (~case f when coalesce((select max(17) from t1 where b+t1.f*case 11 when coalesce((select max(t1.f) from t1 where 17>t1.f),19)-t1.b-t1.b | d then b else c end+t1.d*11-t1.c<=case when b>=a then 19 else f end | t1.a),13) then f else t1.e end*t1.e*17-d in (select 13 from t1 union select t1.e from t1))} +} {-24192000000} +do_test randexpr-2.1815 { + db eval {SELECT f*~13*(abs(13*d- -(abs(case when ~coalesce((select max(c) from t1 where b>case when not exists(select 1 from t1 where f not in ( - -(t1.b),t1.b,t1.f)) then e when t1.c<>f then c else 13 end),17) & -19 not in (f,b,f) then -b when not 13 in (select max((19)) from t1 union select count(*) & count(*) from t1) and 11 not between t1.b and e or 13 in (t1.a, -e,(t1.c)) then a else 11 end)/abs(t1.c))*b & t1.b)/abs(f))*f*f FROM t1 WHERE NOT (~case f when coalesce((select max(17) from t1 where b+t1.f*case 11 when coalesce((select max(t1.f) from t1 where 17>t1.f),19)-t1.b-t1.b | d then b else c end+t1.d*11-t1.c<=case when b>=a then 19 else f end | t1.a),13) then f else t1.e end*t1.e*17-d in (select 13 from t1 union select t1.e from t1))} +} {0} +do_test randexpr-2.1816 { + db eval {SELECT t1.b | (select case max( -17)-min(17) when cast(avg(a) AS integer)*(+cast(avg(f) AS integer)-cast(avg(case when not exists(select 1 from t1 where not case when t1.c<>t1.b or -d not between b and a then 11 when (11)=11 then b else t1.b end in (t1.d,t1.c,13)) then 13 when t1.e not between 17 and t1.b then t1.c else t1.d end*t1.b) AS integer))-cast(avg(19) AS integer)*~max(t1.c)-((max(13)))*(count(*))+(max(11)) then count(distinct 13) else cast(avg(17) AS integer) end from t1) FROM t1 WHERE (abs(t1.c)/abs(case t1.d when t1.f then 13 else t1.f+13 end)) not between c and 19} +} {217} +do_test randexpr-2.1817 { + db eval {SELECT t1.b | (select case max( -17)-min(17) when cast(avg(a) AS integer)*(+cast(avg(f) AS integer)-cast(avg(case when not exists(select 1 from t1 where not case when t1.c<>t1.b or -d not between b and a then 11 when (11)=11 then b else t1.b end in (t1.d,t1.c,13)) then 13 when t1.e not between 17 and t1.b then t1.c else t1.d end*t1.b) AS integer))-cast(avg(19) AS integer)*~max(t1.c)-((max(13)))*(count(*))+(max(11)) then count(distinct 13) else cast(avg(17) AS integer) end from t1) FROM t1 WHERE NOT ((abs(t1.c)/abs(case t1.d when t1.f then 13 else t1.f+13 end)) not between c and 19)} +} {} +do_test randexpr-2.1818 { + db eval {SELECT t1.b & (select case max( -17)-min(17) when cast(avg(a) AS integer)*(+cast(avg(f) AS integer)-cast(avg(case when not exists(select 1 from t1 where not case when t1.c<>t1.b or -d not between b and a then 11 when (11)=11 then b else t1.b end in (t1.d,t1.c,13)) then 13 when t1.e not between 17 and t1.b then t1.c else t1.d end*t1.b) AS integer))-cast(avg(19) AS integer)*~max(t1.c)-((max(13)))*(count(*))+(max(11)) then count(distinct 13) else cast(avg(17) AS integer) end from t1) FROM t1 WHERE (abs(t1.c)/abs(case t1.d when t1.f then 13 else t1.f+13 end)) not between c and 19} +} {0} +do_test randexpr-2.1819 { + db eval {SELECT case +c-case (select case count(distinct 13) when min(19*e) then ~count(*) else ~min(case when not +13*(case when e*c>=e then e else f end)-a+c not in (b,t1.b,t1.e) then 19 else 17 end*a) end from t1) when 11 then 11 else c end+t1.c when t1.b then d else 19 end FROM t1 WHERE t1.a<>~coalesce((select max(e) from t1 where 13-17*13<>19*17-f or coalesce((select max(~case +t1.d-f*e | c+(17)+a | c*((b)) when a then t1.a else d end-d) from t1 where t1.c>= -t1.a),t1.b) | 19>t1.a),c)} +} {19} +do_test randexpr-2.1820 { + db eval {SELECT case +c-case (select case count(distinct 13) when min(19*e) then ~count(*) else ~min(case when not +13*(case when e*c>=e then e else f end)-a+c not in (b,t1.b,t1.e) then 19 else 17 end*a) end from t1) when 11 then 11 else c end+t1.c when t1.b then d else 19 end FROM t1 WHERE NOT (t1.a<>~coalesce((select max(e) from t1 where 13-17*13<>19*17-f or coalesce((select max(~case +t1.d-f*e | c+(17)+a | c*((b)) when a then t1.a else d end-d) from t1 where t1.c>= -t1.a),t1.b) | 19>t1.a),c))} +} {} +do_test randexpr-2.1821 { + db eval {SELECT coalesce((select max(t1.d) from t1 where f between case when (19 not in (t1.b,(a),t1.a)) or t1.a=t1.b | -(select +cast(avg(17-case when -c<=17 then a when -11 not in (11,19,a) then e else 11 end-t1.a*d) AS integer) from t1) then t1.b when (11)*f in (13,t1.a,a) or t1.a=e),f)*b-f and t1.f),t1.b) else d end+19 when t1.a then 11 else e end-t1.a)} +} {} +do_test randexpr-2.1822 { + db eval {SELECT coalesce((select max(t1.d) from t1 where f between case when (19 not in (t1.b,(a),t1.a)) or t1.a=t1.b | -(select +cast(avg(17-case when -c<=17 then a when -11 not in (11,19,a) then e else 11 end-t1.a*d) AS integer) from t1) then t1.b when (11)*f in (13,t1.a,a) or t1.a=e),f)*b-f and t1.f),t1.b) else d end+19 when t1.a then 11 else e end-t1.a))} +} {-200} +do_test randexpr-2.1823 { + db eval {SELECT coalesce((select max(t1.d) from t1 where f between case when (19 not in (t1.b,(a),t1.a)) or t1.a=t1.b & -(select +cast(avg(17-case when -c<=17 then a when -11 not in (11,19,a) then e else 11 end-t1.a*d) AS integer) from t1) then t1.b when (11)*f in (13,t1.a,a) or t1.a=e),f)*b-f and t1.f),t1.b) else d end+19 when t1.a then 11 else e end-t1.a))} +} {-200} +do_test randexpr-2.1824 { + db eval {SELECT case when not -t1.c in (coalesce((select d from t1 where t1.a not in (t1.c+f, -f,19) and t1.b in (select max(t1.d)+min(19)*min(t1.e) from t1 union select count(distinct d) from t1) and (t1.d) in (select -count(*) from t1 union select -count(*) from t1)),d* -t1.e),b,f) or -c not in (a, -t1.a,t1.e) then case when b between 17 and t1.b and a not in (t1.a,e,t1.e) then t1.d else 19 end*t1.b else t1.d end+t1.d FROM t1 WHERE (abs((17))/abs(11 | e*e+d++t1.d)) in (19+t1.f,e,(abs(13)/abs( -t1.c)))} +} {4200} +do_test randexpr-2.1825 { + db eval {SELECT case when not -t1.c in (coalesce((select d from t1 where t1.a not in (t1.c+f, -f,19) and t1.b in (select max(t1.d)+min(19)*min(t1.e) from t1 union select count(distinct d) from t1) and (t1.d) in (select -count(*) from t1 union select -count(*) from t1)),d* -t1.e),b,f) or -c not in (a, -t1.a,t1.e) then case when b between 17 and t1.b and a not in (t1.a,e,t1.e) then t1.d else 19 end*t1.b else t1.d end+t1.d FROM t1 WHERE NOT ((abs((17))/abs(11 | e*e+d++t1.d)) in (19+t1.f,e,(abs(13)/abs( -t1.c))))} +} {} +do_test randexpr-2.1826 { + db eval {SELECT case when ( -(select ~ -~ -(max(c))-min(t1.e) | count(distinct (11)) | min(t1.a) from t1)-case when case d when a then case when t1.e=t1.a then t1.c else c end else c end<=t1.f then t1.b when t1.c not in (a,19,c) then b else 17 end>=19) or d in (19,f, -11) then 19 else (select case min(t1.a)-(cast(avg(t1.f) AS integer))-(min(11)) when count(*) then count(*) else count(distinct a) end from t1) end FROM t1 WHERE not exists(select 1 from t1 where (abs(11-13)/abs(f))>19*~19+t1.d-t1.f+coalesce((select max(f) from t1 where t1.a-t1.e+case when case when a not between t1.c and 19 and -t1.e>t1.c then case when t1.f in (t1.d,e,t1.f) then d when c not in (11,t1.c,d) then t1.a else a end when t1.b=11 then t1.c else t1.e end>e then e else e end-11t1.f} +} {1} +do_test randexpr-2.1827 { + db eval {SELECT case when ( -(select ~ -~ -(max(c))-min(t1.e) | count(distinct (11)) | min(t1.a) from t1)-case when case d when a then case when t1.e=t1.a then t1.c else c end else c end<=t1.f then t1.b when t1.c not in (a,19,c) then b else 17 end>=19) or d in (19,f, -11) then 19 else (select case min(t1.a)-(cast(avg(t1.f) AS integer))-(min(11)) when count(*) then count(*) else count(distinct a) end from t1) end FROM t1 WHERE NOT (not exists(select 1 from t1 where (abs(11-13)/abs(f))>19*~19+t1.d-t1.f+coalesce((select max(f) from t1 where t1.a-t1.e+case when case when a not between t1.c and 19 and -t1.e>t1.c then case when t1.f in (t1.d,e,t1.f) then d when c not in (11,t1.c,d) then t1.a else a end when t1.b=11 then t1.c else t1.e end>e then e else e end-11t1.f)} +} {} +do_test randexpr-2.1828 { + db eval {SELECT case when ( -(select ~ -~ -(max(c))-min(t1.e) & count(distinct (11)) & min(t1.a) from t1)-case when case d when a then case when t1.e=t1.a then t1.c else c end else c end<=t1.f then t1.b when t1.c not in (a,19,c) then b else 17 end>=19) or d in (19,f, -11) then 19 else (select case min(t1.a)-(cast(avg(t1.f) AS integer))-(min(11)) when count(*) then count(*) else count(distinct a) end from t1) end FROM t1 WHERE not exists(select 1 from t1 where (abs(11-13)/abs(f))>19*~19+t1.d-t1.f+coalesce((select max(f) from t1 where t1.a-t1.e+case when case when a not between t1.c and 19 and -t1.e>t1.c then case when t1.f in (t1.d,e,t1.f) then d when c not in (11,t1.c,d) then t1.a else a end when t1.b=11 then t1.c else t1.e end>e then e else e end-11t1.f} +} {1} +do_test randexpr-2.1829 { + db eval {SELECT t1.e | t1.a*~(17)-t1.c*f*f-coalesce((select max( -t1.a+coalesce((select t1.a from t1 where 19 not between 17 and f),(t1.b))*c+11) from t1 where 19 in (select -cast(avg(f) AS integer)-cast(avg(a) AS integer)*count(distinct d) from t1 union select count(*) from t1) and t1.d in (17,t1.d, -t1.c) or 19<>19),a)*11 FROM t1 WHERE not +19+coalesce((select -19 from t1 where t1.c | e in (select ~ -abs(case ~abs(+(count(distinct 17) | case ~(max(t1.a))+(+~ -min(17)) when abs(min(t1.c)) then count(distinct 17) else -cast(avg(t1.e) AS integer) end)*cast(avg(c) AS integer)*cast(avg(t1.b) AS integer)) when count(distinct t1.d) then min(b) else -cast(avg(d) AS integer) end) from t1 union select count(*) from t1)),13)>13} +} {} +do_test randexpr-2.1830 { + db eval {SELECT t1.e | t1.a*~(17)-t1.c*f*f-coalesce((select max( -t1.a+coalesce((select t1.a from t1 where 19 not between 17 and f),(t1.b))*c+11) from t1 where 19 in (select -cast(avg(f) AS integer)-cast(avg(a) AS integer)*count(distinct d) from t1 union select count(*) from t1) and t1.d in (17,t1.d, -t1.c) or 19<>19),a)*11 FROM t1 WHERE NOT (not +19+coalesce((select -19 from t1 where t1.c | e in (select ~ -abs(case ~abs(+(count(distinct 17) | case ~(max(t1.a))+(+~ -min(17)) when abs(min(t1.c)) then count(distinct 17) else -cast(avg(t1.e) AS integer) end)*cast(avg(c) AS integer)*cast(avg(t1.b) AS integer)) when count(distinct t1.d) then min(b) else -cast(avg(d) AS integer) end) from t1 union select count(*) from t1)),13)>13)} +} {-108002820} +do_test randexpr-2.1831 { + db eval {SELECT t1.e & t1.a*~(17)-t1.c*f*f-coalesce((select max( -t1.a+coalesce((select t1.a from t1 where 19 not between 17 and f),(t1.b))*c+11) from t1 where 19 in (select -cast(avg(f) AS integer)-cast(avg(a) AS integer)*count(distinct d) from t1 union select count(*) from t1) and t1.d in (17,t1.d, -t1.c) or 19<>19),a)*11 FROM t1 WHERE NOT (not +19+coalesce((select -19 from t1 where t1.c | e in (select ~ -abs(case ~abs(+(count(distinct 17) | case ~(max(t1.a))+(+~ -min(17)) when abs(min(t1.c)) then count(distinct 17) else -cast(avg(t1.e) AS integer) end)*cast(avg(c) AS integer)*cast(avg(t1.b) AS integer)) when count(distinct t1.d) then min(b) else -cast(avg(d) AS integer) end) from t1 union select count(*) from t1)),13)>13)} +} {420} +do_test randexpr-2.1832 { + db eval {SELECT case when t1.a<(abs((abs(13)/abs(case t1.e+11*17*case +case case when ~19>=t1.c then f when f not in (a,e,d) then 19 else b end when 19 then 19 else b end | -c when c then t1.c else c end*d-t1.e when e then 13 else c end)))/abs(t1.b)) then 17 when t1.b not in (t1.a,13,e) then e else -t1.c end FROM t1 WHERE 19>=11} +} {500} +do_test randexpr-2.1833 { + db eval {SELECT case when t1.a<(abs((abs(13)/abs(case t1.e+11*17*case +case case when ~19>=t1.c then f when f not in (a,e,d) then 19 else b end when 19 then 19 else b end | -c when c then t1.c else c end*d-t1.e when e then 13 else c end)))/abs(t1.b)) then 17 when t1.b not in (t1.a,13,e) then e else -t1.c end FROM t1 WHERE NOT (19>=11)} +} {} +do_test randexpr-2.1834 { + db eval {SELECT case when t1.a<(abs((abs(13)/abs(case t1.e+11*17*case +case case when ~19>=t1.c then f when f not in (a,e,d) then 19 else b end when 19 then 19 else b end & -c when c then t1.c else c end*d-t1.e when e then 13 else c end)))/abs(t1.b)) then 17 when t1.b not in (t1.a,13,e) then e else -t1.c end FROM t1 WHERE 19>=11} +} {500} +do_test randexpr-2.1835 { + db eval {SELECT coalesce((select (select count(*)-+count(*) from t1) from t1 where +t1.f+t1.f<~case when exists(select 1 from t1 where coalesce((select t1.a from t1 where b-19(11) then d else (c) end+e+t1.d),c) FROM t1 WHERE case when t1.f+(select min(t1.c+(abs(13+(abs(t1.e+d-11-e+d+c)/abs(t1.e))-c*t1.f)/abs(t1.b))) from t1)+f=d or t1.b not between t1.e and t1.a then 11-a when (13 in (13,19,19)) then t1.d else t1.b end(11) then d else (c) end+e+t1.d),c) FROM t1 WHERE NOT (case when t1.f+(select min(t1.c+(abs(13+(abs(t1.e+d-11-e+d+c)/abs(t1.e))-c*t1.f)/abs(t1.b))) from t1)+f=d or t1.b not between t1.e and t1.a then 11-a when (13 in (13,19,19)) then t1.d else t1.b end=t1.b)),((d))) and t1.c then 19 else 13 end FROM t1 WHERE d*a in (case when 19>t1.e then c | (select +~count(distinct t1.b)-++abs(min(11)+ -~min(t1.b)+ -(max(t1.d))-min(t1.b)-count(distinct t1.f)) | max(f) from t1) else a+t1.c end,t1.a+case 19 when (11*a)*t1.c then d else a end*t1.a-d,f)} +} {} +do_test randexpr-2.1838 { + db eval {SELECT case when not exists(select 1 from t1 where not exists(select 1 from t1 where (case when (abs(a)/abs(t1.f))=t1.b)),((d))) and t1.c then 19 else 13 end FROM t1 WHERE NOT (d*a in (case when 19>t1.e then c | (select +~count(distinct t1.b)-++abs(min(11)+ -~min(t1.b)+ -(max(t1.d))-min(t1.b)-count(distinct t1.f)) | max(f) from t1) else a+t1.c end,t1.a+case 19 when (11*a)*t1.c then d else a end*t1.a-d,f))} +} {-14} +do_test randexpr-2.1839 { + db eval {SELECT case when b<= -coalesce((select max(t1.b+t1.c+a*a-t1.c-e) from t1 where not 11>e or c<=17 and b<=b), -t1.d)+13 and 17 not between a and c and not exists(select 1 from t1 where f not between t1.d and t1.e and t1.d between 13 and -t1.a) then t1.b when e not in (a,t1.f, -t1.d) then t1.c else e end FROM t1 WHERE not coalesce((select max((c)) from t1 where d* -coalesce((select max(coalesce((select t1.d from t1 where (d<=d)),d)) from t1 where (abs(case 11 when (select -+count(distinct 13)*min(c) | count(*) from t1) then 11 else case when (19 between (19) and 17 or t1.c in (c,19,d)) then c when -t1.e>=c then c else c end end*11)/abs((13))) not in (17, -t1.e, -t1.e)),t1.e)=17),t1.c) between 13 and t1.f} +} {} +do_test randexpr-2.1840 { + db eval {SELECT case when b<= -coalesce((select max(t1.b+t1.c+a*a-t1.c-e) from t1 where not 11>e or c<=17 and b<=b), -t1.d)+13 and 17 not between a and c and not exists(select 1 from t1 where f not between t1.d and t1.e and t1.d between 13 and -t1.a) then t1.b when e not in (a,t1.f, -t1.d) then t1.c else e end FROM t1 WHERE NOT (not coalesce((select max((c)) from t1 where d* -coalesce((select max(coalesce((select t1.d from t1 where (d<=d)),d)) from t1 where (abs(case 11 when (select -+count(distinct 13)*min(c) | count(*) from t1) then 11 else case when (19 between (19) and 17 or t1.c in (c,19,d)) then c when -t1.e>=c then c else c end end*11)/abs((13))) not in (17, -t1.e, -t1.e)),t1.e)=17),t1.c) between 13 and t1.f)} +} {300} +do_test randexpr-2.1841 { + db eval {SELECT 17 | -(case when (a) not between 11 and case (abs(~(abs(13-case (abs(17)/abs(19+e | t1.e)) when (t1.d) then -(t1.c) else t1.f end+t1.f*t1.c)/abs(a)))/abs(17)) when 19 then d else t1.d end then 17 when not exists(select 1 from t1 where t1.e not in (t1.b,t1.b,b) or a between a and 17) then 11 else b end) | t1.e FROM t1 WHERE 17>=e} +} {} +do_test randexpr-2.1842 { + db eval {SELECT 17 | -(case when (a) not between 11 and case (abs(~(abs(13-case (abs(17)/abs(19+e | t1.e)) when (t1.d) then -(t1.c) else t1.f end+t1.f*t1.c)/abs(a)))/abs(17)) when 19 then d else t1.d end then 17 when not exists(select 1 from t1 where t1.e not in (t1.b,t1.b,b) or a between a and 17) then 11 else b end) | t1.e FROM t1 WHERE NOT (17>=e)} +} {-3} +do_test randexpr-2.1843 { + db eval {SELECT 17 & -(case when (a) not between 11 and case (abs(~(abs(13-case (abs(17)/abs(19+e & t1.e)) when (t1.d) then -(t1.c) else t1.f end+t1.f*t1.c)/abs(a)))/abs(17)) when 19 then d else t1.d end then 17 when not exists(select 1 from t1 where t1.e not in (t1.b,t1.b,b) or a between a and 17) then 11 else b end) & t1.e FROM t1 WHERE NOT (17>=e)} +} {16} +do_test randexpr-2.1844 { + db eval {SELECT (abs(11 | t1.e)/abs(case 13 when 17*+t1.a+d*+d then ~ -17*+ - -case f when b then a-b else t1.d end-f+t1.f+17 else t1.a end)) FROM t1 WHERE t1.f<>17} +} {5} +do_test randexpr-2.1845 { + db eval {SELECT (abs(11 | t1.e)/abs(case 13 when 17*+t1.a+d*+d then ~ -17*+ - -case f when b then a-b else t1.d end-f+t1.f+17 else t1.a end)) FROM t1 WHERE NOT (t1.f<>17)} +} {} +do_test randexpr-2.1846 { + db eval {SELECT (abs(11 & t1.e)/abs(case 13 when 17*+t1.a+d*+d then ~ -17*+ - -case f when b then a-b else t1.d end-f+t1.f+17 else t1.a end)) FROM t1 WHERE t1.f<>17} +} {0} +do_test randexpr-2.1847 { + db eval {SELECT case when not coalesce((select max(case 11 when case d when coalesce((select f from t1 where case when (t1.d) | case 11 when t1.d then 11 else (t1.a) end | t1.b in (e,c,(11)) then 17 when c between e and f then t1.e else t1.a end>t1.e),t1.d) then 13 else c end then c else c end) from t1 where t1.e not between (a) and (t1.d)),c) not in ((11),((19)),a) then (t1.c) else (c) end FROM t1 WHERE t1.d-t1.c>=13} +} {300} +do_test randexpr-2.1848 { + db eval {SELECT case when not coalesce((select max(case 11 when case d when coalesce((select f from t1 where case when (t1.d) | case 11 when t1.d then 11 else (t1.a) end | t1.b in (e,c,(11)) then 17 when c between e and f then t1.e else t1.a end>t1.e),t1.d) then 13 else c end then c else c end) from t1 where t1.e not between (a) and (t1.d)),c) not in ((11),((19)),a) then (t1.c) else (c) end FROM t1 WHERE NOT (t1.d-t1.c>=13)} +} {} +do_test randexpr-2.1849 { + db eval {SELECT case when not coalesce((select max(case 11 when case d when coalesce((select f from t1 where case when (t1.d) & case 11 when t1.d then 11 else (t1.a) end & t1.b in (e,c,(11)) then 17 when c between e and f then t1.e else t1.a end>t1.e),t1.d) then 13 else c end then c else c end) from t1 where t1.e not between (a) and (t1.d)),c) not in ((11),((19)),a) then (t1.c) else (c) end FROM t1 WHERE t1.d-t1.c>=13} +} {300} +do_test randexpr-2.1850 { + db eval {SELECT (select case count(distinct ~case when (abs(coalesce((select t1.e from t1 where (not exists(select 1 from t1 where a | e between c and coalesce((select (t1.d) from t1 where (t1.a=t1.a)), -(c))))),b+19))/abs(d))>11 then b else t1.d end) when count(distinct 17) then ~min((t1.d))-case -(case -cast(avg(t1.b) AS integer) when -max(13) then (min(t1.d)) else count(distinct t1.b) end+(min(t1.e)))*(cast(avg( -17) AS integer)) when -count(distinct 19) then count(*) else max(t1.c) end else count(distinct f) end from t1) FROM t1 WHERE t1.e=t1.d} +} {} +do_test randexpr-2.1851 { + db eval {SELECT (select case count(distinct ~case when (abs(coalesce((select t1.e from t1 where (not exists(select 1 from t1 where a | e between c and coalesce((select (t1.d) from t1 where (t1.a=t1.a)), -(c))))),b+19))/abs(d))>11 then b else t1.d end) when count(distinct 17) then ~min((t1.d))-case -(case -cast(avg(t1.b) AS integer) when -max(13) then (min(t1.d)) else count(distinct t1.b) end+(min(t1.e)))*(cast(avg( -17) AS integer)) when -count(distinct 19) then count(*) else max(t1.c) end else count(distinct f) end from t1) FROM t1 WHERE NOT (t1.e=t1.d)} +} {-701} +do_test randexpr-2.1852 { + db eval {SELECT (select case count(distinct ~case when (abs(coalesce((select t1.e from t1 where (not exists(select 1 from t1 where a & e between c and coalesce((select (t1.d) from t1 where (t1.a=t1.a)), -(c))))),b+19))/abs(d))>11 then b else t1.d end) when count(distinct 17) then ~min((t1.d))-case -(case -cast(avg(t1.b) AS integer) when -max(13) then (min(t1.d)) else count(distinct t1.b) end+(min(t1.e)))*(cast(avg( -17) AS integer)) when -count(distinct 19) then count(*) else max(t1.c) end else count(distinct f) end from t1) FROM t1 WHERE NOT (t1.e=t1.d)} +} {-701} +do_test randexpr-2.1853 { + db eval {SELECT case when t1.d<>t1.a and a-t1.b-c in (13,t1.e-(abs(d)/abs(coalesce((select max(e) from t1 where 19 not between -b and 17),b))),t1.b) or (not exists(select 1 from t1 where t1.f not between -17 and a)) then case when e>t1.e then t1.d when t1.cf-11 and not not bt1.a and a-t1.b-c in (13,t1.e-(abs(d)/abs(coalesce((select max(e) from t1 where 19 not between -b and 17),b))),t1.b) or (not exists(select 1 from t1 where t1.f not between -17 and a)) then case when e>t1.e then t1.d when t1.cf-11 and not not bcoalesce((select d from t1 where not exists(select 1 from t1 where c*b in (t1.b*t1.d,t1.c,b) or c between d and a)),19)-t1.c*e) then coalesce((select f from t1 where 11 in (select c from t1 union select b from t1)),(c)) when 17<>t1.b then d else 19 end)) from t1 where f in (a,t1.f,t1.d)),(19)) else t1.e end FROM t1 WHERE not not exists(select 1 from t1 where (select abs(min(19-19))*count(*) | min(13)*min((a))+cast(avg(t1.e) AS integer)+(cast(avg(19) AS integer)) from t1) in (17,+(select min(b) from t1),(select cast(avg(f) AS integer) from t1)) and 11 in (select ( -(min(c))) from t1 union select (min(13)) from t1)) or t1.d between c and -(f) or not t1.c in (select min(e) from t1 union select -(max(e)) from t1) and t1.e in (t1.f,a,11) and f not between a and 17 and 19<=17 and 13 not in (b,t1.b,13)} +} {} +do_test randexpr-2.1856 { + db eval {SELECT ~case 17 when t1.c then coalesce((select max((case when not exists(select 1 from t1 where 11<>coalesce((select d from t1 where not exists(select 1 from t1 where c*b in (t1.b*t1.d,t1.c,b) or c between d and a)),19)-t1.c*e) then coalesce((select f from t1 where 11 in (select c from t1 union select b from t1)),(c)) when 17<>t1.b then d else 19 end)) from t1 where f in (a,t1.f,t1.d)),(19)) else t1.e end FROM t1 WHERE NOT (not not exists(select 1 from t1 where (select abs(min(19-19))*count(*) | min(13)*min((a))+cast(avg(t1.e) AS integer)+(cast(avg(19) AS integer)) from t1) in (17,+(select min(b) from t1),(select cast(avg(f) AS integer) from t1)) and 11 in (select ( -(min(c))) from t1 union select (min(13)) from t1)) or t1.d between c and -(f) or not t1.c in (select min(e) from t1 union select -(max(e)) from t1) and t1.e in (t1.f,a,11) and f not between a and 17 and 19<=17 and 13 not in (b,t1.b,13))} +} {-501} +do_test randexpr-2.1857 { + db eval {SELECT coalesce((select +f+coalesce((select case when b- -f*t1.d-t1.a>d and t1.e in (select b from t1 union select t1.d from t1) then 11 else -a end from t1 where (not (t1.f) not between 13 and t1.f)),11) from t1 where t1.c<=c and (d) between 11 and t1.b or b in (select d from t1 union select t1.e from t1) and 19<>t1.e or 19 not between a and a),19) FROM t1 WHERE t1.e<>(select cast(avg((b)*(select abs( -max(t1.f)) from t1)) AS integer) from t1)} +} {500} +do_test randexpr-2.1858 { + db eval {SELECT coalesce((select +f+coalesce((select case when b- -f*t1.d-t1.a>d and t1.e in (select b from t1 union select t1.d from t1) then 11 else -a end from t1 where (not (t1.f) not between 13 and t1.f)),11) from t1 where t1.c<=c and (d) between 11 and t1.b or b in (select d from t1 union select t1.e from t1) and 19<>t1.e or 19 not between a and a),19) FROM t1 WHERE NOT (t1.e<>(select cast(avg((b)*(select abs( -max(t1.f)) from t1)) AS integer) from t1))} +} {} +do_test randexpr-2.1859 { + db eval {SELECT coalesce((select max(coalesce((select (t1.f) from t1 where f in (select t1.f+(select case count(distinct 19) when count(*) then max(t1.d) else -count(*) end from t1) from t1 union select 13 from t1)),c)) from t1 where not exists(select 1 from t1 where coalesce((select (select +count(*) | ~(~ -count(distinct -13)) from t1) from t1 where case when d*~f-13<>((d)) then 19 else t1.a end not between d and t1.e),t1.f) | t1.d in (select t1.d from t1 union select t1.d from t1))),13) FROM t1 WHERE b= -~case f-t1.a | ~case coalesce((select max(t1.b) from t1 where b>t1.e or t1.d=17-(abs(coalesce((select 17 from t1 where 17 between c and c),a)-c+a)/abs(t1.f))-c and d not in (17,19,c)),c) when 11 then e else t1.d end | t1.c-d when t1.c then c else e end | a} +} {} +do_test randexpr-2.1860 { + db eval {SELECT coalesce((select max(coalesce((select (t1.f) from t1 where f in (select t1.f+(select case count(distinct 19) when count(*) then max(t1.d) else -count(*) end from t1) from t1 union select 13 from t1)),c)) from t1 where not exists(select 1 from t1 where coalesce((select (select +count(*) | ~(~ -count(distinct -13)) from t1) from t1 where case when d*~f-13<>((d)) then 19 else t1.a end not between d and t1.e),t1.f) | t1.d in (select t1.d from t1 union select t1.d from t1))),13) FROM t1 WHERE NOT (b= -~case f-t1.a | ~case coalesce((select max(t1.b) from t1 where b>t1.e or t1.d=17-(abs(coalesce((select 17 from t1 where 17 between c and c),a)-c+a)/abs(t1.f))-c and d not in (17,19,c)),c) when 11 then e else t1.d end | t1.c-d when t1.c then c else e end | a)} +} {300} +do_test randexpr-2.1861 { + db eval {SELECT coalesce((select max(coalesce((select (t1.f) from t1 where f in (select t1.f+(select case count(distinct 19) when count(*) then max(t1.d) else -count(*) end from t1) from t1 union select 13 from t1)),c)) from t1 where not exists(select 1 from t1 where coalesce((select (select +count(*) & ~(~ -count(distinct -13)) from t1) from t1 where case when d*~f-13<>((d)) then 19 else t1.a end not between d and t1.e),t1.f) & t1.d in (select t1.d from t1 union select t1.d from t1))),13) FROM t1 WHERE NOT (b= -~case f-t1.a | ~case coalesce((select max(t1.b) from t1 where b>t1.e or t1.d=17-(abs(coalesce((select 17 from t1 where 17 between c and c),a)-c+a)/abs(t1.f))-c and d not in (17,19,c)),c) when 11 then e else t1.d end | t1.c-d when t1.c then c else e end | a)} +} {300} +do_test randexpr-2.1862 { + db eval {SELECT coalesce((select max(( -17-case when t1.c-13<+11 | (t1.a)-e then 13*t1.a when coalesce((select 11 from t1 where t1.a>t1.c),17)+f+t1.a not between 13 and e then t1.f else c end)) from t1 where exists(select 1 from t1 where (19>=t1.f)) and f in (select max(13) from t1 union select count(*) from t1) and (19)>=t1.f),d) FROM t1 WHERE t1.f in (select 19 from t1 union select -17*11+t1.d from t1)} +} {} +do_test randexpr-2.1863 { + db eval {SELECT coalesce((select max(( -17-case when t1.c-13<+11 | (t1.a)-e then 13*t1.a when coalesce((select 11 from t1 where t1.a>t1.c),17)+f+t1.a not between 13 and e then t1.f else c end)) from t1 where exists(select 1 from t1 where (19>=t1.f)) and f in (select max(13) from t1 union select count(*) from t1) and (19)>=t1.f),d) FROM t1 WHERE NOT (t1.f in (select 19 from t1 union select -17*11+t1.d from t1))} +} {400} +do_test randexpr-2.1864 { + db eval {SELECT coalesce((select max(( -17-case when t1.c-13<+11 & (t1.a)-e then 13*t1.a when coalesce((select 11 from t1 where t1.a>t1.c),17)+f+t1.a not between 13 and e then t1.f else c end)) from t1 where exists(select 1 from t1 where (19>=t1.f)) and f in (select max(13) from t1 union select count(*) from t1) and (19)>=t1.f),d) FROM t1 WHERE NOT (t1.f in (select 19 from t1 union select -17*11+t1.d from t1))} +} {400} +do_test randexpr-2.1865 { + db eval {SELECT (t1.a)+c*case when not b in (select 11 from t1 union select 13 from t1) and a=case when not exists(select 1 from t1 where exists(select 1 from t1 where ~+( -(17)) | t1.d>=b)) then case t1.d when c then 19 else t1.c end*a else d end-a then e when b not between f and d and t1.b>=11 or not (t1.e>=b) and 11<=17 then 13 else t1.d end FROM t1 WHERE b in (e | 19,t1.c,case 17 when 19 then +(case when 19> -coalesce((select max(a) from t1 where t1.a not in (case e when t1.d then (c)-c else 11 end | (11)-c*t1.f,e,t1.f)),13) then t1.e else t1.e end)*e else 13 end-19+ - -t1.d* -b) or -t1.e>b} +} {} +do_test randexpr-2.1866 { + db eval {SELECT (t1.a)+c*case when not b in (select 11 from t1 union select 13 from t1) and a=case when not exists(select 1 from t1 where exists(select 1 from t1 where ~+( -(17)) | t1.d>=b)) then case t1.d when c then 19 else t1.c end*a else d end-a then e when b not between f and d and t1.b>=11 or not (t1.e>=b) and 11<=17 then 13 else t1.d end FROM t1 WHERE NOT (b in (e | 19,t1.c,case 17 when 19 then +(case when 19> -coalesce((select max(a) from t1 where t1.a not in (case e when t1.d then (c)-c else 11 end | (11)-c*t1.f,e,t1.f)),13) then t1.e else t1.e end)*e else 13 end-19+ - -t1.d* -b) or -t1.e>b)} +} {4000} +do_test randexpr-2.1867 { + db eval {SELECT (t1.a)+c*case when not b in (select 11 from t1 union select 13 from t1) and a=case when not exists(select 1 from t1 where exists(select 1 from t1 where ~+( -(17)) & t1.d>=b)) then case t1.d when c then 19 else t1.c end*a else d end-a then e when b not between f and d and t1.b>=11 or not (t1.e>=b) and 11<=17 then 13 else t1.d end FROM t1 WHERE NOT (b in (e | 19,t1.c,case 17 when 19 then +(case when 19> -coalesce((select max(a) from t1 where t1.a not in (case e when t1.d then (c)-c else 11 end | (11)-c*t1.f,e,t1.f)),13) then t1.e else t1.e end)*e else 13 end-19+ - -t1.d* -b) or -t1.e>b)} +} {4000} +do_test randexpr-2.1868 { + db eval {SELECT case when b | case when 13 between ~coalesce((select 19 from t1 where b in (select max(a*17) from t1 union select cast(avg( -19) AS integer)+abs(cast(avg(a) AS integer)) from t1)),17) and 11 then a when not exists(select 1 from t1 where not exists(select 1 from t1 where 19<=e)) and d in (select 17 from t1 union select 17 from t1) then -b else a end-a in (select max(t1.c) from t1 union select min(e) | count(*)+count(*) from t1) then t1.b when not (not 19<=t1.b) then 13 else a end-b FROM t1 WHERE +~+13>=t1.c} +} {} +do_test randexpr-2.1869 { + db eval {SELECT case when b | case when 13 between ~coalesce((select 19 from t1 where b in (select max(a*17) from t1 union select cast(avg( -19) AS integer)+abs(cast(avg(a) AS integer)) from t1)),17) and 11 then a when not exists(select 1 from t1 where not exists(select 1 from t1 where 19<=e)) and d in (select 17 from t1 union select 17 from t1) then -b else a end-a in (select max(t1.c) from t1 union select min(e) | count(*)+count(*) from t1) then t1.b when not (not 19<=t1.b) then 13 else a end-b FROM t1 WHERE NOT (+~+13>=t1.c)} +} {-187} +do_test randexpr-2.1870 { + db eval {SELECT case when b & case when 13 between ~coalesce((select 19 from t1 where b in (select max(a*17) from t1 union select cast(avg( -19) AS integer)+abs(cast(avg(a) AS integer)) from t1)),17) and 11 then a when not exists(select 1 from t1 where not exists(select 1 from t1 where 19<=e)) and d in (select 17 from t1 union select 17 from t1) then -b else a end-a in (select max(t1.c) from t1 union select min(e) & count(*)+count(*) from t1) then t1.b when not (not 19<=t1.b) then 13 else a end-b FROM t1 WHERE NOT (+~+13>=t1.c)} +} {0} +do_test randexpr-2.1871 { + db eval {SELECT coalesce((select case when t1.d in (select min(f) from t1 union select ~ -count(*) from t1) then d else 13 end from t1 where 19<=case when 13>=+17-c+(select count(*)-min(11) from t1)+t1.f*t1.e*c*t1.d then c else t1.b end),t1.c | +t1.e) FROM t1 WHERE a between (abs(coalesce((select max(case when (t1.d+a*coalesce((select d-13 from t1 where a<=19),t1.f))>= -c then c else 13 end) from t1 where f>=d or t1.a>t1.d),t1.a))/abs(t1.f)) and 19 and 13=t1.e and not exists(select 1 from t1 where 13 in (select -( -count(distinct (a))) | -cast(avg(t1.c) AS integer) from t1 union select (min(t1.c)) from t1) or t1.f not between t1.c and t1.c)} +} {} +do_test randexpr-2.1872 { + db eval {SELECT coalesce((select case when t1.d in (select min(f) from t1 union select ~ -count(*) from t1) then d else 13 end from t1 where 19<=case when 13>=+17-c+(select count(*)-min(11) from t1)+t1.f*t1.e*c*t1.d then c else t1.b end),t1.c | +t1.e) FROM t1 WHERE NOT (a between (abs(coalesce((select max(case when (t1.d+a*coalesce((select d-13 from t1 where a<=19),t1.f))>= -c then c else 13 end) from t1 where f>=d or t1.a>t1.d),t1.a))/abs(t1.f)) and 19 and 13=t1.e and not exists(select 1 from t1 where 13 in (select -( -count(distinct (a))) | -cast(avg(t1.c) AS integer) from t1 union select (min(t1.c)) from t1) or t1.f not between t1.c and t1.c))} +} {13} +do_test randexpr-2.1873 { + db eval {SELECT coalesce((select case when t1.d in (select min(f) from t1 union select ~ -count(*) from t1) then d else 13 end from t1 where 19<=case when 13>=+17-c+(select count(*)-min(11) from t1)+t1.f*t1.e*c*t1.d then c else t1.b end),t1.c & +t1.e) FROM t1 WHERE NOT (a between (abs(coalesce((select max(case when (t1.d+a*coalesce((select d-13 from t1 where a<=19),t1.f))>= -c then c else 13 end) from t1 where f>=d or t1.a>t1.d),t1.a))/abs(t1.f)) and 19 and 13=t1.e and not exists(select 1 from t1 where 13 in (select -( -count(distinct (a))) | -cast(avg(t1.c) AS integer) from t1 union select (min(t1.c)) from t1) or t1.f not between t1.c and t1.c))} +} {13} +do_test randexpr-2.1874 { + db eval {SELECT coalesce((select max(f) from t1 where coalesce((select max(+(select cast(avg(t1.d) AS integer) from t1)*19) from t1 where (abs(t1.d*t1.c)/abs(f))+t1.e> -t1.d*t1.e-a),13-case +coalesce((select max(t1.c) from t1 where d<=d and - -t1.a<=(t1.f) or f<>19 and 17<19),(t1.c)) | c*t1.f*b when t1.a then 19 else (b) end)>=a),t1.f) FROM t1 WHERE (~c-13*case when case when a+19-c in (select case count(distinct c)-case cast(avg(t1.a) AS integer) when max( -b) then cast(avg(t1.f) AS integer) else cast(avg((t1.d)) AS integer) end when min(b) then cast(avg(b) AS integer) else count(*) end from t1 union select max(t1.f) from t1) and 17 between (t1.b) and c and 19>t1.d or 19 in (t1.f,t1.a,(b)) then a else t1.e end in (13,t1.a,b) then 17 else t1.e end*t1.d+a+t1.b+t1.f) -t1.d*t1.e-a),13-case +coalesce((select max(t1.c) from t1 where d<=d and - -t1.a<=(t1.f) or f<>19 and 17<19),(t1.c)) | c*t1.f*b when t1.a then 19 else (b) end)>=a),t1.f) FROM t1 WHERE NOT ((~c-13*case when case when a+19-c in (select case count(distinct c)-case cast(avg(t1.a) AS integer) when max( -b) then cast(avg(t1.f) AS integer) else cast(avg((t1.d)) AS integer) end when min(b) then cast(avg(b) AS integer) else count(*) end from t1 union select max(t1.f) from t1) and 17 between (t1.b) and c and 19>t1.d or 19 in (t1.f,t1.a,(b)) then a else t1.e end in (13,t1.a,b) then 17 else t1.e end*t1.d+a+t1.b+t1.f) -t1.d*t1.e-a),13-case +coalesce((select max(t1.c) from t1 where d<=d and - -t1.a<=(t1.f) or f<>19 and 17<19),(t1.c)) & c*t1.f*b when t1.a then 19 else (b) end)>=a),t1.f) FROM t1 WHERE (~c-13*case when case when a+19-c in (select case count(distinct c)-case cast(avg(t1.a) AS integer) when max( -b) then cast(avg(t1.f) AS integer) else cast(avg((t1.d)) AS integer) end when min(b) then cast(avg(b) AS integer) else count(*) end from t1 union select max(t1.f) from t1) and 17 between (t1.b) and c and 19>t1.d or 19 in (t1.f,t1.a,(b)) then a else t1.e end in (13,t1.a,b) then 17 else t1.e end*t1.d+a+t1.b+t1.f) -b then a else f end then t1.e else f end FROM t1 WHERE t1.f-~coalesce((select 17 from t1 where (e+ -case when (d -b then a else f end then t1.e else f end FROM t1 WHERE NOT (t1.f-~coalesce((select 17 from t1 where (e+ -case when (d -b then a else f end then t1.e else f end FROM t1 WHERE t1.f-~coalesce((select 17 from t1 where (e+ -case when (d19) then case when f in (11,11,d) then t1.e when t1.a<=19 then a else e end else -t1.e end from t1) then e when t1.c=t1.b then 19 else e end when f then 19 else c end) | d-c and a} +} {} +do_test randexpr-2.1881 { + db eval {SELECT -(17-case (select max(a)+min( -(abs(t1.c-t1.a | t1.e- -t1.b+19*t1.c)/abs(c)))+ -case min(a) when count(distinct -a) then count(distinct 19) else count(*) end-count(distinct t1.e)*(max(t1.a))-(count(distinct 19)) from t1) when (select count(*) from t1) then b else t1.d end*11)-11* -c FROM t1 WHERE NOT (f between (case case when +(f) in (select t1.f from t1 union select case when t1.b in ((abs(19)/abs(11)),f,c) and (d) in (select -count(distinct b)*count(*) from t1 union select count(distinct -13) from t1) or (t1.e>19) then case when f in (11,11,d) then t1.e when t1.a<=19 then a else e end else -t1.e end from t1) then e when t1.c=t1.b then 19 else e end when f then 19 else c end) | d-c and a)} +} {7683} +do_test randexpr-2.1882 { + db eval {SELECT -(17-case (select max(a)+min( -(abs(t1.c-t1.a & t1.e- -t1.b+19*t1.c)/abs(c)))+ -case min(a) when count(distinct -a) then count(distinct 19) else count(*) end-count(distinct t1.e)*(max(t1.a))-(count(distinct 19)) from t1) when (select count(*) from t1) then b else t1.d end*11)-11* -c FROM t1 WHERE NOT (f between (case case when +(f) in (select t1.f from t1 union select case when t1.b in ((abs(19)/abs(11)),f,c) and (d) in (select -count(distinct b)*count(*) from t1 union select count(distinct -13) from t1) or (t1.e>19) then case when f in (11,11,d) then t1.e when t1.a<=19 then a else e end else -t1.e end from t1) then e when t1.c=t1.b then 19 else e end when f then 19 else c end) | d-c and a)} +} {7683} +do_test randexpr-2.1883 { + db eval {SELECT (case coalesce((select +a from t1 where exists(select 1 from t1 where t1.e not between t1.f-b and (select count(*) from t1)-t1.f | e)),t1.d+case when t1.b not between t1.d and 17+case when a in (t1.d,a,(abs(~case when (t1.f)<=t1.c then -17 else t1.f end)/abs(19))*d*t1.d) then (b) else a end then 11 else f end+(t1.a)) when f then 17 else t1.e end) FROM t1 WHERE a-e*case t1.d+case c when (abs(~t1.d*(select min(case when not exists(select 1 from t1 where ((d)+(19) between 11 and 19)) then 11+13 when e not in (t1.f,17,e) and t1.c<>a then t1.e else 19 end*t1.a-f) from t1))/abs(b)) then 13 else 17 end when t1.f then (f) else t1.c enda then t1.e else 19 end*t1.a-f) from t1))/abs(b)) then 13 else 17 end when t1.f then (f) else t1.c enda then t1.e else 19 end*t1.a-f) from t1))/abs(b)) then 13 else 17 end when t1.f then (f) else t1.c end(13) | -11 and c>f),19)+t1.c) AS integer)-(~case cast(avg(t1.f) AS integer)*abs(max(b)+(count(*))+count(distinct b)) when min(c) then cast(avg(t1.b) AS integer) else count(*) end) from t1) in (select t1.e from t1 union select t1.c from t1) then f when d=(c)),b)) when max(d) then ( -max(c))+((min(11)))+max(t1.c) else max(t1.a) end from t1)-e+t1.b-(b)-11-t1.d*t1.c<>t1.c)} +} {} +do_test randexpr-2.1890 { + db eval {SELECT (abs(b)/abs((select max(c) from t1)))+case when (select +cast(avg(17 | ~coalesce((select e from t1 where t1.b>(13) | -11 and c>f),19)+t1.c) AS integer)-(~case cast(avg(t1.f) AS integer)*abs(max(b)+(count(*))+count(distinct b)) when min(c) then cast(avg(t1.b) AS integer) else count(*) end) from t1) in (select t1.e from t1 union select t1.c from t1) then f when d=(c)),b)) when max(d) then ( -max(c))+((min(11)))+max(t1.c) else max(t1.a) end from t1)-e+t1.b-(b)-11-t1.d*t1.c<>t1.c))} +} {500} +do_test randexpr-2.1891 { + db eval {SELECT (abs(b)/abs((select max(c) from t1)))+case when (select +cast(avg(17 & ~coalesce((select e from t1 where t1.b>(13) & -11 and c>f),19)+t1.c) AS integer)-(~case cast(avg(t1.f) AS integer)*abs(max(b)+(count(*))+count(distinct b)) when min(c) then cast(avg(t1.b) AS integer) else count(*) end) from t1) in (select t1.e from t1 union select t1.c from t1) then f when d=(c)),b)) when max(d) then ( -max(c))+((min(11)))+max(t1.c) else max(t1.a) end from t1)-e+t1.b-(b)-11-t1.d*t1.c<>t1.c))} +} {500} +do_test randexpr-2.1892 { + db eval {SELECT coalesce((select max(case 13 when +coalesce((select max(c) from t1 where t1.a+f in (t1.b,t1.b,(abs(19)/abs(+17+~(abs(t1.a+f)/abs(~t1.c))+case when not exists(select 1 from t1 where coalesce((select max(e) from t1 where (b)> -t1.a),c)=t1.b) then 19 else b end))-f)),t1.a)+a then f else 17 end*t1.e) from t1 where 13<>t1.f),t1.f) FROM t1 WHERE not exists(select 1 from t1 where coalesce((select max(case when 13 not in (t1.b,b,t1.c) then t1.c | t1.a else 13-19+a+t1.e-t1.e end+t1.a*17+( -d)-17 | t1.c-t1.a | 19+b) from t1 where not a=e),11) in (select 17 from t1 union select c from t1) or t1.c>=t1.e)} +} {8500} +do_test randexpr-2.1893 { + db eval {SELECT coalesce((select max(case 13 when +coalesce((select max(c) from t1 where t1.a+f in (t1.b,t1.b,(abs(19)/abs(+17+~(abs(t1.a+f)/abs(~t1.c))+case when not exists(select 1 from t1 where coalesce((select max(e) from t1 where (b)> -t1.a),c)=t1.b) then 19 else b end))-f)),t1.a)+a then f else 17 end*t1.e) from t1 where 13<>t1.f),t1.f) FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select max(case when 13 not in (t1.b,b,t1.c) then t1.c | t1.a else 13-19+a+t1.e-t1.e end+t1.a*17+( -d)-17 | t1.c-t1.a | 19+b) from t1 where not a=e),11) in (select 17 from t1 union select c from t1) or t1.c>=t1.e))} +} {} +do_test randexpr-2.1894 { + db eval {SELECT t1.f++c*coalesce((select +t1.f from t1 where a<~13),case when exists(select 1 from t1 where not exists(select 1 from t1 where 17 in (select 11 from t1 union select (17) from t1))) then b else + -19 | coalesce((select case when (select cast(avg(a) AS integer) from t1)>e then case when (11=(e) and 17=t1.a then -c else 19 end-f) from t1 where not exists(select 1 from t1 where d in (select -~count(distinct 11)+max(t1.a) from t1 union select count(distinct e)* -count(distinct t1.b) from t1)) or (ce then case when (11=(e) and 17=t1.a then -c else 19 end-f) from t1 where not exists(select 1 from t1 where d in (select -~count(distinct 11)+max(t1.a) from t1 union select count(distinct e)* -count(distinct t1.b) from t1)) or (ce then case when (11=(e) and 17=t1.a then -c else 19 end-f) from t1 where not exists(select 1 from t1 where d in (select -~count(distinct 11)+max(t1.a) from t1 union select count(distinct e)* -count(distinct t1.b) from t1)) or (c=t1.c then f else t1.f end-f) from t1) FROM t1 WHERE (~ -t1.c in (select d from t1 union select t1.c*case when (17 in (+case c when t1.f then t1.c else c+e+t1.c*e+coalesce((select max((c)) from t1 where (t1.e)>a),19)-t1.e end | e-t1.b,t1.d,c)) then d when t1.e in (select (max( -e)-~~count(*)) from t1 union select count(*) from t1) then d else t1.f end from t1))} +} {} +do_test randexpr-2.1898 { + db eval {SELECT (select + -min(case when case when exists(select 1 from t1 where a<=c or coalesce((select max(11) from t1 where d=17),19)*11<=f and t1.e in (select t1.c from t1 union select a from t1)) then (f)-d when a=t1.c then f else t1.f end-f) from t1) FROM t1 WHERE NOT ((~ -t1.c in (select d from t1 union select t1.c*case when (17 in (+case c when t1.f then t1.c else c+e+t1.c*e+coalesce((select max((c)) from t1 where (t1.e)>a),19)-t1.e end | e-t1.b,t1.d,c)) then d when t1.e in (select (max( -e)-~~count(*)) from t1 union select count(*) from t1) then d else t1.f end from t1)))} +} {0} +do_test randexpr-2.1899 { + db eval {SELECT ~+t1.f-coalesce((select t1.f from t1 where case when t1.d>=t1.f then b else case c when 11 then t1.f*case when (select (count(*)) from t1)<>a+t1.b | +11-coalesce((select max(t1.f-a) from t1 where (f<=t1.c and t1.d=c)),d)-11 then b when (t1.c)<=t1.b then 19 else 11 end else c end end*19-13< - -b),e) FROM t1 WHERE (exists(select 1 from t1 where -t1.f not between ~17 and t1.a+(b+d+13)))} +} {-1101} +do_test randexpr-2.1900 { + db eval {SELECT ~+t1.f-coalesce((select t1.f from t1 where case when t1.d>=t1.f then b else case c when 11 then t1.f*case when (select (count(*)) from t1)<>a+t1.b | +11-coalesce((select max(t1.f-a) from t1 where (f<=t1.c and t1.d=c)),d)-11 then b when (t1.c)<=t1.b then 19 else 11 end else c end end*19-13< - -b),e) FROM t1 WHERE NOT ((exists(select 1 from t1 where -t1.f not between ~17 and t1.a+(b+d+13))))} +} {} +do_test randexpr-2.1901 { + db eval {SELECT ~+t1.f-coalesce((select t1.f from t1 where case when t1.d>=t1.f then b else case c when 11 then t1.f*case when (select (count(*)) from t1)<>a+t1.b & +11-coalesce((select max(t1.f-a) from t1 where (f<=t1.c and t1.d=c)),d)-11 then b when (t1.c)<=t1.b then 19 else 11 end else c end end*19-13< - -b),e) FROM t1 WHERE (exists(select 1 from t1 where -t1.f not between ~17 and t1.a+(b+d+13)))} +} {-1101} +do_test randexpr-2.1902 { + db eval {SELECT -t1.e+coalesce((select (d) from t1 where t1.f=t1.f*(select +count(distinct case when (coalesce((select max(case when a in (select b+17 from t1 union select -17 from t1) then 19 when 17a),e)<>f or d not between (e) and b) then 11 else (abs(13)/abs( -(d))) end*t1.c) from t1)),e-f) FROM t1 WHERE ((case when t1.e+d*~coalesce((select coalesce((select max(b) from t1 where ~case when t1.f not between t1.c and coalesce((select t1.b from t1 where -t1.e in (select (( - -min(19))) from t1 union select count(distinct t1.d) from t1)),t1.d) then c when t1.f=e then t1.f else b end=13),13) from t1 where t1.e not between 13 and 11 or not exists(select 1 from t1 where t1.a not between (11) and d and 11>=a)),t1.f) in (select count(*) from t1 union select ~max( -13) from t1) then -13 else 17 end) | d in (a,d,13))} +} {} +do_test randexpr-2.1903 { + db eval {SELECT -t1.e+coalesce((select (d) from t1 where t1.f=t1.f*(select +count(distinct case when (coalesce((select max(case when a in (select b+17 from t1 union select -17 from t1) then 19 when 17a),e)<>f or d not between (e) and b) then 11 else (abs(13)/abs( -(d))) end*t1.c) from t1)),e-f) FROM t1 WHERE NOT (((case when t1.e+d*~coalesce((select coalesce((select max(b) from t1 where ~case when t1.f not between t1.c and coalesce((select t1.b from t1 where -t1.e in (select (( - -min(19))) from t1 union select count(distinct t1.d) from t1)),t1.d) then c when t1.f=e then t1.f else b end=13),13) from t1 where t1.e not between 13 and 11 or not exists(select 1 from t1 where t1.a not between (11) and d and 11>=a)),t1.f) in (select count(*) from t1 union select ~max( -13) from t1) then -13 else 17 end) | d in (a,d,13)))} +} {-100} +do_test randexpr-2.1904 { + db eval {SELECT -t1.e+coalesce((select (d) from t1 where t1.f=t1.f*(select +count(distinct case when (coalesce((select max(case when a in (select b+17 from t1 union select -17 from t1) then 19 when 17a),e)<>f or d not between (e) and b) then 11 else (abs(13)/abs( -(d))) end*t1.c) from t1)),e-f) FROM t1 WHERE NOT (((case when t1.e+d*~coalesce((select coalesce((select max(b) from t1 where ~case when t1.f not between t1.c and coalesce((select t1.b from t1 where -t1.e in (select (( - -min(19))) from t1 union select count(distinct t1.d) from t1)),t1.d) then c when t1.f=e then t1.f else b end=13),13) from t1 where t1.e not between 13 and 11 or not exists(select 1 from t1 where t1.a not between (11) and d and 11>=a)),t1.f) in (select count(*) from t1 union select ~max( -13) from t1) then -13 else 17 end) | d in (a,d,13)))} +} {-100} +do_test randexpr-2.1905 { + db eval {SELECT coalesce((select max((19)) from t1 where d* -a<=(select count(*) from t1)+19*19*a-e-d or b in (t1.c+ -t1.b,t1.a,b+t1.b)),d) FROM t1 WHERE exists(select 1 from t1 where exists(select 1 from t1 where not t1.e>e))} +} {19} +do_test randexpr-2.1906 { + db eval {SELECT coalesce((select max((19)) from t1 where d* -a<=(select count(*) from t1)+19*19*a-e-d or b in (t1.c+ -t1.b,t1.a,b+t1.b)),d) FROM t1 WHERE NOT (exists(select 1 from t1 where exists(select 1 from t1 where not t1.e>e)))} +} {} +do_test randexpr-2.1907 { + db eval {SELECT (select -~count(distinct (abs(11)/abs(f-17-+(select cast(avg(+(select count(*) from t1)) AS integer) from t1)))) from t1) FROM t1 WHERE (abs((a))/abs(t1.b))>(select count(distinct case case when 17 in (select -b-case when 17 in (select +(( - -max(t1.b))) from t1 union select max((t1.b)) from t1) then f when t1.e=(t1.d) then 17 else e end | e-t1.d | t1.c* -13*d*t1.b from t1 union select 11 from t1) then c when c>=a then 13 else 13 end+t1.b when -f then 19 else 13 end)*min(t1.f) from t1)-19-f} +} {2} +do_test randexpr-2.1908 { + db eval {SELECT (select -~count(distinct (abs(11)/abs(f-17-+(select cast(avg(+(select count(*) from t1)) AS integer) from t1)))) from t1) FROM t1 WHERE NOT ((abs((a))/abs(t1.b))>(select count(distinct case case when 17 in (select -b-case when 17 in (select +(( - -max(t1.b))) from t1 union select max((t1.b)) from t1) then f when t1.e=(t1.d) then 17 else e end | e-t1.d | t1.c* -13*d*t1.b from t1 union select 11 from t1) then c when c>=a then 13 else 13 end+t1.b when -f then 19 else 13 end)*min(t1.f) from t1)-19-f)} +} {} +do_test randexpr-2.1909 { + db eval {SELECT -(select cast(avg(coalesce((select max(f) from t1 where -case coalesce((select max(~c-case when exists(select 1 from t1 where -b in (~e,t1.e,t1.e)) then t1.e when (17 in (select ++ -(count(distinct t1.a)) from t1 union select (max( -f)) from t1)) then b else t1.f end) from t1 where (13 in (19,b,11))),t1.e) when c then (b) else 11 end-a*b*13=t1.e),13)) AS integer) from t1) FROM t1 WHERE exists(select 1 from t1 where case when not (case when ~17*d>=b then a when c*(abs((abs(f)/abs(t1.c)))/abs(t1.b))+d*t1.b<19 and not case 13 when a then 11 else -t1.e end<>f then 11 else c end+t1.d) not in (t1.c,t1.f,d) then (abs(c)/abs(t1.f)) else t1.a end*t1.f not between t1.d and c)} +} {-13} +do_test randexpr-2.1910 { + db eval {SELECT -(select cast(avg(coalesce((select max(f) from t1 where -case coalesce((select max(~c-case when exists(select 1 from t1 where -b in (~e,t1.e,t1.e)) then t1.e when (17 in (select ++ -(count(distinct t1.a)) from t1 union select (max( -f)) from t1)) then b else t1.f end) from t1 where (13 in (19,b,11))),t1.e) when c then (b) else 11 end-a*b*13=t1.e),13)) AS integer) from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where case when not (case when ~17*d>=b then a when c*(abs((abs(f)/abs(t1.c)))/abs(t1.b))+d*t1.b<19 and not case 13 when a then 11 else -t1.e end<>f then 11 else c end+t1.d) not in (t1.c,t1.f,d) then (abs(c)/abs(t1.f)) else t1.a end*t1.f not between t1.d and c))} +} {} +do_test randexpr-2.1911 { + db eval {SELECT case t1.c when (select abs( -max(t1.a*t1.f*t1.a*e)) from t1)*case when not exists(select 1 from t1 where (select cast(avg(c) AS integer) from t1) in (select case case when ( -case t1.f when 17 then t1.c else e end=17) then 19 else e end when e then c else -a end*t1.d from t1 union select d from t1)) then e*t1.a else b end+e*t1.d+t1.b then t1.d else c end+t1.e FROM t1 WHERE 13 in (select +abs(case count(distinct t1.e+(abs((abs(coalesce((select t1.b from t1 where coalesce((select max(case when (19<=t1.d) then (13) when a>=13 then 13 else t1.f end) from t1 where a in (t1.c,19,t1.b)),19)>13),d))/abs(f))+t1.a*t1.b)/abs(e))) when +cast(avg(c) AS integer) then ~~+max(f) | cast(avg(t1.c) AS integer) else count(distinct 13)+min(t1.b) | count(*) end)*max(t1.d)-count(*) from t1 union select count(*) from t1)} +} {} +do_test randexpr-2.1912 { + db eval {SELECT case t1.c when (select abs( -max(t1.a*t1.f*t1.a*e)) from t1)*case when not exists(select 1 from t1 where (select cast(avg(c) AS integer) from t1) in (select case case when ( -case t1.f when 17 then t1.c else e end=17) then 19 else e end when e then c else -a end*t1.d from t1 union select d from t1)) then e*t1.a else b end+e*t1.d+t1.b then t1.d else c end+t1.e FROM t1 WHERE NOT (13 in (select +abs(case count(distinct t1.e+(abs((abs(coalesce((select t1.b from t1 where coalesce((select max(case when (19<=t1.d) then (13) when a>=13 then 13 else t1.f end) from t1 where a in (t1.c,19,t1.b)),19)>13),d))/abs(f))+t1.a*t1.b)/abs(e))) when +cast(avg(c) AS integer) then ~~+max(f) | cast(avg(t1.c) AS integer) else count(distinct 13)+min(t1.b) | count(*) end)*max(t1.d)-count(*) from t1 union select count(*) from t1))} +} {800} +do_test randexpr-2.1913 { + db eval {SELECT case when f in (d, -case when (case 11 when (select max(t1.d) from t1) then (abs(a)/abs(+t1.b)) else ~b end<19) then (abs( -(abs(17)/abs(t1.f)))/abs((select count(*) from t1))) when (f) not between coalesce((select 13 from t1 where t1.a<=case t1.a when 13 then -t1.c else 13 end and 13 not between t1.f and 11),11) and 19 then e else b end,t1.d) then b else t1.b end FROM t1 WHERE t1.f between f and a-c-t1.d-t1.d+t1.d*case when exists(select 1 from t1 where d between (select ~cast(avg(17) AS integer) from t1) and a) then case when case b when f then 13 else b end19),t1.b)) or ((t1.a>19)) or e<>19 then -t1.e else -13 end-b+t1.d else a end then 19 when d between b and t1.c then t1.e else e end)/abs(t1.a)) FROM t1 WHERE b | t1.b>b-case when a-f in (select 17 from t1 union select coalesce((select coalesce((select t1.e+t1.a+d+d from t1 where 13 not between t1.e+19 and 13),(select count(distinct t1.e) from t1)*11) from t1 where b not in (b,(t1.f),t1.a)),13) from t1) then b else c end+a-13-13*(13) | 11} +} {0} +do_test randexpr-2.1916 { + db eval {SELECT (abs(case when 11<=case 17 when t1.d then t1.b+~19-~case when not t1.b not in (t1.a,b,coalesce((select a+(a) from t1 where t1.b>19),t1.b)) or ((t1.a>19)) or e<>19 then -t1.e else -13 end-b+t1.d else a end then 19 when d between b and t1.c then t1.e else e end)/abs(t1.a)) FROM t1 WHERE NOT (b | t1.b>b-case when a-f in (select 17 from t1 union select coalesce((select coalesce((select t1.e+t1.a+d+d from t1 where 13 not between t1.e+19 and 13),(select count(distinct t1.e) from t1)*11) from t1 where b not in (b,(t1.f),t1.a)),13) from t1) then b else c end+a-13-13*(13) | 11)} +} {} +do_test randexpr-2.1917 { + db eval {SELECT -t1.a | coalesce((select t1.f*(select min(f)+min(( -(select -case (min(13)) when -abs(min(t1.b)) then count(distinct a) else count(*) end from t1)*(select - -count(*) from t1)))* -count(*) from t1) from t1 where t1.d in (select case case when t1.a<(f) then c else 19 end when f then b else -c end*a*t1.c from t1 union select t1.b from t1)),b) | a FROM t1 WHERE +19*case when exists(select 1 from t1 where e<+13 | f or t1.d=19) then t1.a when case when exists(select 1 from t1 where t1.c in (select 11 from t1 union select c from t1)) then 13*t1.e else 19 end<=c and (t1.e between (b) and 13) or 11 not between t1.f and 13 or 17 between b and 13 then t1.e+a else 17 end not between b and d or t1.e not between 13 and 17} +} {-4} +do_test randexpr-2.1918 { + db eval {SELECT -t1.a | coalesce((select t1.f*(select min(f)+min(( -(select -case (min(13)) when -abs(min(t1.b)) then count(distinct a) else count(*) end from t1)*(select - -count(*) from t1)))* -count(*) from t1) from t1 where t1.d in (select case case when t1.a<(f) then c else 19 end when f then b else -c end*a*t1.c from t1 union select t1.b from t1)),b) | a FROM t1 WHERE NOT (+19*case when exists(select 1 from t1 where e<+13 | f or t1.d=19) then t1.a when case when exists(select 1 from t1 where t1.c in (select 11 from t1 union select c from t1)) then 13*t1.e else 19 end<=c and (t1.e between (b) and 13) or 11 not between t1.f and 13 or 17 between b and 13 then t1.e+a else 17 end not between b and d or t1.e not between 13 and 17)} +} {} +do_test randexpr-2.1919 { + db eval {SELECT -t1.a & coalesce((select t1.f*(select min(f)+min(( -(select -case (min(13)) when -abs(min(t1.b)) then count(distinct a) else count(*) end from t1)*(select - -count(*) from t1)))* -count(*) from t1) from t1 where t1.d in (select case case when t1.a<(f) then c else 19 end when f then b else -c end*a*t1.c from t1 union select t1.b from t1)),b) & a FROM t1 WHERE +19*case when exists(select 1 from t1 where e<+13 | f or t1.d=19) then t1.a when case when exists(select 1 from t1 where t1.c in (select 11 from t1 union select c from t1)) then 13*t1.e else 19 end<=c and (t1.e between (b) and 13) or 11 not between t1.f and 13 or 17 between b and 13 then t1.e+a else 17 end not between b and d or t1.e not between 13 and 17} +} {0} +do_test randexpr-2.1920 { + db eval {SELECT (select -case +count(distinct case when -+ -~case when ((t1.e)) not between e and f then e when t1.b between -11 and t1.b then d else t1.a end*19 in (select t1.f from t1 union select t1.d from t1) then t1.b when a in (select -19 from t1 union select c from t1) then a else f end) when +~ -(count(*)) then -( -count(distinct t1.e))-count(distinct c) else max(t1.c) end-count(distinct t1.c)-count(distinct 19)-(max(11)) from t1) FROM t1 WHERE -~coalesce((select max(19*t1.b) from t1 where t1.d in (select max( -coalesce((select max(t1.c) from t1 where case 13 when f+ -13+t1.b-case 13 when t1.a | (abs(t1.a)/abs(t1.f)) then 11 else f end then f else 17 end in (b,t1.d,(e))),13)) from t1 union select ~~min(b)*abs(cast(avg(b) AS integer)) from t1)),e)*((t1.d))<>t1.d} +} {-313} +do_test randexpr-2.1921 { + db eval {SELECT (select -case +count(distinct case when -+ -~case when ((t1.e)) not between e and f then e when t1.b between -11 and t1.b then d else t1.a end*19 in (select t1.f from t1 union select t1.d from t1) then t1.b when a in (select -19 from t1 union select c from t1) then a else f end) when +~ -(count(*)) then -( -count(distinct t1.e))-count(distinct c) else max(t1.c) end-count(distinct t1.c)-count(distinct 19)-(max(11)) from t1) FROM t1 WHERE NOT ( -~coalesce((select max(19*t1.b) from t1 where t1.d in (select max( -coalesce((select max(t1.c) from t1 where case 13 when f+ -13+t1.b-case 13 when t1.a | (abs(t1.a)/abs(t1.f)) then 11 else f end then f else 17 end in (b,t1.d,(e))),13)) from t1 union select ~~min(b)*abs(cast(avg(b) AS integer)) from t1)),e)*((t1.d))<>t1.d)} +} {} +do_test randexpr-2.1922 { + db eval {SELECT case a when c then (abs((select abs(~(+~~case max(t1.d) when +count(distinct ~d | (select case max(17) when count(*) then count(distinct (t1.c)) else count(distinct 11) end from t1)) then (+cast(avg((17)) AS integer))+count(*) else -(( - -(cast(avg(c) AS integer)))) end)+count(distinct t1.e)+min(13)) from t1)*+11-((abs(t1.a)/abs(coalesce((select c from t1 where ((t1.f<>d))),(t1.c))))) | t1.d)/abs( -(d))) else a end FROM t1 WHERE coalesce((select max(case t1.a when +t1.e then case when t1.c+(select (max(t1.d))-max(13)+cast(avg(c) AS integer)+min((e)) | max(a) from t1)<= -t1.a | case when not exists(select 1 from t1 where -t1.d<=t1.a) then t1.f when 11=c then a else 13 end | t1.c else t1.a end) from t1 where 19<=e and t1.e between t1.d and 11),13) not in (e,a,c)} +} {100} +do_test randexpr-2.1923 { + db eval {SELECT case a when c then (abs((select abs(~(+~~case max(t1.d) when +count(distinct ~d | (select case max(17) when count(*) then count(distinct (t1.c)) else count(distinct 11) end from t1)) then (+cast(avg((17)) AS integer))+count(*) else -(( - -(cast(avg(c) AS integer)))) end)+count(distinct t1.e)+min(13)) from t1)*+11-((abs(t1.a)/abs(coalesce((select c from t1 where ((t1.f<>d))),(t1.c))))) | t1.d)/abs( -(d))) else a end FROM t1 WHERE NOT (coalesce((select max(case t1.a when +t1.e then case when t1.c+(select (max(t1.d))-max(13)+cast(avg(c) AS integer)+min((e)) | max(a) from t1)<= -t1.a | case when not exists(select 1 from t1 where -t1.d<=t1.a) then t1.f when 11=c then a else 13 end | t1.c else t1.a end) from t1 where 19<=e and t1.e between t1.d and 11),13) not in (e,a,c))} +} {} +do_test randexpr-2.1924 { + db eval {SELECT case a when c then (abs((select abs(~(+~~case max(t1.d) when +count(distinct ~d & (select case max(17) when count(*) then count(distinct (t1.c)) else count(distinct 11) end from t1)) then (+cast(avg((17)) AS integer))+count(*) else -(( - -(cast(avg(c) AS integer)))) end)+count(distinct t1.e)+min(13)) from t1)*+11-((abs(t1.a)/abs(coalesce((select c from t1 where ((t1.f<>d))),(t1.c))))) & t1.d)/abs( -(d))) else a end FROM t1 WHERE coalesce((select max(case t1.a when +t1.e then case when t1.c+(select (max(t1.d))-max(13)+cast(avg(c) AS integer)+min((e)) | max(a) from t1)<= -t1.a | case when not exists(select 1 from t1 where -t1.d<=t1.a) then t1.f when 11=c then a else 13 end | t1.c else t1.a end) from t1 where 19<=e and t1.e between t1.d and 11),13) not in (e,a,c)} +} {100} +do_test randexpr-2.1925 { + db eval {SELECT t1.d-+case ~(select ~+~count(distinct case when case when case when 11 not between t1.c and t1.a-e then t1.d else e end*d-(d) between -13 and e then a else c end in (select b from t1 union select 17 from t1) then a else 13 end)*cast(avg(d) AS integer) from t1) when t1.e then (abs(11)/abs(coalesce((select max(19) from t1 where (a)<>t1.e),19))) else t1.c end+t1.c FROM t1 WHERE 19 not in (t1.a*+case when -c+~t1.a-t1.c in (t1.a,b*case t1.a | coalesce((select max(coalesce((select 17 from t1 where t1.e>t1.a),t1.d)) from t1 where not 11=19),17) when 11 then t1.d else (f) end*b-t1.a+c, -b) then d when a<>f then a else b end-c,d,t1.b)} +} {400} +do_test randexpr-2.1926 { + db eval {SELECT t1.d-+case ~(select ~+~count(distinct case when case when case when 11 not between t1.c and t1.a-e then t1.d else e end*d-(d) between -13 and e then a else c end in (select b from t1 union select 17 from t1) then a else 13 end)*cast(avg(d) AS integer) from t1) when t1.e then (abs(11)/abs(coalesce((select max(19) from t1 where (a)<>t1.e),19))) else t1.c end+t1.c FROM t1 WHERE NOT (19 not in (t1.a*+case when -c+~t1.a-t1.c in (t1.a,b*case t1.a | coalesce((select max(coalesce((select 17 from t1 where t1.e>t1.a),t1.d)) from t1 where not 11=19),17) when 11 then t1.d else (f) end*b-t1.a+c, -b) then d when a<>f then a else b end-c,d,t1.b))} +} {} +do_test randexpr-2.1927 { + db eval {SELECT case when case (select +min(~ -11+f*~b) | case abs(cast(avg(t1.f) AS integer))*~min(c) when count(*)+max( -11) then abs(count(*)) else max(13) end from t1) when coalesce((select max(coalesce((select max(19) from t1 where (17>=17)),t1.f)) from t1 where ct1.a then -d else -t1.b end FROM t1 WHERE t1.a+b-t1.c*17>=c} +} {} +do_test randexpr-2.1928 { + db eval {SELECT case when case (select +min(~ -11+f*~b) | case abs(cast(avg(t1.f) AS integer))*~min(c) when count(*)+max( -11) then abs(count(*)) else max(13) end from t1) when coalesce((select max(coalesce((select max(19) from t1 where (17>=17)),t1.f)) from t1 where ct1.a then -d else -t1.b end FROM t1 WHERE NOT (t1.a+b-t1.c*17>=c)} +} {-400} +do_test randexpr-2.1929 { + db eval {SELECT case when case (select +min(~ -11+f*~b) & case abs(cast(avg(t1.f) AS integer))*~min(c) when count(*)+max( -11) then abs(count(*)) else max(13) end from t1) when coalesce((select max(coalesce((select max(19) from t1 where (17>=17)),t1.f)) from t1 where ct1.a then -d else -t1.b end FROM t1 WHERE NOT (t1.a+b-t1.c*17>=c)} +} {-400} +do_test randexpr-2.1930 { + db eval {SELECT case when ~case when t1.f>11*t1.a then f when case when (t1.c*19<(t1.f)) then (e) when at1.e and a in (d,t1.c,13) then t1.b when -17 not between f and d then f else t1.c end FROM t1 WHERE c in (select + -min(case (select count(*) from t1) when t1.a then t1.c else coalesce((select max(b) from t1 where d in (select -abs(cast(avg(t1.b) AS integer)) | (min(t1.f)) | count(distinct a)+abs(cast(avg(b) AS integer))*( -min(b)) | cast(avg(t1.c) AS integer)*((min(t1.e))) from t1 union select cast(avg(f) AS integer) from t1)),t1.e) | +case b when -t1.c then (select (count(*)) from t1) else b end | 13 end) from t1 union select min(t1.d) from t1)} +} {} +do_test randexpr-2.1931 { + db eval {SELECT case when ~case when t1.f>11*t1.a then f when case when (t1.c*19<(t1.f)) then (e) when at1.e and a in (d,t1.c,13) then t1.b when -17 not between f and d then f else t1.c end FROM t1 WHERE NOT (c in (select + -min(case (select count(*) from t1) when t1.a then t1.c else coalesce((select max(b) from t1 where d in (select -abs(cast(avg(t1.b) AS integer)) | (min(t1.f)) | count(distinct a)+abs(cast(avg(b) AS integer))*( -min(b)) | cast(avg(t1.c) AS integer)*((min(t1.e))) from t1 union select cast(avg(f) AS integer) from t1)),t1.e) | +case b when -t1.c then (select (count(*)) from t1) else b end | 13 end) from t1 union select min(t1.d) from t1))} +} {600} +do_test randexpr-2.1932 { + db eval {SELECT case when (b) between 19 and case when t1.a* -t1.d+t1.a-t1.d-b-a<=d then t1.c when not exists(select 1 from t1 where (13>t1.e) and ((a>a))) and -(13)>t1.b then t1.d else 11 end or d=e then 13+t1.f when ( -a) not between t1.e and t1.b then (c) else t1.e end+t1.a+17 FROM t1 WHERE (case when a<=f+t1.a | f then t1.c*a-coalesce((select max( -e) from t1 where t1.a=t1.d),b)*d- -f else t1.b end) in (select min(t1.f)+~max(b) | count(distinct t1.d)*+ - -case (count(*)) when +count(distinct e) then count(*) else -cast(avg(d) AS integer) end from t1 union select count(*) from t1) and d between 11 and t1.a} +} {} +do_test randexpr-2.1933 { + db eval {SELECT case when (b) between 19 and case when t1.a* -t1.d+t1.a-t1.d-b-a<=d then t1.c when not exists(select 1 from t1 where (13>t1.e) and ((a>a))) and -(13)>t1.b then t1.d else 11 end or d=e then 13+t1.f when ( -a) not between t1.e and t1.b then (c) else t1.e end+t1.a+17 FROM t1 WHERE NOT ((case when a<=f+t1.a | f then t1.c*a-coalesce((select max( -e) from t1 where t1.a=t1.d),b)*d- -f else t1.b end) in (select min(t1.f)+~max(b) | count(distinct t1.d)*+ - -case (count(*)) when +count(distinct e) then count(*) else -cast(avg(d) AS integer) end from t1 union select count(*) from t1) and d between 11 and t1.a)} +} {730} +do_test randexpr-2.1934 { + db eval {SELECT +f*19*~~ -t1.c-13-case when t1.b in (select +case when not exists(select 1 from t1 where (((abs((abs((select count(*)*(count(distinct t1.d)) from t1))/abs(b)))/abs(e))*(e))>=d)) then f when t1.a=f then b else t1.e end+19 | (17) from t1 union select t1.b from t1) or -ee and t1.e<=t1.b} +} {} +do_test randexpr-2.1935 { + db eval {SELECT +f*19*~~ -t1.c-13-case when t1.b in (select +case when not exists(select 1 from t1 where (((abs((abs((select count(*)*(count(distinct t1.d)) from t1))/abs(b)))/abs(e))*(e))>=d)) then f when t1.a=f then b else t1.e end+19 | (17) from t1 union select t1.b from t1) or -ee and t1.e<=t1.b)} +} {-3420224} +do_test randexpr-2.1936 { + db eval {SELECT +f*19*~~ -t1.c-13-case when t1.b in (select +case when not exists(select 1 from t1 where (((abs((abs((select count(*)*(count(distinct t1.d)) from t1))/abs(b)))/abs(e))*(e))>=d)) then f when t1.a=f then b else t1.e end+19 & (17) from t1 union select t1.b from t1) or -ee and t1.e<=t1.b)} +} {-3420224} +do_test randexpr-2.1937 { + db eval {SELECT f-coalesce((select max(d+~+ - -(a)*(select min(t1.d) from t1)*t1.f+case when ( -13)*t1.e<>11 | -t1.e or c=11 then (t1.e) when -t1.d<=t1.b and (t1.f<>t1.c) then a else -t1.f end) from t1 where 11 not between t1.e and b),t1.f)-13 FROM t1 WHERE -a not in (17+~coalesce((select t1.a from t1 where (exists(select 1 from t1 where 11>c))),11)+17-11,11,t1.c) or f in (select case (min((t1.a))) when max(b) then min(13) else cast(avg(c) AS integer) end*max(d)*(case cast(avg(19) AS integer) when ( -min(19)) then count(*) else count(*) end) | -cast(avg(19) AS integer) from t1 union select cast(avg(b) AS integer) from t1) or t1.f>= -t1.d} +} {24239687} +do_test randexpr-2.1938 { + db eval {SELECT f-coalesce((select max(d+~+ - -(a)*(select min(t1.d) from t1)*t1.f+case when ( -13)*t1.e<>11 | -t1.e or c=11 then (t1.e) when -t1.d<=t1.b and (t1.f<>t1.c) then a else -t1.f end) from t1 where 11 not between t1.e and b),t1.f)-13 FROM t1 WHERE NOT ( -a not in (17+~coalesce((select t1.a from t1 where (exists(select 1 from t1 where 11>c))),11)+17-11,11,t1.c) or f in (select case (min((t1.a))) when max(b) then min(13) else cast(avg(c) AS integer) end*max(d)*(case cast(avg(19) AS integer) when ( -min(19)) then count(*) else count(*) end) | -cast(avg(19) AS integer) from t1 union select cast(avg(b) AS integer) from t1) or t1.f>= -t1.d)} +} {} +do_test randexpr-2.1939 { + db eval {SELECT f-coalesce((select max(d+~+ - -(a)*(select min(t1.d) from t1)*t1.f+case when ( -13)*t1.e<>11 & -t1.e or c=11 then (t1.e) when -t1.d<=t1.b and (t1.f<>t1.c) then a else -t1.f end) from t1 where 11 not between t1.e and b),t1.f)-13 FROM t1 WHERE -a not in (17+~coalesce((select t1.a from t1 where (exists(select 1 from t1 where 11>c))),11)+17-11,11,t1.c) or f in (select case (min((t1.a))) when max(b) then min(13) else cast(avg(c) AS integer) end*max(d)*(case cast(avg(19) AS integer) when ( -min(19)) then count(*) else count(*) end) | -cast(avg(19) AS integer) from t1 union select cast(avg(b) AS integer) from t1) or t1.f>= -t1.d} +} {24239687} +do_test randexpr-2.1940 { + db eval {SELECT ~case when ~coalesce((select max(f) from t1 where b | (select +max(13) from t1)+t1.b<~13*t1.d*coalesce((select -t1.b from t1 where coalesce((select t1.e+a from t1 where 11=17),a) between 19 and e),17)*d),t1.b) in (select cast(avg(t1.d) AS integer) from t1 union select ~count(distinct 11) from t1) then 11 when t1.d>=t1.b then 13 else f end-t1.e FROM t1 WHERE not exists(select 1 from t1 where coalesce((select case t1.b when -t1.c then c-17 else case f when (abs(case when ((13*case -e when case when b>c and 11>11 then -a when -(t1.c)>t1.e then d else t1.d end then t1.d else t1.e end<=11)) then ~t1.b+f when (d)<=c then t1.a else (t1.a) end+b)/abs(b)) then -b else 11 end end-19 from t1 where t1.e<=t1.b),a)>t1.a)} +} {-514} +do_test randexpr-2.1941 { + db eval {SELECT ~case when ~coalesce((select max(f) from t1 where b | (select +max(13) from t1)+t1.b<~13*t1.d*coalesce((select -t1.b from t1 where coalesce((select t1.e+a from t1 where 11=17),a) between 19 and e),17)*d),t1.b) in (select cast(avg(t1.d) AS integer) from t1 union select ~count(distinct 11) from t1) then 11 when t1.d>=t1.b then 13 else f end-t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where coalesce((select case t1.b when -t1.c then c-17 else case f when (abs(case when ((13*case -e when case when b>c and 11>11 then -a when -(t1.c)>t1.e then d else t1.d end then t1.d else t1.e end<=11)) then ~t1.b+f when (d)<=c then t1.a else (t1.a) end+b)/abs(b)) then -b else 11 end end-19 from t1 where t1.e<=t1.b),a)>t1.a))} +} {} +do_test randexpr-2.1942 { + db eval {SELECT ~case when ~coalesce((select max(f) from t1 where b & (select +max(13) from t1)+t1.b<~13*t1.d*coalesce((select -t1.b from t1 where coalesce((select t1.e+a from t1 where 11=17),a) between 19 and e),17)*d),t1.b) in (select cast(avg(t1.d) AS integer) from t1 union select ~count(distinct 11) from t1) then 11 when t1.d>=t1.b then 13 else f end-t1.e FROM t1 WHERE not exists(select 1 from t1 where coalesce((select case t1.b when -t1.c then c-17 else case f when (abs(case when ((13*case -e when case when b>c and 11>11 then -a when -(t1.c)>t1.e then d else t1.d end then t1.d else t1.e end<=11)) then ~t1.b+f when (d)<=c then t1.a else (t1.a) end+b)/abs(b)) then -b else 11 end end-19 from t1 where t1.e<=t1.b),a)>t1.a)} +} {-514} +do_test randexpr-2.1943 { + db eval {SELECT +(case when (not exists(select 1 from t1 where t1.c in (select +(abs(a)/abs( -coalesce((select max(17) from t1 where (not (c>=t1.d and t1.c>=f) and t1.e>e)),19-17))) from t1 union select case when (b)>d then d when c not in (f,t1.b,t1.d) then t1.f else t1.d end from t1) or a not in (t1.d,a, -b))) and exists(select 1 from t1 where b<11) then c when t1.c not between e and -19 then t1.b else ~c end) FROM t1 WHERE t1.e*f-a- -13-b= -d} +} {} +do_test randexpr-2.1944 { + db eval {SELECT +(case when (not exists(select 1 from t1 where t1.c in (select +(abs(a)/abs( -coalesce((select max(17) from t1 where (not (c>=t1.d and t1.c>=f) and t1.e>e)),19-17))) from t1 union select case when (b)>d then d when c not in (f,t1.b,t1.d) then t1.f else t1.d end from t1) or a not in (t1.d,a, -b))) and exists(select 1 from t1 where b<11) then c when t1.c not between e and -19 then t1.b else ~c end) FROM t1 WHERE NOT (t1.e*f-a- -13-b= -d)} +} {200} +do_test randexpr-2.1945 { + db eval {SELECT b-case when a not between t1.f and case when t1.d in (select count(*) from t1 union select cast(avg(coalesce((select +11*t1.e from t1 where e+bb and t1.d between c and b then t1.d else t1.d endb and t1.d between c and b then t1.d else t1.d endb and t1.d between c and b then t1.d else t1.d end=t1.d and 17<=13 or f between -t1.c and 11 then case d when t1.c then 13 else t1.e end when (11)>b then a else c end in (t1.e,a,b)} +} {} +do_test randexpr-2.1949 { + db eval {SELECT (select (min(coalesce((select max((case when t1.f=t1.d and 17<=13 or f between -t1.c and 11 then case d when t1.c then 13 else t1.e end when (11)>b then a else c end in (t1.e,a,b))} +} {582} +do_test randexpr-2.1950 { + db eval {SELECT coalesce((select max((abs(e)/abs(t1.a))) from t1 where (select (count(distinct ~ - -11- -t1.a-a*t1.d | 11-19+t1.f+17*c)-cast(avg(17) AS integer)+(cast(avg((19)) AS integer))) from t1)>a),17 | 11+17)+e-(c)-d-b FROM t1 WHERE (d>t1.d-case when case +(abs(t1.d | t1.f)/abs(t1.b)) when +b then coalesce((select max(t1.d | t1.c+(11+t1.d-t1.c)) from t1 where ((t1.e=17))),17) else t1.c end>=b then a else t1.f end) and (not (e<=c)) and not (t1.c<>b)} +} {} +do_test randexpr-2.1951 { + db eval {SELECT coalesce((select max((abs(e)/abs(t1.a))) from t1 where (select (count(distinct ~ - -11- -t1.a-a*t1.d | 11-19+t1.f+17*c)-cast(avg(17) AS integer)+(cast(avg((19)) AS integer))) from t1)>a),17 | 11+17)+e-(c)-d-b FROM t1 WHERE NOT ((d>t1.d-case when case +(abs(t1.d | t1.f)/abs(t1.b)) when +b then coalesce((select max(t1.d | t1.c+(11+t1.d-t1.c)) from t1 where ((t1.e=17))),17) else t1.c end>=b then a else t1.f end) and (not (e<=c)) and not (t1.c<>b))} +} {-371} +do_test randexpr-2.1952 { + db eval {SELECT coalesce((select max((abs(e)/abs(t1.a))) from t1 where (select (count(distinct ~ - -11- -t1.a-a*t1.d & 11-19+t1.f+17*c)-cast(avg(17) AS integer)+(cast(avg((19)) AS integer))) from t1)>a),17 & 11+17)+e-(c)-d-b FROM t1 WHERE NOT ((d>t1.d-case when case +(abs(t1.d | t1.f)/abs(t1.b)) when +b then coalesce((select max(t1.d | t1.c+(11+t1.d-t1.c)) from t1 where ((t1.e=17))),17) else t1.c end>=b then a else t1.f end) and (not (e<=c)) and not (t1.c<>b))} +} {-384} +do_test randexpr-2.1953 { + db eval {SELECT coalesce((select c from t1 where case b when t1.a*(17) | case b++b when e then d else t1.b+f end+a+t1.d then d else t1.b | +e end<+~(select (count(*)) from t1)),17) FROM t1 WHERE (b+t1.c*c in (11, -t1.f,t1.b))} +} {} +do_test randexpr-2.1954 { + db eval {SELECT coalesce((select c from t1 where case b when t1.a*(17) | case b++b when e then d else t1.b+f end+a+t1.d then d else t1.b | +e end<+~(select (count(*)) from t1)),17) FROM t1 WHERE NOT ((b+t1.c*c in (11, -t1.f,t1.b)))} +} {17} +do_test randexpr-2.1955 { + db eval {SELECT coalesce((select c from t1 where case b when t1.a*(17) & case b++b when e then d else t1.b+f end+a+t1.d then d else t1.b & +e end<+~(select (count(*)) from t1)),17) FROM t1 WHERE NOT ((b+t1.c*c in (11, -t1.f,t1.b)))} +} {17} +do_test randexpr-2.1956 { + db eval {SELECT case when coalesce((select max((abs(c)/abs(t1.d))) from t1 where t1.f*case when t1.a in (select (abs(17)/abs(c))*(t1.a) from t1 union select t1.e from t1) then t1.b else b end<19),e)+a-d in (select case max(t1.b)-count(distinct t1.c) when +case abs(cast(avg(t1.f) AS integer)) when +cast(avg(f) AS integer)-min(f) then count(distinct c) else cast(avg(d) AS integer) end then count(distinct t1.a) else cast(avg(b) AS integer) end from t1 union select count(distinct t1.e) from t1) then t1.c else f end FROM t1 WHERE ((19 in (t1.b,case t1.f when 11 then 11 else -+t1.b | 19 end+coalesce((select 11 from t1 where c<=t1.c* -e),f),t1.f)) or (b between t1.b and 17) or not exists(select 1 from t1 where -17 between -f and t1.e or (not b<>11) and 19 in (select 11 from t1 union select t1.b from t1))) or 13>(t1.e)} +} {} +do_test randexpr-2.1957 { + db eval {SELECT case when coalesce((select max((abs(c)/abs(t1.d))) from t1 where t1.f*case when t1.a in (select (abs(17)/abs(c))*(t1.a) from t1 union select t1.e from t1) then t1.b else b end<19),e)+a-d in (select case max(t1.b)-count(distinct t1.c) when +case abs(cast(avg(t1.f) AS integer)) when +cast(avg(f) AS integer)-min(f) then count(distinct c) else cast(avg(d) AS integer) end then count(distinct t1.a) else cast(avg(b) AS integer) end from t1 union select count(distinct t1.e) from t1) then t1.c else f end FROM t1 WHERE NOT (((19 in (t1.b,case t1.f when 11 then 11 else -+t1.b | 19 end+coalesce((select 11 from t1 where c<=t1.c* -e),f),t1.f)) or (b between t1.b and 17) or not exists(select 1 from t1 where -17 between -f and t1.e or (not b<>11) and 19 in (select 11 from t1 union select t1.b from t1))) or 13>(t1.e))} +} {300} +do_test randexpr-2.1958 { + db eval {SELECT f+case when e>+11+t1.e or ~t1.a=f+t1.e+t1.c then t1.a+case when b*coalesce((select max(a) from t1 where not exists(select 1 from t1 where (t1.f=case when exists(select 1 from t1 where t1.ff),11))<(e) then t1.e else 19 end+(c) else t1.a end*c-t1.c FROM t1 WHERE not ~coalesce((select max(t1.f*coalesce((select max(f) from t1 where case 17 when e*19 then case t1.a when 17 then f else t1.c+t1.d end | (e) else ~a end>=e or not t1.b in (select a from t1 union select d from t1)),19)) from t1 where e>coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.c=t1.a)),case t1.b when t1.b then a else 19 end)),13)*t1.b not between t1.e and t1.e} +} {} +do_test randexpr-2.1959 { + db eval {SELECT f+case when e>+11+t1.e or ~t1.a=f+t1.e+t1.c then t1.a+case when b*coalesce((select max(a) from t1 where not exists(select 1 from t1 where (t1.f=case when exists(select 1 from t1 where t1.ff),11))<(e) then t1.e else 19 end+(c) else t1.a end*c-t1.c FROM t1 WHERE NOT (not ~coalesce((select max(t1.f*coalesce((select max(f) from t1 where case 17 when e*19 then case t1.a when 17 then f else t1.c+t1.d end | (e) else ~a end>=e or not t1.b in (select a from t1 union select d from t1)),19)) from t1 where e>coalesce((select 17 from t1 where not exists(select 1 from t1 where t1.c=t1.a)),case t1.b when t1.b then a else 19 end)),13)*t1.b not between t1.e and t1.e)} +} {30300} +do_test randexpr-2.1960 { + db eval {SELECT e*(select -max((case when -case when (+(abs(f)/abs(17))*13)> -a then 17 else f end | -t1.f-e*11<>11 then c when exists(select 1 from t1 where not exists(select 1 from t1 where t1.b not in (t1.d,19,d) and t1.d<>11)) or 13<= -t1.f then 11 else d end-t1.a)*e) from t1) FROM t1 WHERE exists(select 1 from t1 where c<>a)} +} {-50000000} +do_test randexpr-2.1961 { + db eval {SELECT e*(select -max((case when -case when (+(abs(f)/abs(17))*13)> -a then 17 else f end | -t1.f-e*11<>11 then c when exists(select 1 from t1 where not exists(select 1 from t1 where t1.b not in (t1.d,19,d) and t1.d<>11)) or 13<= -t1.f then 11 else d end-t1.a)*e) from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where c<>a))} +} {} +do_test randexpr-2.1962 { + db eval {SELECT e*(select -max((case when -case when (+(abs(f)/abs(17))*13)> -a then 17 else f end & -t1.f-e*11<>11 then c when exists(select 1 from t1 where not exists(select 1 from t1 where t1.b not in (t1.d,19,d) and t1.d<>11)) or 13<= -t1.f then 11 else d end-t1.a)*e) from t1) FROM t1 WHERE exists(select 1 from t1 where c<>a)} +} {-50000000} +do_test randexpr-2.1963 { + db eval {SELECT a-t1.b | (case case when 13 in (t1.c,(t1.c),t1.e) then e+b when b in (select e from t1 union select d from t1) then (select count(distinct (abs(case when t1.e not between c and c then f else case t1.a when t1.c then e+t1.d else c end end)/abs(b))) from t1) else t1.b- -t1.d end when t1.c then 11 else e end- -a)+d-t1.b FROM t1 WHERE (case when f between f+(abs(coalesce((select t1.c*t1.c from t1 where f between 19 and (select count(distinct coalesce((select max(case case when t1.b<>t1.c then t1.d when 19t1.c then t1.d when 19t1.c then t1.d when 19 -case t1.f when +b-case when (17 in (select count(distinct b)+count(distinct t1.a) from t1 union select count(distinct 13) from t1)) then d else 13 end+t1.d | d* -11+t1.d*t1.f | a-17 then 13 else c end*t1.e),d) then t1.b else d end)/abs(t1.a))*19 FROM t1 WHERE t1.f in (select count(*) from t1 union select count(*) from t1)} +} {} +do_test randexpr-2.1967 { + db eval {SELECT (abs(case t1.f | d when coalesce((select max(~b) from t1 where +t1.a<> -case t1.f when +b-case when (17 in (select count(distinct b)+count(distinct t1.a) from t1 union select count(distinct 13) from t1)) then d else 13 end+t1.d | d* -11+t1.d*t1.f | a-17 then 13 else c end*t1.e),d) then t1.b else d end)/abs(t1.a))*19 FROM t1 WHERE NOT (t1.f in (select count(*) from t1 union select count(*) from t1))} +} {76} +do_test randexpr-2.1968 { + db eval {SELECT (abs(case t1.f & d when coalesce((select max(~b) from t1 where +t1.a<> -case t1.f when +b-case when (17 in (select count(distinct b)+count(distinct t1.a) from t1 union select count(distinct 13) from t1)) then d else 13 end+t1.d & d* -11+t1.d*t1.f & a-17 then 13 else c end*t1.e),d) then t1.b else d end)/abs(t1.a))*19 FROM t1 WHERE NOT (t1.f in (select count(*) from t1 union select count(*) from t1))} +} {76} +do_test randexpr-2.1969 { + db eval {SELECT t1.d+coalesce((select max(t1.b*t1.b | ~case a | c | t1.d when t1.c then t1.a else t1.e end | e-13*b) from t1 where -t1.a in (select e from t1 union select t1.b from t1) and not exists(select 1 from t1 where (a) in (select min(13)* -cast(avg(t1.e) AS integer)*~case count(*) when count(*) then ((cast(avg(e) AS integer))) else count(*) end | (min(t1.e)) | -count(*) from t1 union select max(t1.a) from t1))), -t1.b)+a FROM t1 WHERE not exists(select 1 from t1 where 11*d+a>=(t1.a-e+17*(select +cast(avg((select cast(avg((abs(case when (abs(t1.a)/abs(coalesce((select max(c+t1.e) from t1 where not exists(select 1 from t1 where 13 in (select -t1.c from t1 union select t1.f from t1))),17) | e*e)) not between e and t1.f then 19 else t1.b end)/abs(19))) AS integer)* -count(*) from t1)) AS integer)*count(distinct 11)-abs(cast(avg(b) AS integer)) from t1)))} +} {} +do_test randexpr-2.1970 { + db eval {SELECT t1.d+coalesce((select max(t1.b*t1.b | ~case a | c | t1.d when t1.c then t1.a else t1.e end | e-13*b) from t1 where -t1.a in (select e from t1 union select t1.b from t1) and not exists(select 1 from t1 where (a) in (select min(13)* -cast(avg(t1.e) AS integer)*~case count(*) when count(*) then ((cast(avg(e) AS integer))) else count(*) end | (min(t1.e)) | -count(*) from t1 union select max(t1.a) from t1))), -t1.b)+a FROM t1 WHERE NOT (not exists(select 1 from t1 where 11*d+a>=(t1.a-e+17*(select +cast(avg((select cast(avg((abs(case when (abs(t1.a)/abs(coalesce((select max(c+t1.e) from t1 where not exists(select 1 from t1 where 13 in (select -t1.c from t1 union select t1.f from t1))),17) | e*e)) not between e and t1.f then 19 else t1.b end)/abs(19))) AS integer)* -count(*) from t1)) AS integer)*count(distinct 11)-abs(cast(avg(b) AS integer)) from t1))))} +} {300} +do_test randexpr-2.1971 { + db eval {SELECT t1.d+coalesce((select max(t1.b*t1.b & ~case a & c & t1.d when t1.c then t1.a else t1.e end & e-13*b) from t1 where -t1.a in (select e from t1 union select t1.b from t1) and not exists(select 1 from t1 where (a) in (select min(13)* -cast(avg(t1.e) AS integer)*~case count(*) when count(*) then ((cast(avg(e) AS integer))) else count(*) end & (min(t1.e)) & -count(*) from t1 union select max(t1.a) from t1))), -t1.b)+a FROM t1 WHERE NOT (not exists(select 1 from t1 where 11*d+a>=(t1.a-e+17*(select +cast(avg((select cast(avg((abs(case when (abs(t1.a)/abs(coalesce((select max(c+t1.e) from t1 where not exists(select 1 from t1 where 13 in (select -t1.c from t1 union select t1.f from t1))),17) | e*e)) not between e and t1.f then 19 else t1.b end)/abs(19))) AS integer)* -count(*) from t1)) AS integer)*count(distinct 11)-abs(cast(avg(b) AS integer)) from t1))))} +} {300} +do_test randexpr-2.1972 { + db eval {SELECT ~case when case when +d+case b when 11 then coalesce((select max(b) from t1 where (((abs(f)/abs((abs(11)/abs(e))+t1.b))>t1.f))),(select max(t1.e) from t1)) else t1.f end*t1.f*17>=(t1.e) or 17>t1.f then t1.a else t1.a end in (c,13,c) then t1.f when t1.a not in (t1.d, -t1.b,a) then -t1.b else 11 end FROM t1 WHERE t1.a in (+e,17,11*13) and b not between t1.f*(abs(t1.c-((abs(t1.a | coalesce((select max(case when -f-t1.c<=t1.f then 19 when (t1.a)<>t1.f and 13 between a and t1.e then -11 else 17 end) from t1 where c>19),f)-t1.e)/abs(e))))/abs(b))-t1.e | (19) and -t1.a and t1.f in (select 13 from t1 union select a from t1)} +} {} +do_test randexpr-2.1973 { + db eval {SELECT ~case when case when +d+case b when 11 then coalesce((select max(b) from t1 where (((abs(f)/abs((abs(11)/abs(e))+t1.b))>t1.f))),(select max(t1.e) from t1)) else t1.f end*t1.f*17>=(t1.e) or 17>t1.f then t1.a else t1.a end in (c,13,c) then t1.f when t1.a not in (t1.d, -t1.b,a) then -t1.b else 11 end FROM t1 WHERE NOT (t1.a in (+e,17,11*13) and b not between t1.f*(abs(t1.c-((abs(t1.a | coalesce((select max(case when -f-t1.c<=t1.f then 19 when (t1.a)<>t1.f and 13 between a and t1.e then -11 else 17 end) from t1 where c>19),f)-t1.e)/abs(e))))/abs(b))-t1.e | (19) and -t1.a and t1.f in (select 13 from t1 union select a from t1))} +} {-12} +do_test randexpr-2.1974 { + db eval {SELECT case when case 17 when case when (abs(t1.c)/abs(t1.c | coalesce((select max(t1.d) from t1 where not t1.e<17 or 11 not in (t1.a,t1.c,a) or c=d and (t1.b)=t1.e and 17 in ( -t1.c,a,d) and t1.f not in (19,a,b)),11) | (select -max(+t1.b) from t1)+19-19 | f))<>t1.a or e>17 then f else a end then 11 else f end=t1.a then f else -t1.f end FROM t1 WHERE -t1.b+a>= -t1.a} +} {-600} +do_test randexpr-2.1975 { + db eval {SELECT case when case 17 when case when (abs(t1.c)/abs(t1.c | coalesce((select max(t1.d) from t1 where not t1.e<17 or 11 not in (t1.a,t1.c,a) or c=d and (t1.b)=t1.e and 17 in ( -t1.c,a,d) and t1.f not in (19,a,b)),11) | (select -max(+t1.b) from t1)+19-19 | f))<>t1.a or e>17 then f else a end then 11 else f end=t1.a then f else -t1.f end FROM t1 WHERE NOT ( -t1.b+a>= -t1.a)} +} {} +do_test randexpr-2.1976 { + db eval {SELECT (abs(coalesce((select ((t1.c)) from t1 where not exists(select 1 from t1 where t1.e*17<13*coalesce((select max(a) from t1 where 19 in (select max(e*11) from t1 union select cast(avg(t1.b) AS integer) from t1)),a | a))),case when f-13t1.e then t1.b else f end))/abs(17)) FROM t1 WHERE ((d not between -a and b))} +} {17} +do_test randexpr-2.1977 { + db eval {SELECT (abs(coalesce((select ((t1.c)) from t1 where not exists(select 1 from t1 where t1.e*17<13*coalesce((select max(a) from t1 where 19 in (select max(e*11) from t1 union select cast(avg(t1.b) AS integer) from t1)),a | a))),case when f-13t1.e then t1.b else f end))/abs(17)) FROM t1 WHERE NOT (((d not between -a and b)))} +} {} +do_test randexpr-2.1978 { + db eval {SELECT (abs(coalesce((select ((t1.c)) from t1 where not exists(select 1 from t1 where t1.e*17<13*coalesce((select max(a) from t1 where 19 in (select max(e*11) from t1 union select cast(avg(t1.b) AS integer) from t1)),a & a))),case when f-13t1.e then t1.b else f end))/abs(17)) FROM t1 WHERE ((d not between -a and b))} +} {17} +do_test randexpr-2.1979 { + db eval {SELECT case f when (d)-case when coalesce((select max(coalesce((select 11 from t1 where case when (t1.f<=17 or exists(select 1 from t1 where 11 | d in (select (abs(max(t1.f))) from t1 union select ( -min(c)) from t1))) then a when t1.f not in (e,13,13) then t1.c else e end between 19 and c),t1.a)) from t1 where f>=t1.d),17) not between e and t1.c and 11<=17 then t1.e-19 when t1.a not in (c,t1.e,t1.c) then 11 else t1.b end then t1.e else t1.f end FROM t1 WHERE (not (case 17 when d then t1.c else c end=f | (select case count(*) when count(*)++max(11)+ -(abs(+cast(avg(c) AS integer)-(~count(*))+count(*)*(~case max( -c) when - -cast(avg(t1.f) AS integer) then (count(*)) else -max(t1.b) end*cast(avg(a) AS integer))-count(*) | ( -( -max(11)))) | ( -min(17))+count(*)) then (max(19)) else max(t1.c) end from t1)))} +} {600} +do_test randexpr-2.1980 { + db eval {SELECT case f when (d)-case when coalesce((select max(coalesce((select 11 from t1 where case when (t1.f<=17 or exists(select 1 from t1 where 11 | d in (select (abs(max(t1.f))) from t1 union select ( -min(c)) from t1))) then a when t1.f not in (e,13,13) then t1.c else e end between 19 and c),t1.a)) from t1 where f>=t1.d),17) not between e and t1.c and 11<=17 then t1.e-19 when t1.a not in (c,t1.e,t1.c) then 11 else t1.b end then t1.e else t1.f end FROM t1 WHERE NOT ((not (case 17 when d then t1.c else c end=f | (select case count(*) when count(*)++max(11)+ -(abs(+cast(avg(c) AS integer)-(~count(*))+count(*)*(~case max( -c) when - -cast(avg(t1.f) AS integer) then (count(*)) else -max(t1.b) end*cast(avg(a) AS integer))-count(*) | ( -( -max(11)))) | ( -min(17))+count(*)) then (max(19)) else max(t1.c) end from t1))))} +} {} +do_test randexpr-2.1981 { + db eval {SELECT case f when (d)-case when coalesce((select max(coalesce((select 11 from t1 where case when (t1.f<=17 or exists(select 1 from t1 where 11 & d in (select (abs(max(t1.f))) from t1 union select ( -min(c)) from t1))) then a when t1.f not in (e,13,13) then t1.c else e end between 19 and c),t1.a)) from t1 where f>=t1.d),17) not between e and t1.c and 11<=17 then t1.e-19 when t1.a not in (c,t1.e,t1.c) then 11 else t1.b end then t1.e else t1.f end FROM t1 WHERE (not (case 17 when d then t1.c else c end=f | (select case count(*) when count(*)++max(11)+ -(abs(+cast(avg(c) AS integer)-(~count(*))+count(*)*(~case max( -c) when - -cast(avg(t1.f) AS integer) then (count(*)) else -max(t1.b) end*cast(avg(a) AS integer))-count(*) | ( -( -max(11)))) | ( -min(17))+count(*)) then (max(19)) else max(t1.c) end from t1)))} +} {600} +do_test randexpr-2.1982 { + db eval {SELECT case when d+t1.d not between t1.f and + -t1.c then ~+a+(select +count(*) from t1) else (select +abs(count(*)) from t1)-t1.a end FROM t1 WHERE t1.b+f | d+a in (select +cast(avg(b) AS integer)++case min(coalesce((select t1.c from t1 where (e) in ((a)+17,t1.b,d)),t1.f)) when ~~cast(avg(17) AS integer)-max((t1.a)) then case min(13) when count(*) then count(distinct t1.a) else cast(avg(b) AS integer) end*max(d)+max(t1.b) else -count(*) end-count(*) from t1 union select cast(avg(t1.f) AS integer) from t1)} +} {} +do_test randexpr-2.1983 { + db eval {SELECT case when d+t1.d not between t1.f and + -t1.c then ~+a+(select +count(*) from t1) else (select +abs(count(*)) from t1)-t1.a end FROM t1 WHERE NOT (t1.b+f | d+a in (select +cast(avg(b) AS integer)++case min(coalesce((select t1.c from t1 where (e) in ((a)+17,t1.b,d)),t1.f)) when ~~cast(avg(17) AS integer)-max((t1.a)) then case min(13) when count(*) then count(distinct t1.a) else cast(avg(b) AS integer) end*max(d)+max(t1.b) else -count(*) end-count(*) from t1 union select cast(avg(t1.f) AS integer) from t1))} +} {-100} +do_test randexpr-2.1984 { + db eval {SELECT case when case when case case when (case when (( -ft1.c or exists(select 1 from t1 where not exists(select 1 from t1 where (a not between b and -t1.e)) and t1.f>=(t1.a)) and t1.f<(t1.b)) then 19 else e end) when a then t1.e else 11 end,(a),19)} +} {} +do_test randexpr-2.1985 { + db eval {SELECT case when case when case case when (case when (( -ft1.c or exists(select 1 from t1 where not exists(select 1 from t1 where (a not between b and -t1.e)) and t1.f>=(t1.a)) and t1.f<(t1.b)) then 19 else e end) when a then t1.e else 11 end,(a),19))} +} {-11300} +do_test randexpr-2.1986 { + db eval {SELECT coalesce((select 11 from t1 where 19 in (select ((count(*)*min(11)*(abs(max(a)))-max(b)*+count(*))) from t1 union select case abs(abs(min(t1.b))*case count(distinct b) when count(distinct t1.a) then count(distinct t1.f-t1.f) else max(11) end) when cast(avg(e) AS integer) then count(*) else count(*) end from t1)),d)*11+t1.c+b | 13+19 FROM t1 WHERE t1.c in (select 19 from t1 union select ~t1.f-t1.f+17- -17 from t1)} +} {} +do_test randexpr-2.1987 { + db eval {SELECT coalesce((select 11 from t1 where 19 in (select ((count(*)*min(11)*(abs(max(a)))-max(b)*+count(*))) from t1 union select case abs(abs(min(t1.b))*case count(distinct b) when count(distinct t1.a) then count(distinct t1.f-t1.f) else max(11) end) when cast(avg(e) AS integer) then count(*) else count(*) end from t1)),d)*11+t1.c+b | 13+19 FROM t1 WHERE NOT (t1.c in (select 19 from t1 union select ~t1.f-t1.f+17- -17 from t1))} +} {4900} +do_test randexpr-2.1988 { + db eval {SELECT coalesce((select 11 from t1 where 19 in (select ((count(*)*min(11)*(abs(max(a)))-max(b)*+count(*))) from t1 union select case abs(abs(min(t1.b))*case count(distinct b) when count(distinct t1.a) then count(distinct t1.f-t1.f) else max(11) end) when cast(avg(e) AS integer) then count(*) else count(*) end from t1)),d)*11+t1.c+b & 13+19 FROM t1 WHERE NOT (t1.c in (select 19 from t1 union select ~t1.f-t1.f+17- -17 from t1))} +} {32} +do_test randexpr-2.1989 { + db eval {SELECT case f when (select ++abs(max(d))+case case count(*) when min(t1.c) then (count(*)) else min(t1.e) end when -count(distinct t1.e) then count(distinct a) else min(t1.b) end from t1) then coalesce((select case when e in (select d from t1 union select f from t1) and t1.a not between b and 13 and d in (select 17 from t1 union select b from t1) then 17 when 11=f then 19 else d end from t1 where 11 not in (t1.c,t1.c,t1.d)),a) else e end-t1.e-t1.d-17*t1.f FROM t1 WHERE case when coalesce((select max(c) from t1 where 19 not between 11 and t1.e and t1.b in (select count(*) from t1 union select ~min(case c when (abs(case when d=( -t1.e) or t1.b<>t1.f then b else t1.b end)/abs(t1.c))+19 then t1.f else d end) from t1) and -b in (select min(17) from t1 union select min( -c) | count(distinct 17)- -(count(*))+max(t1.c) | -cast(avg(t1.c) AS integer) from t1)),t1.c)*t1.f not between -t1.e and t1.f then 11 else f end>f} +} {} +do_test randexpr-2.1990 { + db eval {SELECT case f when (select ++abs(max(d))+case case count(*) when min(t1.c) then (count(*)) else min(t1.e) end when -count(distinct t1.e) then count(distinct a) else min(t1.b) end from t1) then coalesce((select case when e in (select d from t1 union select f from t1) and t1.a not between b and 13 and d in (select 17 from t1 union select b from t1) then 17 when 11=f then 19 else d end from t1 where 11 not in (t1.c,t1.c,t1.d)),a) else e end-t1.e-t1.d-17*t1.f FROM t1 WHERE NOT (case when coalesce((select max(c) from t1 where 19 not between 11 and t1.e and t1.b in (select count(*) from t1 union select ~min(case c when (abs(case when d=( -t1.e) or t1.b<>t1.f then b else t1.b end)/abs(t1.c))+19 then t1.f else d end) from t1) and -b in (select min(17) from t1 union select min( -c) | count(distinct 17)- -(count(*))+max(t1.c) | -cast(avg(t1.c) AS integer) from t1)),t1.c)*t1.f not between -t1.e and t1.f then 11 else f end>f)} +} {-10700} +do_test randexpr-2.1991 { + db eval {SELECT case when ((coalesce((select t1.a from t1 where exists(select 1 from t1 where t1.a<=t1.b-e*coalesce((select max(a) from t1 where t1.e in (select min(13+13) from t1 union select -(count(distinct t1.f)-count(*)) from t1)),17)-f-t1.f) or t1.d in (select t1.a from t1 union select b from t1)),t1.d*t1.f)<>a)) then t1.d when not exists(select 1 from t1 where ((t1.f in (c,19,f)))) then t1.f else 17 end FROM t1 WHERE t1.c<=a} +} {} +do_test randexpr-2.1992 { + db eval {SELECT case when ((coalesce((select t1.a from t1 where exists(select 1 from t1 where t1.a<=t1.b-e*coalesce((select max(a) from t1 where t1.e in (select min(13+13) from t1 union select -(count(distinct t1.f)-count(*)) from t1)),17)-f-t1.f) or t1.d in (select t1.a from t1 union select b from t1)),t1.d*t1.f)<>a)) then t1.d when not exists(select 1 from t1 where ((t1.f in (c,19,f)))) then t1.f else 17 end FROM t1 WHERE NOT (t1.c<=a)} +} {400} +do_test randexpr-2.1993 { + db eval {SELECT case 17 when t1.f then 11 else (case when (c between case when ~t1.e+13-t1.c+case coalesce((select t1.c from t1 where t1.a not between a and 17),coalesce((select max(case when exists(select 1 from t1 where a>=t1.a) then ((t1.e)) when t1.e>=11 then 17 else t1.b end) from t1 where ( -11d),t1.c) | b- -17-(17)*c) from t1 where (19<13)),t1.c) not between a and t1.a} +} {200} +do_test randexpr-2.1994 { + db eval {SELECT case 17 when t1.f then 11 else (case when (c between case when ~t1.e+13-t1.c+case coalesce((select t1.c from t1 where t1.a not between a and 17),coalesce((select max(case when exists(select 1 from t1 where a>=t1.a) then ((t1.e)) when t1.e>=11 then 17 else t1.b end) from t1 where ( -11d),t1.c) | b- -17-(17)*c) from t1 where (19<13)),t1.c) not between a and t1.a)} +} {} +do_test randexpr-2.1995 { + db eval {SELECT case 17 when t1.f then 11 else (case when (c between case when ~t1.e+13-t1.c+case coalesce((select t1.c from t1 where t1.a not between a and 17),coalesce((select max(case when exists(select 1 from t1 where a>=t1.a) then ((t1.e)) when t1.e>=11 then 17 else t1.b end) from t1 where ( -11d),t1.c) | b- -17-(17)*c) from t1 where (19<13)),t1.c) not between a and t1.a} +} {200} +do_test randexpr-2.1996 { + db eval {SELECT 17+(select case ~max((abs(t1.c+coalesce((select max(t1.f) from t1 where t1.f in (select 13-c-case when not a>=t1.c then f else t1.c end+t1.c from t1 union select 19 from t1) or exists(select 1 from t1 where 1317 | e*d-17*t1.e*case a when case when (not f>=19 and t1.f<=t1.b) then coalesce((select case 11 when -c then t1.f else (t1.f) end from t1 where 13 between t1.e and t1.f),(e)) when -t1.f not between b and d then t1.d else t1.a end then 11 else 19 end then d when ad)} +} {1017} +do_test randexpr-2.1997 { + db eval {SELECT 17+(select case ~max((abs(t1.c+coalesce((select max(t1.f) from t1 where t1.f in (select 13-c-case when not a>=t1.c then f else t1.c end+t1.c from t1 union select 19 from t1) or exists(select 1 from t1 where 1317 | e*d-17*t1.e*case a when case when (not f>=19 and t1.f<=t1.b) then coalesce((select case 11 when -c then t1.f else (t1.f) end from t1 where 13 between t1.e and t1.f),(e)) when -t1.f not between b and d then t1.d else t1.a end then 11 else 19 end then d when ad))} +} {} +do_test randexpr-2.1998 { + db eval {SELECT 17+(select case ~max((abs(t1.c+coalesce((select max(t1.f) from t1 where t1.f in (select 13-c-case when not a>=t1.c then f else t1.c end+t1.c from t1 union select 19 from t1) or exists(select 1 from t1 where 1317 | e*d-17*t1.e*case a when case when (not f>=19 and t1.f<=t1.b) then coalesce((select case 11 when -c then t1.f else (t1.f) end from t1 where 13 between t1.e and t1.f),(e)) when -t1.f not between b and d then t1.d else t1.a end then 11 else 19 end then d when ad)} +} {0} +do_test randexpr-2.1999 { + db eval {SELECT ~c-t1.a*case -case 19 when d then t1.f else t1.a end-d when 11 then coalesce((select max(case when (case when exists(select 1 from t1 where 11*11>13) then t1.c else 11 end)<=(select min(~d+case 19 when e then 13 else e end) from t1) then c when ((f))<=17 then d else t1.c end+t1.f) from t1 where (t1.b between -c and t1.e)),t1.e) else 17 end FROM t1 WHERE +(abs(d-(select cast(avg((select (abs(max(t1.d*+d*( -e*(13)) | 17)+ -min(t1.d)+~ - -max(17) | max(t1.a) | -count(distinct t1.a)-count(distinct 13)*(count(distinct t1.a)) | (count(distinct 17)))) from t1)) AS integer) from t1)-11)/abs(c+d-t1.e))>=t1.d} +} {} +do_test randexpr-2.2000 { + db eval {SELECT ~c-t1.a*case -case 19 when d then t1.f else t1.a end-d when 11 then coalesce((select max(case when (case when exists(select 1 from t1 where 11*11>13) then t1.c else 11 end)<=(select min(~d+case 19 when e then 13 else e end) from t1) then c when ((f))<=17 then d else t1.c end+t1.f) from t1 where (t1.b between -c and t1.e)),t1.e) else 17 end FROM t1 WHERE NOT (+(abs(d-(select cast(avg((select (abs(max(t1.d*+d*( -e*(13)) | 17)+ -min(t1.d)+~ - -max(17) | max(t1.a) | -count(distinct t1.a)-count(distinct 13)*(count(distinct t1.a)) | (count(distinct 17)))) from t1)) AS integer) from t1)-11)/abs(c+d-t1.e))>=t1.d)} +} {-2001} +do_test randexpr-2.2001 { + db eval {SELECT coalesce((select 11 from t1 where a not in (17,e,(select -abs(case ( -count(distinct t1.e)) when count(distinct 13) | max((abs(case 11 when -(abs(19)/abs(17 | t1.c*t1.e))*t1.c | t1.b then a else +d end)/abs(b*t1.a))) then max(c*13) else cast(avg(t1.f) AS integer) end)-max(11) from t1)*d)),t1.d) FROM t1 WHERE 19-c*coalesce((select max(case (select count(distinct t1.f) from t1) | t1.a when case a when (abs(case when not c+t1.d>=e then 17*t1.e+a when not exists(select 1 from t1 where 11>b) then c else a end)/abs(t1.e))+t1.f*13 then 11 else t1.f end then 19 else d end-b) from t1 where (d) not between f and e),t1.d)= -c} +} {} +do_test randexpr-2.2002 { + db eval {SELECT coalesce((select 11 from t1 where a not in (17,e,(select -abs(case ( -count(distinct t1.e)) when count(distinct 13) | max((abs(case 11 when -(abs(19)/abs(17 | t1.c*t1.e))*t1.c | t1.b then a else +d end)/abs(b*t1.a))) then max(c*13) else cast(avg(t1.f) AS integer) end)-max(11) from t1)*d)),t1.d) FROM t1 WHERE NOT (19-c*coalesce((select max(case (select count(distinct t1.f) from t1) | t1.a when case a when (abs(case when not c+t1.d>=e then 17*t1.e+a when not exists(select 1 from t1 where 11>b) then c else a end)/abs(t1.e))+t1.f*13 then 11 else t1.f end then 19 else d end-b) from t1 where (d) not between f and e),t1.d)= -c)} +} {11} +do_test randexpr-2.2003 { + db eval {SELECT coalesce((select 11 from t1 where a not in (17,e,(select -abs(case ( -count(distinct t1.e)) when count(distinct 13) & max((abs(case 11 when -(abs(19)/abs(17 & t1.c*t1.e))*t1.c & t1.b then a else +d end)/abs(b*t1.a))) then max(c*13) else cast(avg(t1.f) AS integer) end)-max(11) from t1)*d)),t1.d) FROM t1 WHERE NOT (19-c*coalesce((select max(case (select count(distinct t1.f) from t1) | t1.a when case a when (abs(case when not c+t1.d>=e then 17*t1.e+a when not exists(select 1 from t1 where 11>b) then c else a end)/abs(t1.e))+t1.f*13 then 11 else t1.f end then 19 else d end-b) from t1 where (d) not between f and e),t1.d)= -c)} +} {11} +do_test randexpr-2.2004 { + db eval {SELECT 11+t1.b*~c*17-13-a+t1.d | t1.f+t1.b*coalesce((select 17 from t1 where t1.e in (select (select cast(avg(case case e when (t1.d) then 17 else (abs((abs(case when d19 then 19 else a end)/abs(f)))/abs((t1.e))) end when b then (11) else f end+17) AS integer) from t1) from t1 union select t1.c from t1)),(17)) FROM t1 WHERE e=11} +} {} +do_test randexpr-2.2005 { + db eval {SELECT 11+t1.b*~c*17-13-a+t1.d | t1.f+t1.b*coalesce((select 17 from t1 where t1.e in (select (select cast(avg(case case e when (t1.d) then 17 else (abs((abs(case when d19 then 19 else a end)/abs(f)))/abs((t1.e))) end when b then (11) else f end+17) AS integer) from t1) from t1 union select t1.c from t1)),(17)) FROM t1 WHERE NOT (e=11)} +} {-1019998} +do_test randexpr-2.2006 { + db eval {SELECT 11+t1.b*~c*17-13-a+t1.d & t1.f+t1.b*coalesce((select 17 from t1 where t1.e in (select (select cast(avg(case case e when (t1.d) then 17 else (abs((abs(case when d19 then 19 else a end)/abs(f)))/abs((t1.e))) end when b then (11) else f end+17) AS integer) from t1) from t1 union select t1.c from t1)),(17)) FROM t1 WHERE NOT (e=11)} +} {896} +do_test randexpr-2.2007 { + db eval {SELECT e*~~(coalesce((select +case when not exists(select 1 from t1 where 13*coalesce((select max(coalesce((select max(11) from t1 where not exists(select 1 from t1 where (select -count(distinct 11) | min(11) from t1)>case b when b then c else d end)),13)) from t1 where -c<>d),13)<>t1.f and 13 between 13 and 19) then b-t1.e+e else (t1.f) end from t1 where ((not not e>t1.c and c not between a and e))),t1.d)) FROM t1 WHERE exists(select 1 from t1 where case when case when e -b)} +} {200000} +do_test randexpr-2.2008 { + db eval {SELECT e*~~(coalesce((select +case when not exists(select 1 from t1 where 13*coalesce((select max(coalesce((select max(11) from t1 where not exists(select 1 from t1 where (select -count(distinct 11) | min(11) from t1)>case b when b then c else d end)),13)) from t1 where -c<>d),13)<>t1.f and 13 between 13 and 19) then b-t1.e+e else (t1.f) end from t1 where ((not not e>t1.c and c not between a and e))),t1.d)) FROM t1 WHERE NOT (exists(select 1 from t1 where case when case when e -b))} +} {} +do_test randexpr-2.2009 { + db eval {SELECT e*~~(coalesce((select +case when not exists(select 1 from t1 where 13*coalesce((select max(coalesce((select max(11) from t1 where not exists(select 1 from t1 where (select -count(distinct 11) & min(11) from t1)>case b when b then c else d end)),13)) from t1 where -c<>d),13)<>t1.f and 13 between 13 and 19) then b-t1.e+e else (t1.f) end from t1 where ((not not e>t1.c and c not between a and e))),t1.d)) FROM t1 WHERE exists(select 1 from t1 where case when case when e -b)} +} {200000} +do_test randexpr-2.2010 { + db eval {SELECT (case t1.b-coalesce((select max(t1.f) from t1 where +t1.c=e or coalesce((select max(t1.a) from t1 where exists(select 1 from t1 where ((13-(select +cast(avg( -t1.b) AS integer) from t1) in (case f when (19) then t1.f else t1.f end,11,t1.e))))),(t1.a)+t1.e) not in (t1.f,t1.a,b) and t1.e not in (11,t1.b,t1.b)),d) when 19 then t1.e else c end-t1.e*t1.f) FROM t1 WHERE t1.ecoalesce((select max(f) from t1 where 19>=b),19) then f else t1.e end-f)/abs(t1.a))-11 else t1.e end when exists(select 1 from t1 where not exists(select 1 from t1 where ((c)) not in (b,a,e))) then t1.c else ((11)) end FROM t1 WHERE (not 13 not in (17,a,e))} +} {} +do_test randexpr-2.2013 { + db eval {SELECT t1.a+e-case when 19<+17 then case when 19 not between t1.e and t1.e then (abs(case when e+17*(select count(distinct (abs(+17)/abs(t1.c))) from t1)<>coalesce((select max(f) from t1 where 19>=b),19) then f else t1.e end-f)/abs(t1.a))-11 else t1.e end when exists(select 1 from t1 where not exists(select 1 from t1 where ((c)) not in (b,a,e))) then t1.c else ((11)) end FROM t1 WHERE NOT ((not 13 not in (17,a,e)))} +} {589} +do_test randexpr-2.2014 { + db eval {SELECT case when not exists(select 1 from t1 where case when -~(19)=t1.c then t1.f*~case when t1.f<=(select max(t1.c) from t1) then e when (c<>13) then t1.a else (b) end when t1.b between 19 and 17 then 17 else e end-e+t1.a>e or -19 in (select max(13) from t1 union select min( -19) from t1)) then t1.b when -11>=a then ~b else 19 end FROM t1 WHERE (c not between coalesce((select max(c) from t1 where (not t1.c<>t1.a)), -(abs(case when t1.e<=t1.c then t1.d when exists(select 1 from t1 where 17 in (select case when coalesce((select c from t1 where 17-t1.a-coalesce((select 17 from t1 where t1.f in (t1.b,19,t1.c)),17) not between e and 13),t1.b) not in (e,13,t1.a) then t1.c else b end | f from t1 union select t1.f from t1)) then t1.f else 11 end)/abs(t1.a))) and t1.e)} +} {} +do_test randexpr-2.2015 { + db eval {SELECT case when not exists(select 1 from t1 where case when -~(19)=t1.c then t1.f*~case when t1.f<=(select max(t1.c) from t1) then e when (c<>13) then t1.a else (b) end when t1.b between 19 and 17 then 17 else e end-e+t1.a>e or -19 in (select max(13) from t1 union select min( -19) from t1)) then t1.b when -11>=a then ~b else 19 end FROM t1 WHERE NOT ((c not between coalesce((select max(c) from t1 where (not t1.c<>t1.a)), -(abs(case when t1.e<=t1.c then t1.d when exists(select 1 from t1 where 17 in (select case when coalesce((select c from t1 where 17-t1.a-coalesce((select 17 from t1 where t1.f in (t1.b,19,t1.c)),17) not between e and 13),t1.b) not in (e,13,t1.a) then t1.c else b end | f from t1 union select t1.f from t1)) then t1.f else 11 end)/abs(t1.a))) and t1.e))} +} {19} +do_test randexpr-2.2016 { + db eval {SELECT case t1.c | t1.b when t1.f-c then case when c=11) or t1.c<=t1.e) then + - -b+11 else 13 end from t1 union select (t1.c) from t1) then 17 else 11 end else t1.a end FROM t1 WHERE t1.f | 13+coalesce((select max(11) from t1 where e>=(select ~case cast(avg(19*f+(c)) AS integer) when (min(c))-min(t1.a) then cast(avg(13) AS integer) else count(distinct e) end from t1)),t1.f)>=coalesce((select c from t1 where (exists(select 1 from t1 where t1.f>=f and (t1.d)<>t1.a))),c) or not exists(select 1 from t1 where not 11>=t1.d) or (b between c and 11 and 11< -t1.b and t1.e>=t1.b) or t1.c>e} +} {100} +do_test randexpr-2.2017 { + db eval {SELECT case t1.c | t1.b when t1.f-c then case when c=11) or t1.c<=t1.e) then + - -b+11 else 13 end from t1 union select (t1.c) from t1) then 17 else 11 end else t1.a end FROM t1 WHERE NOT (t1.f | 13+coalesce((select max(11) from t1 where e>=(select ~case cast(avg(19*f+(c)) AS integer) when (min(c))-min(t1.a) then cast(avg(13) AS integer) else count(distinct e) end from t1)),t1.f)>=coalesce((select c from t1 where (exists(select 1 from t1 where t1.f>=f and (t1.d)<>t1.a))),c) or not exists(select 1 from t1 where not 11>=t1.d) or (b between c and 11 and 11< -t1.b and t1.e>=t1.b) or t1.c>e)} +} {} +do_test randexpr-2.2018 { + db eval {SELECT case t1.c & t1.b when t1.f-c then case when c=11) or t1.c<=t1.e) then + - -b+11 else 13 end from t1 union select (t1.c) from t1) then 17 else 11 end else t1.a end FROM t1 WHERE t1.f | 13+coalesce((select max(11) from t1 where e>=(select ~case cast(avg(19*f+(c)) AS integer) when (min(c))-min(t1.a) then cast(avg(13) AS integer) else count(distinct e) end from t1)),t1.f)>=coalesce((select c from t1 where (exists(select 1 from t1 where t1.f>=f and (t1.d)<>t1.a))),c) or not exists(select 1 from t1 where not 11>=t1.d) or (b between c and 11 and 11< -t1.b and t1.e>=t1.b) or t1.c>e} +} {100} +do_test randexpr-2.2019 { + db eval {SELECT coalesce((select 19 from t1 where a<=case (abs(e)/abs(case b+f when b then t1.e else e end)) when + -t1.b+coalesce((select max(t1.f) from t1 where (19<=+e) and (c*b)>= -t1.e and (c>=c)),11+(e)+a)-t1.b then 17 else 17 end-t1.e),a) FROM t1 WHERE +d*t1.f+c+t1.c*13<>t1.e} +} {100} +do_test randexpr-2.2020 { + db eval {SELECT coalesce((select 19 from t1 where a<=case (abs(e)/abs(case b+f when b then t1.e else e end)) when + -t1.b+coalesce((select max(t1.f) from t1 where (19<=+e) and (c*b)>= -t1.e and (c>=c)),11+(e)+a)-t1.b then 17 else 17 end-t1.e),a) FROM t1 WHERE NOT (+d*t1.f+c+t1.c*13<>t1.e)} +} {} +do_test randexpr-2.2021 { + db eval {SELECT (abs(t1.e)/abs(coalesce((select +t1.a*c from t1 where (abs(e)/abs(d)) in (select +~count(*)-min(t1.d) from t1 union select abs(abs(cast(avg(t1.b) AS integer))+cast(avg(b) AS integer)) from t1)),d))) FROM t1 WHERE not b not between (select max(13) from t1) and 13} +} {} +do_test randexpr-2.2022 { + db eval {SELECT (abs(t1.e)/abs(coalesce((select +t1.a*c from t1 where (abs(e)/abs(d)) in (select +~count(*)-min(t1.d) from t1 union select abs(abs(cast(avg(t1.b) AS integer))+cast(avg(b) AS integer)) from t1)),d))) FROM t1 WHERE NOT (not b not between (select max(13) from t1) and 13)} +} {1} +do_test randexpr-2.2023 { + db eval {SELECT +(select +~(count(distinct (abs((abs(coalesce((select max(t1.c) from t1 where -e in (select t1.e from t1 union select (e) from t1)),c)-11)/abs(19))*t1.c)/abs(19))))*count(distinct t1.a)*+count(distinct a)*count(distinct t1.d) | count(*)-max(11)+cast(avg(t1.b) AS integer)*min(t1.a) from t1)+19+t1.c*19+~coalesce((select e from t1 where 13 in (select count(distinct 17) from t1 union select count(distinct 11) from t1) or t1.f<>c),17) FROM t1 WHERE exists(select 1 from t1 where coalesce((select t1.f from t1 where t1.a in (case when exists(select 1 from t1 where b*t1.e in (select (t1.a) from t1 union select (case -13 when f then t1.b else t1.a end) from t1)) then t1.d else 17 end,d,11)),c) not in (17,19,t1.b)) or (b) in (select abs(~~abs(count(*)) | - -min(c)-min(11)+count(*) | max(a) | count(*)-count(distinct 11)) from t1 union select max(t1.f) from t1) or t1.b>=19} +} {5216} +do_test randexpr-2.2024 { + db eval {SELECT +(select +~(count(distinct (abs((abs(coalesce((select max(t1.c) from t1 where -e in (select t1.e from t1 union select (e) from t1)),c)-11)/abs(19))*t1.c)/abs(19))))*count(distinct t1.a)*+count(distinct a)*count(distinct t1.d) | count(*)-max(11)+cast(avg(t1.b) AS integer)*min(t1.a) from t1)+19+t1.c*19+~coalesce((select e from t1 where 13 in (select count(distinct 17) from t1 union select count(distinct 11) from t1) or t1.f<>c),17) FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select t1.f from t1 where t1.a in (case when exists(select 1 from t1 where b*t1.e in (select (t1.a) from t1 union select (case -13 when f then t1.b else t1.a end) from t1)) then t1.d else 17 end,d,11)),c) not in (17,19,t1.b)) or (b) in (select abs(~~abs(count(*)) | - -min(c)-min(11)+count(*) | max(a) | count(*)-count(distinct 11)) from t1 union select max(t1.f) from t1) or t1.b>=19)} +} {} +do_test randexpr-2.2025 { + db eval {SELECT +(select +~(count(distinct (abs((abs(coalesce((select max(t1.c) from t1 where -e in (select t1.e from t1 union select (e) from t1)),c)-11)/abs(19))*t1.c)/abs(19))))*count(distinct t1.a)*+count(distinct a)*count(distinct t1.d) & count(*)-max(11)+cast(avg(t1.b) AS integer)*min(t1.a) from t1)+19+t1.c*19+~coalesce((select e from t1 where 13 in (select count(distinct 17) from t1 union select count(distinct 11) from t1) or t1.f<>c),17) FROM t1 WHERE exists(select 1 from t1 where coalesce((select t1.f from t1 where t1.a in (case when exists(select 1 from t1 where b*t1.e in (select (t1.a) from t1 union select (case -13 when f then t1.b else t1.a end) from t1)) then t1.d else 17 end,d,11)),c) not in (17,19,t1.b)) or (b) in (select abs(~~abs(count(*)) | - -min(c)-min(11)+count(*) | max(a) | count(*)-count(distinct 11)) from t1 union select max(t1.f) from t1) or t1.b>=19} +} {25208} +do_test randexpr-2.2026 { + db eval {SELECT (abs(case t1.c when ~coalesce((select max(case coalesce((select max(b) from t1 where not aa),e) then 17 else a end)/abs(19)) FROM t1 WHERE d not in (d,d+case coalesce((select t1.e from t1 where (case when 17*case case f-+t1.c+coalesce((select t1.c from t1 where t1.df)),d) when t1.e then (t1.c) else -e end,t1.f)} +} {} +do_test randexpr-2.2027 { + db eval {SELECT (abs(case t1.c when ~coalesce((select max(case coalesce((select max(b) from t1 where not aa),e) then 17 else a end)/abs(19)) FROM t1 WHERE NOT (d not in (d,d+case coalesce((select t1.e from t1 where (case when 17*case case f-+t1.c+coalesce((select t1.c from t1 where t1.df)),d) when t1.e then (t1.c) else -e end,t1.f))} +} {5} +do_test randexpr-2.2028 { + db eval {SELECT case 13 when 13 then case when 11 between case case when not 17 not between f-t1.e and (abs(19)/abs(((t1.b))))*19 then t1.a when exists(select 1 from t1 where t1.e not between d and 13) then t1.c else -e end when t1.e then t1.c else e end and 17 then 19 when not exists(select 1 from t1 where 11=f) and exists(select 1 from t1 where d<>t1.a) or t1.f>=17 then a else t1.e end else 19 end*11 FROM t1 WHERE case 17 when t1.f then 11 else c end+d=t1.f} +} {} +do_test randexpr-2.2029 { + db eval {SELECT case 13 when 13 then case when 11 between case case when not 17 not between f-t1.e and (abs(19)/abs(((t1.b))))*19 then t1.a when exists(select 1 from t1 where t1.e not between d and 13) then t1.c else -e end when t1.e then t1.c else e end and 17 then 19 when not exists(select 1 from t1 where 11=f) and exists(select 1 from t1 where d<>t1.a) or t1.f>=17 then a else t1.e end else 19 end*11 FROM t1 WHERE NOT (case 17 when t1.f then 11 else c end+d=t1.f)} +} {1100} +do_test randexpr-2.2030 { + db eval {SELECT coalesce((select max(b-case when exists(select 1 from t1 where case when t1.c>t1.b then t1.c*19 else coalesce((select max((abs(t1.a)/abs(~(select +max(t1.c)*max(a)*cast(avg(t1.d) AS integer) from t1)+case when e=t1.c or t1.c between e and b then +a else 13 end))) from t1 where 17=b),t1.a) end not between f and t1.c) then c else e end+ - -d-17) from t1 where t1.e=(select cast(avg(d) AS integer) from t1)} +} {} +do_test randexpr-2.2031 { + db eval {SELECT coalesce((select max(b-case when exists(select 1 from t1 where case when t1.c>t1.b then t1.c*19 else coalesce((select max((abs(t1.a)/abs(~(select +max(t1.c)*max(a)*cast(avg(t1.d) AS integer) from t1)+case when e=t1.c or t1.c between e and b then +a else 13 end))) from t1 where 17=b),t1.a) end not between f and t1.c) then c else e end+ - -d-17) from t1 where t1.e=(select cast(avg(d) AS integer) from t1))} +} {17} +do_test randexpr-2.2032 { + db eval {SELECT case when -13 in (select +case when case when exists(select 1 from t1 where ~coalesce((select t1.f from t1 where exists(select 1 from t1 where t1.a not between t1.b and -t1.e)),t1.c)+c | b not between f and t1.b) then -11-19 else t1.d end in (select ~abs(max(19))+cast(avg(e) AS integer)-max(13)-count(*) from t1 union select min(f) from t1) then t1.f else b end+t1.e from t1 union select t1.f from t1) then b when e(select count(distinct d) from t1)) then t1.a when +(select cast(avg(e-19*~case 19 when t1.f then (t1.d) else t1.e end*t1.d*c) AS integer) from t1) in (e,t1.c,t1.e) then 13 else a end from t1 where d not between t1.b and f),a)) from t1 union select min((t1.b)) from t1) or (t1.e<=13)} +} {} +do_test randexpr-2.2033 { + db eval {SELECT case when -13 in (select +case when case when exists(select 1 from t1 where ~coalesce((select t1.f from t1 where exists(select 1 from t1 where t1.a not between t1.b and -t1.e)),t1.c)+c | b not between f and t1.b) then -11-19 else t1.d end in (select ~abs(max(19))+cast(avg(e) AS integer)-max(13)-count(*) from t1 union select min(f) from t1) then t1.f else b end+t1.e from t1 union select t1.f from t1) then b when e(select count(distinct d) from t1)) then t1.a when +(select cast(avg(e-19*~case 19 when t1.f then (t1.d) else t1.e end*t1.d*c) AS integer) from t1) in (e,t1.c,t1.e) then 13 else a end from t1 where d not between t1.b and f),a)) from t1 union select min((t1.b)) from t1) or (t1.e<=13))} +} {411} +do_test randexpr-2.2034 { + db eval {SELECT case when -13 in (select +case when case when exists(select 1 from t1 where ~coalesce((select t1.f from t1 where exists(select 1 from t1 where t1.a not between t1.b and -t1.e)),t1.c)+c & b not between f and t1.b) then -11-19 else t1.d end in (select ~abs(max(19))+cast(avg(e) AS integer)-max(13)-count(*) from t1 union select min(f) from t1) then t1.f else b end+t1.e from t1 union select t1.f from t1) then b when e(select count(distinct d) from t1)) then t1.a when +(select cast(avg(e-19*~case 19 when t1.f then (t1.d) else t1.e end*t1.d*c) AS integer) from t1) in (e,t1.c,t1.e) then 13 else a end from t1 where d not between t1.b and f),a)) from t1 union select min((t1.b)) from t1) or (t1.e<=13))} +} {411} +do_test randexpr-2.2035 { + db eval {SELECT (+coalesce((select max(c) from t1 where case when ( -t1.f between t1.a | -a*(abs(11 | e+case when not exists(select 1 from t1 where t1.b<>f or a=t1.a) then 17*(a) else 17 end*c)/abs(c))-d+f* -e-t1.a and b) then -11-a else t1.a end*19+b | t1.a<=t1.e),t1.b)) FROM t1 WHERE t1.e between -case when e not in (t1.e,case when d+t1.c-b-t1.b+case when -ef or a=t1.a) then 17*(a) else 17 end*c)/abs(c))-d+f* -e-t1.a and b) then -11-a else t1.a end*19+b | t1.a<=t1.e),t1.b)) FROM t1 WHERE NOT (t1.e between -case when e not in (t1.e,case when d+t1.c-b-t1.b+case when -ef or a=t1.a) then 17*(a) else 17 end*c)/abs(c))-d+f* -e-t1.a and b) then -11-a else t1.a end*19+b & t1.a<=t1.e),t1.b)) FROM t1 WHERE NOT (t1.e between -case when e not in (t1.e,case when d+t1.c-b-t1.b+case when -ee then t1.d else a end+f)-case (+min(t1.f)*min(e)+cast(avg(c) AS integer))*count(*) when - -((count(distinct f))) then max(a) else count(*) end | -cast(avg(11) AS integer)*count(*))-count(*)*( -max(f)) from t1)} +} {} +do_test randexpr-2.2039 { + db eval {SELECT (select +~~ -(count(*))+max((select ~count(*)+count(distinct d)*~cast(avg(19) AS integer)+case count(*)- -abs(abs(~abs(++abs(cast(avg(t1.c) AS integer)))+count(distinct e)+count(*)))+(min(19) | ( -cast(avg(b) AS integer) | - -(count(distinct t1.f)))) when -count(*) then max( -b) else max((t1.d)) end from t1)) from t1) FROM t1 WHERE NOT ((abs(c)/abs((select (abs(count(*))) from t1))) not between t1.b and (select abs(count(*)* -~min(~e+case when t1.a+(a)>e then t1.d else a end+f)-case (+min(t1.f)*min(e)+cast(avg(c) AS integer))*count(*) when - -((count(distinct f))) then max(a) else count(*) end | -cast(avg(11) AS integer)*count(*))-count(*)*( -max(f)) from t1))} +} {377} +do_test randexpr-2.2040 { + db eval {SELECT (select +~~ -(count(*))+max((select ~count(*)+count(distinct d)*~cast(avg(19) AS integer)+case count(*)- -abs(abs(~abs(++abs(cast(avg(t1.c) AS integer)))+count(distinct e)+count(*)))+(min(19) & ( -cast(avg(b) AS integer) & - -(count(distinct t1.f)))) when -count(*) then max( -b) else max((t1.d)) end from t1)) from t1) FROM t1 WHERE NOT ((abs(c)/abs((select (abs(count(*))) from t1))) not between t1.b and (select abs(count(*)* -~min(~e+case when t1.a+(a)>e then t1.d else a end+f)-case (+min(t1.f)*min(e)+cast(avg(c) AS integer))*count(*) when - -((count(distinct f))) then max(a) else count(*) end | -cast(avg(11) AS integer)*count(*))-count(*)*( -max(f)) from t1))} +} {377} +do_test randexpr-2.2041 { + db eval {SELECT case when ((select abs((count(*)))+min(case 17 when b then 13 | 11+c | f else 19 end) | +count(*)- - -max(t1.d) from t1) not between 19-case when t1.c not between ~e and (e) then t1.d else t1.c end and t1.e) then t1.d when t1.d in (select -~count(distinct t1.f)*(min(t1.b)) from t1 union select (cast(avg(17) AS integer)) from t1) then d else t1.b end FROM t1 WHERE not exists(select 1 from t1 where d in (coalesce((select max((select abs(~min(f))++~count(distinct t1.a)+cast(avg(t1.b) AS integer)*cast(avg(13) AS integer) from t1)) from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where (exists(select 1 from t1 where 11=13 then ~19*13 | t1.c+t1.e when c between t1.d and a then t1.b else t1.d end)-13,17,11))} +} {400} +do_test randexpr-2.2042 { + db eval {SELECT case when ((select abs((count(*)))+min(case 17 when b then 13 | 11+c | f else 19 end) | +count(*)- - -max(t1.d) from t1) not between 19-case when t1.c not between ~e and (e) then t1.d else t1.c end and t1.e) then t1.d when t1.d in (select -~count(distinct t1.f)*(min(t1.b)) from t1 union select (cast(avg(17) AS integer)) from t1) then d else t1.b end FROM t1 WHERE NOT (not exists(select 1 from t1 where d in (coalesce((select max((select abs(~min(f))++~count(distinct t1.a)+cast(avg(t1.b) AS integer)*cast(avg(13) AS integer) from t1)) from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where (exists(select 1 from t1 where 11=13 then ~19*13 | t1.c+t1.e when c between t1.d and a then t1.b else t1.d end)-13,17,11)))} +} {} +do_test randexpr-2.2043 { + db eval {SELECT case when ((select abs((count(*)))+min(case 17 when b then 13 & 11+c & f else 19 end) & +count(*)- - -max(t1.d) from t1) not between 19-case when t1.c not between ~e and (e) then t1.d else t1.c end and t1.e) then t1.d when t1.d in (select -~count(distinct t1.f)*(min(t1.b)) from t1 union select (cast(avg(17) AS integer)) from t1) then d else t1.b end FROM t1 WHERE not exists(select 1 from t1 where d in (coalesce((select max((select abs(~min(f))++~count(distinct t1.a)+cast(avg(t1.b) AS integer)*cast(avg(13) AS integer) from t1)) from t1 where exists(select 1 from t1 where not not exists(select 1 from t1 where (exists(select 1 from t1 where 11=13 then ~19*13 | t1.c+t1.e when c between t1.d and a then t1.b else t1.d end)-13,17,11))} +} {400} +do_test randexpr-2.2044 { + db eval {SELECT case when not exists(select 1 from t1 where e in (select +(count(distinct (abs(case when ((abs(coalesce((select coalesce((select case when c>f and a in (19, -e,t1.c) then +t1.a else t1.e end from t1 where ct1.f),(select case abs(count(distinct t1.e)-cast(avg(t1.d) AS integer)*cast(avg(t1.b) AS integer)) when min(19) then count(*) else min(c) end+count(distinct t1.c) from t1))+t1.b,t1.d, -d)} +} {} +do_test randexpr-2.2045 { + db eval {SELECT case when not exists(select 1 from t1 where e in (select +(count(distinct (abs(case when ((abs(coalesce((select coalesce((select case when c>f and a in (19, -e,t1.c) then +t1.a else t1.e end from t1 where ct1.f),(select case abs(count(distinct t1.e)-cast(avg(t1.d) AS integer)*cast(avg(t1.b) AS integer)) when min(19) then count(*) else min(c) end+count(distinct t1.c) from t1))+t1.b,t1.d, -d))} +} {120000} +do_test randexpr-2.2046 { + db eval {SELECT -case when -b=t1.c then t1.a when (select min(t1.b) from t1)<=d+coalesce((select max(11+a) from t1 where (not exists(select 1 from t1 where c | -((case case when (t1.f between a and t1.b) then b else c end-t1.c when 19 then t1.c else f end+t1.c)+t1.b | a)-t1.c-(c)<=19))),t1.c) then e else -t1.d end-(17) FROM t1 WHERE (t1.b | case t1.b when ((t1.e)) then (abs(19)/abs(t1.a))-coalesce((select max(t1.e*case b when a then 11 else t1.a end) from t1 where +~case when 13=17 and t1.e+11 in (select t1.f from t1 union select t1.d from t1) then t1.b when (b<17 and a>= -17) then f else -t1.e end+(17)<=13),d) else b end | b between t1.d and t1.f)} +} {} +do_test randexpr-2.2047 { + db eval {SELECT -case when -b=t1.c then t1.a when (select min(t1.b) from t1)<=d+coalesce((select max(11+a) from t1 where (not exists(select 1 from t1 where c | -((case case when (t1.f between a and t1.b) then b else c end-t1.c when 19 then t1.c else f end+t1.c)+t1.b | a)-t1.c-(c)<=19))),t1.c) then e else -t1.d end-(17) FROM t1 WHERE NOT ((t1.b | case t1.b when ((t1.e)) then (abs(19)/abs(t1.a))-coalesce((select max(t1.e*case b when a then 11 else t1.a end) from t1 where +~case when 13=17 and t1.e+11 in (select t1.f from t1 union select t1.d from t1) then t1.b when (b<17 and a>= -17) then f else -t1.e end+(17)<=13),d) else b end | b between t1.d and t1.f))} +} {-517} +do_test randexpr-2.2048 { + db eval {SELECT -case when -b=t1.c then t1.a when (select min(t1.b) from t1)<=d+coalesce((select max(11+a) from t1 where (not exists(select 1 from t1 where c & -((case case when (t1.f between a and t1.b) then b else c end-t1.c when 19 then t1.c else f end+t1.c)+t1.b & a)-t1.c-(c)<=19))),t1.c) then e else -t1.d end-(17) FROM t1 WHERE NOT ((t1.b | case t1.b when ((t1.e)) then (abs(19)/abs(t1.a))-coalesce((select max(t1.e*case b when a then 11 else t1.a end) from t1 where +~case when 13=17 and t1.e+11 in (select t1.f from t1 union select t1.d from t1) then t1.b when (b<17 and a>= -17) then f else -t1.e end+(17)<=13),d) else b end | b between t1.d and t1.f))} +} {-517} +do_test randexpr-2.2049 { + db eval {SELECT case when not c=t1.f | t1.d),19),t1.a) then (t1.d) when -a<=( -t1.a) then a else f end*a,13,19)) or e=17),a)*17 FROM t1 WHERE (select case min(+19) when abs((max(17)* -min(a*(abs(case e when t1.b then t1.f else -t1.c end*f)/abs(t1.d))*e)-count(*) | max(19))) then - -case count(distinct 11) when min(11) then max(19) else min(13) end-( -count(distinct 13)) else -(count(distinct b)) end*cast(avg(17) AS integer)-max(e) from t1) between t1.d and coalesce((select max(13) from t1 where not 17>a-f-e),13)} +} {} +do_test randexpr-2.2052 { + db eval {SELECT +11+~coalesce((select -19 from t1 where exists(select 1 from t1 where f*t1.e not in ( -f*~t1.a-f*case when t1.f in ((e),coalesce((select b from t1 where b>=t1.f | t1.d),19),t1.a) then (t1.d) when -a<=( -t1.a) then a else f end*a,13,19)) or e=17),a)*17 FROM t1 WHERE NOT ((select case min(+19) when abs((max(17)* -min(a*(abs(case e when t1.b then t1.f else -t1.c end*f)/abs(t1.d))*e)-count(*) | max(19))) then - -case count(distinct 11) when min(11) then max(19) else min(13) end-( -count(distinct 13)) else -(count(distinct b)) end*cast(avg(17) AS integer)-max(e) from t1) between t1.d and coalesce((select max(13) from t1 where not 17>a-f-e),13))} +} {317} +do_test randexpr-2.2053 { + db eval {SELECT +11+~coalesce((select -19 from t1 where exists(select 1 from t1 where f*t1.e not in ( -f*~t1.a-f*case when t1.f in ((e),coalesce((select b from t1 where b>=t1.f & t1.d),19),t1.a) then (t1.d) when -a<=( -t1.a) then a else f end*a,13,19)) or e=17),a)*17 FROM t1 WHERE NOT ((select case min(+19) when abs((max(17)* -min(a*(abs(case e when t1.b then t1.f else -t1.c end*f)/abs(t1.d))*e)-count(*) | max(19))) then - -case count(distinct 11) when min(11) then max(19) else min(13) end-( -count(distinct 13)) else -(count(distinct b)) end*cast(avg(17) AS integer)-max(e) from t1) between t1.d and coalesce((select max(13) from t1 where not 17>a-f-e),13))} +} {317} +do_test randexpr-2.2054 { + db eval {SELECT coalesce((select 11 from t1 where (b-case (select count(distinct t1.f*e) from t1) when t1.f | 11 | 11*coalesce((select 19 from t1 where (~coalesce((select f from t1 where (t1.c>17)),a)+t1.c not between f and t1.e or 19>=c)),(t1.d)) then a else t1.f end>=f and exists(select 1 from t1 where 13<>c) or - -t1.f17)),a)+t1.c not between f and t1.e or 19>=c)),(t1.d)) then a else t1.f end>=f and exists(select 1 from t1 where 13<>c) or - -t1.f17)),a)+t1.c not between f and t1.e or 19>=c)),(t1.d)) then a else t1.f end>=f and exists(select 1 from t1 where 13<>c) or - -t1.fcoalesce((select max(coalesce((select t1.e from t1 where not (abs(a+t1.e*c | case when t1.b in (select -max(t1.b)*cast(avg(19) AS integer) from t1 union select -max(13) from t1) then t1.f else 19 end-f+(19)+19)/abs(t1.e)) in (d,13,e) or t1.e<=t1.e),t1.b-17)) from t1 where -11<>17 or e in (select max(19) from t1 union select (cast(avg(f) AS integer)) from t1)),a)),17))/abs(t1.e)) FROM t1 WHERE t1.e<>13 | (t1.f)+c-((13))-~13 | (abs(e)/abs(coalesce((select max(t1.c) from t1 where (d)<=t1.d),case when (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(t1.d))>coalesce((select max(a) from t1 where t1.c not between t1.f and t1.f and f not in (t1.f, -t1.c,13)),t1.c)))) then c else 19 end))) | t1.a*11* -e*t1.c or not exists(select 1 from t1 where f>c)} +} {0} +do_test randexpr-2.2058 { + db eval {SELECT (abs(coalesce((select max(t1.e) from t1 where c>coalesce((select max(coalesce((select t1.e from t1 where not (abs(a+t1.e*c | case when t1.b in (select -max(t1.b)*cast(avg(19) AS integer) from t1 union select -max(13) from t1) then t1.f else 19 end-f+(19)+19)/abs(t1.e)) in (d,13,e) or t1.e<=t1.e),t1.b-17)) from t1 where -11<>17 or e in (select max(19) from t1 union select (cast(avg(f) AS integer)) from t1)),a)),17))/abs(t1.e)) FROM t1 WHERE NOT (t1.e<>13 | (t1.f)+c-((13))-~13 | (abs(e)/abs(coalesce((select max(t1.c) from t1 where (d)<=t1.d),case when (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(t1.d))>coalesce((select max(a) from t1 where t1.c not between t1.f and t1.f and f not in (t1.f, -t1.c,13)),t1.c)))) then c else 19 end))) | t1.a*11* -e*t1.c or not exists(select 1 from t1 where f>c))} +} {} +do_test randexpr-2.2059 { + db eval {SELECT (abs(coalesce((select max(t1.e) from t1 where c>coalesce((select max(coalesce((select t1.e from t1 where not (abs(a+t1.e*c & case when t1.b in (select -max(t1.b)*cast(avg(19) AS integer) from t1 union select -max(13) from t1) then t1.f else 19 end-f+(19)+19)/abs(t1.e)) in (d,13,e) or t1.e<=t1.e),t1.b-17)) from t1 where -11<>17 or e in (select max(19) from t1 union select (cast(avg(f) AS integer)) from t1)),a)),17))/abs(t1.e)) FROM t1 WHERE t1.e<>13 | (t1.f)+c-((13))-~13 | (abs(e)/abs(coalesce((select max(t1.c) from t1 where (d)<=t1.d),case when (exists(select 1 from t1 where not exists(select 1 from t1 where (abs(17)/abs(t1.d))>coalesce((select max(a) from t1 where t1.c not between t1.f and t1.f and f not in (t1.f, -t1.c,13)),t1.c)))) then c else 19 end))) | t1.a*11* -e*t1.c or not exists(select 1 from t1 where f>c)} +} {0} +do_test randexpr-2.2060 { + db eval {SELECT case t1.e when a then case when not exists(select 1 from t1 where (abs(~coalesce((select c from t1 where (case when not case when a between t1.b and t1.a then t1.c when -17 not in (11,t1.d,11) then a else t1.a end in (select count(distinct t1.a)+count(distinct t1.a) from t1 union select count(*) from t1) then t1.c when t1.b<(11) then f else a end>=11 and (t1.f)=11)),+11))/abs(e)) not between 17 and -t1.a) or c not between 19 and t1.b then t1.c when t1.e=11 and (t1.f)=11)),+11))/abs(e)) not between 17 and -t1.a) or c not between 19 and t1.b then t1.c when t1.e=11 and (t1.f)=11)),+11))/abs(e)) not between 17 and -t1.a) or c not between 19 and t1.b then t1.c when t1.eb),~case when b between 17 and e | coalesce((select max(a) from t1 where (f in (t1.b,f,a))),13) then f when -d<=d then t1.e else e end+13)+13 then d else d end+t1.f=d),b)+b FROM t1 WHERE b=b} +} {400} +do_test randexpr-2.2064 { + db eval {SELECT ~~coalesce((select t1.a from t1 where case f*+e when ~11-coalesce((select max(t1.f) from t1 where t1.f>b),~case when b between 17 and e | coalesce((select max(a) from t1 where (f in (t1.b,f,a))),13) then f when -d<=d then t1.e else e end+13)+13 then d else d end+t1.f=d),b)+b FROM t1 WHERE NOT (b=b)} +} {} +do_test randexpr-2.2065 { + db eval {SELECT ~~coalesce((select t1.a from t1 where case f*+e when ~11-coalesce((select max(t1.f) from t1 where t1.f>b),~case when b between 17 and e & coalesce((select max(a) from t1 where (f in (t1.b,f,a))),13) then f when -d<=d then t1.e else e end+13)+13 then d else d end+t1.f=d),b)+b FROM t1 WHERE b=b} +} {400} +do_test randexpr-2.2066 { + db eval {SELECT e | t1.e*case d when t1.e then a else case when t1.a<= -~+e then b else 17-t1.e end*c*f+case when case when +c in (select +min(11) from t1 union select cast(avg(f) AS integer) from t1) and b between c and t1.f then 11+t1.a when f>=c then d else t1.c end=c then d else t1.c end=c then d else t1.c endt1.e), -t1.d) FROM t1 WHERE t1.b between coalesce((select (coalesce((select max(case when case when not exists(select 1 from t1 where (17) not in (13,case when 19 not in (19,t1.f,t1.e) and b>=t1.a then e when b<=t1.c then 11 else b end,11)) then c | t1.a else 17 end | 19 in (c,t1.b,d) then t1.a else t1.a end | t1.c) from t1 where not exists(select 1 from t1 where t1.a<=t1.e)),t1.c)) from t1 where t1.d<=t1.a),17)*c-11 and d} +} {} +do_test randexpr-2.2070 { + db eval {SELECT coalesce((select -(select min(f)-+min(f)*~case +cast(avg(t1.e) AS integer) when max(13)-abs( -max(a)) then +count(distinct a) | abs(max( -c+13)) else (count(*)) end from t1) from t1 where t1.a<>t1.e), -t1.d) FROM t1 WHERE NOT (t1.b between coalesce((select (coalesce((select max(case when case when not exists(select 1 from t1 where (17) not in (13,case when 19 not in (19,t1.f,t1.e) and b>=t1.a then e when b<=t1.c then 11 else b end,11)) then c | t1.a else 17 end | 19 in (c,t1.b,d) then t1.a else t1.a end | t1.c) from t1 where not exists(select 1 from t1 where t1.a<=t1.e)),t1.c)) from t1 where t1.d<=t1.a),17)*c-11 and d)} +} {-1800} +do_test randexpr-2.2071 { + db eval {SELECT coalesce((select -(select min(f)-+min(f)*~case +cast(avg(t1.e) AS integer) when max(13)-abs( -max(a)) then +count(distinct a) & abs(max( -c+13)) else (count(*)) end from t1) from t1 where t1.a<>t1.e), -t1.d) FROM t1 WHERE NOT (t1.b between coalesce((select (coalesce((select max(case when case when not exists(select 1 from t1 where (17) not in (13,case when 19 not in (19,t1.f,t1.e) and b>=t1.a then e when b<=t1.c then 11 else b end,11)) then c | t1.a else 17 end | 19 in (c,t1.b,d) then t1.a else t1.a end | t1.c) from t1 where not exists(select 1 from t1 where t1.a<=t1.e)),t1.c)) from t1 where t1.d<=t1.a),17)*c-11 and d)} +} {-1800} +do_test randexpr-2.2072 { + db eval {SELECT coalesce((select c from t1 where case when +case when not 11 | c not in (11,case when 13> -d then e when a>t1.c then 17 else t1.e end,t1.b) then t1.d when c<>t1.a then t1.b else 19 end-b>=17 or 11=19 and b<=e),d) FROM t1 WHERE (+a*t1.a+(19-(abs(case -c when d then (abs(f)/abs(case t1.a when 19 then b else +~( -case t1.f*t1.a | 17 when -t1.a then d else (t1.e) end*d)+t1.a-a end)) else 13 end)/abs(11))*t1.c)+17-d not in (11,a,b))} +} {300} +do_test randexpr-2.2073 { + db eval {SELECT coalesce((select c from t1 where case when +case when not 11 | c not in (11,case when 13> -d then e when a>t1.c then 17 else t1.e end,t1.b) then t1.d when c<>t1.a then t1.b else 19 end-b>=17 or 11=19 and b<=e),d) FROM t1 WHERE NOT ((+a*t1.a+(19-(abs(case -c when d then (abs(f)/abs(case t1.a when 19 then b else +~( -case t1.f*t1.a | 17 when -t1.a then d else (t1.e) end*d)+t1.a-a end)) else 13 end)/abs(11))*t1.c)+17-d not in (11,a,b)))} +} {} +do_test randexpr-2.2074 { + db eval {SELECT coalesce((select c from t1 where case when +case when not 11 & c not in (11,case when 13> -d then e when a>t1.c then 17 else t1.e end,t1.b) then t1.d when c<>t1.a then t1.b else 19 end-b>=17 or 11=19 and b<=e),d) FROM t1 WHERE (+a*t1.a+(19-(abs(case -c when d then (abs(f)/abs(case t1.a when 19 then b else +~( -case t1.f*t1.a | 17 when -t1.a then d else (t1.e) end*d)+t1.a-a end)) else 13 end)/abs(11))*t1.c)+17-d not in (11,a,b))} +} {300} +do_test randexpr-2.2075 { + db eval {SELECT case 17 when t1.c then t1.c*f | t1.b+t1.d+b+c-t1.e+t1.c+t1.c-t1.c*t1.f else case when t1.f+case when (abs(t1.a-coalesce((select a from t1 where (t1.c) in (t1.c,d,19)), -t1.a))/abs(f)) between t1.c and a then -(t1.b) else b end not in (11, -t1.d,t1.d) then t1.d else d end end FROM t1 WHERE ~17 between (select -count(distinct b+b)++max(t1.b)*(~(max(t1.d)))-abs(cast(avg(17) AS integer)*count(*))-max(f) | count(distinct t1.a)-count(distinct 13)-cast(avg(c) AS integer) from t1) and c-case when f<>t1.e then (abs(~(a)+e+t1.a | t1.a)/abs(t1.c)) else 13 end- -t1.e} +} {400} +do_test randexpr-2.2076 { + db eval {SELECT case 17 when t1.c then t1.c*f | t1.b+t1.d+b+c-t1.e+t1.c+t1.c-t1.c*t1.f else case when t1.f+case when (abs(t1.a-coalesce((select a from t1 where (t1.c) in (t1.c,d,19)), -t1.a))/abs(f)) between t1.c and a then -(t1.b) else b end not in (11, -t1.d,t1.d) then t1.d else d end end FROM t1 WHERE NOT (~17 between (select -count(distinct b+b)++max(t1.b)*(~(max(t1.d)))-abs(cast(avg(17) AS integer)*count(*))-max(f) | count(distinct t1.a)-count(distinct 13)-cast(avg(c) AS integer) from t1) and c-case when f<>t1.e then (abs(~(a)+e+t1.a | t1.a)/abs(t1.c)) else 13 end- -t1.e)} +} {} +do_test randexpr-2.2077 { + db eval {SELECT case 17 when t1.c then t1.c*f & t1.b+t1.d+b+c-t1.e+t1.c+t1.c-t1.c*t1.f else case when t1.f+case when (abs(t1.a-coalesce((select a from t1 where (t1.c) in (t1.c,d,19)), -t1.a))/abs(f)) between t1.c and a then -(t1.b) else b end not in (11, -t1.d,t1.d) then t1.d else d end end FROM t1 WHERE ~17 between (select -count(distinct b+b)++max(t1.b)*(~(max(t1.d)))-abs(cast(avg(17) AS integer)*count(*))-max(f) | count(distinct t1.a)-count(distinct 13)-cast(avg(c) AS integer) from t1) and c-case when f<>t1.e then (abs(~(a)+e+t1.a | t1.a)/abs(t1.c)) else 13 end- -t1.e} +} {400} +do_test randexpr-2.2078 { + db eval {SELECT (select cast(avg(coalesce((select max(coalesce((select e from t1 where not ((coalesce((select b from t1 where coalesce((select max(11) from t1 where exists(select 1 from t1 where (a in (select count(*)+max(((t1.a))) from t1 union select cast(avg(a) AS integer) from t1)))),b)<=19), -b))*f=t1.e) and 17<>11 and e in (t1.f,f,17)) or a not between -a and (17)),+~b)-17*b) from t1 where t1.b>=b),t1.a)) AS integer) from t1) FROM t1 WHERE f in (select cast(avg(t1.e-f-t1.e) AS integer)+min(t1.d) from t1 union select max(case b when 11 then case case when f in (a,a,f) then t1.b when (t1.f)>d then -19 else t1.a end when 11 then a else t1.e end else (t1.b) end*a)*cast(avg(a) AS integer)+ -+cast(avg(t1.e) AS integer)*case cast(avg(t1.e) AS integer) when (cast(avg( -t1.a) AS integer)) then count(*) else count(*) end*min(t1.d)*min(e) from t1) and (a between d and t1.f)} +} {} +do_test randexpr-2.2079 { + db eval {SELECT (select cast(avg(coalesce((select max(coalesce((select e from t1 where not ((coalesce((select b from t1 where coalesce((select max(11) from t1 where exists(select 1 from t1 where (a in (select count(*)+max(((t1.a))) from t1 union select cast(avg(a) AS integer) from t1)))),b)<=19), -b))*f=t1.e) and 17<>11 and e in (t1.f,f,17)) or a not between -a and (17)),+~b)-17*b) from t1 where t1.b>=b),t1.a)) AS integer) from t1) FROM t1 WHERE NOT (f in (select cast(avg(t1.e-f-t1.e) AS integer)+min(t1.d) from t1 union select max(case b when 11 then case case when f in (a,a,f) then t1.b when (t1.f)>d then -19 else t1.a end when 11 then a else t1.e end else (t1.b) end*a)*cast(avg(a) AS integer)+ -+cast(avg(t1.e) AS integer)*case cast(avg(t1.e) AS integer) when (cast(avg( -t1.a) AS integer)) then count(*) else count(*) end*min(t1.d)*min(e) from t1) and (a between d and t1.f))} +} {-2900} +do_test randexpr-2.2080 { + db eval {SELECT case when coalesce((select max(coalesce((select max((select min(13) from t1)*d*case when not 19<>(t1.c)-d then 11 else 17 end) from t1 where 13=t1.e then t1.d when not exists(select 1 from t1 where t1.c in (select (count(*)) from t1 union select +count(*) from t1)) then t1.c else 19 end FROM t1 WHERE ((11>=11))} +} {300} +do_test randexpr-2.2081 { + db eval {SELECT case when coalesce((select max(coalesce((select max((select min(13) from t1)*d*case when not 19<>(t1.c)-d then 11 else 17 end) from t1 where 13=t1.e then t1.d when not exists(select 1 from t1 where t1.c in (select (count(*)) from t1 union select +count(*) from t1)) then t1.c else 19 end FROM t1 WHERE NOT (((11>=11)))} +} {} +do_test randexpr-2.2082 { + db eval {SELECT -case when 19 in (select abs((count(*))) from t1 union select abs(min(t1.f)*min(e*e)) from t1) and case when not not (17>a) or d>=c and (19)<=t1.b and - -t1.f<>t1.f then f when t1.b between d and t1.f then case when t1.e=e then coalesce((select max(d) from t1 where t1.b>=b),a) when t1.a not between c and e then e else 13 end else (17) end>t1.d then b else b end+t1.b-a FROM t1 WHERE exists(select 1 from t1 where +coalesce((select 19 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where case when (select max(11-(select +count(distinct +case + -coalesce((select t1.d from t1 where exists(select 1 from t1 where (b)>t1.c)),t1.f)*11 when -a then 19 else 19 end) from t1)) from t1)<=t1.d-c then f when exists(select 1 from t1 where t1.f not between b and a) then -d else t1.d end not in (t1.b,t1.e, -t1.f)))),f) not in (f,e,13))} +} {} +do_test randexpr-2.2083 { + db eval {SELECT -case when 19 in (select abs((count(*))) from t1 union select abs(min(t1.f)*min(e*e)) from t1) and case when not not (17>a) or d>=c and (19)<=t1.b and - -t1.f<>t1.f then f when t1.b between d and t1.f then case when t1.e=e then coalesce((select max(d) from t1 where t1.b>=b),a) when t1.a not between c and e then e else 13 end else (17) end>t1.d then b else b end+t1.b-a FROM t1 WHERE NOT (exists(select 1 from t1 where +coalesce((select 19 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where case when (select max(11-(select +count(distinct +case + -coalesce((select t1.d from t1 where exists(select 1 from t1 where (b)>t1.c)),t1.f)*11 when -a then 19 else 19 end) from t1)) from t1)<=t1.d-c then f when exists(select 1 from t1 where t1.f not between b and a) then -d else t1.d end not in (t1.b,t1.e, -t1.f)))),f) not in (f,e,13)))} +} {-100} +do_test randexpr-2.2084 { + db eval {SELECT coalesce((select max(b) from t1 where d not between a-t1.e and a),coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where t1.ee or 11 between b and 13} +} {200} +do_test randexpr-2.2085 { + db eval {SELECT coalesce((select max(b) from t1 where d not between a-t1.e and a),coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where t1.ee or 11 between b and 13)} +} {} +do_test randexpr-2.2086 { + db eval {SELECT (select case count(*) when ~(case case -abs(count(*) | (case case ~case -count(distinct case when t1.a< -t1.d then b when 19 in (t1.e, - -19,t1.b) then t1.c else t1.f end)-count(distinct (t1.f)) when count(*) then max(c) else count(distinct 17) end when count(*) then ((cast(avg(b) AS integer))) else -count(*) end when -count(distinct t1.f) then count(distinct t1.a) else count(distinct t1.e) end))+count(*) when cast(avg(19) AS integer) then -min( -t1.c) else count(*) end when (min(t1.e)) then cast(avg(c) AS integer) else min(t1.f) end) then min(e) else count(*) end | max(11) from t1)+19 FROM t1 WHERE case when (((d not between (+t1.a-coalesce((select max(b*t1.b* -t1.f) from t1 where a>a),13)) and a)) and c>=d or fe and t1.c< -11 and f<>b or t1.b<17),c) else t1.a end>=11} +} {30} +do_test randexpr-2.2087 { + db eval {SELECT (select case count(*) when ~(case case -abs(count(*) | (case case ~case -count(distinct case when t1.a< -t1.d then b when 19 in (t1.e, - -19,t1.b) then t1.c else t1.f end)-count(distinct (t1.f)) when count(*) then max(c) else count(distinct 17) end when count(*) then ((cast(avg(b) AS integer))) else -count(*) end when -count(distinct t1.f) then count(distinct t1.a) else count(distinct t1.e) end))+count(*) when cast(avg(19) AS integer) then -min( -t1.c) else count(*) end when (min(t1.e)) then cast(avg(c) AS integer) else min(t1.f) end) then min(e) else count(*) end | max(11) from t1)+19 FROM t1 WHERE NOT (case when (((d not between (+t1.a-coalesce((select max(b*t1.b* -t1.f) from t1 where a>a),13)) and a)) and c>=d or fe and t1.c< -11 and f<>b or t1.b<17),c) else t1.a end>=11)} +} {} +do_test randexpr-2.2088 { + db eval {SELECT (select case count(*) when ~(case case -abs(count(*) & (case case ~case -count(distinct case when t1.a< -t1.d then b when 19 in (t1.e, - -19,t1.b) then t1.c else t1.f end)-count(distinct (t1.f)) when count(*) then max(c) else count(distinct 17) end when count(*) then ((cast(avg(b) AS integer))) else -count(*) end when -count(distinct t1.f) then count(distinct t1.a) else count(distinct t1.e) end))+count(*) when cast(avg(19) AS integer) then -min( -t1.c) else count(*) end when (min(t1.e)) then cast(avg(c) AS integer) else min(t1.f) end) then min(e) else count(*) end & max(11) from t1)+19 FROM t1 WHERE case when (((d not between (+t1.a-coalesce((select max(b*t1.b* -t1.f) from t1 where a>a),13)) and a)) and c>=d or fe and t1.c< -11 and f<>b or t1.b<17),c) else t1.a end>=11} +} {20} +do_test randexpr-2.2089 { + db eval {SELECT case when case when t1.a*~t1.a-19-c | 17+t1.d*f*c=d then f else -13 end+t1.b+a in (t1.f,t1.d,t1.f) and (not c=11) and t1.e<>f then coalesce((select f from t1 where t1.d not in (t1.e,f,11)), -17) else f end-b FROM t1 WHERE not exists(select 1 from t1 where +d between d*13 and ((abs(13+e+e)/abs(+case when not t1.c in (~(select cast(avg(case e when b then 11 else 13 end) AS integer) from t1)*b*17,t1.e,t1.e) then 11* -c when t1.f in (select min(e)*count(distinct c) from t1 union select - - - -max(e) | cast(avg((d)) AS integer) from t1) then (c) else e end)))) or d<17} +} {400} +do_test randexpr-2.2090 { + db eval {SELECT case when case when t1.a*~t1.a-19-c | 17+t1.d*f*c=d then f else -13 end+t1.b+a in (t1.f,t1.d,t1.f) and (not c=11) and t1.e<>f then coalesce((select f from t1 where t1.d not in (t1.e,f,11)), -17) else f end-b FROM t1 WHERE NOT (not exists(select 1 from t1 where +d between d*13 and ((abs(13+e+e)/abs(+case when not t1.c in (~(select cast(avg(case e when b then 11 else 13 end) AS integer) from t1)*b*17,t1.e,t1.e) then 11* -c when t1.f in (select min(e)*count(distinct c) from t1 union select - - - -max(e) | cast(avg((d)) AS integer) from t1) then (c) else e end)))) or d<17)} +} {} +do_test randexpr-2.2091 { + db eval {SELECT case when case when t1.a*~t1.a-19-c & 17+t1.d*f*c=d then f else -13 end+t1.b+a in (t1.f,t1.d,t1.f) and (not c=11) and t1.e<>f then coalesce((select f from t1 where t1.d not in (t1.e,f,11)), -17) else f end-b FROM t1 WHERE not exists(select 1 from t1 where +d between d*13 and ((abs(13+e+e)/abs(+case when not t1.c in (~(select cast(avg(case e when b then 11 else 13 end) AS integer) from t1)*b*17,t1.e,t1.e) then 11* -c when t1.f in (select min(e)*count(distinct c) from t1 union select - - - -max(e) | cast(avg((d)) AS integer) from t1) then (c) else e end)))) or d<17} +} {400} +do_test randexpr-2.2092 { + db eval {SELECT coalesce((select c from t1 where t1.b between t1.b and -17),coalesce((select -t1.e from t1 where (select count(distinct coalesce((select case t1.b-t1.a*(b)*13 when 11 then (a) else 11 end from t1 where a not in ((t1.e),c,11) and e>b),13)) from t1) in (t1.d,b,13) and not t1.b<13 or 11<> -17 or (11)>17 or t1.f not between b and (t1.a)),(b))) FROM t1 WHERE ((+case +d when f then (d) else case t1.f-(b)-11 when d then -t1.c else a end end not in ( -17,(t1.d),13) and (11 not in ((c),t1.f,t1.d)) and (e in (select 13 from t1 union select t1.a from t1) and d in (select t1.e from t1 union select 19 from t1))) or exists(select 1 from t1 where -t1.a= -t1.d)) and exists(select 1 from t1 where t1.b not between f and e or 19>=t1.d)} +} {} +do_test randexpr-2.2093 { + db eval {SELECT coalesce((select c from t1 where t1.b between t1.b and -17),coalesce((select -t1.e from t1 where (select count(distinct coalesce((select case t1.b-t1.a*(b)*13 when 11 then (a) else 11 end from t1 where a not in ((t1.e),c,11) and e>b),13)) from t1) in (t1.d,b,13) and not t1.b<13 or 11<> -17 or (11)>17 or t1.f not between b and (t1.a)),(b))) FROM t1 WHERE NOT (((+case +d when f then (d) else case t1.f-(b)-11 when d then -t1.c else a end end not in ( -17,(t1.d),13) and (11 not in ((c),t1.f,t1.d)) and (e in (select 13 from t1 union select t1.a from t1) and d in (select t1.e from t1 union select 19 from t1))) or exists(select 1 from t1 where -t1.a= -t1.d)) and exists(select 1 from t1 where t1.b not between f and e or 19>=t1.d))} +} {-500} +do_test randexpr-2.2094 { + db eval {SELECT case d when f then case when (abs(coalesce((select ~f*case when t1.f<(select -count(distinct (select count(*)-min(13) from t1)) from t1) then d when t1.d between t1.b and f and not (t1.b between ( -t1.f) and f) then -d else b end-b | t1.f*17 from t1 where ((d>t1.d))),17))/abs(11))-13=t1.c then a else 11 end else b end FROM t1 WHERE t1.b between coalesce((select case when coalesce((select t1.c from t1 where not ((t1.a>=11+17 and (13+(11)<>13))) and b<=c and c in (c, -c,(e)) and d not in (f,b,c) or t1.d>=13 and 13 between 19 and a),d) not between 13-case when t1.f<>t1.b then t1.f else t1.c end | d and d then b when c= -d),19) and c} +} {} +do_test randexpr-2.2095 { + db eval {SELECT case d when f then case when (abs(coalesce((select ~f*case when t1.f<(select -count(distinct (select count(*)-min(13) from t1)) from t1) then d when t1.d between t1.b and f and not (t1.b between ( -t1.f) and f) then -d else b end-b | t1.f*17 from t1 where ((d>t1.d))),17))/abs(11))-13=t1.c then a else 11 end else b end FROM t1 WHERE NOT (t1.b between coalesce((select case when coalesce((select t1.c from t1 where not ((t1.a>=11+17 and (13+(11)<>13))) and b<=c and c in (c, -c,(e)) and d not in (f,b,c) or t1.d>=13 and 13 between 19 and a),d) not between 13-case when t1.f<>t1.b then t1.f else t1.c end | d and d then b when c= -d),19) and c)} +} {200} +do_test randexpr-2.2096 { + db eval {SELECT case d when f then case when (abs(coalesce((select ~f*case when t1.f<(select -count(distinct (select count(*)-min(13) from t1)) from t1) then d when t1.d between t1.b and f and not (t1.b between ( -t1.f) and f) then -d else b end-b & t1.f*17 from t1 where ((d>t1.d))),17))/abs(11))-13=t1.c then a else 11 end else b end FROM t1 WHERE NOT (t1.b between coalesce((select case when coalesce((select t1.c from t1 where not ((t1.a>=11+17 and (13+(11)<>13))) and b<=c and c in (c, -c,(e)) and d not in (f,b,c) or t1.d>=13 and 13 between 19 and a),d) not between 13-case when t1.f<>t1.b then t1.f else t1.c end | d and d then b when c= -d),19) and c)} +} {200} +do_test randexpr-2.2097 { + db eval {SELECT (coalesce((select case when exists(select 1 from t1 where case when (t1.b)>=f+e*coalesce((select max( -+t1.c) from t1 where case a when e then e else 11 end in (select 17 from t1 union select d from t1) or e not between d and a),t1.f) then ( -t1.d) else e end in (11,c,b)) then 17 else t1.f end+t1.f from t1 where not d in ((b),(f),11) and t1.f=t1.b and 19<13 then 19 else 13 end=19) and b not in (c,t1.a,d) or b between e and -t1.f or t1.b between t1.e and c and t1.a<=t1.d} +} {} +do_test randexpr-2.2098 { + db eval {SELECT (coalesce((select case when exists(select 1 from t1 where case when (t1.b)>=f+e*coalesce((select max( -+t1.c) from t1 where case a when e then e else 11 end in (select 17 from t1 union select d from t1) or e not between d and a),t1.f) then ( -t1.d) else e end in (11,c,b)) then 17 else t1.f end+t1.f from t1 where not d in ((b),(f),11) and t1.f=t1.b and 19<13 then 19 else 13 end=19) and b not in (c,t1.a,d) or b between e and -t1.f or t1.b between t1.e and c and t1.a<=t1.d)} +} {19} +do_test randexpr-2.2099 { + db eval {SELECT 11+17+case when case 17 when coalesce((select max(d) from t1 where 13+(t1.c-e)+19+e-t1.e>=b and not 11 not in (19,t1.e,13) and (t1.f)>b),19)*19 then c else -d end not in (c,19,t1.c) then d when d<=t1.d then 13 else 11 end+ -a FROM t1 WHERE coalesce((select max(~t1.f) from t1 where (13*t1.e)<=case when 17 | a<=t1.e then coalesce((select max(19) from t1 where case when not not exists(select 1 from t1 where 19 in (t1.d+19,11,t1.f) or not exists(select 1 from t1 where a=t1.c then - -11 else t1.b end else f end-f<=b),t1.b) else t1.e end),f)-19>=13} +} {328} +do_test randexpr-2.2100 { + db eval {SELECT 11+17+case when case 17 when coalesce((select max(d) from t1 where 13+(t1.c-e)+19+e-t1.e>=b and not 11 not in (19,t1.e,13) and (t1.f)>b),19)*19 then c else -d end not in (c,19,t1.c) then d when d<=t1.d then 13 else 11 end+ -a FROM t1 WHERE NOT (coalesce((select max(~t1.f) from t1 where (13*t1.e)<=case when 17 | a<=t1.e then coalesce((select max(19) from t1 where case when not not exists(select 1 from t1 where 19 in (t1.d+19,11,t1.f) or not exists(select 1 from t1 where a=t1.c then - -11 else t1.b end else f end-f<=b),t1.b) else t1.e end),f)-19>=13)} +} {} +do_test randexpr-2.2101 { + db eval {SELECT coalesce((select max(t1.a+(select count(distinct 11-case when coalesce((select max(11) from t1 where t1.f<(t1.a)-t1.b),b) in (select ~abs(min(c-case when (case 13 when -coalesce((select (t1.e) from t1 where -a not in (f,t1.d,d)),(11)) then b else t1.e end not between b and -t1.e) then e else t1.a end)) | count(*) from t1 union select -min(17) from t1) then t1.a else t1.d end) from t1)-t1.b) from t1 where 1711) then e else a end-t1.c+(d)*(13) in (select ~count(distinct (t1.f))+ -~ -count(distinct t1.e)+(min(13)) from t1 union select cast(avg(11) AS integer) from t1) or t1.e<>t1.f)) then f when not a<19 then coalesce((select max(11) from t1 where (t1.d) between -d and -t1.e or t1.f not between d and a and -b=19),t1.b) else +t1.f end not between a and e} +} {-99} +do_test randexpr-2.2102 { + db eval {SELECT coalesce((select max(t1.a+(select count(distinct 11-case when coalesce((select max(11) from t1 where t1.f<(t1.a)-t1.b),b) in (select ~abs(min(c-case when (case 13 when -coalesce((select (t1.e) from t1 where -a not in (f,t1.d,d)),(11)) then b else t1.e end not between b and -t1.e) then e else t1.a end)) | count(*) from t1 union select -min(17) from t1) then t1.a else t1.d end) from t1)-t1.b) from t1 where 1711) then e else a end-t1.c+(d)*(13) in (select ~count(distinct (t1.f))+ -~ -count(distinct t1.e)+(min(13)) from t1 union select cast(avg(11) AS integer) from t1) or t1.e<>t1.f)) then f when not a<19 then coalesce((select max(11) from t1 where (t1.d) between -d and -t1.e or t1.f not between d and a and -b=19),t1.b) else +t1.f end not between a and e)} +} {} +do_test randexpr-2.2103 { + db eval {SELECT coalesce((select max(t1.a+(select count(distinct 11-case when coalesce((select max(11) from t1 where t1.f<(t1.a)-t1.b),b) in (select ~abs(min(c-case when (case 13 when -coalesce((select (t1.e) from t1 where -a not in (f,t1.d,d)),(11)) then b else t1.e end not between b and -t1.e) then e else t1.a end)) & count(*) from t1 union select -min(17) from t1) then t1.a else t1.d end) from t1)-t1.b) from t1 where 1711) then e else a end-t1.c+(d)*(13) in (select ~count(distinct (t1.f))+ -~ -count(distinct t1.e)+(min(13)) from t1 union select cast(avg(11) AS integer) from t1) or t1.e<>t1.f)) then f when not a<19 then coalesce((select max(11) from t1 where (t1.d) between -d and -t1.e or t1.f not between d and a and -b=19),t1.b) else +t1.f end not between a and e} +} {-99} +do_test randexpr-2.2104 { + db eval {SELECT t1.b-case when 13 not between 13 and (select +count(*) from t1) then t1.e when +11 in (coalesce((select t1.f from t1 where d-((f))*coalesce((select d from t1 where 17 between ~(select max(d) | count(*) | cast(avg(e) AS integer)+count(*) from t1) and case when c<13 or 17>13 then a else e end-t1.b),e)-t1.a<=(t1.e)),19),b,13) then e else b end-t1.b FROM t1 WHERE t1.b>=coalesce((select max(d-c) from t1 where exists(select 1 from t1 where (~a*(select -count(distinct 11-d*13+d+19) from t1)* -b in (f,t1.d-c,a-(abs(c)/abs(case when (abs(13- -(19))/abs(t1.f)) in (select c from t1 union select -a from t1) then t1.c when b<=c then t1.a else -13 end)))))),19)} +} {-500} +do_test randexpr-2.2105 { + db eval {SELECT t1.b-case when 13 not between 13 and (select +count(*) from t1) then t1.e when +11 in (coalesce((select t1.f from t1 where d-((f))*coalesce((select d from t1 where 17 between ~(select max(d) | count(*) | cast(avg(e) AS integer)+count(*) from t1) and case when c<13 or 17>13 then a else e end-t1.b),e)-t1.a<=(t1.e)),19),b,13) then e else b end-t1.b FROM t1 WHERE NOT (t1.b>=coalesce((select max(d-c) from t1 where exists(select 1 from t1 where (~a*(select -count(distinct 11-d*13+d+19) from t1)* -b in (f,t1.d-c,a-(abs(c)/abs(case when (abs(13- -(19))/abs(t1.f)) in (select c from t1 union select -a from t1) then t1.c when b<=c then t1.a else -13 end)))))),19))} +} {} +do_test randexpr-2.2106 { + db eval {SELECT t1.b-case when 13 not between 13 and (select +count(*) from t1) then t1.e when +11 in (coalesce((select t1.f from t1 where d-((f))*coalesce((select d from t1 where 17 between ~(select max(d) & count(*) & cast(avg(e) AS integer)+count(*) from t1) and case when c<13 or 17>13 then a else e end-t1.b),e)-t1.a<=(t1.e)),19),b,13) then e else b end-t1.b FROM t1 WHERE t1.b>=coalesce((select max(d-c) from t1 where exists(select 1 from t1 where (~a*(select -count(distinct 11-d*13+d+19) from t1)* -b in (f,t1.d-c,a-(abs(c)/abs(case when (abs(13- -(19))/abs(t1.f)) in (select c from t1 union select -a from t1) then t1.c when b<=c then t1.a else -13 end)))))),19)} +} {-500} +do_test randexpr-2.2107 { + db eval {SELECT t1.f*case when c*case when t1.d*t1.b-(~19) in (select (cast(avg(d-t1.d) AS integer)) from t1 union select min(11)+cast(avg(e) AS integer) | abs(count(distinct t1.a) | min(19)) from t1) then t1.d when not 11 not in (d,t1.e,13) then t1.a else 11 end in (select (t1.c) from t1 union select 11 from t1) or t1.e not in (f, -t1.f,t1.e) then c else d end FROM t1 WHERE case when t1.e=t1.c and (abs(case when (11* -17 not in (c,t1.f-t1.c-coalesce((select max(c) from t1 where c in (select min(19) from t1 union select ~count(*)*max(t1.f) from t1)),a),t1.a)) then coalesce((select max(17) from t1 where -b>=(t1.c)),19) else f end+19)/abs(t1.f))*t1.d between d and b then t1.b-t1.e else c end=19} +} {} +do_test randexpr-2.2108 { + db eval {SELECT t1.f*case when c*case when t1.d*t1.b-(~19) in (select (cast(avg(d-t1.d) AS integer)) from t1 union select min(11)+cast(avg(e) AS integer) | abs(count(distinct t1.a) | min(19)) from t1) then t1.d when not 11 not in (d,t1.e,13) then t1.a else 11 end in (select (t1.c) from t1 union select 11 from t1) or t1.e not in (f, -t1.f,t1.e) then c else d end FROM t1 WHERE NOT (case when t1.e=t1.c and (abs(case when (11* -17 not in (c,t1.f-t1.c-coalesce((select max(c) from t1 where c in (select min(19) from t1 union select ~count(*)*max(t1.f) from t1)),a),t1.a)) then coalesce((select max(17) from t1 where -b>=(t1.c)),19) else f end+19)/abs(t1.f))*t1.d between d and b then t1.b-t1.e else c end=19)} +} {240000} +do_test randexpr-2.2109 { + db eval {SELECT t1.f*case when c*case when t1.d*t1.b-(~19) in (select (cast(avg(d-t1.d) AS integer)) from t1 union select min(11)+cast(avg(e) AS integer) & abs(count(distinct t1.a) & min(19)) from t1) then t1.d when not 11 not in (d,t1.e,13) then t1.a else 11 end in (select (t1.c) from t1 union select 11 from t1) or t1.e not in (f, -t1.f,t1.e) then c else d end FROM t1 WHERE NOT (case when t1.e=t1.c and (abs(case when (11* -17 not in (c,t1.f-t1.c-coalesce((select max(c) from t1 where c in (select min(19) from t1 union select ~count(*)*max(t1.f) from t1)),a),t1.a)) then coalesce((select max(17) from t1 where -b>=(t1.c)),19) else f end+19)/abs(t1.f))*t1.d between d and b then t1.b-t1.e else c end=19)} +} {240000} +do_test randexpr-2.2110 { + db eval {SELECT coalesce((select max((abs(t1.d)/abs((coalesce((select c from t1 where (abs(+f)/abs(t1.b))-t1.a between 13 and case (13+c+((abs(coalesce((select 11 from t1 where 11+19a then (coalesce((select -e from t1 where case coalesce((select case when 19 in (select t1.e from t1 union select f from t1) then b when t1.c=11 then a else (13) end from t1 where t1.a in (select ( -cast(avg(13) AS integer)+max(t1.e)) from t1 union select cast(avg(19) AS integer) from t1)),19) when f then f else ( -t1.c) end+17<=e and a>=t1.b or t1.c>=b),t1.e)) else e end)>=e),b)+f FROM t1 WHERE exists(select 1 from t1 where 17 in (select -abs(case (min(t1.b)) when count(*)*max(a) then -abs((max(e))) | ~max( -coalesce((select max(coalesce((select e from t1 where f>=11 or exists(select 1 from t1 where 11 not in (11,t1.c,f))),d)) from t1 where 13=t1.d and 17<>f),t1.d))+count(distinct t1.e) else count(*)+~cast(avg(t1.f) AS integer) end | count(distinct t1.a))+count(distinct t1.a) from t1 union select count(*) from t1))} +} {} +do_test randexpr-2.2113 { + db eval {SELECT f+coalesce((select max(t1.f) from t1 where (case when 13<>a then (coalesce((select -e from t1 where case coalesce((select case when 19 in (select t1.e from t1 union select f from t1) then b when t1.c=11 then a else (13) end from t1 where t1.a in (select ( -cast(avg(13) AS integer)+max(t1.e)) from t1 union select cast(avg(19) AS integer) from t1)),19) when f then f else ( -t1.c) end+17<=e and a>=t1.b or t1.c>=b),t1.e)) else e end)>=e),b)+f FROM t1 WHERE NOT (exists(select 1 from t1 where 17 in (select -abs(case (min(t1.b)) when count(*)*max(a) then -abs((max(e))) | ~max( -coalesce((select max(coalesce((select e from t1 where f>=11 or exists(select 1 from t1 where 11 not in (11,t1.c,f))),d)) from t1 where 13=t1.d and 17<>f),t1.d))+count(distinct t1.e) else count(*)+~cast(avg(t1.f) AS integer) end | count(distinct t1.a))+count(distinct t1.a) from t1 union select count(*) from t1)))} +} {1400} +do_test randexpr-2.2114 { + db eval {SELECT case when case when (abs( -t1.b)/abs(case case case (select ~ -(+abs(case min(19) when (( -min(t1.e))) then count(distinct (t1.e)) else cast(avg(11) AS integer) end)) from t1) when t1.e then (select min(19) from t1) else 17 end when (13)-a*17 then t1.d else t1.a end when a then 19 else -( -f) end))>=d then t1.e else 13 end between f and 19 then f when t1.c<=t1.a or (t1.b>(11)) then 11 else t1.b end FROM t1 WHERE t1.c in (select case when 11<17 then case when (t1.b*coalesce((select (abs((coalesce((select a-19 from t1 where t1.c between e and f and d<>17 and t1.d not between 19 and 19),a)))/abs(t1.c))+t1.b-17 from t1 where c=a), -t1.d)+c>t1.f) then -13+(t1.e) when 11<>t1.c then 13 else t1.c end when 11=c then t1.c else (c) end from t1 union select t1.e from t1)} +} {} +do_test randexpr-2.2115 { + db eval {SELECT case when case when (abs( -t1.b)/abs(case case case (select ~ -(+abs(case min(19) when (( -min(t1.e))) then count(distinct (t1.e)) else cast(avg(11) AS integer) end)) from t1) when t1.e then (select min(19) from t1) else 17 end when (13)-a*17 then t1.d else t1.a end when a then 19 else -( -f) end))>=d then t1.e else 13 end between f and 19 then f when t1.c<=t1.a or (t1.b>(11)) then 11 else t1.b end FROM t1 WHERE NOT (t1.c in (select case when 11<17 then case when (t1.b*coalesce((select (abs((coalesce((select a-19 from t1 where t1.c between e and f and d<>17 and t1.d not between 19 and 19),a)))/abs(t1.c))+t1.b-17 from t1 where c=a), -t1.d)+c>t1.f) then -13+(t1.e) when 11<>t1.c then 13 else t1.c end when 11=c then t1.c else (c) end from t1 union select t1.e from t1))} +} {11} +do_test randexpr-2.2116 { + db eval {SELECT t1.e+coalesce((select case t1.a-case when t1.a in (case (abs(coalesce((select t1.e from t1 where t1.a>t1.b),~c))/abs(t1.b))* -(select count(distinct t1.c)-cast(avg(coalesce((select 19 from t1 where c not between (abs(b-11)/abs( -t1.e)) and (17)),17)) AS integer) from t1) when t1.e then f else 17 end,t1.c,t1.c) then d else t1.e end when d then 17 else 13 end from t1 where 11<11),t1.f) FROM t1 WHERE 11* -19 in (select case when ~coalesce((select t1.b from t1 where coalesce((select d from t1 where t1.a=17*~e+t1.d*case when 11< -~t1.b*t1.b*c+a then (c) else 19 end*a),e)>e),11)<=19 then t1.c when (not exists(select 1 from t1 where t1.d<17)) then b else c end from t1 union select t1.a from t1)} +} {} +do_test randexpr-2.2117 { + db eval {SELECT t1.e+coalesce((select case t1.a-case when t1.a in (case (abs(coalesce((select t1.e from t1 where t1.a>t1.b),~c))/abs(t1.b))* -(select count(distinct t1.c)-cast(avg(coalesce((select 19 from t1 where c not between (abs(b-11)/abs( -t1.e)) and (17)),17)) AS integer) from t1) when t1.e then f else 17 end,t1.c,t1.c) then d else t1.e end when d then 17 else 13 end from t1 where 11<11),t1.f) FROM t1 WHERE NOT (11* -19 in (select case when ~coalesce((select t1.b from t1 where coalesce((select d from t1 where t1.a=17*~e+t1.d*case when 11< -~t1.b*t1.b*c+a then (c) else 19 end*a),e)>e),11)<=19 then t1.c when (not exists(select 1 from t1 where t1.d<17)) then b else c end from t1 union select t1.a from t1))} +} {1100} +do_test randexpr-2.2118 { + db eval {SELECT 19* -coalesce((select coalesce((select t1.d*17 from t1 where t1.b<=t1.b+17), -(a | 17)) from t1 where t1.d in (select case abs(count(*))*count(distinct (17)) when max(11) then abs(+max(13)-case -cast(avg(t1.d) AS integer)- -(max(19))-count(distinct d) when min(t1.c) then cast(avg(c) AS integer) else count(distinct t1.f) end | max(c)) else max(t1.d) end from t1 union select count(*) from t1)),t1.f)-t1.e+c FROM t1 WHERE ~(abs(case 17 when d then coalesce((select t1.d from t1 where 13 in (select t1.d-f | case when (17 in (t1.a,19,t1.f)) then case when a*f in (select e from t1 union select t1.a from t1) or 11=t1.c or t1.a>=(19) and ( -b)13 then b when t1.e in (t1.c, -t1.b,a) then 19 else 19 end else a end from t1 union select t1.b from t1)),d) else 13 end)/abs(11))+19*t1.e in (e, -t1.e,a)} +} {} +do_test randexpr-2.2119 { + db eval {SELECT 19* -coalesce((select coalesce((select t1.d*17 from t1 where t1.b<=t1.b+17), -(a | 17)) from t1 where t1.d in (select case abs(count(*))*count(distinct (17)) when max(11) then abs(+max(13)-case -cast(avg(t1.d) AS integer)- -(max(19))-count(distinct d) when min(t1.c) then cast(avg(c) AS integer) else count(distinct t1.f) end | max(c)) else max(t1.d) end from t1 union select count(*) from t1)),t1.f)-t1.e+c FROM t1 WHERE NOT (~(abs(case 17 when d then coalesce((select t1.d from t1 where 13 in (select t1.d-f | case when (17 in (t1.a,19,t1.f)) then case when a*f in (select e from t1 union select t1.a from t1) or 11=t1.c or t1.a>=(19) and ( -b)13 then b when t1.e in (t1.c, -t1.b,a) then 19 else 19 end else a end from t1 union select t1.b from t1)),d) else 13 end)/abs(11))+19*t1.e in (e, -t1.e,a))} +} {-129400} +do_test randexpr-2.2120 { + db eval {SELECT 19* -coalesce((select coalesce((select t1.d*17 from t1 where t1.b<=t1.b+17), -(a & 17)) from t1 where t1.d in (select case abs(count(*))*count(distinct (17)) when max(11) then abs(+max(13)-case -cast(avg(t1.d) AS integer)- -(max(19))-count(distinct d) when min(t1.c) then cast(avg(c) AS integer) else count(distinct t1.f) end & max(c)) else max(t1.d) end from t1 union select count(*) from t1)),t1.f)-t1.e+c FROM t1 WHERE NOT (~(abs(case 17 when d then coalesce((select t1.d from t1 where 13 in (select t1.d-f | case when (17 in (t1.a,19,t1.f)) then case when a*f in (select e from t1 union select t1.a from t1) or 11=t1.c or t1.a>=(19) and ( -b)13 then b when t1.e in (t1.c, -t1.b,a) then 19 else 19 end else a end from t1 union select t1.b from t1)),d) else 13 end)/abs(11))+19*t1.e in (e, -t1.e,a))} +} {-129400} +do_test randexpr-2.2121 { + db eval {SELECT case t1.f when f then t1.a-case d+t1.d+coalesce((select (select cast(avg( -case when t1.d in (select -min(17)-count(*)+max(f) from t1 union select -count(distinct 13) from t1) then t1.e else a end*a) AS integer) from t1)-t1.d from t1 where -t1.b not in (11, -(t1.b),t1.d) and c in (select b from t1 union select 19 from t1) and t1.a in (select -e from t1 union select t1.e from t1)),a)*t1.f when 19 then t1.f else 11 end else c end FROM t1 WHERE t1.c>11} +} {89} +do_test randexpr-2.2122 { + db eval {SELECT case t1.f when f then t1.a-case d+t1.d+coalesce((select (select cast(avg( -case when t1.d in (select -min(17)-count(*)+max(f) from t1 union select -count(distinct 13) from t1) then t1.e else a end*a) AS integer) from t1)-t1.d from t1 where -t1.b not in (11, -(t1.b),t1.d) and c in (select b from t1 union select 19 from t1) and t1.a in (select -e from t1 union select t1.e from t1)),a)*t1.f when 19 then t1.f else 11 end else c end FROM t1 WHERE NOT (t1.c>11)} +} {} +do_test randexpr-2.2123 { + db eval {SELECT case when (case when (e not in (e | e,17,e)) then 13 else t1.b end>+t1.b*f-b+t1.d-e) or 19 between b and t1.a then 11 when exists(select 1 from t1 where (t1.d) | t1.d in (case when (e>=(11)) or (t1.a)>=t1.f then c-b when t1.c<>t1.e then t1.a else (17) end,c,13)) then 17 else t1.b end FROM t1 WHERE (select min(case when a not in (coalesce((select 19 from t1 where t1.f<((abs(e)/abs(t1.a+e)) | d)-e),e),t1.f,t1.a) then c else 13 end)-(count(distinct d)-abs(count(distinct t1.c)-cast(avg(d) AS integer) | min(b)+(cast(avg(19) AS integer) | case count(distinct t1.c) when cast(avg( -t1.b) AS integer) then cast(avg(t1.a) AS integer) else max(13) end))) from t1) not between b | a and 19} +} {200} +do_test randexpr-2.2124 { + db eval {SELECT case when (case when (e not in (e | e,17,e)) then 13 else t1.b end>+t1.b*f-b+t1.d-e) or 19 between b and t1.a then 11 when exists(select 1 from t1 where (t1.d) | t1.d in (case when (e>=(11)) or (t1.a)>=t1.f then c-b when t1.c<>t1.e then t1.a else (17) end,c,13)) then 17 else t1.b end FROM t1 WHERE NOT ((select min(case when a not in (coalesce((select 19 from t1 where t1.f<((abs(e)/abs(t1.a+e)) | d)-e),e),t1.f,t1.a) then c else 13 end)-(count(distinct d)-abs(count(distinct t1.c)-cast(avg(d) AS integer) | min(b)+(cast(avg(19) AS integer) | case count(distinct t1.c) when cast(avg( -t1.b) AS integer) then cast(avg(t1.a) AS integer) else max(13) end))) from t1) not between b | a and 19)} +} {} +do_test randexpr-2.2125 { + db eval {SELECT case when (case when (e not in (e & e,17,e)) then 13 else t1.b end>+t1.b*f-b+t1.d-e) or 19 between b and t1.a then 11 when exists(select 1 from t1 where (t1.d) & t1.d in (case when (e>=(11)) or (t1.a)>=t1.f then c-b when t1.c<>t1.e then t1.a else (17) end,c,13)) then 17 else t1.b end FROM t1 WHERE (select min(case when a not in (coalesce((select 19 from t1 where t1.f<((abs(e)/abs(t1.a+e)) | d)-e),e),t1.f,t1.a) then c else 13 end)-(count(distinct d)-abs(count(distinct t1.c)-cast(avg(d) AS integer) | min(b)+(cast(avg(19) AS integer) | case count(distinct t1.c) when cast(avg( -t1.b) AS integer) then cast(avg(t1.a) AS integer) else max(13) end))) from t1) not between b | a and 19} +} {200} +do_test randexpr-2.2126 { + db eval {SELECT case when case when t1.c+13<13 then 11 when (t1.b) not in (t1.b,e,t1.c) then t1.f else -t1.c end- -a | 13 in (select max(a) from t1 union select count(distinct 17)* -case count(*) when count(*) then -((count(distinct 17))) else max(t1.b) end | ( -count(*)) from t1) and e<=17 and t1.c<=d then coalesce((select max(coalesce((select max(e) from t1 where t1.f not in (e,17,t1.b) and d= -t1.b),t1.d)) from t1 where t1.d(f) then t1.e else 17 end else t1.c end-19} +} {200} +do_test randexpr-2.2127 { + db eval {SELECT case when case when t1.c+13<13 then 11 when (t1.b) not in (t1.b,e,t1.c) then t1.f else -t1.c end- -a | 13 in (select max(a) from t1 union select count(distinct 17)* -case count(*) when count(*) then -((count(distinct 17))) else max(t1.b) end | ( -count(*)) from t1) and e<=17 and t1.c<=d then coalesce((select max(coalesce((select max(e) from t1 where t1.f not in (e,17,t1.b) and d= -t1.b),t1.d)) from t1 where t1.d(f) then t1.e else 17 end else t1.c end-19)} +} {} +do_test randexpr-2.2128 { + db eval {SELECT case when case when t1.c+13<13 then 11 when (t1.b) not in (t1.b,e,t1.c) then t1.f else -t1.c end- -a & 13 in (select max(a) from t1 union select count(distinct 17)* -case count(*) when count(*) then -((count(distinct 17))) else max(t1.b) end & ( -count(*)) from t1) and e<=17 and t1.c<=d then coalesce((select max(coalesce((select max(e) from t1 where t1.f not in (e,17,t1.b) and d= -t1.b),t1.d)) from t1 where t1.d(f) then t1.e else 17 end else t1.c end-19} +} {200} +do_test randexpr-2.2129 { + db eval {SELECT coalesce((select case t1.e when coalesce((select max(e- -coalesce((select 17-d-e from t1 where ( -e*(d)>t1.c and 17=(t1.b) or not 11>(a) and b not between ((f)) and t1.d)),t1.c)-f-(f)*b+t1.a) from t1 where f<>13),t1.b) then t1.c else t1.b end from t1 where c in (select t1.a from t1 union select (t1.e) from t1)),e) FROM t1 WHERE (c in (select ~abs(cast(avg(19) AS integer))- -(case (++abs(max( -(select case case ( -abs(+cast(avg(b) AS integer) | count(distinct t1.b*17)*min( -11)*count(distinct t1.e))) when (max( -t1.b)) then count(distinct e) else max(11) end when -min(d) then count(*) else cast(avg(t1.a) AS integer) end from t1))*max(11))) when min(b) then max(19) else (count(*)) end)* -(max(t1.a))-count(*) from t1 union select count(distinct t1.a) from t1))} +} {} +do_test randexpr-2.2130 { + db eval {SELECT coalesce((select case t1.e when coalesce((select max(e- -coalesce((select 17-d-e from t1 where ( -e*(d)>t1.c and 17=(t1.b) or not 11>(a) and b not between ((f)) and t1.d)),t1.c)-f-(f)*b+t1.a) from t1 where f<>13),t1.b) then t1.c else t1.b end from t1 where c in (select t1.a from t1 union select (t1.e) from t1)),e) FROM t1 WHERE NOT ((c in (select ~abs(cast(avg(19) AS integer))- -(case (++abs(max( -(select case case ( -abs(+cast(avg(b) AS integer) | count(distinct t1.b*17)*min( -11)*count(distinct t1.e))) when (max( -t1.b)) then count(distinct e) else max(11) end when -min(d) then count(*) else cast(avg(t1.a) AS integer) end from t1))*max(11))) when min(b) then max(19) else (count(*)) end)* -(max(t1.a))-count(*) from t1 union select count(distinct t1.a) from t1)))} +} {500} +do_test randexpr-2.2131 { + db eval {SELECT t1.e+13-(abs(f)/abs(e | coalesce((select case when (f>=~t1.c*case t1.a when -d then (11) else 17 end*19) then case a when t1.e then b else e end else t1.c end from t1 where e in (select t1.a from t1 union select a from t1) or t1.d not in (f,f,17) and t1.b not between f and 17 and e=c),t1.c)*17+d+t1.d)) FROM t1 WHERE coalesce((select ~f+t1.c*t1.d | t1.d*t1.d-t1.b from t1 where t1.b | t1.a between case when (abs(coalesce((select f from t1 where t1.e between 11-17 and t1.c),e)-t1.d*b)/abs(((d))))-d between t1.b and d then a when -(f) between e and t1.e then t1.a else a end and t1.b),t1.a)-11=d} +} {} +do_test randexpr-2.2132 { + db eval {SELECT t1.e+13-(abs(f)/abs(e | coalesce((select case when (f>=~t1.c*case t1.a when -d then (11) else 17 end*19) then case a when t1.e then b else e end else t1.c end from t1 where e in (select t1.a from t1 union select a from t1) or t1.d not in (f,f,17) and t1.b not between f and 17 and e=c),t1.c)*17+d+t1.d)) FROM t1 WHERE NOT (coalesce((select ~f+t1.c*t1.d | t1.d*t1.d-t1.b from t1 where t1.b | t1.a between case when (abs(coalesce((select f from t1 where t1.e between 11-17 and t1.c),e)-t1.d*b)/abs(((d))))-d between t1.b and d then a when -(f) between e and t1.e then t1.a else a end and t1.b),t1.a)-11=d)} +} {513} +do_test randexpr-2.2133 { + db eval {SELECT t1.e+13-(abs(f)/abs(e & coalesce((select case when (f>=~t1.c*case t1.a when -d then (11) else 17 end*19) then case a when t1.e then b else e end else t1.c end from t1 where e in (select t1.a from t1 union select a from t1) or t1.d not in (f,f,17) and t1.b not between f and 17 and e=c),t1.c)*17+d+t1.d)) FROM t1 WHERE NOT (coalesce((select ~f+t1.c*t1.d | t1.d*t1.d-t1.b from t1 where t1.b | t1.a between case when (abs(coalesce((select f from t1 where t1.e between 11-17 and t1.c),e)-t1.d*b)/abs(((d))))-d between t1.b and d then a when -(f) between e and t1.e then t1.a else a end and t1.b),t1.a)-11=d)} +} {511} +do_test randexpr-2.2134 { + db eval {SELECT +(abs(~+13+(abs(t1.c)/abs(t1.c | coalesce((select t1.a from t1 where (select min(t1.c) from t1)<>(abs(t1.f | coalesce((select c from t1 where b=17),f)-b)/abs(coalesce((select max(d-t1.e) from t1 where not exists(select 1 from t1 where t1.e in (select f from t1 union select t1.d from t1))),19)*e+19)) or t1.a in (select 13 from t1 union select t1.d from t1) and (b)<= -t1.f),11))))/abs(e)) FROM t1 WHERE t1.e<>coalesce((select case 17 when f then coalesce((select max(t1.c) from t1 where coalesce((select coalesce((select ~e from t1 where not 17<=e | 17),11)+t1.d+t1.e from t1 where (e>=f or (not t1.e>=t1.a or e between f and t1.f))),t1.b) not in (13,17,c) or t1.a> -t1.d),19) else t1.c end from t1 where (not 17 not in (t1.b,11,b) and f>=t1.f) or 19<=t1.f),d)-11} +} {0} +do_test randexpr-2.2135 { + db eval {SELECT +(abs(~+13+(abs(t1.c)/abs(t1.c | coalesce((select t1.a from t1 where (select min(t1.c) from t1)<>(abs(t1.f | coalesce((select c from t1 where b=17),f)-b)/abs(coalesce((select max(d-t1.e) from t1 where not exists(select 1 from t1 where t1.e in (select f from t1 union select t1.d from t1))),19)*e+19)) or t1.a in (select 13 from t1 union select t1.d from t1) and (b)<= -t1.f),11))))/abs(e)) FROM t1 WHERE NOT (t1.e<>coalesce((select case 17 when f then coalesce((select max(t1.c) from t1 where coalesce((select coalesce((select ~e from t1 where not 17<=e | 17),11)+t1.d+t1.e from t1 where (e>=f or (not t1.e>=t1.a or e between f and t1.f))),t1.b) not in (13,17,c) or t1.a> -t1.d),19) else t1.c end from t1 where (not 17 not in (t1.b,11,b) and f>=t1.f) or 19<=t1.f),d)-11)} +} {} +do_test randexpr-2.2136 { + db eval {SELECT +(abs(~+13+(abs(t1.c)/abs(t1.c & coalesce((select t1.a from t1 where (select min(t1.c) from t1)<>(abs(t1.f & coalesce((select c from t1 where b=17),f)-b)/abs(coalesce((select max(d-t1.e) from t1 where not exists(select 1 from t1 where t1.e in (select f from t1 union select t1.d from t1))),19)*e+19)) or t1.a in (select 13 from t1 union select t1.d from t1) and (b)<= -t1.f),11))))/abs(e)) FROM t1 WHERE t1.e<>coalesce((select case 17 when f then coalesce((select max(t1.c) from t1 where coalesce((select coalesce((select ~e from t1 where not 17<=e | 17),11)+t1.d+t1.e from t1 where (e>=f or (not t1.e>=t1.a or e between f and t1.f))),t1.b) not in (13,17,c) or t1.a> -t1.d),19) else t1.c end from t1 where (not 17 not in (t1.b,11,b) and f>=t1.f) or 19<=t1.f),d)-11} +} {0} +do_test randexpr-2.2137 { + db eval {SELECT (case when not case when ((e not between d and case when not exists(select 1 from t1 where 11>=(a)*t1.d*11 or -(d) not in (a,11,t1.f)) then f else ~f end or not d<>t1.e or t1.c in (a,t1.d,t1.c))) then case when -b between 11 and b then (select count(distinct 17) from t1) when t1.e<>11 then f else d end else t1.d end<=a then (abs(t1.d)/abs(e)) when t1.d=t1.b and 17=t1.e)) then f else 19 end-t1.a*t1.a-e<=t1.b and 17 in (t1.d,13,t1.b) then c else t1.b end<>t1.b or not exists(select 1 from t1 where 17 between (d) and ( -(t1.d)))} +} {0} +do_test randexpr-2.2138 { + db eval {SELECT (case when not case when ((e not between d and case when not exists(select 1 from t1 where 11>=(a)*t1.d*11 or -(d) not in (a,11,t1.f)) then f else ~f end or not d<>t1.e or t1.c in (a,t1.d,t1.c))) then case when -b between 11 and b then (select count(distinct 17) from t1) when t1.e<>11 then f else d end else t1.d end<=a then (abs(t1.d)/abs(e)) when t1.d=t1.b and 17=t1.e)) then f else 19 end-t1.a*t1.a-e<=t1.b and 17 in (t1.d,13,t1.b) then c else t1.b end<>t1.b or not exists(select 1 from t1 where 17 between (d) and ( -(t1.d))))} +} {} +do_test randexpr-2.2139 { + db eval {SELECT t1.b+case when f+f not in (c+case when t1.f<>d then 11 when f between 11 and t1.d then 11 else 13 end,e,(t1.f)) and not exists(select 1 from t1 where (exists(select 1 from t1 where 19<11)) or 11 in ((t1.d),t1.c,b) and t1.b>13) and t1.b=t1.b then (abs(t1.d)/abs(13)) when a not between t1.c and 19 then t1.f else 19 end+13*17-t1.e FROM t1 WHERE not exists(select 1 from t1 where (exists(select 1 from t1 where t1.c>=19)))} +} {} +do_test randexpr-2.2140 { + db eval {SELECT t1.b+case when f+f not in (c+case when t1.f<>d then 11 when f between 11 and t1.d then 11 else 13 end,e,(t1.f)) and not exists(select 1 from t1 where (exists(select 1 from t1 where 19<11)) or 11 in ((t1.d),t1.c,b) and t1.b>13) and t1.b=t1.b then (abs(t1.d)/abs(13)) when a not between t1.c and 19 then t1.f else 19 end+13*17-t1.e FROM t1 WHERE NOT (not exists(select 1 from t1 where (exists(select 1 from t1 where t1.c>=19))))} +} {-49} +do_test randexpr-2.2141 { + db eval {SELECT (case when f>(select abs((((count(*)-+cast(avg(d) AS integer)))) | count(distinct a)) from t1) then case when (abs(coalesce((select max(t1.d) from t1 where coalesce((select max(case when t1.b between t1.f and a then -f when f<> -b then t1.e else -19 end) from t1 where not exists(select 1 from t1 where t1.c not in (t1.f,t1.c,t1.a))),t1.c)<=b), -t1.c))/abs(t1.a))11} +} {600} +do_test randexpr-2.2142 { + db eval {SELECT (case when f>(select abs((((count(*)-+cast(avg(d) AS integer)))) | count(distinct a)) from t1) then case when (abs(coalesce((select max(t1.d) from t1 where coalesce((select max(case when t1.b between t1.f and a then -f when f<> -b then t1.e else -19 end) from t1 where not exists(select 1 from t1 where t1.c not in (t1.f,t1.c,t1.a))),t1.c)<=b), -t1.c))/abs(t1.a))11)} +} {} +do_test randexpr-2.2143 { + db eval {SELECT (case when f>(select abs((((count(*)-+cast(avg(d) AS integer)))) & count(distinct a)) from t1) then case when (abs(coalesce((select max(t1.d) from t1 where coalesce((select max(case when t1.b between t1.f and a then -f when f<> -b then t1.e else -19 end) from t1 where not exists(select 1 from t1 where t1.c not in (t1.f,t1.c,t1.a))),t1.c)<=b), -t1.c))/abs(t1.a))11} +} {600} +do_test randexpr-2.2144 { + db eval {SELECT (abs(+coalesce((select t1.f from t1 where not exists(select 1 from t1 where (((c)<=t1.a)))),f+(select count(distinct t1.b) from t1)*t1.b+case when case (select count(*) from t1) when coalesce((select max(t1.f-e+13) from t1 where (t1.e>a and 19 not in (13,b,19))),t1.c)+e then t1.b else t1.b end in (select -c from t1 union select c from t1) then f when t1.a>t1.e then t1.c else d end+ -13))/abs((t1.f))) FROM t1 WHERE coalesce((select t1.f from t1 where a>=e),13) between -c and t1.a} +} {1} +do_test randexpr-2.2145 { + db eval {SELECT (abs(+coalesce((select t1.f from t1 where not exists(select 1 from t1 where (((c)<=t1.a)))),f+(select count(distinct t1.b) from t1)*t1.b+case when case (select count(*) from t1) when coalesce((select max(t1.f-e+13) from t1 where (t1.e>a and 19 not in (13,b,19))),t1.c)+e then t1.b else t1.b end in (select -c from t1 union select c from t1) then f when t1.a>t1.e then t1.c else d end+ -13))/abs((t1.f))) FROM t1 WHERE NOT (coalesce((select t1.f from t1 where a>=e),13) between -c and t1.a)} +} {} +do_test randexpr-2.2146 { + db eval {SELECT coalesce((select max(~19) from t1 where t1.a between case t1.c when t1.b then t1.e else +~f end and case when 19 not in (e+b,t1.e-d,(select max(e) from t1)) then t1.a else case 13 when case e when e then t1.f else f end-a+t1.f then 19 else t1.b end+11 end-t1.d-17 or t1.b<>t1.a),13)-t1.b | 11 FROM t1 WHERE (+(17)-(select cast(avg( -((17)*case t1.b when 13+f then t1.f else t1.b end)) AS integer) | case case cast(avg(e) AS integer) when abs((case (~min(t1.c)) when max(t1.e) then cast(avg(t1.b) AS integer) else (( -count(*))) end-max(b)))+(min(t1.c)) then -cast(avg(c) AS integer) else min(f) end when cast(avg(17) AS integer) then max(f) else (min(d)) end from t1)+e+c*19>=13)} +} {-209} +do_test randexpr-2.2147 { + db eval {SELECT coalesce((select max(~19) from t1 where t1.a between case t1.c when t1.b then t1.e else +~f end and case when 19 not in (e+b,t1.e-d,(select max(e) from t1)) then t1.a else case 13 when case e when e then t1.f else f end-a+t1.f then 19 else t1.b end+11 end-t1.d-17 or t1.b<>t1.a),13)-t1.b | 11 FROM t1 WHERE NOT ((+(17)-(select cast(avg( -((17)*case t1.b when 13+f then t1.f else t1.b end)) AS integer) | case case cast(avg(e) AS integer) when abs((case (~min(t1.c)) when max(t1.e) then cast(avg(t1.b) AS integer) else (( -count(*))) end-max(b)))+(min(t1.c)) then -cast(avg(c) AS integer) else min(f) end when cast(avg(17) AS integer) then max(f) else (min(d)) end from t1)+e+c*19>=13))} +} {} +do_test randexpr-2.2148 { + db eval {SELECT coalesce((select max(~19) from t1 where t1.a between case t1.c when t1.b then t1.e else +~f end and case when 19 not in (e+b,t1.e-d,(select max(e) from t1)) then t1.a else case 13 when case e when e then t1.f else f end-a+t1.f then 19 else t1.b end+11 end-t1.d-17 or t1.b<>t1.a),13)-t1.b & 11 FROM t1 WHERE (+(17)-(select cast(avg( -((17)*case t1.b when 13+f then t1.f else t1.b end)) AS integer) | case case cast(avg(e) AS integer) when abs((case (~min(t1.c)) when max(t1.e) then cast(avg(t1.b) AS integer) else (( -count(*))) end-max(b)))+(min(t1.c)) then -cast(avg(c) AS integer) else min(f) end when cast(avg(17) AS integer) then max(f) else (min(d)) end from t1)+e+c*19>=13)} +} {0} +do_test randexpr-2.2149 { + db eval {SELECT coalesce((select max(e) from t1 where 11>=coalesce((select max(b) from t1 where (abs(13)/abs(coalesce((select max(11) from t1 where f not between t1.a and t1.d),t1.d)))=case when 11 in (select (11 | d)-coalesce((select t1.e | coalesce((select t1.e from t1 where t1.f in (select 13 from t1 union select t1.c from t1) and d in (select t1.b from t1 union select 17 from t1)),(c))-17-19 from t1 where (t1.b)<=t1.b),(d)) from t1 union select t1.d from t1) then t1.a else (b) end),c)),19) FROM t1 WHERE ~t1.b not in (~++(select (case ~ -min( -11) when abs(count(*)*count(*)) then +~max(t1.a-11 | (19)) else case abs((cast(avg(f) AS integer)))-count(distinct t1.a) when (( -(max(a)))) then (min(t1.d)) else (min(a)) end end) from t1)+(abs(+t1.b)/abs(a))-t1.f+~t1.d+b+t1.c,13,e)} +} {19} +do_test randexpr-2.2150 { + db eval {SELECT coalesce((select max(e) from t1 where 11>=coalesce((select max(b) from t1 where (abs(13)/abs(coalesce((select max(11) from t1 where f not between t1.a and t1.d),t1.d)))=case when 11 in (select (11 | d)-coalesce((select t1.e | coalesce((select t1.e from t1 where t1.f in (select 13 from t1 union select t1.c from t1) and d in (select t1.b from t1 union select 17 from t1)),(c))-17-19 from t1 where (t1.b)<=t1.b),(d)) from t1 union select t1.d from t1) then t1.a else (b) end),c)),19) FROM t1 WHERE NOT (~t1.b not in (~++(select (case ~ -min( -11) when abs(count(*)*count(*)) then +~max(t1.a-11 | (19)) else case abs((cast(avg(f) AS integer)))-count(distinct t1.a) when (( -(max(a)))) then (min(t1.d)) else (min(a)) end end) from t1)+(abs(+t1.b)/abs(a))-t1.f+~t1.d+b+t1.c,13,e))} +} {} +do_test randexpr-2.2151 { + db eval {SELECT coalesce((select max(e) from t1 where 11>=coalesce((select max(b) from t1 where (abs(13)/abs(coalesce((select max(11) from t1 where f not between t1.a and t1.d),t1.d)))=case when 11 in (select (11 & d)-coalesce((select t1.e & coalesce((select t1.e from t1 where t1.f in (select 13 from t1 union select t1.c from t1) and d in (select t1.b from t1 union select 17 from t1)),(c))-17-19 from t1 where (t1.b)<=t1.b),(d)) from t1 union select t1.d from t1) then t1.a else (b) end),c)),19) FROM t1 WHERE ~t1.b not in (~++(select (case ~ -min( -11) when abs(count(*)*count(*)) then +~max(t1.a-11 | (19)) else case abs((cast(avg(f) AS integer)))-count(distinct t1.a) when (( -(max(a)))) then (min(t1.d)) else (min(a)) end end) from t1)+(abs(+t1.b)/abs(a))-t1.f+~t1.d+b+t1.c,13,e)} +} {19} +do_test randexpr-2.2152 { + db eval {SELECT (abs(+b)/abs(coalesce((select max(t1.b) from t1 where (not t1.a not between t1.c-(abs(b)/abs(d)) and c)),19)+19*t1.e | t1.e))-t1.f*coalesce((select case d when e*t1.d*f then 17 else t1.c+t1.c end from t1 where t1.b>=(select count(*) from t1)),+f+t1.b-t1.b+19- -b) FROM t1 WHERE not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where not (b>=(abs(case when case (select count(*) from t1) when t1.a then a+case t1.f when a+ -t1.a*t1.d then 19 else e end+t1.a+f else -d end>=e then f when t1.b>=t1.d or not dt1.b then t1.e else d end)/abs(f)) or a>e))))} +} {-360000} +do_test randexpr-2.2153 { + db eval {SELECT (abs(+b)/abs(coalesce((select max(t1.b) from t1 where (not t1.a not between t1.c-(abs(b)/abs(d)) and c)),19)+19*t1.e | t1.e))-t1.f*coalesce((select case d when e*t1.d*f then 17 else t1.c+t1.c end from t1 where t1.b>=(select count(*) from t1)),+f+t1.b-t1.b+19- -b) FROM t1 WHERE NOT (not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where not (b>=(abs(case when case (select count(*) from t1) when t1.a then a+case t1.f when a+ -t1.a*t1.d then 19 else e end+t1.a+f else -d end>=e then f when t1.b>=t1.d or not dt1.b then t1.e else d end)/abs(f)) or a>e)))))} +} {} +do_test randexpr-2.2154 { + db eval {SELECT (abs(+b)/abs(coalesce((select max(t1.b) from t1 where (not t1.a not between t1.c-(abs(b)/abs(d)) and c)),19)+19*t1.e & t1.e))-t1.f*coalesce((select case d when e*t1.d*f then 17 else t1.c+t1.c end from t1 where t1.b>=(select count(*) from t1)),+f+t1.b-t1.b+19- -b) FROM t1 WHERE not exists(select 1 from t1 where not exists(select 1 from t1 where not exists(select 1 from t1 where not (b>=(abs(case when case (select count(*) from t1) when t1.a then a+case t1.f when a+ -t1.a*t1.d then 19 else e end+t1.a+f else -d end>=e then f when t1.b>=t1.d or not dt1.b then t1.e else d end)/abs(f)) or a>e))))} +} {-360000} +do_test randexpr-2.2155 { + db eval {SELECT (abs((select +abs(case count(*) when +max(19) then count(distinct b)*count(distinct (13+(select max(t1.d) from t1)* -a+t1.e*t1.b*a))+cast(avg(13) AS integer) | min(13)*cast(avg(c) AS integer)-count(distinct t1.e)-((min(f))) | cast(avg(17) AS integer)-( -cast(avg(( -t1.d)) AS integer))- -cast(avg(t1.d) AS integer) | count(*) else max(t1.f) end) from t1))/abs(t1.a)) FROM t1 WHERE b<=e or exists(select 1 from t1 where 17 in (select ~e+coalesce((select d from t1 where 11* -~+case when not (b) not between t1.f and b then -~t1.c-11*+19+((b)) when f not between f and 11 then b else a end+11-(b)-t1.f<>17),d) from t1 union select t1.a from t1))} +} {6} +do_test randexpr-2.2156 { + db eval {SELECT (abs((select +abs(case count(*) when +max(19) then count(distinct b)*count(distinct (13+(select max(t1.d) from t1)* -a+t1.e*t1.b*a))+cast(avg(13) AS integer) | min(13)*cast(avg(c) AS integer)-count(distinct t1.e)-((min(f))) | cast(avg(17) AS integer)-( -cast(avg(( -t1.d)) AS integer))- -cast(avg(t1.d) AS integer) | count(*) else max(t1.f) end) from t1))/abs(t1.a)) FROM t1 WHERE NOT (b<=e or exists(select 1 from t1 where 17 in (select ~e+coalesce((select d from t1 where 11* -~+case when not (b) not between t1.f and b then -~t1.c-11*+19+((b)) when f not between f and 11 then b else a end+11-(b)-t1.f<>17),d) from t1 union select t1.a from t1)))} +} {} +do_test randexpr-2.2157 { + db eval {SELECT (abs((select +abs(case count(*) when +max(19) then count(distinct b)*count(distinct (13+(select max(t1.d) from t1)* -a+t1.e*t1.b*a))+cast(avg(13) AS integer) & min(13)*cast(avg(c) AS integer)-count(distinct t1.e)-((min(f))) & cast(avg(17) AS integer)-( -cast(avg(( -t1.d)) AS integer))- -cast(avg(t1.d) AS integer) & count(*) else max(t1.f) end) from t1))/abs(t1.a)) FROM t1 WHERE b<=e or exists(select 1 from t1 where 17 in (select ~e+coalesce((select d from t1 where 11* -~+case when not (b) not between t1.f and b then -~t1.c-11*+19+((b)) when f not between f and 11 then b else a end+11-(b)-t1.f<>17),d) from t1 union select t1.a from t1))} +} {6} +do_test randexpr-2.2158 { + db eval {SELECT coalesce((select max(11) from t1 where c=(abs(coalesce((select case when t1.c-t1.f+coalesce((select max(b) from t1 where case when (11<>17) then t1.c else c end in (select b from t1 union select t1.b from t1) and 13=11),f)+t1.b>=t1.f then 11 when c>t1.f then 19 else 19 end from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (e>19)))),t1.d))/abs(b)) and -t1.d between t1.b and 13 or 17<>t1.e), -((11))) FROM t1 WHERE case when case when (not exists(select 1 from t1 where 19 not between case when coalesce((select b from t1 where (abs(t1.c)/abs(17))+t1.e between case when not exists(select 1 from t1 where not a<=t1.e) then t1.e when d17) then t1.c else c end in (select b from t1 union select t1.b from t1) and 13=11),f)+t1.b>=t1.f then 11 when c>t1.f then 19 else 19 end from t1 where exists(select 1 from t1 where not exists(select 1 from t1 where (e>19)))),t1.d))/abs(b)) and -t1.d between t1.b and 13 or 17<>t1.e), -((11))) FROM t1 WHERE NOT (case when case when (not exists(select 1 from t1 where 19 not between case when coalesce((select b from t1 where (abs(t1.c)/abs(17))+t1.e between case when not exists(select 1 from t1 where not a<=t1.e) then t1.e when d(t1.c)} +} {-2600247} +do_test randexpr-2.2161 { + db eval {SELECT coalesce((select ( -t1.e*(abs((case when not 13 not in (case coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where d between -b and f)),11) when 11 then 19 else a end,t1.a,t1.a) then f-t1.f when t1.c in (select -abs(count(*)+(max((t1.a)))) from t1 union select -max((19)) from t1) then d else 13 end-19))/abs(t1.b))-t1.d*e-19) from t1 where t1.e not between 13 and c),19)*13 FROM t1 WHERE NOT (19<>(t1.c))} +} {} +do_test randexpr-2.2162 { + db eval {SELECT coalesce((select max(13) from t1 where f= -case when exists(select 1 from t1 where not t1.b>=e and b in (select b from t1 union select (+(t1.f-d)) from t1) or 19 in (select min(e) from t1 union select -~+++ -abs(min(17*t1.d)) from t1) or not t1.a>a) then 13 else t1.c end+a | ~11),19) FROM t1 WHERE (exists(select 1 from t1 where t1.c>19)) and a>d-a} +} {} +do_test randexpr-2.2163 { + db eval {SELECT coalesce((select max(13) from t1 where f= -case when exists(select 1 from t1 where not t1.b>=e and b in (select b from t1 union select (+(t1.f-d)) from t1) or 19 in (select min(e) from t1 union select -~+++ -abs(min(17*t1.d)) from t1) or not t1.a>a) then 13 else t1.c end+a | ~11),19) FROM t1 WHERE NOT ((exists(select 1 from t1 where t1.c>19)) and a>d-a)} +} {19} +do_test randexpr-2.2164 { + db eval {SELECT coalesce((select max(13) from t1 where f= -case when exists(select 1 from t1 where not t1.b>=e and b in (select b from t1 union select (+(t1.f-d)) from t1) or 19 in (select min(e) from t1 union select -~+++ -abs(min(17*t1.d)) from t1) or not t1.a>a) then 13 else t1.c end+a & ~11),19) FROM t1 WHERE NOT ((exists(select 1 from t1 where t1.c>19)) and a>d-a)} +} {19} +do_test randexpr-2.2165 { + db eval {SELECT coalesce((select case when a between (select count(distinct 19) from t1) and case when de then b*t1.e else a end) from t1 where t1.e=t1.e),t1.f) from t1 where (d not between 13 and (f))),17)-d) from t1 where (11<>19)),t1.e)+t1.c)/abs(t1.e))*11*c-t1.d*t1.d+a end FROM t1 WHERE 13-e*t1.e=19),(abs(e)/abs((abs( -d+e)/abs(a))))+t1.a) from t1 where t1.b in (t1.e,(t1.e),t1.f)),f))=t1.e)) or b<=19),t1.b)<=13) then 13 else t1.f end-f} +} {-159900} +do_test randexpr-2.2168 { + db eval {SELECT case 17 when -b then e*c else (abs(coalesce((select max(coalesce((select coalesce((select max(case when t1.d<=19 and t1.d>e then b*t1.e else a end) from t1 where t1.e=t1.e),t1.f) from t1 where (d not between 13 and (f))),17)-d) from t1 where (11<>19)),t1.e)+t1.c)/abs(t1.e))*11*c-t1.d*t1.d+a end FROM t1 WHERE NOT (13-e*t1.e=19),(abs(e)/abs((abs( -d+e)/abs(a))))+t1.a) from t1 where t1.b in (t1.e,(t1.e),t1.f)),f))=t1.e)) or b<=19),t1.b)<=13) then 13 else t1.f end-f)} +} {} +do_test randexpr-2.2169 { + db eval {SELECT case when case when e*(d-case a when 13 then (19) else d end) between 13 and f then f when exists(select 1 from t1 where 19<>t1.a) then e else b end in (select -max(e)+min(11)-case ~~cast(avg(t1.c) AS integer) when max(19) then max(f) else -cast(avg(f) AS integer) end from t1 union select -max(13) from t1) and f>d and (t1.f=c) then t1.b else t1.c+ -t1.f end FROM t1 WHERE t1.e+11>=~t1.a-11} +} {-300} +do_test randexpr-2.2170 { + db eval {SELECT case when case when e*(d-case a when 13 then (19) else d end) between 13 and f then f when exists(select 1 from t1 where 19<>t1.a) then e else b end in (select -max(e)+min(11)-case ~~cast(avg(t1.c) AS integer) when max(19) then max(f) else -cast(avg(f) AS integer) end from t1 union select -max(13) from t1) and f>d and (t1.f=c) then t1.b else t1.c+ -t1.f end FROM t1 WHERE NOT (t1.e+11>=~t1.a-11)} +} {} +do_test randexpr-2.2171 { + db eval {SELECT coalesce((select t1.f from t1 where not (abs(coalesce((select 17*13+(select cast(avg(t1.a) AS integer)-(count(distinct t1.c)*+cast(avg((select count(*) from t1)) AS integer))+count(*) from t1) from t1 where (select count(distinct t1.d*(((t1.d)))+f) from t1) in ( -b*t1.e-11,t1.d,d) and exists(select 1 from t1 where t1.d>c)),t1.e))/abs(b)) not in (t1.f,11,d)),t1.d) FROM t1 WHERE exists(select 1 from t1 where +t1.c-case when exists(select 1 from t1 where (select +case count(distinct case when 19*d in (select (cast(avg(11) AS integer)*cast(avg( -13) AS integer)) from t1 union select count(*) from t1) then t1.c else 13 end) when count(*) then count(*) else (min(t1.b)) end from t1)<>case when (not t1.ft1.d then case when f>=17 then t1.a else t1.e end else b end) then 11+t1.f when d<>17 then t1.e else a end- -13<>e) and t1.a<=17} +} {} +do_test randexpr-2.2172 { + db eval {SELECT coalesce((select t1.f from t1 where not (abs(coalesce((select 17*13+(select cast(avg(t1.a) AS integer)-(count(distinct t1.c)*+cast(avg((select count(*) from t1)) AS integer))+count(*) from t1) from t1 where (select count(distinct t1.d*(((t1.d)))+f) from t1) in ( -b*t1.e-11,t1.d,d) and exists(select 1 from t1 where t1.d>c)),t1.e))/abs(b)) not in (t1.f,11,d)),t1.d) FROM t1 WHERE NOT (exists(select 1 from t1 where +t1.c-case when exists(select 1 from t1 where (select +case count(distinct case when 19*d in (select (cast(avg(11) AS integer)*cast(avg( -13) AS integer)) from t1 union select count(*) from t1) then t1.c else 13 end) when count(*) then count(*) else (min(t1.b)) end from t1)<>case when (not t1.ft1.d then case when f>=17 then t1.a else t1.e end else b end) then 11+t1.f when d<>17 then t1.e else a end- -13<>e) and t1.a<=17)} +} {400} +do_test randexpr-2.2173 { + db eval {SELECT case when not (select - -count(distinct t1.f)-(max(case when e not between f and t1.b+(13)+ -d-t1.a then t1.d else 11 end))+ -max(t1.b)*cast(avg(13) AS integer)-count(*) | (max(t1.e)) from t1)<>~t1.d then b when -coalesce((select (abs(t1.e)/abs(t1.b)) from t1 where a<>b), - -17)<=t1.a then -f else 11 end FROM t1 WHERE t1.a<>(select max(19) from t1)} +} {-600} +do_test randexpr-2.2174 { + db eval {SELECT case when not (select - -count(distinct t1.f)-(max(case when e not between f and t1.b+(13)+ -d-t1.a then t1.d else 11 end))+ -max(t1.b)*cast(avg(13) AS integer)-count(*) | (max(t1.e)) from t1)<>~t1.d then b when -coalesce((select (abs(t1.e)/abs(t1.b)) from t1 where a<>b), - -17)<=t1.a then -f else 11 end FROM t1 WHERE NOT (t1.a<>(select max(19) from t1))} +} {} +do_test randexpr-2.2175 { + db eval {SELECT case when not (select - -count(distinct t1.f)-(max(case when e not between f and t1.b+(13)+ -d-t1.a then t1.d else 11 end))+ -max(t1.b)*cast(avg(13) AS integer)-count(*) & (max(t1.e)) from t1)<>~t1.d then b when -coalesce((select (abs(t1.e)/abs(t1.b)) from t1 where a<>b), - -17)<=t1.a then -f else 11 end FROM t1 WHERE t1.a<>(select max(19) from t1)} +} {-600} +do_test randexpr-2.2176 { + db eval {SELECT case when case coalesce((select t1.d+a*11 from t1 where e<=t1.d),19) when 19 then -t1.d-t1.a else t1.e end not between 17 and d then t1.f when not (t1.c<=e and ((13<>e or t1.c not between t1.c and 13)) or t1.c=17 and t1.a not in (t1.e, -t1.d,t1.b) and b=b then t1.d else 13 end FROM t1 WHERE (case t1.f when t1.b then case when case when not exists(select 1 from t1 where (t1.d+t1.a in (c,coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where (t1.a>=c))),+b), -t1.b))) then (select abs( -case ((abs( - - -count(*)+count(*)))) when min(d) then -(cast(avg(t1.d) AS integer)) else cast(avg(e) AS integer) end | ((max((t1.f)))))+(min(t1.c)) from t1) else 11 end>f then 19 else t1.b end else b end)<=13 or (t1.f>b)} +} {600} +do_test randexpr-2.2177 { + db eval {SELECT case when case coalesce((select t1.d+a*11 from t1 where e<=t1.d),19) when 19 then -t1.d-t1.a else t1.e end not between 17 and d then t1.f when not (t1.c<=e and ((13<>e or t1.c not between t1.c and 13)) or t1.c=17 and t1.a not in (t1.e, -t1.d,t1.b) and b=b then t1.d else 13 end FROM t1 WHERE NOT ((case t1.f when t1.b then case when case when not exists(select 1 from t1 where (t1.d+t1.a in (c,coalesce((select max(t1.c) from t1 where exists(select 1 from t1 where (t1.a>=c))),+b), -t1.b))) then (select abs( -case ((abs( - - -count(*)+count(*)))) when min(d) then -(cast(avg(t1.d) AS integer)) else cast(avg(e) AS integer) end | ((max((t1.f)))))+(min(t1.c)) from t1) else 11 end>f then 19 else t1.b end else b end)<=13 or (t1.f>b))} +} {} +do_test randexpr-2.2178 { + db eval {SELECT (((d)+t1.f))-case +t1.d when coalesce((select max(13) from t1 where (select -max(17*case when d>=coalesce((select 19 from t1 where a<>t1.e),t1.b) then e when -c<>d then e else t1.a end*t1.f)+ -case count(*) when (+cast(avg(c) AS integer)) then count(*) else -count(distinct t1.f) end+count(*) from t1)<=(abs(t1.c)/abs(t1.f))),17) then 17 else t1.d end-t1.b FROM t1 WHERE ~d-c in (select cast(avg(19) AS integer) from t1 union select - -abs((abs((cast(avg(f) AS integer)) | abs(count(distinct 19))))) from t1)} +} {} +do_test randexpr-2.2179 { + db eval {SELECT (((d)+t1.f))-case +t1.d when coalesce((select max(13) from t1 where (select -max(17*case when d>=coalesce((select 19 from t1 where a<>t1.e),t1.b) then e when -c<>d then e else t1.a end*t1.f)+ -case count(*) when (+cast(avg(c) AS integer)) then count(*) else -count(distinct t1.f) end+count(*) from t1)<=(abs(t1.c)/abs(t1.f))),17) then 17 else t1.d end-t1.b FROM t1 WHERE NOT (~d-c in (select cast(avg(19) AS integer) from t1 union select - -abs((abs((cast(avg(f) AS integer)) | abs(count(distinct 19))))) from t1))} +} {400} +do_test randexpr-2.2180 { + db eval {SELECT coalesce((select max(f+t1.c*b) from t1 where (select abs(cast(avg(f) AS integer)) from t1)-c*~ -b+ -coalesce((select max(t1.a) from t1 where (select cast(avg((c) | ~t1.d) AS integer) from t1) not between t1.d-+(abs(t1.d)/abs(t1.c))+d and 11 and 17>=t1.e),t1.e)-b in (t1.c,d,e)),a)+c FROM t1 WHERE 19*e not in (a,t1.d,coalesce((select coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where not exists(select 1 from t1 where e*case when ~c | f+11* -a in ( -t1.c,17,(t1.b)) then (f) when e=e or t1.d=f and (e)>(e) then (11) else a end+a*c in (select d from t1 union select -11 from t1))))),t1.f) from t1 where t1.d<=d),13))} +} {400} +do_test randexpr-2.2181 { + db eval {SELECT coalesce((select max(f+t1.c*b) from t1 where (select abs(cast(avg(f) AS integer)) from t1)-c*~ -b+ -coalesce((select max(t1.a) from t1 where (select cast(avg((c) | ~t1.d) AS integer) from t1) not between t1.d-+(abs(t1.d)/abs(t1.c))+d and 11 and 17>=t1.e),t1.e)-b in (t1.c,d,e)),a)+c FROM t1 WHERE NOT (19*e not in (a,t1.d,coalesce((select coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where not exists(select 1 from t1 where e*case when ~c | f+11* -a in ( -t1.c,17,(t1.b)) then (f) when e=e or t1.d=f and (e)>(e) then (11) else a end+a*c in (select d from t1 union select -11 from t1))))),t1.f) from t1 where t1.d<=d),13)))} +} {} +do_test randexpr-2.2182 { + db eval {SELECT coalesce((select max(f+t1.c*b) from t1 where (select abs(cast(avg(f) AS integer)) from t1)-c*~ -b+ -coalesce((select max(t1.a) from t1 where (select cast(avg((c) & ~t1.d) AS integer) from t1) not between t1.d-+(abs(t1.d)/abs(t1.c))+d and 11 and 17>=t1.e),t1.e)-b in (t1.c,d,e)),a)+c FROM t1 WHERE 19*e not in (a,t1.d,coalesce((select coalesce((select max(t1.d) from t1 where (exists(select 1 from t1 where not exists(select 1 from t1 where e*case when ~c | f+11* -a in ( -t1.c,17,(t1.b)) then (f) when e=e or t1.d=f and (e)>(e) then (11) else a end+a*c in (select d from t1 union select -11 from t1))))),t1.f) from t1 where t1.d<=d),13))} +} {400} +do_test randexpr-2.2183 { + db eval {SELECT c*~case ((abs(t1.b)/abs(t1.b))) when c then e else t1.c end-(case when (c)>=case coalesce((select max((abs(d)/abs(c))) from t1 where 13 not in (a-t1.e-(select count(*) | min(e)+min(c) from t1)*19*t1.b,11,a)),e) when e then b else t1.d end then d when 17<11 then c else t1.d end) | t1.f FROM t1 WHERE case when not (abs(t1.d | (abs( - -coalesce((select max(coalesce((select c+e from t1 where not t1.b in ((c),b,(f))),t1.b)) from t1 where 11=b),t1.f)+13*t1.f*e)/abs(t1.e)))/abs(t1.b))>=c then coalesce((select (t1.c) from t1 where t1.e in (11,e,t1.a)),a) when 13<=t1.b then t1.f else t1.d end in (select e from t1 union select (t1.d) from t1)} +} {} +do_test randexpr-2.2184 { + db eval {SELECT c*~case ((abs(t1.b)/abs(t1.b))) when c then e else t1.c end-(case when (c)>=case coalesce((select max((abs(d)/abs(c))) from t1 where 13 not in (a-t1.e-(select count(*) | min(e)+min(c) from t1)*19*t1.b,11,a)),e) when e then b else t1.d end then d when 17<11 then c else t1.d end) | t1.f FROM t1 WHERE NOT (case when not (abs(t1.d | (abs( - -coalesce((select max(coalesce((select c+e from t1 where not t1.b in ((c),b,(f))),t1.b)) from t1 where 11=b),t1.f)+13*t1.f*e)/abs(t1.e)))/abs(t1.b))>=c then coalesce((select (t1.c) from t1 where t1.e in (11,e,t1.a)),a) when 13<=t1.b then t1.f else t1.d end in (select e from t1 union select (t1.d) from t1))} +} {-90116} +do_test randexpr-2.2185 { + db eval {SELECT c*~case ((abs(t1.b)/abs(t1.b))) when c then e else t1.c end-(case when (c)>=case coalesce((select max((abs(d)/abs(c))) from t1 where 13 not in (a-t1.e-(select count(*) & min(e)+min(c) from t1)*19*t1.b,11,a)),e) when e then b else t1.d end then d when 17<11 then c else t1.d end) & t1.f FROM t1 WHERE NOT (case when not (abs(t1.d | (abs( - -coalesce((select max(coalesce((select c+e from t1 where not t1.b in ((c),b,(f))),t1.b)) from t1 where 11=b),t1.f)+13*t1.f*e)/abs(t1.e)))/abs(t1.b))>=c then coalesce((select (t1.c) from t1 where t1.e in (11,e,t1.a)),a) when 13<=t1.b then t1.f else t1.d end in (select e from t1 union select (t1.d) from t1))} +} {16} +do_test randexpr-2.2186 { + db eval {SELECT case when a+13*+ -~case when 17=t1.c*17 then 19 | (t1.b) when f+t1.e+(d)+b+c not between (d) and e or (a between t1.b and t1.a) then 17 else a end-17-(e)<=17 then b when c in (select 17 from t1 union select t1.a from t1) then c else t1.e end FROM t1 WHERE e-coalesce((select f-case 17+t1.a*(abs(t1.e)/abs((abs(coalesce((select max(+ -case when t1.a>=d then c else t1.e end-d) from t1 where (not exists(select 1 from t1 where (t1.d in ( -f,d,t1.b))) or -t1.f not between -b and t1.b)),11))/abs(13)))) when 13 then d else t1.f end from t1 where t1.e in ((19),t1.e,17) or e>=t1.d),e)<>17 or 19<=19} +} {200} +do_test randexpr-2.2187 { + db eval {SELECT case when a+13*+ -~case when 17=t1.c*17 then 19 | (t1.b) when f+t1.e+(d)+b+c not between (d) and e or (a between t1.b and t1.a) then 17 else a end-17-(e)<=17 then b when c in (select 17 from t1 union select t1.a from t1) then c else t1.e end FROM t1 WHERE NOT (e-coalesce((select f-case 17+t1.a*(abs(t1.e)/abs((abs(coalesce((select max(+ -case when t1.a>=d then c else t1.e end-d) from t1 where (not exists(select 1 from t1 where (t1.d in ( -f,d,t1.b))) or -t1.f not between -b and t1.b)),11))/abs(13)))) when 13 then d else t1.f end from t1 where t1.e in ((19),t1.e,17) or e>=t1.d),e)<>17 or 19<=19)} +} {} +do_test randexpr-2.2188 { + db eval {SELECT case when a+13*+ -~case when 17=t1.c*17 then 19 & (t1.b) when f+t1.e+(d)+b+c not between (d) and e or (a between t1.b and t1.a) then 17 else a end-17-(e)<=17 then b when c in (select 17 from t1 union select t1.a from t1) then c else t1.e end FROM t1 WHERE e-coalesce((select f-case 17+t1.a*(abs(t1.e)/abs((abs(coalesce((select max(+ -case when t1.a>=d then c else t1.e end-d) from t1 where (not exists(select 1 from t1 where (t1.d in ( -f,d,t1.b))) or -t1.f not between -b and t1.b)),11))/abs(13)))) when 13 then d else t1.f end from t1 where t1.e in ((19),t1.e,17) or e>=t1.d),e)<>17 or 19<=19} +} {200} +do_test randexpr-2.2189 { + db eval {SELECT 17-t1.a*(select abs(~count(*)*abs(count(distinct a)) | (~count(distinct case (a* -coalesce((select a from t1 where (13 in (select max((abs(t1.e)/abs(case when not exists(select 1 from t1 where (b<>c)) then (11)-t1.f-e else e end))) from t1 union select (count(distinct 11)) from t1))),t1.b)+11) when (17) then e else f end))) from t1) FROM t1 WHERE 13>case (e) when t1.a then t1.a else 11 end-t1.b} +} {-183} +do_test randexpr-2.2190 { + db eval {SELECT 17-t1.a*(select abs(~count(*)*abs(count(distinct a)) | (~count(distinct case (a* -coalesce((select a from t1 where (13 in (select max((abs(t1.e)/abs(case when not exists(select 1 from t1 where (b<>c)) then (11)-t1.f-e else e end))) from t1 union select (count(distinct 11)) from t1))),t1.b)+11) when (17) then e else f end))) from t1) FROM t1 WHERE NOT (13>case (e) when t1.a then t1.a else 11 end-t1.b)} +} {} +do_test randexpr-2.2191 { + db eval {SELECT 17-t1.a*(select abs(~count(*)*abs(count(distinct a)) & (~count(distinct case (a* -coalesce((select a from t1 where (13 in (select max((abs(t1.e)/abs(case when not exists(select 1 from t1 where (b<>c)) then (11)-t1.f-e else e end))) from t1 union select (count(distinct 11)) from t1))),t1.b)+11) when (17) then e else f end))) from t1) FROM t1 WHERE 13>case (e) when t1.a then t1.a else 11 end-t1.b} +} {-183} +do_test randexpr-2.2192 { + db eval {SELECT case when t1.b= -b then e else (select -(count(distinct t1.a))*max(c)-count(*)+count(distinct t1.b+d)*min(t1.f-case when 19 in (select t1.d from t1 union select e from t1) then 17 when f<=t1.c then t1.b else e end-(d)*c)-count(distinct t1.d)*case +max(f) when max(17) | max(d) | -(cast(avg(d) AS integer)) then -cast(avg(11) AS integer) else -count(distinct 11) end*min(t1.d) from t1) end FROM t1 WHERE t1.f>=f} +} {-119801} +do_test randexpr-2.2193 { + db eval {SELECT case when t1.b= -b then e else (select -(count(distinct t1.a))*max(c)-count(*)+count(distinct t1.b+d)*min(t1.f-case when 19 in (select t1.d from t1 union select e from t1) then 17 when f<=t1.c then t1.b else e end-(d)*c)-count(distinct t1.d)*case +max(f) when max(17) | max(d) | -(cast(avg(d) AS integer)) then -cast(avg(11) AS integer) else -count(distinct 11) end*min(t1.d) from t1) end FROM t1 WHERE NOT (t1.f>=f)} +} {} +do_test randexpr-2.2194 { + db eval {SELECT case when t1.b= -b then e else (select -(count(distinct t1.a))*max(c)-count(*)+count(distinct t1.b+d)*min(t1.f-case when 19 in (select t1.d from t1 union select e from t1) then 17 when f<=t1.c then t1.b else e end-(d)*c)-count(distinct t1.d)*case +max(f) when max(17) & max(d) & -(cast(avg(d) AS integer)) then -cast(avg(11) AS integer) else -count(distinct 11) end*min(t1.d) from t1) end FROM t1 WHERE t1.f>=f} +} {-119801} +do_test randexpr-2.2195 { + db eval {SELECT -~f | (abs(13+t1.b)/abs((select max(t1.b | t1.f+ -17-11) | +case min(e) when count(*) | case (~ -min(c)*cast(avg(19) AS integer)) when -count(*) then min(a) else min(13) end then -((max(t1.c))) else max(e) end-(count(distinct -t1.a)) from t1)))+~(abs((abs(case when a<>19 then t1.a when f>17 then a else b end)/abs(t1.b)))/abs(t1.f)) FROM t1 WHERE (17 between t1.f*(abs(b)/abs((abs((select max(17) from t1) | 17)/abs(13))+c-coalesce((select max(d) from t1 where d between f-a-11-d and a+t1.a+d-t1.b+17+13),case when a not between a and t1.b then t1.d when t1.d not in ((e),a,d) then c else b end*d))) and b and t1.e> -17)} +} {} +do_test randexpr-2.2196 { + db eval {SELECT -~f | (abs(13+t1.b)/abs((select max(t1.b | t1.f+ -17-11) | +case min(e) when count(*) | case (~ -min(c)*cast(avg(19) AS integer)) when -count(*) then min(a) else min(13) end then -((max(t1.c))) else max(e) end-(count(distinct -t1.a)) from t1)))+~(abs((abs(case when a<>19 then t1.a when f>17 then a else b end)/abs(t1.b)))/abs(t1.f)) FROM t1 WHERE NOT ((17 between t1.f*(abs(b)/abs((abs((select max(17) from t1) | 17)/abs(13))+c-coalesce((select max(d) from t1 where d between f-a-11-d and a+t1.a+d-t1.b+17+13),case when a not between a and t1.b then t1.d when t1.d not in ((e),a,d) then c else b end*d))) and b and t1.e> -17))} +} {-1} +do_test randexpr-2.2197 { + db eval {SELECT (select abs(abs( -case case ~count(distinct t1.f+(t1.f)+coalesce((select (abs(t1.e+(b)+a)/abs(11))+b from t1 where exists(select 1 from t1 where t1.f not in (t1.b,(b),e) and not (t1.b)>c)),f)) when ~count(*)-min(t1.f) then +(count(*))*( -count(*)-max(t1.a)) else min(11) end when count(distinct (f)) then -count(distinct a) else count(*) end | count(distinct 13))) from t1) FROM t1 WHERE exists(select 1 from t1 where case when t1.f>(abs(b)/abs(a)) then ~case when t1.e+13-b<=(coalesce((select max(11) from t1 where (select abs(min(11)) from t1) in (select case d when f then 17 else t1.f end from t1 union select t1.f from t1)),b)*13)-19 then 11 when not 19 between t1.c and t1.b then a else e end-t1.a when (t1.a) not between b and t1.f then t1.a else c end=t1.e)} +} {} +do_test randexpr-2.2198 { + db eval {SELECT (select abs(abs( -case case ~count(distinct t1.f+(t1.f)+coalesce((select (abs(t1.e+(b)+a)/abs(11))+b from t1 where exists(select 1 from t1 where t1.f not in (t1.b,(b),e) and not (t1.b)>c)),f)) when ~count(*)-min(t1.f) then +(count(*))*( -count(*)-max(t1.a)) else min(11) end when count(distinct (f)) then -count(distinct a) else count(*) end | count(distinct 13))) from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where case when t1.f>(abs(b)/abs(a)) then ~case when t1.e+13-b<=(coalesce((select max(11) from t1 where (select abs(min(11)) from t1) in (select case d when f then 17 else t1.f end from t1 union select t1.f from t1)),b)*13)-19 then 11 when not 19 between t1.c and t1.b then a else e end-t1.a when (t1.a) not between b and t1.f then t1.a else c end=t1.e))} +} {1} +do_test randexpr-2.2199 { + db eval {SELECT (select abs(abs( -case case ~count(distinct t1.f+(t1.f)+coalesce((select (abs(t1.e+(b)+a)/abs(11))+b from t1 where exists(select 1 from t1 where t1.f not in (t1.b,(b),e) and not (t1.b)>c)),f)) when ~count(*)-min(t1.f) then +(count(*))*( -count(*)-max(t1.a)) else min(11) end when count(distinct (f)) then -count(distinct a) else count(*) end & count(distinct 13))) from t1) FROM t1 WHERE NOT (exists(select 1 from t1 where case when t1.f>(abs(b)/abs(a)) then ~case when t1.e+13-b<=(coalesce((select max(11) from t1 where (select abs(min(11)) from t1) in (select case d when f then 17 else t1.f end from t1 union select t1.f from t1)),b)*13)-19 then 11 when not 19 between t1.c and t1.b then a else e end-t1.a when (t1.a) not between b and t1.f then t1.a else c end=t1.e))} +} {1} +do_test randexpr-2.2200 { + db eval {SELECT 19 | t1.a*(select case max(case when t1.b*17>=t1.b then coalesce((select max(e) from t1 where e in (select count(*) from t1 union select count(distinct t1.f) from t1)),d) when t1.a in (select min(11) from t1 union select (( -( -max(t1.f)))) from t1) and 17 in (select count(distinct 17) from t1 union select -count(distinct d) from t1) and (d)<>t1.c and t1.c not between b and b then a else 11 end)+cast(avg(t1.a) AS integer) when ~count(distinct t1.e) then count(distinct d) else count(distinct e) end from t1) | e*t1.b-t1.d FROM t1 WHERE (((abs(19)/abs(case ~c*d+(abs(e)/abs((coalesce((select case when (f in (select count(*) from t1 union select -min(d) from t1)) then case when -t1.f between t1.c and t1.f then b when 11<>a then t1.a else t1.c end when 13=13 then 13 else t1.a end from t1 where 19 not between 11 and t1.b or t1.b not in ((e),(b),c)),a)- -((t1.c))-c)))+t1.b+17 when 13 then ((13)) else t1.f end*t1.b)) in ( -17,t1.a,11)))} +} {} +do_test randexpr-2.2201 { + db eval {SELECT 19 | t1.a*(select case max(case when t1.b*17>=t1.b then coalesce((select max(e) from t1 where e in (select count(*) from t1 union select count(distinct t1.f) from t1)),d) when t1.a in (select min(11) from t1 union select (( -( -max(t1.f)))) from t1) and 17 in (select count(distinct 17) from t1 union select -count(distinct d) from t1) and (d)<>t1.c and t1.c not between b and b then a else 11 end)+cast(avg(t1.a) AS integer) when ~count(distinct t1.e) then count(distinct d) else count(distinct e) end from t1) | e*t1.b-t1.d FROM t1 WHERE NOT ((((abs(19)/abs(case ~c*d+(abs(e)/abs((coalesce((select case when (f in (select count(*) from t1 union select -min(d) from t1)) then case when -t1.f between t1.c and t1.f then b when 11<>a then t1.a else t1.c end when 13=13 then 13 else t1.a end from t1 where 19 not between 11 and t1.b or t1.b not in ((e),(b),c)),a)- -((t1.c))-c)))+t1.b+17 when 13 then ((13)) else t1.f end*t1.b)) in ( -17,t1.a,11))))} +} {99703} +do_test randexpr-2.2202 { + db eval {SELECT 19 & t1.a*(select case max(case when t1.b*17>=t1.b then coalesce((select max(e) from t1 where e in (select count(*) from t1 union select count(distinct t1.f) from t1)),d) when t1.a in (select min(11) from t1 union select (( -( -max(t1.f)))) from t1) and 17 in (select count(distinct 17) from t1 union select -count(distinct d) from t1) and (d)<>t1.c and t1.c not between b and b then a else 11 end)+cast(avg(t1.a) AS integer) when ~count(distinct t1.e) then count(distinct d) else count(distinct e) end from t1) & e*t1.b-t1.d FROM t1 WHERE NOT ((((abs(19)/abs(case ~c*d+(abs(e)/abs((coalesce((select case when (f in (select count(*) from t1 union select -min(d) from t1)) then case when -t1.f between t1.c and t1.f then b when 11<>a then t1.a else t1.c end when 13=13 then 13 else t1.a end from t1 where 19 not between 11 and t1.b or t1.b not in ((e),(b),c)),a)- -((t1.c))-c)))+t1.b+17 when 13 then ((13)) else t1.f end*t1.b)) in ( -17,t1.a,11))))} +} {0} +do_test randexpr-2.2203 { + db eval {SELECT c-coalesce((select -coalesce((select max(case when (abs(~~case when case when t1.e<=e and t1.f>t1.d then b when t1.a<>t1.a then 17 else 17 end+t1.c>=t1.a then (c) when c not in (f,e,t1.c) then t1.d else 13 end)/abs(t1.a))c),t1.a)*19 FROM t1 WHERE (17) | case when 19 not in ((case when (e*19=f) then case t1.f when a then 13 else t1.d end when bt1.b) then f else a end in (select c from t1 union select -13 from t1) or 17 in (select 19 from t1 union select d from t1) and t1.b in (c,b,19) and t1.b>=( -b)} +} {} +do_test randexpr-2.2204 { + db eval {SELECT c-coalesce((select -coalesce((select max(case when (abs(~~case when case when t1.e<=e and t1.f>t1.d then b when t1.a<>t1.a then 17 else 17 end+t1.c>=t1.a then (c) when c not in (f,e,t1.c) then t1.d else 13 end)/abs(t1.a))c),t1.a)*19 FROM t1 WHERE NOT ((17) | case when 19 not in ((case when (e*19=f) then case t1.f when a then 13 else t1.d end when bt1.b) then f else a end in (select c from t1 union select -13 from t1) or 17 in (select 19 from t1 union select d from t1) and t1.b in (c,b,19) and t1.b>=( -b))} +} {-1600} +do_test randexpr-2.2205 { + db eval {SELECT 13+case when not (t1.d in (11,f,t1.a)) then coalesce((select +t1.e from t1 where case t1.e when t1.b then 19+t1.a+~e+a*t1.a else 11 end not between 19 and 19),(abs(t1.f-case when (19)=17 then t1.c else t1.f end)/abs(19)) from t1 union select c from t1)), -d)) from t1))/abs(t1.d))) from t1)*(c) | 11+t1.c*t1.b) from t1 union select cast(avg(t1.c) AS integer) from t1)} +} {} +do_test randexpr-2.2206 { + db eval {SELECT 13+case when not (t1.d in (11,f,t1.a)) then coalesce((select +t1.e from t1 where case t1.e when t1.b then 19+t1.a+~e+a*t1.a else 11 end not between 19 and 19),(abs(t1.f-case when (19)=17 then t1.c else t1.f end)/abs(19)) from t1 union select c from t1)), -d)) from t1))/abs(t1.d))) from t1)*(c) | 11+t1.c*t1.b) from t1 union select cast(avg(t1.c) AS integer) from t1))} +} {400013} +do_test randexpr-2.2207 { + db eval {SELECT case when -11-t1.b-f-t1.b>~c then t1.e else case when t1.d<>b*~17+t1.d*(select max(+(select count(distinct t1.a)+ -cast(avg(d) AS integer)*max(13) from t1)) from t1) or (abs(c)/abs(c)) not in (11,d,t1.c) then 13 when d in (select f from t1 union select b from t1) then t1.f else -t1.a end+ -f end FROM t1 WHERE ~t1.b*19-d not between ~b and t1.f} +} {-587} +do_test randexpr-2.2208 { + db eval {SELECT case when -11-t1.b-f-t1.b>~c then t1.e else case when t1.d<>b*~17+t1.d*(select max(+(select count(distinct t1.a)+ -cast(avg(d) AS integer)*max(13) from t1)) from t1) or (abs(c)/abs(c)) not in (11,d,t1.c) then 13 when d in (select f from t1 union select b from t1) then t1.f else -t1.a end+ -f end FROM t1 WHERE NOT (~t1.b*19-d not between ~b and t1.f)} +} {} +do_test randexpr-2.2209 { + db eval {SELECT coalesce((select t1.b from t1 where coalesce((select max(coalesce((select max(t1.a) from t1 where t1.c=t1.e),case b-f when f then e else 13 end-t1.d)) from t1 where not exists(select 1 from t1 where -t1.f>=17)),a)*(19) in (select max(d) from t1 union select case -count(*) when +count(distinct (t1.f)) then min(t1.d) else count(*) end from t1) and a<=f and d not between b and 19 and not exists(select 1 from t1 where b between t1.c and e or c<>t1.f)),17) FROM t1 WHERE t1.a-19<>c*d} +} {17} +do_test randexpr-2.2210 { + db eval {SELECT coalesce((select t1.b from t1 where coalesce((select max(coalesce((select max(t1.a) from t1 where t1.c=t1.e),case b-f when f then e else 13 end-t1.d)) from t1 where not exists(select 1 from t1 where -t1.f>=17)),a)*(19) in (select max(d) from t1 union select case -count(*) when +count(distinct (t1.f)) then min(t1.d) else count(*) end from t1) and a<=f and d not between b and 19 and not exists(select 1 from t1 where b between t1.c and e or c<>t1.f)),17) FROM t1 WHERE NOT (t1.a-19<>c*d)} +} {} +do_test randexpr-2.2211 { + db eval {SELECT (coalesce((select case (select ~count(*) | max(b+t1.b)+case max((abs(+coalesce((select max(f) from t1 where not (17=e)),t1.f))/abs(b))*a) when -~~ -(cast(avg(13) AS integer)) | count(*) then min(13) else count(*) end-count(distinct d) from t1) when 17+t1.d then t1.a else 13 end from t1 where e not between 13 and 11),11)+t1.e+b) FROM t1 WHERE not f in (select t1.e from t1 union select t1.f from t1) or 13 not in (t1.b | t1.e,t1.f,d) or (abs(f)/abs(+(abs(f+(select max(case when ((13<>t1.c)) then 13 else t1.c end) | ~min(t1.a)+cast(avg(a) AS integer) from t1)*(d)-b)/abs(d))*e))-t1.b not in (t1.c,f,t1.d) and t1.b<>t1.f} +} {713} +do_test randexpr-2.2212 { + db eval {SELECT (coalesce((select case (select ~count(*) | max(b+t1.b)+case max((abs(+coalesce((select max(f) from t1 where not (17=e)),t1.f))/abs(b))*a) when -~~ -(cast(avg(13) AS integer)) | count(*) then min(13) else count(*) end-count(distinct d) from t1) when 17+t1.d then t1.a else 13 end from t1 where e not between 13 and 11),11)+t1.e+b) FROM t1 WHERE NOT (not f in (select t1.e from t1 union select t1.f from t1) or 13 not in (t1.b | t1.e,t1.f,d) or (abs(f)/abs(+(abs(f+(select max(case when ((13<>t1.c)) then 13 else t1.c end) | ~min(t1.a)+cast(avg(a) AS integer) from t1)*(d)-b)/abs(d))*e))-t1.b not in (t1.c,f,t1.d) and t1.b<>t1.f)} +} {} +do_test randexpr-2.2213 { + db eval {SELECT (coalesce((select case (select ~count(*) & max(b+t1.b)+case max((abs(+coalesce((select max(f) from t1 where not (17=e)),t1.f))/abs(b))*a) when -~~ -(cast(avg(13) AS integer)) & count(*) then min(13) else count(*) end-count(distinct d) from t1) when 17+t1.d then t1.a else 13 end from t1 where e not between 13 and 11),11)+t1.e+b) FROM t1 WHERE not f in (select t1.e from t1 union select t1.f from t1) or 13 not in (t1.b | t1.e,t1.f,d) or (abs(f)/abs(+(abs(f+(select max(case when ((13<>t1.c)) then 13 else t1.c end) | ~min(t1.a)+cast(avg(a) AS integer) from t1)*(d)-b)/abs(d))*e))-t1.b not in (t1.c,f,t1.d) and t1.b<>t1.f} +} {713} +do_test randexpr-2.2214 { + db eval {SELECT t1.b-c*a*t1.b+ -f | (case when 1317)} +} {-6000392} +do_test randexpr-2.2215 { + db eval {SELECT t1.b-c*a*t1.b+ -f | (case when 1317))} +} {} +do_test randexpr-2.2216 { + db eval {SELECT t1.b-c*a*t1.b+ -f & (case when 1317)} +} {192} +do_test randexpr-2.2217 { + db eval {SELECT ~(select (abs(cast(avg(((b)-d*t1.a-c+17+f+e+ -17)) AS integer))) from t1)*t1.c++ -(11-t1.b*~f-e*t1.b)-coalesce((select max(case when not c=13 then 17 else b end) from t1 where (t1.a>17)),c) | -f-f FROM t1 WHERE a+coalesce((select max(coalesce((select max(f) from t1 where ((not b in (select t1.b from t1 union select (select -cast(avg(t1.b) AS integer) from t1) from t1)) or not t1.d= -t1.c and 19<=t1.c)),t1.f)-coalesce((select c from t1 where d<=t1.a), -e)) from t1 where d in (select t1.d from t1 union select t1.d from t1)),t1.d)-a | t1.b>(f) or t1.d between 19 and t1.c and exists(select 1 from t1 where b=13) and not 13 not in (t1.d,(c),d) and e not between 17 and 13} +} {-1040} +do_test randexpr-2.2218 { + db eval {SELECT ~(select (abs(cast(avg(((b)-d*t1.a-c+17+f+e+ -17)) AS integer))) from t1)*t1.c++ -(11-t1.b*~f-e*t1.b)-coalesce((select max(case when not c=13 then 17 else b end) from t1 where (t1.a>17)),c) | -f-f FROM t1 WHERE NOT (a+coalesce((select max(coalesce((select max(f) from t1 where ((not b in (select t1.b from t1 union select (select -cast(avg(t1.b) AS integer) from t1) from t1)) or not t1.d= -t1.c and 19<=t1.c)),t1.f)-coalesce((select c from t1 where d<=t1.a), -e)) from t1 where d in (select t1.d from t1 union select t1.d from t1)),t1.d)-a | t1.b>(f) or t1.d between 19 and t1.c and exists(select 1 from t1 where b=13) and not 13 not in (t1.d,(c),d) and e not between 17 and 13)} +} {} +do_test randexpr-2.2219 { + db eval {SELECT ~(select (abs(cast(avg(((b)-d*t1.a-c+17+f+e+ -17)) AS integer))) from t1)*t1.c++ -(11-t1.b*~f-e*t1.b)-coalesce((select max(case when not c=13 then 17 else b end) from t1 where (t1.a>17)),c) & -f-f FROM t1 WHERE a+coalesce((select max(coalesce((select max(f) from t1 where ((not b in (select t1.b from t1 union select (select -cast(avg(t1.b) AS integer) from t1) from t1)) or not t1.d= -t1.c and 19<=t1.c)),t1.f)-coalesce((select c from t1 where d<=t1.a), -e)) from t1 where d in (select t1.d from t1 union select t1.d from t1)),t1.d)-a | t1.b>(f) or t1.d between 19 and t1.c and exists(select 1 from t1 where b=13) and not 13 not in (t1.d,(c),d) and e not between 17 and 13} +} {-11720688} +do_test randexpr-2.2220 { + db eval {SELECT case when t1.a in (select count(*) from t1 union select cast(avg(t1.a) AS integer)*count(distinct 17) | -count(*) from t1) then ~coalesce((select max(19+t1.a) from t1 where +d=t1.a),case t1.c-(select count(*) from t1) when coalesce((select (abs((select (cast(avg(13) AS integer)) from t1))/abs(13)) from t1 where f<~13-(t1.a)*19),d) then a else 19 end) | b when t1.d>a then f else b end FROM t1 WHERE 19<=case when (t1.a*11*19-e<>(select abs(min(e))+case -abs(abs( - -( -(( -max(c)))))-(min(c))) when min(e) then -(min(f)) else - -min(t1.a) end from t1)*t1.d) then e+f+coalesce((select max(e-a) from t1 where (t1.b) between 11 and -t1.c),c) when t1.c<=17 then 17 else t1.b end and 19<>t1.f} +} {600} +do_test randexpr-2.2221 { + db eval {SELECT case when t1.a in (select count(*) from t1 union select cast(avg(t1.a) AS integer)*count(distinct 17) | -count(*) from t1) then ~coalesce((select max(19+t1.a) from t1 where +d=t1.a),case t1.c-(select count(*) from t1) when coalesce((select (abs((select (cast(avg(13) AS integer)) from t1))/abs(13)) from t1 where f<~13-(t1.a)*19),d) then a else 19 end) | b when t1.d>a then f else b end FROM t1 WHERE NOT (19<=case when (t1.a*11*19-e<>(select abs(min(e))+case -abs(abs( - -( -(( -max(c)))))-(min(c))) when min(e) then -(min(f)) else - -min(t1.a) end from t1)*t1.d) then e+f+coalesce((select max(e-a) from t1 where (t1.b) between 11 and -t1.c),c) when t1.c<=17 then 17 else t1.b end and 19<>t1.f)} +} {} +do_test randexpr-2.2222 { + db eval {SELECT case when t1.a in (select count(*) from t1 union select cast(avg(t1.a) AS integer)*count(distinct 17) & -count(*) from t1) then ~coalesce((select max(19+t1.a) from t1 where +d=t1.a),case t1.c-(select count(*) from t1) when coalesce((select (abs((select (cast(avg(13) AS integer)) from t1))/abs(13)) from t1 where f<~13-(t1.a)*19),d) then a else 19 end) & b when t1.d>a then f else b end FROM t1 WHERE 19<=case when (t1.a*11*19-e<>(select abs(min(e))+case -abs(abs( - -( -(( -max(c)))))-(min(c))) when min(e) then -(min(f)) else - -min(t1.a) end from t1)*t1.d) then e+f+coalesce((select max(e-a) from t1 where (t1.b) between 11 and -t1.c),c) when t1.c<=17 then 17 else t1.b end and 19<>t1.f} +} {200} +do_test randexpr-2.2223 { + db eval {SELECT c-case when t1.e>coalesce((select case -t1.d-case when d in (select -t1.f from t1 union select t1.c+t1.c from t1) and (t1.a<=t1.a) then 11*(17) when d between 11 and e or -c<>t1.f then 19 else 19 end+11 when 19 then b else t1.b end-t1.a from t1 where not e<=f),( -t1.f)) then b when ((dcoalesce((select case -t1.d-case when d in (select -t1.f from t1 union select t1.c+t1.c from t1) and (t1.a<=t1.a) then 11*(17) when d between 11 and e or -c<>t1.f then 19 else 19 end+11 when 19 then b else t1.b end-t1.a from t1 where not e<=f),( -t1.f)) then b when ((dt1.d),d)>=13 then coalesce((select -17+e from t1 where t1.a<=19),b) else (19) end FROM t1 WHERE (abs( -t1.f)/abs(t1.a))<=t1.d} +} {200} +do_test randexpr-2.2229 { + db eval {SELECT case when not (select -case (( -(count(*)) | cast(avg(d) AS integer))) | min((e)) when cast(avg(d) AS integer) then count(*) else count(distinct t1.e) end+max((17)) | max(t1.a)+ -count(*) from t1)-e in (t1.a,11-t1.d,t1.b) and coalesce((select max(t1.c) from t1 where case t1.d when t1.f then d else b end<>t1.d),d)>=13 then coalesce((select -17+e from t1 where t1.a<=19),b) else (19) end FROM t1 WHERE NOT ((abs( -t1.f)/abs(t1.a))<=t1.d)} +} {} +do_test randexpr-2.2230 { + db eval {SELECT case when not (select -case (( -(count(*)) & cast(avg(d) AS integer))) & min((e)) when cast(avg(d) AS integer) then count(*) else count(distinct t1.e) end+max((17)) & max(t1.a)+ -count(*) from t1)-e in (t1.a,11-t1.d,t1.b) and coalesce((select max(t1.c) from t1 where case t1.d when t1.f then d else b end<>t1.d),d)>=13 then coalesce((select -17+e from t1 where t1.a<=19),b) else (19) end FROM t1 WHERE (abs( -t1.f)/abs(t1.a))<=t1.d} +} {200} +do_test randexpr-2.2231 { + db eval {SELECT case when 13 in (select cast(avg(11) AS integer) from t1 union select count(*) from t1) then t1.f-case c-(abs(d+~+t1.d-(abs(13)/abs(t1.e-t1.b-t1.c))*e)/abs(17*19+t1.e)) when 19 then 17 else a end when (t1.a in (select count(distinct 13) from t1 union select max(t1.f) from t1)) and c between ((c)) and (t1.a) then c else 19 end+t1.e FROM t1 WHERE 19<>t1.c} +} {519} +do_test randexpr-2.2232 { + db eval {SELECT case when 13 in (select cast(avg(11) AS integer) from t1 union select count(*) from t1) then t1.f-case c-(abs(d+~+t1.d-(abs(13)/abs(t1.e-t1.b-t1.c))*e)/abs(17*19+t1.e)) when 19 then 17 else a end when (t1.a in (select count(distinct 13) from t1 union select max(t1.f) from t1)) and c between ((c)) and (t1.a) then c else 19 end+t1.e FROM t1 WHERE NOT (19<>t1.c)} +} {} +do_test randexpr-2.2233 { + db eval {SELECT coalesce((select max(case when not exists(select 1 from t1 where coalesce((select a from t1 where (t1.c+t1.d<=t1.b and exists(select 1 from t1 where t1.f not in (~case when t1.d>d then t1.a else a end,( -e),t1.b))) and (c<>17)),e) in (select e from t1 union select d from t1)) then case when b not in (a,17,e) or f=t1.e then t1.d else d end else a end*19) from t1 where ((t1.c not between e and t1.e))),13) FROM t1 WHERE c not in (~t1.e,t1.e,a)} +} {1900} +do_test randexpr-2.2234 { + db eval {SELECT coalesce((select max(case when not exists(select 1 from t1 where coalesce((select a from t1 where (t1.c+t1.d<=t1.b and exists(select 1 from t1 where t1.f not in (~case when t1.d>d then t1.a else a end,( -e),t1.b))) and (c<>17)),e) in (select e from t1 union select d from t1)) then case when b not in (a,17,e) or f=t1.e then t1.d else d end else a end*19) from t1 where ((t1.c not between e and t1.e))),13) FROM t1 WHERE NOT (c not in (~t1.e,t1.e,a))} +} {} +do_test randexpr-2.2235 { + db eval {SELECT coalesce((select t1.f from t1 where d+(select count(distinct e) from t1)+~+ -~e-a+t1.a-b- -a*coalesce((select c-t1.d*case when ( -11<=e or b>= - -c and t1.c19),t1.f) FROM t1 WHERE t1.f<>c} +} {600} +do_test randexpr-2.2236 { + db eval {SELECT coalesce((select t1.f from t1 where d+(select count(distinct e) from t1)+~+ -~e-a+t1.a-b- -a*coalesce((select c-t1.d*case when ( -11<=e or b>= - -c and t1.c19),t1.f) FROM t1 WHERE NOT (t1.f<>c)} +} {} +do_test randexpr-2.2237 { + db eval {SELECT 19+case when d between t1.b and 19+t1.d*(select ~min(t1.e | a) from t1)-case when exists(select 1 from t1 where 19<>t1.a and 19 between case +19 when 19 then t1.e else e end and t1.a) then a when t1.a between 13 and f or (t1.f<19) and d>=t1.c and f not between a and t1.b then a else t1.d end then b else t1.a end+ -d FROM t1 WHERE f>=t1.d+(t1.a)} +} {-281} +do_test randexpr-2.2238 { + db eval {SELECT 19+case when d between t1.b and 19+t1.d*(select ~min(t1.e | a) from t1)-case when exists(select 1 from t1 where 19<>t1.a and 19 between case +19 when 19 then t1.e else e end and t1.a) then a when t1.a between 13 and f or (t1.f<19) and d>=t1.c and f not between a and t1.b then a else t1.d end then b else t1.a end+ -d FROM t1 WHERE NOT (f>=t1.d+(t1.a))} +} {} +do_test randexpr-2.2239 { + db eval {SELECT 19+case when d between t1.b and 19+t1.d*(select ~min(t1.e & a) from t1)-case when exists(select 1 from t1 where 19<>t1.a and 19 between case +19 when 19 then t1.e else e end and t1.a) then a when t1.a between 13 and f or (t1.f<19) and d>=t1.c and f not between a and t1.b then a else t1.d end then b else t1.a end+ -d FROM t1 WHERE f>=t1.d+(t1.a)} +} {-281} +do_test randexpr-2.2240 { + db eval {SELECT t1.d+(select case max(t1.f) when count(distinct ~coalesce((select case when 17 in (select t1.b from t1 union select t1.e from t1) then c when (d<= -(abs(t1.a)/abs(t1.d))) then t1.b+ -case when t1.bt1.a or t1.d>=t1.f),t1.a)-e)<=t1.e} +} {902} +do_test randexpr-2.2241 { + db eval {SELECT t1.d+(select case max(t1.f) when count(distinct ~coalesce((select case when 17 in (select t1.b from t1 union select t1.e from t1) then c when (d<= -(abs(t1.a)/abs(t1.d))) then t1.b+ -case when t1.bt1.a or t1.d>=t1.f),t1.a)-e)<=t1.e)} +} {} +do_test randexpr-2.2242 { + db eval {SELECT t1.d+(select case max(t1.f) when count(distinct ~coalesce((select case when 17 in (select t1.b from t1 union select t1.e from t1) then c when (d<= -(abs(t1.a)/abs(t1.d))) then t1.b+ -case when t1.bt1.a or t1.d>=t1.f),t1.a)-e)<=t1.e} +} {902} +do_test randexpr-2.2243 { + db eval {SELECT (select count(distinct (select case ~abs(~+abs(case (max(17)) when max(coalesce((select ~b from t1 where (not exists(select 1 from t1 where -17<>f or t1.d>=b and 19 between 19 and t1.b))),(abs(case when 19<>a then t1.c else t1.b end)/abs(19)))) then ~+cast(avg(19) AS integer) else min(t1.a) end) | case min(13) when max(11) then count(distinct -d) else count(distinct t1.d) end)*max(t1.d) when count(*) then -min(e) else (count(*)) end+count(*) from t1)) from t1) FROM t1 WHERE (d in (select abs(count(*) | case max((case when b<=13 then t1.b*e when case when t1.c between t1.d and a then t1.a when (f< -19) then t1.c else d end between t1.d and b then t1.e else t1.b end))-max((t1.c)) when max(t1.f) then -abs(+cast(avg(19) AS integer)) else abs(max(t1.c)) end++max(17))- -cast(avg(f) AS integer) from t1 union select min(11) from t1))} +} {} +do_test randexpr-2.2244 { + db eval {SELECT (select count(distinct (select case ~abs(~+abs(case (max(17)) when max(coalesce((select ~b from t1 where (not exists(select 1 from t1 where -17<>f or t1.d>=b and 19 between 19 and t1.b))),(abs(case when 19<>a then t1.c else t1.b end)/abs(19)))) then ~+cast(avg(19) AS integer) else min(t1.a) end) | case min(13) when max(11) then count(distinct -d) else count(distinct t1.d) end)*max(t1.d) when count(*) then -min(e) else (count(*)) end+count(*) from t1)) from t1) FROM t1 WHERE NOT ((d in (select abs(count(*) | case max((case when b<=13 then t1.b*e when case when t1.c between t1.d and a then t1.a when (f< -19) then t1.c else d end between t1.d and b then t1.e else t1.b end))-max((t1.c)) when max(t1.f) then -abs(+cast(avg(19) AS integer)) else abs(max(t1.c)) end++max(17))- -cast(avg(f) AS integer) from t1 union select min(11) from t1)))} +} {1} +do_test randexpr-2.2245 { + db eval {SELECT (select count(distinct (select case ~abs(~+abs(case (max(17)) when max(coalesce((select ~b from t1 where (not exists(select 1 from t1 where -17<>f or t1.d>=b and 19 between 19 and t1.b))),(abs(case when 19<>a then t1.c else t1.b end)/abs(19)))) then ~+cast(avg(19) AS integer) else min(t1.a) end) & case min(13) when max(11) then count(distinct -d) else count(distinct t1.d) end)*max(t1.d) when count(*) then -min(e) else (count(*)) end+count(*) from t1)) from t1) FROM t1 WHERE NOT ((d in (select abs(count(*) | case max((case when b<=13 then t1.b*e when case when t1.c between t1.d and a then t1.a when (f< -19) then t1.c else d end between t1.d and b then t1.e else t1.b end))-max((t1.c)) when max(t1.f) then -abs(+cast(avg(19) AS integer)) else abs(max(t1.c)) end++max(17))- -cast(avg(f) AS integer) from t1 union select min(11) from t1)))} +} {1} +do_test randexpr-2.2246 { + db eval {SELECT case d*coalesce((select e from t1 where t1.f in (case when not exists(select 1 from t1 where 19>=(+f-13)) then case when not not exists(select 1 from t1 where 17>=t1.d-13) then f else d end else t1.c end,c,+(abs(e)/abs(19*d | case 19 when b then 17 else b end-b))) or e between 13 and a),19) when b then c else t1.b end FROM t1 WHERE t1.b<=coalesce((select coalesce((select t1.a from t1 where not t1.b*(select max(t1.d) from t1)=(+f-13)) then case when not not exists(select 1 from t1 where 17>=t1.d-13) then f else d end else t1.c end,c,+(abs(e)/abs(19*d | case 19 when b then 17 else b end-b))) or e between 13 and a),19) when b then c else t1.b end FROM t1 WHERE NOT (t1.b<=coalesce((select coalesce((select t1.a from t1 where not t1.b*(select max(t1.d) from t1) -c then (b)* -19 else t1.d end<=11 or 17 not between t1.f and 13 or a not in (t1.c,t1.b,11) then c else c end<>t1.a and (f) in (select cast(avg(11) AS integer) from t1 union select case max(b) when (min(t1.c)) then count(distinct f) else max(19) end from t1) then 13 else d end | f-t1.d<=t1.f then f else 19 end FROM t1 WHERE ((f not between t1.f and d))} +} {600} +do_test randexpr-2.2251 { + db eval {SELECT case when case when case when case when t1.b<> -c then (b)* -19 else t1.d end<=11 or 17 not between t1.f and 13 or a not in (t1.c,t1.b,11) then c else c end<>t1.a and (f) in (select cast(avg(11) AS integer) from t1 union select case max(b) when (min(t1.c)) then count(distinct f) else max(19) end from t1) then 13 else d end | f-t1.d<=t1.f then f else 19 end FROM t1 WHERE NOT (((f not between t1.f and d)))} +} {} +do_test randexpr-2.2252 { + db eval {SELECT case when case when case when case when t1.b<> -c then (b)* -19 else t1.d end<=11 or 17 not between t1.f and 13 or a not in (t1.c,t1.b,11) then c else c end<>t1.a and (f) in (select cast(avg(11) AS integer) from t1 union select case max(b) when (min(t1.c)) then count(distinct f) else max(19) end from t1) then 13 else d end & f-t1.d<=t1.f then f else 19 end FROM t1 WHERE ((f not between t1.f and d))} +} {600} +do_test randexpr-2.2253 { + db eval {SELECT d-b-(abs(a)/abs(coalesce((select b from t1 where coalesce((select t1.f from t1 where 13>=f-b),t1.c)*case when coalesce((select case (d*t1.e+b) when t1.a-13 then - -t1.d else t1.a end+13 from t1 where e>=t1.f),11) | b=case when coalesce((select max(case when f<>~b | coalesce((select max(11*c) from t1 where 17=t1.f),t1.d)*d then b when a in (c,(t1.d),(f)) then a else 19 end-t1.f) from t1 where not 13 in (select cast(avg(t1.b) AS integer)-cast(avg( -t1.a) AS integer) from t1 union select count(*) from t1)),17) not in ((t1.f),c, -19) and e between 11 and (19) then 19 else t1.d end} +} {199} +do_test randexpr-2.2254 { + db eval {SELECT d-b-(abs(a)/abs(coalesce((select b from t1 where coalesce((select t1.f from t1 where 13>=f-b),t1.c)*case when coalesce((select case (d*t1.e+b) when t1.a-13 then - -t1.d else t1.a end+13 from t1 where e>=t1.f),11) | b=case when coalesce((select max(case when f<>~b | coalesce((select max(11*c) from t1 where 17=t1.f),t1.d)*d then b when a in (c,(t1.d),(f)) then a else 19 end-t1.f) from t1 where not 13 in (select cast(avg(t1.b) AS integer)-cast(avg( -t1.a) AS integer) from t1 union select count(*) from t1)),17) not in ((t1.f),c, -19) and e between 11 and (19) then 19 else t1.d end)} +} {} +do_test randexpr-2.2255 { + db eval {SELECT d-b-(abs(a)/abs(coalesce((select b from t1 where coalesce((select t1.f from t1 where 13>=f-b),t1.c)*case when coalesce((select case (d*t1.e+b) when t1.a-13 then - -t1.d else t1.a end+13 from t1 where e>=t1.f),11) & b=case when coalesce((select max(case when f<>~b | coalesce((select max(11*c) from t1 where 17=t1.f),t1.d)*d then b when a in (c,(t1.d),(f)) then a else 19 end-t1.f) from t1 where not 13 in (select cast(avg(t1.b) AS integer)-cast(avg( -t1.a) AS integer) from t1 union select count(*) from t1)),17) not in ((t1.f),c, -19) and e between 11 and (19) then 19 else t1.d end} +} {199} +do_test randexpr-2.2256 { + db eval {SELECT coalesce((select max(coalesce((select 13 from t1 where not t1.b<>e*b),t1.c*case when d>=case case 13 when coalesce((select ~~t1.f*(abs(t1.f)/abs(t1.e))-e | -t1.b from t1 where a in (11,13,t1.e)),d)*t1.e then -e else t1.b end when t1.e then 11 else t1.e end then -f else c end) | t1.a) from t1 where e>t1.d), -(t1.f)) FROM t1 WHERE not -13 in (select (+(case case min(a+t1.a) when abs(count(*)-count(distinct t1.d-+(f)-case 19 when b then t1.b else a end)) then case count(*)*max(c) when ~ -count(*)*cast(avg(t1.e) AS integer)*count(distinct -a) then count(*) else cast(avg(19) AS integer) end else cast(avg(b) AS integer) end when min(f) then max( -a) else (count(*)) end)*count(distinct t1.f)-count(*)) from t1 union select count(distinct f) from t1)} +} {90100} +do_test randexpr-2.2257 { + db eval {SELECT coalesce((select max(coalesce((select 13 from t1 where not t1.b<>e*b),t1.c*case when d>=case case 13 when coalesce((select ~~t1.f*(abs(t1.f)/abs(t1.e))-e | -t1.b from t1 where a in (11,13,t1.e)),d)*t1.e then -e else t1.b end when t1.e then 11 else t1.e end then -f else c end) | t1.a) from t1 where e>t1.d), -(t1.f)) FROM t1 WHERE NOT (not -13 in (select (+(case case min(a+t1.a) when abs(count(*)-count(distinct t1.d-+(f)-case 19 when b then t1.b else a end)) then case count(*)*max(c) when ~ -count(*)*cast(avg(t1.e) AS integer)*count(distinct -a) then count(*) else cast(avg(19) AS integer) end else cast(avg(b) AS integer) end when min(f) then max( -a) else (count(*)) end)*count(distinct t1.f)-count(*)) from t1 union select count(distinct f) from t1))} +} {} +do_test randexpr-2.2258 { + db eval {SELECT coalesce((select max(coalesce((select 13 from t1 where not t1.b<>e*b),t1.c*case when d>=case case 13 when coalesce((select ~~t1.f*(abs(t1.f)/abs(t1.e))-e & -t1.b from t1 where a in (11,13,t1.e)),d)*t1.e then -e else t1.b end when t1.e then 11 else t1.e end then -f else c end) & t1.a) from t1 where e>t1.d), -(t1.f)) FROM t1 WHERE not -13 in (select (+(case case min(a+t1.a) when abs(count(*)-count(distinct t1.d-+(f)-case 19 when b then t1.b else a end)) then case count(*)*max(c) when ~ -count(*)*cast(avg(t1.e) AS integer)*count(distinct -a) then count(*) else cast(avg(19) AS integer) end else cast(avg(b) AS integer) end when min(f) then max( -a) else (count(*)) end)*count(distinct t1.f)-count(*)) from t1 union select count(distinct f) from t1)} +} {0} +do_test randexpr-2.2259 { + db eval {SELECT coalesce((select max(t1.e*~t1.b- -t1.b-t1.b-coalesce((select t1.a from t1 where exists(select 1 from t1 where ~d+case case when a between b and f then 13 else -17 end-13 when -19 then t1.f else d end+t1.b<>e or not t1.e between 19 and t1.a or 11 in (19,c, -19))),a)*e) from t1 where t1.f<19),t1.e)-13 FROM t1 WHERE t1.b not between e and 13} +} {487} +do_test randexpr-2.2260 { + db eval {SELECT coalesce((select max(t1.e*~t1.b- -t1.b-t1.b-coalesce((select t1.a from t1 where exists(select 1 from t1 where ~d+case case when a between b and f then 13 else -17 end-13 when -19 then t1.f else d end+t1.b<>e or not t1.e between 19 and t1.a or 11 in (19,c, -19))),a)*e) from t1 where t1.f<19),t1.e)-13 FROM t1 WHERE NOT (t1.b not between e and 13)} +} {} +do_test randexpr-2.2261 { + db eval {SELECT (select (count(distinct case t1.d+case when (coalesce((select max((select + -cast(avg(b) AS integer)-min(19) | (cast(avg(19) AS integer)) from t1)) from t1 where ~c+t1.ct1.a and f between t1.e and d and f<=19 then t1.f else t1.b end-c*a when t1.f then e else t1.b end)) from t1) FROM t1 WHERE not b*c+d<>b} +} {} +do_test randexpr-2.2262 { + db eval {SELECT (select (count(distinct case t1.d+case when (coalesce((select max((select + -cast(avg(b) AS integer)-min(19) | (cast(avg(19) AS integer)) from t1)) from t1 where ~c+t1.ct1.a and f between t1.e and d and f<=19 then t1.f else t1.b end-c*a when t1.f then e else t1.b end)) from t1) FROM t1 WHERE NOT (not b*c+d<>b)} +} {1} +do_test randexpr-2.2263 { + db eval {SELECT (select (count(distinct case t1.d+case when (coalesce((select max((select + -cast(avg(b) AS integer)-min(19) & (cast(avg(19) AS integer)) from t1)) from t1 where ~c+t1.ct1.a and f between t1.e and d and f<=19 then t1.f else t1.b end-c*a when t1.f then e else t1.b end)) from t1) FROM t1 WHERE NOT (not b*c+d<>b)} +} {1} +do_test randexpr-2.2264 { + db eval {SELECT t1.b+case case c when f-((abs(t1.f)/abs(coalesce((select max(f+t1.d | t1.c*e+f+~case when c not between b and t1.a or 11<19 then c-d else t1.f end+e-t1.b*11+t1.e) from t1 where 17 not between e and 19),19)))) then d else a end when (t1.c) then t1.f else f end FROM t1 WHERE (b)-t1.c*19-t1.b>17*b-13} +} {} +do_test randexpr-2.2265 { + db eval {SELECT t1.b+case case c when f-((abs(t1.f)/abs(coalesce((select max(f+t1.d | t1.c*e+f+~case when c not between b and t1.a or 11<19 then c-d else t1.f end+e-t1.b*11+t1.e) from t1 where 17 not between e and 19),19)))) then d else a end when (t1.c) then t1.f else f end FROM t1 WHERE NOT ((b)-t1.c*19-t1.b>17*b-13)} +} {800} +do_test randexpr-2.2266 { + db eval {SELECT t1.b+case case c when f-((abs(t1.f)/abs(coalesce((select max(f+t1.d & t1.c*e+f+~case when c not between b and t1.a or 11<19 then c-d else t1.f end+e-t1.b*11+t1.e) from t1 where 17 not between e and 19),19)))) then d else a end when (t1.c) then t1.f else f end FROM t1 WHERE NOT ((b)-t1.c*19-t1.b>17*b-13)} +} {800} +do_test randexpr-2.2267 { + db eval {SELECT coalesce((select coalesce((select ((abs(19)/abs(17))) from t1 where +13 | d>d),13-(select abs(abs(~count(*)))+~count(*) from t1)+(t1.c*t1.e*(abs(19+(13))/abs(a)))-coalesce((select 17 from t1 where c<>e and b not in ((d),t1.b,b)),t1.c)+t1.d)-13 from t1 where t1.f19 then 17 else t1.c end)-count(*))) then max(11) else +max(b) end) from t1))} +} {} +do_test randexpr-2.2268 { + db eval {SELECT coalesce((select coalesce((select ((abs(19)/abs(17))) from t1 where +13 | d>d),13-(select abs(abs(~count(*)))+~count(*) from t1)+(t1.c*t1.e*(abs(19+(13))/abs(a)))-coalesce((select 17 from t1 where c<>e and b not in ((d),t1.b,b)),t1.c)+t1.d)-13 from t1 where t1.f19 then 17 else t1.c end)-count(*))) then max(11) else +max(b) end) from t1)))} +} {-289} +do_test randexpr-2.2269 { + db eval {SELECT coalesce((select coalesce((select ((abs(19)/abs(17))) from t1 where +13 & d>d),13-(select abs(abs(~count(*)))+~count(*) from t1)+(t1.c*t1.e*(abs(19+(13))/abs(a)))-coalesce((select 17 from t1 where c<>e and b not in ((d),t1.b,b)),t1.c)+t1.d)-13 from t1 where t1.f19 then 17 else t1.c end)-count(*))) then max(11) else +max(b) end) from t1)))} +} {-289} +do_test randexpr-2.2270 { + db eval {SELECT coalesce((select case d when e then t1.f else d++(abs((select count(*) from t1)-case when t1.f*case when t1.b-c in (select -cast(avg(e) AS integer) from t1 union select max(t1.a) from t1) or b between t1.a and -17 and -t1.f not between 17 and a then t1.e when 17<>11 then (abs(19)/abs(f)) else 17 end-17 not in (13,11,c) then t1.f else t1.c end)/abs(c))*t1.e end from t1 where f between t1.c and 17),t1.f) FROM t1 WHERE t1.b<>19} +} {600} +do_test randexpr-2.2271 { + db eval {SELECT coalesce((select case d when e then t1.f else d++(abs((select count(*) from t1)-case when t1.f*case when t1.b-c in (select -cast(avg(e) AS integer) from t1 union select max(t1.a) from t1) or b between t1.a and -17 and -t1.f not between 17 and a then t1.e when 17<>11 then (abs(19)/abs(f)) else 17 end-17 not in (13,11,c) then t1.f else t1.c end)/abs(c))*t1.e end from t1 where f between t1.c and 17),t1.f) FROM t1 WHERE NOT (t1.b<>19)} +} {} +do_test randexpr-2.2272 { + db eval {SELECT t1.f-case when ((t1.a in (select case case +min(case when coalesce((select max(a) from t1 where t1.e not between f and t1.b),f)<>(t1.d) then - -t1.f else 19 end)-case count(*)+(count(distinct t1.d)) when -min(e) then max(t1.f) else min(19) end when cast(avg(13) AS integer) then cast(avg( -t1.a) AS integer) else (min(t1.f)) end when (count(distinct t1.e)) then -cast(avg(a) AS integer) else cast(avg(19) AS integer) end | count(distinct 13)+ -count(*) from t1 union select -max(t1.b) from t1))) then a when d between a and 11 or t1.e<>c then +t1.a-(t1.e) else t1.e end FROM t1 WHERE t1.e between d | t1.a*13 and 11+13*17+b*c++13-~b} +} {} +do_test randexpr-2.2273 { + db eval {SELECT t1.f-case when ((t1.a in (select case case +min(case when coalesce((select max(a) from t1 where t1.e not between f and t1.b),f)<>(t1.d) then - -t1.f else 19 end)-case count(*)+(count(distinct t1.d)) when -min(e) then max(t1.f) else min(19) end when cast(avg(13) AS integer) then cast(avg( -t1.a) AS integer) else (min(t1.f)) end when (count(distinct t1.e)) then -cast(avg(a) AS integer) else cast(avg(19) AS integer) end | count(distinct 13)+ -count(*) from t1 union select -max(t1.b) from t1))) then a when d between a and 11 or t1.e<>c then +t1.a-(t1.e) else t1.e end FROM t1 WHERE NOT (t1.e between d | t1.a*13 and 11+13*17+b*c++13-~b)} +} {1000} +do_test randexpr-2.2274 { + db eval {SELECT t1.f-case when ((t1.a in (select case case +min(case when coalesce((select max(a) from t1 where t1.e not between f and t1.b),f)<>(t1.d) then - -t1.f else 19 end)-case count(*)+(count(distinct t1.d)) when -min(e) then max(t1.f) else min(19) end when cast(avg(13) AS integer) then cast(avg( -t1.a) AS integer) else (min(t1.f)) end when (count(distinct t1.e)) then -cast(avg(a) AS integer) else cast(avg(19) AS integer) end & count(distinct 13)+ -count(*) from t1 union select -max(t1.b) from t1))) then a when d between a and 11 or t1.e<>c then +t1.a-(t1.e) else t1.e end FROM t1 WHERE NOT (t1.e between d | t1.a*13 and 11+13*17+b*c++13-~b)} +} {1000} +do_test randexpr-2.2275 { + db eval {SELECT coalesce((select ~(abs(e)/abs(case when exists(select 1 from t1 where 19=+c or exists(select 1 from t1 where not exists(select 1 from t1 where 11>=d or b not between b and 19)) or t1.a not in (t1.a,(11),13)) then e-13+a-c else a end))*t1.f-(19) | 19 from t1 where t1.d in (select -(cast(avg(19) AS integer)) from t1 union select count(distinct (t1.e)) from t1) and (f in (a,c,(t1.a))) and a between 11 and 11 and t1.d>=t1.f and 11 not in ((t1.f),e,(f)) and 13 not in (t1.c,t1.d,t1.c)),t1.d) FROM t1 WHERE not exists(select 1 from t1 where not coalesce((select max(b) from t1 where coalesce((select t1.f from t1 where t1.f not between t1.e and coalesce((select 13*+ -t1.a | e+case when t1.a not in (case t1.f when d then 19 else 11 end,f*e+19,t1.e+(d)) then 13 else t1.d end+t1.c-17 from t1 where t1.c>=t1.d),t1.c)),t1.d)>t1.c),11) not between b and t1.f)} +} {} +do_test randexpr-2.2276 { + db eval {SELECT coalesce((select ~(abs(e)/abs(case when exists(select 1 from t1 where 19=+c or exists(select 1 from t1 where not exists(select 1 from t1 where 11>=d or b not between b and 19)) or t1.a not in (t1.a,(11),13)) then e-13+a-c else a end))*t1.f-(19) | 19 from t1 where t1.d in (select -(cast(avg(19) AS integer)) from t1 union select count(distinct (t1.e)) from t1) and (f in (a,c,(t1.a))) and a between 11 and 11 and t1.d>=t1.f and 11 not in ((t1.f),e,(f)) and 13 not in (t1.c,t1.d,t1.c)),t1.d) FROM t1 WHERE NOT (not exists(select 1 from t1 where not coalesce((select max(b) from t1 where coalesce((select t1.f from t1 where t1.f not between t1.e and coalesce((select 13*+ -t1.a | e+case when t1.a not in (case t1.f when d then 19 else 11 end,f*e+19,t1.e+(d)) then 13 else t1.d end+t1.c-17 from t1 where t1.c>=t1.d),t1.c)),t1.d)>t1.c),11) not between b and t1.f))} +} {400} +do_test randexpr-2.2277 { + db eval {SELECT coalesce((select ~(abs(e)/abs(case when exists(select 1 from t1 where 19=+c or exists(select 1 from t1 where not exists(select 1 from t1 where 11>=d or b not between b and 19)) or t1.a not in (t1.a,(11),13)) then e-13+a-c else a end))*t1.f-(19) & 19 from t1 where t1.d in (select -(cast(avg(19) AS integer)) from t1 union select count(distinct (t1.e)) from t1) and (f in (a,c,(t1.a))) and a between 11 and 11 and t1.d>=t1.f and 11 not in ((t1.f),e,(f)) and 13 not in (t1.c,t1.d,t1.c)),t1.d) FROM t1 WHERE NOT (not exists(select 1 from t1 where not coalesce((select max(b) from t1 where coalesce((select t1.f from t1 where t1.f not between t1.e and coalesce((select 13*+ -t1.a | e+case when t1.a not in (case t1.f when d then 19 else 11 end,f*e+19,t1.e+(d)) then 13 else t1.d end+t1.c-17 from t1 where t1.c>=t1.d),t1.c)),t1.d)>t1.c),11) not between b and t1.f))} +} {400} +do_test randexpr-2.2278 { + db eval {SELECT case when (select +case -+ -case min(t1.f) when cast(avg(t1.a) AS integer) then abs(~case (min(t1.a)) when (count(*)) then (min(e)) else count(*) end) else ( -cast(avg(b) AS integer)) end*count(*) | count(distinct 11) when -cast(avg(13) AS integer) then -min(13) else max(b) end+max(a) from t1) in ((abs(coalesce((select max(11*a) from t1 where t1.b>11-(select -cast(avg(t1.d) AS integer) from t1)),case when exists(select 1 from t1 where t1.f<13) then a else e end))/abs(c)) | t1.f,f,f) then t1.e else a end FROM t1 WHERE (select case min(case when not 17<11 then (abs(+(d)*t1.c+e-f)/abs(13)) when b between a and 11 then e else b end) when abs(min(t1.b) | (+count(*))) | ~case ( -count(*))-cast(avg(a) AS integer) when count(distinct t1.a) then -count(distinct f) else count(distinct 11) end then max( -t1.d) else -max(f) end from t1)-~c*t1.a not in (t1.e,t1.c,t1.a)} +} {100} +do_test randexpr-2.2279 { + db eval {SELECT case when (select +case -+ -case min(t1.f) when cast(avg(t1.a) AS integer) then abs(~case (min(t1.a)) when (count(*)) then (min(e)) else count(*) end) else ( -cast(avg(b) AS integer)) end*count(*) | count(distinct 11) when -cast(avg(13) AS integer) then -min(13) else max(b) end+max(a) from t1) in ((abs(coalesce((select max(11*a) from t1 where t1.b>11-(select -cast(avg(t1.d) AS integer) from t1)),case when exists(select 1 from t1 where t1.f<13) then a else e end))/abs(c)) | t1.f,f,f) then t1.e else a end FROM t1 WHERE NOT ((select case min(case when not 17<11 then (abs(+(d)*t1.c+e-f)/abs(13)) when b between a and 11 then e else b end) when abs(min(t1.b) | (+count(*))) | ~case ( -count(*))-cast(avg(a) AS integer) when count(distinct t1.a) then -count(distinct f) else count(distinct 11) end then max( -t1.d) else -max(f) end from t1)-~c*t1.a not in (t1.e,t1.c,t1.a))} +} {} +do_test randexpr-2.2280 { + db eval {SELECT case when (select +case -+ -case min(t1.f) when cast(avg(t1.a) AS integer) then abs(~case (min(t1.a)) when (count(*)) then (min(e)) else count(*) end) else ( -cast(avg(b) AS integer)) end*count(*) & count(distinct 11) when -cast(avg(13) AS integer) then -min(13) else max(b) end+max(a) from t1) in ((abs(coalesce((select max(11*a) from t1 where t1.b>11-(select -cast(avg(t1.d) AS integer) from t1)),case when exists(select 1 from t1 where t1.f<13) then a else e end))/abs(c)) & t1.f,f,f) then t1.e else a end FROM t1 WHERE (select case min(case when not 17<11 then (abs(+(d)*t1.c+e-f)/abs(13)) when b between a and 11 then e else b end) when abs(min(t1.b) | (+count(*))) | ~case ( -count(*))-cast(avg(a) AS integer) when count(distinct t1.a) then -count(distinct f) else count(distinct 11) end then max( -t1.d) else -max(f) end from t1)-~c*t1.a not in (t1.e,t1.c,t1.a)} +} {100} +do_test randexpr-2.2281 { + db eval {SELECT case when ~t1.b | 13>=~coalesce((select t1.e from t1 where 11 in (select -case +max(case when (t1.f) in (t1.b,t1.a,t1.f) then f else e end) when max(f)*cast(avg(t1.d) AS integer) then cast(avg(c) AS integer) else -( - -max(t1.f)) end from t1 union select count(*) from t1)),b | ( -t1.e))*t1.c*t1.a*t1.d-f then a when 19 not between -t1.e and t1.e or f not between -a and 19 then d else 11 end FROM t1 WHERE not (d in (select t1.c from t1 union select 11 from t1))} +} {400} +do_test randexpr-2.2282 { + db eval {SELECT case when ~t1.b | 13>=~coalesce((select t1.e from t1 where 11 in (select -case +max(case when (t1.f) in (t1.b,t1.a,t1.f) then f else e end) when max(f)*cast(avg(t1.d) AS integer) then cast(avg(c) AS integer) else -( - -max(t1.f)) end from t1 union select count(*) from t1)),b | ( -t1.e))*t1.c*t1.a*t1.d-f then a when 19 not between -t1.e and t1.e or f not between -a and 19 then d else 11 end FROM t1 WHERE NOT (not (d in (select t1.c from t1 union select 11 from t1)))} +} {} +do_test randexpr-2.2283 { + db eval {SELECT case when ~t1.b & 13>=~coalesce((select t1.e from t1 where 11 in (select -case +max(case when (t1.f) in (t1.b,t1.a,t1.f) then f else e end) when max(f)*cast(avg(t1.d) AS integer) then cast(avg(c) AS integer) else -( - -max(t1.f)) end from t1 union select count(*) from t1)),b & ( -t1.e))*t1.c*t1.a*t1.d-f then a when 19 not between -t1.e and t1.e or f not between -a and 19 then d else 11 end FROM t1 WHERE not (d in (select t1.c from t1 union select 11 from t1))} +} {100} +do_test randexpr-2.2284 { + db eval {SELECT coalesce((select c from t1 where 19 in (select case count(*) when count(distinct c)*+cast(avg(13) AS integer) then max(t1.d) else max(case case when exists(select 1 from t1 where 13 not in (d,e,(19)) and 13 between t1.d and t1.f) then t1.a when b in (t1.a,a,17) then case when t1.a not between 13 and c then (t1.b) else t1.b end else 19 end when 13 then a else 19 end) end from t1 union select (abs(abs(~cast(avg(t1.d) AS integer))) | cast(avg(t1.a) AS integer)) from t1)),t1.e-11)*(t1.a) FROM t1 WHERE not exists(select 1 from t1 where t1.e in (coalesce((select max(13) from t1 where 19 in (select f from t1 union select a from t1) or (not exists(select 1 from t1 where t1.a<=(19)*c*c | 13))),+e-(f)*case when t1.c not in (coalesce((select max(t1.a) from t1 where not c<(19)),19),e,(19)) then d else f end)+a,19,17)) or (d13))),t1.a)-f-a+t1.f) | case (cast(avg(t1.c) AS integer)) when cast(avg(t1.a) AS integer)-(count(*))+max(19) then - -max(19) else cast(avg(e) AS integer) end from t1)+(select cast(avg(b) AS integer) from t1) then t1.a else e-t1.d end-17+11 FROM t1 WHERE +c-(c)*d in (coalesce((select max( -t1.d-d-13) from t1 where (t1.c) not between (abs(13)/abs(t1.c)) and t1.b),d),11,c)} +} {} +do_test randexpr-2.2288 { + db eval {SELECT -~a+d-case d when -(select max(d)*~min(coalesce((select max(t1.e) from t1 where (exists(select 1 from t1 where 17<>13))),t1.a)-f-a+t1.f) | case (cast(avg(t1.c) AS integer)) when cast(avg(t1.a) AS integer)-(count(*))+max(19) then - -max(19) else cast(avg(e) AS integer) end from t1)+(select cast(avg(b) AS integer) from t1) then t1.a else e-t1.d end-17+11 FROM t1 WHERE NOT (+c-(c)*d in (coalesce((select max( -t1.d-d-13) from t1 where (t1.c) not between (abs(13)/abs(t1.c)) and t1.b),d),11,c))} +} {395} +do_test randexpr-2.2289 { + db eval {SELECT -~a+d-case d when -(select max(d)*~min(coalesce((select max(t1.e) from t1 where (exists(select 1 from t1 where 17<>13))),t1.a)-f-a+t1.f) & case (cast(avg(t1.c) AS integer)) when cast(avg(t1.a) AS integer)-(count(*))+max(19) then - -max(19) else cast(avg(e) AS integer) end from t1)+(select cast(avg(b) AS integer) from t1) then t1.a else e-t1.d end-17+11 FROM t1 WHERE NOT (+c-(c)*d in (coalesce((select max( -t1.d-d-13) from t1 where (t1.c) not between (abs(13)/abs(t1.c)) and t1.b),d),11,c))} +} {395} +do_test randexpr-2.2290 { + db eval {SELECT case when 17 in (case (abs(coalesce((select max((select cast(avg(case when 17-(t1.b)+t1.a | b+b in (select b from t1 union select 17 from t1) then c when t1.f in (select t1.a from t1 union select 19 from t1) then 11 else t1.c end) AS integer) from t1)) from t1 where t1.e>=t1.e or (b)=b and c not in (f,t1.a,t1.a)),d))/abs(t1.b)) when 17 then t1.b else 13 end-a,13,17) then t1.a else -d end FROM t1 WHERE t1.e=t1.e or (b)=b and c not in (f,t1.a,t1.a)),d))/abs(t1.b)) when 17 then t1.b else 13 end-a,13,17) then t1.a else -d end FROM t1 WHERE NOT (t1.e=t1.e or (b)=b and c not in (f,t1.a,t1.a)),d))/abs(t1.b)) when 17 then t1.b else 13 end-a,13,17) then t1.a else -d end FROM t1 WHERE NOT (t1.e19),b-case when +13>case when (coalesce((select b from t1 where coalesce((select max(t1.f) from t1 where 17<=case c when t1.e+f then d else case when 11<17 and t1.d<=t1.e then 13 when t1.d<>f then (t1.f) else c end end*t1.c),a) in (select 17 from t1 union select b from t1)),t1.c)>= -11) then (a)*t1.a else 19 end then 13 else 17 end*19) then d else (t1.a) end FROM t1 WHERE t1.d+t1.b not in (b,f,coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where c-t1.b not between case when coalesce((select max(~t1.e) from t1 where f not in (t1.b,17,t1.a)),t1.e) not in (e,13,(t1.d)) then 11 when t1.d>=17 then t1.c else 11 end and (11) and (exists(select 1 from t1 where t1.b<>11))) or 13 in (select max(t1.d) from t1 union select max(b) from t1)),t1.b+19+a))} +} {} +do_test randexpr-2.2294 { + db eval {SELECT case t1.a when coalesce((select a from t1 where t1.b>19),b-case when +13>case when (coalesce((select b from t1 where coalesce((select max(t1.f) from t1 where 17<=case c when t1.e+f then d else case when 11<17 and t1.d<=t1.e then 13 when t1.d<>f then (t1.f) else c end end*t1.c),a) in (select 17 from t1 union select b from t1)),t1.c)>= -11) then (a)*t1.a else 19 end then 13 else 17 end*19) then d else (t1.a) end FROM t1 WHERE NOT (t1.d+t1.b not in (b,f,coalesce((select max(t1.b) from t1 where exists(select 1 from t1 where c-t1.b not between case when coalesce((select max(~t1.e) from t1 where f not in (t1.b,17,t1.a)),t1.e) not in (e,13,(t1.d)) then 11 when t1.d>=17 then t1.c else 11 end and (11) and (exists(select 1 from t1 where t1.b<>11))) or 13 in (select max(t1.d) from t1 union select max(b) from t1)),t1.b+19+a)))} +} {400} +do_test randexpr-2.2295 { + db eval {SELECT coalesce((select max((coalesce((select coalesce((select max(case when case when et1.f then t1.b else c end19),t1.f) from t1 where t1.e<>t1.d),t1.b))) from t1 where 11=t1.c), -c) FROM t1 WHERE not exists(select 1 from t1 where -~e not in (c++case when 17+t1.c=d))),f-13) then a else (t1.a) end+f*19-a,b,f)) and t1.a=b} +} {} +do_test randexpr-2.2296 { + db eval {SELECT coalesce((select max((coalesce((select coalesce((select max(case when case when et1.f then t1.b else c end19),t1.f) from t1 where t1.e<>t1.d),t1.b))) from t1 where 11=t1.c), -c) FROM t1 WHERE NOT (not exists(select 1 from t1 where -~e not in (c++case when 17+t1.c=d))),f-13) then a else (t1.a) end+f*19-a,b,f)) and t1.a=b)} +} {-300} +do_test randexpr-2.2297 { + db eval {SELECT coalesce((select max((coalesce((select coalesce((select max(case when case when et1.f then t1.b else c end19),t1.f) from t1 where t1.e<>t1.d),t1.b))) from t1 where 11=t1.c), -c) FROM t1 WHERE NOT (not exists(select 1 from t1 where -~e not in (c++case when 17+t1.c=d))),f-13) then a else (t1.a) end+f*19-a,b,f)) and t1.a=b)} +} {-300} +do_test randexpr-2.2298 { + db eval {SELECT t1.b-11-case when t1.d+13+t1.c | 17+case when (+a*t1.b*t1.c not in (e,t1.f,t1.e)) then coalesce((select max(e) from t1 where t1.f>=f), -d) when f>b and t1.et1.c then 17 else -13 end not in (f,t1.f,a) and exists(select 1 from t1 where a<=11) then t1.e else c end FROM t1 WHERE case f+~d*case when t1.f<=t1.b*t1.a then e*t1.e else f end*a+f when ~case when 11 not between +(abs(b)/abs(case b+d when t1.a then f else t1.e end*13))+a and (b) then t1.e when t1.e<>11 then t1.d else 17 end+11 then t1.d else t1.b end<=13} +} {} +do_test randexpr-2.2299 { + db eval {SELECT t1.b-11-case when t1.d+13+t1.c | 17+case when (+a*t1.b*t1.c not in (e,t1.f,t1.e)) then coalesce((select max(e) from t1 where t1.f>=f), -d) when f>b and t1.et1.c then 17 else -13 end not in (f,t1.f,a) and exists(select 1 from t1 where a<=11) then t1.e else c end FROM t1 WHERE NOT (case f+~d*case when t1.f<=t1.b*t1.a then e*t1.e else f end*a+f when ~case when 11 not between +(abs(b)/abs(case b+d when t1.a then f else t1.e end*13))+a and (b) then t1.e when t1.e<>11 then t1.d else 17 end+11 then t1.d else t1.b end<=13)} +} {-111} +do_test randexpr-2.2300 { + db eval {SELECT t1.b-11-case when t1.d+13+t1.c & 17+case when (+a*t1.b*t1.c not in (e,t1.f,t1.e)) then coalesce((select max(e) from t1 where t1.f>=f), -d) when f>b and t1.et1.c then 17 else -13 end not in (f,t1.f,a) and exists(select 1 from t1 where a<=11) then t1.e else c end FROM t1 WHERE NOT (case f+~d*case when t1.f<=t1.b*t1.a then e*t1.e else f end*a+f when ~case when 11 not between +(abs(b)/abs(case b+d when t1.a then f else t1.e end*13))+a and (b) then t1.e when t1.e<>11 then t1.d else 17 end+11 then t1.d else t1.b end<=13)} +} {-111} +do_test randexpr-2.2301 { + db eval {SELECT coalesce((select t1.a from t1 where d not between 11 and 13 or case 13*17 when -c then case when (coalesce((select 17 from t1 where (~case when t1.e=d then 19 when 11 in (t1.d,b,17) then t1.c else c end-11 in (select max(e) from t1 union select (case cast(avg((t1.b)) AS integer) when max(11) then min(17) else ( -count(*)) end) from t1))),(19))>d) then t1.d else 11 end else t1.c end<=a),c) FROM t1 WHERE 19 | (abs(t1.d)/abs(11))=b} +} {} +do_test randexpr-2.2302 { + db eval {SELECT coalesce((select t1.a from t1 where d not between 11 and 13 or case 13*17 when -c then case when (coalesce((select 17 from t1 where (~case when t1.e=d then 19 when 11 in (t1.d,b,17) then t1.c else c end-11 in (select max(e) from t1 union select (case cast(avg((t1.b)) AS integer) when max(11) then min(17) else ( -count(*)) end) from t1))),(19))>d) then t1.d else 11 end else t1.c end<=a),c) FROM t1 WHERE NOT (19 | (abs(t1.d)/abs(11))=b)} +} {100} +do_test randexpr-2.2303 { + db eval {SELECT coalesce((select max(17-t1.e-17) from t1 where (t1.c>d)),case when coalesce((select +f+~coalesce((select coalesce((select case when (select cast(avg(17) AS integer) | cast(avg(t1.e) AS integer) from t1)<>coalesce((select t1.e from t1 where 19 in (select count(*) from t1 union select -( -count(*)) from t1)), -d) then b when exists(select 1 from t1 where t1.b between (t1.b) and 13) then a else -b end from t1 where 19=e),t1.c) from t1 where t1.c<=b),t1.d) from t1 where 17 between t1.a and b),t1.e) between c and t1.e then -t1.d else 13 end) FROM t1 WHERE exists(select 1 from t1 where t1.e-13-17-f*f*t1.d*coalesce((select 19-case when not not t1.d>e then case when t1.f=t1.c then 19 else f end else -t1.b end when e in (f,t1.e,17) then t1.a else t1.b end*t1.d from t1 where ((f)) in (select (~case count(distinct 11) when count(distinct t1.d) | count(distinct t1.b)-max( -f) then max(e) else (count(distinct (((a))))) end) from t1 union select max(e) from t1)),f)+c>=t1.f)} +} {} +do_test randexpr-2.2304 { + db eval {SELECT coalesce((select max(17-t1.e-17) from t1 where (t1.c>d)),case when coalesce((select +f+~coalesce((select coalesce((select case when (select cast(avg(17) AS integer) | cast(avg(t1.e) AS integer) from t1)<>coalesce((select t1.e from t1 where 19 in (select count(*) from t1 union select -( -count(*)) from t1)), -d) then b when exists(select 1 from t1 where t1.b between (t1.b) and 13) then a else -b end from t1 where 19=e),t1.c) from t1 where t1.c<=b),t1.d) from t1 where 17 between t1.a and b),t1.e) between c and t1.e then -t1.d else 13 end) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.e-13-17-f*f*t1.d*coalesce((select 19-case when not not t1.d>e then case when t1.f=t1.c then 19 else f end else -t1.b end when e in (f,t1.e,17) then t1.a else t1.b end*t1.d from t1 where ((f)) in (select (~case count(distinct 11) when count(distinct t1.d) | count(distinct t1.b)-max( -f) then max(e) else (count(distinct (((a))))) end) from t1 union select max(e) from t1)),f)+c>=t1.f))} +} {-400} +do_test randexpr-2.2305 { + db eval {SELECT coalesce((select max(17-t1.e-17) from t1 where (t1.c>d)),case when coalesce((select +f+~coalesce((select coalesce((select case when (select cast(avg(17) AS integer) & cast(avg(t1.e) AS integer) from t1)<>coalesce((select t1.e from t1 where 19 in (select count(*) from t1 union select -( -count(*)) from t1)), -d) then b when exists(select 1 from t1 where t1.b between (t1.b) and 13) then a else -b end from t1 where 19=e),t1.c) from t1 where t1.c<=b),t1.d) from t1 where 17 between t1.a and b),t1.e) between c and t1.e then -t1.d else 13 end) FROM t1 WHERE NOT (exists(select 1 from t1 where t1.e-13-17-f*f*t1.d*coalesce((select 19-case when not not t1.d>e then case when t1.f=t1.c then 19 else f end else -t1.b end when e in (f,t1.e,17) then t1.a else t1.b end*t1.d from t1 where ((f)) in (select (~case count(distinct 11) when count(distinct t1.d) | count(distinct t1.b)-max( -f) then max(e) else (count(distinct (((a))))) end) from t1 union select max(e) from t1)),f)+c>=t1.f))} +} {-400} +do_test randexpr-2.2306 { + db eval {SELECT coalesce((select t1.b from t1 where exists(select 1 from t1 where (abs(~case (~13*case when c in (select (max(case when b<>11 then d when 13 not in (19,c,e) then t1.f else 19 end*t1.d)) from t1 union select abs(count(*)) | min(19) from t1) then t1.a else t1.c end-a-13-f*e*17) when f then t1.a else 13 end*t1.c)/abs(a))>t1.b)),13) FROM t1 WHERE ++case when a<=t1.a then 17 else 13 end>+f+(coalesce((select max(19) from t1 where 11 not in (case when t1.e<(abs(11)/abs(19*d*t1.c)) and (c in (select t1.c from t1 union select f from t1) or a>a) then t1.a when 11 not between t1.c and t1.a or t1.e not in ( -t1.a,17,f) then t1.d else e end+t1.f,19,(17))),17))* -11} +} {} +do_test randexpr-2.2307 { + db eval {SELECT coalesce((select t1.b from t1 where exists(select 1 from t1 where (abs(~case (~13*case when c in (select (max(case when b<>11 then d when 13 not in (19,c,e) then t1.f else 19 end*t1.d)) from t1 union select abs(count(*)) | min(19) from t1) then t1.a else t1.c end-a-13-f*e*17) when f then t1.a else 13 end*t1.c)/abs(a))>t1.b)),13) FROM t1 WHERE NOT (++case when a<=t1.a then 17 else 13 end>+f+(coalesce((select max(19) from t1 where 11 not in (case when t1.e<(abs(11)/abs(19*d*t1.c)) and (c in (select t1.c from t1 union select f from t1) or a>a) then t1.a when 11 not between t1.c and t1.a or t1.e not in ( -t1.a,17,f) then t1.d else e end+t1.f,19,(17))),17))* -11)} +} {13} +do_test randexpr-2.2308 { + db eval {SELECT coalesce((select t1.b from t1 where exists(select 1 from t1 where (abs(~case (~13*case when c in (select (max(case when b<>11 then d when 13 not in (19,c,e) then t1.f else 19 end*t1.d)) from t1 union select abs(count(*)) & min(19) from t1) then t1.a else t1.c end-a-13-f*e*17) when f then t1.a else 13 end*t1.c)/abs(a))>t1.b)),13) FROM t1 WHERE NOT (++case when a<=t1.a then 17 else 13 end>+f+(coalesce((select max(19) from t1 where 11 not in (case when t1.e<(abs(11)/abs(19*d*t1.c)) and (c in (select t1.c from t1 union select f from t1) or a>a) then t1.a when 11 not between t1.c and t1.a or t1.e not in ( -t1.a,17,f) then t1.d else e end+t1.f,19,(17))),17))* -11)} +} {13} +do_test randexpr-2.2309 { + db eval {SELECT case when c*(abs(t1.f)/abs(c))*b-11-t1.at1.d then -d else t1.f end*e) from t1 where (b)<>t1.a or 11 between ( -a) and a),t1.b) then t1.d when e=t1.e then t1.c else t1.e end FROM t1 WHERE (coalesce((select (t1.b)+f*case case +coalesce((select 13 from t1 where t1.e<=d),f)-a when d then t1.b else t1.c end+t1.e when a then 17 else t1.e end from t1 where not t1.d in (select b from t1 union select 19 from t1) or not (17t1.d then -d else t1.f end*e) from t1 where (b)<>t1.a or 11 between ( -a) and a),t1.b) then t1.d when e=t1.e then t1.c else t1.e end FROM t1 WHERE NOT ((coalesce((select (t1.b)+f*case case +coalesce((select 13 from t1 where t1.e<=d),f)-a when d then t1.b else t1.c end+t1.e when a then 17 else t1.e end from t1 where not t1.d in (select b from t1 union select 19 from t1) or not (17a) or ( -d) between c and c or (19) between t1.f and t1.b) or (b) not in (t1.d,t1.c,e)) then t1.b*t1.b when a>19 then t1.d else 11 end>=11 then t1.e else -e end FROM t1 WHERE not exists(select 1 from t1 where ((11<=+11)))} +} {} +do_test randexpr-2.2314 { + db eval {SELECT case when case when -f-case when t1.a between 13 and (e) then t1.d | a else 13 enda) or ( -d) between c and c or (19) between t1.f and t1.b) or (b) not in (t1.d,t1.c,e)) then t1.b*t1.b when a>19 then t1.d else 11 end>=11 then t1.e else -e end FROM t1 WHERE NOT (not exists(select 1 from t1 where ((11<=+11))))} +} {500} +do_test randexpr-2.2315 { + db eval {SELECT case when case when -f-case when t1.a between 13 and (e) then t1.d & a else 13 enda) or ( -d) between c and c or (19) between t1.f and t1.b) or (b) not in (t1.d,t1.c,e)) then t1.b*t1.b when a>19 then t1.d else 11 end>=11 then t1.e else -e end FROM t1 WHERE NOT (not exists(select 1 from t1 where ((11<=+11))))} +} {500} +do_test randexpr-2.2316 { + db eval {SELECT (abs(+case when 11*t1.d not between 13 and t1.d then coalesce((select 17 from t1 where case ~e when (abs(+(b+(select ~ -cast(avg(t1.c) AS integer) from t1)))/abs(case 17 when 17 then c else a end)) then t1.d else t1.d end<>t1.a),f) when not exists(select 1 from t1 where (19<=(f))) and 17=t1.b or 19 not between a and a then t1.d else d end)/abs(b)) FROM t1 WHERE t1.d-13 in (t1.a,d,(t1.b))} +} {} +do_test randexpr-2.2317 { + db eval {SELECT (abs(+case when 11*t1.d not between 13 and t1.d then coalesce((select 17 from t1 where case ~e when (abs(+(b+(select ~ -cast(avg(t1.c) AS integer) from t1)))/abs(case 17 when 17 then c else a end)) then t1.d else t1.d end<>t1.a),f) when not exists(select 1 from t1 where (19<=(f))) and 17=t1.b or 19 not between a and a then t1.d else d end)/abs(b)) FROM t1 WHERE NOT (t1.d-13 in (t1.a,d,(t1.b)))} +} {0} +do_test randexpr-2.2318 { + db eval {SELECT b+(select case ~min(t1.a+13) when (cast(avg(t1.a) AS integer)) then max(d) else max(case when case t1.b when t1.e then t1.c else t1.f end+19<>+(select count(*) from t1) then case when b in (t1.e,t1.d,t1.e) and t1.c not between t1.f and 13 then (t1.c) when 17>t1.b then 19 else t1.b end-t1.d when d in (e,f,t1.f) and (a)+t1.e then e+case when (exists(select 1 from t1 where d<17) and d<(abs(t1.e)/abs(+ - -t1.f+d))) then coalesce((select max((t1.f)) from t1 where not 19=t1.e),t1.e)+t1.e else t1.d end when not exists(select 1 from t1 where t1.d not in (19,11,t1.c)) then (t1.f) else d end} +} {1800} +do_test randexpr-2.2319 { + db eval {SELECT b+(select case ~min(t1.a+13) when (cast(avg(t1.a) AS integer)) then max(d) else max(case when case t1.b when t1.e then t1.c else t1.f end+19<>+(select count(*) from t1) then case when b in (t1.e,t1.d,t1.e) and t1.c not between t1.f and 13 then (t1.c) when 17>t1.b then 19 else t1.b end-t1.d when d in (e,f,t1.f) and (a)+t1.e then e+case when (exists(select 1 from t1 where d<17) and d<(abs(t1.e)/abs(+ - -t1.f+d))) then coalesce((select max((t1.f)) from t1 where not 19=t1.e),t1.e)+t1.e else t1.d end when not exists(select 1 from t1 where t1.d not in (19,11,t1.c)) then (t1.f) else d end)} +} {} +do_test randexpr-2.2320 { + db eval {SELECT coalesce((select max(t1.d) from t1 where t1.b+b in (select (t1.c)*11*e+f+ -c-t1.b*coalesce((select max(a) from t1 where t1.a*17 between 19 and (((abs(f)/abs(t1.c+d))))),t1.c-(abs(t1.c)/abs(19)) | case when t1.d= -t1.f then b when (t1.c) not in (e, -11,19) then 19 else t1.a end-c)*t1.a-c from t1 union select t1.d from t1)),a) FROM t1 WHERE (select abs(+min(b)) from t1)<=d+t1.a} +} {400} +do_test randexpr-2.2321 { + db eval {SELECT coalesce((select max(t1.d) from t1 where t1.b+b in (select (t1.c)*11*e+f+ -c-t1.b*coalesce((select max(a) from t1 where t1.a*17 between 19 and (((abs(f)/abs(t1.c+d))))),t1.c-(abs(t1.c)/abs(19)) | case when t1.d= -t1.f then b when (t1.c) not in (e, -11,19) then 19 else t1.a end-c)*t1.a-c from t1 union select t1.d from t1)),a) FROM t1 WHERE NOT ((select abs(+min(b)) from t1)<=d+t1.a)} +} {} +do_test randexpr-2.2322 { + db eval {SELECT coalesce((select max(t1.d) from t1 where t1.b+b in (select (t1.c)*11*e+f+ -c-t1.b*coalesce((select max(a) from t1 where t1.a*17 between 19 and (((abs(f)/abs(t1.c+d))))),t1.c-(abs(t1.c)/abs(19)) & case when t1.d= -t1.f then b when (t1.c) not in (e, -11,19) then 19 else t1.a end-c)*t1.a-c from t1 union select t1.d from t1)),a) FROM t1 WHERE (select abs(+min(b)) from t1)<=d+t1.a} +} {400} +do_test randexpr-2.2323 { + db eval {SELECT case when coalesce((select c from t1 where (~13<>d)),t1.d-+d+13*coalesce((select max(17) from t1 where -fd),e))/abs(13))*f not in (t1.e,t1.c,e) then 19 when 17 not between t1.f and 17 then t1.f else t1.e end),f)+t1.c) | d<>11 then a else 19 end FROM t1 WHERE 13=b} +} {} +do_test randexpr-2.2324 { + db eval {SELECT case when coalesce((select c from t1 where (~13<>d)),t1.d-+d+13*coalesce((select max(17) from t1 where -fd),e))/abs(13))*f not in (t1.e,t1.c,e) then 19 when 17 not between t1.f and 17 then t1.f else t1.e end),f)+t1.c) | d<>11 then a else 19 end FROM t1 WHERE NOT (13=b)} +} {100} +do_test randexpr-2.2325 { + db eval {SELECT case when coalesce((select c from t1 where (~13<>d)),t1.d-+d+13*coalesce((select max(17) from t1 where -fd),e))/abs(13))*f not in (t1.e,t1.c,e) then 19 when 17 not between t1.f and 17 then t1.f else t1.e end),f)+t1.c) & d<>11 then a else 19 end FROM t1 WHERE NOT (13=b)} +} {100} +do_test randexpr-2.2326 { + db eval {SELECT case case t1.e+13 when case when not -f>coalesce((select max(t1.b) from t1 where (select min(a) from t1)t1.d and t1.c<19 and d between b and ( -c)) then (select case ~max( -( - -t1.f)) when min(e) then -count(*) else count(*) end-cast(avg(b) AS integer) from t1) when 17<>11 then f else case -17 when t1.d then b else -t1.f end end+t1.e when t1.d>=11 then 17 else 11 end then t1.d else t1.d end when t1.c then t1.a else 11 end FROM t1 WHERE (coalesce((select coalesce((select max(coalesce((select max( -(select + -case ++case (count(*)) when cast(avg(11) AS integer) then count(*) else -min(13) end when max(19) then -cast(avg(11) AS integer) else count(distinct (b)) end | max(t1.a)+max(b) from t1)) from t1 where 11 in (select b from t1 union select 13 from t1)),case (select count(*) from t1) when 19 then case when d not between -d and b then t1.f else t1.b end else t1.c end)+d-t1.e) from t1 where t1.f not between t1.c and 19),t1.b) from t1 where t1.c between d and -t1.b),t1.b))>=c} +} {} +do_test randexpr-2.2327 { + db eval {SELECT case case t1.e+13 when case when not -f>coalesce((select max(t1.b) from t1 where (select min(a) from t1)t1.d and t1.c<19 and d between b and ( -c)) then (select case ~max( -( - -t1.f)) when min(e) then -count(*) else count(*) end-cast(avg(b) AS integer) from t1) when 17<>11 then f else case -17 when t1.d then b else -t1.f end end+t1.e when t1.d>=11 then 17 else 11 end then t1.d else t1.d end when t1.c then t1.a else 11 end FROM t1 WHERE NOT ((coalesce((select coalesce((select max(coalesce((select max( -(select + -case ++case (count(*)) when cast(avg(11) AS integer) then count(*) else -min(13) end when max(19) then -cast(avg(11) AS integer) else count(distinct (b)) end | max(t1.a)+max(b) from t1)) from t1 where 11 in (select b from t1 union select 13 from t1)),case (select count(*) from t1) when 19 then case when d not between -d and b then t1.f else t1.b end else t1.c end)+d-t1.e) from t1 where t1.f not between t1.c and 19),t1.b) from t1 where t1.c between d and -t1.b),t1.b))>=c)} +} {11} +do_test randexpr-2.2328 { + db eval {SELECT case when +case when coalesce((select t1.b from t1 where not exists(select 1 from t1 where f<=coalesce((select c from t1 where t1.a in (select ~f from t1 union select coalesce((select max(case -(13) when 13 then t1.f else a end | 13) from t1 where c<= -c or b not between f and t1.d and t1.b not in (e,t1.a,17)),a)+d from t1)),13) or t1.a>c)),11*19) between e and 17 then c else -(c) end>=t1.c then t1.d else c end FROM t1 WHERE t1.d<17-t1.a | a-+11} +} {} +do_test randexpr-2.2329 { + db eval {SELECT case when +case when coalesce((select t1.b from t1 where not exists(select 1 from t1 where f<=coalesce((select c from t1 where t1.a in (select ~f from t1 union select coalesce((select max(case -(13) when 13 then t1.f else a end | 13) from t1 where c<= -c or b not between f and t1.d and t1.b not in (e,t1.a,17)),a)+d from t1)),13) or t1.a>c)),11*19) between e and 17 then c else -(c) end>=t1.c then t1.d else c end FROM t1 WHERE NOT (t1.d<17-t1.a | a-+11)} +} {300} +do_test randexpr-2.2330 { + db eval {SELECT case when +case when coalesce((select t1.b from t1 where not exists(select 1 from t1 where f<=coalesce((select c from t1 where t1.a in (select ~f from t1 union select coalesce((select max(case -(13) when 13 then t1.f else a end & 13) from t1 where c<= -c or b not between f and t1.d and t1.b not in (e,t1.a,17)),a)+d from t1)),13) or t1.a>c)),11*19) between e and 17 then c else -(c) end>=t1.c then t1.d else c end FROM t1 WHERE NOT (t1.d<17-t1.a | a-+11)} +} {300} +do_test randexpr-2.2331 { + db eval {SELECT t1.c+c- -d*t1.d+t1.e | case when t1.e<=e and (a*t1.c) in (select ((abs(f)/abs(( -+(select abs(~(min( -c))-max( - -b)-count(*)) from t1))))) from t1 union select b from t1) then +a*t1.c-t1.d*t1.c else e end-t1.d+t1.f FROM t1 WHERE (exists(select 1 from t1 where coalesce((select max(++11+coalesce((select max(17) from t1 where case case when exists(select 1 from t1 where c not between t1.e and 17) then 19 else f end when -t1.f then t1.f else t1.a end<=t1.e or 11 in (b,a,e) and e between 11 and 11), -(a)-19)*t1.f) from t1 where t1.b between d and 17 and 17=e),19) not in (a,b,b))) and (e>=d) or b not in (c,13,19)} +} {161788} +do_test randexpr-2.2332 { + db eval {SELECT t1.c+c- -d*t1.d+t1.e | case when t1.e<=e and (a*t1.c) in (select ((abs(f)/abs(( -+(select abs(~(min( -c))-max( - -b)-count(*)) from t1))))) from t1 union select b from t1) then +a*t1.c-t1.d*t1.c else e end-t1.d+t1.f FROM t1 WHERE NOT ((exists(select 1 from t1 where coalesce((select max(++11+coalesce((select max(17) from t1 where case case when exists(select 1 from t1 where c not between t1.e and 17) then 19 else f end when -t1.f then t1.f else t1.a end<=t1.e or 11 in (b,a,e) and e between 11 and 11), -(a)-19)*t1.f) from t1 where t1.b between d and 17 and 17=e),19) not in (a,b,b))) and (e>=d) or b not in (c,13,19))} +} {} +do_test randexpr-2.2333 { + db eval {SELECT t1.c+c- -d*t1.d+t1.e & case when t1.e<=e and (a*t1.c) in (select ((abs(f)/abs(( -+(select abs(~(min( -c))-max( - -b)-count(*)) from t1))))) from t1 union select b from t1) then +a*t1.c-t1.d*t1.c else e end-t1.d+t1.f FROM t1 WHERE (exists(select 1 from t1 where coalesce((select max(++11+coalesce((select max(17) from t1 where case case when exists(select 1 from t1 where c not between t1.e and 17) then 19 else f end when -t1.f then t1.f else t1.a end<=t1.e or 11 in (b,a,e) and e between 11 and 11), -(a)-19)*t1.f) from t1 where t1.b between d and 17 and 17=e),19) not in (a,b,b))) and (e>=d) or b not in (c,13,19)} +} {12} +do_test randexpr-2.2334 { + db eval {SELECT b-case when exists(select 1 from t1 where (exists(select 1 from t1 where t1.a not between 17 and a+t1.f) or not exists(select 1 from t1 where not exists(select 1 from t1 where t1.b+f+a in (select max(19) | -max(t1.e)-cast(avg(t1.c) AS integer)- -count(distinct t1.b) from t1 union select max(t1.b) from t1)) or not exists(select 1 from t1 where not exists(select 1 from t1 where 11>c or (13) in ( -11,c,19)) or 11>f))) and t1.c not in ( -(d),t1.a,t1.a) and 17 in (t1.b,13,19)) then coalesce((select max(+19) from t1 where 17e)),b) from t1))) or ((t1.dc or (13) in ( -11,c,19)) or 11>f))) and t1.c not in ( -(d),t1.a,t1.a) and 17 in (t1.b,13,19)) then coalesce((select max(+19) from t1 where 17e)),b) from t1))) or ((t1.dc or (13) in ( -11,c,19)) or 11>f))) and t1.c not in ( -(d),t1.a,t1.a) and 17 in (t1.b,13,19)) then coalesce((select max(+19) from t1 where 17e)),b) from t1))) or ((t1.d= -t1.f),t1.c))),b) end from t1 where not a=11),t1.c) FROM t1 WHERE not 13<>11+17-case when 17 between (abs(case f when 19 | t1.a then +(select cast(avg(case when not exists(select 1 from t1 where ~ -13*(select -cast(avg(t1.b*d) AS integer) from t1)+17<>(t1.b)) then ~t1.c when b>t1.d then c else (f) end) AS integer) from t1) else a end)/abs(19)) and t1.f then t1.b when a<>t1.c then t1.e else b end} +} {} +do_test randexpr-2.2338 { + db eval {SELECT coalesce((select t1.f*t1.b+case t1.a when 17 then -t1.c else coalesce((select b from t1 where 19 in (f,d+b,coalesce((select t1.e-b from t1 where t1.b*d+case t1.c when case coalesce((select t1.b from t1 where c not in (b,a,13)),(13)) when t1.b then 19 else 19 end then t1.d else 19 end+ -b>= -t1.f),t1.c))),b) end from t1 where not a=11),t1.c) FROM t1 WHERE NOT (not 13<>11+17-case when 17 between (abs(case f when 19 | t1.a then +(select cast(avg(case when not exists(select 1 from t1 where ~ -13*(select -cast(avg(t1.b*d) AS integer) from t1)+17<>(t1.b)) then ~t1.c when b>t1.d then c else (f) end) AS integer) from t1) else a end)/abs(19)) and t1.f then t1.b when a<>t1.c then t1.e else b end)} +} {120200} +do_test randexpr-2.2339 { + db eval {SELECT coalesce((select max(19) from t1 where t1.f*17+case t1.f when 11 then coalesce((select max(t1.a) from t1 where 13<>t1.d),(abs(13+b-case when not c+(abs(case when t1.c not between a and t1.f then -(e) else t1.d end)/abs( -17))=13} +} {119} +do_test randexpr-2.2340 { + db eval {SELECT coalesce((select max(19) from t1 where t1.f*17+case t1.f when 11 then coalesce((select max(t1.a) from t1 where 13<>t1.d),(abs(13+b-case when not c+(abs(case when t1.c not between a and t1.f then -(e) else t1.d end)/abs( -17))=13)} +} {} +do_test randexpr-2.2341 { + db eval {SELECT +coalesce((select max(e) from t1 where -(case 13*(t1.b* -case when e<=19 then b when t1.e=c then (b) else f end*t1.e) when e then 13 else t1.f end)=t1.b and t1.a in (select count(*) | case case min(b)*(count(*)) when abs(cast(avg(13) AS integer))-max(t1.d) then min(19) else -cast(avg(b) AS integer) end when count(*) then (max(c)) else count(distinct 19) end+cast(avg((b)) AS integer) from t1 union select count(*) from t1)),t1.a) FROM t1 WHERE (select (min(13-(abs(c)/abs(case when coalesce((select case when coalesce((select -a from t1 where case a*f when t1.a then -c else (f) end between t1.a and t1.c),b) not between t1.e and b then 19 when 17 not in (19,d,11) then b else a end from t1 where b in (select t1.e from t1 union select t1.b from t1)),t1.a) not in (t1.e,t1.a,t1.f) then (d) else 19 end)))) from t1) in (select +13 from t1 union select 17 from t1)} +} {100} +do_test randexpr-2.2342 { + db eval {SELECT +coalesce((select max(e) from t1 where -(case 13*(t1.b* -case when e<=19 then b when t1.e=c then (b) else f end*t1.e) when e then 13 else t1.f end)=t1.b and t1.a in (select count(*) | case case min(b)*(count(*)) when abs(cast(avg(13) AS integer))-max(t1.d) then min(19) else -cast(avg(b) AS integer) end when count(*) then (max(c)) else count(distinct 19) end+cast(avg((b)) AS integer) from t1 union select count(*) from t1)),t1.a) FROM t1 WHERE NOT ((select (min(13-(abs(c)/abs(case when coalesce((select case when coalesce((select -a from t1 where case a*f when t1.a then -c else (f) end between t1.a and t1.c),b) not between t1.e and b then 19 when 17 not in (19,d,11) then b else a end from t1 where b in (select t1.e from t1 union select t1.b from t1)),t1.a) not in (t1.e,t1.a,t1.f) then (d) else 19 end)))) from t1) in (select +13 from t1 union select 17 from t1))} +} {} +do_test randexpr-2.2343 { + db eval {SELECT +coalesce((select max(e) from t1 where -(case 13*(t1.b* -case when e<=19 then b when t1.e=c then (b) else f end*t1.e) when e then 13 else t1.f end)=t1.b and t1.a in (select count(*) & case case min(b)*(count(*)) when abs(cast(avg(13) AS integer))-max(t1.d) then min(19) else -cast(avg(b) AS integer) end when count(*) then (max(c)) else count(distinct 19) end+cast(avg((b)) AS integer) from t1 union select count(*) from t1)),t1.a) FROM t1 WHERE (select (min(13-(abs(c)/abs(case when coalesce((select case when coalesce((select -a from t1 where case a*f when t1.a then -c else (f) end between t1.a and t1.c),b) not between t1.e and b then 19 when 17 not in (19,d,11) then b else a end from t1 where b in (select t1.e from t1 union select t1.b from t1)),t1.a) not in (t1.e,t1.a,t1.f) then (d) else 19 end)))) from t1) in (select +13 from t1 union select 17 from t1)} +} {100} +do_test randexpr-2.2344 { + db eval {SELECT case when b in (select 19 from t1 union select c from t1) then -d else 19-13+coalesce((select t1.c from t1 where t1.d>=case when e in (select f*t1.b from t1 union select t1.d from t1) then t1.c when not exists(select 1 from t1 where t1.f not in (17,t1.c,11) and b between b and 17 or c in (t1.b,17,a) or t1.d>t1.d and t1.c<>11 and 13=e and t1.f not in ( -t1.c,19,f)) then coalesce((select max(case when t1.c in (t1.e,d,b) then t1.f else t1.a end) from t1 where e<=t1.f),11) else t1.b end*11),t1.e) end FROM t1 WHERE 13 not between +19 and a} +} {506} +do_test randexpr-2.2345 { + db eval {SELECT case when b in (select 19 from t1 union select c from t1) then -d else 19-13+coalesce((select t1.c from t1 where t1.d>=case when e in (select f*t1.b from t1 union select t1.d from t1) then t1.c when not exists(select 1 from t1 where t1.f not in (17,t1.c,11) and b between b and 17 or c in (t1.b,17,a) or t1.d>t1.d and t1.c<>11 and 13=e and t1.f not in ( -t1.c,19,f)) then coalesce((select max(case when t1.c in (t1.e,d,b) then t1.f else t1.a end) from t1 where e<=t1.f),11) else t1.b end*11),t1.e) end FROM t1 WHERE NOT (13 not between +19 and a)} +} {} +do_test randexpr-2.2346 { + db eval {SELECT (abs(13)/abs(case when t1.f not between a and f then 19-t1.d-t1.d*d | c+(select case count(*) | (~ -count(*)) when cast(avg( -19) AS integer) then min(d) else (cast(avg(e) AS integer)) end from t1) | t1.f-t1.b when f<>case when f<>b and 19 in (d,( -t1.a),t1.c) then 11 when e not between b and (t1.d) then t1.e else t1.d end-t1.e or t1.b not in (f,c,(a)) then -d else t1.f end-t1.f)) FROM t1 WHERE (select -count(*) from t1)=d+11} +} {} +do_test randexpr-2.2347 { + db eval {SELECT (abs(13)/abs(case when t1.f not between a and f then 19-t1.d-t1.d*d | c+(select case count(*) | (~ -count(*)) when cast(avg( -19) AS integer) then min(d) else (cast(avg(e) AS integer)) end from t1) | t1.f-t1.b when f<>case when f<>b and 19 in (d,( -t1.a),t1.c) then 11 when e not between b and (t1.d) then t1.e else t1.d end-t1.e or t1.b not in (f,c,(a)) then -d else t1.f end-t1.f)) FROM t1 WHERE NOT ((select -count(*) from t1)=d+11)} +} {0} +do_test randexpr-2.2348 { + db eval {SELECT (abs(13)/abs(case when t1.f not between a and f then 19-t1.d-t1.d*d & c+(select case count(*) & (~ -count(*)) when cast(avg( -19) AS integer) then min(d) else (cast(avg(e) AS integer)) end from t1) & t1.f-t1.b when f<>case when f<>b and 19 in (d,( -t1.a),t1.c) then 11 when e not between b and (t1.d) then t1.e else t1.d end-t1.e or t1.b not in (f,c,(a)) then -d else t1.f end-t1.f)) FROM t1 WHERE NOT ((select -count(*) from t1)=d+11)} +} {0} +do_test randexpr-2.2349 { + db eval {SELECT ((select count(distinct 11+19 | case (d) when t1.b then coalesce((select case coalesce((select max(+c*t1.f) from t1 where (t1.e=f and 13<=t1.d)), -17)+11-t1.a when (t1.c) then 19 else 13 end from t1 where t1.c in (select ~+ -count(distinct t1.f) from t1 union select count(*)+count(distinct b)*min(11) from t1)),e) else 19 end+d) | count(*) from t1)) FROM t1 WHERE case b when 19 then ~b-~e-d+d+t1.c else a end in (select max(t1.b)-~count(*)+abs(abs((case min((abs(~t1.c*t1.f)/abs(t1.e))) when case max(b) when abs(count(distinct t1.b)) then +cast(avg((13)) AS integer) else +case min(b) when count(*) then count(*) else count(distinct t1.f) end end then max(19) else ( -count(*)) end)))*count(distinct f)*cast(avg(t1.c) AS integer) from t1 union select count(distinct a) from t1)} +} {} +do_test randexpr-2.2350 { + db eval {SELECT ((select count(distinct 11+19 | case (d) when t1.b then coalesce((select case coalesce((select max(+c*t1.f) from t1 where (t1.e=f and 13<=t1.d)), -17)+11-t1.a when (t1.c) then 19 else 13 end from t1 where t1.c in (select ~+ -count(distinct t1.f) from t1 union select count(*)+count(distinct b)*min(11) from t1)),e) else 19 end+d) | count(*) from t1)) FROM t1 WHERE NOT (case b when 19 then ~b-~e-d+d+t1.c else a end in (select max(t1.b)-~count(*)+abs(abs((case min((abs(~t1.c*t1.f)/abs(t1.e))) when case max(b) when abs(count(distinct t1.b)) then +cast(avg((13)) AS integer) else +case min(b) when count(*) then count(*) else count(distinct t1.f) end end then max(19) else ( -count(*)) end)))*count(distinct f)*cast(avg(t1.c) AS integer) from t1 union select count(distinct a) from t1))} +} {1} +do_test randexpr-2.2351 { + db eval {SELECT ((select count(distinct 11+19 & case (d) when t1.b then coalesce((select case coalesce((select max(+c*t1.f) from t1 where (t1.e=f and 13<=t1.d)), -17)+11-t1.a when (t1.c) then 19 else 13 end from t1 where t1.c in (select ~+ -count(distinct t1.f) from t1 union select count(*)+count(distinct b)*min(11) from t1)),e) else 19 end+d) & count(*) from t1)) FROM t1 WHERE NOT (case b when 19 then ~b-~e-d+d+t1.c else a end in (select max(t1.b)-~count(*)+abs(abs((case min((abs(~t1.c*t1.f)/abs(t1.e))) when case max(b) when abs(count(distinct t1.b)) then +cast(avg((13)) AS integer) else +case min(b) when count(*) then count(*) else count(distinct t1.f) end end then max(19) else ( -count(*)) end)))*count(distinct f)*cast(avg(t1.c) AS integer) from t1 union select count(distinct a) from t1))} +} {1} +do_test randexpr-2.2352 { + db eval {SELECT 17+ -(abs(case case when a>t1.c then t1.e else a end*11-case when not exists(select 1 from t1 where coalesce((select -t1.e-11+coalesce((select t1.e from t1 where 13=t1.e),d) from t1 where t1.e between t1.d and a),13)-t1.e in (select t1.d from t1 union select d from t1)) then t1.b else t1.d end-t1.e-13+b when 19 then t1.b else c end)/abs(t1.d)) FROM t1 WHERE coalesce((select max(t1.d) from t1 where t1.a+t1.d<19),t1.a) in (select t1.b from t1 union select c from t1) or t1.c in (select -abs(max(case when -f<>t1.b and b<>11 then t1.f when t1.a=e then t1.d else -(f) end) | case cast(avg(f) AS integer) when count(distinct t1.f) then min(e) else -count(*) end+cast(avg((t1.f)) AS integer)) from t1 union select max(17) from t1) or t1.c between ((c)) and -t1.b and -c not between d and 11 or b>=19} +} {17} +do_test randexpr-2.2353 { + db eval {SELECT 17+ -(abs(case case when a>t1.c then t1.e else a end*11-case when not exists(select 1 from t1 where coalesce((select -t1.e-11+coalesce((select t1.e from t1 where 13=t1.e),d) from t1 where t1.e between t1.d and a),13)-t1.e in (select t1.d from t1 union select d from t1)) then t1.b else t1.d end-t1.e-13+b when 19 then t1.b else c end)/abs(t1.d)) FROM t1 WHERE NOT (coalesce((select max(t1.d) from t1 where t1.a+t1.d<19),t1.a) in (select t1.b from t1 union select c from t1) or t1.c in (select -abs(max(case when -f<>t1.b and b<>11 then t1.f when t1.a=e then t1.d else -(f) end) | case cast(avg(f) AS integer) when count(distinct t1.f) then min(e) else -count(*) end+cast(avg((t1.f)) AS integer)) from t1 union select max(17) from t1) or t1.c between ((c)) and -t1.b and -c not between d and 11 or b>=19)} +} {} +do_test randexpr-2.2354 { + db eval {SELECT e*~+(e)-(abs(~case when (t1.f)>13+~t1.d then case when d=t1.b+13 then 17 when 11 in (t1.d,e,e) then ~19*t1.a else coalesce((select t1.c from t1 where 19*(abs(t1.e)/abs(b)) between t1.c and t1.c),t1.d) end when a not between 13 and -17 then 19 else b end)/abs(t1.b)) FROM t1 WHERE (not d>case t1.b+t1.f when +(~(select (case abs(cast(avg(13) AS integer)) when cast(avg(+a) AS integer) then abs(abs(count(distinct case when t1.f*e<=11 then 13 when exists(select 1 from t1 where t1.e<17 or t1.a>=t1.a) then (11) else f end))) else min(t1.b)-min(11) end) from t1))+17*t1.b*f*17 then e else 11 end)} +} {} +do_test randexpr-2.2355 { + db eval {SELECT e*~+(e)-(abs(~case when (t1.f)>13+~t1.d then case when d=t1.b+13 then 17 when 11 in (t1.d,e,e) then ~19*t1.a else coalesce((select t1.c from t1 where 19*(abs(t1.e)/abs(b)) between t1.c and t1.c),t1.d) end when a not between 13 and -17 then 19 else b end)/abs(t1.b)) FROM t1 WHERE NOT ((not d>case t1.b+t1.f when +(~(select (case abs(cast(avg(13) AS integer)) when cast(avg(+a) AS integer) then abs(abs(count(distinct case when t1.f*e<=11 then 13 when exists(select 1 from t1 where t1.e<17 or t1.a>=t1.a) then (11) else f end))) else min(t1.b)-min(11) end) from t1))+17*t1.b*f*17 then e else 11 end))} +} {-250502} +do_test randexpr-2.2356 { + db eval {SELECT -case when t1.c<= -case coalesce((select max((coalesce((select case 11 when t1.b then t1.f else 11 end-d from t1 where c in (select count(*) | ~count(distinct f) from t1 union select count(*) from t1)),a)*t1.a)-t1.f) from t1 where not exists(select 1 from t1 where ((t1.f not in ( -c,t1.d,b)) or t1.a not in (b,11,t1.c)) or t1.d not in (17,a,t1.a))),19)-t1.b when d then t1.e else t1.e end-19 | e then b else -13 end*e-c FROM t1 WHERE b<>coalesce((select max((abs((abs(11)/abs(13)))/abs(case when t1.e between 11 and 19 then t1.d when 11>=b-19 then (select count(distinct ~a | 19*f+case when f not in (t1.e,t1.f, -t1.f) then 17 when c not in ( -t1.a,t1.c,b) then f else 11 end) from t1) else t1.e end))-t1.e*a) from t1 where e in (t1.c,17,17)),t1.a) or a=t1.e or d>t1.b} +} {6200} +do_test randexpr-2.2357 { + db eval {SELECT -case when t1.c<= -case coalesce((select max((coalesce((select case 11 when t1.b then t1.f else 11 end-d from t1 where c in (select count(*) | ~count(distinct f) from t1 union select count(*) from t1)),a)*t1.a)-t1.f) from t1 where not exists(select 1 from t1 where ((t1.f not in ( -c,t1.d,b)) or t1.a not in (b,11,t1.c)) or t1.d not in (17,a,t1.a))),19)-t1.b when d then t1.e else t1.e end-19 | e then b else -13 end*e-c FROM t1 WHERE NOT (b<>coalesce((select max((abs((abs(11)/abs(13)))/abs(case when t1.e between 11 and 19 then t1.d when 11>=b-19 then (select count(distinct ~a | 19*f+case when f not in (t1.e,t1.f, -t1.f) then 17 when c not in ( -t1.a,t1.c,b) then f else 11 end) from t1) else t1.e end))-t1.e*a) from t1 where e in (t1.c,17,17)),t1.a) or a=t1.e or d>t1.b)} +} {} +do_test randexpr-2.2358 { + db eval {SELECT -case when t1.c<= -case coalesce((select max((coalesce((select case 11 when t1.b then t1.f else 11 end-d from t1 where c in (select count(*) & ~count(distinct f) from t1 union select count(*) from t1)),a)*t1.a)-t1.f) from t1 where not exists(select 1 from t1 where ((t1.f not in ( -c,t1.d,b)) or t1.a not in (b,11,t1.c)) or t1.d not in (17,a,t1.a))),19)-t1.b when d then t1.e else t1.e end-19 & e then b else -13 end*e-c FROM t1 WHERE b<>coalesce((select max((abs((abs(11)/abs(13)))/abs(case when t1.e between 11 and 19 then t1.d when 11>=b-19 then (select count(distinct ~a | 19*f+case when f not in (t1.e,t1.f, -t1.f) then 17 when c not in ( -t1.a,t1.c,b) then f else 11 end) from t1) else t1.e end))-t1.e*a) from t1 where e in (t1.c,17,17)),t1.a) or a=t1.e or d>t1.b} +} {-100300} +do_test randexpr-2.2359 { + db eval {SELECT (abs(case when t1.d not in (t1.f,t1.d,(select abs(min(((select +count(*)*case max(t1.e-coalesce((select max(case t1.b when 13 then a else e end) from t1 where t1.b>b),19)+d)- -+count(*) when +cast(avg(d) AS integer) then max(c) else (cast(avg(c) AS integer)) end | count(*) from t1)+t1.f)))-max(t1.c) from t1)) then t1.b*t1.f else f end)/abs(b+19)) FROM t1 WHERE a not in ((11),(t1.d),a) or case when f(abs(d)/abs(t1.d)))) then a when f not between t1.f | t1.b and t1.d then a else 13 end from t1 where 19<=c),f) then t1.a else f end between 13 and 11} +} {} +do_test randexpr-2.2360 { + db eval {SELECT (abs(case when t1.d not in (t1.f,t1.d,(select abs(min(((select +count(*)*case max(t1.e-coalesce((select max(case t1.b when 13 then a else e end) from t1 where t1.b>b),19)+d)- -+count(*) when +cast(avg(d) AS integer) then max(c) else (cast(avg(c) AS integer)) end | count(*) from t1)+t1.f)))-max(t1.c) from t1)) then t1.b*t1.f else f end)/abs(b+19)) FROM t1 WHERE NOT (a not in ((11),(t1.d),a) or case when f(abs(d)/abs(t1.d)))) then a when f not between t1.f | t1.b and t1.d then a else 13 end from t1 where 19<=c),f) then t1.a else f end between 13 and 11)} +} {2} +do_test randexpr-2.2361 { + db eval {SELECT (abs(case when t1.d not in (t1.f,t1.d,(select abs(min(((select +count(*)*case max(t1.e-coalesce((select max(case t1.b when 13 then a else e end) from t1 where t1.b>b),19)+d)- -+count(*) when +cast(avg(d) AS integer) then max(c) else (cast(avg(c) AS integer)) end & count(*) from t1)+t1.f)))-max(t1.c) from t1)) then t1.b*t1.f else f end)/abs(b+19)) FROM t1 WHERE NOT (a not in ((11),(t1.d),a) or case when f(abs(d)/abs(t1.d)))) then a when f not between t1.f | t1.b and t1.d then a else 13 end from t1 where 19<=c),f) then t1.a else f end between 13 and 11)} +} {2} +do_test randexpr-2.2362 { + db eval {SELECT t1.a+d | +case when +t1.a-t1.f++t1.c+(select case ~count(*) when (+cast(avg(f*t1.f) AS integer) | min(t1.b)) then -(cast(avg(t1.f) AS integer)) else min(e) end from t1)-b* - -13-f+c in (select b from t1 union select t1.d from t1) or et1.a),t1.f) between t1.a and 19 then ( -b) else t1.a end) from t1 where t1.c in (a,(f),e)),t1.c))/abs(a)))) from t1)) from t1 where case when exists(select 1 from t1 where e<11) and 17 in (select 11 from t1 union select a from t1) then d else (d) end in (select cast(avg(f) AS integer) from t1 union select count(*) from t1)),t1.d) FROM t1 WHERE exists(select 1 from t1 where b not between case 11 when d then (select + -(abs(abs(case -min(d)+ - -count(*)-max(c) when count(*) then max(t1.b) else count(*) end))) from t1)+t1.f-f*t1.b*((select min(a) from t1))-b+f else t1.e end | t1.c+13 and 19) and bt1.e)} +} {400} +do_test randexpr-2.2366 { + db eval {SELECT coalesce((select max((select (max((abs(coalesce((select max(+case when ~t1.d=t1.a then a when coalesce((select case when t1.c in (select 19 from t1 union select (d) from t1) then e else f end from t1 where t1.a<>t1.a),t1.f) between t1.a and 19 then ( -b) else t1.a end) from t1 where t1.c in (a,(f),e)),t1.c))/abs(a)))) from t1)) from t1 where case when exists(select 1 from t1 where e<11) and 17 in (select 11 from t1 union select a from t1) then d else (d) end in (select cast(avg(f) AS integer) from t1 union select count(*) from t1)),t1.d) FROM t1 WHERE NOT (exists(select 1 from t1 where b not between case 11 when d then (select + -(abs(abs(case -min(d)+ - -count(*)-max(c) when count(*) then max(t1.b) else count(*) end))) from t1)+t1.f-f*t1.b*((select min(a) from t1))-b+f else t1.e end | t1.c+13 and 19) and bt1.e))} +} {} +do_test randexpr-2.2367 { + db eval {SELECT case when t1.d+b+c | case +a-t1.d-f*(select cast(avg(17) AS integer)+count(distinct e)-count(distinct t1.a) | - -cast(avg(t1.b) AS integer) from t1)+~t1.e-a when d then t1.f else d end+t1.e*b<>11 then f when t1.a=b or t1.b>(t1.d) then 19 else t1.f end+19 FROM t1 WHERE coalesce((select case t1.e-case coalesce((select (select min(t1.d) from t1) from t1 where coalesce((select max(coalesce((select max(a) from t1 where t1.d in (select cast(avg(t1.b) AS integer) from t1 union select count(distinct a) from t1)), -19)*t1.e) from t1 where d>11),t1.f)>17),t1.f) when (17) then e else d end when b then (19) else 19 end from t1 where not t1.f in (select ( -max(13)) from t1 union select max(c) from t1)),11)-d not in ( -19,13,d)} +} {619} +do_test randexpr-2.2368 { + db eval {SELECT case when t1.d+b+c | case +a-t1.d-f*(select cast(avg(17) AS integer)+count(distinct e)-count(distinct t1.a) | - -cast(avg(t1.b) AS integer) from t1)+~t1.e-a when d then t1.f else d end+t1.e*b<>11 then f when t1.a=b or t1.b>(t1.d) then 19 else t1.f end+19 FROM t1 WHERE NOT (coalesce((select case t1.e-case coalesce((select (select min(t1.d) from t1) from t1 where coalesce((select max(coalesce((select max(a) from t1 where t1.d in (select cast(avg(t1.b) AS integer) from t1 union select count(distinct a) from t1)), -19)*t1.e) from t1 where d>11),t1.f)>17),t1.f) when (17) then e else d end when b then (19) else 19 end from t1 where not t1.f in (select ( -max(13)) from t1 union select max(c) from t1)),11)-d not in ( -19,13,d))} +} {} +do_test randexpr-2.2369 { + db eval {SELECT case when t1.d+b+c & case +a-t1.d-f*(select cast(avg(17) AS integer)+count(distinct e)-count(distinct t1.a) & - -cast(avg(t1.b) AS integer) from t1)+~t1.e-a when d then t1.f else d end+t1.e*b<>11 then f when t1.a=b or t1.b>(t1.d) then 19 else t1.f end+19 FROM t1 WHERE coalesce((select case t1.e-case coalesce((select (select min(t1.d) from t1) from t1 where coalesce((select max(coalesce((select max(a) from t1 where t1.d in (select cast(avg(t1.b) AS integer) from t1 union select count(distinct a) from t1)), -19)*t1.e) from t1 where d>11),t1.f)>17),t1.f) when (17) then e else d end when b then (19) else 19 end from t1 where not t1.f in (select ( -max(13)) from t1 union select max(c) from t1)),11)-d not in ( -19,13,d)} +} {619} +do_test randexpr-2.2370 { + db eval {SELECT case when (t1.a not in (coalesce((select 17 from t1 where case when t1.b*(abs( -t1.b*f*coalesce((select 17 from t1 where not t1.dt1.d then 13 when c>b then c else 11 end when e then a else t1.e end>c) or 19 in (select ++min(f) from t1 union select -count(distinct t1.a) from t1) then (case when t1.f in (select t1.f from t1 union select -t1.a from t1) then c when b not between t1.a and b then -t1.c else t1.a end) else t1.c end not in (f,a,17) then 11 else 11 end FROM t1 WHERE not c not between (select abs(max(~(19*e-t1.a*c*t1.d))*~abs((abs(min(a)-min(c) | cast(avg(19) AS integer))) | count(distinct 19)) | (cast(avg(d) AS integer))) from t1) and (abs(case coalesce((select max(19) from t1 where b not between a and f or 19 in (t1.c,t1.c,b)),t1.e) when c then f else 11 end)/abs(c))} +} {} +do_test randexpr-2.2373 { + db eval {SELECT case when case when (case (t1.a)*case when ct1.d then 13 when c>b then c else 11 end when e then a else t1.e end>c) or 19 in (select ++min(f) from t1 union select -count(distinct t1.a) from t1) then (case when t1.f in (select t1.f from t1 union select -t1.a from t1) then c when b not between t1.a and b then -t1.c else t1.a end) else t1.c end not in (f,a,17) then 11 else 11 end FROM t1 WHERE NOT (not c not between (select abs(max(~(19*e-t1.a*c*t1.d))*~abs((abs(min(a)-min(c) | cast(avg(19) AS integer))) | count(distinct 19)) | (cast(avg(d) AS integer))) from t1) and (abs(case coalesce((select max(19) from t1 where b not between a and f or 19 in (t1.c,t1.c,b)),t1.e) when c then f else 11 end)/abs(c)))} +} {11} +do_test randexpr-2.2374 { + db eval {SELECT (select count(*)-+ -(max(~coalesce((select ~b from t1 where not t1.c | 19 not between c+t1.c and d),a)*(abs(t1.a)/abs(d*(case t1.a*case when 17>e then 11 else 13 end when 19 then e else t1.d end)))+17))-cast(avg(c) AS integer) | count(distinct f) from t1)+(select abs(min(11)) from t1) FROM t1 WHERE coalesce((select max(11) from t1 where case when b<=13-~case when ~~(select count(*)+count(*)* -count(*) from t1)>17*17 then t1.f+case when not case when 19 in (t1.e,a,19) then 17 when f<=19 then 17 else -d end=19 then f when a>=19 then d else f end else t1.c end | f then 19 else b end*t1.d between e and b),f)e then 11 else 13 end when 19 then e else t1.d end)))+17))-cast(avg(c) AS integer) | count(distinct f) from t1)+(select abs(min(11)) from t1) FROM t1 WHERE NOT (coalesce((select max(11) from t1 where case when b<=13-~case when ~~(select count(*)+count(*)* -count(*) from t1)>17*17 then t1.f+case when not case when 19 in (t1.e,a,19) then 17 when f<=19 then 17 else -d end=19 then f when a>=19 then d else f end else t1.c end | f then 19 else b end*t1.d between e and b),f)e then 11 else 13 end when 19 then e else t1.d end)))+17))-cast(avg(c) AS integer) & count(distinct f) from t1)+(select abs(min(11)) from t1) FROM t1 WHERE NOT (coalesce((select max(11) from t1 where case when b<=13-~case when ~~(select count(*)+count(*)* -count(*) from t1)>17*17 then t1.f+case when not case when 19 in (t1.e,a,19) then 17 when f<=19 then 17 else -d end=19 then f when a>=19 then d else f end else t1.c end | f then 19 else b end*t1.d between e and b),f)19 then 11 else 17 end-t1.d FROM t1 WHERE (select min(a) from t1)19 then 11 else 17 end-t1.d FROM t1 WHERE NOT ((select min(a) from t1)19 then 11 else 17 end-t1.d FROM t1 WHERE (select min(a) from t1)c then t1.a else (d) end),d)<= -t1.c) then t1.e*t1.c else 13 end end FROM t1 WHERE exists(select 1 from t1 where ((b not between f and t1.a)))} +} {15004100} +do_test randexpr-2.2381 { + db eval {SELECT t1.d*11-case 11 when a then 11 else - -t1.b-(t1.b)+c+t1.a* -case when not exists(select 1 from t1 where coalesce((select t1.c from t1 where t1.c=case when 13 in (coalesce((select max(coalesce((select max(t1.c) from t1 where c between t1.d and t1.f and t1.a<=b),e)) from t1 where (11 not in (b,19,c))),b),e, -b) then 17 when t1.a in (b,t1.d,b) and t1.f>c then t1.a else (d) end),d)<= -t1.c) then t1.e*t1.c else 13 end end FROM t1 WHERE NOT (exists(select 1 from t1 where ((b not between f and t1.a))))} +} {} +do_test randexpr-2.2382 { + db eval {SELECT t1.c*case when not b>(+coalesce((select t1.e from t1 where t1.b>(abs(case when t1.d<=c+ -17*t1.f*19*17 then 11+a-13-t1.d else case (select abs(count(distinct 19))+ -count(distinct 17) from t1) when 17*t1.d then a else t1.a end end)/abs(17))),(11)))+17 then (t1.c)*f else 17 end FROM t1 WHERE (t1.b)-b<=t1.a*13} +} {54000000} +do_test randexpr-2.2383 { + db eval {SELECT t1.c*case when not b>(+coalesce((select t1.e from t1 where t1.b>(abs(case when t1.d<=c+ -17*t1.f*19*17 then 11+a-13-t1.d else case (select abs(count(distinct 19))+ -count(distinct 17) from t1) when 17*t1.d then a else t1.a end end)/abs(17))),(11)))+17 then (t1.c)*f else 17 end FROM t1 WHERE NOT ((t1.b)-b<=t1.a*13)} +} {} +do_test randexpr-2.2384 { + db eval {SELECT t1.b+coalesce((select max(~e- -t1.d+case +b+f when a-case when t1.a-d+t1.c between t1.e and a*e then (abs(e)/abs(t1.a)) else f | -f*t1.b-t1.c end*t1.e+f then 19 else t1.b end*19) from t1 where 19 in (select e from t1 union select 17 from t1)),19) FROM t1 WHERE d in (11,t1.c+c*t1.d+case when t1.c-case when ~(19+13)*c=11 and d<>17 or t1.e>=c then case t1.a when c then f else 11 end+t1.c when t1.f in (select max(13) from t1 union select cast(avg(c) AS integer) from t1) or t1.ct1.b then t1.e else 19 end,a)} +} {} +do_test randexpr-2.2385 { + db eval {SELECT t1.b+coalesce((select max(~e- -t1.d+case +b+f when a-case when t1.a-d+t1.c between t1.e and a*e then (abs(e)/abs(t1.a)) else f | -f*t1.b-t1.c end*t1.e+f then 19 else t1.b end*19) from t1 where 19 in (select e from t1 union select 17 from t1)),19) FROM t1 WHERE NOT (d in (11,t1.c+c*t1.d+case when t1.c-case when ~(19+13)*c=11 and d<>17 or t1.e>=c then case t1.a when c then f else 11 end+t1.c when t1.f in (select max(13) from t1 union select cast(avg(c) AS integer) from t1) or t1.ct1.b then t1.e else 19 end,a))} +} {219} +do_test randexpr-2.2386 { + db eval {SELECT t1.b+coalesce((select max(~e- -t1.d+case +b+f when a-case when t1.a-d+t1.c between t1.e and a*e then (abs(e)/abs(t1.a)) else f & -f*t1.b-t1.c end*t1.e+f then 19 else t1.b end*19) from t1 where 19 in (select e from t1 union select 17 from t1)),19) FROM t1 WHERE NOT (d in (11,t1.c+c*t1.d+case when t1.c-case when ~(19+13)*c=11 and d<>17 or t1.e>=c then case t1.a when c then f else 11 end+t1.c when t1.f in (select max(13) from t1 union select cast(avg(c) AS integer) from t1) or t1.ct1.b then t1.e else 19 end,a))} +} {219} +do_test randexpr-2.2387 { + db eval {SELECT (abs((select (case (abs(max( -t1.a))* -case count(*) when case min(c) when max(d) then count(*) else max(17) end-cast(avg(17) AS integer) then max(11) else cast(avg(t1.d) AS integer) end | max(13)+max(f)) when cast(avg(f) AS integer) then cast(avg(19) AS integer) else (max(11)) end) from t1) | coalesce((select (select max( -t1.d) from t1) from t1 where t1.b-~e in (select d from t1 union select e from t1) and t1.e=t1.d), -t1.e)-17)/abs(t1.e)) | -t1.e FROM t1 WHERE exists(select 1 from t1 where coalesce((select +19 from t1 where (coalesce((select max(e) from t1 where ((coalesce((select max(19) from t1 where coalesce((select t1.d*19+(t1.c) from t1 where e in (select -11 from t1 union select t1.f from t1) and (t1.d) in (select ~max(t1.e) from t1 union select (( -count(*))) from t1) or 19>=(a)),f) in ((e),e,t1.a)),t1.a)<=t1.c))),t1.f+t1.c)>13)),11) in (11,17,t1.d) and e>=t1.b)} +} {} +do_test randexpr-2.2388 { + db eval {SELECT (abs((select (case (abs(max( -t1.a))* -case count(*) when case min(c) when max(d) then count(*) else max(17) end-cast(avg(17) AS integer) then max(11) else cast(avg(t1.d) AS integer) end | max(13)+max(f)) when cast(avg(f) AS integer) then cast(avg(19) AS integer) else (max(11)) end) from t1) | coalesce((select (select max( -t1.d) from t1) from t1 where t1.b-~e in (select d from t1 union select e from t1) and t1.e=t1.d), -t1.e)-17)/abs(t1.e)) | -t1.e FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select +19 from t1 where (coalesce((select max(e) from t1 where ((coalesce((select max(19) from t1 where coalesce((select t1.d*19+(t1.c) from t1 where e in (select -11 from t1 union select t1.f from t1) and (t1.d) in (select ~max(t1.e) from t1 union select (( -count(*))) from t1) or 19>=(a)),f) in ((e),e,t1.a)),t1.a)<=t1.c))),t1.f+t1.c)>13)),11) in (11,17,t1.d) and e>=t1.b))} +} {-499} +do_test randexpr-2.2389 { + db eval {SELECT (abs((select (case (abs(max( -t1.a))* -case count(*) when case min(c) when max(d) then count(*) else max(17) end-cast(avg(17) AS integer) then max(11) else cast(avg(t1.d) AS integer) end & max(13)+max(f)) when cast(avg(f) AS integer) then cast(avg(19) AS integer) else (max(11)) end) from t1) & coalesce((select (select max( -t1.d) from t1) from t1 where t1.b-~e in (select d from t1 union select e from t1) and t1.e=t1.d), -t1.e)-17)/abs(t1.e)) & -t1.e FROM t1 WHERE NOT (exists(select 1 from t1 where coalesce((select +19 from t1 where (coalesce((select max(e) from t1 where ((coalesce((select max(19) from t1 where coalesce((select t1.d*19+(t1.c) from t1 where e in (select -11 from t1 union select t1.f from t1) and (t1.d) in (select ~max(t1.e) from t1 union select (( -count(*))) from t1) or 19>=(a)),f) in ((e),e,t1.a)),t1.a)<=t1.c))),t1.f+t1.c)>13)),11) in (11,17,t1.d) and e>=t1.b))} +} {0} +do_test randexpr-2.2390 { + db eval {SELECT f-coalesce((select 19+t1.e+t1.f from t1 where +11>coalesce((select +t1.f from t1 where t1.a between ~ -(select case cast(avg((abs(t1.d)/abs(t1.b))) AS integer) when -~max(19) then - -case count(distinct c) when count(*) then min((a)) else -min(t1.d) end else max( -t1.b) end from t1) and (select count(distinct f) from t1)),(coalesce((select max(t1.e) from t1 where not 11>=d),t1.c)))),19)-t1.f+19+f*t1.d FROM t1 WHERE f in (select (min((abs(d-t1.c+coalesce((select t1.f from t1 where fcoalesce((select +t1.f from t1 where t1.a between ~ -(select case cast(avg((abs(t1.d)/abs(t1.b))) AS integer) when -~max(19) then - -case count(distinct c) when count(*) then min((a)) else -min(t1.d) end else max( -t1.b) end from t1) and (select count(distinct f) from t1)),(coalesce((select max(t1.e) from t1 where not 11>=d),t1.c)))),19)-t1.f+19+f*t1.d FROM t1 WHERE NOT (f in (select (min((abs(d-t1.c+coalesce((select t1.f from t1 where f(c)), -a) from t1 where (e)<=t1.a),d) then d when e=a then t1.f else f end FROM t1 WHERE f in (13*13-(abs(d)/abs(e)),19,case t1.b+coalesce((select max((abs((abs(17)/abs(a)))/abs(11+t1.c))) from t1 where -t1.c>=t1.f and e in (select count(*) | min(t1.c) from t1 union select cast(avg(e) AS integer) from t1) or 11 not in (e,b,a) or t1.c< -a and t1.e not in (t1.e,b,t1.d)),t1.b) when f then 19 else b end-11) or d>t1.b} +} {-400} +do_test randexpr-2.2393 { + db eval {SELECT t1.b-case when b not between 17 and t1.d*11*f*t1.a or t1.c+case when -t1.e between t1.d and coalesce((select coalesce((select max((select ~count(*) from t1)) from t1 where -17*13-19-((d))<>(c)), -a) from t1 where (e)<=t1.a),d) then d when e=a then t1.f else f end FROM t1 WHERE NOT (f in (13*13-(abs(d)/abs(e)),19,case t1.b+coalesce((select max((abs((abs(17)/abs(a)))/abs(11+t1.c))) from t1 where -t1.c>=t1.f and e in (select count(*) | min(t1.c) from t1 union select cast(avg(e) AS integer) from t1) or 11 not in (e,b,a) or t1.c< -a and t1.e not in (t1.e,b,t1.d)),t1.b) when f then 19 else b end-11) or d>t1.b)} +} {} +do_test randexpr-2.2394 { + db eval {SELECT case t1.d when (abs(17)/abs(coalesce((select max(e) from t1 where a not in (t1.e,case when 11+t1.d not between t1.e and -t1.c | t1.a*(abs(b)/abs(c)) then -d when a in (select +11 from t1 union select c from t1) then -t1.c else 13 end | t1.c,t1.b)),d)-f)) | t1.c then case when 13t1.d then 13 else f end else b end FROM t1 WHERE 17>d*~t1.e+case when not t1.f<>(select count(distinct 19)+min(e) from t1) then case when (13-a<= -t1.b) and t1.f<=t1.f then 19*d else f end-t1.f*d+t1.d when b not in (t1.b,19,19) or t1.d not between t1.b and a then t1.f else b end} +} {200} +do_test randexpr-2.2395 { + db eval {SELECT case t1.d when (abs(17)/abs(coalesce((select max(e) from t1 where a not in (t1.e,case when 11+t1.d not between t1.e and -t1.c | t1.a*(abs(b)/abs(c)) then -d when a in (select +11 from t1 union select c from t1) then -t1.c else 13 end | t1.c,t1.b)),d)-f)) | t1.c then case when 13t1.d then 13 else f end else b end FROM t1 WHERE NOT (17>d*~t1.e+case when not t1.f<>(select count(distinct 19)+min(e) from t1) then case when (13-a<= -t1.b) and t1.f<=t1.f then 19*d else f end-t1.f*d+t1.d when b not in (t1.b,19,19) or t1.d not between t1.b and a then t1.f else b end)} +} {} +do_test randexpr-2.2396 { + db eval {SELECT case t1.d when (abs(17)/abs(coalesce((select max(e) from t1 where a not in (t1.e,case when 11+t1.d not between t1.e and -t1.c & t1.a*(abs(b)/abs(c)) then -d when a in (select +11 from t1 union select c from t1) then -t1.c else 13 end & t1.c,t1.b)),d)-f)) & t1.c then case when 13t1.d then 13 else f end else b end FROM t1 WHERE 17>d*~t1.e+case when not t1.f<>(select count(distinct 19)+min(e) from t1) then case when (13-a<= -t1.b) and t1.f<=t1.f then 19*d else f end-t1.f*d+t1.d when b not in (t1.b,19,19) or t1.d not between t1.b and a then t1.f else b end} +} {200} +do_test randexpr-2.2397 { + db eval {SELECT coalesce((select max(d) from t1 where coalesce((select t1.c from t1 where 17>b),d*coalesce((select max(11*19) from t1 where coalesce((select c from t1 where 19<(abs((case a when b then ~case t1.a+(select min(t1.f)+min(b) from t1) when (d) then e else t1.b end else t1.c end+f+t1.f))/abs(t1.b))),c)<=19),13))*d | eb),d*coalesce((select max(11*19) from t1 where coalesce((select c from t1 where 19<(abs((case a when b then ~case t1.a+(select min(t1.f)+min(b) from t1) when (d) then e else t1.b end else t1.c end+f+t1.f))/abs(t1.b))),c)<=19),13))*d | eb),d*coalesce((select max(11*19) from t1 where coalesce((select c from t1 where 19<(abs((case a when b then ~case t1.a+(select min(t1.f)+min(b) from t1) when (d) then e else t1.b end else t1.c end+f+t1.f))/abs(t1.b))),c)<=19),13))*d & et1.e and 11 in (t1.e,t1.e,d)),f)+13 then t1.b else c end))- -f)) from t1)) AS integer))-count(distinct 11+11+13)+count(distinct t1.a) from t1) FROM t1 WHERE t1.d=b then t1.c when -f*e<=t1.b then e else 17 end not between 17 and t1.f then t1.c else t1.b end-19+f+19*(t1.c)} +} {-558600} +do_test randexpr-2.2401 { + db eval {SELECT t1.b+ -t1.d*(select max(t1.a) | count(*) | abs(cast(avg(f+a-(select ~(min((abs(a)/abs(13+case when f=coalesce((select t1.b from t1 where d<>t1.e and 11 in (t1.e,t1.e,d)),f)+13 then t1.b else c end))- -f)) from t1)) AS integer))-count(distinct 11+11+13)+count(distinct t1.a) from t1) FROM t1 WHERE NOT (t1.d=b then t1.c when -f*e<=t1.b then e else 17 end not between 17 and t1.f then t1.c else t1.b end-19+f+19*(t1.c))} +} {} +do_test randexpr-2.2402 { + db eval {SELECT t1.b+ -t1.d*(select max(t1.a) & count(*) & abs(cast(avg(f+a-(select ~(min((abs(a)/abs(13+case when f=coalesce((select t1.b from t1 where d<>t1.e and 11 in (t1.e,t1.e,d)),f)+13 then t1.b else c end))- -f)) from t1)) AS integer))-count(distinct 11+11+13)+count(distinct t1.a) from t1) FROM t1 WHERE t1.d=b then t1.c when -f*e<=t1.b then e else 17 end not between 17 and t1.f then t1.c else t1.b end-19+f+19*(t1.c)} +} {200} +do_test randexpr-2.2403 { + db eval {SELECT case when case when t1.e<~17 or (case case case t1.d*17*13 when t1.a then e+c else c end when d*f+coalesce((select 17 from t1 where 13 not between 13 and -13),(17)) then t1.b else b end when t1.a then a else t1.c end*d<>d) then ~t1.c else a end<>t1.f then -t1.d else t1.a end+11-t1.c-e FROM t1 WHERE (case when (~f- -e in (17,case when d in (select t1.f from t1 union select a+(abs(coalesce((select (t1.c) from t1 where a in (select min(13) | (max(t1.e)) from t1 union select count(distinct t1.d) from t1)),b)+13)/abs(e))*19*f from t1) then b when not a between 13 and 13 then t1.f else 17 end,t1.c)) then (select max(t1.e)-count(*) | count(*) from t1) else c end)>(t1.e)} +} {} +do_test randexpr-2.2404 { + db eval {SELECT case when case when t1.e<~17 or (case case case t1.d*17*13 when t1.a then e+c else c end when d*f+coalesce((select 17 from t1 where 13 not between 13 and -13),(17)) then t1.b else b end when t1.a then a else t1.c end*d<>d) then ~t1.c else a end<>t1.f then -t1.d else t1.a end+11-t1.c-e FROM t1 WHERE NOT ((case when (~f- -e in (17,case when d in (select t1.f from t1 union select a+(abs(coalesce((select (t1.c) from t1 where a in (select min(13) | (max(t1.e)) from t1 union select count(distinct t1.d) from t1)),b)+13)/abs(e))*19*f from t1) then b when not a between 13 and 13 then t1.f else 17 end,t1.c)) then (select max(t1.e)-count(*) | count(*) from t1) else c end)>(t1.e))} +} {-1189} +do_test randexpr-2.2405 { + db eval {SELECT coalesce((select max(t1.a-(abs(e*coalesce((select max(d) from t1 where (case when case e when case when (t1.e)=d then t1.a+11 else 17 end then (c) else b end<=a then b when 19 in (t1.b,b,t1.e) then f else -19 end+17 between 19 and c or b in (select t1.c from t1 union select t1.a from t1))),t1.a))/abs( -t1.d))) from t1 where 13=17),t1.b)+(t1.b) FROM t1 WHERE coalesce((select -case when (d)>=(select ~case +(+~~cast(avg(a) AS integer)*abs(( -count(*))) | count(distinct 11)) when (count(*)) then count(distinct 19) else min(t1.a) end+min(t1.a) from t1)*13-t1.f then 13 else (e) | t1.c*(select (min(17)) from t1) end*case when (c) in (select 11 from t1 union select t1.f from t1) then 17 else 19 end from t1 where t1.cc} +} {400} +do_test randexpr-2.2406 { + db eval {SELECT coalesce((select max(t1.a-(abs(e*coalesce((select max(d) from t1 where (case when case e when case when (t1.e)=d then t1.a+11 else 17 end then (c) else b end<=a then b when 19 in (t1.b,b,t1.e) then f else -19 end+17 between 19 and c or b in (select t1.c from t1 union select t1.a from t1))),t1.a))/abs( -t1.d))) from t1 where 13=17),t1.b)+(t1.b) FROM t1 WHERE NOT (coalesce((select -case when (d)>=(select ~case +(+~~cast(avg(a) AS integer)*abs(( -count(*))) | count(distinct 11)) when (count(*)) then count(distinct 19) else min(t1.a) end+min(t1.a) from t1)*13-t1.f then 13 else (e) | t1.c*(select (min(17)) from t1) end*case when (c) in (select 11 from t1 union select t1.f from t1) then 17 else 19 end from t1 where t1.cc)} +} {} +do_test randexpr-2.2407 { + db eval {SELECT t1.b-t1.d-case when exists(select 1 from t1 where -coalesce((select t1.a from t1 where a in (c,coalesce((select max((abs(t1.d)/abs(e))) from t1 where case t1.b when t1.e then t1.d else t1.d end-17 between b and t1.f),17)-t1.f-t1.e,t1.a) or t1.b in (t1.a,19,t1.f)),19)>=d) then 19-b when t1.c between (f) and t1.f then t1.d else t1.f end-11 FROM t1 WHERE coalesce((select 13 from t1 where ( -t1.a13 or a in (select cast(avg(d) AS integer) | count(*)* -max(t1.f) from t1 union select count(*) from t1) then 17 when not exists(select 1 from t1 where b>=c) then e else 17 end | -t1.a))*b)*t1.d>=b} +} {-811} +do_test randexpr-2.2408 { + db eval {SELECT t1.b-t1.d-case when exists(select 1 from t1 where -coalesce((select t1.a from t1 where a in (c,coalesce((select max((abs(t1.d)/abs(e))) from t1 where case t1.b when t1.e then t1.d else t1.d end-17 between b and t1.f),17)-t1.f-t1.e,t1.a) or t1.b in (t1.a,19,t1.f)),19)>=d) then 19-b when t1.c between (f) and t1.f then t1.d else t1.f end-11 FROM t1 WHERE NOT (coalesce((select 13 from t1 where ( -t1.a13 or a in (select cast(avg(d) AS integer) | count(*)* -max(t1.f) from t1 union select count(*) from t1) then 17 when not exists(select 1 from t1 where b>=c) then e else 17 end | -t1.a))*b)*t1.d>=b)} +} {} +do_test randexpr-2.2409 { + db eval {SELECT 17 | t1.c*t1.a | case when ~ -~(abs(t1.b)/abs(coalesce((select max(coalesce((select max(+t1.d) from t1 where (t1.b not between 17 and t1.b) and d not between c and 19),d)*(t1.d)-d) from t1 where t1.a in (t1.c,(t1.c),t1.f)),19)))-b+19+ -17>=t1.a then 19 when 19 in (select t1.f from t1 union select t1.b from t1) then t1.c else f end-19*t1.c FROM t1 WHERE (17-t1.f in (d | b-17,t1.f,coalesce((select e+(abs(11)/abs(case t1.c when case (abs(a)/abs(11)) when e then t1.c else 17+c end then b else 11+t1.e end)) from t1 where (13 not between + -b and 13)),t1.c)) and 17 between t1.d | t1.f and t1.e)} +} {} +do_test randexpr-2.2410 { + db eval {SELECT 17 | t1.c*t1.a | case when ~ -~(abs(t1.b)/abs(coalesce((select max(coalesce((select max(+t1.d) from t1 where (t1.b not between 17 and t1.b) and d not between c and 19),d)*(t1.d)-d) from t1 where t1.a in (t1.c,(t1.c),t1.f)),19)))-b+19+ -17>=t1.a then 19 when 19 in (select t1.f from t1 union select t1.b from t1) then t1.c else f end-19*t1.c FROM t1 WHERE NOT ((17-t1.f in (d | b-17,t1.f,coalesce((select e+(abs(11)/abs(case t1.c when case (abs(a)/abs(11)) when e then t1.c else 17+c end then b else 11+t1.e end)) from t1 where (13 not between + -b and 13)),t1.c)) and 17 between t1.d | t1.f and t1.e))} +} {-715} +do_test randexpr-2.2411 { + db eval {SELECT 17 & t1.c*t1.a & case when ~ -~(abs(t1.b)/abs(coalesce((select max(coalesce((select max(+t1.d) from t1 where (t1.b not between 17 and t1.b) and d not between c and 19),d)*(t1.d)-d) from t1 where t1.a in (t1.c,(t1.c),t1.f)),19)))-b+19+ -17>=t1.a then 19 when 19 in (select t1.f from t1 union select t1.b from t1) then t1.c else f end-19*t1.c FROM t1 WHERE NOT ((17-t1.f in (d | b-17,t1.f,coalesce((select e+(abs(11)/abs(case t1.c when case (abs(a)/abs(11)) when e then t1.c else 17+c end then b else 11+t1.e end)) from t1 where (13 not between + -b and 13)),t1.c)) and 17 between t1.d | t1.f and t1.e))} +} {16} +do_test randexpr-2.2412 { + db eval {SELECT coalesce((select t1.a*a+t1.f | t1.d from t1 where t1.d<+t1.c*d-c*19+t1.e-(abs( -t1.e)/abs(19))), -t1.c+coalesce((select t1.b from t1 where not not (select max(t1.c) from t1)-17+e in (e,t1.c,b) and not (d in (select ( -((max(b)))) from t1 union select min(d) from t1))),t1.b) | t1.a) FROM t1 WHERE not t1.f in (select ((select abs(count(*)) from t1)-11) from t1 union select t1.a-17 from t1) or not exists(select 1 from t1 where case (abs(e)/abs(+c)) when coalesce((select max((select +(count(distinct t1.a)) from t1)) from t1 where not (e<=c*t1.a)),~(case when t1.c<=17 then e when t1.c<=t1.c then e else 17 end)) then 13 else d end*b-a= -d)} +} {10744} +do_test randexpr-2.2413 { + db eval {SELECT coalesce((select t1.a*a+t1.f | t1.d from t1 where t1.d<+t1.c*d-c*19+t1.e-(abs( -t1.e)/abs(19))), -t1.c+coalesce((select t1.b from t1 where not not (select max(t1.c) from t1)-17+e in (e,t1.c,b) and not (d in (select ( -((max(b)))) from t1 union select min(d) from t1))),t1.b) | t1.a) FROM t1 WHERE NOT (not t1.f in (select ((select abs(count(*)) from t1)-11) from t1 union select t1.a-17 from t1) or not exists(select 1 from t1 where case (abs(e)/abs(+c)) when coalesce((select max((select +(count(distinct t1.a)) from t1)) from t1 where not (e<=c*t1.a)),~(case when t1.c<=17 then e when t1.c<=t1.c then e else 17 end)) then 13 else d end*b-a= -d))} +} {} +do_test randexpr-2.2414 { + db eval {SELECT coalesce((select t1.a*a+t1.f & t1.d from t1 where t1.d<+t1.c*d-c*19+t1.e-(abs( -t1.e)/abs(19))), -t1.c+coalesce((select t1.b from t1 where not not (select max(t1.c) from t1)-17+e in (e,t1.c,b) and not (d in (select ( -((max(b)))) from t1 union select min(d) from t1))),t1.b) & t1.a) FROM t1 WHERE not t1.f in (select ((select abs(count(*)) from t1)-11) from t1 union select t1.a-17 from t1) or not exists(select 1 from t1 where case (abs(e)/abs(+c)) when coalesce((select max((select +(count(distinct t1.a)) from t1)) from t1 where not (e<=c*t1.a)),~(case when t1.c<=17 then e when t1.c<=t1.c then e else 17 end)) then 13 else d end*b-a= -d)} +} {256} +do_test randexpr-2.2415 { + db eval {SELECT case a+(abs(+13)/abs(a)) when ~(e)*(abs(b* -t1.d*19-t1.c+a-~t1.b*b-coalesce((select max(case when not exists(select 1 from t1 where d in (f,t1.c,f) or t1.c not in (13,f,t1.a)) then case when t1.a>= -t1.e then (( - -b)) else t1.b end else c end+e) from t1 where (a>11)),13)*17)/abs(e)) then 11 else c end FROM t1 WHERE 17 between a and t1.a} +} {} +do_test randexpr-2.2416 { + db eval {SELECT case a+(abs(+13)/abs(a)) when ~(e)*(abs(b* -t1.d*19-t1.c+a-~t1.b*b-coalesce((select max(case when not exists(select 1 from t1 where d in (f,t1.c,f) or t1.c not in (13,f,t1.a)) then case when t1.a>= -t1.e then (( - -b)) else t1.b end else c end+e) from t1 where (a>11)),13)*17)/abs(e)) then 11 else c end FROM t1 WHERE NOT (17 between a and t1.a)} +} {300} +do_test randexpr-2.2417 { + db eval {SELECT +~t1.f-c*case when t1.f between coalesce((select max(a) from t1 where (t1.c-17*t1.b | c=e)),t1.b) and (abs(coalesce((select max(19) from t1 where t1.b not between c+(select min(t1.d) from t1)-t1.d+d+t1.d+t1.c*t1.e and 11),t1.a))/abs(a))-c*b then 17 else 13 end FROM t1 WHERE t1.c not between (abs(+case when not -19 in (case when t1.b+~d+11+f>e then (select -cast(avg(coalesce((select 17 from t1 where (t1.b>=f)),19)) AS integer)*min(d)*(min(e))* -min(b) from t1) when 17+b not between 17 and t1.a then 11 else a end,19,(t1.e)) then f else 19 end*t1.a)/abs(b)) and 19} +} {-4501} +do_test randexpr-2.2418 { + db eval {SELECT +~t1.f-c*case when t1.f between coalesce((select max(a) from t1 where (t1.c-17*t1.b | c=e)),t1.b) and (abs(coalesce((select max(19) from t1 where t1.b not between c+(select min(t1.d) from t1)-t1.d+d+t1.d+t1.c*t1.e and 11),t1.a))/abs(a))-c*b then 17 else 13 end FROM t1 WHERE NOT (t1.c not between (abs(+case when not -19 in (case when t1.b+~d+11+f>e then (select -cast(avg(coalesce((select 17 from t1 where (t1.b>=f)),19)) AS integer)*min(d)*(min(e))* -min(b) from t1) when 17+b not between 17 and t1.a then 11 else a end,19,(t1.e)) then f else 19 end*t1.a)/abs(b)) and 19)} +} {} +do_test randexpr-2.2419 { + db eval {SELECT +~t1.f-c*case when t1.f between coalesce((select max(a) from t1 where (t1.c-17*t1.b & c=e)),t1.b) and (abs(coalesce((select max(19) from t1 where t1.b not between c+(select min(t1.d) from t1)-t1.d+d+t1.d+t1.c*t1.e and 11),t1.a))/abs(a))-c*b then 17 else 13 end FROM t1 WHERE t1.c not between (abs(+case when not -19 in (case when t1.b+~d+11+f>e then (select -cast(avg(coalesce((select 17 from t1 where (t1.b>=f)),19)) AS integer)*min(d)*(min(e))* -min(b) from t1) when 17+b not between 17 and t1.a then 11 else a end,19,(t1.e)) then f else 19 end*t1.a)/abs(b)) and 19} +} {-4501} +do_test randexpr-2.2420 { + db eval {SELECT +(abs(case t1.a when coalesce((select max(13) from t1 where d<=case when t1.b=(select abs(count(distinct t1.e)) from t1) and (select -count(distinct e) from t1) not in ( -11,e,13) then 13 else t1.e end and (not exists(select 1 from t1 where t1.d in (select count(*) from t1 union select max(f) from t1))) and 19=13 or -e=17),coalesce((select (abs(17)/abs(b))-t1.b from t1 where (19)<=t1.f),t1.d))*t1.b then 17 else 13 end)/abs(19)) FROM t1 WHERE a in (select case max(13)-~cast(avg(case when t1.d>13 or exists(select 1 from t1 where not (( -c<=e)) and (b)*t1.a in (select count(*) from t1 union select cast(avg(t1.c) AS integer)+max(f) from t1)) then t1.a else t1.c end) AS integer) when abs(count(distinct t1.d)) then count(distinct (~t1.a)) else count(distinct c)-cast(avg(e) AS integer) end from t1 union select abs(count(distinct a)*max(t1.d)) from t1)} +} {} +do_test randexpr-2.2421 { + db eval {SELECT +(abs(case t1.a when coalesce((select max(13) from t1 where d<=case when t1.b=(select abs(count(distinct t1.e)) from t1) and (select -count(distinct e) from t1) not in ( -11,e,13) then 13 else t1.e end and (not exists(select 1 from t1 where t1.d in (select count(*) from t1 union select max(f) from t1))) and 19=13 or -e=17),coalesce((select (abs(17)/abs(b))-t1.b from t1 where (19)<=t1.f),t1.d))*t1.b then 17 else 13 end)/abs(19)) FROM t1 WHERE NOT (a in (select case max(13)-~cast(avg(case when t1.d>13 or exists(select 1 from t1 where not (( -c<=e)) and (b)*t1.a in (select count(*) from t1 union select cast(avg(t1.c) AS integer)+max(f) from t1)) then t1.a else t1.c end) AS integer) when abs(count(distinct t1.d)) then count(distinct (~t1.a)) else count(distinct c)-cast(avg(e) AS integer) end from t1 union select abs(count(distinct a)*max(t1.d)) from t1))} +} {0} +do_test randexpr-2.2422 { + db eval {SELECT +coalesce((select max(f+c) from t1 where t1.b in (select +max(b+t1.b) from t1 union select cast(avg(d-b | f-11-t1.b | coalesce((select ~t1.a from t1 where (t1.a=case when not exists(select 1 from t1 where 13 not in (t1.b,t1.e,t1.f)) then (abs(t1.d)/abs(c)) when c<>17 then c else 19 end)),t1.c)) AS integer) from t1) and t1.e not in (b,d,(13))),t1.b) FROM t1 WHERE (select cast(avg(~t1.f) AS integer) from t1) not in ( -c,17,11*c)} +} {200} +do_test randexpr-2.2423 { + db eval {SELECT +coalesce((select max(f+c) from t1 where t1.b in (select +max(b+t1.b) from t1 union select cast(avg(d-b | f-11-t1.b | coalesce((select ~t1.a from t1 where (t1.a=case when not exists(select 1 from t1 where 13 not in (t1.b,t1.e,t1.f)) then (abs(t1.d)/abs(c)) when c<>17 then c else 19 end)),t1.c)) AS integer) from t1) and t1.e not in (b,d,(13))),t1.b) FROM t1 WHERE NOT ((select cast(avg(~t1.f) AS integer) from t1) not in ( -c,17,11*c))} +} {} +do_test randexpr-2.2424 { + db eval {SELECT +coalesce((select max(f+c) from t1 where t1.b in (select +max(b+t1.b) from t1 union select cast(avg(d-b & f-11-t1.b & coalesce((select ~t1.a from t1 where (t1.a=case when not exists(select 1 from t1 where 13 not in (t1.b,t1.e,t1.f)) then (abs(t1.d)/abs(c)) when c<>17 then c else 19 end)),t1.c)) AS integer) from t1) and t1.e not in (b,d,(13))),t1.b) FROM t1 WHERE (select cast(avg(~t1.f) AS integer) from t1) not in ( -c,17,11*c)} +} {200} +do_test randexpr-2.2425 { + db eval {SELECT t1.e*case when ((13)-13-13-t1.d+t1.c*b>11) then b when case when (t1.a*b not in (t1.a,t1.b,t1.f)) then 11+e else t1.f end<= -f or f in (t1.a,11,13) or exists(select 1 from t1 where not exists(select 1 from t1 where f in (f,d,t1.e))) then t1.d else b end FROM t1 WHERE coalesce((select 19 from t1 where 13-t1.b*c-t1.a+case when case when coalesce((select +t1.b from t1 where a<>b),13) in ((b),t1.f,b) and not t1.b in (select -cast(avg(13) AS integer) from t1 union select cast(avg(11) AS integer) from t1) or a>=13 then (abs(t1.b+a)/abs(11)) else t1.e end-17+t1.d<>b then (19) else f end=e),13)>=t1.c} +} {} +do_test randexpr-2.2426 { + db eval {SELECT t1.e*case when ((13)-13-13-t1.d+t1.c*b>11) then b when case when (t1.a*b not in (t1.a,t1.b,t1.f)) then 11+e else t1.f end<= -f or f in (t1.a,11,13) or exists(select 1 from t1 where not exists(select 1 from t1 where f in (f,d,t1.e))) then t1.d else b end FROM t1 WHERE NOT (coalesce((select 19 from t1 where 13-t1.b*c-t1.a+case when case when coalesce((select +t1.b from t1 where a<>b),13) in ((b),t1.f,b) and not t1.b in (select -cast(avg(13) AS integer) from t1 union select cast(avg(11) AS integer) from t1) or a>=13 then (abs(t1.b+a)/abs(11)) else t1.e end-17+t1.d<>b then (19) else f end=e),13)>=t1.c)} +} {100000} +do_test randexpr-2.2427 { + db eval {SELECT coalesce((select max(d) from t1 where 19+case t1.b when t1.a-a then (abs(case when (e>=case t1.a when coalesce((select max(t1.d) from t1 where (select case -max(c)+cast(avg(t1.a) AS integer) when cast(avg(t1.a) AS integer) then cast(avg(19) AS integer) else cast(avg(t1.b) AS integer) end from t1)>t1.c),coalesce((select max(d) from t1 where 19<>17 and d<=b), -(t1.c)))+e then c else t1.d end+b) then b when 19 between c and 17 then 11 else e end)/abs( -t1.b)) else t1.a end+13>=d),d) FROM t1 WHERE a=case when t1.f in (select (max(f)-++(min(t1.a))-max(19)-count(*)) from t1 union select +max(t1.b) from t1) then t1.b*19*19 when t1.f>d then 17-d else t1.f end and exists(select 1 from t1 where not exists(select 1 from t1 where d in (select count(distinct 11)+max(a) from t1 union select cast(avg(13) AS integer) from t1) or 19 not in (t1.b,c,13)))} +} {} +do_test randexpr-2.2428 { + db eval {SELECT coalesce((select max(d) from t1 where 19+case t1.b when t1.a-a then (abs(case when (e>=case t1.a when coalesce((select max(t1.d) from t1 where (select case -max(c)+cast(avg(t1.a) AS integer) when cast(avg(t1.a) AS integer) then cast(avg(19) AS integer) else cast(avg(t1.b) AS integer) end from t1)>t1.c),coalesce((select max(d) from t1 where 19<>17 and d<=b), -(t1.c)))+e then c else t1.d end+b) then b when 19 between c and 17 then 11 else e end)/abs( -t1.b)) else t1.a end+13>=d),d) FROM t1 WHERE NOT (a=case when t1.f in (select (max(f)-++(min(t1.a))-max(19)-count(*)) from t1 union select +max(t1.b) from t1) then t1.b*19*19 when t1.f>d then 17-d else t1.f end and exists(select 1 from t1 where not exists(select 1 from t1 where d in (select count(distinct 11)+max(a) from t1 union select cast(avg(13) AS integer) from t1) or 19 not in (t1.b,c,13))))} +} {400} +do_test randexpr-2.2429 { + db eval {SELECT coalesce((select max(case t1.c | b-t1.d+13 when 17 then c else 13 end) from t1 where case when exists(select 1 from t1 where b<>t1.c) then t1.d when a not between (abs(t1.d)/abs((t1.b))) and (t1.c) or (a in (select ~max(((17))) from t1 union select case -(count(distinct -t1.c)) when count(distinct t1.c) then (count(*)) else max(f) end from t1)) and t1.f>19 or a<>11 then t1.b else t1.b end>(11)),13)+b*(b) FROM t1 WHERE case when not exists(select 1 from t1 where (19<>11+t1.b*c+d)) and 13<>b or t1.d between t1.c and b and f between t1.b and -a or 19 between 19 and 17 or t1.e not between e and t1.d then ~13 else coalesce((select max(t1.b) from t1 where f=a),(a)) end in (select -( -+count(distinct 11)-count(*))*count(distinct ( -t1.c))+(count(distinct t1.c))+max(17)-count(*) from t1 union select count(*) from t1)} +} {} +do_test randexpr-2.2430 { + db eval {SELECT coalesce((select max(case t1.c | b-t1.d+13 when 17 then c else 13 end) from t1 where case when exists(select 1 from t1 where b<>t1.c) then t1.d when a not between (abs(t1.d)/abs((t1.b))) and (t1.c) or (a in (select ~max(((17))) from t1 union select case -(count(distinct -t1.c)) when count(distinct t1.c) then (count(*)) else max(f) end from t1)) and t1.f>19 or a<>11 then t1.b else t1.b end>(11)),13)+b*(b) FROM t1 WHERE NOT (case when not exists(select 1 from t1 where (19<>11+t1.b*c+d)) and 13<>b or t1.d between t1.c and b and f between t1.b and -a or 19 between 19 and 17 or t1.e not between e and t1.d then ~13 else coalesce((select max(t1.b) from t1 where f=a),(a)) end in (select -( -+count(distinct 11)-count(*))*count(distinct ( -t1.c))+(count(distinct t1.c))+max(17)-count(*) from t1 union select count(*) from t1))} +} {40013} +do_test randexpr-2.2431 { + db eval {SELECT coalesce((select max(case t1.c & b-t1.d+13 when 17 then c else 13 end) from t1 where case when exists(select 1 from t1 where b<>t1.c) then t1.d when a not between (abs(t1.d)/abs((t1.b))) and (t1.c) or (a in (select ~max(((17))) from t1 union select case -(count(distinct -t1.c)) when count(distinct t1.c) then (count(*)) else max(f) end from t1)) and t1.f>19 or a<>11 then t1.b else t1.b end>(11)),13)+b*(b) FROM t1 WHERE NOT (case when not exists(select 1 from t1 where (19<>11+t1.b*c+d)) and 13<>b or t1.d between t1.c and b and f between t1.b and -a or 19 between 19 and 17 or t1.e not between e and t1.d then ~13 else coalesce((select max(t1.b) from t1 where f=a),(a)) end in (select -( -+count(distinct 11)-count(*))*count(distinct ( -t1.c))+(count(distinct t1.c))+max(17)-count(*) from t1 union select count(*) from t1))} +} {40013} +do_test randexpr-2.2432 { + db eval {SELECT coalesce((select max(coalesce((select max(11) from t1 where t1.b< -t1.b),e)+coalesce((select t1.b from t1 where not case when ~case when -17+t1.d> - -t1.d then t1.b when t1.b between 13 and c or t1.a>= -f then t1.b else t1.e end+t1.c<= -c then 19 else t1.f end not in (c,d,e) or t1.f not between t1.b and 19 and 13>= -t1.f or 13 in (e,(t1.b),11)),t1.b)) from t1 where -(f) not in (f,(t1.e),b)),t1.f) FROM t1 WHERE f in (select f from t1 union select t1.f*t1.b from t1)} +} {700} +do_test randexpr-2.2433 { + db eval {SELECT coalesce((select max(coalesce((select max(11) from t1 where t1.b< -t1.b),e)+coalesce((select t1.b from t1 where not case when ~case when -17+t1.d> - -t1.d then t1.b when t1.b between 13 and c or t1.a>= -f then t1.b else t1.e end+t1.c<= -c then 19 else t1.f end not in (c,d,e) or t1.f not between t1.b and 19 and 13>= -t1.f or 13 in (e,(t1.b),11)),t1.b)) from t1 where -(f) not in (f,(t1.e),b)),t1.f) FROM t1 WHERE NOT (f in (select f from t1 union select t1.f*t1.b from t1))} +} {} +do_test randexpr-2.2434 { + db eval {SELECT ( -+(a)*(abs(case coalesce((select max(d) from t1 where t1.d<>c*(select count(distinct e*coalesce((select 13-17 from t1 where not exists(select 1 from t1 where t1.a in (select f from t1 union select (a) from t1))),t1.f)+(t1.c)) from t1) | t1.e*19 and not t1.a<13),t1.b)+t1.b when t1.d then (t1.f) else t1.c end)/abs(t1.f))-13*t1.f) FROM t1 WHERE f>=t1.a+ -(select (count(*))-(~case cast(avg(t1.b-13-e) AS integer) when count(*) then (max(t1.f*case 13 when 11 then 13 else c end))- -cast(avg(t1.f) AS integer)*count(*)-min(19) else count(distinct d) end)+min(t1.d) | -max(t1.b) from t1) | t1.b*17+t1.d+t1.b-d} +} {} +do_test randexpr-2.2435 { + db eval {SELECT ( -+(a)*(abs(case coalesce((select max(d) from t1 where t1.d<>c*(select count(distinct e*coalesce((select 13-17 from t1 where not exists(select 1 from t1 where t1.a in (select f from t1 union select (a) from t1))),t1.f)+(t1.c)) from t1) | t1.e*19 and not t1.a<13),t1.b)+t1.b when t1.d then (t1.f) else t1.c end)/abs(t1.f))-13*t1.f) FROM t1 WHERE NOT (f>=t1.a+ -(select (count(*))-(~case cast(avg(t1.b-13-e) AS integer) when count(*) then (max(t1.f*case 13 when 11 then 13 else c end))- -cast(avg(t1.f) AS integer)*count(*)-min(19) else count(distinct d) end)+min(t1.d) | -max(t1.b) from t1) | t1.b*17+t1.d+t1.b-d)} +} {-7800} +do_test randexpr-2.2436 { + db eval {SELECT ( -+(a)*(abs(case coalesce((select max(d) from t1 where t1.d<>c*(select count(distinct e*coalesce((select 13-17 from t1 where not exists(select 1 from t1 where t1.a in (select f from t1 union select (a) from t1))),t1.f)+(t1.c)) from t1) & t1.e*19 and not t1.a<13),t1.b)+t1.b when t1.d then (t1.f) else t1.c end)/abs(t1.f))-13*t1.f) FROM t1 WHERE NOT (f>=t1.a+ -(select (count(*))-(~case cast(avg(t1.b-13-e) AS integer) when count(*) then (max(t1.f*case 13 when 11 then 13 else c end))- -cast(avg(t1.f) AS integer)*count(*)-min(19) else count(distinct d) end)+min(t1.d) | -max(t1.b) from t1) | t1.b*17+t1.d+t1.b-d)} +} {-7800} +do_test randexpr-2.2437 { + db eval {SELECT coalesce((select t1.a from t1 where c in (select a from t1 union select t1.a*f from t1) and t1.b in (select (select count(*) from t1)*11 from t1 union select -13 from t1)),13) FROM t1 WHERE (d=17 then d when f<=t1.c then t1.a else d end,t1.e,e) or not 19>c then t1.c-19 else 13 end<>t1.c} +} {-180500} +do_test randexpr-2.2440 { + db eval {SELECT case when (not exists(select 1 from t1 where a<=case a | e-case t1.f when c then e else 19 end | t1.b when t1.c then t1.e else 19 end+d)) or f between a and b and (t1.f) not in (d,t1.e,11) then case 17+e | t1.c when 19 then 13 else -(19) end | 11 else a end-t1.f-f*t1.c FROM t1 WHERE NOT (case when t1.b in ( - -case when case when t1.f-case when 19<=c then a else 19 end between 13 and t1.d and not a not in ((f),d,f) then t1.c-a when t1.d not in ( -b,c,11) then 13 else f end>=17 then d when f<=t1.c then t1.a else d end,t1.e,e) or not 19>c then t1.c-19 else 13 end<>t1.c)} +} {} +do_test randexpr-2.2441 { + db eval {SELECT case when (not exists(select 1 from t1 where a<=case a & e-case t1.f when c then e else 19 end & t1.b when t1.c then t1.e else 19 end+d)) or f between a and b and (t1.f) not in (d,t1.e,11) then case 17+e & t1.c when 19 then 13 else -(19) end & 11 else a end-t1.f-f*t1.c FROM t1 WHERE case when t1.b in ( - -case when case when t1.f-case when 19<=c then a else 19 end between 13 and t1.d and not a not in ((f),d,f) then t1.c-a when t1.d not in ( -b,c,11) then 13 else f end>=17 then d when f<=t1.c then t1.a else d end,t1.e,e) or not 19>c then t1.c-19 else 13 end<>t1.c} +} {-180500} +do_test randexpr-2.2442 { + db eval {SELECT coalesce((select d-(abs(case when +coalesce((select 19 from t1 where not exists(select 1 from t1 where d | f in (select ~case count(distinct f) when ( -(cast(avg((( -19))) AS integer))) then (count(*)) else count(distinct 17) end*(max(t1.d)) from t1 union select min(b) from t1))),13) | t1.b+t1.e in (13,(t1.b),t1.a) then t1.a when a in (select t1.f from t1 union select t1.b from t1) then t1.e else a end)/abs(f))-t1.e from t1 where not exists(select 1 from t1 where not 19 in (select t1.b from t1 union select t1.f from t1) or 13 in (select e from t1 union select e from t1))),f) FROM t1 WHERE not exists(select 1 from t1 where case when not exists(select 1 from t1 where a<+case c when (abs(t1.b)/abs(e))+t1.b-b-t1.b then (t1.d)*t1.c else t1.d end) then b else 19 end in (select -count(distinct c)*(max(f)) | ~+case min(t1.a) when cast(avg(c) AS integer) then cast(avg(t1.a) AS integer) | count(distinct t1.d)* -count(distinct t1.e) else ( -count(*)) end | -cast(avg(t1.d) AS integer)+min(a)*count(distinct b) from t1 union select max(13) from t1))} +} {600} +do_test randexpr-2.2443 { + db eval {SELECT coalesce((select d-(abs(case when +coalesce((select 19 from t1 where not exists(select 1 from t1 where d | f in (select ~case count(distinct f) when ( -(cast(avg((( -19))) AS integer))) then (count(*)) else count(distinct 17) end*(max(t1.d)) from t1 union select min(b) from t1))),13) | t1.b+t1.e in (13,(t1.b),t1.a) then t1.a when a in (select t1.f from t1 union select t1.b from t1) then t1.e else a end)/abs(f))-t1.e from t1 where not exists(select 1 from t1 where not 19 in (select t1.b from t1 union select t1.f from t1) or 13 in (select e from t1 union select e from t1))),f) FROM t1 WHERE NOT (not exists(select 1 from t1 where case when not exists(select 1 from t1 where a<+case c when (abs(t1.b)/abs(e))+t1.b-b-t1.b then (t1.d)*t1.c else t1.d end) then b else 19 end in (select -count(distinct c)*(max(f)) | ~+case min(t1.a) when cast(avg(c) AS integer) then cast(avg(t1.a) AS integer) | count(distinct t1.d)* -count(distinct t1.e) else ( -count(*)) end | -cast(avg(t1.d) AS integer)+min(a)*count(distinct b) from t1 union select max(13) from t1)))} +} {} +do_test randexpr-2.2444 { + db eval {SELECT coalesce((select d-(abs(case when +coalesce((select 19 from t1 where not exists(select 1 from t1 where d & f in (select ~case count(distinct f) when ( -(cast(avg((( -19))) AS integer))) then (count(*)) else count(distinct 17) end*(max(t1.d)) from t1 union select min(b) from t1))),13) & t1.b+t1.e in (13,(t1.b),t1.a) then t1.a when a in (select t1.f from t1 union select t1.b from t1) then t1.e else a end)/abs(f))-t1.e from t1 where not exists(select 1 from t1 where not 19 in (select t1.b from t1 union select t1.f from t1) or 13 in (select e from t1 union select e from t1))),f) FROM t1 WHERE not exists(select 1 from t1 where case when not exists(select 1 from t1 where a<+case c when (abs(t1.b)/abs(e))+t1.b-b-t1.b then (t1.d)*t1.c else t1.d end) then b else 19 end in (select -count(distinct c)*(max(f)) | ~+case min(t1.a) when cast(avg(c) AS integer) then cast(avg(t1.a) AS integer) | count(distinct t1.d)* -count(distinct t1.e) else ( -count(*)) end | -cast(avg(t1.d) AS integer)+min(a)*count(distinct b) from t1 union select max(13) from t1))} +} {600} +do_test randexpr-2.2445 { + db eval {SELECT (t1.e)+t1.c-coalesce((select max((abs(coalesce((select case when f>=(abs(coalesce((select max(a) from t1 where 11*(t1.f)*a*t1.d=11),t1.b))/abs(t1.d))+t1.b then c when not exists(select 1 from t1 where t1.c<>b) then 13 else 11 end from t1 where (13 not in (f,t1.c,13))),b)+t1.d)/abs(t1.f))) from t1 where b<>t1.a),t1.a) | t1.d FROM t1 WHERE ~a<>a or d<>t1.e} +} {927} +do_test randexpr-2.2446 { + db eval {SELECT (t1.e)+t1.c-coalesce((select max((abs(coalesce((select case when f>=(abs(coalesce((select max(a) from t1 where 11*(t1.f)*a*t1.d=11),t1.b))/abs(t1.d))+t1.b then c when not exists(select 1 from t1 where t1.c<>b) then 13 else 11 end from t1 where (13 not in (f,t1.c,13))),b)+t1.d)/abs(t1.f))) from t1 where b<>t1.a),t1.a) | t1.d FROM t1 WHERE NOT (~a<>a or d<>t1.e)} +} {} +do_test randexpr-2.2447 { + db eval {SELECT (t1.e)+t1.c-coalesce((select max((abs(coalesce((select case when f>=(abs(coalesce((select max(a) from t1 where 11*(t1.f)*a*t1.d=11),t1.b))/abs(t1.d))+t1.b then c when not exists(select 1 from t1 where t1.c<>b) then 13 else 11 end from t1 where (13 not in (f,t1.c,13))),b)+t1.d)/abs(t1.f))) from t1 where b<>t1.a),t1.a) & t1.d FROM t1 WHERE ~a<>a or d<>t1.e} +} {272} +do_test randexpr-2.2448 { + db eval {SELECT case when coalesce((select 11 from t1 where exists(select 1 from t1 where t1.a<= -19)),t1.c-t1.e*e-19-t1.d-t1.e-~a*coalesce((select max(b) from t1 where b>(abs(+c+case c when 11 then t1.f else 11 end)/abs(b))),t1.e)-f+t1.c+19+e-t1.e)<=t1.f then e else c end FROM t1 WHERE (abs(t1.d)/abs(~b)) in (select count(distinct case when t1.c+t1.fe and ((d) between t1.a and d) then t1.b else 13 end else 11 end) from t1 union select count(*) from t1)} +} {500} +do_test randexpr-2.2449 { + db eval {SELECT case when coalesce((select 11 from t1 where exists(select 1 from t1 where t1.a<= -19)),t1.c-t1.e*e-19-t1.d-t1.e-~a*coalesce((select max(b) from t1 where b>(abs(+c+case c when 11 then t1.f else 11 end)/abs(b))),t1.e)-f+t1.c+19+e-t1.e)<=t1.f then e else c end FROM t1 WHERE NOT ((abs(t1.d)/abs(~b)) in (select count(distinct case when t1.c+t1.fe and ((d) between t1.a and d) then t1.b else 13 end else 11 end) from t1 union select count(*) from t1))} +} {} +do_test randexpr-2.2450 { + db eval {SELECT case when 19*case when case when t1.e>((t1.d)) and 11>t1.d then -17 else e end in (select count(distinct a) from t1 union select min(d) from t1) then (d) else e end | t1.c+a in (select count(*) from t1 union select case +(max(19))+count(distinct -t1.d) when min(19) then cast(avg(e) AS integer) else cast(avg(t1.a) AS integer) end from t1) and 17 between 17 and t1.b then -(t1.e) when b between t1.c and 13 then b else 11 end+t1.f*(t1.d)+t1.c FROM t1 WHERE ~+e+11>b} +} {} +do_test randexpr-2.2451 { + db eval {SELECT case when 19*case when case when t1.e>((t1.d)) and 11>t1.d then -17 else e end in (select count(distinct a) from t1 union select min(d) from t1) then (d) else e end | t1.c+a in (select count(*) from t1 union select case +(max(19))+count(distinct -t1.d) when min(19) then cast(avg(e) AS integer) else cast(avg(t1.a) AS integer) end from t1) and 17 between 17 and t1.b then -(t1.e) when b between t1.c and 13 then b else 11 end+t1.f*(t1.d)+t1.c FROM t1 WHERE NOT (~+e+11>b)} +} {240311} +do_test randexpr-2.2452 { + db eval {SELECT case when 19*case when case when t1.e>((t1.d)) and 11>t1.d then -17 else e end in (select count(distinct a) from t1 union select min(d) from t1) then (d) else e end & t1.c+a in (select count(*) from t1 union select case +(max(19))+count(distinct -t1.d) when min(19) then cast(avg(e) AS integer) else cast(avg(t1.a) AS integer) end from t1) and 17 between 17 and t1.b then -(t1.e) when b between t1.c and 13 then b else 11 end+t1.f*(t1.d)+t1.c FROM t1 WHERE NOT (~+e+11>b)} +} {240311} +do_test randexpr-2.2453 { + db eval {SELECT coalesce((select max((e)) from t1 where not (((abs(c)/abs((abs(t1.e)/abs(t1.d)))) between d and a+t1.f+19-a or (not exists(select 1 from t1 where f*11 in (19,t1.d,case when (11 in (19,17,19) and t1.a>t1.d) then t1.e-19 else t1.e end+f))) and a<11) and 19<>a)),c+d) FROM t1 WHERE 17+case b*f when b then a+e else d end*t1.b<=case when not f=11 then c when t1.ed and exists(select 1 from t1 where 19 in (t1.e,t1.a,(e)))),a)*c from t1 union select f from t1)),t1.a)+f+17 then t1.c else b end} +} {} +do_test randexpr-2.2454 { + db eval {SELECT coalesce((select max((e)) from t1 where not (((abs(c)/abs((abs(t1.e)/abs(t1.d)))) between d and a+t1.f+19-a or (not exists(select 1 from t1 where f*11 in (19,t1.d,case when (11 in (19,17,19) and t1.a>t1.d) then t1.e-19 else t1.e end+f))) and a<11) and 19<>a)),c+d) FROM t1 WHERE NOT (17+case b*f when b then a+e else d end*t1.b<=case when not f=11 then c when t1.ed and exists(select 1 from t1 where 19 in (t1.e,t1.a,(e)))),a)*c from t1 union select f from t1)),t1.a)+f+17 then t1.c else b end)} +} {500} +do_test randexpr-2.2455 { + db eval {SELECT ((select cast(avg(case a when t1.d then (abs(coalesce((select coalesce((select coalesce((select e-a from t1 where not exists(select 1 from t1 where t1.f>11 or t1.a= -f)), -t1.a) from t1 where 11<= -t1.f),t1.f)-13 from t1 where not exists(select 1 from t1 where t1.e in (f,t1.b,d))),t1.d))/abs(11)) else (17) end) AS integer)+abs( -count(distinct e)+count(*)) | -count(*)*+min(e)*count(distinct b)*cast(avg(11) AS integer) from t1)) FROM t1 WHERE d= -19} +} {} +do_test randexpr-2.2456 { + db eval {SELECT ((select cast(avg(case a when t1.d then (abs(coalesce((select coalesce((select coalesce((select e-a from t1 where not exists(select 1 from t1 where t1.f>11 or t1.a= -f)), -t1.a) from t1 where 11<= -t1.f),t1.f)-13 from t1 where not exists(select 1 from t1 where t1.e in (f,t1.b,d))),t1.d))/abs(11)) else (17) end) AS integer)+abs( -count(distinct e)+count(*)) | -count(*)*+min(e)*count(distinct b)*cast(avg(11) AS integer) from t1)) FROM t1 WHERE NOT (d= -19)} +} {-5483} +do_test randexpr-2.2457 { + db eval {SELECT ((select cast(avg(case a when t1.d then (abs(coalesce((select coalesce((select coalesce((select e-a from t1 where not exists(select 1 from t1 where t1.f>11 or t1.a= -f)), -t1.a) from t1 where 11<= -t1.f),t1.f)-13 from t1 where not exists(select 1 from t1 where t1.e in (f,t1.b,d))),t1.d))/abs(11)) else (17) end) AS integer)+abs( -count(distinct e)+count(*)) & -count(*)*+min(e)*count(distinct b)*cast(avg(11) AS integer) from t1)) FROM t1 WHERE NOT (d= -19)} +} {0} +do_test randexpr-2.2458 { + db eval {SELECT 11+t1.e*c | t1.a+t1.a*coalesce((select max(b*t1.d*case when c in (select t1.b from t1 union select case when (t1.b>=d) then 19 else case when ((((t1.a<>t1.b)))) then b when f<=11 then case when e not in (19,t1.d,a) then coalesce((select 11 from t1 where e between a and e),e) when 11<=e then t1.a else 13 end else t1.c end end from t1) then 19 else (t1.d) end-a) from t1 where (t1.d)<= -e),t1.f) FROM t1 WHERE ((f not between t1.a and (abs(19)/abs(17 | (a))) and ((exists(select 1 from t1 where coalesce((select case e*(17) when b-(abs((abs(11)/abs(t1.c+e+t1.c)))/abs(17-((t1.f-t1.e | 11)))) then e else a end from t1 where t1.c not in (19,t1.b,t1.d)),c)=b)))))} +} {} +do_test randexpr-2.2459 { + db eval {SELECT 11+t1.e*c | t1.a+t1.a*coalesce((select max(b*t1.d*case when c in (select t1.b from t1 union select case when (t1.b>=d) then 19 else case when ((((t1.a<>t1.b)))) then b when f<=11 then case when e not in (19,t1.d,a) then coalesce((select 11 from t1 where e between a and e),e) when 11<=e then t1.a else 13 end else t1.c end end from t1) then 19 else (t1.d) end-a) from t1 where (t1.d)<= -e),t1.f) FROM t1 WHERE NOT (((f not between t1.a and (abs(19)/abs(17 | (a))) and ((exists(select 1 from t1 where coalesce((select case e*(17) when b-(abs((abs(11)/abs(t1.c+e+t1.c)))/abs(17-((t1.f-t1.e | 11)))) then e else a end from t1 where t1.c not in (19,t1.b,t1.d)),c)=b))))))} +} {191487} +do_test randexpr-2.2460 { + db eval {SELECT 11+t1.e*c & t1.a+t1.a*coalesce((select max(b*t1.d*case when c in (select t1.b from t1 union select case when (t1.b>=d) then 19 else case when ((((t1.a<>t1.b)))) then b when f<=11 then case when e not in (19,t1.d,a) then coalesce((select 11 from t1 where e between a and e),e) when 11<=e then t1.a else 13 end else t1.c end end from t1) then 19 else (t1.d) end-a) from t1 where (t1.d)<= -e),t1.f) FROM t1 WHERE NOT (((f not between t1.a and (abs(19)/abs(17 | (a))) and ((exists(select 1 from t1 where coalesce((select case e*(17) when b-(abs((abs(11)/abs(t1.c+e+t1.c)))/abs(17-((t1.f-t1.e | 11)))) then e else a end from t1 where t1.c not in (19,t1.b,t1.d)),c)=b))))))} +} {18624} +do_test randexpr-2.2461 { + db eval {SELECT (select (case +~ -abs(count(distinct + -(select (case ~((min(t1.b)+max(a))+count(*))*cast(avg(e) AS integer) when count(distinct (17)) then count(distinct t1.d) else max(a) end) from t1)*(17)-t1.f+case (abs( -t1.e)/abs(17)) when t1.f then b else 11 end)) | max(c)-case max(f) when (max(t1.f)) then min(c) else cast(avg((t1.d)) AS integer) end when count(*) then min(t1.a) else cast(avg(t1.c) AS integer) end) from t1) FROM t1 WHERE 13 in ((select ~ -abs((abs( -max(c)+count(distinct c)-~case +max(f) when min(13) then count(distinct t1.e) else count(*) end-((cast(avg(t1.c) AS integer)))))) from t1),~t1.c-t1.e,case when exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (select case when t1.ca then b else (c) end+t1.d from t1 union select -t1.e from t1)) or 11 not between b and d or e>e) then t1.f else t1.f end*t1.b- -t1.b)} +} {} +do_test randexpr-2.2462 { + db eval {SELECT (select (case +~ -abs(count(distinct + -(select (case ~((min(t1.b)+max(a))+count(*))*cast(avg(e) AS integer) when count(distinct (17)) then count(distinct t1.d) else max(a) end) from t1)*(17)-t1.f+case (abs( -t1.e)/abs(17)) when t1.f then b else 11 end)) | max(c)-case max(f) when (max(t1.f)) then min(c) else cast(avg((t1.d)) AS integer) end when count(*) then min(t1.a) else cast(avg(t1.c) AS integer) end) from t1) FROM t1 WHERE NOT (13 in ((select ~ -abs((abs( -max(c)+count(distinct c)-~case +max(f) when min(13) then count(distinct t1.e) else count(*) end-((cast(avg(t1.c) AS integer)))))) from t1),~t1.c-t1.e,case when exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (select case when t1.ca then b else (c) end+t1.d from t1 union select -t1.e from t1)) or 11 not between b and d or e>e) then t1.f else t1.f end*t1.b- -t1.b))} +} {300} +do_test randexpr-2.2463 { + db eval {SELECT (select (case +~ -abs(count(distinct + -(select (case ~((min(t1.b)+max(a))+count(*))*cast(avg(e) AS integer) when count(distinct (17)) then count(distinct t1.d) else max(a) end) from t1)*(17)-t1.f+case (abs( -t1.e)/abs(17)) when t1.f then b else 11 end)) & max(c)-case max(f) when (max(t1.f)) then min(c) else cast(avg((t1.d)) AS integer) end when count(*) then min(t1.a) else cast(avg(t1.c) AS integer) end) from t1) FROM t1 WHERE NOT (13 in ((select ~ -abs((abs( -max(c)+count(distinct c)-~case +max(f) when min(13) then count(distinct t1.e) else count(*) end-((cast(avg(t1.c) AS integer)))))) from t1),~t1.c-t1.e,case when exists(select 1 from t1 where not exists(select 1 from t1 where t1.a in (select case when t1.ca then b else (c) end+t1.d from t1 union select -t1.e from t1)) or 11 not between b and d or e>e) then t1.f else t1.f end*t1.b- -t1.b))} +} {300} +do_test randexpr-2.2464 { + db eval {SELECT case when (abs(~(t1.e))/abs(case when (( -13c)),f)+t1.b when 13 then t1.c else t1.b end<>a) or t1.a=a),e+t1.e))/abs((f))) when a then e else f end) from t1 where t1.a>t1.d),19)) from t1) FROM t1 WHERE 19*~case when (case when t1.f<>t1.a*17*(abs(t1.e)/abs(a))*a*(select case +min(11)*cast(avg(b) AS integer)*cast(avg(19) AS integer) when count(distinct t1.f) then max( -t1.e) else cast(avg( -f) AS integer) end from t1)*(select min(t1.b) from t1)*t1.d then coalesce((select max(11) from t1 where t1.a between t1.d and 17 and 19 not between 17 and a),17) else 17 end in (select t1.f from t1 union select 17 from t1)) then ~t1.b else t1.d end<=b} +} {} +do_test randexpr-2.2471 { + db eval {SELECT (select min(coalesce((select max(t1.c-case t1.e | (abs(coalesce((select max(t1.b) from t1 where 19c)),f)+t1.b when 13 then t1.c else t1.b end<>a) or t1.a=a),e+t1.e))/abs((f))) when a then e else f end) from t1 where t1.a>t1.d),19)) from t1) FROM t1 WHERE NOT (19*~case when (case when t1.f<>t1.a*17*(abs(t1.e)/abs(a))*a*(select case +min(11)*cast(avg(b) AS integer)*cast(avg(19) AS integer) when count(distinct t1.f) then max( -t1.e) else cast(avg( -f) AS integer) end from t1)*(select min(t1.b) from t1)*t1.d then coalesce((select max(11) from t1 where t1.a between t1.d and 17 and 19 not between 17 and a),17) else 17 end in (select t1.f from t1 union select 17 from t1)) then ~t1.b else t1.d end<=b)} +} {19} +do_test randexpr-2.2472 { + db eval {SELECT (select min(coalesce((select max(t1.c-case t1.e & (abs(coalesce((select max(t1.b) from t1 where 19c)),f)+t1.b when 13 then t1.c else t1.b end<>a) or t1.a=a),e+t1.e))/abs((f))) when a then e else f end) from t1 where t1.a>t1.d),19)) from t1) FROM t1 WHERE NOT (19*~case when (case when t1.f<>t1.a*17*(abs(t1.e)/abs(a))*a*(select case +min(11)*cast(avg(b) AS integer)*cast(avg(19) AS integer) when count(distinct t1.f) then max( -t1.e) else cast(avg( -f) AS integer) end from t1)*(select min(t1.b) from t1)*t1.d then coalesce((select max(11) from t1 where t1.a between t1.d and 17 and 19 not between 17 and a),17) else 17 end in (select t1.f from t1 union select 17 from t1)) then ~t1.b else t1.d end<=b)} +} {19} +do_test randexpr-2.2473 { + db eval {SELECT -case (select ~count(*)-~abs(~ -(count(*)+count(*)))*count(*) from t1)*13++coalesce((select max( -+17+case when f not between e and t1.c and t1.f between t1.e and t1.a then e when (b)>19 then f else t1.b end) from t1 where 17 not in (a,t1.f,17) or (d>=t1.e) or a<=17),d) when t1.c then 19 else t1.f end FROM t1 WHERE (19<+case when not 17>e then +t1.f when e | 13 in (select ~(abs(a)/abs(t1.b)) from t1 union select t1.f from t1) then case when f between case case b*f+19-case t1.c when f then 13 else c end when t1.d then b else b end*11 when 19 then 13 else t1.c end and t1.f then c when t1.b<=c then t1.d else 13 end else t1.d end)} +} {-600} +do_test randexpr-2.2474 { + db eval {SELECT -case (select ~count(*)-~abs(~ -(count(*)+count(*)))*count(*) from t1)*13++coalesce((select max( -+17+case when f not between e and t1.c and t1.f between t1.e and t1.a then e when (b)>19 then f else t1.b end) from t1 where 17 not in (a,t1.f,17) or (d>=t1.e) or a<=17),d) when t1.c then 19 else t1.f end FROM t1 WHERE NOT ((19<+case when not 17>e then +t1.f when e | 13 in (select ~(abs(a)/abs(t1.b)) from t1 union select t1.f from t1) then case when f between case case b*f+19-case t1.c when f then 13 else c end when t1.d then b else b end*11 when 19 then 13 else t1.c end and t1.f then c when t1.b<=c then t1.d else 13 end else t1.d end))} +} {} +do_test randexpr-2.2475 { + db eval {SELECT case when e not in (t1.a,t1.b,t1.e-t1.a) then f-coalesce((select max(~19-t1.b-f) from t1 where case when (select count(*)*count(*) from t1)-coalesce((select max(13) from t1 where (abs(13)/abs(19-f)) in (select count(distinct f) from t1 union select ~ - -count(distinct -f) from t1)),t1.b) between t1.f and t1.d then d else f end between t1.f and a),t1.f)+ -t1.f else t1.e end FROM t1 WHERE d not in (c,t1.d, -coalesce((select max( -coalesce((select f from t1 where t1.b>t1.c* - -t1.f),case when (t1.e-t1.e | 19*t1.c+e<19 and 19<=e or not exists(select 1 from t1 where t1.a<=t1.d or e in (a,t1.e,b))) then -e when f in ((t1.a),d,11) then 13 else d end)) from t1 where c between 19 and f),b))} +} {} +do_test randexpr-2.2476 { + db eval {SELECT case when e not in (t1.a,t1.b,t1.e-t1.a) then f-coalesce((select max(~19-t1.b-f) from t1 where case when (select count(*)*count(*) from t1)-coalesce((select max(13) from t1 where (abs(13)/abs(19-f)) in (select count(distinct f) from t1 union select ~ - -count(distinct -f) from t1)),t1.b) between t1.f and t1.d then d else f end between t1.f and a),t1.f)+ -t1.f else t1.e end FROM t1 WHERE NOT (d not in (c,t1.d, -coalesce((select max( -coalesce((select f from t1 where t1.b>t1.c* - -t1.f),case when (t1.e-t1.e | 19*t1.c+e<19 and 19<=e or not exists(select 1 from t1 where t1.a<=t1.d or e in (a,t1.e,b))) then -e when f in ((t1.a),d,11) then 13 else d end)) from t1 where c between 19 and f),b)))} +} {-600} +do_test randexpr-2.2477 { + db eval {SELECT -case when (17<>t1.b-d+t1.a | t1.f) then ~c when ((19)-coalesce((select case t1.d-t1.f when (abs(((select abs(cast(avg(13) AS integer) | cast(avg( -(t1.b)) AS integer)) from t1)))/abs(case d when t1.b then -11 else 19 end))*17 then t1.e else t1.a end from t1 where (19 not in (f,t1.d,t1.e))),t1.d)<>a) then t1.d else t1.c end FROM t1 WHERE a in (~b-t1.f*c,13 | coalesce((select max(t1.a) from t1 where -t1.a-~case when b in (case when t1.e in (select 11 from t1 union select d from t1) and 13>19 then 13*c when f not in (t1.d,c,13) then t1.a else a end,t1.f,d) then a else 11 end+b in (select +(min(11)) from t1 union select max(11)+cast(avg(19) AS integer) from t1)),13),t1.f)} +} {} +do_test randexpr-2.2478 { + db eval {SELECT -case when (17<>t1.b-d+t1.a | t1.f) then ~c when ((19)-coalesce((select case t1.d-t1.f when (abs(((select abs(cast(avg(13) AS integer) | cast(avg( -(t1.b)) AS integer)) from t1)))/abs(case d when t1.b then -11 else 19 end))*17 then t1.e else t1.a end from t1 where (19 not in (f,t1.d,t1.e))),t1.d)<>a) then t1.d else t1.c end FROM t1 WHERE NOT (a in (~b-t1.f*c,13 | coalesce((select max(t1.a) from t1 where -t1.a-~case when b in (case when t1.e in (select 11 from t1 union select d from t1) and 13>19 then 13*c when f not in (t1.d,c,13) then t1.a else a end,t1.f,d) then a else 11 end+b in (select +(min(11)) from t1 union select max(11)+cast(avg(19) AS integer) from t1)),13),t1.f))} +} {301} +do_test randexpr-2.2479 { + db eval {SELECT -case when (17<>t1.b-d+t1.a & t1.f) then ~c when ((19)-coalesce((select case t1.d-t1.f when (abs(((select abs(cast(avg(13) AS integer) & cast(avg( -(t1.b)) AS integer)) from t1)))/abs(case d when t1.b then -11 else 19 end))*17 then t1.e else t1.a end from t1 where (19 not in (f,t1.d,t1.e))),t1.d)<>a) then t1.d else t1.c end FROM t1 WHERE NOT (a in (~b-t1.f*c,13 | coalesce((select max(t1.a) from t1 where -t1.a-~case when b in (case when t1.e in (select 11 from t1 union select d from t1) and 13>19 then 13*c when f not in (t1.d,c,13) then t1.a else a end,t1.f,d) then a else 11 end+b in (select +(min(11)) from t1 union select max(11)+cast(avg(19) AS integer) from t1)),13),t1.f))} +} {301} +do_test randexpr-2.2480 { + db eval {SELECT case f when case when +t1.a between a and case e when 17 then t1.e else f-t1.e+a-((select ++count(distinct d) | cast(avg(t1.e) AS integer)+count(distinct e) | -count(*) from t1)) end-t1.b*f and t1.b | t1.b-b<=c then -t1.b+d when 11 in (select t1.e from t1 union select 11 from t1) then 13 else a end then b else c end FROM t1 WHERE case when ++c-13*d>t1.a and f=t1.d-t1.b then (select count(distinct 11)*(+cast(avg(t1.b) AS integer)+case cast(avg(e) AS integer) when max(d) | min(11) then min(f) else ( -min(t1.b)) end*(count(*)))* -min(19) from t1) else t1.e end*11 in (select a from t1 union select t1.e from t1) and e=17 or 11 not in ( -t1.d,f,t1.f)} +} {300} +do_test randexpr-2.2481 { + db eval {SELECT case f when case when +t1.a between a and case e when 17 then t1.e else f-t1.e+a-((select ++count(distinct d) | cast(avg(t1.e) AS integer)+count(distinct e) | -count(*) from t1)) end-t1.b*f and t1.b | t1.b-b<=c then -t1.b+d when 11 in (select t1.e from t1 union select 11 from t1) then 13 else a end then b else c end FROM t1 WHERE NOT (case when ++c-13*d>t1.a and f=t1.d-t1.b then (select count(distinct 11)*(+cast(avg(t1.b) AS integer)+case cast(avg(e) AS integer) when max(d) | min(11) then min(f) else ( -min(t1.b)) end*(count(*)))* -min(19) from t1) else t1.e end*11 in (select a from t1 union select t1.e from t1) and e=17 or 11 not in ( -t1.d,f,t1.f))} +} {} +do_test randexpr-2.2482 { + db eval {SELECT case f when case when +t1.a between a and case e when 17 then t1.e else f-t1.e+a-((select ++count(distinct d) & cast(avg(t1.e) AS integer)+count(distinct e) & -count(*) from t1)) end-t1.b*f and t1.b & t1.b-b<=c then -t1.b+d when 11 in (select t1.e from t1 union select 11 from t1) then 13 else a end then b else c end FROM t1 WHERE case when ++c-13*d>t1.a and f=t1.d-t1.b then (select count(distinct 11)*(+cast(avg(t1.b) AS integer)+case cast(avg(e) AS integer) when max(d) | min(11) then min(f) else ( -min(t1.b)) end*(count(*)))* -min(19) from t1) else t1.e end*11 in (select a from t1 union select t1.e from t1) and e=17 or 11 not in ( -t1.d,f,t1.f)} +} {300} +do_test randexpr-2.2483 { + db eval {SELECT -(19)-coalesce((select max(t1.e) from t1 where c not in (t1.b,17,t1.c)),case coalesce((select b+f+coalesce((select t1.a from t1 where t1.e>=t1.e+t1.a+t1.c or t1.f between c and t1.f),t1.e) from t1 where 11<>13 or t1.a=b),t1.c)*f+a when a then 17 else 17 end+t1.e)+a FROM t1 WHERE e | a not between -case when not c between case when exists(select 1 from t1 where (f not in (coalesce((select max(t1.d) from t1 where t1.e=t1.d),t1.e)+a,19,t1.c)) or not exists(select 1 from t1 where a in (19,a,e) and 11>=t1.f)) or 11<17 then t1.e+19*t1.f-b when t1.c in (e,t1.b,e) then f else t1.f end and t1.b or (11>=(t1.a)) then e when t1.a=t1.a then (select count(*) from t1) else e end and t1.b} +} {-436} +do_test randexpr-2.2484 { + db eval {SELECT -(19)-coalesce((select max(t1.e) from t1 where c not in (t1.b,17,t1.c)),case coalesce((select b+f+coalesce((select t1.a from t1 where t1.e>=t1.e+t1.a+t1.c or t1.f between c and t1.f),t1.e) from t1 where 11<>13 or t1.a=b),t1.c)*f+a when a then 17 else 17 end+t1.e)+a FROM t1 WHERE NOT (e | a not between -case when not c between case when exists(select 1 from t1 where (f not in (coalesce((select max(t1.d) from t1 where t1.e=t1.d),t1.e)+a,19,t1.c)) or not exists(select 1 from t1 where a in (19,a,e) and 11>=t1.f)) or 11<17 then t1.e+19*t1.f-b when t1.c in (e,t1.b,e) then f else t1.f end and t1.b or (11>=(t1.a)) then e when t1.a=t1.a then (select count(*) from t1) else e end and t1.b)} +} {} +do_test randexpr-2.2485 { + db eval {SELECT case (abs(case when 13 not in (t1.f,a,t1.b) then d*(abs((coalesce((select coalesce((select coalesce((select max(t1.d-t1.a) from t1 where (t1.c between 19 and (c) and c=17)),t1.f) from t1 where t1.e between e and 17),17))-b)/abs(d)) | b+t1.b when e between t1.f and d then 19 else 17 end*f)/abs(a)) when t1.c then 11 else t1.d end FROM t1 WHERE d>=e} +} {} +do_test randexpr-2.2486 { + db eval {SELECT case (abs(case when 13 not in (t1.f,a,t1.b) then d*(abs((coalesce((select coalesce((select coalesce((select max(t1.d-t1.a) from t1 where (t1.c between 19 and (c) and c=17)),t1.f) from t1 where t1.e between e and 17),17))-b)/abs(d)) | b+t1.b when e between t1.f and d then 19 else 17 end*f)/abs(a)) when t1.c then 11 else t1.d end FROM t1 WHERE NOT (d>=e)} +} {400} +do_test randexpr-2.2487 { + db eval {SELECT case (abs(case when 13 not in (t1.f,a,t1.b) then d*(abs((coalesce((select coalesce((select coalesce((select max(t1.d-t1.a) from t1 where (t1.c between 19 and (c) and c=17)),t1.f) from t1 where t1.e between e and 17),17))-b)/abs(d)) & b+t1.b when e between t1.f and d then 19 else 17 end*f)/abs(a)) when t1.c then 11 else t1.d end FROM t1 WHERE NOT (d>=e)} +} {400} +do_test randexpr-2.2488 { + db eval {SELECT case ((abs(case when case -(select count(distinct case when t1.d in (select t1.b from t1 union select t1.b from t1) then b when f not in (t1.a,b,a) then c else 17 end) | cast(avg(d) AS integer) | min(b) from t1) | +b-e when t1.e then f else a end not between 11 and 13 then f when 17>e and 17=t1.f) or d in ( -t1.c,f,t1.a) then -a else t1.f end)/abs(t1.b))) when 17 then t1.f else t1.f end FROM t1 WHERE t1.d=t1.b+case c-11+coalesce((select case when +(select +(case max(t1.e) when count(*) then (count(*)) else cast(avg(d) AS integer) end) from t1)-d between b and t1.d then 11 else f end from t1 where t1.f<=t1.c and exists(select 1 from t1 where exists(select 1 from t1 where e between t1.e and t1.e))),t1.b)-19 when t1.d then t1.f else (t1.f) end | e-c or t1.f not in (b, -f, -f)} +} {600} +do_test randexpr-2.2489 { + db eval {SELECT case ((abs(case when case -(select count(distinct case when t1.d in (select t1.b from t1 union select t1.b from t1) then b when f not in (t1.a,b,a) then c else 17 end) | cast(avg(d) AS integer) | min(b) from t1) | +b-e when t1.e then f else a end not between 11 and 13 then f when 17>e and 17=t1.f) or d in ( -t1.c,f,t1.a) then -a else t1.f end)/abs(t1.b))) when 17 then t1.f else t1.f end FROM t1 WHERE NOT (t1.d=t1.b+case c-11+coalesce((select case when +(select +(case max(t1.e) when count(*) then (count(*)) else cast(avg(d) AS integer) end) from t1)-d between b and t1.d then 11 else f end from t1 where t1.f<=t1.c and exists(select 1 from t1 where exists(select 1 from t1 where e between t1.e and t1.e))),t1.b)-19 when t1.d then t1.f else (t1.f) end | e-c or t1.f not in (b, -f, -f))} +} {} +do_test randexpr-2.2490 { + db eval {SELECT case ((abs(case when case -(select count(distinct case when t1.d in (select t1.b from t1 union select t1.b from t1) then b when f not in (t1.a,b,a) then c else 17 end) & cast(avg(d) AS integer) & min(b) from t1) & +b-e when t1.e then f else a end not between 11 and 13 then f when 17>e and 17=t1.f) or d in ( -t1.c,f,t1.a) then -a else t1.f end)/abs(t1.b))) when 17 then t1.f else t1.f end FROM t1 WHERE t1.d=t1.b+case c-11+coalesce((select case when +(select +(case max(t1.e) when count(*) then (count(*)) else cast(avg(d) AS integer) end) from t1)-d between b and t1.d then 11 else f end from t1 where t1.f<=t1.c and exists(select 1 from t1 where exists(select 1 from t1 where e between t1.e and t1.e))),t1.b)-19 when t1.d then t1.f else (t1.f) end | e-c or t1.f not in (b, -f, -f)} +} {600} +do_test randexpr-2.2491 { + db eval {SELECT coalesce((select max(11) from t1 where 17 not in (11,case when (case when t1.f>b then t1.d*t1.d else (abs((abs(19)/abs(coalesce((select 17*t1.e-t1.c from t1 where 17<13 and (t1.a in (select (min(17)) from t1 union select max(c) from t1) and -t1.d not in ((t1.b),d,a))), -17))))/abs(c))*13 end)<>(t1.f) then a when a=t1.a then 17 else -19 end-d,a)),e) FROM t1 WHERE 19<=case when not exists(select 1 from t1 where case when case when case when ((t1.a in (select +min(t1.c) from t1 union select max(t1.a) from t1))) or 19 between t1.d and b then +c | 11*f else d endb then c else t1.d end in (17,( -b),t1.c)) then t1.e when t1.f in (t1.a,13,d) then 17 else t1.f end*11*t1.d and a<=t1.d} +} {11} +do_test randexpr-2.2492 { + db eval {SELECT coalesce((select max(11) from t1 where 17 not in (11,case when (case when t1.f>b then t1.d*t1.d else (abs((abs(19)/abs(coalesce((select 17*t1.e-t1.c from t1 where 17<13 and (t1.a in (select (min(17)) from t1 union select max(c) from t1) and -t1.d not in ((t1.b),d,a))), -17))))/abs(c))*13 end)<>(t1.f) then a when a=t1.a then 17 else -19 end-d,a)),e) FROM t1 WHERE NOT (19<=case when not exists(select 1 from t1 where case when case when case when ((t1.a in (select +min(t1.c) from t1 union select max(t1.a) from t1))) or 19 between t1.d and b then +c | 11*f else d endb then c else t1.d end in (17,( -b),t1.c)) then t1.e when t1.f in (t1.a,13,d) then 17 else t1.f end*11*t1.d and a<=t1.d)} +} {} +do_test randexpr-2.2493 { + db eval {SELECT b*case when t1.f not in (a,f,t1.e-e) and t1.b in (select coalesce((select max(t1.e) from t1 where coalesce((select max(~d) from t1 where case when t1.b not in (t1.c,17, -c) then t1.f when t1.c>17 then 17 else e end>t1.f and t1.f not in (b,f,d)),17)>=t1.c or 19<=t1.e),t1.a) from t1 union select (e) from t1) then d when t1.c17 then 17 else e end>t1.f and t1.f not in (b,f,d)),17)>=t1.c or 19<=t1.e),t1.a) from t1 union select (e) from t1) then d when t1.cc and e in (select +max(17) from t1 union select count(*) from t1) then (abs( -c)/abs(a)) when b>=t1.f then t1.b else 11 end when t1.f then 17 else t1.d end*(c)+17 when e then c else t1.f end else -c end-t1.c-c-19+c+a not in (t1.a,13,e)} +} {-90801} +do_test randexpr-2.2496 { + db eval {SELECT +(select ~(~cast(avg(t1.c) AS integer)* -cast(avg(c) AS integer))-case min(t1.e) when case count(*)*~(count(*)-+count(*)*cast(avg(case t1.d when 19 then d else (t1.a) end*e) AS integer) | cast(avg(13) AS integer)-cast(avg( -11) AS integer)+max(b)+cast(avg(19) AS integer) | (max(t1.e))) | min(f) when -max(19) then (count(distinct -t1.a)) else (count(distinct 17)) end then max(t1.d) else cast(avg(t1.e) AS integer) end from t1) FROM t1 WHERE NOT (t1.c-case f when 17 | b then case +case f | case when +t1.a>c and e in (select +max(17) from t1 union select count(*) from t1) then (abs( -c)/abs(a)) when b>=t1.f then t1.b else 11 end when t1.f then 17 else t1.d end*(c)+17 when e then c else t1.f end else -c end-t1.c-c-19+c+a not in (t1.a,13,e))} +} {} +do_test randexpr-2.2497 { + db eval {SELECT +(select ~(~cast(avg(t1.c) AS integer)* -cast(avg(c) AS integer))-case min(t1.e) when case count(*)*~(count(*)-+count(*)*cast(avg(case t1.d when 19 then d else (t1.a) end*e) AS integer) & cast(avg(13) AS integer)-cast(avg( -11) AS integer)+max(b)+cast(avg(19) AS integer) & (max(t1.e))) & min(f) when -max(19) then (count(distinct -t1.a)) else (count(distinct 17)) end then max(t1.d) else cast(avg(t1.e) AS integer) end from t1) FROM t1 WHERE t1.c-case f when 17 | b then case +case f | case when +t1.a>c and e in (select +max(17) from t1 union select count(*) from t1) then (abs( -c)/abs(a)) when b>=t1.f then t1.b else 11 end when t1.f then 17 else t1.d end*(c)+17 when e then c else t1.f end else -c end-t1.c-c-19+c+a not in (t1.a,13,e)} +} {-90801} +do_test randexpr-2.2498 { + db eval {SELECT case t1.d when e then t1.d else (abs(e-b)/abs(t1.c+a*a | 17+19*coalesce((select 17 from t1 where 11 between +(select abs(+cast(avg(13) AS integer)) from t1)*19 and t1.e),t1.e-11-t1.e+( -t1.e*13)*t1.e | e*t1.b)*f)) end FROM t1 WHERE (abs(t1.d)/abs(t1.c)) not between +13 and t1.c} +} {0} +do_test randexpr-2.2499 { + db eval {SELECT case t1.d when e then t1.d else (abs(e-b)/abs(t1.c+a*a | 17+19*coalesce((select 17 from t1 where 11 between +(select abs(+cast(avg(13) AS integer)) from t1)*19 and t1.e),t1.e-11-t1.e+( -t1.e*13)*t1.e | e*t1.b)*f)) end FROM t1 WHERE NOT ((abs(t1.d)/abs(t1.c)) not between +13 and t1.c)} +} {} +do_test randexpr-2.2500 { + db eval {SELECT case t1.d when e then t1.d else (abs(e-b)/abs(t1.c+a*a & 17+19*coalesce((select 17 from t1 where 11 between +(select abs(+cast(avg(13) AS integer)) from t1)*19 and t1.e),t1.e-11-t1.e+( -t1.e*13)*t1.e & e*t1.b)*f)) end FROM t1 WHERE (abs(t1.d)/abs(t1.c)) not between +13 and t1.c} +} {18} +do_test randexpr-2.2501 { + db eval {SELECT coalesce((select coalesce((select t1.e from t1 where case when c+a in (select t1.f from t1 union select 13 from t1) then c when not not exists(select 1 from t1 where d>= -11) then t1.d else -t1.f end between b and 11 or d not between e and 11), -f)+e+ -11*17 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where t1.e in (select ~min(e) from t1 union select case case count(distinct f) | min(19)+min(a) when count(*) then max( -t1.c) else max(17) end when (max(t1.c)) then min(11) else min(t1.c) end from t1)) or d=a)),t1.e) FROM t1 WHERE +t1.e<~case when t1.e in (select (abs(c)/abs(~t1.d)) from t1 union select a from t1) then coalesce((select e from t1 where t1.d+ -coalesce((select max(11-t1.e*b) from t1 where 19 in (11,t1.b,e)),11)*t1.e+19 in (select t1.d from t1 union select -t1.d from t1)),17) | t1.e+e when t1.f in (17,f,f) then t1.b else 17 end*13} +} {} +do_test randexpr-2.2502 { + db eval {SELECT coalesce((select coalesce((select t1.e from t1 where case when c+a in (select t1.f from t1 union select 13 from t1) then c when not not exists(select 1 from t1 where d>= -11) then t1.d else -t1.f end between b and 11 or d not between e and 11), -f)+e+ -11*17 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where t1.e in (select ~min(e) from t1 union select case case count(distinct f) | min(19)+min(a) when count(*) then max( -t1.c) else max(17) end when (max(t1.c)) then min(11) else min(t1.c) end from t1)) or d=a)),t1.e) FROM t1 WHERE NOT (+t1.e<~case when t1.e in (select (abs(c)/abs(~t1.d)) from t1 union select a from t1) then coalesce((select e from t1 where t1.d+ -coalesce((select max(11-t1.e*b) from t1 where 19 in (11,t1.b,e)),11)*t1.e+19 in (select t1.d from t1 union select -t1.d from t1)),17) | t1.e+e when t1.f in (17,f,f) then t1.b else 17 end*13)} +} {813} +do_test randexpr-2.2503 { + db eval {SELECT coalesce((select coalesce((select t1.e from t1 where case when c+a in (select t1.f from t1 union select 13 from t1) then c when not not exists(select 1 from t1 where d>= -11) then t1.d else -t1.f end between b and 11 or d not between e and 11), -f)+e+ -11*17 from t1 where not exists(select 1 from t1 where exists(select 1 from t1 where t1.e in (select ~min(e) from t1 union select case case count(distinct f) & min(19)+min(a) when count(*) then max( -t1.c) else max(17) end when (max(t1.c)) then min(11) else min(t1.c) end from t1)) or d=a)),t1.e) FROM t1 WHERE NOT (+t1.e<~case when t1.e in (select (abs(c)/abs(~t1.d)) from t1 union select a from t1) then coalesce((select e from t1 where t1.d+ -coalesce((select max(11-t1.e*b) from t1 where 19 in (11,t1.b,e)),11)*t1.e+19 in (select t1.d from t1 union select -t1.d from t1)),17) | t1.e+e when t1.f in (17,f,f) then t1.b else 17 end*13)} +} {813} +do_test randexpr-2.2504 { + db eval {SELECT case when ((t1.f)+coalesce((select coalesce((select ++d from t1 where not t1.d not between e and e),19) from t1 where t1.d<>19),a)-c*a not between c and t1.a and not exists(select 1 from t1 where 17<=a) and exists(select 1 from t1 where not e in (select t1.b from t1 union select t1.e from t1)) and t1.f between 11 and t1.d) or e between c and 13 then t1.a+e when t1.a not between a and d then 17 else t1.a end FROM t1 WHERE (a)+t1.f>t1.e+a} +} {100} +do_test randexpr-2.2505 { + db eval {SELECT case when ((t1.f)+coalesce((select coalesce((select ++d from t1 where not t1.d not between e and e),19) from t1 where t1.d<>19),a)-c*a not between c and t1.a and not exists(select 1 from t1 where 17<=a) and exists(select 1 from t1 where not e in (select t1.b from t1 union select t1.e from t1)) and t1.f between 11 and t1.d) or e between c and 13 then t1.a+e when t1.a not between a and d then 17 else t1.a end FROM t1 WHERE NOT ((a)+t1.f>t1.e+a)} +} {} +do_test randexpr-2.2506 { + db eval {SELECT b*b+case d*d when t1.f then c else coalesce((select coalesce((select max(f) from t1 where (d=t1.b or case when e=11 then t1.a else f end<>t1.d and exists(select 1 from t1 where f not between t1.c and a))),(select count(distinct f) from t1)+case when t1.b between a and (19) and t1.e=a then 13 else 17 end) from t1 where d>=11),f)*t1.e end-11-a- -(11) FROM t1 WHERE (c<19)} +} {} +do_test randexpr-2.2507 { + db eval {SELECT b*b+case d*d when t1.f then c else coalesce((select coalesce((select max(f) from t1 where (d=t1.b or case when e=11 then t1.a else f end<>t1.d and exists(select 1 from t1 where f not between t1.c and a))),(select count(distinct f) from t1)+case when t1.b between a and (19) and t1.e=a then 13 else 17 end) from t1 where d>=11),f)*t1.e end-11-a- -(11) FROM t1 WHERE NOT ((c<19))} +} {339900} +do_test randexpr-2.2508 { + db eval {SELECT coalesce((select max(c) from t1 where ((d between t1.c and c)) and b not between t1.a and a or f+c in (d | +f*d*coalesce((select case when not -t1.c=a)),e)*f,b,11) or -19>=t1.c and t1.a in (b,t1.f,c)),13) FROM t1 WHERE t1.c in (select count(distinct t1.a)*max(d) | +case (~ -~+count(distinct 13)*min(19) | (max(e))+ -(count(*))) when count(distinct t1.a) then max(d) else count(*) end+min(t1.c) from t1 union select min(e) from t1) and 17=t1.c-t1.d or t1.c-d not in ( -c,(abs(case a when t1.a then 13 else e end+f)/abs(e)),t1.a)} +} {13} +do_test randexpr-2.2509 { + db eval {SELECT coalesce((select max(c) from t1 where ((d between t1.c and c)) and b not between t1.a and a or f+c in (d | +f*d*coalesce((select case when not -t1.c=a)),e)*f,b,11) or -19>=t1.c and t1.a in (b,t1.f,c)),13) FROM t1 WHERE NOT (t1.c in (select count(distinct t1.a)*max(d) | +case (~ -~+count(distinct 13)*min(19) | (max(e))+ -(count(*))) when count(distinct t1.a) then max(d) else count(*) end+min(t1.c) from t1 union select min(e) from t1) and 17=t1.c-t1.d or t1.c-d not in ( -c,(abs(case a when t1.a then 13 else e end+f)/abs(e)),t1.a))} +} {} +do_test randexpr-2.2510 { + db eval {SELECT coalesce((select max(c) from t1 where ((d between t1.c and c)) and b not between t1.a and a or f+c in (d & +f*d*coalesce((select case when not -t1.c=a)),e)*f,b,11) or -19>=t1.c and t1.a in (b,t1.f,c)),13) FROM t1 WHERE t1.c in (select count(distinct t1.a)*max(d) | +case (~ -~+count(distinct 13)*min(19) | (max(e))+ -(count(*))) when count(distinct t1.a) then max(d) else count(*) end+min(t1.c) from t1 union select min(e) from t1) and 17=t1.c-t1.d or t1.c-d not in ( -c,(abs(case a when t1.a then 13 else e end+f)/abs(e)),t1.a)} +} {13} +do_test randexpr-2.2511 { + db eval {SELECT case case when not (abs(t1.d)/abs(17))>=t1.a+((19))+ -e-b or 11 between t1.a and 11 then 13 when t1.f in (select case count(distinct t1.d) when abs( -+(cast(avg(t1.c) AS integer)))*count(distinct (t1.e)) then max(19) else case count(distinct t1.a) when cast(avg(19) AS integer) then count(*) else cast(avg((t1.a)) AS integer) end end from t1 union select max(13) from t1) then -t1.b else t1.f end when c then -c else b end FROM t1 WHERE not exists(select 1 from t1 where not exists(select 1 from t1 where 13>=f))} +} {} +do_test randexpr-2.2512 { + db eval {SELECT case case when not (abs(t1.d)/abs(17))>=t1.a+((19))+ -e-b or 11 between t1.a and 11 then 13 when t1.f in (select case count(distinct t1.d) when abs( -+(cast(avg(t1.c) AS integer)))*count(distinct (t1.e)) then max(19) else case count(distinct t1.a) when cast(avg(19) AS integer) then count(*) else cast(avg((t1.a)) AS integer) end end from t1 union select max(13) from t1) then -t1.b else t1.f end when c then -c else b end FROM t1 WHERE NOT (not exists(select 1 from t1 where not exists(select 1 from t1 where 13>=f)))} +} {200} +do_test randexpr-2.2513 { + db eval {SELECT 11-(abs( -(select ((count(*)-(abs( -min(~19)))+case min(case when not exists(select 1 from t1 where (exists(select 1 from t1 where 17>f) or t1.c>=a)) then d else 11 end) | abs(cast(avg(19) AS integer)) when (count(distinct t1.f*19))-+ -( -count(*)) then ((cast(avg(t1.d) AS integer))) else cast(avg(t1.a) AS integer) end*count(distinct t1.d))+cast(avg(c) AS integer))-max(17) from t1)-17)/abs(t1.f)) FROM t1 WHERE - - -f+d in (select 19 from t1 union select t1.b from t1) or ((abs(a)/abs( -11+case when t1.e>=( -f) | d then ~t1.a when coalesce((select t1.d from t1 where e not in (e-(d)+a,e,t1.b)),a)<>t1.b then a else -t1.c end)))<=t1.e and t1.e in (13,t1.a,t1.f)} +} {} +do_test randexpr-2.2514 { + db eval {SELECT 11-(abs( -(select ((count(*)-(abs( -min(~19)))+case min(case when not exists(select 1 from t1 where (exists(select 1 from t1 where 17>f) or t1.c>=a)) then d else 11 end) | abs(cast(avg(19) AS integer)) when (count(distinct t1.f*19))-+ -( -count(*)) then ((cast(avg(t1.d) AS integer))) else cast(avg(t1.a) AS integer) end*count(distinct t1.d))+cast(avg(c) AS integer))-max(17) from t1)-17)/abs(t1.f)) FROM t1 WHERE NOT ( - - -f+d in (select 19 from t1 union select t1.b from t1) or ((abs(a)/abs( -11+case when t1.e>=( -f) | d then ~t1.a when coalesce((select t1.d from t1 where e not in (e-(d)+a,e,t1.b)),a)<>t1.b then a else -t1.c end)))<=t1.e and t1.e in (13,t1.a,t1.f))} +} {11} +do_test randexpr-2.2515 { + db eval {SELECT 11-(abs( -(select ((count(*)-(abs( -min(~19)))+case min(case when not exists(select 1 from t1 where (exists(select 1 from t1 where 17>f) or t1.c>=a)) then d else 11 end) & abs(cast(avg(19) AS integer)) when (count(distinct t1.f*19))-+ -( -count(*)) then ((cast(avg(t1.d) AS integer))) else cast(avg(t1.a) AS integer) end*count(distinct t1.d))+cast(avg(c) AS integer))-max(17) from t1)-17)/abs(t1.f)) FROM t1 WHERE NOT ( - - -f+d in (select 19 from t1 union select t1.b from t1) or ((abs(a)/abs( -11+case when t1.e>=( -f) | d then ~t1.a when coalesce((select t1.d from t1 where e not in (e-(d)+a,e,t1.b)),a)<>t1.b then a else -t1.c end)))<=t1.e and t1.e in (13,t1.a,t1.f))} +} {11} +do_test randexpr-2.2516 { + db eval {SELECT coalesce((select ~11*b from t1 where (not exists(select 1 from t1 where case d when t1.b then t1.b else d end not between b and t1.b and f in (select ~count(*) from t1 union select count(distinct coalesce((select max( -c+(abs(coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where d>a)),t1.b)-17)/abs((b)))*(a)) from t1 where t1.f>b),f)) from t1) or t1.e not in ((d),c,c)))),c)*17+t1.c FROM t1 WHERE coalesce((select 17*case when exists(select 1 from t1 where coalesce((select t1.e from t1 where f<>e and e not between c and 11),d) in (select 11 from t1 union select c from t1)) then t1.b when t1.a between t1.f and 19 then t1.d else t1.c end*f | 19 from t1 where a between t1.c and b or t1.e in ((b),b,t1.f)),17) in (select ( -~case case (((count(*)))) when max(e) then max(e) else cast(avg(c) AS integer) end when min(17) then cast(avg(13) AS integer) else cast(avg(t1.b) AS integer) end+ -count(*)* -count(*))+min(d) from t1 union select count(distinct t1.e) from t1)} +} {} +do_test randexpr-2.2517 { + db eval {SELECT coalesce((select ~11*b from t1 where (not exists(select 1 from t1 where case d when t1.b then t1.b else d end not between b and t1.b and f in (select ~count(*) from t1 union select count(distinct coalesce((select max( -c+(abs(coalesce((select max(t1.a) from t1 where not exists(select 1 from t1 where d>a)),t1.b)-17)/abs((b)))*(a)) from t1 where t1.f>b),f)) from t1) or t1.e not in ((d),c,c)))),c)*17+t1.c FROM t1 WHERE NOT (coalesce((select 17*case when exists(select 1 from t1 where coalesce((select t1.e from t1 where f<>e and e not between c and 11),d) in (select 11 from t1 union select c from t1)) then t1.b when t1.a between t1.f and 19 then t1.d else t1.c end*f | 19 from t1 where a between t1.c and b or t1.e in ((b),b,t1.f)),17) in (select ( -~case case (((count(*)))) when max(e) then max(e) else cast(avg(c) AS integer) end when min(17) then cast(avg(13) AS integer) else cast(avg(t1.b) AS integer) end+ -count(*)* -count(*))+min(d) from t1 union select count(distinct t1.e) from t1))} +} {5400} +do_test randexpr-2.2518 { + db eval {SELECT (abs(case when not +c<>coalesce((select max(19) from t1 where not (abs(c)/abs(a))*a-t1.a>=case when (exists(select 1 from t1 where d=11)) then t1.a*~b else case when b in (select (f) from t1 union select 17 from t1) or not 17 not between f and -b then t1.a when fcoalesce((select max(19) from t1 where not (abs(c)/abs(a))*a-t1.a>=case when (exists(select 1 from t1 where d=11)) then t1.a*~b else case when b in (select (f) from t1 union select 17 from t1) or not 17 not between f and -b then t1.a when f=t1.b and (b not in (c,t1.e,t1.a))} +} {} +do_test randexpr-2.2521 { + db eval {SELECT ~case when case 11*17 when f then t1.a else t1.e end in ( -coalesce((select max(case coalesce((select t1.f from t1 where exists(select 1 from t1 where t1.c in (case t1.e when -d then c else (d) end,t1.e,t1.a))), -t1.c) when 19 then 11 else t1.e end) from t1 where t1.e in (19, -t1.b,a)),17)+f-11,17,19) then a when ((d=t1.b and (b not in (c,t1.e,t1.a)))} +} {499} +do_test randexpr-2.2522 { + db eval {SELECT (abs(case f when case when d+f between e and t1.f then f when coalesce((select max(t1.f) from t1 where c in (select t1.a from t1 union select case when a not between t1.c and 13 then a else t1.c end from t1) or f*f not in (case when (11<=d) then case when 13= -d),b)<=t1.b then t1.e else 13 end then f else t1.b end)/abs(f)) FROM t1 WHERE c between c and coalesce((select max(f) from t1 where b in (select count(*) from t1 union select max(13) from t1)),19)} +} {} +do_test randexpr-2.2523 { + db eval {SELECT (abs(case f when case when d+f between e and t1.f then f when coalesce((select max(t1.f) from t1 where c in (select t1.a from t1 union select case when a not between t1.c and 13 then a else t1.c end from t1) or f*f not in (case when (11<=d) then case when 13= -d),b)<=t1.b then t1.e else 13 end then f else t1.b end)/abs(f)) FROM t1 WHERE NOT (c between c and coalesce((select max(f) from t1 where b in (select count(*) from t1 union select max(13) from t1)),19))} +} {0} +do_test randexpr-2.2524 { + db eval {SELECT d++11*a+coalesce((select max(t1.a) from t1 where 17+case when (19>=a) then t1.b when f>=f then -(select cast(avg(t1.e-t1.f*t1.a) AS integer) from t1)-f else t1.f end*a+f*t1.a not in (t1.e,e,13)),17)- -t1.b-a-c*19 FROM t1 WHERE f*t1.a*t1.b>17 and case when 13 not in (19, -(select count(*) from t1),coalesce((select max(coalesce((select max(t1.a) from t1 where -coalesce((select max(case when not t1.f<=(t1.d) then t1.a else (a) end) from t1 where t1.f>c or 13<(t1.a)),17)>=t1.a or not exists(select 1 from t1 where - -c not in (a,t1.b,t1.e))),t1.e)) from t1 where (f not in (b,f,f))),c)) then (t1.e) when t1.a<>e then e else b end- -t1.f not in (a, -c,(c))} +} {-4000} +do_test randexpr-2.2525 { + db eval {SELECT d++11*a+coalesce((select max(t1.a) from t1 where 17+case when (19>=a) then t1.b when f>=f then -(select cast(avg(t1.e-t1.f*t1.a) AS integer) from t1)-f else t1.f end*a+f*t1.a not in (t1.e,e,13)),17)- -t1.b-a-c*19 FROM t1 WHERE NOT (f*t1.a*t1.b>17 and case when 13 not in (19, -(select count(*) from t1),coalesce((select max(coalesce((select max(t1.a) from t1 where -coalesce((select max(case when not t1.f<=(t1.d) then t1.a else (a) end) from t1 where t1.f>c or 13<(t1.a)),17)>=t1.a or not exists(select 1 from t1 where - -c not in (a,t1.b,t1.e))),t1.e)) from t1 where (f not in (b,f,f))),c)) then (t1.e) when t1.a<>e then e else b end- -t1.f not in (a, -c,(c)))} +} {} +do_test randexpr-2.2526 { + db eval {SELECT coalesce((select (a) from t1 where 11-11+t1.b<=17-b),case when case when not t1.e*f>= -t1.f and a in (11,t1.c,t1.b) or 19>e then (select case min((f)-f) when cast(avg(t1.a) AS integer) then (cast(avg(17) AS integer)) else ((cast(avg((13)) AS integer))) end from t1) when 13 not between f and t1.c then (abs(e)/abs(17)) else t1.e end | -17<=f then b when f<19 or t1.b<=t1.d then f else f end) FROM t1 WHERE -f | t1.f*c-t1.a | t1.c+11*case ~17 when -coalesce((select max(t1.e) from t1 where 13*(17)>=11),t1.a) then case case when (t1.b>= -t1.b) then t1.f when t1.fa and t1.e in (e,(t1.d),19) then t1.f else t1.c end when a then t1.a else t1.e end else a end*t1.a-13= -t1.f and a in (11,t1.c,t1.b) or 19>e then (select case min((f)-f) when cast(avg(t1.a) AS integer) then (cast(avg(17) AS integer)) else ((cast(avg((13)) AS integer))) end from t1) when 13 not between f and t1.c then (abs(e)/abs(17)) else t1.e end | -17<=f then b when f<19 or t1.b<=t1.d then f else f end) FROM t1 WHERE NOT ( -f | t1.f*c-t1.a | t1.c+11*case ~17 when -coalesce((select max(t1.e) from t1 where 13*(17)>=11),t1.a) then case case when (t1.b>= -t1.b) then t1.f when t1.fa and t1.e in (e,(t1.d),19) then t1.f else t1.c end when a then t1.a else t1.e end else a end*t1.a-13= -t1.f and a in (11,t1.c,t1.b) or 19>e then (select case min((f)-f) when cast(avg(t1.a) AS integer) then (cast(avg(17) AS integer)) else ((cast(avg((13)) AS integer))) end from t1) when 13 not between f and t1.c then (abs(e)/abs(17)) else t1.e end & -17<=f then b when f<19 or t1.b<=t1.d then f else f end) FROM t1 WHERE -f | t1.f*c-t1.a | t1.c+11*case ~17 when -coalesce((select max(t1.e) from t1 where 13*(17)>=11),t1.a) then case case when (t1.b>= -t1.b) then t1.f when t1.fa and t1.e in (e,(t1.d),19) then t1.f else t1.c end when a then t1.a else t1.e end else a end*t1.a-13a then 11 else e end*11 and t1.e) then t1.e when -17<11 then 17 else t1.a end)/abs(a)) FROM t1 WHERE c<=19} +} {} +do_test randexpr-2.2530 { + db eval {SELECT (abs(case when exists(select 1 from t1 where b not between ~case when (t1.e-(c-t1.c) | t1.a) in (select abs(~((min(t1.f) | cast(avg(c) AS integer))*(min(b))-count(distinct 19)*min(e)) | -((count(*))))-cast(avg(d) AS integer) from t1 union select -count(distinct t1.a) from t1) or f>a then 11 else e end*11 and t1.e) then t1.e when -17<11 then 17 else t1.a end)/abs(a)) FROM t1 WHERE NOT (c<=19)} +} {0} +do_test randexpr-2.2531 { + db eval {SELECT (abs(case when exists(select 1 from t1 where b not between ~case when (t1.e-(c-t1.c) & t1.a) in (select abs(~((min(t1.f) & cast(avg(c) AS integer))*(min(b))-count(distinct 19)*min(e)) & -((count(*))))-cast(avg(d) AS integer) from t1 union select -count(distinct t1.a) from t1) or f>a then 11 else e end*11 and t1.e) then t1.e when -17<11 then 17 else t1.a end)/abs(a)) FROM t1 WHERE NOT (c<=19)} +} {0} +do_test randexpr-2.2532 { + db eval {SELECT case when t1.e-19 in (case (abs(t1.a*+~c*coalesce((select c from t1 where ~ -(select abs(case cast(avg(13) AS integer) when - -cast(avg(f) AS integer) then count(distinct t1.d) else (count(*)) end+count(*)) from t1) not between (abs(a | t1.a)/abs(t1.c)) and 19),t1.b)-c*17*(t1.f))/abs(d)) when 13 then 19 else t1.b end,(b),17) then 19 when (11)>=t1.b then b else b end*11 FROM t1 WHERE (case 11 when case t1.e when coalesce((select a from t1 where t1.a=t1.a),t1.f),d,13) then c when 11 between t1.b and 17 then d else 19 end) then f else 19 end then t1.d else c end< -c) and a not in (11,c,11) or 11<>e or exists(select 1 from t1 where b<17)} +} {2200} +do_test randexpr-2.2533 { + db eval {SELECT case when t1.e-19 in (case (abs(t1.a*+~c*coalesce((select c from t1 where ~ -(select abs(case cast(avg(13) AS integer) when - -cast(avg(f) AS integer) then count(distinct t1.d) else (count(*)) end+count(*)) from t1) not between (abs(a | t1.a)/abs(t1.c)) and 19),t1.b)-c*17*(t1.f))/abs(d)) when 13 then 19 else t1.b end,(b),17) then 19 when (11)>=t1.b then b else b end*11 FROM t1 WHERE NOT ((case 11 when case t1.e when coalesce((select a from t1 where t1.a=t1.a),t1.f),d,13) then c when 11 between t1.b and 17 then d else 19 end) then f else 19 end then t1.d else c end< -c) and a not in (11,c,11) or 11<>e or exists(select 1 from t1 where b<17))} +} {} +do_test randexpr-2.2534 { + db eval {SELECT case when t1.e-19 in (case (abs(t1.a*+~c*coalesce((select c from t1 where ~ -(select abs(case cast(avg(13) AS integer) when - -cast(avg(f) AS integer) then count(distinct t1.d) else (count(*)) end+count(*)) from t1) not between (abs(a & t1.a)/abs(t1.c)) and 19),t1.b)-c*17*(t1.f))/abs(d)) when 13 then 19 else t1.b end,(b),17) then 19 when (11)>=t1.b then b else b end*11 FROM t1 WHERE (case 11 when case t1.e when coalesce((select a from t1 where t1.a=t1.a),t1.f),d,13) then c when 11 between t1.b and 17 then d else 19 end) then f else 19 end then t1.d else c end< -c) and a not in (11,c,11) or 11<>e or exists(select 1 from t1 where b<17)} +} {2200} +do_test randexpr-2.2535 { + db eval {SELECT t1.b*case when (abs(t1.c+case when d not in (a,case when b=(t1.a) then (e) when b not between f and t1.c then t1.b else t1.e end, -11) then t1.d when not exists(select 1 from t1 where 19 not between (a) and a or t1.c>d) then d else b end+t1.a+13-19+d)/abs(t1.d))> -t1.f then t1.a when t1.d in (select d from t1 union select c from t1) or 13 not between d and t1.f then t1.b else e end+ - -a FROM t1 WHERE t1.f<=11} +} {} +do_test randexpr-2.2536 { + db eval {SELECT t1.b*case when (abs(t1.c+case when d not in (a,case when b=(t1.a) then (e) when b not between f and t1.c then t1.b else t1.e end, -11) then t1.d when not exists(select 1 from t1 where 19 not between (a) and a or t1.c>d) then d else b end+t1.a+13-19+d)/abs(t1.d))> -t1.f then t1.a when t1.d in (select d from t1 union select c from t1) or 13 not between d and t1.f then t1.b else e end+ - -a FROM t1 WHERE NOT (t1.f<=11)} +} {20100} +do_test randexpr-2.2537 { + db eval {SELECT coalesce((select max(coalesce((select e+t1.c from t1 where f*11+coalesce((select max(17) from t1 where not ~case a when t1.f+13*e-(11)*t1.f then d else a end>d and (a not between t1.c and t1.c)),t1.d)- -f-b+11=b),19)-t1.f) from t1 where exists(select 1 from t1 where 19<>11)),c) FROM t1 WHERE case when 11 in (select -abs(abs( - -(cast(avg(+11-c) AS integer)+cast(avg(~a) AS integer))*max(11))+cast(avg(d) AS integer)-cast(avg(e) AS integer)-((max(t1.e))))+count(*) from t1 union select ( -count(*)) from t1) then t1.a when e>d then c- - -t1.a else 19 end in (select count(distinct -f) from t1 union select count(distinct d) from t1) and not e<17} +} {} +do_test randexpr-2.2538 { + db eval {SELECT coalesce((select max(coalesce((select e+t1.c from t1 where f*11+coalesce((select max(17) from t1 where not ~case a when t1.f+13*e-(11)*t1.f then d else a end>d and (a not between t1.c and t1.c)),t1.d)- -f-b+11=b),19)-t1.f) from t1 where exists(select 1 from t1 where 19<>11)),c) FROM t1 WHERE NOT (case when 11 in (select -abs(abs( - -(cast(avg(+11-c) AS integer)+cast(avg(~a) AS integer))*max(11))+cast(avg(d) AS integer)-cast(avg(e) AS integer)-((max(t1.e))))+count(*) from t1 union select ( -count(*)) from t1) then t1.a when e>d then c- - -t1.a else 19 end in (select count(distinct -f) from t1 union select count(distinct d) from t1) and not e<17)} +} {-581} +do_test randexpr-2.2539 { + db eval {SELECT case when (coalesce((select max(a*case when 17+f>f-t1.d*t1.f then t1.d when t1.c not between t1.e and d then 19 else (c) end) from t1 where not t1.d not between - -17 and 19),t1.a) in (select min((13)) from t1 union select ~(abs(count(distinct t1.a))*((( -max( -t1.f)))+max( -t1.c) | count(*)))-cast(avg(11) AS integer) from t1)) then c- - -d when t1.d>=d then d else 13 end FROM t1 WHERE ((abs(t1.a-t1.a*t1.d*coalesce((select coalesce((select max(11) from t1 where exists(select 1 from t1 where 11+t1.d | -t1.c-case when b+d in (select count(*) from t1 union select max(17)+ -count(distinct t1.d) from t1) then t1.c else d end-a | 13<>c)),t1.c) from t1 where 13 not in (d,t1.a,f) and 19=t1.f),(13))+(t1.d))/abs(t1.c)) between t1.f and t1.d)} +} {} +do_test randexpr-2.2540 { + db eval {SELECT case when (coalesce((select max(a*case when 17+f>f-t1.d*t1.f then t1.d when t1.c not between t1.e and d then 19 else (c) end) from t1 where not t1.d not between - -17 and 19),t1.a) in (select min((13)) from t1 union select ~(abs(count(distinct t1.a))*((( -max( -t1.f)))+max( -t1.c) | count(*)))-cast(avg(11) AS integer) from t1)) then c- - -d when t1.d>=d then d else 13 end FROM t1 WHERE NOT (((abs(t1.a-t1.a*t1.d*coalesce((select coalesce((select max(11) from t1 where exists(select 1 from t1 where 11+t1.d | -t1.c-case when b+d in (select count(*) from t1 union select max(17)+ -count(distinct t1.d) from t1) then t1.c else d end-a | 13<>c)),t1.c) from t1 where 13 not in (d,t1.a,f) and 19=t1.f),(13))+(t1.d))/abs(t1.c)) between t1.f and t1.d))} +} {400} +do_test randexpr-2.2541 { + db eval {SELECT case when (coalesce((select max(a*case when 17+f>f-t1.d*t1.f then t1.d when t1.c not between t1.e and d then 19 else (c) end) from t1 where not t1.d not between - -17 and 19),t1.a) in (select min((13)) from t1 union select ~(abs(count(distinct t1.a))*((( -max( -t1.f)))+max( -t1.c) & count(*)))-cast(avg(11) AS integer) from t1)) then c- - -d when t1.d>=d then d else 13 end FROM t1 WHERE NOT (((abs(t1.a-t1.a*t1.d*coalesce((select coalesce((select max(11) from t1 where exists(select 1 from t1 where 11+t1.d | -t1.c-case when b+d in (select count(*) from t1 union select max(17)+ -count(distinct t1.d) from t1) then t1.c else d end-a | 13<>c)),t1.c) from t1 where 13 not in (d,t1.a,f) and 19=t1.f),(13))+(t1.d))/abs(t1.c)) between t1.f and t1.d))} +} {400} +do_test randexpr-2.2542 { + db eval {SELECT case when f | c>t1.d-case when (abs(t1.b-t1.d*f)/abs(c))=t1.e then 17 when not exists(select 1 from t1 where t1.b=(11) or c not in (13,17,b)) or aa then t1.c when not 11<(f) then case when t1.c= -b then c else 11 end else e end | f>=t1.b and b not between -(t1.e) and f) then 17 when f in (select -count(distinct t1.e) from t1 union select case min(f) when case cast(avg( -t1.b) AS integer) when cast(avg(e) AS integer) then -max(e) else min(t1.b) end then count(*) else (cast(avg(t1.e) AS integer)) end from t1) then case c when e then t1.f else 13 end else t1.d end} +} {} +do_test randexpr-2.2543 { + db eval {SELECT case when f | c>t1.d-case when (abs(t1.b-t1.d*f)/abs(c))=t1.e then 17 when not exists(select 1 from t1 where t1.b=(11) or c not in (13,17,b)) or aa then t1.c when not 11<(f) then case when t1.c= -b then c else 11 end else e end | f>=t1.b and b not between -(t1.e) and f) then 17 when f in (select -count(distinct t1.e) from t1 union select case min(f) when case cast(avg( -t1.b) AS integer) when cast(avg(e) AS integer) then -max(e) else min(t1.b) end then count(*) else (cast(avg(t1.e) AS integer)) end from t1) then case c when e then t1.f else 13 end else t1.d end)} +} {11} +do_test randexpr-2.2544 { + db eval {SELECT case when f & c>t1.d-case when (abs(t1.b-t1.d*f)/abs(c))=t1.e then 17 when not exists(select 1 from t1 where t1.b=(11) or c not in (13,17,b)) or aa then t1.c when not 11<(f) then case when t1.c= -b then c else 11 end else e end | f>=t1.b and b not between -(t1.e) and f) then 17 when f in (select -count(distinct t1.e) from t1 union select case min(f) when case cast(avg( -t1.b) AS integer) when cast(avg(e) AS integer) then -max(e) else min(t1.b) end then count(*) else (cast(avg(t1.e) AS integer)) end from t1) then case c when e then t1.f else 13 end else t1.d end)} +} {11} +do_test randexpr-2.2545 { + db eval {SELECT 17+coalesce((select max(19) from t1 where 11 in (select (abs((abs(~(case +b+17 when t1.e*t1.b then 17 else case when t1.b+17+d*a in (select (~count(distinct a)) from t1 union select case cast(avg(t1.e) AS integer) when count(*) then count(distinct t1.d) else count(distinct b) end from t1) then t1.f when (t1.e in ( -t1.a,t1.e,d)) then 17 else t1.e end | e end)- -b)/abs(t1.f)))/abs(13)) from t1 union select t1.d from t1)),17) FROM t1 WHERE e+t1.b not in (d,a,t1.c) and case case e when (case when +case 13 when t1.a then 19 else 19 end+d in (select count(*)-min(b) from t1 union select - -min(t1.d) from t1) or f in (select ( -min(t1.e)) from t1 union select cast(avg( -19) AS integer) from t1) or (t1.f in (select -max( -t1.c) from t1 union select (min(t1.c)) from t1)) then b else +t1.b end)-t1.b then b else 19 end when a then b else e end between ( -(t1.c)) and a} +} {} +do_test randexpr-2.2546 { + db eval {SELECT 17+coalesce((select max(19) from t1 where 11 in (select (abs((abs(~(case +b+17 when t1.e*t1.b then 17 else case when t1.b+17+d*a in (select (~count(distinct a)) from t1 union select case cast(avg(t1.e) AS integer) when count(*) then count(distinct t1.d) else count(distinct b) end from t1) then t1.f when (t1.e in ( -t1.a,t1.e,d)) then 17 else t1.e end | e end)- -b)/abs(t1.f)))/abs(13)) from t1 union select t1.d from t1)),17) FROM t1 WHERE NOT (e+t1.b not in (d,a,t1.c) and case case e when (case when +case 13 when t1.a then 19 else 19 end+d in (select count(*)-min(b) from t1 union select - -min(t1.d) from t1) or f in (select ( -min(t1.e)) from t1 union select cast(avg( -19) AS integer) from t1) or (t1.f in (select -max( -t1.c) from t1 union select (min(t1.c)) from t1)) then b else +t1.b end)-t1.b then b else 19 end when a then b else e end between ( -(t1.c)) and a)} +} {34} +do_test randexpr-2.2547 { + db eval {SELECT 17+coalesce((select max(19) from t1 where 11 in (select (abs((abs(~(case +b+17 when t1.e*t1.b then 17 else case when t1.b+17+d*a in (select (~count(distinct a)) from t1 union select case cast(avg(t1.e) AS integer) when count(*) then count(distinct t1.d) else count(distinct b) end from t1) then t1.f when (t1.e in ( -t1.a,t1.e,d)) then 17 else t1.e end & e end)- -b)/abs(t1.f)))/abs(13)) from t1 union select t1.d from t1)),17) FROM t1 WHERE NOT (e+t1.b not in (d,a,t1.c) and case case e when (case when +case 13 when t1.a then 19 else 19 end+d in (select count(*)-min(b) from t1 union select - -min(t1.d) from t1) or f in (select ( -min(t1.e)) from t1 union select cast(avg( -19) AS integer) from t1) or (t1.f in (select -max( -t1.c) from t1 union select (min(t1.c)) from t1)) then b else +t1.b end)-t1.b then b else 19 end when a then b else e end between ( -(t1.c)) and a)} +} {34} +do_test randexpr-2.2548 { + db eval {SELECT (abs(~(abs((select ~count(*) | +(max( -coalesce((select max(13) from t1 where coalesce((select max(t1.d) from t1 where 11<+coalesce((select max((case when 19=t1.a then (d) else 19 end)) from t1 where (11) in (17,c,b)),c)*t1.e),t1.c)<13),11)*b | t1.c+17)) from t1))/abs(~b-f))-t1.d*a)/abs(e)) FROM t1 WHERE c not in (coalesce((select t1.a from t1 where -(t1.a+17*~case when coalesce((select max(t1.c) from t1 where (coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where a<=t1.a)),11) in (select (count(distinct t1.d)+count(distinct c)) from t1 union select count(distinct e) from t1))),13)*f=d then d when t1.d in (select t1.d from t1 union select t1.f from t1) then d else t1.f end+c*c | f)+t1.c*t1.a in (select 17 from t1 union select 13 from t1)),t1.f),17,t1.f)} +} {80} +do_test randexpr-2.2549 { + db eval {SELECT (abs(~(abs((select ~count(*) | +(max( -coalesce((select max(13) from t1 where coalesce((select max(t1.d) from t1 where 11<+coalesce((select max((case when 19=t1.a then (d) else 19 end)) from t1 where (11) in (17,c,b)),c)*t1.e),t1.c)<13),11)*b | t1.c+17)) from t1))/abs(~b-f))-t1.d*a)/abs(e)) FROM t1 WHERE NOT (c not in (coalesce((select t1.a from t1 where -(t1.a+17*~case when coalesce((select max(t1.c) from t1 where (coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where a<=t1.a)),11) in (select (count(distinct t1.d)+count(distinct c)) from t1 union select count(distinct e) from t1))),13)*f=d then d when t1.d in (select t1.d from t1 union select t1.f from t1) then d else t1.f end+c*c | f)+t1.c*t1.a in (select 17 from t1 union select 13 from t1)),t1.f),17,t1.f))} +} {} +do_test randexpr-2.2550 { + db eval {SELECT (abs(~(abs((select ~count(*) & +(max( -coalesce((select max(13) from t1 where coalesce((select max(t1.d) from t1 where 11<+coalesce((select max((case when 19=t1.a then (d) else 19 end)) from t1 where (11) in (17,c,b)),c)*t1.e),t1.c)<13),11)*b & t1.c+17)) from t1))/abs(~b-f))-t1.d*a)/abs(e)) FROM t1 WHERE c not in (coalesce((select t1.a from t1 where -(t1.a+17*~case when coalesce((select max(t1.c) from t1 where (coalesce((select max(t1.f) from t1 where not exists(select 1 from t1 where a<=t1.a)),11) in (select (count(distinct t1.d)+count(distinct c)) from t1 union select count(distinct e) from t1))),13)*f=d then d when t1.d in (select t1.d from t1 union select t1.f from t1) then d else t1.f end+c*c | f)+t1.c*t1.a in (select 17 from t1 union select 13 from t1)),t1.f),17,t1.f)} +} {80} +do_test randexpr-2.2551 { + db eval {SELECT case (19) when t1.a then t1.f+coalesce((select max(t1.f) from t1 where case when t1.c=t1.a or (t1.d | case when t1.f=t1.d then a else coalesce((select max(case when 11>=a then t1.b else d end+t1.a) from t1 where -t1.a not between t1.e and 19),11) end<>t1.d) then t1.e else c end-t1.f*b+f=19),t1.b) | (t1.a)+e else a end FROM t1 WHERE (case e when d then +(select (min(t1.a)) from t1) else case when a in ((select min(case -t1.c when d then d else f end+ -e)-+cast(avg(19) AS integer)+max(d) from t1)*t1.d | -t1.c,b,e) then t1.d when t1.b in (select +min(e) | min(t1.b) from t1 union select -count(distinct e) from t1) then d else 11 end*13-(e) end not in (t1.c,c,17))} +} {100} +do_test randexpr-2.2552 { + db eval {SELECT case (19) when t1.a then t1.f+coalesce((select max(t1.f) from t1 where case when t1.c=t1.a or (t1.d | case when t1.f=t1.d then a else coalesce((select max(case when 11>=a then t1.b else d end+t1.a) from t1 where -t1.a not between t1.e and 19),11) end<>t1.d) then t1.e else c end-t1.f*b+f=19),t1.b) | (t1.a)+e else a end FROM t1 WHERE NOT ((case e when d then +(select (min(t1.a)) from t1) else case when a in ((select min(case -t1.c when d then d else f end+ -e)-+cast(avg(19) AS integer)+max(d) from t1)*t1.d | -t1.c,b,e) then t1.d when t1.b in (select +min(e) | min(t1.b) from t1 union select -count(distinct e) from t1) then d else 11 end*13-(e) end not in (t1.c,c,17)))} +} {} +do_test randexpr-2.2553 { + db eval {SELECT case (19) when t1.a then t1.f+coalesce((select max(t1.f) from t1 where case when t1.c=t1.a or (t1.d & case when t1.f=t1.d then a else coalesce((select max(case when 11>=a then t1.b else d end+t1.a) from t1 where -t1.a not between t1.e and 19),11) end<>t1.d) then t1.e else c end-t1.f*b+f=19),t1.b) & (t1.a)+e else a end FROM t1 WHERE (case e when d then +(select (min(t1.a)) from t1) else case when a in ((select min(case -t1.c when d then d else f end+ -e)-+cast(avg(19) AS integer)+max(d) from t1)*t1.d | -t1.c,b,e) then t1.d when t1.b in (select +min(e) | min(t1.b) from t1 union select -count(distinct e) from t1) then d else 11 end*13-(e) end not in (t1.c,c,17))} +} {100} +do_test randexpr-2.2554 { + db eval {SELECT (abs(( -case when 11*coalesce((select coalesce((select d from t1 where ((+t1.f*(select max(t1.f)*min(t1.a) from t1)*d*t1.f between 11 and 13))), -t1.c) from t1 where ((e)>=t1.b) or not t1.a in (select f from t1 union select c from t1) and 11<=a or c between (t1.c) and t1.d),t1.f)t1.f} +} {} +do_test randexpr-2.2555 { + db eval {SELECT (abs(( -case when 11*coalesce((select coalesce((select d from t1 where ((+t1.f*(select max(t1.f)*min(t1.a) from t1)*d*t1.f between 11 and 13))), -t1.c) from t1 where ((e)>=t1.b) or not t1.a in (select f from t1 union select c from t1) and 11<=a or c between (t1.c) and t1.d),t1.f)t1.f)} +} {53} +do_test randexpr-2.2556 { + db eval {SELECT case (t1.b) | t1.d-+t1.e*(select (~count(*) | min(c)-case max(case when e | b in (select t1.b from t1 union select t1.b from t1) then d when 17 between 13 and t1.d then d else t1.c end) when abs(count(distinct (t1.e)))- -min(t1.e) then cast(avg(17) AS integer) else count(distinct c) end) from t1) | b-a-+f-t1.f when +a then t1.d else d end FROM t1 WHERE (17>t1.d) and coalesce((select max((t1.a)+coalesce((select max(17*b) from t1 where t1.d-coalesce((select t1.e from t1 where t1.b<>13 or 19=t1.a),t1.d)*f<=(19) or (t1.c<11 and not not dt1.d or d=11} +} {} +do_test randexpr-2.2557 { + db eval {SELECT case (t1.b) | t1.d-+t1.e*(select (~count(*) | min(c)-case max(case when e | b in (select t1.b from t1 union select t1.b from t1) then d when 17 between 13 and t1.d then d else t1.c end) when abs(count(distinct (t1.e)))- -min(t1.e) then cast(avg(17) AS integer) else count(distinct c) end) from t1) | b-a-+f-t1.f when +a then t1.d else d end FROM t1 WHERE NOT ((17>t1.d) and coalesce((select max((t1.a)+coalesce((select max(17*b) from t1 where t1.d-coalesce((select t1.e from t1 where t1.b<>13 or 19=t1.a),t1.d)*f<=(19) or (t1.c<11 and not not dt1.d or d=11)} +} {400} +do_test randexpr-2.2558 { + db eval {SELECT case (t1.b) & t1.d-+t1.e*(select (~count(*) & min(c)-case max(case when e & b in (select t1.b from t1 union select t1.b from t1) then d when 17 between 13 and t1.d then d else t1.c end) when abs(count(distinct (t1.e)))- -min(t1.e) then cast(avg(17) AS integer) else count(distinct c) end) from t1) & b-a-+f-t1.f when +a then t1.d else d end FROM t1 WHERE NOT ((17>t1.d) and coalesce((select max((t1.a)+coalesce((select max(17*b) from t1 where t1.d-coalesce((select t1.e from t1 where t1.b<>13 or 19=t1.a),t1.d)*f<=(19) or (t1.c<11 and not not dt1.d or d=11)} +} {400} +do_test randexpr-2.2559 { + db eval {SELECT case when case when coalesce((select max(c*case (select min(case when f in (select t1.e from t1 union select f+case when d<=d then t1.f when b<=11 then t1.c else t1.b end*11 from t1) then f else c end) from t1) when f then 11 else b end) from t1 where d in (t1.b,t1.a,c)),d) between (d) and 19 then -a else a end in ( -c,t1.d,t1.d) then c when e<> -d then a else t1.c end FROM t1 WHERE a=c or case when e=(e)),t1.a) then c | t1.f when exists(select 1 from t1 where a not between 19 and e) then t1.a else 17 end>t1.d} +} {} +do_test randexpr-2.2560 { + db eval {SELECT case when case when coalesce((select max(c*case (select min(case when f in (select t1.e from t1 union select f+case when d<=d then t1.f when b<=11 then t1.c else t1.b end*11 from t1) then f else c end) from t1) when f then 11 else b end) from t1 where d in (t1.b,t1.a,c)),d) between (d) and 19 then -a else a end in ( -c,t1.d,t1.d) then c when e<> -d then a else t1.c end FROM t1 WHERE NOT (a=c or case when e=(e)),t1.a) then c | t1.f when exists(select 1 from t1 where a not between 19 and e) then t1.a else 17 end>t1.d)} +} {100} +do_test randexpr-2.2561 { + db eval {SELECT 13+(select -abs(+cast(avg((select cast(avg(t1.e*(t1.c)- -(abs(b+e)/abs(f))) AS integer) from t1)) AS integer)-~ -+abs(abs(count(*))) | min(t1.e | t1.e-t1.b)*max(e)-max(t1.f) | min(c)*min(t1.b)+min(t1.e)-count(distinct 11) | min(b)*( - -count(distinct 19)))-count(*) from t1) FROM t1 WHERE d in (select count(*) from t1 union select case count(*) when max(17) | -max(coalesce((select case t1.d*t1.e when t1.a then 11 else 13 end*f- -f from t1 where b in (select case ~abs(max(13)) when case ((max(c))) when cast(avg(t1.c) AS integer) then max(13) else count(distinct t1.d) end then cast(avg(t1.a) AS integer) else cast(avg(11) AS integer) end from t1 union select -max(13) from t1)),13))*cast(avg(f) AS integer) then count(*) else count(distinct e) end from t1) and exists(select 1 from t1 where case d when -(abs(17)/abs(t1.f)) then t1.a else t1.d end=19} +} {17017} +do_test randexpr-2.2565 { + db eval {SELECT c+c*(abs(t1.c+coalesce((select case when 17 not in (t1.f,t1.e,t1.d) or (17=19)} +} {} +do_test randexpr-2.2566 { + db eval {SELECT +case when not c in (select count(distinct t1.b) from t1 union select -+(cast(avg(b*t1.b) AS integer))*max(case 17 when b then 13 else t1.a end)-count(distinct a) | cast(avg(t1.f) AS integer)+max(t1.d) from t1) then t1.e when a<=case t1.a when (e) then t1.d else d end then d else t1.b end*11-a | 17 | t1.a-f FROM t1 WHERE (c not in (t1.b,(select case case ++(min(19))*(count(distinct t1.a))+count(distinct e) | cast(avg(t1.e) AS integer) when min( -t1.d) then cast(avg(13) AS integer) else min(17) end*cast(avg(a) AS integer) when count(distinct -b) then cast(avg(11) AS integer) else - -(cast(avg(c) AS integer)) end from t1)-11+t1.e,t1.a) or d*case d when a then t1.c else 17 end*19 not between b and t1.c or -17=b or f in (select a from t1 union select -b from t1))} +} {-227} +do_test randexpr-2.2567 { + db eval {SELECT +case when not c in (select count(distinct t1.b) from t1 union select -+(cast(avg(b*t1.b) AS integer))*max(case 17 when b then 13 else t1.a end)-count(distinct a) | cast(avg(t1.f) AS integer)+max(t1.d) from t1) then t1.e when a<=case t1.a when (e) then t1.d else d end then d else t1.b end*11-a | 17 | t1.a-f FROM t1 WHERE NOT ((c not in (t1.b,(select case case ++(min(19))*(count(distinct t1.a))+count(distinct e) | cast(avg(t1.e) AS integer) when min( -t1.d) then cast(avg(13) AS integer) else min(17) end*cast(avg(a) AS integer) when count(distinct -b) then cast(avg(11) AS integer) else - -(cast(avg(c) AS integer)) end from t1)-11+t1.e,t1.a) or d*case d when a then t1.c else 17 end*19 not between b and t1.c or -17=b or f in (select a from t1 union select -b from t1)))} +} {} +do_test randexpr-2.2568 { + db eval {SELECT +case when not c in (select count(distinct t1.b) from t1 union select -+(cast(avg(b*t1.b) AS integer))*max(case 17 when b then 13 else t1.a end)-count(distinct a) & cast(avg(t1.f) AS integer)+max(t1.d) from t1) then t1.e when a<=case t1.a when (e) then t1.d else d end then d else t1.b end*11-a & 17 & t1.a-f FROM t1 WHERE (c not in (t1.b,(select case case ++(min(19))*(count(distinct t1.a))+count(distinct e) | cast(avg(t1.e) AS integer) when min( -t1.d) then cast(avg(13) AS integer) else min(17) end*cast(avg(a) AS integer) when count(distinct -b) then cast(avg(11) AS integer) else - -(cast(avg(c) AS integer)) end from t1)-11+t1.e,t1.a) or d*case d when a then t1.c else 17 end*19 not between b and t1.c or -17=b or f in (select a from t1 union select -b from t1))} +} {0} +do_test randexpr-2.2569 { + db eval {SELECT coalesce((select (abs(f)/abs(coalesce((select max(19*b+d*coalesce((select max(t1.c) from t1 where case when d>=(abs((11))/abs(t1.a*13+(13)-d*e+11)) then t1.c when t1.c>=a then 19 else -17 end*t1.e> -e),t1.f)) from t1 where 13<=t1.e),t1.d))) from t1 where t1.d in (select d from t1 union select a from t1)),t1.e) FROM t1 WHERE t1.c between (11) and coalesce((select max(b*case t1.c when t1.f then t1.f else 11 end) from t1 where +(select count(distinct case when f not between -13 and 19 then t1.f++(f) | t1.e*(+13)* -(t1.c)-t1.b when 13=t1.d then 19 else t1.b end*t1.a) from t1) in (t1.e,11, -19)),d)+f} +} {0} +do_test randexpr-2.2570 { + db eval {SELECT coalesce((select (abs(f)/abs(coalesce((select max(19*b+d*coalesce((select max(t1.c) from t1 where case when d>=(abs((11))/abs(t1.a*13+(13)-d*e+11)) then t1.c when t1.c>=a then 19 else -17 end*t1.e> -e),t1.f)) from t1 where 13<=t1.e),t1.d))) from t1 where t1.d in (select d from t1 union select a from t1)),t1.e) FROM t1 WHERE NOT (t1.c between (11) and coalesce((select max(b*case t1.c when t1.f then t1.f else 11 end) from t1 where +(select count(distinct case when f not between -13 and 19 then t1.f++(f) | t1.e*(+13)* -(t1.c)-t1.b when 13=t1.d then 19 else t1.b end*t1.a) from t1) in (t1.e,11, -19)),d)+f)} +} {} +do_test randexpr-2.2571 { + db eval {SELECT case when (not 19>=(abs(t1.b)/abs(+f))) then case 13 when case t1.c when t1.b then f else 13 end then t1.e else t1.a end+coalesce((select max(c) from t1 where a not between t1.d*17*coalesce((select max(e*b) from t1 where t1.a=11),t1.c) and t1.d),t1.d) when (case when t1.d not in (e,t1.a,t1.b) then 19 else t1.f end between t1.c and 19) then t1.e else 11 end FROM t1 WHERE t1.b*+c>=17} +} {11} +do_test randexpr-2.2572 { + db eval {SELECT case when (not 19>=(abs(t1.b)/abs(+f))) then case 13 when case t1.c when t1.b then f else 13 end then t1.e else t1.a end+coalesce((select max(c) from t1 where a not between t1.d*17*coalesce((select max(e*b) from t1 where t1.a=11),t1.c) and t1.d),t1.d) when (case when t1.d not in (e,t1.a,t1.b) then 19 else t1.f end between t1.c and 19) then t1.e else 11 end FROM t1 WHERE NOT (t1.b*+c>=17)} +} {} +do_test randexpr-2.2573 { + db eval {SELECT case when d-t1.c<>e then c when (11 not between 13 and 13) then 13 else -case when c*t1.d>=b*b then -t1.f else b-t1.c | d*(case t1.d when -case t1.b when t1.b then t1.b else 19 end*19*(t1.d) then 13 else 19 end) end+19*11 end+b FROM t1 WHERE ~~case when t1.d+(abs(t1.b+coalesce((select coalesce((select max(b-a-a) from t1 where 17 not in (e,case when (t1.d)<=t1.f or -a not between c and t1.b then c when -19 in ( -d,(t1.a),19) then b else f end,t1.e)), -13) from t1 where not b in (t1.b, -t1.b,c)),e))/abs(11)) between 13 and d then (t1.b) when t1.e<13 then 19 else a end-(19)-d*t1.d not in (d,t1.c,13)} +} {500} +do_test randexpr-2.2574 { + db eval {SELECT case when d-t1.c<>e then c when (11 not between 13 and 13) then 13 else -case when c*t1.d>=b*b then -t1.f else b-t1.c | d*(case t1.d when -case t1.b when t1.b then t1.b else 19 end*19*(t1.d) then 13 else 19 end) end+19*11 end+b FROM t1 WHERE NOT (~~case when t1.d+(abs(t1.b+coalesce((select coalesce((select max(b-a-a) from t1 where 17 not in (e,case when (t1.d)<=t1.f or -a not between c and t1.b then c when -19 in ( -d,(t1.a),19) then b else f end,t1.e)), -13) from t1 where not b in (t1.b, -t1.b,c)),e))/abs(11)) between 13 and d then (t1.b) when t1.e<13 then 19 else a end-(19)-d*t1.d not in (d,t1.c,13))} +} {} +do_test randexpr-2.2575 { + db eval {SELECT case when d-t1.c<>e then c when (11 not between 13 and 13) then 13 else -case when c*t1.d>=b*b then -t1.f else b-t1.c & d*(case t1.d when -case t1.b when t1.b then t1.b else 19 end*19*(t1.d) then 13 else 19 end) end+19*11 end+b FROM t1 WHERE ~~case when t1.d+(abs(t1.b+coalesce((select coalesce((select max(b-a-a) from t1 where 17 not in (e,case when (t1.d)<=t1.f or -a not between c and t1.b then c when -19 in ( -d,(t1.a),19) then b else f end,t1.e)), -13) from t1 where not b in (t1.b, -t1.b,c)),e))/abs(11)) between 13 and d then (t1.b) when t1.e<13 then 19 else a end-(19)-d*t1.d not in (d,t1.c,13)} +} {500} +do_test randexpr-2.2576 { + db eval {SELECT 19+t1.d+d-t1.c*case when 11 not between e and ~c+(select min((abs(t1.b*t1.b)/abs(+t1.c-e))) from t1) then 17 when case when 17*13 not in (t1.b,(abs(~c)/abs( -17-e)),(t1.e)) then 17 else (t1.c) end+c+t1.f not in (t1.f,19,t1.f) then -t1.e else t1.f end FROM t1 WHERE (+13) between +b and t1.e+11} +} {} +do_test randexpr-2.2577 { + db eval {SELECT 19+t1.d+d-t1.c*case when 11 not between e and ~c+(select min((abs(t1.b*t1.b)/abs(+t1.c-e))) from t1) then 17 when case when 17*13 not in (t1.b,(abs(~c)/abs( -17-e)),(t1.e)) then 17 else (t1.c) end+c+t1.f not in (t1.f,19,t1.f) then -t1.e else t1.f end FROM t1 WHERE NOT ((+13) between +b and t1.e+11)} +} {-4281} +do_test randexpr-2.2578 { + db eval {SELECT 17+d*~(abs(coalesce((select 19 | f | e*~+((abs(e)/abs(+19))-t1.c-case 17 when t1.f then f else 19 end-17) from t1 where (e in (select ~(11) from t1 union select case when (f)>a then b when e between -e and t1.b then 17 else t1.f end*t1.a from t1))),t1.b)*e)/abs(17))-t1.a-19 FROM t1 WHERE t1.e not in (d,e,case 19 when - -~case when exists(select 1 from t1 where 17 not in (t1.d,t1.a,coalesce((select max(11-a) from t1 where coalesce((select +c from t1 where exists(select 1 from t1 where case when t1.f not in (19+(f),d,t1.c) then t1.c when (exists(select 1 from t1 where t1.c>19)) then 19 else f end not between a and t1.f)),t1.c)<=b),17))) then t1.d-11 else t1.b end then (d) else t1.f end-(c))} +} {} +do_test randexpr-2.2579 { + db eval {SELECT 17+d*~(abs(coalesce((select 19 | f | e*~+((abs(e)/abs(+19))-t1.c-case 17 when t1.f then f else 19 end-17) from t1 where (e in (select ~(11) from t1 union select case when (f)>a then b when e between -e and t1.b then 17 else t1.f end*t1.a from t1))),t1.b)*e)/abs(17))-t1.a-19 FROM t1 WHERE NOT (t1.e not in (d,e,case 19 when - -~case when exists(select 1 from t1 where 17 not in (t1.d,t1.a,coalesce((select max(11-a) from t1 where coalesce((select +c from t1 where exists(select 1 from t1 where case when t1.f not in (19+(f),d,t1.c) then t1.c when (exists(select 1 from t1 where t1.c>19)) then 19 else f end not between a and t1.f)),t1.c)<=b),17))) then t1.d-11 else t1.b end then (d) else t1.f end-(c)))} +} {-2353302} +do_test randexpr-2.2580 { + db eval {SELECT 17+d*~(abs(coalesce((select 19 & f & e*~+((abs(e)/abs(+19))-t1.c-case 17 when t1.f then f else 19 end-17) from t1 where (e in (select ~(11) from t1 union select case when (f)>a then b when e between -e and t1.b then 17 else t1.f end*t1.a from t1))),t1.b)*e)/abs(17))-t1.a-19 FROM t1 WHERE NOT (t1.e not in (d,e,case 19 when - -~case when exists(select 1 from t1 where 17 not in (t1.d,t1.a,coalesce((select max(11-a) from t1 where coalesce((select +c from t1 where exists(select 1 from t1 where case when t1.f not in (19+(f),d,t1.c) then t1.c when (exists(select 1 from t1 where t1.c>19)) then 19 else f end not between a and t1.f)),t1.c)<=b),17))) then t1.d-11 else t1.b end then (d) else t1.f end-(c)))} +} {-2353302} +do_test randexpr-2.2581 { + db eval {SELECT case a when b-coalesce((select coalesce((select max(c-(abs((19))/abs(coalesce((select t1.c+d from t1 where 17 not in (d,t1.c, -t1.e)),t1.b)-(e)))) from t1 where t1.d in (t1.e,e,t1.f)),(e)) from t1 where t1.b=t1.e or t1.b not between b and e or t1.f not between t1.b and e or c not between -b and a),d) then 13 else 17 end FROM t1 WHERE a+17+(17) in ( -t1.a,13,coalesce((select max(e) from t1 where b+a-13<=b),e)) or e in (select abs( -+~abs(+(min(c))))+count(distinct b) from t1 union select abs(+((max(t1.c)) | min(t1.b))) from t1) and 13 not between f and 19 or not e not in ( -17,13,t1.a)} +} {} +do_test randexpr-2.2582 { + db eval {SELECT case a when b-coalesce((select coalesce((select max(c-(abs((19))/abs(coalesce((select t1.c+d from t1 where 17 not in (d,t1.c, -t1.e)),t1.b)-(e)))) from t1 where t1.d in (t1.e,e,t1.f)),(e)) from t1 where t1.b=t1.e or t1.b not between b and e or t1.f not between t1.b and e or c not between -b and a),d) then 13 else 17 end FROM t1 WHERE NOT (a+17+(17) in ( -t1.a,13,coalesce((select max(e) from t1 where b+a-13<=b),e)) or e in (select abs( -+~abs(+(min(c))))+count(distinct b) from t1 union select abs(+((max(t1.c)) | min(t1.b))) from t1) and 13 not between f and 19 or not e not in ( -17,13,t1.a))} +} {17} +do_test randexpr-2.2583 { + db eval {SELECT case when not t1.e between 17 and a then 11+ -(select ~case count(distinct +13+t1.c | c*13)- -+ -cast(avg(c) AS integer)-min(19)+case -max(c) when -cast(avg(b) AS integer) then max(11) else max(13) end+count(distinct t1.f) when max(( -d)) then cast(avg(t1.c) AS integer) else (min((t1.b))) end | cast(avg(t1.f) AS integer)*count(distinct 17) from t1)+b else +t1.e | -t1.a-a end FROM t1 WHERE (t1.f<=~c+f)} +} {} +do_test randexpr-2.2584 { + db eval {SELECT case when not t1.e between 17 and a then 11+ -(select ~case count(distinct +13+t1.c | c*13)- -+ -cast(avg(c) AS integer)-min(19)+case -max(c) when -cast(avg(b) AS integer) then max(11) else max(13) end+count(distinct t1.f) when max(( -d)) then cast(avg(t1.c) AS integer) else (min((t1.b))) end | cast(avg(t1.f) AS integer)*count(distinct 17) from t1)+b else +t1.e | -t1.a-a end FROM t1 WHERE NOT ((t1.f<=~c+f))} +} {340} +do_test randexpr-2.2585 { + db eval {SELECT case when not t1.e between 17 and a then 11+ -(select ~case count(distinct +13+t1.c & c*13)- -+ -cast(avg(c) AS integer)-min(19)+case -max(c) when -cast(avg(b) AS integer) then max(11) else max(13) end+count(distinct t1.f) when max(( -d)) then cast(avg(t1.c) AS integer) else (min((t1.b))) end & cast(avg(t1.f) AS integer)*count(distinct 17) from t1)+b else +t1.e & -t1.a-a end FROM t1 WHERE NOT ((t1.f<=~c+f))} +} {-317} +do_test randexpr-2.2586 { + db eval {SELECT t1.f-coalesce((select max(case when b<>~t1.f then b+f else coalesce((select t1.c from t1 where case a when 19*t1.e+a then 19 else 13 end between 13 and a),t1.d)+b end) from t1 where (t1.c) in (select -~min(c) | max(t1.d) from t1 union select -cast(avg(t1.a) AS integer) from t1) and t1.c in (t1.a,d,11) or 1113 and not exists(select 1 from t1 where (((t1.d<=t1.b))))),e)*b*t1.f>t1.a or not exists(select 1 from t1 where (13) not in (11,t1.b,t1.c)) then c+d else t1.e end>=t1.f) or (not exists(select 1 from t1 where -11 in (c,t1.d, -a)) or a not between - - -(b) and b) or 13 between t1.b and f} +} {-200} +do_test randexpr-2.2587 { + db eval {SELECT t1.f-coalesce((select max(case when b<>~t1.f then b+f else coalesce((select t1.c from t1 where case a when 19*t1.e+a then 19 else 13 end between 13 and a),t1.d)+b end) from t1 where (t1.c) in (select -~min(c) | max(t1.d) from t1 union select -cast(avg(t1.a) AS integer) from t1) and t1.c in (t1.a,d,11) or 1113 and not exists(select 1 from t1 where (((t1.d<=t1.b))))),e)*b*t1.f>t1.a or not exists(select 1 from t1 where (13) not in (11,t1.b,t1.c)) then c+d else t1.e end>=t1.f) or (not exists(select 1 from t1 where -11 in (c,t1.d, -a)) or a not between - - -(b) and b) or 13 between t1.b and f)} +} {} +do_test randexpr-2.2588 { + db eval {SELECT t1.f-coalesce((select max(case when b<>~t1.f then b+f else coalesce((select t1.c from t1 where case a when 19*t1.e+a then 19 else 13 end between 13 and a),t1.d)+b end) from t1 where (t1.c) in (select -~min(c) & max(t1.d) from t1 union select -cast(avg(t1.a) AS integer) from t1) and t1.c in (t1.a,d,11) or 1113 and not exists(select 1 from t1 where (((t1.d<=t1.b))))),e)*b*t1.f>t1.a or not exists(select 1 from t1 where (13) not in (11,t1.b,t1.c)) then c+d else t1.e end>=t1.f) or (not exists(select 1 from t1 where -11 in (c,t1.d, -a)) or a not between - - -(b) and b) or 13 between t1.b and f} +} {-200} +do_test randexpr-2.2589 { + db eval {SELECT case when ( -c=~t1.b and coalesce((select max(coalesce((select b from t1 where t1.f between case when t1.e between t1.f and 19 then (t1.b) else t1.a end and t1.f),a)) from t1 where 11=t1.f),t1.f)+t1.c=d) and a>t1.c and 19> -19 and exists(select 1 from t1 where (b=17)) and 17 between 19 and 13 then 19*case (d) when c then b else a end when t1.d not in ( -t1.a,f,13) then -t1.f else (d) end FROM t1 WHERE 11*case when d | (abs(+t1.e-t1.e*b+(select case abs(count(*)) when count(*) then count(*) else cast(avg(t1.c) AS integer) end from t1)*17+(d)-13-11)/abs(c))-f- -t1.c-d | t1.a not between 19 and f then t1.a when t1.d in (select 11 from t1 union select d from t1) then e else e end-t1.c between 19 and c} +} {} +do_test randexpr-2.2590 { + db eval {SELECT case when ( -c=~t1.b and coalesce((select max(coalesce((select b from t1 where t1.f between case when t1.e between t1.f and 19 then (t1.b) else t1.a end and t1.f),a)) from t1 where 11=t1.f),t1.f)+t1.c=d) and a>t1.c and 19> -19 and exists(select 1 from t1 where (b=17)) and 17 between 19 and 13 then 19*case (d) when c then b else a end when t1.d not in ( -t1.a,f,13) then -t1.f else (d) end FROM t1 WHERE NOT (11*case when d | (abs(+t1.e-t1.e*b+(select case abs(count(*)) when count(*) then count(*) else cast(avg(t1.c) AS integer) end from t1)*17+(d)-13-11)/abs(c))-f- -t1.c-d | t1.a not between 19 and f then t1.a when t1.d in (select 11 from t1 union select d from t1) then e else e end-t1.c between 19 and c)} +} {-600} +do_test randexpr-2.2591 { + db eval {SELECT +case when t1.a-17 in (select cast(avg(t1.a*t1.d+(abs( -t1.e)/abs(case when t1.e>t1.a or a>t1.d then t1.f when 13<11 then t1.b else c end))*t1.d) AS integer) from t1 union select count(distinct t1.a) from t1) then t1.c when d in (select +count(distinct b)-case case - -cast(avg(d) AS integer) when case max(11) when min(17) then count(*) else (cast(avg(a) AS integer)) end then -count(*) else -cast(avg(17) AS integer) end when max(19) then count(distinct t1.f) else count(distinct -t1.d) end | min(e) from t1 union select count(*) from t1) then t1.d else t1.a end FROM t1 WHERE -+b>=19} +} {} +do_test randexpr-2.2592 { + db eval {SELECT +case when t1.a-17 in (select cast(avg(t1.a*t1.d+(abs( -t1.e)/abs(case when t1.e>t1.a or a>t1.d then t1.f when 13<11 then t1.b else c end))*t1.d) AS integer) from t1 union select count(distinct t1.a) from t1) then t1.c when d in (select +count(distinct b)-case case - -cast(avg(d) AS integer) when case max(11) when min(17) then count(*) else (cast(avg(a) AS integer)) end then -count(*) else -cast(avg(17) AS integer) end when max(19) then count(distinct t1.f) else count(distinct -t1.d) end | min(e) from t1 union select count(*) from t1) then t1.d else t1.a end FROM t1 WHERE NOT ( -+b>=19)} +} {100} +do_test randexpr-2.2593 { + db eval {SELECT +case when t1.a-17 in (select cast(avg(t1.a*t1.d+(abs( -t1.e)/abs(case when t1.e>t1.a or a>t1.d then t1.f when 13<11 then t1.b else c end))*t1.d) AS integer) from t1 union select count(distinct t1.a) from t1) then t1.c when d in (select +count(distinct b)-case case - -cast(avg(d) AS integer) when case max(11) when min(17) then count(*) else (cast(avg(a) AS integer)) end then -count(*) else -cast(avg(17) AS integer) end when max(19) then count(distinct t1.f) else count(distinct -t1.d) end & min(e) from t1 union select count(*) from t1) then t1.d else t1.a end FROM t1 WHERE NOT ( -+b>=19)} +} {100} +do_test randexpr-2.2594 { + db eval {SELECT case ~(t1.f)-t1.b-t1.e*c when coalesce((select case when d*13 | d=case when 19 between b+e+a | t1.f and a+11+t1.b*(t1.f) then d else b end then t1.c when e not between 13 and 13 then 19 else a end from t1 where 13=t1.b),c) then t1.c else b end FROM t1 WHERE not t1.d in (select cast(avg(t1.e) AS integer)-~~min(coalesce((select (abs(11)/abs(11+(select count(*)+min(17)+ -cast(avg(t1.d) AS integer) from t1)*13+coalesce((select max(b) from t1 where (t1.c)<>t1.e or e<(a)),13)-d*t1.c))*t1.b from t1 where 19<=e),c))++abs(count(distinct t1.b))+~max(11)*max(11) from t1 union select +max(11) from t1)} +} {200} +do_test randexpr-2.2595 { + db eval {SELECT case ~(t1.f)-t1.b-t1.e*c when coalesce((select case when d*13 | d=case when 19 between b+e+a | t1.f and a+11+t1.b*(t1.f) then d else b end then t1.c when e not between 13 and 13 then 19 else a end from t1 where 13=t1.b),c) then t1.c else b end FROM t1 WHERE NOT (not t1.d in (select cast(avg(t1.e) AS integer)-~~min(coalesce((select (abs(11)/abs(11+(select count(*)+min(17)+ -cast(avg(t1.d) AS integer) from t1)*13+coalesce((select max(b) from t1 where (t1.c)<>t1.e or e<(a)),13)-d*t1.c))*t1.b from t1 where 19<=e),c))++abs(count(distinct t1.b))+~max(11)*max(11) from t1 union select +max(11) from t1))} +} {} +do_test randexpr-2.2596 { + db eval {SELECT case ~(t1.f)-t1.b-t1.e*c when coalesce((select case when d*13 & d=case when 19 between b+e+a & t1.f and a+11+t1.b*(t1.f) then d else b end then t1.c when e not between 13 and 13 then 19 else a end from t1 where 13=t1.b),c) then t1.c else b end FROM t1 WHERE not t1.d in (select cast(avg(t1.e) AS integer)-~~min(coalesce((select (abs(11)/abs(11+(select count(*)+min(17)+ -cast(avg(t1.d) AS integer) from t1)*13+coalesce((select max(b) from t1 where (t1.c)<>t1.e or e<(a)),13)-d*t1.c))*t1.b from t1 where 19<=e),c))++abs(count(distinct t1.b))+~max(11)*max(11) from t1 union select +max(11) from t1)} +} {200} +do_test randexpr-2.2597 { + db eval {SELECT t1.d+(abs(11)/abs(e*~(select -+ -case min(t1.e) when count(distinct case when (exists(select 1 from t1 where (t1.d not in (19+11,t1.e,t1.c)))) then c*b-t1.a else -c end) then count(*)+case (cast(avg(a) AS integer))-count(distinct f) when -(count(*)) then count(distinct e) else max(t1.b) end- -count(distinct 17)* -min(t1.c) else count(distinct -19) end-count(distinct b) | cast(avg(19) AS integer) from t1)))-~t1.c FROM t1 WHERE c*coalesce((select e from t1 where case when exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select +b | 13 from t1 where ((17<(select (+~min(coalesce((select t1.c from t1 where case e when 13 then a else 11 end not in ( -b,t1.b,e)),(a)))) from t1)+d-19))),17) not between t1.b and t1.a)) then 11*d else t1.a end in (select c from t1 union select t1.e from t1)),t1.f) not between ( -d) and 13} +} {701} +do_test randexpr-2.2598 { + db eval {SELECT t1.d+(abs(11)/abs(e*~(select -+ -case min(t1.e) when count(distinct case when (exists(select 1 from t1 where (t1.d not in (19+11,t1.e,t1.c)))) then c*b-t1.a else -c end) then count(*)+case (cast(avg(a) AS integer))-count(distinct f) when -(count(*)) then count(distinct e) else max(t1.b) end- -count(distinct 17)* -min(t1.c) else count(distinct -19) end-count(distinct b) | cast(avg(19) AS integer) from t1)))-~t1.c FROM t1 WHERE NOT (c*coalesce((select e from t1 where case when exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select +b | 13 from t1 where ((17<(select (+~min(coalesce((select t1.c from t1 where case e when 13 then a else 11 end not in ( -b,t1.b,e)),(a)))) from t1)+d-19))),17) not between t1.b and t1.a)) then 11*d else t1.a end in (select c from t1 union select t1.e from t1)),t1.f) not between ( -d) and 13)} +} {} +do_test randexpr-2.2599 { + db eval {SELECT t1.d+(abs(11)/abs(e*~(select -+ -case min(t1.e) when count(distinct case when (exists(select 1 from t1 where (t1.d not in (19+11,t1.e,t1.c)))) then c*b-t1.a else -c end) then count(*)+case (cast(avg(a) AS integer))-count(distinct f) when -(count(*)) then count(distinct e) else max(t1.b) end- -count(distinct 17)* -min(t1.c) else count(distinct -19) end-count(distinct b) & cast(avg(19) AS integer) from t1)))-~t1.c FROM t1 WHERE c*coalesce((select e from t1 where case when exists(select 1 from t1 where not exists(select 1 from t1 where coalesce((select +b | 13 from t1 where ((17<(select (+~min(coalesce((select t1.c from t1 where case e when 13 then a else 11 end not in ( -b,t1.b,e)),(a)))) from t1)+d-19))),17) not between t1.b and t1.a)) then 11*d else t1.a end in (select c from t1 union select t1.e from t1)),t1.f) not between ( -d) and 13} +} {701} +finish_test diff --git a/components/external/SQLite-3.8.1/test/rdonly.test b/components/external/SQLite-3.8.1/test/rdonly.test new file mode 100644 index 0000000000000000000000000000000000000000..bf19597871ac4dc07dd9d21bb3746f6e9ca14447 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/rdonly.test @@ -0,0 +1,84 @@ +# 2007 April 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure SQLite treats a database +# as readonly if its write version is set to high. +# +# $Id: rdonly.test,v 1.2 2008/07/08 10:19:58 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# Create a database. +# +do_test rdonly-1.1 { + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + SELECT * FROM t1; + } +} {1} + +# Changes the write version from 1 to 3. Verify that the database +# can be read but not written. +# +do_test rdonly-1.2 { + db close + hexio_get_int [hexio_read test.db 18 1] +} 1 +do_test rdonly-1.3 { + hexio_write test.db 18 03 + sqlite3 db test.db + execsql { + SELECT * FROM t1; + } +} {1} +do_test rdonly-1.4 { + catchsql { + INSERT INTO t1 VALUES(2) + } +} {1 {attempt to write a readonly database}} + +# Change the write version back to 1. Verify that the database +# is read-write again. +# +do_test rdonly-1.5 { + db close + hexio_write test.db 18 01 + sqlite3 db test.db + catchsql { + INSERT INTO t1 VALUES(2); + SELECT * FROM t1; + } +} {0 {1 2}} + +# Now, after connection [db] has loaded the database schema, modify the +# write-version of the file (and the change-counter, so that the +# write-version is reloaded). This way, SQLite does not discover that +# the database is read-only until after it is locked. +# +set ro_version 02 +ifcapable wal { set ro_version 03 } +do_test rdonly-1.6 { + hexio_write test.db 18 $ro_version ; # write-version + hexio_write test.db 24 11223344 ; # change-counter + catchsql { + INSERT INTO t1 VALUES(2); + } +} {1 {attempt to write a readonly database}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/regexp1.test b/components/external/SQLite-3.8.1/test/regexp1.test new file mode 100644 index 0000000000000000000000000000000000000000..0e63cd98c800973e79fe1dffd668c5b0fd4fbef5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/regexp1.test @@ -0,0 +1,211 @@ +# 2012 December 31 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements test for the REGEXP operator in test_regexp.c. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test regexp1-1.1 { + load_static_extension db regexp + db eval { + CREATE TABLE t1(x INTEGER PRIMARY KEY, y TEXT); + INSERT INTO t1 VALUES(1, 'For since by man came death,'); + INSERT INTO t1 VALUES(2, 'by man came also the resurrection of the dead.'); + INSERT INTO t1 VALUES(3, 'For as in Adam all die,'); + INSERT INTO t1 VALUES(4, 'even so in Christ shall all be made alive.'); + + SELECT x FROM t1 WHERE y REGEXP '^For ' ORDER BY x; + } +} {1 3} + +do_execsql_test regexp1-1.2 { + SELECT x FROM t1 WHERE y REGEXP 'by|in' ORDER BY x; +} {1 2 3 4} +do_execsql_test regexp1-1.3 { + SELECT x FROM t1 WHERE y REGEXP 'by|Christ' ORDER BY x; +} {1 2 4} +do_execsql_test regexp1-1.4 { + SELECT x FROM t1 WHERE y REGEXP 'shal+ al+' ORDER BY x; +} {4} +do_execsql_test regexp1-1.5 { + SELECT x FROM t1 WHERE y REGEXP 'shall x*y*z*all' ORDER BY x; +} {4} +do_execsql_test regexp1-1.6 { + SELECT x FROM t1 WHERE y REGEXP 'shallx?y? ?z?all' ORDER BY x; +} {4} +do_execsql_test regexp1-1.7 { + SELECT x FROM t1 WHERE y REGEXP 'r{2}' ORDER BY x; +} {2} +do_execsql_test regexp1-1.8 { + SELECT x FROM t1 WHERE y REGEXP 'r{3}' ORDER BY x; +} {} +do_execsql_test regexp1-1.9 { + SELECT x FROM t1 WHERE y REGEXP 'r{1}' ORDER BY x; +} {1 2 3 4} +do_execsql_test regexp1-1.10 { + SELECT x FROM t1 WHERE y REGEXP 'ur{2,10}e' ORDER BY x; +} {2} +do_execsql_test regexp1-1.11 { + SELECT x FROM t1 WHERE y REGEXP '[Aa]dam' ORDER BY x; +} {3} +do_execsql_test regexp1-1.12 { + SELECT x FROM t1 WHERE y REGEXP '[^Aa]dam' ORDER BY x; +} {} +do_execsql_test regexp1-1.13 { + SELECT x FROM t1 WHERE y REGEXP '[^b-zB-Z]dam' ORDER BY x; +} {3} +do_execsql_test regexp1-1.14 { + SELECT x FROM t1 WHERE y REGEXP 'alive' ORDER BY x; +} {4} +do_execsql_test regexp1-1.15 { + SELECT x FROM t1 WHERE y REGEXP '^alive' ORDER BY x; +} {} +do_execsql_test regexp1-1.16 { + SELECT x FROM t1 WHERE y REGEXP 'alive$' ORDER BY x; +} {} +do_execsql_test regexp1-1.17 { + SELECT x FROM t1 WHERE y REGEXP 'alive.$' ORDER BY x; +} {4} +do_execsql_test regexp1-1.18 { + SELECT x FROM t1 WHERE y REGEXP 'alive\.$' ORDER BY x; +} {4} +do_execsql_test regexp1-1.19 { + SELECT x FROM t1 WHERE y REGEXP 'ma[nd]' ORDER BY x; +} {1 2 4} +do_execsql_test regexp1-1.20 { + SELECT x FROM t1 WHERE y REGEXP '\bma[nd]' ORDER BY x; +} {1 2 4} +do_execsql_test regexp1-1.21 { + SELECT x FROM t1 WHERE y REGEXP 'ma[nd]\b' ORDER BY x; +} {1 2} +do_execsql_test regexp1-1.22 { + SELECT x FROM t1 WHERE y REGEXP 'ma\w' ORDER BY x; +} {1 2 4} +do_execsql_test regexp1-1.23 { + SELECT x FROM t1 WHERE y REGEXP 'ma\W' ORDER BY x; +} {} +do_execsql_test regexp1-1.24 { + SELECT x FROM t1 WHERE y REGEXP '\sma\w' ORDER BY x; +} {1 2 4} +do_execsql_test regexp1-1.25 { + SELECT x FROM t1 WHERE y REGEXP '\Sma\w' ORDER BY x; +} {} +do_execsql_test regexp1-1.26 { + SELECT x FROM t1 WHERE y REGEXP 'alive\S$' ORDER BY x; +} {4} +do_execsql_test regexp1-1.27 { + SELECT x FROM t1 WHERE y REGEXP + '\b(unto|us|son|given|his|name|called|' || + 'wonderful|councelor|mighty|god|everlasting|father|' || + 'prince|peace|alive)\b'; +} {4} + +do_execsql_test regexp1-2.1 { + SELECT 'aaaabbbbcccc' REGEXP 'ab*c', + 'aaaacccc' REGEXP 'ab*c'; +} {1 1} +do_execsql_test regexp1-2.2 { + SELECT 'aaaabbbbcccc' REGEXP 'ab+c', + 'aaaacccc' REGEXP 'ab+c'; +} {1 0} +do_execsql_test regexp1-2.3 { + SELECT 'aaaabbbbcccc' REGEXP 'ab?c', + 'aaaacccc' REGEXP 'ab?c'; +} {0 1} +do_execsql_test regexp1-2.4 { + SELECT 'aaaabbbbbbcccc' REGEXP 'ab{3,5}c', + 'aaaabbbbbcccc' REGEXP 'ab{3,5}c', + 'aaaabbbbcccc' REGEXP 'ab{3,5}c', + 'aaaabbbcccc' REGEXP 'ab{3,5}c', + 'aaaabbcccc' REGEXP 'ab{3,5}c', + 'aaaabcccc' REGEXP 'ab{3,5}c' +} {0 1 1 1 0 0} +do_execsql_test regexp1-2.5 { + SELECT 'aaaabbbbcccc' REGEXP 'a(a|b|c)+c', + 'aaaabbbbcccc' REGEXP '^a(a|b|c){11}c$', + 'aaaabbbbcccc' REGEXP '^a(a|b|c){10}c$', + 'aaaabbbbcccc' REGEXP '^a(a|b|c){9}c$' +} {1 0 1 0} +do_execsql_test regexp1-2.6 { + SELECT 'aaaabbbbcccc' REGEXP '^a(a|bb|c)+c$', + 'aaaabbbbcccc' REGEXP '^a(a|bbb|c)+c$', + 'aaaabbbbcccc' REGEXP '^a(a|bbbb|c)+c$' +} {1 0 1} +do_execsql_test regexp1-2.7 { + SELECT 'aaaabbbbcccc' REGEXP '^a([ac]+|bb){3}c$', + 'aaaabbbbcccc' REGEXP '^a([ac]+|bb){4}c$', + 'aaaabbbbcccc' REGEXP '^a([ac]+|bb){5}c$' +} {0 1 1} + +do_execsql_test regexp1-2.8 { + SELECT 'abc*def+ghi.jkl[mno]pqr' REGEXP 'c.d', + 'abc*def+ghi.jkl[mno]pqr' REGEXP 'c\*d', + 'abc*def+ghi.jkl[mno]pqr' REGEXP 'f\+g', + 'abc*def+ghi.jkl[mno]pqr' REGEXP 'i\.j', + 'abc*def+ghi.jkl[mno]pqr' REGEXP 'l\[mno\]p' +} {1 1 1 1 1} + +do_test regexp1-2.9 { + set v1 "abc\ndef" + db eval {SELECT $v1 REGEXP '^abc\ndef$'} +} {1} +do_test regexp1-2.10 { + set v1 "abc\adef" + db eval {SELECT $v1 REGEXP '^abc\adef$'} +} {1} +do_test regexp1-2.11 { + set v1 "abc\tdef" + db eval {SELECT $v1 REGEXP '^abc\tdef$'} +} {1} +do_test regexp1-2.12 { + set v1 "abc\rdef" + db eval {SELECT $v1 REGEXP '^abc\rdef$'} +} {1} +do_test regexp1-2.13 { + set v1 "abc\fdef" + db eval {SELECT $v1 REGEXP '^abc\fdef$'} +} {1} +do_test regexp1-2.14 { + set v1 "abc\vdef" + db eval {SELECT $v1 REGEXP '^abc\vdef$'} +} {1} +do_execsql_test regexp1-2.15 { + SELECT 'abc\def' REGEXP '^abc\\def', + 'abc(def' REGEXP '^abc\(def', + 'abc)def' REGEXP '^abc\)def', + 'abc*def' REGEXP '^abc\*def', + 'abc.def' REGEXP '^abc\.def', + 'abc+def' REGEXP '^abc\+def', + 'abc?def' REGEXP '^abc\?def', + 'abc[def' REGEXP '^abc\[def', + 'abc$def' REGEXP '^abc\$', + '^def' REGEXP '\^def', + 'abc{4}x' REGEXP '^abc\{4\}x$', + 'abc|def' REGEXP '^abc\|def$' +} {1 1 1 1 1 1 1 1 1 1 1 1} + +do_execsql_test regexp1-2.20 { + SELECT 'abc$¢€xyz' REGEXP '^abc\u0024\u00a2\u20acxyz$', + 'abc$¢€xyz' REGEXP '^abc\u0024\u00A2\u20ACxyz$', + 'abc$¢€xyz' REGEXP '^abc\x24\xa2\u20acxyz$' +} {1 1 1} +do_execsql_test regexp1-2.21 { + SELECT 'abc$¢€xyz' REGEXP '^abc[\u0024][\u00a2][\u20ac]xyz$', + 'abc$¢€xyz' REGEXP '^abc[\u0024\u00A2\u20AC]{3}xyz$', + 'abc$¢€xyz' REGEXP '^abc[\x24][\xa2\u20ac]+xyz$' +} {1 1 1} +do_execsql_test regexp1-2.22 { + SELECT 'abc$¢€xyz' REGEXP '^abc[^\u0025-X][^ -\u007f][^\u20ab]xyz$' +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/reindex.test b/components/external/SQLite-3.8.1/test/reindex.test new file mode 100644 index 0000000000000000000000000000000000000000..9d5ecd9ee285f4b878fd887c472bf3a550ecd958 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/reindex.test @@ -0,0 +1,171 @@ +# 2004 November 5 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# This file implements tests for the REINDEX command. +# +# $Id: reindex.test,v 1.4 2008/07/12 14:52:20 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# There is nothing to test if REINDEX is disable for this build. +# +ifcapable {!reindex} { + finish_test + return +} + +# Basic sanity checks. +# +do_test reindex-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + CREATE INDEX i1 ON t1(a); + REINDEX; + } +} {} +integrity_check reindex-1.2 +do_test reindex-1.3 { + execsql { + REINDEX t1; + } +} {} +integrity_check reindex-1.4 +do_test reindex-1.5 { + execsql { + REINDEX i1; + } +} {} +integrity_check reindex-1.6 +do_test reindex-1.7 { + execsql { + REINDEX main.t1; + } +} {} +do_test reindex-1.8 { + execsql { + REINDEX main.i1; + } +} {} +do_test reindex-1.9 { + catchsql { + REINDEX bogus + } +} {1 {unable to identify the object to be reindexed}} + +# Set up a table for testing that includes several different collating +# sequences including some that we can modify. +# +do_test reindex-2.1 { + proc c1 {a b} { + return [expr {-[string compare $a $b]}] + } + proc c2 {a b} { + return [expr {-[string compare [string tolower $a] [string tolower $b]]}] + } + db collate c1 c1 + db collate c2 c2 + execsql { + CREATE TABLE t2( + a TEXT PRIMARY KEY COLLATE c1, + b TEXT UNIQUE COLLATE c2, + c TEXT COLLATE nocase, + d TEST COLLATE binary + ); + INSERT INTO t2 VALUES('abc','abc','abc','abc'); + INSERT INTO t2 VALUES('ABCD','ABCD','ABCD','ABCD'); + INSERT INTO t2 VALUES('bcd','bcd','bcd','bcd'); + INSERT INTO t2 VALUES('BCDE','BCDE','BCDE','BCDE'); + SELECT a FROM t2 ORDER BY a; + } +} {bcd abc BCDE ABCD} +do_test reindex-2.2 { + execsql { + SELECT b FROM t2 ORDER BY b; + } +} {BCDE bcd ABCD abc} +do_test reindex-2.3 { + execsql { + SELECT c FROM t2 ORDER BY c; + } +} {abc ABCD bcd BCDE} +do_test reindex-2.4 { + execsql { + SELECT d FROM t2 ORDER BY d; + } +} {ABCD BCDE abc bcd} + +# Change a collating sequence function. Verify that REINDEX rebuilds +# the index. +# +do_test reindex-2.5 { + proc c1 {a b} { + return [string compare $a $b] + } + execsql { + SELECT a FROM t2 ORDER BY a; + } +} {bcd abc BCDE ABCD} +ifcapable {integrityck} { + do_test reindex-2.5.1 { + string equal ok [execsql {PRAGMA integrity_check}] + } {0} +} +do_test reindex-2.6 { + execsql { + REINDEX c2; + SELECT a FROM t2 ORDER BY a; + } +} {bcd abc BCDE ABCD} +do_test reindex-2.7 { + execsql { + REINDEX t1; + SELECT a FROM t2 ORDER BY a; + } +} {bcd abc BCDE ABCD} +do_test reindex-2.8 { + execsql { + REINDEX c1; + SELECT a FROM t2 ORDER BY a; + } +} {ABCD BCDE abc bcd} +integrity_check reindex-2.8.1 + +# Try to REINDEX an index for which the collation sequence is not available. +# +do_test reindex-3.1 { + sqlite3 db2 test.db + catchsql { + REINDEX c1; + } db2 +} {1 {no such collation sequence: c1}} +do_test reindex-3.2 { + proc need_collate {collation} { + db2 collate c1 c1 + } + db2 collation_needed need_collate + catchsql { + REINDEX c1; + } db2 +} {0 {}} +do_test reindex-3.3 { + catchsql { + REINDEX; + } db2 +} {1 {no such collation sequence: c2}} + +do_test reindex-3.99 { + db2 close +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/releasetest.mk b/components/external/SQLite-3.8.1/test/releasetest.mk new file mode 100644 index 0000000000000000000000000000000000000000..5d217c645b59c9f999d4ecd19ad5d5700f6d87ef --- /dev/null +++ b/components/external/SQLite-3.8.1/test/releasetest.mk @@ -0,0 +1,14 @@ +######################################################## +TOP=/home/drh/sqlite/sqlite + +TCL_FLAGS=-I/home/drh/tcltk/86linux +LIBTCL=/home/drh/tcltk/86linux/libtcl8.6.a -lm -ldl -lpthread + +BCC = gcc +TCC = gcc -ansi -g $(CFLAGS) +NAWK = awk +AR = ar cr +RANLIB = ranlib +THREADLIB = -lpthread -ldl -lz +include $(TOP)/main.mk +######################################################## diff --git a/components/external/SQLite-3.8.1/test/releasetest.tcl b/components/external/SQLite-3.8.1/test/releasetest.tcl new file mode 100644 index 0000000000000000000000000000000000000000..b635061c55415825b910664ad83844b5f6f98a4b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/releasetest.tcl @@ -0,0 +1,366 @@ + +set rcsid {$Id: $} + +# Documentation for this script. This may be output to stderr +# if the script is invoked incorrectly. See the [process_options] +# proc below. +# +set ::USAGE_MESSAGE { +This Tcl script is used to test the various configurations required +before releasing a new version. Supported command line options (all +optional) are: + + -makefile PATH-TO-MAKEFILE (default "releasetest.mk") + -platform PLATFORM (see below) + -quick BOOLEAN (default "0") + +The default value for -makefile is "./releasetest.mk". + +The script determines the default value for -platform using the +$tcl_platform(os) and $tcl_platform(machine) variables. Supported +platforms are "Linux-x86", "Linux-x86_64" and "Darwin-i386". + +If the -quick option is set to true, then the "veryquick.test" script +is run for all compilation configurations. Otherwise, sometimes "all.test" +is run, sometimes "veryquick.test". + +Almost any SQLite makefile (except those generated by configure - see below) +should work. The following properties are required: + + * The makefile should support the "fulltest" target. + * The makefile should support the variable "OPTS" as a way to pass + options from the make command line to lemon and the C compiler. + +More precisely, the following invocation must be supported: + + make -f $::MAKEFILE fulltest OPTS="-DSQLITE_SECURE_DELETE=1 -DSQLITE_DEBUG=1" + +Makefiles generated by the sqlite configure program cannot be used as +they do not respect the OPTS variable. + +Example Makefile contents: + + ######################################################## + TOP=/home/dan/work/sqlite/sqlite + + TCL_FLAGS=-I/home/dan/tcl/include + LIBTCL=-L/home/dan/tcl/lib -ltcl + + BCC = gcc + TCC = gcc -ansi -g $(CFLAGS) + NAWK = awk + AR = ar cr + RANLIB = ranlib + THREADLIB = -lpthread -ldl + include $(TOP)/main.mk + ######################################################## +} + +array set ::Configs { + "Default" { + -O2 + } + "Ftrapv" { + -O2 -ftrapv + -DSQLITE_MAX_ATTACHED=55 + -DSQLITE_TCL_DEFAULT_FULLMUTEX=1 + } + "Unlock-Notify" { + -O2 + -DSQLITE_ENABLE_UNLOCK_NOTIFY + -DSQLITE_THREADSAFE + -DSQLITE_TCL_DEFAULT_FULLMUTEX=1 + } + "Secure-Delete" { + -O2 + -DSQLITE_SECURE_DELETE=1 + -DSQLITE_SOUNDEX=1 + } + "Update-Delete-Limit" { + -O2 + -DSQLITE_DEFAULT_FILE_FORMAT=4 + -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT=1 + } + "Check-Symbols" { + -DSQLITE_MEMDEBUG=1 + -DSQLITE_ENABLE_FTS3_PARENTHESIS=1 + -DSQLITE_ENABLE_FTS3=1 + -DSQLITE_ENABLE_RTREE=1 + -DSQLITE_ENABLE_MEMSYS5=1 + -DSQLITE_ENABLE_MEMSYS3=1 + -DSQLITE_ENABLE_COLUMN_METADATA=1 + -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT=1 + -DSQLITE_SECURE_DELETE=1 + -DSQLITE_SOUNDEX=1 + -DSQLITE_ENABLE_ATOMIC_WRITE=1 + -DSQLITE_ENABLE_IOTRACE=1 + -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 + -DSQLITE_ENABLE_OVERSIZE_CELL_CHECK=1 + } + "Debug-One" { + -O2 + -DSQLITE_DEBUG=1 + -DSQLITE_MEMDEBUG=1 + -DSQLITE_MUTEX_NOOP=1 + -DSQLITE_TCL_DEFAULT_FULLMUTEX=1 + -DSQLITE_ENABLE_FTS3=1 + -DSQLITE_ENABLE_RTREE=1 + -DSQLITE_ENABLE_MEMSYS5=1 + -DSQLITE_ENABLE_MEMSYS3=1 + -DSQLITE_ENABLE_COLUMN_METADATA=1 + } + "Device-One" { + -O2 + -DSQLITE_DEBUG=1 + -DSQLITE_DEFAULT_AUTOVACUUM=1 + -DSQLITE_DEFAULT_CACHE_SIZE=64 + -DSQLITE_DEFAULT_PAGE_SIZE=1024 + -DSQLITE_DEFAULT_TEMP_CACHE_SIZE=32 + -DSQLITE_DISABLE_LFS=1 + -DSQLITE_ENABLE_ATOMIC_WRITE=1 + -DSQLITE_ENABLE_IOTRACE=1 + -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 + -DSQLITE_MAX_PAGE_SIZE=4096 + -DSQLITE_OMIT_LOAD_EXTENSION=1 + -DSQLITE_OMIT_PROGRESS_CALLBACK=1 + -DSQLITE_OMIT_VIRTUALTABLE=1 + -DSQLITE_TEMP_STORE=3 + } + "Device-Two" { + -DSQLITE_4_BYTE_ALIGNED_MALLOC=1 + -DSQLITE_DEFAULT_AUTOVACUUM=1 + -DSQLITE_DEFAULT_CACHE_SIZE=1000 + -DSQLITE_DEFAULT_LOCKING_MODE=0 + -DSQLITE_DEFAULT_PAGE_SIZE=1024 + -DSQLITE_DEFAULT_TEMP_CACHE_SIZE=1000 + -DSQLITE_DISABLE_LFS=1 + -DSQLITE_ENABLE_FTS3=1 + -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 + -DSQLITE_ENABLE_RTREE=1 + -DSQLITE_MAX_COMPOUND_SELECT=50 + -DSQLITE_MAX_PAGE_SIZE=32768 + -DSQLITE_OMIT_TRACE=1 + -DSQLITE_TEMP_STORE=3 + -DSQLITE_THREADSAFE=2 + } + "Locking-Style" { + -O2 + -DSQLITE_ENABLE_LOCKING_STYLE=1 + } + "OS-X" { + -DSQLITE_OMIT_LOAD_EXTENSION=1 + -DSQLITE_DEFAULT_MEMSTATUS=0 + -DSQLITE_THREADSAFE=2 + -DSQLITE_OS_UNIX=1 + -DSQLITE_ENABLE_LOCKING_STYLE=1 + -DUSE_PREAD=1 + -DSQLITE_ENABLE_RTREE=1 + -DSQLITE_ENABLE_FTS3=1 + -DSQLITE_ENABLE_FTS3_PARENTHESIS=1 + -DSQLITE_DEFAULT_CACHE_SIZE=1000 + -DSQLITE_MAX_LENGTH=2147483645 + -DSQLITE_MAX_VARIABLE_NUMBER=500000 + -DSQLITE_DEBUG=1 + -DSQLITE_PREFER_PROXY_LOCKING=1 + } + "Extra-Robustness" { + -DSQLITE_ENABLE_OVERSIZE_CELL_CHECK=1 + -DSQLITE_MAX_ATTACHED=62 + } + "Devkit" { + -DSQLITE_DEFAULT_FILE_FORMAT=4 + -DSQLITE_MAX_ATTACHED=30 + -DSQLITE_ENABLE_COLUMN_METADATA + -DSQLITE_ENABLE_FTS4 + -DSQLITE_ENABLE_FTS4_PARENTHESIS + -DSQLITE_DISABLE_FTS4_DEFERRED + -DSQLITE_ENABLE_RTREE + } +} + +array set ::Platforms { + Linux-x86_64 { + "Check-Symbols" checksymbols + "Debug-One" test + "Secure-Delete" test + "Unlock-Notify" "QUICKTEST_INCLUDE=notify2.test test" + "Update-Delete-Limit" test + "Extra-Robustness" test + "Device-Two" test + "Ftrapv" test + "Default" "threadtest test" + "Device-One" fulltest + } + Linux-i686 { + "Devkit" test + "Unlock-Notify" "QUICKTEST_INCLUDE=notify2.test test" + "Device-One" test + "Device-Two" test + "Default" "threadtest fulltest" + } + Darwin-i386 { + "Locking-Style" test + "OS-X" "threadtest fulltest" + } +} + + +# End of configuration section. +######################################################################### +######################################################################### + +foreach {key value} [array get ::Platforms] { + foreach {v t} $value { + if {0==[info exists ::Configs($v)]} { + puts stderr "No such configuration: \"$v\"" + exit -1 + } + } +} + +proc run_test_suite {name testtarget config} { + + # Tcl variable $opts is used to build up the value used to set the + # OPTS Makefile variable. Variable $cflags holds the value for + # CFLAGS. The makefile will pass OPTS to both gcc and lemon, but + # CFLAGS is only passed to gcc. + # + set cflags "" + set opts "" + foreach arg $config { + if {[string match -D* $arg]} { + lappend opts $arg + } else { + lappend cflags $arg + } + } + + set cflags [join $cflags " "] + set opts [join $opts " "] + append opts " -DSQLITE_NO_SYNC=1 -DHAVE_USLEEP" + + # Set the sub-directory to use. + # + set dir [string tolower [string map {- _ " " _} $name]] + + if {$::tcl_platform(platform)=="windows"} { + append opts " -DSQLITE_OS_WIN=1" + } else { + append opts " -DSQLITE_OS_UNIX=1" + } + + # Run the test. + # + set makefile [file normalize $::MAKEFILE] + file mkdir $dir + puts -nonewline "Testing configuration \"$name\" (logfile=$dir/test.log)..." + flush stdout + + set makecmd [concat \ + [list exec make -C $dir -f $makefile clean] \ + $testtarget \ + [list CFLAGS=$cflags OPTS=$opts >& $dir/test.log] \ + ] + + set tm1 [clock seconds] + set rc [catch $makecmd] + set tm2 [clock seconds] + + set minutes [expr {($tm2-$tm1)/60}] + set seconds [expr {($tm2-$tm1)%60}] + puts -nonewline [format " (%d:%.2d) " $minutes $seconds] + if {$rc} { + puts "FAILED." + } else { + puts "Ok." + } +} + + +# This proc processes the command line options passed to this script. +# Currently the only option supported is "-makefile", default +# "releasetest.mk". Set the ::MAKEFILE variable to the value of this +# option. +# +proc process_options {argv} { + set ::MAKEFILE releasetest.mk ;# Default value + set ::QUICK 0 ;# Default value + set platform $::tcl_platform(os)-$::tcl_platform(machine) + + for {set i 0} {$i < [llength $argv]} {incr i} { + switch -- [lindex $argv $i] { + -makefile { + incr i + set ::MAKEFILE [lindex $argv $i] + } + + -platform { + incr i + set platform [lindex $argv $i] + } + + -quick { + incr i + set ::QUICK [lindex $argv $i] + } + + default { + puts stderr "" + puts stderr [string trim $::USAGE_MESSAGE] + exit -1 + } + } + } + + set ::MAKEFILE [file normalize $::MAKEFILE] + + if {0==[info exists ::Platforms($platform)]} { + puts "Unknown platform: $platform" + puts -nonewline "Set the -platform option to " + set print [list] + foreach p [array names ::Platforms] { + lappend print "\"$p\"" + } + lset print end "or [lindex $print end]" + puts "[join $print {, }]." + exit + } + + set ::CONFIGLIST $::Platforms($platform) + puts "Running the following configurations for $platform:" + puts " [string trim $::CONFIGLIST]" +} + +# Main routine. +# +proc main {argv} { + + # Process any command line options. + process_options $argv + + foreach {zConfig target} $::CONFIGLIST { + if {$::QUICK} {set target test} + set config_options $::Configs($zConfig) + + run_test_suite $zConfig $target $config_options + + # If the configuration included the SQLITE_DEBUG option, then remove + # it and run veryquick.test. If it did not include the SQLITE_DEBUG option + # add it and run veryquick.test. + if {$target!="checksymbols"} { + set debug_idx [lsearch -glob $config_options -DSQLITE_DEBUG*] + if {$debug_idx < 0} { + run_test_suite "${zConfig}_debug" test [ + concat $config_options -DSQLITE_DEBUG=1 + ] + } else { + run_test_suite "${zConfig}_ndebug" test [ + lreplace $config_options $debug_idx $debug_idx + ] + } + } + + } +} + +main $argv diff --git a/components/external/SQLite-3.8.1/test/resolver01.test b/components/external/SQLite-3.8.1/test/resolver01.test new file mode 100644 index 0000000000000000000000000000000000000000..7d95a2132a3240c791eeac125a5b4619d04de264 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/resolver01.test @@ -0,0 +1,208 @@ +# 2013-04-13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests features of the name resolver (the component that +# figures out what identifiers in the SQL statement refer to) that +# were fixed by ticket [2500cdb9be] +# +# See also tickets [1c69be2daf] and [f617ea3125] from 2013-08-14. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# "ORDER BY y" binds to the output result-set column named "y" +# if available. If no output column is named "y", then try to +# bind against an input column named "y". +# +# This is classical SQL92 behavior. +# +do_test resolver01-1.1 { + catchsql { + CREATE TABLE t1(x, y); INSERT INTO t1 VALUES(11,22); + CREATE TABLE t2(y, z); INSERT INTO t2 VALUES(33,44); + SELECT 1 AS y FROM t1, t2 ORDER BY y; + } +} {0 1} +do_test resolver01-1.2 { + catchsql { + SELECT 1 AS yy FROM t1, t2 ORDER BY y; + } +} {1 {ambiguous column name: y}} +do_test resolver01-1.3 { + catchsql { + CREATE TABLE t3(x,y); INSERT INTO t3 VALUES(11,44),(33,22); + SELECT x AS y FROM t3 ORDER BY y; + } +} {0 {11 33}} +do_test resolver01-1.4 { + catchsql { + SELECT x AS yy FROM t3 ORDER BY y; + } +} {0 {33 11}} + +# SQLite allows the WHERE clause to reference output columns if there is +# no other way to resolve the name. +# +do_test resolver01-1.5 { + catchsql { + SELECT x AS yy FROM t3 ORDER BY yy; + } +} {0 {11 33}} +do_test resolver01-1.6 { + catchsql { + SELECT x AS yy FROM t3 ORDER BY 1; + } +} {0 {11 33}} + +# The "ORDER BY y COLLATE nocase" form works the same as "ORDER BY y". +# The "y" binds more tightly to output columns than to input columns. +# +# This is for compatibility with SQL92 and with historical SQLite behavior. +# Note that PostgreSQL considers "y COLLATE nocase" to be an expression +# and thus PostgreSQL treats this case as if it where the 3.x case below. +# +do_test resolver01-2.1 { + catchsql { + SELECT 2 AS y FROM t1, t2 ORDER BY y COLLATE nocase; + } +} {0 2} +do_test resolver01-2.2 { + catchsql { + SELECT 2 AS yy FROM t1, t2 ORDER BY y COLLATE nocase; + } +} {1 {ambiguous column name: y}} +do_test resolver01-2.3 { + catchsql { + SELECT x AS y FROM t3 ORDER BY y COLLATE nocase; + } +} {0 {11 33}} +do_test resolver01-2.4 { + catchsql { + SELECT x AS yy FROM t3 ORDER BY y COLLATE nocase; + } +} {0 {33 11}} +do_test resolver01-2.5 { + catchsql { + SELECT x AS yy FROM t3 ORDER BY yy COLLATE nocase; + } +} {0 {11 33}} +do_test resolver01-2.6 { + catchsql { + SELECT x AS yy FROM t3 ORDER BY 1 COLLATE nocase; + } +} {0 {11 33}} + +# But if the form is "ORDER BY expr" then bind more tightly to the +# the input column names and only use the output column names if no +# input column name matches. +# +# This is SQL99 behavior, as implemented by PostgreSQL and MS-SQL. +# Note that Oracle works differently. +# +do_test resolver01-3.1 { + catchsql { + SELECT 3 AS y FROM t1, t2 ORDER BY +y; + } +} {1 {ambiguous column name: y}} +do_test resolver01-3.2 { + catchsql { + SELECT 2 AS yy FROM t1, t2 ORDER BY +y; + } +} {1 {ambiguous column name: y}} +do_test resolver01-3.3 { + catchsql { + SELECT x AS y FROM t3 ORDER BY +y; + } +} {0 {33 11}} +do_test resolver01-3.4 { + catchsql { + SELECT x AS yy FROM t3 ORDER BY +y; + } +} {0 {33 11}} +do_test resolver01-3.5 { + catchsql { + SELECT x AS yy FROM t3 ORDER BY +yy + } +} {0 {11 33}} + +# This is the test case given in ticket [f617ea3125e9] (with table name +# changed from "t1" to "t4". The behavior of (1) and (3) match with +# PostgreSQL, but we intentionally break with PostgreSQL to provide +# SQL92 behavior for case (2). +# +do_execsql_test resolver01-4.1 { + CREATE TABLE t4(m CHAR(2)); + INSERT INTO t4 VALUES('az'); + INSERT INTO t4 VALUES('by'); + INSERT INTO t4 VALUES('cx'); + SELECT '1', substr(m,2) AS m FROM t4 ORDER BY m; + SELECT '2', substr(m,2) AS m FROM t4 ORDER BY m COLLATE binary; + SELECT '3', substr(m,2) AS m FROM t4 ORDER BY lower(m); +} {1 x 1 y 1 z 2 x 2 y 2 z 3 z 3 y 3 x} + +########################################################################## +# Test cases for ticket [1c69be2dafc28]: Make sure the GROUP BY binds +# more tightly to the input tables in all cases. +# +# This first case case has been wrong in SQLite for time out of mind. +# For SQLite version 3.7.17 the answer was two rows, which is wrong. +# +do_execsql_test resolver01-5.1 { + CREATE TABLE t5(m CHAR(2)); + INSERT INTO t5 VALUES('ax'); + INSERT INTO t5 VALUES('bx'); + INSERT INTO t5 VALUES('cy'); + SELECT count(*), substr(m,2,1) AS m FROM t5 GROUP BY m ORDER BY 1, 2; +} {1 x 1 x 1 y} + +# This case is unambiguous and has always been correct. +# +do_execsql_test resolver01-5.2 { + SELECT count(*), substr(m,2,1) AS mx FROM t5 GROUP BY m ORDER BY 1, 2; +} {1 x 1 x 1 y} + +# This case is not allowed in standard SQL, but SQLite allows and does +# the sensible thing. +# +do_execsql_test resolver01-5.3 { + SELECT count(*), substr(m,2,1) AS mx FROM t5 GROUP BY mx ORDER BY 1, 2; +} {1 y 2 x} +do_execsql_test resolver01-5.4 { + SELECT count(*), substr(m,2,1) AS mx FROM t5 + GROUP BY substr(m,2,1) ORDER BY 1, 2; +} {1 y 2 x} + +# These test case weere provided in the 2013-08-14 email from Rob Golsteijn +# that originally reported the problem of ticket [1c69be2dafc28]. +# +do_execsql_test resolver01-6.1 { + CREATE TABLE t61(name); + SELECT min(name) FROM t61 GROUP BY lower(name); +} {} +do_execsql_test resolver01-6.2 { + SELECT min(name) AS name FROM t61 GROUP BY lower(name); +} {} +do_execsql_test resolver01-6.3 { + CREATE TABLE t63(name); + INSERT INTO t63 VALUES (NULL); + INSERT INTO t63 VALUES ('abc'); + SELECT count(), + NULLIF(name,'abc') AS name + FROM t63 + GROUP BY lower(name); +} {1 {} 1 {}} + + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/rollback.test b/components/external/SQLite-3.8.1/test/rollback.test new file mode 100644 index 0000000000000000000000000000000000000000..fc123ab9389dfca7e58685514006179d4b7588c5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/rollback.test @@ -0,0 +1,150 @@ +# 2004 June 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is verifying that a rollback in one statement +# caused by an ON CONFLICT ROLLBACK clause aborts any other pending +# statements. +# +# $Id: rollback.test,v 1.11 2009/06/26 07:12:07 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set DB [sqlite3_connection_pointer db] + +do_test rollback-1.1 { + execsql { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + SELECT * FROM t1; + } +} {1 2 3 4} + +ifcapable conflict { + do_test rollback-1.2 { + execsql { + CREATE TABLE t3(a unique on conflict rollback); + INSERT INTO t3 SELECT a FROM t1; + BEGIN; + INSERT INTO t1 SELECT * FROM t1; + } + } {} +} +do_test rollback-1.3 { + set STMT [sqlite3_prepare $DB "SELECT a FROM t1" -1 TAIL] + sqlite3_step $STMT +} {SQLITE_ROW} + +ifcapable conflict { + # This causes a ROLLBACK, which deletes the table out from underneath the + # SELECT statement. + # + do_test rollback-1.4 { + catchsql { + INSERT INTO t3 SELECT a FROM t1; + } + } {1 {column a is not unique}} + + # Try to continue with the SELECT statement + # + do_test rollback-1.5 { + sqlite3_step $STMT + } {SQLITE_ERROR} + + # Restart the SELECT statement + # + do_test rollback-1.6 { sqlite3_reset $STMT } {SQLITE_ABORT} +} else { + do_test rollback-1.6 { sqlite3_reset $STMT } {SQLITE_OK} +} + +do_test rollback-1.7 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test rollback-1.8 { + sqlite3_step $STMT +} {SQLITE_ROW} +do_test rollback-1.9 { + sqlite3_finalize $STMT +} {SQLITE_OK} + +if {$tcl_platform(platform) == "unix" + && [permutation] ne "onefile" + && [permutation] ne "inmemory_journal" +} { + do_test rollback-2.1 { + execsql { + BEGIN; + INSERT INTO t3 VALUES('hello world'); + } + forcecopy test.db testA.db + forcecopy test.db-journal testA.db-journal + execsql { + COMMIT; + } + } {} + + # At this point files testA.db and testA.db-journal are present in the + # file system. This block adds a master-journal file pointer to the + # end of testA.db-journal. The master-journal file does not exist. + # + set mj [file normalize testA.db-mj-123] + binary scan $mj c* a + set cksum 0 + foreach i $a { incr cksum $i } + set mj_pgno [expr $sqlite_pending_byte / 1024] + set zAppend [binary format Ia*IIa8 $mj_pgno $mj [string length $mj] $cksum \ + "\xd9\xd5\x05\xf9\x20\xa1\x63\xd7" + ] + set iOffset [expr (([file size testA.db-journal] + 511)/512)*512] + set fd [open testA.db-journal a+] + fconfigure $fd -encoding binary -translation binary + seek $fd $iOffset + puts -nonewline $fd $zAppend + + # Also, fix the first journal-header in the journal-file. Because the + # journal file has not yet been synced, the 8-byte magic string at the + # start of the first journal-header has not been written by SQLite. + # So write it now. + seek $fd 0 + puts -nonewline $fd "\xd9\xd5\x05\xf9\x20\xa1\x63\xd7" + close $fd + + # Open a handle on testA.db and use it to query the database. At one + # point the first query would attempt a hot rollback, attempt to open + # the master-journal file and return SQLITE_CANTOPEN when it could not + # be opened. This is incorrect, it should simply delete the journal + # file and proceed with the query. + # + do_test rollback-2.2 { + sqlite3 db2 testA.db + execsql { + SELECT distinct tbl_name FROM sqlite_master; + } db2 + } {t1 t3} + if {[lsearch {exclusive persistent_journal no_journal} [permutation]]<0} { + do_test rollback-2.3 { + file exists testA.db-journal + } 0 + } + do_test rollback-2.4 { + execsql { + SELECT distinct tbl_name FROM sqlite_master; + } db2 + } {t1 t3} + + db2 close +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/rowhash.test b/components/external/SQLite-3.8.1/test/rowhash.test new file mode 100644 index 0000000000000000000000000000000000000000..4a553cd6d5454a3465ba6df29a4b9ec3a9fd5a66 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/rowhash.test @@ -0,0 +1,59 @@ +# 2009 April 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this file is the code in rowhash.c. +# +# NB: The rowhash.c module is no longer part of the source tree. But +# we might as well keep this test. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test rowhash-1.1 { + execsql { + CREATE TABLE t1(id INTEGER PRIMARY KEY, a, b, c); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); + CREATE INDEX i3 ON t1(c); + } +} {} + +proc do_keyset_test {name lKey} { + db transaction { + execsql { DELETE FROM t1 } + foreach key $lKey { + execsql { INSERT OR IGNORE INTO t1 VALUES($key, 'a', 'b', 'c') } + } + } + do_test $name { + lsort -integer [execsql { + SELECT id FROM t1 WHERE a = 'a' OR b = 'b' OR c = 'c'; + }] + } [lsort -integer -unique $lKey] +} + +do_keyset_test rowhash-2.1 {1 2 3} +do_keyset_test rowhash-2.2 {0 1 2 3} +do_keyset_test rowhash-2.3 {62 125 188} +if {[working_64bit_int]} { + expr srand(1) + unset -nocomplain i L + for {set i 4} {$i < 10} {incr i} { + for {set j 0} {$j < 5000} {incr j} { + lappend L [expr int(rand()*1000000000)] + } + do_keyset_test rowhash-2.$i $L + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/rowid.test b/components/external/SQLite-3.8.1/test/rowid.test new file mode 100644 index 0000000000000000000000000000000000000000..5daf581ea64a8b74c5a5b5095b7f30c7fd64a7d7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/rowid.test @@ -0,0 +1,703 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the magic ROWID column that is +# found on all tables. +# +# $Id: rowid.test,v 1.21 2009/06/26 15:14:55 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Basic ROWID functionality tests. +# +do_test rowid-1.1 { + execsql { + CREATE TABLE t1(x int, y int); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + SELECT x FROM t1 ORDER BY y; + } +} {1 3} +do_test rowid-1.2 { + set r [execsql {SELECT rowid FROM t1 ORDER BY x}] + global x2rowid rowid2x + set x2rowid(1) [lindex $r 0] + set x2rowid(3) [lindex $r 1] + set rowid2x($x2rowid(1)) 1 + set rowid2x($x2rowid(3)) 3 + llength $r +} {2} +do_test rowid-1.3 { + global x2rowid + set sql "SELECT x FROM t1 WHERE rowid==$x2rowid(1)" + execsql $sql +} {1} +do_test rowid-1.4 { + global x2rowid + set sql "SELECT x FROM t1 WHERE rowid==$x2rowid(3)" + execsql $sql +} {3} +do_test rowid-1.5 { + global x2rowid + set sql "SELECT x FROM t1 WHERE oid==$x2rowid(1)" + execsql $sql +} {1} +do_test rowid-1.6 { + global x2rowid + set sql "SELECT x FROM t1 WHERE OID==$x2rowid(3)" + execsql $sql +} {3} +do_test rowid-1.7 { + global x2rowid + set sql "SELECT x FROM t1 WHERE _rowid_==$x2rowid(1)" + execsql $sql +} {1} +do_test rowid-1.7.1 { + while 1 { + set norow [expr {int(rand()*1000000)}] + if {$norow!=$x2rowid(1) && $norow!=$x2rowid(3)} break + } + execsql "SELECT x FROM t1 WHERE rowid=$norow" +} {} +do_test rowid-1.8 { + global x2rowid + set v [execsql {SELECT x, oid FROM t1 order by x}] + set v2 [list 1 $x2rowid(1) 3 $x2rowid(3)] + expr {$v==$v2} +} {1} +do_test rowid-1.9 { + global x2rowid + set v [execsql {SELECT x, RowID FROM t1 order by x}] + set v2 [list 1 $x2rowid(1) 3 $x2rowid(3)] + expr {$v==$v2} +} {1} +do_test rowid-1.10 { + global x2rowid + set v [execsql {SELECT x, _rowid_ FROM t1 order by x}] + set v2 [list 1 $x2rowid(1) 3 $x2rowid(3)] + expr {$v==$v2} +} {1} + +# We can insert or update the ROWID column. +# +do_test rowid-2.1 { + catchsql { + INSERT INTO t1(rowid,x,y) VALUES(1234,5,6); + SELECT rowid, * FROM t1; + } +} {0 {1 1 2 2 3 4 1234 5 6}} +do_test rowid-2.2 { + catchsql { + UPDATE t1 SET rowid=12345 WHERE x==1; + SELECT rowid, * FROM t1 + } +} {0 {2 3 4 1234 5 6 12345 1 2}} +do_test rowid-2.3 { + catchsql { + INSERT INTO t1(y,x,oid) VALUES(8,7,1235); + SELECT rowid, * FROM t1 WHERE rowid>1000; + } +} {0 {1234 5 6 1235 7 8 12345 1 2}} +do_test rowid-2.4 { + catchsql { + UPDATE t1 SET oid=12346 WHERE x==1; + SELECT rowid, * FROM t1; + } +} {0 {2 3 4 1234 5 6 1235 7 8 12346 1 2}} +do_test rowid-2.5 { + catchsql { + INSERT INTO t1(x,_rowid_,y) VALUES(9,1236,10); + SELECT rowid, * FROM t1 WHERE rowid>1000; + } +} {0 {1234 5 6 1235 7 8 1236 9 10 12346 1 2}} +do_test rowid-2.6 { + catchsql { + UPDATE t1 SET _rowid_=12347 WHERE x==1; + SELECT rowid, * FROM t1 WHERE rowid>1000; + } +} {0 {1234 5 6 1235 7 8 1236 9 10 12347 1 2}} + +# But we can use ROWID in the WHERE clause of an UPDATE that does not +# change the ROWID. +# +do_test rowid-2.7 { + global x2rowid + set sql "UPDATE t1 SET x=2 WHERE OID==$x2rowid(3)" + execsql $sql + execsql {SELECT x FROM t1 ORDER BY x} +} {1 2 5 7 9} +do_test rowid-2.8 { + global x2rowid + set sql "UPDATE t1 SET x=3 WHERE _rowid_==$x2rowid(3)" + execsql $sql + execsql {SELECT x FROM t1 ORDER BY x} +} {1 3 5 7 9} + +# We cannot index by ROWID +# +do_test rowid-2.9 { + set v [catch {execsql {CREATE INDEX idxt1 ON t1(rowid)}} msg] + lappend v $msg +} {1 {table t1 has no column named rowid}} +do_test rowid-2.10 { + set v [catch {execsql {CREATE INDEX idxt1 ON t1(_rowid_)}} msg] + lappend v $msg +} {1 {table t1 has no column named _rowid_}} +do_test rowid-2.11 { + set v [catch {execsql {CREATE INDEX idxt1 ON t1(oid)}} msg] + lappend v $msg +} {1 {table t1 has no column named oid}} +do_test rowid-2.12 { + set v [catch {execsql {CREATE INDEX idxt1 ON t1(x, rowid)}} msg] + lappend v $msg +} {1 {table t1 has no column named rowid}} + +# Columns defined in the CREATE statement override the buildin ROWID +# column names. +# +do_test rowid-3.1 { + execsql { + CREATE TABLE t2(rowid int, x int, y int); + INSERT INTO t2 VALUES(0,2,3); + INSERT INTO t2 VALUES(4,5,6); + INSERT INTO t2 VALUES(7,8,9); + SELECT * FROM t2 ORDER BY x; + } +} {0 2 3 4 5 6 7 8 9} +do_test rowid-3.2 { + execsql {SELECT * FROM t2 ORDER BY rowid} +} {0 2 3 4 5 6 7 8 9} +do_test rowid-3.3 { + execsql {SELECT rowid, x, y FROM t2 ORDER BY rowid} +} {0 2 3 4 5 6 7 8 9} +do_test rowid-3.4 { + set r1 [execsql {SELECT _rowid_, rowid FROM t2 ORDER BY rowid}] + foreach {a b c d e f} $r1 {} + set r2 [execsql {SELECT _rowid_, rowid FROM t2 ORDER BY x DESC}] + foreach {u v w x y z} $r2 {} + expr {$u==$e && $w==$c && $y==$a} +} {1} +# sqlite3 v3 - do_probtest doesn't exist anymore? +if 0 { +do_probtest rowid-3.5 { + set r1 [execsql {SELECT _rowid_, rowid FROM t2 ORDER BY rowid}] + foreach {a b c d e f} $r1 {} + expr {$a!=$b && $c!=$d && $e!=$f} +} {1} +} + +# Let's try some more complex examples, including some joins. +# +do_test rowid-4.1 { + execsql { + DELETE FROM t1; + DELETE FROM t2; + } + for {set i 1} {$i<=50} {incr i} { + execsql "INSERT INTO t1(x,y) VALUES($i,[expr {$i*$i}])" + } + execsql {INSERT INTO t2 SELECT _rowid_, x*y, y*y FROM t1} + execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t1.rowid==t2.rowid} +} {256} +do_test rowid-4.2 { + execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1.rowid==t2.rowid} +} {256} +do_test rowid-4.2.1 { + execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1.oid==t2.rowid} +} {256} +do_test rowid-4.2.2 { + execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1._rowid_==t2.rowid} +} {256} +do_test rowid-4.2.3 { + execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t2.rowid==t1.rowid} +} {256} +do_test rowid-4.2.4 { + execsql {SELECT t2.y FROM t2, t1 WHERE t2.rowid==t1.oid AND t1.x==4} +} {256} +do_test rowid-4.2.5 { + execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t1._rowid_==t2.rowid} +} {256} +do_test rowid-4.2.6 { + execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t2.rowid==t1.rowid} +} {256} +do_test rowid-4.2.7 { + execsql {SELECT t2.y FROM t1, t2 WHERE t2.rowid==t1.oid AND t1.x==4} +} {256} +do_test rowid-4.3 { + execsql {CREATE INDEX idxt1 ON t1(x)} + execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t1.rowid==t2.rowid} +} {256} +do_test rowid-4.3.1 { + execsql {SELECT t2.y FROM t1, t2 WHERE t1.x==4 AND t1._rowid_==t2.rowid} +} {256} +do_test rowid-4.3.2 { + execsql {SELECT t2.y FROM t1, t2 WHERE t2.rowid==t1.oid AND 4==t1.x} +} {256} +do_test rowid-4.4 { + execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1.rowid==t2.rowid} +} {256} +do_test rowid-4.4.1 { + execsql {SELECT t2.y FROM t2, t1 WHERE t1.x==4 AND t1._rowid_==t2.rowid} +} {256} +do_test rowid-4.4.2 { + execsql {SELECT t2.y FROM t2, t1 WHERE t2.rowid==t1.oid AND 4==t1.x} +} {256} +do_test rowid-4.5 { + execsql {CREATE INDEX idxt2 ON t2(y)} + set sqlite_search_count 0 + concat [execsql { + SELECT t1.x FROM t2, t1 + WHERE t2.y==256 AND t1.rowid==t2.rowid + }] $sqlite_search_count +} {4 3} +do_test rowid-4.5.1 { + set sqlite_search_count 0 + concat [execsql { + SELECT t1.x FROM t2, t1 + WHERE t1.OID==t2.rowid AND t2.y==81 + }] $sqlite_search_count +} {3 3} +do_test rowid-4.6 { + execsql { + SELECT t1.x FROM t1, t2 + WHERE t2.y==256 AND t1.rowid==t2.rowid + } +} {4} + +do_test rowid-5.1.1 { + ifcapable subquery { + execsql {DELETE FROM t1 WHERE _rowid_ IN (SELECT oid FROM t1 WHERE x>8)} + } else { + set oids [execsql {SELECT oid FROM t1 WHERE x>8}] + set where "_rowid_ = [join $oids { OR _rowid_ = }]" + execsql "DELETE FROM t1 WHERE $where" + } +} {} +do_test rowid-5.1.2 { + execsql {SELECT max(x) FROM t1} +} {8} + +# Make sure a "WHERE rowid=X" clause works when there is no ROWID of X. +# +do_test rowid-6.1 { + execsql { + SELECT x FROM t1 + } +} {1 2 3 4 5 6 7 8} +do_test rowid-6.2 { + for {set ::norow 1} {1} {incr ::norow} { + if {[execsql "SELECT x FROM t1 WHERE rowid=$::norow"]==""} break + } + execsql [subst { + DELETE FROM t1 WHERE rowid=$::norow + }] +} {} +do_test rowid-6.3 { + execsql { + SELECT x FROM t1 + } +} {1 2 3 4 5 6 7 8} + +# Beginning with version 2.3.4, SQLite computes rowids of new rows by +# finding the maximum current rowid and adding one. It falls back to +# the old random algorithm if the maximum rowid is the largest integer. +# The following tests are for this new behavior. +# +do_test rowid-7.0 { + execsql { + DELETE FROM t1; + DROP TABLE t2; + DROP INDEX idxt1; + INSERT INTO t1 VALUES(1,2); + SELECT rowid, * FROM t1; + } +} {1 1 2} +do_test rowid-7.1 { + execsql { + INSERT INTO t1 VALUES(99,100); + SELECT rowid,* FROM t1 + } +} {1 1 2 2 99 100} +do_test rowid-7.2 { + execsql { + CREATE TABLE t2(a INTEGER PRIMARY KEY, b); + INSERT INTO t2(b) VALUES(55); + SELECT * FROM t2; + } +} {1 55} +do_test rowid-7.3 { + execsql { + INSERT INTO t2(b) VALUES(66); + SELECT * FROM t2; + } +} {1 55 2 66} +do_test rowid-7.4 { + execsql { + INSERT INTO t2(a,b) VALUES(1000000,77); + INSERT INTO t2(b) VALUES(88); + SELECT * FROM t2; + } +} {1 55 2 66 1000000 77 1000001 88} +do_test rowid-7.5 { + execsql { + INSERT INTO t2(a,b) VALUES(2147483647,99); + INSERT INTO t2(b) VALUES(11); + SELECT b FROM t2 ORDER BY b; + } +} {11 55 66 77 88 99} +ifcapable subquery { + do_test rowid-7.6 { + execsql { + SELECT b FROM t2 WHERE a NOT IN(1,2,1000000,1000001,2147483647); + } + } {11} + do_test rowid-7.7 { + execsql { + INSERT INTO t2(b) VALUES(22); + INSERT INTO t2(b) VALUES(33); + INSERT INTO t2(b) VALUES(44); + INSERT INTO t2(b) VALUES(55); + SELECT b FROM t2 WHERE a NOT IN(1,2,1000000,1000001,2147483647) + ORDER BY b; + } + } {11 22 33 44 55} +} +do_test rowid-7.8 { + execsql { + DELETE FROM t2 WHERE a!=2; + INSERT INTO t2(b) VALUES(111); + SELECT * FROM t2; + } +} {2 66 3 111} + +ifcapable {trigger} { +# Make sure AFTER triggers that do INSERTs do not change the last_insert_rowid. +# Ticket #290 +# +do_test rowid-8.1 { + execsql { + CREATE TABLE t3(a integer primary key); + CREATE TABLE t4(x); + INSERT INTO t4 VALUES(1); + CREATE TRIGGER r3 AFTER INSERT on t3 FOR EACH ROW BEGIN + INSERT INTO t4 VALUES(NEW.a+10); + END; + SELECT * FROM t3; + } +} {} +do_test rowid-8.2 { + execsql { + SELECT rowid, * FROM t4; + } +} {1 1} +do_test rowid-8.3 { + execsql { + INSERT INTO t3 VALUES(123); + SELECT last_insert_rowid(); + } +} {123} +do_test rowid-8.4 { + execsql { + SELECT * FROM t3; + } +} {123} +do_test rowid-8.5 { + execsql { + SELECT rowid, * FROM t4; + } +} {1 1 2 133} +do_test rowid-8.6 { + execsql { + INSERT INTO t3 VALUES(NULL); + SELECT last_insert_rowid(); + } +} {124} +do_test rowid-8.7 { + execsql { + SELECT * FROM t3; + } +} {123 124} +do_test rowid-8.8 { + execsql { + SELECT rowid, * FROM t4; + } +} {1 1 2 133 3 134} +} ;# endif trigger + +# If triggers are not enable, simulate their effect for the tests that +# follow. +ifcapable {!trigger} { + execsql { + CREATE TABLE t3(a integer primary key); + INSERT INTO t3 VALUES(123); + INSERT INTO t3 VALUES(124); + } +} + +# ticket #377: Comparison between integer primiary key and floating point +# values. +# +do_test rowid-9.1 { + execsql { + SELECT * FROM t3 WHERE a<123.5 + } +} {123} +do_test rowid-9.2 { + execsql { + SELECT * FROM t3 WHERE a<124.5 + } +} {123 124} +do_test rowid-9.3 { + execsql { + SELECT * FROM t3 WHERE a>123.5 + } +} {124} +do_test rowid-9.4 { + execsql { + SELECT * FROM t3 WHERE a>122.5 + } +} {123 124} +do_test rowid-9.5 { + execsql { + SELECT * FROM t3 WHERE a==123.5 + } +} {} +do_test rowid-9.6 { + execsql { + SELECT * FROM t3 WHERE a==123.000 + } +} {123} +do_test rowid-9.7 { + execsql { + SELECT * FROM t3 WHERE a>100.5 AND a<200.5 + } +} {123 124} +do_test rowid-9.8 { + execsql { + SELECT * FROM t3 WHERE a>'xyz'; + } +} {} +do_test rowid-9.9 { + execsql { + SELECT * FROM t3 WHERE a<'xyz'; + } +} {123 124} +do_test rowid-9.10 { + execsql { + SELECT * FROM t3 WHERE a>=122.9 AND a<=123.1 + } +} {123} + +# Ticket #567. Comparisons of ROWID or integery primary key against +# floating point numbers still do not always work. +# +do_test rowid-10.1 { + execsql { + CREATE TABLE t5(a); + INSERT INTO t5 VALUES(1); + INSERT INTO t5 VALUES(2); + INSERT INTO t5 SELECT a+2 FROM t5; + INSERT INTO t5 SELECT a+4 FROM t5; + SELECT rowid, * FROM t5; + } +} {1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8} +do_test rowid-10.2 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>=5.5} +} {6 6 7 7 8 8} +do_test rowid-10.3 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>=5.0} +} {5 5 6 6 7 7 8 8} +do_test rowid-10.4 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>5.5} +} {6 6 7 7 8 8} +do_test rowid-10.3.2 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>5.0} +} {6 6 7 7 8 8} +do_test rowid-10.5 { + execsql {SELECT rowid, a FROM t5 WHERE 5.5<=rowid} +} {6 6 7 7 8 8} +do_test rowid-10.6 { + execsql {SELECT rowid, a FROM t5 WHERE 5.5=rowid} +} {1 1 2 2 3 3 4 4 5 5} +do_test rowid-10.10 { + execsql {SELECT rowid, a FROM t5 WHERE 5.5>rowid} +} {1 1 2 2 3 3 4 4 5 5} +do_test rowid-10.11 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>=5.5 ORDER BY rowid DESC} +} {8 8 7 7 6 6} +do_test rowid-10.11.2 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>=5.0 ORDER BY rowid DESC} +} {8 8 7 7 6 6 5 5} +do_test rowid-10.12 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>5.5 ORDER BY rowid DESC} +} {8 8 7 7 6 6} +do_test rowid-10.12.2 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>5.0 ORDER BY rowid DESC} +} {8 8 7 7 6 6} +do_test rowid-10.13 { + execsql {SELECT rowid, a FROM t5 WHERE 5.5<=rowid ORDER BY rowid DESC} +} {8 8 7 7 6 6} +do_test rowid-10.14 { + execsql {SELECT rowid, a FROM t5 WHERE 5.5=rowid ORDER BY rowid DESC} +} {5 5 4 4 3 3 2 2 1 1} +do_test rowid-10.18 { + execsql {SELECT rowid, a FROM t5 WHERE 5.5>rowid ORDER BY rowid DESC} +} {5 5 4 4 3 3 2 2 1 1} + +do_test rowid-10.30 { + execsql { + CREATE TABLE t6(a); + INSERT INTO t6(rowid,a) SELECT -a,a FROM t5; + SELECT rowid, * FROM t6; + } +} {-8 8 -7 7 -6 6 -5 5 -4 4 -3 3 -2 2 -1 1} +do_test rowid-10.31.1 { + execsql {SELECT rowid, a FROM t6 WHERE rowid>=-5.5} +} {-5 5 -4 4 -3 3 -2 2 -1 1} +do_test rowid-10.31.2 { + execsql {SELECT rowid, a FROM t6 WHERE rowid>=-5.0} +} {-5 5 -4 4 -3 3 -2 2 -1 1} +do_test rowid-10.32.1 { + execsql {SELECT rowid, a FROM t6 WHERE rowid>=-5.5 ORDER BY rowid DESC} +} {-1 1 -2 2 -3 3 -4 4 -5 5} +do_test rowid-10.32.1 { + execsql {SELECT rowid, a FROM t6 WHERE rowid>=-5.0 ORDER BY rowid DESC} +} {-1 1 -2 2 -3 3 -4 4 -5 5} +do_test rowid-10.33 { + execsql {SELECT rowid, a FROM t6 WHERE -5.5<=rowid} +} {-5 5 -4 4 -3 3 -2 2 -1 1} +do_test rowid-10.34 { + execsql {SELECT rowid, a FROM t6 WHERE -5.5<=rowid ORDER BY rowid DESC} +} {-1 1 -2 2 -3 3 -4 4 -5 5} +do_test rowid-10.35.1 { + execsql {SELECT rowid, a FROM t6 WHERE rowid>-5.5} +} {-5 5 -4 4 -3 3 -2 2 -1 1} +do_test rowid-10.35.2 { + execsql {SELECT rowid, a FROM t6 WHERE rowid>-5.0} +} {-4 4 -3 3 -2 2 -1 1} +do_test rowid-10.36.1 { + execsql {SELECT rowid, a FROM t6 WHERE rowid>-5.5 ORDER BY rowid DESC} +} {-1 1 -2 2 -3 3 -4 4 -5 5} +do_test rowid-10.36.2 { + execsql {SELECT rowid, a FROM t6 WHERE rowid>-5.0 ORDER BY rowid DESC} +} {-1 1 -2 2 -3 3 -4 4} +do_test rowid-10.37 { + execsql {SELECT rowid, a FROM t6 WHERE -5.5=rowid} +} {-8 8 -7 7 -6 6} +do_test rowid-10.42 { + execsql {SELECT rowid, a FROM t6 WHERE -5.5>=rowid ORDER BY rowid DESC} +} {-6 6 -7 7 -8 8} +do_test rowid-10.43 { + execsql {SELECT rowid, a FROM t6 WHERE rowid<-5.5} +} {-8 8 -7 7 -6 6} +do_test rowid-10.44 { + execsql {SELECT rowid, a FROM t6 WHERE rowid<-5.5 ORDER BY rowid DESC} +} {-6 6 -7 7 -8 8} +do_test rowid-10.44 { + execsql {SELECT rowid, a FROM t6 WHERE -5.5>rowid} +} {-8 8 -7 7 -6 6} +do_test rowid-10.46 { + execsql {SELECT rowid, a FROM t6 WHERE -5.5>rowid ORDER BY rowid DESC} +} {-6 6 -7 7 -8 8} + +# Comparison of rowid against string values. +# +do_test rowid-11.1 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>'abc'} +} {} +do_test rowid-11.2 { + execsql {SELECT rowid, a FROM t5 WHERE rowid>='abc'} +} {} +do_test rowid-11.3 { + execsql {SELECT rowid, a FROM t5 WHERE rowid<'abc'} +} {1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8} +do_test rowid-11.4 { + execsql {SELECT rowid, a FROM t5 WHERE rowid<='abc'} +} {1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8} + +# Test the automatic generation of rowids when the table already contains +# a rowid with the maximum value. +# +# Once the maximum rowid is taken, rowids are normally chosen at +# random. By by reseting the random number generator, we can cause +# the rowid guessing loop to collide with prior rowids, and test the +# loop out to its limit of 100 iterations. After 100 collisions, the +# rowid guesser gives up and reports SQLITE_FULL. +# +do_test rowid-12.1 { + execsql { + CREATE TABLE t7(x INTEGER PRIMARY KEY, y); + CREATE TABLE t7temp(a INTEGER PRIMARY KEY); + INSERT INTO t7 VALUES(9223372036854775807,'a'); + SELECT y FROM t7; + } +} {a} +do_test rowid-12.2 { + db close + sqlite3 db test.db + save_prng_state + execsql { + INSERT INTO t7 VALUES(NULL,'b'); + SELECT x, y FROM t7; + } +} {1 b 9223372036854775807 a} +execsql {INSERT INTO t7 VALUES(2,'y');} +for {set i 1} {$i<100} {incr i} { + do_test rowid-12.3.$i { + db eval {DELETE FROM t7temp; INSERT INTO t7temp VALUES(1);} + restore_prng_state + execsql { + INSERT INTO t7 VALUES(NULL,'x'); + SELECT count(*) FROM t7 WHERE y=='x'; + } + } $i +} +do_test rowid-12.4 { + db eval {DELETE FROM t7temp; INSERT INTO t7temp VALUES(1);} + restore_prng_state + catchsql { + INSERT INTO t7 VALUES(NULL,'x'); + } +} {1 {database or disk is full}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/rtree.test b/components/external/SQLite-3.8.1/test/rtree.test new file mode 100644 index 0000000000000000000000000000000000000000..b5045746cd8681de61cc4c9ad780db45e4999f7f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/rtree.test @@ -0,0 +1,18 @@ +# 2008 June 23 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs all rtree related tests. +# + +set testdir [file dirname $argv0] +source $testdir/permutations.test + +ifcapable rtree { + run_test_suite rtree +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/savepoint.test b/components/external/SQLite-3.8.1/test/savepoint.test new file mode 100644 index 0000000000000000000000000000000000000000..015d97fe1aca017d266b1c4ccfd47eb76acbeed4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/savepoint.test @@ -0,0 +1,1051 @@ +# 2008 December 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: savepoint.test,v 1.13 2009/07/18 08:30:45 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +#---------------------------------------------------------------------- +# The following tests - savepoint-1.* - test that the SAVEPOINT, RELEASE +# and ROLLBACK TO comands are correctly parsed, and that the auto-commit +# flag is correctly set and unset as a result. +# +do_test savepoint-1.1 { + wal_set_journal_mode + execsql { + SAVEPOINT sp1; + RELEASE sp1; + } +} {} +do_test savepoint-1.2 { + execsql { + SAVEPOINT sp1; + ROLLBACK TO sp1; + } +} {} +do_test savepoint-1.3 { + execsql { SAVEPOINT sp1 } + db close +} {} +sqlite3 db test.db +do_test savepoint-1.4.1 { + execsql { + SAVEPOINT sp1; + SAVEPOINT sp2; + RELEASE sp1; + } + sqlite3_get_autocommit db +} {1} +do_test savepoint-1.4.2 { + execsql { + SAVEPOINT sp1; + SAVEPOINT sp2; + RELEASE sp2; + } + sqlite3_get_autocommit db +} {0} +do_test savepoint-1.4.3 { + execsql { RELEASE sp1 } + sqlite3_get_autocommit db +} {1} +do_test savepoint-1.4.4 { + execsql { + SAVEPOINT sp1; + SAVEPOINT sp2; + ROLLBACK TO sp1; + } + sqlite3_get_autocommit db +} {0} +do_test savepoint-1.4.5 { + execsql { RELEASE SAVEPOINT sp1 } + sqlite3_get_autocommit db +} {1} +do_test savepoint-1.4.6 { + execsql { + SAVEPOINT sp1; + SAVEPOINT sp2; + SAVEPOINT sp3; + ROLLBACK TO SAVEPOINT sp3; + ROLLBACK TRANSACTION TO sp2; + ROLLBACK TRANSACTION TO SAVEPOINT sp1; + } + sqlite3_get_autocommit db +} {0} +do_test savepoint-1.4.7 { + execsql { RELEASE SAVEPOINT SP1 } + sqlite3_get_autocommit db +} {1} +do_test savepoint-1.5 { + execsql { + SAVEPOINT sp1; + ROLLBACK TO sp1; + } +} {} +do_test savepoint-1.6 { + execsql COMMIT +} {} +wal_check_journal_mode savepoint-1.7 + +#------------------------------------------------------------------------ +# These tests - savepoint-2.* - test rollbacks and releases of savepoints +# with a very simple data set. +# + +do_test savepoint-2.1 { + execsql { + CREATE TABLE t1(a, b, c); + BEGIN; + INSERT INTO t1 VALUES(1, 2, 3); + SAVEPOINT one; + UPDATE t1 SET a = 2, b = 3, c = 4; + } + execsql { SELECT * FROM t1 } +} {2 3 4} +do_test savepoint-2.2 { + execsql { + ROLLBACK TO one; + } + execsql { SELECT * FROM t1 } +} {1 2 3} +do_test savepoint-2.3 { + execsql { + INSERT INTO t1 VALUES(4, 5, 6); + } + execsql { SELECT * FROM t1 } +} {1 2 3 4 5 6} +do_test savepoint-2.4 { + execsql { + ROLLBACK TO one; + } + execsql { SELECT * FROM t1 } +} {1 2 3} + + +do_test savepoint-2.5 { + execsql { + INSERT INTO t1 VALUES(7, 8, 9); + SAVEPOINT two; + INSERT INTO t1 VALUES(10, 11, 12); + } + execsql { SELECT * FROM t1 } +} {1 2 3 7 8 9 10 11 12} +do_test savepoint-2.6 { + execsql { + ROLLBACK TO two; + } + execsql { SELECT * FROM t1 } +} {1 2 3 7 8 9} +do_test savepoint-2.7 { + execsql { + INSERT INTO t1 VALUES(10, 11, 12); + } + execsql { SELECT * FROM t1 } +} {1 2 3 7 8 9 10 11 12} +do_test savepoint-2.8 { + execsql { + ROLLBACK TO one; + } + execsql { SELECT * FROM t1 } +} {1 2 3} +do_test savepoint-2.9 { + execsql { + INSERT INTO t1 VALUES('a', 'b', 'c'); + SAVEPOINT two; + INSERT INTO t1 VALUES('d', 'e', 'f'); + } + execsql { SELECT * FROM t1 } +} {1 2 3 a b c d e f} +do_test savepoint-2.10 { + execsql { + RELEASE two; + } + execsql { SELECT * FROM t1 } +} {1 2 3 a b c d e f} +do_test savepoint-2.11 { + execsql { + ROLLBACK; + } + execsql { SELECT * FROM t1 } +} {} +wal_check_journal_mode savepoint-2.12 + +#------------------------------------------------------------------------ +# This block of tests - savepoint-3.* - test that when a transaction +# savepoint is rolled back, locks are not released from database files. +# And that when a transaction savepoint is released, they are released. +# +# These tests do not work in WAL mode. WAL mode does not take RESERVED +# locks on the database file. +# +if {[wal_is_wal_mode]==0} { + do_test savepoint-3.1 { + execsql { SAVEPOINT "transaction" } + execsql { PRAGMA lock_status } + } {main unlocked temp closed} + + do_test savepoint-3.2 { + execsql { INSERT INTO t1 VALUES(1, 2, 3) } + execsql { PRAGMA lock_status } + } {main reserved temp closed} + + do_test savepoint-3.3 { + execsql { ROLLBACK TO "transaction" } + execsql { PRAGMA lock_status } + } {main reserved temp closed} + + do_test savepoint-3.4 { + execsql { INSERT INTO t1 VALUES(1, 2, 3) } + execsql { PRAGMA lock_status } + } {main reserved temp closed} + + do_test savepoint-3.5 { + execsql { RELEASE "transaction" } + execsql { PRAGMA lock_status } + } {main unlocked temp closed} +} + +#------------------------------------------------------------------------ +# Test that savepoints that include schema modifications are handled +# correctly. Test cases savepoint-4.*. +# +do_test savepoint-4.1 { + execsql { + CREATE TABLE t2(d, e, f); + SELECT sql FROM sqlite_master; + } +} {{CREATE TABLE t1(a, b, c)} {CREATE TABLE t2(d, e, f)}} +do_test savepoint-4.2 { + execsql { + BEGIN; + CREATE TABLE t3(g,h); + INSERT INTO t3 VALUES('I', 'II'); + SAVEPOINT one; + DROP TABLE t3; + } +} {} +do_test savepoint-4.3 { + execsql { + CREATE TABLE t3(g, h, i); + INSERT INTO t3 VALUES('III', 'IV', 'V'); + } + execsql {SELECT * FROM t3} +} {III IV V} +do_test savepoint-4.4 { + execsql { ROLLBACK TO one; } + execsql {SELECT * FROM t3} +} {I II} +do_test savepoint-4.5 { + execsql { + ROLLBACK; + SELECT sql FROM sqlite_master; + } +} {{CREATE TABLE t1(a, b, c)} {CREATE TABLE t2(d, e, f)}} + +do_test savepoint-4.6 { + execsql { + BEGIN; + INSERT INTO t1 VALUES('o', 't', 't'); + SAVEPOINT sp1; + CREATE TABLE t3(a, b, c); + INSERT INTO t3 VALUES('z', 'y', 'x'); + } + execsql {SELECT * FROM t3} +} {z y x} +do_test savepoint-4.7 { + execsql { + ROLLBACK TO sp1; + CREATE TABLE t3(a); + INSERT INTO t3 VALUES('value'); + } + execsql {SELECT * FROM t3} +} {value} +do_test savepoint-4.8 { + execsql COMMIT +} {} +wal_check_journal_mode savepoint-4.9 + +#------------------------------------------------------------------------ +# Test some logic errors to do with the savepoint feature. +# + +ifcapable incrblob { + do_test savepoint-5.1.1 { + execsql { + CREATE TABLE blobs(x); + INSERT INTO blobs VALUES('a twentyeight character blob'); + } + set fd [db incrblob blobs x 1] + puts -nonewline $fd "hello" + catchsql {SAVEPOINT abc} + } {1 {cannot open savepoint - SQL statements in progress}} + do_test savepoint-5.1.2 { + close $fd + catchsql {SAVEPOINT abc} + } {0 {}} + + do_test savepoint-5.2 { + execsql {RELEASE abc} + catchsql {RELEASE abc} + } {1 {no such savepoint: abc}} + + do_test savepoint-5.3.1 { + execsql {SAVEPOINT abc} + catchsql {ROLLBACK TO def} + } {1 {no such savepoint: def}} + do_test savepoint-5.3.2.1 { + execsql {SAVEPOINT def} + set fd [db incrblob -readonly blobs x 1] + set rc [catch {seek $fd 0;read $fd} res] + lappend rc $res + } {0 {hellontyeight character blob}} + do_test savepoint-5.3.2.2 { + catchsql {ROLLBACK TO def} + } {0 {}} + do_test savepoint-5.3.2.3 { + set rc [catch {seek $fd 0; read $fd} res] + set rc + } {1} + do_test savepoint-5.3.3 { + catchsql {RELEASE def} + } {0 {}} + do_test savepoint-5.3.4 { + close $fd + execsql {savepoint def} + set fd [db incrblob blobs x 1] + catchsql {release def} + } {1 {cannot release savepoint - SQL statements in progress}} + do_test savepoint-5.3.5 { + close $fd + execsql {release abc} + } {} + + # Rollback mode: + # + # Open a savepoint transaction and insert a row into the database. Then, + # using a second database handle, open a read-only transaction on the + # database file. Check that the savepoint transaction cannot be committed + # until after the read-only transaction has been closed. + # + # WAL mode: + # + # As above, except that the savepoint transaction can be successfully + # committed before the read-only transaction has been closed. + # + do_test savepoint-5.4.1 { + execsql { + SAVEPOINT main; + INSERT INTO blobs VALUES('another blob'); + } + } {} + do_test savepoint-5.4.2 { + sqlite3 db2 test.db + execsql { BEGIN ; SELECT count(*) FROM blobs } db2 + } {1} + if {[wal_is_wal_mode]} { + do_test savepoint-5.4.3 { catchsql "RELEASE main" } {0 {}} + do_test savepoint-5.4.4 { db2 close } {} + } else { + do_test savepoint-5.4.3 { + catchsql { RELEASE main } + } {1 {database is locked}} + do_test savepoint-5.4.4 { + db2 close + catchsql { RELEASE main } + } {0 {}} + } + do_test savepoint-5.4.5 { + execsql { SELECT x FROM blobs WHERE rowid = 2 } + } {{another blob}} + do_test savepoint-5.4.6 { + execsql { SELECT count(*) FROM blobs } + } {2} +} +wal_check_journal_mode savepoint-5.5 + +#------------------------------------------------------------------------- +# The following tests, savepoint-6.*, test an incr-vacuum inside of a +# couple of nested savepoints. +# +ifcapable {autovacuum && pragma} { + db close + forcedelete test.db + sqlite3 db test.db + + do_test savepoint-6.1 { + execsql { PRAGMA auto_vacuum = incremental } + wal_set_journal_mode + execsql { + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(a, b); + BEGIN; + INSERT INTO t1 VALUES(randstr(10,400),randstr(10,400),randstr(10,400)); + } + set r "randstr(10,400)" + for {set ii 0} {$ii < 10} {incr ii} { + execsql "INSERT INTO t1 SELECT $r, $r, $r FROM t1" + } + execsql { COMMIT } + } {} + + integrity_check savepoint-6.2 + + do_test savepoint-6.3 { + execsql { + PRAGMA cache_size = 10; + BEGIN; + UPDATE t1 SET a = randstr(10,10) WHERE (rowid%4)==0; + SAVEPOINT one; + DELETE FROM t1 WHERE rowid%2; + PRAGMA incr_vacuum; + SAVEPOINT two; + INSERT INTO t1 SELECT randstr(10,400), randstr(10,400), c FROM t1; + DELETE FROM t1 WHERE rowid%2; + PRAGMA incr_vacuum; + ROLLBACK TO one; + COMMIT; + } + } {} + + integrity_check savepoint-6.4 + + wal_check_journal_mode savepoint-6.5 +} + +#------------------------------------------------------------------------- +# The following tests, savepoint-7.*, attempt to break the logic +# surrounding savepoints by growing and shrinking the database file. +# +db close +forcedelete test.db +sqlite3 db test.db + +do_test savepoint-7.1 { + execsql { PRAGMA auto_vacuum = incremental } + wal_set_journal_mode + execsql { + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1(a) VALUES('alligator'); + INSERT INTO t1(a) VALUES('angelfish'); + INSERT INTO t1(a) VALUES('ant'); + INSERT INTO t1(a) VALUES('antelope'); + INSERT INTO t1(a) VALUES('ape'); + INSERT INTO t1(a) VALUES('baboon'); + INSERT INTO t1(a) VALUES('badger'); + INSERT INTO t1(a) VALUES('bear'); + INSERT INTO t1(a) VALUES('beetle'); + INSERT INTO t1(a) VALUES('bird'); + INSERT INTO t1(a) VALUES('bison'); + UPDATE t1 SET b = randstr(1000,1000); + UPDATE t1 SET b = b||randstr(1000,1000); + UPDATE t1 SET b = b||randstr(1000,1000); + UPDATE t1 SET b = b||randstr(10,1000); + COMMIT; + } + expr ([execsql { PRAGMA page_count }] > 20) +} {1} +do_test savepoint-7.2.1 { + execsql { + BEGIN; + SAVEPOINT one; + CREATE TABLE t2(a, b); + INSERT INTO t2 SELECT a, b FROM t1; + ROLLBACK TO one; + } + execsql { + PRAGMA integrity_check; + } +} {ok} +do_test savepoint-7.2.2 { + execsql { + COMMIT; + PRAGMA integrity_check; + } +} {ok} + +do_test savepoint-7.3.1 { + execsql { + CREATE TABLE t2(a, b); + INSERT INTO t2 SELECT a, b FROM t1; + } +} {} +do_test savepoint-7.3.2 { + execsql { + BEGIN; + SAVEPOINT one; + DELETE FROM t2; + PRAGMA incremental_vacuum; + SAVEPOINT two; + INSERT INTO t2 SELECT a, b FROM t1; + ROLLBACK TO two; + COMMIT; + } + execsql { PRAGMA integrity_check } +} {ok} +wal_check_journal_mode savepoint-7.3.3 + +do_test savepoint-7.4.1 { + db close + forcedelete test.db + sqlite3 db test.db + execsql { PRAGMA auto_vacuum = incremental } + wal_set_journal_mode + execsql { + CREATE TABLE t1(a, b, PRIMARY KEY(a, b)); + INSERT INTO t1 VALUES(randstr(1000,1000), randstr(1000,1000)); + BEGIN; + DELETE FROM t1; + SAVEPOINT one; + PRAGMA incremental_vacuum; + ROLLBACK TO one; + COMMIT; + } + + execsql { PRAGMA integrity_check } +} {ok} + +do_test savepoint-7.5.1 { + execsql { + PRAGMA incremental_vacuum; + CREATE TABLE t5(x, y); + INSERT INTO t5 VALUES(1, randstr(1000,1000)); + INSERT INTO t5 VALUES(2, randstr(1000,1000)); + INSERT INTO t5 VALUES(3, randstr(1000,1000)); + + BEGIN; + INSERT INTO t5 VALUES(4, randstr(1000,1000)); + INSERT INTO t5 VALUES(5, randstr(1000,1000)); + DELETE FROM t5 WHERE x=1 OR x=2; + SAVEPOINT one; + PRAGMA incremental_vacuum; + SAVEPOINT two; + INSERT INTO t5 VALUES(1, randstr(1000,1000)); + INSERT INTO t5 VALUES(2, randstr(1000,1000)); + ROLLBACK TO two; + ROLLBACK TO one; + COMMIT; + PRAGMA integrity_check; + } +} {ok} +do_test savepoint-7.5.2 { + execsql { + DROP TABLE t5; + } +} {} +wal_check_journal_mode savepoint-7.5.3 + +# Test oddly named and quoted savepoints. +# +do_test savepoint-8-1 { + execsql { SAVEPOINT "save1" } + execsql { RELEASE save1 } +} {} +do_test savepoint-8-2 { + execsql { SAVEPOINT "Including whitespace " } + execsql { RELEASE "including Whitespace " } +} {} + +# Test that the authorization callback works. +# +ifcapable auth { + proc auth {args} { + eval lappend ::authdata $args + return SQLITE_OK + } + db auth auth + + do_test savepoint-9.1 { + set ::authdata [list] + execsql { SAVEPOINT sp1 } + set ::authdata + } {SQLITE_SAVEPOINT BEGIN sp1 {} {}} + do_test savepoint-9.2 { + set ::authdata [list] + execsql { ROLLBACK TO sp1 } + set ::authdata + } {SQLITE_SAVEPOINT ROLLBACK sp1 {} {}} + do_test savepoint-9.3 { + set ::authdata [list] + execsql { RELEASE sp1 } + set ::authdata + } {SQLITE_SAVEPOINT RELEASE sp1 {} {}} + + proc auth {args} { + eval lappend ::authdata $args + return SQLITE_DENY + } + db auth auth + + do_test savepoint-9.4 { + set ::authdata [list] + set res [catchsql { SAVEPOINT sp1 }] + concat $::authdata $res + } {SQLITE_SAVEPOINT BEGIN sp1 {} {} 1 {not authorized}} + do_test savepoint-9.5 { + set ::authdata [list] + set res [catchsql { ROLLBACK TO sp1 }] + concat $::authdata $res + } {SQLITE_SAVEPOINT ROLLBACK sp1 {} {} 1 {not authorized}} + do_test savepoint-9.6 { + set ::authdata [list] + set res [catchsql { RELEASE sp1 }] + concat $::authdata $res + } {SQLITE_SAVEPOINT RELEASE sp1 {} {} 1 {not authorized}} + + catch { db eval ROLLBACK } + db auth "" +} + +#------------------------------------------------------------------------- +# The following tests - savepoint-10.* - test the interaction of +# savepoints and ATTACH statements. +# + +# First make sure it is not possible to attach or detach a database while +# a savepoint is open (it is not possible if any transaction is open). +# +do_test savepoint-10.1.1 { + catchsql { + SAVEPOINT one; + ATTACH 'test2.db' AS aux; + } +} {1 {cannot ATTACH database within transaction}} +do_test savepoint-10.1.2 { + execsql { + RELEASE one; + ATTACH 'test2.db' AS aux; + } + catchsql { + SAVEPOINT one; + DETACH aux; + } +} {1 {cannot DETACH database within transaction}} +do_test savepoint-10.1.3 { + execsql { + RELEASE one; + DETACH aux; + } +} {} + +# The lock state of the TEMP database can vary if SQLITE_TEMP_STORE=3 +# And the following set of tests is only really interested in the status +# of the aux1 and aux2 locks. So record the current lock status of +# TEMP for use in the answers. +set templockstate [lindex [db eval {PRAGMA lock_status}] 3] + + +if {[wal_is_wal_mode]==0} { + do_test savepoint-10.2.1 { + forcedelete test3.db + forcedelete test2.db + execsql { + ATTACH 'test2.db' AS aux1; + ATTACH 'test3.db' AS aux2; + DROP TABLE t1; + CREATE TABLE main.t1(x, y); + CREATE TABLE aux1.t2(x, y); + CREATE TABLE aux2.t3(x, y); + SELECT name FROM sqlite_master; + SELECT name FROM aux1.sqlite_master; + SELECT name FROM aux2.sqlite_master; + } + } {t1 t2 t3} + do_test savepoint-10.2.2 { + execsql { PRAGMA lock_status } + } [list main unlocked temp $templockstate aux1 unlocked aux2 unlocked] + + do_test savepoint-10.2.3 { + execsql { + SAVEPOINT one; + INSERT INTO t1 VALUES(1, 2); + PRAGMA lock_status; + } + } [list main reserved temp $templockstate aux1 unlocked aux2 unlocked] + do_test savepoint-10.2.4 { + execsql { + INSERT INTO t3 VALUES(3, 4); + PRAGMA lock_status; + } + } [list main reserved temp $templockstate aux1 unlocked aux2 reserved] + do_test savepoint-10.2.5 { + execsql { + SAVEPOINT two; + INSERT INTO t2 VALUES(5, 6); + PRAGMA lock_status; + } + } [list main reserved temp $templockstate aux1 reserved aux2 reserved] + do_test savepoint-10.2.6 { + execsql { SELECT * FROM t2 } + } {5 6} + do_test savepoint-10.2.7 { + execsql { ROLLBACK TO two } + execsql { SELECT * FROM t2 } + } {} + do_test savepoint-10.2.8 { + execsql { PRAGMA lock_status } + } [list main reserved temp $templockstate aux1 reserved aux2 reserved] + do_test savepoint-10.2.9 { + execsql { SELECT 'a', * FROM t1 ; SELECT 'b', * FROM t3 } + } {a 1 2 b 3 4} + do_test savepoint-10.2.9 { + execsql { + INSERT INTO t2 VALUES(5, 6); + RELEASE one; + } + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + SELECT * FROM t3; + } + } {1 2 5 6 3 4} + do_test savepoint-10.2.9 { + execsql { PRAGMA lock_status } + } [list main unlocked temp $templockstate aux1 unlocked aux2 unlocked] + + do_test savepoint-10.2.10 { + execsql { + SAVEPOINT one; + INSERT INTO t1 VALUES('a', 'b'); + SAVEPOINT two; + INSERT INTO t2 VALUES('c', 'd'); + SAVEPOINT three; + INSERT INTO t3 VALUES('e', 'f'); + } + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + SELECT * FROM t3; + } + } {1 2 a b 5 6 c d 3 4 e f} + do_test savepoint-10.2.11 { + execsql { ROLLBACK TO two } + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + SELECT * FROM t3; + } + } {1 2 a b 5 6 3 4} + do_test savepoint-10.2.12 { + execsql { + INSERT INTO t3 VALUES('g', 'h'); + ROLLBACK TO two; + } + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + SELECT * FROM t3; + } + } {1 2 a b 5 6 3 4} + do_test savepoint-10.2.13 { + execsql { ROLLBACK } + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + SELECT * FROM t3; + } + } {1 2 5 6 3 4} + do_test savepoint-10.2.14 { + execsql { PRAGMA lock_status } + } [list main unlocked temp $templockstate aux1 unlocked aux2 unlocked] +} + +#------------------------------------------------------------------------- +# The following tests - savepoint-11.* - test the interaction of +# savepoints and creating or dropping tables and indexes in +# auto-vacuum mode. +# +do_test savepoint-11.1 { + db close + forcedelete test.db + sqlite3 db test.db + execsql { PRAGMA auto_vacuum = full; } + wal_set_journal_mode + execsql { + CREATE TABLE t1(a, b, UNIQUE(a, b)); + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 VALUES(2, randstr(1000,1000)); + } +} {} +do_test savepoint-11.2 { + execsql { + SAVEPOINT one; + CREATE TABLE t2(a, b, UNIQUE(a, b)); + SAVEPOINT two; + CREATE TABLE t3(a, b, UNIQUE(a, b)); + } +} {} +integrity_check savepoint-11.3 +do_test savepoint-11.4 { + execsql { ROLLBACK TO two } +} {} +integrity_check savepoint-11.5 +do_test savepoint-11.6 { + execsql { + CREATE TABLE t3(a, b, UNIQUE(a, b)); + ROLLBACK TO one; + } +} {} +integrity_check savepoint-11.7 +do_test savepoint-11.8 { + execsql { ROLLBACK } + execsql { PRAGMA wal_checkpoint } + file size test.db +} {8192} + +do_test savepoint-11.9 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + DROP TABLE IF EXISTS t3; + } +} {} +do_test savepoint-11.10 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES(1, 2); + SAVEPOINT one; + INSERT INTO t2 VALUES(3, 4); + SAVEPOINT two; + DROP TABLE t1; + ROLLBACK TO two; + } + execsql {SELECT * FROM t2} +} {1 2 3 4} +do_test savepoint-11.11 { + execsql COMMIT +} {} +do_test savepoint-11.12 { + execsql {SELECT * FROM t2} +} {1 2 3 4} +wal_check_journal_mode savepoint-11.13 + +#------------------------------------------------------------------------- +# The following tests - savepoint-12.* - test the interaction of +# savepoints and "ON CONFLICT ROLLBACK" clauses. +# +do_test savepoint-12.1 { + execsql { + CREATE TABLE t4(a PRIMARY KEY, b); + INSERT INTO t4 VALUES(1, 'one'); + } +} {} +do_test savepoint-12.2 { + # The final statement of the following SQL hits a constraint when the + # conflict handling mode is "OR ROLLBACK" and there are a couple of + # open savepoints. At one point this would fail to clear the internal + # record of the open savepoints, resulting in an assert() failure + # later on. + # + catchsql { + BEGIN; + INSERT INTO t4 VALUES(2, 'two'); + SAVEPOINT sp1; + INSERT INTO t4 VALUES(3, 'three'); + SAVEPOINT sp2; + INSERT OR ROLLBACK INTO t4 VALUES(1, 'one'); + } +} {1 {column a is not unique}} +do_test savepoint-12.3 { + sqlite3_get_autocommit db +} {1} +do_test savepoint-12.4 { + execsql { SAVEPOINT one } +} {} +wal_check_journal_mode savepoint-12.5 + +#------------------------------------------------------------------------- +# The following tests - savepoint-13.* - test the interaction of +# savepoints and "journal_mode = off". +# +if {[wal_is_wal_mode]==0} { + do_test savepoint-13.1 { + db close + catch {forcedelete test.db} + sqlite3 db test.db + execsql { + BEGIN; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 2); + COMMIT; + PRAGMA journal_mode = off; + } + } {off} + do_test savepoint-13.2 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t1 SELECT a+4,b+4 FROM t1; + COMMIT; + } + } {} + do_test savepoint-13.3 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(9, 10); + SAVEPOINT s1; + INSERT INTO t1 VALUES(11, 12); + COMMIT; + } + } {} + do_test savepoint-13.4 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(13, 14); + SAVEPOINT s1; + INSERT INTO t1 VALUES(15, 16); + ROLLBACK TO s1; + ROLLBACK; + SELECT * FROM t1; + } + } {1 2 3 4 5 6 7 8 9 10 11 12} +} + +db close +delete_file test.db +do_multiclient_test tn { + do_test savepoint-14.$tn.1 { + sql1 { + CREATE TABLE foo(x); + INSERT INTO foo VALUES(1); + INSERT INTO foo VALUES(2); + } + sql2 { + BEGIN; + SELECT * FROM foo; + } + } {1 2} + do_test savepoint-14.$tn.2 { + sql1 { + SAVEPOINT one; + INSERT INTO foo VALUES(1); + } + csql1 { RELEASE one } + } {1 {database is locked}} + do_test savepoint-14.$tn.3 { + sql1 { ROLLBACK TO one } + sql2 { COMMIT } + sql1 { RELEASE one } + } {} + + do_test savepoint-14.$tn.4 { + sql2 { + BEGIN; + SELECT * FROM foo; + } + } {1 2} + do_test savepoint-14.$tn.5 { + sql1 { + SAVEPOINT one; + INSERT INTO foo VALUES(1); + } + csql1 { RELEASE one } + } {1 {database is locked}} + do_test savepoint-14.$tn.6 { + sql2 { COMMIT } + sql1 { + ROLLBACK TO one; + INSERT INTO foo VALUES(3); + INSERT INTO foo VALUES(4); + INSERT INTO foo VALUES(5); + RELEASE one; + } + } {} + do_test savepoint-14.$tn.7 { + sql2 { CREATE INDEX fooidx ON foo(x); } + sql3 { PRAGMA integrity_check } + } {ok} +} + +do_multiclient_test tn { + do_test savepoint-15.$tn.1 { + sql1 { + CREATE TABLE foo(x); + INSERT INTO foo VALUES(1); + INSERT INTO foo VALUES(2); + } + sql2 { BEGIN; SELECT * FROM foo; } + } {1 2} + do_test savepoint-15.$tn.2 { + sql1 { + PRAGMA locking_mode = EXCLUSIVE; + BEGIN; + INSERT INTO foo VALUES(3); + } + csql1 { COMMIT } + } {1 {database is locked}} + do_test savepoint-15.$tn.3 { + sql1 { ROLLBACK } + sql2 { COMMIT } + sql1 { + INSERT INTO foo VALUES(3); + PRAGMA locking_mode = NORMAL; + INSERT INTO foo VALUES(4); + } + sql2 { CREATE INDEX fooidx ON foo(x); } + sql3 { PRAGMA integrity_check } + } {ok} +} + +do_multiclient_test tn { + do_test savepoint-16.$tn.1 { + sql1 { + CREATE TABLE foo(x); + INSERT INTO foo VALUES(1); + INSERT INTO foo VALUES(2); + } + } {} + do_test savepoint-16.$tn.2 { + + db eval {SELECT * FROM foo} { + sql1 { INSERT INTO foo VALUES(3) } + sql2 { SELECT * FROM foo } + sql1 { INSERT INTO foo VALUES(4) } + break + } + + sql2 { CREATE INDEX fooidx ON foo(x); } + sql3 { PRAGMA integrity_check } + } {ok} + do_test savepoint-16.$tn.3 { + sql1 { SELECT * FROM foo } + } {1 2 3 4} +} + +#------------------------------------------------------------------------- +# This next block of tests verifies that a problem reported on the mailing +# list has been resolved. At one point the second "CREATE TABLE t6" would +# fail as table t6 still existed in the internal cache of the db schema +# (even though it had been removed from the database by the ROLLBACK +# command). +# +sqlite3 db test.db +do_execsql_test savepoint-17.1 { + BEGIN; + CREATE TABLE t6(a, b); + INSERT INTO t6 VALUES(1, 2); + SAVEPOINT one; + INSERT INTO t6 VALUES(3, 4); + ROLLBACK TO one; + SELECT * FROM t6; + ROLLBACK; +} {1 2} + +do_execsql_test savepoint-17.2 { + CREATE TABLE t6(a, b); +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/savepoint2.test b/components/external/SQLite-3.8.1/test/savepoint2.test new file mode 100644 index 0000000000000000000000000000000000000000..be1bdbd424539f2b58faaa07494b2f4215e89500 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/savepoint2.test @@ -0,0 +1,154 @@ +# 2008 December 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: savepoint2.test,v 1.5 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +# Tests in this file are quite similar to those run by trans.test and +# avtrans.test. +# + +proc signature {} { + return [db eval {SELECT count(*), md5sum(x) FROM t3}] +} + +do_test savepoint2-1 { + wal_set_journal_mode + execsql { + PRAGMA cache_size=10; + BEGIN; + CREATE TABLE t3(x TEXT); + INSERT INTO t3 VALUES(randstr(10,400)); + INSERT INTO t3 VALUES(randstr(10,400)); + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + INSERT INTO t3 SELECT randstr(10,400) FROM t3; + COMMIT; + SELECT count(*) FROM t3; + } +} {1024} +wal_check_journal_mode savepoint2-1.1 + +unset -nocomplain ::sig +unset -nocomplain SQL + +set iterations 20 + +set SQL(1) { + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; +} +set SQL(2) { + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; + DELETE FROM t3 WHERE random()%10!=0; + INSERT INTO t3 SELECT randstr(10,10)||x FROM t3; +} +set SQL(3) { + UPDATE t3 SET x = randstr(10, 400) WHERE random()%10; + INSERT INTO t3 SELECT x FROM t3 WHERE random()%10; + DELETE FROM t3 WHERE random()%10; +} +set SQL(4) { + INSERT INTO t3 SELECT randstr(10,400) FROM t3 WHERE (random()%10 == 0); +} + + + +for {set ii 2} {$ii < ($iterations+2)} {incr ii} { + + # Record the database signature. Optionally (every second run) open a + # transaction. In all cases open savepoint "one", which may or may + # not be a transaction savepoint, depending on whether or not a real + # transaction has been opened. + # + do_test savepoint2-$ii.1 { + if {$ii % 2} { execsql BEGIN } + set ::sig(one) [signature] + execsql "SAVEPOINT one" + } {} + + # Execute some SQL on the database. Then rollback to savepoint "one". + # Check that the database signature is as it was when "one" was opened. + # + do_test savepoint2-$ii.2 { + execsql $SQL(1) + execsql "ROLLBACK to one" + signature + } $::sig(one) + integrity_check savepoint2-$ii.2.1 + + # Execute some SQL. Then open savepoint "two". Savepoint "two" is therefore + # nested in savepoint "one". + # + do_test savepoint2-$ii.3 { + execsql $SQL(1) + set ::sig(two) [signature] + execsql "SAVEPOINT two" + } {} + + # More SQL changes. The rollback to savepoint "two". Check that the + # signature is as it was when savepoint "two" was opened. + # + do_test savepoint2-$ii.4 { + execsql $SQL(2) + execsql "ROLLBACK to two" + signature + } $::sig(two) + integrity_check savepoint2-$ii.4.1 + + # More SQL changes. The rollback to savepoint "two". Check that the + # signature is as it was when savepoint "two" was opened. + # + do_test savepoint2-$ii.5 { + execsql $SQL(2) + execsql "SAVEPOINT three" + execsql $SQL(3) + execsql "RELEASE three" + execsql "ROLLBACK to one" + signature + } $::sig(one) + + # By this point the database is in the same state as it was at the + # top of the for{} loop (everything having been rolled back by the + # "ROLLBACK TO one" command above). So make a few changes to the + # database and COMMIT the open transaction, so that the next iteration + # of the for{} loop works on a different dataset. + # + # The transaction being committed here may have been opened normally using + # "BEGIN", or may have been opened using a transaction savepoint created + # by the "SAVEPOINT one" statement. + # + do_test savepoint2-$ii.6 { + execsql $SQL(4) + execsql COMMIT + sqlite3_get_autocommit db + } {1} + integrity_check savepoint2-$ii.6.1 + + # Check that the connection is still running in WAL mode. + wal_check_journal_mode savepoint2-$ii.7 +} + +unset -nocomplain ::sig +unset -nocomplain SQL + +finish_test diff --git a/components/external/SQLite-3.8.1/test/savepoint3.test b/components/external/SQLite-3.8.1/test/savepoint3.test new file mode 100644 index 0000000000000000000000000000000000000000..0dcb0aceba1f0b621e385879ff359415e26b2ad1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/savepoint3.test @@ -0,0 +1,136 @@ +# 2008 December 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: savepoint3.test,v 1.5 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +source $testdir/malloc_common.tcl + +do_malloc_test savepoint3-1 -sqlprep { + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, 2, 3); +} -sqlbody { + SAVEPOINT one; + INSERT INTO t1 VALUES(4, 5, 6); + SAVEPOINT two; + DELETE FROM t1; + ROLLBACK TO two; + RELEASE one; +} + +do_malloc_test savepoint3-2 -sqlprep { + PRAGMA cache_size = 10; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(randstr(400,400), randstr(400,400), randstr(400,400)); + INSERT INTO t1 SELECT + randstr(400,400), randstr(400,400), randstr(400,400) FROM t1; + INSERT INTO t1 + SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1; + INSERT INTO t1 + SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1; + INSERT INTO t1 + SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1; + INSERT INTO t1 + SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1; + INSERT INTO t1 + SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1; + INSERT INTO t1 + SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1; + INSERT INTO t1 + SELECT randstr(400,400), randstr(400,400), randstr(400,400) FROM t1; +} -sqlbody { + PRAGMA cache_size = 10; + SAVEPOINT one; + DELETE FROM t1 WHERE rowid < 5; + SAVEPOINT two; + DELETE FROM t1 WHERE rowid > 10; + ROLLBACK TO two; + ROLLBACK TO one; + RELEASE one; +} + +do_ioerr_test savepoint3.3 -sqlprep { + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, randstr(1000,1000), randstr(1000,1000)); + INSERT INTO t1 VALUES(2, randstr(1000,1000), randstr(1000,1000)); +} -sqlbody { + BEGIN; + UPDATE t1 SET a = 3 WHERE a = 1; + SAVEPOINT one; + UPDATE t1 SET a = 4 WHERE a = 2; + COMMIT; +} -cleanup { + db eval { + SAVEPOINT one; + RELEASE one; + } +} + +# The following test does a really big savepoint rollback. One involving +# more than 4000 pages. The idea is to get a specific sqlite3BitvecSet() +# operation in pagerPlaybackSavepoint() to fail. +#do_malloc_test savepoint3-4 -sqlprep { +# BEGIN; +# CREATE TABLE t1(a, b); +# CREATE INDEX i1 ON t1(a); +# CREATE INDEX i2 ON t1(b); +# INSERT INTO t1 VALUES(randstr(500,500), randstr(500,500)); -- 1 +# INSERT INTO t1 VALUES(randstr(500,500), randstr(500,500)); -- 2 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 4 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 8 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 16 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 32 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 64 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 128 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 256 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 512 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 1024 +# INSERT INTO t1 SELECT randstr(500,500), randstr(500,500) FROM t1; -- 2048 +# COMMIT; +# BEGIN; +# SAVEPOINT abc; +# UPDATE t1 SET a = randstr(500,500); +#} -sqlbody { +# ROLLBACK TO abc; +#} + + +# Cause a specific malloc in savepoint rollback code to fail. +# +do_malloc_test savepoint3-4 -start 7 -sqlprep { + PRAGMA auto_vacuum = incremental; + PRAGMA cache_size = 1000; + + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + CREATE TABLE t3(a, b); + INSERT INTO t1 VALUES(1, randstr(500,500)); + INSERT INTO t1 VALUES(2, randstr(500,500)); + INSERT INTO t1 VALUES(3, randstr(500,500)); + DELETE FROM t1; + + BEGIN; + INSERT INTO t1 VALUES(1, randstr(500,500)); + INSERT INTO t1 VALUES(2, randstr(500,500)); + INSERT INTO t1 VALUES(3, randstr(500,500)); + DROP TABLE t3; -- Page 5 of the database file is now free. + DROP TABLE t2; -- Page 4 of the database file is now free. + + SAVEPOINT abc; + PRAGMA incremental_vacuum; +} -sqlbody { + ROLLBACK TO abc; +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/savepoint4.test b/components/external/SQLite-3.8.1/test/savepoint4.test new file mode 100644 index 0000000000000000000000000000000000000000..f8c5b713c2fef432a24fd5bfc718a2845913db10 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/savepoint4.test @@ -0,0 +1,169 @@ +# 2008 December 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: savepoint4.test,v 1.7 2009/06/09 15:25:33 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !crashtest { + finish_test + return +} + +proc signature {} { + return [db eval {SELECT count(*), md5sum(x) FROM t1}] +} + +set ITERATIONS 25 ;# Number of iterations for savepoint4-1 +set ITERATIONS2 13 ;# Number of iterations for savepoint4-2 +expr srand(0) + +do_test savepoint4-1 { + execsql { + PRAGMA cache_size=10; + BEGIN; + CREATE TABLE t1(x TEXT); + INSERT INTO t1 VALUES(randstr(10,400)); + INSERT INTO t1 VALUES(randstr(10,400)); + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + COMMIT; + SELECT count(*) FROM t1; + } +} {1024} + + +unset -nocomplain ::sig + +for {set ii 1} {$ii<=$ITERATIONS} {incr ii} { + set ::sig [signature] + + for {set iDelay 1 ; set crashed 1} {$crashed} {incr iDelay} { + + do_test savepoint4-1.$ii.1.$iDelay { + set ret [crashsql -delay $iDelay -file test.db-journal { + PRAGMA cache_size = 20; + SAVEPOINT one; + DELETE FROM t1 WHERE random()%2==0; + SAVEPOINT two; + INSERT INTO t1 SELECT randstr(10,10)||x FROM t1; + ROLLBACK TO two; + UPDATE t1 SET x = randstr(10, 400) WHERE random()%10; + RELEASE two; + ROLLBACK TO one; + RELEASE one; + }] + signature + } $::sig + + set crashed [lindex $ret 0] + integrity_check savepoint4-1.$ii.1.$iDelay.integrity + } + + do_test savepoint4-1.$ii.2 { + execsql { + DELETE FROM t1 WHERE random()%10==0; + INSERT INTO t1 SELECT randstr(10,10)||x FROM t1 WHERE random()%9==0; + } + } {} +} + +do_test savepoint4-2 { + execsql { + PRAGMA cache_size=10; + DROP TABLE IF EXISTS t1; + BEGIN; + CREATE TABLE t1(x TEXT); + CREATE INDEX i1 ON t1(x); + INSERT INTO t1 VALUES(randstr(10,400)); + INSERT INTO t1 VALUES(randstr(10,400)); + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + INSERT INTO t1 SELECT randstr(10,400) FROM t1; + COMMIT; + SELECT count(*) FROM t1; + } +} {256} + +for {set ii 1} {$ii<=$ITERATIONS2} {incr ii} { + set ::sig [signature] + set file test.db-journal + + for {set iDelay 1 ; set crashed 1} {$crashed} {incr iDelay} { + + do_test savepoint4-2.$ii.1.$iDelay { + + set ret [crashsql -delay $iDelay -file $file { + SAVEPOINT one; + INSERT INTO t1 SELECT * FROM t1 WHERE rowid<50; + ROLLBACK TO one; + INSERT INTO t1 SELECT * FROM t1 WHERE rowid<50; + SAVEPOINT two; + DELETE FROM t1 WHERE (random()%10)==0; + SAVEPOINT three; + DELETE FROM t1 WHERE (random()%10)==0; + SAVEPOINT four; + DELETE FROM t1 WHERE (random()%10)==0; + RELEASE two; + + SAVEPOINT three; + UPDATE t1 SET x = substr(x||x, 12, 100000) WHERE (rowid%12)==0; + SAVEPOINT four; + UPDATE t1 SET x = substr(x||x, 14, 100000) WHERE (rowid%14)==0; + ROLLBACK TO three; + UPDATE t1 SET x = substr(x||x, 13, 100000) WHERE (rowid%13)==0; + RELEASE three; + + DELETE FROM t1 WHERE rowid > ( + SELECT rowid FROM t1 ORDER BY rowid ASC LIMIT 1 OFFSET 256 + ); + RELEASE one; + }] + + set crashed [lindex $ret 0] + if {$crashed} { + signature + } else { + set ::sig + } + } $::sig + + integrity_check savepoint4-2.$ii.1.$iDelay.integrity + + if {$crashed == 0 && $file == "test.db-journal"} { + set crashed 1 + set iDelay 0 + set file test.db + set ::sig [signature] + } + } + + do_test savepoint4-2.$ii.2 { + execsql { + DELETE FROM t1 WHERE random()%10==0; + INSERT INTO t1 SELECT randstr(10,10)||x FROM t1 WHERE random()%9==0; + } + } {} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/savepoint5.test b/components/external/SQLite-3.8.1/test/savepoint5.test new file mode 100644 index 0000000000000000000000000000000000000000..dc5268b3c366062195e1e58d8b62179207312680 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/savepoint5.test @@ -0,0 +1,46 @@ +# 2009 January 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Verify that a SAVEPOINT on a new, empty database followed by a +# ROLLBACK TO that savepoint starts over again with another new +# empty database. +# +# $Id: savepoint5.test,v 1.1 2009/01/02 21:08:09 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test savepoint5-1.1 { + db eval { + SAVEPOINT sp1; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + SELECT count(*) FROM sqlite_master; + SELECT * FROM t1; + } +} {1 1} +do_test savepoint5-1.2 { + db eval { + ROLLBACK TO sp1; + SELECT count(*) FROM sqlite_master; + } +} {0} +do_test savepoint5-1.3 { + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + SELECT count(*) FROM sqlite_master; + SELECT * FROM t1; + } +} {1 1} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/savepoint6.test b/components/external/SQLite-3.8.1/test/savepoint6.test new file mode 100644 index 0000000000000000000000000000000000000000..b1d0d46f5c9f3beef77133eb0e620059828e6871 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/savepoint6.test @@ -0,0 +1,281 @@ +# 2009 January 3 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: savepoint6.test,v 1.4 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc sql {zSql} { + uplevel db eval [list $zSql] + #puts stderr "$zSql ;" +} + +set DATABASE_SCHEMA { + PRAGMA auto_vacuum = incremental; + CREATE TABLE t1(x, y); + CREATE UNIQUE INDEX i1 ON t1(x); + CREATE INDEX i2 ON t1(y); +} + +if {0==[info exists ::G(savepoint6_iterations)]} { + set ::G(savepoint6_iterations) 1000 +} + +#-------------------------------------------------------------------------- +# In memory database state. +# +# ::lSavepoint is a list containing one entry for each active savepoint. The +# first entry in the list corresponds to the most recently opened savepoint. +# Each entry consists of two elements: +# +# 1. The savepoint name. +# +# 2. A serialized Tcl array representing the contents of table t1 at the +# start of the savepoint. The keys of the array are the x values. The +# values are the y values. +# +# Array ::aEntry contains the contents of database table t1. Array keys are +# x values, the array data values are y values. +# +set lSavepoint [list] +array set aEntry [list] + +proc x_to_y {x} { + set nChar [expr int(rand()*250) + 250] + set str " $nChar [string repeat $x. $nChar]" + string range $str 1 $nChar +} +#-------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Procs to operate on database: +# +# savepoint NAME +# rollback NAME +# release NAME +# +# insert_rows XVALUES +# delete_rows XVALUES +# +proc savepoint {zName} { + catch { sql "SAVEPOINT $zName" } + lappend ::lSavepoint [list $zName [array get ::aEntry]] +} + +proc rollback {zName} { + catch { sql "ROLLBACK TO $zName" } + for {set i [expr {[llength $::lSavepoint]-1}]} {$i>=0} {incr i -1} { + set zSavepoint [lindex $::lSavepoint $i 0] + if {$zSavepoint eq $zName} { + unset -nocomplain ::aEntry + array set ::aEntry [lindex $::lSavepoint $i 1] + + + if {$i+1 < [llength $::lSavepoint]} { + set ::lSavepoint [lreplace $::lSavepoint [expr $i+1] end] + } + break + } + } +} + +proc release {zName} { + catch { sql "RELEASE $zName" } + for {set i [expr {[llength $::lSavepoint]-1}]} {$i>=0} {incr i -1} { + set zSavepoint [lindex $::lSavepoint $i 0] + if {$zSavepoint eq $zName} { + set ::lSavepoint [lreplace $::lSavepoint $i end] + break + } + } + + if {[llength $::lSavepoint] == 0} { + #puts stderr "-- End of transaction!!!!!!!!!!!!!" + } +} + +proc insert_rows {lX} { + foreach x $lX { + set y [x_to_y $x] + + # Update database [db] + sql "INSERT OR REPLACE INTO t1 VALUES($x, '$y')" + + # Update the Tcl database. + set ::aEntry($x) $y + } +} + +proc delete_rows {lX} { + foreach x $lX { + # Update database [db] + sql "DELETE FROM t1 WHERE x = $x" + + # Update the Tcl database. + unset -nocomplain ::aEntry($x) + } +} +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Proc to compare database content with the in-memory representation. +# +# checkdb +# +proc checkdb {} { + set nEntry [db one {SELECT count(*) FROM t1}] + set nEntry2 [array size ::aEntry] + if {$nEntry != $nEntry2} { + error "$nEntry entries in database, $nEntry2 entries in array" + } + db eval {SELECT x, y FROM t1} { + if {![info exists ::aEntry($x)]} { + error "Entry $x exists in database, but not in array" + } + if {$::aEntry($x) ne $y} { + error "Entry $x is set to {$y} in database, {$::aEntry($x)} in array" + } + } + + db eval { PRAGMA integrity_check } +} +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Proc to return random set of x values. +# +# random_integers +# +proc random_integers {nRes nRange} { + set ret [list] + for {set i 0} {$i<$nRes} {incr i} { + lappend ret [expr int(rand()*$nRange)] + } + return $ret +} +#------------------------------------------------------------------------- + +proc database_op {} { + set i [expr int(rand()*2)] + if {$i==0} { + insert_rows [random_integers 100 1000] + } + if {$i==1} { + delete_rows [random_integers 100 1000] + set i [expr int(rand()*3)] + if {$i==0} { + sql {PRAGMA incremental_vacuum} + } + } +} + +proc savepoint_op {} { + set names {one two three four five} + set cmds {savepoint savepoint savepoint savepoint release rollback} + + set C [lindex $cmds [expr int(rand()*6)]] + set N [lindex $names [expr int(rand()*5)]] + + #puts stderr " $C $N ; " + #flush stderr + + $C $N + return ok +} + +expr srand(0) + +############################################################################ +############################################################################ +# Start of test cases. + +do_test savepoint6-1.1 { + sql $DATABASE_SCHEMA +} {} +do_test savepoint6-1.2 { + insert_rows { + 497 166 230 355 779 588 394 317 290 475 362 193 805 851 564 + 763 44 930 389 819 765 760 966 280 538 414 500 18 25 287 320 + 30 382 751 87 283 981 429 630 974 421 270 810 405 + } + + savepoint one + insert_rows 858 + delete_rows 930 + savepoint two + execsql {PRAGMA incremental_vacuum} + savepoint three + insert_rows 144 + rollback three + rollback two + release one + + execsql {SELECT count(*) FROM t1} +} {44} + +foreach zSetup [list { + set testname normal + sqlite3 db test.db +} { + if {[wal_is_wal_mode]} continue + set testname tempdb + sqlite3 db "" +} { + if {[permutation] eq "journaltest"} { + continue + } + set testname nosync + sqlite3 db test.db + sql { PRAGMA synchronous = off } +} { + set testname smallcache + sqlite3 db test.db + sql { PRAGMA cache_size = 10 } +}] { + + unset -nocomplain ::lSavepoint + unset -nocomplain ::aEntry + + catch { db close } + forcedelete test.db test.db-wal test.db-journal + eval $zSetup + sql $DATABASE_SCHEMA + + wal_set_journal_mode + + do_test savepoint6-$testname.setup { + savepoint one + insert_rows [random_integers 100 1000] + release one + checkdb + } {ok} + + for {set i 0} {$i < $::G(savepoint6_iterations)} {incr i} { + do_test savepoint6-$testname.$i.1 { + savepoint_op + checkdb + } {ok} + + do_test savepoint6-$testname.$i.2 { + database_op + database_op + checkdb + } {ok} + } + + wal_check_journal_mode savepoint6-$testname.walok +} + +unset -nocomplain ::lSavepoint +unset -nocomplain ::aEntry + +finish_test diff --git a/components/external/SQLite-3.8.1/test/savepoint7.test b/components/external/SQLite-3.8.1/test/savepoint7.test new file mode 100644 index 0000000000000000000000000000000000000000..bc99187d27e9729581a9f6f7d198425fce00ec5f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/savepoint7.test @@ -0,0 +1,96 @@ +# 2012 March 31 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Focus on the interaction between RELEASE and ROLLBACK TO with +# pending query aborts. See ticket [27ca74af3c083f787a1c44b11fbb7c53bdbbcf1e]. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# The RELEASE of an inner savepoint should not effect pending queries. +# +do_test savepoint7-1.1 { + db eval { + CREATE TABLE t1(a,b,c); + CREATE TABLE t2(x,y,z); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(4,5,6); + INSERT INTO t1 VALUES(7,8,9); + SAVEPOINT x1; + } + db eval {SELECT * FROM t1} { + db eval { + SAVEPOINT x2; + INSERT INTO t2 VALUES($a,$b,$c); + RELEASE x2; + } + } + db eval {SELECT * FROM t2; RELEASE x1} +} {1 2 3 4 5 6 7 8 9} + +do_test savepoint7-1.2 { + db eval {DELETE FROM t2;} + db eval {SELECT * FROM t1} { + db eval { + SAVEPOINT x2; + INSERT INTO t2 VALUES($a,$b,$c); + RELEASE x2; + } + } + db eval {SELECT * FROM t2} +} {1 2 3 4 5 6 7 8 9} + +do_test savepoint7-1.3 { + db eval {DELETE FROM t2; BEGIN;} + db eval {SELECT * FROM t1} { + db eval { + SAVEPOINT x2; + INSERT INTO t2 VALUES($a,$b,$c); + RELEASE x2; + } + } + db eval {SELECT * FROM t2; ROLLBACK;} +} {1 2 3 4 5 6 7 8 9} + +# However, a ROLLBACK of an inner savepoint will abort all queries, including +# queries in outer contexts. +# +do_test savepoint7-2.1 { + db eval {DELETE FROM t2; SAVEPOINT x1;} + set rc [catch { + db eval {SELECT * FROM t1} { + db eval { + SAVEPOINT x2; + INSERT INTO t2 VALUES($a,$b,$c); + ROLLBACK TO x2; + } + } + } msg] + db eval {RELEASE x1} + list $rc $msg [db eval {SELECT * FROM t2}] +} {1 {callback requested query abort} {}} + +do_test savepoint7-2.2 { + db eval {DELETE FROM t2;} + set rc [catch { + db eval {SELECT * FROM t1} { + db eval { + SAVEPOINT x2; + INSERT INTO t2 VALUES($a,$b,$c); + ROLLBACK TO x2; + } + } + } msg] + list $rc $msg [db eval {SELECT * FROM t2}] +} {1 {callback requested query abort} {}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/schema.test b/components/external/SQLite-3.8.1/test/schema.test new file mode 100644 index 0000000000000000000000000000000000000000..afca39ed60a484b3b3c2ff72e4351c3c26b9eeb0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/schema.test @@ -0,0 +1,391 @@ +# 2005 Jan 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file tests the various conditions under which an SQLITE_SCHEMA +# error should be returned. +# +# $Id: schema.test,v 1.9 2009/02/04 17:40:58 drh Exp $ + +#--------------------------------------------------------------------- +# When any of the following types of SQL statements or actions are +# executed, all pre-compiled statements are invalidated. An attempt +# to execute an invalidated statement always returns SQLITE_SCHEMA. +# +# CREATE/DROP TABLE...................................schema-1.* +# CREATE/DROP VIEW....................................schema-2.* +# CREATE/DROP TRIGGER.................................schema-3.* +# CREATE/DROP INDEX...................................schema-4.* +# DETACH..............................................schema-5.* +# Deleting a user-function............................schema-6.* +# Deleting a collation sequence.......................schema-7.* +# Setting or changing the authorization function......schema-8.* +# Rollback of a DDL statement.........................schema-12.* +# +# Test cases schema-9.* and schema-10.* test some specific bugs +# that came up during development. +# +# Test cases schema-11.* test that it is impossible to delete or +# change a collation sequence or user-function while SQL statements +# are executing. Adding new collations or functions is allowed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test schema-1.1 { + set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + CREATE TABLE abc(a, b, c); + } + sqlite3_step $::STMT +} {SQLITE_ERROR} +do_test schema-1.2 { + sqlite3_finalize $::STMT +} {SQLITE_SCHEMA} +do_test schema-1.3 { + set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + DROP TABLE abc; + } + sqlite3_step $::STMT +} {SQLITE_ERROR} +do_test schema-1.4 { + sqlite3_finalize $::STMT +} {SQLITE_SCHEMA} + +ifcapable view { + do_test schema-2.1 { + set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + CREATE VIEW v1 AS SELECT * FROM sqlite_master; + } + sqlite3_step $::STMT + } {SQLITE_ERROR} + do_test schema-2.2 { + sqlite3_finalize $::STMT + } {SQLITE_SCHEMA} + do_test schema-2.3 { + set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + DROP VIEW v1; + } + sqlite3_step $::STMT + } {SQLITE_ERROR} + do_test schema-2.4 { + sqlite3_finalize $::STMT + } {SQLITE_SCHEMA} +} + +ifcapable trigger { + do_test schema-3.1 { + execsql { + CREATE TABLE abc(a, b, c); + } + set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + CREATE TRIGGER abc_trig AFTER INSERT ON abc BEGIN + SELECT 1, 2, 3; + END; + } + sqlite3_step $::STMT + } {SQLITE_ERROR} + do_test schema-3.2 { + sqlite3_finalize $::STMT + } {SQLITE_SCHEMA} + do_test schema-3.3 { + set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + DROP TRIGGER abc_trig; + } + sqlite3_step $::STMT + } {SQLITE_ERROR} + do_test schema-3.4 { + sqlite3_finalize $::STMT + } {SQLITE_SCHEMA} +} + +do_test schema-4.1 { + catchsql { + CREATE TABLE abc(a, b, c); + } + set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + CREATE INDEX abc_index ON abc(a); + } + sqlite3_step $::STMT +} {SQLITE_ERROR} +do_test schema-4.2 { + sqlite3_finalize $::STMT +} {SQLITE_SCHEMA} +do_test schema-4.3 { + set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + DROP INDEX abc_index; + } + sqlite3_step $::STMT +} {SQLITE_ERROR} +do_test schema-4.4 { + sqlite3_finalize $::STMT +} {SQLITE_SCHEMA} + +#--------------------------------------------------------------------- +# Tests 5.1 to 5.4 check that prepared statements are invalidated when +# a database is DETACHed (but not when one is ATTACHed). +# +ifcapable attach { + do_test schema-5.1 { + set sql {SELECT * FROM abc;} + set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL] + execsql { + ATTACH 'test2.db' AS aux; + } + sqlite3_step $::STMT + } {SQLITE_DONE} + do_test schema-5.2 { + sqlite3_reset $::STMT + } {SQLITE_OK} + do_test schema-5.3 { + execsql { + DETACH aux; + } + sqlite3_step $::STMT + } {SQLITE_ERROR} + do_test schema-5.4 { + sqlite3_finalize $::STMT + } {SQLITE_SCHEMA} +} + +#--------------------------------------------------------------------- +# Tests 6.* check that prepared statements are invalidated when +# a user-function is deleted (but not when one is added). +do_test schema-6.1 { + set sql {SELECT * FROM abc;} + set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL] + db function hello_function {} + sqlite3_step $::STMT +} {SQLITE_DONE} +do_test schema-6.2 { + sqlite3_reset $::STMT +} {SQLITE_OK} +do_test schema-6.3 { + sqlite_delete_function $::DB hello_function + sqlite3_step $::STMT +} {SQLITE_ERROR} +do_test schema-6.4 { + sqlite3_finalize $::STMT +} {SQLITE_SCHEMA} + +#--------------------------------------------------------------------- +# Tests 7.* check that prepared statements are invalidated when +# a collation sequence is deleted (but not when one is added). +# +ifcapable utf16 { + do_test schema-7.1 { + set sql {SELECT * FROM abc;} + set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL] + add_test_collate $::DB 1 1 1 + sqlite3_step $::STMT + } {SQLITE_DONE} + do_test schema-7.2 { + sqlite3_reset $::STMT + } {SQLITE_OK} + do_test schema-7.3 { + add_test_collate $::DB 0 0 0 + sqlite3_step $::STMT + } {SQLITE_ERROR} + do_test schema-7.4 { + sqlite3_finalize $::STMT + } {SQLITE_SCHEMA} +} + +#--------------------------------------------------------------------- +# Tests 8.1 and 8.2 check that prepared statements are invalidated when +# the authorization function is set. +# +ifcapable auth { + do_test schema-8.1 { + set ::STMT [sqlite3_prepare $::DB {SELECT * FROM sqlite_master} -1 TAIL] + db auth {} + sqlite3_step $::STMT + } {SQLITE_ERROR} + do_test schema-8.3 { + sqlite3_finalize $::STMT + } {SQLITE_SCHEMA} +} + +#--------------------------------------------------------------------- +# schema-9.1: Test that if a table is dropped by one database connection, +# other database connections are aware of the schema change. +# schema-9.2: Test that if a view is dropped by one database connection, +# other database connections are aware of the schema change. +# +do_test schema-9.1 { + sqlite3 db2 test.db + execsql { + DROP TABLE abc; + } db2 + db2 close + catchsql { + SELECT * FROM abc; + } +} {1 {no such table: abc}} +execsql { + CREATE TABLE abc(a, b, c); +} +ifcapable view { + do_test schema-9.2 { + execsql { + CREATE VIEW abcview AS SELECT * FROM abc; + } + sqlite3 db2 test.db + execsql { + DROP VIEW abcview; + } db2 + db2 close + catchsql { + SELECT * FROM abcview; + } + } {1 {no such table: abcview}} +} + +#--------------------------------------------------------------------- +# Test that if a CREATE TABLE statement fails because there are other +# btree cursors open on the same database file it does not corrupt +# the sqlite_master table. +# +# 2007-05-02: These tests have been overcome by events. Open btree +# cursors no longer block CREATE TABLE. But there is no reason not +# to keep the tests in the test suite. +# +do_test schema-10.1 { + execsql { + INSERT INTO abc VALUES(1, 2, 3); + } + set sql {SELECT * FROM abc} + set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL] + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test schema-10.2 { + catchsql { + CREATE TABLE t2(a, b, c); + } +} {0 {}} +do_test schema-10.3 { + sqlite3_finalize $::STMT +} {SQLITE_OK} +do_test schema-10.4 { + sqlite3 db2 test.db + execsql { + SELECT * FROM abc + } db2 +} {1 2 3} +do_test schema-10.5 { + db2 close +} {} + +#--------------------------------------------------------------------- +# Attempting to delete or replace a user-function or collation sequence +# while there are active statements returns an SQLITE_BUSY error. +# +# schema-11.1 - 11.4: User function. +# schema-11.5 - 11.8: Collation sequence. +# +do_test schema-11.1 { + db function tstfunc {} + set sql {SELECT * FROM abc} + set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL] + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test schema-11.2 { + sqlite_delete_function $::DB tstfunc +} {SQLITE_BUSY} +do_test schema-11.3 { + set rc [catch { + db function tstfunc {} + } msg] + list $rc $msg +} {1 {unable to delete/modify user-function due to active statements}} +do_test schema-11.4 { + sqlite3_finalize $::STMT +} {SQLITE_OK} +do_test schema-11.5 { + db collate tstcollate {} + set sql {SELECT * FROM abc} + set ::STMT [sqlite3_prepare $::DB $sql -1 TAIL] + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test schema-11.6 { + sqlite_delete_collation $::DB tstcollate +} {SQLITE_BUSY} +do_test schema-11.7 { + set rc [catch { + db collate tstcollate {} + } msg] + list $rc $msg +} {1 {unable to delete/modify collation sequence due to active statements}} +do_test schema-11.8 { + sqlite3_finalize $::STMT +} {SQLITE_OK} + +# The following demonstrates why statements need to be expired whenever +# there is a rollback (explicit or otherwise). +# +do_test schema-12.1 { + # Begin a transaction and create a table. This increments + # the schema cookie. Then compile an SQL statement, using + # the current (incremented) value of the cookie. + execsql { + BEGIN; + CREATE TABLE t3(a, b, c); + } + set ::STMT [sqlite3_prepare $::DB "CREATE TABLE t4(a,b,c)" -1 TAIL] + + # Rollback the transaction, resetting the schema cookie to the value + # it had at the start of this test case. Then create a table, + # incrementing the schema cookie. + execsql { + ROLLBACK; + CREATE TABLE t4(a, b, c); + } + + # The schema cookie now has the same value as it did when SQL statement + # $::STMT was prepared. So unless it has been expired, it would be + # possible to run the "CREATE TABLE t4" statement and create a + # duplicate table. + list [sqlite3_step $::STMT] [sqlite3_finalize $::STMT] +} {SQLITE_ERROR SQLITE_SCHEMA} + +ifcapable {auth} { + +do_test schema-13.1 { + set S [sqlite3_prepare_v2 db "SELECT * FROM sqlite_master" -1 dummy] + db function hello hello + db function hello {} + db auth auth + proc auth {args} { + if {[lindex $args 0] == "SQLITE_READ"} {return SQLITE_DENY} + return SQLITE_OK + } + sqlite3_step $S +} {SQLITE_AUTH} + +do_test schema-13.2 { + sqlite3_step $S +} {SQLITE_AUTH} + +do_test schema-13.3 { + sqlite3_finalize $S +} {SQLITE_AUTH} + +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/schema2.test b/components/external/SQLite-3.8.1/test/schema2.test new file mode 100644 index 0000000000000000000000000000000000000000..61d7f731d32999953652d3c193fb5acf0243987e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/schema2.test @@ -0,0 +1,340 @@ +# 2006 November 08 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file tests the various conditions under which an SQLITE_SCHEMA +# error should be returned. This is a copy of schema.test that +# has been altered to use sqlite3_prepare_v2 instead of sqlite3_prepare +# +# $Id: schema2.test,v 1.4 2009/02/04 17:40:58 drh Exp $ + +#--------------------------------------------------------------------- +# When any of the following types of SQL statements or actions are +# executed, all pre-compiled statements are invalidated. An attempt +# to execute an invalidated statement always returns SQLITE_SCHEMA. +# +# CREATE/DROP TABLE...................................schema2-1.* +# CREATE/DROP VIEW....................................schema2-2.* +# CREATE/DROP TRIGGER.................................schema2-3.* +# CREATE/DROP INDEX...................................schema2-4.* +# DETACH..............................................schema2-5.* +# Deleting a user-function............................schema2-6.* +# Deleting a collation sequence.......................schema2-7.* +# Setting or changing the authorization function......schema2-8.* +# +# Test cases schema2-9.* and schema2-10.* test some specific bugs +# that came up during development. +# +# Test cases schema2-11.* test that it is impossible to delete or +# change a collation sequence or user-function while SQL statements +# are executing. Adding new collations or functions is allowed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test schema2-1.1 { + set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + CREATE TABLE abc(a, b, c); + } + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test schema2-1.2 { + sqlite3_finalize $::STMT +} {SQLITE_OK} +do_test schema2-1.3 { + set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + DROP TABLE abc; + } + sqlite3_step $::STMT +} {SQLITE_DONE} +do_test schema2-1.4 { + sqlite3_finalize $::STMT +} {SQLITE_OK} + + +ifcapable view { + do_test schema2-2.1 { + set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + CREATE VIEW v1 AS SELECT * FROM sqlite_master; + } + sqlite3_step $::STMT + } {SQLITE_ROW} + do_test schema2-2.2 { + sqlite3_finalize $::STMT + } {SQLITE_OK} + do_test schema2-2.3 { + set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + DROP VIEW v1; + } + sqlite3_step $::STMT + } {SQLITE_DONE} + do_test schema2-2.4 { + sqlite3_finalize $::STMT + } {SQLITE_OK} +} + +ifcapable trigger { + do_test schema2-3.1 { + execsql { + CREATE TABLE abc(a, b, c); + } + set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + CREATE TRIGGER abc_trig AFTER INSERT ON abc BEGIN + SELECT 1, 2, 3; + END; + } + sqlite3_step $::STMT + } {SQLITE_ROW} + do_test schema2-3.2 { + sqlite3_finalize $::STMT + } {SQLITE_OK} + do_test schema2-3.3 { + set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + DROP TRIGGER abc_trig; + } + sqlite3_step $::STMT + } {SQLITE_ROW} + do_test schema2-3.4 { + sqlite3_finalize $::STMT + } {SQLITE_OK} +} + +do_test schema2-4.1 { + catchsql { + CREATE TABLE abc(a, b, c); + } + set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + CREATE INDEX abc_index ON abc(a); + } + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test schema2-4.2 { + sqlite3_finalize $::STMT +} {SQLITE_OK} +do_test schema2-4.3 { + set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL] + execsql { + DROP INDEX abc_index; + } + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test schema2-4.4 { + sqlite3_finalize $::STMT +} {SQLITE_OK} + +#--------------------------------------------------------------------- +# Tests 5.1 to 5.4 check that prepared statements are invalidated when +# a database is DETACHed (but not when one is ATTACHed). +# +ifcapable attach { + do_test schema2-5.1 { + set sql {SELECT * FROM abc;} + set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL] + execsql { + ATTACH 'test2.db' AS aux; + } + sqlite3_step $::STMT + } {SQLITE_DONE} + do_test schema2-5.2 { + sqlite3_reset $::STMT + } {SQLITE_OK} + do_test schema2-5.3 { + execsql { + DETACH aux; + } + sqlite3_step $::STMT + } {SQLITE_DONE} + do_test schema2-5.4 { + sqlite3_finalize $::STMT + } {SQLITE_OK} +} + +#--------------------------------------------------------------------- +# Tests 6.* check that prepared statements are invalidated when +# a user-function is deleted (but not when one is added). +do_test schema2-6.1 { + set sql {SELECT * FROM abc;} + set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL] + db function hello_function {} + sqlite3_step $::STMT +} {SQLITE_DONE} +do_test schema2-6.2 { + sqlite3_reset $::STMT +} {SQLITE_OK} +do_test schema2-6.3 { + sqlite_delete_function $::DB hello_function + sqlite3_step $::STMT +} {SQLITE_DONE} +do_test schema2-6.4 { + sqlite3_finalize $::STMT +} {SQLITE_OK} + +#--------------------------------------------------------------------- +# Tests 7.* check that prepared statements are invalidated when +# a collation sequence is deleted (but not when one is added). +# +ifcapable utf16 { + do_test schema2-7.1 { + set sql {SELECT * FROM abc;} + set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL] + add_test_collate $::DB 1 1 1 + sqlite3_step $::STMT + } {SQLITE_DONE} + do_test schema2-7.2 { + sqlite3_reset $::STMT + } {SQLITE_OK} + do_test schema2-7.3 { + add_test_collate $::DB 0 0 0 + sqlite3_step $::STMT + } {SQLITE_DONE} + do_test schema2-7.4 { + sqlite3_finalize $::STMT + } {SQLITE_OK} +} + +#--------------------------------------------------------------------- +# Tests 8.1 and 8.2 check that prepared statements are invalidated when +# the authorization function is set. +# +ifcapable auth { + do_test schema2-8.1 { + set ::STMT [sqlite3_prepare_v2 $::DB {SELECT * FROM sqlite_master} -1 TAIL] + db auth {} + sqlite3_step $::STMT + } {SQLITE_ROW} + do_test schema2-8.3 { + sqlite3_finalize $::STMT + } {SQLITE_OK} +} + +#--------------------------------------------------------------------- +# schema2-9.1: Test that if a table is dropped by one database connection, +# other database connections are aware of the schema change. +# schema2-9.2: Test that if a view is dropped by one database connection, +# other database connections are aware of the schema change. +# +do_test schema2-9.1 { + sqlite3 db2 test.db + execsql { + DROP TABLE abc; + } db2 + db2 close + catchsql { + SELECT * FROM abc; + } +} {1 {no such table: abc}} +execsql { + CREATE TABLE abc(a, b, c); +} +ifcapable view { + do_test schema2-9.2 { + execsql { + CREATE VIEW abcview AS SELECT * FROM abc; + } + sqlite3 db2 test.db + execsql { + DROP VIEW abcview; + } db2 + db2 close + catchsql { + SELECT * FROM abcview; + } + } {1 {no such table: abcview}} +} + +#--------------------------------------------------------------------- +# Test that if a CREATE TABLE statement fails because there are other +# btree cursors open on the same database file it does not corrupt +# the sqlite_master table. +# +# 2007-05-02: These tests have been overcome by events. Open btree +# cursors no longer block CREATE TABLE. But there is no reason not +# to keep the tests in the test suite. +# +do_test schema2-10.1 { + execsql { + INSERT INTO abc VALUES(1, 2, 3); + } + set sql {SELECT * FROM abc} + set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL] + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test schema2-10.2 { + catchsql { + CREATE TABLE t2(a, b, c); + } +} {0 {}} +do_test schema2-10.3 { + sqlite3_finalize $::STMT +} {SQLITE_OK} +do_test schema2-10.4 { + sqlite3 db2 test.db + execsql { + SELECT * FROM abc + } db2 +} {1 2 3} +do_test schema2-10.5 { + db2 close +} {} + +#--------------------------------------------------------------------- +# Attempting to delete or replace a user-function or collation sequence +# while there are active statements returns an SQLITE_BUSY error. +# +# schema2-11.1 - 11.4: User function. +# schema2-11.5 - 11.8: Collation sequence. +# +do_test schema2-11.1 { + db function tstfunc {} + set sql {SELECT * FROM abc} + set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL] + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test schema2-11.2 { + sqlite_delete_function $::DB tstfunc +} {SQLITE_BUSY} +do_test schema2-11.3 { + set rc [catch { + db function tstfunc {} + } msg] + list $rc $msg +} {1 {unable to delete/modify user-function due to active statements}} +do_test schema2-11.4 { + sqlite3_finalize $::STMT +} {SQLITE_OK} +do_test schema2-11.5 { + db collate tstcollate {} + set sql {SELECT * FROM abc} + set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 TAIL] + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test schema2-11.6 { + sqlite_delete_collation $::DB tstcollate +} {SQLITE_BUSY} +do_test schema2-11.7 { + set rc [catch { + db collate tstcollate {} + } msg] + list $rc $msg +} {1 {unable to delete/modify collation sequence due to active statements}} +do_test schema2-11.8 { + sqlite3_finalize $::STMT +} {SQLITE_OK} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/schema3.test b/components/external/SQLite-3.8.1/test/schema3.test new file mode 100644 index 0000000000000000000000000000000000000000..ba7d745eb7dbde606928d8fad21f0b3c7dad03b3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/schema3.test @@ -0,0 +1,97 @@ +# 2010 Jun 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +source $testdir/lock_common.tcl + +# This block tests that if one client modifies the database schema, a +# second client updates its internal cache of the database schema before +# executing any queries. Specifically, it does not return a "no such column" +# or "no such table" error if the table or column in question does exist +# but was added after the second client loaded its cache of the database +# schema. +# +# Types of schema modifications: +# +# 1. Adding a database table. +# 2. Adding a database view. +# 3. Adding a database index. +# 4. Adding a database trigger. +# 5. Adding a column to an existing table (ALTER TABLE). +# +do_multiclient_test tn { + + # Have connections [db1] and [db2] load the current database schema. + # + sql1 { SELECT * FROM sqlite_master } + sql2 { SELECT * FROM sqlite_master } + + foreach {tn2 c1 c2} { + 1 { CREATE TABLE t1(a, b) } { SELECT * FROM t1 } + 2 { CREATE TABLE t2(a, b) } { UPDATE t2 SET a = b } + 3 { CREATE TABLE t3(a, b) } { DELETE FROM t3 } + 4 { CREATE TABLE t4(a, b) } { INSERT INTO t4 VALUES(1, 2) } + 5 { CREATE TABLE t5(a, b) } { DROP TABLE t5 } + 6 { CREATE TABLE t6(a, b) } { CREATE INDEX i1 ON t6(a) } + + 7 { ALTER TABLE t1 ADD COLUMN c } { SELECT a, b, c FROM t1 } + 8 { ALTER TABLE t2 ADD COLUMN c } { UPDATE t2 SET a = c } + 9 { ALTER TABLE t2 ADD COLUMN d } { UPDATE t2 SET d = c } + 10 { ALTER TABLE t3 ADD COLUMN c } { DELETE FROM t3 WHERE c>10 } + 11 { ALTER TABLE t4 ADD COLUMN c } { INSERT INTO t4(a,b,c) VALUES(1,2,3) } + 12 { ALTER TABLE t6 ADD COLUMN c } { CREATE INDEX i2 ON t6(c) } + 13 { ALTER TABLE t6 ADD COLUMN d } { + CREATE TRIGGER tr1 AFTER UPDATE OF d ON t6 BEGIN + SELECT 1, 2, 3; + END; + } + + 14 { CREATE INDEX i3 ON t1(a) } { DROP INDEX i3 } + 15 { CREATE INDEX i4 ON t2(a) } { + SELECT * FROM t2 INDEXED BY i4 ORDER BY a + } + + 16 { CREATE TRIGGER tr2 AFTER INSERT ON t3 BEGIN SELECT 1 ; END } { + DROP TRIGGER tr2 + } + + 17 { CREATE VIEW v1 AS SELECT * FROM t1 } { SELECT a,b,c FROM v1 } + 18 { ALTER TABLE t1 ADD COLUMN d } { SELECT a,b,c,d FROM v1 } + + 19 { CREATE TABLE t7(a, b) } { + DROP TABLE IF EXISTS t7; CREATE TABLE t7(c, d); + } + 20 { CREATE INDEX i5 ON t7(c, d) } { + DROP INDEX IF EXISTS i5; CREATE INDEX i5 ON t7(c) + } + 21 { CREATE TRIGGER tr3 BEFORE DELETE ON t7 BEGIN SELECT 1, 2, 3 ; END } { + DROP TRIGGER IF EXISTS tr3; + CREATE TRIGGER tr3 AFTER INSERT ON t7 BEGIN SELECT 1, 2, 3 ; END + } + + 22 { CREATE TABLE t8(a, b) } { + CREATE TRIGGER tr4 AFTER UPDATE OF a ON t8 BEGIN + SELECT 1, 2, 3; + END; + } + } { + do_test schema3-1.$tn.$tn2 { + sql1 $c1 + sql2 $c2 + } {} + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/schema4.test b/components/external/SQLite-3.8.1/test/schema4.test new file mode 100644 index 0000000000000000000000000000000000000000..6618d753881e2b077da33cc221b29f4807b3beff --- /dev/null +++ b/components/external/SQLite-3.8.1/test/schema4.test @@ -0,0 +1,175 @@ +# 2010 September 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that a trigger may have the same +# name as an index, view or table in the same database. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +#-------------------------------------------------------------------------- +# Test organization: +# +# schema4-1.*: Dropping and creating triggers and other objects where +# triggers and at least on other object share a name. +# +# schema4-2.*: Renaming tables where there is a trigger that shares the +# name of the table or one of its indices. +# + +do_execsql_test schema4-1.1 { + CREATE TABLE log(x, a, b); + CREATE TABLE tbl(a, b); + + CREATE TABLE t1(a, b); + CREATE VIEW v1 AS SELECT * FROM tbl; + CREATE INDEX i1 ON tbl(a); +} {} + +do_execsql_test schema4-1.2 { + CREATE TRIGGER t1 AFTER INSERT ON tbl BEGIN + INSERT INTO log VALUES('after insert', new.a, new.b); + END; + CREATE TRIGGER v1 AFTER UPDATE ON tbl BEGIN + INSERT INTO log VALUES('after update', new.a, new.b); + END; + CREATE TRIGGER i1 AFTER DELETE ON tbl BEGIN + INSERT INTO log VALUES('after delete', old.a, old.b); + END; +} {} + +do_execsql_test schema4-1.3 { + INSERT INTO tbl VALUES(1, 2); + UPDATE tbl SET b=a+b, a=a+1; + DELETE FROM tbl; + + SELECT x, a, b FROM log; +} {{after insert} 1 2 {after update} 2 3 {after delete} 2 3} + +do_execsql_test schema4-1.4 { + DELETE FROM log; + + DROP INDEX i1; + DROP TABLE t1; + DROP VIEW v1; + + INSERT INTO tbl VALUES(1, 2); + UPDATE tbl SET b=a+b, a=a+1; + DELETE FROM tbl; + + SELECT x, a, b FROM log; +} {{after insert} 1 2 {after update} 2 3 {after delete} 2 3} + +db close +sqlite3 db test.db + +do_execsql_test schema4-1.5 { + DELETE FROM log; + INSERT INTO tbl VALUES(1, 2); + UPDATE tbl SET b=a+b, a=a+1; + DELETE FROM tbl; + SELECT x, a, b FROM log; +} {{after insert} 1 2 {after update} 2 3 {after delete} 2 3} + +do_execsql_test schema4-1.6 { + CREATE TABLE t1(a, b); + CREATE VIEW v1 AS SELECT * FROM tbl; + CREATE INDEX i1 ON tbl(a); +} {} + +ifcapable fts3 { + do_execsql_test schema4-1.7 { + DROP TABLE t1; + CREATE VIRTUAL TABLE t1 USING fts3; + } {} + + do_execsql_test schema4-1.8 { + DELETE FROM log; + DROP TABLE t1; + INSERT INTO tbl VALUES(1, 2); + UPDATE tbl SET b=a+b, a=a+1; + DELETE FROM tbl; + SELECT x, a, b FROM log; + } {{after insert} 1 2 {after update} 2 3 {after delete} 2 3} +} + +ifcapable altertable { + drop_all_tables + do_execsql_test schema4-2.1 { + CREATE TABLE log(x, a, b); + CREATE TABLE tbl(a, b); + + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + } {} + + do_execsql_test schema4-2.2 { + CREATE TRIGGER t1 AFTER INSERT ON tbl BEGIN + INSERT INTO log VALUES('after insert', new.a, new.b); + END; + CREATE TRIGGER i1 AFTER DELETE ON tbl BEGIN + INSERT INTO log VALUES('after delete', old.a, old.b); + END; + } {} + + do_execsql_test schema4-2.3 { ALTER TABLE t1 RENAME TO t2 } {} + + do_execsql_test schema4-2.4 { + INSERT INTO tbl VALUES('a', 'b'); + DELETE FROM tbl; + SELECT * FROM log; + } {{after insert} a b {after delete} a b} + + db close + sqlite3 db test.db + + do_execsql_test schema4-2.5 { + DELETE FROM log; + INSERT INTO tbl VALUES('c', 'd'); + DELETE FROM tbl; + SELECT * FROM log; + } {{after insert} c d {after delete} c d} + + do_execsql_test schema4-2.6 { + CREATE TEMP TRIGGER x1 AFTER UPDATE ON tbl BEGIN + INSERT INTO log VALUES('after update', new.a, new.b); + END; + + CREATE TEMP TABLE x1(x); + INSERT INTO x1 VALUES(123); + } {} + + do_execsql_test schema4-2.8 { + select sql from sqlite_temp_master WHERE type='table'; + } {{CREATE TABLE x1(x)}} + + do_execsql_test schema4-2.7 { ALTER TABLE tbl RENAME TO tbl2 } {} + + do_execsql_test schema4-2.9 { + select sql from sqlite_temp_master WHERE type='table'; + } {{CREATE TABLE x1(x)}} + + do_execsql_test schema4-2.10 { + DELETE FROM log; + INSERT INTO tbl2 VALUES('e', 'f'); + UPDATE tbl2 SET a='g', b='h'; + DELETE FROM tbl2; + SELECT * FROM log; + } {{after insert} e f {after update} g h {after delete} g h} + + do_execsql_test schema4-2.11 { + INSERT INTO x1 VALUES(456); + SELECT * FROM x1 + } {123 456} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/schema5.test b/components/external/SQLite-3.8.1/test/schema5.test new file mode 100644 index 0000000000000000000000000000000000000000..6dea5e8f5f2aeb3eedea5196bf1dd7d5dd72d5b2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/schema5.test @@ -0,0 +1,69 @@ +# 2010 September 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file checks corner cases in the CREATE TABLE syntax to make +# sure that legacy syntax (syntax that is disallowed according to the +# syntax diagrams) is still accepted, so that older databases that use +# that syntax can still be read. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Table constraints should be separated by commas, but they do not have +# to be. +# +do_test schema5-1.1 { + db eval { + CREATE TABLE t1(a,b,c, PRIMARY KEY(a) UNIQUE (a) CONSTRAINT one); + INSERT INTO t1 VALUES(1,2,3); + SELECT * FROM t1; + } +} {1 2 3} +do_test schema5-1.2 { + catchsql {INSERT INTO t1 VALUES(1,3,4);} +} {1 {column a is not unique}} +do_test schema5-1.3 { + db eval { + DROP TABLE t1; + CREATE TABLE t1(a,b,c, + CONSTRAINT one PRIMARY KEY(a) CONSTRAINT two CHECK(b<10) UNIQUE(b) + CONSTRAINT three + ); + INSERT INTO t1 VALUES(1,2,3); + SELECT * FROM t1; + } +} {1 2 3} +do_test schema5-1.4 { + catchsql {INSERT INTO t1 VALUES(10,11,12);} +} {1 {constraint two failed}} +do_test schema5-1.5 { + db eval { + DROP TABLE t1; + CREATE TABLE t1(a,b,c, + UNIQUE(a) CONSTRAINT one, + PRIMARY KEY(b,c) CONSTRAINT two + ); + INSERT INTO t1 VALUES(1,2,3); + } +} {} +do_test schema5-1.6 { + catchsql {INSERT INTO t1 VALUES(1,3,4)} +} {1 {column a is not unique}} +do_test schema5-1.7 { + catchsql {INSERT INTO t1 VALUES(10,2,3)} +} {1 {columns b, c are not unique}} + + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/securedel.test b/components/external/SQLite-3.8.1/test/securedel.test new file mode 100644 index 0000000000000000000000000000000000000000..7ff5a628a1a73d9b25dceddbd925f3b03bd8f03c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/securedel.test @@ -0,0 +1,73 @@ +# 2010 January 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# +# Tests for the secure_delete pragma. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +unset -nocomplain DEFAULT_SECDEL +set DEFAULT_SECDEL 0 +ifcapable secure_delete { + set DEFAULT_SECDEL 1 +} + + +do_test securedel-1.0 { + db eval {PRAGMA secure_delete;} +} $DEFAULT_SECDEL + +forcedelete test2.db test2.db-journal +do_test securedel-1.1 { + db eval { + ATTACH 'test2.db' AS db2; + PRAGMA main.secure_delete=ON; + PRAGMA db2.secure_delete; + } +} [list 1 $DEFAULT_SECDEL] +do_test securedel-1.2 { + db eval { + PRAGMA main.secure_delete=OFF; + PRAGMA db2.secure_delete; + } +} [list 0 $DEFAULT_SECDEL] +do_test securedel-1.3 { + db eval { + PRAGMA secure_delete=OFF; + PRAGMA db2.secure_delete; + } +} {0 0} +do_test securedel-1.4 { +breakpoint + db eval { + PRAGMA secure_delete=ON; + PRAGMA db2.secure_delete; + } +} {1 1} + +do_test securedel-2.1 { + db eval { + DETACH db2; + ATTACH 'test2.db' AS db2; + PRAGMA db2.secure_delete; + } +} 1 +do_test securedel-2.2 { + db eval { + DETACH db2; + PRAGMA main.secure_delete=OFF; + ATTACH 'test2.db' AS db2; + PRAGMA db2.secure_delete; + } +} {0 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/securedel2.test b/components/external/SQLite-3.8.1/test/securedel2.test new file mode 100644 index 0000000000000000000000000000000000000000..9badc560d4e0cbd42498553fe5ce26f499189f93 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/securedel2.test @@ -0,0 +1,94 @@ +# 2012 August 7 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# +# Tests for the secure_delete pragma. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix securedel2 + +# Generate 1000 pseudo-random 64-bit blobs. +# +for {set i 1} {$i <= 1000} {incr i} { + set aBlob($i) [string range [db one {SELECT quote(randomblob(8))}] 2 end-1] +} + +proc detect_blob_prepare {zFile} { + set nByte [file size $zFile] + set ::detect_blob_data [hexio_read $zFile 0 $nByte] +} + +proc detect_blob {zFile iBlob} { + if {$zFile != ""} { detect_blob_prepare $zFile } + string match "*$::aBlob($iBlob)*" $::detect_blob_data +} + +do_test 1.1 { + execsql { PRAGMA secure_delete = 1 } + execsql { PRAGMA auto_vacuum = 0 } + execsql { CREATE TABLE t1(x, y) } + for {set i 1} {$i <= 1000} {incr i} { + set x "X'[string repeat $aBlob($i) 1]'" + set y "X'[string repeat $aBlob($i) 500]'" + execsql "INSERT INTO t1 VALUES($x, $y)" + } +} {} + +do_test 1.2 { detect_blob test.db 1 } {1} + +forcecopy test.db test.db.bak +do_execsql_test 1.3.1 { PRAGMA secure_delete = 0 } {0} +do_execsql_test 1.3.2 { DELETE FROM t1 WHERE rowid = 1 } +do_test 1.3.3 { detect_blob test.db 1 } {1} + +db close +forcecopy test.db.bak test.db +sqlite3 db test.db +do_execsql_test 1.4.1 { PRAGMA secure_delete = 1 } {1} +do_execsql_test 1.4.2 { DELETE FROM t1 WHERE rowid = 1 } +do_test 1.4.3 { detect_blob test.db 1 } {0} + +do_execsql_test 1.5.1 { DELETE FROM t1 WHERE rowid>850 } {} +do_test 1.5.2 { + set n 0 + detect_blob_prepare test.db + for {set i 851} {$i <= 1000} {incr i 5} { + incr n [detect_blob {} $i] + } + set n +} {0} + +db close +sqlite3 db test.db +do_test 1.6.1 { + execsql { + PRAGMA cache_size = 200; + PRAGMA secure_delete = 1; + CREATE TABLE t2(x); + SELECT * FROM t1; + } + for {set i 100} {$i < 5000} {incr i} { + execsql { INSERT INTO t2 VALUES(randomblob($i)) } + } + execsql { DELETE FROM t1 } +} {} + +do_test 1.6.2 { + set n 0 + detect_blob_prepare test.db + for {set i 2} {$i <= 850} {incr i 5} { + incr n [detect_blob {} $i] + } + set n +} {0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/select1.test b/components/external/SQLite-3.8.1/test/select1.test new file mode 100644 index 0000000000000000000000000000000000000000..875c87c84ab5f92d8363a2a1f7543f4468cc45b9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/select1.test @@ -0,0 +1,1076 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the SELECT statement. +# +# $Id: select1.test,v 1.70 2009/05/28 01:00:56 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Try to select on a non-existant table. +# +do_test select1-1.1 { + set v [catch {execsql {SELECT * FROM test1}} msg] + lappend v $msg +} {1 {no such table: test1}} + + +execsql {CREATE TABLE test1(f1 int, f2 int)} + +do_test select1-1.2 { + set v [catch {execsql {SELECT * FROM test1, test2}} msg] + lappend v $msg +} {1 {no such table: test2}} +do_test select1-1.3 { + set v [catch {execsql {SELECT * FROM test2, test1}} msg] + lappend v $msg +} {1 {no such table: test2}} + +execsql {INSERT INTO test1(f1,f2) VALUES(11,22)} + + +# Make sure the columns are extracted correctly. +# +do_test select1-1.4 { + execsql {SELECT f1 FROM test1} +} {11} +do_test select1-1.5 { + execsql {SELECT f2 FROM test1} +} {22} +do_test select1-1.6 { + execsql {SELECT f2, f1 FROM test1} +} {22 11} +do_test select1-1.7 { + execsql {SELECT f1, f2 FROM test1} +} {11 22} +do_test select1-1.8 { + execsql {SELECT * FROM test1} +} {11 22} +do_test select1-1.8.1 { + execsql {SELECT *, * FROM test1} +} {11 22 11 22} +do_test select1-1.8.2 { + execsql {SELECT *, min(f1,f2), max(f1,f2) FROM test1} +} {11 22 11 22} +do_test select1-1.8.3 { + execsql {SELECT 'one', *, 'two', * FROM test1} +} {one 11 22 two 11 22} + +execsql {CREATE TABLE test2(r1 real, r2 real)} +execsql {INSERT INTO test2(r1,r2) VALUES(1.1,2.2)} + +do_test select1-1.9 { + execsql {SELECT * FROM test1, test2} +} {11 22 1.1 2.2} +do_test select1-1.9.1 { + execsql {SELECT *, 'hi' FROM test1, test2} +} {11 22 1.1 2.2 hi} +do_test select1-1.9.2 { + execsql {SELECT 'one', *, 'two', * FROM test1, test2} +} {one 11 22 1.1 2.2 two 11 22 1.1 2.2} +do_test select1-1.10 { + execsql {SELECT test1.f1, test2.r1 FROM test1, test2} +} {11 1.1} +do_test select1-1.11 { + execsql {SELECT test1.f1, test2.r1 FROM test2, test1} +} {11 1.1} +do_test select1-1.11.1 { + execsql {SELECT * FROM test2, test1} +} {1.1 2.2 11 22} +do_test select1-1.11.2 { + execsql {SELECT * FROM test1 AS a, test1 AS b} +} {11 22 11 22} +do_test select1-1.12 { + execsql {SELECT max(test1.f1,test2.r1), min(test1.f2,test2.r2) + FROM test2, test1} +} {11 2.2} +do_test select1-1.13 { + execsql {SELECT min(test1.f1,test2.r1), max(test1.f2,test2.r2) + FROM test1, test2} +} {1.1 22} + +set long {This is a string that is too big to fit inside a NBFS buffer} +do_test select1-2.0 { + execsql " + DROP TABLE test2; + DELETE FROM test1; + INSERT INTO test1 VALUES(11,22); + INSERT INTO test1 VALUES(33,44); + CREATE TABLE t3(a,b); + INSERT INTO t3 VALUES('abc',NULL); + INSERT INTO t3 VALUES(NULL,'xyz'); + INSERT INTO t3 SELECT * FROM test1; + CREATE TABLE t4(a,b); + INSERT INTO t4 VALUES(NULL,'$long'); + SELECT * FROM t3; + " +} {abc {} {} xyz 11 22 33 44} + +# Error messges from sqliteExprCheck +# +do_test select1-2.1 { + set v [catch {execsql {SELECT count(f1,f2) FROM test1}} msg] + lappend v $msg +} {1 {wrong number of arguments to function count()}} +do_test select1-2.2 { + set v [catch {execsql {SELECT count(f1) FROM test1}} msg] + lappend v $msg +} {0 2} +do_test select1-2.3 { + set v [catch {execsql {SELECT Count() FROM test1}} msg] + lappend v $msg +} {0 2} +do_test select1-2.4 { + set v [catch {execsql {SELECT COUNT(*) FROM test1}} msg] + lappend v $msg +} {0 2} +do_test select1-2.5 { + set v [catch {execsql {SELECT COUNT(*)+1 FROM test1}} msg] + lappend v $msg +} {0 3} +do_test select1-2.5.1 { + execsql {SELECT count(*),count(a),count(b) FROM t3} +} {4 3 3} +do_test select1-2.5.2 { + execsql {SELECT count(*),count(a),count(b) FROM t4} +} {1 0 1} +do_test select1-2.5.3 { + execsql {SELECT count(*),count(a),count(b) FROM t4 WHERE b=5} +} {0 0 0} +do_test select1-2.6 { + set v [catch {execsql {SELECT min(*) FROM test1}} msg] + lappend v $msg +} {1 {wrong number of arguments to function min()}} +do_test select1-2.7 { + set v [catch {execsql {SELECT Min(f1) FROM test1}} msg] + lappend v $msg +} {0 11} +do_test select1-2.8 { + set v [catch {execsql {SELECT MIN(f1,f2) FROM test1}} msg] + lappend v [lsort $msg] +} {0 {11 33}} +do_test select1-2.8.1 { + execsql {SELECT coalesce(min(a),'xyzzy') FROM t3} +} {11} +do_test select1-2.8.2 { + execsql {SELECT min(coalesce(a,'xyzzy')) FROM t3} +} {11} +do_test select1-2.8.3 { + execsql {SELECT min(b), min(b) FROM t4} +} [list $long $long] +do_test select1-2.9 { + set v [catch {execsql {SELECT MAX(*) FROM test1}} msg] + lappend v $msg +} {1 {wrong number of arguments to function MAX()}} +do_test select1-2.10 { + set v [catch {execsql {SELECT Max(f1) FROM test1}} msg] + lappend v $msg +} {0 33} +do_test select1-2.11 { + set v [catch {execsql {SELECT max(f1,f2) FROM test1}} msg] + lappend v [lsort $msg] +} {0 {22 44}} +do_test select1-2.12 { + set v [catch {execsql {SELECT MAX(f1,f2)+1 FROM test1}} msg] + lappend v [lsort $msg] +} {0 {23 45}} +do_test select1-2.13 { + set v [catch {execsql {SELECT MAX(f1)+1 FROM test1}} msg] + lappend v $msg +} {0 34} +do_test select1-2.13.1 { + execsql {SELECT coalesce(max(a),'xyzzy') FROM t3} +} {abc} +do_test select1-2.13.2 { + execsql {SELECT max(coalesce(a,'xyzzy')) FROM t3} +} {xyzzy} +do_test select1-2.14 { + set v [catch {execsql {SELECT SUM(*) FROM test1}} msg] + lappend v $msg +} {1 {wrong number of arguments to function SUM()}} +do_test select1-2.15 { + set v [catch {execsql {SELECT Sum(f1) FROM test1}} msg] + lappend v $msg +} {0 44} +do_test select1-2.16 { + set v [catch {execsql {SELECT sum(f1,f2) FROM test1}} msg] + lappend v $msg +} {1 {wrong number of arguments to function sum()}} +do_test select1-2.17 { + set v [catch {execsql {SELECT SUM(f1)+1 FROM test1}} msg] + lappend v $msg +} {0 45} +do_test select1-2.17.1 { + execsql {SELECT sum(a) FROM t3} +} {44.0} +do_test select1-2.18 { + set v [catch {execsql {SELECT XYZZY(f1) FROM test1}} msg] + lappend v $msg +} {1 {no such function: XYZZY}} +do_test select1-2.19 { + set v [catch {execsql {SELECT SUM(min(f1,f2)) FROM test1}} msg] + lappend v $msg +} {0 44} +do_test select1-2.20 { + set v [catch {execsql {SELECT SUM(min(f1)) FROM test1}} msg] + lappend v $msg +} {1 {misuse of aggregate function min()}} + +# Ticket #2526 +# +do_test select1-2.21 { + catchsql { + SELECT min(f1) AS m FROM test1 GROUP BY f1 HAVING max(m+5)<10 + } +} {1 {misuse of aliased aggregate m}} +do_test select1-2.22 { + catchsql { + SELECT coalesce(min(f1)+5,11) AS m FROM test1 + GROUP BY f1 + HAVING max(m+5)<10 + } +} {1 {misuse of aliased aggregate m}} +do_test select1-2.23 { + execsql { + CREATE TABLE tkt2526(a,b,c PRIMARY KEY); + INSERT INTO tkt2526 VALUES('x','y',NULL); + INSERT INTO tkt2526 VALUES('x','z',NULL); + } + catchsql { + SELECT count(a) AS cn FROM tkt2526 GROUP BY a HAVING cn=11}} msg] + lappend v [lsort $msg] +} {0 {11 33}} +do_test select1-3.5 { + set v [catch {execsql {SELECT f1 FROM test1 WHERE f1>11}} msg] + lappend v [lsort $msg] +} {0 33} +do_test select1-3.6 { + set v [catch {execsql {SELECT f1 FROM test1 WHERE f1!=11}} msg] + lappend v [lsort $msg] +} {0 33} +do_test select1-3.7 { + set v [catch {execsql {SELECT f1 FROM test1 WHERE min(f1,f2)!=11}} msg] + lappend v [lsort $msg] +} {0 33} +do_test select1-3.8 { + set v [catch {execsql {SELECT f1 FROM test1 WHERE max(f1,f2)!=11}} msg] + lappend v [lsort $msg] +} {0 {11 33}} +do_test select1-3.9 { + set v [catch {execsql {SELECT f1 FROM test1 WHERE count(f1,f2)!=11}} msg] + lappend v $msg +} {1 {wrong number of arguments to function count()}} + +# ORDER BY expressions +# +do_test select1-4.1 { + set v [catch {execsql {SELECT f1 FROM test1 ORDER BY f1}} msg] + lappend v $msg +} {0 {11 33}} +do_test select1-4.2 { + set v [catch {execsql {SELECT f1 FROM test1 ORDER BY -f1}} msg] + lappend v $msg +} {0 {33 11}} +do_test select1-4.3 { + set v [catch {execsql {SELECT f1 FROM test1 ORDER BY min(f1,f2)}} msg] + lappend v $msg +} {0 {11 33}} +do_test select1-4.4 { + set v [catch {execsql {SELECT f1 FROM test1 ORDER BY min(f1)}} msg] + lappend v $msg +} {1 {misuse of aggregate: min()}} + +# The restriction not allowing constants in the ORDER BY clause +# has been removed. See ticket #1768 +#do_test select1-4.5 { +# catchsql { +# SELECT f1 FROM test1 ORDER BY 8.4; +# } +#} {1 {ORDER BY terms must not be non-integer constants}} +#do_test select1-4.6 { +# catchsql { +# SELECT f1 FROM test1 ORDER BY '8.4'; +# } +#} {1 {ORDER BY terms must not be non-integer constants}} +#do_test select1-4.7.1 { +# catchsql { +# SELECT f1 FROM test1 ORDER BY 'xyz'; +# } +#} {1 {ORDER BY terms must not be non-integer constants}} +#do_test select1-4.7.2 { +# catchsql { +# SELECT f1 FROM test1 ORDER BY -8.4; +# } +#} {1 {ORDER BY terms must not be non-integer constants}} +#do_test select1-4.7.3 { +# catchsql { +# SELECT f1 FROM test1 ORDER BY +8.4; +# } +#} {1 {ORDER BY terms must not be non-integer constants}} +#do_test select1-4.7.4 { +# catchsql { +# SELECT f1 FROM test1 ORDER BY 4294967296; -- constant larger than 32 bits +# } +#} {1 {ORDER BY terms must not be non-integer constants}} + +do_test select1-4.5 { + execsql { + SELECT f1 FROM test1 ORDER BY 8.4 + } +} {11 33} +do_test select1-4.6 { + execsql { + SELECT f1 FROM test1 ORDER BY '8.4' + } +} {11 33} + +do_test select1-4.8 { + execsql { + CREATE TABLE t5(a,b); + INSERT INTO t5 VALUES(1,10); + INSERT INTO t5 VALUES(2,9); + SELECT * FROM t5 ORDER BY 1; + } +} {1 10 2 9} +do_test select1-4.9.1 { + execsql { + SELECT * FROM t5 ORDER BY 2; + } +} {2 9 1 10} +do_test select1-4.9.2 { + execsql { + SELECT * FROM t5 ORDER BY +2; + } +} {2 9 1 10} +do_test select1-4.10.1 { + catchsql { + SELECT * FROM t5 ORDER BY 3; + } +} {1 {1st ORDER BY term out of range - should be between 1 and 2}} +do_test select1-4.10.2 { + catchsql { + SELECT * FROM t5 ORDER BY -1; + } +} {1 {1st ORDER BY term out of range - should be between 1 and 2}} +do_test select1-4.11 { + execsql { + INSERT INTO t5 VALUES(3,10); + SELECT * FROM t5 ORDER BY 2, 1 DESC; + } +} {2 9 3 10 1 10} +do_test select1-4.12 { + execsql { + SELECT * FROM t5 ORDER BY 1 DESC, b; + } +} {3 10 2 9 1 10} +do_test select1-4.13 { + execsql { + SELECT * FROM t5 ORDER BY b DESC, 1; + } +} {1 10 3 10 2 9} + + +# ORDER BY ignored on an aggregate query +# +do_test select1-5.1 { + set v [catch {execsql {SELECT max(f1) FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 33} + +execsql {CREATE TABLE test2(t1 text, t2 text)} +execsql {INSERT INTO test2 VALUES('abc','xyz')} + +# Check for column naming +# +do_test select1-6.1 { + set v [catch {execsql2 {SELECT f1 FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 {f1 11 f1 33}} +do_test select1-6.1.1 { + db eval {PRAGMA full_column_names=on} + set v [catch {execsql2 {SELECT f1 FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 {test1.f1 11 test1.f1 33}} +do_test select1-6.1.2 { + set v [catch {execsql2 {SELECT f1 as 'f1' FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 {f1 11 f1 33}} +do_test select1-6.1.3 { + set v [catch {execsql2 {SELECT * FROM test1 WHERE f1==11}} msg] + lappend v $msg +} {0 {f1 11 f2 22}} +do_test select1-6.1.4 { + set v [catch {execsql2 {SELECT DISTINCT * FROM test1 WHERE f1==11}} msg] + db eval {PRAGMA full_column_names=off} + lappend v $msg +} {0 {f1 11 f2 22}} +do_test select1-6.1.5 { + set v [catch {execsql2 {SELECT * FROM test1 WHERE f1==11}} msg] + lappend v $msg +} {0 {f1 11 f2 22}} +do_test select1-6.1.6 { + set v [catch {execsql2 {SELECT DISTINCT * FROM test1 WHERE f1==11}} msg] + lappend v $msg +} {0 {f1 11 f2 22}} +do_test select1-6.2 { + set v [catch {execsql2 {SELECT f1 as xyzzy FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 {xyzzy 11 xyzzy 33}} +do_test select1-6.3 { + set v [catch {execsql2 {SELECT f1 as "xyzzy" FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 {xyzzy 11 xyzzy 33}} +do_test select1-6.3.1 { + set v [catch {execsql2 {SELECT f1 as 'xyzzy ' FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 {{xyzzy } 11 {xyzzy } 33}} +do_test select1-6.4 { + set v [catch {execsql2 {SELECT f1+F2 as xyzzy FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 {xyzzy 33 xyzzy 77}} +do_test select1-6.4a { + set v [catch {execsql2 {SELECT f1+F2 FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 {f1+F2 33 f1+F2 77}} +do_test select1-6.5 { + set v [catch {execsql2 {SELECT test1.f1+F2 FROM test1 ORDER BY f2}} msg] + lappend v $msg +} {0 {test1.f1+F2 33 test1.f1+F2 77}} +do_test select1-6.5.1 { + execsql2 {PRAGMA full_column_names=on} + set v [catch {execsql2 {SELECT test1.f1+F2 FROM test1 ORDER BY f2}} msg] + execsql2 {PRAGMA full_column_names=off} + lappend v $msg +} {0 {test1.f1+F2 33 test1.f1+F2 77}} +do_test select1-6.6 { + set v [catch {execsql2 {SELECT test1.f1+F2, t1 FROM test1, test2 + ORDER BY f2}} msg] + lappend v $msg +} {0 {test1.f1+F2 33 t1 abc test1.f1+F2 77 t1 abc}} +do_test select1-6.7 { + set v [catch {execsql2 {SELECT A.f1, t1 FROM test1 as A, test2 + ORDER BY f2}} msg] + lappend v $msg +} {0 {f1 11 t1 abc f1 33 t1 abc}} +do_test select1-6.8 { + set v [catch {execsql2 {SELECT A.f1, f1 FROM test1 as A, test1 as B + ORDER BY f2}} msg] + lappend v $msg +} {1 {ambiguous column name: f1}} +do_test select1-6.8b { + set v [catch {execsql2 {SELECT A.f1, B.f1 FROM test1 as A, test1 as B + ORDER BY f2}} msg] + lappend v $msg +} {1 {ambiguous column name: f2}} +do_test select1-6.8c { + set v [catch {execsql2 {SELECT A.f1, f1 FROM test1 as A, test1 as A + ORDER BY f2}} msg] + lappend v $msg +} {1 {ambiguous column name: A.f1}} +do_test select1-6.9.1 { + set v [catch {execsql {SELECT A.f1, B.f1 FROM test1 as A, test1 as B + ORDER BY A.f1, B.f1}} msg] + lappend v $msg +} {0 {11 11 11 33 33 11 33 33}} +do_test select1-6.9.2 { + set v [catch {execsql2 {SELECT A.f1, B.f1 FROM test1 as A, test1 as B + ORDER BY A.f1, B.f1}} msg] + lappend v $msg +} {0 {f1 11 f1 11 f1 33 f1 33 f1 11 f1 11 f1 33 f1 33}} + +do_test select1-6.9.3 { + db eval { + PRAGMA short_column_names=OFF; + PRAGMA full_column_names=OFF; + } + execsql2 { + SELECT test1 . f1, test1 . f2 FROM test1 LIMIT 1 + } +} {{test1 . f1} 11 {test1 . f2} 22} +do_test select1-6.9.4 { + db eval { + PRAGMA short_column_names=OFF; + PRAGMA full_column_names=ON; + } + execsql2 { + SELECT test1 . f1, test1 . f2 FROM test1 LIMIT 1 + } +} {test1.f1 11 test1.f2 22} +do_test select1-6.9.5 { + db eval { + PRAGMA short_column_names=OFF; + PRAGMA full_column_names=ON; + } + execsql2 { + SELECT 123.45; + } +} {123.45 123.45} +do_test select1-6.9.6 { + execsql2 { + SELECT * FROM test1 a, test1 b LIMIT 1 + } +} {a.f1 11 a.f2 22 b.f1 11 b.f2 22} +do_test select1-6.9.7 { + set x [execsql2 { + SELECT * FROM test1 a, (select 5, 6) LIMIT 1 + }] + regsub -all {sq_[0-9a-fA-F_]+} $x {subquery} x + set x +} {a.f1 11 a.f2 22 sqlite_subquery.5 5 sqlite_subquery.6 6} +do_test select1-6.9.8 { + set x [execsql2 { + SELECT * FROM test1 a, (select 5 AS x, 6 AS y) AS b LIMIT 1 + }] + regsub -all {subquery_[0-9a-fA-F]+_} $x {subquery} x + set x +} {a.f1 11 a.f2 22 b.x 5 b.y 6} +do_test select1-6.9.9 { + execsql2 { + SELECT a.f1, b.f2 FROM test1 a, test1 b LIMIT 1 + } +} {test1.f1 11 test1.f2 22} +do_test select1-6.9.10 { + execsql2 { + SELECT f1, t1 FROM test1, test2 LIMIT 1 + } +} {test1.f1 11 test2.t1 abc} +do_test select1-6.9.11 { + db eval { + PRAGMA short_column_names=ON; + PRAGMA full_column_names=ON; + } + execsql2 { + SELECT a.f1, b.f2 FROM test1 a, test1 b LIMIT 1 + } +} {test1.f1 11 test1.f2 22} +do_test select1-6.9.12 { + execsql2 { + SELECT f1, t1 FROM test1, test2 LIMIT 1 + } +} {test1.f1 11 test2.t1 abc} +do_test select1-6.9.13 { + db eval { + PRAGMA short_column_names=ON; + PRAGMA full_column_names=OFF; + } + execsql2 { + SELECT a.f1, b.f1 FROM test1 a, test1 b LIMIT 1 + } +} {f1 11 f1 11} +do_test select1-6.9.14 { + execsql2 { + SELECT f1, t1 FROM test1, test2 LIMIT 1 + } +} {f1 11 t1 abc} +do_test select1-6.9.15 { + db eval { + PRAGMA short_column_names=OFF; + PRAGMA full_column_names=ON; + } + execsql2 { + SELECT a.f1, b.f1 FROM test1 a, test1 b LIMIT 1 + } +} {test1.f1 11 test1.f1 11} +do_test select1-6.9.16 { + execsql2 { + SELECT f1, t1 FROM test1, test2 LIMIT 1 + } +} {test1.f1 11 test2.t1 abc} + + +db eval { + PRAGMA short_column_names=ON; + PRAGMA full_column_names=OFF; +} + +ifcapable compound { +do_test select1-6.10 { + set v [catch {execsql2 { + SELECT f1 FROM test1 UNION SELECT f2 FROM test1 + ORDER BY f2; + }} msg] + lappend v $msg +} {0 {f1 11 f1 22 f1 33 f1 44}} +do_test select1-6.11 { + set v [catch {execsql2 { + SELECT f1 FROM test1 UNION SELECT f2+100 FROM test1 + ORDER BY f2+101; + }} msg] + lappend v $msg +} {1 {1st ORDER BY term does not match any column in the result set}} + +# Ticket #2296 +ifcapable subquery&&compound { +do_test select1-6.20 { + execsql { + CREATE TABLE t6(a TEXT, b TEXT); + INSERT INTO t6 VALUES('a','0'); + INSERT INTO t6 VALUES('b','1'); + INSERT INTO t6 VALUES('c','2'); + INSERT INTO t6 VALUES('d','3'); + SELECT a FROM t6 WHERE b IN + (SELECT b FROM t6 WHERE a<='b' UNION SELECT '3' AS x + ORDER BY 1 LIMIT 1) + } +} {a} +do_test select1-6.21 { + execsql { + SELECT a FROM t6 WHERE b IN + (SELECT b FROM t6 WHERE a<='b' UNION SELECT '3' AS x + ORDER BY 1 DESC LIMIT 1) + } +} {d} +do_test select1-6.22 { + execsql { + SELECT a FROM t6 WHERE b IN + (SELECT b FROM t6 WHERE a<='b' UNION SELECT '3' AS x + ORDER BY b LIMIT 2) + ORDER BY a; + } +} {a b} +do_test select1-6.23 { + execsql { + SELECT a FROM t6 WHERE b IN + (SELECT b FROM t6 WHERE a<='b' UNION SELECT '3' AS x + ORDER BY x DESC LIMIT 2) + ORDER BY a; + } +} {b d} +} + +} ;#ifcapable compound + +do_test select1-7.1 { + set v [catch {execsql { + SELECT f1 FROM test1 WHERE f2=; + }} msg] + lappend v $msg +} {1 {near ";": syntax error}} +ifcapable compound { +do_test select1-7.2 { + set v [catch {execsql { + SELECT f1 FROM test1 UNION SELECT WHERE; + }} msg] + lappend v $msg +} {1 {near "WHERE": syntax error}} +} ;# ifcapable compound +do_test select1-7.3 { + set v [catch {execsql {SELECT f1 FROM test1 as 'hi', test2 as}} msg] + lappend v $msg +} {1 {near "as": syntax error}} +do_test select1-7.4 { + set v [catch {execsql { + SELECT f1 FROM test1 ORDER BY; + }} msg] + lappend v $msg +} {1 {near ";": syntax error}} +do_test select1-7.5 { + set v [catch {execsql { + SELECT f1 FROM test1 ORDER BY f1 desc, f2 where; + }} msg] + lappend v $msg +} {1 {near "where": syntax error}} +do_test select1-7.6 { + set v [catch {execsql { + SELECT count(f1,f2 FROM test1; + }} msg] + lappend v $msg +} {1 {near "FROM": syntax error}} +do_test select1-7.7 { + set v [catch {execsql { + SELECT count(f1,f2+) FROM test1; + }} msg] + lappend v $msg +} {1 {near ")": syntax error}} +do_test select1-7.8 { + set v [catch {execsql { + SELECT f1 FROM test1 ORDER BY f2, f1+; + }} msg] + lappend v $msg +} {1 {near ";": syntax error}} +do_test select1-7.9 { + catchsql { + SELECT f1 FROM test1 LIMIT 5+3 OFFSET 11 ORDER BY f2; + } +} {1 {near "ORDER": syntax error}} + +do_test select1-8.1 { + execsql {SELECT f1 FROM test1 WHERE 4.3+2.4 OR 1 ORDER BY f1} +} {11 33} +do_test select1-8.2 { + execsql { + SELECT f1 FROM test1 WHERE ('x' || f1) BETWEEN 'x10' AND 'x20' + ORDER BY f1 + } +} {11} +do_test select1-8.3 { + execsql { + SELECT f1 FROM test1 WHERE 5-3==2 + ORDER BY f1 + } +} {11 33} + +# TODO: This test is failing because f1 is now being loaded off the +# disk as a vdbe integer, not a string. Hence the value of f1/(f1-11) +# changes because of rounding. Disable the test for now. +if 0 { +do_test select1-8.4 { + execsql { + SELECT coalesce(f1/(f1-11),'x'), + coalesce(min(f1/(f1-11),5),'y'), + coalesce(max(f1/(f1-33),6),'z') + FROM test1 ORDER BY f1 + } +} {x y 6 1.5 1.5 z} +} +do_test select1-8.5 { + execsql { + SELECT min(1,2,3), -max(1,2,3) + FROM test1 ORDER BY f1 + } +} {1 -3 1 -3} + + +# Check the behavior when the result set is empty +# +# SQLite v3 always sets r(*). +# +# do_test select1-9.1 { +# catch {unset r} +# set r(*) {} +# db eval {SELECT * FROM test1 WHERE f1<0} r {} +# set r(*) +# } {} +do_test select1-9.2 { + execsql {PRAGMA empty_result_callbacks=on} + catch {unset r} + set r(*) {} + db eval {SELECT * FROM test1 WHERE f1<0} r {} + set r(*) +} {f1 f2} +ifcapable subquery { + do_test select1-9.3 { + set r(*) {} + db eval {SELECT * FROM test1 WHERE f1<(select count(*) from test2)} r {} + set r(*) + } {f1 f2} +} +do_test select1-9.4 { + set r(*) {} + db eval {SELECT * FROM test1 ORDER BY f1} r {} + set r(*) +} {f1 f2} +do_test select1-9.5 { + set r(*) {} + db eval {SELECT * FROM test1 WHERE f1<0 ORDER BY f1} r {} + set r(*) +} {f1 f2} +unset r + +# Check for ORDER BY clauses that refer to an AS name in the column list +# +do_test select1-10.1 { + execsql { + SELECT f1 AS x FROM test1 ORDER BY x + } +} {11 33} +do_test select1-10.2 { + execsql { + SELECT f1 AS x FROM test1 ORDER BY -x + } +} {33 11} +do_test select1-10.3 { + execsql { + SELECT f1-23 AS x FROM test1 ORDER BY abs(x) + } +} {10 -12} +do_test select1-10.4 { + execsql { + SELECT f1-23 AS x FROM test1 ORDER BY -abs(x) + } +} {-12 10} +do_test select1-10.5 { + execsql { + SELECT f1-22 AS x, f2-22 as y FROM test1 + } +} {-11 0 11 22} +do_test select1-10.6 { + execsql { + SELECT f1-22 AS x, f2-22 as y FROM test1 WHERE x>0 AND y<50 + } +} {11 22} +do_test select1-10.7 { + execsql { + SELECT f1 COLLATE nocase AS x FROM test1 ORDER BY x + } +} {11 33} + +# Check the ability to specify "TABLE.*" in the result set of a SELECT +# +do_test select1-11.1 { + execsql { + DELETE FROM t3; + DELETE FROM t4; + INSERT INTO t3 VALUES(1,2); + INSERT INTO t4 VALUES(3,4); + SELECT * FROM t3, t4; + } +} {1 2 3 4} +do_test select1-11.2.1 { + execsql { + SELECT * FROM t3, t4; + } +} {1 2 3 4} +do_test select1-11.2.2 { + execsql2 { + SELECT * FROM t3, t4; + } +} {a 3 b 4 a 3 b 4} +do_test select1-11.4.1 { + execsql { + SELECT t3.*, t4.b FROM t3, t4; + } +} {1 2 4} +do_test select1-11.4.2 { + execsql { + SELECT "t3".*, t4.b FROM t3, t4; + } +} {1 2 4} +do_test select1-11.5.1 { + execsql2 { + SELECT t3.*, t4.b FROM t3, t4; + } +} {a 1 b 4 b 4} +do_test select1-11.6 { + execsql2 { + SELECT x.*, y.b FROM t3 AS x, t4 AS y; + } +} {a 1 b 4 b 4} +do_test select1-11.7 { + execsql { + SELECT t3.b, t4.* FROM t3, t4; + } +} {2 3 4} +do_test select1-11.8 { + execsql2 { + SELECT t3.b, t4.* FROM t3, t4; + } +} {b 4 a 3 b 4} +do_test select1-11.9 { + execsql2 { + SELECT x.b, y.* FROM t3 AS x, t4 AS y; + } +} {b 4 a 3 b 4} +do_test select1-11.10 { + catchsql { + SELECT t5.* FROM t3, t4; + } +} {1 {no such table: t5}} +do_test select1-11.11 { + catchsql { + SELECT t3.* FROM t3 AS x, t4; + } +} {1 {no such table: t3}} +ifcapable subquery { + do_test select1-11.12 { + execsql2 { + SELECT t3.* FROM t3, (SELECT max(a), max(b) FROM t4) + } + } {a 1 b 2} + do_test select1-11.13 { + execsql2 { + SELECT t3.* FROM (SELECT max(a), max(b) FROM t4), t3 + } + } {a 1 b 2} + do_test select1-11.14 { + execsql2 { + SELECT * FROM t3, (SELECT max(a), max(b) FROM t4) AS 'tx' + } + } {a 1 b 2 max(a) 3 max(b) 4} + do_test select1-11.15 { + execsql2 { + SELECT y.*, t3.* FROM t3, (SELECT max(a), max(b) FROM t4) AS y + } + } {max(a) 3 max(b) 4 a 1 b 2} +} +do_test select1-11.16 { + execsql2 { + SELECT y.* FROM t3 as y, t4 as z + } +} {a 1 b 2} + +# Tests of SELECT statements without a FROM clause. +# +do_test select1-12.1 { + execsql2 { + SELECT 1+2+3 + } +} {1+2+3 6} +do_test select1-12.2 { + execsql2 { + SELECT 1,'hello',2 + } +} {1 1 'hello' hello 2 2} +do_test select1-12.3 { + execsql2 { + SELECT 1 AS 'a','hello' AS 'b',2 AS 'c' + } +} {a 1 b hello c 2} +do_test select1-12.4 { + execsql { + DELETE FROM t3; + INSERT INTO t3 VALUES(1,2); + } +} {} + +ifcapable compound { +do_test select1-12.5 { + execsql { + SELECT * FROM t3 UNION SELECT 3 AS 'a', 4 ORDER BY a; + } +} {1 2 3 4} + +do_test select1-12.6 { + execsql { + SELECT 3, 4 UNION SELECT * FROM t3; + } +} {1 2 3 4} +} ;# ifcapable compound + +ifcapable subquery { + do_test select1-12.7 { + execsql { + SELECT * FROM t3 WHERE a=(SELECT 1); + } + } {1 2} + do_test select1-12.8 { + execsql { + SELECT * FROM t3 WHERE a=(SELECT 2); + } + } {} +} + +ifcapable {compound && subquery} { + do_test select1-12.9 { + execsql2 { + SELECT x FROM ( + SELECT a AS x, b AS y FROM t3 UNION SELECT a,b FROM t4 ORDER BY a,b + ) ORDER BY x; + } + } {x 1 x 3} + do_test select1-12.10 { + execsql2 { + SELECT z.x FROM ( + SELECT a AS x,b AS y FROM t3 UNION SELECT a, b FROM t4 ORDER BY a,b + ) AS 'z' ORDER BY x; + } + } {x 1 x 3} +} ;# ifcapable compound + + +# Check for a VDBE stack growth problem that existed at one point. +# +ifcapable subquery { + do_test select1-13.1 { + execsql { + BEGIN; + create TABLE abc(a, b, c, PRIMARY KEY(a, b)); + INSERT INTO abc VALUES(1, 1, 1); + } + for {set i 0} {$i<10} {incr i} { + execsql { + INSERT INTO abc SELECT a+(select max(a) FROM abc), + b+(select max(a) FROM abc), c+(select max(a) FROM abc) FROM abc; + } + } + execsql {COMMIT} + + # This used to seg-fault when the problem existed. + execsql { + SELECT count( + (SELECT a FROM abc WHERE a = NULL AND b >= upper.c) + ) FROM abc AS upper; + } + } {0} +} + +foreach tab [db eval {SELECT name FROM sqlite_master WHERE type = 'table'}] { + db eval "DROP TABLE $tab" +} +db close +sqlite3 db test.db + +do_test select1-14.1 { + execsql { + SELECT * FROM sqlite_master WHERE rowid>10; + SELECT * FROM sqlite_master WHERE rowid=10; + SELECT * FROM sqlite_master WHERE rowid<10; + SELECT * FROM sqlite_master WHERE rowid<=10; + SELECT * FROM sqlite_master WHERE rowid>=10; + SELECT * FROM sqlite_master; + } +} {} +do_test select1-14.2 { + execsql { + SELECT 10 IN (SELECT rowid FROM sqlite_master); + } +} {0} + +if {[db one {PRAGMA locking_mode}]=="normal"} { + # Check that ticket #3771 has been fixed. This test does not + # work with locking_mode=EXCLUSIVE so disable in that case. + # + do_test select1-15.1 { + execsql { + CREATE TABLE t1(a); + CREATE INDEX i1 ON t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + } + } {} + do_test select1-15.2 { + sqlite3 db2 test.db + execsql { DROP INDEX i1 } db2 + db2 close + } {} + do_test select1-15.3 { + execsql { SELECT 2 IN (SELECT a FROM t1) } + } {1} +} + +# Crash bug reported on the mailing list on 2012-02-23 +# +do_test select1-16.1 { + catchsql {SELECT 1 FROM (SELECT *)} +} {1 {no tables specified}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/select2.test b/components/external/SQLite-3.8.1/test/select2.test new file mode 100644 index 0000000000000000000000000000000000000000..35f8dd587905eafd358b23f51b78e009867cdf6a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/select2.test @@ -0,0 +1,185 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the SELECT statement. +# +# $Id: select2.test,v 1.28 2009/01/15 15:23:59 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a table with some data +# +execsql {CREATE TABLE tbl1(f1 int, f2 int)} +execsql {BEGIN} +for {set i 0} {$i<=30} {incr i} { + execsql "INSERT INTO tbl1 VALUES([expr {$i%9}],[expr {$i%10}])" +} +execsql {COMMIT} + +# Do a second query inside a first. +# +do_test select2-1.1 { + set sql {SELECT DISTINCT f1 FROM tbl1 ORDER BY f1} + set r {} + catch {unset data} + db eval $sql data { + set f1 $data(f1) + lappend r $f1: + set sql2 "SELECT f2 FROM tbl1 WHERE f1=$f1 ORDER BY f2" + db eval $sql2 d2 { + lappend r $d2(f2) + } + } + set r +} {0: 0 7 8 9 1: 0 1 8 9 2: 0 1 2 9 3: 0 1 2 3 4: 2 3 4 5: 3 4 5 6: 4 5 6 7: 5 6 7 8: 6 7 8} + +do_test select2-1.2 { + set sql {SELECT DISTINCT f1 FROM tbl1 WHERE f1>3 AND f1<5} + set r {} + db eval $sql data { + set f1 $data(f1) + lappend r $f1: + set sql2 "SELECT f2 FROM tbl1 WHERE f1=$f1 ORDER BY f2" + db eval $sql2 d2 { + lappend r $d2(f2) + } + } + set r +} {4: 2 3 4} +unset data + +# Create a largish table. Do this twice, once using the TCL cache and once +# without. Compare the performance to make sure things go faster with the +# cache turned on. +# +ifcapable tclvar { + do_test select2-2.0.1 { + set t1 [time { + execsql {CREATE TABLE tbl2(f1 int, f2 int, f3 int); BEGIN;} + for {set i 1} {$i<=30000} {incr i} { + set i2 [expr {$i*2}] + set i3 [expr {$i*3}] + db eval {INSERT INTO tbl2 VALUES($i,$i2,$i3)} + } + execsql {COMMIT} + }] + list + } {} + puts "time with cache: $::t1" +} +catch {execsql {DROP TABLE tbl2}} +do_test select2-2.0.2 { + set t2 [time { + execsql {CREATE TABLE tbl2(f1 int, f2 int, f3 int); BEGIN;} + for {set i 1} {$i<=30000} {incr i} { + set i2 [expr {$i*2}] + set i3 [expr {$i*3}] + execsql "INSERT INTO tbl2 VALUES($i,$i2,$i3)" + } + execsql {COMMIT} + }] + list +} {} +puts "time without cache: $t2" +#ifcapable tclvar { +# do_test select2-2.0.3 { +# expr {[lindex $t1 0]<[lindex $t2 0]} +# } 1 +#} + +do_test select2-2.1 { + execsql {SELECT count(*) FROM tbl2} +} {30000} +do_test select2-2.2 { + execsql {SELECT count(*) FROM tbl2 WHERE f2>1000} +} {29500} + +do_test select2-3.1 { + execsql {SELECT f1 FROM tbl2 WHERE 1000=f2} +} {500} + +do_test select2-3.2a { + execsql {CREATE INDEX idx1 ON tbl2(f2)} +} {} +do_test select2-3.2b { + execsql {SELECT f1 FROM tbl2 WHERE 1000=f2} +} {500} +do_test select2-3.2c { + execsql {SELECT f1 FROM tbl2 WHERE f2=1000} +} {500} +do_test select2-3.2d { + set sqlite_search_count 0 + execsql {SELECT * FROM tbl2 WHERE 1000=f2} + set sqlite_search_count +} {3} +do_test select2-3.2e { + set sqlite_search_count 0 + execsql {SELECT * FROM tbl2 WHERE f2=1000} + set sqlite_search_count +} {3} + +# Make sure queries run faster with an index than without +# +do_test select2-3.3 { + execsql {DROP INDEX idx1} + set sqlite_search_count 0 + execsql {SELECT f1 FROM tbl2 WHERE f2==2000} + set sqlite_search_count +} {29999} + +# Make sure we can optimize functions in the WHERE clause that +# use fields from two or more different table. (Bug #6) +# +do_test select2-4.1 { + execsql { + CREATE TABLE aa(a); + CREATE TABLE bb(b); + INSERT INTO aa VALUES(1); + INSERT INTO aa VALUES(3); + INSERT INTO bb VALUES(2); + INSERT INTO bb VALUES(4); + SELECT * FROM aa, bb WHERE max(a,b)>2; + } +} {1 4 3 2 3 4} +do_test select2-4.2 { + execsql { + INSERT INTO bb VALUES(0); + SELECT * FROM aa CROSS JOIN bb WHERE b; + } +} {1 2 1 4 3 2 3 4} +do_test select2-4.3 { + execsql { + SELECT * FROM aa CROSS JOIN bb WHERE NOT b; + } +} {1 0 3 0} +do_test select2-4.4 { + execsql { + SELECT * FROM aa, bb WHERE min(a,b); + } +} {1 2 1 4 3 2 3 4} +do_test select2-4.5 { + execsql { + SELECT * FROM aa, bb WHERE NOT min(a,b); + } +} {1 0 3 0} +do_test select2-4.6 { + execsql { + SELECT * FROM aa, bb WHERE CASE WHEN a=b-1 THEN 1 END; + } +} {1 2 3 4} +do_test select2-4.7 { + execsql { + SELECT * FROM aa, bb WHERE CASE WHEN a=b-1 THEN 0 ELSE 1 END; + } +} {1 4 1 0 3 2 3 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/select3.test b/components/external/SQLite-3.8.1/test/select3.test new file mode 100644 index 0000000000000000000000000000000000000000..b5dbef5fb44cef397ef4fa1d84ef076650afd0fa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/select3.test @@ -0,0 +1,264 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing aggregate functions and the +# GROUP BY and HAVING clauses of SELECT statements. +# +# $Id: select3.test,v 1.23 2008/01/16 18:20:42 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build some test data +# +do_test select3-1.0 { + execsql { + CREATE TABLE t1(n int, log int); + BEGIN; + } + for {set i 1} {$i<32} {incr i} { + for {set j 0} {(1<<$j)<$i} {incr j} {} + execsql "INSERT INTO t1 VALUES($i,$j)" + } + execsql { + COMMIT + } + execsql {SELECT DISTINCT log FROM t1 ORDER BY log} +} {0 1 2 3 4 5} + +# Basic aggregate functions. +# +do_test select3-1.1 { + execsql {SELECT count(*) FROM t1} +} {31} +do_test select3-1.2 { + execsql { + SELECT min(n),min(log),max(n),max(log),sum(n),sum(log),avg(n),avg(log) + FROM t1 + } +} {1 0 31 5 496 124 16.0 4.0} +do_test select3-1.3 { + execsql {SELECT max(n)/avg(n), max(log)/avg(log) FROM t1} +} {1.9375 1.25} + +# Try some basic GROUP BY clauses +# +do_test select3-2.1 { + execsql {SELECT log, count(*) FROM t1 GROUP BY log ORDER BY log} +} {0 1 1 1 2 2 3 4 4 8 5 15} +do_test select3-2.2 { + execsql {SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log} +} {0 1 1 2 2 3 3 5 4 9 5 17} +do_test select3-2.3.1 { + execsql {SELECT log, avg(n) FROM t1 GROUP BY log ORDER BY log} +} {0 1.0 1 2.0 2 3.5 3 6.5 4 12.5 5 24.0} +do_test select3-2.3.2 { + execsql {SELECT log, avg(n)+1 FROM t1 GROUP BY log ORDER BY log} +} {0 2.0 1 3.0 2 4.5 3 7.5 4 13.5 5 25.0} +do_test select3-2.4 { + execsql {SELECT log, avg(n)-min(n) FROM t1 GROUP BY log ORDER BY log} +} {0 0.0 1 0.0 2 0.5 3 1.5 4 3.5 5 7.0} +do_test select3-2.5 { + execsql {SELECT log*2+1, avg(n)-min(n) FROM t1 GROUP BY log ORDER BY log} +} {1 0.0 3 0.0 5 0.5 7 1.5 9 3.5 11 7.0} +do_test select3-2.6 { + execsql { + SELECT log*2+1 as x, count(*) FROM t1 GROUP BY x ORDER BY x + } +} {1 1 3 1 5 2 7 4 9 8 11 15} +do_test select3-2.7 { + execsql { + SELECT log*2+1 AS x, count(*) AS y FROM t1 GROUP BY x ORDER BY y, x + } +} {1 1 3 1 5 2 7 4 9 8 11 15} +do_test select3-2.8 { + execsql { + SELECT log*2+1 AS x, count(*) AS y FROM t1 GROUP BY x ORDER BY 10-(x+y) + } +} {11 15 9 8 7 4 5 2 3 1 1 1} +#do_test select3-2.9 { +# catchsql { +# SELECT log, count(*) FROM t1 GROUP BY 'x' ORDER BY log; +# } +#} {1 {GROUP BY terms must not be non-integer constants}} +do_test select3-2.10 { + catchsql { + SELECT log, count(*) FROM t1 GROUP BY 0 ORDER BY log; + } +} {1 {1st GROUP BY term out of range - should be between 1 and 2}} +do_test select3-2.11 { + catchsql { + SELECT log, count(*) FROM t1 GROUP BY 3 ORDER BY log; + } +} {1 {1st GROUP BY term out of range - should be between 1 and 2}} +do_test select3-2.12 { + catchsql { + SELECT log, count(*) FROM t1 GROUP BY 1 ORDER BY log; + } +} {0 {0 1 1 1 2 2 3 4 4 8 5 15}} + +# Cannot have an empty GROUP BY +do_test select3-2.13 { + catchsql { + SELECT log, count(*) FROM t1 GROUP BY ORDER BY log; + } +} {1 {near "ORDER": syntax error}} +do_test select3-2.14 { + catchsql { + SELECT log, count(*) FROM t1 GROUP BY; + } +} {1 {near ";": syntax error}} + +# Cannot have a HAVING without a GROUP BY +# +do_test select3-3.1 { + set v [catch {execsql {SELECT log, count(*) FROM t1 HAVING log>=4}} msg] + lappend v $msg +} {1 {a GROUP BY clause is required before HAVING}} + +# Toss in some HAVING clauses +# +do_test select3-4.1 { + execsql {SELECT log, count(*) FROM t1 GROUP BY log HAVING log>=4 ORDER BY log} +} {4 8 5 15} +do_test select3-4.2 { + execsql { + SELECT log, count(*) FROM t1 + GROUP BY log + HAVING count(*)>=4 + ORDER BY log + } +} {3 4 4 8 5 15} +do_test select3-4.3 { + execsql { + SELECT log, count(*) FROM t1 + GROUP BY log + HAVING count(*)>=4 + ORDER BY max(n)+0 + } +} {3 4 4 8 5 15} +do_test select3-4.4 { + execsql { + SELECT log AS x, count(*) AS y FROM t1 + GROUP BY x + HAVING y>=4 + ORDER BY max(n)+0 + } +} {3 4 4 8 5 15} +do_test select3-4.5 { + execsql { + SELECT log AS x FROM t1 + GROUP BY x + HAVING count(*)>=4 + ORDER BY max(n)+0 + } +} {3 4 5} + +do_test select3-5.1 { + execsql { + SELECT log, count(*), avg(n), max(n+log*2) FROM t1 + GROUP BY log + ORDER BY max(n+log*2)+0, avg(n)+0 + } +} {0 1 1.0 1 1 1 2.0 4 2 2 3.5 8 3 4 6.5 14 4 8 12.5 24 5 15 24.0 41} +do_test select3-5.2 { + execsql { + SELECT log, count(*), avg(n), max(n+log*2) FROM t1 + GROUP BY log + ORDER BY max(n+log*2)+0, min(log,avg(n))+0 + } +} {0 1 1.0 1 1 1 2.0 4 2 2 3.5 8 3 4 6.5 14 4 8 12.5 24 5 15 24.0 41} + +# Test sorting of GROUP BY results in the presence of an index +# on the GROUP BY column. +# +do_test select3-6.1 { + execsql { + SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log; + } +} {0 1 1 2 2 3 3 5 4 9 5 17} +do_test select3-6.2 { + execsql { + SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log DESC; + } +} {5 17 4 9 3 5 2 3 1 2 0 1} +do_test select3-6.3 { + execsql { + SELECT log, min(n) FROM t1 GROUP BY log ORDER BY 1; + } +} {0 1 1 2 2 3 3 5 4 9 5 17} +do_test select3-6.4 { + execsql { + SELECT log, min(n) FROM t1 GROUP BY log ORDER BY 1 DESC; + } +} {5 17 4 9 3 5 2 3 1 2 0 1} +do_test select3-6.5 { + execsql { + CREATE INDEX i1 ON t1(log); + SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log; + } +} {0 1 1 2 2 3 3 5 4 9 5 17} +do_test select3-6.6 { + execsql { + SELECT log, min(n) FROM t1 GROUP BY log ORDER BY log DESC; + } +} {5 17 4 9 3 5 2 3 1 2 0 1} +do_test select3-6.7 { + execsql { + SELECT log, min(n) FROM t1 GROUP BY log ORDER BY 1; + } +} {0 1 1 2 2 3 3 5 4 9 5 17} +do_test select3-6.8 { + execsql { + SELECT log, min(n) FROM t1 GROUP BY log ORDER BY 1 DESC; + } +} {5 17 4 9 3 5 2 3 1 2 0 1} + +# Sometimes an aggregate query can return no rows at all. +# +do_test select3-7.1 { + execsql { + CREATE TABLE t2(a,b); + INSERT INTO t2 VALUES(1,2); + SELECT a, sum(b) FROM t2 WHERE b=5 GROUP BY a; + } +} {} +do_test select3-7.2 { + execsql { + SELECT a, sum(b) FROM t2 WHERE b=5; + } +} {{} {}} + +# If a table column is of type REAL but we are storing integer values +# in it, the values are stored as integers to take up less space. The +# values are converted by to REAL as they are read out of the table. +# Make sure the GROUP BY clause does this conversion correctly. +# Ticket #2251. +# +do_test select3-8.1 { + execsql { + CREATE TABLE A ( + A1 DOUBLE, + A2 VARCHAR COLLATE NOCASE, + A3 DOUBLE + ); + INSERT INTO A VALUES(39136,'ABC',1201900000); + INSERT INTO A VALUES(39136,'ABC',1207000000); + SELECT typeof(sum(a3)) FROM a; + } +} {real} +do_test select3-8.2 { + execsql { + SELECT typeof(sum(a3)) FROM a GROUP BY a1; + } +} {real} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/select4.test b/components/external/SQLite-3.8.1/test/select4.test new file mode 100644 index 0000000000000000000000000000000000000000..e205b37a4f6b4731d2670a1a3b03aad9737cb885 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/select4.test @@ -0,0 +1,827 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing UNION, INTERSECT and EXCEPT operators +# in SELECT statements. +# +# $Id: select4.test,v 1.30 2009/04/16 00:24:24 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Most tests in this file depend on compound-select. But there are a couple +# right at the end that test DISTINCT, so we cannot omit the entire file. +# +ifcapable compound { + +# Build some test data +# +execsql { + CREATE TABLE t1(n int, log int); + BEGIN; +} +for {set i 1} {$i<32} {incr i} { + for {set j 0} {(1<<$j)<$i} {incr j} {} + execsql "INSERT INTO t1 VALUES($i,$j)" +} +execsql { + COMMIT; +} + +do_test select4-1.0 { + execsql {SELECT DISTINCT log FROM t1 ORDER BY log} +} {0 1 2 3 4 5} + +# Union All operator +# +do_test select4-1.1a { + lsort [execsql {SELECT DISTINCT log FROM t1}] +} {0 1 2 3 4 5} +do_test select4-1.1b { + lsort [execsql {SELECT n FROM t1 WHERE log=3}] +} {5 6 7 8} +do_test select4-1.1c { + execsql { + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + } +} {0 1 2 3 4 5 5 6 7 8} +do_test select4-1.1d { + execsql { + CREATE TABLE t2 AS + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + SELECT * FROM t2; + } +} {0 1 2 3 4 5 5 6 7 8} +execsql {DROP TABLE t2} +do_test select4-1.1e { + execsql { + CREATE TABLE t2 AS + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY log DESC; + SELECT * FROM t2; + } +} {8 7 6 5 5 4 3 2 1 0} +execsql {DROP TABLE t2} +do_test select4-1.1f { + execsql { + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=2 + } +} {0 1 2 3 4 5 3 4} +do_test select4-1.1g { + execsql { + CREATE TABLE t2 AS + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=2; + SELECT * FROM t2; + } +} {0 1 2 3 4 5 3 4} +execsql {DROP TABLE t2} +ifcapable subquery { + do_test select4-1.2 { + execsql { + SELECT log FROM t1 WHERE n IN + (SELECT DISTINCT log FROM t1 UNION ALL + SELECT n FROM t1 WHERE log=3) + ORDER BY log; + } + } {0 1 2 2 3 3 3 3} +} +do_test select4-1.3 { + set v [catch {execsql { + SELECT DISTINCT log FROM t1 ORDER BY log + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + }} msg] + lappend v $msg +} {1 {ORDER BY clause should come after UNION ALL not before}} + +# Union operator +# +do_test select4-2.1 { + execsql { + SELECT DISTINCT log FROM t1 + UNION + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + } +} {0 1 2 3 4 5 6 7 8} +ifcapable subquery { + do_test select4-2.2 { + execsql { + SELECT log FROM t1 WHERE n IN + (SELECT DISTINCT log FROM t1 UNION + SELECT n FROM t1 WHERE log=3) + ORDER BY log; + } + } {0 1 2 2 3 3 3 3} +} +do_test select4-2.3 { + set v [catch {execsql { + SELECT DISTINCT log FROM t1 ORDER BY log + UNION + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + }} msg] + lappend v $msg +} {1 {ORDER BY clause should come after UNION not before}} + +# Except operator +# +do_test select4-3.1.1 { + execsql { + SELECT DISTINCT log FROM t1 + EXCEPT + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + } +} {0 1 2 3 4} +do_test select4-3.1.2 { + execsql { + CREATE TABLE t2 AS + SELECT DISTINCT log FROM t1 + EXCEPT + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + SELECT * FROM t2; + } +} {0 1 2 3 4} +execsql {DROP TABLE t2} +do_test select4-3.1.3 { + execsql { + CREATE TABLE t2 AS + SELECT DISTINCT log FROM t1 + EXCEPT + SELECT n FROM t1 WHERE log=3 + ORDER BY log DESC; + SELECT * FROM t2; + } +} {4 3 2 1 0} +execsql {DROP TABLE t2} +ifcapable subquery { + do_test select4-3.2 { + execsql { + SELECT log FROM t1 WHERE n IN + (SELECT DISTINCT log FROM t1 EXCEPT + SELECT n FROM t1 WHERE log=3) + ORDER BY log; + } + } {0 1 2 2} +} +do_test select4-3.3 { + set v [catch {execsql { + SELECT DISTINCT log FROM t1 ORDER BY log + EXCEPT + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + }} msg] + lappend v $msg +} {1 {ORDER BY clause should come after EXCEPT not before}} + +# Intersect operator +# +do_test select4-4.1.1 { + execsql { + SELECT DISTINCT log FROM t1 + INTERSECT + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + } +} {5} + +do_test select4-4.1.2 { + execsql { + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT 6 + INTERSECT + SELECT n FROM t1 WHERE log=3 + ORDER BY t1.log; + } +} {5 6} + +do_test select4-4.1.3 { + execsql { + CREATE TABLE t2 AS + SELECT DISTINCT log FROM t1 UNION ALL SELECT 6 + INTERSECT + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + SELECT * FROM t2; + } +} {5 6} +execsql {DROP TABLE t2} +do_test select4-4.1.4 { + execsql { + CREATE TABLE t2 AS + SELECT DISTINCT log FROM t1 UNION ALL SELECT 6 + INTERSECT + SELECT n FROM t1 WHERE log=3 + ORDER BY log DESC; + SELECT * FROM t2; + } +} {6 5} +execsql {DROP TABLE t2} +ifcapable subquery { + do_test select4-4.2 { + execsql { + SELECT log FROM t1 WHERE n IN + (SELECT DISTINCT log FROM t1 INTERSECT + SELECT n FROM t1 WHERE log=3) + ORDER BY log; + } + } {3} +} +do_test select4-4.3 { + set v [catch {execsql { + SELECT DISTINCT log FROM t1 ORDER BY log + INTERSECT + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + }} msg] + lappend v $msg +} {1 {ORDER BY clause should come after INTERSECT not before}} + +# Various error messages while processing UNION or INTERSECT +# +do_test select4-5.1 { + set v [catch {execsql { + SELECT DISTINCT log FROM t2 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + }} msg] + lappend v $msg +} {1 {no such table: t2}} +do_test select4-5.2 { + set v [catch {execsql { + SELECT DISTINCT log AS "xyzzy" FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY xyzzy; + }} msg] + lappend v $msg +} {0 {0 1 2 3 4 5 5 6 7 8}} +do_test select4-5.2b { + set v [catch {execsql { + SELECT DISTINCT log AS xyzzy FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY "xyzzy"; + }} msg] + lappend v $msg +} {0 {0 1 2 3 4 5 5 6 7 8}} +do_test select4-5.2c { + set v [catch {execsql { + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY "xyzzy"; + }} msg] + lappend v $msg +} {1 {1st ORDER BY term does not match any column in the result set}} +do_test select4-5.2d { + set v [catch {execsql { + SELECT DISTINCT log FROM t1 + INTERSECT + SELECT n FROM t1 WHERE log=3 + ORDER BY "xyzzy"; + }} msg] + lappend v $msg +} {1 {1st ORDER BY term does not match any column in the result set}} +do_test select4-5.2e { + set v [catch {execsql { + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY n; + }} msg] + lappend v $msg +} {0 {0 1 2 3 4 5 5 6 7 8}} +do_test select4-5.2f { + catchsql { + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + } +} {0 {0 1 2 3 4 5 5 6 7 8}} +do_test select4-5.2g { + catchsql { + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY 1; + } +} {0 {0 1 2 3 4 5 5 6 7 8}} +do_test select4-5.2h { + catchsql { + SELECT DISTINCT log FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY 2; + } +} {1 {1st ORDER BY term out of range - should be between 1 and 1}} +do_test select4-5.2i { + catchsql { + SELECT DISTINCT 1, log FROM t1 + UNION ALL + SELECT 2, n FROM t1 WHERE log=3 + ORDER BY 2, 1; + } +} {0 {1 0 1 1 1 2 1 3 1 4 1 5 2 5 2 6 2 7 2 8}} +do_test select4-5.2j { + catchsql { + SELECT DISTINCT 1, log FROM t1 + UNION ALL + SELECT 2, n FROM t1 WHERE log=3 + ORDER BY 1, 2 DESC; + } +} {0 {1 5 1 4 1 3 1 2 1 1 1 0 2 8 2 7 2 6 2 5}} +do_test select4-5.2k { + catchsql { + SELECT DISTINCT 1, log FROM t1 + UNION ALL + SELECT 2, n FROM t1 WHERE log=3 + ORDER BY n, 1; + } +} {0 {1 0 1 1 1 2 1 3 1 4 1 5 2 5 2 6 2 7 2 8}} +do_test select4-5.3 { + set v [catch {execsql { + SELECT DISTINCT log, n FROM t1 + UNION ALL + SELECT n FROM t1 WHERE log=3 + ORDER BY log; + }} msg] + lappend v $msg +} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}} +do_test select4-5.3-3807-1 { + catchsql { + SELECT 1 UNION SELECT 2, 3 UNION SELECT 4, 5 ORDER BY 1; + } +} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}} +do_test select4-5.4 { + set v [catch {execsql { + SELECT log FROM t1 WHERE n=2 + UNION ALL + SELECT log FROM t1 WHERE n=3 + UNION ALL + SELECT log FROM t1 WHERE n=4 + UNION ALL + SELECT log FROM t1 WHERE n=5 + ORDER BY log; + }} msg] + lappend v $msg +} {0 {1 2 2 3}} + +do_test select4-6.1 { + execsql { + SELECT log, count(*) as cnt FROM t1 GROUP BY log + UNION + SELECT log, n FROM t1 WHERE n=7 + ORDER BY cnt, log; + } +} {0 1 1 1 2 2 3 4 3 7 4 8 5 15} +do_test select4-6.2 { + execsql { + SELECT log, count(*) FROM t1 GROUP BY log + UNION + SELECT log, n FROM t1 WHERE n=7 + ORDER BY count(*), log; + } +} {0 1 1 1 2 2 3 4 3 7 4 8 5 15} + +# NULLs are indistinct for the UNION operator. +# Make sure the UNION operator recognizes this +# +do_test select4-6.3 { + execsql { + SELECT NULL UNION SELECT NULL UNION + SELECT 1 UNION SELECT 2 AS 'x' + ORDER BY x; + } +} {{} 1 2} +do_test select4-6.3.1 { + execsql { + SELECT NULL UNION ALL SELECT NULL UNION ALL + SELECT 1 UNION ALL SELECT 2 AS 'x' + ORDER BY x; + } +} {{} {} 1 2} + +# Make sure the DISTINCT keyword treats NULLs as indistinct. +# +ifcapable subquery { + do_test select4-6.4 { + execsql { + SELECT * FROM ( + SELECT NULL, 1 UNION ALL SELECT NULL, 1 + ); + } + } {{} 1 {} 1} + do_test select4-6.5 { + execsql { + SELECT DISTINCT * FROM ( + SELECT NULL, 1 UNION ALL SELECT NULL, 1 + ); + } + } {{} 1} + do_test select4-6.6 { + execsql { + SELECT DISTINCT * FROM ( + SELECT 1,2 UNION ALL SELECT 1,2 + ); + } + } {1 2} +} + +# Test distinctness of NULL in other ways. +# +do_test select4-6.7 { + execsql { + SELECT NULL EXCEPT SELECT NULL + } +} {} + + +# Make sure column names are correct when a compound select appears as +# an expression in the WHERE clause. +# +do_test select4-7.1 { + execsql { + CREATE TABLE t2 AS SELECT log AS 'x', count(*) AS 'y' FROM t1 GROUP BY log; + SELECT * FROM t2 ORDER BY x; + } +} {0 1 1 1 2 2 3 4 4 8 5 15} +ifcapable subquery { + do_test select4-7.2 { + execsql2 { + SELECT * FROM t1 WHERE n IN (SELECT n FROM t1 INTERSECT SELECT x FROM t2) + ORDER BY n + } + } {n 1 log 0 n 2 log 1 n 3 log 2 n 4 log 2 n 5 log 3} + do_test select4-7.3 { + execsql2 { + SELECT * FROM t1 WHERE n IN (SELECT n FROM t1 EXCEPT SELECT x FROM t2) + ORDER BY n LIMIT 2 + } + } {n 6 log 3 n 7 log 3} + do_test select4-7.4 { + execsql2 { + SELECT * FROM t1 WHERE n IN (SELECT n FROM t1 UNION SELECT x FROM t2) + ORDER BY n LIMIT 2 + } + } {n 1 log 0 n 2 log 1} +} ;# ifcapable subquery + +} ;# ifcapable compound + +# Make sure DISTINCT works appropriately on TEXT and NUMERIC columns. +do_test select4-8.1 { + execsql { + BEGIN; + CREATE TABLE t3(a text, b float, c text); + INSERT INTO t3 VALUES(1, 1.1, '1.1'); + INSERT INTO t3 VALUES(2, 1.10, '1.10'); + INSERT INTO t3 VALUES(3, 1.10, '1.1'); + INSERT INTO t3 VALUES(4, 1.1, '1.10'); + INSERT INTO t3 VALUES(5, 1.2, '1.2'); + INSERT INTO t3 VALUES(6, 1.3, '1.3'); + COMMIT; + } + execsql { + SELECT DISTINCT b FROM t3 ORDER BY c; + } +} {1.1 1.2 1.3} +do_test select4-8.2 { + execsql { + SELECT DISTINCT c FROM t3 ORDER BY c; + } +} {1.1 1.10 1.2 1.3} + +# Make sure the names of columns are taken from the right-most subquery +# right in a compound query. Ticket #1721 +# +ifcapable compound { + +do_test select4-9.1 { + execsql2 { + SELECT x, y FROM t2 UNION SELECT a, b FROM t3 ORDER BY x LIMIT 1 + } +} {x 0 y 1} +do_test select4-9.2 { + execsql2 { + SELECT x, y FROM t2 UNION ALL SELECT a, b FROM t3 ORDER BY x LIMIT 1 + } +} {x 0 y 1} +do_test select4-9.3 { + execsql2 { + SELECT x, y FROM t2 EXCEPT SELECT a, b FROM t3 ORDER BY x LIMIT 1 + } +} {x 0 y 1} +do_test select4-9.4 { + execsql2 { + SELECT x, y FROM t2 INTERSECT SELECT 0 AS a, 1 AS b; + } +} {x 0 y 1} +do_test select4-9.5 { + execsql2 { + SELECT 0 AS x, 1 AS y + UNION + SELECT 2 AS p, 3 AS q + UNION + SELECT 4 AS a, 5 AS b + ORDER BY x LIMIT 1 + } +} {x 0 y 1} + +ifcapable subquery { +do_test select4-9.6 { + execsql2 { + SELECT * FROM ( + SELECT 0 AS x, 1 AS y + UNION + SELECT 2 AS p, 3 AS q + UNION + SELECT 4 AS a, 5 AS b + ) ORDER BY 1 LIMIT 1; + } +} {x 0 y 1} +do_test select4-9.7 { + execsql2 { + SELECT * FROM ( + SELECT 0 AS x, 1 AS y + UNION + SELECT 2 AS p, 3 AS q + UNION + SELECT 4 AS a, 5 AS b + ) ORDER BY x LIMIT 1; + } +} {x 0 y 1} +} ;# ifcapable subquery + +do_test select4-9.8 { + execsql { + SELECT 0 AS x, 1 AS y + UNION + SELECT 2 AS y, -3 AS x + ORDER BY x LIMIT 1; + } +} {0 1} + +do_test select4-9.9.1 { + execsql2 { + SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS b, 4 AS a + } +} {a 1 b 2 a 3 b 4} + +ifcapable subquery { +do_test select4-9.9.2 { + execsql2 { + SELECT * FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS b, 4 AS a) + WHERE b=3 + } +} {} +do_test select4-9.10 { + execsql2 { + SELECT * FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS b, 4 AS a) + WHERE b=2 + } +} {a 1 b 2} +do_test select4-9.11 { + execsql2 { + SELECT * FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS e, 4 AS b) + WHERE b=2 + } +} {a 1 b 2} +do_test select4-9.12 { + execsql2 { + SELECT * FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS e, 4 AS b) + WHERE b>0 + } +} {a 1 b 2 a 3 b 4} +} ;# ifcapable subquery + +# Try combining DISTINCT, LIMIT, and OFFSET. Make sure they all work +# together. +# +do_test select4-10.1 { + execsql { + SELECT DISTINCT log FROM t1 ORDER BY log + } +} {0 1 2 3 4 5} +do_test select4-10.2 { + execsql { + SELECT DISTINCT log FROM t1 ORDER BY log LIMIT 4 + } +} {0 1 2 3} +do_test select4-10.3 { + execsql { + SELECT DISTINCT log FROM t1 ORDER BY log LIMIT 0 + } +} {} +do_test select4-10.4 { + execsql { + SELECT DISTINCT log FROM t1 ORDER BY log LIMIT -1 + } +} {0 1 2 3 4 5} +do_test select4-10.5 { + execsql { + SELECT DISTINCT log FROM t1 ORDER BY log LIMIT -1 OFFSET 2 + } +} {2 3 4 5} +do_test select4-10.6 { + execsql { + SELECT DISTINCT log FROM t1 ORDER BY log LIMIT 3 OFFSET 2 + } +} {2 3 4} +do_test select4-10.7 { + execsql { + SELECT DISTINCT log FROM t1 ORDER BY +log LIMIT 3 OFFSET 20 + } +} {} +do_test select4-10.8 { + execsql { + SELECT DISTINCT log FROM t1 ORDER BY log LIMIT 0 OFFSET 3 + } +} {} +do_test select4-10.9 { + execsql { + SELECT DISTINCT max(n), log FROM t1 ORDER BY +log; -- LIMIT 2 OFFSET 1 + } +} {31 5} + +# Make sure compound SELECTs with wildly different numbers of columns +# do not cause assertion faults due to register allocation issues. +# +do_test select4-11.1 { + catchsql { + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + UNION + SELECT x FROM t2 + } +} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}} +do_test select4-11.2 { + catchsql { + SELECT x FROM t2 + UNION + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + } +} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}} +do_test select4-11.3 { + catchsql { + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + UNION ALL + SELECT x FROM t2 + } +} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}} +do_test select4-11.4 { + catchsql { + SELECT x FROM t2 + UNION ALL + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + } +} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}} +do_test select4-11.5 { + catchsql { + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + EXCEPT + SELECT x FROM t2 + } +} {1 {SELECTs to the left and right of EXCEPT do not have the same number of result columns}} +do_test select4-11.6 { + catchsql { + SELECT x FROM t2 + EXCEPT + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + } +} {1 {SELECTs to the left and right of EXCEPT do not have the same number of result columns}} +do_test select4-11.7 { + catchsql { + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + INTERSECT + SELECT x FROM t2 + } +} {1 {SELECTs to the left and right of INTERSECT do not have the same number of result columns}} +do_test select4-11.8 { + catchsql { + SELECT x FROM t2 + INTERSECT + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + } +} {1 {SELECTs to the left and right of INTERSECT do not have the same number of result columns}} + +do_test select4-11.11 { + catchsql { + SELECT x FROM t2 + UNION + SELECT x FROM t2 + UNION ALL + SELECT x FROM t2 + EXCEPT + SELECT x FROM t2 + INTERSECT + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + } +} {1 {SELECTs to the left and right of INTERSECT do not have the same number of result columns}} +do_test select4-11.12 { + catchsql { + SELECT x FROM t2 + UNION + SELECT x FROM t2 + UNION ALL + SELECT x FROM t2 + EXCEPT + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + EXCEPT + SELECT x FROM t2 + } +} {1 {SELECTs to the left and right of EXCEPT do not have the same number of result columns}} +do_test select4-11.13 { + catchsql { + SELECT x FROM t2 + UNION + SELECT x FROM t2 + UNION ALL + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + UNION ALL + SELECT x FROM t2 + EXCEPT + SELECT x FROM t2 + } +} {1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}} +do_test select4-11.14 { + catchsql { + SELECT x FROM t2 + UNION + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + UNION + SELECT x FROM t2 + UNION ALL + SELECT x FROM t2 + EXCEPT + SELECT x FROM t2 + } +} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}} +do_test select4-11.15 { + catchsql { + SELECT x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x FROM t2 + UNION + SELECT x FROM t2 + INTERSECT + SELECT x FROM t2 + UNION ALL + SELECT x FROM t2 + EXCEPT + SELECT x FROM t2 + } +} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}} + +do_test select4-12.1 { + sqlite3 db2 :memory: + catchsql { + SELECT 1 UNION SELECT 2,3 UNION SELECT 4,5 ORDER BY 1; + } db2 +} {1 {SELECTs to the left and right of UNION do not have the same number of result columns}} + +} ;# ifcapable compound + + +# Ticket [3557ad65a076c] - Incorrect DISTINCT processing with an +# indexed query using IN. +# +do_test select4-13.1 { + sqlite3 db test.db + db eval { + CREATE TABLE t13(a,b); + INSERT INTO t13 VALUES(1,1); + INSERT INTO t13 VALUES(2,1); + INSERT INTO t13 VALUES(3,1); + INSERT INTO t13 VALUES(2,2); + INSERT INTO t13 VALUES(3,2); + INSERT INTO t13 VALUES(4,2); + CREATE INDEX t13ab ON t13(a,b); + SELECT DISTINCT b from t13 WHERE a IN (1,2,3); + } +} {1 2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/select5.test b/components/external/SQLite-3.8.1/test/select5.test new file mode 100644 index 0000000000000000000000000000000000000000..3a787fc767aff05cbfcd47ae9b2b68fb72269373 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/select5.test @@ -0,0 +1,257 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing aggregate functions and the +# GROUP BY and HAVING clauses of SELECT statements. +# +# $Id: select5.test,v 1.20 2008/08/21 14:15:59 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build some test data +# +execsql { + CREATE TABLE t1(x int, y int); + BEGIN; +} +for {set i 1} {$i<32} {incr i} { + for {set j 0} {(1<<$j)<$i} {incr j} {} + execsql "INSERT INTO t1 VALUES([expr {32-$i}],[expr {10-$j}])" +} +execsql { + COMMIT +} + +do_test select5-1.0 { + execsql {SELECT DISTINCT y FROM t1 ORDER BY y} +} {5 6 7 8 9 10} + +# Sort by an aggregate function. +# +do_test select5-1.1 { + execsql {SELECT y, count(*) FROM t1 GROUP BY y ORDER BY y} +} {5 15 6 8 7 4 8 2 9 1 10 1} +do_test select5-1.2 { + execsql {SELECT y, count(*) FROM t1 GROUP BY y ORDER BY count(*), y} +} {9 1 10 1 8 2 7 4 6 8 5 15} +do_test select5-1.3 { + execsql {SELECT count(*), y FROM t1 GROUP BY y ORDER BY count(*), y} +} {1 9 1 10 2 8 4 7 8 6 15 5} + +# Some error messages associated with aggregates and GROUP BY +# +do_test select5-2.1.1 { + catchsql { + SELECT y, count(*) FROM t1 GROUP BY z ORDER BY y + } +} {1 {no such column: z}} +do_test select5-2.1.2 { + catchsql { + SELECT y, count(*) FROM t1 GROUP BY temp.t1.y ORDER BY y + } +} {1 {no such column: temp.t1.y}} +do_test select5-2.2 { + set v [catch {execsql { + SELECT y, count(*) FROM t1 GROUP BY z(y) ORDER BY y + }} msg] + lappend v $msg +} {1 {no such function: z}} +do_test select5-2.3 { + set v [catch {execsql { + SELECT y, count(*) FROM t1 GROUP BY y HAVING count(*)<3 ORDER BY y + }} msg] + lappend v $msg +} {0 {8 2 9 1 10 1}} +do_test select5-2.4 { + set v [catch {execsql { + SELECT y, count(*) FROM t1 GROUP BY y HAVING z(y)<3 ORDER BY y + }} msg] + lappend v $msg +} {1 {no such function: z}} +do_test select5-2.5 { + set v [catch {execsql { + SELECT y, count(*) FROM t1 GROUP BY y HAVING count(*)100 + } +} {{}} +do_test select5-4.2 { + execsql { + SELECT count(x) FROM t1 WHERE x>100 + } +} {0} +do_test select5-4.3 { + execsql { + SELECT min(x) FROM t1 WHERE x>100 + } +} {{}} +do_test select5-4.4 { + execsql { + SELECT max(x) FROM t1 WHERE x>100 + } +} {{}} +do_test select5-4.5 { + execsql { + SELECT sum(x) FROM t1 WHERE x>100 + } +} {{}} + +# Some tests for queries with a GROUP BY clause but no aggregate functions. +# +# Note: The query in test cases 5.1 through 5.5 are not legal SQL. So if the +# implementation changes in the future and it returns different results, +# this is not such a big deal. +# +do_test select5-5.1 { + execsql { + CREATE TABLE t2(a, b, c); + INSERT INTO t2 VALUES(1, 2, 3); + INSERT INTO t2 VALUES(1, 4, 5); + INSERT INTO t2 VALUES(6, 4, 7); + CREATE INDEX t2_idx ON t2(a); + } +} {} +do_test select5-5.2 { + execsql { + SELECT a FROM t2 GROUP BY a; + } +} {1 6} +do_test select5-5.3 { + execsql { + SELECT a FROM t2 WHERE a>2 GROUP BY a; + } +} {6} +do_test select5-5.4 { + execsql { + SELECT a, b FROM t2 GROUP BY a, b; + } +} {1 2 1 4 6 4} +do_test select5-5.5 { + execsql { + SELECT a, b FROM t2 GROUP BY a; + } +} {1 4 6 4} + +# Test rendering of columns for the GROUP BY clause. +# +do_test select5-5.11 { + execsql { + SELECT max(c), b*a, b, a FROM t2 GROUP BY b*a, b, a + } +} {3 2 2 1 5 4 4 1 7 24 4 6} + +# NULL compare equal to each other for the purposes of processing +# the GROUP BY clause. +# +do_test select5-6.1 { + execsql { + CREATE TABLE t3(x,y); + INSERT INTO t3 VALUES(1,NULL); + INSERT INTO t3 VALUES(2,NULL); + INSERT INTO t3 VALUES(3,4); + SELECT count(x), y FROM t3 GROUP BY y ORDER BY 1 + } +} {1 4 2 {}} +do_test select5-6.2 { + execsql { + CREATE TABLE t4(x,y,z); + INSERT INTO t4 VALUES(1,2,NULL); + INSERT INTO t4 VALUES(2,3,NULL); + INSERT INTO t4 VALUES(3,NULL,5); + INSERT INTO t4 VALUES(4,NULL,6); + INSERT INTO t4 VALUES(4,NULL,6); + INSERT INTO t4 VALUES(5,NULL,NULL); + INSERT INTO t4 VALUES(5,NULL,NULL); + INSERT INTO t4 VALUES(6,7,8); + SELECT max(x), count(x), y, z FROM t4 GROUP BY y, z ORDER BY 1 + } +} {1 1 2 {} 2 1 3 {} 3 1 {} 5 4 2 {} 6 5 2 {} {} 6 1 7 8} + +do_test select5-7.2 { + execsql { + SELECT count(*), count(x) as cnt FROM t4 GROUP BY y ORDER BY cnt; + } +} {1 1 1 1 1 1 5 5} + +# See ticket #3324. +# +do_test select5-8.1 { + execsql { + CREATE TABLE t8a(a,b); + CREATE TABLE t8b(x); + INSERT INTO t8a VALUES('one', 1); + INSERT INTO t8a VALUES('one', 2); + INSERT INTO t8a VALUES('two', 3); + INSERT INTO t8a VALUES('one', NULL); + INSERT INTO t8b(rowid,x) VALUES(1,111); + INSERT INTO t8b(rowid,x) VALUES(2,222); + INSERT INTO t8b(rowid,x) VALUES(3,333); + SELECT a, count(b) FROM t8a, t8b WHERE b=t8b.rowid GROUP BY a ORDER BY a; + } +} {one 2 two 1} +do_test select5-8.2 { + execsql { + SELECT a, count(b) FROM t8a, t8b WHERE b=+t8b.rowid GROUP BY a ORDER BY a; + } +} {one 2 two 1} +do_test select5-8.3 { + execsql { + SELECT t8a.a, count(t8a.b) FROM t8a, t8b WHERE t8a.b=t8b.rowid + GROUP BY 1 ORDER BY 1; + } +} {one 2 two 1} +do_test select5-8.4 { + execsql { + SELECT a, count(*) FROM t8a, t8b WHERE b=+t8b.rowid GROUP BY a ORDER BY a; + } +} {one 2 two 1} +do_test select5-8.5 { + execsql { + SELECT a, count(b) FROM t8a, t8b WHERE b10 + } +} {10.5 3.7 14.2} +do_test select6-3.7 { + execsql { + SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1) + WHERE a<10 + } +} {} +do_test select6-3.8 { + execsql { + SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1 WHERE y=4) + WHERE a>10 + } +} {11.5 4.0 15.5} +do_test select6-3.9 { + execsql { + SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1 WHERE y=4) + WHERE a<10 + } +} {} +do_test select6-3.10 { + execsql { + SELECT a,b,a+b FROM (SELECT avg(x) as 'a', y as 'b' FROM t1 GROUP BY b) + ORDER BY a + } +} {1.0 1 2.0 2.5 2 4.5 5.5 3 8.5 11.5 4 15.5 18.0 5 23.0} +do_test select6-3.11 { + execsql { + SELECT a,b,a+b FROM + (SELECT avg(x) as 'a', y as 'b' FROM t1 GROUP BY b) + WHERE b<4 ORDER BY a + } +} {1.0 1 2.0 2.5 2 4.5 5.5 3 8.5} +do_test select6-3.12 { + execsql { + SELECT a,b,a+b FROM + (SELECT avg(x) as 'a', y as 'b' FROM t1 GROUP BY b HAVING a>1) + WHERE b<4 ORDER BY a + } +} {2.5 2 4.5 5.5 3 8.5} +do_test select6-3.13 { + execsql { + SELECT a,b,a+b FROM + (SELECT avg(x) as 'a', y as 'b' FROM t1 GROUP BY b HAVING a>1) + ORDER BY a + } +} {2.5 2 4.5 5.5 3 8.5 11.5 4 15.5 18.0 5 23.0} +do_test select6-3.14 { + execsql { + SELECT [count(*)],y FROM (SELECT count(*), y FROM t1 GROUP BY y) + ORDER BY [count(*)] + } +} {1 1 2 2 4 3 5 5 8 4} +do_test select6-3.15 { + execsql { + SELECT [count(*)],y FROM (SELECT count(*), y FROM t1 GROUP BY y) + ORDER BY y + } +} {1 1 2 2 4 3 8 4 5 5} + +do_test select6-4.1 { + execsql { + SELECT a,b,c FROM + (SELECT x AS 'a', y AS 'b', x+y AS 'c' FROM t1 WHERE y=4) + WHERE a<10 ORDER BY a; + } +} {8 4 12 9 4 13} +do_test select6-4.2 { + execsql { + SELECT y FROM (SELECT DISTINCT y FROM t1) WHERE y<5 ORDER BY y + } +} {1 2 3 4} +do_test select6-4.3 { + execsql { + SELECT DISTINCT y FROM (SELECT y FROM t1) WHERE y<5 ORDER BY y + } +} {1 2 3 4} +do_test select6-4.4 { + execsql { + SELECT avg(y) FROM (SELECT DISTINCT y FROM t1) WHERE y<5 ORDER BY y + } +} {2.5} +do_test select6-4.5 { + execsql { + SELECT avg(y) FROM (SELECT DISTINCT y FROM t1 WHERE y<5) ORDER BY y + } +} {2.5} + +do_test select6-5.1 { + execsql { + SELECT a,x,b FROM + (SELECT x+3 AS 'a', x FROM t1 WHERE y=3) AS 'p', + (SELECT x AS 'b' FROM t1 WHERE y=4) AS 'q' + WHERE a=b + ORDER BY a + } +} {8 5 8 9 6 9 10 7 10} +do_test select6-5.2 { + execsql { + SELECT a,x,b FROM + (SELECT x+3 AS 'a', x FROM t1 WHERE y=3), + (SELECT x AS 'b' FROM t1 WHERE y=4) + WHERE a=b + ORDER BY a + } +} {8 5 8 9 6 9 10 7 10} + +# Tests of compound sub-selects +# +do_test select6-6.1 { + execsql { + DELETE FROM t1 WHERE x>4; + SELECT * FROM t1 + } +} {1 1 2 2 3 2 4 3} +ifcapable compound { + do_test select6-6.2 { + execsql { + SELECT * FROM ( + SELECT x AS 'a' FROM t1 UNION ALL SELECT x+10 AS 'a' FROM t1 + ) ORDER BY a; + } + } {1 2 3 4 11 12 13 14} + do_test select6-6.3 { + execsql { + SELECT * FROM ( + SELECT x AS 'a' FROM t1 UNION ALL SELECT x+1 AS 'a' FROM t1 + ) ORDER BY a; + } + } {1 2 2 3 3 4 4 5} + do_test select6-6.4 { + execsql { + SELECT * FROM ( + SELECT x AS 'a' FROM t1 UNION SELECT x+1 AS 'a' FROM t1 + ) ORDER BY a; + } + } {1 2 3 4 5} + do_test select6-6.5 { + execsql { + SELECT * FROM ( + SELECT x AS 'a' FROM t1 INTERSECT SELECT x+1 AS 'a' FROM t1 + ) ORDER BY a; + } + } {2 3 4} + do_test select6-6.6 { + execsql { + SELECT * FROM ( + SELECT x AS 'a' FROM t1 EXCEPT SELECT x*2 AS 'a' FROM t1 + ) ORDER BY a; + } + } {1 3} +} ;# ifcapable compound + +# Subselects with no FROM clause +# +do_test select6-7.1 { + execsql { + SELECT * FROM (SELECT 1) + } +} {1} +do_test select6-7.2 { + execsql { + SELECT c,b,a,* FROM (SELECT 1 AS 'a', 2 AS 'b', 'abc' AS 'c') + } +} {abc 2 1 1 2 abc} +do_test select6-7.3 { + execsql { + SELECT c,b,a,* FROM (SELECT 1 AS 'a', 2 AS 'b', 'abc' AS 'c' WHERE 0) + } +} {} +do_test select6-7.4 { + execsql2 { + SELECT c,b,a,* FROM (SELECT 1 AS 'a', 2 AS 'b', 'abc' AS 'c' WHERE 1) + } +} {c abc b 2 a 1 a 1 b 2 c abc} + +# The remaining tests in this file depend on the EXPLAIN keyword. +# Skip these tests if EXPLAIN is disabled in the current build. +# +ifcapable {!explain} { + finish_test + return +} + +# The following procedure compiles the SQL given as an argument and returns +# TRUE if that SQL uses any transient tables and returns FALSE if no +# transient tables are used. This is used to make sure that the +# sqliteFlattenSubquery() routine in select.c is doing its job. +# +proc is_flat {sql} { + return [expr 0>[lsearch [execsql "EXPLAIN $sql"] OpenEphemeral]] +} + +# Check that the flattener works correctly for deeply nested subqueries +# involving joins. +# +do_test select6-8.1 { + execsql { + BEGIN; + CREATE TABLE t3(p,q); + INSERT INTO t3 VALUES(1,11); + INSERT INTO t3 VALUES(2,22); + CREATE TABLE t4(q,r); + INSERT INTO t4 VALUES(11,111); + INSERT INTO t4 VALUES(22,222); + COMMIT; + SELECT * FROM t3 NATURAL JOIN t4; + } +} {1 11 111 2 22 222} +do_test select6-8.2 { + execsql { + SELECT y, p, q, r FROM + (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m, + (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n + WHERE y=p + } +} {1 1 11 111 2 2 22 222 2 2 22 222} +# If view support is omitted from the build, then so is the query +# "flattener". So omit this test and test select6-8.6 in that case. +ifcapable view { +do_test select6-8.3 { + is_flat { + SELECT y, p, q, r FROM + (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m, + (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n + WHERE y=p + } +} {1} +} ;# ifcapable view +do_test select6-8.4 { + execsql { + SELECT DISTINCT y, p, q, r FROM + (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m, + (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n + WHERE y=p + } +} {1 1 11 111 2 2 22 222} +do_test select6-8.5 { + execsql { + SELECT * FROM + (SELECT y, p, q, r FROM + (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m, + (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n + WHERE y=p) AS e, + (SELECT r AS z FROM t4 WHERE q=11) AS f + WHERE e.r=f.z + } +} {1 1 11 111 111} +ifcapable view { +do_test select6-8.6 { + is_flat { + SELECT * FROM + (SELECT y, p, q, r FROM + (SELECT t1.y AS y, t2.b AS b FROM t1, t2 WHERE t1.x=t2.a) AS m, + (SELECT t3.p AS p, t3.q AS q, t4.r AS r FROM t3 NATURAL JOIN t4) as n + WHERE y=p) AS e, + (SELECT r AS z FROM t4 WHERE q=11) AS f + WHERE e.r=f.z + } +} {1} +} ;# ifcapable view + +# Ticket #1634 +# +do_test select6-9.1 { + execsql { + SELECT a.x, b.x FROM t1 AS a, (SELECT x FROM t1 LIMIT 2) AS b + ORDER BY 1, 2 + } +} {1 1 1 2 2 1 2 2 3 1 3 2 4 1 4 2} +do_test select6-9.2 { + execsql { + SELECT x FROM (SELECT x FROM t1 LIMIT 2); + } +} {1 2} +do_test select6-9.3 { + execsql { + SELECT x FROM (SELECT x FROM t1 LIMIT 2 OFFSET 1); + } +} {2 3} +do_test select6-9.4 { + execsql { + SELECT x FROM (SELECT x FROM t1) LIMIT 2; + } +} {1 2} +do_test select6-9.5 { + execsql { + SELECT x FROM (SELECT x FROM t1) LIMIT 2 OFFSET 1; + } +} {2 3} +do_test select6-9.6 { + execsql { + SELECT x FROM (SELECT x FROM t1 LIMIT 2) LIMIT 3; + } +} {1 2} +do_test select6-9.7 { + execsql { + SELECT x FROM (SELECT x FROM t1 LIMIT -1) LIMIT 3; + } +} {1 2 3} +do_test select6-9.8 { + execsql { + SELECT x FROM (SELECT x FROM t1 LIMIT -1); + } +} {1 2 3 4} +do_test select6-9.9 { + execsql { + SELECT x FROM (SELECT x FROM t1 LIMIT -1 OFFSET 1); + } +} {2 3 4} +do_test select6-9.10 { + execsql { + SELECT x, y FROM (SELECT x, (SELECT 10+x) y FROM t1 LIMIT -1 OFFSET 1); + } +} {2 12 3 13 4 14} +do_test select6-9.11 { + execsql { + SELECT x, y FROM (SELECT x, (SELECT 10)+x y FROM t1 LIMIT -1 OFFSET 1); + } +} {2 12 3 13 4 14} + + +#------------------------------------------------------------------------- +# Test that if a UNION ALL sub-query that would otherwise be eligible for +# flattening consists of two or more SELECT statements that do not all +# return the same number of result columns, the error is detected. +# +do_execsql_test 10.1 { + CREATE TABLE t(i,j,k); + CREATE TABLE j(l,m); + CREATE TABLE k(o); +} + +set err [list 1 {SELECTs to the left and right of UNION ALL do not have the same number of result columns}] + +do_execsql_test 10.2 { + SELECT * FROM (SELECT * FROM t), j; +} +do_catchsql_test 10.3 { + SELECT * FROM t UNION ALL SELECT * FROM j +} $err +do_catchsql_test 10.4 { + SELECT * FROM (SELECT i FROM t UNION ALL SELECT l, m FROM j) +} $err +do_catchsql_test 10.5 { + SELECT * FROM (SELECT j FROM t UNION ALL SELECT * FROM j) +} $err +do_catchsql_test 10.6 { + SELECT * FROM (SELECT * FROM t UNION ALL SELECT * FROM j) +} $err +do_catchsql_test 10.7 { + SELECT * FROM ( + SELECT * FROM t UNION ALL + SELECT l,m,l FROM j UNION ALL + SELECT * FROM k + ) +} $err +do_catchsql_test 10.8 { + SELECT * FROM ( + SELECT * FROM k UNION ALL + SELECT * FROM t UNION ALL + SELECT l,m,l FROM j + ) +} $err + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/select7.test b/components/external/SQLite-3.8.1/test/select7.test new file mode 100644 index 0000000000000000000000000000000000000000..e8fc4400064faa52317ac439f0dad2cd7b75df19 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/select7.test @@ -0,0 +1,202 @@ +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing compute SELECT statements and nested +# views. +# +# $Id: select7.test,v 1.11 2007/09/12 17:01:45 danielk1977 Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable compound { + +# A 3-way INTERSECT. Ticket #875 +ifcapable tempdb { + do_test select7-1.1 { + execsql { + create temp table t1(x); + insert into t1 values('amx'); + insert into t1 values('anx'); + insert into t1 values('amy'); + insert into t1 values('bmy'); + select * from t1 where x like 'a__' + intersect select * from t1 where x like '_m_' + intersect select * from t1 where x like '__x'; + } + } {amx} +} + + +# Nested views do not handle * properly. Ticket #826. +# +ifcapable view { +do_test select7-2.1 { + execsql { + CREATE TABLE x(id integer primary key, a TEXT NULL); + INSERT INTO x (a) VALUES ('first'); + CREATE TABLE tempx(id integer primary key, a TEXT NULL); + INSERT INTO tempx (a) VALUES ('t-first'); + CREATE VIEW tv1 AS SELECT x.id, tx.id FROM x JOIN tempx tx ON tx.id=x.id; + CREATE VIEW tv1b AS SELECT x.id, tx.id FROM x JOIN tempx tx on tx.id=x.id; + CREATE VIEW tv2 AS SELECT * FROM tv1 UNION SELECT * FROM tv1b; + SELECT * FROM tv2; + } +} {1 1} +} ;# ifcapable view + +} ;# ifcapable compound + +# Do not allow GROUP BY without an aggregate. Ticket #1039. +# +# Change: force any query with a GROUP BY clause to be processed as +# an aggregate query, whether it contains aggregates or not. +# +ifcapable subquery { + # do_test select7-3.1 { + # catchsql { + # SELECT * FROM (SELECT * FROM sqlite_master) GROUP BY name + # } + # } {1 {GROUP BY may only be used on aggregate queries}} + do_test select7-3.1 { + catchsql { + SELECT * FROM (SELECT * FROM sqlite_master) GROUP BY name + } + } [list 0 [execsql {SELECT * FROM sqlite_master ORDER BY name}]] +} + +# Ticket #2018 - Make sure names are resolved correctly on all +# SELECT statements of a compound subquery. +# +ifcapable {subquery && compound} { + do_test select7-4.1 { + execsql { + CREATE TABLE IF NOT EXISTS photo(pk integer primary key, x); + CREATE TABLE IF NOT EXISTS tag(pk integer primary key, fk int, name); + + SELECT P.pk from PHOTO P WHERE NOT EXISTS ( + SELECT T2.pk from TAG T2 WHERE T2.fk = P.pk + EXCEPT + SELECT T3.pk from TAG T3 WHERE T3.fk = P.pk AND T3.name LIKE '%foo%' + ); + } + } {} + do_test select7-4.2 { + execsql { + INSERT INTO photo VALUES(1,1); + INSERT INTO photo VALUES(2,2); + INSERT INTO photo VALUES(3,3); + INSERT INTO tag VALUES(11,1,'one'); + INSERT INTO tag VALUES(12,1,'two'); + INSERT INTO tag VALUES(21,1,'one-b'); + SELECT P.pk from PHOTO P WHERE NOT EXISTS ( + SELECT T2.pk from TAG T2 WHERE T2.fk = P.pk + EXCEPT + SELECT T3.pk from TAG T3 WHERE T3.fk = P.pk AND T3.name LIKE '%foo%' + ); + } + } {2 3} +} + +# ticket #2347 +# +ifcapable {subquery && compound} { + do_test select7-5.1 { + catchsql { + CREATE TABLE t2(a,b); + SELECT 5 IN (SELECT a,b FROM t2); + } + } [list 1 \ + {only a single result allowed for a SELECT that is part of an expression}] + do_test select7-5.2 { + catchsql { + SELECT 5 IN (SELECT * FROM t2); + } + } [list 1 \ + {only a single result allowed for a SELECT that is part of an expression}] + do_test select7-5.3 { + catchsql { + SELECT 5 IN (SELECT a,b FROM t2 UNION SELECT b,a FROM t2); + } + } [list 1 \ + {only a single result allowed for a SELECT that is part of an expression}] + do_test select7-5.4 { + catchsql { + SELECT 5 IN (SELECT * FROM t2 UNION SELECT * FROM t2); + } + } [list 1 \ + {only a single result allowed for a SELECT that is part of an expression}] +} + +# Verify that an error occurs if you have too many terms on a +# compound select statement. +# +ifcapable compound { + if {$SQLITE_MAX_COMPOUND_SELECT>0} { + set sql {SELECT 0} + set result 0 + for {set i 1} {$i<$SQLITE_MAX_COMPOUND_SELECT} {incr i} { + append sql " UNION ALL SELECT $i" + lappend result $i + } + do_test select7-6.1 { + catchsql $sql + } [list 0 $result] + append sql { UNION ALL SELECT 99999999} + do_test select7-6.2 { + catchsql $sql + } {1 {too many terms in compound SELECT}} + } +} + +# This block of tests verifies that bug aa92c76cd4 is fixed. +# +do_test select7-7.1 { + execsql { + CREATE TABLE t3(a REAL); + INSERT INTO t3 VALUES(44.0); + INSERT INTO t3 VALUES(56.0); + } +} {} +do_test select7-7.2 { + execsql { + pragma vdbe_trace = 0; + SELECT (CASE WHEN a=0 THEN 0 ELSE (a + 25) / 50 END) AS categ, count(*) + FROM t3 GROUP BY categ + } +} {1.38 1 1.62 1} +do_test select7-7.3 { + execsql { + CREATE TABLE t4(a REAL); + INSERT INTO t4 VALUES( 2.0 ); + INSERT INTO t4 VALUES( 3.0 ); + } +} {} +do_test select7-7.4 { + execsql { + SELECT (CASE WHEN a=0 THEN 'zero' ELSE a/2 END) AS t FROM t4 GROUP BY t; + } +} {1.0 1.5} +do_test select7-7.5 { + execsql { SELECT a=0, typeof(a) FROM t4 } +} {0 real 0 real} +do_test select7-7.6 { + execsql { SELECT a=0, typeof(a) FROM t4 GROUP BY a } +} {0 real 0 real} + +do_test select7-7.7 { + execsql { + CREATE TABLE t5(a TEXT, b INT); + INSERT INTO t5 VALUES(123, 456); + SELECT typeof(a), a FROM t5 GROUP BY a HAVING a=5} { + set iOffsetIncr [expr $nRow / 5] + set iLimitIncr [expr $nRow / 5] + } + + set iLimitEnd [expr $nRow+$iLimitIncr] + set iOffsetEnd [expr $nRow+$iOffsetIncr] + + for {set iOffset 0} {$iOffset < $iOffsetEnd} {incr iOffset $iOffsetIncr} { + for {set iLimit 0} {$iLimit < $iLimitEnd} {incr iLimit} { + + set ::compound_sql "$sql LIMIT $iLimit" + if {$iOffset != 0} { + append ::compound_sql " OFFSET $iOffset" + } + + set iStart [expr {$iOffset*$nCol}] + set iEnd [expr {($iOffset*$nCol) + ($iLimit*$nCol) -1}] + + do_test $testname.limit=$iLimit.offset=$iOffset { + execsql $::compound_sql + } [lrange $result $iStart $iEnd] + } + } +} + +#------------------------------------------------------------------------- +# test_compound_select_flippable TESTNAME SELECT RESULT +# +# This command is for testing statements of the form: +# +# ORDER BY +# +# where each is a simple (non-compound) select statement +# and is one of "INTERSECT", "UNION ALL" or "UNION". +# +# This proc calls [test_compound_select] twice, once with the select +# statement as it is passed to this command, and once with the positions +# of exchanged. +# +proc test_compound_select_flippable {testname sql result} { + test_compound_select $testname $sql $result + + set select [string trim $sql] + set RE {(.*)(UNION ALL|INTERSECT|UNION)(.*)(ORDER BY.*)} + set rc [regexp $RE $select -> s1 op s2 order_by] + if {!$rc} {error "Statement is unflippable: $select"} + + set flipsql "$s2 $op $s1 $order_by" + test_compound_select $testname.flipped $flipsql $result +} + +############################################################################# +# Begin tests. +# + +# Create and populate a sample database. +# +do_test select9-1.0 { + execsql { + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(d, e, f); + BEGIN; + INSERT INTO t1 VALUES(1, 'one', 'I'); + INSERT INTO t1 VALUES(3, NULL, NULL); + INSERT INTO t1 VALUES(5, 'five', 'V'); + INSERT INTO t1 VALUES(7, 'seven', 'VII'); + INSERT INTO t1 VALUES(9, NULL, NULL); + INSERT INTO t1 VALUES(2, 'two', 'II'); + INSERT INTO t1 VALUES(4, 'four', 'IV'); + INSERT INTO t1 VALUES(6, NULL, NULL); + INSERT INTO t1 VALUES(8, 'eight', 'VIII'); + INSERT INTO t1 VALUES(10, 'ten', 'X'); + + INSERT INTO t2 VALUES(1, 'two', 'IV'); + INSERT INTO t2 VALUES(2, 'four', 'VIII'); + INSERT INTO t2 VALUES(3, NULL, NULL); + INSERT INTO t2 VALUES(4, 'eight', 'XVI'); + INSERT INTO t2 VALUES(5, 'ten', 'XX'); + INSERT INTO t2 VALUES(6, NULL, NULL); + INSERT INTO t2 VALUES(7, 'fourteen', 'XXVIII'); + INSERT INTO t2 VALUES(8, 'sixteen', 'XXXII'); + INSERT INTO t2 VALUES(9, NULL, NULL); + INSERT INTO t2 VALUES(10, 'twenty', 'XL'); + + COMMIT; + } +} {} + +# Each iteration of this loop runs the same tests with a different set +# of indexes present within the database schema. The data returned by +# the compound SELECT statements in the test cases should be the same +# in each case. +# +set iOuterLoop 1 +foreach indexes [list { + /* Do not create any indexes. */ +} { + CREATE INDEX i1 ON t1(a) +} { + CREATE INDEX i2 ON t1(b) +} { + CREATE INDEX i3 ON t2(d) +} { + CREATE INDEX i4 ON t2(e) +}] { + + do_test select9-1.$iOuterLoop.1 { + execsql $indexes + } {} + + # Test some 2-way UNION ALL queries. No WHERE clauses. + # + test_compound_select select9-1.$iOuterLoop.2 { + SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 + } {1 one 3 {} 5 five 7 seven 9 {} 2 two 4 four 6 {} 8 eight 10 ten 1 two 2 four 3 {} 4 eight 5 ten 6 {} 7 fourteen 8 sixteen 9 {} 10 twenty} + test_compound_select select9-1.$iOuterLoop.3 { + SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY 1 + } {1 one 1 two 2 two 2 four 3 {} 3 {} 4 four 4 eight 5 five 5 ten 6 {} 6 {} 7 seven 7 fourteen 8 eight 8 sixteen 9 {} 9 {} 10 ten 10 twenty} + test_compound_select select9-1.$iOuterLoop.4 { + SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY 2 + } {3 {} 9 {} 6 {} 3 {} 6 {} 9 {} 8 eight 4 eight 5 five 4 four 2 four 7 fourteen 1 one 7 seven 8 sixteen 10 ten 5 ten 10 twenty 2 two 1 two} + test_compound_select_flippable select9-1.$iOuterLoop.5 { + SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY 1, 2 + } {1 one 1 two 2 four 2 two 3 {} 3 {} 4 eight 4 four 5 five 5 ten 6 {} 6 {} 7 fourteen 7 seven 8 eight 8 sixteen 9 {} 9 {} 10 ten 10 twenty} + test_compound_select_flippable select9-1.$iOuterLoop.6 { + SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY 2, 1 + } {3 {} 3 {} 6 {} 6 {} 9 {} 9 {} 4 eight 8 eight 5 five 2 four 4 four 7 fourteen 1 one 7 seven 8 sixteen 5 ten 10 ten 10 twenty 1 two 2 two} + + # Test some 2-way UNION queries. + # + test_compound_select select9-1.$iOuterLoop.7 { + SELECT a, b FROM t1 UNION SELECT d, e FROM t2 + } {1 one 1 two 2 four 2 two 3 {} 4 eight 4 four 5 five 5 ten 6 {} 7 fourteen 7 seven 8 eight 8 sixteen 9 {} 10 ten 10 twenty} + + test_compound_select select9-1.$iOuterLoop.8 { + SELECT a, b FROM t1 UNION SELECT d, e FROM t2 ORDER BY 1 + } {1 one 1 two 2 four 2 two 3 {} 4 eight 4 four 5 five 5 ten 6 {} 7 fourteen 7 seven 8 eight 8 sixteen 9 {} 10 ten 10 twenty} + + test_compound_select select9-1.$iOuterLoop.9 { + SELECT a, b FROM t1 UNION SELECT d, e FROM t2 ORDER BY 2 + } {3 {} 6 {} 9 {} 4 eight 8 eight 5 five 2 four 4 four 7 fourteen 1 one 7 seven 8 sixteen 5 ten 10 ten 10 twenty 1 two 2 two} + + test_compound_select_flippable select9-1.$iOuterLoop.10 { + SELECT a, b FROM t1 UNION SELECT d, e FROM t2 ORDER BY 1, 2 + } {1 one 1 two 2 four 2 two 3 {} 4 eight 4 four 5 five 5 ten 6 {} 7 fourteen 7 seven 8 eight 8 sixteen 9 {} 10 ten 10 twenty} + + test_compound_select_flippable select9-1.$iOuterLoop.11 { + SELECT a, b FROM t1 UNION SELECT d, e FROM t2 ORDER BY 2, 1 + } {3 {} 6 {} 9 {} 4 eight 8 eight 5 five 2 four 4 four 7 fourteen 1 one 7 seven 8 sixteen 5 ten 10 ten 10 twenty 1 two 2 two} + + # Test some 2-way INTERSECT queries. + # + test_compound_select select9-1.$iOuterLoop.11 { + SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 + } {3 {} 6 {} 9 {}} + test_compound_select_flippable select9-1.$iOuterLoop.12 { + SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 ORDER BY 1 + } {3 {} 6 {} 9 {}} + test_compound_select select9-1.$iOuterLoop.13 { + SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 ORDER BY 2 + } {3 {} 6 {} 9 {}} + test_compound_select_flippable select9-1.$iOuterLoop.14 { + SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 ORDER BY 2, 1 + } {3 {} 6 {} 9 {}} + test_compound_select_flippable select9-1.$iOuterLoop.15 { + SELECT a, b FROM t1 INTERSECT SELECT d, e FROM t2 ORDER BY 1, 2 + } {3 {} 6 {} 9 {}} + + # Test some 2-way EXCEPT queries. + # + test_compound_select select9-1.$iOuterLoop.16 { + SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 + } {1 one 2 two 4 four 5 five 7 seven 8 eight 10 ten} + + test_compound_select select9-1.$iOuterLoop.17 { + SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 ORDER BY 1 + } {1 one 2 two 4 four 5 five 7 seven 8 eight 10 ten} + + test_compound_select select9-1.$iOuterLoop.18 { + SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 ORDER BY 2 + } {8 eight 5 five 4 four 1 one 7 seven 10 ten 2 two} + + test_compound_select select9-1.$iOuterLoop.19 { + SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 ORDER BY 1, 2 + } {1 one 2 two 4 four 5 five 7 seven 8 eight 10 ten} + + test_compound_select select9-1.$iOuterLoop.20 { + SELECT a, b FROM t1 EXCEPT SELECT d, e FROM t2 ORDER BY 2, 1 + } {8 eight 5 five 4 four 1 one 7 seven 10 ten 2 two} + + incr iOuterLoop +} + +do_test select9-2.0 { + execsql { + DROP INDEX i1; + DROP INDEX i2; + DROP INDEX i3; + DROP INDEX i4; + } +} {} + +proc reverse {lhs rhs} { + return [string compare $rhs $lhs] +} +db collate reverse reverse + +# This loop is similar to the previous one (test cases select9-1.*) +# except that the simple select statements have WHERE clauses attached +# to them. Sometimes the WHERE clause may be satisfied using the same +# index used for ORDER BY, sometimes not. +# +set iOuterLoop 1 +foreach indexes [list { + /* Do not create any indexes. */ +} { + CREATE INDEX i1 ON t1(a) +} { + DROP INDEX i1; + CREATE INDEX i1 ON t1(b, a) +} { + CREATE INDEX i2 ON t2(d DESC, e COLLATE REVERSE ASC); +} { + CREATE INDEX i3 ON t1(a DESC); +}] { + do_test select9-2.$iOuterLoop.1 { + execsql $indexes + } {} + + test_compound_select_flippable select9-2.$iOuterLoop.2 { + SELECT * FROM t1 WHERE a<5 UNION SELECT * FROM t2 WHERE d>=5 ORDER BY 1 + } {1 one I 2 two II 3 {} {} 4 four IV 5 ten XX 6 {} {} 7 fourteen XXVIII 8 sixteen XXXII 9 {} {} 10 twenty XL} + + test_compound_select_flippable select9-2.$iOuterLoop.2 { + SELECT * FROM t1 WHERE a<5 UNION SELECT * FROM t2 WHERE d>=5 ORDER BY 2, 1 + } {3 {} {} 6 {} {} 9 {} {} 4 four IV 7 fourteen XXVIII 1 one I 8 sixteen XXXII 5 ten XX 10 twenty XL 2 two II} + + test_compound_select_flippable select9-2.$iOuterLoop.3 { + SELECT * FROM t1 WHERE a<5 UNION SELECT * FROM t2 WHERE d>=5 + ORDER BY 2 COLLATE reverse, 1 + } {3 {} {} 6 {} {} 9 {} {} 2 two II 10 twenty XL 5 ten XX 8 sixteen XXXII 1 one I 7 fourteen XXVIII 4 four IV} + + test_compound_select_flippable select9-2.$iOuterLoop.4 { + SELECT * FROM t1 WHERE a<5 UNION ALL SELECT * FROM t2 WHERE d>=5 ORDER BY 1 + } {1 one I 2 two II 3 {} {} 4 four IV 5 ten XX 6 {} {} 7 fourteen XXVIII 8 sixteen XXXII 9 {} {} 10 twenty XL} + + test_compound_select_flippable select9-2.$iOuterLoop.5 { + SELECT * FROM t1 WHERE a<5 UNION ALL SELECT * FROM t2 WHERE d>=5 ORDER BY 2, 1 + } {3 {} {} 6 {} {} 9 {} {} 4 four IV 7 fourteen XXVIII 1 one I 8 sixteen XXXII 5 ten XX 10 twenty XL 2 two II} + + test_compound_select_flippable select9-2.$iOuterLoop.6 { + SELECT * FROM t1 WHERE a<5 UNION ALL SELECT * FROM t2 WHERE d>=5 + ORDER BY 2 COLLATE reverse, 1 + } {3 {} {} 6 {} {} 9 {} {} 2 two II 10 twenty XL 5 ten XX 8 sixteen XXXII 1 one I 7 fourteen XXVIII 4 four IV} + + test_compound_select select9-2.$iOuterLoop.4 { + SELECT a FROM t1 WHERE a<8 EXCEPT SELECT d FROM t2 WHERE d<=3 ORDER BY 1 + } {4 5 6 7} + + test_compound_select select9-2.$iOuterLoop.4 { + SELECT a FROM t1 WHERE a<8 INTERSECT SELECT d FROM t2 WHERE d<=3 ORDER BY 1 + } {1 2 3} + +} + +do_test select9-2.X { + execsql { + DROP INDEX i1; + DROP INDEX i2; + DROP INDEX i3; + } +} {} + +# This procedure executes the SQL. Then it checks the generated program +# for the SQL and appends a "nosort" to the result if the program contains the +# SortCallback opcode. If the program does not contain the SortCallback +# opcode it appends "sort" +# +proc cksort {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + if {$::sqlite_sort_count} {set x sort} {set x nosort} + lappend data $x + return $data +} + +# If the right indexes exist, the following query: +# +# SELECT t1.a FROM t1 UNION ALL SELECT t2.d FROM t2 ORDER BY 1 +# +# can use indexes to run without doing a in-memory sort operation. +# This block of tests (select9-3.*) is used to check if the same +# is possible with: +# +# CREATE VIEW v1 AS SELECT a FROM t1 UNION ALL SELECT d FROM t2 +# SELECT a FROM v1 ORDER BY 1 +# +# It turns out that it is. +# +do_test select9-3.1 { + cksort { SELECT a FROM t1 ORDER BY 1 } +} {1 2 3 4 5 6 7 8 9 10 sort} +do_test select9-3.2 { + execsql { CREATE INDEX i1 ON t1(a) } + cksort { SELECT a FROM t1 ORDER BY 1 } +} {1 2 3 4 5 6 7 8 9 10 nosort} +do_test select9-3.3 { + cksort { SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 5 } +} {1 1 2 2 3 sort} +do_test select9-3.4 { + execsql { CREATE INDEX i2 ON t2(d) } + cksort { SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 5 } +} {1 1 2 2 3 nosort} +do_test select9-3.5 { + execsql { CREATE VIEW v1 AS SELECT a FROM t1 UNION ALL SELECT d FROM t2 } + cksort { SELECT a FROM v1 ORDER BY 1 LIMIT 5 } +} {1 1 2 2 3 nosort} +do_test select9-3.X { + execsql { + DROP INDEX i1; + DROP INDEX i2; + DROP VIEW v1; + } +} {} + +# This block of tests is the same as the preceding one, except that +# "UNION" is tested instead of "UNION ALL". +# +do_test select9-4.1 { + cksort { SELECT a FROM t1 ORDER BY 1 } +} {1 2 3 4 5 6 7 8 9 10 sort} +do_test select9-4.2 { + execsql { CREATE INDEX i1 ON t1(a) } + cksort { SELECT a FROM t1 ORDER BY 1 } +} {1 2 3 4 5 6 7 8 9 10 nosort} +do_test select9-4.3 { + cksort { SELECT a FROM t1 UNION SELECT d FROM t2 ORDER BY 1 LIMIT 5 } +} {1 2 3 4 5 sort} +do_test select9-4.4 { + execsql { CREATE INDEX i2 ON t2(d) } + cksort { SELECT a FROM t1 UNION SELECT d FROM t2 ORDER BY 1 LIMIT 5 } +} {1 2 3 4 5 nosort} +do_test select9-4.5 { + execsql { CREATE VIEW v1 AS SELECT a FROM t1 UNION SELECT d FROM t2 } + cksort { SELECT a FROM v1 ORDER BY 1 LIMIT 5 } +} {1 2 3 4 5 sort} +do_test select9-4.X { + execsql { + DROP INDEX i1; + DROP INDEX i2; + DROP VIEW v1; + } +} {} + +# Testing to make sure that queries involving a view of a compound select +# are planned efficiently. This detects a problem reported on the mailing +# list on 2012-04-26. See +# +# http://www.mail-archive.com/sqlite-users%40sqlite.org/msg69746.html +# +# For additional information. +# +do_test select9-5.1 { + db eval { + CREATE TABLE t51(x, y); + CREATE TABLE t52(x, y); + CREATE VIEW v5 as + SELECT x, y FROM t51 + UNION ALL + SELECT x, y FROM t52; + CREATE INDEX t51x ON t51(x); + CREATE INDEX t52x ON t52(x); + EXPLAIN QUERY PLAN + SELECT * FROM v5 WHERE x='12345' ORDER BY y; + } +} {~/SCAN TABLE/} ;# Uses indices with "*" +do_test select9-5.2 { + db eval { + EXPLAIN QUERY PLAN + SELECT x, y FROM v5 WHERE x='12345' ORDER BY y; + } +} {~/SCAN TABLE/} ;# Uses indices with "x, y" +do_test select9-5.3 { + db eval { + EXPLAIN QUERY PLAN + SELECT x, y FROM v5 WHERE +x='12345' ORDER BY y; + } +} {/SCAN TABLE/} ;# Full table scan if the "+x" prevents index usage. + +# 2013-07-09: Ticket [490a4b7235624298]: +# "WHERE 0" on the first element of a UNION causes an assertion fault +# +do_execsql_test select9-6.1 { + CREATE TABLE t61(a); + CREATE TABLE t62(b); + INSERT INTO t61 VALUES(111); + INSERT INTO t62 VALUES(222); + SELECT a FROM t61 WHERE 0 UNION SELECT b FROM t62; +} {222} +do_execsql_test select9-6.2 { + SELECT a FROM t61 WHERE 0 UNION ALL SELECT b FROM t62; +} {222} +do_execsql_test select9-6.3 { + SELECT a FROM t61 UNION SELECT b FROM t62 WHERE 0; +} {111} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/selectA.test b/components/external/SQLite-3.8.1/test/selectA.test new file mode 100644 index 0000000000000000000000000000000000000000..5fd2288dbf30220f373c3156e315b6f02f33a65d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/selectA.test @@ -0,0 +1,1296 @@ +# 2008 June 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# The focus of this file is testing the compound-SELECT merge +# optimization. Or, in other words, making sure that all +# possible combinations of UNION, UNION ALL, EXCEPT, and +# INTERSECT work together with an ORDER BY clause (with or w/o +# explicit sort order and explicit collating secquites) and +# with and without optional LIMIT and OFFSET clauses. +# +# $Id: selectA.test,v 1.6 2008/08/21 14:24:29 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_test selectA-1.0 { + execsql { + CREATE TABLE t1(a,b,c COLLATE NOCASE); + INSERT INTO t1 VALUES(1,'a','a'); + INSERT INTO t1 VALUES(9.9, 'b', 'B'); + INSERT INTO t1 VALUES(NULL, 'C', 'c'); + INSERT INTO t1 VALUES('hello', 'd', 'D'); + INSERT INTO t1 VALUES(x'616263', 'e', 'e'); + SELECT * FROM t1; + } +} {1 a a 9.9 b B {} C c hello d D abc e e} +do_test selectA-1.1 { + execsql { + CREATE TABLE t2(x,y,z COLLATE NOCASE); + INSERT INTO t2 VALUES(NULL,'U','u'); + INSERT INTO t2 VALUES('mad', 'Z', 'z'); + INSERT INTO t2 VALUES(x'68617265', 'm', 'M'); + INSERT INTO t2 VALUES(5.2e6, 'X', 'x'); + INSERT INTO t2 VALUES(-23, 'Y', 'y'); + SELECT * FROM t2; + } +} {{} U u mad Z z hare m M 5200000.0 X x -23 Y y} +do_test selectA-1.2 { + execsql { + CREATE TABLE t3(a,b,c COLLATE NOCASE); + INSERT INTO t3 SELECT * FROM t1; + INSERT INTO t3 SELECT * FROM t2; + INSERT INTO t3 SELECT * FROM t1; + INSERT INTO t3 SELECT * FROM t2; + INSERT INTO t3 SELECT * FROM t1; + INSERT INTO t3 SELECT * FROM t2; + SELECT count(*) FROM t3; + } +} {30} + +do_test selectA-2.1 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.1.1 { # Ticket #3314 + execsql { + SELECT t1.a, t1.b, t1.c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.1.2 { # Ticket #3314 + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY t1.a, t1.b, t1.c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.2 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-2.3 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.4 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-2.5 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE,a,c + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.6 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE DESC,a,c + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.7 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.8 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.9 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.10 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY c COLLATE BINARY DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-2.11 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.12 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-2.13 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.14 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-2.15 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY b COLLATE NOCASE,a,c + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.16 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY b COLLATE NOCASE DESC,a,c + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.17 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.18 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.19 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.20 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY c COLLATE BINARY DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-2.21 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.22 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-2.23 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.24 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-2.25 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE,a,c + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.26 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE DESC,a,c + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.27 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.28 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.29 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.30 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY c COLLATE BINARY DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-2.31 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.32 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-2.33 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.34 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-2.35 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY y COLLATE NOCASE,x,z + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.36 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY y COLLATE NOCASE DESC,x,z + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.37 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.38 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.39 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.40 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY z COLLATE BINARY DESC,x,y + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-2.41 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY a,b,c + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-2.42 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY a,b,c + } +} {hello d D abc e e} +do_test selectA-2.43 { + execsql { + SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY a,b,c + } +} {hello d D abc e e} +do_test selectA-2.44 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY a,b,c + } +} {hello d D abc e e} +do_test selectA-2.45 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY a,b,c + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-2.46 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY a,b,c + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-2.47 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY a DESC + } +} {9.9 b B 1 a a {} C c} +do_test selectA-2.48 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY a DESC + } +} {abc e e hello d D} +do_test selectA-2.49 { + execsql { + SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY a DESC + } +} {abc e e hello d D} +do_test selectA-2.50 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY a DESC + } +} {abc e e hello d D} +do_test selectA-2.51 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY a DESC + } +} {9.9 b B 1 a a {} C c} +do_test selectA-2.52 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY a DESC + } +} {9.9 b B 1 a a {} C c} +do_test selectA-2.53 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY b, a DESC + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-2.54 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY b + } +} {hello d D abc e e} +do_test selectA-2.55 { + execsql { + SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY b DESC, c + } +} {abc e e hello d D} +do_test selectA-2.56 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY b, c DESC, a + } +} {hello d D abc e e} +do_test selectA-2.57 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY b COLLATE NOCASE + } +} {1 a a 9.9 b B {} C c} +do_test selectA-2.58 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY b + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-2.59 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY c, a DESC + } +} {1 a a 9.9 b B {} C c} +do_test selectA-2.60 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY c + } +} {hello d D abc e e} +do_test selectA-2.61 { + execsql { + SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY c COLLATE BINARY, b DESC, c, a, b, c, a, b, c + } +} {hello d D abc e e} +do_test selectA-2.62 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY c DESC, a + } +} {abc e e hello d D} +do_test selectA-2.63 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY c COLLATE NOCASE + } +} {1 a a 9.9 b B {} C c} +do_test selectA-2.64 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY c + } +} {1 a a 9.9 b B {} C c} +do_test selectA-2.65 { + execsql { + SELECT a,b,c FROM t3 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY c COLLATE NOCASE + } +} {1 a a 9.9 b B {} C c} +do_test selectA-2.66 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t3 + ORDER BY c + } +} {1 a a 9.9 b B {} C c} +do_test selectA-2.67 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t3 WHERE b<'d' + ORDER BY c DESC, a + } +} {abc e e hello d D} +do_test selectA-2.68 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT b,c,a FROM t3 + ORDER BY c DESC, a + } +} {abc e e hello d D} +do_test selectA-2.69 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT b,c,a FROM t3 + ORDER BY c COLLATE NOCASE + } +} {1 a a 9.9 b B {} C c} +do_test selectA-2.70 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT b,c,a FROM t3 + ORDER BY c + } +} {1 a a 9.9 b B {} C c} +do_test selectA-2.71 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' + INTERSECT SELECT a,b,c FROM t1 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT b,c,a FROM t3 + INTERSECT SELECT a,b,c FROM t1 + EXCEPT SELECT x,y,z FROM t2 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT y,x,z FROM t2 + INTERSECT SELECT a,b,c FROM t1 + EXCEPT SELECT c,b,a FROM t3 + ORDER BY c + } +} {1 a a 9.9 b B {} C c} +do_test selectA-2.72 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.73 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-2.74 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.75 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-2.76 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE,a,c + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.77 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE DESC,a,c + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.78 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.79 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.80 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.81 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY c COLLATE BINARY DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-2.82 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.83 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-2.84 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-2.85 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-2.86 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY y COLLATE NOCASE,x,z + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.87 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY y COLLATE NOCASE DESC,x,z + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.88 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.89 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-2.90 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.91 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY z COLLATE BINARY DESC,x,y + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-2.92 { + execsql { + SELECT x,y,z FROM t2 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT c,b,a FROM t1 + UNION SELECT a,b,c FROM t3 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT c,b,a FROM t1 + UNION SELECT a,b,c FROM t3 + ORDER BY y COLLATE NOCASE DESC,x,z + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-2.93 { + execsql { + SELECT upper((SELECT c FROM t1 UNION SELECT z FROM t2 ORDER BY 1)); + } +} {A} +do_test selectA-2.94 { + execsql { + SELECT lower((SELECT c FROM t1 UNION ALL SELECT z FROM t2 ORDER BY 1)); + } +} {a} +do_test selectA-2.95 { + execsql { + SELECT lower((SELECT c FROM t1 INTERSECT SELECT z FROM t2 ORDER BY 1)); + } +} {{}} +do_test selectA-2.96 { + execsql { + SELECT lower((SELECT z FROM t2 EXCEPT SELECT c FROM t1 ORDER BY 1)); + } +} {m} + + +do_test selectA-3.0 { + execsql { + CREATE UNIQUE INDEX t1a ON t1(a); + CREATE UNIQUE INDEX t1b ON t1(b); + CREATE UNIQUE INDEX t1c ON t1(c); + CREATE UNIQUE INDEX t2x ON t2(x); + CREATE UNIQUE INDEX t2y ON t2(y); + CREATE UNIQUE INDEX t2z ON t2(z); + SELECT name FROM sqlite_master WHERE type='index' + } +} {t1a t1b t1c t2x t2y t2z} +do_test selectA-3.1 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.1.1 { # Ticket #3314 + execsql { + SELECT t1.a,b,t1.c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY a,t1.b,t1.c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.2 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-3.3 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.4 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-3.5 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE,a,c + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.6 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE DESC,a,c + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.7 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.8 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.9 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.10 { + execsql { + SELECT a,b,c FROM t1 UNION ALL SELECT x,y,z FROM t2 + ORDER BY c COLLATE BINARY DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-3.11 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.12 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-3.13 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.14 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-3.15 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY b COLLATE NOCASE,a,c + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.16 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY b COLLATE NOCASE DESC,a,c + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.17 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.18 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.19 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.20 { + execsql { + SELECT x,y,z FROM t2 UNION ALL SELECT a,b,c FROM t1 + ORDER BY c COLLATE BINARY DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-3.21 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.22 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-3.23 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.24 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-3.25 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE,a,c + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.26 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE DESC,a,c + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.27 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.28 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.29 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.30 { + execsql { + SELECT a,b,c FROM t1 UNION SELECT x,y,z FROM t2 + ORDER BY c COLLATE BINARY DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-3.31 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.32 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-3.33 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.34 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-3.35 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY y COLLATE NOCASE,x,z + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.36 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY y COLLATE NOCASE DESC,x,z + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.37 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.38 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.39 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.40 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t1 + ORDER BY z COLLATE BINARY DESC,x,y + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-3.41 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY a,b,c + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-3.42 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY a,b,c + } +} {hello d D abc e e} +do_test selectA-3.43 { + execsql { + SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY a,b,c + } +} {hello d D abc e e} +do_test selectA-3.44 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY a,b,c + } +} {hello d D abc e e} +do_test selectA-3.45 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY a,b,c + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-3.46 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY a,b,c + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-3.47 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY a DESC + } +} {9.9 b B 1 a a {} C c} +do_test selectA-3.48 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY a DESC + } +} {abc e e hello d D} +do_test selectA-3.49 { + execsql { + SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY a DESC + } +} {abc e e hello d D} +do_test selectA-3.50 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY a DESC + } +} {abc e e hello d D} +do_test selectA-3.51 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY a DESC + } +} {9.9 b B 1 a a {} C c} +do_test selectA-3.52 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY a DESC + } +} {9.9 b B 1 a a {} C c} +do_test selectA-3.53 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY b, a DESC + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-3.54 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY b + } +} {hello d D abc e e} +do_test selectA-3.55 { + execsql { + SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY b DESC, c + } +} {abc e e hello d D} +do_test selectA-3.56 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY b, c DESC, a + } +} {hello d D abc e e} +do_test selectA-3.57 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY b COLLATE NOCASE + } +} {1 a a 9.9 b B {} C c} +do_test selectA-3.58 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY b + } +} {{} C c 1 a a 9.9 b B} +do_test selectA-3.59 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY c, a DESC + } +} {1 a a 9.9 b B {} C c} +do_test selectA-3.60 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b>='d' + ORDER BY c + } +} {hello d D abc e e} +do_test selectA-3.61 { + execsql { + SELECT a,b,c FROM t1 WHERE b>='d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY c COLLATE BINARY, b DESC, c, a, b, c, a, b, c + } +} {hello d D abc e e} +do_test selectA-3.62 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY c DESC, a + } +} {abc e e hello d D} +do_test selectA-3.63 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY c COLLATE NOCASE + } +} {1 a a 9.9 b B {} C c} +do_test selectA-3.64 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + ORDER BY c + } +} {1 a a 9.9 b B {} C c} +do_test selectA-3.65 { + execsql { + SELECT a,b,c FROM t3 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + ORDER BY c COLLATE NOCASE + } +} {1 a a 9.9 b B {} C c} +do_test selectA-3.66 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t3 + ORDER BY c + } +} {1 a a 9.9 b B {} C c} +do_test selectA-3.67 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t3 WHERE b<'d' + ORDER BY c DESC, a + } +} {abc e e hello d D} +do_test selectA-3.68 { + execsql { + SELECT a,b,c FROM t1 EXCEPT SELECT a,b,c FROM t1 WHERE b<'d' + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT b,c,a FROM t3 + ORDER BY c DESC, a + } +} {abc e e hello d D} +do_test selectA-3.69 { + execsql { + SELECT a,b,c FROM t1 INTERSECT SELECT a,b,c FROM t1 WHERE b<'d' + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT b,c,a FROM t3 + ORDER BY c COLLATE NOCASE + } +} {1 a a 9.9 b B {} C c} +do_test selectA-3.70 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' INTERSECT SELECT a,b,c FROM t1 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT b,c,a FROM t3 + ORDER BY c + } +} {1 a a 9.9 b B {} C c} +do_test selectA-3.71 { + execsql { + SELECT a,b,c FROM t1 WHERE b<'d' + INTERSECT SELECT a,b,c FROM t1 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT b,c,a FROM t3 + INTERSECT SELECT a,b,c FROM t1 + EXCEPT SELECT x,y,z FROM t2 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT y,x,z FROM t2 + INTERSECT SELECT a,b,c FROM t1 + EXCEPT SELECT c,b,a FROM t3 + ORDER BY c + } +} {1 a a 9.9 b B {} C c} +do_test selectA-3.72 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.73 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-3.74 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.75 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-3.76 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE,a,c + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.77 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY b COLLATE NOCASE DESC,a,c + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.78 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.79 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.80 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.81 { + execsql { + SELECT a,b,c FROM t3 UNION SELECT x,y,z FROM t2 + ORDER BY c COLLATE BINARY DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-3.82 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY a,b,c + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.83 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY a DESC,b,c + } +} {hare m M abc e e mad Z z hello d D 5200000.0 X x 9.9 b B 1 a a -23 Y y {} C c {} U u} +do_test selectA-3.84 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY a,c,b + } +} {{} C c {} U u -23 Y y 1 a a 9.9 b B 5200000.0 X x hello d D mad Z z abc e e hare m M} +do_test selectA-3.85 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY b,a,c + } +} {{} C c {} U u 5200000.0 X x -23 Y y mad Z z 1 a a 9.9 b B hello d D abc e e hare m M} +do_test selectA-3.86 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY y COLLATE NOCASE,x,z + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.87 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY y COLLATE NOCASE DESC,x,z + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.88 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY c,b,a + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.89 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY c,a,b + } +} {1 a a 9.9 b B {} C c hello d D abc e e hare m M {} U u 5200000.0 X x -23 Y y mad Z z} +do_test selectA-3.90 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY c DESC,a,b + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.91 { + execsql { + SELECT x,y,z FROM t2 UNION SELECT a,b,c FROM t3 + ORDER BY z COLLATE BINARY DESC,x,y + } +} {mad Z z -23 Y y 5200000.0 X x {} U u abc e e {} C c 1 a a hare m M hello d D 9.9 b B} +do_test selectA-3.92 { + execsql { + SELECT x,y,z FROM t2 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT c,b,a FROM t1 + UNION SELECT a,b,c FROM t3 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT c,b,a FROM t1 + UNION SELECT a,b,c FROM t3 + ORDER BY y COLLATE NOCASE DESC,x,z + } +} {mad Z z -23 Y y 5200000.0 X x {} U u hare m M abc e e hello d D {} C c 9.9 b B 1 a a} +do_test selectA-3.93 { + execsql { + SELECT upper((SELECT c FROM t1 UNION SELECT z FROM t2 ORDER BY 1)); + } +} {A} +do_test selectA-3.94 { + execsql { + SELECT lower((SELECT c FROM t1 UNION ALL SELECT z FROM t2 ORDER BY 1)); + } +} {a} +do_test selectA-3.95 { + execsql { + SELECT lower((SELECT c FROM t1 INTERSECT SELECT z FROM t2 ORDER BY 1)); + } +} {{}} +do_test selectA-3.96 { + execsql { + SELECT lower((SELECT z FROM t2 EXCEPT SELECT c FROM t1 ORDER BY 1)); + } +} {m} +do_test selectA-3.97 { + execsql { + SELECT upper((SELECT x FROM ( + SELECT x,y,z FROM t2 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT c,b,a FROM t1 + UNION SELECT a,b,c FROM t3 + INTERSECT SELECT a,b,c FROM t3 + EXCEPT SELECT c,b,a FROM t1 + UNION SELECT a,b,c FROM t3 + ORDER BY y COLLATE NOCASE DESC,x,z))) + } +} {MAD} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/selectB.test b/components/external/SQLite-3.8.1/test/selectB.test new file mode 100644 index 0000000000000000000000000000000000000000..05ec9c6bdb0f5fc96b13444b612354f80086a3eb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/selectB.test @@ -0,0 +1,426 @@ +# 2008 June 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# $Id: selectB.test,v 1.10 2009/04/02 16:59:47 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +proc test_transform {testname sql1 sql2 results} { + set ::vdbe1 [list] + set ::vdbe2 [list] + db eval "explain $sql1" { lappend ::vdbe1 $opcode } + db eval "explain $sql2" { lappend ::vdbe2 $opcode } + + do_test $testname.transform { + set ::vdbe1 + } $::vdbe2 + + set ::sql1 $sql1 + do_test $testname.sql1 { + execsql $::sql1 + } $results + + set ::sql2 $sql2 + do_test $testname.sql2 { + execsql $::sql2 + } $results +} + +do_test selectB-1.1 { + execsql { + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(d, e, f); + + INSERT INTO t1 VALUES( 2, 4, 6); + INSERT INTO t1 VALUES( 8, 10, 12); + INSERT INTO t1 VALUES(14, 16, 18); + + INSERT INTO t2 VALUES(3, 6, 9); + INSERT INTO t2 VALUES(12, 15, 18); + INSERT INTO t2 VALUES(21, 24, 27); + } +} {} + +for {set ii 1} {$ii <= 2} {incr ii} { + + if {$ii == 2} { + do_test selectB-2.1 { + execsql { + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t2(d); + } + } {} + } + + test_transform selectB-$ii.2 { + SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) + } { + SELECT a FROM t1 UNION ALL SELECT d FROM t2 + } {2 8 14 3 12 21} + + test_transform selectB-$ii.3 { + SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) ORDER BY 1 + } { + SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 + } {2 3 8 12 14 21} + + test_transform selectB-$ii.4 { + SELECT * FROM + (SELECT a FROM t1 UNION ALL SELECT d FROM t2) + WHERE a>10 ORDER BY 1 + } { + SELECT a FROM t1 WHERE a>10 UNION ALL SELECT d FROM t2 WHERE d>10 ORDER BY 1 + } {12 14 21} + + test_transform selectB-$ii.5 { + SELECT * FROM + (SELECT a FROM t1 UNION ALL SELECT d FROM t2) + WHERE a>10 ORDER BY a + } { + SELECT a FROM t1 WHERE a>10 + UNION ALL + SELECT d FROM t2 WHERE d>10 + ORDER BY a + } {12 14 21} + + test_transform selectB-$ii.6 { + SELECT * FROM + (SELECT a FROM t1 UNION ALL SELECT d FROM t2 WHERE d > 12) + WHERE a>10 ORDER BY a + } { + SELECT a FROM t1 WHERE a>10 + UNION ALL + SELECT d FROM t2 WHERE d>12 AND d>10 + ORDER BY a + } {14 21} + + test_transform selectB-$ii.7 { + SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) ORDER BY 1 + LIMIT 2 + } { + SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 2 + } {2 3} + + test_transform selectB-$ii.8 { + SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) ORDER BY 1 + LIMIT 2 OFFSET 3 + } { + SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 LIMIT 2 OFFSET 3 + } {12 14} + + test_transform selectB-$ii.9 { + SELECT * FROM ( + SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1 + ) + } { + SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1 + } {2 8 14 3 12 21 6 12 18} + + test_transform selectB-$ii.10 { + SELECT * FROM ( + SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1 + ) ORDER BY 1 + } { + SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1 + ORDER BY 1 + } {2 3 6 8 12 12 14 18 21} + + test_transform selectB-$ii.11 { + SELECT * FROM ( + SELECT a FROM t1 UNION ALL SELECT d FROM t2 UNION ALL SELECT c FROM t1 + ) WHERE a>=10 ORDER BY 1 LIMIT 3 + } { + SELECT a FROM t1 WHERE a>=10 UNION ALL SELECT d FROM t2 WHERE d>=10 + UNION ALL SELECT c FROM t1 WHERE c>=10 + ORDER BY 1 LIMIT 3 + } {12 12 14} + + test_transform selectB-$ii.12 { + SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 2) + } { + SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 2 + } {2 8} + + # An ORDER BY in a compound subqueries defeats flattening. Ticket #3773 + # test_transform selectB-$ii.13 { + # SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY a ASC) + # } { + # SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 ASC + # } {2 3 8 12 14 21} + # + # test_transform selectB-$ii.14 { + # SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY a DESC) + # } { + # SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 DESC + # } {21 14 12 8 3 2} + # + # test_transform selectB-$ii.14 { + # SELECT * FROM ( + # SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY a DESC + # ) LIMIT 2 OFFSET 2 + # } { + # SELECT a FROM t1 UNION ALL SELECT d FROM t2 ORDER BY 1 DESC + # LIMIT 2 OFFSET 2 + # } {12 8} + # + # test_transform selectB-$ii.15 { + # SELECT * FROM ( + # SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY a ASC, e DESC + # ) + # } { + # SELECT a, b FROM t1 UNION ALL SELECT d, e FROM t2 ORDER BY a ASC, e DESC + # } {2 4 3 6 8 10 12 15 14 16 21 24} +} + +do_test selectB-3.0 { + execsql { + DROP INDEX i1; + DROP INDEX i2; + } +} {} + +for {set ii 3} {$ii <= 6} {incr ii} { + + switch $ii { + 4 { + optimization_control db query-flattener off + } + 5 { + optimization_control db query-flattener on + do_test selectB-5.0 { + execsql { + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); + CREATE INDEX i3 ON t1(c); + CREATE INDEX i4 ON t2(d); + CREATE INDEX i5 ON t2(e); + CREATE INDEX i6 ON t2(f); + } + } {} + } + 6 { + optimization_control db query-flattener off + } + } + + do_test selectB-$ii.1 { + execsql { + SELECT DISTINCT * FROM + (SELECT c FROM t1 UNION ALL SELECT e FROM t2) + ORDER BY 1; + } + } {6 12 15 18 24} + + do_test selectB-$ii.2 { + execsql { + SELECT c, count(*) FROM + (SELECT c FROM t1 UNION ALL SELECT e FROM t2) + GROUP BY c ORDER BY 1; + } + } {6 2 12 1 15 1 18 1 24 1} + do_test selectB-$ii.3 { + execsql { + SELECT c, count(*) FROM + (SELECT c FROM t1 UNION ALL SELECT e FROM t2) + GROUP BY c HAVING count(*)>1; + } + } {6 2} + do_test selectB-$ii.4 { + execsql { + SELECT t4.c, t3.a FROM + (SELECT c FROM t1 UNION ALL SELECT e FROM t2) AS t4, t1 AS t3 + WHERE t3.a=14 + ORDER BY 1 + } + } {6 14 6 14 12 14 15 14 18 14 24 14} + + do_test selectB-$ii.5 { + execsql { + SELECT d FROM t2 + EXCEPT + SELECT a FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) + } + } {} + do_test selectB-$ii.6 { + execsql { + SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) + EXCEPT + SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT d FROM t2) + } + } {} + do_test selectB-$ii.7 { + execsql { + SELECT c FROM t1 + EXCEPT + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + } + } {12} + do_test selectB-$ii.8 { + execsql { + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + EXCEPT + SELECT c FROM t1 + } + } {9 15 24 27} + do_test selectB-$ii.9 { + execsql { + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + EXCEPT + SELECT c FROM t1 + ORDER BY c DESC + } + } {27 24 15 9} + + do_test selectB-$ii.10 { + execsql { + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + UNION + SELECT c FROM t1 + ORDER BY c DESC + } + } {27 24 18 15 12 9 6} + do_test selectB-$ii.11 { + execsql { + SELECT c FROM t1 + UNION + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + ORDER BY c + } + } {6 9 12 15 18 24 27} + do_test selectB-$ii.12 { + execsql { + SELECT c FROM t1 UNION SELECT e FROM t2 UNION ALL SELECT f FROM t2 + ORDER BY c + } + } {6 9 12 15 18 18 24 27} + do_test selectB-$ii.13 { + execsql { + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + UNION + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + ORDER BY 1 + } + } {6 9 15 18 24 27} + + do_test selectB-$ii.14 { + execsql { + SELECT c FROM t1 + INTERSECT + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + ORDER BY 1 + } + } {6 18} + do_test selectB-$ii.15 { + execsql { + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + INTERSECT + SELECT c FROM t1 + ORDER BY 1 + } + } {6 18} + do_test selectB-$ii.16 { + execsql { + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + INTERSECT + SELECT * FROM (SELECT e FROM t2 UNION ALL SELECT f FROM t2) + ORDER BY 1 + } + } {6 9 15 18 24 27} + + do_test selectB-$ii.17 { + execsql { + SELECT * FROM ( + SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 4 + ) LIMIT 2 + } + } {2 8} + + do_test selectB-$ii.18 { + execsql { + SELECT * FROM ( + SELECT a FROM t1 UNION ALL SELECT d FROM t2 LIMIT 4 OFFSET 2 + ) LIMIT 2 + } + } {14 3} + + do_test selectB-$ii.19 { + execsql { + SELECT * FROM ( + SELECT DISTINCT (a/10) FROM t1 UNION ALL SELECT DISTINCT(d%2) FROM t2 + ) + } + } {0 1 1 0} + + do_test selectB-$ii.20 { + execsql { + SELECT DISTINCT * FROM ( + SELECT DISTINCT (a/10) FROM t1 UNION ALL SELECT DISTINCT(d%2) FROM t2 + ) + } + } {0 1} + + do_test selectB-$ii.21 { + execsql { + SELECT * FROM (SELECT * FROM t1 UNION ALL SELECT * FROM t2) ORDER BY a+b + } + } {2 4 6 3 6 9 8 10 12 12 15 18 14 16 18 21 24 27} + + do_test selectB-$ii.22 { + execsql { + SELECT * FROM (SELECT 345 UNION ALL SELECT d FROM t2) ORDER BY 1; + } + } {3 12 21 345} + + do_test selectB-$ii.23 { + execsql { + SELECT x, y FROM ( + SELECT a AS x, b AS y FROM t1 + UNION ALL + SELECT a*10 + 0.1, f*10 + 0.1 FROM t1 JOIN t2 ON (c=d) + UNION ALL + SELECT a*100, b*100 FROM t1 + ) ORDER BY 1; + } + } {2 4 8 10 14 16 80.1 180.1 200 400 800 1000 1400 1600} + + do_test selectB-$ii.24 { + execsql { + SELECT x, y FROM ( + SELECT a AS x, b AS y FROM t1 + UNION ALL + SELECT a*10 + 0.1, f*10 + 0.1 FROM t1 LEFT JOIN t2 ON (c=d) + UNION ALL + SELECT a*100, b*100 FROM t1 + ) ORDER BY 1; + } + } {2 4 8 10 14 16 20.1 {} 80.1 180.1 140.1 {} 200 400 800 1000 1400 1600} + + do_test selectB-$ii.25 { + execsql { + SELECT x+y FROM ( + SELECT a AS x, b AS y FROM t1 + UNION ALL + SELECT a*10 + 0.1, f*10 + 0.1 FROM t1 LEFT JOIN t2 ON (c=d) + UNION ALL + SELECT a*100, b*100 FROM t1 + ) WHERE y+x NOT NULL ORDER BY 1; + } + } {6 18 30 260.2 600 1800 3000} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/selectC.test b/components/external/SQLite-3.8.1/test/selectC.test new file mode 100644 index 0000000000000000000000000000000000000000..dedac41fc474dd816bf798a114fbdbcd4cc159c3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/selectC.test @@ -0,0 +1,236 @@ +# 2008 September 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# $Id: selectC.test,v 1.5 2009/05/17 15:26:21 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Ticket # +do_test selectC-1.1 { + execsql { + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1,'aaa','bbb'); + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 VALUES(2,'ccc','ddd'); + + SELECT DISTINCT a AS x, b||c AS y + FROM t1 + WHERE y IN ('aaabbb','xxx'); + } +} {1 aaabbb} +do_test selectC-1.2 { + execsql { + SELECT DISTINCT a AS x, b||c AS y + FROM t1 + WHERE b||c IN ('aaabbb','xxx'); + } +} {1 aaabbb} +do_test selectC-1.3 { + execsql { + SELECT DISTINCT a AS x, b||c AS y + FROM t1 + WHERE y='aaabbb' + } +} {1 aaabbb} +do_test selectC-1.4 { + execsql { + SELECT DISTINCT a AS x, b||c AS y + FROM t1 + WHERE b||c='aaabbb' + } +} {1 aaabbb} +do_test selectC-1.5 { + execsql { + SELECT DISTINCT a AS x, b||c AS y + FROM t1 + WHERE x=2 + } +} {2 cccddd} +do_test selectC-1.6 { + execsql { + SELECT DISTINCT a AS x, b||c AS y + FROM t1 + WHERE a=2 + } +} {2 cccddd} +do_test selectC-1.7 { + execsql { + SELECT DISTINCT a AS x, b||c AS y + FROM t1 + WHERE +y='aaabbb' + } +} {1 aaabbb} +do_test selectC-1.8 { + execsql { + SELECT a AS x, b||c AS y + FROM t1 + GROUP BY x, y + HAVING y='aaabbb' + } +} {1 aaabbb} +do_test selectC-1.9 { + execsql { + SELECT a AS x, b||c AS y + FROM t1 + GROUP BY x, y + HAVING b||c='aaabbb' + } +} {1 aaabbb} +do_test selectC-1.10 { + execsql { + SELECT a AS x, b||c AS y + FROM t1 + WHERE y='aaabbb' + GROUP BY x, y + } +} {1 aaabbb} +do_test selectC-1.11 { + execsql { + SELECT a AS x, b||c AS y + FROM t1 + WHERE b||c='aaabbb' + GROUP BY x, y + } +} {1 aaabbb} +proc longname_toupper x {return [string toupper $x]} +db function uppercaseconversionfunctionwithaverylongname longname_toupper +do_test selectC-1.12.1 { + execsql { + SELECT DISTINCT upper(b) AS x + FROM t1 + ORDER BY x + } +} {AAA CCC} +do_test selectC-1.12.2 { + execsql { + SELECT DISTINCT uppercaseconversionfunctionwithaverylongname(b) AS x + FROM t1 + ORDER BY x + } +} {AAA CCC} +do_test selectC-1.13.1 { + execsql { + SELECT upper(b) AS x + FROM t1 + GROUP BY x + ORDER BY x + } +} {AAA CCC} +do_test selectC-1.13.2 { + execsql { + SELECT uppercaseconversionfunctionwithaverylongname(b) AS x + FROM t1 + GROUP BY x + ORDER BY x + } +} {AAA CCC} +do_test selectC-1.14.1 { + execsql { + SELECT upper(b) AS x + FROM t1 + ORDER BY x DESC + } +} {CCC AAA AAA} +do_test selectC-1.14.2 { + execsql { + SELECT uppercaseconversionfunctionwithaverylongname(b) AS x + FROM t1 + ORDER BY x DESC + } +} {CCC AAA AAA} + +# The following query used to leak memory. Verify that has been fixed. +# +ifcapable trigger&&compound { + do_test selectC-2.1 { + catchsql { + CREATE TABLE t21a(a,b); + INSERT INTO t21a VALUES(1,2); + CREATE TABLE t21b(n); + CREATE TRIGGER r21 AFTER INSERT ON t21b BEGIN + SELECT a FROM t21a WHERE a>new.x UNION ALL + SELECT b FROM t21a WHERE b>new.x ORDER BY 1 LIMIT 2; + END; + INSERT INTO t21b VALUES(6); + } + } {1 {no such column: new.x}} +} + +# Check that ticket [883034dcb5] is fixed. +# +do_test selectC-3.1 { + execsql { + CREATE TABLE person ( + org_id TEXT NOT NULL, + nickname TEXT NOT NULL, + license TEXT, + CONSTRAINT person_pk PRIMARY KEY (org_id, nickname), + CONSTRAINT person_license_uk UNIQUE (license) + ); + INSERT INTO person VALUES('meyers', 'jack', '2GAT123'); + INSERT INTO person VALUES('meyers', 'hill', 'V345FMP'); + INSERT INTO person VALUES('meyers', 'jim', '2GAT138'); + INSERT INTO person VALUES('smith', 'maggy', ''); + INSERT INTO person VALUES('smith', 'jose', 'JJZ109'); + INSERT INTO person VALUES('smith', 'jack', 'THX138'); + INSERT INTO person VALUES('lakeside', 'dave', '953OKG'); + INSERT INTO person VALUES('lakeside', 'amy', NULL); + INSERT INTO person VALUES('lake-apts', 'tom', NULL); + INSERT INTO person VALUES('acorn', 'hideo', 'CQB421'); + + SELECT + org_id, + count((NOT (org_id IS NULL)) AND (NOT (nickname IS NULL))) + FROM person + WHERE (CASE WHEN license != '' THEN 1 ELSE 0 END) + GROUP BY 1; + } +} {acorn 1 lakeside 1 meyers 3 smith 2} +do_test selectC-3.2 { + execsql { + CREATE TABLE t2(a PRIMARY KEY, b); + INSERT INTO t2 VALUES('abc', 'xxx'); + INSERT INTO t2 VALUES('def', 'yyy'); + SELECT a, max(b || a) FROM t2 WHERE (b||b||b)!='value' GROUP BY a; + } +} {abc xxxabc def yyydef} +do_test selectC-3.3 { + execsql { + SELECT b, max(a || b) FROM t2 WHERE (b||b||b)!='value' GROUP BY a; + } +} {xxx abcxxx yyy defyyy} + + +proc udf {} { incr ::udf } +set ::udf 0 +db function udf udf + +do_execsql_test selectC-4.1 { + create table t_distinct_bug (a, b, c); + insert into t_distinct_bug values ('1', '1', 'a'); + insert into t_distinct_bug values ('1', '2', 'b'); + insert into t_distinct_bug values ('1', '3', 'c'); + insert into t_distinct_bug values ('1', '1', 'd'); + insert into t_distinct_bug values ('1', '2', 'e'); + insert into t_distinct_bug values ('1', '3', 'f'); +} {} + +do_execsql_test selectC-4.2 { + select a from (select distinct a, b from t_distinct_bug) +} {1 1 1} + +do_execsql_test selectC-4.3 { + select a, udf() from (select distinct a, b from t_distinct_bug) +} {1 1 1 2 1 3} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/selectD.test b/components/external/SQLite-3.8.1/test/selectD.test new file mode 100644 index 0000000000000000000000000000000000000000..89f999eb6db97d6411df3f2afdae4e012909cc62 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/selectD.test @@ -0,0 +1,174 @@ +# 2012 December 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for name resolution in SELECT +# statements that have parenthesized FROM clauses. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +for {set i 1} {$i<=2} {incr i} { + db close + forcedelete test$i.db + sqlite3 db test$i.db + if {$i==2} { + optimization_control db query-flattener off + } + do_test selectD-$i.0 { + db eval { + ATTACH ':memory:' AS aux1; + CREATE TABLE t1(a,b); INSERT INTO t1 VALUES(111,'x1'); + CREATE TABLE t2(a,b); INSERT INTO t2 VALUES(222,'x2'); + CREATE TEMP TABLE t3(a,b); INSERT INTO t3 VALUES(333,'x3'); + CREATE TABLE main.t4(a,b); INSERT INTO main.t4 VALUES(444,'x4'); + CREATE TABLE aux1.t4(a,b); INSERT INTO aux1.t4 VALUES(555,'x5'); + } + } {} + do_test selectD-$i.1 { + db eval { + SELECT * + FROM (t1), (t2), (t3), (t4) + WHERE t4.a=t3.a+111 + AND t3.a=t2.a+111 + AND t2.a=t1.a+111; + } + } {111 x1 222 x2 333 x3 444 x4} + do_test selectD-$i.2.1 { + db eval { + SELECT * + FROM t1 JOIN (t2 JOIN (t3 JOIN t4 ON t4.a=t3.a+111) + ON t3.a=t2.a+111) + ON t2.a=t1.a+111; + } + } {111 x1 222 x2 333 x3 444 x4} + do_test selectD-$i.2.2 { + db eval { + SELECT t3.a + FROM t1 JOIN (t2 JOIN (t3 JOIN t4 ON t4.a=t3.a+111) + ON t3.a=t2.a+111) + ON t2.a=t1.a+111; + } + } {333} + do_test selectD-$i.2.3 { + db eval { + SELECT t3.* + FROM t1 JOIN (t2 JOIN (t3 JOIN t4 ON t4.a=t3.a+111) + ON t3.a=t2.a+111) + ON t2.a=t1.a+111; + } + } {333 x3} + do_test selectD-$i.2.3 { + db eval { + SELECT t3.*, t2.* + FROM t1 JOIN (t2 JOIN (t3 JOIN t4 ON t4.a=t3.a+111) + ON t3.a=t2.a+111) + ON t2.a=t1.a+111; + } + } {333 x3 222 x2} + do_test selectD-$i.2.4 { + db eval { + SELECT * + FROM t1 JOIN (t2 JOIN (main.t4 JOIN aux1.t4 ON aux1.t4.a=main.t4.a+111) + ON main.t4.a=t2.a+222) + ON t2.a=t1.a+111; + } + } {111 x1 222 x2 444 x4 555 x5} + do_test selectD-$i.2.5 { + db eval { + SELECT * + FROM t1 JOIN (t2 JOIN (main.t4 AS x JOIN aux1.t4 ON aux1.t4.a=x.a+111) + ON x.a=t2.a+222) + ON t2.a=t1.a+111; + } + } {111 x1 222 x2 444 x4 555 x5} + do_test selectD-$i.2.6 { + catchsql { + SELECT * + FROM t1 JOIN (t2 JOIN (main.t4 JOIN aux.t4 ON aux.t4.a=main.t4.a+111) + ON main.t4.a=t2.a+222) + ON t2.a=t1.a+111; + } + } {1 {no such table: aux.t4}} + do_test selectD-$i.2.7 { + db eval { + SELECT x.a, y.b + FROM t1 JOIN (t2 JOIN (main.t4 x JOIN aux1.t4 y ON y.a=x.a+111) + ON x.a=t2.a+222) + ON t2.a=t1.a+111; + } + } {444 x5} + do_test selectD-$i.3 { + db eval { + UPDATE t2 SET a=111; + UPDATE t3 SET a=111; + UPDATE t4 SET a=111; + SELECT * + FROM t1 JOIN (t2 JOIN (t3 JOIN t4 USING(a)) USING (a)) USING (a); + } + } {111 x1 x2 x3 x4} + do_test selectD-$i.4 { + db eval { + UPDATE t2 SET a=111; + UPDATE t3 SET a=111; + UPDATE t4 SET a=111; + SELECT * + FROM t1 LEFT JOIN (t2 LEFT JOIN (t3 LEFT JOIN t4 USING(a)) + USING (a)) + USING (a); + } + } {111 x1 x2 x3 x4} + do_test selectD-$i.5 { + db eval { + UPDATE t3 SET a=222; + UPDATE t4 SET a=222; + SELECT * + FROM (t1 LEFT JOIN t2 USING(a)) JOIN (t3 LEFT JOIN t4 USING(a)) + ON t1.a=t3.a-111; + } + } {111 x1 x2 222 x3 x4} + do_test selectD-$i.6 { + db eval { + UPDATE t4 SET a=333; + SELECT * + FROM (t1 LEFT JOIN t2 USING(a)) JOIN (t3 LEFT JOIN t4 USING(a)) + ON t1.a=t3.a-111; + } + } {111 x1 x2 222 x3 {}} + do_test selectD-$i.7 { + db eval { + SELECT t1.*, t2.*, t3.*, t4.b + FROM (t1 LEFT JOIN t2 USING(a)) JOIN (t3 LEFT JOIN t4 USING(a)) + ON t1.a=t3.a-111; + } + } {111 x1 111 x2 222 x3 {}} +} + +# The following test was added on 2013-04-24 in order to verify that +# the datatypes and affinities of sub-sub-queries are set prior to computing +# the datatypes and affinities of the parent sub-queries because the +# latter computation depends on the former. +# +do_execsql_test selectD-4.1 { + CREATE TABLE t41(a INTEGER PRIMARY KEY, b INTEGER); + CREATE TABLE t42(d INTEGER PRIMARY KEY, e INTEGER); + CREATE TABLE t43(f INTEGER PRIMARY KEY, g INTEGER); + EXPLAIN QUERY PLAN + SELECT * + FROM t41 + LEFT JOIN (SELECT count(*) AS cnt, x1.d + FROM (t42 INNER JOIN t43 ON d=g) AS x1 + WHERE x1.d>5 + GROUP BY x1.d) AS x2 + ON t41.b=x2.d; +} {/.*SEARCH SUBQUERY 1 AS x2 USING AUTOMATIC.*/} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/selectE.test b/components/external/SQLite-3.8.1/test/selectE.test new file mode 100644 index 0000000000000000000000000000000000000000..d7592bbbc5711c91cc43898a38924f9a2f953cbf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/selectE.test @@ -0,0 +1,95 @@ +# 2013-05-07 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for compound SELECT statements +# that have ORDER BY clauses with collating sequences that differ +# from the collating sequence used for comparison in the compound. +# +# Ticket 6709574d2a8d8b9be3a9cb1afbf4ff2de48ea4e7: +# drh added on 2013-05-06 15:21:16: +# +# In the code shown below (which is intended to be run from the +# sqlite3.exe command-line tool) the three SELECT statements should all +# generate the same answer. But the third one does not. It is as if the +# COLLATE clause on the ORDER BY somehow got pulled into the EXCEPT +# operator. Note that the ".print" commands are instructions to the +# sqlite3.exe shell program to output delimiter lines so that you can more +# easily tell where the output of one query ends and the next query +# begins. +# +# CREATE TABLE t1(a); +# INSERT INTO t1 VALUES('abc'),('def'); +# CREATE TABLE t2(a); +# INSERT INTO t2 VALUES('DEF'); +# +# SELECT a FROM t1 EXCEPT SELECT a FROM t2 ORDER BY a; +# .print ----- +# SELECT a FROM (SELECT a FROM t1 EXCEPT SELECT a FROM t2) +# ORDER BY a COLLATE nocase; +# .print ----- +# SELECT a FROM t1 EXCEPT SELECT a FROM t2 ORDER BY a COLLATE nocase; +# +# Bisecting shows that this problem was introduced in SQLite version 3.6.0 +# by check-in [8bbfa97837a74ef] on 2008-06-15. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test selectE-1.0 { + db eval { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES('abc'),('def'),('ghi'); + CREATE TABLE t2(a); + INSERT INTO t2 VALUES('DEF'),('abc'); + CREATE TABLE t3(a); + INSERT INTO t3 VALUES('def'),('jkl'); + + SELECT a FROM t1 EXCEPT SELECT a FROM t2 + ORDER BY a COLLATE nocase; + } +} {def ghi} +do_test selectE-1.1 { + db eval { + SELECT a FROM t2 EXCEPT SELECT a FROM t3 + ORDER BY a COLLATE nocase; + } +} {abc DEF} +do_test selectE-1.2 { + db eval { + SELECT a FROM t2 EXCEPT SELECT a FROM t3 + ORDER BY a COLLATE binary; + } +} {DEF abc} +do_test selectE-1.3 { + db eval { + SELECT a FROM t2 EXCEPT SELECT a FROM t3 + ORDER BY a; + } +} {DEF abc} + +do_test selectE-2.1 { + db eval { + DELETE FROM t2; + DELETE FROM t3; + INSERT INTO t2 VALUES('ABC'),('def'),('GHI'),('jkl'); + INSERT INTO t3 SELECT lower(a) FROM t2; + SELECT a COLLATE nocase FROM t2 EXCEPT SELECT a FROM t3 + ORDER BY 1 + } +} {} +do_test selectE-2.2 { + db eval { + SELECT a COLLATE nocase FROM t2 EXCEPT SELECT a FROM t3 + ORDER BY 1 COLLATE binary + } +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/server1.test b/components/external/SQLite-3.8.1/test/server1.test new file mode 100644 index 0000000000000000000000000000000000000000..90673ef00011a3dd2221c280527c6f4a827d4486 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/server1.test @@ -0,0 +1,171 @@ +# 2006 January 09 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is testing the server mode of SQLite. +# +# This file is derived from thread1.test +# +# $Id: server1.test,v 1.5 2007/08/29 18:20:17 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Skip this whole file if the server testing code is not enabled +# +if {[llength [info command client_step]]==0 || [sqlite3 -has-codec]} { + finish_test + return +} + +# The sample server implementation does not work right when memory +# management is enabled. +# +ifcapable (memorymanage||mutex_noop) { + finish_test + return +} + +# Create some data to work with +# +do_test server1-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,'abcdefgh'); + INSERT INTO t1 SELECT a+1, b||b FROM t1; + INSERT INTO t1 SELECT a+2, b||b FROM t1; + INSERT INTO t1 SELECT a+4, b||b FROM t1; + SELECT count(*), max(length(b)) FROM t1; + } +} {8 64} + +# Interleave two threads on read access. Then make sure a third +# thread can write the database. In other words: +# +# read-lock A +# read-lock B +# unlock A +# unlock B +# write-lock C +# +do_test server1-1.2 { + client_create A test.db + client_create B test.db + client_create C test.db + client_compile A {SELECT a FROM t1} + client_step A + client_result A +} SQLITE_ROW +do_test server1-1.3 { + client_argc A +} 1 +do_test server1-1.4 { + client_argv A 0 +} 1 +do_test server1-1.5 { + client_compile B {SELECT b FROM t1} + client_step B + client_result B +} SQLITE_ROW +do_test server1-1.6 { + client_argc B +} 1 +do_test server1-1.7 { + client_argv B 0 +} abcdefgh +do_test server1-1.8 { + client_finalize A + client_result A +} SQLITE_OK +do_test server1-1.9 { + client_finalize B + client_result B +} SQLITE_OK +do_test server1-1.10 { + client_compile C {CREATE TABLE t2(x,y)} + client_step C + client_result C +} SQLITE_DONE +do_test server1-1.11 { + client_finalize C + client_result C +} SQLITE_OK +do_test server1-1.12 { + catchsql {SELECT name FROM sqlite_master} + execsql {SELECT name FROM sqlite_master} +} {t1 t2} + + +# Read from table t1. Do not finalize the statement. This +# will leave the lock pending. +# +do_test server1-2.1 { + client_halt * + client_create A test.db + client_compile A {SELECT a FROM t1} + client_step A + client_result A +} SQLITE_ROW + +# Read from the same table from another thread. This is allows. +# +do_test server1-2.2 { + client_create B test.db + client_compile B {SELECT b FROM t1} + client_step B + client_result B +} SQLITE_ROW + +# Write to a different table from another thread. This is allowed +# because in server mode with a shared cache we have table-level locking. +# +do_test server1-2.3 { + client_create C test.db + client_compile C {INSERT INTO t2 VALUES(98,99)} + client_step C + client_result C + client_finalize C + client_result C +} SQLITE_OK + +# But we cannot insert into table t1 because threads A and B have it locked. +# +do_test server1-2.4 { + client_compile C {INSERT INTO t1 VALUES(98,99)} + client_step C + client_result C + client_finalize C + client_result C +} SQLITE_LOCKED +do_test server1-2.5 { + client_finalize B + client_wait B + client_compile C {INSERT INTO t1 VALUES(98,99)} + client_step C + client_result C + client_finalize C + client_result C +} SQLITE_LOCKED + +# Insert into t1 is successful after finishing the other two threads. +do_test server1-2.6 { + client_finalize A + client_wait A + client_compile C {INSERT INTO t1 VALUES(98,99)} + client_step C + client_result C + client_finalize C + client_result C +} SQLITE_OK + +client_halt * +sqlite3_enable_shared_cache 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/shared.test b/components/external/SQLite-3.8.1/test/shared.test new file mode 100644 index 0000000000000000000000000000000000000000..4eab476582c2230ca24cdcdadda3205ba2217563 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shared.test @@ -0,0 +1,1184 @@ +# 2005 December 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: shared.test,v 1.36 2009/03/16 13:19:36 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +db close + +# These tests cannot be run without the ATTACH command. +# +ifcapable !shared_cache||!attach { + finish_test + return +} + +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +foreach av [list 0 1] { + +# Open the database connection and execute the auto-vacuum pragma +forcedelete test.db +sqlite3 db test.db + +ifcapable autovacuum { + do_test shared-[expr $av+1].1.0 { + execsql "pragma auto_vacuum=$::av" + execsql {pragma auto_vacuum} + } "$av" +} else { + if {$av} { + db close + break + } +} + +# if we're using proxy locks, we use 2 filedescriptors for a db +# that is open but NOT yet locked, after a lock is taken we'll have 3, +# normally sqlite uses 1 (proxy locking adds the conch and the local lock) +set using_proxy 0 +foreach {name value} [array get env SQLITE_FORCE_PROXY_LOCKING] { + set using_proxy $value +} +set extrafds_prelock 0 +set extrafds_postlock 0 +if {$using_proxy>0} { + set extrafds_prelock 1 + set extrafds_postlock 2 +} + +# $av is currently 0 if this loop iteration is to test with auto-vacuum turned +# off, and 1 if it is turned on. Increment it so that (1 -> no auto-vacuum) +# and (2 -> auto-vacuum). The sole reason for this is so that it looks nicer +# when we use this variable as part of test-case names. +# +incr av + +# Test organization: +# +# shared-1.*: Simple test to verify basic sanity of table level locking when +# two connections share a pager cache. +# shared-2.*: Test that a read transaction can co-exist with a +# write-transaction, including a simple test to ensure the +# external locking protocol is still working. +# shared-3.*: Simple test of read-uncommitted mode. +# shared-4.*: Check that the schema is locked and unlocked correctly. +# shared-5.*: Test that creating/dropping schema items works when databases +# are attached in different orders to different handles. +# shared-6.*: Locking, UNION ALL queries and sub-queries. +# shared-7.*: Autovacuum and shared-cache. +# shared-8.*: Tests related to the text encoding of shared-cache databases. +# shared-9.*: TEMP triggers and shared-cache databases. +# shared-10.*: Tests of sqlite3_close(). +# shared-11.*: Test transaction locking. +# + +do_test shared-$av.1.1 { + # Open a second database on the file test.db. It should use the same pager + # cache and schema as the original connection. Verify that only 1 file is + # opened. + sqlite3 db2 test.db + set ::sqlite_open_file_count + expr $sqlite_open_file_count-$extrafds_postlock +} {1} +do_test shared-$av.1.2 { + # Add a table and a single row of data via the first connection. + # Ensure that the second connection can see them. + execsql { + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(1, 2, 3); + } db + execsql { + SELECT * FROM abc; + } db2 +} {1 2 3} +do_test shared-$av.1.3 { + # Have the first connection begin a transaction and obtain a read-lock + # on table abc. This should not prevent the second connection from + # querying abc. + execsql { + BEGIN; + SELECT * FROM abc; + } + execsql { + SELECT * FROM abc; + } db2 +} {1 2 3} +do_test shared-$av.1.4 { + # Try to insert a row into abc via connection 2. This should fail because + # of the read-lock connection 1 is holding on table abc (obtained in the + # previous test case). + catchsql { + INSERT INTO abc VALUES(4, 5, 6); + } db2 +} {1 {database table is locked: abc}} +do_test shared-$av.1.5 { + # Using connection 2 (the one without the open transaction), try to create + # a new table. This should fail because of the open read transaction + # held by connection 1. + catchsql { + CREATE TABLE def(d, e, f); + } db2 +} {1 {database table is locked: sqlite_master}} +do_test shared-$av.1.6 { + # Upgrade connection 1's transaction to a write transaction. Create + # a new table - def - and insert a row into it. Because the connection 1 + # transaction modifies the schema, it should not be possible for + # connection 2 to access the database at all until the connection 1 + # has finished the transaction. + execsql { + CREATE TABLE def(d, e, f); + INSERT INTO def VALUES('IV', 'V', 'VI'); + } +} {} +do_test shared-$av.1.7 { + # Read from the sqlite_master table with connection 1 (inside the + # transaction). Then test that we can not do this with connection 2. This + # is because of the schema-modified lock established by connection 1 + # in the previous test case. + execsql { + SELECT * FROM sqlite_master; + } + catchsql { + SELECT * FROM sqlite_master; + } db2 +} {1 {database schema is locked: main}} +do_test shared-$av.1.8 { + # Commit the connection 1 transaction. + execsql { + COMMIT; + } +} {} + +do_test shared-$av.2.1 { + # Open connection db3 to the database. Use a different path to the same + # file so that db3 does *not* share the same pager cache as db and db2 + # (there should be two open file handles). + if {$::tcl_platform(platform)=="unix"} { + sqlite3 db3 ./test.db + } else { + sqlite3 db3 TEST.DB + } + set ::sqlite_open_file_count + expr $sqlite_open_file_count-($extrafds_prelock+$extrafds_postlock) +} {2} +do_test shared-$av.2.2 { + # Start read transactions on db and db2 (the shared pager cache). Ensure + # db3 cannot write to the database. + execsql { + BEGIN; + SELECT * FROM abc; + } + execsql { + BEGIN; + SELECT * FROM abc; + } db2 + catchsql { + INSERT INTO abc VALUES(1, 2, 3); + } db2 +} {1 {database table is locked: abc}} +do_test shared-$av.2.3 { + # Turn db's transaction into a write-transaction. db3 should still be + # able to read from table def (but will not see the new row). Connection + # db2 should not be able to read def (because of the write-lock). + +# Todo: The failed "INSERT INTO abc ..." statement in the above test +# has started a write-transaction on db2 (should this be so?). This +# would prevent connection db from starting a write-transaction. So roll the +# db2 transaction back and replace it with a new read transaction. + execsql { + ROLLBACK; + BEGIN; + SELECT * FROM abc; + } db2 + + execsql { + INSERT INTO def VALUES('VII', 'VIII', 'IX'); + } + concat [ + catchsql { SELECT * FROM def; } db3 + ] [ + catchsql { SELECT * FROM def; } db2 + ] +} {0 {IV V VI} 1 {database table is locked: def}} +do_test shared-$av.2.4 { + # Commit the open transaction on db. db2 still holds a read-transaction. + # This should prevent db3 from writing to the database, but not from + # reading. + execsql { + COMMIT; + } + concat [ + catchsql { SELECT * FROM def; } db3 + ] [ + catchsql { INSERT INTO def VALUES('X', 'XI', 'XII'); } db3 + ] +} {0 {IV V VI VII VIII IX} 1 {database is locked}} + +catchsql COMMIT db2 + +do_test shared-$av.3.1.1 { + # This test case starts a linear scan of table 'seq' using a + # read-uncommitted connection. In the middle of the scan, rows are added + # to the end of the seq table (ahead of the current cursor position). + # The uncommitted rows should be included in the results of the scan. + execsql " + CREATE TABLE seq(i PRIMARY KEY, x); + INSERT INTO seq VALUES(1, '[string repeat X 500]'); + INSERT INTO seq VALUES(2, '[string repeat X 500]'); + " + execsql {SELECT * FROM sqlite_master} db2 + execsql {PRAGMA read_uncommitted = 1} db2 + + set ret [list] + db2 eval {SELECT i FROM seq ORDER BY i} { + if {$i < 4} { + set max [execsql {SELECT max(i) FROM seq}] + db eval { + INSERT INTO seq SELECT i + :max, x FROM seq; + } + } + lappend ret $i + } + set ret +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} +do_test shared-$av.3.1.2 { + # Another linear scan through table seq using a read-uncommitted connection. + # This time, delete each row as it is read. Should not affect the results of + # the scan, but the table should be empty after the scan is concluded + # (test 3.1.3 verifies this). + set ret [list] + db2 eval {SELECT i FROM seq} { + db eval {DELETE FROM seq WHERE i = :i} + lappend ret $i + } + set ret +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} +do_test shared-$av.3.1.3 { + execsql { + SELECT * FROM seq; + } +} {} + +catch {db close} +catch {db2 close} +catch {db3 close} + +#-------------------------------------------------------------------------- +# Tests shared-4.* test that the schema locking rules are applied +# correctly. i.e.: +# +# 1. All transactions require a read-lock on the schemas of databases they +# access. +# 2. Transactions that modify a database schema require a write-lock on that +# schema. +# 3. It is not possible to compile a statement while another handle has a +# write-lock on the schema. +# + +# Open two database handles db and db2. Each has a single attach database +# (as well as main): +# +# db.main -> ./test.db +# db.test2 -> ./test2.db +# db2.main -> ./test2.db +# db2.test -> ./test.db +# +forcedelete test.db +forcedelete test2.db +forcedelete test2.db-journal +sqlite3 db test.db +sqlite3 db2 test2.db +do_test shared-$av.4.1.1 { + set sqlite_open_file_count + expr $sqlite_open_file_count-($extrafds_prelock*2) +} {2} +do_test shared-$av.4.1.2 { + execsql {ATTACH 'test2.db' AS test2} + set sqlite_open_file_count + expr $sqlite_open_file_count-($extrafds_postlock*2) +} {2} +do_test shared-$av.4.1.3 { + execsql {ATTACH 'test.db' AS test} db2 + set sqlite_open_file_count + expr $sqlite_open_file_count-($extrafds_postlock*2) +} {2} + +# Sanity check: Create a table in ./test.db via handle db, and test that handle +# db2 can "see" the new table immediately. A handle using a seperate pager +# cache would have to reload the database schema before this were possible. +# +do_test shared-$av.4.2.1 { + execsql { + CREATE TABLE abc(a, b, c); + CREATE TABLE def(d, e, f); + INSERT INTO abc VALUES('i', 'ii', 'iii'); + INSERT INTO def VALUES('I', 'II', 'III'); + } +} {} +do_test shared-$av.4.2.2 { + execsql { + SELECT * FROM test.abc; + } db2 +} {i ii iii} + +# Open a read-transaction and read from table abc via handle 2. Check that +# handle 1 can read table abc. Check that handle 1 cannot modify table abc +# or the database schema. Then check that handle 1 can modify table def. +# +do_test shared-$av.4.3.1 { + execsql { + BEGIN; + SELECT * FROM test.abc; + } db2 +} {i ii iii} +do_test shared-$av.4.3.2 { + catchsql { + INSERT INTO abc VALUES('iv', 'v', 'vi'); + } +} {1 {database table is locked: abc}} +do_test shared-$av.4.3.3 { + catchsql { + CREATE TABLE ghi(g, h, i); + } +} {1 {database table is locked: sqlite_master}} +do_test shared-$av.4.3.3 { + catchsql { + INSERT INTO def VALUES('IV', 'V', 'VI'); + } +} {0 {}} +do_test shared-$av.4.3.4 { + # Cleanup: commit the transaction opened by db2. + execsql { + COMMIT + } db2 +} {} + +# Open a write-transaction using handle 1 and modify the database schema. +# Then try to execute a compiled statement to read from the same +# database via handle 2 (fails to get the lock on sqlite_master). Also +# try to compile a read of the same database using handle 2 (also fails). +# Finally, compile a read of the other database using handle 2. This +# should also fail. +# +ifcapable compound { + do_test shared-$av.4.4.1.2 { + # Sanity check 1: Check that the schema is what we think it is when viewed + # via handle 1. + execsql { + CREATE TABLE test2.ghi(g, h, i); + SELECT 'test.db:'||name FROM sqlite_master + UNION ALL + SELECT 'test2.db:'||name FROM test2.sqlite_master; + } + } {test.db:abc test.db:def test2.db:ghi} + do_test shared-$av.4.4.1.2 { + # Sanity check 2: Check that the schema is what we think it is when viewed + # via handle 2. + execsql { + SELECT 'test2.db:'||name FROM sqlite_master + UNION ALL + SELECT 'test.db:'||name FROM test.sqlite_master; + } db2 + } {test2.db:ghi test.db:abc test.db:def} +} + +do_test shared-$av.4.4.2 { + set ::DB2 [sqlite3_connection_pointer db2] + set sql {SELECT * FROM abc} + set ::STMT1 [sqlite3_prepare $::DB2 $sql -1 DUMMY] + execsql { + BEGIN; + CREATE TABLE jkl(j, k, l); + } + sqlite3_step $::STMT1 +} {SQLITE_ERROR} +do_test shared-$av.4.4.3 { + sqlite3_finalize $::STMT1 +} {SQLITE_LOCKED} +do_test shared-$av.4.4.4 { + set rc [catch { + set ::STMT1 [sqlite3_prepare $::DB2 $sql -1 DUMMY] + } msg] + list $rc $msg +} {1 {(6) database schema is locked: test}} +do_test shared-$av.4.4.5 { + set rc [catch { + set ::STMT1 [sqlite3_prepare $::DB2 "SELECT * FROM ghi" -1 DUMMY] + } msg] + list $rc $msg +} {1 {(6) database schema is locked: test}} + + +catch {db2 close} +catch {db close} + +#-------------------------------------------------------------------------- +# Tests shared-5.* +# +foreach db [list test.db test1.db test2.db test3.db] { + forcedelete $db ${db}-journal +} +do_test shared-$av.5.1.1 { + sqlite3 db1 test.db + sqlite3 db2 test.db + execsql { + ATTACH 'test1.db' AS test1; + ATTACH 'test2.db' AS test2; + ATTACH 'test3.db' AS test3; + } db1 + execsql { + ATTACH 'test3.db' AS test3; + ATTACH 'test2.db' AS test2; + ATTACH 'test1.db' AS test1; + } db2 +} {} +do_test shared-$av.5.1.2 { + execsql { + CREATE TABLE test1.t1(a, b); + CREATE INDEX test1.i1 ON t1(a, b); + } db1 +} {} +ifcapable view { + do_test shared-$av.5.1.3 { + execsql { + CREATE VIEW test1.v1 AS SELECT * FROM t1; + } db1 + } {} +} +ifcapable trigger { + do_test shared-$av.5.1.4 { + execsql { + CREATE TRIGGER test1.trig1 AFTER INSERT ON t1 BEGIN + INSERT INTO t1 VALUES(new.a, new.b); + END; + } db1 + } {} +} +do_test shared-$av.5.1.5 { + execsql { + DROP INDEX i1; + } db2 +} {} +ifcapable view { + do_test shared-$av.5.1.6 { + execsql { + DROP VIEW v1; + } db2 + } {} +} +ifcapable trigger { + do_test shared-$av.5.1.7 { + execsql { + DROP TRIGGER trig1; + } db2 + } {} +} +do_test shared-$av.5.1.8 { + execsql { + DROP TABLE t1; + } db2 +} {} +ifcapable compound { + do_test shared-$av.5.1.9 { + execsql { + SELECT * FROM sqlite_master UNION ALL SELECT * FROM test1.sqlite_master + } db1 + } {} +} + +#-------------------------------------------------------------------------- +# Tests shared-6.* test that a query obtains all the read-locks it needs +# before starting execution of the query. This means that there is no chance +# some rows of data will be returned before a lock fails and SQLITE_LOCK +# is returned. +# +do_test shared-$av.6.1.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t2 VALUES(3, 4); + } db1 +} {} +ifcapable compound { + do_test shared-$av.6.1.2 { + execsql { + SELECT * FROM t1 UNION ALL SELECT * FROM t2; + } db2 + } {1 2 3 4} +} +do_test shared-$av.6.1.3 { + # Establish a write lock on table t2 via connection db2. Then make a + # UNION all query using connection db1 that first accesses t1, followed + # by t2. If the locks are grabbed at the start of the statement (as + # they should be), no rows are returned. If (as was previously the case) + # they are grabbed as the tables are accessed, the t1 rows will be + # returned before the query fails. + # + execsql { + BEGIN; + INSERT INTO t2 VALUES(5, 6); + } db2 + set ret [list] + catch { + db1 eval {SELECT * FROM t1 UNION ALL SELECT * FROM t2} { + lappend ret $a $b + } + } + set ret +} {} +do_test shared-$av.6.1.4 { + execsql { + COMMIT; + BEGIN; + INSERT INTO t1 VALUES(7, 8); + } db2 + set ret [list] + catch { + db1 eval { + SELECT (CASE WHEN a>4 THEN (SELECT a FROM t1) ELSE 0 END) AS d FROM t2; + } { + lappend ret $d + } + } + set ret +} {} + +catch {db1 close} +catch {db2 close} +foreach f [list test.db test2.db] { + forcedelete $f ${f}-journal +} + +#-------------------------------------------------------------------------- +# Tests shared-7.* test auto-vacuum does not invalidate cursors from +# other shared-cache users when it reorganizes the database on +# COMMIT. +# +do_test shared-$av.7.1 { + # This test case sets up a test database in auto-vacuum mode consisting + # of two tables, t1 and t2. Both have a single index. Table t1 is + # populated first (so consists of pages toward the start of the db file), + # t2 second (pages toward the end of the file). + sqlite3 db test.db + sqlite3 db2 test.db + execsql { + BEGIN; + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TABLE t2(a PRIMARY KEY, b); + } + set ::contents {} + for {set i 0} {$i < 100} {incr i} { + set a [string repeat "$i " 20] + set b [string repeat "$i " 20] + db eval { + INSERT INTO t1 VALUES(:a, :b); + } + lappend ::contents [list [expr $i+1] $a $b] + } + execsql { + INSERT INTO t2 SELECT * FROM t1; + COMMIT; + } +} {} +do_test shared-$av.7.2 { + # This test case deletes the contents of table t1 (the one at the start of + # the file) while many cursors are open on table t2 and its index. All of + # the non-root pages will be moved from the end to the start of the file + # when the DELETE is committed - this test verifies that moving the pages + # does not disturb the open cursors. + # + + proc lockrow {db tbl oids body} { + set ret [list] + db eval "SELECT oid AS i, a, b FROM $tbl ORDER BY a" { + if {$i==[lindex $oids 0]} { + set noids [lrange $oids 1 end] + if {[llength $noids]==0} { + set subret [eval $body] + } else { + set subret [lockrow $db $tbl $noids $body] + } + } + lappend ret [list $i $a $b] + } + return [linsert $subret 0 $ret] + } + proc locktblrows {db tbl body} { + set oids [db eval "SELECT oid FROM $tbl"] + lockrow $db $tbl $oids $body + } + + set scans [locktblrows db t2 { + execsql { + DELETE FROM t1; + } db2 + }] + set error 0 + + # Test that each SELECT query returned the expected contents of t2. + foreach s $scans { + if {[lsort -integer -index 0 $s]!=$::contents} { + set error 1 + } + } + set error +} {0} + +catch {db close} +catch {db2 close} +unset -nocomplain contents + +#-------------------------------------------------------------------------- +# The following tests try to trick the shared-cache code into assuming +# the wrong encoding for a database. +# +forcedelete test.db test.db-journal +ifcapable utf16 { + do_test shared-$av.8.1.1 { + sqlite3 db test.db + execsql { + PRAGMA encoding = 'UTF-16'; + SELECT * FROM sqlite_master; + } + } {} + do_test shared-$av.8.1.2 { + string range [execsql {PRAGMA encoding;}] 0 end-2 + } {UTF-16} + + do_test shared-$av.8.1.3 { + sqlite3 db2 test.db + execsql { + PRAGMA encoding = 'UTF-8'; + CREATE TABLE abc(a, b, c); + } db2 + } {} + do_test shared-$av.8.1.4 { + execsql { + SELECT * FROM sqlite_master; + } + } "table abc abc [expr $AUTOVACUUM?3:2] {CREATE TABLE abc(a, b, c)}" + do_test shared-$av.8.1.5 { + db2 close + execsql { + PRAGMA encoding; + } + } {UTF-8} + + forcedelete test2.db test2.db-journal + do_test shared-$av.8.2.1 { + execsql { + ATTACH 'test2.db' AS aux; + SELECT * FROM aux.sqlite_master; + } + } {} + do_test shared-$av.8.2.2 { + sqlite3 db2 test2.db + execsql { + PRAGMA encoding = 'UTF-16'; + CREATE TABLE def(d, e, f); + } db2 + string range [execsql {PRAGMA encoding;} db2] 0 end-2 + } {UTF-16} + + catch {db close} + catch {db2 close} + forcedelete test.db test2.db + + do_test shared-$av.8.3.2 { + sqlite3 db test.db + execsql { CREATE TABLE def(d, e, f) } + execsql { PRAGMA encoding } + } {UTF-8} + do_test shared-$av.8.3.3 { + set zDb16 "[encoding convertto unicode test.db]\x00\x00" + set db16 [sqlite3_open16 $zDb16 {}] + + set stmt [sqlite3_prepare $db16 "SELECT sql FROM sqlite_master" -1 DUMMY] + sqlite3_step $stmt + set sql [sqlite3_column_text $stmt 0] + sqlite3_finalize $stmt + set sql + } {CREATE TABLE def(d, e, f)} + do_test shared-$av.8.3.4 { + set stmt [sqlite3_prepare $db16 "PRAGMA encoding" -1 DUMMY] + sqlite3_step $stmt + set enc [sqlite3_column_text $stmt 0] + sqlite3_finalize $stmt + set enc + } {UTF-8} + + sqlite3_close $db16 + +# Bug #2547 is causing this to fail. +if 0 { + do_test shared-$av.8.2.3 { + catchsql { + SELECT * FROM aux.sqlite_master; + } + } {1 {attached databases must use the same text encoding as main database}} +} +} + +catch {db close} +catch {db2 close} +forcedelete test.db test2.db + +#--------------------------------------------------------------------------- +# The following tests - shared-9.* - test interactions between TEMP triggers +# and shared-schemas. +# +ifcapable trigger&&tempdb { + +do_test shared-$av.9.1 { + sqlite3 db test.db + sqlite3 db2 test.db + execsql { + CREATE TABLE abc(a, b, c); + CREATE TABLE abc_mirror(a, b, c); + CREATE TEMP TRIGGER BEFORE INSERT ON abc BEGIN + INSERT INTO abc_mirror(a, b, c) VALUES(new.a, new.b, new.c); + END; + INSERT INTO abc VALUES(1, 2, 3); + SELECT * FROM abc_mirror; + } +} {1 2 3} +do_test shared-$av.9.2 { + execsql { + INSERT INTO abc VALUES(4, 5, 6); + SELECT * FROM abc_mirror; + } db2 +} {1 2 3} +do_test shared-$av.9.3 { + db close + db2 close +} {} + +} ; # End shared-9.* + +#--------------------------------------------------------------------------- +# The following tests - shared-10.* - test that the library behaves +# correctly when a connection to a shared-cache is closed. +# +do_test shared-$av.10.1 { + # Create a small sample database with two connections to it (db and db2). + forcedelete test.db + sqlite3 db test.db + sqlite3 db2 test.db + execsql { + CREATE TABLE ab(a PRIMARY KEY, b); + CREATE TABLE de(d PRIMARY KEY, e); + INSERT INTO ab VALUES('Chiang Mai', 100000); + INSERT INTO ab VALUES('Bangkok', 8000000); + INSERT INTO de VALUES('Ubon', 120000); + INSERT INTO de VALUES('Khon Kaen', 200000); + } +} {} +do_test shared-$av.10.2 { + # Open a read-transaction with the first connection, a write-transaction + # with the second. + execsql { + BEGIN; + SELECT * FROM ab; + } + execsql { + BEGIN; + INSERT INTO de VALUES('Pataya', 30000); + } db2 +} {} +do_test shared-$av.10.3 { + # An external connection should be able to read the database, but not + # prepare a write operation. + if {$::tcl_platform(platform)=="unix"} { + sqlite3 db3 ./test.db + } else { + sqlite3 db3 TEST.DB + } + execsql { + SELECT * FROM ab; + } db3 + catchsql { + BEGIN; + INSERT INTO de VALUES('Pataya', 30000); + } db3 +} {1 {database is locked}} +do_test shared-$av.10.4 { + # Close the connection with the write-transaction open + db2 close +} {} +do_test shared-$av.10.5 { + # Test that the db2 transaction has been automatically rolled back. + # If it has not the ('Pataya', 30000) entry will still be in the table. + execsql { + SELECT * FROM de; + } +} {Ubon 120000 {Khon Kaen} 200000} +do_test shared-$av.10.5 { + # Closing db2 should have dropped the shared-cache back to a read-lock. + # So db3 should be able to prepare a write... + catchsql {INSERT INTO de VALUES('Pataya', 30000);} db3 +} {0 {}} +do_test shared-$av.10.6 { + # ... but not commit it. + catchsql {COMMIT} db3 +} {1 {database is locked}} +do_test shared-$av.10.7 { + # Commit the (read-only) db transaction. Check via db3 to make sure the + # contents of table "de" are still as they should be. + execsql { + COMMIT; + } + execsql { + SELECT * FROM de; + } db3 +} {Ubon 120000 {Khon Kaen} 200000 Pataya 30000} +do_test shared-$av.10.9 { + # Commit the external transaction. + catchsql {COMMIT} db3 +} {0 {}} +integrity_check shared-$av.10.10 +do_test shared-$av.10.11 { + db close + db3 close +} {} + +do_test shared-$av.11.1 { + forcedelete test.db + sqlite3 db test.db + sqlite3 db2 test.db + execsql { + CREATE TABLE abc(a, b, c); + CREATE TABLE abc2(a, b, c); + BEGIN; + INSERT INTO abc VALUES(1, 2, 3); + } +} {} +do_test shared-$av.11.2 { + catchsql {BEGIN;} db2 + catchsql {SELECT * FROM abc;} db2 +} {1 {database table is locked: abc}} +do_test shared-$av.11.3 { + catchsql {BEGIN} db2 +} {1 {cannot start a transaction within a transaction}} +do_test shared-$av.11.4 { + catchsql {SELECT * FROM abc2;} db2 +} {0 {}} +do_test shared-$av.11.5 { + catchsql {INSERT INTO abc2 VALUES(1, 2, 3);} db2 +} {1 {database table is locked}} +do_test shared-$av.11.6 { + catchsql {SELECT * FROM abc2} +} {0 {}} +do_test shared-$av.11.6 { + execsql { + ROLLBACK; + PRAGMA read_uncommitted = 1; + } db2 +} {} +do_test shared-$av.11.7 { + execsql { + INSERT INTO abc2 VALUES(4, 5, 6); + INSERT INTO abc2 VALUES(7, 8, 9); + } +} {} +do_test shared-$av.11.8 { + set res [list] + db2 eval { + SELECT abc.a as I, abc2.a as II FROM abc, abc2; + } { + execsql { + DELETE FROM abc WHERE 1; + } + lappend res $I $II + } + set res +} {1 4 {} 7} +if {[llength [info command sqlite3_shared_cache_report]]==1} { + ifcapable curdir { + do_test shared-$av.11.9 { + string tolower [sqlite3_shared_cache_report] + } [string tolower [list [file nativename [file normalize test.db]] 2]] + } +} + +do_test shared-$av.11.11 { + db close + db2 close +} {} + +# This tests that if it is impossible to free any pages, SQLite will +# exceed the limit set by PRAGMA cache_size. +forcedelete test.db test.db-journal +sqlite3 db test.db +ifcapable pager_pragmas { + do_test shared-$av.12.1 { + execsql { + PRAGMA cache_size = 10; + PRAGMA cache_size; + } + } {10} +} +do_test shared-$av.12.2 { + set ::db_handles [list] + for {set i 1} {$i < 15} {incr i} { + lappend ::db_handles db$i + sqlite3 db$i test.db + execsql "CREATE TABLE db${i}(a, b, c)" db$i + execsql "INSERT INTO db${i} VALUES(1, 2, 3)" + } +} {} +proc nested_select {handles} { + [lindex $handles 0] eval "SELECT * FROM [lindex $handles 0]" { + lappend ::res $a $b $c + if {[llength $handles]>1} { + nested_select [lrange $handles 1 end] + } + } +} +do_test shared-$av.12.3 { + set ::res [list] + nested_select $::db_handles + set ::res +} [string range [string repeat "1 2 3 " [llength $::db_handles]] 0 end-1] + +do_test shared-$av.12.X { + db close + foreach h $::db_handles { + $h close + } +} {} + +# Internally, locks are acquired on shared B-Tree structures in the order +# that the structures appear in the virtual memory address space. This +# test case attempts to cause the order of the structures in memory +# to be different from the order in which they are attached to a given +# database handle. This covers an extra line or two. +# +do_test shared-$av.13.1 { + forcedelete test2.db test3.db test4.db test5.db + sqlite3 db :memory: + execsql { + ATTACH 'test2.db' AS aux2; + ATTACH 'test3.db' AS aux3; + ATTACH 'test4.db' AS aux4; + ATTACH 'test5.db' AS aux5; + DETACH aux2; + DETACH aux3; + DETACH aux4; + ATTACH 'test2.db' AS aux2; + ATTACH 'test3.db' AS aux3; + ATTACH 'test4.db' AS aux4; + } +} {} +do_test shared-$av.13.2 { + execsql { + CREATE TABLE t1(a, b, c); + CREATE TABLE aux2.t2(a, b, c); + CREATE TABLE aux3.t3(a, b, c); + CREATE TABLE aux4.t4(a, b, c); + CREATE TABLE aux5.t5(a, b, c); + SELECT count(*) FROM + aux2.sqlite_master, + aux3.sqlite_master, + aux4.sqlite_master, + aux5.sqlite_master + } +} {1} +do_test shared-$av.13.3 { + db close +} {} + +# Test that nothing horrible happens if a connection to a shared B-Tree +# structure is closed while some other connection has an open cursor. +# +do_test shared-$av.14.1 { + sqlite3 db test.db + sqlite3 db2 test.db + execsql {SELECT name FROM sqlite_master} +} {db1 db2 db3 db4 db5 db6 db7 db8 db9 db10 db11 db12 db13 db14} +do_test shared-$av.14.2 { + set res [list] + db eval {SELECT name FROM sqlite_master} { + if {$name eq "db7"} { + db2 close + } + lappend res $name + } + set res +} {db1 db2 db3 db4 db5 db6 db7 db8 db9 db10 db11 db12 db13 db14} +do_test shared-$av.14.3 { + db close +} {} + +# Populate a database schema using connection [db]. Then drop it using +# [db2]. This is to try to find any points where shared-schema elements +# are allocated using the lookaside buffer of [db]. +# +# Mutexes are enabled for this test as that activates a couple of useful +# assert() statements in the C code. +# +do_test shared-$av-15.1 { + forcedelete test.db + sqlite3 db test.db -fullmutex 1 + sqlite3 db2 test.db -fullmutex 1 + execsql { + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(a, b); + CREATE VIEW v1 AS SELECT * FROM t1; + CREATE VIEW v2 AS SELECT * FROM t1, v1 + WHERE t1.c=v1.c GROUP BY t1.a ORDER BY v1.b; + CREATE TRIGGER tr1 AFTER INSERT ON t1 + WHEN new.a!=1 + BEGIN + DELETE FROM t1 WHERE a=5; + INSERT INTO t1 VALUES(1, 2, 3); + UPDATE t1 SET c=c+1; + END; + + INSERT INTO t1 VALUES(5, 6, 7); + INSERT INTO t1 VALUES(8, 9, 10); + INSERT INTO t1 VALUES(11, 12, 13); + ANALYZE; + SELECT * FROM t1; + } +} {1 2 6 8 9 12 1 2 5 11 12 14 1 2 4} +do_test shared-$av-15.2 { + execsql { DROP TABLE t1 } db2 +} {} +db close +db2 close + +# Shared cache on a :memory: database. This only works for URI filenames. +# +do_test shared-$av-16.1 { + sqlite3 db1 file::memory: -uri 1 + sqlite3 db2 file::memory: -uri 1 + db1 eval { + CREATE TABLE t1(x); INSERT INTO t1 VALUES(1),(2),(3); + } + db2 eval { + SELECT x FROM t1 ORDER BY x; + } +} {1 2 3} +do_test shared-$av-16.2 { + db2 eval { + INSERT INTO t1 VALUES(99); + DELETE FROM t1 WHERE x=2; + } + db1 eval { + SELECT x FROM t1 ORDER BY x; + } +} {1 3 99} + +# Verify that there is no cache sharing ordinary (non-URI) filenames are +# used. +# +do_test shared-$av-16.3 { + db1 close + db2 close + sqlite3 db1 :memory: + sqlite3 db2 :memory: + db1 eval { + CREATE TABLE t1(x); INSERT INTO t1 VALUES(4),(5),(6); + } + catchsql { + SELECT * FROM t1; + } db2 +} {1 {no such table: t1}} + +# Shared cache on named memory databases. +# +do_test shared-$av-16.4 { + db1 close + db2 close + forcedelete test.db test.db-wal test.db-journal + sqlite3 db1 file:test.db?mode=memory -uri 1 + sqlite3 db2 file:test.db?mode=memory -uri 1 + db1 eval { + CREATE TABLE t1(x); INSERT INTO t1 VALUES(1),(2),(3); + } + db2 eval { + SELECT x FROM t1 ORDER BY x; + } +} {1 2 3} +do_test shared-$av-16.5 { + db2 eval { + INSERT INTO t1 VALUES(99); + DELETE FROM t1 WHERE x=2; + } + db1 eval { + SELECT x FROM t1 ORDER BY x; + } +} {1 3 99} +do_test shared-$av-16.6 { + file exists test.db +} {0} ;# Verify that the database is in-memory + +# Shared cache on named memory databases with different names. +# +do_test shared-$av-16.7 { + db1 close + db2 close + forcedelete test1.db test2.db + sqlite3 db1 file:test1.db?mode=memory -uri 1 + sqlite3 db2 file:test2.db?mode=memory -uri 1 + db1 eval { + CREATE TABLE t1(x); INSERT INTO t1 VALUES(1),(2),(3); + } + catchsql { + SELECT x FROM t1 ORDER BY x; + } db2 +} {1 {no such table: t1}} +do_test shared-$av-16.8 { + file exists test1.db +} {0} ;# Verify that the database is in-memory + +# Shared cache on named memory databases attached to readonly connections. +# +do_test shared-$av-16.8.1 { + db1 close + db2 close + + sqlite3 db test1.db + db eval { + CREATE TABLE yy(a, b); + INSERT INTO yy VALUES(77, 88); + } + db close + + sqlite3 db1 test1.db -uri 1 -readonly 1 + sqlite3 db2 test2.db -uri 1 + + db1 eval { + ATTACH 'file:mem?mode=memory&cache=shared' AS shared; + CREATE TABLE shared.xx(a, b); + INSERT INTO xx VALUES(55, 66); + } + db2 eval { + ATTACH 'file:mem?mode=memory&cache=shared' AS shared; + SELECT * FROM xx; + } +} {55 66} + +do_test shared-$av-16.8.2 { db1 eval { SELECT * FROM yy } } {77 88} +do_test shared-$av-16.8.3 { + list [catch {db1 eval { INSERT INTO yy VALUES(1, 2) }} msg] $msg +} {1 {attempt to write a readonly database}} + +db1 close +db2 close + +} ;# end of autovacuum on/off loop + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/shared2.test b/components/external/SQLite-3.8.1/test/shared2.test new file mode 100644 index 0000000000000000000000000000000000000000..5bde8cfad84371b5a1c6346e93844b1ddce55650 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shared2.test @@ -0,0 +1,139 @@ +# 2005 January 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: shared2.test,v 1.8 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl +db close + +ifcapable !shared_cache { + finish_test + return +} +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +# Test that if we delete all rows from a table any read-uncommitted +# cursors are correctly invalidated. Test on both table and index btrees. +do_test shared2-1.1 { + sqlite3 db1 test.db + sqlite3 db2 test.db + + # Set up some data. Table "numbers" has 64 rows after this block + # is executed. + execsql { + BEGIN; + CREATE TABLE numbers(a PRIMARY KEY, b); + INSERT INTO numbers(oid) VALUES(NULL); + INSERT INTO numbers(oid) SELECT NULL FROM numbers; + INSERT INTO numbers(oid) SELECT NULL FROM numbers; + INSERT INTO numbers(oid) SELECT NULL FROM numbers; + INSERT INTO numbers(oid) SELECT NULL FROM numbers; + INSERT INTO numbers(oid) SELECT NULL FROM numbers; + INSERT INTO numbers(oid) SELECT NULL FROM numbers; + UPDATE numbers set a = oid, b = 'abcdefghijklmnopqrstuvwxyz0123456789'; + COMMIT; + } db1 +} {} +do_test shared2-1.2 { + # Put connection 2 in read-uncommitted mode and start a SELECT on table + # 'numbers'. Half way through the SELECT, use connection 1 to delete the + # contents of this table. + execsql { + pragma read_uncommitted = 1; + } db2 + set count [execsql {SELECT count(*) FROM numbers} db2] + db2 eval {SELECT a FROM numbers ORDER BY oid} { + if {$a==32} { + execsql { + BEGIN; + DELETE FROM numbers; + } db1 + } + } + list $a $count +} {32 64} +do_test shared2-1.3 { + # Same test as 1.2, except scan using the index this time. + execsql { + ROLLBACK; + } db1 + set count [execsql {SELECT count(*) FROM numbers} db2] + db2 eval {SELECT a, b FROM numbers ORDER BY a} { + if {$a==32} { + execsql { + DELETE FROM numbers; + } db1 + } + } + list $a $count +} {32 64} + + +db1 close +db2 close + +do_test shared2-3.2 { + sqlite3_enable_shared_cache 1 +} {1} + +forcedelete test.db + +sqlite3 db test.db +do_test shared2-4.1 { + execsql { + CREATE TABLE t0(a, b); + CREATE TABLE t1(a, b DEFAULT 'hello world'); + } +} {} +db close + +sqlite3 db test.db +sqlite3 db2 test.db + +do_test shared2-4.2 { + execsql { SELECT a, b FROM t0 } db + execsql { INSERT INTO t1(a) VALUES(1) } db2 +} {} + +do_test shared2-4.3 { + db2 close + db close +} {} + +# At one point, this was causing a crash. +# +do_test shared2-5.1 { + sqlite3 db test.db + sqlite3 db2 test.db + execsql { CREATE TABLE t2(a, b, c) } + + # The following statement would crash when attempting to sqlite3_free() + # a pointer allocated from a lookaside buffer. + execsql { CREATE INDEX i1 ON t2(a) } db2 +} {} + +db close +db2 close + +# The following test verifies that shared-cache mode does not automatically +# turn on exclusive-locking mode for some reason. +do_multiclient_test {tn} { + sql1 { CREATE TABLE t1(a, b) } + sql2 { CREATE TABLE t2(a, b) } + do_test shared2-6.$tn.1 { sql1 { SELECT * FROM t2 } } {} + do_test shared2-6.$tn.2 { sql2 { SELECT * FROM t1 } } {} +} + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/shared3.test b/components/external/SQLite-3.8.1/test/shared3.test new file mode 100644 index 0000000000000000000000000000000000000000..acc86d2a07c1f846798a9b067549cad1c8bd3ea3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shared3.test @@ -0,0 +1,142 @@ +# 2005 January 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: shared3.test,v 1.4 2008/08/20 14:49:25 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix shared3 +db close + +ifcapable !shared_cache { + finish_test + return +} +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +# Ticket #1824 +# +do_test shared3-1.1 { + forcedelete test.db test.db-journal + sqlite3 db1 test.db + db1 eval { + PRAGMA encoding=UTF16; + CREATE TABLE t1(x,y); + INSERT INTO t1 VALUES('abc','This is a test string'); + } + db1 close + sqlite3 db1 test.db + db1 eval {SELECT * FROM t1} +} {abc {This is a test string}} +do_test shared3-1.2 { + sqlite3 db2 test.db + db2 eval {SELECT y FROM t1 WHERE x='abc'} +} {{This is a test string}} + +db1 close +db2 close + +do_test shared3-2.1 { + sqlite3 db1 test.db + execsql { + PRAGMA main.cache_size = 10; + } db1 +} {} +do_test shared3-2.2 { + execsql { PRAGMA main.cache_size } db1 +} {10} +do_test shared3-2.3 { + sqlite3 db2 test.db + execsql { PRAGMA main.cache_size } db1 +} {10} +do_test shared3-2.4 { + execsql { PRAGMA main.cache_size } db2 +} {10} +do_test shared3-2.5 { + execsql { PRAGMA main.cache_size } db1 +} {10} + +# The cache-size should now be 10 pages. However at one point there was +# a bug that caused the cache size to return to the default value when +# a second connection was opened on the shared-cache (as happened in +# test case shared3-2.3 above). The goal of the following tests is to +# ensure that the cache-size really is 10 pages. +# +if {$::tcl_platform(platform)=="unix"} { + set alternative_name ./test.db +} else { + set alternative_name TEST.DB +} +do_test shared3-2.6 { + sqlite3 db3 $alternative_name + catchsql {select count(*) from sqlite_master} db3 +} {0 1} +do_test shared3-2.7 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(10, randomblob(5000)) + } db1 + catchsql {select count(*) from sqlite_master} db3 +} {0 1} +do_test shared3-2.8 { + db3 close + execsql { + INSERT INTO t1 VALUES(10, randomblob(10000)) + } db1 + + # If the pager-cache is really still limited to 10 pages, then the INSERT + # statement above should have caused the pager to grab an exclusive lock + # on the database file so that the cache could be spilled. + # + catch { sqlite3 db3 $alternative_name } + catchsql {select count(*) from sqlite_master} db3 +} {1 {database is locked}} + +db1 close +db2 close +db3 close + +#------------------------------------------------------------------------- +# At one point this was causing a faulty assert to fail. +# +forcedelete test.db +sqlite3 db test.db +sqlite3 db2 test.db +do_execsql_test 3.1 { + PRAGMA auto_vacuum = 2; + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(randomblob(500), randomblob(500)); + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; +} +do_test 3.2 { + execsql { SELECT count(*) FROM sqlite_master } db2 +} {1} +do_execsql_test 3.3 { + BEGIN; + DELETE FROM t1 WHERE 1; + PRAGMA incremental_vacuum; +} {} +do_test 3.4 { + execsql { SELECT count(*) FROM sqlite_master } db2 +} {1} +do_test 3.5 { + execsql { COMMIT } +} {} + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test + diff --git a/components/external/SQLite-3.8.1/test/shared4.test b/components/external/SQLite-3.8.1/test/shared4.test new file mode 100644 index 0000000000000000000000000000000000000000..83925b06e4cbf79a1d5365cb0ddffad7f629c543 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shared4.test @@ -0,0 +1,237 @@ +# 2008 July 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test the btree mutex protocol for shared cache mode. +# +# $Id: shared4.test,v 1.2 2008/08/04 03:51:24 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +db close +puts hello + +# This script is only valid if we are running shared-cache mode in a +# threadsafe-capable database engine. +# +ifcapable !shared_cache||!compound { + finish_test + return +} +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +# Prepare multiple databases in shared cache mode. +# +do_test shared4-1.1 { + forcedelete test1.db test1.db-journal + forcedelete test2.db test2.db-journal + forcedelete test3.db test3.db-journal + forcedelete test4.db test4.db-journal + sqlite3 db1 test1.db + sqlite3 db2 test2.db + sqlite3 db3 test3.db + sqlite3 db4 test4.db + db1 eval { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(111); + } + db2 eval { + CREATE TABLE t2(b); + INSERT INTO t2 VALUES(222); + } + db3 eval { + CREATE TABLE t3(c); + INSERT INTO t3 VALUES(333); + } + db4 eval { + CREATE TABLE t4(d); + INSERT INTO t4 VALUES(444); + } + db1 eval { + ATTACH DATABASE 'test2.db' AS two; + ATTACH DATABASE 'test3.db' AS three; + ATTACH DATABASE 'test4.db' AS four; + } + db2 eval { + ATTACH DATABASE 'test4.db' AS four; + ATTACH DATABASE 'test3.db' AS three; + ATTACH DATABASE 'test1.db' AS one; + } + db3 eval { + ATTACH DATABASE 'test1.db' AS one; + ATTACH DATABASE 'test2.db' AS two; + ATTACH DATABASE 'test4.db' AS four; + } + db4 eval { + ATTACH DATABASE 'test3.db' AS three; + ATTACH DATABASE 'test2.db' AS two; + ATTACH DATABASE 'test1.db' AS one; + } + db1 eval { + SELECT a FROM t1 UNION ALL + SELECT b FROM t2 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT d FROM t4; + } +} {111 222 333 444} +do_test shared4-1.2 { + db2 eval { + SELECT a FROM t1 UNION ALL + SELECT b FROM t2 UNION ALL + SELECT d FROM t4 UNION ALL + SELECT c FROM t3; + } +} {111 222 444 333} +do_test shared4-1.3 { + db3 eval { + SELECT a FROM t1 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT b FROM t2 UNION ALL + SELECT d FROM t4; + } +} {111 333 222 444} +do_test shared4-1.4 { + db4 eval { + SELECT a FROM t1 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT d FROM t4 UNION ALL + SELECT b FROM t2; + } +} {111 333 444 222} +do_test shared4-1.5 { + db3 eval { + SELECT a FROM t1 UNION ALL + SELECT d FROM t4 UNION ALL + SELECT b FROM t2 UNION ALL + SELECT c FROM t3; + } +} {111 444 222 333} +do_test shared4-1.6 { + db4 eval { + SELECT a FROM t1 UNION ALL + SELECT d FROM t4 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT b FROM t2; + } +} {111 444 333 222} +do_test shared4-1.7 { + db1 eval { + SELECT b FROM t2 UNION ALL + SELECT a FROM t1 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT d FROM t4; + } +} {222 111 333 444} +do_test shared4-1.8 { + db2 eval { + SELECT b FROM t2 UNION ALL + SELECT a FROM t1 UNION ALL + SELECT d FROM t4 UNION ALL + SELECT c FROM t3; + } +} {222 111 444 333} +do_test shared4-1.9 { + db3 eval { + SELECT b FROM t2 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT a FROM t1 UNION ALL + SELECT d FROM t4; + } +} {222 333 111 444} +do_test shared4-1.10 { + db4 eval { + SELECT b FROM t2 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT d FROM t4 UNION ALL + SELECT a FROM t1; + } +} {222 333 444 111} +do_test shared4-1.11 { + db1 eval { + SELECT c FROM t3 UNION ALL + SELECT a FROM t1 UNION ALL + SELECT b FROM t2 UNION ALL + SELECT d FROM t4; + } +} {333 111 222 444} +do_test shared4-1.12 { + db2 eval { + SELECT c FROM t3 UNION ALL + SELECT a FROM t1 UNION ALL + SELECT d FROM t4 UNION ALL + SELECT b FROM t2; + } +} {333 111 444 222} + +do_test shared4-2.1 { + db1 eval { + UPDATE t1 SET a=a+1000; + UPDATE t2 SET b=b+2000; + UPDATE t3 SET c=c+3000; + UPDATE t4 SET d=d+4000; + } + db2 eval { + UPDATE t1 SET a=a+10000; + UPDATE t2 SET b=b+20000; + UPDATE t3 SET c=c+30000; + UPDATE t4 SET d=d+40000; + } + db3 eval { + UPDATE t1 SET a=a+100000; + UPDATE t2 SET b=b+200000; + UPDATE t3 SET c=c+300000; + UPDATE t4 SET d=d+400000; + } + db4 eval { + UPDATE t1 SET a=a+1000000; + UPDATE t2 SET b=b+2000000; + UPDATE t3 SET c=c+3000000; + UPDATE t4 SET d=d+4000000; + } + db1 eval { + SELECT a FROM t1 UNION ALL + SELECT b FROM t2 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT d FROM t4; + } +} {1111111 2222222 3333333 4444444} +do_test shared4-2.2 { + db2 eval { + SELECT a FROM t1 UNION ALL + SELECT b FROM t2 UNION ALL + SELECT d FROM t4 UNION ALL + SELECT c FROM t3; + } +} {1111111 2222222 4444444 3333333} +do_test shared4-2.3 { + db3 eval { + SELECT a FROM t1 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT b FROM t2 UNION ALL + SELECT d FROM t4; + } +} {1111111 3333333 2222222 4444444} +do_test shared4-2.4 { + db4 eval { + SELECT a FROM t1 UNION ALL + SELECT c FROM t3 UNION ALL + SELECT d FROM t4 UNION ALL + SELECT b FROM t2; + } +} {1111111 3333333 4444444 2222222} + + +db1 close +db2 close +db3 close +db4 close + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/shared6.test b/components/external/SQLite-3.8.1/test/shared6.test new file mode 100644 index 0000000000000000000000000000000000000000..499cbb0eb572237136ccc18f9d090ea6a4b75931 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shared6.test @@ -0,0 +1,255 @@ +# 2009 April 01 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: shared6.test,v 1.4 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !shared_cache { finish_test ; return } + +do_test shared6-1.1.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); + CREATE TABLE t3(e, f); + } + db close +} {} +do_test shared6-1.1.2 { + set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + sqlite3_enable_shared_cache +} {1} + +do_test shared6-1.1.3 { + sqlite3 db1 test.db + sqlite3 db2 test.db +} {} + +# Exclusive shared-cache locks. Test the following: +# +# 1.2.1: If [db1] has an exclusive lock, [db2] cannot read. +# 1.2.2: If [db1] has an exclusive lock, [db1] can read. +# 1.2.3: If [db1] has a non-exclusive write-lock, [db2] can read. +# +do_test shared6-1.2.1 { + execsql { SELECT * FROM t1 } db2 ;# Cache a compiled statement + execsql { BEGIN EXCLUSIVE } db1 + catchsql { SELECT * FROM t1 } db2 ;# Execute the cached compiled statement +} {1 {database table is locked}} +do_test shared6-1.2.2 { + execsql { SELECT * FROM t1 } db1 +} {} +do_test shared6-1.2.3 { + execsql { + COMMIT; + BEGIN; + INSERT INTO t2 VALUES(3, 4); + } db1 + execsql { SELECT * FROM t1 } db2 +} {} +do_test shared6-1.2.X { + execsql { COMMIT } db1 +} {} + +# Regular shared-cache locks. Verify the following: +# +# 1.3.1: If [db1] has a write-lock on t1, [db1] can read from t1. +# 1.3.2: If [db1] has a write-lock on t1, [db2] can read from t2. +# 1.3.3: If [db1] has a write-lock on t1, [db2] cannot read from t1. +# 1.3.4: If [db1] has a write-lock on t1, [db2] cannot write to t1. +# 1.3.5: If [db1] has a read-lock on t1, [db2] can read from t1. +# 1.3.6: If [db1] has a read-lock on t1, [db2] cannot write to t1. +# +do_test shared6-1.3.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(1, 2); + } db1 + execsql { SELECT * FROM t1 } db1 +} {1 2} +do_test shared6-1.3.2 { + execsql { SELECT * FROM t2 } db2 +} {3 4} +do_test shared6-1.3.3 { + catchsql { SELECT * FROM t1 } db2 +} {1 {database table is locked: t1}} +do_test shared6-1.3.4 { + catchsql { INSERT INTO t2 VALUES(1, 2) } db2 +} {1 {database table is locked}} +do_test shared6-1.3.5 { + execsql { + COMMIT; + BEGIN; + SELECT * FROM t1; + } db1 + execsql { SELECT * FROM t1 } db2 +} {1 2} +do_test shared6-1.3.5 { + catchsql { INSERT INTO t1 VALUES(5, 6) } db2 +} {1 {database table is locked: t1}} +do_test shared6-1.3.X { + execsql { COMMIT } db1 +} {} + +# Read-uncommitted mode. +# +# For these tests, connection [db2] is in read-uncommitted mode. +# +# 1.4.1: If [db1] has a write-lock on t1, [db2] can still read from t1. +# 1.4.2: If [db1] has a write-lock on the db schema (sqlite_master table), +# [db2] cannot read from the schema. +# 1.4.3: If [db1] has a read-lock on t1, [db2] cannot write to t1. +# +do_test shared6-1.4.1 { + execsql { PRAGMA read_uncommitted = 1 } db2 + execsql { + BEGIN; + INSERT INTO t1 VALUES(5, 6); + } db1 + execsql { SELECT * FROM t1 } db2 +} {1 2 5 6} +do_test shared6-1.4.2 { + execsql { CREATE TABLE t4(a, b) } db1 + catchsql { SELECT * FROM t1 } db2 +} {1 {database table is locked}} +do_test shared6-1.4.3 { + execsql { + COMMIT; + BEGIN; + SELECT * FROM t1; + } db1 + catchsql { INSERT INTO t1 VALUES(7, 8) } db2 +} {1 {database table is locked: t1}} + +do_test shared6-1.X { + db1 close + db2 close +} {} + +#------------------------------------------------------------------------- +# The following tests - shared6-2.* - test that two database connections +# that connect to the same file using different VFS implementations do +# not share a cache. +# +if {$::tcl_platform(platform) eq "unix"} { + do_test shared6-2.1 { + sqlite3 db1 test.db -vfs unix + sqlite3 db2 test.db -vfs unix + sqlite3 db3 test.db -vfs unix-none + sqlite3 db4 test.db -vfs unix-none + } {} + + do_test shared6-2.2 { + execsql { BEGIN; INSERT INTO t1 VALUES(9, 10); } db1 + catchsql { SELECT * FROM t1 } db2 + } {1 {database table is locked: t1}} + do_test shared6-2.3 { + execsql { SELECT * FROM t1 } db3 + } {1 2 5 6} + + do_test shared6-2.3 { + execsql { COMMIT } db1 + execsql { BEGIN; INSERT INTO t1 VALUES(11, 12); } db3 + catchsql { SELECT * FROM t1 } db4 + } {1 {database table is locked: t1}} + + do_test shared6-2.4 { + execsql { SELECT * FROM t1 } db1 + } {1 2 5 6 9 10} + + do_test shared6-2.5 { + execsql { COMMIT } db3 + } {} + + do_test shared6-2.X { + db1 close + db2 close + db3 close + db4 close + } {} +} + +#------------------------------------------------------------------------- +# Test that it is possible to open an exclusive transaction while +# already holding a read-lock on the database file. And that it is +# not possible if some other connection holds such a lock. +# +do_test shared6-3.1 { + sqlite3 db1 test.db + sqlite3 db2 test.db + sqlite3 db3 test.db +} {} +db1 eval {SELECT * FROM t1} { + # Within this block [db1] is holding a read-lock on t1. Test that + # this means t1 cannot be written by [db2]. + # + do_test shared6-3.2 { + catchsql { INSERT INTO t1 VALUES(1, 2) } db2 + } {1 {database table is locked: t1}} + + do_test shared6-3.3 { + execsql { BEGIN EXCLUSIVE } db1 + } {} + break +} +do_test shared6-3.4 { + catchsql { SELECT * FROM t1 } db2 +} {1 {database schema is locked: main}} +do_test shared6-3.5 { + execsql COMMIT db1 +} {} +db2 eval {SELECT * FROM t1} { + do_test shared6-3.6 { + catchsql { BEGIN EXCLUSIVE } db1 + } {1 {database table is locked}} + break +} +do_test shared6-3.7 { + execsql { BEGIN } db1 + execsql { BEGIN } db2 +} {} +db2 eval {SELECT * FROM t1} { + do_test shared6-3.8 { + catchsql { INSERT INTO t1 VALUES(1, 2) } db1 + } {1 {database table is locked: t1}} + break +} +do_test shared6-3.9 { + execsql { BEGIN ; ROLLBACK } db3 +} {} +do_test shared6-3.10 { + catchsql { SELECT * FROM t1 } db3 +} {1 {database table is locked}} +do_test shared6-3.X { + db1 close + db2 close + db3 close +} {} + +do_test shared6-4.1 { + #forcedelete test.db test.db-journal + sqlite3 db1 test.db + sqlite3 db2 test.db + + set ::STMT [sqlite3_prepare_v2 db1 "SELECT * FROM t1" -1 DUMMY] + execsql { CREATE TABLE t5(a, b) } db2 +} {} +do_test shared6-4.2 { + sqlite3_finalize $::STMT +} {SQLITE_OK} +do_test shared6-4.X { + + db1 close + db2 close +} {} + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/shared7.test b/components/external/SQLite-3.8.1/test/shared7.test new file mode 100644 index 0000000000000000000000000000000000000000..9f4880f56e2a9a91b34fa2c5e2e46248c87f501d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shared7.test @@ -0,0 +1,58 @@ +# 2009 April 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Make sure that attaching the same database multiple times in +# shared cache mode fails. +# +# $Id: shared7.test,v 1.1 2009/04/30 13:30:33 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !shared_cache { finish_test ; return } + +do_test shared7-1.1 { + set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + sqlite3_enable_shared_cache +} {1} + +# EVIDENCE-OF: R-05098-06501 In shared cache mode, attempting to attach +# the same database file more than once results in an error. +# +do_test shared7-1.2 { + db close + sqlite3 db test.db + db eval { + CREATE TABLE t1(x); + } + catchsql { + ATTACH 'test.db' AS err1; + } +} {1 {database is already attached}} + +do_test shared7-1.3 { + forcedelete test2.db test2.db-journal + db eval { + ATTACH 'test2.db' AS test2; + CREATE TABLE test2.t2(y); + } + catchsql { + ATTACH 'test2.db' AS err2; + } +} {1 {database is already attached}} +do_test shared7-1.4 { + catchsql { + ATTACH 'test.db' AS err1; + } +} {1 {database is already attached}} + + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/shared8.test b/components/external/SQLite-3.8.1/test/shared8.test new file mode 100644 index 0000000000000000000000000000000000000000..73f0d476277ca5a0471b2dce5a7c2e9f5497a900 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shared8.test @@ -0,0 +1,112 @@ +# 2012 May 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The tests in this file are intended to show that closing one database +# connection to a shared-cache while there exist other connections (a) +# does not cause the schema to be reloaded and (b) does not cause any +# other problems. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !shared_cache { finish_test ; return } +set testprefix shared8 + +db close +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] +do_test 0.0 { sqlite3_enable_shared_cache } {1} + +proc roman {n} { + array set R {1 i 2 ii 3 iii 4 iv 5 v 6 vi 7 vii 8 viii 9 ix 10 x} + set R($n) +} + +#------------------------------------------------------------------------- +# The following tests work as follows: +# +# 1.0: Open connection [db1] and populate the database. +# +# 1.1: Using "PRAGMA writable_schema", destroy the database schema on +# disk. The schema is still in memory, so it is possible to keep +# using it, but any attempt to reload it from disk will fail. +# +# 1.3-4: Open connection db2. Check that it can see the db schema. Then +# close db1 and check that db2 still works. This shows that closing +# db1 did not reset the in-memory schema. +# +# 1.5-7: Similar to 1.3-4. +# +# 1.8: Close all database connections (deleting the in-memory schema). +# Then open a new connection and check that it cannot read the db. +# +do_test 1.0 { + sqlite3 db1 test.db + db1 func roman roman + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 1); + INSERT INTO t1 VALUES(2, 2); + INSERT INTO t1 VALUES(3, 3); + INSERT INTO t1 VALUES(4, 4); + CREATE VIEW v1 AS SELECT a, roman(b) FROM t1; + SELECT * FROM v1; + } db1 +} {1 i 2 ii 3 iii 4 iv} + +do_test 1.1 { + execsql { + PRAGMA writable_schema = 1; + DELETE FROM sqlite_master WHERE 1; + PRAGMA writable_schema = 0; + SELECT * FROM sqlite_master; + } db1 +} {} + +do_test 1.2 { + execsql { SELECT * FROM v1 } db1 +} {1 i 2 ii 3 iii 4 iv} + +do_test 1.3 { + sqlite3 db2 test.db + db2 func roman roman + execsql { SELECT * FROM v1 } db2 +} {1 i 2 ii 3 iii 4 iv} + +do_test 1.4 { + db1 close + execsql { SELECT * FROM v1 } db2 +} {1 i 2 ii 3 iii 4 iv} + +do_test 1.5 { + sqlite3 db3 test.db + db3 func roman roman + execsql { SELECT * FROM v1 } db3 +} {1 i 2 ii 3 iii 4 iv} + +do_test 1.6 { + execsql { SELECT * FROM v1 } db2 +} {1 i 2 ii 3 iii 4 iv} + +do_test 1.7 { + db2 close + execsql { SELECT * FROM v1 } db3 +} {1 i 2 ii 3 iii 4 iv} + +do_test 1.8 { + db3 close + sqlite3 db4 test.db + catchsql { SELECT * FROM v1 } db4 +} {1 {no such table: v1}} + + +foreach db {db1 db2 db3 db4} { catch { $db close } } +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/shared9.test b/components/external/SQLite-3.8.1/test/shared9.test new file mode 100644 index 0000000000000000000000000000000000000000..1982a593e34dbc8a85741aa3324229ab32d2f56f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shared9.test @@ -0,0 +1,230 @@ +# 2012 October 5 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The tests in this file are intended to show if two connections attach +# to the same shared cache using different database names, views and +# virtual tables may still be accessed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +set testprefix shared9 + +ifcapable !view||!trigger { + finish_test + return +} + +db close +set enable_shared_cache [sqlite3_enable_shared_cache 1] + +sqlite3 db1 test.db +sqlite3 db2 test.db +forcedelete test.db2 + +do_test 1.1 { + db1 eval { + ATTACH 'test.db2' AS 'fred'; + CREATE TABLE fred.t1(a, b, c); + CREATE VIEW fred.v1 AS SELECT * FROM t1; + + CREATE TABLE fred.t2(a, b); + CREATE TABLE fred.t3(a, b); + CREATE TRIGGER fred.trig AFTER INSERT ON t2 BEGIN + DELETE FROM t3; + INSERT INTO t3 SELECT * FROM t2; + END; + INSERT INTO t2 VALUES(1, 2); + SELECT * FROM t3; + } +} {1 2} + +do_test 1.2 { db2 eval "ATTACH 'test.db2' AS 'jones'" } {} +do_test 1.3 { db2 eval "SELECT * FROM v1" } {} +do_test 1.4 { db2 eval "INSERT INTO t2 VALUES(3, 4)" } {} + +ifcapable fts3 { + do_test 1.5 { + db1 eval { + CREATE VIRTUAL TABLE fred.t4 USING fts4; + INSERT INTO t4 VALUES('hello world'); + } + } {} + + do_test 1.6 { + db2 eval { + INSERT INTO t4 VALUES('shared cache'); + SELECT * FROM t4 WHERE t4 MATCH 'hello'; + } + } {{hello world}} + + do_test 1.7 { + db1 eval { + SELECT * FROM t4 WHERE t4 MATCH 'c*'; + } + } {{shared cache}} +} + +db1 close +db2 close + +#------------------------------------------------------------------------- +# The following tests attempt to find a similar problem with collation +# sequence names - pointers to database handle specific allocations leaking +# into schema objects and being used after the original handle has been +# closed. +# +forcedelete test.db test.db2 +sqlite3 db1 test.db +sqlite3 db2 test.db +foreach x {collate1 collate2 collate3} { + proc $x {a b} { string compare $a $b } + db1 collate $x $x + db2 collate $x $x +} +do_test 2.1 { + db1 eval { + CREATE TABLE t1(a, b, c COLLATE collate1); + CREATE INDEX i1 ON t1(a COLLATE collate2, c, b); + } +} {} +do_test 2.2 { + db1 close + db2 eval "INSERT INTO t1 VALUES('abc', 'def', 'ghi')" +} {} +db2 close + +#------------------------------------------------------------------------- +# At one point, the following would cause a collation sequence belonging +# to connection [db1] to be invoked by a call to [db2 eval]. Which is a +# problem if [db1] has already been closed. +# +forcedelete test.db test.db2 +sqlite3 db1 test.db +sqlite3 db2 test.db + +proc mycollate_db1 {a b} {set ::invoked_mycollate_db1 1 ; string compare $a $b} +proc mycollate_db2 {a b} {string compare $a $b} + +db1 collate mycollate mycollate_db1 +db2 collate mycollate mycollate_db2 + +do_test 2.3 { + set ::invoked_mycollate_db1 0 + db1 eval { + CREATE TABLE t1(a COLLATE mycollate, CHECK (a IN ('one', 'two', 'three'))); + INSERT INTO t1 VALUES('one'); + } + db1 close + set ::invoked_mycollate_db1 +} {1} +do_test 2.4 { + set ::invoked_mycollate_db1 0 + db2 eval { + INSERT INTO t1 VALUES('two'); + } + db2 close + set ::invoked_mycollate_db1 +} {0} + +forcedelete test.db test.db2 +sqlite3 db1 test.db +sqlite3 db2 test.db +db1 collate mycollate mycollate_db1 +db2 collate mycollate mycollate_db2 + +do_test 2.13 { + set ::invoked_mycollate_db1 0 + db1 eval { + CREATE TABLE t1(a, CHECK (a COLLATE mycollate IN ('one', 'two', 'three'))); + INSERT INTO t1 VALUES('one'); + } + db1 close + set ::invoked_mycollate_db1 +} {1} +do_test 2.14 { + set ::invoked_mycollate_db1 0 + db2 eval { + INSERT INTO t1 VALUES('two'); + } + db2 close + set ::invoked_mycollate_db1 +} {0} + +#------------------------------------------------------------------------- +# This test verifies that a bug causing a busy-handler belonging to one +# shared-cache connection to be executed as a result of an sqlite3_step() +# on another has been fixed. +# +forcedelete test.db test.db2 +sqlite3 db1 test.db +sqlite3 db2 test.db + +proc busyhandler {handle args} { + set ::busyhandler_invoked_for $handle + return 1 +} +db1 busy [list busyhandler db1] +db2 busy [list busyhandler db2] + +do_test 3.1 { + db1 eval { + BEGIN; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t2 VALUES(1, 2); + } + # Keep this next COMMIT as a separate statement. This ensures that COMMIT + # has already been compiled and loaded into the tcl interface statement + # cache when it is attempted below. + db1 eval COMMIT + db1 eval { + BEGIN; + INSERT INTO t1 VALUES(3, 4); + } +} {} + +do_test 3.2 { + set ::tf [launch_testfixture] + testfixture $::tf { + sqlite3 db test.db + db eval { + BEGIN; + SELECT * FROM t1; + } + } +} {1 2} + +do_test 3.3 { + db2 eval { SELECT * FROM t2 } +} {1 2} + +do_test 3.4 { + list [catch { db1 eval COMMIT } msg] $msg +} {1 {database is locked}} + +# At one point the following would fail, showing that the busy-handler +# belonging to [db2] was invoked instead. +do_test 3.5 { + set ::busyhandler_invoked_for +} {db1} +do_test 3.6 { + close $::tf + db1 eval COMMIT +} {} + +db1 close +db2 close + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/sharedA.test b/components/external/SQLite-3.8.1/test/sharedA.test new file mode 100644 index 0000000000000000000000000000000000000000..146fb26be0ed3e5aec5ab82ecc76ee6b4a243ca1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/sharedA.test @@ -0,0 +1,188 @@ +# 2013 May 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test some specific circumstances to do with shared cache mode. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +if {[run_thread_tests]==0} { finish_test ; return } +db close +set ::testprefix sharedA + +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +#------------------------------------------------------------------------- +# +do_test 0.1 { + sqlite3 db1 test.db + sqlite3 db2 test.db + + db1 eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 SELECT randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(100) FROM t1; + CREATE INDEX i1 ON t1(x); + } + + db1 eval { + BEGIN; + DROP INDEX i1; + } + + db2 close + + db1 eval { + INSERT INTO t1 SELECT randomblob(100) FROM t1; + ROLLBACK; + PRAGMA integrity_check; + } +} {ok} + +db1 close +forcedelete test.db + + +#------------------------------------------------------------------------- +# +do_test 1.1 { + sqlite3 db1 test.db + sqlite3 db2 test.db + db2 eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(123); + } + db1 eval { + SELECT * FROM t1; + CREATE INDEX i1 ON t1(x); + } +} {123} + +do_test 1.2 { + db2 eval { SELECT * FROM t1 ORDER BY x; } + + db1 eval { + BEGIN; DROP INDEX i1; + } + db1 close + + db2 eval { SELECT * FROM t1 ORDER BY x; } +} {123} + +do_test 1.3 { + db2 close +} {} + +#------------------------------------------------------------------------- +# +# sqlite3RollbackAll() loops through all attached b-trees and rolls +# back each one separately. Then if the SQLITE_InternChanges flag is +# set, it resets the schema. Both of the above steps must be done +# while holding a mutex, otherwise another thread might slip in and +# try to use the new schema with the old data. +# +# The following sequence of tests attempt to verify that the actions +# taken by sqlite3RollbackAll() are thread-atomic (that they cannot be +# interrupted by a separate thread.) +# +# Note that a TCL interpreter can only be used within the thread in which +# it was originally created (because it uses thread-local-storage). +# The tvfs callbacks must therefore only run on the main thread. +# There is some trickery in the read_callback procedure to ensure that +# this is the case. +# +testvfs tvfs + +# Set up two databases and two database connections. +# +# db1: main(test.db), two(test2.db) +# db2: main(test.db) +# +# The cache for test.db is shared between db1 and db2. +# +do_test 2.1 { + forcedelete test.db test.db2 + sqlite3 db1 test.db -vfs tvfs + db1 eval { ATTACH 'test.db2' AS two } + + db1 eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + CREATE TABLE two.t2(x); + INSERT INTO t2 SELECT * FROM t1; + } + + sqlite3 db2 test.db -vfs tvfs + db2 eval { SELECT * FROM t1 } +} {1 2 3} + +# Create a prepared statement on db2 that will attempt a schema change +# in test.db. Meanwhile, start a transaction on db1 that changes +# the schema of test.db and that creates a rollback journal on test2.db +# +do_test 2.2 { + set ::STMT [sqlite3_prepare db2 "CREATE INDEX i1 ON t1(x)" -1 tail] + db1 eval { + BEGIN; + CREATE INDEX i1 ON t1(x); + INSERT INTO t2 VALUES('value!'); + } +} {} + +# Set up a callback that will cause db2 to try to execute its +# schema change when db1 accesses the journal file of test2.db. +# +# This callback will be invoked after the content of test.db has +# be rolled back but before the schema has been reset. If the +# sqlite3RollbackAll() operation is not thread-atomic, then the +# db2 statement in the callback will see old content with the newer +# schema, which is wrong. +# +tvfs filter xRead +tvfs script read_callback +unset -nocomplain ::some_time_laster +unset -nocomplain ::thread_result +proc read_callback {call file args} { + if {[string match *test.db2-journal $file]} { + tvfs filter {} ;# Ensure that tvfs callbacks to do run on the + # child thread + sqlthread spawn ::thread_result [subst -nocommands { + sqlite3_step $::STMT + set rc [sqlite3_finalize $::STMT] + }] + after 1000 { set ::some_time_later 1 } + vwait ::some_time_later + } +} +do_test 2.3 { db1 eval ROLLBACK } {} + +# Verify that the db2 statement invoked by the callback detected the +# schema change. +# +if {[info exists ::thread_result]==0} { vwait ::thread_result } +do_test 2.4 { + list $::thread_result [sqlite3_errmsg db2] +} {SQLITE_SCHEMA {database schema has changed}} + +db1 close +db2 close +tvfs delete + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/shared_err.test b/components/external/SQLite-3.8.1/test/shared_err.test new file mode 100644 index 0000000000000000000000000000000000000000..17add94bb7ee44b63d1418911216beec081496c5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shared_err.test @@ -0,0 +1,522 @@ +# 2005 December 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of the tests in this file are IO errors that occur in a shared +# cache context. What happens to connection B if one connection A encounters +# an IO-error whilst reading or writing the file-system? +# +# $Id: shared_err.test,v 1.24 2008/10/12 00:27:54 shane Exp $ + +proc skip {args} {} + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +db close + +ifcapable !shared_cache||!subquery { + finish_test + return +} + +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +do_ioerr_test shared_ioerr-1 -tclprep { + sqlite3 db2 test.db + execsql { + PRAGMA read_uncommitted = 1; + CREATE TABLE t1(a,b,c); + BEGIN; + SELECT * FROM sqlite_master; + } db2 +} -sqlbody { + SELECT * FROM sqlite_master; + INSERT INTO t1 VALUES(1,2,3); + BEGIN TRANSACTION; + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(4,5,6); + ROLLBACK; + SELECT * FROM t1; + BEGIN TRANSACTION; + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(4,5,6); + COMMIT; + SELECT * FROM t1; + DELETE FROM t1 WHERE a<100; +} -cleanup { + do_test shared_ioerr-1.$n.cleanup.1 { + set res [catchsql { + SELECT * FROM t1; + } db2] + set possible_results [list \ + "1 {disk I/O error}" \ + "0 {1 2 3}" \ + "0 {1 2 3 1 2 3 4 5 6}" \ + "0 {1 2 3 1 2 3 4 5 6 1 2 3 4 5 6}" \ + "0 {}" \ + "1 {database disk image is malformed}" \ + ] + set rc [expr [lsearch -exact $possible_results $res] >= 0] + if {$rc != 1} { + puts "" + puts "Result: $res" + } + set rc + } {1} + + # The "database disk image is malformed" is a special case that can + # occur if an IO error occurs during a rollback in the {SELECT * FROM t1} + # statement above. This test is to make sure there is no real database + # corruption. + db2 close + do_test shared_ioerr-1.$n.cleanup.2 { + execsql {pragma integrity_check} db + } {ok} +} + +do_ioerr_test shared_ioerr-2 -tclprep { + sqlite3 db2 test.db + execsql { + PRAGMA read_uncommitted = 1; + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1(oid) VALUES(NULL); + INSERT INTO t1(oid) SELECT NULL FROM t1; + INSERT INTO t1(oid) SELECT NULL FROM t1; + INSERT INTO t1(oid) SELECT NULL FROM t1; + INSERT INTO t1(oid) SELECT NULL FROM t1; + INSERT INTO t1(oid) SELECT NULL FROM t1; + INSERT INTO t1(oid) SELECT NULL FROM t1; + INSERT INTO t1(oid) SELECT NULL FROM t1; + INSERT INTO t1(oid) SELECT NULL FROM t1; + INSERT INTO t1(oid) SELECT NULL FROM t1; + INSERT INTO t1(oid) SELECT NULL FROM t1; + UPDATE t1 set a = oid, b = 'abcdefghijklmnopqrstuvwxyz0123456789'; + CREATE INDEX i1 ON t1(a); + COMMIT; + BEGIN; + SELECT * FROM sqlite_master; + } db2 +} -tclbody { + set ::residx 0 + execsql {DELETE FROM t1 WHERE 0 = (a % 2);} + incr ::residx + + # When this transaction begins the table contains 512 entries. The + # two statements together add 512+146 more if it succeeds. + # (1024/7==146) + execsql {BEGIN;} + execsql {INSERT INTO t1 SELECT a+1, b FROM t1;} + execsql {INSERT INTO t1 SELECT 'string' || a, b FROM t1 WHERE 0 = (a%7);} + execsql {COMMIT;} + + incr ::residx +} -cleanup { + catchsql ROLLBACK + do_test shared_ioerr-2.$n.cleanup.1 { + set res [catchsql { + SELECT max(a), min(a), count(*) FROM (SELECT a FROM t1 order by a); + } db2] + set possible_results [list \ + {0 {1024 1 1024}} \ + {0 {1023 1 512}} \ + {0 {string994 1 1170}} \ + ] + set idx [lsearch -exact $possible_results $res] + set success [expr {$idx==$::residx || $res=="1 {disk I/O error}"}] + if {!$success} { + puts "" + puts "Result: \"$res\" ($::residx)" + } + set success + } {1} + db2 close +} + +# This test is designed to provoke an IO error when a cursor position is +# "saved" (because another cursor is going to modify the underlying table). +# +do_ioerr_test shared_ioerr-3 -tclprep { + sqlite3 db2 test.db + execsql { + PRAGMA read_uncommitted = 1; + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE t1(a, b, UNIQUE(a, b)); + } db2 + for {set i 0} {$i < 200} {incr i} { + set a [string range [string repeat "[format %03d $i]." 5] 0 end-1] + + set b [string repeat $i 2000] + execsql {INSERT INTO t1 VALUES($a, $b)} db2 + } + execsql {COMMIT} db2 + set ::DB2 [sqlite3_connection_pointer db2] + set ::STMT [sqlite3_prepare $::DB2 "SELECT a FROM t1 ORDER BY a" -1 DUMMY] + sqlite3_step $::STMT ;# Cursor points at 000.000.000.000 + sqlite3_step $::STMT ;# Cursor points at 001.001.001.001 + +} -tclbody { + execsql { + BEGIN; + INSERT INTO t1 VALUES('201.201.201.201.201', NULL); + UPDATE t1 SET a = '202.202.202.202.202' WHERE a LIKE '201%'; + COMMIT; + } +} -cleanup { + set ::steprc [sqlite3_step $::STMT] + set ::column [sqlite3_column_text $::STMT 0] + set ::finalrc [sqlite3_finalize $::STMT] + + # There are three possible outcomes here (assuming persistent IO errors): + # + # 1. If the [sqlite3_step] did not require any IO (required pages in + # the cache), then the next row ("002...") may be retrieved + # successfully. + # + # 2. If the [sqlite3_step] does require IO, then [sqlite3_step] returns + # SQLITE_ERROR and [sqlite3_finalize] returns IOERR. + # + # 3. If, after the initial IO error, SQLite tried to rollback the + # active transaction and a second IO error was encountered, then + # statement $::STMT will have been aborted. This means [sqlite3_stmt] + # returns SQLITE_ABORT, and the statement cursor does not move. i.e. + # [sqlite3_column] still returns the current row ("001...") and + # [sqlite3_finalize] returns SQLITE_OK. + # + + do_test shared_ioerr-3.$n.cleanup.1 { + expr { + $::steprc eq "SQLITE_ROW" || + $::steprc eq "SQLITE_ERROR" || + $::steprc eq "SQLITE_ABORT" + } + } {1} + do_test shared_ioerr-3.$n.cleanup.2 { + expr { + ($::steprc eq "SQLITE_ROW" && $::column eq "002.002.002.002.002") || + ($::steprc eq "SQLITE_ERROR" && $::column eq "") || + ($::steprc eq "SQLITE_ABORT" && $::column eq "001.001.001.001.001") + } + } {1} + do_test shared_ioerr-3.$n.cleanup.3 { + expr { + ($::steprc eq "SQLITE_ROW" && $::finalrc eq "SQLITE_OK") || + ($::steprc eq "SQLITE_ERROR" && $::finalrc eq "SQLITE_IOERR") || + ($::steprc eq "SQLITE_ERROR" && $::finalrc eq "SQLITE_ABORT") + } + } {1} + +# db2 eval {select * from sqlite_master} + db2 close +} + +# This is a repeat of the previous test except that this time we +# are doing a reverse-order scan of the table when the cursor is +# "saved". +# +do_ioerr_test shared_ioerr-3rev -tclprep { + sqlite3 db2 test.db + execsql { + PRAGMA read_uncommitted = 1; + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE t1(a, b, UNIQUE(a, b)); + } db2 + for {set i 0} {$i < 200} {incr i} { + set a [string range [string repeat "[format %03d $i]." 5] 0 end-1] + + set b [string repeat $i 2000] + execsql {INSERT INTO t1 VALUES($a, $b)} db2 + } + execsql {COMMIT} db2 + set ::DB2 [sqlite3_connection_pointer db2] + set ::STMT [sqlite3_prepare $::DB2 \ + "SELECT a FROM t1 ORDER BY a DESC" -1 DUMMY] + sqlite3_step $::STMT ;# Cursor points at 199.199.199.199.199 + sqlite3_step $::STMT ;# Cursor points at 198.198.198.198.198 + +} -tclbody { + execsql { + BEGIN; + INSERT INTO t1 VALUES('201.201.201.201.201', NULL); + UPDATE t1 SET a = '202.202.202.202.202' WHERE a LIKE '201%'; + COMMIT; + } +} -cleanup { + set ::steprc [sqlite3_step $::STMT] + set ::column [sqlite3_column_text $::STMT 0] + set ::finalrc [sqlite3_finalize $::STMT] + + # There are three possible outcomes here (assuming persistent IO errors): + # + # 1. If the [sqlite3_step] did not require any IO (required pages in + # the cache), then the next row ("002...") may be retrieved + # successfully. + # + # 2. If the [sqlite3_step] does require IO, then [sqlite3_step] returns + # SQLITE_ERROR and [sqlite3_finalize] returns IOERR. + # + # 3. If, after the initial IO error, SQLite tried to rollback the + # active transaction and a second IO error was encountered, then + # statement $::STMT will have been aborted. This means [sqlite3_stmt] + # returns SQLITE_ABORT, and the statement cursor does not move. i.e. + # [sqlite3_column] still returns the current row ("001...") and + # [sqlite3_finalize] returns SQLITE_OK. + # + + do_test shared_ioerr-3rev.$n.cleanup.1 { + expr { + $::steprc eq "SQLITE_ROW" || + $::steprc eq "SQLITE_ERROR" || + $::steprc eq "SQLITE_ABORT" + } + } {1} + do_test shared_ioerr-3rev.$n.cleanup.2 { + expr { + ($::steprc eq "SQLITE_ROW" && $::column eq "197.197.197.197.197") || + ($::steprc eq "SQLITE_ERROR" && $::column eq "") || + ($::steprc eq "SQLITE_ABORT" && $::column eq "198.198.198.198.198") + } + } {1} + do_test shared_ioerr-3rev.$n.cleanup.3 { + expr { + ($::steprc eq "SQLITE_ROW" && $::finalrc eq "SQLITE_OK") || + ($::steprc eq "SQLITE_ERROR" && $::finalrc eq "SQLITE_IOERR") || + ($::steprc eq "SQLITE_ERROR" && $::finalrc eq "SQLITE_ABORT") + } + } {1} + +# db2 eval {select * from sqlite_master} + db2 close +} + +# Provoke a malloc() failure when a cursor position is being saved. This +# only happens with index cursors (because they malloc() space to save the +# current key value). It does not happen with tables, because an integer +# key does not require a malloc() to store. +# +# The library should return an SQLITE_NOMEM to the caller. The query that +# owns the cursor (the one for which the position is not saved) should +# continue unaffected. +# +do_malloc_test shared_err-4 -tclprep { + sqlite3 db2 test.db + execsql { + PRAGMA read_uncommitted = 1; + BEGIN; + CREATE TABLE t1(a, b, UNIQUE(a, b)); + } db2 + for {set i 0} {$i < 5} {incr i} { + set a [string repeat $i 10] + set b [string repeat $i 2000] + execsql {INSERT INTO t1 VALUES($a, $b)} db2 + } + execsql {COMMIT} db2 + set ::DB2 [sqlite3_connection_pointer db2] + set ::STMT [sqlite3_prepare $::DB2 "SELECT a FROM t1 ORDER BY a" -1 DUMMY] + sqlite3_step $::STMT ;# Cursor points at 0000000000 + sqlite3_step $::STMT ;# Cursor points at 1111111111 +} -tclbody { + execsql { + INSERT INTO t1 VALUES(6, NULL); + } +} -cleanup { + do_test shared_malloc-4.$::n.cleanup.1 { + set ::rc [sqlite3_step $::STMT] + expr {$::rc=="SQLITE_ROW" || $::rc=="SQLITE_ERROR"} + } {1} + if {$::rc=="SQLITE_ROW"} { + do_test shared_malloc-4.$::n.cleanup.2 { + sqlite3_column_text $::STMT 0 + } {2222222222} + } + do_test shared_malloc-4.$::n.cleanup.3 { + set rc [sqlite3_finalize $::STMT] + expr {$rc=="SQLITE_OK" || $rc=="SQLITE_ABORT" || + $rc=="SQLITE_NOMEM" || $rc=="SQLITE_IOERR"} + } {1} +# db2 eval {select * from sqlite_master} + db2 close +} + +do_malloc_test shared_err-5 -tclbody { + db close + sqlite3 dbX test.db + sqlite3 dbY test.db + dbX close + dbY close +} -cleanup { + catch {dbX close} + catch {dbY close} +} + +do_malloc_test shared_err-6 -tclbody { + catch {db close} + ifcapable deprecated { + sqlite3_thread_cleanup + } + sqlite3_enable_shared_cache 0 +} -cleanup { + sqlite3_enable_shared_cache 1 +} + +# As of 3.5.0, sqlite3_enable_shared_cache can be called at +# any time and from any thread +#do_test shared_err-misuse-7.1 { +# sqlite3 db test.db +# catch { +# sqlite3_enable_shared_cache 0 +# } msg +# set msg +#} {library routine called out of sequence} + +# Again provoke a malloc() failure when a cursor position is being saved, +# this time during a ROLLBACK operation by some other handle. +# +# The library should return an SQLITE_NOMEM to the caller. The query that +# owns the cursor (the one for which the position is not saved) should +# be aborted. +# +set ::aborted 0 +do_malloc_test shared_err-8 -tclprep { + sqlite3 db2 test.db + execsql { + PRAGMA read_uncommitted = 1; + BEGIN; + CREATE TABLE t1(a, b, UNIQUE(a, b)); + } db2 + for {set i 0} {$i < 2} {incr i} { + set a [string repeat $i 10] + set b [string repeat $i 2000] + execsql {INSERT INTO t1 VALUES($a, $b)} db2 + } + execsql {COMMIT} db2 + execsql BEGIN + execsql ROLLBACK + set ::DB2 [sqlite3_connection_pointer db2] + set ::STMT [sqlite3_prepare $::DB2 "SELECT a FROM t1 ORDER BY a" -1 DUMMY] + sqlite3_step $::STMT ;# Cursor points at 0000000000 + sqlite3_step $::STMT ;# Cursor points at 1111111111 +} -tclbody { + execsql { + BEGIN; + INSERT INTO t1 VALUES(6, NULL); + ROLLBACK} +} -cleanup { + # UPDATE: As of [5668], if the rollback fails SQLITE_CORRUPT is returned. + # So these tests have been updated to expect SQLITE_CORRUPT and its + # associated English language error message. + # + do_test shared_malloc-8.$::n.cleanup.1 { + set res [catchsql {SELECT a FROM t1} db2] + set ans [lindex $res 1] + if {[lindex $res 0]} { + set r [expr { + $ans=="disk I/O error" || + $ans=="out of memory" || + $ans=="database disk image is malformed" + }] + } else { + set r [expr {[lrange $ans 0 1]=="0000000000 1111111111"}] + } + } {1} + do_test shared_malloc-8.$::n.cleanup.2 { + set rc1 [sqlite3_step $::STMT] + set rc2 [sqlite3_finalize $::STMT] + if {$rc2=="SQLITE_ABORT"} { + incr ::aborted + } + expr { + ($rc1=="SQLITE_DONE" && $rc2=="SQLITE_OK") || + ($rc1=="SQLITE_ERROR" && $rc2=="SQLITE_ABORT") || + ($rc1=="SQLITE_ERROR" && $rc2=="SQLITE_NOMEM") || + ($rc1=="SQLITE_ERROR" && $rc2=="SQLITE_IOERR") || + ($rc1=="SQLITE_ERROR" && $rc2=="SQLITE_CORRUPT") + } + } {1} + db2 close +} +do_test shared_malloc-8.X { + # Test that one or more queries were aborted due to the malloc() failure. + expr $::aborted>=1 +} {1} + +# This test is designed to catch a specific bug that was present during +# development of 3.5.0. If a malloc() failed while setting the page-size, +# a buffer (Pager.pTmpSpace) was being freed. This could cause a seg-fault +# later if another connection tried to use the pager. +# +# This test will crash 3.4.2. +# +do_malloc_test shared_err-9 -tclprep { + sqlite3 db2 test.db +} -sqlbody { + PRAGMA page_size = 4096; + PRAGMA page_size = 1024; +} -cleanup { + db2 eval { + CREATE TABLE abc(a, b, c); + BEGIN; + INSERT INTO abc VALUES(1, 2, 3); + ROLLBACK; + } + db2 close +} + +catch {db close} +catch {db2 close} +do_malloc_test shared_err-10 -tclprep { + sqlite3 db test.db + sqlite3 db2 test.db + + db eval { SELECT * FROM sqlite_master } + db2 eval { + BEGIN; + CREATE TABLE abc(a, b, c); + } +} -tclbody { + catch {db eval {SELECT * FROM sqlite_master}} + error 1 +} -cleanup { + execsql { SELECT * FROM sqlite_master } +} + +do_malloc_test shared_err-11 -tclprep { + sqlite3 db test.db + sqlite3 db2 test.db + + db eval { SELECT * FROM sqlite_master } + db2 eval { + BEGIN; + CREATE TABLE abc(a, b, c); + } +} -tclbody { + catch {db eval {SELECT * FROM sqlite_master}} + catch {sqlite3_errmsg16 db} + error 1 +} -cleanup { + execsql { SELECT * FROM sqlite_master } +} + +catch {db close} +catch {db2 close} + +do_malloc_test shared_err-12 -sqlbody { + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(1, 2, 3); +} + +catch {db close} +catch {db2 close} +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/sharedlock.test b/components/external/SQLite-3.8.1/test/sharedlock.test new file mode 100644 index 0000000000000000000000000000000000000000..caa48f5bbd4417d63fe495252a528f042c68f326 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/sharedlock.test @@ -0,0 +1,82 @@ +# 2009 July 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: sharedlock.test,v 1.1 2009/07/02 17:21:58 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix sharedlock +db close + +ifcapable !shared_cache { + finish_test + return +} + +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] +sqlite3 db test.db +sqlite3 db2 test.db + +do_test sharedlock-1.1 { + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + } +} {} + +do_test sharedlock-1.2 { + set res [list] + db eval { SELECT * FROM t1 ORDER BY rowid } { + lappend res $a $b + if {$a == 1} { catch { db eval "INSERT INTO t1 VALUES(3, 'three')" } } + + # This should fail. Connection [db] has a read-lock on t1, which should + # prevent connection [db2] from obtaining the write-lock it needs to + # modify t1. At one point there was a bug causing the previous INSERT + # to drop the read-lock belonging to [db]. + if {$a == 2} { catch { db2 eval "INSERT INTO t1 VALUES(4, 'four')" } } + } + set res +} {1 one 2 two 3 three} + + +#------------------------------------------------------------------------- +# Test that a write-lock is taken on a table when its entire contents +# are deleted using the OP_Clear optimization. +# +foreach {tn delete_sql} { + 1 { DELETE FROM t2 WHERE 1 } + 2 { DELETE FROM t2 } +} { + do_execsql_test 2.1 { + DROP TABLE IF EXISTS t2; + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES(1, 2); + INSERT INTO t2 VALUES(3, 4); + } + + do_test 2.2 { execsql { SELECT * FROM t2 } db2 } {1 2 3 4} + + do_execsql_test 2.3 " BEGIN; $delete_sql; " + + do_test 2.4 { + catchsql { SELECT * FROM t2 } db2 + } {1 {database table is locked: t2}} + + do_execsql_test 2.5 COMMIT +} + + +db close +db2 close +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/shell1.test b/components/external/SQLite-3.8.1/test/shell1.test new file mode 100644 index 0000000000000000000000000000000000000000..2e936a0b53e8142db19d72884a878a720ef263f6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shell1.test @@ -0,0 +1,812 @@ +# 2009 Nov 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing the CLI shell tool. +# +# + +# Test plan: +# +# shell1-1.*: Basic command line option handling. +# shell1-2.*: Basic "dot" command token parsing. +# shell1-3.*: Basic test that "dot" command can be called. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +if {$tcl_platform(platform)=="windows"} { + set CLI "sqlite3.exe" +} else { + set CLI "./sqlite3" +} +if {![file executable $CLI]} { + finish_test + return +} +db close +forcedelete test.db test.db-journal test.db-wal +sqlite3 db test.db + +#---------------------------------------------------------------------------- +# Test cases shell1-1.*: Basic command line option handling. +# + +# invalid option +do_test shell1-1.1.1 { + set res [catchcmd "-bad test.db" ""] + set rc [lindex $res 0] + list $rc \ + [regexp {Error: unknown option: -bad} $res] +} {1 1} +# error on extra options +do_test shell1-1.1.2 { + set res [catchcmd "-bad test.db \"select 3\" \"select 4\"" ""] + set rc [lindex $res 0] + list $rc \ + [regexp {Error: too many options: "select 4"} $res] +} {1 1} +# error on extra options +do_test shell1-1.1.3 { + set res [catchcmd "-bad FOO test.db BAD" ".quit"] + set rc [lindex $res 0] + list $rc \ + [regexp {Error: too many options: "BAD"} $res] +} {1 1} + +# -help +do_test shell1-1.2.1 { + set res [catchcmd "-help test.db" ""] + set rc [lindex $res 0] + list $rc \ + [regexp {Usage} $res] \ + [regexp {\-init} $res] \ + [regexp {\-version} $res] +} {1 1 1 1} + +# -init filename read/process named file +do_test shell1-1.3.1 { + catchcmd "-init FOO test.db" "" +} {0 {}} +do_test shell1-1.3.2 { + set res [catchcmd "-init FOO test.db .quit BAD" ""] + set rc [lindex $res 0] + list $rc \ + [regexp {Error: too many options: "BAD"} $res] +} {1 1} + +# -echo print commands before execution +do_test shell1-1.4.1 { + catchcmd "-echo test.db" "" +} {0 {}} + +# -[no]header turn headers on or off +do_test shell1-1.5.1 { + catchcmd "-header test.db" "" +} {0 {}} +do_test shell1-1.5.2 { + catchcmd "-noheader test.db" "" +} {0 {}} + +# -bail stop after hitting an error +do_test shell1-1.6.1 { + catchcmd "-bail test.db" "" +} {0 {}} + +# -interactive force interactive I/O +do_test shell1-1.7.1 { + set res [catchcmd "-interactive test.db" ".quit"] + set rc [lindex $res 0] + list $rc \ + [regexp {SQLite version} $res] \ + [regexp {Enter SQL statements} $res] +} {0 1 1} + +# -batch force batch I/O +do_test shell1-1.8.1 { + catchcmd "-batch test.db" "" +} {0 {}} + +# -column set output mode to 'column' +do_test shell1-1.9.1 { + catchcmd "-column test.db" "" +} {0 {}} + +# -csv set output mode to 'csv' +do_test shell1-1.10.1 { + catchcmd "-csv test.db" "" +} {0 {}} + +# -html set output mode to HTML +do_test shell1-1.11.1 { + catchcmd "-html test.db" "" +} {0 {}} + +# -line set output mode to 'line' +do_test shell1-1.12.1 { + catchcmd "-line test.db" "" +} {0 {}} + +# -list set output mode to 'list' +do_test shell1-1.13.1 { + catchcmd "-list test.db" "" +} {0 {}} + +# -separator 'x' set output field separator (|) +do_test shell1-1.14.1 { + catchcmd "-separator 'x' test.db" "" +} {0 {}} +do_test shell1-1.14.2 { + catchcmd "-separator x test.db" "" +} {0 {}} +do_test shell1-1.14.3 { + set res [catchcmd "-separator" ""] + set rc [lindex $res 0] + list $rc \ + [regexp {Error: missing argument to -separator} $res] +} {1 1} + +# -stats print memory stats before each finalize +do_test shell1-1.14b.1 { + catchcmd "-stats test.db" "" +} {0 {}} + +# -nullvalue 'text' set text string for NULL values +do_test shell1-1.15.1 { + catchcmd "-nullvalue 'x' test.db" "" +} {0 {}} +do_test shell1-1.15.2 { + catchcmd "-nullvalue x test.db" "" +} {0 {}} +do_test shell1-1.15.3 { + set res [catchcmd "-nullvalue" ""] + set rc [lindex $res 0] + list $rc \ + [regexp {Error: missing argument to -nullvalue} $res] +} {1 1} + +# -version show SQLite version +do_test shell1-1.16.1 { + set x [catchcmd "-version test.db" ""] +} {/3.[0-9.]+ 20\d\d-[01]\d-\d\d \d\d:\d\d:\d\d [0-9a-f]+/} + +#---------------------------------------------------------------------------- +# Test cases shell1-2.*: Basic "dot" command token parsing. +# + +# check first token handling +do_test shell1-2.1.1 { + catchcmd "test.db" ".foo" +} {1 {Error: unknown command or invalid arguments: "foo". Enter ".help" for help}} +do_test shell1-2.1.2 { + catchcmd "test.db" ".\"foo OFF\"" +} {1 {Error: unknown command or invalid arguments: "foo OFF". Enter ".help" for help}} +do_test shell1-2.1.3 { + catchcmd "test.db" ".\'foo OFF\'" +} {1 {Error: unknown command or invalid arguments: "foo OFF". Enter ".help" for help}} + +# unbalanced quotes +do_test shell1-2.2.1 { + catchcmd "test.db" ".\"foo OFF" +} {1 {Error: unknown command or invalid arguments: "foo OFF". Enter ".help" for help}} +do_test shell1-2.2.2 { + catchcmd "test.db" ".\'foo OFF" +} {1 {Error: unknown command or invalid arguments: "foo OFF". Enter ".help" for help}} +do_test shell1-2.2.3 { + catchcmd "test.db" ".explain \"OFF" +} {0 {}} +do_test shell1-2.2.4 { + catchcmd "test.db" ".explain \'OFF" +} {0 {}} +do_test shell1-2.2.5 { + catchcmd "test.db" ".mode \"insert FOO" +} {1 {Error: mode should be one of: column csv html insert line list tabs tcl}} +do_test shell1-2.2.6 { + catchcmd "test.db" ".mode \'insert FOO" +} {1 {Error: mode should be one of: column csv html insert line list tabs tcl}} + +# check multiple tokens, and quoted tokens +do_test shell1-2.3.1 { + catchcmd "test.db" ".explain 1" +} {0 {}} +do_test shell1-2.3.2 { + catchcmd "test.db" ".explain on" +} {0 {}} +do_test shell1-2.3.3 { + catchcmd "test.db" ".explain \"1 2 3\"" +} {1 {ERROR: Not a boolean value: "1 2 3". Assuming "no".}} +do_test shell1-2.3.4 { + catchcmd "test.db" ".explain \"OFF\"" +} {0 {}} +do_test shell1-2.3.5 { + catchcmd "test.db" ".\'explain\' \'OFF\'" +} {0 {}} +do_test shell1-2.3.6 { + catchcmd "test.db" ".explain \'OFF\'" +} {0 {}} +do_test shell1-2.3.7 { + catchcmd "test.db" ".\'explain\' \'OFF\'" +} {0 {}} + +# check quoted args are unquoted +do_test shell1-2.4.1 { + catchcmd "test.db" ".mode FOO" +} {1 {Error: mode should be one of: column csv html insert line list tabs tcl}} +do_test shell1-2.4.2 { + catchcmd "test.db" ".mode csv" +} {0 {}} +do_test shell1-2.4.2 { + catchcmd "test.db" ".mode \"csv\"" +} {0 {}} + + +#---------------------------------------------------------------------------- +# Test cases shell1-3.*: Basic test that "dot" command can be called. +# + +# .backup ?DB? FILE Backup DB (default "main") to FILE +do_test shell1-3.1.1 { + catchcmd "test.db" ".backup" +} {1 {missing FILENAME argument on .backup}} +do_test shell1-3.1.2 { + catchcmd "test.db" ".backup FOO" +} {0 {}} +do_test shell1-3.1.3 { + catchcmd "test.db" ".backup FOO BAR" +} {1 {Error: unknown database FOO}} +do_test shell1-3.1.4 { + # too many arguments + catchcmd "test.db" ".backup FOO BAR BAD" +} {1 {too many arguments to .backup}} + +# .bail ON|OFF Stop after hitting an error. Default OFF +do_test shell1-3.2.1 { + catchcmd "test.db" ".bail" +} {1 {Error: unknown command or invalid arguments: "bail". Enter ".help" for help}} +do_test shell1-3.2.2 { + catchcmd "test.db" ".bail ON" +} {0 {}} +do_test shell1-3.2.3 { + catchcmd "test.db" ".bail OFF" +} {0 {}} +do_test shell1-3.2.4 { + # too many arguments + catchcmd "test.db" ".bail OFF BAD" +} {1 {Error: unknown command or invalid arguments: "bail". Enter ".help" for help}} + +# .databases List names and files of attached databases +do_test shell1-3.3.1 { + catchcmd "-csv test.db" ".databases" +} "/0 +.*main +[string map {/ .} [string range [get_pwd] 0 10]].*/" +do_test shell1-3.3.2 { + # too many arguments + catchcmd "test.db" ".databases BAD" +} {1 {Error: unknown command or invalid arguments: "databases". Enter ".help" for help}} + +# .dump ?TABLE? ... Dump the database in an SQL text format +# If TABLE specified, only dump tables matching +# LIKE pattern TABLE. +do_test shell1-3.4.1 { + set res [catchcmd "test.db" ".dump"] + list [regexp {BEGIN TRANSACTION;} $res] \ + [regexp {COMMIT;} $res] +} {1 1} +do_test shell1-3.4.2 { + set res [catchcmd "test.db" ".dump FOO"] + list [regexp {BEGIN TRANSACTION;} $res] \ + [regexp {COMMIT;} $res] +} {1 1} +do_test shell1-3.4.3 { + # too many arguments + catchcmd "test.db" ".dump FOO BAD" +} {1 {Error: unknown command or invalid arguments: "dump". Enter ".help" for help}} + +# .echo ON|OFF Turn command echo on or off +do_test shell1-3.5.1 { + catchcmd "test.db" ".echo" +} {1 {Error: unknown command or invalid arguments: "echo". Enter ".help" for help}} +do_test shell1-3.5.2 { + catchcmd "test.db" ".echo ON" +} {0 {}} +do_test shell1-3.5.3 { + catchcmd "test.db" ".echo OFF" +} {0 {}} +do_test shell1-3.5.4 { + # too many arguments + catchcmd "test.db" ".echo OFF BAD" +} {1 {Error: unknown command or invalid arguments: "echo". Enter ".help" for help}} + +# .exit Exit this program +do_test shell1-3.6.1 { + catchcmd "test.db" ".exit" +} {0 {}} + +# .explain ON|OFF Turn output mode suitable for EXPLAIN on or off. +do_test shell1-3.7.1 { + catchcmd "test.db" ".explain" + # explain is the exception to the booleans. without an option, it turns it on. +} {0 {}} +do_test shell1-3.7.2 { + catchcmd "test.db" ".explain ON" +} {0 {}} +do_test shell1-3.7.3 { + catchcmd "test.db" ".explain OFF" +} {0 {}} +do_test shell1-3.7.4 { + # too many arguments + catchcmd "test.db" ".explain OFF BAD" +} {1 {Error: unknown command or invalid arguments: "explain". Enter ".help" for help}} + + +# .header(s) ON|OFF Turn display of headers on or off +do_test shell1-3.9.1 { + catchcmd "test.db" ".header" +} {1 {Error: unknown command or invalid arguments: "header". Enter ".help" for help}} +do_test shell1-3.9.2 { + catchcmd "test.db" ".header ON" +} {0 {}} +do_test shell1-3.9.3 { + catchcmd "test.db" ".header OFF" +} {0 {}} +do_test shell1-3.9.4 { + # too many arguments + catchcmd "test.db" ".header OFF BAD" +} {1 {Error: unknown command or invalid arguments: "header". Enter ".help" for help}} + +do_test shell1-3.9.5 { + catchcmd "test.db" ".headers" +} {1 {Error: unknown command or invalid arguments: "headers". Enter ".help" for help}} +do_test shell1-3.9.6 { + catchcmd "test.db" ".headers ON" +} {0 {}} +do_test shell1-3.9.7 { + catchcmd "test.db" ".headers OFF" +} {0 {}} +do_test shell1-3.9.8 { + # too many arguments + catchcmd "test.db" ".headers OFF BAD" +} {1 {Error: unknown command or invalid arguments: "headers". Enter ".help" for help}} + +# .help Show this message +do_test shell1-3.10.1 { + set res [catchcmd "test.db" ".help"] + # look for a few of the possible help commands + list [regexp {.help} $res] \ + [regexp {.quit} $res] \ + [regexp {.show} $res] +} {1 1 1} +do_test shell1-3.10.2 { + # we allow .help to take extra args (it is help after all) + set res [catchcmd "test.db" ".help BAD"] + # look for a few of the possible help commands + list [regexp {.help} $res] \ + [regexp {.quit} $res] \ + [regexp {.show} $res] +} {1 1 1} + +# .import FILE TABLE Import data from FILE into TABLE +do_test shell1-3.11.1 { + catchcmd "test.db" ".import" +} {1 {Error: unknown command or invalid arguments: "import". Enter ".help" for help}} +do_test shell1-3.11.2 { + catchcmd "test.db" ".import FOO" +} {1 {Error: unknown command or invalid arguments: "import". Enter ".help" for help}} +#do_test shell1-3.11.2 { +# catchcmd "test.db" ".import FOO BAR" +#} {1 {Error: no such table: BAR}} +do_test shell1-3.11.3 { + # too many arguments + catchcmd "test.db" ".import FOO BAR BAD" +} {1 {Error: unknown command or invalid arguments: "import". Enter ".help" for help}} + +# .indices ?TABLE? Show names of all indices +# If TABLE specified, only show indices for tables +# matching LIKE pattern TABLE. +do_test shell1-3.12.1 { + catchcmd "test.db" ".indices" +} {0 {}} +do_test shell1-3.12.2 { + catchcmd "test.db" ".indices FOO" +} {0 {}} +do_test shell1-3.12.3 { + # too many arguments + catchcmd "test.db" ".indices FOO BAD" +} {1 {Error: unknown command or invalid arguments: "indices". Enter ".help" for help}} + +# .mode MODE ?TABLE? Set output mode where MODE is one of: +# csv Comma-separated values +# column Left-aligned columns. (See .width) +# html HTML
    code +# insert SQL insert statements for TABLE +# line One value per line +# list Values delimited by .separator string +# tabs Tab-separated values +# tcl TCL list elements +do_test shell1-3.13.1 { + catchcmd "test.db" ".mode" +} {1 {Error: unknown command or invalid arguments: "mode". Enter ".help" for help}} +do_test shell1-3.13.2 { + catchcmd "test.db" ".mode FOO" +} {1 {Error: mode should be one of: column csv html insert line list tabs tcl}} +do_test shell1-3.13.3 { + catchcmd "test.db" ".mode csv" +} {0 {}} +do_test shell1-3.13.4 { + catchcmd "test.db" ".mode column" +} {0 {}} +do_test shell1-3.13.5 { + catchcmd "test.db" ".mode html" +} {0 {}} +do_test shell1-3.13.6 { + catchcmd "test.db" ".mode insert" +} {0 {}} +do_test shell1-3.13.7 { + catchcmd "test.db" ".mode line" +} {0 {}} +do_test shell1-3.13.8 { + catchcmd "test.db" ".mode list" +} {0 {}} +do_test shell1-3.13.9 { + catchcmd "test.db" ".mode tabs" +} {0 {}} +do_test shell1-3.13.10 { + catchcmd "test.db" ".mode tcl" +} {0 {}} +do_test shell1-3.13.11 { + # too many arguments + catchcmd "test.db" ".mode tcl BAD" +} {1 {Error: invalid arguments: "BAD". Enter ".help" for help}} + +# don't allow partial mode type matches +do_test shell1-3.13.12 { + catchcmd "test.db" ".mode l" +} {1 {Error: mode should be one of: column csv html insert line list tabs tcl}} +do_test shell1-3.13.13 { + catchcmd "test.db" ".mode li" +} {1 {Error: mode should be one of: column csv html insert line list tabs tcl}} +do_test shell1-3.13.14 { + catchcmd "test.db" ".mode lin" +} {1 {Error: mode should be one of: column csv html insert line list tabs tcl}} + +# .nullvalue STRING Print STRING in place of NULL values +do_test shell1-3.14.1 { + catchcmd "test.db" ".nullvalue" +} {1 {Error: unknown command or invalid arguments: "nullvalue". Enter ".help" for help}} +do_test shell1-3.14.2 { + catchcmd "test.db" ".nullvalue FOO" +} {0 {}} +do_test shell1-3.14.3 { + # too many arguments + catchcmd "test.db" ".nullvalue FOO BAD" +} {1 {Error: unknown command or invalid arguments: "nullvalue". Enter ".help" for help}} + +# .output FILENAME Send output to FILENAME +do_test shell1-3.15.1 { + catchcmd "test.db" ".output" +} {1 {Error: unknown command or invalid arguments: "output". Enter ".help" for help}} +do_test shell1-3.15.2 { + catchcmd "test.db" ".output FOO" +} {0 {}} +do_test shell1-3.15.3 { + # too many arguments + catchcmd "test.db" ".output FOO BAD" +} {1 {Error: unknown command or invalid arguments: "output". Enter ".help" for help}} + +# .output stdout Send output to the screen +do_test shell1-3.16.1 { + catchcmd "test.db" ".output stdout" +} {0 {}} +do_test shell1-3.16.2 { + # too many arguments + catchcmd "test.db" ".output stdout BAD" +} {1 {Error: unknown command or invalid arguments: "output". Enter ".help" for help}} + +# .prompt MAIN CONTINUE Replace the standard prompts +do_test shell1-3.17.1 { + catchcmd "test.db" ".prompt" +} {1 {Error: unknown command or invalid arguments: "prompt". Enter ".help" for help}} +do_test shell1-3.17.2 { + catchcmd "test.db" ".prompt FOO" +} {0 {}} +do_test shell1-3.17.3 { + catchcmd "test.db" ".prompt FOO BAR" +} {0 {}} +do_test shell1-3.17.4 { + # too many arguments + catchcmd "test.db" ".prompt FOO BAR BAD" +} {1 {Error: unknown command or invalid arguments: "prompt". Enter ".help" for help}} + +# .quit Exit this program +do_test shell1-3.18.1 { + catchcmd "test.db" ".quit" +} {0 {}} +do_test shell1-3.18.2 { + # too many arguments + catchcmd "test.db" ".quit BAD" +} {1 {Error: unknown command or invalid arguments: "quit". Enter ".help" for help}} + +# .read FILENAME Execute SQL in FILENAME +do_test shell1-3.19.1 { + catchcmd "test.db" ".read" +} {1 {Error: unknown command or invalid arguments: "read". Enter ".help" for help}} +do_test shell1-3.19.2 { + forcedelete FOO + catchcmd "test.db" ".read FOO" +} {1 {Error: cannot open "FOO"}} +do_test shell1-3.19.3 { + # too many arguments + catchcmd "test.db" ".read FOO BAD" +} {1 {Error: unknown command or invalid arguments: "read". Enter ".help" for help}} + +# .restore ?DB? FILE Restore content of DB (default "main") from FILE +do_test shell1-3.20.1 { + catchcmd "test.db" ".restore" +} {1 {Error: unknown command or invalid arguments: "restore". Enter ".help" for help}} +do_test shell1-3.20.2 { + catchcmd "test.db" ".restore FOO" +} {0 {}} +do_test shell1-3.20.3 { + catchcmd "test.db" ".restore FOO BAR" +} {1 {Error: unknown database FOO}} +do_test shell1-3.20.4 { + # too many arguments + catchcmd "test.db" ".restore FOO BAR BAD" +} {1 {Error: unknown command or invalid arguments: "restore". Enter ".help" for help}} + +# .schema ?TABLE? Show the CREATE statements +# If TABLE specified, only show tables matching +# LIKE pattern TABLE. +do_test shell1-3.21.1 { + catchcmd "test.db" ".schema" +} {0 {}} +do_test shell1-3.21.2 { + catchcmd "test.db" ".schema FOO" +} {0 {}} +do_test shell1-3.21.3 { + # too many arguments + catchcmd "test.db" ".schema FOO BAD" +} {1 {Error: unknown command or invalid arguments: "schema". Enter ".help" for help}} + +do_test shell1-3.21.4 { + catchcmd "test.db" { + CREATE TABLE t1(x); + CREATE VIEW v2 AS SELECT x+1 AS y FROM t1; + CREATE VIEW v1 AS SELECT y+1 FROM v2; + } + catchcmd "test.db" ".schema" +} {0 {CREATE TABLE t1(x); +CREATE VIEW v2 AS SELECT x+1 AS y FROM t1; +CREATE VIEW v1 AS SELECT y+1 FROM v2;}} +db eval {DROP VIEW v1; DROP VIEW v2; DROP TABLE t1;} + +# .separator STRING Change separator used by output mode and .import +do_test shell1-3.22.1 { + catchcmd "test.db" ".separator" +} {1 {Error: unknown command or invalid arguments: "separator". Enter ".help" for help}} +do_test shell1-3.22.2 { + catchcmd "test.db" ".separator FOO" +} {0 {}} +do_test shell1-3.22.3 { + # too many arguments + catchcmd "test.db" ".separator FOO BAD" +} {1 {Error: unknown command or invalid arguments: "separator". Enter ".help" for help}} + +# .show Show the current values for various settings +do_test shell1-3.23.1 { + set res [catchcmd "test.db" ".show"] + list [regexp {echo:} $res] \ + [regexp {explain:} $res] \ + [regexp {headers:} $res] \ + [regexp {mode:} $res] \ + [regexp {nullvalue:} $res] \ + [regexp {output:} $res] \ + [regexp {separator:} $res] \ + [regexp {stats:} $res] \ + [regexp {width:} $res] +} {1 1 1 1 1 1 1 1 1} +do_test shell1-3.23.2 { + # too many arguments + catchcmd "test.db" ".show BAD" +} {1 {Error: unknown command or invalid arguments: "show". Enter ".help" for help}} + +# .stats ON|OFF Turn stats on or off +do_test shell1-3.23b.1 { + catchcmd "test.db" ".stats" +} {1 {Error: unknown command or invalid arguments: "stats". Enter ".help" for help}} +do_test shell1-3.23b.2 { + catchcmd "test.db" ".stats ON" +} {0 {}} +do_test shell1-3.23b.3 { + catchcmd "test.db" ".stats OFF" +} {0 {}} +do_test shell1-3.23b.4 { + # too many arguments + catchcmd "test.db" ".stats OFF BAD" +} {1 {Error: unknown command or invalid arguments: "stats". Enter ".help" for help}} + +# .tables ?TABLE? List names of tables +# If TABLE specified, only list tables matching +# LIKE pattern TABLE. +do_test shell1-3.24.1 { + catchcmd "test.db" ".tables" +} {0 {}} +do_test shell1-3.24.2 { + catchcmd "test.db" ".tables FOO" +} {0 {}} +do_test shell1-3.24.3 { + # too many arguments + catchcmd "test.db" ".tables FOO BAD" +} {1 {Error: unknown command or invalid arguments: "tables". Enter ".help" for help}} + +# .timeout MS Try opening locked tables for MS milliseconds +do_test shell1-3.25.1 { + catchcmd "test.db" ".timeout" +} {1 {Error: unknown command or invalid arguments: "timeout". Enter ".help" for help}} +do_test shell1-3.25.2 { + catchcmd "test.db" ".timeout zzz" + # this should be treated the same as a '0' timeout +} {0 {}} +do_test shell1-3.25.3 { + catchcmd "test.db" ".timeout 1" +} {0 {}} +do_test shell1-3.25.4 { + # too many arguments + catchcmd "test.db" ".timeout 1 BAD" +} {1 {Error: unknown command or invalid arguments: "timeout". Enter ".help" for help}} + +# .width NUM NUM ... Set column widths for "column" mode +do_test shell1-3.26.1 { + catchcmd "test.db" ".width" +} {1 {Error: unknown command or invalid arguments: "width". Enter ".help" for help}} +do_test shell1-3.26.2 { + catchcmd "test.db" ".width xxx" + # this should be treated the same as a '0' width for col 1 +} {0 {}} +do_test shell1-3.26.3 { + catchcmd "test.db" ".width xxx yyy" + # this should be treated the same as a '0' width for col 1 and 2 +} {0 {}} +do_test shell1-3.26.4 { + catchcmd "test.db" ".width 1 1" + # this should be treated the same as a '1' width for col 1 and 2 +} {0 {}} +do_test shell1-3.26.5 { + catchcmd "test.db" ".mode column\n.width 10 -10\nSELECT 'abcdefg', 123456;" + # this should be treated the same as a '1' width for col 1 and 2 +} {0 {abcdefg 123456}} +do_test shell1-3.26.6 { + catchcmd "test.db" ".mode column\n.width -10 10\nSELECT 'abcdefg', 123456;" + # this should be treated the same as a '1' width for col 1 and 2 +} {0 { abcdefg 123456 }} + + +# .timer ON|OFF Turn the CPU timer measurement on or off +do_test shell1-3.27.1 { + catchcmd "test.db" ".timer" +} {1 {Error: unknown command or invalid arguments: "timer". Enter ".help" for help}} +do_test shell1-3.27.2 { + catchcmd "test.db" ".timer ON" +} {0 {}} +do_test shell1-3.27.3 { + catchcmd "test.db" ".timer OFF" +} {0 {}} +do_test shell1-3.27.4 { + # too many arguments + catchcmd "test.db" ".timer OFF BAD" +} {1 {Error: unknown command or invalid arguments: "timer". Enter ".help" for help}} + +do_test shell1-3-28.1 { + catchcmd test.db \ + ".log stdout\nSELECT coalesce(sqlite_log(123,'hello'),'456');" +} "0 {(123) hello\n456}" + +do_test shell1-3-29.1 { + catchcmd "test.db" ".print this is a test" +} {0 {this is a test}} + +# dot-command argument quoting +do_test shell1-3-30.1 { + catchcmd {test.db} {.print "this\"is'a\055test" 'this\"is\\a\055test'} +} {0 {this"is'a-test this\"is\\a\055test}} +do_test shell1-3-31.1 { + catchcmd {test.db} {.print "this\nis\ta\\test" 'this\nis\ta\\test'} +} [list 0 "this\nis\ta\\test this\\nis\\ta\\\\test"] + + +# Test the output of the ".dump" command +# +do_test shell1-4.1 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA encoding=UTF16; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(null), (''), (1), (2.25), ('hello'), (x'807f'); + } + catchcmd test.db {.dump} +} {0 {PRAGMA foreign_keys=OFF; +BEGIN TRANSACTION; +CREATE TABLE t1(x); +INSERT INTO "t1" VALUES(NULL); +INSERT INTO "t1" VALUES(''); +INSERT INTO "t1" VALUES(1); +INSERT INTO "t1" VALUES(2.25); +INSERT INTO "t1" VALUES('hello'); +INSERT INTO "t1" VALUES(X'807F'); +COMMIT;}} + +# Test the output of ".mode insert" +# +do_test shell1-4.2 { + catchcmd test.db ".mode insert t1\nselect * from t1;" +} {0 {INSERT INTO t1 VALUES(NULL); +INSERT INTO t1 VALUES(''); +INSERT INTO t1 VALUES(1); +INSERT INTO t1 VALUES(2.25); +INSERT INTO t1 VALUES('hello'); +INSERT INTO t1 VALUES(X'807f');}} + +# Test the output of ".mode tcl" +# +do_test shell1-4.3 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA encoding=UTF8; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(null), (''), (1), (2.25), ('hello'), (x'807f'); + } + catchcmd test.db ".mode tcl\nselect * from t1;" +} {0 {"" +"" +"1" +"2.25" +"hello" +"\200\177"}} + +# Test the output of ".mode tcl" with multiple columns +# +do_test shell1-4.4 { + db eval { + CREATE TABLE t2(x,y); + INSERT INTO t2 VALUES(null, ''), (1, 2.25), ('hello', x'807f'); + } + catchcmd test.db ".mode tcl\nselect * from t2;" +} {0 {"" "" +"1" "2.25" +"hello" "\200\177"}} + +# Test the output of ".mode tcl" with ".nullvalue" +# +do_test shell1-4.5 { + catchcmd test.db ".mode tcl\n.nullvalue NULL\nselect * from t2;" +} {0 {"NULL" "" +"1" "2.25" +"hello" "\200\177"}} + +# Test the output of ".mode tcl" with Tcl reserved characters +# +do_test shell1-4.6 { + db eval { + CREATE TABLE tcl1(x); + INSERT INTO tcl1 VALUES('"'), ('['), (']'), ('\{'), ('\}'), (';'), ('$'); + } + foreach {x y} [catchcmd test.db ".mode tcl\nselect * from tcl1;"] break + list $x $y [llength $y] +} {0 {"\"" +"[" +"]" +"\\{" +"\\}" +";" +"$"} 7} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/shell2.test b/components/external/SQLite-3.8.1/test/shell2.test new file mode 100644 index 0000000000000000000000000000000000000000..f02d788415e91804aa541b2a081608e0e670f423 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shell2.test @@ -0,0 +1,197 @@ +# 2009 Nov 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing the CLI shell tool. +# +# $Id: shell2.test,v 1.7 2009/07/17 16:54:48 shaneh Exp $ +# + +# Test plan: +# +# shell2-1.*: Misc. test of various tickets and reported errors. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +if {$tcl_platform(platform)=="windows"} { + set CLI "sqlite3.exe" +} else { + set CLI "./sqlite3" +} +if {![file executable $CLI]} { + finish_test + return +} +db close +forcedelete test.db test.db-journal test.db-wal +sqlite3 db test.db + + +#---------------------------------------------------------------------------- +# shell2-1.*: Misc. test of various tickets and reported errors. +# + +# Batch mode not creating databases. +# Reported on mailing list by Ken Zalewski. +# Ticket [aeff892c57]. +do_test shell2-1.1.1 { + forcedelete foo.db + set rc [ catchcmd "-batch foo.db" "CREATE TABLE t1(a);" ] + set fexist [file exist foo.db] + list $rc $fexist +} {{0 {}} 1} + +# Shell silently ignores extra parameters. +# Ticket [f5cb008a65]. +do_test shell2-1.2.1 { + set rc [catch { eval exec $CLI \":memory:\" \"select 3\" \"select 4\" } msg] + list $rc \ + [regexp {Error: too many options: "select 4"} $msg] +} {1 1} + +# Test a problem reported on the mailing list. The shell was at one point +# returning the generic SQLITE_ERROR message ("SQL error or missing database") +# instead of the "too many levels..." message in the test below. +# +do_test shell2-1.3 { + catchcmd "-batch test.db" { + PRAGMA recursive_triggers = ON; + CREATE TABLE t5(a PRIMARY KEY, b, c); + INSERT INTO t5 VALUES(1, 2, 3); + CREATE TRIGGER au_tble AFTER UPDATE ON t5 BEGIN + UPDATE OR IGNORE t5 SET a = new.a, c = 10; + END; + + UPDATE OR REPLACE t5 SET a = 4 WHERE a = 1; + } +} {1 {Error: near line 9: too many levels of trigger recursion}} + + + +# Shell not echoing all commands with echo on. +# Ticket [eb620916be]. + +# Test with echo off +# NB. whitespace is important +do_test shell2-1.4.1 { + forcedelete foo.db + catchcmd "foo.db" {CREATE TABLE foo(a); +INSERT INTO foo(a) VALUES(1); +SELECT * FROM foo;} +} {0 1} + +# Test with echo on using command line option +# NB. whitespace is important +do_test shell2-1.4.2 { + forcedelete foo.db + catchcmd "-echo foo.db" {CREATE TABLE foo(a); +INSERT INTO foo(a) VALUES(1); +SELECT * FROM foo;} +} {0 {CREATE TABLE foo(a); +INSERT INTO foo(a) VALUES(1); +SELECT * FROM foo; +1}} + +# Test with echo on using dot command +# NB. whitespace is important +do_test shell2-1.4.3 { + forcedelete foo.db + catchcmd "foo.db" {.echo ON +CREATE TABLE foo(a); +INSERT INTO foo(a) VALUES(1); +SELECT * FROM foo;} +} {0 {CREATE TABLE foo(a); +INSERT INTO foo(a) VALUES(1); +SELECT * FROM foo; +1}} + +# Test with echo on using dot command and +# turning off mid- processing. +# NB. whitespace is important +do_test shell2-1.4.4 { + forcedelete foo.db + catchcmd "foo.db" {.echo ON +CREATE TABLE foo(a); +.echo OFF +INSERT INTO foo(a) VALUES(1); +SELECT * FROM foo;} +} {0 {CREATE TABLE foo(a); +.echo OFF +1}} + +# Test with echo on using dot command and +# multiple commands per line. +# NB. whitespace is important +do_test shell2-1.4.5 { + forcedelete foo.db + catchcmd "foo.db" {.echo ON +CREATE TABLE foo1(a); +INSERT INTO foo1(a) VALUES(1); +CREATE TABLE foo2(b); +INSERT INTO foo2(b) VALUES(1); +SELECT * FROM foo1; SELECT * FROM foo2; +INSERT INTO foo1(a) VALUES(2); INSERT INTO foo2(b) VALUES(2); +SELECT * FROM foo1; SELECT * FROM foo2; +} +} {0 {CREATE TABLE foo1(a); +INSERT INTO foo1(a) VALUES(1); +CREATE TABLE foo2(b); +INSERT INTO foo2(b) VALUES(1); +SELECT * FROM foo1; +1 +SELECT * FROM foo2; +1 +INSERT INTO foo1(a) VALUES(2); +INSERT INTO foo2(b) VALUES(2); +SELECT * FROM foo1; +1 +2 +SELECT * FROM foo2; +1 +2}} + +# Test with echo on and headers on using dot command and +# multiple commands per line. +# NB. whitespace is important +do_test shell2-1.4.6 { + forcedelete foo.db + catchcmd "foo.db" {.echo ON +.headers ON +CREATE TABLE foo1(a); +INSERT INTO foo1(a) VALUES(1); +CREATE TABLE foo2(b); +INSERT INTO foo2(b) VALUES(1); +SELECT * FROM foo1; SELECT * FROM foo2; +INSERT INTO foo1(a) VALUES(2); INSERT INTO foo2(b) VALUES(2); +SELECT * FROM foo1; SELECT * FROM foo2; +} +} {0 {.headers ON +CREATE TABLE foo1(a); +INSERT INTO foo1(a) VALUES(1); +CREATE TABLE foo2(b); +INSERT INTO foo2(b) VALUES(1); +SELECT * FROM foo1; +a +1 +SELECT * FROM foo2; +b +1 +INSERT INTO foo1(a) VALUES(2); +INSERT INTO foo2(b) VALUES(2); +SELECT * FROM foo1; +a +1 +2 +SELECT * FROM foo2; +b +1 +2}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/shell3.test b/components/external/SQLite-3.8.1/test/shell3.test new file mode 100644 index 0000000000000000000000000000000000000000..ce1fd4ecb5d82931fc0dddf5abaa1f2b63a71885 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shell3.test @@ -0,0 +1,97 @@ +# 2009 Dec 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing the CLI shell tool. +# +# $Id: shell2.test,v 1.7 2009/07/17 16:54:48 shaneh Exp $ +# + +# Test plan: +# +# shell3-1.*: Basic tests for running SQL statments from command line. +# shell3-2.*: Basic tests for running SQL file from command line. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +if {$tcl_platform(platform)=="windows"} { + set CLI "sqlite3.exe" +} else { + set CLI "./sqlite3" +} +if {![file executable $CLI]} { + finish_test + return +} +db close +forcedelete test.db test.db-journal test.db-wal +sqlite3 db test.db + +#---------------------------------------------------------------------------- +# shell3-1.*: Basic tests for running SQL statments from command line. +# + +# Run SQL statement from command line +do_test shell3-1.1 { + forcedelete foo.db + set rc [ catchcmd "foo.db \"CREATE TABLE t1(a);\"" ] + set fexist [file exist foo.db] + list $rc $fexist +} {{0 {}} 1} +do_test shell3-1.2 { + catchcmd "foo.db" ".tables" +} {0 t1} +do_test shell3-1.3 { + catchcmd "foo.db \"DROP TABLE t1;\"" +} {0 {}} +do_test shell3-1.4 { + catchcmd "foo.db" ".tables" +} {0 {}} +do_test shell3-1.5 { + catchcmd "foo.db \"CREATE TABLE t1(a); DROP TABLE t1;\"" +} {0 {}} +do_test shell3-1.6 { + catchcmd "foo.db" ".tables" +} {0 {}} +do_test shell3-1.7 { + catchcmd "foo.db \"CREATE TABLE\"" +} {1 {Error: near "TABLE": syntax error}} + +#---------------------------------------------------------------------------- +# shell3-2.*: Basic tests for running SQL file from command line. +# + +# Run SQL file from command line +do_test shell3-2.1 { + forcedelete foo.db + set rc [ catchcmd "foo.db" "CREATE TABLE t1(a);" ] + set fexist [file exist foo.db] + list $rc $fexist +} {{0 {}} 1} +do_test shell3-2.2 { + catchcmd "foo.db" ".tables" +} {0 t1} +do_test shell3-2.3 { + catchcmd "foo.db" "DROP TABLE t1;" +} {0 {}} +do_test shell3-2.4 { + catchcmd "foo.db" ".tables" +} {0 {}} +do_test shell3-2.5 { + catchcmd "foo.db" "CREATE TABLE t1(a); DROP TABLE t1;" +} {0 {}} +do_test shell3-2.6 { + catchcmd "foo.db" ".tables" +} {0 {}} +do_test shell3-2.7 { + catchcmd "foo.db" "CREATE TABLE" +} {1 {Error: incomplete SQL: CREATE TABLE}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/shell4.test b/components/external/SQLite-3.8.1/test/shell4.test new file mode 100644 index 0000000000000000000000000000000000000000..5af44c8fd7cb05d160bfef7c01771473d43bb9e7 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shell4.test @@ -0,0 +1,116 @@ +# 2010 July 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing the CLI shell tool. +# These tests are specific to the .stats command. +# +# $Id: shell4.test,v 1.7 2009/07/17 16:54:48 shaneh Exp $ +# + +# Test plan: +# +# shell4-1.*: Basic tests specific to the "stats" command. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +if {$tcl_platform(platform)=="windows"} { + set CLI "sqlite3.exe" +} else { + set CLI "./sqlite3" +} +if {![file executable $CLI]} { + finish_test + return +} +db close +forcedelete test.db test.db-journal test.db-wal +sqlite3 db test.db + +#---------------------------------------------------------------------------- +# Test cases shell4-1.*: Tests specific to the "stats" command. +# + +# should default to off +do_test shell4-1.1.1 { + set res [catchcmd "test.db" ".show"] + list [regexp {stats: off} $res] +} {1} + +do_test shell4-1.1.2 { + set res [catchcmd "test.db" ".show"] + list [regexp {stats: on} $res] +} {0} + +# -stats should turn it on +do_test shell4-1.2.1 { + set res [catchcmd "-stats test.db" ".show"] + list [regexp {stats: on} $res] +} {1} + +do_test shell4-1.2.2 { + set res [catchcmd "-stats test.db" ".show"] + list [regexp {stats: off} $res] +} {0} + +# .stats ON|OFF Turn stats on or off +do_test shell4-1.3.1 { + catchcmd "test.db" ".stats" +} {1 {Error: unknown command or invalid arguments: "stats". Enter ".help" for help}} +do_test shell4-1.3.2 { + catchcmd "test.db" ".stats ON" +} {0 {}} +do_test shell4-1.3.3 { + catchcmd "test.db" ".stats OFF" +} {0 {}} +do_test shell4-1.3.4 { + # too many arguments + catchcmd "test.db" ".stats OFF BAD" +} {1 {Error: unknown command or invalid arguments: "stats". Enter ".help" for help}} + +# NB. whitespace is important +do_test shell4-1.4.1 { + set res [catchcmd "test.db" {.show}] + list [regexp {stats: off} $res] +} {1} + +do_test shell4-1.4.2 { + set res [catchcmd "test.db" {.stats ON +.show +}] + list [regexp {stats: on} $res] +} {1} + +do_test shell4-1.4.3 { + set res [catchcmd "test.db" {.stats OFF +.show +}] + list [regexp {stats: off} $res] +} {1} + +# make sure stats not present when off +do_test shell4-1.5.1 { + set res [catchcmd "test.db" {SELECT 1;}] + list [regexp {Memory Used} $res] \ + [regexp {Heap Usage} $res] \ + [regexp {Autoindex Inserts} $res] +} {0 0 0} + +# make sure stats are present when on +do_test shell4-1.5.2 { + set res [catchcmd "test.db" {.stats ON +SELECT 1; +}] + list [regexp {Memory Used} $res] \ + [regexp {Heap Usage} $res] \ + [regexp {Autoindex Inserts} $res] +} {1 1 1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/shell5.test b/components/external/SQLite-3.8.1/test/shell5.test new file mode 100644 index 0000000000000000000000000000000000000000..cd3d471031912018a6d9093788b18249b691484e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shell5.test @@ -0,0 +1,271 @@ +# 2010 August 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The focus of this file is testing the CLI shell tool. +# These tests are specific to the .import command. +# +# $Id: shell5.test,v 1.7 2009/07/17 16:54:48 shaneh Exp $ +# + +# Test plan: +# +# shell5-1.*: Basic tests specific to the ".import" command. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +if {$tcl_platform(platform)=="windows"} { + set CLI "sqlite3.exe" +} else { + set CLI "./sqlite3" +} +if {![file executable $CLI]} { + finish_test + return +} +db close +forcedelete test.db test.db-journal test.db-wal + +#---------------------------------------------------------------------------- +# Test cases shell5-1.*: Basic handling of the .import and .separator commands. +# + +# .import FILE TABLE Import data from FILE into TABLE +do_test shell5-1.1.1 { + catchcmd "test.db" ".import" +} {1 {Error: unknown command or invalid arguments: "import". Enter ".help" for help}} +do_test shell5-1.1.2 { + catchcmd "test.db" ".import FOO" +} {1 {Error: unknown command or invalid arguments: "import". Enter ".help" for help}} +#do_test shell5-1.1.2 { +# catchcmd "test.db" ".import FOO BAR" +#} {1 {Error: no such table: BAR}} +do_test shell5-1.1.3 { + # too many arguments + catchcmd "test.db" ".import FOO BAR BAD" +} {1 {Error: unknown command or invalid arguments: "import". Enter ".help" for help}} + +# .separator STRING Change separator used by output mode and .import +do_test shell1-1.2.1 { + catchcmd "test.db" ".separator" +} {1 {Error: unknown command or invalid arguments: "separator". Enter ".help" for help}} +do_test shell1-1.2.2 { + catchcmd "test.db" ".separator FOO" +} {0 {}} +do_test shell1-1.2.3 { + # too many arguments + catchcmd "test.db" ".separator FOO BAD" +} {1 {Error: unknown command or invalid arguments: "separator". Enter ".help" for help}} + +# separator should default to "|" +do_test shell5-1.3.1 { + set res [catchcmd "test.db" ".show"] + list [regexp {separator: \"\|\"} $res] +} {1} + +# set separator to different value. +# check that .show reports new value +do_test shell5-1.3.2 { + set res [catchcmd "test.db" {.separator , +.show}] + list [regexp {separator: \",\"} $res] +} {1} + +# import file doesn't exist +do_test shell5-1.4.1 { + forcedelete FOO + set res [catchcmd "test.db" {CREATE TABLE t1(a, b); +.import FOO t1}] +} {1 {Error: cannot open "FOO"}} + +# empty import file +do_test shell5-1.4.2 { + forcedelete shell5.csv + set in [open shell5.csv w] + close $in + set res [catchcmd "test.db" {.import shell5.csv t1 +SELECT COUNT(*) FROM t1;}] +} {0 0} + +# import file with 1 row, 1 column (expecting 2 cols) +do_test shell5-1.4.3 { + set in [open shell5.csv w] + puts $in "1" + close $in + set res [catchcmd "test.db" {.import shell5.csv t1}] +} {1 {shell5.csv:1: expected 2 columns but found 1 - filling the rest with NULL}} + +# import file with 1 row, 3 columns (expecting 2 cols) +do_test shell5-1.4.4 { + set in [open shell5.csv w] + puts $in "1|2|3" + close $in + set res [catchcmd "test.db" {.import shell5.csv t1}] +} {1 {shell5.csv:1: expected 2 columns but found 3 - extras ignored}} + +# import file with 1 row, 2 columns +do_test shell5-1.4.5 { + set in [open shell5.csv w] + puts $in "1|2" + close $in + set res [catchcmd "test.db" {DELETE FROM t1; +.import shell5.csv t1 +SELECT COUNT(*) FROM t1;}] +} {0 1} + +# import file with 2 rows, 2 columns +# note we end up with 3 rows because of the 1 row +# imported above. +do_test shell5-1.4.6 { + set in [open shell5.csv w] + puts $in "2|3" + puts $in "3|4" + close $in + set res [catchcmd "test.db" {.import shell5.csv t1 +SELECT COUNT(*) FROM t1;}] +} {0 3} + +# import file with 1 row, 2 columns, using a comma +do_test shell5-1.4.7 { + set in [open shell5.csv w] + puts $in "4,5" + close $in + set res [catchcmd "test.db" {.separator , +.import shell5.csv t1 +SELECT COUNT(*) FROM t1;}] +} {0 4} + +# import file with 1 row, 2 columns, text data +do_test shell5-1.4.8.1 { + set in [open shell5.csv w] + puts $in "5|Now is the time for all good men to come to the aid of their country." + close $in + set res [catchcmd "test.db" {.import shell5.csv t1 +SELECT COUNT(*) FROM t1;}] +} {0 5} + +do_test shell5-1.4.8.2 { + catchcmd "test.db" {SELECT b FROM t1 WHERE a='5';} +} {0 {Now is the time for all good men to come to the aid of their country.}} + +# import file with 1 row, 2 columns, quoted text data +# note that currently sqlite doesn't support quoted fields, and +# imports the entire field, quotes and all. +do_test shell5-1.4.9.1 { + set in [open shell5.csv w] + puts $in "6|'Now is the time for all good men to come to the aid of their country.'" + close $in + set res [catchcmd "test.db" {.import shell5.csv t1 +SELECT COUNT(*) FROM t1;}] +} {0 6} + +do_test shell5-1.4.9.2 { + catchcmd "test.db" {SELECT b FROM t1 WHERE a='6';} +} {0 {'Now is the time for all good men to come to the aid of their country.'}} + +# import file with 1 row, 2 columns, quoted text data +do_test shell5-1.4.10.1 { + set in [open shell5.csv w] + puts $in "7|\"Now is the time for all good men to come to the aid of their country.\"" + close $in + set res [catchcmd "test.db" {.import shell5.csv t1 +SELECT COUNT(*) FROM t1;}] +} {0 7} + +do_test shell5-1.4.10.2 { + catchcmd "test.db" {SELECT b FROM t1 WHERE a='7';} +} {0 {Now is the time for all good men to come to the aid of their country.}} + +# check importing very long field +do_test shell5-1.5.1 { + set str [string repeat X 999] + set in [open shell5.csv w] + puts $in "8|$str" + close $in + set res [catchcmd "test.db" {.import shell5.csv t1 +SELECT length(b) FROM t1 WHERE a='8';}] +} {0 999} + +# try importing into a table with a large number of columns. +# This is limited by SQLITE_MAX_VARIABLE_NUMBER, which defaults to 999. +set cols 999 +do_test shell5-1.6.1 { + set data {} + for {set i 1} {$i<$cols} {incr i} { + append data "c$i|" + } + append data "c$cols\n"; + for {set i 1} {$i<$cols} {incr i} { + append data "$i|" + } + append data "$cols" + set in [open shell5.csv w] + puts $in $data + close $in + set res [catchcmd "test.db" {.import shell5.csv t2 +SELECT COUNT(*) FROM t2;}] +} {0 1} + +# try importing a large number of rows +set rows 9999 +do_test shell5-1.7.1 { + set in [open shell5.csv w] + puts $in a + for {set i 1} {$i<=$rows} {incr i} { + puts $in $i + } + close $in + set res [catchcmd "test.db" {.mode csv +.import shell5.csv t3 +SELECT COUNT(*) FROM t3;}] +} [list 0 $rows] + +# Inport from a pipe. (Unix only, as it requires "awk") +if {$tcl_platform(platform)=="unix"} { + do_test shell5-1.8 { + forcedelete test.db + catchcmd test.db {.mode csv +.import "|awk 'END{print \"x,y\";for(i=1;i<=5;i++){print i \",this is \" i}}'" t1 +SELECT * FROM t1;} + } {0 {1,"this is 1" +2,"this is 2" +3,"this is 3" +4,"this is 4" +5,"this is 5"}} +} + +# Import columns containing quoted strings +do_test shell5-1.9 { + set out [open shell5.csv w] + fconfigure $out -translation lf + puts $out {1,"",11} + puts $out {2,"x",22} + puts $out {3,"""",33} + puts $out {4,"hello",44} + puts $out "5,55,\"\"\r" + puts $out {6,66,"x"} + puts $out {7,77,""""} + puts $out {8,88,"hello"} + puts $out {"",9,99} + puts $out {"x",10,110} + puts $out {"""",11,121} + puts $out {"hello",12,132} + close $out + forcedelete test.db + catchcmd test.db {.mode csv + CREATE TABLE t1(a,b,c); +.import shell5.csv t1 + } + sqlite3 db test.db + db eval {SELECT *, '|' FROM t1 ORDER BY rowid} +} {1 {} 11 | 2 x 22 | 3 {"} 33 | 4 hello 44 | 5 55 {} | 6 66 x | 7 77 {"} | 8 88 hello | {} 9 99 | x 10 110 | {"} 11 121 | hello 12 132 |} +db close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/shortread1.test b/components/external/SQLite-3.8.1/test/shortread1.test new file mode 100644 index 0000000000000000000000000000000000000000..647f2ff674fedf4e184a551462337e5caa6dc8f6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shortread1.test @@ -0,0 +1,52 @@ +# 2007 Sep 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file attempts to duplicate an error scenario seen on a +# customer system using version 3.2.2. The problem appears to +# have been fixed (perhaps by accident) with check-in [3503]. +# These tests will prevent an accidental recurrance. +# +# $Id: shortread1.test,v 1.1 2007/09/14 01:48:12 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test shortread1-1.1 { + execsql { + CREATE TABLE t1(a TEXT); + BEGIN; + INSERT INTO t1 VALUES(hex(randomblob(5000))); + INSERT INTO t1 VALUES(hex(randomblob(100))); + PRAGMA freelist_count; + } +} {0} +do_test shortread1-1.2 { + execsql { + DELETE FROM t1 WHERE rowid=1; + PRAGMA freelist_count; + } +} {11} +do_test shortread1-1.3 { + sqlite3_release_memory [expr {1024*9}] + execsql { + INSERT INTO t1 VALUES(hex(randomblob(5000))); + PRAGMA freelist_count; + } +} {0} +do_test shortread1-1.4 { + execsql { + COMMIT; + SELECT count(*) FROM t1; + } +} {2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/shrink.test b/components/external/SQLite-3.8.1/test/shrink.test new file mode 100644 index 0000000000000000000000000000000000000000..e03ebeeb6ecab22d1bb6444736b493f6a8bd8a98 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/shrink.test @@ -0,0 +1,43 @@ +# 2011 November 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains test cases for sqlite3_db_release_memory and +# the PRAGMA shrink_memory statement. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +unset -nocomplain baseline +do_test shrink-1.1 { + db eval { + PRAGMA cache_size = 2000; + CREATE TABLE t1(x,y); + INSERT INTO t1 VALUES(randomblob(1000000),1); + } + set ::baseline sqlite3_memory_used + sqlite3_db_release_memory db + expr {$::baseline > [sqlite3_memory_used]+500000} +} {1} +do_test shrink-1.2 { + set baseline [sqlite3_memory_used] + db eval { + UPDATE t1 SET y=y+1; + } + expr {$::baseline+500000 < [sqlite3_memory_used]} +} {1} +do_test shrink-1.3 { + set baseline [sqlite3_memory_used] + db eval {PRAGMA shrink_memory} + expr {$::baseline > [sqlite3_memory_used]+500000} +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/sidedelete.test b/components/external/SQLite-3.8.1/test/sidedelete.test new file mode 100644 index 0000000000000000000000000000000000000000..04e457d8504c429b3188d32b3cb59dcc3445195d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/sidedelete.test @@ -0,0 +1,92 @@ +# 2007 Dec 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains test cases for stressing database +# changes that involve side effects that delete rows from +# the table being changed. Ticket #2832 shows that in +# older versions of SQLite that behavior was implemented +# incorrectly and resulted in corrupt database files. +# +# $Id: sidedelete.test,v 1.2 2008/08/04 03:51:24 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# The sequence table is created to store a sequence of integers +# starting with 1. This is used to reinitialize other tables +# as part of other tests. +# +do_test sidedelete-1.1 { + execsql { + CREATE TABLE sequence(a INTEGER PRIMARY KEY); + INSERT INTO sequence VALUES(1); + INSERT INTO sequence VALUES(2); + } + for {set i 0} {$i<8} {incr i} { + execsql { + INSERT INTO sequence SELECT a+(SELECT max(a) FROM sequence) FROM sequence; + } + } + execsql {SELECT count(*) FROM sequence} +} {512} + +# Make a series of changes using an UPDATE OR REPLACE and a +# correlated subquery. This would cause database corruption +# prior to the fix for ticket #2832. +# +do_test sidedelete-2.0 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TABLE chng(a PRIMARY KEY, b); + SELECT count(*) FROM t1; + SELECT count(*) FROM chng; + } +} {0 0} +for {set i 2} {$i<=100} {incr i} { + set n [expr {($i+2)/2}] + do_test sidedelete-2.$i.1 { + execsql { + DELETE FROM t1; + INSERT INTO t1 SELECT a, a FROM sequence WHERE a<=$i; + DELETE FROM chng; + INSERT INTO chng SELECT a*2, a*2+1 FROM sequence WHERE a<=$i/2; + UPDATE OR REPLACE t1 SET a=(SELECT b FROM chng WHERE a=t1.a); + SELECT count(*), sum(a) FROM t1; + } + } [list $n [expr {$n*$n-1}]] + integrity_check sidedelete-2.$i.2 +} + +# This will cause stacks leaks but not database corruption prior +# to the #2832 fix. +# +do_test sidedelete-3.0 { + execsql { + DROP TABLE t1; + CREATE TABLE t1(a PRIMARY KEY); + SELECT * FROM t1; + } +} {} +for {set i 1} {$i<=100} {incr i} { + set n [expr {($i+1)/2}] + do_test sidedelete-3.$i.1 { + execsql { + DELETE FROM t1; + INSERT INTO t1 SELECT a FROM sequence WHERE a<=$i; + UPDATE OR REPLACE t1 SET a=a+1; + SELECT count(*), sum(a) FROM t1; + } + } [list $n [expr {$n*($n+1)}]] + integrity_check sidedelete-3.$i.2 +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/soak.test b/components/external/SQLite-3.8.1/test/soak.test new file mode 100644 index 0000000000000000000000000000000000000000..c457dec4a957a44b6daafc43c4944554449b2ea6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/soak.test @@ -0,0 +1,90 @@ +# 2007 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file is the driver for the "soak" tests. It is a peer of the +# quick.test and all.test scripts. +# +# $Id: soak.test,v 1.4 2008/11/13 18:29:51 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +rename finish_test really_finish_test +proc finish_test {} {} + +# By default, guarantee that the tests will run for at least 1 hour. +# +set TIMEOUT 3600 + +# Process command-line arguments. +# +if {[llength $argv]>0} { + foreach {name value} $argv { + switch -- $name { + -timeout { + set TIMEOUT $value + } + default { + puts stderr "Unknown option: $name" + exit + } + } + } +} +set argv [list] + +# Test plan: +# +# The general principle is to run those SQLite tests that use +# pseudo-random data in some way over and over again for a very +# long time. The number of tests run depends on the value of +# global variable $TIMEOUT - tests are run for at least $TIMEOUT +# seconds. +# +# fuzz.test (pseudo-random SQL statements) +# trans.test (pseudo-random changes to a database followed by rollbacks) +# fuzz_malloc.test +# corruptC.test (pseudo-random corruption to a database) +# +# Many database changes maintaining some kind of invariant. +# Storing checksums etc. +# + +# List of test files that are run by this file. +# +set SOAKTESTS { + fuzz.test + fuzz_malloc.test + trans.test + corruptC.test +} + +set G(isquick) 1 + +set soak_starttime [clock seconds] +set soak_finishtime [expr {$soak_starttime + $TIMEOUT}] + +# Loop until the timeout is reached or an error occurs. +# +for {set iRun 0} {[clock seconds] < $soak_finishtime} {incr iRun} { + + set iIdx [expr {$iRun % [llength $SOAKTESTS]}] + source [file join $testdir [lindex $SOAKTESTS $iIdx]] + catch {db close} + + if {$sqlite_open_file_count>0} { + puts "$tail did not close all files: $sqlite_open_file_count" + fail_test $tail + set sqlite_open_file_count 0 + } + + if {[set_test_counter errors]>0} break +} + +really_finish_test diff --git a/components/external/SQLite-3.8.1/test/softheap1.test b/components/external/SQLite-3.8.1/test/softheap1.test new file mode 100644 index 0000000000000000000000000000000000000000..522e455e339cc81fa7fd679e7334ce6ec35afc2a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/softheap1.test @@ -0,0 +1,66 @@ +# 2007 Aug 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test script reproduces the problem reported by ticket #2565, +# A database corruption bug that occurs in auto_vacuum mode when +# the soft_heap_limit is set low enough to be triggered. +# +# $Id: softheap1.test,v 1.5 2008/07/08 17:13:59 danielk1977 Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !integrityck { + finish_test + return +} + +do_test softheap1-1.0 { + execsql {PRAGMA soft_heap_limit} +} [sqlite3_soft_heap_limit -1] +do_test softheap1-1.1 { + execsql {PRAGMA soft_heap_limit=123456; PRAGMA soft_heap_limit;} +} {123456 123456} +do_test softheap1-1.2 { + sqlite3_soft_heap_limit -1 +} {123456} +do_test softheap1-1.3 { + execsql {PRAGMA soft_heap_limit(-1); PRAGMA soft_heap_limit;} +} {123456 123456} +do_test softheap1-1.4 { + execsql {PRAGMA soft_heap_limit(0); PRAGMA soft_heap_limit;} +} {0 0} + +sqlite3_soft_heap_limit 5000 +do_test softheap1-2.0 { + execsql {PRAGMA soft_heap_limit} +} {5000} +do_test softheap1-2.1 { + execsql { + PRAGMA auto_vacuum=1; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(hex(randomblob(1000))); + BEGIN; + } + execsql { + CREATE TABLE t2 AS SELECT * FROM t1; + } + execsql { + ROLLBACK; + } + execsql { + PRAGMA integrity_check; + } +} {ok} + +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) +finish_test diff --git a/components/external/SQLite-3.8.1/test/sort.test b/components/external/SQLite-3.8.1/test/sort.test new file mode 100644 index 0000000000000000000000000000000000000000..08d496b2596a0380455034930d974f4e20a816c2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/sort.test @@ -0,0 +1,467 @@ +# 2001 September 15. +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the CREATE TABLE statement. +# +# $Id: sort.test,v 1.25 2005/11/14 22:29:06 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a bunch of data to sort against +# +do_test sort-1.0 { + execsql { + CREATE TABLE t1( + n int, + v varchar(10), + log int, + roman varchar(10), + flt real + ); + INSERT INTO t1 VALUES(1,'one',0,'I',3.141592653); + INSERT INTO t1 VALUES(2,'two',1,'II',2.15); + INSERT INTO t1 VALUES(3,'three',1,'III',4221.0); + INSERT INTO t1 VALUES(4,'four',2,'IV',-0.0013442); + INSERT INTO t1 VALUES(5,'five',2,'V',-11); + INSERT INTO t1 VALUES(6,'six',2,'VI',0.123); + INSERT INTO t1 VALUES(7,'seven',2,'VII',123.0); + INSERT INTO t1 VALUES(8,'eight',3,'VIII',-1.6); + } + execsql {SELECT count(*) FROM t1} +} {8} + +do_test sort-1.1 { + execsql {SELECT n FROM t1 ORDER BY n} +} {1 2 3 4 5 6 7 8} +do_test sort-1.1.1 { + execsql {SELECT n FROM t1 ORDER BY n ASC} +} {1 2 3 4 5 6 7 8} +do_test sort-1.1.1 { + execsql {SELECT ALL n FROM t1 ORDER BY n ASC} +} {1 2 3 4 5 6 7 8} +do_test sort-1.2 { + execsql {SELECT n FROM t1 ORDER BY n DESC} +} {8 7 6 5 4 3 2 1} +do_test sort-1.3a { + execsql {SELECT v FROM t1 ORDER BY v} +} {eight five four one seven six three two} +do_test sort-1.3b { + execsql {SELECT n FROM t1 ORDER BY v} +} {8 5 4 1 7 6 3 2} +do_test sort-1.4 { + execsql {SELECT n FROM t1 ORDER BY v DESC} +} {2 3 6 7 1 4 5 8} +do_test sort-1.5 { + execsql {SELECT flt FROM t1 ORDER BY flt} +} {-11.0 -1.6 -0.0013442 0.123 2.15 3.141592653 123.0 4221.0} +do_test sort-1.6 { + execsql {SELECT flt FROM t1 ORDER BY flt DESC} +} {4221.0 123.0 3.141592653 2.15 0.123 -0.0013442 -1.6 -11.0} +do_test sort-1.7 { + execsql {SELECT roman FROM t1 ORDER BY roman} +} {I II III IV V VI VII VIII} +do_test sort-1.8 { + execsql {SELECT n FROM t1 ORDER BY log, flt} +} {1 2 3 5 4 6 7 8} +do_test sort-1.8.1 { + execsql {SELECT n FROM t1 ORDER BY log asc, flt} +} {1 2 3 5 4 6 7 8} +do_test sort-1.8.2 { + execsql {SELECT n FROM t1 ORDER BY log, flt ASC} +} {1 2 3 5 4 6 7 8} +do_test sort-1.8.3 { + execsql {SELECT n FROM t1 ORDER BY log ASC, flt asc} +} {1 2 3 5 4 6 7 8} +do_test sort-1.9 { + execsql {SELECT n FROM t1 ORDER BY log, flt DESC} +} {1 3 2 7 6 4 5 8} +do_test sort-1.9.1 { + execsql {SELECT n FROM t1 ORDER BY log ASC, flt DESC} +} {1 3 2 7 6 4 5 8} +do_test sort-1.10 { + execsql {SELECT n FROM t1 ORDER BY log DESC, flt} +} {8 5 4 6 7 2 3 1} +do_test sort-1.11 { + execsql {SELECT n FROM t1 ORDER BY log DESC, flt DESC} +} {8 7 6 4 5 3 2 1} + +# These tests are designed to reach some hard-to-reach places +# inside the string comparison routines. +# +# (Later) The sorting behavior changed in 2.7.0. But we will +# keep these tests. You can never have too many test cases! +# +do_test sort-2.1.1 { + execsql { + UPDATE t1 SET v='x' || -flt; + UPDATE t1 SET v='x-2b' where v=='x-0.123'; + SELECT v FROM t1 ORDER BY v; + } +} {x-123.0 x-2.15 x-2b x-3.141592653 x-4221.0 x0.0013442 x1.6 x11.0} +do_test sort-2.1.2 { + execsql { + SELECT v FROM t1 ORDER BY substr(v,2,999); + } +} {x-123.0 x-2.15 x-2b x-3.141592653 x-4221.0 x0.0013442 x1.6 x11.0} +do_test sort-2.1.3 { + execsql { + SELECT v FROM t1 ORDER BY substr(v,2,999)+0.0; + } +} {x-4221.0 x-123.0 x-3.141592653 x-2.15 x-2b x0.0013442 x1.6 x11.0} +do_test sort-2.1.4 { + execsql { + SELECT v FROM t1 ORDER BY substr(v,2,999) DESC; + } +} {x11.0 x1.6 x0.0013442 x-4221.0 x-3.141592653 x-2b x-2.15 x-123.0} +do_test sort-2.1.5 { + execsql { + SELECT v FROM t1 ORDER BY substr(v,2,999)+0.0 DESC; + } +} {x11.0 x1.6 x0.0013442 x-2b x-2.15 x-3.141592653 x-123.0 x-4221.0} + +# This is a bug fix for 2.2.4. +# Strings are normally mapped to upper-case for a caseless comparison. +# But this can cause problems for characters in between 'Z' and 'a'. +# +do_test sort-3.1 { + execsql { + CREATE TABLE t2(a,b); + INSERT INTO t2 VALUES('AGLIENTU',1); + INSERT INTO t2 VALUES('AGLIE`',2); + INSERT INTO t2 VALUES('AGNA',3); + SELECT a, b FROM t2 ORDER BY a; + } +} {AGLIENTU 1 AGLIE` 2 AGNA 3} +do_test sort-3.2 { + execsql { + SELECT a, b FROM t2 ORDER BY a DESC; + } +} {AGNA 3 AGLIE` 2 AGLIENTU 1} +do_test sort-3.3 { + execsql { + DELETE FROM t2; + INSERT INTO t2 VALUES('aglientu',1); + INSERT INTO t2 VALUES('aglie`',2); + INSERT INTO t2 VALUES('agna',3); + SELECT a, b FROM t2 ORDER BY a; + } +} {aglie` 2 aglientu 1 agna 3} +do_test sort-3.4 { + execsql { + SELECT a, b FROM t2 ORDER BY a DESC; + } +} {agna 3 aglientu 1 aglie` 2} + +# Version 2.7.0 testing. +# +do_test sort-4.1 { + execsql { + INSERT INTO t1 VALUES(9,'x2.7',3,'IX',4.0e5); + INSERT INTO t1 VALUES(10,'x5.0e10',3,'X',-4.0e5); + INSERT INTO t1 VALUES(11,'x-4.0e9',3,'XI',4.1e4); + INSERT INTO t1 VALUES(12,'x01234567890123456789',3,'XII',-4.2e3); + SELECT n FROM t1 ORDER BY n; + } +} {1 2 3 4 5 6 7 8 9 10 11 12} +do_test sort-4.2 { + execsql { + SELECT n||'' FROM t1 ORDER BY 1; + } +} {1 10 11 12 2 3 4 5 6 7 8 9} +do_test sort-4.3 { + execsql { + SELECT n+0 FROM t1 ORDER BY 1; + } +} {1 2 3 4 5 6 7 8 9 10 11 12} +do_test sort-4.4 { + execsql { + SELECT n||'' FROM t1 ORDER BY 1 DESC; + } +} {9 8 7 6 5 4 3 2 12 11 10 1} +do_test sort-4.5 { + execsql { + SELECT n+0 FROM t1 ORDER BY 1 DESC; + } +} {12 11 10 9 8 7 6 5 4 3 2 1} +do_test sort-4.6 { + execsql { + SELECT v FROM t1 ORDER BY 1; + } +} {x-123.0 x-2.15 x-2b x-3.141592653 x-4.0e9 x-4221.0 x0.0013442 x01234567890123456789 x1.6 x11.0 x2.7 x5.0e10} +do_test sort-4.7 { + execsql { + SELECT v FROM t1 ORDER BY 1 DESC; + } +} {x5.0e10 x2.7 x11.0 x1.6 x01234567890123456789 x0.0013442 x-4221.0 x-4.0e9 x-3.141592653 x-2b x-2.15 x-123.0} +do_test sort-4.8 { + execsql { + SELECT substr(v,2,99) FROM t1 ORDER BY 1; + } +} {-123.0 -2.15 -2b -3.141592653 -4.0e9 -4221.0 0.0013442 01234567890123456789 1.6 11.0 2.7 5.0e10} +#do_test sort-4.9 { +# execsql { +# SELECT substr(v,2,99)+0.0 FROM t1 ORDER BY 1; +# } +#} {-4000000000 -4221 -123 -3.141592653 -2.15 -2 0.0013442 1.6 2.7 11 50000000000 1.23456789012346e+18} + +do_test sort-5.1 { + execsql { + create table t3(a,b); + insert into t3 values(5,NULL); + insert into t3 values(6,NULL); + insert into t3 values(3,NULL); + insert into t3 values(4,'cd'); + insert into t3 values(1,'ab'); + insert into t3 values(2,NULL); + select a from t3 order by b, a; + } +} {2 3 5 6 1 4} +do_test sort-5.2 { + execsql { + select a from t3 order by b, a desc; + } +} {6 5 3 2 1 4} +do_test sort-5.3 { + execsql { + select a from t3 order by b desc, a; + } +} {4 1 2 3 5 6} +do_test sort-5.4 { + execsql { + select a from t3 order by b desc, a desc; + } +} {4 1 6 5 3 2} + +do_test sort-6.1 { + execsql { + create index i3 on t3(b,a); + select a from t3 order by b, a; + } +} {2 3 5 6 1 4} +do_test sort-6.2 { + execsql { + select a from t3 order by b, a desc; + } +} {6 5 3 2 1 4} +do_test sort-6.3 { + execsql { + select a from t3 order by b desc, a; + } +} {4 1 2 3 5 6} +do_test sort-6.4 { + execsql { + select a from t3 order by b desc, a desc; + } +} {4 1 6 5 3 2} + +do_test sort-7.1 { + execsql { + CREATE TABLE t4( + a INTEGER, + b VARCHAR(30) + ); + INSERT INTO t4 VALUES(1,1); + INSERT INTO t4 VALUES(2,2); + INSERT INTO t4 VALUES(11,11); + INSERT INTO t4 VALUES(12,12); + SELECT a FROM t4 ORDER BY 1; + } +} {1 2 11 12} +do_test sort-7.2 { + execsql { + SELECT b FROM t4 ORDER BY 1 + } +} {1 11 12 2} + +# Omit tests sort-7.3 to sort-7.8 if view support was disabled at +# compilatation time. +ifcapable view { +do_test sort-7.3 { + execsql { + CREATE VIEW v4 AS SELECT * FROM t4; + SELECT a FROM v4 ORDER BY 1; + } +} {1 2 11 12} +do_test sort-7.4 { + execsql { + SELECT b FROM v4 ORDER BY 1; + } +} {1 11 12 2} + +ifcapable compound { +do_test sort-7.5 { + execsql { + SELECT a FROM t4 UNION SELECT a FROM v4 ORDER BY 1; + } +} {1 2 11 12} +do_test sort-7.6 { + execsql { + SELECT b FROM t4 UNION SELECT a FROM v4 ORDER BY 1; + } +} {1 2 11 12 1 11 12 2} ;# text from t4.b and numeric from v4.a +do_test sort-7.7 { + execsql { + SELECT a FROM t4 UNION SELECT b FROM v4 ORDER BY 1; + } +} {1 2 11 12 1 11 12 2} ;# numeric from t4.a and text from v4.b +do_test sort-7.8 { + execsql { + SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1; + } +} {1 11 12 2} +} ;# ifcapable compound +} ;# ifcapable view + +#### Version 3 works differently here: +#do_test sort-7.9 { +# execsql { +# SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE numeric; +# } +#} {1 2 11 12} +#do_test sort-7.10 { +# execsql { +# SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE integer; +# } +#} {1 2 11 12} +#do_test sort-7.11 { +# execsql { +# SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE text; +# } +#} {1 11 12 2} +#do_test sort-7.12 { +# execsql { +# SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE blob; +# } +#} {1 11 12 2} +#do_test sort-7.13 { +# execsql { +# SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE clob; +# } +#} {1 11 12 2} +#do_test sort-7.14 { +# execsql { +# SELECT b FROM t4 UNION SELECT b FROM v4 ORDER BY 1 COLLATE varchar; +# } +#} {1 11 12 2} + +# Ticket #297 +# +do_test sort-8.1 { + execsql { + CREATE TABLE t5(a real, b text); + INSERT INTO t5 VALUES(100,'A1'); + INSERT INTO t5 VALUES(100.0,'A2'); + SELECT * FROM t5 ORDER BY a, b; + } +} {100.0 A1 100.0 A2} + + +ifcapable {bloblit} { +# BLOBs should sort after TEXT +# +do_test sort-9.1 { + execsql { + CREATE TABLE t6(x, y); + INSERT INTO t6 VALUES(1,1); + INSERT INTO t6 VALUES(2,'1'); + INSERT INTO t6 VALUES(3,x'31'); + INSERT INTO t6 VALUES(4,NULL); + SELECT x FROM t6 ORDER BY y; + } +} {4 1 2 3} +do_test sort-9.2 { + execsql { + SELECT x FROM t6 ORDER BY y DESC; + } +} {3 2 1 4} +do_test sort-9.3 { + execsql { + SELECT x FROM t6 WHERE y<1 + } +} {} +do_test sort-9.4 { + execsql { + SELECT x FROM t6 WHERE y<'1' + } +} {1} +do_test sort-9.5 { + execsql { + SELECT x FROM t6 WHERE y1 + } +} {2 3} +do_test sort-9.7 { + execsql { + SELECT x FROM t6 WHERE y>'1' + } +} {3} +} ;# endif bloblit + +# Ticket #1092 - ORDER BY on rowid fields. +do_test sort-10.1 { + execsql { + CREATE TABLE t7(c INTEGER PRIMARY KEY); + INSERT INTO t7 VALUES(1); + INSERT INTO t7 VALUES(2); + INSERT INTO t7 VALUES(3); + INSERT INTO t7 VALUES(4); + } +} {} +do_test sort-10.2 { + execsql { + SELECT c FROM t7 WHERE c<=3 ORDER BY c DESC; + } +} {3 2 1} +do_test sort-10.3 { + execsql { + SELECT c FROM t7 WHERE c<3 ORDER BY c DESC; + } +} {2 1} + +# ticket #1358. Just because one table in a join gives a unique +# result does not mean they all do. We cannot disable sorting unless +# all tables in the join give unique results. +# +do_test sort-11.1 { + execsql { + create table t8(a unique, b, c); + insert into t8 values(1,2,3); + insert into t8 values(2,3,4); + create table t9(x,y); + insert into t9 values(2,4); + insert into t9 values(2,3); + select y from t8, t9 where a=1 order by a, y; + } +} {3 4} + +# Trouble reported on the mailing list. Check for overly aggressive +# (which is to say, incorrect) optimization of order-by with a rowid +# in a join. +# +do_test sort-12.1 { + execsql { + create table a (id integer primary key); + create table b (id integer primary key, aId integer, text); + insert into a values (1); + insert into b values (2, 1, 'xxx'); + insert into b values (1, 1, 'zzz'); + insert into b values (3, 1, 'yyy'); + select a.id, b.id, b.text from a join b on (a.id = b.aId) + order by a.id, b.text; + } +} {1 2 xxx 1 3 yyy 1 1 zzz} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/speed1.test b/components/external/SQLite-3.8.1/test/speed1.test new file mode 100644 index 0000000000000000000000000000000000000000..86d13ba4aee7d005c24a1979ac24c532707405ec --- /dev/null +++ b/components/external/SQLite-3.8.1/test/speed1.test @@ -0,0 +1,298 @@ +# 2006 November 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is measuring executing speed. +# +# $Id: speed1.test,v 1.11 2009/04/09 01:23:49 drh Exp $ +# + +sqlite3_shutdown +#sqlite3_config_scratch 29000 1 +set old_lookaside [sqlite3_config_lookaside 1000 300] +#sqlite3_config_pagecache 1024 10000 +set testdir [file dirname $argv0] +source $testdir/tester.tcl +speed_trial_init speed1 + +# Set a uniform random seed +expr srand(0) + +set sqlout [open speed1.txt w] +proc tracesql {sql} { + puts $::sqlout $sql\; +} +#db trace tracesql + +# The number_name procedure below converts its argment (an integer) +# into a string which is the English-language name for that number. +# +# Example: +# +# puts [number_name 123] -> "one hundred twenty three" +# +set ones {zero one two three four five six seven eight nine + ten eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen} +set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} +proc number_name {n} { + if {$n>=1000} { + set txt "[number_name [expr {$n/1000}]] thousand" + set n [expr {$n%1000}] + } else { + set txt {} + } + if {$n>=100} { + append txt " [lindex $::ones [expr {$n/100}]] hundred" + set n [expr {$n%100}] + } + if {$n>=20} { + append txt " [lindex $::tens [expr {$n/10}]]" + set n [expr {$n%10}] + } + if {$n>0} { + append txt " [lindex $::ones $n]" + } + set txt [string trim $txt] + if {$txt==""} {set txt zero} + return $txt +} + +# Create a database schema. +# +do_test speed1-1.0 { + execsql { + PRAGMA page_size=1024; + PRAGMA cache_size=8192; + PRAGMA locking_mode=EXCLUSIVE; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); + CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT); + CREATE INDEX i2a ON t2(a); + CREATE INDEX i2b ON t2(b); + } + execsql { + SELECT name FROM sqlite_master ORDER BY 1; + } +} {i2a i2b t1 t2} + + +# 50000 INSERTs on an unindexed table +# +set sql {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + append sql "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');\n" +} +db eval BEGIN +speed_trial speed1-insert1 50000 row $sql +db eval COMMIT + +# 50000 INSERTs on an indexed table +# +set sql {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + append sql "INSERT INTO t2 VALUES($i,$r,'[number_name $r]');\n" +} +db eval BEGIN +speed_trial speed1-insert2 50000 row $sql +db eval COMMIT + + + +# 50 SELECTs on an integer comparison. There is no index so +# a full table scan is required. +# +set sql {} +for {set i 0} {$i<50} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" +} +db eval BEGIN +speed_trial speed1-select1 [expr {50*50000}] row $sql +db eval COMMIT + +# 50 SELECTs on an LIKE comparison. There is no index so a full +# table scan is required. +# +set sql {} +for {set i 0} {$i<50} {incr i} { + append sql \ + "SELECT count(*), avg(b) FROM t1 WHERE c LIKE '%[number_name $i]%';" +} +db eval BEGIN +speed_trial speed1-select2 [expr {50*50000}] row $sql +db eval COMMIT + +# Create indices +# +db eval BEGIN +speed_trial speed1-createidx 150000 row { + CREATE INDEX i1a ON t1(a); + CREATE INDEX i1b ON t1(b); + CREATE INDEX i1c ON t1(c); +} +db eval COMMIT + +# 5000 SELECTs on an integer comparison where the integer is +# indexed. +# +set sql {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" +} +db eval BEGIN +speed_trial speed1-select3 5000 stmt $sql +db eval COMMIT + +# 100000 random SELECTs against rowid. +# +set sql {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + append sql "SELECT c FROM t1 WHERE rowid=$id;" +} +db eval BEGIN +speed_trial speed1-select4 100000 row $sql +db eval COMMIT + +# 100000 random SELECTs against a unique indexed column. +# +set sql {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + append sql "SELECT c FROM t1 WHERE a=$id;" +} +db eval BEGIN +speed_trial speed1-select5 100000 row $sql +db eval COMMIT + +# 50000 random SELECTs against an indexed column text column +# +set sql {} +db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000} { + append sql "SELECT c FROM t1 WHERE c='$c';" +} +db eval BEGIN +speed_trial speed1-select6 50000 row $sql +db eval COMMIT + + +# Vacuum +speed_trial speed1-vacuum 100000 row VACUUM + +# 5000 updates of ranges where the field being compared is indexed. +# +set sql {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*2}] + set upr [expr {($i+1)*2}] + append sql "UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr;" +} +db eval BEGIN +speed_trial speed1-update1 5000 stmt $sql +db eval COMMIT + +# 50000 single-row updates. An index is used to find the row quickly. +# +set sql {} +for {set i 0} {$i<50000} {incr i} { + set r [expr {int(rand()*500000)}] + append sql "UPDATE t1 SET b=$r WHERE a=$i;" +} +db eval BEGIN +speed_trial speed1-update2 50000 row $sql +db eval COMMIT + +# 1 big text update that touches every row in the table. +# +speed_trial speed1-update3 50000 row { + UPDATE t1 SET c=a; +} + +# Many individual text updates. Each row in the table is +# touched through an index. +# +set sql {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + append sql "UPDATE t1 SET c='[number_name $r]' WHERE a=$i;" +} +db eval BEGIN +speed_trial speed1-update4 50000 row $sql +db eval COMMIT + +# Delete all content in a table. +# +speed_trial speed1-delete1 50000 row {DELETE FROM t1} + +# Copy one table into another +# +speed_trial speed1-copy1 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Delete all content in a table, one row at a time. +# +speed_trial speed1-delete2 50000 row {DELETE FROM t1 WHERE 1} + +# Refill the table yet again +# +speed_trial speed1-copy2 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Drop the table and recreate it without its indices. +# +db eval BEGIN +speed_trial speed1-drop1 50000 row { + DROP TABLE t1; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); +} +db eval COMMIT + +# Refill the table yet again. This copy should be faster because +# there are no indices to deal with. +# +speed_trial speed1-copy3 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Select 20000 rows from the table at random. +# +speed_trial speed1-random1 50000 row { + SELECT rowid FROM t1 ORDER BY random() LIMIT 20000 +} + +# Delete 20000 random rows from the table. +# +speed_trial speed1-random-del1 20000 row { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000) +} +do_test speed1-1.1 { + db one {SELECT count(*) FROM t1} +} 30000 + + +# Delete 20000 more rows at random from the table. +# +speed_trial speed1-random-del2 20000 row { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000) +} +do_test speed1-1.2 { + db one {SELECT count(*) FROM t1} +} 10000 +speed_trial_summary speed1 + +db close +sqlite3_shutdown +eval sqlite3_config_lookaside $old_lookaside +sqlite3_initialize +autoinstall_test_functions +finish_test diff --git a/components/external/SQLite-3.8.1/test/speed1p.explain b/components/external/SQLite-3.8.1/test/speed1p.explain new file mode 100644 index 0000000000000000000000000000000000000000..e32feddf304e2940ae4cedbf53fb9d2cf9b4106d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/speed1p.explain @@ -0,0 +1,366 @@ +# 2008 March 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is measuring executing speed. +# +# This is a copy of speed1.test modified to user prepared statements. +# +# $Id: speed1p.explain,v 1.1 2008/04/16 12:57:48 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +speed_trial_init speed1 + +# Set a uniform random seed +expr srand(0) + +set sqlout [open speed1.txt w] +proc tracesql {sql} { + puts $::sqlout $sql\; +} +#db trace tracesql + +# The number_name procedure below converts its argment (an integer) +# into a string which is the English-language name for that number. +# +# Example: +# +# puts [number_name 123] -> "one hundred twenty three" +# +set ones {zero one two three four five six seven eight nine + ten eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen} +set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} +proc number_name {n} { + if {$n>=1000} { + set txt "[number_name [expr {$n/1000}]] thousand" + set n [expr {$n%1000}] + } else { + set txt {} + } + if {$n>=100} { + append txt " [lindex $::ones [expr {$n/100}]] hundred" + set n [expr {$n%100}] + } + if {$n>=20} { + append txt " [lindex $::tens [expr {$n/10}]]" + set n [expr {$n%10}] + } + if {$n>0} { + append txt " [lindex $::ones $n]" + } + set txt [string trim $txt] + if {$txt==""} {set txt zero} + return $txt +} + +# Create a database schema. +# +do_test speed1p-1.0 { + execsql { + PRAGMA page_size=1024; + PRAGMA cache_size=8192; + PRAGMA locking_mode=EXCLUSIVE; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); + CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT); + CREATE INDEX i2a ON t2(a); + CREATE INDEX i2b ON t2(b); + } + execsql { + SELECT name FROM sqlite_master ORDER BY 1; + } +} {i2a i2b t1 t2} + + +# 50000 INSERTs on an unindexed table +# +set list {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + set x [number_name $r] + lappend list $i $r $x +} +set script { + foreach {i r x} $::list { + db eval {INSERT INTO t1 VALUES($i,$r,$x)} + } +} +explain {INSERT INTO t1 VALUES($i,$r,$x)} +db eval BEGIN +speed_trial_tcl speed1p-insert1 50000 row $script +db eval COMMIT + +# 50000 INSERTs on an indexed table +# +set list {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + set x [number_name $r] + lappend list $i $r $x +} +set script { + foreach {i r x} $::list { + db eval {INSERT INTO t2 VALUES($i,$r,$x)} + } +} +explain {INSERT INTO t2 VALUES($i,$r,$x)} +db eval BEGIN +speed_trial_tcl speed1p-insert2 50000 row $script +db eval COMMIT + + + +# 50 SELECTs on an integer comparison. There is no index so +# a full table scan is required. +# +set list {} +for {set i 0} {$i<50} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + lappend list $lwr $upr +} +set script { + foreach {lwr upr} $::list { + db eval {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr} + } +} +explain {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr} +db eval BEGIN +speed_trial_tcl speed1p-select1 [expr {50*50000}] row $script +db eval COMMIT + +# 50 SELECTs on an LIKE comparison. There is no index so a full +# table scan is required. +# +set list {} +for {set i 0} {$i<50} {incr i} { + lappend list "%[number_name $i]%" +} +set script { + foreach pattern $::list { + db eval {SELECT count(*), avg(b) FROM t1 WHERE c LIKE $pattern} + } +} +explain {SELECT count(*), avg(b) FROM t1 WHERE c LIKE $pattern} +db eval BEGIN +speed_trial_tcl speed1p-select2 [expr {50*50000}] row $script +db eval COMMIT + +# Create indices +# +explain {CREATE INDEX i1a ON t1(a)} +explain {CREATE INDEX i1b ON t1(b)} +db eval BEGIN +speed_trial speed1p-createidx 150000 row { + CREATE INDEX i1a ON t1(a); + CREATE INDEX i1b ON t1(b); + CREATE INDEX i1c ON t1(c); +} +db eval COMMIT + +# 5000 SELECTs on an integer comparison where the integer is +# indexed. +# +set list {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + lappend list $lwr $upr +} +set script { + foreach {lwr upr} $::list { + db eval {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr} + } +} +explain {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr} +db eval BEGIN +speed_trial_tcl speed1p-select3 5000 stmt $script +db eval COMMIT + +# 100000 random SELECTs against rowid. +# +set list {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + lappend list $id +} +set script { + foreach id $::list { + db eval {SELECT c FROM t1 WHERE rowid=$id} + } +} +explain {SELECT c FROM t1 WHERE rowid=$id} +db eval BEGIN +speed_trial_tcl speed1p-select4 100000 row $script +db eval COMMIT + +# 100000 random SELECTs against a unique indexed column. +# +set list {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + lappend list $id +} +set script { + foreach id $::list { + db eval {SELECT c FROM t1 WHERE a=$id} + } +} +explain {SELECT c FROM t1 WHERE a=$id} +db eval BEGIN +speed_trial_tcl speed1p-select5 100000 row $script +db eval COMMIT + +# 50000 random SELECTs against an indexed column text column +# +set list [db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000}] +set script { + foreach c $::list { + db eval {SELECT c FROM t1 WHERE c=$c} + } +} +explain {SELECT c FROM t1 WHERE c=$c} +db eval BEGIN +speed_trial_tcl speed1p-select6 50000 row $script +db eval COMMIT + + +# Vacuum +speed_trial speed1p-vacuum 100000 row VACUUM + +# 5000 updates of ranges where the field being compared is indexed. +# +set list {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*2}] + set upr [expr {($i+1)*2}] + lappend list $lwr $upr +} +set script { + foreach {lwr upr} $::list { + db eval {UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr} + } +} +explain {UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr} +db eval BEGIN +speed_trial_tcl speed1p-update1 5000 stmt $script +db eval COMMIT + +# 50000 single-row updates. An index is used to find the row quickly. +# +set list {} +for {set i 0} {$i<50000} {incr i} { + set r [expr {int(rand()*500000)}] + lappend list $i $r +} +set script { + foreach {i r} $::list { + db eval {UPDATE t1 SET b=$r WHERE a=$i} + } +} +explain {UPDATE t1 SET b=$r WHERE a=$i} +db eval BEGIN +speed_trial_tcl speed1p-update2 50000 row $script +db eval COMMIT + +# 1 big text update that touches every row in the table. +# +explain {UPDATE t1 SET c=a} +speed_trial speed1p-update3 50000 row { + UPDATE t1 SET c=a; +} + +# Many individual text updates. Each row in the table is +# touched through an index. +# +set list {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + lappend list $i [number_name $r] +} +set script { + foreach {i x} $::list { + db eval {UPDATE t1 SET c=$x WHERE a=$i} + } +} +explain {UPDATE t1 SET c=$x WHERE a=$i} +db eval BEGIN +speed_trial_tcl speed1p-update4 50000 row $script +db eval COMMIT + +# Delete all content in a table. +# +explain {DELETE FROM t1} +speed_trial speed1p-delete1 50000 row {DELETE FROM t1} + +# Copy one table into another +# +explain {INSERT INTO t1 SELECT * FROM t2} +speed_trial speed1p-copy1 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Delete all content in a table, one row at a time. +# +explain {DELETE FROM t1 WHERE 1} +speed_trial speed1p-delete2 50000 row {DELETE FROM t1 WHERE 1} + +# Refill the table yet again +# +speed_trial speed1p-copy2 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Drop the table and recreate it without its indices. +# +explain {DROP TABLE t1} +explain {CREATE TABLE tX(a INTEGER, b INTEGER, c TEXT)} +db eval BEGIN +speed_trial speed1p-drop1 50000 row { + DROP TABLE t1; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); +} +db eval COMMIT + +# Refill the table yet again. This copy should be faster because +# there are no indices to deal with. +# +speed_trial speed1p-copy3 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Select 20000 rows from the table at random. +# +explain {SELECT rowid FROM t1 ORDER BY random() LIMIT 20000} +speed_trial speed1p-random1 50000 row { + SELECT rowid FROM t1 ORDER BY random() LIMIT 20000 +} + +# Delete 20000 random rows from the table. +# +explain {DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000)} +speed_trial speed1p-random-del1 20000 row { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000) +} +do_test speed1p-1.1 { + db one {SELECT count(*) FROM t1} +} 30000 + + +# Delete 20000 more rows at random from the table. +# +speed_trial speed1p-random-del2 20000 row { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000) +} +do_test speed1p-1.2 { + db one {SELECT count(*) FROM t1} +} 10000 +speed_trial_summary speed1 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/speed1p.test b/components/external/SQLite-3.8.1/test/speed1p.test new file mode 100644 index 0000000000000000000000000000000000000000..6bf7b10e1fa87142bd11bce2f8c59597f3105782 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/speed1p.test @@ -0,0 +1,347 @@ +# 2008 March 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is measuring executing speed. +# +# This is a copy of speed1.test modified to user prepared statements. +# +# $Id: speed1p.test,v 1.7 2009/04/09 01:23:49 drh Exp $ +# + +sqlite3_shutdown +#sqlite3_config_scratch 29000 1 +set old_lookaside [sqlite3_config_lookaside 2048 300] +#sqlite3_config_pagecache 1024 11000 +set testdir [file dirname $argv0] +source $testdir/tester.tcl +speed_trial_init speed1 + +sqlite3_memdebug_vfs_oom_test 0 + +# Set a uniform random seed +expr srand(0) + +# The number_name procedure below converts its argment (an integer) +# into a string which is the English-language name for that number. +# +# Example: +# +# puts [number_name 123] -> "one hundred twenty three" +# +set ones {zero one two three four five six seven eight nine + ten eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen} +set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} +proc number_name {n} { + if {$n>=1000} { + set txt "[number_name [expr {$n/1000}]] thousand" + set n [expr {$n%1000}] + } else { + set txt {} + } + if {$n>=100} { + append txt " [lindex $::ones [expr {$n/100}]] hundred" + set n [expr {$n%100}] + } + if {$n>=20} { + append txt " [lindex $::tens [expr {$n/10}]]" + set n [expr {$n%10}] + } + if {$n>0} { + append txt " [lindex $::ones $n]" + } + set txt [string trim $txt] + if {$txt==""} {set txt zero} + return $txt +} + +# Create a database schema. +# +do_test speed1p-1.0 { + execsql { + PRAGMA page_size=1024; + PRAGMA cache_size=500; + PRAGMA locking_mode=EXCLUSIVE; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); + CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT); + CREATE INDEX i2a ON t2(a); + CREATE INDEX i2b ON t2(b); + } + execsql { + SELECT name FROM sqlite_master ORDER BY 1; + } +} {i2a i2b t1 t2} + +# 50000 INSERTs on an unindexed table +# +set list {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + set x [number_name $r] + lappend list $i $r $x +} +set script { + foreach {i r x} $::list { + db eval {INSERT INTO t1 VALUES($i,$r,$x)} + } +} +db eval BEGIN +speed_trial_tcl speed1p-insert1 50000 row $script +db eval COMMIT + +# 50000 INSERTs on an indexed table +# +set list {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + set x [number_name $r] + lappend list $i $r $x +} +set script { + foreach {i r x} $::list { + db eval {INSERT INTO t2 VALUES($i,$r,$x)} + } +} +db eval BEGIN +speed_trial_tcl speed1p-insert2 50000 row $script +db eval COMMIT + + + +# 50 SELECTs on an integer comparison. There is no index so +# a full table scan is required. +# +set list {} +for {set i 0} {$i<50} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + lappend list $lwr $upr +} +set script { + foreach {lwr upr} $::list { + db eval {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr} + } +} +db eval BEGIN +speed_trial_tcl speed1p-select1 [expr {50*50000}] row $script +db eval COMMIT + +# 50 SELECTs on an LIKE comparison. There is no index so a full +# table scan is required. +# +set list {} +for {set i 0} {$i<50} {incr i} { + lappend list "%[number_name $i]%" +} +set script { + foreach pattern $::list { + db eval {SELECT count(*), avg(b) FROM t1 WHERE c LIKE $pattern} + } +} +db eval BEGIN +speed_trial_tcl speed1p-select2 [expr {50*50000}] row $script +db eval COMMIT + +# Create indices +# +db eval BEGIN +speed_trial speed1p-createidx 150000 row { + CREATE INDEX i1a ON t1(a); + CREATE INDEX i1b ON t1(b); + CREATE INDEX i1c ON t1(c); +} +db eval COMMIT + +# 5000 SELECTs on an integer comparison where the integer is +# indexed. +# +set list {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + lappend list $lwr $upr +} +set script { + foreach {lwr upr} $::list { + db eval {SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr} + } +} +db eval BEGIN +speed_trial_tcl speed1p-select3 5000 stmt $script +db eval COMMIT + +# 100000 random SELECTs against rowid. +# +set list {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + lappend list $id +} +set script { + foreach id $::list { + db eval {SELECT c FROM t1 WHERE rowid=$id} + } +} +db eval BEGIN +speed_trial_tcl speed1p-select4 100000 row $script +db eval COMMIT + +# 100000 random SELECTs against a unique indexed column. +# +set list {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + lappend list $id +} +set script { + foreach id $::list { + db eval {SELECT c FROM t1 WHERE a=$id} + } +} +db eval BEGIN +speed_trial_tcl speed1p-select5 100000 row $script +db eval COMMIT + +# 50000 random SELECTs against an indexed column text column +# +set list [db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000}] +set script { + foreach c $::list { + db eval {SELECT c FROM t1 WHERE c=$c} + } +} +db eval BEGIN +speed_trial_tcl speed1p-select6 50000 row $script +db eval COMMIT + + +# Vacuum +speed_trial speed1p-vacuum 100000 row VACUUM + +# 5000 updates of ranges where the field being compared is indexed. +# +set list {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*2}] + set upr [expr {($i+1)*2}] + lappend list $lwr $upr +} +set script { + foreach {lwr upr} $::list { + db eval {UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr} + } +} +db eval BEGIN +speed_trial_tcl speed1p-update1 5000 stmt $script +db eval COMMIT + +# 50000 single-row updates. An index is used to find the row quickly. +# +set list {} +for {set i 0} {$i<50000} {incr i} { + set r [expr {int(rand()*500000)}] + lappend list $i $r +} +set script { + foreach {i r} $::list { + db eval {UPDATE t1 SET b=$r WHERE a=$i} + } +} +db eval BEGIN +speed_trial_tcl speed1p-update2 50000 row $script +db eval COMMIT + +# 1 big text update that touches every row in the table. +# +speed_trial speed1p-update3 50000 row { + UPDATE t1 SET c=a; +} + +# Many individual text updates. Each row in the table is +# touched through an index. +# +set list {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + lappend list $i [number_name $r] +} +set script { + foreach {i x} $::list { + db eval {UPDATE t1 SET c=$x WHERE a=$i} + } +} +db eval BEGIN +speed_trial_tcl speed1p-update4 50000 row $script +db eval COMMIT + +# Delete all content in a table. +# +speed_trial speed1p-delete1 50000 row {DELETE FROM t1} + +# Copy one table into another +# +speed_trial speed1p-copy1 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Delete all content in a table, one row at a time. +# +speed_trial speed1p-delete2 50000 row {DELETE FROM t1 WHERE 1} + +# Refill the table yet again +# +speed_trial speed1p-copy2 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Drop the table and recreate it without its indices. +# +db eval BEGIN +speed_trial speed1p-drop1 50000 row { + DROP TABLE t1; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); +} +db eval COMMIT + +# Refill the table yet again. This copy should be faster because +# there are no indices to deal with. +# +speed_trial speed1p-copy3 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Select 20000 rows from the table at random. +# +speed_trial speed1p-random1 50000 row { + SELECT rowid FROM t1 ORDER BY random() LIMIT 20000 +} + +# Delete 20000 random rows from the table. +# +speed_trial speed1p-random-del1 20000 row { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000) +} +do_test speed1p-1.1 { + db one {SELECT count(*) FROM t1} +} 30000 + +# Delete 20000 more rows at random from the table. +# +speed_trial speed1p-random-del2 20000 row { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000) +} +do_test speed1p-1.2 { + db one {SELECT count(*) FROM t1} +} 10000 +speed_trial_summary speed1 + +db close +sqlite3_shutdown +eval sqlite3_config_lookaside $old_lookaside +sqlite3_initialize +autoinstall_test_functions +finish_test diff --git a/components/external/SQLite-3.8.1/test/speed2.test b/components/external/SQLite-3.8.1/test/speed2.test new file mode 100644 index 0000000000000000000000000000000000000000..f6d1a4c8ab6e20add3f932d9e9aa4017f05fac20 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/speed2.test @@ -0,0 +1,339 @@ +# 2006 November 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is measuring executing speed. +# +# $Id: speed2.test,v 1.7 2007/04/16 15:02:20 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +speed_trial_init speed2 + +# Set a uniform random seed +expr srand(0) + +set sqlout [open speed2.txt w] +proc tracesql {sql} { + puts $::sqlout $sql\; +} +#db trace tracesql + +# The number_name procedure below converts its argment (an integer) +# into a string which is the English-language name for that number. +# +# Example: +# +# puts [number_name 123] -> "one hundred twenty three" +# +set ones {zero one two three four five six seven eight nine + ten eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen} +set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} +proc number_name {n} { + if {$n>=1000} { + set txt "[number_name [expr {$n/1000}]] thousand" + set n [expr {$n%1000}] + } else { + set txt {} + } + if {$n>=100} { + append txt " [lindex $::ones [expr {$n/100}]] hundred" + set n [expr {$n%100}] + } + if {$n>=20} { + append txt " [lindex $::tens [expr {$n/10}]]" + set n [expr {$n%10}] + } + if {$n>0} { + append txt " [lindex $::ones $n]" + } + set txt [string trim $txt] + if {$txt==""} {set txt zero} + return $txt +} + +# Create a database schema. +# +do_test speed2-1.0 { + execsql { + PRAGMA page_size=1024; + PRAGMA cache_size=8192; + PRAGMA locking_mode=EXCLUSIVE; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); + CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT); + CREATE INDEX i2a ON t2(a); + CREATE INDEX i2b ON t2(b); + } + execsql { + SELECT name FROM sqlite_master ORDER BY 1; + } +} {i2a i2b t1 t2} + + +# 50000 INSERTs on an unindexed table +# +set sql {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + append sql "INSERT INTO t1 VALUES($i,$r,'[number_name $r]');\n" +} +db eval BEGIN +speed_trial speed2-insert1 50000 row $sql +db eval COMMIT + +# 50000 INSERTs on an indexed table +# +set sql {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + append sql "INSERT INTO t2 VALUES($i,$r,'[number_name $r]');\n" +} +db eval BEGIN +speed_trial speed2-insert2 50000 row $sql +db eval COMMIT + + + +# 50 SELECTs on an integer comparison. There is no index so +# a full table scan is required. +# +set sql {} +for {set i 0} {$i<50} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" +} +speed_trial speed2-select1a [expr {50*50000}] row $sql + +# 50 SELECTs on an LIKE comparison. There is no index so a full +# table scan is required. +# +set sql {} +for {set i 0} {$i<50} {incr i} { + append sql \ + "SELECT count(*), avg(b) FROM t1 WHERE c LIKE '%[number_name $i]%';" +} +speed_trial speed2-select2a [expr {50*50000}] row $sql + +# Vacuum +speed_trial speed2-vacuum1 100000 row VACUUM + +# 50 SELECTs on an integer comparison. There is no index so +# a full table scan is required. +# +set sql {} +for {set i 0} {$i<50} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" +} +speed_trial speed2-select1b [expr {50*50000}] row $sql + +# 50 SELECTs on an LIKE comparison. There is no index so a full +# table scan is required. +# +set sql {} +for {set i 0} {$i<50} {incr i} { + append sql \ + "SELECT count(*), avg(b) FROM t1 WHERE c LIKE '%[number_name $i]%';" +} +speed_trial speed2-select2b [expr {50*50000}] row $sql + +# Create indices +# +db eval BEGIN +speed_trial speed2-createidx 150000 row { + CREATE INDEX i1a ON t1(a); + CREATE INDEX i1b ON t1(b); + CREATE INDEX i1c ON t1(c); +} +db eval COMMIT + +# 5000 SELECTs on an integer comparison where the integer is +# indexed. +# +set sql {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" +} +speed_trial speed2-select3a 5000 stmt $sql + +# 100000 random SELECTs against rowid. +# +set sql {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + append sql "SELECT c=='hi' FROM t1 WHERE rowid=$id;\n" +} +speed_trial speed2-select4a 100000 row $sql + +# 100000 random SELECTs against a unique indexed column. +# +set sql {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + append sql "SELECT c FROM t1 WHERE a=$id;" +} +speed_trial speed2-select5a 100000 row $sql + +# 50000 random SELECTs against an indexed column text column +# +set sql {} +db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000} { + append sql "SELECT c FROM t1 WHERE c='$c';" +} +speed_trial speed2-select6a 50000 row $sql + +# Vacuum +speed_trial speed2-vacuum2 100000 row VACUUM + + +# 5000 SELECTs on an integer comparison where the integer is +# indexed. +# +set sql {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + append sql "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" +} +speed_trial speed2-select3b 5000 stmt $sql + +# 100000 random SELECTs against rowid. +# +set sql {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + append sql "SELECT c=='hi' FROM t1 WHERE rowid=$id;\n" +} +speed_trial speed2-select4b 100000 row $sql + +# 100000 random SELECTs against a unique indexed column. +# +set sql {} +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + append sql "SELECT c FROM t1 WHERE a=$id;" +} +speed_trial speed2-select5b 100000 row $sql + +# 50000 random SELECTs against an indexed column text column +# +set sql {} +db eval {SELECT c FROM t1 ORDER BY random() LIMIT 50000} { + append sql "SELECT c FROM t1 WHERE c='$c';" +} +speed_trial speed2-select6b 50000 row $sql + +# 5000 updates of ranges where the field being compared is indexed. +# +set sql {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*2}] + set upr [expr {($i+1)*2}] + append sql "UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr;" +} +db eval BEGIN +speed_trial speed2-update1 5000 stmt $sql +db eval COMMIT + +# 50000 single-row updates. An index is used to find the row quickly. +# +set sql {} +for {set i 0} {$i<50000} {incr i} { + set r [expr {int(rand()*500000)}] + append sql "UPDATE t1 SET b=$r WHERE a=$i;" +} +db eval BEGIN +speed_trial speed2-update2 50000 row $sql +db eval COMMIT + +# 1 big text update that touches every row in the table. +# +speed_trial speed2-update3 50000 row { + UPDATE t1 SET c=a; +} + +# Many individual text updates. Each row in the table is +# touched through an index. +# +set sql {} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + append sql "UPDATE t1 SET c='[number_name $r]' WHERE a=$i;" +} +db eval BEGIN +speed_trial speed2-update4 50000 row $sql +db eval COMMIT + +# Delete all content in a table. +# +speed_trial speed2-delete1 50000 row {DELETE FROM t1} + +# Copy one table into another +# +speed_trial speed2-copy1 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Delete all content in a table, one row at a time. +# +speed_trial speed2-delete2 50000 row {DELETE FROM t1 WHERE 1} + +# Refill the table yet again +# +speed_trial speed2-copy2 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Drop the table and recreate it without its indices. +# +db eval BEGIN +speed_trial speed2-drop1 50000 row { + DROP TABLE t1; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); +} +db eval COMMIT + +# Refill the table yet again. This copy should be faster because +# there are no indices to deal with. +# +speed_trial speed2-copy3 50000 row {INSERT INTO t1 SELECT * FROM t2} + +# Select 20000 rows from the table at random. +# +speed_trial speed2-random1 50000 row { + SELECT rowid FROM t1 ORDER BY random() LIMIT 20000 +} + +# Delete 20000 random rows from the table. +# +speed_trial speed2-random-del1 20000 row { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000) +} +do_test speed2-1.1 { + db one {SELECT count(*) FROM t1} +} 30000 + + +# Delete 20000 more rows at random from the table. +# +speed_trial speed2-random-del2 20000 row { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000) +} +do_test speed2-1.2 { + db one {SELECT count(*) FROM t1} +} 10000 +speed_trial_summary speed2 + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/speed3.test b/components/external/SQLite-3.8.1/test/speed3.test new file mode 100644 index 0000000000000000000000000000000000000000..1beaeb74f337f422d77f1dc41f71098e86d18ca3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/speed3.test @@ -0,0 +1,172 @@ +# 2007 May 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing that the overflow-page related +# enhancements added after version 3.3.17 speed things up. +# +# $Id: speed3.test,v 1.6 2009/07/09 02:48:24 shane Exp $ +# + +#--------------------------------------------------------------------- +# Test plan: +# +# If auto-vacuum is enabled for the database, the following cases +# should show performance improvement with respect to 3.3.17. +# +# + When deleting rows that span overflow pages. This is faster +# because the overflow pages no longer need to be read before +# they can be moved to the free list (test cases speed3-1.X). +# +# + When reading a column value stored on an overflow page that +# is not the first overflow page for the row. The improvement +# in this case is because the overflow pages between the tree +# page and the overflow page containing the value do not have +# to be read (test cases speed3-2.X). +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !tclvar||!attach { + finish_test + return +} + +speed_trial_init speed1 + +# Set a uniform random seed +expr srand(0) + +set ::NROW 1000 + +# The number_name procedure below converts its argment (an integer) +# into a string which is the English-language name for that number. +# +# Example: +# +# puts [number_name 123] -> "one hundred twenty three" +# +set ones {zero one two three four five six seven eight nine + ten eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen} +set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} +proc number_name {n} { + if {$n>=1000} { + set txt "[number_name [expr {$n/1000}]] thousand" + set n [expr {$n%1000}] + } else { + set txt {} + } + if {$n>=100} { + append txt " [lindex $::ones [expr {$n/100}]] hundred" + set n [expr {$n%100}] + } + if {$n>=20} { + append txt " [lindex $::tens [expr {$n/10}]]" + set n [expr {$n%10}] + } + if {$n>0} { + append txt " [lindex $::ones $n]" + } + set txt [string trim $txt] + if {$txt==""} {set txt zero} + return $txt +} + +proc populate_t1 {db} { + $db transaction { + for {set ii 0} {$ii < $::NROW} {incr ii} { + set N [number_name $ii] + set repeats [expr {(10000/[string length $N])+1}] + set text [string range [string repeat $N $repeats] 0 10000] + $db eval {INSERT INTO main.t1 VALUES($ii, $text, $ii)} + } + $db eval {INSERT INTO aux.t1 SELECT * FROM main.t1} + } +} + + +proc io_log {db} { + db_enter db + array set stats1 [btree_pager_stats [btree_from_db db]] + array set stats2 [btree_pager_stats [btree_from_db db 2]] + db_leave db +# puts "1: [array get stats1]" +# puts "2: [array get stats2]" + puts "Incrvacuum: Read $stats1(read), wrote $stats1(write)" + puts "Normal : Read $stats2(read), wrote $stats2(write)" +} + +proc reset_db {} { + db close + sqlite3 db test.db + db eval { + PRAGMA main.cache_size = 200000; + PRAGMA main.auto_vacuum = 'incremental'; + ATTACH 'test2.db' AS 'aux'; + PRAGMA aux.auto_vacuum = 'none'; + } +} + +forcedelete test2.db test2.db-journal +reset_db + +# Set up a database in auto-vacuum mode and create a database schema. +# +do_test speed3-0.1 { + execsql { + CREATE TABLE main.t1(a INTEGER, b TEXT, c INTEGER); + } + execsql { + SELECT name FROM sqlite_master ORDER BY 1; + } +} {t1} +do_test speed3-0.2 { + execsql { + CREATE TABLE aux.t1(a INTEGER, b TEXT, c INTEGER); + } + execsql { + SELECT name FROM aux.sqlite_master ORDER BY 1; + } +} {t1} +do_test speed3-0.3 { + populate_t1 db + execsql { + SELECT count(*) FROM main.t1; + SELECT count(*) FROM aux.t1; + } +} "$::NROW $::NROW" +do_test speed3-0.4 { + execsql { + PRAGMA main.auto_vacuum; + PRAGMA aux.auto_vacuum; + } +} {2 0} + +# Delete all content in a table, one row at a time. +# +#io_log db +reset_db +speed_trial speed3-1.incrvacuum $::NROW row {DELETE FROM main.t1 WHERE 1} +speed_trial speed3-1.normal $::NROW row {DELETE FROM aux.t1 WHERE 1} +io_log db + +# Select the "C" column (located at the far end of the overflow +# chain) from each table row. +# +#db eval {PRAGMA incremental_vacuum(500000)} +populate_t1 db +reset_db +speed_trial speed3-2.incrvacuum $::NROW row {SELECT c FROM main.t1} +speed_trial speed3-2.normal $::NROW row {SELECT c FROM aux.t1} +io_log db + +finish_test diff --git a/components/external/SQLite-3.8.1/test/speed4.test b/components/external/SQLite-3.8.1/test/speed4.test new file mode 100644 index 0000000000000000000000000000000000000000..2ccdaf5cd3a3874ee36d279d848e144d8b81cbd9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/speed4.test @@ -0,0 +1,231 @@ +# 2007 October 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is measuring executing speed. More specifically, +# the focus is on the speed of: +# +# * joins +# * views +# * sub-selects +# * triggers +# +# $Id: speed4.test,v 1.2 2008/07/12 14:52:20 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +speed_trial_init speed1 + +# Set a uniform random seed +expr srand(0) + +set sqlout [open speed1.txt w] +proc tracesql {sql} { + puts $::sqlout $sql\; +} +#db trace tracesql + +# The number_name procedure below converts its argment (an integer) +# into a string which is the English-language name for that number. +# +# Example: +# +# puts [number_name 123] -> "one hundred twenty three" +# +set ones {zero one two three four five six seven eight nine + ten eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen} +set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} +proc number_name {n} { + if {$n>=1000} { + set txt "[number_name [expr {$n/1000}]] thousand" + set n [expr {$n%1000}] + } else { + set txt {} + } + if {$n>=100} { + append txt " [lindex $::ones [expr {$n/100}]] hundred" + set n [expr {$n%100}] + } + if {$n>=20} { + append txt " [lindex $::tens [expr {$n/10}]]" + set n [expr {$n%10}] + } + if {$n>0} { + append txt " [lindex $::ones $n]" + } + set txt [string trim $txt] + if {$txt==""} {set txt zero} + return $txt +} + +# Summary of tests: +# +# speed4-join1: Join three tables using IPK index. +# speed4-join2: Join three tables using an index. +# speed4-join3: Join two tables without an index. +# +# speed4-view1: Querying a view. +# speed4-table1: Same queries as in speed4-view1, but run directly against +# the tables for comparison purposes. +# +# speed4-subselect1: A SELECT statement that uses many sub-queries.. +# +# speed4-trigger1: An INSERT statement that fires a trigger. +# speed4-trigger2: An UPDATE statement that fires a trigger. +# speed4-trigger3: A DELETE statement that fires a trigger. +# speed4-notrigger1: Same operation as trigger1, but without the trigger. +# speed4-notrigger2: " trigger2 " +# speed4-notrigger3: " trigger3 " +# + +# Set up the schema. Each of the tables t1, t2 and t3 contain 50,000 rows. +# This creates a database of around 16MB. +execsql { + BEGIN; + CREATE TABLE t1(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + CREATE TABLE t2(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + CREATE TABLE t3(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + + CREATE VIEW v1 AS SELECT rowid, i, t FROM t1; + CREATE VIEW v2 AS SELECT rowid, i, t FROM t2; + CREATE VIEW v3 AS SELECT rowid, i, t FROM t3; +} +for {set jj 1} {$jj <= 3} {incr jj} { + set stmt [string map "%T% t$jj" {INSERT INTO %T% VALUES(NULL, $i, $t)}] + for {set ii 0} {$ii < 50000} {incr ii} { + set i [expr {int(rand()*50000)}] + set t [number_name $i] + execsql $stmt + } +} +execsql { + CREATE INDEX i1 ON t1(t); + CREATE INDEX i2 ON t2(t); + CREATE INDEX i3 ON t3(t); + COMMIT; +} + +# Before running these tests, disable the compiled statement cache built into +# the Tcl interface. This is because we want to test the speed of SQL +# compilation as well as execution. +# +db cache size 0 + +# Join t1, t2, t3 on IPK. +set sql "SELECT * FROM t1, t2, t3 WHERE t1.oid = t2.oid AND t2.oid = t3.oid" +speed_trial speed4-join1 50000 row $sql + +# Join t1, t2, t3 on the non-IPK index. +set sql "SELECT * FROM t1, t2, t3 WHERE t1.t = t2.t AND t2.t = t3.t" +speed_trial speed4-join2 50000 row $sql + +# Run 10000 simple queries against the views. +set sql "" +for {set ii 1} {$ii < 10000} {incr ii} { + append sql "SELECT * FROM v[expr {($ii%3)+1}] WHERE rowid = [expr {$ii*3}];" +} +speed_trial speed4-view1 10000 stmt $sql + +# Run the same 10000 simple queries as in the previous test case against +# the underlying tables. The compiled vdbe programs should be identical, so +# the only difference in running time is the extra time taken to compile +# the view definitions. +# +set sql "" +for {set ii 1} {$ii < 10000} {incr ii} { + append sql "SELECT t FROM t[expr {($ii%3)+1}] WHERE rowid = [expr {$ii*3}];" +} +speed_trial speed4-table1 10000 stmt $sql + +# Run a SELECT that uses sub-queries 10000 times. A total of 30000 sub-selects. +# +set sql "" +for {set ii 1} {$ii < 10000} {incr ii} { + append sql " + SELECT (SELECT t FROM t1 WHERE rowid = [expr {$ii*3}]), + (SELECT t FROM t2 WHERE rowid = [expr {$ii*3}]), + (SELECT t FROM t3 WHERE rowid = [expr {$ii*3}]) + ;" +} +speed_trial speed4-subselect1 10000 stmt $sql + +# The following block tests the speed of some DML statements that cause +# triggers to fire. +# +execsql { + CREATE TABLE log(op TEXT, r INTEGER, i INTEGER, t TEXT); + CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + CREATE TRIGGER t4_trigger1 AFTER INSERT ON t4 BEGIN + INSERT INTO log VALUES('INSERT INTO t4', new.rowid, new.i, new.t); + END; + CREATE TRIGGER t4_trigger2 AFTER UPDATE ON t4 BEGIN + INSERT INTO log VALUES('UPDATE OF t4', new.rowid, new.i, new.t); + END; + CREATE TRIGGER t4_trigger3 AFTER DELETE ON t4 BEGIN + INSERT INTO log VALUES('DELETE OF t4', old.rowid, old.i, old.t); + END; + BEGIN; +} +set sql "" +for {set ii 1} {$ii < 10000} {incr ii} { + append sql "INSERT INTO t4 VALUES(NULL, $ii, '[number_name $ii]');" +} +speed_trial speed4-trigger1 10000 stmt $sql +set sql "" +for {set ii 1} {$ii < 20000} {incr ii 2} { + set ii2 [expr {$ii*2}] + append sql " + UPDATE t4 SET i = $ii2, t = '[number_name $ii2]' WHERE rowid = $ii; + " +} +speed_trial speed4-trigger2 10000 stmt $sql +set sql "" +for {set ii 1} {$ii < 20000} {incr ii 2} { + append sql "DELETE FROM t4 WHERE rowid = $ii;" +} +speed_trial speed4-trigger3 10000 stmt $sql +execsql {COMMIT} + +# The following block contains the same tests as the above block that +# tests triggers, with one crucial difference: no triggers are defined. +# So the difference in speed between these tests and the preceding ones +# is the amount of time taken to compile and execute the trigger programs. +# +execsql { + DROP TABLE t4; + DROP TABLE log; + VACUUM; + CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + BEGIN; +} +set sql "" +for {set ii 1} {$ii < 10000} {incr ii} { + append sql "INSERT INTO t4 VALUES(NULL, $ii, '[number_name $ii]');" +} +speed_trial speed4-notrigger1 10000 stmt $sql +set sql "" +for {set ii 1} {$ii < 20000} {incr ii 2} { + set ii2 [expr {$ii*2}] + append sql " + UPDATE t4 SET i = $ii2, t = '[number_name $ii2]' WHERE rowid = $ii; + " +} +speed_trial speed4-notrigger2 10000 stmt $sql +set sql "" +for {set ii 1} {$ii < 20000} {incr ii 2} { + append sql "DELETE FROM t4 WHERE rowid = $ii;" +} +speed_trial speed4-notrigger3 10000 stmt $sql +execsql {COMMIT} + +speed_trial_summary speed4 +finish_test diff --git a/components/external/SQLite-3.8.1/test/speed4p.explain b/components/external/SQLite-3.8.1/test/speed4p.explain new file mode 100644 index 0000000000000000000000000000000000000000..a713955e618a615575772749927438eb04c47b1c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/speed4p.explain @@ -0,0 +1,283 @@ +# 2007 October 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is measuring executing speed. More specifically, +# the focus is on the speed of: +# +# * joins +# * views +# * sub-selects +# * triggers +# +# $Id: speed4p.explain,v 1.1 2008/04/16 12:57:48 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +speed_trial_init speed1 + +# Set a uniform random seed +expr srand(0) + +set sqlout [open speed1.txt w] +proc tracesql {sql} { + puts $::sqlout $sql\; +} +#db trace tracesql + +# The number_name procedure below converts its argment (an integer) +# into a string which is the English-language name for that number. +# +# Example: +# +# puts [number_name 123] -> "one hundred twenty three" +# +set ones {zero one two three four five six seven eight nine + ten eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen} +set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} +proc number_name {n} { + if {$n>=1000} { + set txt "[number_name [expr {$n/1000}]] thousand" + set n [expr {$n%1000}] + } else { + set txt {} + } + if {$n>=100} { + append txt " [lindex $::ones [expr {$n/100}]] hundred" + set n [expr {$n%100}] + } + if {$n>=20} { + append txt " [lindex $::tens [expr {$n/10}]]" + set n [expr {$n%10}] + } + if {$n>0} { + append txt " [lindex $::ones $n]" + } + set txt [string trim $txt] + if {$txt==""} {set txt zero} + return $txt +} + +# Summary of tests: +# +# speed4p-join1: Join three tables using IPK index. +# speed4p-join2: Join three tables using an index. +# speed4p-join3: Join two tables without an index. +# +# speed4p-view1: Querying a view. +# speed4p-table1: Same queries as in speed4p-view1, but run directly against +# the tables for comparison purposes. +# +# speed4p-subselect1: A SELECT statement that uses many sub-queries.. +# +# speed4p-trigger1: An INSERT statement that fires a trigger. +# speed4p-trigger2: An UPDATE statement that fires a trigger. +# speed4p-trigger3: A DELETE statement that fires a trigger. +# speed4p-notrigger1: Same operation as trigger1, but without the trigger. +# speed4p-notrigger2: " trigger2 " +# speed4p-notrigger3: " trigger3 " +# + +# Set up the schema. Each of the tables t1, t2 and t3 contain 50,000 rows. +# This creates a database of around 16MB. +execsql { + PRAGMA page_size=1024; + PRAGMA cache_size=8192; + PRAGMA locking_mode=EXCLUSIVE; + BEGIN; + CREATE TABLE t1(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + CREATE TABLE t2(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + CREATE TABLE t3(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + + CREATE VIEW v1 AS SELECT rowid, i, t FROM t1; + CREATE VIEW v2 AS SELECT rowid, i, t FROM t2; + CREATE VIEW v3 AS SELECT rowid, i, t FROM t3; +} +for {set jj 1} {$jj <= 3} {incr jj} { + set stmt [string map "%T% t$jj" {INSERT INTO %T% VALUES(NULL, $i, $t)}] + for {set ii 0} {$ii < 50000} {incr ii} { + set i [expr {int(rand()*50000)}] + set t [number_name $i] + execsql $stmt + } +} +execsql { + CREATE INDEX i1 ON t1(t); + CREATE INDEX i2 ON t2(t); + CREATE INDEX i3 ON t3(t); + COMMIT; +} + +# Before running these tests, disable the compiled statement cache built into +# the Tcl interface. This is because we want to test the speed of SQL +# compilation as well as execution. +# +db cache size 0 + +# Join t1, t2, t3 on IPK. +set sql "SELECT * FROM t1, t2, t3 WHERE t1.oid = t2.oid AND t2.oid = t3.oid" +explain $sql +speed_trial speed4p-join1 50000 row $sql + +# Join t1, t2, t3 on the non-IPK index. +set sql "SELECT * FROM t1, t2, t3 WHERE t1.t = t2.t AND t2.t = t3.t" +explain $sql +speed_trial speed4p-join2 50000 row $sql + +# Run 10000 simple queries against the views. +set script { + for {set ii 1} {$ii < 10000} {incr ii} { + set v [expr {$ii*3}] + set t [expr {$ii%3+1}] + db eval "SELECT * FROM v$t WHERE rowid = \$v" + } +} +explain {SELECT * FROm v1 WHERE rowid=$v} +speed_trial_tcl speed4p-view1 10000 stmt $script + +# Run the same 10000 simple queries as in the previous test case against +# the underlying tables. The compiled vdbe programs should be identical, so +# the only difference in running time is the extra time taken to compile +# the view definitions. +# +set script { + for {set ii 1} {$ii < 10000} {incr ii} { + set v [expr {$ii*3}] + set t [expr {$ii%3+1}] + db eval "SELECT t FROM t$t WHERE rowid = \$v" + } +} +explain {SELECT * FROM t1 WHERE rowid=$v} +speed_trial_tcl speed4p-table1 10000 stmt $script + +# Run a SELECT that uses sub-queries 10000 times. A total of 30000 sub-selects. +# +set script { + for {set ii 1} {$ii < 10000} {incr ii} { + set v [expr {$ii*3}] + db eval { + SELECT (SELECT t FROM t1 WHERE rowid = $v), + (SELECT t FROM t2 WHERE rowid = $v), + (SELECT t FROM t3 WHERE rowid = $v) + } + } +} +explain { + SELECT (SELECT t FROM t1 WHERE rowid = $v), + (SELECT t FROM t2 WHERE rowid = $v), + (SELECT t FROM t3 WHERE rowid = $v) +} +speed_trial_tcl speed4p-subselect1 10000 stmt $script + +# The following block tests the speed of some DML statements that cause +# triggers to fire. +# +execsql { + CREATE TABLE log(op TEXT, r INTEGER, i INTEGER, t TEXT); + CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + CREATE TRIGGER t4_trigger1 AFTER INSERT ON t4 BEGIN + INSERT INTO log VALUES('INSERT INTO t4', new.rowid, new.i, new.t); + END; + CREATE TRIGGER t4_trigger2 AFTER UPDATE ON t4 BEGIN + INSERT INTO log VALUES('UPDATE OF t4', new.rowid, new.i, new.t); + END; + CREATE TRIGGER t4_trigger3 AFTER DELETE ON t4 BEGIN + INSERT INTO log VALUES('DELETE OF t4', old.rowid, old.i, old.t); + END; + BEGIN; +} +set list {} +for {set ii 1} {$ii < 10000} {incr ii} { + lappend list $ii [number_name $ii] +} +set script { + foreach {ii name} $::list { + db eval {INSERT INTO t4 VALUES(NULL, $ii, $name)} + } +} +explain {INSERT INTO t4 VALUES(NULL, $ii, $name)} +speed_trial_tcl speed4p-trigger1 10000 stmt $script + +set list {} +for {set ii 1} {$ii < 20000} {incr ii 2} { + set ii2 [expr {$ii*2}] + lappend list $ii $ii2 [number_name $ii2] +} +set script { + foreach {ii ii2 name} $::list { + db eval { + UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii; + } + } +} +explain {UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii} +speed_trial_tcl speed4p-trigger2 10000 stmt $script + +set script { + for {set ii 1} {$ii < 20000} {incr ii 2} { + db eval {DELETE FROM t4 WHERE rowid = $ii} + } +} +explain {DELETE FROM t4 WHERE rowid = $ii} +speed_trial_tcl speed4p-trigger3 10000 stmt $script +execsql {COMMIT} + +# The following block contains the same tests as the above block that +# tests triggers, with one crucial difference: no triggers are defined. +# So the difference in speed between these tests and the preceding ones +# is the amount of time taken to compile and execute the trigger programs. +# +execsql { + DROP TABLE t4; + DROP TABLE log; + VACUUM; + CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + BEGIN; +} +set list {} +for {set ii 1} {$ii < 10000} {incr ii} { + lappend list $ii [number_name $ii] +} +set script { + foreach {ii name} $::list { + db eval {INSERT INTO t4 VALUES(NULL, $ii, $name);} + } +} +explain {INSERT INTO t4 VALUES(NULL, $ii, $name)} +speed_trial_tcl speed4p-notrigger1 10000 stmt $script + +set list {} +for {set ii 1} {$ii < 20000} {incr ii 2} { + set ii2 [expr {$ii*2}] + lappend list $ii $ii2 [number_name $ii2] +} +set script { + foreach {ii ii2 name} $::list { + db eval { + UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii; + } + } +} +explain {UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii} +speed_trial_tcl speed4p-notrigger2 10000 stmt $script + +set script { + for {set ii 1} {$ii < 20000} {incr ii 2} { + db eval {DELETE FROM t4 WHERE rowid = $ii} + } +} +explain {DELETE FROM t4 WHERE rowid = $ii} +speed_trial_tcl speed4p-notrigger3 10000 stmt $script +execsql {COMMIT} + +speed_trial_summary speed4 +finish_test diff --git a/components/external/SQLite-3.8.1/test/speed4p.test b/components/external/SQLite-3.8.1/test/speed4p.test new file mode 100644 index 0000000000000000000000000000000000000000..024232e1b8afb3cae620691203d79309d9708c59 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/speed4p.test @@ -0,0 +1,292 @@ +# 2007 October 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is measuring executing speed. More specifically, +# the focus is on the speed of: +# +# * joins +# * views +# * sub-selects +# * triggers +# +# $Id: speed4p.test,v 1.4 2008/04/10 13:32:37 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +speed_trial_init speed1 + +# Set a uniform random seed +expr srand(0) + +set sqlout [open speed1.txt w] +proc tracesql {sql} { + puts $::sqlout $sql\; +} +#db trace tracesql + +# The number_name procedure below converts its argment (an integer) +# into a string which is the English-language name for that number. +# +# Example: +# +# puts [number_name 123] -> "one hundred twenty three" +# +set ones {zero one two three four five six seven eight nine + ten eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen} +set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} +proc number_name {n} { + if {$n>=1000} { + set txt "[number_name [expr {$n/1000}]] thousand" + set n [expr {$n%1000}] + } else { + set txt {} + } + if {$n>=100} { + append txt " [lindex $::ones [expr {$n/100}]] hundred" + set n [expr {$n%100}] + } + if {$n>=20} { + append txt " [lindex $::tens [expr {$n/10}]]" + set n [expr {$n%10}] + } + if {$n>0} { + append txt " [lindex $::ones $n]" + } + set txt [string trim $txt] + if {$txt==""} {set txt zero} + return $txt +} + +# Summary of tests: +# +# speed4p-join1: Join three tables using IPK index. +# speed4p-join2: Join three tables using an index. +# speed4p-join3: Join two tables without an index. +# +# speed4p-view1: Querying a view. +# speed4p-table1: Same queries as in speed4p-view1, but run directly against +# the tables for comparison purposes. +# +# speed4p-subselect1: A SELECT statement that uses many sub-queries.. +# +# speed4p-trigger1: An INSERT statement that fires a trigger. +# speed4p-trigger2: An UPDATE statement that fires a trigger. +# speed4p-trigger3: A DELETE statement that fires a trigger. +# speed4p-notrigger1: Same operation as trigger1, but without the trigger. +# speed4p-notrigger2: " trigger2 " +# speed4p-notrigger3: " trigger3 " +# + +# Set up the schema. Each of the tables t1, t2 and t3 contain 50,000 rows. +# This creates a database of around 16MB. +execsql { + PRAGMA page_size=1024; + PRAGMA cache_size=8192; + PRAGMA locking_mode=EXCLUSIVE; + BEGIN; + CREATE TABLE t1(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + CREATE TABLE t2(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + CREATE TABLE t3(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + + CREATE VIEW v1 AS SELECT rowid, i, t FROM t1; + CREATE VIEW v2 AS SELECT rowid, i, t FROM t2; + CREATE VIEW v3 AS SELECT rowid, i, t FROM t3; +} +for {set jj 1} {$jj <= 3} {incr jj} { + set stmt [string map "%T% t$jj" {INSERT INTO %T% VALUES(NULL, $i, $t)}] + for {set ii 0} {$ii < 50000} {incr ii} { + set i [expr {int(rand()*50000)}] + set t [number_name $i] + execsql $stmt + } +} +execsql { + CREATE INDEX i1 ON t1(t); + CREATE INDEX i2 ON t2(t); + CREATE INDEX i3 ON t3(t); + COMMIT; +} + +# Join t1, t2, t3 on IPK. +set sql "SELECT * FROM t1, t2, t3 WHERE t1.oid = t2.oid AND t2.oid = t3.oid" +speed_trial speed4p-join1 50000 row $sql + +# Join t1, t2, t3 on the non-IPK index. +set sql "SELECT * FROM t1, t2, t3 WHERE t1.t = t2.t AND t2.t = t3.t" +speed_trial speed4p-join2 50000 row $sql + +# Run 10000 simple queries against the views. +set script { + for {set ii 1} {$ii < 10000} {incr ii} { + set v [expr {$ii*3}] + set t [expr {$ii%3+1}] + db eval "SELECT * FROM v$t WHERE rowid = \$v" + } +} +speed_trial_tcl speed4p-view1 10000 stmt $script + +# Run the same 10000 simple queries as in the previous test case against +# the underlying tables. The compiled vdbe programs should be identical, so +# the only difference in running time is the extra time taken to compile +# the view definitions. +# +set script { + for {set ii 1} {$ii < 10000} {incr ii} { + set v [expr {$ii*3}] + set t [expr {$ii%3+1}] + db eval "SELECT t FROM t$t WHERE rowid = \$v" + } +} +speed_trial_tcl speed4p-table1 10000 stmt $script + +# Run a SELECT that uses sub-queries 10000 times. A total of 30000 sub-selects. +# +set script { + for {set ii 1} {$ii < 10000} {incr ii} { + set v [expr {$ii*3}] + db eval { + SELECT (SELECT t FROM t1 WHERE rowid = $v), + (SELECT t FROM t2 WHERE rowid = $v), + (SELECT t FROM t3 WHERE rowid = $v) + } + } +} +speed_trial_tcl speed4p-subselect1 10000 stmt $script + +# Single-row updates performance. +# +set script { + db eval BEGIN + for {set ii 1} {$ii < 10000} {incr ii} { + set v [expr {$ii*3}] + db eval {UPDATE t1 SET i=i+1 WHERE rowid=$ii} + } + db eval COMMIT +} +speed_trial_tcl speed4p-rowid-update 10000 stmt $script + + +db eval { + CREATE TABLE t5(t TEXT PRIMARY KEY, i INTEGER); +} +speed_trial speed4p-insert-ignore 50000 row { + INSERT OR IGNORE INTO t5 SELECT t, i FROM t1; +} + +set list [db eval {SELECT t FROM t5}] +set script { + db eval BEGIN + foreach t $::list { + db eval {UPDATE t5 SET i=i+1 WHERE t=$t} + } + db eval COMMIT +} +speed_trial_tcl speed4p-unique-update [llength $list] stmt $script + +# The following block tests the speed of some DML statements that cause +# triggers to fire. +# +execsql { + CREATE TABLE log(op TEXT, r INTEGER, i INTEGER, t TEXT); + CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + CREATE TRIGGER t4_trigger1 AFTER INSERT ON t4 BEGIN + INSERT INTO log VALUES('INSERT INTO t4', new.rowid, new.i, new.t); + END; + CREATE TRIGGER t4_trigger2 AFTER UPDATE ON t4 BEGIN + INSERT INTO log VALUES('UPDATE OF t4', new.rowid, new.i, new.t); + END; + CREATE TRIGGER t4_trigger3 AFTER DELETE ON t4 BEGIN + INSERT INTO log VALUES('DELETE OF t4', old.rowid, old.i, old.t); + END; + BEGIN; +} +set list {} +for {set ii 1} {$ii < 10000} {incr ii} { + lappend list $ii [number_name $ii] +} +set script { + foreach {ii name} $::list { + db eval {INSERT INTO t4 VALUES(NULL, $ii, $name)} + } +} +speed_trial_tcl speed4p-trigger1 10000 stmt $script + +set list {} +for {set ii 1} {$ii < 20000} {incr ii 2} { + set ii2 [expr {$ii*2}] + lappend list $ii $ii2 [number_name $ii2] +} +set script { + foreach {ii ii2 name} $::list { + db eval { + UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii; + } + } +} +speed_trial_tcl speed4p-trigger2 10000 stmt $script + +set script { + for {set ii 1} {$ii < 20000} {incr ii 2} { + db eval {DELETE FROM t4 WHERE rowid = $ii} + } +} +speed_trial_tcl speed4p-trigger3 10000 stmt $script +execsql {COMMIT} + +# The following block contains the same tests as the above block that +# tests triggers, with one crucial difference: no triggers are defined. +# So the difference in speed between these tests and the preceding ones +# is the amount of time taken to compile and execute the trigger programs. +# +execsql { + DROP TABLE t4; + DROP TABLE log; + VACUUM; + CREATE TABLE t4(rowid INTEGER PRIMARY KEY, i INTEGER, t TEXT); + BEGIN; +} +set list {} +for {set ii 1} {$ii < 10000} {incr ii} { + lappend list $ii [number_name $ii] +} +set script { + foreach {ii name} $::list { + db eval {INSERT INTO t4 VALUES(NULL, $ii, $name);} + } +} +speed_trial_tcl speed4p-notrigger1 10000 stmt $script + +set list {} +for {set ii 1} {$ii < 20000} {incr ii 2} { + set ii2 [expr {$ii*2}] + lappend list $ii $ii2 [number_name $ii2] +} +set script { + foreach {ii ii2 name} $::list { + db eval { + UPDATE t4 SET i = $ii2, t = $name WHERE rowid = $ii; + } + } +} +speed_trial_tcl speed4p-notrigger2 10000 stmt $script + +set script { + for {set ii 1} {$ii < 20000} {incr ii 2} { + db eval {DELETE FROM t4 WHERE rowid = $ii} + } +} +speed_trial_tcl speed4p-notrigger3 10000 stmt $script +execsql {COMMIT} + +speed_trial_summary speed4 +finish_test diff --git a/components/external/SQLite-3.8.1/test/spellfix.test b/components/external/SQLite-3.8.1/test/spellfix.test new file mode 100644 index 0000000000000000000000000000000000000000..9eb7a45f5dde88d022b97bd83673a7020c611cdb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/spellfix.test @@ -0,0 +1,226 @@ +# 2012 July 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix spellfix + +ifcapable !vtab { finish_test ; return } + +load_static_extension db spellfix nextchar + +set vocab { +rabbi rabbit rabbits rabble rabid rabies raccoon raccoons race raced racer +racers races racetrack racial racially racing rack racked racket racketeer +racketeering racketeers rackets racking racks radar radars radial radially +radian radiance radiant radiantly radiate radiated radiates radiating radiation +radiations radiator radiators radical radically radicals radices radii radio +radioactive radioastronomy radioed radiography radioing radiology radios radish +radishes radium radius radix radon raft rafter rafters rafts rag rage raged +rages ragged raggedly raggedness raging rags ragweed raid raided raider raiders +raiding raids rail railed railer railers railing railroad railroaded railroader +railroaders railroading railroads rails railway railways raiment rain rainbow +raincoat raincoats raindrop raindrops rained rainfall rainier rainiest raining +rains rainstorm rainy raise raised raiser raisers raises raisin raising rake +raked rakes raking rallied rallies rally rallying ram ramble rambler rambles +rambling ramblings ramification ramifications ramp rampage rampant rampart +ramps ramrod rams ran ranch ranched rancher ranchers ranches ranching rancid +random randomization randomize randomized randomizes randomly randomness randy +rang range ranged rangeland ranger rangers ranges ranging rangy rank ranked +ranker rankers rankest ranking rankings rankle rankly rankness ranks ransack +ransacked ransacking ransacks ransom ransomer ransoming ransoms rant ranted +ranter ranters ranting rants rap rapacious rape raped raper rapes rapid +rapidity rapidly rapids rapier raping rapport rapprochement raps rapt raptly +rapture raptures rapturous rare rarely rareness rarer rarest rarity rascal +rascally rascals rash rasher rashly rashness rasp raspberry rasped rasping +rasps raster rat rate rated rater raters rates rather ratification ratified +ratifies ratify ratifying rating ratings ratio ration rational rationale +rationales rationalities rationality rationalization rationalizations +rationalize rationalized rationalizes rationalizing rationally rationals +rationing rations ratios rats rattle rattled rattler rattlers rattles +rattlesnake rattlesnakes rattling raucous ravage ravaged ravager ravagers +ravages ravaging rave raved raven ravening ravenous ravenously ravens raves +ravine ravines raving ravings raw rawer rawest rawly rawness ray rays raze +razor razors re reabbreviate reabbreviated reabbreviates reabbreviating reach +reachability reachable reachably reached reacher reaches reaching reacquired +react reacted reacting reaction reactionaries reactionary reactions reactivate +reactivated reactivates reactivating reactivation reactive reactively +reactivity reactor reactors reacts read readability readable reader readers +readied readier readies readiest readily readiness reading readings readjusted +readout readouts reads ready readying real realest realign realigned realigning +realigns realism realist realistic realistically realists realities reality +} + +do_test 1.1 { + execsql { CREATE VIRTUAL TABLE t1 USING spellfix1 } + foreach word $vocab { + execsql { INSERT INTO t1(word) VALUES($word) } + } +} {} + +foreach {tn word res} { + 1 raxpi* {rasping 5 rasped 5 ragweed 5 raspberry 6 rasp 4} + 2 ril* {rail 4 railed 4 railer 4 railers 4 railing 4} + 3 rilis* {realism 6 realist 6 realistic 6 realistically 6 realists 6} + 4 reail* {real 3 realest 3 realign 3 realigned 3 realigning 3} + 5 ras* {rascal 3 rascally 3 rascals 3 rash 3 rasher 3} + 6 realistss* {realists 8 realigns 8 realistic 9 realistically 9 realest 7} + 7 realistss {realists 8 realist 7 realigns 8 realistic 9 realest 7} + 8 rllation* {realities 9 reality 7 rallied 7 railed 4} + 9 renstom* {rainstorm 8 ransom 6 ransomer 6 ransoming 6 ransoms 6} +} { + do_execsql_test 1.2.$tn { + SELECT word, matchlen FROM t1 WHERE word MATCH $word + ORDER BY score, word LIMIT 5 + } $res +} + +# Tests of the next_char function. +# +do_test 1.10 { + db eval { + CREATE TABLE vocab(w TEXT PRIMARY KEY); + INSERT INTO vocab SELECT word FROM t1; + } +} {} +do_execsql_test 1.11 { + SELECT next_char('re','vocab','w'); +} {a} +do_execsql_test 1.11sub { + SELECT next_char('re','(SELECT w AS x FROM vocab)','x'); +} {a} +do_execsql_test 1.12 { + SELECT next_char('r','vocab','w'); +} {ae} +do_execsql_test 1.13 { + SELECT next_char('','vocab','w'); +} {r} +do_test 1.14 { + catchsql {SELECT next_char('','xyzzy','a')} +} {1 {no such table: xyzzy}} + +do_execsql_test 1.20 { + CREATE TABLE vocab2(w TEXT); + CREATE INDEX vocab2w ON vocab2(w COLLATE nocase); + INSERT INTO vocab2 VALUES('abc'), ('ABD'), ('aBe'), ('AbF'); + SELECT next_char('ab', 'vocab2', 'w', null, 'nocase'); +} {cDeF} +do_execsql_test 1.21 { + SELECT next_char('ab','vocab2','w',null,null); +} {c} +do_execsql_test 1.22 { + SELECT next_char('AB','vocab2','w',null,'NOCASE'); +} {cDeF} +do_execsql_test 1.23 { + SELECT next_char('ab','vocab2','w',null,'binary'); +} {c} + +do_execsql_test 2.1 { + CREATE VIRTUAL TABLE t2 USING spellfix1; + INSERT INTO t2 (word, soundslike) VALUES('school', 'skuul'); + INSERT INTO t2 (word, soundslike) VALUES('psalm', 'sarm'); + SELECT word, matchlen FROM t2 WHERE word MATCH 'sar*' LIMIT 5; +} {psalm 4} + +do_execsql_test 2.2 { + SELECT word, matchlen FROM t2 WHERE word MATCH 'skol*' LIMIT 5; +} {school 6} + +set vocab { +kangaroo kanji kappa karate keel keeled keeling keels keen keener keenest +keenly keenness keep keeper keepers keeping keeps ken kennel kennels kept +kerchief kerchiefs kern kernel kernels kerosene ketchup kettle +kettles key keyboard keyboards keyed keyhole keying keynote keypad keypads keys +keystroke keystrokes keyword keywords kick kicked kicker kickers kicking +kickoff kicks kid kidded kiddie kidding kidnap kidnapper kidnappers kidnapping +kidnappings kidnaps kidney kidneys kids kill killed killer killers killing +killingly killings killjoy kills kilobit kilobits kiloblock kilobyte kilobytes +kilogram kilograms kilohertz kilohm kilojoule kilometer kilometers kiloton +kilovolt kilowatt kiloword kimono kin kind kinder kindergarten kindest +kindhearted kindle kindled kindles kindling kindly kindness kindred kinds +kinetic king kingdom kingdoms kingly kingpin kings kink kinky kinship kinsman +kiosk kiss kissed kisser kissers kisses kissing kit kitchen kitchenette +kitchens kite kited kites kiting kits kitten kittenish kittens kitty klaxon +kludge kludges klystron knack knapsack knapsacks knave knaves knead kneads knee +kneecap kneed kneeing kneel kneeled kneeling kneels knees knell knells knelt +knew knife knifed knifes knifing knight knighted knighthood knighting knightly +knights knit knits knives knob knobs knock knockdown knocked knocker knockers +knocking knockout knocks knoll knolls knot knots knotted knotting know knowable +knower knowhow knowing knowingly knowledge knowledgeable known knows knuckle +knuckled knuckles koala kosher kudo +} + +do_execsql_test 3.1 { + CREATE TABLE costs(iLang, cFrom, cTo, iCost); + INSERT INTO costs VALUES(0, 'a', 'e', 1); + INSERT INTO costs VALUES(0, 'e', 'i', 1); + INSERT INTO costs VALUES(0, 'i', 'o', 1); + INSERT INTO costs VALUES(0, 'o', 'u', 1); + INSERT INTO costs VALUES(0, 'u', 'a', 1); + CREATE VIRTUAL TABLE t3 USING spellfix1(edit_cost_table=costs); +} + +do_test 3.2 { + foreach w $vocab { + execsql { INSERT INTO t3(word) VALUES($w) } + } +} {} + +foreach {tn word res} { + 1 kos* {kosher 3 kiosk 4 kudo 2 kiss 3 kissed 3} + 2 kellj* {killjoy 5 kill 4 killed 4 killer 4 killers 4} + 3 kellj {kill 4 kills 5 killjoy 7 keel 4 killed 6} +} { + do_execsql_test 3.2.$tn { + SELECT word, matchlen FROM t3 WHERE word MATCH $word + ORDER BY score, word LIMIT 5 + } $res +} + +do_execsql_test 4.0 { + INSERT INTO t3(command) VALUES('edit_cost_table=NULL'); +} +foreach {tn word res} { + 1 kosher {kosher 0 kisser 51 kissers 76 kissed 126 kisses 126} + 2 kellj {keels 60 killjoy 68 kills 80 keel 120 kill 125} + 3 kashar {kosher 80 kisser 91 kissers 116 kissed 166 kisses 166} +} { + do_execsql_test 4.1.$tn { + SELECT word, distance FROM t3 WHERE word MATCH $word + ORDER BY score, word LIMIT 5 + } $res +} +do_execsql_test 5.0 { + CREATE TABLE costs2(iLang, cFrom, cTo, iCost); + INSERT INTO costs2 VALUES(0, 'a', 'o', 1); + INSERT INTO costs2 VALUES(0, 'e', 'o', 4); + INSERT INTO costs2 VALUES(0, 'i', 'o', 8); + INSERT INTO costs2 VALUES(0, 'u', 'o', 16); + INSERT INTO t3(command) VALUES('edit_cost_table="costs2"'); +} + +foreach {tn word res} { + 1 kasher {kosher 1} + 2 kesher {kosher 4} + 3 kisher {kosher 8} + 4 kosher {kosher 0} + 5 kusher {kosher 16} +} { + do_execsql_test 5.1.$tn { + SELECT word, distance FROM t3 WHERE word MATCH $word + ORDER BY score, word LIMIT 1 + } $res +} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/sqllimits1.test b/components/external/SQLite-3.8.1/test/sqllimits1.test new file mode 100644 index 0000000000000000000000000000000000000000..2cbad3ffb884c0ef6cf8de621bfce6efb4344a4e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/sqllimits1.test @@ -0,0 +1,844 @@ +# 2007 May 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests to verify that the limits defined in +# sqlite source file limits.h are enforced. +# +# $Id: sqllimits1.test,v 1.33 2009/06/25 01:47:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Verify that the default per-connection limits are the same as +# the compile-time hard limits. +# +sqlite3 db2 :memory: +do_test sqllimits1-1.1 { + sqlite3_limit db SQLITE_LIMIT_LENGTH -1 +} $SQLITE_MAX_LENGTH +do_test sqllimits1-1.2 { + sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH -1 +} $SQLITE_MAX_SQL_LENGTH +do_test sqllimits1-1.3 { + sqlite3_limit db SQLITE_LIMIT_COLUMN -1 +} $SQLITE_MAX_COLUMN +do_test sqllimits1-1.4 { + sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH -1 +} $SQLITE_MAX_EXPR_DEPTH +do_test sqllimits1-1.5 { + sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT -1 +} $SQLITE_MAX_COMPOUND_SELECT +do_test sqllimits1-1.6 { + sqlite3_limit db SQLITE_LIMIT_VDBE_OP -1 +} $SQLITE_MAX_VDBE_OP +do_test sqllimits1-1.7 { + sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG -1 +} $SQLITE_MAX_FUNCTION_ARG +do_test sqllimits1-1.8 { + sqlite3_limit db SQLITE_LIMIT_ATTACHED -1 +} $SQLITE_MAX_ATTACHED +do_test sqllimits1-1.9 { + sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH -1 +} $SQLITE_MAX_LIKE_PATTERN_LENGTH +do_test sqllimits1-1.10 { + sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER -1 +} $SQLITE_MAX_VARIABLE_NUMBER + +# Limit parameters out of range. +# +do_test sqllimits1-1.20 { + sqlite3_limit db SQLITE_LIMIT_TOOSMALL 123 +} {-1} +do_test sqllimits1-1.21 { + sqlite3_limit db SQLITE_LIMIT_TOOSMALL 123 +} {-1} +do_test sqllimits1-1.22 { + sqlite3_limit db SQLITE_LIMIT_TOOBIG 123 +} {-1} +do_test sqllimits1-1.23 { + sqlite3_limit db SQLITE_LIMIT_TOOBIG 123 +} {-1} + + +# Decrease all limits by half. Verify that the new limits take. +# +if {$SQLITE_MAX_LENGTH>=2} { + do_test sqllimits1-2.1.1 { + sqlite3_limit db SQLITE_LIMIT_LENGTH \ + [expr {$::SQLITE_MAX_LENGTH/2}] + } $SQLITE_MAX_LENGTH + do_test sqllimits1-2.1.2 { + sqlite3_limit db SQLITE_LIMIT_LENGTH -1 + } [expr {$SQLITE_MAX_LENGTH/2}] +} +if {$SQLITE_MAX_SQL_LENGTH>=2} { + do_test sqllimits1-2.2.1 { + sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH \ + [expr {$::SQLITE_MAX_SQL_LENGTH/2}] + } $SQLITE_MAX_SQL_LENGTH + do_test sqllimits1-2.2.2 { + sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH -1 + } [expr {$SQLITE_MAX_SQL_LENGTH/2}] +} +if {$SQLITE_MAX_COLUMN>=2} { + do_test sqllimits1-2.3.1 { + sqlite3_limit db SQLITE_LIMIT_COLUMN \ + [expr {$::SQLITE_MAX_COLUMN/2}] + } $SQLITE_MAX_COLUMN + do_test sqllimits1-2.3.2 { + sqlite3_limit db SQLITE_LIMIT_COLUMN -1 + } [expr {$SQLITE_MAX_COLUMN/2}] +} +if {$SQLITE_MAX_EXPR_DEPTH>=2} { + do_test sqllimits1-2.4.1 { + sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH \ + [expr {$::SQLITE_MAX_EXPR_DEPTH/2}] + } $SQLITE_MAX_EXPR_DEPTH + do_test sqllimits1-2.4.2 { + sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH -1 + } [expr {$SQLITE_MAX_EXPR_DEPTH/2}] +} +if {$SQLITE_MAX_COMPOUND_SELECT>=2} { + do_test sqllimits1-2.5.1 { + sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT \ + [expr {$::SQLITE_MAX_COMPOUND_SELECT/2}] + } $SQLITE_MAX_COMPOUND_SELECT + do_test sqllimits1-2.5.2 { + sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT -1 + } [expr {$SQLITE_MAX_COMPOUND_SELECT/2}] +} +if {$SQLITE_MAX_VDBE_OP>=2} { + do_test sqllimits1-2.6.1 { + sqlite3_limit db SQLITE_LIMIT_VDBE_OP \ + [expr {$::SQLITE_MAX_VDBE_OP/2}] + } $SQLITE_MAX_VDBE_OP + do_test sqllimits1-2.6.2 { + sqlite3_limit db SQLITE_LIMIT_VDBE_OP -1 + } [expr {$SQLITE_MAX_VDBE_OP/2}] +} +if {$SQLITE_MAX_FUNCTION_ARG>=2} { + do_test sqllimits1-2.7.1 { + sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG \ + [expr {$::SQLITE_MAX_FUNCTION_ARG/2}] + } $SQLITE_MAX_FUNCTION_ARG + do_test sqllimits1-2.7.2 { + sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG -1 + } [expr {$SQLITE_MAX_FUNCTION_ARG/2}] +} +if {$SQLITE_MAX_ATTACHED>=2} { + do_test sqllimits1-2.8.1 { + sqlite3_limit db SQLITE_LIMIT_ATTACHED \ + [expr {$::SQLITE_MAX_ATTACHED/2}] + } $SQLITE_MAX_ATTACHED + do_test sqllimits1-2.8.2 { + sqlite3_limit db SQLITE_LIMIT_ATTACHED -1 + } [expr {$SQLITE_MAX_ATTACHED/2}] +} +if {$SQLITE_MAX_LIKE_PATTERN_LENGTH>=2} { + do_test sqllimits1-2.9.1 { + sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH \ + [expr {$::SQLITE_MAX_LIKE_PATTERN_LENGTH/2}] + } $SQLITE_MAX_LIKE_PATTERN_LENGTH + do_test sqllimits1-2.9.2 { + sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH -1 + } [expr {$SQLITE_MAX_LIKE_PATTERN_LENGTH/2}] +} +if {$SQLITE_MAX_VARIABLE_NUMBER>=2} { + do_test sqllimits1-2.10.1 { + sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER \ + [expr {$::SQLITE_MAX_VARIABLE_NUMBER/2}] + } $SQLITE_MAX_VARIABLE_NUMBER + do_test sqllimits1-2.10.2 { + sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER -1 + } [expr {$SQLITE_MAX_VARIABLE_NUMBER/2}] +} + +# In a separate database connection, verify that the limits are unchanged. +# +do_test sqllimits1-3.1 { + sqlite3_limit db2 SQLITE_LIMIT_LENGTH -1 +} $SQLITE_MAX_LENGTH +do_test sqllimits1-3.2 { + sqlite3_limit db2 SQLITE_LIMIT_SQL_LENGTH -1 +} $SQLITE_MAX_SQL_LENGTH +do_test sqllimits1-3.3 { + sqlite3_limit db2 SQLITE_LIMIT_COLUMN -1 +} $SQLITE_MAX_COLUMN +do_test sqllimits1-3.4 { + sqlite3_limit db2 SQLITE_LIMIT_EXPR_DEPTH -1 +} $SQLITE_MAX_EXPR_DEPTH +do_test sqllimits1-3.5 { + sqlite3_limit db2 SQLITE_LIMIT_COMPOUND_SELECT -1 +} $SQLITE_MAX_COMPOUND_SELECT +do_test sqllimits1-3.6 { + sqlite3_limit db2 SQLITE_LIMIT_VDBE_OP -1 +} $SQLITE_MAX_VDBE_OP +do_test sqllimits1-3.7 { + sqlite3_limit db2 SQLITE_LIMIT_FUNCTION_ARG -1 +} $SQLITE_MAX_FUNCTION_ARG +do_test sqllimits1-3.8 { + sqlite3_limit db2 SQLITE_LIMIT_ATTACHED -1 +} $SQLITE_MAX_ATTACHED +do_test sqllimits1-3.9 { + sqlite3_limit db2 SQLITE_LIMIT_LIKE_PATTERN_LENGTH -1 +} $SQLITE_MAX_LIKE_PATTERN_LENGTH +do_test sqllimits1-3.10 { + sqlite3_limit db2 SQLITE_LIMIT_VARIABLE_NUMBER -1 +} $SQLITE_MAX_VARIABLE_NUMBER +db2 close + +# Attempt to set all limits to the maximum 32-bit integer. Verify +# that the limit does not exceed the compile-time upper bound. +# +do_test sqllimits1-4.1.1 { + sqlite3_limit db SQLITE_LIMIT_LENGTH 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_LENGTH -1 +} $SQLITE_MAX_LENGTH +do_test sqllimits1-4.2.1 { + sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH -1 +} $SQLITE_MAX_SQL_LENGTH +do_test sqllimits1-4.3.1 { + sqlite3_limit db SQLITE_LIMIT_COLUMN 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_COLUMN -1 +} $SQLITE_MAX_COLUMN +do_test sqllimits1-4.4.1 { + sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_EXPR_DEPTH -1 +} $SQLITE_MAX_EXPR_DEPTH +do_test sqllimits1-4.5.1 { + sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_COMPOUND_SELECT -1 +} $SQLITE_MAX_COMPOUND_SELECT +do_test sqllimits1-4.6.1 { + sqlite3_limit db SQLITE_LIMIT_VDBE_OP 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_VDBE_OP -1 +} $SQLITE_MAX_VDBE_OP +do_test sqllimits1-4.7.1 { + sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG -1 +} $SQLITE_MAX_FUNCTION_ARG +do_test sqllimits1-4.8.1 { + sqlite3_limit db SQLITE_LIMIT_ATTACHED 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_ATTACHED -1 +} $SQLITE_MAX_ATTACHED +do_test sqllimits1-4.9.1 { + sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH -1 +} $SQLITE_MAX_LIKE_PATTERN_LENGTH +do_test sqllimits1-4.10.1 { + sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER 0x7fffffff + sqlite3_limit db SQLITE_LIMIT_VARIABLE_NUMBER -1 +} $SQLITE_MAX_VARIABLE_NUMBER + +#-------------------------------------------------------------------- +# Test cases sqllimits1-5.* test that the SQLITE_MAX_LENGTH limit +# is enforced. +# +db close +sqlite3 db test.db +set LARGESIZE 99999 +set SQLITE_LIMIT_LENGTH 100000 +sqlite3_limit db SQLITE_LIMIT_LENGTH $SQLITE_LIMIT_LENGTH + +do_test sqllimits1-5.1.1 { + catchsql { SELECT randomblob(2147483647) } +} {1 {string or blob too big}} +do_test sqllimits1-5.1.2 { + catchsql { SELECT zeroblob(2147483647) } +} {1 {string or blob too big}} + +do_test sqllimits1-5.2 { + catchsql { SELECT LENGTH(randomblob($::LARGESIZE)) } +} [list 0 $LARGESIZE] + +do_test sqllimits1-5.3 { + catchsql { SELECT quote(randomblob($::LARGESIZE)) } +} {1 {string or blob too big}} + +do_test sqllimits1-5.4 { + catchsql { SELECT LENGTH(zeroblob($::LARGESIZE)) } +} [list 0 $LARGESIZE] + +do_test sqllimits1-5.5 { + catchsql { SELECT quote(zeroblob($::LARGESIZE)) } +} {1 {string or blob too big}} + +do_test sqllimits1-5.6 { + catchsql { SELECT zeroblob(-1) } +} {0 {{}}} + +do_test sqllimits1-5.9 { + set ::str [string repeat A 65537] + set ::rep [string repeat B 65537] + catchsql { SELECT replace($::str, 'A', $::rep) } +} {1 {string or blob too big}} + +do_test sqllimits1-5.10 { + set ::str [string repeat %J 2100] + catchsql { SELECT strftime($::str, '2003-10-31') } +} {1 {string or blob too big}} + +do_test sqllimits1-5.11 { + set ::str1 [string repeat A [expr {$SQLITE_LIMIT_LENGTH - 10}]] + set ::str2 [string repeat B [expr {$SQLITE_LIMIT_LENGTH - 10}]] + catchsql { SELECT $::str1 || $::str2 } +} {1 {string or blob too big}} + +do_test sqllimits1-5.12 { + set ::str1 [string repeat ' [expr {$SQLITE_LIMIT_LENGTH - 10}]] + catchsql { SELECT quote($::str1) } +} {1 {string or blob too big}} + +do_test sqllimits1-5.13 { + set ::str1 [string repeat ' [expr {$SQLITE_LIMIT_LENGTH - 10}]] + catchsql { SELECT hex($::str1) } +} {1 {string or blob too big}} + +do_test sqllimits1-5.14.1 { + set ::STMT [sqlite3_prepare db "SELECT ?" -1 TAIL] + sqlite3_bind_zeroblob $::STMT 1 [expr {$SQLITE_LIMIT_LENGTH + 1}] +} {} +do_test sqllimits1-5.14.2 { + sqlite3_step $::STMT +} {SQLITE_ERROR} +do_test sqllimits1-5.14.3 { + sqlite3_reset $::STMT +} {SQLITE_TOOBIG} +do_test sqllimits1-5.14.4 { + set np1 [expr {$SQLITE_LIMIT_LENGTH + 1}] + set ::str1 [string repeat A $np1] + catch {sqlite3_bind_text $::STMT 1 $::str1 -1} res + set res +} {SQLITE_TOOBIG} +ifcapable utf16 { + do_test sqllimits1-5.14.5 { + catch {sqlite3_bind_text16 $::STMT 1 $::str1 -1} res + set res + } {SQLITE_TOOBIG} +} +do_test sqllimits1-5.14.6 { + catch {sqlite3_bind_text $::STMT 1 $::str1 $np1} res + set res +} {SQLITE_TOOBIG} +ifcapable utf16 { + do_test sqllimits1-5.14.7 { + catch {sqlite3_bind_text16 $::STMT 1 $::str1 $np1} res + set res + } {SQLITE_TOOBIG} +} +do_test sqllimits1-5.14.8 { + set n [expr {$np1-1}] + catch {sqlite3_bind_text $::STMT 1 $::str1 $n} res + set res +} {} +do_test sqllimits1-5.14.9 { + catch {sqlite3_bind_text16 $::STMT 1 $::str1 $n} res + set res +} {} +sqlite3_finalize $::STMT + +do_test sqllimits1-5.15 { + execsql { + CREATE TABLE t4(x); + INSERT INTO t4 VALUES(1); + INSERT INTO t4 VALUES(2); + INSERT INTO t4 SELECT 2+x FROM t4; + } + catchsql { + SELECT group_concat(hex(randomblob(20000))) FROM t4; + } +} {1 {string or blob too big}} +db eval {DROP TABLE t4} + +sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH 0x7fffffff +set strvalue [string repeat A $::SQLITE_LIMIT_LENGTH] +do_test sqllimits1-5.16 { + catchsql "SELECT '$strvalue'" +} [list 0 $strvalue] +do_test sqllimits1-5.17.1 { + catchsql "SELECT 'A$strvalue'" +} [list 1 {string or blob too big}] +do_test sqllimits1-5.17.2 { + sqlite3_limit db SQLITE_LIMIT_LENGTH 0x7fffffff + catchsql {SELECT 'A' || $::strvalue} +} [list 0 A$strvalue] +do_test sqllimits1-5.17.3 { + sqlite3_limit db SQLITE_LIMIT_LENGTH $SQLITE_LIMIT_LENGTH + catchsql {SELECT 'A' || $::strvalue} +} [list 1 {string or blob too big}] +set blobvalue [string repeat 41 $::SQLITE_LIMIT_LENGTH] +do_test sqllimits1-5.18 { + catchsql "SELECT x'$blobvalue'" +} [list 0 $strvalue] +do_test sqllimits1-5.19 { + catchsql "SELECT '41$blobvalue'" +} [list 1 {string or blob too big}] +unset blobvalue + +ifcapable datetime { + set strvalue [string repeat D [expr {$SQLITE_LIMIT_LENGTH-12}]] + do_test sqllimits1-5.20 { + catchsql {SELECT strftime('%Y ' || $::strvalue, '2008-01-02')} + } [list 0 [list "2008 $strvalue"]] + do_test sqllimits1-5.21 { + catchsql {SELECT strftime('%Y-%m-%d ' || $::strvalue, '2008-01-02')} + } {1 {string or blob too big}} +} +unset strvalue + +#-------------------------------------------------------------------- +# Test cases sqllimits1-6.* test that the SQLITE_MAX_SQL_LENGTH limit +# is enforced. +# +do_test sqllimits1-6.1 { + sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH 50000 + set sql "SELECT 1 WHERE 1==1" + set tail " /* A comment to take up space in order to make the string\ + longer without increasing the expression depth */\ + AND 1 == 1" + set N [expr {(50000 / [string length $tail])+1}] + append sql [string repeat $tail $N] + catchsql $sql +} {1 {string or blob too big}} +do_test sqllimits1-6.3 { + sqlite3_limit db SQLITE_LIMIT_SQL_LENGTH 50000 + set sql "SELECT 1 WHERE 1==1" + set tail " /* A comment to take up space in order to make the string\ + longer without increasing the expression depth */\ + AND 1 == 1" + set N [expr {(50000 / [string length $tail])+1}] + append sql [string repeat $tail $N] + set nbytes [string length $sql] + append sql { AND 0} + set rc [catch {sqlite3_prepare db $sql $nbytes TAIL} STMT] + lappend rc $STMT +} {1 {(18) statement too long}} +do_test sqllimits1-6.4 { + sqlite3_errmsg db +} {statement too long} + +#-------------------------------------------------------------------- +# Test cases sqllimits1-7.* test that the limit set using the +# max_page_count pragma. +# +do_test sqllimits1-7.1 { + execsql { + PRAGMA max_page_count = 1000; + } +} {1000} +do_test sqllimits1-7.2 { + execsql { CREATE TABLE trig (a INTEGER, b INTEGER); } + + # Set up a tree of triggers to fire when a row is inserted + # into table "trig". + # + # INSERT -> insert_b -> update_b -> insert_a -> update_a (chain 1) + # -> update_a -> insert_a -> update_b (chain 2) + # -> insert_a -> update_b -> insert_b -> update_a (chain 3) + # -> update_a -> insert_b -> update_b (chain 4) + # + # Table starts with N rows. + # + # Chain 1: insert_b (update N rows) + # -> update_b (insert 1 rows) + # -> insert_a (update N rows) + # -> update_a (insert 1 rows) + # + # chains 2, 3 and 4 are similar. Each inserts more than N^2 rows, where + # N is the number of rows at the conclusion of the previous chain. + # + # Therefore, a single insert adds (N^16 plus some) rows to the database. + # A really long loop... + # + execsql { + CREATE TRIGGER update_b BEFORE UPDATE ON trig + FOR EACH ROW BEGIN + INSERT INTO trig VALUES (65, 'update_b'); + END; + + CREATE TRIGGER update_a AFTER UPDATE ON trig + FOR EACH ROW BEGIN + INSERT INTO trig VALUES (65, 'update_a'); + END; + + CREATE TRIGGER insert_b BEFORE INSERT ON trig + FOR EACH ROW BEGIN + UPDATE trig SET a = 1; + END; + + CREATE TRIGGER insert_a AFTER INSERT ON trig + FOR EACH ROW BEGIN + UPDATE trig SET a = 1; + END; + } +} {} + +do_test sqllimits1-7.3 { + execsql { + INSERT INTO trig VALUES (1,1); + } +} {} + +do_test sqllimits1-7.4 { + execsql { + SELECT COUNT(*) FROM trig; + } +} {7} + +# This tries to insert so many rows it fills up the database (limited +# to 1MB, so not that noteworthy an achievement). +# +do_test sqllimits1-7.5 { + catchsql { + INSERT INTO trig VALUES (1,10); + } +} {1 {database or disk is full}} + +do_test sqllimits1-7.6 { + catchsql { + SELECT COUNT(*) FROM trig; + } +} {0 7} + +# Now check the response of the library to opening a file larger than +# the current max_page_count value. The response is to change the +# internal max_page_count value to match the actual size of the file. +if {[db eval {PRAGMA auto_vacuum}]} { + set fsize 1700 +} else { + set fsize 1691 +} +do_test sqllimits1-7.7.1 { + execsql { + PRAGMA max_page_count = 1000000; + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc; + INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc; + INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc; + INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc; + INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc; + INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc; + INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc; + INSERT INTO abc SELECT a||b||c, b||c||a, c||a||b FROM abc; + INSERT INTO abc SELECT a, b, c FROM abc; + INSERT INTO abc SELECT b, a, c FROM abc; + INSERT INTO abc SELECT c, b, a FROM abc; + } + expr [file size test.db] / 1024 +} $fsize +do_test sqllimits1-7.7.2 { + db close + sqlite3 db test.db + execsql { + PRAGMA max_page_count = 1000; + } + execsql { + SELECT count(*) FROM sqlite_master; + } +} {6} +do_test sqllimits1-7.7.3 { + execsql { + PRAGMA max_page_count; + } +} $fsize +do_test sqllimits1-7.7.4 { + execsql { + DROP TABLE abc; + } +} {} + +#-------------------------------------------------------------------- +# Test cases sqllimits1-8.* test the SQLITE_MAX_COLUMN limit. +# +set SQLITE_LIMIT_COLUMN 200 +sqlite3_limit db SQLITE_LIMIT_COLUMN $SQLITE_LIMIT_COLUMN +do_test sqllimits1-8.1 { + # Columns in a table. + set cols [list] + for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} { + lappend cols "c$i" + } + catchsql "CREATE TABLE t([join $cols ,])" +} {1 {too many columns on t}} + +do_test sqllimits1-8.2 { + # Columns in the result-set of a SELECT. + set cols [list] + for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} { + lappend cols "sql AS sql$i" + } + catchsql "SELECT [join $cols ,] FROM sqlite_master" +} {1 {too many columns in result set}} + +do_test sqllimits1-8.3 { + # Columns in the result-set of a sub-SELECT. + set cols [list] + for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} { + lappend cols "sql AS sql$i" + } + catchsql "SELECT sql4 FROM (SELECT [join $cols ,] FROM sqlite_master)" +} {1 {too many columns in result set}} + +do_test sqllimits1-8.4 { + # Columns in an index. + set cols [list] + for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} { + lappend cols c + } + set sql1 "CREATE TABLE t1(c);" + set sql2 "CREATE INDEX i1 ON t1([join $cols ,]);" + catchsql "$sql1 ; $sql2" +} {1 {too many columns in index}} + +do_test sqllimits1-8.5 { + # Columns in a GROUP BY clause. + catchsql "SELECT * FROM t1 GROUP BY [join $cols ,]" +} {1 {too many terms in GROUP BY clause}} + +do_test sqllimits1-8.6 { + # Columns in an ORDER BY clause. + catchsql "SELECT * FROM t1 ORDER BY [join $cols ,]" +} {1 {too many terms in ORDER BY clause}} + +do_test sqllimits1-8.7 { + # Assignments in an UPDATE statement. + set cols [list] + for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} { + lappend cols "c = 1" + } + catchsql "UPDATE t1 SET [join $cols ,];" +} {1 {too many columns in set list}} + +do_test sqllimits1-8.8 { + # Columns in a view definition: + set cols [list] + for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} { + lappend cols "c$i" + } + catchsql "CREATE VIEW v1 AS SELECT [join $cols ,] FROM t1;" +} {1 {too many columns in result set}} + +do_test sqllimits1-8.9 { + # Columns in a view definition (testing * expansion): + set cols [list] + for {set i 0} {$i < $SQLITE_LIMIT_COLUMN} {incr i} { + lappend cols "c$i" + } + catchsql "CREATE TABLE t2([join $cols ,])" + catchsql "CREATE VIEW v1 AS SELECT *, c1 AS o FROM t2;" +} {1 {too many columns in result set}} +do_test sqllimits1-8.10 { + # ORDER BY columns + set cols [list] + for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} { + lappend cols c + } + set sql "SELECT c FROM t1 ORDER BY [join $cols ,]" + catchsql $sql +} {1 {too many terms in ORDER BY clause}} +do_test sqllimits1-8.11 { + # ORDER BY columns + set cols [list] + for {set i 0} {$i <= $SQLITE_LIMIT_COLUMN} {incr i} { + lappend cols [expr {$i%3 + 1}] + } + set sql "SELECT c, c+1, c+2 FROM t1 UNION SELECT c-1, c-2, c-3 FROM t1" + append sql " ORDER BY [join $cols ,]" + catchsql $sql +} {1 {too many terms in ORDER BY clause}} + + +#-------------------------------------------------------------------- +# These tests - sqllimits1-9.* - test that the SQLITE_LIMIT_EXPR_DEPTH +# limit is enforced. The limit refers to the number of terms in +# the expression. +# +if {$SQLITE_MAX_EXPR_DEPTH==0} { + puts -nonewline stderr "WARNING: Compile with -DSQLITE_MAX_EXPR_DEPTH to run " + puts stderr "tests sqllimits1-9.X" +} else { + do_test sqllimits1-9.1 { + set max $::SQLITE_MAX_EXPR_DEPTH + set expr "(1 [string repeat {AND 1 } $max])" + catchsql [subst { + SELECT $expr + }] + } "1 {Expression tree is too large (maximum depth $::SQLITE_MAX_EXPR_DEPTH)}" + + # Attempting to beat the expression depth limit using nested SELECT + # queries causes a parser stack overflow. + do_test sqllimits1-9.2 { + set max $::SQLITE_MAX_EXPR_DEPTH + set expr "SELECT 1" + for {set i 0} {$i <= $max} {incr i} { + set expr "SELECT ($expr)" + } + catchsql [subst { $expr }] + } "1 {parser stack overflow}" + +if 0 { + do_test sqllimits1-9.3 { + execsql { + PRAGMA max_page_count = 1000000; -- 1 GB + CREATE TABLE v0(a); + INSERT INTO v0 VALUES(1); + } + db transaction { + for {set i 1} {$i < 200} {incr i} { + set expr "(a [string repeat {AND 1 } 50]) AS a" + execsql [subst { + CREATE VIEW v${i} AS SELECT $expr FROM v[expr {$i-1}] + }] + } + } + } {} + + do_test sqllimits1-9.4 { + catchsql { + SELECT a FROM v199 + } + } "1 {Expression tree is too large (maximum depth $::SQLITE_MAX_EXPR_DEPTH)}" +} +} + +#-------------------------------------------------------------------- +# Test cases sqllimits1-10.* test that the SQLITE_MAX_VDBE_OP +# limit works as expected. The limit refers to the number of opcodes +# in a single VDBE program. +# +# TODO + +#-------------------------------------------------------------------- +# Test the SQLITE_LIMIT_FUNCTION_ARG limit works. Test case names +# match the pattern "sqllimits1-11.*". +# +for {set max 5} {$max<=$SQLITE_MAX_FUNCTION_ARG} {incr max} { + do_test sqllimits1-11.$max.1 { + set vals [list] + sqlite3_limit db SQLITE_LIMIT_FUNCTION_ARG $::max + for {set i 0} {$i < $::max} {incr i} { + lappend vals $i + } + catchsql "SELECT max([join $vals ,])" + } "0 [expr {$::max - 1}]" + do_test sqllimits1-11.$max.2 { + set vals [list] + for {set i 0} {$i <= $::max} {incr i} { + lappend vals $i + } + catchsql "SELECT max([join $vals ,])" + } {1 {too many arguments on function max}} + + # Test that it is SQLite, and not the implementation of the + # user function that is throwing the error. + proc myfunc {args} {error "I don't like to be called!"} + do_test sqllimits1-11.$max.2 { + db function myfunc myfunc + set vals [list] + for {set i 0} {$i <= $::max} {incr i} { + lappend vals $i + } + catchsql "SELECT myfunc([join $vals ,])" + } {1 {too many arguments on function myfunc}} +} + +#-------------------------------------------------------------------- +# Test cases sqllimits1-12.*: Test the SQLITE_MAX_ATTACHED limit. +# +ifcapable attach { + do_test sqllimits1-12.1 { + set max $::SQLITE_MAX_ATTACHED + for {set i 0} {$i < ($max)} {incr i} { + forcedelete test${i}.db test${i}.db-journal + } + for {set i 0} {$i < ($max)} {incr i} { + execsql "ATTACH 'test${i}.db' AS aux${i}" + } + catchsql "ATTACH 'test${i}.db' AS aux${i}" + } "1 {too many attached databases - max $::SQLITE_MAX_ATTACHED}" + do_test sqllimits1-12.2 { + set max $::SQLITE_MAX_ATTACHED + for {set i 0} {$i < ($max)} {incr i} { + execsql "DETACH aux${i}" + } + } {} +} + +#-------------------------------------------------------------------- +# Test cases sqllimits1-13.*: Check that the SQLITE_MAX_VARIABLE_NUMBER +# limit works. +# +do_test sqllimits1-13.1 { + set max $::SQLITE_MAX_VARIABLE_NUMBER + catchsql "SELECT ?[expr {$max+1}] FROM t1" +} "1 {variable number must be between ?1 and ?$::SQLITE_MAX_VARIABLE_NUMBER}" +do_test sqllimits1-13.2 { + set max $::SQLITE_MAX_VARIABLE_NUMBER + set vals [list] + for {set i 0} {$i < ($max+3)} {incr i} { + lappend vals ? + } + catchsql "SELECT [join $vals ,] FROM t1" +} "1 {too many SQL variables}" + + +#-------------------------------------------------------------------- +# Test cases sqllimits1-15.* verify that the +# SQLITE_MAX_LIKE_PATTERN_LENGTH limit is enforced. This limit only +# applies to the built-in LIKE operator, supplying an external +# implementation by overriding the like() scalar function bypasses +# this limitation. +# +# These tests check that the limit is not incorrectly applied to +# the left-hand-side of the LIKE operator (the string being tested +# against the pattern). +# +set SQLITE_LIMIT_LIKE_PATTERN 1000 +sqlite3_limit db SQLITE_LIMIT_LIKE_PATTERN_LENGTH $SQLITE_LIMIT_LIKE_PATTERN +do_test sqllimits1-15.1 { + set max $::SQLITE_LIMIT_LIKE_PATTERN + set ::pattern [string repeat "A%" [expr $max/2]] + set ::string [string repeat "A" [expr {$max*2}]] + execsql { + SELECT $::string LIKE $::pattern; + } +} {1} +do_test sqllimits1-15.2 { + set max $::SQLITE_LIMIT_LIKE_PATTERN + set ::pattern [string repeat "A%" [expr {($max/2) + 1}]] + set ::string [string repeat "A" [expr {$max*2}]] + catchsql { + SELECT $::string LIKE $::pattern; + } +} {1 {LIKE or GLOB pattern too complex}} + +#-------------------------------------------------------------------- +# This test case doesn't really belong with the other limits tests. +# It is in this file because it is taxing to run, like the limits tests. +# +do_test sqllimits1-16.1 { + set ::N [expr int(([expr pow(2,32)]/50) + 1)] + expr (($::N*50) & 0xffffffff)<55 +} {1} +do_test sqllimits1-16.2 { + set ::format "[string repeat A 60][string repeat "%J" $::N]" + catchsql { + SELECT strftime($::format, 1); + } +} {1 {string or blob too big}} + + +foreach {key value} [array get saved] { + catch {set $key $value} +} +finish_test diff --git a/components/external/SQLite-3.8.1/test/stat.test b/components/external/SQLite-3.8.1/test/stat.test new file mode 100644 index 0000000000000000000000000000000000000000..ac88f7acb3f60798e3b73356d2f7dbaea6fd6d65 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/stat.test @@ -0,0 +1,172 @@ +# 2010 July 09 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the SELECT statement. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab||!compound { + finish_test + return +} + + +set ::asc 1 +proc a_string {n} { string range [string repeat [incr ::asc]. $n] 1 $n } +db func a_string a_string + +register_dbstat_vtab db +do_execsql_test stat-0.0 { + PRAGMA auto_vacuum = OFF; + CREATE VIRTUAL TABLE temp.stat USING dbstat; + SELECT * FROM stat; +} {} + +ifcapable wal { + do_execsql_test stat-0.1 { + PRAGMA journal_mode = WAL; + PRAGMA journal_mode = delete; + SELECT name, path, pageno, pagetype, ncell, payload, unused, mx_payload + FROM stat; + } {wal delete sqlite_master / 1 leaf 0 0 916 0} +} + +do_test stat-1.0 { + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(b); + INSERT INTO t1(rowid, a, b) VALUES(2, 2, 3); + INSERT INTO t1(rowid, a, b) VALUES(3, 4, 5); + } +} {} +do_test stat-1.1 { + execsql { + SELECT name, path, pageno, pagetype, ncell, payload, unused, mx_payload + FROM stat WHERE name = 't1'; + } +} {t1 / 2 leaf 2 10 998 5} +do_test stat-1.2 { + execsql { + SELECT name, path, pageno, pagetype, ncell, payload, unused, mx_payload + FROM stat WHERE name = 'i1'; + } +} {i1 / 3 leaf 2 10 1000 5} +do_test stat-1.3 { + execsql { + SELECT name, path, pageno, pagetype, ncell, payload, unused, mx_payload + FROM stat WHERE name = 'sqlite_master'; + } +} {sqlite_master / 1 leaf 2 77 831 40} +do_test stat-1.4 { + execsql { + DROP TABLE t1; + } +} {} + +do_execsql_test stat-2.1 { + CREATE TABLE t3(a PRIMARY KEY, b); + INSERT INTO t3(rowid, a, b) VALUES(2, a_string(111), a_string(222)); + INSERT INTO t3 SELECT a_string(110+rowid), a_string(221+rowid) FROM t3 + ORDER BY rowid; + INSERT INTO t3 SELECT a_string(110+rowid), a_string(221+rowid) FROM t3 + ORDER BY rowid; + INSERT INTO t3 SELECT a_string(110+rowid), a_string(221+rowid) FROM t3 + ORDER BY rowid; + INSERT INTO t3 SELECT a_string(110+rowid), a_string(221+rowid) FROM t3 + ORDER BY rowid; + INSERT INTO t3 SELECT a_string(110+rowid), a_string(221+rowid) FROM t3 + ORDER BY rowid; + SELECT name, path, pageno, pagetype, ncell, payload, unused, mx_payload + FROM stat WHERE name != 'sqlite_master'; +} [list \ + sqlite_autoindex_t3_1 / 3 internal 3 368 623 125 \ + sqlite_autoindex_t3_1 /000/ 8 leaf 8 946 46 123 \ + sqlite_autoindex_t3_1 /001/ 9 leaf 8 988 2 131 \ + sqlite_autoindex_t3_1 /002/ 15 leaf 7 857 137 132 \ + sqlite_autoindex_t3_1 /003/ 20 leaf 6 739 257 129 \ + t3 / 2 internal 15 0 907 0 \ + t3 /000/ 4 leaf 2 678 328 340 \ + t3 /001/ 5 leaf 2 682 324 342 \ + t3 /002/ 6 leaf 2 682 324 342 \ + t3 /003/ 7 leaf 2 690 316 346 \ + t3 /004/ 10 leaf 2 682 324 342 \ + t3 /005/ 11 leaf 2 690 316 346 \ + t3 /006/ 12 leaf 2 698 308 350 \ + t3 /007/ 13 leaf 2 706 300 354 \ + t3 /008/ 14 leaf 2 682 324 342 \ + t3 /009/ 16 leaf 2 690 316 346 \ + t3 /00a/ 17 leaf 2 698 308 350 \ + t3 /00b/ 18 leaf 2 706 300 354 \ + t3 /00c/ 19 leaf 2 714 292 358 \ + t3 /00d/ 21 leaf 2 722 284 362 \ + t3 /00e/ 22 leaf 2 730 276 366 \ + t3 /00f/ 23 leaf 2 738 268 370 \ +] +do_execsql_test stat-2.2 { DROP TABLE t3 } {} + +do_execsql_test stat-3.1 { + CREATE TABLE t4(x); + CREATE INDEX i4 ON t4(x); + INSERT INTO t4(rowid, x) VALUES(2, a_string(7777)); + SELECT name, path, pageno, pagetype, ncell, payload, unused, mx_payload + FROM stat WHERE name != 'sqlite_master'; +} [list \ + i4 / 3 leaf 1 103 905 7782 \ + i4 /000+000000 9 overflow 0 1020 0 0 \ + i4 /000+000001 10 overflow 0 1020 0 0 \ + i4 /000+000002 11 overflow 0 1020 0 0 \ + i4 /000+000003 12 overflow 0 1020 0 0 \ + i4 /000+000004 13 overflow 0 1020 0 0 \ + i4 /000+000005 14 overflow 0 1020 0 0 \ + i4 /000+000006 15 overflow 0 1020 0 0 \ + i4 /000+000007 16 overflow 0 539 481 0 \ + t4 / 2 leaf 1 640 367 7780 \ + t4 /000+000000 22 overflow 0 1020 0 0 \ + t4 /000+000001 23 overflow 0 1020 0 0 \ + t4 /000+000002 21 overflow 0 1020 0 0 \ + t4 /000+000003 20 overflow 0 1020 0 0 \ + t4 /000+000004 19 overflow 0 1020 0 0 \ + t4 /000+000005 18 overflow 0 1020 0 0 \ + t4 /000+000006 17 overflow 0 1020 0 0 \ +] + +do_execsql_test stat-4.1 { + CREATE TABLE t5(x); + CREATE INDEX i5 ON t5(x); + SELECT name, path, pageno, pagetype, ncell, payload, unused, mx_payload + FROM stat WHERE name = 't5' OR name = 'i5'; +} [list \ + i5 / 5 leaf 0 0 1016 0 \ + t5 / 4 leaf 0 0 1016 0 \ +] + +db close +forcedelete test.db +sqlite3 db test.db +register_dbstat_vtab db +breakpoint +do_execsql_test stat-5.1 { + PRAGMA auto_vacuum = OFF; + CREATE VIRTUAL TABLE temp.stat USING dbstat; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(zeroblob(1513)); + INSERT INTO t1 VALUES(zeroblob(1514)); + SELECT name, path, pageno, pagetype, ncell, payload, unused, mx_payload + FROM stat WHERE name = 't1'; +} [list \ + t1 / 2 leaf 2 993 5 1517 \ + t1 /000+000000 3 overflow 0 1020 0 0 \ + t1 /001+000000 4 overflow 0 1020 0 0 \ +] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/stmt.test b/components/external/SQLite-3.8.1/test/stmt.test new file mode 100644 index 0000000000000000000000000000000000000000..49a41414b779dc1f9cd113a5aaf9a4337d431bf2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/stmt.test @@ -0,0 +1,97 @@ +# 2010 February 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# The tests in this file check that SQLite uses (or does not use) a +# statement journal for various SQL statements. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test stmt-1.1 { + execsql { CREATE TABLE t1(a integer primary key, b INTEGER NOT NULL) } +} {} + +# The following tests verify the method used for the tests in this file - +# that if a statement journal is required by a statement it is opened and +# remains open until the current transaction is committed or rolled back. +# +# This only work if SQLITE_TEMP_STORE!=3 +# +if {$::TEMP_STORE==3} { + finish_test + return +} +do_test stmt-1.2 { + set sqlite_open_file_count +} {1} +do_test stmt-1.3 { + execsql { + PRAGMA temp_store = file; + BEGIN; + INSERT INTO t1 VALUES(1, 1); + } + set sqlite_open_file_count +} {2} +do_test stmt-1.4 { + execsql { + INSERT INTO t1 SELECT a+1, b+1 FROM t1; + } + set sqlite_open_file_count +} {3} +do_test stmt-1.5 { + execsql COMMIT + set sqlite_open_file_count +} {1} +do_test stmt-1.6.1 { + execsql { + BEGIN; + INSERT INTO t1 SELECT a+2, b+2 FROM t1; + } + set sqlite_open_file_count +} {2} +do_test stmt-1.6.2 { + execsql { INSERT INTO t1 SELECT a+4, b+4 FROM t1 } + set sqlite_open_file_count +} {3} +do_test stmt-1.7 { + execsql COMMIT + set sqlite_open_file_count +} {1} + + +proc filecount {testname sql expected} { + uplevel [list do_test $testname [subst -nocommand { + execsql BEGIN + execsql { $sql } + set ret [set sqlite_open_file_count] + execsql ROLLBACK + set ret + }] $expected] +} + +filecount stmt-2.1 { INSERT INTO t1 VALUES(9, 9) } 2 +filecount stmt-2.2 { REPLACE INTO t1 VALUES(9, 9) } 2 +filecount stmt-2.3 { INSERT INTO t1 SELECT 9, 9 } 2 +filecount stmt-2.4 { + INSERT INTO t1 SELECT 9, 9; + INSERT INTO t1 SELECT 10, 10; +} 3 + +do_test stmt-2.5 { + execsql { CREATE INDEX i1 ON t1(b) } +} {} +filecount stmt-2.6 { + REPLACE INTO t1 VALUES(5, 5); + REPLACE INTO t1 VALUES(5, 5); +} 3 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/subquery.test b/components/external/SQLite-3.8.1/test/subquery.test new file mode 100644 index 0000000000000000000000000000000000000000..93c3f28ddbb7e17f06cf406026f96acc808bfbcc --- /dev/null +++ b/components/external/SQLite-3.8.1/test/subquery.test @@ -0,0 +1,587 @@ +# 2005 January 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing correlated subqueries +# +# $Id: subquery.test,v 1.17 2009/01/09 01:12:28 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !subquery { + finish_test + return +} + +do_test subquery-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + INSERT INTO t1 VALUES(5,6); + INSERT INTO t1 VALUES(7,8); + CREATE TABLE t2(x,y); + INSERT INTO t2 VALUES(1,1); + INSERT INTO t2 VALUES(3,9); + INSERT INTO t2 VALUES(5,25); + INSERT INTO t2 VALUES(7,49); + COMMIT; + } + execsql { + SELECT a, (SELECT y FROM t2 WHERE x=a) FROM t1 WHERE b<8 + } +} {1 1 3 9 5 25} +do_test subquery-1.2 { + execsql { + UPDATE t1 SET b=b+(SELECT y FROM t2 WHERE x=a); + SELECT * FROM t1; + } +} {1 3 3 13 5 31 7 57} + +do_test subquery-1.3 { + execsql { + SELECT b FROM t1 WHERE EXISTS(SELECT * FROM t2 WHERE y=a) + } +} {3} +do_test subquery-1.4 { + execsql { + SELECT b FROM t1 WHERE NOT EXISTS(SELECT * FROM t2 WHERE y=a) + } +} {13 31 57} + +# Simple tests to make sure correlated subqueries in WHERE clauses +# are used by the query optimizer correctly. +do_test subquery-1.5 { + execsql { + SELECT a, x FROM t1, t2 WHERE t1.a = (SELECT x); + } +} {1 1 3 3 5 5 7 7} +do_test subquery-1.6 { + execsql { + CREATE INDEX i1 ON t1(a); + SELECT a, x FROM t1, t2 WHERE t1.a = (SELECT x); + } +} {1 1 3 3 5 5 7 7} +do_test subquery-1.7 { + execsql { + SELECT a, x FROM t2, t1 WHERE t1.a = (SELECT x); + } +} {1 1 3 3 5 5 7 7} + +# Try an aggregate in both the subquery and the parent query. +do_test subquery-1.8 { + execsql { + SELECT count(*) FROM t1 WHERE a > (SELECT count(*) FROM t2); + } +} {2} + +# Test a correlated subquery disables the "only open the index" optimization. +do_test subquery-1.9.1 { + execsql { + SELECT (y*2)>b FROM t1, t2 WHERE a=x; + } +} {0 1 1 1} +do_test subquery-1.9.2 { + execsql { + SELECT a FROM t1 WHERE (SELECT (y*2)>b FROM t2 WHERE a=x); + } +} {3 5 7} + +# Test that the flattening optimization works with subquery expressions. +do_test subquery-1.10.1 { + execsql { + SELECT (SELECT a), b FROM t1; + } +} {1 3 3 13 5 31 7 57} +do_test subquery-1.10.2 { + execsql { + SELECT * FROM (SELECT (SELECT a), b FROM t1); + } +} {1 3 3 13 5 31 7 57} +do_test subquery-1.10.3 { + execsql { + SELECT * FROM (SELECT (SELECT sum(a) FROM t1)); + } +} {16} +do_test subquery-1.10.4 { + execsql { + CREATE TABLE t5 (val int, period text PRIMARY KEY); + INSERT INTO t5 VALUES(5, '2001-3'); + INSERT INTO t5 VALUES(10, '2001-4'); + INSERT INTO t5 VALUES(15, '2002-1'); + INSERT INTO t5 VALUES(5, '2002-2'); + INSERT INTO t5 VALUES(10, '2002-3'); + INSERT INTO t5 VALUES(15, '2002-4'); + INSERT INTO t5 VALUES(10, '2003-1'); + INSERT INTO t5 VALUES(5, '2003-2'); + INSERT INTO t5 VALUES(25, '2003-3'); + INSERT INTO t5 VALUES(5, '2003-4'); + + SELECT period, vsum + FROM (SELECT + a.period, + (select sum(val) from t5 where period between a.period and '2002-4') vsum + FROM t5 a where a.period between '2002-1' and '2002-4') + WHERE vsum < 45 ; + } +} {2002-2 30 2002-3 25 2002-4 15} +do_test subquery-1.10.5 { + execsql { + SELECT period, vsum from + (select a.period, + (select sum(val) from t5 where period between a.period and '2002-4') vsum + FROM t5 a where a.period between '2002-1' and '2002-4') + WHERE vsum < 45 ; + } +} {2002-2 30 2002-3 25 2002-4 15} +do_test subquery-1.10.6 { + execsql { + DROP TABLE t5; + } +} {} + + + +#------------------------------------------------------------------ +# The following test cases - subquery-2.* - are not logically +# organized. They're here largely because they were failing during +# one stage of development of sub-queries. +# +do_test subquery-2.1 { + execsql { + SELECT (SELECT 10); + } +} {10} +do_test subquery-2.2.1 { + execsql { + CREATE TABLE t3(a PRIMARY KEY, b); + INSERT INTO t3 VALUES(1, 2); + INSERT INTO t3 VALUES(3, 1); + } +} {} +do_test subquery-2.2.2 { + execsql { + SELECT * FROM t3 WHERE a IN (SELECT b FROM t3); + } +} {1 2} +do_test subquery-2.2.3 { + execsql { + DROP TABLE t3; + } +} {} +do_test subquery-2.3.1 { + execsql { + CREATE TABLE t3(a TEXT); + INSERT INTO t3 VALUES('10'); + } +} {} +do_test subquery-2.3.2 { + execsql { + SELECT a IN (10.0, 20) FROM t3; + } +} {0} +do_test subquery-2.3.3 { + execsql { + DROP TABLE t3; + } +} {} +do_test subquery-2.4.1 { + execsql { + CREATE TABLE t3(a TEXT); + INSERT INTO t3 VALUES('XX'); + } +} {} +do_test subquery-2.4.2 { + execsql { + SELECT count(*) FROM t3 WHERE a IN (SELECT 'XX') + } +} {1} +do_test subquery-2.4.3 { + execsql { + DROP TABLE t3; + } +} {} +do_test subquery-2.5.1 { + execsql { + CREATE TABLE t3(a INTEGER); + INSERT INTO t3 VALUES(10); + + CREATE TABLE t4(x TEXT); + INSERT INTO t4 VALUES('10.0'); + } +} {} +do_test subquery-2.5.2 { + # In the expr "x IN (SELECT a FROM t3)" the RHS of the IN operator + # has text affinity and the LHS has integer affinity. The rule is + # that we try to convert both sides to an integer before doing the + # comparision. Hence, the integer value 10 in t3 will compare equal + # to the string value '10.0' in t4 because the t4 value will be + # converted into an integer. + execsql { + SELECT * FROM t4 WHERE x IN (SELECT a FROM t3); + } +} {10.0} +do_test subquery-2.5.3.1 { + # The t4i index cannot be used to resolve the "x IN (...)" constraint + # because the constraint has integer affinity but t4i has text affinity. + execsql { + CREATE INDEX t4i ON t4(x); + SELECT * FROM t4 WHERE x IN (SELECT a FROM t3); + } +} {10.0} +do_test subquery-2.5.3.2 { + # Verify that the t4i index was not used in the previous query + execsql { + EXPLAIN QUERY PLAN + SELECT * FROM t4 WHERE x IN (SELECT a FROM t3); + } +} {~/t4i/} +do_test subquery-2.5.4 { + execsql { + DROP TABLE t3; + DROP TABLE t4; + } +} {} + +#------------------------------------------------------------------ +# The following test cases - subquery-3.* - test tickets that +# were raised during development of correlated subqueries. +# + +# Ticket 1083 +ifcapable view { + do_test subquery-3.1 { + catchsql { DROP TABLE t1; } + catchsql { DROP TABLE t2; } + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + CREATE VIEW v1 AS SELECT b FROM t1 WHERE a>0; + CREATE TABLE t2(p,q); + INSERT INTO t2 VALUES(2,9); + SELECT * FROM v1 WHERE EXISTS(SELECT * FROM t2 WHERE p=v1.b); + } + } {2} + do_test subquery-3.1.1 { + execsql { + SELECT * FROM v1 WHERE EXISTS(SELECT 1); + } + } {2} +} else { + catchsql { DROP TABLE t1; } + catchsql { DROP TABLE t2; } + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + CREATE TABLE t2(p,q); + INSERT INTO t2 VALUES(2,9); + } +} + +# Ticket 1084 +do_test subquery-3.2 { + catchsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + } + execsql { + SELECT (SELECT t1.a) FROM t1; + } +} {1} + +# Test Cases subquery-3.3.* test correlated subqueries where the +# parent query is an aggregate query. Ticket #1105 is an example +# of such a query. +# +do_test subquery-3.3.1 { + execsql { + SELECT a, (SELECT b) FROM t1 GROUP BY a; + } +} {1 2} +do_test subquery-3.3.2 { + catchsql {DROP TABLE t2} + execsql { + CREATE TABLE t2(c, d); + INSERT INTO t2 VALUES(1, 'one'); + INSERT INTO t2 VALUES(2, 'two'); + SELECT a, (SELECT d FROM t2 WHERE a=c) FROM t1 GROUP BY a; + } +} {1 one} +do_test subquery-3.3.3 { + execsql { + INSERT INTO t1 VALUES(2, 4); + SELECT max(a), (SELECT d FROM t2 WHERE a=c) FROM t1; + } +} {2 two} +do_test subquery-3.3.4 { + execsql { + SELECT a, (SELECT (SELECT d FROM t2 WHERE a=c)) FROM t1 GROUP BY a; + } +} {1 one 2 two} +do_test subquery-3.3.5 { + execsql { + SELECT a, (SELECT count(*) FROM t2 WHERE a=c) FROM t1; + } +} {1 1 2 1} + +# The following tests check for aggregate subqueries in an aggregate +# query. +# +do_test subquery-3.4.1 { + execsql { + CREATE TABLE t34(x,y); + INSERT INTO t34 VALUES(106,4), (107,3), (106,5), (107,5); + SELECT a.x, avg(a.y) + FROM t34 AS a + GROUP BY a.x + HAVING NOT EXISTS( SELECT b.x, avg(b.y) + FROM t34 AS b + GROUP BY b.x + HAVING avg(a.y) > avg(b.y)); + } +} {107 4.0} +do_test subquery-3.4.2 { + execsql { + SELECT a.x, avg(a.y) AS avg1 + FROM t34 AS a + GROUP BY a.x + HAVING NOT EXISTS( SELECT b.x, avg(b.y) AS avg2 + FROM t34 AS b + GROUP BY b.x + HAVING avg1 > avg2); + } +} {107 4.0} +do_test subquery-3.4.3 { + execsql { + SELECT + a.x, + avg(a.y), + NOT EXISTS ( SELECT b.x, avg(b.y) + FROM t34 AS b + GROUP BY b.x + HAVING avg(a.y) > avg(b.y)), + EXISTS ( SELECT c.x, avg(c.y) + FROM t34 AS c + GROUP BY c.x + HAVING avg(a.y) > avg(c.y)) + FROM t34 AS a + GROUP BY a.x + ORDER BY a.x; + } +} {106 4.5 0 1 107 4.0 1 0} + +do_test subquery-3.5.1 { + execsql { + CREATE TABLE t35a(x); INSERT INTO t35a VALUES(1),(2),(3); + CREATE TABLE t35b(y); INSERT INTO t35b VALUES(98), (99); + SELECT max((SELECT avg(y) FROM t35b)) FROM t35a; + } +} {98.5} +do_test subquery-3.5.2 { + execsql { + SELECT max((SELECT count(y) FROM t35b)) FROM t35a; + } +} {2} +do_test subquery-3.5.3 { + execsql { + SELECT max((SELECT count() FROM t35b)) FROM t35a; + } +} {2} +do_test subquery-3.5.4 { + catchsql { + SELECT max((SELECT count(x) FROM t35b)) FROM t35a; + } +} {1 {misuse of aggregate: count()}} +do_test subquery-3.5.5 { + catchsql { + SELECT max((SELECT count(x) FROM t35b)) FROM t35a; + } +} {1 {misuse of aggregate: count()}} +do_test subquery-3.5.6 { + catchsql { + SELECT max((SELECT a FROM (SELECT count(x) AS a FROM t35b))) FROM t35a; + } +} {1 {misuse of aggregate: count()}} +do_test subquery-3.5.7 { + execsql { + SELECT max((SELECT a FROM (SELECT count(y) AS a FROM t35b))) FROM t35a; + } +} {2} + + +#------------------------------------------------------------------ +# These tests - subquery-4.* - use the TCL statement cache to try +# and expose bugs to do with re-using statements that have been +# passed to sqlite3_reset(). +# +# One problem was that VDBE memory cells were not being initialized +# to NULL on the second and subsequent executions. +# +do_test subquery-4.1.1 { + execsql { + SELECT (SELECT a FROM t1); + } +} {1} +do_test subquery-4.2 { + execsql { + DELETE FROM t1; + SELECT (SELECT a FROM t1); + } +} {{}} +do_test subquery-4.2.1 { + execsql { + CREATE TABLE t3(a PRIMARY KEY); + INSERT INTO t3 VALUES(10); + } + execsql {INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1)} +} {} +do_test subquery-4.2.2 { + execsql {INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1)} +} {} + +#------------------------------------------------------------------ +# The subquery-5.* tests make sure string literals in double-quotes +# are handled efficiently. Double-quote literals are first checked +# to see if they match any column names. If there is not column name +# match then those literals are used a string constants. When a +# double-quoted string appears, we want to make sure that the search +# for a matching column name did not cause an otherwise static subquery +# to become a dynamic (correlated) subquery. +# +do_test subquery-5.1 { + proc callcntproc {n} { + incr ::callcnt + return $n + } + set callcnt 0 + db function callcnt callcntproc + execsql { + CREATE TABLE t4(x,y); + INSERT INTO t4 VALUES('one',1); + INSERT INTO t4 VALUES('two',2); + INSERT INTO t4 VALUES('three',3); + INSERT INTO t4 VALUES('four',4); + CREATE TABLE t5(a,b); + INSERT INTO t5 VALUES(1,11); + INSERT INTO t5 VALUES(2,22); + INSERT INTO t5 VALUES(3,33); + INSERT INTO t5 VALUES(4,44); + SELECT b FROM t5 WHERE a IN + (SELECT callcnt(y)+0 FROM t4 WHERE x="two") + } +} {22} +do_test subquery-5.2 { + # This is the key test. The subquery should have only run once. If + # The double-quoted identifier "two" were causing the subquery to be + # processed as a correlated subquery, then it would have run 4 times. + set callcnt +} {1} + + +# Ticket #1380. Make sure correlated subqueries on an IN clause work +# correctly when the left-hand side of the IN operator is constant. +# +do_test subquery-6.1 { + set callcnt 0 + execsql { + SELECT x FROM t4 WHERE 1 IN (SELECT callcnt(count(*)) FROM t5 WHERE a=y) + } +} {one two three four} +do_test subquery-6.2 { + set callcnt +} {4} +do_test subquery-6.3 { + set callcnt 0 + execsql { + SELECT x FROM t4 WHERE 1 IN (SELECT callcnt(count(*)) FROM t5 WHERE a=1) + } +} {one two three four} +do_test subquery-6.4 { + set callcnt +} {1} + +if 0 { ############# disable until we get #2652 fixed +# Ticket #2652. Allow aggregate functions of outer queries inside +# a non-aggregate subquery. +# +do_test subquery-7.1 { + execsql { + CREATE TABLE t7(c7); + INSERT INTO t7 VALUES(1); + INSERT INTO t7 VALUES(2); + INSERT INTO t7 VALUES(3); + CREATE TABLE t8(c8); + INSERT INTO t8 VALUES(100); + INSERT INTO t8 VALUES(200); + INSERT INTO t8 VALUES(300); + CREATE TABLE t9(c9); + INSERT INTO t9 VALUES(10000); + INSERT INTO t9 VALUES(20000); + INSERT INTO t9 VALUES(30000); + + SELECT (SELECT c7+c8 FROM t7) FROM t8; + } +} {101 201 301} +do_test subquery-7.2 { + execsql { + SELECT (SELECT max(c7)+c8 FROM t7) FROM t8; + } +} {103 203 303} +do_test subquery-7.3 { + execsql { + SELECT (SELECT c7+max(c8) FROM t8) FROM t7 + } +} {301} +do_test subquery-7.4 { + execsql { + SELECT (SELECT max(c7)+max(c8) FROM t8) FROM t7 + } +} {303} +do_test subquery-7.5 { + execsql { + SELECT (SELECT c8 FROM t8 WHERE rowid=max(c7)) FROM t7 + } +} {300} +do_test subquery-7.6 { + execsql { + SELECT (SELECT (SELECT max(c7+c8+c9) FROM t9) FROM t8) FROM t7 + } +} {30101 30102 30103} +do_test subquery-7.7 { + execsql { + SELECT (SELECT (SELECT c7+max(c8+c9) FROM t9) FROM t8) FROM t7 + } +} {30101 30102 30103} +do_test subquery-7.8 { + execsql { + SELECT (SELECT (SELECT max(c7)+c8+c9 FROM t9) FROM t8) FROM t7 + } +} {10103} +do_test subquery-7.9 { + execsql { + SELECT (SELECT (SELECT c7+max(c8)+c9 FROM t9) FROM t8) FROM t7 + } +} {10301 10302 10303} +do_test subquery-7.10 { + execsql { + SELECT (SELECT (SELECT c7+c8+max(c9) FROM t9) FROM t8) FROM t7 + } +} {30101 30102 30103} +do_test subquery-7.11 { + execsql { + SELECT (SELECT (SELECT max(c7)+max(c8)+max(c9) FROM t9) FROM t8) FROM t7 + } +} {30303} +} ;############# Disabled + +finish_test diff --git a/components/external/SQLite-3.8.1/test/subquery2.test b/components/external/SQLite-3.8.1/test/subquery2.test new file mode 100644 index 0000000000000000000000000000000000000000..4406efccf2797b0e7779aaf5ef268e45e1486101 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/subquery2.test @@ -0,0 +1,107 @@ +# 2011 September 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing correlated subqueries +# +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix subquery2 + +ifcapable !subquery { + finish_test + return +} + +do_test subquery2-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + INSERT INTO t1 VALUES(5,6); + INSERT INTO t1 VALUES(7,8); + CREATE TABLE t2(c,d); + INSERT INTO t2 VALUES(1,1); + INSERT INTO t2 VALUES(3,9); + INSERT INTO t2 VALUES(5,25); + INSERT INTO t2 VALUES(7,49); + CREATE TABLE t3(e,f); + INSERT INTO t3 VALUES(1,1); + INSERT INTO t3 VALUES(3,27); + INSERT INTO t3 VALUES(5,125); + INSERT INTO t3 VALUES(7,343); + COMMIT; + } + execsql { + SELECT a FROM t1 + WHERE b IN (SELECT x+1 FROM (SELECT DISTINCT f/(a*a) AS x FROM t3)); + } +} {1 3 5 7} +do_test subquery2-1.2 { + execsql { + CREATE INDEX t1b ON t1(b); + SELECT a FROM t1 + WHERE b IN (SELECT x+1 FROM (SELECT DISTINCT f/(a*a) AS x FROM t3)); + } +} {1 3 5 7} + +do_test subquery2-1.11 { + execsql { + SELECT a FROM t1 + WHERE +b=(SELECT x+1 FROM (SELECT DISTINCT f/(a*a) AS x FROM t3)); + } +} {1} +do_test subquery2-1.12 { + execsql { + SELECT a FROM t1 + WHERE b=(SELECT x+1 FROM (SELECT DISTINCT f/(a*a) AS x FROM t3)); + } +} {1} + +do_test subquery2-1.21 { + execsql { + SELECT a FROM t1 + WHERE +b=(SELECT x+1 FROM + (SELECT DISTINCT f/d AS x FROM t2 JOIN t3 ON d*a=f)) + } +} {1 3 5 7} +do_test subquery2-1.22 { + execsql { + SELECT a FROM t1 + WHERE b=(SELECT x+1 FROM + (SELECT DISTINCT f/d AS x FROM t2 JOIN t3 ON d*a=f)) + } +} {1 3 5 7} + +#------------------------------------------------------------------------- +# Test that ticket d6b36be38a has been fixed. +do_execsql_test 2.1 { + CREATE TABLE t4(a, b); + CREATE TABLE t5(a, b); + INSERT INTO t5 VALUES(3, 5); + + INSERT INTO t4 VALUES(1, 1); + INSERT INTO t4 VALUES(2, 3); + INSERT INTO t4 VALUES(3, 6); + INSERT INTO t4 VALUES(4, 10); + INSERT INTO t4 VALUES(5, 15); +} + +do_execsql_test 2.2 { + SELECT * + FROM (SELECT * FROM t4 ORDER BY a LIMIT -1 OFFSET 1) + LIMIT (SELECT a FROM t5) +} {2 3 3 6 4 10} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/subselect.test b/components/external/SQLite-3.8.1/test/subselect.test new file mode 100644 index 0000000000000000000000000000000000000000..247f68ee80ef6ebeb99375faf27c06fecc32d9aa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/subselect.test @@ -0,0 +1,210 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing SELECT statements that are part of +# expressions. +# +# $Id: subselect.test,v 1.16 2008/08/04 03:51:24 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Omit this whole file if the library is build without subquery support. +ifcapable !subquery { + finish_test + return +} + +# Basic sanity checking. Try a simple subselect. +# +do_test subselect-1.1 { + execsql { + CREATE TABLE t1(a int, b int); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + INSERT INTO t1 VALUES(5,6); + } + execsql {SELECT * FROM t1 WHERE a = (SELECT count(*) FROM t1)} +} {3 4} + +# Try a select with more than one result column. +# +do_test subselect-1.2 { + set v [catch {execsql {SELECT * FROM t1 WHERE a = (SELECT * FROM t1)}} msg] + lappend v $msg +} {1 {only a single result allowed for a SELECT that is part of an expression}} + +# A subselect without an aggregate. +# +do_test subselect-1.3a { + execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=2)} +} {2} +do_test subselect-1.3b { + execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=4)} +} {4} +do_test subselect-1.3c { + execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=6)} +} {6} +do_test subselect-1.3d { + execsql {SELECT b from t1 where a = (SELECT a FROM t1 WHERE b=8)} +} {} +ifcapable compound { + do_test subselect-1.3e { + execsql { + SELECT b FROM t1 + WHERE a = (SELECT a FROM t1 UNION SELECT b FROM t1 ORDER BY 1); + } + } {2} +} + +# What if the subselect doesn't return any value. We should get +# NULL as the result. Check it out. +# +do_test subselect-1.4 { + execsql {SELECT b from t1 where a = coalesce((SELECT a FROM t1 WHERE b=5),1)} +} {2} + +# Try multiple subselects within a single expression. +# +do_test subselect-1.5 { + execsql { + CREATE TABLE t2(x int, y int); + INSERT INTO t2 VALUES(1,2); + INSERT INTO t2 VALUES(2,4); + INSERT INTO t2 VALUES(3,8); + INSERT INTO t2 VALUES(4,16); + } + execsql { + SELECT y from t2 + WHERE x = (SELECT sum(b) FROM t1 where a notnull) - (SELECT sum(a) FROM t1) + } +} {8} + +# Try something useful. Delete every entry from t2 where the +# x value is less than half of the maximum. +# +do_test subselect-1.6 { + execsql {DELETE FROM t2 WHERE x < 0.5*(SELECT max(x) FROM t2)} + execsql {SELECT x FROM t2 ORDER BY x} +} {2 3 4} + +# Make sure sorting works for SELECTs there used as a scalar expression. +# +do_test subselect-2.1 { + execsql { + SELECT (SELECT a FROM t1 ORDER BY a), (SELECT a FROM t1 ORDER BY a DESC) + } +} {1 5} +do_test subselect-2.2 { + execsql { + SELECT 1 IN (SELECT a FROM t1 ORDER BY a); + } +} {1} +do_test subselect-2.3 { + execsql { + SELECT 2 IN (SELECT a FROM t1 ORDER BY a DESC); + } +} {0} + +# Verify that the ORDER BY clause is honored in a subquery. +# +ifcapable compound { +do_test subselect-3.1 { + execsql { + CREATE TABLE t3(x int); + INSERT INTO t3 SELECT a FROM t1 UNION ALL SELECT b FROM t1; + SELECT * FROM t3 ORDER BY x; + } +} {1 2 3 4 5 6} +} ;# ifcapable compound +ifcapable !compound { +do_test subselect-3.1 { + execsql { + CREATE TABLE t3(x int); + INSERT INTO t3 SELECT a FROM t1; + INSERT INTO t3 SELECT b FROM t1; + SELECT * FROM t3 ORDER BY x; + } +} {1 2 3 4 5 6} +} ;# ifcapable !compound + +do_test subselect-3.2 { + execsql { + SELECT sum(x) FROM (SELECT x FROM t3 ORDER BY x LIMIT 2); + } +} {3} +do_test subselect-3.3 { + execsql { + SELECT sum(x) FROM (SELECT x FROM t3 ORDER BY x DESC LIMIT 2); + } +} {11} +do_test subselect-3.4 { + execsql { + SELECT (SELECT x FROM t3 ORDER BY x); + } +} {1} +do_test subselect-3.5 { + execsql { + SELECT (SELECT x FROM t3 ORDER BY x DESC); + } +} {6} +do_test subselect-3.6 { + execsql { + SELECT (SELECT x FROM t3 ORDER BY x LIMIT 1); + } +} {1} +do_test subselect-3.7 { + execsql { + SELECT (SELECT x FROM t3 ORDER BY x DESC LIMIT 1); + } +} {6} +do_test subselect-3.8 { + execsql { + SELECT (SELECT x FROM t3 ORDER BY x LIMIT 1 OFFSET 2); + } +} {3} +do_test subselect-3.9 { + execsql { + SELECT (SELECT x FROM t3 ORDER BY x DESC LIMIT 1 OFFSET 2); + } +} {4} +do_test subselect-3.10 { + execsql { + SELECT x FROM t3 WHERE x IN + (SELECT x FROM t3 ORDER BY x DESC LIMIT 1 OFFSET 2); + } +} {4} + +# Ticket #2295. +# Make sure type affinities work correctly on subqueries with +# an ORDER BY clause. +# +do_test subselect-4.1 { + execsql { + CREATE TABLE t4(a TEXT, b TEXT); + INSERT INTO t4 VALUES('a','1'); + INSERT INTO t4 VALUES('b','2'); + INSERT INTO t4 VALUES('c','3'); + SELECT a FROM t4 WHERE b IN (SELECT b FROM t4 ORDER BY b); + } +} {a b c} +do_test subselect-4.2 { + execsql { + SELECT a FROM t4 WHERE b IN (SELECT b FROM t4 ORDER BY b LIMIT 1); + } +} {a} +do_test subselect-4.3 { + execsql { + SELECT a FROM t4 WHERE b IN (SELECT b FROM t4 ORDER BY b DESC LIMIT 1); + } +} {c} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/substr.test b/components/external/SQLite-3.8.1/test/substr.test new file mode 100644 index 0000000000000000000000000000000000000000..bcd0588d2d3be865efc2edca726ac2e68c18b13f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/substr.test @@ -0,0 +1,159 @@ +# 2007 May 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the built-in SUBSTR() functions. +# +# $Id: substr.test,v 1.7 2009/02/03 13:10:54 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !tclvar { + finish_test + return +} + +# Create a table to work with. +# +execsql { + CREATE TABLE t1(t text, b blob) +} +proc substr-test {id string i1 i2 result} { + db eval { + DELETE FROM t1; + INSERT INTO t1(t) VALUES($string) + } + do_test substr-$id.1 [subst { + execsql { + SELECT substr(t, $i1, $i2) FROM t1 + } + }] [list $result] + set qstr '[string map {' ''} $string]' + do_test substr-$id.2 [subst { + execsql { + SELECT substr($qstr, $i1, $i2) + } + }] [list $result] +} +proc subblob-test {id hex i1 i2 hexresult} { + db eval " + DELETE FROM t1; + INSERT INTO t1(b) VALUES(x'$hex') + " + do_test substr-$id.1 [subst { + execsql { + SELECT hex(substr(b, $i1, $i2)) FROM t1 + } + }] [list $hexresult] + do_test substr-$id.2 [subst { + execsql { + SELECT hex(substr(x'$hex', $i1, $i2)) + } + }] [list $hexresult] +} + +# Basic SUBSTR functionality +# +substr-test 1.1 abcdefg 1 1 a +substr-test 1.2 abcdefg 2 1 b +substr-test 1.3 abcdefg 1 2 ab +substr-test 1.4 abcdefg 1 100 abcdefg +substr-test 1.5 abcdefg 0 2 a +substr-test 1.6 abcdefg -1 1 g +substr-test 1.7 abcdefg -1 10 g +substr-test 1.8 abcdefg -5 3 cde +substr-test 1.9 abcdefg -7 3 abc +substr-test 1.10 abcdefg -100 98 abcde +substr-test 1.11 abcdefg 5 -1 d +substr-test 1.12 abcdefg 5 -4 abcd +substr-test 1.13 abcdefg 5 -5 abcd +substr-test 1.14 abcdefg -5 -1 b +substr-test 1.15 abcdefg -5 -2 ab +substr-test 1.16 abcdefg -5 -3 ab +substr-test 1.17 abcdefg 100 200 {} +substr-test 1.18 abcdefg 200 100 {} + +# Make sure NULL is returned if any parameter is NULL +# +do_test substr-1.90 { + db eval {SELECT ifnull(substr(NULL,1,1),'nil')} +} nil +do_test substr-1.91 { + db eval {SELECT ifnull(substr(NULL,1),'nil')} +} nil +do_test substr-1.92 { + db eval {SELECT ifnull(substr('abcdefg',NULL,1),'nil')} +} nil +do_test substr-1.93 { + db eval {SELECT ifnull(substr('abcdefg',NULL),'nil')} +} nil +do_test substr-1.94 { + db eval {SELECT ifnull(substr('abcdefg',1,NULL),'nil')} +} nil + +# Make sure everything works with long unicode characters +# +substr-test 2.1 \u1234\u2345\u3456 1 1 \u1234 +substr-test 2.2 \u1234\u2345\u3456 2 1 \u2345 +substr-test 2.3 \u1234\u2345\u3456 1 2 \u1234\u2345 +substr-test 2.4 \u1234\u2345\u3456 -1 1 \u3456 +substr-test 2.5 a\u1234b\u2345c\u3456c -5 3 b\u2345c +substr-test 2.6 a\u1234b\u2345c\u3456c -2 -3 b\u2345c + +# Basic functionality for BLOBs +# +subblob-test 3.1 61626364656667 1 1 61 +subblob-test 3.2 61626364656667 2 1 62 +subblob-test 3.3 61626364656667 1 2 6162 +subblob-test 3.4 61626364656667 1 100 61626364656667 +subblob-test 3.5 61626364656667 0 2 61 +subblob-test 3.6 61626364656667 -1 1 67 +subblob-test 3.7 61626364656667 -1 10 67 +subblob-test 3.8 61626364656667 -5 3 636465 +subblob-test 3.9 61626364656667 -7 3 616263 +subblob-test 3.10 61626364656667 -100 98 6162636465 +subblob-test 3.11 61626364656667 100 200 {} +subblob-test 3.12 61626364656667 200 100 {} + +# If these blobs were strings, then they would contain multi-byte +# characters. But since they are blobs, the substr indices refer +# to bytes. +# +subblob-test 4.1 61E188B462E28D8563E3919663 1 1 61 +subblob-test 4.2 61E188B462E28D8563E3919663 2 1 E1 +subblob-test 4.3 61E188B462E28D8563E3919663 1 2 61E1 +subblob-test 4.4 61E188B462E28D8563E3919663 -2 1 96 +subblob-test 4.5 61E188B462E28D8563E3919663 -5 4 63E39196 +subblob-test 4.6 61E188B462E28D8563E3919663 -100 98 61E188B462E28D8563E391 + +# Two-argument SUBSTR +# +proc substr-2-test {id string idx result} { + db eval { + DELETE FROM t1; + INSERT INTO t1(t) VALUES($string) + } + do_test substr-$id.1 [subst { + execsql { + SELECT substr(t, $idx) FROM t1 + } + }] [list $result] + set qstr '[string map {' ''} $string]' + do_test substr-$id.2 [subst { + execsql { + SELECT substr($qstr, $idx) + } + }] [list $result] +} +substr-2-test 5.1 abcdefghijklmnop 5 efghijklmnop +substr-2-test 5.2 abcdef -5 bcdef + +finish_test diff --git a/components/external/SQLite-3.8.1/test/superlock.test b/components/external/SQLite-3.8.1/test/superlock.test new file mode 100644 index 0000000000000000000000000000000000000000..8199d5218df53c66388fa8ee6b4ba600cd124194 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/superlock.test @@ -0,0 +1,257 @@ +# 2010 November 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl + +set testprefix superlock + +# Test organization: +# +# 1.*: Test superlock on a rollback database. Test that once the db is +# superlocked, it is not possible for a second client to read from +# it. +# +# 2.*: Test superlock on a WAL database with zero frames in the WAL file. +# Test that once the db is superlocked, it is not possible to read, +# write or checkpoint the db. +# +# 3.*: As 2.*, for WAL databases with one or more frames in the WAL. +# +# 4.*: As 2.*, for WAL databases with one or more checkpointed frames +# in the WAL. +# +# 5.*: Test that a call to sqlite3demo_superlock() uses the busy handler +# correctly to wait for existing clients to clear on a WAL database. +# And returns SQLITE_BUSY if no busy handler is defined or the busy +# handler returns 0 before said clients relinquish their locks. +# +# 6.*: Test that if a superlocked WAL database is overwritten, existing +# clients run the recovery to build the new wal-index after the +# superlock is released. +# +# + +do_execsql_test 1.1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + PRAGMA journal_mode = DELETE; +} {delete} + +ifcapable !wal { + finish_test + return +} + +do_test 1.2 { sqlite3demo_superlock unlock test.db } {unlock} +do_catchsql_test 1.3 { SELECT * FROM t1 } {1 {database is locked}} +do_test 1.4 { unlock } {} + +do_execsql_test 2.1 { + INSERT INTO t1 VALUES(3, 4); + PRAGMA journal_mode = WAL; +} {wal} + +do_test 2.2 { sqlite3demo_superlock unlock test.db } {unlock} +do_catchsql_test 2.3 { SELECT * FROM t1 } {1 {database is locked}} +do_catchsql_test 2.4 { INSERT INTO t1 VALUES(5, 6)} {1 {database is locked}} +do_catchsql_test 2.5 { PRAGMA wal_checkpoint } {0 {1 -1 -1}} +do_test 2.6 { unlock } {} + +do_execsql_test 3.1 { INSERT INTO t1 VALUES(3, 4) } + +do_test 3.2 { sqlite3demo_superlock unlock test.db } {unlock} +do_catchsql_test 3.3 { SELECT * FROM t1 } {1 {database is locked}} +do_catchsql_test 3.4 { INSERT INTO t1 VALUES(5, 6)} {1 {database is locked}} +do_catchsql_test 3.5 { PRAGMA wal_checkpoint } {0 {1 -1 -1}} +do_test 3.6 { unlock } {} + +# At this point the WAL file consists of a single frame only - written +# by test case 3.1. If the ZERO_DAMAGE flag were not set, it would consist +# of two frames - the frame written by 3.1 and a padding frame. +do_execsql_test 4.1 { PRAGMA wal_checkpoint } {0 1 1} + +do_test 4.2 { sqlite3demo_superlock unlock test.db } {unlock} +do_catchsql_test 4.3 { SELECT * FROM t1 } {1 {database is locked}} +do_catchsql_test 4.4 { INSERT INTO t1 VALUES(5, 6)} {1 {database is locked}} +do_catchsql_test 4.5 { PRAGMA wal_checkpoint } {0 {1 -1 -1}} +do_test 4.6 { unlock } {} + +do_multiclient_test tn { + + proc busyhandler {x} { + switch -- $x { + 1 { sql1 "COMMIT" } + 2 { sql2 "COMMIT" } + 3 { sql3 "COMMIT" } + } + lappend ::busylist $x + return 1 + } + set ::busylist [list] + + do_test 5.$tn.1 { + sql1 { + CREATE TABLE t1(a, b); + PRAGMA journal_mode = WAL; + INSERT INTO t1 VALUES(1, 2); + } + } {wal} + + do_test 5.$tn.2 { + sql1 { BEGIN ; SELECT * FROM t1 } + sql2 { BEGIN ; INSERT INTO t1 VALUES(3, 4) } + sql3 { BEGIN ; SELECT * FROM t1 } + } {1 2} + + do_test 5.$tn.3 { + set ::busylist [list] + sqlite3demo_superlock unlock test.db "" busyhandler + set ::busylist + } {0 1 2 3} + + do_test 5.$tn.4 { csql2 { SELECT * FROM t1 } } {1 {database is locked}} + do_test 5.$tn.5 { + csql3 { INSERT INTO t1 VALUES(5, 6) } + } {1 {database is locked}} + do_test 5.$tn.6 { csql1 "PRAGMA wal_checkpoint" } {0 {1 -1 -1}} + + do_test 5.$tn.7 { unlock } {} + + + do_test 5.$tn.8 { + sql1 { BEGIN ; SELECT * FROM t1 } + sql2 { BEGIN ; INSERT INTO t1 VALUES(5, 6) } + sql3 { BEGIN ; SELECT * FROM t1 } + } {1 2 3 4} + + do_test 5.$tn.9 { + list [catch {sqlite3demo_superlock unlock test.db} msg] $msg + } {1 {database is locked}} + do_test 5.$tn.10 { + sql1 COMMIT + list [catch {sqlite3demo_superlock unlock test.db} msg] $msg + } {1 {database is locked}} + do_test 5.$tn.11 { + sql2 COMMIT + list [catch {sqlite3demo_superlock unlock test.db} msg] $msg + } {1 {database is locked}} + do_test 5.$tn.12 { + sql3 COMMIT + list [catch {sqlite3demo_superlock unlock test.db} msg] $msg + } {0 unlock} + unlock + + + do_test 5.$tn.13 { sql1 { SELECT * FROM t1 } } {1 2 3 4 5 6} + do_test 5.$tn.14 { sql2 { SELECT * FROM t1 } } {1 2 3 4 5 6} + do_test 5.$tn.15 { sqlite3demo_superlock unlock test.db } {unlock} + do_test 5.$tn.16 { unlock } {} + do_test 5.$tn.17 { sql2 { SELECT * FROM t1 } } {1 2 3 4 5 6} + do_test 5.$tn.18 { sql1 { SELECT * FROM t1 } } {1 2 3 4 5 6} + do_test 5.$tn.19 { sql2 { SELECT * FROM t1 } } {1 2 3 4 5 6} +} + +proc read_content {file} { + if {[file exists $file]==0} {return ""} + set fd [open $file] + fconfigure $fd -encoding binary -translation binary + set content [read $fd] + close $fd + return $content +} + +proc write_content {file content} { + set fd [open $file w+] + fconfigure $fd -encoding binary -translation binary + puts -nonewline $fd $content + close $fd +} + +# Both $file1 and $file2 are database files. This function takes a +# superlock on each, then exchanges the content of the two files (i.e. +# overwrites $file1 with the initial contents of $file2, and overwrites +# $file2 with the initial contents of $file1). The contents of any WAL +# file is also exchanged. +# +proc db_swap {file1 file2} { + sqlite3demo_superlock unlock1 $file1 + sqlite3demo_superlock unlock2 $file2 + + set db1 [read_content $file1] + set db2 [read_content $file2] + write_content $file1 $db2 + write_content $file2 $db1 + + set wal1 [read_content ${file1}-wal] + set wal2 [read_content ${file2}-wal] + write_content ${file1}-wal $wal2 + write_content ${file2}-wal $wal1 + + unlock1 + unlock2 +} + +forcedelete test.db +sqlite3 db test.db +do_execsql_test 6.1 { + ATTACH 'test.db2' AS aux; + PRAGMA aux.journal_mode = wal; + CREATE TABLE aux.t2(x, y); + INSERT INTO aux.t2 VALUES('a', 'b'); + PRAGMA schema_version = 450; + DETACH aux; + + PRAGMA main.journal_mode = wal; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + SELECT * FROM t1; +} {wal wal 1 2 3 4} + + +db_swap test.db2 test.db +do_catchsql_test 6.2 { SELECT * FROM t1 } {1 {no such table: t1}} +do_catchsql_test 6.3 { SELECT * FROM t2 } {0 {a b}} + +db_swap test.db2 test.db +do_catchsql_test 6.4 { SELECT * FROM t1 } {0 {1 2 3 4}} +do_catchsql_test 6.5 { SELECT * FROM t2 } {1 {no such table: t2}} + +do_execsql_test 6.6 { PRAGMA wal_checkpoint } {0 0 0} + +db_swap test.db2 test.db +do_catchsql_test 6.7 { SELECT * FROM t1 } {1 {no such table: t1}} +do_catchsql_test 6.8 { SELECT * FROM t2 } {0 {a b}} + +db_swap test.db2 test.db +do_catchsql_test 6.9 { SELECT * FROM t1 } {0 {1 2 3 4}} +do_catchsql_test 6.10 { SELECT * FROM t2 } {1 {no such table: t2}} + +do_execsql_test 6.11 { + PRAGMA journal_mode = delete; + PRAGMA page_size = 512; + VACUUM; + PRAGMA journal_mode = wal; + INSERT INTO t1 VALUES(5, 6); +} {delete wal} + +db_swap test.db2 test.db +do_catchsql_test 6.12 { SELECT * FROM t1 } {1 {no such table: t1}} +do_catchsql_test 6.13 { SELECT * FROM t2 } {0 {a b}} + +db_swap test.db2 test.db +do_catchsql_test 6.14 { SELECT * FROM t1 } {0 {1 2 3 4 5 6}} +do_catchsql_test 6.15 { SELECT * FROM t2 } {1 {no such table: t2}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/sync.test b/components/external/SQLite-3.8.1/test/sync.test new file mode 100644 index 0000000000000000000000000000000000000000..14252b5c08af33a59917bc79269cced40ed2aacb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/sync.test @@ -0,0 +1,100 @@ +# 2005 August 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that fsync is disabled when +# pragma synchronous=off even for multi-database commits. +# +# $Id: sync.test,v 1.6 2007/10/09 08:29:33 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# +# These tests are only applicable when pager pragma are +# enabled. Also, since every test uses an ATTACHed database, they +# are only run when ATTACH is enabled. +# +ifcapable !pager_pragmas||!attach { + finish_test + return +} + +set sqlite_sync_count 0 +proc cond_incr_sync_count {adj} { + global sqlite_sync_count + if {$::tcl_platform(platform) == "windows"} { + incr sqlite_sync_count $adj + } { + ifcapable !dirsync { + incr sqlite_sync_count $adj + } + } +} + +do_test sync-1.1 { + set sqlite_sync_count 0 + forcedelete test2.db + forcedelete test2.db-journal + execsql { + PRAGMA fullfsync=OFF; + CREATE TABLE t1(a,b); + ATTACH DATABASE 'test2.db' AS db2; + CREATE TABLE db2.t2(x,y); + } + cond_incr_sync_count 2 + set sqlite_sync_count +} 8 +ifcapable pager_pragmas { + do_test sync-1.2 { + set sqlite_sync_count 0 + execsql { + PRAGMA main.synchronous=on; + PRAGMA db2.synchronous=on; + BEGIN; + INSERT INTO t1 VALUES(1,2); + INSERT INTO t2 VALUES(3,4); + COMMIT; + } + cond_incr_sync_count 3 + set sqlite_sync_count + } 8 +} +do_test sync-1.3 { + set sqlite_sync_count 0 + execsql { + PRAGMA main.synchronous=full; + PRAGMA db2.synchronous=full; + BEGIN; + INSERT INTO t1 VALUES(3,4); + INSERT INTO t2 VALUES(5,6); + COMMIT; + } + cond_incr_sync_count 3 + set sqlite_sync_count +} 10 +ifcapable pager_pragmas { + do_test sync-1.4 { + set sqlite_sync_count 0 + execsql { + PRAGMA main.synchronous=off; + PRAGMA db2.synchronous=off; + BEGIN; + INSERT INTO t1 VALUES(5,6); + INSERT INTO t2 VALUES(7,8); + COMMIT; + } + set sqlite_sync_count + } 0 +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/syscall.test b/components/external/SQLite-3.8.1/test/syscall.test new file mode 100644 index 0000000000000000000000000000000000000000..5bf12258678610c0d9e27d89491cf71b6cfacb51 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/syscall.test @@ -0,0 +1,277 @@ +# 2011 March 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +if {[llength [info commands test_syscall]]==0} { + finish_test + return +} + +if {[test_syscall defaultvfs] != "unix"} { + finish_test + return +} +set testprefix syscall + +#------------------------------------------------------------------------- +# Tests for the xSetSystemCall method. +# +do_test 1.1.1 { + list [catch { test_syscall reset open } msg] $msg +} {0 {}} +do_test 1.1.2 { + list [catch { test_syscall reset nosuchcall } msg] $msg +} {1 SQLITE_NOTFOUND} +do_test 1.1.3 { + list [catch { test_syscall reset open } msg] $msg +} {0 {}} +do_test 1.1.4 { + list [catch { test_syscall reset ""} msg] $msg +} {1 SQLITE_NOTFOUND} + +do_test 1.2 { test_syscall reset } {} + +do_test 1.3.1 { test_syscall install {open getcwd access} } {} +do_test 1.3.2 { test_syscall reset } {} + +#------------------------------------------------------------------------- +# Tests for the xGetSystemCall method. +# +do_test 2.1.1 { test_syscall exists open } 1 +do_test 2.1.2 { test_syscall exists nosuchcall } 0 + +#------------------------------------------------------------------------- +# Tests for the xNextSystemCall method. +# +foreach s { + open close access getcwd stat fstat ftruncate + fcntl read pread write pwrite fchmod fallocate + pread64 pwrite64 unlink openDirectory mkdir rmdir + statvfs fchown umask mmap munmap mremap +} { + if {[test_syscall exists $s]} {lappend syscall_list $s} +} +do_test 3.1 { lsort [test_syscall list] } [lsort $syscall_list] + +#------------------------------------------------------------------------- +# This test verifies that if a call to open() fails and errno is set to +# EINTR, the call is retried. If it succeeds, execution continues as if +# nothing happened. +# +test_syscall reset +forcedelete test.db2 +do_execsql_test 4.1 { + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(1, 2); + ATTACH 'test.db2' AS aux; + CREATE TABLE aux.t2(x, y); + INSERT INTO t2 VALUES(3, 4); +} + +db_save_and_close +test_syscall install open +foreach jrnl [list wal delete] { + for {set i 1} {$i < 20} {incr i} { + db_restore_and_reopen + test_syscall fault $i 0 + test_syscall errno open EINTR + + do_test 4.2.$jrnl.$i { + sqlite3 db test.db + execsql { ATTACH 'test.db2' AS aux } + execsql "PRAGMA main.journal_mode = $jrnl" + execsql "PRAGMA aux.journal_mode = $jrnl" + execsql { + BEGIN; + INSERT INTO t1 VALUES(5, 6); + INSERT INTO t2 VALUES(7, 8); + COMMIT; + } + + db close + sqlite3 db test.db + execsql { ATTACH 'test.db2' AS aux } + execsql { + SELECT * FROM t1; + SELECT * FROM t2; + } + } {1 2 5 6 3 4 7 8} + } +} + +#------------------------------------------------------------------------- +# This test verifies that closing database handles does not drop locks +# held by other database handles in the same process on the same file. +# +# The os_unix.c module has to take precautions to prevent this as the +# close() system call drops locks held by other file-descriptors on the +# same file. From the Linux man page: +# +# close() closes a file descriptor, so that it no longer refers to any file +# and may be reused. Any record locks (see fcntl(2)) held on the file it +# was associated with, and owned by the process, are removed (regardless +# of the file descriptor that was used to obtain the lock). +# +catch { db close } +forcedelete test.db test.db2 + +do_multiclient_test tn { + code1 { + sqlite3 dbX1 test.db + sqlite3 dbX2 test.db + } + + do_test syscall-5.$tn.1 { + sql1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + BEGIN; + INSERT INTO t1 VALUES(3, 4); + } + } {} + + do_test syscall-5.$tn.2 { sql2 { SELECT * FROM t1 } } {1 2} + do_test syscall-5.$tn.3 { + csql2 { INSERT INTO t1 VALUES(5, 6) } + } {1 {database is locked}} + + do_test syscall-5.$tn.4 { + code1 { + dbX1 close + dbX2 close + } + } {} + + do_test syscall-5.$tn.5 { + csql2 { INSERT INTO t1 VALUES(5, 6) } + } {1 {database is locked}} + + do_test syscall-5.$tn.6 { sql1 { COMMIT } } {} + + do_test syscall-5.$tn.7 { + csql2 { INSERT INTO t1 VALUES(5, 6) } + } {0 {}} +} + +catch {db close} +do_test 6.1 { + sqlite3 db1 test.db1 + sqlite3 db2 test.db2 + sqlite3 db3 test.db3 + sqlite3 dbM "" + + db2 close + db3 close + dbM close + db1 close +} {} + +do_test 6.2 { + sqlite3 db test.db + execsql { + PRAGMA temp_store = file; + + PRAGMA main.cache_size = 10; + PRAGMA temp.cache_size = 10; + CREATE TABLE temp.tt(a, b); + INSERT INTO tt VALUES(randomblob(500), randomblob(600)); + INSERT INTO tt SELECT randomblob(500), randomblob(600) FROM tt; + INSERT INTO tt SELECT randomblob(500), randomblob(600) FROM tt; + INSERT INTO tt SELECT randomblob(500), randomblob(600) FROM tt; + INSERT INTO tt SELECT randomblob(500), randomblob(600) FROM tt; + INSERT INTO tt SELECT randomblob(500), randomblob(600) FROM tt; + INSERT INTO tt SELECT randomblob(500), randomblob(600) FROM tt; + INSERT INTO tt SELECT randomblob(500), randomblob(600) FROM tt; + INSERT INTO tt SELECT randomblob(500), randomblob(600) FROM tt; + } + + db close +} {} + +#------------------------------------------------------------------------- +# Test that a database file a single byte in size is treated as an empty +# file. Whereas a file 2 bytes or larger might be considered corrupt. +# +catch { db close } +forcedelete test.db test.db2 + +proc create_db_file {nByte} { + set fd [open test.db w] + fconfigure $fd -translation binary -encoding binary + puts -nonewline $fd [string range "xSQLite" 1 $nByte] + close $fd +} + +foreach {nByte res} { + 1 {0 {}} + 2 {1 {file is encrypted or is not a database}} + 3 {1 {file is encrypted or is not a database}} +} { + do_test 7.$nByte { + create_db_file $nByte + list [catch { + sqlite3 db test.db + execsql { CREATE TABLE t1(a, b) } + } msg] $msg + } $res + catch { db close } +} + +#------------------------------------------------------------------------- +# +catch { db close } +forcedelete test.db test.db2 + +do_test 8.1 { + sqlite3 db test.db + file_control_chunksize_test db main 4096 + file size test.db +} {0} +foreach {tn hint size} { + 1 1000 4096 + 2 1000 4096 + 3 3000 4096 + 4 4096 4096 + 5 4197 8192 +} { + do_test 8.2.$tn { + file_control_sizehint_test db main $hint + file size test.db + } $size +} + +do_test 8.3 { + db close + forcedelete test.db test.db2 + sqlite3 db test.db + file_control_chunksize_test db main 16 + file size test.db +} {0} +foreach {tn hint size} { + 1 5 16 + 2 13 16 + 3 45 48 + 4 48 48 + 5 49 64 +} { + do_test 8.4.$tn { + file_control_sizehint_test db main $hint + file size test.db + } $size +} + +test_syscall reset +finish_test diff --git a/components/external/SQLite-3.8.1/test/sysfault.test b/components/external/SQLite-3.8.1/test/sysfault.test new file mode 100644 index 0000000000000000000000000000000000000000..92fb534dd09dd6fe770a14efd648d676d167b385 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/sysfault.test @@ -0,0 +1,277 @@ +# 2011 March 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +if {[llength [info commands test_syscall]]==0} { + finish_test + return +} + +set testprefix sysfault + +set FAULTSIM(vfsfault-transient) [list \ + -injectinstall vfsfault_install \ + -injectstart vfsfault_injectstart_t \ + -injectstop vfsfault_injectstop \ + -injecterrlist {} \ + -injectuninstall {test_syscall uninstall} \ +] +set FAULTSIM(vfsfault-persistent) [list \ + -injectinstall vfsfault_install \ + -injectstart vfsfault_injectstart_p \ + -injectstop vfsfault_injectstop \ + -injecterrlist {} \ + -injectuninstall {test_syscall uninstall} \ +] + +proc vfsfault_injectstart_t {iFail} { test_syscall fault $iFail 0 } +proc vfsfault_injectstart_p {iFail} { test_syscall fault $iFail 1 } +proc vfsfault_injectstop {} { test_syscall fault } + +faultsim_save_and_close + + +set open_and_write_body { + sqlite3 db test.db + db eval { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + PRAGMA journal_mode = WAL; + INSERT INTO t1 VALUES(3, 4); + SELECT * FROM t1; + CREATE TEMP TABLE t2(x); + INSERT INTO t2 VALUES('y'); + } +} + +proc vfsfault_install {} { test_syscall install {open getcwd} } +do_faultsim_test 1 -faults vfsfault-* -prep { + faultsim_restore +} -body $open_and_write_body -test { + faultsim_test_result {0 {wal 1 2 3 4}} \ + {1 {unable to open database file}} \ + {1 {attempt to write a readonly database}} +} + +#------------------------------------------------------------------------- +# Errors in the fstat() function when opening and writing a file. Cases +# where fstat() fails and sets errno to ENOMEM and EOVERFLOW are both +# tested. EOVERFLOW is interpreted as meaning that a file on disk is +# too large to be opened by the OS. +# +foreach {tn errno errlist} { + 1 ENOMEM {{disk I/O error}} + 2 EOVERFLOW {{disk I/O error} {large file support is disabled}} +} { + proc vfsfault_install {} { test_syscall install fstat } + set errs [list] + foreach e $errlist { lappend errs [list 1 $e] } + do_faultsim_test 1.2.$tn -faults vfsfault-* -prep { + faultsim_restore + } -body " + test_syscall errno fstat $errno + $open_and_write_body + " -test " + faultsim_test_result {0 {wal 1 2 3 4}} $errs + " +} + +#------------------------------------------------------------------------- +# Various errors in locking functions. +# +foreach vfs {unix unix-excl} { + foreach {tn errno errlist} { + 1 EAGAIN {{database is locked} {disk I/O error}} + 2 ETIMEDOUT {{database is locked} {disk I/O error}} + 3 EBUSY {{database is locked} {disk I/O error}} + 4 EINTR {{database is locked} {disk I/O error}} + 5 ENOLCK {{database is locked} {disk I/O error}} + 6 EACCES {{database is locked} {disk I/O error}} + 7 EPERM {{access permission denied} {disk I/O error}} + 8 EDEADLK {{disk I/O error}} + 9 ENOMEM {{disk I/O error}} + } { + proc vfsfault_install {} { test_syscall install fcntl } + set errs [list] + foreach e $errlist { lappend errs [list 1 $e] } + + set body [string map [list %VFS% $vfs] { + sqlite3 db test.db + db eval { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } + set fd [open test.db-journal w] + puts $fd "hello world" + close $fd + sqlite3 db test.db -vfs %VFS% + db eval { + SELECT * FROM t1; + } + }] + + do_faultsim_test 1.3.$vfs.$tn -faults vfsfault-* -prep { + faultsim_restore + } -body " + test_syscall errno fcntl $errno + $body + " -test " + faultsim_test_result {0 {1 2}} $errs + " + } +} + +#------------------------------------------------------------------------- +# Check that a single EINTR error does not affect processing. +# +proc vfsfault_install {} { + test_syscall reset + test_syscall install {open ftruncate close read pread pread64 write fallocate} +} + +forcedelete test.db test.db2 +sqlite3 db test.db +do_test 2.setup { + execsql { + CREATE TABLE t1(a, b, c, PRIMARY KEY(a)); + INSERT INTO t1 VALUES('abc', 'def', 'ghi'); + ATTACH 'test.db2' AS 'aux'; + CREATE TABLE aux.t2(x); + INSERT INTO t2 VALUES(1); + } + faultsim_save_and_close +} {} + +do_faultsim_test 2.1 -faults vfsfault-transient -prep { + catch { db close } + faultsim_restore +} -body { + test_syscall errno open EINTR + test_syscall errno ftruncate EINTR + test_syscall errno close EINTR + test_syscall errno read EINTR + test_syscall errno pread EINTR + test_syscall errno pread64 EINTR + test_syscall errno write EINTR + test_syscall errno fallocate EINTR + + sqlite3 db test.db + file_control_chunksize_test db main 8192 + + set res [db eval { + ATTACH 'test.db2' AS 'aux'; + SELECT * FROM t1; + PRAGMA journal_mode = truncate; + BEGIN; + INSERT INTO t1 VALUES('jkl', 'mno', 'pqr'); + INSERT INTO t1 VALUES(randomblob(10000), 0, 0); + UPDATE t2 SET x = 2; + COMMIT; + DELETE FROM t1 WHERE length(a)>3; + SELECT * FROM t1; + SELECT * FROM t2; + }] + db close + set res +} -test { + faultsim_test_result {0 {abc def ghi truncate abc def ghi jkl mno pqr 2}} +} + +do_faultsim_test 2.2 -faults vfsfault-* -prep { + catch { db close } + faultsim_restore +} -body { + sqlite3 db test.db + set res [db eval { + ATTACH 'test.db2' AS 'aux'; + SELECT * FROM t1; + PRAGMA journal_mode = truncate; + BEGIN; + INSERT INTO t1 VALUES('jkl', 'mno', 'pqr'); + UPDATE t2 SET x = 2; + COMMIT; + SELECT * FROM t1; + SELECT * FROM t2; + }] + db close + set res +} -test { + faultsim_test_result {0 {abc def ghi truncate abc def ghi jkl mno pqr 2}} \ + {1 {unable to open database file}} \ + {1 {unable to open database: test.db2}} \ + {1 {attempt to write a readonly database}} \ + {1 {disk I/O error}} +} + +#------------------------------------------------------------------------- + +proc vfsfault_install {} { + test_syscall reset + test_syscall install {fstat fallocate} +} +do_faultsim_test 3 -faults vfsfault-* -prep { + faultsim_delete_and_reopen + file_control_chunksize_test db main 8192 + execsql { + CREATE TABLE t1(a, b); + BEGIN; + SELECT * FROM t1; + } +} -body { + test_syscall errno fstat EIO + test_syscall errno fallocate EIO + + execsql { + INSERT INTO t1 VALUES(randomblob(10000), randomblob(10000)); + SELECT length(a) + length(b) FROM t1; + COMMIT; + } +} -test { + faultsim_test_result {0 20000} +} + +#------------------------------------------------------------------------- +# Test errors in mmap(). +# +proc vfsfault_install {} { + test_syscall reset + test_syscall install {mmap} +} + +faultsim_delete_and_reopen +execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); +} +faultsim_save_and_close + +do_faultsim_test 4 -faults vfsfault-* -prep { + faultsim_restore_and_reopen + file_control_chunksize_test db main 8192 + execsql { + PRAGMA mmap_size = 1000000; + } +} -body { + test_syscall errno mmap EACCES + + execsql { + SELECT * FROM t1; + } +} -test { + faultsim_test_result {0 {1 2}} {1 {disk I/O error}} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/table.test b/components/external/SQLite-3.8.1/test/table.test new file mode 100644 index 0000000000000000000000000000000000000000..e186450a2f6a20b4caacc6bc8f8f051d7653c483 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/table.test @@ -0,0 +1,729 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the CREATE TABLE statement. +# +# $Id: table.test,v 1.53 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a basic table and verify it is added to sqlite_master +# +do_test table-1.1 { + execsql { + CREATE TABLE test1 ( + one varchar(10), + two text + ) + } + execsql { + SELECT sql FROM sqlite_master WHERE type!='meta' + } +} {{CREATE TABLE test1 ( + one varchar(10), + two text + )}} + + +# Verify the other fields of the sqlite_master file. +# +do_test table-1.3 { + execsql {SELECT name, tbl_name, type FROM sqlite_master WHERE type!='meta'} +} {test1 test1 table} + +# Close and reopen the database. Verify that everything is +# still the same. +# +do_test table-1.4 { + db close + sqlite3 db test.db + execsql {SELECT name, tbl_name, type from sqlite_master WHERE type!='meta'} +} {test1 test1 table} + +# Drop the database and make sure it disappears. +# +do_test table-1.5 { + execsql {DROP TABLE test1} + execsql {SELECT * FROM sqlite_master WHERE type!='meta'} +} {} + +# Close and reopen the database. Verify that the table is +# still gone. +# +do_test table-1.6 { + db close + sqlite3 db test.db + execsql {SELECT name FROM sqlite_master WHERE type!='meta'} +} {} + +# Repeat the above steps, but this time quote the table name. +# +do_test table-1.10 { + execsql {CREATE TABLE "create" (f1 int)} + execsql {SELECT name FROM sqlite_master WHERE type!='meta'} +} {create} +do_test table-1.11 { + execsql {DROP TABLE "create"} + execsql {SELECT name FROM "sqlite_master" WHERE type!='meta'} +} {} +do_test table-1.12 { + execsql {CREATE TABLE test1("f1 ho" int)} + execsql {SELECT name as "X" FROM sqlite_master WHERE type!='meta'} +} {test1} +do_test table-1.13 { + execsql {DROP TABLE "TEST1"} + execsql {SELECT name FROM "sqlite_master" WHERE type!='meta'} +} {} + + + +# Verify that we cannot make two tables with the same name +# +do_test table-2.1 { + execsql {CREATE TABLE TEST2(one text)} + catchsql {CREATE TABLE test2(two text default 'hi')} +} {1 {table test2 already exists}} +do_test table-2.1.1 { + catchsql {CREATE TABLE "test2" (two)} +} {1 {table "test2" already exists}} +do_test table-2.1b { + set v [catch {execsql {CREATE TABLE sqlite_master(two text)}} msg] + lappend v $msg +} {1 {object name reserved for internal use: sqlite_master}} +do_test table-2.1c { + db close + sqlite3 db test.db + set v [catch {execsql {CREATE TABLE sqlite_master(two text)}} msg] + lappend v $msg +} {1 {object name reserved for internal use: sqlite_master}} +do_test table-2.1d { + catchsql {CREATE TABLE IF NOT EXISTS test2(x,y)} +} {0 {}} +do_test table-2.1e { + catchsql {CREATE TABLE IF NOT EXISTS test2(x UNIQUE, y TEXT PRIMARY KEY)} +} {0 {}} +do_test table-2.1f { + execsql {DROP TABLE test2; SELECT name FROM sqlite_master WHERE type!='meta'} +} {} + +# Verify that we cannot make a table with the same name as an index +# +do_test table-2.2a { + execsql {CREATE TABLE test2(one text)} + execsql {CREATE INDEX test3 ON test2(one)} + catchsql {CREATE TABLE test3(two text)} +} {1 {there is already an index named test3}} +do_test table-2.2b { + db close + sqlite3 db test.db + set v [catch {execsql {CREATE TABLE test3(two text)}} msg] + lappend v $msg +} {1 {there is already an index named test3}} +do_test table-2.2c { + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {test2 test3} +do_test table-2.2d { + execsql {DROP INDEX test3} + set v [catch {execsql {CREATE TABLE test3(two text)}} msg] + lappend v $msg +} {0 {}} +do_test table-2.2e { + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {test2 test3} +do_test table-2.2f { + execsql {DROP TABLE test2; DROP TABLE test3} + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {} + +# Create a table with many field names +# +set big_table \ +{CREATE TABLE big( + f1 varchar(20), + f2 char(10), + f3 varchar(30) primary key, + f4 text, + f5 text, + f6 text, + f7 text, + f8 text, + f9 text, + f10 text, + f11 text, + f12 text, + f13 text, + f14 text, + f15 text, + f16 text, + f17 text, + f18 text, + f19 text, + f20 text +)} +do_test table-3.1 { + execsql $big_table + execsql {SELECT sql FROM sqlite_master WHERE type=='table'} +} \{$big_table\} +do_test table-3.2 { + set v [catch {execsql {CREATE TABLE BIG(xyz foo)}} msg] + lappend v $msg +} {1 {table BIG already exists}} +do_test table-3.3 { + set v [catch {execsql {CREATE TABLE biG(xyz foo)}} msg] + lappend v $msg +} {1 {table biG already exists}} +do_test table-3.4 { + set v [catch {execsql {CREATE TABLE bIg(xyz foo)}} msg] + lappend v $msg +} {1 {table bIg already exists}} +do_test table-3.5 { + db close + sqlite3 db test.db + set v [catch {execsql {CREATE TABLE Big(xyz foo)}} msg] + lappend v $msg +} {1 {table Big already exists}} +do_test table-3.6 { + execsql {DROP TABLE big} + execsql {SELECT name FROM sqlite_master WHERE type!='meta'} +} {} + +# Try creating large numbers of tables +# +set r {} +for {set i 1} {$i<=100} {incr i} { + lappend r [format test%03d $i] +} +do_test table-4.1 { + for {set i 1} {$i<=100} {incr i} { + set sql "CREATE TABLE [format test%03d $i] (" + for {set k 1} {$k<$i} {incr k} { + append sql "field$k text," + } + append sql "last_field text)" + execsql $sql + } + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} $r +do_test table-4.1b { + db close + sqlite3 db test.db + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} $r + +# Drop the even numbered tables +# +set r {} +for {set i 1} {$i<=100} {incr i 2} { + lappend r [format test%03d $i] +} +do_test table-4.2 { + for {set i 2} {$i<=100} {incr i 2} { + # if {$i==38} {execsql {pragma vdbe_trace=on}} + set sql "DROP TABLE [format TEST%03d $i]" + execsql $sql + } + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} $r +#exit + +# Drop the odd number tables +# +do_test table-4.3 { + for {set i 1} {$i<=100} {incr i 2} { + set sql "DROP TABLE [format test%03d $i]" + execsql $sql + } + execsql {SELECT name FROM sqlite_master WHERE type!='meta' ORDER BY name} +} {} + +# Try to drop a table that does not exist +# +do_test table-5.1.1 { + catchsql {DROP TABLE test009} +} {1 {no such table: test009}} +do_test table-5.1.2 { + catchsql {DROP TABLE IF EXISTS test009} +} {0 {}} + +# Try to drop sqlite_master +# +do_test table-5.2 { + catchsql {DROP TABLE IF EXISTS sqlite_master} +} {1 {table sqlite_master may not be dropped}} + +# Dropping sqlite_statN tables is OK. +# +do_test table-5.2.1 { + db eval { + ANALYZE; + DROP TABLE IF EXISTS sqlite_stat1; + DROP TABLE IF EXISTS sqlite_stat2; + DROP TABLE IF EXISTS sqlite_stat3; + DROP TABLE IF EXISTS sqlite_stat4; + SELECT name FROM sqlite_master WHERE name GLOB 'sqlite_stat*'; + } +} {} + +# Make sure an EXPLAIN does not really create a new table +# +do_test table-5.3 { + ifcapable {explain} { + execsql {EXPLAIN CREATE TABLE test1(f1 int)} + } + execsql {SELECT name FROM sqlite_master WHERE type!='meta'} +} {} + +# Make sure an EXPLAIN does not really drop an existing table +# +do_test table-5.4 { + execsql {CREATE TABLE test1(f1 int)} + ifcapable {explain} { + execsql {EXPLAIN DROP TABLE test1} + } + execsql {SELECT name FROM sqlite_master WHERE type!='meta'} +} {test1} + +# Create a table with a goofy name +# +#do_test table-6.1 { +# execsql {CREATE TABLE 'Spaces In This Name!'(x int)} +# execsql {INSERT INTO 'spaces in this name!' VALUES(1)} +# set list [glob -nocomplain testdb/spaces*.tbl] +#} {testdb/spaces+in+this+name+.tbl} + +# Try using keywords as table names or column names. +# +do_test table-7.1 { + set v [catch {execsql { + CREATE TABLE weird( + desc text, + asc text, + key int, + [14_vac] boolean, + fuzzy_dog_12 varchar(10), + begin blob, + end clob + ) + }} msg] + lappend v $msg +} {0 {}} +do_test table-7.2 { + execsql { + INSERT INTO weird VALUES('a','b',9,0,'xyz','hi','y''all'); + SELECT * FROM weird; + } +} {a b 9 0 xyz hi y'all} +do_test table-7.3 { + execsql2 { + SELECT * FROM weird; + } +} {desc a asc b key 9 14_vac 0 fuzzy_dog_12 xyz begin hi end y'all} +do_test table-7.3 { + execsql { + CREATE TABLE savepoint(release); + INSERT INTO savepoint(release) VALUES(10); + UPDATE savepoint SET release = 5; + SELECT release FROM savepoint; + } +} {5} + +# Try out the CREATE TABLE AS syntax +# +do_test table-8.1 { + execsql2 { + CREATE TABLE t2 AS SELECT * FROM weird; + SELECT * FROM t2; + } +} {desc a asc b key 9 14_vac 0 fuzzy_dog_12 xyz begin hi end y'all} +do_test table-8.1.1 { + execsql { + SELECT sql FROM sqlite_master WHERE name='t2'; + } +} {{CREATE TABLE t2( + "desc" TEXT, + "asc" TEXT, + "key" INT, + "14_vac" NUM, + fuzzy_dog_12 TEXT, + "begin", + "end" TEXT +)}} +do_test table-8.2 { + execsql { + CREATE TABLE "t3""xyz"(a,b,c); + INSERT INTO [t3"xyz] VALUES(1,2,3); + SELECT * FROM [t3"xyz]; + } +} {1 2 3} +do_test table-8.3 { + execsql2 { + CREATE TABLE [t4"abc] AS SELECT count(*) as cnt, max(b+c) FROM [t3"xyz]; + SELECT * FROM [t4"abc]; + } +} {cnt 1 max(b+c) 5} + +# Update for v3: The declaration type of anything except a column is now a +# NULL pointer, so the created table has no column types. (Changed result +# from {{CREATE TABLE 't4"abc'(cnt NUMERIC,"max(b+c)" NUMERIC)}}). +do_test table-8.3.1 { + execsql { + SELECT sql FROM sqlite_master WHERE name='t4"abc' + } +} {{CREATE TABLE "t4""abc"(cnt,"max(b+c)")}} + +ifcapable tempdb { + do_test table-8.4 { + execsql2 { + CREATE TEMPORARY TABLE t5 AS SELECT count(*) AS [y'all] FROM [t3"xyz]; + SELECT * FROM t5; + } + } {y'all 1} +} + +do_test table-8.5 { + db close + sqlite3 db test.db + execsql2 { + SELECT * FROM [t4"abc]; + } +} {cnt 1 max(b+c) 5} +do_test table-8.6 { + execsql2 { + SELECT * FROM t2; + } +} {desc a asc b key 9 14_vac 0 fuzzy_dog_12 xyz begin hi end y'all} +do_test table-8.7 { + catchsql { + SELECT * FROM t5; + } +} {1 {no such table: t5}} +do_test table-8.8 { + catchsql { + CREATE TABLE t5 AS SELECT * FROM no_such_table; + } +} {1 {no such table: no_such_table}} + +do_test table-8.9 { + execsql { + CREATE TABLE t10("col.1" [char.3]); + CREATE TABLE t11 AS SELECT * FROM t10; + SELECT sql FROM sqlite_master WHERE name = 't11'; + } +} {{CREATE TABLE t11("col.1" TEXT)}} +do_test table-8.10 { + execsql { + CREATE TABLE t12( + a INTEGER, + b VARCHAR(10), + c VARCHAR(1,10), + d VARCHAR(+1,-10), + e VARCHAR (+1,-10), + f "VARCHAR (+1,-10, 5)", + g BIG INTEGER + ); + CREATE TABLE t13 AS SELECT * FROM t12; + SELECT sql FROM sqlite_master WHERE name = 't13'; + } +} {{CREATE TABLE t13( + a INT, + b TEXT, + c TEXT, + d TEXT, + e TEXT, + f TEXT, + g INT +)}} + +# Make sure we cannot have duplicate column names within a table. +# +do_test table-9.1 { + catchsql { + CREATE TABLE t6(a,b,a); + } +} {1 {duplicate column name: a}} +do_test table-9.2 { + catchsql { + CREATE TABLE t6(a varchar(100), b blob, a integer); + } +} {1 {duplicate column name: a}} + +# Check the foreign key syntax. +# +ifcapable {foreignkey} { +do_test table-10.1 { + catchsql { + CREATE TABLE t6(a REFERENCES t4(a) NOT NULL); + INSERT INTO t6 VALUES(NULL); + } +} {1 {t6.a may not be NULL}} +do_test table-10.2 { + catchsql { + DROP TABLE t6; + CREATE TABLE t6(a REFERENCES t4(a) MATCH PARTIAL); + } +} {0 {}} +do_test table-10.3 { + catchsql { + DROP TABLE t6; + CREATE TABLE t6(a REFERENCES t4 MATCH FULL ON DELETE SET NULL NOT NULL); + } +} {0 {}} +do_test table-10.4 { + catchsql { + DROP TABLE t6; + CREATE TABLE t6(a REFERENCES t4 MATCH FULL ON UPDATE SET DEFAULT DEFAULT 1); + } +} {0 {}} +do_test table-10.5 { + catchsql { + DROP TABLE t6; + CREATE TABLE t6(a NOT NULL NOT DEFERRABLE INITIALLY IMMEDIATE); + } +} {0 {}} +do_test table-10.6 { + catchsql { + DROP TABLE t6; + CREATE TABLE t6(a NOT NULL DEFERRABLE INITIALLY DEFERRED); + } +} {0 {}} +do_test table-10.7 { + catchsql { + DROP TABLE t6; + CREATE TABLE t6(a, + FOREIGN KEY (a) REFERENCES t4(b) DEFERRABLE INITIALLY DEFERRED + ); + } +} {0 {}} +do_test table-10.8 { + catchsql { + DROP TABLE t6; + CREATE TABLE t6(a,b,c, + FOREIGN KEY (b,c) REFERENCES t4(x,y) MATCH PARTIAL + ON UPDATE SET NULL ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED + ); + } +} {0 {}} +do_test table-10.9 { + catchsql { + DROP TABLE t6; + CREATE TABLE t6(a,b,c, + FOREIGN KEY (b,c) REFERENCES t4(x) + ); + } +} {1 {number of columns in foreign key does not match the number of columns in the referenced table}} +do_test table-10.10 { + catchsql {DROP TABLE t6} + catchsql { + CREATE TABLE t6(a,b,c, + FOREIGN KEY (b,c) REFERENCES t4(x,y,z) + ); + } +} {1 {number of columns in foreign key does not match the number of columns in the referenced table}} +do_test table-10.11 { + catchsql {DROP TABLE t6} + catchsql { + CREATE TABLE t6(a,b, c REFERENCES t4(x,y)); + } +} {1 {foreign key on c should reference only one column of table t4}} +do_test table-10.12 { + catchsql {DROP TABLE t6} + catchsql { + CREATE TABLE t6(a,b,c, + FOREIGN KEY (b,x) REFERENCES t4(x,y) + ); + } +} {1 {unknown column "x" in foreign key definition}} +do_test table-10.13 { + catchsql {DROP TABLE t6} + catchsql { + CREATE TABLE t6(a,b,c, + FOREIGN KEY (x,b) REFERENCES t4(x,y) + ); + } +} {1 {unknown column "x" in foreign key definition}} +} ;# endif foreignkey + +# Test for the "typeof" function. More tests for the +# typeof() function are found in bind.test and types.test. +# +do_test table-11.1 { + execsql { + CREATE TABLE t7( + a integer primary key, + b number(5,10), + c character varying (8), + d VARCHAR(9), + e clob, + f BLOB, + g Text, + h + ); + INSERT INTO t7(a) VALUES(1); + SELECT typeof(a), typeof(b), typeof(c), typeof(d), + typeof(e), typeof(f), typeof(g), typeof(h) + FROM t7 LIMIT 1; + } +} {integer null null null null null null null} +do_test table-11.2 { + execsql { + SELECT typeof(a+b), typeof(a||b), typeof(c+d), typeof(c||d) + FROM t7 LIMIT 1; + } +} {null null null null} + +# Test that when creating a table using CREATE TABLE AS, column types are +# assigned correctly for (SELECT ...) and 'x AS y' expressions. +do_test table-12.1 { + ifcapable subquery { + execsql { + CREATE TABLE t8 AS SELECT b, h, a as i, (SELECT f FROM t7) as j FROM t7; + } + } else { + execsql { + CREATE TABLE t8 AS SELECT b, h, a as i, f as j FROM t7; + } + } +} {} +do_test table-12.2 { + execsql { + SELECT sql FROM sqlite_master WHERE tbl_name = 't8' + } +} {{CREATE TABLE t8(b NUM,h,i INT,j)}} + +#-------------------------------------------------------------------- +# Test cases table-13.* +# +# Test the ability to have default values of CURRENT_TIME, CURRENT_DATE +# and CURRENT_TIMESTAMP. +# +do_test table-13.1 { + execsql { + CREATE TABLE tablet8( + a integer primary key, + tm text DEFAULT CURRENT_TIME, + dt text DEFAULT CURRENT_DATE, + dttm text DEFAULT CURRENT_TIMESTAMP + ); + SELECT * FROM tablet8; + } +} {} +set i 0 +unset -nocomplain date time seconds +foreach {date time seconds} { + 1976-07-04 12:00:00 205329600 + 1994-04-16 14:00:00 766504800 + 2000-01-01 00:00:00 946684800 + 2003-12-31 12:34:56 1072874096 +} { + incr i + set sqlite_current_time $seconds + do_test table-13.2.$i { + execsql " + INSERT INTO tablet8(a) VALUES($i); + SELECT tm, dt, dttm FROM tablet8 WHERE a=$i; + " + } [list $time $date [list $date $time]] +} +set sqlite_current_time 0 + +#-------------------------------------------------------------------- +# Test cases table-14.* +# +# Test that a table cannot be created or dropped while other virtual +# machines are active. This is required because otherwise when in +# auto-vacuum mode the btree-layer may need to move the root-pages of +# a table for which there is an open cursor. +# +# 2007-05-02: A open btree cursor no longer blocks CREATE TABLE. +# But DROP TABLE is still prohibited because we do not want to +# delete a table out from under a running query. +# + +# db eval { +# pragma vdbe_trace = 0; +# } +# Try to create a table from within a callback: +unset -nocomplain result +do_test table-14.1 { + set rc [ + catch { + db eval {SELECT * FROM tablet8 LIMIT 1} {} { + db eval {CREATE TABLE t9(a, b, c)} + } + } msg + ] + set result [list $rc $msg] +} {0 {}} + +# Try to drop a table from within a callback: +do_test table-14.2 { + set rc [ + catch { + db eval {SELECT * FROM tablet8 LIMIT 1} {} { + db eval {DROP TABLE t9;} + } + } msg + ] + set result [list $rc $msg] +} {1 {database table is locked}} + +ifcapable attach { + # Now attach a database and ensure that a table can be created in the + # attached database whilst in a callback from a query on the main database. + do_test table-14.3 { + forcedelete test2.db + forcedelete test2.db-journal + execsql { + ATTACH 'test2.db' as aux; + } + db eval {SELECT * FROM tablet8 LIMIT 1} {} { + db eval {CREATE TABLE aux.t1(a, b, c)} + } + } {} + + # On the other hand, it should be impossible to drop a table when any VMs + # are active. This is because VerifyCookie instructions may have already + # been executed, and btree root-pages may not move after this (which a + # delete table might do). + do_test table-14.4 { + set rc [ + catch { + db eval {SELECT * FROM tablet8 LIMIT 1} {} { + db eval {DROP TABLE aux.t1;} + } + } msg + ] + set result [list $rc $msg] + } {1 {database table is locked}} +} + +# Create and drop 2000 tables. This is to check that the balance_shallow() +# routine works correctly on the sqlite_master table. At one point it +# contained a bug that would prevent the right-child pointer of the +# child page from being copied to the root page. +# +do_test table-15.1 { + execsql {BEGIN} + for {set i 0} {$i<2000} {incr i} { + execsql "CREATE TABLE tbl$i (a, b, c)" + } + execsql {COMMIT} +} {} +do_test table-15.2 { + execsql {BEGIN} + for {set i 0} {$i<2000} {incr i} { + execsql "DROP TABLE tbl$i" + } + execsql {COMMIT} +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tableapi.test b/components/external/SQLite-3.8.1/test/tableapi.test new file mode 100644 index 0000000000000000000000000000000000000000..122267fea8fb9bf37d6e17a36d2addd3aa4aad11 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tableapi.test @@ -0,0 +1,256 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the sqlite_exec_printf() and +# sqlite_get_table_printf() APIs. +# +# $Id: tableapi.test,v 1.21 2009/07/17 14:37:25 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !gettable { + finish_test + return +} + +ifcapable memdebug { + source $testdir/malloc_common.tcl +} + +do_test tableapi-1.0 { + set ::dbx [sqlite3_open test.db] + catch {sqlite_exec_printf $::dbx {DROP TABLE xyz} {}} + sqlite3_exec_printf $::dbx {CREATE TABLE %s(a int, b text)} xyz +} {0 {}} +do_test tableapi-1.1 { + sqlite3_exec_printf $::dbx { + INSERT INTO xyz VALUES(1,'%q') + } {Hi Y'all} +} {0 {}} +do_test tableapi-1.2 { + sqlite3_exec_printf $::dbx {SELECT * FROM xyz} {} +} {0 {a b 1 {Hi Y'all}}} + +do_test tableapi-2.1 { + sqlite3_get_table_printf $::dbx { + BEGIN TRANSACTION; + SELECT * FROM xyz WHERE b='%q' + } {Hi Y'all} +} {0 1 2 a b 1 {Hi Y'all}} +do_test tableapi-2.2 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz + } {} +} {0 1 2 a b 1 {Hi Y'all}} +do_test tableapi-2.3 { + for {set i 2} {$i<=50} {incr i} { + sqlite3_get_table_printf $::dbx \ + "INSERT INTO xyz VALUES($i,'(%s)')" $i + } + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz ORDER BY a + } {} +} {0 50 2 a b 1 {Hi Y'all} 2 (2) 3 (3) 4 (4) 5 (5) 6 (6) 7 (7) 8 (8) 9 (9) 10 (10) 11 (11) 12 (12) 13 (13) 14 (14) 15 (15) 16 (16) 17 (17) 18 (18) 19 (19) 20 (20) 21 (21) 22 (22) 23 (23) 24 (24) 25 (25) 26 (26) 27 (27) 28 (28) 29 (29) 30 (30) 31 (31) 32 (32) 33 (33) 34 (34) 35 (35) 36 (36) 37 (37) 38 (38) 39 (39) 40 (40) 41 (41) 42 (42) 43 (43) 44 (44) 45 (45) 46 (46) 47 (47) 48 (48) 49 (49) 50 (50)} +do_test tableapi-2.3.1 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>49 ORDER BY a + } {} +} {0 1 2 a b 50 (50)} +do_test tableapi-2.3.2 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>47 ORDER BY a + } {} +} {0 3 2 a b 48 (48) 49 (49) 50 (50)} +do_test tableapi-2.3.3 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>47 ORDER BY a; invalid + } {} +} {1 {near "invalid": syntax error}} +do_test tableapi-2.3.4 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>47 ORDER BY a + } {} 8 +} {0 a b 48 (48) 49 (49) 50 (50)} +do_test tableapi-2.4 { + set manyquote '''''''' + append manyquote $manyquote + append manyquote $manyquote + append manyquote $manyquote + append manyquote $manyquote + append manyquote $manyquote + append manyquote $manyquote + set ::big_str "$manyquote Hello $manyquote" + sqlite3_get_table_printf $::dbx { + INSERT INTO xyz VALUES(51,'%q') + } $::big_str +} {0 0 0} +do_test tableapi-2.5 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>49 ORDER BY a; + } {} +} "0 2 2 a b 50 (50) 51 \173$::big_str\175" +do_test tableapi-2.6 { + sqlite3_get_table_printf $::dbx { + INSERT INTO xyz VALUES(52,NULL) + } {} + ifcapable subquery { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a IN (42,50,52) ORDER BY a DESC + } {} + } else { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a=42 OR a=50 OR a=52 ORDER BY a DESC + } {} + } +} {0 3 2 a b 52 NULL 50 (50) 42 (42)} +do_test tableapi-2.7 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>1000 + } {} +} {0 0 0} + +# Repeat all tests with the empty_result_callbacks pragma turned on +# +do_test tableapi-3.1 { + sqlite3_get_table_printf $::dbx { + ROLLBACK; + PRAGMA empty_result_callbacks = ON; + SELECT * FROM xyz WHERE b='%q' + } {Hi Y'all} +} {0 1 2 a b 1 {Hi Y'all}} +do_test tableapi-3.2 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz + } {} +} {0 1 2 a b 1 {Hi Y'all}} +do_test tableapi-3.3 { + for {set i 2} {$i<=50} {incr i} { + sqlite3_get_table_printf $::dbx \ + "INSERT INTO xyz VALUES($i,'(%s)')" $i + } + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz ORDER BY a + } {} +} {0 50 2 a b 1 {Hi Y'all} 2 (2) 3 (3) 4 (4) 5 (5) 6 (6) 7 (7) 8 (8) 9 (9) 10 (10) 11 (11) 12 (12) 13 (13) 14 (14) 15 (15) 16 (16) 17 (17) 18 (18) 19 (19) 20 (20) 21 (21) 22 (22) 23 (23) 24 (24) 25 (25) 26 (26) 27 (27) 28 (28) 29 (29) 30 (30) 31 (31) 32 (32) 33 (33) 34 (34) 35 (35) 36 (36) 37 (37) 38 (38) 39 (39) 40 (40) 41 (41) 42 (42) 43 (43) 44 (44) 45 (45) 46 (46) 47 (47) 48 (48) 49 (49) 50 (50)} +do_test tableapi-3.3.1 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>49 ORDER BY a + } {} +} {0 1 2 a b 50 (50)} +do_test tableapi-3.3.2 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>47 ORDER BY a + } {} +} {0 3 2 a b 48 (48) 49 (49) 50 (50)} +do_test tableapi-3.4 { + sqlite3_get_table_printf $::dbx { + INSERT INTO xyz VALUES(51,'%q') + } $::big_str +} {0 0 0} +do_test tableapi-3.5 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>49 ORDER BY a; + } {} +} "0 2 2 a b 50 (50) 51 \173$::big_str\175" +do_test tableapi-3.6 { + sqlite3_get_table_printf $::dbx { + INSERT INTO xyz VALUES(52,NULL) + } {} + ifcapable subquery { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a IN (42,50,52) ORDER BY a DESC + } {} + } else { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a=42 OR a=50 OR a=52 ORDER BY a DESC + } {} + } +} {0 3 2 a b 52 NULL 50 (50) 42 (42)} +do_test tableapi-3.7 { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz WHERE a>1000 + } {} +} {0 0 2 a b} + +do_test tableapi-4.1 { + set rc [catch { + sqlite3_get_table_printf $::dbx { + SELECT * FROM xyz; SELECT * FROM sqlite_master + } {} + } msg] + concat $rc $msg +} {0 1 {sqlite3_get_table() called with two or more incompatible queries}} + +# A report on the mailing list says that the sqlite_get_table() api fails +# on queries involving more than 40 columns. The following code attempts +# to test that complaint +# +do_test tableapi-5.1 { + set sql "CREATE TABLE t2(" + set sep "" + for {set i 1} {$i<=100} {incr i} { + append sql ${sep}x$i + set sep , + } + append sql ) + sqlite3_get_table_printf $::dbx $sql {} + set sql "INSERT INTO t2 VALUES(" + set sep "" + for {set i 1} {$i<=100} {incr i} { + append sql ${sep}$i + set sep , + } + append sql ) + sqlite3_get_table_printf $::dbx $sql {} + sqlite3_get_table_printf $::dbx {SELECT * FROM t2} {} +} {0 1 100 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 x51 x52 x53 x54 x55 x56 x57 x58 x59 x60 x61 x62 x63 x64 x65 x66 x67 x68 x69 x70 x71 x72 x73 x74 x75 x76 x77 x78 x79 x80 x81 x82 x83 x84 x85 x86 x87 x88 x89 x90 x91 x92 x93 x94 x95 x96 x97 x98 x99 x100 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100} +do_test tableapi-5.2 { + set sql "INSERT INTO t2 VALUES(" + set sep "" + for {set i 1} {$i<=100} {incr i} { + append sql ${sep}[expr {$i+1000}] + set sep , + } + append sql ) + sqlite3_get_table_printf $::dbx $sql {} + sqlite3_get_table_printf $::dbx {SELECT * FROM t2} {} +} {0 2 100 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 x51 x52 x53 x54 x55 x56 x57 x58 x59 x60 x61 x62 x63 x64 x65 x66 x67 x68 x69 x70 x71 x72 x73 x74 x75 x76 x77 x78 x79 x80 x81 x82 x83 x84 x85 x86 x87 x88 x89 x90 x91 x92 x93 x94 x95 x96 x97 x98 x99 x100 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100} + +ifcapable schema_pragmas { + do_test tableapi-6.1 { + sqlite3_get_table_printf $::dbx {PRAGMA user_version} {} + } {0 1 1 user_version 0} +} + +# do_malloc_test closes and deletes the usual db connections and files on +# each iteration. $::dbx is a seperate connection, and on Windows, will +# cause the file deletion of test.db to fail, so we move the close of $::dbx +# up to here before the do_malloc_test. +do_test tableapi-99.0 { + sqlite3_close $::dbx +} {SQLITE_OK} + +ifcapable memdebug { + do_malloc_test tableapi-7 -sqlprep { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + INSERT INTO t1 SELECT a+4, b+4 FROM t1; + INSERT INTO t1 SELECT a+8, b+8 FROM t1; + } -tclbody { + set r [sqlite3_get_table_printf db {SELECT rowid, a, b FROM t1} {}] + if {[llength $r]<26} {error "out of memory"} + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tclsqlite.test b/components/external/SQLite-3.8.1/test/tclsqlite.test new file mode 100644 index 0000000000000000000000000000000000000000..3d9cd46ac6b949e366e0b352b1f961a654bd555a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tclsqlite.test @@ -0,0 +1,641 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for TCL interface to the +# SQLite library. +# +# Actually, all tests are based on the TCL interface, so the main +# interface is pretty well tested. This file contains some addition +# tests for fringe issues that the main test suite does not cover. +# +# $Id: tclsqlite.test,v 1.73 2009/03/16 13:19:36 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Check the error messages generated by tclsqlite +# +if {[sqlite3 -has-codec]} { + set r "sqlite_orig HANDLE FILENAME ?-key CODEC-KEY?" +} else { + set r "sqlite_orig HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN? ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?" +} +do_test tcl-1.1 { + set v [catch {sqlite3 bogus} msg] + regsub {really_sqlite3} $msg {sqlite3} msg + lappend v $msg +} [list 1 "wrong # args: should be \"$r\""] +do_test tcl-1.2 { + set v [catch {db bogus} msg] + lappend v $msg +} {1 {bad option "bogus": must be authorizer, backup, busy, cache, changes, close, collate, collation_needed, commit_hook, complete, copy, enable_load_extension, errorcode, eval, exists, function, incrblob, interrupt, last_insert_rowid, nullvalue, onecolumn, profile, progress, rekey, restore, rollback_hook, status, timeout, total_changes, trace, transaction, unlock_notify, update_hook, version, or wal_hook}} +do_test tcl-1.2.1 { + set v [catch {db cache bogus} msg] + lappend v $msg +} {1 {bad option "bogus": must be flush or size}} +do_test tcl-1.2.2 { + set v [catch {db cache} msg] + lappend v $msg +} {1 {wrong # args: should be "db cache option ?arg?"}} +do_test tcl-1.3 { + execsql {CREATE TABLE t1(a int, b int)} + execsql {INSERT INTO t1 VALUES(10,20)} + set v [catch { + db eval {SELECT * FROM t1} data { + error "The error message" + } + } msg] + lappend v $msg +} {1 {The error message}} +do_test tcl-1.4 { + set v [catch { + db eval {SELECT * FROM t2} data { + error "The error message" + } + } msg] + lappend v $msg +} {1 {no such table: t2}} +do_test tcl-1.5 { + set v [catch { + db eval {SELECT * FROM t1} data { + break + } + } msg] + lappend v $msg +} {0 {}} +catch {expr x*} msg +do_test tcl-1.6 { + set v [catch { + db eval {SELECT * FROM t1} data { + expr x* + } + } msg] + lappend v $msg +} [list 1 $msg] +do_test tcl-1.7 { + set v [catch {db} msg] + lappend v $msg +} {1 {wrong # args: should be "db SUBCOMMAND ..."}} +if {[catch {db auth {}}]==0} { + do_test tcl-1.8 { + set v [catch {db authorizer 1 2 3} msg] + lappend v $msg + } {1 {wrong # args: should be "db authorizer ?CALLBACK?"}} +} +do_test tcl-1.9 { + set v [catch {db busy 1 2 3} msg] + lappend v $msg +} {1 {wrong # args: should be "db busy CALLBACK"}} +do_test tcl-1.10 { + set v [catch {db progress 1} msg] + lappend v $msg +} {1 {wrong # args: should be "db progress N CALLBACK"}} +do_test tcl-1.11 { + set v [catch {db changes xyz} msg] + lappend v $msg +} {1 {wrong # args: should be "db changes "}} +do_test tcl-1.12 { + set v [catch {db commit_hook a b c} msg] + lappend v $msg +} {1 {wrong # args: should be "db commit_hook ?CALLBACK?"}} +ifcapable {complete} { + do_test tcl-1.13 { + set v [catch {db complete} msg] + lappend v $msg + } {1 {wrong # args: should be "db complete SQL"}} +} +do_test tcl-1.14 { + set v [catch {db eval} msg] + lappend v $msg +} {1 {wrong # args: should be "db eval SQL ?ARRAY-NAME? ?SCRIPT?"}} +do_test tcl-1.15 { + set v [catch {db function} msg] + lappend v $msg +} {1 {wrong # args: should be "db function NAME [-argcount N] SCRIPT"}} +do_test tcl-1.16 { + set v [catch {db last_insert_rowid xyz} msg] + lappend v $msg +} {1 {wrong # args: should be "db last_insert_rowid "}} +do_test tcl-1.17 { + set v [catch {db rekey} msg] + lappend v $msg +} {1 {wrong # args: should be "db rekey KEY"}} +do_test tcl-1.18 { + set v [catch {db timeout} msg] + lappend v $msg +} {1 {wrong # args: should be "db timeout MILLISECONDS"}} +do_test tcl-1.19 { + set v [catch {db collate} msg] + lappend v $msg +} {1 {wrong # args: should be "db collate NAME SCRIPT"}} +do_test tcl-1.20 { + set v [catch {db collation_needed} msg] + lappend v $msg +} {1 {wrong # args: should be "db collation_needed SCRIPT"}} +do_test tcl-1.21 { + set v [catch {db total_changes xyz} msg] + lappend v $msg +} {1 {wrong # args: should be "db total_changes "}} +do_test tcl-1.22 { + set v [catch {db copy} msg] + lappend v $msg +} {1 {wrong # args: should be "db copy CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?"}} +do_test tcl-1.23 { + set v [catch {sqlite3 db2 test.db -vfs nosuchvfs} msg] + lappend v $msg +} {1 {no such vfs: nosuchvfs}} + +catch {unset ::result} +do_test tcl-2.1 { + execsql "CREATE TABLE t\u0123x(a int, b\u1235 float)" +} {} +ifcapable schema_pragmas { + do_test tcl-2.2 { + execsql "PRAGMA table_info(t\u0123x)" + } "0 a int 0 {} 0 1 b\u1235 float 0 {} 0" +} +do_test tcl-2.3 { + execsql "INSERT INTO t\u0123x VALUES(1,2.3)" + db eval "SELECT * FROM t\u0123x" result break + set result(*) +} "a b\u1235" + + +# Test the onecolumn method +# +do_test tcl-3.1 { + execsql { + INSERT INTO t1 SELECT a*2, b*2 FROM t1; + INSERT INTO t1 SELECT a*2+1, b*2+1 FROM t1; + INSERT INTO t1 SELECT a*2+3, b*2+3 FROM t1; + } + set rc [catch {db onecolumn {SELECT * FROM t1 ORDER BY a}} msg] + lappend rc $msg +} {0 10} +do_test tcl-3.2 { + db onecolumn {SELECT * FROM t1 WHERE a<0} +} {} +do_test tcl-3.3 { + set rc [catch {db onecolumn} errmsg] + lappend rc $errmsg +} {1 {wrong # args: should be "db onecolumn SQL"}} +do_test tcl-3.4 { + set rc [catch {db onecolumn {SELECT bogus}} errmsg] + lappend rc $errmsg +} {1 {no such column: bogus}} +ifcapable {tclvar} { + do_test tcl-3.5 { + set b 50 + set rc [catch {db one {SELECT * FROM t1 WHERE b>$b}} msg] + lappend rc $msg + } {0 41} + do_test tcl-3.6 { + set b 500 + set rc [catch {db one {SELECT * FROM t1 WHERE b>$b}} msg] + lappend rc $msg + } {0 {}} + do_test tcl-3.7 { + set b 500 + set rc [catch {db one { + INSERT INTO t1 VALUES(99,510); + SELECT * FROM t1 WHERE b>$b + }} msg] + lappend rc $msg + } {0 99} +} +ifcapable {!tclvar} { + execsql {INSERT INTO t1 VALUES(99,510)} +} + +# Turn the busy handler on and off +# +do_test tcl-4.1 { + proc busy_callback {cnt} { + break + } + db busy busy_callback + db busy +} {busy_callback} +do_test tcl-4.2 { + db busy {} + db busy +} {} + +ifcapable {tclvar} { + # Parsing of TCL variable names within SQL into bound parameters. + # + do_test tcl-5.1 { + execsql {CREATE TABLE t3(a,b,c)} + catch {unset x} + set x(1) A + set x(2) B + execsql { + INSERT INTO t3 VALUES($::x(1),$::x(2),$::x(3)); + SELECT * FROM t3 + } + } {A B {}} + do_test tcl-5.2 { + execsql { + SELECT typeof(a), typeof(b), typeof(c) FROM t3 + } + } {text text null} + do_test tcl-5.3 { + catch {unset x} + set x [binary format h12 686900686f00] + execsql { + UPDATE t3 SET a=$::x; + } + db eval { + SELECT a FROM t3 + } break + binary scan $a h12 adata + set adata + } {686900686f00} + do_test tcl-5.4 { + execsql { + SELECT typeof(a), typeof(b), typeof(c) FROM t3 + } + } {blob text null} +} + +# Operation of "break" and "continue" within row scripts +# +do_test tcl-6.1 { + db eval {SELECT * FROM t1} { + break + } + lappend a $b +} {10 20} +do_test tcl-6.2 { + set cnt 0 + db eval {SELECT * FROM t1} { + if {$a>40} continue + incr cnt + } + set cnt +} {4} +do_test tcl-6.3 { + set cnt 0 + db eval {SELECT * FROM t1} { + if {$a<40} continue + incr cnt + } + set cnt +} {5} +do_test tcl-6.4 { + proc return_test {x} { + db eval {SELECT * FROM t1} { + if {$a==$x} {return $b} + } + } + return_test 10 +} 20 +do_test tcl-6.5 { + return_test 20 +} 40 +do_test tcl-6.6 { + return_test 99 +} 510 +do_test tcl-6.7 { + return_test 0 +} {} + +do_test tcl-7.1 { + db version + expr 0 +} {0} + +# modify and reset the NULL representation +# +do_test tcl-8.1 { + db nullvalue NaN + execsql {INSERT INTO t1 VALUES(30,NULL)} + db eval {SELECT * FROM t1 WHERE b IS NULL} +} {30 NaN} +proc concatFunc args {return [join $args {}]} +do_test tcl-8.2 { + db function concat concatFunc + db eval {SELECT concat('a', b, 'z') FROM t1 WHERE b is NULL} +} {aNaNz} +do_test tcl-8.3 { + db nullvalue NULL + db nullvalue +} {NULL} +do_test tcl-8.4 { + db nullvalue {} + db eval {SELECT * FROM t1 WHERE b IS NULL} +} {30 {}} +do_test tcl-8.5 { + db function concat concatFunc + db eval {SELECT concat('a', b, 'z') FROM t1 WHERE b is NULL} +} {az} + +# Test the return type of user-defined functions +# +do_test tcl-9.1 { + db function ret_str {return "hi"} + execsql {SELECT typeof(ret_str())} +} {text} +do_test tcl-9.2 { + db function ret_dbl {return [expr {rand()*0.5}]} + execsql {SELECT typeof(ret_dbl())} +} {real} +do_test tcl-9.3 { + db function ret_int {return [expr {int(rand()*200)}]} + execsql {SELECT typeof(ret_int())} +} {integer} + +# Recursive calls to the same user-defined function +# +ifcapable tclvar { + do_test tcl-9.10 { + proc userfunc_r1 {n} { + if {$n<=0} {return 0} + set nm1 [expr {$n-1}] + return [expr {[db eval {SELECT r1($nm1)}]+$n}] + } + db function r1 userfunc_r1 + execsql {SELECT r1(10)} + } {55} + do_test tcl-9.11 { + execsql {SELECT r1(100)} + } {5050} +} + +# Tests for the new transaction method +# +do_test tcl-10.1 { + db transaction {} +} {} +do_test tcl-10.2 { + db transaction deferred {} +} {} +do_test tcl-10.3 { + db transaction immediate {} +} {} +do_test tcl-10.4 { + db transaction exclusive {} +} {} +do_test tcl-10.5 { + set rc [catch {db transaction xyzzy {}} msg] + lappend rc $msg +} {1 {bad transaction type "xyzzy": must be deferred, exclusive, or immediate}} +do_test tcl-10.6 { + set rc [catch {db transaction {error test-error}} msg] + lappend rc $msg +} {1 test-error} +do_test tcl-10.7 { + db transaction { + db eval {CREATE TABLE t4(x)} + db transaction { + db eval {INSERT INTO t4 VALUES(1)} + } + } + db eval {SELECT * FROM t4} +} 1 +do_test tcl-10.8 { + catch { + db transaction { + db eval {INSERT INTO t4 VALUES(2)} + db eval {INSERT INTO t4 VALUES(3)} + db eval {INSERT INTO t4 VALUES(4)} + error test-error + } + } + db eval {SELECT * FROM t4} +} 1 +do_test tcl-10.9 { + db transaction { + db eval {INSERT INTO t4 VALUES(2)} + catch { + db transaction { + db eval {INSERT INTO t4 VALUES(3)} + db eval {INSERT INTO t4 VALUES(4)} + error test-error + } + } + } + db eval {SELECT * FROM t4} +} {1 2} +do_test tcl-10.10 { + for {set i 0} {$i<1} {incr i} { + db transaction { + db eval {INSERT INTO t4 VALUES(5)} + continue + } + error "This line should not be run" + } + db eval {SELECT * FROM t4} +} {1 2 5} +do_test tcl-10.11 { + for {set i 0} {$i<10} {incr i} { + db transaction { + db eval {INSERT INTO t4 VALUES(6)} + break + } + } + db eval {SELECT * FROM t4} +} {1 2 5 6} +do_test tcl-10.12 { + set rc [catch { + for {set i 0} {$i<10} {incr i} { + db transaction { + db eval {INSERT INTO t4 VALUES(7)} + return + } + } + }] +} {2} +do_test tcl-10.13 { + db eval {SELECT * FROM t4} +} {1 2 5 6 7} + +# Now test that [db transaction] commands may be nested with +# the expected results. +# +do_test tcl-10.14 { + db transaction { + db eval { + DELETE FROM t4; + INSERT INTO t4 VALUES('one'); + } + + catch { + db transaction { + db eval { INSERT INTO t4 VALUES('two') } + db transaction { + db eval { INSERT INTO t4 VALUES('three') } + error "throw an error!" + } + } + } + } + + db eval {SELECT * FROM t4} +} {one} +do_test tcl-10.15 { + # Make sure a transaction has not been left open. + db eval {BEGIN ; COMMIT} +} {} +do_test tcl-10.16 { + db transaction { + db eval { INSERT INTO t4 VALUES('two'); } + db transaction { + db eval { INSERT INTO t4 VALUES('three') } + db transaction { + db eval { INSERT INTO t4 VALUES('four') } + } + } + } + db eval {SELECT * FROM t4} +} {one two three four} +do_test tcl-10.17 { + catch { + db transaction { + db eval { INSERT INTO t4 VALUES('A'); } + db transaction { + db eval { INSERT INTO t4 VALUES('B') } + db transaction { + db eval { INSERT INTO t4 VALUES('C') } + error "throw an error!" + } + } + } + } + db eval {SELECT * FROM t4} +} {one two three four} +do_test tcl-10.18 { + # Make sure a transaction has not been left open. + db eval {BEGIN ; COMMIT} +} {} + +# Mess up a [db transaction] command by locking the database using a +# second connection when it tries to commit. Make sure the transaction +# is not still open after the "database is locked" exception is thrown. +# +do_test tcl-10.18 { + sqlite3 db2 test.db + db2 eval { + BEGIN; + SELECT * FROM sqlite_master; + } + + set rc [catch { + db transaction { + db eval {INSERT INTO t4 VALUES('five')} + } + } msg] + list $rc $msg +} {1 {database is locked}} +do_test tcl-10.19 { + db eval {BEGIN ; COMMIT} +} {} + +# Thwart a [db transaction] command by locking the database using a +# second connection with "BEGIN EXCLUSIVE". Make sure no transaction is +# open after the "database is locked" exception is thrown. +# +do_test tcl-10.20 { + db2 eval { + COMMIT; + BEGIN EXCLUSIVE; + } + set rc [catch { + db transaction { + db eval {INSERT INTO t4 VALUES('five')} + } + } msg] + list $rc $msg +} {1 {database is locked}} +do_test tcl-10.21 { + db2 close + db eval {BEGIN ; COMMIT} +} {} +do_test tcl-10.22 { + sqlite3 db2 test.db + db transaction exclusive { + catch { db2 eval {SELECT * FROM sqlite_master} } msg + set msg "db2: $msg" + } + set msg +} {db2: database is locked} +db2 close + +do_test tcl-11.1 { + db eval {INSERT INTO t4 VALUES(6)} + db exists {SELECT x,x*2,x+x FROM t4 WHERE x==6} +} {1} +do_test tcl-11.2 { + db exists {SELECT 0 FROM t4 WHERE x==6} +} {1} +do_test tcl-11.3 { + db exists {SELECT 1 FROM t4 WHERE x==8} +} {0} +do_test tcl-11.3.1 { + tcl_objproc db exists {SELECT 1 FROM t4 WHERE x==8} +} {0} + +do_test tcl-12.1 { + unset -nocomplain a b c version + set version [db version] + scan $version "%d.%d.%d" a b c + expr $a*1000000 + $b*1000 + $c +} [sqlite3_libversion_number] + + +# Check to see that when bindings of the form @aaa are used instead +# of $aaa, that objects are treated as bytearray and are inserted +# as BLOBs. +# +ifcapable tclvar { + do_test tcl-13.1 { + db eval {CREATE TABLE t5(x BLOB)} + set x abc123 + db eval {INSERT INTO t5 VALUES($x)} + db eval {SELECT typeof(x) FROM t5} + } {text} + do_test tcl-13.2 { + binary scan $x H notUsed + db eval { + DELETE FROM t5; + INSERT INTO t5 VALUES($x); + SELECT typeof(x) FROM t5; + } + } {text} + do_test tcl-13.3 { + db eval { + DELETE FROM t5; + INSERT INTO t5 VALUES(@x); + SELECT typeof(x) FROM t5; + } + } {blob} + do_test tcl-13.4 { + set y 1234 + db eval { + DELETE FROM t5; + INSERT INTO t5 VALUES(@y); + SELECT hex(x), typeof(x) FROM t5 + } + } {31323334 blob} +} + +db func xCall xCall +proc xCall {} { return "value" } +do_execsql_test tcl-14.1 { + CREATE TABLE t6(x); + INSERT INTO t6 VALUES(1); +} +do_test tcl-14.2 { + db one {SELECT x FROM t6 WHERE xCall()!='value'} +} {} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tempdb.test b/components/external/SQLite-3.8.1/test/tempdb.test new file mode 100644 index 0000000000000000000000000000000000000000..ecd23d4e32866f437f953f1e3370013e4a8ed072 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tempdb.test @@ -0,0 +1,93 @@ +# 2008 April 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# The focus of this file is in making sure that rolling back +# a statement journal works correctly. +# +# $Id: tempdb.test,v 1.4 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Use a temporary database. +# +db close +sqlite3 db {} + +# Force a statement journal rollback on a database file that +# has never been opened. +# +do_test tempdb-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(x UNIQUE); + CREATE TABLE t2(y); + INSERT INTO t2 VALUES('hello'); + INSERT INTO t2 VALUES(NULL); + } + # Because of the transaction, the temporary database file + # has not even been opened yet. The following statement + # will cause a statement journal rollback on this non-existant + # file. + catchsql { + INSERT INTO t1 + SELECT CASE WHEN y IS NULL THEN test_error('oops', 11) ELSE y END + FROM t2; + } +} {1 oops} + +# Verify that no writes occurred in t1. +# +do_test tempdb-1.2 { + execsql { + SELECT * FROM t1 + } +} {} + +do_test tempdb-2.1 { + # Set $::jrnl_in_memory if the journal file is expected to be in-memory. + # Similarly, set $::subj_in_memory if the sub-journal file is expected + # to be in memory. These variables are used to calculate the expected + # number of open files in the test cases below. + # + set jrnl_in_memory [expr {[permutation] eq "inmemory_journal"}] + set subj_in_memory [expr {$jrnl_in_memory || $TEMP_STORE>=2}] + + db close + sqlite3 db test.db +} {} +do_test tempdb-2.2 { + execsql { + CREATE TABLE t1 (a PRIMARY KEY, b, c); + CREATE TABLE t2 (a, b, c); + BEGIN; + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + INSERT INTO t2 VALUES(7, 8, 9); + INSERT INTO t2 SELECT * FROM t1; + } + catchsql { INSERT INTO t1 SELECT * FROM t2 } + set sqlite_open_file_count +} [expr 1 + (0==$jrnl_in_memory) + (0==$subj_in_memory)] +do_test tempdb-2.3 { + execsql { + PRAGMA temp_store = 'memory'; + ROLLBACK; + BEGIN; + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + INSERT INTO t2 SELECT * FROM t1; + } + catchsql { INSERT INTO t1 SELECT * FROM t2 } + set sqlite_open_file_count +} [expr 1 + (0==$jrnl_in_memory)] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/temptable.test b/components/external/SQLite-3.8.1/test/temptable.test new file mode 100644 index 0000000000000000000000000000000000000000..6a1e2b9867901100d83b59f05cc40f9ab90e2238 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/temptable.test @@ -0,0 +1,441 @@ +# 2001 October 7 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for temporary tables and indices. +# +# $Id: temptable.test,v 1.21 2009/06/16 17:49:36 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !tempdb { + finish_test + return +} + +# Create an alternative connection to the database +# +do_test temptable-1.0 { + sqlite3 db2 ./test.db + set dummy {} +} {} + +# Create a permanent table. +# +do_test temptable-1.1 { + execsql {CREATE TABLE t1(a,b,c);} + execsql {INSERT INTO t1 VALUES(1,2,3);} + execsql {SELECT * FROM t1} +} {1 2 3} +do_test temptable-1.2 { + catch {db2 eval {SELECT * FROM sqlite_master}} + db2 eval {SELECT * FROM t1} +} {1 2 3} +do_test temptable-1.3 { + execsql {SELECT name FROM sqlite_master} +} {t1} +do_test temptable-1.4 { + db2 eval {SELECT name FROM sqlite_master} +} {t1} + +# Create a temporary table. Verify that only one of the two +# processes can see it. +# +do_test temptable-1.5 { + db2 eval { + CREATE TEMP TABLE t2(x,y,z); + INSERT INTO t2 VALUES(4,5,6); + } + db2 eval {SELECT * FROM t2} +} {4 5 6} +do_test temptable-1.6 { + catch {execsql {SELECT * FROM sqlite_master}} + catchsql {SELECT * FROM t2} +} {1 {no such table: t2}} +do_test temptable-1.7 { + catchsql {INSERT INTO t2 VALUES(8,9,0);} +} {1 {no such table: t2}} +do_test temptable-1.8 { + db2 eval {INSERT INTO t2 VALUES(8,9,0);} + db2 eval {SELECT * FROM t2 ORDER BY x} +} {4 5 6 8 9 0} +do_test temptable-1.9 { + db2 eval {DELETE FROM t2 WHERE x==8} + db2 eval {SELECT * FROM t2 ORDER BY x} +} {4 5 6} +do_test temptable-1.10 { + db2 eval {DELETE FROM t2} + db2 eval {SELECT * FROM t2} +} {} +do_test temptable-1.11 { + db2 eval { + INSERT INTO t2 VALUES(7,6,5); + INSERT INTO t2 VALUES(4,3,2); + SELECT * FROM t2 ORDER BY x; + } +} {4 3 2 7 6 5} +do_test temptable-1.12 { + db2 eval {DROP TABLE t2;} + set r [catch {db2 eval {SELECT * FROM t2}} msg] + lappend r $msg +} {1 {no such table: t2}} + +# Make sure temporary tables work with transactions +# +do_test temptable-2.1 { + execsql { + BEGIN TRANSACTION; + CREATE TEMPORARY TABLE t2(x,y); + INSERT INTO t2 VALUES(1,2); + SELECT * FROM t2; + } +} {1 2} +do_test temptable-2.2 { + execsql {ROLLBACK} + catchsql {SELECT * FROM t2} +} {1 {no such table: t2}} +do_test temptable-2.3 { + execsql { + BEGIN TRANSACTION; + CREATE TEMPORARY TABLE t2(x,y); + INSERT INTO t2 VALUES(1,2); + SELECT * FROM t2; + } +} {1 2} +do_test temptable-2.4 { + execsql {COMMIT} + catchsql {SELECT * FROM t2} +} {0 {1 2}} +do_test temptable-2.5 { + set r [catch {db2 eval {SELECT * FROM t2}} msg] + lappend r $msg +} {1 {no such table: t2}} + +# Make sure indices on temporary tables are also temporary. +# +do_test temptable-3.1 { + execsql { + CREATE INDEX i2 ON t2(x); + SELECT name FROM sqlite_master WHERE type='index'; + } +} {} +do_test temptable-3.2 { + execsql { + SELECT y FROM t2 WHERE x=1; + } +} {2} +do_test temptable-3.3 { + execsql { + DROP INDEX i2; + SELECT y FROM t2 WHERE x=1; + } +} {2} +do_test temptable-3.4 { + execsql { + CREATE INDEX i2 ON t2(x); + DROP TABLE t2; + } + catchsql {DROP INDEX i2} +} {1 {no such index: i2}} + +# Check for correct name collision processing. A name collision can +# occur when process A creates a temporary table T then process B +# creates a permanent table also named T. The temp table in process A +# hides the existence of the permanent table. +# +do_test temptable-4.1 { + execsql { + CREATE TEMP TABLE t2(x,y); + INSERT INTO t2 VALUES(10,20); + SELECT * FROM t2; + } db2 +} {10 20} +do_test temptable-4.2 { + execsql { + CREATE TABLE t2(x,y,z); + INSERT INTO t2 VALUES(9,8,7); + SELECT * FROM t2; + } +} {9 8 7} +do_test temptable-4.3 { + catchsql { + SELECT * FROM t2; + } db2 +} {0 {10 20}} +do_test temptable-4.4.1 { + catchsql { + SELECT * FROM temp.t2; + } db2 +} {0 {10 20}} +do_test temptable-4.4.2 { + catchsql { + SELECT * FROM main.t2; + } db2 +} {0 {9 8 7}} +#do_test temptable-4.4.3 { +# catchsql { +# SELECT name FROM main.sqlite_master WHERE type='table'; +# } db2 +#} {1 {database schema has changed}} +do_test temptable-4.4.4 { + catchsql { + SELECT name FROM main.sqlite_master WHERE type='table'; + } db2 +} {0 {t1 t2}} +do_test temptable-4.4.5 { + catchsql { + SELECT * FROM main.t2; + } db2 +} {0 {9 8 7}} +do_test temptable-4.4.6 { + # TEMP takes precedence over MAIN + catchsql { + SELECT * FROM t2; + } db2 +} {0 {10 20}} +do_test temptable-4.5 { + catchsql { + DROP TABLE t2; -- should drop TEMP + SELECT * FROM t2; -- data should be from MAIN + } db2 +} {0 {9 8 7}} +do_test temptable-4.6 { + db2 close + sqlite3 db2 ./test.db + catchsql { + SELECT * FROM t2; + } db2 +} {0 {9 8 7}} +do_test temptable-4.7 { + catchsql { + DROP TABLE t2; + SELECT * FROM t2; + } +} {1 {no such table: t2}} +do_test temptable-4.8 { + db2 close + sqlite3 db2 ./test.db + execsql { + CREATE TEMP TABLE t2(x unique,y); + INSERT INTO t2 VALUES(1,2); + SELECT * FROM t2; + } db2 +} {1 2} +do_test temptable-4.9 { + execsql { + CREATE TABLE t2(x unique, y); + INSERT INTO t2 VALUES(3,4); + SELECT * FROM t2; + } +} {3 4} +do_test temptable-4.10.1 { + catchsql { + SELECT * FROM t2; + } db2 +} {0 {1 2}} +# Update: The schema is reloaded in test temptable-4.10.1. And tclsqlite.c +# handles it and retries the query anyway. +# do_test temptable-4.10.2 { +# catchsql { +# SELECT name FROM sqlite_master WHERE type='table' +# } db2 +# } {1 {database schema has changed}} +do_test temptable-4.10.3 { + catchsql { + SELECT name FROM sqlite_master WHERE type='table' + } db2 +} {0 {t1 t2}} +do_test temptable-4.11 { + execsql { + SELECT * FROM t2; + } db2 +} {1 2} +do_test temptable-4.12 { + execsql { + SELECT * FROM t2; + } +} {3 4} +do_test temptable-4.13 { + catchsql { + DROP TABLE t2; -- drops TEMP.T2 + SELECT * FROM t2; -- uses MAIN.T2 + } db2 +} {0 {3 4}} +do_test temptable-4.14 { + execsql { + SELECT * FROM t2; + } +} {3 4} +do_test temptable-4.15 { + db2 close + sqlite3 db2 ./test.db + execsql { + SELECT * FROM t2; + } db2 +} {3 4} + +# Now create a temporary table in db2 and a permanent index in db. The +# temporary table in db2 should mask the name of the permanent index, +# but the permanent index should still be accessible and should still +# be updated when its corresponding table changes. +# +do_test temptable-5.1 { + execsql { + CREATE TEMP TABLE mask(a,b,c) + } db2 + if {[permutation]=="prepare"} { db2 cache flush } + execsql { + CREATE INDEX mask ON t2(x); + SELECT * FROM t2; + } +} {3 4} +#do_test temptable-5.2 { +# catchsql { +# SELECT * FROM t2; +# } db2 +#} {1 {database schema has changed}} +do_test temptable-5.3 { + catchsql { + SELECT * FROM t2; + } db2 +} {0 {3 4}} +do_test temptable-5.4 { + execsql { + SELECT y FROM t2 WHERE x=3 + } +} {4} +do_test temptable-5.5 { + execsql { + SELECT y FROM t2 WHERE x=3 + } db2 +} {4} +do_test temptable-5.6 { + execsql { + INSERT INTO t2 VALUES(1,2); + SELECT y FROM t2 WHERE x=1; + } db2 +} {2} +do_test temptable-5.7 { + execsql { + SELECT y FROM t2 WHERE x=3 + } db2 +} {4} +do_test temptable-5.8 { + execsql { + SELECT y FROM t2 WHERE x=1; + } +} {2} +do_test temptable-5.9 { + execsql { + SELECT y FROM t2 WHERE x=3 + } +} {4} + +db2 close + +# Test for correct operation of read-only databases +# +do_test temptable-6.1 { + execsql { + CREATE TABLE t8(x); + INSERT INTO t8 VALUES('xyzzy'); + SELECT * FROM t8; + } +} {xyzzy} +do_test temptable-6.2 { + db close + catch {file attributes test.db -permissions 0444} + catch {file attributes test.db -readonly 1} + sqlite3 db test.db + if {[file writable test.db]} { + error "Unable to make the database file test.db readonly - rerun this test as an unprivileged user" + } + execsql { + SELECT * FROM t8; + } +} {xyzzy} +do_test temptable-6.3 { + if {[file writable test.db]} { + error "Unable to make the database file test.db readonly - rerun this test as an unprivileged user" + } + catchsql { + CREATE TABLE t9(x,y); + } +} {1 {attempt to write a readonly database}} +do_test temptable-6.4 { + catchsql { + CREATE TEMP TABLE t9(x,y); + } +} {0 {}} +do_test temptable-6.5 { + catchsql { + INSERT INTO t9 VALUES(1,2); + SELECT * FROM t9; + } +} {0 {1 2}} +do_test temptable-6.6 { + if {[file writable test.db]} { + error "Unable to make the database file test.db readonly - rerun this test as an unprivileged user" + } + catchsql { + INSERT INTO t8 VALUES('hello'); + SELECT * FROM t8; + } +} {1 {attempt to write a readonly database}} +do_test temptable-6.7 { + catchsql { + SELECT * FROM t8,t9; + } +} {0 {xyzzy 1 2}} +do_test temptable-6.8 { + db close + sqlite3 db test.db + catchsql { + SELECT * FROM t8,t9; + } +} {1 {no such table: t9}} + +forcedelete test2.db test2.db-journal +ifcapable attach { + do_test temptable-7.1 { + catchsql { + ATTACH 'test2.db' AS two; + CREATE TEMP TABLE two.abc(x,y); + } + } {1 {temporary table name must be unqualified}} +} + +# Need to do the following for tcl 8.5 on mac. On that configuration, the +# -readonly flag is taken so seriously that a subsequent [forcedelete] +# (required before the next test file can be executed) will fail. +# +catch {file attributes test.db -readonly 0} + +do_test temptable-8.0 { + db close + catch {forcedelete test.db} + sqlite3 db test.db +} {} +do_test temptable-8.1 { + execsql { CREATE TEMP TABLE tbl2(a, b); } + execsql { + CREATE TABLE tbl(a, b); + INSERT INTO tbl VALUES(1, 2); + } + execsql {SELECT * FROM tbl} +} {1 2} +do_test temptable-8.2 { + execsql { CREATE TEMP TABLE tbl(a, b); } + execsql {SELECT * FROM tbl} +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/temptrigger.test b/components/external/SQLite-3.8.1/test/temptrigger.test new file mode 100644 index 0000000000000000000000000000000000000000..ed1efb91251fb68fb0d9a1ba4898c46d08476117 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/temptrigger.test @@ -0,0 +1,204 @@ +# 2009 February 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: temptrigger.test,v 1.3 2009/04/15 13:07:19 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!trigger || !shared_cache} { finish_test ; return } + +# Test cases: +# +# temptrigger-1.*: Shared cache problem. +# temptrigger-2.*: A similar shared cache problem. +# temptrigger-3.*: Attached database problem. +# + +#------------------------------------------------------------------------- +# Test case temptrigger-1.* demonstrates a problem with temp triggers +# in shared-cache mode. If process 1 connections to a shared-cache and +# creates a temp trigger, the temp trigger is linked into the shared-cache +# schema. If process 2 reloads the shared-cache schema from disk, then +# it does not recreate the temp trigger belonging to process 1. From the +# point of view of process 1, the temp trigger just disappeared. +# +# temptrigger-1.1: In shared cache mode, create a table in the main +# database and add a temp trigger to it. +# +# temptrigger-1.2: Check that the temp trigger is correctly fired. Check +# that the temp trigger is not fired by statements +# executed by a second connection connected to the +# same shared cache. +# +# temptrigger-1.3: Using the second connection to the shared-cache, cause +# the shared-cache schema to be reloaded. +# +# temptrigger-1.4: Check that the temp trigger is still fired correctly. +# +# temptrigger-1.5: Check that the temp trigger can be dropped without error. +# +db close +set ::enable_shared_cache [sqlite3_enable_shared_cache] +sqlite3_enable_shared_cache 1 + +sqlite3 db test.db +sqlite3 db2 test.db + +do_test temptrigger-1.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE TEMP TABLE tt1(a, b); + CREATE TEMP TRIGGER tr1 AFTER INSERT ON t1 BEGIN + INSERT INTO tt1 VALUES(new.a, new.b); + END; + } +} {} + +do_test temptrigger-1.2.1 { + execsql { INSERT INTO t1 VALUES(1, 2) } + execsql { SELECT * FROM t1 } +} {1 2} +do_test temptrigger-1.2.2 { + execsql { SELECT * FROM tt1 } +} {1 2} +do_test temptrigger-1.2.3 { + execsql { INSERT INTO t1 VALUES(3, 4) } db2 + execsql { SELECT * FROM t1 } +} {1 2 3 4} +do_test temptrigger-1.2.4 { + execsql { SELECT * FROM tt1 } +} {1 2} + +# Cause the shared-cache schema to be reloaded. +# +do_test temptrigger-1.3 { + execsql { BEGIN; CREATE TABLE t3(a, b); ROLLBACK; } db2 +} {} + +do_test temptrigger-1.4 { + execsql { INSERT INTO t1 VALUES(5, 6) } + execsql { SELECT * FROM tt1 } +} {1 2 5 6} + +do_test temptrigger-1.5 { + # Before the bug was fixed, the following 'DROP TRIGGER' hit an + # assert if executed. + #execsql { DROP TRIGGER tr1 } +} {} + +catch {db close} +catch {db2 close} + +#------------------------------------------------------------------------- +# Tests temptrigger-2.* are similar to temptrigger-1.*, except that +# temptrigger-2.3 simply opens and closes a connection to the shared-cache. +# It does not do anything special to cause the schema to be reloaded. +# +do_test temptrigger-2.1 { + sqlite3 db test.db + execsql { + DELETE FROM t1; + CREATE TEMP TABLE tt1(a, b); + CREATE TEMP TRIGGER tr1 AFTER INSERT ON t1 BEGIN + INSERT INTO tt1 VALUES(new.a, new.b); + END; + } +} {} +do_test temptrigger-2.2 { + execsql { + INSERT INTO t1 VALUES(10, 20); + SELECT * FROM tt1; + } +} {10 20} +do_test temptrigger-2.3 { + sqlite3 db2 test.db + db2 close +} {} +do_test temptrigger-2.4 { + execsql { + INSERT INTO t1 VALUES(30, 40); + SELECT * FROM tt1; + } +} {10 20 30 40} +do_test temptrigger-2.5 { + #execsql { DROP TRIGGER tr1 } +} {} + +catch {db close} +catch {db2 close} +sqlite3_enable_shared_cache $::enable_shared_cache + +#------------------------------------------------------------------------- +# Test case temptrigger-3.* demonstrates a problem with temp triggers +# on tables located in attached databases. At one point when SQLite reloaded +# the schema of an attached database (because some other connection had +# changed the schema cookie) it was not re-creating temp triggers attached +# to tables located within the attached database. +# +# temptrigger-3.1: Attach database 'test2.db' to connection [db]. Add a +# temp trigger to a table in 'test2.db'. +# +# temptrigger-3.2: Check that the temp trigger is correctly fired. +# +# temptrigger-3.3: Update the schema of 'test2.db' using an external +# connection. This forces [db] to reload the 'test2.db' +# schema. Check that the temp trigger is still fired +# correctly. +# +# temptrigger-3.4: Check that the temp trigger can be dropped without error. +# +do_test temptrigger-3.1 { + catch { forcedelete test2.db test2.db-journal } + catch { forcedelete test.db test.db-journal } + sqlite3 db test.db + sqlite3 db2 test2.db + execsql { CREATE TABLE t2(a, b) } db2 + execsql { + ATTACH 'test2.db' AS aux; + CREATE TEMP TABLE tt2(a, b); + CREATE TEMP TRIGGER tr2 AFTER INSERT ON aux.t2 BEGIN + INSERT INTO tt2 VALUES(new.a, new.b); + END; + } +} {} + +do_test temptrigger-3.2.1 { + execsql { + INSERT INTO aux.t2 VALUES(1, 2); + SELECT * FROM aux.t2; + } +} {1 2} +do_test temptrigger-3.2.2 { + execsql { SELECT * FROM tt2 } +} {1 2} + +do_test temptrigger-3.3.1 { + execsql { CREATE TABLE t3(a, b) } db2 + execsql { + INSERT INTO aux.t2 VALUES(3, 4); + SELECT * FROM aux.t2; + } +} {1 2 3 4} +do_test temptrigger-3.3.2 { + execsql { SELECT * FROM tt2 } +} {1 2 3 4} + +do_test temptrigger-3.4 { + # Before the bug was fixed, the following 'DROP TRIGGER' hit an + # assert if executed. + #execsql { DROP TRIGGER tr2 } +} {} + +catch { db close } +catch { db2 close } + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tester.tcl b/components/external/SQLite-3.8.1/test/tester.tcl new file mode 100644 index 0000000000000000000000000000000000000000..e4b5edeb809acb491512b40b2e6317be29a7d774 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tester.tcl @@ -0,0 +1,1803 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements some common TCL routines used for regression +# testing the SQLite library +# +# $Id: tester.tcl,v 1.143 2009/04/09 01:23:49 drh Exp $ + +#------------------------------------------------------------------------- +# The commands provided by the code in this file to help with creating +# test cases are as follows: +# +# Commands to manipulate the db and the file-system at a high level: +# +# is_relative_file +# test_pwd +# get_pwd +# copy_file FROM TO +# delete_file FILENAME +# drop_all_tables ?DB? +# forcecopy FROM TO +# forcedelete FILENAME +# +# Test the capability of the SQLite version built into the interpreter to +# determine if a specific test can be run: +# +# capable EXPR +# ifcapable EXPR +# +# Calulate checksums based on database contents: +# +# dbcksum DB DBNAME +# allcksum ?DB? +# cksum ?DB? +# +# Commands to execute/explain SQL statements: +# +# memdbsql SQL +# stepsql DB SQL +# execsql2 SQL +# explain_no_trace SQL +# explain SQL ?DB? +# catchsql SQL ?DB? +# execsql SQL ?DB? +# +# Commands to run test cases: +# +# do_ioerr_test TESTNAME ARGS... +# crashsql ARGS... +# integrity_check TESTNAME ?DB? +# verify_ex_errcode TESTNAME EXPECTED ?DB? +# do_test TESTNAME SCRIPT EXPECTED +# do_execsql_test TESTNAME SQL EXPECTED +# do_catchsql_test TESTNAME SQL EXPECTED +# +# Commands providing a lower level interface to the global test counters: +# +# set_test_counter COUNTER ?VALUE? +# omit_test TESTNAME REASON ?APPEND? +# fail_test TESTNAME +# incr_ntest +# +# Command run at the end of each test file: +# +# finish_test +# +# Commands to help create test files that run with the "WAL" and other +# permutations (see file permutations.test): +# +# wal_is_wal_mode +# wal_set_journal_mode ?DB? +# wal_check_journal_mode TESTNAME?DB? +# permutation +# presql +# + +# Set the precision of FP arithmatic used by the interpreter. And +# configure SQLite to take database file locks on the page that begins +# 64KB into the database file instead of the one 1GB in. This means +# the code that handles that special case can be tested without creating +# very large database files. +# +set tcl_precision 15 +sqlite3_test_control_pending_byte 0x0010000 + + +# If the pager codec is available, create a wrapper for the [sqlite3] +# command that appends "-key {xyzzy}" to the command line. i.e. this: +# +# sqlite3 db test.db +# +# becomes +# +# sqlite3 db test.db -key {xyzzy} +# +if {[info command sqlite_orig]==""} { + rename sqlite3 sqlite_orig + proc sqlite3 {args} { + if {[llength $args]>=2 && [string index [lindex $args 0] 0]!="-"} { + # This command is opening a new database connection. + # + if {[info exists ::G(perm:sqlite3_args)]} { + set args [concat $args $::G(perm:sqlite3_args)] + } + if {[sqlite_orig -has-codec] && ![info exists ::do_not_use_codec]} { + lappend args -key {xyzzy} + } + + set res [uplevel 1 sqlite_orig $args] + if {[info exists ::G(perm:presql)]} { + [lindex $args 0] eval $::G(perm:presql) + } + if {[info exists ::G(perm:dbconfig)]} { + set ::dbhandle [lindex $args 0] + uplevel #0 $::G(perm:dbconfig) + } + set res + } else { + # This command is not opening a new database connection. Pass the + # arguments through to the C implementation as the are. + # + uplevel 1 sqlite_orig $args + } + } +} + +proc getFileRetries {} { + if {![info exists ::G(file-retries)]} { + # + # NOTE: Return the default number of retries for [file] operations. A + # value of zero or less here means "disabled". + # + return [expr {$::tcl_platform(platform) eq "windows" ? 50 : 0}] + } + return $::G(file-retries) +} + +proc getFileRetryDelay {} { + if {![info exists ::G(file-retry-delay)]} { + # + # NOTE: Return the default number of milliseconds to wait when retrying + # failed [file] operations. A value of zero or less means "do not + # wait". + # + return 100; # TODO: Good default? + } + return $::G(file-retry-delay) +} + +# Return the string representing the name of the current directory. On +# Windows, the result is "normalized" to whatever our parent command shell +# is using to prevent case-mismatch issues. +# +proc get_pwd {} { + if {$::tcl_platform(platform) eq "windows"} { + # + # NOTE: Cannot use [file normalize] here because it would alter the + # case of the result to what Tcl considers canonical, which would + # defeat the purpose of this procedure. + # + return [string map [list \\ /] \ + [string trim [exec -- $::env(ComSpec) /c echo %CD%]]] + } else { + return [pwd] + } +} + +# Copy file $from into $to. This is used because some versions of +# TCL for windows (notably the 8.4.1 binary package shipped with the +# current mingw release) have a broken "file copy" command. +# +proc copy_file {from to} { + do_copy_file false $from $to +} + +proc forcecopy {from to} { + do_copy_file true $from $to +} + +proc do_copy_file {force from to} { + set nRetry [getFileRetries] ;# Maximum number of retries. + set nDelay [getFileRetryDelay] ;# Delay in ms before retrying. + + # On windows, sometimes even a [file copy -force] can fail. The cause is + # usually "tag-alongs" - programs like anti-virus software, automatic backup + # tools and various explorer extensions that keep a file open a little longer + # than we expect, causing the delete to fail. + # + # The solution is to wait a short amount of time before retrying the copy. + # + if {$nRetry > 0} { + for {set i 0} {$i<$nRetry} {incr i} { + set rc [catch { + if {$force} { + file copy -force $from $to + } else { + file copy $from $to + } + } msg] + if {$rc==0} break + if {$nDelay > 0} { after $nDelay } + } + if {$rc} { error $msg } + } else { + if {$force} { + file copy -force $from $to + } else { + file copy $from $to + } + } +} + +# Check if a file name is relative +# +proc is_relative_file { file } { + return [expr {[file pathtype $file] != "absolute"}] +} + +# If the VFS supports using the current directory, returns [pwd]; +# otherwise, it returns only the provided suffix string (which is +# empty by default). +# +proc test_pwd { args } { + if {[llength $args] > 0} { + set suffix1 [lindex $args 0] + if {[llength $args] > 1} { + set suffix2 [lindex $args 1] + } else { + set suffix2 $suffix1 + } + } else { + set suffix1 ""; set suffix2 "" + } + ifcapable curdir { + return "[get_pwd]$suffix1" + } else { + return $suffix2 + } +} + +# Delete a file or directory +# +proc delete_file {args} { + do_delete_file false {*}$args +} + +proc forcedelete {args} { + do_delete_file true {*}$args +} + +proc do_delete_file {force args} { + set nRetry [getFileRetries] ;# Maximum number of retries. + set nDelay [getFileRetryDelay] ;# Delay in ms before retrying. + + foreach filename $args { + # On windows, sometimes even a [file delete -force] can fail just after + # a file is closed. The cause is usually "tag-alongs" - programs like + # anti-virus software, automatic backup tools and various explorer + # extensions that keep a file open a little longer than we expect, causing + # the delete to fail. + # + # The solution is to wait a short amount of time before retrying the + # delete. + # + if {$nRetry > 0} { + for {set i 0} {$i<$nRetry} {incr i} { + set rc [catch { + if {$force} { + file delete -force $filename + } else { + file delete $filename + } + } msg] + if {$rc==0} break + if {$nDelay > 0} { after $nDelay } + } + if {$rc} { error $msg } + } else { + if {$force} { + file delete -force $filename + } else { + file delete $filename + } + } + } +} + +if {$::tcl_platform(platform) eq "windows"} { + proc do_remove_win32_dir {args} { + set nRetry [getFileRetries] ;# Maximum number of retries. + set nDelay [getFileRetryDelay] ;# Delay in ms before retrying. + + foreach dirName $args { + # On windows, sometimes even a [remove_win32_dir] can fail just after + # a directory is emptied. The cause is usually "tag-alongs" - programs + # like anti-virus software, automatic backup tools and various explorer + # extensions that keep a file open a little longer than we expect, + # causing the delete to fail. + # + # The solution is to wait a short amount of time before retrying the + # removal. + # + if {$nRetry > 0} { + for {set i 0} {$i < $nRetry} {incr i} { + set rc [catch { + remove_win32_dir $dirName + } msg] + if {$rc == 0} break + if {$nDelay > 0} { after $nDelay } + } + if {$rc} { error $msg } + } else { + remove_win32_dir $dirName + } + } + } + + proc do_delete_win32_file {args} { + set nRetry [getFileRetries] ;# Maximum number of retries. + set nDelay [getFileRetryDelay] ;# Delay in ms before retrying. + + foreach fileName $args { + # On windows, sometimes even a [delete_win32_file] can fail just after + # a file is closed. The cause is usually "tag-alongs" - programs like + # anti-virus software, automatic backup tools and various explorer + # extensions that keep a file open a little longer than we expect, + # causing the delete to fail. + # + # The solution is to wait a short amount of time before retrying the + # delete. + # + if {$nRetry > 0} { + for {set i 0} {$i < $nRetry} {incr i} { + set rc [catch { + delete_win32_file $fileName + } msg] + if {$rc == 0} break + if {$nDelay > 0} { after $nDelay } + } + if {$rc} { error $msg } + } else { + delete_win32_file $fileName + } + } + } +} + +proc execpresql {handle args} { + trace remove execution $handle enter [list execpresql $handle] + if {[info exists ::G(perm:presql)]} { + $handle eval $::G(perm:presql) + } +} + +# This command should be called after loading tester.tcl from within +# all test scripts that are incompatible with encryption codecs. +# +proc do_not_use_codec {} { + set ::do_not_use_codec 1 + reset_db +} + +# The following block only runs the first time this file is sourced. It +# does not run in slave interpreters (since the ::cmdlinearg array is +# populated before the test script is run in slave interpreters). +# +if {[info exists cmdlinearg]==0} { + + # Parse any options specified in the $argv array. This script accepts the + # following options: + # + # --pause + # --soft-heap-limit=NN + # --maxerror=NN + # --malloctrace=N + # --backtrace=N + # --binarylog=N + # --soak=N + # --file-retries=N + # --file-retry-delay=N + # --start=[$permutation:]$testfile + # --match=$pattern + # + set cmdlinearg(soft-heap-limit) 0 + set cmdlinearg(maxerror) 1000 + set cmdlinearg(malloctrace) 0 + set cmdlinearg(backtrace) 10 + set cmdlinearg(binarylog) 0 + set cmdlinearg(soak) 0 + set cmdlinearg(file-retries) 0 + set cmdlinearg(file-retry-delay) 0 + set cmdlinearg(start) "" + set cmdlinearg(match) "" + + set leftover [list] + foreach a $argv { + switch -regexp -- $a { + {^-+pause$} { + # Wait for user input before continuing. This is to give the user an + # opportunity to connect profiling tools to the process. + puts -nonewline "Press RETURN to begin..." + flush stdout + gets stdin + } + {^-+soft-heap-limit=.+$} { + foreach {dummy cmdlinearg(soft-heap-limit)} [split $a =] break + } + {^-+maxerror=.+$} { + foreach {dummy cmdlinearg(maxerror)} [split $a =] break + } + {^-+malloctrace=.+$} { + foreach {dummy cmdlinearg(malloctrace)} [split $a =] break + if {$cmdlinearg(malloctrace)} { + sqlite3_memdebug_log start + } + } + {^-+backtrace=.+$} { + foreach {dummy cmdlinearg(backtrace)} [split $a =] break + sqlite3_memdebug_backtrace $value + } + {^-+binarylog=.+$} { + foreach {dummy cmdlinearg(binarylog)} [split $a =] break + } + {^-+soak=.+$} { + foreach {dummy cmdlinearg(soak)} [split $a =] break + set ::G(issoak) $cmdlinearg(soak) + } + {^-+file-retries=.+$} { + foreach {dummy cmdlinearg(file-retries)} [split $a =] break + set ::G(file-retries) $cmdlinearg(file-retries) + } + {^-+file-retry-delay=.+$} { + foreach {dummy cmdlinearg(file-retry-delay)} [split $a =] break + set ::G(file-retry-delay) $cmdlinearg(file-retry-delay) + } + {^-+start=.+$} { + foreach {dummy cmdlinearg(start)} [split $a =] break + + set ::G(start:file) $cmdlinearg(start) + if {[regexp {(.*):(.*)} $cmdlinearg(start) -> s.perm s.file]} { + set ::G(start:permutation) ${s.perm} + set ::G(start:file) ${s.file} + } + if {$::G(start:file) == ""} {unset ::G(start:file)} + } + {^-+match=.+$} { + foreach {dummy cmdlinearg(match)} [split $a =] break + + set ::G(match) $cmdlinearg(match) + if {$::G(match) == ""} {unset ::G(match)} + } + default { + lappend leftover $a + } + } + } + set argv $leftover + + # Install the malloc layer used to inject OOM errors. And the 'automatic' + # extensions. This only needs to be done once for the process. + # + sqlite3_shutdown + install_malloc_faultsim 1 + sqlite3_initialize + autoinstall_test_functions + + # If the --binarylog option was specified, create the logging VFS. This + # call installs the new VFS as the default for all SQLite connections. + # + if {$cmdlinearg(binarylog)} { + vfslog new binarylog {} vfslog.bin + } + + # Set the backtrace depth, if malloc tracing is enabled. + # + if {$cmdlinearg(malloctrace)} { + sqlite3_memdebug_backtrace $cmdlinearg(backtrace) + } +} + +# Update the soft-heap-limit each time this script is run. In that +# way if an individual test file changes the soft-heap-limit, it +# will be reset at the start of the next test file. +# +sqlite3_soft_heap_limit $cmdlinearg(soft-heap-limit) + +# Create a test database +# +proc reset_db {} { + catch {db close} + forcedelete test.db + forcedelete test.db-journal + forcedelete test.db-wal + sqlite3 db ./test.db + set ::DB [sqlite3_connection_pointer db] + if {[info exists ::SETUP_SQL]} { + db eval $::SETUP_SQL + } +} +reset_db + +# Abort early if this script has been run before. +# +if {[info exists TC(count)]} return + +# Make sure memory statistics are enabled. +# +sqlite3_config_memstatus 1 + +# Initialize the test counters and set up commands to access them. +# Or, if this is a slave interpreter, set up aliases to write the +# counters in the parent interpreter. +# +if {0==[info exists ::SLAVE]} { + set TC(errors) 0 + set TC(count) 0 + set TC(fail_list) [list] + set TC(omit_list) [list] + set TC(warn_list) [list] + + proc set_test_counter {counter args} { + if {[llength $args]} { + set ::TC($counter) [lindex $args 0] + } + set ::TC($counter) + } +} + +# Record the fact that a sequence of tests were omitted. +# +proc omit_test {name reason {append 1}} { + set omitList [set_test_counter omit_list] + if {$append} { + lappend omitList [list $name $reason] + } + set_test_counter omit_list $omitList +} + +# Record the fact that a test failed. +# +proc fail_test {name} { + set f [set_test_counter fail_list] + lappend f $name + set_test_counter fail_list $f + set_test_counter errors [expr [set_test_counter errors] + 1] + + set nFail [set_test_counter errors] + if {$nFail>=$::cmdlinearg(maxerror)} { + puts "*** Giving up..." + finalize_testing + } +} + +# Remember a warning message to be displayed at the conclusion of all testing +# +proc warning {msg {append 1}} { + puts "Warning: $msg" + set warnList [set_test_counter warn_list] + if {$append} { + lappend warnList $msg + } + set_test_counter warn_list $warnList +} + + +# Increment the number of tests run +# +proc incr_ntest {} { + set_test_counter count [expr [set_test_counter count] + 1] +} + + +# Invoke the do_test procedure to run a single test +# +proc do_test {name cmd expected} { + global argv cmdlinearg + + fix_testname name + + sqlite3_memdebug_settitle $name + +# if {[llength $argv]==0} { +# set go 1 +# } else { +# set go 0 +# foreach pattern $argv { +# if {[string match $pattern $name]} { +# set go 1 +# break +# } +# } +# } + + if {[info exists ::G(perm:prefix)]} { + set name "$::G(perm:prefix)$name" + } + + incr_ntest + puts -nonewline $name... + flush stdout + + if {![info exists ::G(match)] || [string match $::G(match) $name]} { + if {[catch {uplevel #0 "$cmd;\n"} result]} { + puts "\nError: $result" + fail_test $name + } else { + if {[regexp {^~?/.*/$} $expected]} { + # "expected" is of the form "/PATTERN/" then the result if correct if + # regular expression PATTERN matches the result. "~/PATTERN/" means + # the regular expression must not match. + if {[string index $expected 0]=="~"} { + set re [string map {# {[-0-9.]+}} [string range $expected 2 end-1]] + set ok [expr {![regexp $re $result]}] + } else { + set re [string map {# {[-0-9.]+}} [string range $expected 1 end-1]] + set ok [regexp $re $result] + } + } elseif {[regexp {^~?\*.*\*$} $expected]} { + # "expected" is of the form "*GLOB*" then the result if correct if + # glob pattern GLOB matches the result. "~/GLOB/" means + # the glob must not match. + if {[string index $expected 0]=="~"} { + set e [string range $expected 1 end] + set ok [expr {![string match $e $result]}] + } else { + set ok [string match $expected $result] + } + } else { + set ok [expr {[string compare $result $expected]==0}] + } + if {!$ok} { + # if {![info exists ::testprefix] || $::testprefix eq ""} { + # error "no test prefix" + # } + puts "\nExpected: \[$expected\]\n Got: \[$result\]" + fail_test $name + } else { + puts " Ok" + } + } + } else { + puts " Omitted" + omit_test $name "pattern mismatch" 0 + } + flush stdout +} + +proc catchcmd {db {cmd ""}} { + global CLI + set out [open cmds.txt w] + puts $out $cmd + close $out + set line "exec $CLI $db < cmds.txt" + set rc [catch { eval $line } msg] + list $rc $msg +} + +proc filepath_normalize {p} { + # test cases should be written to assume "unix"-like file paths + if {$::tcl_platform(platform)!="unix"} { + # lreverse*2 as a hack to remove any unneeded {} after the string map + lreverse [lreverse [string map {\\ /} [regsub -nocase -all {[a-z]:[/\\]+} $p {/}]]] + } { + set p + } +} +proc do_filepath_test {name cmd expected} { + uplevel [list do_test $name [ + subst -nocommands { filepath_normalize [ $cmd ] } + ] [filepath_normalize $expected]] +} + +proc realnum_normalize {r} { + # different TCL versions display floating point values differently. + string map {1.#INF inf Inf inf .0e e} [regsub -all {(e[+-])0+} $r {\1}] +} +proc do_realnum_test {name cmd expected} { + uplevel [list do_test $name [ + subst -nocommands { realnum_normalize [ $cmd ] } + ] [realnum_normalize $expected]] +} + +proc fix_testname {varname} { + upvar $varname testname + if {[info exists ::testprefix] + && [string is digit [string range $testname 0 0]] + } { + set testname "${::testprefix}-$testname" + } +} + +proc do_execsql_test {testname sql {result {}}} { + fix_testname testname + uplevel do_test [list $testname] [list "execsql {$sql}"] [list [list {*}$result]] +} +proc do_catchsql_test {testname sql result} { + fix_testname testname + uplevel do_test [list $testname] [list "catchsql {$sql}"] [list $result] +} +proc do_eqp_test {name sql res} { + uplevel do_execsql_test $name [list "EXPLAIN QUERY PLAN $sql"] [list $res] +} + +#------------------------------------------------------------------------- +# Usage: do_select_tests PREFIX ?SWITCHES? TESTLIST +# +# Where switches are: +# +# -errorformat FMTSTRING +# -count +# -query SQL +# -tclquery TCL +# -repair TCL +# +proc do_select_tests {prefix args} { + + set testlist [lindex $args end] + set switches [lrange $args 0 end-1] + + set errfmt "" + set countonly 0 + set tclquery "" + set repair "" + + for {set i 0} {$i < [llength $switches]} {incr i} { + set s [lindex $switches $i] + set n [string length $s] + if {$n>=2 && [string equal -length $n $s "-query"]} { + set tclquery [list execsql [lindex $switches [incr i]]] + } elseif {$n>=2 && [string equal -length $n $s "-tclquery"]} { + set tclquery [lindex $switches [incr i]] + } elseif {$n>=2 && [string equal -length $n $s "-errorformat"]} { + set errfmt [lindex $switches [incr i]] + } elseif {$n>=2 && [string equal -length $n $s "-repair"]} { + set repair [lindex $switches [incr i]] + } elseif {$n>=2 && [string equal -length $n $s "-count"]} { + set countonly 1 + } else { + error "unknown switch: $s" + } + } + + if {$countonly && $errfmt!=""} { + error "Cannot use -count and -errorformat together" + } + set nTestlist [llength $testlist] + if {$nTestlist%3 || $nTestlist==0 } { + error "SELECT test list contains [llength $testlist] elements" + } + + eval $repair + foreach {tn sql res} $testlist { + if {$tclquery != ""} { + execsql $sql + uplevel do_test ${prefix}.$tn [list $tclquery] [list [list {*}$res]] + } elseif {$countonly} { + set nRow 0 + db eval $sql {incr nRow} + uplevel do_test ${prefix}.$tn [list [list set {} $nRow]] [list $res] + } elseif {$errfmt==""} { + uplevel do_execsql_test ${prefix}.${tn} [list $sql] [list [list {*}$res]] + } else { + set res [list 1 [string trim [format $errfmt {*}$res]]] + uplevel do_catchsql_test ${prefix}.${tn} [list $sql] [list $res] + } + eval $repair + } + +} + +proc delete_all_data {} { + db eval {SELECT tbl_name AS t FROM sqlite_master WHERE type = 'table'} { + db eval "DELETE FROM '[string map {' ''} $t]'" + } +} + +# Run an SQL script. +# Return the number of microseconds per statement. +# +proc speed_trial {name numstmt units sql} { + puts -nonewline [format {%-21.21s } $name...] + flush stdout + set speed [time {sqlite3_exec_nr db $sql}] + set tm [lindex $speed 0] + if {$tm == 0} { + set rate [format %20s "many"] + } else { + set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]] + } + set u2 $units/s + puts [format {%12d uS %s %s} $tm $rate $u2] + global total_time + set total_time [expr {$total_time+$tm}] + lappend ::speed_trial_times $name $tm +} +proc speed_trial_tcl {name numstmt units script} { + puts -nonewline [format {%-21.21s } $name...] + flush stdout + set speed [time {eval $script}] + set tm [lindex $speed 0] + if {$tm == 0} { + set rate [format %20s "many"] + } else { + set rate [format %20.5f [expr {1000000.0*$numstmt/$tm}]] + } + set u2 $units/s + puts [format {%12d uS %s %s} $tm $rate $u2] + global total_time + set total_time [expr {$total_time+$tm}] + lappend ::speed_trial_times $name $tm +} +proc speed_trial_init {name} { + global total_time + set total_time 0 + set ::speed_trial_times [list] + sqlite3 versdb :memory: + set vers [versdb one {SELECT sqlite_source_id()}] + versdb close + puts "SQLite $vers" +} +proc speed_trial_summary {name} { + global total_time + puts [format {%-21.21s %12d uS TOTAL} $name $total_time] + + if { 0 } { + sqlite3 versdb :memory: + set vers [lindex [versdb one {SELECT sqlite_source_id()}] 0] + versdb close + puts "CREATE TABLE IF NOT EXISTS time(version, script, test, us);" + foreach {test us} $::speed_trial_times { + puts "INSERT INTO time VALUES('$vers', '$name', '$test', $us);" + } + } +} + +# Run this routine last +# +proc finish_test {} { + catch {db close} + catch {db2 close} + catch {db3 close} + if {0==[info exists ::SLAVE]} { finalize_testing } +} +proc finalize_testing {} { + global sqlite_open_file_count + + set omitList [set_test_counter omit_list] + + catch {db close} + catch {db2 close} + catch {db3 close} + + vfs_unlink_test + sqlite3 db {} + # sqlite3_clear_tsd_memdebug + db close + sqlite3_reset_auto_extension + + sqlite3_soft_heap_limit 0 + set nTest [incr_ntest] + set nErr [set_test_counter errors] + + set nKnown 0 + if {[file readable known-problems.txt]} { + set fd [open known-problems.txt] + set content [read $fd] + close $fd + foreach x $content {set known_error($x) 1} + foreach x [set_test_counter fail_list] { + if {[info exists known_error($x)]} {incr nKnown} + } + } + if {$nKnown>0} { + puts "[expr {$nErr-$nKnown}] new errors and $nKnown known errors\ + out of $nTest tests" + } else { + puts "$nErr errors out of $nTest tests" + } + if {$nErr>$nKnown} { + puts -nonewline "Failures on these tests:" + foreach x [set_test_counter fail_list] { + if {![info exists known_error($x)]} {puts -nonewline " $x"} + } + puts "" + } + foreach warning [set_test_counter warn_list] { + puts "Warning: $warning" + } + run_thread_tests 1 + if {[llength $omitList]>0} { + puts "Omitted test cases:" + set prec {} + foreach {rec} [lsort $omitList] { + if {$rec==$prec} continue + set prec $rec + puts [format { %-12s %s} [lindex $rec 0] [lindex $rec 1]] + } + } + if {$nErr>0 && ![working_64bit_int]} { + puts "******************************************************************" + puts "N.B.: The version of TCL that you used to build this test harness" + puts "is defective in that it does not support 64-bit integers. Some or" + puts "all of the test failures above might be a result from this defect" + puts "in your TCL build." + puts "******************************************************************" + } + if {$::cmdlinearg(binarylog)} { + vfslog finalize binarylog + } + if {$sqlite_open_file_count} { + puts "$sqlite_open_file_count files were left open" + incr nErr + } + if {[lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1]>0 || + [sqlite3_memory_used]>0} { + puts "Unfreed memory: [sqlite3_memory_used] bytes in\ + [lindex [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] 1] allocations" + incr nErr + ifcapable memdebug||mem5||(mem3&&debug) { + puts "Writing unfreed memory log to \"./memleak.txt\"" + sqlite3_memdebug_dump ./memleak.txt + } + } else { + puts "All memory allocations freed - no leaks" + ifcapable memdebug||mem5 { + sqlite3_memdebug_dump ./memusage.txt + } + } + show_memstats + puts "Maximum memory usage: [sqlite3_memory_highwater 1] bytes" + puts "Current memory usage: [sqlite3_memory_highwater] bytes" + if {[info commands sqlite3_memdebug_malloc_count] ne ""} { + puts "Number of malloc() : [sqlite3_memdebug_malloc_count] calls" + } + if {$::cmdlinearg(malloctrace)} { + puts "Writing mallocs.sql..." + memdebug_log_sql + sqlite3_memdebug_log stop + sqlite3_memdebug_log clear + + if {[sqlite3_memory_used]>0} { + puts "Writing leaks.sql..." + sqlite3_memdebug_log sync + memdebug_log_sql leaks.sql + } + } + foreach f [glob -nocomplain test.db-*-journal] { + forcedelete $f + } + foreach f [glob -nocomplain test.db-mj*] { + forcedelete $f + } + exit [expr {$nErr>0}] +} + +# Display memory statistics for analysis and debugging purposes. +# +proc show_memstats {} { + set x [sqlite3_status SQLITE_STATUS_MEMORY_USED 0] + set y [sqlite3_status SQLITE_STATUS_MALLOC_SIZE 0] + set val [format {now %10d max %10d max-size %10d} \ + [lindex $x 1] [lindex $x 2] [lindex $y 2]] + puts "Memory used: $val" + set x [sqlite3_status SQLITE_STATUS_MALLOC_COUNT 0] + set val [format {now %10d max %10d} [lindex $x 1] [lindex $x 2]] + puts "Allocation count: $val" + set x [sqlite3_status SQLITE_STATUS_PAGECACHE_USED 0] + set y [sqlite3_status SQLITE_STATUS_PAGECACHE_SIZE 0] + set val [format {now %10d max %10d max-size %10d} \ + [lindex $x 1] [lindex $x 2] [lindex $y 2]] + puts "Page-cache used: $val" + set x [sqlite3_status SQLITE_STATUS_PAGECACHE_OVERFLOW 0] + set val [format {now %10d max %10d} [lindex $x 1] [lindex $x 2]] + puts "Page-cache overflow: $val" + set x [sqlite3_status SQLITE_STATUS_SCRATCH_USED 0] + set val [format {now %10d max %10d} [lindex $x 1] [lindex $x 2]] + puts "Scratch memory used: $val" + set x [sqlite3_status SQLITE_STATUS_SCRATCH_OVERFLOW 0] + set y [sqlite3_status SQLITE_STATUS_SCRATCH_SIZE 0] + set val [format {now %10d max %10d max-size %10d} \ + [lindex $x 1] [lindex $x 2] [lindex $y 2]] + puts "Scratch overflow: $val" + ifcapable yytrackmaxstackdepth { + set x [sqlite3_status SQLITE_STATUS_PARSER_STACK 0] + set val [format { max %10d} [lindex $x 2]] + puts "Parser stack depth: $val" + } +} + +# A procedure to execute SQL +# +proc execsql {sql {db db}} { + # puts "SQL = $sql" + uplevel [list $db eval $sql] +} + +# Execute SQL and catch exceptions. +# +proc catchsql {sql {db db}} { + # puts "SQL = $sql" + set r [catch [list uplevel [list $db eval $sql]] msg] + lappend r $msg + return $r +} + +# Do an VDBE code dump on the SQL given +# +proc explain {sql {db db}} { + puts "" + puts "addr opcode p1 p2 p3 p4 p5 #" + puts "---- ------------ ------ ------ ------ --------------- -- -" + $db eval "explain $sql" {} { + puts [format {%-4d %-12.12s %-6d %-6d %-6d % -17s %s %s} \ + $addr $opcode $p1 $p2 $p3 $p4 $p5 $comment + ] + } +} + +# Show the VDBE program for an SQL statement but omit the Trace +# opcode at the beginning. This procedure can be used to prove +# that different SQL statements generate exactly the same VDBE code. +# +proc explain_no_trace {sql} { + set tr [db eval "EXPLAIN $sql"] + return [lrange $tr 7 end] +} + +# Another procedure to execute SQL. This one includes the field +# names in the returned list. +# +proc execsql2 {sql} { + set result {} + db eval $sql data { + foreach f $data(*) { + lappend result $f $data($f) + } + } + return $result +} + +# Use a temporary in-memory database to execute SQL statements +# +proc memdbsql {sql} { + sqlite3 memdb :memory: + set result [memdb eval $sql] + memdb close + return $result +} + +# Use the non-callback API to execute multiple SQL statements +# +proc stepsql {dbptr sql} { + set sql [string trim $sql] + set r 0 + while {[string length $sql]>0} { + if {[catch {sqlite3_prepare $dbptr $sql -1 sqltail} vm]} { + return [list 1 $vm] + } + set sql [string trim $sqltail] +# while {[sqlite_step $vm N VAL COL]=="SQLITE_ROW"} { +# foreach v $VAL {lappend r $v} +# } + while {[sqlite3_step $vm]=="SQLITE_ROW"} { + for {set i 0} {$i<[sqlite3_data_count $vm]} {incr i} { + lappend r [sqlite3_column_text $vm $i] + } + } + if {[catch {sqlite3_finalize $vm} errmsg]} { + return [list 1 $errmsg] + } + } + return $r +} + +# Do an integrity check of the entire database +# +proc integrity_check {name {db db}} { + ifcapable integrityck { + do_test $name [list execsql {PRAGMA integrity_check} $db] {ok} + } +} + +# Check the extended error code +# +proc verify_ex_errcode {name expected {db db}} { + do_test $name [list sqlite3_extended_errcode $db] $expected +} + + +# Return true if the SQL statement passed as the second argument uses a +# statement transaction. +# +proc sql_uses_stmt {db sql} { + set stmt [sqlite3_prepare $db $sql -1 dummy] + set uses [uses_stmt_journal $stmt] + sqlite3_finalize $stmt + return $uses +} + +proc fix_ifcapable_expr {expr} { + set ret "" + set state 0 + for {set i 0} {$i < [string length $expr]} {incr i} { + set char [string range $expr $i $i] + set newstate [expr {[string is alnum $char] || $char eq "_"}] + if {$newstate && !$state} { + append ret {$::sqlite_options(} + } + if {!$newstate && $state} { + append ret ) + } + append ret $char + set state $newstate + } + if {$state} {append ret )} + return $ret +} + +# Returns non-zero if the capabilities are present; zero otherwise. +# +proc capable {expr} { + set e [fix_ifcapable_expr $expr]; return [expr ($e)] +} + +# Evaluate a boolean expression of capabilities. If true, execute the +# code. Omit the code if false. +# +proc ifcapable {expr code {else ""} {elsecode ""}} { + #regsub -all {[a-z_0-9]+} $expr {$::sqlite_options(&)} e2 + set e2 [fix_ifcapable_expr $expr] + if ($e2) { + set c [catch {uplevel 1 $code} r] + } else { + set c [catch {uplevel 1 $elsecode} r] + } + return -code $c $r +} + +# This proc execs a seperate process that crashes midway through executing +# the SQL script $sql on database test.db. +# +# The crash occurs during a sync() of file $crashfile. When the crash +# occurs a random subset of all unsynced writes made by the process are +# written into the files on disk. Argument $crashdelay indicates the +# number of file syncs to wait before crashing. +# +# The return value is a list of two elements. The first element is a +# boolean, indicating whether or not the process actually crashed or +# reported some other error. The second element in the returned list is the +# error message. This is "child process exited abnormally" if the crash +# occurred. +# +# crashsql -delay CRASHDELAY -file CRASHFILE ?-blocksize BLOCKSIZE? $sql +# +proc crashsql {args} { + + set blocksize "" + set crashdelay 1 + set prngseed 0 + set tclbody {} + set crashfile "" + set dc "" + set sql [lindex $args end] + + for {set ii 0} {$ii < [llength $args]-1} {incr ii 2} { + set z [lindex $args $ii] + set n [string length $z] + set z2 [lindex $args [expr $ii+1]] + + if {$n>1 && [string first $z -delay]==0} {set crashdelay $z2} \ + elseif {$n>1 && [string first $z -seed]==0} {set prngseed $z2} \ + elseif {$n>1 && [string first $z -file]==0} {set crashfile $z2} \ + elseif {$n>1 && [string first $z -tclbody]==0} {set tclbody $z2} \ + elseif {$n>1 && [string first $z -blocksize]==0} {set blocksize "-s $z2" } \ + elseif {$n>1 && [string first $z -characteristics]==0} {set dc "-c {$z2}" } \ + else { error "Unrecognized option: $z" } + } + + if {$crashfile eq ""} { + error "Compulsory option -file missing" + } + + # $crashfile gets compared to the native filename in + # cfSync(), which can be different then what TCL uses by + # default, so here we force it to the "nativename" format. + set cfile [string map {\\ \\\\} [file nativename [file join [get_pwd] $crashfile]]] + + set f [open crash.tcl w] + puts $f "sqlite3_crash_enable 1" + puts $f "sqlite3_crashparams $blocksize $dc $crashdelay $cfile" + puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte" + puts $f "sqlite3 db test.db -vfs crash" + + # This block sets the cache size of the main database to 10 + # pages. This is done in case the build is configured to omit + # "PRAGMA cache_size". + puts $f {db eval {SELECT * FROM sqlite_master;}} + puts $f {set bt [btree_from_db db]} + puts $f {btree_set_cache_size $bt 10} + if {$prngseed} { + set seed [expr {$prngseed%10007+1}] + # puts seed=$seed + puts $f "db eval {SELECT randomblob($seed)}" + } + + if {[string length $tclbody]>0} { + puts $f $tclbody + } + if {[string length $sql]>0} { + puts $f "db eval {" + puts $f "$sql" + puts $f "}" + } + close $f + set r [catch { + exec [info nameofexec] crash.tcl >@stdout + } msg] + + # Windows/ActiveState TCL returns a slightly different + # error message. We map that to the expected message + # so that we don't have to change all of the test + # cases. + if {$::tcl_platform(platform)=="windows"} { + if {$msg=="child killed: unknown signal"} { + set msg "child process exited abnormally" + } + } + + lappend r $msg +} + +proc run_ioerr_prep {} { + set ::sqlite_io_error_pending 0 + catch {db close} + catch {db2 close} + catch {forcedelete test.db} + catch {forcedelete test.db-journal} + catch {forcedelete test2.db} + catch {forcedelete test2.db-journal} + set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db] + sqlite3_extended_result_codes $::DB $::ioerropts(-erc) + if {[info exists ::ioerropts(-tclprep)]} { + eval $::ioerropts(-tclprep) + } + if {[info exists ::ioerropts(-sqlprep)]} { + execsql $::ioerropts(-sqlprep) + } + expr 0 +} + +# Usage: do_ioerr_test +# +# This proc is used to implement test cases that check that IO errors +# are correctly handled. The first argument, , is an integer +# used to name the tests executed by this proc. Options are as follows: +# +# -tclprep TCL script to run to prepare test. +# -sqlprep SQL script to run to prepare test. +# -tclbody TCL script to run with IO error simulation. +# -sqlbody TCL script to run with IO error simulation. +# -exclude List of 'N' values not to test. +# -erc Use extended result codes +# -persist Make simulated I/O errors persistent +# -start Value of 'N' to begin with (default 1) +# +# -cksum Boolean. If true, test that the database does +# not change during the execution of the test case. +# +proc do_ioerr_test {testname args} { + + set ::ioerropts(-start) 1 + set ::ioerropts(-cksum) 0 + set ::ioerropts(-erc) 0 + set ::ioerropts(-count) 100000000 + set ::ioerropts(-persist) 1 + set ::ioerropts(-ckrefcount) 0 + set ::ioerropts(-restoreprng) 1 + array set ::ioerropts $args + + # TEMPORARY: For 3.5.9, disable testing of extended result codes. There are + # a couple of obscure IO errors that do not return them. + set ::ioerropts(-erc) 0 + + # Create a single TCL script from the TCL and SQL specified + # as the body of the test. + set ::ioerrorbody {} + if {[info exists ::ioerropts(-tclbody)]} { + append ::ioerrorbody "$::ioerropts(-tclbody)\n" + } + if {[info exists ::ioerropts(-sqlbody)]} { + append ::ioerrorbody "db eval {$::ioerropts(-sqlbody)}" + } + + save_prng_state + if {$::ioerropts(-cksum)} { + run_ioerr_prep + eval $::ioerrorbody + set ::goodcksum [cksum] + } + + set ::go 1 + #reset_prng_state + for {set n $::ioerropts(-start)} {$::go} {incr n} { + set ::TN $n + incr ::ioerropts(-count) -1 + if {$::ioerropts(-count)<0} break + + # Skip this IO error if it was specified with the "-exclude" option. + if {[info exists ::ioerropts(-exclude)]} { + if {[lsearch $::ioerropts(-exclude) $n]!=-1} continue + } + if {$::ioerropts(-restoreprng)} { + restore_prng_state + } + + # Delete the files test.db and test2.db, then execute the TCL and + # SQL (in that order) to prepare for the test case. + do_test $testname.$n.1 { + run_ioerr_prep + } {0} + + # Read the 'checksum' of the database. + if {$::ioerropts(-cksum)} { + set ::checksum [cksum] + } + + # Set the Nth IO error to fail. + do_test $testname.$n.2 [subst { + set ::sqlite_io_error_persist $::ioerropts(-persist) + set ::sqlite_io_error_pending $n + }] $n + + # Execute the TCL script created for the body of this test. If + # at least N IO operations performed by SQLite as a result of + # the script, the Nth will fail. + do_test $testname.$n.3 { + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_hardhit 0 + set r [catch $::ioerrorbody msg] + set ::errseen $r + set rc [sqlite3_errcode $::DB] + if {$::ioerropts(-erc)} { + # If we are in extended result code mode, make sure all of the + # IOERRs we get back really do have their extended code values. + # If an extended result code is returned, the sqlite3_errcode + # TCLcommand will return a string of the form: SQLITE_IOERR+nnnn + # where nnnn is a number + if {[regexp {^SQLITE_IOERR} $rc] && ![regexp {IOERR\+\d} $rc]} { + return $rc + } + } else { + # If we are not in extended result code mode, make sure no + # extended error codes are returned. + if {[regexp {\+\d} $rc]} { + return $rc + } + } + # The test repeats as long as $::go is non-zero. $::go starts out + # as 1. When a test runs to completion without hitting an I/O + # error, that means there is no point in continuing with this test + # case so set $::go to zero. + # + if {$::sqlite_io_error_pending>0} { + set ::go 0 + set q 0 + set ::sqlite_io_error_pending 0 + } else { + set q 1 + } + + set s [expr $::sqlite_io_error_hit==0] + if {$::sqlite_io_error_hit>$::sqlite_io_error_hardhit && $r==0} { + set r 1 + } + set ::sqlite_io_error_hit 0 + + # One of two things must have happened. either + # 1. We never hit the IO error and the SQL returned OK + # 2. An IO error was hit and the SQL failed + # + #puts "s=$s r=$r q=$q" + expr { ($s && !$r && !$q) || (!$s && $r && $q) } + } {1} + + set ::sqlite_io_error_hit 0 + set ::sqlite_io_error_pending 0 + + # Check that no page references were leaked. There should be + # a single reference if there is still an active transaction, + # or zero otherwise. + # + # UPDATE: If the IO error occurs after a 'BEGIN' but before any + # locks are established on database files (i.e. if the error + # occurs while attempting to detect a hot-journal file), then + # there may 0 page references and an active transaction according + # to [sqlite3_get_autocommit]. + # + if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-ckrefcount)} { + do_test $testname.$n.4 { + set bt [btree_from_db db] + db_enter db + array set stats [btree_pager_stats $bt] + db_leave db + set nRef $stats(ref) + expr {$nRef == 0 || ([sqlite3_get_autocommit db]==0 && $nRef == 1)} + } {1} + } + + # If there is an open database handle and no open transaction, + # and the pager is not running in exclusive-locking mode, + # check that the pager is in "unlocked" state. Theoretically, + # if a call to xUnlock() failed due to an IO error the underlying + # file may still be locked. + # + ifcapable pragma { + if { [info commands db] ne "" + && $::ioerropts(-ckrefcount) + && [db one {pragma locking_mode}] eq "normal" + && [sqlite3_get_autocommit db] + } { + do_test $testname.$n.5 { + set bt [btree_from_db db] + db_enter db + array set stats [btree_pager_stats $bt] + db_leave db + set stats(state) + } 0 + } + } + + # If an IO error occurred, then the checksum of the database should + # be the same as before the script that caused the IO error was run. + # + if {$::go && $::sqlite_io_error_hardhit && $::ioerropts(-cksum)} { + do_test $testname.$n.6 { + catch {db close} + catch {db2 close} + set ::DB [sqlite3 db test.db; sqlite3_connection_pointer db] + set nowcksum [cksum] + set res [expr {$nowcksum==$::checksum || $nowcksum==$::goodcksum}] + if {$res==0} { + puts "now=$nowcksum" + puts "the=$::checksum" + puts "fwd=$::goodcksum" + } + set res + } 1 + } + + set ::sqlite_io_error_hardhit 0 + set ::sqlite_io_error_pending 0 + if {[info exists ::ioerropts(-cleanup)]} { + catch $::ioerropts(-cleanup) + } + } + set ::sqlite_io_error_pending 0 + set ::sqlite_io_error_persist 0 + unset ::ioerropts +} + +# Return a checksum based on the contents of the main database associated +# with connection $db +# +proc cksum {{db db}} { + set txt [$db eval { + SELECT name, type, sql FROM sqlite_master order by name + }]\n + foreach tbl [$db eval { + SELECT name FROM sqlite_master WHERE type='table' order by name + }] { + append txt [$db eval "SELECT * FROM $tbl"]\n + } + foreach prag {default_synchronous default_cache_size} { + append txt $prag-[$db eval "PRAGMA $prag"]\n + } + set cksum [string length $txt]-[md5 $txt] + # puts $cksum-[file size test.db] + return $cksum +} + +# Generate a checksum based on the contents of the main and temp tables +# database $db. If the checksum of two databases is the same, and the +# integrity-check passes for both, the two databases are identical. +# +proc allcksum {{db db}} { + set ret [list] + ifcapable tempdb { + set sql { + SELECT name FROM sqlite_master WHERE type = 'table' UNION + SELECT name FROM sqlite_temp_master WHERE type = 'table' UNION + SELECT 'sqlite_master' UNION + SELECT 'sqlite_temp_master' ORDER BY 1 + } + } else { + set sql { + SELECT name FROM sqlite_master WHERE type = 'table' UNION + SELECT 'sqlite_master' ORDER BY 1 + } + } + set tbllist [$db eval $sql] + set txt {} + foreach tbl $tbllist { + append txt [$db eval "SELECT * FROM $tbl"] + } + foreach prag {default_cache_size} { + append txt $prag-[$db eval "PRAGMA $prag"]\n + } + # puts txt=$txt + return [md5 $txt] +} + +# Generate a checksum based on the contents of a single database with +# a database connection. The name of the database is $dbname. +# Examples of $dbname are "temp" or "main". +# +proc dbcksum {db dbname} { + if {$dbname=="temp"} { + set master sqlite_temp_master + } else { + set master $dbname.sqlite_master + } + set alltab [$db eval "SELECT name FROM $master WHERE type='table'"] + set txt [$db eval "SELECT * FROM $master"]\n + foreach tab $alltab { + append txt [$db eval "SELECT * FROM $dbname.$tab"]\n + } + return [md5 $txt] +} + +proc memdebug_log_sql {{filename mallocs.sql}} { + + set data [sqlite3_memdebug_log dump] + set nFrame [expr [llength [lindex $data 0]]-2] + if {$nFrame < 0} { return "" } + + set database temp + + set tbl "CREATE TABLE ${database}.malloc(zTest, nCall, nByte, lStack);" + + set sql "" + foreach e $data { + set nCall [lindex $e 0] + set nByte [lindex $e 1] + set lStack [lrange $e 2 end] + append sql "INSERT INTO ${database}.malloc VALUES" + append sql "('test', $nCall, $nByte, '$lStack');\n" + foreach f $lStack { + set frames($f) 1 + } + } + + set tbl2 "CREATE TABLE ${database}.frame(frame INTEGER PRIMARY KEY, line);\n" + set tbl3 "CREATE TABLE ${database}.file(name PRIMARY KEY, content);\n" + + foreach f [array names frames] { + set addr [format %x $f] + set cmd "addr2line -e [info nameofexec] $addr" + set line [eval exec $cmd] + append sql "INSERT INTO ${database}.frame VALUES($f, '$line');\n" + + set file [lindex [split $line :] 0] + set files($file) 1 + } + + foreach f [array names files] { + set contents "" + catch { + set fd [open $f] + set contents [read $fd] + close $fd + } + set contents [string map {' ''} $contents] + append sql "INSERT INTO ${database}.file VALUES('$f', '$contents');\n" + } + + set fd [open $filename w] + puts $fd "BEGIN; ${tbl}${tbl2}${tbl3}${sql} ; COMMIT;" + close $fd +} + +# Drop all tables in database [db] +proc drop_all_tables {{db db}} { + ifcapable trigger&&foreignkey { + set pk [$db one "PRAGMA foreign_keys"] + $db eval "PRAGMA foreign_keys = OFF" + } + foreach {idx name file} [db eval {PRAGMA database_list}] { + if {$idx==1} { + set master sqlite_temp_master + } else { + set master $name.sqlite_master + } + foreach {t type} [$db eval " + SELECT name, type FROM $master + WHERE type IN('table', 'view') AND name NOT LIKE 'sqliteX_%' ESCAPE 'X' + "] { + $db eval "DROP $type \"$t\"" + } + } + ifcapable trigger&&foreignkey { + $db eval "PRAGMA foreign_keys = $pk" + } +} + +#------------------------------------------------------------------------- +# If a test script is executed with global variable $::G(perm:name) set to +# "wal", then the tests are run in WAL mode. Otherwise, they should be run +# in rollback mode. The following Tcl procs are used to make this less +# intrusive: +# +# wal_set_journal_mode ?DB? +# +# If running a WAL test, execute "PRAGMA journal_mode = wal" using +# connection handle DB. Otherwise, this command is a no-op. +# +# wal_check_journal_mode TESTNAME ?DB? +# +# If running a WAL test, execute a tests case that fails if the main +# database for connection handle DB is not currently a WAL database. +# Otherwise (if not running a WAL permutation) this is a no-op. +# +# wal_is_wal_mode +# +# Returns true if this test should be run in WAL mode. False otherwise. +# +proc wal_is_wal_mode {} { + expr {[permutation] eq "wal"} +} +proc wal_set_journal_mode {{db db}} { + if { [wal_is_wal_mode] } { + $db eval "PRAGMA journal_mode = WAL" + } +} +proc wal_check_journal_mode {testname {db db}} { + if { [wal_is_wal_mode] } { + $db eval { SELECT * FROM sqlite_master } + do_test $testname [list $db eval "PRAGMA main.journal_mode"] {wal} + } +} + +proc permutation {} { + set perm "" + catch {set perm $::G(perm:name)} + set perm +} +proc presql {} { + set presql "" + catch {set presql $::G(perm:presql)} + set presql +} + +#------------------------------------------------------------------------- +# +proc slave_test_script {script} { + + # Create the interpreter used to run the test script. + interp create tinterp + + # Populate some global variables that tester.tcl expects to see. + foreach {var value} [list \ + ::argv0 $::argv0 \ + ::argv {} \ + ::SLAVE 1 \ + ] { + interp eval tinterp [list set $var $value] + } + + # The alias used to access the global test counters. + tinterp alias set_test_counter set_test_counter + + # Set up the ::cmdlinearg array in the slave. + interp eval tinterp [list array set ::cmdlinearg [array get ::cmdlinearg]] + + # Set up the ::G array in the slave. + interp eval tinterp [list array set ::G [array get ::G]] + + # Load the various test interfaces implemented in C. + load_testfixture_extensions tinterp + + # Run the test script. + interp eval tinterp $script + + # Check if the interpreter call [run_thread_tests] + if { [interp eval tinterp {info exists ::run_thread_tests_called}] } { + set ::run_thread_tests_called 1 + } + + # Delete the interpreter used to run the test script. + interp delete tinterp +} + +proc slave_test_file {zFile} { + set tail [file tail $zFile] + + if {[info exists ::G(start:permutation)]} { + if {[permutation] != $::G(start:permutation)} return + unset ::G(start:permutation) + } + if {[info exists ::G(start:file)]} { + if {$tail != $::G(start:file) && $tail!="$::G(start:file).test"} return + unset ::G(start:file) + } + + # Remember the value of the shared-cache setting. So that it is possible + # to check afterwards that it was not modified by the test script. + # + ifcapable shared_cache { set scs [sqlite3_enable_shared_cache] } + + # Run the test script in a slave interpreter. + # + unset -nocomplain ::run_thread_tests_called + reset_prng_state + set ::sqlite_open_file_count 0 + set time [time { slave_test_script [list source $zFile] }] + set ms [expr [lindex $time 0] / 1000] + + # Test that all files opened by the test script were closed. Omit this + # if the test script has "thread" in its name. The open file counter + # is not thread-safe. + # + if {[info exists ::run_thread_tests_called]==0} { + do_test ${tail}-closeallfiles { expr {$::sqlite_open_file_count>0} } {0} + } + set ::sqlite_open_file_count 0 + + # Test that the global "shared-cache" setting was not altered by + # the test script. + # + ifcapable shared_cache { + set res [expr {[sqlite3_enable_shared_cache] == $scs}] + do_test ${tail}-sharedcachesetting [list set {} $res] 1 + } + + # Add some info to the output. + # + puts "Time: $tail $ms ms" + show_memstats +} + +# Open a new connection on database test.db and execute the SQL script +# supplied as an argument. Before returning, close the new conection and +# restore the 4 byte fields starting at header offsets 28, 92 and 96 +# to the values they held before the SQL was executed. This simulates +# a write by a pre-3.7.0 client. +# +proc sql36231 {sql} { + set B [hexio_read test.db 92 8] + set A [hexio_read test.db 28 4] + sqlite3 db36231 test.db + catch { db36231 func a_string a_string } + execsql $sql db36231 + db36231 close + hexio_write test.db 28 $A + hexio_write test.db 92 $B + return "" +} + +proc db_save {} { + foreach f [glob -nocomplain sv_test.db*] { forcedelete $f } + foreach f [glob -nocomplain test.db*] { + set f2 "sv_$f" + forcecopy $f $f2 + } +} +proc db_save_and_close {} { + db_save + catch { db close } + return "" +} +proc db_restore {} { + foreach f [glob -nocomplain test.db*] { forcedelete $f } + foreach f2 [glob -nocomplain sv_test.db*] { + set f [string range $f2 3 end] + forcecopy $f2 $f + } +} +proc db_restore_and_reopen {{dbfile test.db}} { + catch { db close } + db_restore + sqlite3 db $dbfile +} +proc db_delete_and_reopen {{file test.db}} { + catch { db close } + foreach f [glob -nocomplain test.db*] { forcedelete $f } + sqlite3 db $file +} + +# If the library is compiled with the SQLITE_DEFAULT_AUTOVACUUM macro set +# to non-zero, then set the global variable $AUTOVACUUM to 1. +set AUTOVACUUM $sqlite_options(default_autovacuum) + +# Make sure the FTS enhanced query syntax is disabled. +set sqlite_fts3_enable_parentheses 0 + +source $testdir/thread_common.tcl +source $testdir/malloc_common.tcl diff --git a/components/external/SQLite-3.8.1/test/thread001.test b/components/external/SQLite-3.8.1/test/thread001.test new file mode 100644 index 0000000000000000000000000000000000000000..a796c57b4a13a9d2f10ec5854d205caf87d0250f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/thread001.test @@ -0,0 +1,145 @@ +# 2007 September 7 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: thread001.test,v 1.10 2009/03/26 14:48:07 danielk1977 Exp $ + +set testdir [file dirname $argv0] + +source $testdir/tester.tcl +if {[run_thread_tests]==0} { finish_test ; return } + +set ::enable_shared_cache [sqlite3_enable_shared_cache] + +set ::NTHREAD 10 + +# Run this test three times: +# +# 1) All threads use the same database handle. +# 2) All threads use their own database handles. +# 3) All threads use their own database handles, shared-cache is enabled. +# +# +# +foreach {tn same_db shared_cache} [list \ + 1 1 0 \ + 2 0 0 \ + 3 0 1 \ +] { + # Empty the database. + # + catchsql { DROP TABLE ab; } + + do_test thread001.$tn.0 { + db close + sqlite3_enable_shared_cache $shared_cache + sqlite3_enable_shared_cache $shared_cache + } $shared_cache + sqlite3 db test.db -fullmutex 1 -key xyzzy + + set dbconfig "" + if {$same_db} { + set dbconfig [list set ::DB [sqlite3_connection_pointer db]] + } + + # Set up a database and a schema. The database contains a single + # table with two columns. The first column ("a") is an INTEGER PRIMARY + # KEY. The second contains the md5sum of all rows in the table with + # a smaller value stored in column "a". + # + do_test thread001.$tn.1 { + execsql { + CREATE TABLE ab(a INTEGER PRIMARY KEY, b); + CREATE INDEX ab_i ON ab(b); + INSERT INTO ab SELECT NULL, md5sum(a, b) FROM ab; + SELECT count(*) FROM ab; + } + } {1} + do_test thread001.$tn.2 { + execsql { + SELECT + (SELECT md5sum(a, b) FROM ab WHERE a < (SELECT max(a) FROM ab)) == + (SELECT b FROM ab WHERE a = (SELECT max(a) FROM ab)) + } + } {1} + do_test thread001.$tn.3 { + execsql { PRAGMA integrity_check } + } {ok} + + set thread_program { + #sqlthread parent {puts STARTING..} + set needToClose 0 + if {![info exists ::DB]} { + set ::DB [sqlthread open test.db xyzzy] + #sqlthread parent "puts \"OPEN $::DB\"" + set needToClose 1 + } + + for {set i 0} {$i < 100} {incr i} { + # Test that the invariant is true. + do_test t1 { + execsql { + SELECT + (SELECT md5sum(a, b) FROM ab WHERE +a < (SELECT max(a) FROM ab)) == + (SELECT b FROM ab WHERE a = (SELECT max(a) FROM ab)) + } + } {1} + + # Add another row to the database. + execsql { INSERT INTO ab SELECT NULL, md5sum(a, b) FROM ab } + } + + if {$needToClose} { + #sqlthread parent "puts \"CLOSE $::DB\"" + sqlite3_close $::DB + } + #sqlthread parent "puts \"DONE\"" + + list OK + } + + # Kick off $::NTHREAD threads: + # + array unset finished + for {set i 0} {$i < $::NTHREAD} {incr i} { + thread_spawn finished($i) $dbconfig $thread_procs $thread_program + } + + # Wait for all threads to finish, then check they all returned "OK". + # + for {set i 0} {$i < $::NTHREAD} {incr i} { + if {![info exists finished($i)]} { + vwait finished($i) + } + do_test thread001.$tn.4.$i { + set ::finished($i) + } OK + } + + # Check the database still looks Ok. + # + do_test thread001.$tn.5 { + execsql { SELECT count(*) FROM ab; } + } [expr {1 + $::NTHREAD*100}] + do_test thread001.$tn.6 { + execsql { + SELECT + (SELECT md5sum(a, b) FROM ab WHERE +a < (SELECT max(a) FROM ab)) == + (SELECT b FROM ab WHERE a = (SELECT max(a) FROM ab)) + } + } {1} + do_test thread001.$tn.7 { + execsql { PRAGMA integrity_check } + } {ok} +} + +sqlite3_enable_shared_cache $::enable_shared_cache +set sqlite_open_file_count 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/thread002.test b/components/external/SQLite-3.8.1/test/thread002.test new file mode 100644 index 0000000000000000000000000000000000000000..b39c9ae7cd2617705298df8c02420957bf419675 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/thread002.test @@ -0,0 +1,105 @@ +# 2007 September 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test attempts to deadlock SQLite in shared-cache mode. +# +# +# $Id: thread002.test,v 1.9 2009/03/26 14:48:07 danielk1977 Exp $ + +set testdir [file dirname $argv0] + +set do_not_use_codec 1 +source $testdir/tester.tcl +if {[run_thread_tests]==0} { finish_test ; return } + + +db close +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +set ::NTHREAD 10 + +do_test thread002.1 { + # Create 3 databases with identical schemas: + for {set ii 0} {$ii < 3} {incr ii} { + forcedelete test${ii}.db + sqlite3 db test${ii}.db + execsql { + CREATE TABLE t1(k, v); + CREATE INDEX t1_i ON t1(v); + INSERT INTO t1(v) VALUES(1.0); + } + db close + } +} {} + +set thread_program { + set ::DB [sqlite3_open test.db] + for {set ii 1} {$ii <= 3} {incr ii} { + set T [lindex $order [expr $ii-1]] + execsql "ATTACH 'test${T}.db' AS aux${ii}" + } + + for {set ii 0} {$ii < 100} {incr ii} { + execsql { SELECT * FROM aux1.t1 } + execsql { INSERT INTO aux1.t1(v) SELECT sum(v) FROM aux2.t1 } + + execsql { SELECT * FROM aux2.t1 } + execsql { INSERT INTO aux2.t1(v) SELECT sum(v) FROM aux3.t1 } + + execsql { SELECT * FROM aux3.t1 } + execsql { INSERT INTO aux3.t1(v) SELECT sum(v) FROM aux1.t1 } + + execsql { CREATE TABLE IF NOT EXISTS aux1.t2(a,b) } + execsql { DROP TABLE IF EXISTS aux1.t2 } + + # if {($ii%10)==0} {puts -nonewline . ; flush stdout} + puts -nonewline . ; flush stdout + } + + sqlite3_close $::DB + list OK +} + +set order_list [list {0 1 2} {0 2 1} {1 0 2} {1 2 0} {2 0 1} {2 1 0}] + +array unset finished +for {set ii 0} {$ii < $::NTHREAD} {incr ii} { + set order [lindex $order_list [expr $ii%6]] + thread_spawn finished($ii) $thread_procs "set order {$order}" $thread_program +} + +# Wait for all threads to finish, then check they all returned "OK". +# +for {set i 0} {$i < $::NTHREAD} {incr i} { + if {![info exists finished($i)]} { + vwait finished($i) + } + do_test thread002.2.$i { + set ::finished($i) + } OK +} + +# Check all three databases are Ok. +for {set ii 0} {$ii < 3} {incr ii} { + do_test thread002.3.$ii { + sqlite3 db test${ii}.db + set res [list \ + [execsql {SELECT count(*) FROM t1}] \ + [execsql {PRAGMA integrity_check}] \ + ] + db close + set res + } [list [expr 1 + $::NTHREAD*100] ok] +} + +sqlite3_enable_shared_cache $::enable_shared_cache +set sqlite_open_file_count 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/thread003.test b/components/external/SQLite-3.8.1/test/thread003.test new file mode 100644 index 0000000000000000000000000000000000000000..8c7440c82ee6f3b4abf749bd054b3cbc2d5a5447 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/thread003.test @@ -0,0 +1,189 @@ +# 2007 September 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests that attempt to break the pcache module +# by bombarding it with simultaneous requests from multiple threads. +# +# $Id: thread003.test,v 1.8 2009/03/26 14:48:07 danielk1977 Exp $ + +set testdir [file dirname $argv0] + +source $testdir/tester.tcl +if {[run_thread_tests]==0} { finish_test ; return } + +# Set up a couple of different databases full of pseudo-randomly +# generated data. +# +do_test thread003.1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a, b, c); + } + for {set ii 0} {$ii < 5000} {incr ii} { + execsql {INSERT INTO t1 VALUES($ii, randomblob(200), randomblob(200))} + } + execsql { + CREATE INDEX i1 ON t1(a, b); + COMMIT; + } +} {} +do_test thread003.1.2 { + expr {([file size test.db] / 1024) > 2000} +} {1} +do_test thread003.1.3 { + db close + forcedelete test2.db + sqlite3 db test2.db +} {} +do_test thread003.1.4 { + execsql { + BEGIN; + CREATE TABLE t1(a, b, c); + } + for {set ii 0} {$ii < 5000} {incr ii} { + execsql {INSERT INTO t1 VALUES($ii, randomblob(200), randomblob(200))} + } + execsql { + CREATE INDEX i1 ON t1(a, b); + COMMIT; + } +} {} +do_test thread003.1.5 { + expr {([file size test.db] / 1024) > 2000} +} {1} +do_test thread003.1.6 { + db close +} {} + + +# This test opens a connection on each of the large (>2MB) database files +# created by the previous block. The connections do not share a cache. +# Both "cache_size" parameters are set to 15, so there is a maximum of +# 30 pages available globally. +# +# Then, in separate threads, the databases are randomly queried over and +# over again. This will force the connections to recycle clean pages from +# each other. If there is a thread-safety problem, a segfault or assertion +# failure may eventually occur. +# +set nSecond 30 +puts "Starting thread003.2 (should run for ~$nSecond seconds)" +do_test thread003.2 { + foreach zFile {test.db test2.db} { + set SCRIPT [format { + set iEnd [expr {[clock_seconds] + %d}] + set ::DB [sqlthread open %s xyzzy] + + # Set the cache size to 15 pages per cache. 30 available globally. + execsql { PRAGMA cache_size = 15 } + + while {[clock_seconds] < $iEnd} { + set iQuery [expr {int(rand()*5000)}] + execsql " SELECT * FROM t1 WHERE a = $iQuery " + } + + sqlite3_close $::DB + expr 1 + } $nSecond $zFile] + + unset -nocomplain finished($zFile) + thread_spawn finished($zFile) $thread_procs $SCRIPT + } + foreach zFile {test.db test2.db} { + if {![info exists finished($zFile)]} { + vwait finished($zFile) + } + } + expr 0 +} {0} + +# This test is the same as the test above, except that each thread also +# writes to the database. This causes pages to be moved back and forth +# between the caches internal dirty and clean lists, which is another +# opportunity for a thread-related bug to present itself. +# +set nSecond 30 +puts "Starting thread003.3 (should run for ~$nSecond seconds)" +do_test thread003.3 { + foreach zFile {test.db test2.db} { + set SCRIPT [format { + set iStart [clock_seconds] + set iEnd [expr {[clock_seconds] + %d}] + set ::DB [sqlthread open %s xyzzy] + + # Set the cache size to 15 pages per cache. 30 available globally. + execsql { PRAGMA cache_size = 15 } + + while {[clock_seconds] < $iEnd} { + set iQuery [expr {int(rand()*5000)}] + execsql "SELECT * FROM t1 WHERE a = $iQuery" + execsql "UPDATE t1 SET b = randomblob(200) + WHERE a < $iQuery AND a > $iQuery + 20 + " + } + + sqlite3_close $::DB + expr 1 + } $nSecond $zFile] + + unset -nocomplain finished($zFile) + thread_spawn finished($zFile) $thread_procs $SCRIPT + } + foreach zFile {test.db test2.db} { + if {![info exists finished($zFile)]} { + vwait finished($zFile) + } + } + expr 0 +} {0} + +# In this test case, one thread is continually querying the database. +# The other thread does not have a database connection, but calls +# sqlite3_release_memory() over and over again. +# +set nSecond 30 +puts "Starting thread003.4 (should run for ~$nSecond seconds)" +unset -nocomplain finished(1) +unset -nocomplain finished(2) +do_test thread003.4 { + thread_spawn finished(1) $thread_procs [format { + set iEnd [expr {[clock_seconds] + %d}] + set ::DB [sqlthread open test.db xyzzy] + + # Set the cache size to 15 pages per cache. 30 available globally. + execsql { PRAGMA cache_size = 15 } + + while {[clock_seconds] < $iEnd} { + set iQuery [expr {int(rand()*5000)}] + execsql "SELECT * FROM t1 WHERE a = $iQuery" + } + + sqlite3_close $::DB + expr 1 + } $nSecond] + thread_spawn finished(2) [format { + set iEnd [expr {[clock_seconds] + %d}] + + while {[clock_seconds] < $iEnd} { + sqlite3_release_memory 1000 + } + } $nSecond] + + foreach ii {1 2} { + if {![info exists finished($ii)]} { + vwait finished($ii) + } + } + expr 0 +} {0} + +set sqlite_open_file_count 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/thread004.test b/components/external/SQLite-3.8.1/test/thread004.test new file mode 100644 index 0000000000000000000000000000000000000000..b2adc460d008a85446bab42c65e7643a70a78fde --- /dev/null +++ b/components/external/SQLite-3.8.1/test/thread004.test @@ -0,0 +1,79 @@ +# 2009 February 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: thread004.test,v 1.3 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] + +source $testdir/tester.tcl +if {[run_thread_tests]==0} { finish_test ; return } +ifcapable !shared_cache { + finish_test + return +} +if { [info commands sqlite3_table_column_metadata] eq "" } { + finish_test + return +} + +# Use shared-cache mode for this test. +# +db close +set ::enable_shared_cache [sqlite3_enable_shared_cache] +sqlite3_enable_shared_cache 1 + +# Create a table in database test.db +# +sqlite3 db test.db +do_test thread004-1.1 { + execsql { CREATE TABLE t1(a, b, c) } +} {} + +do_test thread004-1.2 { + + set ThreadOne { + set iStart [clock_seconds] + while {[clock_seconds]<$iStart+20} { + set ::DB [sqlite3_open test.db] + sqlite3_close $::DB + } + } + set ThreadTwo { + set ::DB [sqlite3_open test.db] + set iStart [clock_seconds] + set nErr 0 + while {[clock_seconds] <$iStart+20} { + incr nErr [catch {sqlite3_table_column_metadata $::DB main t1 a}] + } + sqlite3_close $::DB + set nErr + } + + # Run two threads. The first thread opens and closes database test.db + # repeatedly. Each time this happens, the in-memory schema used by + # all connections to test.db is discarded. + # + # The second thread calls sqlite3_table_column_metadata() over and + # over again. Each time it is called, the database schema is loaded + # if it is not already in memory. At one point this was crashing. + # + unset -nocomplain finished + thread_spawn finished(1) $thread_procs $ThreadOne + thread_spawn finished(2) $thread_procs $ThreadTwo + + foreach t {1 2} { + if {![info exists finished($t)]} { vwait finished($t) } + } + + set finished(2) +} {0} +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/thread005.test b/components/external/SQLite-3.8.1/test/thread005.test new file mode 100644 index 0000000000000000000000000000000000000000..89cbfe76da8f5e46736ba90c7c3a788b9754386c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/thread005.test @@ -0,0 +1,238 @@ +# 2009 March 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test a race-condition that shows up in shared-cache mode. +# +# $Id: thread005.test,v 1.5 2009/03/26 14:48:07 danielk1977 Exp $ + +set testdir [file dirname $argv0] + +source $testdir/tester.tcl +if {[run_thread_tests]==0} { finish_test ; return } +ifcapable !shared_cache { + finish_test + return +} + +db close + +# Use shared-cache mode for these tests. +# +set ::enable_shared_cache [sqlite3_enable_shared_cache] +sqlite3_enable_shared_cache 1 + +#------------------------------------------------------------------------- +# This test attempts to hit the race condition fixed by commit [6363]. +# +proc runsql {zSql {db {}}} { + set rc SQLITE_OK + while {$rc=="SQLITE_OK" && $zSql ne ""} { + set STMT [sqlite3_prepare_v2 $db $zSql -1 zSql] + while {[set rc [sqlite3_step $STMT]] eq "SQLITE_ROW"} { } + set rc [sqlite3_finalize $STMT] + } + return $rc +} +do_test thread005-1.1 { + sqlite3 db test.db + db eval { CREATE TABLE t1(a, b) } + db close +} {} +for {set ii 2} {$ii < 500} {incr ii} { + unset -nocomplain finished + thread_spawn finished(0) {sqlite3_open test.db} + thread_spawn finished(1) {sqlite3_open test.db} + if {![info exists finished(0)]} { vwait finished(0) } + if {![info exists finished(1)]} { vwait finished(1) } + + do_test thread005-1.$ii { + runsql { BEGIN } $finished(0) + runsql { INSERT INTO t1 VALUES(1, 2) } $finished(0) + + # If the race-condition was hit, then $finished(0 and $finished(1) + # will not use the same pager cache. In this case the next statement + # can be executed succesfully. However, if the race-condition is not + # hit, then $finished(1) will be blocked by the write-lock held by + # $finished(0) on the shared-cache table t1 and the statement will + # return SQLITE_LOCKED. + # + runsql { SELECT * FROM t1 } $finished(1) + } {SQLITE_LOCKED} + + sqlite3_close $finished(0) + sqlite3_close $finished(1) +} + + +#------------------------------------------------------------------------- +# This test tries to exercise a race-condition that existed in shared-cache +# mode at one point. The test uses two threads; each has a database connection +# open on the same shared cache. The schema of the database is: +# +# CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE); +# +# One thread is a reader and the other thread a reader and a writer. The +# writer thread repeats the following transaction as fast as possible: +# +# BEGIN; +# DELETE FROM t1 WHERE a = (SELECT max(a) FROM t1); +# INSERT INTO t1 VALUES(NULL, NULL); +# UPDATE t1 SET b = a WHERE a = (SELECT max(a) FROM t1); +# SELECT count(*) FROM t1 WHERE b IS NULL; +# COMMIT; +# +# The reader thread does the following over and over as fast as possible: +# +# BEGIN; +# SELECT count(*) FROM t1 WHERE b IS NULL; +# COMMIT; +# +# The test runs for 20 seconds or until one of the "SELECT count(*)" +# statements returns a non-zero value. If an SQLITE_LOCKED error occurs, +# the connection issues a ROLLBACK immediately to abandon the current +# transaction. +# +# If everything is working correctly, the "SELECT count(*)" statements +# should never return a value other than 0. The "INSERT" statement +# executed by the writer adds a row with "b IS NULL" to the table, but +# the subsequent UPDATE statement sets its "b" value to an integer +# immediately afterwards. +# +# However, before the race-condition was fixed, if the reader's SELECT +# statement hit an error (say an SQLITE_LOCKED) at the same time as the +# writer was executing the UPDATE statement, then it could incorrectly +# rollback the statement-transaction belonging to the UPDATE statement. +# The UPDATE statement would still be reported as successful to the user, +# but it would have no effect on the database contents. +# +# Note that it has so far only proved possible to hit this race-condition +# when using an ATTACHed database. There doesn't seem to be any reason +# for this, other than that operating on an ATTACHed database means there +# are a few more mutex grabs and releases during the window of time open +# for the race-condition. Maybe this encourages the scheduler to context +# switch or something... +# + +forcedelete test.db test2.db +unset -nocomplain finished + +do_test thread005-2.1 { + sqlite3 db test.db + execsql { ATTACH 'test2.db' AS aux } + execsql { + CREATE TABLE aux.t1(a INTEGER PRIMARY KEY, b UNIQUE); + INSERT INTO t1 VALUES(1, 1); + INSERT INTO t1 VALUES(2, 2); + } + db close +} {} + + +set ThreadProgram { + proc execsql {zSql {db {}}} { + if {$db eq ""} {set db $::DB} + + set lRes [list] + set rc SQLITE_OK + + while {$rc=="SQLITE_OK" && $zSql ne ""} { + set STMT [sqlite3_prepare_v2 $db $zSql -1 zSql] + while {[set rc [sqlite3_step $STMT]] eq "SQLITE_ROW"} { + for {set i 0} {$i < [sqlite3_column_count $STMT]} {incr i} { + lappend lRes [sqlite3_column_text $STMT 0] + } + } + set rc [sqlite3_finalize $STMT] + } + + if {$rc != "SQLITE_OK"} { error "$rc [sqlite3_errmsg $db]" } + return $lRes + } + + if {$isWriter} { + set Sql { + BEGIN; + DELETE FROM t1 WHERE a = (SELECT max(a) FROM t1); + INSERT INTO t1 VALUES(NULL, NULL); + UPDATE t1 SET b = a WHERE a = (SELECT max(a) FROM t1); + SELECT count(*) FROM t1 WHERE b IS NULL; + COMMIT; + } + } else { + set Sql { + BEGIN; + SELECT count(*) FROM t1 WHERE b IS NULL; + COMMIT; + } + } + + set ::DB [sqlite3_open test.db] + + execsql { ATTACH 'test2.db' AS aux } + + set result "ok" + set finish [expr [clock_seconds]+5] + while {$result eq "ok" && [clock_seconds] < $finish} { + set rc [catch {execsql $Sql} msg] + if {$rc} { + if {[string match "SQLITE_LOCKED*" $msg]} { + catch { execsql ROLLBACK } + } else { + sqlite3_close $::DB + error $msg + } + } elseif {$msg ne "0"} { + set result "failed" + } + } + + sqlite3_close $::DB + set result +} + +# There is a race-condition in btree.c that means that if two threads +# attempt to open the same database at roughly the same time, and there +# does not already exist a shared-cache corresponding to that database, +# then two shared-caches can be created instead of one. Things still more +# or less work, but the two database connections do not use the same +# shared-cache. +# +# If the threads run by this test hit this race-condition, the tests +# fail (because SQLITE_BUSY may be unexpectedly returned instead of +# SQLITE_LOCKED). To prevent this from happening, open a couple of +# connections to test.db and test2.db now to make sure that there are +# already shared-caches in memory for all databases opened by the +# test threads. +# +sqlite3 db test.db +sqlite3 db test2.db + +puts "Running thread-tests for ~20 seconds" +thread_spawn finished(0) {set isWriter 0} $ThreadProgram +thread_spawn finished(1) {set isWriter 1} $ThreadProgram +if {![info exists finished(0)]} { vwait finished(0) } +if {![info exists finished(1)]} { vwait finished(1) } + +catch { db close } +catch { db2 close } + +do_test thread005-2.2 { + list $finished(0) $finished(1) +} {ok ok} + +do_test thread005-2.3 { + sqlite3 db test.db + execsql { ATTACH 'test2.db' AS aux } + execsql { SELECT count(*) FROM t1 WHERE b IS NULL } +} {0} + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/thread1.test b/components/external/SQLite-3.8.1/test/thread1.test new file mode 100644 index 0000000000000000000000000000000000000000..0618f2c66f81cd4caa802b6d02f51fbdac3cdcfa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/thread1.test @@ -0,0 +1,173 @@ +# 2003 December 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is multithreading behavior +# +# $Id: thread1.test,v 1.8 2008/10/07 15:25:49 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Skip this whole file if the thread testing code is not enabled +# +if {[run_thread_tests]==0} { finish_test ; return } +if {[llength [info command thread_step]]==0 || [sqlite3 -has-codec]} { + finish_test + return +} + +# Create some data to work with +# +do_test thread1-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,'abcdefgh'); + INSERT INTO t1 SELECT a+1, b||b FROM t1; + INSERT INTO t1 SELECT a+2, b||b FROM t1; + INSERT INTO t1 SELECT a+4, b||b FROM t1; + SELECT count(*), max(length(b)) FROM t1; + } +} {8 64} + +# Interleave two threads on read access. Then make sure a third +# thread can write the database. In other words: +# +# read-lock A +# read-lock B +# unlock A +# unlock B +# write-lock C +# +# At one point, the write-lock of C would fail on Linux. +# +do_test thread1-1.2 { + thread_create A test.db + thread_create B test.db + thread_create C test.db + thread_compile A {SELECT a FROM t1} + thread_step A + thread_result A +} SQLITE_ROW +do_test thread1-1.3 { + thread_argc A +} 1 +do_test thread1-1.4 { + thread_argv A 0 +} 1 +do_test thread1-1.5 { + thread_compile B {SELECT b FROM t1} + thread_step B + thread_result B +} SQLITE_ROW +do_test thread1-1.6 { + thread_argc B +} 1 +do_test thread1-1.7 { + thread_argv B 0 +} abcdefgh +do_test thread1-1.8 { + thread_finalize A + thread_result A +} SQLITE_OK +do_test thread1-1.9 { + thread_finalize B + thread_result B +} SQLITE_OK +do_test thread1-1.10 { + thread_compile C {CREATE TABLE t2(x,y)} + thread_step C + thread_result C +} SQLITE_DONE +do_test thread1-1.11 { + thread_finalize C + thread_result C +} SQLITE_OK +do_test thread1-1.12 { + catchsql {SELECT name FROM sqlite_master} + execsql {SELECT name FROM sqlite_master} +} {t1 t2} + + +# +# The following tests - thread1-2.* - test the following scenario: +# +# 1: Read-lock thread A +# 2: Read-lock thread B +# 3: Attempt to write in thread C -> SQLITE_BUSY +# 4: Check db write failed from main thread. +# 5: Unlock from thread A. +# 6: Attempt to write in thread C -> SQLITE_BUSY +# 7: Check db write failed from main thread. +# 8: Unlock from thread B. +# 9: Attempt to write in thread C -> SQLITE_DONE +# 10: Finalize the write from thread C +# 11: Check db write succeeded from main thread. +# +do_test thread1-2.1 { + thread_halt * + thread_create A test.db + thread_compile A {SELECT a FROM t1} + thread_step A + thread_result A +} SQLITE_ROW +do_test thread1-2.2 { + thread_create B test.db + thread_compile B {SELECT b FROM t1} + thread_step B + thread_result B +} SQLITE_ROW +do_test thread1-2.3 { + thread_create C test.db + thread_compile C {INSERT INTO t2 VALUES(98,99)} + thread_step C + thread_result C + thread_finalize C + thread_result C +} SQLITE_BUSY + +do_test thread1-2.4 { + execsql {SELECT * FROM t2} +} {} + +do_test thread1-2.5 { + thread_finalize A + thread_result A +} SQLITE_OK +do_test thread1-2.6 { + thread_compile C {INSERT INTO t2 VALUES(98,99)} + thread_step C + thread_result C + thread_finalize C + thread_result C +} SQLITE_BUSY +do_test thread1-2.7 { + execsql {SELECT * FROM t2} +} {} +do_test thread1-2.8 { + thread_finalize B + thread_result B +} SQLITE_OK +do_test thread1-2.9 { + thread_compile C {INSERT INTO t2 VALUES(98,99)} + thread_step C + thread_result C +} SQLITE_DONE +do_test thread1-2.10 { + thread_finalize C + thread_result C +} SQLITE_OK +do_test thread1-2.11 { + execsql {SELECT * FROM t2} +} {98 99} + +thread_halt * +finish_test diff --git a/components/external/SQLite-3.8.1/test/thread2.test b/components/external/SQLite-3.8.1/test/thread2.test new file mode 100644 index 0000000000000000000000000000000000000000..dad2bf2c5f4b1881af82362c11818b8093e9f762 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/thread2.test @@ -0,0 +1,120 @@ +# 2006 January 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is multithreading behavior +# +# $Id: thread2.test,v 1.3 2008/10/07 15:25:49 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +if {[run_thread_tests]==0} { finish_test ; return } + +# Skip this whole file if the thread testing code is not enabled +# +if {[llength [info command thread_step]]==0 || [sqlite3 -has-codec]} { + finish_test + return +} + +# Create some data to work with +# +do_test thread1-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,'abcdefgh'); + INSERT INTO t1 SELECT a+1, b||b FROM t1; + INSERT INTO t1 SELECT a+2, b||b FROM t1; + INSERT INTO t1 SELECT a+4, b||b FROM t1; + SELECT count(*), max(length(b)) FROM t1; + } +} {8 64} + +# Use the thread_swap command to move the database connections between +# threads, then verify that they still work. +# +do_test thread2-1.2 { + db close + thread_create A test.db + thread_create B test.db + thread_swap A B + thread_compile A {SELECT a FROM t1 LIMIT 1} + thread_result A +} {SQLITE_OK} +do_test thread2-1.3 { + thread_step A + thread_result A +} {SQLITE_ROW} +do_test thread2-1.4 { + thread_argv A 0 +} {1} +do_test thread2-1.5 { + thread_finalize A + thread_result A +} {SQLITE_OK} +do_test thread2-1.6 { + thread_compile B {SELECT a FROM t1 LIMIT 1} + thread_result B +} {SQLITE_OK} +do_test thread2-1.7 { + thread_step B + thread_result B +} {SQLITE_ROW} +do_test thread2-1.8 { + thread_argv B 0 +} {1} +do_test thread2-1.9 { + thread_finalize B + thread_result B +} {SQLITE_OK} + +# Swap them again. +# +do_test thread2-2.2 { + thread_swap A B + thread_compile A {SELECT a FROM t1 LIMIT 1} + thread_result A +} {SQLITE_OK} +do_test thread2-2.3 { + thread_step A + thread_result A +} {SQLITE_ROW} +do_test thread2-2.4 { + thread_argv A 0 +} {1} +do_test thread2-2.5 { + thread_finalize A + thread_result A +} {SQLITE_OK} +do_test thread2-2.6 { + thread_compile B {SELECT a FROM t1 LIMIT 1} + thread_result B +} {SQLITE_OK} +do_test thread2-2.7 { + thread_step B + thread_result B +} {SQLITE_ROW} +do_test thread2-2.8 { + thread_argv B 0 +} {1} +do_test thread2-2.9 { + thread_finalize B + thread_result B +} {SQLITE_OK} +thread_halt A +thread_halt B + +# Also important to halt the worker threads, which are using spin +# locks and eating away CPU cycles. +# +thread_halt * +finish_test diff --git a/components/external/SQLite-3.8.1/test/thread_common.tcl b/components/external/SQLite-3.8.1/test/thread_common.tcl new file mode 100644 index 0000000000000000000000000000000000000000..6b17082ad4508528d2fd2d6686996c682bf7e89a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/thread_common.tcl @@ -0,0 +1,110 @@ +# 2007 September 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: thread_common.tcl,v 1.5 2009/03/26 14:48:07 danielk1977 Exp $ + +if {[info exists ::thread_procs]} { + return 0 +} + +# The following script is sourced by every thread spawned using +# [sqlthread spawn]: +set thread_procs { + + # Execute the supplied SQL using database handle $::DB. + # + proc execsql {sql} { + + set rc SQLITE_LOCKED + while {$rc eq "SQLITE_LOCKED" + || $rc eq "SQLITE_BUSY" + || $rc eq "SQLITE_SCHEMA"} { + set res [list] + + enter_db_mutex $::DB + set err [catch { + set ::STMT [sqlite3_prepare_v2 $::DB $sql -1 dummy_tail] + } msg] + + if {$err == 0} { + while {[set rc [sqlite3_step $::STMT]] eq "SQLITE_ROW"} { + for {set i 0} {$i < [sqlite3_column_count $::STMT]} {incr i} { + lappend res [sqlite3_column_text $::STMT 0] + } + } + set rc [sqlite3_finalize $::STMT] + } else { + if {[lindex $msg 0]=="(6)"} { + set rc SQLITE_LOCKED + } else { + set rc SQLITE_ERROR + } + } + + if {[string first locked [sqlite3_errmsg $::DB]]>=0} { + set rc SQLITE_LOCKED + } + if {$rc ne "SQLITE_OK"} { + set errtxt "$rc - [sqlite3_errmsg $::DB] (debug1)" + } + leave_db_mutex $::DB + + if {$rc eq "SQLITE_LOCKED" || $rc eq "SQLITE_BUSY"} { + #sqlthread parent "puts \"thread [sqlthread id] is busy. rc=$rc\"" + after 200 + } else { + #sqlthread parent "puts \"thread [sqlthread id] ran $sql\"" + } + } + + if {$rc ne "SQLITE_OK"} { + error $errtxt + } + set res + } + + proc do_test {name script result} { + set res [eval $script] + if {$res ne $result} { + error "$name failed: expected \"$result\" got \"$res\"" + } + } +} + +proc thread_spawn {varname args} { + sqlthread spawn $varname [join $args {;}] +} + +# Return true if this build can run the multi-threaded tests. +# +proc run_thread_tests {{print_warning 0}} { + ifcapable !mutex { + set zProblem "SQLite build is not threadsafe" + } + ifcapable mutex_noop { + set zProblem "SQLite build uses SQLITE_MUTEX_NOOP" + } + if {[info commands sqlthread] eq ""} { + set zProblem "SQLite build is not threadsafe" + } + if {![info exists ::tcl_platform(threaded)]} { + set zProblem "Linked against a non-threadsafe Tcl build" + } + if {[info exists zProblem]} { + puts "WARNING: Multi-threaded tests skipped: $zProblem" + return 0 + } + set ::run_thread_tests_called 1 + return 1; +} + +return 0 + diff --git a/components/external/SQLite-3.8.1/test/threadtest1.c b/components/external/SQLite-3.8.1/test/threadtest1.c new file mode 100644 index 0000000000000000000000000000000000000000..56fcce33e8a1cb8290ecc6cd5a43697b4a6b2e67 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/threadtest1.c @@ -0,0 +1,289 @@ +/* +** 2002 January 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements a simple standalone program used to test whether +** or not the SQLite library is threadsafe. +** +** Testing the thread safety of SQLite is difficult because there are very +** few places in the code that are even potentially unsafe, and those +** places execute for very short periods of time. So even if the library +** is compiled with its mutexes disabled, it is likely to work correctly +** in a multi-threaded program most of the time. +** +** This file is NOT part of the standard SQLite library. It is used for +** testing only. +*/ +#include "sqlite.h" +#include +#include +#include +#include +#include +#include + +/* +** Enable for tracing +*/ +static int verbose = 0; + +/* +** Come here to die. +*/ +static void Exit(int rc){ + exit(rc); +} + +extern char *sqlite3_mprintf(const char *zFormat, ...); +extern char *sqlite3_vmprintf(const char *zFormat, va_list); + +/* +** When a lock occurs, yield. +*/ +static int db_is_locked(void *NotUsed, int iCount){ + /* sched_yield(); */ + if( verbose ) printf("BUSY %s #%d\n", (char*)NotUsed, iCount); + usleep(100); + return iCount<25; +} + +/* +** Used to accumulate query results by db_query() +*/ +struct QueryResult { + const char *zFile; /* Filename - used for error reporting */ + int nElem; /* Number of used entries in azElem[] */ + int nAlloc; /* Number of slots allocated for azElem[] */ + char **azElem; /* The result of the query */ +}; + +/* +** The callback function for db_query +*/ +static int db_query_callback( + void *pUser, /* Pointer to the QueryResult structure */ + int nArg, /* Number of columns in this result row */ + char **azArg, /* Text of data in all columns */ + char **NotUsed /* Names of the columns */ +){ + struct QueryResult *pResult = (struct QueryResult*)pUser; + int i; + if( pResult->nElem + nArg >= pResult->nAlloc ){ + if( pResult->nAlloc==0 ){ + pResult->nAlloc = nArg+1; + }else{ + pResult->nAlloc = pResult->nAlloc*2 + nArg + 1; + } + pResult->azElem = realloc( pResult->azElem, pResult->nAlloc*sizeof(char*)); + if( pResult->azElem==0 ){ + fprintf(stdout,"%s: malloc failed\n", pResult->zFile); + return 1; + } + } + if( azArg==0 ) return 0; + for(i=0; iazElem[pResult->nElem++] = + sqlite3_mprintf("%s",azArg[i] ? azArg[i] : ""); + } + return 0; +} + +/* +** Execute a query against the database. NULL values are returned +** as an empty string. The list is terminated by a single NULL pointer. +*/ +char **db_query(sqlite *db, const char *zFile, const char *zFormat, ...){ + char *zSql; + int rc; + char *zErrMsg = 0; + va_list ap; + struct QueryResult sResult; + va_start(ap, zFormat); + zSql = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + memset(&sResult, 0, sizeof(sResult)); + sResult.zFile = zFile; + if( verbose ) printf("QUERY %s: %s\n", zFile, zSql); + rc = sqlite3_exec(db, zSql, db_query_callback, &sResult, &zErrMsg); + if( rc==SQLITE_SCHEMA ){ + if( zErrMsg ) free(zErrMsg); + rc = sqlite3_exec(db, zSql, db_query_callback, &sResult, &zErrMsg); + } + if( verbose ) printf("DONE %s %s\n", zFile, zSql); + if( zErrMsg ){ + fprintf(stdout,"%s: query failed: %s - %s\n", zFile, zSql, zErrMsg); + free(zErrMsg); + free(zSql); + Exit(1); + } + sqlite3_free(zSql); + if( sResult.azElem==0 ){ + db_query_callback(&sResult, 0, 0, 0); + } + sResult.azElem[sResult.nElem] = 0; + return sResult.azElem; +} + +/* +** Execute an SQL statement. +*/ +void db_execute(sqlite *db, const char *zFile, const char *zFormat, ...){ + char *zSql; + int rc; + char *zErrMsg = 0; + va_list ap; + va_start(ap, zFormat); + zSql = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + if( verbose ) printf("EXEC %s: %s\n", zFile, zSql); + do{ + rc = sqlite3_exec(db, zSql, 0, 0, &zErrMsg); + }while( rc==SQLITE_BUSY ); + if( verbose ) printf("DONE %s: %s\n", zFile, zSql); + if( zErrMsg ){ + fprintf(stdout,"%s: command failed: %s - %s\n", zFile, zSql, zErrMsg); + free(zErrMsg); + sqlite3_free(zSql); + Exit(1); + } + sqlite3_free(zSql); +} + +/* +** Free the results of a db_query() call. +*/ +void db_query_free(char **az){ + int i; + for(i=0; az[i]; i++){ + sqlite3_free(az[i]); + } + free(az); +} + +/* +** Check results +*/ +void db_check(const char *zFile, const char *zMsg, char **az, ...){ + va_list ap; + int i; + char *z; + va_start(ap, az); + for(i=0; (z = va_arg(ap, char*))!=0; i++){ + if( az[i]==0 || strcmp(az[i],z)!=0 ){ + fprintf(stdout,"%s: %s: bad result in column %d: %s\n", + zFile, zMsg, i+1, az[i]); + db_query_free(az); + Exit(1); + } + } + va_end(ap); + db_query_free(az); +} + +pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +pthread_cond_t sig = PTHREAD_COND_INITIALIZER; +int thread_cnt = 0; + +static void *worker_bee(void *pArg){ + const char *zFilename = (char*)pArg; + char *azErr; + int i, cnt; + int t = atoi(zFilename); + char **az; + sqlite *db; + + pthread_mutex_lock(&lock); + thread_cnt++; + pthread_mutex_unlock(&lock); + printf("%s: START\n", zFilename); + fflush(stdout); + for(cnt=0; cnt<10; cnt++){ + sqlite3_open(&zFilename[2], &db); + if( db==0 ){ + fprintf(stdout,"%s: can't open\n", zFilename); + Exit(1); + } + sqlite3_busy_handler(db, db_is_locked, zFilename); + db_execute(db, zFilename, "CREATE TABLE t%d(a,b,c);", t); + for(i=1; i<=100; i++){ + db_execute(db, zFilename, "INSERT INTO t%d VALUES(%d,%d,%d);", + t, i, i*2, i*i); + } + az = db_query(db, zFilename, "SELECT count(*) FROM t%d", t); + db_check(zFilename, "tX size", az, "100", 0); + az = db_query(db, zFilename, "SELECT avg(b) FROM t%d", t); + db_check(zFilename, "tX avg", az, "101", 0); + db_execute(db, zFilename, "DELETE FROM t%d WHERE a>50", t); + az = db_query(db, zFilename, "SELECT avg(b) FROM t%d", t); + db_check(zFilename, "tX avg2", az, "51", 0); + for(i=1; i<=50; i++){ + char z1[30], z2[30]; + az = db_query(db, zFilename, "SELECT b, c FROM t%d WHERE a=%d", t, i); + sprintf(z1, "%d", i*2); + sprintf(z2, "%d", i*i); + db_check(zFilename, "readback", az, z1, z2, 0); + } + db_execute(db, zFilename, "DROP TABLE t%d;", t); + sqlite3_close(db); + } + printf("%s: END\n", zFilename); + /* unlink(zFilename); */ + fflush(stdout); + pthread_mutex_lock(&lock); + thread_cnt--; + if( thread_cnt<=0 ){ + pthread_cond_signal(&sig); + } + pthread_mutex_unlock(&lock); + return 0; +} + +int main(int argc, char **argv){ + char *zFile; + int i, n; + pthread_t id; + if( argc>2 && strcmp(argv[1], "-v")==0 ){ + verbose = 1; + argc--; + argv++; + } + if( argc<2 || (n=atoi(argv[1]))<1 ) n = 10; + for(i=0; i0 ){ + pthread_cond_wait(&sig, &lock); + } + pthread_mutex_unlock(&lock); + for(i=0; i +#include +#include +#include +#include +#include "sqlite.h" + +/* +** Name of the database +*/ +#define DB_FILE "test.db" + +/* +** When this variable becomes non-zero, all threads stop +** what they are doing. +*/ +volatile int all_stop = 0; + +/* +** Callback from the integrity check. If the result is anything other +** than "ok" it means the integrity check has failed. Set the "all_stop" +** global variable to stop all other activity. Print the error message +** or print OK if the string "ok" is seen. +*/ +int check_callback(void *pid, int argc, char **argv, char **notUsed2){ + int id = (int)pid; + if( strcmp(argv[0],"ok") ){ + all_stop = 1; + fprintf(stderr,"id: %s\n", id, argv[0]); + }else{ + /* fprintf(stderr,"%d: OK\n", id); */ + } + return 0; +} + +/* +** Do an integrity check on the database. If the first integrity check +** fails, try it a second time. +*/ +int integrity_check(sqlite *db, int id){ + int rc; + if( all_stop ) return 0; + /* fprintf(stderr,"%d: CHECK\n", id); */ + rc = sqlite3_exec(db, "pragma integrity_check", check_callback, 0, 0); + if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){ + fprintf(stderr,"%d, Integrity check returns %d\n", id, rc); + } + if( all_stop ){ + sqlite3_exec(db, "pragma integrity_check", check_callback, 0, 0); + } + return 0; +} + +/* +** This is the worker thread +*/ +void *worker(void *workerArg){ + sqlite *db; + int id = (int)workerArg; + int rc; + int cnt = 0; + fprintf(stderr, "Starting worker %d\n", id); + while( !all_stop && cnt++<10000 ){ + if( cnt%100==0 ) printf("%d: %d\n", id, cnt); + while( (sqlite3_open(DB_FILE, &db))!=SQLITE_OK ) sched_yield(); + sqlite3_exec(db, "PRAGMA synchronous=OFF", 0, 0, 0); + /* integrity_check(db, id); */ + if( all_stop ){ sqlite3_close(db); break; } + /* fprintf(stderr, "%d: BEGIN\n", id); */ + rc = sqlite3_exec(db, "INSERT INTO t1 VALUES('bogus data')", 0, 0, 0); + /* fprintf(stderr, "%d: END rc=%d\n", id, rc); */ + sqlite3_close(db); + } + fprintf(stderr, "Worker %d finished\n", id); + return 0; +} + +/* +** Initialize the database and start the threads +*/ +int main(int argc, char **argv){ + sqlite *db; + int i, rc; + pthread_t aThread[5]; + + if( strcmp(DB_FILE,":memory:") ){ + char *zJournal = sqlite3_mprintf("%s-journal", DB_FILE); + unlink(DB_FILE); + unlink(zJournal); + sqlite3_free(zJournal); + } + sqlite3_open(DB_FILE, &db); + if( db==0 ){ + fprintf(stderr,"unable to initialize database\n"); + exit(1); + } + rc = sqlite3_exec(db, "CREATE TABLE t1(x);", 0,0,0); + if( rc ){ + fprintf(stderr,"cannot create table t1: %d\n", rc); + exit(1); + } + sqlite3_close(db); + for(i=0; i +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * This code implements the MD5 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + * + * Equivalent code is available from RSA Data Security, Inc. + * This code has been tested against that, and is equivalent, + * except that you don't need to include two pages of legalese + * with every copy. + * + * To compute the message digest of a chunk of bytes, declare an + * MD5Context structure, pass it to MD5Init, call MD5Update as + * needed on buffers full of bytes, and then call MD5Final, which + * will fill a supplied 16-byte array with the digest. + */ + +/* + * If compiled on a machine that doesn't have a 32-bit integer, + * you just set "uint32" to the appropriate datatype for an + * unsigned 32-bit integer. For example: + * + * cc -Duint32='unsigned long' md5.c + * + */ +#ifndef uint32 +# define uint32 unsigned int +#endif + +struct MD5Context { + int isInit; + uint32 buf[4]; + uint32 bits[2]; + unsigned char in[64]; +}; +typedef struct MD5Context MD5Context; + +/* + * Note: this code is harmless on little-endian machines. + */ +static void byteReverse (unsigned char *buf, unsigned longs){ + uint32 t; + do { + t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 | + ((unsigned)buf[1]<<8 | buf[0]); + *(uint32 *)buf = t; + buf += 4; + } while (--longs); +} +/* The four core functions - F1 is optimized somewhat */ + +/* #define F1(x, y, z) (x & y | ~x & z) */ +#define F1(x, y, z) (z ^ (x & (y ^ z))) +#define F2(x, y, z) F1(z, x, y) +#define F3(x, y, z) (x ^ y ^ z) +#define F4(x, y, z) (y ^ (x | ~z)) + +/* This is the central step in the MD5 algorithm. */ +#define MD5STEP(f, w, x, y, z, data, s) \ + ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + +/* + * The core of the MD5 algorithm, this alters an existing MD5 hash to + * reflect the addition of 16 longwords of new data. MD5Update blocks + * the data and converts bytes into longwords for this routine. + */ +static void MD5Transform(uint32 buf[4], const uint32 in[16]){ + register uint32 a, b, c, d; + + a = buf[0]; + b = buf[1]; + c = buf[2]; + d = buf[3]; + + MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17); + MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17); + MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22); + MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7); + MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12); + MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17); + MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22); + MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7); + MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12); + MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17); + MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22); + + MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9); + MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14); + MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9); + MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14); + MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20); + + MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11); + MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16); + MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23); + MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16); + MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23); + MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23); + MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4); + MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11); + MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16); + MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23); + + MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6); + MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10); + MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15); + MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10); + MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15); + MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6); + MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10); + MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15); + MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21); + MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6); + MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10); + MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} + +/* + * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious + * initialization constants. + */ +static void MD5Init(MD5Context *ctx){ + ctx->isInit = 1; + ctx->buf[0] = 0x67452301; + ctx->buf[1] = 0xefcdab89; + ctx->buf[2] = 0x98badcfe; + ctx->buf[3] = 0x10325476; + ctx->bits[0] = 0; + ctx->bits[1] = 0; +} + +/* + * Update context to reflect the concatenation of another buffer full + * of bytes. + */ +static +void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){ + uint32 t; + + /* Update bitcount */ + + t = ctx->bits[0]; + if ((ctx->bits[0] = t + ((uint32)len << 3)) < t) + ctx->bits[1]++; /* Carry from low to high */ + ctx->bits[1] += len >> 29; + + t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ + + /* Handle any leading odd-sized chunks */ + + if ( t ) { + unsigned char *p = (unsigned char *)ctx->in + t; + + t = 64-t; + if (len < t) { + memcpy(p, buf, len); + return; + } + memcpy(p, buf, t); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32 *)ctx->in); + buf += t; + len -= t; + } + + /* Process data in 64-byte chunks */ + + while (len >= 64) { + memcpy(ctx->in, buf, 64); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32 *)ctx->in); + buf += 64; + len -= 64; + } + + /* Handle any remaining bytes of data. */ + + memcpy(ctx->in, buf, len); +} + +/* + * Final wrapup - pad to 64-byte boundary with the bit pattern + * 1 0* (64-bit count of bits processed, MSB-first) + */ +static void MD5Final(unsigned char digest[16], MD5Context *ctx){ + unsigned count; + unsigned char *p; + + /* Compute number of bytes mod 64 */ + count = (ctx->bits[0] >> 3) & 0x3F; + + /* Set the first char of padding to 0x80. This is safe since there is + always at least one byte free */ + p = ctx->in + count; + *p++ = 0x80; + + /* Bytes of padding needed to make 64 bytes */ + count = 64 - 1 - count; + + /* Pad out to 56 mod 64 */ + if (count < 8) { + /* Two lots of padding: Pad the first block to 64 bytes */ + memset(p, 0, count); + byteReverse(ctx->in, 16); + MD5Transform(ctx->buf, (uint32 *)ctx->in); + + /* Now fill the next block with 56 bytes */ + memset(ctx->in, 0, 56); + } else { + /* Pad block to 56 bytes */ + memset(p, 0, count-8); + } + byteReverse(ctx->in, 14); + + /* Append length in bits and transform */ + ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0]; + ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1]; + + MD5Transform(ctx->buf, (uint32 *)ctx->in); + byteReverse((unsigned char *)ctx->buf, 4); + memcpy(digest, ctx->buf, 16); + memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */ +} + +/* +** Convert a 128-bit MD5 digest into a 32-digit base-16 number. +*/ +static void MD5DigestToBase16(unsigned char *digest, char *zBuf){ + static char const zEncode[] = "0123456789abcdef"; + int i, j; + + for(j=i=0; i<16; i++){ + int a = digest[i]; + zBuf[j++] = zEncode[(a>>4)&0xf]; + zBuf[j++] = zEncode[a & 0xf]; + } + zBuf[j] = 0; +} + +/* +** During testing, the special md5sum() aggregate function is available. +** inside SQLite. The following routines implement that function. +*/ +static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){ + MD5Context *p; + int i; + if( argc<1 ) return; + p = sqlite3_aggregate_context(context, sizeof(*p)); + if( p==0 ) return; + if( !p->isInit ){ + MD5Init(p); + } + for(i=0; izErr); + p->zErr = 0; + p->rc = 0; +} + +static void print_err(Error *p){ + if( p->rc!=SQLITE_OK ){ + printf("Error: (%d) \"%s\" at line %d\n", p->rc, p->zErr, p->iLine); + nGlobalErr++; + } +} + +static void print_and_free_err(Error *p){ + print_err(p); + free_err(p); +} + +static void system_error(Error *pErr, int iSys){ + pErr->rc = iSys; + pErr->zErr = (char *)sqlite3_malloc(512); + strerror_r(iSys, pErr->zErr, 512); + pErr->zErr[511] = '\0'; +} + +static void sqlite_error( + Error *pErr, + Sqlite *pDb, + const char *zFunc +){ + pErr->rc = sqlite3_errcode(pDb->db); + pErr->zErr = sqlite3_mprintf( + "sqlite3_%s() - %s (%d)", zFunc, sqlite3_errmsg(pDb->db), + sqlite3_extended_errcode(pDb->db) + ); +} + +static void test_error_x( + Error *pErr, + char *zErr +){ + if( pErr->rc==SQLITE_OK ){ + pErr->rc = 1; + pErr->zErr = zErr; + }else{ + sqlite3_free(zErr); + } +} + +static void clear_error_x( + Error *pErr, + int rc +){ + if( pErr->rc==rc ){ + pErr->rc = SQLITE_OK; + sqlite3_free(pErr->zErr); + pErr->zErr = 0; + } +} + +static int busyhandler(void *pArg, int n){ + usleep(10*1000); + return 1; +} + +static void opendb_x( + Error *pErr, /* IN/OUT: Error code */ + Sqlite *pDb, /* OUT: Database handle */ + const char *zFile, /* Database file name */ + int bDelete /* True to delete db file before opening */ +){ + if( pErr->rc==SQLITE_OK ){ + int rc; + if( bDelete ) unlink(zFile); + rc = sqlite3_open(zFile, &pDb->db); + if( rc ){ + sqlite_error(pErr, pDb, "open"); + sqlite3_close(pDb->db); + pDb->db = 0; + }else{ + sqlite3_create_function( + pDb->db, "md5sum", -1, SQLITE_UTF8, 0, 0, md5step, md5finalize + ); + sqlite3_busy_handler(pDb->db, busyhandler, 0); + sqlite3_exec(pDb->db, "PRAGMA synchronous=OFF", 0, 0, 0); + } + } +} + +static void closedb_x( + Error *pErr, /* IN/OUT: Error code */ + Sqlite *pDb /* OUT: Database handle */ +){ + int rc; + int i; + Statement *pIter; + Statement *pNext; + for(pIter=pDb->pCache; pIter; pIter=pNext){ + pNext = pIter->pNext; + sqlite3_finalize(pIter->pStmt); + sqlite3_free(pIter); + } + for(i=0; inText; i++){ + sqlite3_free(pDb->aText[i]); + } + sqlite3_free(pDb->aText); + rc = sqlite3_close(pDb->db); + if( rc && pErr->rc==SQLITE_OK ){ + pErr->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(pDb->db)); + } + memset(pDb, 0, sizeof(Sqlite)); +} + +static void sql_script_x( + Error *pErr, /* IN/OUT: Error code */ + Sqlite *pDb, /* Database handle */ + const char *zSql /* SQL script to execute */ +){ + if( pErr->rc==SQLITE_OK ){ + pErr->rc = sqlite3_exec(pDb->db, zSql, 0, 0, &pErr->zErr); + } +} + +static Statement *getSqlStatement( + Error *pErr, /* IN/OUT: Error code */ + Sqlite *pDb, /* Database handle */ + const char *zSql /* SQL statement */ +){ + Statement *pRet; + int rc; + + for(pRet=pDb->pCache; pRet; pRet=pRet->pNext){ + if( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) ){ + return pRet; + } + } + + pRet = sqlite3_malloc(sizeof(Statement)); + rc = sqlite3_prepare_v2(pDb->db, zSql, -1, &pRet->pStmt, 0); + if( rc!=SQLITE_OK ){ + sqlite_error(pErr, pDb, "prepare_v2"); + return 0; + } + assert( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) ); + + pRet->pNext = pDb->pCache; + pDb->pCache = pRet; + return pRet; +} + +static sqlite3_stmt *getAndBindSqlStatement( + Error *pErr, /* IN/OUT: Error code */ + Sqlite *pDb, /* Database handle */ + va_list ap /* SQL followed by parameters */ +){ + Statement *pStatement; /* The SQLite statement wrapper */ + sqlite3_stmt *pStmt; /* The SQLite statement to return */ + int i; /* Used to iterate through parameters */ + + pStatement = getSqlStatement(pErr, pDb, va_arg(ap, const char *)); + if( !pStatement ) return 0; + pStmt = pStatement->pStmt; + for(i=1; i<=sqlite3_bind_parameter_count(pStmt); i++){ + const char *zName = sqlite3_bind_parameter_name(pStmt, i); + void * pArg = va_arg(ap, void*); + + switch( zName[1] ){ + case 'i': + sqlite3_bind_int64(pStmt, i, *(i64 *)pArg); + break; + + default: + pErr->rc = 1; + pErr->zErr = sqlite3_mprintf("Cannot discern type: \"%s\"", zName); + pStmt = 0; + break; + } + } + + return pStmt; +} + +static i64 execsql_i64_x( + Error *pErr, /* IN/OUT: Error code */ + Sqlite *pDb, /* Database handle */ + ... /* SQL and pointers to parameter values */ +){ + i64 iRet = 0; + if( pErr->rc==SQLITE_OK ){ + sqlite3_stmt *pStmt; /* SQL statement to execute */ + va_list ap; /* ... arguments */ + int i; /* Used to iterate through parameters */ + va_start(ap, pDb); + pStmt = getAndBindSqlStatement(pErr, pDb, ap); + if( pStmt ){ + int rc; + int first = 1; + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( first && sqlite3_column_count(pStmt)>0 ){ + iRet = sqlite3_column_int64(pStmt, 0); + } + first = 0; + } + if( SQLITE_OK!=sqlite3_reset(pStmt) ){ + sqlite_error(pErr, pDb, "reset"); + } + } + va_end(ap); + } + return iRet; +} + +static char * execsql_text_x( + Error *pErr, /* IN/OUT: Error code */ + Sqlite *pDb, /* Database handle */ + int iSlot, /* Db handle slot to store text in */ + ... /* SQL and pointers to parameter values */ +){ + char *zRet = 0; + + if( iSlot>=pDb->nText ){ + int nByte = sizeof(char *)*(iSlot+1); + pDb->aText = (char **)sqlite3_realloc(pDb->aText, nByte); + memset(&pDb->aText[pDb->nText], 0, sizeof(char*)*(iSlot+1-pDb->nText)); + pDb->nText = iSlot+1; + } + + if( pErr->rc==SQLITE_OK ){ + sqlite3_stmt *pStmt; /* SQL statement to execute */ + va_list ap; /* ... arguments */ + int i; /* Used to iterate through parameters */ + va_start(ap, iSlot); + pStmt = getAndBindSqlStatement(pErr, pDb, ap); + if( pStmt ){ + int rc; + int first = 1; + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( first && sqlite3_column_count(pStmt)>0 ){ + zRet = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); + sqlite3_free(pDb->aText[iSlot]); + pDb->aText[iSlot] = zRet; + } + first = 0; + } + if( SQLITE_OK!=sqlite3_reset(pStmt) ){ + sqlite_error(pErr, pDb, "reset"); + } + } + va_end(ap); + } + + return zRet; +} + +static void integrity_check_x( + Error *pErr, /* IN/OUT: Error code */ + Sqlite *pDb /* Database handle */ +){ + if( pErr->rc==SQLITE_OK ){ + Statement *pStatement; /* Statement to execute */ + int rc; /* Return code */ + char *zErr = 0; /* Integrity check error */ + + pStatement = getSqlStatement(pErr, pDb, "PRAGMA integrity_check"); + if( pStatement ){ + sqlite3_stmt *pStmt = pStatement->pStmt; + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + const char *z = sqlite3_column_text(pStmt, 0); + if( strcmp(z, "ok") ){ + if( zErr==0 ){ + zErr = sqlite3_mprintf("%s", z); + }else{ + zErr = sqlite3_mprintf("%z\n%s", zErr, z); + } + } + } + sqlite3_reset(pStmt); + + if( zErr ){ + pErr->zErr = zErr; + pErr->rc = 1; + } + } + } +} + +static void *launch_thread_main(void *pArg){ + Thread *p = (Thread *)pArg; + return (void *)p->xProc(p->iTid, p->iArg); +} + +static void launch_thread_x( + Error *pErr, /* IN/OUT: Error code */ + Threadset *pThreads, /* Thread set */ + char *(*xProc)(int, int), /* Proc to run */ + int iArg /* Argument passed to thread proc */ +){ + if( pErr->rc==SQLITE_OK ){ + int iTid = ++pThreads->iMaxTid; + Thread *p; + int rc; + + p = (Thread *)sqlite3_malloc(sizeof(Thread)); + memset(p, 0, sizeof(Thread)); + p->iTid = iTid; + p->iArg = iArg; + p->xProc = xProc; + + rc = pthread_create(&p->tid, NULL, launch_thread_main, (void *)p); + if( rc!=0 ){ + system_error(pErr, rc); + sqlite3_free(p); + }else{ + p->pNext = pThreads->pThread; + pThreads->pThread = p; + } + } +} + +static void join_all_threads_x( + Error *pErr, /* IN/OUT: Error code */ + Threadset *pThreads /* Thread set */ +){ + Thread *p; + Thread *pNext; + for(p=pThreads->pThread; p; p=pNext){ + void *ret; + pNext = p->pNext; + int rc; + rc = pthread_join(p->tid, &ret); + if( rc!=0 ){ + if( pErr->rc==SQLITE_OK ) system_error(pErr, rc); + }else{ + printf("Thread %d says: %s\n", p->iTid, (ret==0 ? "..." : (char *)ret)); + } + sqlite3_free(p); + } + pThreads->pThread = 0; +} + +static i64 filesize_x( + Error *pErr, + const char *zFile +){ + i64 iRet = 0; + if( pErr->rc==SQLITE_OK ){ + struct stat sStat; + if( stat(zFile, &sStat) ){ + iRet = -1; + }else{ + iRet = sStat.st_size; + } + } + return iRet; +} + +static void filecopy_x( + Error *pErr, + const char *zFrom, + const char *zTo +){ + if( pErr->rc==SQLITE_OK ){ + i64 nByte = filesize_x(pErr, zFrom); + if( nByte<0 ){ + test_error_x(pErr, sqlite3_mprintf("no such file: %s", zFrom)); + }else{ + i64 iOff; + char aBuf[1024]; + int fd1; + int fd2; + unlink(zTo); + + fd1 = open(zFrom, O_RDONLY); + if( fd1<0 ){ + system_error(pErr, errno); + return; + } + fd2 = open(zTo, O_RDWR|O_CREAT|O_EXCL, 0644); + if( fd2<0 ){ + system_error(pErr, errno); + close(fd1); + return; + } + + iOff = 0; + while( iOffnByte ){ + nCopy = nByte - iOff; + } + if( nCopy!=read(fd1, aBuf, nCopy) ){ + system_error(pErr, errno); + break; + } + if( nCopy!=write(fd2, aBuf, nCopy) ){ + system_error(pErr, errno); + break; + } + iOff += nCopy; + } + + close(fd1); + close(fd2); + } + } +} + +/* +** Used by setstoptime() and timetostop(). +*/ +static double timelimit = 0.0; +static sqlite3_vfs *pTimelimitVfs = 0; + +static void setstoptime_x( + Error *pErr, /* IN/OUT: Error code */ + int nMs /* Milliseconds until "stop time" */ +){ + if( pErr->rc==SQLITE_OK ){ + double t; + int rc; + pTimelimitVfs = sqlite3_vfs_find(0); + rc = pTimelimitVfs->xCurrentTime(pTimelimitVfs, &t); + if( rc!=SQLITE_OK ){ + pErr->rc = rc; + }else{ + timelimit = t + ((double)nMs)/(1000.0*60.0*60.0*24.0); + } + } +} + +static int timetostop_x( + Error *pErr /* IN/OUT: Error code */ +){ + int ret = 1; + if( pErr->rc==SQLITE_OK ){ + double t; + int rc; + rc = pTimelimitVfs->xCurrentTime(pTimelimitVfs, &t); + if( rc!=SQLITE_OK ){ + pErr->rc = rc; + }else{ + ret = (t >= timelimit); + } + } + return ret; +} + +/* +** The "Set Error Line" macro. +*/ +#define SEL(e) ((e)->iLine = ((e)->rc ? (e)->iLine : __LINE__)) + + +/************************************************************************* +************************************************************************** +************************************************************************** +** End infrastructure. Begin tests. +*/ + +#define WALTHREAD1_NTHREAD 10 +#define WALTHREAD3_NTHREAD 6 + +static char *walthread1_thread(int iTid, int iArg){ + Error err = {0}; /* Error code and message */ + Sqlite db = {0}; /* SQLite database connection */ + int nIter = 0; /* Iterations so far */ + + opendb(&err, &db, "test.db", 0); + while( !timetostop(&err) ){ + const char *azSql[] = { + "SELECT md5sum(x) FROM t1 WHERE rowid != (SELECT max(rowid) FROM t1)", + "SELECT x FROM t1 WHERE rowid = (SELECT max(rowid) FROM t1)", + }; + char *z1, *z2, *z3; + + execsql(&err, &db, "BEGIN"); + integrity_check(&err, &db); + z1 = execsql_text(&err, &db, 1, azSql[0]); + z2 = execsql_text(&err, &db, 2, azSql[1]); + z3 = execsql_text(&err, &db, 3, azSql[0]); + execsql(&err, &db, "COMMIT"); + + if( strcmp(z1, z2) || strcmp(z1, z3) ){ + test_error(&err, "Failed read: %s %s %s", z1, z2, z3); + } + + sql_script(&err, &db, + "BEGIN;" + "INSERT INTO t1 VALUES(randomblob(100));" + "INSERT INTO t1 VALUES(randomblob(100));" + "INSERT INTO t1 SELECT md5sum(x) FROM t1;" + "COMMIT;" + ); + nIter++; + } + closedb(&err, &db); + + print_and_free_err(&err); + return sqlite3_mprintf("%d iterations", nIter); +} + +static char *walthread1_ckpt_thread(int iTid, int iArg){ + Error err = {0}; /* Error code and message */ + Sqlite db = {0}; /* SQLite database connection */ + int nCkpt = 0; /* Checkpoints so far */ + + opendb(&err, &db, "test.db", 0); + while( !timetostop(&err) ){ + usleep(500*1000); + execsql(&err, &db, "PRAGMA wal_checkpoint"); + if( err.rc==SQLITE_OK ) nCkpt++; + clear_error(&err, SQLITE_BUSY); + } + closedb(&err, &db); + + print_and_free_err(&err); + return sqlite3_mprintf("%d checkpoints", nCkpt); +} + +static void walthread1(int nMs){ + Error err = {0}; /* Error code and message */ + Sqlite db = {0}; /* SQLite database connection */ + Threadset threads = {0}; /* Test threads */ + int i; /* Iterator variable */ + + opendb(&err, &db, "test.db", 1); + sql_script(&err, &db, + "PRAGMA journal_mode = WAL;" + "CREATE TABLE t1(x PRIMARY KEY);" + "INSERT INTO t1 VALUES(randomblob(100));" + "INSERT INTO t1 VALUES(randomblob(100));" + "INSERT INTO t1 SELECT md5sum(x) FROM t1;" + ); + + setstoptime(&err, nMs); + for(i=0; i= 0); + wal_exists = (filesize(&err, "test.db-wal") >= 0); + if( (journal_exists+wal_exists)!=1 ){ + test_error(&err, "File system looks incorrect (%d, %d)", + journal_exists, wal_exists + ); + } + anTrans[journal_exists]++; + + sql_script(&err, &db, "COMMIT"); + integrity_check(&err, &db); + closedb(&err, &db); + } + + print_and_free_err(&err); + return sqlite3_mprintf("W %d R %d", anTrans[0], anTrans[1]); +} + +static void walthread2(int nMs){ + Error err = {0}; + Sqlite db = {0}; + Threadset threads = {0}; + + opendb(&err, &db, "test.db", 1); + sql_script(&err, &db, "CREATE TABLE t1(x INTEGER PRIMARY KEY, y UNIQUE)"); + closedb(&err, &db); + + setstoptime(&err, nMs); + launch_thread(&err, &threads, walthread2_thread, 0); + launch_thread(&err, &threads, walthread2_thread, 0); + launch_thread(&err, &threads, walthread2_thread, 1); + launch_thread(&err, &threads, walthread2_thread, 1); + join_all_threads(&err, &threads); + + print_and_free_err(&err); +} + +static char *walthread3_thread(int iTid, int iArg){ + Error err = {0}; /* Error code and message */ + Sqlite db = {0}; /* SQLite database connection */ + i64 iNextWrite; /* Next value this thread will write */ + + opendb(&err, &db, "test.db", 0); + sql_script(&err, &db, "PRAGMA wal_autocheckpoint = 10"); + + iNextWrite = iArg+1; + while( 1 ){ + i64 sum1; + i64 sum2; + int stop = 0; /* True to stop executing (test timed out) */ + + while( 0==(stop = timetostop(&err)) ){ + i64 iMax = execsql_i64(&err, &db, "SELECT max(cnt) FROM t1"); + if( iMax+1==iNextWrite ) break; + } + if( stop ) break; + + sum1 = execsql_i64(&err, &db, "SELECT sum(cnt) FROM t1"); + sum2 = execsql_i64(&err, &db, "SELECT sum(sum1) FROM t1"); + execsql_i64(&err, &db, + "INSERT INTO t1 VALUES(:iNextWrite, :iSum1, :iSum2)", + &iNextWrite, &sum1, &sum2 + ); + integrity_check(&err, &db); + + iNextWrite += WALTHREAD3_NTHREAD; + } + + closedb(&err, &db); + print_and_free_err(&err); + return 0; +} + +static void walthread3(int nMs){ + Error err = {0}; + Sqlite db = {0}; + Threadset threads = {0}; + int i; + + opendb(&err, &db, "test.db", 1); + sql_script(&err, &db, + "PRAGMA journal_mode = WAL;" + "CREATE TABLE t1(cnt PRIMARY KEY, sum1, sum2);" + "CREATE INDEX i1 ON t1(sum1);" + "CREATE INDEX i2 ON t1(sum2);" + "INSERT INTO t1 VALUES(0, 0, 0);" + ); + closedb(&err, &db); + + setstoptime(&err, nMs); + for(i=0; i2 ) goto usage; + if( argc==2 ){ + zTest = argv[1]; + nTest = strlen(zTest); + if( zTest[nTest-1]=='*' ){ + nTest--; + bPrefix = 1; + } + } + + sqlite3_config(SQLITE_CONFIG_MULTITHREAD); + + for(i=0; i0 ? 255 : 0); + + usage: + printf("Usage: %s [testname|testprefix*]\n", argv[0]); + printf("Available tests are:\n"); + for(i=0; i'def' ORDER BY a; + } +} {1 3} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-31338dca7e.test b/components/external/SQLite-3.8.1/test/tkt-31338dca7e.test new file mode 100644 index 0000000000000000000000000000000000000000..41dd9d3bf8e9f7dda5625278b2df08b3259d47be --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-31338dca7e.test @@ -0,0 +1,178 @@ +# 2009 December 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [31338dca7e] has been +# fixed. Ticket [31338dca7e] demonstrates problems with the OR-clause +# optimization in joins where the WHERE clause is of the form +# +# (x AND y) OR z +# +# And the x and y subterms from from different tables of the join. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-31338-1.1 { + db eval { + CREATE TABLE t1(x); + CREATE TABLE t2(y); + INSERT INTO t1 VALUES(111); + INSERT INTO t1 VALUES(222); + INSERT INTO t2 VALUES(333); + INSERT INTO t2 VALUES(444); + SELECT * FROM t1, t2 + WHERE (x=111 AND y!=444) OR x=222 + ORDER BY x, y; + } +} {111 333 222 333 222 444} + +do_test tkt-31338-1.2 { + db eval { + CREATE INDEX t1x ON t1(x); + SELECT * FROM t1, t2 + WHERE (x=111 AND y!=444) OR x=222 + ORDER BY x, y; + } +} {111 333 222 333 222 444} + +do_test tkt-31338-2.1 { + db eval { + CREATE TABLE t3(v,w); + CREATE TABLE t4(x,y); + CREATE TABLE t5(z); + INSERT INTO t3 VALUES(111,222); + INSERT INTO t3 VALUES(333,444); + INSERT INTO t4 VALUES(222,333); + INSERT INTO t4 VALUES(444,555); + INSERT INTO t5 VALUES(888); + INSERT INTO t5 VALUES(999); + + SELECT * FROM t3, t4, t5 + WHERE (v=111 AND x=w AND z!=999) OR (v=333 AND x=444) + ORDER BY v, w, x, y, z; + } +} {111 222 222 333 888 333 444 444 555 888 333 444 444 555 999} + +do_test tkt-31338-2.2 { + db eval { + CREATE INDEX t3v ON t3(v); + CREATE INDEX t4x ON t4(x); + SELECT * FROM t3, t4, t5 + WHERE (v=111 AND x=w AND z!=999) OR (v=333 AND x=444) + ORDER BY v, w, x, y, z; + } +} {111 222 222 333 888 333 444 444 555 888 333 444 444 555 999} + + +# Ticket [2c2de252666662f5459904fc33a9f2956cbff23c] +# +do_test tkt-31338-3.1 { + foreach x [db eval {SELECT name FROM sqlite_master WHERE type='table'}] { + db eval "DROP TABLE $x" + } + db eval { + CREATE TABLE t1(a,b,c,d); + CREATE TABLE t2(e,f); + INSERT INTO t1 VALUES(1,2,3,4); + INSERT INTO t2 VALUES(10,-8); + CREATE INDEX t1a ON t1(a); + CREATE INDEX t1b ON t1(b); + CREATE TABLE t3(g); + INSERT INTO t3 VALUES(4); + CREATE TABLE t4(h); + INSERT INTO t4 VALUES(5); + + SELECT * FROM t3 LEFT JOIN t1 ON d=g LEFT JOIN t4 ON c=h + WHERE (a=1 AND h=4) + OR (b IN ( + SELECT x FROM (SELECT e+f AS x, e FROM t2 ORDER BY 1 LIMIT 2) + GROUP BY e + )); + } +} {4 1 2 3 4 {}} +do_test tkt-31338-3.2 { + db eval { + SELECT * FROM t3 LEFT JOIN t1 ON d=g LEFT JOIN t4 ON c=h + WHERE (a=1 AND h=4) + OR (b=2 AND b NOT IN ( + SELECT x+1 FROM (SELECT e+f AS x, e FROM t2 ORDER BY 1 LIMIT 2) + GROUP BY e + )); + } +} {4 1 2 3 4 {}} +do_test tkt-31338-3.3 { + db eval { + SELECT * FROM t3 LEFT JOIN t1 ON d=g LEFT JOIN t4 ON c=h + WHERE (+a=1 AND h=4) + OR (b IN ( + SELECT x FROM (SELECT e+f AS x, e FROM t2 ORDER BY 1 LIMIT 2) + GROUP BY e + )); + } +} {4 1 2 3 4 {}} +do_test tkt-31338-3.4 { + db eval { + SELECT * FROM t3 LEFT JOIN t1 ON d=g LEFT JOIN t4 ON c=h + WHERE (a=1 AND h=4) + OR (+b IN ( + SELECT x FROM (SELECT e+f AS x, e FROM t2 ORDER BY 1 LIMIT 2) + GROUP BY e + )); + } +} {4 1 2 3 4 {}} + +do_test tkt-31338-3.5 { + db eval { + CREATE TABLE t5(a,b,c,d,e,f); + CREATE TABLE t6(g,h); + CREATE TRIGGER t6r AFTER INSERT ON t6 BEGIN + INSERT INTO t5 + SELECT * FROM t3 LEFT JOIN t1 ON d=g LEFT JOIN t4 ON c=h + WHERE (a=1 AND h=4) + OR (b IN ( + SELECT x FROM (SELECT e+f AS x, e FROM t2 ORDER BY 1 LIMIT 2) + GROUP BY e + )); + END; + INSERT INTO t6 VALUES(88,99); + SELECT * FROM t5; + } +} {4 1 2 3 4 {}} + +do_test tkt-31338-3.6 { + db eval { + INSERT INTO t1 VALUES(2,4,3,4); + INSERT INTO t1 VALUES(99,101,3,4); + INSERT INTO t1 VALUES(98,97,3,4); + SELECT * FROM t3 LEFT JOIN t1 ON d=g LEFT JOIN t4 ON c=h + WHERE (a=1 AND h=4) + OR (b IN ( + SELECT x+a FROM (SELECT e+f AS x, e FROM t2 ORDER BY 1 LIMIT 2) + GROUP BY e + )); + } +} {4 2 4 3 4 {} 4 99 101 3 4 {}} + +do_test tkt-31338-3.7 { + db eval { + SELECT * FROM t3 LEFT JOIN t1 ON d=g LEFT JOIN t4 ON c=h + WHERE (a=1 AND h=4) + OR (b IN ( + SELECT x FROM (SELECT e+f+a AS x, e FROM t2 ORDER BY 1 LIMIT 2) + GROUP BY e + )); + } +} {4 2 4 3 4 {} 4 99 101 3 4 {}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-313723c356.test b/components/external/SQLite-3.8.1/test/tkt-313723c356.test new file mode 100644 index 0000000000000000000000000000000000000000..8c08c349761535bfebd67d057f3a3be4ac569bfd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-313723c356.test @@ -0,0 +1,57 @@ +# 2010 September 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [313723c356] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +ifcapable !wal { finish_test ; return } + +do_execsql_test tkt-313723c356.1 { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(randomblob(400), randomblob(400)); + INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1; + INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1; + INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1; + INSERT INTO t1 SELECT randomblob(400), randomblob(400) FROM t1; +} {wal} +faultsim_save_and_close + +do_faultsim_test tkt-313723c356.2 -faults shmerr* -prep { + faultsim_restore_and_reopen + sqlite3 db2 test.db + db eval { SELECT * FROM t1 } + db2 eval { UPDATE t1 SET a = randomblob(399) } + db2 close +} -body { + # At this point, the cache contains all of table t1 and none of index i1. The + # cache is out of date. When the bug existed and the right xShmLock() fails + # in the following statement, the internal cache of the WAL header was + # being updated, but the contents of the page-cache not flushed. This causes + # the integrity-check in the "-test" code to fail, as it is comparing the + # cached (out-of-date) version of table t1 with the on disk (up-to-date) + # version of index i1. + # + execsql { SELECT min(rowid) FROM t1 } +} -test { + faultsim_test_result {0 1} + faultsim_integrity_check +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-385a5b56b9.test b/components/external/SQLite-3.8.1/test/tkt-385a5b56b9.test new file mode 100644 index 0000000000000000000000000000000000000000..1338435ed68d6f0db50cf5cd0e8e013560bc295a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-385a5b56b9.test @@ -0,0 +1,53 @@ +# 2012 April 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# The tests in this file were used while developing the SQLite 4 code. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix tkt-385a5b56b9 + +do_execsql_test 1.0 { + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(1, NULL); + INSERT INTO t1 VALUES(2, NULL); + INSERT INTO t1 VALUES(1, NULL); +} + +do_execsql_test 1.1 { SELECT DISTINCT x, y FROM t1 } {1 {} 2 {}} +do_execsql_test 1.2 { CREATE UNIQUE INDEX i1 ON t1(x, y) } +do_execsql_test 1.3 { SELECT DISTINCT x, y FROM t1 } {1 {} 2 {}} + + +#------------------------------------------------------------------------- + +do_execsql_test 2.0 { + CREATE TABLE t2(x, y NOT NULL); + CREATE UNIQUE INDEX t2x ON t2(x); + CREATE UNIQUE INDEX t2y ON t2(y); +} + +do_eqp_test 2.1 { SELECT DISTINCT x FROM t2 } { + 0 0 0 {SCAN TABLE t2 USING COVERING INDEX t2x} +} + +do_eqp_test 2.2 { SELECT DISTINCT y FROM t2 } { + 0 0 0 {SCAN TABLE t2 USING COVERING INDEX t2y} +} + +do_eqp_test 2.3 { SELECT DISTINCT x, y FROM t2 WHERE y=10 } { + 0 0 0 {SEARCH TABLE t2 USING INDEX t2y (y=?)} +} + +do_eqp_test 2.4 { SELECT DISTINCT x, y FROM t2 WHERE x=10 } { + 0 0 0 {SEARCH TABLE t2 USING INDEX t2x (x=?)} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-38cb5df375.test b/components/external/SQLite-3.8.1/test/tkt-38cb5df375.test new file mode 100644 index 0000000000000000000000000000000000000000..e5e02671b76d7e97b1c2ae953d3972eb9a7b5a32 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-38cb5df375.test @@ -0,0 +1,326 @@ +# 2010 October 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [38cb5df375078d3f9711482d2a1615d09f6b3f33] has +# been resolved. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_test tkt-38cb5df375.0 { + execsql { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 SELECT a+2 FROM t1; + INSERT INTO t1 SELECT a+4 FROM t1; + } +} {} + +foreach ii {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} { + do_test tkt-38cb5df375.1.$ii { + execsql { + SELECT * FROM (SELECT * FROM t1 ORDER BY a) + UNION ALL SELECT 9 FROM (SELECT a FROM t1) + LIMIT $::ii; + } + } [lrange {1 2 3 4 5 6 7 8 9 9 9 9 9 9 9 9} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} { + do_test tkt-38cb5df375.2.$ii { + execsql { + SELECT 9 FROM (SELECT * FROM t1) + UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a) + LIMIT $::ii; + } + } [lrange {9 9 9 9 9 9 9 9 1 2 3 4 5 6 7 8} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} { + do_test tkt-38cb5df375.3.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a) + UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a) + LIMIT $::ii; + } + } [lrange {1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} { + do_test tkt-38cb5df375.4.$ii { + execsql { + SELECT 0 FROM (SELECT * FROM t1) + UNION ALL SELECT 9 FROM (SELECT a FROM t1) + LIMIT $::ii; + } + } [lrange {0 0 0 0 0 0 0 0 9 9 9 9 9 9 9 9} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4} { + do_test tkt-38cb5df375.5.$ii { + execsql { + SELECT 0 FROM (SELECT * FROM t1) + UNION SELECT 9 FROM (SELECT a FROM t1) + LIMIT $::ii; + } + } [lrange {0 9} 0 [expr {$ii-1}]] +} + +foreach ii {1 2 3 4 5 6 7 8 9 10 11} { + do_test tkt-38cb5df375.11.$ii { + execsql { + SELECT * FROM (SELECT * FROM t1 ORDER BY a LIMIT 3) + UNION ALL SELECT 9 FROM (SELECT a FROM t1) + LIMIT $::ii; + } + } [lrange {1 2 3 9 9 9 9 9 9 9 9} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9 10 11} { + do_test tkt-38cb5df375.12.$ii { + execsql { + SELECT 9 FROM (SELECT * FROM t1) + UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a LIMIT 3) + LIMIT $::ii; + } + } [lrange {9 9 9 9 9 9 9 9 1 2 3} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6} { + do_test tkt-38cb5df375.13.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 3) + UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a LIMIT 3) + LIMIT $::ii; + } + } [lrange {1 2 3 1 2 3} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6} { + do_test tkt-38cb5df375.14.$ii { + execsql { + SELECT 0 FROM (SELECT * FROM t1 LIMIT 3) + UNION ALL SELECT 9 FROM (SELECT a FROM t1 LIMIT 3) + LIMIT $::ii; + } + } [lrange {0 0 0 9 9 9} 0 [expr {$ii-1}]] +} + +foreach ii {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} { + do_test tkt-38cb5df375.21.$ii { + execsql { + SELECT * FROM (SELECT * FROM t1 ORDER BY a) + UNION ALL SELECT 9 FROM (SELECT a FROM t1) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2 3 4 5 6 7 8 9 9 9 9 9 9 9 9} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} { + do_test tkt-38cb5df375.22.$ii { + execsql { + SELECT 9 FROM (SELECT * FROM t1) + UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2 3 4 5 6 7 8 9 9 9 9 9 9 9 9} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} { + do_test tkt-38cb5df375.23.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a) + UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a) + ORDER BY 1 DESC + LIMIT $::ii; + } + } [lrange {8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} { + do_test tkt-38cb5df375.24.$ii { + execsql { + SELECT 0 FROM (SELECT * FROM t1) + UNION ALL SELECT 9 FROM (SELECT a FROM t1) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {0 0 0 0 0 0 0 0 9 9 9 9 9 9 9 9} 0 [expr {$ii-1}]] +} + +foreach ii {1 2 3 4 5 6 7 8 9 10 11} { + do_test tkt-38cb5df375.31.$ii { + execsql { + SELECT * FROM (SELECT * FROM t1 ORDER BY a LIMIT 3) + UNION ALL SELECT 9 FROM (SELECT a FROM t1) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2 3 9 9 9 9 9 9 9 9} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9 10 11} { + do_test tkt-38cb5df375.32.$ii { + execsql { + SELECT 9 FROM (SELECT * FROM t1) + UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a LIMIT 3) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2 3 9 9 9 9 9 9 9 9} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.33.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 4) + UNION ALL SELECT 90+a FROM (SELECT a FROM t1 ORDER BY a LIMIT 3) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2 3 4 91 92 93} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.34.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 2) + UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a LIMIT 5) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 1 2 2 3 4 5} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.35.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 5) + UNION ALL SELECT a FROM (SELECT a FROM t1 ORDER BY a LIMIT 2) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 1 2 2 3 4 5} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.35b.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 5) + UNION ALL SELECT a+10 FROM (SELECT a FROM t1 ORDER BY a LIMIT 2) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2 3 4 5 11 12} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.35c.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 5) + UNION SELECT a+10 FROM (SELECT a FROM t1 ORDER BY a LIMIT 2) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2 3 4 5 11 12} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.35d.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 5) + INTERSECT SELECT a FROM (SELECT a FROM t1 ORDER BY a LIMIT 2) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.35e.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 5) + EXCEPT SELECT a FROM (SELECT a FROM t1 ORDER BY a LIMIT 2) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {3 4 5} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.36.$ii { + execsql { + SELECT 0 FROM (SELECT * FROM t1 LIMIT 3) + UNION ALL SELECT 9 FROM (SELECT a FROM t1 LIMIT 4) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {0 0 0 9 9 9 9} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.37.$ii { + execsql { + SELECT 0 FROM (SELECT * FROM t1 LIMIT 3) + UNION SELECT 9 FROM (SELECT a FROM t1 LIMIT 4) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {0 9} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7} { + do_test tkt-38cb5df375.38.$ii { + execsql { + SELECT 0 FROM (SELECT * FROM t1 LIMIT 3) + EXCEPT SELECT 9 FROM (SELECT a FROM t1 LIMIT 4) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {0} 0 [expr {$ii-1}]] +} + +foreach ii {1 2 3 4 5 6 7 8 9} { + do_test tkt-38cb5df375.41.$ii { + execsql { + SELECT 0 FROM (SELECT * FROM t1 LIMIT 3) + UNION ALL SELECT 9 FROM (SELECT a FROM t1 LIMIT 4) + UNION ALL SELECT 88 FROM (SELECT a FROM t1 LIMIT 2) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {0 0 0 9 9 9 9 88 88} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9} { + do_test tkt-38cb5df375.42.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 3) + UNION ALL SELECT a+10 FROM (SELECT a FROM t1 ORDER BY a LIMIT 4) + UNION ALL SELECT a+20 FROM (SELECT a FROM t1 ORDER BY a LIMIT 2) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2 3 11 12 13 14 21 22} 0 [expr {$ii-1}]] +} +foreach ii {1 2 3 4 5 6 7 8 9} { + do_test tkt-38cb5df375.43.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a LIMIT 3) + UNION SELECT a+10 FROM (SELECT a FROM t1 ORDER BY a LIMIT 4) + UNION SELECT a+20 FROM (SELECT a FROM t1 ORDER BY a LIMIT 2) + ORDER BY 1 + LIMIT $::ii; + } + } [lrange {1 2 3 11 12 13 14 21 22} 0 [expr {$ii-1}]] +} + +foreach ii {1 2 3 4 5 6 7} { + set jj [expr {7-$ii}] + do_test tkt-38cb5df375.51.$ii { + execsql { + SELECT a FROM (SELECT * FROM t1 ORDER BY a) + EXCEPT SELECT a FROM (SELECT a FROM t1 ORDER BY a LIMIT $::ii) + ORDER BY a DESC + LIMIT $::jj; + } + } [lrange {8 7 6 5 4 3 2 1} 0 [expr {$jj-1}]] +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-3998683a16.test b/components/external/SQLite-3.8.1/test/tkt-3998683a16.test new file mode 100644 index 0000000000000000000000000000000000000000..919dc23368c434f0f824a8bff6bae091253c5988 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-3998683a16.test @@ -0,0 +1,46 @@ +# 2010 September 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [3998683a16a7076e08f5585c1f4816414c8c653a] where in +# floating point values with a decimal point at the beginning or end +# of the mantissa are used. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-3998683a16.1 { + db eval { + CREATE TABLE t1(x, y REAL); + INSERT INTO t1 VALUES(1, '1.0'); + INSERT INTO t1 VALUES(2, '.125'); + INSERT INTO t1 VALUES(3, '123.'); + INSERT INTO t1 VALUES(4, '123.e+2'); + INSERT INTO t1 VALUES(5, '.125e+3'); + INSERT INTO t1 VALUES(6, '123e4'); + INSERT INTO t1 VALUES(11, ' 1.0'); + INSERT INTO t1 VALUES(12, ' .125'); + INSERT INTO t1 VALUES(13, ' 123.'); + INSERT INTO t1 VALUES(14, ' 123.e+2'); + INSERT INTO t1 VALUES(15, ' .125e+3'); + INSERT INTO t1 VALUES(16, ' 123e4'); + INSERT INTO t1 VALUES(21, '1.0 '); + INSERT INTO t1 VALUES(22, '.125 '); + INSERT INTO t1 VALUES(23, '123. '); + INSERT INTO t1 VALUES(24, '123.e+2 '); + INSERT INTO t1 VALUES(25, '.125e+3 '); + INSERT INTO t1 VALUES(26, '123e4 '); + SELECT x FROM t1 WHERE typeof(y)=='real' ORDER BY x; + } +} {1 2 3 4 5 6 11 12 13 14 15 16 21 22 23 24 25 26} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-3a77c9714e.test b/components/external/SQLite-3.8.1/test/tkt-3a77c9714e.test new file mode 100644 index 0000000000000000000000000000000000000000..b7d366f36e8bc21c5095d0173b7b2ae039efcdfc --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-3a77c9714e.test @@ -0,0 +1,72 @@ +# 2011 December 06 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [3a77c9714e] has been +# fixed. + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +set testprefix "tkt-3a77c9714e" + +do_execsql_test 1.1 { + CREATE TABLE t1(t1_id INTEGER PRIMARY KEY, t1_title TEXT); + CREATE TABLE t2(t2_id INTEGER PRIMARY KEY, t2_title TEXT); + CREATE TABLE t3(t3_id INTEGER PRIMARY KEY, t3_title TEXT); + + INSERT INTO t1 (t1_id, t1_title) VALUES (888, 'ABCDEF'); + INSERT INTO t2 (t2_id, t2_title) VALUES (999, 'ABCDEF'); + INSERT INTO t3 (t3_id, t3_title) VALUES (999, 'ABCDEF'); +} + +do_execsql_test 1.2 { + SELECT t1_title, t2_title + FROM t1 LEFT JOIN t2 + WHERE + t2_id = (SELECT t3_id FROM + ( SELECT t3_id FROM t3 WHERE t3_title=t1_title LIMIT 500 ) + ) +} {ABCDEF ABCDEF} + +do_execsql_test 2.1 { + CREATE TABLE [Beginnings] ( + [Id] INTEGER PRIMARY KEY AUTOINCREMENT,[Title] TEXT, [EndingId] INTEGER + ); + CREATE TABLE [Endings] (Id INT,Title TEXT,EndingId INT); + INSERT INTO Beginnings (Id, Title, EndingId) VALUES (1, 'FACTOR', 18); + INSERT INTO Beginnings (Id, Title, EndingId) VALUES (2, 'SWIMM', 18); + INSERT INTO Endings (Id, Title, EndingId) VALUES (1, 'ING', 18); +} + +do_execsql_test 2.2 { + SELECT + SrcWord, Beginnings.Title + FROM + (SELECT 'FACTORING' AS SrcWord UNION SELECT 'SWIMMING' AS SrcWord ) + LEFT JOIN + Beginnings + WHERE Beginnings.Id= ( + SELECT BeginningId FROM ( + SELECT SrcWord, B.Id as BeginningId, B.Title || E.Title As Connected + FROM Beginnings B LEFT JOIN Endings E ON B.EndingId=E.EndingId + WHERE Connected=SrcWord LIMIT 1 + ) + ) +} {FACTORING FACTOR SWIMMING SWIMM} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-3fe897352e.test b/components/external/SQLite-3.8.1/test/tkt-3fe897352e.test new file mode 100644 index 0000000000000000000000000000000000000000..bc2b2033e70c7d19d876de04fdac90c8387544b3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-3fe897352e.test @@ -0,0 +1,60 @@ +# 2009 October 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [3fe897352e8d8] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# The following tests use hex_to_utf16be() and hex_to_utf16le() which +# which are only available if SQLite is built with UTF16 support. +ifcapable {!utf16} { + finish_test + return +} + +do_test tkt-3fe89-1.1 { + db close + sqlite3 db :memory: + db eval { + PRAGMA encoding=UTF8; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(hex_to_utf16be('D800')); + SELECT hex(x) FROM t1; + } +} {EDA080} +do_test tkt-3fe89-1.2 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES(hex_to_utf16le('00D8')); + SELECT hex(x) FROM t1; + } +} {EDA080} +do_test tkt-3fe89-1.3 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES(hex_to_utf16be('DFFF')); + SELECT hex(x) FROM t1; + } +} {EDBFBF} +do_test tkt-3fe89-1.4 { + db eval { + DELETE FROM t1; + INSERT INTO t1 VALUES(hex_to_utf16le('FFDF')); + SELECT hex(x) FROM t1; + } +} {EDBFBF} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-4a03edc4c8.test b/components/external/SQLite-3.8.1/test/tkt-4a03edc4c8.test new file mode 100644 index 0000000000000000000000000000000000000000..649f27d22bcee17dd0a89d99b7023bdb59fbf166 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-4a03edc4c8.test @@ -0,0 +1,46 @@ +# 2009 September 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that +# ticket [4a03edc4c8c028c93e9269f64fc5e97f632c1166] has been fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-4a03ed-1.1 { + db eval { + CREATE TABLE t1( + a INTEGER PRIMARY KEY ON CONFLICT REPLACE, + b UNIQUE ON CONFLICT FAIL + ); + INSERT INTO t1 VALUES(1, 1); + INSERT INTO t1 VALUES(2, 2); + } + catchsql { + BEGIN; + INSERT INTO t1 VALUES(1, 2); + COMMIT; + } +} {1 {column b is not unique}} +do_test tkt-4a03ed-1.2 { + db eval { + PRAGMA integrity_check; + } +} {ok} +do_test tkt-4a03ed-1.3 { + db eval { + SELECT * FROM t1 ORDER BY a; + } +} {1 1 2 2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-4dd95f6943.test b/components/external/SQLite-3.8.1/test/tkt-4dd95f6943.test new file mode 100644 index 0000000000000000000000000000000000000000..353031e74e3dc8831ff96d4a979b4fbd99ffac40 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-4dd95f6943.test @@ -0,0 +1,151 @@ +# 2013 March 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix tkt-4dd95f6943 + +do_execsql_test 1.0 { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES (3), (4), (2), (1), (5), (6); +} + +foreach {tn1 idx} { + 1 { CREATE INDEX i1 ON t1(x ASC) } + 2 { CREATE INDEX i1 ON t1(x DESC) } +} { + do_execsql_test 1.$tn1.1 { DROP INDEX IF EXISTS i1; } + do_execsql_test 1.$tn1.2 $idx + + do_execsql_test 1.$tn1.3 { + SELECT x FROM t1 WHERE x IN(2, 4, 5) ORDER BY x ASC; + } {2 4 5} + + do_execsql_test 1.$tn1.4 { + SELECT x FROM t1 WHERE x IN(2, 4, 5) ORDER BY x DESC; + } {5 4 2} +} + + +do_execsql_test 2.0 { + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES (5, 3), (5, 4), (5, 2), (5, 1), (5, 5), (5, 6); + INSERT INTO t2 VALUES (1, 3), (1, 4), (1, 2), (1, 1), (1, 5), (1, 6); + INSERT INTO t2 VALUES (3, 3), (3, 4), (3, 2), (3, 1), (3, 5), (3, 6); + INSERT INTO t2 VALUES (2, 3), (2, 4), (2, 2), (2, 1), (2, 5), (2, 6); + INSERT INTO t2 VALUES (4, 3), (4, 4), (4, 2), (4, 1), (4, 5), (4, 6); + INSERT INTO t2 VALUES (6, 3), (6, 4), (6, 2), (6, 1), (6, 5), (6, 6); + + CREATE TABLE t3(a, b); + INSERT INTO t3 VALUES (2, 2), (4, 4), (5, 5); + CREATE UNIQUE INDEX t3i1 ON t3(a ASC); + CREATE UNIQUE INDEX t3i2 ON t3(b DESC); +} + +foreach {tn1 idx} { + 1 { CREATE INDEX i1 ON t2(x ASC, y ASC) } + 2 { CREATE INDEX i1 ON t2(x ASC, y DESC) } + 3 { CREATE INDEX i1 ON t2(x DESC, y ASC) } + 4 { CREATE INDEX i1 ON t2(x DESC, y DESC) } + + 5 { CREATE INDEX i1 ON t2(y ASC, x ASC) } + 6 { CREATE INDEX i1 ON t2(y ASC, x DESC) } + 7 { CREATE INDEX i1 ON t2(y DESC, x ASC) } + 8 { CREATE INDEX i1 ON t2(y DESC, x DESC) } +} { + do_execsql_test 2.$tn1.1 { DROP INDEX IF EXISTS i1; } + do_execsql_test 2.$tn1.2 $idx + + foreach {tn2 inexpr} { + 3 "(2, 4, 5)" + 4 "(SELECT a FROM t3)" + 5 "(SELECT b FROM t3)" + } { + do_execsql_test 2.$tn1.$tn2.1 " + SELECT x, y FROM t2 WHERE x = 1 AND y IN $inexpr ORDER BY x ASC, y ASC; + " {1 2 1 4 1 5} + + do_execsql_test 2.$tn1.$tn2.2 " + SELECT x, y FROM t2 WHERE x = 2 AND y IN $inexpr ORDER BY x ASC, y DESC; + " {2 5 2 4 2 2} + + do_execsql_test 2.$tn1.$tn2.3 " + SELECT x, y FROM t2 WHERE x = 3 AND y IN $inexpr ORDER BY x DESC, y ASC; + " {3 2 3 4 3 5} + + do_execsql_test 2.$tn1.$tn2.4 " + SELECT x, y FROM t2 WHERE x = 4 AND y IN $inexpr ORDER BY x DESC, y DESC; + " {4 5 4 4 4 2} + + do_execsql_test 2.$tn1.$tn2.5 " + SELECT a, x, y FROM t2, t3 WHERE a = 4 AND x = 1 AND y IN $inexpr + ORDER BY a, x ASC, y ASC; + " {4 1 2 4 1 4 4 1 5} + do_execsql_test 2.$tn1.$tn2.6 " + SELECT a, x, y FROM t2, t3 WHERE a = 2 AND x = 1 AND y IN $inexpr + ORDER BY x ASC, y ASC; + " {2 1 2 2 1 4 2 1 5} + + do_execsql_test 2.$tn1.$tn2.7 " + SELECT a, x, y FROM t2, t3 WHERE a = 4 AND x = 1 AND y IN $inexpr + ORDER BY a, x ASC, y DESC; + " {4 1 5 4 1 4 4 1 2} + do_execsql_test 2.$tn1.8 " + SELECT a, x, y FROM t2, t3 WHERE a = 2 AND x = 1 AND y IN $inexpr + ORDER BY x ASC, y DESC; + " {2 1 5 2 1 4 2 1 2} + + do_execsql_test 2.$tn1.$tn2.9 " + SELECT a, x, y FROM t2, t3 WHERE a = 4 AND x = 1 AND y IN $inexpr + ORDER BY a, x DESC, y ASC; + " {4 1 2 4 1 4 4 1 5} + do_execsql_test 2.$tn1.10 " + SELECT a, x, y FROM t2, t3 WHERE a = 2 AND x = 1 AND y IN $inexpr + ORDER BY x DESC, y ASC; + " {2 1 2 2 1 4 2 1 5} + + do_execsql_test 2.$tn1.$tn2.11 " + SELECT a, x, y FROM t2, t3 WHERE a = 4 AND x = 1 AND y IN $inexpr + ORDER BY a, x DESC, y DESC; + " {4 1 5 4 1 4 4 1 2} + do_execsql_test 2.$tn1.$tn2.12 " + SELECT a, x, y FROM t2, t3 WHERE a = 2 AND x = 1 AND y IN $inexpr + ORDER BY x DESC, y DESC; + " {2 1 5 2 1 4 2 1 2} + } +} + +do_execsql_test 3.0 { + CREATE TABLE t7(x); + INSERT INTO t7 VALUES (1), (2), (3); + CREATE INDEX i7 ON t7(x); + + CREATE TABLE t8(y); + INSERT INTO t8 VALUES (1), (2), (3); +} + +foreach {tn idxdir sortdir sortdata} { + 1 ASC ASC {1 2 3} + 2 ASC DESC {3 2 1} + 3 DESC ASC {1 2 3} + 4 ASC DESC {3 2 1} +} { + + do_execsql_test 3.$tn " + DROP INDEX IF EXISTS i8; + CREATE UNIQUE INDEX i8 ON t8(y $idxdir); + SELECT x FROM t7 WHERE x IN (SELECT y FROM t8) ORDER BY x $sortdir; + " $sortdata +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-54844eea3f.test b/components/external/SQLite-3.8.1/test/tkt-54844eea3f.test new file mode 100644 index 0000000000000000000000000000000000000000..7b04f6935d0710c00c32f419ba3fcc2c178a347b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-54844eea3f.test @@ -0,0 +1,67 @@ +# 2011 July 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that bug [54844eea3f] has been fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set ::testprefix tkt-54844eea3f + +do_test 1.0 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(4); + + CREATE TABLE t2(b INTEGER PRIMARY KEY); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(2); + INSERT INTO t2 SELECT b+2 FROM t2; + INSERT INTO t2 SELECT b+4 FROM t2; + INSERT INTO t2 SELECT b+8 FROM t2; + INSERT INTO t2 SELECT b+16 FROM t2; + + CREATE TABLE t3(c INTEGER PRIMARY KEY); + INSERT INTO t3 VALUES(1); + INSERT INTO t3 VALUES(2); + INSERT INTO t3 VALUES(3); + } +} {} + +do_test 1.1 { + execsql { + SELECT 'test-2', t3.c, ( + SELECT count(*) + FROM t1 JOIN (SELECT DISTINCT t3.c AS p FROM t2) AS x ON t1.a=x.p + ) + FROM t3; + } +} {test-2 1 1 test-2 2 0 test-2 3 0} + +do_test 1.2 { + execsql { + CREATE TABLE t4(a, b, c); + INSERT INTO t4 VALUES('a', 1, 'one'); + INSERT INTO t4 VALUES('a', 2, 'two'); + INSERT INTO t4 VALUES('b', 1, 'three'); + INSERT INTO t4 VALUES('b', 2, 'four'); + SELECT ( + SELECT c FROM ( + SELECT * FROM t4 WHERE a=out.a ORDER BY b LIMIT 10 OFFSET 1 + ) WHERE b=out.b + ) FROM t4 AS out; + } +} {{} two {} four} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-5d863f876e.test b/components/external/SQLite-3.8.1/test/tkt-5d863f876e.test new file mode 100644 index 0000000000000000000000000000000000000000..86024e300b06392eb2eec604b8f953793c124dd3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-5d863f876e.test @@ -0,0 +1,55 @@ +# 2011 January 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [5d863f876e] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +set ::testprefix tkt-5d863f876e +ifcapable !wal {finish_test ; return } + +do_multiclient_test tn { + do_test $tn.1 { + sql1 { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + PRAGMA journal_mode = WAL; + VACUUM; + PRAGMA journal_mode = DELETE; + } + } {wal delete} + + do_test $tn.2 { + sql2 { SELECT * FROM t1 } + } {1 2 3 4} + + do_test $tn.3 { + sql1 { + INSERT INTO t1 VALUES(5, 6); + PRAGMA journal_mode = WAL; + VACUUM; + PRAGMA journal_mode = DELETE; + } + } {wal delete} + + do_test $tn.2 { + sql2 { PRAGMA integrity_check } + } {ok} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-5e10420e8d.test b/components/external/SQLite-3.8.1/test/tkt-5e10420e8d.test new file mode 100644 index 0000000000000000000000000000000000000000..a2dfefdb0b6a3bdab639b3c4887defebf8fad73f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-5e10420e8d.test @@ -0,0 +1,50 @@ +# 2010 August 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_execsql_test tkt-5e10420e8d.1 { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = incremental; + + CREATE TABLE t1(x); + CREATE TABLE t2(x); + CREATE TABLE t3(x); +} {} + +do_execsql_test tkt-5e10420e8d.2 { + INSERT INTO t3 VALUES(randomblob(500 + 1024*248)); + INSERT INTO t1 VALUES(randomblob(1500)); + INSERT INTO t2 VALUES(randomblob(500 + 1024*248)); + + DELETE FROM t3; + DELETE FROM t2; + DELETE FROM t1; +} {} + +do_execsql_test tkt-5e10420e8d.3 { + PRAGMA incremental_vacuum(248) +} {} + +do_execsql_test tkt-5e10420e8d.4 { + PRAGMA incremental_vacuum(1) +} {} + +db close +sqlite3 db test.db + +do_execsql_test tkt-5e10420e8d.5 { + PRAGMA integrity_check; +} {ok} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-5ee23731f.test b/components/external/SQLite-3.8.1/test/tkt-5ee23731f.test new file mode 100644 index 0000000000000000000000000000000000000000..761382a4d1311848d67aa7578d0d70297baa590a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-5ee23731f.test @@ -0,0 +1,42 @@ +# 2009 October 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [5ee23731f15] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-5ee237-1.1 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + CREATE TABLE t1(x UNIQUE); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 SELECT x+2 FROM t1; + INSERT INTO t1 SELECT x+4 FROM t1; + INSERT INTO t1 SELECT x+8 FROM t1; + } + db close + sqlite3 db test.db -readonly 1 + set rc [catch { + db eval {SELECT rowid, x FROM t1 ORDER BY x} { + db eval {UPDATE t1 SET x=x+1 WHERE rowid=:rowid} + } + } msg] + lappend rc $msg +} {1 {attempt to write a readonly database}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-6bfb98dfc0.test b/components/external/SQLite-3.8.1/test/tkt-6bfb98dfc0.test new file mode 100644 index 0000000000000000000000000000000000000000..675a3fc2e9fe7db1708e44152d06af6f5794cb82 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-6bfb98dfc0.test @@ -0,0 +1,61 @@ +# 2013 March 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [6bfb98dfc0] +# +# The final INSERT in the script below reports that the database is +# corrupt (SQLITE_CORRUPT) and aborts even though the database is not +# corrupt. +# +# PRAGMA page_size=512; +# CREATE TABLE t1(x INTEGER PRIMARY KEY, y); +# INSERT INTO t1 VALUES(1,randomblob(400)); +# INSERT INTO t1 VALUES(2,randomblob(400)); +# INSERT INTO t1 SELECT x+2, randomblob(400) FROM t1; +# INSERT INTO t1 SELECT x+4, randomblob(400) FROM t1; +# INSERT INTO t1 SELECT x+8, randomblob(400) FROM t1; +# INSERT INTO t1 SELECT x+16, randomblob(400) FROM t1; +# INSERT INTO t1 SELECT x+32, randomblob(400) FROM t1; +# INSERT INTO t1 SELECT x+64, randomblob(400) FROM t1 WHERE x<10; +# CREATE TRIGGER r1 AFTER INSERT ON t1 WHEN new.x=74 BEGIN +# DELETE FROM t1; +# INSERT INTO t1 VALUES(75, randomblob(400)); +# INSERT INTO t1 VALUES(76, randomblob(400)); +# END; +# INSERT INTO t1 VALUES(74, randomblob(400)); +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-6bfb98dfc0.100 { + db eval { + PRAGMA page_size=512; + CREATE TABLE t1(x INTEGER PRIMARY KEY, y); + INSERT INTO t1 VALUES(1,randomblob(400)); + INSERT INTO t1 VALUES(2,randomblob(400)); + INSERT INTO t1 SELECT x+2, randomblob(400) FROM t1; + INSERT INTO t1 SELECT x+4, randomblob(400) FROM t1; + INSERT INTO t1 SELECT x+8, randomblob(400) FROM t1; + INSERT INTO t1 SELECT x+16, randomblob(400) FROM t1; + INSERT INTO t1 SELECT x+32, randomblob(400) FROM t1; + INSERT INTO t1 SELECT x+64, randomblob(400) FROM t1 WHERE x<10; + CREATE TRIGGER r1 AFTER INSERT ON t1 WHEN new.x=74 BEGIN + DELETE FROM t1; + INSERT INTO t1 VALUES(75, randomblob(400)); + INSERT INTO t1 VALUES(76, randomblob(400)); + END; + INSERT INTO t1 VALUES(74, randomblob(400)); + SELECT x, length(y) FROM t1 ORDER BY x; + } +} {75 400 76 400} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-752e1646fc.test b/components/external/SQLite-3.8.1/test/tkt-752e1646fc.test new file mode 100644 index 0000000000000000000000000000000000000000..3837df8664ead2af7bd34b715b0dfb3068cfb547 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-752e1646fc.test @@ -0,0 +1,30 @@ +# 2010 April 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [752e1646fc] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-752e1646fc-1.1 { + execsql { + CREATE TABLE "test" ("letter" VARCHAR(1) PRIMARY KEY, "number" INTEGER NOT NULL); + INSERT INTO "test" ("letter", "number") VALUES('b', 1); + INSERT INTO "test" ("letter", "number") VALUES('a', 2); + INSERT INTO "test" ("letter", "number") VALUES('c', 2); + SELECT DISTINCT "number" FROM (SELECT "letter", "number" FROM "test" ORDER BY "letter", "number" LIMIT 1) AS "test"; + } +} {2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-78e04e52ea.test b/components/external/SQLite-3.8.1/test/tkt-78e04e52ea.test new file mode 100644 index 0000000000000000000000000000000000000000..dde6502a9de60d0c8be6caf37641bc74f21b783a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-78e04e52ea.test @@ -0,0 +1,68 @@ +# 2009 December 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# Verify that we can create zero-length tables. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-78e04-1.0 { + execsql { + CREATE TABLE ""("" UNIQUE, x CHAR(100)); + CREATE TABLE t2(x); + INSERT INTO ""("") VALUES(1); + INSERT INTO t2 VALUES(2); + SELECT * FROM "", t2; + } +} {1 {} 2} +do_test tkt-78e04-1.1 { + catchsql { + INSERT INTO ""("") VALUES(1); + } +} {1 {column is not unique}} +do_test tkt-78e04-1.2 { + execsql { + PRAGMA table_info(""); + } +} {0 {} {} 0 {} 0 1 x CHAR(100) 0 {} 0} +do_test tkt-78e04-1.3 { + execsql { + CREATE INDEX i1 ON ""("" COLLATE nocase); + } +} {} +do_test tkt-78e04-1.4 { + execsql { + EXPLAIN QUERY PLAN SELECT "" FROM "" WHERE "" LIKE 'abc%'; + } +} {0 0 0 {SCAN TABLE USING COVERING INDEX i1}} +do_test tkt-78e04-1.5 { + execsql { + DROP TABLE ""; + SELECT name FROM sqlite_master; + } +} {t2} + +do_test tkt-78e04-2.1 { + execsql { + CREATE INDEX "" ON t2(x); + EXPLAIN QUERY PLAN SELECT * FROM t2 WHERE x=5; + } +} {0 0 0 {SEARCH TABLE t2 USING COVERING INDEX (x=?)}} +do_test tkt-78e04-2.2 { + execsql { + DROP INDEX ""; + EXPLAIN QUERY PLAN SELECT * FROM t2 WHERE x=2; + } +} {0 0 0 {SCAN TABLE t2}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-7a31705a7e6.test b/components/external/SQLite-3.8.1/test/tkt-7a31705a7e6.test new file mode 100644 index 0000000000000000000000000000000000000000..e3e402917dd0103d14e545eaa45f4ac24c1f382e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-7a31705a7e6.test @@ -0,0 +1,25 @@ +# 2013 February 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [7a31705a7e6c95d514e6f20a6900f436bbc9fed8] in the +# name resolver has been fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_execsql_test tkt-7a31705a7e6-1.1 { + CREATE TABLE t1 (a INTEGER PRIMARY KEY); + CREATE TABLE t2 (a INTEGER PRIMARY KEY, b INTEGER); + CREATE TABLE t2x (b INTEGER PRIMARY KEY); + SELECT t1.a FROM ((t1 JOIN t2 ON t1.a=t2.a) AS x JOIN t2x ON x.b=t2x.b) as y; +} {} diff --git a/components/external/SQLite-3.8.1/test/tkt-7bbfb7d442.test b/components/external/SQLite-3.8.1/test/tkt-7bbfb7d442.test new file mode 100644 index 0000000000000000000000000000000000000000..56d4caeb3e44835b4d4a52a484a827b49592728e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-7bbfb7d442.test @@ -0,0 +1,154 @@ +# 2011 December 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [7bbfb7d442] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix tkt-7bbfb7d442 + +do_execsql_test 1.1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t1 VALUES(3, 'three'); + + CREATE TABLE t2(c, d); + INSERT INTO t2 VALUES('one', 'I'); + INSERT INTO t2 VALUES('two', 'II'); + INSERT INTO t2 VALUES('three', 'III'); + + CREATE TABLE t3(t3_a PRIMARY KEY, t3_d); + CREATE TRIGGER t3t AFTER INSERT ON t3 WHEN new.t3_d IS NULL BEGIN + UPDATE t3 SET t3_d = ( + SELECT d FROM + (SELECT * FROM t2 WHERE (new.t3_a%2)=(rowid%2) LIMIT 10), + (SELECT * FROM t1 WHERE (new.t3_a%2)=(rowid%2) LIMIT 10) + WHERE a = new.t3_a AND b = c + ) WHERE t3_a = new.t3_a; + END; +} + +do_execsql_test 1.2 { + INSERT INTO t3(t3_a) VALUES(1); + INSERT INTO t3(t3_a) VALUES(2); + INSERT INTO t3(t3_a) VALUES(3); + SELECT * FROM t3; +} {1 I 2 II 3 III} + +do_execsql_test 1.3 { DELETE FROM t3 } + +ifcapable compound { + do_execsql_test 1.4 { + INSERT INTO t3(t3_a) SELECT 1 UNION SELECT 2 UNION SELECT 3; + SELECT * FROM t3; + } {1 I 2 II 3 III} +} + + + +#------------------------------------------------------------------------- +# The following test case - 2.* - is from the original bug report as +# posted to the mailing list. +# +do_execsql_test 2.1 { + CREATE TABLE InventoryControl ( + InventoryControlId INTEGER PRIMARY KEY AUTOINCREMENT, + SKU INTEGER NOT NULL, + Variant INTEGER NOT NULL DEFAULT 0, + ControlDate DATE NOT NULL, + ControlState INTEGER NOT NULL DEFAULT -1, + DeliveredQty VARCHAR(30) + ); + + CREATE TRIGGER TGR_InventoryControl_AfterInsert + AFTER INSERT ON InventoryControl + FOR EACH ROW WHEN NEW.ControlState=-1 BEGIN + + INSERT OR REPLACE INTO InventoryControl( + InventoryControlId,SKU,Variant,ControlDate,ControlState,DeliveredQty + ) SELECT + T1.InventoryControlId AS InventoryControlId, + T1.SKU AS SKU, + T1.Variant AS Variant, + T1.ControlDate AS ControlDate, + 1 AS ControlState, + COALESCE(T2.DeliveredQty,0) AS DeliveredQty + FROM ( + SELECT + NEW.InventoryControlId AS InventoryControlId, + II.SKU AS SKU, + II.Variant AS Variant, + COALESCE(LastClosedIC.ControlDate,NEW.ControlDate) AS ControlDate + FROM + InventoryItem II + LEFT JOIN + InventoryControl LastClosedIC + ON LastClosedIC.InventoryControlId IN ( SELECT 99999 ) + WHERE + II.SKU=NEW.SKU AND + II.Variant=NEW.Variant + ) T1 + LEFT JOIN ( + SELECT + TD.SKU AS SKU, + TD.Variant AS Variant, + 10 AS DeliveredQty + FROM + TransactionDetail TD + WHERE + TD.SKU=NEW.SKU AND + TD.Variant=NEW.Variant + ) T2 + ON T2.SKU=T1.SKU AND + T2.Variant=T1.Variant; + END; + + CREATE TABLE InventoryItem ( + SKU INTEGER NOT NULL, + Variant INTEGER NOT NULL DEFAULT 0, + DeptCode INTEGER NOT NULL, + GroupCode INTEGER NOT NULL, + ItemDescription VARCHAR(120) NOT NULL, + PRIMARY KEY(SKU, Variant) + ); + + INSERT INTO InventoryItem VALUES(220,0,1,170,'Scoth Tampon Recurer'); + INSERT INTO InventoryItem VALUES(31,0,1,110,'Fromage'); + + CREATE TABLE TransactionDetail ( + TransactionId INTEGER NOT NULL, + SKU INTEGER NOT NULL, + Variant INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(TransactionId, SKU, Variant) + ); + INSERT INTO TransactionDetail(TransactionId, SKU, Variant) VALUES(44, 31, 0); + + + INSERT INTO InventoryControl(SKU, Variant, ControlDate) SELECT + II.SKU AS SKU, II.Variant AS Variant, '2011-08-30' AS ControlDate + FROM InventoryItem II; +} + +do_execsql_test 2.2 { + SELECT SKU, DeliveredQty FROM InventoryControl WHERE SKU=31 +} {31 10} + +do_execsql_test 2.3 { + SELECT CASE WHEN DeliveredQty=10 THEN "TEST PASSED!" ELSE "TEST FAILED!" END + FROM InventoryControl WHERE SKU=31; +} {{TEST PASSED!}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-80ba201079.test b/components/external/SQLite-3.8.1/test/tkt-80ba201079.test new file mode 100644 index 0000000000000000000000000000000000000000..ea0799b5683c12275bf2484f8acb5349a29cbd00 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-80ba201079.test @@ -0,0 +1,195 @@ +# 2010 December 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [80ba201079ea608071d22a57856b940ea3ac53ce] is +# resolved. That ticket is about an incorrect result that appears when +# an index is added. The root cause is that a constant is being used +# without initialization when the OR optimization applies in the WHERE clause. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix tkt-80ba201079 + +do_test tkt-80ba2-100 { + db eval { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES('A'); + CREATE TABLE t2(b); + INSERT INTO t2 VALUES('B'); + CREATE TABLE t3(c); + INSERT INTO t3 VALUES('C'); + SELECT * FROM t1, t2 + WHERE (a='A' AND b='X') + OR (a='A' AND EXISTS (SELECT * FROM t3 WHERE c='C')); + } +} {A B} +do_test tkt-80ba2-101 { + db eval { + CREATE INDEX i1 ON t1(a); + SELECT * FROM t1, t2 + WHERE (a='A' AND b='X') + OR (a='A' AND EXISTS (SELECT * FROM t3 WHERE c='C')); + } +} {A B} +do_test tkt-80ba2-102 { + optimization_control db factor-constants 0 + db cache flush + db eval { + SELECT * FROM t1, t2 + WHERE (a='A' AND b='X') + OR (a='A' AND EXISTS (SELECT * FROM t3 WHERE c='C')); + } +} {A B} +optimization_control db all 1 + +# Verify that the optimization_control command is actually working +# +do_test tkt-80ba2-150 { + optimization_control db factor-constants 1 + db cache flush + set x1 [db eval {EXPLAIN + SELECT * FROM t1, t2 + WHERE (a='A' AND b='X') + OR (a='A' AND EXISTS (SELECT * FROM t3 WHERE c='C'));}] + optimization_control db factor-constants 0 + db cache flush + set x2 [db eval {EXPLAIN + SELECT * FROM t1, t2 + WHERE (a='A' AND b='X') + OR (a='A' AND EXISTS (SELECT * FROM t3 WHERE c='C'));}] + + expr {$x1==$x2} +} {0} + +do_test tkt-80ba2-200 { + db eval { + CREATE TABLE entry_types ( + id integer primary key, + name text + ); + INSERT INTO "entry_types" VALUES(100,'cli_command'); + INSERT INTO "entry_types" VALUES(300,'object_change'); + CREATE TABLE object_changes ( + change_id integer primary key, + system_id int, + obj_id int, + obj_context text, + change_type int, + command_id int + ); + INSERT INTO "object_changes" VALUES(1551,1,114608,'exported_pools',1,2114); + INSERT INTO "object_changes" VALUES(2048,1,114608,'exported_pools',2,2319); + CREATE TABLE timeline ( + rowid integer primary key, + timestamp text, + system_id int, + entry_type int, + entry_id int + ); + INSERT INTO "timeline" VALUES(6735,'2010-11-21 17:08:27.000',1,300,2048); + INSERT INTO "timeline" VALUES(6825,'2010-11-21 17:09:21.000',1,300,2114); + SELECT entry_type, + entry_types.name, + entry_id + FROM timeline JOIN entry_types ON entry_type = entry_types.id + WHERE (entry_types.name = 'cli_command' AND entry_id=2114) + OR (entry_types.name = 'object_change' + AND entry_id IN (SELECT change_id + FROM object_changes + WHERE obj_context = 'exported_pools')); + } +} {300 object_change 2048} +do_test tkt-80ba2-201 { + db eval { + CREATE INDEX timeline_entry_id_idx on timeline(entry_id); + SELECT entry_type, + entry_types.name, + entry_id + FROM timeline JOIN entry_types ON entry_type = entry_types.id + WHERE (entry_types.name = 'cli_command' AND entry_id=2114) + OR (entry_types.name = 'object_change' + AND entry_id IN (SELECT change_id + FROM object_changes + WHERE obj_context = 'exported_pools')); + } +} {300 object_change 2048} +do_test tkt-80ba2-202 { + optimization_control db factor-constants 0 + db cache flush + db eval { + SELECT entry_type, + entry_types.name, + entry_id + FROM timeline JOIN entry_types ON entry_type = entry_types.id + WHERE (entry_types.name = 'cli_command' AND entry_id=2114) + OR (entry_types.name = 'object_change' + AND entry_id IN (SELECT change_id + FROM object_changes + WHERE obj_context = 'exported_pools')); + } +} {300 object_change 2048} + +#------------------------------------------------------------------------- +# + +drop_all_tables +do_execsql_test 301 { + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); + CREATE TABLE t2(d, e); + + INSERT INTO t1 VALUES('A', 'B', 'C'); + INSERT INTO t2 VALUES('D', 'E'); +} + +do_execsql_test 302 { + SELECT * FROM t1, t2 WHERE + (a='A' AND d='E') OR + (b='B' AND c IN ('C', 'D', 'E')) +} {A B C D E} + +do_execsql_test 303 { + SELECT * FROM t1, t2 WHERE + (a='A' AND d='E') OR + (b='B' AND c IN (SELECT c FROM t1)) +} {A B C D E} + +ifcapable compound { + do_execsql_test 304 { + SELECT * FROM t1, t2 WHERE + (a='A' AND d='E') OR + (b='B' AND c IN (SELECT 'B' UNION SELECT 'C' UNION SELECT 'D')) + } {A B C D E} +} + +do_execsql_test 305 { + SELECT * FROM t1, t2 WHERE + (b='B' AND c IN ('C', 'D', 'E')) OR + (a='A' AND d='E') +} {A B C D E} + +do_execsql_test 306 { + SELECT * FROM t1, t2 WHERE + (b='B' AND c IN (SELECT c FROM t1)) OR + (a='A' AND d='E') +} {A B C D E} + +ifcapable compound { + do_execsql_test 307 { + SELECT * FROM t1, t2 WHERE + (b='B' AND c IN (SELECT 'B' UNION SELECT 'C' UNION SELECT 'D')) OR + (a='A' AND d='E') + } {A B C D E} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-80e031a00f.test b/components/external/SQLite-3.8.1/test/tkt-80e031a00f.test new file mode 100644 index 0000000000000000000000000000000000000000..95372abf043a159d201157abb758bb4bda3a3f70 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-80e031a00f.test @@ -0,0 +1,206 @@ +# 2010 July 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [80e031a00f45dca877ed92b225209cfa09280f4f] has been +# resolved. That ticket is about IN and NOT IN operators with empty-set +# right-hand sides. Such expressions should always return TRUE or FALSE +# even if the left-hand side is NULL. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +# EVIDENCE-OF: R-58875-56087 The IN and NOT IN operators take a single +# scalar operand on the left and a vector operand on the right formed by +# an explicit list of zero or more scalars or by a single subquery. +# +# EVIDENCE-OF: R-52275-55503 When the right operand is an empty set, the +# result of IN is false and the result of NOT IN is true, regardless of +# the left operand and even if the left operand is NULL. +# +# EVIDENCE-OF: R-13595-45863 Note that SQLite allows the parenthesized +# list of scalar values on the right-hand side of an IN or NOT IN +# operator to be an empty list but most other SQL database database +# engines and the SQL92 standard require the list to contain at least +# one element. +# +do_execsql_test tkt-80e031a00f.1 {SELECT 1 IN ()} 0 +do_execsql_test tkt-80e031a00f.1b {SELECT 1 IN (2)} 0 +do_execsql_test tkt-80e031a00f.1c {SELECT 1 IN (2,3,4,5,6,7,8,9)} 0 +do_execsql_test tkt-80e031a00f.2 {SELECT 1 NOT IN ()} 1 +do_execsql_test tkt-80e031a00f.2b {SELECT 1 NOT IN (2)} 1 +do_execsql_test tkt-80e031a00f.2c {SELECT 1 NOT IN (2,3,4,5,6,7,8,9)} 1 +do_execsql_test tkt-80e031a00f.3 {SELECT null IN ()} 0 +do_execsql_test tkt-80e031a00f.4 {SELECT null NOT IN ()} 1 +do_execsql_test tkt-80e031a00f.5 { + CREATE TABLE t1(x); + SELECT 1 IN t1; +} 0 +do_execsql_test tkt-80e031a00f.6 {SELECT 1 NOT IN t1} 1 +do_execsql_test tkt-80e031a00f.7 {SELECT null IN t1} 0 +do_execsql_test tkt-80e031a00f.8 {SELECT null NOT IN t1} 1 +do_execsql_test tkt-80e031a00f.9 { + CREATE TABLE t2(y INTEGER PRIMARY KEY); + SELECT 1 IN t2; +} 0 +do_execsql_test tkt-80e031a00f.10 {SELECT 1 NOT IN t2} 1 +do_execsql_test tkt-80e031a00f.11 {SELECT null IN t2} 0 +do_execsql_test tkt-80e031a00f.12 {SELECT null NOT IN t2} 1 +do_execsql_test tkt-80e031a00f.13 { + CREATE TABLE t3(z INT UNIQUE); + SELECT 1 IN t3; +} 0 +do_execsql_test tkt-80e031a00f.14 {SELECT 1 NOT IN t3} 1 +do_execsql_test tkt-80e031a00f.15 {SELECT null IN t3} 0 +do_execsql_test tkt-80e031a00f.16 {SELECT null NOT IN t3} 1 +do_execsql_test tkt-80e031a00f.17 {SELECT 1 IN (SELECT x+y FROM t1, t2)} 0 +do_execsql_test tkt-80e031a00f.18 {SELECT 1 NOT IN (SELECT x+y FROM t1,t2)} 1 +do_execsql_test tkt-80e031a00f.19 {SELECT null IN (SELECT x+y FROM t1,t2)} 0 +do_execsql_test tkt-80e031a00f.20 {SELECT null NOT IN (SELECT x+y FROM t1,t2)} 1 +do_execsql_test tkt-80e031a00f.21 {SELECT 1.23 IN ()} 0 +do_execsql_test tkt-80e031a00f.22 {SELECT 1.23 NOT IN ()} 1 +do_execsql_test tkt-80e031a00f.23 {SELECT 1.23 IN t1} 0 +do_execsql_test tkt-80e031a00f.24 {SELECT 1.23 NOT IN t1} 1 +do_execsql_test tkt-80e031a00f.25 {SELECT 'hello' IN ()} 0 +do_execsql_test tkt-80e031a00f.26 {SELECT 'hello' NOT IN ()} 1 +do_execsql_test tkt-80e031a00f.27 {SELECT 'hello' IN t1} 0 +do_execsql_test tkt-80e031a00f.28 {SELECT 'hello' NOT IN t1} 1 +do_execsql_test tkt-80e031a00f.29 {SELECT x'303132' IN ()} 0 +do_execsql_test tkt-80e031a00f.30 {SELECT x'303132' NOT IN ()} 1 +do_execsql_test tkt-80e031a00f.31 {SELECT x'303132' IN t1} 0 +do_execsql_test tkt-80e031a00f.32 {SELECT x'303132' NOT IN t1} 1 + +# EVIDENCE-OF: R-50221-42915 The result of an IN or NOT IN operator is +# determined by the following matrix: Left operand is NULL Right operand +# contains NULL Right operand is an empty set Left operand found within +# right operand Result of IN operator Result of NOT IN operator no no no +# no false true does not matter no yes no false true no does not matter +# no yes true false no yes no no NULL NULL yes does not matter no does +# not matter NULL NULL +# +# Row 1: +do_execsql_test tkt-80e031a00f.100 {SELECT 1 IN (2,3,4)} 0 +do_execsql_test tkt-80e031a00f.101 {SELECT 1 NOT IN (2,3,4)} 1 +do_execsql_test tkt-80e031a00f.102 {SELECT 'a' IN ('b','c','d')} 0 +do_execsql_test tkt-80e031a00f.103 {SELECT 'a' NOT IN ('b','c','d')} 1 +do_test tkt-80e031a00f.104 { + db eval { + CREATE TABLE t4(a UNIQUE); + CREATE TABLE t5(b INTEGER PRIMARY KEY); + CREATE TABLE t6(c); + INSERT INTO t4 VALUES(2); + INSERT INTO t4 VALUES(3); + INSERT INTO t4 VALUES(4); + INSERT INTO t5 SELECT * FROM t4; + INSERT INTO t6 SELECT * FROM t4; + CREATE TABLE t4n(a UNIQUE); + CREATE TABLE t6n(c); + INSERT INTO t4n SELECT * FROM t4; + INSERT INTO t4n VALUES(null); + INSERT INTO t6n SELECT * FROM t4n; + CREATE TABLE t7(a UNIQUE); + CREATE TABLE t8(c); + INSERT INTO t7 VALUES('b'); + INSERT INTO t7 VALUES('c'); + INSERT INTO t7 VALUES('d'); + INSERT INTO t8 SELECT * FROM t7; + CREATE TABLE t7n(a UNIQUE); + CREATE TABLE t8n(c); + INSERT INTO t7n SELECT * FROM t7; + INSERT INTO t7n VALUES(null); + INSERT INTO t8n SELECT * FROM t7n; + } + execsql {SELECT 1 IN t4} +} 0 +do_execsql_test tkt-80e031a00f.105 {SELECT 1 NOT IN t4} 1 +do_execsql_test tkt-80e031a00f.106 {SELECT 1 IN t5} 0 +do_execsql_test tkt-80e031a00f.107 {SELECT 1 NOT IN t5} 1 +do_execsql_test tkt-80e031a00f.108 {SELECT 1 IN t6} 0 +do_execsql_test tkt-80e031a00f.109 {SELECT 1 NOT IN t6} 1 +do_execsql_test tkt-80e031a00f.110 {SELECT 'a' IN t7} 0 +do_execsql_test tkt-80e031a00f.111 {SELECT 'a' NOT IN t7} 1 +do_execsql_test tkt-80e031a00f.112 {SELECT 'a' IN t8} 0 +do_execsql_test tkt-80e031a00f.113 {SELECT 'a' NOT IN t8} 1 +# +# Row 2 is tested by cases 1-32 above. +# Row 3: +do_execsql_test tkt-80e031a00f.300 {SELECT 2 IN (2,3,4,null)} 1 +do_execsql_test tkt-80e031a00f.301 {SELECT 3 NOT IN (2,3,4,null)} 0 +do_execsql_test tkt-80e031a00f.302 {SELECT 4 IN (2,3,4)} 1 +do_execsql_test tkt-80e031a00f.303 {SELECT 2 NOT IN (2,3,4)} 0 +do_execsql_test tkt-80e031a00f.304 {SELECT 'b' IN ('b','c','d')} 1 +do_execsql_test tkt-80e031a00f.305 {SELECT 'c' NOT IN ('b','c','d')} 0 +do_execsql_test tkt-80e031a00f.306 {SELECT 'd' IN ('b','c',null,'d')} 1 +do_execsql_test tkt-80e031a00f.307 {SELECT 'b' NOT IN (null,'b','c','d')} 0 +do_execsql_test tkt-80e031a00f.308 {SELECT 2 IN t4} 1 +do_execsql_test tkt-80e031a00f.309 {SELECT 3 NOT IN t4} 0 +do_execsql_test tkt-80e031a00f.310 {SELECT 4 IN t4n} 1 +do_execsql_test tkt-80e031a00f.311 {SELECT 2 NOT IN t4n} 0 +do_execsql_test tkt-80e031a00f.312 {SELECT 2 IN t5} 1 +do_execsql_test tkt-80e031a00f.313 {SELECT 3 NOT IN t5} 0 +do_execsql_test tkt-80e031a00f.314 {SELECT 2 IN t6} 1 +do_execsql_test tkt-80e031a00f.315 {SELECT 3 NOT IN t6} 0 +do_execsql_test tkt-80e031a00f.316 {SELECT 4 IN t6n} 1 +do_execsql_test tkt-80e031a00f.317 {SELECT 2 NOT IN t6n} 0 +do_execsql_test tkt-80e031a00f.318 {SELECT 'b' IN t7} 1 +do_execsql_test tkt-80e031a00f.319 {SELECT 'c' NOT IN t7} 0 +do_execsql_test tkt-80e031a00f.320 {SELECT 'c' IN t7n} 1 +do_execsql_test tkt-80e031a00f.321 {SELECT 'd' NOT IN t7n} 0 +do_execsql_test tkt-80e031a00f.322 {SELECT 'b' IN t8} 1 +do_execsql_test tkt-80e031a00f.323 {SELECT 'c' NOT IN t8} 0 +do_execsql_test tkt-80e031a00f.324 {SELECT 'c' IN t8n} 1 +do_execsql_test tkt-80e031a00f.325 {SELECT 'd' NOT IN t8n} 0 +# +# Row 4: +do_execsql_test tkt-80e031a00f.400 {SELECT 1 IN (2,3,4,null)} {{}} +do_execsql_test tkt-80e031a00f.401 {SELECT 1 NOT IN (2,3,4,null)} {{}} +do_execsql_test tkt-80e031a00f.402 {SELECT 'a' IN ('b','c',null,'d')} {{}} +do_execsql_test tkt-80e031a00f.403 {SELECT 'a' NOT IN (null,'b','c','d')} {{}} +do_execsql_test tkt-80e031a00f.404 {SELECT 1 IN t4n} {{}} +do_execsql_test tkt-80e031a00f.405 {SELECT 5 NOT IN t4n} {{}} +do_execsql_test tkt-80e031a00f.406 {SELECT 6 IN t6n} {{}} +do_execsql_test tkt-80e031a00f.407 {SELECT 7 NOT IN t6n} {{}} +do_execsql_test tkt-80e031a00f.408 {SELECT 'a' IN t7n} {{}} +do_execsql_test tkt-80e031a00f.409 {SELECT 'e' NOT IN t7n} {{}} +do_execsql_test tkt-80e031a00f.410 {SELECT 'f' IN t8n} {{}} +do_execsql_test tkt-80e031a00f.411 {SELECT 'g' NOT IN t8n} {{}} +# +# Row 5: +do_execsql_test tkt-80e031a00f.500 {SELECT null IN (2,3,4,null)} {{}} +do_execsql_test tkt-80e031a00f.501 {SELECT null NOT IN (2,3,4,null)} {{}} +do_execsql_test tkt-80e031a00f.502 {SELECT null IN (2,3,4)} {{}} +do_execsql_test tkt-80e031a00f.503 {SELECT null NOT IN (2,3,4)} {{}} +do_execsql_test tkt-80e031a00f.504 {SELECT null IN ('b','c','d')} {{}} +do_execsql_test tkt-80e031a00f.505 {SELECT null NOT IN ('b','c','d')} {{}} +do_execsql_test tkt-80e031a00f.506 {SELECT null IN ('b','c',null,'d')} {{}} +do_execsql_test tkt-80e031a00f.507 {SELECT null NOT IN (null,'b','c','d')} {{}} +do_execsql_test tkt-80e031a00f.508 {SELECT null IN t4} {{}} +do_execsql_test tkt-80e031a00f.509 {SELECT null NOT IN t4} {{}} +do_execsql_test tkt-80e031a00f.510 {SELECT null IN t4n} {{}} +do_execsql_test tkt-80e031a00f.511 {SELECT null NOT IN t4n} {{}} +do_execsql_test tkt-80e031a00f.512 {SELECT null IN t5} {{}} +do_execsql_test tkt-80e031a00f.513 {SELECT null NOT IN t5} {{}} +do_execsql_test tkt-80e031a00f.514 {SELECT null IN t6} {{}} +do_execsql_test tkt-80e031a00f.515 {SELECT null NOT IN t6} {{}} +do_execsql_test tkt-80e031a00f.516 {SELECT null IN t6n} {{}} +do_execsql_test tkt-80e031a00f.517 {SELECT null NOT IN t6n} {{}} +do_execsql_test tkt-80e031a00f.518 {SELECT null IN t7} {{}} +do_execsql_test tkt-80e031a00f.519 {SELECT null NOT IN t7} {{}} +do_execsql_test tkt-80e031a00f.520 {SELECT null IN t7n} {{}} +do_execsql_test tkt-80e031a00f.521 {SELECT null NOT IN t7n} {{}} +do_execsql_test tkt-80e031a00f.522 {SELECT null IN t8} {{}} +do_execsql_test tkt-80e031a00f.523 {SELECT null NOT IN t8} {{}} +do_execsql_test tkt-80e031a00f.524 {SELECT null IN t8n} {{}} +do_execsql_test tkt-80e031a00f.525 {SELECT null NOT IN t8n} {{}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-8454a207b9.test b/components/external/SQLite-3.8.1/test/tkt-8454a207b9.test new file mode 100644 index 0000000000000000000000000000000000000000..88a8614f8285a3cb11d1eff637891fa49257cbaa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-8454a207b9.test @@ -0,0 +1,67 @@ +# 2010 September 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [8454a207b9fd2243c4c6b7a73f67ea0315717c1a]. Verify +# that a negative default value on an added text column actually comes +# out negative. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-8454a207b9.1 { + db eval { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + ALTER TABLE t1 ADD COLUMN b TEXT DEFAULT -123.0; + SELECT b, typeof(b) FROM t1; + } +} {-123.0 text} +do_test tkt-8454a207b9.2 { + db eval { + ALTER TABLE t1 ADD COLUMN c TEXT DEFAULT -123.5; + SELECT c, typeof(c) FROM t1; + } +} {-123.5 text} +do_test tkt-8454a207b9.3 { + db eval { + ALTER TABLE t1 ADD COLUMN d TEXT DEFAULT -'hello'; + SELECT d, typeof(d) FROM t1; + } +} {0 text} +do_test tkt-8454a207b9.4 { + db eval { + ALTER TABLE t1 ADD COLUMN e DEFAULT -123.0; + SELECT e, typeof(e) FROM t1; + } +} {-123 integer} +do_test tkt-8454a207b9.5 { + db eval { + ALTER TABLE t1 ADD COLUMN f DEFAULT -123.5; + SELECT f, typeof(f) FROM t1; + } +} {-123.5 real} +do_test tkt-8454a207b9.6 { + db eval { + ALTER TABLE t1 ADD COLUMN g DEFAULT -9223372036854775808; + SELECT g, typeof(g) FROM t1; + } +} {-9223372036854775808 integer} +do_test tkt-8454a207b9.7 { + db eval { + ALTER TABLE t1 ADD COLUMN h DEFAULT 9223372036854775807; + SELECT h, typeof(h) FROM t1; + } +} {9223372036854775807 integer} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-868145d012.test b/components/external/SQLite-3.8.1/test/tkt-868145d012.test new file mode 100644 index 0000000000000000000000000000000000000000..145d159e540d731eae0e3ffff33cc5427553efba --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-868145d012.test @@ -0,0 +1,64 @@ +# 2013 March 05 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [868145d012a1] is fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_execsql_test tkt-868145d012.100 { + CREATE TABLE p ( + id INTEGER PRIMARY KEY, + uid VARCHAR(36), + t INTEGER + ); + + CREATE TABLE pa ( + id INTEGER PRIMARY KEY, + a_uid VARCHAR(36) + ); + + CREATE TABLE a ( + id INTEGER PRIMARY KEY, + uid VARCHAR(36), + t INTEGER + ); + + INSERT INTO pa VALUES(1,'1234'); + INSERT INTO pa VALUES(2,'2345'); + INSERT INTO p VALUES(3,'1234',97); + INSERT INTO p VALUES(4,'1234',98); + INSERT INTO a VALUES(5,'1234',98); + INSERT INTO a VALUES(6,'1234',99); +} {} +do_execsql_test tkt-868145d012.110 { + SELECT DISTINCT pa.id, p.id, a.id + FROM + pa + LEFT JOIN p ON p.uid='1234' + LEFT JOIN a ON a.uid=pa.a_uid + WHERE + a.t=p.t + ; +} {1 4 5} +do_execsql_test tkt-868145d012.120 { + SELECT DISTINCT pa.id, p.id, a.id + FROM + pa + LEFT JOIN p ON p.uid='1234' + LEFT JOIN a ON a.uid=pa.a_uid AND a.t=p.t + ORDER BY 1, 2, 3 + ; +} {1 3 {} 1 4 5 2 3 {} 2 4 {}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-91e2e8ba6f.test b/components/external/SQLite-3.8.1/test/tkt-91e2e8ba6f.test new file mode 100644 index 0000000000000000000000000000000000000000..57f13740a256d27c41adedf821164e8ebf24f889 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-91e2e8ba6f.test @@ -0,0 +1,52 @@ +# 2011 June 23 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests for SQLite. Specifically, it tests that SQLite +# does not crash and an error is returned if localhost() fails. This +# is the problem reported by ticket 91e2e8ba6f. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set testprefix tkt-91e2e8ba6f + + +do_execsql_test 1.1 { + CREATE TABLE t1(x INTEGER, y REAL); + INSERT INTO t1 VALUES(11, 11); +} {} + +do_execsql_test 1.2 { + SELECT x/10, y/10 FROM t1; +} {1 1.1} + +do_execsql_test 1.3 { + SELECT x/10, y/10 FROM (SELECT * FROM t1); +} {1 1.1} + +do_execsql_test 1.4 { + SELECT x/10, y/10 FROM (SELECT * FROM t1 LIMIT 5 OFFSET 0); +} {1 1.1} + +do_execsql_test 1.5 { + SELECT x/10, y/10 FROM (SELECT * FROM t1 LIMIT 5 OFFSET 0) LIMIT 5 OFFSET 0; +} {1 1.1} + +do_execsql_test 1.6 { + SELECT a.x/10, a.y/10 FROM + (SELECT * FROM t1 LIMIT 5 OFFSET 0) AS a, t1 AS b WHERE a.x = b.x + LIMIT 5 OFFSET 0; +} {1 1.1} + +do_execsql_test 1.7 { + CREATE VIEW v1 AS SELECT * FROM t1 LIMIT 5; + SELECT a.x/10, a.y/10 FROM v1 AS a, t1 AS b WHERE a.x = b.x LIMIT 5 OFFSET 0; +} {1 1.1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-94c04eaadb.test b/components/external/SQLite-3.8.1/test/tkt-94c04eaadb.test new file mode 100644 index 0000000000000000000000000000000000000000..0063de664d633505716ad373b11d209b30b3c934 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-94c04eaadb.test @@ -0,0 +1,73 @@ +# 2009 October 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +if {[info commands sqlite3async_initialize] eq ""} { + # The async logic is not built into this system + finish_test + return +} + +# Create a database. +do_test tkt-94c94-1.1 { + execsql { CREATE TABLE t1(a, b) } +} {} + +# Grow the file to larger than 4096MB (2^32 bytes) +db close +if {[catch {fake_big_file 4096 [get_pwd]/test.db} msg]} { + puts "**** Unable to create a file larger than 4096 MB. *****" + finish_test + return +} + +# Switch to async mode. +sqlite3async_initialize "" 1 +sqlite3 db test.db +sqlite3 db2 test.db + +# Read from and write to the db just past the 4096MB mark. +# +do_test tkt-94c94-2.1 { + execsql { CREATE TABLE t2(x, y) } db +} {} +do_test tkt-94c94-2.2 { +breakpoint + execsql { INSERT INTO t2 VALUES(1, 2) } db2 +} {} +do_test tkt-94c94-2.3 { + execsql { SELECT * FROM t2 } db +} {1 2} +do_test tkt-94c94-2.4 { + sqlite3async_control halt idle + sqlite3async_start + sqlite3async_wait +} {} +do_test tkt-94c94-2.5 { + execsql { SELECT * FROM t2 } db +} {1 2} +do_test tkt-94c94-2.6 { + sqlite3async_start + sqlite3async_wait +} {} + +db close +db2 close +sqlite3async_start +sqlite3async_wait +sqlite3async_control halt never +sqlite3async_shutdown + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-9d68c883.test b/components/external/SQLite-3.8.1/test/tkt-9d68c883.test new file mode 100644 index 0000000000000000000000000000000000000000..18dc6ccd67fd6b26c371ade9ae09064a9c88ab0f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-9d68c883.test @@ -0,0 +1,53 @@ +# 2010 April 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file tests that bug 9d68c883132c8e9ffcd5b0c148c990807b5df1b7 +# is fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-9d68c88-1.1 { + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 2; + CREATE TABLE t3(x); + CREATE TABLE t4(x); + CREATE TABLE t5(x); + INSERT INTO t5 VALUES(randomblob(1500)); + CREATE TABLE t7(x); + CREATE TABLE t8(x); + } +} {} + + +for {set i 0} {$i < 100} {incr i} { + db close + sqlite3_simulate_device -sectorsize 8192 + sqlite3 db test.db -vfs devsym + + do_test tkt-9d68c88-2.$i { + execsql { + BEGIN; + DELETE FROM t5; + INSERT INTO t8 VALUES('hello world'); + } + + sqlite3_memdebug_fail $i -repeat 0 + catchsql { DROP TABLE t7; } + sqlite3_memdebug_fail -1 + + catchsql { ROLLBACK } + execsql { PRAGMA integrity_check } + } {ok} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-9f2eb3abac.test b/components/external/SQLite-3.8.1/test/tkt-9f2eb3abac.test new file mode 100644 index 0000000000000000000000000000000000000000..5b93733afe7799df629be8ce55f5f52f34a78e6d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-9f2eb3abac.test @@ -0,0 +1,79 @@ + +# 2013 August 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +set ::testprefix tkt-9f2eb3abac + +do_execsql_test 1.1 { + CREATE TABLE t1(a,b,c,d,e, PRIMARY KEY(a,b,c,d,e)); + SELECT * FROM t1 WHERE a=? AND b=? AND c=? AND d=? AND e=?; +} {} + +do_execsql_test 1.2 { + CREATE TABLE "a" ( + "b" integer NOT NULL, + "c" integer NOT NULL, + PRIMARY KEY ("b", "c") + ); + + CREATE TABLE "d" ( + "e" integer NOT NULL, + "g" integer NOT NULL, + "f" integer NOT NULL, + "h" integer NOT NULL, + "i" character(10) NOT NULL, + "j" int, + PRIMARY KEY ("e", "g", "f", "h") + ); + + CREATE TABLE "d_to_a" ( + "f_e" integer NOT NULL, + "f_g" integer NOT NULL, + "f_f" integer NOT NULL, + "f_h" integer NOT NULL, + "t_b" integer NOT NULL, + "t_c" integer NOT NULL, + "r" character NOT NULL, + "s" integer, + PRIMARY KEY ("f_e", "f_g", "f_f", "f_h", "t_b", "t_c") + ); + + INSERT INTO d (g, e, h, f, j, i) VALUES ( 1, 1, 1, 1, 1, 1 ); + INSERT INTO a (b, c) VALUES ( 1, 1 ); + INSERT INTO d_to_a VALUES (1, 1, 1, 1, 1, 1, 1, 1); + + DELETE FROM d_to_a + WHERE f_g = 1 AND f_e = 1 AND f_h = 1 AND f_f = 1 AND t_b = 1 AND t_c = 1; + + SELECT * FROM d_to_a; +} {} + +faultsim_delete_and_reopen +do_execsql_test 2.0 { CREATE TABLE t1(a,b,c,d,e, PRIMARY KEY(a,b,c,d,e)) } +do_execsql_test 2.1 { CREATE TABLE t2(x) } +faultsim_save_and_close + +do_faultsim_test 3 -faults oom* -prep { + faultsim_restore_and_reopen + execsql { SELECT 1 FROM sqlite_master } +} -body { + execsql { SELECT * FROM t1,t2 WHERE a=? AND b=? AND c=? AND d=? AND e=? } +} -test { + faultsim_test_result {0 {}} +} + +finish_test + diff --git a/components/external/SQLite-3.8.1/test/tkt-a7b7803e.test b/components/external/SQLite-3.8.1/test/tkt-a7b7803e.test new file mode 100644 index 0000000000000000000000000000000000000000..b617cf6df2381e7af7bebbfb07650ca114b14714 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-a7b7803e.test @@ -0,0 +1,84 @@ +# 2012 December 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [a7b7803e8d1e8699cd8a460a38133b98892d2e17] has +# been fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +do_test tkt-a7b7803e.1 { + db eval { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(0,'first'),(99,'fuzzy'); + SELECT (t1.a==0) AS x, b + FROM t1 + WHERE a=0 OR x; + } +} {1 first} +do_test tkt-a7b7803e.2 { + db eval { + SELECT a, (t1.b='fuzzy') AS x + FROM t1 + WHERE x + } +} {99 1} +do_test tkt-a7b7803e.3 { + db eval { + SELECT (a=99) AS x, (t1.b='fuzzy') AS y, * + FROM t1 + WHERE x AND y + } +} {1 1 99 fuzzy} +do_test tkt-a7b7803e.4 { + db eval { + SELECT (a=99) AS x, (t1.b='first') AS y, * + FROM t1 + WHERE x OR y + ORDER BY a + } +} {0 1 0 first 1 0 99 fuzzy} +do_test tkt-a7b7803e.5 { + db eval { + SELECT (M.a=99) AS x, M.b, (N.b='first') AS y, N.b + FROM t1 M, t1 N + WHERE x OR y + ORDER BY M.a, N.a + } +} {0 first 1 first 1 fuzzy 1 first 1 fuzzy 0 fuzzy} +do_test tkt-a7b7803e.6 { + db eval { + SELECT (M.a=99) AS x, M.b, (N.b='first') AS y, N.b + FROM t1 M, t1 N + WHERE x AND y + ORDER BY M.a, N.a + } +} {1 fuzzy 1 first} +do_test tkt-a7b7803e.7 { + db eval { + SELECT (M.a=99) AS x, M.b, (N.b='first') AS y, N.b + FROM t1 M JOIN t1 N ON x AND y + ORDER BY M.a, N.a + } +} {1 fuzzy 1 first} +do_test tkt-a7b7803e.8 { + db eval { + SELECT (M.a=99) AS x, M.b, (N.b='first') AS y, N.b + FROM t1 M JOIN t1 N ON x + ORDER BY M.a, N.a + } +} {1 fuzzy 1 first 1 fuzzy 0 fuzzy} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-b1d3a2e531.test b/components/external/SQLite-3.8.1/test/tkt-b1d3a2e531.test new file mode 100644 index 0000000000000000000000000000000000000000..54534b6cbebe4e078ba7ae572b616c7b08219c47 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-b1d3a2e531.test @@ -0,0 +1,109 @@ +# 2011 August 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for foreign keys. Specifically, it tests +# that ticket b1d3a2e531 has been fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!foreignkey||!trigger} { + finish_test + return +} +set testprefix tkt-b1d3a2e531 + +do_execsql_test 1.0 { PRAGMA foreign_keys = ON } + +do_execsql_test 1.1 { + CREATE TABLE pp(x PRIMARY KEY); + CREATE TABLE cc(y REFERENCES pp DEFERRABLE INITIALLY DEFERRED); + INSERT INTO pp VALUES('abc'); + INSERT INTO cc VALUES('abc'); +} +do_execsql_test 1.2 { + BEGIN; + DROP TABLE pp; + DROP TABLE cc; + COMMIT; +} +do_execsql_test 1.3 { + CREATE TABLE pp(x PRIMARY KEY); + CREATE TABLE cc(y REFERENCES pp DEFERRABLE INITIALLY DEFERRED); + INSERT INTO pp VALUES('abc'); + INSERT INTO cc VALUES('abc'); +} +do_execsql_test 1.4 { + BEGIN; + DROP TABLE cc; + DROP TABLE pp; + COMMIT; +} + +do_execsql_test 2.1 { + CREATE TABLE pp(x PRIMARY KEY); + CREATE TABLE cc( + y INTEGER PRIMARY KEY REFERENCES pp DEFERRABLE INITIALLY DEFERRED + ); + INSERT INTO pp VALUES(5); + INSERT INTO cc VALUES(5); +} +do_execsql_test 2.2 { + BEGIN; + DROP TABLE pp; + DROP TABLE cc; + COMMIT; +} +do_execsql_test 2.3 { + CREATE TABLE pp(x PRIMARY KEY); + CREATE TABLE cc( + y INTEGER PRIMARY KEY REFERENCES pp DEFERRABLE INITIALLY DEFERRED + ); + INSERT INTO pp VALUES(5); + INSERT INTO cc VALUES(5); +} +do_execsql_test 2.4 { + BEGIN; + DROP TABLE cc; + DROP TABLE pp; + COMMIT; +} + +do_execsql_test 3.1 { + CREATE TABLE pp1(x PRIMARY KEY); + CREATE TABLE cc1(y REFERENCES pp1 DEFERRABLE INITIALLY DEFERRED); + + CREATE TABLE pp2(x PRIMARY KEY); + CREATE TABLE cc2(y REFERENCES pp1 DEFERRABLE INITIALLY DEFERRED); + + INSERT INTO pp1 VALUES(2200); + INSERT INTO cc1 VALUES(NULL); + + INSERT INTO pp2 VALUES(2200); + INSERT INTO cc2 VALUES(2200); +} +do_catchsql_test 3.2 { + BEGIN; + DELETE FROM pp2; + DROP TABLE pp1; + DROP TABLE cc1; + COMMIT; +} {1 {foreign key constraint failed}} +do_catchsql_test 3.3 { + DROP TABLE cc2; + COMMIT; +} {0 {}} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-b351d95f9.test b/components/external/SQLite-3.8.1/test/tkt-b351d95f9.test new file mode 100644 index 0000000000000000000000000000000000000000..5bd5ee486528842bc51dddc1716f05acb382cf08 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-b351d95f9.test @@ -0,0 +1,47 @@ +# 2010 September 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [b351d95f9cd5ef17e9d9dbae18f5ca8611190001] has been +# resolved. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +do_test tkt-b351d95.1 { + execsql { + CREATE table t1(a,b); + INSERT INTO t1 VALUES('name1','This is a test'); + INSERT INTO t1 VALUES('name2','xyz'); + CREATE TABLE t2(x,y); + INSERT INTO t2 SELECT a, CASE b WHEN 'xyz' THEN null ELSE b END FROM t1; + SELECT x, y FROM t2 ORDER BY x; + } +} {name1 {This is a test} name2 {}} + +do_test tkt-b351d95.2 { + execsql { + DELETE FROM t2; + INSERT INTO t2 SELECT a, coalesce(b,a) FROM t1; + SELECT x, y FROM t2 ORDER BY x; + } +} {name1 {This is a test} name2 xyz} +do_test tkt-b351d95.3 { + execsql { + DELETE FROM t2; + INSERT INTO t2 SELECT a, coalesce(b,a) FROM t1; + SELECT x, y BETWEEN 'xy' AND 'xz' FROM t2 ORDER BY x; + } +} {name1 0 name2 1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-b72787b1.test b/components/external/SQLite-3.8.1/test/tkt-b72787b1.test new file mode 100644 index 0000000000000000000000000000000000000000..dea3f49a6409d2678111bfe9282aac3b36430044 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-b72787b1.test @@ -0,0 +1,82 @@ +# 2011 February 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [b72787b1a7] has been +# fixed. From the ticket: +# +# The sqlite3ExpirePreparedStatements routine marks all statements +# as expired. This includes statements that are not expired. +# +# Steps to reproduce: +# +# * Prepare a statement (A) +# * Alter the schema to invalidate cookie in A +# * Prepare a statement (B) +# * Run B and have A run as part of B +# * A will find a bad cookie and cause *all* statements +# to be expired including the currently running B by calling +# sqlite3ExpirePreparedStatements +# * When control returns to B it will then abort +# +# The bug is that sqlite3ExpirePreparedStatements expires all statements. +# Note that B was prepared after the schema change and hence is perfectly +# valid and then is marked as expired while running. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +unset -nocomplain ::STMT +proc runsql {} { + db eval {CREATE TABLE IF NOT EXISTS t4(q)} + sqlite3_step $::STMT + set rc [sqlite3_column_int $::STMT 0] + sqlite3_reset $::STMT + return $rc +} + +do_test tkt-b72787b1.1 { + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + CREATE TABLE t2(y); + INSERT INTO t2 SELECT x+2 FROM t1; + INSERT INTO t2 SELECT x+4 FROM t1; + } + db func runsql ::runsql + set DB [sqlite3_connection_pointer db] + set sql {SELECT max(x) FROM t1} + set ::STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL] + + # The runsql() call on the second row of the first query will + # cause all $::STMT to hit an expired cookie. Prior to the fix + # for [b72787b1a7, the bad cookie would expire all statements, including + # the following compound SELECT, which would cause a fault when the + # second SELECT was reached. After the fix, the current statement + # continues to completion. + db eval { + SELECT CASE WHEN y=3 THEN y+100 WHEN y==4 THEN runsql()+200 + ELSE 300+y END FROM t2 + UNION ALL + SELECT * FROM t1; + } +} {103 202 305 306 1 2} + +sqlite3_finalize $::STMT + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-bd484a090c.test b/components/external/SQLite-3.8.1/test/tkt-bd484a090c.test new file mode 100644 index 0000000000000000000000000000000000000000..3d2b59995857c9a7f61b6860c381c51b23cdf036 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-bd484a090c.test @@ -0,0 +1,38 @@ +# 2011 June 21 +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests for SQLite. Specifically, it tests that SQLite +# does not crash and an error is returned if localhost() fails. This +# is the problem reported by ticket bd484a090c. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set testprefix tkt-bd484a090c + + +do_test 1.1 { + lindex [catchsql { SELECT datetime('now', 'localtime') }] 0 +} {0} +do_test 1.2 { + lindex [catchsql { SELECT datetime('now', 'utc') }] 0 +} {0} + +sqlite3_test_control SQLITE_TESTCTRL_LOCALTIME_FAULT 1 + +do_test 2.1 { + catchsql { SELECT datetime('now', 'localtime') } +} {1 {local time unavailable}} +do_test 2.2 { + catchsql { SELECT datetime('now', 'utc') } +} {1 {local time unavailable}} + +sqlite3_test_control SQLITE_TESTCTRL_LOCALTIME_FAULT 0 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-bdc6bbbb38.test b/components/external/SQLite-3.8.1/test/tkt-bdc6bbbb38.test new file mode 100644 index 0000000000000000000000000000000000000000..8b0d55df84c2d1ff96699288ad47e26f3f2a807e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-bdc6bbbb38.test @@ -0,0 +1,90 @@ +# 2012 May 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [bdc6bbbb38] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix tkt-bdc6bbbb38 + +# If SQLITE_ENABLE_FTS3 is defined, omit this file. +ifcapable !fts3 { finish_test ; return } +set sqlite_fts3_enable_parentheses 1 + +foreach {tn idxdir} {1 ASC 2 DESC} { + execsql { DROP TABLE IF EXISTS t2 } + + do_execsql_test $tn.1.1 "CREATE VIRTUAL TABLE t2 USING fts4(x, order=$idxdir)" + do_execsql_test $tn.1.2 { INSERT INTO t2 VALUES('a b c') } + + do_execsql_test $tn.1.3 { + SELECT offsets(t2) FROM t2 WHERE t2 MATCH 'a AND d OR b' ORDER BY docid ASC + } { + {0 0 0 1 0 2 2 1} + } + do_execsql_test $tn.1.4 { + SELECT snippet(t2,'[',']') FROM t2 WHERE t2 MATCH 'a AND d OR b' + ORDER BY docid ASC + } { + {[a] [b] c} + } + do_execsql_test $tn.1.5 { INSERT INTO t2 VALUES('a c d') } + do_execsql_test $tn.1.6 { + SELECT offsets(t2) FROM t2 WHERE t2 MATCH 'a AND d OR b' ORDER BY docid ASC + } { + {0 0 0 1 0 2 2 1} + {0 0 0 1 0 1 4 1} + } + do_execsql_test $tn.1.7 { + SELECT snippet(t2,'[',']') FROM t2 WHERE t2 MATCH 'a AND d OR b' + ORDER BY docid ASC + } { + {[a] [b] c} + {[a] c [d]} + } + + execsql { DROP TABLE IF EXISTS t3 } + do_execsql_test $tn.2.1 "CREATE VIRTUAL TABLE t3 USING fts4(x, order=$idxdir)" + do_execsql_test $tn.2.2 { INSERT INTO t3 VALUES('a c d') } + do_execsql_test $tn.2.3 { + SELECT offsets(t3) FROM t3 WHERE t3 MATCH 'a AND d OR b' ORDER BY docid DESC + } { + {0 0 0 1 0 1 4 1} + } + do_execsql_test $tn.2.4 { + SELECT snippet(t3,'[',']') FROM t3 WHERE t3 MATCH 'a AND d OR b' + ORDER BY docid DESC + } { + {[a] c [d]} + } + do_execsql_test $tn.2.5 { + INSERT INTO t3 VALUES('a b c'); + } + do_execsql_test $tn.2.6 { + SELECT offsets(t3) FROM t3 WHERE t3 MATCH 'a AND d OR b' ORDER BY docid DESC + } { + {0 0 0 1 0 2 2 1} + {0 0 0 1 0 1 4 1} + } + do_execsql_test $tn.2.7 { + SELECT snippet(t3,'[',']') FROM t3 WHERE t3 MATCH 'a AND d OR b' + ORDER BY docid DESC + } { + {[a] [b] c} + {[a] c [d]} + } +} + +set sqlite_fts3_enable_parentheses 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-c48d99d690.test b/components/external/SQLite-3.8.1/test/tkt-c48d99d690.test new file mode 100644 index 0000000000000000000000000000000000000000..6d1b9dbe619f521937885923941aae74b1fc1da0 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-c48d99d690.test @@ -0,0 +1,25 @@ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set ::testprefix tkt-c48d99d690 + +do_test 1.0 { + execsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(a, b); + INSERT INTO t1 VALUES('one' , 1); + INSERT INTO t1 VALUES('two' , 5); + INSERT INTO t1 VALUES('two' , 2); + INSERT INTO t1 VALUES('three', 3); + PRAGMA count_changes = 1; + } +} {} + +do_test 1.1 { + execsql { INSERT INTO t2 SELECT * FROM t1 } +} {4} + +do_test 1.2 { execsql VACUUM } {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-cbd054fa6b.test b/components/external/SQLite-3.8.1/test/tkt-cbd054fa6b.test new file mode 100644 index 0000000000000000000000000000000000000000..2951233a5bb974c5213b7df5bd3950f585848386 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-cbd054fa6b.test @@ -0,0 +1,114 @@ +# 2010 March 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests to verify that ticket [cbd054fa6b] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !stat4&&!stat3 { + finish_test + return +} + +proc s {blob} { + set ret "" + binary scan $blob c* bytes + foreach b $bytes { + set t [binary format c $b] + if {[string is print $t]} { + append ret $t + } else { + append ret . + } + } + return $ret +} +db function s s + +do_test tkt-cbd05-1.1 { + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT UNIQUE NOT NULL); + CREATE INDEX t1_x ON t1(b); + INSERT INTO t1 VALUES (NULL, ''); + INSERT INTO t1 VALUES (NULL, 'A'); + INSERT INTO t1 VALUES (NULL, 'B'); + INSERT INTO t1 VALUES (NULL, 'C'); + INSERT INTO t1 VALUES (NULL, 'D'); + INSERT INTO t1 VALUES (NULL, 'E'); + INSERT INTO t1 VALUES (NULL, 'F'); + INSERT INTO t1 VALUES (NULL, 'G'); + INSERT INTO t1 VALUES (NULL, 'H'); + INSERT INTO t1 VALUES (NULL, 'I'); + SELECT count(*) FROM t1; + } +} {10} +do_test tkt-cbd05-1.2 { + db eval { ANALYZE; } + ifcapable stat4 { + db eval { + PRAGMA writable_schema = 1; + CREATE VIEW vvv AS + SELECT tbl,idx,neq,nlt,ndlt,test_extract(sample,0) AS sample + FROM sqlite_stat4; + PRAGMA writable_schema = 0; + } + } else { + db eval { + CREATE VIEW vvv AS + SELECT tbl,idx,neq,nlt,ndlt,sample FROM sqlite_stat3; + } + } +} {} +do_test tkt-cbd05-1.3 { + execsql { + SELECT tbl,idx,group_concat(s(sample),' ') + FROM vvv + WHERE idx = 't1_x' + GROUP BY tbl,idx + } +} {t1 t1_x { A B C D E F G H I}} + +do_test tkt-cbd05-2.1 { + db eval { + DROP TABLE t1; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b BLOB UNIQUE NOT NULL); + CREATE INDEX t1_x ON t1(b); + INSERT INTO t1 VALUES(NULL, X''); + INSERT INTO t1 VALUES(NULL, X'41'); + INSERT INTO t1 VALUES(NULL, X'42'); + INSERT INTO t1 VALUES(NULL, X'43'); + INSERT INTO t1 VALUES(NULL, X'44'); + INSERT INTO t1 VALUES(NULL, X'45'); + INSERT INTO t1 VALUES(NULL, X'46'); + INSERT INTO t1 VALUES(NULL, X'47'); + INSERT INTO t1 VALUES(NULL, X'48'); + INSERT INTO t1 VALUES(NULL, X'49'); + SELECT count(*) FROM t1; + } +} {10} +do_test tkt-cbd05-2.2 { + db eval { + ANALYZE; + } +} {} +do_test tkt-cbd05-2.3 { + execsql { + SELECT tbl,idx,group_concat(s(sample),' ') + FROM vvv + WHERE idx = 't1_x' + GROUP BY tbl,idx + } +} {t1 t1_x { A B C D E F G H I}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-d11f09d36e.test b/components/external/SQLite-3.8.1/test/tkt-d11f09d36e.test new file mode 100644 index 0000000000000000000000000000000000000000..ffd3d219288d2cd5ba6bbdc0dba0007d498c9528 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-d11f09d36e.test @@ -0,0 +1,61 @@ +# 2010 June 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test that the bug reported by ticket d11f09d36e7cb0821e01f4 has +# been fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set a_string_counter 1 +proc a_string {n} { + global a_string_counter + incr a_string_counter + string range [string repeat "${a_string_counter}." $n] 1 $n +} +db func a_string a_string + +do_test tkt-d11f09d36e.1 { + execsql { + PRAGMA synchronous = NORMAL; + PRAGMA cache_size = 10; + CREATE TABLE t1(x, y, UNIQUE(x, y)); + BEGIN; + } + for {set i 0} {$i < 10000} {incr i} { + execsql { INSERT INTO t1 VALUES($i, $i) } + } + execsql COMMIT +} {} +do_test tkt-d11f09d36e.2 { + execsql { + BEGIN; + UPDATE t1 set x = x+10000; + ROLLBACK; + } +} {} +do_test tkt-d11f09d36e.3 { + execsql { PRAGMA integrity_check } +} {ok} +do_test tkt-d11f09d36e.4 { + execsql { + SAVEPOINT tr; + UPDATE t1 set x = x+10000; + ROLLBACK TO tr; + RELEASE tr; + } +} {} +do_test tkt-d11f09d36e.5 { + execsql { PRAGMA integrity_check } +} {ok} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-d635236375.test b/components/external/SQLite-3.8.1/test/tkt-d635236375.test new file mode 100644 index 0000000000000000000000000000000000000000..3fc782265e2f32671a721f7f2ca797f1f43c1365 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-d635236375.test @@ -0,0 +1,38 @@ +# 2011 August 3 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that bug [d63523637517386191d634e] +# has been fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set ::testprefix tkt-d635236375 + +do_test 1.0 { + execsql { + CREATE TABLE t1(id1 INTEGER PRIMARY KEY); + INSERT INTO t1 VALUES(9999); + CREATE TABLE t2(id2 INTEGER PRIMARY KEY); + INSERT INTO t2 VALUES(12345); + INSERT INTO t2 VALUES(54321); + SELECT DISTINCT id1 AS x, id1 AS y FROM t1, t2; + } +} {9999 9999} +do_test 1.1 { + execsql { + SELECT count(*) FROM t1, t2 GROUP BY id1, id1; + } +} {2} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-d82e3f3721.test b/components/external/SQLite-3.8.1/test/tkt-d82e3f3721.test new file mode 100644 index 0000000000000000000000000000000000000000..da932d1eaa8a5c66ed6f910c46bcbf8c3b9d9891 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-d82e3f3721.test @@ -0,0 +1,85 @@ +# 2009 September 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [d82e3f3721] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_test tkt-d82e3-1.1 { + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY AUTOINCREMENT, b); + INSERT INTO t1 VALUES(null,'abc'); + INSERT INTO t1 VALUES(null,'def'); + DELETE FROM t1; + INSERT INTO t1 VALUES(null,'ghi'); + SELECT * FROM t1; + } +} {3 ghi} +do_test tkt-d82e3-1.2 { + db eval { + CREATE TEMP TABLE t2(a INTEGER PRIMARY KEY AUTOINCREMENT, b); + INSERT INTO t2 VALUES(null,'jkl'); + INSERT INTO t2 VALUES(null,'mno'); + DELETE FROM t2; + INSERT INTO t2 VALUES(null,'pqr'); + SELECT * FROM t2; + } +} {3 pqr} +do_test tkt-d82e3-1.3 { + db eval { + SELECT 'main', * FROM main.sqlite_sequence + UNION ALL + SELECT 'temp', * FROM temp.sqlite_sequence + ORDER BY 2 + } +} {main t1 3 temp t2 3} +do_test tkt-d82e3-1.4 { + db eval { + VACUUM; + SELECT 'main', * FROM main.sqlite_sequence + UNION ALL + SELECT 'temp', * FROM temp.sqlite_sequence + ORDER BY 2 + } +} {main t1 3 temp t2 3} + +sqlite3 db2 test.db +do_test tkt-d82e3-2.1 { + db eval { + CREATE TEMP TABLE t3(x); + INSERT INTO t3 VALUES(1); + } + db2 eval { + CREATE TABLE t3(y,z); + INSERT INTO t3 VALUES(8,9); + } + db eval { + SELECT * FROM temp.t3 JOIN main.t3; + } +} {1 8 9} +do_test tkt-d82e3-2.2 { + db eval { + VACUUM; + SELECT * FROM temp.t3 JOIN main.t3; + } +} {1 8 9} +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-f3e5abed55.test b/components/external/SQLite-3.8.1/test/tkt-f3e5abed55.test new file mode 100644 index 0000000000000000000000000000000000000000..3c793d4f4da854962f1a16dd9ff6949862acae18 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-f3e5abed55.test @@ -0,0 +1,116 @@ +# 2010 July 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +foreach f [glob -nocomplain test.db*mj*] { forcedelete $f } +forcedelete test.db2 + +do_test tkt-f3e5abed55-1.1 { + execsql { + ATTACH 'test.db2' AS aux; + CREATE TABLE main.t1(a, b); + CREATE TABLE aux.t2(c, d); + } +} {} + +do_test tkt-f3e5abed55-1.2 { + glob -nocomplain test.db*mj* +} {} + +do_test tkt-f3e5abed55-1.3 { + sqlite3 db2 test.db + execsql { BEGIN; SELECT * FROM t1 } db2 +} {} + +do_test tkt-f3e5abed55-1.4 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t2 VALUES(1, 2); + } + catchsql COMMIT +} {1 {database is locked}} + +do_test tkt-f3e5abed55-1.5 { + execsql COMMIT db2 + execsql COMMIT +} {} + +do_test tkt-f3e5abed55-1.6 { + glob -nocomplain test.db*mj* +} {} +foreach f [glob -nocomplain test.db*mj*] { forcedelete $f } +db close +db2 close + + + +# Set up a testvfs so that the next time SQLite tries to delete the +# file "test.db-journal", a snapshot of the current file-system contents +# is taken. +# +# This test will not work with an in-memory journal. +# +if {[permutation]!="inmemory_journal"} { + testvfs tvfs -default 1 + tvfs script xDelete + tvfs filter xDelete + proc xDelete {method file args} { + if {[file tail $file] == "test.db-journal"} { + faultsim_save + tvfs filter {} + } + return "SQLITE_OK" + } + + sqlite3 db test.db + sqlite3 db2 test.db + do_test tkt-f3e5abed55-2.1 { + execsql { + ATTACH 'test.db2' AS aux; + BEGIN; + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t2 VALUES(3, 4); + } + } {} + do_test tkt-f3e5abed55-2.2 { + execsql { BEGIN; SELECT * FROM t1 } db2 + } {1 2} + do_test tkt-f3e5abed55-2.3 { + catchsql COMMIT + } {1 {database is locked}} + + do_test tkt-f3e5abed55-2.4 { + execsql COMMIT db2 + execsql { + COMMIT; + SELECT * FROM t1; + SELECT * FROM t2; + } + } {1 2 3 4 1 2 3 4} + do_test tkt-f3e5abed55-2.5 { + db close + db2 close + faultsim_restore_and_reopen + execsql { + ATTACH 'test.db2' AS aux; + SELECT * FROM t1; + SELECT * FROM t2; + } + } {1 2 3 4 1 2 3 4} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-f777251dc7a.test b/components/external/SQLite-3.8.1/test/tkt-f777251dc7a.test new file mode 100644 index 0000000000000000000000000000000000000000..af6f71ad96d4e6060eec7db71c1292e5be46aaed --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-f777251dc7a.test @@ -0,0 +1,104 @@ +# 2009 October 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket [f777251dc7a] has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_test tkt-f7772-1.1 { + execsql { + CREATE TEMP TABLE t1(x UNIQUE); + INSERT INTO t1 VALUES(1); + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES(1, 2); + CREATE TEMP TABLE t3(w, z); + } +} {} + +proc force_rollback {} { + catch {db eval {INSERT OR ROLLBACK INTO t1 VALUES(1)}} +} +db function force_rollback force_rollback + +do_test tkt-f7772-1.2 { + catchsql { + BEGIN IMMEDIATE; + SELECT x, force_rollback(), EXISTS(SELECT 1 FROM t3 WHERE w=x) FROM t2; + } +} {1 {abort due to ROLLBACK}} +do_test tkt-f7772-1.3 { + sqlite3_get_autocommit db +} {1} + +do_test tkt-f7772-2.1 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + DROP TABLE IF EXISTS t3; + + CREATE TEMP TABLE t1(x UNIQUE); + INSERT INTO t1 VALUES(1); + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES(1, 2); + } +} {} +do_test tkt-f7772-2.2 { + execsql { + BEGIN IMMEDIATE; + CREATE TEMP TABLE t3(w, z); + } + catchsql { + SELECT x, force_rollback(), EXISTS(SELECT 1 FROM t3 WHERE w=x) FROM t2 + } +} {1 {callback requested query abort}} +do_test tkt-f7772-2.3 { + sqlite3_get_autocommit db +} {1} + +do_test tkt-f7772-3.1 { + execsql { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + DROP TABLE IF EXISTS t3; + + CREATE TEMP TABLE t1(x); + CREATE TABLE t2(x); + CREATE TABLE t3(x); + + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(2); + } +} {} + +proc ins {} { db eval {INSERT INTO t3 VALUES('hello')} } +db function ins ins + +do_test tkt-f7772-3.2 { + execsql { + SELECT ins() AS x FROM t2 UNION ALL SELECT ins() AS x FROM t1 + } +} {{} {} {} {}} +do_test tkt-f7772-3.3 { + execsql { SELECT * FROM t3 } +} {hello hello hello hello} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-f7b4edec.test b/components/external/SQLite-3.8.1/test/tkt-f7b4edec.test new file mode 100644 index 0000000000000000000000000000000000000000..f6d3d5b95a51d0c635577838020c678366cbdfbf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-f7b4edec.test @@ -0,0 +1,74 @@ +# 2011 March 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket +# [f7b4edece25c994857dc139207f55a53c8319fae] has been fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Open two database connections to the same database file in +# shared cache mode. Create update hooks that will fire on +# each connection. +# +db close +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] +sqlite3 db1 test.db +sqlite3 db2 test.db +unset -nocomplain HOOKS +set HOOKS {} +proc update_hook {args} { lappend ::HOOKS $args } +db1 update_hook update_hook +db2 update_hook update_hook + +# Create a prepared statement +# +do_test tkt-f7b4edec-1 { + execsql { CREATE TABLE t1(x, y); } db1 + execsql { INSERT INTO t1 VALUES(1, 2) } db1 + set ::HOOKS +} {{INSERT main t1 1}} + +# In the second database connection cause the schema to be reparsed +# without changing the schema cookie. +# +set HOOKS {} +do_test tkt-f7b4edec-2 { + execsql { + BEGIN; + DROP TABLE t1; + CREATE TABLE t1(x, y); + ROLLBACK; + } db2 + set ::HOOKS +} {} + +# Rerun the prepared statement that was created prior to the +# schema reparse. Verify that the update-hook gives the correct +# output. +# +set HOOKS {} +do_test tkt-f7b4edec-3 { + execsql { INSERT INTO t1 VALUES(1, 2) } db1 + set ::HOOKS +} {{INSERT main t1 2}} + +# Be sure to restore the original shared-cache mode setting before +# returning. +# +db1 close +db2 close +sqlite3_enable_shared_cache $::enable_shared_cache + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-f973c7ac31.test b/components/external/SQLite-3.8.1/test/tkt-f973c7ac31.test new file mode 100644 index 0000000000000000000000000000000000000000..454309057f7f2909d5a89e4be912cf8c4ac56fc8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-f973c7ac31.test @@ -0,0 +1,86 @@ +# 2010 June 09 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-f973c7ac3-1.0 { + execsql { + CREATE TABLE t(c1 INTEGER, c2 INTEGER); + INSERT INTO t VALUES(5, 5); + INSERT INTO t VALUES(5, 4); + } +} {} + +foreach {tn sql} { + 1 "" + 2 "CREATE INDEX i1 ON t(c1, c2)" +} { + + execsql $sql + + do_test tkt-f973c7ac3-1.$tn.1 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>0 AND c2<='2' ORDER BY c2 DESC + } + } {} + do_test tkt-f973c7ac3-1.$tn.2 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>0 AND c2<=5 ORDER BY c2 DESC + } + } {5 5 5 4} + do_test tkt-f973c7ac3-1.$tn.3 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>0 AND c2<='5' ORDER BY c2 DESC + } + } {5 5 5 4} + do_test tkt-f973c7ac3-1.$tn.4 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>'0' AND c2<=5 ORDER BY c2 DESC + } + } {5 5 5 4} + do_test tkt-f973c7ac3-1.$tn.5 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>'0' AND c2<='5' ORDER BY c2 DESC + } + } {5 5 5 4} + + do_test tkt-f973c7ac3-1.$tn.6 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>0 AND c2<='2' ORDER BY c2 ASC + } + } {} + do_test tkt-f973c7ac3-1.$tn.7 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>0 AND c2<=5 ORDER BY c2 ASC + } + } {5 4 5 5} + do_test tkt-f973c7ac3-1.$tn.8 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>0 AND c2<='5' ORDER BY c2 ASC + } + } {5 4 5 5} + do_test tkt-f973c7ac3-1.$tn.9 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>'0' AND c2<=5 ORDER BY c2 ASC + } + } {5 4 5 5} + do_test tkt-f973c7ac3-1.$tn.10 { + execsql { + SELECT * FROM t WHERE c1 = 5 AND c2>'0' AND c2<='5' ORDER BY c2 ASC + } + } {5 4 5 5} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-fa7bf5ec.test b/components/external/SQLite-3.8.1/test/tkt-fa7bf5ec.test new file mode 100644 index 0000000000000000000000000000000000000000..34f12b96773cca65049d5a87319f4993300fc7b2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-fa7bf5ec.test @@ -0,0 +1,39 @@ +# 2011 October 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [fa7bf5ec94801e7e2030e41eefe5d9dd96eaacfd] has +# been resolved. +# +# The problem described by this ticket was that the sqlite3ExprCompare() +# function was saying that expressions (x='a') and (x='A') were identical +# because it was using sqlite3StrICmp() instead of strcmp() to compare string +# literals. That was causing the query optimizer for aggregate queries to +# believe that both count() operations were identical, and thus only +# computing the first count() and making a copy of the result for the +# second count(). +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-fa7bf5ec-1 { + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES ('a'); + INSERT INTO t1 VALUES ('A'); + INSERT INTO t1 VALUES ('A'); + SELECT count(CASE WHEN x='a' THEN 1 END), + count(CASE WHEN x='A' THEN 1 END) + FROM t1; + } +} {1 2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-fc62af4523.test b/components/external/SQLite-3.8.1/test/tkt-fc62af4523.test new file mode 100644 index 0000000000000000000000000000000000000000..ed1497b948cc4ee26cf57e49d84695135a256e78 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-fc62af4523.test @@ -0,0 +1,84 @@ +# 2010 June 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [fc62af4523] has been resolved. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +do_test tkt-fc62af4523.1 { + execsql { + PRAGMA cache_size = 10; + PRAGMA journal_mode = persist; + CREATE TABLE t1(a UNIQUE, b UNIQUE); + INSERT INTO t1 SELECT randomblob(200), randomblob(300); + INSERT INTO t1 SELECT randomblob(200), randomblob(300) FROM t1; -- 2 + INSERT INTO t1 SELECT randomblob(200), randomblob(300) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(200), randomblob(300) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(200), randomblob(300) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(200), randomblob(300) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(200), randomblob(300) FROM t1; -- 64 + } + execsql { + PRAGMA integrity_check; + SELECT count(*) FROM t1; + } +} {ok 64} + +# Launch an external process. Have it write (but not commit) a large +# transaction to the database. +# +set ::chan [launch_testfixture] +proc buddy {code} { testfixture $::chan $code } +do_test tkt-fc62af4523.2 { + testfixture $::chan { + sqlite3 db test.db + db eval { + PRAGMA cache_size = 10; + BEGIN; + UPDATE t1 SET b = randomblob(400); + UPDATE t1 SET a = randomblob(201); + } + } + file exists test.db-journal +} {1} + +# Now do "PRAGMA journal_mode = DELETE" in this process. At one point +# this was causing SQLite to delete the journal file from the file-system, +# even though the external process is currently using it. +# +do_test tkt-fc62af4523.3 { execsql { PRAGMA journal_mode = DELETE } } {delete} +do_test tkt-fc62af4523.4 { file exists test.db-journal } {1} + +# Cause the external process to crash. Since it has already written +# uncommitted data into the database file, the next reader will have +# to do a hot-journal rollback to recover the database. +# +# Or, if this test is run in a version with the bug present, the journal +# file has already been deleted. In this case we are left with a corrupt +# database file and no hot-journal to fix it with. +# +do_test tkt-fc62af4523.5 { + testfixture $::chan sqlite_abort +} {ERROR: Child process hung up} +after 200 +do_test tkt-fc62af4523.6 { + execsql { + PRAGMA integrity_check; + SELECT count(*) FROM t1; + } +} {ok 64} + +catch { close $::chan } +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt-fc7bd6358f.test b/components/external/SQLite-3.8.1/test/tkt-fc7bd6358f.test new file mode 100644 index 0000000000000000000000000000000000000000..a1b13c463c70c42bed43eb9b214c1bac3bcd8ffd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt-fc7bd6358f.test @@ -0,0 +1,78 @@ +# 2013 March 05 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that ticket [fc7bd6358f]: +# +# The following SQL yields an incorrect result (zero rows) in all +# versions of SQLite between 3.6.14 and 3.7.15.2: +# +# CREATE TABLE t(textid TEXT); +# INSERT INTO t VALUES('12'); +# INSERT INTO t VALUES('34'); +# CREATE TABLE i(intid INTEGER PRIMARY KEY); +# INSERT INTO i VALUES(12); +# INSERT INTO i VALUES(34); +# +# SELECT t1.textid AS a, i.intid AS b, t2.textid AS c +# FROM t t1, i, t t2 +# WHERE t1.textid = i.intid +# AND t1.textid = t2.textid; +# +# The correct result should be two rows, one with 12|12|12 and the other +# with 34|34|34. With this bug, no rows are returned. Bisecting shows that +# this bug was introduced with check-in [dd4d67a67454] on 2009-04-23. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt-fc7bd6358f.100 { + db eval { + CREATE TABLE t(textid TEXT); + INSERT INTO t VALUES('12'); + INSERT INTO t VALUES('34'); + CREATE TABLE i(intid INTEGER PRIMARY KEY); + INSERT INTO i VALUES(12); + INSERT INTO i VALUES(34); + } +} {} +unset -nocomplain from +unset -nocomplain where +unset -nocomplain a +unset -nocomplain b +foreach {a from} { + 1 {FROM t t1, i, t t2} + 2 {FROM i, t t1, t t2} + 3 {FROM t t1, t t2, i} +} { + foreach {b where} { + 1 {WHERE t1.textid=i.intid AND t1.textid=t2.textid} + 2 {WHERE i.intid=t1.textid AND t1.textid=t2.textid} + 3 {WHERE t1.textid=i.intid AND i.intid=t2.textid} + 4 {WHERE t1.textid=i.intid AND t2.textid=i.intid} + 5 {WHERE i.intid=t1.textid AND i.intid=t2.textid} + 6 {WHERE i.intid=t1.textid AND t2.textid=i.intid} + 7 {WHERE t1.textid=t2.textid AND i.intid=t2.textid} + 8 {WHERE t1.textid=t2.textid AND t2.textid=i.intid} + } { + do_test tkt-fc7bd6358f.110.$a.$b.1 { + db eval {PRAGMA automatic_index=ON} + db eval "SELECT t1.textid, i.intid, t2.textid $from $where" + } {12 12 12 34 34 34} + do_test tkt-fc7bd6358f.110.$a.$b.2 { + db eval {PRAGMA automatic_index=OFF} + db eval "SELECT t1.textid, i.intid, t2.textid $from $where" + } {12 12 12 34 34 34} + } +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1435.test b/components/external/SQLite-3.8.1/test/tkt1435.test new file mode 100644 index 0000000000000000000000000000000000000000..1f62147b4465181095dd521faf0567defef18b44 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1435.test @@ -0,0 +1,111 @@ +# 2005 September 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1435 has been +# fixed. +# +# +# $Id: tkt1435.test,v 1.2 2006/01/17 09:35:02 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !memorydb { + finish_test + return +} + +# Construct the sample database. +# +do_test tkt1435-1.0 { + sqlite3 db :memory: + execsql { + CREATE TABLE Instances( + instanceId INTEGER PRIMARY KEY, + troveName STR, + versionId INT, + flavorId INT, + timeStamps STR, + isPresent INT, + pinned BOOLEAN + ); + INSERT INTO "Instances" + VALUES(1, 'libhello:runtime', 1, 1, 1126929880.094, 1, 1); + INSERT INTO "Instances" + VALUES(2, 'libhello:user', 1, 1, 1126929880.094, 1, 0); + INSERT INTO "Instances" + VALUES(3, 'libhello:script', 1, 1, 1126929880.094, 1, 0); + INSERT INTO "Instances" + VALUES(4, 'libhello', 1, 1, 1126929880.094, 1, 0); + + CREATE TABLE Versions(versionId INTEGER PRIMARY KEY,version STR UNIQUE); + INSERT INTO "Versions" VALUES(0, NULL); + INSERT INTO "Versions" VALUES(1, '/localhost@rpl:linux/0-1-1'); + + CREATE TABLE Flavors(flavorId integer primary key, flavor str unique); + INSERT INTO "Flavors" VALUES(0, NULL); + INSERT INTO "Flavors" VALUES(1, '1#x86'); + + CREATE TEMPORARY TABLE tlList ( + row INTEGER PRIMARY KEY, + name STRING, + version STRING, + flavor STRING + ); + + INSERT INTO tlList + values(NULL, 'libhello:script', '/localhost@rpl:linux/0-1-1', '1#x86'); + INSERT INTO tlList + values(NULL, 'libhello:user', '/localhost@rpl:linux/0-1-1', '1#x86'); + INSERT INTO tlList + values(NULL, 'libhello:runtime', '/localhost@rpl:linux/0-1-1', '1#x86'); + } +} {} + +# Run the query with an index +# +do_test tkt1435-1.1 { + execsql { + select row, pinned from tlList, Instances, Versions, Flavors + where + Instances.troveName = tlList.name + and Versions.version = tlList.version + and Instances.versionId = Versions.versionId + and ( Flavors.flavor = tlList.flavor or Flavors.flavor is NULL + and tlList.flavor = '') + and Instances.flavorId = Flavors.flavorId + order by row asc; + } +} {1 0 2 0 3 1} + +# Create a indices, analyze and rerun the query. +# Verify that the results are the same +# +do_test tkt1435-1.2 { + execsql { + CREATE INDEX InstancesNameIdx ON Instances(troveName); + CREATE UNIQUE INDEX InstancesIdx + ON Instances(troveName, versionId, flavorId); + ANALYZE; + select row, pinned from tlList, Instances, Versions, Flavors + where + Instances.troveName = tlList.name + and Versions.version = tlList.version + and Instances.versionId = Versions.versionId + and ( Flavors.flavor = tlList.flavor or Flavors.flavor is NULL + and tlList.flavor = '') + and Instances.flavorId = Flavors.flavorId + order by row asc; + } +} {1 0 2 0 3 1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1443.test b/components/external/SQLite-3.8.1/test/tkt1443.test new file mode 100644 index 0000000000000000000000000000000000000000..0f55437bcaa61b22d05ec7b2748dd674db66ba13 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1443.test @@ -0,0 +1,180 @@ +# 2005 September 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1433 has been +# fixed. +# +# The problem in ticket #1433 was that the dependencies on the right-hand +# side of an IN operator were not being checked correctly. So in an +# expression of the form: +# +# t1.x IN (1,t2.b,3) +# +# the optimizer was missing the fact that the right-hand side of the IN +# depended on table t2. It was checking dependencies based on the +# Expr.pRight field rather than Expr.pList and Expr.pSelect. +# +# Such a bug could be verifed using a less elaborate test case. But +# this test case (from the original bug poster) exercises so many different +# parts of the system all at once, that it seemed like a good one to +# include in the test suite. +# +# NOTE: Yes, in spite of the name of this file (tkt1443.test) this +# test is for ticket #1433 not #1443. I mistyped the name when I was +# creating the file and I had already checked in the file by the wrong +# name be the time I noticed the error. With CVS it is a really hassle +# to change filenames, so I'll just leave it as is. No harm done. +# +# $Id: tkt1443.test,v 1.4 2006/01/17 09:35:02 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !subquery||!memorydb { + finish_test + return +} + +# Construct the sample database. +# +do_test tkt1443-1.0 { + sqlite3 db :memory: + execsql { + CREATE TABLE Items( + itemId integer primary key, + item str unique + ); + INSERT INTO "Items" VALUES(0, 'ALL'); + INSERT INTO "Items" VALUES(1, 'double:source'); + INSERT INTO "Items" VALUES(2, 'double'); + INSERT INTO "Items" VALUES(3, 'double:runtime'); + INSERT INTO "Items" VALUES(4, '.*:runtime'); + + CREATE TABLE Labels( + labelId INTEGER PRIMARY KEY, + label STR UNIQUE + ); + INSERT INTO "Labels" VALUES(0, 'ALL'); + INSERT INTO "Labels" VALUES(1, 'localhost@rpl:linux'); + INSERT INTO "Labels" VALUES(2, 'localhost@rpl:branch'); + + CREATE TABLE LabelMap( + itemId INTEGER, + labelId INTEGER, + branchId integer + ); + INSERT INTO "LabelMap" VALUES(1, 1, 1); + INSERT INTO "LabelMap" VALUES(2, 1, 1); + INSERT INTO "LabelMap" VALUES(3, 1, 1); + INSERT INTO "LabelMap" VALUES(1, 2, 2); + INSERT INTO "LabelMap" VALUES(2, 2, 3); + INSERT INTO "LabelMap" VALUES(3, 2, 3); + + CREATE TABLE Users ( + userId INTEGER PRIMARY KEY, + user STRING UNIQUE, + salt BINARY, + password STRING + ); + INSERT INTO "Users" VALUES(1, 'test', 'Šæ$d', + '43ba0f45014306bd6df529551ffdb3df'); + INSERT INTO "Users" VALUES(2, 'limited', 'ªš>S', + 'cf07c8348fdf675cc1f7696b7d45191b'); + CREATE TABLE UserGroups ( + userGroupId INTEGER PRIMARY KEY, + userGroup STRING UNIQUE + ); + INSERT INTO "UserGroups" VALUES(1, 'test'); + INSERT INTO "UserGroups" VALUES(2, 'limited'); + + CREATE TABLE UserGroupMembers ( + userGroupId INTEGER, + userId INTEGER + ); + INSERT INTO "UserGroupMembers" VALUES(1, 1); + INSERT INTO "UserGroupMembers" VALUES(2, 2); + + CREATE TABLE Permissions ( + userGroupId INTEGER, + labelId INTEGER NOT NULL, + itemId INTEGER NOT NULL, + write INTEGER, + capped INTEGER, + admin INTEGER + ); + INSERT INTO "Permissions" VALUES(1, 0, 0, 1, 0, 1); + INSERT INTO "Permissions" VALUES(2, 2, 4, 0, 0, 0); + } +} {} + +# Run the query with an index +# +do_test tkt1443-1.1 { + execsql { + select distinct + Items.Item as trove, UP.pattern as pattern + from + ( select + Permissions.labelId as labelId, + PerItems.item as pattern + from + Users, UserGroupMembers, Permissions + left outer join Items as PerItems + on Permissions.itemId = PerItems.itemId + where + Users.user = 'limited' + and Users.userId = UserGroupMembers.userId + and UserGroupMembers.userGroupId = Permissions.userGroupId + ) as UP join LabelMap on ( UP.labelId = 0 or + UP.labelId = LabelMap.labelId ), + Labels, Items + where + Labels.label = 'localhost@rpl:branch' + and Labels.labelId = LabelMap.labelId + and LabelMap.itemId = Items.itemId + ORDER BY +trove, +pattern + } +} {double .*:runtime double:runtime .*:runtime double:source .*:runtime} + +# Create an index and rerun the query. +# Verify that the results are the same +# +do_test tkt1443-1.2 { + execsql { + CREATE UNIQUE INDEX PermissionsIdx + ON Permissions(userGroupId, labelId, itemId); + select distinct + Items.Item as trove, UP.pattern as pattern + from + ( select + Permissions.labelId as labelId, + PerItems.item as pattern + from + Users, UserGroupMembers, Permissions + left outer join Items as PerItems + on Permissions.itemId = PerItems.itemId + where + Users.user = 'limited' + and Users.userId = UserGroupMembers.userId + and UserGroupMembers.userGroupId = Permissions.userGroupId + ) as UP join LabelMap on ( UP.labelId = 0 or + UP.labelId = LabelMap.labelId ), + Labels, Items + where + Labels.label = 'localhost@rpl:branch' + and Labels.labelId = LabelMap.labelId + and LabelMap.itemId = Items.itemId + ORDER BY +trove, +pattern + } +} {double .*:runtime double:runtime .*:runtime double:source .*:runtime} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1444.test b/components/external/SQLite-3.8.1/test/tkt1444.test new file mode 100644 index 0000000000000000000000000000000000000000..13870db8e807ce62eaef919922e450b74125e447 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1444.test @@ -0,0 +1,56 @@ +# 2005 September 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1444 has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound||!view { + finish_test + return +} + +# The use of a VIEW that contained an ORDER BY clause within a UNION ALL +# was causing problems. See ticket #1444. +# +do_test tkt1444-1.1 { + execsql { + CREATE TABLE DemoTable (x INTEGER, TextKey TEXT, DKey Real); + CREATE INDEX DemoTableIdx ON DemoTable (TextKey); + INSERT INTO DemoTable VALUES(9,8,7); + INSERT INTO DemoTable VALUES(1,2,3); + CREATE VIEW DemoView AS SELECT * FROM DemoTable ORDER BY TextKey; + SELECT * FROM DemoTable UNION ALL SELECT * FROM DemoView ORDER BY 1; + } +} {1 2 3.0 1 2 3.0 9 8 7.0 9 8 7.0} +do_test tkt1444-1.2 { + execsql { + SELECT * FROM DemoTable UNION ALL SELECT * FROM DemoView; + } +} {9 8 7.0 1 2 3.0 1 2 3.0 9 8 7.0} +do_test tkt1444-1.3 { + execsql { + DROP VIEW DemoView; + CREATE VIEW DemoView AS SELECT * FROM DemoTable; + SELECT * FROM DemoTable UNION ALL SELECT * FROM DemoView ORDER BY 1; + } +} {1 2 3.0 1 2 3.0 9 8 7.0 9 8 7.0} +do_test tkt1444-1.4 { + execsql { + SELECT * FROM DemoTable UNION ALL SELECT * FROM DemoView; + } +} {9 8 7.0 1 2 3.0 9 8 7.0 1 2 3.0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1449.test b/components/external/SQLite-3.8.1/test/tkt1449.test new file mode 100644 index 0000000000000000000000000000000000000000..5f27ee7a4c6d6b09396309ecd115b9ba9fcab352 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1449.test @@ -0,0 +1,262 @@ +# 2005 September 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1449 has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Somewhere in tkt1449-1.1 is a VIEW definition that uses a subquery and +# a compound SELECT. So we cannot run this file if any of these features +# are not available. +ifcapable !subquery||!compound||!view { + finish_test + return +} + +# The following schema generated problems in ticket #1449. We've retained +# the original schema here because it is some unbelievably complex, it seemed +# like a good test case for SQLite. +# +do_test tkt1449-1.1 { + execsql { + BEGIN; + CREATE TABLE ACLS(ISSUEID text(50) not null, OBJECTID text(50) not null, PARTICIPANTID text(50) not null, PERMISSIONBITS int not null, constraint PK_ACLS primary key (ISSUEID, OBJECTID, PARTICIPANTID)); + CREATE TABLE ACTIONITEMSTATUSES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, FRIENDLYNAME text(100) not null, REVISION int not null, SHORTNAME text(30) not null, LONGNAME text(200) not null, ATTACHMENTHANDLING int not null, RESULT int not null, NOTIFYCREATOR text(1) null, NOTIFYASSIGNEE text(1) null, NOTIFYFYI text(1) null, NOTIFYCLOSURETEAM text(1) null, NOTIFYCOORDINATORS text(1) null, COMMENTREQUIRED text(1) not null, constraint PK_ACTIONITEMSTATUSES primary key (ISSUEID, OBJECTID)); + CREATE TABLE ACTIONITEMTYPES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, REVISION int not null, LABEL text(200) not null, INSTRUCTIONS text not null, EMAILINSTRUCTIONS text null, ALLOWEDSTATUSES text not null, INITIALSTATUS text(100) not null, COMMENTREQUIRED text(1) not null, ATTACHMENTHANDLING int not null, constraint PK_ACTIONITEMTYPES primary key (ISSUEID, OBJECTID)); + CREATE TABLE ATTACHMENTS(TQUNID text(36) not null, OBJECTID text(50) null, ISSUEID text(50) null, DATASTREAM blob not null, CONTENTENCODING text(50) null, CONTENTCHARSET text(50) null, CONTENTTYPE text(100) null, CONTENTID text(100) null, CONTENTLOCATION text(100) null, CONTENTNAME text(100) not null, constraint PK_ATTACHMENTS primary key (TQUNID)); + CREATE TABLE COMPLIANCEPOLICIES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, BODY text null, constraint PK_COMPLIANCEPOLICIES primary key (ISSUEID, OBJECTID)); + CREATE TABLE DBHISTORY(DATETIME text(25) not null, OPERATION text(20) not null, KUBIVERSION text(100) not null, FROMVERSION int null, TOVERSION int null); + CREATE TABLE DBINFO(FINGERPRINT text(32) not null, VERSION int not null); + CREATE TABLE DETACHEDATTACHMENTS (TQUNID text(36) not null, ISSUEID text(50) not null, OBJECTID text(50) not null, PATH text(300) not null, DETACHEDFILELASTMODTIMESTAMP text(25) null, CONTENTID text(100) not null, constraint PK_DETACHEDATTACHMENTS primary key (TQUNID)); + CREATE TABLE DOCREFERENCES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, REFERENCEDOCUMENTID text(50) null, constraint PK_DOCREFERENCES primary key (ISSUEID, OBJECTID)); + CREATE TABLE DQ (TQUNID text(36) not null, ISSUEID text(50) not null, DEPENDSID text(50) null, DEPENDSTYPE int null, DEPENDSCOMMANDSTREAM blob null, DEPENDSNODEIDSEQNOKEY text(100) null, DEPENDSACLVERSION int null, constraint PK_DQ primary key (TQUNID)); + CREATE TABLE EMAILQ(TIMEQUEUED int not null, NODEID text(50) not null, MIME blob not null, TQUNID text(36) not null); + CREATE TABLE ENTERPRISEDATA(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, DATE1 text(25) null, DATE2 text(25) null, DATE3 text(25) null, DATE4 text(25) null, DATE5 text(25) null, DATE6 text(25) null, DATE7 text(25) null, DATE8 text(25) null, DATE9 text(25) null, DATE10 text(25) null, VALUE1 int null, VALUE2 int null, VALUE3 int null, VALUE4 int null, VALUE5 int null, VALUE6 int null, VALUE7 int null, VALUE8 int null, VALUE9 int null, VALUE10 int null, VALUE11 int null, VALUE12 int null, VALUE13 int null, VALUE14 int null, VALUE15 int null, VALUE16 int null, VALUE17 int null, VALUE18 int null, VALUE19 int null, VALUE20 int null, STRING1 text(300) null, STRING2 text(300) null, STRING3 text(300) null, STRING4 text(300) null, STRING5 text(300) null, STRING6 text(300) null, STRING7 text(300) null, STRING8 text(300) null, STRING9 text(300) null, STRING10 text(300) null, LONGSTRING1 text null, LONGSTRING2 text null, LONGSTRING3 text null, LONGSTRING4 text null, LONGSTRING5 text null, LONGSTRING6 text null, LONGSTRING7 text null, LONGSTRING8 text null, LONGSTRING9 text null, LONGSTRING10 text null, constraint PK_ENTERPRISEDATA primary key (ISSUEID, OBJECTID)); + CREATE TABLE FILEMORGUE(TQUNID text(36) not null, PATH text(300) not null, DELETEFOLDERWHENEMPTY text(1) null, constraint PK_FILEMORGUE primary key (TQUNID)); + CREATE TABLE FILES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARENTENTITYID text(50) null, BODY text null, BODYCONTENTTYPE text(100) null, ISOBSOLETE text(1) null, FILENAME text(300) not null, VISIBLENAME text(300) not null, VERSIONSTRING text(300) not null, DOCUMENTHASH text(40) not null, ISFINAL text(1) null, DOCREFERENCEID text(50) not null, constraint PK_FILES primary key (ISSUEID, OBJECTID)); + CREATE TABLE FOLDERS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, CONTAINERNAME text(300) null, CONTAINERACLSETTINGS text null, constraint PK_FOLDERS primary key (ISSUEID, OBJECTID)); + CREATE TABLE GLOBALSETTINGS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, SINGULARPROJECTLABEL text(30) not null, PLURALPROJECTLABEL text(30) not null, PROJECTREQUIRED text(1) not null, CUSTOMPROJECTSALLOWED text(1) not null, ACTIONITEMSPECXML text null, PROJECTLISTXML text null, ENTERPRISEDATALABELS text null, ENTERPRISEDATATABXSL text null, constraint PK_GLOBALSETTINGS primary key (ISSUEID, OBJECTID)); + CREATE TABLE GLOBALSTRINGPROPERTIES(ID int not null, VALUE text(300) not null, constraint PK_GLOBALSTRINGPROPERTIES primary key (ID)); + CREATE TABLE IMQ(TQUNID text(36) not null, DATETIMEQUEUED text(25) not null, ISSUEID text(50) not null, KUBIBUILD text(30) not null, FAILCOUNT int not null, LASTRUN text(25) null, ENVELOPESTREAM blob not null, PAYLOADSTREAM blob not null, constraint PK_IMQ primary key (TQUNID)); + CREATE TABLE INVITATIONNODES(INVITATIONID text(50) not null, RECIPIENTNODEID text(50) not null, DATECREATED text(25) not null, constraint PK_INVITATIONNODES primary key (INVITATIONID, RECIPIENTNODEID)); + CREATE TABLE INVITATIONS (INVITATIONID text(50) not null, SENDERNODEID text(50) not null, RECIPIENTEMAILADDR text(200) not null, RECIPIENTUSERID text(50) null, RECIPIENTNODES text null, ISSUEID text(50) not null, ENVELOPE text not null, MESSAGEBLOB blob not null, INVITATIONSTATE int not null, TQUNID text(36) not null, DATECREATED text(25) not null); + CREATE TABLE ISSUES (CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, CONTAINERNAME text(300) null, CONTAINERACLSETTINGS text null, ISINITIALIZED text(1) null, BLINDINVITES text null, ISSYSTEMISSUE text(1) not null, ISSUETYPE int not null, ACTIVITYTYPEID text(50) null, ISINCOMPLETE text(1) not null, constraint PK_ISSUES primary key (ISSUEID, OBJECTID)); + CREATE TABLE ISSUESETTINGS (CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, ISSUENAME text(300) not null, ISSUEACLSETTINGS text not null, ISSUEDUEDATE text(25) null, ISSUEPRIORITY int null, ISSUESTATUS int null, DESCRIPTION text null, PROJECTID text(100) null, PROJECTNAME text null, PROJECTNAMEISCUSTOM text(1) null, ISSYSTEMISSUE text(1) not null, ACTIONITEMREVNUM int not null, constraint PK_ISSUESETTINGS primary key (ISSUEID, OBJECTID)); + CREATE TABLE KMTPMSG (MSGID integer not null, SENDERID text(50) null, RECIPIENTIDLIST text not null, ISSUEID text(50) null, MESSAGETYPE int not null, ENVELOPE text null, MESSAGEBLOB blob not null, RECEIVEDDATE text(25) not null, constraint PK_KMTPMSG primary key (MSGID)); + CREATE TABLE KMTPNODEQ(NODEID text(50) not null, MSGID int not null, RECEIVEDDATE text(25) not null, SENDCOUNT int not null); + CREATE TABLE KMTPQ(MSGID integer not null, SENDERID text(50) null, RECIPIENTIDLIST text not null, ISSUEID text(50) null, MESSAGETYPE int not null, ENVELOPE text null, MESSAGEBLOB blob not null, constraint PK_KMTPQ primary key (MSGID)); + CREATE TABLE LOGENTRIES(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARENTENTITYID text(50) null, BODY text null, BODYCONTENTTYPE text(100) null, ISOBSOLETE text(1) null, ACTIONTYPE int not null, ASSOCIATEDOBJECTIDS text null, OLDENTITIES text null, NEWENTITIES text null, OTHERENTITIES text null, constraint PK_LOGENTRIES primary key (ISSUEID, OBJECTID)); + CREATE TABLE LSBI(TQUNID text(36) not null, ISSUEID text(50) not null, TABLEITEMID text(50) null, TABLENODEID text(50) null, TABLECMD int null, TABLECONTAINERID text(50) null, TABLESEQNO int null, DIRTYCONTENT text null, STUBBED text(1) null, ENTITYSTUBDATA text null, UPDATENUMBER int not null, constraint PK_LSBI primary key (TQUNID)); + CREATE TABLE LSBN(TQUNID text(36) not null, ISSUEID text(50) not null, NODEID text(50) not null, STORESEQNO int not null, SYNCSEQNO int not null, LASTMSGDATE text(25) null, constraint PK_LSBN primary key (TQUNID)); + CREATE TABLE MMQ(TQUNID text(36) not null, ISSUEID text(50) not null, TABLEREQUESTNODE text(50) null, MMQENTRYINDEX text(60) null, DIRECTION int null, NODEID text(50) null, TABLEFIRSTSEQNO int null, TABLELASTSEQNO int null, NEXTRESENDTIMEOUT text(25) null, TABLETIMEOUTMULTIPLIER int null, constraint PK_MMQ primary key (TQUNID)); + CREATE TABLE NODEREG(NODEID text(50) not null, USERID text(50) null, CREATETIME text(25) not null, TQUNID text(36) not null); + CREATE TABLE NODES (NODEID text(50) not null, USERID text(50) null, NODESTATE int not null, NODECERT text null, KUBIVERSION int not null, KUBIBUILD text(30) not null, TQUNID text(36) not null, LASTBINDDATE text(25) null, LASTUNBINDDATE text(25) null, LASTBINDIP text(15) null, NUMBINDS int not null, NUMSENDS int not null, NUMPOLLS int not null, NUMRECVS int not null); + CREATE TABLE PARTICIPANTNODES(ISSUEID text(50) not null, OBJECTID text(50) not null, NODEID text(50) not null, USERID text(50) null, NODESTATE int not null, NODECERT text null, KUBIVERSION int not null, KUBIBUILD text(30) not null, TQUNID text(36) not null); + CREATE TABLE PARTICIPANTS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARTICIPANTSTATE int not null, PARTICIPANTROLE int not null, PARTICIPANTTEAM int not null, ISREQUIREDMEMBER text(1) null, USERID text(50) null, ISAGENT text(1) null, NAME text(150) not null, EMAILADDRESS text(200) not null, ISEMAILONLY text(1) not null, INVITATION text null, ACCEPTRESENDCOUNT int null, ACCEPTRESENDTIMEOUT text(25) null, ACCEPTLASTSENTTONODEID text(50) null, constraint PK_PARTICIPANTS primary key (ISSUEID, OBJECTID)); + CREATE TABLE PARTICIPANTSETTINGS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARTICIPANTID text(50) not null, TASKPIMSYNC text(1) null, MOBILESUPPORT text(1) null, NOTIFYBYEMAIL text(1) null, MARKEDCRITICAL text(1) null, constraint PK_PARTICIPANTSETTINGS primary key (ISSUEID, OBJECTID)); + CREATE TABLE PARTITIONS(PARTITIONID text(50) not null, NAME text(100) not null, LDAPDN text(300) not null, SERVERNODEID text(50) not null, TQUNID text(36) not null); + CREATE TABLE PROJECTS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, NAME text(100) not null, ID text(100) null, constraint PK_PROJECTS primary key (ISSUEID, OBJECTID)); + CREATE TABLE TASKCOMPLETIONS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARENTENTITYID text(50) null, BODY text null, BODYCONTENTTYPE text(100) null, ISOBSOLETE text(1) null, TASKID text(50) not null, DISPOSITION int not null, STATUSID text(50) not null, SHORTNAME text(30) not null, LONGNAME text(200) not null, constraint PK_TASKCOMPLETIONS primary key (ISSUEID, OBJECTID)); + CREATE TABLE TASKS(CLASSID int null, SEQNO int not null, LASTMODONNODEID text(50) not null, PREVMODONNODEID text(50) null, ISSUEID text(50) not null, OBJECTID text(50) not null, REVISIONNUM int not null, CONTAINERID text(50) not null, AUTHORID text(50) not null, CREATIONDATE text(25) null, LASTMODIFIEDDATE text(25) null, UPDATENUMBER int null, PREVREVISIONNUM int null, LASTCMD int null, LASTCMDACLVERSION int null, USERDEFINEDFIELD text(300) null, LASTMODIFIEDBYID text(50) null, PARENTENTITYID text(50) null, BODY text null, BODYCONTENTTYPE text(100) null, ISOBSOLETE text(1) null, DUETIME text(25) null, ASSIGNEDTO text(50) not null, TARGETOBJECTIDS text null, RESPONSEID text(50) not null, TYPEID text(50) not null, LABEL text(200) not null, INSTRUCTIONS text not null, ALLOWEDSTATUSES text not null, ISSERIALREVIEW text(1) null, DAYSTOREVIEW int null, REVIEWERIDS text(500) null, REVIEWTYPE int null, REVIEWGROUP text(300) null, constraint PK_TASKS primary key (ISSUEID, OBJECTID)); + CREATE TABLE USERS (USERID text(50) not null, USERSID text(100) not null, ENTERPRISEUSER text(1) not null, USEREMAILADDRESS text(200) null, EMAILVALIDATED text(1) null, VALIDATIONCOOKIE text(50) null, CREATETIME text(25) not null, TQUNID text(36) not null, PARTITIONID text(50) null); + CREATE VIEW CRITICALISSUES as + + + select + USERID, ISSUEID, ISSUENAME, min(DATE1) DATE1 + from ( + select p.USERID USERID, p.ISSUEID ISSUEID, iset.ISSUENAME ISSUENAME, t.DUETIME DATE1 + from PARTICIPANTS p + join TASKS t on t.ASSIGNEDTO = p.OBJECTID + join TASKCOMPLETIONS tc on tc.TASKID = t.OBJECTID + join ISSUESETTINGS iset on iset.ISSUEID = p.ISSUEID + where (t.ISOBSOLETE = 'n' or t.ISOBSOLETE is null) + and tc.DISPOSITION = 1 + and iset.ISSUESTATUS = 1 + union + select p.USERID USERID, p.ISSUEID ISSUEID, iset.ISSUENAME ISSUENAME, iset.ISSUEDUEDATE DATE1 + from PARTICIPANTS p + join PARTICIPANTSETTINGS ps on ps.PARTICIPANTID = p.OBJECTID + join ISSUESETTINGS iset on iset.ISSUEID = p.ISSUEID + where ps.MARKEDCRITICAL = 'y' + and iset.ISSUESTATUS = 1 + ) as CRITICALDATA + group by USERID, ISSUEID, ISSUENAME; + CREATE VIEW CURRENTFILES as + + + select + d.ISSUEID as ISSUEID, + d.REFERENCEDOCUMENTID as OBJECTID, + f.VISIBLENAME as VISIBLENAME + from + DOCREFERENCES d + join FILES f on f.OBJECTID = d.REFERENCEDOCUMENTID; + CREATE VIEW ISSUEDATA as + + + select + ISSUES.OBJECTID as ISSUEID, + ISSUES.CREATIONDATE as CREATIONDATE, + ISSUES.AUTHORID as AUTHORID, + ISSUES.LASTMODIFIEDDATE as LASTMODIFIEDDATE, + ISSUES.LASTMODIFIEDBYID as LASTMODIFIEDBYID, + ISSUESETTINGS.ISSUENAME as ISSUENAME, + ISSUES.ISINITIALIZED as ISINITIALIZED, + ISSUES.ISSYSTEMISSUE as ISSYSTEMISSUE, + ISSUES.ISSUETYPE as ISSUETYPE, + ISSUES.ISINCOMPLETE as ISINCOMPLETE, + ISSUESETTINGS.REVISIONNUM as ISSUESETTINGS_REVISIONNUM, + ISSUESETTINGS.LASTMODIFIEDDATE as ISSUESETTINGS_LASTMODIFIEDDATE, + ISSUESETTINGS.LASTMODIFIEDBYID as ISSUESETTINGS_LASTMODIFIEDBYID, + ISSUESETTINGS.ISSUEDUEDATE as ISSUEDUEDATE, + ISSUESETTINGS.ISSUEPRIORITY as ISSUEPRIORITY, + ISSUESETTINGS.ISSUESTATUS as ISSUESTATUS, + ISSUESETTINGS.DESCRIPTION as DESCRIPTION, + ISSUESETTINGS.PROJECTID as PROJECTID, + ISSUESETTINGS.PROJECTNAME as PROJECTNAME, + ISSUESETTINGS.PROJECTNAMEISCUSTOM as PROJECTNAMEISCUSTOM, + ENTERPRISEDATA.REVISIONNUM as ENTERPRISEDATA_REVISIONNUM, + ENTERPRISEDATA.CREATIONDATE as ENTERPRISEDATA_CREATIONDATE, + ENTERPRISEDATA.AUTHORID as ENTERPRISEDATA_AUTHORID, + ENTERPRISEDATA.LASTMODIFIEDDATE as ENTERPRISEDATA_LASTMODIFIEDDATE, + ENTERPRISEDATA.LASTMODIFIEDBYID as ENTERPRISEDATA_LASTMODIFIEDBYID, + ENTERPRISEDATA.DATE1 as DATE1, + ENTERPRISEDATA.DATE2 as DATE2, + ENTERPRISEDATA.DATE3 as DATE3, + ENTERPRISEDATA.DATE4 as DATE4, + ENTERPRISEDATA.DATE5 as DATE5, + ENTERPRISEDATA.DATE6 as DATE6, + ENTERPRISEDATA.DATE7 as DATE7, + ENTERPRISEDATA.DATE8 as DATE8, + ENTERPRISEDATA.DATE9 as DATE9, + ENTERPRISEDATA.DATE10 as DATE10, + ENTERPRISEDATA.VALUE1 as VALUE1, + ENTERPRISEDATA.VALUE2 as VALUE2, + ENTERPRISEDATA.VALUE3 as VALUE3, + ENTERPRISEDATA.VALUE4 as VALUE4, + ENTERPRISEDATA.VALUE5 as VALUE5, + ENTERPRISEDATA.VALUE6 as VALUE6, + ENTERPRISEDATA.VALUE7 as VALUE7, + ENTERPRISEDATA.VALUE8 as VALUE8, + ENTERPRISEDATA.VALUE9 as VALUE9, + ENTERPRISEDATA.VALUE10 as VALUE10, + ENTERPRISEDATA.VALUE11 as VALUE11, + ENTERPRISEDATA.VALUE12 as VALUE12, + ENTERPRISEDATA.VALUE13 as VALUE13, + ENTERPRISEDATA.VALUE14 as VALUE14, + ENTERPRISEDATA.VALUE15 as VALUE15, + ENTERPRISEDATA.VALUE16 as VALUE16, + ENTERPRISEDATA.VALUE17 as VALUE17, + ENTERPRISEDATA.VALUE18 as VALUE18, + ENTERPRISEDATA.VALUE19 as VALUE19, + ENTERPRISEDATA.VALUE20 as VALUE20, + ENTERPRISEDATA.STRING1 as STRING1, + ENTERPRISEDATA.STRING2 as STRING2, + ENTERPRISEDATA.STRING3 as STRING3, + ENTERPRISEDATA.STRING4 as STRING4, + ENTERPRISEDATA.STRING5 as STRING5, + ENTERPRISEDATA.STRING6 as STRING6, + ENTERPRISEDATA.STRING7 as STRING7, + ENTERPRISEDATA.STRING8 as STRING8, + ENTERPRISEDATA.STRING9 as STRING9, + ENTERPRISEDATA.STRING10 as STRING10, + ENTERPRISEDATA.LONGSTRING1 as LONGSTRING1, + ENTERPRISEDATA.LONGSTRING2 as LONGSTRING2, + ENTERPRISEDATA.LONGSTRING3 as LONGSTRING3, + ENTERPRISEDATA.LONGSTRING4 as LONGSTRING4, + ENTERPRISEDATA.LONGSTRING5 as LONGSTRING5, + ENTERPRISEDATA.LONGSTRING6 as LONGSTRING6, + ENTERPRISEDATA.LONGSTRING7 as LONGSTRING7, + ENTERPRISEDATA.LONGSTRING8 as LONGSTRING8, + ENTERPRISEDATA.LONGSTRING9 as LONGSTRING9, + ENTERPRISEDATA.LONGSTRING10 as LONGSTRING10 + from + ISSUES + join ISSUESETTINGS on ISSUES.OBJECTID = ISSUESETTINGS.ISSUEID + left outer join ENTERPRISEDATA on ISSUES.OBJECTID = ENTERPRISEDATA.ISSUEID; + CREATE VIEW ITEMS as + + select 'FILES' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, PARENTENTITYID, BODY, BODYCONTENTTYPE, ISOBSOLETE, FILENAME, VISIBLENAME, VERSIONSTRING, DOCUMENTHASH, ISFINAL, DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from FILES + union all + select 'LOGENTRIES' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, PARENTENTITYID, BODY, BODYCONTENTTYPE, ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, ACTIONTYPE, ASSOCIATEDOBJECTIDS, OLDENTITIES, NEWENTITIES, OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from LOGENTRIES + union all + select 'LSBI' as TABLENAME, NULL as CLASSID, NULL as SEQNO, NULL as LASTMODONNODEID, NULL as PREVMODONNODEID, ISSUEID, NULL as OBJECTID, NULL as REVISIONNUM, NULL as CONTAINERID, NULL as AUTHORID, NULL as CREATIONDATE, NULL as LASTMODIFIEDDATE, UPDATENUMBER, NULL as PREVREVISIONNUM, NULL as LASTCMD, NULL as LASTCMDACLVERSION, NULL as USERDEFINEDFIELD, NULL as LASTMODIFIEDBYID, NULL as PARENTENTITYID, NULL as BODY, NULL as BODYCONTENTTYPE, NULL as ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, TQUNID, TABLEITEMID, TABLENODEID, TABLECMD, TABLECONTAINERID, TABLESEQNO, DIRTYCONTENT, STUBBED, ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from LSBI where TABLECMD=3 + union all + select 'PARTICIPANTS' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, NULL as PARENTENTITYID, NULL as BODY, NULL as BODYCONTENTTYPE, NULL as ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, PARTICIPANTSTATE, PARTICIPANTROLE, PARTICIPANTTEAM, ISREQUIREDMEMBER, USERID, ISAGENT, NAME, EMAILADDRESS, ISEMAILONLY, INVITATION, ACCEPTRESENDCOUNT, ACCEPTRESENDTIMEOUT, ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from PARTICIPANTS + union all + select 'TASKCOMPLETIONS' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, PARENTENTITYID, BODY, BODYCONTENTTYPE, ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, TASKID, DISPOSITION, STATUSID, SHORTNAME, LONGNAME, NULL as DUETIME, NULL as ASSIGNEDTO, NULL as TARGETOBJECTIDS, NULL as RESPONSEID, NULL as TYPEID, NULL as LABEL, NULL as INSTRUCTIONS, NULL as ALLOWEDSTATUSES, NULL as ISSERIALREVIEW, NULL as DAYSTOREVIEW, NULL as REVIEWERIDS, NULL as REVIEWTYPE, NULL as REVIEWGROUP from TASKCOMPLETIONS + union all + select 'TASKS' as TABLENAME, CLASSID, SEQNO, LASTMODONNODEID, PREVMODONNODEID, ISSUEID, OBJECTID, REVISIONNUM, CONTAINERID, AUTHORID, CREATIONDATE, LASTMODIFIEDDATE, UPDATENUMBER, PREVREVISIONNUM, LASTCMD, LASTCMDACLVERSION, USERDEFINEDFIELD, LASTMODIFIEDBYID, PARENTENTITYID, BODY, BODYCONTENTTYPE, ISOBSOLETE, NULL as FILENAME, NULL as VISIBLENAME, NULL as VERSIONSTRING, NULL as DOCUMENTHASH, NULL as ISFINAL, NULL as DOCREFERENCEID, NULL as ACTIONTYPE, NULL as ASSOCIATEDOBJECTIDS, NULL as OLDENTITIES, NULL as NEWENTITIES, NULL as OTHERENTITIES, NULL as TQUNID, NULL as TABLEITEMID, NULL as TABLENODEID, NULL as TABLECMD, NULL as TABLECONTAINERID, NULL as TABLESEQNO, NULL as DIRTYCONTENT, NULL as STUBBED, NULL as ENTITYSTUBDATA, NULL as PARTICIPANTSTATE, NULL as PARTICIPANTROLE, NULL as PARTICIPANTTEAM, NULL as ISREQUIREDMEMBER, NULL as USERID, NULL as ISAGENT, NULL as NAME, NULL as EMAILADDRESS, NULL as ISEMAILONLY, NULL as INVITATION, NULL as ACCEPTRESENDCOUNT, NULL as ACCEPTRESENDTIMEOUT, NULL as ACCEPTLASTSENTTONODEID, NULL as TASKID, NULL as DISPOSITION, NULL as STATUSID, NULL as SHORTNAME, NULL as LONGNAME, DUETIME, ASSIGNEDTO, TARGETOBJECTIDS, RESPONSEID, TYPEID, LABEL, INSTRUCTIONS, ALLOWEDSTATUSES, ISSERIALREVIEW, DAYSTOREVIEW, REVIEWERIDS, REVIEWTYPE, REVIEWGROUP from TASKS; + CREATE VIEW TASKINFO as + + + select + t.ISSUEID as ISSUEID, + t.OBJECTID as OBJECTID, + t.ASSIGNEDTO as ASSIGNEDTO, + t.TARGETOBJECTIDS as TARGETOBJECTIDS, + t.DUETIME as DUETIME, + t.ISOBSOLETE as ISOBSOLETE, + tc.DISPOSITION as DISPOSITION + from + TASKS t + join TASKCOMPLETIONS tc on tc.TASKID = t.OBJECTID; + CREATE INDEX DQ_ISSUEID_DEPENDSID on DQ (ISSUEID, DEPENDSID); + CREATE INDEX EMAILQ_TIMEQUEUED on EMAILQ (TIMEQUEUED); + CREATE INDEX FOLDERS_CONTAINERID_ISSUEID on FOLDERS (CONTAINERID, ISSUEID); + CREATE INDEX IMQ_DATETIMEQUEUED on IMQ (DATETIMEQUEUED); + CREATE INDEX INVITATIONS_RECIPIENTUSERID_INVITATIONID on INVITATIONS (RECIPIENTUSERID, INVITATIONID); + CREATE INDEX INVITATIONS_TQUNID on INVITATIONS (TQUNID); + CREATE INDEX ISSUESETTINGS_CONTAINERID on ISSUESETTINGS (CONTAINERID); + CREATE INDEX KMTPMSG_RECEIVEDDATE on KMTPMSG (RECEIVEDDATE desc); + CREATE INDEX KMTPNODEQ_MSGID on KMTPNODEQ (MSGID); + CREATE INDEX KMTPNODEQ_NODEID_MSGID on KMTPNODEQ (NODEID, MSGID); + CREATE INDEX KMTPNODEQ_RECEIVEDDATE on KMTPNODEQ (RECEIVEDDATE desc); + CREATE INDEX LSBI_ISSUEID_TABLEITEMID on LSBI (ISSUEID, TABLEITEMID); + CREATE INDEX LSBN_ISSUEID_NODEID on LSBN (ISSUEID, NODEID); + CREATE INDEX MMQ_ISSUEID_MMQENTRYINDEX on MMQ (ISSUEID, MMQENTRYINDEX); + CREATE INDEX NODEREG_NODEID_USERID on NODEREG (NODEID, USERID); + CREATE INDEX NODEREG_TQUNID on NODEREG (TQUNID); + CREATE INDEX NODEREG_USERID_NODEID on NODEREG (USERID, NODEID); + CREATE INDEX NODES_NODEID on NODES (NODEID); + CREATE INDEX NODES_TQUNID on NODES (TQUNID); + CREATE INDEX PARTICIPANTNODES_ISSUEID_OBJECTID_NODEID on PARTICIPANTNODES (ISSUEID, OBJECTID, NODEID); + CREATE INDEX PARTICIPANTNODES_TQUNID on PARTICIPANTNODES (TQUNID); + CREATE INDEX PARTICIPANTSETTINGS_PARTICIPANTID on PARTICIPANTSETTINGS (PARTICIPANTID); + CREATE INDEX PARTITIONS_LDAPDN on PARTITIONS (LDAPDN); + CREATE INDEX PARTITIONS_PARTITIONID_SERVERNODEID on PARTITIONS (PARTITIONID, SERVERNODEID); + CREATE INDEX PARTITIONS_SERVERNODEID_PARTITIONID on PARTITIONS (SERVERNODEID, PARTITIONID); + CREATE INDEX PARTITIONS_TQUNID on PARTITIONS (TQUNID); + CREATE INDEX TASKCOMPLETIONS_TASKID on TASKCOMPLETIONS (TASKID); + CREATE INDEX TASKS_ASSIGNEDTO on TASKS (ASSIGNEDTO); + CREATE INDEX USERS_PARTITIONID_USERID on USERS (PARTITIONID, USERID); + CREATE INDEX USERS_TQUNID on USERS (TQUNID); + CREATE INDEX USERS_USERID_PARTITIONID on USERS (USERID, PARTITIONID); + CREATE INDEX USERS_USERSID_USERID on USERS (USERSID, USERID); + COMMIT; + } +} {} + +# Given the schema above, the following query was cause an assertion fault +# do to an uninitialized field in a Select structure. +# +do_test tkt1449-1.2 { + execsql { + select NEWENTITIES from ITEMS where ((ISSUEID = 'x') and (OBJECTID = 'y')) + } +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1473.test b/components/external/SQLite-3.8.1/test/tkt1473.test new file mode 100644 index 0000000000000000000000000000000000000000..3950272f0498e772772236d9488864000e334971 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1473.test @@ -0,0 +1,728 @@ +# 2005 September 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1473 has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_test tkt1473-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + SELECT * FROM t1 + } +} {1 2 3 4} + +do_test tkt1473-1.2 { + execsql { + SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=0 + } +} {1} +do_test tkt1473-1.3 { + execsql { + SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=0 + } +} {1} +do_test tkt1473-1.4 { + execsql { + SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=4 + } +} {1 2} +do_test tkt1473-1.5 { + execsql { + SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=4 + } +} {1 2} +do_test tkt1473-1.6 { + execsql { + SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=4 + } +} {2} +do_test tkt1473-1.7 { + execsql { + SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=4 + } +} {2} +do_test tkt1473-1.8 { + execsql { + SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=0 + } +} {} +do_test tkt1473-1.9 { + execsql { + SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=0 + } +} {} + +# Everything from this point on depends on sub-queries. So skip it +# if sub-queries are not available. +ifcapable !subquery { + finish_test + return +} + +do_test tkt1473-2.2 { + execsql { + SELECT (SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=0) + } +} {1} +do_test tkt1473-2.3 { + execsql { + SELECT (SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=0) + } +} {1} +do_test tkt1473-2.4 { + execsql { + SELECT (SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=4) + } +} {1} +do_test tkt1473-2.5 { + execsql { + SELECT (SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=4) + } +} {1} +do_test tkt1473-2.6 { + execsql { + SELECT (SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=4) + } +} {2} +do_test tkt1473-2.7 { + execsql { + SELECT (SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=4) + } +} {2} +do_test tkt1473-2.8 { + execsql { + SELECT (SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=0) + } +} {{}} +do_test tkt1473-2.9 { + execsql { + SELECT (SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=0) + } +} {{}} + +do_test tkt1473-3.2 { + execsql { + SELECT EXISTS + (SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=0) + } +} {1} +do_test tkt1473-3.3 { + execsql { + SELECT EXISTS + (SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=0) + } +} {1} +do_test tkt1473-3.4 { + execsql { + SELECT EXISTS + (SELECT 1 FROM t1 WHERE a=1 UNION ALL SELECT 2 FROM t1 WHERE b=4) + } +} {1} +do_test tkt1473-3.5 { + execsql { + SELECT EXISTS + (SELECT 1 FROM t1 WHERE a=1 UNION SELECT 2 FROM t1 WHERE b=4) + } +} {1} +do_test tkt1473-3.6 { + execsql { + SELECT EXISTS + (SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=4) + } +} {1} +do_test tkt1473-3.7 { + execsql { + SELECT EXISTS + (SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=4) + } +} {1} +do_test tkt1473-3.8 { + execsql { + SELECT EXISTS + (SELECT 1 FROM t1 WHERE a=0 UNION ALL SELECT 2 FROM t1 WHERE b=0) + } +} {0} +do_test tkt1473-3.9 { + execsql { + SELECT EXISTS + (SELECT 1 FROM t1 WHERE a=0 UNION SELECT 2 FROM t1 WHERE b=0) + } +} {0} + +do_test tkt1473-4.1 { + execsql { + CREATE TABLE t2(x,y); + INSERT INTO t2 VALUES(1,2); + INSERT INTO t2 SELECT x+2, y+2 FROM t2; + INSERT INTO t2 SELECT x+4, y+4 FROM t2; + INSERT INTO t2 SELECT x+8, y+8 FROM t2; + INSERT INTO t2 SELECT x+16, y+16 FROM t2; + INSERT INTO t2 SELECT x+32, y+32 FROM t2; + INSERT INTO t2 SELECT x+64, y+64 FROM t2; + SELECT count(*), sum(x), sum(y) FROM t2; + } +} {64 4096 4160} +do_test tkt1473-4.2 { + execsql { + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=3 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=2 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=4 + } +} {2 4 8 10} +do_test tkt1473-4.3 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=3 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=2 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {2} +do_test tkt1473-4.4 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=-1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=3 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=2 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {4} +do_test tkt1473-4.5 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=-1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=-1 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=2 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=-4 + ) + } +} {8} +do_test tkt1473-4.6 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=-1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=-2 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=-3 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {10} +do_test tkt1473-4.7 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=-1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=-2 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=-3 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=-4 + ) + } +} {{}} + +do_test tkt1473-5.3 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=3 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=2 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {1} +do_test tkt1473-5.4 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=-1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=3 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=2 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {1} + +do_test tkt1473-5.5 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=-1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=-1 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=2 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=-4 + ) + } +} {1} +do_test tkt1473-5.6 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=-1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=-2 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=-3 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {1} +do_test tkt1473-5.7 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION ALL + SELECT 2 FROM t2 WHERE x=-1 + UNION ALL + SELECT 3 FROM t2 WHERE x=2 + UNION ALL + SELECT 4 FROM t2 WHERE x=-2 + UNION ALL + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION ALL + SELECT 7 FROM t2 WHERE y=1 + UNION ALL + SELECT 8 FROM t2 WHERE y=-3 + UNION ALL + SELECT 9 FROM t2 WHERE y=3 + UNION ALL + SELECT 10 FROM t2 WHERE y=-4 + ) + } +} {0} + +do_test tkt1473-6.3 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION + SELECT 2 FROM t2 WHERE x=1 + UNION + SELECT 3 FROM t2 WHERE x=2 + UNION + SELECT 4 FROM t2 WHERE x=3 + UNION + SELECT 5 FROM t2 WHERE x=4 + UNION + SELECT 6 FROM t2 WHERE y=0 + UNION + SELECT 7 FROM t2 WHERE y=1 + UNION + SELECT 8 FROM t2 WHERE y=2 + UNION + SELECT 9 FROM t2 WHERE y=3 + UNION + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {1} +do_test tkt1473-6.4 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION + SELECT 2 FROM t2 WHERE x=-1 + UNION + SELECT 3 FROM t2 WHERE x=2 + UNION + SELECT 4 FROM t2 WHERE x=3 + UNION + SELECT 5 FROM t2 WHERE x=4 + UNION + SELECT 6 FROM t2 WHERE y=0 + UNION + SELECT 7 FROM t2 WHERE y=1 + UNION + SELECT 8 FROM t2 WHERE y=2 + UNION + SELECT 9 FROM t2 WHERE y=3 + UNION + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {1} + +do_test tkt1473-6.5 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION + SELECT 2 FROM t2 WHERE x=-1 + UNION + SELECT 3 FROM t2 WHERE x=2 + UNION + SELECT 4 FROM t2 WHERE x=-1 + UNION + SELECT 5 FROM t2 WHERE x=4 + UNION + SELECT 6 FROM t2 WHERE y=0 + UNION + SELECT 7 FROM t2 WHERE y=1 + UNION + SELECT 8 FROM t2 WHERE y=2 + UNION + SELECT 9 FROM t2 WHERE y=3 + UNION + SELECT 10 FROM t2 WHERE y=-4 + ) + } +} {1} +do_test tkt1473-6.6 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION + SELECT 2 FROM t2 WHERE x=-1 + UNION + SELECT 3 FROM t2 WHERE x=2 + UNION + SELECT 4 FROM t2 WHERE x=-2 + UNION + SELECT 5 FROM t2 WHERE x=4 + UNION + SELECT 6 FROM t2 WHERE y=0 + UNION + SELECT 7 FROM t2 WHERE y=1 + UNION + SELECT 8 FROM t2 WHERE y=-3 + UNION + SELECT 9 FROM t2 WHERE y=3 + UNION + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {1} +do_test tkt1473-6.7 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION + SELECT 2 FROM t2 WHERE x=-1 + UNION + SELECT 3 FROM t2 WHERE x=2 + UNION + SELECT 4 FROM t2 WHERE x=-2 + UNION + SELECT 5 FROM t2 WHERE x=4 + UNION + SELECT 6 FROM t2 WHERE y=0 + UNION + SELECT 7 FROM t2 WHERE y=1 + UNION + SELECT 8 FROM t2 WHERE y=-3 + UNION + SELECT 9 FROM t2 WHERE y=3 + UNION + SELECT 10 FROM t2 WHERE y=-4 + ) + } +} {0} +do_test tkt1473-6.8 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION + SELECT 2 FROM t2 WHERE x=-1 + UNION + SELECT 3 FROM t2 WHERE x=2 + UNION + SELECT 4 FROM t2 WHERE x=-2 + UNION + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION + SELECT 7 FROM t2 WHERE y=1 + UNION + SELECT 8 FROM t2 WHERE y=-3 + UNION + SELECT 9 FROM t2 WHERE y=3 + UNION + SELECT 10 FROM t2 WHERE y=4 + ) + } +} {1} +do_test tkt1473-6.9 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 + UNION + SELECT 2 FROM t2 WHERE x=-1 + UNION + SELECT 3 FROM t2 WHERE x=2 + UNION + SELECT 4 FROM t2 WHERE x=-2 + UNION + SELECT 5 FROM t2 WHERE x=4 + UNION ALL + SELECT 6 FROM t2 WHERE y=0 + UNION + SELECT 7 FROM t2 WHERE y=1 + UNION + SELECT 8 FROM t2 WHERE y=-3 + UNION + SELECT 9 FROM t2 WHERE y=3 + UNION + SELECT 10 FROM t2 WHERE y=-4 + ) + } +} {0} + +do_test tkt1473-7.1 { + execsql { + SELECT 1 FROM t2 WHERE x=1 EXCEPT SELECT 2 FROM t2 WHERE y=2 + } +} {1} +do_test tkt1473-7.2 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=1 EXCEPT SELECT 2 FROM t2 WHERE y=2 + ) + } +} {1} +do_test tkt1473-7.3 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=1 EXCEPT SELECT 2 FROM t2 WHERE y=2 + ) + } +} {1} +do_test tkt1473-7.4 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=0 EXCEPT SELECT 2 FROM t2 WHERE y=2 + ) + } +} {{}} +do_test tkt1473-7.5 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=0 EXCEPT SELECT 2 FROM t2 WHERE y=2 + ) + } +} {0} + +do_test tkt1473-8.1 { + execsql { + SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 2 FROM t2 WHERE y=2 + } +} {} +do_test tkt1473-8.1 { + execsql { + SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 1 FROM t2 WHERE y=2 + } +} {1} +do_test tkt1473-8.3 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 2 FROM t2 WHERE y=2 + ) + } +} {{}} +do_test tkt1473-8.4 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 1 FROM t2 WHERE y=2 + ) + } +} {1} +do_test tkt1473-8.5 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 2 FROM t2 WHERE y=2 + ) + } +} {0} +do_test tkt1473-8.6 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 1 FROM t2 WHERE y=2 + ) + } +} {1} +do_test tkt1473-8.7 { + execsql { + SELECT ( + SELECT 1 FROM t2 WHERE x=0 INTERSECT SELECT 1 FROM t2 WHERE y=2 + ) + } +} {{}} +do_test tkt1473-8.8 { + execsql { + SELECT EXISTS ( + SELECT 1 FROM t2 WHERE x=1 INTERSECT SELECT 1 FROM t2 WHERE y=0 + ) + } +} {0} + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1501.test b/components/external/SQLite-3.8.1/test/tkt1501.test new file mode 100644 index 0000000000000000000000000000000000000000..19ec7f7e8f629439fe0b987ced8fdb4ca8d0d23a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1501.test @@ -0,0 +1,36 @@ +# 2005 November 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1501 is +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_test tkt1501-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + SELECT a, b, 'abc' FROM t1 + UNION + SELECT b, a, 'xyz' FROM t1 + ORDER BY 2, 3; + } +} {2 1 xyz 1 2 abc} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1512.test b/components/external/SQLite-3.8.1/test/tkt1512.test new file mode 100644 index 0000000000000000000000000000000000000000..a2c39dbe48602453a3f61afb399af86420aaf288 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1512.test @@ -0,0 +1,54 @@ +# 2005 September 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1512 is +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable {!vacuum || !autovacuum} { + finish_test + return +} +if {[db one {PRAGMA auto_vacuum}]} { + finish_test + return +} + +do_test tkt1512-1.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(3,4); + SELECT * FROM t1 + } +} {1 2 3 4} +do_test tkt1512-1.2 { + file size test.db +} {2048} +do_test tkt1512-1.3 { + execsql { + DROP TABLE t1; + } + file size test.db +} {2048} +do_test tkt1512-1.4 { + execsql { + VACUUM; + } + file size test.db +} {1024} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1514.test b/components/external/SQLite-3.8.1/test/tkt1514.test new file mode 100644 index 0000000000000000000000000000000000000000..1dfae1d97a10f4f93d4ebc1b26a070ee138b7360 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1514.test @@ -0,0 +1,27 @@ +# 2005 November 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1514 is +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt1514-1.1 { + catchsql { + CREATE TABLE t1(a,b); + SELECT a FROM t1 WHERE max(b)<10 GROUP BY a; + } +} {1 {misuse of aggregate: max()}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1536.test b/components/external/SQLite-3.8.1/test/tkt1536.test new file mode 100644 index 0000000000000000000000000000000000000000..46e46192b6108c60b7c5559735813277e617e300 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1536.test @@ -0,0 +1,38 @@ +# 2005 November 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1536 is +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt1536-1.1 { + execsql { + CREATE TABLE t1( + a INTEGER PRIMARY KEY, + b TEXT + ); + INSERT INTO t1 VALUES(1,'01'); + SELECT typeof(a), typeof(b) FROM t1; + } +} {integer text} +do_test tkt1536-1.2 { + execsql { + INSERT INTO t1(b) SELECT b FROM t1; + SELECT b FROM t1 WHERE rowid=2; + } +} {01} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1537.test b/components/external/SQLite-3.8.1/test/tkt1537.test new file mode 100644 index 0000000000000000000000000000000000000000..633f91fceef2eee16bc31cab4eff6a839124f807 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1537.test @@ -0,0 +1,122 @@ +# 2005 November 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1537 is +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt1537-1.1 { + execsql { + CREATE TABLE t1(id, a1, a2); + INSERT INTO t1 VALUES(1, NULL, NULL); + INSERT INTO t1 VALUES(2, 1, 3); + CREATE TABLE t2(id, b); + INSERT INTO t2 VALUES(3, 1); + INSERT INTO t2 VALUES(4, NULL); + SELECT * FROM t1 LEFT JOIN t2 ON a1=b OR a2=+b; + } +} {1 {} {} {} {} 2 1 3 3 1} +do_test tkt1537-1.2 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON a1=b OR a2=b; + } +} {1 {} {} {} {} 2 1 3 3 1} +do_test tkt1537-1.3 { + execsql { + SELECT * FROM t2 LEFT JOIN t1 ON a1=b OR a2=b; + } +} {3 1 2 1 3 4 {} {} {} {}} +ifcapable subquery { + do_test tkt1537-1.4 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b IN (a1,a2); + } + } {1 {} {} {} {} 2 1 3 3 1} + do_test tkt1537-1.5 { + execsql { + SELECT * FROM t2 LEFT JOIN t1 ON b IN (a2,a1); + } + } {3 1 2 1 3 4 {} {} {} {}} +} +do_test tkt1537-1.6 { + execsql { + CREATE INDEX t1a1 ON t1(a1); + CREATE INDEX t1a2 ON t1(a2); + CREATE INDEX t2b ON t2(b); + SELECT * FROM t1 LEFT JOIN t2 ON a1=b OR a2=b; + } +} {1 {} {} {} {} 2 1 3 3 1} +do_test tkt1537-1.7 { + execsql { + SELECT * FROM t2 LEFT JOIN t1 ON a1=b OR a2=b; + } +} {3 1 2 1 3 4 {} {} {} {}} + +ifcapable subquery { + do_test tkt1537-1.8 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b IN (a1,a2); + } + } {1 {} {} {} {} 2 1 3 3 1} + do_test tkt1537-1.9 { + execsql { + SELECT * FROM t2 LEFT JOIN t1 ON b IN (a2,a1); + } + } {3 1 2 1 3 4 {} {} {} {}} +} + +execsql { + DROP INDEX t1a1; + DROP INDEX t1a2; + DROP INDEX t2b; +} + +do_test tkt1537-2.1 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b BETWEEN a1 AND a2; + } +} {1 {} {} {} {} 2 1 3 3 1} +do_test tkt1537-2.2 { + execsql { + CREATE INDEX t2b ON t2(b); + SELECT * FROM t1 LEFT JOIN t2 ON b BETWEEN a1 AND a2; + } +} {1 {} {} {} {} 2 1 3 3 1} +do_test tkt1537-2.3 { + execsql { + SELECT * FROM t2 LEFT JOIN t1 ON b BETWEEN a1 AND a2; + } +} {3 1 2 1 3 4 {} {} {} {}} +do_test tkt1537-2.4 { + execsql { + CREATE INDEX t1a1 ON t1(a1); + CREATE INDEX t1a2 ON t1(a2); + SELECT * FROM t2 LEFT JOIN t1 ON b BETWEEN a1 AND a2; + } +} {3 1 2 1 3 4 {} {} {} {}} + +do_test tkt1537-3.1 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b GLOB 'abc*' WHERE t1.id=1; + } +} {1 {} {} {} {}} +do_test tkt1537-3.2 { + execsql { + SELECT * FROM t2 LEFT JOIN t1 ON a1 GLOB 'abc*' WHERE t2.id=3; + } +} {3 1 {} {} {}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1567.test b/components/external/SQLite-3.8.1/test/tkt1567.test new file mode 100644 index 0000000000000000000000000000000000000000..6c4548a31404cecbc1a1ad93787d8813f4e15513 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1567.test @@ -0,0 +1,51 @@ +# 2005 December 19 2005 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1567 is +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt1567-1.1 { + execsql { + CREATE TABLE t1(a TEXT PRIMARY KEY); + } + set bigstr abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ + for {set i 0} {$i<100} {incr i} { + set x [format %5d [expr $i*2]] + set sql "INSERT INTO t1 VALUES('$x-$bigstr')" + execsql $sql + } +} {} +integrity_check tkt1567-1.2 + +do_test tkt1567-1.3 { + execsql { + BEGIN; + UPDATE t1 SET a = a||'x' WHERE rowid%2==0; + } +} {} +do_test tkt1567-1.4 { + catchsql { + UPDATE t1 SET a = CASE WHEN rowid<90 THEN substr(a,1,10) ELSE '9999' END; + } +} {1 {column a is not unique}} +do_test tkt1567-1.5 { + execsql { + COMMIT; + } +} {} +integrity_check tkt1567-1.6 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1644.test b/components/external/SQLite-3.8.1/test/tkt1644.test new file mode 100644 index 0000000000000000000000000000000000000000..aa26a88d33abb156978fe4ba85b2be2cde0bc640 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1644.test @@ -0,0 +1,111 @@ +# 2006 January 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1644 is +# fixed. Ticket #1644 complains that precompiled statements +# are not expired correctly as a result of changes to TEMP +# views and triggers. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !tempdb||!view { + finish_test + return +} + +# Create two tables T1 and T2 and make V1 point to T1. +do_test tkt1644-1.1 { + execsql { + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + CREATE TABLE t2(b); + INSERT INTO t2 VALUES(99); + CREATE TEMP VIEW v1 AS SELECT * FROM t1; + SELECT * FROM v1; + } +} {1} + +# The "SELECT * FROM v1" should be in the TCL interface cache below. +# It will continue to point to T1 unless the cache is invalidated when +# the view changes. +# +do_test tkt1644-1.2 { + execsql { + DROP VIEW v1; + CREATE TEMP VIEW v1 AS SELECT * FROM t2; + SELECT * FROM v1; + } +} {99} + +# Cache an access to the T1 table. +# +do_test tkt1644-1.3 { + execsql { + SELECT * FROM t1; + } +} {1} + +# Create a temp table T1. Make sure the cache is invalidated so that +# the statement is recompiled and refers to the empty temp table. +# +do_test tkt1644-1.4 { + execsql { + CREATE TEMP TABLE t1(x); + } + execsql { + SELECT * FROM t1; + } +} {} + +ifcapable view { + do_test tkt1644-2.1 { + execsql { + CREATE TEMP TABLE temp_t1(a, b); + } + set ::DB [sqlite3_connection_pointer db] + set ::STMT [sqlite3_prepare $::DB "SELECT * FROM temp_t1" -1 DUMMY] + execsql { + DROP TABLE temp_t1; + } + list [sqlite3_step $::STMT] [sqlite3_finalize $::STMT] + } {SQLITE_ERROR SQLITE_SCHEMA} + + do_test tkt1644-2.2 { + execsql { + CREATE TABLE real_t1(a, b); + CREATE TEMP VIEW temp_v1 AS SELECT * FROM real_t1; + } + set ::DB [sqlite3_connection_pointer db] + set ::STMT [sqlite3_prepare $::DB "SELECT * FROM temp_v1" -1 DUMMY] + execsql { + DROP VIEW temp_v1; + } + list [sqlite3_step $::STMT] [sqlite3_finalize $::STMT] + } {SQLITE_ERROR SQLITE_SCHEMA} + + do_test tkt1644-2.3 { + execsql { + CREATE TEMP VIEW temp_v1 AS SELECT * FROM real_t1 LIMIT 10 OFFSET 10; + } + set ::DB [sqlite3_connection_pointer db] + set ::STMT [sqlite3_prepare $::DB "SELECT * FROM temp_v1" -1 DUMMY] + execsql { + DROP VIEW temp_v1; + } + list [sqlite3_step $::STMT] [sqlite3_finalize $::STMT] + } {SQLITE_ERROR SQLITE_SCHEMA} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1667.test b/components/external/SQLite-3.8.1/test/tkt1667.test new file mode 100644 index 0000000000000000000000000000000000000000..63815061c0e2f080d9c2b2bfb30fd6abcc9a5a06 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1667.test @@ -0,0 +1,83 @@ +# 2006 February 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1667 has been +# fixed. +# +# +# $Id: tkt1667.test,v 1.4 2009/02/05 17:00:54 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !autovacuum||!tclvar { + finish_test + return +} + +db close +forcedelete test.db test.db-journal + +# Set the pending byte offset such that the page it is on is +# the first autovacuum pointer map page in the file (assume a page +# size of 1024). + +set first_ptrmap_page [expr 1024/5 + 3] +sqlite3_test_control_pending_byte [expr 1024 * ($first_ptrmap_page-1)] + +sqlite3 db test.db + +do_test tkt1667-1 { + execsql { + PRAGMA auto_vacuum = 1; + BEGIN; + CREATE TABLE t1(a, b); + } + for {set i 0} {$i < 500} {incr i} { + execsql { + INSERT INTO t1 VALUES($i, randstr(1000, 2000)) + } + } + execsql { + COMMIT; + } +} {} +for {set i 0} {$i < 500} {incr i} { + do_test tkt1667-2.$i.1 { + execsql { + DELETE FROM t1 WHERE a = $i; + } + } {} + integrity_check tkt1667-2.$i.2 +} + +do_test tkt1667-3 { + execsql { + BEGIN; + } + for {set i 0} {$i < 500} {incr i} { + execsql { + INSERT INTO t1 VALUES($i, randstr(1000, 2000)) + } + } + execsql { + COMMIT; + } +} {} +do_test tkt1667-4.1 { + execsql { + DELETE FROM t1; + } +} {} +integrity_check tkt1667-4.2 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt1873.test b/components/external/SQLite-3.8.1/test/tkt1873.test new file mode 100644 index 0000000000000000000000000000000000000000..9930790c747d846171c6015c7b5644fc87c5a4d6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt1873.test @@ -0,0 +1,72 @@ +# 2006 June 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #1873 has been +# fixed. +# +# +# $Id: tkt1873.test,v 1.2 2007/10/09 08:29:33 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !attach { + finish_test + return +} + +forcedelete test2.db test2.db-journal + +do_test tkt1873-1.1 { + execsql { + CREATE TABLE t1(x, y); + ATTACH 'test2.db' AS aux; + CREATE TABLE aux.t2(x, y); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t2 VALUES(5, 6); + INSERT INTO t2 VALUES(7, 8); + } +} {} + +do_test tkt1873-1.2 { + set rc [catch { + db eval {SELECT * FROM t2 LIMIT 1} { + db eval {DETACH aux} + } + } msg] + list $rc $msg +} {1 {database aux is locked}} + +do_test tkt1873-1.3 { + set rc [catch { + db eval {SELECT * FROM t1 LIMIT 1} { + db eval {DETACH aux} + } + } msg] + list $rc $msg +} {0 {}} + +do_test tkt1873-1.4 { + catchsql { + select * from t2; + } +} {1 {no such table: t2}} + +do_test tkt1873-1.5 { + catchsql { + ATTACH 'test2.db' AS aux; + select * from t2; + } +} {0 {5 6 7 8}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2141.test b/components/external/SQLite-3.8.1/test/tkt2141.test new file mode 100644 index 0000000000000000000000000000000000000000..a40659ff84d3f47f9dc23c2f49e444182b00d1f4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2141.test @@ -0,0 +1,61 @@ +# 2007 January 03 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #2141 has been +# fixed. +# +# +# $Id: tkt2141.test,v 1.2 2007/09/12 17:01:45 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !subquery { + finish_test + return +} + +do_test tkt2141-1.1 { + execsql { + CREATE TABLE tab1 (t1_id integer PRIMARY KEY, t1_desc); + INSERT INTO tab1 VALUES(1,'rec 1 tab 1'); + CREATE TABLE tab2 (t2_id integer PRIMARY KEY, t2_id_t1, t2_desc); + INSERT INTO tab2 VALUES(1,1,'rec 1 tab 2'); + CREATE TABLE tab3 (t3_id integer PRIMARY KEY, t3_id_t2, t3_desc); + INSERT INTO tab3 VALUES(1,1,'aa'); + SELECT * + FROM tab1 t1 LEFT JOIN tab2 t2 ON t1.t1_id = t2.t2_id_t1 + WHERE t2.t2_id IN + (SELECT t2_id FROM tab2, tab3 ON t2_id = t3_id_t2 + WHERE t3_id IN (1,2) GROUP BY t2_id); + } +} {1 {rec 1 tab 1} 1 1 {rec 1 tab 2}} +do_test tkt2141-1.2 { + execsql { + SELECT * + FROM tab1 t1 LEFT JOIN tab2 t2 ON t1.t1_id = t2.t2_id_t1 + WHERE t2.t2_id IN + (SELECT t2_id FROM tab2, tab3 ON t2_id = t3_id_t2 + WHERE t3_id IN (1,2)); + } +} {1 {rec 1 tab 1} 1 1 {rec 1 tab 2}} +do_test tkt2141-1.3 { + execsql { + SELECT * + FROM tab1 t1 LEFT JOIN tab2 t2 + WHERE t2.t2_id IN + (SELECT t2_id FROM tab2, tab3 ON t2_id = t3_id_t2 + WHERE t3_id IN (1,2)); + } +} {1 {rec 1 tab 1} 1 1 {rec 1 tab 2}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2192.test b/components/external/SQLite-3.8.1/test/tkt2192.test new file mode 100644 index 0000000000000000000000000000000000000000..72ef9a2621d77f85dbaa8380db1437d44abfb0a6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2192.test @@ -0,0 +1,140 @@ +# 2007 January 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #2192 has been +# fixed. +# +# +# $Id: tkt2192.test,v 1.3 2008/08/04 03:51:24 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !datetime||!compound { + finish_test + return +} + +do_test tkt2192-1.1 { + execsql { + -- Raw data (RBS) -------- + + create table records ( + date real, + type text, + description text, + value integer, + acc_name text, + acc_no text + ); + + -- Direct Debits ---------------- + create view direct_debits as + select * from records where type = 'D/D'; + + create view monthly_direct_debits as + select strftime('%Y-%m', date) as date, (-1 * sum(value)) as value + from direct_debits + group by strftime('%Y-%m', date); + + -- Expense Categories --------------- + create view energy as + select strftime('%Y-%m', date) as date, (-1 * sum(value)) as value + from direct_debits + where description like '%NPOWER%' + group by strftime('%Y-%m', date); + + create view phone_internet as + select strftime('%Y-%m', date) as date, (-1 * sum(value)) as value + from direct_debits + where description like '%BT DIRECT%' + or description like '%SUPANET%' + or description like '%ORANGE%' + group by strftime('%Y-%m', date); + + create view credit_cards as + select strftime('%Y-%m', date) as date, (-1 * sum(value)) as value + from direct_debits where description like '%VISA%' + group by strftime('%Y-%m', date); + + -- Overview --------------------- + + create view expense_overview as + select 'Energy' as expense, date, value from energy + union + select 'Phone/Internet' as expense, date, value from phone_internet + union + select 'Credit Card' as expense, date, value from credit_cards; + + create view jan as + select 'jan', expense, value from expense_overview + where date like '%-01'; + + create view nov as + select 'nov', expense, value from expense_overview + where date like '%-11'; + + create view summary as + select * from jan join nov on (jan.expense = nov.expense); + } +} {} +do_test tkt2192-1.2 { + # set ::sqlite_addop_trace 1 + execsql { + select * from summary; + } +} {} +do_test tkt2192-2.1 { + execsql { + CREATE TABLE t1(a,b); + CREATE VIEW v1 AS + SELECT * FROM t1 WHERE b%7=0 UNION SELECT * FROM t1 WHERE b%5=0; + INSERT INTO t1 VALUES(1,7); + INSERT INTO t1 VALUES(2,10); + INSERT INTO t1 VALUES(3,14); + INSERT INTO t1 VALUES(4,15); + INSERT INTO t1 VALUES(1,16); + INSERT INTO t1 VALUES(2,17); + INSERT INTO t1 VALUES(3,20); + INSERT INTO t1 VALUES(4,21); + INSERT INTO t1 VALUES(1,22); + INSERT INTO t1 VALUES(2,24); + INSERT INTO t1 VALUES(3,25); + INSERT INTO t1 VALUES(4,26); + INSERT INTO t1 VALUES(1,27); + + SELECT b FROM v1 ORDER BY b; + } +} {7 10 14 15 20 21 25} +do_test tkt2192-2.2 { + execsql { + SELECT * FROM v1 ORDER BY a, b; + } +} {1 7 2 10 3 14 3 20 3 25 4 15 4 21} +do_test tkt2192-2.3 { + execsql { + SELECT x.a || '/' || x.b || '/' || y.b + FROM v1 AS x JOIN v1 AS y ON x.a=y.a AND x.b0; + SELECT count(*), sum(x) FROM t1; + } +} {32 528} + +# Try to update all elements of the table. This will invoke the +# UPDATE trigger 32 times, which should overflow the VDBE stack if +# the problem of #2767 is not fixed. If the problem is fixed, all +# the updates should be no-ops so the table should remain unchanged. +# +do_test tkt2767-1.3 { + execsql { + UPDATE t1 SET x=x+1; + SELECT count(*), sum(x) FROM t1; + } +} {32 528} + +# Invoke the insert trigger. The insert trigger was working +# even prior to the fix of #2767. But it seems good to go ahead +# and verify that it works. +# +do_test tkt2767-1.4 { + execsql { + INSERT INTO t1 SELECT x+32 FROM t1; + SELECT count(*), sum(x) FROM t1; + } +} {32 528} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2817.test b/components/external/SQLite-3.8.1/test/tkt2817.test new file mode 100644 index 0000000000000000000000000000000000000000..579cf2f7ba62fd7b606a8ef0251b87c6e5bbe837 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2817.test @@ -0,0 +1,72 @@ +# 2007 December 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# Specifically, it tests that bug 2817 is fixed. +# +# $Id: tkt2817.test,v 1.2 2008/07/12 14:52:21 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt2817-1.0 { + execsql { + CREATE TEMP TABLE tbl(a, b, c); + -- INSERT INTO tbl VALUES(1, 'abc', 'def'); + -- INSERT INTO tbl VALUES(2, 'ghi', 'jkl'); + } +} {} +do_test tkt2817-1.1 { + execsql { + CREATE TABLE main.tbl(a, b, c); + CREATE INDEX main.tbli ON tbl(a, b, c); + INSERT INTO main.tbl SELECT a, b, c FROM temp.tbl; + } +} {} + +# When bug #2817 existed, this test was failing. +# +integrity_check tkt2817-1.2 + +# So was this one. +# +db close +sqlite3 db test.db +integrity_check tkt2817-1.3 + + +# These tests - tkt2817-2.* - are the same as the previous block, except +# for the fact that the temp-table and the main table do not share the +# same name. #2817 did not cause a problem with these tests. +# +db close +forcedelete test.db +sqlite3 db test.db +do_test tkt2817-2.0 { + execsql { + CREATE TEMP TABLE tmp(a, b, c); + INSERT INTO tmp VALUES(1, 'abc', 'def'); + INSERT INTO tmp VALUES(2, 'ghi', 'jkl'); + } +} {} +do_test tkt2817-2.1 { + execsql { + CREATE TABLE main.tbl(a, b, c); + CREATE INDEX main.tbli ON tbl(a, b, c); + INSERT INTO main.tbl SELECT a, b, c FROM temp.tmp; + } +} {} +integrity_check tkt2817-2.2 +db close +sqlite3 db test.db +integrity_check tkt2817-2.3 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2820.test b/components/external/SQLite-3.8.1/test/tkt2820.test new file mode 100644 index 0000000000000000000000000000000000000000..11c4cd3a0f04b09a3b4c451a2b92009468f75944 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2820.test @@ -0,0 +1,94 @@ +# 2007 Dec 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file is to test that ticket #2820 has been fixed. +# Ticket #2820 observes that a DROP TABLE statement that +# occurs while a query is in process will fail with a +# "database is locked" error, but the entry in the sqlite_master +# table will still be removed. This is incorrect. The +# entry in the sqlite_master table should persist when +# the DROP fails due to an error. +# +# $Id: tkt2820.test,v 1.1 2007/12/04 16:54:53 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc test_schema_change {testid init ddl res} { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + execsql $init + do_test tkt2820-$testid.1 { + set STMT [sqlite3_prepare db {SELECT * FROM sqlite_master} -1 DUMMY] + sqlite3_step $STMT + } {SQLITE_ROW} +#if {$testid==3} {execsql {PRAGMA vdbe_trace=ON}} + do_test tkt2820-$testid.2 "catchsql [list $ddl]" \ + {1 {database table is locked}} + do_test tkt2820-$testid.3 { + sqlite3_finalize $STMT + execsql {SELECT name FROM sqlite_master ORDER BY 1} + } $res + integrity_check tkt2820-$testid.4 + db close + sqlite3 db test.db + integrity_check tkt2820-$testid.5 +} + +test_schema_change 1 { + CREATE TABLE t1(a); +} { + DROP TABLE t1 +} {t1} +test_schema_change 2 { + CREATE TABLE t1(a); + CREATE TABLE t2(b); +} { + DROP TABLE t2 +} {t1 t2} +test_schema_change 3 { + CREATE TABLE t1(a); + CREATE INDEX i1 ON t1(a); +} { + DROP INDEX i1 +} {i1 t1} + +# We further observe that prior to the fix associated with ticket #2820, +# no statement journal would be created on an SQL statement that was run +# while a second statement was active, as long as we are in autocommit +# mode. This is incorrect. +# +do_test tkt2820-4.1 { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + } + + # The INSERT statement within the loop should fail on a + # constraint violation on the second inserted row. This + # should cause the entire INSERT to rollback using a statement + # journal. + # + db eval {SELECT name FROM sqlite_master} { + catch {db eval { + INSERT INTO t1 SELECT a+1 FROM t1 ORDER BY a DESC + }} + } + db eval {SELECT a FROM t1 ORDER BY a} +} {1 2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2822.test b/components/external/SQLite-3.8.1/test/tkt2822.test new file mode 100644 index 0000000000000000000000000000000000000000..d0b16338c6b842a81ed0aaf2daacc8e10dbfa5ba --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2822.test @@ -0,0 +1,346 @@ +# 2007 Dec 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file is to test that the issues surrounding expressions in +# ORDER BY clauses on compound SELECT statements raised by ticket +# #2822 have been dealt with. +# +# $Id: tkt2822.test,v 1.6 2008/08/20 16:35:10 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +# The ORDER BY matching algorithm is three steps: +# +# (1) If the ORDER BY term is an integer constant i, then +# sort by the i-th column of the result set. +# +# (2) If the ORDER BY term is an identifier (not x.y or x.y.z +# but simply x) then look for a column alias with the same +# name. If found, then sort by that column. +# +# (3) Evaluate the term as an expression and sort by the +# value of the expression. +# +# For a compound SELECT the rules are modified slightly. +# In the third rule, the expression must exactly match one +# of the result columns. The sequences of three rules is +# attempted first on the left-most SELECT. If that doesn't +# work, we move to the right, one by one. +# +# Rule (3) is not in standard SQL - it is an SQLite extension, +# though one copied from PostgreSQL. The rule for compound +# queries where a search is made of SELECTs to the right +# if the left-most SELECT does not match is not a part of +# standard SQL either. This extension is unique to SQLite +# as far as we know. +# +# Rule (2) was added by the changes ticket #2822. Prior to +# that changes, SQLite did not support rule (2), making it +# technically in violation of standard SQL semantics. +# No body noticed because rule (3) has the same effect as +# rule (2) except in some obscure cases. +# + + +# Test plan: +# +# tkt2822-1.* - Simple identifier as ORDER BY expression. +# tkt2822-2.* - More complex ORDER BY expressions. + +do_test tkt2822-0.1 { + execsql { + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(a, b, c); + + INSERT INTO t1 VALUES(1, 3, 9); + INSERT INTO t1 VALUES(3, 9, 27); + INSERT INTO t1 VALUES(5, 15, 45); + + INSERT INTO t2 VALUES(2, 6, 18); + INSERT INTO t2 VALUES(4, 12, 36); + INSERT INTO t2 VALUES(6, 18, 54); + } +} {} + +# Test the "ORDER BY " syntax. +# +do_test tkt2822-1.1 { + execsql { + SELECT a, b, c FROM t1 UNION ALL SELECT a, b, c FROM t2 ORDER BY 1; + } +} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54} +do_test tkt2822-1.2 { + execsql { + SELECT a, CAST (b AS TEXT), c FROM t1 + UNION ALL + SELECT a, b, c FROM t2 + ORDER BY 2; + } +} {2 6 18 4 12 36 6 18 54 5 15 45 1 3 9 3 9 27} + +# Test the "ORDER BY " syntax. +# +do_test tkt2822-2.1 { + execsql { + SELECT a, b, c FROM t1 UNION ALL SELECT a, b, c FROM t2 ORDER BY a; + } +} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54} + +do_test tkt2822-2.2 { + execsql { + SELECT a, CAST (b AS TEXT) AS x, c FROM t1 + UNION ALL + SELECT a, b, c FROM t2 + ORDER BY x; + } +} {2 6 18 4 12 36 6 18 54 5 15 45 1 3 9 3 9 27} +do_test tkt2822-2.3 { + execsql { + SELECT t1.a, b, c FROM t1 UNION ALL SELECT t2.a, b, c FROM t2 ORDER BY a; + } +} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54} + +# Test the "ORDER BY " syntax. +# +do_test tkt2822-3.1 { + execsql { + SELECT a, CAST (b AS TEXT) AS x, c FROM t1 + UNION ALL + SELECT a, b, c FROM t2 + ORDER BY CAST (b AS TEXT); + } +} {2 6 18 4 12 36 6 18 54 5 15 45 1 3 9 3 9 27} +do_test tkt2822-3.2 { + execsql { + SELECT t1.a, b, c FROM t1 UNION ALL SELECT t2.a, b, c FROM t2 ORDER BY t1.a; + } +} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54} + +# Test that if a match cannot be found in the leftmost SELECT, an +# attempt is made to find a match in subsequent SELECT statements. +# +do_test tkt2822-3.3 { + execsql { + SELECT a, b, c FROM t1 UNION ALL SELECT a AS x, b, c FROM t2 ORDER BY x; + } +} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54} +do_test tkt2822-3.4 { + # But the leftmost SELECT takes precedence. + execsql { + SELECT a AS b, CAST (b AS TEXT) AS a, c FROM t1 + UNION ALL + SELECT a, b, c FROM t2 + ORDER BY a; + } +} {2 6 18 4 12 36 6 18 54 5 15 45 1 3 9 3 9 27} +do_test tkt2822-3.5 { + execsql { + SELECT a, b, c FROM t2 + UNION ALL + SELECT a AS b, CAST (b AS TEXT) AS a, c FROM t1 + ORDER BY a; + } +} {1 3 9 2 6 18 3 9 27 4 12 36 5 15 45 6 18 54} + +# Test some error conditions (ORDER BY clauses that match no column). +# +do_test tkt2822-4.1 { + catchsql { + SELECT a, b, c FROM t1 UNION ALL SELECT a, b, c FROM t2 ORDER BY x + } +} {1 {1st ORDER BY term does not match any column in the result set}} +do_test tkt2822-4.2 { + catchsql { + SELECT a, CAST (b AS TEXT) AS x, c FROM t1 + UNION ALL + SELECT a, b, c FROM t2 + ORDER BY CAST (b AS INTEGER); + } +} {1 {1st ORDER BY term does not match any column in the result set}} + +# Tests for rule (2). +# +# The "ORDER BY b" should match the column alias (rule 2), not the +# the t3.b value (rule 3). +# +do_test tkt2822-5.1 { + execsql { + CREATE TABLE t3(a,b); + INSERT INTO t3 VALUES(1,8); + INSERT INTO t3 VALUES(9,2); + + SELECT a AS b FROM t3 ORDER BY b; + } +} {1 9} +do_test tkt2822-5.2 { + # Case does not matter. b should match B + execsql { + SELECT a AS b FROM t3 ORDER BY B; + } +} {1 9} +do_test tkt2822-5.3 { + # Quoting should not matter + execsql { + SELECT a AS 'b' FROM t3 ORDER BY "B"; + } +} {1 9} +do_test tkt2822-5.4 { + # Quoting should not matter + execsql { + SELECT a AS "b" FROM t3 ORDER BY [B]; + } +} {1 9} + +# In "ORDER BY +b" the term is now an expression rather than +# a label. It therefore matches by rule (3) instead of rule (2). +# +do_test tkt2822-5.5 { + execsql { + SELECT a AS b FROM t3 ORDER BY +b; + } +} {9 1} + +# Tests for rule 2 in compound queries +# +do_test tkt2822-6.1 { + execsql { + CREATE TABLE t6a(p,q); + INSERT INTO t6a VALUES(1,8); + INSERT INTO t6a VALUES(9,2); + CREATE TABLE t6b(x,y); + INSERT INTO t6b VALUES(1,7); + INSERT INTO t6b VALUES(7,2); + + SELECT p, q FROM t6a UNION ALL SELECT x, y FROM t6b ORDER BY 1, 2 + } +} {1 7 1 8 7 2 9 2} +do_test tkt2822-6.2 { + execsql { + SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b + ORDER BY PX, YX + } +} {1 7 1 8 7 2 9 2} +do_test tkt2822-6.3 { + execsql { + SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b + ORDER BY XX, QX + } +} {1 7 1 8 7 2 9 2} +do_test tkt2822-6.4 { + execsql { + SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b + ORDER BY QX, XX + } +} {7 2 9 2 1 7 1 8} +do_test tkt2822-6.5 { + execsql { + SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b + ORDER BY t6b.x, QX + } +} {1 7 1 8 7 2 9 2} +do_test tkt2822-6.6 { + execsql { + SELECT p PX, q QX FROM t6a UNION ALL SELECT x XX, y YX FROM t6b + ORDER BY t6a.q, XX + } +} {7 2 9 2 1 7 1 8} + +# More error message tests. This is really more of a test of the +# %r ordinal value formatting capablity added to sqlite3_snprintf() +# by ticket #2822. +# +do_test tkt2822-7.1 { + execsql { + CREATE TABLE t7(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14, + a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25); + } + catchsql { + SELECT * FROM t7 ORDER BY 0; + } +} {1 {1st ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.2.1 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 0; + } +} {1 {2nd ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.2.2 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 26; + } +} {1 {2nd ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.2.3 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 65536; + } +} {1 {2nd ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.3 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 0; + } +} {1 {3rd ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.4 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 3, 0; + } +} {1 {4th ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.9 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 0; + } +} {1 {9th ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.10 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 0; + } +} {1 {10th ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.11 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0; + } +} {1 {11th ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.12 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 0; + } +} {1 {12th ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.13 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 0; + } +} {1 {13th ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.20 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11,12,13,14,15,16,17,18,19, 0 + } +} {1 {20th ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.21 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11,12,13,14,15,16,17,18,19, 20, 0 + } +} {1 {21st ORDER BY term out of range - should be between 1 and 25}} +do_test tkt2822-7.22 { + catchsql { + SELECT * FROM t7 ORDER BY 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11,12,13,14,15,16,17,18,19, 20, 21, 0 + } +} {1 {22nd ORDER BY term out of range - should be between 1 and 25}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2832.test b/components/external/SQLite-3.8.1/test/tkt2832.test new file mode 100644 index 0000000000000000000000000000000000000000..f9986990069b34aa8343466122c386f44b141442 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2832.test @@ -0,0 +1,67 @@ +# 2007 Dec 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file is to test that ticket #2832 has been fixed. +# +# $Id: tkt2832.test,v 1.5 2009/04/07 14:14:23 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !trigger { finish_test ; return } + +do_test tkt2832-1.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(3); + } +} {} +do_test tkt2832-1.2 { + execsql { + UPDATE OR REPLACE t1 SET a = 1; + SELECT * FROM t1; + } +} {1} + +do_test tkt2832-2.1 { + execsql { + CREATE TABLE t2(a, b); + CREATE TRIGGER t2_t AFTER UPDATE ON t2 BEGIN + DELETE FROM t2 WHERE a = new.a + 1; + END; + INSERT INTO t2 VALUES(1, 2); + INSERT INTO t2 VALUES(2, 3); + } +} {} +do_test tkt2832-2.2 { + execsql { + UPDATE t2 SET b = 5 + } +} {} + +do_test tkt2832-3.1 { + execsql { + CREATE TABLE t3(a, b); + CREATE TRIGGER t3_t AFTER DELETE ON t3 BEGIN + DELETE FROM t3 WHERE a = old.a + 1; + END; + INSERT INTO t3 VALUES(1, 2); + INSERT INTO t3 VALUES(2, 3); + } +} {} +do_test tkt2832-3.2 { + execsql { DELETE FROM t3 WHERE 1 } +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2854.test b/components/external/SQLite-3.8.1/test/tkt2854.test new file mode 100644 index 0000000000000000000000000000000000000000..914ddd1b697c95c31bf199bb3f8e8b361f244e5f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2854.test @@ -0,0 +1,149 @@ +# 2007 December 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: tkt2854.test,v 1.4 2009/03/16 13:19:36 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +db close + +ifcapable !shared_cache { + finish_test + return +} + +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +# Open 3 database connections. Connection "db" and "db2" share a cache. +# Connection "db3" has its own cache. +# +do_test tkt2854-1.1 { + sqlite3 db test.db + sqlite3 db2 test.db + + # This is taken from shared.test. The Windows VFS expands + # ./test.db (and test.db) to be the same thing so the path + # matches and they share a cache. By changing the case + # for Windows platform, we get around this and get a separate + # connection. + if {$::tcl_platform(platform)=="unix"} { + sqlite3 db3 ./test.db + } else { + sqlite3 db3 TEST.DB + } + + db eval { + CREATE TABLE abc(a, b, c); + } +} {} + +# Check that an exclusive lock cannot be obtained if some other +# shared-cache connection has a read-lock on a table. +# +do_test tkt2854-1.2 { + execsql { + BEGIN; + SELECT * FROM abc; + } db2 +} {} +do_test tkt2854-1.3 { + catchsql { BEGIN EXCLUSIVE } db +} {1 {database table is locked}} +do_test tkt2854-1.4 { + execsql { SELECT * FROM abc } db3 +} {} +do_test tkt2854-1.5 { + catchsql { INSERT INTO abc VALUES(1, 2, 3) } db3 +} {1 {database is locked}} +do_test tkt2854-1.6 { + execsql { COMMIT } db2 +} {} + +# Check that an exclusive lock prevents other shared-cache users from +# starting a transaction. +# +do_test tkt2854-1.7 { + set ::DB2 [sqlite3_connection_pointer db2] + set ::STMT1 [sqlite3_prepare $DB2 "SELECT * FROM abc" -1 TAIL] + set ::STMT2 [sqlite3_prepare $DB2 "BEGIN EXCLUSIVE" -1 TAIL] + set ::STMT3 [sqlite3_prepare $DB2 "BEGIN IMMEDIATE" -1 TAIL] + set ::STMT4 [sqlite3_prepare $DB2 "BEGIN" -1 TAIL] + set ::STMT5 [sqlite3_prepare $DB2 "COMMIT" -1 TAIL] + execsql { BEGIN EXCLUSIVE } db +} {} +do_test tkt2854-1.8 { + catchsql { BEGIN EXCLUSIVE } db2 +} {1 {database schema is locked: main}} +do_test tkt2854-1.9 { + catchsql { BEGIN IMMEDIATE } db2 +} {1 {database schema is locked: main}} +do_test tkt2854-1.10 { + # This fails because the schema of main cannot be verified. + catchsql { BEGIN } db2 +} {1 {database schema is locked: main}} + +# Check that an exclusive lock prevents other shared-cache users from +# reading the database. Use stored statements so that the error occurs +# at the b-tree level, not the schema level. +# +do_test tkt2854-1.11 { + list [sqlite3_step $::STMT1] [sqlite3_finalize $::STMT1] +} {SQLITE_ERROR SQLITE_LOCKED} +do_test tkt2854-1.12 { + list [sqlite3_step $::STMT2] [sqlite3_finalize $::STMT2] +} {SQLITE_ERROR SQLITE_LOCKED} +do_test tkt2854-1.13 { + list [sqlite3_step $::STMT3] [sqlite3_finalize $::STMT3] +} {SQLITE_ERROR SQLITE_LOCKED} +do_test tkt2854-1.14 { + # A regular "BEGIN" doesn't touch any databases. So it succeeds. + list [sqlite3_step $::STMT4] [sqlite3_finalize $::STMT4] +} {SQLITE_DONE SQLITE_OK} +do_test tkt2854-1.15 { + # As does a COMMIT. + list [sqlite3_step $::STMT5] [sqlite3_finalize $::STMT5] +} {SQLITE_DONE SQLITE_OK} + +# Try to read the database using connection "db3" (which does not share +# a cache with "db"). The database should be locked. +do_test tkt2854-1.16 { + catchsql { SELECT * FROM abc } db3 +} {1 {database is locked}} +do_test tkt2854-1.17 { + execsql { COMMIT } db +} {} +do_test tkt2854-1.18 { + execsql { SELECT * FROM abc } db2 +} {} + +# Check that if an attempt to obtain an exclusive lock fails because an +# attached db cannot be locked, the internal exclusive flag used by +# shared-cache users is correctly cleared. +do_test tkt2854-1.19 { + forcedelete test2.db test2.db-journal + sqlite3 db4 test2.db + execsql { CREATE TABLE def(d, e, f) } db4 + execsql { ATTACH 'test2.db' AS aux } db +} {} +do_test tkt2854-1.20 { + execsql {BEGIN IMMEDIATE} db4 + catchsql {BEGIN EXCLUSIVE} db +} {1 {database table is locked}} +do_test tkt2854-1.21 { + execsql {SELECT * FROM abc} db2 +} {} + +db close +db2 close +db3 close +db4 close +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2920.test b/components/external/SQLite-3.8.1/test/tkt2920.test new file mode 100644 index 0000000000000000000000000000000000000000..d76c05bab95fe3c2cafa2893a26c733882dd4ad5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2920.test @@ -0,0 +1,78 @@ +# 2008 Feb 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file is to test that ticket #2920 is fixed. +# +# $Id: tkt2920.test,v 1.1 2008/02/02 02:48:52 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Create a database file that is full. +# +do_test tkt2920-1.1 { + db eval { + PRAGMA page_size=1024; + PRAGMA max_page_count=40; + PRAGMA auto_vacuum=0; + CREATE TABLE filler (fill); + } + file size test.db +} {2048} +do_test tkt2920-1.2 { + db eval BEGIN + for {set i 0} {$i<34} {incr i} { + db eval {INSERT INTO filler VALUES(randomblob(1024))} + } + db eval COMMIT +} {} + +# Try to add a single new page to the full database. We get +# a disk full error. But this does not corrupt the database. +# +do_test tkt2920-1.3 { + db eval BEGIN + catchsql { + INSERT INTO filler VALUES(randomblob(1024)) + } +} {1 {database or disk is full}} +integrity_check tkt2920-1.4 + +# Increase the maximum size of the database file by 1 page, +# but then try to add a two-page record. This also fails. +# +do_test tkt2920-1.5 { + db eval {PRAGMA max_page_count=41} + catchsql { + INSERT INTO filler VALUES(randomblob(2048)) + } +} {1 {database or disk is full}} +integrity_check tkt2920-1.6 + +# Increase the maximum size of the database by one more page. +# This time the insert works. +# +do_test tkt2920-1.7 { + db eval {PRAGMA max_page_count=42} + catchsql { + INSERT INTO filler VALUES(randomblob(2048)) + } +} {0 {}} +integrity_check tkt2920-1.8 + +# The previous errors cancelled the transaction. +# +do_test tkt2920-1.9 { + catchsql {COMMIT} +} {1 {cannot commit - no transaction is active}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2927.test b/components/external/SQLite-3.8.1/test/tkt2927.test new file mode 100644 index 0000000000000000000000000000000000000000..fc89a415389e0153f882c89a6de83b534675a31f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2927.test @@ -0,0 +1,674 @@ +# 2008 Feb 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file is to test that ticket #2927 is fixed. +# +# $Id: tkt2927.test,v 1.4 2008/08/04 03:51:24 danielk1977 Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +# Create a database. +# +do_test tkt2927-1.1 { + db eval { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1,11); + INSERT INTO t1 VALUES(2,22); + INSERT INTO t1 VALUES(3,33); + INSERT INTO t1 VALUES(4,44); + INSERT INTO t1 VALUES(5,55); + SELECT * FROM t1; + } +} {1 11 2 22 3 33 4 44 5 55} + + +do_test tkt2927-2.1 { + db eval { + SELECT a, b FROM t1 + UNION ALL + SELECT a, b FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.2 { +#set sqlite_addop_trace 1 + db eval { + SELECT a, b FROM t1 + UNION ALL + SELECT a, abs(b) FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.3 { + db eval { + SELECT a, b FROM t1 + UNION ALL + SELECT abs(a), b FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.4 { + db eval { + SELECT a, b FROM t1 + UNION ALL + SELECT abs(a), abs(b) FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.5 { + db eval { + SELECT a, abs(b) FROM t1 + UNION ALL + SELECT a, b FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.6 { + db eval { + SELECT a, abs(b) FROM t1 + UNION ALL + SELECT a, abs(b) FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.7 { + db eval { + SELECT a, abs(b) FROM t1 + UNION ALL + SELECT abs(a), b FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.8 { + db eval { + SELECT a, abs(b) FROM t1 + UNION ALL + SELECT abs(a), abs(b) FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.9 { + db eval { + SELECT abs(a), b FROM t1 + UNION ALL + SELECT a, b FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.10 { + db eval { + SELECT abs(a), b FROM t1 + UNION ALL + SELECT a, abs(b) FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.11 { + db eval { + SELECT abs(a), b FROM t1 + UNION ALL + SELECT abs(a), b FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.12 { + db eval { + SELECT abs(a), b FROM t1 + UNION ALL + SELECT abs(a), abs(b) FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.13 { + db eval { + SELECT abs(a), abs(b) FROM t1 + UNION ALL + SELECT a, b FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.14 { + db eval { + SELECT abs(a), abs(b) FROM t1 + UNION ALL + SELECT a, abs(b) FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.15 { + db eval { + SELECT abs(a), abs(b) FROM t1 + UNION ALL + SELECT abs(a), b FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-2.16 { + db eval { + SELECT abs(a), abs(b) FROM t1 + UNION ALL + SELECT abs(a), abs(b) FROM t1 + } +} {1 11 2 22 3 33 4 44 5 55 1 11 2 22 3 33 4 44 5 55} + + +do_test tkt2927-3.1 { + db eval { + SELECT a, b FROM t1 + UNION + SELECT a, b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.2 { + db eval { + SELECT a, b FROM t1 + UNION + SELECT a, abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.3 { + db eval { + SELECT a, b FROM t1 + UNION + SELECT abs(a), b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.4 { + db eval { + SELECT a, b FROM t1 + UNION + SELECT abs(a), abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.5 { + db eval { + SELECT a, abs(b) FROM t1 + UNION + SELECT a, b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.6 { + db eval { + SELECT a, abs(b) FROM t1 + UNION + SELECT a, abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.7 { + db eval { + SELECT a, abs(b) FROM t1 + UNION + SELECT abs(a), b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.8 { + db eval { + SELECT a, abs(b) FROM t1 + UNION + SELECT abs(a), abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.9 { + db eval { + SELECT abs(a), b FROM t1 + UNION + SELECT a, b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.10 { + db eval { + SELECT abs(a), b FROM t1 + UNION + SELECT a, abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.11 { + db eval { + SELECT abs(a), b FROM t1 + UNION + SELECT abs(a), b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.12 { + db eval { + SELECT abs(a), b FROM t1 + UNION + SELECT abs(a), abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.13 { + db eval { + SELECT abs(a), abs(b) FROM t1 + UNION + SELECT a, b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.14 { + db eval { + SELECT abs(a), abs(b) FROM t1 + UNION + SELECT a, abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.15 { + db eval { + SELECT abs(a), abs(b) FROM t1 + UNION + SELECT abs(a), b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-3.16 { + db eval { + SELECT abs(a), abs(b) FROM t1 + UNION + SELECT abs(a), abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} + + +do_test tkt2927-4.1 { + db eval { + SELECT a+b, a-b, a, b FROM t1 + UNION ALL + SELECT a+b, a-b, a, b FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.2 { + db eval { + SELECT a+b, a-b, a, b FROM t1 + UNION ALL + SELECT a+b, a-b, a, abs(b) FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.3 { + db eval { + SELECT a+b, a-b, a, b FROM t1 + UNION ALL + SELECT a+b, a-b, abs(a), b FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.4 { + db eval { + SELECT a+b, a-b, a, b FROM t1 + UNION ALL + SELECT a+b, a-b, abs(a), abs(b) FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.5 { + db eval { + SELECT a+b, a-b, a, abs(b) FROM t1 + UNION ALL + SELECT a+b, a-b, a, b FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.6 { + db eval { + SELECT a+b, a-b, a, abs(b) FROM t1 + UNION ALL + SELECT a+b, a-b, a, abs(b) FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.7 { + db eval { + SELECT a+b, a-b, a, abs(b) FROM t1 + UNION ALL + SELECT a+b, a-b, abs(a), b FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.8 { + db eval { + SELECT a+b, a-b, a, abs(b) FROM t1 + UNION ALL + SELECT a+b, a-b, abs(a), abs(b) FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.9 { + db eval { + SELECT a+b, a-b, abs(a), b FROM t1 + UNION ALL + SELECT a+b, a-b, a, b FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.10 { + db eval { + SELECT a+b, a-b, abs(a), b FROM t1 + UNION ALL + SELECT a+b, a-b, a, abs(b) FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.11 { + db eval { + SELECT a+b, a-b, abs(a), b FROM t1 + UNION ALL + SELECT a+b, a-b, abs(a), b FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.12 { + db eval { + SELECT a+b, a-b, abs(a), b FROM t1 + UNION ALL + SELECT a+b, a-b, abs(a), abs(b) FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.13 { + db eval { + SELECT a+b, a-b, abs(a), abs(b) FROM t1 + UNION ALL + SELECT a+b, a-b, a, b FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.14 { + db eval { + SELECT a+b, a-b, abs(a), abs(b) FROM t1 + UNION ALL + SELECT a+b, a-b, a, abs(b) FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.15 { + db eval { + SELECT a+b, a-b, abs(a), abs(b) FROM t1 + UNION ALL + SELECT a+b, a-b, abs(a), b FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} +do_test tkt2927-4.16 { + db eval { + SELECT a+b, a-b, abs(a), abs(b) FROM t1 + UNION ALL + SELECT a+b, a-b, abs(a), abs(b) FROM t1 + } +} {12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55 12 -10 1 11 24 -20 2 22 36 -30 3 33 48 -40 4 44 60 -50 5 55} + + +do_test tkt2927-5.1 { + db eval { + SELECT a, b FROM t1 + EXCEPT + SELECT a, b FROM t1 + } +} {} +do_test tkt2927-5.2 { + db eval { + SELECT a, b FROM t1 + EXCEPT + SELECT a, abs(b) FROM t1 + } +} {} +do_test tkt2927-5.3 { + db eval { + SELECT a, b FROM t1 + EXCEPT + SELECT abs(a), b FROM t1 + } +} {} +do_test tkt2927-5.4 { + db eval { + SELECT a, b FROM t1 + EXCEPT + SELECT abs(a), abs(b) FROM t1 + } +} {} +do_test tkt2927-5.5 { + db eval { + SELECT a, abs(b) FROM t1 + EXCEPT + SELECT a, b FROM t1 + } +} {} +do_test tkt2927-5.6 { + db eval { + SELECT a, abs(b) FROM t1 + EXCEPT + SELECT a, abs(b) FROM t1 + } +} {} +do_test tkt2927-5.7 { + db eval { + SELECT a, abs(b) FROM t1 + EXCEPT + SELECT abs(a), b FROM t1 + } +} {} +do_test tkt2927-5.8 { + db eval { + SELECT a, abs(b) FROM t1 + EXCEPT + SELECT abs(a), abs(b) FROM t1 + } +} {} +do_test tkt2927-5.9 { + db eval { + SELECT abs(a), b FROM t1 + EXCEPT + SELECT a, b FROM t1 + } +} {} +do_test tkt2927-5.10 { + db eval { + SELECT abs(a), b FROM t1 + EXCEPT + SELECT a, abs(b) FROM t1 + } +} {} +do_test tkt2927-5.11 { + db eval { + SELECT abs(a), b FROM t1 + EXCEPT + SELECT abs(a), b FROM t1 + } +} {} +do_test tkt2927-5.12 { + db eval { + SELECT abs(a), b FROM t1 + EXCEPT + SELECT abs(a), abs(b) FROM t1 + } +} {} +do_test tkt2927-5.13 { + db eval { + SELECT abs(a), abs(b) FROM t1 + EXCEPT + SELECT a, b FROM t1 + } +} {} +do_test tkt2927-5.14 { + db eval { + SELECT abs(a), abs(b) FROM t1 + EXCEPT + SELECT a, abs(b) FROM t1 + } +} {} +do_test tkt2927-5.15 { + db eval { + SELECT abs(a), abs(b) FROM t1 + EXCEPT + SELECT abs(a), b FROM t1 + } +} {} +do_test tkt2927-5.16 { + db eval { + SELECT abs(a), abs(b) FROM t1 + EXCEPT + SELECT abs(a), abs(b) FROM t1 + } +} {} + + +do_test tkt2927-6.1 { + db eval { + SELECT a, b FROM t1 + INTERSECT + SELECT a, b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.2 { + db eval { + SELECT a, b FROM t1 + INTERSECT + SELECT a, abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.3 { + db eval { + SELECT a, b FROM t1 + INTERSECT + SELECT abs(a), b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.4 { + db eval { + SELECT a, b FROM t1 + INTERSECT + SELECT abs(a), abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.5 { + db eval { + SELECT a, abs(b) FROM t1 + INTERSECT + SELECT a, b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.6 { + db eval { + SELECT a, abs(b) FROM t1 + INTERSECT + SELECT a, abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.7 { + db eval { + SELECT a, abs(b) FROM t1 + INTERSECT + SELECT abs(a), b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.8 { + db eval { + SELECT a, abs(b) FROM t1 + INTERSECT + SELECT abs(a), abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.9 { + db eval { + SELECT abs(a), b FROM t1 + INTERSECT + SELECT a, b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.10 { + db eval { + SELECT abs(a), b FROM t1 + INTERSECT + SELECT a, abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.11 { + db eval { + SELECT abs(a), b FROM t1 + INTERSECT + SELECT abs(a), b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.12 { + db eval { + SELECT abs(a), b FROM t1 + INTERSECT + SELECT abs(a), abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.13 { + db eval { + SELECT abs(a), abs(b) FROM t1 + INTERSECT + SELECT a, b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.14 { + db eval { + SELECT abs(a), abs(b) FROM t1 + INTERSECT + SELECT a, abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.15 { + db eval { + SELECT abs(a), abs(b) FROM t1 + INTERSECT + SELECT abs(a), b FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} +do_test tkt2927-6.16 { + db eval { + SELECT abs(a), abs(b) FROM t1 + INTERSECT + SELECT abs(a), abs(b) FROM t1 + ORDER BY 1 + } +} {1 11 2 22 3 33 4 44 5 55} + +# Ticket #3092 is the same bug. But another test case never hurts. +# +do_test tkt2927-7.1 { + db eval { + CREATE TABLE host ( + hostname text not null primary key, + consoleHost text, + consolePort text + ); + INSERT INTO "host" VALUES('aald04','aalp03','4'); + INSERT INTO "host" VALUES('aald17','aalp01','1'); + CREATE VIEW consolemap1a as + select hostname, consolehost, '/dev/cuaD0.' || (consoleport-1) consoleport + from host where consolehost='aalp01'; + CREATE VIEW consolemap1b as + select hostname hostname, consolehost consolehost, '/dev/cuaD' || + substr('01',1+((consoleport-1)/16),1) || + substr('0123456789abcdef',1+((consoleport-1)%16),1) consoleport + from host where consolehost='aalp03'; + CREATE VIEW consolemap1 as + select * from consolemap1a + union + select * from consolemap1b; + SELECT * from consolemap1b; + } +} {aald04 aalp03 /dev/cuaD03} +do_test tkt2927-7.2 { + db eval { + SELECT * FROM consolemap1 + } +} {aald04 aalp03 /dev/cuaD03 aald17 aalp01 /dev/cuaD0.0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt2942.test b/components/external/SQLite-3.8.1/test/tkt2942.test new file mode 100644 index 0000000000000000000000000000000000000000..a7b861c75cd167f31eafd7c171276065e47df284 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt2942.test @@ -0,0 +1,62 @@ +# 2008 February 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #2942. +# +# Queries of the form: +# +# SELECT group_concat(x) FROM (SELECT * FROM table ORDER BY 1); +# +# The ORDER BY would be dropped by the query flattener. This used +# to not matter because aggregate functions sum(), min(), max(), avg(), +# and so forth give the same result regardless of the order of inputs. +# But with the addition of the group_concat() function, suddenly the +# order does matter. +# +# $Id: tkt2942.test,v 1.1 2008/02/15 14:33:04 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !subquery { + finish_test + return +} + +do_test tkt2942.1 { + execsql { + create table t1(num int); + insert into t1 values (2); + insert into t1 values (1); + insert into t1 values (3); + insert into t1 values (4); + SELECT group_concat(num) FROM (SELECT num FROM t1 ORDER BY num DESC); + } +} {4,3,2,1} +do_test tkt2942.2 { + execsql { + SELECT group_concat(num) FROM (SELECT num FROM t1 ORDER BY num); + } +} {1,2,3,4} +do_test tkt2942.3 { + execsql { + SELECT group_concat(num) FROM (SELECT num FROM t1); + } +} {2,1,3,4} +do_test tkt2942.4 { + execsql { + SELECT group_concat(num) FROM (SELECT num FROM t1 ORDER BY rowid DESC); + } +} {4,3,1,2} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3080.test b/components/external/SQLite-3.8.1/test/tkt3080.test new file mode 100644 index 0000000000000000000000000000000000000000..bfccaa9b84b17db4fbdd3badb20a439c458a4063 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3080.test @@ -0,0 +1,77 @@ +# 2008 April 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3080 +# +# Make sure that application-defined functions are able to recursively +# invoke SQL statements that create and drop virtual tables. +# +# $Id: tkt3080.test,v 1.2 2008/11/05 16:37:35 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3080.1 { + db function execsql execsql + db eval { + SELECT execsql('CREATE TABLE t1(x)'); + } + execsql {SELECT name FROM sqlite_master} +} {t1} +do_test tkt3080.2 { + db eval { + INSERT INTO t1 VALUES('CREATE TABLE t2(y);'); + SELECT execsql(x) FROM t1; + } + db eval { + SELECT name FROM sqlite_master; + } +} {t1 t2} +do_test tkt3080.3 { + execsql { + INSERT INTO t1 VALUES('CREATE TABLE t3(z); DROP TABLE t3;'); + } + catchsql { + SELECT execsql(x) FROM t1 WHERE rowid=2; + } +} {1 {database table is locked}} +do_test tkt3080.4 { + db eval { + SELECT name FROM sqlite_master; + } +} {t1 t2 t3} + +ifcapable vtab { + register_echo_module [sqlite3_connection_pointer db] + do_test tkt3080.10 { + set sql { + CREATE VIRTUAL TABLE t4 USING echo(t2); + INSERT INTO t4 VALUES(123); + DROP TABLE t4; + } + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES($sql); + } + db eval { + SELECT execsql(x) FROM t1 + } + execsql {SELECT name FROM sqlite_master} + } {t1 t2 t3} + do_test tkt3080.11 { + execsql {SELECT * FROM t2} + } {123} +} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3093.test b/components/external/SQLite-3.8.1/test/tkt3093.test new file mode 100644 index 0000000000000000000000000000000000000000..3be46d15cfec7fc4aa968fa52c6620186e431545 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3093.test @@ -0,0 +1,86 @@ +# 2008 May 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3093 +# +# Verify that a busy callback waiting on a reserved lock resolves +# once the lock clears. +# +# $Id: tkt3093.test,v 1.2 2008/05/02 14:23:55 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Set up a test database +# +do_test tkt3093.1 { + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + SELECT * FROM t1 + } +} {1} + +# Establish a separate, independent connection to that database. +# +do_test tkt3093.2 { + catch {sqlite3_enable_shared_cache 0} + sqlite3 db2 test.db + db2 eval { + SELECT * FROM t1 + } +} {1} + +# Make sure that clearing a lock allows a pending request for +# a reserved lock to continue. +# +do_test tkt3093.3 { + # This will be the busy callback for connection db2. On the first + # busy callback, commit the transaction in db. This should clear + # the lock so that there should not be a second callback. If the + # busy handler is called a second time, then fail so that we get + # timeout. + proc busy_callback {cnt} { + if {$cnt==0} { + db eval COMMIT + return 0 + } else { + return 1 + } + } + db2 busy ::busy_callback + + # Start a write transaction on db. + db eval { + BEGIN; + INSERT INTO t1 VALUES(2); + } + + # Attempt to modify the database on db2 + catchsql { + UPDATE t1 SET x=x+1; + } db2 +} {0 {}} + +# Verify that everything worked as expected. The db transaction should +# have gone first and added entry 2. Then the db2 transaction would have +# run and added one to each entry. +# +do_test tkt3093.4 { + db eval {SELECT * FROM t1} +} {2 3} +do_test tkt3093.5 { + db2 eval {SELECT * FROM t1} +} {2 3} +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3121.test b/components/external/SQLite-3.8.1/test/tkt3121.test new file mode 100644 index 0000000000000000000000000000000000000000..2e8fdbb629870809f7d10f4fffec830df9d278a8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3121.test @@ -0,0 +1,50 @@ +# 2008 May 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: tkt3121.test,v 1.2 2008/07/12 14:52:21 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +# Register the module +register_echo_module [sqlite3_connection_pointer db] + +do_test vtabD-1.1 { + execsql { + PRAGMA encoding = 'utf16'; + + CREATE TABLE r1(field); + CREATE TABLE r2(col PRIMARY KEY, descr); + + INSERT INTO r1 VALUES('abcd'); + INSERT INTO r2 VALUES('abcd', 'A nice description'); + INSERT INTO r2 VALUES('efgh', 'Another description'); + + CREATE VIRTUAL TABLE t1 USING echo(r1); + CREATE VIRTUAL TABLE t2 USING echo(r2); + } +} {} + +do_test vtabD-1.2 { + execsql { + select + t1.field as Field, + t2.descr as Descr + from t1 inner join t2 on t1.field = t2.col order by t1.field + } +} {abcd {A nice description}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3201.test b/components/external/SQLite-3.8.1/test/tkt3201.test new file mode 100644 index 0000000000000000000000000000000000000000..47c5ebb5fd6fb46ff76bf41b6c6e8a4f1260afed --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3201.test @@ -0,0 +1,105 @@ +# 2008 July 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# Specifically, it tests that bug #3201 has been fixed. +# +# $Id: tkt3201.test,v 1.3 2008/07/12 14:52:21 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3201-1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + } +} {} + +do_test tkt3201-2 { + execsql { + SELECT l.a, r.a FROM t1 AS l, t1 AS r WHERE l.a < r.a; + } +} {1 2} + +do_test tkt3201-3 { + execsql { + CREATE TABLE t2(a INTEGER PRIMARY KEY, b TEXT); + INSERT INTO t2 VALUES(2, 'two'); + } + execsql { + SELECT l.a, r.a FROM t1 AS l, t2 AS r WHERE l.a < r.a; + } +} {1 2} + +do_test tkt3201-4 { + execsql { + DELETE FROM t1 WHERE a = 2; + } + execsql { + SELECT l.a, r.a FROM t1 AS l, t2 AS r WHERE l.a < r.a; + } +} {1 2} + +do_test tkt3201-5 { + execsql { + DELETE FROM t1 WHERE a = 2; + } + execsql { + SELECT t1.a, t1.b, t2.a, t2.b FROM t1, t2; + } +} {1 one 2 two} + +do_test tkt3201-6 { + execsql { + CREATE TABLE t3(c INTEGER PRIMARY KEY, d TEXT); + INSERT INTO t3 VALUES(2, 'two'); + } + execsql { SELECT a, b, c, d FROM t1, t3 } +} {1 one 2 two} + +do_test tkt3201-7 { + execsql { SELECT a, b, c, d FROM t1, t3 WHERE a < c } +} {1 one 2 two} + +# Ticket [efc02f977919] +# +ifcapable trigger { + do_test tkt3201-4.0 { + db eval { + CREATE TABLE t4(x); + CREATE TABLE t4_log(x); + CREATE TRIGGER r4_1 AFTER INSERT ON t4 WHEN new.x=1 BEGIN + INSERT INTO t4_log(x) VALUES(new.x); + END; + CREATE TRIGGER r4_2 AFTER INSERT ON t4 WHEN new.x=2 BEGIN + INSERT INTO t4_log(x) VALUES(new.x); + END; + CREATE TRIGGER r4_3 AFTER INSERT ON t4 WHEN new.x=3 BEGIN + INSERT INTO t4_log(x) VALUES(new.x); + END; + CREATE TRIGGER r4_4 AFTER INSERT ON t4 WHEN new.x=4 BEGIN + INSERT INTO t4_log(x) VALUES(new.x); + END; + INSERT INTO t4 VALUES(1); + INSERT INTO t4 VALUES(2); + INSERT INTO t4 VALUES(3); + INSERT INTO t4 VALUES(4); + SELECT * FROM t4_log; + } + } {1 2 3 4} +} + + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3292.test b/components/external/SQLite-3.8.1/test/tkt3292.test new file mode 100644 index 0000000000000000000000000000000000000000..0f9524464390b97036cf43537a14716910a311b1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3292.test @@ -0,0 +1,61 @@ +# 2008 August 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# Specifically, it tests the behavior of the sqlite3VdbeRecordCompare() +# routine in cases where the rowid is 0 or 1 in file format 4 +# (meaning that the rowid has type code 8 or 9 with zero bytes of +# data). Ticket #3292. +# +# $Id: tkt3292.test,v 1.1 2008/08/13 14:07:41 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3292-1.1 { + execsql { + PRAGMA legacy_file_format=OFF; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT); + INSERT INTO t1 VALUES(0, 1); + INSERT INTO t1 VALUES(1, 1); + INSERT INTO t1 VALUES(2, 1); + CREATE INDEX i1 ON t1(b); + SELECT * FROM t1 WHERE b>=1; + } +} {0 1 1 1 2 1} +do_test tkt3292-1.2 { + execsql { + INSERT INTO t1 VALUES(3, 0); + INSERT INTO t1 VALUES(4, 2); + SELECT * FROM t1 WHERE b>=1; + } +} {0 1 1 1 2 1 4 2} + + +do_test tkt3292-2.1 { + execsql { + CREATE TABLE t2(a INTEGER PRIMARY KEY, b, c, d); + INSERT INTO t2 VALUES(0, 1, 'hello', x'012345'); + INSERT INTO t2 VALUES(1, 1, 'hello', x'012345'); + INSERT INTO t2 VALUES(2, 1, 'hello', x'012345'); + CREATE INDEX i2 ON t2(b,c,d); + SELECT a FROM t2 WHERE b=1 AND c='hello' AND d>=x'012345'; + } +} {0 1 2} +do_test tkt3292-2.2 { + execsql { + INSERT INTO t2 VALUES(3, 1, 'hello', x'012344'); + INSERT INTO t2 VALUES(4, 1, 'hello', x'012346'); + SELECT a FROM t2 WHERE b=1 AND c='hello' AND d>=x'012345'; + } +} {0 1 2 4} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3298.test b/components/external/SQLite-3.8.1/test/tkt3298.test new file mode 100644 index 0000000000000000000000000000000000000000..0e546f7e696411c2c37103a37f05dfbd39fc2d52 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3298.test @@ -0,0 +1,80 @@ +# 2008 August 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests changes to the name resolution logic that occurred +# in august of 2008 and where associated with tickets #3298 and #3301 +# +# $Id: tkt3298.test,v 1.3 2009/04/07 14:14:23 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !trigger { finish_test ; return } + +do_test tkt3298-1.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT); + INSERT INTO t1 VALUES(0, 1); + INSERT INTO t1 VALUES(1, 1); + INSERT INTO t1 VALUES(2, 1); + CREATE VIEW v1 AS SELECT a AS x, b+1 AS y FROM t1; + CREATE TRIGGER r1 INSTEAD OF UPDATE ON v1 + BEGIN + UPDATE t1 SET b=new.y-1 WHERE a=new.x; + END; + CREATE TRIGGER r2 INSTEAD OF DELETE ON v1 + BEGIN + DELETE FROM t1 WHERE a=old.x; + END; + SELECT * FROM v1 ORDER BY x; + } +} {0 2 1 2 2 2} +do_test tkt3298-1.2 { + execsql { + UPDATE v1 SET y=3 WHERE x=0; + SELECT * FROM v1 ORDER by x; + } +} {0 3 1 2 2 2} +do_test tkt3298-1.3 { + execsql { + UPDATE v1 SET y=4 WHERE v1.x=2; + SELECT * FROM v1 ORDER by x; + } +} {0 3 1 2 2 4} +do_test tkt3298-1.4 { + execsql { + DELETE FROM v1 WHERE x=1; + SELECT * FROM v1 ORDER BY x; + } +} {0 3 2 4} +do_test tkt3298-1.5 { + execsql { + DELETE FROM v1 WHERE v1.x=2; + SELECT * FROM v1 ORDER BY x; + } +} {0 3} + +# Ticket #3301 +# +do_test tkt3298-2.1 { + execsql { + CREATE TABLE t2(p,q); + INSERT INTO t2 VALUES(1,11); + INSERT INTO t2 VALUES(2,22); + CREATE TABLE t3(x,y); + INSERT INTO t3 VALUES(1,'one'); + + SELECT *, (SELECT z FROM (SELECT y AS z FROM t3 WHERE x=t1.a+1) ) FROM t1; + } +} {0 2 one} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3334.test b/components/external/SQLite-3.8.1/test/tkt3334.test new file mode 100644 index 0000000000000000000000000000000000000000..5473ab4cf8f298bed06d54742bb325c94e5cb071 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3334.test @@ -0,0 +1,84 @@ +# 2008 August 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. +# Specifically, it tests that bug #3334 has been fixed by the +# addition of restriction (19) to the subquery flattener optimization. +# +# $Id: tkt3334.test,v 1.1 2008/08/26 12:56:14 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3334-1.0 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,934); + INSERT INTO t1 VALUES(2,221); + INSERT INTO t1 VALUES(1,372); + INSERT INTO t1 VALUES(3,552); + INSERT INTO t1 VALUES(1,719); + INSERT INTO t1 VALUES(4,102); + SELECT * FROM t1 ORDER BY b; + } +} {4 102 2 221 1 372 3 552 1 719 1 934} + +do_test tkt3334-1.1 { + execsql { + SELECT a FROM (SELECT a FROM t1 ORDER BY b LIMIT 2) WHERE a=1; + } +} {} +do_test tkt3334-1.2 { + execsql { + SELECT count(*) FROM (SELECT a FROM t1 ORDER BY b LIMIT 2) WHERE a=1; + } +} {0} +do_test tkt3334-1.3 { + execsql { + SELECT a FROM (SELECT a FROM t1 ORDER BY b LIMIT 3) WHERE a=1; + } +} {1} +do_test tkt3334-1.4 { + execsql { + SELECT count(*) FROM (SELECT a FROM t1 ORDER BY b LIMIT 3) WHERE a=1; + } +} {1} +do_test tkt3334-1.5 { + execsql { + SELECT a FROM (SELECT a FROM t1 ORDER BY b LIMIT 99) WHERE a=1; + } +} {1 1 1} +do_test tkt3334-1.6 { + execsql { + SELECT count(*) FROM (SELECT a FROM t1 ORDER BY b LIMIT 99) WHERE a=1; + } +} {3} +do_test tkt3334-1.7 { + execsql { + SELECT a FROM (SELECT a FROM t1 ORDER BY b) WHERE a=1; + } +} {1 1 1} +do_test tkt3334-1.8 { + execsql { + SELECT count(*) FROM (SELECT a FROM t1 ORDER BY b) WHERE a=1; + } +} {3} +do_test tkt3334-1.9 { + execsql { + SELECT a FROM (SELECT a FROM t1) WHERE a=1; + } +} {1 1 1} +do_test tkt3334-1.10 { + execsql { + SELECT count(*) FROM (SELECT a FROM t1) WHERE a=1; + } +} {3} diff --git a/components/external/SQLite-3.8.1/test/tkt3346.test b/components/external/SQLite-3.8.1/test/tkt3346.test new file mode 100644 index 0000000000000000000000000000000000000000..806e5e9c70b0e0df63590d57313f8d1449d2a732 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3346.test @@ -0,0 +1,67 @@ +# 2008 September 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this file is testing the fix for ticket #3346 +# +# $Id: tkt3346.test,v 1.3 2008/12/09 13:12:57 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3346-1.1 { + db eval { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(2,'bob'); + INSERT INTO t1 VALUES(1,'alice'); + INSERT INTO t1 VALUES(3,'claire'); + SELECT *, ( SELECT y FROM (SELECT x.b='alice' AS y) ) + FROM ( SELECT * FROM t1 ) AS x; + } +} {2 bob 0 1 alice 1 3 claire 0} +do_test tkt3346-1.2 { + db eval { + SELECT b FROM (SELECT * FROM t1) AS x + WHERE (SELECT y FROM (SELECT x.b='alice' AS y))=0 + } +} {bob claire} +do_test tkt3346-1.3 { + db eval { + SELECT b FROM (SELECT * FROM t1 ORDER BY a) AS x + WHERE (SELECT y FROM (SELECT a||b y FROM t1 WHERE t1.b=x.b))=(x.a||x.b) + } +} {alice bob claire} +do_test tkt3346-1.4 { + db eval { + SELECT b FROM (SELECT * FROM t1 ORDER BY a) AS x + WHERE (SELECT y FROM (SELECT a||b y FROM t1 WHERE t1.b=x.b))=('2'||x.b) + } +} {bob} + +# Ticket #3530 +# +# As shown by ticket #3346 above (see also ticket #3298) it is important +# that a subquery in the result-set be able to look up through multiple +# FROM levels in order to view tables in the FROM clause at the top level. +# +# But ticket #3530 shows us that a subquery in the FROM clause should not +# be able to look up to higher levels: +# +do_test tkt3346-2.1 { + catchsql { + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(1); + + SELECT * FROM (SELECT * FROM t1 WHERE 1=x.a) AS x; + } +} {1 {no such column: x.a}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3357.test b/components/external/SQLite-3.8.1/test/tkt3357.test new file mode 100644 index 0000000000000000000000000000000000000000..c3e2a2bc92bdd87adb23edc48032b3aeacc3ca40 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3357.test @@ -0,0 +1,64 @@ +# 2008 September 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this file is testing the fix for ticket #3357. +# +# $Id: tkt3357.test,v 1.2 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3357-1.1 { + execsql { + create table a(id integer primary key, b_id integer, myvalue varchar); + create table b(id integer primary key, bvalue varchar); + insert into a(b_id, myvalue) values(1,'Test'); + insert into a(b_id, myvalue) values(1,'Test2'); + insert into a(b_id, myvalue) values(1,'Test3'); + insert into b(bvalue) values('btest'); + } +} {} + +do_test tkt3357-1.2 { + execsql { + SELECT cc.id, cc.b_id, cc.myvalue, dd.bvalue + FROM ( + SELECT DISTINCT a.id, a.b_id, a.myvalue FROM a + INNER JOIN b ON a.b_id = b.id WHERE b.bvalue = 'btest' + ) cc + LEFT OUTER JOIN b dd ON cc.b_id = dd.id + } +} {1 1 Test btest 2 1 Test2 btest 3 1 Test3 btest} + +do_test tkt3357-1.3 { + execsql { + SELECT cc.id, cc.b_id, cc.myvalue + FROM ( + SELECT a.id, a.b_id, a.myvalue + FROM a, b WHERE a.b_id = b.id + ) cc + LEFT OUTER JOIN b dd ON cc.b_id = dd.id + } +} {1 1 Test 2 1 Test2 3 1 Test3} + +do_test tkt3357-1.4 { + execsql { + SELECT cc.id, cc.b_id, cc.myvalue + FROM ( + SELECT DISTINCT a.id, a.b_id, a.myvalue + FROM a, b WHERE a.b_id = b.id + ) cc + LEFT OUTER JOIN b dd ON cc.b_id = dd.id + } +} {1 1 Test 2 1 Test2 3 1 Test3} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3419.test b/components/external/SQLite-3.8.1/test/tkt3419.test new file mode 100644 index 0000000000000000000000000000000000000000..4cfd02357c58fec9ce8a64716519af3333d9c058 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3419.test @@ -0,0 +1,73 @@ +# 2008 October 06 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this file is testing the fix for ticket #3419. +# Ticket #3419 is really a duplication of #3408 and had already +# been fixed by the time it was reported. But it never hurts to +# add new test cases. +# +# $Id: tkt3419.test,v 1.1 2008/10/06 15:31:13 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3419-1.1 { + execsql { + create table a(id integer primary key); + create table b(id integer primary key, a_id integer); + create table c(id integer primary key, b_id integer); + + insert into a values (1); + insert into a values (2); + + insert into b values (3, 1); + insert into b values (4, 1); + insert into b values (5, 1); + insert into b values (6, 1); + insert into b values (9, 2); + + insert into c values (4, 3); + insert into c values (5, 5); + insert into c values (6, 4); + insert into c values (7, 6); + insert into c values (8, 9); + + select * FROM a, b, c WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id; + } +} {2 9 2 8 9} +do_test tkt3419-1.2 { + execsql { + select * FROM a, c, b WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id; + } +} {2 8 9 9 2} +do_test tkt3419-1.3 { + execsql { + select * FROM b, a, c WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id; + } +} {9 2 2 8 9} +do_test tkt3419-1.4 { + execsql { + select * FROM b, c, a WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id; + } +} {9 2 8 9 2} +do_test tkt3419-1.5 { + execsql { + select * FROM c, a, b WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id; + } +} {8 9 2 9 2} +do_test tkt3419-1.6 { + execsql { + select * FROM c, b, a WHERE a.id=2 AND b.a_id = a.id AND b.id=c.b_id; + } +} {8 9 9 2 2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3424.test b/components/external/SQLite-3.8.1/test/tkt3424.test new file mode 100644 index 0000000000000000000000000000000000000000..f38fa5aafa4b762aca64db301461e8ce00e6cf2f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3424.test @@ -0,0 +1,53 @@ +# 2008 October 06 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# +# $Id: tkt3424.test,v 1.2 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3424-1.1 { + execsql { + CREATE TABLE names(id INTEGER, data TEXT, code TEXT); + INSERT INTO names VALUES(1,'E1','AAA'); + INSERT INTO names VALUES(2,NULL,'BBB'); + + CREATE TABLE orig(code TEXT, data TEXT); + INSERT INTO orig VALUES('AAA','E1'); + INSERT INTO orig VALUES('AAA','E2'); + INSERT INTO orig VALUES('AAA','E3'); + INSERT INTO orig VALUES('AAA','E4'); + INSERT INTO orig VALUES('AAA','E5'); + } +} {} + +do_test tkt3424-1.2 { + execsql { + SELECT * FROM + names LEFT OUTER JOIN orig + ON names.data = orig.data AND names.code = orig.code; + } +} {1 E1 AAA AAA E1 2 {} BBB {} {}} + +do_test tkt3424-1.3 { + execsql { CREATE INDEX udx_orig_code_data ON orig(code, data) } +} {} + +do_test tkt3424-1.4 { + execsql { + SELECT * FROM + names LEFT OUTER JOIN orig + ON names.data = orig.data AND names.code = orig.code; + } +} {1 E1 AAA AAA E1 2 {} BBB {} {}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3442.test b/components/external/SQLite-3.8.1/test/tkt3442.test new file mode 100644 index 0000000000000000000000000000000000000000..ee9169ce2c4f6ac624f23d6ada3e579f1df6ba28 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3442.test @@ -0,0 +1,72 @@ +# 2008 October 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #3442 has been +# fixed. +# +# +# $Id: tkt3442.test,v 1.2 2009/06/05 17:09:12 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + + +# Create a schema with some indexes. +# +do_test tkt3442-1.1 { + execsql { + CREATE TABLE listhash( + key INTEGER PRIMARY KEY, + id TEXT, + node INTEGER + ); + CREATE UNIQUE INDEX ididx ON listhash(id); + } +} {} + + +# Explain Query Plan +# +proc EQP {sql} { + uplevel "execsql {EXPLAIN QUERY PLAN $sql}" +} + + +# These tests perform an EXPLAIN QUERY PLAN on both versions of the +# SELECT referenced in ticket #3442 (both '5000' and "5000") +# and verify that the query plan is the same. +# +ifcapable explain { + do_test tkt3442-1.2 { + EQP { SELECT node FROM listhash WHERE id='5000' LIMIT 1; } + } {0 0 0 {SEARCH TABLE listhash USING INDEX ididx (id=?)}} + do_test tkt3442-1.3 { + EQP { SELECT node FROM listhash WHERE id="5000" LIMIT 1; } + } {0 0 0 {SEARCH TABLE listhash USING INDEX ididx (id=?)}} +} + + +# Some extra tests testing other permutations of 5000. +# +ifcapable explain { + do_test tkt3442-1.4 { + EQP { SELECT node FROM listhash WHERE id=5000 LIMIT 1; } + } {0 0 0 {SEARCH TABLE listhash USING INDEX ididx (id=?)}} +} +do_test tkt3442-1.5 { + catchsql { + SELECT node FROM listhash WHERE id=[5000] LIMIT 1; + } +} {1 {no such column: 5000}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3457.test b/components/external/SQLite-3.8.1/test/tkt3457.test new file mode 100644 index 0000000000000000000000000000000000000000..04757413221c16d0143da057d438d3f68c905f1c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3457.test @@ -0,0 +1,101 @@ +# 2008 October 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# $Id: tkt3457.test,v 1.3 2009/06/26 07:12:07 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +if {$tcl_platform(platform) != "unix"} { + finish_test + return +} + +#----------------------------------------------------------------------- +# To roll back a hot-journal file, the application needs read and write +# permission on the journal file in question. The following tests test +# the outcome of trying to rollback a hot-journal file when this is not +# the case. +# +# tkt3457-1.2: Application has neither read, nor write permission on +# the hot-journal file. Result: SQLITE_CANTOPEN. +# +# tkt3457-1.3: Application has write but not read permission on +# the hot-journal file. Result: SQLITE_CANTOPEN. +# +# tkt3457-1.4: Application has read but not write permission on +# the hot-journal file. Result: SQLITE_CANTOPEN. +# +# tkt3457-1.5: Application has read/write permission on the hot-journal +# file. Result: SQLITE_OK. +# +do_test tkt3457-1.1 { + execsql { + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, 2, 3); + BEGIN; + INSERT INTO t1 VALUES(4, 5, 6); + } + + forcecopy test.db bak.db + forcecopy test.db-journal bak.db-journal + + # Fix the first journal-header in the journal-file. Because the + # journal file has not yet been synced, the 8-byte magic string at the + # start of the first journal-header has not been written by SQLite. + # So write it now. + set fd [open bak.db-journal a+] + fconfigure $fd -encoding binary -translation binary + seek $fd 0 + puts -nonewline $fd "\xd9\xd5\x05\xf9\x20\xa1\x63\xd7" + close $fd + + execsql COMMIT +} {} + +# Disable fchmod to make sure SQLite itself does not try to change the +# permission bits on us +# +catch { + test_syscall install fchmod + test_syscall fault 1 1 +} + +do_test tkt3457-1.2 { + forcecopy bak.db-journal test.db-journal + file attributes test.db-journal -permissions --------- + catchsql { SELECT * FROM t1 } +} {1 {unable to open database file}} +do_test tkt3457-1.3 { + forcecopy bak.db-journal test.db-journal + file attributes test.db-journal -permissions -w--w--w- + catchsql { SELECT * FROM t1 } +} {1 {unable to open database file}} +do_test tkt3457-1.4 { + forcecopy bak.db-journal test.db-journal + file attributes test.db-journal -permissions r--r--r-- + catchsql { SELECT * FROM t1 } +} {1 {unable to open database file}} + +do_test tkt3457-1.5 { + forcecopy bak.db-journal test.db-journal + file attributes test.db-journal -permissions rw-rw-rw- + catchsql { SELECT * FROM t1 } +} {0 {1 2 3 4 5 6}} + +# Reenable fchmod +catch { + test_syscall uninstall + test_syscall fault 0 0 +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3461.test b/components/external/SQLite-3.8.1/test/tkt3461.test new file mode 100644 index 0000000000000000000000000000000000000000..642980be09435200edf9bc0a8a3e93154681f8cf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3461.test @@ -0,0 +1,67 @@ +# 2008 October 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #3461 has been +# fixed. +# +# $Id: tkt3461.test,v 1.4 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +#################################### +#################################### +# REMOVE THESE TWO LINES: +#################################### +#################################### +#finish_test +#return + +do_test tkt3461-1.1 { + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } +} {} + +do_test tkt3461-1.2 { + execsql { SELECT a, b+1 AS b_plus_one FROM t1 WHERE a=1 } +} {1 3} + +do_test tkt3461-1.3 { + # explain { SELECT a, b+1 AS b_plus_one FROM t1 WHERE a=1 OR b_plus_one } + # execsql { PRAGMA vdbe_trace = 1; PRAGMA vdbe_listing=1 } + execsql { SELECT a, b+1 AS b_plus_one FROM t1 WHERE a=1 OR b_plus_one } +} {1 3} + +do_test tkt3461-2.1 { + execsql { + SELECT a, b+1 AS b_plus_one + FROM t1 + WHERE CASE WHEN a=1 THEN 1 ELSE b_plus_one END + } +} {1 3} + +do_test tkt3461-3.1 { + execsql { + CREATE TABLE t2(c, d); + INSERT INTO t2 VALUES(3, 4); + } + # execsql { PRAGMA vdbe_trace = 1; PRAGMA vdbe_listing=1 } + execsql { + SELECT a, b+1 AS b_plus_one, c, d + FROM t1 LEFT JOIN t2 + ON (a=c AND d=b_plus_one) + } +} {1 3 {} {}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3493.test b/components/external/SQLite-3.8.1/test/tkt3493.test new file mode 100644 index 0000000000000000000000000000000000000000..8fe91ddd209b47132099deb627d339e10de5512b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3493.test @@ -0,0 +1,153 @@ +# 2008 October 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests that affinities and collation sequences are correctly applied +# in aggregate queries. +# +# $Id: tkt3493.test,v 1.2 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3493-1.1 { + execsql { + BEGIN; + CREATE TABLE A (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT); + INSERT INTO A VALUES(1,'123'); + INSERT INTO A VALUES(2,'456'); + CREATE TABLE B (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT); + INSERT INTO B VALUES(1,1); + INSERT INTO B VALUES(2,2); + CREATE TABLE A_B (B_id INTEGER NOT NULL, A_id INTEGER); + INSERT INTO A_B VALUES(1,1); + INSERT INTO A_B VALUES(2,2); + COMMIT; + } +} {} +do_test tkt3493-1.2 { + execsql { + SELECT + CASE + WHEN B.val = 1 THEN 'XYZ' + ELSE A.val + END AS Col1 + FROM B + LEFT OUTER JOIN A_B ON B.id = A_B.B_id + LEFT OUTER JOIN A ON A.id = A_B.A_id + ORDER BY Col1 ASC; + } +} {456 XYZ} +do_test tkt3493-1.3 { + execsql { + SELECT DISTINCT + CASE + WHEN B.val = 1 THEN 'XYZ' + ELSE A.val + END AS Col1 + FROM B + LEFT OUTER JOIN A_B ON B.id = A_B.B_id + LEFT OUTER JOIN A ON A.id = A_B.A_id + ORDER BY Col1 ASC; + } +} {456 XYZ} +do_test tkt3493-1.4 { + execsql { + SELECT b.val, CASE WHEN b.val = 1 THEN 'xyz' ELSE b.val END AS col1 FROM b; + } +} {1 xyz 2 2} +do_test tkt3493-1.5 { + execsql { + SELECT DISTINCT + b.val, + CASE WHEN b.val = 1 THEN 'xyz' ELSE b.val END AS col1 + FROM b; + } +} {1 xyz 2 2} +do_test tkt3493-1.6 { + execsql { + SELECT DISTINCT + b.val, + CASE WHEN b.val = '1' THEN 'xyz' ELSE b.val END AS col1 + FROM b; + } +} {1 xyz 2 2} + + +do_test tkt3493-2.1 { + execsql { + CREATE TABLE t1(a TEXT, b INT); + INSERT INTO t1 VALUES(123, 456); + } +} {} +do_test tkt3493-2.2.1 { + execsql { SELECT a=123 FROM t1 GROUP BY a } +} {1} +do_test tkt3493-2.2.2 { + execsql { SELECT a=123 FROM t1 } +} {1} +do_test tkt3493-2.2.3 { + execsql { SELECT a='123' FROM t1 } +} {1} +do_test tkt3493-2.2.4 { + execsql { SELECT count(*), a=123 FROM t1 } +} {1 1} +do_test tkt3493-2.2.5 { + execsql { SELECT count(*), +a=123 FROM t1 } +} {1 0} +do_test tkt3493-2.3.3 { + execsql { SELECT b='456' FROM t1 GROUP BY a } +} {1} +do_test tkt3493-2.3.1 { + execsql { SELECT b='456' FROM t1 GROUP BY b } +} {1} +do_test tkt3493-2.3.2 { + execsql { SELECT b='456' FROM t1 } +} {1} +do_test tkt3493-2.4.1 { + execsql { SELECT typeof(a), a FROM t1 GROUP BY a HAVING a=123 } +} {text 123} +do_test tkt3493-2.4.2 { + execsql { SELECT typeof(a), a FROM t1 GROUP BY b HAVING a=123 } +} {text 123} +do_test tkt3493-2.5.1 { + execsql { SELECT typeof(b), b FROM t1 GROUP BY a HAVING b='456' } +} {integer 456} +do_test tkt3493-2.5.2 { + execsql { SELECT typeof(b), b FROM t1 GROUP BY b HAVING b='456' } +} {integer 456} + +do_test tkt3493-3.1 { + execsql { + CREATE TABLE t2(a COLLATE NOCASE, b COLLATE BINARY); + INSERT INTO t2 VALUES('aBc', 'DeF'); + } +} {} +do_test tkt3493-3.2.1 { + execsql { SELECT a='abc' FROM t2 GROUP BY a } +} {1} +do_test tkt3493-3.2.2 { + execsql { SELECT a='abc' FROM t2 } +} {1} + +do_test tkt3493-3.3.1 { + execsql { SELECT a>b FROM t2 GROUP BY a, b} +} {0} +do_test tkt3493-3.3.2 { + execsql { SELECT a>b COLLATE BINARY FROM t2 GROUP BY a, b} +} {1} +do_test tkt3493-3.3.3 { + execsql { SELECT b>a FROM t2 GROUP BY a, b} +} {0} +do_test tkt3493-3.3.4 { + execsql { SELECT b>a COLLATE NOCASE FROM t2 GROUP BY a, b} +} {1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3508.test b/components/external/SQLite-3.8.1/test/tkt3508.test new file mode 100644 index 0000000000000000000000000000000000000000..8275d69987378ebee258e7402a9389b0dcafd650 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3508.test @@ -0,0 +1,38 @@ +# 2008 November 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# $Id: tkt3508.test,v 1.5 2009/05/28 01:00:56 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3508-1.1 { + catchsql { + CREATE TABLE modificationsTmp ( + SUBSTRATE_HPRD_ID VARCHAR(80), + SUBSTRATE_GENE_SYMBOL VARCHAR(80), + SUBSTRATE_ISOFORM_ID VARCHAR(80), + SUBSTRATE_REFSEQ_ID VARCHAR(80), + SITE INTEGER, + RESIDUE VARCHAR(80), + ENZYME_NAME VARCHAR(80), + ENZYME_HPRD_ID VARCHAR(80), + MODIFICATION_TYPE VARCHAR(80), + EXPERIMENT_TYPE VARCHAR(80), + REFERENCE_ID VARCHAR(80) + ); + select SUBSTRATE_HPRD_ID, count(substrate_refseq_id) as c + from modificationsTmp where c > 1 group by SUBSTRATE_HPRD_ID; + } +} {1 {misuse of aggregate: count()}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3522.test b/components/external/SQLite-3.8.1/test/tkt3522.test new file mode 100644 index 0000000000000000000000000000000000000000..998d489345f276a917397ca272e5d89c4ec3b33a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3522.test @@ -0,0 +1,43 @@ +# 2008 December 4 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is a verification that the bugs identified in ticket +# #3522 have been fixed. +# +# $Id: tkt3522.test,v 1.1 2008/12/05 00:00:07 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3522-1.1 { + db eval { + CREATE TABLE tab4( + col0 INTEGER, + col1 INTEGER, + col2 INTEGER, + col3 INTEGER, + col4 INTEGER + ); + SELECT cor1.* + FROM tab4 AS cor0 + JOIN tab4 AS cor1 USING ( col4, col3, col2, col1, col0 ); + } +} {} +do_test tkt3522-1.2 { + db eval { + CREATE TABLE tab1(col0 INTEGER); + CREATE TABLE tab2(col0 INTEGER); + SELECT cor0.* FROM tab1 NATURAL JOIN tab2 AS cor0; + } +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3527.test b/components/external/SQLite-3.8.1/test/tkt3527.test new file mode 100644 index 0000000000000000000000000000000000000000..da3d05ac46cf1e7b516c394ea3d7cf48d0f4e927 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3527.test @@ -0,0 +1,123 @@ +# 2008 December 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is a verification that the bugs identified in ticket +# #3527 have been fixed. +# +# $Id: tkt3527.test,v 1.1 2008/12/08 13:42:36 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_test tkt3527-1.1 { + db eval { + CREATE TABLE Element ( + Code INTEGER PRIMARY KEY, + Name VARCHAR(60) + ); + + CREATE TABLE ElemOr ( + CodeOr INTEGER NOT NULL, + Code INTEGER NOT NULL, + PRIMARY KEY(CodeOr,Code) + ); + + CREATE TABLE ElemAnd ( + CodeAnd INTEGER, + Code INTEGER, + Attr1 INTEGER, + Attr2 INTEGER, + Attr3 INTEGER, + PRIMARY KEY(CodeAnd,Code) + ); + + INSERT INTO Element VALUES(1,'Elem1'); + INSERT INTO Element VALUES(2,'Elem2'); + INSERT INTO Element VALUES(3,'Elem3'); + INSERT INTO Element VALUES(4,'Elem4'); + INSERT INTO Element VALUES(5,'Elem5'); + INSERT INTO ElemOr Values(3,4); + INSERT INTO ElemOr Values(3,5); + INSERT INTO ElemAnd VALUES(1,3,'a','b','c'); + INSERT INTO ElemAnd VALUES(1,2,'x','y','z'); + + CREATE VIEW ElemView1 AS + SELECT + CAST(Element.Code AS VARCHAR(50)) AS ElemId, + Element.Code AS ElemCode, + Element.Name AS ElemName, + ElemAnd.Code AS InnerCode, + ElemAnd.Attr1 AS Attr1, + ElemAnd.Attr2 AS Attr2, + ElemAnd.Attr3 AS Attr3, + 0 AS Level, + 0 AS IsOrElem + FROM Element JOIN ElemAnd ON ElemAnd.CodeAnd=Element.Code + WHERE ElemAnd.CodeAnd NOT IN (SELECT CodeOr FROM ElemOr) + UNION ALL + SELECT + CAST(ElemOr.CodeOr AS VARCHAR(50)) AS ElemId, + Element.Code AS ElemCode, + Element.Name AS ElemName, + ElemOr.Code AS InnerCode, + NULL AS Attr1, + NULL AS Attr2, + NULL AS Attr3, + 0 AS Level, + 1 AS IsOrElem + FROM ElemOr JOIN Element ON Element.Code=ElemOr.CodeOr + ORDER BY ElemId, InnerCode; + + CREATE VIEW ElemView2 AS + SELECT + ElemId, + ElemCode, + ElemName, + InnerCode, + Attr1, + Attr2, + Attr3, + Level, + IsOrElem + FROM ElemView1 + UNION ALL + SELECT + Element.ElemId || '.' || InnerElem.ElemId AS ElemId, + InnerElem.ElemCode, + InnerElem.ElemName, + InnerElem.InnerCode, + InnerElem.Attr1, + InnerElem.Attr2, + InnerElem.Attr3, + InnerElem.Level+1, + InnerElem.IsOrElem + FROM ElemView1 AS Element + JOIN ElemView1 AS InnerElem + ON Element.Level=0 AND Element.InnerCode=InnerElem.ElemCode + ORDER BY ElemId, InnerCode; + + SELECT * FROM ElemView1; + } +} {1 1 Elem1 2 x y z 0 0 1 1 Elem1 3 a b c 0 0 3 3 Elem3 4 {} {} {} 0 1 3 3 Elem3 5 {} {} {} 0 1} + +do_test tkt3527-1.2 { + db eval { + SELECT * FROM ElemView2; + } +} {1 1 Elem1 2 x y z 0 0 1 1 Elem1 3 a b c 0 0 1.3 3 Elem3 4 {} {} {} 1 1 1.3 3 Elem3 5 {} {} {} 1 1 3 3 Elem3 4 {} {} {} 0 1 3 3 Elem3 5 {} {} {} 0 1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3541.test b/components/external/SQLite-3.8.1/test/tkt3541.test new file mode 100644 index 0000000000000000000000000000000000000000..f0597cfa10b48d17ac10e8911dd45ea72cf7f2e9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3541.test @@ -0,0 +1,35 @@ +# 2008 December 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file is a verification that the bugs identified in ticket +# #3541 have been fixed. +# +# $Id: tkt3541.test,v 1.1 2008/12/15 15:27:52 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3541-1.1 { + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(123); + SELECT CASE ~max(x) WHEN min(x) THEN 1 ELSE max(x) END FROM t1; + } +} {123} +do_test tkt3541-1.2 { + db eval { + SELECT CASE NOT max(x) WHEN min(x) THEN 1 ELSE max(x) END FROM t1; + } +} {123} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3554.test b/components/external/SQLite-3.8.1/test/tkt3554.test new file mode 100644 index 0000000000000000000000000000000000000000..a059486d640349b816d452657b52afe7c968dd65 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3554.test @@ -0,0 +1,67 @@ +# 2008 December 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #3554 has been +# fixed. +# +# $Id: tkt3554.test,v 1.2 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !trigger { + finish_test + return +} + +do_test tkt3544-1.1 { + execsql { + CREATE TABLE test ( obj, t1, t2, PRIMARY KEY(obj, t1, t2) ); + + CREATE TRIGGER test_insert BEFORE INSERT ON test BEGIN + UPDATE test SET t1 = new.t1 + WHERE obj = new.obj AND new.t1 < t1 AND new.t2 >= t1; + + UPDATE test SET t2 = new.t2 + WHERE obj = new.obj AND new.t2 > t2 AND new.t1 <= t2; + + SELECT RAISE(IGNORE) WHERE EXISTS ( + SELECT obj FROM test + WHERE obj = new.obj AND new.t1 >= t1 AND new.t2 <= t2 + ); + END; + } +} {} + +do_test tkt3544-1.2 { + execsql { + INSERT INTO test VALUES('a', 10000, 11000); + SELECT * FROM test; + } +} {a 10000 11000} + + +do_test tkt3544-1.3 { + execsql { + INSERT INTO test VALUES('a', 9000, 10500); + } + execsql { SELECT * FROM test } +} {a 9000 11000} + +do_test tkt3544-1.4 { + execsql { + INSERT INTO test VALUES('a', 10000, 12000); + } + execsql { SELECT * FROM test } +} {a 9000 12000} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3581.test b/components/external/SQLite-3.8.1/test/tkt3581.test new file mode 100644 index 0000000000000000000000000000000000000000..e9b18fd9f496c31a0ef221807aca73d35a756f02 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3581.test @@ -0,0 +1,54 @@ +# 2008 January 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #3581 has been +# fixed. +# +# $Id: tkt3581.test,v 1.1 2009/01/14 01:10:40 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3581-1.1 { + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c); + INSERT INTO t1 VALUES(0,544,846); + INSERT INTO t1 VALUES(1,345,51); + CREATE TABLE t2(a INTEGER PRIMARY KEY, b, c); + INSERT INTO t2 SELECT * FROM t1; + CREATE INDEX i2 on t2(c); + } +} {} + +do_test tkt3581-1.2 { + db eval { + SELECT a FROM t1 + WHERE (b > 45 AND c < 356) + OR b <= 733 + OR b >= 557 + OR (b >= 614 AND c < 251) + ORDER BY b; + } +} {1 0} + +do_test tkt3581-1.3 { + db eval { + SELECT a FROM t2 + WHERE (b > 45 AND c < 356) + OR b <= 733 + OR b >= 557 + OR (b >= 614 AND c < 251) + ORDER BY b; + } +} {1 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt35xx.test b/components/external/SQLite-3.8.1/test/tkt35xx.test new file mode 100644 index 0000000000000000000000000000000000000000..f9d10c30332ae53d1423cd5255d4f1666a169544 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt35xx.test @@ -0,0 +1,102 @@ +# 2008 November 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# When a transaction rolls back, make sure that dirty pages in the +# page cache which are not in the rollback journal are reinitialized +# in the btree layer. +# +# $Id: tkt35xx.test,v 1.4 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt35xx-1.1 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 1024; + } +} {} + +# Trigger the problem using explicit rollback. +# +do_test tkt35xx-1.1 { + execsql { + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(a,b,c); + CREATE INDEX i1 ON t1(c); + INSERT INTO t1 VALUES(0, 0, zeroblob(676)); + INSERT INTO t1 VALUES(1, 1, zeroblob(676)); + DELETE FROM t1; + BEGIN; + INSERT INTO t1 VALUES(0, 0, zeroblob(676)); + INSERT INTO t1 VALUES(1, 1, zeroblob(676)); + ROLLBACK; + INSERT INTO t1 VALUES(0, 0, zeroblob(676)); + } + execsql { + INSERT INTO t1 VALUES(1, 1, zeroblob(676)); + } +} {} + +# Trigger the problem using statement rollback. +# +db close +delete_file test.db +sqlite3 db test.db +set big [string repeat abcdefghij 22] ;# 220 byte string +do_test tkt35xx-1.2.1 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 1024; + CREATE TABLE t3(a INTEGER PRIMARY KEY, b); + INSERT INTO t3 VALUES(1, $big); + INSERT INTO t3 VALUES(2, $big); + INSERT INTO t3 VALUES(3, $big); + INSERT INTO t3 VALUES(4, $big); + CREATE TABLE t4(c, d); + INSERT INTO t4 VALUES(5, $big); + INSERT INTO t4 VALUES(1, $big); + } +} {} +do_test tkt35xx-1.2.2 { + catchsql { + BEGIN; + CREATE TABLE t5(e PRIMARY KEY, f); + DROP TABLE t5; + INSERT INTO t3(a, b) SELECT c, d FROM t4; + } +} {1 {PRIMARY KEY must be unique}} +do_test tkt35xx-1.2.3 { + # Show that the transaction has not been rolled back. + catchsql BEGIN +} {1 {cannot start a transaction within a transaction}} +do_test tkt35xx-1.2.4 { + execsql { SELECT count(*) FROM t3 } +} {4} +do_test tkt35xx-1.2.5 { + # Before the bug was fixed, if SQLITE_DEBUG was defined an assert() + # would fail during the following INSERT statement. If SQLITE_DEBUG + # was not defined, then the statement would pass and the transaction + # would be committed. But, the "SELECT count(*)" in tkt35xx-1.2.6 would + # return 1, not 5. Data magically disappeared! + # + execsql { + INSERT INTO t3 VALUES(5, $big); + COMMIT; + } +} {} +do_test tkt35xx-1.2.6 { + execsql { SELECT count(*) FROM t3 } +} {5} +integrity_check tkt35xx-1.2.7 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3630.test b/components/external/SQLite-3.8.1/test/tkt3630.test new file mode 100644 index 0000000000000000000000000000000000000000..b329c48dcfafad56fba3e28484fb7893a8999022 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3630.test @@ -0,0 +1,47 @@ +# 2009 February 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# +# This file checks to make sure the "TEMP" or "TEMPORARY" keyword is +# omitted from the schema of a table that is created using that +# keyword. Ticket #3630. +# +# $Id: tkt3630.test,v 1.1 2009/02/02 18:03:22 drh Exp $ +# + +set testdir [file dirname $argv0] + +source $testdir/tester.tcl + +do_test tkt3630-1 { + db eval { + CREATE TEMP TABLE temp1(a,b,c); + SELECT * FROM sqlite_temp_master WHERE sql GLOB '*TEMP*'; + } +} {} +do_test tkt3630-2 { + db eval { + CREATE TABLE main1(a,b,c); + CREATE TEMP TABLE temp2 AS SELECT * FROM main1; + SELECT * FROM sqlite_temp_master WHERE sql GLOB '*TEMP*'; + } +} {} + +ifcapable altertable { + do_test tkt3630-3 { + db eval { + ALTER TABLE temp2 ADD COLUMN d; + ALTER TABLE temp2 RENAME TO temp2rn; + SELECT name FROM sqlite_temp_master WHERE name LIKE 'temp2%'; + } + } {temp2rn} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3718.test b/components/external/SQLite-3.8.1/test/tkt3718.test new file mode 100644 index 0000000000000000000000000000000000000000..e5eb247481310bf1cb16f90a30b2a66f9a747c16 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3718.test @@ -0,0 +1,230 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the execution of SQL statements from +# within callbacks generated by VMs that themselves open statement +# transactions. +# +# $Id: tkt3718.test,v 1.2 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3718-1.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t1 VALUES(3, 'three'); + INSERT INTO t1 VALUES(4, 'four'); + INSERT INTO t1 VALUES(5, 'five'); + CREATE TABLE t2(a PRIMARY KEY, b); + } +} {} + +# SQL scalar function: +# +# f1() +# +# Uses database handle [db] to execute "SELECT f2()". Returns either +# the results or error message from the "SELECT f2()" query to the +# caller. +# +proc f1 {args} { + set a [lindex $args 0] + catch { db eval {SELECT f2($a)} } msg + set msg +} + +# SQL scalar function: +# +# f2() +# +# Return the value of . Unless is "three", in which case throw +# an exception. +# +proc f2 {args} { + set a [lindex $args 0] + if {$a == "three"} { error "Three!!" } + return $a +} + +db func f1 f1 +db func f2 f2 + +# The second INSERT statement below uses the f1 user function such that +# half-way through the INSERT operation f1() will run an SQL statement +# that throws an exception. At one point, before #3718 was fixed, this +# caused the statement transaction belonging to the INSERT statement to +# be rolled back. The result was that some (but not all) of the rows that +# should have been inserted went missing. +# +do_test tkt3718-1.2 { + execsql { + BEGIN; + INSERT INTO t2 SELECT a, b FROM t1; + INSERT INTO t2 SELECT a+5, f1(b) FROM t1; + COMMIT; + } + execsql { + SELECT a FROM t2; + } +} {1 2 3 4 5 6 7 8 9 10} + +# This test turns on the count_changes pragma (causing DML statements to +# return SQLITE_ROW once, with a single integer result value reporting the +# number of rows affected by the statement). It then executes an INSERT +# statement that requires a statement journal. After stepping the statement +# once, so that it returns SQLITE_ROW, a second SQL statement that throws an +# exception is run. At one point, before #3718 was fixed, this caused the +# statement transaction belonging to the INSERT statement to be rolled back. +# The result was that none of the rows were actually inserted. +# +# +do_test tkt3718-1.3 { + execsql { + DELETE FROM t2 WHERE a > 5; + PRAGMA count_changes = 1; + BEGIN; + } + db eval {INSERT INTO t2 SELECT a+5, b||'+5' FROM t1} { + catch { db eval {SELECT f2('three')} } msg + } + execsql { + COMMIT; + SELECT a FROM t2; + } +} {1 2 3 4 5 6 7 8 9 10} + +do_test tkt3718-1.4 { + execsql {pragma count_changes=0} +} {} + +# This SQL function executes the SQL specified as an argument against +# database [db]. +# +proc sql {doit zSql} { + if {$doit} { catchsql $zSql } +} +db func sql [list sql] + +# The following tests, tkt3718-2.*, test that a nested statement +# transaction can be successfully committed or reverted without +# affecting the parent statement transaction. +# +do_test tkt3718-2.1 { + execsql { SELECT sql(1, 'DELETE FROM t2 WHERE a = '||a ) FROM t2 WHERE a>5 } + execsql { SELECT a from t2 } +} {1 2 3 4 5} +do_test tkt3718-2.2 { + execsql { + DELETE FROM t2 WHERE a > 5; + BEGIN; + INSERT INTO t2 SELECT a+5, sql(a==3, + 'INSERT INTO t2 SELECT a+10, f2(b) FROM t1' + ) FROM t1; + } + execsql { + COMMIT; + SELECT a FROM t2; + } +} {1 2 3 4 5 6 7 8 9 10} +do_test tkt3718-2.3 { + execsql { + DELETE FROM t2 WHERE a > 5; + BEGIN; + INSERT INTO t2 SELECT a+5, sql(a==3, + 'INSERT INTO t2 SELECT a+10, b FROM t1' + ) FROM t1; + COMMIT; + } + execsql { SELECT a FROM t2 ORDER BY a+0} +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} +integrity_check tkt3718.2-4 + +# The next set of tests, tkt3718-3.*, test that a statement transaction +# that has a committed statement transaction nested inside of it can +# be committed or reverted. +# +foreach {tn io ii results} { + 1 0 10 {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20} + 2 1 10 {6 7 8 9 10 16 17 18 19 20} + 3 0 11 {1 2 3 4 5 6 7 8 9 10 16 17 18 19 20} + 4 1 11 {6 7 8 9 10 16 17 18 19 20} +} { + do_test tkt3718-3.$tn { + execsql { + DELETE FROM t2; + INSERT INTO t2 SELECT a+5, b FROM t1; + INSERT INTO t2 SELECT a+15, b FROM t1; + } + + catchsql " + BEGIN; + INSERT INTO t2 SELECT a+$io, sql(a==3, + 'INSERT INTO t2 SELECT a+$ii, b FROM t1' + ) FROM t1; + " + + execsql { COMMIT } + + execsql { SELECT a FROM t2 ORDER BY a+0} + } $results + + integrity_check tkt3718-3.$tn.integrity +} + +# This is the same test as tkt3718-3.*, but with 3 levels of nesting. +# +foreach {tn i1 i2 i3 results} { + 1 0 10 20 {5 10 15 20 25 30} + 2 0 10 21 {5 10 15 20 30} + 3 0 11 20 {5 10 20 30} + 4 0 11 21 {5 10 20 30} + 5 1 10 20 {10 20 30} + 6 1 10 21 {10 20 30} + 7 1 11 20 {10 20 30} + 8 1 11 21 {10 20 30} +} { + do_test tkt3718-4.$tn { + execsql { + DELETE FROM t2; + INSERT INTO t2 SELECT a+5, b FROM t1; + INSERT INTO t2 SELECT a+15, b FROM t1; + INSERT INTO t2 SELECT a+25, b FROM t1; + } + + catchsql " + BEGIN; + INSERT INTO t2 SELECT a+$i1, sql(a==3, + 'INSERT INTO t2 SELECT a+$i2, sql(a==3, + ''INSERT INTO t2 SELECT a+$i3, b FROM t1'' + ) FROM t1' + ) FROM t1; + " + + execsql { COMMIT } + + execsql { SELECT a FROM t2 WHERE (a%5)==0 ORDER BY a+0} + } $results + + do_test tkt3718-4.$tn.extra { + execsql { + SELECT + (SELECT sum(a) FROM t2)==(SELECT sum(a*5-10) FROM t2 WHERE (a%5)==0) + } + } {1} + + integrity_check tkt3718-4.$tn.integrity +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3731.test b/components/external/SQLite-3.8.1/test/tkt3731.test new file mode 100644 index 0000000000000000000000000000000000000000..11e5efd707e66f1e326b689cb639c77a2213cf6d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3731.test @@ -0,0 +1,56 @@ +# 2009 March 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: tkt3731.test,v 1.1 2009/03/17 22:33:01 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +# The tests in this file were written before SQLite supported recursive +# trigger invocation, and some tests depend on that to pass. So disable +# recursive triggers for this file. +catchsql { pragma recursive_triggers = off } + +do_test tkt3731-1.1 { + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN + INSERT INTO t1 VALUES(new.a || '+', new.b || '+'); + END; + } +} {} + +do_test tkt3731-1.2 { + execsql { + INSERT INTO t1 VALUES('a', 'b'); + INSERT INTO t1 VALUES('c', 'd'); + SELECT * FROM t1; + } +} {a b a+ b+ c d c+ d+} + +do_test tkt3731-1.3 { + execsql { + DELETE FROM t1; + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES('e', 'f'); + INSERT INTO t2 VALUES('g', 'h'); + INSERT INTO t1 SELECT * FROM t2; + SELECT * FROM t1; + } +} {e f e+ f+ g h g+ h+} + +integrity_check tkt3731-1.4 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3757.test b/components/external/SQLite-3.8.1/test/tkt3757.test new file mode 100644 index 0000000000000000000000000000000000000000..011beb5c8b79f8f1a1b46832dab5bdfce88ea10d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3757.test @@ -0,0 +1,60 @@ +# 2009 March 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3757: The cost functions on the query optimizer for the +# IN operator can be improved. +# +# $Id: tkt3757.test,v 1.1 2009/03/29 00:13:04 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Evaluate SQL. Return the result set followed by the +# and the number of full-scan steps. +# +proc count_steps {sql} { + set r [db eval $sql] + lappend r scan [db status step] sort [db status sort] +} + +# Construct tables +# +do_test tkt3757-1.1 { + db eval { + CREATE TABLE t1(x INTEGER, y INTEGER, z TEXT); + CREATE INDEX t1i1 ON t1(y,z); + INSERT INTO t1 VALUES(1,2,'three'); + CREATE TABLE t2(a INTEGER, b TEXT); + INSERT INTO t2 VALUES(2, 'two'); + ANALYZE; + SELECT * FROM sqlite_stat1 ORDER BY 1, 2; + } +} {t1 t1i1 {1 1 1} t2 {} 1} + +# Modify statistics in order to make the optimizer then that: +# +# (1) Table T1 has about 250K entries +# (2) There are only about 5 distinct values of T1. +# +# Then run a query with "t1.y IN (SELECT ..)" in the WHERE clause. +# Make sure the index is used. +# +do_test tkt3757-1.2 { + db eval { + DELETE FROM sqlite_stat1; + INSERT INTO sqlite_stat1 VALUES('t1','t1i1','250000 50000 30'); + } + count_steps { + SELECT * FROM t1 WHERE y IN (SELECT a FROM t2) + } +} {1 2 three scan 0 sort 0} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3761.test b/components/external/SQLite-3.8.1/test/tkt3761.test new file mode 100644 index 0000000000000000000000000000000000000000..2601b151dfa35306948722524adcd9f5f597735a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3761.test @@ -0,0 +1,40 @@ +# 2009 March 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3761: Make sure that an incremental vacuum on an in-memory +# database can be rolled back. +# +# $Id: tkt3761.test,v 1.1 2009/03/31 02:54:40 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3761-1.1 { + db close + sqlite3 db :memory: + db eval { + PRAGMA auto_vacuum=INCREMENTAL; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(zeroblob(900)); + INSERT INTO t1 VALUES(zeroblob(900)); + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + BEGIN; + DELETE FROM t1 WHERE rowid%2; + PRAGMA incremental_vacuum(4); + ROLLBACK; + } + db eval {PRAGMA integrity_check} +} {ok} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3762.test b/components/external/SQLite-3.8.1/test/tkt3762.test new file mode 100644 index 0000000000000000000000000000000000000000..424b1e6487554a5e43084e4b7720263faee0ed32 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3762.test @@ -0,0 +1,54 @@ +# 2009 March 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3762: Make sure that an incremental vacuum that reduces the +# size of the database file such that if a pointer-map page is eliminated +# it can be correctly rolled back. +# +# That ticket #3762 has been fixed has already been verified by the +# savepoint6.test test script. But this script is simplier and a +# redundant test never hurts. +# +# $Id: tkt3762.test,v 1.1 2009/03/31 00:50:36 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3762-1.1 { + db eval { + PRAGMA auto_vacuum=INCREMENTAL; + PRAGMA page_size=1024; + PRAGMA cache_size=10; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(zeroblob(900)); + INSERT INTO t1 VALUES(zeroblob(900)); + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + INSERT INTO t1 SELECT x FROM t1; + DELETE FROM t1 WHERE rowid>202; + VACUUM; + + BEGIN; + DELETE FROM t1 WHERE rowid IN (10,11,12) ; + PRAGMA incremental_vacuum(10); + UPDATE t1 SET x=zeroblob(900) WHERE rowid BETWEEN 100 AND 110; + INSERT INTO t1 VALUES(zeroblob(39000)); + SELECT count(*) FROM t1; + ROLLBACK; + } + db eval {PRAGMA integrity_check} +} {ok} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3773.test b/components/external/SQLite-3.8.1/test/tkt3773.test new file mode 100644 index 0000000000000000000000000000000000000000..3f5a1a3217ae4ede2647bdfef161aa0d81b69fa9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3773.test @@ -0,0 +1,43 @@ +# 2009 April 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3773: Be careful not to over-optimize when a compound +# subquery contains an ORDER BY clause. +# +# +# $Id: tkt3773.test,v 1.1 2009/04/02 16:59:47 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !compound { + finish_test + return +} + +do_test tkt3773-1.1 { + db eval { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(2,1); + INSERT INTO t1 VALUES(33,3); + CREATE TABLE t2(x,y); + INSERT INTO t2 VALUES(123,2); + INSERT INTO t2 VALUES(4,4); + SELECT a FROM ( + SELECT a, b FROM t1 + UNION ALL + SELECT x, y FROM t2 + ORDER BY 2 + ); + } +} {2 123 33 4} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3791.test b/components/external/SQLite-3.8.1/test/tkt3791.test new file mode 100644 index 0000000000000000000000000000000000000000..5d676ca1038206ae3a7e166a4e2b60faf8063fd3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3791.test @@ -0,0 +1,28 @@ +# 2009 April 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3791: A segfault when inserting into a table that contains +# an arbitrary expression as its default value. +# +# $Id: tkt3791.test,v 1.1 2009/04/08 12:21:31 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3791-1.1 { + db eval { + CREATE TABLE t1(x, y DEFAULT(datetime('now'))); + INSERT INTO t1(x) VALUES(1); + SELECT x, length(y) FROM t1; + } +} {1 19} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3793.test b/components/external/SQLite-3.8.1/test/tkt3793.test new file mode 100644 index 0000000000000000000000000000000000000000..074aab2df0a7a46fa66a81a922fce261fc8f4795 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3793.test @@ -0,0 +1,121 @@ +# 2009 April 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #3793 has been +# fixed. +# +# $Id: tkt3793.test,v 1.2 2009/06/01 16:42:18 shane Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !shared_cache||!attach { + finish_test + return +} +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +do_test tkt3793-1.1 { + # This is taken from shared.test. The Windows VFS expands + # ./test.db (and test.db) to be the same thing so the path + # matches and they share a cache. By changing the case + # for Windows platform, we get around this and get a separate + # connection. + if {$::tcl_platform(platform)=="unix"} { + sqlite3 db1 test.db + sqlite3 db2 test.db + } else { + sqlite3 db1 TEST.DB + sqlite3 db2 TEST.DB + } + execsql { + BEGIN; + CREATE TABLE t1(a, b); + CREATE TABLE t2(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(randstr(50,50), randstr(50,50)); + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t1 SELECT randstr(50,50), randstr(50,50) FROM t1; + INSERT INTO t2 SELECT * FROM t1; + COMMIT; + } +} {} + +proc busyhandler {db args} { set ::busyconnection $db ; return 1 } +db2 busy {busyhandler db2} +db1 busy {busyhandler db1} + +# Establish a read-lock on the database file using connection [db]. +# +do_test tkt3793-1.2 { + execsql { + BEGIN; + SELECT count(*) FROM t1; + } +} {1024} + +# Set the size of the cache shared by [db1] and [db2] to 10. Then update +# more than 10 pages of table t1. At this point the shared-cache will +# hold a RESERVED lock on the database file. Even though there are now +# more than 10 dirty pages in memory, it cannot upgrade to an EXCLUSIVE +# lock because of the read-lock held by [db]. +# +do_test tkt3793-1.3 { + execsql { + PRAGMA cache_size = 10; + BEGIN; + UPDATE t1 SET b = randstr(50,50); + } db1 +} {} + +set x 0 + +# Run one SELECT query on the shared-cache using [db1], then from within +# the callback run another via [db2]. Because of the large number of dirty +# pages within the cache, each time a new page is read from the database +# SQLite will attempt to upgrade to an EXCLUSIVE lock, and hence invoke +# the busy-handler. The tests here verify that the correct busy-handler +# function is invoked (the busy-handler associated with the database +# connection that called sqlite3_step()). When bug #3793 existed, sometimes +# the [db2] busy-handler was invoked from within the call to sqlite3_step() +# associated with [db1]. +# +# Note: Before the bug was fixed, if [db2] was opened with the "-fullmutex 1" +# option, then this test case would cause an assert() to fail. +# +ifcapable threadsafe { + set ::busyconnection db1 + db1 eval {SELECT * FROM t2 ORDER BY a LIMIT 20} { + do_test tkt3793-2.[incr x] { set ::busyconnection } db1 + set ::busyconnection db2 + + db2 eval { SELECT count(*) FROM t2 } + do_test tkt3793-2.[incr x] { set ::busyconnection } db2 + set ::busyconnection db1 + } +} + +do_test tkt3793-3 { + db1 close + db2 close +} {} + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3810.test b/components/external/SQLite-3.8.1/test/tkt3810.test new file mode 100644 index 0000000000000000000000000000000000000000..7e1b2ec5c9cddc3deabbcddc1c5964c51ccceeaa --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3810.test @@ -0,0 +1,87 @@ +# 2009 August 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests to make sure #3810 is fixed. +# +# $Id: tkt3810.test,v 1.4 2009/08/06 17:43:31 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +# Create a table using the first database connection. +# +do_test tkt3810-1.1 { + execsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(123); + SELECT * FROM t1; + CREATE TABLE t2(y); + CREATE TABLE t3(z); + } +} 123 + +# Create a second connection to the same database. Make sure the +# schema of the database has been parsed by the second connection. +# +do_test tkt3810-2 { + sqlite3 db2 test.db + execsql { + SELECT * FROM t1; + } db2 +} 123 + +# DROP the table using the second connection. The table no longer exists +# but the first connection does not yet know this. Then try to create a TEMP +# trigger in the first connection that references the table that was dropped. +# +do_test tkt3810-3 { + execsql {DROP TABLE t1} db2 + execsql { + CREATE TEMP TRIGGER r1 AFTER INSERT ON t1 BEGIN + INSERT INTO t2 VALUES(new.rowid); + END; + } + catchsql { + SELECT * FROM t3; + } +} {0 {}} + +# Trigger still exists in the sqlite_temp_master table, but now it is +# an orphan. +# +do_test tkt3810-4 { + execsql {SELECT name FROM sqlite_temp_master ORDER BY name} +} {r1} + +# Because it is an orphan, it cannot be dropped. +# +do_test tkt3810-5 { + catchsql {DROP TRIGGER r1} +} {1 {no such trigger: r1}} + +# Create a table t1 then drop the table in order to drop the orphaned +# trigger. +# +do_test tkt3810-6 { + execsql {CREATE TABLE t1(x)} db2 + execsql {DROP TABLE t1} + execsql { + SELECT name FROM sqlite_temp_master; + } +} {} + +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3824.test b/components/external/SQLite-3.8.1/test/tkt3824.test new file mode 100644 index 0000000000000000000000000000000000000000..3198abbdd3afbd17b801727cfb6c73c97649284e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3824.test @@ -0,0 +1,99 @@ +# 2009 April 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3824 +# +# When you use an "IS NULL" constraint on a UNIQUE index, the result +# is not necessarily UNIQUE. Make sure the optimizer does not assume +# uniqueness. +# +# $Id: tkt3824.test,v 1.2 2009/04/24 20:32:31 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc execsql_status {sql {db db}} { + set result [uplevel $db eval [list $sql]] + if {[db status sort]} { + concat $result sort + } else { + concat $result nosort + } +} + +do_test tkt3824-1.1 { + db eval { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,NULL); + INSERT INTO t1 VALUES(9,NULL); + INSERT INTO t1 VALUES(5,NULL); + INSERT INTO t1 VALUES(123,NULL); + INSERT INTO t1 VALUES(-10,NULL); + CREATE UNIQUE INDEX t1b ON t1(b); + } + execsql_status { + SELECT a FROM t1 WHERE b IS NULL ORDER BY a; + } +} {-10 1 5 9 123 sort} +do_test tkt3824-1.2 { + execsql_status { + SELECT a FROM t1 WHERE b IS NULL ORDER BY b, a; + } +} {-10 1 5 9 123 sort} + +do_test tkt3824-2.1 { + db eval { + CREATE TABLE t2(a,b,c); + INSERT INTO t2 VALUES(1,1,NULL); + INSERT INTO t2 VALUES(9,2,NULL); + INSERT INTO t2 VALUES(5,2,NULL); + INSERT INTO t2 VALUES(123,3,NULL); + INSERT INTO t2 VALUES(-10,3,NULL); + CREATE UNIQUE INDEX t2bc ON t2(b,c); + } + execsql_status { + SELECT a FROM t2 WHERE b=2 AND c IS NULL ORDER BY a; + } +} {5 9 sort} +do_test tkt3824-2.2 { + execsql_status { + SELECT a FROM t2 WHERE b=2 AND c IS NULL ORDER BY b, a; + } +} {5 9 sort} +do_test tkt3824-2.3 { + lsort [execsql_status { + SELECT a FROM t2 WHERE b=2 AND c IS NULL ORDER BY b; + }] +} {5 9 nosort} + +do_test tkt3824-3.1 { + db eval { + CREATE TABLE t3(x,y); + INSERT INTO t3 SELECT a, b FROM t1; + INSERT INTO t3 VALUES(234,567); + CREATE UNIQUE INDEX t3y ON t3(y); + DELETE FROM t3 WHERE y IS NULL; + SELECT * FROM t3; + } +} {234 567} + +do_test tkt3824-4.1 { + db eval { + CREATE TABLE t4(x,y); + INSERT INTO t4 SELECT a, b FROM t1; + INSERT INTO t4 VALUES(234,567); + CREATE UNIQUE INDEX t4y ON t4(y); + UPDATE t4 SET rowid=rowid+100 WHERE y IS NULL; + SELECT rowid, x FROM t4 ORDER BY rowid; + } +} {6 234 101 1 102 9 103 5 104 123 105 -10} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3832.test b/components/external/SQLite-3.8.1/test/tkt3832.test new file mode 100644 index 0000000000000000000000000000000000000000..bb73c8c7d061a035cce8482c89abbbb6cf3ddc21 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3832.test @@ -0,0 +1,41 @@ +# 2009 April 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3832 +# +# A segfault when using a BEFORE trigger on an INSERT and inserting +# a NULL into the INTEGER PRIMARY KEY. +# +# $Id: tkt3832.test,v 1.1 2009/05/01 02:08:04 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + + +do_test tkt3832-1.1 { + db eval { + CREATE TABLE t1(a INT, b INTEGER PRIMARY KEY); + CREATE TABLE log(x); + CREATE TRIGGER t1r1 BEFORE INSERT ON t1 BEGIN + INSERT INTO log VALUES(new.b); + END; + INSERT INTO t1 VALUES(NULL,5); + INSERT INTO t1 SELECT b, a FROM t1 ORDER BY b; + SELECT rowid, * FROM t1; + SELECT rowid, * FROM log; + } +} {5 {} 5 6 5 6 1 5 2 -1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3838.test b/components/external/SQLite-3.8.1/test/tkt3838.test new file mode 100644 index 0000000000000000000000000000000000000000..fa937acdf4ea2f5b7024443ff2eafb9f29a8bea3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3838.test @@ -0,0 +1,58 @@ +# 2009 May 5 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3838 +# +# The ticket reports that the encoding is UTF8 on the DEFAULT VALUE of +# a column added using ALTER TABLE even when the database is UTF16. +# Verify that this has been fixed. +# +# $Id: tkt3838.test,v 1.1 2009/05/05 12:54:50 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !altertable { + finish_test + return +} + +do_realnum_test tkt3838-1.1 { + db eval { + PRAGMA encoding=UTF16; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + ALTER TABLE t1 ADD COLUMN b INTEGER DEFAULT '999'; + ALTER TABLE t1 ADD COLUMN c REAL DEFAULT '9e99'; + ALTER TABLE t1 ADD COLUMN d TEXT DEFAULT 'xyzzy'; + UPDATE t1 SET x=x+1; + SELECT * FROM t1; + } +} {2 999 9e+99 xyzzy} + +ifcapable trigger { + do_test tkt3838-1.2 { + db eval { + CREATE TABLE log(y); + CREATE TRIGGER r1 AFTER INSERT ON T1 BEGIN + INSERT INTO log VALUES(new.x); + END; + INSERT INTO t1(x) VALUES(123); + ALTER TABLE T1 RENAME TO XYZ2; + INSERT INTO xyz2(x) VALUES(456); + ALTER TABLE xyz2 RENAME TO pqr3; + INSERT INTO pqr3(x) VALUES(789); + SELECT * FROM log; + } + } {123 456 789} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3841.test b/components/external/SQLite-3.8.1/test/tkt3841.test new file mode 100644 index 0000000000000000000000000000000000000000..df6de5c2f3972689f6c8d722804506c3cead5476 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3841.test @@ -0,0 +1,48 @@ +# 2009 May 7 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Ticket #3841 +# +# The sqlite3_aggregate_count() is not being reset when an aggregate +# functio is used in a correlated subquery. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !subquery { + finish_test + return +} + +do_test tkt3841.1 { + execsql { + CREATE TABLE table2 (key TEXT, x TEXT); + CREATE TABLE list (key TEXT, value TEXT); + + INSERT INTO table2 VALUES ("a", "alist"); + INSERT INTO table2 VALUES ("b", "blist"); + INSERT INTO list VALUES ("a", 1); + INSERT INTO list VALUES ("a", 2); + INSERT INTO list VALUES ("a", 3); + INSERT INTO list VALUES ("b", 4); + INSERT INTO list VALUES ("b", 5); + INSERT INTO list VALUES ("b", 6); + + SELECT + table2.x, + (SELECT group_concat(list.value) + FROM list + WHERE list.key = table2.key) + FROM table2; + } +} {alist 1,2,3 blist 4,5,6} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3871.test b/components/external/SQLite-3.8.1/test/tkt3871.test new file mode 100644 index 0000000000000000000000000000000000000000..e7dbfde714d9286f3b3d602af32219835f27ee60 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3871.test @@ -0,0 +1,53 @@ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +register_echo_module [sqlite3_connection_pointer db] + +do_test tkt3871-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + } + for {set i 0} {$i < 500} {incr i} { + execsql { INSERT INTO t1 VALUES($i, $i*$i) } + } + execsql COMMIT + execsql { + CREATE VIRTUAL TABLE e USING echo(t1); + SELECT count(*) FROM e; + } +} {500} + +do_test tkt3871-1.2 { + execsql { SELECT * FROM e WHERE a = 1 OR a = 2 } +} {1 1 2 4} +do_test tkt3871-1.3 { + set echo_module "" + execsql { SELECT * FROM e WHERE a = 1 OR a = 2 } + set echo_module +} [list \ + xFilter {SELECT rowid, * FROM 't1' WHERE a = ?} 1 \ + xFilter {SELECT rowid, * FROM 't1' WHERE a = ?} 2 \ +] + +do_test tkt3871-1.4 { + execsql { SELECT * FROM e WHERE a = 1 OR a = 2 OR b = 9 } +} {1 1 2 4 3 9} +do_test tkt3871-1.5 { + set echo_module "" + execsql { SELECT * FROM e WHERE a = 1 OR a = 2 OR b = 9 } + set echo_module +} [list \ + xFilter {SELECT rowid, * FROM 't1' WHERE a = ?} 1 \ + xFilter {SELECT rowid, * FROM 't1' WHERE a = ?} 2 \ + xFilter {SELECT rowid, * FROM 't1' WHERE b = ?} 9 +] + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3879.test b/components/external/SQLite-3.8.1/test/tkt3879.test new file mode 100644 index 0000000000000000000000000000000000000000..ed5577f909c86b1d571cb9dd5855304af1e716a5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3879.test @@ -0,0 +1,52 @@ +# 2009 May 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests to verify ticket #3879 is fixed. +# +# $Id: tkt3879.test,v 1.2 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3879.1.1 { + execsql { + CREATE TABLE t1 (a PRIMARY KEY, b); + INSERT INTO t1 VALUES ('w', 1); + INSERT INTO t1 VALUES ('z', -1); + + CREATE TABLE t2 (m INTEGER PRIMARY KEY, n, a, p); + INSERT INTO t2 VALUES (25, 13, 'w', 1); + INSERT INTO t2 VALUES (26, 25, 'z', 153); + INSERT INTO t2 VALUES (27, 25, 'z', 68); + + CREATE TABLE t3 (m); + INSERT INTO t3 VALUES (25); + } +} {} + +do_test tkt3879.1.2 { + execsql { + SELECT 111, t1.b*123 + FROM t3, t2 AS j0, t2 AS j1, t1 + WHERE j0.m=t3.m AND t1.a=j0.a AND j1.n=j0.m; + } +} {111 123 111 123} + +do_test tkt3879.1.3 { + execsql { + SELECT 222, t1.b*123 + FROM t3, t2 AS j0, t2 AS j1, t1 + WHERE j0.m=t3.m AND t1.a=j0.a AND j1.n=j0.m + ORDER BY t1.b; + } +} {222 123 222 123} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3911.test b/components/external/SQLite-3.8.1/test/tkt3911.test new file mode 100644 index 0000000000000000000000000000000000000000..2ac56cbbc756d9be4f276c3623270ea9d257fba6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3911.test @@ -0,0 +1,58 @@ +# 2009 June 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests to verify ticket #3911 is fixed. +# +# $Id: tkt3911.test,v 1.1 2009/06/12 03:27:28 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3911.1 { + execsql { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(11,12); + + CREATE TABLE t2(b,c); + INSERT INTO t2 VALUES(2,3); + INSERT INTO t2 VALUES(22,23); + + SELECT * FROM t1 JOIN t2 USING(b); + } +} {1 2 3} +do_test tkt3911.2 { + db eval { + SELECT * FROM t1 JOIN (t2) AS x USING (b); + } +} {1 2 3} +do_test tkt3911.3 { + db eval { + SELECT * FROM t1 JOIN (SELECT * FROM t2) AS x USING (b); + } +} {1 2 3} + +do_test tkt3911.4 { + db eval { + CREATE TABLE t3(m,a); + INSERT INTO t3 VALUES('one',1); + INSERT INTO t3 VALUES('two',2); + + SELECT * FROM t3 JOIN (SELECT * FROM t1 NATURAL JOIN t2) AS x USING(a); + } +} {one 1 2 3} +do_test tkt3911.5 { + db eval { + SELECT * FROM t3 JOIN (SELECT * FROM t1 JOIN t2 USING (b)) AS x USING(a); + } +} {one 1 2 3} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3918.test b/components/external/SQLite-3.8.1/test/tkt3918.test new file mode 100644 index 0000000000000000000000000000000000000000..e20ee152fc17a16334b644a9bd8321f08b132b91 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3918.test @@ -0,0 +1,59 @@ +# 2009 June 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: tkt3918.test,v 1.1 2009/06/17 11:13:28 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3918.1 { + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = incremental; + CREATE TABLE t1(i, x); + } +} {} +do_test tkt3918.2 { + execsql { + INSERT INTO t1 VALUES(1, randstr(1000,1000)); + INSERT INTO t1 VALUES(2, zeroblob(248*1020 + 100)); + INSERT INTO t1 VALUES(3, zeroblob(2*1020 + 100)); + } +} {} + +# This set of statements sets up the free list so that the +# first free-list trunk page contains only a single leaf. +# The leaf page is also the last page in the database. The +# second free-list trunk page contains, amongst other things, +# page number 4. +do_test tkt3918.3 { + execsql { + DELETE FROM t1 WHERE i = 2; + DELETE FROM t1 WHERE i = 1; + DELETE FROM t1 WHERE i = 3; + } +} {} + +# Incrementally vacuum the database to reduce its size by a single +# page. This will remove the single leaf from the first page in +# the linked list of free-list trunk pages. +do_test tkt3918.4 { + execsql { PRAGMA incremental_vacuum = 1 } +} {} + +# Create another table. This operation will attempt to extract +# page 4 from the database free-list. Bug 3918 caused sqlite to +# incorrectly report corruption here. +do_test tkt3918.5 { + execsql { CREATE TABLE t2(a, b) } +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3922.test b/components/external/SQLite-3.8.1/test/tkt3922.test new file mode 100644 index 0000000000000000000000000000000000000000..86bf5feceb71fdfc3e02e641d007d8fab518c5f9 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3922.test @@ -0,0 +1,89 @@ +# 2009 June 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: tkt3922.test,v 1.2 2009/06/26 14:17:47 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +if {[working_64bit_int]} { + do_test tkt3922.1 { + execsql { + CREATE TABLE t1(a NUMBER); + INSERT INTO t1 VALUES('-9223372036854775808'); + SELECT a, typeof(a) FROM t1; + } + } {-9223372036854775808 integer} +} else { + # this alternate version of tkt3922.1 doesn't + # really test the same thing as the original, + # but is needed to create the table and + # provided simply as a place holder for + # platforms without working 64bit support. + do_test tkt3922.1 { + execsql { + CREATE TABLE t1(a NUMBER); + INSERT INTO t1 VALUES('-1'); + SELECT a, typeof(a) FROM t1; + } + } {-1 integer} +} +do_realnum_test tkt3922.2 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES('-9223372036854775809'); + SELECT a, typeof(a) FROM t1; + } +} {-9.22337203685478e+18 real} +do_realnum_test tkt3922.3 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES('-9223372036854776832'); + SELECT a, typeof(a) FROM t1; + } +} {-9.22337203685478e+18 real} +do_realnum_test tkt3922.4 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES('-9223372036854776833'); + SELECT a, typeof(a) FROM t1; + } +} {-9.22337203685478e+18 real} +if {[working_64bit_int]} { + do_test tkt3922.5 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES('9223372036854775807'); + SELECT a, typeof(a) FROM t1; + } + } {9223372036854775807 integer} +} else { + # this alternate version of tkt3922.5 doesn't + # really test the same thing as the original, + # but provided simply as a place holder for + # platforms without working 64bit support. + do_test tkt3922.5 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES('1'); + SELECT a, typeof(a) FROM t1; + } + } {1 integer} +} +do_realnum_test tkt3922.6 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES('9223372036854775808'); + SELECT a, typeof(a) FROM t1; + } +} {9.22337203685478e+18 real} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3929.test b/components/external/SQLite-3.8.1/test/tkt3929.test new file mode 100644 index 0000000000000000000000000000000000000000..db02bb841e5330a0de545eeee118fd68627c0972 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3929.test @@ -0,0 +1,52 @@ +# 2009 June 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests to verify ticket #3929 is fixed. +# +# $Id: tkt3929.test,v 1.1 2009/06/23 11:53:09 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +do_test tkt3929-1.0 { + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a, b); + CREATE TRIGGER t1_t1 AFTER INSERT ON t1 BEGIN + UPDATE t1 SET b = 'value: ' || a WHERE t1.rowid = new.rowid; + END; + } +} {} + +do_test tkt3929-1.1 { + execsql { + INSERT INTO t1(a) VALUES(1); + INSERT INTO t1(a) VALUES(2); + SELECT * FROM t1; + } +} {1 {value: 1} 2 {value: 2}} + +# Before it was fixed, the following provoked the bug, causing either an +# assertion failure or a "database is malformed" error. +# +do_test tkt3930-1.2 { + for {set i 3} {$i < 100} {incr i} { + execsql { INSERT INTO t1(a) VALUES($i) } + } +} {} + +integrity_check tkt3930-1.3 +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3935.test b/components/external/SQLite-3.8.1/test/tkt3935.test new file mode 100644 index 0000000000000000000000000000000000000000..abbeb3f8669e66d6a9eccf40c2a59d78dcb4dc72 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3935.test @@ -0,0 +1,57 @@ +# 2009 July 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #3935 has been fixed. +# +# $Id: tkt3935.test,v 1.2 2009/07/01 16:12:08 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3935.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); + } +} {} + +do_test tkt3935.2 { + execsql { SELECT j1.b FROM ( SELECT * FROM t1 INNER JOIN t2 ON a=c ) AS j1 } +} {} +do_test tkt3935.3 { + execsql { SELECT j1.b FROM (t1 INNER JOIN t2 ON a=c) AS j1 } +} {} + + +do_test tkt3935.4 { + catchsql { SELECT a FROM (t1) AS t ON b USING(a) } +} {1 {a JOIN clause is required before ON}} +do_test tkt3935.5 { + catchsql { SELECT a FROM (t1) AS t ON b } +} {1 {a JOIN clause is required before ON}} +do_test tkt3935.6 { + catchsql { SELECT a FROM (SELECT * FROM t1) AS t ON b USING(a) } +} {1 {a JOIN clause is required before ON}} +do_test tkt3935.7 { + catchsql { SELECT a FROM (SELECT * FROM t1) AS t ON b } +} {1 {a JOIN clause is required before ON}} +do_test tkt3935.8 { + catchsql { SELECT a FROM t1 AS t ON b } +} {1 {a JOIN clause is required before ON}} +do_test tkt3935.9 { + catchsql { SELECT a FROM t1 AS t ON b USING(a) } +} {1 {a JOIN clause is required before ON}} +do_test tkt3935.10 { + catchsql { SELECT a FROM t1 AS t USING(a) } +} {1 {a JOIN clause is required before USING}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3992.test b/components/external/SQLite-3.8.1/test/tkt3992.test new file mode 100644 index 0000000000000000000000000000000000000000..0d8a30f94d7386617765b374e184ae4c586dac22 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3992.test @@ -0,0 +1,81 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: tkt3992.test,v 1.1 2009/07/27 10:05:06 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tkt3992-1.1 { + execsql { + CREATE TABLE parameters1( + mountcnt INT NOT NULL CHECK (typeof(mountcnt) == 'integer'), + version REAL NOT NULL + ); + INSERT INTO parameters1(mountcnt, version) VALUES(1, 1.0); + + CREATE TABLE parameters2( + mountcnt INT NOT NULL CHECK (typeof(mountcnt) == 'integer'), + version REAL CHECK (typeof(version) == 'real') + ); + INSERT INTO parameters2(mountcnt, version) VALUES(1, 1.0); + } +} {} + +do_test tkt3992-1.2 { + execsql { + UPDATE parameters1 SET mountcnt = mountcnt + 1; + SELECT * FROM parameters1; + } +} {2 1.0} + +do_test tkt3992-1.3 { + execsql { + UPDATE parameters2 SET mountcnt = mountcnt + 1; + SELECT * FROM parameters2; + } +} {2 1.0} + +ifcapable altertable { + do_test tkt3992-2.1 { + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + ALTER TABLE t1 ADD COLUMN c DEFAULT 3; + SELECT * FROM t1; + } + } {1 2 3} + do_test tkt3992-2.2 { + execsql { + UPDATE t1 SET a = 'one'; + SELECT * FROM t1; + } + } {one 2 3} +} + +ifcapable trigger { + db function tcl eval + do_test tkt3992-2.3 { + execsql { + CREATE TABLE t2(a REAL, b REAL, c REAL); + INSERT INTO t2 VALUES(1, 2, 3); + CREATE TRIGGER tr2 BEFORE UPDATE ON t2 BEGIN + SELECT tcl('set res', typeof(new.c)); + END; + + UPDATE t2 SET a = 'I'; + } + set res + } {real} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt3997.test b/components/external/SQLite-3.8.1/test/tkt3997.test new file mode 100644 index 0000000000000000000000000000000000000000..85e88db5913d69b1a13a41894e08e4e089146f12 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt3997.test @@ -0,0 +1,73 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Tests to make sure #3997 is fixed. +# +# $Id: tkt3997.test,v 1.1 2009/07/28 13:30:31 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc reverse {lhs rhs} { + return [string compare $rhs $lhs] +} +proc usual {lhs rhs} { + return [string compare $lhs $rhs] +} + +db collate reverse reverse +db collate usual usual + +do_test tkt3997-1.1 { + execsql { + create table mytext(name BLOB); + INSERT INTO mytext VALUES('abc'); + INSERT INTO mytext VALUES('acd'); + INSERT INTO mytext VALUES('afe'); + } +} {} +do_test tkt3997-1.2 { + execsql { + SELECT name + FROM mytext + ORDER BY name COLLATE reverse + } +} {afe acd abc} +do_test tkt3997-1.3 { + execsql { + SELECT name + FROM (SELECT name FROM mytext) + ORDER BY name COLLATE reverse + } +} {afe acd abc} + +do_test tkt3997-2.1 { + execsql { + CREATE TABLE mytext2(name COLLATE reverse); + INSERT INTO mytext2 SELECT name FROM mytext; + } +} {} +do_test tkt3997-2.2 { + execsql { + SELECT name + FROM (SELECT name FROM mytext2) + ORDER BY name + } +} {afe acd abc} +do_test tkt3997-2.3 { + execsql { + SELECT name + FROM (SELECT name FROM mytext2) + ORDER BY name COLLATE usual + } +} {abc acd afe} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tkt4018.test b/components/external/SQLite-3.8.1/test/tkt4018.test new file mode 100644 index 0000000000000000000000000000000000000000..2bc41d47aa8fa882dc6c442be05f8b22296dc14e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tkt4018.test @@ -0,0 +1,89 @@ +# 2009 August 20 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to verify that ticket #4018 has been +# fixed. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc testsql {sql} { + set fd [open tf_main.tcl w] + puts $fd [subst -nocommands { + sqlite3_test_control_pending_byte 0x0010000 + sqlite3 db test.db + set rc [catch { db eval {$sql} } msg] + puts -nonewline "[set rc] {[set msg]}" + flush stdout + exit + }] + close $fd + set fd [open "| [info nameofexec] ./tf_main.tcl" r] + set res [read $fd] + close $fd + return $res +} + +do_test tkt4018-1.1 { + execsql { + CREATE TABLE t1(a, b); + BEGIN; + SELECT * FROM t1; + } +} {} + +# The database is locked by connection [db]. Open and close a second +# connection to test.db 10000 times. If file-descriptors are not being +# reused, then the process will quickly exceed its maximum number of +# file descriptors (1024 by default on linux). +do_test tkt4018-1.2 { + for {set i 0} {$i < 10000} {incr i} { + sqlite3 db2 test.db + db2 close + } +} {} + +# Now check that connection [db] is still holding a SHARED lock by +# having a second process try to write the db. +do_test tkt4018-1.3 { + testsql {INSERT INTO t1 VALUES(3, 4)} +} {1 {database is locked}} + +# Sanity checking. Have [db] release the lock and then retry the +# INSERT from the previous test case. +do_test tkt4018-1.4 { + db eval COMMIT + testsql {INSERT INTO t1 VALUES(3, 4)} +} {0 {}} + +# Check that reusing a file descriptor cannot change a read-only +# connection into a read-write connection. +do_test tkt4018-2.1 { + sqlite3 db2 test.db + execsql {INSERT INTO t1 VALUES(1, 2)} db2 +} {} +do_test tkt4018-2.2 { + execsql { + BEGIN; + SELECT * FROM t1 ORDER BY a; + } +} {1 2 3 4} +do_test tkt4018-2.3 { + db2 close + sqlite3 db2 test.db -readonly 1 + execsql COMMIT + catchsql {INSERT INTO t1 VALUES(5, 6)} db2 +} {1 {attempt to write a readonly database}} +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tokenize.test b/components/external/SQLite-3.8.1/test/tokenize.test new file mode 100644 index 0000000000000000000000000000000000000000..46fd4eeb75a0b30bb5031db18367640f4f3c0696 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tokenize.test @@ -0,0 +1,65 @@ +# 2008 July 7 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the tokenizer +# +# $Id: tokenize.test,v 1.1 2008/07/08 00:06:51 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test tokenize-1.1 { + catchsql {SELECT 1.0e+} +} {1 {unrecognized token: "1.0e"}} +do_test tokenize-1.2 { + catchsql {SELECT 1.0E+} +} {1 {unrecognized token: "1.0E"}} +do_test tokenize-1.3 { + catchsql {SELECT 1.0e-} +} {1 {unrecognized token: "1.0e"}} +do_test tokenize-1.4 { + catchsql {SELECT 1.0E-} +} {1 {unrecognized token: "1.0E"}} +do_test tokenize-1.5 { + catchsql {SELECT 1.0e+/} +} {1 {unrecognized token: "1.0e"}} +do_test tokenize-1.6 { + catchsql {SELECT 1.0E+:} +} {1 {unrecognized token: "1.0E"}} +do_test tokenize-1.7 { + catchsql {SELECT 1.0e-:} +} {1 {unrecognized token: "1.0e"}} +do_test tokenize-1.8 { + catchsql {SELECT 1.0E-/} +} {1 {unrecognized token: "1.0E"}} +do_test tokenize-1.9 { + catchsql {SELECT 1.0F+5} +} {1 {unrecognized token: "1.0F"}} +do_test tokenize-1.10 { + catchsql {SELECT 1.0d-10} +} {1 {unrecognized token: "1.0d"}} +do_test tokenize-1.11 { + catchsql {SELECT 1.0e,5} +} {1 {unrecognized token: "1.0e"}} +do_test tokenize-1.12 { + catchsql {SELECT 1.0E.10} +} {1 {unrecognized token: "1.0E"}} + +do_test tokenize-2.1 { + catchsql {SELECT 1, 2 /*} +} {1 {near "*": syntax error}} +do_test tokenize-2.2 { + catchsql {SELECT 1, 2 /* } +} {0 {1 2}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/tpch01.test b/components/external/SQLite-3.8.1/test/tpch01.test new file mode 100644 index 0000000000000000000000000000000000000000..2d099d63fb560bf385773f7110549ebe76b38a1f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tpch01.test @@ -0,0 +1,187 @@ +# 2013-09-05 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# TPC-H test queries. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix tpch01 + +do_execsql_test tpch01-1.0 { + CREATE TABLE NATION ( N_NATIONKEY INTEGER NOT NULL, + N_NAME CHAR(25) NOT NULL, + N_REGIONKEY INTEGER NOT NULL, + N_COMMENT VARCHAR(152)); + CREATE TABLE REGION ( R_REGIONKEY INTEGER NOT NULL, + R_NAME CHAR(25) NOT NULL, + R_COMMENT VARCHAR(152)); + CREATE TABLE PART ( P_PARTKEY INTEGER NOT NULL, + P_NAME VARCHAR(55) NOT NULL, + P_MFGR CHAR(25) NOT NULL, + P_BRAND CHAR(10) NOT NULL, + P_TYPE VARCHAR(25) NOT NULL, + P_SIZE INTEGER NOT NULL, + P_CONTAINER CHAR(10) NOT NULL, + P_RETAILPRICE DECIMAL(15,2) NOT NULL, + P_COMMENT VARCHAR(23) NOT NULL ); + CREATE TABLE SUPPLIER ( S_SUPPKEY INTEGER NOT NULL, + S_NAME CHAR(25) NOT NULL, + S_ADDRESS VARCHAR(40) NOT NULL, + S_NATIONKEY INTEGER NOT NULL, + S_PHONE CHAR(15) NOT NULL, + S_ACCTBAL DECIMAL(15,2) NOT NULL, + S_COMMENT VARCHAR(101) NOT NULL); + CREATE TABLE PARTSUPP ( PS_PARTKEY INTEGER NOT NULL, + PS_SUPPKEY INTEGER NOT NULL, + PS_AVAILQTY INTEGER NOT NULL, + PS_SUPPLYCOST DECIMAL(15,2) NOT NULL, + PS_COMMENT VARCHAR(199) NOT NULL ); + CREATE TABLE CUSTOMER ( C_CUSTKEY INTEGER NOT NULL, + C_NAME VARCHAR(25) NOT NULL, + C_ADDRESS VARCHAR(40) NOT NULL, + C_NATIONKEY INTEGER NOT NULL, + C_PHONE CHAR(15) NOT NULL, + C_ACCTBAL DECIMAL(15,2) NOT NULL, + C_MKTSEGMENT CHAR(10) NOT NULL, + C_COMMENT VARCHAR(117) NOT NULL); + CREATE TABLE ORDERS ( O_ORDERKEY INTEGER NOT NULL, + O_CUSTKEY INTEGER NOT NULL, + O_ORDERSTATUS CHAR(1) NOT NULL, + O_TOTALPRICE DECIMAL(15,2) NOT NULL, + O_ORDERDATE DATE NOT NULL, + O_ORDERPRIORITY CHAR(15) NOT NULL, + O_CLERK CHAR(15) NOT NULL, + O_SHIPPRIORITY INTEGER NOT NULL, + O_COMMENT VARCHAR(79) NOT NULL); + CREATE TABLE LINEITEM ( L_ORDERKEY INTEGER NOT NULL, + L_PARTKEY INTEGER NOT NULL, + L_SUPPKEY INTEGER NOT NULL, + L_LINENUMBER INTEGER NOT NULL, + L_QUANTITY DECIMAL(15,2) NOT NULL, + L_EXTENDEDPRICE DECIMAL(15,2) NOT NULL, + L_DISCOUNT DECIMAL(15,2) NOT NULL, + L_TAX DECIMAL(15,2) NOT NULL, + L_RETURNFLAG CHAR(1) NOT NULL, + L_LINESTATUS CHAR(1) NOT NULL, + L_SHIPDATE DATE NOT NULL, + L_COMMITDATE DATE NOT NULL, + L_RECEIPTDATE DATE NOT NULL, + L_SHIPINSTRUCT CHAR(25) NOT NULL, + L_SHIPMODE CHAR(10) NOT NULL, + L_COMMENT VARCHAR(44) NOT NULL); + CREATE INDEX npki on nation(N_NATIONKEY); + CREATE INDEX rpki on region(R_REGIONKEY); + CREATE INDEX ppki on part(P_PARTKEY); + CREATE INDEX spki on supplier(S_SUPPKEY); + CREATE INDEX pspki on partsupp(PS_PARTKEY, PS_SUPPKEY); + CREATE INDEX cpki on customer(C_CUSTKEY); + CREATE INDEX opki on orders(O_ORDERKEY); + CREATE INDEX lpki on lineitem(L_ORDERKEY, L_LINENUMBER); + CREATE INDEX nrki on nation(n_regionkey); + CREATE INDEX snki on supplier(s_nationkey); + CREATE INDEX cnki on customer(c_nationkey); + CREATE INDEX ocki on orders(O_CUSTKEY); + CREATE INDEX odi on orders(O_ORDERDATE); + CREATE INDEX lpki2 on lineitem(L_PARTKEY); + CREATE INDEX lski on lineitem(L_SUPPKEY); + CREATE INDEX lsdi on lineitem(L_SHIPDATE); + CREATE INDEX lcdi on lineitem(L_COMMITDATE); + CREATE INDEX lrdi on lineitem(L_RECEIPTDATE); + CREATE INDEX bootleg_nni on nation(N_NAME); + CREATE INDEX bootleg_psi on part(p_size); + CREATE INDEX bootleg_pti on part(p_type); + ANALYZE sqlite_master; + INSERT INTO sqlite_stat1 VALUES('LINEITEM','lrdi','600572 236'); + INSERT INTO sqlite_stat1 VALUES('LINEITEM','lcdi','600572 244'); + INSERT INTO sqlite_stat1 VALUES('LINEITEM','lsdi','600572 238'); + INSERT INTO sqlite_stat1 VALUES('LINEITEM','lski','600572 601'); + INSERT INTO sqlite_stat1 VALUES('LINEITEM','lpki2','600572 31'); + INSERT INTO sqlite_stat1 VALUES('LINEITEM','lpki','600572 5 1'); + INSERT INTO sqlite_stat1 VALUES('ORDERS','odi','150000 63'); + INSERT INTO sqlite_stat1 VALUES('ORDERS','ocki','150000 15'); + INSERT INTO sqlite_stat1 VALUES('ORDERS','opki','150000 1'); + INSERT INTO sqlite_stat1 VALUES('CUSTOMER','cnki','15000 600'); + INSERT INTO sqlite_stat1 VALUES('CUSTOMER','cpki','15000 1'); + INSERT INTO sqlite_stat1 VALUES('PARTSUPP','pspki','80000 4 1'); + INSERT INTO sqlite_stat1 VALUES('SUPPLIER','snki','1000 40'); + INSERT INTO sqlite_stat1 VALUES('SUPPLIER','spki','1000 1'); + INSERT INTO sqlite_stat1 VALUES('PART','bootleg_pti','20000 134'); + INSERT INTO sqlite_stat1 VALUES('PART','bootleg_psi','20000 400'); + INSERT INTO sqlite_stat1 VALUES('PART','ppki','20000 1'); + INSERT INTO sqlite_stat1 VALUES('REGION','rpki','5 1'); + INSERT INTO sqlite_stat1 VALUES('NATION','bootleg_nni','25 1'); + INSERT INTO sqlite_stat1 VALUES('NATION','nrki','25 5'); + INSERT INTO sqlite_stat1 VALUES('NATION','npki','25 1'); + ANALYZE sqlite_master; +} {} + +do_test tpch01-1.1 { + unset -nocomplain ::eqpres + set ::eqpres [db eval {EXPLAIN QUERY PLAN + select + o_year, + sum(case + when nation = 'EGYPT' then volume + else 0 + end) / sum(volume) as mkt_share + from + ( + select + strftime('%Y', o_orderdate) as o_year, + l_extendedprice * (1 - l_discount) as volume, + n2.n_name as nation + from + part, + supplier, + lineitem, + orders, + customer, + nation n1, + nation n2, + region + where + p_partkey = l_partkey + and s_suppkey = l_suppkey + and l_orderkey = o_orderkey + and o_custkey = c_custkey + and c_nationkey = n1.n_nationkey + and n1.n_regionkey = r_regionkey + and r_name = 'MIDDLE EAST' + and s_nationkey = n2.n_nationkey + and o_orderdate between '1995-01-01' and '1996-12-31' + and p_type = 'LARGE PLATED STEEL' + ) as all_nations + group by + o_year + order by + o_year;}] + set ::eqpres +} {/0 0 0 {SEARCH TABLE part USING INDEX bootleg_pti .P_TYPE=..} 0 1 2 {SEARCH TABLE lineitem USING INDEX lpki2 .L_PARTKEY=..}.*/} +do_test tpch01-1.1b { + set ::eqpres +} {/.* customer .* nation AS n1 .* nation AS n2 .*/} + +do_eqp_test tpch01-1.2 { +select + c_custkey, c_name, sum(l_extendedprice * (1 - l_discount)) as revenue, + c_acctbal, n_name, c_address, c_phone, c_comment +from + customer, orders, lineitem, nation +where + c_custkey = o_custkey and l_orderkey = o_orderkey + and o_orderdate >= '1994-08-01' and o_orderdate < date('1994-08-01', '+3 month') + and l_returnflag = 'R' and c_nationkey = n_nationkey +group by + c_custkey, c_name, c_acctbal, c_phone, n_name, c_address, c_comment +order by + revenue desc; +} {0 0 1 {SEARCH TABLE orders USING INDEX odi (O_ORDERDATE>? AND O_ORDERDATE0} + } 1 + ifcapable pager_pragmas { + do_test trans-9.$i.5-$cnt { + expr {$sqlite_fullsync_count>0} + } [expr {$i%2==0}] + } else { + do_test trans-9.$i.5-$cnt { + expr {$sqlite_fullsync_count==0} + } {1} + } + } + } + + wal_check_journal_mode trans-9.$i.6-$cnt + set ::pager_old_format 0 +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trans2.test b/components/external/SQLite-3.8.1/test/trans2.test new file mode 100644 index 0000000000000000000000000000000000000000..cfd3e67736c258d73d62a89c060d238a4a92bc7b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trans2.test @@ -0,0 +1,232 @@ +# 2008 August 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this script is transactions +# +# $Id: trans2.test,v 1.1 2008/08/27 18:56:36 drh Exp $ +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# A procedure to scramble the elements of list $inlist into a random order. +# +proc scramble {inlist} { + set y {} + foreach x $inlist { + lappend y [list [expr {rand()}] $x] + } + set y [lsort $y] + set outlist {} + foreach x $y { + lappend outlist [lindex $x 1] + } + return $outlist +} + +# Generate a UUID using randomness. +# +expr srand(1) +proc random_uuid {} { + set u {} + for {set i 0} {$i<5} {incr i} { + append u [format %06x [expr {int(rand()*16777216)}]] + } + return $u +} + +# Compute hashes on the u1 and u2 fields of the sample data. +# +proc hash1 {} { + global data + set x "" + foreach rec [lsort -integer -index 0 $data] { + append x [lindex $rec 1] + } + return [md5 $x] +} +proc hash2 {} { + global data + set x "" + foreach rec [lsort -integer -index 0 $data] { + append x [lindex $rec 3] + } + return [md5 $x] +} + +# Create the initial data set +# +unset -nocomplain data i max_rowid todel n rec max1 id origres newres +unset -nocomplain inssql modsql s j z +set data {} +for {set i 0} {$i<400} {incr i} { + set rec [list $i [random_uuid] [expr {int(rand()*5000)+1000}] [random_uuid]] + lappend data $rec +} +set max_rowid [expr {$i-1}] + +# Create the T1 table used to hold test data. Populate that table with +# the initial data set and check hashes to make sure everything is correct. +# +do_test trans2-1.1 { + execsql { + PRAGMA cache_size=100; + CREATE TABLE t1( + id INTEGER PRIMARY KEY, + u1 TEXT UNIQUE, + z BLOB NOT NULL, + u2 TEXT UNIQUE + ); + } + foreach rec [scramble $data] { + foreach {id u1 z u2} $rec break + db eval {INSERT INTO t1 VALUES($id,$u1,zeroblob($z),$u2)} + } + db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id} +} [list [hash1] [hash2]] + +# Repeat the main test loop multiple times. +# +for {set i 2} {$i<=30} {incr i} { + # Delete one row out of every 10 in the database. This will add + # many pages to the freelist. + # + set todel {} + set n [expr {[llength $data]/10}] + set data [scramble $data] + foreach rec [lrange $data 0 $n] { + lappend todel [lindex $rec 0] + } + set data [lrange $data [expr {$n+1}] end] + set max1 [lindex [lindex $data 0] 0] + foreach rec $data { + set id [lindex $rec 0] + if {$id>$max1} {set max1 $id} + } + set origres [list [hash1] [hash2]] + do_test trans2-$i.1 { + db eval "DELETE FROM t1 WHERE id IN ([join $todel ,])" + db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id} + } $origres + integrity_check trans2-$i.2 + + # Begin a transaction and insert many new records. + # + set newdata {} + foreach id $todel { + set rec [list $id [random_uuid] \ + [expr {int(rand()*5000)+1000}] [random_uuid]] + lappend newdata $rec + lappend data $rec + } + for {set j 1} {$j<50} {incr j} { + set id [expr {$max_rowid+$j}] + lappend todel $id + set rec [list $id [random_uuid] \ + [expr {int(rand()*5000)+1000}] [random_uuid]] + lappend newdata $rec + lappend data $rec + } + set max_rowid [expr {$max_rowid+$j-1}] + set modsql {} + set inssql {} + set newres [list [hash1] [hash2]] + do_test trans2-$i.3 { + db eval BEGIN + foreach rec [scramble $newdata] { + foreach {id u1 z u2} $rec break + set s "INSERT INTO t1 VALUES($id,'$u1',zeroblob($z),'$u2');" + append modsql $s\n + append inssql $s\n + db eval $s + } + db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id} + } $newres + integrity_check trans2-$i.4 + + # Do a large update that aborts do to a constraint failure near + # the end. This stresses the statement journal mechanism. + # + do_test trans2-$i.10 { + catchsql { + UPDATE t1 SET u1=u1||'x', + z = CASE WHEN id<$max_rowid + THEN zeroblob((random()&65535)%5000 + 1000) END; + } + } {1 {t1.z may not be NULL}} + do_test trans2-$i.11 { + db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id} + } $newres + + # Delete all of the newly inserted records. Verify that the database + # is back to its original state. + # + do_test trans2-$i.20 { + set s "DELETE FROM t1 WHERE id IN ([join $todel ,]);" + append modsql $s\n + db eval $s + db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id} + } $origres + + # Do another large update that aborts do to a constraint failure near + # the end. This stresses the statement journal mechanism. + # + do_test trans2-$i.30 { + catchsql { + UPDATE t1 SET u1=u1||'x', + z = CASE WHEN id<$max1 + THEN zeroblob((random()&65535)%5000 + 1000) END; + } + } {1 {t1.z may not be NULL}} + do_test trans2-$i.31 { + db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id} + } $origres + + # Redo the inserts + # + do_test trans2-$i.40 { + db eval $inssql + append modsql $inssql + db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id} + } $newres + + # Rollback the transaction. Verify that the content is restored. + # + do_test trans2-$i.90 { + db eval ROLLBACK + db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id} + } $origres + integrity_check trans2-$i.91 + + # Repeat all the changes, but this time commit. + # + do_test trans2-$i.92 { + db eval BEGIN + catchsql { + UPDATE t1 SET u1=u1||'x', + z = CASE WHEN id<$max1 + THEN zeroblob((random()&65535)%5000 + 1000) END; + } + db eval $modsql + catchsql { + UPDATE t1 SET u1=u1||'x', + z = CASE WHEN id<$max1 + THEN zeroblob((random()&65535)%5000 + 1000) END; + } + db eval COMMIT + db eval {SELECT md5sum(u1), md5sum(u2) FROM t1 ORDER BY id} + } $newres + integrity_check trans2-$i.93 +} + +unset -nocomplain data i max_rowid todel n rec max1 id origres newres +unset -nocomplain inssql modsql s j z +finish_test diff --git a/components/external/SQLite-3.8.1/test/trans3.test b/components/external/SQLite-3.8.1/test/trans3.test new file mode 100644 index 0000000000000000000000000000000000000000..d5b316bec8e8a79edf24762c20e333b34abd48e6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trans3.test @@ -0,0 +1,76 @@ +# 2008 November 3 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements regression tests for SQLite library. The +# focus of this script is the response of COMMIT and ROLLBACK when +# statements are still pending. +# +# $Id: trans3.test,v 1.2 2008/11/05 16:37:35 drh Exp $ +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +unset -nocomplain ecode + +do_test trans3-1.1 { + db eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + SELECT * FROM t1; + } +} {1 2 3} +do_test trans3-1.2 { + db eval BEGIN + db eval {INSERT INTO t1 VALUES(4);} + set ::ecode {} + set x [catch { + db eval {SELECT * FROM t1 LIMIT 1} { + if {[catch {db eval COMMIT} errmsg]} { + set ::ecode [sqlite3_extended_errcode db] + error $errmsg + } + } + } errmsg] + lappend x $errmsg +} {0 {}} +do_test trans3-1.3 { + set ::ecode +} {} +do_test trans3-1.3.1 { + sqlite3_get_autocommit db +} 1 +do_test trans3-1.4 { + db eval {SELECT * FROM t1} +} {1 2 3 4} +do_test trans3-1.5 { + db eval BEGIN + db eval {INSERT INTO t1 VALUES(5);} + set ::ecode {} + set x [catch { + db eval {SELECT * FROM t1} { + if {[catch {db eval ROLLBACK} errmsg]} { + set ::ecode [sqlite3_extended_errcode db] + error $errmsg + } + } + } errmsg] + lappend x $errmsg +} {1 {abort due to ROLLBACK}} +do_test trans3-1.6 { + set ::ecode +} {} +do_test trans3-1.7 { + db eval {SELECT * FROM t1} +} {1 2 3 4} +unset -nocomplain ecode + +finish_test diff --git a/components/external/SQLite-3.8.1/test/transitive1.test b/components/external/SQLite-3.8.1/test/transitive1.test new file mode 100644 index 0000000000000000000000000000000000000000..4cf439bb45692a06505da13c7c11deb0848e2949 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/transitive1.test @@ -0,0 +1,105 @@ +# 2013 April 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file implements regression tests for SQLite library. The +# focus of this script is testing of transitive WHERE clause constraints +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_execsql_test transitive1-100 { + CREATE TABLE t1(a TEXT, b TEXT, c TEXT COLLATE NOCASE); + INSERT INTO t1 VALUES('abc','abc','Abc'); + INSERT INTO t1 VALUES('def','def','def'); + INSERT INTO t1 VALUES('ghi','ghi','GHI'); + CREATE INDEX t1a1 ON t1(a); + CREATE INDEX t1a2 ON t1(a COLLATE nocase); + + SELECT * FROM t1 WHERE a=b AND c=b AND c='DEF'; +} {def def def} +do_execsql_test transitive1-110 { + SELECT * FROM t1 WHERE a=b AND c=b AND c>='DEF' ORDER BY +a; +} {def def def ghi ghi GHI} +do_execsql_test transitive1-120 { + SELECT * FROM t1 WHERE a=b AND c=b AND c<='DEF' ORDER BY +a; +} {abc abc Abc def def def} + +do_execsql_test transitive1-200 { + CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT); + INSERT INTO t2 VALUES(100,100,100); + INSERT INTO t2 VALUES(20,20,20); + INSERT INTO t2 VALUES(3,3,3); + + SELECT * FROM t2 WHERE a=b AND c=b AND c=20; +} {20 20 20} +do_execsql_test transitive1-210 { + SELECT * FROM t2 WHERE a=b AND c=b AND c>=20 ORDER BY +a; +} {3 3 3 20 20 20} +do_execsql_test transitive1-220 { + SELECT * FROM t2 WHERE a=b AND c=b AND c<=20 ORDER BY +a; +} {20 20 20 100 100 100} + +# Test cases for ticket [[d805526eae253103] 2013-07-08 +# "Incorrect join result or assertion fault due to transitive constraints" +# +do_execsql_test transitive1-300 { + CREATE TABLE t301(w INTEGER PRIMARY KEY, x); + CREATE TABLE t302(y INTEGER UNIQUE, z); + INSERT INTO t301 VALUES(1,2),(3,4),(5,6); + INSERT INTO t302 VALUES(1,3),(3,6),(5,7); + SELECT * + FROM t301 CROSS JOIN t302 + WHERE w=y AND y IS NOT NULL + ORDER BY +w; +} {1 2 1 3 3 4 3 6 5 6 5 7} +do_execsql_test transitive1-301 { + SELECT * + FROM t301 CROSS JOIN t302 + WHERE w=y AND y IS NOT NULL + ORDER BY w; +} {1 2 1 3 3 4 3 6 5 6 5 7} +do_execsql_test transitive1-310 { + SELECT * + FROM t301 CROSS JOIN t302 ON w=y + WHERE y>1 + ORDER BY +w +} {3 4 3 6 5 6 5 7} +do_execsql_test transitive1-311 { + SELECT * + FROM t301 CROSS JOIN t302 ON w=y + WHERE y>1 + ORDER BY w +} {3 4 3 6 5 6 5 7} +do_execsql_test transitive1-312 { + SELECT * + FROM t301 CROSS JOIN t302 ON w=y + WHERE y>1 + ORDER BY w DESC +} {5 6 5 7 3 4 3 6} +do_execsql_test transitive1-320 { + SELECT * + FROM t301 CROSS JOIN t302 ON w=y + WHERE y BETWEEN 2 AND 4; +} {3 4 3 6} +do_execsql_test transitive1-331 { + SELECT * + FROM t301 CROSS JOIN t302 ON w=y + WHERE y BETWEEN 1 AND 4 + ORDER BY w; +} {1 2 1 3 3 4 3 6} +do_execsql_test transitive1-332 { + SELECT * + FROM t301 CROSS JOIN t302 ON w=y + WHERE y BETWEEN 1 AND 4 + ORDER BY w DESC; +} {3 4 3 6 1 2 1 3} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trigger1.test b/components/external/SQLite-3.8.1/test/trigger1.test new file mode 100644 index 0000000000000000000000000000000000000000..1ebe12c89b58ea2e43424f18927310ce81a7aa7b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trigger1.test @@ -0,0 +1,715 @@ +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests creating and dropping triggers, and interaction thereof +# with the database COMMIT/ROLLBACK logic. +# +# 1. CREATE and DROP TRIGGER tests +# trigger1-1.1: Error if table does not exist +# trigger1-1.2: Error if trigger already exists +# trigger1-1.3: Created triggers are deleted if the transaction is rolled back +# trigger1-1.4: DROP TRIGGER removes trigger +# trigger1-1.5: Dropped triggers are restored if the transaction is rolled back +# trigger1-1.6: Error if dropped trigger doesn't exist +# trigger1-1.7: Dropping the table automatically drops all triggers +# trigger1-1.8: A trigger created on a TEMP table is not inserted into sqlite_master +# trigger1-1.9: Ensure that we cannot create a trigger on sqlite_master +# trigger1-1.10: +# trigger1-1.11: +# trigger1-1.12: Ensure that INSTEAD OF triggers cannot be created on tables +# trigger1-1.13: Ensure that AFTER triggers cannot be created on views +# trigger1-1.14: Ensure that BEFORE triggers cannot be created on views +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !trigger||!compound { + finish_test + return +} + +do_test trigger1-1.1.1 { + catchsql { + CREATE TRIGGER trig UPDATE ON no_such_table BEGIN + SELECT * from sqlite_master; + END; + } +} {1 {no such table: main.no_such_table}} + +ifcapable tempdb { + do_test trigger1-1.1.2 { + catchsql { + CREATE TEMP TRIGGER trig UPDATE ON no_such_table BEGIN + SELECT * from sqlite_master; + END; + } + } {1 {no such table: no_such_table}} +} + +execsql { + CREATE TABLE t1(a); +} +do_test trigger1-1.1.3 { + catchsql { + CREATE TRIGGER trig UPDATE ON t1 FOR EACH STATEMENT BEGIN + SELECT * FROM sqlite_master; + END; + } +} {1 {near "STATEMENT": syntax error}} +execsql { + CREATE TRIGGER tr1 INSERT ON t1 BEGIN + INSERT INTO t1 values(1); + END; +} +do_test trigger1-1.2.0 { + catchsql { + CREATE TRIGGER IF NOT EXISTS tr1 DELETE ON t1 BEGIN + SELECT * FROM sqlite_master; + END + } +} {0 {}} +do_test trigger1-1.2.1 { + catchsql { + CREATE TRIGGER tr1 DELETE ON t1 BEGIN + SELECT * FROM sqlite_master; + END + } +} {1 {trigger tr1 already exists}} +do_test trigger1-1.2.2 { + catchsql { + CREATE TRIGGER "tr1" DELETE ON t1 BEGIN + SELECT * FROM sqlite_master; + END + } +} {1 {trigger "tr1" already exists}} +do_test trigger1-1.2.3 { + catchsql { + CREATE TRIGGER [tr1] DELETE ON t1 BEGIN + SELECT * FROM sqlite_master; + END + } +} {1 {trigger [tr1] already exists}} + +do_test trigger1-1.3 { + catchsql { + BEGIN; + CREATE TRIGGER tr2 INSERT ON t1 BEGIN + SELECT * from sqlite_master; END; + ROLLBACK; + CREATE TRIGGER tr2 INSERT ON t1 BEGIN + SELECT * from sqlite_master; END; + } +} {0 {}} + +do_test trigger1-1.4 { + catchsql { + DROP TRIGGER IF EXISTS tr1; + CREATE TRIGGER tr1 DELETE ON t1 BEGIN + SELECT * FROM sqlite_master; + END + } +} {0 {}} + +do_test trigger1-1.5 { + execsql { + BEGIN; + DROP TRIGGER tr2; + ROLLBACK; + DROP TRIGGER tr2; + } +} {} + +do_test trigger1-1.6.1 { + catchsql { + DROP TRIGGER IF EXISTS biggles; + } +} {0 {}} + +do_test trigger1-1.6.2 { + catchsql { + DROP TRIGGER biggles; + } +} {1 {no such trigger: biggles}} + +do_test trigger1-1.7 { + catchsql { + DROP TABLE t1; + DROP TRIGGER tr1; + } +} {1 {no such trigger: tr1}} + +ifcapable tempdb { + execsql { + CREATE TEMP TABLE temp_table(a); + } + do_test trigger1-1.8 { + execsql { + CREATE TRIGGER temp_trig UPDATE ON temp_table BEGIN + SELECT * from sqlite_master; + END; + SELECT count(*) FROM sqlite_master WHERE name = 'temp_trig'; + } + } {0} +} + +do_test trigger1-1.9 { + catchsql { + CREATE TRIGGER tr1 AFTER UPDATE ON sqlite_master BEGIN + SELECT * FROM sqlite_master; + END; + } +} {1 {cannot create trigger on system table}} + +# Check to make sure that a DELETE statement within the body of +# a trigger does not mess up the DELETE that caused the trigger to +# run in the first place. +# +do_test trigger1-1.10 { + execsql { + create table t1(a,b); + insert into t1 values(1,'a'); + insert into t1 values(2,'b'); + insert into t1 values(3,'c'); + insert into t1 values(4,'d'); + create trigger r1 after delete on t1 for each row begin + delete from t1 WHERE a=old.a+2; + end; + delete from t1 where a=1 OR a=3; + select * from t1; + drop table t1; + } +} {2 b 4 d} + +do_test trigger1-1.11 { + execsql { + create table t1(a,b); + insert into t1 values(1,'a'); + insert into t1 values(2,'b'); + insert into t1 values(3,'c'); + insert into t1 values(4,'d'); + create trigger r1 after update on t1 for each row begin + delete from t1 WHERE a=old.a+2; + end; + update t1 set b='x-' || b where a=1 OR a=3; + select * from t1; + drop table t1; + } +} {1 x-a 2 b 4 d} + +# Ensure that we cannot create INSTEAD OF triggers on tables +do_test trigger1-1.12 { + catchsql { + create table t1(a,b); + create trigger t1t instead of update on t1 for each row begin + delete from t1 WHERE a=old.a+2; + end; + } +} {1 {cannot create INSTEAD OF trigger on table: t1}} + +ifcapable view { +# Ensure that we cannot create BEFORE triggers on views +do_test trigger1-1.13 { + catchsql { + create view v1 as select * from t1; + create trigger v1t before update on v1 for each row begin + delete from t1 WHERE a=old.a+2; + end; + } +} {1 {cannot create BEFORE trigger on view: v1}} +# Ensure that we cannot create AFTER triggers on views +do_test trigger1-1.14 { + catchsql { + drop view v1; + create view v1 as select * from t1; + create trigger v1t AFTER update on v1 for each row begin + delete from t1 WHERE a=old.a+2; + end; + } +} {1 {cannot create AFTER trigger on view: v1}} +} ;# ifcapable view + +# Check for memory leaks in the trigger parser +# +do_test trigger1-2.1 { + catchsql { + CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN + SELECT * FROM; -- Syntax error + END; + } +} {1 {near ";": syntax error}} +do_test trigger1-2.2 { + catchsql { + CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN + SELECT * FROM t1; + SELECT * FROM; -- Syntax error + END; + } +} {1 {near ";": syntax error}} + +# Create a trigger that refers to a table that might not exist. +# +ifcapable tempdb { + do_test trigger1-3.1 { + execsql { + CREATE TEMP TABLE t2(x,y); + } + catchsql { + CREATE TRIGGER r1 AFTER INSERT ON t1 BEGIN + INSERT INTO t2 VALUES(NEW.a,NEW.b); + END; + } + } {0 {}} + do_test trigger1-3.2 { + catchsql { + INSERT INTO t1 VALUES(1,2); + SELECT * FROM t2; + } + } {1 {no such table: main.t2}} + do_test trigger1-3.3 { + db close + set rc [catch {sqlite3 db test.db} err] + if {$rc} {lappend rc $err} + set rc + } {0} + do_test trigger1-3.4 { + catchsql { + INSERT INTO t1 VALUES(1,2); + SELECT * FROM t2; + } + } {1 {no such table: main.t2}} + do_test trigger1-3.5 { + catchsql { + CREATE TEMP TABLE t2(x,y); + INSERT INTO t1 VALUES(1,2); + SELECT * FROM t2; + } + } {1 {no such table: main.t2}} + do_test trigger1-3.6.1 { + catchsql { + DROP TRIGGER r1; + CREATE TEMP TRIGGER r1 AFTER INSERT ON t1 BEGIN + INSERT INTO t2 VALUES(NEW.a,NEW.b), (NEW.b*100, NEW.a*100); + END; + INSERT INTO t1 VALUES(1,2); + SELECT * FROM t2; + } + } {0 {1 2 200 100}} + do_test trigger1-3.6.2 { + catchsql { + DROP TRIGGER r1; + DELETE FROM t1; + DELETE FROM t2; + CREATE TEMP TRIGGER r1 AFTER INSERT ON t1 BEGIN + INSERT INTO t2 VALUES(NEW.a,NEW.b); + END; + INSERT INTO t1 VALUES(1,2); + SELECT * FROM t2; + } + } {0 {1 2}} + do_test trigger1-3.7 { + execsql { + DROP TABLE t2; + CREATE TABLE t2(x,y); + SELECT * FROM t2; + } + } {} + + # There are two versions of trigger1-3.8 and trigger1-3.9. One that uses + # compound SELECT statements, and another that does not. + ifcapable compound { + do_test trigger1-3.8 { + execsql { + INSERT INTO t1 VALUES(3,4); + SELECT * FROM t1 UNION ALL SELECT * FROM t2; + } + } {1 2 3 4 3 4} + do_test trigger1-3.9 { + db close + sqlite3 db test.db + execsql { + INSERT INTO t1 VALUES(5,6); + SELECT * FROM t1 UNION ALL SELECT * FROM t2; + } + } {1 2 3 4 5 6 3 4} + } ;# ifcapable compound + ifcapable !compound { + do_test trigger1-3.8 { + execsql { + INSERT INTO t1 VALUES(3,4); + SELECT * FROM t1; + SELECT * FROM t2; + } + } {1 2 3 4 3 4} + do_test trigger1-3.9 { + db close + sqlite3 db test.db + execsql { + INSERT INTO t1 VALUES(5,6); + SELECT * FROM t1; + SELECT * FROM t2; + } + } {1 2 3 4 5 6 3 4} + } ;# ifcapable !compound + + do_test trigger1-4.1 { + execsql { + CREATE TEMP TRIGGER r1 BEFORE INSERT ON t1 BEGIN + INSERT INTO t2 VALUES(NEW.a,NEW.b); + END; + INSERT INTO t1 VALUES(7,8); + SELECT * FROM t2; + } + } {3 4 7 8} + do_test trigger1-4.2 { + sqlite3 db2 test.db + execsql { + INSERT INTO t1 VALUES(9,10); + } db2; + db2 close + execsql { + SELECT * FROM t2; + } + } {3 4 7 8} + do_test trigger1-4.3 { + execsql { + DROP TABLE t1; + SELECT * FROM t2; + }; + } {3 4 7 8} + do_test trigger1-4.4 { + db close + sqlite3 db test.db + execsql { + SELECT * FROM t2; + }; + } {3 4 7 8} +} else { + execsql { + CREATE TABLE t2(x,y); + DROP TABLE t1; + INSERT INTO t2 VALUES(3, 4); + INSERT INTO t2 VALUES(7, 8); + } +} + + +integrity_check trigger1-5.1 + +# Create a trigger with the same name as a table. Make sure the +# trigger works. Then drop the trigger. Make sure the table is +# still there. +# +set view_v1 {} +ifcapable view { + set view_v1 {view v1} +} +do_test trigger1-6.1 { + execsql {SELECT type, name FROM sqlite_master} +} [concat $view_v1 {table t2}] +do_test trigger1-6.2 { + execsql { + CREATE TRIGGER t2 BEFORE DELETE ON t2 BEGIN + SELECT RAISE(ABORT,'deletes are not permitted'); + END; + SELECT type, name FROM sqlite_master; + } +} [concat $view_v1 {table t2 trigger t2}] +do_test trigger1-6.3 { + catchsql {DELETE FROM t2} +} {1 {deletes are not permitted}} +verify_ex_errcode trigger1-6.3b SQLITE_CONSTRAINT_TRIGGER +do_test trigger1-6.4 { + execsql {SELECT * FROM t2} +} {3 4 7 8} +do_test trigger1-6.5 { + db close + sqlite3 db test.db + execsql {SELECT type, name FROM sqlite_master} +} [concat $view_v1 {table t2 trigger t2}] +do_test trigger1-6.6 { + execsql { + DROP TRIGGER t2; + SELECT type, name FROM sqlite_master; + } +} [concat $view_v1 {table t2}] +do_test trigger1-6.7 { + execsql {SELECT * FROM t2} +} {3 4 7 8} +do_test trigger1-6.8 { + db close + sqlite3 db test.db + execsql {SELECT * FROM t2} +} {3 4 7 8} + +integrity_check trigger1-7.1 + +# Check to make sure the name of a trigger can be quoted so that keywords +# can be used as trigger names. Ticket #468 +# +do_test trigger1-8.1 { + execsql { + CREATE TRIGGER 'trigger' AFTER INSERT ON t2 BEGIN SELECT 1; END; + SELECT name FROM sqlite_master WHERE type='trigger'; + } +} {trigger} +do_test trigger1-8.2 { + execsql { + DROP TRIGGER 'trigger'; + SELECT name FROM sqlite_master WHERE type='trigger'; + } +} {} +do_test trigger1-8.3 { + execsql { + CREATE TRIGGER "trigger" AFTER INSERT ON t2 BEGIN SELECT 1; END; + SELECT name FROM sqlite_master WHERE type='trigger'; + } +} {trigger} +do_test trigger1-8.4 { + execsql { + DROP TRIGGER "trigger"; + SELECT name FROM sqlite_master WHERE type='trigger'; + } +} {} +do_test trigger1-8.5 { + execsql { + CREATE TRIGGER [trigger] AFTER INSERT ON t2 BEGIN SELECT 1; END; + SELECT name FROM sqlite_master WHERE type='trigger'; + } +} {trigger} +do_test trigger1-8.6 { + execsql { + DROP TRIGGER [trigger]; + SELECT name FROM sqlite_master WHERE type='trigger'; + } +} {} + +ifcapable conflict { + # Make sure REPLACE works inside of triggers. + # + # There are two versions of trigger1-9.1 and trigger1-9.2. One that uses + # compound SELECT statements, and another that does not. + ifcapable compound { + do_test trigger1-9.1 { + execsql { + CREATE TABLE t3(a,b); + CREATE TABLE t4(x UNIQUE, b); + CREATE TRIGGER r34 AFTER INSERT ON t3 BEGIN + REPLACE INTO t4 VALUES(new.a,new.b); + END; + INSERT INTO t3 VALUES(1,2); + SELECT * FROM t3 UNION ALL SELECT 99, 99 UNION ALL SELECT * FROM t4; + } + } {1 2 99 99 1 2} + do_test trigger1-9.2 { + execsql { + INSERT INTO t3 VALUES(1,3); + SELECT * FROM t3 UNION ALL SELECT 99, 99 UNION ALL SELECT * FROM t4; + } + } {1 2 1 3 99 99 1 3} + } else { + do_test trigger1-9.1 { + execsql { + CREATE TABLE t3(a,b); + CREATE TABLE t4(x UNIQUE, b); + CREATE TRIGGER r34 AFTER INSERT ON t3 BEGIN + REPLACE INTO t4 VALUES(new.a,new.b); + END; + INSERT INTO t3 VALUES(1,2); + SELECT * FROM t3; SELECT 99, 99; SELECT * FROM t4; + } + } {1 2 99 99 1 2} + do_test trigger1-9.2 { + execsql { + INSERT INTO t3 VALUES(1,3); + SELECT * FROM t3; SELECT 99, 99; SELECT * FROM t4; + } + } {1 2 1 3 99 99 1 3} + } + execsql { + DROP TABLE t3; + DROP TABLE t4; + } +} + + +# Ticket #764. At one stage TEMP triggers would fail to re-install when the +# schema was reloaded. The following tests ensure that TEMP triggers are +# correctly re-installed. +# +# Also verify that references within trigger programs are resolved at +# statement compile time, not trigger installation time. This means, for +# example, that you can drop and re-create tables referenced by triggers. +ifcapable tempdb&&attach { + do_test trigger1-10.0 { + forcedelete test2.db + forcedelete test2.db-journal + execsql { + ATTACH 'test2.db' AS aux; + } + } {} + do_test trigger1-10.1 { + execsql { + CREATE TABLE main.t4(a, b, c); + CREATE TABLE temp.t4(a, b, c); + CREATE TABLE aux.t4(a, b, c); + CREATE TABLE insert_log(db, a, b, c); + } + } {} + do_test trigger1-10.2 { + execsql { + CREATE TEMP TRIGGER trig1 AFTER INSERT ON main.t4 BEGIN + INSERT INTO insert_log VALUES('main', new.a, new.b, new.c); + END; + CREATE TEMP TRIGGER trig2 AFTER INSERT ON temp.t4 BEGIN + INSERT INTO insert_log VALUES('temp', new.a, new.b, new.c); + END; + CREATE TEMP TRIGGER trig3 AFTER INSERT ON aux.t4 BEGIN + INSERT INTO insert_log VALUES('aux', new.a, new.b, new.c); + END; + } + } {} + do_test trigger1-10.3 { + execsql { + INSERT INTO main.t4 VALUES(1, 2, 3); + INSERT INTO temp.t4 VALUES(4, 5, 6); + INSERT INTO aux.t4 VALUES(7, 8, 9); + } + } {} + do_test trigger1-10.4 { + execsql { + SELECT * FROM insert_log; + } + } {main 1 2 3 temp 4 5 6 aux 7 8 9} + do_test trigger1-10.5 { + execsql { + BEGIN; + INSERT INTO main.t4 VALUES(1, 2, 3); + INSERT INTO temp.t4 VALUES(4, 5, 6); + INSERT INTO aux.t4 VALUES(7, 8, 9); + ROLLBACK; + } + } {} + do_test trigger1-10.6 { + execsql { + SELECT * FROM insert_log; + } + } {main 1 2 3 temp 4 5 6 aux 7 8 9} + do_test trigger1-10.7 { + execsql { + DELETE FROM insert_log; + INSERT INTO main.t4 VALUES(11, 12, 13); + INSERT INTO temp.t4 VALUES(14, 15, 16); + INSERT INTO aux.t4 VALUES(17, 18, 19); + } + } {} + do_test trigger1-10.8 { + execsql { + SELECT * FROM insert_log; + } + } {main 11 12 13 temp 14 15 16 aux 17 18 19} + do_test trigger1-10.9 { + # Drop and re-create the insert_log table in a different database. Note + # that we can change the column names because the trigger programs don't + # use them explicitly. + execsql { + DROP TABLE insert_log; + CREATE TABLE aux.insert_log(db, d, e, f); + } + } {} + do_test trigger1-10.10 { + execsql { + INSERT INTO main.t4 VALUES(21, 22, 23); + INSERT INTO temp.t4 VALUES(24, 25, 26); + INSERT INTO aux.t4 VALUES(27, 28, 29); + } + } {} + do_test trigger1-10.11 { + execsql { + SELECT * FROM insert_log; + } + } {main 21 22 23 temp 24 25 26 aux 27 28 29} +} + +do_test trigger1-11.1 { + catchsql {SELECT raise(abort,'message');} +} {1 {RAISE() may only be used within a trigger-program}} + +do_test trigger1-15.1 { + execsql { + CREATE TABLE tA(a INTEGER PRIMARY KEY, b, c); + CREATE TRIGGER tA_trigger BEFORE UPDATE ON "tA" BEGIN SELECT 1; END; + INSERT INTO tA VALUES(1, 2, 3); + } + catchsql { UPDATE tA SET a = 'abc' } +} {1 {datatype mismatch}} +do_test trigger1-15.2 { + catchsql { INSERT INTO tA VALUES('abc', 2, 3) } +} {1 {datatype mismatch}} + +# Ticket #3947: Do not allow qualified table names on INSERT, UPDATE, and +# DELETE statements within triggers. Actually, this has never been allowed +# by the grammar. But the error message is confusing: one simply gets a +# "syntax error". That has now been changed to give a full error message. +# +do_test trigger1-16.1 { + db eval { + CREATE TABLE t16(a,b,c); + CREATE INDEX t16a ON t16(a); + CREATE INDEX t16b ON t16(b); + } + catchsql { + CREATE TRIGGER main.t16err1 AFTER INSERT ON tA BEGIN + INSERT INTO main.t16 VALUES(1,2,3); + END; + } +} {1 {qualified table names are not allowed on INSERT, UPDATE, and DELETE statements within triggers}} +do_test trigger1-16.2 { + catchsql { + CREATE TRIGGER main.t16err2 AFTER INSERT ON tA BEGIN + UPDATE main.t16 SET rowid=rowid+1; + END; + } +} {1 {qualified table names are not allowed on INSERT, UPDATE, and DELETE statements within triggers}} +do_test trigger1-16.3 { + catchsql { + CREATE TRIGGER main.t16err3 AFTER INSERT ON tA BEGIN + DELETE FROM main.t16; + END; + } +} {1 {qualified table names are not allowed on INSERT, UPDATE, and DELETE statements within triggers}} +do_test trigger1-16.4 { + catchsql { + CREATE TRIGGER main.t16err4 AFTER INSERT ON tA BEGIN + UPDATE t16 NOT INDEXED SET rowid=rowid+1; + END; + } +} {1 {the NOT INDEXED clause is not allowed on UPDATE or DELETE statements within triggers}} +do_test trigger1-16.5 { + catchsql { + CREATE TRIGGER main.t16err5 AFTER INSERT ON tA BEGIN + UPDATE t16 INDEXED BY t16a SET rowid=rowid+1 WHERE a=1; + END; + } +} {1 {the INDEXED BY clause is not allowed on UPDATE or DELETE statements within triggers}} +do_test trigger1-16.6 { + catchsql { + CREATE TRIGGER main.t16err6 AFTER INSERT ON tA BEGIN + DELETE FROM t16 NOT INDEXED WHERE a=123; + END; + } +} {1 {the NOT INDEXED clause is not allowed on UPDATE or DELETE statements within triggers}} +do_test trigger1-16.7 { + catchsql { + CREATE TRIGGER main.t16err7 AFTER INSERT ON tA BEGIN + DELETE FROM t16 INDEXED BY t16a WHERE a=123; + END; + } +} {1 {the INDEXED BY clause is not allowed on UPDATE or DELETE statements within triggers}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trigger2.test b/components/external/SQLite-3.8.1/test/trigger2.test new file mode 100644 index 0000000000000000000000000000000000000000..b4b922a5ee939f09481f24979a46a255b3efd9e6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trigger2.test @@ -0,0 +1,759 @@ +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Regression testing of FOR EACH ROW table triggers +# +# 1. Trigger execution order tests. +# These tests ensure that BEFORE and AFTER triggers are fired at the correct +# times relative to each other and the triggering statement. +# +# trigger2-1.1.*: ON UPDATE trigger execution model. +# trigger2-1.2.*: DELETE trigger execution model. +# trigger2-1.3.*: INSERT trigger execution model. +# +# 2. Trigger program execution tests. +# These tests ensure that trigger programs execute correctly (ie. that a +# trigger program can correctly execute INSERT, UPDATE, DELETE * SELECT +# statements, and combinations thereof). +# +# 3. Selective trigger execution +# This tests that conditional triggers (ie. UPDATE OF triggers and triggers +# with WHEN clauses) are fired only fired when they are supposed to be. +# +# trigger2-3.1: UPDATE OF triggers +# trigger2-3.2: WHEN clause +# +# 4. Cascaded trigger execution +# Tests that trigger-programs may cause other triggers to fire. Also that a +# trigger-program is never executed recursively. +# +# trigger2-4.1: Trivial cascading trigger +# trigger2-4.2: Trivial recursive trigger handling +# +# 5. Count changes behaviour. +# Verify that rows altered by triggers are not included in the return value +# of the "count changes" interface. +# +# 6. ON CONFLICT clause handling +# trigger2-6.1[a-f]: INSERT statements +# trigger2-6.2[a-f]: UPDATE statements +# +# 7. & 8. Triggers on views fire correctly. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +# The tests in this file were written before SQLite supported recursive +# trigger invocation, and some tests depend on that to pass. So disable +# recursive triggers for this file. +catchsql { pragma recursive_triggers = off } + +# 1. +ifcapable subquery { + set ii 0 + set tbl_definitions [list \ + {CREATE TABLE tbl (a, b);} \ + {CREATE TABLE tbl (a INTEGER PRIMARY KEY, b);} \ + {CREATE TABLE tbl (a, b PRIMARY KEY);} \ + {CREATE TABLE tbl (a, b); CREATE INDEX tbl_idx ON tbl(b);} \ + ] + ifcapable tempdb { + lappend tbl_definitions \ + {CREATE TEMP TABLE tbl (a, b); CREATE INDEX tbl_idx ON tbl(b);} + lappend tbl_definitions {CREATE TEMP TABLE tbl (a, b);} + lappend tbl_definitions \ + {CREATE TEMPORARY TABLE tbl (a INTEGER PRIMARY KEY, b);} + } + foreach tbl_defn $tbl_definitions { + incr ii + catchsql { DROP INDEX tbl_idx; } + catchsql { + DROP TABLE rlog; + DROP TABLE clog; + DROP TABLE tbl; + DROP TABLE other_tbl; + } + + execsql $tbl_defn + + execsql { + INSERT INTO tbl VALUES(1, 2); + INSERT INTO tbl VALUES(3, 4); + + CREATE TABLE rlog (idx, old_a, old_b, db_sum_a, db_sum_b, new_a, new_b); + CREATE TABLE clog (idx, old_a, old_b, db_sum_a, db_sum_b, new_a, new_b); + + CREATE TRIGGER before_update_row BEFORE UPDATE ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + + CREATE TRIGGER after_update_row AFTER UPDATE ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + + CREATE TRIGGER conditional_update_row AFTER UPDATE ON tbl FOR EACH ROW + WHEN old.a = 1 + BEGIN + INSERT INTO clog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM clog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + } + + do_test trigger2-1.$ii.1 { + set r {} + foreach v [execsql { + UPDATE tbl SET a = a * 10, b = b * 10; + SELECT * FROM rlog ORDER BY idx; + SELECT * FROM clog ORDER BY idx; + }] { + lappend r [expr {int($v)}] + } + set r + } [list 1 1 2 4 6 10 20 \ + 2 1 2 13 24 10 20 \ + 3 3 4 13 24 30 40 \ + 4 3 4 40 60 30 40 \ + 1 1 2 13 24 10 20 ] + + execsql { + DELETE FROM rlog; + DELETE FROM tbl; + INSERT INTO tbl VALUES (100, 100); + INSERT INTO tbl VALUES (300, 200); + CREATE TRIGGER delete_before_row BEFORE DELETE ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + 0, 0); + END; + + CREATE TRIGGER delete_after_row AFTER DELETE ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + old.a, old.b, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + 0, 0); + END; + } + do_test trigger2-1.$ii.2 { + set r {} + foreach v [execsql { + DELETE FROM tbl; + SELECT * FROM rlog; + }] { + lappend r [expr {int($v)}] + } + set r + } [list 1 100 100 400 300 0 0 \ + 2 100 100 300 200 0 0 \ + 3 300 200 300 200 0 0 \ + 4 300 200 0 0 0 0 ] + + execsql { + DELETE FROM rlog; + CREATE TRIGGER insert_before_row BEFORE INSERT ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + 0, 0, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + + CREATE TRIGGER insert_after_row AFTER INSERT ON tbl FOR EACH ROW + BEGIN + INSERT INTO rlog VALUES ( (SELECT coalesce(max(idx),0) + 1 FROM rlog), + 0, 0, + (SELECT coalesce(sum(a),0) FROM tbl), + (SELECT coalesce(sum(b),0) FROM tbl), + new.a, new.b); + END; + } + do_test trigger2-1.$ii.3 { + execsql { + + CREATE TABLE other_tbl(a, b); + INSERT INTO other_tbl VALUES(1, 2); + INSERT INTO other_tbl VALUES(3, 4); + -- INSERT INTO tbl SELECT * FROM other_tbl; + INSERT INTO tbl VALUES(5, 6); + DROP TABLE other_tbl; + + SELECT * FROM rlog; + } + } [list 1 0 0 0 0 5 6 \ + 2 0 0 5 6 5 6 ] + + integrity_check trigger2-1.$ii.4 + } + catchsql { + DROP TABLE rlog; + DROP TABLE clog; + DROP TABLE tbl; + DROP TABLE other_tbl; + } +} + +# 2. +set ii 0 +foreach tr_program { + {UPDATE tbl SET b = old.b;} + {INSERT INTO log VALUES(new.c, 2, 3);} + {DELETE FROM log WHERE a = 1;} + {INSERT INTO tbl VALUES(500, new.b * 10, 700); + UPDATE tbl SET c = old.c; + DELETE FROM log;} + {INSERT INTO log select * from tbl;} +} { + foreach test_varset [ list \ + { + set statement {UPDATE tbl SET c = 10 WHERE a = 1;} + set prep {INSERT INTO tbl VALUES(1, 2, 3);} + set newC 10 + set newB 2 + set newA 1 + set oldA 1 + set oldB 2 + set oldC 3 + } \ + { + set statement {DELETE FROM tbl WHERE a = 1;} + set prep {INSERT INTO tbl VALUES(1, 2, 3);} + set oldA 1 + set oldB 2 + set oldC 3 + } \ + { + set statement {INSERT INTO tbl VALUES(1, 2, 3);} + set newA 1 + set newB 2 + set newC 3 + } + ] \ + { + set statement {} + set prep {} + set newA {''} + set newB {''} + set newC {''} + set oldA {''} + set oldB {''} + set oldC {''} + + incr ii + + eval $test_varset + + set statement_type [string range $statement 0 5] + set tr_program_fixed $tr_program + if {$statement_type == "DELETE"} { + regsub -all new\.a $tr_program_fixed {''} tr_program_fixed + regsub -all new\.b $tr_program_fixed {''} tr_program_fixed + regsub -all new\.c $tr_program_fixed {''} tr_program_fixed + } + if {$statement_type == "INSERT"} { + regsub -all old\.a $tr_program_fixed {''} tr_program_fixed + regsub -all old\.b $tr_program_fixed {''} tr_program_fixed + regsub -all old\.c $tr_program_fixed {''} tr_program_fixed + } + + + set tr_program_cooked $tr_program + regsub -all new\.a $tr_program_cooked $newA tr_program_cooked + regsub -all new\.b $tr_program_cooked $newB tr_program_cooked + regsub -all new\.c $tr_program_cooked $newC tr_program_cooked + regsub -all old\.a $tr_program_cooked $oldA tr_program_cooked + regsub -all old\.b $tr_program_cooked $oldB tr_program_cooked + regsub -all old\.c $tr_program_cooked $oldC tr_program_cooked + + catchsql { + DROP TABLE tbl; + DROP TABLE log; + } + + execsql { + CREATE TABLE tbl(a PRIMARY KEY, b, c); + CREATE TABLE log(a, b, c); + } + + set query {SELECT * FROM tbl; SELECT * FROM log;} + set prep "$prep; INSERT INTO log VALUES(1, 2, 3);\ + INSERT INTO log VALUES(10, 20, 30);" + +# Check execution of BEFORE programs: + + set before_data [ execsql "$prep $tr_program_cooked $statement $query" ] + + execsql "DELETE FROM tbl; DELETE FROM log; $prep"; + execsql "CREATE TRIGGER the_trigger BEFORE [string range $statement 0 6]\ + ON tbl BEGIN $tr_program_fixed END;" + + do_test trigger2-2.$ii-before "execsql {$statement $query}" $before_data + + execsql "DROP TRIGGER the_trigger;" + execsql "DELETE FROM tbl; DELETE FROM log;" + +# Check execution of AFTER programs + set after_data [ execsql "$prep $statement $tr_program_cooked $query" ] + + execsql "DELETE FROM tbl; DELETE FROM log; $prep"; + execsql "CREATE TRIGGER the_trigger AFTER [string range $statement 0 6]\ + ON tbl BEGIN $tr_program_fixed END;" + + do_test trigger2-2.$ii-after "execsql {$statement $query}" $after_data + execsql "DROP TRIGGER the_trigger;" + + integrity_check trigger2-2.$ii-integrity + } +} +catchsql { + DROP TABLE tbl; + DROP TABLE log; +} + +# 3. + +# trigger2-3.1: UPDATE OF triggers +execsql { + CREATE TABLE tbl (a, b, c, d); + CREATE TABLE log (a); + INSERT INTO log VALUES (0); + INSERT INTO tbl VALUES (0, 0, 0, 0); + INSERT INTO tbl VALUES (1, 0, 0, 0); + CREATE TRIGGER tbl_after_update_cd BEFORE UPDATE OF c, d ON tbl + BEGIN + UPDATE log SET a = a + 1; + END; +} +do_test trigger2-3.1 { + execsql { + UPDATE tbl SET b = 1, c = 10; -- 2 + UPDATE tbl SET b = 10; -- 0 + UPDATE tbl SET d = 4 WHERE a = 0; --1 + UPDATE tbl SET a = 4, b = 10; --0 + SELECT * FROM log; + } +} {3} +execsql { + DROP TABLE tbl; + DROP TABLE log; +} + +# trigger2-3.2: WHEN clause +set when_triggers [list {t1 BEFORE INSERT ON tbl WHEN new.a > 20}] +ifcapable subquery { + lappend when_triggers \ + {t2 BEFORE INSERT ON tbl WHEN (SELECT count(*) FROM tbl) = 0} +} + +execsql { + CREATE TABLE tbl (a, b, c, d); + CREATE TABLE log (a); + INSERT INTO log VALUES (0); +} + +foreach trig $when_triggers { + execsql "CREATE TRIGGER $trig BEGIN UPDATE log set a = a + 1; END;" +} + +ifcapable subquery { + set t232 {1 0 1} +} else { + set t232 {0 0 1} +} +do_test trigger2-3.2 { + execsql { + + INSERT INTO tbl VALUES(0, 0, 0, 0); -- 1 (ifcapable subquery) + SELECT * FROM log; + UPDATE log SET a = 0; + + INSERT INTO tbl VALUES(0, 0, 0, 0); -- 0 + SELECT * FROM log; + UPDATE log SET a = 0; + + INSERT INTO tbl VALUES(200, 0, 0, 0); -- 1 + SELECT * FROM log; + UPDATE log SET a = 0; + } +} $t232 +execsql { + DROP TABLE tbl; + DROP TABLE log; +} +integrity_check trigger2-3.3 + +# Simple cascaded trigger +execsql { + CREATE TABLE tblA(a, b); + CREATE TABLE tblB(a, b); + CREATE TABLE tblC(a, b); + + CREATE TRIGGER tr1 BEFORE INSERT ON tblA BEGIN + INSERT INTO tblB values(new.a, new.b); + END; + + CREATE TRIGGER tr2 BEFORE INSERT ON tblB BEGIN + INSERT INTO tblC values(new.a, new.b); + END; +} +do_test trigger2-4.1 { + execsql { + INSERT INTO tblA values(1, 2); + SELECT * FROM tblA; + SELECT * FROM tblB; + SELECT * FROM tblC; + } +} {1 2 1 2 1 2} +execsql { + DROP TABLE tblA; + DROP TABLE tblB; + DROP TABLE tblC; +} + +# Simple recursive trigger +execsql { + CREATE TABLE tbl(a, b, c); + CREATE TRIGGER tbl_trig BEFORE INSERT ON tbl + BEGIN + INSERT INTO tbl VALUES (new.a, new.b, new.c); + END; +} +do_test trigger2-4.2 { + execsql { + INSERT INTO tbl VALUES (1, 2, 3); + select * from tbl; + } +} {1 2 3 1 2 3} +execsql { + DROP TABLE tbl; +} + +# 5. +execsql { + CREATE TABLE tbl(a, b, c); + CREATE TRIGGER tbl_trig BEFORE INSERT ON tbl + BEGIN + INSERT INTO tbl VALUES (1, 2, 3); + INSERT INTO tbl VALUES (2, 2, 3); + UPDATE tbl set b = 10 WHERE a = 1; + DELETE FROM tbl WHERE a = 1; + DELETE FROM tbl; + END; +} +do_test trigger2-5 { + execsql { + INSERT INTO tbl VALUES(100, 200, 300); + } + db changes +} {1} +execsql { + DROP TABLE tbl; +} + +ifcapable conflict { + # Handling of ON CONFLICT by INSERT statements inside triggers + execsql { + CREATE TABLE tbl (a primary key, b, c); + CREATE TRIGGER ai_tbl AFTER INSERT ON tbl BEGIN + INSERT OR IGNORE INTO tbl values (new.a, 0, 0); + END; + } + do_test trigger2-6.1a { + execsql { + BEGIN; + INSERT INTO tbl values (1, 2, 3); + SELECT * from tbl; + } + } {1 2 3} + do_test trigger2-6.1b { + catchsql { + INSERT OR ABORT INTO tbl values (2, 2, 3); + } + } {1 {column a is not unique}} + do_test trigger2-6.1c { + execsql { + SELECT * from tbl; + } + } {1 2 3} + do_test trigger2-6.1d { + catchsql { + INSERT OR FAIL INTO tbl values (2, 2, 3); + } + } {1 {column a is not unique}} + do_test trigger2-6.1e { + execsql { + SELECT * from tbl; + } + } {1 2 3 2 2 3} + do_test trigger2-6.1f { + execsql { + INSERT OR REPLACE INTO tbl values (2, 2, 3); + SELECT * from tbl; + } + } {1 2 3 2 0 0} + do_test trigger2-6.1g { + catchsql { + INSERT OR ROLLBACK INTO tbl values (3, 2, 3); + } + } {1 {column a is not unique}} + do_test trigger2-6.1h { + execsql { + SELECT * from tbl; + } + } {} + execsql {DELETE FROM tbl} + + + # Handling of ON CONFLICT by UPDATE statements inside triggers + execsql { + INSERT INTO tbl values (4, 2, 3); + INSERT INTO tbl values (6, 3, 4); + CREATE TRIGGER au_tbl AFTER UPDATE ON tbl BEGIN + UPDATE OR IGNORE tbl SET a = new.a, c = 10; + END; + } + do_test trigger2-6.2a { + execsql { + BEGIN; + UPDATE tbl SET a = 1 WHERE a = 4; + SELECT * from tbl; + } + } {1 2 10 6 3 4} + do_test trigger2-6.2b { + catchsql { + UPDATE OR ABORT tbl SET a = 4 WHERE a = 1; + } + } {1 {column a is not unique}} + do_test trigger2-6.2c { + execsql { + SELECT * from tbl; + } + } {1 2 10 6 3 4} + do_test trigger2-6.2d { + catchsql { + UPDATE OR FAIL tbl SET a = 4 WHERE a = 1; + } + } {1 {column a is not unique}} + do_test trigger2-6.2e { + execsql { + SELECT * from tbl; + } + } {4 2 10 6 3 4} + do_test trigger2-6.2f.1 { + execsql { + UPDATE OR REPLACE tbl SET a = 1 WHERE a = 4; + SELECT * from tbl; + } + } {1 3 10} + do_test trigger2-6.2f.2 { + execsql { + INSERT INTO tbl VALUES (2, 3, 4); + SELECT * FROM tbl; + } + } {1 3 10 2 3 4} + do_test trigger2-6.2g { + catchsql { + UPDATE OR ROLLBACK tbl SET a = 4 WHERE a = 1; + } + } {1 {column a is not unique}} + do_test trigger2-6.2h { + execsql { + SELECT * from tbl; + } + } {4 2 3 6 3 4} + execsql { + DROP TABLE tbl; + } +} ; # ifcapable conflict + +# 7. Triggers on views +ifcapable view { + +do_test trigger2-7.1 { + execsql { + CREATE TABLE ab(a, b); + CREATE TABLE cd(c, d); + INSERT INTO ab VALUES (1, 2); + INSERT INTO ab VALUES (0, 0); + INSERT INTO cd VALUES (3, 4); + + CREATE TABLE tlog(ii INTEGER PRIMARY KEY, + olda, oldb, oldc, oldd, newa, newb, newc, newd); + + CREATE VIEW abcd AS SELECT a, b, c, d FROM ab, cd; + + CREATE TRIGGER before_update INSTEAD OF UPDATE ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + old.a, old.b, old.c, old.d, new.a, new.b, new.c, new.d); + END; + CREATE TRIGGER after_update INSTEAD OF UPDATE ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + old.a, old.b, old.c, old.d, new.a, new.b, new.c, new.d); + END; + + CREATE TRIGGER before_delete INSTEAD OF DELETE ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + old.a, old.b, old.c, old.d, 0, 0, 0, 0); + END; + CREATE TRIGGER after_delete INSTEAD OF DELETE ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + old.a, old.b, old.c, old.d, 0, 0, 0, 0); + END; + + CREATE TRIGGER before_insert INSTEAD OF INSERT ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + 0, 0, 0, 0, new.a, new.b, new.c, new.d); + END; + CREATE TRIGGER after_insert INSTEAD OF INSERT ON abcd BEGIN + INSERT INTO tlog VALUES(NULL, + 0, 0, 0, 0, new.a, new.b, new.c, new.d); + END; + } +} {}; + +do_test trigger2-7.2 { + execsql { + UPDATE abcd SET a = 100, b = 5*5 WHERE a = 1; + DELETE FROM abcd WHERE a = 1; + INSERT INTO abcd VALUES(10, 20, 30, 40); + SELECT * FROM tlog; + } +} [ list 1 1 2 3 4 100 25 3 4 \ + 2 1 2 3 4 100 25 3 4 \ + 3 1 2 3 4 0 0 0 0 \ + 4 1 2 3 4 0 0 0 0 \ + 5 0 0 0 0 10 20 30 40 \ + 6 0 0 0 0 10 20 30 40 ] + +do_test trigger2-7.3 { + execsql { + DELETE FROM tlog; + INSERT INTO abcd VALUES(10, 20, 30, 40); + UPDATE abcd SET a = 100, b = 5*5 WHERE a = 1; + DELETE FROM abcd WHERE a = 1; + SELECT * FROM tlog; + } +} [ list \ + 1 0 0 0 0 10 20 30 40 \ + 2 0 0 0 0 10 20 30 40 \ + 3 1 2 3 4 100 25 3 4 \ + 4 1 2 3 4 100 25 3 4 \ + 5 1 2 3 4 0 0 0 0 \ + 6 1 2 3 4 0 0 0 0 \ +] +do_test trigger2-7.4 { + execsql { + DELETE FROM tlog; + DELETE FROM abcd WHERE a = 1; + INSERT INTO abcd VALUES(10, 20, 30, 40); + UPDATE abcd SET a = 100, b = 5*5 WHERE a = 1; + SELECT * FROM tlog; + } +} [ list \ + 1 1 2 3 4 0 0 0 0 \ + 2 1 2 3 4 0 0 0 0 \ + 3 0 0 0 0 10 20 30 40 \ + 4 0 0 0 0 10 20 30 40 \ + 5 1 2 3 4 100 25 3 4 \ + 6 1 2 3 4 100 25 3 4 \ +] + +do_test trigger2-8.1 { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(1,2,3); + CREATE VIEW v1 AS + SELECT a+b AS x, b+c AS y, a+c AS z FROM t1; + SELECT * FROM v1; + } +} {3 5 4} +do_test trigger2-8.2 { + execsql { + CREATE TABLE v1log(a,b,c,d,e,f); + CREATE TRIGGER r1 INSTEAD OF DELETE ON v1 BEGIN + INSERT INTO v1log VALUES(OLD.x,NULL,OLD.y,NULL,OLD.z,NULL); + END; + DELETE FROM v1 WHERE x=1; + SELECT * FROM v1log; + } +} {} +do_test trigger2-8.3 { + execsql { + DELETE FROM v1 WHERE x=3; + SELECT * FROM v1log; + } +} {3 {} 5 {} 4 {}} +do_test trigger2-8.4 { + execsql { + INSERT INTO t1 VALUES(4,5,6); + DELETE FROM v1log; + DELETE FROM v1 WHERE y=11; + SELECT * FROM v1log; + } +} {9 {} 11 {} 10 {}} +do_test trigger2-8.5 { + execsql { + CREATE TRIGGER r2 INSTEAD OF INSERT ON v1 BEGIN + INSERT INTO v1log VALUES(NULL,NEW.x,NULL,NEW.y,NULL,NEW.z); + END; + DELETE FROM v1log; + INSERT INTO v1 VALUES(1,2,3); + SELECT * FROM v1log; + } +} {{} 1 {} 2 {} 3} +do_test trigger2-8.6 { + execsql { + CREATE TRIGGER r3 INSTEAD OF UPDATE ON v1 BEGIN + INSERT INTO v1log VALUES(OLD.x,NEW.x,OLD.y,NEW.y,OLD.z,NEW.z); + END; + DELETE FROM v1log; + UPDATE v1 SET x=x+100, y=y+200, z=z+300; + SELECT * FROM v1log; + } +} {3 103 5 205 4 304 9 109 11 211 10 310} + +# At one point the following was causing a segfault. +do_test trigger2-9.1 { + execsql { + CREATE TABLE t3(a TEXT, b TEXT); + CREATE VIEW v3 AS SELECT t3.a FROM t3; + CREATE TRIGGER trig1 INSTEAD OF DELETE ON v3 BEGIN + SELECT 1; + END; + DELETE FROM v3 WHERE a = 1; + } +} {} + +} ;# ifcapable view + +integrity_check trigger2-9.9 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trigger3.test b/components/external/SQLite-3.8.1/test/trigger3.test new file mode 100644 index 0000000000000000000000000000000000000000..fe91b9dcf8e2a09fd13fbbe4e5d8516916770a8c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trigger3.test @@ -0,0 +1,200 @@ +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests the RAISE() function. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +# The tests in this file were written before SQLite supported recursive } +# trigger invocation, and some tests depend on that to pass. So disable +# recursive triggers for this file. +catchsql { pragma recursive_triggers = off } + +# Test that we can cause ROLLBACK, FAIL and ABORT correctly +# +catchsql { CREATE TABLE tbl(a, b ,c) } +execsql { + CREATE TRIGGER before_tbl_insert BEFORE INSERT ON tbl BEGIN SELECT CASE + WHEN (new.a = 4) THEN RAISE(IGNORE) END; + END; + + CREATE TRIGGER after_tbl_insert AFTER INSERT ON tbl BEGIN SELECT CASE + WHEN (new.a = 1) THEN RAISE(ABORT, 'Trigger abort') + WHEN (new.a = 2) THEN RAISE(FAIL, 'Trigger fail') + WHEN (new.a = 3) THEN RAISE(ROLLBACK, 'Trigger rollback') END; + END; +} +# ABORT +do_test trigger3-1.1 { + catchsql { + BEGIN; + INSERT INTO tbl VALUES (5, 5, 6); + INSERT INTO tbl VALUES (1, 5, 6); + } +} {1 {Trigger abort}} +verify_ex_errcode trigger3-1.1b SQLITE_CONSTRAINT_TRIGGER +do_test trigger3-1.2 { + execsql { + SELECT * FROM tbl; + ROLLBACK; + } +} {5 5 6} +do_test trigger3-1.3 { + execsql {SELECT * FROM tbl} +} {} + +# FAIL +do_test trigger3-2.1 { + catchsql { + BEGIN; + INSERT INTO tbl VALUES (5, 5, 6); + INSERT INTO tbl VALUES (2, 5, 6); + } +} {1 {Trigger fail}} +verify_ex_errcode trigger3-2.1b SQLITE_CONSTRAINT_TRIGGER +do_test trigger3-2.2 { + execsql { + SELECT * FROM tbl; + ROLLBACK; + } +} {5 5 6 2 5 6} +# ROLLBACK +do_test trigger3-3.1 { + catchsql { + BEGIN; + INSERT INTO tbl VALUES (5, 5, 6); + INSERT INTO tbl VALUES (3, 5, 6); + } +} {1 {Trigger rollback}} +verify_ex_errcode trigger3-3.1b SQLITE_CONSTRAINT_TRIGGER +do_test trigger3-3.2 { + execsql { + SELECT * FROM tbl; + } +} {} + +# Verify that a ROLLBACK trigger works like a FAIL trigger if +# we are not within a transaction. Ticket #3035. +# +do_test trigger3-3.3 { + catchsql {COMMIT} + catchsql { + INSERT INTO tbl VALUES (3, 9, 10); + } +} {1 {Trigger rollback}} +verify_ex_errcode trigger3-3.3b SQLITE_CONSTRAINT_TRIGGER +do_test trigger3-3.4 { + execsql {SELECT * FROM tbl} +} {} + +# IGNORE +do_test trigger3-4.1 { + catchsql { + BEGIN; + INSERT INTO tbl VALUES (5, 5, 6); + INSERT INTO tbl VALUES (4, 5, 6); + } +} {0 {}} +do_test trigger3-4.2 { + execsql { + SELECT * FROM tbl; + ROLLBACK; + } +} {5 5 6} + +# Check that we can also do RAISE(IGNORE) for UPDATE and DELETE +execsql {DROP TABLE tbl;} +execsql {CREATE TABLE tbl (a, b, c);} +execsql {INSERT INTO tbl VALUES(1, 2, 3);} +execsql {INSERT INTO tbl VALUES(4, 5, 6);} +execsql { + CREATE TRIGGER before_tbl_update BEFORE UPDATE ON tbl BEGIN + SELECT CASE WHEN (old.a = 1) THEN RAISE(IGNORE) END; + END; + + CREATE TRIGGER before_tbl_delete BEFORE DELETE ON tbl BEGIN + SELECT CASE WHEN (old.a = 1) THEN RAISE(IGNORE) END; + END; +} +do_test trigger3-5.1 { + execsql { + UPDATE tbl SET c = 10; + SELECT * FROM tbl; + } +} {1 2 3 4 5 10} +do_test trigger3-5.2 { + execsql { + DELETE FROM tbl; + SELECT * FROM tbl; + } +} {1 2 3} + +# Check that RAISE(IGNORE) works correctly for nested triggers: +execsql {CREATE TABLE tbl2(a, b, c)} +execsql { + CREATE TRIGGER after_tbl2_insert AFTER INSERT ON tbl2 BEGIN + UPDATE tbl SET c = 10; + INSERT INTO tbl2 VALUES (new.a, new.b, new.c); + END; +} +do_test trigger3-6 { + execsql { + INSERT INTO tbl2 VALUES (1, 2, 3); + SELECT * FROM tbl2; + SELECT * FROM tbl; + } +} {1 2 3 1 2 3 1 2 3} + +# Check that things also work for view-triggers + +ifcapable view { + +execsql {CREATE VIEW tbl_view AS SELECT * FROM tbl} +execsql { + CREATE TRIGGER tbl_view_insert INSTEAD OF INSERT ON tbl_view BEGIN + SELECT CASE WHEN (new.a = 1) THEN RAISE(ROLLBACK, 'View rollback') + WHEN (new.a = 2) THEN RAISE(IGNORE) + WHEN (new.a = 3) THEN RAISE(ABORT, 'View abort') END; + END; +} + +do_test trigger3-7.1 { + catchsql { + INSERT INTO tbl_view VALUES(1, 2, 3); + } +} {1 {View rollback}} +verify_ex_errcode trigger3-7.1b SQLITE_CONSTRAINT_TRIGGER +do_test trigger3-7.2 { + catchsql { + INSERT INTO tbl_view VALUES(2, 2, 3); + } +} {0 {}} +do_test trigger3-7.3 { + catchsql { + INSERT INTO tbl_view VALUES(3, 2, 3); + } +} {1 {View abort}} +verify_ex_errcode trigger3-7.3b SQLITE_CONSTRAINT_TRIGGER + +} ;# ifcapable view + +integrity_check trigger3-8.1 + +catchsql { DROP TABLE tbl; } +catchsql { DROP TABLE tbl2; } +catchsql { DROP VIEW tbl_view; } + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trigger4.test b/components/external/SQLite-3.8.1/test/trigger4.test new file mode 100644 index 0000000000000000000000000000000000000000..a05a5e735f3ea96f1d8d5f423694a96f432a2db5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trigger4.test @@ -0,0 +1,200 @@ +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests the triggers of views. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If either views or triggers are disabled in this build, omit this file. +ifcapable {!trigger || !view} { + finish_test + return +} + +do_test trigger4-1.1 { + execsql { + create table test1(id integer primary key,a); + create table test2(id integer,b); + create view test as + select test1.id as id,a as a,b as b + from test1 join test2 on test2.id = test1.id; + create trigger I_test instead of insert on test + begin + insert into test1 (id,a) values (NEW.id,NEW.a); + insert into test2 (id,b) values (NEW.id,NEW.b); + end; + insert into test values(1,2,3); + select * from test1; + } +} {1 2} +do_test trigger4-1.2 { + execsql { + select * from test2; + } +} {1 3} +do_test trigger4-1.3 { + db close + sqlite3 db test.db + execsql { + insert into test values(4,5,6); + select * from test1; + } +} {1 2 4 5} +do_test trigger4-1.4 { + execsql { + select * from test2; + } +} {1 3 4 6} + +do_test trigger4-2.1 { + execsql { + create trigger U_test instead of update on test + begin + update test1 set a=NEW.a where id=NEW.id; + update test2 set b=NEW.b where id=NEW.id; + end; + update test set a=22 where id=1; + select * from test1; + } +} {1 22 4 5} +do_test trigger4-2.2 { + execsql { + select * from test2; + } +} {1 3 4 6} +do_test trigger4-2.3 { + db close + sqlite3 db test.db + execsql { + update test set b=66 where id=4; + select * from test1; + } +} {1 22 4 5} +do_test trigger4-2.4 { + execsql { + select * from test2; + } +} {1 3 4 66} + +do_test trigger4-3.1 { + catchsql { + drop table test2; + insert into test values(7,8,9); + } +} {1 {no such table: main.test2}} +do_test trigger4-3.2 { + db close + sqlite3 db test.db + catchsql { + insert into test values(7,8,9); + } +} {1 {no such table: main.test2}} +do_test trigger4-3.3 { + catchsql { + update test set a=222 where id=1; + } +} {1 {no such table: main.test2}} +do_test trigger4-3.4 { + execsql { + select * from test1; + } +} {1 22 4 5} +do_test trigger4-3.5 { + execsql { + create table test2(id,b); + insert into test values(7,8,9); + select * from test1; + } +} {1 22 4 5 7 8} +do_test trigger4-3.6 { + execsql { + select * from test2; + } +} {7 9} +do_test trigger4-3.7 { + db close + sqlite3 db test.db + execsql { + update test set b=99 where id=7; + select * from test2; + } +} {7 99} + +do_test trigger4-4.1 { + db close + forcedelete trigtest.db + forcedelete trigtest.db-journal + sqlite3 db trigtest.db + catchsql {drop table tbl; drop view vw} + execsql { + create table tbl(a integer primary key, b integer); + create view vw as select * from tbl; + create trigger t_del_tbl instead of delete on vw for each row begin + delete from tbl where a = old.a; + end; + create trigger t_upd_tbl instead of update on vw for each row begin + update tbl set a=new.a, b=new.b where a = old.a; + end; + create trigger t_ins_tbl instead of insert on vw for each row begin + insert into tbl values (new.a,new.b); + end; + insert into tbl values(101,1001); + insert into tbl values(102,1002); + insert into tbl select a+2, b+2 from tbl; + insert into tbl select a+4, b+4 from tbl; + insert into tbl select a+8, b+8 from tbl; + insert into tbl select a+16, b+16 from tbl; + insert into tbl select a+32, b+32 from tbl; + insert into tbl select a+64, b+64 from tbl; + select count(*) from vw; + } +} {128} +do_test trigger4-4.2 { + execsql {select a, b from vw where a<103 or a>226 order by a} +} {101 1001 102 1002 227 1127 228 1128} + +#test delete from view +do_test trigger4-5.1 { + catchsql {delete from vw where a>101 and a<2000} +} {0 {}} +do_test trigger4-5.2 { + execsql {select * from vw} +} {101 1001} + +#test insert into view +do_test trigger4-6.1 { + catchsql { + insert into vw values(102,1002); + insert into vw select a+2, b+2 from vw; + insert into vw select a+4, b+4 from vw; + insert into vw select a+8, b+8 from vw; + insert into vw select a+16, b+16 from vw; + insert into vw select a+32, b+32 from vw; + insert into vw select a+64, b+64 from vw; + } +} {0 {}} +do_test trigger4-6.2 { + execsql {select count(*) from vw} +} {128} + +#test update of view +do_test trigger4-7.1 { + catchsql {update vw set b=b+1000 where a>101 and a<2000} +} {0 {}} +do_test trigger4-7.2 { + execsql {select a, b from vw where a<=102 or a>=227 order by a} +} {101 1001 102 2002 227 2127 228 2128} + +integrity_check trigger4-99.9 +db close +forcedelete trigtest.db trigtest.db-journal + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trigger5.test b/components/external/SQLite-3.8.1/test/trigger5.test new file mode 100644 index 0000000000000000000000000000000000000000..75c56b19c9af14170e9ffab15541e74082b07d9f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trigger5.test @@ -0,0 +1,43 @@ +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests the triggers of views. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +# Ticket #844 +# +do_test trigger5-1.1 { + execsql { + CREATE TABLE Item( + a integer PRIMARY KEY NOT NULL , + b double NULL , + c int NOT NULL DEFAULT 0 + ); + CREATE TABLE Undo(UndoAction TEXT); + INSERT INTO Item VALUES (1,38205.60865,340); + CREATE TRIGGER trigItem_UNDO_AD AFTER DELETE ON Item FOR EACH ROW + BEGIN + INSERT INTO Undo SELECT 'INSERT INTO Item (a,b,c) VALUES (' + || coalesce(old.a,'NULL') || ',' || quote(old.b) || ',' || old.c || ');'; + END; + DELETE FROM Item WHERE a = 1; + SELECT * FROM Undo; + } +} {{INSERT INTO Item (a,b,c) VALUES (1,38205.60865,340);}} + +integrity_check trigger5-99.9 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trigger6.test b/components/external/SQLite-3.8.1/test/trigger6.test new file mode 100644 index 0000000000000000000000000000000000000000..bb343faf051b8bc546048104d8ec0a3f2b79922c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trigger6.test @@ -0,0 +1,82 @@ +# 2004 December 07 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure expression of an INSERT +# and UPDATE statement are only evaluated once. See ticket #980. +# If an expression uses a function that has side-effects or which +# is not deterministic (ex: random()) then we want to make sure +# that the same evaluation occurs for the actual INSERT/UPDATE and +# for the NEW.* fields of any triggers that fire. +# +# $Id: trigger6.test,v 1.2 2005/05/05 11:04:50 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +do_test trigger6-1.1 { + execsql { + CREATE TABLE t1(x, y); + CREATE TABLE log(a, b, c); + CREATE TRIGGER r1 BEFORE INSERT ON t1 BEGIN + INSERT INTO log VALUES(1, new.x, new.y); + END; + CREATE TRIGGER r2 BEFORE UPDATE ON t1 BEGIN + INSERT INTO log VALUES(2, new.x, new.y); + END; + } + set ::trigger6_cnt 0 + proc trigger6_counter {args} { + incr ::trigger6_cnt + return $::trigger6_cnt + } + db function counter trigger6_counter + execsql { + INSERT INTO t1 VALUES(1,counter()); + SELECT * FROM t1; + } +} {1 1} +do_test trigger6-1.2 { + execsql { + SELECT * FROM log; + } +} {1 1 1} +do_test trigger6-1.3 { + execsql { + DELETE FROM t1; + DELETE FROM log; + INSERT INTO t1 VALUES(2,counter(2,3)+4); + SELECT * FROM t1; + } +} {2 6} +do_test trigger6-1.4 { + execsql { + SELECT * FROM log; + } +} {1 2 6} +do_test trigger6-1.5 { + execsql { + DELETE FROM log; + UPDATE t1 SET y=counter(5); + SELECT * FROM t1; + } +} {2 3} +do_test trigger6-1.6 { + execsql { + SELECT * FROM log; + } +} {2 2 3} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trigger7.test b/components/external/SQLite-3.8.1/test/trigger7.test new file mode 100644 index 0000000000000000000000000000000000000000..8fde2004f87bd0c283b3a1e3ee25d1ac1fbb3c4d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trigger7.test @@ -0,0 +1,119 @@ +# 2005 August 18 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to increase coverage of trigger.c. +# +# $Id: trigger7.test,v 1.3 2008/08/11 18:44:58 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + + +# Error messages resulting from qualified trigger names. +# +do_test trigger7-1.1 { + execsql { + CREATE TABLE t1(x, y); + } + catchsql { + CREATE TEMP TRIGGER main.r1 AFTER INSERT ON t1 BEGIN + SELECT 'no nothing'; + END + } +} {1 {temporary trigger may not have qualified name}} +do_test trigger7-1.2 { + catchsql { + CREATE TRIGGER not_a_db.r1 AFTER INSERT ON t1 BEGIN + SELECT 'no nothing'; + END + } +} {1 {unknown database not_a_db}} + + +# When the UPDATE OF syntax is used, no code is generated for triggers +# that do not match the update columns. +# +ifcapable explain { + do_test trigger7-2.1 { + execsql { + CREATE TRIGGER r1 AFTER UPDATE OF x ON t1 BEGIN + SELECT '___update_t1.x___'; + END; + CREATE TRIGGER r2 AFTER UPDATE OF y ON t1 BEGIN + SELECT '___update_t1.y___'; + END; + } + set txt [db eval {EXPLAIN UPDATE t1 SET x=5}] + string match *___update_t1.x___* $txt + } 1 + do_test trigger7-2.2 { + set txt [db eval {EXPLAIN UPDATE t1 SET x=5}] + string match *___update_t1.y___* $txt + } 0 + do_test trigger7-2.3 { + set txt [db eval {EXPLAIN UPDATE t1 SET y=5}] + string match *___update_t1.x___* $txt + } 0 + do_test trigger7-2.4 { + set txt [db eval {EXPLAIN UPDATE t1 SET y=5}] + string match *___update_t1.y___* $txt + } 1 + do_test trigger7-2.5 { + set txt [db eval {EXPLAIN UPDATE t1 SET rowid=5}] + string match *___update_t1.x___* $txt + } 0 + do_test trigger7-2.6 { + set txt [db eval {EXPLAIN UPDATE t1 SET rowid=5}] + string match *___update_t1.x___* $txt + } 0 +} + +# Test the ability to create many triggers on the same table, then +# selectively drop those triggers. +# +do_test trigger7-3.1 { + execsql { + CREATE TABLE t2(x,y,z); + CREATE TRIGGER t2r1 AFTER INSERT ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r2 BEFORE INSERT ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r3 AFTER UPDATE ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r4 BEFORE UPDATE ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r5 AFTER DELETE ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r6 BEFORE DELETE ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r7 AFTER INSERT ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r8 BEFORE INSERT ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r9 AFTER UPDATE ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r10 BEFORE UPDATE ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r11 AFTER DELETE ON t2 BEGIN SELECT 1; END; + CREATE TRIGGER t2r12 BEFORE DELETE ON t2 BEGIN SELECT 1; END; + DROP TRIGGER t2r6; + } +} {} + +# This test corrupts the database file so it must be the last test +# in the series. +# +do_test trigger7-99.1 { + execsql { + PRAGMA writable_schema=on; + UPDATE sqlite_master SET sql='nonsense'; + } + db close + catch { sqlite3 db test.db } + catchsql { DROP TRIGGER t2r5 } +} {1 {malformed database schema (t2r12) - near "nonsense": syntax error}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trigger8.test b/components/external/SQLite-3.8.1/test/trigger8.test new file mode 100644 index 0000000000000000000000000000000000000000..3064ea601489cc50f32965e3b286a0fc2c52b5ce --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trigger8.test @@ -0,0 +1,53 @@ +# 2006 February 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests to make sure abusively large triggers +# (triggers with 100s or 1000s of statements) work. +# +# $Id: trigger8.test,v 1.2 2008/09/17 16:14:10 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +# Set variable $nStatement to the number of statements to include in the +# body of the trigger. On a workstation with virtually unlimited memory, +# use 10000. But on symbian, which allows each application at most a 32MB +# heap, use 1000. +# +set nStatement 10000 +if {$tcl_platform(platform) == "symbian"} { + set nStatement 1000 +} + +set nStatement 5 +do_test trigger8-1.1 { + execsql { + CREATE TABLE t1(x); + CREATE TABLE t2(y); + } + set sql "CREATE TRIGGER r${nStatement} AFTER INSERT ON t1 BEGIN\n" + for {set i 0} {$i<$nStatement} {incr i} { + append sql " INSERT INTO t2 VALUES($i);\n" + } + append sql "END;" + execsql $sql + execsql { + INSERT INTO t1 VALUES(5); + SELECT count(*) FROM t2; + } +} $nStatement + +finish_test diff --git a/components/external/SQLite-3.8.1/test/trigger9.test b/components/external/SQLite-3.8.1/test/trigger9.test new file mode 100644 index 0000000000000000000000000000000000000000..f56c8acbc58edf08a1b49f5c8f9259a8354907c2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/trigger9.test @@ -0,0 +1,223 @@ +# 2008 January 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests some compiler optimizations for SQL statements featuring +# triggers: +# +# +# + +# trigger9-1.* - Test that if there are no references to OLD.* cols, or a +# reference to only OLD.rowid, the data is not loaded. +# +# trigger9-2.* - Test that for NEW.* records populated by UPDATE +# statements, unused fields are populated with NULL values. +# +# trigger9-3.* - Test that the temporary tables used for OLD.* references +# in "INSTEAD OF" triggers have NULL values in unused +# fields. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +proc has_rowdata {sql} { + expr {[lsearch [execsql "explain $sql"] RowData]>=0} +} + +do_test trigger9-1.1 { + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(x, y, z); + INSERT INTO t1 VALUES('1', randstr(10000,10000), '2'); + INSERT INTO t1 VALUES('2', randstr(10000,10000), '4'); + INSERT INTO t1 VALUES('3', randstr(10000,10000), '6'); + CREATE TABLE t2(x); + } +} {} + +do_test trigger9-1.2.1 { + execsql { + BEGIN; + CREATE TRIGGER trig1 BEFORE DELETE ON t1 BEGIN + INSERT INTO t2 VALUES(old.rowid); + END; + DELETE FROM t1; + SELECT * FROM t2; + } +} {1 2 3} +do_test trigger9-1.2.3 { + has_rowdata {DELETE FROM t1} +} 0 +do_test trigger9-1.2.4 { execsql { ROLLBACK } } {} + +do_test trigger9-1.3.1 { + execsql { + BEGIN; + CREATE TRIGGER trig1 BEFORE DELETE ON t1 BEGIN + INSERT INTO t2 VALUES(old.x); + END; + DELETE FROM t1; + SELECT * FROM t2; + } +} {1 2 3} +do_test trigger9-1.3.2 { + has_rowdata {DELETE FROM t1} +} 0 +do_test trigger9-1.3.3 { execsql { ROLLBACK } } {} + +do_test trigger9-1.4.1 { + execsql { + BEGIN; + CREATE TRIGGER trig1 BEFORE DELETE ON t1 WHEN old.x='1' BEGIN + INSERT INTO t2 VALUES(old.rowid); + END; + DELETE FROM t1; + SELECT * FROM t2; + } +} {1} +do_test trigger9-1.4.2 { + has_rowdata {DELETE FROM t1} +} 0 +do_test trigger9-1.4.3 { execsql { ROLLBACK } } {} + +do_test trigger9-1.5.1 { + execsql { + BEGIN; + CREATE TRIGGER trig1 BEFORE UPDATE ON t1 BEGIN + INSERT INTO t2 VALUES(old.rowid); + END; + UPDATE t1 SET y = ''; + SELECT * FROM t2; + } +} {1 2 3} +do_test trigger9-1.5.2 { + has_rowdata {UPDATE t1 SET y = ''} +} 0 +do_test trigger9-1.5.3 { execsql { ROLLBACK } } {} + +do_test trigger9-1.6.1 { + execsql { + BEGIN; + CREATE TRIGGER trig1 BEFORE UPDATE ON t1 BEGIN + INSERT INTO t2 VALUES(old.x); + END; + UPDATE t1 SET y = ''; + SELECT * FROM t2; + } +} {1 2 3} +do_test trigger9-1.6.2 { + has_rowdata {UPDATE t1 SET y = ''} +} 0 +do_test trigger9-1.6.3 { execsql { ROLLBACK } } {} + +do_test trigger9-1.7.1 { + execsql { + BEGIN; + CREATE TRIGGER trig1 BEFORE UPDATE ON t1 WHEN old.x>='2' BEGIN + INSERT INTO t2 VALUES(old.x); + END; + UPDATE t1 SET y = ''; + SELECT * FROM t2; + } +} {2 3} +do_test trigger9-1.7.2 { + has_rowdata {UPDATE t1 SET y = ''} +} 0 +do_test trigger9-1.7.3 { execsql { ROLLBACK } } {} + +do_test trigger9-3.1 { + execsql { + CREATE TABLE t3(a, b); + INSERT INTO t3 VALUES(1, 'one'); + INSERT INTO t3 VALUES(2, 'two'); + INSERT INTO t3 VALUES(3, 'three'); + } +} {} +do_test trigger9-3.2 { + execsql { + BEGIN; + CREATE VIEW v1 AS SELECT * FROM t3; + CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN + INSERT INTO t2 VALUES(old.a); + END; + UPDATE v1 SET b = 'hello'; + SELECT * FROM t2; + ROLLBACK; + } +} {1 2 3} +do_test trigger9-3.3 { + # In this test the 'c' column of the view is not required by + # the INSTEAD OF trigger, but the expression is reused internally as + # part of the view's WHERE clause. Check that this does not cause + # a problem. + # + execsql { + BEGIN; + CREATE VIEW v1 AS SELECT a, b AS c FROM t3 WHERE c > 'one'; + CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN + INSERT INTO t2 VALUES(old.a); + END; + UPDATE v1 SET c = 'hello'; + SELECT * FROM t2; + ROLLBACK; + } +} {2 3} +do_test trigger9-3.4 { + execsql { + BEGIN; + INSERT INTO t3 VALUES(3, 'three'); + INSERT INTO t3 VALUES(3, 'four'); + CREATE VIEW v1 AS SELECT DISTINCT a, b FROM t3; + CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN + INSERT INTO t2 VALUES(old.a); + END; + UPDATE v1 SET b = 'hello'; + SELECT * FROM t2; + ROLLBACK; + } +} {1 2 3 3} + +ifcapable compound { + do_test trigger9-3.5 { + execsql { + BEGIN; + INSERT INTO t3 VALUES(1, 'uno'); + CREATE VIEW v1 AS SELECT a, b FROM t3 EXCEPT SELECT 1, 'one'; + CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN + INSERT INTO t2 VALUES(old.a); + END; + UPDATE v1 SET b = 'hello'; + SELECT * FROM t2; + ROLLBACK; + } + } {1 2 3} + do_test trigger9-3.6 { + execsql { + BEGIN; + INSERT INTO t3 VALUES(1, 'zero'); + CREATE VIEW v1 AS + SELECT sum(a) AS a, max(b) AS b FROM t3 GROUP BY t3.a HAVING b>'two'; + CREATE TRIGGER trig1 INSTEAD OF UPDATE ON v1 BEGIN + INSERT INTO t2 VALUES(old.a); + END; + UPDATE v1 SET b = 'hello'; + SELECT * FROM t2; + ROLLBACK; + } + } {2} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/triggerA.test b/components/external/SQLite-3.8.1/test/triggerA.test new file mode 100644 index 0000000000000000000000000000000000000000..821e2d90e477538f8bb7a56fe06dd1ad3fdd9905 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/triggerA.test @@ -0,0 +1,237 @@ +# 2008 February 12 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests issues relating to firing an INSTEAD OF trigger on a VIEW +# when one tries to UPDATE or DELETE from the view. Does the WHERE +# clause of the UPDATE or DELETE statement get passed down correctly +# into the query that manifests the view? +# +# Ticket #2938 +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !trigger||!compound { + finish_test + return +} + +# Create two table containing some sample data +# +do_test triggerA-1.1 { + db eval { + CREATE TABLE t1(x INTEGER PRIMARY KEY, y TEXT UNIQUE); + CREATE TABLE t2(a INTEGER PRIMARY KEY, b INTEGER UNIQUE, c TEXT); + } + set i 1 + foreach word {one two three four five six seven eight nine ten} { + set j [expr {$i*100 + [string length $word]}] + db eval { + INSERT INTO t1 VALUES($i,$word); + INSERT INTO t2 VALUES(20-$i,$j,$word); + } + incr i + } + db eval { + SELECT count(*) FROM t1 UNION ALL SELECT count(*) FROM t2; + } +} {10 10} + +# Create views of various forms against one or both of the two tables. +# +do_test triggerA-1.2 { + db eval { + CREATE VIEW v1 AS SELECT y, x FROM t1; + SELECT * FROM v1 ORDER BY 1; + } +} {eight 8 five 5 four 4 nine 9 one 1 seven 7 six 6 ten 10 three 3 two 2} +do_test triggerA-1.3 { + db eval { + CREATE VIEW v2 AS SELECT x, y FROM t1 WHERE y GLOB '*e*'; + SELECT * FROM v2 ORDER BY 1; + } +} {1 one 3 three 5 five 7 seven 8 eight 9 nine 10 ten} +do_test triggerA-1.4 { + db eval { + CREATE VIEW v3 AS + SELECT CAST(x AS TEXT) AS c1 FROM t1 UNION SELECT y FROM t1; + SELECT * FROM v3 ORDER BY c1; + } +} {1 10 2 3 4 5 6 7 8 9 eight five four nine one seven six ten three two} +do_test triggerA-1.5 { + db eval { + CREATE VIEW v4 AS + SELECT CAST(x AS TEXT) AS c1 FROM t1 + UNION SELECT y FROM t1 WHERE x BETWEEN 3 and 5; + SELECT * FROM v4 ORDER BY 1; + } +} {1 10 2 3 4 5 6 7 8 9 five four three} +do_test triggerA-1.6 { + db eval { + CREATE VIEW v5 AS SELECT x, b FROM t1, t2 WHERE y=c; + SELECT * FROM v5 ORDER BY x DESC; + } +} {10 1003 9 904 8 805 7 705 6 603 5 504 4 404 3 305 2 203 1 103} + +# Create INSTEAD OF triggers on the views. Run UPDATE and DELETE statements +# using those triggers. Verify correct operation. +# +do_test triggerA-2.1 { + db eval { + CREATE TABLE result2(a,b); + CREATE TRIGGER r1d INSTEAD OF DELETE ON v1 BEGIN + INSERT INTO result2(a,b) VALUES(old.y, old.x); + END; + DELETE FROM v1 WHERE x=5; + SELECT * FROM result2; + } +} {five 5} +do_test triggerA-2.2 { + db eval { + CREATE TABLE result4(a,b,c,d); + CREATE TRIGGER r1u INSTEAD OF UPDATE ON v1 BEGIN + INSERT INTO result4(a,b,c,d) VALUES(old.y, old.x, new.y, new.x); + END; + UPDATE v1 SET y=y||'-extra' WHERE x BETWEEN 3 AND 5; + SELECT * FROM result4 ORDER BY a; + } +} {five 5 five-extra 5 four 4 four-extra 4 three 3 three-extra 3} + + +do_test triggerA-2.3 { + db eval { + DELETE FROM result2; + CREATE TRIGGER r2d INSTEAD OF DELETE ON v2 BEGIN + INSERT INTO result2(a,b) VALUES(old.y, old.x); + END; + DELETE FROM v2 WHERE x=5; + SELECT * FROM result2; + } +} {five 5} +do_test triggerA-2.4 { + db eval { + DELETE FROM result4; + CREATE TRIGGER r2u INSTEAD OF UPDATE ON v2 BEGIN + INSERT INTO result4(a,b,c,d) VALUES(old.y, old.x, new.y, new.x); + END; + UPDATE v2 SET y=y||'-extra' WHERE x BETWEEN 3 AND 5; + SELECT * FROM result4 ORDER BY a; + } +} {five 5 five-extra 5 three 3 three-extra 3} + + +do_test triggerA-2.5 { + db eval { + CREATE TABLE result1(a); + CREATE TRIGGER r3d INSTEAD OF DELETE ON v3 BEGIN + INSERT INTO result1(a) VALUES(old.c1); + END; + DELETE FROM v3 WHERE c1 BETWEEN '8' AND 'eight'; + SELECT * FROM result1 ORDER BY a; + } +} {8 9 eight} +do_test triggerA-2.6 { + db eval { + DELETE FROM result2; + CREATE TRIGGER r3u INSTEAD OF UPDATE ON v3 BEGIN + INSERT INTO result2(a,b) VALUES(old.c1, new.c1); + END; + UPDATE v3 SET c1 = c1 || '-extra' WHERE c1 BETWEEN '8' and 'eight'; + SELECT * FROM result2 ORDER BY a; + } +} {8 8-extra 9 9-extra eight eight-extra} + + +do_test triggerA-2.7 { + db eval { + DELETE FROM result1; + CREATE TRIGGER r4d INSTEAD OF DELETE ON v4 BEGIN + INSERT INTO result1(a) VALUES(old.c1); + END; + DELETE FROM v4 WHERE c1 BETWEEN '8' AND 'eight'; + SELECT * FROM result1 ORDER BY a; + } +} {8 9} +do_test triggerA-2.8 { + db eval { + DELETE FROM result2; + CREATE TRIGGER r4u INSTEAD OF UPDATE ON v4 BEGIN + INSERT INTO result2(a,b) VALUES(old.c1, new.c1); + END; + UPDATE v4 SET c1 = c1 || '-extra' WHERE c1 BETWEEN '8' and 'eight'; + SELECT * FROM result2 ORDER BY a; + } +} {8 8-extra 9 9-extra} + + +do_test triggerA-2.9 { + db eval { + DELETE FROM result2; + CREATE TRIGGER r5d INSTEAD OF DELETE ON v5 BEGIN + INSERT INTO result2(a,b) VALUES(old.x, old.b); + END; + DELETE FROM v5 WHERE x=5; + SELECT * FROM result2; + } +} {5 504} +do_test triggerA-2.10 { + db eval { + DELETE FROM result4; + CREATE TRIGGER r5u INSTEAD OF UPDATE ON v5 BEGIN + INSERT INTO result4(a,b,c,d) VALUES(old.x, old.b, new.x, new.b); + END; + UPDATE v5 SET b = b+9900000 WHERE x BETWEEN 3 AND 5; + SELECT * FROM result4 ORDER BY a; + } +} {3 305 3 9900305 4 404 4 9900404 5 504 5 9900504} +do_test triggerA-2.11 { + db eval { + DELETE FROM result4; + UPDATE v5 SET b = main.v5.b+9900000 WHERE main.v5.x BETWEEN 3 AND 5; + SELECT * FROM result4 ORDER BY a; + } +} {3 305 3 9900305 4 404 4 9900404 5 504 5 9900504} + +# Only run the reamining tests if memory debugging is turned on. +# +ifcapable !memdebug { + puts "Skipping triggerA malloc tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} +source $testdir/malloc_common.tcl + +# Save a copy of the current database configuration. +# +db close +forcedelete test.db-triggerA +copy_file test.db test.db-triggerA +sqlite3 db test.db + +# Run malloc tests on the INSTEAD OF trigger firing. +# +do_malloc_test triggerA-3 -tclprep { + db close + forcedelete test.db test.db-journal + forcecopy test.db-triggerA test.db + sqlite3 db test.db + sqlite3_extended_result_codes db 1 + db eval {SELECT * FROM v5; -- warm up the cache} +} -sqlbody { + DELETE FROM v5 WHERE x=5; + UPDATE v5 SET b=b+9900000 WHERE x BETWEEN 3 AND 5; +} + +# Clean up the saved database copy. +# +forcedelete test.db-triggerA + +finish_test diff --git a/components/external/SQLite-3.8.1/test/triggerB.test b/components/external/SQLite-3.8.1/test/triggerB.test new file mode 100644 index 0000000000000000000000000000000000000000..ac4f37bcf4cadab496cadb73f97af825d08e222f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/triggerB.test @@ -0,0 +1,153 @@ +# 2008 April 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice', here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specifically, +# it tests updating tables with constraints within a trigger. Ticket #3055. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +# Create test tables with constraints. +# +do_test triggerB-1.1 { + execsql { + CREATE TABLE x(x INTEGER PRIMARY KEY, y INT NOT NULL); + INSERT INTO x(y) VALUES(1); + INSERT INTO x(y) VALUES(1); + CREATE TEMP VIEW vx AS SELECT x, y, 0 AS yy FROM x; + CREATE TEMP TRIGGER tx INSTEAD OF UPDATE OF y ON vx + BEGIN + UPDATE x SET y = new.y WHERE x = new.x; + END; + SELECT * FROM vx; + } +} {1 1 0 2 1 0} +do_test triggerB-1.2 { + execsql { + UPDATE vx SET y = yy; + SELECT * FROM vx; + } +} {1 0 0 2 0 0} + +# Added 2008-08-22: +# +# Name resolution within triggers. +# +do_test triggerB-2.1 { + catchsql { + CREATE TRIGGER ty AFTER INSERT ON x BEGIN + SELECT wen.x; -- Unrecognized name + END; + INSERT INTO x VALUES(1,2); + } +} {1 {no such column: wen.x}} +do_test triggerB-2.2 { + catchsql { + CREATE TRIGGER tz AFTER UPDATE ON x BEGIN + SELECT dlo.x; -- Unrecognized name + END; + UPDATE x SET y=y+1; + } +} {1 {no such column: dlo.x}} + +do_test triggerB-2.3 { + execsql { + CREATE TABLE t2(a INTEGER PRIMARY KEY, b); + INSERT INTO t2 VALUES(1,2); + CREATE TABLE changes(x,y); + CREATE TRIGGER r1t2 AFTER UPDATE ON t2 BEGIN + INSERT INTO changes VALUES(new.a, new.b); + END; + } + execsql { + UPDATE t2 SET a=a+10; + SELECT * FROM changes; + } +} {11 2} +do_test triggerB-2.4 { + execsql { + CREATE TRIGGER r2t2 AFTER DELETE ON t2 BEGIN + INSERT INTO changes VALUES(old.a, old.c); + END; + } + catchsql { + DELETE FROM t2; + } +} {1 {no such column: old.c}} + +# Triggers maintain a mask of columns from the invoking table that are +# used in the trigger body as NEW.column or OLD.column. That mask is then +# used to reduce the amount of information that needs to be loaded into +# the NEW and OLD pseudo-tables at run-time. +# +# These tests cases check the logic for when there are many columns - more +# than will fit in a bitmask. +# +do_test triggerB-3.1 { + execsql { + CREATE TABLE t3( + c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, + c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, + c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, + c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, + c40, c41, c42, c43, c44, c45, c46, c47, c48, c49, + c50, c51, c52, c53, c54, c55, c56, c57, c58, c59, + c60, c61, c62, c63, c64, c65 + ); + CREATE TABLE t3_changes(colnum, oldval, newval); + INSERT INTO t3 VALUES( + 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', + 'a10','a11','a12','a13','a14','a15','a16','a17','a18','a19', + 'a20','a21','a22','a23','a24','a25','a26','a27','a28','a29', + 'a30','a31','a32','a33','a34','a35','a36','a37','a38','a39', + 'a40','a41','a42','a43','a44','a45','a46','a47','a48','a49', + 'a50','a51','a52','a53','a54','a55','a56','a57','a58','a59', + 'a60','a61','a62','a63','a64','a65' + ); + } + for {set i 0} {$i<=65} {incr i} { + set sql [subst { + CREATE TRIGGER t3c$i AFTER UPDATE ON t3 + WHEN old.c$i!=new.c$i BEGIN + INSERT INTO t3_changes VALUES($i, old.c$i, new.c$i); + END + }] + db eval $sql + } + execsql { + SELECT * FROM t3_changes + } +} {} +for {set i 0} {$i<=64} {incr i} { + do_test triggerB-3.2.$i.1 [subst { + execsql { + UPDATE t3 SET c$i='b$i'; + SELECT * FROM t3_changes ORDER BY rowid DESC LIMIT 1; + } + }] [subst {$i a$i b$i}] + do_test triggerB-3.2.$i.2 [subst { + execsql { + SELECT count(*) FROM t3_changes + } + }] [expr {$i+1}] + do_test triggerB-3.2.$i.2 [subst { + execsql { + SELECT * FROM t3_changes WHERE colnum=$i + } + }] [subst {$i a$i b$i}] +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/triggerC.test b/components/external/SQLite-3.8.1/test/triggerC.test new file mode 100644 index 0000000000000000000000000000000000000000..8d9848794ad65eef345157f71a0290b86117100f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/triggerC.test @@ -0,0 +1,996 @@ +# 2009 August 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice', here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +#------------------------------------------------------------------------- +# Test organization: +# +# triggerC-1.*: Haphazardly designed trigger related tests that were useful +# during an upgrade of the triggers sub-system. +# +# triggerC-2.*: +# +# triggerC-3.*: +# +# triggerC-4.*: +# +# triggerC-5.*: Test that when recursive triggers are enabled DELETE +# triggers are fired when rows are deleted as part of OR +# REPLACE conflict resolution. And that they are not fired +# if recursive triggers are not enabled. +# +# triggerC-6.*: Test that the recursive_triggers pragma returns correct +# results when invoked without an argument. +# + +# Enable recursive triggers for this file. +# +execsql { PRAGMA recursive_triggers = on } + +#sqlite3_db_config_lookaside db 0 0 0 + +#------------------------------------------------------------------------- +# This block of tests, triggerC-1.*, are not aimed at any specific +# property of the triggers sub-system. They were created to debug +# specific problems while modifying SQLite to support recursive +# triggers. They are left here in case they can help debug the +# same problems again. +# +do_test triggerC-1.1 { + execsql { + CREATE TABLE t1(a, b, c); + CREATE TABLE log(t, a1, b1, c1, a2, b2, c2); + CREATE TRIGGER trig1 BEFORE INSERT ON t1 BEGIN + INSERT INTO log VALUES('before', NULL, NULL, NULL, new.a, new.b, new.c); + END; + CREATE TRIGGER trig2 AFTER INSERT ON t1 BEGIN + INSERT INTO log VALUES('after', NULL, NULL, NULL, new.a, new.b, new.c); + END; + CREATE TRIGGER trig3 BEFORE UPDATE ON t1 BEGIN + INSERT INTO log VALUES('before', old.a,old.b,old.c, new.a,new.b,new.c); + END; + CREATE TRIGGER trig4 AFTER UPDATE ON t1 BEGIN + INSERT INTO log VALUES('after', old.a,old.b,old.c, new.a,new.b,new.c); + END; + + CREATE TRIGGER trig5 BEFORE DELETE ON t1 BEGIN + INSERT INTO log VALUES('before', old.a,old.b,old.c, NULL,NULL,NULL); + END; + CREATE TRIGGER trig6 AFTER DELETE ON t1 BEGIN + INSERT INTO log VALUES('after', old.a,old.b,old.c, NULL,NULL,NULL); + END; + } +} {} +do_test triggerC-1.2 { + execsql { + INSERT INTO t1 VALUES('A', 'B', 'C'); + SELECT * FROM log; + } +} {before {} {} {} A B C after {} {} {} A B C} +do_test triggerC-1.3 { + execsql { SELECT * FROM t1 } +} {A B C} +do_test triggerC-1.4 { + execsql { + DELETE FROM log; + UPDATE t1 SET a = 'a'; + SELECT * FROM log; + } +} {before A B C a B C after A B C a B C} +do_test triggerC-1.5 { + execsql { SELECT * FROM t1 } +} {a B C} +do_test triggerC-1.6 { + execsql { + DELETE FROM log; + DELETE FROM t1; + SELECT * FROM log; + } +} {before a B C {} {} {} after a B C {} {} {}} +do_test triggerC-1.7 { + execsql { SELECT * FROM t1 } +} {} +do_test triggerC-1.8 { + execsql { + CREATE TABLE t4(a, b); + CREATE TRIGGER t4t AFTER DELETE ON t4 BEGIN + SELECT RAISE(ABORT, 'delete is not supported'); + END; + } +} {} +do_test triggerC-1.9 { + execsql { INSERT INTO t4 VALUES(1, 2) } + catchsql { DELETE FROM t4 } +} {1 {delete is not supported}} +do_test triggerC-1.10 { + execsql { SELECT * FROM t4 } +} {1 2} +do_test triggerC-1.11 { + execsql { + CREATE TABLE t5 (a primary key, b, c); + INSERT INTO t5 values (1, 2, 3); + CREATE TRIGGER au_tbl AFTER UPDATE ON t5 BEGIN + UPDATE OR IGNORE t5 SET a = new.a, c = 10; + END; + } +} {} +do_test triggerC-1.12 { + catchsql { UPDATE OR REPLACE t5 SET a = 4 WHERE a = 1 } +} {1 {too many levels of trigger recursion}} +do_test triggerC-1.13 { + execsql { + CREATE TABLE t6(a INTEGER PRIMARY KEY, b); + INSERT INTO t6 VALUES(1, 2); + create trigger r1 after update on t6 for each row begin + SELECT 1; + end; + UPDATE t6 SET a=a; + } +} {} +do_test triggerC-1.14 { + execsql { + DROP TABLE t1; + CREATE TABLE cnt(n); + INSERT INTO cnt VALUES(0); + CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE, c, d, e); + CREATE INDEX t1cd ON t1(c,d); + CREATE TRIGGER t1r1 AFTER UPDATE ON t1 BEGIN UPDATE cnt SET n=n+1; END; + INSERT INTO t1 VALUES(1,2,3,4,5); + INSERT INTO t1 VALUES(6,7,8,9,10); + INSERT INTO t1 VALUES(11,12,13,14,15); + } +} {} +do_test triggerC-1.15 { + catchsql { UPDATE OR ROLLBACK t1 SET a=100 } +} {1 {PRIMARY KEY must be unique}} + + +#------------------------------------------------------------------------- +# This block of tests, triggerC-2.*, tests that recursive trigger +# programs (triggers that fire themselves) work. More specifically, +# this block focuses on recursive INSERT triggers. +# +do_test triggerC-2.1.0 { + execsql { + CREATE TABLE t2(a PRIMARY KEY); + } +} {} + +foreach {n tdefn rc} { + 1 { + CREATE TRIGGER t2_trig AFTER INSERT ON t2 WHEN (new.a>0) BEGIN + INSERT INTO t2 VALUES(new.a - 1); + END; + } {0 {10 9 8 7 6 5 4 3 2 1 0}} + + 2 { + CREATE TRIGGER t2_trig AFTER INSERT ON t2 BEGIN + SELECT CASE WHEN new.a==2 THEN RAISE(IGNORE) ELSE NULL END; + INSERT INTO t2 VALUES(new.a - 1); + END; + } {0 {10 9 8 7 6 5 4 3 2}} + + 3 { + CREATE TRIGGER t2_trig BEFORE INSERT ON t2 WHEN (new.a>0) BEGIN + INSERT INTO t2 VALUES(new.a - 1); + END; + } {0 {0 1 2 3 4 5 6 7 8 9 10}} + + 4 { + CREATE TRIGGER t2_trig BEFORE INSERT ON t2 BEGIN + SELECT CASE WHEN new.a==2 THEN RAISE(IGNORE) ELSE NULL END; + INSERT INTO t2 VALUES(new.a - 1); + END; + } {0 {3 4 5 6 7 8 9 10}} + + 5 { + CREATE TRIGGER t2_trig BEFORE INSERT ON t2 BEGIN + INSERT INTO t2 VALUES(new.a - 1); + END; + } {1 {too many levels of trigger recursion}} + + 6 { + CREATE TRIGGER t2_trig AFTER INSERT ON t2 WHEN (new.a>0) BEGIN + INSERT OR IGNORE INTO t2 VALUES(new.a); + END; + } {0 10} + + 7 { + CREATE TRIGGER t2_trig BEFORE INSERT ON t2 WHEN (new.a>0) BEGIN + INSERT OR IGNORE INTO t2 VALUES(new.a); + END; + } {1 {too many levels of trigger recursion}} +} { + do_test triggerC-2.1.$n { + catchsql { DROP TRIGGER t2_trig } + execsql { DELETE FROM t2 } + execsql $tdefn + catchsql { + INSERT INTO t2 VALUES(10); + SELECT * FROM t2 ORDER BY rowid; + } + } $rc +} + +do_test triggerC-2.2 { + execsql " + CREATE TABLE t22(x); + + CREATE TRIGGER t22a AFTER INSERT ON t22 BEGIN + INSERT INTO t22 SELECT x + (SELECT max(x) FROM t22) FROM t22; + END; + CREATE TRIGGER t22b BEFORE INSERT ON t22 BEGIN + SELECT CASE WHEN (SELECT count(*) FROM t22) >= [expr $SQLITE_MAX_TRIGGER_DEPTH / 2] + THEN RAISE(IGNORE) + ELSE NULL END; + END; + + INSERT INTO t22 VALUES(1); + SELECT count(*) FROM t22; + " +} [list [expr $SQLITE_MAX_TRIGGER_DEPTH / 2]] + +do_test triggerC-2.3 { + execsql " + CREATE TABLE t23(x PRIMARY KEY); + + CREATE TRIGGER t23a AFTER INSERT ON t23 BEGIN + INSERT INTO t23 VALUES(new.x + 1); + END; + + CREATE TRIGGER t23b BEFORE INSERT ON t23 BEGIN + SELECT CASE WHEN new.x>[expr $SQLITE_MAX_TRIGGER_DEPTH / 2] + THEN RAISE(IGNORE) + ELSE NULL END; + END; + + INSERT INTO t23 VALUES(1); + SELECT count(*) FROM t23; + " +} [list [expr $SQLITE_MAX_TRIGGER_DEPTH / 2]] + + +#----------------------------------------------------------------------- +# This block of tests, triggerC-3.*, test that SQLite throws an exception +# when it detects excessive recursion. +# +do_test triggerC-3.1.1 { + execsql { + CREATE TABLE t3(a, b); + CREATE TRIGGER t3i AFTER INSERT ON t3 BEGIN + DELETE FROM t3 WHERE rowid = new.rowid; + END; + CREATE TRIGGER t3d AFTER DELETE ON t3 BEGIN + INSERT INTO t3 VALUES(old.a, old.b); + END; + } +} {} +do_test triggerC-3.1.2 { + catchsql { INSERT INTO t3 VALUES(0,0) } +} {1 {too many levels of trigger recursion}} +do_test triggerC-3.1.3 { + execsql { SELECT * FROM t3 } +} {} + +do_test triggerC-3.2.1 { + execsql " + CREATE TABLE t3b(x); + CREATE TRIGGER t3bi AFTER INSERT ON t3b WHEN new.x<[expr $SQLITE_MAX_TRIGGER_DEPTH * 2] BEGIN + INSERT INTO t3b VALUES(new.x+1); + END; + " + catchsql { + INSERT INTO t3b VALUES(1); + } +} {1 {too many levels of trigger recursion}} +do_test triggerC-3.2.2 { + db eval {SELECT * FROM t3b} +} {} + +do_test triggerC-3.3.1 { + catchsql " + INSERT INTO t3b VALUES([expr $SQLITE_MAX_TRIGGER_DEPTH + 1]); + " +} {0 {}} +do_test triggerC-3.3.2 { + db eval {SELECT count(*), max(x), min(x) FROM t3b} +} [list $SQLITE_MAX_TRIGGER_DEPTH [expr $SQLITE_MAX_TRIGGER_DEPTH * 2] [expr $SQLITE_MAX_TRIGGER_DEPTH + 1]] + +do_test triggerC-3.4.1 { + catchsql " + DELETE FROM t3b; + INSERT INTO t3b VALUES([expr $SQLITE_MAX_TRIGGER_DEPTH - 1]); + " +} {1 {too many levels of trigger recursion}} +do_test triggerC-3.4.2 { + db eval {SELECT count(*), max(x), min(x) FROM t3b} +} {0 {} {}} + +do_test triggerC-3.5.1 { + sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH [expr $SQLITE_MAX_TRIGGER_DEPTH / 10] + catchsql " + INSERT INTO t3b VALUES([expr ($SQLITE_MAX_TRIGGER_DEPTH * 2) - ($SQLITE_MAX_TRIGGER_DEPTH / 10) + 1]); + " +} {0 {}} +do_test triggerC-3.5.2 { + db eval {SELECT count(*), max(x), min(x) FROM t3b} +} [list [expr $SQLITE_MAX_TRIGGER_DEPTH / 10] [expr $SQLITE_MAX_TRIGGER_DEPTH * 2] [expr ($SQLITE_MAX_TRIGGER_DEPTH * 2) - ($SQLITE_MAX_TRIGGER_DEPTH / 10) + 1]] + +do_test triggerC-3.5.3 { + catchsql " + DELETE FROM t3b; + INSERT INTO t3b VALUES([expr ($SQLITE_MAX_TRIGGER_DEPTH * 2) - ($SQLITE_MAX_TRIGGER_DEPTH / 10)]); + " +} {1 {too many levels of trigger recursion}} +do_test triggerC-3.5.4 { + db eval {SELECT count(*), max(x), min(x) FROM t3b} +} {0 {} {}} + +do_test triggerC-3.6.1 { + sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH 1 + catchsql " + INSERT INTO t3b VALUES([expr $SQLITE_MAX_TRIGGER_DEPTH * 2]); + " +} {0 {}} +do_test triggerC-3.6.2 { + db eval {SELECT count(*), max(x), min(x) FROM t3b} +} [list 1 [expr $SQLITE_MAX_TRIGGER_DEPTH * 2] [expr $SQLITE_MAX_TRIGGER_DEPTH * 2]] + +do_test triggerC-3.6.3 { + catchsql " + DELETE FROM t3b; + INSERT INTO t3b VALUES([expr ($SQLITE_MAX_TRIGGER_DEPTH * 2) - 1]); + " +} {1 {too many levels of trigger recursion}} +do_test triggerC-3.6.4 { + db eval {SELECT count(*), max(x), min(x) FROM t3b} +} {0 {} {}} +sqlite3_limit db SQLITE_LIMIT_TRIGGER_DEPTH $SQLITE_MAX_TRIGGER_DEPTH + + +#----------------------------------------------------------------------- +# This next block of tests, triggerC-4.*, checks that affinity +# transformations and constraint processing is performed at the correct +# times relative to BEFORE and AFTER triggers. +# +# For an INSERT statement, for each row to be inserted: +# +# 1. Apply affinities to non-rowid values to be inserted. +# 2. Fire BEFORE triggers. +# 3. Process constraints. +# 4. Insert new record. +# 5. Fire AFTER triggers. +# +# If the value of the rowid field is to be automatically assigned, it is +# set to -1 in the new.* record. Even if it is explicitly set to NULL +# by the INSERT statement. +# +# For an UPDATE statement, for each row to be deleted: +# +# 1. Apply affinities to non-rowid values to be inserted. +# 2. Fire BEFORE triggers. +# 3. Process constraints. +# 4. Insert new record. +# 5. Fire AFTER triggers. +# +# For a DELETE statement, for each row to be deleted: +# +# 1. Fire BEFORE triggers. +# 2. Remove database record. +# 3. Fire AFTER triggers. +# +# When a numeric value that as an exact integer representation is stored +# in a column with REAL affinity, it is actually stored as an integer. +# These tests check that the typeof() such values is always 'real', +# not 'integer'. +# +# triggerC-4.1.*: Check that affinity transformations are made before +# triggers are invoked. +# +do_test triggerC-4.1.1 { + catchsql { DROP TABLE log } + catchsql { DROP TABLE t4 } + execsql { + CREATE TABLE log(t); + CREATE TABLE t4(a TEXT,b INTEGER,c REAL); + CREATE TRIGGER t4bi BEFORE INSERT ON t4 BEGIN + INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' || + new.a || ' ' || typeof(new.a) || ' ' || + new.b || ' ' || typeof(new.b) || ' ' || + new.c || ' ' || typeof(new.c) + ); + END; + CREATE TRIGGER t4ai AFTER INSERT ON t4 BEGIN + INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' || + new.a || ' ' || typeof(new.a) || ' ' || + new.b || ' ' || typeof(new.b) || ' ' || + new.c || ' ' || typeof(new.c) + ); + END; + CREATE TRIGGER t4bd BEFORE DELETE ON t4 BEGIN + INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' || + old.a || ' ' || typeof(old.a) || ' ' || + old.b || ' ' || typeof(old.b) || ' ' || + old.c || ' ' || typeof(old.c) + ); + END; + CREATE TRIGGER t4ad AFTER DELETE ON t4 BEGIN + INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' || + old.a || ' ' || typeof(old.a) || ' ' || + old.b || ' ' || typeof(old.b) || ' ' || + old.c || ' ' || typeof(old.c) + ); + END; + CREATE TRIGGER t4bu BEFORE UPDATE ON t4 BEGIN + INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' || + old.a || ' ' || typeof(old.a) || ' ' || + old.b || ' ' || typeof(old.b) || ' ' || + old.c || ' ' || typeof(old.c) + ); + INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' || + new.a || ' ' || typeof(new.a) || ' ' || + new.b || ' ' || typeof(new.b) || ' ' || + new.c || ' ' || typeof(new.c) + ); + END; + CREATE TRIGGER t4au AFTER UPDATE ON t4 BEGIN + INSERT INTO log VALUES(old.rowid || ' ' || typeof(old.rowid) || ' ' || + old.a || ' ' || typeof(old.a) || ' ' || + old.b || ' ' || typeof(old.b) || ' ' || + old.c || ' ' || typeof(old.c) + ); + INSERT INTO log VALUES(new.rowid || ' ' || typeof(new.rowid) || ' ' || + new.a || ' ' || typeof(new.a) || ' ' || + new.b || ' ' || typeof(new.b) || ' ' || + new.c || ' ' || typeof(new.c) + ); + END; + } +} {} +foreach {n insert log} { + + 2 { + INSERT INTO t4 VALUES('1', '1', '1'); + DELETE FROM t4; + } { + -1 integer 1 text 1 integer 1.0 real + 1 integer 1 text 1 integer 1.0 real + 1 integer 1 text 1 integer 1.0 real + 1 integer 1 text 1 integer 1.0 real + } + + 3 { + INSERT INTO t4(rowid,a,b,c) VALUES(45, 45, 45, 45); + DELETE FROM t4; + } { + 45 integer 45 text 45 integer 45.0 real + 45 integer 45 text 45 integer 45.0 real + 45 integer 45 text 45 integer 45.0 real + 45 integer 45 text 45 integer 45.0 real + } + + 4 { + INSERT INTO t4(rowid,a,b,c) VALUES(-42.0, -42.0, -42.0, -42.0); + DELETE FROM t4; + } { + -42 integer -42.0 text -42 integer -42.0 real + -42 integer -42.0 text -42 integer -42.0 real + -42 integer -42.0 text -42 integer -42.0 real + -42 integer -42.0 text -42 integer -42.0 real + } + + 5 { + INSERT INTO t4(rowid,a,b,c) VALUES(NULL, -42.4, -42.4, -42.4); + DELETE FROM t4; + } { + -1 integer -42.4 text -42.4 real -42.4 real + 1 integer -42.4 text -42.4 real -42.4 real + 1 integer -42.4 text -42.4 real -42.4 real + 1 integer -42.4 text -42.4 real -42.4 real + } + + 6 { + INSERT INTO t4 VALUES(7, 7, 7); + UPDATE t4 SET a=8, b=8, c=8; + } { + -1 integer 7 text 7 integer 7.0 real + 1 integer 7 text 7 integer 7.0 real + 1 integer 7 text 7 integer 7.0 real + 1 integer 8 text 8 integer 8.0 real + 1 integer 7 text 7 integer 7.0 real + 1 integer 8 text 8 integer 8.0 real + } + + 7 { + UPDATE t4 SET rowid=2; + } { + 1 integer 8 text 8 integer 8.0 real + 2 integer 8 text 8 integer 8.0 real + 1 integer 8 text 8 integer 8.0 real + 2 integer 8 text 8 integer 8.0 real + } + + 8 { + UPDATE t4 SET a='9', b='9', c='9'; + } { + 2 integer 8 text 8 integer 8.0 real + 2 integer 9 text 9 integer 9.0 real + 2 integer 8 text 8 integer 8.0 real + 2 integer 9 text 9 integer 9.0 real + } + + 9 { + UPDATE t4 SET a='9.1', b='9.1', c='9.1'; + } { + 2 integer 9 text 9 integer 9.0 real + 2 integer 9.1 text 9.1 real 9.1 real + 2 integer 9 text 9 integer 9.0 real + 2 integer 9.1 text 9.1 real 9.1 real + } +} { + do_test triggerC-4.1.$n { + eval concat [execsql " + DELETE FROM log; + $insert ; + SELECT * FROM log ORDER BY rowid; + "] + } [join $log " "] +} + +#------------------------------------------------------------------------- +# This block of tests, triggerC-5.*, test that DELETE triggers are fired +# if a row is deleted as a result of OR REPLACE conflict resolution. +# +do_test triggerC-5.1.0 { + execsql { + DROP TABLE IF EXISTS t5; + CREATE TABLE t5(a INTEGER PRIMARY KEY, b); + CREATE UNIQUE INDEX t5i ON t5(b); + INSERT INTO t5 VALUES(1, 'a'); + INSERT INTO t5 VALUES(2, 'b'); + INSERT INTO t5 VALUES(3, 'c'); + + CREATE TABLE t5g(a, b, c); + CREATE TRIGGER t5t BEFORE DELETE ON t5 BEGIN + INSERT INTO t5g VALUES(old.a, old.b, (SELECT count(*) FROM t5)); + END; + } +} {} +foreach {n dml t5g t5} { + 1 "DELETE FROM t5 WHERE a=2" {2 b 3} {1 a 3 c} + 2 "INSERT OR REPLACE INTO t5 VALUES(2, 'd')" {2 b 3} {1 a 2 d 3 c} + 3 "UPDATE OR REPLACE t5 SET a = 2 WHERE a = 3" {2 b 3} {1 a 2 c} + 4 "INSERT OR REPLACE INTO t5 VALUES(4, 'b')" {2 b 3} {1 a 3 c 4 b} + 5 "UPDATE OR REPLACE t5 SET b = 'b' WHERE b = 'c'" {2 b 3} {1 a 3 b} + 6 "INSERT OR REPLACE INTO t5 VALUES(2, 'c')" {2 b 3 3 c 2} {1 a 2 c} + 7 "UPDATE OR REPLACE t5 SET a=1, b='b' WHERE a = 3" {1 a 3 2 b 2} {1 b} +} { + do_test triggerC-5.1.$n { + execsql " + BEGIN; + $dml ; + SELECT * FROM t5g ORDER BY rowid; + SELECT * FROM t5 ORDER BY rowid; + ROLLBACK; + " + } [concat $t5g $t5] +} +do_test triggerC-5.2.0 { + execsql { + DROP TRIGGER t5t; + CREATE TRIGGER t5t AFTER DELETE ON t5 BEGIN + INSERT INTO t5g VALUES(old.a, old.b, (SELECT count(*) FROM t5)); + END; + } +} {} +foreach {n dml t5g t5} { + 1 "DELETE FROM t5 WHERE a=2" {2 b 2} {1 a 3 c} + 2 "INSERT OR REPLACE INTO t5 VALUES(2, 'd')" {2 b 2} {1 a 2 d 3 c} + 3 "UPDATE OR REPLACE t5 SET a = 2 WHERE a = 3" {2 b 2} {1 a 2 c} + 4 "INSERT OR REPLACE INTO t5 VALUES(4, 'b')" {2 b 2} {1 a 3 c 4 b} + 5 "UPDATE OR REPLACE t5 SET b = 'b' WHERE b = 'c'" {2 b 2} {1 a 3 b} + 6 "INSERT OR REPLACE INTO t5 VALUES(2, 'c')" {2 b 2 3 c 1} {1 a 2 c} + 7 "UPDATE OR REPLACE t5 SET a=1, b='b' WHERE a = 3" {1 a 2 2 b 1} {1 b} +} { + do_test triggerC-5.2.$n { + execsql " + BEGIN; + $dml ; + SELECT * FROM t5g ORDER BY rowid; + SELECT * FROM t5 ORDER BY rowid; + ROLLBACK; + " + } [concat $t5g $t5] +} +do_test triggerC-5.3.0 { + execsql { PRAGMA recursive_triggers = off } +} {} +foreach {n dml t5g t5} { + 1 "DELETE FROM t5 WHERE a=2" {2 b 2} {1 a 3 c} + 2 "INSERT OR REPLACE INTO t5 VALUES(2, 'd')" {} {1 a 2 d 3 c} + 3 "UPDATE OR REPLACE t5 SET a = 2 WHERE a = 3" {} {1 a 2 c} + 4 "INSERT OR REPLACE INTO t5 VALUES(4, 'b')" {} {1 a 3 c 4 b} + 5 "UPDATE OR REPLACE t5 SET b = 'b' WHERE b = 'c'" {} {1 a 3 b} + 6 "INSERT OR REPLACE INTO t5 VALUES(2, 'c')" {} {1 a 2 c} + 7 "UPDATE OR REPLACE t5 SET a=1, b='b' WHERE a = 3" {} {1 b} +} { + do_test triggerC-5.3.$n { + execsql " + BEGIN; + $dml ; + SELECT * FROM t5g ORDER BY rowid; + SELECT * FROM t5 ORDER BY rowid; + ROLLBACK; + " + } [concat $t5g $t5] +} +do_test triggerC-5.3.8 { + execsql { PRAGMA recursive_triggers = on } +} {} + +#------------------------------------------------------------------------- +# This block of tests, triggerC-6.*, tests that "PRAGMA recursive_triggers" +# statements return the current value of the recursive triggers flag. +# +do_test triggerC-6.1 { + execsql { PRAGMA recursive_triggers } +} {1} +do_test triggerC-6.2 { + execsql { + PRAGMA recursive_triggers = off; + PRAGMA recursive_triggers; + } +} {0} +do_test triggerC-6.3 { + execsql { + PRAGMA recursive_triggers = on; + PRAGMA recursive_triggers; + } +} {1} + +#------------------------------------------------------------------------- +# Test some of the "undefined behaviour" associated with triggers. The +# undefined behaviour occurs when a row being updated or deleted is +# manipulated by a BEFORE trigger. +# +do_test triggerC-7.1 { + execsql { + CREATE TABLE t8(x); + CREATE TABLE t7(a, b); + INSERT INTO t7 VALUES(1, 2); + INSERT INTO t7 VALUES(3, 4); + INSERT INTO t7 VALUES(5, 6); + CREATE TRIGGER t7t BEFORE UPDATE ON t7 BEGIN + DELETE FROM t7 WHERE a = 1; + END; + CREATE TRIGGER t7ta AFTER UPDATE ON t7 BEGIN + INSERT INTO t8 VALUES('after fired ' || old.rowid || '->' || new.rowid); + END; + } +} {} +do_test triggerC-7.2 { + execsql { + BEGIN; + UPDATE t7 SET b=7 WHERE a = 5; + SELECT * FROM t7; + SELECT * FROM t8; + ROLLBACK; + } +} {3 4 5 7 {after fired 3->3}} +do_test triggerC-7.3 { + execsql { + BEGIN; + UPDATE t7 SET b=7 WHERE a = 1; + SELECT * FROM t7; + SELECT * FROM t8; + ROLLBACK; + } +} {3 4 5 6} + +do_test triggerC-7.4 { + execsql { + DROP TRIGGER t7t; + CREATE TRIGGER t7t BEFORE UPDATE ON t7 WHEN (old.rowid!=1 OR new.rowid!=8) + BEGIN + UPDATE t7 set rowid = 8 WHERE rowid=1; + END; + } +} {} +do_test triggerC-7.5 { + execsql { + BEGIN; + UPDATE t7 SET b=7 WHERE a = 5; + SELECT rowid, * FROM t7; + SELECT * FROM t8; + ROLLBACK; + } +} {2 3 4 3 5 7 8 1 2 {after fired 1->8} {after fired 3->3}} +do_test triggerC-7.6 { + execsql { + BEGIN; + UPDATE t7 SET b=7 WHERE a = 1; + SELECT rowid, * FROM t7; + SELECT * FROM t8; + ROLLBACK; + } +} {2 3 4 3 5 6 8 1 2 {after fired 1->8}} + +do_test triggerC-7.7 { + execsql { + DROP TRIGGER t7t; + DROP TRIGGER t7ta; + CREATE TRIGGER t7t BEFORE DELETE ON t7 BEGIN + UPDATE t7 set rowid = 8 WHERE rowid=1; + END; + CREATE TRIGGER t7ta AFTER DELETE ON t7 BEGIN + INSERT INTO t8 VALUES('after fired ' || old.rowid); + END; + } +} {} +do_test triggerC-7.8 { + execsql { + BEGIN; + DELETE FROM t7 WHERE a = 3; + SELECT rowid, * FROM t7; + SELECT * FROM t8; + ROLLBACK; + } +} {3 5 6 8 1 2 {after fired 2}} +do_test triggerC-7.9 { + execsql { + BEGIN; + DELETE FROM t7 WHERE a = 1; + SELECT rowid, * FROM t7; + SELECT * FROM t8; + ROLLBACK; + } +} {2 3 4 3 5 6 8 1 2} + +# Ticket [e25d9ea771febc9c311928c1c01c3163dcb26643] +# +do_test triggerC-9.1 { + execsql { + CREATE TABLE t9(a,b); + CREATE INDEX t9b ON t9(b); + INSERT INTO t9 VALUES(1,0); + INSERT INTO t9 VALUES(2,1); + INSERT INTO t9 VALUES(3,2); + INSERT INTO t9 SELECT a+3, a+2 FROM t9; + INSERT INTO t9 SELECT a+6, a+5 FROM t9; + SELECT a FROM t9 ORDER BY a; + } +} {1 2 3 4 5 6 7 8 9 10 11 12} +do_test triggerC-9.2 { + execsql { + CREATE TRIGGER t9r1 AFTER DELETE ON t9 BEGIN + DELETE FROM t9 WHERE b=old.a; + END; + DELETE FROM t9 WHERE b=4; + SELECT a FROM t9 ORDER BY a; + } +} {1 2 3 4} + +# At one point (between versions 3.6.18 and 3.6.20 inclusive), an UPDATE +# that fired a BEFORE trigger that itself updated the same row as the +# statement causing it to fire was causing a strange side-effect: The +# values updated by the statement within the trigger were being overwritten +# by the values in the new.* array, even if those values were not +# themselves written by the parent UPDATE statement. +# +# Technically speaking this was not a bug. The SQLite documentation says +# that if a BEFORE UPDATE or BEFORE DELETE trigger modifies or deletes the +# row that the parent statement is operating on the results are undefined. +# But as of 3.6.21 behaviour is restored to the way it was in versions +# 3.6.17 and earlier to avoid causing unnecessary difficulties. +# +do_test triggerC-10.1 { + execsql { + CREATE TABLE t10(a, updatecnt DEFAULT 0); + CREATE TRIGGER t10_bu BEFORE UPDATE OF a ON t10 BEGIN + UPDATE t10 SET updatecnt = updatecnt+1 WHERE rowid = old.rowid; + END; + INSERT INTO t10(a) VALUES('hello'); + } + + # Before the problem was fixed, table t10 would contain the tuple + # (world, 0) after running the following script (because the value + # 1 written to column "updatecnt" was clobbered by the old value 0). + # + execsql { + UPDATE t10 SET a = 'world'; + SELECT * FROM t10; + } +} {world 1} + +do_test triggerC-10.2 { + execsql { + UPDATE t10 SET a = 'tcl', updatecnt = 5; + SELECT * FROM t10; + } +} {tcl 5} + +do_test triggerC-10.3 { + execsql { + CREATE TABLE t11( + c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, + c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, + c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, + c31, c32, c33, c34, c35, c36, c37, c38, c39, c40 + ); + + CREATE TRIGGER t11_bu BEFORE UPDATE OF c1 ON t11 BEGIN + UPDATE t11 SET c31 = c31+1, c32=c32+1 WHERE rowid = old.rowid; + END; + + INSERT INTO t11 VALUES( + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 + ); + } + + # Before the problem was fixed, table t10 would contain the tuple + # (world, 0) after running the following script (because the value + # 1 written to column "updatecnt" was clobbered by the old value 0). + # + execsql { + UPDATE t11 SET c4=35, c33=22, c1=5; + SELECT * FROM t11; + } +} {5 2 3 35 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 32 33 22 34 35 36 37 38 39 40} + +#------------------------------------------------------------------------- +# Test that bug [371bab5d65] has been fixed. BEFORE INSERT and INSTEAD OF +# INSERT triggers with the DEFAULT VALUES INSERT syntax. +# +do_test triggerC-11.0 { + catchsql { DROP TABLE log } + execsql { CREATE TABLE log(a, b) } +} {} + +foreach {testno tbl defaults} { + 1 "CREATE TABLE t1(a, b)" {{} {}} + 2 "CREATE TABLE t1(a DEFAULT 1, b DEFAULT 'abc')" {1 abc} + 3 "CREATE TABLE t1(a, b DEFAULT 4.5)" {{} 4.5} +} { + do_test triggerC-11.$testno.1 { + catchsql { DROP TABLE t1 } + execsql { DELETE FROM log } + execsql $tbl + execsql { + CREATE TRIGGER tt1 BEFORE INSERT ON t1 BEGIN + INSERT INTO log VALUES(new.a, new.b); + END; + INSERT INTO t1 DEFAULT VALUES; + SELECT * FROM log; + } + } $defaults + + do_test triggerC-11.$testno.2 { + execsql { DELETE FROM log } + execsql { + CREATE TRIGGER tt2 AFTER INSERT ON t1 BEGIN + INSERT INTO log VALUES(new.a, new.b); + END; + INSERT INTO t1 DEFAULT VALUES; + SELECT * FROM log; + } + } [concat $defaults $defaults] + + do_test triggerC-11.$testno.3 { + execsql { DROP TRIGGER tt1 } + execsql { DELETE FROM log } + execsql { + INSERT INTO t1 DEFAULT VALUES; + SELECT * FROM log; + } + } $defaults +} +do_test triggerC-11.4 { + catchsql { DROP TABLE t2 } + execsql { + DELETE FROM log; + CREATE TABLE t2(a, b); + CREATE VIEW v2 AS SELECT * FROM t2; + CREATE TRIGGER tv2 INSTEAD OF INSERT ON v2 BEGIN + INSERT INTO log VALUES(new.a, new.b); + END; + INSERT INTO v2 DEFAULT VALUES; + SELECT a, b, a IS NULL, b IS NULL FROM log; + } +} {{} {} 1 1} + +do_test triggerC-12.1 { + db close + forcedelete test.db + sqlite3 db test.db + + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t1 VALUES(5, 6); + CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN SELECT 1 ; END ; + SELECT count(*) FROM sqlite_master; + } +} {2} +do_test triggerC-12.2 { + db eval { SELECT * FROM t1 } { + if {$a == 3} { execsql { DROP TRIGGER tr1 } } + } + execsql { SELECT count(*) FROM sqlite_master } +} {1} + +do_execsql_test triggerC-13.1 { + PRAGMA recursive_triggers = ON; + CREATE TABLE t12(a, b); + INSERT INTO t12 VALUES(1, 2); + CREATE TRIGGER tr12 AFTER UPDATE ON t12 BEGIN + UPDATE t12 SET a=new.a+1, b=new.b+1; + END; +} {} +do_catchsql_test triggerC-13.2 { + UPDATE t12 SET a=a+1, b=b+1; +} {1 {too many levels of trigger recursion}} + +#------------------------------------------------------------------------- +# The following tests seek to verify that constant values (i.e. literals) +# are not factored out of loops within trigger programs. SQLite does +# not factor constants out of loops within trigger programs as it may only +# do so in code generated before the first table or index is opened. And +# by the time a trigger program is coded, at least one table or index has +# always been opened. +# +# At one point, due to a bug allowing constant factoring within triggers, +# the following SQL would produce the wrong result. +# +set SQL { + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(a, c); + CREATE INDEX i2 ON t1(b, c); + INSERT INTO t1 VALUES(1, 2, 3); + + CREATE TABLE t2(e, f); + CREATE INDEX i3 ON t2(e); + INSERT INTO t2 VALUES(1234567, 3); + + CREATE TABLE empty(x); + CREATE TABLE not_empty(x); + INSERT INTO not_empty VALUES(2); + + CREATE TABLE t4(x); + CREATE TABLE t5(g, h, i); + + CREATE TRIGGER trig BEFORE INSERT ON t4 BEGIN + INSERT INTO t5 SELECT * FROM t1 WHERE + (a IN (SELECT x FROM empty) OR b IN (SELECT x FROM not_empty)) + AND c IN (SELECT f FROM t2 WHERE e=1234567); + END; + + INSERT INTO t4 VALUES(0); + SELECT * FROM t5; +} + +reset_db +do_execsql_test triggerC-14.1 $SQL {1 2 3} +reset_db +optimization_control db factor-constants 0 +do_execsql_test triggerC-14.2 $SQL {1 2 3} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/triggerD.test b/components/external/SQLite-3.8.1/test/triggerD.test new file mode 100644 index 0000000000000000000000000000000000000000..a5dd4bdd580467662d57f3ba759e76cd57db6dcc --- /dev/null +++ b/components/external/SQLite-3.8.1/test/triggerD.test @@ -0,0 +1,219 @@ +# 2009 December 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice', here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Verify that when columns named "rowid", "oid", and "_rowid_" appear +# in a table as ordinary columns (not as the INTEGER PRIMARY KEY) then +# the use of these columns in triggers will refer to the column and not +# to the actual ROWID. Ticket [34d2ae1c6d08b5271ba5e5592936d4a1d913ffe3] +# +# Also, verify that triggers created like this: +# +# CREATE TRIGGER attached.trig AFTER INSERT ON attached.tab ... +# +# can be reparsed as a main database. Ticket [d6ddba6706353915ceedc56b4e3] +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} + +# Triggers on tables where the table has ordinary columns named +# rowid, oid, and _rowid_. +# +do_test triggerD-1.1 { + db eval { + CREATE TABLE t1(rowid, oid, _rowid_, x); + CREATE TABLE log(a,b,c,d,e); + CREATE TRIGGER r1 BEFORE INSERT ON t1 BEGIN + INSERT INTO log VALUES('r1', new.rowid, new.oid, new._rowid_, new.x); + END; + CREATE TRIGGER r2 AFTER INSERT ON t1 BEGIN + INSERT INTO log VALUES('r2', new.rowid, new.oid, new._rowid_, new.x); + END; + CREATE TRIGGER r3 BEFORE UPDATE ON t1 BEGIN + INSERT INTO log VALUES('r3.old', old.rowid, old.oid, old._rowid_, old.x); + INSERT INTO log VALUES('r3.new', new.rowid, new.oid, new._rowid_, new.x); + END; + CREATE TRIGGER r4 AFTER UPDATE ON t1 BEGIN + INSERT INTO log VALUES('r4.old', old.rowid, old.oid, old._rowid_, old.x); + INSERT INTO log VALUES('r4.new', new.rowid, new.oid, new._rowid_, new.x); + END; + CREATE TRIGGER r5 BEFORE DELETE ON t1 BEGIN + INSERT INTO log VALUES('r5', old.rowid, old.oid, old._rowid_, old.x); + END; + CREATE TRIGGER r6 AFTER DELETE ON t1 BEGIN + INSERT INTO log VALUES('r6', old.rowid, old.oid, old._rowid_, old.x); + END; + } +} {} +do_test triggerD-1.2 { + db eval { + INSERT INTO t1 VALUES(100,200,300,400); + SELECT * FROM log + } +} {r1 100 200 300 400 r2 100 200 300 400} +do_test triggerD-1.3 { + db eval { + DELETE FROM log; + UPDATE t1 SET rowid=rowid+1; + SELECT * FROM log + } +} {r3.old 100 200 300 400 r3.new 101 200 300 400 r4.old 100 200 300 400 r4.new 101 200 300 400} +do_test triggerD-1.4 { + db eval { + DELETE FROM log; + DELETE FROM t1; + SELECT * FROM log + } +} {r5 101 200 300 400 r6 101 200 300 400} + +# Triggers on tables where the table does not have ordinary columns named +# rowid, oid, and _rowid_. +# +do_test triggerD-2.1 { + db eval { + DROP TABLE t1; + CREATE TABLE t1(w,x,y,z); + CREATE TRIGGER r1 BEFORE INSERT ON t1 BEGIN + INSERT INTO log VALUES('r1', new.rowid, new.oid, new._rowid_, new.x); + END; + CREATE TRIGGER r2 AFTER INSERT ON t1 BEGIN + INSERT INTO log VALUES('r2', new.rowid, new.oid, new._rowid_, new.x); + END; + CREATE TRIGGER r3 BEFORE UPDATE ON t1 BEGIN + INSERT INTO log VALUES('r3.old', old.rowid, old.oid, old._rowid_, old.x); + INSERT INTO log VALUES('r3.new', new.rowid, new.oid, new._rowid_, new.x); + END; + CREATE TRIGGER r4 AFTER UPDATE ON t1 BEGIN + INSERT INTO log VALUES('r4.old', old.rowid, old.oid, old._rowid_, old.x); + INSERT INTO log VALUES('r4.new', new.rowid, new.oid, new._rowid_, new.x); + END; + CREATE TRIGGER r5 BEFORE DELETE ON t1 BEGIN + INSERT INTO log VALUES('r5', old.rowid, old.oid, old._rowid_, old.x); + END; + CREATE TRIGGER r6 AFTER DELETE ON t1 BEGIN + INSERT INTO log VALUES('r6', old.rowid, old.oid, old._rowid_, old.x); + END; + } +} {} +do_test triggerD-2.2 { + db eval { + DELETE FROM log; + INSERT INTO t1 VALUES(100,200,300,400); + SELECT * FROM log; + } +} {r1 -1 -1 -1 200 r2 1 1 1 200} +do_test triggerD-2.3 { + db eval { + DELETE FROM log; + UPDATE t1 SET x=x+1; + SELECT * FROM log + } +} {r3.old 1 1 1 200 r3.new 1 1 1 201 r4.old 1 1 1 200 r4.new 1 1 1 201} +do_test triggerD-2.4 { + db eval { + DELETE FROM log; + DELETE FROM t1; + SELECT * FROM log + } +} {r5 1 1 1 201 r6 1 1 1 201} + + +########################################################################### +# +# Ticket [985771e1161200ae5eac3162686ea6711c035d08]: +# +# When both a main database table and a TEMP table have the same name, +# and a main database trigge is created on the main table, the trigger +# is incorrectly bound to the TEMP table. For example: +# +# CREATE TABLE t1(x); +# CREATE TEMP TABLE t1(x); +# CREATE TABLE t2(z); +# CREATE TRIGGER main.r1 AFTER INSERT ON t1 BEGIN +# INSERT INTO t2 VALUES(10000 + new.x); +# END; +# INSERT INTO main.t1 VALUES(3); +# INSERT INTO temp.t1 VALUES(4); +# SELECT * FROM t2; +# +# The r1 trigger fires when the value 4 is inserted into the temp.t1 +# table, rather than when value 3 is inserted into main.t1. +# +do_test triggerD-3.1 { + db eval { + CREATE TABLE t300(x); + CREATE TEMP TABLE t300(x); + CREATE TABLE t301(y); + CREATE TRIGGER main.r300 AFTER INSERT ON t300 BEGIN + INSERT INTO t301 VALUES(10000 + new.x); + END; + INSERT INTO main.t300 VALUES(3); + INSERT INTO temp.t300 VALUES(4); + SELECT * FROM t301; + } +} {10003} +do_test triggerD-3.2 { + db eval { + DELETE FROM t301; + CREATE TRIGGER temp.r301 AFTER INSERT ON t300 BEGIN + INSERT INTO t301 VALUES(20000 + new.x); + END; + INSERT INTO main.t300 VALUES(3); + INSERT INTO temp.t300 VALUES(4); + SELECT * FROM t301; + } +} {10003 20004} + + +############################################################################# +# +# Ticket [d6ddba6706353915ceedc56b4e3e72ecb4d77ba4] +# +# The following syntax really should not be allowed: +# +# CREATE TRIGGER xyz.trig BEFORE UPDATE ON xyz.tab BEGIN ... +# +# But a long-standing bug does allow it. And the "xyz.tab" slips into +# the sqlite_master table. We cannot fix the bug simply by disallowing +# "xyz.tab" since that could break legacy applications. We have to +# fix the system so that the "xyz." on "xyz.tab" is ignored. +# Verify that this is the case. +# +do_test triggerD-4.1 { + db close + forcedelete test.db test2.db + sqlite3 db test.db + db eval { + CREATE TABLE t1(x); + ATTACH 'test2.db' AS db2; + CREATE TABLE db2.t2(y); + CREATE TABLE db2.log(z); + CREATE TRIGGER db2.trig AFTER INSERT ON db2.t2 BEGIN + INSERT INTO log(z) VALUES(new.y); + END; + INSERT INTO t2 VALUES(123); + SELECT * FROM log; + } +} {123} +do_test triggerD-4.2 { + sqlite3 db2 test2.db + db2 eval { + INSERT INTO t2 VALUES(234); + SELECT * FROM log; + } +} {123 234} +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/triggerE.test b/components/external/SQLite-3.8.1/test/triggerE.test new file mode 100644 index 0000000000000000000000000000000000000000..e2727bbdcb02d75a1add08c222280e134792aec1 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/triggerE.test @@ -0,0 +1,112 @@ +# 2009 December 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice', here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file tests the effects of SQL variable references embedded in +# triggers. If the user attempts to create such a trigger, it is an +# error. However, if an existing trigger definition is read from +# the sqlite_master table, the variable reference always evaluates +# to NULL. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable {!trigger} { + finish_test + return +} +set testprefix triggerE + +do_execsql_test 1.0 { + CREATE TABLE t1(a, b); + CREATE TABLE t2(c, d); + CREATE TABLE t3(e, f); +} + +# forcedelete test.db2 +# do_execsql_test 1.1 { +# ATTACH 'test.db2' AS aux; +# CREATE TABLE aux.t4(x); +# INSERT INTO aux.t4 VALUES(5); +# +# CREATE TRIGGER tr1 AFTER INSERT ON t1 WHEN new.a IN (SELECT x FROM aux.t4) +# BEGIN +# SELECT 1; +# END; +# } +# do_execsql_test 1.2 { INSERT INTO t1 VALUES(1,1); } +# do_execsql_test 1.3 { INSERT INTO t1 VALUES(5,5); } + +#------------------------------------------------------------------------- +# Attempt to create various triggers that use bound variables. +# +set errmsg "trigger cannot use variables" +foreach {tn defn} { + 1 { AFTER INSERT ON t1 WHEN new.a = ? BEGIN SELECT 1; END; } + 2 { BEFORE DELETE ON t1 BEGIN SELECT ?; END; } + 3 { BEFORE DELETE ON t1 BEGIN SELECT * FROM (SELECT * FROM (SELECT ?)); END; } + 5 { BEFORE DELETE ON t1 BEGIN SELECT * FROM t2 GROUP BY ?; END; } + 6 { BEFORE DELETE ON t1 BEGIN SELECT * FROM t2 LIMIT ?; END; } + 7 { BEFORE DELETE ON t1 BEGIN SELECT * FROM t2 ORDER BY ?; END; } + 8 { BEFORE UPDATE ON t1 BEGIN UPDATE t2 SET c = ?; END; } + 9 { BEFORE UPDATE ON t1 BEGIN UPDATE t2 SET c = 1 WHERE d = ?; END; } +} { + catchsql {drop trigger tr1} + do_catchsql_test 1.1.$tn "CREATE TRIGGER tr1 $defn" [list 1 $errmsg] + do_catchsql_test 1.2.$tn "CREATE TEMP TRIGGER tr1 $defn" [list 1 $errmsg] +} + +#------------------------------------------------------------------------- +# Test that variable references within trigger definitions loaded from +# the sqlite_master table are automatically converted to NULL. +# +do_execsql_test 2.1 { + PRAGMA writable_schema = 1; + INSERT INTO sqlite_master VALUES('trigger', 'tr1', 't1', 0, + 'CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN + INSERT INTO t2 VALUES(?1, ?2); + END' + ); + + INSERT INTO sqlite_master VALUES('trigger', 'tr2', 't3', 0, + 'CREATE TRIGGER tr2 AFTER INSERT ON t3 WHEN ?1 IS NULL BEGIN + UPDATE t2 SET c=d WHERE c IS ?2; + END' + ); +} +db close +sqlite3 db test.db + +do_execsql_test 2.2.1 { + INSERT INTO t1 VALUES(1, 2); + SELECT * FROM t2; +} {{} {}} +do_test 2.2.2 { + set one 3 + execsql { + DELETE FROM t2; + INSERT INTO t1 VALUES($one, ?1); + SELECT * FROM t2; + } +} {{} {}} +do_execsql_test 2.2.3 { SELECT * FROM t1 } {1 2 3 3} + +do_execsql_test 2.3 { + DELETE FROM t2; + INSERT INTO t2 VALUES('x', 'y'); + INSERT INTO t2 VALUES(NULL, 'z'); + INSERT INTO t3 VALUES(1, 2); + SELECT * FROM t3; + SELECT * FROM t2; +} {1 2 x y z z} + +finish_test + + diff --git a/components/external/SQLite-3.8.1/test/tt3_checkpoint.c b/components/external/SQLite-3.8.1/test/tt3_checkpoint.c new file mode 100644 index 0000000000000000000000000000000000000000..3c28f0d3a50ac30241922592b577d5f061b0d18f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/tt3_checkpoint.c @@ -0,0 +1,150 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file is part of the test program "threadtest3". Despite being a C +** file it is not compiled separately, but included by threadtest3.c using +** the #include directive normally used with header files. +** +** This file contains the implementation of test cases: +** +** checkpoint_starvation_1 +** checkpoint_starvation_2 +*/ + +/* +** Both test cases involve 1 writer/checkpointer thread and N reader threads. +** +** Each reader thread performs a series of read transactions, one after +** another. Each read transaction lasts for 100 ms. +** +** The writer writes transactions as fast as possible. It uses a callback +** registered with sqlite3_wal_hook() to try to keep the WAL-size limited to +** around 50 pages. +** +** In test case checkpoint_starvation_1, the auto-checkpoint uses +** SQLITE_CHECKPOINT_PASSIVE. In checkpoint_starvation_2, it uses RESTART. +** The expectation is that in the first case the WAL file will grow very +** large, and in the second will be limited to the 50 pages or thereabouts. +** However, the overall transaction throughput will be lower for +** checkpoint_starvation_2, as every checkpoint will block for up to 200 ms +** waiting for readers to clear. +*/ + +/* Frame limit used by the WAL hook for these tests. */ +#define CHECKPOINT_STARVATION_FRAMELIMIT 50 + +/* Duration in ms of each read transaction */ +#define CHECKPOINT_STARVATION_READMS 100 + +struct CheckpointStarvationCtx { + int eMode; + int nMaxFrame; +}; +typedef struct CheckpointStarvationCtx CheckpointStarvationCtx; + +static int checkpoint_starvation_walhook( + void *pCtx, + sqlite3 *db, + const char *zDb, + int nFrame +){ + CheckpointStarvationCtx *p = (CheckpointStarvationCtx *)pCtx; + if( nFrame>p->nMaxFrame ){ + p->nMaxFrame = nFrame; + } + if( nFrame>=CHECKPOINT_STARVATION_FRAMELIMIT ){ + sqlite3_wal_checkpoint_v2(db, zDb, p->eMode, 0, 0); + } + return SQLITE_OK; +} + +static char *checkpoint_starvation_reader(int iTid, int iArg){ + Error err = {0}; + Sqlite db = {0}; + + opendb(&err, &db, "test.db", 0); + while( !timetostop(&err) ){ + i64 iCount1, iCount2; + sql_script(&err, &db, "BEGIN"); + iCount1 = execsql_i64(&err, &db, "SELECT count(x) FROM t1"); + usleep(CHECKPOINT_STARVATION_READMS*1000); + iCount2 = execsql_i64(&err, &db, "SELECT count(x) FROM t1"); + sql_script(&err, &db, "COMMIT"); + + if( iCount1!=iCount2 ){ + test_error(&err, "Isolation failure - %lld %lld", iCount1, iCount2); + } + } + closedb(&err, &db); + + print_and_free_err(&err); + return 0; +} + +static void checkpoint_starvation_main(int nMs, CheckpointStarvationCtx *p){ + Error err = {0}; + Sqlite db = {0}; + Threadset threads = {0}; + int nInsert = 0; + int i; + + opendb(&err, &db, "test.db", 1); + sql_script(&err, &db, + "PRAGMA page_size = 1024;" + "PRAGMA journal_mode = WAL;" + "CREATE TABLE t1(x);" + ); + + setstoptime(&err, nMs); + + for(i=0; i<4; i++){ + launch_thread(&err, &threads, checkpoint_starvation_reader, 0); + usleep(CHECKPOINT_STARVATION_READMS*1000/4); + } + + sqlite3_wal_hook(db.db, checkpoint_starvation_walhook, (void *)p); + while( !timetostop(&err) ){ + sql_script(&err, &db, "INSERT INTO t1 VALUES(randomblob(1200))"); + nInsert++; + } + + printf(" Checkpoint mode : %s\n", + p->eMode==SQLITE_CHECKPOINT_PASSIVE ? "PASSIVE" : "RESTART" + ); + printf(" Peak WAL : %d frames\n", p->nMaxFrame); + printf(" Transaction count: %d transactions\n", nInsert); + + join_all_threads(&err, &threads); + closedb(&err, &db); + print_and_free_err(&err); +} + +static void checkpoint_starvation_1(int nMs){ + Error err = {0}; + CheckpointStarvationCtx ctx = { SQLITE_CHECKPOINT_PASSIVE, 0 }; + checkpoint_starvation_main(nMs, &ctx); + if( ctx.nMaxFrame<(CHECKPOINT_STARVATION_FRAMELIMIT*10) ){ + test_error(&err, "WAL failed to grow - %d frames", ctx.nMaxFrame); + } + print_and_free_err(&err); +} + +static void checkpoint_starvation_2(int nMs){ + Error err = {0}; + CheckpointStarvationCtx ctx = { SQLITE_CHECKPOINT_RESTART, 0 }; + checkpoint_starvation_main(nMs, &ctx); + if( ctx.nMaxFrame>CHECKPOINT_STARVATION_FRAMELIMIT+10 ){ + test_error(&err, "WAL grew too large - %d frames", ctx.nMaxFrame); + } + print_and_free_err(&err); +} + + diff --git a/components/external/SQLite-3.8.1/test/types.test b/components/external/SQLite-3.8.1/test/types.test new file mode 100644 index 0000000000000000000000000000000000000000..62a8efca82d9b17e45d368ccac43bff187812a37 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/types.test @@ -0,0 +1,325 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. Specfically +# it tests that the different storage classes (integer, real, text etc.) +# all work correctly. +# +# $Id: types.test,v 1.20 2009/06/29 06:00:37 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Tests in this file are organized roughly as follows: +# +# types-1.*.*: Test that values are stored using the expected storage +# classes when various forms of literals are inserted into +# columns with different affinities. +# types-1.1.*: INSERT INTO
    VALUES(...) +# types-1.2.*: INSERT INTO
    SELECT... +# types-1.3.*: UPDATE
    SET... +# +# types-2.*.*: Check that values can be stored and retrieving using the +# various storage classes. +# types-2.1.*: INTEGER +# types-2.2.*: REAL +# types-2.3.*: NULL +# types-2.4.*: TEXT +# types-2.5.*: Records with a few different storage classes. +# +# types-3.*: Test that the '=' operator respects manifest types. +# + +# Disable encryption on the database for this test. +db close +set DB [sqlite3 db test.db; sqlite3_connection_pointer db] +sqlite3_rekey $DB {} + +# Create a table with one column for each type of affinity +do_test types-1.1.0 { + execsql { + CREATE TABLE t1(i integer, n numeric, t text, o blob); + } +} {} + +# Each element of the following list represents one test case. +# +# The first value of each sub-list is an SQL literal. The following +# four value are the storage classes that would be used if the +# literal were inserted into a column with affinity INTEGER, NUMERIC, TEXT +# or NONE, respectively. +set values { + { 5.0 integer integer text real } + { 5.1 real real text real } + { 5 integer integer text integer } + { '5.0' integer integer text text } + { '5.1' real real text text } + { '-5.0' integer integer text text } + { '-5.0' integer integer text text } + { '5' integer integer text text } + { 'abc' text text text text } + { NULL null null null null } +} +ifcapable {bloblit} { + lappend values { X'00' blob blob blob blob } +} + +# This code tests that the storage classes specified above (in the $values +# table) are correctly assigned when values are inserted using a statement +# of the form: +# +# INSERT INTO
    VALUE(); +# +set tnum 1 +foreach val $values { + set lit [lindex $val 0] + execsql "DELETE FROM t1;" + execsql "INSERT INTO t1 VALUES($lit, $lit, $lit, $lit);" + do_test types-1.1.$tnum { + execsql { + SELECT typeof(i), typeof(n), typeof(t), typeof(o) FROM t1; + } + } [lrange $val 1 end] + incr tnum +} + +# This code tests that the storage classes specified above (in the $values +# table) are correctly assigned when values are inserted using a statement +# of the form: +# +# INSERT INTO t1 SELECT .... +# +set tnum 1 +foreach val $values { + set lit [lindex $val 0] + execsql "DELETE FROM t1;" + execsql "INSERT INTO t1 SELECT $lit, $lit, $lit, $lit;" + do_test types-1.2.$tnum { + execsql { + SELECT typeof(i), typeof(n), typeof(t), typeof(o) FROM t1; + } + } [lrange $val 1 end] + incr tnum +} + +# This code tests that the storage classes specified above (in the $values +# table) are correctly assigned when values are inserted using a statement +# of the form: +# +# UPDATE
    SET = ; +# +set tnum 1 +foreach val $values { + set lit [lindex $val 0] + execsql "UPDATE t1 SET i = $lit, n = $lit, t = $lit, o = $lit;" + do_test types-1.3.$tnum { + execsql { + SELECT typeof(i), typeof(n), typeof(t), typeof(o) FROM t1; + } + } [lrange $val 1 end] + incr tnum +} + +execsql { + DROP TABLE t1; +} + +# Open the table with root-page $rootpage at the btree +# level. Return a list that is the length of each record +# in the table, in the tables default scanning order. +proc record_sizes {rootpage} { + set bt [btree_open test.db 10] + btree_begin_transaction $bt + set c [btree_cursor $bt $rootpage 0] + btree_first $c + while 1 { + lappend res [btree_payload_size $c] + if {[btree_next $c]} break + } + btree_close_cursor $c + btree_close $bt + set res +} + + +# Create a table and insert some 1-byte integers. Make sure they +# can be read back OK. These should be 3 byte records. +do_test types-2.1.1 { + execsql { + CREATE TABLE t1(a integer); + INSERT INTO t1 VALUES(0); + INSERT INTO t1 VALUES(120); + INSERT INTO t1 VALUES(-120); + } +} {} +do_test types-2.1.2 { + execsql { + SELECT a FROM t1; + } +} {0 120 -120} + +# Try some 2-byte integers (4 byte records) +do_test types-2.1.3 { + execsql { + INSERT INTO t1 VALUES(30000); + INSERT INTO t1 VALUES(-30000); + } +} {} +do_test types-2.1.4 { + execsql { + SELECT a FROM t1; + } +} {0 120 -120 30000 -30000} + +# 4-byte integers (6 byte records) +do_test types-2.1.5 { + execsql { + INSERT INTO t1 VALUES(2100000000); + INSERT INTO t1 VALUES(-2100000000); + } +} {} +do_test types-2.1.6 { + execsql { + SELECT a FROM t1; + } +} {0 120 -120 30000 -30000 2100000000 -2100000000} + +# 8-byte integers (10 byte records) +do_test types-2.1.7 { + execsql { + INSERT INTO t1 VALUES(9000000*1000000*1000000); + INSERT INTO t1 VALUES(-9000000*1000000*1000000); + } +} {} +do_test types-2.1.8 { + execsql { + SELECT a FROM t1; + } +} [list 0 120 -120 30000 -30000 2100000000 -2100000000 \ + 9000000000000000000 -9000000000000000000] + +# Check that all the record sizes are as we expected. +ifcapable legacyformat { + do_test types-2.1.9 { + set root [db eval {select rootpage from sqlite_master where name = 't1'}] + record_sizes $root + } {3 3 3 4 4 6 6 10 10} +} else { + do_test types-2.1.9 { + set root [db eval {select rootpage from sqlite_master where name = 't1'}] + record_sizes $root + } {2 3 3 4 4 6 6 10 10} +} + +# Insert some reals. These should be 10 byte records. +do_test types-2.2.1 { + execsql { + CREATE TABLE t2(a float); + INSERT INTO t2 VALUES(0.0); + INSERT INTO t2 VALUES(12345.678); + INSERT INTO t2 VALUES(-12345.678); + } +} {} +do_test types-2.2.2 { + execsql { + SELECT a FROM t2; + } +} {0.0 12345.678 -12345.678} + +# Check that all the record sizes are as we expected. +ifcapable legacyformat { + do_test types-2.2.3 { + set root [db eval {select rootpage from sqlite_master where name = 't2'}] + record_sizes $root + } {3 10 10} +} else { + do_test types-2.2.3 { + set root [db eval {select rootpage from sqlite_master where name = 't2'}] + record_sizes $root + } {2 10 10} +} + +# Insert a NULL. This should be a two byte record. +do_test types-2.3.1 { + execsql { + CREATE TABLE t3(a nullvalue); + INSERT INTO t3 VALUES(NULL); + } +} {} +do_test types-2.3.2 { + execsql { + SELECT a ISNULL FROM t3; + } +} {1} + +# Check that all the record sizes are as we expected. +do_test types-2.3.3 { + set root [db eval {select rootpage from sqlite_master where name = 't3'}] + record_sizes $root +} {2} + +# Insert a couple of strings. +do_test types-2.4.1 { + set string10 abcdefghij + set string500 [string repeat $string10 50] + set string500000 [string repeat $string10 50000] + + execsql " + CREATE TABLE t4(a string); + INSERT INTO t4 VALUES('$string10'); + INSERT INTO t4 VALUES('$string500'); + INSERT INTO t4 VALUES('$string500000'); + " +} {} +do_test types-2.4.2 { + execsql { + SELECT a FROM t4; + } +} [list $string10 $string500 $string500000] + +# Check that all the record sizes are as we expected. This is dependant on +# the database encoding. +if { $sqlite_options(utf16)==0 || [execsql {pragma encoding}] == "UTF-8" } { + do_test types-2.4.3 { + set root [db eval {select rootpage from sqlite_master where name = 't4'}] + record_sizes $root + } {12 503 500004} +} else { + do_test types-2.4.3 { + set root [db eval {select rootpage from sqlite_master where name = 't4'}] + record_sizes $root + } {22 1003 1000004} +} + +do_test types-2.5.1 { + execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + DROP TABLE t4; + CREATE TABLE t1(a, b, c); + } +} {} +do_test types-2.5.2 { + set string10 abcdefghij + set string500 [string repeat $string10 50] + set string500000 [string repeat $string10 50000] + + execsql "INSERT INTO t1 VALUES(NULL, '$string10', 4000);" + execsql "INSERT INTO t1 VALUES('$string500', 4000, NULL);" + execsql "INSERT INTO t1 VALUES(4000, NULL, '$string500000');" +} {} +do_test types-2.5.3 { + execsql { + SELECT * FROM t1; + } +} [list {} $string10 4000 $string500 4000 {} 4000 {} $string500000] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/types2.test b/components/external/SQLite-3.8.1/test/types2.test new file mode 100644 index 0000000000000000000000000000000000000000..4a70aa5fe29e6134f114e1fa1de5669e58495b7f --- /dev/null +++ b/components/external/SQLite-3.8.1/test/types2.test @@ -0,0 +1,340 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus +# of this file is testing the interaction of manifest types, type affinity +# and comparison expressions. +# +# $Id: types2.test,v 1.7 2007/02/23 03:00:45 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Tests in this file are organized roughly as follows: +# +# types2-1.*: The '=' operator in the absence of an index. +# types2-2.*: The '=' operator implemented using an index. +# types2-3.*: The '<' operator implemented using an index. +# types2-4.*: The '>' operator in the absence of an index. +# types2-5.*: The 'IN(x, y...)' operator in the absence of an index. +# types2-6.*: The 'IN(x, y...)' operator with an index. +# types2-7.*: The 'IN(SELECT...)' operator in the absence of an index. +# types2-8.*: The 'IN(SELECT...)' operator with an index. +# +# All tests test the operators using literals and columns, but no +# other types of expressions. All expressions except columns are +# handled similarly in the implementation. + +execsql { + CREATE TABLE t1( + i1 INTEGER, + i2 INTEGER, + n1 NUMERIC, + n2 NUMERIC, + t1 TEXT, + t2 TEXT, + o1 BLOB, + o2 BLOB + ); + INSERT INTO t1 VALUES(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); +} + +proc test_bool {testname vars expr res} { + if { $vars != "" } { + execsql "UPDATE t1 SET $vars" + } + + foreach {t e r} [list $testname $expr $res] {} + + do_test $t.1 "execsql {SELECT $e FROM t1}" $r + do_test $t.2 "execsql {SELECT 1 FROM t1 WHERE $expr}" [expr $r?"1":""] + do_test $t.3 "execsql {SELECT 1 FROM t1 WHERE NOT ($e)}" [expr $r?"":"1"] +} + +# Compare literals against literals. This should always use a numeric +# comparison. +# +# Changed by ticket #805: Use no affinity for literal comparisons. +# +test_bool types2-1.1 "" {500 = 500.0} 1 +test_bool types2-1.2 "" {'500' = 500.0} 0 +test_bool types2-1.3 "" {500 = '500.0'} 0 +test_bool types2-1.4 "" {'500' = '500.0'} 0 + +# Compare literals against a column with TEXT affinity +test_bool types2-1.5 {t1=500} {500 = t1} 1 +test_bool types2-1.6 {t1=500} {'500' = t1} 1 +test_bool types2-1.7 {t1=500} {500.0 = t1} 0 +test_bool types2-1.8 {t1=500} {'500.0' = t1} 0 +test_bool types2-1.9 {t1='500'} {500 = t1} 1 +test_bool types2-1.10 {t1='500'} {'500' = t1} 1 +test_bool types2-1.11 {t1='500'} {500.0 = t1} 0 +test_bool types2-1.12 {t1='500'} {'500.0' = t1} 0 + +# Compare literals against a column with NUMERIC affinity +test_bool types2-1.13 {n1=500} {500 = n1} 1 +test_bool types2-1.14 {n1=500} {'500' = n1} 1 +test_bool types2-1.15 {n1=500} {500.0 = n1} 1 +test_bool types2-1.16 {n1=500} {'500.0' = n1} 1 +test_bool types2-1.17 {n1='500'} {500 = n1} 1 +test_bool types2-1.18 {n1='500'} {'500' = n1} 1 +test_bool types2-1.19 {n1='500'} {500.0 = n1} 1 +test_bool types2-1.20 {n1='500'} {'500.0' = n1} 1 + +# Compare literals against a column with affinity NONE +test_bool types2-1.21 {o1=500} {500 = o1} 1 +test_bool types2-1.22 {o1=500} {'500' = o1} 0 +test_bool types2-1.23 {o1=500} {500.0 = o1} 1 +test_bool types2-1.24 {o1=500} {'500.0' = o1} 0 +test_bool types2-1.25 {o1='500'} {500 = o1} 0 +test_bool types2-1.26 {o1='500'} {'500' = o1} 1 +test_bool types2-1.27 {o1='500'} {500.0 = o1} 0 +test_bool types2-1.28 {o1='500'} {'500.0' = o1} 0 + +set vals [list 10 10.0 '10' '10.0' 20 20.0 '20' '20.0' 30 30.0 '30' '30.0'] +# 1 2 3 4 5 6 7 8 9 10 11 12 + +execsql { + CREATE TABLE t2(i INTEGER, n NUMERIC, t TEXT, o XBLOBY); + CREATE INDEX t2i1 ON t2(i); + CREATE INDEX t2i2 ON t2(n); + CREATE INDEX t2i3 ON t2(t); + CREATE INDEX t2i4 ON t2(o); +} +foreach v $vals { + execsql "INSERT INTO t2 VALUES($v, $v, $v, $v);" +} + +proc test_boolset {testname where set} { + set ::tb_sql "SELECT rowid FROM t2 WHERE $where" + do_test $testname { + lsort -integer [execsql $::tb_sql] + } $set +} + +test_boolset types2-2.1 {i = 10} {1 2 3 4} +test_boolset types2-2.2 {i = 10.0} {1 2 3 4} +test_boolset types2-2.3 {i = '10'} {1 2 3 4} +test_boolset types2-2.4 {i = '10.0'} {1 2 3 4} + +test_boolset types2-2.5 {n = 20} {5 6 7 8} +test_boolset types2-2.6 {n = 20.0} {5 6 7 8} +test_boolset types2-2.7 {n = '20'} {5 6 7 8} +test_boolset types2-2.8 {n = '20.0'} {5 6 7 8} + +test_boolset types2-2.9 {t = 20} {5 7} +test_boolset types2-2.10 {t = 20.0} {6 8} +test_boolset types2-2.11 {t = '20'} {5 7} +test_boolset types2-2.12 {t = '20.0'} {6 8} + +test_boolset types2-2.10 {o = 30} {9 10} +test_boolset types2-2.11 {o = 30.0} {9 10} +test_boolset types2-2.12 {o = '30'} 11 +test_boolset types2-2.13 {o = '30.0'} 12 + +test_boolset types2-3.1 {i < 20} {1 2 3 4} +test_boolset types2-3.2 {i < 20.0} {1 2 3 4} +test_boolset types2-3.3 {i < '20'} {1 2 3 4} +test_boolset types2-3.4 {i < '20.0'} {1 2 3 4} + +test_boolset types2-3.1 {n < 20} {1 2 3 4} +test_boolset types2-3.2 {n < 20.0} {1 2 3 4} +test_boolset types2-3.3 {n < '20'} {1 2 3 4} +test_boolset types2-3.4 {n < '20.0'} {1 2 3 4} + +test_boolset types2-3.1 {t < 20} {1 2 3 4} +test_boolset types2-3.2 {t < 20.0} {1 2 3 4 5 7} +test_boolset types2-3.3 {t < '20'} {1 2 3 4} +test_boolset types2-3.4 {t < '20.0'} {1 2 3 4 5 7} + +test_boolset types2-3.1 {o < 20} {1 2} +test_boolset types2-3.2 {o < 20.0} {1 2} +test_boolset types2-3.3 {o < '20'} {1 2 3 4 5 6 9 10} +test_boolset types2-3.3 {o < '20.0'} {1 2 3 4 5 6 7 9 10} + +# Compare literals against literals (always a numeric comparison). +# Change (by ticket #805): No affinity in comparisons +test_bool types2-4.1 "" {500 > 60.0} 1 +test_bool types2-4.2 "" {'500' > 60.0} 1 +test_bool types2-4.3 "" {500 > '60.0'} 0 +test_bool types2-4.4 "" {'500' > '60.0'} 0 + +# Compare literals against a column with TEXT affinity +test_bool types2-4.5 {t1=500.0} {t1 > 500} 1 +test_bool types2-4.6 {t1=500.0} {t1 > '500' } 1 +test_bool types2-4.7 {t1=500.0} {t1 > 500.0 } 0 +test_bool types2-4.8 {t1=500.0} {t1 > '500.0' } 0 +test_bool types2-4.9 {t1='500.0'} {t1 > 500 } 1 +test_bool types2-4.10 {t1='500.0'} {t1 > '500' } 1 +test_bool types2-4.11 {t1='500.0'} {t1 > 500.0 } 0 +test_bool types2-4.12 {t1='500.0'} {t1 > '500.0' } 0 + +# Compare literals against a column with NUMERIC affinity +test_bool types2-4.13 {n1=400} {500 > n1} 1 +test_bool types2-4.14 {n1=400} {'500' > n1} 1 +test_bool types2-4.15 {n1=400} {500.0 > n1} 1 +test_bool types2-4.16 {n1=400} {'500.0' > n1} 1 +test_bool types2-4.17 {n1='400'} {500 > n1} 1 +test_bool types2-4.18 {n1='400'} {'500' > n1} 1 +test_bool types2-4.19 {n1='400'} {500.0 > n1} 1 +test_bool types2-4.20 {n1='400'} {'500.0' > n1} 1 + +# Compare literals against a column with affinity NONE +test_bool types2-4.21 {o1=500} {500 > o1} 0 +test_bool types2-4.22 {o1=500} {'500' > o1} 1 +test_bool types2-4.23 {o1=500} {500.0 > o1} 0 +test_bool types2-4.24 {o1=500} {'500.0' > o1} 1 +test_bool types2-4.25 {o1='500'} {500 > o1} 0 +test_bool types2-4.26 {o1='500'} {'500' > o1} 0 +test_bool types2-4.27 {o1='500'} {500.0 > o1} 0 +test_bool types2-4.28 {o1='500'} {'500.0' > o1} 1 + +ifcapable subquery { + # types2-5.* - The 'IN (x, y....)' operator with no index. + # + # Compare literals against literals (no affinity applied) + test_bool types2-5.1 {} {(NULL IN ('10.0', 20)) ISNULL} 1 + test_bool types2-5.2 {} {10 IN ('10.0', 20)} 0 + test_bool types2-5.3 {} {'10' IN ('10.0', 20)} 0 + test_bool types2-5.4 {} {10 IN (10.0, 20)} 1 + test_bool types2-5.5 {} {'10.0' IN (10, 20)} 0 + + # Compare literals against a column with TEXT affinity + test_bool types2-5.6 {t1='10.0'} {t1 IN (10.0, 20)} 1 + test_bool types2-5.7 {t1='10.0'} {t1 IN (10, 20)} 0 + test_bool types2-5.8 {t1='10'} {t1 IN (10.0, 20)} 0 + test_bool types2-5.9 {t1='10'} {t1 IN (20, '10.0')} 0 + test_bool types2-5.10 {t1=10} {t1 IN (20, '10')} 1 + + # Compare literals against a column with NUMERIC affinity + test_bool types2-5.11 {n1='10.0'} {n1 IN (10.0, 20)} 1 + test_bool types2-5.12 {n1='10.0'} {n1 IN (10, 20)} 1 + test_bool types2-5.13 {n1='10'} {n1 IN (10.0, 20)} 1 + test_bool types2-5.14 {n1='10'} {n1 IN (20, '10.0')} 1 + test_bool types2-5.15 {n1=10} {n1 IN (20, '10')} 1 + + # Compare literals against a column with affinity NONE + test_bool types2-5.16 {o1='10.0'} {o1 IN (10.0, 20)} 0 + test_bool types2-5.17 {o1='10.0'} {o1 IN (10, 20)} 0 + test_bool types2-5.18 {o1='10'} {o1 IN (10.0, 20)} 0 + test_bool types2-5.19 {o1='10'} {o1 IN (20, '10.0')} 0 + test_bool types2-5.20 {o1=10} {o1 IN (20, '10')} 0 + test_bool types2-5.21 {o1='10.0'} {o1 IN (10, 20, '10.0')} 1 + test_bool types2-5.22 {o1='10'} {o1 IN (10.0, 20, '10')} 1 + test_bool types2-5.23 {o1=10} {n1 IN (20, '10', 10)} 1 + + # Ticket #2248: Comparisons of strings literals that look like + # numbers. + test_bool types2-5.24 {} {'1' IN ('1')} 1 + test_bool types2-5.25 {} {'2' IN (2)} 0 + test_bool types2-5.26 {} {3 IN ('3')} 0 + test_bool types2-5.27 {} {4 IN (4)} 1 + + # The affinity of columns on the right side of IN(...) is ignored. + # All values in the expression list are treated as ordinary expressions, + # even if they are columns with affinity. + test_bool types2-5.30 {t1='10'} {10 IN (5,t1,'abc')} 0 + test_bool types2-5.31 {t1='10'} {10 IN ('abc',t1,5)} 0 + test_bool types2-5.32 {t1='010'} {10 IN (5,t1,'abc')} 0 + test_bool types2-5.33 {t1='010'} {10 IN ('abc',t1,5)} 0 + test_bool types2-5.34 {t1='10'} {'10' IN (5,t1,'abc')} 1 + test_bool types2-5.35 {t1='10'} {'10' IN ('abc',t1,5)} 1 + test_bool types2-5.36 {t1='010'} {'10' IN (5,t1,'abc')} 0 + test_bool types2-5.37 {t1='010'} {'10' IN ('abc',t1,5)} 0 + + # Columns on both the left and right of IN(...). Only the column + # on the left matters. The all values on the right are treated like + # expressions. + test_bool types2-5.40 {t1='10',n1=10} {t1 IN (5,n1,11)} 1 + test_bool types2-5.41 {t1='010',n1=10} {t1 IN (5,n1,11)} 0 + test_bool types2-5.42 {t1='10',n1=10} {n1 IN (5,t1,11)} 1 + test_bool types2-5.43 {t1='010',n1=10} {n1 IN (5,t1,11)} 1 +} + +# Tests named types2-6.* use the same infrastructure as the types2-2.* +# tests. The contents of the vals array is repeated here for easy +# reference. +# +# set vals [list 10 10.0 '10' '10.0' 20 20.0 '20' '20.0' 30 30.0 '30' '30.0'] +# 1 2 3 4 5 6 7 8 9 10 11 12 + +ifcapable subquery { + test_boolset types2-6.1 {o IN ('10', 30)} {3 9 10} + test_boolset types2-6.2 {o IN (20.0, 30.0)} {5 6 9 10} + test_boolset types2-6.3 {t IN ('10', 30)} {1 3 9 11} + test_boolset types2-6.4 {t IN (20.0, 30.0)} {6 8 10 12} + test_boolset types2-6.5 {n IN ('10', 30)} {1 2 3 4 9 10 11 12} + test_boolset types2-6.6 {n IN (20.0, 30.0)} {5 6 7 8 9 10 11 12} + test_boolset types2-6.7 {i IN ('10', 30)} {1 2 3 4 9 10 11 12} + test_boolset types2-6.8 {i IN (20.0, 30.0)} {5 6 7 8 9 10 11 12} + + # Also test than IN(x, y, z) works on a rowid: + test_boolset types2-6.9 {rowid IN (1, 6, 10)} {1 6 10} +} + +# Tests types2-7.* concentrate on expressions of the form +# "x IN (SELECT...)" with no index. +execsql { + CREATE TABLE t3(i INTEGER, n NUMERIC, t TEXT, o BLOB); + INSERT INTO t3 VALUES(1, 1, 1, 1); + INSERT INTO t3 VALUES(2, 2, 2, 2); + INSERT INTO t3 VALUES(3, 3, 3, 3); + INSERT INTO t3 VALUES('1', '1', '1', '1'); + INSERT INTO t3 VALUES('1.0', '1.0', '1.0', '1.0'); +} + +ifcapable subquery { + test_bool types2-7.1 {i1=1} {i1 IN (SELECT i FROM t3)} 1 + test_bool types2-7.2 {i1='2.0'} {i1 IN (SELECT i FROM t3)} 1 + test_bool types2-7.3 {i1='2.0'} {i1 IN (SELECT n FROM t3)} 1 + test_bool types2-7.4 {i1='2.0'} {i1 IN (SELECT t FROM t3)} 1 + test_bool types2-7.5 {i1='2.0'} {i1 IN (SELECT o FROM t3)} 1 + + test_bool types2-7.6 {n1=1} {n1 IN (SELECT n FROM t3)} 1 + test_bool types2-7.7 {n1='2.0'} {n1 IN (SELECT i FROM t3)} 1 + test_bool types2-7.8 {n1='2.0'} {n1 IN (SELECT n FROM t3)} 1 + test_bool types2-7.9 {n1='2.0'} {n1 IN (SELECT t FROM t3)} 1 + test_bool types2-7.10 {n1='2.0'} {n1 IN (SELECT o FROM t3)} 1 + + test_bool types2-7.6 {t1=1} {t1 IN (SELECT t FROM t3)} 1 + test_bool types2-7.7 {t1='2.0'} {t1 IN (SELECT t FROM t3)} 0 + test_bool types2-7.8 {t1='2.0'} {t1 IN (SELECT n FROM t3)} 1 + test_bool types2-7.9 {t1='2.0'} {t1 IN (SELECT i FROM t3)} 1 + test_bool types2-7.10 {t1='2.0'} {t1 IN (SELECT o FROM t3)} 0 + test_bool types2-7.11 {t1='1.0'} {t1 IN (SELECT t FROM t3)} 1 + test_bool types2-7.12 {t1='1.0'} {t1 IN (SELECT o FROM t3)} 1 + + test_bool types2-7.13 {o1=2} {o1 IN (SELECT o FROM t3)} 1 + test_bool types2-7.14 {o1='2'} {o1 IN (SELECT o FROM t3)} 0 + test_bool types2-7.15 {o1='2'} {o1 IN (SELECT o||'' FROM t3)} 1 +} + +# set vals [list 10 10.0 '10' '10.0' 20 20.0 '20' '20.0' 30 30.0 '30' '30.0'] +# 1 2 3 4 5 6 7 8 9 10 11 12 +execsql { + CREATE TABLE t4(i INTEGER, n NUMERIC, t VARCHAR(20), o LARGE BLOB); + INSERT INTO t4 VALUES(10, 20, 20, 30); +} +ifcapable subquery { + test_boolset types2-8.1 {i IN (SELECT i FROM t4)} {1 2 3 4} + test_boolset types2-8.2 {n IN (SELECT i FROM t4)} {1 2 3 4} + test_boolset types2-8.3 {t IN (SELECT i FROM t4)} {1 2 3 4} + test_boolset types2-8.4 {o IN (SELECT i FROM t4)} {1 2 3 4} + test_boolset types2-8.5 {i IN (SELECT t FROM t4)} {5 6 7 8} + test_boolset types2-8.6 {n IN (SELECT t FROM t4)} {5 6 7 8} + test_boolset types2-8.7 {t IN (SELECT t FROM t4)} {5 7} + test_boolset types2-8.8 {o IN (SELECT t FROM t4)} {7} + test_boolset types2-8.9 {i IN (SELECT o FROM t4)} {9 10 11 12} + test_boolset types2-8.6 {n IN (SELECT o FROM t4)} {9 10 11 12} + test_boolset types2-8.7 {t IN (SELECT o FROM t4)} {9 11} + test_boolset types2-8.8 {o IN (SELECT o FROM t4)} {9 10} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/types3.test b/components/external/SQLite-3.8.1/test/types3.test new file mode 100644 index 0000000000000000000000000000000000000000..807ae84f9d2dbe5896b7348eefd3556920f8dcbf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/types3.test @@ -0,0 +1,99 @@ +# 2005 June 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus +# of this file is testing the interaction of SQLite manifest types +# with Tcl dual-representations. +# +# $Id: types3.test,v 1.8 2008/04/28 13:02:58 drh Exp $ +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# A variable with only a string representation comes in as TEXT +do_test types3-1.1 { + set V {} + append V x + concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}] +} {string text} + +# A variable with an integer representation comes in as INTEGER +do_test types3-1.2 { + set V [expr {int(1+2)}] + concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}] +} {int integer} +set V [expr {1+12345678012345}] +if {[tcl_variable_type V]=="wideInt"} { + do_test types3-1.3 { + set V [expr {1+123456789012345}] + concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}] + } {wideInt integer} +} else { + do_test types3-1.3 { + set V [expr {1+123456789012345}] + concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}] + } {int integer} +} + +# A double variable comes in as REAL +do_test types3-1.4 { + set V [expr {1.0+1}] + concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}] +} {double real} + +# A byte-array variable comes in a BLOB if it has no string representation +# or as TEXT if there is a string representation. +# +do_test types3-1.5 { + set V [binary format a3 abc] + concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}] +} {bytearray blob} +do_test types3-1.6 { + set V "abc" + binary scan $V a3 x + concat [tcl_variable_type V] [execsql {SELECT typeof(:V)}] +} {bytearray text} + +# Check to make sure return values are of the right types. +# +ifcapable bloblit { + do_test types3-2.1 { + set V [db one {SELECT x'616263'}] + tcl_variable_type V + } bytearray +} +do_test types3-2.2 { + set V [db one {SELECT 123}] + tcl_variable_type V +} int +set Vx [expr {1+wide(123456789123456)}] +do_test types3-2.3 { + set V [db one {SELECT 1234567890123456}] + tcl_variable_type V +} [tcl_variable_type Vx] +do_test types3-2.4.1 { + set V [db one {SELECT 1234567890123456.1}] + tcl_variable_type V +} double +do_test types3-2.4.2 { + set V [db one {SELECT 1234567890123.456}] + tcl_variable_type V +} double +do_test types3-2.5 { + set V [db one {SELECT '1234567890123456.0'}] + tcl_variable_type V +} {} +do_test types3-2.6 { + set V [db one {SELECT NULL}] + tcl_variable_type V +} {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/unique.test b/components/external/SQLite-3.8.1/test/unique.test new file mode 100644 index 0000000000000000000000000000000000000000..eac19b59e02dcd32828b6d4e11f69bd58ac4c587 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/unique.test @@ -0,0 +1,261 @@ +# 2001 September 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the CREATE UNIQUE INDEX statement, +# and primary keys, and the UNIQUE constraint on table columns +# +# $Id: unique.test,v 1.9 2009/05/02 15:46:47 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Try to create a table with two primary keys. +# (This is allowed in SQLite even that it is not valid SQL) +# +do_test unique-1.1 { + catchsql { + CREATE TABLE t1( + a int PRIMARY KEY, + b int PRIMARY KEY, + c text + ); + } +} {1 {table "t1" has more than one primary key}} +do_test unique-1.1b { + catchsql { + CREATE TABLE t1( + a int PRIMARY KEY, + b int UNIQUE, + c text + ); + } +} {0 {}} +do_test unique-1.2 { + catchsql { + INSERT INTO t1(a,b,c) VALUES(1,2,3) + } +} {0 {}} +do_test unique-1.3 { + catchsql { + INSERT INTO t1(a,b,c) VALUES(1,3,4) + } +} {1 {column a is not unique}} +verify_ex_errcode unique-1.3b SQLITE_CONSTRAINT_UNIQUE +do_test unique-1.4 { + execsql { + SELECT * FROM t1 ORDER BY a; + } +} {1 2 3} +do_test unique-1.5 { + catchsql { + INSERT INTO t1(a,b,c) VALUES(3,2,4) + } +} {1 {column b is not unique}} +verify_ex_errcode unique-1.5b SQLITE_CONSTRAINT_UNIQUE +do_test unique-1.6 { + execsql { + SELECT * FROM t1 ORDER BY a; + } +} {1 2 3} +do_test unique-1.7 { + catchsql { + INSERT INTO t1(a,b,c) VALUES(3,4,5) + } +} {0 {}} +do_test unique-1.8 { + execsql { + SELECT * FROM t1 ORDER BY a; + } +} {1 2 3 3 4 5} +integrity_check unique-1.9 + +do_test unique-2.0 { + execsql { + DROP TABLE t1; + CREATE TABLE t2(a int, b int); + INSERT INTO t2(a,b) VALUES(1,2); + INSERT INTO t2(a,b) VALUES(3,4); + SELECT * FROM t2 ORDER BY a; + } +} {1 2 3 4} +do_test unique-2.1 { + catchsql { + CREATE UNIQUE INDEX i2 ON t2(a) + } +} {0 {}} +do_test unique-2.2 { + catchsql { + SELECT * FROM t2 ORDER BY a + } +} {0 {1 2 3 4}} +do_test unique-2.3 { + catchsql { + INSERT INTO t2 VALUES(1,5); + } +} {1 {column a is not unique}} +verify_ex_errcode unique-2.3b SQLITE_CONSTRAINT_UNIQUE +do_test unique-2.4 { + catchsql { + SELECT * FROM t2 ORDER BY a + } +} {0 {1 2 3 4}} +do_test unique-2.5 { + catchsql { + DROP INDEX i2; + SELECT * FROM t2 ORDER BY a; + } +} {0 {1 2 3 4}} +do_test unique-2.6 { + catchsql { + INSERT INTO t2 VALUES(1,5) + } +} {0 {}} +do_test unique-2.7 { + catchsql { + SELECT * FROM t2 ORDER BY a, b; + } +} {0 {1 2 1 5 3 4}} +do_test unique-2.8 { + catchsql { + CREATE UNIQUE INDEX i2 ON t2(a); + } +} {1 {indexed columns are not unique}} +verify_ex_errcode unique-2.8b SQLITE_CONSTRAINT_UNIQUE +do_test unique-2.9 { + catchsql { + CREATE INDEX i2 ON t2(a); + } +} {0 {}} +integrity_check unique-2.10 + +# Test the UNIQUE keyword as used on two or more fields. +# +do_test unique-3.1 { + catchsql { + CREATE TABLE t3( + a int, + b int, + c int, + d int, + unique(a,c,d) + ); + } +} {0 {}} +do_test unique-3.2 { + catchsql { + INSERT INTO t3(a,b,c,d) VALUES(1,2,3,4); + SELECT * FROM t3 ORDER BY a,b,c,d; + } +} {0 {1 2 3 4}} +do_test unique-3.3 { + catchsql { + INSERT INTO t3(a,b,c,d) VALUES(1,2,3,5); + SELECT * FROM t3 ORDER BY a,b,c,d; + } +} {0 {1 2 3 4 1 2 3 5}} +do_test unique-3.4 { + catchsql { + INSERT INTO t3(a,b,c,d) VALUES(1,4,3,5); + SELECT * FROM t3 ORDER BY a,b,c,d; + } +} {1 {columns a, c, d are not unique}} +verify_ex_errcode unique-3.4b SQLITE_CONSTRAINT_UNIQUE +integrity_check unique-3.5 + +# Make sure NULLs are distinct as far as the UNIQUE tests are +# concerned. +# +do_test unique-4.1 { + execsql { + CREATE TABLE t4(a UNIQUE, b, c, UNIQUE(b,c)); + INSERT INTO t4 VALUES(1,2,3); + INSERT INTO t4 VALUES(NULL, 2, NULL); + SELECT * FROM t4; + } +} {1 2 3 {} 2 {}} +do_test unique-4.2 { + catchsql { + INSERT INTO t4 VALUES(NULL, 3, 4); + } +} {0 {}} +do_test unique-4.3 { + execsql { + SELECT * FROM t4 + } +} {1 2 3 {} 2 {} {} 3 4} +do_test unique-4.4 { + catchsql { + INSERT INTO t4 VALUES(2, 2, NULL); + } +} {0 {}} +do_test unique-4.5 { + execsql { + SELECT * FROM t4 + } +} {1 2 3 {} 2 {} {} 3 4 2 2 {}} + +# Ticket #1301. Any NULL value in a set of unique columns should +# cause the rows to be distinct. +# +do_test unique-4.6 { + catchsql { + INSERT INTO t4 VALUES(NULL, 2, NULL); + } +} {0 {}} +do_test unique-4.7 { + execsql {SELECT * FROM t4} +} {1 2 3 {} 2 {} {} 3 4 2 2 {} {} 2 {}} +do_test unique-4.8 { + catchsql {CREATE UNIQUE INDEX i4a ON t4(a,b)} +} {0 {}} +do_test unique-4.9 { + catchsql {CREATE UNIQUE INDEX i4b ON t4(a,b,c)} +} {0 {}} +do_test unique-4.10 { + catchsql {CREATE UNIQUE INDEX i4c ON t4(b)} +} {1 {indexed columns are not unique}} +verify_ex_errcode unique-4.10b SQLITE_CONSTRAINT_UNIQUE +integrity_check unique-4.99 + +# Test the error message generation logic. In particular, make sure we +# do not overflow the static buffer used to generate the error message. +# +do_test unique-5.1 { + execsql { + CREATE TABLE t5( + first_column_with_long_name, + second_column_with_long_name, + third_column_with_long_name, + fourth_column_with_long_name, + fifth_column_with_long_name, + sixth_column_with_long_name, + UNIQUE( + first_column_with_long_name, + second_column_with_long_name, + third_column_with_long_name, + fourth_column_with_long_name, + fifth_column_with_long_name, + sixth_column_with_long_name + ) + ); + INSERT INTO t5 VALUES(1,2,3,4,5,6); + SELECT * FROM t5; + } +} {1 2 3 4 5 6} +do_test unique-5.2 { + catchsql { + INSERT INTO t5 VALUES(1,2,3,4,5,6); + } +} {1 {columns first_column_with_long_name, second_column_with_long_name, third_column_with_long_name, fourth_column_with_long_name, fifth_column_with_long_name, sixth_column_with_long_name are not unique}} +verify_ex_errcode unique-5.2b SQLITE_CONSTRAINT_UNIQUE + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/unixexcl.test b/components/external/SQLite-3.8.1/test/unixexcl.test new file mode 100644 index 0000000000000000000000000000000000000000..0147e6bbb41b81476f5abc517cf571ba8642fdbe --- /dev/null +++ b/components/external/SQLite-3.8.1/test/unixexcl.test @@ -0,0 +1,128 @@ +# 2011 March 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests for the "unix-excl" VFS module (part of +# os_unix.c). +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl + +if {$::tcl_platform(platform)!="unix" || [info commands test_syscall]==""} { + finish_test + return +} +set testprefix unixexcl + + + +# Test that when using VFS "unix-excl", the first time the database is read +# a process-wide exclusive lock is taken on it. This means other connections +# within the process may still access the db normally, but connections from +# outside the process cannot. +# +do_multiclient_test tn { + do_test unixexcl-1.$tn.1 { + sql1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('hello', 'world'); + } + } {} + do_test unixexcl-1.$tn.2 { sql2 { SELECT * FROM t1 } } {hello world} + do_test unixexcl-1.$tn.3 { + code1 { + db close + sqlite3 db test.db -vfs unix-excl + db eval { SELECT * FROM t1 } + } + } {hello world} + if {$tn==1} { + do_test unixexcl-1.$tn.4.multiproc { + csql2 { SELECT * FROM t1 } + } {1 {database is locked}} + } else { + do_test unixexcl-1.$tn.4.singleproc { + csql2 { SELECT * FROM t1 } + } {0 {hello world}} + } +} + +# Test that when using VFS "unix-excl", if a file is opened in read-only mode +# the behaviour is the same as if VFS "unix" were used. +# +do_multiclient_test tn { + do_test unixexcl-2.$tn.1 { + sql1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('hello', 'world'); + } + } {} + do_test unixexcl-2.$tn.2 { sql2 { SELECT * FROM t1 } } {hello world} + do_test unixexcl-2.$tn.3 { + code1 { + db close + sqlite3 db test.db -readonly yes -vfs unix-excl + db eval { SELECT * FROM t1 } + } + } {hello world} + do_test unixexcl-2.$tn.4 { + csql2 { SELECT * FROM t1 } + } {0 {hello world}} +} + +do_multiclient_test tn { + do_test unixexcl-3.$tn.1 { + code1 { db close; sqlite3 db file:test.db?psow=0 -vfs unix-excl -uri 1 } + code2 { db2 close; sqlite3 db2 file:test.db?psow=0 -vfs unix-excl -uri 1 } + sql1 { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } + } {wal} + + if {$tn==1} { + do_test unixexcl-3.$tn.1.multiproc { + csql2 { SELECT * FROM t1; } + } {1 {database is locked}} + } else { + do_test unixexcl-3.$tn.1.singleproc { + sql2 { SELECT * FROM t1; } + } {1 2} + + do_test unixexcl-3.$tn.2 { + sql2 { + BEGIN; + SELECT * FROM t1; + } + } {1 2} + do_test unixexcl-3.$tn.3 { + sql1 { PRAGMA wal_checkpoint; INSERT INTO t1 VALUES(3, 4); } + } {0 3 3} + do_test unixexcl-3.$tn.4 { + sql2 { SELECT * FROM t1; } + } {1 2} + do_test unixexcl-3.$tn.5 { + sql1 { SELECT * FROM t1; } + } {1 2 3 4} + do_test unixexcl-3.$tn.6 { + sql2 { COMMIT; SELECT * FROM t1; } + } {1 2 3 4} + do_test unixexcl-3.$tn.7 { + sql1 { PRAGMA wal_checkpoint; } + } {0 4 4} + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/unordered.test b/components/external/SQLite-3.8.1/test/unordered.test new file mode 100644 index 0000000000000000000000000000000000000000..d8f7aa6add53ab84e4bc6f5c2477f693af80516b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/unordered.test @@ -0,0 +1,70 @@ +# 2011 April 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set testprefix unordered + +do_execsql_test 1.0 { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a); + INSERT INTO t1 VALUES(1, 'xxx'); + INSERT INTO t1 SELECT a+1, b FROM t1; + INSERT INTO t1 SELECT a+2, b FROM t1; + INSERT INTO t1 SELECT a+4, b FROM t1; + INSERT INTO t1 SELECT a+8, b FROM t1; + INSERT INTO t1 SELECT a+16, b FROM t1; + INSERT INTO t1 SELECT a+32, b FROM t1; + INSERT INTO t1 SELECT a+64, b FROM t1; + ANALYZE; +} {} + +foreach idxmode {ordered unordered} { + catchsql { DELETE FROM sqlite_stat2 } + catchsql { DELETE FROM sqlite_stat3 } + if {$idxmode == "unordered"} { + execsql { UPDATE sqlite_stat1 SET stat = stat || ' unordered' } + } + db close + sqlite3 db test.db + foreach {tn sql r(ordered) r(unordered)} { + 1 "SELECT * FROM t1 ORDER BY a" + {0 0 0 {SCAN TABLE t1 USING INDEX i1}} + {0 0 0 {SCAN TABLE t1} 0 0 0 {USE TEMP B-TREE FOR ORDER BY}} + 2 "SELECT * FROM t1 WHERE a >?" + {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a>?)}} + {0 0 0 {SCAN TABLE t1}} + 3 "SELECT * FROM t1 WHERE a = ? ORDER BY rowid" + {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)}} + {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY}} + 4 "SELECT max(a) FROM t1" + {0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i1}} + {0 0 0 {SEARCH TABLE t1}} + 5 "SELECT group_concat(b) FROM t1 GROUP BY a" + {0 0 0 {SCAN TABLE t1 USING INDEX i1}} + {0 0 0 {SCAN TABLE t1} 0 0 0 {USE TEMP B-TREE FOR GROUP BY}} + + 6 "SELECT * FROM t1 WHERE a = ?" + {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)}} + {0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)}} + 7 "SELECT count(*) FROM t1" + {0 0 0 {SCAN TABLE t1 USING COVERING INDEX i1}} + {0 0 0 {SCAN TABLE t1}} + } { + do_eqp_test 1.$idxmode.$tn $sql $r($idxmode) + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/update.test b/components/external/SQLite-3.8.1/test/update.test new file mode 100644 index 0000000000000000000000000000000000000000..a6fef7d9affce51293f6c70c505fc4e412d6ae28 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/update.test @@ -0,0 +1,608 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the UPDATE statement. +# +# $Id: update.test,v 1.19 2008/04/10 18:44:36 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Try to update an non-existent table +# +do_test update-1.1 { + set v [catch {execsql {UPDATE test1 SET f2=5 WHERE f1<1}} msg] + lappend v $msg +} {1 {no such table: test1}} + +# Try to update a read-only table +# +do_test update-2.1 { + set v [catch \ + {execsql {UPDATE sqlite_master SET name='xyz' WHERE name='123'}} msg] + lappend v $msg +} {1 {table sqlite_master may not be modified}} + +# Create a table to work with +# +do_test update-3.1 { + execsql {CREATE TABLE test1(f1 int,f2 int)} + for {set i 1} {$i<=10} {incr i} { + set sql "INSERT INTO test1 VALUES($i,[expr {1<<$i}])" + execsql $sql + } + execsql {SELECT * FROM test1 ORDER BY f1} +} {1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024} + +# Unknown column name in an expression +# +do_test update-3.2 { + set v [catch {execsql {UPDATE test1 SET f1=f3*2 WHERE f2==32}} msg] + lappend v $msg +} {1 {no such column: f3}} +do_test update-3.3 { + set v [catch {execsql {UPDATE test1 SET f1=test2.f1*2 WHERE f2==32}} msg] + lappend v $msg +} {1 {no such column: test2.f1}} +do_test update-3.4 { + set v [catch {execsql {UPDATE test1 SET f3=f1*2 WHERE f2==32}} msg] + lappend v $msg +} {1 {no such column: f3}} + +# Actually do some updates +# +do_test update-3.5 { + execsql {UPDATE test1 SET f2=f2*3} +} {} +do_test update-3.5.1 { + db changes +} {10} + +# verify that SELECT does not reset the change counter +do_test update-3.5.2 { + db eval {SELECT count(*) FROM test1} +} {10} +do_test update-3.5.3 { + db changes +} {10} + +do_test update-3.6 { + execsql {SELECT * FROM test1 ORDER BY f1} +} {1 6 2 12 3 24 4 48 5 96 6 192 7 384 8 768 9 1536 10 3072} +do_test update-3.7 { + execsql {PRAGMA count_changes=on} + execsql {UPDATE test1 SET f2=f2/3 WHERE f1<=5} +} {5} +do_test update-3.8 { + execsql {SELECT * FROM test1 ORDER BY f1} +} {1 2 2 4 3 8 4 16 5 32 6 192 7 384 8 768 9 1536 10 3072} +do_test update-3.9 { + execsql {UPDATE test1 SET f2=f2/3 WHERE f1>5} +} {5} +do_test update-3.10 { + execsql {SELECT * FROM test1 ORDER BY f1} +} {1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024} + +# Swap the values of f1 and f2 for all elements +# +do_test update-3.11 { + execsql {UPDATE test1 SET F2=f1, F1=f2} +} {10} +do_test update-3.12 { + execsql {SELECT * FROM test1 ORDER BY F1} +} {2 1 4 2 8 3 16 4 32 5 64 6 128 7 256 8 512 9 1024 10} +do_test update-3.13 { + execsql {PRAGMA count_changes=off} + execsql {UPDATE test1 SET F2=f1, F1=f2} +} {} +do_test update-3.14 { + execsql {SELECT * FROM test1 ORDER BY F1} +} {1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024} + +# Create duplicate entries and make sure updating still +# works. +# +do_test update-4.0 { + execsql { + DELETE FROM test1 WHERE f1<=5; + INSERT INTO test1(f1,f2) VALUES(8,88); + INSERT INTO test1(f1,f2) VALUES(8,888); + INSERT INTO test1(f1,f2) VALUES(77,128); + INSERT INTO test1(f1,f2) VALUES(777,128); + } + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-4.1 { + execsql {UPDATE test1 SET f2=f2+1 WHERE f1==8} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 89 8 257 8 889 9 512 10 1024 77 128 777 128} +do_test update-4.2 { + execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2>800} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 89 8 257 8 888 9 512 10 1024 77 128 777 128} +do_test update-4.3 { + execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2<800} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-4.4 { + execsql {UPDATE test1 SET f1=f1+1 WHERE f2==128} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 778 128} +do_test update-4.5 { + execsql {UPDATE test1 SET f1=f1-1 WHERE f1>100 and f2==128} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 777 128} +do_test update-4.6 { + execsql { + PRAGMA count_changes=on; + UPDATE test1 SET f1=f1-1 WHERE f1<=100 and f2==128; + } +} {2} +do_test update-4.7 { + execsql { + PRAGMA count_changes=off; + SELECT * FROM test1 ORDER BY f1,f2 + } +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} + +# Repeat the previous sequence of tests with an index. +# +do_test update-5.0 { + execsql {CREATE INDEX idx1 ON test1(f1)} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-5.1 { + execsql {UPDATE test1 SET f2=f2+1 WHERE f1==8} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 89 8 257 8 889 9 512 10 1024 77 128 777 128} +do_test update-5.2 { + execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2>800} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 89 8 257 8 888 9 512 10 1024 77 128 777 128} +do_test update-5.3 { + execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2<800} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-5.4 { + execsql {UPDATE test1 SET f1=f1+1 WHERE f2==128} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 778 128} +do_test update-5.4.1 { + execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2} +} {78 128} +do_test update-5.4.2 { + execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2} +} {778 128} +do_test update-5.4.3 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 128 8 256 8 888} +do_test update-5.5 { + execsql {UPDATE test1 SET f1=f1-1 WHERE f1>100 and f2==128} +} {} +do_test update-5.5.1 { + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 777 128} +do_test update-5.5.2 { + execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2} +} {78 128} +do_test update-5.5.3 { + execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2} +} {} +do_test update-5.5.4 { + execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2} +} {777 128} +do_test update-5.5.5 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 128 8 256 8 888} +do_test update-5.6 { + execsql { + PRAGMA count_changes=on; + UPDATE test1 SET f1=f1-1 WHERE f1<=100 and f2==128; + } +} {2} +do_test update-5.6.1 { + execsql { + PRAGMA count_changes=off; + SELECT * FROM test1 ORDER BY f1,f2 + } +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-5.6.2 { + execsql {SELECT * FROM test1 WHERE f1==77 ORDER BY f1,f2} +} {77 128} +do_test update-5.6.3 { + execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2} +} {} +do_test update-5.6.4 { + execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2} +} {777 128} +do_test update-5.6.5 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 256 8 888} + +# Repeat the previous sequence of tests with a different index. +# +execsql {PRAGMA synchronous=FULL} +do_test update-6.0 { + execsql {DROP INDEX idx1} + execsql {CREATE INDEX idx1 ON test1(f2)} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-6.1 { + execsql {UPDATE test1 SET f2=f2+1 WHERE f1==8} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 89 8 257 8 889 9 512 10 1024 77 128 777 128} +do_test update-6.1.1 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 89 8 257 8 889} +do_test update-6.1.2 { + execsql {SELECT * FROM test1 WHERE f2==89 ORDER BY f1,f2} +} {8 89} +do_test update-6.1.3 { + execsql {SELECT * FROM test1 WHERE f1==88 ORDER BY f1,f2} +} {} +do_test update-6.2 { + execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2>800} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 89 8 257 8 888 9 512 10 1024 77 128 777 128} +do_test update-6.3 { + execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2<800} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-6.3.1 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 256 8 888} +do_test update-6.3.2 { + execsql {SELECT * FROM test1 WHERE f2==89 ORDER BY f1,f2} +} {} +do_test update-6.3.3 { + execsql {SELECT * FROM test1 WHERE f2==88 ORDER BY f1,f2} +} {8 88} +do_test update-6.4 { + execsql {UPDATE test1 SET f1=f1+1 WHERE f2==128} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 778 128} +do_test update-6.4.1 { + execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2} +} {78 128} +do_test update-6.4.2 { + execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2} +} {778 128} +do_test update-6.4.3 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 128 8 256 8 888} +do_test update-6.5 { + execsql {UPDATE test1 SET f1=f1-1 WHERE f1>100 and f2==128} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 777 128} +do_test update-6.5.1 { + execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2} +} {78 128} +do_test update-6.5.2 { + execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2} +} {} +do_test update-6.5.3 { + execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2} +} {777 128} +do_test update-6.5.4 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 128 8 256 8 888} +do_test update-6.6 { + execsql {UPDATE test1 SET f1=f1-1 WHERE f1<=100 and f2==128} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-6.6.1 { + execsql {SELECT * FROM test1 WHERE f1==77 ORDER BY f1,f2} +} {77 128} +do_test update-6.6.2 { + execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2} +} {} +do_test update-6.6.3 { + execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2} +} {777 128} +do_test update-6.6.4 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 256 8 888} + +# Repeat the previous sequence of tests with multiple +# indices +# +do_test update-7.0 { + execsql {CREATE INDEX idx2 ON test1(f2)} + execsql {CREATE INDEX idx3 ON test1(f1,f2)} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-7.1 { + execsql {UPDATE test1 SET f2=f2+1 WHERE f1==8} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 89 8 257 8 889 9 512 10 1024 77 128 777 128} +do_test update-7.1.1 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 89 8 257 8 889} +do_test update-7.1.2 { + execsql {SELECT * FROM test1 WHERE f2==89 ORDER BY f1,f2} +} {8 89} +do_test update-7.1.3 { + execsql {SELECT * FROM test1 WHERE f1==88 ORDER BY f1,f2} +} {} +do_test update-7.2 { + execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2>800} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 89 8 257 8 888 9 512 10 1024 77 128 777 128} +do_test update-7.3 { + # explain {UPDATE test1 SET f2=f2-1 WHERE f1==8 and F2<300} + execsql {UPDATE test1 SET f2=f2-1 WHERE f1==8 and f2<800} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-7.3.1 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 256 8 888} +do_test update-7.3.2 { + execsql {SELECT * FROM test1 WHERE f2==89 ORDER BY f1,f2} +} {} +do_test update-7.3.3 { + execsql {SELECT * FROM test1 WHERE f2==88 ORDER BY f1,f2} +} {8 88} +do_test update-7.4 { + execsql {UPDATE test1 SET f1=f1+1 WHERE f2==128} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 778 128} +do_test update-7.4.1 { + execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2} +} {78 128} +do_test update-7.4.2 { + execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2} +} {778 128} +do_test update-7.4.3 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 128 8 256 8 888} +do_test update-7.5 { + execsql {UPDATE test1 SET f1=f1-1 WHERE f1>100 and f2==128} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 8 88 8 128 8 256 8 888 9 512 10 1024 78 128 777 128} +do_test update-7.5.1 { + execsql {SELECT * FROM test1 WHERE f1==78 ORDER BY f1,f2} +} {78 128} +do_test update-7.5.2 { + execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2} +} {} +do_test update-7.5.3 { + execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2} +} {777 128} +do_test update-7.5.4 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 128 8 256 8 888} +do_test update-7.6 { + execsql {UPDATE test1 SET f1=f1-1 WHERE f1<=100 and f2==128} + execsql {SELECT * FROM test1 ORDER BY f1,f2} +} {6 64 7 128 8 88 8 256 8 888 9 512 10 1024 77 128 777 128} +do_test update-7.6.1 { + execsql {SELECT * FROM test1 WHERE f1==77 ORDER BY f1,f2} +} {77 128} +do_test update-7.6.2 { + execsql {SELECT * FROM test1 WHERE f1==778 ORDER BY f1,f2} +} {} +do_test update-7.6.3 { + execsql {SELECT * FROM test1 WHERE f1==777 ORDER BY f1,f2} +} {777 128} +do_test update-7.6.4 { + execsql {SELECT * FROM test1 WHERE f1==8 ORDER BY f1,f2} +} {8 88 8 256 8 888} + +# Error messages +# +do_test update-9.1 { + set v [catch {execsql { + UPDATE test1 SET x=11 WHERE f1=1025 + }} msg] + lappend v $msg +} {1 {no such column: x}} +do_test update-9.2 { + set v [catch {execsql { + UPDATE test1 SET f1=x(11) WHERE f1=1025 + }} msg] + lappend v $msg +} {1 {no such function: x}} +do_test update-9.3 { + set v [catch {execsql { + UPDATE test1 SET f1=11 WHERE x=1025 + }} msg] + lappend v $msg +} {1 {no such column: x}} +do_test update-9.4 { + set v [catch {execsql { + UPDATE test1 SET f1=11 WHERE x(f1)=1025 + }} msg] + lappend v $msg +} {1 {no such function: x}} + +# Try doing updates on a unique column where the value does not +# really change. +# +do_test update-10.1 { + execsql { + DROP TABLE test1; + CREATE TABLE t1( + a integer primary key, + b UNIQUE, + c, d, + e, f, + UNIQUE(c,d) + ); + INSERT INTO t1 VALUES(1,2,3,4,5,6); + INSERT INTO t1 VALUES(2,3,4,4,6,7); + SELECT * FROM t1 + } +} {1 2 3 4 5 6 2 3 4 4 6 7} +do_test update-10.2 { + catchsql { + UPDATE t1 SET a=1, e=9 WHERE f=6; + SELECT * FROM t1; + } +} {0 {1 2 3 4 9 6 2 3 4 4 6 7}} +do_test update-10.3 { + catchsql { + UPDATE t1 SET a=1, e=10 WHERE f=7; + SELECT * FROM t1; + } +} {1 {PRIMARY KEY must be unique}} +do_test update-10.4 { + catchsql { + SELECT * FROM t1; + } +} {0 {1 2 3 4 9 6 2 3 4 4 6 7}} +do_test update-10.5 { + catchsql { + UPDATE t1 SET b=2, e=11 WHERE f=6; + SELECT * FROM t1; + } +} {0 {1 2 3 4 11 6 2 3 4 4 6 7}} +do_test update-10.6 { + catchsql { + UPDATE t1 SET b=2, e=12 WHERE f=7; + SELECT * FROM t1; + } +} {1 {column b is not unique}} +do_test update-10.7 { + catchsql { + SELECT * FROM t1; + } +} {0 {1 2 3 4 11 6 2 3 4 4 6 7}} +do_test update-10.8 { + catchsql { + UPDATE t1 SET c=3, d=4, e=13 WHERE f=6; + SELECT * FROM t1; + } +} {0 {1 2 3 4 13 6 2 3 4 4 6 7}} +do_test update-10.9 { + catchsql { + UPDATE t1 SET c=3, d=4, e=14 WHERE f=7; + SELECT * FROM t1; + } +} {1 {columns c, d are not unique}} +do_test update-10.10 { + catchsql { + SELECT * FROM t1; + } +} {0 {1 2 3 4 13 6 2 3 4 4 6 7}} + +# Make sure we can handle a subquery in the where clause. +# +ifcapable subquery { + do_test update-11.1 { + execsql { + UPDATE t1 SET e=e+1 WHERE b IN (SELECT b FROM t1); + SELECT b,e FROM t1; + } + } {2 14 3 7} + do_test update-11.2 { + execsql { + UPDATE t1 SET e=e+1 WHERE a IN (SELECT a FROM t1); + SELECT a,e FROM t1; + } + } {1 15 2 8} +} + +integrity_check update-12.1 + +# Ticket 602. Updates should occur in the same order as the records +# were discovered in the WHERE clause. +# +do_test update-13.1 { + execsql { + BEGIN; + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(2); + INSERT INTO t2 SELECT a+2 FROM t2; + INSERT INTO t2 SELECT a+4 FROM t2; + INSERT INTO t2 SELECT a+8 FROM t2; + INSERT INTO t2 SELECT a+16 FROM t2; + INSERT INTO t2 SELECT a+32 FROM t2; + INSERT INTO t2 SELECT a+64 FROM t2; + INSERT INTO t2 SELECT a+128 FROM t2; + INSERT INTO t2 SELECT a+256 FROM t2; + INSERT INTO t2 SELECT a+512 FROM t2; + INSERT INTO t2 SELECT a+1024 FROM t2; + COMMIT; + SELECT count(*) FROM t2; + } +} {2048} +do_test update-13.2 { + execsql { + SELECT count(*) FROM t2 WHERE a=rowid; + } +} {2048} +do_test update-13.3 { + execsql { + UPDATE t2 SET rowid=rowid-1; + SELECT count(*) FROM t2 WHERE a=rowid+1; + } +} {2048} +do_test update-13.3 { + execsql { + UPDATE t2 SET rowid=rowid+10000; + UPDATE t2 SET rowid=rowid-9999; + SELECT count(*) FROM t2 WHERE a=rowid; + } +} {2048} +do_test update-13.4 { + execsql { + BEGIN; + INSERT INTO t2 SELECT a+2048 FROM t2; + INSERT INTO t2 SELECT a+4096 FROM t2; + INSERT INTO t2 SELECT a+8192 FROM t2; + SELECT count(*) FROM t2 WHERE a=rowid; + COMMIT; + } +} 16384 +do_test update-13.5 { + execsql { + UPDATE t2 SET rowid=rowid-1; + SELECT count(*) FROM t2 WHERE a=rowid+1; + } +} 16384 + +integrity_check update-13.6 + +ifcapable {trigger} { +# Test for proper detection of malformed WHEN clauses on UPDATE triggers. +# +do_test update-14.1 { + execsql { + CREATE TABLE t3(a,b,c); + CREATE TRIGGER t3r1 BEFORE UPDATE on t3 WHEN nosuchcol BEGIN + SELECT 'illegal WHEN clause'; + END; + } +} {} +do_test update-14.2 { + catchsql { + UPDATE t3 SET a=1; + } +} {1 {no such column: nosuchcol}} +do_test update-14.3 { + execsql { + CREATE TABLE t4(a,b,c); + CREATE TRIGGER t4r1 AFTER UPDATE on t4 WHEN nosuchcol BEGIN + SELECT 'illegal WHEN clause'; + END; + } +} {} +do_test update-14.4 { + catchsql { + UPDATE t4 SET a=1; + } +} {1 {no such column: nosuchcol}} + +} ;# ifcapable {trigger} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/uri.test b/components/external/SQLite-3.8.1/test/uri.test new file mode 100644 index 0000000000000000000000000000000000000000..af1ad672508744d55b8ae73011224bfc7f2696c2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/uri.test @@ -0,0 +1,325 @@ +# 2011 April 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Test organization: +# +# 1.*: That file names are correctly extracted from URIs. +# 2.*: That URI options (query parameters) are correctly extracted from URIs. +# 3.*: That specifying an unknown VFS causes an error. +# 4.*: Tests for specifying other options (other than "vfs"). +# 5.*: Test using a different VFS with an attached database. +# 6.*: Test that authorities other than "" and localhost cause errors. +# 7.*: Test that a read-write db can be attached to a read-only connection. +# + +set testprefix uri +db close +sqlite3_shutdown +sqlite3_config_uri 1 + +#------------------------------------------------------------------------- +# Test that file names are correctly extracted from URIs. +# +foreach {tn uri file} { + 1 test.db test.db + 2 file:test.db test.db + 3 file://PWD/test.db test.db + 4 file:PWD/test.db test.db + 5 file:test.db?mork=1 test.db + 6 file:test.db?mork=1&tonglor=2 test.db + 7 file:test.db?mork=1#boris test.db + 8 file:test.db#boris test.db + 9 test.db#boris test.db#boris + 10 file:test%2Edb test.db + 11 file file + 12 http:test.db http:test.db + 13 file:test.db%00extra test.db + 14 file:testdb%00.db%00extra testdb + + 15 test.db?mork=1#boris test.db?mork=1#boris + 16 file://localhostPWD/test.db%3Fhello test.db?hello +} { + + + ifcapable !curdir { if {$tn==3} break } + + if {$tcl_platform(platform)=="windows"} { + # + # NOTE: Due to limits on legal characters for file names imposed by + # Windows, we must skip the final two tests here (i.e. the + # question mark is illegal in a file name on Windows). + # + if {$tn>14} break + + # + # NOTE: On Windows, we need to account for the fact that the current + # directory does not start with a forward slash. + # + set uri [string map [list PWD/ /[test_pwd /]] $uri] + } else { + set uri [string map [list PWD/ [test_pwd /]] $uri] + } + + if {[file isdir $file]} {error "$file is a directory"} + forcedelete $file + do_test 1.$tn.1 { file exists $file } 0 + set DB [sqlite3_open $uri] + do_test 1.$tn.2 { file exists $file } 1 + sqlite3_close $DB + forcedelete $file + + do_test 1.$tn.3 { file exists $file } 0 + sqlite3 db xxx.db + catchsql { ATTACH $uri AS aux } + do_test 1.$tn.4 { file exists $file } 1 + db close +} + +#------------------------------------------------------------------------- +# Test that URI query parameters are passed through to the VFS layer +# correctly. +# +testvfs tvfs2 +testvfs tvfs -default 1 +tvfs filter xOpen +tvfs script open_method +proc open_method {method file arglist} { + set ::arglist $arglist +} +foreach {tn uri kvlist} { + 1 file:test.db?hello=world {hello world} + 2 file:test.db?hello&world {hello {} world {}} + 3 file:test.db?hello=1&world=2&vfs=tvfs {hello 1 world 2 vfs tvfs} + 4 file:test.db?hello=1&world=2&vfs=tvfs2 {} + 5 file:test.db?%68%65%6C%6C%6F=%77%6F%72%6C%64 {hello world} + 6 file:testdb%00.db?hello%00extra=world%00ex {hello world} + 7 file:testdb%00.db?hello%00=world%00 {hello world} + 8 file:testdb%00.db?=world&xyz=abc {xyz abc} + 9 file:test.db?%00hello=world&xyz=abc {xyz abc} + 10 file:test.db?hello=%00world&xyz= {hello {} xyz {}} + 11 file:test.db?=#ravada {} + 12 file:test.db?&&&&&&&&hello=world&&&&&&& {hello world} + + 13 test.db?&&&&&&&&hello=world&&&&&&& {} + 14 http:test.db?hello&world {} +} { + + if {$tcl_platform(platform) == "windows" && $tn>12} { + continue + } + + set ::arglist "" + set DB [sqlite3_open $uri] + do_test 2.$tn.1 { set ::arglist } $kvlist + sqlite3_close $DB + + sqlite3 db xxx.db + set ::arglist "" + execsql { ATTACH $uri AS aux } + do_test 2.$tn.2 { set ::arglist } $kvlist + db close +} +tvfs delete +tvfs2 delete + +#------------------------------------------------------------------------- +# Test that specifying a non-existent VFS raises an error. +# +do_test 3.1 { + list [catch { sqlite3 db "file:test.db?vfs=nosuchvfs" } msg] $msg +} {1 {no such vfs: nosuchvfs}} + +#------------------------------------------------------------------------- +# Test some of the other options (other than "vfs"). +# +foreach {tn mode create_ok write_ok readonly_ok} { + 1 ro 0 0 1 + 2 rw 0 1 0 + 3 rwc 1 1 0 +} { + catch { db close } + forcedelete test.db + + set A(1) {0 {}} + set A(0) {1 {unable to open database file}} + do_test 4.1.$tn.1 { + list [catch {sqlite3 db "file:test.db?mode=$mode"} msg] $msg + } $A($create_ok) + + catch { db close } + forcedelete test.db + sqlite3 db test.db + db eval { CREATE TABLE t1(a, b) } + db close + + set A(1) {0 {}} + set A(0) {1 {attempt to write a readonly database}} + do_test 4.1.$tn.2 { + sqlite3 db "file:test.db?mode=$mode" + catchsql { INSERT INTO t1 VALUES(1, 2) } + } $A($write_ok) + + set A(1) {0 {}} + set A(0) [list 1 "access mode not allowed: $mode"] + do_test 4.1.$tn.3 { + list [catch {sqlite3 db "file:test.db?mode=$mode" -readonly 1} msg] $msg + } $A($readonly_ok) +} + +set orig [sqlite3_enable_shared_cache] +foreach {tn options sc_default is_shared} { + 1 "" 1 1 + 2 "cache=private" 1 0 + 3 "cache=shared" 1 1 + 4 "" 0 0 + 5 "cache=private" 0 0 + 6 "cache=shared" 0 1 +} { + catch { db close } + forcedelete test.db + + sqlite3_enable_shared_cache 1 + sqlite3 db2 test.db + db2 eval {CREATE TABLE t1(a, b)} + + sqlite3_enable_shared_cache $sc_default + sqlite3 db "file:test.db?$options" + db eval {SELECT * FROM t1} + + set A(1) {1 {database table is locked: t1}} + set A(0) {0 {}} + do_test 4.2.$tn { + db2 eval {BEGIN; INSERT INTO t1 VALUES(1, 2);} + catchsql { SELECT * FROM t1 } + } $A($is_shared) + + db2 close +} + +do_test 4.3.1 { + list [catch {sqlite3 db "file:test.db?mode=rc"} msg] $msg +} {1 {no such access mode: rc}} +do_test 4.3.2 { + list [catch {sqlite3 db "file:test.db?cache=public"} msg] $msg +} {1 {no such cache mode: public}} + +#------------------------------------------------------------------------- +# Test that things work if an ATTACHed database uses a different VFS than +# the main database. The important point is that for all operations +# involving the ATTACHed database, the correct versions of the following +# VFS are used for all operations involving the attached database. +# +# xOpen +# xDelete +# xAccess +# xFullPathname +# + +# This block of code creates two VFS - "tvfs1" and "tvfs2". Each time one +# of the above methods is called using "tvfs1", global variable ::T1(X) is +# set, where X is the file-name the method is called on. Calls to the above +# methods using "tvfs2" set entries in the global T2 array. +# +ifcapable wal { + testvfs tvfs1 + tvfs1 filter {xOpen xDelete xAccess xFullPathname} + tvfs1 script tvfs1_callback + proc tvfs1_callback {method filename args} { + set ::T1([file tail $filename]) 1 + } + testvfs tvfs2 + tvfs2 filter {xOpen xDelete xAccess xFullPathname} + tvfs2 script tvfs2_callback + proc tvfs2_callback {method filename args} { + set ::T2([file tail $filename]) 1 + } + + catch {db close} + eval forcedelete [glob test.db*] + do_test 5.1.1 { + sqlite3 db file:test.db1?vfs=tvfs1 + execsql { + ATTACH 'file:test.db2?vfs=tvfs2' AS aux; + PRAGMA main.journal_mode = PERSIST; + PRAGMA aux.journal_mode = PERSIST; + CREATE TABLE t1(a, b); + CREATE TABLE aux.t2(a, b); + PRAGMA main.journal_mode = WAL; + PRAGMA aux.journal_mode = WAL; + INSERT INTO t1 VALUES('x', 'y'); + INSERT INTO t2 VALUES('x', 'y'); + } + lsort [array names ::T1] + } {test.db1 test.db1-journal test.db1-wal} + + do_test 5.1.2 { + lsort [array names ::T2] + } {test.db2 test.db2-journal test.db2-wal} + db close + + tvfs1 delete + tvfs2 delete +} + +#------------------------------------------------------------------------- +# Check that only "" and "localhost" are acceptable as authorities. +# +catch {db close} +foreach {tn uri res} { + 1 "file://localhost/PWD/test.db" {not an error} + 2 "file:///PWD/test.db" {not an error} + 3 "file:/PWD/test.db" {not an error} + 4 "file://l%6Fcalhost/PWD/test.db" {invalid uri authority: l%6Fcalhost} + 5 "file://lbcalhost/PWD/test.db" {invalid uri authority: lbcalhost} + 6 "file://x/PWD/test.db" {invalid uri authority: x} +} { + + if {$tcl_platform(platform)=="windows"} { + set uri [string map [list PWD [string range [get_pwd] 3 end]] $uri] + } else { + set uri [string map [list PWD [string range [get_pwd] 1 end]] $uri] + } + + do_test 6.$tn { + set DB [sqlite3_open $uri] + sqlite3_errmsg $DB + } $res + catch { sqlite3_close $DB } +} + +forcedelete test.db test.db2 +do_test 7.1 { + sqlite3 db test.db + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + ATTACH 'test.db2' AS aux; + CREATE TABLE aux.t2(a, b); + INSERT INTO t1 VALUES('a', 'b'); + } + db close +} {} +do_test 7.2 { + sqlite3 db file:test.db?mode=ro + execsql { ATTACH 'file:test.db2?mode=rw' AS aux } +} {} +do_execsql_test 7.3 { + INSERT INTO t2 VALUES('c', 'd') +} {} +do_catchsql_test 7.4 { + INSERT INTO t1 VALUES(3, 4) +} {1 {attempt to write a readonly database}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/utf16align.test b/components/external/SQLite-3.8.1/test/utf16align.test new file mode 100644 index 0000000000000000000000000000000000000000..f026d9575db73bd222185b9c423f538147126810 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/utf16align.test @@ -0,0 +1,95 @@ +# 2006 February 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains code to verify that the SQLITE_UTF16_ALIGNED +# flag passed into the sqlite3_create_collation() function insures +# that all strings passed to that function are aligned on an even +# byte boundary. +# +# $Id: utf16align.test,v 1.2 2008/11/07 03:29:34 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Skip this entire test if we do not support UTF16 +# +ifcapable !utf16 { + finish_test + return +} + +# Create a database with a UTF16 encoding. Put in lots of string +# data of varying lengths. +# +do_test utf16align-1.0 { + set unaligned_string_counter 0 + add_alignment_test_collations [sqlite3_connection_pointer db] + execsql { + PRAGMA encoding=UTF16; + CREATE TABLE t1( + id INTEGER PRIMARY KEY, + spacer TEXT, + a TEXT COLLATE utf16_aligned, + b TEXT COLLATE utf16_unaligned + ); + INSERT INTO t1(a) VALUES("abc"); + INSERT INTO t1(a) VALUES("defghi"); + INSERT INTO t1(a) VALUES("jklmnopqrstuv"); + INSERT INTO t1(a) VALUES("wxyz0123456789-"); + UPDATE t1 SET b=a||'-'||a; + INSERT INTO t1(a,b) SELECT a||b, b||a FROM t1; + INSERT INTO t1(a,b) SELECT a||b, b||a FROM t1; + INSERT INTO t1(a,b) SELECT a||b, b||a FROM t1; + INSERT INTO t1(a,b) VALUES('one','two'); + INSERT INTO t1(a,b) SELECT a, b FROM t1; + UPDATE t1 SET spacer = CASE WHEN rowid&1 THEN 'x' ELSE 'xx' END; + SELECT count(*) FROM t1; + } +} 66 +do_test utf16align-1.1 { + set unaligned_string_counter +} 0 + +# Creating an index that uses the unaligned collation. We should see +# some unaligned strings passed to the collating function. +# +do_test utf16align-1.2 { + execsql { + CREATE INDEX t1i1 ON t1(spacer, b); + } + # puts $unaligned_string_counter + expr {$unaligned_string_counter>0} +} 1 + +# Create another index that uses the aligned collation. This time +# there should be no unaligned accesses +# +do_test utf16align-1.3 { + set unaligned_string_counter 0 + execsql { + CREATE INDEX t1i2 ON t1(spacer, a); + } + expr {$unaligned_string_counter>0} +} 0 +integrity_check utf16align-1.4 + +# ticket #3482 +# +db close +sqlite3 db :memory: +do_test utf16align-2.1 { + db eval { + PRAGMA encoding=UTF16be; + SELECT hex(ltrim(x'6efcda')); + } +} {6EFC} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vacuum.test b/components/external/SQLite-3.8.1/test/vacuum.test new file mode 100644 index 0000000000000000000000000000000000000000..57429c29ea5f867d6e63c6272d3c05e15bd4cf14 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vacuum.test @@ -0,0 +1,404 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the VACUUM statement. +# +# $Id: vacuum.test,v 1.43 2009/01/31 14:54:07 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If the VACUUM statement is disabled in the current build, skip all +# the tests in this file. +# +ifcapable {!vacuum} { + omit_test vacuum.test {Compiled with SQLITE_OMIT_VACUUM} + finish_test + return +} +if $AUTOVACUUM { + omit_test vacuum.test {Auto-vacuum is enabled} + finish_test + return +} + +set fcnt 1 +do_test vacuum-1.1 { + execsql { + BEGIN; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c); + INSERT INTO t1 VALUES(NULL,randstr(10,100),randstr(5,50)); + INSERT INTO t1 VALUES(123456,randstr(10,100),randstr(5,50)); + INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT NULL, b||'-'||rowid, c||'-'||rowid FROM t1; + CREATE INDEX i1 ON t1(b,c); + CREATE UNIQUE INDEX i2 ON t1(c,a); + CREATE TABLE t2 AS SELECT * FROM t1; + COMMIT; + DROP TABLE t2; + } + set ::size1 [file size test.db] + set ::cksum [cksum] + expr {$::cksum!=""} +} {1} + +# Create bogus application-defined functions for functions used +# internally by VACUUM, to ensure that VACUUM falls back +# to the built-in functions. +# +proc failing_app_func {args} {error "bad function"} +do_test vacuum-1.1b { + db func substr failing_app_func + db func like failing_app_func + db func quote failing_app_func + catchsql {SELECT substr(name,1,3) FROM sqlite_master} +} {1 {bad function}} + +do_test vacuum-1.2 { + execsql { + VACUUM; + } + cksum +} $cksum +ifcapable vacuum { + do_test vacuum-1.3 { + expr {[file size test.db]<$::size1} + } {1} +} +do_test vacuum-1.4 { + set sql_script { + BEGIN; + CREATE TABLE t2 AS SELECT * FROM t1; + CREATE TABLE t3 AS SELECT * FROM t1; + CREATE VIEW v1 AS SELECT b, c FROM t3; + CREATE TRIGGER r1 AFTER DELETE ON t2 BEGIN SELECT 1; END; + COMMIT; + DROP TABLE t2; + } + # If the library was compiled to omit view support, comment out the + # create view in the script $sql_script before executing it. Similarly, + # if triggers are not supported, comment out the trigger definition. + ifcapable !view { + regsub {CREATE VIEW} $sql_script {-- CREATE VIEW} sql_script + } + ifcapable !trigger { + regsub {CREATE TRIGGER} $sql_script {-- CREATE TRIGGER} sql_script + } + execsql $sql_script + set ::size1 [file size test.db] + set ::cksum [cksum] + expr {$::cksum!=""} +} {1} +do_test vacuum-1.5 { + execsql { + VACUUM; + } + cksum +} $cksum + +ifcapable vacuum { + do_test vacuum-1.6 { + expr {[file size test.db]<$::size1} + } {1} +} +ifcapable vacuum { + do_test vacuum-2.1.1 { + catchsql { + BEGIN; + VACUUM; + } + } {1 {cannot VACUUM from within a transaction}} + do_test vacuum-2.1.2 { + sqlite3_get_autocommit db + } {0} + do_test vacuum-2.1.3 { + db eval {COMMIT} + } {} +} +do_test vacuum-2.2 { + sqlite3 db2 test.db + execsql { + BEGIN; + CREATE TABLE t4 AS SELECT * FROM t1; + CREATE TABLE t5 AS SELECT * FROM t1; + COMMIT; + DROP TABLE t4; + DROP TABLE t5; + } db2 + set ::cksum [cksum db2] + catchsql { + VACUUM + } +} {0 {}} +do_test vacuum-2.3 { + cksum +} $cksum +do_test vacuum-2.4 { + catch {db2 eval {SELECT count(*) FROM sqlite_master}} + cksum db2 +} $cksum + +# Make sure the schema cookie is incremented by vacuum. +# +do_test vacuum-2.5 { + execsql { + BEGIN; + CREATE TABLE t6 AS SELECT * FROM t1; + CREATE TABLE t7 AS SELECT * FROM t1; + COMMIT; + } + sqlite3 db3 test.db + execsql { + -- The "SELECT * FROM sqlite_master" statement ensures that this test + -- works when shared-cache is enabled. If shared-cache is enabled, then + -- db3 shares a cache with db2 (but not db - it was opened as + -- "./test.db"). + SELECT * FROM sqlite_master; + SELECT * FROM t7 LIMIT 1 + } db3 + execsql { + VACUUM; + } + execsql { + INSERT INTO t7 VALUES(1234567890,'hello','world'); + } db3 + execsql { + SELECT * FROM t7 WHERE a=1234567890 + } +} {1234567890 hello world} +integrity_check vacuum-2.6 +do_test vacuum-2.7 { + execsql { + SELECT * FROM t7 WHERE a=1234567890 + } db3 +} {1234567890 hello world} +do_test vacuum-2.8 { + execsql { + INSERT INTO t7 SELECT * FROM t6; + SELECT count(*) FROM t7; + } +} 513 +integrity_check vacuum-2.9 +do_test vacuum-2.10 { + execsql { + DELETE FROM t7; + SELECT count(*) FROM t7; + } db3 +} 0 +integrity_check vacuum-2.11 +db3 close + + +# Ticket #427. Make sure VACUUM works when the EMPTY_RESULT_CALLBACKS +# pragma is turned on. +# +do_test vacuum-3.1 { + db close + db2 close + delete_file test.db + sqlite3 db test.db + execsql { + PRAGMA empty_result_callbacks=on; + VACUUM; + } +} {} + +# Ticket #464. Make sure VACUUM works with the sqlite3_prepare() API. +# +do_test vacuum-4.1 { + db close + sqlite3 db test.db; set DB [sqlite3_connection_pointer db] + set VM [sqlite3_prepare $DB {VACUUM} -1 TAIL] + sqlite3_step $VM +} {SQLITE_DONE} +do_test vacuum-4.2 { + sqlite3_finalize $VM +} SQLITE_OK + +# Ticket #515. VACUUM after deleting and recreating the table that +# a view refers to. Omit this test if the library is not view-enabled. +# +ifcapable view { +do_test vacuum-5.1 { + db close + forcedelete test.db + sqlite3 db test.db + catchsql { + CREATE TABLE Test (TestID int primary key); + INSERT INTO Test VALUES (NULL); + CREATE VIEW viewTest AS SELECT * FROM Test; + + BEGIN; + CREATE TABLE tempTest (TestID int primary key, Test2 int NULL); + INSERT INTO tempTest SELECT TestID, 1 FROM Test; + DROP TABLE Test; + CREATE TABLE Test(TestID int primary key, Test2 int NULL); + INSERT INTO Test SELECT * FROM tempTest; + DROP TABLE tempTest; + COMMIT; + VACUUM; + } +} {0 {}} +do_test vacuum-5.2 { + catchsql { + VACUUM; + } +} {0 {}} +} ;# ifcapable view + +# Ensure vacuum works with complicated tables names. +do_test vacuum-6.1 { + execsql { + CREATE TABLE "abc abc"(a, b, c); + INSERT INTO "abc abc" VALUES(1, 2, 3); + VACUUM; + } +} {} +do_test vacuum-6.2 { + execsql { + select * from "abc abc"; + } +} {1 2 3} + +# Also ensure that blobs survive a vacuum. +ifcapable {bloblit} { + do_test vacuum-6.3 { + execsql { + DELETE FROM "abc abc"; + INSERT INTO "abc abc" VALUES(X'00112233', NULL, NULL); + VACUUM; + } + } {} + do_test vacuum-6.4 { + execsql { + select count(*) from "abc abc" WHERE a = X'00112233'; + } + } {1} +} + +# Check what happens when an in-memory database is vacuumed. The +# [delete_file] command covers us in case the library was compiled +# without in-memory database support. +# +forcedelete :memory: +do_test vacuum-7.0 { + sqlite3 db2 :memory: + execsql { + CREATE TABLE t1(t); + VACUUM; + } db2 +} {} +do_test vacuum-7.1 { + execsql { + CREATE TABLE t2(t); + CREATE TABLE t3(t); + DROP TABLE t2; + PRAGMA freelist_count; + } +} {1} +do_test vacuum-7.2 { + execsql { + VACUUM; + pragma integrity_check; + } db2 +} {ok} +do_test vacuum-7.3 { + execsql { PRAGMA freelist_count; } db2 +} {0} +ifcapable autovacuum { + do_test vacuum-7.4 { + execsql { PRAGMA auto_vacuum } db2 + } {0} + do_test vacuum-7.5 { + execsql { PRAGMA auto_vacuum = 1} db2 + execsql { PRAGMA auto_vacuum } db2 + } {0} + do_test vacuum-7.6 { + execsql { PRAGMA auto_vacuum = 1} db2 + execsql { VACUUM } db2 + execsql { PRAGMA auto_vacuum } db2 + } {1} +} +db2 close + +# Ticket #873. VACUUM a database that has ' in its name. +# +do_test vacuum-8.1 { + forcedelete a'z.db + forcedelete a'z.db-journal + sqlite3 db2 a'z.db + execsql { + CREATE TABLE t1(t); + VACUUM; + } db2 +} {} +db2 close + +# Ticket #1095: Vacuum a table that uses AUTOINCREMENT +# +ifcapable {autoinc} { + do_test vacuum-9.1 { + execsql { + DROP TABLE 'abc abc'; + CREATE TABLE autoinc(a INTEGER PRIMARY KEY AUTOINCREMENT, b); + INSERT INTO autoinc(b) VALUES('hi'); + INSERT INTO autoinc(b) VALUES('there'); + DELETE FROM autoinc; + } + set ::cksum [cksum] + expr {$::cksum!=""} + } {1} + do_test vacuum-9.2 { + execsql { + VACUUM; + } + cksum + } $::cksum + do_test vacuum-9.3 { + execsql { + INSERT INTO autoinc(b) VALUES('one'); + INSERT INTO autoinc(b) VALUES('two'); + } + set ::cksum [cksum] + expr {$::cksum!=""} + } {1} + do_test vacuum-9.4 { + execsql { + VACUUM; + } + cksum + } $::cksum +} + +forcedelete {a'z.db} + +# Test that "PRAGMA count_changes" does not interfere with VACUUM or cause +# it to return any rows to the user. +# +do_test vacuum-10.1 { + db close + forcedelete test.db + sqlite3 db test.db + execsql { + CREATE TABLE t8(a, b); + INSERT INTO t8 VALUES('a', 'b'); + INSERT INTO t8 VALUES('c', 'd'); + PRAGMA count_changes = 1; + } +} {} +do_test vacuum-10.2 { execsql VACUUM } {} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vacuum2.test b/components/external/SQLite-3.8.1/test/vacuum2.test new file mode 100644 index 0000000000000000000000000000000000000000..b3bfab30228f4adc236adeb2bbbe29312b15de8e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vacuum2.test @@ -0,0 +1,231 @@ +# 2005 February 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the VACUUM statement. +# +# $Id: vacuum2.test,v 1.10 2009/02/18 20:31:18 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Do not use a codec for tests in this file, as the database file is +# manipulated directly using tcl scripts (using the [hexio_write] command). +# +do_not_use_codec + +# If the VACUUM statement is disabled in the current build, skip all +# the tests in this file. +# +ifcapable {!vacuum||!autoinc} { + finish_test + return +} +if $AUTOVACUUM { + finish_test + return +} + +# Ticket #1121 - make sure vacuum works if all autoincrement tables +# have been deleted. +# +do_test vacuum2-1.1 { + execsql { + CREATE TABLE t1(x INTEGER PRIMARY KEY AUTOINCREMENT, y); + DROP TABLE t1; + VACUUM; + } +} {} + +# Ticket #2518. Make sure vacuum increments the change counter +# in the database header. +# +do_test vacuum2-2.1 { + execsql { + CREATE TABLE t1(x); + CREATE TABLE t2(y); + INSERT INTO t1 VALUES(1); + } + hexio_get_int [hexio_read test.db 24 4] +} [expr {[hexio_get_int [hexio_read test.db 24 4]]+3}] +do_test vacuum2-2.1 { + execsql { + VACUUM + } + hexio_get_int [hexio_read test.db 24 4] +} [expr {[hexio_get_int [hexio_read test.db 24 4]]+1}] + +############################################################################ +# Verify that we can use the auto_vacuum pragma to request a new +# autovacuum setting, do a VACUUM, and the new setting takes effect. +# Make sure this happens correctly even if there are multiple open +# connections to the same database file. +# +sqlite3 db2 test.db +set pageSize [db eval {pragma page_size}] + +# We are currently not autovacuuming so the database should be 3 pages +# in size. 1 page for each of sqlite_master, t1, and t2. +# +do_test vacuum2-3.1 { + execsql { + INSERT INTO t1 VALUES('hello'); + INSERT INTO t2 VALUES('out there'); + } + expr {[file size test.db]/$pageSize} +} {3} +set cksum [cksum] +do_test vacuum2-3.2 { + cksum db2 +} $cksum + +# Convert the database to an autovacuumed database. +ifcapable autovacuum { + do_test vacuum2-3.3 { + execsql { + PRAGMA auto_vacuum=FULL; + VACUUM; + } + expr {[file size test.db]/$pageSize} + } {4} +} +do_test vacuum2-3.4 { + cksum db2 +} $cksum +do_test vacuum2-3.5 { + cksum +} $cksum +do_test vacuum2-3.6 { + execsql {PRAGMA integrity_check} db2 +} {ok} +do_test vacuum2-3.7 { + execsql {PRAGMA integrity_check} db +} {ok} + +# Convert the database back to a non-autovacuumed database. +do_test vacuum2-3.13 { + execsql { + PRAGMA auto_vacuum=NONE; + VACUUM; + } + expr {[file size test.db]/$pageSize} +} {3} +do_test vacuum2-3.14 { + cksum db2 +} $cksum +do_test vacuum2-3.15 { + cksum +} $cksum +do_test vacuum2-3.16 { + execsql {PRAGMA integrity_check} db2 +} {ok} +do_test vacuum2-3.17 { + execsql {PRAGMA integrity_check} db +} {ok} + +db2 close + +ifcapable autovacuum { + do_test vacuum2-4.1 { + db close + forcedelete test.db + sqlite3 db test.db + execsql { + pragma auto_vacuum=1; + create table t(a, b); + insert into t values(1, 2); + insert into t values(1, 2); + pragma auto_vacuum=0; + vacuum; + pragma auto_vacuum; + } + } {0} + do_test vacuum2-4.2 { + execsql { + pragma auto_vacuum=1; + vacuum; + pragma auto_vacuum; + } + } {1} + do_test vacuum2-4.3 { + execsql { + pragma integrity_check + } + } {ok} + do_test vacuum2-4.4 { + db close + sqlite3 db test.db + execsql { + pragma auto_vacuum; + } + } {1} + do_test vacuum2-4.5 { # Ticket #3663 + execsql { + pragma auto_vacuum=2; + vacuum; + pragma auto_vacuum; + } + } {2} + do_test vacuum2-4.6 { + execsql { + pragma integrity_check + } + } {ok} + do_test vacuum2-4.7 { + db close + sqlite3 db test.db + execsql { + pragma auto_vacuum; + } + } {2} +} + + +#------------------------------------------------------------------------- +# The following block of tests verify the behaviour of the library when +# a database is VACUUMed when there are one or more unfinalized SQL +# statements reading the same database using the same db handle. +# +db close +forcedelete test.db +sqlite3 db test.db +do_execsql_test vacuum2-5.1 { + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + INSERT INTO t1 VALUES(1, randomblob(500)); + INSERT INTO t1 SELECT a+1, randomblob(500) FROM t1; -- 2 + INSERT INTO t1 SELECT a+2, randomblob(500) FROM t1; -- 4 + INSERT INTO t1 SELECT a+4, randomblob(500) FROM t1; -- 8 + INSERT INTO t1 SELECT a+8, randomblob(500) FROM t1; -- 16 +} {} + +do_test vacuum2-5.2 { + list [catch { + db eval {SELECT a, b FROM t1} { if {$a == 8} { execsql VACUUM } } + } msg] $msg +} {1 {cannot VACUUM - SQL statements in progress}} + +do_test vacuum2-5.3 { + list [catch { + db eval {SELECT 1, 2, 3} { execsql VACUUM } + } msg] $msg +} {1 {cannot VACUUM - SQL statements in progress}} + +do_test vacuum2-5.4 { + set res "" + set res2 "" + db eval {SELECT a, b FROM t1 WHERE a<=10} { + if {$a==6} { set res [catchsql VACUUM] } + lappend res2 $a + } + lappend res2 $res +} {1 2 3 4 5 6 7 8 9 10 {1 {cannot VACUUM - SQL statements in progress}}} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vacuum3.test b/components/external/SQLite-3.8.1/test/vacuum3.test new file mode 100644 index 0000000000000000000000000000000000000000..484a7d448a7e798ceba6a40dbccad26718a01f76 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vacuum3.test @@ -0,0 +1,340 @@ +# 2007 March 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is changing the database page size using a +# VACUUM statement. +# +# $Id: vacuum3.test,v 1.9 2008/08/26 21:07:27 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If the VACUUM statement is disabled in the current build, skip all +# the tests in this file. +# +ifcapable !vacuum { + finish_test + return +} + + +#------------------------------------------------------------------- +# Test cases vacuum3-1.* convert a simple 2-page database between a +# few different page sizes. +# +do_test vacuum3-1.1 { + execsql { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, 2, 3); + } +} {} +do_test vacuum3-1.2 { + execsql { PRAGMA page_size } +} {1024} +do_test vacuum3-1.3 { + file size test.db +} {2048} + +set I 4 +foreach {request actual database} [list \ + 2048 2048 4096 \ + 1024 1024 2048 \ + 1170 1024 2048 \ + 256 1024 2048 \ + 512 512 1024 \ + 4096 4096 8192 \ + 1024 1024 2048 \ +] { + do_test vacuum3-1.$I.1 { + execsql " + PRAGMA page_size = $request; + VACUUM; + " + execsql { PRAGMA page_size } + } $actual + do_test vacuum3-1.$I.2 { + file size test.db + } $database + do_test vacuum3-1.$I.3 { + execsql { SELECT * FROM t1 } + } {1 2 3} + integrity_check vacuum3-1.$I.4 + + incr I +} + +#------------------------------------------------------------------- +# Test cases vacuum3-2.* convert a simple 3-page database between a +# few different page sizes. +# +do_test vacuum3-2.1 { + execsql { + PRAGMA page_size = 1024; + VACUUM; + ALTER TABLE t1 ADD COLUMN d; + UPDATE t1 SET d = randomblob(1000); + } + file size test.db +} {3072} +do_test vacuum3-2.2 { + execsql { PRAGMA page_size } +} {1024} +do_test vacuum3-2.3 { + set blob [db one {select d from t1}] + string length $blob +} {1000} + +set I 4 +foreach {request actual database} [list \ + 2048 2048 4096 \ + 1024 1024 3072 \ + 1170 1024 3072 \ + 256 1024 3072 \ + 512 512 2048 \ + 4096 4096 8192 \ + 1024 1024 3072 \ +] { + do_test vacuum3-2.$I.1 { + execsql " + PRAGMA page_size = $request; + VACUUM; + " + execsql { PRAGMA page_size } + } $actual + do_test vacuum3-2.$I.2 { + file size test.db + } $database + do_test vacuum3-2.$I.3 { + execsql { SELECT * FROM t1 } + } [list 1 2 3 $blob] + integrity_check vacuum3-1.$I.4 + + incr I +} + +#------------------------------------------------------------------- +# Test cases vacuum3-3.* converts a database large enough to include +# the locking page (in a test environment) between few different +# page sizes. +# +proc signature {} { + return [db eval {SELECT count(*), md5sum(a), md5sum(b), md5sum(c) FROM abc}] +} +do_test vacuum3-3.1 { + execsql " + PRAGMA page_size = 1024; + BEGIN; + CREATE TABLE abc(a PRIMARY KEY, b, c); + INSERT INTO abc VALUES(randomblob(100), randomblob(200), randomblob(1000)); + INSERT INTO abc + SELECT randomblob(1000), randomblob(200), randomblob(100) + FROM abc; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc; + INSERT INTO abc + SELECT randomblob(25), randomblob(45), randomblob(9456) + FROM abc; + INSERT INTO abc + SELECT randomblob(100), randomblob(200), randomblob(1000) + FROM abc; + INSERT INTO abc + SELECT randomblob(25), randomblob(45), randomblob(9456) + FROM abc; + COMMIT; + " +} {} +do_test vacuum3-3.2 { + execsql { PRAGMA page_size } +} {1024} + +set ::sig [signature] + +set I 3 +foreach {request actual} [list \ + 2048 2048 \ + 1024 1024 \ + 1170 1024 \ + 256 1024 \ + 512 512 \ + 4096 4096 \ + 1024 1024 \ +] { + do_test vacuum3-3.$I.1 { + execsql " + PRAGMA page_size = $request; + VACUUM; + " + execsql { PRAGMA page_size } + } $actual + do_test vacuum3-3.$I.2 { + signature + } $::sig + integrity_check vacuum3-3.$I.3 + + incr I +} + +do_test vacuum3-4.1 { + db close + delete_file test.db + sqlite3 db test.db + execsql { + PRAGMA page_size=1024; + CREATE TABLE abc(a, b, c); + INSERT INTO abc VALUES(1, 2, 3); + INSERT INTO abc VALUES(4, 5, 6); + } + execsql { SELECT * FROM abc } +} {1 2 3 4 5 6} +do_test vacuum3-4.2 { + sqlite3 db2 test.db + execsql { SELECT * FROM abc } db2 +} {1 2 3 4 5 6} +do_test vacuum3-4.3 { + execsql { + PRAGMA page_size = 2048; + VACUUM; + } + execsql { SELECT * FROM abc } +} {1 2 3 4 5 6} +do_test vacuum3-4.4 { + execsql { SELECT * FROM abc } db2 +} {1 2 3 4 5 6} +do_test vacuum3-4.5 { + execsql { + PRAGMA page_size=16384; + VACUUM; + } db2 + execsql { SELECT * FROM abc } db2 +} {1 2 3 4 5 6} +do_test vacuum3-4.6 { + execsql { + PRAGMA page_size=1024; + VACUUM; + } + execsql { SELECT * FROM abc } db2 +} {1 2 3 4 5 6} + +# Unable to change the page-size of an in-memory using vacuum. +db2 close +sqlite3 db2 :memory: +do_test vacuum3-5.1 { + db2 eval { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1234); + PRAGMA page_size=4096; + VACUUM; + SELECT * FROM t1; + } +} {1234} +do_test vacuum3-5.2 { + db2 eval { + PRAGMA page_size + } +} {1024} + +set create_database_sql { + BEGIN; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, randstr(50,50), randstr(50,50)); + INSERT INTO t1 SELECT a+2, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+4, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+8, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+16, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+32, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+64, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+128, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 VALUES(1, randstr(600,600), randstr(600,600)); + CREATE TABLE t2 AS SELECT * FROM t1; + CREATE TABLE t3 AS SELECT * FROM t1; + COMMIT; + DROP TABLE t2; +} + +do_ioerr_test vacuum3-ioerr-1 -cksum true -sqlprep " + PRAGMA page_size = 1024; + $create_database_sql +" -sqlbody { + PRAGMA page_size = 4096; + VACUUM; +} +do_ioerr_test vacuum3-ioerr-2 -cksum true -sqlprep " + PRAGMA page_size = 2048; + $create_database_sql +" -sqlbody { + PRAGMA page_size = 512; + VACUUM; +} + +ifcapable autovacuum { + do_ioerr_test vacuum3-ioerr-3 -cksum true -sqlprep " + PRAGMA auto_vacuum = 0; + $create_database_sql + " -sqlbody { + PRAGMA auto_vacuum = 1; + VACUUM; + } + do_ioerr_test vacuum3-ioerr-4 -cksum true -sqlprep " + PRAGMA auto_vacuum = 1; + $create_database_sql + " -sqlbody { + PRAGMA auto_vacuum = 0; + VACUUM; + } +} + +source $testdir/malloc_common.tcl +if {$MEMDEBUG} { + do_malloc_test vacuum3-malloc-1 -sqlprep { + PRAGMA page_size = 2048; + BEGIN; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, randstr(50,50), randstr(50,50)); + INSERT INTO t1 SELECT a+2, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+4, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+8, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+16, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+32, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+64, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 SELECT a+128, b||'-'||rowid, c||'-'||rowid FROM t1; + INSERT INTO t1 VALUES(1, randstr(600,600), randstr(600,600)); + CREATE TABLE t2 AS SELECT * FROM t1; + CREATE TABLE t3 AS SELECT * FROM t1; + COMMIT; + DROP TABLE t2; + } -sqlbody { + PRAGMA page_size = 512; + VACUUM; + } + do_malloc_test vacuum3-malloc-2 -sqlprep { + PRAGMA encoding=UTF16; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, 2, 3); + CREATE TABLE t2(x,y,z); + INSERT INTO t2 SELECT * FROM t1; + } -sqlbody { + VACUUM; + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vacuum4.test b/components/external/SQLite-3.8.1/test/vacuum4.test new file mode 100644 index 0000000000000000000000000000000000000000..326d0372764cf98e44cb40a889a3051d9d8a6096 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vacuum4.test @@ -0,0 +1,67 @@ +# 2010 February 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements a test of ticket [da1151f97df244a1]: An +# assertion fault while VACUUMing an auto_vacuumed database with +# large schema. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# If the VACUUM statement is disabled in the current build, skip all +# the tests in this file. +# +ifcapable !vacuum { + finish_test + return +} + +do_test vacuum4-1.1 { + db eval { + PRAGMA auto_vacuum=FULL; + CREATE TABLE t1( + c000, c001, c002, c003, c004, c005, c006, c007, c008, c009, + c010, c011, c012, c013, c014, c015, c016, c017, c018, c019, + c020, c021, c022, c023, c024, c025, c026, c027, c028, c029, + c030, c031, c032, c033, c034, c035, c036, c037, c038, c039, + c040, c041, c042, c043, c044, c045, c046, c047, c048, c049, + c050, c051, c052, c053, c054, c055, c056, c057, c058, c059, + c060, c061, c062, c063, c064, c065, c066, c067, c068, c069, + c070, c071, c072, c073, c074, c075, c076, c077, c078, c079, + c080, c081, c082, c083, c084, c085, c086, c087, c088, c089, + c090, c091, c092, c093, c094, c095, c096, c097, c098, c099, + c100, c101, c102, c103, c104, c105, c106, c107, c108, c109, + c110, c111, c112, c113, c114, c115, c116, c117, c118, c119, + c120, c121, c122, c123, c124, c125, c126, c127, c128, c129, + c130, c131, c132, c133, c134, c135, c136, c137, c138, c139, + c140, c141, c142, c143, c144, c145, c146, c147, c148, c149 + ); + CREATE TABLE t2( + c000, c001, c002, c003, c004, c005, c006, c007, c008, c009, + c010, c011, c012, c013, c014, c015, c016, c017, c018, c019, + c020, c021, c022, c023, c024, c025, c026, c027, c028, c029, + c030, c031, c032, c033, c034, c035, c036, c037, c038, c039, + c040, c041, c042, c043, c044, c045, c046, c047, c048, c049, + c050, c051, c052, c053, c054, c055, c056, c057, c058, c059, + c060, c061, c062, c063, c064, c065, c066, c067, c068, c069, + c070, c071, c072, c073, c074, c075, c076, c077, c078, c079, + c080, c081, c082, c083, c084, c085, c086, c087, c088, c089, + c090, c091, c092, c093, c094, c095, c096, c097, c098, c099, + c100, c101, c102, c103, c104, c105, c106, c107, c108, c109, + c110, c111, c112, c113, c114, c115, c116, c117, c118, c119, + c120, c121, c122, c123, c124, c125, c126, c127, c128, c129, + c130, c131, c132, c133, c134, c135, c136, c137, c138, c139, + c140, c141, c142, c143, c144, c145, c146, c147, c148, c149 + ); + VACUUM; + } +} {} diff --git a/components/external/SQLite-3.8.1/test/varint.test b/components/external/SQLite-3.8.1/test/varint.test new file mode 100644 index 0000000000000000000000000000000000000000..974e88f2a6f486a19d8b5c163e3c6df05414b867 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/varint.test @@ -0,0 +1,32 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is variable-length integer encoding scheme. +# +# $Id: varint.test,v 1.1 2004/05/18 15:57:42 drh Exp $ + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Test reading and writing of varints. +# +set cnt 0 +foreach start {0 100 10000 1000000 0x10000000} { + foreach mult {1 0x10 0x100 0x1000 0x10000 0x100000 0x1000000 0x10000000} { + foreach incr {1 500 10000 50000000} { + incr cnt + do_test varint-1.$cnt { + btree_varint_test $start $mult 5000 $incr + } {} + } + } +} diff --git a/components/external/SQLite-3.8.1/test/veryquick.test b/components/external/SQLite-3.8.1/test/veryquick.test new file mode 100644 index 0000000000000000000000000000000000000000..c8d6ce8f8bf8351b25d10ae002c3eb93939e20fb --- /dev/null +++ b/components/external/SQLite-3.8.1/test/veryquick.test @@ -0,0 +1,18 @@ +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file runs all the tests run by quick.test except for those related +# to malloc or IO error simulation. With these tests omitted, the overall +# run time is reduced by about 75%. +# +# $Id: veryquick.test,v 1.9 2008/07/12 14:52:21 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/permutations.test + +run_test_suite veryquick + +finish_test diff --git a/components/external/SQLite-3.8.1/test/view.test b/components/external/SQLite-3.8.1/test/view.test new file mode 100644 index 0000000000000000000000000000000000000000..779f77b6aed68f0dbb0264daf51114b33731edb6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/view.test @@ -0,0 +1,614 @@ +# 2002 February 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing VIEW statements. +# +# $Id: view.test,v 1.39 2008/12/14 14:45:21 danielk1977 Exp $ +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Omit this entire file if the library is not configured with views enabled. +ifcapable !view { + finish_test + return +} + +do_test view-1.0 { + execsql { + CREATE TABLE t1(a,b,c); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(4,5,6); + INSERT INTO t1 VALUES(7,8,9); + SELECT * FROM t1; + } +} {1 2 3 4 5 6 7 8 9} + +do_test view-1.1 { + execsql { + BEGIN; + CREATE VIEW IF NOT EXISTS v1 AS SELECT a,b FROM t1; + SELECT * FROM v1 ORDER BY a; + } +} {1 2 4 5 7 8} +do_test view-1.2 { + catchsql { + ROLLBACK; + SELECT * FROM v1 ORDER BY a; + } +} {1 {no such table: v1}} +do_test view-1.3 { + execsql { + CREATE VIEW v1 AS SELECT a,b FROM t1; + SELECT * FROM v1 ORDER BY a; + } +} {1 2 4 5 7 8} +do_test view-1.3.1 { + db close + sqlite3 db test.db + execsql { + SELECT * FROM v1 ORDER BY a; + } +} {1 2 4 5 7 8} +do_test view-1.4 { + catchsql { + DROP VIEW IF EXISTS v1; + SELECT * FROM v1 ORDER BY a; + } +} {1 {no such table: v1}} +do_test view-1.5 { + execsql { + CREATE VIEW v1 AS SELECT a,b FROM t1; + SELECT * FROM v1 ORDER BY a; + } +} {1 2 4 5 7 8} +do_test view-1.6 { + catchsql { + DROP TABLE t1; + SELECT * FROM v1 ORDER BY a; + } +} {1 {no such table: main.t1}} +do_test view-1.7 { + execsql { + CREATE TABLE t1(x,a,b,c); + INSERT INTO t1 VALUES(1,2,3,4); + INSERT INTO t1 VALUES(4,5,6,7); + INSERT INTO t1 VALUES(7,8,9,10); + SELECT * FROM v1 ORDER BY a; + } +} {2 3 5 6 8 9} +do_test view-1.8 { + db close + sqlite3 db test.db + execsql { + SELECT * FROM v1 ORDER BY a; + } +} {2 3 5 6 8 9} + +do_test view-2.1 { + execsql { + CREATE VIEW v2 AS SELECT * FROM t1 WHERE a>5 + }; # No semicolon + execsql2 { + SELECT * FROM v2; + } +} {x 7 a 8 b 9 c 10} +do_test view-2.2 { + catchsql { + INSERT INTO v2 VALUES(1,2,3,4); + } +} {1 {cannot modify v2 because it is a view}} +do_test view-2.3 { + catchsql { + UPDATE v2 SET a=10 WHERE a=5; + } +} {1 {cannot modify v2 because it is a view}} +do_test view-2.4 { + catchsql { + DELETE FROM v2; + } +} {1 {cannot modify v2 because it is a view}} +do_test view-2.5 { + execsql { + INSERT INTO t1 VALUES(11,12,13,14); + SELECT * FROM v2 ORDER BY x; + } +} {7 8 9 10 11 12 13 14} +do_test view-2.6 { + execsql { + SELECT x FROM v2 WHERE a>10 + } +} {11} + +# Test that column name of views are generated correctly. +# +do_test view-3.1 { + execsql2 { + SELECT * FROM v1 LIMIT 1 + } +} {a 2 b 3} +do_test view-3.2 { + execsql2 { + SELECT * FROM v2 LIMIT 1 + } +} {x 7 a 8 b 9 c 10} +do_test view-3.3.1 { + execsql2 { + DROP VIEW v1; + CREATE VIEW v1 AS SELECT a AS 'xyz', b+c AS 'pqr', c-b FROM t1; + SELECT * FROM v1 LIMIT 1 + } +} {xyz 2 pqr 7 c-b 1} +do_test view-3.3.2 { + execsql2 { + CREATE VIEW v1b AS SELECT t1.a, b+c, t1.c FROM t1; + SELECT * FROM v1b LIMIT 1 + } +} {a 2 b+c 7 c 4} + +ifcapable compound { +do_test view-3.4 { + execsql2 { + CREATE VIEW v3 AS SELECT a FROM t1 UNION SELECT b FROM t1 ORDER BY b; + SELECT * FROM v3 LIMIT 4; + } +} {a 2 a 3 a 5 a 6} +do_test view-3.5 { + execsql2 { + CREATE VIEW v4 AS + SELECT a, b FROM t1 + UNION + SELECT b AS 'x', a AS 'y' FROM t1 + ORDER BY x, y; + SELECT b FROM v4 ORDER BY b LIMIT 4; + } +} {b 2 b 3 b 5 b 6} +} ;# ifcapable compound + + +do_test view-4.1 { + catchsql { + DROP VIEW t1; + } +} {1 {use DROP TABLE to delete table t1}} +do_test view-4.2 { + execsql { + SELECT 1 FROM t1 LIMIT 1; + } +} 1 +do_test view-4.3 { + catchsql { + DROP TABLE v1; + } +} {1 {use DROP VIEW to delete view v1}} +do_test view-4.4 { + execsql { + SELECT 1 FROM v1 LIMIT 1; + } +} {1} +do_test view-4.5 { + catchsql { + CREATE INDEX i1v1 ON v1(xyz); + } +} {1 {views may not be indexed}} + +do_test view-5.1 { + execsql { + CREATE TABLE t2(y,a); + INSERT INTO t2 VALUES(22,2); + INSERT INTO t2 VALUES(33,3); + INSERT INTO t2 VALUES(44,4); + INSERT INTO t2 VALUES(55,5); + SELECT * FROM t2; + } +} {22 2 33 3 44 4 55 5} +do_test view-5.2 { + execsql { + CREATE VIEW v5 AS + SELECT t1.x AS v, t2.y AS w FROM t1 JOIN t2 USING(a); + SELECT * FROM v5; + } +} {1 22 4 55} + +# Verify that the view v5 gets flattened. see sqliteFlattenSubquery(). +# This will only work if EXPLAIN is enabled. +# Ticket #272 +# +ifcapable {explain} { +do_test view-5.3 { + lsearch [execsql { + EXPLAIN SELECT * FROM v5; + }] OpenEphemeral +} {-1} +do_test view-5.4 { + execsql { + SELECT * FROM v5 AS a, t2 AS b WHERE a.w=b.y; + } +} {1 22 22 2 4 55 55 5} +do_test view-5.5 { + lsearch [execsql { + EXPLAIN SELECT * FROM v5 AS a, t2 AS b WHERE a.w=b.y; + }] OpenEphemeral +} {-1} +do_test view-5.6 { + execsql { + SELECT * FROM t2 AS b, v5 AS a WHERE a.w=b.y; + } +} {22 2 1 22 55 5 4 55} +do_test view-5.7 { + lsearch [execsql { + EXPLAIN SELECT * FROM t2 AS b, v5 AS a WHERE a.w=b.y; + }] OpenEphemeral +} {-1} +do_test view-5.8 { + execsql { + SELECT * FROM t1 AS a, v5 AS b, t2 AS c WHERE a.x=b.v AND b.w=c.y; + } +} {1 2 3 4 1 22 22 2 4 5 6 7 4 55 55 5} +do_test view-5.9 { + lsearch [execsql { + EXPLAIN SELECT * FROM t1 AS a, v5 AS b, t2 AS c WHERE a.x=b.v AND b.w=c.y; + }] OpenEphemeral +} {-1} +} ;# endif explain + +do_test view-6.1 { + execsql { + SELECT min(x), min(a), min(b), min(c), min(a+b+c) FROM v2; + } +} {7 8 9 10 27} +do_test view-6.2 { + execsql { + SELECT max(x), max(a), max(b), max(c), max(a+b+c) FROM v2; + } +} {11 12 13 14 39} + +do_test view-7.1 { + execsql { + CREATE TABLE test1(id integer primary key, a); + CREATE TABLE test2(id integer, b); + INSERT INTO test1 VALUES(1,2); + INSERT INTO test2 VALUES(1,3); + CREATE VIEW test AS + SELECT test1.id, a, b + FROM test1 JOIN test2 ON test2.id=test1.id; + SELECT * FROM test; + } +} {1 2 3} +do_test view-7.2 { + db close + sqlite3 db test.db + execsql { + SELECT * FROM test; + } +} {1 2 3} +do_test view-7.3 { + execsql { + DROP VIEW test; + CREATE VIEW test AS + SELECT test1.id, a, b + FROM test1 JOIN test2 USING(id); + SELECT * FROM test; + } +} {1 2 3} +do_test view-7.4 { + db close + sqlite3 db test.db + execsql { + SELECT * FROM test; + } +} {1 2 3} +do_test view-7.5 { + execsql { + DROP VIEW test; + CREATE VIEW test AS + SELECT test1.id, a, b + FROM test1 NATURAL JOIN test2; + SELECT * FROM test; + } +} {1 2 3} +do_test view-7.6 { + db close + sqlite3 db test.db + execsql { + SELECT * FROM test; + } +} {1 2 3} + +do_test view-8.1 { + execsql { + CREATE VIEW v6 AS SELECT pqr, xyz FROM v1; + SELECT * FROM v6 ORDER BY xyz; + } +} {7 2 13 5 19 8 27 12} +do_test view-8.2 { + db close + sqlite3 db test.db + execsql { + SELECT * FROM v6 ORDER BY xyz; + } +} {7 2 13 5 19 8 27 12} +do_test view-8.3 { + execsql { + CREATE VIEW v7 AS SELECT pqr+xyz AS a FROM v6; + SELECT * FROM v7 ORDER BY a; + } +} {9 18 27 39} + +ifcapable subquery { + do_test view-8.4 { + execsql { + CREATE VIEW v8 AS SELECT max(cnt) AS mx FROM + (SELECT a%2 AS eo, count(*) AS cnt FROM t1 GROUP BY eo); + SELECT * FROM v8; + } + } 3 + do_test view-8.5 { + execsql { + SELECT mx+10, mx*2 FROM v8; + } + } {13 6} + do_test view-8.6 { + execsql { + SELECT mx+10, pqr FROM v6, v8 WHERE xyz=2; + } + } {13 7} + do_test view-8.7 { + execsql { + SELECT mx+10, pqr FROM v6, v8 WHERE xyz>2; + } + } {13 13 13 19 13 27} +} ;# ifcapable subquery + +# Tests for a bug found by Michiel de Wit involving ORDER BY in a VIEW. +# +do_test view-9.1 { + execsql { + INSERT INTO t2 SELECT * FROM t2 WHERE a<5; + INSERT INTO t2 SELECT * FROM t2 WHERE a<4; + INSERT INTO t2 SELECT * FROM t2 WHERE a<3; + SELECT DISTINCT count(*) FROM t2 GROUP BY a ORDER BY 1; + } +} {1 2 4 8} +do_test view-9.2 { + execsql { + SELECT DISTINCT count(*) FROM t2 GROUP BY a ORDER BY 1 LIMIT 3; + } +} {1 2 4} +do_test view-9.3 { + execsql { + CREATE VIEW v9 AS + SELECT DISTINCT count(*) FROM t2 GROUP BY a ORDER BY 1 LIMIT 3; + SELECT * FROM v9; + } +} {1 2 4} +do_test view-9.4 { + execsql { + SELECT * FROM v9 ORDER BY 1 DESC; + } +} {4 2 1} +do_test view-9.5 { + execsql { + CREATE VIEW v10 AS + SELECT DISTINCT a, count(*) FROM t2 GROUP BY a ORDER BY 2 LIMIT 3; + SELECT * FROM v10; + } +} {5 1 4 2 3 4} +do_test view-9.6 { + execsql { + SELECT * FROM v10 ORDER BY 1; + } +} {3 4 4 2 5 1} + +# Tables with columns having peculiar quoted names used in views +# Ticket #756. +# +do_test view-10.1 { + execsql { + CREATE TABLE t3("9" integer, [4] text); + INSERT INTO t3 VALUES(1,2); + CREATE VIEW v_t3_a AS SELECT a.[9] FROM t3 AS a; + CREATE VIEW v_t3_b AS SELECT "4" FROM t3; + SELECT * FROM v_t3_a; + } +} {1} +do_test view-10.2 { + execsql { + SELECT * FROM v_t3_b; + } +} {2} + +do_test view-11.1 { + execsql { + CREATE TABLE t4(a COLLATE NOCASE); + INSERT INTO t4 VALUES('This'); + INSERT INTO t4 VALUES('this'); + INSERT INTO t4 VALUES('THIS'); + SELECT * FROM t4 WHERE a = 'THIS'; + } +} {This this THIS} +ifcapable subquery { + do_test view-11.2 { + execsql { + SELECT * FROM (SELECT * FROM t4) WHERE a = 'THIS'; + } + } {This this THIS} +} +do_test view-11.3 { + execsql { + CREATE VIEW v11 AS SELECT * FROM t4; + SELECT * FROM v11 WHERE a = 'THIS'; + } +} {This this THIS} + +# Ticket #1270: Do not allow parameters in view definitions. +# +do_test view-12.1 { + catchsql { + CREATE VIEW v12 AS SELECT a FROM t1 WHERE b=? + } +} {1 {parameters are not allowed in views}} + +ifcapable attach { + do_test view-13.1 { + forcedelete test2.db + catchsql { + ATTACH 'test2.db' AS two; + CREATE TABLE two.t2(x,y); + CREATE VIEW v13 AS SELECT y FROM two.t2; + } + } {1 {view v13 cannot reference objects in database two}} +} + +# Ticket #1658 +# +do_test view-14.1 { + catchsql { + CREATE TEMP VIEW t1 AS SELECT a,b FROM t1; + SELECT * FROM temp.t1; + } +} {1 {view t1 is circularly defined}} + +# Tickets #1688, #1709 +# +do_test view-15.1 { + execsql2 { + CREATE VIEW v15 AS SELECT a AS x, b AS y FROM t1; + SELECT * FROM v15 LIMIT 1; + } +} {x 2 y 3} +do_test view-15.2 { + execsql2 { + SELECT x, y FROM v15 LIMIT 1 + } +} {x 2 y 3} + +do_test view-16.1 { + catchsql { + CREATE VIEW IF NOT EXISTS v1 AS SELECT * FROM t1; + } +} {0 {}} +do_test view-16.2 { + execsql { + SELECT sql FROM sqlite_master WHERE name='v1' + } +} {{CREATE VIEW v1 AS SELECT a AS 'xyz', b+c AS 'pqr', c-b FROM t1}} +do_test view-16.3 { + catchsql { + DROP VIEW IF EXISTS nosuchview + } +} {0 {}} + +# correct error message when attempting to drop a view that does not +# exist. +# +do_test view-17.1 { + catchsql { + DROP VIEW nosuchview + } +} {1 {no such view: nosuchview}} +do_test view-17.2 { + catchsql { + DROP VIEW main.nosuchview + } +} {1 {no such view: main.nosuchview}} + +do_test view-18.1 { + execsql { + DROP VIEW t1; + DROP TABLE t1; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + + CREATE VIEW vv1 AS SELECT * FROM t1; + CREATE VIEW vv2 AS SELECT * FROM vv1; + CREATE VIEW vv3 AS SELECT * FROM vv2; + CREATE VIEW vv4 AS SELECT * FROM vv3; + CREATE VIEW vv5 AS SELECT * FROM vv4; + + SELECT * FROM vv5; + } +} {1 2 3 4 5 6} + +# Ticket #3308 +# Make sure "rowid" columns in a view are named correctly. +# +do_test view-19.1 { + execsql { + CREATE VIEW v3308a AS SELECT rowid, * FROM t1; + } + execsql2 { + SELECT * FROM v3308a + } +} {rowid 1 a 1 b 2 c 3 rowid 2 a 4 b 5 c 6} +do_test view-19.2 { + execsql { + CREATE VIEW v3308b AS SELECT t1.rowid, t1.a, t1.b+t1.c FROM t1; + } + execsql2 { + SELECT * FROM v3308b + } +} {rowid 1 a 1 t1.b+t1.c 5 rowid 2 a 4 t1.b+t1.c 11} +do_test view-19.3 { + execsql { + CREATE VIEW v3308c AS SELECT t1.oid, A, t1.b+t1.c AS x FROM t1; + } + execsql2 { + SELECT * FROM v3308c + } +} {rowid 1 a 1 x 5 rowid 2 a 4 x 11} + +# Ticket #3539 had this crashing (see commit [5940]). +do_test view-20.1 { + execsql { + DROP TABLE IF EXISTS t1; + DROP VIEW IF EXISTS v1; + CREATE TABLE t1(c1); + CREATE VIEW v1 AS SELECT c1 FROM (SELECT t1.c1 FROM t1); + } +} {} + +# Ticket [d58ccbb3f1b]: Prevent Table.nRef overflow. +db close +sqlite3 db :memory: +do_test view-21.1 { + catchsql { + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(5); + CREATE VIEW v1 AS SELECT x*2 FROM t1; + CREATE VIEW v2 AS SELECT * FROM v1 UNION SELECT * FROM v1; + CREATE VIEW v4 AS SELECT * FROM v2 UNION SELECT * FROM v2; + CREATE VIEW v8 AS SELECT * FROM v4 UNION SELECT * FROM v4; + CREATE VIEW v16 AS SELECT * FROM v8 UNION SELECT * FROM v8; + CREATE VIEW v32 AS SELECT * FROM v16 UNION SELECT * FROM v16; + CREATE VIEW v64 AS SELECT * FROM v32 UNION SELECT * FROM v32; + CREATE VIEW v128 AS SELECT * FROM v64 UNION SELECT * FROM v64; + CREATE VIEW v256 AS SELECT * FROM v128 UNION SELECT * FROM v128; + CREATE VIEW v512 AS SELECT * FROM v256 UNION SELECT * FROM v256; + CREATE VIEW v1024 AS SELECT * FROM v512 UNION SELECT * FROM v512; + CREATE VIEW v2048 AS SELECT * FROM v1024 UNION SELECT * FROM v1024; + CREATE VIEW v4096 AS SELECT * FROM v2048 UNION SELECT * FROM v2048; + CREATE VIEW v8192 AS SELECT * FROM v4096 UNION SELECT * FROM v4096; + CREATE VIEW v16384 AS SELECT * FROM v8192 UNION SELECT * FROM v8192; + CREATE VIEW v32768 AS SELECT * FROM v16384 UNION SELECT * FROM v16384; + CREATE VIEW vx AS SELECT * FROM v32768 UNION SELECT * FROM v32768; + } +} {1 {too many references to "v1": max 65535}} +ifcapable progress { + do_test view-21.2 { + db progress 1000 {expr 1} + catchsql { + SELECT * FROM v32768; + } + } {1 interrupted} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab1.test b/components/external/SQLite-3.8.1/test/vtab1.test new file mode 100644 index 0000000000000000000000000000000000000000..dfcec5ba9023ce9bfba0d0d7e185621f208cf207 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab1.test @@ -0,0 +1,1379 @@ +# 2006 June 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is creating and dropping virtual tables. +# +# $Id: vtab1.test,v 1.57 2008/08/01 17:51:47 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix vtab1 + +ifcapable !vtab||!schema_pragmas { + finish_test + return +} + +#---------------------------------------------------------------------- +# Organization of tests in this file: +# +# vtab1-1.*: Error conditions and other issues surrounding creation/connection +# of a virtual module. +# vtab1-2.*: Test sqlite3_declare_vtab() and the xConnect/xDisconnect methods. +# vtab1-3.*: Table scans and WHERE clauses. +# vtab1-4.*: Table scans and ORDER BY clauses. +# vtab1-5.*: Test queries that include joins. This brings the +# sqlite3_index_info.estimatedCost variable into play. +# vtab1-6.*: Test UPDATE/INSERT/DELETE on vtables. +# vtab1-7.*: Test sqlite3_last_insert_rowid(). +# +# This file uses the "echo" module (see src/test8.c). Refer to comments +# in that file for the special behaviour of the Tcl $echo_module variable. +# +# TODO: +# * How to test the sqlite3_index_constraint_usage.omit field? +# * vtab1-5.* +# +# vtab1-14.*: Test 'IN' constraints - i.e. "SELECT * FROM t1 WHERE id IN(...)" +# +# vtab1-18.*: Check that the LIKE optimization is not applied when the lhs +# is a virtual table column. +# + + +#---------------------------------------------------------------------- +# Test cases vtab1.1.* +# + +# We cannot create a virtual table if the module has not been registered. +# +do_test vtab1-1.1.1 { + explain { + CREATE VIRTUAL TABLE t1 USING echo; + } + catchsql { + CREATE VIRTUAL TABLE t1 USING echo; + } +} {1 {no such module: echo}} +do_test vtab1-1.1.2 { + catchsql { + CREATE VIRTUAL TABLE IF NOT EXISTS t1 USING echo; + } +} {1 {no such module: echo}} +do_test vtab1-1.2 { + execsql { + SELECT name FROM sqlite_master ORDER BY 1 + } +} {} + +# Register the module +register_echo_module [sqlite3_connection_pointer db] + +# Once a module has been registered, virtual tables using that module +# may be created. However if a module xCreate() fails to call +# sqlite3_declare_vtab() an error will be raised and the table not created. +# +# The "echo" module does not invoke sqlite3_declare_vtab() if it is +# passed zero arguments. +# +do_test vtab1-1.3.1 { + catchsql { + CREATE VIRTUAL TABLE t1 USING echo; + } +} {1 {vtable constructor did not declare schema: t1}} +do_test vtab1-1.3.2 { + catchsql { + CREATE VIRTUAL TABLE IF NOT EXISTS t1 USING echo; + } +} {1 {vtable constructor did not declare schema: t1}} +do_test vtab1-1.4 { + execsql { + SELECT name FROM sqlite_master ORDER BY 1 + } +} {} + +# The "echo" module xCreate method returns an error and does not create +# the virtual table if it is passed an argument that does not correspond +# to an existing real table in the same database. +# +do_test vtab1-1.5.1 { + catchsql { + CREATE VIRTUAL TABLE t1 USING echo(no_such_table); + } +} {1 {vtable constructor failed: t1}} +do_test vtab1-1.5.2 { + catchsql { + CREATE VIRTUAL TABLE IF NOT EXISTS t1 USING echo(no_such_table); + } +} {1 {vtable constructor failed: t1}} +do_test vtab1-1.6 { + execsql { + SELECT name FROM sqlite_master ORDER BY 1 + } +} {} + +# Ticket #2156. Using the sqlite3_prepare_v2() API, make sure that +# a CREATE VIRTUAL TABLE statement can be used multiple times. +# +do_test vtab1-1.2152.1 { + set DB [sqlite3_connection_pointer db] + set sql {CREATE VIRTUAL TABLE t2152a USING echo(t2152b)} + set STMT [sqlite3_prepare_v2 $DB $sql -1 TAIL] + sqlite3_step $STMT +} SQLITE_ERROR +do_test vtab-1.2152.2 { + sqlite3_reset $STMT + sqlite3_step $STMT +} SQLITE_ERROR +do_test vtab-1.2152.3 { + sqlite3_reset $STMT + db eval {CREATE TABLE t2152b(x,y)} + sqlite3_step $STMT +} SQLITE_DONE +do_test vtab-1.2152.4 { + sqlite3_finalize $STMT + db eval {DROP TABLE t2152a; DROP TABLE t2152b} +} {} + +# Test to make sure nothing goes wrong and no memory is leaked if we +# select an illegal table-name (i.e a reserved name or the name of a +# table that already exists). +# +do_test vtab1-1.7.1 { + catchsql { + CREATE VIRTUAL TABLE sqlite_master USING echo; + } +} {1 {object name reserved for internal use: sqlite_master}} +do_test vtab1-1.7.2 { + catchsql { + CREATE VIRTUAL TABLE IF NOT EXISTS sqlite_master USING echo; + } +} {1 {object name reserved for internal use: sqlite_master}} +do_test vtab1-1.8.1 { + catchsql { + CREATE TABLE treal(a, b, c); + CREATE VIRTUAL TABLE treal USING echo(treal); + } +} {1 {table treal already exists}} +do_test vtab1-1.8.2 { + catchsql { + CREATE VIRTUAL TABLE IF NOT EXISTS treal USING echo(treal); + } +} {0 {}} +do_test vtab1-1.9 { + execsql { + DROP TABLE treal; + SELECT name FROM sqlite_master ORDER BY 1 + } +} {} + +do_test vtab1-1.10 { + execsql { + CREATE TABLE treal(a, b, c); + CREATE VIRTUAL TABLE techo USING echo(treal); + } + db close + sqlite3 db test.db + catchsql { + SELECT * FROM techo; + } +} {1 {no such module: echo}} +do_test vtab1-1.11 { + catchsql { + INSERT INTO techo VALUES(1, 2, 3); + } +} {1 {no such module: echo}} +do_test vtab1-1.12 { + catchsql { + UPDATE techo SET a = 10; + } +} {1 {no such module: echo}} +do_test vtab1-1.13 { + catchsql { + DELETE FROM techo; + } +} {1 {no such module: echo}} +do_test vtab1-1.14 { + catchsql { + PRAGMA table_info(techo) + } +} {1 {no such module: echo}} +do_test vtab1-1.15 { + catchsql { + DROP TABLE techo; + } +} {1 {no such module: echo}} + +register_echo_module [sqlite3_connection_pointer db] +register_echo_module [sqlite3_connection_pointer db] + +# Test an error message returned from a v-table constructor. +# +do_test vtab1-1.16 { + execsql { + DROP TABLE techo; + CREATE TABLE logmsg(log); + } + catchsql { + CREATE VIRTUAL TABLE techo USING echo(treal, logmsg); + } +} {1 {table 'logmsg' already exists}} + +do_test vtab1-1.17 { + execsql { + DROP TABLE treal; + DROP TABLE logmsg; + SELECT sql FROM sqlite_master; + } +} {} + +#---------------------------------------------------------------------- +# Test cases vtab1.2.* +# +# At this point, the database is completely empty. The echo module +# has already been registered. + +# If a single argument is passed to the echo module during table +# creation, it is assumed to be the name of a table in the same +# database. The echo module attempts to set the schema of the +# new virtual table to be the same as the existing database table. +# +do_test vtab1-2.1 { + execsql { + CREATE TABLE template(a, b, c); + } + execsql { PRAGMA table_info(template); } +} [list \ + 0 a {} 0 {} 0 \ + 1 b {} 0 {} 0 \ + 2 c {} 0 {} 0 \ +] +do_test vtab1-2.2 { + execsql { + CREATE VIRTUAL TABLE t1 USING echo(template); + } + execsql { PRAGMA table_info(t1); } +} [list \ + 0 a {} 0 {} 0 \ + 1 b {} 0 {} 0 \ + 2 c {} 0 {} 0 \ +] + +# Test that the database can be unloaded. This should invoke the xDisconnect() +# callback for the successfully create virtual table (t1). +# +do_test vtab1-2.3 { + set echo_module [list] + db close + set echo_module +} [list xDisconnect] + +# Re-open the database. This should not cause any virtual methods to +# be called. The invocation of xConnect() is delayed until the virtual +# table schema is first required by the compiler. +# +do_test vtab1-2.4 { + set echo_module [list] + sqlite3 db test.db + db cache size 0 + set echo_module +} {} + +# Try to query the virtual table schema. This should fail, as the +# echo module has not been registered with this database connection. +# +do_test vtab1.2.6 { + catchsql { PRAGMA table_info(t1); } +} {1 {no such module: echo}} + +# Register the module +register_echo_module [sqlite3_connection_pointer db] + +# Try to query the virtual table schema again. This time it should +# invoke the xConnect method and succeed. +# +do_test vtab1.2.7 { + execsql { PRAGMA table_info(t1); } +} [list \ + 0 a {} 0 {} 0 \ + 1 b {} 0 {} 0 \ + 2 c {} 0 {} 0 \ +] +do_test vtab1.2.8 { + set echo_module +} {xConnect echo main t1 template} + +# Drop table t1. This should cause the xDestroy (but not xDisconnect) method +# to be invoked. +do_test vtab1-2.5 { + set echo_module "" + execsql { + DROP TABLE t1; + } + set echo_module +} {xDestroy} + +do_test vtab1-2.6 { + execsql { + PRAGMA table_info(t1); + } +} {} +do_test vtab1-2.7 { + execsql { + SELECT sql FROM sqlite_master; + } +} [list {CREATE TABLE template(a, b, c)}] +# Clean up other test artifacts: +do_test vtab1-2.8 { + execsql { + DROP TABLE template; + SELECT sql FROM sqlite_master; + } +} [list] + +#---------------------------------------------------------------------- +# Test case vtab1-3 test table scans and the echo module's +# xBestIndex/xFilter handling of WHERE conditions. + +do_test vtab1-3.1 { + set echo_module "" + execsql { + CREATE TABLE treal(a INTEGER, b INTEGER, c); + CREATE INDEX treal_idx ON treal(b); + CREATE VIRTUAL TABLE t1 USING echo(treal); + } + set echo_module +} [list xCreate echo main t1 treal \ + xSync echo(treal) \ + xCommit echo(treal) \ +] + +# Test that a SELECT on t1 doesn't crash. No rows are returned +# because the underlying real table is currently empty. +# +do_test vtab1-3.2 { + execsql { + SELECT a, b, c FROM t1; + } +} {} + +# Put some data into the table treal. Then try a few simple SELECT +# statements on t1. +# +do_test vtab1-3.3 { + execsql { + INSERT INTO treal VALUES(1, 2, 3); + INSERT INTO treal VALUES(4, 5, 6); + SELECT * FROM t1; + } +} {1 2 3 4 5 6} +do_test vtab1-3.4 { + execsql { + SELECT a FROM t1; + } +} {1 4} +do_test vtab1-3.5 { + execsql { + SELECT rowid FROM t1; + } +} {1 2} +do_test vtab1-3.6 { + set echo_module "" + execsql { + SELECT * FROM t1; + } +} {1 2 3 4 5 6} +do_test vtab1-3.7 { + execsql { + SELECT rowid, * FROM t1; + } +} {1 1 2 3 2 4 5 6} +do_test vtab1-3.8 { + execsql { + SELECT a AS d, b AS e, c AS f FROM t1; + } +} {1 2 3 4 5 6} + +# Execute some SELECT statements with WHERE clauses on the t1 table. +# Then check the echo_module variable (written to by the module methods +# in test8.c) to make sure the xBestIndex() and xFilter() methods were +# called correctly. +# +do_test vtab1-3.8 { + set echo_module "" + execsql { + SELECT * FROM t1; + } + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal'} \ + xFilter {SELECT rowid, * FROM 'treal'} ] +do_test vtab1-3.9 { + set echo_module "" + execsql { + SELECT * FROM t1 WHERE b = 5; + } +} {4 5 6} +do_test vtab1-3.10 { + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal' WHERE b = ?} \ + xFilter {SELECT rowid, * FROM 'treal' WHERE b = ?} 5 ] +do_test vtab1-3.10 { + set echo_module "" + execsql { + SELECT * FROM t1 WHERE b >= 5 AND b <= 10; + } +} {4 5 6} +do_test vtab1-3.11 { + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal' WHERE b >= ? AND b <= ?} \ + xFilter {SELECT rowid, * FROM 'treal' WHERE b >= ? AND b <= ?} 5 10 ] +do_test vtab1-3.12 { + set echo_module "" + execsql { + SELECT * FROM t1 WHERE b BETWEEN 2 AND 10; + } +} {1 2 3 4 5 6} +do_test vtab1-3.13 { + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal' WHERE b >= ? AND b <= ?} \ + xFilter {SELECT rowid, * FROM 'treal' WHERE b >= ? AND b <= ?} 2 10 ] + +# Add a function for the MATCH operator. Everything always matches! +#proc test_match {lhs rhs} { +# lappend ::echo_module MATCH $lhs $rhs +# return 1 +#} +#db function match test_match + +set echo_module "" +do_test vtab1-3.12 { + set echo_module "" + catchsql { + SELECT * FROM t1 WHERE a MATCH 'string'; + } +} {1 {unable to use function MATCH in the requested context}} +do_test vtab1-3.13 { + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal'} \ + xFilter {SELECT rowid, * FROM 'treal'}] +ifcapable subquery { +# The echo module uses a subquery internally to implement the MATCH operator. +do_test vtab1-3.14 { + set echo_module "" + execsql { + SELECT * FROM t1 WHERE b MATCH 'string'; + } +} {} +do_test vtab1-3.15 { + set echo_module +} [list xBestIndex \ + {SELECT rowid, * FROM 'treal' WHERE b LIKE (SELECT '%'||?||'%')} \ + xFilter \ + {SELECT rowid, * FROM 'treal' WHERE b LIKE (SELECT '%'||?||'%')} \ + string ] +}; #ifcapable subquery + +#---------------------------------------------------------------------- +# Test case vtab1-3 test table scans and the echo module's +# xBestIndex/xFilter handling of ORDER BY clauses. + +# This procedure executes the SQL. Then it checks to see if the OP_Sort +# opcode was executed. If an OP_Sort did occur, then "sort" is appended +# to the result. If no OP_Sort happened, then "nosort" is appended. +# +# This procedure is used to check to make sure sorting is or is not +# occurring as expected. +# +proc cksort {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + if {$::sqlite_sort_count} {set x sort} {set x nosort} + lappend data $x + return $data +} + +do_test vtab1-4.1 { + set echo_module "" + cksort { + SELECT b FROM t1 ORDER BY b; + } +} {2 5 nosort} +do_test vtab1-4.2 { + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal' ORDER BY b ASC} \ + xFilter {SELECT rowid, * FROM 'treal' ORDER BY b ASC} ] +do_test vtab1-4.3 { + set echo_module "" + cksort { + SELECT b FROM t1 ORDER BY b DESC; + } +} {5 2 nosort} +do_test vtab1-4.4 { + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal' ORDER BY b DESC} \ + xFilter {SELECT rowid, * FROM 'treal' ORDER BY b DESC} ] +do_test vtab1-4.3 { + set echo_module "" + cksort { + SELECT b FROM t1 ORDER BY b||''; + } +} {2 5 sort} +do_test vtab1-4.4 { + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal'} \ + xFilter {SELECT rowid, * FROM 'treal'} ] + +execsql { + DROP TABLE t1; + DROP TABLE treal; +} + +#---------------------------------------------------------------------- +# Test cases vtab1-5 test SELECT queries that include joins on virtual +# tables. + +proc filter {log} { + set out [list] + for {set ii 0} {$ii < [llength $log]} {incr ii} { + if {[lindex $log $ii] eq "xFilter"} { + lappend out xFilter + lappend out [lindex $log [expr $ii+1]] + } + } + return $out +} + +do_test vtab1-5-1 { + execsql { + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(d, e, f); + INSERT INTO t1 VALUES(1, 'red', 'green'); + INSERT INTO t1 VALUES(2, 'blue', 'black'); + INSERT INTO t2 VALUES(1, 'spades', 'clubs'); + INSERT INTO t2 VALUES(2, 'hearts', 'diamonds'); + CREATE VIRTUAL TABLE et1 USING echo(t1); + CREATE VIRTUAL TABLE et2 USING echo(t2); + } +} {} + +do_test vtab1-5-2 { + set echo_module "" + execsql { + SELECT * FROM et1, et2; + } +} [list \ + 1 red green 1 spades clubs \ + 1 red green 2 hearts diamonds \ + 2 blue black 1 spades clubs \ + 2 blue black 2 hearts diamonds \ +] +do_test vtab1-5-3 { + filter $echo_module +} [list \ + xFilter {SELECT rowid, * FROM 't1'} \ + xFilter {SELECT rowid, * FROM 't2'} \ + xFilter {SELECT rowid, * FROM 't2'} \ +] +do_test vtab1-5-4 { + set echo_module "" + execsql { + SELECT * FROM et1, et2 WHERE et2.d = 2; + } +} [list \ + 1 red green 2 hearts diamonds \ + 2 blue black 2 hearts diamonds \ +] +do_test vtab1-5-5 { + filter $echo_module +} [list \ + xFilter {SELECT rowid, * FROM 't1'} \ + xFilter {SELECT rowid, * FROM 't2'} \ + xFilter {SELECT rowid, * FROM 't2'} \ +] +do_test vtab1-5-6 { + execsql { + CREATE INDEX i1 ON t2(d); + } + + db close + sqlite3 db test.db + register_echo_module [sqlite3_connection_pointer db] + + set ::echo_module "" + execsql { + SELECT * FROM et1, et2 WHERE et2.d = 2; + } +} [list \ + 1 red green 2 hearts diamonds \ + 2 blue black 2 hearts diamonds \ +] +do_test vtab1-5-7 { + filter $::echo_module +} [list \ + xFilter {SELECT rowid, * FROM 't1'} \ + xFilter {SELECT rowid, * FROM 't2' WHERE d = ?} \ + xFilter {SELECT rowid, * FROM 't2' WHERE d = ?} \ +] + +execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE et1; + DROP TABLE et2; +} + +#---------------------------------------------------------------------- +# Test cases vtab1-6 test INSERT, UPDATE and DELETE operations +# on virtual tables. +do_test vtab1-6-1 { + execsql { SELECT sql FROM sqlite_master } +} {} +do_test vtab1-6-2 { + execsql { + CREATE TABLE treal(a PRIMARY KEY, b, c); + CREATE VIRTUAL TABLE techo USING echo(treal); + SELECT name FROM sqlite_master WHERE type = 'table'; + } +} {treal techo} +do_test vtab1-6-3.1.1 { + execsql { + PRAGMA count_changes=ON; + INSERT INTO techo VALUES(1, 2, 3); + } +} {1} +do_test vtab1-6-3.1.2 { + db changes +} {1} +do_test vtab1-6-3.2 { + execsql { + SELECT * FROM techo; + } +} {1 2 3} +do_test vtab1-6-4.1 { + execsql { + UPDATE techo SET a = 5; + } + db changes +} {1} +do_test vtab1-6-4.2 { + execsql { + SELECT * FROM techo; + } +} {5 2 3} +do_test vtab1-6-4.3 { + execsql { + UPDATE techo SET a=6 WHERE a<0; + } + db changes +} {0} +do_test vtab1-6-4.4 { + execsql { + SELECT * FROM techo; + } +} {5 2 3} + +do_test vtab1-6-5.1 { + execsql { + UPDATE techo set a = a||b||c; + } + db changes +} {1} +do_test vtab1-6-5.2 { + execsql { + SELECT * FROM techo; + } +} {523 2 3} + +do_test vtab1-6-6.1 { + execsql { + UPDATE techo set rowid = 10; + } + db changes +} {1} +do_test vtab1-6-6.2 { + execsql { + SELECT rowid FROM techo; + } +} {10} + +do_test vtab1-6-7.1.1 { + execsql { + INSERT INTO techo VALUES(11,12,13); + } +} {1} +do_test vtab1-6-7.1.2 { + db changes +} {1} +do_test vtab1-6-7.2 { + execsql { + SELECT * FROM techo ORDER BY a; + } +} {11 12 13 523 2 3} +do_test vtab1-6-7.3 { + execsql { + UPDATE techo SET b=b+1000 + } + db changes +} {2} +do_test vtab1-6-7.4 { + execsql { + SELECT * FROM techo ORDER BY a; + } +} {11 1012 13 523 1002 3} + + +do_test vtab1-6-8.1 { + execsql { + DELETE FROM techo WHERE a=5; + } + db changes +} {0} +do_test vtab1-6-8.2 { + execsql { + SELECT * FROM techo ORDER BY a; + } +} {11 1012 13 523 1002 3} +do_test vtab1-6-8.3 { + execsql { + DELETE FROM techo; + } + db changes +} {2} +do_test vtab1-6-8.4 { + execsql { + SELECT * FROM techo ORDER BY a; + } +} {} +execsql {PRAGMA count_changes=OFF} + +forcedelete test2.db +forcedelete test2.db-journal +sqlite3 db2 test2.db +execsql { + CREATE TABLE techo(a PRIMARY KEY, b, c); +} db2 +proc check_echo_table {tn} { + set ::data1 [execsql {SELECT rowid, * FROM techo}] + set ::data2 [execsql {SELECT rowid, * FROM techo} db2] + do_test $tn { + string equal $::data1 $::data2 + } 1 +} +set tn 0 +foreach stmt [list \ + {INSERT INTO techo VALUES('abc', 'def', 'ghi')} \ + {INSERT INTO techo SELECT a||'.'||rowid, b, c FROM techo} \ + {INSERT INTO techo SELECT a||'x'||rowid, b, c FROM techo} \ + {INSERT INTO techo SELECT a||'y'||rowid, b, c FROM techo} \ + {DELETE FROM techo WHERE (oid % 3) = 0} \ + {UPDATE techo set rowid = 100 WHERE rowid = 1} \ + {INSERT INTO techo(a, b) VALUES('hello', 'world')} \ + {DELETE FROM techo} \ +] { + execsql $stmt + execsql $stmt db2 + check_echo_table vtab1-6.8.[incr tn] +} + +db2 close + + + +#---------------------------------------------------------------------- +# Test cases vtab1-7 tests that the value returned by +# sqlite3_last_insert_rowid() is set correctly when rows are inserted +# into virtual tables. +do_test vtab1.7-1 { + execsql { + CREATE TABLE real_abc(a PRIMARY KEY, b, c); + CREATE VIRTUAL TABLE echo_abc USING echo(real_abc); + } +} {} +do_test vtab1.7-2 { + execsql { + INSERT INTO echo_abc VALUES(1, 2, 3); + SELECT last_insert_rowid(); + } +} {1} +do_test vtab1.7-3 { + execsql { + INSERT INTO echo_abc(rowid) VALUES(31427); + SELECT last_insert_rowid(); + } +} {31427} +do_test vtab1.7-4 { + execsql { + INSERT INTO echo_abc SELECT a||'.v2', b, c FROM echo_abc; + SELECT last_insert_rowid(); + } +} {31429} +do_test vtab1.7-5 { + execsql { + SELECT rowid, a, b, c FROM echo_abc + } +} [list 1 1 2 3 \ + 31427 {} {} {} \ + 31428 1.v2 2 3 \ + 31429 {} {} {} \ +] + +# Now test that DELETE and UPDATE operations do not modify the value. +do_test vtab1.7-6 { + execsql { + UPDATE echo_abc SET c = 5 WHERE b = 2; + SELECT last_insert_rowid(); + } +} {31429} +do_test vtab1.7-7 { + execsql { + UPDATE echo_abc SET rowid = 5 WHERE rowid = 1; + SELECT last_insert_rowid(); + } +} {31429} +do_test vtab1.7-8 { + execsql { + DELETE FROM echo_abc WHERE b = 2; + SELECT last_insert_rowid(); + } +} {31429} +do_test vtab1.7-9 { + execsql { + SELECT rowid, a, b, c FROM echo_abc + } +} [list 31427 {} {} {} \ + 31429 {} {} {} \ +] +do_test vtab1.7-10 { + execsql { + DELETE FROM echo_abc WHERE b = 2; + SELECT last_insert_rowid(); + } +} {31429} +do_test vtab1.7-11 { + execsql { + SELECT rowid, a, b, c FROM real_abc + } +} [list 31427 {} {} {} \ + 31429 {} {} {} \ +] +do_test vtab1.7-12 { + execsql { + DELETE FROM echo_abc; + SELECT last_insert_rowid(); + } +} {31429} +do_test vtab1.7-13 { + execsql { + SELECT rowid, a, b, c FROM real_abc + } +} {} + +ifcapable attach { + do_test vtab1.8-1 { + set echo_module "" + execsql { + ATTACH 'test2.db' AS aux; + CREATE VIRTUAL TABLE aux.e2 USING echo(real_abc); + } + set echo_module + } [list xCreate echo aux e2 real_abc \ + xSync echo(real_abc) \ + xCommit echo(real_abc) \ + ] +} +do_test vtab1.8-2 { + catchsql { + DROP TABLE aux.e2; + } + execsql { + DROP TABLE treal; + DROP TABLE techo; + DROP TABLE echo_abc; + DROP TABLE real_abc; + } +} {} + +do_test vtab1.9-1 { + set echo_module "" + execsql { + CREATE TABLE r(a, b, c); + CREATE VIRTUAL TABLE e USING echo(r, e_log); + SELECT name FROM sqlite_master; + } +} {r e e_log} +do_test vtab1.9-2 { + execsql { + DROP TABLE e; + SELECT name FROM sqlite_master; + } +} {r} + +do_test vtab1.9-3 { + set echo_module "" + execsql { + CREATE VIRTUAL TABLE e USING echo(r, e_log, virtual 1 2 3 varchar(32)); + } + set echo_module +} [list \ + xCreate echo main e r e_log {virtual 1 2 3 varchar(32)} \ + xSync echo(r) \ + xCommit echo(r) \ +] + +do_test vtab1.10-1 { + execsql { + CREATE TABLE del(d); + CREATE VIRTUAL TABLE e2 USING echo(del); + } + db close + sqlite3 db test.db + register_echo_module [sqlite3_connection_pointer db] + execsql { + DROP TABLE del; + } + catchsql { + SELECT * FROM e2; + } +} {1 {vtable constructor failed: e2}} +do_test vtab1.10-2 { + set rc [catch { + set ptr [sqlite3_connection_pointer db] + sqlite3_declare_vtab $ptr {CREATE TABLE abc(a, b, c)} + } msg] + list $rc $msg +} {1 {library routine called out of sequence}} +do_test vtab1.10-3 { + set ::echo_module_begin_fail r + catchsql { + INSERT INTO e VALUES(1, 2, 3); + } +} {1 {SQL logic error or missing database}} +do_test vtab1.10-4 { + catch {execsql { + EXPLAIN SELECT * FROM e WHERE rowid = 2; + EXPLAIN QUERY PLAN SELECT * FROM e WHERE rowid = 2 ORDER BY rowid; + }} +} {0} + +do_test vtab1.10-5 { + set echo_module "" + execsql { + SELECT * FROM e WHERE rowid||'' MATCH 'pattern'; + } + set echo_module +} [list \ + xBestIndex {SELECT rowid, * FROM 'r'} \ + xFilter {SELECT rowid, * FROM 'r'} \ +] +proc match_func {args} {return ""} +do_test vtab1.10-6 { + set echo_module "" + db function match match_func + execsql { + SELECT * FROM e WHERE match('pattern', rowid, 'pattern2'); + } + set echo_module +} [list \ + xBestIndex {SELECT rowid, * FROM 'r'} \ + xFilter {SELECT rowid, * FROM 'r'} \ +] + + +# Testing the xFindFunction interface +# +catch {rename ::echo_glob_overload {}} +do_test vtab1.11-1 { + execsql { + INSERT INTO r(a,b,c) VALUES(1,'?',99); + INSERT INTO r(a,b,c) VALUES(2,3,99); + SELECT a GLOB b FROM e + } +} {1 0} +proc ::echo_glob_overload {a b} { + return [list $b $a] +} +do_test vtab1.11-2 { + execsql { + SELECT a like 'b' FROM e + } +} {0 0} +do_test vtab1.11-3 { + execsql { + SELECT a glob '2' FROM e + } +} {{1 2} {2 2}} +do_test vtab1.11-4 { + execsql { + SELECT glob('2',a) FROM e + } +} {0 1} +do_test vtab1.11-5 { + execsql { + SELECT glob(a,'2') FROM e + } +} {{2 1} {2 2}} + +#---------------------------------------------------------------------- +# Test the outcome if a constraint is encountered half-way through +# a multi-row INSERT that is inside a transaction +# +do_test vtab1.12-1 { + execsql { + CREATE TABLE b(a, b, c); + CREATE TABLE c(a UNIQUE, b, c); + INSERT INTO b VALUES(1, 'A', 'B'); + INSERT INTO b VALUES(2, 'C', 'D'); + INSERT INTO b VALUES(3, 'E', 'F'); + INSERT INTO c VALUES(3, 'G', 'H'); + CREATE VIRTUAL TABLE echo_c USING echo(c); + } +} {} + +# First test outside of a transaction. +do_test vtab1.12-2 { + catchsql { INSERT INTO echo_c SELECT * FROM b; } +} {1 {echo-vtab-error: column a is not unique}} +do_test vtab1.12-2.1 { + sqlite3_errmsg db +} {echo-vtab-error: column a is not unique} +do_test vtab1.12-3 { + execsql { SELECT * FROM c } +} {3 G H} + +# Now the real test - wrapped in a transaction. +do_test vtab1.12-4 { + execsql {BEGIN} + catchsql { INSERT INTO echo_c SELECT * FROM b; } +} {1 {echo-vtab-error: column a is not unique}} +do_test vtab1.12-5 { + execsql { SELECT * FROM c } +} {3 G H} +do_test vtab1.12-6 { + execsql { COMMIT } + execsql { SELECT * FROM c } +} {3 G H} + +# At one point (ticket #2759), a WHERE clause of the form " IS NULL" +# on a virtual table was causing an assert() to fail in the compiler. +# +# "IS NULL" clauses should not be passed through to the virtual table +# implementation. They are handled by SQLite after the vtab returns its +# data. +# +do_test vtab1.13-1 { + execsql { + SELECT * FROM echo_c WHERE a IS NULL + } +} {} +do_test vtab1.13-2 { + execsql { + INSERT INTO c VALUES(NULL, 15, 16); + SELECT * FROM echo_c WHERE a IS NULL + } +} {{} 15 16} +do_test vtab1.13-3 { + execsql { + INSERT INTO c VALUES(15, NULL, 16); + SELECT * FROM echo_c WHERE b IS NULL + } +} {15 {} 16} +do_test vtab1.13-3 { + execsql { + SELECT * FROM echo_c WHERE b IS NULL AND a = 15; + } +} {15 {} 16} + + +do_test vtab1-14.001 { + execsql {SELECT rowid, * FROM echo_c WHERE +rowid IN (1,2,3)} +} {1 3 G H 2 {} 15 16 3 15 {} 16} +do_test vtab1-14.002 { + execsql {SELECT rowid, * FROM echo_c WHERE rowid IN (1,2,3)} +} {1 3 G H 2 {} 15 16 3 15 {} 16} +do_test vtab1-14.003 { + execsql {SELECT rowid, * FROM echo_c WHERE +rowid IN (0,1,5,2,'a',3,NULL)} +} {1 3 G H 2 {} 15 16 3 15 {} 16} +do_test vtab1-14.004 { + execsql {SELECT rowid, * FROM echo_c WHERE rowid IN (0,1,5,'a',2,3,NULL)} +} {1 3 G H 2 {} 15 16 3 15 {} 16} +do_test vtab1-14.005 { + execsql {SELECT rowid, * FROM echo_c WHERE rowid NOT IN (0,1,5,'a',2,3)} +} {} +do_test vtab1-14.006 { + execsql {SELECT rowid, * FROM echo_c WHERE rowid NOT IN (0,5,'a',2,3)} +} {1 3 G H} +do_test vtab1-14.007 { + execsql {SELECT rowid, * FROM echo_c WHERE +rowid NOT IN (0,5,'a',2,3,NULL)} +} {} +do_test vtab1-14.008 { + execsql {SELECT rowid, * FROM echo_c WHERE rowid NOT IN (0,5,'a',2,3,NULL)} +} {} +do_test vtab1-14.011 { + execsql {SELECT * FROM echo_c WHERE +a IN (1,3,8,'x',NULL,15,24)} +} {3 G H 15 {} 16} +do_test vtab1-14.012 { + execsql {SELECT * FROM echo_c WHERE a IN (1,3,8,'x',NULL,15,24)} +} {3 G H 15 {} 16} +do_test vtab1-14.013 { + execsql {SELECT * FROM echo_c WHERE a NOT IN (1,8,'x',15,24)} +} {3 G H} +do_test vtab1-14.014 { + execsql {SELECT * FROM echo_c WHERE a NOT IN (1,8,'x',NULL,15,24)} +} {} +do_test vtab1-14.015 { + execsql {SELECT * FROM echo_c WHERE +a NOT IN (1,8,'x',NULL,15,24)} +} {} + + + +#do_test vtab1-14.1 { +# execsql { DELETE FROM c } +# set echo_module "" +# execsql { SELECT * FROM echo_c WHERE rowid IN (1, 2, 3) } +# set echo_module +#} {/.*xBestIndex {SELECT rowid, . FROM 'c' WHERE rowid = .} xFilter {SELECT rowid, . FROM 'c'} 1/} + +do_test vtab1-14.2 { + set echo_module "" + execsql { SELECT * FROM echo_c WHERE rowid = 1 } + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'c' WHERE rowid = ?} xFilter {SELECT rowid, * FROM 'c' WHERE rowid = ?} 1] + +do_test vtab1-14.3 { + set echo_module "" + execsql { SELECT * FROM echo_c WHERE a = 1 } + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'c' WHERE a = ?} xFilter {SELECT rowid, * FROM 'c' WHERE a = ?} 1] + +#do_test vtab1-14.4 { +# set echo_module "" +# execsql { SELECT * FROM echo_c WHERE a IN (1, 2) } +# set echo_module +#} {/xBestIndex {SELECT rowid, . FROM 'c' WHERE a = .} xFilter {SELECT rowid, . FROM 'c' WHERE a = .} 1/} + +do_test vtab1-15.1 { + execsql { + CREATE TABLE t1(a, b, c); + CREATE VIRTUAL TABLE echo_t1 USING echo(t1); + } +} {} +do_test vtab1-15.2 { + execsql { + INSERT INTO echo_t1(rowid) VALUES(45); + SELECT rowid, * FROM echo_t1; + } +} {45 {} {} {}} +do_test vtab1-15.3 { + execsql { + INSERT INTO echo_t1(rowid) VALUES(NULL); + SELECT rowid, * FROM echo_t1; + } +} {45 {} {} {} 46 {} {} {}} +do_test vtab1-15.4 { + catchsql { + INSERT INTO echo_t1(rowid) VALUES('new rowid'); + } +} {1 {datatype mismatch}} + +# The following tests - vtab1-16.* - are designed to test that setting +# sqlite3_vtab.zErrMsg variable can be used by the vtab interface to +# return an error message to the user. +# +do_test vtab1-16.1 { + execsql { + CREATE TABLE t2(a PRIMARY KEY, b, c); + INSERT INTO t2 VALUES(1, 2, 3); + INSERT INTO t2 VALUES(4, 5, 6); + CREATE VIRTUAL TABLE echo_t2 USING echo(t2); + } +} {} + +set tn 2 +foreach method [list \ + xBestIndex \ + xOpen \ + xFilter \ + xNext \ + xColumn \ + xRowid \ +] { + do_test vtab1-16.$tn { + set echo_module_fail($method,t2) "the $method method has failed" + catchsql { SELECT rowid, * FROM echo_t2 WHERE a >= 1 } + } "1 {echo-vtab-error: the $method method has failed}" + unset echo_module_fail($method,t2) + incr tn +} + +foreach method [list \ + xUpdate \ + xBegin \ + xSync \ +] { + do_test vtab1-16.$tn { + set echo_module_fail($method,t2) "the $method method has failed" + catchsql { INSERT INTO echo_t2 VALUES(7, 8, 9) } + } "1 {echo-vtab-error: the $method method has failed}" + unset echo_module_fail($method,t2) + incr tn +} + +ifcapable altertable { + do_test vtab1-16.$tn { + set echo_module_fail(xRename,t2) "the xRename method has failed" + catchsql { ALTER TABLE echo_t2 RENAME TO another_name } + } "1 {echo-vtab-error: the xRename method has failed}" + unset echo_module_fail(xRename,t2) + incr tn +} + +# The following test case exposes an instance in sqlite3_declare_vtab() +# an error message was set using a call similar to sqlite3_mprintf(zErr), +# where zErr is an arbitrary string. This is no good if the string contains +# characters that can be mistaken for printf() formatting directives. +# +do_test vtab1-17.1 { + execsql { + PRAGMA writable_schema = 1; + INSERT INTO sqlite_master VALUES( + 'table', 't3', 't3', 0, 'INSERT INTO "%s%s" VALUES(1)' + ); + } + catchsql { CREATE VIRTUAL TABLE t4 USING echo(t3); } +} {1 {vtable constructor failed: t4}} + +# This test verifies that ticket 48f29963 is fixed. +# +do_test vtab1-17.1 { + execsql { + CREATE TABLE t5(a, b); + CREATE VIRTUAL TABLE e5 USING echo_v2(t5); + BEGIN; + INSERT INTO e5 VALUES(1, 2); + DROP TABLE e5; + SAVEPOINT one; + ROLLBACK TO one; + COMMIT; + } +} {} + +do_test vtab1-17.2 { + execsql { DELETE FROM sqlite_master WHERE sql LIKE 'insert%' } +} {} + +#------------------------------------------------------------------------- +# The following tests - vtab1-18.* - test that the optimization of LIKE +# constraints in where.c plays well with virtual tables. +# +# 18.1.*: Case-insensitive LIKE. +# 18.2.*: Case-sensitive LIKE. +# +unset -nocomplain echo_module_begin_fail + +do_execsql_test 18.1.0 { + CREATE TABLE t6(a, b TEXT); + CREATE INDEX i6 ON t6(b, a); + INSERT INTO t6 VALUES(1, 'Peter'); + INSERT INTO t6 VALUES(2, 'Andrew'); + INSERT INTO t6 VALUES(3, 'James'); + INSERT INTO t6 VALUES(4, 'John'); + INSERT INTO t6 VALUES(5, 'Phillip'); + INSERT INTO t6 VALUES(6, 'Bartholomew'); + CREATE VIRTUAL TABLE e6 USING echo(t6); +} + +foreach {tn sql res filter} { + 1.1 "SELECT a FROM e6 WHERE b>'James'" {4 1 5} + {xFilter {SELECT rowid, * FROM 't6' WHERE b > ?} James} + + 1.2 "SELECT a FROM e6 WHERE b>='J' AND b<'K'" {3 4} + {xFilter {SELECT rowid, * FROM 't6' WHERE b >= ? AND b < ?} J K} + + 1.3 "SELECT a FROM e6 WHERE b LIKE 'J%'" {3 4} + {xFilter {SELECT rowid, * FROM 't6'}} + + 1.4 "SELECT a FROM e6 WHERE b LIKE 'j%'" {3 4} + {xFilter {SELECT rowid, * FROM 't6'}} +} { + set echo_module {} + do_execsql_test 18.$tn.1 $sql $res + do_test 18.$tn.2 { lrange $::echo_module 2 end } $filter +} + +do_execsql_test 18.2.0 { PRAGMA case_sensitive_like = ON } +foreach {tn sql res filter} { + 2.1 "SELECT a FROM e6 WHERE b LIKE 'J%'" {3 4} + {xFilter {SELECT rowid, * FROM 't6'}} + + 2.2 "SELECT a FROM e6 WHERE b LIKE 'j%'" {} + {xFilter {SELECT rowid, * FROM 't6'}} +} { + set echo_module {} + do_execsql_test 18.$tn.1 $sql $res + do_test 18.$tn.2 { lrange $::echo_module 2 end } $filter +} +do_execsql_test 18.2.x { PRAGMA case_sensitive_like = OFF } + +#------------------------------------------------------------------------- +# Test that an existing module may not be overridden. +# +do_test 19.1 { + sqlite3 db2 test.db + register_echo_module [sqlite3_connection_pointer db2] +} SQLITE_OK +do_test 19.2 { + register_echo_module [sqlite3_connection_pointer db2] +} SQLITE_MISUSE +do_test 19.3 { + db2 close +} {} + +#------------------------------------------------------------------------- +# Test that the bug fixed by [b0c1ba655d69] really is fixed. +# +do_execsql_test 20.1 { + CREATE TABLE t7 (a, b); + CREATE TABLE t8 (c, d); + CREATE INDEX i2 ON t7(a); + CREATE INDEX i3 ON t7(b); + CREATE INDEX i4 ON t8(c); + CREATE INDEX i5 ON t8(d); + + CREATE VIRTUAL TABLE t7v USING echo(t7); + CREATE VIRTUAL TABLE t8v USING echo(t8); +} + +do_test 20.2 { + for {set i 0} {$i < 1000} {incr i} { + db eval {INSERT INTO t7 VALUES($i, $i)} + db eval {INSERT INTO t8 VALUES($i, $i)} + } +} {} + +do_execsql_test 20.3 { + SELECT a, b FROM ( + SELECT a, b FROM t7 WHERE a=11 OR b=12 + UNION ALL + SELECT c, d FROM t8 WHERE c=5 OR d=6 + ) + ORDER BY 1, 2; +} {5 5 6 6 11 11 12 12} + +do_execsql_test 20.4 { + SELECT a, b FROM ( + SELECT a, b FROM t7v WHERE a=11 OR b=12 + UNION ALL + SELECT c, d FROM t8v WHERE c=5 OR d=6 + ) + ORDER BY 1, 2; +} {5 5 6 6 11 11 12 12} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab2.test b/components/external/SQLite-3.8.1/test/vtab2.test new file mode 100644 index 0000000000000000000000000000000000000000..05a4834a1bc9db3e4983f3b19962f796d14074ba --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab2.test @@ -0,0 +1,136 @@ +# 2006 June 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# $Id: vtab2.test,v 1.9 2008/10/13 10:37:50 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab||!schema_pragmas { + finish_test + return +} + +register_schema_module [sqlite3_connection_pointer db] +do_test vtab2-1.1 { + execsql { + CREATE VIRTUAL TABLE schema USING schema; + SELECT * FROM schema; + } +} [list \ + main schema 0 database {} 0 {} 0 \ + main schema 1 tablename {} 0 {} 0 \ + main schema 2 cid {} 0 {} 0 \ + main schema 3 name {} 0 {} 0 \ + main schema 4 type {} 0 {} 0 \ + main schema 5 not_null {} 0 {} 0 \ + main schema 6 dflt_value {} 0 {} 0 \ + main schema 7 pk {} 0 {} 0 \ +] + +# See ticket #2230. +# +do_test vtab2-1.2 { + execsql { + SELECT length(tablename) FROM schema GROUP by tablename; + } +} {6} +do_test vtab2-1.3 { + execsql { + SELECT tablename FROM schema GROUP by length(tablename); + } +} {schema} +do_test vtab2-1.4 { + execsql { + SELECT length(tablename) FROM schema GROUP by length(tablename); + } +} {6} + +register_tclvar_module [sqlite3_connection_pointer db] +do_test vtab2-2.1 { + set ::abc 123 + execsql { + CREATE VIRTUAL TABLE vars USING tclvar; + SELECT * FROM vars WHERE name='abc'; + } +} [list abc "" 123] +do_test vtab2-2.2 { + set A(1) 1 + set A(2) 4 + set A(3) 9 + execsql { + SELECT * FROM vars WHERE name='A'; + } +} [list A 1 1 A 2 4 A 3 9] +unset -nocomplain result +unset -nocomplain var +set result {} +foreach var [lsort [info vars tcl_*]] { + catch {lappend result $var [set $var]} +} +do_test vtab2-2.3 { + execsql { + SELECT name, value FROM vars + WHERE name MATCH 'tcl_*' AND arrayname = '' + ORDER BY name; + } +} $result +unset result +unset var + +# Ticket #2894. +# +# Make sure we do call Column(), and Rowid() methods of +# a virtual table when that table is in a LEFT JOIN. +# +do_test vtab2-3.1 { + execsql { + SELECT * FROM schema WHERE dflt_value IS NULL LIMIT 1 + } +} {main schema 0 database {} 0 {} 0} +do_test vtab2-3.2 { + execsql { + SELECT *, b.rowid + FROM schema a LEFT JOIN schema b ON a.dflt_value=b.dflt_value + WHERE a.rowid=1 + } +} {main schema 0 database {} 0 {} 0 {} {} {} {} {} {} {} {} {}} + +do_test vtab2-4.1 { + execsql { + BEGIN TRANSACTION; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c)); + CREATE TABLE fkey( + to_tbl, + to_col + ); + INSERT INTO "fkey" VALUES('t1',NULL); + COMMIT; + } +} {} +do_test vtab2-4.2 { + execsql { CREATE VIRTUAL TABLE v_col USING schema } +} {} +do_test vtab2-4.3 { + execsql { SELECT name FROM v_col WHERE tablename = 't1' AND pk } +} {a} +do_test vtab2-4.4 { + execsql { + UPDATE fkey + SET to_col = (SELECT name FROM v_col WHERE tablename = 't1' AND pk); + } +} {} +do_test vtab2-4.5 { + execsql { SELECT * FROM fkey } +} {t1 a} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab3.test b/components/external/SQLite-3.8.1/test/vtab3.test new file mode 100644 index 0000000000000000000000000000000000000000..ebf8369d5df2a76db0777fbb925791f6302f2514 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab3.test @@ -0,0 +1,140 @@ +# 2006 June 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is the authorisation callback and virtual tables. +# +# $Id: vtab3.test,v 1.3 2008/07/12 14:52:21 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab||!auth { + finish_test + return +} + +set ::auth_fail 0 +set ::auth_log [list] +set ::auth_filter [list SQLITE_READ SQLITE_UPDATE SQLITE_SELECT SQLITE_PRAGMA] + +proc auth {code arg1 arg2 arg3 arg4} { + if {[lsearch $::auth_filter $code]>-1} { + return SQLITE_OK + } + lappend ::auth_log $code $arg1 $arg2 $arg3 $arg4 + incr ::auth_fail -1 + if {$::auth_fail == 0} { + return SQLITE_DENY + } + return SQLITE_OK +} + +do_test vtab3-1.1 { + execsql { + CREATE TABLE elephant( + name VARCHAR(32), + color VARCHAR(16), + age INTEGER, + UNIQUE(name, color) + ); + } +} {} + + +do_test vtab3-1.2 { + register_echo_module [sqlite3_connection_pointer db] + db authorizer ::auth + execsql { + CREATE VIRTUAL TABLE pachyderm USING echo(elephant); + } + set ::auth_log +} [list \ + SQLITE_INSERT sqlite_master {} main {} \ + SQLITE_CREATE_VTABLE pachyderm echo main {} \ +] + +do_test vtab3-1.3 { + set ::auth_log [list] + execsql { + DROP TABLE pachyderm; + } + set ::auth_log +} [list \ + SQLITE_DELETE sqlite_master {} main {} \ + SQLITE_DROP_VTABLE pachyderm echo main {} \ + SQLITE_DELETE pachyderm {} main {} \ + SQLITE_DELETE sqlite_master {} main {} \ +] + +do_test vtab3-1.4 { + set ::auth_fail 1 + catchsql { + CREATE VIRTUAL TABLE pachyderm USING echo(elephant); + } +} {1 {not authorized}} +do_test vtab3-1.5 { + execsql { + SELECT name FROM sqlite_master WHERE type = 'table'; + } +} {elephant} + +do_test vtab3-1.5 { + set ::auth_fail 2 + catchsql { + CREATE VIRTUAL TABLE pachyderm USING echo(elephant); + } +} {1 {not authorized}} +do_test vtab3-1.6 { + execsql { + SELECT name FROM sqlite_master WHERE type = 'table'; + } +} {elephant} + +do_test vtab3-1.5 { + set ::auth_fail 3 + catchsql { + CREATE VIRTUAL TABLE pachyderm USING echo(elephant); + } +} {0 {}} +do_test vtab3-1.6 { + execsql { + SELECT name FROM sqlite_master WHERE type = 'table'; + } +} {elephant pachyderm} + +foreach i [list 1 2 3 4] { + set ::auth_fail $i + do_test vtab3-1.7.$i.1 { + set rc [catch { + execsql {DROP TABLE pachyderm;} + } msg] + if {$msg eq "authorization denied"} {set msg "not authorized"} + list $rc $msg + } {1 {not authorized}} + do_test vtab3-1.7.$i.2 { + execsql { + SELECT name FROM sqlite_master WHERE type = 'table'; + } + } {elephant pachyderm} +} +do_test vtab3-1.8.1 { + set ::auth_fail 0 + catchsql { + DROP TABLE pachyderm; + } +} {0 {}} +do_test vtab3-1.8.2 { + execsql { + SELECT name FROM sqlite_master WHERE type = 'table'; + } +} {elephant} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab4.test b/components/external/SQLite-3.8.1/test/vtab4.test new file mode 100644 index 0000000000000000000000000000000000000000..07b6e839d7d4abd2de5286ff886921fc288b0cad --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab4.test @@ -0,0 +1,193 @@ +# 2006 June 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus is on testing the following virtual table methods: +# +# xBegin +# xSync +# xCommit +# xRollback +# +# $Id: vtab4.test,v 1.3 2008/07/12 14:52:21 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +unset -nocomplain echo_module +unset -nocomplain echo_module_sync_fail + +ifcapable !vtab { + finish_test + return +} + +# Register the echo module +db cache size 0 +register_echo_module [sqlite3_connection_pointer db] + +do_test vtab4-1.1 { + execsql { + CREATE TABLE treal(a PRIMARY KEY, b, c); + CREATE VIRTUAL TABLE techo USING echo(treal); + } +} {} + +# Test an INSERT, UPDATE and DELETE statement on the virtual table +# in an implicit transaction. Each should result in a single call +# to xBegin, xSync and xCommit. +# +do_test vtab4-1.2 { + set echo_module [list] + execsql { + INSERT INTO techo VALUES(1, 2, 3); + } + set echo_module +} {xBegin echo(treal) xSync echo(treal) xCommit echo(treal)} +do_test vtab4-1.3 { + set echo_module [list] + execsql { + UPDATE techo SET a = 2; + } + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal'} \ + xBegin echo(treal) \ + xFilter {SELECT rowid, * FROM 'treal'} \ + xSync echo(treal) \ + xCommit echo(treal) \ +] +do_test vtab4-1.4 { + set echo_module [list] + execsql { + DELETE FROM techo; + } + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal'} \ + xBegin echo(treal) \ + xFilter {SELECT rowid, * FROM 'treal'} \ + xSync echo(treal) \ + xCommit echo(treal) \ +] + +# Ensure xBegin is not called more than once in a single transaction. +# +do_test vtab4-2.1 { + set echo_module [list] + execsql { + BEGIN; + INSERT INTO techo VALUES(1, 2, 3); + INSERT INTO techo VALUES(4, 5, 6); + INSERT INTO techo VALUES(7, 8, 9); + COMMIT; + } + set echo_module +} {xBegin echo(treal) xSync echo(treal) xCommit echo(treal)} + +# Try a transaction with two virtual tables. +# +do_test vtab4-2.2 { + execsql { + CREATE TABLE sreal(a, b, c UNIQUE); + CREATE VIRTUAL TABLE secho USING echo(sreal); + } + set echo_module [list] + execsql { + BEGIN; + INSERT INTO secho SELECT * FROM techo; + DELETE FROM techo; + COMMIT; + } + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'treal'} \ + xBegin echo(sreal) \ + xFilter {SELECT rowid, * FROM 'treal'} \ + xBestIndex {SELECT rowid, * FROM 'treal'} \ + xBegin echo(treal) \ + xFilter {SELECT rowid, * FROM 'treal'} \ + xSync echo(sreal) \ + xSync echo(treal) \ + xCommit echo(sreal) \ + xCommit echo(treal) \ +] +do_test vtab4-2.3 { + execsql { + SELECT * FROM secho; + } +} {1 2 3 4 5 6 7 8 9} +do_test vtab4-2.4 { + execsql { + SELECT * FROM techo; + } +} {} + +# Try an explicit ROLLBACK on a transaction with two open virtual tables. +do_test vtab4-2.5 { + set echo_module [list] + execsql { + BEGIN; + INSERT INTO techo SELECT * FROM secho; + DELETE FROM secho; + ROLLBACK; + } + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'sreal'} \ + xBegin echo(treal) \ + xFilter {SELECT rowid, * FROM 'sreal'} \ + xBestIndex {SELECT rowid, * FROM 'sreal'} \ + xBegin echo(sreal) \ + xFilter {SELECT rowid, * FROM 'sreal'} \ + xRollback echo(treal) \ + xRollback echo(sreal) \ +] +do_test vtab4-2.6 { + execsql { + SELECT * FROM secho; + } +} {1 2 3 4 5 6 7 8 9} +do_test vtab4-2.7 { + execsql { + SELECT * FROM techo; + } +} {} + +do_test vtab4-3.1 { + set echo_module [list] + set echo_module_sync_fail treal + catchsql { + INSERT INTO techo VALUES(1, 2, 3); + } +} {1 {unknown error}} +do_test vtab4-3.2 { + set echo_module +} {xBegin echo(treal) xSync echo(treal) xRollback echo(treal)} + +do_test vtab4-3.3 { + set echo_module [list] + set echo_module_sync_fail sreal + catchsql { + BEGIN; + INSERT INTO techo SELECT * FROM secho; + DELETE FROM secho; + COMMIT; + } + set echo_module +} [list xBestIndex {SELECT rowid, * FROM 'sreal'} \ + xBegin echo(treal) \ + xFilter {SELECT rowid, * FROM 'sreal'} \ + xBestIndex {SELECT rowid, * FROM 'sreal'} \ + xBegin echo(sreal) \ + xFilter {SELECT rowid, * FROM 'sreal'} \ + xSync echo(treal) \ + xSync echo(sreal) \ + xRollback echo(treal) \ + xRollback echo(sreal) \ +] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab5.test b/components/external/SQLite-3.8.1/test/vtab5.test new file mode 100644 index 0000000000000000000000000000000000000000..bb84a5ceec6c6237db80ac6e6b04762dd3089790 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab5.test @@ -0,0 +1,154 @@ +# 2006 June 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# $Id: vtab5.test,v 1.8 2008/07/12 14:52:21 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +# The following tests - vtab5-1.* - ensure that an INSERT, DELETE or UPDATE +# statement can be executed immediately after a CREATE or schema reload. The +# point here is testing that the parser always calls xConnect() before the +# schema of a virtual table is used. +# +register_echo_module [sqlite3_connection_pointer db] +do_test vtab5-1.1 { + execsql { + CREATE TABLE treal(a VARCHAR(16), b INTEGER, c FLOAT); + INSERT INTO treal VALUES('a', 'b', 'c'); + CREATE VIRTUAL TABLE techo USING echo(treal); + } +} {} +do_test vtab5.1.2 { + execsql { + SELECT * FROM techo; + } +} {a b c} +do_test vtab5.1.3 { + db close + sqlite3 db test.db + register_echo_module [sqlite3_connection_pointer db] + execsql { + INSERT INTO techo VALUES('c', 'd', 'e'); + SELECT * FROM techo; + } +} {a b c c d e} +do_test vtab5.1.4 { + db close + sqlite3 db test.db + register_echo_module [sqlite3_connection_pointer db] + execsql { + UPDATE techo SET a = 10; + SELECT * FROM techo; + } +} {10 b c 10 d e} +do_test vtab5.1.5 { + db close + sqlite3 db test.db + register_echo_module [sqlite3_connection_pointer db] + execsql { + DELETE FROM techo WHERE b > 'c'; + SELECT * FROM techo; + } +} {10 b c} +do_test vtab5.1.X { + execsql { + DROP TABLE techo; + DROP TABLE treal; + } +} {} + +# The following tests - vtab5-2.* - ensure that collation sequences +# assigned to virtual table columns via the "CREATE TABLE" statement +# passed to sqlite3_declare_vtab() are used correctly. +# +do_test vtab5.2.1 { + execsql { + CREATE TABLE strings(str COLLATE NOCASE); + INSERT INTO strings VALUES('abc1'); + INSERT INTO strings VALUES('Abc3'); + INSERT INTO strings VALUES('ABc2'); + INSERT INTO strings VALUES('aBc4'); + SELECT str FROM strings ORDER BY 1; + } +} {abc1 ABc2 Abc3 aBc4} +do_test vtab5.2.2 { + execsql { + CREATE VIRTUAL TABLE echo_strings USING echo(strings); + SELECT str FROM echo_strings ORDER BY 1; + } +} {abc1 ABc2 Abc3 aBc4} +do_test vtab5.2.3 { + execsql { + SELECT str||'' FROM echo_strings ORDER BY 1; + } +} {ABc2 Abc3 aBc4 abc1} + +# Test that it is impossible to create a triggger on a virtual table. +# +ifcapable trigger { + do_test vtab5.3.1 { + catchsql { + CREATE TRIGGER trig INSTEAD OF INSERT ON echo_strings BEGIN + SELECT 1, 2, 3; + END; + } + } {1 {cannot create triggers on virtual tables}} + do_test vtab5.3.2 { + catchsql { + CREATE TRIGGER trig AFTER INSERT ON echo_strings BEGIN + SELECT 1, 2, 3; + END; + } + } {1 {cannot create triggers on virtual tables}} + do_test vtab5.3.2 { + catchsql { + CREATE TRIGGER trig BEFORE INSERT ON echo_strings BEGIN + SELECT 1, 2, 3; + END; + } + } {1 {cannot create triggers on virtual tables}} +} + +# Test that it is impossible to create an index on a virtual table. +# +do_test vtab5.4.1 { + catchsql { + CREATE INDEX echo_strings_i ON echo_strings(str); + } +} {1 {virtual tables may not be indexed}} + +# Test that it is impossible to add a column to a virtual table. +# +ifcapable altertable { + do_test vtab5.4.2 { + catchsql { + ALTER TABLE echo_strings ADD COLUMN col2; + } + } {1 {virtual tables may not be altered}} +} + +# Test that it is impossible to rename a virtual table. +# UPDATE: It is now possible. +# +# do_test vtab5.4.3 { +# catchsql { +# ALTER TABLE echo_strings RENAME TO echo_strings2; +# } +# } {1 {virtual tables may not be altered}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab6.test b/components/external/SQLite-3.8.1/test/vtab6.test new file mode 100644 index 0000000000000000000000000000000000000000..10bf286ab0f15f1b91d0929ff2f928b477ea63e3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab6.test @@ -0,0 +1,573 @@ +# 2002 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# This file implements tests for joins, including outer joins involving +# virtual tables. The test cases in this file are copied from the file +# join.test, and some of the comments still reflect that. +# +# $Id: vtab6.test,v 1.5 2009/07/01 16:12:08 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +register_echo_module [sqlite3_connection_pointer db] + +execsql { + CREATE TABLE real_t1(a,b,c); + CREATE TABLE real_t2(b,c,d); + CREATE TABLE real_t3(c,d,e); + CREATE TABLE real_t4(d,e,f); + CREATE TABLE real_t5(a INTEGER PRIMARY KEY); + CREATE TABLE real_t6(a INTEGER); + CREATE TABLE real_t7 (x, y); + CREATE TABLE real_t8 (a integer primary key, b); + CREATE TABLE real_t9(a INTEGER PRIMARY KEY, b); + CREATE TABLE real_t10(x INTEGER PRIMARY KEY, y); + CREATE TABLE real_t11(p INTEGER PRIMARY KEY, q); + CREATE TABLE real_t12(a,b); + CREATE TABLE real_t13(b,c); + CREATE TABLE real_t21(a,b,c); + CREATE TABLE real_t22(p,q); +} +foreach t [list t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t21 t22] { + execsql "CREATE VIRTUAL TABLE $t USING echo(real_$t)" +} + +do_test vtab6-1.1 { + execsql { + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(2,3,4); + INSERT INTO t1 VALUES(3,4,5); + SELECT * FROM t1; + } +} {1 2 3 2 3 4 3 4 5} +do_test vtab6-1.2 { + execsql { + INSERT INTO t2 VALUES(1,2,3); + INSERT INTO t2 VALUES(2,3,4); + INSERT INTO t2 VALUES(3,4,5); + SELECT * FROM t2; + } +} {1 2 3 2 3 4 3 4 5} + +do_test vtab6-1.3 { + execsql2 { + SELECT * FROM t1 NATURAL JOIN t2; + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test vtab6-1.3.1 { + execsql2 { + SELECT * FROM t2 NATURAL JOIN t1; + } +} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2} +do_test vtab6-1.3.2 { + execsql2 { + SELECT * FROM t2 AS x NATURAL JOIN t1; + } +} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2} +do_test vtab6-1.3.3 { + execsql2 { + SELECT * FROM t2 NATURAL JOIN t1 AS y; + } +} {b 2 c 3 d 4 a 1 b 3 c 4 d 5 a 2} +do_test vtab6-1.3.4 { + execsql { + SELECT b FROM t1 NATURAL JOIN t2; + } +} {2 3} +do_test vtab6-1.4.1 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 USING(b,c); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test vtab6-1.4.2 { + execsql2 { + SELECT * FROM t1 AS x INNER JOIN t2 USING(b,c); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test vtab6-1.4.3 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 AS y USING(b,c); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test vtab6-1.4.4 { + execsql2 { + SELECT * FROM t1 AS x INNER JOIN t2 AS y USING(b,c); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} +do_test vtab6-1.4.5 { + execsql { + SELECT b FROM t1 JOIN t2 USING(b); + } +} {2 3} +do_test vtab6-1.5 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 USING(b); + } +} {a 1 b 2 c 3 c 3 d 4 a 2 b 3 c 4 c 4 d 5} +do_test vtab6-1.6 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 USING(c); + } +} {a 1 b 2 c 3 b 2 d 4 a 2 b 3 c 4 b 3 d 5} +do_test vtab6-1.7 { + execsql2 { + SELECT * FROM t1 INNER JOIN t2 USING(c,b); + } +} {a 1 b 2 c 3 d 4 a 2 b 3 c 4 d 5} + +do_test vtab6-1.8 { + execsql { + SELECT * FROM t1 NATURAL CROSS JOIN t2; + } +} {1 2 3 4 2 3 4 5} +do_test vtab6-1.9 { + execsql { + SELECT * FROM t1 CROSS JOIN t2 USING(b,c); + } +} {1 2 3 4 2 3 4 5} +do_test vtab6-1.10 { + execsql { + SELECT * FROM t1 NATURAL INNER JOIN t2; + } +} {1 2 3 4 2 3 4 5} +do_test vtab6-1.11 { + execsql { + SELECT * FROM t1 INNER JOIN t2 USING(b,c); + } +} {1 2 3 4 2 3 4 5} +do_test vtab6-1.12 { + execsql { + SELECT * FROM t1 natural inner join t2; + } +} {1 2 3 4 2 3 4 5} + +ifcapable subquery { + do_test vtab6-1.13 { + execsql2 { + SELECT * FROM t1 NATURAL JOIN + (SELECT b as 'c', c as 'd', d as 'e' FROM t2) as t3 + } + } {a 1 b 2 c 3 d 4 e 5} + do_test vtab6-1.14 { + execsql2 { + SELECT * FROM (SELECT b as 'c', c as 'd', d as 'e' FROM t2) as 'tx' + NATURAL JOIN t1 + } + } {c 3 d 4 e 5 a 1 b 2} +} + +do_test vtab6-1.15 { + execsql { + INSERT INTO t3 VALUES(2,3,4); + INSERT INTO t3 VALUES(3,4,5); + INSERT INTO t3 VALUES(4,5,6); + SELECT * FROM t3; + } +} {2 3 4 3 4 5 4 5 6} +do_test vtab6-1.16 { + execsql { + SELECT * FROM t1 natural join t2 natural join t3; + } +} {1 2 3 4 5 2 3 4 5 6} +do_test vtab6-1.17 { + execsql2 { + SELECT * FROM t1 natural join t2 natural join t3; + } +} {a 1 b 2 c 3 d 4 e 5 a 2 b 3 c 4 d 5 e 6} +do_test vtab6-1.18 { + execsql { + INSERT INTO t4 VALUES(2,3,4); + INSERT INTO t4 VALUES(3,4,5); + INSERT INTO t4 VALUES(4,5,6); + SELECT * FROM t4; + } +} {2 3 4 3 4 5 4 5 6} +do_test vtab6-1.19.1 { + execsql { + SELECT * FROM t1 natural join t2 natural join t4; + } +} {1 2 3 4 5 6} +do_test vtab6-1.19.2 { + execsql2 { + SELECT * FROM t1 natural join t2 natural join t4; + } +} {a 1 b 2 c 3 d 4 e 5 f 6} +do_test vtab6-1.20 { + execsql { + SELECT * FROM t1 natural join t2 natural join t3 WHERE t1.a=1 + } +} {1 2 3 4 5} + +do_test vtab6-2.1 { + execsql { + SELECT * FROM t1 NATURAL LEFT JOIN t2; + } +} {1 2 3 4 2 3 4 5 3 4 5 {}} +do_test vtab6-2.2 { + execsql { + SELECT * FROM t2 NATURAL LEFT OUTER JOIN t1; + } +} {1 2 3 {} 2 3 4 1 3 4 5 2} +do_test vtab6-2.3 { + catchsql { + SELECT * FROM t1 NATURAL RIGHT OUTER JOIN t2; + } +} {1 {RIGHT and FULL OUTER JOINs are not currently supported}} +do_test vtab6-2.4 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d + } +} {1 2 3 {} {} {} 2 3 4 {} {} {} 3 4 5 1 2 3} +do_test vtab6-2.5 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d WHERE t1.a>1 + } +} {2 3 4 {} {} {} 3 4 5 1 2 3} +do_test vtab6-2.6 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.d WHERE t2.b IS NULL OR t2.b>1 + } +} {1 2 3 {} {} {} 2 3 4 {} {} {}} + +do_test vtab6-3.1 { + catchsql { + SELECT * FROM t1 NATURAL JOIN t2 ON t1.a=t2.b; + } +} {1 {a NATURAL join may not have an ON or USING clause}} +do_test vtab6-3.2 { + catchsql { + SELECT * FROM t1 NATURAL JOIN t2 USING(b); + } +} {1 {a NATURAL join may not have an ON or USING clause}} +do_test vtab6-3.3 { + catchsql { + SELECT * FROM t1 JOIN t2 ON t1.a=t2.b USING(b); + } +} {1 {cannot have both ON and USING clauses in the same join}} +do_test vtab6-3.4 { + catchsql { + SELECT * FROM t1 JOIN t2 USING(a); + } +} {1 {cannot join using column a - column not present in both tables}} +do_test vtab6-3.5 { + catchsql { SELECT * FROM t1 USING(a) } +} {1 {a JOIN clause is required before USING}} +do_test vtab6-3.6 { + catchsql { + SELECT * FROM t1 JOIN t2 ON t3.a=t2.b; + } +} {1 {no such column: t3.a}} +do_test vtab6-3.7 { + catchsql { + SELECT * FROM t1 INNER OUTER JOIN t2; + } +} {1 {unknown or unsupported join type: INNER OUTER}} +do_test vtab6-3.7 { + catchsql { + SELECT * FROM t1 LEFT BOGUS JOIN t2; + } +} {1 {unknown or unsupported join type: LEFT BOGUS}} + +do_test vtab6-4.1 { + execsql { + BEGIN; + INSERT INTO t6 VALUES(NULL); + INSERT INTO t6 VALUES(NULL); + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + INSERT INTO t6 SELECT * FROM t6; + COMMIT; + } + execsql { + SELECT * FROM t6 NATURAL JOIN t5; + } +} {} +do_test vtab6-4.2 { + execsql { + SELECT * FROM t6, t5 WHERE t6.at5.a; + } +} {} +do_test vtab6-4.4 { + execsql { + UPDATE t6 SET a='xyz'; + SELECT * FROM t6 NATURAL JOIN t5; + } +} {} +do_test vtab6-4.6 { + execsql { + SELECT * FROM t6, t5 WHERE t6.at5.a; + } +} {} +do_test vtab6-4.8 { + execsql { + UPDATE t6 SET a=1; + SELECT * FROM t6 NATURAL JOIN t5; + } +} {} +do_test vtab6-4.9 { + execsql { + SELECT * FROM t6, t5 WHERE t6.at5.a; + } +} {} + +# A test for ticket #247. +# +do_test vtab6-7.1 { + execsql { + INSERT INTO t7 VALUES ("pa1", 1); + INSERT INTO t7 VALUES ("pa2", NULL); + INSERT INTO t7 VALUES ("pa3", NULL); + INSERT INTO t7 VALUES ("pa4", 2); + INSERT INTO t7 VALUES ("pa30", 131); + INSERT INTO t7 VALUES ("pa31", 130); + INSERT INTO t7 VALUES ("pa28", NULL); + + INSERT INTO t8 VALUES (1, "pa1"); + INSERT INTO t8 VALUES (2, "pa4"); + INSERT INTO t8 VALUES (3, NULL); + INSERT INTO t8 VALUES (4, NULL); + INSERT INTO t8 VALUES (130, "pa31"); + INSERT INTO t8 VALUES (131, "pa30"); + + SELECT coalesce(t8.a,999) from t7 LEFT JOIN t8 on y=a; + } +} {1 999 999 2 131 130 999} + +# Make sure a left join where the right table is really a view that +# is itself a join works right. Ticket #306. +# +ifcapable view { +do_test vtab6-8.1 { + execsql { + BEGIN; + INSERT INTO t9 VALUES(1,11); + INSERT INTO t9 VALUES(2,22); + INSERT INTO t10 VALUES(1,2); + INSERT INTO t10 VALUES(3,3); + INSERT INTO t11 VALUES(2,111); + INSERT INTO t11 VALUES(3,333); + CREATE VIEW v10_11 AS SELECT x, q FROM t10, t11 WHERE t10.y=t11.p; + COMMIT; + SELECT * FROM t9 LEFT JOIN v10_11 ON( a=x ); + } +} {1 11 1 111 2 22 {} {}} +ifcapable subquery { + do_test vtab6-8.2 { + execsql { + SELECT * FROM t9 LEFT JOIN (SELECT x, q FROM t10, t11 WHERE t10.y=t11.p) + ON( a=x); + } + } {1 11 1 111 2 22 {} {}} +} +do_test vtab6-8.3 { + execsql { + SELECT * FROM v10_11 LEFT JOIN t9 ON( a=x ); + } +} {1 111 1 11 3 333 {} {}} +} ;# ifcapable view + +# Ticket #350 describes a scenario where LEFT OUTER JOIN does not +# function correctly if the right table in the join is really +# subquery. +# +# To test the problem, we generate the same LEFT OUTER JOIN in two +# separate selects but with on using a subquery and the other calling +# the table directly. Then connect the two SELECTs using an EXCEPT. +# Both queries should generate the same results so the answer should +# be an empty set. +# +ifcapable compound { +do_test vtab6-9.1 { + execsql { + BEGIN; + INSERT INTO t12 VALUES(1,11); + INSERT INTO t12 VALUES(2,22); + INSERT INTO t13 VALUES(22,222); + COMMIT; + } +} {} + +ifcapable subquery { + do_test vtab6-9.1.1 { + execsql { + SELECT * FROM t12 NATURAL LEFT JOIN t13 + EXCEPT + SELECT * FROM t12 NATURAL LEFT JOIN (SELECT * FROM t13 WHERE b>0); + } + } {} +} +ifcapable view { + do_test vtab6-9.2 { + execsql { + CREATE VIEW v13 AS SELECT * FROM t13 WHERE b>0; + SELECT * FROM t12 NATURAL LEFT JOIN t13 + EXCEPT + SELECT * FROM t12 NATURAL LEFT JOIN v13; + } + } {} +} ;# ifcapable view +} ;# ifcapable compound + +ifcapable subquery { +do_test vtab6-10.1 { + execsql { + CREATE INDEX i22 ON real_t22(q); + SELECT a FROM t21 LEFT JOIN t22 ON b=p WHERE q= + (SELECT max(m.q) FROM t22 m JOIN t21 n ON n.b=m.p WHERE n.c=1); + } +} {} +} ;# ifcapable subquery + +do_test vtab6-11.1.0 { + execsql { + CREATE TABLE ab_r(a, b); + CREATE TABLE bc_r(b, c); + + CREATE VIRTUAL TABLE ab USING echo(ab_r); + CREATE VIRTUAL TABLE bc USING echo(bc_r); + + INSERT INTO ab VALUES(1, 2); + INSERT INTO bc VALUES(2, 3); + } +} {} + +do_test vtab6-11.1.1 { + execsql { + SELECT a, b, c FROM ab NATURAL JOIN bc; + } +} {1 2 3} +do_test vtab6-11.1.2 { + execsql { + SELECT a, b, c FROM bc NATURAL JOIN ab; + } +} {1 2 3} + +set ::echo_module_cost 1.0 + +do_test vtab6-11.1.3 { + execsql { + SELECT a, b, c FROM ab NATURAL JOIN bc; + } +} {1 2 3} +do_test vtab6-11.1.4 { + execsql { + SELECT a, b, c FROM bc NATURAL JOIN ab; + } +} {1 2 3} + + +do_test vtab6-11.2.0 { + execsql { + CREATE INDEX ab_i ON ab_r(b); + CREATE INDEX bc_i ON bc_r(b); + } +} {} + +unset ::echo_module_cost + +do_test vtab6-11.2.1 { + execsql { + SELECT a, b, c FROM ab NATURAL JOIN bc; + } +} {1 2 3} +do_test vtab6-11.2.2 { + execsql { + SELECT a, b, c FROM bc NATURAL JOIN ab; + } +} {1 2 3} + +set ::echo_module_cost 1.0 + +do_test vtab6-11.2.3 { + execsql { + SELECT a, b, c FROM ab NATURAL JOIN bc; + } +} {1 2 3} +do_test vtab6-11.2.4 { + execsql { + SELECT a, b, c FROM bc NATURAL JOIN ab; + } +} {1 2 3} + +unset ::echo_module_cost +db close +sqlite3 db test.db +register_echo_module [sqlite3_connection_pointer db] + +do_test vtab6-11.3.1 { + execsql { + SELECT a, b, c FROM ab NATURAL JOIN bc; + } +} {1 2 3} + +do_test vtab6-11.3.2 { + execsql { + SELECT a, b, c FROM bc NATURAL JOIN ab; + } +} {1 2 3} + +set ::echo_module_cost 1.0 + +do_test vtab6-11.3.3 { + execsql { + SELECT a, b, c FROM ab NATURAL JOIN bc; + } +} {1 2 3} +do_test vtab6-11.3.4 { + execsql { + SELECT a, b, c FROM bc NATURAL JOIN ab; + } +} {1 2 3} + +unset ::echo_module_cost + +set ::echo_module_ignore_usable 1 +db cache flush + +do_test vtab6-11.4.1 { + catchsql { + SELECT a, b, c FROM ab NATURAL JOIN bc; + } +} {1 {table ab: xBestIndex returned an invalid plan}} +do_test vtab6-11.4.2 { + catchsql { + SELECT a, b, c FROM bc NATURAL JOIN ab; + } +} {1 {table bc: xBestIndex returned an invalid plan}} + +unset ::echo_module_ignore_usable + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab7.test b/components/external/SQLite-3.8.1/test/vtab7.test new file mode 100644 index 0000000000000000000000000000000000000000..162bab5e879a1a3118b3b6f8468f0cb511516c1e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab7.test @@ -0,0 +1,207 @@ +# 2006 July 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus +# of this test is reading and writing to the database from within a +# virtual table xSync() callback. +# +# $Id: vtab7.test,v 1.4 2007/12/04 16:54:53 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +# Register the echo module. Code inside the echo module appends elements +# to the global tcl list variable ::echo_module whenever SQLite invokes +# certain module callbacks. This includes the xSync(), xCommit() and +# xRollback() callbacks. For each of these callback, two elements are +# appended to ::echo_module, as follows: +# +# Module method Elements appended to ::echo_module +# ------------------------------------------------------- +# xSync() xSync echo($tablename) +# xCommit() xCommit echo($tablename) +# xRollback() xRollback echo($tablename) +# ------------------------------------------------------- +# +# In each case, $tablename is replaced by the name of the real table (not +# the echo table). By setting up a tcl trace on the ::echo_module variable, +# code in this file arranges for a Tcl script to be executed from within +# the echo module xSync() callback. +# +register_echo_module [sqlite3_connection_pointer db] +trace add variable ::echo_module write echo_module_trace + +# This Tcl proc is invoked whenever the ::echo_module variable is written. +# +proc echo_module_trace {args} { + # Filter out writes to ::echo_module that are not xSync, xCommit or + # xRollback callbacks. + if {[llength $::echo_module] < 2} return + set x [lindex $::echo_module end-1] + if {$x ne "xSync" && $x ne "xCommit" && $x ne "xRollback"} return + + regexp {^echo.(.*).$} [lindex $::echo_module end] dummy tablename + # puts "Ladies and gentlemen, an $x on $tablename!" + + if {[info exists ::callbacks($x,$tablename)]} { + eval $::callbacks($x,$tablename) + } +} + +# The following tests, vtab7-1.*, test that the trace callback on +# ::echo_module is providing the expected tcl callbacks. +do_test vtab7-1.1 { + execsql { + CREATE TABLE abc(a, b, c); + CREATE VIRTUAL TABLE abc2 USING echo(abc); + } +} {} + +do_test vtab7-1.2 { + set ::callbacks(xSync,abc) {incr ::counter} + set ::counter 0 + execsql { + INSERT INTO abc2 VALUES(1, 2, 3); + } + set ::counter +} {1} + +# Write to an existing database table from within an xSync callback. +do_test vtab7-2.1 { + set ::callbacks(xSync,abc) { + execsql {INSERT INTO log VALUES('xSync');} + } + execsql { + CREATE TABLE log(msg); + INSERT INTO abc2 VALUES(4, 5, 6); + SELECT * FROM log; + } +} {xSync} +do_test vtab7-2.3 { + execsql { + INSERT INTO abc2 VALUES(4, 5, 6); + SELECT * FROM log; + } +} {xSync xSync} +do_test vtab7-2.4 { + execsql { + INSERT INTO abc2 VALUES(4, 5, 6); + SELECT * FROM log; + } +} {xSync xSync xSync} + +# Create a database table from within xSync callback. +do_test vtab7-2.5 { + set ::callbacks(xSync,abc) { + execsql { CREATE TABLE newtab(d, e, f); } + } + execsql { + INSERT INTO abc2 VALUES(1, 2, 3); + SELECT name FROM sqlite_master ORDER BY name; + } +} {abc abc2 log newtab} + +# Drop a database table from within xSync callback. +# This is not allowed. Tables cannot be dropped while +# any other statement is active. +# +do_test vtab7-2.6 { + set ::callbacks(xSync,abc) { + set ::rc [catchsql { DROP TABLE newtab }] + } + execsql { + INSERT INTO abc2 VALUES(1, 2, 3); + SELECT name FROM sqlite_master ORDER BY name; + } +} {abc abc2 log newtab} +do_test vtab7-2.6.1 { + set ::rc +} {1 {database table is locked}} +execsql {DROP TABLE newtab} + +# Write to an attached database from xSync(). +ifcapable attach { + do_test vtab7-3.1 { + forcedelete test2.db + forcedelete test2.db-journal + execsql { + ATTACH 'test2.db' AS db2; + CREATE TABLE db2.stuff(description, shape, color); + } + set ::callbacks(xSync,abc) { + execsql { INSERT INTO db2.stuff VALUES('abc', 'square', 'green'); } + } + execsql { + INSERT INTO abc2 VALUES(1, 2, 3); + SELECT * from stuff; + } + } {abc square green} +} + +# UPDATE: The next test passes, but leaks memory. So leave it out. +# +# The following tests test that writing to the database from within +# the xCommit callback causes a misuse error. +# do_test vtab7-4.1 { +# unset -nocomplain ::callbacks(xSync,abc) +# set ::callbacks(xCommit,abc) { +# execsql { INSERT INTO log VALUES('hello') } +# } +# catchsql { +# INSERT INTO abc2 VALUES(1, 2, 3); +# } +# } {1 {library routine called out of sequence}} + +# These tests, vtab7-4.*, test that an SQLITE_LOCKED error is returned +# if an attempt to write to a virtual module table or create a new +# virtual table from within an xSync() callback. +do_test vtab7-4.1 { + execsql { + CREATE TABLE def(d, e, f); + CREATE VIRTUAL TABLE def2 USING echo(def); + } + set ::callbacks(xSync,abc) { + set ::error [catchsql { INSERT INTO def2 VALUES(1, 2, 3) }] + } + execsql { + INSERT INTO abc2 VALUES(1, 2, 3); + } + set ::error +} {1 {database table is locked}} +do_test vtab7-4.2 { + set ::callbacks(xSync,abc) { + set ::error [catchsql { CREATE VIRTUAL TABLE def3 USING echo(def) }] + } + execsql { + INSERT INTO abc2 VALUES(1, 2, 3); + } + set ::error +} {1 {database table is locked}} + +do_test vtab7-4.3 { + set ::callbacks(xSync,abc) { + set ::error [catchsql { DROP TABLE def2 }] + } + execsql { + INSERT INTO abc2 VALUES(1, 2, 3); + SELECT name FROM sqlite_master ORDER BY name; + } + set ::error +} {1 {database table is locked}} + +trace remove variable ::echo_module write echo_module_trace +unset -nocomplain ::callbacks + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab8.test b/components/external/SQLite-3.8.1/test/vtab8.test new file mode 100644 index 0000000000000000000000000000000000000000..8e04a4155f18d7b5f11c7de61b857a50bf1cdfe6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab8.test @@ -0,0 +1,78 @@ +# 2006 August 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file inserting into virtual tables from a SELECT +# statement. +# +# $Id: vtab8.test,v 1.2 2007/03/02 08:12:23 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +register_echo_module [sqlite3_connection_pointer db] + +# See ticket #2244 +# +do_test vtab1.2244-1 { + execsql { + CREATE TABLE t2244(a, b); + CREATE VIRTUAL TABLE t2244e USING echo(t2244); + INSERT INTO t2244 VALUES('AA', 'BB'); + INSERT INTO t2244 VALUES('CC', 'DD'); + SELECT rowid, * FROM t2244e; + } +} {1 AA BB 2 CC DD} +do_test vtab1.2244-2 { + execsql { + SELECT * FROM t2244e WHERE rowid = 10; + } +} {} +do_test vtab1.2244-3 { + execsql { + UPDATE t2244e SET a = 'hello world' WHERE 0; + SELECT rowid, * FROM t2244e; + } +} {1 AA BB 2 CC DD} + +do_test vtab1-2250-2 { + execsql { + CREATE TABLE t2250(a, b); + INSERT INTO t2250 VALUES(10, 20); + CREATE VIRTUAL TABLE t2250e USING echo(t2250); + select max(rowid) from t2250; + select max(rowid) from t2250e; + } +} {1 1} + +# See ticket #2260. +# +do_test vtab1.2260-1 { + execsql { + CREATE TABLE t2260a_real(a, b); + CREATE TABLE t2260b_real(a, b); + + CREATE INDEX i2260 ON t2260a_real(a); + CREATE INDEX i2260x ON t2260b_real(a); + + CREATE VIRTUAL TABLE t2260a USING echo(t2260a_real); + CREATE VIRTUAL TABLE t2260b USING echo(t2260b_real); + + SELECT * FROM t2260a, t2260b WHERE t2260a.a = t2260b.a AND t2260a.a > 101; + } +} {} + +unset -nocomplain echo_module_begin_fail +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab9.test b/components/external/SQLite-3.8.1/test/vtab9.test new file mode 100644 index 0000000000000000000000000000000000000000..b1290ebd507646d22e7163d4a747c64b50af9962 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab9.test @@ -0,0 +1,70 @@ +# 2006 August 29 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file inserting into virtual tables from a SELECT +# statement. +# +# $Id: vtab9.test,v 1.2 2007/04/16 15:06:26 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +do_test vtab9-1.1 { + register_echo_module [sqlite3_connection_pointer db] + execsql { + CREATE TABLE t0(a); + CREATE VIRTUAL TABLE t1 USING echo(t0); + INSERT INTO t1 SELECT 'hello'; + SELECT rowid, * FROM t1; + } +} {1 hello} + +do_test vtab9-1.2 { + execsql { + CREATE TABLE t2(a,b,c); + CREATE VIRTUAL TABLE t3 USING echo(t2); + CREATE TABLE d1(a,b,c); + INSERT INTO d1 VALUES(1,2,3); + INSERT INTO d1 VALUES('a','b','c'); + INSERT INTO d1 VALUES(NULL,'x',123.456); + INSERT INTO d1 VALUES(x'6869',123456789,-12345); + INSERT INTO t3(a,b,c) SELECT * FROM d1; + SELECT rowid, * FROM t3; + } +} {1 1 2 3 2 a b c 3 {} x 123.456 4 hi 123456789 -12345} + +# do_test vtab9-2.1 { +# execsql { +# CREATE TABLE t4(a); +# CREATE VIRTUAL TABLE t5 USING echo(t4); +# INSERT INTO t4 VALUES('hello'); +# SELECT rowid, a FROM t5; +# } +# } {1 hello} +# do_test vtab9-2.2 { +# execsql { +# INSERT INTO t5(rowid, a) VALUES(1, 'goodbye'); +# } +# } {1 hello} +# do_test vtab9-2.3 { +# execsql { +# REPLACE INTO t5(rowid, a) VALUES(1, 'goodbye'); +# SELECT * FROM t5; +# } +# } {1 goodbye} + +unset -nocomplain echo_module_begin_fail +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtabA.test b/components/external/SQLite-3.8.1/test/vtabA.test new file mode 100644 index 0000000000000000000000000000000000000000..928cc2b703a0b129ff765f16c50e9e68d2371228 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtabA.test @@ -0,0 +1,153 @@ +# 2007 June 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is 'hidden' virtual table columns. +# +# $Id: vtabA.test,v 1.2 2008/07/12 14:52:21 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +proc get_decltype {table col} { + set STMT [sqlite3_prepare $::DB "SELECT $col FROM $table" -1 TAIL] + set decltype [sqlite3_column_decltype $STMT 0] + sqlite3_finalize $STMT + set decltype +} + +proc get_collist {table} { + set ret [list] + db eval "PRAGMA table_info($table)" { lappend ret $name } + set ret +} + +# Register the echo module +register_echo_module [sqlite3_connection_pointer db] + +# Create a virtual table with a 'hidden' column (column b). +# +do_test vtabA-1.1 { + execsql { CREATE TABLE t1(a, b HIDDEN VARCHAR, c INTEGER) } +} {} +do_test vtabA-1.2 { + execsql { CREATE VIRTUAL TABLE t1e USING echo(t1) } +} {} + +# Test that the hidden column is not listed by [PRAGMA table_info]. +# +do_test vtabA-1.3 { + execsql { PRAGMA table_info(t1e) } +} [list \ + 0 a {} 0 {} 0 \ + 1 c INTEGER 0 {} 0 \ +] + +# Test that the hidden column is not require in the default column +# list for an INSERT statement. +# +do_test vtabA-1.4 { + catchsql { + INSERT INTO t1e VALUES('value a', 'value c'); + } +} {0 {}} +do_test vtabA-1.5 { + execsql { + SELECT a, b, c FROM t1e; + } +} {{value a} {} {value c}} + +do_test vtabA-1.6 { + execsql { + SELECT * FROM t1e; + } +} {{value a} {value c}} + +# Test that the expansion of a '*' expression in the result set of +# a SELECT does not include the hidden column. +# +do_test vtabA-1.7 { + execsql { + INSERT INTO t1e SELECT * FROM t1e; + } +} {} +do_test vtabA-1.8 { + execsql { + SELECT * FROM t1e; + } +} {{value a} {value c} {value a} {value c}} + +# Test that the declaration type of the hidden column does not include +# the token "HIDDEN". +# +do_test vtabA-1.9 { + get_decltype t1e b +} {VARCHAR} +do_test vtabA-1.10 { + get_collist t1e +} {a c} + +#---------------------------------------------------------------------- +# These tests vtabA-2.* concentrate on testing that the HIDDEN token +# is detected and handled correctly in various declarations. +# +proc analyse_parse {columns decltype_list} { + db eval { DROP TABLE IF EXISTS t1e; } + db eval { DROP TABLE IF EXISTS t1; } + db eval " CREATE TABLE t1 $columns " + db eval { CREATE VIRTUAL TABLE t1e USING echo(t1) } + set ret [list [get_collist t1e]] + foreach c $decltype_list { + lappend ret [get_decltype t1e $c] + } + set ret +} + +do_test vtabA-2.1 { + analyse_parse {(a text, b integer hidden, c hidden)} {a b c} +} {a text integer {}} + +do_test vtabA-2.2 { + analyse_parse {(a hidden , b integerhidden, c hidden1)} {a b c} +} {{b c} {} integerhidden hidden1} + +do_test vtabA-2.3 { + analyse_parse {(a HiDden, b HIDDEN, c hidden)} {a b c} +} {{} {} {} {}} + +do_test vtabA-2.4 { + analyse_parse {(a whatelse can i hidden test, b HIDDEN hidden)} {a b} +} {{} {whatelse can i test} hidden} + + +# Ticket [d2f02d37f52bfe23e421f2c60fbb8586ac76ff01]: +# assertion failure on an UPDATE involving two virtual tables. +# +do_test vtabA-3.1 { + db eval { + DROP TABLE IF EXISTS t1; + DROP TABLE IF EXISTS t2; + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,2); + CREATE TABLE t2(x,y); + INSERT INTO t2 VALUES(3,4); + CREATE VIRTUAL TABLE vt1 USING echo(t1); + CREATE VIRTUAL TABLE vt2 USING echo(t2); + UPDATE vt2 SET x=(SELECT a FROM vt1 WHERE b=2) WHERE y=4; + SELECT * FROM t2; + } +} {1 4} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtabB.test b/components/external/SQLite-3.8.1/test/vtabB.test new file mode 100644 index 0000000000000000000000000000000000000000..201e97895043c05a411d733067e31cb937db2390 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtabB.test @@ -0,0 +1,79 @@ +# 2008 April 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is is verifying that a virtual table in the +# TEMP database that is created and dropped within a transaction +# is handled correctly. Ticket #2994. +# +# Also make sure a virtual table on the right-hand side of an IN operator +# is materialized rather than being used directly. Ticket #3082. +# + +# +# $Id: vtabB.test,v 1.2 2008/04/25 12:10:15 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +do_test vtabB-1.1 { + register_echo_module [sqlite3_connection_pointer db] + execsql { + CREATE TABLE t1(x); + BEGIN; + CREATE VIRTUAL TABLE temp.echo_test1 USING echo(t1); + DROP TABLE echo_test1; + ROLLBACK; + } +} {} + +do_test vtabB-2.1 { + execsql { + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + CREATE TABLE t2(y); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(2); + CREATE VIRTUAL TABLE echo_t2 USING echo(t2); + SELECT * FROM t1 WHERE x IN (SELECT rowid FROM t2); + } +} {2} +do_test vtab8-2.2 { + execsql { + SELECT rowid FROM echo_t2 + } +} {1 2} +do_test vtabB-2.3 { + execsql { + SELECT * FROM t1 WHERE x IN (SELECT rowid FROM t2); + } +} {2} +do_test vtabB-2.4 { + execsql { + SELECT * FROM t1 WHERE x IN (SELECT rowid FROM echo_t2); + } +} {2} +do_test vtabB-2.5 { + execsql { + SELECT * FROM t1 WHERE x IN (SELECT y FROM t2); + } +} {2} +do_test vtabB-2.6 { + execsql { + SELECT * FROM t1 WHERE x IN (SELECT y FROM echo_t2); + } +} {2} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtabC.test b/components/external/SQLite-3.8.1/test/vtabC.test new file mode 100644 index 0000000000000000000000000000000000000000..ca78b706f6ca5db198d73af21f5e40038738fe95 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtabC.test @@ -0,0 +1,116 @@ +# 2008 April 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is is verifying that the xUpdate, xSync, xCommit +# and xRollback methods are only invoked after an xBegin or xCreate. +# Ticket #3083. +# +# $Id: vtabC.test,v 1.2 2009/04/07 14:14:23 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +ifcapable !trigger { finish_test ; return } + + +# N will be the number of virtual tables we have defined. +# +unset -nocomplain N +for {set N 1} {$N<=20} {incr N} { + db close + forcedelete test.db test.db-journal + sqlite3 db test.db + register_echo_module [sqlite3_connection_pointer db] + + # Create $N tables and $N virtual tables to echo them. + # + unset -nocomplain tablist + set tablist {} + do_test vtabC-1.$N.1 { + for {set i 1} {$i<=$::N} {incr i} { + execsql "CREATE TABLE t${i}(x)" + execsql "CREATE VIRTUAL TABLE vt$i USING echo(t$i)" + lappend ::tablist t$i vt$i + } + execsql {SELECT count(*) FROM sqlite_master} + } [expr {$N*2}] + do_test vtabC-1.$N.2 { + execsql {SELECT name FROM sqlite_master} + } $tablist + + # Create a table m and add triggers to make changes on all + # of the virtual tables when m is changed. + # + do_test vtabC-1.$N.3 { + execsql {CREATE TABLE m(a)} + set sql "CREATE TRIGGER rins AFTER INSERT ON m BEGIN\n" + for {set i 1} {$i<=$::N} {incr i} { + append sql " INSERT INTO vt$i VALUES(NEW.a+$i);\n" + } + append sql "END;" + execsql $sql + execsql {SELECT count(*) FROM sqlite_master} + } [expr {$N*2+2}] + do_test vtabC-1.$N.4 { + execsql { + INSERT INTO m VALUES(1000); + SELECT * FROM m; + } + } {1000} + for {set j 1} {$j<=$::N} {incr j} { + do_test vtabC-1.$N.5.$j { + execsql "SELECT * FROM t$::j" + } [expr {$j+1000}] + do_test vtabC-1.$N.6.$j { + execsql "SELECT * FROM vt$::j" + } [expr {$j+1000}] + } + do_test vtabC-1.$N.7 { + set sql "CREATE TRIGGER rins2 BEFORE INSERT ON m BEGIN\n" + for {set i 1} {$i<=$::N} {incr i} { + append sql " INSERT INTO vt$i VALUES(NEW.a+$i*100);\n" + } + for {set i 1} {$i<=$::N} {incr i} { + append sql " INSERT INTO vt$i VALUES(NEW.a+$i*10000);\n" + } + append sql "END;" + execsql $sql + execsql {SELECT count(*) FROM sqlite_master} + } [expr {$N*2+3}] + do_test vtabC-1.$N.8 { + execsql { + INSERT INTO m VALUES(9000000); + SELECT * FROM m; + } + } {1000 9000000} + unset -nocomplain res + for {set j 1} {$j<=$::N} {incr j} { + set res [expr {$j+1000}] + lappend res [expr {$j*100+9000000}] + lappend res [expr {$j*10000+9000000}] + lappend res [expr {$j+9000000}] + do_test vtabC-1.$N.9.$j { + execsql "SELECT * FROM t$::j" + } $res + do_test vtabC-1.$N.10.$j { + execsql "SELECT * FROM vt$::j" + } $res + } +} +unset -nocomplain res N i j + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtabD.test b/components/external/SQLite-3.8.1/test/vtabD.test new file mode 100644 index 0000000000000000000000000000000000000000..589f518983d0b0abdf945175fb1067eecf486b3a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtabD.test @@ -0,0 +1,69 @@ +# 2009 April 14 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is creating and dropping virtual tables. +# +# $Id: vtabD.test,v 1.3 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab||!schema_pragmas { finish_test ; return } + +# Register the echo module +register_echo_module [sqlite3_connection_pointer db] + +do_test vtabD-1.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); + CREATE VIRTUAL TABLE tv1 USING echo(t1); + } +} {} +do_test vtabD-1.2 { + execsql BEGIN + for {set i 0} {$i < 100000} {incr i} { + execsql { INSERT INTO t1 VALUES($i, $i*$i) } + } + execsql COMMIT +} {} +do_test vtabD-1.3 { + execsql { SELECT * FROM tv1 WHERE a = 1 OR b = 4 } +} {1 1 2 4} +do_test vtabD-1.4 { + execsql { SELECT * FROM tv1 WHERE a = 1 OR b = 1 } +} {1 1} +do_test vtabD-1.5 { + execsql { SELECT * FROM tv1 WHERE (a > 0 AND a < 5) OR (b > 15 AND b < 65) } +} {1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64} + +do_test vtabD-1.6 { + execsql { SELECT * FROM tv1 WHERE a < 500 OR b = 810000 } +} [execsql { + SELECT * FROM t1 WHERE a < 500; + SELECT * FROM t1 WHERE b = 810000 AND NOT (a < 500); +}] + +do_test vtabD-1.7 { + execsql { SELECT * FROM tv1 WHERE a < 90000 OR b = 8100000000 } +} [execsql { + SELECT * FROM t1 WHERE a < 90000; + SELECT * FROM t1 WHERE b = 8100000000 AND NOT (a < 90000); +}] + +if {[working_64bit_int]} { +do_test vtabD-1.8 { + execsql { SELECT * FROM tv1 WHERE a = 90001 OR b = 810000 } +} {90001 8100180001 900 810000} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtabE.test b/components/external/SQLite-3.8.1/test/vtabE.test new file mode 100644 index 0000000000000000000000000000000000000000..22ec0181bfbc5c9e45228e330f4c41f20196fe0c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtabE.test @@ -0,0 +1,48 @@ +# 2009 November 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# +# The focus of this file making sure the register cache logic works +# correctly with virtual tables. Ticket [16fbf14cb2]. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + +register_tclvar_module [sqlite3_connection_pointer db] + +unset -nocomplain vtabE +set vtabE(vtabE1) 11 +set vtabE(vtabE2) 22 +unset -nocomplain vtabE1 +set vtabE1(w) x +set vtabE1(y) z +unset -nocomplain vtabE2 +set vtabE2(a) b +set vtabE2(c) d + +do_test vtabE-1 { + db eval { + CREATE VIRTUAL TABLE t1 USING tclvar; + CREATE VIRTUAL TABLE t2 USING tclvar; + CREATE TABLE t3(a INTEGER PRIMARY KEY, b); + SELECT t1.*, t2.*, abs(t3.b + abs(t2.value + abs(t1.value))) + FROM t1 LEFT JOIN t2 ON t2.name = t1.arrayname + LEFT JOIN t3 ON t3.a=t2.value + WHERE t1.name = 'vtabE' + ORDER BY t1.value, t2.value; + } +} {vtabE vtabE1 11 vtabE1 w x {} vtabE vtabE1 11 vtabE1 y z {} vtabE vtabE2 22 vtabE2 a b {} vtabE vtabE2 22 vtabE2 c d {}} diff --git a/components/external/SQLite-3.8.1/test/vtabF.test b/components/external/SQLite-3.8.1/test/vtabF.test new file mode 100644 index 0000000000000000000000000000000000000000..b9341ea5972ae92c4766e9d31c3839ddd1136d28 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtabF.test @@ -0,0 +1,45 @@ +# 2011 Aug 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. +# This file checks to make sure IS NOT NULL constraints work on +# virtual tables. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab||!schema_pragmas { finish_test ; return } + +# Register the echo module +register_echo_module [sqlite3_connection_pointer db] + +do_test vtabE-1.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); + INSERT INTO t1 VALUES(10,110); + INSERT INTO t1 VALUES(11,111); + INSERT INTO t1 SELECT a+2, b+2 FROM t1; + INSERT INTO t1 SELECT null, b+4 FROM t1; + INSERT INTO t1 SELECT null, b+8 FROM t1; + INSERT INTO t1 SELECT null, b+16 FROM t1; + ANALYZE; + CREATE VIRTUAL TABLE tv1 USING echo(t1); + SELECT b FROM t1 WHERE a IS NOT NULL; + } +} {110 111 112 113} +do_test vtabE-1.2 { + execsql {SELECT b FROM tv1 WHERE a IS NOT NULL} +} {110 111 112 113} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab_alter.test b/components/external/SQLite-3.8.1/test/vtab_alter.test new file mode 100644 index 0000000000000000000000000000000000000000..eb50a28a5e8d93e60e80dfa7f38da49d8df75a71 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab_alter.test @@ -0,0 +1,103 @@ +# 2007 June 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the ALTER TABLE ... RENAME TO +# command on virtual tables. +# +# $Id: vtab_alter.test,v 1.3 2007/12/13 21:54:11 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab||!altertable { + finish_test + return +} + +# Register the echo module. +# +# This test uses a special feature of the echo module. If the name +# of the virtual table is a prefix of the name of the underlying +# real table (for example if the v-table is "tbl" and the real table +# is "tbl_base"), then the name of the real table is modified +# when an "ALTER TABLE ... RENAME TO" is executed on the v-table. +# For example: +# +# sqlite> CREATE TABLE t1_base(a, b, c); +# sqlite> CREATE VIRTUAL TABLE t1 USING(t1_base); +# sqlite> ALTER TABLE t1 RENAME TO t2; +# sqlite> SELECT tbl_name FROM sqlite_master; +# t2_base +# t2 +# +register_echo_module [sqlite3_connection_pointer db] + + +# Try to rename an echo table. Make sure nothing terrible happens. +# +do_test vtab_alter-1.1 { + execsql { CREATE TABLE t1(a, b VARCHAR, c INTEGER) } +} {} +do_test vtab_alter-1.2 { + execsql { CREATE VIRTUAL TABLE t1echo USING echo(t1) } +} {} +do_test vtab_alter-1.3 { + catchsql { SELECT * FROM t1echo } +} {0 {}} +do_test vtab_alter-1.4 { + execsql { ALTER TABLE t1echo RENAME TO new } +} {} +do_test vtab_alter-1.5 { + catchsql { SELECT * FROM t1echo } +} {1 {no such table: t1echo}} +do_test vtab_alter-1.6 { + catchsql { SELECT * FROM new } +} {0 {}} + +# Try to rename an echo table that renames its base table. Make +# sure nothing terrible happens. +# +do_test vtab_alter-2.1 { + execsql { + DROP TABLE new; + DROP TABLE t1; + CREATE TABLE t1_base(a, b, c); + CREATE VIRTUAL TABLE t1 USING echo('*_base'); + } +} {} +do_test vtab_alter-2.2 { + execsql { + INSERT INTO t1_base VALUES(1, 2, 3); + SELECT * FROM t1; + } +} {1 2 3} +do_test vtab_alter-2.3 { + execsql { ALTER TABLE t1 RENAME TO x } +} {} +do_test vtab_alter-2.4 { + execsql { SELECT * FROM x; } +} {1 2 3} +do_test vtab_alter-2.5 { + execsql { SELECT * FROM x_base; } +} {1 2 3} + +# Cause an error to occur when the echo module renames its +# backing store table. +# +do_test vtab_alter-3.1 { + execsql { CREATE TABLE y_base(a, b, c) } + catchsql { ALTER TABLE x RENAME TO y } +} {1 {SQL logic error or missing database}} +do_test vtab_alter-3.2 { + execsql { SELECT * FROM x } +} {1 2 3} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab_err.test b/components/external/SQLite-3.8.1/test/vtab_err.test new file mode 100644 index 0000000000000000000000000000000000000000..068386eb31e12eb50eb2ec4e5cf1163fce05ec85 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab_err.test @@ -0,0 +1,71 @@ +# 2006 June 10 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# $Id: vtab_err.test,v 1.8 2007/09/03 16:12:10 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab { + finish_test + return +} + + + +unset -nocomplain echo_module_begin_fail +do_ioerr_test vtab_err-1 -tclprep { + register_echo_module [sqlite3_connection_pointer db] +} -sqlbody { + BEGIN; + CREATE TABLE r(a PRIMARY KEY, b, c); + CREATE VIRTUAL TABLE e USING echo(r); + INSERT INTO e VALUES(1, 2, 3); + INSERT INTO e VALUES('a', 'b', 'c'); + UPDATE e SET c = 10; + DELETE FROM e WHERE a = 'a'; + COMMIT; + BEGIN; + CREATE TABLE r2(a, b, c); + INSERT INTO r2 SELECT * FROM e; + INSERT INTO e SELECT a||'x', b, c FROM r2; + COMMIT; +} + +ifcapable !memdebug { + puts "Skipping vtab_err-2 tests: not compiled with -DSQLITE_MEMDEBUG..." + finish_test + return +} +source $testdir/malloc_common.tcl + + +do_malloc_test vtab_err-2 -tclprep { + register_echo_module [sqlite3_connection_pointer db] +} -sqlbody { + BEGIN; + CREATE TABLE r(a PRIMARY KEY, b, c); + CREATE VIRTUAL TABLE e USING echo(r); + INSERT INTO e VALUES(1, 2, 3); + INSERT INTO e VALUES('a', 'b', 'c'); + UPDATE e SET c = 10; + DELETE FROM e WHERE a = 'a'; + COMMIT; + BEGIN; + CREATE TABLE r2(a, b, c); + INSERT INTO r2 SELECT * FROM e; + INSERT INTO e SELECT a||'x', b, c FROM r2; + COMMIT; +} + +sqlite3_memdebug_fail -1 + +finish_test diff --git a/components/external/SQLite-3.8.1/test/vtab_shared.test b/components/external/SQLite-3.8.1/test/vtab_shared.test new file mode 100644 index 0000000000000000000000000000000000000000..6a76e2749b014c57cedd4e36da2b85a635854c4b --- /dev/null +++ b/components/external/SQLite-3.8.1/test/vtab_shared.test @@ -0,0 +1,233 @@ +# 2007 April 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file tests interactions between the virtual table and +# shared-schema functionality. +# +# $Id: vtab_shared.test,v 1.3 2009/07/24 17:58:53 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !vtab||!shared_cache { + finish_test + return +} + +db close +sqlite3_enable_shared_cache 1 +sqlite3 db test.db +sqlite3 db2 test.db + +do_test vtab_shared-1.1 { + register_echo_module [sqlite3_connection_pointer db] + execsql { + CREATE TABLE t0(a, b, c); + INSERT INTO t0 VALUES(1, 2, 3); + CREATE VIRTUAL TABLE t1 USING echo(t0); + } +} {} + +do_test vtab_shared-1.2 { + execsql { SELECT * FROM t1 } db +} {1 2 3} + +# Fails because the 'echo' module has not been registered with connection db2 +do_test vtab_shared-1.3 { + catchsql { SELECT * FROM t1 } db2 +} {1 {no such module: echo}} + +do_test vtab_shared-1.4 { + execsql { SELECT * FROM t0 } db2 +} {1 2 3} + +do_test vtab_shared-1.5 { + register_echo_module [sqlite3_connection_pointer db2] + execsql { SELECT * FROM t1 } db +} {1 2 3} + +# Works after the module is registered with db2 +do_test vtab_shared-1.6 { + execsql { SELECT * FROM t1 } db2 +} {1 2 3} + +# Set a write-lock on table t0 using connection [db]. Then try to read from +# virtual table t1 using [db2]. That this returns an SQLITE_LOCKED error +# shows that the correct sqlite3_vtab is being used. +# +do_test vtab_shared-1.8.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(4, 5, 6); + SELECT * FROM t1; + } +} {1 2 3 4 5 6} +do_test vtab_shared-1.8.2 { + catchsql { SELECT * FROM t1 } db2 +} {1 {database table is locked}} +do_test vtab_shared-1.8.3 { + catchsql { SELECT * FROM t0 } db2 +} {1 {database table is locked: t0}} +do_test vtab_shared-1.8.4 { + execsql { SELECT * FROM t0 } db +} {1 2 3 4 5 6} +do_test vtab_shared-1.8.5 { + execsql { COMMIT } db + execsql { SELECT * FROM t1 } db2 +} {1 2 3 4 5 6} + +# While a SELECT is active on virtual table t1 via connection [db], close +# [db2]. This causes the schema to be reset internally. Verify that this +# does not cause a problem. +# +foreach {iTest dbSelect dbClose} { + 1 db db2 + 2 db db2 + 3 db2 db +} { + do_test vtab_shared-1.9.$iTest { + set res [list] + $dbSelect eval { SELECT * FROM t1 } { + if {$a == 1} {$dbClose close} + lappend res $a $b $c + } + sqlite3 $dbClose test.db + register_echo_module [sqlite3_connection_pointer $dbClose] + set res + } {1 2 3 4 5 6} +} + +# Ensure that it is not possible for one connection to DROP a virtual +# table while a second connection is reading from the database. +# +do_test vtab_shared-1.10 { + db eval { SELECT * FROM t1 } { + set error [catchsql { DROP TABLE t1 } db2] + break + } + set error +} {1 {database table is locked: sqlite_master}} + +do_test vtab_shared-1.11 { +breakpoint + execsql { + CREATE VIRTUAL TABLE t2 USING echo(t0); + CREATE VIRTUAL TABLE t3 USING echo(t0); + } + execsql { SELECT * FROM t3 } db2 +} {1 2 3 4 5 6} + +ifcapable compound { + do_test vtab_shared-1.12.1 { + db close + execsql { + SELECT * FROM t1 UNION ALL + SELECT * FROM t2 UNION ALL + SELECT * FROM t3 + } db2 + } {1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6} + do_test vtab_shared-1.12.2 { + sqlite3 db test.db + register_echo_module [sqlite3_connection_pointer db] + execsql { + SELECT * FROM t1 UNION ALL + SELECT * FROM t2 UNION ALL + SELECT * FROM t3 + } db + } {1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6} +} + +# Try a rename or two. +# +ifcapable altertable { + do_test vtab_shared-1.13.1 { + execsql { ALTER TABLE t1 RENAME TO t4 } + execsql { SELECT * FROM t4 } db + } {1 2 3 4 5 6} + do_test vtab_shared-1.13.2 { + execsql { SELECT * FROM t4 } db2 + } {1 2 3 4 5 6} + do_test vtab_shared-1.13.3 { + execsql { ALTER TABLE t2 RENAME TO t5 } + execsql { SELECT * FROM t4 } db2 + } {1 2 3 4 5 6} +} + +# Try an UPDATE/INSERT/DELETE on a shared vtab as the first statement after a +# schema is loaded. +do_test vtab_shared_1.14.1 { + db2 close + sqlite3 db2 test.db + register_echo_module [sqlite3_connection_pointer db2] + execsql { SELECT * FROM t3 } +} {1 2 3 4 5 6} +do_test vtab_shared_1.14.2 { + execsql { + UPDATE t3 SET c = 'six' WHERE c = 6; + SELECT * FROM t3; + } db2 +} {1 2 3 4 5 six} +do_test vtab_shared_1.14.3 { + db2 close + sqlite3 db2 test.db + register_echo_module [sqlite3_connection_pointer db2] + execsql { SELECT * FROM t3 } +} {1 2 3 4 5 six} +do_test vtab_shared_1.14.4 { + execsql { + DELETE FROM t3 WHERE c = 'six'; + SELECT * FROM t3; + } db2 +} {1 2 3} +do_test vtab_shared_1.14.5 { + db2 close + sqlite3 db2 test.db + register_echo_module [sqlite3_connection_pointer db2] + execsql { SELECT * FROM t3 } +} {1 2 3} +do_test vtab_shared_1.14.6 { + execsql { + INSERT INTO t3 VALUES(4, 5, 6); + SELECT * FROM t3; + } db2 +} {1 2 3 4 5 6} + +do_test vtab_shared_1.15.1 { + db2 close + sqlite3 db2 test.db + register_echo_module [sqlite3_connection_pointer db2] + execsql { + UPDATE t3 SET c = 'six' WHERE c = 6; + SELECT * FROM t3; + } db2 +} {1 2 3 4 5 six} +do_test vtab_shared_1.15.2 { + db2 close + sqlite3 db2 test.db + register_echo_module [sqlite3_connection_pointer db2] + execsql { + DELETE FROM t3 WHERE c = 'six'; + SELECT * FROM t3; + } db2 +} {1 2 3} +do_test vtab_shared_1.15.3 { + db2 close + sqlite3 db2 test.db + register_echo_module [sqlite3_connection_pointer db2] + execsql { + INSERT INTO t3 VALUES(4, 5, 6); + SELECT * FROM t3; + } +} {1 2 3 4 5 6} + +db close +db2 close +sqlite3_enable_shared_cache 0 +finish_test diff --git a/components/external/SQLite-3.8.1/test/wal.test b/components/external/SQLite-3.8.1/test/wal.test new file mode 100644 index 0000000000000000000000000000000000000000..c8078a1b958ac6ac59d46a333b4e3b0c4596a854 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal.test @@ -0,0 +1,1578 @@ +# 2010 April 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl +source $testdir/wal_common.tcl + +set testprefix wal + +ifcapable !wal {finish_test ; return } + +proc reopen_db {} { + catch { db close } + forcedelete test.db test.db-wal test.db-wal-summary + sqlite3_wal db test.db +} + +set ::blobcnt 0 +proc blob {nByte} { + incr ::blobcnt + return [string range [string repeat "${::blobcnt}x" $nByte] 1 $nByte] +} + +proc sqlite3_wal {args} { + eval sqlite3 $args + [lindex $args 0] eval { PRAGMA auto_vacuum = 0 } + [lindex $args 0] eval { PRAGMA page_size = 1024 } + [lindex $args 0] eval { PRAGMA journal_mode = wal } + [lindex $args 0] eval { PRAGMA synchronous = normal } + [lindex $args 0] function blob blob +} + +proc log_deleted {logfile} { + return [expr [file exists $logfile]==0] +} + +# +# These are 'warm-body' tests used while developing the WAL code. They +# serve to prove that a few really simple cases work: +# +# wal-1.*: Read and write the database. +# wal-2.*: Test MVCC with one reader, one writer. +# wal-3.*: Test transaction rollback. +# wal-4.*: Test savepoint/statement rollback. +# wal-5.*: Test the temp database. +# wal-6.*: Test creating databases with different page sizes. +# +# +# +do_test wal-0.1 { + execsql { PRAGMA auto_vacuum = 0 } + execsql { PRAGMA synchronous = normal } + execsql { PRAGMA journal_mode = wal } +} {wal} +do_test wal-0.2 { + file size test.db +} {1024} + +do_test wal-1.0 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + } + list [file exists test.db-journal] \ + [file exists test.db-wal] \ + [file size test.db] +} {0 1 1024} +do_test wal-1.1 { + execsql COMMIT + list [file exists test.db-journal] [file exists test.db-wal] +} {0 1} +do_test wal-1.2 { + # There are now two pages in the log. + file size test.db-wal +} [wal_file_size 2 1024] + +do_test wal-1.3 { + execsql { SELECT * FROM sqlite_master } +} {table t1 t1 2 {CREATE TABLE t1(a, b)}} + +do_test wal-1.4 { + execsql { INSERT INTO t1 VALUES(1, 2) } + execsql { INSERT INTO t1 VALUES(3, 4) } + execsql { INSERT INTO t1 VALUES(5, 6) } + execsql { INSERT INTO t1 VALUES(7, 8) } + execsql { INSERT INTO t1 VALUES(9, 10) } +} {} + +do_test wal-1.5 { + execsql { SELECT * FROM t1 } +} {1 2 3 4 5 6 7 8 9 10} + +do_test wal-2.1 { + sqlite3_wal db2 ./test.db + execsql { BEGIN; SELECT * FROM t1 } db2 +} {1 2 3 4 5 6 7 8 9 10} + +do_test wal-2.2 { + execsql { INSERT INTO t1 VALUES(11, 12) } + execsql { SELECT * FROM t1 } +} {1 2 3 4 5 6 7 8 9 10 11 12} + +do_test wal-2.3 { + execsql { SELECT * FROM t1 } db2 +} {1 2 3 4 5 6 7 8 9 10} + +do_test wal-2.4 { + execsql { INSERT INTO t1 VALUES(13, 14) } + execsql { SELECT * FROM t1 } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14} + +do_test wal-2.5 { + execsql { SELECT * FROM t1 } db2 +} {1 2 3 4 5 6 7 8 9 10} + +do_test wal-2.6 { + execsql { COMMIT; SELECT * FROM t1 } db2 +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14} + +do_test wal-3.1 { + execsql { BEGIN; DELETE FROM t1 } + execsql { SELECT * FROM t1 } +} {} +do_test wal-3.2 { + execsql { SELECT * FROM t1 } db2 +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14} +do_test wal-3.3 { + execsql { ROLLBACK } + execsql { SELECT * FROM t1 } +} {1 2 3 4 5 6 7 8 9 10 11 12 13 14} +db2 close + +#------------------------------------------------------------------------- +# The following tests, wal-4.*, test that savepoints work with WAL +# databases. +# +do_test wal-4.1 { + execsql { + DELETE FROM t1; + BEGIN; + INSERT INTO t1 VALUES('a', 'b'); + SAVEPOINT sp; + INSERT INTO t1 VALUES('c', 'd'); + SELECT * FROM t1; + } +} {a b c d} +do_test wal-4.2 { + execsql { + ROLLBACK TO sp; + SELECT * FROM t1; + } +} {a b} +do_test wal-4.3 { + execsql { + COMMIT; + SELECT * FROM t1; + } +} {a b} + +do_test wal-4.4.1 { + db close + sqlite3 db test.db + db func blob blob + list [execsql { SELECT * FROM t1 }] [file size test.db-wal] +} {{a b} 0} +do_test wal-4.4.2 { + execsql { PRAGMA cache_size = 10 } + execsql { + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES(blob(400), blob(400)); + SAVEPOINT tr; + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 2 */ + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 4 */ + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 8 */ + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 16 */ + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 32 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 2 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 4 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 8 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 16 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 32 */ + SELECT count(*) FROM t2; + } +} {32} +do_test wal-4.4.3 { + execsql { ROLLBACK TO tr } +} {} +do_test wal-4.4.4 { + set logsize [file size test.db-wal] + execsql { + INSERT INTO t1 VALUES('x', 'y'); + RELEASE tr; + } + expr { $logsize == [file size test.db-wal] } +} {1} +do_test wal-4.4.5 { + execsql { SELECT count(*) FROM t2 } +} {1} +do_test wal-4.4.6 { + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + sqlite3 db2 test2.db + execsql { SELECT count(*) FROM t2 ; SELECT count(*) FROM t1 } db2 +} {1 2} +do_test wal-4.4.7 { + execsql { PRAGMA integrity_check } db2 +} {ok} +db2 close + +do_test wal-4.5.1 { + reopen_db + db func blob blob + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('a', 'b'); + } + sqlite3 db test.db + db func blob blob + list [execsql { SELECT * FROM t1 }] [file size test.db-wal] +} {{a b} 0} +do_test wal-4.5.2 { + execsql { PRAGMA cache_size = 10 } + execsql { + CREATE TABLE t2(a, b); + BEGIN; + INSERT INTO t2 VALUES(blob(400), blob(400)); + SAVEPOINT tr; + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 2 */ + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 4 */ + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 8 */ + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 16 */ + INSERT INTO t2 SELECT blob(400), blob(400) FROM t2; /* 32 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 2 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 4 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 8 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 16 */ + INSERT INTO t1 SELECT blob(400), blob(400) FROM t1; /* 32 */ + SELECT count(*) FROM t2; + } +} {32} +do_test wal-4.5.3 { + execsql { ROLLBACK TO tr } +} {} +do_test wal-4.5.4 { + set logsize [file size test.db-wal] + execsql { + INSERT INTO t1 VALUES('x', 'y'); + RELEASE tr; + COMMIT; + } + expr { $logsize == [file size test.db-wal] } +} {1} +do_test wal-4.5.5 { + execsql { SELECT count(*) FROM t2 ; SELECT count(*) FROM t1 } +} {1 2} +do_test wal-4.5.6 { + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + sqlite3 db2 test2.db + execsql { SELECT count(*) FROM t2 ; SELECT count(*) FROM t1 } db2 +} {1 2} +do_test wal-4.5.7 { + execsql { PRAGMA integrity_check } db2 +} {ok} +db2 close + +do_test wal-4.6.1 { + execsql { + DELETE FROM t2; + PRAGMA wal_checkpoint; + BEGIN; + INSERT INTO t2 VALUES('w', 'x'); + SAVEPOINT save; + INSERT INTO t2 VALUES('y', 'z'); + ROLLBACK TO save; + COMMIT; + } + execsql { SELECT * FROM t2 } +} {w x} + + +reopen_db +do_test wal-5.1 { + execsql { + CREATE TEMP TABLE t2(a, b); + INSERT INTO t2 VALUES(1, 2); + } +} {} +do_test wal-5.2 { + execsql { + BEGIN; + INSERT INTO t2 VALUES(3, 4); + SELECT * FROM t2; + } +} {1 2 3 4} +do_test wal-5.3 { + execsql { + ROLLBACK; + SELECT * FROM t2; + } +} {1 2} +do_test wal-5.4 { + execsql { + CREATE TEMP TABLE t3(x UNIQUE); + BEGIN; + INSERT INTO t2 VALUES(3, 4); + INSERT INTO t3 VALUES('abc'); + } + catchsql { INSERT INTO t3 VALUES('abc') } +} {1 {column x is not unique}} +do_test wal-5.5 { + execsql { + COMMIT; + SELECT * FROM t2; + } +} {1 2 3 4} +db close + +foreach sector {512 4096} { + sqlite3_simulate_device -sectorsize $sector + foreach pgsz {512 1024 2048 4096} { + forcedelete test.db test.db-wal + do_test wal-6.$sector.$pgsz.1 { + sqlite3 db test.db -vfs devsym + execsql " + PRAGMA page_size = $pgsz; + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = wal; + " + execsql " + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + " + db close + file size test.db + } [expr $pgsz*2] + + do_test wal-6.$sector.$pgsz.2 { + log_deleted test.db-wal + } {1} + } +} + +do_test wal-7.1 { + forcedelete test.db test.db-wal + sqlite3_wal db test.db + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } + list [file size test.db] [file size test.db-wal] +} [list 1024 [wal_file_size 3 1024]] +do_test wal-7.2 { + execsql { PRAGMA wal_checkpoint } + list [file size test.db] [file size test.db-wal] +} [list 2048 [wal_file_size 3 1024]] + +# Execute some transactions in auto-vacuum mode to test database file +# truncation. +# +do_test wal-8.1 { + reopen_db + catch { db close } + forcedelete test.db test.db-wal + + sqlite3 db test.db + db function blob blob + execsql { + PRAGMA auto_vacuum = 1; + PRAGMA journal_mode = wal; + PRAGMA auto_vacuum; + } +} {wal 1} +do_test wal-8.2 { + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(blob(900)); + INSERT INTO t1 VALUES(blob(900)); + INSERT INTO t1 SELECT blob(900) FROM t1; /* 4 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 8 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 16 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 32 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 64 */ + PRAGMA wal_checkpoint; + } + file size test.db +} [expr 68*1024] +do_test wal-8.3 { + execsql { + DELETE FROM t1 WHERE rowid<54; + PRAGMA wal_checkpoint; + } + file size test.db +} [expr 14*1024] + +# Run some "warm-body" tests to ensure that log-summary files with more +# than 256 entries (log summaries that contain index blocks) work Ok. +# +do_test wal-9.1 { + reopen_db + execsql { + PRAGMA cache_size=2000; + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(blob(900)); + INSERT INTO t1 VALUES(blob(900)); + INSERT INTO t1 SELECT blob(900) FROM t1; /* 4 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 8 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 16 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 32 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 64 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 128 */ + INSERT INTO t1 SELECT blob(900) FROM t1; /* 256 */ + } + file size test.db +} 1024 +do_test wal-9.2 { + sqlite3_wal db2 test.db + execsql {PRAGMA integrity_check } db2 +} {ok} + +do_test wal-9.3 { + forcedelete test2.db test2.db-wal + copy_file test.db test2.db + copy_file test.db-wal test2.db-wal + sqlite3_wal db3 test2.db + execsql {PRAGMA integrity_check } db3 +} {ok} +db3 close + +do_test wal-9.4 { + execsql { PRAGMA wal_checkpoint } + db2 close + sqlite3_wal db2 test.db + execsql {PRAGMA integrity_check } db2 +} {ok} + +foreach handle {db db2 db3} { catch { $handle close } } +unset handle + +#------------------------------------------------------------------------- +# The following block of tests - wal-10.* - test that the WAL locking +# scheme works in simple cases. This block of tests is run twice. Once +# using multiple connections in the address space of the current process, +# and once with all connections except one running in external processes. +# +do_multiclient_test tn { + + # Initialize the database schema and contents. + # + do_test wal-10.$tn.1 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = wal; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + SELECT * FROM t1; + } + } {wal 1 2} + + # Open a transaction and write to the database using [db]. Check that [db2] + # is still able to read the snapshot before the transaction was opened. + # + do_test wal-10.$tn.2 { + execsql { BEGIN; INSERT INTO t1 VALUES(3, 4); } + sql2 {SELECT * FROM t1} + } {1 2} + + # Have [db] commit the transaction. Check that [db2] is now seeing the + # new, updated snapshot. + # + do_test wal-10.$tn.3 { + execsql { COMMIT } + sql2 {SELECT * FROM t1} + } {1 2 3 4} + + # Have [db2] open a read transaction. Then write to the db via [db]. Check + # that [db2] is still seeing the original snapshot. Then read with [db3]. + # [db3] should see the newly committed data. + # + do_test wal-10.$tn.4 { + sql2 { BEGIN ; SELECT * FROM t1} + } {1 2 3 4} + do_test wal-10.$tn.5 { + execsql { INSERT INTO t1 VALUES(5, 6); } + sql2 {SELECT * FROM t1} + } {1 2 3 4} + do_test wal-10.$tn.6 { + sql3 {SELECT * FROM t1} + } {1 2 3 4 5 6} + do_test wal-10.$tn.7 { + sql2 COMMIT + } {} + + # Have [db2] open a write transaction. Then attempt to write to the + # database via [db]. This should fail (writer lock cannot be obtained). + # + # Then open a read-transaction with [db]. Commit the [db2] transaction + # to disk. Verify that [db] still cannot write to the database (because + # it is reading an old snapshot). + # + # Close the current [db] transaction. Open a new one. [db] can now write + # to the database (as it is not locked and [db] is reading the latest + # snapshot). + # + do_test wal-10.$tn.7 { + sql2 { BEGIN; INSERT INTO t1 VALUES(7, 8) ; } + catchsql { INSERT INTO t1 VALUES(9, 10) } + } {1 {database is locked}} + do_test wal-10.$tn.8 { + execsql { BEGIN ; SELECT * FROM t1 } + } {1 2 3 4 5 6} + do_test wal-10.$tn.9 { + sql2 COMMIT + catchsql { INSERT INTO t1 VALUES(9, 10) } + } {1 {database is locked}} + do_test wal-10.$tn.10 { + execsql { COMMIT } + execsql { BEGIN } + execsql { INSERT INTO t1 VALUES(9, 10) } + execsql { COMMIT } + execsql { SELECT * FROM t1 } + } {1 2 3 4 5 6 7 8 9 10} + + # Open a read transaction with [db2]. Check that this prevents [db] from + # checkpointing the database. But not from writing to it. + # + do_test wal-10.$tn.11 { + sql2 { BEGIN; SELECT * FROM t1 } + } {1 2 3 4 5 6 7 8 9 10} + do_test wal-10.$tn.12 { + catchsql { PRAGMA wal_checkpoint } + } {0 {0 7 7}} ;# Reader no longer block checkpoints + do_test wal-10.$tn.13 { + execsql { INSERT INTO t1 VALUES(11, 12) } + sql2 {SELECT * FROM t1} + } {1 2 3 4 5 6 7 8 9 10} + + # Writers do not block checkpoints any more either. + # + do_test wal-10.$tn.14 { + catchsql { PRAGMA wal_checkpoint } + } {0 {0 8 7}} + + # The following series of test cases used to verify another blocking + # case in WAL - a case which no longer blocks. + # + do_test wal-10.$tn.15 { + sql2 { COMMIT; BEGIN; SELECT * FROM t1; } + } {1 2 3 4 5 6 7 8 9 10 11 12} + do_test wal-10.$tn.16 { + catchsql { PRAGMA wal_checkpoint } + } {0 {0 8 8}} + do_test wal-10.$tn.17 { + execsql { PRAGMA wal_checkpoint } + } {0 8 8} + do_test wal-10.$tn.18 { + sql3 { BEGIN; SELECT * FROM t1 } + } {1 2 3 4 5 6 7 8 9 10 11 12} + do_test wal-10.$tn.19 { + catchsql { INSERT INTO t1 VALUES(13, 14) } + } {0 {}} + do_test wal-10.$tn.20 { + execsql { SELECT * FROM t1 } + } {1 2 3 4 5 6 7 8 9 10 11 12 13 14} + do_test wal-10.$tn.21 { + sql3 COMMIT + sql2 COMMIT + } {} + do_test wal-10.$tn.22 { + execsql { SELECT * FROM t1 } + } {1 2 3 4 5 6 7 8 9 10 11 12 13 14} + + # Another series of tests that used to demonstrate blocking behavior + # but which now work. + # + do_test wal-10.$tn.23 { + execsql { PRAGMA wal_checkpoint } + } {0 9 9} + do_test wal-10.$tn.24 { + sql2 { BEGIN; SELECT * FROM t1; } + } {1 2 3 4 5 6 7 8 9 10 11 12 13 14} + do_test wal-10.$tn.25 { + execsql { PRAGMA wal_checkpoint } + } {0 9 9} + do_test wal-10.$tn.26 { + catchsql { INSERT INTO t1 VALUES(15, 16) } + } {0 {}} + do_test wal-10.$tn.27 { + sql3 { INSERT INTO t1 VALUES(17, 18) } + } {} + do_test wal-10.$tn.28 { + code3 { + set ::STMT [sqlite3_prepare db3 "SELECT * FROM t1" -1 TAIL] + sqlite3_step $::STMT + } + execsql { SELECT * FROM t1 } + } {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18} + do_test wal-10.$tn.29 { + execsql { INSERT INTO t1 VALUES(19, 20) } + catchsql { PRAGMA wal_checkpoint } + } {0 {0 3 0}} + do_test wal-10.$tn.30 { + code3 { sqlite3_finalize $::STMT } + execsql { PRAGMA wal_checkpoint } + } {0 3 0} + + # At one point, if a reader failed to upgrade to a writer because it + # was reading an old snapshot, the write-locks were not being released. + # Test that this bug has been fixed. + # + do_test wal-10.$tn.31 { + sql2 COMMIT + execsql { BEGIN ; SELECT * FROM t1 } + sql2 { INSERT INTO t1 VALUES(21, 22) } + catchsql { INSERT INTO t1 VALUES(23, 24) } + } {1 {database is locked}} + do_test wal-10.$tn.32 { + # This statement would fail when the bug was present. + sql2 { INSERT INTO t1 VALUES(23, 24) } + } {} + do_test wal-10.$tn.33 { + execsql { SELECT * FROM t1 ; COMMIT } + } {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20} + do_test wal-10.$tn.34 { + execsql { SELECT * FROM t1 } + } {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24} + + # Test that if a checkpointer cannot obtain the required locks, it + # releases all locks before returning a busy error. + # + do_test wal-10.$tn.35 { + execsql { + DELETE FROM t1; + INSERT INTO t1 VALUES('a', 'b'); + INSERT INTO t1 VALUES('c', 'd'); + } + sql2 { + BEGIN; + SELECT * FROM t1; + } + } {a b c d} + do_test wal-10.$tn.36 { + catchsql { PRAGMA wal_checkpoint } + } {0 {0 8 8}} + do_test wal-10.$tn.36 { + sql3 { INSERT INTO t1 VALUES('e', 'f') } + sql2 { SELECT * FROM t1 } + } {a b c d} + do_test wal-10.$tn.37 { + sql2 COMMIT + execsql { PRAGMA wal_checkpoint } + } {0 9 9} +} + +#------------------------------------------------------------------------- +# This block of tests, wal-11.*, test that nothing goes terribly wrong +# if frames must be written to the log file before a transaction is +# committed (in order to free up memory). +# +do_test wal-11.1 { + reopen_db + execsql { + PRAGMA cache_size = 10; + PRAGMA page_size = 1024; + CREATE TABLE t1(x PRIMARY KEY); + } + list [expr [file size test.db]/1024] [expr [file size test.db-wal]/1044] +} {1 3} +do_test wal-11.2 { + execsql { PRAGMA wal_checkpoint } + list [expr [file size test.db]/1024] [file size test.db-wal] +} [list 3 [wal_file_size 3 1024]] +do_test wal-11.3 { + execsql { INSERT INTO t1 VALUES( blob(900) ) } + list [expr [file size test.db]/1024] [file size test.db-wal] +} [list 3 [wal_file_size 4 1024]] + +do_test wal-11.4 { + execsql { + BEGIN; + INSERT INTO t1 SELECT blob(900) FROM t1; -- 2 + INSERT INTO t1 SELECT blob(900) FROM t1; -- 4 + INSERT INTO t1 SELECT blob(900) FROM t1; -- 8 + INSERT INTO t1 SELECT blob(900) FROM t1; -- 16 + } + list [expr [file size test.db]/1024] [file size test.db-wal] +} [list 3 [wal_file_size 32 1024]] +do_test wal-11.5 { + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check; + } +} {16 ok} +do_test wal-11.6 { + execsql COMMIT + list [expr [file size test.db]/1024] [file size test.db-wal] +} [list 3 [wal_file_size 41 1024]] +do_test wal-11.7 { + execsql { + SELECT count(*) FROM t1; + PRAGMA integrity_check; + } +} {16 ok} +do_test wal-11.8 { + execsql { PRAGMA wal_checkpoint } + list [expr [file size test.db]/1024] [file size test.db-wal] +} [list 37 [wal_file_size 41 1024]] +do_test wal-11.9 { + db close + list [expr [file size test.db]/1024] [log_deleted test.db-wal] +} {37 1} +sqlite3_wal db test.db +set nWal 39 +if {[permutation]!="mmap"} {set nWal 37} +ifcapable !mmap {set nWal 37} +do_test wal-11.10 { + execsql { + PRAGMA cache_size = 10; + BEGIN; + INSERT INTO t1 SELECT blob(900) FROM t1; -- 32 + SELECT count(*) FROM t1; + } + list [expr [file size test.db]/1024] [file size test.db-wal] +} [list 37 [wal_file_size $nWal 1024]] +do_test wal-11.11 { + execsql { + SELECT count(*) FROM t1; + ROLLBACK; + SELECT count(*) FROM t1; + } +} {32 16} +do_test wal-11.12 { + list [expr [file size test.db]/1024] [file size test.db-wal] +} [list 37 [wal_file_size $nWal 1024]] +do_test wal-11.13 { + execsql { + INSERT INTO t1 VALUES( blob(900) ); + SELECT count(*) FROM t1; + PRAGMA integrity_check; + } +} {17 ok} +do_test wal-11.14 { + list [expr [file size test.db]/1024] [file size test.db-wal] +} [list 37 [wal_file_size $nWal 1024]] + + +#------------------------------------------------------------------------- +# This block of tests, wal-12.*, tests the fix for a problem that +# could occur if a log that is a prefix of an older log is written +# into a reused log file. +# +reopen_db +do_test wal-12.1 { + execsql { + PRAGMA page_size = 1024; + CREATE TABLE t1(x, y); + CREATE TABLE t2(x, y); + INSERT INTO t1 VALUES('A', 1); + } + list [expr [file size test.db]/1024] [file size test.db-wal] +} [list 1 [wal_file_size 5 1024]] +do_test wal-12.2 { + db close + sqlite3 db test.db + execsql { + PRAGMA synchronous = normal; + UPDATE t1 SET y = 0 WHERE x = 'A'; + } + list [expr [file size test.db]/1024] [expr [file size test.db-wal]/1044] +} {3 1} +do_test wal-12.3 { + execsql { INSERT INTO t2 VALUES('B', 1) } + list [expr [file size test.db]/1024] [expr [file size test.db-wal]/1044] +} {3 2} +do_test wal-12.4 { + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + sqlite3_wal db2 test2.db + execsql { SELECT * FROM t2 } db2 +} {B 1} +db2 close +do_test wal-12.5 { + execsql { + PRAGMA wal_checkpoint; + UPDATE t2 SET y = 2 WHERE x = 'B'; + PRAGMA wal_checkpoint; + UPDATE t1 SET y = 1 WHERE x = 'A'; + PRAGMA wal_checkpoint; + UPDATE t1 SET y = 0 WHERE x = 'A'; + } + execsql { SELECT * FROM t2 } +} {B 2} +do_test wal-12.6 { + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + sqlite3_wal db2 test2.db + execsql { SELECT * FROM t2 } db2 +} {B 2} +db2 close +db close + +#------------------------------------------------------------------------- +# Test large log summaries. +# +# In this case "large" usually means a log file that requires a wal-index +# mapping larger than 64KB (the default initial allocation). A 64KB wal-index +# is large enough for a log file that contains approximately 13100 frames. +# So the following tests create logs containing at least this many frames. +# +# wal-13.1.*: This test case creates a very large log file within the +# file-system (around 200MB). The log file does not contain +# any valid frames. Test that the database file can still be +# opened and queried, and that the invalid log file causes no +# problems. +# +# wal-13.2.*: Test that a process may create a large log file and query +# the database (including the log file that it itself created). +# +# wal-13.3.*: Test that if a very large log file is created, and then a +# second connection is opened on the database file, it is possible +# to query the database (and the very large log) using the +# second connection. +# +# wal-13.4.*: Same test as wal-13.3.*. Except in this case the second +# connection is opened by an external process. +# +do_test wal-13.1.1 { + list [file exists test.db] [file exists test.db-wal] +} {1 0} +do_test wal-13.1.2 { + set fd [open test.db-wal w] + seek $fd [expr 200*1024*1024] + puts $fd "" + close $fd + sqlite3 db test.db + execsql { SELECT * FROM t2 } +} {B 2} +breakpoint +do_test wal-13.1.3 { + db close + file exists test.db-wal +} {0} + +do_test wal-13.2.1 { + sqlite3 db test.db + execsql { SELECT count(*) FROM t2 } +} {1} +do_test wal-13.2.2 { + db function blob blob + for {set i 0} {$i < 16} {incr i} { + execsql { INSERT INTO t2 SELECT blob(400), blob(400) FROM t2 } + } + execsql { SELECT count(*) FROM t2 } +} [expr int(pow(2, 16))] +do_test wal-13.2.3 { + expr [file size test.db-wal] > [wal_file_size 33000 1024] +} 1 + +do_multiclient_test tn { + incr tn 2 + + do_test wal-13.$tn.0 { + sql1 { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(x); + INSERT INTO t1 SELECT randomblob(800); + } + sql1 { SELECT count(*) FROM t1 } + } {1} + + for {set ii 1} {$ii<16} {incr ii} { + do_test wal-13.$tn.$ii.a { + sql2 { INSERT INTO t1 SELECT randomblob(800) FROM t1 } + sql2 { SELECT count(*) FROM t1 } + } [expr (1<<$ii)] + do_test wal-13.$tn.$ii.b { + sql1 { SELECT count(*) FROM t1 } + } [expr (1<<$ii)] + do_test wal-13.$tn.$ii.c { + sql1 { SELECT count(*) FROM t1 } + } [expr (1<<$ii)] + do_test wal-13.$tn.$ii.d { + sql1 { PRAGMA integrity_check } + } {ok} + } +} + +#------------------------------------------------------------------------- +# Check a fun corruption case has been fixed. +# +# The problem was that after performing a checkpoint using a connection +# that had an out-of-date pager-cache, the next time the connection was +# used it did not realize the cache was out-of-date and proceeded to +# operate with an inconsistent cache. Leading to corruption. +# +catch { db close } +catch { db2 close } +catch { db3 close } +forcedelete test.db test.db-wal +sqlite3 db test.db +sqlite3 db2 test.db +do_test wal-14 { + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(randomblob(10), randomblob(100)); + INSERT INTO t1 SELECT randomblob(10), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(10), randomblob(100) FROM t1; + INSERT INTO t1 SELECT randomblob(10), randomblob(100) FROM t1; + } + + db2 eval { + INSERT INTO t1 SELECT randomblob(10), randomblob(100); + INSERT INTO t1 SELECT randomblob(10), randomblob(100); + INSERT INTO t1 SELECT randomblob(10), randomblob(100); + INSERT INTO t1 SELECT randomblob(10), randomblob(100); + } + + # After executing the "PRAGMA wal_checkpoint", connection [db] was being + # left with an inconsistent cache. Running the CREATE INDEX statement + # in this state led to database corruption. + catchsql { + PRAGMA wal_checkpoint; + CREATE INDEX i1 on t1(b); + } + + db2 eval { PRAGMA integrity_check } +} {ok} + +catch { db close } +catch { db2 close } + +#------------------------------------------------------------------------- +# The following block of tests - wal-15.* - focus on testing the +# implementation of the sqlite3_wal_checkpoint() interface. +# +forcedelete test.db test.db-wal +sqlite3 db test.db +do_test wal-15.1 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + } + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } +} {} + +# Test that an error is returned if the database name is not recognized +# +do_test wal-15.2.1 { + sqlite3_wal_checkpoint db aux +} {SQLITE_ERROR} +do_test wal-15.2.2 { + sqlite3_errcode db +} {SQLITE_ERROR} +do_test wal-15.2.3 { + sqlite3_errmsg db +} {unknown database: aux} + +# Test that an error is returned if an attempt is made to checkpoint +# if a transaction is open on the database. +# +do_test wal-15.3.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(3, 4); + } + sqlite3_wal_checkpoint db main +} {SQLITE_LOCKED} +do_test wal-15.3.2 { + sqlite3_errcode db +} {SQLITE_LOCKED} +do_test wal-15.3.3 { + sqlite3_errmsg db +} {database table is locked} + +# Earlier versions returned an error is returned if the db cannot be +# checkpointed because of locks held by another connection. Check that +# this is no longer the case. +# +sqlite3 db2 test.db +do_test wal-15.4.1 { + execsql { + BEGIN; + SELECT * FROM t1; + } db2 +} {1 2} +do_test wal-15.4.2 { + execsql { COMMIT } + sqlite3_wal_checkpoint db +} {SQLITE_OK} +do_test wal-15.4.3 { + sqlite3_errmsg db +} {not an error} + +# After [db2] drops its lock, [db] may checkpoint the db. +# +do_test wal-15.4.4 { + execsql { COMMIT } db2 + sqlite3_wal_checkpoint db +} {SQLITE_OK} +do_test wal-15.4.5 { + sqlite3_errmsg db +} {not an error} +do_test wal-15.4.6 { + file size test.db +} [expr 1024*2] + +catch { db2 close } +catch { db close } + +#------------------------------------------------------------------------- +# The following block of tests - wal-16.* - test that if a NULL pointer or +# an empty string is passed as the second argument of the wal_checkpoint() +# API, an attempt is made to checkpoint all attached databases. +# +foreach {tn ckpt_cmd ckpt_res ckpt_main ckpt_aux} { + 1 {sqlite3_wal_checkpoint db} SQLITE_OK 1 1 + 2 {sqlite3_wal_checkpoint db ""} SQLITE_OK 1 1 + 3 {db eval "PRAGMA wal_checkpoint"} {0 10 10} 1 1 + + 4 {sqlite3_wal_checkpoint db main} SQLITE_OK 1 0 + 5 {sqlite3_wal_checkpoint db aux} SQLITE_OK 0 1 + 6 {sqlite3_wal_checkpoint db temp} SQLITE_OK 0 0 + 7 {db eval "PRAGMA main.wal_checkpoint"} {0 10 10} 1 0 + 8 {db eval "PRAGMA aux.wal_checkpoint"} {0 13 13} 0 1 + 9 {db eval "PRAGMA temp.wal_checkpoint"} {0 -1 -1} 0 0 +} { + do_test wal-16.$tn.1 { + forcedelete test2.db test2.db-wal test2.db-journal + forcedelete test.db test.db-wal test.db-journal + + sqlite3 db test.db + execsql { + ATTACH 'test2.db' AS aux; + PRAGMA main.auto_vacuum = 0; + PRAGMA aux.auto_vacuum = 0; + PRAGMA main.journal_mode = WAL; + PRAGMA aux.journal_mode = WAL; + PRAGMA main.synchronous = NORMAL; + PRAGMA aux.synchronous = NORMAL; + } + } {wal wal} + + do_test wal-16.$tn.2 { + execsql { + CREATE TABLE main.t1(a, b, PRIMARY KEY(a, b)); + CREATE TABLE aux.t2(a, b, PRIMARY KEY(a, b)); + + INSERT INTO t2 VALUES(1, randomblob(1000)); + INSERT INTO t2 VALUES(2, randomblob(1000)); + INSERT INTO t1 SELECT * FROM t2; + } + + list [file size test.db] [file size test.db-wal] + } [list [expr 1*1024] [wal_file_size 10 1024]] + do_test wal-16.$tn.3 { + list [file size test2.db] [file size test2.db-wal] + } [list [expr 1*1024] [wal_file_size 13 1024]] + + do_test wal-16.$tn.4 [list eval $ckpt_cmd] $ckpt_res + + do_test wal-16.$tn.5 { + list [file size test.db] [file size test.db-wal] + } [list [expr ($ckpt_main ? 7 : 1)*1024] [wal_file_size 10 1024]] + + do_test wal-16.$tn.6 { + list [file size test2.db] [file size test2.db-wal] + } [list [expr ($ckpt_aux ? 7 : 1)*1024] [wal_file_size 13 1024]] + + catch { db close } +} + +#------------------------------------------------------------------------- +# The following tests - wal-17.* - attempt to verify that the correct +# number of "padding" frames are appended to the log file when a transaction +# is committed in synchronous=FULL mode. +# +# Do this by creating a database that uses 512 byte pages. Then writing +# a transaction that modifies 171 pages. In synchronous=NORMAL mode, this +# produces a log file of: +# +# 32 + (24+512)*171 = 90312 bytes. +# +# Slightly larger than 11*8192 = 90112 bytes. +# +# Run the test using various different sector-sizes. In each case, the +# WAL code should write the 90300 bytes of log file containing the +# transaction, then append as may frames as are required to extend the +# log file so that no part of the next transaction will be written into +# a disk-sector used by transaction just committed. +# +set old_pending_byte [sqlite3_test_control_pending_byte 0x10000000] +catch { db close } +foreach {tn sectorsize logsize} " + 1 128 [wal_file_size 172 512] + 2 256 [wal_file_size 172 512] + 3 512 [wal_file_size 172 512] + 4 1024 [wal_file_size 172 512] + 5 2048 [wal_file_size 172 512] + 6 4096 [wal_file_size 176 512] + 7 8192 [wal_file_size 184 512] +" { + forcedelete test.db test.db-wal test.db-journal + sqlite3_simulate_device -sectorsize $sectorsize + sqlite3 db test.db -vfs devsym + + do_test wal-17.$tn.1 { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA page_size = 512; + PRAGMA cache_size = -2000; + PRAGMA journal_mode = WAL; + PRAGMA synchronous = FULL; + } + execsql { + BEGIN; + CREATE TABLE t(x); + } + for {set i 0} {$i<166} {incr i} { + execsql { INSERT INTO t VALUES(randomblob(400)) } + } + execsql COMMIT + + file size test.db-wal + } $logsize + + do_test wal-17.$tn.2 { + file size test.db + } 512 + + do_test wal-17.$tn.3 { + db close + file size test.db + } [expr 512*171] +} +sqlite3_test_control_pending_byte $old_pending_byte + +#------------------------------------------------------------------------- +# This test - wal-18.* - verifies a couple of specific conditions that +# may be encountered while recovering a log file are handled correctly: +# +# wal-18.1.* When the first 32-bits of a frame checksum is correct but +# the second 32-bits are false, and +# +# wal-18.2.* When the page-size field that occurs at the start of a log +# file is a power of 2 greater than 16384 or smaller than 512. +# +forcedelete test.db test.db-wal test.db-journal +do_test wal-18.0 { + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + PRAGMA synchronous = OFF; + + CREATE TABLE t1(a, b, UNIQUE(a, b)); + INSERT INTO t1 VALUES(0, 0); + PRAGMA wal_checkpoint; + + INSERT INTO t1 VALUES(1, 2); -- frames 1 and 2 + INSERT INTO t1 VALUES(3, 4); -- frames 3 and 4 + INSERT INTO t1 VALUES(5, 6); -- frames 5 and 6 + } + + forcecopy test.db testX.db + forcecopy test.db-wal testX.db-wal + db close + list [file size testX.db] [file size testX.db-wal] +} [list [expr 3*1024] [wal_file_size 6 1024]] + +unset -nocomplain nFrame result +foreach {nFrame result} { + 0 {0 0} + 1 {0 0} + 2 {0 0 1 2} + 3 {0 0 1 2} + 4 {0 0 1 2 3 4} + 5 {0 0 1 2 3 4} + 6 {0 0 1 2 3 4 5 6} +} { + do_test wal-18.1.$nFrame { + forcecopy testX.db test.db + forcecopy testX.db-wal test.db-wal + + hexio_write test.db-wal [expr 24 + $nFrame*(24+1024) + 20] 00000000 + + sqlite3 db test.db + execsql { + SELECT * FROM t1; + PRAGMA integrity_check; + } + } [concat $result ok] + db close +} + +proc randomblob {pgsz} { + sqlite3 rbdb :memory: + set blob [rbdb one {SELECT randomblob($pgsz)}] + rbdb close + set blob +} + +proc logcksum {ckv1 ckv2 blob} { + upvar $ckv1 c1 + upvar $ckv2 c2 + + # Since the magic number at the start of the -wal file header is + # 931071618 that indicates that the content should always be read as + # little-endian. + # + set scanpattern i* + + binary scan $blob $scanpattern values + foreach {v1 v2} $values { + set c1 [expr {($c1 + $v1 + $c2)&0xFFFFFFFF}] + set c2 [expr {($c2 + $v2 + $c1)&0xFFFFFFFF}] + } +} + +forcecopy test.db testX.db +foreach {tn pgsz works} { + 1 128 0 + 2 256 0 + 3 512 1 + 4 1024 1 + 5 2048 1 + 6 4096 1 + 7 8192 1 + 8 16384 1 + 9 32768 1 + 10 65536 1 + 11 131072 0 + 11 1016 0 +} { + + if {$::SQLITE_MAX_PAGE_SIZE < $pgsz} { + set works 0 + } + + for {set pg 1} {$pg <= 3} {incr pg} { + forcecopy testX.db test.db + forcedelete test.db-wal + + # Check that the database now exists and consists of three pages. And + # that there is no associated wal file. + # + do_test wal-18.2.$tn.$pg.1 { file exists test.db-wal } 0 + do_test wal-18.2.$tn.$pg.2 { file exists test.db } 1 + do_test wal-18.2.$tn.$pg.3 { file size test.db } [expr 1024*3] + + do_test wal-18.2.$tn.$pg.4 { + + # Create a wal file that contains a single frame (database page + # number $pg) with the commit flag set. The frame checksum is + # correct, but the contents of the database page are corrupt. + # + # The page-size in the log file header is set to $pgsz. If the + # WAL code considers $pgsz to be a valid SQLite database file page-size, + # the database will be corrupt (because the garbage frame contents + # will be treated as valid content). If $pgsz is invalid (too small + # or too large), the db will not be corrupt as the log file will + # be ignored. + # + set walhdr [binary format IIIIII 931071618 3007000 $pgsz 1234 22 23] + set framebody [randomblob $pgsz] + set framehdr [binary format IIII $pg 5 22 23] + set c1 0 + set c2 0 + logcksum c1 c2 $walhdr + + append walhdr [binary format II $c1 $c2] + logcksum c1 c2 [string range $framehdr 0 7] + logcksum c1 c2 $framebody + set framehdr [binary format IIIIII $pg 5 22 23 $c1 $c2] + + set fd [open test.db-wal w] + fconfigure $fd -encoding binary -translation binary + puts -nonewline $fd $walhdr + puts -nonewline $fd $framehdr + puts -nonewline $fd $framebody + close $fd + + file size test.db-wal + } [wal_file_size 1 $pgsz] + + do_test wal-18.2.$tn.$pg.5 { + sqlite3 db test.db + set rc [catch { db one {PRAGMA integrity_check} } msg] + expr { $rc!=0 || $msg!="ok" } + } $works + + db close + } +} + +#------------------------------------------------------------------------- +# The following test - wal-19.* - fixes a bug that was present during +# development. +# +# When a database connection in WAL mode is closed, it attempts an +# EXCLUSIVE lock on the database file. If the lock is obtained, the +# connection knows that it is the last connection to disconnect from +# the database, so it runs a checkpoint operation. The bug was that +# the connection was not updating its private copy of the wal-index +# header before doing so, meaning that it could checkpoint an old +# snapshot. +# +do_test wal-19.1 { + forcedelete test.db test.db-wal test.db-journal + sqlite3 db test.db + sqlite3 db2 test.db + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + } + execsql { SELECT * FROM t1 } db2 +} {1 2 3 4} +do_test wal-19.2 { + execsql { + INSERT INTO t1 VALUES(5, 6); + SELECT * FROM t1; + } +} {1 2 3 4 5 6} +do_test wal-19.3 { + db close + db2 close + file exists test.db-wal +} {0} +do_test wal-19.4 { + # When the bug was present, the following was returning {1 2 3 4} only, + # as [db2] had an out-of-date copy of the wal-index header when it was + # closed. + # + sqlite3 db test.db + execsql { SELECT * FROM t1 } +} {1 2 3 4 5 6} + +#------------------------------------------------------------------------- +# This test - wal-20.* - uses two connections. One in this process and +# the other in an external process. The procedure is: +# +# 1. Using connection 1, create the database schema. +# +# 2. Using connection 2 (in an external process), add so much +# data to the database without checkpointing that a wal-index +# larger than 64KB is required. +# +# 3. Using connection 1, checkpoint the database. Make sure all +# the data is present and the database is not corrupt. +# +# At one point, SQLite was failing to grow the mapping of the wal-index +# file in step 3 and the checkpoint was corrupting the database file. +# +do_test wal-20.1 { + catch {db close} + forcedelete test.db test.db-wal test.db-journal + sqlite3 db test.db + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(900)); + SELECT count(*) FROM t1; + } +} {wal 1} +do_test wal-20.2 { + set ::buddy [launch_testfixture] + testfixture $::buddy { + sqlite3 db test.db + db transaction { db eval { + PRAGMA wal_autocheckpoint = 0; + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 2 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 4 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 8 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 16 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 32 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 64 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 128 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 256 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 512 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 1024 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 2048 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 4096 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 8192 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 16384 */ + } } + } +} {0} +do_test wal-20.3 { + close $::buddy + execsql { PRAGMA wal_checkpoint } + execsql { SELECT count(*) FROM t1 } +} {16384} +do_test wal-20.4 { + db close + sqlite3 db test.db + execsql { SELECT count(*) FROM t1 } +} {16384} +integrity_check wal-20.5 + +catch { db2 close } +catch { db close } + +do_test wal-21.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t1 VALUES(5, 6); + INSERT INTO t1 VALUES(7, 8); + INSERT INTO t1 VALUES(9, 10); + INSERT INTO t1 VALUES(11, 12); + } +} {wal} +do_test wal-21.2 { + execsql { + PRAGMA cache_size = 10; + PRAGMA wal_checkpoint; + BEGIN; + SAVEPOINT s; + INSERT INTO t1 SELECT randomblob(900), randomblob(900) FROM t1; + ROLLBACK TO s; + COMMIT; + } + execsql { SELECT * FROM t1 } +} {1 2 3 4 5 6 7 8 9 10 11 12} +do_test wal-21.3 { + execsql { PRAGMA integrity_check } +} {ok} + +#------------------------------------------------------------------------- +# Test reading and writing of databases with different page-sizes. +# +foreach pgsz {512 1024 2048 4096 8192 16384 32768 65536} { + do_multiclient_test tn [string map [list %PGSZ% $pgsz] { + do_test wal-22.%PGSZ%.$tn.1 { + sql1 { + PRAGMA main.page_size = %PGSZ%; + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(x UNIQUE); + INSERT INTO t1 SELECT randomblob(800); + INSERT INTO t1 SELECT randomblob(800); + INSERT INTO t1 SELECT randomblob(800); + } + } {wal} + do_test wal-22.%PGSZ%.$tn.2 { sql2 { PRAGMA integrity_check } } {ok} + do_test wal-22.%PGSZ%.$tn.3 { + sql1 {PRAGMA wal_checkpoint} + expr {[file size test.db] % %PGSZ%} + } {0} + }] +} + +#------------------------------------------------------------------------- +# Test that when 1 or more pages are recovered from a WAL file, +# sqlite3_log() is invoked to report this to the user. +# +ifcapable curdir { + set walfile [file nativename [file join [get_pwd] test.db-wal]] +} else { + set walfile test.db-wal +} +catch {db close} +forcedelete test.db +do_test wal-23.1 { + faultsim_delete_and_reopen + execsql { + CREATE TABLE t1(a, b); + PRAGMA journal_mode = WAL; + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + } + faultsim_save_and_close + + sqlite3_shutdown + test_sqlite3_log [list lappend ::log] + set ::log [list] + sqlite3 db test.db + execsql { SELECT * FROM t1 } +} {1 2 3 4} +do_test wal-23.2 { set ::log } {} + +do_test wal-23.3 { + db close + set ::log [list] + faultsim_restore_and_reopen + execsql { SELECT * FROM t1 } +} {1 2 3 4} +do_test wal-23.4 { + set ::log +} [list SQLITE_NOTICE_RECOVER_WAL \ + "recovered 2 frames from WAL file $walfile"] + + +ifcapable autovacuum { + # This block tests that if the size of a database is reduced by a + # transaction (because of an incremental or auto-vacuum), that no + # data is written to the WAL file for the truncated pages as part + # of the commit. e.g. if a transaction reduces the size of a database + # to N pages, data for page N+1 should not be written to the WAL file + # when committing the transaction. At one point such data was being + # written. + # + catch {db close} + forcedelete test.db + sqlite3 db test.db + do_execsql_test 24.1 { + PRAGMA auto_vacuum = 2; + PRAGMA journal_mode = WAL; + PRAGMA page_size = 1024; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(5000)); + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + } {wal} + do_test 24.2 { + execsql { + DELETE FROM t1; + PRAGMA wal_checkpoint; + } + db close + sqlite3 db test.db + file exists test.db-wal + } 0 + do_test 24.3 { + file size test.db + } [expr 84 * 1024] + do_test 24.4 { + execsql { + PRAGMA cache_size = 200; + PRAGMA incremental_vacuum; + PRAGMA wal_checkpoint; + } + file size test.db + } [expr 3 * 1024] + + # WAL file now contains a single frame - the new root page for table t1. + # It would be two frames (the new root page and a padding frame) if the + # ZERO_DAMAGE flag were not set. + do_test 24.5 { + file size test.db-wal + } [wal_file_size 1 1024] +} + +db close +sqlite3_shutdown +test_sqlite3_log +sqlite3_initialize + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wal2.test b/components/external/SQLite-3.8.1/test/wal2.test new file mode 100644 index 0000000000000000000000000000000000000000..4371e988b24f5589289fb1921e8f090c6576795c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal2.test @@ -0,0 +1,1317 @@ +# 2010 May 5 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/malloc_common.tcl +source $testdir/wal_common.tcl + +set testprefix wal2 + +ifcapable !wal {finish_test ; return } + +set sqlite_sync_count 0 +proc cond_incr_sync_count {adj} { + global sqlite_sync_count + if {$::tcl_platform(platform) == "windows"} { + incr sqlite_sync_count $adj + } { + ifcapable !dirsync { + incr sqlite_sync_count $adj + } + } +} + +proc set_tvfs_hdr {file args} { + + # Set $nHdr to the number of bytes in the wal-index header: + set nHdr 48 + set nInt [expr {$nHdr/4}] + + if {[llength $args]>2} { + error {wrong # args: should be "set_tvfs_hdr fileName ?val1? ?val2?"} + } + + set blob [tvfs shm $file] + if {$::tcl_platform(byteOrder)=="bigEndian"} {set fmt I} {set fmt i} + + if {[llength $args]} { + set ia [lindex $args 0] + set ib $ia + if {[llength $args]==2} { + set ib [lindex $args 1] + } + binary scan $blob a[expr $nHdr*2]a* dummy tail + set blob [binary format ${fmt}${nInt}${fmt}${nInt}a* $ia $ib $tail] + tvfs shm $file $blob + } + + binary scan $blob ${fmt}${nInt} ints + return $ints +} + +proc incr_tvfs_hdr {file idx incrval} { + set ints [set_tvfs_hdr $file] + set v [lindex $ints $idx] + incr v $incrval + lset ints $idx $v + set_tvfs_hdr $file $ints +} + + +#------------------------------------------------------------------------- +# Test case wal2-1.*: +# +# Set up a small database containing a single table. The database is not +# checkpointed during the test - all content resides in the log file. +# +# Two connections are established to the database file - a writer ([db]) +# and a reader ([db2]). For each of the 8 integer fields in the wal-index +# header (6 fields and 2 checksum values), do the following: +# +# 1. Modify the database using the writer. +# +# 2. Attempt to read the database using the reader. Before the reader +# has a chance to snapshot the wal-index header, increment one +# of the integer fields (so that the reader ends up with a corrupted +# header). +# +# 3. Check that the reader recovers the wal-index and reads the correct +# database content. +# +do_test wal2-1.0 { + proc tvfs_cb {method filename args} { + set ::filename $filename + return SQLITE_OK + } + + testvfs tvfs + tvfs script tvfs_cb + tvfs filter xShmOpen + + sqlite3 db test.db -vfs tvfs + sqlite3 db2 test.db -vfs tvfs + + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a); + } db2 + execsql { + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + SELECT count(a), sum(a) FROM t1; + } +} {4 10} +do_test wal2-1.1 { + execsql { SELECT count(a), sum(a) FROM t1 } db2 +} {4 10} + +set RECOVER [list \ + {0 1 lock exclusive} {1 7 lock exclusive} \ + {1 7 unlock exclusive} {0 1 unlock exclusive} \ +] +set READ [list \ + {4 1 lock shared} {4 1 unlock shared} \ +] +set INITSLOT [list \ + {4 1 lock exclusive} {4 1 unlock exclusive} \ +] + +foreach {tn iInsert res wal_index_hdr_mod wal_locks} " + 2 5 {5 15} 0 {$RECOVER $READ} + 3 6 {6 21} 1 {$RECOVER $READ} + 4 7 {7 28} 2 {$RECOVER $READ} + 5 8 {8 36} 3 {$RECOVER $READ} + 6 9 {9 45} 4 {$RECOVER $READ} + 7 10 {10 55} 5 {$RECOVER $READ} + 8 11 {11 66} 6 {$RECOVER $READ} + 9 12 {12 78} 7 {$RECOVER $READ} + 10 13 {13 91} 8 {$RECOVER $READ} + 11 14 {14 105} 9 {$RECOVER $READ} + 12 15 {15 120} -1 {$INITSLOT $READ} +" { + + do_test wal2-1.$tn.1 { + execsql { INSERT INTO t1 VALUES($iInsert) } + set ::locks [list] + proc tvfs_cb {method args} { + lappend ::locks [lindex $args 2] + return SQLITE_OK + } + tvfs filter xShmLock + if {$::wal_index_hdr_mod >= 0} { + incr_tvfs_hdr $::filename $::wal_index_hdr_mod 1 + } + execsql { SELECT count(a), sum(a) FROM t1 } db2 + } $res + + do_test wal2-1.$tn.2 { + set ::locks + } $wal_locks +} +db close +db2 close +tvfs delete +forcedelete test.db test.db-wal test.db-journal + +#------------------------------------------------------------------------- +# This test case is very similar to the previous one, except, after +# the reader reads the corrupt wal-index header, but before it has +# a chance to re-read it under the cover of the RECOVER lock, the +# wal-index header is replaced with a valid, but out-of-date, header. +# +# Because the header checksum looks Ok, the reader does not run recovery, +# it simply drops back to a READ lock and proceeds. But because the +# header is out-of-date, the reader reads the out-of-date snapshot. +# +# After this, the header is corrupted again and the reader is allowed +# to run recovery. This time, it sees an up-to-date snapshot of the +# database file. +# +set WRITER [list 0 1 lock exclusive] +set LOCKS [list \ + {0 1 lock exclusive} {0 1 unlock exclusive} \ + {4 1 lock exclusive} {4 1 unlock exclusive} \ + {4 1 lock shared} {4 1 unlock shared} \ +] +do_test wal2-2.0 { + + testvfs tvfs + tvfs script tvfs_cb + tvfs filter xShmOpen + proc tvfs_cb {method args} { + set ::filename [lindex $args 0] + return SQLITE_OK + } + + sqlite3 db test.db -vfs tvfs + sqlite3 db2 test.db -vfs tvfs + + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a); + } db2 + execsql { + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + SELECT count(a), sum(a) FROM t1; + } +} {4 10} +do_test wal2-2.1 { + execsql { SELECT count(a), sum(a) FROM t1 } db2 +} {4 10} + +foreach {tn iInsert res0 res1 wal_index_hdr_mod} { + 2 5 {4 10} {5 15} 0 + 3 6 {5 15} {6 21} 1 + 4 7 {6 21} {7 28} 2 + 5 8 {7 28} {8 36} 3 + 6 9 {8 36} {9 45} 4 + 7 10 {9 45} {10 55} 5 + 8 11 {10 55} {11 66} 6 + 9 12 {11 66} {12 78} 7 +} { + tvfs filter xShmLock + + do_test wal2-2.$tn.1 { + set oldhdr [set_tvfs_hdr $::filename] + execsql { INSERT INTO t1 VALUES($iInsert) } + execsql { SELECT count(a), sum(a) FROM t1 } + } $res1 + + do_test wal2-2.$tn.2 { + set ::locks [list] + proc tvfs_cb {method args} { + set lock [lindex $args 2] + lappend ::locks $lock + if {$lock == $::WRITER} { + set_tvfs_hdr $::filename $::oldhdr + } + return SQLITE_OK + } + + if {$::wal_index_hdr_mod >= 0} { + incr_tvfs_hdr $::filename $::wal_index_hdr_mod 1 + } + execsql { SELECT count(a), sum(a) FROM t1 } db2 + } $res0 + + do_test wal2-2.$tn.3 { + set ::locks + } $LOCKS + + do_test wal2-2.$tn.4 { + set ::locks [list] + proc tvfs_cb {method args} { + set lock [lindex $args 2] + lappend ::locks $lock + return SQLITE_OK + } + + if {$::wal_index_hdr_mod >= 0} { + incr_tvfs_hdr $::filename $::wal_index_hdr_mod 1 + } + execsql { SELECT count(a), sum(a) FROM t1 } db2 + } $res1 +} +db close +db2 close +tvfs delete +forcedelete test.db test.db-wal test.db-journal + + +if 0 { +#------------------------------------------------------------------------- +# This test case - wal2-3.* - tests the response of the library to an +# SQLITE_BUSY when attempting to obtain a READ or RECOVER lock. +# +# wal2-3.0 - 2: SQLITE_BUSY when obtaining a READ lock +# wal2-3.3 - 6: SQLITE_BUSY when obtaining a RECOVER lock +# +do_test wal2-3.0 { + proc tvfs_cb {method args} { + if {$method == "xShmLock"} { + if {[info exists ::locked]} { return SQLITE_BUSY } + } + return SQLITE_OK + } + + proc busyhandler x { + if {$x>3} { unset -nocomplain ::locked } + return 0 + } + + testvfs tvfs + tvfs script tvfs_cb + sqlite3 db test.db -vfs tvfs + db busy busyhandler + + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + } + + set ::locked 1 + info exists ::locked +} {1} +do_test wal2-3.1 { + execsql { SELECT count(a), sum(a) FROM t1 } +} {4 10} +do_test wal2-3.2 { + info exists ::locked +} {0} + +do_test wal2-3.3 { + proc tvfs_cb {method args} { + if {$method == "xShmLock"} { + if {[info exists ::sabotage]} { + unset -nocomplain ::sabotage + incr_tvfs_hdr [lindex $args 0] 1 1 + } + if {[info exists ::locked] && [lindex $args 2] == "RECOVER"} { + return SQLITE_BUSY + } + } + return SQLITE_OK + } + set ::sabotage 1 + set ::locked 1 + list [info exists ::sabotage] [info exists ::locked] +} {1 1} +do_test wal2-3.4 { + execsql { SELECT count(a), sum(a) FROM t1 } +} {4 10} +do_test wal2-3.5 { + list [info exists ::sabotage] [info exists ::locked] +} {0 0} +db close +tvfs delete +forcedelete test.db test.db-wal test.db-journal + +} + +#------------------------------------------------------------------------- +# Test that a database connection using a VFS that does not support the +# xShmXXX interfaces cannot open a WAL database. +# +do_test wal2-4.1 { + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + CREATE TABLE data(x); + INSERT INTO data VALUES('need xShmOpen to see this'); + PRAGMA wal_checkpoint; + } + # Three pages in the WAL file at this point: One copy of page 1 and two + # of the root page for table "data". +} {wal 0 3 3} +do_test wal2-4.2 { + db close + testvfs tvfs -noshm 1 + sqlite3 db test.db -vfs tvfs + catchsql { SELECT * FROM data } +} {1 {unable to open database file}} +do_test wal2-4.3 { + db close + testvfs tvfs + sqlite3 db test.db -vfs tvfs + catchsql { SELECT * FROM data } +} {0 {{need xShmOpen to see this}}} +db close +tvfs delete + +#------------------------------------------------------------------------- +# Test that if a database connection is forced to run recovery before it +# can perform a checkpoint, it does not transition into RECOVER state. +# +# UPDATE: This has now changed. When running a checkpoint, if recovery is +# required the client grabs all exclusive locks (just as it would for a +# recovery performed as a pre-cursor to a normal database transaction). +# +set expected_locks [list] +lappend expected_locks {1 1 lock exclusive} ;# Lock checkpoint +lappend expected_locks {0 1 lock exclusive} ;# Lock writer +lappend expected_locks {2 6 lock exclusive} ;# Lock recovery & all aReadMark[] +lappend expected_locks {2 6 unlock exclusive} ;# Unlock recovery & aReadMark[] +lappend expected_locks {0 1 unlock exclusive} ;# Unlock writer +lappend expected_locks {3 1 lock exclusive} ;# Lock aReadMark[0] +lappend expected_locks {3 1 unlock exclusive} ;# Unlock aReadMark[0] +lappend expected_locks {1 1 unlock exclusive} ;# Unlock checkpoint +do_test wal2-5.1 { + proc tvfs_cb {method args} { + set ::shm_file [lindex $args 0] + if {$method == "xShmLock"} { lappend ::locks [lindex $args 2] } + return $::tvfs_cb_return + } + set tvfs_cb_return SQLITE_OK + + testvfs tvfs + tvfs script tvfs_cb + + sqlite3 db test.db -vfs tvfs + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE x(y); + INSERT INTO x VALUES(1); + } + + incr_tvfs_hdr $::shm_file 1 1 + set ::locks [list] + execsql { PRAGMA wal_checkpoint } + set ::locks +} $expected_locks +db close +tvfs delete + +#------------------------------------------------------------------------- +# This block, test cases wal2-6.*, tests the operation of WAL with +# "PRAGMA locking_mode=EXCLUSIVE" set. +# +# wal2-6.1.*: Changing to WAL mode before setting locking_mode=exclusive. +# +# wal2-6.2.*: Changing to WAL mode after setting locking_mode=exclusive. +# +# wal2-6.3.*: Changing back to rollback mode from WAL mode after setting +# locking_mode=exclusive. +# +# wal2-6.4.*: Check that xShmLock calls are omitted in exclusive locking +# mode. +# +# wal2-6.5.*: +# +# wal2-6.6.*: Check that if the xShmLock() to reaquire a WAL read-lock when +# exiting exclusive mode fails (i.e. SQLITE_IOERR), then the +# connection silently remains in exclusive mode. +# +do_test wal2-6.1.1 { + forcedelete test.db test.db-wal test.db-journal + sqlite3 db test.db + execsql { + Pragma Journal_Mode = Wal; + } +} {wal} +do_test wal2-6.1.2 { + execsql { PRAGMA lock_status } +} {main unlocked temp closed} +do_test wal2-6.1.3 { + execsql { + SELECT * FROM sqlite_master; + Pragma Locking_Mode = Exclusive; + } + execsql { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + COMMIT; + PRAGMA lock_status; + } +} {main exclusive temp closed} +do_test wal2-6.1.4 { + execsql { + PRAGMA locking_mode = normal; + PRAGMA lock_status; + } +} {normal main exclusive temp closed} +do_test wal2-6.1.5 { + execsql { + SELECT * FROM t1; + PRAGMA lock_status; + } +} {1 2 main shared temp closed} +do_test wal2-6.1.6 { + execsql { + INSERT INTO t1 VALUES(3, 4); + PRAGMA lock_status; + } +} {main shared temp closed} +db close + +do_test wal2-6.2.1 { + forcedelete test.db test.db-wal test.db-journal + sqlite3 db test.db + execsql { + Pragma Locking_Mode = Exclusive; + Pragma Journal_Mode = Wal; + Pragma Lock_Status; + } +} {exclusive wal main exclusive temp closed} +do_test wal2-6.2.2 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + COMMIT; + Pragma loCK_STATus; + } +} {main exclusive temp closed} +do_test wal2-6.2.3 { + db close + sqlite3 db test.db + execsql { SELECT * FROM sqlite_master } + execsql { PRAGMA LOCKING_MODE = EXCLUSIVE } +} {exclusive} +do_test wal2-6.2.4 { + execsql { + SELECT * FROM t1; + pragma lock_status; + } +} {1 2 main shared temp closed} +do_test wal2-6.2.5 { + execsql { + INSERT INTO t1 VALUES(3, 4); + pragma lock_status; + } +} {main exclusive temp closed} +do_test wal2-6.2.6 { + execsql { + PRAGMA locking_mode = NORMAL; + pragma lock_status; + } +} {normal main exclusive temp closed} +do_test wal2-6.2.7 { + execsql { + BEGIN IMMEDIATE; COMMIT; + pragma lock_status; + } +} {main shared temp closed} +do_test wal2-6.2.8 { + execsql { + PRAGMA locking_mode = EXCLUSIVE; + BEGIN IMMEDIATE; COMMIT; + PRAGMA locking_mode = NORMAL; + } + execsql { + SELECT * FROM t1; + pragma lock_status; + } +} {1 2 3 4 main shared temp closed} +do_test wal2-6.2.9 { + execsql { + INSERT INTO t1 VALUES(5, 6); + SELECT * FROM t1; + pragma lock_status; + } +} {1 2 3 4 5 6 main shared temp closed} +db close + +do_test wal2-6.3.1 { + forcedelete test.db test.db-wal test.db-journal + sqlite3 db test.db + execsql { + PRAGMA journal_mode = WAL; + PRAGMA locking_mode = exclusive; + BEGIN; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('Chico'); + INSERT INTO t1 VALUES('Harpo'); + COMMIT; + } + list [file exists test.db-wal] [file exists test.db-journal] +} {1 0} +do_test wal2-6.3.2 { + execsql { PRAGMA journal_mode = DELETE } + file exists test.db-wal +} {0} +do_test wal2-6.3.3 { + execsql { PRAGMA lock_status } +} {main exclusive temp closed} +do_test wal2-6.3.4 { + execsql { + BEGIN; + INSERT INTO t1 VALUES('Groucho'); + } + list [file exists test.db-wal] [file exists test.db-journal] +} {0 1} +do_test wal2-6.3.5 { + execsql { PRAGMA lock_status } +} {main exclusive temp closed} +do_test wal2-6.3.6 { + execsql { COMMIT } + list [file exists test.db-wal] [file exists test.db-journal] +} {0 1} +do_test wal2-6.3.7 { + execsql { PRAGMA lock_status } +} {main exclusive temp closed} +db close + + +# This test - wal2-6.4.* - uses a single database connection and the +# [testvfs] instrumentation to test that xShmLock() is being called +# as expected when a WAL database is used with locking_mode=exclusive. +# +do_test wal2-6.4.1 { + forcedelete test.db test.db-wal test.db-journal + proc tvfs_cb {method args} { + set ::shm_file [lindex $args 0] + if {$method == "xShmLock"} { lappend ::locks [lindex $args 2] } + return "SQLITE_OK" + } + testvfs tvfs + tvfs script tvfs_cb + sqlite3 db test.db -vfs tvfs + set {} {} +} {} + +set RECOVERY { + {0 1 lock exclusive} {1 7 lock exclusive} + {1 7 unlock exclusive} {0 1 unlock exclusive} +} +set READMARK0_READ { + {3 1 lock shared} {3 1 unlock shared} +} +set READMARK0_WRITE { + {3 1 lock shared} + {0 1 lock exclusive} {3 1 unlock shared} + {4 1 lock exclusive} {4 1 unlock exclusive} {4 1 lock shared} + {0 1 unlock exclusive} {4 1 unlock shared} +} +set READMARK1_SET { + {4 1 lock exclusive} {4 1 unlock exclusive} +} +set READMARK1_READ { + {4 1 lock shared} {4 1 unlock shared} +} +set READMARK1_WRITE { + {4 1 lock shared} + {0 1 lock exclusive} {0 1 unlock exclusive} + {4 1 unlock shared} +} + +foreach {tn sql res expected_locks} { + 2 { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + BEGIN; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES('Leonard'); + INSERT INTO t1 VALUES('Arthur'); + COMMIT; + } {wal} { + $RECOVERY + $READMARK0_WRITE + } + + 3 { + # This test should do the READMARK1_SET locking to populate the + # aReadMark[1] slot with the current mxFrame value. Followed by + # READMARK1_READ to read the database. + # + SELECT * FROM t1 + } {Leonard Arthur} { + $READMARK1_SET + $READMARK1_READ + } + + 4 { + # aReadMark[1] is already set to mxFrame. So just READMARK1_READ + # this time, not READMARK1_SET. + # + SELECT * FROM t1 ORDER BY x + } {Arthur Leonard} { + $READMARK1_READ + } + + 5 { + PRAGMA locking_mode = exclusive + } {exclusive} { } + + 6 { + INSERT INTO t1 VALUES('Julius Henry'); + SELECT * FROM t1; + } {Leonard Arthur {Julius Henry}} { + $READMARK1_READ + } + + 7 { + INSERT INTO t1 VALUES('Karl'); + SELECT * FROM t1; + } {Leonard Arthur {Julius Henry} Karl} { } + + 8 { + PRAGMA locking_mode = normal + } {normal} { } + + 9 { + SELECT * FROM t1 ORDER BY x + } {Arthur {Julius Henry} Karl Leonard} $READMARK1_READ + + 10 { DELETE FROM t1 } {} $READMARK1_WRITE + + 11 { + SELECT * FROM t1 + } {} { + $READMARK1_SET + $READMARK1_READ + } +} { + + set L [list] + foreach el [subst $expected_locks] { lappend L $el } + + set S "" + foreach sq [split $sql "\n"] { + set sq [string trim $sq] + if {[string match {#*} $sq]==0} {append S "$sq\n"} + } + + set ::locks [list] + do_test wal2-6.4.$tn.1 { execsql $S } $res + do_test wal2-6.4.$tn.2 { set ::locks } $L +} + +db close +tvfs delete + +do_test wal2-6.5.1 { + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = wal; + PRAGMA locking_mode = exclusive; + CREATE TABLE t2(a, b); + PRAGMA wal_checkpoint; + INSERT INTO t2 VALUES('I', 'II'); + PRAGMA journal_mode; + } +} {wal exclusive 0 2 2 wal} +do_test wal2-6.5.2 { + execsql { + PRAGMA locking_mode = normal; + INSERT INTO t2 VALUES('III', 'IV'); + PRAGMA locking_mode = exclusive; + SELECT * FROM t2; + } +} {normal exclusive I II III IV} +do_test wal2-6.5.3 { + execsql { PRAGMA wal_checkpoint } +} {0 2 2} +db close + +proc lock_control {method filename handle spec} { + foreach {start n op type} $spec break + if {$op == "lock"} { return SQLITE_IOERR } + return SQLITE_OK +} +do_test wal2-6.6.1 { + testvfs T + T script lock_control + T filter {} + sqlite3 db test.db -vfs T + execsql { SELECT * FROM sqlite_master } + execsql { PRAGMA locking_mode = exclusive } + execsql { INSERT INTO t2 VALUES('V', 'VI') } +} {} +do_test wal2-6.6.2 { + execsql { PRAGMA locking_mode = normal } + T filter xShmLock + execsql { INSERT INTO t2 VALUES('VII', 'VIII') } +} {} +do_test wal2-6.6.3 { + # At this point the connection should still be in exclusive-mode, even + # though it tried to exit exclusive-mode when committing the INSERT + # statement above. To exit exclusive mode, SQLite has to take a read-lock + # on the WAL file using xShmLock(). Since that call failed, it remains + # in exclusive mode. + # + sqlite3 db2 test.db -vfs T + catchsql { SELECT * FROM t2 } db2 +} {1 {database is locked}} +do_test wal2-6.6.2 { + db2 close + T filter {} + execsql { INSERT INTO t2 VALUES('IX', 'X') } +} {} +do_test wal2-6.6.4 { + # This time, we have successfully exited exclusive mode. So the second + # connection can read the database. + sqlite3 db2 test.db -vfs T + catchsql { SELECT * FROM t2 } db2 +} {0 {I II III IV V VI VII VIII IX X}} + +db close +db2 close +T delete + +#------------------------------------------------------------------------- +# Test a theory about the checksum algorithm. Theory was false and this +# test did not provoke a bug. +# +forcedelete test.db test.db-wal test.db-journal +do_test wal2-7.1.1 { + sqlite3 db test.db + execsql { + PRAGMA page_size = 4096; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + } + file size test.db +} {4096} +do_test wal2-7.1.2 { + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + hexio_write test2.db-wal 48 FF +} {1} +do_test wal2-7.1.3 { + sqlite3 db2 test2.db + execsql { PRAGMA wal_checkpoint } db2 + execsql { SELECT * FROM sqlite_master } db2 +} {} +db close +db2 close +forcedelete test.db test.db-wal test.db-journal +do_test wal2-8.1.2 { + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum=OFF; + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(zeroblob(8188*1020)); + CREATE TABLE t2(y); + PRAGMA wal_checkpoint; + } + execsql { + SELECT rootpage>=8192 FROM sqlite_master WHERE tbl_name = 't2'; + } +} {1} +do_test wal2-8.1.3 { + execsql { + PRAGMA cache_size = 10; + CREATE TABLE t3(z); + BEGIN; + INSERT INTO t3 VALUES(randomblob(900)); + INSERT INTO t3 SELECT randomblob(900) FROM t3; + INSERT INTO t2 VALUES('hello'); + INSERT INTO t3 SELECT randomblob(900) FROM t3; + INSERT INTO t3 SELECT randomblob(900) FROM t3; + INSERT INTO t3 SELECT randomblob(900) FROM t3; + INSERT INTO t3 SELECT randomblob(900) FROM t3; + INSERT INTO t3 SELECT randomblob(900) FROM t3; + INSERT INTO t3 SELECT randomblob(900) FROM t3; + ROLLBACK; + } + execsql { + INSERT INTO t2 VALUES('goodbye'); + INSERT INTO t3 SELECT randomblob(900) FROM t3; + INSERT INTO t3 SELECT randomblob(900) FROM t3; + } +} {} +do_test wal2-8.1.4 { + sqlite3 db2 test.db + execsql { SELECT * FROM t2 } +} {goodbye} +db2 close +db close + +#------------------------------------------------------------------------- +# Test that even if the checksums for both are valid, if the two copies +# of the wal-index header in the wal-index do not match, the client +# runs (or at least tries to run) database recovery. +# +# +proc get_name {method args} { set ::filename [lindex $args 0] ; tvfs filter {} } +testvfs tvfs +tvfs script get_name +tvfs filter xShmOpen + +forcedelete test.db test.db-wal test.db-journal +do_test wal2-9.1 { + sqlite3 db test.db -vfs tvfs + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE x(y); + INSERT INTO x VALUES('Barton'); + INSERT INTO x VALUES('Deakin'); + } + + # Set $wih(1) to the contents of the wal-index header after + # the frames associated with the first two rows in table 'x' have + # been inserted. Then insert one more row and set $wih(2) + # to the new value of the wal-index header. + # + # If the $wih(1) is written into the wal-index before running + # a read operation, the client will see only the first two rows. If + # $wih(2) is written into the wal-index, the client will see + # three rows. If an invalid header is written into the wal-index, then + # the client will run recovery and see three rows. + # + set wih(1) [set_tvfs_hdr $::filename] + execsql { INSERT INTO x VALUES('Watson') } + set wih(2) [set_tvfs_hdr $::filename] + + sqlite3 db2 test.db -vfs tvfs + execsql { SELECT * FROM x } db2 +} {Barton Deakin Watson} + +foreach {tn hdr1 hdr2 res} [list \ + 3 $wih(1) $wih(1) {Barton Deakin} \ + 4 $wih(1) $wih(2) {Barton Deakin Watson} \ + 5 $wih(2) $wih(1) {Barton Deakin Watson} \ + 6 $wih(2) $wih(2) {Barton Deakin Watson} \ + 7 $wih(1) $wih(1) {Barton Deakin} \ + 8 {0 0 0 0 0 0 0 0 0 0 0 0} {0 0 0 0 0 0 0 0 0 0 0 0} {Barton Deakin Watson} +] { + do_test wal2-9.$tn { + set_tvfs_hdr $::filename $hdr1 $hdr2 + execsql { SELECT * FROM x } db2 + } $res +} + +db2 close +db close + +#------------------------------------------------------------------------- +# This block of tests - wal2-10.* - focus on the libraries response to +# new versions of the wal or wal-index formats. +# +# wal2-10.1.*: Test that the library refuses to "recover" a new WAL +# format. +# +# wal2-10.2.*: Test that the library refuses to read or write a database +# if the wal-index version is newer than it understands. +# +# At time of writing, the only versions of the wal and wal-index formats +# that exist are versions 3007000 (corresponding to SQLite version 3.7.0, +# the first version of SQLite to feature wal mode). +# +do_test wal2-10.1.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + PRAGMA wal_checkpoint; + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + } + faultsim_save_and_close +} {} +do_test wal2-10.1.2 { + faultsim_restore_and_reopen + execsql { SELECT * FROM t1 } +} {1 2 3 4} +do_test wal2-10.1.3 { + faultsim_restore_and_reopen + set hdr [wal_set_walhdr test.db-wal] + lindex $hdr 1 +} {3007000} +do_test wal2-10.1.4 { + lset hdr 1 3007001 + wal_set_walhdr test.db-wal $hdr + catchsql { SELECT * FROM t1 } +} {1 {unable to open database file}} + +testvfs tvfs -default 1 +do_test wal2-10.2.1 { + faultsim_restore_and_reopen + execsql { SELECT * FROM t1 } +} {1 2 3 4} +do_test wal2-10.2.2 { + set hdr [set_tvfs_hdr $::filename] + lindex $hdr 0 +} {3007000} +do_test wal2-10.2.3 { + lset hdr 0 3007001 + wal_fix_walindex_cksum hdr + set_tvfs_hdr $::filename $hdr + catchsql { SELECT * FROM t1 } +} {1 {unable to open database file}} +db close +tvfs delete + +#------------------------------------------------------------------------- +# This block of tests - wal2-11.* - tests that it is not possible to put +# the library into an infinite loop by presenting it with a corrupt +# hash table (one that appears to contain a single chain of infinite +# length). +# +# wal2-11.1.*: While reading the hash-table. +# +# wal2-11.2.*: While writing the hash-table. +# +testvfs tvfs -default 1 +do_test wal2-11.0 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b, c); + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + INSERT INTO t1 VALUES(7, 8, 9); + SELECT * FROM t1; + } +} {wal 1 2 3 4 5 6 7 8 9} + +do_test wal2-11.1.1 { + sqlite3 db2 test.db + execsql { SELECT name FROM sqlite_master } db2 +} {t1} + +if {$::tcl_version>=8.5} { + # Set all zeroed slots in the first hash table to invalid values. + # + set blob [string range [tvfs shm $::filename] 0 16383] + set I [string range [tvfs shm $::filename] 16384 end] + binary scan $I t* L + set I [list] + foreach p $L { + lappend I [expr $p ? $p : 400] + } + append blob [binary format t* $I] + tvfs shm $::filename $blob + do_test wal2-11.2 { + catchsql { INSERT INTO t1 VALUES(10, 11, 12) } + } {1 {database disk image is malformed}} + + # Fill up the hash table on the first page of shared memory with 0x55 bytes. + # + set blob [string range [tvfs shm $::filename] 0 16383] + append blob [string repeat [binary format c 55] 16384] + tvfs shm $::filename $blob + do_test wal2-11.3 { + catchsql { SELECT * FROM t1 } db2 + } {1 {database disk image is malformed}} +} + +db close +db2 close +tvfs delete + +#------------------------------------------------------------------------- +# If a connection is required to create a WAL or SHM file, it creates +# the new files with the same file-system permissions as the database +# file itself. Test this. +# +if {$::tcl_platform(platform) == "unix"} { + faultsim_delete_and_reopen + # Changed on 2012-02-13: umask is deliberately ignored for -wal files. + #set umask [exec /bin/sh -c umask] + set umask 0 + + + do_test wal2-12.1 { + sqlite3 db test.db + execsql { + CREATE TABLE tx(y, z); + PRAGMA journal_mode = WAL; + } + db close + list [file exists test.db-wal] [file exists test.db-shm] + } {0 0} + + foreach {tn permissions} { + 1 00644 + 2 00666 + 3 00600 + 4 00755 + } { + set effective [format %.5o [expr $permissions & ~$umask]] + do_test wal2-12.2.$tn.1 { + file attributes test.db -permissions $permissions + file attributes test.db -permissions + } $permissions + do_test wal2-12.2.$tn.2 { + list [file exists test.db-wal] [file exists test.db-shm] + } {0 0} + do_test wal2-12.2.$tn.3 { + sqlite3 db test.db + execsql { INSERT INTO tx DEFAULT VALUES } + list [file exists test.db-wal] [file exists test.db-shm] + } {1 1} + do_test wal2-12.2.$tn.4 { + list [file attr test.db-wal -perm] [file attr test.db-shm -perm] + } [list $effective $effective] + do_test wal2-12.2.$tn.5 { + db close + list [file exists test.db-wal] [file exists test.db-shm] + } {0 0} + } +} + +#------------------------------------------------------------------------- +# Test the libraries response to discovering that one or more of the +# database, wal or shm files cannot be opened, or can only be opened +# read-only. +# +if {$::tcl_platform(platform) == "unix"} { + proc perm {} { + set L [list] + foreach f {test.db test.db-wal test.db-shm} { + if {[file exists $f]} { + lappend L [file attr $f -perm] + } else { + lappend L {} + } + } + set L + } + + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + PRAGMA wal_checkpoint; + INSERT INTO t1 VALUES('3.14', '2.72'); + } + do_test wal2-13.1.1 { + list [file exists test.db-shm] [file exists test.db-wal] + } {1 1} + faultsim_save_and_close + + foreach {tn db_perm wal_perm shm_perm can_open can_read can_write} { + 2 00644 00644 00644 1 1 1 + 3 00644 00400 00644 1 1 0 + 4 00644 00644 00400 1 0 0 + 5 00400 00644 00644 1 1 0 + + 7 00644 00000 00644 1 0 0 + 8 00644 00644 00000 1 0 0 + 9 00000 00644 00644 0 0 0 + } { + faultsim_restore + do_test wal2-13.$tn.1 { + file attr test.db -perm $db_perm + file attr test.db-wal -perm $wal_perm + file attr test.db-shm -perm $shm_perm + + set L [file attr test.db -perm] + lappend L [file attr test.db-wal -perm] + lappend L [file attr test.db-shm -perm] + } [list $db_perm $wal_perm $shm_perm] + + # If $can_open is true, then it should be possible to open a database + # handle. Otherwise, if $can_open is 0, attempting to open the db + # handle throws an "unable to open database file" exception. + # + set r(1) {0 ok} + set r(0) {1 {unable to open database file}} + do_test wal2-13.$tn.2 { + list [catch {sqlite3 db test.db ; set {} ok} msg] $msg + } $r($can_open) + + if {$can_open} { + + # If $can_read is true, then the client should be able to read from + # the database file. If $can_read is false, attempting to read should + # throw the "unable to open database file" exception. + # + set a(0) {1 {unable to open database file}} + set a(1) {0 {3.14 2.72}} + do_test wal2-13.$tn.3 { + catchsql { SELECT * FROM t1 } + } $a($can_read) + + # Now try to write to the db file. If the client can read but not + # write, then it should throw the familiar "unable to open db file" + # exception. If it can read but not write, the exception should + # be "attempt to write a read only database". + # + # If the client can read and write, the operation should succeed. + # + set b(0,0) {1 {unable to open database file}} + set b(1,0) {1 {attempt to write a readonly database}} + set b(1,1) {0 {}} + do_test wal2-13.$tn.4 { + catchsql { INSERT INTO t1 DEFAULT VALUES } + } $b($can_read,$can_write) + } + catch { db close } + } +} + +#------------------------------------------------------------------------- +# Test that "PRAGMA checkpoint_fullsync" appears to be working. +# +foreach {tn sql reslist} { + 1 { } {10 0 4 0 6 0} + 2 { PRAGMA checkpoint_fullfsync = 1 } {10 4 4 2 6 2} + 3 { PRAGMA checkpoint_fullfsync = 0 } {10 0 4 0 6 0} +} { + faultsim_delete_and_reopen + + execsql {PRAGMA auto_vacuum = 0} + execsql $sql + do_execsql_test wal2-14.$tn.0 { PRAGMA page_size = 4096 } {} + do_execsql_test wal2-14.$tn.1 { PRAGMA journal_mode = WAL } {wal} + + set sqlite_sync_count 0 + set sqlite_fullsync_count 0 + + do_execsql_test wal2-14.$tn.2 { + PRAGMA wal_autocheckpoint = 10; + CREATE TABLE t1(a, b); -- 2 wal syncs + INSERT INTO t1 VALUES(1, 2); -- 2 wal sync + PRAGMA wal_checkpoint; -- 1 wal sync, 1 db sync + BEGIN; + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t1 VALUES(5, 6); + COMMIT; -- 2 wal sync + PRAGMA wal_checkpoint; -- 1 wal sync, 1 db sync + } {10 0 3 3 0 1 1} + + do_test wal2-14.$tn.3 { + cond_incr_sync_count 1 + list $sqlite_sync_count $sqlite_fullsync_count + } [lrange $reslist 0 1] + + set sqlite_sync_count 0 + set sqlite_fullsync_count 0 + + do_test wal2-14.$tn.4 { + execsql { INSERT INTO t1 VALUES(7, zeroblob(12*4096)) } + list $sqlite_sync_count $sqlite_fullsync_count + } [lrange $reslist 2 3] + + set sqlite_sync_count 0 + set sqlite_fullsync_count 0 + + do_test wal2-14.$tn.5 { + execsql { PRAGMA wal_autocheckpoint = 1000 } + execsql { INSERT INTO t1 VALUES(9, 10) } + execsql { INSERT INTO t1 VALUES(11, 12) } + execsql { INSERT INTO t1 VALUES(13, 14) } + db close + list $sqlite_sync_count $sqlite_fullsync_count + } [lrange $reslist 4 5] +} + +catch { db close } + +# PRAGMA checkpoint_fullsync +# PRAGMA fullfsync +# PRAGMA synchronous +# +foreach {tn settings restart_sync commit_sync ckpt_sync} { + 1 {0 0 off} {0 0} {0 0} {0 0} + 2 {0 0 normal} {1 0} {0 0} {2 0} + 3 {0 0 full} {2 0} {1 0} {2 0} + + 4 {0 1 off} {0 0} {0 0} {0 0} + 5 {0 1 normal} {0 1} {0 0} {0 2} + 6 {0 1 full} {0 2} {0 1} {0 2} + + 7 {1 0 off} {0 0} {0 0} {0 0} + 8 {1 0 normal} {1 0} {0 0} {0 2} + 9 {1 0 full} {2 0} {1 0} {0 2} + + 10 {1 1 off} {0 0} {0 0} {0 0} + 11 {1 1 normal} {0 1} {0 0} {0 2} + 12 {1 1 full} {0 2} {0 1} {0 2} +} { + forcedelete test.db + + testvfs tvfs -default 1 + tvfs filter xSync + tvfs script xSyncCb + proc xSyncCb {method file fileid flags} { + incr ::sync($flags) + } + + sqlite3 db test.db + do_execsql_test 15.$tn.1 " + PRAGMA page_size = 4096; + CREATE TABLE t1(x); + PRAGMA wal_autocheckpoint = OFF; + PRAGMA journal_mode = WAL; + PRAGMA checkpoint_fullfsync = [lindex $settings 0]; + PRAGMA fullfsync = [lindex $settings 1]; + PRAGMA synchronous = [lindex $settings 2]; + " {0 wal} + +if { $tn==2} breakpoint + do_test 15.$tn.2 { + set sync(normal) 0 + set sync(full) 0 + execsql { INSERT INTO t1 VALUES('abc') } + list $::sync(normal) $::sync(full) + } $restart_sync + + do_test 15.$tn.3 { + set sync(normal) 0 + set sync(full) 0 + execsql { INSERT INTO t1 VALUES('abc') } + list $::sync(normal) $::sync(full) + } $commit_sync + + do_test 15.$tn.4 { + set sync(normal) 0 + set sync(full) 0 + execsql { INSERT INTO t1 VALUES('def') } + list $::sync(normal) $::sync(full) + } $commit_sync + + do_test 15.$tn.5 { + set sync(normal) 0 + set sync(full) 0 + execsql { PRAGMA wal_checkpoint } + list $::sync(normal) $::sync(full) + } $ckpt_sync + + db close + tvfs delete +} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wal3.test b/components/external/SQLite-3.8.1/test/wal3.test new file mode 100644 index 0000000000000000000000000000000000000000..18e6075a4a870799821b667995b9b3f01344fb5c --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal3.test @@ -0,0 +1,787 @@ +# 2010 April 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/wal_common.tcl +source $testdir/malloc_common.tcl +ifcapable !wal {finish_test ; return } + +set a_string_counter 1 +proc a_string {n} { + global a_string_counter + incr a_string_counter + string range [string repeat "${a_string_counter}." $n] 1 $n +} +db func a_string a_string + +#------------------------------------------------------------------------- +# When a rollback or savepoint rollback occurs, the client may remove +# elements from one of the hash tables in the wal-index. This block +# of test cases tests that nothing appears to go wrong when this is +# done. +# +do_test wal3-1.0 { + execsql { + PRAGMA cache_size = 2000; + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = off; + PRAGMA synchronous = normal; + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 0; + BEGIN; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES( a_string(800) ); /* 1 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 2 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 4 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 8 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 16 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 32 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 64 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 128*/ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 256 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 512 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 1024 */ + INSERT INTO t1 SELECT a_string(800) FROM t1; /* 2048 */ + INSERT INTO t1 SELECT a_string(800) FROM t1 LIMIT 1970; /* 4018 */ + COMMIT; + PRAGMA cache_size = 10; + } + wal_frame_count test.db-wal 1024 +} 4056 + +for {set i 1} {$i < 50} {incr i} { + + do_test wal3-1.$i.1 { + set str [a_string 800] + execsql { UPDATE t1 SET x = $str WHERE rowid = $i } + lappend L [wal_frame_count test.db-wal 1024] + execsql { + BEGIN; + INSERT INTO t1 SELECT a_string(800) FROM t1 LIMIT 100; + ROLLBACK; + PRAGMA integrity_check; + } + } {ok} + + # Check that everything looks OK from the point of view of an + # external connection. + # + sqlite3 db2 test.db + do_test wal3-1.$i.2 { + execsql { SELECT count(*) FROM t1 } db2 + } 4018 + do_test wal3-1.$i.3 { + execsql { SELECT x FROM t1 WHERE rowid = $i } + } $str + do_test wal3-1.$i.4 { + execsql { PRAGMA integrity_check } db2 + } {ok} + db2 close + + # Check that the file-system in its current state can be recovered. + # + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + forcedelete test2.db-journal + sqlite3 db2 test2.db + do_test wal3-1.$i.5 { + execsql { SELECT count(*) FROM t1 } db2 + } 4018 + do_test wal3-1.$i.6 { + execsql { SELECT x FROM t1 WHERE rowid = $i } + } $str + do_test wal3-1.$i.7 { + execsql { PRAGMA integrity_check } db2 + } {ok} + db2 close +} + +proc byte_is_zero {file offset} { + if {[file size test.db] <= $offset} { return 1 } + expr { [hexio_read $file $offset 1] == "00" } +} + +do_multiclient_test i { + + set testname(1) multiproc + set testname(2) singleproc + set tn $testname($i) + + do_test wal3-2.$tn.1 { + sql1 { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + } + sql1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 'one'); + BEGIN; + SELECT * FROM t1; + } + } {1 one} + do_test wal3-2.$tn.2 { + sql2 { + CREATE TABLE t2(a, b); + INSERT INTO t2 VALUES(2, 'two'); + BEGIN; + SELECT * FROM t2; + } + } {2 two} + do_test wal3-2.$tn.3 { + sql3 { + CREATE TABLE t3(a, b); + INSERT INTO t3 VALUES(3, 'three'); + BEGIN; + SELECT * FROM t3; + } + } {3 three} + + # Try to checkpoint the database using [db]. It should be possible to + # checkpoint everything except the table added by [db3] (checkpointing + # these frames would clobber the snapshot currently being used by [db2]). + # + # After [db2] has committed, a checkpoint can copy the entire log to the + # database file. Checkpointing after [db3] has committed is therefore a + # no-op, as the entire log has already been backfilled. + # + do_test wal3-2.$tn.4 { + sql1 { + COMMIT; + PRAGMA wal_checkpoint; + } + byte_is_zero test.db [expr $AUTOVACUUM ? 4*1024 : 3*1024] + } {1} + do_test wal3-2.$tn.5 { + sql2 { + COMMIT; + PRAGMA wal_checkpoint; + } + list [byte_is_zero test.db [expr $AUTOVACUUM ? 4*1024 : 3*1024]] \ + [byte_is_zero test.db [expr $AUTOVACUUM ? 5*1024 : 4*1024]] + } {0 1} + do_test wal3-2.$tn.6 { + sql3 { + COMMIT; + PRAGMA wal_checkpoint; + } + list [byte_is_zero test.db [expr $AUTOVACUUM ? 4*1024 : 3*1024]] \ + [byte_is_zero test.db [expr $AUTOVACUUM ? 5*1024 : 4*1024]] + } {0 1} +} +catch {db close} + +#------------------------------------------------------------------------- +# Test that that for the simple test: +# +# CREATE TABLE x(y); +# INSERT INTO x VALUES('z'); +# PRAGMA wal_checkpoint; +# +# in WAL mode the xSync method is invoked as expected for each of +# synchronous=off, synchronous=normal and synchronous=full. +# +foreach {tn syncmode synccount} { + 1 off + {} + 2 normal + {test.db-wal normal test.db normal} + 3 full + {test.db-wal normal test.db-wal normal test.db-wal normal test.db normal} +} { + + proc sync_counter {args} { + foreach {method filename id flags} $args break + lappend ::syncs [file tail $filename] $flags + } + do_test wal3-3.$tn { + forcedelete test.db test.db-wal test.db-journal + + testvfs T + T filter {} + T script sync_counter + sqlite3 db test.db -vfs T + + execsql "PRAGMA synchronous = $syncmode" + execsql { PRAGMA journal_mode = WAL } + execsql { CREATE TABLE filler(a,b,c); } + + set ::syncs [list] + T filter xSync + execsql { + CREATE TABLE x(y); + INSERT INTO x VALUES('z'); + PRAGMA wal_checkpoint; + } + T filter {} + set ::syncs + } $synccount + + db close + T delete +} + +#------------------------------------------------------------------------- +# When recovering the contents of a WAL file, a process obtains the WRITER +# lock, then locks all other bytes before commencing recovery. If it fails +# to lock all other bytes (because some other process is holding a read +# lock) it should retry up to 100 times. Then return SQLITE_PROTOCOL to the +# caller. Test this (test case wal3-4.3). +# +# Also test the effect of hitting an SQLITE_BUSY while attempting to obtain +# the WRITER lock (should be the same). Test case wal3-4.4. +# +proc lock_callback {method filename handle lock} { + lappend ::locks $lock +} +do_test wal3-4.1 { + testvfs T + T filter xShmLock + T script lock_callback + set ::locks [list] + sqlite3 db test.db -vfs T + execsql { SELECT * FROM x } + lrange $::locks 0 3 +} [list {0 1 lock exclusive} {1 7 lock exclusive} \ + {1 7 unlock exclusive} {0 1 unlock exclusive} \ +] +do_test wal3-4.2 { + db close + set ::locks [list] + sqlite3 db test.db -vfs T + execsql { SELECT * FROM x } + lrange $::locks 0 3 +} [list {0 1 lock exclusive} {1 7 lock exclusive} \ + {1 7 unlock exclusive} {0 1 unlock exclusive} \ +] +proc lock_callback {method filename handle lock} { + if {$lock == "1 7 lock exclusive"} { return SQLITE_BUSY } + return SQLITE_OK +} +puts " Warning: This next test case causes SQLite to call xSleep(1) 100 times." +puts " Normally this equates to a 100ms delay, but if SQLite is built on unix" +puts " without HAVE_USLEEP defined, it may be 100 seconds." +do_test wal3-4.3 { + db close + set ::locks [list] + sqlite3 db test.db -vfs T + catchsql { SELECT * FROM x } +} {1 {locking protocol}} + +puts " Warning: Same again!" +proc lock_callback {method filename handle lock} { + if {$lock == "0 1 lock exclusive"} { return SQLITE_BUSY } + return SQLITE_OK +} +do_test wal3-4.4 { + db close + set ::locks [list] + sqlite3 db test.db -vfs T + catchsql { SELECT * FROM x } +} {1 {locking protocol}} +db close +T delete + + +#------------------------------------------------------------------------- +# Only one client may run recovery at a time. Test this mechanism. +# +# When client-2 tries to open a read transaction while client-1 is +# running recovery, it fails to obtain a lock on an aReadMark[] slot +# (because they are all locked by recovery). It then tries to obtain +# a shared lock on the RECOVER lock to see if there really is a +# recovery running or not. +# +# This block of tests checks the effect of an SQLITE_BUSY or SQLITE_IOERR +# being returned when client-2 attempts a shared lock on the RECOVER byte. +# +# An SQLITE_BUSY should be converted to an SQLITE_BUSY_RECOVERY. An +# SQLITE_IOERR should be returned to the caller. +# +do_test wal3-5.1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + } + faultsim_save_and_close +} {} + +testvfs T -default 1 +T script method_callback + +proc method_callback {method args} { + if {$method == "xShmBarrier"} { + incr ::barrier_count + if {$::barrier_count == 2} { + # This code is executed within the xShmBarrier() callback invoked + # by the client running recovery as part of writing the recovered + # wal-index header. If a second client attempts to access the + # database now, it reads a corrupt (partially written) wal-index + # header. But it cannot even get that far, as the first client + # is still holding all the locks (recovery takes an exclusive lock + # on *all* db locks, preventing access by any other client). + # + # If global variable ::wal3_do_lockfailure is non-zero, then set + # things up so that an IO error occurs within an xShmLock() callback + # made by the second client (aka [db2]). + # + sqlite3 db2 test.db + if { $::wal3_do_lockfailure } { T filter xShmLock } + set ::testrc [ catch { db2 eval "SELECT * FROM t1" } ::testmsg ] + T filter {} + db2 close + } + } + + if {$method == "xShmLock"} { + foreach {file handle spec} $args break + if { $spec == "2 1 lock shared" } { + return SQLITE_IOERR + } + } + + return SQLITE_OK +} + +# Test a normal SQLITE_BUSY return. +# +T filter xShmBarrier +set testrc "" +set testmsg "" +set barrier_count 0 +set wal3_do_lockfailure 0 +do_test wal3-5.2 { + faultsim_restore_and_reopen + execsql { SELECT * FROM t1 } +} {1 2 3 4} +do_test wal3-5.3 { + list $::testrc $::testmsg +} {1 {database is locked}} +db close + +# Test an SQLITE_IOERR return. +# +T filter xShmBarrier +set barrier_count 0 +set wal3_do_lockfailure 1 +set testrc "" +set testmsg "" +do_test wal3-5.4 { + faultsim_restore_and_reopen + execsql { SELECT * FROM t1 } +} {1 2 3 4} +do_test wal3-5.5 { + list $::testrc $::testmsg +} {1 {disk I/O error}} + +db close +T delete + +#------------------------------------------------------------------------- +# When opening a read-transaction on a database, if the entire log has +# already been copied to the database file, the reader grabs a special +# kind of read lock (on aReadMark[0]). This set of test cases tests the +# outcome of the following: +# +# + The reader discovering that between the time when it determined +# that the log had been completely backfilled and the lock is obtained +# that a writer has written to the log. In this case the reader should +# acquire a different read-lock (not aReadMark[0]) and read the new +# snapshot. +# +# + The attempt to obtain the lock on aReadMark[0] fails with SQLITE_BUSY. +# This can happen if a checkpoint is ongoing. In this case also simply +# obtain a different read-lock. +# +catch {db close} +testvfs T -default 1 +do_test wal3-6.1.1 { + forcedelete test.db test.db-journal test.db wal + sqlite3 db test.db + execsql { PRAGMA auto_vacuum = off } + execsql { PRAGMA journal_mode = WAL } + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('o', 't'); + INSERT INTO t1 VALUES('t', 'f'); + } +} {} +do_test wal3-6.1.2 { + sqlite3 db2 test.db + sqlite3 db3 test.db + execsql { BEGIN ; SELECT * FROM t1 } db3 +} {o t t f} +do_test wal3-6.1.3 { + execsql { PRAGMA wal_checkpoint } db2 +} {0 4 4} + +# At this point the log file has been fully checkpointed. However, +# connection [db3] holds a lock that prevents the log from being wrapped. +# Test case 3.6.1.4 has [db] attempt a read-lock on aReadMark[0]. But +# as it is obtaining the lock, [db2] appends to the log file. +# +T filter xShmLock +T script lock_callback +proc lock_callback {method file handle spec} { + if {$spec == "3 1 lock shared"} { + # This is the callback for [db] to obtain the read lock on aReadMark[0]. + # Disable future callbacks using [T filter {}] and write to the log + # file using [db2]. [db3] is preventing [db2] from wrapping the log + # here, so this is an append. + T filter {} + db2 eval { INSERT INTO t1 VALUES('f', 's') } + } + return SQLITE_OK +} +do_test wal3-6.1.4 { + execsql { + BEGIN; + SELECT * FROM t1; + } +} {o t t f f s} + +# [db] should be left holding a read-lock on some slot other than +# aReadMark[0]. Test this by demonstrating that the read-lock is preventing +# the log from being wrapped. +# +do_test wal3-6.1.5 { + db3 eval COMMIT + db2 eval { PRAGMA wal_checkpoint } + set sz1 [file size test.db-wal] + db2 eval { INSERT INTO t1 VALUES('s', 'e') } + set sz2 [file size test.db-wal] + expr {$sz2>$sz1} +} {1} + +# Test that if [db2] had not interfered when [db] was trying to grab +# aReadMark[0], it would have been possible to wrap the log in 3.6.1.5. +# +do_test wal3-6.1.6 { + execsql { COMMIT } + execsql { PRAGMA wal_checkpoint } db2 + execsql { + BEGIN; + SELECT * FROM t1; + } +} {o t t f f s s e} +do_test wal3-6.1.7 { + db2 eval { PRAGMA wal_checkpoint } + set sz1 [file size test.db-wal] + db2 eval { INSERT INTO t1 VALUES('n', 't') } + set sz2 [file size test.db-wal] + expr {$sz2==$sz1} +} {1} + +db3 close +db2 close +db close + +do_test wal3-6.2.1 { + forcedelete test.db test.db-journal test.db wal + sqlite3 db test.db + sqlite3 db2 test.db + execsql { PRAGMA auto_vacuum = off } + execsql { PRAGMA journal_mode = WAL } + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('h', 'h'); + INSERT INTO t1 VALUES('l', 'b'); + } +} {} + +T filter xShmLock +T script lock_callback +proc lock_callback {method file handle spec} { + if {$spec == "3 1 unlock exclusive"} { + T filter {} + set ::R [db2 eval { + BEGIN; + SELECT * FROM t1; + }] + } +} +do_test wal3-6.2.2 { + execsql { PRAGMA wal_checkpoint } +} {0 4 4} +do_test wal3-6.2.3 { + set ::R +} {h h l b} +do_test wal3-6.2.4 { + set sz1 [file size test.db-wal] + execsql { INSERT INTO t1 VALUES('b', 'c'); } + set sz2 [file size test.db-wal] + expr {$sz2 > $sz1} +} {1} +do_test wal3-6.2.5 { + db2 eval { COMMIT } + execsql { PRAGMA wal_checkpoint } + set sz1 [file size test.db-wal] + execsql { INSERT INTO t1 VALUES('n', 'o'); } + set sz2 [file size test.db-wal] + expr {$sz2 == $sz1} +} {1} + +db2 close +db close +T delete + +#------------------------------------------------------------------------- +# When opening a read-transaction on a database, if the entire log has +# not yet been copied to the database file, the reader grabs a read +# lock on aReadMark[x], where x>0. The following test cases experiment +# with the outcome of the following: +# +# + The reader discovering that between the time when it read the +# wal-index header and the lock was obtained that a writer has +# written to the log. In this case the reader should re-read the +# wal-index header and lock a snapshot corresponding to the new +# header. +# +# + The value in the aReadMark[x] slot has been modified since it was +# read. +# +catch {db close} +testvfs T -default 1 +do_test wal3-7.1.1 { + forcedelete test.db test.db-journal test.db wal + sqlite3 db test.db + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE blue(red PRIMARY KEY, green); + } +} {wal} + +T script method_callback +T filter xOpen +proc method_callback {method args} { + if {$method == "xOpen"} { return "reader" } +} +do_test wal3-7.1.2 { + sqlite3 db2 test.db + execsql { SELECT * FROM blue } db2 +} {} + +T filter xShmLock +set ::locks [list] +proc method_callback {method file handle spec} { + if {$handle != "reader" } { return } + if {$method == "xShmLock"} { + catch { execsql { INSERT INTO blue VALUES(1, 2) } } + catch { execsql { INSERT INTO blue VALUES(3, 4) } } + } + lappend ::locks $spec +} +do_test wal3-7.1.3 { + execsql { SELECT * FROM blue } db2 +} {1 2 3 4} +do_test wal3-7.1.4 { + set ::locks +} {{4 1 lock shared} {4 1 unlock shared} {5 1 lock shared} {5 1 unlock shared}} + +set ::locks [list] +proc method_callback {method file handle spec} { + if {$handle != "reader" } { return } + if {$method == "xShmLock"} { + catch { execsql { INSERT INTO blue VALUES(5, 6) } } + } + lappend ::locks $spec +} +do_test wal3-7.2.1 { + execsql { SELECT * FROM blue } db2 +} {1 2 3 4 5 6} +do_test wal3-7.2.2 { + set ::locks +} {{5 1 lock shared} {5 1 unlock shared} {4 1 lock shared} {4 1 unlock shared}} + +db close +db2 close +T delete + +#------------------------------------------------------------------------- +# +do_test wal3-8.1 { + forcedelete test.db test.db-journal test.db wal + sqlite3 db test.db + sqlite3 db2 test.db + execsql { + PRAGMA auto_vacuum = off; + PRAGMA journal_mode = WAL; + CREATE TABLE b(c); + INSERT INTO b VALUES('Tehran'); + INSERT INTO b VALUES('Qom'); + INSERT INTO b VALUES('Markazi'); + PRAGMA wal_checkpoint; + } +} {wal 0 5 5} +do_test wal3-8.2 { + execsql { SELECT * FROM b } +} {Tehran Qom Markazi} +do_test wal3-8.3 { + db eval { SELECT * FROM b } { + db eval { INSERT INTO b VALUES('Qazvin') } + set r [db2 eval { SELECT * FROM b }] + break + } + set r +} {Tehran Qom Markazi Qazvin} +do_test wal3-8.4 { + execsql { + INSERT INTO b VALUES('Gilan'); + INSERT INTO b VALUES('Ardabil'); + } +} {} +db2 close + +faultsim_save_and_close +testvfs T -default 1 +faultsim_restore_and_reopen +T filter xShmLock +T script lock_callback + +proc lock_callback {method file handle spec} { + if {$spec == "1 7 unlock exclusive"} { + T filter {} + set ::r [catchsql { SELECT * FROM b } db2] + } +} +sqlite3 db test.db +sqlite3 db2 test.db +do_test wal3-8.5 { + execsql { SELECT * FROM b } +} {Tehran Qom Markazi Qazvin Gilan Ardabil} +do_test wal3-8.6 { + set ::r +} {1 {locking protocol}} + +db close +db2 close + +faultsim_restore_and_reopen +sqlite3 db2 test.db +T filter xShmLock +T script lock_callback +proc lock_callback {method file handle spec} { + if {$spec == "1 7 unlock exclusive"} { + T filter {} + set ::r [catchsql { SELECT * FROM b } db2] + } +} +unset ::r +do_test wal3-8.5 { + execsql { SELECT * FROM b } +} {Tehran Qom Markazi Qazvin Gilan Ardabil} +do_test wal3-8.6 { + set ::r +} {1 {locking protocol}} + +db close +db2 close +T delete + +#------------------------------------------------------------------------- +# When a connection opens a read-lock on the database, it searches for +# an aReadMark[] slot that is already set to the mxFrame value for the +# new transaction. If it cannot find one, it attempts to obtain an +# exclusive lock on an aReadMark[] slot for the purposes of modifying +# the value, then drops back to a shared-lock for the duration of the +# transaction. +# +# This test case verifies that if an exclusive lock cannot be obtained +# on any aReadMark[] slot (because there are already several readers), +# the client takes a shared-lock on a slot without modifying the value +# and continues. +# +set nConn 50 +if { [string match *BSD $tcl_platform(os)] } { set nConn 25 } +do_test wal3-9.0 { + forcedelete test.db test.db-journal test.db wal + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + CREATE TABLE whoami(x); + INSERT INTO whoami VALUES('nobody'); + } +} {wal} +for {set i 0} {$i < $nConn} {incr i} { + set c db$i + do_test wal3-9.1.$i { + sqlite3 $c test.db + execsql { UPDATE whoami SET x = $c } + execsql { + BEGIN; + SELECT * FROM whoami + } $c + } $c +} +for {set i 0} {$i < $nConn} {incr i} { + set c db$i + do_test wal3-9.2.$i { + execsql { SELECT * FROM whoami } $c + } $c +} + +set sz [expr 1024 * (2+$AUTOVACUUM)] +do_test wal3-9.3 { + for {set i 0} {$i < ($nConn-1)} {incr i} { db$i close } + execsql { PRAGMA wal_checkpoint } + byte_is_zero test.db [expr $sz-1024] +} {1} +do_test wal3-9.4 { + db[expr $nConn-1] close + execsql { PRAGMA wal_checkpoint } + set sz2 [file size test.db] + byte_is_zero test.db [expr $sz-1024] +} {0} + +do_multiclient_test tn { + do_test wal3-10.$tn.1 { + sql1 { + PRAGMA page_size = 1024; + CREATE TABLE t1(x); + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 100000; + BEGIN; + INSERT INTO t1 VALUES(randomblob(800)); + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 2 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 4 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 8 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 16 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 32 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 64 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 128 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 256 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 512 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 1024 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 2048 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 4096 + INSERT INTO t1 SELECT randomblob(800) FROM t1; -- 8192 + COMMIT; + CREATE INDEX i1 ON t1(x); + } + + expr {[file size test.db-wal] > [expr 1032*9000]} + } 1 + + do_test wal3-10.$tn.2 { + sql2 {PRAGMA integrity_check} + } {ok} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wal4.test b/components/external/SQLite-3.8.1/test/wal4.test new file mode 100644 index 0000000000000000000000000000000000000000..c7a4381341741db00f2f2a026a4230f48b543b79 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal4.test @@ -0,0 +1,64 @@ +# 2010 July 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# Verify that an empty database and a non-empty WAL file do not +# result in database corruption +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +ifcapable !wal {finish_test ; return } + +do_test wal4-1.1 { + execsql { + PRAGMA journal_mode=WAL; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + SELECT x FROM t1 ORDER BY x; + } +} {wal 1 2} + +do_test wal4-1.2 { + # Save a copy of the file-system containing the wal and wal-index files + # only (no database file). + faultsim_save_and_close + forcedelete sv_test.db +} {} + +do_test wal4-1.3 { + faultsim_restore_and_reopen + catchsql { SELECT * FROM t1 } +} {1 {no such table: t1}} + +do_faultsim_test wal4-2 -prep { + faultsim_restore_and_reopen +} -body { + execsql { SELECT name FROM sqlite_master } +} -test { + # Result should be zero rows (empty db file). + # + faultsim_test_result {0 {}} + + # If the SELECT finished successfully, the WAL file should have been + # deleted. In no case should the database file have been written, so + # it should still be zero bytes in size regardless of whether or not + # a fault was injected. Test these assertions: + # + if { $testrc==0 && [file exists test.db-wal] } { + error "Wal file was not deleted" + } + if { [file size test.db]!=0 } { + error "Db file grew to [file size test.db] bytes" + } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wal5.test b/components/external/SQLite-3.8.1/test/wal5.test new file mode 100644 index 0000000000000000000000000000000000000000..68750f1479d8eb4061a9ead52a6a28c580233103 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal5.test @@ -0,0 +1,354 @@ +# 2010 April 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of "blocking-checkpoint" +# operations. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/wal_common.tcl +ifcapable !wal {finish_test ; return } + +set testprefix wal5 + +proc db_page_count {{file test.db}} { expr [file size $file] / 1024 } +proc wal_page_count {{file test.db}} { wal_frame_count ${file}-wal 1024 } + + +# A checkpoint may be requested either using the C API or by executing +# an SQL PRAGMA command. To test both methods, all tests in this file are +# run twice - once using each method to request checkpoints. +# +foreach {testprefix do_wal_checkpoint} { + + wal5-pragma { + proc do_wal_checkpoint { dbhandle args } { + array set a $args + foreach key [array names a] { + if {[lsearch {-mode -db} $key]<0} { error "unknown switch: $key" } + } + + set sql "PRAGMA " + if {[info exists a(-db)]} { append sql "$a(-db)." } + append sql "wal_checkpoint" + if {[info exists a(-mode)]} { append sql " = $a(-mode)" } + + uplevel [list $dbhandle eval $sql] + } + } + + wal5-capi { + proc do_wal_checkpoint { dbhandle args } { + set a(-mode) passive + array set a $args + foreach key [array names a] { + if {[lsearch {-mode -db} $key]<0} { error "unknown switch: $key" } + } + + if {$a(-mode)!="restart" && $a(-mode)!="full"} { set a(-mode) passive } + + set cmd [list sqlite3_wal_checkpoint_v2 $dbhandle $a(-mode)] + if {[info exists a(-db)]} { lappend sql $a(-db) } + + uplevel $cmd + } + } +} { + + eval $do_wal_checkpoint + + do_multiclient_test tn { + + set ::nBusyHandler 0 + set ::busy_handler_script "" + proc busyhandler {n} { + incr ::nBusyHandler + eval $::busy_handler_script + return 0 + } + + proc reopen_all {} { + code1 {db close} + code2 {db2 close} + code3 {db3 close} + + code1 {sqlite3 db test.db} + code2 {sqlite3 db2 test.db} + code3 {sqlite3 db3 test.db} + + sql1 { PRAGMA synchronous = NORMAL } + code1 { db busy busyhandler } + } + + do_test 1.$tn.1 { + reopen_all + sql1 { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + CREATE TABLE t1(x, y); + PRAGMA journal_mode = WAL; + INSERT INTO t1 VALUES(1, zeroblob(1200)); + INSERT INTO t1 VALUES(2, zeroblob(1200)); + INSERT INTO t1 VALUES(3, zeroblob(1200)); + } + expr [file size test.db] / 1024 + } {2} + + # Have connection 2 grab a read-lock on the current snapshot. + do_test 1.$tn.2 { sql2 { BEGIN; SELECT x FROM t1 } } {1 2 3} + + # Attempt a checkpoint. + do_test 1.$tn.3 { + code1 { do_wal_checkpoint db } + list [db_page_count] [wal_page_count] + } {5 9} + + # Write to the db again. The log cannot wrap because of the lock still + # held by connection 2. The busy-handler has not yet been invoked. + do_test 1.$tn.4 { + sql1 { INSERT INTO t1 VALUES(4, zeroblob(1200)) } + list [db_page_count] [wal_page_count] $::nBusyHandler + } {5 12 0} + + # Now do a blocking-checkpoint. Set the busy-handler up so that connection + # 2 releases its lock on the 6th invocation. The checkpointer should then + # proceed to checkpoint the entire log file. Next write should go to the + # start of the log file. + # + set ::busy_handler_script { if {$n==5} { sql2 COMMIT } } + do_test 1.$tn.5 { + code1 { do_wal_checkpoint db -mode restart } + list [db_page_count] [wal_page_count] $::nBusyHandler + } {6 12 6} + do_test 1.$tn.6 { + set ::nBusyHandler 0 + sql1 { INSERT INTO t1 VALUES(5, zeroblob(1200)) } + list [db_page_count] [wal_page_count] $::nBusyHandler + } {6 12 0} + + do_test 1.$tn.7 { + reopen_all + list [db_page_count] [wal_page_count] $::nBusyHandler + } {7 0 0} + + do_test 1.$tn.8 { sql2 { BEGIN ; SELECT x FROM t1 } } {1 2 3 4 5} + do_test 1.$tn.9 { + sql1 { INSERT INTO t1 VALUES(6, zeroblob(1200)) } + list [db_page_count] [wal_page_count] $::nBusyHandler + } {7 5 0} + do_test 1.$tn.10 { sql3 { BEGIN ; SELECT x FROM t1 } } {1 2 3 4 5 6} + + set ::busy_handler_script { + if {$n==5} { sql2 COMMIT } + if {$n==6} { set ::db_file_size [db_page_count] } + if {$n==7} { sql3 COMMIT } + } + do_test 1.$tn.11 { + code1 { do_wal_checkpoint db -mode restart } + list [db_page_count] [wal_page_count] $::nBusyHandler + } {10 5 8} + do_test 1.$tn.12 { set ::db_file_size } 10 + } + + #------------------------------------------------------------------------- + # This block of tests explores checkpoint operations on more than one + # database file. + # + proc setup_and_attach_aux {} { + sql1 { ATTACH 'test.db2' AS aux } + sql2 { ATTACH 'test.db2' AS aux } + sql3 { ATTACH 'test.db2' AS aux } + sql1 { + PRAGMA aux.auto_vacuum = 0; + PRAGMA main.auto_vacuum = 0; + PRAGMA main.page_size=1024; PRAGMA main.journal_mode=WAL; + PRAGMA aux.page_size=1024; PRAGMA aux.journal_mode=WAL; + } + } + + proc file_page_counts {} { + list [db_page_count test.db ] \ + [wal_page_count test.db ] \ + [db_page_count test.db2] \ + [wal_page_count test.db2] + } + + # Test that executing "PRAGMA wal_checkpoint" checkpoints all attached + # databases, not just the main db. In capi mode, check that this is + # true if a NULL pointer is passed to wal_checkpoint_v2() in place of a + # database name. + do_multiclient_test tn { + setup_and_attach_aux + do_test 2.1.$tn.1 { + sql1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + CREATE TABLE aux.t2(a, b); + INSERT INTO t2 VALUES(1, 2); + } + } {} + do_test 2.2.$tn.2 { file_page_counts } {1 3 1 3} + do_test 2.1.$tn.3 { code1 { do_wal_checkpoint db } } {0 3 3} + do_test 2.1.$tn.4 { file_page_counts } {2 3 2 3} + } + + do_multiclient_test tn { + setup_and_attach_aux + do_test 2.2.$tn.1 { + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + CREATE TABLE aux.t2(a, b); + INSERT INTO t2 VALUES(1, 2); + INSERT INTO t2 VALUES(3, 4); + } + } {} + do_test 2.2.$tn.2 { file_page_counts } {1 3 1 4} + do_test 2.2.$tn.3 { sql2 { BEGIN; SELECT * FROM t1 } } {1 2} + do_test 2.2.$tn.4 { code1 { do_wal_checkpoint db -mode restart } } {1 3 3} + do_test 2.2.$tn.5 { file_page_counts } {2 3 2 4} + } + + do_multiclient_test tn { + setup_and_attach_aux + do_test 2.3.$tn.1 { + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + CREATE TABLE aux.t2(a, b); + INSERT INTO t2 VALUES(1, 2); + } + } {} + do_test 2.3.$tn.2 { file_page_counts } {1 3 1 3} + do_test 2.3.$tn.3 { sql2 { BEGIN; SELECT * FROM t1 } } {1 2} + do_test 2.3.$tn.4 { sql1 { INSERT INTO t1 VALUES(3, 4) } } {} + do_test 2.3.$tn.5 { sql1 { INSERT INTO t2 VALUES(3, 4) } } {} + do_test 2.3.$tn.6 { file_page_counts } {1 4 1 4} + do_test 2.3.$tn.7 { code1 { do_wal_checkpoint db -mode full } } {1 4 3} + + # The checkpoint above only writes page 1 of the db file. The other + # page (page 2) is locked by the read-transaction opened by the + # [sql2] commmand above. So normally, the db is 1 page in size here. + # However, in mmap() mode, the db is pre-allocated to 2 pages at the + # start of the checkpoint, even though page 2 cannot be written. + set nDb 2 + if {[permutation]!="mmap"} {set nDb 1} + ifcapable !mmap {set nDb 1} + do_test 2.3.$tn.8 { file_page_counts } [list $nDb 4 2 4] + } + + # Check that checkpoints block on the correct locks. And respond correctly + # if they cannot obtain those locks. There are three locks that a checkpoint + # may block on (in the following order): + # + # 1. The writer lock: FULL and RESTART checkpoints block until any writer + # process releases its lock. + # + # 2. Readers using part of the log file. FULL and RESTART checkpoints block + # until readers using part (but not all) of the log file have finished. + # + # 3. Readers using any of the log file. After copying data into the + # database file, RESTART checkpoints block until readers using any part + # of the log file have finished. + # + # This test case involves running a checkpoint while there exist other + # processes holding all three types of locks. + # + foreach {tn1 checkpoint busy_on ckpt_expected expected} { + 1 PASSIVE - {0 3 3} - + 2 TYPO - {0 3 3} - + + 3 FULL - {0 4 4} 2 + 4 FULL 1 {1 3 3} 1 + 5 FULL 2 {1 4 3} 2 + 6 FULL 3 {0 4 4} 2 + + 7 RESTART - {0 4 4} 3 + 8 RESTART 1 {1 3 3} 1 + 9 RESTART 2 {1 4 3} 2 + 10 RESTART 3 {1 4 4} 3 + + } { + do_multiclient_test tn { + setup_and_attach_aux + + proc busyhandler {x} { + set ::max_busyhandler $x + if {$::busy_on!="-" && $x==$::busy_on} { return 1 } + switch -- $x { + 1 { sql2 "COMMIT ; BEGIN ; SELECT * FROM t1" } + 2 { sql3 "COMMIT" } + 3 { sql2 "COMMIT" } + } + return 0 + } + set ::max_busyhandler - + + do_test 2.4.$tn1.$tn.1 { + sql1 { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } + sql2 { BEGIN; INSERT INTO t1 VALUES(3, 4) } + sql3 { BEGIN; SELECT * FROM t1 } + } {1 2} + + do_test 2.4.$tn1.$tn.2 { + code1 { db busy busyhandler } + code1 { do_wal_checkpoint db -mode [string tolower $checkpoint] } + } $ckpt_expected + do_test 2.4.$tn1.$tn.3 { set ::max_busyhandler } $expected + } + } + + + do_multiclient_test tn { + + code1 $do_wal_checkpoint + code2 $do_wal_checkpoint + code3 $do_wal_checkpoint + + do_test 3.$tn.1 { + sql1 { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + PRAGMA synchronous = normal; + CREATE TABLE t1(x, y); + } + + sql2 { PRAGMA journal_mode } + sql3 { PRAGMA journal_mode } + } {wal} + + do_test 3.$tn.2 { code2 { do_wal_checkpoint db2 } } {0 2 2} + + do_test 3.$tn.3 { code2 { do_wal_checkpoint db2 } } {0 2 2} + + do_test 3.$tn.4 { code3 { do_wal_checkpoint db3 } } {0 2 2} + + code1 {db close} + code2 {db2 close} + code3 {db3 close} + + code1 {sqlite3 db test.db} + code2 {sqlite3 db2 test.db} + code3 {sqlite3 db3 test.db} + + do_test 3.$tn.5 { sql3 { PRAGMA journal_mode } } {wal} + + do_test 3.$tn.6 { code3 { do_wal_checkpoint db3 } } {0 0 0} + } +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wal6.test b/components/external/SQLite-3.8.1/test/wal6.test new file mode 100644 index 0000000000000000000000000000000000000000..2498907ea908549f9ecc636b0ba1ba3170565fa3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal6.test @@ -0,0 +1,197 @@ +# 2010 December 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. +# + +set testdir [file dirname $argv0] +set testprefix wal6 +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/wal_common.tcl +source $testdir/malloc_common.tcl +ifcapable !wal {finish_test ; return } + +#------------------------------------------------------------------------- +# Changing to WAL mode in one connection forces the change in others. +# +db close +forcedelete test.db + +set all_journal_modes {delete persist truncate memory off} +foreach jmode $all_journal_modes { + + do_test wal6-1.0.$jmode { + sqlite3 db test.db + execsql "PRAGMA journal_mode = $jmode;" + } $jmode + + do_test wal6-1.1.$jmode { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b); + INSERT INTO t1 VALUES(1,2); + SELECT * FROM t1; + } + } {1 2} + +# Under Windows, you'll get an error trying to delete +# a file this is already opened. Close the first connection +# so the other tests work. +if {$tcl_platform(platform)=="windows"} { + if {$jmode=="persist" || $jmode=="truncate"} { + db close + } +} + + do_test wal6-1.2.$jmode { + sqlite3 db2 test.db + execsql { + PRAGMA journal_mode=WAL; + INSERT INTO t1 VALUES(3,4); + SELECT * FROM t1 ORDER BY a; + } db2 + } {wal 1 2 3 4} + +if {$tcl_platform(platform)=="windows"} { + if {$jmode=="persist" || $jmode=="truncate"} { + sqlite3 db test.db + } +} + + do_test wal6-1.3.$jmode { + execsql { + SELECT * FROM t1 ORDER BY a; + } + } {1 2 3 4} + + db close + db2 close + forcedelete test.db + +} + +#------------------------------------------------------------------------- +# Test that SQLITE_BUSY_SNAPSHOT is returned as expected. +# +reset_db +sqlite3 db2 test.db + +do_execsql_test 2.1 { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a PRIMARY KEY, b TEXT); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + BEGIN; + SELECT * FROM t1; +} {wal 1 one 2 two} + +do_test 2.2 { + execsql { + SELECT * FROM t1; + INSERT INTO t1 VALUES(3, 'three'); + } db2 +} {1 one 2 two} + +do_catchsql_test 2.3 { + INSERT INTO t1 VALUES('x', 'x') +} {1 {database is locked}} + +do_test 2.4 { + list [sqlite3_errcode db] [sqlite3_extended_errcode db] +} {SQLITE_BUSY SQLITE_BUSY_SNAPSHOT} + +do_execsql_test 2.5 { + SELECT * FROM t1; + COMMIT; + INSERT INTO t1 VALUES('x', 'x') +} {1 one 2 two} + +proc test3 {prefix} { + do_test $prefix.1 { + execsql { SELECT count(*) FROM t1 } + } {0} + do_test $prefix.2 { + execsql { INSERT INTO t1 VALUES('x', 'x') } db2 + } {} + do_test $prefix.3 { + execsql { INSERT INTO t1 VALUES('y', 'y') } + } {} + do_test $prefix.4 { + execsql { SELECT count(*) FROM t1 } + } {2} +} + +do_execsql_test 2.6.1 { DELETE FROM t1 } +test3 2.6.2 + +db func test3 test3 +do_execsql_test 2.6.3 { DELETE FROM t1 } +db eval {SELECT test3('2.6.4')} + +do_test 2.x { + db2 close +} {} + +#------------------------------------------------------------------------- +# Check that if BEGIN IMMEDIATE fails, it does not leave the user with +# an open read-transaction (unless one was already open before the BEGIN +# IMMEDIATE). Even if there are other active VMs. +# + +proc test4 {prefix} { + do_test $prefix.1 { + catchsql { BEGIN IMMEDIATE } + } {1 {database is locked}} + + do_test $prefix.2 { + execsql { COMMIT } db2 + } {} + + do_test $prefix.3 { + execsql { BEGIN IMMEDIATE } + } {} + do_test $prefix.4 { + execsql { COMMIT } + } {} +} + +reset_db +sqlite3 db2 test.db +do_execsql_test 3.1 { + PRAGMA journal_mode = WAL; + CREATE TABLE ab(a PRIMARY KEY, b); +} {wal} + +do_test 3.2.1 { + execsql { + BEGIN; + INSERT INTO ab VALUES(1, 2); + } db2 +} {} +test4 3.2.2 + +db func test4 test4 +do_test 3.3.1 { + execsql { + BEGIN; + INSERT INTO ab VALUES(3, 4); + } db2 +} {} + +db eval {SELECT test4('3.3.2')} + +do_test 3.x { + db2 close +} {} + +finish_test + diff --git a/components/external/SQLite-3.8.1/test/wal7.test b/components/external/SQLite-3.8.1/test/wal7.test new file mode 100644 index 0000000000000000000000000000000000000000..cacfaedacb57f679395f73d89280d49a07ed9693 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal7.test @@ -0,0 +1,118 @@ +# 2011 May 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the PRAGMA journal_size_limit when +# in WAL mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !wal {finish_test ; return } + +# Case 1: No size limit. Journal can get large. +# +do_test wal7-1.0 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA page_size=1024; + PRAGMA journal_mode=WAL; + PRAGMA wal_autocheckpoint=50; -- 50 pages + CREATE TABLE t1(x, y UNIQUE); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(zeroblob(200000),4); + CREATE TABLE t2(z); + DELETE FROM t1; + INSERT INTO t2 SELECT x FROM t1; + } + expr {[file size test.db-wal]>50*1100} +} 1 +do_test wal7-1.1 { + db eval {PRAGMA wal_checkpoint} + expr {[file size test.db-wal]>50*1100} +} 1 +do_test wal7-1.2 { + db eval {INSERT INTO t2 VALUES('hi');} + expr {[file size test.db-wal]>50*1100} +} 1 + +# Case 2: Size limit at half the autocheckpoint size. +# +do_test wal7-2.0 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA page_size=1024; + PRAGMA journal_mode=WAL; + PRAGMA wal_autocheckpoint=50; -- 50 pages + PRAGMA journal_size_limit=25000; + CREATE TABLE t1(x, y UNIQUE); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(zeroblob(200000),4); + CREATE TABLE t2(z); + DELETE FROM t1; + INSERT INTO t2 VALUES(1); + } + file size test.db-wal +} 25000 + + +# Case 3: Size limit of zero. +# +do_test wal7-3.0 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA page_size=1024; + PRAGMA journal_mode=WAL; + PRAGMA wal_autocheckpoint=50; -- 50 pages + PRAGMA journal_size_limit=0; + CREATE TABLE t1(x, y UNIQUE); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(zeroblob(200000),4); + CREATE TABLE t2(z); + DELETE FROM t1; + INSERT INTO t2 VALUES(1); + } + set sz [file size test.db-wal] + expr {$sz>0 && $sz<13700} +} 1 + + +# Case 4: Size limit set before going WAL +# +do_test wal7-4.0 { + db close + forcedelete test.db + sqlite3 db test.db + db eval { + PRAGMA page_size=1024; + PRAGMA journal_size_limit=25000; + PRAGMA journal_mode=WAL; + PRAGMA wal_autocheckpoint=50; -- 50 pages + CREATE TABLE t1(x, y UNIQUE); + INSERT INTO t1 VALUES(1,2); + INSERT INTO t1 VALUES(zeroblob(200000),4); + CREATE TABLE t2(z); + DELETE FROM t1; + INSERT INTO t2 VALUES(1); + } + set sz [file size test.db-wal] +} 25000 + + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wal8.test b/components/external/SQLite-3.8.1/test/wal8.test new file mode 100644 index 0000000000000000000000000000000000000000..0682fce35bdb8b5cb01f51b95da9ab64ef844921 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal8.test @@ -0,0 +1,90 @@ +# 2012 February 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. +# +# Specifically, it tests the case where a connection opens an empty +# file. Then, another connection opens the same file and initializes +# the connection as a WAL database. Following this, the first connection +# executes a "PRAGMA page_size = XXX" command to set its expected page +# size, and then queries the database. +# +# This is an unusual case, as normally SQLite is able to glean the page +# size from the database file as soon as it is opened (even before the +# first read transaction is executed), and the "PRAGMA page_size = XXX" +# is a no-op. +# +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix wal8 +ifcapable !wal {finish_test ; return } + +db close +forcedelete test.db test.db-wal + +sqlite3 db test.db +sqlite3 db2 test.db + +do_test 1.0 { + execsql { + PRAGMA journal_mode = wal; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } db2 +} {wal} + +do_catchsql_test 1.1 { + PRAGMA page_size = 4096; + VACUUM; +} {0 {}} + +db close +db2 close +forcedelete test.db test.db-wal + +sqlite3 db test.db +sqlite3 db2 test.db + +do_test 2.0 { + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + PRAGMA journal_mode = wal; + } db2 +} {wal} + +do_catchsql_test 2.1 { + PRAGMA page_size = 4096; + VACUUM; +} {0 {}} + +db close +db2 close +forcedelete test.db test.db-wal + +sqlite3 db test.db +sqlite3 db2 test.db + +do_test 3.0 { + execsql { + PRAGMA journal_mode = wal; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + } db2 +} {wal} + +do_execsql_test 3.1 { + PRAGMA page_size = 4096; + SELECT name FROM sqlite_master; +} {t1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wal9.test b/components/external/SQLite-3.8.1/test/wal9.test new file mode 100644 index 0000000000000000000000000000000000000000..ae2a52bb02a783c64673aa5ee458f25a77420b78 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal9.test @@ -0,0 +1,94 @@ +# 2012 October 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test case tests that a problem causing a failing assert() has +# been fixed. The problem occurred if a writer process with a subset +# of the *shm file mapped rolled back a transaction begun after the +# entire WAL file was checkpointed into the db file (i.e. a transaction +# that would have restarted the WAL file from the beginning). +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix wal9 + +sqlite3 db2 test.db + +do_execsql_test 1.0 { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 0; + CREATE TABLE t(x); +} {wal 0} + +do_test 1.1 { + execsql "SELECT * FROM t" db2 +} {} + +do_execsql_test 1.2 { + BEGIN; + INSERT INTO t VALUES(randomblob(100)); + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + + INSERT INTO t SELECT randomblob(100) FROM t; + INSERT INTO t SELECT randomblob(100) FROM t; + COMMIT; +} {} + +# Check file sizes are as expected. The real requirement here is that +# the *shm file is now more than one chunk (>32KiB). +# +# The sizes of various files are slightly different in normal and +# auto-vacuum mode. +do_test 1.3 { file size test.db } {1024} +do_test 1.4 { expr {[file size test.db-wal]>(1500*1024)} } {1} +do_test 1.5 { expr {[file size test.db-shm]>32768} } {1} +do_test 1.6 { + foreach {a b c} [db eval {PRAGMA wal_checkpoint}] break + list [expr {$a==0}] [expr {$b>14500}] [expr {$c>14500}] [expr {$b==$c}] +} {1 1 1 1} + +# At this point connection [db2] has mapped the first 32KB of the *shm file +# only. Because the entire WAL file has been checkpointed, it is not +# necessary to map any more of the *-shm file to read or write the database +# (since all data will be read directly from the db file). +# +# However, at one point if a transaction that had not yet written to the +# WAL file was rolled back an assert() attempting to verify that the entire +# *-shm file was mapped would fail. If NDEBUG was defined (and the assert() +# disabled) this bug caused SQLite to ignore the return code of a mmap() +# call. +# +do_test 1.7 { + execsql { + BEGIN; + INSERT INTO t VALUES('hello'); + ROLLBACK; + } db2 +} {} +db2 close + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wal_common.tcl b/components/external/SQLite-3.8.1/test/wal_common.tcl new file mode 100644 index 0000000000000000000000000000000000000000..917ad598f6307567d79c63f58b431e817acb8f61 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wal_common.tcl @@ -0,0 +1,93 @@ +# 2010 June 03 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains common code used by many different malloc tests +# within the test suite. +# + +proc wal_file_size {nFrame pgsz} { + expr {32 + ($pgsz+24)*$nFrame} +} + +proc wal_frame_count {zFile pgsz} { + if {[file exists $zFile]==0} { return 0 } + set f [file size $zFile] + if {$f < 32} { return 0 } + expr {($f - 32) / ($pgsz+24)} +} + +proc wal_cksum_intlist {ckv1 ckv2 intlist} { + upvar $ckv1 c1 + upvar $ckv2 c2 + foreach {v1 v2} $intlist { + set c1 [expr {($c1 + $v1 + $c2)&0xFFFFFFFF}] + set c2 [expr {($c2 + $v2 + $c1)&0xFFFFFFFF}] + } +} + + +# This proc calculates checksums in the same way as those used by SQLite +# in WAL files. If the $endian argument is "big", then checksums are +# calculated by interpreting data as an array of big-endian integers. If +# it is "little", data is interpreted as an array of little-endian integers. +# +proc wal_cksum {endian ckv1 ckv2 blob} { + upvar $ckv1 c1 + upvar $ckv2 c2 + + if {$endian!="big" && $endian!="little"} { + return -error "Bad value \"$endian\" - must be \"big\" or \"little\"" + } + set scanpattern I* + if {$endian == "little"} { set scanpattern i* } + + binary scan $blob $scanpattern values + wal_cksum_intlist c1 c2 $values +} + +proc wal_set_walhdr {filename {intlist {}}} { + if {[llength $intlist]==6} { + set blob [binary format I6 $intlist] + set endian little + if {[lindex $intlist 0] & 0x00000001} { set endian big } + set c1 0 + set c2 0 + wal_cksum $endian c1 c2 $blob + append blob [binary format II $c1 $c2] + + set fd [open $filename r+] + fconfigure $fd -translation binary + fconfigure $fd -encoding binary + seek $fd 0 + puts -nonewline $fd $blob + close $fd + } + + set fd [open $filename] + fconfigure $fd -translation binary + fconfigure $fd -encoding binary + set blob [read $fd 24] + close $fd + + binary scan $blob I6 ints + set ints +} + +proc wal_fix_walindex_cksum {hdrvar} { + upvar $hdrvar hdr + set c1 0 + set c2 0 + wal_cksum_intlist c1 c2 [lrange $hdr 0 9] + lset hdr 10 $c1 + lset hdr 11 $c2 +} + + diff --git a/components/external/SQLite-3.8.1/test/walbak.test b/components/external/SQLite-3.8.1/test/walbak.test new file mode 100644 index 0000000000000000000000000000000000000000..303a628a84bb9f39e83ae6adb63d3310e43fb360 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walbak.test @@ -0,0 +1,357 @@ +# 2010 April 22 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/wal_common.tcl +source $testdir/malloc_common.tcl + +do_not_use_codec + +ifcapable !wal {finish_test ; return } + + +# Test organization: +# +# walback-1.*: Simple tests. +# +# walback-2.*: Test backups when the source db is modified mid-backup. +# +# walback-3.*: Backup of WAL sources into rollback destinations, and +# vice-versa. +# + +# Make sure a simple backup from a WAL database works. +# +do_test walbak-1.0 { + execsql { + PRAGMA synchronous = NORMAL; + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = wal; + BEGIN; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES('I', 'one'); + COMMIT; + } +} {wal} +do_test walbak-1.1 { + forcedelete bak.db bak.db-journal bak.db-wal + db backup bak.db + file size bak.db +} [expr 3*1024] +do_test walbak-1.2 { + sqlite3 db2 bak.db + execsql { + SELECT * FROM t1; + PRAGMA main.journal_mode; + } db2 +} {I one wal} +do_test walbak-1.3 { + execsql { PRAGMA integrity_check } db2 +} {ok} +db2 close + +# Try a VACUUM on a WAL database. +# +do_test walbak-1.4 { + execsql { + VACUUM; + PRAGMA main.journal_mode; + } +} {wal} +do_test walbak-1.5 { + list [file size test.db] [file size test.db-wal] +} [list 1024 [wal_file_size 6 1024]] +do_test walbak-1.6 { + execsql { PRAGMA wal_checkpoint } + list [file size test.db] [file size test.db-wal] +} [list [expr 3*1024] [wal_file_size 6 1024]] +do_test walbak-1.6.1 { + hexio_read test.db 18 2 +} {0202} +do_test walbak-1.7 { + execsql { + CREATE TABLE t2(a, b); + INSERT INTO t2 SELECT * FROM t1; + DROP TABLE t1; + } + list [file size test.db] [file size test.db-wal] +} [list [expr 3*1024] [wal_file_size 6 1024]] +do_test walbak-1.8 { + execsql { VACUUM } + list [file size test.db] [file size test.db-wal] +} [list [expr 3*1024] [wal_file_size 8 1024]] +do_test walbak-1.9 { + execsql { PRAGMA wal_checkpoint } + list [file size test.db] [file size test.db-wal] +} [list [expr 2*1024] [wal_file_size 8 1024]] + +#------------------------------------------------------------------------- +# Backups when the source db is modified mid-backup. +# +proc sig {{db db}} { + $db eval { + PRAGMA integrity_check; + SELECT md5sum(a, b) FROM t1; + } +} +db close +delete_file test.db +sqlite3 db test.db +do_test walbak-2.1 { + execsql { PRAGMA journal_mode = WAL } + execsql { + CREATE TABLE t1(a PRIMARY KEY, b); + BEGIN; + INSERT INTO t1 VALUES(randomblob(500), randomblob(500)); + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; /* 2 */ + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; /* 4 */ + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; /* 8 */ + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; /* 16 */ + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; /* 32 */ + INSERT INTO t1 SELECT randomblob(500), randomblob(500) FROM t1; /* 64 */ + COMMIT; + } +} {} +do_test walbak-2.2 { + db backup abc.db + sqlite3 db2 abc.db + string compare [sig db] [sig db2] +} {0} + +do_test walbak-2.3 { + sqlite3_backup B db2 main db main + B step 50 + execsql { UPDATE t1 SET b = randomblob(500) } + list [B step 1000] [B finish] +} {SQLITE_DONE SQLITE_OK} +do_test walbak-2.4 { + string compare [sig db] [sig db2] +} {0} + +do_test walbak-2.5 { + db close + sqlite3 db test.db + execsql { PRAGMA cache_size = 10 } + sqlite3_backup B db2 main db main + B step 50 + execsql { + BEGIN; + UPDATE t1 SET b = randomblob(500); + } + expr [file size test.db-wal] > 10*1024 +} {1} +do_test walbak-2.6 { + B step 1000 +} {SQLITE_BUSY} +do_test walbak-2.7 { + execsql COMMIT + list [B step 1000] [B finish] +} {SQLITE_DONE SQLITE_OK} +do_test walbak-2.8 { + string compare [sig db] [sig db2] +} {0} + +do_test walbak-2.9 { + db close + sqlite3 db test.db + execsql { PRAGMA cache_size = 10 } + sqlite3_backup B db2 main db main + B step 50 + execsql { + BEGIN; + UPDATE t1 SET b = randomblob(500); + } + expr [file size test.db-wal] > 10*1024 +} {1} +do_test walbak-2.10 { + B step 1000 +} {SQLITE_BUSY} +do_test walbak-2.11 { + execsql ROLLBACK +set sigB [sig db] + list [B step 1000] [B finish] +} {SQLITE_DONE SQLITE_OK} +do_test walbak-2.12 { + string compare [sig db] [sig db2] +} {0} +db2 close +db close + +#------------------------------------------------------------------------- +# Run some backup operations to copy back and forth between WAL and: +# +# walbak-3.1.*: an in-memory database +# +# walbak-3.2.*: a temporary database +# +# walbak-3.3.*: a database in rollback mode. +# +# walbak-3.4.*: a database in rollback mode that (initially) uses a +# different page-size. +# +# Check that this does not confuse any connected clients. +# +foreach {tn setup} { + 1 { + sqlite3 db test.db + sqlite3 db2 :memory: + db eval { PRAGMA page_size = 1024 ; PRAGMA journal_mode = WAL } + db2 eval { PRAGMA page_size = 1024 } + } + + 2 { + sqlite3 db test.db + sqlite3 db2 "" + db eval { PRAGMA page_size = 1024 ; PRAGMA journal_mode = WAL } + db2 eval { PRAGMA page_size = 1024 } + } + + 3 { + sqlite3 db test.db + sqlite3 db2 test.db2 + db eval { PRAGMA page_size = 1024 ; PRAGMA journal_mode = WAL } + db2 eval { PRAGMA page_size = 1024 ; PRAGMA journal_mode = PERSIST } + } + + 4 { + sqlite3 db test.db + sqlite3 db2 test.db2 + db eval { PRAGMA page_size = 1024 ; PRAGMA journal_mode = WAL } + db2 eval { + PRAGMA page_size = 2048; + PRAGMA journal_mode = PERSIST; + CREATE TABLE xx(x); + } + } + +} { + foreach f [glob -nocomplain test.db*] { forcedelete $f } + + eval $setup + + do_test walbak-3.$tn.1 { + execsql { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + SELECT * FROM t1; + } + } {1 2 3 4} + + do_test walbak-3.$tn.2 { + sqlite3_backup B db2 main db main + B step 10000 + B finish + execsql { SELECT * FROM t1 } db2 + } {1 2 3 4} + + do_test walbak-3.$tn.3 { + execsql { + INSERT INTO t1 VALUES(5, 6); + INSERT INTO t1 VALUES(7, 8); + SELECT * FROM t1; + } db2 + } {1 2 3 4 5 6 7 8} + + do_test walbak-3.$tn.4 { + sqlite3_backup B db main db2 main + B step 10000 + B finish + execsql { SELECT * FROM t1 } + } {1 2 3 4 5 6 7 8} + + # Check that [db] is still in WAL mode. + do_test walbak-3.$tn.5 { + execsql { PRAGMA journal_mode } + } {wal} + do_test walbak-3.$tn.6 { + execsql { PRAGMA wal_checkpoint } + hexio_read test.db 18 2 + } {0202} + + # If it was not an in-memory database, check that [db2] is still in + # rollback mode. + if {[file exists test.db2]} { + do_test walbak-3.$tn.7 { + execsql { PRAGMA journal_mode } db2 + } {wal} + do_test walbak-3.$tn.8 { + execsql { PRAGMA wal_checkpoint } + hexio_read test.db 18 2 + } {0202} + } + + db close + db2 close +} + +#------------------------------------------------------------------------- +# Test that the following holds when a backup operation is run: +# +# Source | Destination inital | Destination final +# --------------------------------------------------- +# Rollback Rollback Rollback +# Rollback WAL WAL +# WAL Rollback WAL +# WAL WAL WAL +# +foreach {tn src dest dest_final} { + 1 delete delete delete + 2 delete wal wal + 3 wal delete wal + 4 wal wal wal +} { + catch { db close } + catch { db2 close } + forcedelete test.db test.db2 + + do_test walbak-4.$tn.1 { + sqlite3 db test.db + db eval "PRAGMA journal_mode = $src" + db eval { + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES('I', 'II'); + INSERT INTO t1 VALUES('III', 'IV'); + } + + sqlite3 db2 test.db2 + db2 eval "PRAGMA journal_mode = $dest" + db2 eval { + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES('1', '2'); + INSERT INTO t2 VALUES('3', '4'); + } + } {} + + do_test walbak-4.$tn.2 { execsql { PRAGMA journal_mode } db } $src + do_test walbak-4.$tn.3 { execsql { PRAGMA journal_mode } db2 } $dest + + do_test walbak-4.$tn.4 { db backup test.db2 } {} + do_test walbak-4.$tn.5 { + execsql { SELECT * FROM t1 } db2 + } {I II III IV} + do_test walbak-4.$tn.5 { execsql { PRAGMA journal_mode } db2 } $dest_final + + + db2 close + do_test walbak-4.$tn.6 { file exists test.db2-wal } 0 + sqlite3 db2 test.db2 + do_test walbak-4.$tn.7 { execsql { PRAGMA journal_mode } db2 } $dest_final +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walbig.test b/components/external/SQLite-3.8.1/test/walbig.test new file mode 100644 index 0000000000000000000000000000000000000000..c43b7e25033b691c05eaa5638d81e3745ef60c2e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walbig.test @@ -0,0 +1,78 @@ +# 2010 July 07 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script testing the ability of SQLite to handle database +# files larger than 4GB in WAL mode. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !wal { + finish_test + return +} + +# Do not use a codec for this file, as the database is manipulated using +# external methods (the [fake_big_file] and [hexio_write] commands). +# +do_not_use_codec + +# If SQLITE_DISABLE_LFS is defined, omit this file. +ifcapable !lfs { + finish_test + return +} + +set a_string_counter 1 +proc a_string {n} { + incr ::a_string_counter + string range [string repeat "${::a_string_counter}." $n] 1 $n +} +db func a_string a_string + +do_test walbig-1.0 { + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + INSERT INTO t1 VALUES(a_string(300), a_string(500)); + INSERT INTO t1 SELECT a_string(300), a_string(500) FROM t1; + INSERT INTO t1 SELECT a_string(300), a_string(500) FROM t1; + INSERT INTO t1 SELECT a_string(300), a_string(500) FROM t1; + } +} {wal} + +db close +if {[catch {fake_big_file 5000 [get_pwd]/test.db}]} { + puts "**** Unable to create a file larger than 5000 MB. *****" + finish_test + return +} +hexio_write test.db 28 00000000 + +sqlite3 db test.db +db func a_string a_string +do_test walbig-1.1 { + execsql { INSERT INTO t1 SELECT a_string(300), a_string(500) FROM t1 } +} {} +db close + +sqlite3 db test.db +do_test walbig-1.2 { + execsql { SELECT a FROM t1 ORDER BY a } +} [lsort [execsql { SELECT a FROM t1 ORDER BY rowid }]] + +do_test walbig-1.3 { + execsql { SELECT b FROM t1 ORDER BY b } +} [lsort [execsql { SELECT b FROM t1 ORDER BY rowid }]] + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walcksum.test b/components/external/SQLite-3.8.1/test/walcksum.test new file mode 100644 index 0000000000000000000000000000000000000000..3005a758acd1af0fbcf505991409524f2edf4ce6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walcksum.test @@ -0,0 +1,392 @@ +# 2010 May 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/wal_common.tcl + +ifcapable !wal {finish_test ; return } + +# Read and return the contents of file $filename. Treat the content as +# binary data. +# +proc readfile {filename} { + set fd [open $filename] + fconfigure $fd -encoding binary + fconfigure $fd -translation binary + set data [read $fd] + close $fd + return $data +} + +# +# File $filename must be a WAL file on disk. Check that the checksum of frame +# $iFrame in the file is correct when interpreting data as $endian-endian +# integers ($endian must be either "big" or "little"). If the checksum looks +# correct, return 1. Otherwise 0. +# +proc log_checksum_verify {filename iFrame endian} { + set data [readfile $filename] + + foreach {offset c1 c2} [log_checksum_calc $data $iFrame $endian] {} + + binary scan [string range $data $offset [expr $offset+7]] II expect1 expect2 + set expect1 [expr $expect1&0xFFFFFFFF] + set expect2 [expr $expect2&0xFFFFFFFF] + + expr {$c1==$expect1 && $c2==$expect2} +} + +# File $filename must be a WAL file on disk. Compute the checksum for frame +# $iFrame in the file by interpreting data as $endian-endian integers +# ($endian must be either "big" or "little"). Then write the computed +# checksum into the file. +# +proc log_checksum_write {filename iFrame endian} { + set data [readfile $filename] + + foreach {offset c1 c2} [log_checksum_calc $data $iFrame $endian] {} + + set bin [binary format II $c1 $c2] + set fd [open $filename r+] + fconfigure $fd -encoding binary + fconfigure $fd -translation binary + seek $fd $offset + puts -nonewline $fd $bin + close $fd +} + +# Calculate and return the checksum for a particular frame in a WAL. +# +# Arguments are: +# +# $data Blob containing the entire contents of a WAL. +# +# $iFrame Frame number within the $data WAL. Frames are numbered +# starting at 1. +# +# $endian One of "big" or "little". +# +# Returns a list of three elements, as follows: +# +# * The byte offset of the checksum belonging to frame $iFrame in the WAL. +# * The first integer in the calculated version of the checksum. +# * The second integer in the calculated version of the checksum. +# +proc log_checksum_calc {data iFrame endian} { + + binary scan [string range $data 8 11] I pgsz + if {$iFrame > 1} { + set n [wal_file_size [expr $iFrame-2] $pgsz] + binary scan [string range $data [expr $n+16] [expr $n+23]] II c1 c2 + } else { + set c1 0 + set c2 0 + wal_cksum $endian c1 c2 [string range $data 0 23] + } + + set n [wal_file_size [expr $iFrame-1] $pgsz] + wal_cksum $endian c1 c2 [string range $data $n [expr $n+7]] + wal_cksum $endian c1 c2 [string range $data [expr $n+24] [expr $n+24+$pgsz-1]] + + list [expr $n+16] $c1 $c2 +} + +# +# File $filename must be a WAL file on disk. Set the 'magic' field of the +# WAL header to indicate that checksums are $endian-endian ($endian must be +# either "big" or "little"). +# +# Also update the wal header checksum (since the wal header contents may +# have changed). +# +proc log_checksum_writemagic {filename endian} { + set val [expr {0x377f0682 | ($endian == "big" ? 1 : 0)}] + set bin [binary format I $val] + set fd [open $filename r+] + fconfigure $fd -encoding binary + fconfigure $fd -translation binary + puts -nonewline $fd $bin + + seek $fd 0 + set blob [read $fd 24] + set c1 0 + set c2 0 + wal_cksum $endian c1 c2 $blob + seek $fd 24 + puts -nonewline $fd [binary format II $c1 $c2] + + close $fd +} + +#------------------------------------------------------------------------- +# Test cases walcksum-1.* attempt to verify the following: +# +# * That both native and non-native order checksum log files can +# be recovered. +# +# * That when appending to native or non-native checksum log files +# SQLite continues to use the right kind of checksums. +# +# * Test point 2 when the appending process is not one that recovered +# the log file. +# +# * Test that both native and non-native checksum log files can be +# checkpointed. And that after doing so the next write to the log +# file occurs using native byte-order checksums. +# +set native "big" +if {$::tcl_platform(byteOrder) == "littleEndian"} { set native "little" } +foreach endian {big little} { + + # Create a database. Leave some data in the log file. + # + do_test walcksum-1.$endian.1 { + catch { db close } + forcedelete test.db test.db-wal test.db-journal + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + PRAGMA synchronous = NORMAL; + + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 'one'); + INSERT INTO t1 VALUES(2, 'two'); + INSERT INTO t1 VALUES(3, 'three'); + INSERT INTO t1 VALUES(5, 'five'); + + PRAGMA journal_mode = WAL; + INSERT INTO t1 VALUES(8, 'eight'); + INSERT INTO t1 VALUES(13, 'thirteen'); + INSERT INTO t1 VALUES(21, 'twentyone'); + } + + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + db close + + list [file size test2.db] [file size test2.db-wal] + } [list [expr 1024*3] [wal_file_size 6 1024]] + + # Verify that the checksums are valid for all frames and that they + # are calculated by interpreting data in native byte-order. + # + for {set f 1} {$f <= 6} {incr f} { + do_test walcksum-1.$endian.2.$f { + log_checksum_verify test2.db-wal $f $native + } 1 + } + + # Replace all checksums in the current WAL file with $endian versions. + # Then check that it is still possible to recover and read the database. + # + log_checksum_writemagic test2.db-wal $endian + for {set f 1} {$f <= 6} {incr f} { + do_test walcksum-1.$endian.3.$f { + log_checksum_write test2.db-wal $f $endian + log_checksum_verify test2.db-wal $f $endian + } {1} + } + do_test walcksum-1.$endian.4.1 { + forcecopy test2.db test.db + forcecopy test2.db-wal test.db-wal + sqlite3 db test.db + execsql { SELECT a FROM t1 } + } {1 2 3 5 8 13 21} + + # Following recovery, any frames written to the log should use the same + # endianness as the existing frames. Check that this is the case. + # + do_test walcksum-1.$endian.5.0 { + execsql { + PRAGMA synchronous = NORMAL; + INSERT INTO t1 VALUES(34, 'thirtyfour'); + } + list [file size test.db] [file size test.db-wal] + } [list [expr 1024*3] [wal_file_size 8 1024]] + for {set f 1} {$f <= 8} {incr f} { + do_test walcksum-1.$endian.5.$f { + log_checksum_verify test.db-wal $f $endian + } {1} + } + + # Now connect a second connection to the database. Check that this one + # (not the one that did recovery) also appends frames to the log using + # the same endianness for checksums as the existing frames. + # + do_test walcksum-1.$endian.6 { + sqlite3 db2 test.db + execsql { + PRAGMA integrity_check; + SELECT a FROM t1; + } db2 + } {ok 1 2 3 5 8 13 21 34} + do_test walcksum-1.$endian.7.0 { + execsql { + PRAGMA synchronous = NORMAL; + INSERT INTO t1 VALUES(55, 'fiftyfive'); + } db2 + list [file size test.db] [file size test.db-wal] + } [list [expr 1024*3] [wal_file_size 10 1024]] + for {set f 1} {$f <= 10} {incr f} { + do_test walcksum-1.$endian.7.$f { + log_checksum_verify test.db-wal $f $endian + } {1} + } + + # Now that both the recoverer and non-recoverer have added frames to the + # log file, check that it can still be recovered. + # + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + do_test walcksum-1.$endian.7.11 { + sqlite3 db3 test2.db + execsql { + PRAGMA integrity_check; + SELECT a FROM t1; + } db3 + } {ok 1 2 3 5 8 13 21 34 55} + db3 close + + # Run a checkpoint on the database file. Then, check that any frames written + # to the start of the log use native byte-order checksums. + # + do_test walcksum-1.$endian.8.1 { + execsql { + PRAGMA wal_checkpoint; + INSERT INTO t1 VALUES(89, 'eightynine'); + } + log_checksum_verify test.db-wal 1 $native + } {1} + do_test walcksum-1.$endian.8.2 { + log_checksum_verify test.db-wal 2 $native + } {1} + do_test walcksum-1.$endian.8.3 { + log_checksum_verify test.db-wal 3 $native + } {0} + + do_test walcksum-1.$endian.9 { + execsql { + PRAGMA integrity_check; + SELECT a FROM t1; + } db2 + } {ok 1 2 3 5 8 13 21 34 55 89} + + catch { db close } + catch { db2 close } +} + +#------------------------------------------------------------------------- +# Test case walcksum-2.* tests that if a statement transaction is rolled +# back after frames are written to the WAL, and then (after writing some +# more) the outer transaction is committed, the WAL file is still correctly +# formatted (and can be recovered by a second process if required). +# +do_test walcksum-2.1 { + forcedelete test.db test.db-wal test.db-journal + sqlite3 db test.db + execsql { + PRAGMA synchronous = NORMAL; + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + PRAGMA cache_size = 10; + CREATE TABLE t1(x PRIMARY KEY); + PRAGMA wal_checkpoint; + INSERT INTO t1 VALUES(randomblob(800)); + BEGIN; + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 2 */ + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 4 */ + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 8 */ + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 16 */ + SAVEPOINT one; + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 32 */ + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 64 */ + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 128 */ + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 256 */ + ROLLBACK TO one; + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 32 */ + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 64 */ + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 128 */ + INSERT INTO t1 SELECT randomblob(800) FROM t1; /* 256 */ + COMMIT; + } + + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + + sqlite3 db2 test2.db + execsql { + PRAGMA integrity_check; + SELECT count(*) FROM t1; + } db2 +} {ok 256} +catch { db close } +catch { db2 close } + +#------------------------------------------------------------------------- +# Test case walcksum-3.* tests that the checksum calculation detects single +# byte changes to frame or frame-header data and considers the frame +# invalid as a result. +# +do_test walcksum-3.1 { + forcedelete test.db test.db-wal test.db-journal + sqlite3 db test.db + + execsql { + PRAGMA synchronous = NORMAL; + PRAGMA page_size = 1024; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, randomblob(300)); + INSERT INTO t1 VALUES(2, randomblob(300)); + PRAGMA journal_mode = WAL; + INSERT INTO t1 VALUES(3, randomblob(300)); + } + + file size test.db-wal +} [wal_file_size 1 1024] +do_test walcksum-3.2 { + forcecopy test.db-wal test2.db-wal + forcecopy test.db test2.db + sqlite3 db2 test2.db + execsql { SELECT a FROM t1 } db2 +} {1 2 3} +db2 close +forcecopy test.db test2.db + + +foreach incr {1 2 3 20 40 60 80 100 120 140 160 180 200 220 240 253 254 255} { + do_test walcksum-3.3.$incr { + set FAIL 0 + for {set iOff 0} {$iOff < [wal_file_size 1 1024]} {incr iOff} { + + forcecopy test.db-wal test2.db-wal + set fd [open test2.db-wal r+] + fconfigure $fd -encoding binary + fconfigure $fd -translation binary + + seek $fd $iOff + binary scan [read $fd 1] c x + seek $fd $iOff + puts -nonewline $fd [binary format c [expr {($x+$incr)&0xFF}]] + close $fd + + sqlite3 db2 test2.db + if { [execsql { SELECT a FROM t1 } db2] != "1 2" } {set FAIL 1} + db2 close + } + set FAIL + } {0} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walcrash.test b/components/external/SQLite-3.8.1/test/walcrash.test new file mode 100644 index 0000000000000000000000000000000000000000..2a647188b07697ea6fe045c384f070a659d008a3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walcrash.test @@ -0,0 +1,295 @@ +# 2010 February 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library when +# recovering a database following a simulated system failure in +# "PRAGMA journal_mode=WAL" mode. +# + +# +# These are 'warm-body' tests of database recovery used while developing +# the WAL code. They serve to prove that a few really simple cases work: +# +# walcrash-1.*: Recover a database. +# walcrash-2.*: Recover a database where the failed transaction spanned more +# than one page. +# walcrash-3.*: Recover multiple databases where the failed transaction +# was a multi-file transaction. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +ifcapable !wal {finish_test ; return } + +db close + +set seed 0 +set REPEATS 100 + +# walcrash-1.* +# +for {set i 1} {$i < $REPEATS} {incr i} { + forcedelete test.db test.db-wal + do_test walcrash-1.$i.1 { + crashsql -delay 4 -file test.db-wal -seed [incr seed] { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 1); + INSERT INTO t1 VALUES(2, 3); + INSERT INTO t1 VALUES(3, 6); + } + } {1 {child process exited abnormally}} + do_test walcrash-1.$i.2 { + sqlite3 db test.db + execsql { SELECT sum(a)==max(b) FROM t1 } + } {1} + integrity_check walcrash-1.$i.3 + db close + + do_test walcrash-1.$i.4 { + crashsql -delay 2 -file test.db-wal -seed [incr seed] { + INSERT INTO t1 VALUES(4, (SELECT sum(a) FROM t1) + 4); + INSERT INTO t1 VALUES(5, (SELECT sum(a) FROM t1) + 5); + } + } {1 {child process exited abnormally}} + do_test walcrash-1.$i.5 { + sqlite3 db test.db + execsql { SELECT sum(a)==max(b) FROM t1 } + } {1} + integrity_check walcrash-1.$i.6 + do_test walcrash-1.$i.7 { + execsql { PRAGMA main.journal_mode } + } {wal} + db close +} + +# walcrash-2.* +# +for {set i 1} {$i < $REPEATS} {incr i} { + forcedelete test.db test.db-wal + do_test walcrash-2.$i.1 { + crashsql -delay 5 -file test.db-wal -seed [incr seed] { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t1 VALUES(5, 9); + } + } {1 {child process exited abnormally}} + do_test walcrash-2.$i.2 { + sqlite3 db test.db + execsql { SELECT sum(a)==max(b) FROM t1 } + } {1} + integrity_check walcrash-2.$i.3 + db close + + do_test walcrash-2.$i.4 { + crashsql -delay 2 -file test.db-wal -seed [incr seed] { + INSERT INTO t1 VALUES(6, (SELECT sum(a) FROM t1) + 6); + INSERT INTO t1 VALUES(7, (SELECT sum(a) FROM t1) + 7); + } + } {1 {child process exited abnormally}} + do_test walcrash-2.$i.5 { + sqlite3 db test.db + execsql { SELECT sum(a)==max(b) FROM t1 } + } {1} + integrity_check walcrash-2.$i.6 + do_test walcrash-2.$i.6 { + execsql { PRAGMA main.journal_mode } + } {wal} + db close +} + +# walcrash-3.* +# +# for {set i 1} {$i < $REPEATS} {incr i} { +# forcedelete test.db test.db-wal +# forcedelete test2.db test2.db-wal +# +# do_test walcrash-3.$i.1 { +# crashsql -delay 2 -file test2.db-wal -seed [incr seed] { +# PRAGMA journal_mode = WAL; +# ATTACH 'test2.db' AS aux; +# CREATE TABLE t1(a PRIMARY KEY, b); +# CREATE TABLE aux.t2(a PRIMARY KEY, b); +# BEGIN; +# INSERT INTO t1 VALUES(1, 2); +# INSERT INTO t2 VALUES(1, 2); +# COMMIT; +# } +# } {1 {child process exited abnormally}} +# +# do_test walcrash-3.$i.2 { +# sqlite3_wal db test.db +# execsql { +# ATTACH 'test2.db' AS aux; +# SELECT * FROM t1 EXCEPT SELECT * FROM t2; +# } +# } {} +# do_test walcrash-3.$i.3 { execsql { PRAGMA main.integrity_check } } {ok} +# do_test walcrash-3.$i.4 { execsql { PRAGMA aux.integrity_check } } {ok} +# +# db close +# } + +# walcrash-4.* +# +for {set i 1} {$i < $REPEATS} {incr i} { + forcedelete test.db test.db-wal + forcedelete test2.db test2.db-wal + + do_test walcrash-4.$i.1 { + crashsql -delay 4 -file test.db-wal -seed [incr seed] -blocksize 4096 { + PRAGMA journal_mode = WAL; + PRAGMA page_size = 1024; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + } + } {1 {child process exited abnormally}} + + do_test walcrash-4.$i.2 { + sqlite3 db test.db + execsql { + SELECT * FROM t1 WHERE a = 1; + } + } {1 2} + do_test walcrash-4.$i.3 { execsql { PRAGMA main.integrity_check } } {ok} + do_test walcrash-4.$i.4 { execsql { PRAGMA main.journal_mode } } {wal} + + db close +} + +# walcrash-5.* +# +for {set i 1} {$i < $REPEATS} {incr i} { + forcedelete test.db test.db-wal + forcedelete test2.db test2.db-wal + + do_test walcrash-5.$i.1 { + crashsql -delay 13 -file test.db-wal -seed [incr seed] -blocksize 4096 { + PRAGMA journal_mode = WAL; + PRAGMA page_size = 1024; + BEGIN; + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 4 */ + COMMIT; + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 8 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 12 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 16 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 20 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 24 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 28 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 32 */ + + PRAGMA wal_checkpoint; + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 VALUES(randomblob(900)); + } + } {1 {child process exited abnormally}} + + do_test walcrash-5.$i.2 { + sqlite3 db test.db + execsql { SELECT count(*)==33 OR count(*)==34 FROM t1 WHERE x != 1 } + } {1} + do_test walcrash-5.$i.3 { execsql { PRAGMA main.integrity_check } } {ok} + do_test walcrash-5.$i.4 { execsql { PRAGMA main.journal_mode } } {wal} + + db close +} + +# walcrash-6.* +# +for {set i 1} {$i < $REPEATS} {incr i} { + forcedelete test.db test.db-wal + forcedelete test2.db test2.db-wal + + do_test walcrash-6.$i.1 { + crashsql -delay 14 -file test.db-wal -seed [incr seed] -blocksize 512 { + PRAGMA journal_mode = WAL; + PRAGMA page_size = 1024; + BEGIN; + CREATE TABLE t1(x PRIMARY KEY); + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 4 */ + COMMIT; + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 8 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 12 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 16 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 20 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 24 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 28 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1 LIMIT 4; /* 32 */ + + PRAGMA wal_checkpoint; + INSERT INTO t1 VALUES(randomblob(9000)); + INSERT INTO t1 VALUES(randomblob(9000)); + INSERT INTO t1 VALUES(randomblob(9000)); + } + } {1 {child process exited abnormally}} + + do_test walcrash-6.$i.2 { + sqlite3 db test.db + execsql { SELECT count(*)==34 OR count(*)==35 FROM t1 WHERE x != 1 } + } {1} + do_test walcrash-6.$i.3 { execsql { PRAGMA main.integrity_check } } {ok} + do_test walcrash-6.$i.4 { execsql { PRAGMA main.journal_mode } } {wal} + + db close +} + +#------------------------------------------------------------------------- +# This test case simulates a crash while checkpointing the database. Page +# 1 is one of the pages overwritten by the checkpoint. This is a special +# case because it means the content of page 1 may be damaged. SQLite will +# have to determine: +# +# (a) that the database is a WAL database, and +# (b) the database page-size +# +# based on the log file. +# +for {set i 1} {$i < $REPEATS} {incr i} { + forcedelete test.db test.db-wal + + # Select a page-size for this test. + # + set pgsz [lindex {512 1024 2048 4096 8192 16384} [expr $i%6]] + + do_test walcrash-7.$i.1 { + crashsql -delay 3 -file test.db -seed [incr seed] -blocksize 512 " + PRAGMA page_size = $pgsz; + PRAGMA journal_mode = wal; + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + COMMIT; + PRAGMA wal_checkpoint; + CREATE INDEX i1 ON t1(a); + PRAGMA wal_checkpoint; + " + } {1 {child process exited abnormally}} + + do_test walcrash-7.$i.2 { + sqlite3 db test.db + execsql { SELECT b FROM t1 WHERE a = 1 } + } {2} + do_test walcrash-7.$i.3 { execsql { PRAGMA main.integrity_check } } {ok} + do_test walcrash-7.$i.4 { execsql { PRAGMA main.journal_mode } } {wal} + + db close +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walcrash2.test b/components/external/SQLite-3.8.1/test/walcrash2.test new file mode 100644 index 0000000000000000000000000000000000000000..9c93bcdef38d4d1c445d2c7175dfd971346b67bf --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walcrash2.test @@ -0,0 +1,98 @@ +# 2010 May 25 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +source $testdir/wal_common.tcl +ifcapable !wal {finish_test ; return } + + +#------------------------------------------------------------------------- +# This test case demonstrates a flaw in the wal-index manipulation that +# existed at one point: If a process crashes mid-transaction, it may have +# already added some entries to one of the hash-tables in the wal-index. +# If the transaction were to be explicitly rolled back at this point, the +# hash-table entries would be removed as part of the rollback. However, +# if the process crashes, the transaction is implicitly rolled back and +# the rogue entries remain in the hash table. +# +# Normally, this causes no problem - readers can tell the difference +# between committed and uncommitted entries in the hash table. However, +# if it happens often enough that all slots in the hash-table become +# non-zero, the next process that attempts to read or write the hash +# table falls into an infinite loop. +# +# Even if run with an SQLite version affected by the bug, this test case +# only goes into an infinite loop if SQLite is compiled without SQLITE_DEBUG +# defined. If SQLITE_DEBUG is defined, the program is halted by a failing +# assert() before entering the infinite loop. +# +# walcrash2-1.1: Create a database. Commit a transaction that adds 8 frames +# to the WAL (and 8 entry to the first hash-table in the +# wal-index). +# +# walcrash2-1.2: Have an external process open a transaction, add 8 entries +# to the wal-index hash-table, then crash. Repeat this 1023 +# times (so that the wal-index contains 8192 entries - all +# slots are non-zero). +# +# walcrash2-1.3: Using a new database connection, attempt to query the +# database. This should cause the process to go into the +# infinite loop. +# +do_test walcrash2-1.1 { + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = off; + PRAGMA journal_mode = WAL; + PRAGMA synchronous = NORMAL; + BEGIN; + CREATE TABLE t1(x); + CREATE TABLE t2(x); + CREATE TABLE t3(x); + CREATE TABLE t4(x); + CREATE TABLE t5(x); + CREATE TABLE t6(x); + CREATE TABLE t7(x); + COMMIT; + } + file size test.db-wal +} [wal_file_size 8 1024] +for {set nEntry 8} {$nEntry < 8192} {incr nEntry 8} { + do_test walcrash2-1.2.[expr $nEntry/8] { + set C [launch_testfixture] + testfixture $C { + sqlite3 db test.db + db eval { + PRAGMA cache_size = 15; + BEGIN; + INSERT INTO t1 VALUES(randomblob(900)); -- 1 row, 1 page + INSERT INTO t1 SELECT * FROM t1; -- 2 rows, 3 pages + INSERT INTO t1 SELECT * FROM t1; -- 4 rows, 5 pages + INSERT INTO t1 SELECT * FROM t1; -- 8 rows, 9 pages + INSERT INTO t1 SELECT * FROM t1; -- 16 rows, 17 pages + INSERT INTO t1 SELECT * FROM t1 LIMIT 3; -- 20 rows, 20 pages + } + } + close $C + file size test.db-wal + } [wal_file_size 16 1024] +} +do_test walcrash2-1.3 { + sqlite3 db2 test.db + execsql { SELECT count(*) FROM t1 } db2 +} {0} +catch { db2 close } + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walcrash3.test b/components/external/SQLite-3.8.1/test/walcrash3.test new file mode 100644 index 0000000000000000000000000000000000000000..71dfb4555a6c53bc63b22ca19518a6fc30055fe4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walcrash3.test @@ -0,0 +1,128 @@ +# 2011 December 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This test simulates an application crash immediately following a +# system call to truncate a file. Specifically, the system call that +# truncates the WAL file if "PRAGMA journal_size_limit" is configured. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !wal {finish_test ; return } +set testprefix walcrash3 + +db close +testvfs tvfs +tvfs filter {xTruncate xWrite} +tvfs script tvfs_callback +proc tvfs_callback {args} {} + +sqlite3 db test.db -vfs tvfs +do_execsql_test 1.1 { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 128; + PRAGMA journal_size_limit = 16384; + + CREATE TABLE t1(a BLOB, b BLOB, UNIQUE(a, b)); + INSERT INTO t1 VALUES(randomblob(10), randomblob(1000)); +} {wal 128 16384} + +proc tvfs_callback {method file arglist} { + if {$::state==1} { + foreach f [glob -nocomplain xx_test.*] { forcedelete $f } + foreach f [glob -nocomplain test.*] { forcecopy $f "xx_$f" } + set ::state 2 + } + if {$::state==0 && $method=="xTruncate" && [file tail $file]=="test.db-wal"} { + set ::state 1 + } +} + +for {set i 2} {$i<1000} {incr i} { + + # If the WAL file is truncated within the following, within the following + # xWrite call the [tvfs_callback] makes a copy of the database and WAL + # files set sets $::state to 2. So that the copied files are in the same + # state as the real database and WAL files would be if an application crash + # occurred immediately following the xTruncate(). + # + set ::state 0 + do_execsql_test 1.$i.1 { + INSERT INTO t1 VALUES(randomblob(10), randomblob(1000)); + } + + # If a copy was made, open it and run the integrity-check. + # + if {$::state==2} { + sqlite3 db2 xx_test.db + do_test 1.$i.2 { execsql { PRAGMA integrity_check } db2 } "ok" + do_test 1.$i.3 { execsql { SELECT count(*) FROM t1 } db2 } [expr $i-1] + db2 close + } +} +catch { db close } +tvfs delete + +#-------------------------------------------------------------------------- +# +catch { db close } +forcedelete test.db + +do_test 2.1 { + sqlite3 db test.db + execsql { + PRAGMA page_size = 512; + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 128; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES(randomblob(25), randomblob(200)); + } + + for {set i 0} {$i < 1500} {incr i} { + execsql { INSERT INTO t1 VALUES(randomblob(25), randomblob(200)) } + } + + db_save + db close +} {} + +set nInitialErr [set_test_counter errors] +for {set i 2} {$i<10000 && [set_test_counter errors]==$nInitialErr} {incr i} { + + do_test 2.$i.1 { + catch { db close } + db_restore + crashsql -delay 2 -file test.db-wal -seed $i { + SELECT * FROM sqlite_master; + PRAGMA synchronous = full; + PRAGMA wal_checkpoint; + BEGIN; + INSERT INTO t1 VALUES(randomblob(26), randomblob(200)); + INSERT INTO t1 VALUES(randomblob(26), randomblob(200)); + INSERT INTO t1 VALUES(randomblob(26), randomblob(200)); + INSERT INTO t1 VALUES(randomblob(26), randomblob(200)); + INSERT INTO t1 VALUES(randomblob(26), randomblob(200)); + INSERT INTO t1 VALUES(randomblob(26), randomblob(200)); + INSERT INTO t1 VALUES(randomblob(26), randomblob(200)); + INSERT INTO t1 VALUES(randomblob(26), randomblob(200)); + COMMIT; + } + } {1 {child process exited abnormally}} + + do_test 2.$i.2 { + sqlite3 db test.db + execsql { PRAGMA integrity_check } + } {ok} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walfault.test b/components/external/SQLite-3.8.1/test/walfault.test new file mode 100644 index 0000000000000000000000000000000000000000..4a9d98afda8c9f85c7c4ba9fcb0ac77fb88d5584 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walfault.test @@ -0,0 +1,591 @@ +# 2010 May 03 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl +source $testdir/lock_common.tcl + +ifcapable !wal {finish_test ; return } + +#------------------------------------------------------------------------- +# This test case, walfault-1-*, simulates faults while executing a +# +# PRAGMA journal_mode = WAL; +# +# statement immediately after creating a new database. +# +do_test walfault-1-pre-1 { + faultsim_delete_and_reopen + faultsim_save_and_close +} {} +do_faultsim_test walfault-1 -prep { + faultsim_restore_and_reopen +} -body { + db eval { PRAGMA main.journal_mode = WAL } +} -test { + + faultsim_test_result {0 wal} + + # Test that the connection that encountered an error as part of + # "PRAGMA journal_mode = WAL" and a new connection use the same + # journal mode when accessing the database. + # + # If "PRAGMA journal_mode" is executed immediately, connection [db] (the + # one that hit the error in journal_mode="WAL") might return "wal" even + # if it failed to switch the database to WAL mode. This is not considered + # a problem. When it tries to read the database, connection [db] correctly + # recognizes that it is a rollback database and switches back to a + # rollback compatible journal mode. + # + if {[permutation] != "inmemory_journal"} { + set jm [db one {SELECT * FROM sqlite_master ; PRAGMA main.journal_mode}] + sqlite3 db2 test.db + set jm2 [db2 one {SELECT * FROM sqlite_master ; PRAGMA main.journal_mode}] + db2 close + + if { $jm!=$jm2 } { error "Journal modes do not match: $jm $jm2" } + if { $testrc==0 && $jm!="wal" } { error "Journal mode is not WAL" } + } +} + +#-------------------------------------------------------------------------- +# Test case walfault-2-* tests fault injection during recovery of a +# short WAL file (a dozen frames or thereabouts). +# +do_test walfault-2-pre-1 { + sqlite3 db test.db + execsql { + PRAGMA journal_mode = WAL; + BEGIN; + CREATE TABLE x(y, z, UNIQUE(y, z)); + INSERT INTO x VALUES(randomblob(100), randomblob(100)); + COMMIT; + PRAGMA wal_checkpoint; + + INSERT INTO x SELECT randomblob(100), randomblob(100) FROM x; + INSERT INTO x SELECT randomblob(100), randomblob(100) FROM x; + INSERT INTO x SELECT randomblob(100), randomblob(100) FROM x; + } + execsql { + SELECT count(*) FROM x + } +} {8} +do_test walfault-2-pre-2 { + faultsim_save_and_close + faultsim_restore_and_reopen + execsql { SELECT count(*) FROM x } +} {8} +do_faultsim_test walfault-2 -prep { + faultsim_restore_and_reopen +} -body { + execsql { SELECT count(*) FROM x } +} -test { + faultsim_test_result {0 8} + faultsim_integrity_check +} + +#-------------------------------------------------------------------------- +# Test fault injection while writing and checkpointing a small WAL file. +# +do_test walfault-3-pre-1 { + sqlite3 db test.db + execsql { + PRAGMA auto_vacuum = 1; + PRAGMA journal_mode = WAL; + CREATE TABLE abc(a PRIMARY KEY); + INSERT INTO abc VALUES(randomblob(1500)); + } + db close + faultsim_save_and_close +} {} +do_faultsim_test walfault-3 -prep { + faultsim_restore_and_reopen +} -body { + db eval { + DELETE FROM abc; + PRAGMA wal_checkpoint; + } + set {} {} +} -test { + faultsim_test_result {0 {}} +} + +#-------------------------------------------------------------------------- +# +if {[permutation] != "inmemory_journal"} { + faultsim_delete_and_reopen + faultsim_save_and_close + do_faultsim_test walfault-4 -prep { + faultsim_restore_and_reopen + } -body { + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a PRIMARY KEY, b); + INSERT INTO t1 VALUES('a', 'b'); + PRAGMA wal_checkpoint; + SELECT * FROM t1; + } + } -test { + # Update: The following changed from {0 {wal 0 7 7 a b}} as a result + # of PSOW being set by default. + faultsim_test_result {0 {wal 0 5 5 a b}} + faultsim_integrity_check + } +} + +#-------------------------------------------------------------------------- +# +do_test walfault-5-pre-1 { + faultsim_delete_and_reopen + execsql { + PRAGMA page_size = 512; + PRAGMA journal_mode = WAL; + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-5 -faults shmerr* -prep { + faultsim_restore_and_reopen + execsql { PRAGMA wal_autocheckpoint = 0 } + shmfault filter xShmMap +} -body { + execsql { + CREATE TABLE t1(x); + BEGIN; + INSERT INTO t1 VALUES(randomblob(400)); /* 1 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 2 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 4 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 8 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 16 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 32 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 64 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 128 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 256 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 512 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 1024 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 2048 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 4096 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 8192 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 16384 */ + COMMIT; + SELECT count(*) FROM t1; + } +} -test { + faultsim_test_result {0 16384} + faultsim_integrity_check +} + +#-------------------------------------------------------------------------- +# +do_test walfault-6-pre-1 { + faultsim_delete_and_reopen + execsql { + PRAGMA page_size = 512; + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 0; + CREATE TABLE t1(x); + BEGIN; + INSERT INTO t1 VALUES(randomblob(400)); /* 1 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 2 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 4 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 8 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 16 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 32 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 64 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 128 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 256 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 512 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 1024 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 2048 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 4096 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 8192 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 16384 */ + COMMIT; + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-6 -faults shmerr* -prep { + faultsim_restore_and_reopen + shmfault filter xShmMap +} -body { + execsql { SELECT count(*) FROM t1 } +} -test { + faultsim_test_result {0 16384} + faultsim_integrity_check + set n [db one {SELECT count(*) FROM t1}] + if {$n != 16384 && $n != 0} { error "Incorrect number of rows: $n" } +} + +#-------------------------------------------------------------------------- +# +do_test walfault-7-pre-1 { + faultsim_delete_and_reopen + execsql { + PRAGMA page_size = 512; + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 0; + CREATE TABLE t1(x); + BEGIN; + INSERT INTO t1 VALUES(randomblob(400)); /* 1 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 2 */ + INSERT INTO t1 SELECT randomblob(400) FROM t1; /* 4 */ + COMMIT; + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-7 -prep { + faultsim_restore_and_reopen +} -body { + execsql { SELECT count(*) FROM t1 } +} -test { + faultsim_test_result {0 4} + set n [db one {SELECT count(*) FROM t1}] + if {$n != 4 && $n != 0} { error "Incorrect number of rows: $n" } +} + +#-------------------------------------------------------------------------- +# +do_test walfault-8-pre-1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE abc(a PRIMARY KEY); + INSERT INTO abc VALUES(randomblob(900)); + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-8 -prep { + faultsim_restore_and_reopen + execsql { PRAGMA cache_size = 10 } +} -body { + execsql { + BEGIN; + INSERT INTO abc SELECT randomblob(900) FROM abc; /* 1 */ + --INSERT INTO abc SELECT randomblob(900) FROM abc; /* 2 */ + --INSERT INTO abc SELECT randomblob(900) FROM abc; /* 4 */ + --INSERT INTO abc SELECT randomblob(900) FROM abc; /* 8 */ + ROLLBACK; + SELECT count(*) FROM abc; + } +} -test { + faultsim_test_result {0 1} + + faultsim_integrity_check + catch { db eval ROLLBACK } + faultsim_integrity_check + + set n [db one {SELECT count(*) FROM abc}] + if {$n != 1} { error "Incorrect number of rows: $n" } +} + +#-------------------------------------------------------------------------- +# +do_test walfault-9-pre-1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE abc(a PRIMARY KEY); + INSERT INTO abc VALUES(randomblob(900)); + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-9 -prep { + #if {$iFail<73} { set iFail 73 } + #if {$iFail>73} { exit } + + faultsim_restore_and_reopen + execsql { PRAGMA cache_size = 10 } +} -body { + execsql { + BEGIN; + INSERT INTO abc SELECT randomblob(900) FROM abc; /* 1 */ + SAVEPOINT spoint; + INSERT INTO abc SELECT randomblob(900) FROM abc; /* 2 */ + INSERT INTO abc SELECT randomblob(900) FROM abc; /* 4 */ + INSERT INTO abc SELECT randomblob(900) FROM abc; /* 8 */ + ROLLBACK TO spoint; + COMMIT; + SELECT count(*) FROM abc; + } +} -test { + faultsim_test_result {0 2} + faultsim_integrity_check + + catch { db eval { ROLLBACK TO spoint } } + catch { db eval { COMMIT } } + set n [db one {SELECT count(*) FROM abc}] + if {$n != 1 && $n != 2} { error "Incorrect number of rows: $n" } +} + +do_test walfault-10-pre1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 0; + CREATE TABLE z(zz INTEGER PRIMARY KEY, zzz BLOB); + CREATE INDEX zzzz ON z(zzz); + INSERT INTO z VALUES(NULL, randomblob(800)); + INSERT INTO z VALUES(NULL, randomblob(800)); + INSERT INTO z SELECT NULL, randomblob(800) FROM z; + INSERT INTO z SELECT NULL, randomblob(800) FROM z; + INSERT INTO z SELECT NULL, randomblob(800) FROM z; + INSERT INTO z SELECT NULL, randomblob(800) FROM z; + INSERT INTO z SELECT NULL, randomblob(800) FROM z; + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-10 -prep { + faultsim_restore_and_reopen + execsql { + PRAGMA cache_size = 10; + BEGIN; + UPDATE z SET zzz = randomblob(799); + } + + set ::stmt [sqlite3_prepare db "SELECT zzz FROM z WHERE zz IN (1, 2, 3)" -1] + sqlite3_step $::stmt +} -body { + execsql { INSERT INTO z VALUES(NULL, NULL) } +} -test { + sqlite3_finalize $::stmt + faultsim_integrity_check + + faultsim_test_result {0 {}} + catch { db eval { ROLLBACK } } + faultsim_integrity_check + + set n [db eval {SELECT count(*), sum(length(zzz)) FROM z}] + if {$n != "64 51200"} { error "Incorrect data: $n" } +} + +#-------------------------------------------------------------------------- +# Test fault injection while checkpointing a large WAL file, if the +# checkpoint is the first operation run after opening the database. +# This means that some of the required wal-index pages are mapped as part of +# the checkpoint process, which means there are a few more opportunities +# for IO errors. +# +# To speed this up, IO errors are only simulated within xShmMap() calls. +# +do_test walfault-11-pre-1 { + sqlite3 db test.db + execsql { + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 0; + BEGIN; + CREATE TABLE abc(a PRIMARY KEY); + INSERT INTO abc VALUES(randomblob(1500)); + INSERT INTO abc VALUES(randomblob(1500)); + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 4 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 8 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 16 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 32 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 64 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 128 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 256 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 512 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 1024 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 2048 + INSERT INTO abc SELECT randomblob(1500) FROM abc; -- 4096 + COMMIT; + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-11 -faults shmerr* -prep { + catch { db2 close } + faultsim_restore_and_reopen + shmfault filter xShmMap +} -body { + db eval { SELECT count(*) FROM abc } + sqlite3 db2 test.db -vfs shmfault + db2 eval { PRAGMA wal_checkpoint } + set {} {} +} -test { + faultsim_test_result {0 {}} +} + +#------------------------------------------------------------------------- +# Test the handling of the various IO/OOM/SHM errors that may occur during +# a log recovery operation undertaken as part of a call to +# sqlite3_wal_checkpoint(). +# +do_test walfault-12-pre-1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 0; + BEGIN; + CREATE TABLE abc(a PRIMARY KEY); + INSERT INTO abc VALUES(randomblob(1500)); + INSERT INTO abc VALUES(randomblob(1500)); + COMMIT; + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-12 -prep { + if {[info commands shmfault] == ""} { + testvfs shmfault -default true + } + faultsim_restore_and_reopen + db eval { SELECT * FROM sqlite_master } + shmfault shm test.db [string repeat "\000" 40] +} -body { + set rc [sqlite3_wal_checkpoint db] + if {$rc != "SQLITE_OK"} { error [sqlite3_errmsg db] } +} -test { + db close + faultsim_test_result {0 {}} +} + +#------------------------------------------------------------------------- +# Test simple recovery, reading and writing a database file using a +# heap-memory wal-index. +# +do_test walfault-13-pre-1 { + faultsim_delete_and_reopen + execsql { + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint = 0; + BEGIN; + CREATE TABLE abc(a PRIMARY KEY); + INSERT INTO abc VALUES(randomblob(1500)); + INSERT INTO abc VALUES(randomblob(1500)); + COMMIT; + } + faultsim_save_and_close + delete_file sv_test.db-shm +} {} + +do_faultsim_test walfault-13.1 -prep { + faultsim_restore_and_reopen +} -body { + db eval { PRAGMA locking_mode = exclusive } + db eval { SELECT count(*) FROM abc } +} -test { + faultsim_test_result {0 2} + if {[file exists test.db-shm]} { error "Not using heap-memory mode" } + faultsim_integrity_check +} + +do_faultsim_test walfault-13.2 -prep { + faultsim_restore_and_reopen + db eval { PRAGMA locking_mode = exclusive } +} -body { + db eval { PRAGMA journal_mode = delete } +} -test { + faultsim_test_result {0 delete} + if {[file exists test.db-shm]} { error "Not using heap-memory mode" } + faultsim_integrity_check +} + +do_test walfault-13-pre-2 { + faultsim_delete_and_reopen + execsql { + BEGIN; + CREATE TABLE abc(a PRIMARY KEY); + INSERT INTO abc VALUES(randomblob(1500)); + INSERT INTO abc VALUES(randomblob(1500)); + COMMIT; + } + faultsim_save_and_close +} {} + +do_faultsim_test walfault-13.3 -prep { + faultsim_restore_and_reopen +} -body { + db eval { + PRAGMA locking_mode = exclusive; + PRAGMA journal_mode = WAL; + INSERT INTO abc VALUES(randomblob(1500)); + } +} -test { + faultsim_test_result {0 {exclusive wal}} + if {[file exists test.db-shm]} { error "Not using heap-memory mode" } + faultsim_integrity_check + set nRow [db eval {SELECT count(*) FROM abc}] + if {!(($nRow==2 && $testrc) || $nRow==3)} { error "Bad db content" } +} + +#------------------------------------------------------------------------- +# Test fault-handling when wrapping around to the start of a WAL file. +# +do_test walfault-14-pre { + faultsim_delete_and_reopen + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + BEGIN; + CREATE TABLE abc(a PRIMARY KEY); + INSERT INTO abc VALUES(randomblob(1500)); + INSERT INTO abc VALUES(randomblob(1500)); + COMMIT; + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-14 -prep { + faultsim_restore_and_reopen +} -body { + db eval { + PRAGMA wal_checkpoint = full; + INSERT INTO abc VALUES(randomblob(1500)); + } +} -test { + faultsim_test_result {0 {0 9 9}} + faultsim_integrity_check + set nRow [db eval {SELECT count(*) FROM abc}] + if {!(($nRow==2 && $testrc) || $nRow==3)} { error "Bad db content" } +} + +#------------------------------------------------------------------------- +# Test fault-handling when switching out of exclusive-locking mode. +# +do_test walfault-14-pre { + faultsim_delete_and_reopen + execsql { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + BEGIN; + CREATE TABLE abc(a PRIMARY KEY); + INSERT INTO abc VALUES(randomblob(1500)); + INSERT INTO abc VALUES(randomblob(1500)); + COMMIT; + } + faultsim_save_and_close +} {} +do_faultsim_test walfault-14 -prep { + faultsim_restore_and_reopen + breakpoint + execsql { + SELECT count(*) FROM abc; + PRAGMA locking_mode = exclusive; + BEGIN; + INSERT INTO abc VALUES(randomblob(1500)); + COMMIT; + } +} -body { + db eval { + PRAGMA locking_mode = normal; + BEGIN; + INSERT INTO abc VALUES(randomblob(1500)); + COMMIT; + } +} -test { + faultsim_integrity_check + set nRow [db eval {SELECT count(*) FROM abc}] + if {$nRow!=3 && $nRow!=4} { error "Bad db content" } +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walhook.test b/components/external/SQLite-3.8.1/test/walhook.test new file mode 100644 index 0000000000000000000000000000000000000000..631ec834e3873b57421cf6eb548ff5e929b6486e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walhook.test @@ -0,0 +1,109 @@ +# 2010 April 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. +# +# More specifically, this file contains regression tests for the +# sqlite3_wal_hook() mechanism, including the sqlite3_wal_autocheckpoint() +# and "PRAGMA wal_autocheckpoint" convenience interfaces. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/wal_common.tcl + +ifcapable !wal {finish_test ; return } + +set ::wal_hook [list] +proc wal_hook {zDb nEntry} { + lappend ::wal_hook $zDb $nEntry + return 0 +} +db wal_hook wal_hook + +do_test walhook-1.1 { + execsql { + PRAGMA page_size = 1024; + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = wal; + PRAGMA synchronous = normal; + CREATE TABLE t1(i PRIMARY KEY, j); + } + set ::wal_hook +} {main 3} + +do_test walhook-1.2 { + set ::wal_hook [list] + execsql { INSERT INTO t1 VALUES(1, 'one') } + set ::wal_hook +} {main 5} +do_test walhook-1.3 { + proc wal_hook {args} { db eval {PRAGMA wal_checkpoint}; return 0 } + execsql { INSERT INTO t1 VALUES(2, 'two') } + file size test.db +} [expr 3*1024] +do_test walhook-1.4 { + proc wal_hook {zDb nEntry} { + execsql { PRAGMA wal_checkpoint } + return 0 + } + execsql { CREATE TABLE t2(a, b) } + file size test.db +} [expr 4*1024] + +do_test walhook-1.5 { + sqlite3 db2 test.db + proc wal_hook {zDb nEntry} { + execsql { PRAGMA wal_checkpoint } db2 + return 0 + } + execsql { CREATE TABLE t3(a PRIMARY KEY, b) } + file size test.db +} [expr 6*1024] + +db2 close +db close +sqlite3 db test.db +do_test walhook-2.1 { + execsql { PRAGMA synchronous = NORMAL } + execsql { PRAGMA wal_autocheckpoint } +} {1000} +do_test walhook-2.2 { + execsql { PRAGMA wal_autocheckpoint = 10} +} {10} +do_test walhook-2.3 { + execsql { PRAGMA wal_autocheckpoint } +} {10} + +# +# The database connection is configured with "PRAGMA wal_autocheckpoint = 10". +# Check that transactions are written to the log file until it contains at +# least 10 frames, then the database is checkpointed. Subsequent transactions +# are written into the start of the log file. +# +foreach {tn sql dbpages logpages} { + 4 "CREATE TABLE t4(x PRIMARY KEY, y)" 6 3 + 5 "INSERT INTO t4 VALUES(1, 'one')" 6 5 + 6 "INSERT INTO t4 VALUES(2, 'two')" 6 7 + 7 "INSERT INTO t4 VALUES(3, 'three')" 6 9 + 8 "INSERT INTO t4 VALUES(4, 'four')" 8 11 + 9 "INSERT INTO t4 VALUES(5, 'five')" 8 11 +} { + do_test walhook-2.$tn { + execsql $sql + list [file size test.db] [file size test.db-wal] + } [list [expr $dbpages*1024] [wal_file_size $logpages 1024]] +} + +catch { db2 close } +catch { db close } +finish_test diff --git a/components/external/SQLite-3.8.1/test/walmode.test b/components/external/SQLite-3.8.1/test/walmode.test new file mode 100644 index 0000000000000000000000000000000000000000..4e14d54d4f71551a04f0f9a0d8aceb87ebf987a8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walmode.test @@ -0,0 +1,387 @@ +# 2010 April 19 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/malloc_common.tcl + +# If the library was compiled without WAL support, check that the +# "PRAGMA journal_mode=WAL" treats "WAL" as an unrecognized mode. +# +ifcapable !wal { + + do_test walmode-0.1 { + execsql { PRAGMA journal_mode = wal } + } {delete} + do_test walmode-0.2 { + execsql { PRAGMA main.journal_mode = wal } + } {delete} + do_test walmode-0.3 { + execsql { PRAGMA main.journal_mode } + } {delete} + + finish_test + return +} + +do_test walmode-1.1 { + set sqlite_sync_count 0 + execsql { PRAGMA page_size = 1024 } + execsql { PRAGMA journal_mode = wal } +} {wal} +do_test walmode-1.2 { + file size test.db +} {1024} + +set expected_sync_count 3 +if {$::tcl_platform(platform)!="windows"} { + ifcapable dirsync { + incr expected_sync_count + } +} +do_test walmode-1.3 { + set sqlite_sync_count +} $expected_sync_count + +do_test walmode-1.4 { + file exists test.db-wal +} {0} +do_test walmode-1.5 { + execsql { CREATE TABLE t1(a, b) } + file size test.db +} {1024} +do_test walmode-1.6 { + file exists test.db-wal +} {1} +do_test walmode-1.7 { + db close + file exists test.db-wal +} {0} + +# There is now a database file with the read and write versions set to 2 +# in the file system. This file should default to WAL mode. +# +do_test walmode-2.1 { + sqlite3 db test.db + file exists test.db-wal +} {0} +do_test walmode-2.2 { + execsql { SELECT * FROM sqlite_master } + file exists test.db-wal +} {1} +do_test walmode-2.3 { + db close + file exists test.db-wal +} {0} + +# If the first statement executed is "PRAGMA journal_mode = wal", and +# the file is already configured for WAL (read and write versions set +# to 2), then there should be no need to write the database. The +# statement should cause the client to connect to the log file. +# +set sqlite_sync_count 0 +do_test walmode-3.1 { + sqlite3 db test.db + execsql { PRAGMA journal_mode = wal } +} {wal} +do_test walmode-3.2 { + list $sqlite_sync_count [file exists test.db-wal] [file size test.db-wal] +} {0 1 0} + +# Test that changing back to journal_mode=persist works. +# +do_test walmode-4.1 { + execsql { INSERT INTO t1 VALUES(1, 2) } + execsql { PRAGMA journal_mode = persist } +} {persist} +do_test walmode-4.2 { + list [file exists test.db-journal] [file exists test.db-wal] +} {1 0} +do_test walmode-4.3 { + execsql { SELECT * FROM t1 } +} {1 2} +do_test walmode-4.4 { + db close + sqlite3 db test.db + execsql { SELECT * FROM t1 } +} {1 2} +do_test walmode-4.5 { + list [file exists test.db-journal] [file exists test.db-wal] +} {1 0} + +# Test that nothing goes wrong if a connection is prevented from changing +# from WAL to rollback mode because a second connection has the database +# open. Or from rollback to WAL. +# +do_test walmode-4.6 { + sqlite3 db2 test.db + execsql { PRAGMA main.journal_mode } db2 +} {delete} +do_test walmode-4.7 { + execsql { PRAGMA main.journal_mode = wal } db +} {wal} +do_test walmode-4.8 { + execsql { SELECT * FROM t1 } db2 +} {1 2} +do_test walmode-4.9 { + catchsql { PRAGMA journal_mode = delete } db +} {1 {database is locked}} +do_test walmode-4.10 { + execsql { PRAGMA main.journal_mode } db +} {wal} + +do_test walmode-4.11 { + db2 close + execsql { PRAGMA journal_mode = delete } db +} {delete} +do_test walmode-4.12 { + execsql { PRAGMA main.journal_mode } db +} {delete} +do_test walmode-4.13 { + list [file exists test.db-journal] [file exists test.db-wal] +} {0 0} +do_test walmode-4.14 { + sqlite3 db2 test.db + execsql { + BEGIN; + SELECT * FROM t1; + } db2 +} {1 2} + +do_test walmode-4.16 { execsql { PRAGMA main.journal_mode } db } {delete} +do_test walmode-4.17 { execsql { PRAGMA main.journal_mode } db2 } {delete} + +do_test walmode-4.17 { + catchsql { PRAGMA main.journal_mode = wal } db +} {1 {database is locked}} +do_test walmode-4.18 { + execsql { PRAGMA main.journal_mode } db +} {delete} +catch { db close } +catch { db2 close } + +# Test that it is not possible to change a temporary or in-memory database +# to WAL mode. WAL mode is for persistent file-backed databases only. +# +# walmode-5.1.*: Try to set journal_mode=WAL on [sqlite3 db :memory:] database. +# walmode-5.2.*: Try to set journal_mode=WAL on [sqlite3 db ""] database. +# walmode-5.3.*: Try to set temp.journal_mode=WAL. +# +do_test walmode-5.1.1 { + sqlite3 db :memory: + execsql { PRAGMA main.journal_mode } +} {memory} +do_test walmode-5.1.2 { + execsql { PRAGMA main.journal_mode = wal } +} {memory} +do_test walmode-5.1.3 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + COMMIT; + SELECT * FROM t1; + PRAGMA main.journal_mode; + } +} {1 2 memory} +do_test walmode-5.1.4 { + execsql { PRAGMA main.journal_mode = wal } +} {memory} +do_test walmode-5.1.5 { + execsql { + INSERT INTO t1 VALUES(3, 4); + SELECT * FROM t1; + PRAGMA main.journal_mode; + } +} {1 2 3 4 memory} + +if {$TEMP_STORE>=2} { + set tempJrnlMode memory +} else { + set tempJrnlMode delete +} +do_test walmode-5.2.1 { + sqlite3 db "" + execsql { PRAGMA main.journal_mode } +} $tempJrnlMode +do_test walmode-5.2.2 { + execsql { PRAGMA main.journal_mode = wal } +} $tempJrnlMode +do_test walmode-5.2.3 { + execsql { + BEGIN; + CREATE TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + COMMIT; + SELECT * FROM t1; + PRAGMA main.journal_mode; + } +} [list 1 2 $tempJrnlMode] +do_test walmode-5.2.4 { + execsql { PRAGMA main.journal_mode = wal } +} $tempJrnlMode +do_test walmode-5.2.5 { + execsql { + INSERT INTO t1 VALUES(3, 4); + SELECT * FROM t1; + PRAGMA main.journal_mode; + } +} [list 1 2 3 4 $tempJrnlMode] + +do_test walmode-5.3.1 { + sqlite3 db test.db + execsql { PRAGMA temp.journal_mode } +} $tempJrnlMode +do_test walmode-5.3.2 { + execsql { PRAGMA temp.journal_mode = wal } +} $tempJrnlMode +do_test walmode-5.3.3 { + execsql { + BEGIN; + CREATE TEMP TABLE t1(a, b); + INSERT INTO t1 VALUES(1, 2); + COMMIT; + SELECT * FROM t1; + PRAGMA temp.journal_mode; + } +} [list 1 2 $tempJrnlMode] +do_test walmode-5.3.4 { + execsql { PRAGMA temp.journal_mode = wal } +} $tempJrnlMode +do_test walmode-5.3.5 { + execsql { + INSERT INTO t1 VALUES(3, 4); + SELECT * FROM t1; + PRAGMA temp.journal_mode; + } +} [list 1 2 3 4 $tempJrnlMode] + + +#------------------------------------------------------------------------- +# Test changing to WAL mode from journal_mode=off or journal_mode=memory +# +foreach {tn mode} { + 1 off + 2 memory + 3 persist + 4 delete + 5 truncate +} { + do_test walmode-6.$tn { + faultsim_delete_and_reopen + execsql " + PRAGMA journal_mode = $mode; + PRAGMA journal_mode = wal; + " + } [list $mode wal] +} +db close + +#------------------------------------------------------------------------- +# Test the effect of a "PRAGMA journal_mode" command being the first +# thing executed by a new connection. This means that the schema is not +# loaded when sqlite3_prepare_v2() is called to compile the statement. +# +do_test walmode-7.0 { + forcedelete test.db + sqlite3 db test.db + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a, b); + } +} {wal} +foreach {tn sql result} { + 1 "PRAGMA journal_mode" wal + 2 "PRAGMA main.journal_mode" wal + 3 "PRAGMA journal_mode = delete" delete + 4 "PRAGMA journal_mode" delete + 5 "PRAGMA main.journal_mode" delete + 6 "PRAGMA journal_mode = wal" wal + 7 "PRAGMA journal_mode" wal + 8 "PRAGMA main.journal_mode" wal + + 9 "PRAGMA journal_mode" wal + 10 "PRAGMA main.journal_mode" wal + 11 "PRAGMA main.journal_mode = delete" delete + 12 "PRAGMA journal_mode" delete + 13 "PRAGMA main.journal_mode" delete + 14 "PRAGMA main.journal_mode = wal" wal + 15 "PRAGMA journal_mode" wal + 16 "PRAGMA main.journal_mode" wal +} { + do_test walmode-7.$tn { + db close + sqlite3 db test.db + execsql $sql + } $result +} +db close + +#------------------------------------------------------------------------- +# Test the effect of a "PRAGMA journal_mode" command on an attached +# database. +# +faultsim_delete_and_reopen +do_execsql_test walmode-8.1 { + CREATE TABLE t1(a, b); + PRAGMA journal_mode = WAL; + ATTACH 'test.db2' AS two; + CREATE TABLE two.t2(a, b); +} {wal} +do_execsql_test walmode-8.2 { PRAGMA main.journal_mode } {wal} +do_execsql_test walmode-8.3 { PRAGMA two.journal_mode } {delete} +do_execsql_test walmode-8.4 { PRAGMA two.journal_mode = DELETE } {delete} + +db close +sqlite3 db test.db +do_execsql_test walmode-8.5 { ATTACH 'test.db2' AS two } {} +do_execsql_test walmode-8.6 { PRAGMA main.journal_mode } {wal} +do_execsql_test walmode-8.7 { PRAGMA two.journal_mode } {delete} +do_execsql_test walmode-8.8 { INSERT INTO two.t2 DEFAULT VALUES } {} +do_execsql_test walmode-8.9 { PRAGMA two.journal_mode } {delete} +do_execsql_test walmode-8.10 { INSERT INTO t1 DEFAULT VALUES } {} +do_execsql_test walmode-8.11 { PRAGMA main.journal_mode } {wal} +do_execsql_test walmode-8.12 { PRAGMA journal_mode } {wal} + +# Change to WAL mode on test2.db and make sure (in the tests that follow) +# that this mode change persists. +do_test walmode-8.x1 { + execsql { + PRAGMA two.journal_mode=WAL; + PRAGMA two.journal_mode; + } +} {wal wal} + +db close +sqlite3 db test.db +do_execsql_test walmode-8.13 { PRAGMA journal_mode = WAL } {wal} +do_execsql_test walmode-8.14 { ATTACH 'test.db2' AS two } {} +do_execsql_test walmode-8.15 { PRAGMA main.journal_mode } {wal} +do_execsql_test walmode-8.16 { PRAGMA two.journal_mode } {wal} +do_execsql_test walmode-8.17 { INSERT INTO two.t2 DEFAULT VALUES } {} +do_execsql_test walmode-8.18 { PRAGMA two.journal_mode } {wal} + +sqlite3 db2 test.db2 +do_test walmode-8.19 { execsql { PRAGMA main.journal_mode } db2 } {wal} +db2 close + +do_execsql_test walmode-8.20 { PRAGMA journal_mode = DELETE } {delete} +do_execsql_test walmode-8.21 { PRAGMA main.journal_mode } {delete} +do_execsql_test walmode-8.22 { PRAGMA two.journal_mode } {delete} +do_execsql_test walmode-8.21 { PRAGMA journal_mode = WAL } {wal} +do_execsql_test walmode-8.21 { PRAGMA main.journal_mode } {wal} +do_execsql_test walmode-8.22 { PRAGMA two.journal_mode } {wal} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walnoshm.test b/components/external/SQLite-3.8.1/test/walnoshm.test new file mode 100644 index 0000000000000000000000000000000000000000..d4082178dde26c7427a8c6aa275cd3413efd7d7d --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walnoshm.test @@ -0,0 +1,184 @@ +# 2010 November 1 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that WAL databases may be accessed without +# using the xShm primitives if the connection is in exclusive-mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix walnoshm +ifcapable !wal {finish_test ; return } + +db close +testvfs tvfsshm +testvfs tvfs -default 1 -iversion 1 +sqlite3 db test.db + +#-------------------------------------------------------------------------- +# Test that when using a version 1 VFS, a database can only be converted +# to WAL mode after setting locking_mode=EXCLUSIVE. Also, test that if a +# WAL database is opened using heap-memory for the WAL index, the connection +# cannot change back to locking_mode=NORMAL while the database is still in +# WAL mode. +# +do_execsql_test 1.1 { + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES(1, 2); +} + +do_execsql_test 1.2 { + PRAGMA journal_mode = WAL; + SELECT * FROM t1; +} {delete 1 2} +do_test 1.3 { file exists test.db-wal } {0} + +do_execsql_test 1.4 { + PRAGMA locking_mode = exclusive; + PRAGMA journal_mode = WAL; + SELECT * FROM t1; +} {exclusive wal 1 2} +do_test 1.5 { file exists test.db-wal } {1} + +do_execsql_test 1.6 { INSERT INTO t1 VALUES(3, 4) } + +do_execsql_test 1.7 { + PRAGMA locking_mode = normal; +} {exclusive} +do_execsql_test 1.8 { + PRAGMA journal_mode = delete; + PRAGMA main.locking_mode; +} {delete exclusive} +do_execsql_test 1.9 { + PRAGMA locking_mode = normal; +} {normal} +do_execsql_test 1.10 { + SELECT * FROM t1; +} {1 2 3 4} +do_test 1.11 { file exists test.db-wal } {0} + +#------------------------------------------------------------------------- +# +# 2.1.*: Test that a connection using a version 1 VFS can open a WAL database +# and convert it to rollback mode if it is set to use +# locking_mode=exclusive. +# +# 2.2.*: Test that if the exclusive lock cannot be obtained while attempting +# the above, the operation fails and the WAL file is not opened. +# +do_execsql_test 2.1.1 { + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES('a', 'b'); + INSERT INTO t2 VALUES('c', 'd'); +} +do_execsql_test 2.1.2 { + PRAGMA locking_mode = exclusive; + PRAGMA journal_mode = WAL; + INSERT INTO t2 VALUES('e', 'f'); + INSERT INTO t2 VALUES('g', 'h'); +} {exclusive wal} + +do_test 2.1.3 { + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + sqlite3 db2 test2.db + catchsql { SELECT * FROM t2 } db2 +} {1 {unable to open database file}} +do_test 2.1.4 { + catchsql { PRAGMA journal_mode = delete } db2 +} {1 {unable to open database file}} +do_test 2.1.5 { + execsql { + PRAGMA locking_mode = exclusive; + PRAGMA journal_mode = delete; + SELECT * FROM t2; + } db2 +} {exclusive delete a b c d e f g h} + +do_test 2.2.1 { + forcecopy test.db test2.db + forcecopy test.db-wal test2.db-wal + sqlite3 db3 test2.db -vfs tvfsshm + sqlite3 db2 test2.db + execsql { SELECT * FROM t2 } db3 +} {a b c d e f g h} + +do_test 2.2.2 { + execsql { PRAGMA locking_mode = exclusive } db2 + catchsql { PRAGMA journal_mode = delete } db2 +} {1 {database is locked}} + +do_test 2.2.3 { + # This is to test that [db2] is not holding a PENDING lock (which can + # happen when an attempt to obtain an EXCLUSIVE lock fails). + sqlite3 db4 test2.db -vfs tvfsshm + execsql { SELECT * FROM t2 } db4 +} {a b c d e f g h} + +do_test 2.2.4 { + catchsql { SELECT * FROM t2 } db2 +} {1 {database is locked}} + +do_test 2.2.5 { + db4 close + sqlite3 db4 test2.db -vfs tvfsshm + execsql { SELECT * FROM t2 } db4 +} {a b c d e f g h} + +do_test 2.2.6 { + db3 close + db4 close + execsql { SELECT * FROM t2 } db2 +} {a b c d e f g h} + +db2 close +db close + +#------------------------------------------------------------------------- +# +# 3.1: Test that if locking_mode=EXCLUSIVE is set after the wal file is +# opened, it is possible to drop back to locking_mode=NORMAL. +# +# 3.2: Test that if locking_mode=EXCLUSIVE is set before the wal file is +# opened, it is not. +# +do_test 3.1 { + sqlite3 db test.db -vfs tvfsshm + execsql { + SELECT * FROM t1; + PRAGMA locking_mode = EXCLUSIVE; + INSERT INTO t1 VALUES(5, 6); + PRAGMA locking_mode = NORMAL; + INSERT INTO t1 VALUES(7, 8); + } + sqlite3 db2 test.db -vfs tvfsshm + execsql { SELECT * FROM t1 } db2 +} {1 2 3 4 5 6 7 8} +db close +db2 close +do_test 3.2 { + sqlite3 db test.db -vfs tvfsshm + execsql { + PRAGMA locking_mode = EXCLUSIVE; + INSERT INTO t1 VALUES(9, 10); + PRAGMA locking_mode = NORMAL; + INSERT INTO t1 VALUES(11, 12); + } + sqlite3 db2 test.db -vfs tvfsshm + catchsql { SELECT * FROM t1 } db2 +} {1 {database is locked}} +db close +db2 close + +tvfs delete +tvfsshm delete + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walpersist.test b/components/external/SQLite-3.8.1/test/walpersist.test new file mode 100644 index 0000000000000000000000000000000000000000..692728dda48d296a0aa8a3aabeeb6c9730f7b780 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walpersist.test @@ -0,0 +1,126 @@ +# 2011 July 26 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests for using WAL with persistent WAL file mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +set ::testprefix walpersist + +ifcapable !wal { + finish_test + return +} + +do_test walpersist-1.0 { + db eval { + PRAGMA journal_mode=WAL; + CREATE TABLE t1(a); + INSERT INTO t1 VALUES(randomblob(5000)); + } + file exists test.db-wal +} {1} +do_test walpersist-1.1 { + file exists test.db-shm +} {1} +do_test walpersist-1.2 { + db close + list [file exists test.db] [file exists test.db-wal] [file exists test.db-shm] +} {1 0 0} +do_test walpersist-1.3 { + sqlite3 db test.db + db eval {SELECT length(a) FROM t1} +} {5000} +do_test walpersist-1.4 { + list [file exists test.db] [file exists test.db-wal] [file exists test.db-shm] +} {1 1 1} +do_test walpersist-1.5 { + file_control_persist_wal db -1 +} {0 0} +do_test walpersist-1.6 { + file_control_persist_wal db 1 +} {0 1} +do_test walpersist-1.7 { + file_control_persist_wal db -1 +} {0 1} +do_test walpersist-1.8 { + file_control_persist_wal db 0 +} {0 0} +do_test walpersist-1.9 { + file_control_persist_wal db -1 +} {0 0} +do_test walpersist-1.10 { + file_control_persist_wal db 1 +} {0 1} +do_test walpersist-1.11 { + db close + list [file exists test.db] [file exists test.db-wal] [file exists test.db-shm] +} {1 1 1} + +# Make sure the journal_size_limit works to limit the size of the +# persisted wal file. In persistent-wal mode, any non-negative +# journal_size_limit causes the WAL file to be truncated to zero bytes +# when closing. +# +forcedelete test.db test.db-shm test.db-wal +do_test walpersist-2.1 { + sqlite3 db test.db + db eval { + PRAGMA journal_mode=WAL; + PRAGMA wal_autocheckpoint=OFF; + PRAGMA journal_size_limit=12000; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(randomblob(50000)); + UPDATE t1 SET x=randomblob(50000); + } + expr {[file size test.db-wal]>100000} +} {1} +do_test walpersist-2.2 { + file_control_persist_wal db 1 + db close + concat [file exists test.db-wal] [file size test.db-wal] +} {1 0} +do_test walpersist-2.3 { + sqlite3 db test.db + execsql { PRAGMA integrity_check } +} {ok} + +do_test 3.1 { + catch {db close} + forcedelete test.db test.db-shm test.db-wal + sqlite3 db test.db + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + PRAGMA wal_autocheckpoint=128; + PRAGMA journal_size_limit=16384; + CREATE TABLE t1(a, b, PRIMARY KEY(a, b)); + } +} {wal 128 16384} +do_test 3.2 { + for {set i 0} {$i<200} {incr i} { + execsql { INSERT INTO t1 VALUES(randomblob(500), randomblob(500)) } + } + file_control_persist_wal db 1 + db close +} {} +do_test walpersist-3.3 { + file size test.db-wal +} {0} +do_test walpersist-3.4 { + sqlite3 db test.db + execsql { PRAGMA integrity_check } +} {ok} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walro.test b/components/external/SQLite-3.8.1/test/walro.test new file mode 100644 index 0000000000000000000000000000000000000000..f1ed275a1d807d3ea2f068b0a667fafcf31161f6 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walro.test @@ -0,0 +1,293 @@ +# 2011 May 09 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file contains tests for using WAL databases in read-only mode. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +source $testdir/lock_common.tcl +set ::testprefix walro + +# These tests are only going to work on unix. +# +if {$::tcl_platform(platform) != "unix"} { + finish_test + return +} + +# And only if the build is WAL-capable. +# +ifcapable !wal { + finish_test + return +} + +do_multiclient_test tn { + # Do not run tests with the connections in the same process. + # + if {$tn==2} continue + + # Close all connections and delete the database. + # + code1 { db close } + code2 { db2 close } + code3 { db3 close } + forcedelete test.db + forcedelete walro + + foreach c {code1 code2 code3} { + $c { + sqlite3_shutdown + sqlite3_config_uri 1 + } + } + + file mkdir walro + + do_test 1.1.1 { + code2 { sqlite3 db2 test.db } + sql2 { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(x, y); + INSERT INTO t1 VALUES('a', 'b'); + } + file exists test.db-shm + } {1} + + do_test 1.1.2 { + file attributes test.db-shm -permissions r--r--r-- + code1 { sqlite3 db file:test.db?readonly_shm=1 } + } {} + + do_test 1.1.3 { sql1 "SELECT * FROM t1" } {a b} + do_test 1.1.4 { sql2 "INSERT INTO t1 VALUES('c', 'd')" } {} + do_test 1.1.5 { sql1 "SELECT * FROM t1" } {a b c d} + + # Check that the read-only connection cannot write or checkpoint the db. + # + do_test 1.1.6 { + csql1 "INSERT INTO t1 VALUES('e', 'f')" + } {1 {attempt to write a readonly database}} + do_test 1.1.7 { + csql1 "PRAGMA wal_checkpoint" + } {1 {attempt to write a readonly database}} + + do_test 1.1.9 { sql2 "INSERT INTO t1 VALUES('e', 'f')" } {} + do_test 1.1.10 { sql1 "SELECT * FROM t1" } {a b c d e f} + + do_test 1.1.11 { + sql2 { + INSERT INTO t1 VALUES('g', 'h'); + PRAGMA wal_checkpoint; + } + set {} {} + } {} + do_test 1.1.12 { sql1 "SELECT * FROM t1" } {a b c d e f g h} + do_test 1.1.13 { sql2 "INSERT INTO t1 VALUES('i', 'j')" } {} + + do_test 1.2.1 { + code2 { db2 close } + code1 { db close } + list [file exists test.db-wal] [file exists test.db-shm] + } {1 1} + do_test 1.2.2 { + code1 { sqlite3 db file:test.db?readonly_shm=1 } + sql1 { SELECT * FROM t1 } + } {a b c d e f g h i j} + + do_test 1.2.3 { + code1 { db close } + file attributes test.db-shm -permissions rw-r--r-- + hexio_write test.db-shm 0 01020304 + file attributes test.db-shm -permissions r--r--r-- + code1 { sqlite3 db file:test.db?readonly_shm=1 } + csql1 { SELECT * FROM t1 } + } {1 {attempt to write a readonly database}} + do_test 1.2.4 { + code1 { sqlite3_extended_errcode db } + } {SQLITE_READONLY_RECOVERY} + + do_test 1.2.5 { + file attributes test.db-shm -permissions rw-r--r-- + code2 { sqlite3 db2 test.db } + sql2 "SELECT * FROM t1" + } {a b c d e f g h i j} + file attributes test.db-shm -permissions r--r--r-- + do_test 1.2.6 { sql1 "SELECT * FROM t1" } {a b c d e f g h i j} + + do_test 1.2.7 { + sql2 { + PRAGMA wal_checkpoint; + INSERT INTO t1 VALUES('k', 'l'); + } + set {} {} + } {} + do_test 1.2.8 { sql1 "SELECT * FROM t1" } {a b c d e f g h i j k l} + + # Now check that if the readonly_shm option is not supplied, or if it + # is set to zero, it is not possible to connect to the database without + # read-write access to the shm. + do_test 1.3.1 { + code1 { db close } + code1 { sqlite3 db test.db } + csql1 { SELECT * FROM t1 } + } {1 {unable to open database file}} + + # Also test that if the -shm file can be opened for read/write access, + # it is not if readonly_shm=1 is present in the URI. + do_test 1.3.2.1 { + code1 { db close } + code2 { db2 close } + file exists test.db-shm + } {0} + do_test 1.3.2.2 { + code1 { sqlite3 db file:test.db?readonly_shm=1 } + csql1 { SELECT * FROM sqlite_master } + } {1 {unable to open database file}} + do_test 1.3.2.3 { + code1 { db close } + close [open test.db-shm w] + file attributes test.db-shm -permissions r--r--r-- + code1 { sqlite3 db file:test.db?readonly_shm=1 } + csql1 { SELECT * FROM t1 } + } {1 {attempt to write a readonly database}} + do_test 1.3.2.4 { + code1 { sqlite3_extended_errcode db } + } {SQLITE_READONLY_RECOVERY} + + #----------------------------------------------------------------------- + # Test cases 1.4.* check that checkpoints and log wraps don't prevent + # read-only connections from reading the database. + do_test 1.4.1 { + code1 { db close } + forcedelete test.db-shm + file exists test.db-shm + } {0} + + # Open one read-only and one read-write connection. Write some data + # and then run a checkpoint using the read-write connection. Then + # check the read-only connection can still read. + do_test 1.4.2 { + code1 { sqlite3 db file:test.db?readonly_shm=1 } + code2 { sqlite3 db2 test.db } + csql2 { + INSERT INTO t1 VALUES(1, 2); + INSERT INTO t1 VALUES(3, 4); + INSERT INTO t1 VALUES(5, 6); + PRAGMA wal_checkpoint; + } + } {0 {0 3 3}} + do_test 1.4.3 { + csql1 { SELECT * FROM t1 } + } {0 {a b c d e f g h i j k l 1 2 3 4 5 6}} + + # Using the read-write connection, open a transaction and write lots + # of data - causing a cache spill and a log wrap. Then check that the + # read-only connection can still read the database. + do_test 1.4.4.1 { + csql2 { + PRAGMA cache_size = 10; + BEGIN; + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES('abc', 'xyz'); + INSERT INTO t2 SELECT x||y, y||x FROM t2; + INSERT INTO t2 SELECT x||y, y||x FROM t2; + INSERT INTO t2 SELECT x||y, y||x FROM t2; + INSERT INTO t2 SELECT x||y, y||x FROM t2; + INSERT INTO t2 SELECT x||y, y||x FROM t2; + INSERT INTO t2 SELECT x||y, y||x FROM t2; + INSERT INTO t2 SELECT x||y, y||x FROM t2; + INSERT INTO t2 SELECT x||y, y||x FROM t2; + INSERT INTO t2 SELECT x||y, y||x FROM t2; + } + file size test.db-wal + } {147800} + do_test 1.4.4.2 { + csql1 { SELECT * FROM t1 } + } {0 {a b c d e f g h i j k l 1 2 3 4 5 6}} + do_test 1.4.4.3 { + csql2 COMMIT + csql1 { SELECT count(*) FROM t2 } + } {0 512} + do_test 1.4.5 { + code2 { db2 close } + code1 { db close } + } {} +} + +forcedelete test.db + +#----------------------------------------------------------------------- +# Test cases 2.* check that a read-only connection may read the +# database file while a checkpoint operation is ongoing. +# +do_multiclient_test tn { + # Do not run tests with the connections in the same process. + # + if {$tn==2} continue + + # Close all connections and delete the database. + # + code1 { db close } + code2 { db2 close } + code3 { db3 close } + forcedelete test.db + forcedelete walro + + foreach c {code1 code2 code3} { + $c { + sqlite3_shutdown + sqlite3_config_uri 1 + } + } + + proc tv_hook {x file args} { + if {[file tail $file]=="test.db-wal"} { + do_test 2.1.2 { + code2 { sqlite3 db2 file:test.db?readonly_shm=1 } + csql2 { SELECT count(*) FROM t2 } + } {0 4} + do_test 2.1.3 { + code2 { db2 close } + } {} + } + } + + do_test 2.1.1 { + testvfs tv -default 1 -fullshm 1 + tv script tv_hook + tv filter {} + code1 { sqlite3 db test.db } + csql1 { + PRAGMA auto_vacuum = 0; + PRAGMA journal_mode = WAL; + BEGIN; + CREATE TABLE t2(x, y); + INSERT INTO t2 VALUES('abc', 'xyz'); + INSERT INTO t2 SELECT x||y, y||x FROM t2; + INSERT INTO t2 SELECT x||y, y||x FROM t2; + COMMIT; + } + } {0 wal} + + tv filter xSync + set res [csql1 { PRAGMA wal_checkpoint }] + do_test 2.1.4 { set res } {0 {0 2 2}} + + do_test 2.1.5 { + code1 { db close } + code1 { tv delete } + } {} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walshared.test b/components/external/SQLite-3.8.1/test/walshared.test new file mode 100644 index 0000000000000000000000000000000000000000..fbbdeb4de37a05bb6dd4eaec21ffe68cee98ea14 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walshared.test @@ -0,0 +1,62 @@ +# 2010 August 2 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode with shared-cache turned on. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !wal {finish_test ; return } + +db close +set ::enable_shared_cache [sqlite3_enable_shared_cache 1] + +sqlite3 db test.db +sqlite3 db2 test.db + +do_test walshared-1.0 { + execsql { + PRAGMA cache_size = 10; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a PRIMARY KEY, b UNIQUE); + INSERT INTO t1 VALUES(randomblob(100), randomblob(200)); + } +} {wal} + +do_test walshared-1.1 { + execsql { + BEGIN; + INSERT INTO t1 VALUES(randomblob(100), randomblob(200)); + INSERT INTO t1 SELECT randomblob(100), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(200) FROM t1; + INSERT INTO t1 SELECT randomblob(100), randomblob(200) FROM t1; + } +} {} + +do_test walshared-1.2 { + catchsql { PRAGMA wal_checkpoint } +} {1 {database table is locked}} + +do_test walshared-1.3 { + catchsql { PRAGMA wal_checkpoint } db2 +} {1 {database table is locked}} + +do_test walshared-1.4 { + execsql { COMMIT } + execsql { PRAGMA integrity_check } db2 +} {ok} + + + +sqlite3_enable_shared_cache $::enable_shared_cache +finish_test diff --git a/components/external/SQLite-3.8.1/test/walslow.test b/components/external/SQLite-3.8.1/test/walslow.test new file mode 100644 index 0000000000000000000000000000000000000000..83f292281a33030bec43abfb20ef97bf3c586272 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walslow.test @@ -0,0 +1,73 @@ +# 2010 March 17 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode. The tests in this file use +# brute force methods, so may take a while to run. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !wal {finish_test ; return } + +proc reopen_db {} { + catch { db close } + forcedelete test.db test.db-wal + sqlite3 db test.db + execsql { PRAGMA journal_mode = wal } +} + +db close +save_prng_state +for {set seed 1} {$seed<10} {incr seed} { + expr srand($seed) + restore_prng_state + reopen_db + do_test walslow-1.seed=$seed.0 { + execsql { CREATE TABLE t1(a, b) } + execsql { CREATE INDEX i1 ON t1(a) } + execsql { CREATE INDEX i2 ON t1(b) } + } {} + + for {set iTest 1} {$iTest < 100} {incr iTest} { + + do_test walslow-1.seed=$seed.$iTest.1 { + set w [expr int(rand()*2000)] + set x [expr int(rand()*2000)] + execsql { INSERT INTO t1 VALUES(randomblob($w), randomblob($x)) } + execsql { PRAGMA integrity_check } + } {ok} + + do_test walslow-1.seed=$seed.$iTest.2 { + execsql "PRAGMA wal_checkpoint;" + execsql { PRAGMA integrity_check } + } {ok} + + do_test walslow-1.seed=$seed.$iTest.3 { + forcedelete testX.db testX.db-wal + copy_file test.db testX.db + copy_file test.db-wal testX.db-wal + + sqlite3 db2 testX.db + execsql { PRAGMA journal_mode = WAL } db2 + execsql { PRAGMA integrity_check } db2 + } {ok} + + do_test walslow-1.seed=$seed.$iTest.4 { + execsql { SELECT count(*) FROM t1 WHERE a!=b } db2 + } [execsql { SELECT count(*) FROM t1 WHERE a!=b }] + db2 close + } +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/walthread.test b/components/external/SQLite-3.8.1/test/walthread.test new file mode 100644 index 0000000000000000000000000000000000000000..6249ce11af09cd131813283d5ab12e6a83f08bdd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/walthread.test @@ -0,0 +1,527 @@ +# 2010 April 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the operation of the library in +# "PRAGMA journal_mode=WAL" mode with multiple threads. +# + +set testdir [file dirname $argv0] + +source $testdir/tester.tcl +source $testdir/lock_common.tcl +if {[run_thread_tests]==0} { finish_test ; return } +ifcapable !wal { finish_test ; return } + +set sqlite_walsummary_mmap_incr 64 + +# How long, in seconds, to run each test for. If a test is set to run for +# 0 seconds, it is omitted entirely. +# +unset -nocomplain seconds +set seconds(walthread-1) 20 +set seconds(walthread-2) 20 +set seconds(walthread-3) 20 +set seconds(walthread-4) 20 +set seconds(walthread-5) 1 + +# The parameter is the name of a variable in the callers context. The +# variable may or may not exist when this command is invoked. +# +# If the variable does exist, its value is returned. Otherwise, this +# command uses [vwait] to wait until it is set, then returns the value. +# In other words, this is a version of the [set VARNAME] command that +# blocks until a variable exists. +# +proc wait_for_var {varname} { + if {0==[uplevel [list info exists $varname]]} { + uplevel [list vwait $varname] + } + uplevel [list set $varname] +} + +# The argument is the name of a list variable in the callers context. The +# first element of the list is removed and returned. For example: +# +# set L {a b c} +# set x [lshift L] +# assert { $x == "a" && $L == "b c" } +# +proc lshift {lvar} { + upvar $lvar L + set ret [lindex $L 0] + set L [lrange $L 1 end] + return $ret +} + + +#------------------------------------------------------------------------- +# do_thread_test TESTNAME OPTIONS... +# +# where OPTIONS are: +# +# -seconds SECONDS How many seconds to run the test for +# -init SCRIPT Script to run before test. +# -thread NAME COUNT SCRIPT Scripts to run in threads (or processes). +# -processes BOOLEAN True to use processes instead of threads. +# -check SCRIPT Script to run after test. +# +proc do_thread_test {args} { + + set A $args + + set P(testname) [lshift A] + set P(seconds) 5 + set P(init) "" + set P(threads) [list] + set P(processes) 0 + set P(check) { + set ic [db eval "PRAGMA integrity_check"] + if {$ic != "ok"} { error $ic } + } + + unset -nocomplain ::done + + while {[llength $A]>0} { + set a [lshift A] + switch -glob -- $a { + -seconds { + set P(seconds) [lshift A] + } + + -init { + set P(init) [lshift A] + } + + -processes { + set P(processes) [lshift A] + } + + -check { + set P(check) [lshift A] + } + + -thread { + set name [lshift A] + set count [lshift A] + set prg [lshift A] + lappend P(threads) [list $name $count $prg] + } + + default { + error "Unknown option: $a" + } + } + } + + if {$P(seconds) == 0} { + puts "Skipping $P(testname)" + return + } + + puts "Running $P(testname) for $P(seconds) seconds..." + + catch { db close } + forcedelete test.db test.db-journal test.db-wal + + sqlite3 db test.db + eval $P(init) + catch { db close } + + foreach T $P(threads) { + set name [lindex $T 0] + set count [lindex $T 1] + set prg [lindex $T 2] + + for {set i 1} {$i <= $count} {incr i} { + set vars " + set E(pid) $i + set E(nthread) $count + set E(seconds) $P(seconds) + " + set program [string map [list %TEST% $prg %VARS% $vars] { + + %VARS% + + proc usleep {ms} { + set ::usleep 0 + after $ms {set ::usleep 1} + vwait ::usleep + } + + proc integrity_check {{db db}} { + set ic [$db eval {PRAGMA integrity_check}] + if {$ic != "ok"} {error $ic} + } + + proc busyhandler {n} { usleep 10 ; return 0 } + + sqlite3 db test.db + db busy busyhandler + db eval { SELECT randomblob($E(pid)*5) } + + set ::finished 0 + after [expr $E(seconds) * 1000] {set ::finished 1} + proc tt_continue {} { update ; expr ($::finished==0) } + + set rc [catch { %TEST% } msg] + + catch { db close } + list $rc $msg + }] + + if {$P(processes)==0} { + sqlthread spawn ::done($name,$i) $program + } else { + testfixture_nb ::done($name,$i) $program + } + } + } + + set report " Results:" + foreach T $P(threads) { + set name [lindex $T 0] + set count [lindex $T 1] + set prg [lindex $T 2] + + set reslist [list] + for {set i 1} {$i <= $count} {incr i} { + set res [wait_for_var ::done($name,$i)] + lappend reslist [lindex $res 1] + do_test $P(testname).$name.$i [list lindex $res 0] 0 + } + + append report " $name $reslist" + } + puts $report + + sqlite3 db test.db + set res "" + if {[catch $P(check) msg]} { set res $msg } + do_test $P(testname).check [list set {} $res] "" +} + +# A wrapper around [do_thread_test] which runs the specified test twice. +# Once using processes, once using threads. This command takes the same +# arguments as [do_thread_test], except specifying the -processes switch +# is illegal. +# +proc do_thread_test2 {args} { + set name [lindex $args 0] + if {[lsearch $args -processes]>=0} { error "bad option: -processes"} + uplevel [lreplace $args 0 0 do_thread_test "$name-threads" -processes 0] + uplevel [lreplace $args 0 0 do_thread_test "$name-processes" -processes 1] +} + +#-------------------------------------------------------------------------- +# Start 10 threads. Each thread performs both read and write +# transactions. Each read transaction consists of: +# +# 1) Reading the md5sum of all but the last table row, +# 2) Running integrity check. +# 3) Reading the value stored in the last table row, +# 4) Check that the values read in steps 1 and 3 are the same, and that +# the md5sum of all but the last table row has not changed. +# +# Each write transaction consists of: +# +# 1) Modifying the contents of t1 (inserting, updating, deleting rows). +# 2) Appending a new row to the table containing the md5sum() of all +# rows in the table. +# +# Each of the N threads runs N read transactions followed by a single write +# transaction in a loop as fast as possible. +# +# There is also a single checkpointer thread. It runs the following loop: +# +# 1) Execute "PRAGMA wal_checkpoint" +# 2) Sleep for 500 ms. +# +do_thread_test2 walthread-1 -seconds $seconds(walthread-1) -init { + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(x PRIMARY KEY); + PRAGMA lock_status; + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 VALUES(randomblob(100)); + INSERT INTO t1 SELECT md5sum(x) FROM t1; + } +} -thread main 10 { + + proc read_transaction {} { + set results [db eval { + BEGIN; + PRAGMA integrity_check; + SELECT md5sum(x) FROM t1 WHERE rowid != (SELECT max(rowid) FROM t1); + SELECT x FROM t1 WHERE rowid = (SELECT max(rowid) FROM t1); + SELECT md5sum(x) FROM t1 WHERE rowid != (SELECT max(rowid) FROM t1); + COMMIT; + }] + + if {[llength $results]!=4 + || [lindex $results 0] != "ok" + || [lindex $results 1] != [lindex $results 2] + || [lindex $results 2] != [lindex $results 3] + } { + error "Failed read transaction: $results" + } + } + + proc write_transaction {} { + db eval { + BEGIN; + INSERT INTO t1 VALUES(randomblob(101 + $::E(pid))); + INSERT INTO t1 VALUES(randomblob(101 + $::E(pid))); + INSERT INTO t1 SELECT md5sum(x) FROM t1; + COMMIT; + } + } + + # Turn off auto-checkpoint. Otherwise, an auto-checkpoint run by a + # writer may cause the dedicated checkpoint thread to return an + # SQLITE_BUSY error. + # + db eval { PRAGMA wal_autocheckpoint = 0 } + + set nRun 0 + while {[tt_continue]} { + read_transaction + write_transaction + incr nRun + } + set nRun + +} -thread ckpt 1 { + set nRun 0 + while {[tt_continue]} { + db eval "PRAGMA wal_checkpoint" + usleep 500 + incr nRun + } + set nRun +} + +#-------------------------------------------------------------------------- +# This test has clients run the following procedure as fast as possible +# in a loop: +# +# 1. Open a database handle. +# 2. Execute a read-only transaction on the db. +# 3. Do "PRAGMA journal_mode = XXX", where XXX is one of WAL or DELETE. +# Ignore any SQLITE_BUSY error. +# 4. Execute a write transaction to insert a row into the db. +# 5. Run "PRAGMA integrity_check" +# +# At present, there are 4 clients in total. 2 do "journal_mode = WAL", and +# two do "journal_mode = DELETE". +# +# Each client returns a string of the form "W w, R r", where W is the +# number of write-transactions performed using a WAL journal, and D is +# the number of write-transactions performed using a rollback journal. +# For example, "192 w, 185 r". +# +do_thread_test2 walthread-2 -seconds $seconds(walthread-2) -init { + execsql { CREATE TABLE t1(x INTEGER PRIMARY KEY, y UNIQUE) } +} -thread RB 2 { + + db close + set nRun 0 + set nDel 0 + while {[tt_continue]} { + sqlite3 db test.db + db busy busyhandler + db eval { SELECT * FROM sqlite_master } + catch { db eval { PRAGMA journal_mode = DELETE } } + db eval { + BEGIN; + INSERT INTO t1 VALUES(NULL, randomblob(100+$E(pid))); + } + incr nRun 1 + incr nDel [file exists test.db-journal] + if {[file exists test.db-journal] + [file exists test.db-wal] != 1} { + error "File-system looks bad..." + } + db eval COMMIT + + integrity_check + db close + } + list $nRun $nDel + set {} "[expr $nRun-$nDel] w, $nDel r" + +} -thread WAL 2 { + db close + set nRun 0 + set nDel 0 + while {[tt_continue]} { + sqlite3 db test.db + db busy busyhandler + db eval { SELECT * FROM sqlite_master } + catch { db eval { PRAGMA journal_mode = WAL } } + db eval { + BEGIN; + INSERT INTO t1 VALUES(NULL, randomblob(110+$E(pid))); + } + incr nRun 1 + incr nDel [file exists test.db-journal] + if {[file exists test.db-journal] + [file exists test.db-wal] != 1} { + error "File-system looks bad..." + } + db eval COMMIT + + integrity_check + db close + } + set {} "[expr $nRun-$nDel] w, $nDel r" +} + +do_thread_test walthread-3 -seconds $seconds(walthread-3) -init { + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(cnt PRIMARY KEY, sum1, sum2); + CREATE INDEX i1 ON t1(sum1); + CREATE INDEX i2 ON t1(sum2); + INSERT INTO t1 VALUES(0, 0, 0); + } +} -thread t 10 { + + set nextwrite $E(pid) + + proc wal_hook {zDb nEntry} { + if {$nEntry>10} { + set rc [catch { db eval {PRAGMA wal_checkpoint} } msg] + if {$rc && $msg != "database is locked"} { error $msg } + } + return 0 + } + db wal_hook wal_hook + + while {[tt_continue]} { + set max 0 + while { $max != ($nextwrite-1) && [tt_continue] } { + set max [db eval { SELECT max(cnt) FROM t1 }] + } + + if {[tt_continue]} { + set sum1 [db eval { SELECT sum(cnt) FROM t1 }] + set sum2 [db eval { SELECT sum(sum1) FROM t1 }] + db eval { INSERT INTO t1 VALUES($nextwrite, $sum1, $sum2) } + incr nextwrite $E(nthread) + integrity_check + } + } + + set {} ok +} -check { + puts " Final db contains [db eval {SELECT count(*) FROM t1}] rows" + puts " Final integrity-check says: [db eval {PRAGMA integrity_check}]" + + # Check that the contents of the database are Ok. + set c 0 + set s1 0 + set s2 0 + db eval { SELECT cnt, sum1, sum2 FROM t1 ORDER BY cnt } { + if {$c != $cnt || $s1 != $sum1 || $s2 != $sum2} { + error "database content is invalid" + } + incr s2 $s1 + incr s1 $c + incr c 1 + } +} + +do_thread_test2 walthread-4 -seconds $seconds(walthread-4) -init { + execsql { + PRAGMA journal_mode = WAL; + CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE); + } +} -thread r 1 { + # This connection only ever reads the database. Therefore the + # busy-handler is not required. Disable it to check that this is true. + # + # UPDATE: That is no longer entirely true - as we don't use a blocking + # lock to enter RECOVER state. Which means there is a small chance a + # reader can see an SQLITE_BUSY. + # + while {[tt_continue]} { + integrity_check + } + set {} ok +} -thread w 1 { + + proc wal_hook {zDb nEntry} { + if {$nEntry>15} {db eval {PRAGMA wal_checkpoint}} + return 0 + } + db wal_hook wal_hook + set row 1 + while {[tt_continue]} { + db eval { REPLACE INTO t1 VALUES($row, randomblob(300)) } + incr row + if {$row == 10} { set row 1 } + } + + set {} ok +} + + +# This test case attempts to provoke a deadlock condition that existed in +# the unix VFS at one point. The problem occurred only while recovering a +# very large wal file (one that requires a wal-index larger than the +# initial default allocation of 64KB). +# +do_thread_test walthread-5 -seconds $seconds(walthread-5) -init { + + proc log_file_size {nFrame pgsz} { + expr {12 + ($pgsz+16)*$nFrame} + } + + execsql { + PRAGMA page_size = 1024; + PRAGMA journal_mode = WAL; + CREATE TABLE t1(x); + BEGIN; + INSERT INTO t1 VALUES(randomblob(900)); + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 2 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 4 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 8 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 16 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 32 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 64 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 128 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 256 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 512 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 1024 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 2048 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 4096 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 8192 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 16384 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 32768 */ + INSERT INTO t1 SELECT randomblob(900) FROM t1; /* 65536 */ + COMMIT; + } + + forcecopy test.db-wal bak.db-wal + forcecopy test.db bak.db + db close + + forcecopy bak.db-wal test.db-wal + forcecopy bak.db test.db + + if {[file size test.db-wal] < [log_file_size [expr 64*1024] 1024]} { + error "Somehow failed to create a large log file" + } + puts "Database with large log file recovered. Now running clients..." +} -thread T 5 { + db eval { SELECT count(*) FROM t1 } +} +unset -nocomplain seconds + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where.test b/components/external/SQLite-3.8.1/test/where.test new file mode 100644 index 0000000000000000000000000000000000000000..a50fe7ebcf0858e8e34171127e92cd395d4689ad --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where.test @@ -0,0 +1,1336 @@ +# 2001 September 15 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the use of indices in WHERE clases. +# +# $Id: where.test,v 1.50 2008/11/03 09:06:06 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build some test data +# +do_test where-1.0 { + execsql { + CREATE TABLE t1(w int, x int, y int); + CREATE TABLE t2(p int, q int, r int, s int); + } + for {set i 1} {$i<=100} {incr i} { + set w $i + set x [expr {int(log($i)/log(2))}] + set y [expr {$i*$i + 2*$i + 1}] + execsql "INSERT INTO t1 VALUES($w,$x,$y)" + } + + ifcapable subquery { + execsql { + INSERT INTO t2 SELECT 101-w, x, (SELECT max(y) FROM t1)+1-y, y FROM t1; + } + } else { + set maxy [execsql {select max(y) from t1}] + execsql " + INSERT INTO t2 SELECT 101-w, x, $maxy+1-y, y FROM t1; + " + } + + execsql { + CREATE INDEX i1w ON t1(w); + CREATE INDEX i1xy ON t1(x,y); + CREATE INDEX i2p ON t2(p); + CREATE INDEX i2r ON t2(r); + CREATE INDEX i2qs ON t2(q, s); + } +} {} + +# Do an SQL statement. Append the search count to the end of the result. +# +proc count sql { + set ::sqlite_search_count 0 + return [concat [execsql $sql] $::sqlite_search_count] +} + +# Verify that queries use an index. We are using the special variable +# "sqlite_search_count" which tallys the number of executions of MoveTo +# and Next operators in the VDBE. By verifing that the search count is +# small we can be assured that indices are being used properly. +# +do_test where-1.1.1 { + count {SELECT x, y, w FROM t1 WHERE w=10} +} {3 121 10 3} +do_eqp_test where-1.1.2 { + SELECT x, y, w FROM t1 WHERE w=10 +} {*SEARCH TABLE t1 USING INDEX i1w (w=?)*} +do_test where-1.1.3 { + db status step +} {0} +do_test where-1.1.4 { + db eval {SELECT x, y, w FROM t1 WHERE +w=10} +} {3 121 10} +do_test where-1.1.5 { + db status step +} {99} +do_eqp_test where-1.1.6 { + SELECT x, y, w FROM t1 WHERE +w=10 +} {*SCAN TABLE t1*} +do_test where-1.1.7 { + count {SELECT x, y, w AS abc FROM t1 WHERE abc=10} +} {3 121 10 3} +do_eqp_test where-1.1.8 { + SELECT x, y, w AS abc FROM t1 WHERE abc=10 +} {*SEARCH TABLE t1 USING INDEX i1w (w=?)*} +do_test where-1.1.9 { + db status step +} {0} +do_test where-1.2.1 { + count {SELECT x, y, w FROM t1 WHERE w=11} +} {3 144 11 3} +do_test where-1.2.2 { + count {SELECT x, y, w AS abc FROM t1 WHERE abc=11} +} {3 144 11 3} +do_test where-1.3.1 { + count {SELECT x, y, w AS abc FROM t1 WHERE 11=w} +} {3 144 11 3} +do_test where-1.3.2 { + count {SELECT x, y, w AS abc FROM t1 WHERE 11=abc} +} {3 144 11 3} +do_test where-1.4.1 { + count {SELECT w, x, y FROM t1 WHERE 11=w AND x>2} +} {11 3 144 3} +do_eqp_test where-1.4.2 { + SELECT w, x, y FROM t1 WHERE 11=w AND x>2 +} {*SEARCH TABLE t1 USING INDEX i1w (w=?)*} +do_test where-1.4.3 { + count {SELECT w AS a, x AS b, y FROM t1 WHERE 11=a AND b>2} +} {11 3 144 3} +do_eqp_test where-1.4.4 { + SELECT w AS a, x AS b, y FROM t1 WHERE 11=a AND b>2 +} {*SEARCH TABLE t1 USING INDEX i1w (w=?)*} +do_test where-1.5 { + count {SELECT x, y FROM t1 WHERE y<200 AND w=11 AND x>2} +} {3 144 3} +do_eqp_test where-1.5.2 { + SELECT x, y FROM t1 WHERE y<200 AND w=11 AND x>2 +} {*SEARCH TABLE t1 USING INDEX i1w (w=?)*} +do_test where-1.6 { + count {SELECT x, y FROM t1 WHERE y<200 AND x>2 AND w=11} +} {3 144 3} +do_test where-1.7 { + count {SELECT x, y FROM t1 WHERE w=11 AND y<200 AND x>2} +} {3 144 3} +do_test where-1.8 { + count {SELECT x, y FROM t1 WHERE w>10 AND y=144 AND x=3} +} {3 144 3} +do_eqp_test where-1.8.2 { + SELECT x, y FROM t1 WHERE w>10 AND y=144 AND x=3 +} {*SEARCH TABLE t1 USING INDEX i1xy (x=? AND y=?)*} +do_eqp_test where-1.8.3 { + SELECT x, y FROM t1 WHERE y=144 AND x=3 +} {*SEARCH TABLE t1 USING COVERING INDEX i1xy (x=? AND y=?)*} +do_test where-1.9 { + count {SELECT x, y FROM t1 WHERE y=144 AND w>10 AND x=3} +} {3 144 3} +do_test where-1.10 { + count {SELECT x, y FROM t1 WHERE x=3 AND w>=10 AND y=121} +} {3 121 3} +do_test where-1.11 { + count {SELECT x, y FROM t1 WHERE x=3 AND y=100 AND w<10} +} {3 100 3} + +# New for SQLite version 2.1: Verify that that inequality constraints +# are used correctly. +# +do_test where-1.12 { + count {SELECT w FROM t1 WHERE x=3 AND y<100} +} {8 3} +do_test where-1.13 { + count {SELECT w FROM t1 WHERE x=3 AND 100>y} +} {8 3} +do_test where-1.14 { + count {SELECT w FROM t1 WHERE 3=x AND y<100} +} {8 3} +do_test where-1.15 { + count {SELECT w FROM t1 WHERE 3=x AND 100>y} +} {8 3} +do_test where-1.16 { + count {SELECT w FROM t1 WHERE x=3 AND y<=100} +} {8 9 5} +do_test where-1.17 { + count {SELECT w FROM t1 WHERE x=3 AND 100>=y} +} {8 9 5} +do_test where-1.18 { + count {SELECT w FROM t1 WHERE x=3 AND y>225} +} {15 3} +do_test where-1.19 { + count {SELECT w FROM t1 WHERE x=3 AND 225=225} +} {14 15 5} +do_test where-1.21 { + count {SELECT w FROM t1 WHERE x=3 AND 225<=y} +} {14 15 5} +do_test where-1.22 { + count {SELECT w FROM t1 WHERE x=3 AND y>121 AND y<196} +} {11 12 5} +do_test where-1.23 { + count {SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<=196} +} {10 11 12 13 9} +do_test where-1.24 { + count {SELECT w FROM t1 WHERE x=3 AND 121y} +} {11 12 5} +do_test where-1.25 { + count {SELECT w FROM t1 WHERE x=3 AND 121<=y AND 196>=y} +} {10 11 12 13 9} + +# Need to work on optimizing the BETWEEN operator. +# +# do_test where-1.26 { +# count {SELECT w FROM t1 WHERE x=3 AND y BETWEEN 121 AND 196} +# } {10 11 12 13 9} + +do_test where-1.27 { + count {SELECT w FROM t1 WHERE x=3 AND y+1==122} +} {10 10} + +do_test where-1.28 { + count {SELECT w FROM t1 WHERE x+1=4 AND y+1==122} +} {10 99} +do_test where-1.29 { + count {SELECT w FROM t1 WHERE y==121} +} {10 99} + + +do_test where-1.30 { + count {SELECT w FROM t1 WHERE w>97} +} {98 99 100 3} +do_test where-1.31 { + count {SELECT w FROM t1 WHERE w>=97} +} {97 98 99 100 4} +do_test where-1.33 { + count {SELECT w FROM t1 WHERE w==97} +} {97 2} +do_test where-1.33.1 { + count {SELECT w FROM t1 WHERE w<=97 AND w==97} +} {97 2} +do_test where-1.33.2 { + count {SELECT w FROM t1 WHERE w<98 AND w==97} +} {97 2} +do_test where-1.33.3 { + count {SELECT w FROM t1 WHERE w>=97 AND w==97} +} {97 2} +do_test where-1.33.4 { + count {SELECT w FROM t1 WHERE w>96 AND w==97} +} {97 2} +do_test where-1.33.5 { + count {SELECT w FROM t1 WHERE w==97 AND w==97} +} {97 2} +do_test where-1.34 { + count {SELECT w FROM t1 WHERE w+1==98} +} {97 99} +do_test where-1.35 { + count {SELECT w FROM t1 WHERE w<3} +} {1 2 2} +do_test where-1.36 { + count {SELECT w FROM t1 WHERE w<=3} +} {1 2 3 3} +do_test where-1.37 { + count {SELECT w FROM t1 WHERE w+1<=4 ORDER BY w} +} {1 2 3 99} + +do_test where-1.38 { + count {SELECT (w) FROM t1 WHERE (w)>(97)} +} {98 99 100 3} +do_test where-1.39 { + count {SELECT (w) FROM t1 WHERE (w)>=(97)} +} {97 98 99 100 4} +do_test where-1.40 { + count {SELECT (w) FROM t1 WHERE (w)==(97)} +} {97 2} +do_test where-1.41 { + count {SELECT (w) FROM t1 WHERE ((w)+(1))==(98)} +} {97 99} + + +# Do the same kind of thing except use a join as the data source. +# +do_test where-2.1 { + count { + SELECT w, p FROM t2, t1 + WHERE x=q AND y=s AND r=8977 + } +} {34 67 6} +do_test where-2.2 { + count { + SELECT w, p FROM t2, t1 + WHERE x=q AND s=y AND r=8977 + } +} {34 67 6} +do_test where-2.3 { + count { + SELECT w, p FROM t2, t1 + WHERE x=q AND s=y AND r=8977 AND w>10 + } +} {34 67 6} +do_test where-2.4 { + count { + SELECT w, p FROM t2, t1 + WHERE p<80 AND x=q AND s=y AND r=8977 AND w>10 + } +} {34 67 6} +do_test where-2.5 { + count { + SELECT w, p FROM t2, t1 + WHERE p<80 AND x=q AND 8977=r AND s=y AND w>10 + } +} {34 67 6} +do_test where-2.6 { + count { + SELECT w, p FROM t2, t1 + WHERE x=q AND p=77 AND s=y AND w>5 + } +} {24 77 6} +do_test where-2.7 { + count { + SELECT w, p FROM t1, t2 + WHERE x=q AND p>77 AND s=y AND w=5 + } +} {5 96 6} + +# Lets do a 3-way join. +# +do_test where-3.1 { + count { + SELECT A.w, B.p, C.w FROM t1 as A, t2 as B, t1 as C + WHERE C.w=101-B.p AND B.r=10202-A.y AND A.w=11 + } +} {11 90 11 8} +do_test where-3.2 { + count { + SELECT A.w, B.p, C.w FROM t1 as A, t2 as B, t1 as C + WHERE C.w=101-B.p AND B.r=10202-A.y AND A.w=12 + } +} {12 89 12 8} +do_test where-3.3 { + count { + SELECT A.w, B.p, C.w FROM t1 as A, t2 as B, t1 as C + WHERE A.w=15 AND B.p=C.w AND B.r=10202-A.y + } +} {15 86 86 8} + +# Test to see that the special case of a constant WHERE clause is +# handled. +# +do_test where-4.1 { + count { + SELECT * FROM t1 WHERE 0 + } +} {0} +do_test where-4.2 { + count { + SELECT * FROM t1 WHERE 1 LIMIT 1 + } +} {1 0 4 0} +do_test where-4.3 { + execsql { + SELECT 99 WHERE 0 + } +} {} +do_test where-4.4 { + execsql { + SELECT 99 WHERE 1 + } +} {99} +do_test where-4.5 { + execsql { + SELECT 99 WHERE 0.1 + } +} {99} +do_test where-4.6 { + execsql { + SELECT 99 WHERE 0.0 + } +} {} +do_test where-4.7 { + execsql { + SELECT count(*) FROM t1 WHERE t1.w + } +} {100} + +# Verify that IN operators in a WHERE clause are handled correctly. +# Omit these tests if the build is not capable of sub-queries. +# +ifcapable subquery { + do_test where-5.1 { + count { + SELECT * FROM t1 WHERE rowid IN (1,2,3,1234) order by 1; + } + } {1 0 4 2 1 9 3 1 16 4} + do_test where-5.2 { + count { + SELECT * FROM t1 WHERE rowid+0 IN (1,2,3,1234) order by 1; + } + } {1 0 4 2 1 9 3 1 16 102} + do_test where-5.3a { + count { + SELECT * FROM t1 WHERE w IN (-1,1,2,3) order by 1; + } + } {1 0 4 2 1 9 3 1 16 13} + do_test where-5.3b { + count { + SELECT * FROM t1 WHERE w IN (3,-1,1,2) order by 1; + } + } {1 0 4 2 1 9 3 1 16 13} + do_test where-5.3c { + count { + SELECT * FROM t1 WHERE w IN (3,2,-1,1,2) order by 1; + } + } {1 0 4 2 1 9 3 1 16 13} + do_test where-5.3d { + count { + SELECT * FROM t1 WHERE w IN (-1,1,2,3) order by 1 DESC; + } + } {3 1 16 2 1 9 1 0 4 12} + do_test where-5.4 { + count { + SELECT * FROM t1 WHERE w+0 IN (-1,1,2,3) order by 1; + } + } {1 0 4 2 1 9 3 1 16 102} + do_test where-5.5 { + count { + SELECT * FROM t1 WHERE rowid IN + (select rowid from t1 where rowid IN (-1,2,4)) + ORDER BY 1; + } + } {2 1 9 4 2 25 3} + do_test where-5.6 { + count { + SELECT * FROM t1 WHERE rowid+0 IN + (select rowid from t1 where rowid IN (-1,2,4)) + ORDER BY 1; + } + } {2 1 9 4 2 25 103} + do_test where-5.7 { + count { + SELECT * FROM t1 WHERE w IN + (select rowid from t1 where rowid IN (-1,2,4)) + ORDER BY 1; + } + } {2 1 9 4 2 25 9} + do_test where-5.8 { + count { + SELECT * FROM t1 WHERE w+0 IN + (select rowid from t1 where rowid IN (-1,2,4)) + ORDER BY 1; + } + } {2 1 9 4 2 25 103} + do_test where-5.9 { + count { + SELECT * FROM t1 WHERE x IN (1,7) ORDER BY 1; + } + } {2 1 9 3 1 16 7} + do_test where-5.10 { + count { + SELECT * FROM t1 WHERE x+0 IN (1,7) ORDER BY 1; + } + } {2 1 9 3 1 16 199} + do_test where-5.11 { + count { + SELECT * FROM t1 WHERE y IN (6400,8100) ORDER BY 1; + } + } {79 6 6400 89 6 8100 199} + do_test where-5.12 { + count { + SELECT * FROM t1 WHERE x=6 AND y IN (6400,8100) ORDER BY 1; + } + } {79 6 6400 89 6 8100 7} + do_test where-5.13 { + count { + SELECT * FROM t1 WHERE x IN (1,7) AND y NOT IN (6400,8100) ORDER BY 1; + } + } {2 1 9 3 1 16 7} + do_test where-5.14 { + count { + SELECT * FROM t1 WHERE x IN (1,7) AND y IN (9,10) ORDER BY 1; + } + } {2 1 9 8} + do_test where-5.15 { + count { + SELECT * FROM t1 WHERE x IN (1,7) AND y IN (9,16) ORDER BY 1; + } + } {2 1 9 3 1 16 11} + do_test where-5.100 { + db eval { + SELECT w, x, y FROM t1 WHERE x IN (1,5) AND y IN (9,8,3025,1000,3969) + ORDER BY x, y + } + } {2 1 9 54 5 3025 62 5 3969} + do_test where-5.101 { + db eval { + SELECT w, x, y FROM t1 WHERE x IN (1,5) AND y IN (9,8,3025,1000,3969) + ORDER BY x DESC, y DESC + } + } {62 5 3969 54 5 3025 2 1 9} + do_test where-5.102 { + db eval { + SELECT w, x, y FROM t1 WHERE x IN (1,5) AND y IN (9,8,3025,1000,3969) + ORDER BY x DESC, y + } + } {54 5 3025 62 5 3969 2 1 9} + do_test where-5.103 { + db eval { + SELECT w, x, y FROM t1 WHERE x IN (1,5) AND y IN (9,8,3025,1000,3969) + ORDER BY x, y DESC + } + } {2 1 9 62 5 3969 54 5 3025} +} + +# This procedure executes the SQL. Then it checks to see if the OP_Sort +# opcode was executed. If an OP_Sort did occur, then "sort" is appended +# to the result. If no OP_Sort happened, then "nosort" is appended. +# +# This procedure is used to check to make sure sorting is or is not +# occurring as expected. +# +proc cksort {sql} { + set data [execsql $sql] + if {[db status sort]} {set x sort} {set x nosort} + lappend data $x + return $data +} +# Check out the logic that attempts to implement the ORDER BY clause +# using an index rather than by sorting. +# +do_test where-6.1 { + execsql { + CREATE TABLE t3(a,b,c); + CREATE INDEX t3a ON t3(a); + CREATE INDEX t3bc ON t3(b,c); + CREATE INDEX t3acb ON t3(a,c,b); + INSERT INTO t3 SELECT w, 101-w, y FROM t1; + SELECT count(*), sum(a), sum(b), sum(c) FROM t3; + } +} {100 5050 5050 348550} +do_test where-6.2 { + cksort { + SELECT * FROM t3 ORDER BY a LIMIT 3 + } +} {1 100 4 2 99 9 3 98 16 nosort} +do_test where-6.3 { + cksort { + SELECT * FROM t3 ORDER BY a+1 LIMIT 3 + } +} {1 100 4 2 99 9 3 98 16 sort} +do_test where-6.4 { + cksort { + SELECT * FROM t3 WHERE a<10 ORDER BY a LIMIT 3 + } +} {1 100 4 2 99 9 3 98 16 nosort} +do_test where-6.5 { + cksort { + SELECT * FROM t3 WHERE a>0 AND a<10 ORDER BY a LIMIT 3 + } +} {1 100 4 2 99 9 3 98 16 nosort} +do_test where-6.6 { + cksort { + SELECT * FROM t3 WHERE a>0 ORDER BY a LIMIT 3 + } +} {1 100 4 2 99 9 3 98 16 nosort} +do_test where-6.7 { + cksort { + SELECT * FROM t3 WHERE b>0 ORDER BY a LIMIT 3 + } +} {1 100 4 2 99 9 3 98 16 nosort} +ifcapable subquery { + do_test where-6.8a { + cksort { + SELECT * FROM t3 WHERE a IN (3,5,7,1,9,4,2) ORDER BY a LIMIT 3 + } + } {1 100 4 2 99 9 3 98 16 nosort} + do_test where-6.8b { + cksort { + SELECT * FROM t3 WHERE a IN (3,5,7,1,9,4,2) ORDER BY a DESC LIMIT 3 + } + } {9 92 100 7 94 64 5 96 36 nosort} +} +do_test where-6.9.1 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.1.1 { + cksort { + SELECT * FROM t3 WHERE a>=1 AND a=1 AND c>0 ORDER BY a LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.1.2 { + cksort { + SELECT * FROM t3 WHERE a<2 AND a=1 AND c>0 ORDER BY a LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.2 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a,c LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.3 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY c LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.4 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a DESC LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.5 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a DESC, c DESC LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.6 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY c DESC LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.7 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY c,a LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.8 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a DESC, c ASC LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.9.9 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a ASC, c DESC LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.10 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.11 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a,c LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.12 { + cksort { + SELECT * FROM t3 WHERE a=1 AND c>0 ORDER BY a,c,b LIMIT 3 + } +} {1 100 4 nosort} +do_test where-6.13 { + cksort { + SELECT * FROM t3 WHERE a>0 ORDER BY a DESC LIMIT 3 + } +} {100 1 10201 99 2 10000 98 3 9801 nosort} +do_test where-6.13.1 { + cksort { + SELECT * FROM t3 WHERE a>0 ORDER BY -a LIMIT 3 + } +} {100 1 10201 99 2 10000 98 3 9801 sort} +do_test where-6.14 { + cksort { + SELECT * FROM t3 ORDER BY b LIMIT 3 + } +} {100 1 10201 99 2 10000 98 3 9801 nosort} +do_test where-6.15 { + cksort { + SELECT t3.a, t1.x FROM t3, t1 WHERE t3.a=t1.w ORDER BY t3.a LIMIT 3 + } +} {1 0 2 1 3 1 nosort} +do_test where-6.16 { + cksort { + SELECT t3.a, t1.x FROM t3, t1 WHERE t3.a=t1.w ORDER BY t1.x, t3.a LIMIT 3 + } +} {1 0 2 1 3 1 sort} +do_test where-6.19 { + cksort { + SELECT y FROM t1 ORDER BY w LIMIT 3; + } +} {4 9 16 nosort} +do_test where-6.20 { + cksort { + SELECT y FROM t1 ORDER BY rowid LIMIT 3; + } +} {4 9 16 nosort} +do_test where-6.21 { + cksort { + SELECT y FROM t1 ORDER BY rowid, y LIMIT 3; + } +} {4 9 16 nosort} +do_test where-6.22 { + cksort { + SELECT y FROM t1 ORDER BY rowid, y DESC LIMIT 3; + } +} {4 9 16 nosort} +do_test where-6.23 { + cksort { + SELECT y FROM t1 WHERE y>4 ORDER BY rowid, w, x LIMIT 3; + } +} {9 16 25 nosort} +do_test where-6.24 { + cksort { + SELECT y FROM t1 WHERE y>=9 ORDER BY rowid, x DESC, w LIMIT 3; + } +} {9 16 25 nosort} +do_test where-6.25 { + cksort { + SELECT y FROM t1 WHERE y>4 AND y<25 ORDER BY rowid; + } +} {9 16 nosort} +do_test where-6.26 { + cksort { + SELECT y FROM t1 WHERE y>=4 AND y<=25 ORDER BY oid; + } +} {4 9 16 25 nosort} +do_test where-6.27 { + cksort { + SELECT y FROM t1 WHERE y<=25 ORDER BY _rowid_, w+y; + } +} {4 9 16 25 nosort} + + +# Tests for reverse-order sorting. +# +do_test where-7.1 { + cksort { + SELECT w FROM t1 WHERE x=3 ORDER BY y; + } +} {8 9 10 11 12 13 14 15 nosort} +do_test where-7.2 { + cksort { + SELECT w FROM t1 WHERE x=3 ORDER BY y DESC; + } +} {15 14 13 12 11 10 9 8 nosort} +do_test where-7.3 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>100 ORDER BY y LIMIT 3; + } +} {10 11 12 nosort} +do_test where-7.4 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>100 ORDER BY y DESC LIMIT 3; + } +} {15 14 13 nosort} +do_test where-7.5 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>121 ORDER BY y DESC; + } +} {15 14 13 12 11 nosort} +do_test where-7.6 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>=121 ORDER BY y DESC; + } +} {15 14 13 12 11 10 nosort} +do_test where-7.7 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<196 ORDER BY y DESC; + } +} {12 11 10 nosort} +do_test where-7.8 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<=196 ORDER BY y DESC; + } +} {13 12 11 10 nosort} +do_test where-7.9 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>121 AND y<=196 ORDER BY y DESC; + } +} {13 12 11 nosort} +do_test where-7.10 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>100 AND y<196 ORDER BY y DESC; + } +} {12 11 10 nosort} +do_test where-7.11 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<196 ORDER BY y; + } +} {10 11 12 nosort} +do_test where-7.12 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>=121 AND y<=196 ORDER BY y; + } +} {10 11 12 13 nosort} +do_test where-7.13 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>121 AND y<=196 ORDER BY y; + } +} {11 12 13 nosort} +do_test where-7.14 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>100 AND y<196 ORDER BY y; + } +} {10 11 12 nosort} +do_test where-7.15 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y<81 ORDER BY y; + } +} {nosort} +do_test where-7.16 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y<=81 ORDER BY y; + } +} {8 nosort} +do_test where-7.17 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>256 ORDER BY y; + } +} {nosort} +do_test where-7.18 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>=256 ORDER BY y; + } +} {15 nosort} +do_test where-7.19 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y<81 ORDER BY y DESC; + } +} {nosort} +do_test where-7.20 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y<=81 ORDER BY y DESC; + } +} {8 nosort} +do_test where-7.21 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>256 ORDER BY y DESC; + } +} {nosort} +do_test where-7.22 { + cksort { + SELECT w FROM t1 WHERE x=3 AND y>=256 ORDER BY y DESC; + } +} {15 nosort} +do_test where-7.23 { + cksort { + SELECT w FROM t1 WHERE x=0 AND y<4 ORDER BY y; + } +} {nosort} +do_test where-7.24 { + cksort { + SELECT w FROM t1 WHERE x=0 AND y<=4 ORDER BY y; + } +} {1 nosort} +do_test where-7.25 { + cksort { + SELECT w FROM t1 WHERE x=6 AND y>10201 ORDER BY y; + } +} {nosort} +do_test where-7.26 { + cksort { + SELECT w FROM t1 WHERE x=6 AND y>=10201 ORDER BY y; + } +} {100 nosort} +do_test where-7.27 { + cksort { + SELECT w FROM t1 WHERE x=0 AND y<4 ORDER BY y DESC; + } +} {nosort} +do_test where-7.28 { + cksort { + SELECT w FROM t1 WHERE x=0 AND y<=4 ORDER BY y DESC; + } +} {1 nosort} +do_test where-7.29 { + cksort { + SELECT w FROM t1 WHERE x=6 AND y>10201 ORDER BY y DESC; + } +} {nosort} +do_test where-7.30 { + cksort { + SELECT w FROM t1 WHERE x=6 AND y>=10201 ORDER BY y DESC; + } +} {100 nosort} +do_test where-7.31 { + cksort { + SELECT y FROM t1 ORDER BY rowid DESC LIMIT 3 + } +} {10201 10000 9801 nosort} +do_test where-7.32 { + cksort { + SELECT y FROM t1 WHERE y<25 ORDER BY rowid DESC + } +} {16 9 4 nosort} +do_test where-7.33 { + cksort { + SELECT y FROM t1 WHERE y<=25 ORDER BY rowid DESC + } +} {25 16 9 4 nosort} +do_test where-7.34 { + cksort { + SELECT y FROM t1 WHERE y<25 AND y>4 ORDER BY rowid DESC, y DESC + } +} {16 9 nosort} +do_test where-7.35 { + cksort { + SELECT y FROM t1 WHERE y<25 AND y>=4 ORDER BY rowid DESC + } +} {16 9 4 nosort} + +do_test where-8.1 { + execsql { + CREATE TABLE t4 AS SELECT * FROM t1; + CREATE INDEX i4xy ON t4(x,y); + } + cksort { + SELECT w FROM t4 WHERE x=4 and y<1000 ORDER BY y DESC limit 3; + } +} {30 29 28 nosort} +do_test where-8.2 { + execsql { + DELETE FROM t4; + } + cksort { + SELECT w FROM t4 WHERE x=4 and y<1000 ORDER BY y DESC limit 3; + } +} {nosort} + +# Make sure searches with an index work with an empty table. +# +do_test where-9.1 { + execsql { + CREATE TABLE t5(x PRIMARY KEY); + SELECT * FROM t5 WHERE x<10; + } +} {} +do_test where-9.2 { + execsql { + SELECT * FROM t5 WHERE x<10 ORDER BY x DESC; + } +} {} +do_test where-9.3 { + execsql { + SELECT * FROM t5 WHERE x=10; + } +} {} + +do_test where-10.1 { + execsql { + SELECT 1 WHERE abs(random())<0 + } +} {} +do_test where-10.2 { + proc tclvar_func {vname} {return [set ::$vname]} + db function tclvar tclvar_func + set ::v1 0 + execsql { + SELECT count(*) FROM t1 WHERE tclvar('v1'); + } +} {0} +do_test where-10.3 { + set ::v1 1 + execsql { + SELECT count(*) FROM t1 WHERE tclvar('v1'); + } +} {100} +do_test where-10.4 { + set ::v1 1 + proc tclvar_func {vname} { + upvar #0 $vname v + set v [expr {!$v}] + return $v + } + execsql { + SELECT count(*) FROM t1 WHERE tclvar('v1'); + } +} {50} + +# Ticket #1376. The query below was causing a segfault. +# The problem was the age-old error of calling realloc() on an +# array while there are still pointers to individual elements of +# that array. +# +do_test where-11.1 { + execsql { + CREATE TABLE t99(Dte INT, X INT); + DELETE FROM t99 WHERE (Dte = 2451337) OR (Dte = 2451339) OR + (Dte BETWEEN 2451345 AND 2451347) OR (Dte = 2451351) OR + (Dte BETWEEN 2451355 AND 2451356) OR (Dte = 2451358) OR + (Dte = 2451362) OR (Dte = 2451365) OR (Dte = 2451367) OR + (Dte BETWEEN 2451372 AND 2451376) OR (Dte BETWEEN 2451382 AND 2451384) OR + (Dte = 2451387) OR (Dte BETWEEN 2451389 AND 2451391) OR + (Dte BETWEEN 2451393 AND 2451395) OR (Dte = 2451400) OR + (Dte = 2451402) OR (Dte = 2451404) OR (Dte BETWEEN 2451416 AND 2451418) OR + (Dte = 2451422) OR (Dte = 2451426) OR (Dte BETWEEN 2451445 AND 2451446) OR + (Dte = 2451456) OR (Dte = 2451458) OR (Dte BETWEEN 2451465 AND 2451467) OR + (Dte BETWEEN 2451469 AND 2451471) OR (Dte = 2451474) OR + (Dte BETWEEN 2451477 AND 2451501) OR (Dte BETWEEN 2451503 AND 2451509) OR + (Dte BETWEEN 2451511 AND 2451514) OR (Dte BETWEEN 2451518 AND 2451521) OR + (Dte BETWEEN 2451523 AND 2451531) OR (Dte BETWEEN 2451533 AND 2451537) OR + (Dte BETWEEN 2451539 AND 2451544) OR (Dte BETWEEN 2451546 AND 2451551) OR + (Dte BETWEEN 2451553 AND 2451555) OR (Dte = 2451557) OR + (Dte BETWEEN 2451559 AND 2451561) OR (Dte = 2451563) OR + (Dte BETWEEN 2451565 AND 2451566) OR (Dte BETWEEN 2451569 AND 2451571) OR + (Dte = 2451573) OR (Dte = 2451575) OR (Dte = 2451577) OR (Dte = 2451581) OR + (Dte BETWEEN 2451583 AND 2451586) OR (Dte BETWEEN 2451588 AND 2451592) OR + (Dte BETWEEN 2451596 AND 2451598) OR (Dte = 2451600) OR + (Dte BETWEEN 2451602 AND 2451603) OR (Dte = 2451606) OR (Dte = 2451611); + } +} {} + +# Ticket #2116: Make sure sorting by index works well with nn INTEGER PRIMARY +# KEY. +# +do_test where-12.1 { + execsql { + CREATE TABLE t6(a INTEGER PRIMARY KEY, b TEXT); + INSERT INTO t6 VALUES(1,'one'); + INSERT INTO t6 VALUES(4,'four'); + CREATE INDEX t6i1 ON t6(b); + } + cksort { + SELECT * FROM t6 ORDER BY b; + } +} {4 four 1 one nosort} +do_test where-12.2 { + cksort { + SELECT * FROM t6 ORDER BY b, a; + } +} {4 four 1 one nosort} +do_test where-12.3 { + cksort { + SELECT * FROM t6 ORDER BY a; + } +} {1 one 4 four nosort} +do_test where-12.4 { + cksort { + SELECT * FROM t6 ORDER BY a, b; + } +} {1 one 4 four nosort} +do_test where-12.5 { + cksort { + SELECT * FROM t6 ORDER BY b DESC; + } +} {1 one 4 four nosort} +do_test where-12.6 { + cksort { + SELECT * FROM t6 ORDER BY b DESC, a DESC; + } +} {1 one 4 four nosort} +do_test where-12.7 { + cksort { + SELECT * FROM t6 ORDER BY b DESC, a ASC; + } +} {1 one 4 four sort} +do_test where-12.8 { + cksort { + SELECT * FROM t6 ORDER BY b ASC, a DESC; + } +} {4 four 1 one sort} +do_test where-12.9 { + cksort { + SELECT * FROM t6 ORDER BY a DESC; + } +} {4 four 1 one nosort} +do_test where-12.10 { + cksort { + SELECT * FROM t6 ORDER BY a DESC, b DESC; + } +} {4 four 1 one nosort} +do_test where-12.11 { + cksort { + SELECT * FROM t6 ORDER BY a DESC, b ASC; + } +} {4 four 1 one nosort} +do_test where-12.12 { + cksort { + SELECT * FROM t6 ORDER BY a ASC, b DESC; + } +} {1 one 4 four nosort} +do_test where-13.1 { + execsql { + CREATE TABLE t7(a INTEGER PRIMARY KEY, b TEXT); + INSERT INTO t7 VALUES(1,'one'); + INSERT INTO t7 VALUES(4,'four'); + CREATE INDEX t7i1 ON t7(b); + } + cksort { + SELECT * FROM t7 ORDER BY b; + } +} {4 four 1 one nosort} +do_test where-13.2 { + cksort { + SELECT * FROM t7 ORDER BY b, a; + } +} {4 four 1 one nosort} +do_test where-13.3 { + cksort { + SELECT * FROM t7 ORDER BY a; + } +} {1 one 4 four nosort} +do_test where-13.4 { + cksort { + SELECT * FROM t7 ORDER BY a, b; + } +} {1 one 4 four nosort} +do_test where-13.5 { + cksort { + SELECT * FROM t7 ORDER BY b DESC; + } +} {1 one 4 four nosort} +do_test where-13.6 { + cksort { + SELECT * FROM t7 ORDER BY b DESC, a DESC; + } +} {1 one 4 four nosort} +do_test where-13.7 { + cksort { + SELECT * FROM t7 ORDER BY b DESC, a ASC; + } +} {1 one 4 four sort} +do_test where-13.8 { + cksort { + SELECT * FROM t7 ORDER BY b ASC, a DESC; + } +} {4 four 1 one sort} +do_test where-13.9 { + cksort { + SELECT * FROM t7 ORDER BY a DESC; + } +} {4 four 1 one nosort} +do_test where-13.10 { + cksort { + SELECT * FROM t7 ORDER BY a DESC, b DESC; + } +} {4 four 1 one nosort} +do_test where-13.11 { + cksort { + SELECT * FROM t7 ORDER BY a DESC, b ASC; + } +} {4 four 1 one nosort} +do_test where-13.12 { + cksort { + SELECT * FROM t7 ORDER BY a ASC, b DESC; + } +} {1 one 4 four nosort} + +# Ticket #2211. +# +# When optimizing out ORDER BY clauses, make sure that trailing terms +# of the ORDER BY clause do not reference other tables in a join. +# +if {[permutation] != "no_optimization"} { +do_test where-14.1 { + execsql { + CREATE TABLE t8(a INTEGER PRIMARY KEY, b TEXT UNIQUE, c CHAR(100)); + INSERT INTO t8(a,b) VALUES(1,'one'); + INSERT INTO t8(a,b) VALUES(4,'four'); + } + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.a, y.b + } +} {1/4 1/1 4/4 4/1 nosort} +do_test where-14.2 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.a, y.b DESC + } +} {1/1 1/4 4/1 4/4 nosort} +do_test where-14.3 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.a, x.b + } +} {1/4 1/1 4/4 4/1 nosort} +do_test where-14.4 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.a, x.b DESC + } +} {1/4 1/1 4/4 4/1 nosort} +do_test where-14.5 { + # This test case changed from "nosort" to "sort". See ticket 2a5629202f. + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a||x.b + } +} {/4/[14] 4/[14] 1/[14] 1/[14] sort/} +do_test where-14.6 { + # This test case changed from "nosort" to "sort". See ticket 2a5629202f. + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a||x.b DESC + } +} {/4/[14] 4/[14] 1/[14] 1/[14] sort/} +do_test where-14.7 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, y.a||y.b + } +} {4/1 4/4 1/1 1/4 sort} +do_test where-14.7.1 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a, y.a||y.b + } +} {4/1 4/4 1/1 1/4 sort} +do_test where-14.7.2 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a, x.a||x.b + } +} {4/4 4/1 1/4 1/1 nosort} +do_test where-14.8 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, y.a||y.b DESC + } +} {4/4 4/1 1/4 1/1 sort} +do_test where-14.9 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a||y.b + } +} {4/4 4/1 1/4 1/1 sort} +do_test where-14.10 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, x.a||y.b DESC + } +} {4/1 4/4 1/1 1/4 sort} +do_test where-14.11 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, y.a||x.b + } +} {4/1 4/4 1/1 1/4 sort} +do_test where-14.12 { + cksort { + SELECT x.a || '/' || y.a FROM t8 x, t8 y ORDER BY x.b, y.a||x.b DESC + } +} {4/4 4/1 1/4 1/1 sort} +} ;# {permutation != "no_optimization"} + +# Ticket #2445. +# +# There was a crash that could occur when a where clause contains an +# alias for an expression in the result set, and that expression retrieves +# a column of the second or subsequent table in a join. +# +do_test where-15.1 { + execsql { + CREATE TEMP TABLE t1 (a, b, c, d, e); + CREATE TEMP TABLE t2 (f); + SELECT t1.e AS alias FROM t2, t1 WHERE alias = 1 ; + } +} {} + +# Ticket #3408. +# +# The branch of code in where.c that generated rowid lookups was +# incorrectly deallocating a constant register, meaning that if the +# vdbe code ran more than once, the second time around the constant +# value may have been clobbered by some other value. +# +do_test where-16.1 { + execsql { + CREATE TABLE a1(id INTEGER PRIMARY KEY, v); + CREATE TABLE a2(id INTEGER PRIMARY KEY, v); + INSERT INTO a1 VALUES(1, 'one'); + INSERT INTO a1 VALUES(2, 'two'); + INSERT INTO a2 VALUES(1, 'one'); + INSERT INTO a2 VALUES(2, 'two'); + } +} {} +do_test where-16.2 { + execsql { + SELECT * FROM a2 CROSS JOIN a1 WHERE a1.id=1 AND a1.v='one'; + } +} {1 one 1 one 2 two 1 one} + +# The actual problem reported in #3408. +do_test where-16.3 { + execsql { + CREATE TEMP TABLE foo(idx INTEGER); + INSERT INTO foo VALUES(1); + INSERT INTO foo VALUES(1); + INSERT INTO foo VALUES(1); + INSERT INTO foo VALUES(2); + INSERT INTO foo VALUES(2); + CREATE TEMP TABLE bar(stuff INTEGER); + INSERT INTO bar VALUES(100); + INSERT INTO bar VALUES(200); + INSERT INTO bar VALUES(300); + } +} {} +do_test where-16.4 { + execsql { + SELECT bar.RowID id FROM foo, bar WHERE foo.idx = bar.RowID AND id = 2; + } +} {2 2} + +integrity_check {where-99.0} + +#--------------------------------------------------------------------- +# These tests test that a bug surrounding the use of ForceInt has been +# fixed in where.c. +# +do_test where-17.1 { + execsql { + CREATE TABLE tbooking ( + id INTEGER PRIMARY KEY, + eventtype INTEGER NOT NULL + ); + INSERT INTO tbooking VALUES(42, 3); + INSERT INTO tbooking VALUES(43, 4); + } +} {} +do_test where-17.2 { + execsql { + SELECT a.id + FROM tbooking AS a + WHERE a.eventtype=3; + } +} {42} +do_test where-17.3 { + execsql { + SELECT a.id, (SELECT b.id FROM tbooking AS b WHERE b.id>a.id) + FROM tbooking AS a + WHERE a.eventtype=3; + } +} {42 43} +do_test where-17.4 { + execsql { + SELECT a.id, (SELECT b.id FROM tbooking AS b WHERE b.id>a.id) + FROM (SELECT 1.5 AS id) AS a + } +} {1.5 42} +do_test where-17.5 { + execsql { + CREATE TABLE tother(a, b); + INSERT INTO tother VALUES(1, 3.7); + SELECT id, a FROM tbooking, tother WHERE id>a; + } +} {42 1 43 1} + +# Ticket [be84e357c035d068135f20bcfe82761bbf95006b] 2013-09-03 +# Segfault during query involving LEFT JOIN column in the ORDER BY clause. +# +do_execsql_test where-18.1 { + CREATE TABLE t181(a); + CREATE TABLE t182(b,c); + INSERT INTO t181 VALUES(1); + SELECT DISTINCT a FROM t181 LEFT JOIN t182 ON a=b ORDER BY c IS NULL; +} {1} +do_execsql_test where-18.2 { + SELECT DISTINCT a FROM t181 LEFT JOIN t182 ON a=b ORDER BY +c; +} {1} +do_execsql_test where-18.3 { + SELECT DISTINCT a FROM t181 LEFT JOIN t182 ON a=b ORDER BY c; +} {1} +do_execsql_test where-18.4 { + INSERT INTO t181 VALUES(1),(1),(1),(1); + SELECT DISTINCT a FROM t181 LEFT JOIN t182 ON a=b ORDER BY +c; +} {1} +do_execsql_test where-18.5 { + INSERT INTO t181 VALUES(2); + SELECT DISTINCT a FROM t181 LEFT JOIN t182 ON a=b ORDER BY c IS NULL, +a; +} {1 2} +do_execsql_test where-18.6 { + INSERT INTO t181 VALUES(2); + SELECT DISTINCT a FROM t181 LEFT JOIN t182 ON a=b ORDER BY +a, +c IS NULL; +} {1 2} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where2.test b/components/external/SQLite-3.8.1/test/where2.test new file mode 100644 index 0000000000000000000000000000000000000000..45ea486d959577608eba0eae22060cd39491a743 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where2.test @@ -0,0 +1,719 @@ +# 2005 July 28 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the use of indices in WHERE clauses +# based on recent changes to the optimizer. +# +# $Id: where2.test,v 1.15 2009/02/02 01:50:40 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build some test data +# +do_test where2-1.0 { + execsql { + BEGIN; + CREATE TABLE t1(w int, x int, y int, z int); + } + for {set i 1} {$i<=100} {incr i} { + set w $i + set x [expr {int(log($i)/log(2))}] + set y [expr {$i*$i + 2*$i + 1}] + set z [expr {$x+$y}] + ifcapable tclvar { + execsql {INSERT INTO t1 VALUES($::w,$::x,$::y,$::z)} + } else { + execsql {INSERT INTO t1 VALUES(:w,:x,:y,:z)} + } + } + execsql { + CREATE UNIQUE INDEX i1w ON t1(w); + CREATE INDEX i1xy ON t1(x,y); + CREATE INDEX i1zyx ON t1(z,y,x); + COMMIT; + } +} {} + +# Do an SQL statement. Append the search count to the end of the result. +# +proc count sql { + set ::sqlite_search_count 0 + return [concat [execsql $sql] $::sqlite_search_count] +} + +# This procedure executes the SQL. Then it checks to see if the OP_Sort +# opcode was executed. If an OP_Sort did occur, then "sort" is appended +# to the result. If no OP_Sort happened, then "nosort" is appended. +# +# This procedure is used to check to make sure sorting is or is not +# occurring as expected. +# +proc cksort {sql} { + set data [execsql $sql] + if {[db status sort]} {set x sort} {set x nosort} + lappend data $x + return $data +} + +# This procedure executes the SQL. Then it appends to the result the +# "sort" or "nosort" keyword (as in the cksort procedure above) then +# it appends the name of the table and index used. +# +proc queryplan {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + if {$::sqlite_sort_count} {set x sort} {set x nosort} + lappend data $x + set eqp [execsql "EXPLAIN QUERY PLAN $sql"] + # puts eqp=$eqp + foreach {a b c x} $eqp { + if {[regexp { TABLE (\w+ AS )?(\w+) USING.* INDEX (\w+)\y} \ + $x all as tab idx]} { + lappend data $tab $idx + } elseif {[regexp { TABLE (\w+ AS )?(\w+)\y} $x all as tab]} { + lappend data $tab * + } + } + return $data +} + + +# Prefer a UNIQUE index over another index. +# +do_test where2-1.1 { + queryplan { + SELECT * FROM t1 WHERE w=85 AND x=6 AND y=7396 + } +} {85 6 7396 7402 nosort t1 i1w} + +# Always prefer a rowid== constraint over any other index. +# +do_test where2-1.3 { + queryplan { + SELECT * FROM t1 WHERE w=85 AND x=6 AND y=7396 AND rowid=85 + } +} {85 6 7396 7402 nosort t1 *} + +# When constrained by a UNIQUE index, the ORDER BY clause is always ignored. +# +do_test where2-2.1 { + queryplan { + SELECT * FROM t1 WHERE w=85 ORDER BY random(); + } +} {85 6 7396 7402 nosort t1 i1w} +do_test where2-2.2 { + queryplan { + SELECT * FROM t1 WHERE x=6 AND y=7396 ORDER BY random(); + } +} {85 6 7396 7402 sort t1 i1xy} +do_test where2-2.3 { + queryplan { + SELECT * FROM t1 WHERE rowid=85 AND x=6 AND y=7396 ORDER BY random(); + } +} {85 6 7396 7402 nosort t1 *} + + +# Efficient handling of forward and reverse table scans. +# +do_test where2-3.1 { + queryplan { + SELECT * FROM t1 ORDER BY rowid LIMIT 2 + } +} {1 0 4 4 2 1 9 10 nosort t1 *} +do_test where2-3.2 { + queryplan { + SELECT * FROM t1 ORDER BY rowid DESC LIMIT 2 + } +} {100 6 10201 10207 99 6 10000 10006 nosort t1 *} + +# The IN operator can be used by indices at multiple layers +# +ifcapable subquery { + do_test where2-4.1 { + queryplan { + SELECT * FROM t1 WHERE z IN (10207,10006) AND y IN (10000,10201) + AND x>0 AND x<10 + ORDER BY w + } + } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx} + do_test where2-4.2 { + queryplan { + SELECT * FROM t1 WHERE z IN (10207,10006) AND y=10000 + AND x>0 AND x<10 + ORDER BY w + } + } {99 6 10000 10006 sort t1 i1zyx} + do_test where2-4.3 { + queryplan { + SELECT * FROM t1 WHERE z=10006 AND y IN (10000,10201) + AND x>0 AND x<10 + ORDER BY w + } + } {99 6 10000 10006 sort t1 i1zyx} + ifcapable compound { + do_test where2-4.4 { + queryplan { + SELECT * FROM t1 WHERE z IN (SELECT 10207 UNION SELECT 10006) + AND y IN (10000,10201) + AND x>0 AND x<10 + ORDER BY w + } + } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx} + do_test where2-4.5 { + queryplan { + SELECT * FROM t1 WHERE z IN (SELECT 10207 UNION SELECT 10006) + AND y IN (SELECT 10000 UNION SELECT 10201) + AND x>0 AND x<10 + ORDER BY w + } + } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx} + } + do_test where2-4.6a { + queryplan { + SELECT * FROM t1 + WHERE x IN (1,2,3,4,5,6,7,8) + AND y IN (10000,10001,10002,10003,10004,10005) + ORDER BY x + } + } {99 6 10000 10006 nosort t1 i1xy} + do_test where2-4.6b { + queryplan { + SELECT * FROM t1 + WHERE x IN (1,2,3,4,5,6,7,8) + AND y IN (10000,10001,10002,10003,10004,10005) + ORDER BY x DESC + } + } {99 6 10000 10006 nosort t1 i1xy} + do_test where2-4.6c { + queryplan { + SELECT * FROM t1 + WHERE x IN (1,2,3,4,5,6,7,8) + AND y IN (10000,10001,10002,10003,10004,10005) + ORDER BY x, y + } + } {99 6 10000 10006 nosort t1 i1xy} + do_test where2-4.6d { + queryplan { + SELECT * FROM t1 + WHERE x IN (1,2,3,4,5,6,7,8) + AND y IN (10000,10001,10002,10003,10004,10005) + ORDER BY x, y DESC + } + } {99 6 10000 10006 sort t1 i1xy} + + # Duplicate entires on the RHS of an IN operator do not cause duplicate + # output rows. + # + do_test where2-4.6x { + queryplan { + SELECT * FROM t1 WHERE z IN (10207,10006,10006,10207) + ORDER BY w + } + } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx} + do_test where2-4.6y { + queryplan { + SELECT * FROM t1 WHERE z IN (10207,10006,10006,10207) + ORDER BY w DESC + } + } {100 6 10201 10207 99 6 10000 10006 sort t1 i1zyx} + ifcapable compound { + do_test where2-4.7 { + queryplan { + SELECT * FROM t1 WHERE z IN ( + SELECT 10207 UNION ALL SELECT 10006 + UNION ALL SELECT 10006 UNION ALL SELECT 10207) + ORDER BY w + } + } {99 6 10000 10006 100 6 10201 10207 sort t1 i1zyx} + } + +} ;# ifcapable subquery + +# The use of an IN operator disables the index as a sorter. +# +do_test where2-5.1 { + queryplan { + SELECT * FROM t1 WHERE w=99 ORDER BY w + } +} {99 6 10000 10006 nosort t1 i1w} + +ifcapable subquery { + do_test where2-5.2a { + queryplan { + SELECT * FROM t1 WHERE w IN (99) ORDER BY w + } + } {99 6 10000 10006 nosort t1 i1w} + do_test where2-5.2b { + queryplan { + SELECT * FROM t1 WHERE w IN (99) ORDER BY w DESC + } + } {99 6 10000 10006 nosort t1 i1w} +} + +# Verify that OR clauses get translated into IN operators. +# +set ::idx {} +ifcapable subquery {set ::idx i1w} +do_test where2-6.1.1 { + queryplan { + SELECT * FROM t1 WHERE w=99 OR w=100 ORDER BY +w + } +} [list 99 6 10000 10006 100 6 10201 10207 sort t1 $::idx] +do_test where2-6.1.2 { + queryplan { + SELECT * FROM t1 WHERE 99=w OR 100=w ORDER BY +w + } +} [list 99 6 10000 10006 100 6 10201 10207 sort t1 $::idx] +do_test where2-6.2 { + queryplan { + SELECT * FROM t1 WHERE w=99 OR w=100 OR 6=w ORDER BY +w + } +} [list 6 2 49 51 99 6 10000 10006 100 6 10201 10207 sort t1 $::idx] + +do_test where2-6.3 { + queryplan { + SELECT * FROM t1 WHERE w=99 OR w=100 OR 6=+w ORDER BY +w + } +} {6 2 49 51 99 6 10000 10006 100 6 10201 10207 sort t1 *} +do_test where2-6.4 { + queryplan { + SELECT * FROM t1 WHERE w=99 OR +w=100 OR 6=w ORDER BY +w + } +} {6 2 49 51 99 6 10000 10006 100 6 10201 10207 sort t1 *} + +set ::idx {} +ifcapable subquery {set ::idx i1zyx} +do_test where2-6.5 { + queryplan { + SELECT b.* FROM t1 a, t1 b + WHERE a.w=1 AND (a.y=b.z OR b.z=10) + ORDER BY +b.w + } +} [list 1 0 4 4 2 1 9 10 sort a i1w b $::idx] +do_test where2-6.6 { + queryplan { + SELECT b.* FROM t1 a, t1 b + WHERE a.w=1 AND (b.z=10 OR a.y=b.z OR b.z=10) + ORDER BY +b.w + } +} [list 1 0 4 4 2 1 9 10 sort a i1w b $::idx] + +if {[permutation] != "no_optimization"} { + +# Ticket #2249. Make sure the OR optimization is not attempted if +# comparisons between columns of different affinities are needed. +# +do_test where2-6.7 { + execsql { + CREATE TABLE t2249a(a TEXT UNIQUE, x CHAR(100)); + CREATE TABLE t2249b(b INTEGER); + INSERT INTO t2249a(a) VALUES('0123'); + INSERT INTO t2249b VALUES(123); + } + queryplan { + -- Because a is type TEXT and b is type INTEGER, both a and b + -- will attempt to convert to NUMERIC before the comparison. + -- They will thus compare equal. + -- + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE a=b; + } +} {123 0123 nosort t2249b * t2249a sqlite_autoindex_t2249a_1} +do_test where2-6.9 { + queryplan { + -- The + operator removes affinity from the rhs. No conversions + -- occur and the comparison is false. The result is an empty set. + -- + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE a=+b; + } +} {nosort t2249b * t2249a sqlite_autoindex_t2249a_1} +do_test where2-6.9.2 { + # The same thing but with the expression flipped around. + queryplan { + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE +b=a + } +} {nosort t2249b * t2249a sqlite_autoindex_t2249a_1} +do_test where2-6.10 { + queryplan { + -- Use + on both sides of the comparison to disable indices + -- completely. Make sure we get the same result. + -- + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE +a=+b; + } +} {nosort t2249b * t2249a sqlite_autoindex_t2249a_1} +do_test where2-6.11 { + # This will not attempt the OR optimization because of the a=b + # comparison. + queryplan { + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE a=b OR a='hello'; + } +} {123 0123 nosort t2249b * t2249a sqlite_autoindex_t2249a_1} +do_test where2-6.11.2 { + # Permutations of the expression terms. + queryplan { + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE b=a OR a='hello'; + } +} {123 0123 nosort t2249b * t2249a sqlite_autoindex_t2249a_1} +do_test where2-6.11.3 { + # Permutations of the expression terms. + queryplan { + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE 'hello'=a OR b=a; + } +} {123 0123 nosort t2249b * t2249a sqlite_autoindex_t2249a_1} +do_test where2-6.11.4 { + # Permutations of the expression terms. + queryplan { + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE a='hello' OR b=a; + } +} {123 0123 nosort t2249b * t2249a sqlite_autoindex_t2249a_1} +ifcapable explain&&subquery { + # These tests are not run if subquery support is not included in the + # build. This is because these tests test the "a = 1 OR a = 2" to + # "a IN (1, 2)" optimisation transformation, which is not enabled if + # subqueries and the IN operator is not available. + # + do_test where2-6.12 { + # In this case, the +b disables the affinity conflict and allows + # the OR optimization to be used again. The result is now an empty + # set, the same as in where2-6.9. + queryplan { + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE a=+b OR a='hello'; + } + } {nosort t2249b * t2249a sqlite_autoindex_t2249a_1} + do_test where2-6.12.2 { + # In this case, the +b disables the affinity conflict and allows + # the OR optimization to be used again. The result is now an empty + # set, the same as in where2-6.9. + queryplan { + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE a='hello' OR +b=a; + } + } {nosort t2249b * t2249a sqlite_autoindex_t2249a_1} + do_test where2-6.12.3 { + # In this case, the +b disables the affinity conflict and allows + # the OR optimization to be used again. The result is now an empty + # set, the same as in where2-6.9. + queryplan { + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE +b=a OR a='hello'; + } + } {nosort t2249b * t2249a sqlite_autoindex_t2249a_1} + do_test where2-6.13 { + # The addition of +a on the second term disabled the OR optimization. + # But we should still get the same empty-set result as in where2-6.9. + queryplan { + SELECT b,a FROM t2249b CROSS JOIN t2249a WHERE a=+b OR +a='hello'; + } + } {nosort t2249b * t2249a sqlite_autoindex_t2249a_1} +} + +# Variations on the order of terms in a WHERE clause in order +# to make sure the OR optimizer can recognize them all. +do_test where2-6.20 { + queryplan { + SELECT x.a, y.a FROM t2249a x CROSS JOIN t2249a y WHERE x.a=y.a + } +} {0123 0123 nosort x sqlite_autoindex_t2249a_1 y sqlite_autoindex_t2249a_1} +ifcapable explain&&subquery { + # These tests are not run if subquery support is not included in the + # build. This is because these tests test the "a = 1 OR a = 2" to + # "a IN (1, 2)" optimisation transformation, which is not enabled if + # subqueries and the IN operator is not available. + # + do_test where2-6.21 { + queryplan { + SELECT x.a,y.a FROM t2249a x CROSS JOIN t2249a y + WHERE x.a=y.a OR y.a='hello' + } + } {0123 0123 nosort x sqlite_autoindex_t2249a_1 y sqlite_autoindex_t2249a_1} + do_test where2-6.22 { + queryplan { + SELECT x.a,y.a FROM t2249a x CROSS JOIN t2249a y + WHERE y.a=x.a OR y.a='hello' + } + } {0123 0123 nosort x sqlite_autoindex_t2249a_1 y sqlite_autoindex_t2249a_1} + do_test where2-6.23 { + queryplan { + SELECT x.a,y.a FROM t2249a x CROSS JOIN t2249a y + WHERE y.a='hello' OR x.a=y.a + } + } {0123 0123 nosort x sqlite_autoindex_t2249a_1 y sqlite_autoindex_t2249a_1} +} + +# Unique queries (queries that are guaranteed to return only a single +# row of result) do not call the sorter. But all tables must give +# a unique result. If any one table in the join does not give a unique +# result then sorting is necessary. +# +do_test where2-7.1 { + cksort { + create table t8(a unique, b, c); + insert into t8 values(1,2,3); + insert into t8 values(2,3,4); + create table t9(x,y); + insert into t9 values(2,4); + insert into t9 values(2,3); + select y from t8, t9 where a=1 order by a, y; + } +} {3 4 sort} +do_test where2-7.2 { + cksort { + select * from t8 where a=1 order by b, c + } +} {1 2 3 nosort} +do_test where2-7.3 { + cksort { + select * from t8, t9 where a=1 and y=3 order by b, x + } +} {1 2 3 2 3 sort} +do_test where2-7.4 { + cksort { + create unique index i9y on t9(y); + select * from t8, t9 where a=1 and y=3 order by b, x + } +} {1 2 3 2 3 nosort} + +} ;# if {[permutation] != "no_optimization"} + +# Ticket #1807. Using IN constrains on multiple columns of +# a multi-column index. +# +ifcapable subquery { + do_test where2-8.1 { + execsql { + SELECT * FROM t1 WHERE x IN (20,21) AND y IN (1,2) + } + } {} + do_test where2-8.2 { + execsql { + SELECT * FROM t1 WHERE x IN (1,2) AND y IN (-5,-6) + } + } {} + execsql {CREATE TABLE tx AS SELECT * FROM t1} + do_test where2-8.3 { + execsql { + SELECT w FROM t1 + WHERE x IN (SELECT x FROM tx WHERE rowid<0) + AND +y IN (SELECT y FROM tx WHERE rowid=1) + } + } {} + do_test where2-8.4 { + execsql { + SELECT w FROM t1 + WHERE x IN (SELECT x FROM tx WHERE rowid=1) + AND y IN (SELECT y FROM tx WHERE rowid<0) + } + } {} + #set sqlite_where_trace 1 + do_test where2-8.5 { + execsql { + CREATE INDEX tx_xyz ON tx(x, y, z, w); + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 12 AND 14) + } + } {12 13 14} + do_test where2-8.6 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 12 AND 14) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20) + } + } {12 13 14} + do_test where2-8.7 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 12 AND 14) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20) + } + } {10 11 12 13 14 15} + do_test where2-8.8 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20) + } + } {10 11 12 13 14 15 16 17 18 19 20} + do_test where2-8.9 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 2 AND 4) + } + } {} + do_test where2-8.10 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 2 AND 4) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20) + } + } {} + do_test where2-8.11 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 2 AND 4) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20) + } + } {} + do_test where2-8.12 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN -4 AND -2) + } + } {} + do_test where2-8.13 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN -4 AND -2) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20) + } + } {} + do_test where2-8.14 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN -4 AND -2) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20) + } + } {} + do_test where2-8.15 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 200 AND 300) + } + } {} + do_test where2-8.16 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 200 AND 300) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20) + } + } {} + do_test where2-8.17 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE w BETWEEN 200 AND 300) + AND y IN (SELECT y FROM t1 WHERE w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE w BETWEEN 10 AND 20) + } + } {} + do_test where2-8.18 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE +w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE +w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE +w BETWEEN 200 AND 300) + } + } {} + do_test where2-8.19 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE +w BETWEEN 10 AND 20) + AND y IN (SELECT y FROM t1 WHERE +w BETWEEN 200 AND 300) + AND z IN (SELECT z FROM t1 WHERE +w BETWEEN 10 AND 20) + } + } {} + do_test where2-8.20 { + execsql { + SELECT w FROM tx + WHERE x IN (SELECT x FROM t1 WHERE +w BETWEEN 200 AND 300) + AND y IN (SELECT y FROM t1 WHERE +w BETWEEN 10 AND 20) + AND z IN (SELECT z FROM t1 WHERE +w BETWEEN 10 AND 20) + } + } {} +} + +# Make sure WHERE clauses of the form A=1 AND (B=2 OR B=3) are optimized +# when we have an index on A and B. +# +ifcapable or_opt&&tclvar { + do_test where2-9.1 { + execsql { + BEGIN; + CREATE TABLE t10(a,b,c); + INSERT INTO t10 VALUES(1,1,1); + INSERT INTO t10 VALUES(1,2,2); + INSERT INTO t10 VALUES(1,3,3); + } + for {set i 4} {$i<=1000} {incr i} { + execsql {INSERT INTO t10 VALUES(1,$i,$i)} + } + execsql { + CREATE INDEX i10 ON t10(a,b); + COMMIT; + SELECT count(*) FROM t10; + } + } 1000 + ifcapable subquery { + do_test where2-9.2 { + count { + SELECT * FROM t10 WHERE a=1 AND (b=2 OR b=3) + } + } {1 2 2 1 3 3 7} + } +} + +# Indices with redundant columns +# +do_test where2-11.1 { + execsql { + CREATE TABLE t11(a,b,c,d); + CREATE INDEX i11aba ON t11(a,b,a,c); -- column A occurs twice. + INSERT INTO t11 VALUES(1,2,3,4); + INSERT INTO t11 VALUES(5,6,7,8); + INSERT INTO t11 VALUES(1,2,9,10); + INSERT INTO t11 VALUES(5,11,12,13); + SELECT c FROM t11 WHERE a=1 AND b=2 ORDER BY c; + } +} {3 9} +do_test where2-11.2 { + execsql { + CREATE INDEX i11cccccccc ON t11(c,c,c,c,c,c,c,c); -- repeated column + SELECT d FROM t11 WHERE c=9; + } +} {10} +do_test where2-11.3 { + execsql { + SELECT d FROM t11 WHERE c IN (1,2,3,4,5); + } +} {4} +do_test where2-11.4 { + execsql { + SELECT d FROM t11 WHERE c=7 OR (a=1 AND b=2) ORDER BY d; + } +} {4 8 10} + +# Verify that the OR clause is used in an outer loop even when +# the OR clause scores slightly better on an inner loop. +if {[permutation] != "no_optimization"} { +do_execsql_test where2-12.1 { + CREATE TABLE t12(x INTEGER PRIMARY KEY, y INT, z CHAR(100)); + CREATE INDEX t12y ON t12(y); + EXPLAIN QUERY PLAN + SELECT a.x, b.x + FROM t12 AS a JOIN t12 AS b ON a.y=b.x + WHERE (b.x=$abc OR b.y=$abc); +} {/.*SEARCH TABLE t12 AS b .*SEARCH TABLE t12 AS b .*/} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where3.test b/components/external/SQLite-3.8.1/test/where3.test new file mode 100644 index 0000000000000000000000000000000000000000..8fa9fa7840b01ec01c11f9024fc431eeb192019a --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where3.test @@ -0,0 +1,489 @@ +# 2006 January 31 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the join reordering optimization +# in cases that include a LEFT JOIN. +# +# $Id: where3.test,v 1.4 2008/04/17 19:14:02 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# The following is from ticket #1652. +# +# A comma join then a left outer join: A,B left join C. +# Arrange indices so that the B table is chosen to go first. +# Also put an index on C, but make sure that A is chosen before C. +# +do_test where3-1.1 { + execsql { + CREATE TABLE t1(a, b); + CREATE TABLE t2(p, q); + CREATE TABLE t3(x, y); + + INSERT INTO t1 VALUES(111,'one'); + INSERT INTO t1 VALUES(222,'two'); + INSERT INTO t1 VALUES(333,'three'); + + INSERT INTO t2 VALUES(1,111); + INSERT INTO t2 VALUES(2,222); + INSERT INTO t2 VALUES(4,444); + CREATE INDEX t2i1 ON t2(p); + + INSERT INTO t3 VALUES(999,'nine'); + CREATE INDEX t3i1 ON t3(x); + + SELECT * FROM t1, t2 LEFT JOIN t3 ON q=x WHERE p=2 AND a=q; + } +} {222 two 2 222 {} {}} + +ifcapable explain { + do_test where3-1.1.1 { + explain_no_trace {SELECT * FROM t1, t2 LEFT JOIN t3 ON q=x + WHERE p=2 AND a=q} + } [explain_no_trace {SELECT * FROM t1, t2 LEFT JOIN t3 ON x=q + WHERE p=2 AND a=q}] +} + +# Ticket #1830 +# +# This is similar to the above but with the LEFT JOIN on the +# other side. +# +do_test where3-1.2 { + execsql { + CREATE TABLE parent1(parent1key, child1key, Child2key, child3key); + CREATE TABLE child1 ( child1key NVARCHAR, value NVARCHAR ); + CREATE UNIQUE INDEX PKIDXChild1 ON child1 ( child1key ); + CREATE TABLE child2 ( child2key NVARCHAR, value NVARCHAR ); + + INSERT INTO parent1(parent1key,child1key,child2key) + VALUES ( 1, 'C1.1', 'C2.1' ); + INSERT INTO child1 ( child1key, value ) VALUES ( 'C1.1', 'Value for C1.1' ); + INSERT INTO child2 ( child2key, value ) VALUES ( 'C2.1', 'Value for C2.1' ); + + INSERT INTO parent1 ( parent1key, child1key, child2key ) + VALUES ( 2, 'C1.2', 'C2.2' ); + INSERT INTO child2 ( child2key, value ) VALUES ( 'C2.2', 'Value for C2.2' ); + + INSERT INTO parent1 ( parent1key, child1key, child2key ) + VALUES ( 3, 'C1.3', 'C2.3' ); + INSERT INTO child1 ( child1key, value ) VALUES ( 'C1.3', 'Value for C1.3' ); + INSERT INTO child2 ( child2key, value ) VALUES ( 'C2.3', 'Value for C2.3' ); + + SELECT parent1.parent1key, child1.value, child2.value + FROM parent1 + LEFT OUTER JOIN child1 ON child1.child1key = parent1.child1key + INNER JOIN child2 ON child2.child2key = parent1.child2key; + } +} {1 {Value for C1.1} {Value for C2.1} 2 {} {Value for C2.2} 3 {Value for C1.3} {Value for C2.3}} + +ifcapable explain { + do_test where3-1.2.1 { + explain_no_trace { + SELECT parent1.parent1key, child1.value, child2.value + FROM parent1 + LEFT OUTER JOIN child1 ON child1.child1key = parent1.child1key + INNER JOIN child2 ON child2.child2key = parent1.child2key; + } + } [explain_no_trace { + SELECT parent1.parent1key, child1.value, child2.value + FROM parent1 + LEFT OUTER JOIN child1 ON parent1.child1key = child1.child1key + INNER JOIN child2 ON child2.child2key = parent1.child2key; + }] +} + +# This procedure executes the SQL. Then it appends +# the names of the table and index used +# +proc queryplan {sql} { + set ::sqlite_sort_count 0 + set data [execsql $sql] + set eqp [execsql "EXPLAIN QUERY PLAN $sql"] + # puts eqp=$eqp + foreach {a b c x} $eqp { + if {[regexp { TABLE (\w+ AS )?(\w+) USING.* INDEX (\w+)\y} \ + $x all as tab idx]} { + lappend data $tab $idx + } elseif {[regexp { TABLE (\w+ AS )?(\w+)\y} $x all as tab]} { + lappend data $tab * + } + } + return $data +} + + +# If you have a from clause of the form: A B C left join D +# then make sure the query optimizer is able to reorder the +# A B C part anyway it wants. +# +# Following the fix to ticket #1652, there was a time when +# the C table would not reorder. So the following reorderings +# were possible: +# +# A B C left join D +# B A C left join D +# +# But these reorders were not allowed +# +# C A B left join D +# A C B left join D +# C B A left join D +# B C A left join D +# +# The following tests are here to verify that the latter four +# reorderings are allowed again. +# +do_test where3-2.1 { + execsql { + CREATE TABLE tA(apk integer primary key, ax); + CREATE TABLE tB(bpk integer primary key, bx); + CREATE TABLE tC(cpk integer primary key, cx); + CREATE TABLE tD(dpk integer primary key, dx); + } + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx + WHERE cpk=bx AND bpk=ax + } +} {tA * tB * tC * tD *} +do_test where3-2.1.1 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON cx=dpk + WHERE cpk=bx AND bpk=ax + } +} {tA * tB * tC * tD *} +do_test where3-2.1.2 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON cx=dpk + WHERE bx=cpk AND bpk=ax + } +} {tA * tB * tC * tD *} +do_test where3-2.1.3 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON cx=dpk + WHERE bx=cpk AND ax=bpk + } +} {tA * tB * tC * tD *} +do_test where3-2.1.4 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx + WHERE bx=cpk AND ax=bpk + } +} {tA * tB * tC * tD *} +do_test where3-2.1.5 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx + WHERE cpk=bx AND ax=bpk + } +} {tA * tB * tC * tD *} +do_test where3-2.2 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx + WHERE cpk=bx AND apk=bx + } +} {tB * tA * tC * tD *} +do_test where3-2.3 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx + WHERE cpk=bx AND apk=bx + } +} {tB * tA * tC * tD *} +do_test where3-2.4 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx + WHERE apk=cx AND bpk=ax + } +} {tC * tA * tB * tD *} +do_test where3-2.5 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx + WHERE cpk=ax AND bpk=cx + } +} {tA * tC * tB * tD *} +do_test where3-2.6 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx + WHERE bpk=cx AND apk=bx + } +} {tC * tB * tA * tD *} +do_test where3-2.7 { + queryplan { + SELECT * FROM tA, tB, tC LEFT JOIN tD ON dpk=cx + WHERE cpk=bx AND apk=cx + } +} {tB * tC * tA * tD *} + +# Ticket [13f033c865f878953] +# If the outer loop must be a full table scan, do not let ANALYZE trick +# the planner into use a table for the outer loop that might be indexable +# if held until an inner loop. +# +do_execsql_test where3-3.0 { + CREATE TABLE t301(a INTEGER PRIMARY KEY,b,c); + CREATE INDEX t301c ON t301(c); + INSERT INTO t301 VALUES(1,2,3); + CREATE TABLE t302(x, y); + INSERT INTO t302 VALUES(4,5); + ANALYZE; + explain query plan SELECT * FROM t302, t301 WHERE t302.x=5 AND t301.a=t302.y; +} { + 0 0 0 {SCAN TABLE t302} + 0 1 1 {SEARCH TABLE t301 USING INTEGER PRIMARY KEY (rowid=?)} +} +do_execsql_test where3-3.1 { + explain query plan + SELECT * FROM t301, t302 WHERE t302.x=5 AND t301.a=t302.y; +} { + 0 0 1 {SCAN TABLE t302} + 0 1 0 {SEARCH TABLE t301 USING INTEGER PRIMARY KEY (rowid=?)} +} +do_execsql_test where3-3.2 { + SELECT * FROM t301 WHERE c=3 AND a IS NULL; +} {} +do_execsql_test where3-3.3 { + SELECT * FROM t301 WHERE c=3 AND a IS NOT NULL; +} {1 2 3} + +if 0 { # Query planner no longer does this +# Verify that when there are multiple tables in a join which must be +# full table scans that the query planner attempts put the table with +# the fewest number of output rows as the outer loop. +# +do_execsql_test where3-4.0 { + CREATE TABLE t400(a INTEGER PRIMARY KEY, b, c); + CREATE TABLE t401(p INTEGER PRIMARY KEY, q, r); + CREATE TABLE t402(x INTEGER PRIMARY KEY, y, z); + EXPLAIN QUERY PLAN + SELECT * FROM t400, t401, t402 WHERE t402.z GLOB 'abc*'; +} { + 0 0 2 {SCAN TABLE t402} + 0 1 0 {SCAN TABLE t400} + 0 2 1 {SCAN TABLE t401} +} +do_execsql_test where3-4.1 { + EXPLAIN QUERY PLAN + SELECT * FROM t400, t401, t402 WHERE t401.r GLOB 'abc*'; +} { + 0 0 1 {SCAN TABLE t401} + 0 1 0 {SCAN TABLE t400} + 0 2 2 {SCAN TABLE t402} +} +do_execsql_test where3-4.2 { + EXPLAIN QUERY PLAN + SELECT * FROM t400, t401, t402 WHERE t400.c GLOB 'abc*'; +} { + 0 0 0 {SCAN TABLE t400} + 0 1 1 {SCAN TABLE t401} + 0 2 2 {SCAN TABLE t402} +} +} ;# endif + +# Verify that a performance regression encountered by firefox +# has been fixed. +# +do_execsql_test where3-5.0 { + CREATE TABLE aaa (id INTEGER PRIMARY KEY, type INTEGER, + fk INTEGER DEFAULT NULL, parent INTEGER, + position INTEGER, title LONGVARCHAR, + keyword_id INTEGER, folder_type TEXT, + dateAdded INTEGER, lastModified INTEGER); + CREATE INDEX aaa_111 ON aaa (fk, type); + CREATE INDEX aaa_222 ON aaa (parent, position); + CREATE INDEX aaa_333 ON aaa (fk, lastModified); + CREATE TABLE bbb (id INTEGER PRIMARY KEY, type INTEGER, + fk INTEGER DEFAULT NULL, parent INTEGER, + position INTEGER, title LONGVARCHAR, + keyword_id INTEGER, folder_type TEXT, + dateAdded INTEGER, lastModified INTEGER); + CREATE INDEX bbb_111 ON bbb (fk, type); + CREATE INDEX bbb_222 ON bbb (parent, position); + CREATE INDEX bbb_333 ON bbb (fk, lastModified); + + EXPLAIN QUERY PLAN + SELECT bbb.title AS tag_title + FROM aaa JOIN bbb ON bbb.id = aaa.parent + WHERE aaa.fk = 'constant' + AND LENGTH(bbb.title) > 0 + AND bbb.parent = 4 + ORDER BY bbb.title COLLATE NOCASE ASC; +} { + 0 0 0 {SEARCH TABLE aaa USING INDEX aaa_333 (fk=?)} + 0 1 1 {SEARCH TABLE bbb USING INTEGER PRIMARY KEY (rowid=?)} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} +do_execsql_test where3-5.1 { + EXPLAIN QUERY PLAN + SELECT bbb.title AS tag_title + FROM aaa JOIN aaa AS bbb ON bbb.id = aaa.parent + WHERE aaa.fk = 'constant' + AND LENGTH(bbb.title) > 0 + AND bbb.parent = 4 + ORDER BY bbb.title COLLATE NOCASE ASC; +} { + 0 0 0 {SEARCH TABLE aaa USING INDEX aaa_333 (fk=?)} + 0 1 1 {SEARCH TABLE aaa AS bbb USING INTEGER PRIMARY KEY (rowid=?)} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} +do_execsql_test where3-5.2 { + EXPLAIN QUERY PLAN + SELECT bbb.title AS tag_title + FROM bbb JOIN aaa ON bbb.id = aaa.parent + WHERE aaa.fk = 'constant' + AND LENGTH(bbb.title) > 0 + AND bbb.parent = 4 + ORDER BY bbb.title COLLATE NOCASE ASC; +} { + 0 0 1 {SEARCH TABLE aaa USING INDEX aaa_333 (fk=?)} + 0 1 0 {SEARCH TABLE bbb USING INTEGER PRIMARY KEY (rowid=?)} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} +do_execsql_test where3-5.3 { + EXPLAIN QUERY PLAN + SELECT bbb.title AS tag_title + FROM aaa AS bbb JOIN aaa ON bbb.id = aaa.parent + WHERE aaa.fk = 'constant' + AND LENGTH(bbb.title) > 0 + AND bbb.parent = 4 + ORDER BY bbb.title COLLATE NOCASE ASC; +} { + 0 0 1 {SEARCH TABLE aaa USING INDEX aaa_333 (fk=?)} + 0 1 0 {SEARCH TABLE aaa AS bbb USING INTEGER PRIMARY KEY (rowid=?)} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} + +# Name resolution with NATURAL JOIN and USING +# +do_test where3-6.setup { + db eval { + CREATE TABLE t6w(a, w); + INSERT INTO t6w VALUES(1, 'w-one'); + INSERT INTO t6w VALUES(2, 'w-two'); + INSERT INTO t6w VALUES(9, 'w-nine'); + CREATE TABLE t6x(a, x); + INSERT INTO t6x VALUES(1, 'x-one'); + INSERT INTO t6x VALUES(3, 'x-three'); + INSERT INTO t6x VALUES(9, 'x-nine'); + CREATE TABLE t6y(a, y); + INSERT INTO t6y VALUES(1, 'y-one'); + INSERT INTO t6y VALUES(4, 'y-four'); + INSERT INTO t6y VALUES(9, 'y-nine'); + CREATE TABLE t6z(a, z); + INSERT INTO t6z VALUES(1, 'z-one'); + INSERT INTO t6z VALUES(5, 'z-five'); + INSERT INTO t6z VALUES(9, 'z-nine'); + } +} {} +set cnt 0 +foreach predicate { + {} + {ORDER BY a} + {ORDER BY t6w.a} + {WHERE a>0} + {WHERE t6y.a>0} + {WHERE a>0 ORDER BY a} +} { + incr cnt + do_test where3-6.$cnt.1 { + set sql "SELECT * FROM t6w NATURAL JOIN t6x NATURAL JOIN t6y" + append sql " NATURAL JOIN t6z " + append sql $::predicate + db eval $sql + } {1 w-one x-one y-one z-one 9 w-nine x-nine y-nine z-nine} + do_test where3-6.$cnt.2 { + set sql "SELECT * FROM t6w JOIN t6x USING(a) JOIN t6y USING(a)" + append sql " JOIN t6z USING(a) " + append sql $::predicate + db eval $sql + } {1 w-one x-one y-one z-one 9 w-nine x-nine y-nine z-nine} + do_test where3-6.$cnt.3 { + set sql "SELECT * FROM t6w NATURAL JOIN t6x JOIN t6y USING(a)" + append sql " JOIN t6z USING(a) " + append sql $::predicate + db eval $sql + } {1 w-one x-one y-one z-one 9 w-nine x-nine y-nine z-nine} + do_test where3-6.$cnt.4 { + set sql "SELECT * FROM t6w JOIN t6x USING(a) NATURAL JOIN t6y" + append sql " JOIN t6z USING(a) " + append sql $::predicate + db eval $sql + } {1 w-one x-one y-one z-one 9 w-nine x-nine y-nine z-nine} + do_test where3-6.$cnt.5 { + set sql "SELECT * FROM t6w JOIN t6x USING(a) JOIN t6y USING(a)" + append sql " NATURAL JOIN t6z " + append sql $::predicate + db eval $sql + } {1 w-one x-one y-one z-one 9 w-nine x-nine y-nine z-nine} + do_test where3-6.$cnt.6 { + set sql "SELECT * FROM t6w JOIN t6x USING(a) NATURAL JOIN t6y" + append sql " NATURAL JOIN t6z " + append sql $::predicate + db eval $sql + } {1 w-one x-one y-one z-one 9 w-nine x-nine y-nine z-nine} + do_test where3-6.$cnt.7 { + set sql "SELECT * FROM t6w NATURAL JOIN t6x JOIN t6y USING(a)" + append sql " NATURAL JOIN t6z " + append sql $::predicate + db eval $sql + } {1 w-one x-one y-one z-one 9 w-nine x-nine y-nine z-nine} + do_test where3-6.$cnt.8 { + set sql "SELECT * FROM t6w NATURAL JOIN t6x NATURAL JOIN t6y" + append sql " JOIN t6z USING(a) " + append sql $::predicate + db eval $sql + } {1 w-one x-one y-one z-one 9 w-nine x-nine y-nine z-nine} +} + +do_execsql_test where3-7-setup { + CREATE TABLE t71(x1 INTEGER PRIMARY KEY, y1); + CREATE TABLE t72(x2 INTEGER PRIMARY KEY, y2); + CREATE TABLE t73(x3, y3); + CREATE TABLE t74(x4, y4); + INSERT INTO t71 VALUES(123,234); + INSERT INTO t72 VALUES(234,345); + INSERT INTO t73 VALUES(123,234); + INSERT INTO t74 VALUES(234,345); + INSERT INTO t74 VALUES(234,678); +} {} +foreach disabled_opt {none omit-noop-join all} { + optimization_control db all 1 + optimization_control db $disabled_opt 0 + do_execsql_test where3-7.$disabled_opt.1 { + SELECT x1 FROM t71 LEFT JOIN t72 ON x2=y1; + } {123} + do_execsql_test where3-7.$disabled_opt.2 { + SELECT x1 FROM t71 LEFT JOIN t72 ON x2=y1 WHERE y2 IS NULL; + } {} + do_execsql_test where3-7.$disabled_opt.3 { + SELECT x1 FROM t71 LEFT JOIN t72 ON x2=y1 WHERE y2 IS NOT NULL; + } {123} + do_execsql_test where3-7.$disabled_opt.4 { + SELECT x1 FROM t71 LEFT JOIN t72 ON x2=y1 AND y2 IS NULL; + } {123} + do_execsql_test where3-7.$disabled_opt.5 { + SELECT x1 FROM t71 LEFT JOIN t72 ON x2=y1 AND y2 IS NOT NULL; + } {123} + do_execsql_test where3-7.$disabled_opt.6 { + SELECT x3 FROM t73 LEFT JOIN t72 ON x2=y3; + } {123} + do_execsql_test where3-7.$disabled_opt.7 { + SELECT DISTINCT x3 FROM t73 LEFT JOIN t72 ON x2=y3; + } {123} + do_execsql_test where3-7.$disabled_opt.8 { + SELECT x3 FROM t73 LEFT JOIN t74 ON x4=y3; + } {123 123} + do_execsql_test where3-7.$disabled_opt.9 { + SELECT DISTINCT x3 FROM t73 LEFT JOIN t74 ON x4=y3; + } {123} +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where4.test b/components/external/SQLite-3.8.1/test/where4.test new file mode 100644 index 0000000000000000000000000000000000000000..280eb5ff7fb4703fbe5f36c7cfba3e7731ac8c72 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where4.test @@ -0,0 +1,273 @@ +# 2006 October 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the use of indices in WHERE clauses. +# This file was created when support for optimizing IS NULL phrases +# was added. And so the principle purpose of this file is to test +# that IS NULL phrases are correctly optimized. But you can never +# have too many tests, so some other tests are thrown in as well. +# +# $Id: where4.test,v 1.6 2007/12/10 05:03:48 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !tclvar||!bloblit { + finish_test + return +} + +# Build some test data +# +do_test where4-1.0 { + execsql { + CREATE TABLE t1(w, x, y); + CREATE INDEX i1wxy ON t1(w,x,y); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 VALUES(1,NULL,3); + INSERT INTO t1 VALUES('a','b','c'); + INSERT INTO t1 VALUES('a',NULL,'c'); + INSERT INTO t1 VALUES(X'78',x'79',x'7a'); + INSERT INTO t1 VALUES(X'78',NULL,X'7A'); + INSERT INTO t1 VALUES(NULL,NULL,NULL); + SELECT count(*) FROM t1; + } +} {7} + +# Do an SQL statement. Append the search count to the end of the result. +# +proc count sql { + set ::sqlite_search_count 0 + return [concat [execsql $sql] $::sqlite_search_count] +} + +# Verify that queries use an index. We are using the special variable +# "sqlite_search_count" which tallys the number of executions of MoveTo +# and Next operators in the VDBE. By verifing that the search count is +# small we can be assured that indices are being used properly. +# +do_test where4-1.1 { + count {SELECT rowid FROM t1 WHERE w IS NULL} +} {7 2} +do_test where4-1.2 { + count {SELECT rowid FROM t1 WHERE +w IS NULL} +} {7 6} +do_test where4-1.3 { + count {SELECT rowid FROM t1 WHERE w=1 AND x IS NULL} +} {2 2} +do_test where4-1.4 { + count {SELECT rowid FROM t1 WHERE w=1 AND +x IS NULL} +} {2 3} +do_test where4-1.5 { + count {SELECT rowid FROM t1 WHERE w=1 AND x>0} +} {1 2} +do_test where4-1.6 { + count {SELECT rowid FROM t1 WHERE w=1 AND x<9} +} {1 3} +do_test where4-1.7 { + count {SELECT rowid FROM t1 WHERE w=1 AND x IS NULL AND y=3} +} {2 2} +do_test where4-1.8 { + count {SELECT rowid FROM t1 WHERE w=1 AND x IS NULL AND y>2} +} {2 2} +do_test where4-1.9 { + count {SELECT rowid FROM t1 WHERE w='a' AND x IS NULL AND y='c'} +} {4 2} +do_test where4-1.10 { + count {SELECT rowid FROM t1 WHERE w=x'78' AND x IS NULL} +} {6 2} +do_test where4-1.11 { + count {SELECT rowid FROM t1 WHERE w=x'78' AND x IS NULL AND y=123} +} {1} +do_test where4-1.12 { + count {SELECT rowid FROM t1 WHERE w=x'78' AND x IS NULL AND y=x'7A'} +} {6 2} +do_test where4-1.13 { + count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL} +} {7 2} +do_test where4-1.14 { + count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL AND y IS NULL} +} {7 2} +do_test where4-1.15 { + count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL AND y<0} +} {2} +do_test where4-1.16 { + count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL AND y>=0} +} {1} + +do_test where4-2.1 { + execsql {SELECT rowid FROM t1 ORDER BY w, x, y} +} {7 2 1 4 3 6 5} +do_test where4-2.2 { + execsql {SELECT rowid FROM t1 ORDER BY w DESC, x, y} +} {6 5 4 3 2 1 7} +do_test where4-2.3 { + execsql {SELECT rowid FROM t1 ORDER BY w, x DESC, y} +} {7 1 2 3 4 5 6} + + +# Ticket #2177 +# +# Suppose you have a left join where the right table of the left +# join (the one that can be NULL) has an index on two columns. +# The first indexed column is used in the ON clause of the join. +# The second indexed column is used in the WHERE clause with an IS NULL +# constraint. It is not allowed to use the IS NULL optimization to +# optimize the query because the second column might be NULL because +# the right table did not match - something the index does not know +# about. +# +do_test where4-3.1 { + execsql { + CREATE TABLE t2(a); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(2); + INSERT INTO t2 VALUES(3); + CREATE TABLE t3(x,y,UNIQUE(x,y)); + INSERT INTO t3 VALUES(1,11); + INSERT INTO t3 VALUES(2,NULL); + + SELECT * FROM t2 LEFT JOIN t3 ON a=x WHERE +y IS NULL; + } +} {2 2 {} 3 {} {}} +do_test where4-3.2 { + execsql { + SELECT * FROM t2 LEFT JOIN t3 ON a=x WHERE y IS NULL; + } +} {2 2 {} 3 {} {}} + +# Ticket #2189. Probably the same bug as #2177. +# +do_test where4-4.1 { + execsql { + CREATE TABLE test(col1 TEXT PRIMARY KEY); + INSERT INTO test(col1) values('a'); + INSERT INTO test(col1) values('b'); + INSERT INTO test(col1) values('c'); + CREATE TABLE test2(col1 TEXT PRIMARY KEY); + INSERT INTO test2(col1) values('a'); + INSERT INTO test2(col1) values('b'); + INSERT INTO test2(col1) values('c'); + SELECT * FROM test t1 LEFT OUTER JOIN test2 t2 ON t1.col1 = t2.col1 + WHERE +t2.col1 IS NULL; + } +} {} +do_test where4-4.2 { + execsql { + SELECT * FROM test t1 LEFT OUTER JOIN test2 t2 ON t1.col1 = t2.col1 + WHERE t2.col1 IS NULL; + } +} {} +do_test where4-4.3 { + execsql { + SELECT * FROM test t1 LEFT OUTER JOIN test2 t2 ON t1.col1 = t2.col1 + WHERE +t1.col1 IS NULL; + } +} {} +do_test where4-4.4 { + execsql { + SELECT * FROM test t1 LEFT OUTER JOIN test2 t2 ON t1.col1 = t2.col1 + WHERE t1.col1 IS NULL; + } +} {} + +# Ticket #2273. Problems with IN operators and NULLs. +# +ifcapable subquery { +do_test where4-5.1 { + execsql { + CREATE TABLE t4(x,y,z,PRIMARY KEY(x,y)); + } + execsql { + SELECT * + FROM t2 LEFT JOIN t4 b1 + LEFT JOIN t4 b2 ON b2.x=b1.x AND b2.y IN (b1.y); + } +} {1 {} {} {} {} {} {} 2 {} {} {} {} {} {} 3 {} {} {} {} {} {}} +do_test where4-5.2 { + execsql { + INSERT INTO t4 VALUES(1,1,11); + INSERT INTO t4 VALUES(1,2,12); + INSERT INTO t4 VALUES(1,3,13); + INSERT INTO t4 VALUES(2,2,22); + SELECT rowid FROM t4 WHERE x IN (1,9,2,5) AND y IN (1,3,NULL,2) AND z!=13; + } +} {1 2 4} +do_test where4-5.3 { + execsql { + SELECT rowid FROM t4 WHERE x IN (1,9,NULL,2) AND y IN (1,3,2) AND z!=13; + } +} {1 2 4} +do_test where4-6.1 { + execsql { + CREATE TABLE t5(a,b,c,d,e,f,UNIQUE(a,b,c,d,e,f)); + INSERT INTO t5 VALUES(1,1,1,1,1,11111); + INSERT INTO t5 VALUES(2,2,2,2,2,22222); + INSERT INTO t5 VALUES(1,2,3,4,5,12345); + INSERT INTO t5 VALUES(2,3,4,5,6,23456); + } + execsql { + SELECT rowid FROM t5 + WHERE a IN (1,9,2) AND b=2 AND c IN (1,2,3,4) AND d>0 + } +} {3 2} +do_test where4-6.2 { + execsql { + SELECT rowid FROM t5 + WHERE a IN (1,NULL,2) AND b=2 AND c IN (1,2,3,4) AND d>0 + } +} {3 2} +do_test where4-7.1 { + execsql { + CREATE TABLE t6(y,z,PRIMARY KEY(y,z)); + } + execsql { + SELECT * FROM t6 WHERE y=NULL AND z IN ('hello'); + } +} {} + +integrity_check {where4-99.0} + +do_test where4-7.1 { + execsql { + BEGIN; + CREATE TABLE t8(a, b, c, d); + CREATE INDEX t8_i ON t8(a, b, c); + CREATE TABLE t7(i); + + INSERT INTO t7 VALUES(1); + INSERT INTO t7 SELECT i*2 FROM t7; + INSERT INTO t7 SELECT i*2 FROM t7; + INSERT INTO t7 SELECT i*2 FROM t7; + INSERT INTO t7 SELECT i*2 FROM t7; + INSERT INTO t7 SELECT i*2 FROM t7; + INSERT INTO t7 SELECT i*2 FROM t7; + + COMMIT; + } +} {} + +# At one point the sub-select inside the aggregate sum() function in the +# following query was leaking a couple of stack entries. This query +# runs the SELECT in a loop enough times that an assert() fails. Or rather, +# did fail before the bug was fixed. +# +do_test where4-7.2 { + execsql { + SELECT sum(( + SELECT d FROM t8 WHERE a = i AND b = i AND c < NULL + )) FROM t7; + } +} {{}} + +}; #ifcapable subquery + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where5.test b/components/external/SQLite-3.8.1/test/where5.test new file mode 100644 index 0000000000000000000000000000000000000000..760224cc1351a0a6c754130a961913990d0c24d8 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where5.test @@ -0,0 +1,288 @@ +# 2007 June 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing NULL comparisons in the WHERE clause. +# See ticket #2404. +# +# $Id: where5.test,v 1.2 2007/06/08 08:43:10 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build some test data +# +do_test where5-1.0 { + execsql { + CREATE TABLE t1(x TEXT); + CREATE TABLE t2(x INTEGER); + CREATE TABLE t3(x INTEGER PRIMARY KEY); + INSERT INTO t1 VALUES(-1); + INSERT INTO t1 VALUES(0); + INSERT INTO t1 VALUES(1); + INSERT INTO t2 SELECT * FROM t1; + INSERT INTO t3 SELECT * FROM t2; + } + execsql { + SELECT * FROM t1 WHERE x<0 + } +} {-1} +do_test where5-1.1 { + execsql { + SELECT * FROM t1 WHERE x<=0 + } +} {-1 0} +do_test where5-1.2 { + execsql { + SELECT * FROM t1 WHERE x=0 + } +} {0} +do_test where5-1.3 { + execsql { + SELECT * FROM t1 WHERE x>=0 + } +} {0 1} +do_test where5-1.4 { + execsql { + SELECT * FROM t1 WHERE x>0 + } +} {1} +do_test where5-1.5 { + execsql { + SELECT * FROM t1 WHERE x<>0 + } +} {-1 1} +do_test where5-1.6 { + execsql { + SELECT * FROM t1 WHERE x=NULL + } +} {} +do_test where5-1.10 { + execsql { + SELECT * FROM t1 WHERE x>NULL + } +} {} +do_test where5-1.11 { + execsql { + SELECT * FROM t1 WHERE x!=NULL + } +} {} +do_test where5-1.12 { + execsql { + SELECT * FROM t1 WHERE x IS NULL + } +} {} +do_test where5-1.13 { + execsql { + SELECT * FROM t1 WHERE x IS NOT NULL + } +} {-1 0 1} + + +do_test where5-2.0 { + execsql { + SELECT * FROM t2 WHERE x<0 + } +} {-1} +do_test where5-2.1 { + execsql { + SELECT * FROM t2 WHERE x<=0 + } +} {-1 0} +do_test where5-2.2 { + execsql { + SELECT * FROM t2 WHERE x=0 + } +} {0} +do_test where5-2.3 { + execsql { + SELECT * FROM t2 WHERE x>=0 + } +} {0 1} +do_test where5-2.4 { + execsql { + SELECT * FROM t2 WHERE x>0 + } +} {1} +do_test where5-2.5 { + execsql { + SELECT * FROM t2 WHERE x<>0 + } +} {-1 1} +do_test where5-2.6 { + execsql { + SELECT * FROM t2 WHERE x=NULL + } +} {} +do_test where5-2.10 { + execsql { + SELECT * FROM t2 WHERE x>NULL + } +} {} +do_test where5-2.11 { + execsql { + SELECT * FROM t2 WHERE x!=NULL + } +} {} +do_test where5-2.12 { + execsql { + SELECT * FROM t2 WHERE x IS NULL + } +} {} +do_test where5-2.13 { + execsql { + SELECT * FROM t2 WHERE x IS NOT NULL + } +} {-1 0 1} + + +do_test where5-3.0 { + execsql { + SELECT * FROM t3 WHERE x<0 + } +} {-1} +do_test where5-3.1 { + execsql { + SELECT * FROM t3 WHERE x<=0 + } +} {-1 0} +do_test where5-3.2 { + execsql { + SELECT * FROM t3 WHERE x=0 + } +} {0} +do_test where5-3.3 { + execsql { + SELECT * FROM t3 WHERE x>=0 + } +} {0 1} +do_test where5-3.4 { + execsql { + SELECT * FROM t3 WHERE x>0 + } +} {1} +do_test where5-3.5 { + execsql { + SELECT * FROM t3 WHERE x<>0 + } +} {-1 1} +do_test where5-3.6 { + execsql { + SELECT * FROM t3 WHERE x=NULL + } +} {} +do_test where5-3.10 { + execsql { + SELECT * FROM t3 WHERE x>NULL + } +} {} +do_test where5-3.11 { + execsql { + SELECT * FROM t3 WHERE x!=NULL + } +} {} +do_test where5-3.12 { + execsql { + SELECT * FROM t3 WHERE x IS NULL + } +} {} +do_test where5-3.13 { + execsql { + SELECT * FROM t3 WHERE x IS NOT NULL + } +} {-1 0 1} + +do_test where5-4.0 { + execsql { + SELECT xNULL FROM t3 + } +} {{} {} {}} +do_test where5-4.4 { + execsql { + SELECT x>=NULL FROM t3 + } +} {{} {} {}} +do_test where5-4.5 { + execsql { + SELECT x!=NULL FROM t3 + } +} {{} {} {}} +do_test where5-4.6 { + execsql { + SELECT x IS NULL FROM t3 + } +} {0 0 0} +do_test where5-4.7 { + execsql { + SELECT x IS NOT NULL FROM t3 + } +} {1 1 1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where6.test b/components/external/SQLite-3.8.1/test/where6.test new file mode 100644 index 0000000000000000000000000000000000000000..83e975b7dd6d1be9879166ff3fafb0d217b91e31 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where6.test @@ -0,0 +1,154 @@ +# 2007 June 8 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that terms in the ON clause of +# a LEFT OUTER JOIN are not used with indices. See ticket #3015. +# +# $Id: where6.test,v 1.2 2008/04/17 19:14:02 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Build some test data +# +do_test where6-1.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY,b,c); + INSERT INTO t1 VALUES(1,3,1); + INSERT INTO t1 VALUES(2,4,2); + CREATE TABLE t2(x INTEGER PRIMARY KEY); + INSERT INTO t2 VALUES(3); + + SELECT * FROM t1 LEFT JOIN t2 ON b=x AND c=1; + } +} {1 3 1 3 2 4 2 {}} +do_test where6-1.2 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON x=b AND c=1; + } +} {1 3 1 3 2 4 2 {}} +do_test where6-1.3 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON x=b AND 1=c; + } +} {1 3 1 3 2 4 2 {}} +do_test where6-1.4 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b=x AND 1=c; + } +} {1 3 1 3 2 4 2 {}} + +ifcapable explain { + do_test where6-1.5 { + explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON x=b AND 1=c} + } [explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON b=x AND c=1}] + do_test where6-1.6 { + explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE 1=c} + } [explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE c=1}] +} + +do_test where6-1.11 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE c=1; + } +} {1 3 1 3} +do_test where6-1.12 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE c=1; + } +} {1 3 1 3} +do_test where6-1.13 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE 1=c; + } +} {1 3 1 3} + + + +do_test where6-2.1 { + execsql { + CREATE INDEX i1 ON t1(c); + + SELECT * FROM t1 LEFT JOIN t2 ON b=x AND c=1; + } +} {1 3 1 3 2 4 2 {}} +do_test where6-2.2 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON x=b AND c=1; + } +} {1 3 1 3 2 4 2 {}} +do_test where6-2.3 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON x=b AND 1=c; + } +} {1 3 1 3 2 4 2 {}} +do_test where6-2.4 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b=x AND 1=c; + } +} {1 3 1 3 2 4 2 {}} + +ifcapable explain { + do_test where6-2.5 { + explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON x=b AND 1=c} + } [explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON b=x AND c=1}] + do_test where6-2.6 { + explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE 1=c} + } [explain_no_trace {SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE c=1}] +} + + +do_test where6-2.11 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE c=1; + } +} {1 3 1 3} +do_test where6-2.12 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE c=1; + } +} {1 3 1 3} +do_test where6-2.13 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON x=b WHERE 1=c; + } +} {1 3 1 3} +do_test where6-2.14 { + execsql { + SELECT * FROM t1 LEFT JOIN t2 ON b=x WHERE 1=c; + } +} {1 3 1 3} + +# Ticket [ebdbadade5b]: +# If the ON close on a LEFT JOIN is of the form x=y where both x and y +# are indexed columns on tables to left of the join, then do not use that +# term with indices to either table. +# +do_test where6-3.1 { + db eval { + CREATE TABLE t4(x UNIQUE); + INSERT INTO t4 VALUES('abc'); + INSERT INTO t4 VALUES('def'); + INSERT INTO t4 VALUES('ghi'); + CREATE TABLE t5(a, b, c, PRIMARY KEY(a,b)); + INSERT INTO t5 VALUES('abc','def',123); + INSERT INTO t5 VALUES('def','ghi',456); + + SELECT t4a.x, t4b.x, t5.c, t6.v + FROM t4 AS t4a + INNER JOIN t4 AS t4b + LEFT JOIN t5 ON t5.a=t4a.x AND t5.b=t4b.x + LEFT JOIN (SELECT 1 AS v) AS t6 ON t4a.x=t4b.x + ORDER BY 1, 2, 3; + } +} {abc abc {} 1 abc def 123 {} abc ghi {} {} def abc {} {} def def {} 1 def ghi 456 {} ghi abc {} {} ghi def {} {} ghi ghi {} 1} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where7.test b/components/external/SQLite-3.8.1/test/where7.test new file mode 100644 index 0000000000000000000000000000000000000000..5032c698b217f691e018cad152fc032a7aee0fc2 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where7.test @@ -0,0 +1,23348 @@ +# 2008 December 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the multi-index OR clause optimizer. + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !or_opt { + finish_test + return +} + +# Evaluate SQL. Return the result set followed by the +# and the number of full-scan steps. +# +proc count_steps {sql} { + set r [db eval $sql] + lappend r scan [db status step] sort [db status sort] +} + +proc count_steps_sort {sql} { + set r [lsort -integer [db eval $sql]] + return "$r scan [db status step] sort [db status sort]" +} + +# Build some test data +# +do_test where7-1.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY,b,c,d); + INSERT INTO t1 VALUES(1,2,3,4); + INSERT INTO t1 VALUES(2,3,4,5); + INSERT INTO t1 VALUES(3,4,6,8); + INSERT INTO t1 VALUES(4,5,10,15); + INSERT INTO t1 VALUES(5,10,100,1000); + CREATE INDEX t1b ON t1(b); + CREATE INDEX t1c ON t1(c); + SELECT * FROM t1; + } +} {1 2 3 4 2 3 4 5 3 4 6 8 4 5 10 15 5 10 100 1000} +do_test where7-1.2 { + count_steps { + SELECT a FROM t1 WHERE b=3 OR c=6 ORDER BY a + } +} {2 3 scan 0 sort 1} +do_test where7-1.3 { + count_steps { + SELECT a FROM t1 WHERE b=3 OR +c=6 ORDER BY a + } +} {2 3 scan 4 sort 0} +do_test where7-1.4 { + count_steps { + SELECT a FROM t1 WHERE +b=3 OR c=6 ORDER BY 1 + } +} {2 3 scan 4 sort 0} +do_test where7-1.5 { + count_steps { + SELECT a FROM t1 WHERE 3=b OR c=6 ORDER BY rowid + } +} {2 3 scan 0 sort 1} +do_test where7-1.6 { + count_steps { + SELECT a FROM t1 WHERE (3=b OR c=6) AND +a>0 ORDER BY a + } +} {2 3 scan 0 sort 1} +do_test where7-1.7 { + count_steps { + SELECT a FROM t1 WHERE (b=3 OR c>10) + } +} {2 5 scan 0 sort 0} +do_test where7-1.8 { + count_steps { + SELECT a FROM t1 WHERE (b=3 OR c>=10) + } +} {2 4 5 scan 0 sort 0} +do_test where7-1.9 { + count_steps { + SELECT a FROM t1 WHERE (b=3 OR c>=10 OR c=4) + } +} {2 4 5 scan 0 sort 0} +do_test where7-1.10 { + count_steps { + SELECT a FROM t1 WHERE (b=3 OR c>=10 OR c=4 OR b>10) + } +} {2 4 5 scan 0 sort 0} +do_test where7-1.11 { + count_steps { + SELECT a FROM t1 WHERE (d=5 AND b=3) OR c==100 ORDER BY a; + } +} {2 5 scan 0 sort 1} +do_test where7-1.12 { + count_steps { + SELECT a FROM t1 WHERE (b BETWEEN 2 AND 4) OR c=100 ORDER BY a + } +} {1 2 3 5 scan 0 sort 1} +do_test where7-1.13 { + count_steps { + SELECT a FROM t1 WHERE (b BETWEEN 0 AND 2) OR (c BETWEEN 9 AND 999) + ORDER BY +a DESC + } +} {5 4 1 scan 0 sort 1} + +do_test where7-1.14 { + count_steps { + SELECT a FROM t1 WHERE (d=8 OR c=6 OR b=4) AND +a>0 + } +} {3 scan 4 sort 0} +do_test where7-1.15 { + count_steps { + SELECT a FROM t1 WHERE +a>=0 AND (d=8 OR c=6 OR b=4) + } +} {3 scan 4 sort 0} + +do_test where7-1.20 { + set sql "SELECT a FROM t1 WHERE a=11 OR b=11" + for {set i 12} {$i<400} {incr i} { + append sql " OR a=$i OR b=$i" + } + append sql " ORDER BY a" + count_steps $sql +} {scan 0 sort 1} +do_test where7-1.21 { + set sql "SELECT a FROM t1 WHERE b=11 OR c=11" + for {set i 12} {$i<400} {incr i} { + append sql " OR b=$i OR c=$i" + } + append sql " ORDER BY a" + count_steps $sql +} {5 scan 0 sort 1} +do_test where7-1.22 { + set sql "SELECT a FROM t1 WHERE (b=11 OR c=11" + for {set i 12} {$i<400} {incr i} { + append sql " OR b=$i OR c=$i" + } + append sql ") AND d>=0 AND d<9999 ORDER BY a" + count_steps $sql +} {5 scan 0 sort 1} +do_test where7-1.23 { + set sql "SELECT a FROM t1 WHERE (b=11 OR c=11" + for {set i 12} {$i<400} {incr i} { + append sql " OR (b=$i AND d!=0) OR (c=$i AND d IS NOT NULL)" + } + append sql ") AND d>=0 AND d<9999 ORDER BY a" + count_steps $sql +} {5 scan 0 sort 1} + +do_test where7-1.31 { + set sql "SELECT a FROM t1 WHERE (a=11 AND b=11)" + for {set i 12} {$i<400} {incr i} { + append sql " OR (a=$i AND b=$i)" + } + append sql " ORDER BY a" + count_steps $sql +} {scan 0 sort 1} +do_test where7-1.32 { + set sql "SELECT a FROM t1 WHERE (b=11 AND c=11)" + for {set i 12} {$i<400} {incr i} { + append sql " OR (b=$i AND c=$i)" + } + append sql " ORDER BY a" + count_steps $sql +} {scan 0 sort 1} + + +do_test where7-2.1 { + db eval { + CREATE TABLE t2(a INTEGER PRIMARY KEY,b,c,d,e,f TEXT,g); + INSERT INTO t2 VALUES(1,11,1001,1.001,100.1,'bcdefghij','yxwvuts'); + INSERT INTO t2 VALUES(2,22,1001,2.002,100.1,'cdefghijk','yxwvuts'); + INSERT INTO t2 VALUES(3,33,1001,3.0029999999999997,100.1,'defghijkl','xwvutsr'); + INSERT INTO t2 VALUES(4,44,2002,4.004,200.2,'efghijklm','xwvutsr'); + INSERT INTO t2 VALUES(5,55,2002,5.004999999999999,200.2,'fghijklmn','xwvutsr'); + INSERT INTO t2 VALUES(6,66,2002,6.005999999999999,200.2,'ghijklmno','xwvutsr'); + INSERT INTO t2 VALUES(7,77,3003,7.007,300.29999999999995,'hijklmnop','xwvutsr'); + INSERT INTO t2 VALUES(8,88,3003,8.008,300.29999999999995,'ijklmnopq','wvutsrq'); + INSERT INTO t2 VALUES(9,99,3003,9.008999999999999,300.29999999999995,'jklmnopqr','wvutsrq'); + INSERT INTO t2 VALUES(10,110,4004,10.009999999999998,400.4,'klmnopqrs','wvutsrq'); + INSERT INTO t2 VALUES(11,121,4004,11.011,400.4,'lmnopqrst','wvutsrq'); + INSERT INTO t2 VALUES(12,132,4004,12.011999999999999,400.4,'mnopqrstu','wvutsrq'); + INSERT INTO t2 VALUES(13,143,5005,13.012999999999998,500.5,'nopqrstuv','vutsrqp'); + INSERT INTO t2 VALUES(14,154,5005,14.014,500.5,'opqrstuvw','vutsrqp'); + INSERT INTO t2 VALUES(15,165,5005,15.014999999999999,500.5,'pqrstuvwx','vutsrqp'); + INSERT INTO t2 VALUES(16,176,6006,16.016,600.5999999999999,'qrstuvwxy','vutsrqp'); + INSERT INTO t2 VALUES(17,187,6006,17.017,600.5999999999999,'rstuvwxyz','vutsrqp'); + INSERT INTO t2 VALUES(18,198,6006,18.017999999999997,600.5999999999999,'stuvwxyza','utsrqpo'); + INSERT INTO t2 VALUES(19,209,7007,19.019,700.6999999999999,'tuvwxyzab','utsrqpo'); + INSERT INTO t2 VALUES(20,220,7007,20.019999999999996,700.6999999999999,'uvwxyzabc','utsrqpo'); + INSERT INTO t2 VALUES(21,231,7007,21.020999999999997,700.6999999999999,'vwxyzabcd','utsrqpo'); + INSERT INTO t2 VALUES(22,242,8008,22.022,800.8,'wxyzabcde','utsrqpo'); + INSERT INTO t2 VALUES(23,253,8008,23.022999999999996,800.8,'xyzabcdef','tsrqpon'); + INSERT INTO t2 VALUES(24,264,8008,24.023999999999997,800.8,'yzabcdefg','tsrqpon'); + INSERT INTO t2 VALUES(25,275,9009,25.025,900.9,'zabcdefgh','tsrqpon'); + INSERT INTO t2 VALUES(26,286,9009,26.025999999999996,900.9,'abcdefghi','tsrqpon'); + INSERT INTO t2 VALUES(27,297,9009,27.026999999999997,900.9,'bcdefghij','tsrqpon'); + INSERT INTO t2 VALUES(28,308,10010,28.028,1001.0,'cdefghijk','srqponm'); + INSERT INTO t2 VALUES(29,319,10010,29.028999999999996,1001.0,'defghijkl','srqponm'); + INSERT INTO t2 VALUES(30,330,10010,30.029999999999998,1001.0,'efghijklm','srqponm'); + INSERT INTO t2 VALUES(31,341,11011,31.030999999999995,1101.1,'fghijklmn','srqponm'); + INSERT INTO t2 VALUES(32,352,11011,32.032,1101.1,'ghijklmno','srqponm'); + INSERT INTO t2 VALUES(33,363,11011,33.032999999999994,1101.1,'hijklmnop','rqponml'); + INSERT INTO t2 VALUES(34,374,12012,34.034,1201.1999999999998,'ijklmnopq','rqponml'); + INSERT INTO t2 VALUES(35,385,12012,35.035,1201.1999999999998,'jklmnopqr','rqponml'); + INSERT INTO t2 VALUES(36,396,12012,36.035999999999994,1201.1999999999998,'klmnopqrs','rqponml'); + INSERT INTO t2 VALUES(37,407,13013,37.037,1301.3,'lmnopqrst','rqponml'); + INSERT INTO t2 VALUES(38,418,13013,38.038,1301.3,'mnopqrstu','qponmlk'); + INSERT INTO t2 VALUES(39,429,13013,39.038999999999994,1301.3,'nopqrstuv','qponmlk'); + INSERT INTO t2 VALUES(40,440,14014,40.03999999999999,1401.3999999999999,'opqrstuvw','qponmlk'); + INSERT INTO t2 VALUES(41,451,14014,41.041,1401.3999999999999,'pqrstuvwx','qponmlk'); + INSERT INTO t2 VALUES(42,462,14014,42.041999999999994,1401.3999999999999,'qrstuvwxy','qponmlk'); + INSERT INTO t2 VALUES(43,473,15015,43.04299999999999,1501.5,'rstuvwxyz','ponmlkj'); + INSERT INTO t2 VALUES(44,484,15015,44.044,1501.5,'stuvwxyza','ponmlkj'); + INSERT INTO t2 VALUES(45,495,15015,45.044999999999995,1501.5,'tuvwxyzab','ponmlkj'); + INSERT INTO t2 VALUES(46,506,16016,46.04599999999999,1601.6,'uvwxyzabc','ponmlkj'); + INSERT INTO t2 VALUES(47,517,16016,47.047,1601.6,'vwxyzabcd','ponmlkj'); + INSERT INTO t2 VALUES(48,528,16016,48.047999999999995,1601.6,'wxyzabcde','onmlkji'); + INSERT INTO t2 VALUES(49,539,17017,49.04899999999999,1701.6999999999998,'xyzabcdef','onmlkji'); + INSERT INTO t2 VALUES(50,550,17017,50.05,1701.6999999999998,'yzabcdefg','onmlkji'); + INSERT INTO t2 VALUES(51,561,17017,51.050999999999995,1701.6999999999998,'zabcdefgh','onmlkji'); + INSERT INTO t2 VALUES(52,572,18018,52.05199999999999,1801.8,'abcdefghi','onmlkji'); + INSERT INTO t2 VALUES(53,583,18018,53.053,1801.8,'bcdefghij','nmlkjih'); + INSERT INTO t2 VALUES(54,594,18018,54.053999999999995,1801.8,'cdefghijk','nmlkjih'); + INSERT INTO t2 VALUES(55,605,19019,55.05499999999999,1901.8999999999999,'defghijkl','nmlkjih'); + INSERT INTO t2 VALUES(56,616,19019,56.056,1901.8999999999999,'efghijklm','nmlkjih'); + INSERT INTO t2 VALUES(57,627,19019,57.056999999999995,1901.8999999999999,'fghijklmn','nmlkjih'); + INSERT INTO t2 VALUES(58,638,20020,58.05799999999999,2002.0,'ghijklmno','mlkjihg'); + INSERT INTO t2 VALUES(59,649,20020,59.05899999999999,2002.0,'hijklmnop','mlkjihg'); + INSERT INTO t2 VALUES(60,660,20020,60.059999999999995,2002.0,'ijklmnopq','mlkjihg'); + INSERT INTO t2 VALUES(61,671,21021,61.06099999999999,2102.1,'jklmnopqr','mlkjihg'); + INSERT INTO t2 VALUES(62,682,21021,62.06199999999999,2102.1,'klmnopqrs','mlkjihg'); + INSERT INTO t2 VALUES(63,693,21021,63.062999999999995,2102.1,'lmnopqrst','lkjihgf'); + INSERT INTO t2 VALUES(64,704,22022,64.064,2202.2,'mnopqrstu','lkjihgf'); + INSERT INTO t2 VALUES(65,715,22022,65.065,2202.2,'nopqrstuv','lkjihgf'); + INSERT INTO t2 VALUES(66,726,22022,66.06599999999999,2202.2,'opqrstuvw','lkjihgf'); + INSERT INTO t2 VALUES(67,737,23023,67.067,2302.2999999999997,'pqrstuvwx','lkjihgf'); + INSERT INTO t2 VALUES(68,748,23023,68.068,2302.2999999999997,'qrstuvwxy','kjihgfe'); + INSERT INTO t2 VALUES(69,759,23023,69.06899999999999,2302.2999999999997,'rstuvwxyz','kjihgfe'); + INSERT INTO t2 VALUES(70,770,24024,70.07,2402.3999999999996,'stuvwxyza','kjihgfe'); + INSERT INTO t2 VALUES(71,781,24024,71.071,2402.3999999999996,'tuvwxyzab','kjihgfe'); + INSERT INTO t2 VALUES(72,792,24024,72.07199999999999,2402.3999999999996,'uvwxyzabc','kjihgfe'); + INSERT INTO t2 VALUES(73,803,25025,73.073,2502.5,'vwxyzabcd','jihgfed'); + INSERT INTO t2 VALUES(74,814,25025,74.074,2502.5,'wxyzabcde','jihgfed'); + INSERT INTO t2 VALUES(75,825,25025,75.07499999999999,2502.5,'xyzabcdef','jihgfed'); + INSERT INTO t2 VALUES(76,836,26026,76.076,2602.6,'yzabcdefg','jihgfed'); + INSERT INTO t2 VALUES(77,847,26026,77.077,2602.6,'zabcdefgh','jihgfed'); + INSERT INTO t2 VALUES(78,858,26026,78.07799999999999,2602.6,'abcdefghi','ihgfedc'); + INSERT INTO t2 VALUES(79,869,27027,79.079,2702.7,'bcdefghij','ihgfedc'); + INSERT INTO t2 VALUES(80,880,27027,80.07999999999998,2702.7,'cdefghijk','ihgfedc'); + INSERT INTO t2 VALUES(81,891,27027,81.08099999999999,2702.7,'defghijkl','ihgfedc'); + INSERT INTO t2 VALUES(82,902,28028,82.082,2802.7999999999997,'efghijklm','ihgfedc'); + INSERT INTO t2 VALUES(83,913,28028,83.08299999999998,2802.7999999999997,'fghijklmn','hgfedcb'); + INSERT INTO t2 VALUES(84,924,28028,84.08399999999999,2802.7999999999997,'ghijklmno','hgfedcb'); + INSERT INTO t2 VALUES(85,935,29029,85.085,2902.8999999999996,'hijklmnop','hgfedcb'); + INSERT INTO t2 VALUES(86,946,29029,86.08599999999998,2902.8999999999996,'ijklmnopq','hgfedcb'); + INSERT INTO t2 VALUES(87,957,29029,87.08699999999999,2902.8999999999996,'jklmnopqr','hgfedcb'); + INSERT INTO t2 VALUES(88,968,30030,88.088,3003.0,'klmnopqrs','gfedcba'); + INSERT INTO t2 VALUES(89,979,30030,89.08899999999998,3003.0,'lmnopqrst','gfedcba'); + INSERT INTO t2 VALUES(90,990,30030,90.08999999999999,3003.0,'mnopqrstu','gfedcba'); + INSERT INTO t2 VALUES(91,1001,31031,91.091,3103.1,'nopqrstuv','gfedcba'); + INSERT INTO t2 VALUES(92,1012,31031,92.09199999999998,3103.1,'opqrstuvw','gfedcba'); + INSERT INTO t2 VALUES(93,1023,31031,93.09299999999999,3103.1,'pqrstuvwx','fedcbaz'); + INSERT INTO t2 VALUES(94,1034,32032,94.094,3203.2,'qrstuvwxy','fedcbaz'); + INSERT INTO t2 VALUES(95,1045,32032,95.09499999999998,3203.2,'rstuvwxyz','fedcbaz'); + INSERT INTO t2 VALUES(96,1056,32032,96.09599999999999,3203.2,'stuvwxyza','fedcbaz'); + INSERT INTO t2 VALUES(97,1067,33033,97.097,3303.2999999999997,'tuvwxyzab','fedcbaz'); + INSERT INTO t2 VALUES(98,1078,33033,98.09799999999998,3303.2999999999997,'uvwxyzabc','edcbazy'); + INSERT INTO t2 VALUES(99,1089,33033,99.09899999999999,3303.2999999999997,'vwxyzabcd','edcbazy'); + INSERT INTO t2 VALUES(100,1100,34034,100.1,3403.3999999999996,'wxyzabcde','edcbazy'); + CREATE INDEX t2b ON t2(b); + CREATE INDEX t2c ON t2(c); + CREATE INDEX t2d ON t2(d); + CREATE INDEX t2e ON t2(e); + CREATE INDEX t2f ON t2(f); + CREATE INDEX t2g ON t2(g); + CREATE TABLE t3(a INTEGER PRIMARY KEY,b,c,d,e,f TEXT,g); + INSERT INTO t3 SELECT * FROM t2; + CREATE INDEX t3b ON t3(b,c); + CREATE INDEX t3c ON t3(c,e); + CREATE INDEX t3d ON t3(d,g); + CREATE INDEX t3e ON t3(e,f,g); + CREATE INDEX t3f ON t3(f,b,d,c); + CREATE INDEX t3g ON t3(g,f); + } +} {} + +do_test where7-2.2.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1070 + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + } +} {6 18 20 32 39 58 84 89 96 100 scan 0 sort 0} +do_test where7-2.2.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1070 + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + } +} {6 18 20 32 39 58 84 89 96 100 scan 0 sort 0} +do_test where7-2.3.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=47.0 AND d<48.0 AND d NOT NULL) + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR b=220 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR (g='qponmlk' AND f GLOB 'pqrst*') + } +} {20 33 35 41 47 67 69 70 98 scan 0 sort 0} +do_test where7-2.3.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=47.0 AND d<48.0 AND d NOT NULL) + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR b=220 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR (g='qponmlk' AND f GLOB 'pqrst*') + } +} {20 33 35 41 47 67 69 70 98 scan 0 sort 0} +do_test where7-2.4.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=190 + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR (g='rqponml' AND f GLOB 'hijkl*') + OR b=407 + } +} {33 37 49 51 scan 0 sort 0} +do_test where7-2.4.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=190 + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR (g='rqponml' AND f GLOB 'hijkl*') + OR b=407 + } +} {33 37 49 51 scan 0 sort 0} +do_test where7-2.5.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=795 + OR b=1103 + OR b=583 + } +} {13 39 53 65 91 scan 0 sort 0} +do_test where7-2.5.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=795 + OR b=1103 + OR b=583 + } +} {13 39 53 65 91 scan 0 sort 0} +do_test where7-2.6.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=74 + OR a=50 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR c=21021 + OR ((a BETWEEN 82 AND 84) AND a!=83) + } +} {16 18 50 61 62 63 74 82 84 85 scan 0 sort 0} +do_test where7-2.6.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=74 + OR a=50 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR c=21021 + OR ((a BETWEEN 82 AND 84) AND a!=83) + } +} {16 18 50 61 62 63 74 82 84 85 scan 0 sort 0} +do_test where7-2.7.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 8 AND 10) AND a!=9) + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR c=14014 + OR b=828 + } +} {8 10 34 36 40 41 42 94 scan 0 sort 0} +do_test where7-2.7.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 8 AND 10) AND a!=9) + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR c=14014 + OR b=828 + } +} {8 10 34 36 40 41 42 94 scan 0 sort 0} +do_test where7-2.8.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE 1000000=72.0 AND d<73.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR c=11011 + OR c=20020 + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + } +} {18 31 32 33 58 59 60 72 74 scan 0 sort 0} +do_test where7-2.11.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=72.0 AND d<73.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR c=11011 + OR c=20020 + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + } +} {18 31 32 33 58 59 60 72 74 scan 0 sort 0} +do_test where7-2.12.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=50.0 AND d<51.0 AND d NOT NULL) + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR b=792 + OR a=97 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR b=916 + OR a=69 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR c=6006 + } +} {16 17 18 31 50 69 72 81 83 87 97 scan 0 sort 0} +do_test where7-2.12.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=50.0 AND d<51.0 AND d NOT NULL) + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR b=792 + OR a=97 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR b=916 + OR a=69 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR c=6006 + } +} {16 17 18 31 50 69 72 81 83 87 97 scan 0 sort 0} +do_test where7-2.13.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 50 AND 52) AND a!=51) + OR c=9009 + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR b=539 + OR b=297 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR b=957 + OR f='xyzabcdef' + OR b=619 + } +} {10 15 21 23 25 26 27 49 50 52 75 87 scan 0 sort 0} +do_test where7-2.13.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 50 AND 52) AND a!=51) + OR c=9009 + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR b=539 + OR b=297 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR b=957 + OR f='xyzabcdef' + OR b=619 + } +} {10 15 21 23 25 26 27 49 50 52 75 87 scan 0 sort 0} +do_test where7-2.14.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 47 AND 49) AND a!=48) + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + } +} {47 48 49 scan 0 sort 0} +do_test where7-2.14.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 47 AND 49) AND a!=48) + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + } +} {47 48 49 scan 0 sort 0} +do_test where7-2.15.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=20 + OR a=67 + OR b=58 + OR ((a BETWEEN 19 AND 21) AND a!=20) + } +} {19 20 21 67 scan 0 sort 0} +do_test where7-2.15.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=20 + OR a=67 + OR b=58 + OR ((a BETWEEN 19 AND 21) AND a!=20) + } +} {19 20 21 67 scan 0 sort 0} +do_test where7-2.16.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=938 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'rstuv*') + } +} {17 67 scan 0 sort 0} +do_test where7-2.16.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=938 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'rstuv*') + } +} {17 67 scan 0 sort 0} +do_test where7-2.17.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=68.0 AND d<69.0 AND d NOT NULL) + OR f='zabcdefgh' + OR b=308 + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'defgh*') + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR b=443 + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR f='uvwxyzabc' + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + } +} {12 14 15 16 17 20 24 25 28 29 46 50 51 68 72 76 77 98 scan 0 sort 0} +do_test where7-2.17.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=68.0 AND d<69.0 AND d NOT NULL) + OR f='zabcdefgh' + OR b=308 + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'defgh*') + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR b=443 + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR f='uvwxyzabc' + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + } +} {12 14 15 16 17 20 24 25 28 29 46 50 51 68 72 76 77 98 scan 0 sort 0} +do_test where7-2.18.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=762 + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR a=19 + } +} {19 46 56 scan 0 sort 0} +do_test where7-2.18.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=762 + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR a=19 + } +} {19 46 56 scan 0 sort 0} +do_test where7-2.19.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=63.0 AND d<64.0 AND d NOT NULL) + OR a=46 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR a=73 + OR c=20020 + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR b=267 + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + } +} {2 4 20 46 58 59 60 63 68 70 73 scan 0 sort 0} +do_test where7-2.19.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=63.0 AND d<64.0 AND d NOT NULL) + OR a=46 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR a=73 + OR c=20020 + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR b=267 + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + } +} {2 4 20 46 58 59 60 63 68 70 73 scan 0 sort 0} +do_test where7-2.20.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 27 AND 29) AND a!=28) + OR (g='gfedcba' AND f GLOB 'nopqr*') + } +} {27 29 91 scan 0 sort 0} +do_test where7-2.20.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 27 AND 29) AND a!=28) + OR (g='gfedcba' AND f GLOB 'nopqr*') + } +} {27 29 91 scan 0 sort 0} +do_test where7-2.21.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=13013 + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR f='bcdefghij' + OR b=586 + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR (d>=6.0 AND d<7.0 AND d NOT NULL) + OR a=9 + } +} {1 6 9 27 37 38 39 53 55 58 59 61 75 79 87 89 98 scan 0 sort 0} +do_test where7-2.21.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=13013 + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR f='bcdefghij' + OR b=586 + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR (d>=6.0 AND d<7.0 AND d NOT NULL) + OR a=9 + } +} {1 6 9 27 37 38 39 53 55 58 59 61 75 79 87 89 98 scan 0 sort 0} +do_test where7-2.22.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=399 + OR c=28028 + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + } +} {42 82 83 84 98 scan 0 sort 0} +do_test where7-2.22.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=399 + OR c=28028 + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + } +} {42 82 83 84 98 scan 0 sort 0} +do_test where7-2.23.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR c=14014 + OR c=33033 + OR a=89 + OR b=770 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR a=35 + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR b=253 + OR c=14014 + } +} {4 19 23 30 35 40 41 42 56 70 82 89 95 96 97 98 99 scan 0 sort 0} +do_test where7-2.23.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR c=14014 + OR c=33033 + OR a=89 + OR b=770 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR a=35 + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR b=253 + OR c=14014 + } +} {4 19 23 30 35 40 41 42 56 70 82 89 95 96 97 98 99 scan 0 sort 0} +do_test where7-2.24.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='utsrqpo' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=330 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR a=16 + } +} {6 16 21 30 32 34 scan 0 sort 0} +do_test where7-2.24.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='utsrqpo' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=330 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR a=16 + } +} {6 16 21 30 32 34 scan 0 sort 0} +do_test where7-2.25.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=5005 + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + } +} {2 13 14 15 36 38 47 scan 0 sort 0} +do_test where7-2.25.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=5005 + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + } +} {2 13 14 15 36 38 47 scan 0 sort 0} +do_test where7-2.26.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=30.0 AND d<31.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=33 + } +} {30 33 58 64 66 68 scan 0 sort 0} +do_test where7-2.26.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=30.0 AND d<31.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=33 + } +} {30 33 58 64 66 68 scan 0 sort 0} +do_test where7-2.27.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1026 + OR b=410 + } +} { scan 0 sort 0} +do_test where7-2.27.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1026 + OR b=410 + } +} { scan 0 sort 0} +do_test where7-2.28.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=18018 + OR a=94 + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=1012 + OR a=3 + OR d>1e10 + OR b=905 + OR b=1089 + } +} {3 15 26 41 52 53 54 67 92 93 94 99 scan 0 sort 0} +do_test where7-2.28.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=18018 + OR a=94 + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=1012 + OR a=3 + OR d>1e10 + OR b=905 + OR b=1089 + } +} {3 15 26 41 52 53 54 67 92 93 94 99 scan 0 sort 0} +do_test where7-2.29.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=100 + OR c=11011 + OR b=297 + OR a=63 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR a=76 + OR b=1026 + OR a=26 + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR c=30030 + } +} {24 26 27 31 32 33 50 63 76 84 88 89 90 100 scan 0 sort 0} +do_test where7-2.29.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=100 + OR c=11011 + OR b=297 + OR a=63 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR a=76 + OR b=1026 + OR a=26 + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR c=30030 + } +} {24 26 27 31 32 33 50 63 76 84 88 89 90 100 scan 0 sort 0} +do_test where7-2.30.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=561 + OR b=1070 + OR a=59 + OR b=715 + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + } +} {23 49 51 59 65 75 scan 0 sort 0} +do_test where7-2.30.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=561 + OR b=1070 + OR a=59 + OR b=715 + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + } +} {23 49 51 59 65 75 scan 0 sort 0} +do_test where7-2.31.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=1056 + OR b=1012 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + } +} {19 26 52 57 59 67 69 78 92 95 96 scan 0 sort 0} +do_test where7-2.31.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=1056 + OR b=1012 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + } +} {19 26 52 57 59 67 69 78 92 95 96 scan 0 sort 0} +do_test where7-2.32.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='rstuvwxyz' + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + } +} {17 43 69 74 90 92 95 98 scan 0 sort 0} +do_test where7-2.32.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='rstuvwxyz' + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + } +} {17 43 69 74 90 92 95 98 scan 0 sort 0} +do_test where7-2.33.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR c=12012 + OR a=18 + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + } +} {9 15 17 18 26 34 35 36 41 43 52 61 67 69 76 78 87 93 95 scan 0 sort 0} +do_test where7-2.33.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR c=12012 + OR a=18 + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + } +} {9 15 17 18 26 34 35 36 41 43 52 61 67 69 76 78 87 93 95 scan 0 sort 0} +do_test where7-2.34.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=77 + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + } +} {58 77 scan 0 sort 0} +do_test where7-2.34.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=77 + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + } +} {58 77 scan 0 sort 0} +do_test where7-2.35.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=498 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR c=33033 + OR b=11 + OR (g='wvutsrq' AND f GLOB 'lmnop*') + OR ((a BETWEEN 7 AND 9) AND a!=8) + } +} {1 7 9 11 27 67 69 88 97 98 99 scan 0 sort 0} +do_test where7-2.35.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=498 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR c=33033 + OR b=11 + OR (g='wvutsrq' AND f GLOB 'lmnop*') + OR ((a BETWEEN 7 AND 9) AND a!=8) + } +} {1 7 9 11 27 67 69 88 97 98 99 scan 0 sort 0} +do_test where7-2.36.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=6.0 AND d<7.0 AND d NOT NULL) + OR ((a BETWEEN 58 AND 60) AND a!=59) + } +} {6 58 60 scan 0 sort 0} +do_test where7-2.36.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=6.0 AND d<7.0 AND d NOT NULL) + OR ((a BETWEEN 58 AND 60) AND a!=59) + } +} {6 58 60 scan 0 sort 0} +do_test where7-2.37.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1059 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR c=4004 + OR b=806 + } +} {10 11 12 43 scan 0 sort 0} +do_test where7-2.37.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1059 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR c=4004 + OR b=806 + } +} {10 11 12 43 scan 0 sort 0} +do_test where7-2.38.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=165 + OR b=201 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR a=32 + } +} {15 32 99 scan 0 sort 0} +do_test where7-2.38.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=165 + OR b=201 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR a=32 + } +} {15 32 99 scan 0 sort 0} +do_test where7-2.39.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'rstuv*') + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + } +} {22 48 69 74 100 scan 0 sort 0} +do_test where7-2.39.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'rstuv*') + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + } +} {22 48 69 74 100 scan 0 sort 0} +do_test where7-2.40.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=352 + OR b=278 + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR b=660 + OR a=18 + OR a=34 + OR b=132 + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR c=18018 + } +} {2 12 18 28 30 32 34 52 53 54 60 80 89 90 92 scan 0 sort 0} +do_test where7-2.40.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=352 + OR b=278 + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR b=660 + OR a=18 + OR a=34 + OR b=132 + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR c=18018 + } +} {2 12 18 28 30 32 34 52 53 54 60 80 89 90 92 scan 0 sort 0} +do_test where7-2.41.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=73.0 AND d<74.0 AND d NOT NULL) + OR ((a BETWEEN 5 AND 7) AND a!=6) + } +} {5 7 73 scan 0 sort 0} +do_test where7-2.41.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=73.0 AND d<74.0 AND d NOT NULL) + OR ((a BETWEEN 5 AND 7) AND a!=6) + } +} {5 7 73 scan 0 sort 0} +do_test where7-2.42.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?efgh*' AND f GLOB 'defg*') + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'fghij*') + OR b=297 + OR b=113 + OR b=176 + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR a=67 + OR c=26026 + } +} {3 14 16 21 27 29 55 67 75 76 77 78 81 83 scan 0 sort 0} +do_test where7-2.42.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?efgh*' AND f GLOB 'defg*') + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'fghij*') + OR b=297 + OR b=113 + OR b=176 + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR a=67 + OR c=26026 + } +} {3 14 16 21 27 29 55 67 75 76 77 78 81 83 scan 0 sort 0} +do_test where7-2.43.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=78.0 AND d<79.0 AND d NOT NULL) + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR a=83 + OR b=44 + OR b=1023 + OR ((a BETWEEN 11 AND 13) AND a!=12) + OR b=1023 + OR f='ijklmnopq' + } +} {4 6 8 11 13 34 60 78 83 86 93 scan 0 sort 0} +do_test where7-2.43.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=78.0 AND d<79.0 AND d NOT NULL) + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR a=83 + OR b=44 + OR b=1023 + OR ((a BETWEEN 11 AND 13) AND a!=12) + OR b=1023 + OR f='ijklmnopq' + } +} {4 6 8 11 13 34 60 78 83 86 93 scan 0 sort 0} +do_test where7-2.44.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=42.0 AND d<43.0 AND d NOT NULL) + OR b=935 + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=487 + OR b=619 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR (g='vutsrqp' AND f GLOB 'rstuv*') + } +} {17 32 34 39 42 85 scan 0 sort 0} +do_test where7-2.44.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=42.0 AND d<43.0 AND d NOT NULL) + OR b=935 + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=487 + OR b=619 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR (g='vutsrqp' AND f GLOB 'rstuv*') + } +} {17 32 34 39 42 85 scan 0 sort 0} +do_test where7-2.45.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=68.0 AND d<69.0 AND d NOT NULL) + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=938 + OR b=641 + OR c=17017 + OR a=82 + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + OR (g='rqponml' AND f GLOB 'lmnop*') + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + } +} {37 39 49 50 51 56 58 65 68 82 94 scan 0 sort 0} +do_test where7-2.45.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=68.0 AND d<69.0 AND d NOT NULL) + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=938 + OR b=641 + OR c=17017 + OR a=82 + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + OR (g='rqponml' AND f GLOB 'lmnop*') + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + } +} {37 39 49 50 51 56 58 65 68 82 94 scan 0 sort 0} +do_test where7-2.46.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ihgfedc' AND f GLOB 'bcdef*') + OR c=22022 + } +} {64 65 66 79 scan 0 sort 0} +do_test where7-2.46.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ihgfedc' AND f GLOB 'bcdef*') + OR c=22022 + } +} {64 65 66 79 scan 0 sort 0} +do_test where7-2.47.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=7007 + OR b=91 + OR b=212 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR c=28028 + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + } +} {19 20 21 65 82 83 84 scan 0 sort 0} +do_test where7-2.47.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=7007 + OR b=91 + OR b=212 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR c=28028 + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + } +} {19 20 21 65 82 83 84 scan 0 sort 0} +do_test where7-2.48.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=12.0 AND d<13.0 AND d NOT NULL) + OR a=51 + OR ((a BETWEEN 28 AND 30) AND a!=29) + } +} {12 28 30 51 scan 0 sort 0} +do_test where7-2.48.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=12.0 AND d<13.0 AND d NOT NULL) + OR a=51 + OR ((a BETWEEN 28 AND 30) AND a!=29) + } +} {12 28 30 51 scan 0 sort 0} +do_test where7-2.49.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='wvutsrq' AND f GLOB 'mnopq*') + OR (g='wvutsrq' AND f GLOB 'jklmn*') + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR ((a BETWEEN 0 AND 2) AND a!=1) + OR c=4004 + OR b=322 + OR c=13013 + OR a=6 + } +} {2 6 9 10 11 12 23 37 38 39 scan 0 sort 0} +do_test where7-2.49.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='wvutsrq' AND f GLOB 'mnopq*') + OR (g='wvutsrq' AND f GLOB 'jklmn*') + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR ((a BETWEEN 0 AND 2) AND a!=1) + OR c=4004 + OR b=322 + OR c=13013 + OR a=6 + } +} {2 6 9 10 11 12 23 37 38 39 scan 0 sort 0} +do_test where7-2.50.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=297 + OR b=143 + OR a=46 + OR b=660 + OR (d>=41.0 AND d<42.0 AND d NOT NULL) + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR b=355 + OR a=93 + OR b=297 + } +} {13 17 23 27 41 46 49 60 75 93 scan 0 sort 0} +do_test where7-2.50.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=297 + OR b=143 + OR a=46 + OR b=660 + OR (d>=41.0 AND d<42.0 AND d NOT NULL) + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR b=355 + OR a=93 + OR b=297 + } +} {13 17 23 27 41 46 49 60 75 93 scan 0 sort 0} +do_test where7-2.51.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=190 + OR a=62 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + } +} {62 99 scan 0 sort 0} +do_test where7-2.51.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=190 + OR a=62 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + } +} {62 99 scan 0 sort 0} +do_test where7-2.52.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1089 + OR b=102 + OR a=6 + OR b=608 + } +} {6 99 scan 0 sort 0} +do_test where7-2.52.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1089 + OR b=102 + OR a=6 + OR b=608 + } +} {6 99 scan 0 sort 0} +do_test where7-2.53.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=473 + OR b=1100 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR a=20 + OR b=1089 + OR b=330 + OR b=124 + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {15 20 30 43 53 56 58 99 100 scan 0 sort 0} +do_test where7-2.53.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=473 + OR b=1100 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR a=20 + OR b=1089 + OR b=330 + OR b=124 + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {15 20 30 43 53 56 58 99 100 scan 0 sort 0} +do_test where7-2.54.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 68 AND 70) AND a!=69) + OR b=223 + OR a=12 + OR b=1048 + OR b=256 + OR a=72 + OR c>=34035 + OR (g='rqponml' AND f GLOB 'jklmn*') + OR b=674 + OR a=22 + } +} {12 22 35 68 70 72 scan 0 sort 0} +do_test where7-2.54.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 68 AND 70) AND a!=69) + OR b=223 + OR a=12 + OR b=1048 + OR b=256 + OR a=72 + OR c>=34035 + OR (g='rqponml' AND f GLOB 'jklmn*') + OR b=674 + OR a=22 + } +} {12 22 35 68 70 72 scan 0 sort 0} +do_test where7-2.55.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 76 AND 78) AND a!=77) + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR f='yzabcdefg' + OR c=14014 + OR a=1 + OR a=9 + OR b=960 + } +} {1 9 24 40 41 42 50 76 78 scan 0 sort 0} +do_test where7-2.55.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 76 AND 78) AND a!=77) + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR f='yzabcdefg' + OR c=14014 + OR a=1 + OR a=9 + OR b=960 + } +} {1 9 24 40 41 42 50 76 78 scan 0 sort 0} +do_test where7-2.56.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='utsrqpo' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR (g='onmlkji' AND f GLOB 'xyzab*') + } +} {19 49 96 98 scan 0 sort 0} +do_test where7-2.56.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='utsrqpo' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR (g='onmlkji' AND f GLOB 'xyzab*') + } +} {19 49 96 98 scan 0 sort 0} +do_test where7-2.57.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=748 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR b=630 + } +} {9 20 67 68 scan 0 sort 0} +do_test where7-2.57.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=748 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR b=630 + } +} {9 20 67 68 scan 0 sort 0} +do_test where7-2.58.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=223 + OR b=267 + OR a=40 + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR c<=10 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR b=528 + } +} {40 48 55 57 69 71 scan 0 sort 0} +do_test where7-2.58.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=223 + OR b=267 + OR a=40 + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR c<=10 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR b=528 + } +} {40 48 55 57 69 71 scan 0 sort 0} +do_test where7-2.59.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='rstuvwxyz' + OR a=41 + OR b=462 + OR a=68 + OR a=84 + OR a=69 + } +} {17 41 42 43 68 69 84 95 scan 0 sort 0} +do_test where7-2.59.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='rstuvwxyz' + OR a=41 + OR b=462 + OR a=68 + OR a=84 + OR a=69 + } +} {17 41 42 43 68 69 84 95 scan 0 sort 0} +do_test where7-2.60.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=979 + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR (g='vutsrqp' AND f GLOB 'nopqr*') + } +} {3 5 13 89 scan 0 sort 0} +do_test where7-2.60.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=979 + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR (g='vutsrqp' AND f GLOB 'nopqr*') + } +} {3 5 13 89 scan 0 sort 0} +do_test where7-2.61.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=9.0 AND d<10.0 AND d NOT NULL) + OR a=8 + OR a=62 + OR b=726 + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {8 9 10 14 50 52 59 61 62 66 scan 0 sort 0} +do_test where7-2.61.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=9.0 AND d<10.0 AND d NOT NULL) + OR a=8 + OR a=62 + OR b=726 + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {8 9 10 14 50 52 59 61 62 66 scan 0 sort 0} +do_test where7-2.62.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=495 + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR b=924 + OR c=11011 + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR b=231 + OR b=872 + OR (g='jihgfed' AND f GLOB 'yzabc*') + } +} {18 20 21 31 32 33 45 47 73 76 84 99 scan 0 sort 0} +do_test where7-2.62.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=495 + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR b=924 + OR c=11011 + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR b=231 + OR b=872 + OR (g='jihgfed' AND f GLOB 'yzabc*') + } +} {18 20 21 31 32 33 45 47 73 76 84 99 scan 0 sort 0} +do_test where7-2.63.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=24 + OR b=473 + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR b=509 + OR b=924 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + } +} {21 24 43 84 86 96 scan 0 sort 0} +do_test where7-2.63.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=24 + OR b=473 + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR b=509 + OR b=924 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + } +} {21 24 43 84 86 96 scan 0 sort 0} +do_test where7-2.64.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=93.0 AND d<94.0 AND d NOT NULL) + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR b=363 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {2 5 8 23 25 28 33 34 54 56 58 60 80 86 93 100 scan 0 sort 0} +do_test where7-2.64.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=93.0 AND d<94.0 AND d NOT NULL) + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR b=363 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {2 5 8 23 25 28 33 34 54 56 58 60 80 86 93 100 scan 0 sort 0} +do_test where7-2.65.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=42 + OR e IS NULL + OR b=495 + OR 1000000=65.0 AND d<66.0 AND d NOT NULL) + } +} {20 42 45 46 65 69 72 85 98 scan 0 sort 0} +do_test where7-2.65.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=42 + OR e IS NULL + OR b=495 + OR 1000000=65.0 AND d<66.0 AND d NOT NULL) + } +} {20 42 45 46 65 69 72 85 98 scan 0 sort 0} +do_test where7-2.66.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=17017 + OR f='ijklmnopq' + OR a=39 + } +} {8 34 39 49 50 51 60 86 scan 0 sort 0} +do_test where7-2.66.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=17017 + OR f='ijklmnopq' + OR a=39 + } +} {8 34 39 49 50 51 60 86 scan 0 sort 0} +do_test where7-2.67.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c>=34035 + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR a=91 + } +} {11 19 27 37 63 89 91 96 98 100 scan 0 sort 0} +do_test where7-2.67.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c>=34035 + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR a=91 + } +} {11 19 27 37 63 89 91 96 98 100 scan 0 sort 0} +do_test where7-2.68.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='gfedcba' AND f GLOB 'nopqr*') + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR b=649 + OR b=231 + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR b=58 + } +} {9 21 28 29 35 48 59 61 87 91 scan 0 sort 0} +do_test where7-2.68.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='gfedcba' AND f GLOB 'nopqr*') + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR b=649 + OR b=231 + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR b=58 + } +} {9 21 28 29 35 48 59 61 87 91 scan 0 sort 0} +do_test where7-2.69.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=979 + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + } +} {78 89 scan 0 sort 0} +do_test where7-2.69.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=979 + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + } +} {78 89 scan 0 sort 0} +do_test where7-2.70.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=825 + OR b=1004 + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {56 58 60 62 75 scan 0 sort 0} +do_test where7-2.70.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=825 + OR b=1004 + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {56 58 60 62 75 scan 0 sort 0} +do_test where7-2.71.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=65 + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR c=22022 + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR b=671 + OR (g='onmlkji' AND f GLOB 'zabcd*') + OR a=91 + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + OR ((a BETWEEN 47 AND 49) AND a!=48) + OR b=1004 + OR b=960 + } +} {5 31 47 49 51 57 61 64 65 66 83 91 98 scan 0 sort 0} +do_test where7-2.71.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=65 + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR c=22022 + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR b=671 + OR (g='onmlkji' AND f GLOB 'zabcd*') + OR a=91 + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + OR ((a BETWEEN 47 AND 49) AND a!=48) + OR b=1004 + OR b=960 + } +} {5 31 47 49 51 57 61 64 65 66 83 91 98 scan 0 sort 0} +do_test where7-2.72.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=762 + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {56 58 93 scan 0 sort 0} +do_test where7-2.72.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=762 + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {56 58 93 scan 0 sort 0} +do_test where7-2.73.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=11.0 AND d<12.0 AND d NOT NULL) + OR a=14 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR b=212 + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + } +} {11 14 23 54 78 85 scan 0 sort 0} +do_test where7-2.73.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=11.0 AND d<12.0 AND d NOT NULL) + OR a=14 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR b=212 + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + } +} {11 14 23 54 78 85 scan 0 sort 0} +do_test where7-2.74.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ihgfedc' AND f GLOB 'bcdef*') + OR b=168 + OR b=25 + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'opqrs*') + } +} {66 79 89 scan 0 sort 0} +do_test where7-2.74.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ihgfedc' AND f GLOB 'bcdef*') + OR b=168 + OR b=25 + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'opqrs*') + } +} {66 79 89 scan 0 sort 0} +do_test where7-2.75.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=28028 + OR f='jklmnopqr' + OR b=1015 + } +} {9 35 61 82 83 84 87 scan 0 sort 0} +do_test where7-2.75.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=28028 + OR f='jklmnopqr' + OR b=1015 + } +} {9 35 61 82 83 84 87 scan 0 sort 0} +do_test where7-2.76.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=31031 + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR a=49 + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'klmno*') + } +} {15 41 49 56 62 67 87 89 91 92 93 100 scan 0 sort 0} +do_test where7-2.76.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=31031 + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR a=49 + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'klmno*') + } +} {15 41 49 56 62 67 87 89 91 92 93 100 scan 0 sort 0} +do_test where7-2.77.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=80 + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR b=971 + OR a=60 + } +} {4 6 25 29 60 80 scan 0 sort 0} +do_test where7-2.77.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=80 + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR b=971 + OR a=60 + } +} {4 6 25 29 60 80 scan 0 sort 0} +do_test where7-2.78.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=85.0 AND d<86.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR b=1089 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + } +} {30 32 43 85 89 99 scan 0 sort 0} +do_test where7-2.78.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=85.0 AND d<86.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR b=1089 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + } +} {30 32 43 85 89 99 scan 0 sort 0} +do_test where7-2.79.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=399 + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR a=10 + OR b=1026 + } +} {9 10 11 57 90 scan 0 sort 0} +do_test where7-2.79.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=399 + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR a=10 + OR b=1026 + } +} {9 10 11 57 90 scan 0 sort 0} +do_test where7-2.80.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'yzabc*') + OR b=465 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR (g='xwvutsr' AND f GLOB 'fghij*') + } +} {5 43 65 76 scan 0 sort 0} +do_test where7-2.80.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'yzabc*') + OR b=465 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR (g='xwvutsr' AND f GLOB 'fghij*') + } +} {5 43 65 76 scan 0 sort 0} +do_test where7-2.81.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=25 + OR b=792 + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + } +} {19 25 45 71 72 97 scan 0 sort 0} +do_test where7-2.81.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=25 + OR b=792 + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + } +} {19 25 45 71 72 97 scan 0 sort 0} +do_test where7-2.82.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=979 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR a=13 + OR a=15 + OR ((a BETWEEN 6 AND 8) AND a!=7) + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR a=27 + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR a=32 + OR a=39 + } +} {6 8 13 15 21 27 32 39 67 89 98 100 scan 0 sort 0} +do_test where7-2.82.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=979 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR a=13 + OR a=15 + OR ((a BETWEEN 6 AND 8) AND a!=7) + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR a=27 + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR a=32 + OR a=39 + } +} {6 8 13 15 21 27 32 39 67 89 98 100 scan 0 sort 0} +do_test where7-2.83.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='hijklmnop' + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR b=528 + OR c=30030 + OR (g='qponmlk' AND f GLOB 'qrstu*') + } +} {1 7 21 31 33 42 48 58 59 77 79 85 88 89 90 scan 0 sort 0} +do_test where7-2.83.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='hijklmnop' + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR b=528 + OR c=30030 + OR (g='qponmlk' AND f GLOB 'qrstu*') + } +} {1 7 21 31 33 42 48 58 59 77 79 85 88 89 90 scan 0 sort 0} +do_test where7-2.84.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=69 + OR e IS NULL + OR b=352 + OR 1000000=16.0 AND d<17.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR c=33033 + } +} {1 2 3 8 9 14 16 78 85 86 97 98 99 scan 0 sort 0} +do_test where7-2.87.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 14 AND 16) AND a!=15) + OR (g='wvutsrq' AND f GLOB 'jklmn*') + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR c=1001 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR c=33033 + } +} {1 2 3 8 9 14 16 78 85 86 97 98 99 scan 0 sort 0} +do_test where7-2.88.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=311 + OR b=1103 + OR b=88 + } +} {8 scan 0 sort 0} +do_test where7-2.88.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=311 + OR b=1103 + OR b=88 + } +} {8 scan 0 sort 0} +do_test where7-2.89.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 65 AND 67) AND a!=66) + OR ((a BETWEEN 26 AND 28) AND a!=27) + OR c=5005 + OR b=1045 + OR c=8008 + OR f='bcdefghij' + } +} {1 13 14 15 22 23 24 26 27 28 53 65 67 79 95 scan 0 sort 0} +do_test where7-2.89.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 65 AND 67) AND a!=66) + OR ((a BETWEEN 26 AND 28) AND a!=27) + OR c=5005 + OR b=1045 + OR c=8008 + OR f='bcdefghij' + } +} {1 13 14 15 22 23 24 26 27 28 53 65 67 79 95 scan 0 sort 0} +do_test where7-2.90.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=66 + OR b=553 + OR a=64 + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR a=62 + OR b=1081 + OR b=770 + OR b=762 + OR b=803 + OR (g='srqponm' AND f GLOB 'efghi*') + } +} {6 17 30 62 64 70 73 93 scan 0 sort 0} +do_test where7-2.90.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=66 + OR b=553 + OR a=64 + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR a=62 + OR b=1081 + OR b=770 + OR b=762 + OR b=803 + OR (g='srqponm' AND f GLOB 'efghi*') + } +} {6 17 30 62 64 70 73 93 scan 0 sort 0} +do_test where7-2.91.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='wvutsrq' AND f GLOB 'klmno*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR c=17017 + OR b=168 + OR ((a BETWEEN 77 AND 79) AND a!=78) + } +} {10 19 45 49 50 51 71 77 79 97 scan 0 sort 0} +do_test where7-2.91.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='wvutsrq' AND f GLOB 'klmno*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR c=17017 + OR b=168 + OR ((a BETWEEN 77 AND 79) AND a!=78) + } +} {10 19 45 49 50 51 71 77 79 97 scan 0 sort 0} +do_test where7-2.92.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=34034 + OR (d>=68.0 AND d<69.0 AND d NOT NULL) + OR a=44 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR c=31031 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR b=619 + OR (f GLOB '?efgh*' AND f GLOB 'defg*') + OR ((a BETWEEN 29 AND 31) AND a!=30) + } +} {3 12 23 29 31 44 55 68 78 81 91 92 93 100 scan 0 sort 0} +do_test where7-2.92.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=34034 + OR (d>=68.0 AND d<69.0 AND d NOT NULL) + OR a=44 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR c=31031 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR b=619 + OR (f GLOB '?efgh*' AND f GLOB 'defg*') + OR ((a BETWEEN 29 AND 31) AND a!=30) + } +} {3 12 23 29 31 44 55 68 78 81 91 92 93 100 scan 0 sort 0} +do_test where7-2.93.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=48 + OR c=15015 + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR b=110 + OR f='klmnopqrs' + OR (g='fedcbaz' AND f GLOB 'qrstu*') + OR (g='onmlkji' AND f GLOB 'abcde*') + OR b=674 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + } +} {10 36 43 44 45 48 52 62 65 67 88 94 96 97 99 scan 0 sort 0} +do_test where7-2.93.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=48 + OR c=15015 + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR b=110 + OR f='klmnopqrs' + OR (g='fedcbaz' AND f GLOB 'qrstu*') + OR (g='onmlkji' AND f GLOB 'abcde*') + OR b=674 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + } +} {10 36 43 44 45 48 52 62 65 67 88 94 96 97 99 scan 0 sort 0} +do_test where7-2.94.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=72 + OR b=913 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=121 + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + } +} {2 11 28 72 83 scan 0 sort 0} +do_test where7-2.94.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=72 + OR b=913 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=121 + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + } +} {2 11 28 72 83 scan 0 sort 0} +do_test where7-2.95.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=18 + OR b=286 + OR b=1015 + OR a=49 + OR b=264 + } +} {18 24 26 49 scan 0 sort 0} +do_test where7-2.95.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=18 + OR b=286 + OR b=1015 + OR a=49 + OR b=264 + } +} {18 24 26 49 scan 0 sort 0} +do_test where7-2.96.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=69 + OR a=11 + OR c=1001 + OR ((a BETWEEN 54 AND 56) AND a!=55) + OR a=57 + OR ((a BETWEEN 48 AND 50) AND a!=49) + } +} {1 2 3 11 48 50 54 56 57 scan 0 sort 0} +do_test where7-2.96.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=69 + OR a=11 + OR c=1001 + OR ((a BETWEEN 54 AND 56) AND a!=55) + OR a=57 + OR ((a BETWEEN 48 AND 50) AND a!=49) + } +} {1 2 3 11 48 50 54 56 57 scan 0 sort 0} +do_test where7-2.97.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=231 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + } +} {21 84 scan 0 sort 0} +do_test where7-2.97.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=231 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + } +} {21 84 scan 0 sort 0} +do_test where7-2.98.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=25 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR ((a BETWEEN 81 AND 83) AND a!=82) + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR b=289 + OR ((a BETWEEN 85 AND 87) AND a!=86) + } +} {3 5 17 23 81 83 85 87 scan 0 sort 0} +do_test where7-2.98.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=25 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR ((a BETWEEN 81 AND 83) AND a!=82) + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR b=289 + OR ((a BETWEEN 85 AND 87) AND a!=86) + } +} {3 5 17 23 81 83 85 87 scan 0 sort 0} +do_test where7-2.99.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='defghijkl' + OR b=465 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR c=9009 + OR b=990 + OR b=132 + OR a=35 + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR a=81 + OR ((a BETWEEN 71 AND 73) AND a!=72) + } +} {3 12 25 26 27 29 35 46 55 71 73 78 81 90 scan 0 sort 0} +do_test where7-2.99.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='defghijkl' + OR b=465 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR c=9009 + OR b=990 + OR b=132 + OR a=35 + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR a=81 + OR ((a BETWEEN 71 AND 73) AND a!=72) + } +} {3 12 25 26 27 29 35 46 55 71 73 78 81 90 scan 0 sort 0} +do_test where7-2.100.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=26026 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR f='lmnopqrst' + OR a=6 + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {6 9 11 37 59 61 63 76 77 78 89 scan 0 sort 0} +do_test where7-2.100.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=26026 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR f='lmnopqrst' + OR a=6 + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {6 9 11 37 59 61 63 76 77 78 89 scan 0 sort 0} +do_test where7-2.101.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 98 AND 100) AND a!=99) + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + } +} {7 98 100 scan 0 sort 0} +do_test where7-2.101.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 98 AND 100) AND a!=99) + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + } +} {7 98 100 scan 0 sort 0} +do_test where7-2.102.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=11011 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR b=630 + OR c=19019 + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR a=24 + OR (d>=95.0 AND d<96.0 AND d NOT NULL) + OR ((a BETWEEN 51 AND 53) AND a!=52) + } +} {24 31 32 33 51 53 55 56 57 89 95 scan 0 sort 0} +do_test where7-2.102.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=11011 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR b=630 + OR c=19019 + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR a=24 + OR (d>=95.0 AND d<96.0 AND d NOT NULL) + OR ((a BETWEEN 51 AND 53) AND a!=52) + } +} {24 31 32 33 51 53 55 56 57 89 95 scan 0 sort 0} +do_test where7-2.103.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 91 AND 93) AND a!=92) + OR b=993 + OR a=81 + OR b=366 + OR b=69 + } +} {81 91 93 scan 0 sort 0} +do_test where7-2.103.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 91 AND 93) AND a!=92) + OR b=993 + OR a=81 + OR b=366 + OR b=69 + } +} {81 91 93 scan 0 sort 0} +do_test where7-2.104.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='stuvwxyza' + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR ((a BETWEEN 1 AND 3) AND a!=2) + OR b=1037 + OR f='zabcdefgh' + OR (g='gfedcba' AND f GLOB 'mnopq*') + } +} {1 3 18 24 25 44 50 51 70 76 77 90 96 scan 0 sort 0} +do_test where7-2.104.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='stuvwxyza' + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR ((a BETWEEN 1 AND 3) AND a!=2) + OR b=1037 + OR f='zabcdefgh' + OR (g='gfedcba' AND f GLOB 'mnopq*') + } +} {1 3 18 24 25 44 50 51 70 76 77 90 96 scan 0 sort 0} +do_test where7-2.105.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'ghijk*') + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR ((a BETWEEN 30 AND 32) AND a!=31) + } +} {4 6 30 32 scan 0 sort 0} +do_test where7-2.105.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'ghijk*') + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR ((a BETWEEN 30 AND 32) AND a!=31) + } +} {4 6 30 32 scan 0 sort 0} +do_test where7-2.106.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=847 + OR b=190 + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR ((a BETWEEN 70 AND 72) AND a!=71) + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR b=704 + } +} {9 23 35 38 40 61 64 70 72 77 87 scan 0 sort 0} +do_test where7-2.106.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=847 + OR b=190 + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR ((a BETWEEN 70 AND 72) AND a!=71) + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR b=704 + } +} {9 23 35 38 40 61 64 70 72 77 87 scan 0 sort 0} +do_test where7-2.107.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=88 + OR f='vwxyzabcd' + OR f='fghijklmn' + OR (g='gfedcba' AND f GLOB 'lmnop*') + } +} {5 8 21 31 47 57 73 83 89 99 scan 0 sort 0} +do_test where7-2.107.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=88 + OR f='vwxyzabcd' + OR f='fghijklmn' + OR (g='gfedcba' AND f GLOB 'lmnop*') + } +} {5 8 21 31 47 57 73 83 89 99 scan 0 sort 0} +do_test where7-2.108.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=498 + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR a=1 + } +} {1 69 scan 0 sort 0} +do_test where7-2.108.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=498 + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR a=1 + } +} {1 69 scan 0 sort 0} +do_test where7-2.109.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 47 AND 49) AND a!=48) + OR a=5 + OR b=179 + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR a=69 + } +} {5 17 43 47 49 69 95 scan 0 sort 0} +do_test where7-2.109.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 47 AND 49) AND a!=48) + OR a=5 + OR b=179 + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR a=69 + } +} {5 17 43 47 49 69 95 scan 0 sort 0} +do_test where7-2.110.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=971 + OR (g='xwvutsr' AND f GLOB 'hijkl*') + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR b=828 + OR a=81 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR b=627 + OR b=355 + OR b=377 + OR a=44 + } +} {1 7 23 25 44 57 81 scan 0 sort 0} +do_test where7-2.110.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=971 + OR (g='xwvutsr' AND f GLOB 'hijkl*') + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR b=828 + OR a=81 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR b=627 + OR b=355 + OR b=377 + OR a=44 + } +} {1 7 23 25 44 57 81 scan 0 sort 0} +do_test where7-2.111.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=850 + OR ((a BETWEEN 6 AND 8) AND a!=7) + } +} {6 8 scan 0 sort 0} +do_test where7-2.111.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=850 + OR ((a BETWEEN 6 AND 8) AND a!=7) + } +} {6 8 scan 0 sort 0} +do_test where7-2.112.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='lkjihgf' AND f GLOB 'opqrs*') + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + } +} {17 43 66 69 95 scan 0 sort 0} +do_test where7-2.112.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='lkjihgf' AND f GLOB 'opqrs*') + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + } +} {17 43 66 69 95 scan 0 sort 0} +do_test where7-2.113.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=726 + OR b=740 + OR a=33 + OR c=8008 + OR f='rstuvwxyz' + OR b=168 + } +} {17 22 23 24 33 43 66 69 95 scan 0 sort 0} +do_test where7-2.113.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=726 + OR b=740 + OR a=33 + OR c=8008 + OR f='rstuvwxyz' + OR b=168 + } +} {17 22 23 24 33 43 66 69 95 scan 0 sort 0} +do_test where7-2.114.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='vutsrqp' AND f GLOB 'rstuv*') + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=396 + } +} {17 19 36 scan 0 sort 0} +do_test where7-2.114.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='vutsrqp' AND f GLOB 'rstuv*') + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=396 + } +} {17 19 36 scan 0 sort 0} +do_test where7-2.115.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=77 + OR ((a BETWEEN 48 AND 50) AND a!=49) + OR c<=10 + OR ((a BETWEEN 5 AND 7) AND a!=6) + } +} {5 7 48 50 77 scan 0 sort 0} +do_test where7-2.115.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=77 + OR ((a BETWEEN 48 AND 50) AND a!=49) + OR c<=10 + OR ((a BETWEEN 5 AND 7) AND a!=6) + } +} {5 7 48 50 77 scan 0 sort 0} +do_test where7-2.116.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 12 AND 14) AND a!=13) + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR b=253 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR b=396 + OR b=630 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR c=3003 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + } +} {1 7 8 9 12 13 14 15 20 22 23 27 36 49 53 79 scan 0 sort 0} +do_test where7-2.116.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 12 AND 14) AND a!=13) + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR b=253 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR b=396 + OR b=630 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR c=3003 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + } +} {1 7 8 9 12 13 14 15 20 22 23 27 36 49 53 79 scan 0 sort 0} +do_test where7-2.117.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=957 + OR b=242 + OR b=113 + OR b=957 + OR b=311 + OR b=143 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + } +} {9 10 13 22 35 48 61 87 scan 0 sort 0} +do_test where7-2.117.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=957 + OR b=242 + OR b=113 + OR b=957 + OR b=311 + OR b=143 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + } +} {9 10 13 22 35 48 61 87 scan 0 sort 0} +do_test where7-2.118.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 74 AND 76) AND a!=75) + OR ((a BETWEEN 94 AND 96) AND a!=95) + OR b=451 + OR (g='lkjihgf' AND f GLOB 'opqrs*') + } +} {41 66 74 76 94 96 scan 0 sort 0} +do_test where7-2.118.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 74 AND 76) AND a!=75) + OR ((a BETWEEN 94 AND 96) AND a!=95) + OR b=451 + OR (g='lkjihgf' AND f GLOB 'opqrs*') + } +} {41 66 74 76 94 96 scan 0 sort 0} +do_test where7-2.119.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=3.0 AND d<4.0 AND d NOT NULL) + OR b=451 + OR b=363 + OR b=330 + OR (g='srqponm' AND f GLOB 'efghi*') + OR ((a BETWEEN 52 AND 54) AND a!=53) + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR ((a BETWEEN 81 AND 83) AND a!=82) + OR (g='gfedcba' AND f GLOB 'lmnop*') + } +} {3 30 33 41 52 54 81 83 89 scan 0 sort 0} +do_test where7-2.119.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=3.0 AND d<4.0 AND d NOT NULL) + OR b=451 + OR b=363 + OR b=330 + OR (g='srqponm' AND f GLOB 'efghi*') + OR ((a BETWEEN 52 AND 54) AND a!=53) + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR ((a BETWEEN 81 AND 83) AND a!=82) + OR (g='gfedcba' AND f GLOB 'lmnop*') + } +} {3 30 33 41 52 54 81 83 89 scan 0 sort 0} +do_test where7-2.120.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR (d>=68.0 AND d<69.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR e IS NULL + OR b=759 + } +} {15 68 69 95 scan 0 sort 0} +do_test where7-2.120.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR (d>=68.0 AND d<69.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR e IS NULL + OR b=759 + } +} {15 68 69 95 scan 0 sort 0} +do_test where7-2.121.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR (g='jihgfed' AND f GLOB 'wxyza*') + } +} {19 21 45 71 74 97 scan 0 sort 0} +do_test where7-2.121.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR (g='jihgfed' AND f GLOB 'wxyza*') + } +} {19 21 45 71 74 97 scan 0 sort 0} +do_test where7-2.122.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1037 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR ((a BETWEEN 75 AND 77) AND a!=76) + } +} {27 43 45 47 75 77 82 scan 0 sort 0} +do_test where7-2.122.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1037 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR ((a BETWEEN 75 AND 77) AND a!=76) + } +} {27 43 45 47 75 77 82 scan 0 sort 0} +do_test where7-2.123.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1045 + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR c=12012 + } +} {34 35 36 37 38 39 95 scan 0 sort 0} +do_test where7-2.123.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1045 + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR c=12012 + } +} {34 35 36 37 38 39 95 scan 0 sort 0} +do_test where7-2.124.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='fedcbaz' AND f GLOB 'tuvwx*') + OR b=421 + OR b=429 + OR b=498 + OR b=33 + OR b=198 + OR c=14014 + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + } +} {3 18 23 39 40 41 42 49 75 97 scan 0 sort 0} +do_test where7-2.124.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='fedcbaz' AND f GLOB 'tuvwx*') + OR b=421 + OR b=429 + OR b=498 + OR b=33 + OR b=198 + OR c=14014 + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + } +} {3 18 23 39 40 41 42 49 75 97 scan 0 sort 0} +do_test where7-2.125.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=47 + OR c=31031 + OR a=38 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (g='srqponm' AND f GLOB 'fghij*') + OR b=242 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR b=352 + OR a=49 + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {8 22 31 32 34 38 49 57 60 70 86 91 92 93 scan 0 sort 0} +do_test where7-2.125.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=47 + OR c=31031 + OR a=38 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (g='srqponm' AND f GLOB 'fghij*') + OR b=242 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR b=352 + OR a=49 + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {8 22 31 32 34 38 49 57 60 70 86 91 92 93 scan 0 sort 0} +do_test where7-2.126.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=704 + OR a=7 + OR a=8 + OR a=46 + OR b=740 + OR b=993 + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + } +} {7 8 38 46 64 87 scan 0 sort 0} +do_test where7-2.126.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=704 + OR a=7 + OR a=8 + OR a=46 + OR b=740 + OR b=993 + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + } +} {7 8 38 46 64 87 scan 0 sort 0} +do_test where7-2.127.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 62 AND 64) AND a!=63) + OR c=32032 + OR a=76 + } +} {62 64 76 94 95 96 scan 0 sort 0} +do_test where7-2.127.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 62 AND 64) AND a!=63) + OR c=32032 + OR a=76 + } +} {62 64 76 94 95 96 scan 0 sort 0} +do_test where7-2.128.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=528 + OR (g='gfedcba' AND f GLOB 'nopqr*') + } +} {19 48 91 scan 0 sort 0} +do_test where7-2.128.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=528 + OR (g='gfedcba' AND f GLOB 'nopqr*') + } +} {19 48 91 scan 0 sort 0} +do_test where7-2.129.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR a=65 + } +} {26 65 97 scan 0 sort 0} +do_test where7-2.129.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR a=65 + } +} {26 65 97 scan 0 sort 0} +do_test where7-2.130.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=71.0 AND d<72.0 AND d NOT NULL) + OR 1000000=50.0 AND d<51.0 AND d NOT NULL) + OR a=24 + } +} {2 24 50 71 scan 0 sort 0} +do_test where7-2.130.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=71.0 AND d<72.0 AND d NOT NULL) + OR 1000000=50.0 AND d<51.0 AND d NOT NULL) + OR a=24 + } +} {2 24 50 71 scan 0 sort 0} +do_test where7-2.131.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=60 + OR a=39 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR b=36 + OR b=814 + OR a=14 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR b=440 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + } +} {5 14 25 39 40 51 60 61 74 77 93 95 scan 0 sort 0} +do_test where7-2.131.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=60 + OR a=39 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR b=36 + OR b=814 + OR a=14 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR b=440 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + } +} {5 14 25 39 40 51 60 61 74 77 93 95 scan 0 sort 0} +do_test where7-2.132.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f IS NULL + OR ((a BETWEEN 39 AND 41) AND a!=40) + } +} {39 41 scan 0 sort 0} +do_test where7-2.132.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f IS NULL + OR ((a BETWEEN 39 AND 41) AND a!=40) + } +} {39 41 scan 0 sort 0} +do_test where7-2.133.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=44 + OR ((a BETWEEN 17 AND 19) AND a!=18) + } +} {4 17 19 scan 0 sort 0} +do_test where7-2.133.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=44 + OR ((a BETWEEN 17 AND 19) AND a!=18) + } +} {4 17 19 scan 0 sort 0} +do_test where7-2.134.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=80.0 AND d<81.0 AND d NOT NULL) + OR a=82 + } +} {80 82 scan 0 sort 0} +do_test where7-2.134.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=80.0 AND d<81.0 AND d NOT NULL) + OR a=82 + } +} {80 82 scan 0 sort 0} +do_test where7-2.135.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR c=24024 + OR b=946 + OR a=19 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + } +} {19 47 70 71 72 84 86 scan 0 sort 0} +do_test where7-2.135.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR c=24024 + OR b=946 + OR a=19 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + } +} {19 47 70 71 72 84 86 scan 0 sort 0} +do_test where7-2.136.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=27 + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR b=1045 + OR a=84 + OR f='qrstuvwxy' + } +} {16 19 27 42 45 68 71 82 84 89 91 94 95 97 scan 0 sort 0} +do_test where7-2.136.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=27 + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR b=1045 + OR a=84 + OR f='qrstuvwxy' + } +} {16 19 27 42 45 68 71 82 84 89 91 94 95 97 scan 0 sort 0} +do_test where7-2.137.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=704 + OR b=949 + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR c=24024 + OR b=553 + OR a=18 + OR a=92 + } +} {18 22 64 70 71 72 92 scan 0 sort 0} +do_test where7-2.137.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=704 + OR b=949 + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR c=24024 + OR b=553 + OR a=18 + OR a=92 + } +} {18 22 64 70 71 72 92 scan 0 sort 0} +do_test where7-2.138.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR b=902 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR b=25 + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR f='zabcdefgh' + OR b=385 + } +} {1 16 18 25 27 35 51 53 61 77 79 82 scan 0 sort 0} +do_test where7-2.138.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR b=902 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR b=25 + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR f='zabcdefgh' + OR b=385 + } +} {1 16 18 25 27 35 51 53 61 77 79 82 scan 0 sort 0} +do_test where7-2.139.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=22 + OR b=36 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR ((a BETWEEN 81 AND 83) AND a!=82) + } +} {22 31 57 59 81 83 scan 0 sort 0} +do_test where7-2.139.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=22 + OR b=36 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR ((a BETWEEN 81 AND 83) AND a!=82) + } +} {22 31 57 59 81 83 scan 0 sort 0} +do_test where7-2.140.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=253 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + } +} {23 60 scan 0 sort 0} +do_test where7-2.140.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=253 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + } +} {23 60 scan 0 sort 0} +do_test where7-2.141.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR b=641 + OR ((a BETWEEN 36 AND 38) AND a!=37) + } +} {1 15 27 36 38 41 53 67 79 93 scan 0 sort 0} +do_test where7-2.141.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR b=641 + OR ((a BETWEEN 36 AND 38) AND a!=37) + } +} {1 15 27 36 38 41 53 67 79 93 scan 0 sort 0} +do_test where7-2.142.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=30030 + OR a=18 + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR b=11 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR a=52 + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR a=13 + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + } +} {1 13 18 22 40 44 46 52 65 88 89 90 scan 0 sort 0} +do_test where7-2.142.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=30030 + OR a=18 + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR b=11 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR a=52 + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR a=13 + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + } +} {1 13 18 22 40 44 46 52 65 88 89 90 scan 0 sort 0} +do_test where7-2.143.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=23023 + OR f='efghijklm' + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR b=1045 + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR f='uvwxyzabc' + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + } +} {4 20 24 30 39 41 46 50 56 67 68 69 72 76 82 95 98 scan 0 sort 0} +do_test where7-2.143.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=23023 + OR f='efghijklm' + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR b=1045 + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR f='uvwxyzabc' + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + } +} {4 20 24 30 39 41 46 50 56 67 68 69 72 76 82 95 98 scan 0 sort 0} +do_test where7-2.144.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=476 + OR a=11 + OR a=52 + OR b=858 + OR b=264 + OR f='wxyzabcde' + OR c=18018 + OR b=597 + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + } +} {11 22 24 48 52 53 54 69 74 78 100 scan 0 sort 0} +do_test where7-2.144.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=476 + OR a=11 + OR a=52 + OR b=858 + OR b=264 + OR f='wxyzabcde' + OR c=18018 + OR b=597 + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + } +} {11 22 24 48 52 53 54 69 74 78 100 scan 0 sort 0} +do_test where7-2.145.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=91 + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + OR b=102 + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR b=784 + } +} {12 21 22 36 59 61 85 89 91 scan 0 sort 0} +do_test where7-2.145.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=91 + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + OR b=102 + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR b=784 + } +} {12 21 22 36 59 61 85 89 91 scan 0 sort 0} +do_test where7-2.146.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='vutsrqp' AND f GLOB 'opqrs*') + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR b=990 + OR a=52 + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + } +} {14 38 52 90 91 scan 0 sort 0} +do_test where7-2.146.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='vutsrqp' AND f GLOB 'opqrs*') + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR b=990 + OR a=52 + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + } +} {14 38 52 90 91 scan 0 sort 0} +do_test where7-2.147.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=22022 + OR b=960 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR a=48 + OR b=729 + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR a=44 + OR b=773 + } +} {41 43 44 45 48 64 65 66 scan 0 sort 0} +do_test where7-2.147.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=22022 + OR b=960 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR a=48 + OR b=729 + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR a=44 + OR b=773 + } +} {41 43 44 45 48 64 65 66 scan 0 sort 0} +do_test where7-2.148.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 68 AND 70) AND a!=69) + OR b=421 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'defgh*') + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR c=22022 + OR b=825 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + } +} {2 6 17 19 22 24 29 32 58 64 65 66 68 70 75 84 89 scan 0 sort 0} +do_test where7-2.148.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 68 AND 70) AND a!=69) + OR b=421 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'defgh*') + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR c=22022 + OR b=825 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + } +} {2 6 17 19 22 24 29 32 58 64 65 66 68 70 75 84 89 scan 0 sort 0} +do_test where7-2.149.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=44.0 AND d<45.0 AND d NOT NULL) + OR b=484 + OR b=1026 + OR a=90 + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR b=608 + OR a=32 + } +} {32 44 74 90 scan 0 sort 0} +do_test where7-2.149.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=44.0 AND d<45.0 AND d NOT NULL) + OR b=484 + OR b=1026 + OR a=90 + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR b=608 + OR a=32 + } +} {32 44 74 90 scan 0 sort 0} +do_test where7-2.150.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c<=10 + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR b=154 + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR b=880 + OR a=55 + OR b=773 + OR b=319 + OR (g='hgfedcb' AND f GLOB 'fghij*') + } +} {14 29 55 76 77 80 83 scan 0 sort 0} +do_test where7-2.150.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c<=10 + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR b=154 + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR b=880 + OR a=55 + OR b=773 + OR b=319 + OR (g='hgfedcb' AND f GLOB 'fghij*') + } +} {14 29 55 76 77 80 83 scan 0 sort 0} +do_test where7-2.151.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='wvutsrq' AND f GLOB 'ijklm*') + OR f='mnopqrstu' + OR a=62 + } +} {8 12 38 62 64 90 scan 0 sort 0} +do_test where7-2.151.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='wvutsrq' AND f GLOB 'ijklm*') + OR f='mnopqrstu' + OR a=62 + } +} {8 12 38 62 64 90 scan 0 sort 0} +do_test where7-2.152.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=33 + OR b=1045 + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR c=13013 + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR b=124 + OR (g='gfedcba' AND f GLOB 'klmno*') + } +} {33 37 38 39 40 88 90 95 scan 0 sort 0} +do_test where7-2.152.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=33 + OR b=1045 + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR c=13013 + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR b=124 + OR (g='gfedcba' AND f GLOB 'klmno*') + } +} {33 37 38 39 40 88 90 95 scan 0 sort 0} +do_test where7-2.153.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=883 + OR c=32032 + OR f='fghijklmn' + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR b=421 + OR b=803 + OR c=4004 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + } +} {2 5 10 11 12 28 31 49 51 54 57 73 80 83 94 95 96 scan 0 sort 0} +do_test where7-2.153.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=883 + OR c=32032 + OR f='fghijklmn' + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR b=421 + OR b=803 + OR c=4004 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + } +} {2 5 10 11 12 28 31 49 51 54 57 73 80 83 94 95 96 scan 0 sort 0} +do_test where7-2.154.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR b=99 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {9 16 42 68 72 94 scan 0 sort 0} +do_test where7-2.154.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR b=99 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {9 16 42 68 72 94 scan 0 sort 0} +do_test where7-2.155.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='defghijkl' + OR b=308 + } +} {3 28 29 55 81 scan 0 sort 0} +do_test where7-2.155.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='defghijkl' + OR b=308 + } +} {3 28 29 55 81 scan 0 sort 0} +do_test where7-2.156.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=795 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR f='jklmnopqr' + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR b=1056 + } +} {2 9 28 35 51 54 61 80 87 96 scan 0 sort 0} +do_test where7-2.156.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=795 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR f='jklmnopqr' + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR b=1056 + } +} {2 9 28 35 51 54 61 80 87 96 scan 0 sort 0} +do_test where7-2.157.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=47 + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=410 + OR b=682 + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR f='hijklmnop' + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=168 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR a=32 + OR a=72 + } +} {7 32 33 40 47 51 59 62 72 85 94 98 100 scan 0 sort 0} +do_test where7-2.157.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=47 + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=410 + OR b=682 + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR f='hijklmnop' + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=168 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR a=32 + OR a=72 + } +} {7 32 33 40 47 51 59 62 72 85 94 98 100 scan 0 sort 0} +do_test where7-2.158.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=616 + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR a=96 + } +} {25 27 38 56 96 scan 0 sort 0} +do_test where7-2.158.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=616 + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR a=96 + } +} {25 27 38 56 96 scan 0 sort 0} +do_test where7-2.159.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=352 + } +} {32 66 scan 0 sort 0} +do_test where7-2.159.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=352 + } +} {32 66 scan 0 sort 0} +do_test where7-2.160.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=795 + OR c=13013 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=597 + } +} {28 37 38 39 scan 0 sort 0} +do_test where7-2.160.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=795 + OR c=13013 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=597 + } +} {28 37 38 39 scan 0 sort 0} +do_test where7-2.161.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=23 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR b=641 + OR b=352 + OR b=179 + OR b=806 + OR b=839 + OR b=33 + } +} {3 23 32 68 scan 0 sort 0} +do_test where7-2.161.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=23 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR b=641 + OR b=352 + OR b=179 + OR b=806 + OR b=839 + OR b=33 + } +} {3 23 32 68 scan 0 sort 0} +do_test where7-2.162.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1070 + OR b=1078 + OR ((a BETWEEN 11 AND 13) AND a!=12) + OR c=12012 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR b=319 + OR c=5005 + OR 1000000=59.0 AND d<60.0 AND d NOT NULL) + } +} {2 17 28 43 54 59 69 80 81 95 scan 0 sort 0} +do_test where7-2.163.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='cdefghijk' + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR (d>=59.0 AND d<60.0 AND d NOT NULL) + } +} {2 17 28 43 54 59 69 80 81 95 scan 0 sort 0} +do_test where7-2.164.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=65 + OR c=14014 + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR a=47 + OR b=220 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + } +} {20 37 40 41 42 47 65 88 scan 0 sort 0} +do_test where7-2.164.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=65 + OR c=14014 + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR a=47 + OR b=220 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + } +} {20 37 40 41 42 47 65 88 scan 0 sort 0} +do_test where7-2.165.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'ijklm*') + OR (g='rqponml' AND f GLOB 'jklmn*') + OR b=891 + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR b=484 + OR a=62 + OR (g='ihgfedc' AND f GLOB 'defgh*') + } +} {35 44 57 62 81 86 scan 0 sort 0} +do_test where7-2.165.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'ijklm*') + OR (g='rqponml' AND f GLOB 'jklmn*') + OR b=891 + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR b=484 + OR a=62 + OR (g='ihgfedc' AND f GLOB 'defgh*') + } +} {35 44 57 62 81 86 scan 0 sort 0} +do_test where7-2.166.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=363 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR a=39 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + } +} {2 10 25 33 39 46 54 58 60 scan 0 sort 0} +do_test where7-2.166.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=363 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR a=39 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + } +} {2 10 25 33 39 46 54 58 60 scan 0 sort 0} +do_test where7-2.167.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=30030 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR b=850 + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + } +} {20 46 52 72 88 89 90 98 scan 0 sort 0} +do_test where7-2.167.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=30030 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR b=850 + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + } +} {20 46 52 72 88 89 90 98 scan 0 sort 0} +do_test where7-2.168.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR b=80 + } +} {23 91 scan 0 sort 0} +do_test where7-2.168.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR b=80 + } +} {23 91 scan 0 sort 0} +do_test where7-2.169.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 59 AND 61) AND a!=60) + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR b=462 + OR a=51 + OR b=344 + OR b=333 + OR ((a BETWEEN 61 AND 63) AND a!=62) + } +} {42 51 59 61 63 77 scan 0 sort 0} +do_test where7-2.169.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 59 AND 61) AND a!=60) + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR b=462 + OR a=51 + OR b=344 + OR b=333 + OR ((a BETWEEN 61 AND 63) AND a!=62) + } +} {42 51 59 61 63 77 scan 0 sort 0} +do_test where7-2.170.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=586 + OR a=21 + OR b=638 + } +} {21 58 scan 0 sort 0} +do_test where7-2.170.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=586 + OR a=21 + OR b=638 + } +} {21 58 scan 0 sort 0} +do_test where7-2.171.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=179 + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR ((a BETWEEN 72 AND 74) AND a!=73) + } +} {2 4 13 40 42 72 74 scan 0 sort 0} +do_test where7-2.171.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=179 + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR ((a BETWEEN 72 AND 74) AND a!=73) + } +} {2 4 13 40 42 72 74 scan 0 sort 0} +do_test where7-2.172.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=333 + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR b=407 + OR a=5 + OR b=817 + OR b=891 + } +} {5 37 53 62 81 scan 0 sort 0} +do_test where7-2.172.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=333 + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR b=407 + OR a=5 + OR b=817 + OR b=891 + } +} {5 37 53 62 81 scan 0 sort 0} +do_test where7-2.173.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b<0 + OR b=352 + OR b=517 + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR b=1012 + OR ((a BETWEEN 11 AND 13) AND a!=12) + } +} {11 12 13 14 32 47 92 97 scan 0 sort 0} +do_test where7-2.173.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b<0 + OR b=352 + OR b=517 + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR b=1012 + OR ((a BETWEEN 11 AND 13) AND a!=12) + } +} {11 12 13 14 32 47 92 97 scan 0 sort 0} +do_test where7-2.174.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'pqrst*') + OR c<=10 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR a=32 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR d<0.0 + } +} {12 14 32 41 scan 0 sort 0} +do_test where7-2.174.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'pqrst*') + OR c<=10 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR a=32 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR d<0.0 + } +} {12 14 32 41 scan 0 sort 0} +do_test where7-2.175.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 20 AND 22) AND a!=21) + OR b=1045 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR a=26 + OR (g='gfedcba' AND f GLOB 'opqrs*') + } +} {20 22 26 78 92 95 scan 0 sort 0} +do_test where7-2.175.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 20 AND 22) AND a!=21) + OR b=1045 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR a=26 + OR (g='gfedcba' AND f GLOB 'opqrs*') + } +} {20 22 26 78 92 95 scan 0 sort 0} +do_test where7-2.176.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=49 + OR b=58 + } +} {49 scan 0 sort 0} +do_test where7-2.176.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=49 + OR b=58 + } +} {49 scan 0 sort 0} +do_test where7-2.177.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=3.0 AND d<4.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'xyzab*') + OR c=32032 + OR b=289 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {3 14 16 17 19 75 94 95 96 scan 0 sort 0} +do_test where7-2.177.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=3.0 AND d<4.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'xyzab*') + OR c=32032 + OR b=289 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {3 14 16 17 19 75 94 95 96 scan 0 sort 0} +do_test where7-2.178.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 15 AND 17) AND a!=16) + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR b=33 + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + } +} {3 15 17 43 57 59 69 95 scan 0 sort 0} +do_test where7-2.178.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 15 AND 17) AND a!=16) + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR b=33 + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + } +} {3 15 17 43 57 59 69 95 scan 0 sort 0} +do_test where7-2.179.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=828 + OR b=341 + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR b=902 + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=242 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR (g='qponmlk' AND f GLOB 'qrstu*') + } +} {1 2 16 22 31 42 64 66 68 82 91 94 95 scan 0 sort 0} +do_test where7-2.179.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=828 + OR b=341 + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR b=902 + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=242 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR (g='qponmlk' AND f GLOB 'qrstu*') + } +} {1 2 16 22 31 42 64 66 68 82 91 94 95 scan 0 sort 0} +do_test where7-2.180.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='nmlkjih' AND f GLOB 'efghi*') + OR b=982 + OR b=781 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR d>1e10 + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + } +} {56 66 68 71 scan 0 sort 0} +do_test where7-2.180.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='nmlkjih' AND f GLOB 'efghi*') + OR b=982 + OR b=781 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR d>1e10 + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + } +} {56 66 68 71 scan 0 sort 0} +do_test where7-2.181.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'rstuv*') + OR a=31 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR a=76 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR b=176 + } +} {8 16 23 31 34 57 59 60 69 74 76 86 scan 0 sort 0} +do_test where7-2.181.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'rstuv*') + OR a=31 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR a=76 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR b=176 + } +} {8 16 23 31 34 57 59 60 69 74 76 86 scan 0 sort 0} +do_test where7-2.182.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ponmlkj' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=14 + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR f='zabcdefgh' + } +} {12 25 47 51 55 59 60 61 77 88 90 scan 0 sort 0} +do_test where7-2.182.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ponmlkj' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=14 + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR f='zabcdefgh' + } +} {12 25 47 51 55 59 60 61 77 88 90 scan 0 sort 0} +do_test where7-2.183.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='tsrqpon' AND f GLOB 'zabcd*') + OR b=286 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR b=91 + OR ((a BETWEEN 43 AND 45) AND a!=44) + } +} {25 26 31 43 45 scan 0 sort 0} +do_test where7-2.183.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='tsrqpon' AND f GLOB 'zabcd*') + OR b=286 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR b=91 + OR ((a BETWEEN 43 AND 45) AND a!=44) + } +} {25 26 31 43 45 scan 0 sort 0} +do_test where7-2.184.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='lkjihgf' AND f GLOB 'nopqr*') + OR c=19019 + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR b=374 + } +} {22 34 48 55 56 57 65 74 100 scan 0 sort 0} +do_test where7-2.184.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='lkjihgf' AND f GLOB 'nopqr*') + OR c=19019 + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR b=374 + } +} {22 34 48 55 56 57 65 74 100 scan 0 sort 0} +do_test where7-2.185.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE g IS NULL + OR (g='onmlkji' AND f GLOB 'wxyza*') + } +} {48 scan 0 sort 0} +do_test where7-2.185.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE g IS NULL + OR (g='onmlkji' AND f GLOB 'wxyza*') + } +} {48 scan 0 sort 0} +do_test where7-2.186.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=4 + OR b=407 + } +} {4 37 scan 0 sort 0} +do_test where7-2.186.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=4 + OR b=407 + } +} {4 37 scan 0 sort 0} +do_test where7-2.187.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 66 AND 68) AND a!=67) + OR b=564 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR b=234 + OR b=641 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR a=98 + } +} {1 5 12 13 27 39 53 65 66 68 79 91 98 scan 0 sort 0} +do_test where7-2.187.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 66 AND 68) AND a!=67) + OR b=564 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR b=234 + OR b=641 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR a=98 + } +} {1 5 12 13 27 39 53 65 66 68 79 91 98 scan 0 sort 0} +do_test where7-2.188.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=73 + OR b=44 + OR b=539 + OR c=11011 + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=69 + OR b=1001 + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR ((a BETWEEN 32 AND 34) AND a!=33) + } +} {4 23 26 31 32 33 34 49 73 81 91 95 scan 0 sort 0} +do_test where7-2.188.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=73 + OR b=44 + OR b=539 + OR c=11011 + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=69 + OR b=1001 + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR ((a BETWEEN 32 AND 34) AND a!=33) + } +} {4 23 26 31 32 33 34 49 73 81 91 95 scan 0 sort 0} +do_test where7-2.189.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=264 + OR b=143 + OR a=48 + } +} {13 24 48 scan 0 sort 0} +do_test where7-2.189.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=264 + OR b=143 + OR a=48 + } +} {13 24 48 scan 0 sort 0} +do_test where7-2.190.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1001 + OR b=1070 + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR b=14 + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR a=66 + } +} {18 56 58 66 72 74 91 scan 0 sort 0} +do_test where7-2.190.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1001 + OR b=1070 + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR b=14 + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR a=66 + } +} {18 56 58 66 72 74 91 scan 0 sort 0} +do_test where7-2.191.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=23023 + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + OR a=66 + OR (g='onmlkji' AND f GLOB 'zabcd*') + OR a=51 + OR a=23 + OR c=4004 + } +} {10 11 12 23 51 66 67 68 69 83 scan 0 sort 0} +do_test where7-2.191.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=23023 + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + OR a=66 + OR (g='onmlkji' AND f GLOB 'zabcd*') + OR a=51 + OR a=23 + OR c=4004 + } +} {10 11 12 23 51 66 67 68 69 83 scan 0 sort 0} +do_test where7-2.192.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=36 + OR (g='rqponml' AND f GLOB 'lmnop*') + OR a=80 + } +} {37 80 scan 0 sort 0} +do_test where7-2.192.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=36 + OR (g='rqponml' AND f GLOB 'lmnop*') + OR a=80 + } +} {37 80 scan 0 sort 0} +do_test where7-2.193.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR a=55 + OR f='efghijklm' + OR a=8 + OR a=80 + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR b=256 + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + } +} {4 8 30 34 37 39 55 56 60 72 80 82 86 scan 0 sort 0} +do_test where7-2.193.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR a=55 + OR f='efghijklm' + OR a=8 + OR a=80 + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR b=256 + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + } +} {4 8 30 34 37 39 55 56 60 72 80 82 86 scan 0 sort 0} +do_test where7-2.194.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=836 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR a=91 + OR b=594 + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + } +} {2 8 28 47 54 76 80 87 91 scan 0 sort 0} +do_test where7-2.194.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=836 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR a=91 + OR b=594 + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + } +} {2 8 28 47 54 76 80 87 91 scan 0 sort 0} +do_test where7-2.195.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='tsrqpon' AND f GLOB 'yzabc*') + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 62 AND 64) AND a!=63) + OR c=6006 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + } +} {12 16 17 18 24 43 50 52 62 64 88 90 scan 0 sort 0} +do_test where7-2.195.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='tsrqpon' AND f GLOB 'yzabc*') + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 62 AND 64) AND a!=63) + OR c=6006 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + } +} {12 16 17 18 24 43 50 52 62 64 88 90 scan 0 sort 0} +do_test where7-2.196.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 83 AND 85) AND a!=84) + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR a=13 + OR b=121 + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR b=660 + OR b=792 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + } +} {6 11 12 13 14 16 18 44 60 72 83 85 scan 0 sort 0} +do_test where7-2.196.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 83 AND 85) AND a!=84) + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR a=13 + OR b=121 + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR b=660 + OR b=792 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + } +} {6 11 12 13 14 16 18 44 60 72 83 85 scan 0 sort 0} +do_test where7-2.197.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1089 + OR b=495 + OR b=157 + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + OR (d>=59.0 AND d<60.0 AND d NOT NULL) + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR (g='xwvutsr' AND f GLOB 'hijkl*') + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR f='wxyzabcde' + } +} {1 7 20 22 45 46 48 59 72 74 98 99 100 scan 0 sort 0} +do_test where7-2.197.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1089 + OR b=495 + OR b=157 + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + OR (d>=59.0 AND d<60.0 AND d NOT NULL) + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR (g='xwvutsr' AND f GLOB 'hijkl*') + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR f='wxyzabcde' + } +} {1 7 20 22 45 46 48 59 72 74 98 99 100 scan 0 sort 0} +do_test where7-2.198.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='bcdefghij' + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (g='srqponm' AND f GLOB 'ghijk*') + OR b=157 + OR b=267 + OR c=34034 + } +} {1 27 32 40 42 53 79 100 scan 0 sort 0} +do_test where7-2.198.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='bcdefghij' + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (g='srqponm' AND f GLOB 'ghijk*') + OR b=157 + OR b=267 + OR c=34034 + } +} {1 27 32 40 42 53 79 100 scan 0 sort 0} +do_test where7-2.199.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=19 + OR a=23 + OR c<=10 + OR (g='lkjihgf' AND f GLOB 'opqrs*') + } +} {19 23 66 scan 0 sort 0} +do_test where7-2.199.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=19 + OR a=23 + OR c<=10 + OR (g='lkjihgf' AND f GLOB 'opqrs*') + } +} {19 23 66 scan 0 sort 0} +do_test where7-2.200.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 1 AND 3) AND a!=2) + OR b=792 + OR b=803 + OR b=36 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + } +} {1 3 27 53 72 73 79 scan 0 sort 0} +do_test where7-2.200.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 1 AND 3) AND a!=2) + OR b=792 + OR b=803 + OR b=36 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + } +} {1 3 27 53 72 73 79 scan 0 sort 0} +do_test where7-2.201.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='utsrqpo' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 71 AND 73) AND a!=72) + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR f='jklmnopqr' + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR b=891 + OR a=40 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + } +} {9 20 35 40 50 61 67 71 73 76 78 81 87 scan 0 sort 0} +do_test where7-2.201.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='utsrqpo' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 71 AND 73) AND a!=72) + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR f='jklmnopqr' + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR b=891 + OR a=40 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + } +} {9 20 35 40 50 61 67 71 73 76 78 81 87 scan 0 sort 0} +do_test where7-2.202.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=15.0 AND d<16.0 AND d NOT NULL) + OR a=32 + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR a=95 + OR d>1e10 + OR b=429 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR c=10010 + OR ((a BETWEEN 83 AND 85) AND a!=84) + } +} {15 28 29 30 32 39 54 76 83 85 88 95 scan 0 sort 0} +do_test where7-2.202.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=15.0 AND d<16.0 AND d NOT NULL) + OR a=32 + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR a=95 + OR d>1e10 + OR b=429 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR c=10010 + OR ((a BETWEEN 83 AND 85) AND a!=84) + } +} {15 28 29 30 32 39 54 76 83 85 88 95 scan 0 sort 0} +do_test where7-2.203.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'defgh*') + OR a=22 + OR a=26 + OR a=81 + OR a=53 + OR ((a BETWEEN 92 AND 94) AND a!=93) + OR c=30030 + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR a=82 + OR b=594 + } +} {3 8 22 26 53 54 81 82 88 89 90 92 94 scan 0 sort 0} +do_test where7-2.203.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'defgh*') + OR a=22 + OR a=26 + OR a=81 + OR a=53 + OR ((a BETWEEN 92 AND 94) AND a!=93) + OR c=30030 + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR a=82 + OR b=594 + } +} {3 8 22 26 53 54 81 82 88 89 90 92 94 scan 0 sort 0} +do_test where7-2.204.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 34 AND 36) AND a!=35) + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'efghi*') + OR a=83 + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR ((a BETWEEN 99 AND 101) AND a!=100) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=1092 + OR (g='srqponm' AND f GLOB 'efghi*') + OR b=25 + } +} {12 30 34 36 57 68 83 86 99 scan 0 sort 0} +do_test where7-2.204.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 34 AND 36) AND a!=35) + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'efghi*') + OR a=83 + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR ((a BETWEEN 99 AND 101) AND a!=100) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=1092 + OR (g='srqponm' AND f GLOB 'efghi*') + OR b=25 + } +} {12 30 34 36 57 68 83 86 99 scan 0 sort 0} +do_test where7-2.205.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=20 + OR b=421 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR a=50 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + } +} {5 20 40 50 53 scan 0 sort 0} +do_test where7-2.205.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=20 + OR b=421 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR a=50 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + } +} {5 20 40 50 53 scan 0 sort 0} +do_test where7-2.206.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=960 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + } +} {13 39 65 91 scan 0 sort 0} +do_test where7-2.206.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=960 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + } +} {13 39 65 91 scan 0 sort 0} +do_test where7-2.207.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=891 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR f='nopqrstuv' + } +} {13 31 39 65 81 91 scan 0 sort 0} +do_test where7-2.207.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=891 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR f='nopqrstuv' + } +} {13 31 39 65 81 91 scan 0 sort 0} +do_test where7-2.208.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=157 + OR b=289 + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=1001 + OR b=707 + } +} {32 34 91 scan 0 sort 0} +do_test where7-2.208.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=157 + OR b=289 + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=1001 + OR b=707 + } +} {32 34 91 scan 0 sort 0} +do_test where7-2.209.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='edcbazy' AND f GLOB 'wxyza*') + OR b=957 + OR ((a BETWEEN 48 AND 50) AND a!=49) + } +} {48 50 87 100 scan 0 sort 0} +do_test where7-2.209.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='edcbazy' AND f GLOB 'wxyza*') + OR b=957 + OR ((a BETWEEN 48 AND 50) AND a!=49) + } +} {48 50 87 100 scan 0 sort 0} +do_test where7-2.210.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=40.0 AND d<41.0 AND d NOT NULL) + OR a=77 + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + } +} {40 77 85 scan 0 sort 0} +do_test where7-2.210.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=40.0 AND d<41.0 AND d NOT NULL) + OR a=77 + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + } +} {40 77 85 scan 0 sort 0} +do_test where7-2.211.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=11 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR a=99 + } +} {1 14 16 38 66 96 99 scan 0 sort 0} +do_test where7-2.211.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=11 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR a=99 + } +} {1 14 16 38 66 96 99 scan 0 sort 0} +do_test where7-2.212.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='fghijklmn' + OR a=16 + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=80 + } +} {3 5 9 11 16 31 52 57 60 62 71 83 90 92 scan 0 sort 0} +do_test where7-2.212.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='fghijklmn' + OR a=16 + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=80 + } +} {3 5 9 11 16 31 52 57 60 62 71 83 90 92 scan 0 sort 0} +do_test where7-2.213.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='wvutsrq' AND f GLOB 'mnopq*') + OR a=44 + OR a=43 + OR (g='lkjihgf' AND f GLOB 'opqrs*') + OR b=25 + } +} {12 43 44 66 scan 0 sort 0} +do_test where7-2.213.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='wvutsrq' AND f GLOB 'mnopq*') + OR a=44 + OR a=43 + OR (g='lkjihgf' AND f GLOB 'opqrs*') + OR b=25 + } +} {12 43 44 66 scan 0 sort 0} +do_test where7-2.214.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='vwxyzabcd' + OR a=73 + OR b=597 + } +} {21 47 73 99 scan 0 sort 0} +do_test where7-2.214.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='vwxyzabcd' + OR a=73 + OR b=597 + } +} {21 47 73 99 scan 0 sort 0} +do_test where7-2.215.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=22 + OR ((a BETWEEN 61 AND 63) AND a!=62) + OR e IS NULL + OR a=1 + } +} {1 2 61 63 scan 0 sort 0} +do_test where7-2.215.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=22 + OR ((a BETWEEN 61 AND 63) AND a!=62) + OR e IS NULL + OR a=1 + } +} {1 2 61 63 scan 0 sort 0} +do_test where7-2.216.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=3.0 AND d<4.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'opqrs*') + OR b=1015 + OR c=16016 + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR f='abcdefghi' + OR b=605 + OR a=63 + } +} {3 19 26 45 46 47 48 52 55 63 71 78 92 97 scan 0 sort 0} +do_test where7-2.216.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=3.0 AND d<4.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'opqrs*') + OR b=1015 + OR c=16016 + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR f='abcdefghi' + OR b=605 + OR a=63 + } +} {3 19 26 45 46 47 48 52 55 63 71 78 92 97 scan 0 sort 0} +do_test where7-2.217.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='yxwvuts' AND f GLOB 'bcdef*') + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR b=641 + OR b=795 + } +} {1 44 scan 0 sort 0} +do_test where7-2.217.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='yxwvuts' AND f GLOB 'bcdef*') + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR b=641 + OR b=795 + } +} {1 44 scan 0 sort 0} +do_test where7-2.218.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='fghijklmn' + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + } +} {5 15 31 44 57 83 scan 0 sort 0} +do_test where7-2.218.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='fghijklmn' + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + } +} {5 15 31 44 57 83 scan 0 sort 0} +do_test where7-2.219.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 99 AND 101) AND a!=100) + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR a=92 + OR b=1100 + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR ((a BETWEEN 30 AND 32) AND a!=31) + } +} {30 32 72 74 85 87 92 98 99 100 scan 0 sort 0} +do_test where7-2.219.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 99 AND 101) AND a!=100) + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR a=92 + OR b=1100 + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR ((a BETWEEN 30 AND 32) AND a!=31) + } +} {30 32 72 74 85 87 92 98 99 100 scan 0 sort 0} +do_test where7-2.220.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=880 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR b=1089 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR f IS NULL + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + } +} {5 12 16 31 57 69 71 80 83 86 97 99 scan 0 sort 0} +do_test where7-2.220.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=880 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR b=1089 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR f IS NULL + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + } +} {5 12 16 31 57 69 71 80 83 86 97 99 scan 0 sort 0} +do_test where7-2.221.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1026 + OR b=407 + OR (g='srqponm' AND f GLOB 'fghij*') + OR b=564 + OR c=23023 + OR b=891 + OR c=22022 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR (g='rqponml' AND f GLOB 'ijklm*') + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + } +} {9 11 21 22 24 31 34 37 64 65 66 67 68 69 81 scan 0 sort 0} +do_test where7-2.221.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1026 + OR b=407 + OR (g='srqponm' AND f GLOB 'fghij*') + OR b=564 + OR c=23023 + OR b=891 + OR c=22022 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR (g='rqponml' AND f GLOB 'ijklm*') + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + } +} {9 11 21 22 24 31 34 37 64 65 66 67 68 69 81 scan 0 sort 0} +do_test where7-2.222.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR a=72 + OR a=43 + } +} {43 71 72 73 scan 0 sort 0} +do_test where7-2.222.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR a=72 + OR a=43 + } +} {43 71 72 73 scan 0 sort 0} +do_test where7-2.223.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 67 AND 69) AND a!=68) + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR c=18018 + OR b=792 + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR f='uvwxyzabc' + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + } +} {8 20 46 52 53 54 61 67 69 72 74 77 79 81 91 98 scan 0 sort 0} +do_test where7-2.223.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 67 AND 69) AND a!=68) + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR c=18018 + OR b=792 + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR f='uvwxyzabc' + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + } +} {8 20 46 52 53 54 61 67 69 72 74 77 79 81 91 98 scan 0 sort 0} +do_test where7-2.224.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=429 + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR b=1070 + OR (g='vutsrqp' AND f GLOB 'rstuv*') + } +} {4 17 30 33 39 40 56 82 scan 0 sort 0} +do_test where7-2.224.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=429 + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR b=1070 + OR (g='vutsrqp' AND f GLOB 'rstuv*') + } +} {4 17 30 33 39 40 56 82 scan 0 sort 0} +do_test where7-2.225.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=572 + } +} {52 61 scan 0 sort 0} +do_test where7-2.225.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=572 + } +} {52 61 scan 0 sort 0} +do_test where7-2.226.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 62 AND 64) AND a!=63) + OR f='abcdefghi' + OR (g='wvutsrq' AND f GLOB 'ijklm*') + } +} {8 26 52 62 64 78 scan 0 sort 0} +do_test where7-2.226.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 62 AND 64) AND a!=63) + OR f='abcdefghi' + OR (g='wvutsrq' AND f GLOB 'ijklm*') + } +} {8 26 52 62 64 78 scan 0 sort 0} +do_test where7-2.227.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=40 + OR ((a BETWEEN 85 AND 87) AND a!=86) + } +} {40 85 87 scan 0 sort 0} +do_test where7-2.227.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=40 + OR ((a BETWEEN 85 AND 87) AND a!=86) + } +} {40 85 87 scan 0 sort 0} +do_test where7-2.228.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=43 + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR a=1 + OR ((a BETWEEN 75 AND 77) AND a!=76) + OR a=75 + OR (g='hgfedcb' AND f GLOB 'fghij*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {1 43 44 46 59 61 75 77 83 scan 0 sort 0} +do_test where7-2.228.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=43 + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR a=1 + OR ((a BETWEEN 75 AND 77) AND a!=76) + OR a=75 + OR (g='hgfedcb' AND f GLOB 'fghij*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {1 43 44 46 59 61 75 77 83 scan 0 sort 0} +do_test where7-2.229.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='gfedcba' AND f GLOB 'nopqr*') + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR b=231 + OR a=87 + } +} {8 21 34 60 86 87 91 scan 0 sort 0} +do_test where7-2.229.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='gfedcba' AND f GLOB 'nopqr*') + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR b=231 + OR a=87 + } +} {8 21 34 60 86 87 91 scan 0 sort 0} +do_test where7-2.230.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=77 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR (g='rqponml' AND f GLOB 'hijkl*') + OR c=24024 + OR c=5005 + } +} {13 14 15 33 65 70 71 72 77 scan 0 sort 0} +do_test where7-2.230.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=77 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR (g='rqponml' AND f GLOB 'hijkl*') + OR c=24024 + OR c=5005 + } +} {13 14 15 33 65 70 71 72 77 scan 0 sort 0} +do_test where7-2.231.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='mlkjihg' AND f GLOB 'ijklm*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (g='srqponm' AND f GLOB 'defgh*') + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR b=682 + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + } +} {22 29 34 60 62 64 65 66 89 91 scan 0 sort 0} +do_test where7-2.231.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='mlkjihg' AND f GLOB 'ijklm*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (g='srqponm' AND f GLOB 'defgh*') + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR b=682 + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + } +} {22 29 34 60 62 64 65 66 89 91 scan 0 sort 0} +do_test where7-2.232.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=212 + OR b=121 + OR c=2002 + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR (g='jihgfed' AND f GLOB 'xyzab*') + } +} {4 5 6 11 75 84 86 scan 0 sort 0} +do_test where7-2.232.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=212 + OR b=121 + OR c=2002 + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR (g='jihgfed' AND f GLOB 'xyzab*') + } +} {4 5 6 11 75 84 86 scan 0 sort 0} +do_test where7-2.233.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=55.0 AND d<56.0 AND d NOT NULL) + OR f='abcdefghi' + OR b=267 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR a=82 + OR a=54 + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=1078 + } +} {16 20 26 52 54 55 78 82 98 scan 0 sort 0} +do_test where7-2.233.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=55.0 AND d<56.0 AND d NOT NULL) + OR f='abcdefghi' + OR b=267 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR a=82 + OR a=54 + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=1078 + } +} {16 20 26 52 54 55 78 82 98 scan 0 sort 0} +do_test where7-2.234.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=93.0 AND d<94.0 AND d NOT NULL) + OR f='hijklmnop' + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + } +} {7 33 34 59 85 93 scan 0 sort 0} +do_test where7-2.234.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=93.0 AND d<94.0 AND d NOT NULL) + OR f='hijklmnop' + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + } +} {7 33 34 59 85 93 scan 0 sort 0} +do_test where7-2.235.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 98 AND 100) AND a!=99) + OR ((a BETWEEN 51 AND 53) AND a!=52) + OR a=18 + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR 1000000=94.0 AND d<95.0 AND d NOT NULL) + OR 1000000=89.0 AND d<90.0 AND d NOT NULL) + } +} {7 33 59 85 89 91 scan 0 sort 0} +do_test where7-2.236.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1001 + OR b=168 + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + } +} {7 33 59 85 89 91 scan 0 sort 0} +do_test where7-2.237.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=51 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR b=330 + } +} {30 51 96 98 scan 0 sort 0} +do_test where7-2.237.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=51 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR b=330 + } +} {30 51 96 98 scan 0 sort 0} +do_test where7-2.238.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=704 + OR a=62 + OR f='pqrstuvwx' + OR b=495 + OR c=26026 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR b<0 + OR b=597 + } +} {15 41 45 62 64 67 68 71 76 77 78 93 scan 0 sort 0} +do_test where7-2.238.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=704 + OR a=62 + OR f='pqrstuvwx' + OR b=495 + OR c=26026 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR b<0 + OR b=597 + } +} {15 41 45 62 64 67 68 71 76 77 78 93 scan 0 sort 0} +do_test where7-2.239.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=2.0 AND d<3.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR b=520 + OR ((a BETWEEN 47 AND 49) AND a!=48) + OR f IS NULL + } +} {2 47 49 87 89 scan 0 sort 0} +do_test where7-2.239.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=2.0 AND d<3.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR b=520 + OR ((a BETWEEN 47 AND 49) AND a!=48) + OR f IS NULL + } +} {2 47 49 87 89 scan 0 sort 0} +do_test where7-2.240.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=14014 + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=572 + OR c=15015 + } +} {40 41 42 43 44 45 52 95 scan 0 sort 0} +do_test where7-2.240.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=14014 + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=572 + OR c=15015 + } +} {40 41 42 43 44 45 52 95 scan 0 sort 0} +do_test where7-2.241.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?efgh*' AND f GLOB 'defg*') + OR b=850 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR b=88 + OR f='hijklmnop' + OR b=806 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=88 + } +} {3 7 8 15 17 29 33 46 55 59 65 81 85 scan 0 sort 0} +do_test where7-2.241.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?efgh*' AND f GLOB 'defg*') + OR b=850 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR b=88 + OR f='hijklmnop' + OR b=806 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=88 + } +} {3 7 8 15 17 29 33 46 55 59 65 81 85 scan 0 sort 0} +do_test where7-2.242.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=817 + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR a=36 + OR b=960 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR b=374 + OR b=938 + OR b=773 + OR (g='jihgfed' AND f GLOB 'zabcd*') + OR (g='mlkjihg' AND f GLOB 'ghijk*') + } +} {34 36 55 58 63 77 scan 0 sort 0} +do_test where7-2.242.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=817 + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR a=36 + OR b=960 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR b=374 + OR b=938 + OR b=773 + OR (g='jihgfed' AND f GLOB 'zabcd*') + OR (g='mlkjihg' AND f GLOB 'ghijk*') + } +} {34 36 55 58 63 77 scan 0 sort 0} +do_test where7-2.243.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=146 + } +} {69 scan 0 sort 0} +do_test where7-2.243.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=146 + } +} {69 scan 0 sort 0} +do_test where7-2.244.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='pqrstuvwx' + OR ((a BETWEEN 6 AND 8) AND a!=7) + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR b=704 + OR a=18 + } +} {6 8 15 18 41 64 67 76 78 93 scan 0 sort 0} +do_test where7-2.244.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='pqrstuvwx' + OR ((a BETWEEN 6 AND 8) AND a!=7) + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR b=704 + OR a=18 + } +} {6 8 15 18 41 64 67 76 78 93 scan 0 sort 0} +do_test where7-2.245.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR b=399 + OR b=1004 + OR c=16016 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR b=671 + OR a=25 + OR a=30 + OR a=8 + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + } +} {5 8 19 25 30 31 45 46 47 48 61 71 97 scan 0 sort 0} +do_test where7-2.245.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR b=399 + OR b=1004 + OR c=16016 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR b=671 + OR a=25 + OR a=30 + OR a=8 + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + } +} {5 8 19 25 30 31 45 46 47 48 61 71 97 scan 0 sort 0} +do_test where7-2.246.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=561 + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR b=594 + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR b=861 + OR (d>=90.0 AND d<91.0 AND d NOT NULL) + OR b=949 + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR (g='nmlkjih' AND f GLOB 'cdefg*') + } +} {18 28 30 39 41 51 54 90 scan 0 sort 0} +do_test where7-2.246.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=561 + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR b=594 + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR b=861 + OR (d>=90.0 AND d<91.0 AND d NOT NULL) + OR b=949 + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR (g='nmlkjih' AND f GLOB 'cdefg*') + } +} {18 28 30 39 41 51 54 90 scan 0 sort 0} +do_test where7-2.247.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'hijkl*') + OR a=83 + OR c=26026 + OR a=49 + OR a=57 + OR c=23023 + OR f='uvwxyzabc' + } +} {7 20 46 49 57 67 68 69 72 76 77 78 83 98 scan 0 sort 0} +do_test where7-2.247.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'hijkl*') + OR a=83 + OR c=26026 + OR a=49 + OR a=57 + OR c=23023 + OR f='uvwxyzabc' + } +} {7 20 46 49 57 67 68 69 72 76 77 78 83 98 scan 0 sort 0} +do_test where7-2.248.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE d>1e10 + OR b=355 + OR f='stuvwxyza' + OR b=22 + } +} {2 18 44 70 96 scan 0 sort 0} +do_test where7-2.248.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE d>1e10 + OR b=355 + OR f='stuvwxyza' + OR b=22 + } +} {2 18 44 70 96 scan 0 sort 0} +do_test where7-2.249.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=451 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + } +} {8 34 41 60 86 scan 0 sort 0} +do_test where7-2.249.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=451 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + } +} {8 34 41 60 86 scan 0 sort 0} +do_test where7-2.250.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=47 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + } +} {1 27 53 79 scan 0 sort 0} +do_test where7-2.250.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=47 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + } +} {1 27 53 79 scan 0 sort 0} +do_test where7-2.251.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1037 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=344 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + } +} {12 66 68 86 scan 0 sort 0} +do_test where7-2.251.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1037 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=344 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + } +} {12 66 68 86 scan 0 sort 0} +do_test where7-2.252.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=506 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR b=429 + OR b=275 + } +} {20 22 25 39 46 86 scan 0 sort 0} +do_test where7-2.252.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=506 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR b=429 + OR b=275 + } +} {20 22 25 39 46 86 scan 0 sort 0} +do_test where7-2.253.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 60 AND 62) AND a!=61) + OR a=28 + OR b=443 + OR b=363 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR a=60 + OR b=80 + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR b=616 + } +} {28 33 47 56 60 62 scan 0 sort 0} +do_test where7-2.253.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 60 AND 62) AND a!=61) + OR a=28 + OR b=443 + OR b=363 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR a=60 + OR b=80 + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR b=616 + } +} {28 33 47 56 60 62 scan 0 sort 0} +do_test where7-2.254.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=33.0 AND d<34.0 AND d NOT NULL) + OR b=660 + } +} {33 60 scan 0 sort 0} +do_test where7-2.254.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=33.0 AND d<34.0 AND d NOT NULL) + OR b=660 + } +} {33 60 scan 0 sort 0} +do_test where7-2.255.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'hijkl*') + OR a=43 + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR b=586 + OR c=17017 + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR a=87 + OR b=968 + } +} {7 21 43 47 49 50 51 64 66 73 87 88 99 scan 0 sort 0} +do_test where7-2.255.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'hijkl*') + OR a=43 + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR b=586 + OR c=17017 + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR a=87 + OR b=968 + } +} {7 21 43 47 49 50 51 64 66 73 87 88 99 scan 0 sort 0} +do_test where7-2.256.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='klmnopqrs' + OR b=982 + OR b=575 + OR b=110 + OR b=99 + } +} {9 10 36 62 88 scan 0 sort 0} +do_test where7-2.256.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='klmnopqrs' + OR b=982 + OR b=575 + OR b=110 + OR b=99 + } +} {9 10 36 62 88 scan 0 sort 0} +do_test where7-2.257.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='rqponml' AND f GLOB 'jklmn*') + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR c>=34035 + OR b=850 + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=924 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR b=355 + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + } +} {4 32 34 35 37 56 78 84 86 scan 0 sort 0} +do_test where7-2.257.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='rqponml' AND f GLOB 'jklmn*') + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR c>=34035 + OR b=850 + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=924 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR b=355 + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + } +} {4 32 34 35 37 56 78 84 86 scan 0 sort 0} +do_test where7-2.258.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=982 + OR ((a BETWEEN 81 AND 83) AND a!=82) + OR b=374 + } +} {34 46 81 83 scan 0 sort 0} +do_test where7-2.258.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=982 + OR ((a BETWEEN 81 AND 83) AND a!=82) + OR b=374 + } +} {34 46 81 83 scan 0 sort 0} +do_test where7-2.259.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 87 AND 89) AND a!=88) + OR b=814 + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + } +} {19 74 87 89 scan 0 sort 0} +do_test where7-2.259.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 87 AND 89) AND a!=88) + OR b=814 + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + } +} {19 74 87 89 scan 0 sort 0} +do_test where7-2.260.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'nopqr*') + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=993 + } +} {12 39 scan 0 sort 0} +do_test where7-2.260.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'nopqr*') + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=993 + } +} {12 39 scan 0 sort 0} +do_test where7-2.261.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=234 + OR a=22 + OR b=289 + OR b=795 + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR b=242 + OR a=59 + OR b=1045 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + } +} {8 22 59 91 95 scan 0 sort 0} +do_test where7-2.261.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=234 + OR a=22 + OR b=289 + OR b=795 + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR b=242 + OR a=59 + OR b=1045 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + } +} {8 22 59 91 95 scan 0 sort 0} +do_test where7-2.262.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=245 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR c=3003 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + OR ((a BETWEEN 71 AND 73) AND a!=72) + } +} {1 7 8 9 10 26 33 52 68 70 71 73 78 scan 0 sort 0} +do_test where7-2.262.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=245 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR c=3003 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + OR ((a BETWEEN 71 AND 73) AND a!=72) + } +} {1 7 8 9 10 26 33 52 68 70 71 73 78 scan 0 sort 0} +do_test where7-2.263.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'jklmn*') + OR b=220 + OR b=443 + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR a=62 + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR b=1023 + OR a=100 + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + } +} {18 20 44 55 62 70 87 93 96 97 100 scan 0 sort 0} +do_test where7-2.263.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'jklmn*') + OR b=220 + OR b=443 + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR a=62 + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR b=1023 + OR a=100 + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + } +} {18 20 44 55 62 70 87 93 96 97 100 scan 0 sort 0} +do_test where7-2.264.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=11011 + OR f='tuvwxyzab' + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR (g='hgfedcb' AND f GLOB 'ghijk*') + } +} {19 31 32 33 45 47 71 84 97 scan 0 sort 0} +do_test where7-2.264.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=11011 + OR f='tuvwxyzab' + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR (g='hgfedcb' AND f GLOB 'ghijk*') + } +} {19 31 32 33 45 47 71 84 97 scan 0 sort 0} +do_test where7-2.265.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 93 AND 95) AND a!=94) + OR a=79 + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + OR b=462 + } +} {39 42 79 93 95 scan 0 sort 0} +do_test where7-2.265.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 93 AND 95) AND a!=94) + OR a=79 + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + OR b=462 + } +} {39 42 79 93 95 scan 0 sort 0} +do_test where7-2.266.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=33.0 AND d<34.0 AND d NOT NULL) + OR b=146 + OR 1000000=33.0 AND d<34.0 AND d NOT NULL) + OR b=146 + OR 1000000=20.0 AND d<21.0 AND d NOT NULL) + OR ((a BETWEEN 62 AND 64) AND a!=63) + OR a=62 + OR b=619 + OR a=82 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR c=14014 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + } +} {20 28 40 41 42 43 62 64 67 82 85 scan 0 sort 0} +do_test where7-2.267.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=935 + OR b=473 + OR a=28 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR ((a BETWEEN 62 AND 64) AND a!=63) + OR a=62 + OR b=619 + OR a=82 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR c=14014 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + } +} {20 28 40 41 42 43 62 64 67 82 85 scan 0 sort 0} +do_test where7-2.268.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ponmlkj' AND f GLOB 'uvwxy*') + OR b=443 + OR b=33 + OR b=762 + OR b=575 + OR c=16016 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR b=1092 + } +} {3 40 41 43 46 47 48 72 scan 0 sort 0} +do_test where7-2.268.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ponmlkj' AND f GLOB 'uvwxy*') + OR b=443 + OR b=33 + OR b=762 + OR b=575 + OR c=16016 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR b=1092 + } +} {3 40 41 43 46 47 48 72 scan 0 sort 0} +do_test where7-2.269.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=806 + OR b=872 + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR f='uvwxyzabc' + OR b=748 + OR b=586 + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR (g='gfedcba' AND f GLOB 'klmno*') + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR b=891 + } +} {15 17 20 32 34 46 68 72 80 81 88 98 scan 0 sort 0} +do_test where7-2.269.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=806 + OR b=872 + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR f='uvwxyzabc' + OR b=748 + OR b=586 + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR (g='gfedcba' AND f GLOB 'klmno*') + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR b=891 + } +} {15 17 20 32 34 46 68 72 80 81 88 98 scan 0 sort 0} +do_test where7-2.270.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=693 + OR f='fghijklmn' + OR (g='rqponml' AND f GLOB 'hijkl*') + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR ((a BETWEEN 71 AND 73) AND a!=72) + OR a=96 + } +} {5 31 33 39 57 63 71 73 83 96 scan 0 sort 0} +do_test where7-2.270.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=693 + OR f='fghijklmn' + OR (g='rqponml' AND f GLOB 'hijkl*') + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR ((a BETWEEN 71 AND 73) AND a!=72) + OR a=96 + } +} {5 31 33 39 57 63 71 73 83 96 scan 0 sort 0} +do_test where7-2.271.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'ijklm*') + OR b=451 + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR a=84 + } +} {41 84 86 96 97 98 99 scan 0 sort 0} +do_test where7-2.271.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'ijklm*') + OR b=451 + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR a=84 + } +} {41 84 86 96 97 98 99 scan 0 sort 0} +do_test where7-2.272.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='nmlkjih' AND f GLOB 'bcdef*') + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR a=75 + OR b=960 + OR (g='tsrqpon' AND f GLOB 'yzabc*') + OR b=616 + OR b=330 + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR a=26 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {16 18 24 26 30 53 56 63 72 75 scan 0 sort 0} +do_test where7-2.272.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='nmlkjih' AND f GLOB 'bcdef*') + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR a=75 + OR b=960 + OR (g='tsrqpon' AND f GLOB 'yzabc*') + OR b=616 + OR b=330 + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR a=26 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {16 18 24 26 30 53 56 63 72 75 scan 0 sort 0} +do_test where7-2.273.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=762 + OR (g='nmlkjih' AND f GLOB 'bcdef*') + } +} {53 scan 0 sort 0} +do_test where7-2.273.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=762 + OR (g='nmlkjih' AND f GLOB 'bcdef*') + } +} {53 scan 0 sort 0} +do_test where7-2.274.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=14 + OR a=23 + OR b=748 + OR b=407 + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=979 + OR ((a BETWEEN 15 AND 17) AND a!=16) + } +} {4 15 17 23 37 68 87 89 scan 0 sort 0} +do_test where7-2.274.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=14 + OR a=23 + OR b=748 + OR b=407 + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=979 + OR ((a BETWEEN 15 AND 17) AND a!=16) + } +} {4 15 17 23 37 68 87 89 scan 0 sort 0} +do_test where7-2.275.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 36 AND 38) AND a!=37) + OR a=92 + } +} {36 38 92 scan 0 sort 0} +do_test where7-2.275.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 36 AND 38) AND a!=37) + OR a=92 + } +} {36 38 92 scan 0 sort 0} +do_test where7-2.276.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=14014 + OR b=927 + OR b=176 + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR b=220 + OR (g='tsrqpon' AND f GLOB 'yzabc*') + OR a=4 + } +} {4 16 20 24 34 36 40 41 42 scan 0 sort 0} +do_test where7-2.276.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=14014 + OR b=927 + OR b=176 + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR b=220 + OR (g='tsrqpon' AND f GLOB 'yzabc*') + OR a=4 + } +} {4 16 20 24 34 36 40 41 42 scan 0 sort 0} +do_test where7-2.277.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=29 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=979 + OR b=275 + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=41.0 AND d<42.0 AND d NOT NULL) + OR b=539 + OR a=87 + } +} {19 25 29 41 49 56 58 87 89 scan 0 sort 0} +do_test where7-2.277.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=29 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=979 + OR b=275 + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=41.0 AND d<42.0 AND d NOT NULL) + OR b=539 + OR a=87 + } +} {19 25 29 41 49 56 58 87 89 scan 0 sort 0} +do_test where7-2.278.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 43 AND 45) AND a!=44) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR f='fghijklmn' + OR (g='rqponml' AND f GLOB 'klmno*') + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR a=74 + OR ((a BETWEEN 7 AND 9) AND a!=8) + } +} {4 5 6 7 9 31 36 43 45 57 59 69 74 83 scan 0 sort 0} +do_test where7-2.278.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 43 AND 45) AND a!=44) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR f='fghijklmn' + OR (g='rqponml' AND f GLOB 'klmno*') + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR a=74 + OR ((a BETWEEN 7 AND 9) AND a!=8) + } +} {4 5 6 7 9 31 36 43 45 57 59 69 74 83 scan 0 sort 0} +do_test where7-2.279.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 80 AND 82) AND a!=81) + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR (g='ihgfedc' AND f GLOB 'bcdef*') + } +} {8 34 42 49 51 60 79 80 82 86 scan 0 sort 0} +do_test where7-2.279.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 80 AND 82) AND a!=81) + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR (g='ihgfedc' AND f GLOB 'bcdef*') + } +} {8 34 42 49 51 60 79 80 82 86 scan 0 sort 0} +do_test where7-2.280.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 58 AND 60) AND a!=59) + OR b=696 + OR f='tuvwxyzab' + OR b=374 + OR b=110 + OR a=90 + } +} {10 19 34 45 58 60 71 90 97 scan 0 sort 0} +do_test where7-2.280.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 58 AND 60) AND a!=59) + OR b=696 + OR f='tuvwxyzab' + OR b=374 + OR b=110 + OR a=90 + } +} {10 19 34 45 58 60 71 90 97 scan 0 sort 0} +do_test where7-2.281.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'ghijk*') + OR c=23023 + OR b=377 + OR b=858 + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {6 57 67 68 69 78 scan 0 sort 0} +do_test where7-2.281.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'ghijk*') + OR c=23023 + OR b=377 + OR b=858 + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {6 57 67 68 69 78 scan 0 sort 0} +do_test where7-2.282.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=38.0 AND d<39.0 AND d NOT NULL) + OR b=322 + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'pqrst*') + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR b=432 + OR b=55 + OR a=53 + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR b=25 + } +} {5 7 19 33 38 48 53 59 74 85 93 scan 0 sort 0} +do_test where7-2.282.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=38.0 AND d<39.0 AND d NOT NULL) + OR b=322 + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'pqrst*') + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR b=432 + OR b=55 + OR a=53 + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR b=25 + } +} {5 7 19 33 38 48 53 59 74 85 93 scan 0 sort 0} +do_test where7-2.283.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=484 + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR b=616 + OR c=5005 + OR ((a BETWEEN 27 AND 29) AND a!=28) + } +} {13 14 15 27 29 44 56 74 scan 0 sort 0} +do_test where7-2.283.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=484 + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR b=616 + OR c=5005 + OR ((a BETWEEN 27 AND 29) AND a!=28) + } +} {13 14 15 27 29 44 56 74 scan 0 sort 0} +do_test where7-2.284.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=916 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=1048 + OR c=6006 + OR b=762 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR b=751 + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + } +} {13 14 16 17 18 39 40 59 61 65 66 73 91 92 scan 0 sort 0} +do_test where7-2.284.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=916 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=1048 + OR c=6006 + OR b=762 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR b=751 + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + } +} {13 14 16 17 18 39 40 59 61 65 66 73 91 92 scan 0 sort 0} +do_test where7-2.285.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=32.0 AND d<33.0 AND d NOT NULL) + OR b=927 + OR b=275 + OR b=396 + OR c=4004 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR b=319 + OR ((a BETWEEN 83 AND 85) AND a!=84) + OR a=3 + OR ((a BETWEEN 73 AND 75) AND a!=74) + } +} {3 10 11 12 14 25 29 32 36 73 75 83 85 scan 0 sort 0} +do_test where7-2.285.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=32.0 AND d<33.0 AND d NOT NULL) + OR b=927 + OR b=275 + OR b=396 + OR c=4004 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR b=319 + OR ((a BETWEEN 83 AND 85) AND a!=84) + OR a=3 + OR ((a BETWEEN 73 AND 75) AND a!=74) + } +} {3 10 11 12 14 25 29 32 36 73 75 83 85 scan 0 sort 0} +do_test where7-2.286.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='wvutsrq' AND f GLOB 'lmnop*') + OR b=718 + OR f='vwxyzabcd' + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + } +} {9 11 19 21 22 35 45 47 61 66 68 71 73 87 97 98 99 scan 0 sort 0} +do_test where7-2.286.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='wvutsrq' AND f GLOB 'lmnop*') + OR b=718 + OR f='vwxyzabcd' + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + } +} {9 11 19 21 22 35 45 47 61 66 68 71 73 87 97 98 99 scan 0 sort 0} +do_test where7-2.287.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=187 + OR b=1056 + OR b=861 + OR b=1081 + OR b=572 + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR a=11 + OR ((a BETWEEN 99 AND 101) AND a!=100) + OR a=89 + OR b=421 + } +} {4 11 17 52 89 96 99 scan 0 sort 0} +do_test where7-2.287.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=187 + OR b=1056 + OR b=861 + OR b=1081 + OR b=572 + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR a=11 + OR ((a BETWEEN 99 AND 101) AND a!=100) + OR a=89 + OR b=421 + } +} {4 11 17 52 89 96 99 scan 0 sort 0} +do_test where7-2.288.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=231 + OR b=388 + OR d<0.0 + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + OR b=1045 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + } +} {12 21 39 95 scan 0 sort 0} +do_test where7-2.288.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=231 + OR b=388 + OR d<0.0 + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + OR b=1045 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + } +} {12 21 39 95 scan 0 sort 0} +do_test where7-2.289.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=528 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR b=762 + } +} {48 53 scan 0 sort 0} +do_test where7-2.289.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=528 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR b=762 + } +} {48 53 scan 0 sort 0} +do_test where7-2.290.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='stuvwxyza' + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR b=916 + } +} {18 44 70 90 92 96 scan 0 sort 0} +do_test where7-2.290.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='stuvwxyza' + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR b=916 + } +} {18 44 70 90 92 96 scan 0 sort 0} +do_test where7-2.291.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=52.0 AND d<53.0 AND d NOT NULL) + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + } +} {4 19 52 76 96 98 scan 0 sort 0} +do_test where7-2.291.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=52.0 AND d<53.0 AND d NOT NULL) + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + } +} {4 19 52 76 96 98 scan 0 sort 0} +do_test where7-2.292.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=102 + OR c=6006 + OR b=231 + OR b=212 + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'klmno*') + OR c=30030 + OR (g='onmlkji' AND f GLOB 'abcde*') + } +} {16 17 18 21 36 52 88 89 90 scan 0 sort 0} +do_test where7-2.292.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=102 + OR c=6006 + OR b=231 + OR b=212 + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'klmno*') + OR c=30030 + OR (g='onmlkji' AND f GLOB 'abcde*') + } +} {16 17 18 21 36 52 88 89 90 scan 0 sort 0} +do_test where7-2.293.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=47 + OR a=82 + OR c=25025 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR f='qrstuvwxy' + OR a=5 + } +} {5 16 40 42 47 68 73 74 75 82 94 scan 0 sort 0} +do_test where7-2.293.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=47 + OR a=82 + OR c=25025 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR f='qrstuvwxy' + OR a=5 + } +} {5 16 40 42 47 68 73 74 75 82 94 scan 0 sort 0} +do_test where7-2.294.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=429 + OR a=30 + OR f='vwxyzabcd' + OR b=762 + OR a=60 + OR (g='srqponm' AND f GLOB 'efghi*') + OR (g='xwvutsr' AND f GLOB 'efghi*') + } +} {4 21 30 39 47 60 73 99 scan 0 sort 0} +do_test where7-2.294.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=429 + OR a=30 + OR f='vwxyzabcd' + OR b=762 + OR a=60 + OR (g='srqponm' AND f GLOB 'efghi*') + OR (g='xwvutsr' AND f GLOB 'efghi*') + } +} {4 21 30 39 47 60 73 99 scan 0 sort 0} +do_test where7-2.295.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='mlkjihg' AND f GLOB 'ghijk*') + OR a=3 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=498 + OR a=100 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR a=69 + } +} {3 13 31 39 58 63 65 69 91 100 scan 0 sort 0} +do_test where7-2.295.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='mlkjihg' AND f GLOB 'ghijk*') + OR a=3 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=498 + OR a=100 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR a=69 + } +} {3 13 31 39 58 63 65 69 91 100 scan 0 sort 0} +do_test where7-2.296.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ihgfedc' AND f GLOB 'efghi*') + OR b=300 + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR b=58 + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR b=286 + OR b=234 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR f='ghijklmno' + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + } +} {6 7 26 32 43 45 55 57 58 82 84 scan 0 sort 0} +do_test where7-2.296.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ihgfedc' AND f GLOB 'efghi*') + OR b=300 + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR b=58 + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR b=286 + OR b=234 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR f='ghijklmno' + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + } +} {6 7 26 32 43 45 55 57 58 82 84 scan 0 sort 0} +do_test where7-2.297.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=95 + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR b=594 + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR ((a BETWEEN 53 AND 55) AND a!=54) + } +} {5 7 18 20 23 25 31 33 37 39 45 53 54 55 56 57 58 59 72 74 83 85 95 scan 0 sort 0} +do_test where7-2.297.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=95 + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR b=594 + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR ((a BETWEEN 53 AND 55) AND a!=54) + } +} {5 7 18 20 23 25 31 33 37 39 45 53 54 55 56 57 58 59 72 74 83 85 95 scan 0 sort 0} +do_test where7-2.298.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=949 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR (g='vutsrqp' AND f GLOB 'opqrs*') + } +} {5 14 scan 0 sort 0} +do_test where7-2.298.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=949 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR (g='vutsrqp' AND f GLOB 'opqrs*') + } +} {5 14 scan 0 sort 0} +do_test where7-2.299.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=960 + OR a=44 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR a=39 + OR b=828 + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR d<0.0 + OR b=770 + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR b=594 + OR ((a BETWEEN 89 AND 91) AND a!=90) + } +} {3 5 6 18 39 44 54 70 89 91 96 scan 0 sort 0} +do_test where7-2.299.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=960 + OR a=44 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR a=39 + OR b=828 + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR d<0.0 + OR b=770 + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR b=594 + OR ((a BETWEEN 89 AND 91) AND a!=90) + } +} {3 5 6 18 39 44 54 70 89 91 96 scan 0 sort 0} +do_test where7-2.300.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 40 AND 42) AND a!=41) + OR b=198 + OR a=51 + OR b=1056 + OR b=748 + OR ((a BETWEEN 9 AND 11) AND a!=10) + } +} {9 11 18 40 42 51 68 96 scan 0 sort 0} +do_test where7-2.300.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 40 AND 42) AND a!=41) + OR b=198 + OR a=51 + OR b=1056 + OR b=748 + OR ((a BETWEEN 9 AND 11) AND a!=10) + } +} {9 11 18 40 42 51 68 96 scan 0 sort 0} +do_test where7-2.301.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1081 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=1004 + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR ((a BETWEEN 29 AND 31) AND a!=30) + OR b=660 + OR b=957 + OR b=869 + } +} {29 31 60 66 68 79 87 91 scan 0 sort 0} +do_test where7-2.301.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1081 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=1004 + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR ((a BETWEEN 29 AND 31) AND a!=30) + OR b=660 + OR b=957 + OR b=869 + } +} {29 31 60 66 68 79 87 91 scan 0 sort 0} +do_test where7-2.302.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=927 + OR c=12012 + OR f='yzabcdefg' + OR b=880 + OR a=63 + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR (g='hgfedcb' AND f GLOB 'ijklm*') + } +} {24 34 35 36 44 50 58 63 76 80 86 scan 0 sort 0} +do_test where7-2.302.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=927 + OR c=12012 + OR f='yzabcdefg' + OR b=880 + OR a=63 + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR (g='hgfedcb' AND f GLOB 'ijklm*') + } +} {24 34 35 36 44 50 58 63 76 80 86 scan 0 sort 0} +do_test where7-2.303.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=69 + OR b=1103 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR f='wxyzabcde' + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR (g='gfedcba' AND f GLOB 'klmno*') + OR f='pqrstuvwx' + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR a=59 + OR b=946 + } +} {15 18 22 26 41 44 48 52 59 67 69 70 73 74 78 86 88 93 96 100 scan 0 sort 0} +do_test where7-2.303.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=69 + OR b=1103 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR f='wxyzabcde' + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR (g='gfedcba' AND f GLOB 'klmno*') + OR f='pqrstuvwx' + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR a=59 + OR b=946 + } +} {15 18 22 26 41 44 48 52 59 67 69 70 73 74 78 86 88 93 96 100 scan 0 sort 0} +do_test where7-2.304.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=47.0 AND d<48.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'xyzab*') + OR a=68 + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {14 16 47 68 75 scan 0 sort 0} +do_test where7-2.304.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=47.0 AND d<48.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'xyzab*') + OR a=68 + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {14 16 47 68 75 scan 0 sort 0} +do_test where7-2.305.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=10.0 AND d<11.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'lmnop*') + } +} {10 63 scan 0 sort 0} +do_test where7-2.305.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=10.0 AND d<11.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'lmnop*') + } +} {10 63 scan 0 sort 0} +do_test where7-2.306.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=32 + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR ((a BETWEEN 92 AND 94) AND a!=93) + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR c=7007 + OR b=968 + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + } +} {15 17 18 19 20 21 32 86 88 92 94 scan 0 sort 0} +do_test where7-2.306.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=32 + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR ((a BETWEEN 92 AND 94) AND a!=93) + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR c=7007 + OR b=968 + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + } +} {15 17 18 19 20 21 32 86 88 92 94 scan 0 sort 0} +do_test where7-2.307.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='cdefghijk' + OR b=1103 + } +} {2 28 54 80 scan 0 sort 0} +do_test where7-2.307.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='cdefghijk' + OR b=1103 + } +} {2 28 54 80 scan 0 sort 0} +do_test where7-2.308.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 21 AND 23) AND a!=22) + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR c=14014 + OR b=990 + OR (g='nmlkjih' AND f GLOB 'efghi*') + OR c=14014 + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR b=740 + OR c=3003 + } +} {7 8 9 13 14 21 23 40 41 42 56 90 scan 0 sort 0} +do_test where7-2.308.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 21 AND 23) AND a!=22) + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR c=14014 + OR b=990 + OR (g='nmlkjih' AND f GLOB 'efghi*') + OR c=14014 + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR b=740 + OR c=3003 + } +} {7 8 9 13 14 21 23 40 41 42 56 90 scan 0 sort 0} +do_test where7-2.309.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR a=67 + OR b=135 + OR f='bcdefghij' + OR b=924 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + } +} {1 22 27 53 60 67 79 84 scan 0 sort 0} +do_test where7-2.309.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR a=67 + OR b=135 + OR f='bcdefghij' + OR b=924 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + } +} {1 22 27 53 60 67 79 84 scan 0 sort 0} +do_test where7-2.310.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=96 + OR a=13 + } +} {13 96 scan 0 sort 0} +do_test where7-2.310.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=96 + OR a=13 + } +} {13 96 scan 0 sort 0} +do_test where7-2.311.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 34 AND 36) AND a!=35) + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + OR ((a BETWEEN 35 AND 37) AND a!=36) + OR a=49 + OR a=38 + OR b=157 + OR a=4 + OR b=311 + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR b=396 + } +} {4 27 34 35 36 37 38 49 50 97 99 scan 0 sort 0} +do_test where7-2.311.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 34 AND 36) AND a!=35) + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + OR ((a BETWEEN 35 AND 37) AND a!=36) + OR a=49 + OR a=38 + OR b=157 + OR a=4 + OR b=311 + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR b=396 + } +} {4 27 34 35 36 37 38 49 50 97 99 scan 0 sort 0} +do_test where7-2.312.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=82 + OR b=333 + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR b=99 + OR a=63 + OR a=35 + OR b=176 + } +} {9 16 22 35 48 63 74 82 100 scan 0 sort 0} +do_test where7-2.312.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=82 + OR b=333 + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR b=99 + OR a=63 + OR a=35 + OR b=176 + } +} {9 16 22 35 48 63 74 82 100 scan 0 sort 0} +do_test where7-2.313.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=90 + OR a=81 + OR ((a BETWEEN 51 AND 53) AND a!=52) + OR f='mnopqrstu' + OR b=927 + OR b=311 + OR a=34 + OR b=715 + OR f='rstuvwxyz' + } +} {12 17 34 38 43 51 53 64 65 69 81 90 95 scan 0 sort 0} +do_test where7-2.313.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=90 + OR a=81 + OR ((a BETWEEN 51 AND 53) AND a!=52) + OR f='mnopqrstu' + OR b=927 + OR b=311 + OR a=34 + OR b=715 + OR f='rstuvwxyz' + } +} {12 17 34 38 43 51 53 64 65 69 81 90 95 scan 0 sort 0} +do_test where7-2.314.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=484 + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR f='lmnopqrst' + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR b<0 + OR b=231 + OR a=14 + } +} {7 10 11 12 14 21 37 39 44 63 64 89 scan 0 sort 0} +do_test where7-2.314.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=484 + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR f='lmnopqrst' + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR b<0 + OR b=231 + OR a=14 + } +} {7 10 11 12 14 21 37 39 44 63 64 89 scan 0 sort 0} +do_test where7-2.315.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=905 + OR f='hijklmnop' + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR b=817 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + } +} {7 11 20 22 26 33 37 45 59 63 80 85 89 scan 0 sort 0} +do_test where7-2.315.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=905 + OR f='hijklmnop' + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR b=817 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + } +} {7 11 20 22 26 33 37 45 59 63 80 85 89 scan 0 sort 0} +do_test where7-2.316.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'hijkl*') + OR b=311 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR a=48 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR c=32032 + OR f='opqrstuvw' + OR b=300 + OR b=1001 + OR ((a BETWEEN 94 AND 96) AND a!=95) + } +} {14 40 43 47 48 61 66 85 91 92 94 95 96 scan 0 sort 0} +do_test where7-2.316.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'hijkl*') + OR b=311 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR a=48 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR c=32032 + OR f='opqrstuvw' + OR b=300 + OR b=1001 + OR ((a BETWEEN 94 AND 96) AND a!=95) + } +} {14 40 43 47 48 61 66 85 91 92 94 95 96 scan 0 sort 0} +do_test where7-2.317.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=95.0 AND d<96.0 AND d NOT NULL) + OR b=1070 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR a=22 + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR f='tuvwxyzab' + OR a=72 + OR ((a BETWEEN 53 AND 55) AND a!=54) + } +} {11 19 22 45 53 55 61 71 72 95 97 99 scan 0 sort 0} +do_test where7-2.317.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=95.0 AND d<96.0 AND d NOT NULL) + OR b=1070 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR a=22 + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR f='tuvwxyzab' + OR a=72 + OR ((a BETWEEN 53 AND 55) AND a!=54) + } +} {11 19 22 45 53 55 61 71 72 95 97 99 scan 0 sort 0} +do_test where7-2.318.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=8.0 AND d<9.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR a=21 + OR b=1026 + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR b=473 + } +} {8 16 21 34 36 43 scan 0 sort 0} +do_test where7-2.318.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=8.0 AND d<9.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR a=21 + OR b=1026 + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR b=473 + } +} {8 16 21 34 36 43 scan 0 sort 0} +do_test where7-2.319.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR a=100 + OR a=29 + OR c=15015 + OR a=87 + OR (g='gfedcba' AND f GLOB 'klmno*') + } +} {29 43 44 45 71 73 87 88 100 scan 0 sort 0} +do_test where7-2.319.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR a=100 + OR a=29 + OR c=15015 + OR a=87 + OR (g='gfedcba' AND f GLOB 'klmno*') + } +} {29 43 44 45 71 73 87 88 100 scan 0 sort 0} +do_test where7-2.320.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=1.0 AND d<2.0 AND d NOT NULL) + OR b=542 + OR b=638 + } +} {1 58 scan 0 sort 0} +do_test where7-2.320.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=1.0 AND d<2.0 AND d NOT NULL) + OR b=542 + OR b=638 + } +} {1 58 scan 0 sort 0} +do_test where7-2.321.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 5 AND 7) AND a!=6) + OR b=1070 + OR a=91 + OR b=1015 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR ((a BETWEEN 91 AND 93) AND a!=92) + } +} {5 7 12 80 91 93 scan 0 sort 0} +do_test where7-2.321.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 5 AND 7) AND a!=6) + OR b=1070 + OR a=91 + OR b=1015 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR ((a BETWEEN 91 AND 93) AND a!=92) + } +} {5 7 12 80 91 93 scan 0 sort 0} +do_test where7-2.322.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=7 + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR b=1015 + OR b=839 + OR (g='rqponml' AND f GLOB 'klmno*') + OR b=410 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR a=71 + } +} {1 2 7 28 36 54 71 80 scan 0 sort 0} +do_test where7-2.322.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=7 + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR b=1015 + OR b=839 + OR (g='rqponml' AND f GLOB 'klmno*') + OR b=410 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR a=71 + } +} {1 2 7 28 36 54 71 80 scan 0 sort 0} +do_test where7-2.323.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=880 + OR b=982 + OR a=52 + OR (g='onmlkji' AND f GLOB 'abcde*') + OR a=24 + OR ((a BETWEEN 47 AND 49) AND a!=48) + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + } +} {24 47 49 50 52 60 76 80 scan 0 sort 0} +do_test where7-2.323.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=880 + OR b=982 + OR a=52 + OR (g='onmlkji' AND f GLOB 'abcde*') + OR a=24 + OR ((a BETWEEN 47 AND 49) AND a!=48) + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + } +} {24 47 49 50 52 60 76 80 scan 0 sort 0} +do_test where7-2.324.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 67 AND 69) AND a!=68) + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + } +} {5 22 31 57 67 69 83 scan 0 sort 0} +do_test where7-2.324.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 67 AND 69) AND a!=68) + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + } +} {5 22 31 57 67 69 83 scan 0 sort 0} +do_test where7-2.325.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='abcdefghi' + OR a=5 + OR b=124 + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=432 + OR 1000000=45.0 AND d<46.0 AND d NOT NULL) + OR b=77 + OR b=605 + } +} {5 7 26 45 52 55 58 69 78 scan 0 sort 0} +do_test where7-2.325.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='abcdefghi' + OR a=5 + OR b=124 + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=432 + OR 1000000=45.0 AND d<46.0 AND d NOT NULL) + OR b=77 + OR b=605 + } +} {5 7 26 45 52 55 58 69 78 scan 0 sort 0} +do_test where7-2.326.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=89.0 AND d<90.0 AND d NOT NULL) + OR b=583 + OR a=62 + } +} {53 62 89 scan 0 sort 0} +do_test where7-2.326.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=89.0 AND d<90.0 AND d NOT NULL) + OR b=583 + OR a=62 + } +} {53 62 89 scan 0 sort 0} +do_test where7-2.327.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR f='pqrstuvwx' + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR b=278 + OR a=10 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR f='uvwxyzabc' + } +} {5 10 15 20 28 41 46 54 63 65 67 68 72 84 86 93 98 scan 0 sort 0} +do_test where7-2.327.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR f='pqrstuvwx' + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR b=278 + OR a=10 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR f='uvwxyzabc' + } +} {5 10 15 20 28 41 46 54 63 65 67 68 72 84 86 93 98 scan 0 sort 0} +do_test where7-2.328.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 57 AND 59) AND a!=58) + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR b=564 + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR b=77 + OR (g='nmlkjih' AND f GLOB 'efghi*') + OR b=968 + OR b=847 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR (g='lkjihgf' AND f GLOB 'opqrs*') + } +} {7 14 40 56 57 58 59 66 77 85 88 90 92 scan 0 sort 0} +do_test where7-2.328.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 57 AND 59) AND a!=58) + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR b=564 + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR b=77 + OR (g='nmlkjih' AND f GLOB 'efghi*') + OR b=968 + OR b=847 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR (g='lkjihgf' AND f GLOB 'opqrs*') + } +} {7 14 40 56 57 58 59 66 77 85 88 90 92 scan 0 sort 0} +do_test where7-2.329.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=539 + OR b=594 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR f='abcdefghi' + OR a=6 + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR b=762 + } +} {6 17 26 49 52 54 63 65 78 scan 0 sort 0} +do_test where7-2.329.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=539 + OR b=594 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR f='abcdefghi' + OR a=6 + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR b=762 + } +} {6 17 26 49 52 54 63 65 78 scan 0 sort 0} +do_test where7-2.330.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=869 + OR b=630 + } +} {79 scan 0 sort 0} +do_test where7-2.330.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=869 + OR b=630 + } +} {79 scan 0 sort 0} +do_test where7-2.331.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=72.0 AND d<73.0 AND d NOT NULL) + OR b=693 + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR b=968 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR b=132 + OR f='nopqrstuv' + OR ((a BETWEEN 28 AND 30) AND a!=29) + } +} {12 13 28 30 39 63 65 72 86 88 91 scan 0 sort 0} +do_test where7-2.331.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=72.0 AND d<73.0 AND d NOT NULL) + OR b=693 + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR b=968 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR b=132 + OR f='nopqrstuv' + OR ((a BETWEEN 28 AND 30) AND a!=29) + } +} {12 13 28 30 39 63 65 72 86 88 91 scan 0 sort 0} +do_test where7-2.332.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=32032 + OR b=814 + OR (d>=90.0 AND d<91.0 AND d NOT NULL) + OR b=814 + OR a=78 + OR a=37 + } +} {37 74 78 90 94 95 96 scan 0 sort 0} +do_test where7-2.332.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=32032 + OR b=814 + OR (d>=90.0 AND d<91.0 AND d NOT NULL) + OR b=814 + OR a=78 + OR a=37 + } +} {37 74 78 90 94 95 96 scan 0 sort 0} +do_test where7-2.333.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=190 + OR (g='mlkjihg' AND f GLOB 'hijkl*') + OR b=924 + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=759 + OR (g='yxwvuts' AND f GLOB 'bcdef*') + } +} {1 40 59 69 84 scan 0 sort 0} +do_test where7-2.333.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=190 + OR (g='mlkjihg' AND f GLOB 'hijkl*') + OR b=924 + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=759 + OR (g='yxwvuts' AND f GLOB 'bcdef*') + } +} {1 40 59 69 84 scan 0 sort 0} +do_test where7-2.334.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=97 + OR b=201 + OR b=597 + OR a=6 + OR f='cdefghijk' + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR b=300 + OR b=693 + OR b=333 + OR b=740 + } +} {2 6 28 54 63 74 76 80 97 scan 0 sort 0} +do_test where7-2.334.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=97 + OR b=201 + OR b=597 + OR a=6 + OR f='cdefghijk' + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR b=300 + OR b=693 + OR b=333 + OR b=740 + } +} {2 6 28 54 63 74 76 80 97 scan 0 sort 0} +do_test where7-2.335.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=26026 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR c=17017 + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (g='srqponm' AND f GLOB 'ghijk*') + OR (g='jihgfed' AND f GLOB 'zabcd*') + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + } +} {2 4 32 43 49 50 51 60 72 74 76 77 78 scan 0 sort 0} +do_test where7-2.335.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=26026 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR c=17017 + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (g='srqponm' AND f GLOB 'ghijk*') + OR (g='jihgfed' AND f GLOB 'zabcd*') + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + } +} {2 4 32 43 49 50 51 60 72 74 76 77 78 scan 0 sort 0} +do_test where7-2.336.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=70.0 AND d<71.0 AND d NOT NULL) + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR b=638 + OR b=495 + OR a=44 + OR b=374 + OR a=22 + OR c=12012 + } +} {13 15 22 34 35 36 44 45 58 70 scan 0 sort 0} +do_test where7-2.336.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=70.0 AND d<71.0 AND d NOT NULL) + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR b=638 + OR b=495 + OR a=44 + OR b=374 + OR a=22 + OR c=12012 + } +} {13 15 22 34 35 36 44 45 58 70 scan 0 sort 0} +do_test where7-2.337.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=8008 + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR b=300 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR a=41 + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR b=135 + OR b=605 + } +} {1 2 22 23 24 39 41 49 55 100 scan 0 sort 0} +do_test where7-2.337.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=8008 + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR b=300 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR a=41 + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR b=135 + OR b=605 + } +} {1 2 22 23 24 39 41 49 55 100 scan 0 sort 0} +do_test where7-2.338.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR (g='srqponm' AND f GLOB 'efghi*') + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR b=762 + OR b=484 + OR b=190 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=1023 + } +} {4 17 30 41 43 44 56 61 69 74 82 93 95 97 scan 0 sort 0} +do_test where7-2.338.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR (g='srqponm' AND f GLOB 'efghi*') + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR b=762 + OR b=484 + OR b=190 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=1023 + } +} {4 17 30 41 43 44 56 61 69 74 82 93 95 97 scan 0 sort 0} +do_test where7-2.339.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ihgfedc' AND f GLOB 'efghi*') + OR a=34 + OR f='rstuvwxyz' + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=729 + } +} {10 17 34 43 69 82 95 scan 0 sort 0} +do_test where7-2.339.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ihgfedc' AND f GLOB 'efghi*') + OR a=34 + OR f='rstuvwxyz' + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=729 + } +} {10 17 34 43 69 82 95 scan 0 sort 0} +do_test where7-2.340.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=1004 + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR g IS NULL + } +} {37 41 scan 0 sort 0} +do_test where7-2.340.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=1004 + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR g IS NULL + } +} {37 41 scan 0 sort 0} +do_test where7-2.341.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=73 + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR ((a BETWEEN 51 AND 53) AND a!=52) + OR a=9 + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR a=44 + OR a=23 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR (g='rqponml' AND f GLOB 'lmnop*') + } +} {1 9 23 36 37 38 44 51 53 55 63 73 78 scan 0 sort 0} +do_test where7-2.341.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=73 + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR ((a BETWEEN 51 AND 53) AND a!=52) + OR a=9 + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR a=44 + OR a=23 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR (g='rqponml' AND f GLOB 'lmnop*') + } +} {1 9 23 36 37 38 44 51 53 55 63 73 78 scan 0 sort 0} +do_test where7-2.342.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=487 + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR a=11 + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR a=13 + OR a=15 + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR a=36 + } +} {11 12 13 14 15 29 36 69 71 77 78 79 scan 0 sort 0} +do_test where7-2.342.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=487 + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR a=11 + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR a=13 + OR a=15 + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR a=36 + } +} {11 12 13 14 15 29 36 69 71 77 78 79 scan 0 sort 0} +do_test where7-2.343.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=938 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (d>=32.0 AND d<33.0 AND d NOT NULL) + OR b=245 + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + } +} {32 35 54 57 59 scan 0 sort 0} +do_test where7-2.343.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=938 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (d>=32.0 AND d<33.0 AND d NOT NULL) + OR b=245 + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + } +} {32 35 54 57 59 scan 0 sort 0} +do_test where7-2.344.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1078 + OR c=19019 + OR a=38 + OR a=59 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR c=25025 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + } +} {30 32 38 51 55 56 57 59 73 74 75 76 79 95 97 98 scan 0 sort 0} +do_test where7-2.344.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1078 + OR c=19019 + OR a=38 + OR a=59 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR c=25025 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + } +} {30 32 38 51 55 56 57 59 73 74 75 76 79 95 97 98 scan 0 sort 0} +do_test where7-2.345.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='cdefghijk' + OR b=168 + OR b=561 + OR a=81 + OR a=87 + } +} {2 28 51 54 80 81 87 scan 0 sort 0} +do_test where7-2.345.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='cdefghijk' + OR b=168 + OR b=561 + OR a=81 + OR a=87 + } +} {2 28 51 54 80 81 87 scan 0 sort 0} +do_test where7-2.346.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='gfedcba' AND f GLOB 'klmno*') + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR (g='rqponml' AND f GLOB 'hijkl*') + OR a=48 + OR b=113 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR b=880 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'bcdef*') + } +} {9 11 20 22 33 48 53 73 80 85 87 88 scan 0 sort 0} +do_test where7-2.346.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='gfedcba' AND f GLOB 'klmno*') + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR (g='rqponml' AND f GLOB 'hijkl*') + OR a=48 + OR b=113 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR b=880 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'bcdef*') + } +} {9 11 20 22 33 48 53 73 80 85 87 88 scan 0 sort 0} +do_test where7-2.347.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=517 + OR b=187 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR b=1092 + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + } +} {6 17 47 84 86 scan 0 sort 0} +do_test where7-2.347.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=517 + OR b=187 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR b=1092 + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + } +} {6 17 47 84 86 scan 0 sort 0} +do_test where7-2.348.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=982 + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=234 + OR c=15015 + OR a=47 + OR f='qrstuvwxy' + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + OR b=814 + OR b=440 + OR b=454 + } +} {16 40 42 43 44 45 47 65 68 74 94 scan 0 sort 0} +do_test where7-2.348.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=982 + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=234 + OR c=15015 + OR a=47 + OR f='qrstuvwxy' + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + OR b=814 + OR b=440 + OR b=454 + } +} {16 40 42 43 44 45 47 65 68 74 94 scan 0 sort 0} +do_test where7-2.349.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=47.0 AND d<48.0 AND d NOT NULL) + OR c=7007 + OR b=429 + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR b=231 + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR c=22022 + OR f='bcdefghij' + } +} {1 19 20 21 25 26 27 39 47 53 64 65 66 79 scan 0 sort 0} +do_test where7-2.349.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=47.0 AND d<48.0 AND d NOT NULL) + OR c=7007 + OR b=429 + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR b=231 + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR c=22022 + OR f='bcdefghij' + } +} {1 19 20 21 25 26 27 39 47 53 64 65 66 79 scan 0 sort 0} +do_test where7-2.350.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=17017 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR b=784 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR ((a BETWEEN 54 AND 56) AND a!=55) + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR f='zabcdefgh' + } +} {16 18 22 24 25 49 50 51 54 56 62 77 88 90 scan 0 sort 0} +do_test where7-2.350.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=17017 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR b=784 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR ((a BETWEEN 54 AND 56) AND a!=55) + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR f='zabcdefgh' + } +} {16 18 22 24 25 49 50 51 54 56 62 77 88 90 scan 0 sort 0} +do_test where7-2.351.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=344 + OR b=275 + OR c<=10 + } +} {25 scan 0 sort 0} +do_test where7-2.351.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=344 + OR b=275 + OR c<=10 + } +} {25 scan 0 sort 0} +do_test where7-2.352.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 44 AND 46) AND a!=45) + OR a=76 + OR b=154 + OR a=30 + OR c=3003 + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + OR b=564 + OR b=55 + OR a=38 + } +} {5 7 8 9 14 23 30 38 44 46 49 75 76 88 scan 0 sort 0} +do_test where7-2.352.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 44 AND 46) AND a!=45) + OR a=76 + OR b=154 + OR a=30 + OR c=3003 + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + OR b=564 + OR b=55 + OR a=38 + } +} {5 7 8 9 14 23 30 38 44 46 49 75 76 88 scan 0 sort 0} +do_test where7-2.353.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=52 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + } +} {52 54 66 68 scan 0 sort 0} +do_test where7-2.353.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=52 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + } +} {52 54 66 68 scan 0 sort 0} +do_test where7-2.354.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=792 + OR (g='wvutsrq' AND f GLOB 'jklmn*') + } +} {9 72 scan 0 sort 0} +do_test where7-2.354.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=792 + OR (g='wvutsrq' AND f GLOB 'jklmn*') + } +} {9 72 scan 0 sort 0} +do_test where7-2.355.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=73.0 AND d<74.0 AND d NOT NULL) + OR c=21021 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR f='zabcdefgh' + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR b=781 + OR a=64 + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + } +} {1 11 25 51 61 62 63 64 65 71 73 77 scan 0 sort 0} +do_test where7-2.355.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=73.0 AND d<74.0 AND d NOT NULL) + OR c=21021 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR f='zabcdefgh' + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR b=781 + OR a=64 + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + } +} {1 11 25 51 61 62 63 64 65 71 73 77 scan 0 sort 0} +do_test where7-2.356.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='lkjihgf' AND f GLOB 'pqrst*') + OR (d>=90.0 AND d<91.0 AND d NOT NULL) + OR a=34 + OR (g='rqponml' AND f GLOB 'ijklm*') + OR (g='rqponml' AND f GLOB 'klmno*') + OR (g='srqponm' AND f GLOB 'defgh*') + OR b=319 + OR b=330 + OR ((a BETWEEN 28 AND 30) AND a!=29) + } +} {28 29 30 34 36 67 90 scan 0 sort 0} +do_test where7-2.356.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='lkjihgf' AND f GLOB 'pqrst*') + OR (d>=90.0 AND d<91.0 AND d NOT NULL) + OR a=34 + OR (g='rqponml' AND f GLOB 'ijklm*') + OR (g='rqponml' AND f GLOB 'klmno*') + OR (g='srqponm' AND f GLOB 'defgh*') + OR b=319 + OR b=330 + OR ((a BETWEEN 28 AND 30) AND a!=29) + } +} {28 29 30 34 36 67 90 scan 0 sort 0} +do_test where7-2.357.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'pqrst*') + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR a=45 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + } +} {15 41 45 67 81 93 scan 0 sort 0} +do_test where7-2.357.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'pqrst*') + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR a=45 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + } +} {15 41 45 67 81 93 scan 0 sort 0} +do_test where7-2.358.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=53.0 AND d<54.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR b=165 + OR b=836 + } +} {15 53 54 76 scan 0 sort 0} +do_test where7-2.358.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=53.0 AND d<54.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR b=165 + OR b=836 + } +} {15 53 54 76 scan 0 sort 0} +do_test where7-2.359.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1034 + OR f='vwxyzabcd' + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR ((a BETWEEN 57 AND 59) AND a!=58) + } +} {21 47 57 59 73 91 94 99 scan 0 sort 0} +do_test where7-2.359.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1034 + OR f='vwxyzabcd' + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR ((a BETWEEN 57 AND 59) AND a!=58) + } +} {21 47 57 59 73 91 94 99 scan 0 sort 0} +do_test where7-2.360.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=440 + OR a=19 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR c=22022 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR a=92 + OR b=1026 + OR b=608 + } +} {19 40 47 64 65 66 92 scan 0 sort 0} +do_test where7-2.360.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=440 + OR a=19 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR c=22022 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR a=92 + OR b=1026 + OR b=608 + } +} {19 40 47 64 65 66 92 scan 0 sort 0} +do_test where7-2.361.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=37 + OR b=88 + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR c=23023 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR a=56 + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR f='ijklmnopq' + OR ((a BETWEEN 85 AND 87) AND a!=86) + } +} {8 13 15 16 22 34 37 42 56 60 67 68 69 85 86 87 94 scan 0 sort 0} +do_test where7-2.361.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=37 + OR b=88 + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR c=23023 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR a=56 + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR f='ijklmnopq' + OR ((a BETWEEN 85 AND 87) AND a!=86) + } +} {8 13 15 16 22 34 37 42 56 60 67 68 69 85 86 87 94 scan 0 sort 0} +do_test where7-2.362.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR a=74 + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 42 AND 44) AND a!=43) + } +} {20 22 24 42 44 74 97 scan 0 sort 0} +do_test where7-2.362.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR a=74 + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 42 AND 44) AND a!=43) + } +} {20 22 24 42 44 74 97 scan 0 sort 0} +do_test where7-2.363.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='uvwxyzabc' + OR b=869 + OR ((a BETWEEN 49 AND 51) AND a!=50) + } +} {20 46 49 51 72 79 98 scan 0 sort 0} +do_test where7-2.363.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='uvwxyzabc' + OR b=869 + OR ((a BETWEEN 49 AND 51) AND a!=50) + } +} {20 46 49 51 72 79 98 scan 0 sort 0} +do_test where7-2.364.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=682 + OR b=583 + OR b=685 + OR b=817 + OR ((a BETWEEN 34 AND 36) AND a!=35) + } +} {34 36 53 62 scan 0 sort 0} +do_test where7-2.364.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=682 + OR b=583 + OR b=685 + OR b=817 + OR ((a BETWEEN 34 AND 36) AND a!=35) + } +} {34 36 53 62 scan 0 sort 0} +do_test where7-2.365.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=583 + OR a=39 + OR b=627 + OR ((a BETWEEN 72 AND 74) AND a!=73) + } +} {39 53 57 72 74 scan 0 sort 0} +do_test where7-2.365.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=583 + OR a=39 + OR b=627 + OR ((a BETWEEN 72 AND 74) AND a!=73) + } +} {39 53 57 72 74 scan 0 sort 0} +do_test where7-2.366.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR b=212 + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR a=20 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR b=627 + } +} {2 4 20 24 26 53 57 68 73 scan 0 sort 0} +do_test where7-2.366.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR b=212 + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR a=20 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR b=627 + } +} {2 4 20 24 26 53 57 68 73 scan 0 sort 0} +do_test where7-2.367.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR b=157 + OR b=1026 + } +} {8 34 60 77 86 scan 0 sort 0} +do_test where7-2.367.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR b=157 + OR b=1026 + } +} {8 34 60 77 86 scan 0 sort 0} +do_test where7-2.368.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=553 + OR a=16 + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='wvutsrq' AND f GLOB 'lmnop*') + OR f='zabcdefgh' + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR (g='xwvutsr' AND f GLOB 'fghij*') + } +} {5 11 16 25 31 33 51 67 77 80 82 scan 0 sort 0} +do_test where7-2.368.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=553 + OR a=16 + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='wvutsrq' AND f GLOB 'lmnop*') + OR f='zabcdefgh' + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR (g='xwvutsr' AND f GLOB 'fghij*') + } +} {5 11 16 25 31 33 51 67 77 80 82 scan 0 sort 0} +do_test where7-2.369.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=858 + OR c=9009 + OR b=792 + OR b=88 + OR b=154 + } +} {8 14 25 26 27 72 78 scan 0 sort 0} +do_test where7-2.369.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=858 + OR c=9009 + OR b=792 + OR b=88 + OR b=154 + } +} {8 14 25 26 27 72 78 scan 0 sort 0} +do_test where7-2.370.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f IS NULL + OR a=37 + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR b=168 + OR b=22 + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR b=506 + } +} {2 21 37 46 48 55 57 scan 0 sort 0} +do_test where7-2.370.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f IS NULL + OR a=37 + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR b=168 + OR b=22 + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR b=506 + } +} {2 21 37 46 48 55 57 scan 0 sort 0} +do_test where7-2.371.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=29 + OR ((a BETWEEN 26 AND 28) AND a!=27) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR b=209 + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR b=146 + } +} {19 25 26 28 29 42 45 51 69 71 77 97 scan 0 sort 0} +do_test where7-2.371.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=29 + OR ((a BETWEEN 26 AND 28) AND a!=27) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR b=209 + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR b=146 + } +} {19 25 26 28 29 42 45 51 69 71 77 97 scan 0 sort 0} +do_test where7-2.372.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=63 + OR a=69 + OR b=333 + OR (d>=6.0 AND d<7.0 AND d NOT NULL) + OR b=135 + OR b=25 + OR b=1037 + OR b=682 + OR c=27027 + OR a=46 + } +} {6 46 62 63 69 79 80 81 scan 0 sort 0} +do_test where7-2.372.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=63 + OR a=69 + OR b=333 + OR (d>=6.0 AND d<7.0 AND d NOT NULL) + OR b=135 + OR b=25 + OR b=1037 + OR b=682 + OR c=27027 + OR a=46 + } +} {6 46 62 63 69 79 80 81 scan 0 sort 0} +do_test where7-2.373.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='edcbazy' AND f GLOB 'wxyza*') + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR b=113 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {40 42 52 53 55 59 61 100 scan 0 sort 0} +do_test where7-2.373.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='edcbazy' AND f GLOB 'wxyza*') + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR b=113 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {40 42 52 53 55 59 61 100 scan 0 sort 0} +do_test where7-2.374.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1026 + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + } +} {48 scan 0 sort 0} +do_test where7-2.374.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1026 + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + } +} {48 scan 0 sort 0} +do_test where7-2.375.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='rqponml' AND f GLOB 'ijklm*') + OR a=99 + OR a=100 + OR b=429 + OR b=682 + OR b=495 + OR f='efghijklm' + OR a=10 + OR f='mnopqrstu' + OR b=946 + OR (d>=95.0 AND d<96.0 AND d NOT NULL) + } +} {4 10 12 30 34 38 39 45 56 62 64 82 86 90 95 99 100 scan 0 sort 0} +do_test where7-2.375.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='rqponml' AND f GLOB 'ijklm*') + OR a=99 + OR a=100 + OR b=429 + OR b=682 + OR b=495 + OR f='efghijklm' + OR a=10 + OR f='mnopqrstu' + OR b=946 + OR (d>=95.0 AND d<96.0 AND d NOT NULL) + } +} {4 10 12 30 34 38 39 45 56 62 64 82 86 90 95 99 100 scan 0 sort 0} +do_test where7-2.376.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=11.0 AND d<12.0 AND d NOT NULL) + OR c=23023 + OR b=462 + OR ((a BETWEEN 17 AND 19) AND a!=18) + } +} {11 17 19 42 67 68 69 scan 0 sort 0} +do_test where7-2.376.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=11.0 AND d<12.0 AND d NOT NULL) + OR c=23023 + OR b=462 + OR ((a BETWEEN 17 AND 19) AND a!=18) + } +} {11 17 19 42 67 68 69 scan 0 sort 0} +do_test where7-2.377.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=539 + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR c=6006 + OR a=18 + OR c=24024 + OR (g='wvutsrq' AND f GLOB 'jklmn*') + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR c=19019 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR ((a BETWEEN 44 AND 46) AND a!=45) + } +} {9 11 16 17 18 38 43 44 46 49 55 56 57 70 71 72 87 scan 0 sort 0} +do_test where7-2.377.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=539 + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR c=6006 + OR a=18 + OR c=24024 + OR (g='wvutsrq' AND f GLOB 'jklmn*') + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR c=19019 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR ((a BETWEEN 44 AND 46) AND a!=45) + } +} {9 11 16 17 18 38 43 44 46 49 55 56 57 70 71 72 87 scan 0 sort 0} +do_test where7-2.378.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=15.0 AND d<16.0 AND d NOT NULL) + OR a=20 + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=121 + OR a=10 + OR b=792 + } +} {10 11 15 20 72 94 scan 0 sort 0} +do_test where7-2.378.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=15.0 AND d<16.0 AND d NOT NULL) + OR a=20 + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=121 + OR a=10 + OR b=792 + } +} {10 11 15 20 72 94 scan 0 sort 0} +do_test where7-2.379.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=99 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + } +} {9 14 40 66 85 87 92 scan 0 sort 0} +do_test where7-2.379.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=99 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + } +} {9 14 40 66 85 87 92 scan 0 sort 0} +do_test where7-2.380.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR b=715 + OR ((a BETWEEN 23 AND 25) AND a!=24) + } +} {6 23 25 32 58 65 79 81 84 scan 0 sort 0} +do_test where7-2.380.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR b=715 + OR ((a BETWEEN 23 AND 25) AND a!=24) + } +} {6 23 25 32 58 65 79 81 84 scan 0 sort 0} +do_test where7-2.381.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + OR a=46 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + } +} {28 46 97 scan 0 sort 0} +do_test where7-2.381.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + OR a=46 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + } +} {28 46 97 scan 0 sort 0} +do_test where7-2.382.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ihgfedc' AND f GLOB 'defgh*') + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR b=1056 + OR b=146 + } +} {18 81 96 97 99 scan 0 sort 0} +do_test where7-2.382.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ihgfedc' AND f GLOB 'defgh*') + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR b=1056 + OR b=146 + } +} {18 81 96 97 99 scan 0 sort 0} +do_test where7-2.383.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=15 + OR b=388 + OR ((a BETWEEN 82 AND 84) AND a!=83) + OR a=36 + OR b=737 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR a=75 + } +} {15 21 23 36 67 75 82 84 89 scan 0 sort 0} +do_test where7-2.383.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=15 + OR b=388 + OR ((a BETWEEN 82 AND 84) AND a!=83) + OR a=36 + OR b=737 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR a=75 + } +} {15 21 23 36 67 75 82 84 89 scan 0 sort 0} +do_test where7-2.384.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=9009 + OR a=34 + OR (d>=95.0 AND d<96.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=715 + OR b=619 + OR ((a BETWEEN 98 AND 100) AND a!=99) + } +} {16 25 26 27 34 65 95 98 100 scan 0 sort 0} +do_test where7-2.384.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=9009 + OR a=34 + OR (d>=95.0 AND d<96.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=715 + OR b=619 + OR ((a BETWEEN 98 AND 100) AND a!=99) + } +} {16 25 26 27 34 65 95 98 100 scan 0 sort 0} +do_test where7-2.385.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=61.0 AND d<62.0 AND d NOT NULL) + OR ((a BETWEEN 11 AND 13) AND a!=12) + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR b=242 + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR b=300 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR ((a BETWEEN 93 AND 95) AND a!=94) + } +} {1 11 13 21 22 24 26 27 32 34 39 41 53 61 74 76 79 93 95 scan 0 sort 0} +do_test where7-2.385.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=61.0 AND d<62.0 AND d NOT NULL) + OR ((a BETWEEN 11 AND 13) AND a!=12) + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR b=242 + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR b=300 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR ((a BETWEEN 93 AND 95) AND a!=94) + } +} {1 11 13 21 22 24 26 27 32 34 39 41 53 61 74 76 79 93 95 scan 0 sort 0} +do_test where7-2.386.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=85 + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + OR b=212 + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR b=36 + OR b=231 + OR b=1048 + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR c=19019 + } +} {21 25 27 33 43 55 56 57 69 71 85 92 scan 0 sort 0} +do_test where7-2.386.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=85 + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + OR b=212 + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR b=36 + OR b=231 + OR b=1048 + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR c=19019 + } +} {21 25 27 33 43 55 56 57 69 71 85 92 scan 0 sort 0} +do_test where7-2.387.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 28 AND 30) AND a!=29) + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR b=1059 + OR b=630 + } +} {8 28 30 scan 0 sort 0} +do_test where7-2.387.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 28 AND 30) AND a!=29) + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR b=1059 + OR b=630 + } +} {8 28 30 scan 0 sort 0} +do_test where7-2.388.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='ghijklmno' + OR f='nopqrstuv' + OR b=297 + } +} {6 13 27 32 39 58 65 84 91 scan 0 sort 0} +do_test where7-2.388.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='ghijklmno' + OR f='nopqrstuv' + OR b=297 + } +} {6 13 27 32 39 58 65 84 91 scan 0 sort 0} +do_test where7-2.389.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1001 + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR a=58 + OR b=333 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR b=572 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + } +} {7 15 33 43 49 50 52 58 59 68 70 85 87 89 91 scan 0 sort 0} +do_test where7-2.389.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1001 + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR a=58 + OR b=333 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR b=572 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + } +} {7 15 33 43 49 50 52 58 59 68 70 85 87 89 91 scan 0 sort 0} +do_test where7-2.390.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1034 + OR f='lmnopqrst' + OR (g='qponmlk' AND f GLOB 'mnopq*') + } +} {11 37 38 63 89 94 scan 0 sort 0} +do_test where7-2.390.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1034 + OR f='lmnopqrst' + OR (g='qponmlk' AND f GLOB 'mnopq*') + } +} {11 37 38 63 89 94 scan 0 sort 0} +do_test where7-2.391.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=15015 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'hijkl*') + OR b=58 + OR b=674 + OR b=979 + } +} {43 44 45 59 87 89 scan 0 sort 0} +do_test where7-2.391.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=15015 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'hijkl*') + OR b=58 + OR b=674 + OR b=979 + } +} {43 44 45 59 87 89 scan 0 sort 0} +do_test where7-2.392.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 60 AND 62) AND a!=61) + OR b=660 + OR b=341 + } +} {31 60 62 scan 0 sort 0} +do_test where7-2.392.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 60 AND 62) AND a!=61) + OR b=660 + OR b=341 + } +} {31 60 62 scan 0 sort 0} +do_test where7-2.393.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=528 + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR b=630 + OR a=19 + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR f='wxyzabcde' + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR b=377 + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR a=77 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + } +} {8 19 22 43 44 48 64 74 77 100 scan 0 sort 0} +do_test where7-2.393.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=528 + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR b=630 + OR a=19 + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR f='wxyzabcde' + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR b=377 + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR a=77 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + } +} {8 19 22 43 44 48 64 74 77 100 scan 0 sort 0} +do_test where7-2.394.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=506 + OR a=70 + } +} {46 70 scan 0 sort 0} +do_test where7-2.394.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=506 + OR a=70 + } +} {46 70 scan 0 sort 0} +do_test where7-2.395.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=64 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'cdefg*') + OR c=14014 + OR b=586 + OR c=27027 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'wxyza*') + } +} {26 28 40 41 42 52 57 64 74 78 79 80 81 86 scan 0 sort 0} +do_test where7-2.395.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=64 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'cdefg*') + OR c=14014 + OR b=586 + OR c=27027 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'wxyza*') + } +} {26 28 40 41 42 52 57 64 74 78 79 80 81 86 scan 0 sort 0} +do_test where7-2.396.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=46 + OR b=297 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR b=275 + OR b=91 + OR b=1015 + OR c=12012 + OR a=23 + OR b=278 + } +} {23 25 27 34 35 36 46 57 59 75 scan 0 sort 0} +do_test where7-2.396.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=46 + OR b=297 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR b=275 + OR b=91 + OR b=1015 + OR c=12012 + OR a=23 + OR b=278 + } +} {23 25 27 34 35 36 46 57 59 75 scan 0 sort 0} +do_test where7-2.397.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'tuvwx*') + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR a=23 + OR b=737 + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR ((a BETWEEN 68 AND 70) AND a!=69) + } +} {18 20 23 25 27 61 67 68 69 70 71 98 scan 0 sort 0} +do_test where7-2.397.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'tuvwx*') + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR a=23 + OR b=737 + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR ((a BETWEEN 68 AND 70) AND a!=69) + } +} {18 20 23 25 27 61 67 68 69 70 71 98 scan 0 sort 0} +do_test where7-2.398.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=814 + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR b=377 + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + } +} {71 74 79 scan 0 sort 0} +do_test where7-2.398.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=814 + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR b=377 + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + } +} {71 74 79 scan 0 sort 0} +do_test where7-2.399.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=18 + OR b=1059 + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR b=795 + } +} {9 18 25 46 51 53 77 scan 0 sort 0} +do_test where7-2.399.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=18 + OR b=1059 + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR b=795 + } +} {9 18 25 46 51 53 77 scan 0 sort 0} +do_test where7-2.400.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR a=93 + OR a=11 + OR f='nopqrstuv' + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR a=17 + OR b=366 + } +} {11 13 17 22 24 27 37 39 63 65 89 91 93 scan 0 sort 0} +do_test where7-2.400.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR a=93 + OR a=11 + OR f='nopqrstuv' + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR a=17 + OR b=366 + } +} {11 13 17 22 24 27 37 39 63 65 89 91 93 scan 0 sort 0} +do_test where7-2.401.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=685 + OR a=33 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR (g='rqponml' AND f GLOB 'lmnop*') + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR b=715 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR a=6 + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {6 16 33 37 39 40 41 42 59 61 65 80 82 93 95 scan 0 sort 0} +do_test where7-2.401.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=685 + OR a=33 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR (g='rqponml' AND f GLOB 'lmnop*') + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR b=715 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR a=6 + OR ((a BETWEEN 59 AND 61) AND a!=60) + } +} {6 16 33 37 39 40 41 42 59 61 65 80 82 93 95 scan 0 sort 0} +do_test where7-2.402.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=89 + OR b=1037 + OR (g='mlkjihg' AND f GLOB 'ijklm*') + } +} {60 89 scan 0 sort 0} +do_test where7-2.402.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=89 + OR b=1037 + OR (g='mlkjihg' AND f GLOB 'ijklm*') + } +} {60 89 scan 0 sort 0} +do_test where7-2.403.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=663 + OR b=531 + OR b=146 + OR b=102 + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR a=26 + } +} {26 28 44 46 87 89 97 scan 0 sort 0} +do_test where7-2.403.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=663 + OR b=531 + OR b=146 + OR b=102 + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR a=26 + } +} {26 28 44 46 87 89 97 scan 0 sort 0} +do_test where7-2.404.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'stuvw*') + OR (g='rqponml' AND f GLOB 'jklmn*') + OR (g='lkjihgf' AND f GLOB 'mnopq*') + OR b=726 + OR ((a BETWEEN 73 AND 75) AND a!=74) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR c=2002 + OR c=15015 + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR b=201 + } +} {4 5 6 12 35 43 44 45 64 66 70 73 75 scan 0 sort 0} +do_test where7-2.404.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'stuvw*') + OR (g='rqponml' AND f GLOB 'jklmn*') + OR (g='lkjihgf' AND f GLOB 'mnopq*') + OR b=726 + OR ((a BETWEEN 73 AND 75) AND a!=74) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR c=2002 + OR c=15015 + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR b=201 + } +} {4 5 6 12 35 43 44 45 64 66 70 73 75 scan 0 sort 0} +do_test where7-2.405.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'uvwxy*') + OR b=924 + OR f='lmnopqrst' + OR b=1048 + } +} {11 37 63 72 84 89 scan 0 sort 0} +do_test where7-2.405.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'uvwxy*') + OR b=924 + OR f='lmnopqrst' + OR b=1048 + } +} {11 37 63 72 84 89 scan 0 sort 0} +do_test where7-2.406.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=198 + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR b=286 + OR ((a BETWEEN 65 AND 67) AND a!=66) + } +} {12 14 18 20 22 26 58 63 65 67 scan 0 sort 0} +do_test where7-2.406.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=198 + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + OR ((a BETWEEN 12 AND 14) AND a!=13) + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR b=286 + OR ((a BETWEEN 65 AND 67) AND a!=66) + } +} {12 14 18 20 22 26 58 63 65 67 scan 0 sort 0} +do_test where7-2.407.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=242 + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR f='bcdefghij' + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR a=38 + OR b=187 + } +} {1 17 19 22 27 38 53 57 59 79 88 99 scan 0 sort 0} +do_test where7-2.407.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=242 + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR f='bcdefghij' + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR a=38 + OR b=187 + } +} {1 17 19 22 27 38 53 57 59 79 88 99 scan 0 sort 0} +do_test where7-2.408.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=630 + OR a=55 + OR c=26026 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + } +} {10 23 55 68 76 77 78 scan 0 sort 0} +do_test where7-2.408.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=630 + OR a=55 + OR c=26026 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + } +} {10 23 55 68 76 77 78 scan 0 sort 0} +do_test where7-2.409.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='uvwxyzabc' + OR f='xyzabcdef' + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR ((a BETWEEN 51 AND 53) AND a!=52) + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR b=69 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + } +} {8 20 23 31 34 46 49 51 53 60 70 72 75 79 86 98 scan 0 sort 0} +do_test where7-2.409.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='uvwxyzabc' + OR f='xyzabcdef' + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR ((a BETWEEN 51 AND 53) AND a!=52) + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR b=69 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + } +} {8 20 23 31 34 46 49 51 53 60 70 72 75 79 86 98 scan 0 sort 0} +do_test where7-2.410.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1026 + OR b=454 + OR ((a BETWEEN 92 AND 94) AND a!=93) + OR b=179 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR f='qrstuvwxy' + } +} {16 26 42 52 68 78 92 94 scan 0 sort 0} +do_test where7-2.410.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1026 + OR b=454 + OR ((a BETWEEN 92 AND 94) AND a!=93) + OR b=179 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR f='qrstuvwxy' + } +} {16 26 42 52 68 78 92 94 scan 0 sort 0} +do_test where7-2.411.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 6 AND 8) AND a!=7) + OR b=619 + OR a=20 + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR b=946 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR a=64 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR b=1001 + OR b=858 + } +} {6 8 13 17 19 20 61 64 78 86 91 scan 0 sort 0} +do_test where7-2.411.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 6 AND 8) AND a!=7) + OR b=619 + OR a=20 + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR b=946 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR a=64 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR b=1001 + OR b=858 + } +} {6 8 13 17 19 20 61 64 78 86 91 scan 0 sort 0} +do_test where7-2.412.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=902 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR a=86 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + } +} {27 82 86 97 scan 0 sort 0} +do_test where7-2.412.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=902 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR a=86 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + } +} {27 82 86 97 scan 0 sort 0} +do_test where7-2.413.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=56.0 AND d<57.0 AND d NOT NULL) + OR a=32 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR c=32032 + } +} {4 32 38 56 94 95 96 scan 0 sort 0} +do_test where7-2.413.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=56.0 AND d<57.0 AND d NOT NULL) + OR a=32 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR c=32032 + } +} {4 32 38 56 94 95 96 scan 0 sort 0} +do_test where7-2.414.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=168 + OR c=2002 + OR b=77 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR f='qrstuvwxy' + } +} {4 5 6 7 16 27 42 68 94 scan 0 sort 0} +do_test where7-2.414.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=168 + OR c=2002 + OR b=77 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR f='qrstuvwxy' + } +} {4 5 6 7 16 27 42 68 94 scan 0 sort 0} +do_test where7-2.415.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='abcdefghi' + OR b=506 + } +} {26 46 52 78 scan 0 sort 0} +do_test where7-2.415.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='abcdefghi' + OR b=506 + } +} {26 46 52 78 scan 0 sort 0} +do_test where7-2.416.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=264 + OR c=34034 + OR a=96 + } +} {24 96 100 scan 0 sort 0} +do_test where7-2.416.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=264 + OR c=34034 + OR a=96 + } +} {24 96 100 scan 0 sort 0} +do_test where7-2.417.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=32.0 AND d<33.0 AND d NOT NULL) + OR a=27 + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + } +} {19 27 32 55 57 scan 0 sort 0} +do_test where7-2.417.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=32.0 AND d<33.0 AND d NOT NULL) + OR a=27 + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + } +} {19 27 32 55 57 scan 0 sort 0} +do_test where7-2.418.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=74.0 AND d<75.0 AND d NOT NULL) + OR b=77 + } +} {7 74 scan 0 sort 0} +do_test where7-2.418.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=74.0 AND d<75.0 AND d NOT NULL) + OR b=77 + } +} {7 74 scan 0 sort 0} +do_test where7-2.419.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=27027 + OR f='vwxyzabcd' + OR b=1048 + OR a=96 + OR a=99 + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR b=561 + OR b=352 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR a=95 + } +} {18 21 32 37 47 51 56 58 73 79 80 81 95 96 99 scan 0 sort 0} +do_test where7-2.419.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=27027 + OR f='vwxyzabcd' + OR b=1048 + OR a=96 + OR a=99 + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR b=561 + OR b=352 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR a=95 + } +} {18 21 32 37 47 51 56 58 73 79 80 81 95 96 99 scan 0 sort 0} +do_test where7-2.420.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=275 + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR f='ghijklmno' + OR b=619 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=476 + OR a=83 + OR ((a BETWEEN 47 AND 49) AND a!=48) + } +} {6 10 12 25 32 47 49 58 83 84 91 93 99 scan 0 sort 0} +do_test where7-2.420.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=275 + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR f='ghijklmno' + OR b=619 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=476 + OR a=83 + OR ((a BETWEEN 47 AND 49) AND a!=48) + } +} {6 10 12 25 32 47 49 58 83 84 91 93 99 scan 0 sort 0} +do_test where7-2.421.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=542 + OR a=17 + OR f='jklmnopqr' + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + OR a=23 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + } +} {5 7 9 17 23 25 35 39 61 87 scan 0 sort 0} +do_test where7-2.421.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=542 + OR a=17 + OR f='jklmnopqr' + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + OR a=23 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + } +} {5 7 9 17 23 25 35 39 61 87 scan 0 sort 0} +do_test where7-2.422.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=74.0 AND d<75.0 AND d NOT NULL) + OR b=363 + OR b=454 + } +} {33 74 scan 0 sort 0} +do_test where7-2.422.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=74.0 AND d<75.0 AND d NOT NULL) + OR b=363 + OR b=454 + } +} {33 74 scan 0 sort 0} +do_test where7-2.423.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1059 + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR (g='rqponml' AND f GLOB 'jklmn*') + OR b=47 + OR b=660 + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR a=84 + } +} {34 35 36 60 76 84 scan 0 sort 0} +do_test where7-2.423.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1059 + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR (g='rqponml' AND f GLOB 'jklmn*') + OR b=47 + OR b=660 + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR a=84 + } +} {34 35 36 60 76 84 scan 0 sort 0} +do_test where7-2.424.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='ghijklmno' + OR b=1012 + } +} {6 32 58 84 92 scan 0 sort 0} +do_test where7-2.424.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='ghijklmno' + OR b=1012 + } +} {6 32 58 84 92 scan 0 sort 0} +do_test where7-2.425.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=597 + OR f='lmnopqrst' + OR a=24 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR b=1023 + OR a=53 + OR a=78 + OR f='efghijklm' + OR (g='rqponml' AND f GLOB 'lmnop*') + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + } +} {4 11 24 30 31 33 37 53 56 63 78 82 85 89 93 96 scan 0 sort 0} +do_test where7-2.425.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=597 + OR f='lmnopqrst' + OR a=24 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR b=1023 + OR a=53 + OR a=78 + OR f='efghijklm' + OR (g='rqponml' AND f GLOB 'lmnop*') + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + } +} {4 11 24 30 31 33 37 53 56 63 78 82 85 89 93 96 scan 0 sort 0} +do_test where7-2.426.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=198 + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=388 + } +} {18 94 scan 0 sort 0} +do_test where7-2.426.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=198 + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=388 + } +} {18 94 scan 0 sort 0} +do_test where7-2.427.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='tuvwxyzab' + OR b=388 + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR b=957 + OR b=663 + OR b=847 + OR (g='jihgfed' AND f GLOB 'vwxyz*') + } +} {19 45 71 73 77 84 86 87 96 97 scan 0 sort 0} +do_test where7-2.427.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='tuvwxyzab' + OR b=388 + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR b=957 + OR b=663 + OR b=847 + OR (g='jihgfed' AND f GLOB 'vwxyz*') + } +} {19 45 71 73 77 84 86 87 96 97 scan 0 sort 0} +do_test where7-2.428.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=81.0 AND d<82.0 AND d NOT NULL) + OR a=56 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + } +} {56 81 84 scan 0 sort 0} +do_test where7-2.428.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=81.0 AND d<82.0 AND d NOT NULL) + OR a=56 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + } +} {56 81 84 scan 0 sort 0} +do_test where7-2.429.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c>=34035 + OR b=168 + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + } +} {1 27 53 79 89 scan 0 sort 0} +do_test where7-2.429.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c>=34035 + OR b=168 + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + } +} {1 27 53 79 89 scan 0 sort 0} +do_test where7-2.430.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 79 AND 81) AND a!=80) + OR b=564 + OR c=6006 + OR b=979 + } +} {16 17 18 79 81 89 scan 0 sort 0} +do_test where7-2.430.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 79 AND 81) AND a!=80) + OR b=564 + OR c=6006 + OR b=979 + } +} {16 17 18 79 81 89 scan 0 sort 0} +do_test where7-2.431.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=29.0 AND d<30.0 AND d NOT NULL) + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR f='rstuvwxyz' + OR (g='qponmlk' AND f GLOB 'nopqr*') + } +} {17 29 39 40 43 69 95 scan 0 sort 0} +do_test where7-2.431.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=29.0 AND d<30.0 AND d NOT NULL) + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR f='rstuvwxyz' + OR (g='qponmlk' AND f GLOB 'nopqr*') + } +} {17 29 39 40 43 69 95 scan 0 sort 0} +do_test where7-2.432.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=58 + OR b=484 + OR (d>=68.0 AND d<69.0 AND d NOT NULL) + OR b=671 + OR a=69 + } +} {44 61 68 69 scan 0 sort 0} +do_test where7-2.432.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=58 + OR b=484 + OR (d>=68.0 AND d<69.0 AND d NOT NULL) + OR b=671 + OR a=69 + } +} {44 61 68 69 scan 0 sort 0} +do_test where7-2.433.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='mnopqrstu' + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR b=861 + OR b=77 + OR f='qrstuvwxy' + } +} {7 12 16 38 42 64 68 73 90 94 scan 0 sort 0} +do_test where7-2.433.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='mnopqrstu' + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR b=861 + OR b=77 + OR f='qrstuvwxy' + } +} {7 12 16 38 42 64 68 73 90 94 scan 0 sort 0} +do_test where7-2.434.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=113 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR b=113 + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR ((a BETWEEN 62 AND 64) AND a!=63) + OR c=6006 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + OR b=946 + OR a=86 + } +} {4 14 16 17 18 51 62 64 86 scan 0 sort 0} +do_test where7-2.434.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=113 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR b=113 + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR ((a BETWEEN 62 AND 64) AND a!=63) + OR c=6006 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + OR b=946 + OR a=86 + } +} {4 14 16 17 18 51 62 64 86 scan 0 sort 0} +do_test where7-2.435.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'hijkl*') + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR c=22022 + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR c=25025 + } +} {8 10 64 65 66 73 74 75 79 81 85 scan 0 sort 0} +do_test where7-2.435.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'hijkl*') + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR c=22022 + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR c=25025 + } +} {8 10 64 65 66 73 74 75 79 81 85 scan 0 sort 0} +do_test where7-2.436.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 74 AND 76) AND a!=75) + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR b=47 + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR a=92 + OR b=795 + OR b=25 + OR c=7007 + OR a=93 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR (g='utsrqpo' AND f GLOB 'stuvw*') + } +} {14 18 19 20 21 40 44 46 66 74 76 92 93 95 scan 0 sort 0} +do_test where7-2.436.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 74 AND 76) AND a!=75) + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR b=47 + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR a=92 + OR b=795 + OR b=25 + OR c=7007 + OR a=93 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR (g='utsrqpo' AND f GLOB 'stuvw*') + } +} {14 18 19 20 21 40 44 46 66 74 76 92 93 95 scan 0 sort 0} +do_test where7-2.437.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'uvwxy*') + OR a=13 + OR (g='fedcbaz' AND f GLOB 'qrstu*') + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR c=29029 + OR b=311 + OR b=366 + OR a=94 + OR a=72 + } +} {6 13 66 72 85 86 87 94 scan 0 sort 0} +do_test where7-2.437.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'uvwxy*') + OR a=13 + OR (g='fedcbaz' AND f GLOB 'qrstu*') + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR c=29029 + OR b=311 + OR b=366 + OR a=94 + OR a=72 + } +} {6 13 66 72 85 86 87 94 scan 0 sort 0} +do_test where7-2.438.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=26026 + OR a=96 + OR a=22 + OR b=341 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR b=872 + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR ((a BETWEEN 25 AND 27) AND a!=26) + } +} {2 22 25 27 31 76 77 78 96 scan 0 sort 0} +do_test where7-2.438.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=26026 + OR a=96 + OR a=22 + OR b=341 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR b=872 + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR ((a BETWEEN 25 AND 27) AND a!=26) + } +} {2 22 25 27 31 76 77 78 96 scan 0 sort 0} +do_test where7-2.439.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=82.0 AND d<83.0 AND d NOT NULL) + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=41 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR (g='onmlkji' AND f GLOB 'zabcd*') + OR b=913 + } +} {6 23 36 41 51 63 65 82 83 scan 0 sort 0} +do_test where7-2.439.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=82.0 AND d<83.0 AND d NOT NULL) + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=41 + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR (g='onmlkji' AND f GLOB 'zabcd*') + OR b=913 + } +} {6 23 36 41 51 63 65 82 83 scan 0 sort 0} +do_test where7-2.440.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 42 AND 44) AND a!=43) + OR a=90 + } +} {42 44 90 scan 0 sort 0} +do_test where7-2.440.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 42 AND 44) AND a!=43) + OR a=90 + } +} {42 44 90 scan 0 sort 0} +do_test where7-2.441.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=44.0 AND d<45.0 AND d NOT NULL) + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR b=484 + } +} {21 44 scan 0 sort 0} +do_test where7-2.441.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=44.0 AND d<45.0 AND d NOT NULL) + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR b=484 + } +} {21 44 scan 0 sort 0} +do_test where7-2.442.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=22.0 AND d<23.0 AND d NOT NULL) + OR b=377 + OR b=363 + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR b=737 + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR b=506 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR a=16 + } +} {16 22 25 33 46 55 57 67 100 scan 0 sort 0} +do_test where7-2.442.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=22.0 AND d<23.0 AND d NOT NULL) + OR b=377 + OR b=363 + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR b=737 + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR b=506 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR a=16 + } +} {16 22 25 33 46 55 57 67 100 scan 0 sort 0} +do_test where7-2.443.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'zabcd*') + OR b=102 + OR b=212 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=487 + OR (g='ihgfedc' AND f GLOB 'efghi*') + } +} {37 77 82 scan 0 sort 0} +do_test where7-2.443.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'zabcd*') + OR b=102 + OR b=212 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=487 + OR (g='ihgfedc' AND f GLOB 'efghi*') + } +} {37 77 82 scan 0 sort 0} +do_test where7-2.444.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=154 + OR a=51 + OR b=520 + } +} {14 51 scan 0 sort 0} +do_test where7-2.444.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=154 + OR a=51 + OR b=520 + } +} {14 51 scan 0 sort 0} +do_test where7-2.445.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=872 + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR b=957 + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR a=67 + OR a=72 + } +} {21 42 47 58 60 67 72 73 87 99 scan 0 sort 0} +do_test where7-2.445.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=872 + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR b=957 + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR a=67 + OR a=72 + } +} {21 42 47 58 60 67 72 73 87 99 scan 0 sort 0} +do_test where7-2.446.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=66 + OR b=102 + OR b=396 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR ((a BETWEEN 7 AND 9) AND a!=8) + OR b=759 + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR f='ghijklmno' + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + } +} {6 7 9 14 32 36 58 69 84 90 92 97 100 scan 0 sort 0} +do_test where7-2.446.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=66 + OR b=102 + OR b=396 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR ((a BETWEEN 7 AND 9) AND a!=8) + OR b=759 + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR f='ghijklmno' + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + } +} {6 7 9 14 32 36 58 69 84 90 92 97 100 scan 0 sort 0} +do_test where7-2.447.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 69 AND 71) AND a!=70) + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR a=72 + OR b=1100 + OR b=102 + OR b=135 + } +} {24 48 50 69 71 72 76 100 scan 0 sort 0} +do_test where7-2.447.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 69 AND 71) AND a!=70) + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR a=72 + OR b=1100 + OR b=102 + OR b=135 + } +} {24 48 50 69 71 72 76 100 scan 0 sort 0} +do_test where7-2.448.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=99 + OR a=76 + } +} {9 76 scan 0 sort 0} +do_test where7-2.448.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=99 + OR a=76 + } +} {9 76 scan 0 sort 0} +do_test where7-2.449.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=891 + OR b=806 + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR b=861 + OR ((a BETWEEN 82 AND 84) AND a!=83) + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + } +} {19 34 81 82 84 85 87 scan 0 sort 0} +do_test where7-2.449.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=891 + OR b=806 + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR b=861 + OR ((a BETWEEN 82 AND 84) AND a!=83) + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + } +} {19 34 81 82 84 85 87 scan 0 sort 0} +do_test where7-2.450.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1034 + OR b=91 + } +} {94 scan 0 sort 0} +do_test where7-2.450.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1034 + OR b=91 + } +} {94 scan 0 sort 0} +do_test where7-2.451.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=47 + OR a=91 + OR d>1e10 + OR (g='srqponm' AND f GLOB 'cdefg*') + } +} {28 91 scan 0 sort 0} +do_test where7-2.451.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=47 + OR a=91 + OR d>1e10 + OR (g='srqponm' AND f GLOB 'cdefg*') + } +} {28 91 scan 0 sort 0} +do_test where7-2.452.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1023 + OR f='zabcdefgh' + OR b=451 + OR b=443 + OR c>=34035 + OR b=58 + } +} {25 41 51 77 93 scan 0 sort 0} +do_test where7-2.452.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1023 + OR f='zabcdefgh' + OR b=451 + OR b=443 + OR c>=34035 + OR b=58 + } +} {25 41 51 77 93 scan 0 sort 0} +do_test where7-2.453.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=971 + OR b=36 + OR a=11 + OR f='hijklmnop' + } +} {7 11 33 59 85 scan 0 sort 0} +do_test where7-2.453.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=971 + OR b=36 + OR a=11 + OR f='hijklmnop' + } +} {7 11 33 59 85 scan 0 sort 0} +do_test where7-2.454.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?efgh*' AND f GLOB 'defg*') + OR b=619 + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR c=11011 + OR b=550 + OR b=1059 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR b=737 + } +} {3 18 29 31 32 33 50 55 67 78 81 84 91 92 93 scan 0 sort 0} +do_test where7-2.454.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?efgh*' AND f GLOB 'defg*') + OR b=619 + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR c=11011 + OR b=550 + OR b=1059 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR b=737 + } +} {3 18 29 31 32 33 50 55 67 78 81 84 91 92 93 scan 0 sort 0} +do_test where7-2.455.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='edcbazy' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR a=78 + OR a=27 + OR b=792 + OR b=946 + OR c=22022 + OR a=23 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=388 + } +} {13 23 27 39 59 61 64 65 66 72 78 80 86 91 99 scan 0 sort 0} +do_test where7-2.455.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='edcbazy' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR a=78 + OR a=27 + OR b=792 + OR b=946 + OR c=22022 + OR a=23 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=388 + } +} {13 23 27 39 59 61 64 65 66 72 78 80 86 91 99 scan 0 sort 0} +do_test where7-2.456.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=32032 + OR f IS NULL + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR b=825 + } +} {4 37 39 74 75 94 95 96 scan 0 sort 0} +do_test where7-2.456.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=32032 + OR f IS NULL + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR b=825 + } +} {4 37 39 74 75 94 95 96 scan 0 sort 0} +do_test where7-2.457.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=84.0 AND d<85.0 AND d NOT NULL) + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR b=1078 + OR b=198 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR b=55 + OR b=517 + OR b=740 + } +} {5 7 18 21 47 54 67 73 84 98 99 scan 0 sort 0} +do_test where7-2.457.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=84.0 AND d<85.0 AND d NOT NULL) + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR b=1078 + OR b=198 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR b=55 + OR b=517 + OR b=740 + } +} {5 7 18 21 47 54 67 73 84 98 99 scan 0 sort 0} +do_test where7-2.458.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='wvutsrq' AND f GLOB 'ijklm*') + OR c=25025 + OR b=550 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'bcdef*') + } +} {8 22 50 53 73 74 75 scan 0 sort 0} +do_test where7-2.458.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='wvutsrq' AND f GLOB 'ijklm*') + OR c=25025 + OR b=550 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'bcdef*') + } +} {8 22 50 53 73 74 75 scan 0 sort 0} +do_test where7-2.459.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=432 + OR f='opqrstuvw' + OR (g='kjihgfe' AND f GLOB 'qrstu*') + } +} {14 40 66 68 92 scan 0 sort 0} +do_test where7-2.459.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=432 + OR f='opqrstuvw' + OR (g='kjihgfe' AND f GLOB 'qrstu*') + } +} {14 40 66 68 92 scan 0 sort 0} +do_test where7-2.460.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 14 AND 16) AND a!=15) + OR b=847 + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR b=583 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR b=938 + } +} {11 14 16 26 37 40 42 53 63 65 75 77 89 scan 0 sort 0} +do_test where7-2.460.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 14 AND 16) AND a!=15) + OR b=847 + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR b=583 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR b=938 + } +} {11 14 16 26 37 40 42 53 63 65 75 77 89 scan 0 sort 0} +do_test where7-2.461.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=671 + OR a=56 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR b=157 + OR a=83 + OR ((a BETWEEN 73 AND 75) AND a!=74) + OR c=21021 + OR b=319 + OR b=187 + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR b=839 + } +} {17 29 49 56 61 62 63 65 67 73 75 83 scan 0 sort 0} +do_test where7-2.461.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=671 + OR a=56 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR b=157 + OR a=83 + OR ((a BETWEEN 73 AND 75) AND a!=74) + OR c=21021 + OR b=319 + OR b=187 + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR b=839 + } +} {17 29 49 56 61 62 63 65 67 73 75 83 scan 0 sort 0} +do_test where7-2.462.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'uvwxy*') + OR b=586 + OR d<0.0 + OR c=9009 + } +} {25 26 27 72 scan 0 sort 0} +do_test where7-2.462.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'uvwxy*') + OR b=586 + OR d<0.0 + OR c=9009 + } +} {25 26 27 72 scan 0 sort 0} +do_test where7-2.463.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=82 + OR a=34 + OR f='jklmnopqr' + OR a=82 + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=454 + OR b=355 + OR c=21021 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=30 + } +} {9 16 30 34 35 61 62 63 65 82 87 scan 0 sort 0} +do_test where7-2.463.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=82 + OR a=34 + OR f='jklmnopqr' + OR a=82 + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=454 + OR b=355 + OR c=21021 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=30 + } +} {9 16 30 34 35 61 62 63 65 82 87 scan 0 sort 0} +do_test where7-2.464.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 44 AND 46) AND a!=45) + OR a=53 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR b=594 + OR b=80 + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR d>1e10 + } +} {18 20 23 44 46 49 53 54 scan 0 sort 0} +do_test where7-2.464.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 44 AND 46) AND a!=45) + OR a=53 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR b=594 + OR b=80 + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR d>1e10 + } +} {18 20 23 44 46 49 53 54 scan 0 sort 0} +do_test where7-2.465.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='opqrstuvw' + OR a=7 + } +} {7 14 40 66 92 scan 0 sort 0} +do_test where7-2.465.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='opqrstuvw' + OR a=7 + } +} {7 14 40 66 92 scan 0 sort 0} +do_test where7-2.466.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=627 + OR ((a BETWEEN 75 AND 77) AND a!=76) + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR a=90 + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + } +} {33 43 45 57 75 77 90 scan 0 sort 0} +do_test where7-2.466.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=627 + OR ((a BETWEEN 75 AND 77) AND a!=76) + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR a=90 + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + } +} {33 43 45 57 75 77 90 scan 0 sort 0} +do_test where7-2.467.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=59 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR f='wxyzabcde' + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR a=70 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {5 9 14 16 22 23 25 48 51 59 69 70 71 74 77 100 scan 0 sort 0} +do_test where7-2.467.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=59 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR f='wxyzabcde' + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR a=70 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {5 9 14 16 22 23 25 48 51 59 69 70 71 74 77 100 scan 0 sort 0} +do_test where7-2.468.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=69 + OR (g='ihgfedc' AND f GLOB 'defgh*') + } +} {69 81 scan 0 sort 0} +do_test where7-2.468.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=69 + OR (g='ihgfedc' AND f GLOB 'defgh*') + } +} {69 81 scan 0 sort 0} +do_test where7-2.469.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=41 + OR a=43 + OR a=92 + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR (g='mlkjihg' AND f GLOB 'klmno*') + } +} {41 43 62 92 95 scan 0 sort 0} +do_test where7-2.469.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=41 + OR a=43 + OR a=92 + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR (g='mlkjihg' AND f GLOB 'klmno*') + } +} {41 43 62 92 95 scan 0 sort 0} +do_test where7-2.470.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=300 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR b=935 + OR b=190 + } +} {52 85 scan 0 sort 0} +do_test where7-2.470.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=300 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR b=935 + OR b=190 + } +} {52 85 scan 0 sort 0} +do_test where7-2.471.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='fghijklmn' + OR f='fghijklmn' + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR b=465 + OR b=586 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR b=88 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR b=726 + OR ((a BETWEEN 51 AND 53) AND a!=52) + } +} {4 5 8 20 30 31 32 51 53 57 66 83 scan 0 sort 0} +do_test where7-2.471.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='fghijklmn' + OR f='fghijklmn' + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR b=465 + OR b=586 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR b=88 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR b=726 + OR ((a BETWEEN 51 AND 53) AND a!=52) + } +} {4 5 8 20 30 31 32 51 53 57 66 83 scan 0 sort 0} +do_test where7-2.472.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=34.0 AND d<35.0 AND d NOT NULL) + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR b=814 + OR a=20 + OR 1000000=34.0 AND d<35.0 AND d NOT NULL) + OR (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR b=814 + OR a=20 + OR 1000000=65.0 AND d<66.0 AND d NOT NULL) + OR c<=10 + OR a=92 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR ((a BETWEEN 0 AND 2) AND a!=1) + OR b=1026 + } +} {1 2 3 25 44 53 55 65 72 92 scan 0 sort 0} +do_test where7-2.473.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR c=1001 + OR b=484 + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + OR c<=10 + OR a=92 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR ((a BETWEEN 0 AND 2) AND a!=1) + OR b=1026 + } +} {1 2 3 25 44 53 55 65 72 92 scan 0 sort 0} +do_test where7-2.474.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=54 + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR b=993 + OR c=22022 + OR a=68 + OR ((a BETWEEN 99 AND 101) AND a!=100) + OR a=62 + OR (f GLOB '?efgh*' AND f GLOB 'defg*') + OR b=1015 + } +} {3 29 54 55 62 64 65 66 68 81 99 scan 0 sort 0} +do_test where7-2.474.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=54 + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR b=993 + OR c=22022 + OR a=68 + OR ((a BETWEEN 99 AND 101) AND a!=100) + OR a=62 + OR (f GLOB '?efgh*' AND f GLOB 'defg*') + OR b=1015 + } +} {3 29 54 55 62 64 65 66 68 81 99 scan 0 sort 0} +do_test where7-2.475.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=319 + OR a=50 + OR (g='srqponm' AND f GLOB 'defgh*') + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR a=96 + } +} {10 29 50 55 92 96 scan 0 sort 0} +do_test where7-2.475.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=319 + OR a=50 + OR (g='srqponm' AND f GLOB 'defgh*') + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR a=96 + } +} {10 29 50 55 92 96 scan 0 sort 0} +do_test where7-2.476.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=971 + OR c=18018 + OR b=564 + OR b=583 + OR b=80 + } +} {52 53 54 scan 0 sort 0} +do_test where7-2.476.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=971 + OR c=18018 + OR b=564 + OR b=583 + OR b=80 + } +} {52 53 54 scan 0 sort 0} +do_test where7-2.477.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=35.0 AND d<36.0 AND d NOT NULL) + OR b=1026 + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {14 16 35 scan 0 sort 0} +do_test where7-2.477.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=35.0 AND d<36.0 AND d NOT NULL) + OR b=1026 + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {14 16 35 scan 0 sort 0} +do_test where7-2.478.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ponmlkj' AND f GLOB 'uvwxy*') + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR b=407 + OR b=454 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR b=627 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + } +} {9 13 34 35 37 39 46 57 61 65 87 91 scan 0 sort 0} +do_test where7-2.478.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ponmlkj' AND f GLOB 'uvwxy*') + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR b=407 + OR b=454 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR b=627 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + } +} {9 13 34 35 37 39 46 57 61 65 87 91 scan 0 sort 0} +do_test where7-2.479.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=79.0 AND d<80.0 AND d NOT NULL) + OR c=34034 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR a=67 + } +} {6 18 20 24 26 32 58 67 79 84 100 scan 0 sort 0} +do_test where7-2.479.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=79.0 AND d<80.0 AND d NOT NULL) + OR c=34034 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR a=67 + } +} {6 18 20 24 26 32 58 67 79 84 100 scan 0 sort 0} +do_test where7-2.480.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=97 + OR b=575 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + } +} {1 2 4 16 42 68 81 94 97 scan 0 sort 0} +do_test where7-2.480.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=97 + OR b=575 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + } +} {1 2 4 16 42 68 81 94 97 scan 0 sort 0} +do_test where7-2.481.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=561 + OR b=773 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=201 + OR a=99 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR b=946 + OR b=993 + OR (g='fedcbaz' AND f GLOB 'qrstu*') + } +} {19 23 36 38 46 51 86 94 99 scan 0 sort 0} +do_test where7-2.481.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=561 + OR b=773 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=201 + OR a=99 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR b=946 + OR b=993 + OR (g='fedcbaz' AND f GLOB 'qrstu*') + } +} {19 23 36 38 46 51 86 94 99 scan 0 sort 0} +do_test where7-2.482.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=806 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR b=916 + OR b<0 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR b=154 + OR c=10010 + OR b=451 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + } +} {14 24 26 28 29 30 41 62 72 scan 0 sort 0} +do_test where7-2.482.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=806 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR b=916 + OR b<0 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR b=154 + OR c=10010 + OR b=451 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + } +} {14 24 26 28 29 30 41 62 72 scan 0 sort 0} +do_test where7-2.483.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=836 + OR d>1e10 + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR f='pqrstuvwx' + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR f='abcdefghi' + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR a=33 + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR b=476 + } +} {3 5 15 19 20 21 26 33 41 52 57 67 76 78 88 90 93 scan 0 sort 0} +do_test where7-2.483.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=836 + OR d>1e10 + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR f='pqrstuvwx' + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR f='abcdefghi' + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR a=33 + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR b=476 + } +} {3 5 15 19 20 21 26 33 41 52 57 67 76 78 88 90 93 scan 0 sort 0} +do_test where7-2.484.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=48 + OR a=92 + OR a=1 + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR (g='rqponml' AND f GLOB 'lmnop*') + OR b=905 + OR ((a BETWEEN 51 AND 53) AND a!=52) + } +} {1 4 7 28 30 37 48 51 53 56 82 92 scan 0 sort 0} +do_test where7-2.484.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=48 + OR a=92 + OR a=1 + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR (g='rqponml' AND f GLOB 'lmnop*') + OR b=905 + OR ((a BETWEEN 51 AND 53) AND a!=52) + } +} {1 4 7 28 30 37 48 51 53 56 82 92 scan 0 sort 0} +do_test where7-2.485.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR b=212 + OR a=42 + OR a=92 + } +} {4 17 42 92 scan 0 sort 0} +do_test where7-2.485.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR b=212 + OR a=42 + OR a=92 + } +} {4 17 42 92 scan 0 sort 0} +do_test where7-2.486.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=740 + OR b=564 + OR (g='onmlkji' AND f GLOB 'zabcd*') + OR a=11 + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR b=322 + OR (d>=6.0 AND d<7.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR b=902 + OR c>=34035 + } +} {6 11 22 44 46 51 82 scan 0 sort 0} +do_test where7-2.486.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=740 + OR b=564 + OR (g='onmlkji' AND f GLOB 'zabcd*') + OR a=11 + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR b=322 + OR (d>=6.0 AND d<7.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR b=902 + OR c>=34035 + } +} {6 11 22 44 46 51 82 scan 0 sort 0} +do_test where7-2.487.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 52 AND 54) AND a!=53) + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR a=27 + OR a=48 + OR b=927 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR f='abcdefghi' + OR b=91 + OR b=55 + } +} {5 8 26 27 48 52 54 56 58 78 89 91 96 scan 0 sort 0} +do_test where7-2.487.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 52 AND 54) AND a!=53) + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR a=27 + OR a=48 + OR b=927 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (g='fedcbaz' AND f GLOB 'stuvw*') + OR f='abcdefghi' + OR b=91 + OR b=55 + } +} {5 8 26 27 48 52 54 56 58 78 89 91 96 scan 0 sort 0} +do_test where7-2.488.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='srqponm' AND f GLOB 'efghi*') + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR a=20 + OR b=11 + } +} {1 20 30 88 90 scan 0 sort 0} +do_test where7-2.488.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='srqponm' AND f GLOB 'efghi*') + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR a=20 + OR b=11 + } +} {1 20 30 88 90 scan 0 sort 0} +do_test where7-2.489.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=27.0 AND d<28.0 AND d NOT NULL) + OR b=55 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR (g='onmlkji' AND f GLOB 'abcde*') + OR a=50 + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + } +} {5 13 27 50 51 52 64 73 scan 0 sort 0} +do_test where7-2.489.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=27.0 AND d<28.0 AND d NOT NULL) + OR b=55 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR (g='onmlkji' AND f GLOB 'abcde*') + OR a=50 + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + } +} {5 13 27 50 51 52 64 73 scan 0 sort 0} +do_test where7-2.490.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='rqponml' AND f GLOB 'ijklm*') + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + } +} {22 34 48 74 100 scan 0 sort 0} +do_test where7-2.490.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='rqponml' AND f GLOB 'ijklm*') + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + } +} {22 34 48 74 100 scan 0 sort 0} +do_test where7-2.491.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=704 + OR b=924 + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR b=113 + } +} {64 84 90 scan 0 sort 0} +do_test where7-2.491.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=704 + OR b=924 + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR b=113 + } +} {64 84 90 scan 0 sort 0} +do_test where7-2.492.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 20 AND 22) AND a!=21) + OR b=289 + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {14 16 20 22 scan 0 sort 0} +do_test where7-2.492.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 20 AND 22) AND a!=21) + OR b=289 + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {14 16 20 22 scan 0 sort 0} +do_test where7-2.493.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=935 + OR b=1001 + OR ((a BETWEEN 78 AND 80) AND a!=79) + OR a=31 + OR a=56 + } +} {31 56 78 80 85 91 scan 0 sort 0} +do_test where7-2.493.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=935 + OR b=1001 + OR ((a BETWEEN 78 AND 80) AND a!=79) + OR a=31 + OR a=56 + } +} {31 56 78 80 85 91 scan 0 sort 0} +do_test where7-2.494.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR b=726 + OR f='abcdefghi' + OR b=179 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=539 + OR b=66 + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + } +} {6 9 19 26 35 49 52 60 61 66 78 86 87 88 scan 0 sort 0} +do_test where7-2.494.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR b=726 + OR f='abcdefghi' + OR b=179 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=539 + OR b=66 + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + } +} {6 9 19 26 35 49 52 60 61 66 78 86 87 88 scan 0 sort 0} +do_test where7-2.495.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=179 + OR b=685 + } +} { scan 0 sort 0} +do_test where7-2.495.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=179 + OR b=685 + } +} { scan 0 sort 0} +do_test where7-2.496.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=201 + OR b=682 + OR b=443 + OR b=836 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + OR ((a BETWEEN 51 AND 53) AND a!=52) + OR b=110 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + } +} {2 10 11 13 28 39 51 53 54 62 65 76 80 91 scan 0 sort 0} +do_test where7-2.496.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=201 + OR b=682 + OR b=443 + OR b=836 + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + OR ((a BETWEEN 51 AND 53) AND a!=52) + OR b=110 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + } +} {2 10 11 13 28 39 51 53 54 62 65 76 80 91 scan 0 sort 0} +do_test where7-2.497.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR b=462 + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR a=22 + OR b=594 + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (g='mlkjihg' AND f GLOB 'jklmn*') + } +} {4 6 18 22 24 42 44 50 54 57 61 70 74 76 96 scan 0 sort 0} +do_test where7-2.497.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR b=462 + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR a=22 + OR b=594 + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (g='mlkjihg' AND f GLOB 'jklmn*') + } +} {4 6 18 22 24 42 44 50 54 57 61 70 74 76 96 scan 0 sort 0} +do_test where7-2.498.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='utsrqpo' AND f GLOB 'wxyza*') + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR f='vwxyzabcd' + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR a=37 + OR a=50 + } +} {1 10 13 21 22 37 47 50 73 99 scan 0 sort 0} +do_test where7-2.498.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='utsrqpo' AND f GLOB 'wxyza*') + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR f='vwxyzabcd' + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR a=37 + OR a=50 + } +} {1 10 13 21 22 37 47 50 73 99 scan 0 sort 0} +do_test where7-2.499.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 83 AND 85) AND a!=84) + OR b=784 + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + OR b=825 + OR a=80 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR b=531 + OR a=100 + } +} {20 23 46 72 75 80 83 85 97 98 100 scan 0 sort 0} +do_test where7-2.499.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 83 AND 85) AND a!=84) + OR b=784 + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + OR b=825 + OR a=80 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR b=531 + OR a=100 + } +} {20 23 46 72 75 80 83 85 97 98 100 scan 0 sort 0} +do_test where7-2.500.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=220 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + } +} {19 20 53 scan 0 sort 0} +do_test where7-2.500.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='utsrqpo' AND f GLOB 'tuvwx*') + OR b=220 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + } +} {19 20 53 scan 0 sort 0} +do_test where7-2.501.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=92 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR b=990 + } +} {9 90 92 scan 0 sort 0} +do_test where7-2.501.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=92 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR b=990 + } +} {9 90 92 scan 0 sort 0} +do_test where7-2.502.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 77 AND 79) AND a!=78) + OR b=894 + OR c=28028 + OR b=905 + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR b=1037 + } +} {26 45 52 70 77 78 79 82 83 84 scan 0 sort 0} +do_test where7-2.502.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 77 AND 79) AND a!=78) + OR b=894 + OR c=28028 + OR b=905 + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR b=1037 + } +} {26 45 52 70 77 78 79 82 83 84 scan 0 sort 0} +do_test where7-2.503.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=72.0 AND d<73.0 AND d NOT NULL) + OR b=773 + OR f='defghijkl' + } +} {3 29 55 72 81 scan 0 sort 0} +do_test where7-2.503.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=72.0 AND d<73.0 AND d NOT NULL) + OR b=773 + OR f='defghijkl' + } +} {3 29 55 72 81 scan 0 sort 0} +do_test where7-2.504.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=861 + OR (g='rqponml' AND f GLOB 'lmnop*') + } +} {12 37 scan 0 sort 0} +do_test where7-2.504.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=861 + OR (g='rqponml' AND f GLOB 'lmnop*') + } +} {12 37 scan 0 sort 0} +do_test where7-2.505.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=704 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR b=25 + OR (g='jihgfed' AND f GLOB 'zabcd*') + OR b=487 + OR (g='hgfedcb' AND f GLOB 'fghij*') + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (d>=84.0 AND d<85.0 AND d NOT NULL) + } +} {10 23 51 64 77 79 83 84 89 scan 0 sort 0} +do_test where7-2.505.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=704 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR b=25 + OR (g='jihgfed' AND f GLOB 'zabcd*') + OR b=487 + OR (g='hgfedcb' AND f GLOB 'fghij*') + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (d>=84.0 AND d<85.0 AND d NOT NULL) + } +} {10 23 51 64 77 79 83 84 89 scan 0 sort 0} +do_test where7-2.506.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=19 + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR b=674 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR b=355 + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR c=28028 + OR b=649 + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR (g='srqponm' AND f GLOB 'fghij*') + } +} {17 19 31 41 49 59 60 72 74 82 83 84 scan 0 sort 0} +do_test where7-2.506.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=19 + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR b=674 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR b=355 + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR c=28028 + OR b=649 + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR (g='srqponm' AND f GLOB 'fghij*') + } +} {17 19 31 41 49 59 60 72 74 82 83 84 scan 0 sort 0} +do_test where7-2.507.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 76 AND 78) AND a!=77) + OR a=1 + OR a=22 + OR b=836 + OR c=24024 + } +} {1 22 70 71 72 76 78 scan 0 sort 0} +do_test where7-2.507.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 76 AND 78) AND a!=77) + OR a=1 + OR a=22 + OR b=836 + OR c=24024 + } +} {1 22 70 71 72 76 78 scan 0 sort 0} +do_test where7-2.508.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=135 + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 39 AND 41) AND a!=40) + } +} {20 39 41 scan 0 sort 0} +do_test where7-2.508.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=135 + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 39 AND 41) AND a!=40) + } +} {20 39 41 scan 0 sort 0} +do_test where7-2.509.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'ijklm*') + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + } +} {9 35 61 86 87 scan 0 sort 0} +do_test where7-2.509.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'ijklm*') + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + } +} {9 35 61 86 87 scan 0 sort 0} +do_test where7-2.510.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'wxyza*') + OR f='ghijklmno' + } +} {6 32 58 74 84 scan 0 sort 0} +do_test where7-2.510.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'wxyza*') + OR f='ghijklmno' + } +} {6 32 58 74 84 scan 0 sort 0} +do_test where7-2.511.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=825 + OR b=902 + OR a=40 + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR a=30 + OR a=10 + OR a=73 + } +} {10 28 30 40 73 75 82 scan 0 sort 0} +do_test where7-2.511.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=825 + OR b=902 + OR a=40 + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR a=30 + OR a=10 + OR a=73 + } +} {10 28 30 40 73 75 82 scan 0 sort 0} +do_test where7-2.512.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 22 AND 24) AND a!=23) + OR a=5 + OR b=432 + OR b=979 + OR b=762 + OR b=352 + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR c=27027 + OR c=20020 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + } +} {5 22 23 24 32 36 38 58 59 60 79 80 81 89 scan 0 sort 0} +do_test where7-2.512.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 22 AND 24) AND a!=23) + OR a=5 + OR b=432 + OR b=979 + OR b=762 + OR b=352 + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR c=27027 + OR c=20020 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + } +} {5 22 23 24 32 36 38 58 59 60 79 80 81 89 scan 0 sort 0} +do_test where7-2.513.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?lmno*' AND f GLOB 'klmn*') + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR b=99 + OR a=54 + } +} {5 7 9 10 36 54 62 88 scan 0 sort 0} +do_test where7-2.513.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?lmno*' AND f GLOB 'klmn*') + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR b=99 + OR a=54 + } +} {5 7 9 10 36 54 62 88 scan 0 sort 0} +do_test where7-2.514.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=300 + OR (g='mlkjihg' AND f GLOB 'klmno*') + OR b=319 + OR f='fghijklmn' + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR ((a BETWEEN 42 AND 44) AND a!=43) + } +} {5 29 31 42 44 57 62 73 83 scan 0 sort 0} +do_test where7-2.514.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=300 + OR (g='mlkjihg' AND f GLOB 'klmno*') + OR b=319 + OR f='fghijklmn' + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR ((a BETWEEN 42 AND 44) AND a!=43) + } +} {5 29 31 42 44 57 62 73 83 scan 0 sort 0} +do_test where7-2.515.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=671 + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR b=1004 + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR b=748 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + } +} {5 7 18 20 23 27 61 68 82 86 88 scan 0 sort 0} +do_test where7-2.515.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=671 + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR b=1004 + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR b=748 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + } +} {5 7 18 20 23 27 61 68 82 86 88 scan 0 sort 0} +do_test where7-2.516.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=47 + OR b=784 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR a=16 + OR a=25 + OR b=572 + } +} {16 21 23 25 47 52 scan 0 sort 0} +do_test where7-2.516.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=47 + OR b=784 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR a=16 + OR a=25 + OR b=572 + } +} {16 21 23 25 47 52 scan 0 sort 0} +do_test where7-2.517.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'wxyza*') + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR b=110 + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR c=26026 + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR b=850 + OR a=6 + } +} {6 10 67 69 74 76 77 78 91 scan 0 sort 0} +do_test where7-2.517.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'wxyza*') + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR b=110 + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR c=26026 + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR b=850 + OR a=6 + } +} {6 10 67 69 74 76 77 78 91 scan 0 sort 0} +do_test where7-2.518.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 74 AND 76) AND a!=75) + OR ((a BETWEEN 1 AND 3) AND a!=2) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR (g='mlkjihg' AND f GLOB 'klmno*') + OR b=135 + OR a=28 + OR ((a BETWEEN 1 AND 3) AND a!=2) + OR b=737 + } +} {1 3 19 28 62 67 74 76 scan 0 sort 0} +do_test where7-2.518.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 74 AND 76) AND a!=75) + OR ((a BETWEEN 1 AND 3) AND a!=2) + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR (g='mlkjihg' AND f GLOB 'klmno*') + OR b=135 + OR a=28 + OR ((a BETWEEN 1 AND 3) AND a!=2) + OR b=737 + } +} {1 3 19 28 62 67 74 76 scan 0 sort 0} +do_test where7-2.519.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=242 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR ((a BETWEEN 20 AND 22) AND a!=21) + } +} {20 22 scan 0 sort 0} +do_test where7-2.519.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=242 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR ((a BETWEEN 20 AND 22) AND a!=21) + } +} {20 22 scan 0 sort 0} +do_test where7-2.520.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=528 + OR a=41 + OR f='cdefghijk' + OR a=98 + OR b=759 + OR a=43 + OR b=286 + OR f='hijklmnop' + } +} {2 7 26 28 33 41 43 48 54 59 69 80 85 98 scan 0 sort 0} +do_test where7-2.520.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=528 + OR a=41 + OR f='cdefghijk' + OR a=98 + OR b=759 + OR a=43 + OR b=286 + OR f='hijklmnop' + } +} {2 7 26 28 33 41 43 48 54 59 69 80 85 98 scan 0 sort 0} +do_test where7-2.521.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'ghijk*') + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR a=52 + } +} {6 15 52 61 scan 0 sort 0} +do_test where7-2.521.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'ghijk*') + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR a=52 + } +} {6 15 52 61 scan 0 sort 0} +do_test where7-2.522.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ihgfedc' AND f GLOB 'abcde*') + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR a=86 + OR c=33033 + OR c=2002 + OR a=92 + } +} {2 4 5 6 78 86 92 97 98 99 scan 0 sort 0} +do_test where7-2.522.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ihgfedc' AND f GLOB 'abcde*') + OR ((a BETWEEN 2 AND 4) AND a!=3) + OR a=86 + OR c=33033 + OR c=2002 + OR a=92 + } +} {2 4 5 6 78 86 92 97 98 99 scan 0 sort 0} +do_test where7-2.523.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 47 AND 49) AND a!=48) + OR b=517 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR (g='srqponm' AND f GLOB 'fghij*') + OR f='defghijkl' + OR b=707 + OR c>=34035 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR a=80 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + } +} {3 23 29 31 33 35 47 49 55 63 67 69 80 81 scan 0 sort 0} +do_test where7-2.523.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 47 AND 49) AND a!=48) + OR b=517 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR (g='srqponm' AND f GLOB 'fghij*') + OR f='defghijkl' + OR b=707 + OR c>=34035 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR a=80 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + } +} {3 23 29 31 33 35 47 49 55 63 67 69 80 81 scan 0 sort 0} +do_test where7-2.524.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=209 + OR b=399 + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + } +} {19 96 97 scan 0 sort 0} +do_test where7-2.524.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=209 + OR b=399 + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + } +} {19 96 97 scan 0 sort 0} +do_test where7-2.525.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 18 AND 20) AND a!=19) + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR b=597 + OR a=95 + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR b=432 + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + } +} {18 20 24 38 50 55 76 92 95 scan 0 sort 0} +do_test where7-2.525.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 18 AND 20) AND a!=19) + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR b=597 + OR a=95 + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR b=432 + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + } +} {18 20 24 38 50 55 76 92 95 scan 0 sort 0} +do_test where7-2.526.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=88.0 AND d<89.0 AND d NOT NULL) + OR b=157 + OR ((a BETWEEN 78 AND 80) AND a!=79) + OR a=3 + OR b=663 + OR a=2 + OR c=21021 + OR b=330 + OR b=231 + OR (g='tsrqpon' AND f GLOB 'bcdef*') + } +} {2 3 21 27 30 61 62 63 78 80 88 scan 0 sort 0} +do_test where7-2.526.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=88.0 AND d<89.0 AND d NOT NULL) + OR b=157 + OR ((a BETWEEN 78 AND 80) AND a!=79) + OR a=3 + OR b=663 + OR a=2 + OR c=21021 + OR b=330 + OR b=231 + OR (g='tsrqpon' AND f GLOB 'bcdef*') + } +} {2 3 21 27 30 61 62 63 78 80 88 scan 0 sort 0} +do_test where7-2.527.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'fghij*') + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR f IS NULL + } +} {64 66 83 scan 0 sort 0} +do_test where7-2.527.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'fghij*') + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR f IS NULL + } +} {64 66 83 scan 0 sort 0} +do_test where7-2.528.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 99 AND 101) AND a!=100) + OR (g='fedcbaz' AND f GLOB 'pqrst*') + OR 1000000=54.0 AND d<55.0 AND d NOT NULL) + OR b=814 + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR b=619 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + } +} {46 53 54 55 58 74 80 scan 0 sort 0} +do_test where7-2.530.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='nmlkjih' AND f GLOB 'defgh*') + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR b=784 + OR b=583 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR b=814 + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR b=619 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + } +} {46 53 54 55 58 74 80 scan 0 sort 0} +do_test where7-2.531.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=86 + OR b=484 + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR b=418 + OR b=509 + OR a=42 + OR b=825 + OR a=91 + OR b=1023 + OR b=814 + OR ((a BETWEEN 99 AND 101) AND a!=100) + } +} {38 42 44 74 75 79 86 91 93 99 scan 0 sort 0} +do_test where7-2.531.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=86 + OR b=484 + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR b=418 + OR b=509 + OR a=42 + OR b=825 + OR a=91 + OR b=1023 + OR b=814 + OR ((a BETWEEN 99 AND 101) AND a!=100) + } +} {38 42 44 74 75 79 86 91 93 99 scan 0 sort 0} +do_test where7-2.532.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=86.0 AND d<87.0 AND d NOT NULL) + OR b=231 + OR a=81 + OR a=72 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR b=396 + } +} {21 24 26 36 72 81 86 scan 0 sort 0} +do_test where7-2.532.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=86.0 AND d<87.0 AND d NOT NULL) + OR b=231 + OR a=81 + OR a=72 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR b=396 + } +} {21 24 26 36 72 81 86 scan 0 sort 0} +do_test where7-2.533.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=74.0 AND d<75.0 AND d NOT NULL) + OR a=63 + OR ((a BETWEEN 70 AND 72) AND a!=71) + OR a=71 + OR b=22 + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR a=53 + } +} {2 21 53 59 61 63 70 71 72 74 76 78 scan 0 sort 0} +do_test where7-2.533.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=74.0 AND d<75.0 AND d NOT NULL) + OR a=63 + OR ((a BETWEEN 70 AND 72) AND a!=71) + OR a=71 + OR b=22 + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR a=53 + } +} {2 21 53 59 61 63 70 71 72 74 76 78 scan 0 sort 0} +do_test where7-2.534.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=861 + OR b=649 + OR b=146 + OR f='abcdefghi' + } +} {26 52 59 78 scan 0 sort 0} +do_test where7-2.534.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=861 + OR b=649 + OR b=146 + OR f='abcdefghi' + } +} {26 52 59 78 scan 0 sort 0} +do_test where7-2.535.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR c=5005 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR a=93 + OR c=24024 + OR b=619 + OR b=234 + OR b=55 + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + } +} {5 9 13 14 15 21 35 47 50 52 56 61 70 71 72 73 87 93 99 scan 0 sort 0} +do_test where7-2.535.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR c=5005 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR a=93 + OR c=24024 + OR b=619 + OR b=234 + OR b=55 + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + } +} {5 9 13 14 15 21 35 47 50 52 56 61 70 71 72 73 87 93 99 scan 0 sort 0} +do_test where7-2.536.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=355 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=806 + OR b=462 + OR b=531 + OR (g='lkjihgf' AND f GLOB 'lmnop*') + OR f='mnopqrstu' + } +} {12 38 42 49 63 64 69 90 scan 0 sort 0} +do_test where7-2.536.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=355 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=806 + OR b=462 + OR b=531 + OR (g='lkjihgf' AND f GLOB 'lmnop*') + OR f='mnopqrstu' + } +} {12 38 42 49 63 64 69 90 scan 0 sort 0} +do_test where7-2.537.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 60 AND 62) AND a!=61) + OR f='pqrstuvwx' + OR (g='nmlkjih' AND f GLOB 'efghi*') + OR b=495 + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR a=75 + } +} {15 41 45 56 60 62 67 70 75 93 scan 0 sort 0} +do_test where7-2.537.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 60 AND 62) AND a!=61) + OR f='pqrstuvwx' + OR (g='nmlkjih' AND f GLOB 'efghi*') + OR b=495 + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR a=75 + } +} {15 41 45 56 60 62 67 70 75 93 scan 0 sort 0} +do_test where7-2.538.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'efghi*') + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR b=748 + OR b=913 + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR a=22 + } +} {4 5 21 22 68 83 scan 0 sort 0} +do_test where7-2.538.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'efghi*') + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR b=748 + OR b=913 + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR a=22 + } +} {4 5 21 22 68 83 scan 0 sort 0} +do_test where7-2.539.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=19 + OR b=902 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR b=168 + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR a=50 + OR f='uvwxyzabc' + OR b=836 + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR a=50 + } +} {19 20 46 50 63 65 67 72 76 77 79 82 98 scan 0 sort 0} +do_test where7-2.539.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=19 + OR b=902 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR b=168 + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR a=50 + OR f='uvwxyzabc' + OR b=836 + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR a=50 + } +} {19 20 46 50 63 65 67 72 76 77 79 82 98 scan 0 sort 0} +do_test where7-2.540.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=12012 + OR b=993 + OR b=839 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR a=87 + } +} {30 32 34 35 36 87 scan 0 sort 0} +do_test where7-2.540.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=12012 + OR b=993 + OR b=839 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR a=87 + } +} {30 32 34 35 36 87 scan 0 sort 0} +do_test where7-2.541.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=814 + OR c=30030 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR a=16 + OR b=1048 + OR b=113 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR b=729 + OR a=54 + } +} {3 16 34 40 54 61 74 88 89 90 scan 0 sort 0} +do_test where7-2.541.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=814 + OR c=30030 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR a=16 + OR b=1048 + OR b=113 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR b=729 + OR a=54 + } +} {3 16 34 40 54 61 74 88 89 90 scan 0 sort 0} +do_test where7-2.542.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=399 + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=814 + OR c=22022 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR a=1 + OR b=311 + OR b=121 + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=198 + } +} {1 6 8 11 18 32 37 58 63 64 65 66 71 74 84 89 scan 0 sort 0} +do_test where7-2.542.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=399 + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=814 + OR c=22022 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR a=1 + OR b=311 + OR b=121 + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=198 + } +} {1 6 8 11 18 32 37 58 63 64 65 66 71 74 84 89 scan 0 sort 0} +do_test where7-2.543.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=146 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR a=57 + } +} {52 57 scan 0 sort 0} +do_test where7-2.543.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=146 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR a=57 + } +} {52 57 scan 0 sort 0} +do_test where7-2.544.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=100.0 AND d<101.0 AND d NOT NULL) + OR f='fghijklmn' + OR a=70 + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + } +} {4 5 31 57 70 83 100 scan 0 sort 0} +do_test where7-2.544.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=100.0 AND d<101.0 AND d NOT NULL) + OR f='fghijklmn' + OR a=70 + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + } +} {4 5 31 57 70 83 100 scan 0 sort 0} +do_test where7-2.545.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=42 + OR b=333 + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + OR b=1089 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR a=22 + OR b=594 + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + } +} {5 12 15 22 31 35 42 54 57 83 99 scan 0 sort 0} +do_test where7-2.545.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=42 + OR b=333 + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + OR b=1089 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR a=22 + OR b=594 + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + } +} {5 12 15 22 31 35 42 54 57 83 99 scan 0 sort 0} +do_test where7-2.546.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=67.0 AND d<68.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=113 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR f='mnopqrstu' + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR b=902 + } +} {3 5 12 16 17 25 26 38 52 64 67 69 78 82 90 scan 0 sort 0} +do_test where7-2.546.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=67.0 AND d<68.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=113 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR f='mnopqrstu' + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR b=902 + } +} {3 5 12 16 17 25 26 38 52 64 67 69 78 82 90 scan 0 sort 0} +do_test where7-2.547.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='onmlkji' AND f GLOB 'zabcd*') + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR a=13 + } +} {13 15 41 51 67 93 scan 0 sort 0} +do_test where7-2.547.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='onmlkji' AND f GLOB 'zabcd*') + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR a=13 + } +} {13 15 41 51 67 93 scan 0 sort 0} +do_test where7-2.548.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='edcbazy' AND f GLOB 'wxyza*') + OR b=410 + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR b=418 + OR (g='gfedcba' AND f GLOB 'klmno*') + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + } +} {38 65 82 88 100 scan 0 sort 0} +do_test where7-2.548.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='edcbazy' AND f GLOB 'wxyza*') + OR b=410 + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR b=418 + OR (g='gfedcba' AND f GLOB 'klmno*') + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + } +} {38 65 82 88 100 scan 0 sort 0} +do_test where7-2.549.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=5 + OR a=95 + OR a=56 + OR a=46 + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR (d>=41.0 AND d<42.0 AND d NOT NULL) + } +} {5 10 41 46 56 61 95 100 scan 0 sort 0} +do_test where7-2.549.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=5 + OR a=95 + OR a=56 + OR a=46 + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR (d>=41.0 AND d<42.0 AND d NOT NULL) + } +} {5 10 41 46 56 61 95 100 scan 0 sort 0} +do_test where7-2.550.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=87.0 AND d<88.0 AND d NOT NULL) + OR a=13 + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR a=9 + OR a=27 + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=484 + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR b=594 + } +} {9 13 27 37 44 54 75 87 88 90 scan 0 sort 0} +do_test where7-2.550.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=87.0 AND d<88.0 AND d NOT NULL) + OR a=13 + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR a=9 + OR a=27 + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=484 + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR b=594 + } +} {9 13 27 37 44 54 75 87 88 90 scan 0 sort 0} +do_test where7-2.551.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=539 + OR b=418 + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR b=759 + } +} {15 38 49 69 scan 0 sort 0} +do_test where7-2.551.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=539 + OR b=418 + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR b=759 + } +} {15 38 49 69 scan 0 sort 0} +do_test where7-2.552.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1001 + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR c=34034 + OR a=84 + } +} {8 54 84 91 100 scan 0 sort 0} +do_test where7-2.552.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1001 + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR c=34034 + OR a=84 + } +} {8 54 84 91 100 scan 0 sort 0} +do_test where7-2.553.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=795 + OR b=671 + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR ((a BETWEEN 71 AND 73) AND a!=72) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR b=322 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR c=34034 + OR b=410 + } +} {15 38 41 60 61 63 67 71 73 93 100 scan 0 sort 0} +do_test where7-2.553.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=795 + OR b=671 + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR ((a BETWEEN 71 AND 73) AND a!=72) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR b=322 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR c=34034 + OR b=410 + } +} {15 38 41 60 61 63 67 71 73 93 100 scan 0 sort 0} +do_test where7-2.554.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=13013 + OR (g='fedcbaz' AND f GLOB 'qrstu*') + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=47 + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=828 + } +} {37 38 39 42 61 69 79 94 scan 0 sort 0} +do_test where7-2.554.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=13013 + OR (g='fedcbaz' AND f GLOB 'qrstu*') + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=47 + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=828 + } +} {37 38 39 42 61 69 79 94 scan 0 sort 0} +do_test where7-2.555.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=451 + OR b=836 + OR (g='onmlkji' AND f GLOB 'wxyza*') + } +} {41 48 76 scan 0 sort 0} +do_test where7-2.555.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=451 + OR b=836 + OR (g='onmlkji' AND f GLOB 'wxyza*') + } +} {41 48 76 scan 0 sort 0} +do_test where7-2.556.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=575 + OR b=748 + OR b=520 + OR b=154 + OR a=70 + OR f='efghijklm' + } +} {4 14 30 56 68 70 82 scan 0 sort 0} +do_test where7-2.556.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=575 + OR b=748 + OR b=520 + OR b=154 + OR a=70 + OR f='efghijklm' + } +} {4 14 30 56 68 70 82 scan 0 sort 0} +do_test where7-2.557.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='tuvwxyzab' + OR (g='nmlkjih' AND f GLOB 'efghi*') + } +} {19 45 56 71 97 scan 0 sort 0} +do_test where7-2.557.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='tuvwxyzab' + OR (g='nmlkjih' AND f GLOB 'efghi*') + } +} {19 45 56 71 97 scan 0 sort 0} +do_test where7-2.558.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=806 + OR a=47 + OR d<0.0 + OR b=982 + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'jklmn*') + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR e IS NULL + OR c=32032 + OR b=795 + } +} {2 12 47 87 94 95 96 97 99 scan 0 sort 0} +do_test where7-2.558.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=806 + OR a=47 + OR d<0.0 + OR b=982 + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'jklmn*') + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR e IS NULL + OR c=32032 + OR b=795 + } +} {2 12 47 87 94 95 96 97 99 scan 0 sort 0} +do_test where7-2.559.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=62 + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (g='edcbazy' AND f GLOB 'vwxyz*') + } +} {23 49 62 75 89 91 99 scan 0 sort 0} +do_test where7-2.559.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=62 + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR (g='edcbazy' AND f GLOB 'vwxyz*') + } +} {23 49 62 75 89 91 99 scan 0 sort 0} +do_test where7-2.560.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=57.0 AND d<58.0 AND d NOT NULL) + OR b=1056 + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR b=729 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR b=220 + OR b=498 + OR ((a BETWEEN 96 AND 98) AND a!=97) + } +} {9 20 57 73 96 98 scan 0 sort 0} +do_test where7-2.560.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=57.0 AND d<58.0 AND d NOT NULL) + OR b=1056 + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR b=729 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR b=220 + OR b=498 + OR ((a BETWEEN 96 AND 98) AND a!=97) + } +} {9 20 57 73 96 98 scan 0 sort 0} +do_test where7-2.561.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=44 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR (g='wvutsrq' AND f GLOB 'klmno*') + } +} {4 10 38 scan 0 sort 0} +do_test where7-2.561.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=44 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR (g='wvutsrq' AND f GLOB 'klmno*') + } +} {4 10 38 scan 0 sort 0} +do_test where7-2.562.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=883 + OR b=311 + OR b=880 + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR a=88 + OR b=154 + OR a=94 + OR a=37 + OR c=31031 + } +} {14 37 41 57 59 80 88 91 92 93 94 scan 0 sort 0} +do_test where7-2.562.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=883 + OR b=311 + OR b=880 + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR a=88 + OR b=154 + OR a=94 + OR a=37 + OR c=31031 + } +} {14 37 41 57 59 80 88 91 92 93 94 scan 0 sort 0} +do_test where7-2.563.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='onmlkji' AND f GLOB 'xyzab*') + OR a=10 + OR b=190 + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR b=385 + OR a=82 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR c=22022 + } +} {8 10 35 49 55 63 64 65 66 67 69 82 90 scan 0 sort 0} +do_test where7-2.563.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='onmlkji' AND f GLOB 'xyzab*') + OR a=10 + OR b=190 + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR b=385 + OR a=82 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR c=22022 + } +} {8 10 35 49 55 63 64 65 66 67 69 82 90 scan 0 sort 0} +do_test where7-2.564.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1070 + OR a=33 + OR b=363 + OR a=47 + } +} {33 47 scan 0 sort 0} +do_test where7-2.564.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1070 + OR a=33 + OR b=363 + OR a=47 + } +} {33 47 scan 0 sort 0} +do_test where7-2.565.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=1001 + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=49 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR c=33033 + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR g IS NULL + OR b=220 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + } +} {1 2 3 18 20 33 35 49 60 62 63 65 70 81 97 98 99 scan 0 sort 0} +do_test where7-2.565.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=1001 + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=49 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR c=33033 + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR g IS NULL + OR b=220 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + } +} {1 2 3 18 20 33 35 49 60 62 63 65 70 81 97 98 99 scan 0 sort 0} +do_test where7-2.566.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=212 + OR b=418 + OR ((a BETWEEN 31 AND 33) AND a!=32) + } +} {31 33 38 71 scan 0 sort 0} +do_test where7-2.566.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=212 + OR b=418 + OR ((a BETWEEN 31 AND 33) AND a!=32) + } +} {31 33 38 71 scan 0 sort 0} +do_test where7-2.567.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=344 + OR f='nopqrstuv' + OR b=704 + OR a=84 + } +} {13 39 64 65 84 91 scan 0 sort 0} +do_test where7-2.567.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=344 + OR f='nopqrstuv' + OR b=704 + OR a=84 + } +} {13 39 64 65 84 91 scan 0 sort 0} +do_test where7-2.568.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 30 AND 32) AND a!=31) + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + } +} {5 30 32 scan 0 sort 0} +do_test where7-2.568.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 30 AND 32) AND a!=31) + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + } +} {5 30 32 scan 0 sort 0} +do_test where7-2.569.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'jklmn*') + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + } +} {26 52 78 87 scan 0 sort 0} +do_test where7-2.569.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'jklmn*') + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + } +} {26 52 78 87 scan 0 sort 0} +do_test where7-2.570.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 0 AND 2) AND a!=1) + OR b=1100 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR b=421 + OR b=465 + OR b=894 + OR c=13013 + OR b=47 + OR b=674 + OR ((a BETWEEN 0 AND 2) AND a!=1) + } +} {2 37 38 39 70 100 scan 0 sort 0} +do_test where7-2.570.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 0 AND 2) AND a!=1) + OR b=1100 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR b=421 + OR b=465 + OR b=894 + OR c=13013 + OR b=47 + OR b=674 + OR ((a BETWEEN 0 AND 2) AND a!=1) + } +} {2 37 38 39 70 100 scan 0 sort 0} +do_test where7-2.571.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=18018 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR b=410 + OR b=858 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + } +} {49 52 53 54 78 scan 0 sort 0} +do_test where7-2.571.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=18018 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR b=410 + OR b=858 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + } +} {49 52 53 54 78 scan 0 sort 0} +do_test where7-2.572.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ponmlkj' AND f GLOB 'vwxyz*') + OR b=781 + } +} {47 71 scan 0 sort 0} +do_test where7-2.572.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ponmlkj' AND f GLOB 'vwxyz*') + OR b=781 + } +} {47 71 scan 0 sort 0} +do_test where7-2.573.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1070 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR a=54 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR a=9 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + } +} {7 9 25 33 47 50 52 54 59 63 85 scan 0 sort 0} +do_test where7-2.573.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1070 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR a=54 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR a=9 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + } +} {7 9 25 33 47 50 52 54 59 63 85 scan 0 sort 0} +do_test where7-2.574.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=55 + OR a=62 + OR a=63 + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR (g='rqponml' AND f GLOB 'ijklm*') + OR ((a BETWEEN 99 AND 101) AND a!=100) + } +} {34 50 55 62 63 99 scan 0 sort 0} +do_test where7-2.574.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=55 + OR a=62 + OR a=63 + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR (g='rqponml' AND f GLOB 'ijklm*') + OR ((a BETWEEN 99 AND 101) AND a!=100) + } +} {34 50 55 62 63 99 scan 0 sort 0} +do_test where7-2.575.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=421 + OR b=146 + OR b=22 + OR f='efghijklm' + } +} {2 4 30 56 82 scan 0 sort 0} +do_test where7-2.575.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=421 + OR b=146 + OR b=22 + OR f='efghijklm' + } +} {2 4 30 56 82 scan 0 sort 0} +do_test where7-2.576.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=553 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR (d>=59.0 AND d<60.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=583 + OR a=56 + } +} {21 23 48 53 56 59 61 scan 0 sort 0} +do_test where7-2.576.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=553 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR (d>=59.0 AND d<60.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=583 + OR a=56 + } +} {21 23 48 53 56 59 61 scan 0 sort 0} +do_test where7-2.577.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=83 + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'defgh*') + OR a=1 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR b=245 + } +} {1 17 19 29 49 51 77 83 scan 0 sort 0} +do_test where7-2.577.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=83 + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'defgh*') + OR a=1 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR b=245 + } +} {1 17 19 29 49 51 77 83 scan 0 sort 0} +do_test where7-2.578.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=3003 + OR b=619 + OR ((a BETWEEN 19 AND 21) AND a!=20) + } +} {7 8 9 19 21 scan 0 sort 0} +do_test where7-2.578.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=3003 + OR b=619 + OR ((a BETWEEN 19 AND 21) AND a!=20) + } +} {7 8 9 19 21 scan 0 sort 0} +do_test where7-2.579.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=924 + OR a=92 + OR a=63 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + } +} {60 63 84 92 97 scan 0 sort 0} +do_test where7-2.579.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=924 + OR a=92 + OR a=63 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + } +} {60 63 84 92 97 scan 0 sort 0} +do_test where7-2.580.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=440 + OR f='vwxyzabcd' + OR b=190 + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR b=88 + OR b=58 + } +} {8 11 21 37 40 42 47 63 73 89 99 scan 0 sort 0} +do_test where7-2.580.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=440 + OR f='vwxyzabcd' + OR b=190 + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR b=88 + OR b=58 + } +} {8 11 21 37 40 42 47 63 73 89 99 scan 0 sort 0} +do_test where7-2.581.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=495 + OR c=24024 + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR b=1001 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR d>1e10 + OR b=531 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR b=1089 + } +} {25 45 49 70 71 72 82 91 99 scan 0 sort 0} +do_test where7-2.581.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=495 + OR c=24024 + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR b=1001 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR d>1e10 + OR b=531 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR b=1089 + } +} {25 45 49 70 71 72 82 91 99 scan 0 sort 0} +do_test where7-2.582.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=48.0 AND d<49.0 AND d NOT NULL) + OR (d>=41.0 AND d<42.0 AND d NOT NULL) + } +} {41 48 scan 0 sort 0} +do_test where7-2.582.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=48.0 AND d<49.0 AND d NOT NULL) + OR (d>=41.0 AND d<42.0 AND d NOT NULL) + } +} {41 48 scan 0 sort 0} +do_test where7-2.583.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR d>1e10 + OR b=22 + OR c=5005 + OR ((a BETWEEN 22 AND 24) AND a!=23) + } +} {1 2 13 14 15 22 24 52 71 73 80 82 91 93 scan 0 sort 0} +do_test where7-2.583.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR d>1e10 + OR b=22 + OR c=5005 + OR ((a BETWEEN 22 AND 24) AND a!=23) + } +} {1 2 13 14 15 22 24 52 71 73 80 82 91 93 scan 0 sort 0} +do_test where7-2.584.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 9 AND 11) AND a!=10) + OR b=1078 + OR b=806 + OR b=605 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + } +} {9 11 15 23 25 41 55 67 76 93 98 scan 0 sort 0} +do_test where7-2.584.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 9 AND 11) AND a!=10) + OR b=1078 + OR b=806 + OR b=605 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + } +} {9 11 15 23 25 41 55 67 76 93 98 scan 0 sort 0} +do_test where7-2.585.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR b=572 + OR c=10010 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=29 + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + } +} {7 28 29 30 33 52 59 68 84 85 86 scan 0 sort 0} +do_test where7-2.585.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR b=572 + OR c=10010 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=29 + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + } +} {7 28 29 30 33 52 59 68 84 85 86 scan 0 sort 0} +do_test where7-2.586.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 94 AND 96) AND a!=95) + OR b=858 + OR b=806 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + } +} {63 77 78 94 96 scan 0 sort 0} +do_test where7-2.586.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 94 AND 96) AND a!=95) + OR b=858 + OR b=806 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + } +} {63 77 78 94 96 scan 0 sort 0} +do_test where7-2.587.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='vwxyzabcd' + OR a=72 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=935 + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR c=13013 + } +} {21 36 37 38 39 40 47 72 73 85 99 scan 0 sort 0} +do_test where7-2.587.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='vwxyzabcd' + OR a=72 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=935 + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR c=13013 + } +} {21 36 37 38 39 40 47 72 73 85 99 scan 0 sort 0} +do_test where7-2.588.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=5005 + OR (g='gfedcba' AND f GLOB 'klmno*') + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR b=143 + OR a=68 + OR a=77 + OR b=80 + } +} {13 14 15 43 44 68 77 88 scan 0 sort 0} +do_test where7-2.588.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=5005 + OR (g='gfedcba' AND f GLOB 'klmno*') + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR b=143 + OR a=68 + OR a=77 + OR b=80 + } +} {13 14 15 43 44 68 77 88 scan 0 sort 0} +do_test where7-2.589.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=5.0 AND d<6.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=99 + OR ((a BETWEEN 12 AND 14) AND a!=13) + } +} {5 6 12 14 68 72 76 78 99 scan 0 sort 0} +do_test where7-2.589.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=5.0 AND d<6.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'ghijk*') + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=99 + OR ((a BETWEEN 12 AND 14) AND a!=13) + } +} {5 6 12 14 68 72 76 78 99 scan 0 sort 0} +do_test where7-2.590.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'opqrs*') + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR b=971 + OR (g='xwvutsr' AND f GLOB 'fghij*') + } +} {5 13 40 88 90 scan 0 sort 0} +do_test where7-2.590.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'opqrs*') + OR ((a BETWEEN 88 AND 90) AND a!=89) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR b=971 + OR (g='xwvutsr' AND f GLOB 'fghij*') + } +} {5 13 40 88 90 scan 0 sort 0} +do_test where7-2.591.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?lmno*' AND f GLOB 'klmn*') + OR b=806 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR b=1015 + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + } +} {10 13 36 39 43 62 65 68 70 88 91 scan 0 sort 0} +do_test where7-2.591.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?lmno*' AND f GLOB 'klmn*') + OR b=806 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR b=1015 + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + } +} {10 13 36 39 43 62 65 68 70 88 91 scan 0 sort 0} +do_test where7-2.592.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='nopqrstuv' + OR b=993 + OR a=76 + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR c=20020 + OR a=26 + OR b=1048 + OR b=561 + OR (g='rqponml' AND f GLOB 'klmno*') + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR a=56 + } +} {13 26 36 39 51 55 56 57 58 59 60 65 76 79 91 scan 0 sort 0} +do_test where7-2.592.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='nopqrstuv' + OR b=993 + OR a=76 + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR c=20020 + OR a=26 + OR b=1048 + OR b=561 + OR (g='rqponml' AND f GLOB 'klmno*') + OR ((a BETWEEN 55 AND 57) AND a!=56) + OR a=56 + } +} {13 26 36 39 51 55 56 57 58 59 60 65 76 79 91 scan 0 sort 0} +do_test where7-2.593.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=781 + OR b=671 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR b=113 + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=385 + OR (g='hgfedcb' AND f GLOB 'fghij*') + } +} {15 16 35 39 41 60 61 71 83 scan 0 sort 0} +do_test where7-2.593.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=781 + OR b=671 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR b=113 + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=385 + OR (g='hgfedcb' AND f GLOB 'fghij*') + } +} {15 16 35 39 41 60 61 71 83 scan 0 sort 0} +do_test where7-2.594.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=410 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR b=674 + OR b=825 + OR b=704 + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR a=76 + OR c=32032 + OR ((a BETWEEN 43 AND 45) AND a!=44) + } +} {9 43 45 58 60 61 64 75 76 85 87 94 95 96 scan 0 sort 0} +do_test where7-2.594.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=410 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR b=674 + OR b=825 + OR b=704 + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR a=76 + OR c=32032 + OR ((a BETWEEN 43 AND 45) AND a!=44) + } +} {9 43 45 58 60 61 64 75 76 85 87 94 95 96 scan 0 sort 0} +do_test where7-2.595.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=869 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + } +} {43 79 scan 0 sort 0} +do_test where7-2.595.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=869 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + } +} {43 79 scan 0 sort 0} +do_test where7-2.596.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=869 + OR a=34 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + } +} {34 79 87 scan 0 sort 0} +do_test where7-2.596.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=869 + OR a=34 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + } +} {34 79 87 scan 0 sort 0} +do_test where7-2.597.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='rqponml' AND f GLOB 'hijkl*') + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR a=8 + OR a=72 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR (g='gfedcba' AND f GLOB 'mnopq*') + } +} {8 33 44 72 90 95 97 scan 0 sort 0} +do_test where7-2.597.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='rqponml' AND f GLOB 'hijkl*') + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR a=8 + OR a=72 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR (g='gfedcba' AND f GLOB 'mnopq*') + } +} {8 33 44 72 90 95 97 scan 0 sort 0} +do_test where7-2.598.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=20 + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR b=341 + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=814 + OR b=1026 + OR a=14 + OR a=13 + OR b=1037 + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {13 14 20 26 31 56 58 74 76 scan 0 sort 0} +do_test where7-2.598.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=20 + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR b=341 + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=814 + OR b=1026 + OR a=14 + OR a=13 + OR b=1037 + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {13 14 20 26 31 56 58 74 76 scan 0 sort 0} +do_test where7-2.599.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=443 + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=839 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR c=7007 + } +} {10 13 19 20 21 49 51 scan 0 sort 0} +do_test where7-2.599.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=443 + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=839 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR c=7007 + } +} {10 13 19 20 21 49 51 scan 0 sort 0} +do_test where7-2.600.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR a=21 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR (d>=3.0 AND d<4.0 AND d NOT NULL) + OR f='zabcdefgh' + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR b=506 + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR b=88 + OR b=190 + } +} {3 8 9 14 16 21 25 42 46 51 68 77 94 97 scan 0 sort 0} +do_test where7-2.600.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR a=21 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR (d>=3.0 AND d<4.0 AND d NOT NULL) + OR f='zabcdefgh' + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR b=506 + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR b=88 + OR b=190 + } +} {3 8 9 14 16 21 25 42 46 51 68 77 94 97 scan 0 sort 0} +do_test where7-2.601.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=41.0 AND d<42.0 AND d NOT NULL) + OR f='bcdefghij' + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'efghi*') + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=762 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'yzabc*') + } +} {1 27 30 41 53 54 61 63 68 70 76 79 scan 0 sort 0} +do_test where7-2.601.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=41.0 AND d<42.0 AND d NOT NULL) + OR f='bcdefghij' + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'efghi*') + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=762 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'yzabc*') + } +} {1 27 30 41 53 54 61 63 68 70 76 79 scan 0 sort 0} +do_test where7-2.602.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=85.0 AND d<86.0 AND d NOT NULL) + OR f='qrstuvwxy' + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + } +} {16 42 56 68 85 94 scan 0 sort 0} +do_test where7-2.602.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=85.0 AND d<86.0 AND d NOT NULL) + OR f='qrstuvwxy' + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + } +} {16 42 56 68 85 94 scan 0 sort 0} +do_test where7-2.603.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=89.0 AND d<90.0 AND d NOT NULL) + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR a=21 + OR b<0 + OR f='bcdefghij' + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {1 14 16 21 27 53 57 79 89 scan 0 sort 0} +do_test where7-2.603.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=89.0 AND d<90.0 AND d NOT NULL) + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR a=21 + OR b<0 + OR f='bcdefghij' + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {1 14 16 21 27 53 57 79 89 scan 0 sort 0} +do_test where7-2.604.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'fghij*') + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=1067 + OR b=231 + OR b=113 + OR b=22 + OR a=55 + OR b=663 + } +} {2 21 40 55 83 97 scan 0 sort 0} +do_test where7-2.604.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'fghij*') + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=1067 + OR b=231 + OR b=113 + OR b=22 + OR a=55 + OR b=663 + } +} {2 21 40 55 83 97 scan 0 sort 0} +do_test where7-2.605.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=1 + OR b=454 + OR b=396 + OR b=1059 + OR a=69 + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR b=440 + OR b=825 + } +} {1 21 36 40 47 69 73 75 99 scan 0 sort 0} +do_test where7-2.605.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=1 + OR b=454 + OR b=396 + OR b=1059 + OR a=69 + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR b=440 + OR b=825 + } +} {1 21 36 40 47 69 73 75 99 scan 0 sort 0} +do_test where7-2.606.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=26.0 AND d<27.0 AND d NOT NULL) + OR b=308 + OR c<=10 + OR (g='xwvutsr' AND f GLOB 'hijkl*') + OR f='ghijklmno' + OR b=289 + OR a=5 + OR b=267 + OR b=949 + OR ((a BETWEEN 7 AND 9) AND a!=8) + } +} {5 6 7 9 26 28 32 58 84 scan 0 sort 0} +do_test where7-2.606.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=26.0 AND d<27.0 AND d NOT NULL) + OR b=308 + OR c<=10 + OR (g='xwvutsr' AND f GLOB 'hijkl*') + OR f='ghijklmno' + OR b=289 + OR a=5 + OR b=267 + OR b=949 + OR ((a BETWEEN 7 AND 9) AND a!=8) + } +} {5 6 7 9 26 28 32 58 84 scan 0 sort 0} +do_test where7-2.607.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 95 AND 97) AND a!=96) + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR b=993 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR b=663 + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR b=869 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR b=121 + } +} {11 17 24 43 45 50 76 79 81 95 97 scan 0 sort 0} +do_test where7-2.607.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 95 AND 97) AND a!=96) + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR b=993 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR b=663 + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR b=869 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR b=121 + } +} {11 17 24 43 45 50 76 79 81 95 97 scan 0 sort 0} +do_test where7-2.608.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'efghi*') + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR (g='hgfedcb' AND f GLOB 'jklmn*') + OR b=770 + } +} {4 27 70 87 scan 0 sort 0} +do_test where7-2.608.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'efghi*') + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR (g='hgfedcb' AND f GLOB 'jklmn*') + OR b=770 + } +} {4 27 70 87 scan 0 sort 0} +do_test where7-2.609.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 80 AND 82) AND a!=81) + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR (g='gfedcba' AND f GLOB 'mnopq*') + } +} {19 45 57 71 80 82 90 97 scan 0 sort 0} +do_test where7-2.609.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 80 AND 82) AND a!=81) + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR (g='gfedcba' AND f GLOB 'mnopq*') + } +} {19 45 57 71 80 82 90 97 scan 0 sort 0} +do_test where7-2.610.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=22 + OR c=31031 + OR b=894 + OR a=31 + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR a=94 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR a=21 + OR b=1001 + } +} {2 21 31 84 86 91 92 93 94 95 scan 0 sort 0} +do_test where7-2.610.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=22 + OR c=31031 + OR b=894 + OR a=31 + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR a=94 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR a=21 + OR b=1001 + } +} {2 21 31 84 86 91 92 93 94 95 scan 0 sort 0} +do_test where7-2.611.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='onmlkji' AND f GLOB 'zabcd*') + OR b=1092 + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR a=77 + OR a=63 + OR b=762 + OR b=894 + OR b=685 + OR (g='vutsrqp' AND f GLOB 'nopqr*') + } +} {13 46 51 63 77 80 scan 0 sort 0} +do_test where7-2.611.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='onmlkji' AND f GLOB 'zabcd*') + OR b=1092 + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR a=77 + OR a=63 + OR b=762 + OR b=894 + OR b=685 + OR (g='vutsrqp' AND f GLOB 'nopqr*') + } +} {13 46 51 63 77 80 scan 0 sort 0} +do_test where7-2.612.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='wvutsrq' AND f GLOB 'klmno*') + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR b=231 + } +} {10 21 93 95 scan 0 sort 0} +do_test where7-2.612.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='wvutsrq' AND f GLOB 'klmno*') + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR b=231 + } +} {10 21 93 95 scan 0 sort 0} +do_test where7-2.613.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=828 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR ((a BETWEEN 8 AND 10) AND a!=9) + } +} {8 10 26 52 78 scan 0 sort 0} +do_test where7-2.613.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=828 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR ((a BETWEEN 8 AND 10) AND a!=9) + } +} {8 10 26 52 78 scan 0 sort 0} +do_test where7-2.614.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR b=520 + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR a=21 + } +} {4 6 13 21 31 33 39 47 50 65 91 100 scan 0 sort 0} +do_test where7-2.614.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR b=520 + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR a=21 + } +} {4 6 13 21 31 33 39 47 50 65 91 100 scan 0 sort 0} +do_test where7-2.615.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=553 + OR (g='lkjihgf' AND f GLOB 'lmnop*') + OR b=1034 + OR b=418 + OR a=57 + OR f='mnopqrstu' + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + } +} {12 38 57 63 64 90 94 99 scan 0 sort 0} +do_test where7-2.615.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=553 + OR (g='lkjihgf' AND f GLOB 'lmnop*') + OR b=1034 + OR b=418 + OR a=57 + OR f='mnopqrstu' + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + } +} {12 38 57 63 64 90 94 99 scan 0 sort 0} +do_test where7-2.616.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=43 + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR b=418 + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR b=594 + OR a=21 + OR a=78 + OR a=91 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + } +} {21 38 43 47 54 70 78 80 91 scan 0 sort 0} +do_test where7-2.616.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=43 + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR b=418 + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR b=594 + OR a=21 + OR a=78 + OR a=91 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + } +} {21 38 43 47 54 70 78 80 91 scan 0 sort 0} +do_test where7-2.617.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=671 + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR ((a BETWEEN 95 AND 97) AND a!=96) + } +} {48 61 95 97 scan 0 sort 0} +do_test where7-2.617.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=671 + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR ((a BETWEEN 95 AND 97) AND a!=96) + } +} {48 61 95 97 scan 0 sort 0} +do_test where7-2.618.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=2.0 AND d<3.0 AND d NOT NULL) + OR b=726 + OR b=663 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR a=25 + OR f='qrstuvwxy' + } +} {2 13 16 25 42 66 68 94 scan 0 sort 0} +do_test where7-2.618.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=2.0 AND d<3.0 AND d NOT NULL) + OR b=726 + OR b=663 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR a=25 + OR f='qrstuvwxy' + } +} {2 13 16 25 42 66 68 94 scan 0 sort 0} +do_test where7-2.619.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=806 + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR b=275 + OR ((a BETWEEN 80 AND 82) AND a!=81) + } +} {10 12 25 50 80 82 scan 0 sort 0} +do_test where7-2.619.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=806 + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR b=275 + OR ((a BETWEEN 80 AND 82) AND a!=81) + } +} {10 12 25 50 80 82 scan 0 sort 0} +do_test where7-2.620.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=24024 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR b=429 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR b=110 + OR a=39 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + } +} {2 10 23 39 70 71 72 scan 0 sort 0} +do_test where7-2.620.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=24024 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR b=429 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR b=110 + OR a=39 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + } +} {2 10 23 39 70 71 72 scan 0 sort 0} +do_test where7-2.621.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=66 + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR b=198 + OR b=682 + OR c=23023 + } +} {18 62 66 67 68 69 70 scan 0 sort 0} +do_test where7-2.621.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=66 + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR b=198 + OR b=682 + OR c=23023 + } +} {18 62 66 67 68 69 70 scan 0 sort 0} +do_test where7-2.622.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=806 + OR b=253 + OR a=36 + } +} {23 36 scan 0 sort 0} +do_test where7-2.622.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=806 + OR b=253 + OR a=36 + } +} {23 36 scan 0 sort 0} +do_test where7-2.623.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=509 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR b=718 + OR a=4 + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + } +} {4 13 16 22 24 56 58 69 scan 0 sort 0} +do_test where7-2.623.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=509 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR (g='vutsrqp' AND f GLOB 'nopqr*') + OR b=718 + OR a=4 + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + } +} {4 13 16 22 24 56 58 69 scan 0 sort 0} +do_test where7-2.624.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'zabcd*') + OR b=1026 + OR a=93 + OR c=18018 + } +} {52 53 54 77 93 scan 0 sort 0} +do_test where7-2.624.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'zabcd*') + OR b=1026 + OR a=93 + OR c=18018 + } +} {52 53 54 77 93 scan 0 sort 0} +do_test where7-2.625.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=388 + OR a=44 + } +} {44 scan 0 sort 0} +do_test where7-2.625.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=388 + OR a=44 + } +} {44 scan 0 sort 0} +do_test where7-2.626.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=9009 + OR b=542 + OR f='cdefghijk' + OR b=319 + OR b=616 + } +} {2 25 26 27 28 29 54 56 80 scan 0 sort 0} +do_test where7-2.626.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=9009 + OR b=542 + OR f='cdefghijk' + OR b=319 + OR b=616 + } +} {2 25 26 27 28 29 54 56 80 scan 0 sort 0} +do_test where7-2.627.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=990 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR b=531 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR f='qrstuvwxy' + } +} {6 16 32 41 42 43 57 58 67 68 84 86 90 94 97 scan 0 sort 0} +do_test where7-2.627.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=990 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR b=531 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR f='qrstuvwxy' + } +} {6 16 32 41 42 43 57 58 67 68 84 86 90 94 97 scan 0 sort 0} +do_test where7-2.628.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=60 + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR b=627 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR b=883 + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR f='yzabcdefg' + OR (d>=59.0 AND d<60.0 AND d NOT NULL) + } +} {24 38 50 57 59 60 73 76 78 93 99 scan 0 sort 0} +do_test where7-2.628.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=60 + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR b=627 + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR b=883 + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR f='yzabcdefg' + OR (d>=59.0 AND d<60.0 AND d NOT NULL) + } +} {24 38 50 57 59 60 73 76 78 93 99 scan 0 sort 0} +do_test where7-2.629.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=696 + OR b=938 + OR a=18 + OR b=957 + OR c=18018 + OR c=3003 + OR ((a BETWEEN 33 AND 35) AND a!=34) + } +} {7 8 9 18 33 35 52 53 54 87 scan 0 sort 0} +do_test where7-2.629.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=696 + OR b=938 + OR a=18 + OR b=957 + OR c=18018 + OR c=3003 + OR ((a BETWEEN 33 AND 35) AND a!=34) + } +} {7 8 9 18 33 35 52 53 54 87 scan 0 sort 0} +do_test where7-2.630.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=29029 + OR a=73 + } +} {73 85 86 87 scan 0 sort 0} +do_test where7-2.630.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=29029 + OR a=73 + } +} {73 85 86 87 scan 0 sort 0} +do_test where7-2.631.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=28 + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR b=69 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR b=781 + OR a=64 + OR b=91 + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR a=16 + OR b=278 + OR a=26 + } +} {16 26 27 28 64 71 82 85 87 scan 0 sort 0} +do_test where7-2.631.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=28 + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR b=69 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR b=781 + OR a=64 + OR b=91 + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR a=16 + OR b=278 + OR a=26 + } +} {16 26 27 28 64 71 82 85 87 scan 0 sort 0} +do_test where7-2.632.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=70 + OR c=3003 + } +} {7 8 9 70 scan 0 sort 0} +do_test where7-2.632.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=70 + OR c=3003 + } +} {7 8 9 70 scan 0 sort 0} +do_test where7-2.633.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=31031 + OR a=76 + OR b=1023 + OR b=33 + } +} {3 76 91 92 93 scan 0 sort 0} +do_test where7-2.633.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=31031 + OR a=76 + OR b=1023 + OR b=33 + } +} {3 76 91 92 93 scan 0 sort 0} +do_test where7-2.634.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=62.0 AND d<63.0 AND d NOT NULL) + OR b=1001 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + } +} {62 86 91 scan 0 sort 0} +do_test where7-2.634.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=62.0 AND d<63.0 AND d NOT NULL) + OR b=1001 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + } +} {62 86 91 scan 0 sort 0} +do_test where7-2.635.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='yzabcdefg' + OR ((a BETWEEN 48 AND 50) AND a!=49) + OR a=100 + OR (g='rqponml' AND f GLOB 'ijklm*') + OR a=62 + OR a=67 + OR b=605 + OR c=23023 + OR a=26 + OR b=982 + OR ((a BETWEEN 3 AND 5) AND a!=4) + } +} {3 5 24 26 34 48 50 55 62 67 68 69 76 100 scan 0 sort 0} +do_test where7-2.635.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='yzabcdefg' + OR ((a BETWEEN 48 AND 50) AND a!=49) + OR a=100 + OR (g='rqponml' AND f GLOB 'ijklm*') + OR a=62 + OR a=67 + OR b=605 + OR c=23023 + OR a=26 + OR b=982 + OR ((a BETWEEN 3 AND 5) AND a!=4) + } +} {3 5 24 26 34 48 50 55 62 67 68 69 76 100 scan 0 sort 0} +do_test where7-2.636.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=220 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR f IS NULL + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR b=784 + } +} {20 24 25 26 27 scan 0 sort 0} +do_test where7-2.636.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=220 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR f IS NULL + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR b=784 + } +} {20 24 25 26 27 scan 0 sort 0} +do_test where7-2.637.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR b=751 + OR (g='gfedcba' AND f GLOB 'klmno*') + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR a=67 + OR b=102 + } +} {10 17 43 67 69 88 95 scan 0 sort 0} +do_test where7-2.637.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR b=751 + OR (g='gfedcba' AND f GLOB 'klmno*') + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR a=67 + OR b=102 + } +} {10 17 43 67 69 88 95 scan 0 sort 0} +do_test where7-2.638.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=69.0 AND d<70.0 AND d NOT NULL) + OR b=256 + OR c=7007 + OR c=26026 + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + OR a=66 + } +} {19 20 21 66 69 74 76 77 78 80 82 scan 0 sort 0} +do_test where7-2.638.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=69.0 AND d<70.0 AND d NOT NULL) + OR b=256 + OR c=7007 + OR c=26026 + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + OR a=66 + } +} {19 20 21 66 69 74 76 77 78 80 82 scan 0 sort 0} +do_test where7-2.639.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=2002 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR b=33 + OR b=817 + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + } +} {3 4 5 6 8 10 21 34 41 43 45 60 81 86 scan 0 sort 0} +do_test where7-2.639.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=2002 + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR b=33 + OR b=817 + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + } +} {3 4 5 6 8 10 21 34 41 43 45 60 81 86 scan 0 sort 0} +do_test where7-2.640.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='srqponm' AND f GLOB 'cdefg*') + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR a=80 + OR a=53 + OR a=62 + OR a=49 + OR a=53 + OR a=56 + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + } +} {28 49 53 56 62 80 81 83 scan 0 sort 0} +do_test where7-2.640.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='srqponm' AND f GLOB 'cdefg*') + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR a=80 + OR a=53 + OR a=62 + OR a=49 + OR a=53 + OR a=56 + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + } +} {28 49 53 56 62 80 81 83 scan 0 sort 0} +do_test where7-2.641.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 7 AND 9) AND a!=8) + OR b=652 + OR a=72 + OR b=209 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR a=38 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR d>1e10 + } +} {7 9 19 23 38 66 68 72 scan 0 sort 0} +do_test where7-2.641.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 7 AND 9) AND a!=8) + OR b=652 + OR a=72 + OR b=209 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR a=38 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR d>1e10 + } +} {7 9 19 23 38 66 68 72 scan 0 sort 0} +do_test where7-2.642.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=949 + OR e IS NULL + } +} { scan 0 sort 0} +do_test where7-2.642.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=949 + OR e IS NULL + } +} { scan 0 sort 0} +do_test where7-2.643.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=179 + OR (g='srqponm' AND f GLOB 'defgh*') + OR b=509 + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR f='bcdefghij' + } +} {1 26 27 29 49 53 58 60 79 scan 0 sort 0} +do_test where7-2.643.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=179 + OR (g='srqponm' AND f GLOB 'defgh*') + OR b=509 + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR f='bcdefghij' + } +} {1 26 27 29 49 53 58 60 79 scan 0 sort 0} +do_test where7-2.644.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=23 + OR a=43 + OR c=19019 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR c=18018 + } +} {23 43 47 52 53 54 55 56 57 scan 0 sort 0} +do_test where7-2.644.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=23 + OR a=43 + OR c=19019 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR c=18018 + } +} {23 43 47 52 53 54 55 56 57 scan 0 sort 0} +do_test where7-2.645.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=36 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR b=231 + } +} {21 22 36 scan 0 sort 0} +do_test where7-2.645.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=36 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR b=231 + } +} {21 22 36 scan 0 sort 0} +do_test where7-2.646.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=21 + OR b=355 + OR a=97 + } +} {21 97 scan 0 sort 0} +do_test where7-2.646.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=21 + OR b=355 + OR a=97 + } +} {21 97 scan 0 sort 0} +do_test where7-2.647.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=421 + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR b=704 + OR a=90 + OR a=78 + OR 1000000=80.0 AND d<81.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR ((a BETWEEN 53 AND 55) AND a!=54) + } +} {28 42 53 55 64 78 80 81 90 scan 0 sort 0} +do_test where7-2.647.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=421 + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR b=704 + OR a=90 + OR a=78 + OR 1000000=80.0 AND d<81.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR ((a BETWEEN 53 AND 55) AND a!=54) + } +} {28 42 53 55 64 78 80 81 90 scan 0 sort 0} +do_test where7-2.648.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='fedcbaz' AND f GLOB 'pqrst*') + OR ((a BETWEEN 93 AND 95) AND a!=94) + } +} {93 95 scan 0 sort 0} +do_test where7-2.648.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='fedcbaz' AND f GLOB 'pqrst*') + OR ((a BETWEEN 93 AND 95) AND a!=94) + } +} {93 95 scan 0 sort 0} +do_test where7-2.649.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE d<0.0 + OR a=78 + OR b=539 + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR e IS NULL + OR a=48 + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {8 10 25 27 48 49 57 78 scan 0 sort 0} +do_test where7-2.649.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE d<0.0 + OR a=78 + OR b=539 + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR e IS NULL + OR a=48 + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {8 10 25 27 48 49 57 78 scan 0 sort 0} +do_test where7-2.650.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 94 AND 96) AND a!=95) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR b=22 + } +} {2 78 94 96 scan 0 sort 0} +do_test where7-2.650.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 94 AND 96) AND a!=95) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR b=22 + } +} {2 78 94 96 scan 0 sort 0} +do_test where7-2.651.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=275 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR (g='rqponml' AND f GLOB 'lmnop*') + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR f='ijklmnopq' + } +} {8 25 34 37 53 57 59 60 86 92 scan 0 sort 0} +do_test where7-2.651.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=275 + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR (g='rqponml' AND f GLOB 'lmnop*') + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR f='ijklmnopq' + } +} {8 25 34 37 53 57 59 60 86 92 scan 0 sort 0} +do_test where7-2.652.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=256 + OR c=13013 + OR b=44 + OR f='jklmnopqr' + OR b=883 + } +} {4 9 35 37 38 39 61 87 scan 0 sort 0} +do_test where7-2.652.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=256 + OR c=13013 + OR b=44 + OR f='jklmnopqr' + OR b=883 + } +} {4 9 35 37 38 39 61 87 scan 0 sort 0} +do_test where7-2.653.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='zabcdefgh' + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR a=54 + OR b=770 + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR a=81 + OR b=190 + OR a=2 + } +} {2 3 25 51 54 70 77 81 96 98 scan 0 sort 0} +do_test where7-2.653.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='zabcdefgh' + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR a=54 + OR b=770 + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR a=81 + OR b=190 + OR a=2 + } +} {2 3 25 51 54 70 77 81 96 98 scan 0 sort 0} +do_test where7-2.654.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=12.0 AND d<13.0 AND d NOT NULL) + OR c=12012 + OR a=16 + OR a=15 + OR ((a BETWEEN 70 AND 72) AND a!=71) + OR a=69 + OR b=748 + OR a=61 + OR b=473 + OR ((a BETWEEN 69 AND 71) AND a!=70) + } +} {12 15 16 34 35 36 43 61 68 69 70 71 72 scan 0 sort 0} +do_test where7-2.654.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=12.0 AND d<13.0 AND d NOT NULL) + OR c=12012 + OR a=16 + OR a=15 + OR ((a BETWEEN 70 AND 72) AND a!=71) + OR a=69 + OR b=748 + OR a=61 + OR b=473 + OR ((a BETWEEN 69 AND 71) AND a!=70) + } +} {12 15 16 34 35 36 43 61 68 69 70 71 72 scan 0 sort 0} +do_test where7-2.655.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=223 + OR a=14 + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR b=539 + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR a=21 + } +} {14 21 33 35 41 48 49 61 74 76 scan 0 sort 0} +do_test where7-2.655.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=223 + OR a=14 + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR b=539 + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR a=21 + } +} {14 21 33 35 41 48 49 61 74 76 scan 0 sort 0} +do_test where7-2.656.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=99 + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR a=73 + OR a=56 + OR b=253 + OR b=880 + } +} {5 23 31 56 57 73 80 83 99 scan 0 sort 0} +do_test where7-2.656.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=99 + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR a=73 + OR a=56 + OR b=253 + OR b=880 + } +} {5 23 31 56 57 73 80 83 99 scan 0 sort 0} +do_test where7-2.657.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=927 + OR b=300 + OR b=223 + OR (g='wvutsrq' AND f GLOB 'jklmn*') + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=154 + OR b=759 + } +} {9 14 69 95 scan 0 sort 0} +do_test where7-2.657.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=927 + OR b=300 + OR b=223 + OR (g='wvutsrq' AND f GLOB 'jklmn*') + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=154 + OR b=759 + } +} {9 14 69 95 scan 0 sort 0} +do_test where7-2.658.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=242 + OR b=905 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR a=24 + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR b=1100 + OR b=850 + OR ((a BETWEEN 55 AND 57) AND a!=56) + } +} {22 24 55 57 66 67 69 86 96 100 scan 0 sort 0} +do_test where7-2.658.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=242 + OR b=905 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'ijklm*') + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR a=24 + OR ((a BETWEEN 67 AND 69) AND a!=68) + OR b=1100 + OR b=850 + OR ((a BETWEEN 55 AND 57) AND a!=56) + } +} {22 24 55 57 66 67 69 86 96 100 scan 0 sort 0} +do_test where7-2.659.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=190 + OR a=72 + OR b=377 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR b=476 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + } +} {2 26 52 72 78 93 scan 0 sort 0} +do_test where7-2.659.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=190 + OR a=72 + OR b=377 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR b=476 + OR (g='yxwvuts' AND f GLOB 'cdefg*') + } +} {2 26 52 72 78 93 scan 0 sort 0} +do_test where7-2.660.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=245 + OR b=638 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR f='opqrstuvw' + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR b=817 + OR a=85 + OR (g='lkjihgf' AND f GLOB 'mnopq*') + } +} {14 40 58 62 64 66 67 85 86 92 scan 0 sort 0} +do_test where7-2.660.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=245 + OR b=638 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR f='opqrstuvw' + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR b=817 + OR a=85 + OR (g='lkjihgf' AND f GLOB 'mnopq*') + } +} {14 40 58 62 64 66 67 85 86 92 scan 0 sort 0} +do_test where7-2.661.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 22 AND 24) AND a!=23) + OR b=968 + } +} {22 24 88 scan 0 sort 0} +do_test where7-2.661.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 22 AND 24) AND a!=23) + OR b=968 + } +} {22 24 88 scan 0 sort 0} +do_test where7-2.662.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 60 AND 62) AND a!=61) + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR b=22 + OR b=993 + OR f='tuvwxyzab' + } +} {2 19 45 60 62 71 74 76 97 scan 0 sort 0} +do_test where7-2.662.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 60 AND 62) AND a!=61) + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR b=22 + OR b=993 + OR f='tuvwxyzab' + } +} {2 19 45 60 62 71 74 76 97 scan 0 sort 0} +do_test where7-2.663.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 55 AND 57) AND a!=56) + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + OR c<=10 + OR ((a BETWEEN 75 AND 77) AND a!=76) + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR b=553 + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR b=1045 + } +} {55 57 72 73 75 77 85 95 scan 0 sort 0} +do_test where7-2.663.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 55 AND 57) AND a!=56) + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + OR c<=10 + OR ((a BETWEEN 75 AND 77) AND a!=76) + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR b=553 + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR b=1045 + } +} {55 57 72 73 75 77 85 95 scan 0 sort 0} +do_test where7-2.664.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=440 + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR a=89 + OR c=18018 + OR b=154 + OR b=506 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR a=78 + OR b=751 + } +} {1 3 5 14 27 31 40 44 46 52 53 54 57 78 79 83 89 scan 0 sort 0} +do_test where7-2.664.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=440 + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR ((a BETWEEN 44 AND 46) AND a!=45) + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR a=89 + OR c=18018 + OR b=154 + OR b=506 + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR a=78 + OR b=751 + } +} {1 3 5 14 27 31 40 44 46 52 53 54 57 78 79 83 89 scan 0 sort 0} +do_test where7-2.665.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=407 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR (g='rqponml' AND f GLOB 'klmno*') + OR b=209 + OR b=814 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR a=44 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR b=1092 + } +} {10 19 36 37 38 44 65 74 99 scan 0 sort 0} +do_test where7-2.665.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=407 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR (g='rqponml' AND f GLOB 'klmno*') + OR b=209 + OR b=814 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR a=44 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR b=1092 + } +} {10 19 36 37 38 44 65 74 99 scan 0 sort 0} +do_test where7-2.666.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 24 AND 26) AND a!=25) + OR b=1103 + OR b=190 + OR b=737 + OR a=97 + OR b=451 + OR b=583 + OR a=63 + OR c=8008 + OR ((a BETWEEN 45 AND 47) AND a!=46) + } +} {22 23 24 26 41 45 47 53 63 67 97 scan 0 sort 0} +do_test where7-2.666.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 24 AND 26) AND a!=25) + OR b=1103 + OR b=190 + OR b=737 + OR a=97 + OR b=451 + OR b=583 + OR a=63 + OR c=8008 + OR ((a BETWEEN 45 AND 47) AND a!=46) + } +} {22 23 24 26 41 45 47 53 63 67 97 scan 0 sort 0} +do_test where7-2.667.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=12 + OR b=935 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=1070 + OR a=24 + OR a=95 + OR ((a BETWEEN 27 AND 29) AND a!=28) + OR a=40 + OR b=935 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + } +} {12 24 27 29 40 53 85 87 95 scan 0 sort 0} +do_test where7-2.667.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=12 + OR b=935 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=1070 + OR a=24 + OR a=95 + OR ((a BETWEEN 27 AND 29) AND a!=28) + OR a=40 + OR b=935 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + } +} {12 24 27 29 40 53 85 87 95 scan 0 sort 0} +do_test where7-2.668.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=858 + OR a=82 + OR b=209 + OR b=374 + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR c=22022 + } +} {19 34 40 64 65 66 76 78 82 scan 0 sort 0} +do_test where7-2.668.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=858 + OR a=82 + OR b=209 + OR b=374 + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR c=22022 + } +} {19 34 40 64 65 66 76 78 82 scan 0 sort 0} +do_test where7-2.669.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=27 + OR (g='rqponml' AND f GLOB 'lmnop*') + OR b=121 + OR ((a BETWEEN 7 AND 9) AND a!=8) + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR a=67 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR c=1001 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR ((a BETWEEN 19 AND 21) AND a!=20) + } +} {1 2 3 7 8 9 11 19 21 27 30 32 37 50 52 67 scan 0 sort 0} +do_test where7-2.669.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=27 + OR (g='rqponml' AND f GLOB 'lmnop*') + OR b=121 + OR ((a BETWEEN 7 AND 9) AND a!=8) + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR a=67 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR c=1001 + OR ((a BETWEEN 50 AND 52) AND a!=51) + OR ((a BETWEEN 19 AND 21) AND a!=20) + } +} {1 2 3 7 8 9 11 19 21 27 30 32 37 50 52 67 scan 0 sort 0} +do_test where7-2.670.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=99 + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + } +} {1 9 46 57 98 scan 0 sort 0} +do_test where7-2.670.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=99 + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR (d>=98.0 AND d<99.0 AND d NOT NULL) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + } +} {1 9 46 57 98 scan 0 sort 0} +do_test where7-2.671.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=3 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR b=355 + OR b=814 + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR a=81 + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR b=542 + OR b=795 + } +} {3 42 62 74 79 81 scan 0 sort 0} +do_test where7-2.671.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=3 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR b=355 + OR b=814 + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR a=81 + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR b=542 + OR b=795 + } +} {3 42 62 74 79 81 scan 0 sort 0} +do_test where7-2.672.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR b=363 + OR (g='srqponm' AND f GLOB 'fghij*') + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR b=619 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR a=73 + } +} {1 14 31 33 56 64 66 73 scan 0 sort 0} +do_test where7-2.672.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR b=363 + OR (g='srqponm' AND f GLOB 'fghij*') + OR ((a BETWEEN 64 AND 66) AND a!=65) + OR b=619 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + OR a=73 + } +} {1 14 31 33 56 64 66 73 scan 0 sort 0} +do_test where7-2.673.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=935 + OR a=42 + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR b=330 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + } +} {9 30 35 42 55 61 85 87 scan 0 sort 0} +do_test where7-2.673.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=935 + OR a=42 + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR b=330 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + } +} {9 30 35 42 55 61 85 87 scan 0 sort 0} +do_test where7-2.674.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=79 + OR b=201 + OR b=99 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR a=64 + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR a=89 + } +} {9 16 19 21 42 64 68 79 89 94 scan 0 sort 0} +do_test where7-2.674.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=79 + OR b=201 + OR b=99 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR a=64 + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR a=89 + } +} {9 16 19 21 42 64 68 79 89 94 scan 0 sort 0} +do_test where7-2.675.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=784 + OR a=85 + OR b=663 + OR c=17017 + OR b=561 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR b=495 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR b=352 + OR ((a BETWEEN 39 AND 41) AND a!=40) + } +} {32 39 41 45 49 50 51 65 68 85 scan 0 sort 0} +do_test where7-2.675.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=784 + OR a=85 + OR b=663 + OR c=17017 + OR b=561 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR b=495 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR b=352 + OR ((a BETWEEN 39 AND 41) AND a!=40) + } +} {32 39 41 45 49 50 51 65 68 85 scan 0 sort 0} +do_test where7-2.676.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=100.0 AND d<101.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR f='klmnopqrs' + OR f='lmnopqrst' + } +} {10 11 19 36 37 62 63 88 89 100 scan 0 sort 0} +do_test where7-2.676.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=100.0 AND d<101.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR f='klmnopqrs' + OR f='lmnopqrst' + } +} {10 11 19 36 37 62 63 88 89 100 scan 0 sort 0} +do_test where7-2.677.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 90 AND 92) AND a!=91) + OR a=46 + OR a=44 + } +} {44 46 90 92 scan 0 sort 0} +do_test where7-2.677.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 90 AND 92) AND a!=91) + OR a=46 + OR a=44 + } +} {44 46 90 92 scan 0 sort 0} +do_test where7-2.678.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=36 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR b=682 + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR b=91 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR c=12012 + OR b=267 + OR (g='jihgfed' AND f GLOB 'yzabc*') + } +} {18 20 34 35 36 39 43 53 55 62 76 95 97 scan 0 sort 0} +do_test where7-2.678.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=36 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR b=682 + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR b=91 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR c=12012 + OR b=267 + OR (g='jihgfed' AND f GLOB 'yzabc*') + } +} {18 20 34 35 36 39 43 53 55 62 76 95 97 scan 0 sort 0} +do_test where7-2.679.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=594 + OR f='hijklmnop' + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR b=707 + OR b=363 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=157 + OR (g='tsrqpon' AND f GLOB 'yzabc*') + } +} {7 12 24 33 54 58 59 65 67 85 scan 0 sort 0} +do_test where7-2.679.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=594 + OR f='hijklmnop' + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR b=707 + OR b=363 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=157 + OR (g='tsrqpon' AND f GLOB 'yzabc*') + } +} {7 12 24 33 54 58 59 65 67 85 scan 0 sort 0} +do_test where7-2.680.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=27.0 AND d<28.0 AND d NOT NULL) + OR a=2 + OR a=84 + OR b=399 + OR b=828 + OR a=21 + OR b=748 + OR c=13013 + OR a=57 + OR f='mnopqrstu' + } +} {2 12 21 27 37 38 39 57 64 68 84 90 scan 0 sort 0} +do_test where7-2.680.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=27.0 AND d<28.0 AND d NOT NULL) + OR a=2 + OR a=84 + OR b=399 + OR b=828 + OR a=21 + OR b=748 + OR c=13013 + OR a=57 + OR f='mnopqrstu' + } +} {2 12 21 27 37 38 39 57 64 68 84 90 scan 0 sort 0} +do_test where7-2.681.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='nmlkjih' AND f GLOB 'defgh*') + OR b=674 + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR c=3003 + OR a=19 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR ((a BETWEEN 20 AND 22) AND a!=21) + } +} {7 8 9 19 20 22 38 40 46 55 scan 0 sort 0} +do_test where7-2.681.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='nmlkjih' AND f GLOB 'defgh*') + OR b=674 + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR c=3003 + OR a=19 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR ((a BETWEEN 20 AND 22) AND a!=21) + } +} {7 8 9 19 20 22 38 40 46 55 scan 0 sort 0} +do_test where7-2.682.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=652 + OR a=83 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR b=102 + OR b=300 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + } +} {49 83 97 scan 0 sort 0} +do_test where7-2.682.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=652 + OR a=83 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR b=102 + OR b=300 + OR (d>=49.0 AND d<50.0 AND d NOT NULL) + } +} {49 83 97 scan 0 sort 0} +do_test where7-2.683.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 53 AND 55) AND a!=54) + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR c=4004 + OR a=95 + OR b=707 + OR f='vwxyzabcd' + OR b=286 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=693 + OR ((a BETWEEN 6 AND 8) AND a!=7) + } +} {6 8 10 11 12 21 26 43 45 47 53 55 63 73 95 99 scan 0 sort 0} +do_test where7-2.683.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 53 AND 55) AND a!=54) + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR c=4004 + OR a=95 + OR b=707 + OR f='vwxyzabcd' + OR b=286 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=693 + OR ((a BETWEEN 6 AND 8) AND a!=7) + } +} {6 8 10 11 12 21 26 43 45 47 53 55 63 73 95 99 scan 0 sort 0} +do_test where7-2.684.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=209 + OR b=198 + OR a=52 + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR d<0.0 + OR (g='rqponml' AND f GLOB 'jklmn*') + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR b=168 + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR f='uvwxyzabc' + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + } +} {7 18 19 20 24 33 35 42 46 52 59 64 72 85 98 scan 0 sort 0} +do_test where7-2.684.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=209 + OR b=198 + OR a=52 + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR d<0.0 + OR (g='rqponml' AND f GLOB 'jklmn*') + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR b=168 + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR f='uvwxyzabc' + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + } +} {7 18 19 20 24 33 35 42 46 52 59 64 72 85 98 scan 0 sort 0} +do_test where7-2.685.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 4 AND 6) AND a!=5) + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR f='rstuvwxyz' + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR a=14 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + } +} {4 6 8 12 14 17 21 26 43 47 69 73 84 89 91 95 99 scan 0 sort 0} +do_test where7-2.685.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 4 AND 6) AND a!=5) + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR f='rstuvwxyz' + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR a=14 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + } +} {4 6 8 12 14 17 21 26 43 47 69 73 84 89 91 95 99 scan 0 sort 0} +do_test where7-2.686.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 13 AND 15) AND a!=14) + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR f='mnopqrstu' + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR a=38 + OR c=26026 + } +} {2 12 13 15 33 35 38 64 76 77 78 90 93 95 97 scan 0 sort 0} +do_test where7-2.686.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 13 AND 15) AND a!=14) + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR f='mnopqrstu' + OR (g='fedcbaz' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR a=38 + OR c=26026 + } +} {2 12 13 15 33 35 38 64 76 77 78 90 93 95 97 scan 0 sort 0} +do_test where7-2.687.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ponmlkj' AND f GLOB 'stuvw*') + OR ((a BETWEEN 71 AND 73) AND a!=72) + OR a=7 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR (g='srqponm' AND f GLOB 'ghijk*') + OR ((a BETWEEN 33 AND 35) AND a!=34) + } +} {7 32 33 35 39 44 71 73 scan 0 sort 0} +do_test where7-2.687.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ponmlkj' AND f GLOB 'stuvw*') + OR ((a BETWEEN 71 AND 73) AND a!=72) + OR a=7 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR (g='srqponm' AND f GLOB 'ghijk*') + OR ((a BETWEEN 33 AND 35) AND a!=34) + } +} {7 32 33 35 39 44 71 73 scan 0 sort 0} +do_test where7-2.688.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=6006 + OR b=938 + OR b=484 + OR b=652 + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR f='opqrstuvw' + } +} {14 15 16 17 18 40 41 44 58 66 67 92 93 scan 0 sort 0} +do_test where7-2.688.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=6006 + OR b=938 + OR b=484 + OR b=652 + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR f='opqrstuvw' + } +} {14 15 16 17 18 40 41 44 58 66 67 92 93 scan 0 sort 0} +do_test where7-2.689.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=27027 + OR b=968 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR b=487 + OR b=924 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR c=14014 + OR b=1001 + } +} {40 41 42 51 70 79 80 81 84 88 91 scan 0 sort 0} +do_test where7-2.689.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=27027 + OR b=968 + OR (d>=51.0 AND d<52.0 AND d NOT NULL) + OR b=487 + OR b=924 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + OR c=14014 + OR b=1001 + } +} {40 41 42 51 70 79 80 81 84 88 91 scan 0 sort 0} +do_test where7-2.690.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=25 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=443 + OR b=564 + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=531 + OR b=1081 + OR a=96 + } +} {10 19 25 43 45 69 71 90 96 97 scan 0 sort 0} +do_test where7-2.690.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=25 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=443 + OR b=564 + OR (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=531 + OR b=1081 + OR a=96 + } +} {10 19 25 43 45 69 71 90 96 97 scan 0 sort 0} +do_test where7-2.691.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=36 + OR (g='srqponm' AND f GLOB 'defgh*') + } +} {29 scan 0 sort 0} +do_test where7-2.691.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=36 + OR (g='srqponm' AND f GLOB 'defgh*') + } +} {29 scan 0 sort 0} +do_test where7-2.692.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'stuvw*') + OR b=531 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR (d>=3.0 AND d<4.0 AND d NOT NULL) + } +} {3 70 93 95 scan 0 sort 0} +do_test where7-2.692.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'stuvw*') + OR b=531 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR (d>=3.0 AND d<4.0 AND d NOT NULL) + } +} {3 70 93 95 scan 0 sort 0} +do_test where7-2.693.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=256 + OR b=1034 + } +} {94 scan 0 sort 0} +do_test where7-2.693.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=256 + OR b=1034 + } +} {94 scan 0 sort 0} +do_test where7-2.694.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR b=784 + OR b=718 + OR a=18 + OR a=3 + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR c=28028 + } +} {3 18 19 21 24 26 47 58 60 73 82 83 84 99 scan 0 sort 0} +do_test where7-2.694.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR (d>=83.0 AND d<84.0 AND d NOT NULL) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR b=784 + OR b=718 + OR a=18 + OR a=3 + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR c=28028 + } +} {3 18 19 21 24 26 47 58 60 73 82 83 84 99 scan 0 sort 0} +do_test where7-2.695.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=473 + OR b=649 + OR ((a BETWEEN 46 AND 48) AND a!=47) + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR b=1100 + OR b=1012 + OR a=72 + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR b=176 + OR b=355 + } +} {16 18 43 46 48 59 72 91 92 100 scan 0 sort 0} +do_test where7-2.695.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=473 + OR b=649 + OR ((a BETWEEN 46 AND 48) AND a!=47) + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR b=1100 + OR b=1012 + OR a=72 + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR b=176 + OR b=355 + } +} {16 18 43 46 48 59 72 91 92 100 scan 0 sort 0} +do_test where7-2.696.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=15.0 AND d<16.0 AND d NOT NULL) + OR f='cdefghijk' + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'ghijk*') + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + } +} {2 15 19 28 29 30 32 54 80 91 scan 0 sort 0} +do_test where7-2.696.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=15.0 AND d<16.0 AND d NOT NULL) + OR f='cdefghijk' + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'ghijk*') + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + } +} {2 15 19 28 29 30 32 54 80 91 scan 0 sort 0} +do_test where7-2.697.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='mlkjihg' AND f GLOB 'ijklm*') + OR b=883 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR b=938 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR f='defghijkl' + OR c=2002 + OR b=990 + } +} {3 4 5 6 17 19 22 29 55 60 81 90 scan 0 sort 0} +do_test where7-2.697.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='mlkjihg' AND f GLOB 'ijklm*') + OR b=883 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR b=938 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR f='defghijkl' + OR c=2002 + OR b=990 + } +} {3 4 5 6 17 19 22 29 55 60 81 90 scan 0 sort 0} +do_test where7-2.698.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 7 AND 9) AND a!=8) + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR b=902 + OR b=25 + } +} {7 9 76 82 scan 0 sort 0} +do_test where7-2.698.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 7 AND 9) AND a!=8) + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR b=902 + OR b=25 + } +} {7 9 76 82 scan 0 sort 0} +do_test where7-2.699.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='tsrqpon' AND f GLOB 'abcde*') + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR b=1092 + OR b=495 + } +} {26 45 55 68 70 74 76 scan 0 sort 0} +do_test where7-2.699.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='tsrqpon' AND f GLOB 'abcde*') + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR ((a BETWEEN 74 AND 76) AND a!=75) + OR b=1092 + OR b=495 + } +} {26 45 55 68 70 74 76 scan 0 sort 0} +do_test where7-2.700.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 90 AND 92) AND a!=91) + OR a=46 + OR a=74 + } +} {46 74 90 92 scan 0 sort 0} +do_test where7-2.700.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 90 AND 92) AND a!=91) + OR a=46 + OR a=74 + } +} {46 74 90 92 scan 0 sort 0} +do_test where7-2.701.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=18 + OR b=66 + OR b=498 + OR b=143 + OR b=1034 + OR b=289 + OR b=319 + } +} {6 13 18 29 94 scan 0 sort 0} +do_test where7-2.701.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=18 + OR b=66 + OR b=498 + OR b=143 + OR b=1034 + OR b=289 + OR b=319 + } +} {6 13 18 29 94 scan 0 sort 0} +do_test where7-2.702.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR (g='srqponm' AND f GLOB 'efghi*') + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR (g='srqponm' AND f GLOB 'cdefg*') + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR f='lmnopqrst' + OR ((a BETWEEN 11 AND 13) AND a!=12) + OR b=872 + OR a=44 + OR ((a BETWEEN 38 AND 40) AND a!=39) + } +} {11 13 25 28 30 37 38 40 44 45 51 54 63 77 79 89 scan 0 sort 0} +do_test where7-2.702.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?abcd*' AND f GLOB 'zabc*') + OR (g='srqponm' AND f GLOB 'efghi*') + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR (g='srqponm' AND f GLOB 'cdefg*') + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR f='lmnopqrst' + OR ((a BETWEEN 11 AND 13) AND a!=12) + OR b=872 + OR a=44 + OR ((a BETWEEN 38 AND 40) AND a!=39) + } +} {11 13 25 28 30 37 38 40 44 45 51 54 63 77 79 89 scan 0 sort 0} +do_test where7-2.703.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR a=20 + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR (g='jihgfed' AND f GLOB 'xyzab*') + OR b=1004 + OR b=77 + OR b=927 + OR a=99 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + } +} {7 17 20 46 66 71 72 73 75 98 99 scan 0 sort 0} +do_test where7-2.703.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR a=20 + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR (g='jihgfed' AND f GLOB 'xyzab*') + OR b=1004 + OR b=77 + OR b=927 + OR a=99 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + } +} {7 17 20 46 66 71 72 73 75 98 99 scan 0 sort 0} +do_test where7-2.704.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=76.0 AND d<77.0 AND d NOT NULL) + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=11 + OR ((a BETWEEN 21 AND 23) AND a!=22) + } +} {1 21 23 45 76 scan 0 sort 0} +do_test where7-2.704.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=76.0 AND d<77.0 AND d NOT NULL) + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=11 + OR ((a BETWEEN 21 AND 23) AND a!=22) + } +} {1 21 23 45 76 scan 0 sort 0} +do_test where7-2.705.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=572 + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {52 57 scan 0 sort 0} +do_test where7-2.705.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=572 + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {52 57 scan 0 sort 0} +do_test where7-2.706.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=44.0 AND d<45.0 AND d NOT NULL) + OR ((a BETWEEN 54 AND 56) AND a!=55) + OR f='lmnopqrst' + OR (f GLOB '?lmno*' AND f GLOB 'klmn*') + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR a=23 + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + } +} {10 11 23 36 37 44 54 56 62 63 69 81 88 89 scan 0 sort 0} +do_test where7-2.706.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=44.0 AND d<45.0 AND d NOT NULL) + OR ((a BETWEEN 54 AND 56) AND a!=55) + OR f='lmnopqrst' + OR (f GLOB '?lmno*' AND f GLOB 'klmn*') + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR a=23 + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + } +} {10 11 23 36 37 44 54 56 62 63 69 81 88 89 scan 0 sort 0} +do_test where7-2.707.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=836 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR b=605 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR b=759 + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR a=40 + OR f='ghijklmno' + OR (g='hgfedcb' AND f GLOB 'hijkl*') + } +} {6 24 32 38 40 46 50 55 58 69 70 76 84 85 89 91 scan 0 sort 0} +do_test where7-2.707.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=836 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR b=605 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR b=759 + OR (f GLOB '?zabc*' AND f GLOB 'yzab*') + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR a=40 + OR f='ghijklmno' + OR (g='hgfedcb' AND f GLOB 'hijkl*') + } +} {6 24 32 38 40 46 50 55 58 69 70 76 84 85 89 91 scan 0 sort 0} +do_test where7-2.708.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + } +} {42 51 scan 0 sort 0} +do_test where7-2.708.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + } +} {42 51 scan 0 sort 0} +do_test where7-2.709.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=27027 + OR b=872 + OR a=56 + } +} {56 79 80 81 scan 0 sort 0} +do_test where7-2.709.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=27027 + OR b=872 + OR a=56 + } +} {56 79 80 81 scan 0 sort 0} +do_test where7-2.710.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=685 + OR b=256 + OR ((a BETWEEN 78 AND 80) AND a!=79) + OR a=44 + OR a=63 + OR a=15 + OR ((a BETWEEN 22 AND 24) AND a!=23) + } +} {15 22 24 44 63 78 80 scan 0 sort 0} +do_test where7-2.710.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=685 + OR b=256 + OR ((a BETWEEN 78 AND 80) AND a!=79) + OR a=44 + OR a=63 + OR a=15 + OR ((a BETWEEN 22 AND 24) AND a!=23) + } +} {15 22 24 44 63 78 80 scan 0 sort 0} +do_test where7-2.711.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='nmlkjih' AND f GLOB 'efghi*') + OR a=34 + OR ((a BETWEEN 6 AND 8) AND a!=7) + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR a=67 + OR a=28 + } +} {6 8 28 34 56 67 75 scan 0 sort 0} +do_test where7-2.711.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='nmlkjih' AND f GLOB 'efghi*') + OR a=34 + OR ((a BETWEEN 6 AND 8) AND a!=7) + OR (d>=75.0 AND d<76.0 AND d NOT NULL) + OR a=67 + OR a=28 + } +} {6 8 28 34 56 67 75 scan 0 sort 0} +do_test where7-2.712.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'pqrst*') + OR a=52 + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR f='ghijklmno' + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=319 + OR a=34 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR f='hijklmnop' + } +} {6 7 12 18 24 29 32 33 34 41 52 58 59 68 70 84 85 scan 0 sort 0} +do_test where7-2.712.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'pqrst*') + OR a=52 + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR f='ghijklmno' + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=319 + OR a=34 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR f='hijklmnop' + } +} {6 7 12 18 24 29 32 33 34 41 52 58 59 68 70 84 85 scan 0 sort 0} +do_test where7-2.713.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'pqrst*') + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR a=47 + } +} {41 47 69 71 scan 0 sort 0} +do_test where7-2.713.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'pqrst*') + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR a=47 + } +} {41 47 69 71 scan 0 sort 0} +do_test where7-2.714.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 33 AND 35) AND a!=34) + OR c=7007 + } +} {19 20 21 33 35 scan 0 sort 0} +do_test where7-2.714.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 33 AND 35) AND a!=34) + OR c=7007 + } +} {19 20 21 33 35 scan 0 sort 0} +do_test where7-2.715.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=531 + OR a=12 + OR b=583 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR a=61 + OR b=187 + } +} {12 17 53 61 93 95 scan 0 sort 0} +do_test where7-2.715.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=531 + OR a=12 + OR b=583 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR a=61 + OR b=187 + } +} {12 17 53 61 93 95 scan 0 sort 0} +do_test where7-2.716.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=31031 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=256 + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR b=715 + OR b=212 + OR b=99 + OR c=29029 + } +} {9 12 38 45 65 66 68 77 79 85 86 87 91 92 93 scan 0 sort 0} +do_test where7-2.716.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=31031 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=256 + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR b=715 + OR b=212 + OR b=99 + OR c=29029 + } +} {9 12 38 45 65 66 68 77 79 85 86 87 91 92 93 scan 0 sort 0} +do_test where7-2.717.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 40 AND 42) AND a!=41) + OR b=33 + OR a=62 + OR b=916 + OR b=1012 + OR a=2 + OR a=51 + OR b=286 + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=80 + } +} {2 3 26 40 42 51 62 92 96 scan 0 sort 0} +do_test where7-2.717.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 40 AND 42) AND a!=41) + OR b=33 + OR a=62 + OR b=916 + OR b=1012 + OR a=2 + OR a=51 + OR b=286 + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=80 + } +} {2 3 26 40 42 51 62 92 96 scan 0 sort 0} +do_test where7-2.718.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=847 + OR f='efghijklm' + OR (d>=6.0 AND d<7.0 AND d NOT NULL) + } +} {4 6 30 56 77 82 scan 0 sort 0} +do_test where7-2.718.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=847 + OR f='efghijklm' + OR (d>=6.0 AND d<7.0 AND d NOT NULL) + } +} {4 6 30 56 77 82 scan 0 sort 0} +do_test where7-2.719.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='tsrqpon' AND f GLOB 'zabcd*') + OR ((a BETWEEN 62 AND 64) AND a!=63) + } +} {25 62 64 scan 0 sort 0} +do_test where7-2.719.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='tsrqpon' AND f GLOB 'zabcd*') + OR ((a BETWEEN 62 AND 64) AND a!=63) + } +} {25 62 64 scan 0 sort 0} +do_test where7-2.720.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 43 AND 45) AND a!=44) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR a=43 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + OR b=729 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + } +} {14 31 33 43 45 53 scan 0 sort 0} +do_test where7-2.720.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 43 AND 45) AND a!=44) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR a=43 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + OR b=729 + OR (g='vutsrqp' AND f GLOB 'opqrs*') + } +} {14 31 33 43 45 53 scan 0 sort 0} +do_test where7-2.721.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='efghijklm' + OR a=70 + OR b=278 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR c=8008 + OR f='opqrstuvw' + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR (g='xwvutsr' AND f GLOB 'fghij*') + } +} {4 5 14 22 23 24 25 30 33 35 40 56 66 70 82 92 scan 0 sort 0} +do_test where7-2.721.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='efghijklm' + OR a=70 + OR b=278 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR c=8008 + OR f='opqrstuvw' + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR (g='xwvutsr' AND f GLOB 'fghij*') + } +} {4 5 14 22 23 24 25 30 33 35 40 56 66 70 82 92 scan 0 sort 0} +do_test where7-2.722.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 40 AND 42) AND a!=41) + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR c<=10 + OR (g='srqponm' AND f GLOB 'fghij*') + OR a=35 + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=1089 + OR a=73 + OR b=737 + OR c=18018 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + } +} {6 23 31 32 35 40 42 52 53 54 58 62 67 73 84 99 scan 0 sort 0} +do_test where7-2.722.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 40 AND 42) AND a!=41) + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR c<=10 + OR (g='srqponm' AND f GLOB 'fghij*') + OR a=35 + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=1089 + OR a=73 + OR b=737 + OR c=18018 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + } +} {6 23 31 32 35 40 42 52 53 54 58 62 67 73 84 99 scan 0 sort 0} +do_test where7-2.723.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 0 AND 2) AND a!=1) + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=762 + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR a=80 + } +} {2 39 41 79 80 95 scan 0 sort 0} +do_test where7-2.723.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 0 AND 2) AND a!=1) + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=762 + OR ((a BETWEEN 39 AND 41) AND a!=40) + OR a=80 + } +} {2 39 41 79 80 95 scan 0 sort 0} +do_test where7-2.724.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 28 AND 30) AND a!=29) + OR b=737 + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR b=979 + OR a=36 + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + OR a=55 + OR (g='fedcbaz' AND f GLOB 'rstuv*') + } +} {20 28 30 36 46 50 55 67 72 80 82 89 95 98 scan 0 sort 0} +do_test where7-2.724.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 28 AND 30) AND a!=29) + OR b=737 + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR b=979 + OR a=36 + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + OR a=55 + OR (g='fedcbaz' AND f GLOB 'rstuv*') + } +} {20 28 30 36 46 50 55 67 72 80 82 89 95 98 scan 0 sort 0} +do_test where7-2.725.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=75 + OR a=61 + OR (g='onmlkji' AND f GLOB 'abcde*') + OR (g='gfedcba' AND f GLOB 'nopqr*') + } +} {52 61 75 91 scan 0 sort 0} +do_test where7-2.725.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=75 + OR a=61 + OR (g='onmlkji' AND f GLOB 'abcde*') + OR (g='gfedcba' AND f GLOB 'nopqr*') + } +} {52 61 75 91 scan 0 sort 0} +do_test where7-2.726.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1004 + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR a=56 + } +} {7 56 61 scan 0 sort 0} +do_test where7-2.726.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1004 + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR a=56 + } +} {7 56 61 scan 0 sort 0} +do_test where7-2.727.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=93 + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR a=83 + OR b=828 + OR b=454 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR b=924 + OR (g='lkjihgf' AND f GLOB 'opqrs*') + OR a=50 + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + } +} {38 50 58 66 83 84 89 91 93 scan 0 sort 0} +do_test where7-2.727.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=93 + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR a=83 + OR b=828 + OR b=454 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR b=924 + OR (g='lkjihgf' AND f GLOB 'opqrs*') + OR a=50 + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + } +} {38 50 58 66 83 84 89 91 93 scan 0 sort 0} +do_test where7-2.728.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='stuvwxyza' + OR a=44 + OR c=2002 + } +} {4 5 6 18 44 70 96 scan 0 sort 0} +do_test where7-2.728.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='stuvwxyza' + OR a=44 + OR c=2002 + } +} {4 5 6 18 44 70 96 scan 0 sort 0} +do_test where7-2.729.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=55 + OR a=65 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + } +} {14 40 55 65 66 92 scan 0 sort 0} +do_test where7-2.729.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=55 + OR a=65 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + } +} {14 40 55 65 66 92 scan 0 sort 0} +do_test where7-2.730.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 72 AND 74) AND a!=73) + OR b=605 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR f='ijklmnopq' + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR c=9009 + OR b=374 + } +} {8 12 13 25 26 27 34 43 55 60 72 74 86 88 scan 0 sort 0} +do_test where7-2.730.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 72 AND 74) AND a!=73) + OR b=605 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR f='ijklmnopq' + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR c=9009 + OR b=374 + } +} {8 12 13 25 26 27 34 43 55 60 72 74 86 88 scan 0 sort 0} +do_test where7-2.731.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=476 + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR b=982 + OR a=43 + OR b=355 + } +} {8 43 scan 0 sort 0} +do_test where7-2.731.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=476 + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR b=982 + OR a=43 + OR b=355 + } +} {8 43 scan 0 sort 0} +do_test where7-2.732.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=85 + OR b=718 + OR (g='fedcbaz' AND f GLOB 'pqrst*') + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + } +} {1 25 27 53 79 85 93 scan 0 sort 0} +do_test where7-2.732.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=85 + OR b=718 + OR (g='fedcbaz' AND f GLOB 'pqrst*') + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + } +} {1 25 27 53 79 85 93 scan 0 sort 0} +do_test where7-2.733.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=73.0 AND d<74.0 AND d NOT NULL) + OR ((a BETWEEN 96 AND 98) AND a!=97) + } +} {73 96 98 scan 0 sort 0} +do_test where7-2.733.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=73.0 AND d<74.0 AND d NOT NULL) + OR ((a BETWEEN 96 AND 98) AND a!=97) + } +} {73 96 98 scan 0 sort 0} +do_test where7-2.734.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=176 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR ((a BETWEEN 27 AND 29) AND a!=28) + OR b=619 + OR b=597 + OR b=198 + OR a=27 + OR b=91 + OR a=77 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + } +} {16 18 25 27 29 77 80 scan 0 sort 0} +do_test where7-2.734.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=176 + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR ((a BETWEEN 27 AND 29) AND a!=28) + OR b=619 + OR b=597 + OR b=198 + OR a=27 + OR b=91 + OR a=77 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + } +} {16 18 25 27 29 77 80 scan 0 sort 0} +do_test where7-2.735.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=41 + OR b=528 + OR c=3003 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR b=22 + } +} {2 7 8 9 20 22 41 48 scan 0 sort 0} +do_test where7-2.735.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=41 + OR b=528 + OR c=3003 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR b=22 + } +} {2 7 8 9 20 22 41 48 scan 0 sort 0} +do_test where7-2.736.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR b=465 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=37 + OR b=1056 + OR (g='srqponm' AND f GLOB 'defgh*') + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR b=1023 + } +} {4 16 29 37 42 63 65 68 93 94 96 scan 0 sort 0} +do_test where7-2.736.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR b=465 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=37 + OR b=1056 + OR (g='srqponm' AND f GLOB 'defgh*') + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR b=1023 + } +} {4 16 29 37 42 63 65 68 93 94 96 scan 0 sort 0} +do_test where7-2.737.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=76 + OR a=8 + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR b=495 + OR b=663 + OR a=98 + OR b=748 + } +} {8 27 45 68 76 98 scan 0 sort 0} +do_test where7-2.737.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=76 + OR a=8 + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR b=495 + OR b=663 + OR a=98 + OR b=748 + } +} {8 27 45 68 76 98 scan 0 sort 0} +do_test where7-2.738.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1081 + OR b=542 + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR b=828 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR a=18 + } +} {18 47 61 64 67 scan 0 sort 0} +do_test where7-2.738.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1081 + OR b=542 + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR b=828 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR a=18 + } +} {18 47 61 64 67 scan 0 sort 0} +do_test where7-2.739.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='abcdefghi' + OR a=14 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR c=27027 + OR a=47 + } +} {13 14 26 47 52 78 79 80 81 scan 0 sort 0} +do_test where7-2.739.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='abcdefghi' + OR a=14 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR c=27027 + OR a=47 + } +} {13 14 26 47 52 78 79 80 81 scan 0 sort 0} +do_test where7-2.740.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=31031 + OR b=737 + OR a=37 + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR a=91 + OR b=77 + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + } +} {7 37 65 67 91 92 93 94 98 100 scan 0 sort 0} +do_test where7-2.740.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=31031 + OR b=737 + OR a=37 + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR a=91 + OR b=77 + OR (d>=94.0 AND d<95.0 AND d NOT NULL) + } +} {7 37 65 67 91 92 93 94 98 100 scan 0 sort 0} +do_test where7-2.741.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=17 + OR b=484 + OR c=3003 + OR b=121 + OR a=53 + } +} {7 8 9 11 17 44 53 scan 0 sort 0} +do_test where7-2.741.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=17 + OR b=484 + OR c=3003 + OR b=121 + OR a=53 + } +} {7 8 9 11 17 44 53 scan 0 sort 0} +do_test where7-2.742.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=880 + OR b=696 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR b=308 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR ((a BETWEEN 96 AND 98) AND a!=97) + } +} {5 28 65 80 96 98 scan 0 sort 0} +do_test where7-2.742.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=880 + OR b=696 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR b=308 + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR ((a BETWEEN 96 AND 98) AND a!=97) + } +} {5 28 65 80 96 98 scan 0 sort 0} +do_test where7-2.743.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='tsrqpon' AND f GLOB 'zabcd*') + OR a=24 + OR f IS NULL + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR c=12012 + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + } +} {24 25 34 35 36 57 77 88 scan 0 sort 0} +do_test where7-2.743.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='tsrqpon' AND f GLOB 'zabcd*') + OR a=24 + OR f IS NULL + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR c=12012 + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + } +} {24 25 34 35 36 57 77 88 scan 0 sort 0} +do_test where7-2.744.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=94 + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR b=792 + OR a=77 + OR a=26 + OR b=641 + OR a=38 + } +} {26 38 72 74 77 85 94 scan 0 sort 0} +do_test where7-2.744.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=94 + OR (d>=74.0 AND d<75.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR b=792 + OR a=77 + OR a=26 + OR b=641 + OR a=38 + } +} {26 38 72 74 77 85 94 scan 0 sort 0} +do_test where7-2.745.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 51 AND 53) AND a!=52) + OR (d>=30.0 AND d<31.0 AND d NOT NULL) + OR b=14 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR b=121 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + } +} {11 15 17 27 30 51 53 63 86 89 91 scan 0 sort 0} +do_test where7-2.745.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 51 AND 53) AND a!=52) + OR (d>=30.0 AND d<31.0 AND d NOT NULL) + OR b=14 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR ((a BETWEEN 15 AND 17) AND a!=16) + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR b=121 + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + } +} {11 15 17 27 30 51 53 63 86 89 91 scan 0 sort 0} +do_test where7-2.746.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=517 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR f='opqrstuvw' + } +} {14 40 47 66 69 71 92 scan 0 sort 0} +do_test where7-2.746.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=517 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR f='opqrstuvw' + } +} {14 40 47 66 69 71 92 scan 0 sort 0} +do_test where7-2.747.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=84.0 AND d<85.0 AND d NOT NULL) + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=267 + OR c=19019 + OR a=42 + OR b=938 + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + } +} {1 9 17 21 22 24 32 34 35 42 43 55 56 57 61 69 84 87 95 scan 0 sort 0} +do_test where7-2.747.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=84.0 AND d<85.0 AND d NOT NULL) + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=267 + OR c=19019 + OR a=42 + OR b=938 + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + } +} {1 9 17 21 22 24 32 34 35 42 43 55 56 57 61 69 84 87 95 scan 0 sort 0} +do_test where7-2.748.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=179 + OR a=50 + OR (g='srqponm' AND f GLOB 'defgh*') + } +} {29 50 scan 0 sort 0} +do_test where7-2.748.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=179 + OR a=50 + OR (g='srqponm' AND f GLOB 'defgh*') + } +} {29 50 scan 0 sort 0} +do_test where7-2.749.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='vutsrqp' AND f GLOB 'rstuv*') + OR f='xyzabcdef' + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR b=575 + OR b=385 + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=46 + OR b=220 + OR a=63 + } +} {17 18 20 23 35 46 49 51 63 65 75 scan 0 sort 0} +do_test where7-2.749.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='vutsrqp' AND f GLOB 'rstuv*') + OR f='xyzabcdef' + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR b=575 + OR b=385 + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=46 + OR b=220 + OR a=63 + } +} {17 18 20 23 35 46 49 51 63 65 75 scan 0 sort 0} +do_test where7-2.750.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1056 + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=1078 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + OR c=31031 + OR b=869 + OR (g='jihgfed' AND f GLOB 'zabcd*') + OR b=245 + OR a=92 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=880 + } +} {66 77 79 80 91 92 93 96 98 scan 0 sort 0} +do_test where7-2.750.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1056 + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=1078 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + OR c=31031 + OR b=869 + OR (g='jihgfed' AND f GLOB 'zabcd*') + OR b=245 + OR a=92 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=880 + } +} {66 77 79 80 91 92 93 96 98 scan 0 sort 0} +do_test where7-2.751.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1078 + OR c=28028 + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR c=9009 + OR a=17 + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + } +} {16 17 19 25 26 27 38 39 40 42 61 68 82 83 84 94 98 scan 0 sort 0} +do_test where7-2.751.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1078 + OR c=28028 + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR (g='mlkjihg' AND f GLOB 'jklmn*') + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR c=9009 + OR a=17 + OR (d>=39.0 AND d<40.0 AND d NOT NULL) + } +} {16 17 19 25 26 27 38 39 40 42 61 68 82 83 84 94 98 scan 0 sort 0} +do_test where7-2.752.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=57.0 AND d<58.0 AND d NOT NULL) + OR b=762 + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR f='tuvwxyzab' + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR b=1034 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + } +} {14 19 31 33 44 45 57 58 71 94 97 scan 0 sort 0} +do_test where7-2.752.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=57.0 AND d<58.0 AND d NOT NULL) + OR b=762 + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR f='tuvwxyzab' + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR b=1034 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + } +} {14 19 31 33 44 45 57 58 71 94 97 scan 0 sort 0} +do_test where7-2.753.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=47 + OR b=187 + OR a=56 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR ((a BETWEEN 89 AND 91) AND a!=90) + } +} {17 30 32 56 68 70 89 91 scan 0 sort 0} +do_test where7-2.753.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=47 + OR b=187 + OR a=56 + OR ((a BETWEEN 30 AND 32) AND a!=31) + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR ((a BETWEEN 89 AND 91) AND a!=90) + } +} {17 30 32 56 68 70 89 91 scan 0 sort 0} +do_test where7-2.754.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=11011 + OR a=14 + OR c=16016 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'efghi*') + OR f='jklmnopqr' + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=916 + } +} {9 14 21 25 30 31 32 33 35 46 47 48 61 87 96 scan 0 sort 0} +do_test where7-2.754.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=11011 + OR a=14 + OR c=16016 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'efghi*') + OR f='jklmnopqr' + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=916 + } +} {9 14 21 25 30 31 32 33 35 46 47 48 61 87 96 scan 0 sort 0} +do_test where7-2.755.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=949 + OR (g='srqponm' AND f GLOB 'cdefg*') + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR c<=10 + OR a=14 + OR b=608 + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=121 + OR b=333 + OR ((a BETWEEN 93 AND 95) AND a!=94) + } +} {11 14 17 28 66 93 95 98 scan 0 sort 0} +do_test where7-2.755.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=949 + OR (g='srqponm' AND f GLOB 'cdefg*') + OR (g='vutsrqp' AND f GLOB 'rstuv*') + OR c<=10 + OR a=14 + OR b=608 + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=121 + OR b=333 + OR ((a BETWEEN 93 AND 95) AND a!=94) + } +} {11 14 17 28 66 93 95 98 scan 0 sort 0} +do_test where7-2.756.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=355 + OR b=627 + OR b=1001 + OR b=1026 + OR ((a BETWEEN 58 AND 60) AND a!=59) + } +} {57 58 60 69 91 scan 0 sort 0} +do_test where7-2.756.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'rstuv*') + OR b=355 + OR b=627 + OR b=1001 + OR b=1026 + OR ((a BETWEEN 58 AND 60) AND a!=59) + } +} {57 58 60 69 91 scan 0 sort 0} +do_test where7-2.757.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'efghi*') + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + } +} {4 79 scan 0 sort 0} +do_test where7-2.757.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'efghi*') + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + } +} {4 79 scan 0 sort 0} +do_test where7-2.758.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=685 + OR a=14 + OR b=990 + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR f='efghijklm' + OR c=1001 + OR b=784 + OR (g='srqponm' AND f GLOB 'ghijk*') + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + } +} {1 2 3 4 14 26 30 32 56 69 82 90 scan 0 sort 0} +do_test where7-2.758.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=685 + OR a=14 + OR b=990 + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR f='efghijklm' + OR c=1001 + OR b=784 + OR (g='srqponm' AND f GLOB 'ghijk*') + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + } +} {1 2 3 4 14 26 30 32 56 69 82 90 scan 0 sort 0} +do_test where7-2.759.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=54 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR c=26026 + OR ((a BETWEEN 97 AND 99) AND a!=98) + } +} {39 54 76 77 78 97 99 scan 0 sort 0} +do_test where7-2.759.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=54 + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR c=26026 + OR ((a BETWEEN 97 AND 99) AND a!=98) + } +} {39 54 76 77 78 97 99 scan 0 sort 0} +do_test where7-2.760.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'ghijk*') + OR c=24024 + OR a=98 + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR a=5 + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='rqponml' AND f GLOB 'klmno*') + OR f='pqrstuvwx' + OR f='bcdefghij' + OR b=1001 + OR ((a BETWEEN 77 AND 79) AND a!=78) + } +} {1 5 15 21 27 31 33 36 41 53 67 70 71 72 77 79 84 91 93 98 scan 0 sort 0} +do_test where7-2.760.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'ghijk*') + OR c=24024 + OR a=98 + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + OR a=5 + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (g='rqponml' AND f GLOB 'klmno*') + OR f='pqrstuvwx' + OR f='bcdefghij' + OR b=1001 + OR ((a BETWEEN 77 AND 79) AND a!=78) + } +} {1 5 15 21 27 31 33 36 41 53 67 70 71 72 77 79 84 91 93 98 scan 0 sort 0} +do_test where7-2.761.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=781 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR f='lmnopqrst' + OR a=39 + OR a=100 + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {1 11 14 37 39 40 54 56 58 63 66 71 89 92 99 100 scan 0 sort 0} +do_test where7-2.761.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=781 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR f='lmnopqrst' + OR a=39 + OR a=100 + OR ((a BETWEEN 56 AND 58) AND a!=57) + } +} {1 11 14 37 39 40 54 56 58 63 66 71 89 92 99 100 scan 0 sort 0} +do_test where7-2.762.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=4004 + OR b=718 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR a=50 + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + OR b=363 + OR (g='rqponml' AND f GLOB 'ijklm*') + OR b=1023 + } +} {10 11 12 33 34 40 50 93 scan 0 sort 0} +do_test where7-2.762.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=4004 + OR b=718 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR a=50 + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + OR b=363 + OR (g='rqponml' AND f GLOB 'ijklm*') + OR b=1023 + } +} {10 11 12 33 34 40 50 93 scan 0 sort 0} +do_test where7-2.763.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1081 + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR b=473 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR b=586 + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + } +} {20 26 43 45 46 55 72 98 scan 0 sort 0} +do_test where7-2.763.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1081 + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR b=473 + OR ((a BETWEEN 43 AND 45) AND a!=44) + OR b=586 + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR (f GLOB '?vwxy*' AND f GLOB 'uvwx*') + } +} {20 26 43 45 46 55 72 98 scan 0 sort 0} +do_test where7-2.764.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + } +} {7 13 33 58 59 85 scan 0 sort 0} +do_test where7-2.764.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + } +} {7 13 33 58 59 85 scan 0 sort 0} +do_test where7-2.765.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'hijkl*') + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR a=47 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR (g='lkjihgf' AND f GLOB 'lmnop*') + OR (d>=84.0 AND d<85.0 AND d NOT NULL) + OR f='lmnopqrst' + } +} {11 37 47 63 68 76 78 84 85 89 scan 0 sort 0} +do_test where7-2.765.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'hijkl*') + OR ((a BETWEEN 76 AND 78) AND a!=77) + OR a=47 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR (g='lkjihgf' AND f GLOB 'lmnop*') + OR (d>=84.0 AND d<85.0 AND d NOT NULL) + OR f='lmnopqrst' + } +} {11 37 47 63 68 76 78 84 85 89 scan 0 sort 0} +do_test where7-2.766.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c>=34035 + OR a=29 + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR f='abcdefghi' + OR b=993 + OR ((a BETWEEN 52 AND 54) AND a!=53) + OR ((a BETWEEN 45 AND 47) AND a!=46) + } +} {19 21 26 29 45 47 52 54 73 78 99 scan 0 sort 0} +do_test where7-2.766.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c>=34035 + OR a=29 + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR (f GLOB '?wxyz*' AND f GLOB 'vwxy*') + OR f='abcdefghi' + OR b=993 + OR ((a BETWEEN 52 AND 54) AND a!=53) + OR ((a BETWEEN 45 AND 47) AND a!=46) + } +} {19 21 26 29 45 47 52 54 73 78 99 scan 0 sort 0} +do_test where7-2.767.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=696 + OR b=154 + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR a=22 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR a=52 + OR a=21 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + } +} {14 16 21 22 24 47 52 63 70 scan 0 sort 0} +do_test where7-2.767.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=696 + OR b=154 + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR a=22 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR a=52 + OR a=21 + OR (d>=70.0 AND d<71.0 AND d NOT NULL) + } +} {14 16 21 22 24 47 52 63 70 scan 0 sort 0} +do_test where7-2.768.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=693 + OR b=201 + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR b=520 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR b=407 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR c>=34035 + OR b=135 + } +} {23 25 36 37 38 63 scan 0 sort 0} +do_test where7-2.768.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=693 + OR b=201 + OR ((a BETWEEN 36 AND 38) AND a!=37) + OR b=520 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR b=407 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR c>=34035 + OR b=135 + } +} {23 25 36 37 38 63 scan 0 sort 0} +do_test where7-2.769.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=43.0 AND d<44.0 AND d NOT NULL) + OR b=707 + OR b=14 + OR b=1089 + OR b=352 + } +} {32 43 99 scan 0 sort 0} +do_test where7-2.769.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=43.0 AND d<44.0 AND d NOT NULL) + OR b=707 + OR b=14 + OR b=1089 + OR b=352 + } +} {32 43 99 scan 0 sort 0} +do_test where7-2.770.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=278 + OR b=278 + OR b=825 + OR f='rstuvwxyz' + OR b=938 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR ((a BETWEEN 43 AND 45) AND a!=44) + } +} {17 19 43 45 69 75 95 scan 0 sort 0} +do_test where7-2.770.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=278 + OR b=278 + OR b=825 + OR f='rstuvwxyz' + OR b=938 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR ((a BETWEEN 43 AND 45) AND a!=44) + } +} {17 19 43 45 69 75 95 scan 0 sort 0} +do_test where7-2.771.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 32 AND 34) AND a!=33) + OR b=1045 + OR c=27027 + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + } +} {11 32 34 37 63 79 80 81 89 95 scan 0 sort 0} +do_test where7-2.771.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 32 AND 34) AND a!=33) + OR b=1045 + OR c=27027 + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + } +} {11 32 34 37 63 79 80 81 89 95 scan 0 sort 0} +do_test where7-2.772.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=87 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR b=487 + OR (g='gfedcba' AND f GLOB 'mnopq*') + } +} {47 87 90 scan 0 sort 0} +do_test where7-2.772.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=87 + OR (d>=47.0 AND d<48.0 AND d NOT NULL) + OR b=487 + OR (g='gfedcba' AND f GLOB 'mnopq*') + } +} {47 87 90 scan 0 sort 0} +do_test where7-2.773.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 30 AND 32) AND a!=31) + OR b=69 + OR b=608 + OR b=814 + OR a=67 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR b=1059 + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + OR a=18 + OR b=407 + OR ((a BETWEEN 10 AND 12) AND a!=11) + } +} {10 12 18 30 32 37 58 61 67 74 scan 0 sort 0} +do_test where7-2.773.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 30 AND 32) AND a!=31) + OR b=69 + OR b=608 + OR b=814 + OR a=67 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR b=1059 + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + OR a=18 + OR b=407 + OR ((a BETWEEN 10 AND 12) AND a!=11) + } +} {10 12 18 30 32 37 58 61 67 74 scan 0 sort 0} +do_test where7-2.774.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=223 + OR b=80 + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR ((a BETWEEN 74 AND 76) AND a!=75) + } +} {74 76 97 99 scan 0 sort 0} +do_test where7-2.774.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=223 + OR b=80 + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR ((a BETWEEN 74 AND 76) AND a!=75) + } +} {74 76 97 99 scan 0 sort 0} +do_test where7-2.775.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=220 + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR b=363 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR ((a BETWEEN 10 AND 12) AND a!=11) + } +} {10 12 20 33 52 54 55 66 scan 0 sort 0} +do_test where7-2.775.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=220 + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR b=363 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'defgh*') + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR ((a BETWEEN 10 AND 12) AND a!=11) + } +} {10 12 20 33 52 54 55 66 scan 0 sort 0} +do_test where7-2.776.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=498 + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR b=880 + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR b=828 + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR b=113 + } +} {5 15 60 62 80 scan 0 sort 0} +do_test where7-2.776.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=498 + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR b=880 + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR b=828 + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR b=113 + } +} {5 15 60 62 80 scan 0 sort 0} +do_test where7-2.777.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1059 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR b=960 + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=894 + OR c=2002 + } +} {4 5 6 12 16 20 42 68 94 scan 0 sort 0} +do_test where7-2.777.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1059 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR b=960 + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR b=894 + OR c=2002 + } +} {4 5 6 12 16 20 42 68 94 scan 0 sort 0} +do_test where7-2.778.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=14 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + } +} {85 scan 0 sort 0} +do_test where7-2.778.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=14 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + } +} {85 scan 0 sort 0} +do_test where7-2.779.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=806 + OR (g='rqponml' AND f GLOB 'hijkl*') + OR b=795 + OR ((a BETWEEN 99 AND 101) AND a!=100) + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR c=23023 + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + } +} {21 23 33 67 68 69 86 88 99 scan 0 sort 0} +do_test where7-2.779.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=806 + OR (g='rqponml' AND f GLOB 'hijkl*') + OR b=795 + OR ((a BETWEEN 99 AND 101) AND a!=100) + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR c=23023 + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + } +} {21 23 33 67 68 69 86 88 99 scan 0 sort 0} +do_test where7-2.780.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=726 + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR f='abcdefghi' + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR b=869 + } +} {8 10 15 26 41 52 66 67 78 79 92 93 scan 0 sort 0} +do_test where7-2.780.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=726 + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR f='abcdefghi' + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR b=869 + } +} {8 10 15 26 41 52 66 67 78 79 92 93 scan 0 sort 0} +do_test where7-2.781.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=59 + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR b=1081 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + } +} {5 7 59 96 scan 0 sort 0} +do_test where7-2.781.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=59 + OR ((a BETWEEN 5 AND 7) AND a!=6) + OR b=1081 + OR (g='fedcbaz' AND f GLOB 'stuvw*') + } +} {5 7 59 96 scan 0 sort 0} +do_test where7-2.782.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'nopqr*') + OR b=1037 + OR b=132 + OR c=1001 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=32 + } +} {1 2 3 12 18 20 32 39 58 68 91 scan 0 sort 0} +do_test where7-2.782.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'nopqr*') + OR b=1037 + OR b=132 + OR c=1001 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=32 + } +} {1 2 3 12 18 20 32 39 58 68 91 scan 0 sort 0} +do_test where7-2.783.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=24 + OR b=927 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR a=7 + OR b=462 + OR b=608 + OR b=781 + OR b=253 + OR c=25025 + OR b=132 + } +} {7 12 23 24 42 52 71 73 74 75 scan 0 sort 0} +do_test where7-2.783.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=24 + OR b=927 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR a=7 + OR b=462 + OR b=608 + OR b=781 + OR b=253 + OR c=25025 + OR b=132 + } +} {7 12 23 24 42 52 71 73 74 75 scan 0 sort 0} +do_test where7-2.784.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=1001 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR a=83 + } +} {23 25 61 83 91 scan 0 sort 0} +do_test where7-2.784.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=1001 + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR a=83 + } +} {23 25 61 83 91 scan 0 sort 0} +do_test where7-2.785.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR b=36 + OR (f GLOB '?efgh*' AND f GLOB 'defg*') + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR ((a BETWEEN 46 AND 48) AND a!=47) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR ((a BETWEEN 26 AND 28) AND a!=27) + } +} {3 26 28 29 31 33 46 48 55 60 73 77 80 81 82 91 scan 0 sort 0} +do_test where7-2.785.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR b=36 + OR (f GLOB '?efgh*' AND f GLOB 'defg*') + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR ((a BETWEEN 46 AND 48) AND a!=47) + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR (d>=91.0 AND d<92.0 AND d NOT NULL) + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR ((a BETWEEN 26 AND 28) AND a!=27) + } +} {3 26 28 29 31 33 46 48 55 60 73 77 80 81 82 91 scan 0 sort 0} +do_test where7-2.786.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=69 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR a=98 + OR b=300 + OR a=41 + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR a=33 + OR ((a BETWEEN 10 AND 12) AND a!=11) + } +} {1 2 10 12 28 33 37 39 41 54 58 60 69 80 98 scan 0 sort 0} +do_test where7-2.786.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=69 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR a=98 + OR b=300 + OR a=41 + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR a=33 + OR ((a BETWEEN 10 AND 12) AND a!=11) + } +} {1 2 10 12 28 33 37 39 41 54 58 60 69 80 98 scan 0 sort 0} +do_test where7-2.787.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 68 AND 70) AND a!=69) + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR ((a BETWEEN 94 AND 96) AND a!=95) + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR b=619 + OR c=6006 + OR b=91 + OR b=297 + OR b=165 + } +} {1 15 16 17 18 22 24 27 53 68 70 71 79 90 94 96 scan 0 sort 0} +do_test where7-2.787.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 68 AND 70) AND a!=69) + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR ((a BETWEEN 94 AND 96) AND a!=95) + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR b=619 + OR c=6006 + OR b=91 + OR b=297 + OR b=165 + } +} {1 15 16 17 18 22 24 27 53 68 70 71 79 90 94 96 scan 0 sort 0} +do_test where7-2.788.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 9 AND 11) AND a!=10) + OR a=55 + OR (g='jihgfed' AND f GLOB 'xyzab*') + } +} {9 11 55 75 scan 0 sort 0} +do_test where7-2.788.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 9 AND 11) AND a!=10) + OR a=55 + OR (g='jihgfed' AND f GLOB 'xyzab*') + } +} {9 11 55 75 scan 0 sort 0} +do_test where7-2.789.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR b=737 + OR b=201 + OR a=7 + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR b=957 + } +} {2 7 26 67 84 86 87 scan 0 sort 0} +do_test where7-2.789.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR b=737 + OR b=201 + OR a=7 + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (g='yxwvuts' AND f GLOB 'cdefg*') + OR b=957 + } +} {2 7 26 67 84 86 87 scan 0 sort 0} +do_test where7-2.790.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 90 AND 92) AND a!=91) + OR a=74 + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR a=89 + } +} {18 44 67 70 74 79 89 90 92 95 96 97 scan 0 sort 0} +do_test where7-2.790.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 90 AND 92) AND a!=91) + OR a=74 + OR (g='lkjihgf' AND f GLOB 'pqrst*') + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR (f GLOB '?tuvw*' AND f GLOB 'stuv*') + OR a=89 + } +} {18 44 67 70 74 79 89 90 92 95 96 97 scan 0 sort 0} +do_test where7-2.791.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=179 + OR b=1081 + OR b=377 + OR b=495 + OR b=564 + OR b=289 + OR (g='qponmlk' AND f GLOB 'nopqr*') + } +} {39 45 scan 0 sort 0} +do_test where7-2.791.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=179 + OR b=1081 + OR b=377 + OR b=495 + OR b=564 + OR b=289 + OR (g='qponmlk' AND f GLOB 'nopqr*') + } +} {39 45 scan 0 sort 0} +do_test where7-2.792.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='utsrqpo' AND f GLOB 'wxyza*') + OR a=69 + OR a=12 + OR b=718 + OR ((a BETWEEN 20 AND 22) AND a!=21) + } +} {12 20 22 69 scan 0 sort 0} +do_test where7-2.792.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='utsrqpo' AND f GLOB 'wxyza*') + OR a=69 + OR a=12 + OR b=718 + OR ((a BETWEEN 20 AND 22) AND a!=21) + } +} {12 20 22 69 scan 0 sort 0} +do_test where7-2.793.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='tsrqpon' AND f GLOB 'zabcd*') + OR f='klmnopqrs' + OR b=674 + OR a=96 + OR a=99 + OR b=608 + OR b=707 + OR f='cdefghijk' + OR a=91 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + } +} {2 10 23 25 28 36 54 62 80 88 91 96 99 scan 0 sort 0} +do_test where7-2.793.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='tsrqpon' AND f GLOB 'zabcd*') + OR f='klmnopqrs' + OR b=674 + OR a=96 + OR a=99 + OR b=608 + OR b=707 + OR f='cdefghijk' + OR a=91 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + } +} {2 10 23 25 28 36 54 62 80 88 91 96 99 scan 0 sort 0} +do_test where7-2.794.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR b=564 + OR b=784 + OR b=418 + OR b=275 + OR (g='gfedcba' AND f GLOB 'klmno*') + OR a=58 + OR c=11011 + OR b=660 + } +} {9 25 31 32 33 35 38 58 60 61 87 88 scan 0 sort 0} +do_test where7-2.794.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR b=564 + OR b=784 + OR b=418 + OR b=275 + OR (g='gfedcba' AND f GLOB 'klmno*') + OR a=58 + OR c=11011 + OR b=660 + } +} {9 25 31 32 33 35 38 58 60 61 87 88 scan 0 sort 0} +do_test where7-2.795.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=25.0 AND d<26.0 AND d NOT NULL) + OR b=509 + OR b=1004 + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (g='mlkjihg' AND f GLOB 'hijkl*') + OR f='pqrstuvwx' + } +} {15 25 28 30 41 57 59 67 93 scan 0 sort 0} +do_test where7-2.795.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=25.0 AND d<26.0 AND d NOT NULL) + OR b=509 + OR b=1004 + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR ((a BETWEEN 57 AND 59) AND a!=58) + OR (g='mlkjihg' AND f GLOB 'hijkl*') + OR f='pqrstuvwx' + } +} {15 25 28 30 41 57 59 67 93 scan 0 sort 0} +do_test where7-2.796.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=440 + OR ((a BETWEEN 52 AND 54) AND a!=53) + } +} {40 52 54 scan 0 sort 0} +do_test where7-2.796.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=440 + OR ((a BETWEEN 52 AND 54) AND a!=53) + } +} {40 52 54 scan 0 sort 0} +do_test where7-2.797.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=95.0 AND d<96.0 AND d NOT NULL) + OR f='abcdefghi' + } +} {26 52 78 95 scan 0 sort 0} +do_test where7-2.797.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=95.0 AND d<96.0 AND d NOT NULL) + OR f='abcdefghi' + } +} {26 52 78 95 scan 0 sort 0} +do_test where7-2.798.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=19 + OR a=29 + OR b=476 + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR b=91 + } +} {19 29 41 scan 0 sort 0} +do_test where7-2.798.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=19 + OR a=29 + OR b=476 + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR b=91 + } +} {19 29 41 scan 0 sort 0} +do_test where7-2.799.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='lmnopqrst' + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR a=47 + OR a=71 + } +} {8 11 37 47 63 71 89 scan 0 sort 0} +do_test where7-2.799.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='lmnopqrst' + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR a=47 + OR a=71 + } +} {8 11 37 47 63 71 89 scan 0 sort 0} +do_test where7-2.800.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=531 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=44 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR b=707 + OR b=322 + } +} {4 12 32 34 49 84 95 97 scan 0 sort 0} +do_test where7-2.800.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=531 + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=44 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR b=707 + OR b=322 + } +} {4 12 32 34 49 84 95 97 scan 0 sort 0} +do_test where7-2.801.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?efgh*' AND f GLOB 'defg*') + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR f='jklmnopqr' + } +} {3 9 29 35 55 61 81 82 87 89 scan 0 sort 0} +do_test where7-2.801.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?efgh*' AND f GLOB 'defg*') + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR f='jklmnopqr' + } +} {3 9 29 35 55 61 81 82 87 89 scan 0 sort 0} +do_test where7-2.802.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=946 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR a=47 + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR b=80 + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR (g='tsrqpon' AND f GLOB 'xyzab*') + } +} {8 23 42 47 60 62 78 86 93 scan 0 sort 0} +do_test where7-2.802.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=946 + OR (g='ihgfedc' AND f GLOB 'abcde*') + OR a=47 + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR b=80 + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR (g='tsrqpon' AND f GLOB 'xyzab*') + } +} {8 23 42 47 60 62 78 86 93 scan 0 sort 0} +do_test where7-2.803.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=48 + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR b=1015 + OR a=57 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR ((a BETWEEN 47 AND 49) AND a!=48) + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR b=165 + } +} {4 9 15 35 47 48 49 50 55 57 61 87 98 100 scan 0 sort 0} +do_test where7-2.803.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=48 + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR b=1015 + OR a=57 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR ((a BETWEEN 47 AND 49) AND a!=48) + OR ((a BETWEEN 98 AND 100) AND a!=99) + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR (d>=4.0 AND d<5.0 AND d NOT NULL) + OR b=165 + } +} {4 9 15 35 47 48 49 50 55 57 61 87 98 100 scan 0 sort 0} +do_test where7-2.804.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 97 AND 99) AND a!=98) + OR a=73 + OR b=1048 + OR c>=34035 + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR a=72 + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=638 + } +} {58 72 73 80 91 93 97 99 scan 0 sort 0} +do_test where7-2.804.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 97 AND 99) AND a!=98) + OR a=73 + OR b=1048 + OR c>=34035 + OR (g='ihgfedc' AND f GLOB 'cdefg*') + OR a=72 + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=638 + } +} {58 72 73 80 91 93 97 99 scan 0 sort 0} +do_test where7-2.805.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 28 AND 30) AND a!=29) + OR a=39 + OR b=165 + } +} {15 28 30 39 scan 0 sort 0} +do_test where7-2.805.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 28 AND 30) AND a!=29) + OR a=39 + OR b=165 + } +} {15 28 30 39 scan 0 sort 0} +do_test where7-2.806.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=50 + OR ((a BETWEEN 61 AND 63) AND a!=62) + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR a=32 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR a=14 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR b=946 + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR b=124 + } +} {14 17 32 43 45 50 53 55 61 63 69 86 93 95 97 scan 0 sort 0} +do_test where7-2.806.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=50 + OR ((a BETWEEN 61 AND 63) AND a!=62) + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR a=32 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR a=14 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR b=946 + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR b=124 + } +} {14 17 32 43 45 50 53 55 61 63 69 86 93 95 97 scan 0 sort 0} +do_test where7-2.807.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 88 AND 90) AND a!=89) + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'klmno*') + } +} {52 66 88 90 scan 0 sort 0} +do_test where7-2.807.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 88 AND 90) AND a!=89) + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'klmno*') + } +} {52 66 88 90 scan 0 sort 0} +do_test where7-2.808.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=6 + OR f='tuvwxyzab' + OR (g='mlkjihg' AND f GLOB 'hijkl*') + OR b=286 + OR b=781 + } +} {6 19 26 45 59 71 97 scan 0 sort 0} +do_test where7-2.808.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=6 + OR f='tuvwxyzab' + OR (g='mlkjihg' AND f GLOB 'hijkl*') + OR b=286 + OR b=781 + } +} {6 19 26 45 59 71 97 scan 0 sort 0} +do_test where7-2.809.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'zabcd*') + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR f='vwxyzabcd' + OR b=275 + } +} {9 11 21 25 35 37 43 47 61 63 73 77 79 81 87 89 99 100 scan 0 sort 0} +do_test where7-2.809.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'zabcd*') + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR f='vwxyzabcd' + OR b=275 + } +} {9 11 21 25 35 37 43 47 61 63 73 77 79 81 87 89 99 100 scan 0 sort 0} +do_test where7-2.810.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=30.0 AND d<31.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR a=59 + } +} {4 30 59 64 89 91 scan 0 sort 0} +do_test where7-2.810.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=30.0 AND d<31.0 AND d NOT NULL) + OR (g='xwvutsr' AND f GLOB 'efghi*') + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'nopqr*') + OR a=59 + } +} {4 30 59 64 89 91 scan 0 sort 0} +do_test where7-2.811.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR b=663 + OR f='ghijklmno' + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR f='ghijklmno' + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR b=1081 + } +} {6 8 10 14 16 19 22 32 48 58 64 71 74 84 99 100 scan 0 sort 0} +do_test where7-2.811.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR b=663 + OR f='ghijklmno' + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR f='ghijklmno' + OR (d>=64.0 AND d<65.0 AND d NOT NULL) + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + OR b=1081 + } +} {6 8 10 14 16 19 22 32 48 58 64 71 74 84 99 100 scan 0 sort 0} +do_test where7-2.812.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 30 AND 32) AND a!=31) + OR a=96 + OR b=355 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR b=597 + OR ((a BETWEEN 92 AND 94) AND a!=93) + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR (f GLOB '?lmno*' AND f GLOB 'klmn*') + OR b=168 + OR (g='vutsrqp' AND f GLOB 'pqrst*') + } +} {10 15 30 32 36 62 81 88 92 94 96 scan 0 sort 0} +do_test where7-2.812.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 30 AND 32) AND a!=31) + OR a=96 + OR b=355 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR b=597 + OR ((a BETWEEN 92 AND 94) AND a!=93) + OR (d>=88.0 AND d<89.0 AND d NOT NULL) + OR (f GLOB '?lmno*' AND f GLOB 'klmn*') + OR b=168 + OR (g='vutsrqp' AND f GLOB 'pqrst*') + } +} {10 15 30 32 36 62 81 88 92 94 96 scan 0 sort 0} +do_test where7-2.813.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=47.0 AND d<48.0 AND d NOT NULL) + OR b=957 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR a=40 + } +} {9 40 47 58 60 87 89 scan 0 sort 0} +do_test where7-2.813.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=47.0 AND d<48.0 AND d NOT NULL) + OR b=957 + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR a=40 + } +} {9 40 47 58 60 87 89 scan 0 sort 0} +do_test where7-2.814.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 12 AND 14) AND a!=13) + OR a=36 + OR a=75 + OR b=179 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + OR b=850 + OR a=62 + } +} {12 14 18 36 43 62 65 75 scan 0 sort 0} +do_test where7-2.814.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 12 AND 14) AND a!=13) + OR a=36 + OR a=75 + OR b=179 + OR (d>=43.0 AND d<44.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'stuvw*') + OR (d>=65.0 AND d<66.0 AND d NOT NULL) + OR b=850 + OR a=62 + } +} {12 14 18 36 43 62 65 75 scan 0 sort 0} +do_test where7-2.815.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 21 AND 23) AND a!=22) + OR a=79 + OR a=66 + OR b=487 + OR a=1 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR c=5005 + OR a=47 + OR c=5005 + OR b=319 + OR b=1037 + } +} {1 13 14 15 21 23 29 47 54 66 79 scan 0 sort 0} +do_test where7-2.815.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 21 AND 23) AND a!=22) + OR a=79 + OR a=66 + OR b=487 + OR a=1 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR c=5005 + OR a=47 + OR c=5005 + OR b=319 + OR b=1037 + } +} {1 13 14 15 21 23 29 47 54 66 79 scan 0 sort 0} +do_test where7-2.816.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=176 + OR b=297 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR f='ijklmnopq' + } +} {8 16 25 27 34 60 86 scan 0 sort 0} +do_test where7-2.816.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=176 + OR b=297 + OR (g='tsrqpon' AND f GLOB 'zabcd*') + OR f='ijklmnopq' + } +} {8 16 25 27 34 60 86 scan 0 sort 0} +do_test where7-2.817.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=10.0 AND d<11.0 AND d NOT NULL) + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR b=319 + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR a=21 + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + } +} {9 10 11 21 29 31 33 72 90 92 scan 0 sort 0} +do_test where7-2.817.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=10.0 AND d<11.0 AND d NOT NULL) + OR ((a BETWEEN 90 AND 92) AND a!=91) + OR b=319 + OR ((a BETWEEN 31 AND 33) AND a!=32) + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR a=21 + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + } +} {9 10 11 21 29 31 33 72 90 92 scan 0 sort 0} +do_test where7-2.818.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=22.0 AND d<23.0 AND d NOT NULL) + OR b=396 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR b=1012 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR b=784 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR b=979 + OR c<=10 + OR b=913 + OR b=66 + } +} {6 9 22 35 36 60 61 72 83 87 89 92 scan 0 sort 0} +do_test where7-2.818.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=22.0 AND d<23.0 AND d NOT NULL) + OR b=396 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR b=1012 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR b=784 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + OR b=979 + OR c<=10 + OR b=913 + OR b=66 + } +} {6 9 22 35 36 60 61 72 83 87 89 92 scan 0 sort 0} +do_test where7-2.819.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=3 + OR b=803 + } +} {3 73 scan 0 sort 0} +do_test where7-2.819.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=3 + OR b=803 + } +} {3 73 scan 0 sort 0} +do_test where7-2.820.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 79 AND 81) AND a!=80) + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + } +} {16 19 23 25 42 45 68 71 79 81 94 97 scan 0 sort 0} +do_test where7-2.820.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 79 AND 81) AND a!=80) + OR (f GLOB '?rstu*' AND f GLOB 'qrst*') + OR ((a BETWEEN 23 AND 25) AND a!=24) + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + } +} {16 19 23 25 42 45 68 71 79 81 94 97 scan 0 sort 0} +do_test where7-2.821.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=1001 + OR a=16 + OR b=132 + OR b=1012 + OR f='xyzabcdef' + OR b=682 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + } +} {1 2 3 12 16 23 49 52 62 75 92 scan 0 sort 0} +do_test where7-2.821.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=1001 + OR a=16 + OR b=132 + OR b=1012 + OR f='xyzabcdef' + OR b=682 + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + } +} {1 2 3 12 16 23 49 52 62 75 92 scan 0 sort 0} +do_test where7-2.822.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=96 + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + } +} {19 96 scan 0 sort 0} +do_test where7-2.822.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=96 + OR (d>=19.0 AND d<20.0 AND d NOT NULL) + } +} {19 96 scan 0 sort 0} +do_test where7-2.823.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=2 + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + OR a=23 + OR b=1092 + OR c=19019 + OR b=245 + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR b=572 + OR ((a BETWEEN 22 AND 24) AND a!=23) + } +} {2 11 12 22 23 24 38 52 55 56 57 64 68 70 90 97 99 scan 0 sort 0} +do_test where7-2.823.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=2 + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + OR a=23 + OR b=1092 + OR c=19019 + OR b=245 + OR ((a BETWEEN 97 AND 99) AND a!=98) + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR b=572 + OR ((a BETWEEN 22 AND 24) AND a!=23) + } +} {2 11 12 22 23 24 38 52 55 56 57 64 68 70 90 97 99 scan 0 sort 0} +do_test where7-2.824.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=993 + OR c=17017 + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR b=333 + } +} {16 29 37 49 50 51 53 85 scan 0 sort 0} +do_test where7-2.824.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=16.0 AND d<17.0 AND d NOT NULL) + OR b=993 + OR c=17017 + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR b=333 + } +} {16 29 37 49 50 51 53 85 scan 0 sort 0} +do_test where7-2.825.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=330 + OR a=73 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=828 + OR b=363 + OR (g='rqponml' AND f GLOB 'lmnop*') + } +} {30 33 37 40 61 73 scan 0 sort 0} +do_test where7-2.825.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=330 + OR a=73 + OR (d>=61.0 AND d<62.0 AND d NOT NULL) + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=828 + OR b=363 + OR (g='rqponml' AND f GLOB 'lmnop*') + } +} {30 33 37 40 61 73 scan 0 sort 0} +do_test where7-2.826.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='gfedcba' AND f GLOB 'lmnop*') + OR a=41 + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR b=825 + } +} {29 41 75 89 scan 0 sort 0} +do_test where7-2.826.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='gfedcba' AND f GLOB 'lmnop*') + OR a=41 + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR b=825 + } +} {29 41 75 89 scan 0 sort 0} +do_test where7-2.827.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 46 AND 48) AND a!=47) + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=905 + OR b=176 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR b=561 + OR c=8008 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR b=935 + OR c=1001 + } +} {1 2 3 10 16 22 23 24 46 48 51 84 85 89 91 scan 0 sort 0} +do_test where7-2.827.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 46 AND 48) AND a!=47) + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + OR b=905 + OR b=176 + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR b=561 + OR c=8008 + OR (g='hgfedcb' AND f GLOB 'ghijk*') + OR b=935 + OR c=1001 + } +} {1 2 3 10 16 22 23 24 46 48 51 84 85 89 91 scan 0 sort 0} +do_test where7-2.828.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 75 AND 77) AND a!=76) + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {72 75 77 scan 0 sort 0} +do_test where7-2.828.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 75 AND 77) AND a!=76) + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {72 75 77 scan 0 sort 0} +do_test where7-2.829.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 5 AND 7) AND a!=6) + OR a=28 + } +} {5 7 28 scan 0 sort 0} +do_test where7-2.829.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 5 AND 7) AND a!=6) + OR a=28 + } +} {5 7 28 scan 0 sort 0} +do_test where7-2.830.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=781 + OR b=410 + } +} {71 scan 0 sort 0} +do_test where7-2.830.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=781 + OR b=410 + } +} {71 scan 0 sort 0} +do_test where7-2.831.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 18 AND 20) AND a!=19) + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR f='zabcdefgh' + OR b=861 + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR a=28 + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=311 + } +} {6 15 18 20 25 28 32 40 42 51 56 58 63 72 77 84 scan 0 sort 0} +do_test where7-2.831.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 18 AND 20) AND a!=19) + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR f='zabcdefgh' + OR b=861 + OR (g='vutsrqp' AND f GLOB 'pqrst*') + OR a=28 + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=311 + } +} {6 15 18 20 25 28 32 40 42 51 56 58 63 72 77 84 scan 0 sort 0} +do_test where7-2.832.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=575 + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR b=418 + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR b=792 + OR b=861 + OR b=220 + OR ((a BETWEEN 89 AND 91) AND a!=90) + } +} {12 15 20 38 41 64 67 72 73 89 90 91 93 scan 0 sort 0} +do_test where7-2.832.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=575 + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR b=418 + OR (f GLOB '?qrst*' AND f GLOB 'pqrs*') + OR b=792 + OR b=861 + OR b=220 + OR ((a BETWEEN 89 AND 91) AND a!=90) + } +} {12 15 20 38 41 64 67 72 73 89 90 91 93 scan 0 sort 0} +do_test where7-2.833.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=517 + OR b=913 + OR b=253 + OR b=198 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR a=17 + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + } +} {17 18 23 27 47 83 85 scan 0 sort 0} +do_test where7-2.833.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=517 + OR b=913 + OR b=253 + OR b=198 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR a=17 + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + } +} {17 18 23 27 47 83 85 scan 0 sort 0} +do_test where7-2.834.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'qrstu*') + OR b=693 + OR a=73 + OR b=627 + OR c=5005 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=267 + OR b=872 + OR a=27 + OR (g='gfedcba' AND f GLOB 'klmno*') + } +} {13 14 15 27 28 42 57 62 63 73 88 scan 0 sort 0} +do_test where7-2.834.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'qrstu*') + OR b=693 + OR a=73 + OR b=627 + OR c=5005 + OR (d>=62.0 AND d<63.0 AND d NOT NULL) + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR b=267 + OR b=872 + OR a=27 + OR (g='gfedcba' AND f GLOB 'klmno*') + } +} {13 14 15 27 28 42 57 62 63 73 88 scan 0 sort 0} +do_test where7-2.835.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=10 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR b=1059 + OR a=70 + OR a=93 + } +} {10 13 15 70 93 95 97 scan 0 sort 0} +do_test where7-2.835.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=10 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR b=1059 + OR a=70 + OR a=93 + } +} {10 13 15 70 93 95 97 scan 0 sort 0} +do_test where7-2.836.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=30 + OR a=32 + OR b=1037 + OR b=198 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR a=25 + } +} {13 18 25 30 32 scan 0 sort 0} +do_test where7-2.836.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=30 + OR a=32 + OR b=1037 + OR b=198 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR a=25 + } +} {13 18 25 30 32 scan 0 sort 0} +do_test where7-2.837.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ponmlkj' AND f GLOB 'uvwxy*') + OR b=66 + OR b=322 + OR b=465 + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR (g='lkjihgf' AND f GLOB 'mnopq*') + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR b=454 + } +} {6 7 38 46 64 77 79 89 scan 0 sort 0} +do_test where7-2.837.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ponmlkj' AND f GLOB 'uvwxy*') + OR b=66 + OR b=322 + OR b=465 + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR (d>=7.0 AND d<8.0 AND d NOT NULL) + OR ((a BETWEEN 77 AND 79) AND a!=78) + OR (g='lkjihgf' AND f GLOB 'mnopq*') + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR b=454 + } +} {6 7 38 46 64 77 79 89 scan 0 sort 0} +do_test where7-2.838.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=924 + OR ((a BETWEEN 35 AND 37) AND a!=36) + OR c=15015 + OR (d>=84.0 AND d<85.0 AND d NOT NULL) + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR (g='onmlkji' AND f GLOB 'abcde*') + OR b=803 + } +} {3 5 35 37 43 44 45 52 73 84 scan 0 sort 0} +do_test where7-2.838.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=924 + OR ((a BETWEEN 35 AND 37) AND a!=36) + OR c=15015 + OR (d>=84.0 AND d<85.0 AND d NOT NULL) + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR (g='onmlkji' AND f GLOB 'abcde*') + OR b=803 + } +} {3 5 35 37 43 44 45 52 73 84 scan 0 sort 0} +do_test where7-2.839.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1100 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR a=75 + OR a=45 + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR a=27 + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR b=850 + OR ((a BETWEEN 55 AND 57) AND a!=56) + } +} {12 27 45 55 57 68 70 72 74 75 77 90 100 scan 0 sort 0} +do_test where7-2.839.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1100 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR ((a BETWEEN 72 AND 74) AND a!=73) + OR ((a BETWEEN 68 AND 70) AND a!=69) + OR a=75 + OR a=45 + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR a=27 + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR b=850 + OR ((a BETWEEN 55 AND 57) AND a!=56) + } +} {12 27 45 55 57 68 70 72 74 75 77 90 100 scan 0 sort 0} +do_test where7-2.840.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=751 + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR a=89 + OR ((a BETWEEN 36 AND 38) AND a!=37) + } +} {36 38 56 71 89 96 98 scan 0 sort 0} +do_test where7-2.840.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=751 + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR (d>=71.0 AND d<72.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR (d>=56.0 AND d<57.0 AND d NOT NULL) + OR a=89 + OR ((a BETWEEN 36 AND 38) AND a!=37) + } +} {36 38 56 71 89 96 98 scan 0 sort 0} +do_test where7-2.841.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='wvutsrq' AND f GLOB 'jklmn*') + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR a=1 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + } +} {1 9 19 scan 0 sort 0} +do_test where7-2.841.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='wvutsrq' AND f GLOB 'jklmn*') + OR (g='yxwvuts' AND f GLOB 'bcdef*') + OR a=1 + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + } +} {1 9 19 scan 0 sort 0} +do_test where7-2.842.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=927 + OR c=15015 + OR f='klmnopqrs' + OR c=8008 + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR b=960 + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR b=443 + OR (g='rqponml' AND f GLOB 'ijklm*') + } +} {10 22 23 24 34 36 41 43 44 45 62 76 88 scan 0 sort 0} +do_test where7-2.842.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=927 + OR c=15015 + OR f='klmnopqrs' + OR c=8008 + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR b=960 + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR b=443 + OR (g='rqponml' AND f GLOB 'ijklm*') + } +} {10 22 23 24 34 36 41 43 44 45 62 76 88 scan 0 sort 0} +do_test where7-2.843.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=212 + OR f='cdefghijk' + } +} {2 28 37 54 80 scan 0 sort 0} +do_test where7-2.843.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=37.0 AND d<38.0 AND d NOT NULL) + OR b=212 + OR f='cdefghijk' + } +} {2 28 37 54 80 scan 0 sort 0} +do_test where7-2.844.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=685 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR b=520 + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR a=53 + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=938 + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR c=25025 + } +} {43 53 63 73 74 75 76 91 93 scan 0 sort 0} +do_test where7-2.844.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=685 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR b=520 + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR a=53 + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=938 + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR c=25025 + } +} {43 53 63 73 74 75 76 91 93 scan 0 sort 0} +do_test where7-2.845.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=583 + OR b=894 + OR c=26026 + OR (d>=84.0 AND d<85.0 AND d NOT NULL) + } +} {53 76 77 78 84 scan 0 sort 0} +do_test where7-2.845.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=583 + OR b=894 + OR c=26026 + OR (d>=84.0 AND d<85.0 AND d NOT NULL) + } +} {53 76 77 78 84 scan 0 sort 0} +do_test where7-2.846.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='abcdefghi' + OR (g='edcbazy' AND f GLOB 'wxyza*') + } +} {26 52 78 100 scan 0 sort 0} +do_test where7-2.846.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='abcdefghi' + OR (g='edcbazy' AND f GLOB 'wxyza*') + } +} {26 52 78 100 scan 0 sort 0} +do_test where7-2.847.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1103 + OR b=638 + OR b=792 + OR b=1034 + OR b=308 + OR f='nopqrstuv' + OR b=264 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + } +} {13 24 28 33 35 39 58 65 72 91 94 scan 0 sort 0} +do_test where7-2.847.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1103 + OR b=638 + OR b=792 + OR b=1034 + OR b=308 + OR f='nopqrstuv' + OR b=264 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR (d>=58.0 AND d<59.0 AND d NOT NULL) + } +} {13 24 28 33 35 39 58 65 72 91 94 scan 0 sort 0} +do_test where7-2.848.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='defghijkl' + OR b=814 + OR f='yzabcdefg' + } +} {3 24 29 50 55 74 76 81 scan 0 sort 0} +do_test where7-2.848.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='defghijkl' + OR b=814 + OR f='yzabcdefg' + } +} {3 24 29 50 55 74 76 81 scan 0 sort 0} +do_test where7-2.849.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=209 + OR b=806 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'rstuv*') + } +} {8 17 19 scan 0 sort 0} +do_test where7-2.849.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=209 + OR b=806 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'rstuv*') + } +} {8 17 19 scan 0 sort 0} +do_test where7-2.850.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='opqrstuvw' + OR b=69 + OR b=366 + } +} {14 40 66 92 scan 0 sort 0} +do_test where7-2.850.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='opqrstuvw' + OR b=69 + OR b=366 + } +} {14 40 66 92 scan 0 sort 0} +do_test where7-2.851.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=4.0 AND d<5.0 AND d NOT NULL) + OR a=45 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR a=69 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {4 45 69 71 72 scan 0 sort 0} +do_test where7-2.851.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=4.0 AND d<5.0 AND d NOT NULL) + OR a=45 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR a=69 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {4 45 69 71 72 scan 0 sort 0} +do_test where7-2.852.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=9009 + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'pqrst*') + } +} {9 10 25 26 27 67 85 scan 0 sort 0} +do_test where7-2.852.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=9009 + OR (d>=85.0 AND d<86.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR (d>=9.0 AND d<10.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'pqrst*') + } +} {9 10 25 26 27 67 85 scan 0 sort 0} +do_test where7-2.853.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=98 + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR a=47 + OR c=24024 + OR a=27 + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + } +} {20 27 45 47 63 70 71 72 98 100 scan 0 sort 0} +do_test where7-2.853.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=98 + OR (d>=100.0 AND d<101.0 AND d NOT NULL) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + OR a=47 + OR c=24024 + OR a=27 + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + } +} {20 27 45 47 63 70 71 72 98 100 scan 0 sort 0} +do_test where7-2.854.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='utsrqpo' AND f GLOB 'wxyza*') + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR a=19 + } +} {19 22 44 scan 0 sort 0} +do_test where7-2.854.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='utsrqpo' AND f GLOB 'wxyza*') + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR a=19 + } +} {19 22 44 scan 0 sort 0} +do_test where7-2.855.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=12012 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR (g='edcbazy' AND f GLOB 'uvwxy*') + } +} {16 18 34 35 36 80 98 scan 0 sort 0} +do_test where7-2.855.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=12012 + OR (d>=80.0 AND d<81.0 AND d NOT NULL) + OR ((a BETWEEN 16 AND 18) AND a!=17) + OR (g='edcbazy' AND f GLOB 'uvwxy*') + } +} {16 18 34 35 36 80 98 scan 0 sort 0} +do_test where7-2.856.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 38 AND 40) AND a!=39) + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR b=429 + OR f='jklmnopqr' + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR ((a BETWEEN 77 AND 79) AND a!=78) + } +} {9 12 35 38 39 40 48 61 64 77 79 87 90 scan 0 sort 0} +do_test where7-2.856.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 38 AND 40) AND a!=39) + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR b=429 + OR f='jklmnopqr' + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR ((a BETWEEN 77 AND 79) AND a!=78) + } +} {9 12 35 38 39 40 48 61 64 77 79 87 90 scan 0 sort 0} +do_test where7-2.857.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='lkjihgf' AND f GLOB 'mnopq*') + OR b=190 + } +} {64 scan 0 sort 0} +do_test where7-2.857.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='lkjihgf' AND f GLOB 'mnopq*') + OR b=190 + } +} {64 scan 0 sort 0} +do_test where7-2.858.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'yzabc*') + OR b=674 + OR b=289 + } +} {76 scan 0 sort 0} +do_test where7-2.858.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'yzabc*') + OR b=674 + OR b=289 + } +} {76 scan 0 sort 0} +do_test where7-2.859.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=17 + OR b=539 + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + } +} {17 21 47 49 scan 0 sort 0} +do_test where7-2.859.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=17 + OR b=539 + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR (g='utsrqpo' AND f GLOB 'vwxyz*') + } +} {17 21 47 49 scan 0 sort 0} +do_test where7-2.860.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=924 + OR c=27027 + OR ((a BETWEEN 65 AND 67) AND a!=66) + } +} {65 67 79 80 81 84 scan 0 sort 0} +do_test where7-2.860.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=924 + OR c=27027 + OR ((a BETWEEN 65 AND 67) AND a!=66) + } +} {65 67 79 80 81 84 scan 0 sort 0} +do_test where7-2.861.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=564 + OR f='mnopqrstu' + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR b=1103 + } +} {12 28 30 38 64 90 scan 0 sort 0} +do_test where7-2.861.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=564 + OR f='mnopqrstu' + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR b=1103 + } +} {12 28 30 38 64 90 scan 0 sort 0} +do_test where7-2.862.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=231 + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR a=38 + OR a=4 + OR b=784 + } +} {4 21 24 38 scan 0 sort 0} +do_test where7-2.862.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=231 + OR (d>=24.0 AND d<25.0 AND d NOT NULL) + OR a=38 + OR a=4 + OR b=784 + } +} {4 21 24 38 scan 0 sort 0} +do_test where7-2.863.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='ghijklmno' + OR a=26 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=81 + OR (d>=3.0 AND d<4.0 AND d NOT NULL) + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR b=275 + OR (g='hgfedcb' AND f GLOB 'jklmn*') + OR b=311 + OR b=894 + OR b=872 + } +} {3 6 25 26 28 30 32 58 68 81 84 87 scan 0 sort 0} +do_test where7-2.863.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='ghijklmno' + OR a=26 + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR a=81 + OR (d>=3.0 AND d<4.0 AND d NOT NULL) + OR ((a BETWEEN 28 AND 30) AND a!=29) + OR b=275 + OR (g='hgfedcb' AND f GLOB 'jklmn*') + OR b=311 + OR b=894 + OR b=872 + } +} {3 6 25 26 28 30 32 58 68 81 84 87 scan 0 sort 0} +do_test where7-2.864.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=91 + OR b=619 + } +} {91 scan 0 sort 0} +do_test where7-2.864.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=91 + OR b=619 + } +} {91 scan 0 sort 0} +do_test where7-2.865.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=4.0 AND d<5.0 AND d NOT NULL) + OR a=85 + OR f IS NULL + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=154 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + } +} {4 14 25 40 42 49 51 66 68 85 87 89 scan 0 sort 0} +do_test where7-2.865.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=4.0 AND d<5.0 AND d NOT NULL) + OR a=85 + OR f IS NULL + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=154 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + } +} {4 14 25 40 42 49 51 66 68 85 87 89 scan 0 sort 0} +do_test where7-2.866.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=44 + OR b=55 + OR a=30 + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR 1000000=75.0 AND d<76.0 AND d NOT NULL) + OR (g='rqponml' AND f GLOB 'hijkl*') + } +} {5 19 24 30 33 44 45 71 75 97 99 scan 0 sort 0} +do_test where7-2.866.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=44 + OR b=55 + OR a=30 + OR (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR 1000000=75.0 AND d<76.0 AND d NOT NULL) + OR (g='rqponml' AND f GLOB 'hijkl*') + } +} {5 19 24 30 33 44 45 71 75 97 99 scan 0 sort 0} +do_test where7-2.867.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=16.0 AND d<17.0 AND d NOT NULL) + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR b=36 + OR ((a BETWEEN 33 AND 35) AND a!=34) + } +} {16 33 35 80 82 scan 0 sort 0} +do_test where7-2.867.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=16.0 AND d<17.0 AND d NOT NULL) + OR ((a BETWEEN 80 AND 82) AND a!=81) + OR b=36 + OR ((a BETWEEN 33 AND 35) AND a!=34) + } +} {16 33 35 80 82 scan 0 sort 0} +do_test where7-2.868.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + OR c=26026 + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR a=56 + OR b=506 + OR b=781 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + } +} {28 35 37 39 46 56 71 76 77 78 97 scan 0 sort 0} +do_test where7-2.868.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + OR c=26026 + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR a=56 + OR b=506 + OR b=781 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + } +} {28 35 37 39 46 56 71 76 77 78 97 scan 0 sort 0} +do_test where7-2.869.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='edcbazy' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR f='xyzabcdef' + OR b=517 + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR (g='kjihgfe' AND f GLOB 'qrstu*') + } +} {23 25 27 39 47 49 68 75 76 89 91 98 scan 0 sort 0} +do_test where7-2.869.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='edcbazy' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 25 AND 27) AND a!=26) + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR ((a BETWEEN 89 AND 91) AND a!=90) + OR f='xyzabcdef' + OR b=517 + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR (g='kjihgfe' AND f GLOB 'qrstu*') + } +} {23 25 27 39 47 49 68 75 76 89 91 98 scan 0 sort 0} +do_test where7-2.870.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=54 + OR a=59 + } +} {54 59 scan 0 sort 0} +do_test where7-2.870.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=54 + OR a=59 + } +} {54 59 scan 0 sort 0} +do_test where7-2.871.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='tsrqpon' AND f GLOB 'yzabc*') + OR b=762 + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR a=25 + OR ((a BETWEEN 65 AND 67) AND a!=66) + } +} {24 25 48 65 67 scan 0 sort 0} +do_test where7-2.871.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='tsrqpon' AND f GLOB 'yzabc*') + OR b=762 + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR a=25 + OR ((a BETWEEN 65 AND 67) AND a!=66) + } +} {24 25 48 65 67 scan 0 sort 0} +do_test where7-2.872.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=59.0 AND d<60.0 AND d NOT NULL) + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR b=839 + OR f='defghijkl' + OR (d>=95.0 AND d<96.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR b=498 + } +} {3 14 16 29 52 55 59 60 81 85 95 scan 0 sort 0} +do_test where7-2.872.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=59.0 AND d<60.0 AND d NOT NULL) + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR b=839 + OR f='defghijkl' + OR (d>=95.0 AND d<96.0 AND d NOT NULL) + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR (d>=52.0 AND d<53.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR b=498 + } +} {3 14 16 29 52 55 59 60 81 85 95 scan 0 sort 0} +do_test where7-2.873.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=256 + OR c=19019 + OR a=54 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=498 + OR b=77 + } +} {7 46 54 55 56 57 scan 0 sort 0} +do_test where7-2.873.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=256 + OR c=19019 + OR a=54 + OR (d>=46.0 AND d<47.0 AND d NOT NULL) + OR b=498 + OR b=77 + } +} {7 46 54 55 56 57 scan 0 sort 0} +do_test where7-2.874.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=256 + OR b=586 + OR a=74 + OR b=113 + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR b=495 + } +} {45 61 74 99 scan 0 sort 0} +do_test where7-2.874.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='mlkjihg' AND f GLOB 'jklmn*') + OR b=256 + OR b=586 + OR a=74 + OR b=113 + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR b=495 + } +} {45 61 74 99 scan 0 sort 0} +do_test where7-2.875.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=12 + OR a=50 + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + OR ((a BETWEEN 66 AND 68) AND a!=67) + } +} {12 33 50 66 68 scan 0 sort 0} +do_test where7-2.875.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=12 + OR a=50 + OR (d>=33.0 AND d<34.0 AND d NOT NULL) + OR ((a BETWEEN 66 AND 68) AND a!=67) + } +} {12 33 50 66 68 scan 0 sort 0} +do_test where7-2.876.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=308 + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR a=83 + OR c=23023 + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR a=58 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR (g='srqponm' AND f GLOB 'efghi*') + OR c=4004 + } +} {10 11 12 17 19 28 30 53 57 58 65 67 68 69 73 83 scan 0 sort 0} +do_test where7-2.876.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=308 + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR a=83 + OR c=23023 + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR (g='lkjihgf' AND f GLOB 'nopqr*') + OR a=58 + OR ((a BETWEEN 17 AND 19) AND a!=18) + OR (g='srqponm' AND f GLOB 'efghi*') + OR c=4004 + } +} {10 11 12 17 19 28 30 53 57 58 65 67 68 69 73 83 scan 0 sort 0} +do_test where7-2.877.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=476 + OR a=26 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=762 + OR b=157 + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'cdefg*') + } +} {17 26 54 87 scan 0 sort 0} +do_test where7-2.877.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=476 + OR a=26 + OR (d>=87.0 AND d<88.0 AND d NOT NULL) + OR b=762 + OR b=157 + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (g='nmlkjih' AND f GLOB 'cdefg*') + } +} {17 26 54 87 scan 0 sort 0} +do_test where7-2.878.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=77.0 AND d<78.0 AND d NOT NULL) + OR a=1 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR b=278 + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR f='qrstuvwxy' + OR (g='onmlkji' AND f GLOB 'abcde*') + OR ((a BETWEEN 82 AND 84) AND a!=83) + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + } +} {1 3 16 42 52 68 72 74 77 82 84 93 94 95 98 scan 0 sort 0} +do_test where7-2.878.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=77.0 AND d<78.0 AND d NOT NULL) + OR a=1 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR b=278 + OR (g='xwvutsr' AND f GLOB 'defgh*') + OR f='qrstuvwxy' + OR (g='onmlkji' AND f GLOB 'abcde*') + OR ((a BETWEEN 82 AND 84) AND a!=83) + OR (g='edcbazy' AND f GLOB 'uvwxy*') + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + } +} {1 3 16 42 52 68 72 74 77 82 84 93 94 95 98 scan 0 sort 0} +do_test where7-2.879.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=124 + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=759 + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR ((a BETWEEN 45 AND 47) AND a!=46) + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {12 38 41 43 45 47 64 69 72 90 92 96 scan 0 sort 0} +do_test where7-2.879.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=124 + OR (d>=92.0 AND d<93.0 AND d NOT NULL) + OR ((a BETWEEN 41 AND 43) AND a!=42) + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=759 + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR ((a BETWEEN 45 AND 47) AND a!=46) + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + } +} {12 38 41 43 45 47 64 69 72 90 92 96 scan 0 sort 0} +do_test where7-2.880.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=872 + OR b=267 + OR b=814 + OR b=99 + OR c<=10 + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR b=44 + OR f='zabcdefgh' + OR b=979 + OR (g='rqponml' AND f GLOB 'hijkl*') + } +} {4 8 9 10 25 33 51 74 77 89 scan 0 sort 0} +do_test where7-2.880.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=872 + OR b=267 + OR b=814 + OR b=99 + OR c<=10 + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR b=44 + OR f='zabcdefgh' + OR b=979 + OR (g='rqponml' AND f GLOB 'hijkl*') + } +} {4 8 9 10 25 33 51 74 77 89 scan 0 sort 0} +do_test where7-2.881.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=26.0 AND d<27.0 AND d NOT NULL) + OR f='xyzabcdef' + } +} {23 26 49 75 scan 0 sort 0} +do_test where7-2.881.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=26.0 AND d<27.0 AND d NOT NULL) + OR f='xyzabcdef' + } +} {23 26 49 75 scan 0 sort 0} +do_test where7-2.882.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=487 + OR b=355 + OR c=9009 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=113 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR a=90 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'jklmn*') + OR f='nopqrstuv' + } +} {8 13 24 25 26 27 32 34 39 65 66 87 90 91 scan 0 sort 0} +do_test where7-2.882.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=487 + OR b=355 + OR c=9009 + OR (d>=8.0 AND d<9.0 AND d NOT NULL) + OR ((a BETWEEN 32 AND 34) AND a!=33) + OR b=113 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR a=90 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR (g='hgfedcb' AND f GLOB 'jklmn*') + OR f='nopqrstuv' + } +} {8 13 24 25 26 27 32 34 39 65 66 87 90 91 scan 0 sort 0} +do_test where7-2.883.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=34.0 AND d<35.0 AND d NOT NULL) + OR b=275 + } +} {25 34 scan 0 sort 0} +do_test where7-2.883.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=34.0 AND d<35.0 AND d NOT NULL) + OR b=275 + } +} {25 34 scan 0 sort 0} +do_test where7-2.884.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=355 + OR a=44 + OR b=374 + OR c=25025 + OR b=198 + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR d<0.0 + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR c=9009 + } +} {4 6 18 25 26 27 34 41 44 69 71 73 74 75 scan 0 sort 0} +do_test where7-2.884.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=355 + OR a=44 + OR b=374 + OR c=25025 + OR b=198 + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR d<0.0 + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR c=9009 + } +} {4 6 18 25 26 27 34 41 44 69 71 73 74 75 scan 0 sort 0} +do_test where7-2.885.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR b=814 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + } +} {19 45 54 71 74 97 scan 0 sort 0} +do_test where7-2.885.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?uvwx*' AND f GLOB 'tuvw*') + OR b=814 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + } +} {19 45 54 71 74 97 scan 0 sort 0} +do_test where7-2.886.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='lkjihgf' AND f GLOB 'mnopq*') + OR b=333 + OR b=275 + } +} {25 64 scan 0 sort 0} +do_test where7-2.886.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='lkjihgf' AND f GLOB 'mnopq*') + OR b=333 + OR b=275 + } +} {25 64 scan 0 sort 0} +do_test where7-2.887.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='ihgfedc' AND f GLOB 'efghi*') + OR ((a BETWEEN 33 AND 35) AND a!=34) + } +} {33 35 82 scan 0 sort 0} +do_test where7-2.887.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='ihgfedc' AND f GLOB 'efghi*') + OR ((a BETWEEN 33 AND 35) AND a!=34) + } +} {33 35 82 scan 0 sort 0} +do_test where7-2.888.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 11 AND 13) AND a!=12) + OR b=253 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR b=286 + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + } +} {10 11 13 14 23 26 40 66 92 scan 0 sort 0} +do_test where7-2.888.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 11 AND 13) AND a!=12) + OR b=253 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR b=286 + OR (d>=10.0 AND d<11.0 AND d NOT NULL) + } +} {10 11 13 14 23 26 40 66 92 scan 0 sort 0} +do_test where7-2.889.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=15.0 AND d<16.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR ((a BETWEEN 26 AND 28) AND a!=27) + OR b=421 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR f='ijklmnopq' + OR b=891 + OR b=1056 + } +} {5 8 15 26 28 34 60 81 86 90 96 scan 0 sort 0} +do_test where7-2.889.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=15.0 AND d<16.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR ((a BETWEEN 26 AND 28) AND a!=27) + OR b=421 + OR (g='xwvutsr' AND f GLOB 'fghij*') + OR f='ijklmnopq' + OR b=891 + OR b=1056 + } +} {5 8 15 26 28 34 60 81 86 90 96 scan 0 sort 0} +do_test where7-2.890.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='fghijklmn' + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR b=671 + OR (g='xwvutsr' AND f GLOB 'hijkl*') + } +} {5 7 31 39 57 61 83 99 scan 0 sort 0} +do_test where7-2.890.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='fghijklmn' + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR (g='edcbazy' AND f GLOB 'vwxyz*') + OR b=671 + OR (g='xwvutsr' AND f GLOB 'hijkl*') + } +} {5 7 31 39 57 61 83 99 scan 0 sort 0} +do_test where7-2.891.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='lkjihgf' AND f GLOB 'lmnop*') + OR (g='srqponm' AND f GLOB 'fghij*') + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + } +} {4 6 11 31 63 68 scan 0 sort 0} +do_test where7-2.891.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='lkjihgf' AND f GLOB 'lmnop*') + OR (g='srqponm' AND f GLOB 'fghij*') + OR ((a BETWEEN 4 AND 6) AND a!=5) + OR (g='kjihgfe' AND f GLOB 'qrstu*') + OR (d>=11.0 AND d<12.0 AND d NOT NULL) + } +} {4 6 11 31 63 68 scan 0 sort 0} +do_test where7-2.892.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=11011 + OR a=20 + OR b=432 + OR b=410 + OR a=86 + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR b=638 + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR b=190 + } +} {20 31 32 33 58 60 86 89 scan 0 sort 0} +do_test where7-2.892.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=11011 + OR a=20 + OR b=432 + OR b=410 + OR a=86 + OR (d>=89.0 AND d<90.0 AND d NOT NULL) + OR b=638 + OR ((a BETWEEN 58 AND 60) AND a!=59) + OR b=190 + } +} {20 31 32 33 58 60 86 89 scan 0 sort 0} +do_test where7-2.893.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=88 + OR ((a BETWEEN 42 AND 44) AND a!=43) + OR a=76 + OR b=69 + OR b=847 + OR b=275 + } +} {8 25 42 44 76 77 scan 0 sort 0} +do_test where7-2.893.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=88 + OR ((a BETWEEN 42 AND 44) AND a!=43) + OR a=76 + OR b=69 + OR b=847 + OR b=275 + } +} {8 25 42 44 76 77 scan 0 sort 0} +do_test where7-2.894.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=781 + OR b=77 + OR b=58 + OR ((a BETWEEN 67 AND 69) AND a!=68) + } +} {7 67 69 71 scan 0 sort 0} +do_test where7-2.894.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=781 + OR b=77 + OR b=58 + OR ((a BETWEEN 67 AND 69) AND a!=68) + } +} {7 67 69 71 scan 0 sort 0} +do_test where7-2.895.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 67 AND 69) AND a!=68) + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR a=46 + OR b=187 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (g='onmlkji' AND f GLOB 'yzabc*') + } +} {17 20 46 50 67 69 71 scan 0 sort 0} +do_test where7-2.895.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 67 AND 69) AND a!=68) + OR (d>=69.0 AND d<70.0 AND d NOT NULL) + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR a=46 + OR b=187 + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR (g='onmlkji' AND f GLOB 'yzabc*') + } +} {17 20 46 50 67 69 71 scan 0 sort 0} +do_test where7-2.896.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR a=99 + OR c=3003 + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR b=300 + OR b=718 + OR c>=34035 + OR b=264 + } +} {7 8 9 24 57 97 99 scan 0 sort 0} +do_test where7-2.896.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR a=99 + OR c=3003 + OR (d>=57.0 AND d<58.0 AND d NOT NULL) + OR b=300 + OR b=718 + OR c>=34035 + OR b=264 + } +} {7 8 9 24 57 97 99 scan 0 sort 0} +do_test where7-2.897.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=872 + OR b=209 + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR b=355 + OR b=729 + OR ((a BETWEEN 81 AND 83) AND a!=82) + OR a=58 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR b=608 + } +} {14 19 40 58 65 66 67 81 83 92 scan 0 sort 0} +do_test where7-2.897.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=872 + OR b=209 + OR ((a BETWEEN 65 AND 67) AND a!=66) + OR b=355 + OR b=729 + OR ((a BETWEEN 81 AND 83) AND a!=82) + OR a=58 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR b=608 + } +} {14 19 40 58 65 66 67 81 83 92 scan 0 sort 0} +do_test where7-2.898.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=29029 + OR f='efghijklm' + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR a=26 + OR (f GLOB '?efgh*' AND f GLOB 'defg*') + } +} {3 4 26 29 30 48 55 56 81 82 85 86 87 scan 0 sort 0} +do_test where7-2.898.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=29029 + OR f='efghijklm' + OR (d>=48.0 AND d<49.0 AND d NOT NULL) + OR a=26 + OR (f GLOB '?efgh*' AND f GLOB 'defg*') + } +} {3 4 26 29 30 48 55 56 81 82 85 86 87 scan 0 sort 0} +do_test where7-2.899.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=59 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR a=7 + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=762 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + } +} {7 12 14 26 40 59 66 92 scan 0 sort 0} +do_test where7-2.899.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=59 + OR (g='wvutsrq' AND f GLOB 'mnopq*') + OR a=7 + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=762 + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + } +} {7 12 14 26 40 59 66 92 scan 0 sort 0} +do_test where7-2.900.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='gfedcba' AND f GLOB 'nopqr*') + OR b=539 + OR b=399 + } +} {49 91 scan 0 sort 0} +do_test where7-2.900.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='gfedcba' AND f GLOB 'nopqr*') + OR b=539 + OR b=399 + } +} {49 91 scan 0 sort 0} +do_test where7-2.901.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR a=92 + } +} {71 73 92 96 98 scan 0 sort 0} +do_test where7-2.901.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 71 AND 73) AND a!=72) + OR ((a BETWEEN 96 AND 98) AND a!=97) + OR a=92 + } +} {71 73 92 96 98 scan 0 sort 0} +do_test where7-2.902.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (g='rqponml' AND f GLOB 'klmno*') + OR f='lmnopqrst' + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {9 11 35 36 37 57 61 63 87 89 scan 0 sort 0} +do_test where7-2.902.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR (g='rqponml' AND f GLOB 'klmno*') + OR f='lmnopqrst' + OR (g='nmlkjih' AND f GLOB 'fghij*') + } +} {9 11 35 36 37 57 61 63 87 89 scan 0 sort 0} +do_test where7-2.903.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 69 AND 71) AND a!=70) + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=652 + } +} {69 71 91 93 scan 0 sort 0} +do_test where7-2.903.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 69 AND 71) AND a!=70) + OR ((a BETWEEN 91 AND 93) AND a!=92) + OR b=652 + } +} {69 71 91 93 scan 0 sort 0} +do_test where7-2.904.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1067 + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR b=520 + OR b=399 + OR b=209 + OR a=68 + OR (g='fedcbaz' AND f GLOB 'qrstu*') + } +} {18 19 53 54 55 68 73 94 97 scan 0 sort 0} +do_test where7-2.904.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1067 + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR (g='jihgfed' AND f GLOB 'vwxyz*') + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR b=520 + OR b=399 + OR b=209 + OR a=68 + OR (g='fedcbaz' AND f GLOB 'qrstu*') + } +} {18 19 53 54 55 68 73 94 97 scan 0 sort 0} +do_test where7-2.905.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=79.0 AND d<80.0 AND d NOT NULL) + OR a=57 + OR b=55 + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR (g='rqponml' AND f GLOB 'lmnop*') + OR ((a BETWEEN 0 AND 2) AND a!=1) + OR ((a BETWEEN 21 AND 23) AND a!=22) + } +} {2 5 20 21 22 23 34 37 57 79 scan 0 sort 0} +do_test where7-2.905.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=79.0 AND d<80.0 AND d NOT NULL) + OR a=57 + OR b=55 + OR (d>=34.0 AND d<35.0 AND d NOT NULL) + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR (g='rqponml' AND f GLOB 'lmnop*') + OR ((a BETWEEN 0 AND 2) AND a!=1) + OR ((a BETWEEN 21 AND 23) AND a!=22) + } +} {2 5 20 21 22 23 34 37 57 79 scan 0 sort 0} +do_test where7-2.906.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 21 AND 23) AND a!=22) + OR a=2 + OR b=784 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR b=850 + } +} {2 21 23 81 scan 0 sort 0} +do_test where7-2.906.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 21 AND 23) AND a!=22) + OR a=2 + OR b=784 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (g='ihgfedc' AND f GLOB 'defgh*') + OR b=850 + } +} {2 21 23 81 scan 0 sort 0} +do_test where7-2.907.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=748 + OR b=209 + OR a=100 + } +} {19 45 51 68 100 scan 0 sort 0} +do_test where7-2.907.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=51.0 AND d<52.0 AND d NOT NULL) + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=748 + OR b=209 + OR a=100 + } +} {19 45 51 68 100 scan 0 sort 0} +do_test where7-2.908.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'zabcd*') + OR a=18 + OR a=30 + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR b=792 + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR c=26026 + OR (g='rqponml' AND f GLOB 'hijkl*') + } +} {8 9 10 11 18 19 21 30 33 37 63 72 76 77 78 84 86 89 scan 0 sort 0} +do_test where7-2.908.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'zabcd*') + OR a=18 + OR a=30 + OR ((a BETWEEN 9 AND 11) AND a!=10) + OR ((a BETWEEN 84 AND 86) AND a!=85) + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR b=792 + OR (f GLOB '?mnop*' AND f GLOB 'lmno*') + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR c=26026 + OR (g='rqponml' AND f GLOB 'hijkl*') + } +} {8 9 10 11 18 19 21 30 33 37 63 72 76 77 78 84 86 89 scan 0 sort 0} +do_test where7-2.909.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='vutsrqp' AND f GLOB 'qrstu*') + OR b=968 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + OR a=78 + OR ((a BETWEEN 90 AND 92) AND a!=91) + } +} {16 22 48 63 65 72 74 78 88 90 92 100 scan 0 sort 0} +do_test where7-2.909.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='vutsrqp' AND f GLOB 'qrstu*') + OR b=968 + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR (d>=72.0 AND d<73.0 AND d NOT NULL) + OR a=78 + OR ((a BETWEEN 90 AND 92) AND a!=91) + } +} {16 22 48 63 65 72 74 78 88 90 92 100 scan 0 sort 0} +do_test where7-2.910.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=10010 + OR f='pqrstuvwx' + } +} {15 28 29 30 41 67 93 scan 0 sort 0} +do_test where7-2.910.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=10010 + OR f='pqrstuvwx' + } +} {15 28 29 30 41 67 93 scan 0 sort 0} +do_test where7-2.911.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=86 + OR a=10 + OR b=528 + OR b=253 + OR a=80 + OR a=87 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + } +} {10 23 37 48 80 86 87 scan 0 sort 0} +do_test where7-2.911.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=86 + OR a=10 + OR b=528 + OR b=253 + OR a=80 + OR a=87 + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + } +} {10 23 37 48 80 86 87 scan 0 sort 0} +do_test where7-2.912.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=42.0 AND d<43.0 AND d NOT NULL) + OR b=825 + OR a=100 + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR a=60 + } +} {42 60 75 77 100 scan 0 sort 0} +do_test where7-2.912.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=42.0 AND d<43.0 AND d NOT NULL) + OR b=825 + OR a=100 + OR (d>=77.0 AND d<78.0 AND d NOT NULL) + OR a=60 + } +} {42 60 75 77 100 scan 0 sort 0} +do_test where7-2.913.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=883 + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + OR (d>=3.0 AND d<4.0 AND d NOT NULL) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR a=81 + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR f='mnopqrstu' + } +} {3 4 12 30 35 38 45 56 64 78 81 82 90 94 scan 0 sort 0} +do_test where7-2.913.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=94.0 AND d<95.0 AND d NOT NULL) + OR b=883 + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + OR (d>=3.0 AND d<4.0 AND d NOT NULL) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR a=81 + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR f='mnopqrstu' + } +} {3 4 12 30 35 38 45 56 64 78 81 82 90 94 scan 0 sort 0} +do_test where7-2.914.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=443 + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR b=663 + OR b=905 + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=883 + OR c=22022 + OR b=638 + } +} {14 16 58 64 65 66 96 scan 0 sort 0} +do_test where7-2.914.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=443 + OR ((a BETWEEN 14 AND 16) AND a!=15) + OR b=663 + OR b=905 + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR b=883 + OR c=22022 + OR b=638 + } +} {14 16 58 64 65 66 96 scan 0 sort 0} +do_test where7-2.915.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR b=234 + OR a=53 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR ((a BETWEEN 27 AND 29) AND a!=28) + OR b=319 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {14 16 20 22 27 29 40 53 84 86 scan 0 sort 0} +do_test where7-2.915.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 84 AND 86) AND a!=85) + OR b=234 + OR a=53 + OR ((a BETWEEN 20 AND 22) AND a!=21) + OR ((a BETWEEN 27 AND 29) AND a!=28) + OR b=319 + OR (g='qponmlk' AND f GLOB 'opqrs*') + OR ((a BETWEEN 14 AND 16) AND a!=15) + } +} {14 16 20 22 27 29 40 53 84 86 scan 0 sort 0} +do_test where7-2.916.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=179 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR a=46 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR a=25 + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR f='opqrstuvw' + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR b=938 + } +} {5 13 14 25 40 46 53 55 66 72 92 95 97 scan 0 sort 0} +do_test where7-2.916.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=179 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR a=46 + OR (g='kjihgfe' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 53 AND 55) AND a!=54) + OR a=25 + OR (d>=5.0 AND d<6.0 AND d NOT NULL) + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR f='opqrstuvw' + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR b=938 + } +} {5 13 14 25 40 46 53 55 66 72 92 95 97 scan 0 sort 0} +do_test where7-2.917.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='nmlkjih' AND f GLOB 'fghij*') + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + } +} {15 57 scan 0 sort 0} +do_test where7-2.917.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='nmlkjih' AND f GLOB 'fghij*') + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + } +} {15 57 scan 0 sort 0} +do_test where7-2.918.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=748 + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR a=32 + OR b=110 + OR b=297 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR f='ghijklmno' + OR b=473 + OR b=135 + } +} {6 10 13 22 27 32 43 58 60 62 68 84 scan 0 sort 0} +do_test where7-2.918.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=748 + OR (g='utsrqpo' AND f GLOB 'wxyza*') + OR a=32 + OR b=110 + OR b=297 + OR (d>=13.0 AND d<14.0 AND d NOT NULL) + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR f='ghijklmno' + OR b=473 + OR b=135 + } +} {6 10 13 22 27 32 43 58 60 62 68 84 scan 0 sort 0} +do_test where7-2.919.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=33.0 AND d<34.0 AND d NOT NULL) + OR b=905 + OR a=97 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR c=27027 + OR f='bcdefghij' + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + } +} {1 4 25 27 30 33 38 40 53 54 56 79 80 81 82 85 97 scan 0 sort 0} +do_test where7-2.919.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=33.0 AND d<34.0 AND d NOT NULL) + OR b=905 + OR a=97 + OR (g='hgfedcb' AND f GLOB 'hijkl*') + OR c=27027 + OR f='bcdefghij' + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR (d>=25.0 AND d<26.0 AND d NOT NULL) + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + } +} {1 4 25 27 30 33 38 40 53 54 56 79 80 81 82 85 97 scan 0 sort 0} +do_test where7-2.920.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 64 AND 66) AND a!=65) + OR ((a BETWEEN 90 AND 92) AND a!=91) + } +} {64 66 90 92 scan 0 sort 0} +do_test where7-2.920.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 64 AND 66) AND a!=65) + OR ((a BETWEEN 90 AND 92) AND a!=91) + } +} {64 66 90 92 scan 0 sort 0} +do_test where7-2.921.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=594 + OR b=80 + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR b=421 + OR b=418 + OR b=828 + OR a=88 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + } +} {23 27 38 54 60 88 scan 0 sort 0} +do_test where7-2.921.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=594 + OR b=80 + OR (g='tsrqpon' AND f GLOB 'bcdef*') + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR b=421 + OR b=418 + OR b=828 + OR a=88 + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + } +} {23 27 38 54 60 88 scan 0 sort 0} +do_test where7-2.922.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'xyzab*') + OR b=366 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR c=16016 + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR c=9009 + } +} {17 25 26 27 28 46 47 48 75 100 scan 0 sort 0} +do_test where7-2.922.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'xyzab*') + OR b=366 + OR (d>=28.0 AND d<29.0 AND d NOT NULL) + OR c=16016 + OR (g='edcbazy' AND f GLOB 'wxyza*') + OR c=9009 + } +} {17 25 26 27 28 46 47 48 75 100 scan 0 sort 0} +do_test where7-2.923.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=33 + OR f='qrstuvwxy' + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR b=858 + } +} {3 16 20 42 68 78 94 scan 0 sort 0} +do_test where7-2.923.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=33 + OR f='qrstuvwxy' + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR b=858 + } +} {3 16 20 42 68 78 94 scan 0 sort 0} +do_test where7-2.924.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=861 + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR b=682 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR b=286 + } +} {22 26 29 48 62 74 93 95 100 scan 0 sort 0} +do_test where7-2.924.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=861 + OR (f GLOB '?xyza*' AND f GLOB 'wxyz*') + OR (d>=29.0 AND d<30.0 AND d NOT NULL) + OR b=682 + OR ((a BETWEEN 93 AND 95) AND a!=94) + OR b=286 + } +} {22 26 29 48 62 74 93 95 100 scan 0 sort 0} +do_test where7-2.925.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=740 + OR ((a BETWEEN 27 AND 29) AND a!=28) + OR a=88 + } +} {27 29 88 scan 0 sort 0} +do_test where7-2.925.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=740 + OR ((a BETWEEN 27 AND 29) AND a!=28) + OR a=88 + } +} {27 29 88 scan 0 sort 0} +do_test where7-2.926.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='abcdefghi' + OR c=9009 + OR b=663 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR b=91 + } +} {10 25 26 27 52 78 scan 0 sort 0} +do_test where7-2.926.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='abcdefghi' + OR c=9009 + OR b=663 + OR (g='wvutsrq' AND f GLOB 'klmno*') + OR b=91 + } +} {10 25 26 27 52 78 scan 0 sort 0} +do_test where7-2.927.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='kjihgfe' AND f GLOB 'qrstu*') + OR ((a BETWEEN 29 AND 31) AND a!=30) + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=1015 + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR b=916 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR b=69 + OR (g='hgfedcb' AND f GLOB 'fghij*') + } +} {13 29 31 39 42 65 68 83 91 scan 0 sort 0} +do_test where7-2.927.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='kjihgfe' AND f GLOB 'qrstu*') + OR ((a BETWEEN 29 AND 31) AND a!=30) + OR (f GLOB '?opqr*' AND f GLOB 'nopq*') + OR b=1015 + OR (g='qponmlk' AND f GLOB 'qrstu*') + OR b=916 + OR (d>=31.0 AND d<32.0 AND d NOT NULL) + OR b=69 + OR (g='hgfedcb' AND f GLOB 'fghij*') + } +} {13 29 31 39 42 65 68 83 91 scan 0 sort 0} +do_test where7-2.928.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=88 + OR a=1 + OR f='uvwxyzabc' + OR b=498 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR a=63 + OR f='mnopqrstu' + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR b=495 + OR a=35 + OR a=22 + } +} {1 12 20 22 35 38 45 46 60 63 64 72 88 90 98 scan 0 sort 0} +do_test where7-2.928.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=88 + OR a=1 + OR f='uvwxyzabc' + OR b=498 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR a=63 + OR f='mnopqrstu' + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR b=495 + OR a=35 + OR a=22 + } +} {1 12 20 22 35 38 45 46 60 63 64 72 88 90 98 scan 0 sort 0} +do_test where7-2.929.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=869 + OR (g='rqponml' AND f GLOB 'jklmn*') + OR b=289 + OR a=62 + OR ((a BETWEEN 9 AND 11) AND a!=10) + } +} {9 11 35 62 79 scan 0 sort 0} +do_test where7-2.929.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=869 + OR (g='rqponml' AND f GLOB 'jklmn*') + OR b=289 + OR a=62 + OR ((a BETWEEN 9 AND 11) AND a!=10) + } +} {9 11 35 62 79 scan 0 sort 0} +do_test where7-2.930.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 22 AND 24) AND a!=23) + OR b=542 + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR a=7 + OR f='klmnopqrs' + } +} {7 10 19 21 22 24 36 62 88 scan 0 sort 0} +do_test where7-2.930.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 22 AND 24) AND a!=23) + OR b=542 + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR a=7 + OR f='klmnopqrs' + } +} {7 10 19 21 22 24 36 62 88 scan 0 sort 0} +do_test where7-2.931.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 57 AND 59) AND a!=58) + OR b=1078 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR b=429 + } +} {20 21 23 39 57 59 60 98 scan 0 sort 0} +do_test where7-2.931.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 57 AND 59) AND a!=58) + OR b=1078 + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (g='mlkjihg' AND f GLOB 'ijklm*') + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR b=429 + } +} {20 21 23 39 57 59 60 98 scan 0 sort 0} +do_test where7-2.932.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=82.0 AND d<83.0 AND d NOT NULL) + OR b=264 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR b=1048 + OR a=15 + } +} {15 24 82 85 87 scan 0 sort 0} +do_test where7-2.932.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=82.0 AND d<83.0 AND d NOT NULL) + OR b=264 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR b=1048 + OR a=15 + } +} {15 24 82 85 87 scan 0 sort 0} +do_test where7-2.933.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=93 + OR f='ijklmnopq' + OR f='mnopqrstu' + OR ((a BETWEEN 67 AND 69) AND a!=68) + } +} {8 12 34 38 60 64 67 69 86 90 93 scan 0 sort 0} +do_test where7-2.933.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=93 + OR f='ijklmnopq' + OR f='mnopqrstu' + OR ((a BETWEEN 67 AND 69) AND a!=68) + } +} {8 12 34 38 60 64 67 69 86 90 93 scan 0 sort 0} +do_test where7-2.934.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=56.0 AND d<57.0 AND d NOT NULL) + OR b=858 + OR a=58 + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR c=21021 + OR ((a BETWEEN 45 AND 47) AND a!=46) + OR b=616 + OR b=784 + OR b=55 + } +} {5 45 47 49 56 58 61 62 63 78 scan 0 sort 0} +do_test where7-2.934.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=56.0 AND d<57.0 AND d NOT NULL) + OR b=858 + OR a=58 + OR (g='onmlkji' AND f GLOB 'xyzab*') + OR c=21021 + OR ((a BETWEEN 45 AND 47) AND a!=46) + OR b=616 + OR b=784 + OR b=55 + } +} {5 45 47 49 56 58 61 62 63 78 scan 0 sort 0} +do_test where7-2.935.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=682 + OR b=99 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR b=531 + } +} {2 9 28 54 62 80 scan 0 sort 0} +do_test where7-2.935.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=682 + OR b=99 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR b=531 + } +} {2 9 28 54 62 80 scan 0 sort 0} +do_test where7-2.936.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 56 AND 58) AND a!=57) + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR b=726 + OR a=79 + OR a=47 + OR b=212 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR c=8008 + } +} {8 22 23 24 26 34 47 52 56 58 60 66 70 78 79 86 scan 0 sort 0} +do_test where7-2.936.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 56 AND 58) AND a!=57) + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR (f GLOB '?jklm*' AND f GLOB 'ijkl*') + OR b=726 + OR a=79 + OR a=47 + OR b=212 + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + OR c=8008 + } +} {8 22 23 24 26 34 47 52 56 58 60 66 70 78 79 86 scan 0 sort 0} +do_test where7-2.937.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='uvwxyzabc' + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR a=5 + OR b=33 + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + OR a=59 + OR b=44 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + OR (d>=59.0 AND d<60.0 AND d NOT NULL) + } +} {3 4 5 14 20 23 46 49 59 60 62 72 75 98 scan 0 sort 0} +do_test where7-2.937.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='uvwxyzabc' + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR a=5 + OR b=33 + OR (f GLOB '?yzab*' AND f GLOB 'xyza*') + OR a=59 + OR b=44 + OR (d>=14.0 AND d<15.0 AND d NOT NULL) + OR (d>=59.0 AND d<60.0 AND d NOT NULL) + } +} {3 4 5 14 20 23 46 49 59 60 62 72 75 98 scan 0 sort 0} +do_test where7-2.938.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=564 + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR b=451 + OR b=330 + OR a=47 + OR ((a BETWEEN 17 AND 19) AND a!=18) + } +} {17 19 30 41 47 93 scan 0 sort 0} +do_test where7-2.938.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=564 + OR (d>=93.0 AND d<94.0 AND d NOT NULL) + OR b=451 + OR b=330 + OR a=47 + OR ((a BETWEEN 17 AND 19) AND a!=18) + } +} {17 19 30 41 47 93 scan 0 sort 0} +do_test where7-2.939.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=40 + OR b=333 + } +} {40 scan 0 sort 0} +do_test where7-2.939.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=40 + OR b=333 + } +} {40 scan 0 sort 0} +do_test where7-2.940.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=924 + OR ((a BETWEEN 6 AND 8) AND a!=7) + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR a=100 + OR c=15015 + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + } +} {2 6 8 36 40 43 44 45 82 84 100 scan 0 sort 0} +do_test where7-2.940.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=924 + OR ((a BETWEEN 6 AND 8) AND a!=7) + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR (d>=40.0 AND d<41.0 AND d NOT NULL) + OR a=100 + OR c=15015 + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + OR (d>=2.0 AND d<3.0 AND d NOT NULL) + } +} {2 6 8 36 40 43 44 45 82 84 100 scan 0 sort 0} +do_test where7-2.941.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + } +} {36 44 63 scan 0 sort 0} +do_test where7-2.941.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=63.0 AND d<64.0 AND d NOT NULL) + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + } +} {36 44 63 scan 0 sort 0} +do_test where7-2.942.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=58 + OR ((a BETWEEN 7 AND 9) AND a!=8) + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=31 + OR f='tuvwxyzab' + OR b=341 + OR b=47 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR a=49 + OR b=223 + OR f='qrstuvwxy' + } +} {7 9 16 19 31 42 45 49 63 65 68 71 94 95 97 scan 0 sort 0} +do_test where7-2.942.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=58 + OR ((a BETWEEN 7 AND 9) AND a!=8) + OR ((a BETWEEN 63 AND 65) AND a!=64) + OR a=31 + OR f='tuvwxyzab' + OR b=341 + OR b=47 + OR ((a BETWEEN 95 AND 97) AND a!=96) + OR a=49 + OR b=223 + OR f='qrstuvwxy' + } +} {7 9 16 19 31 42 45 49 63 65 68 71 94 95 97 scan 0 sort 0} +do_test where7-2.943.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=96 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR a=85 + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR c=11011 + OR b=641 + OR f='vwxyzabcd' + OR b=286 + } +} {4 10 12 21 23 26 30 31 32 33 37 39 47 56 73 82 85 96 99 scan 0 sort 0} +do_test where7-2.943.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=96 + OR (d>=23.0 AND d<24.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'vwxyz*') + OR (f GLOB '?fghi*' AND f GLOB 'efgh*') + OR ((a BETWEEN 37 AND 39) AND a!=38) + OR a=85 + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR c=11011 + OR b=641 + OR f='vwxyzabcd' + OR b=286 + } +} {4 10 12 21 23 26 30 31 32 33 37 39 47 56 73 82 85 96 99 scan 0 sort 0} +do_test where7-2.944.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 3 AND 5) AND a!=4) + OR b=1012 + OR a=7 + OR b=773 + OR a=1 + OR b=726 + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR b=110 + } +} {1 3 5 7 10 66 87 89 92 99 scan 0 sort 0} +do_test where7-2.944.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 3 AND 5) AND a!=4) + OR b=1012 + OR a=7 + OR b=773 + OR a=1 + OR b=726 + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR ((a BETWEEN 87 AND 89) AND a!=88) + OR b=110 + } +} {1 3 5 7 10 66 87 89 92 99 scan 0 sort 0} +do_test where7-2.945.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'hijkl*') + OR a=60 + OR a=4 + OR b=520 + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR a=44 + OR a=36 + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR b=715 + OR (g='vutsrqp' AND f GLOB 'qrstu*') + } +} {4 7 16 36 44 60 65 76 79 scan 0 sort 0} +do_test where7-2.945.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'hijkl*') + OR a=60 + OR a=4 + OR b=520 + OR (g='ihgfedc' AND f GLOB 'bcdef*') + OR a=44 + OR a=36 + OR (d>=76.0 AND d<77.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR b=715 + OR (g='vutsrqp' AND f GLOB 'qrstu*') + } +} {4 7 16 36 44 60 65 76 79 scan 0 sort 0} +do_test where7-2.946.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 3 AND 5) AND a!=4) + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR a=24 + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + } +} {3 5 15 24 26 52 55 56 58 76 78 99 scan 0 sort 0} +do_test where7-2.946.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 3 AND 5) AND a!=4) + OR ((a BETWEEN 56 AND 58) AND a!=57) + OR (d>=15.0 AND d<16.0 AND d NOT NULL) + OR (d>=55.0 AND d<56.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'yzabc*') + OR a=24 + OR (d>=99.0 AND d<100.0 AND d NOT NULL) + OR (f GLOB '?bcde*' AND f GLOB 'abcd*') + } +} {3 5 15 24 26 52 55 56 58 76 78 99 scan 0 sort 0} +do_test where7-2.947.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='utsrqpo' AND f GLOB 'vwxyz*') + OR b=132 + OR f='ghijklmno' + OR b=740 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=1059 + } +} {6 12 21 26 32 38 58 84 scan 0 sort 0} +do_test where7-2.947.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='utsrqpo' AND f GLOB 'vwxyz*') + OR b=132 + OR f='ghijklmno' + OR b=740 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=1059 + } +} {6 12 21 26 32 38 58 84 scan 0 sort 0} +do_test where7-2.948.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=28 + OR b=927 + OR b=520 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR b=638 + OR f='vwxyzabcd' + } +} {21 28 47 53 58 73 99 scan 0 sort 0} +do_test where7-2.948.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=28 + OR b=927 + OR b=520 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + OR b=638 + OR f='vwxyzabcd' + } +} {21 28 47 53 58 73 99 scan 0 sort 0} +do_test where7-2.949.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='nmlkjih' AND f GLOB 'cdefg*') + OR b=1026 + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'lmnop*') + OR b=355 + OR b=641 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + } +} {1 11 53 54 scan 0 sort 0} +do_test where7-2.949.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='nmlkjih' AND f GLOB 'cdefg*') + OR b=1026 + OR (d>=1.0 AND d<2.0 AND d NOT NULL) + OR (g='wvutsrq' AND f GLOB 'lmnop*') + OR b=355 + OR b=641 + OR (d>=53.0 AND d<54.0 AND d NOT NULL) + } +} {1 11 53 54 scan 0 sort 0} +do_test where7-2.950.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 46 AND 48) AND a!=47) + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR b=641 + OR a=3 + OR a=35 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR f='opqrstuvw' + OR a=41 + OR a=83 + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR b=751 + } +} {3 14 35 40 41 46 48 54 60 62 66 81 83 92 scan 0 sort 0} +do_test where7-2.950.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 46 AND 48) AND a!=47) + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR b=641 + OR a=3 + OR a=35 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR f='opqrstuvw' + OR a=41 + OR a=83 + OR (g='nmlkjih' AND f GLOB 'cdefg*') + OR b=751 + } +} {3 14 35 40 41 46 48 54 60 62 66 81 83 92 scan 0 sort 0} +do_test where7-2.951.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 3 AND 5) AND a!=4) + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR c=15015 + OR b=146 + OR b=1092 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + } +} {3 5 43 44 45 60 62 scan 0 sort 0} +do_test where7-2.951.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 3 AND 5) AND a!=4) + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR c=15015 + OR b=146 + OR b=1092 + OR (d>=60.0 AND d<61.0 AND d NOT NULL) + } +} {3 5 43 44 45 60 62 scan 0 sort 0} +do_test where7-2.952.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'qrstu*') + OR f='bcdefghij' + OR f='hijklmnop' + OR a=65 + OR f='ijklmnopq' + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR g IS NULL + OR a=26 + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR a=9 + OR (d>=32.0 AND d<33.0 AND d NOT NULL) + } +} {1 7 8 9 26 27 32 33 34 38 40 42 53 59 60 65 79 85 86 scan 0 sort 0} +do_test where7-2.952.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'qrstu*') + OR f='bcdefghij' + OR f='hijklmnop' + OR a=65 + OR f='ijklmnopq' + OR (d>=79.0 AND d<80.0 AND d NOT NULL) + OR g IS NULL + OR a=26 + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR a=9 + OR (d>=32.0 AND d<33.0 AND d NOT NULL) + } +} {1 7 8 9 26 27 32 33 34 38 40 42 53 59 60 65 79 85 86 scan 0 sort 0} +do_test where7-2.953.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='jihgfed' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR b=1100 + OR c=6006 + OR c=4004 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR c=33033 + } +} {10 11 12 16 17 18 24 26 41 70 73 79 81 97 98 99 100 scan 0 sort 0} +do_test where7-2.953.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='jihgfed' AND f GLOB 'vwxyz*') + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR ((a BETWEEN 79 AND 81) AND a!=80) + OR (g='kjihgfe' AND f GLOB 'stuvw*') + OR (g='qponmlk' AND f GLOB 'pqrst*') + OR b=1100 + OR c=6006 + OR c=4004 + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR c=33033 + } +} {10 11 12 16 17 18 24 26 41 70 73 79 81 97 98 99 100 scan 0 sort 0} +do_test where7-2.954.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=17 + OR ((a BETWEEN 95 AND 97) AND a!=96) + } +} {17 95 97 scan 0 sort 0} +do_test where7-2.954.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=17 + OR ((a BETWEEN 95 AND 97) AND a!=96) + } +} {17 95 97 scan 0 sort 0} +do_test where7-2.955.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=3003 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR a=93 + } +} {7 8 9 67 93 scan 0 sort 0} +do_test where7-2.955.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=3003 + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR a=93 + } +} {7 8 9 67 93 scan 0 sort 0} +do_test where7-2.956.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=42.0 AND d<43.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=737 + } +} {12 21 23 42 44 67 scan 0 sort 0} +do_test where7-2.956.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=42.0 AND d<43.0 AND d NOT NULL) + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR ((a BETWEEN 21 AND 23) AND a!=22) + OR (d>=12.0 AND d<13.0 AND d NOT NULL) + OR b=737 + } +} {12 21 23 42 44 67 scan 0 sort 0} +do_test where7-2.957.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='rqponml' AND f GLOB 'klmno*') + OR ((a BETWEEN 5 AND 7) AND a!=6) + } +} {5 7 36 scan 0 sort 0} +do_test where7-2.957.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='rqponml' AND f GLOB 'klmno*') + OR ((a BETWEEN 5 AND 7) AND a!=6) + } +} {5 7 36 scan 0 sort 0} +do_test where7-2.958.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='hgfedcb' AND f GLOB 'hijkl*') + OR c=32032 + OR f='opqrstuvw' + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR b=993 + } +} {14 40 49 51 66 68 85 92 94 95 96 scan 0 sort 0} +do_test where7-2.958.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='hgfedcb' AND f GLOB 'hijkl*') + OR c=32032 + OR f='opqrstuvw' + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR ((a BETWEEN 49 AND 51) AND a!=50) + OR b=993 + } +} {14 40 49 51 66 68 85 92 94 95 96 scan 0 sort 0} +do_test where7-2.959.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=12.0 AND d<13.0 AND d NOT NULL) + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR b=245 + OR b=528 + OR b=366 + OR a=73 + OR a=49 + OR b=421 + OR a=58 + } +} {12 38 48 49 58 59 61 73 86 88 scan 0 sort 0} +do_test where7-2.959.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=12.0 AND d<13.0 AND d NOT NULL) + OR ((a BETWEEN 59 AND 61) AND a!=60) + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR b=245 + OR b=528 + OR b=366 + OR a=73 + OR a=49 + OR b=421 + OR a=58 + } +} {12 38 48 49 58 59 61 73 86 88 scan 0 sort 0} +do_test where7-2.960.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=100.0 AND d<101.0 AND d NOT NULL) + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR b=146 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR ((a BETWEEN 73 AND 75) AND a!=74) + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR b=704 + } +} {8 10 20 43 60 62 64 73 75 82 86 88 100 scan 0 sort 0} +do_test where7-2.960.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=100.0 AND d<101.0 AND d NOT NULL) + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR ((a BETWEEN 86 AND 88) AND a!=87) + OR b=146 + OR (g='ponmlkj' AND f GLOB 'rstuv*') + OR ((a BETWEEN 73 AND 75) AND a!=74) + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR ((a BETWEEN 60 AND 62) AND a!=61) + OR (g='ihgfedc' AND f GLOB 'efghi*') + OR b=704 + } +} {8 10 20 43 60 62 64 73 75 82 86 88 100 scan 0 sort 0} +do_test where7-2.961.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 65 AND 67) AND a!=66) + OR b=14 + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR a=49 + OR b=333 + } +} {3 5 49 65 67 scan 0 sort 0} +do_test where7-2.961.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 65 AND 67) AND a!=66) + OR b=14 + OR ((a BETWEEN 3 AND 5) AND a!=4) + OR a=49 + OR b=333 + } +} {3 5 49 65 67 scan 0 sort 0} +do_test where7-2.962.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=17017 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR b=971 + OR a=37 + OR a=7 + OR b=641 + OR a=13 + OR b=597 + } +} {7 13 37 38 49 50 51 scan 0 sort 0} +do_test where7-2.962.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=17017 + OR (g='qponmlk' AND f GLOB 'mnopq*') + OR b=971 + OR a=37 + OR a=7 + OR b=641 + OR a=13 + OR b=597 + } +} {7 13 37 38 49 50 51 scan 0 sort 0} +do_test where7-2.963.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='tuvwxyzab' + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + } +} {17 19 43 45 69 71 95 97 scan 0 sort 0} +do_test where7-2.963.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='tuvwxyzab' + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + } +} {17 19 43 45 69 71 95 97 scan 0 sort 0} +do_test where7-2.964.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=638 + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR b=165 + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR f='stuvwxyza' + OR b=652 + OR b=66 + OR b=770 + OR b=91 + } +} {6 10 12 15 18 44 58 70 89 96 scan 0 sort 0} +do_test where7-2.964.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=638 + OR (d>=44.0 AND d<45.0 AND d NOT NULL) + OR (g='gfedcba' AND f GLOB 'lmnop*') + OR b=165 + OR ((a BETWEEN 10 AND 12) AND a!=11) + OR f='stuvwxyza' + OR b=652 + OR b=66 + OR b=770 + OR b=91 + } +} {6 10 12 15 18 44 58 70 89 96 scan 0 sort 0} +do_test where7-2.965.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=52.0 AND d<53.0 AND d NOT NULL) + OR f='opqrstuvw' + OR a=83 + OR a=93 + OR b=858 + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'vwxyz*') + } +} {14 18 40 52 66 73 78 83 92 93 scan 0 sort 0} +do_test where7-2.965.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=52.0 AND d<53.0 AND d NOT NULL) + OR f='opqrstuvw' + OR a=83 + OR a=93 + OR b=858 + OR (d>=18.0 AND d<19.0 AND d NOT NULL) + OR (g='jihgfed' AND f GLOB 'vwxyz*') + } +} {14 18 40 52 66 73 78 83 92 93 scan 0 sort 0} +do_test where7-2.966.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE c=3003 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR a=38 + } +} {7 8 9 38 40 42 scan 0 sort 0} +do_test where7-2.966.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE c=3003 + OR ((a BETWEEN 40 AND 42) AND a!=41) + OR a=38 + } +} {7 8 9 38 40 42 scan 0 sort 0} +do_test where7-2.967.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR ((a BETWEEN 50 AND 52) AND a!=51) + } +} {50 52 60 scan 0 sort 0} +do_test where7-2.967.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=60.0 AND d<61.0 AND d NOT NULL) + OR ((a BETWEEN 50 AND 52) AND a!=51) + } +} {50 52 60 scan 0 sort 0} +do_test where7-2.968.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='qponmlk' AND f GLOB 'mnopq*') + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR a=5 + OR b=396 + OR a=13 + } +} {5 13 24 26 36 38 scan 0 sort 0} +do_test where7-2.968.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='qponmlk' AND f GLOB 'mnopq*') + OR ((a BETWEEN 24 AND 26) AND a!=25) + OR a=5 + OR b=396 + OR a=13 + } +} {5 13 24 26 36 38 scan 0 sort 0} +do_test where7-2.969.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=748 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR b=531 + OR b=1092 + OR b=418 + } +} {38 68 69 71 95 97 scan 0 sort 0} +do_test where7-2.969.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR b=748 + OR (d>=97.0 AND d<98.0 AND d NOT NULL) + OR ((a BETWEEN 69 AND 71) AND a!=70) + OR b=531 + OR b=1092 + OR b=418 + } +} {38 68 69 71 95 97 scan 0 sort 0} +do_test where7-2.970.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=30.0 AND d<31.0 AND d NOT NULL) + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR a=50 + OR a=46 + OR ((a BETWEEN 38 AND 40) AND a!=39) + } +} {8 10 14 30 38 40 46 50 66 92 scan 0 sort 0} +do_test where7-2.970.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=30.0 AND d<31.0 AND d NOT NULL) + OR ((a BETWEEN 8 AND 10) AND a!=9) + OR (f GLOB '?pqrs*' AND f GLOB 'opqr*') + OR a=50 + OR a=46 + OR ((a BETWEEN 38 AND 40) AND a!=39) + } +} {8 10 14 30 38 40 46 50 66 92 scan 0 sort 0} +do_test where7-2.971.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=24 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR b=487 + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR b=132 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR b=795 + OR b=737 + } +} {12 13 15 22 24 54 67 96 scan 0 sort 0} +do_test where7-2.971.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=24 + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR b=487 + OR (d>=96.0 AND d<97.0 AND d NOT NULL) + OR ((a BETWEEN 13 AND 15) AND a!=14) + OR b=132 + OR (d>=54.0 AND d<55.0 AND d NOT NULL) + OR b=795 + OR b=737 + } +} {12 13 15 22 24 54 67 96 scan 0 sort 0} +do_test where7-2.972.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=88.0 AND d<89.0 AND d NOT NULL) + OR a=34 + OR c=16016 + OR b=1078 + OR b=960 + OR (g='hgfedcb' AND f GLOB 'jklmn*') + } +} {34 46 47 48 87 88 98 scan 0 sort 0} +do_test where7-2.972.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=88.0 AND d<89.0 AND d NOT NULL) + OR a=34 + OR c=16016 + OR b=1078 + OR b=960 + OR (g='hgfedcb' AND f GLOB 'jklmn*') + } +} {34 46 47 48 87 88 98 scan 0 sort 0} +do_test where7-2.973.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1081 + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 73 AND 75) AND a!=74) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR a=6 + } +} {6 19 21 38 45 73 75 scan 0 sort 0} +do_test where7-2.973.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1081 + OR ((a BETWEEN 19 AND 21) AND a!=20) + OR (g='ponmlkj' AND f GLOB 'tuvwx*') + OR ((a BETWEEN 73 AND 75) AND a!=74) + OR (d>=38.0 AND d<39.0 AND d NOT NULL) + OR a=6 + } +} {6 19 21 38 45 73 75 scan 0 sort 0} +do_test where7-2.974.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR (g='rqponml' AND f GLOB 'lmnop*') + OR a=92 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR f='fghijklmn' + OR a=100 + OR b=209 + OR c=9009 + OR ((a BETWEEN 52 AND 54) AND a!=53) + OR a=73 + OR b=902 + } +} {5 9 19 25 26 27 31 35 37 52 54 57 61 73 82 83 87 92 95 100 scan 0 sort 0} +do_test where7-2.974.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='fedcbaz' AND f GLOB 'rstuv*') + OR (g='rqponml' AND f GLOB 'lmnop*') + OR a=92 + OR (f GLOB '?klmn*' AND f GLOB 'jklm*') + OR f='fghijklmn' + OR a=100 + OR b=209 + OR c=9009 + OR ((a BETWEEN 52 AND 54) AND a!=53) + OR a=73 + OR b=902 + } +} {5 9 19 25 26 27 31 35 37 52 54 57 61 73 82 83 87 92 95 100 scan 0 sort 0} +do_test where7-2.975.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=110 + OR f='ghijklmno' + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + } +} {6 10 21 32 40 58 84 scan 0 sort 0} +do_test where7-2.975.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=40.0 AND d<41.0 AND d NOT NULL) + OR b=110 + OR f='ghijklmno' + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + } +} {6 10 21 32 40 58 84 scan 0 sort 0} +do_test where7-2.976.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 51 AND 53) AND a!=52) + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR b=91 + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=77 + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR (g='vutsrqp' AND f GLOB 'pqrst*') + } +} {1 7 15 20 27 45 46 51 53 79 scan 0 sort 0} +do_test where7-2.976.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 51 AND 53) AND a!=52) + OR (g='utsrqpo' AND f GLOB 'uvwxy*') + OR (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR b=91 + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR b=77 + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR (g='vutsrqp' AND f GLOB 'pqrst*') + } +} {1 7 15 20 27 45 46 51 53 79 scan 0 sort 0} +do_test where7-2.977.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR b=693 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR a=52 + OR b=377 + } +} {21 26 42 52 56 63 78 scan 0 sort 0} +do_test where7-2.977.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=56.0 AND d<57.0 AND d NOT NULL) + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR b=693 + OR (d>=21.0 AND d<22.0 AND d NOT NULL) + OR (d>=26.0 AND d<27.0 AND d NOT NULL) + OR (d>=42.0 AND d<43.0 AND d NOT NULL) + OR a=52 + OR b=377 + } +} {21 26 42 52 56 63 78 scan 0 sort 0} +do_test where7-2.978.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=99 + OR a=36 + OR b=297 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=1004 + OR b=872 + OR a=95 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR b=176 + OR b=300 + } +} {16 27 36 66 68 95 99 scan 0 sort 0} +do_test where7-2.978.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=99 + OR a=36 + OR b=297 + OR ((a BETWEEN 66 AND 68) AND a!=67) + OR b=1004 + OR b=872 + OR a=95 + OR (d>=27.0 AND d<28.0 AND d NOT NULL) + OR b=176 + OR b=300 + } +} {16 27 36 66 68 95 99 scan 0 sort 0} +do_test where7-2.979.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=737 + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR a=40 + OR f='uvwxyzabc' + OR b=311 + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=927 + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + } +} {5 6 8 20 31 32 40 46 50 53 57 58 67 72 83 84 98 scan 0 sort 0} +do_test where7-2.979.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=737 + OR (g='wvutsrq' AND f GLOB 'ijklm*') + OR (f GLOB '?ghij*' AND f GLOB 'fghi*') + OR a=40 + OR f='uvwxyzabc' + OR b=311 + OR (g='nmlkjih' AND f GLOB 'bcdef*') + OR (f GLOB '?hijk*' AND f GLOB 'ghij*') + OR b=927 + OR (d>=50.0 AND d<51.0 AND d NOT NULL) + } +} {5 6 8 20 31 32 40 46 50 53 57 58 67 72 83 84 98 scan 0 sort 0} +do_test where7-2.980.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE f='fghijklmn' + OR b=1078 + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + OR f='fghijklmn' + } +} {5 31 35 57 83 98 scan 0 sort 0} +do_test where7-2.980.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE f='fghijklmn' + OR b=1078 + OR (d>=35.0 AND d<36.0 AND d NOT NULL) + OR f='fghijklmn' + } +} {5 31 35 57 83 98 scan 0 sort 0} +do_test where7-2.981.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='xwvutsr' AND f GLOB 'ghijk*') + OR b=487 + OR f='tuvwxyzab' + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR b=971 + OR c=19019 + OR a=39 + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR b=550 + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=660 + } +} {6 12 19 38 39 45 48 50 55 56 57 60 64 71 90 97 scan 0 sort 0} +do_test where7-2.981.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='xwvutsr' AND f GLOB 'ghijk*') + OR b=487 + OR f='tuvwxyzab' + OR (g='onmlkji' AND f GLOB 'wxyza*') + OR b=971 + OR c=19019 + OR a=39 + OR (f GLOB '?nopq*' AND f GLOB 'mnop*') + OR b=550 + OR (g='kjihgfe' AND f GLOB 'tuvwx*') + OR b=660 + } +} {6 12 19 38 39 45 48 50 55 56 57 60 64 71 90 97 scan 0 sort 0} +do_test where7-2.982.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=80 + OR b=839 + } +} { scan 0 sort 0} +do_test where7-2.982.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=80 + OR b=839 + } +} { scan 0 sort 0} +do_test where7-2.983.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=363 + OR b=630 + OR b=935 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'defgh*') + OR f='yzabcdefg' + OR ((a BETWEEN 37 AND 39) AND a!=38) + } +} {20 24 29 33 37 39 50 76 85 scan 0 sort 0} +do_test where7-2.983.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=363 + OR b=630 + OR b=935 + OR (d>=20.0 AND d<21.0 AND d NOT NULL) + OR (g='srqponm' AND f GLOB 'defgh*') + OR f='yzabcdefg' + OR ((a BETWEEN 37 AND 39) AND a!=38) + } +} {20 24 29 33 37 39 50 76 85 scan 0 sort 0} +do_test where7-2.984.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR a=40 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR f='abcdefghi' + OR b=696 + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR b=682 + OR a=32 + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR b=671 + OR a=15 + } +} {15 16 26 32 34 36 40 52 61 62 78 86 97 scan 0 sort 0} +do_test where7-2.984.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=97.0 AND d<98.0 AND d NOT NULL) + OR a=40 + OR (d>=86.0 AND d<87.0 AND d NOT NULL) + OR f='abcdefghi' + OR b=696 + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR b=682 + OR a=32 + OR ((a BETWEEN 34 AND 36) AND a!=35) + OR b=671 + OR a=15 + } +} {15 16 26 32 34 36 40 52 61 62 78 86 97 scan 0 sort 0} +do_test where7-2.985.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (g='gfedcba' AND f GLOB 'lmnop*') + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR b=311 + } +} {7 33 59 85 89 scan 0 sort 0} +do_test where7-2.985.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (g='gfedcba' AND f GLOB 'lmnop*') + OR (f GLOB '?ijkl*' AND f GLOB 'hijk*') + OR b=311 + } +} {7 33 59 85 89 scan 0 sort 0} +do_test where7-2.986.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=96.0 AND d<97.0 AND d NOT NULL) + OR a=73 + OR b=729 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR a=32 + } +} {32 67 73 81 96 scan 0 sort 0} +do_test where7-2.986.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=96.0 AND d<97.0 AND d NOT NULL) + OR a=73 + OR b=729 + OR (d>=81.0 AND d<82.0 AND d NOT NULL) + OR (d>=67.0 AND d<68.0 AND d NOT NULL) + OR a=32 + } +} {32 67 73 81 96 scan 0 sort 0} +do_test where7-2.987.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 98 AND 100) AND a!=99) + OR b=110 + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR b=484 + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + } +} {10 23 38 40 44 82 98 100 scan 0 sort 0} +do_test where7-2.987.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 98 AND 100) AND a!=99) + OR b=110 + OR ((a BETWEEN 38 AND 40) AND a!=39) + OR (g='tsrqpon' AND f GLOB 'xyzab*') + OR b=484 + OR (d>=82.0 AND d<83.0 AND d NOT NULL) + } +} {10 23 38 40 44 82 98 100 scan 0 sort 0} +do_test where7-2.988.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=99.0 AND d<100.0 AND d NOT NULL) + OR b=135 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=209 + OR b=363 + OR c=27027 + OR b=1026 + OR c=6006 + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + } +} {16 17 18 19 33 46 66 73 79 80 81 99 scan 0 sort 0} +do_test where7-2.988.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=99.0 AND d<100.0 AND d NOT NULL) + OR b=135 + OR (d>=66.0 AND d<67.0 AND d NOT NULL) + OR b=209 + OR b=363 + OR c=27027 + OR b=1026 + OR c=6006 + OR (g='ponmlkj' AND f GLOB 'uvwxy*') + OR (d>=73.0 AND d<74.0 AND d NOT NULL) + } +} {16 17 18 19 33 46 66 73 79 80 81 99 scan 0 sort 0} +do_test where7-2.989.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=79.0 AND d<80.0 AND d NOT NULL) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR a=97 + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR b=674 + OR c=14014 + OR b=69 + } +} {18 20 22 24 39 40 41 42 45 58 79 97 scan 0 sort 0} +do_test where7-2.989.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=79.0 AND d<80.0 AND d NOT NULL) + OR ((a BETWEEN 18 AND 20) AND a!=19) + OR (g='qponmlk' AND f GLOB 'nopqr*') + OR a=97 + OR (d>=45.0 AND d<46.0 AND d NOT NULL) + OR ((a BETWEEN 22 AND 24) AND a!=23) + OR (g='mlkjihg' AND f GLOB 'ghijk*') + OR b=674 + OR c=14014 + OR b=69 + } +} {18 20 22 24 39 40 41 42 45 58 79 97 scan 0 sort 0} +do_test where7-2.990.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=297 + OR a=83 + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR ((a BETWEEN 16 AND 18) AND a!=17) + } +} {16 18 27 78 83 scan 0 sort 0} +do_test where7-2.990.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=297 + OR a=83 + OR (d>=78.0 AND d<79.0 AND d NOT NULL) + OR ((a BETWEEN 16 AND 18) AND a!=17) + } +} {16 18 27 78 83 scan 0 sort 0} +do_test where7-2.991.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=451 + OR ((a BETWEEN 11 AND 13) AND a!=12) + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=539 + OR a=26 + OR (g='srqponm' AND f GLOB 'efghi*') + OR b=465 + OR (g='jihgfed' AND f GLOB 'wxyza*') + } +} {11 13 26 30 41 49 74 scan 0 sort 0} +do_test where7-2.991.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=451 + OR ((a BETWEEN 11 AND 13) AND a!=12) + OR (g='tsrqpon' AND f GLOB 'abcde*') + OR b=539 + OR a=26 + OR (g='srqponm' AND f GLOB 'efghi*') + OR b=465 + OR (g='jihgfed' AND f GLOB 'wxyza*') + } +} {11 13 26 30 41 49 74 scan 0 sort 0} +do_test where7-2.992.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (d>=45.0 AND d<46.0 AND d NOT NULL) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + } +} {45 63 scan 0 sort 0} +do_test where7-2.992.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (d>=45.0 AND d<46.0 AND d NOT NULL) + OR (d>=63.0 AND d<64.0 AND d NOT NULL) + } +} {45 63 scan 0 sort 0} +do_test where7-2.993.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 16 AND 18) AND a!=17) + OR b=872 + OR c=31031 + } +} {16 18 91 92 93 scan 0 sort 0} +do_test where7-2.993.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 16 AND 18) AND a!=17) + OR b=872 + OR c=31031 + } +} {16 18 91 92 93 scan 0 sort 0} +do_test where7-2.994.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR a=13 + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR b=322 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR b=377 + OR f='cdefghijk' + OR b=286 + OR ((a BETWEEN 61 AND 63) AND a!=62) + } +} {1 2 13 17 26 27 28 33 35 43 53 54 61 63 69 79 80 95 scan 0 sort 0} +do_test where7-2.994.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE (f GLOB '?cdef*' AND f GLOB 'bcde*') + OR a=13 + OR (f GLOB '?stuv*' AND f GLOB 'rstu*') + OR b=322 + OR ((a BETWEEN 33 AND 35) AND a!=34) + OR b=377 + OR f='cdefghijk' + OR b=286 + OR ((a BETWEEN 61 AND 63) AND a!=62) + } +} {1 2 13 17 26 27 28 33 35 43 53 54 61 63 69 79 80 95 scan 0 sort 0} +do_test where7-2.995.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=41 + OR b=990 + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR b=605 + OR (g='srqponm' AND f GLOB 'cdefg*') + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR b=968 + OR a=66 + } +} {16 28 36 41 55 66 88 90 scan 0 sort 0} +do_test where7-2.995.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=41 + OR b=990 + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR b=605 + OR (g='srqponm' AND f GLOB 'cdefg*') + OR (d>=36.0 AND d<37.0 AND d NOT NULL) + OR (g='vutsrqp' AND f GLOB 'qrstu*') + OR b=968 + OR a=66 + } +} {16 28 36 41 55 66 88 90 scan 0 sort 0} +do_test where7-2.996.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1059 + OR (g='srqponm' AND f GLOB 'ghijk*') + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR (g='onmlkji' AND f GLOB 'abcde*') + OR ((a BETWEEN 39 AND 41) AND a!=40) + } +} {17 19 32 37 39 41 52 57 scan 0 sort 0} +do_test where7-2.996.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1059 + OR (g='srqponm' AND f GLOB 'ghijk*') + OR (g='utsrqpo' AND f GLOB 'tuvwx*') + OR (g='nmlkjih' AND f GLOB 'fghij*') + OR (d>=17.0 AND d<18.0 AND d NOT NULL) + OR (d>=37.0 AND d<38.0 AND d NOT NULL) + OR (g='onmlkji' AND f GLOB 'abcde*') + OR ((a BETWEEN 39 AND 41) AND a!=40) + } +} {17 19 32 37 39 41 52 57 scan 0 sort 0} +do_test where7-2.997.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE ((a BETWEEN 41 AND 43) AND a!=42) + OR f='nopqrstuv' + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR a=42 + OR b=729 + OR b=297 + OR a=77 + OR b=781 + OR ((a BETWEEN 36 AND 38) AND a!=37) + } +} {13 27 36 38 39 41 42 43 44 65 71 77 91 scan 0 sort 0} +do_test where7-2.997.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE ((a BETWEEN 41 AND 43) AND a!=42) + OR f='nopqrstuv' + OR (g='ponmlkj' AND f GLOB 'stuvw*') + OR a=42 + OR b=729 + OR b=297 + OR a=77 + OR b=781 + OR ((a BETWEEN 36 AND 38) AND a!=37) + } +} {13 27 36 38 39 41 42 43 44 65 71 77 91 scan 0 sort 0} +do_test where7-2.998.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE a=12 + OR f='qrstuvwxy' + OR a=47 + OR b=135 + OR a=25 + } +} {12 16 25 42 47 68 94 scan 0 sort 0} +do_test where7-2.998.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE a=12 + OR f='qrstuvwxy' + OR a=47 + OR b=135 + OR a=25 + } +} {12 16 25 42 47 68 94 scan 0 sort 0} +do_test where7-2.999.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=451 + OR b=660 + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR b=781 + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR b=198 + OR b=1023 + OR a=98 + OR d<0.0 + OR ((a BETWEEN 79 AND 81) AND a!=80) + } +} {18 41 50 60 71 74 79 81 93 98 scan 0 sort 0} +do_test where7-2.999.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=451 + OR b=660 + OR (g='onmlkji' AND f GLOB 'yzabc*') + OR b=781 + OR (g='jihgfed' AND f GLOB 'wxyza*') + OR b=198 + OR b=1023 + OR a=98 + OR d<0.0 + OR ((a BETWEEN 79 AND 81) AND a!=80) + } +} {18 41 50 60 71 74 79 81 93 98 scan 0 sort 0} +do_test where7-2.1000.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=685 + OR a=86 + OR c=17017 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR a=80 + OR b=773 + } +} {49 50 51 80 85 86 87 90 scan 0 sort 0} +do_test where7-2.1000.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=685 + OR a=86 + OR c=17017 + OR ((a BETWEEN 85 AND 87) AND a!=86) + OR (g='gfedcba' AND f GLOB 'mnopq*') + OR a=80 + OR b=773 + } +} {49 50 51 80 85 86 87 90 scan 0 sort 0} +do_test where7-2.1001.1 { + count_steps_sort { + SELECT a FROM t2 + WHERE b=1092 + OR a=23 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR d<0.0 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR a=91 + } +} {2 22 23 28 54 80 91 scan 0 sort 0} +do_test where7-2.1001.2 { + count_steps_sort { + SELECT a FROM t3 + WHERE b=1092 + OR a=23 + OR (f GLOB '?defg*' AND f GLOB 'cdef*') + OR d<0.0 + OR (d>=22.0 AND d<23.0 AND d NOT NULL) + OR a=91 + } +} {2 22 23 28 54 80 91 scan 0 sort 0} + +# test case for the performance regression fixed by +# check-in 28ba6255282b on 2010-10-21 02:05:06 +# +# The test case that follows is code from an actual +# application with identifiers change and unused columns +# removed. +# +do_execsql_test where7-3.1 { + CREATE TABLE t301 ( + c8 INTEGER PRIMARY KEY, + c6 INTEGER, + c4 INTEGER, + c7 INTEGER, + FOREIGN KEY (c4) REFERENCES series(c4) + ); + CREATE INDEX t301_c6 on t301(c6); + CREATE INDEX t301_c4 on t301(c4); + CREATE INDEX t301_c7 on t301(c7); + + CREATE TABLE t302 ( + c1 INTEGER PRIMARY KEY, + c8 INTEGER, + c5 INTEGER, + c3 INTEGER, + c2 INTEGER, + c4 INTEGER, + FOREIGN KEY (c8) REFERENCES t301(c8) + ); + CREATE INDEX t302_c3 on t302(c3); + CREATE INDEX t302_c8_c3 on t302(c8, c3); + CREATE INDEX t302_c5 on t302(c5); + + EXPLAIN QUERY PLAN + SELECT t302.c1 + FROM t302 JOIN t301 ON t302.c8 = +t301.c8 + WHERE t302.c2 = 19571 + AND t302.c3 > 1287603136 + AND (t301.c4 = 1407449685622784 + OR t301.c8 = 1407424651264000) + ORDER BY t302.c5 LIMIT 200; +} { + 0 0 1 {SEARCH TABLE t301 USING COVERING INDEX t301_c4 (c4=?)} + 0 0 1 {SEARCH TABLE t301 USING INTEGER PRIMARY KEY (rowid=?)} + 0 1 0 {SEARCH TABLE t302 USING INDEX t302_c8_c3 (c8=? AND c3>?)} + 0 0 0 {USE TEMP B-TREE FOR ORDER BY} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where8.test b/components/external/SQLite-3.8.1/test/where8.test new file mode 100644 index 0000000000000000000000000000000000000000..9127179292ab497304ff58237a5553fd4e7feef5 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where8.test @@ -0,0 +1,752 @@ +# 2008 December 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus +# is testing of where.c. More specifically, the focus is the optimization +# of WHERE clauses that feature the OR operator. +# +# $Id: where8.test,v 1.9 2009/07/31 06:14:52 danielk1977 Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# Test organization: +# +# where8-1.*: Tests to demonstrate simple cases work with a single table +# in the FROM clause. +# +# where8-2.*: Tests surrounding virtual tables and the OR optimization. +# +# where8-3.*: Tests with more than one table in the FROM clause. +# + +proc execsql_status {sql {db db}} { + set result [uplevel $db eval [list $sql]] + concat $result [db status step] [db status sort] +} + +proc execsql_status2 {sql {db db}} { + set ::sqlite_search_count 0 + set result [uplevel [list execsql_status $sql $db]] + concat $result $::sqlite_search_count +} + +do_test where8-1.1 { + execsql { + CREATE TABLE t1(a, b TEXT, c); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); + + INSERT INTO t1 VALUES(1, 'one', 'I'); + INSERT INTO t1 VALUES(2, 'two', 'II'); + INSERT INTO t1 VALUES(3, 'three', 'III'); + INSERT INTO t1 VALUES(4, 'four', 'IV'); + INSERT INTO t1 VALUES(5, 'five', 'V'); + INSERT INTO t1 VALUES(6, 'six', 'VI'); + INSERT INTO t1 VALUES(7, 'seven', 'VII'); + INSERT INTO t1 VALUES(8, 'eight', 'VIII'); + INSERT INTO t1 VALUES(9, 'nine', 'IX'); + INSERT INTO t1 VALUES(10, 'ten', 'X'); + } +} {} + +do_test where8-1.2 { + execsql_status2 { SELECT c FROM t1 WHERE a = 1 OR b = 'nine' } +} {I IX 0 0 6} + +do_test where8-1.3 { + execsql_status2 { SELECT c FROM t1 WHERE a > 8 OR b = 'two' } +} {IX X II 0 0 6} + +do_test where8-1.4 { + execsql_status2 { SELECT c FROM t1 WHERE a > 8 OR b GLOB 't*' } +} {IX X III II 0 0 9} + +do_test where8-1.5 { + execsql_status2 { SELECT c FROM t1 WHERE a > 8 OR b GLOB 'f*' } +} {IX X V IV 0 0 9} + +do_test where8-1.6 { + execsql_status { SELECT c FROM t1 WHERE a = 1 OR b = 'three' ORDER BY rowid } +} {I III 0 1} + +do_test where8-1.7 { + execsql_status { SELECT c FROM t1 WHERE a = 1 OR b = 'three' ORDER BY a } +} {I III 0 1} + +do_test where8-1.8 { + # 18 searches. 9 on the index cursor and 9 on the table cursor. + execsql_status2 { SELECT c FROM t1 WHERE a > 1 AND c LIKE 'I%' } +} {II III IV IX 0 0 18} + +do_test where8-1.9 { + execsql_status2 { SELECT c FROM t1 WHERE a >= 9 OR b <= 'eight' } +} {IX X VIII 0 0 6} + +do_test where8-1.10 { + execsql_status2 { + SELECT c FROM t1 WHERE (a >= 9 AND c != 'X') OR b <= 'eight' + } +} {IX VIII 0 0 6} + +do_test where8-1.11 { + execsql_status2 { + SELECT c FROM t1 WHERE (a >= 4 AND a <= 6) OR b = 'nine' + } +} {IV V VI IX 0 0 10} + +do_test where8-1.12.1 { + execsql_status2 { + SELECT c FROM t1 WHERE a IN(1, 2, 3) OR a = 5 + } +} {I II III V 0 0 14} + +do_test where8-1.12.2 { + execsql_status2 { + SELECT c FROM t1 WHERE +a IN(1, 2, 3) OR +a = 5 + } +} {I II III V 9 0 9} + +do_test where8-1.13 { + execsql_status2 { + SELECT c FROM t1 + WHERE a = 2 OR b = 'three' OR a = 4 OR b = 'five' OR a = 6 + ORDER BY rowid + } +} {II III IV V VI 0 1 18} +do_test where8-1.14 { + execsql_status2 { + SELECT c FROM t1 + WHERE + a = 2 OR b = 'three' OR a = 4 OR b = 'five' OR a = 6 OR + b = 'seven' OR a = 8 OR b = 'nine' OR a = 10 + ORDER BY rowid + } +} {II III IV V VI VII VIII IX X 0 1 33} + +do_test where8-1.15 { + execsql_status2 { + SELECT c FROM t1 WHERE + a BETWEEN 2 AND 4 OR b = 'nine' + ORDER BY rowid + } +} {II III IV IX 0 1 12} + + +#-------------------------------------------------------------------------- +# Tests where8-2.*: Virtual tables +# + +if 0 { +ifcapable vtab { + # Register the 'echo' module used for testing virtual tables. + # + register_echo_module [sqlite3_connection_pointer db] + + do_test where8-2.1 { + execsql { + CREATE VIRTUAL TABLE e1 USING echo(t1); + SELECT b FROM e1; + } + } {one two three four five six seven eight nine ten} + + do_test where8-2.2.1 { + set echo_module "" + execsql { + SELECT c FROM e1 WHERE a=1 OR b='three'; + } + } {I III} + do_test where8-2.2.2 { + set echo_module + } {TODO: What should this be?} +} +} + +#-------------------------------------------------------------------------- +# Tests where8-3.*: Cases with multiple tables in the FROM clause. +# +do_test where8-3.1 { + execsql { + CREATE TABLE t2(d, e, f); + CREATE INDEX i3 ON t2(d); + CREATE INDEX i4 ON t2(e); + + INSERT INTO t2 VALUES(1, NULL, 'I'); + INSERT INTO t2 VALUES(2, 'four', 'IV'); + INSERT INTO t2 VALUES(3, NULL, 'IX'); + INSERT INTO t2 VALUES(4, 'sixteen', 'XVI'); + INSERT INTO t2 VALUES(5, NULL, 'XXV'); + INSERT INTO t2 VALUES(6, 'thirtysix', 'XXXVI'); + INSERT INTO t2 VALUES(7, 'fortynine', 'XLIX'); + INSERT INTO t2 VALUES(8, 'sixtyeight', 'LXIV'); + INSERT INTO t2 VALUES(9, 'eightyone', 'LXXXIX'); + INSERT INTO t2 VALUES(10, NULL, 'C'); + } +} {} + +do_test where8-3.2 { + execsql_status { + SELECT a, d FROM t1, t2 WHERE b=e + } +} {4 2 9 0} + +do_test where8-3.3 { + execsql_status { + SELECT a, d FROM t1, t2 WHERE (a = 2 OR a = 3) AND d = 6 + } +} {2 6 3 6 0 0} + +do_test where8-3.4 { + execsql_status { + SELECT a, d FROM t1, t2 WHERE (a = 2 OR a = 3) AND d = a + } +} {2 2 3 3 0 0} + +do_test where8-3.5 { + execsql_status { + SELECT a, d FROM t1, t2 WHERE (a = 2 OR a = 3) AND (d = a OR e = 'sixteen') + ORDER BY +a, +d; + } +} {2 2 2 4 3 3 3 4 0 1} + +do_test where8-3.6 { + # The first part of the WHERE clause in this query, (a=2 OR a=3) is + # transformed into "a IN (2, 3)". This is why the sort is required. + # + execsql_status { + SELECT a, d + FROM t1, t2 + WHERE (a = 2 OR a = 3) AND (d = a OR e = 'sixteen') + ORDER BY t1.rowid + } +} {2 2 2 4 3 3 3 4 0 1} +do_test where8-3.7 { + execsql_status { + SELECT a, d + FROM t1, t2 + WHERE a = 2 AND (d = a OR e = 'sixteen') + ORDER BY t1.rowid + } +} {/2 2 2 4 0 [01]/} +do_test where8-3.8 { + execsql_status { + SELECT a, d + FROM t1, t2 + WHERE (a = 2 OR b = 'three') AND (d = a OR e = 'sixteen') + ORDER BY t1.rowid + } +} {2 2 2 4 3 3 3 4 0 1} + +do_test where8-3.9 { + # The "OR c = 'IX'" term forces a linear scan. + execsql_status { + SELECT a, d + FROM t1, t2 + WHERE (a = 2 OR b = 'three' OR c = 'IX') AND (d = a OR e = 'sixteen') + ORDER BY t1.rowid + } +} {2 2 2 4 3 3 3 4 9 9 9 4 9 0} + +do_test where8-3.10 { + execsql_status { + SELECT d FROM t2 WHERE e IS NULL OR e = 'four' + } +} {1 3 5 10 2 0 0} + +do_test where8-3.11 { + execsql_status { + SELECT a, d FROM t1, t2 WHERE (a=d OR b=e) AND a<5 ORDER BY a + } +} {1 1 2 2 3 3 4 2 4 4 0 0} +do_test where8-3.12 { + execsql_status { + SELECT a, d FROM t1, t2 WHERE (a=d OR b=e) AND +a<5 ORDER BY a + } +} {1 1 2 2 3 3 4 2 4 4 9 0} +do_test where8-3.13 { + execsql_status { + SELECT a, d FROM t1, t2 WHERE (a=d OR b=e) AND +a<5 + } +} {1 1 2 2 3 3 4 2 4 4 9 0} + +do_test where8-3.14 { + execsql_status { + SELECT c FROM t1 WHERE a > (SELECT d FROM t2 WHERE e = b) OR a = 5 + } +} {IV V 9 0} + +do_test where8-3.15 { + execsql_status { + SELECT c FROM t1, t2 WHERE a BETWEEN 1 AND 2 OR a = ( + SELECT sum(e IS NULL) FROM t2 AS inner WHERE t2.d>inner.d + ) + ORDER BY c + } +} {I I I I I I I I I I II II II II II II II II II II III III III III III 9 1} + + +do_test where8-3.21 { + execsql_status { + SELECT a, d FROM t1, (t2) WHERE (a=d OR b=e) AND a<5 ORDER BY a + } +} {1 1 2 2 3 3 4 2 4 4 0 0} +do_test where8-3.21.1 { + execsql_status { + SELECT a, d FROM t1, ((t2)) AS t3 WHERE (a=d OR b=e) AND a<5 ORDER BY a + } +} {1 1 2 2 3 3 4 2 4 4 0 0} +if {[permutation] != "no_optimization"} { +do_test where8-3.21.2 { + execsql_status { + SELECT a, d FROM t1, ((SELECT * FROM t2)) AS t3 WHERE (a=d OR b=e) AND a<5 ORDER BY a + } +} {1 1 2 2 3 3 4 2 4 4 0 0} +} +do_test where8-3.22 { + execsql_status { + SELECT a, d FROM ((((((t1))), (((t2)))))) + WHERE (a=d OR b=e) AND a<5 ORDER BY a + } +} {1 1 2 2 3 3 4 2 4 4 0 0} +if {[permutation] != "no_optimization"} { +do_test where8-3.23 { + execsql_status { + SELECT * FROM ((SELECT * FROM t2)) AS t3; + } +} {1 {} I 2 four IV 3 {} IX 4 sixteen XVI 5 {} XXV 6 thirtysix XXXVI 7 fortynine XLIX 8 sixtyeight LXIV 9 eightyone LXXXIX 10 {} C 9 0} +} + +#----------------------------------------------------------------------- +# The following tests - where8-4.* - verify that adding or removing +# indexes does not change the results returned by various queries. +# +do_test where8-4.1 { + execsql { + BEGIN; + CREATE TABLE t3(a INTEGER, b REAL, c TEXT); + CREATE TABLE t4(f INTEGER, g REAL, h TEXT); + INSERT INTO t3 VALUES('hills', NULL, 1415926535); + INSERT INTO t3 VALUES('and', 'of', NULL); + INSERT INTO t3 VALUES('have', 'towering', 53594.08128); + INSERT INTO t3 VALUES(NULL, 45.64856692, 'Not'); + INSERT INTO t3 VALUES('same', 5028841971, NULL); + INSERT INTO t3 VALUES('onlookers', 'in', 8214808651); + INSERT INTO t3 VALUES(346.0348610, 2643383279, NULL); + INSERT INTO t3 VALUES(1415926535, 'of', 'are'); + INSERT INTO t3 VALUES(NULL, 0.4811174502, 'snapshots'); + INSERT INTO t3 VALUES('over', 'the', 8628034825); + INSERT INTO t3 VALUES(8628034825, 66.59334461, 2847564.823); + INSERT INTO t3 VALUES('onlookers', 'same', 'and'); + INSERT INTO t3 VALUES(NULL, 'light', 6939937510); + INSERT INTO t3 VALUES('from', 'their', 'viewed'); + INSERT INTO t3 VALUES('from', 'Alpine', 'snapshots'); + INSERT INTO t3 VALUES('from', 'sometimes', 'unalike'); + INSERT INTO t3 VALUES(1339.360726, 'light', 'have'); + INSERT INTO t3 VALUES(6939937510, 3282306647, 'other'); + INSERT INTO t3 VALUES('paintings', 8628034825, 'all'); + INSERT INTO t3 VALUES('paintings', NULL, 'same'); + INSERT INTO t3 VALUES('Alpine', 378678316.5, 'unalike'); + INSERT INTO t3 VALUES('Alpine', NULL, 'same'); + INSERT INTO t3 VALUES(1339.360726, 2847564.823, 'over'); + INSERT INTO t3 VALUES('villages', 'their', 'have'); + INSERT INTO t3 VALUES('unalike', 'remarkably', 'in'); + INSERT INTO t3 VALUES('and', 8979323846, 'and'); + INSERT INTO t3 VALUES(NULL, 1415926535, 'an'); + INSERT INTO t3 VALUES(271.2019091, 8628034825, 0.4811174502); + INSERT INTO t3 VALUES('all', 3421170679, 'the'); + INSERT INTO t3 VALUES('Not', 'and', 1415926535); + INSERT INTO t3 VALUES('of', 'other', 'light'); + INSERT INTO t3 VALUES(NULL, 'towering', 'Not'); + INSERT INTO t3 VALUES(346.0348610, NULL, 'other'); + INSERT INTO t3 VALUES('Not', 378678316.5, NULL); + INSERT INTO t3 VALUES('snapshots', 8628034825, 'of'); + INSERT INTO t3 VALUES(3282306647, 271.2019091, 'and'); + INSERT INTO t3 VALUES(50.58223172, 378678316.5, 5028841971); + INSERT INTO t3 VALUES(50.58223172, 2643383279, 'snapshots'); + INSERT INTO t3 VALUES('writings', 8979323846, 8979323846); + INSERT INTO t3 VALUES('onlookers', 'his', 'in'); + INSERT INTO t3 VALUES('unalike', 8628034825, 1339.360726); + INSERT INTO t3 VALUES('of', 'Alpine', 'and'); + INSERT INTO t3 VALUES('onlookers', NULL, 'from'); + INSERT INTO t3 VALUES('writings', 'it', 1339.360726); + INSERT INTO t3 VALUES('it', 'and', 'villages'); + INSERT INTO t3 VALUES('an', 'the', 'villages'); + INSERT INTO t3 VALUES(8214808651, 8214808651, 'same'); + INSERT INTO t3 VALUES(346.0348610, 'light', 1415926535); + INSERT INTO t3 VALUES(NULL, 8979323846, 'and'); + INSERT INTO t3 VALUES(NULL, 'same', 1339.360726); + INSERT INTO t4 VALUES('his', 'from', 'an'); + INSERT INTO t4 VALUES('snapshots', 'or', NULL); + INSERT INTO t4 VALUES('Alpine', 'have', 'it'); + INSERT INTO t4 VALUES('have', 'peak', 'remarkably'); + INSERT INTO t4 VALUES('hills', NULL, 'Not'); + INSERT INTO t4 VALUES('same', 'from', 2643383279); + INSERT INTO t4 VALUES('have', 'angle', 8628034825); + INSERT INTO t4 VALUES('sometimes', 'it', 2847564.823); + INSERT INTO t4 VALUES(0938446095, 'peak', 'of'); + INSERT INTO t4 VALUES(8628034825, 'and', 'same'); + INSERT INTO t4 VALUES('and', 271.2019091, 'their'); + INSERT INTO t4 VALUES('the', 'of', 'remarkably'); + INSERT INTO t4 VALUES('and', 3421170679, 1415926535); + INSERT INTO t4 VALUES('and', 'in', 'all'); + INSERT INTO t4 VALUES(378678316.5, 0.4811174502, 'snapshots'); + INSERT INTO t4 VALUES('it', 'are', 'have'); + INSERT INTO t4 VALUES('angle', 'snapshots', 378678316.5); + INSERT INTO t4 VALUES('from', 1415926535, 8628034825); + INSERT INTO t4 VALUES('snapshots', 'angle', 'have'); + INSERT INTO t4 VALUES(3421170679, 0938446095, 'Not'); + INSERT INTO t4 VALUES('peak', NULL, 0.4811174502); + INSERT INTO t4 VALUES('same', 'have', 'Alpine'); + INSERT INTO t4 VALUES(271.2019091, 66.59334461, 0938446095); + INSERT INTO t4 VALUES(8979323846, 'his', 'an'); + INSERT INTO t4 VALUES(NULL, 'and', 3282306647); + INSERT INTO t4 VALUES('remarkably', NULL, 'Not'); + INSERT INTO t4 VALUES('villages', 4543.266482, 'his'); + INSERT INTO t4 VALUES(2643383279, 'paintings', 'onlookers'); + INSERT INTO t4 VALUES(1339.360726, 'of', 'the'); + INSERT INTO t4 VALUES('peak', 'other', 'peak'); + INSERT INTO t4 VALUES('it', 'or', 8979323846); + INSERT INTO t4 VALUES('onlookers', 'Not', 'towering'); + INSERT INTO t4 VALUES(NULL, 'peak', 'Not'); + INSERT INTO t4 VALUES('of', 'have', 6939937510); + INSERT INTO t4 VALUES('light', 'hills', 0.4811174502); + INSERT INTO t4 VALUES(5028841971, 'Not', 'it'); + INSERT INTO t4 VALUES('and', 'Not', NULL); + INSERT INTO t4 VALUES(346.0348610, 'villages', NULL); + INSERT INTO t4 VALUES(8979323846, NULL, 6939937510); + INSERT INTO t4 VALUES('an', 'light', 'peak'); + INSERT INTO t4 VALUES(5028841971, 6939937510, 'light'); + INSERT INTO t4 VALUES('sometimes', 'peak', 'peak'); + INSERT INTO t4 VALUES(378678316.5, 5028841971, 'an'); + INSERT INTO t4 VALUES(378678316.5, 'his', 'Alpine'); + INSERT INTO t4 VALUES('from', 'of', 'all'); + INSERT INTO t4 VALUES(0938446095, 'same', NULL); + INSERT INTO t4 VALUES(0938446095, 'Alpine', NULL); + INSERT INTO t4 VALUES('his', 'of', 378678316.5); + INSERT INTO t4 VALUES(271.2019091, 'viewed', 3282306647); + INSERT INTO t4 VALUES('hills', 'all', 'peak'); + CREATE TABLE t5(s); + INSERT INTO t5 VALUES('tab-t5'); + CREATE TABLE t6(t); + INSERT INTO t6 VALUES(123456); + COMMIT; + } +} {} + +catch {unset results} +catch {unset A} +catch {unset B} + +set A 2 +foreach idxsql { + { + /* No indexes */ + } { + CREATE INDEX i5 ON t3(a); + } { + CREATE INDEX i5 ON t3(a, b); + CREATE INDEX i6 ON t4(f); + } { + CREATE UNIQUE INDEX i5 ON t3(a, b); + CREATE INDEX i7 ON t3(c); + CREATE INDEX i6 ON t4(f); + CREATE INDEX i8 ON t4(h); + } { + CREATE INDEX i5 ON t3(a, b, c); + CREATE INDEX i6 ON t4(f, g, h); + CREATE INDEX i7 ON t3(c, b, a); + CREATE INDEX i8 ON t4(h, g, f); + } +} { + + execsql { + DROP INDEX IF EXISTS i5; + DROP INDEX IF EXISTS i6; + DROP INDEX IF EXISTS i7; + DROP INDEX IF EXISTS i8; + } + execsql $idxsql + + foreach {B sql} { + 1 { SELECT * FROM t3 WHERE c LIKE b } + 2 { SELECT * FROM t3 WHERE c||'' LIKE 'the%' } + 3 { SELECT * FROM t3 WHERE rowid LIKE '12%' } + 4 { SELECT * FROM t3 WHERE +c LIKE 'the%' } + 5 { SELECT * FROM t3 WHERE c LIKE 'the%' } + 6 { SELECT * FROM t3 WHERE c GLOB '*llo' } + + 7 { SELECT * FROM t3 WHERE a = 'angle' } + 8 { SELECT * FROM t3 WHERE a = 'it' OR b = 6939937510 } + 9 { SELECT * FROM t3, t4 WHERE a = 'painting' OR a = 'are' OR a = f } +10 { SELECT * FROM t3, t4 WHERE a = 'all' OR a = 'and' OR a = h } +11 { SELECT * FROM t3, t4 WHERE a < 'of' OR b > 346 AND c IS NULL } +12 { SELECT * FROM t3, t4 WHERE 'the' > a OR b > 'have' AND c = 1415926535 } + +13 { SELECT * FROM t3 WHERE a BETWEEN 'one' AND 'two' OR a = 3421170679 } +14 { SELECT * FROM t3 WHERE a BETWEEN 'one' AND 'two' OR a IS NULL } +15 { SELECT * FROM t3 WHERE c > 'one' OR c >= 'one' OR c LIKE 'one%' } +16 { SELECT * FROM t3 WHERE c > 'one' OR c = c OR c = a } +17 { SELECT * FROM t3 WHERE c IS NULL OR a >= 'peak' } +18 { SELECT * FROM t3 WHERE c IN ('other', 'all', 'snapshots') OR a>1 } +19 { SELECT * FROM t3 WHERE c IN ('other', 'all', 'snapshots') AND a>1 } +20 { SELECT * FROM t3 WHERE c IS NULL AND a>'one' } +21 { SELECT * FROM t3 WHERE c IS NULL OR a>'one' } +22 { SELECT * FROM t3 WHERE b = b AND a > 'are' } +23 { SELECT * FROM t3 WHERE c <= b OR b < 'snapshots' } +24 { SELECT * FROM t3 WHERE 'onlookers' >= c AND a <= b OR b = 'angle' } +25 { SELECT * FROM t3 WHERE b = 'from' } +26 { SELECT * FROM t3 WHERE b = 4543.266482 } +27 { SELECT * FROM t3 WHERE c < 3282306647 } +28 { SELECT * FROM t3 WHERE c IS NULL AND b >= c } +29 { SELECT * FROM t3 WHERE b > 0.4811174502 AND c = 'other' AND 'viewed' > a } +30 { SELECT * FROM t3 WHERE c = 'peak' } +31 { SELECT * FROM t3 WHERE c < 53594.08128 OR c <= b } +32 { SELECT * FROM t3 WHERE 'writings' <= b } +33 { SELECT * FROM t3 WHERE 2643383279 = b OR c < b AND b <= 3282306647 } +34 { SELECT * FROM t3 WHERE a IS NULL } +35 { SELECT * FROM t3 WHERE 'writings' = a OR b = 378678316.5 } +36 { SELECT * FROM t3 WHERE 'and' >= c } +37 { SELECT * FROM t3 WHERE c < 'from' } +38 { SELECT * FROM t3 WHERE 'his' < c OR b < b } +39 { SELECT * FROM t3 WHERE 53594.08128 = b AND c >= b } +40 { SELECT * FROM t3 WHERE 'unalike' < c AND 'are' >= c AND a <= b } +41 { SELECT * FROM t3 WHERE b >= 4543.266482 OR 'Alpine' > a OR 271.2019091 <= a } +42 { SELECT * FROM t3 WHERE b = c } +43 { SELECT * FROM t3 WHERE c > a AND b < 'all' } +44 { SELECT * FROM t3 WHERE c BETWEEN 'hills' AND 'snapshots' AND c <= 'the' OR c = a } +45 { SELECT * FROM t3 WHERE b > c AND c >= 'hills' } +46 { SELECT * FROM t3 WHERE b > 'or' OR a <= 'hills' OR c IS NULL } +47 { SELECT * FROM t3 WHERE c > b OR b BETWEEN 1339.360726 AND 'onlookers' OR 1415926535 >= b } +48 { SELECT * FROM t3 WHERE a IS NULL } +49 { SELECT * FROM t3 WHERE a > 'other' } +50 { SELECT * FROM t3 WHERE 'the' <= c AND a <= c } +51 { SELECT * FROM t3 WHERE 346.0348610 = a AND c = b } +52 { SELECT * FROM t3 WHERE c BETWEEN 50.58223172 AND 'same' AND a < b } +53 { SELECT * FROM t3 WHERE 'Alpine' <= b AND c >= 'angle' OR b <= 271.2019091 } +54 { SELECT * FROM t3 WHERE a < a AND 1415926535 > b } +55 { SELECT * FROM t3 WHERE c > a AND 'have' >= c } +56 { SELECT * FROM t3 WHERE b <= b AND c > b } +57 { SELECT * FROM t3 WHERE a IS NULL AND c <= c } +58 { SELECT * FROM t3 WHERE b < c OR b = c } +59 { SELECT * FROM t3 WHERE c < b AND b >= 'it' } +60 { SELECT * FROM t3 WHERE a = b AND a <= b OR b >= a } +61 { SELECT * FROM t3 WHERE b = c } +62 { SELECT * FROM t3 WHERE c BETWEEN 'the' AND 271.2019091 OR c <= 3282306647 AND c >= b } +63 { SELECT * FROM t3 WHERE c >= c AND c < 'writings' } +64 { SELECT * FROM t3 WHERE c <= 3282306647 AND b > a OR 'unalike' <= a } +65 { SELECT * FROM t3 WHERE a > c } +66 { SELECT * FROM t3 WHERE c = 'it' OR b >= b } +67 { SELECT * FROM t3 WHERE c = a OR b < c } +68 { SELECT * FROM t3 WHERE b > a } +69 { SELECT * FROM t3 WHERE a < b OR a > 4543.266482 OR 'same' = b } +70 { SELECT * FROM t3 WHERE c < c OR b <= c OR a <= b } +71 { SELECT * FROM t3 WHERE c > a } +72 { SELECT * FROM t3 WHERE c > b } +73 { SELECT * FROM t3 WHERE b <= a } +74 { SELECT * FROM t3 WHERE 3282306647 < b AND a >= 'or' OR a >= 378678316.5 } +75 { SELECT * FROM t3 WHERE 50.58223172 <= c OR c = c AND b < b } +76 { SELECT * FROM t3 WHERE 'and' < b OR b < c OR c > 1339.360726 } +77 { SELECT * FROM t3 WHERE b <= c } +78 { SELECT * FROM t3 WHERE 'in' <= c } +79 { SELECT * FROM t3 WHERE c <= b AND a > a AND c < b } +80 { SELECT * FROM t3 WHERE 'over' < b } +81 { SELECT * FROM t3 WHERE b >= b OR b < c OR a < b } +82 { SELECT * FROM t3 WHERE 'towering' <= b OR 'towering' = a AND c > b } +83 { SELECT * FROM t3 WHERE 'peak' = a OR b BETWEEN 2643383279 AND 'the' } +84 { SELECT * FROM t3 WHERE 'an' < c AND c > 'the' AND c IS NULL } +85 { SELECT * FROM t3 WHERE a <= 'sometimes' AND a BETWEEN 'unalike' AND 1339.360726 } +86 { SELECT * FROM t3 WHERE 1339.360726 < c AND c IS NULL } +87 { SELECT * FROM t3 WHERE b > 'the' } +88 { SELECT * FROM t3 WHERE 'and' = a } +89 { SELECT * FROM t3 WHERE b >= b } +90 { SELECT * FROM t3 WHERE b >= 8979323846 } +91 { SELECT * FROM t3 WHERE c <= a } +92 { SELECT * FROM t3 WHERE a BETWEEN 'have' AND 'light' OR a > b OR a >= 378678316.5 } +93 { SELECT * FROM t3 WHERE c > 3282306647 } +94 { SELECT * FROM t3 WHERE b > c } +95 { SELECT * FROM t3 WHERE b >= a AND 'villages' > a AND b >= c } +96 { SELECT * FROM t3 WHERE 'angle' > a } +97 { SELECT * FROM t3 WHERE 'paintings' >= a } +98 { SELECT * FROM t3 WHERE 'or' >= c } +99 { SELECT * FROM t3 WHERE c < b } + + +101 { SELECT * FROM t3, t4 WHERE f < 'sometimes' OR 'over' <= g AND h < 1415926535 } +102 { SELECT * FROM t3, t4 WHERE h >= 'from' AND h < 6939937510 OR g > h } +103 { SELECT * FROM t3, t4 WHERE c <= h AND g = h AND c >= 'all' } +104 { SELECT * FROM t3, t4 WHERE c = a } +105 { SELECT * FROM t3, t4 WHERE 'of' >= h } +106 { SELECT * FROM t3, t4 WHERE f >= b AND a < g AND h < 'and' } +107 { SELECT * FROM t3, t4 WHERE f <= 8628034825 AND 0938446095 >= b } +108 { SELECT * FROM t3, t4 WHERE a < 'the' } +109 { SELECT * FROM t3, t4 WHERE f = 'sometimes' OR b < 'of' } +110 { SELECT * FROM t3, t4 WHERE c IS NULL } +111 { SELECT * FROM t3, t4 WHERE 'have' = b OR g <= 346.0348610 } +112 { SELECT * FROM t3, t4 WHERE f > b AND b <= h } +113 { SELECT * FROM t3, t4 WHERE f > c OR 'the' = a OR 50.58223172 = a } +114 { SELECT * FROM t3, t4 WHERE 2643383279 <= a AND c = a } +115 { SELECT * FROM t3, t4 WHERE h >= b AND 'it' <= b } +116 { SELECT * FROM t3, t4 WHERE g BETWEEN 'from' AND 'peak' } +117 { SELECT * FROM t3, t4 WHERE 'their' > a AND g > b AND f <= c } +118 { SELECT * FROM t3, t4 WHERE h = 5028841971 AND 'unalike' <= f } +119 { SELECT * FROM t3, t4 WHERE c IS NULL AND a = 3282306647 OR a <= 'Alpine' } +120 { SELECT * FROM t3, t4 WHERE 'sometimes' <= f OR 8214808651 >= a AND b <= 53594.08128 } +121 { SELECT * FROM t3, t4 WHERE 6939937510 <= f OR c < f OR 'sometimes' = c } +122 { SELECT * FROM t3, t4 WHERE b < 'onlookers' AND 'paintings' = g AND c <= h } +123 { SELECT * FROM t3, t4 WHERE a BETWEEN 'all' AND 'from' OR c > 346.0348610 } +124 { SELECT * FROM t3, t4 WHERE 'from' <= b OR a BETWEEN 53594.08128 AND 'their' AND c > a } +125 { SELECT * FROM t3, t4 WHERE h = 2643383279 } +126 { SELECT * FROM t3, t4 WHERE a <= 'the' } +127 { SELECT * FROM t3, t4 WHERE h <= c } +128 { SELECT * FROM t3, t4 WHERE g <= 346.0348610 AND 66.59334461 >= f AND f <= f } +129 { SELECT * FROM t3, t4 WHERE g >= c OR 'in' < b OR b > g } +130 { SELECT * FROM t3, t4 WHERE 'over' > g AND b BETWEEN 'unalike' AND 'remarkably' } +131 { SELECT * FROM t3, t4 WHERE h <= 2847564.823 } +132 { SELECT * FROM t3, t4 WHERE h <= 'remarkably' AND 4543.266482 > h } +133 { SELECT * FROM t3, t4 WHERE a >= c AND 'it' > g AND c < c } +134 { SELECT * FROM t3, t4 WHERE h <= 66.59334461 AND b > 3421170679 } +135 { SELECT * FROM t3, t4 WHERE h < 'are' OR f BETWEEN 0938446095 AND 'are' OR b = b } +136 { SELECT * FROM t3, t4 WHERE h = a OR 66.59334461 <= f } +137 { SELECT * FROM t3, t4 WHERE f > 'of' OR h <= h OR a = f } +138 { SELECT * FROM t3, t4 WHERE 'other' >= g } +139 { SELECT * FROM t3, t4 WHERE b <= 3421170679 } +140 { SELECT * FROM t3, t4 WHERE 'all' = f AND 4543.266482 = b OR f BETWEEN 'and' AND 'angle' } +141 { SELECT * FROM t3, t4 WHERE 'light' = f OR h BETWEEN 'remarkably' AND 1415926535 } +142 { SELECT * FROM t3, t4 WHERE 'hills' = f OR 'the' >= f } +143 { SELECT * FROM t3, t4 WHERE a > 346.0348610 } +144 { SELECT * FROM t3, t4 WHERE 5028841971 = h } +145 { SELECT * FROM t3, t4 WHERE b >= c AND 'the' >= g OR 45.64856692 <= g } +146 { SELECT * FROM t3, t4 WHERE c < 5028841971 } +147 { SELECT * FROM t3, t4 WHERE a > a } +148 { SELECT * FROM t3, t4 WHERE c = 'snapshots' } +149 { SELECT * FROM t3, t4 WHERE h > 1339.360726 AND 'and' > c } +150 { SELECT * FROM t3, t4 WHERE 'and' > g OR 'sometimes' = c } +151 { SELECT * FROM t3, t4 WHERE g >= 'the' AND b >= 'onlookers' } +152 { SELECT * FROM t3, t4 WHERE h BETWEEN 'other' AND 2643383279 } +153 { SELECT * FROM t3, t4 WHERE 'it' = b } +154 { SELECT * FROM t3, t4 WHERE f = c OR c BETWEEN 'and' AND 0.4811174502 } +155 { SELECT * FROM t3, t4 WHERE b <= 'sometimes' OR c <= 0938446095 } +156 { SELECT * FROM t3, t4 WHERE 'and' <= b } +157 { SELECT * FROM t3, t4 WHERE g > a AND f = 'the' AND b < a } +158 { SELECT * FROM t3, t4 WHERE a < 'an' } +159 { SELECT * FROM t3, t4 WHERE a BETWEEN 'his' AND 'same' OR 8628034825 > f } +160 { SELECT * FROM t3, t4 WHERE b = 'peak' } +161 { SELECT * FROM t3, t4 WHERE f IS NULL AND a >= h } +162 { SELECT * FROM t3, t4 WHERE a IS NULL OR 2643383279 = c } +163 { SELECT * FROM t3, t4 WHERE b >= 5028841971 AND f < c AND a IS NULL } +164 { SELECT * FROM t3, t4 WHERE a >= g } +165 { SELECT * FROM t3, t4 WHERE c IS NULL } +166 { SELECT * FROM t3, t4 WHERE h >= h } +167 { SELECT * FROM t3, t4 WHERE 'over' <= h } +168 { SELECT * FROM t3, t4 WHERE b < 4543.266482 OR b = 2643383279 OR 8628034825 < b } +169 { SELECT * FROM t3, t4 WHERE g >= 6939937510 } +170 { SELECT * FROM t3, t4 WHERE 'or' < a OR b < g } +171 { SELECT * FROM t3, t4 WHERE h < 'hills' OR 'and' > g } +172 { SELECT * FROM t3, t4 WHERE 'from' > f OR f <= f } +173 { SELECT * FROM t3, t4 WHERE 'viewed' > b AND f < c } +174 { SELECT * FROM t3, t4 WHERE 'of' <= a } +175 { SELECT * FROM t3, t4 WHERE f > 0938446095 } +176 { SELECT * FROM t3, t4 WHERE a = g } +177 { SELECT * FROM t3, t4 WHERE g >= b AND f BETWEEN 'peak' AND 'and' } +178 { SELECT * FROM t3, t4 WHERE g = a AND 'it' > f } +179 { SELECT * FROM t3, t4 WHERE a <= b OR 'from' > f } +180 { SELECT * FROM t3, t4 WHERE f < 'and' } +181 { SELECT * FROM t3, t4 WHERE 6939937510 < b OR 'sometimes' < h } +182 { SELECT * FROM t3, t4 WHERE f > g AND f < 'peak' } +183 { SELECT * FROM t3, t4 WHERE a <= 53594.08128 AND c <= f AND f >= c } +184 { SELECT * FROM t3, t4 WHERE f = c OR 'it' > b OR g BETWEEN 'the' AND 'all' } +185 { SELECT * FROM t3, t4 WHERE c <= g OR a = h } +186 { SELECT * FROM t3, t4 WHERE 'same' = b OR c >= 2643383279 } +187 { SELECT * FROM t3, t4 WHERE h <= g OR c > 66.59334461 OR a <= f } +188 { SELECT * FROM t3, t4 WHERE b < c AND f = 'writings' } +189 { SELECT * FROM t3, t4 WHERE b < a } +190 { SELECT * FROM t3, t4 WHERE c >= f OR c = 'and' } +191 { SELECT * FROM t3, t4 WHERE f >= 'peak' AND g > f AND h > g } +192 { SELECT * FROM t3, t4 WHERE a >= 8979323846 AND 'same' > b OR c = 'and' } +193 { SELECT * FROM t3, t4 WHERE c >= g OR 'writings' >= c AND b = 'all' } +194 { SELECT * FROM t3, t4 WHERE 'remarkably' < g } +195 { SELECT * FROM t3, t4 WHERE a BETWEEN 'or' AND 'paintings' AND g <= f } +196 { SELECT * FROM t3, t4 WHERE 0938446095 > b OR g <= a OR h > b } +197 { SELECT * FROM t3, t4 WHERE g = 2643383279 AND f = g } +198 { SELECT * FROM t3, t4 WHERE g < 8979323846 } +199 { SELECT * FROM t3, t4 WHERE 'are' <= b } +200 { SELECT * FROM t3, t4 WHERE (a=1415926535 AND f=8628034825) + OR (a=6939937510 AND f=2643383279) } +201 { SELECT * FROM t3, t4, t5, t6 + WHERE (a=1415926535 AND f=8628034825 AND s!='hello' AND t!=5) + OR (a=6939937510 AND f=2643383279 AND s='tab-t5' AND t=123456) } +202 { SELECT * FROM t3, t4, t5, t6 + WHERE (a=1415926535 AND f=8628034825 AND s!='hello' AND t==5) + OR (a=6939937510 AND f=2643383279 AND s='tab-t5' AND t!=123456) } + + } { + do_test where8-4.$A.$B.1 { + unset -nocomplain R + set R [execsql $sql] + if {![info exists results($B)]} { + set results($B) $R + } + list + } {} + + do_test where8-4.$A.$B.2 { lsort $R } [lsort $results($B)] + } + incr A +} +catch {unset results} +catch {unset A} +catch {unset B} + +# At one point the following tests provoked an invalid write error (writing +# to memory that had already been freed). It was not possible to demonstrate +# that this bug could cause a query to return bad data. +# +do_test where8-5.1 { + db close + sqlite3 db test.db + sqlite3_db_config_lookaside db 0 0 0 + execsql { + CREATE TABLE tA( + a, b, c, d, e, f, g, h, + i, j, k, l, m, n, o, p + ); + } + execsql { + SELECT * FROM tA WHERE + a=1 AND b=2 AND c=3 AND d=4 AND e=5 AND f=6 AND g=7 AND h=8 AND + i=1 AND j=2 AND k=3 AND l=4 AND m=5 AND n=6 AND o=7 AND + (p = 1 OR p = 2 OR p = 3) + } +} {} +do_test where8-5.2 { + execsql { + SELECT * FROM tA WHERE + a=1 AND b=2 AND c=3 AND d=4 AND e=5 AND f=6 AND g=7 AND h=8 AND + i=1 AND j=2 AND k=3 AND l=4 AND m=5 AND + (p = 1 OR p = 2 OR p = 3) AND n=6 AND o=7 + } +} {} +do_test where8-5.3 { + execsql { + INSERT INTO tA VALUES(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8); + CREATE UNIQUE INDEX tAI ON tA(p); + CREATE TABLE tB(x); + INSERT INTO tB VALUES('x'); + } + execsql { + SELECT a, x FROM tA LEFT JOIN tB ON ( + a=1 AND b=2 AND c=3 AND d=4 AND e=5 AND f=6 AND g=7 AND h=8 AND + i=1 AND j=2 AND k=3 AND l=4 AND m=5 AND n=6 AND o=7 AND + (p = 1 OR p = 2 OR p = 3) + ) + } +} {1 {}} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where8m.test b/components/external/SQLite-3.8.1/test/where8m.test new file mode 100644 index 0000000000000000000000000000000000000000..4fce3db7c3bc6de78516ecb4b74e9d4500199c7e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where8m.test @@ -0,0 +1,57 @@ +# 2008 December 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The focus +# is testing of where.c. More specifically, the focus is the optimization +# of WHERE clauses that feature the OR operator. +# +# $Id: where8m.test,v 1.3 2009/06/05 17:09:12 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +source $testdir/malloc_common.tcl + +do_malloc_test where8m-1 -sqlprep { + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); +} -sqlbody { + SELECT c FROM t1 + WHERE + a = 2 OR b = 'three' OR a = 4 OR b = 'five' OR a = 6 OR + b = 'seven' OR a = 8 OR b = 'nine' OR a = 10 + ORDER BY rowid; + + SELECT c FROM t1 WHERE + a = 1 OR a = 2 OR a = 3 OR a = 4 OR a = 5 OR a = 6; + + SELECT c FROM t1 WHERE + a BETWEEN 1 AND 3 AND b < 5 AND b > 2 AND c = 4; +} + +do_malloc_test where8m-2 -tclprep { + db eval { + BEGIN; + CREATE TABLE t1(a, b, c); + CREATE INDEX i1 ON t1(a); + CREATE INDEX i2 ON t1(b); + } + for {set i 0} {$i < 1000} {incr i} { + set ii [expr $i*$i] + set iii [expr $i*$i] + db eval { INSERT INTO t1 VALUES($i, $ii, $iii) } + } + db eval COMMIT +} -sqlbody { + SELECT count(*) FROM t1 WHERE a BETWEEN 5 AND 995 OR b BETWEEN 5 AND 900000; +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/where9.test b/components/external/SQLite-3.8.1/test/where9.test new file mode 100644 index 0000000000000000000000000000000000000000..1c32ff82f7b9f8e25eee2cd2e43919da2c89b598 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/where9.test @@ -0,0 +1,983 @@ +# 2008 December 30 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the multi-index OR clause optimizer. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !or_opt||!compound { + finish_test + return +} + +# Evaluate SQL. Return the result set followed by the +# and the number of full-scan steps. +# +proc count_steps {sql} { + set r [db eval $sql] + lappend r scan [db status step] sort [db status sort] +} + + +# Construct test data. +# +do_test where9-1.1 { + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY,b,c,d,e,f,g); + INSERT INTO t1 VALUES(1,11,1001,1.001,100.1,'bcdefghij','yxwvuts'); + INSERT INTO t1 VALUES(2,22,1001,2.002,100.1,'cdefghijk','yxwvuts'); + INSERT INTO t1 VALUES(3,33,1001,3.003,100.1,'defghijkl','xwvutsr'); + INSERT INTO t1 VALUES(4,44,2002,4.004,200.2,'efghijklm','xwvutsr'); + INSERT INTO t1 VALUES(5,55,2002,5.005,200.2,'fghijklmn','xwvutsr'); + INSERT INTO t1 VALUES(6,66,2002,6.006,200.2,'ghijklmno','xwvutsr'); + INSERT INTO t1 VALUES(7,77,3003,7.007,300.3,'hijklmnop','xwvutsr'); + INSERT INTO t1 VALUES(8,88,3003,8.008,300.3,'ijklmnopq','wvutsrq'); + INSERT INTO t1 VALUES(9,99,3003,9.009,300.3,'jklmnopqr','wvutsrq'); + INSERT INTO t1 VALUES(10,110,4004,10.01,400.4,'klmnopqrs','wvutsrq'); + INSERT INTO t1 VALUES(11,121,4004,11.011,400.4,'lmnopqrst','wvutsrq'); + INSERT INTO t1 VALUES(12,132,4004,12.012,400.4,'mnopqrstu','wvutsrq'); + INSERT INTO t1 VALUES(13,143,5005,13.013,500.5,'nopqrstuv','vutsrqp'); + INSERT INTO t1 VALUES(14,154,5005,14.014,500.5,'opqrstuvw','vutsrqp'); + INSERT INTO t1 VALUES(15,165,5005,15.015,500.5,'pqrstuvwx','vutsrqp'); + INSERT INTO t1 VALUES(16,176,6006,16.016,600.6,'qrstuvwxy','vutsrqp'); + INSERT INTO t1 VALUES(17,187,6006,17.017,600.6,'rstuvwxyz','vutsrqp'); + INSERT INTO t1 VALUES(18,198,6006,18.018,600.6,'stuvwxyza','utsrqpo'); + INSERT INTO t1 VALUES(19,209,7007,19.019,700.7,'tuvwxyzab','utsrqpo'); + INSERT INTO t1 VALUES(20,220,7007,20.02,700.7,'uvwxyzabc','utsrqpo'); + INSERT INTO t1 VALUES(21,231,7007,21.021,700.7,'vwxyzabcd','utsrqpo'); + INSERT INTO t1 VALUES(22,242,8008,22.022,800.8,'wxyzabcde','utsrqpo'); + INSERT INTO t1 VALUES(23,253,8008,23.023,800.8,'xyzabcdef','tsrqpon'); + INSERT INTO t1 VALUES(24,264,8008,24.024,800.8,'yzabcdefg','tsrqpon'); + INSERT INTO t1 VALUES(25,275,9009,25.025,900.9,'zabcdefgh','tsrqpon'); + INSERT INTO t1 VALUES(26,286,9009,26.026,900.9,'abcdefghi','tsrqpon'); + INSERT INTO t1 VALUES(27,297,9009,27.027,900.9,'bcdefghij','tsrqpon'); + INSERT INTO t1 VALUES(28,308,10010,28.028,1001.0,'cdefghijk','srqponm'); + INSERT INTO t1 VALUES(29,319,10010,29.029,1001.0,'defghijkl','srqponm'); + INSERT INTO t1 VALUES(30,330,10010,30.03,1001.0,'efghijklm','srqponm'); + INSERT INTO t1 VALUES(31,341,11011,31.031,1101.1,'fghijklmn','srqponm'); + INSERT INTO t1 VALUES(32,352,11011,32.032,1101.1,'ghijklmno','srqponm'); + INSERT INTO t1 VALUES(33,363,11011,33.033,1101.1,'hijklmnop','rqponml'); + INSERT INTO t1 VALUES(34,374,12012,34.034,1201.2,'ijklmnopq','rqponml'); + INSERT INTO t1 VALUES(35,385,12012,35.035,1201.2,'jklmnopqr','rqponml'); + INSERT INTO t1 VALUES(36,396,12012,36.036,1201.2,'klmnopqrs','rqponml'); + INSERT INTO t1 VALUES(37,407,13013,37.037,1301.3,'lmnopqrst','rqponml'); + INSERT INTO t1 VALUES(38,418,13013,38.038,1301.3,'mnopqrstu','qponmlk'); + INSERT INTO t1 VALUES(39,429,13013,39.039,1301.3,'nopqrstuv','qponmlk'); + INSERT INTO t1 VALUES(40,440,14014,40.04,1401.4,'opqrstuvw','qponmlk'); + INSERT INTO t1 VALUES(41,451,14014,41.041,1401.4,'pqrstuvwx','qponmlk'); + INSERT INTO t1 VALUES(42,462,14014,42.042,1401.4,'qrstuvwxy','qponmlk'); + INSERT INTO t1 VALUES(43,473,15015,43.043,1501.5,'rstuvwxyz','ponmlkj'); + INSERT INTO t1 VALUES(44,484,15015,44.044,1501.5,'stuvwxyza','ponmlkj'); + INSERT INTO t1 VALUES(45,495,15015,45.045,1501.5,'tuvwxyzab','ponmlkj'); + INSERT INTO t1 VALUES(46,506,16016,46.046,1601.6,'uvwxyzabc','ponmlkj'); + INSERT INTO t1 VALUES(47,517,16016,47.047,1601.6,'vwxyzabcd','ponmlkj'); + INSERT INTO t1 VALUES(48,528,16016,48.048,1601.6,'wxyzabcde','onmlkji'); + INSERT INTO t1 VALUES(49,539,17017,49.049,1701.7,'xyzabcdef','onmlkji'); + INSERT INTO t1 VALUES(50,550,17017,50.05,1701.7,'yzabcdefg','onmlkji'); + INSERT INTO t1 VALUES(51,561,17017,51.051,1701.7,'zabcdefgh','onmlkji'); + INSERT INTO t1 VALUES(52,572,18018,52.052,1801.8,'abcdefghi','onmlkji'); + INSERT INTO t1 VALUES(53,583,18018,53.053,1801.8,'bcdefghij','nmlkjih'); + INSERT INTO t1 VALUES(54,594,18018,54.054,1801.8,'cdefghijk','nmlkjih'); + INSERT INTO t1 VALUES(55,605,19019,55.055,1901.9,'defghijkl','nmlkjih'); + INSERT INTO t1 VALUES(56,616,19019,56.056,1901.9,'efghijklm','nmlkjih'); + INSERT INTO t1 VALUES(57,627,19019,57.057,1901.9,'fghijklmn','nmlkjih'); + INSERT INTO t1 VALUES(58,638,20020,58.058,2002.0,'ghijklmno','mlkjihg'); + INSERT INTO t1 VALUES(59,649,20020,59.059,2002.0,'hijklmnop','mlkjihg'); + INSERT INTO t1 VALUES(60,660,20020,60.06,2002.0,'ijklmnopq','mlkjihg'); + INSERT INTO t1 VALUES(61,671,21021,61.061,2102.1,'jklmnopqr','mlkjihg'); + INSERT INTO t1 VALUES(62,682,21021,62.062,2102.1,'klmnopqrs','mlkjihg'); + INSERT INTO t1 VALUES(63,693,21021,63.063,2102.1,'lmnopqrst','lkjihgf'); + INSERT INTO t1 VALUES(64,704,22022,64.064,2202.2,'mnopqrstu','lkjihgf'); + INSERT INTO t1 VALUES(65,715,22022,65.065,2202.2,'nopqrstuv','lkjihgf'); + INSERT INTO t1 VALUES(66,726,22022,66.066,2202.2,'opqrstuvw','lkjihgf'); + INSERT INTO t1 VALUES(67,737,23023,67.067,2302.3,'pqrstuvwx','lkjihgf'); + INSERT INTO t1 VALUES(68,748,23023,68.068,2302.3,'qrstuvwxy','kjihgfe'); + INSERT INTO t1 VALUES(69,759,23023,69.069,2302.3,'rstuvwxyz','kjihgfe'); + INSERT INTO t1 VALUES(70,770,24024,70.07,2402.4,'stuvwxyza','kjihgfe'); + INSERT INTO t1 VALUES(71,781,24024,71.071,2402.4,'tuvwxyzab','kjihgfe'); + INSERT INTO t1 VALUES(72,792,24024,72.072,2402.4,'uvwxyzabc','kjihgfe'); + INSERT INTO t1 VALUES(73,803,25025,73.073,2502.5,'vwxyzabcd','jihgfed'); + INSERT INTO t1 VALUES(74,814,25025,74.074,2502.5,'wxyzabcde','jihgfed'); + INSERT INTO t1 VALUES(75,825,25025,75.075,2502.5,'xyzabcdef','jihgfed'); + INSERT INTO t1 VALUES(76,836,26026,76.076,2602.6,'yzabcdefg','jihgfed'); + INSERT INTO t1 VALUES(77,847,26026,77.077,2602.6,'zabcdefgh','jihgfed'); + INSERT INTO t1 VALUES(78,858,26026,78.078,2602.6,'abcdefghi','ihgfedc'); + INSERT INTO t1 VALUES(79,869,27027,79.079,2702.7,'bcdefghij','ihgfedc'); + INSERT INTO t1 VALUES(80,880,27027,80.08,2702.7,'cdefghijk','ihgfedc'); + INSERT INTO t1 VALUES(81,891,27027,81.081,2702.7,'defghijkl','ihgfedc'); + INSERT INTO t1 VALUES(82,902,28028,82.082,2802.8,'efghijklm','ihgfedc'); + INSERT INTO t1 VALUES(83,913,28028,83.083,2802.8,'fghijklmn','hgfedcb'); + INSERT INTO t1 VALUES(84,924,28028,84.084,2802.8,'ghijklmno','hgfedcb'); + INSERT INTO t1 VALUES(85,935,29029,85.085,2902.9,'hijklmnop','hgfedcb'); + INSERT INTO t1 VALUES(86,946,29029,86.086,2902.9,'ijklmnopq','hgfedcb'); + INSERT INTO t1 VALUES(87,957,29029,87.087,2902.9,'jklmnopqr','hgfedcb'); + INSERT INTO t1 VALUES(88,968,30030,88.088,3003.0,'klmnopqrs','gfedcba'); + INSERT INTO t1 VALUES(89,979,30030,89.089,3003.0,'lmnopqrst','gfedcba'); + INSERT INTO t1 VALUES(90,NULL,30030,90.09,3003.0,'mnopqrstu','gfedcba'); + INSERT INTO t1 VALUES(91,1001,NULL,91.091,3103.1,'nopqrstuv','gfedcba'); + INSERT INTO t1 VALUES(92,1012,31031,NULL,3103.1,'opqrstuvw','gfedcba'); + INSERT INTO t1 VALUES(93,1023,31031,93.093,NULL,'pqrstuvwx','fedcbaz'); + INSERT INTO t1 VALUES(94,1034,32032,94.094,3203.2,NULL,'fedcbaz'); + INSERT INTO t1 VALUES(95,1045,32032,95.095,3203.2,'rstuvwxyz',NULL); + INSERT INTO t1 VALUES(96,NULL,NULL,96.096,3203.2,'stuvwxyza','fedcbaz'); + INSERT INTO t1 VALUES(97,1067,33033,NULL,NULL,'tuvwxyzab','fedcbaz'); + INSERT INTO t1 VALUES(98,1078,33033,98.098,3303.3,NULL,NULL); + INSERT INTO t1 VALUES(99,NULL,NULL,NULL,NULL,NULL,NULL); + CREATE INDEX t1b ON t1(b); + CREATE INDEX t1c ON t1(c); + CREATE INDEX t1d ON t1(d); + CREATE INDEX t1e ON t1(e); + CREATE INDEX t1f ON t1(f); + CREATE INDEX t1g ON t1(g); + CREATE TABLE t2(a INTEGER PRIMARY KEY,b,c,d,e,f,g); + INSERT INTO t2 SELECT * FROM t1; + CREATE INDEX t2b ON t2(b,c); + CREATE INDEX t2c ON t2(c,e); + CREATE INDEX t2d ON t2(d,g); + CREATE INDEX t2e ON t2(e,f,g); + CREATE INDEX t2f ON t2(f,b,d,c); + CREATE INDEX t2g ON t2(g,f); + CREATE TABLE t3(x,y); + INSERT INTO t3 VALUES(1,80); + INSERT INTO t3 VALUES(2,80); + CREATE TABLE t4(a INTEGER PRIMARY KEY,b,c,d,e,f,g); + INSERT INTO t4 SELECT * FROM t1; + CREATE INDEX t4b ON t4(b); + CREATE INDEX t4c ON t4(c); + } +} {} + +do_test where9-1.2.1 { + count_steps { + SELECT a FROM t1 + WHERE b IS NULL + OR c IS NULL + OR d IS NULL + ORDER BY a + } +} {90 91 92 96 97 99 scan 0 sort 1} +do_test where9-1.2.2 { + count_steps { + SELECT a FROM t1 + WHERE +b IS NULL + OR c IS NULL + OR d IS NULL + ORDER BY a + } +} {90 91 92 96 97 99 scan 98 sort 0} +do_test where9-1.2.3 { + count_steps { + SELECT a FROM t1 + WHERE b IS NULL + OR +c IS NULL + OR d IS NULL + ORDER BY a + } +} {90 91 92 96 97 99 scan 98 sort 0} +do_test where9-1.2.4 { + count_steps { + SELECT a FROM t1 + WHERE b IS NULL + OR c IS NULL + OR +d IS NULL + ORDER BY a + } +} {90 91 92 96 97 99 scan 98 sort 0} +do_test where9-1.2.5 { + count_steps { + SELECT a FROM t4 + WHERE b IS NULL + OR c IS NULL + OR d IS NULL + ORDER BY a + } +} {90 91 92 96 97 99 scan 98 sort 0} + +do_test where9-1.3.1 { + count_steps { + SELECT a FROM t1 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + ORDER BY a + } +} {90 91 92 97 scan 0 sort 1} +do_test where9-1.3.2 { + count_steps { + SELECT a FROM t4 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + ORDER BY a + } +} {90 91 92 97 scan 98 sort 0} +do_test where9-1.3.3 { + count_steps { + SELECT a FROM t4 + WHERE (b NOT NULL AND c NOT NULL AND d IS NULL) + OR (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + ORDER BY a + } +} {90 91 92 97 scan 98 sort 0} +do_test where9-1.3.4 { + count_steps { + SELECT a FROM (t4) + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + ORDER BY a + } +} {90 91 92 97 scan 98 sort 0} + +do_test where9-1.4 { + count_steps { + SELECT a FROM t1 + WHERE (b>=950 AND b<=1010) OR (b IS NULL AND c NOT NULL) + ORDER BY a + } +} {87 88 89 90 91 scan 0 sort 1} +do_test where9-1.5 { + # When this test was originally written, SQLite used a rowset object + # to optimize the "ORDER BY a" clause. Now that it is using a rowhash, + # this is not possible. So we have to comment out one term of the OR + # expression in order to prevent SQLite from deeming a full-table + # scan to be a better strategy than using multiple indexes, which would + # defeat the point of the test. + count_steps { + SELECT a FROM t1 + WHERE a=83 + OR b=913 + OR c=28028 + OR (d>=82 AND d<83) +/* OR (e>2802 AND e<2803) */ + OR f='fghijklmn' + OR g='hgfedcb' + ORDER BY a + } +} {5 31 57 82 83 84 85 86 87 scan 0 sort 1} +do_test where9-1.6 { + count_steps { + SELECT a FROM t1 + WHERE b=1012 + OR (d IS NULL AND e IS NOT NULL) + } +} {92 scan 0 sort 0} +do_test where9-1.7 { + count_steps { + SELECT a FROM t1 + WHERE (b=1012 OR (d IS NULL AND e IS NOT NULL)) + AND f!=g + } +} {92 scan 0 sort 0} +do_test where9-1.8 { + count_steps { + SELECT a FROM t1 + WHERE (b=1012 OR (d IS NULL AND e IS NOT NULL)) + AND f==g + } +} {scan 0 sort 0} + +do_test where9-2.1 { + count_steps { + SELECT t2.a FROM t1, t2 + WHERE t1.a=80 + AND (t1.c=t2.c OR t1.d=t2.d) + ORDER BY 1 + } +} {79 80 81 scan 0 sort 1} +do_test where9-2.2 { + count_steps { + SELECT t2.a FROM t1, t2 + WHERE t1.a=80 + AND ((t1.c=t2.c AND t1.d=t2.d) OR t1.f=t2.f) + ORDER BY 1 + } +} {2 28 54 80 scan 0 sort 1} +do_test where9-2.3 { + count_steps { + SELECT coalesce(t2.a,9999) + FROM t1 LEFT JOIN t2 ON (t1.c=t2.c AND t1.d=t2.d) OR t1.f=t2.f + WHERE t1.a=80 + ORDER BY 1 + } +} {2 28 54 80 scan 0 sort 1} +do_test where9-2.4 { + count_steps { + SELECT coalesce(t2.a,9999) + FROM t1 LEFT JOIN t2 ON (t1.c+1=t2.c AND t1.d=t2.d) OR (t1.f||'x')=t2.f + WHERE t1.a=80 + ORDER BY 1 + } +} {9999 scan 0 sort 1} +do_test where9-2.5 { + count_steps { + SELECT t1.a, coalesce(t2.a,9999) + FROM t1 LEFT JOIN t2 ON (t1.c=t2.c AND t1.d=t2.d) OR (t1.f)=t2.f + WHERE t1.a=80 OR t1.b=880 OR (t1.c=27027 AND round(t1.d)==80) + ORDER BY 1 + } +} {80 80 80 2 80 28 80 54 scan 0 sort 1} +do_test where9-2.6 { + count_steps { + SELECT t1.a, coalesce(t2.a,9999) + FROM t1 LEFT JOIN t2 ON (t1.c+1=t2.c AND t1.d=t2.d) OR (t1.f||'x')=t2.f + WHERE t1.a=80 OR t1.b=880 OR (t1.c=27027 AND round(t1.d)==80) + ORDER BY 1 + } +} {80 9999 scan 0 sort 1} +do_test where9-2.7 { + count_steps { + SELECT t3.x, t1.a, coalesce(t2.a,9999) + FROM t3 JOIN + t1 LEFT JOIN t2 ON (t1.c+1=t2.c AND t1.d=t2.d) OR (t1.f||'x')=t2.f + WHERE t1.a=t3.y OR t1.b=t3.y*11 OR (t1.c=27027 AND round(t1.d)==80) + ORDER BY 1, 2 + } +} {1 80 9999 2 80 9999 scan 1 sort 1} +do_test where9-2.8 { + count_steps { + SELECT t3.x, t1.a, coalesce(t2.a,9999) + FROM t3 JOIN + t1 LEFT JOIN t2 ON (t1.c=t2.c AND t1.d=t2.d) OR (t1.f)=t2.f + WHERE t1.a=t3.y OR t1.b=t3.y*11 OR (t1.c=27027 AND round(t1.d)==80) + ORDER BY 1, 2, 3 + } +} {1 80 2 1 80 28 1 80 54 1 80 80 2 80 2 2 80 28 2 80 54 2 80 80 scan 1 sort 1} + + +ifcapable explain { + do_execsql_test where9-3.1 { + EXPLAIN QUERY PLAN + SELECT t2.a FROM t1, t2 + WHERE t1.a=80 AND ((t1.c=t2.c AND t1.d=t2.d) OR t1.f=t2.f) + } { + 0 0 0 {SEARCH TABLE t1 USING INTEGER PRIMARY KEY (rowid=?)} + 0 1 1 {SEARCH TABLE t2 USING INDEX t2d (d=?)} + 0 1 1 {SEARCH TABLE t2 USING COVERING INDEX t2f (f=?)} + } + do_execsql_test where9-3.2 { + EXPLAIN QUERY PLAN + SELECT coalesce(t2.a,9999) + FROM t1 LEFT JOIN t2 ON (t1.c+1=t2.c AND t1.d=t2.d) OR (t1.f||'x')=t2.f + WHERE t1.a=80 + } { + 0 0 0 {SEARCH TABLE t1 USING INTEGER PRIMARY KEY (rowid=?)} + 0 1 1 {SEARCH TABLE t2 USING INDEX t2d (d=?)} + 0 1 1 {SEARCH TABLE t2 USING COVERING INDEX t2f (f=?)} + } +} + +# Make sure that INDEXED BY and multi-index OR clauses play well with +# one another. +# +do_test where9-4.1 { + count_steps { + SELECT a FROM t1 + WHERE b>1000 + AND (c=31031 OR d IS NULL) + ORDER BY +a + } +} {92 93 97 scan 0 sort 1} +do_test where9-4.2 { + count_steps { + SELECT a FROM t1 + WHERE b>1000 + AND (c=31031 OR +d IS NULL) + ORDER BY +a + } +} {92 93 97 scan 0 sort 1} +do_test where9-4.3 { + count_steps { + SELECT a FROM t1 + WHERE +b>1000 + AND (c=31031 OR d IS NULL) + ORDER BY +a + } +} {92 93 97 scan 0 sort 1} +do_test where9-4.4 { + count_steps { + SELECT a FROM t1 INDEXED BY t1b + WHERE b>1000 + AND (c=31031 OR d IS NULL) + ORDER BY +a + } +} {92 93 97 scan 0 sort 1} +do_test where9-4.5 { + catchsql { + SELECT a FROM t1 INDEXED BY t1b + WHERE +b>1000 + AND (c=31031 OR d IS NULL) + ORDER BY +a + } +} {1 {no query solution}} +do_test where9-4.6 { + count_steps { + SELECT a FROM t1 NOT INDEXED + WHERE b>1000 + AND (c=31031 OR d IS NULL) + ORDER BY +a + } +} {92 93 97 scan 98 sort 1} +do_test where9-4.7 { + catchsql { + SELECT a FROM t1 INDEXED BY t1c + WHERE b>1000 + AND (c=31031 OR d IS NULL) + ORDER BY +a + } +} {1 {no query solution}} +do_test where9-4.8 { + catchsql { + SELECT a FROM t1 INDEXED BY t1d + WHERE b>1000 + AND (c=31031 OR d IS NULL) + ORDER BY +a + } +} {1 {no query solution}} + +ifcapable explain { + # The (c=31031 OR d IS NULL) clause is preferred over b>1000 because + # the former is an equality test which is expected to return fewer rows. + # + do_execsql_test where9-5.1 { + EXPLAIN QUERY PLAN SELECT a FROM t1 WHERE b>1000 AND (c=31031 OR d IS NULL) + } { + 0 0 0 {SEARCH TABLE t1 USING INDEX t1c (c=?)} + 0 0 0 {SEARCH TABLE t1 USING INDEX t1d (d=?)} + } + + # In contrast, b=1000 is preferred over any OR-clause. + # + do_execsql_test where9-5.2 { + EXPLAIN QUERY PLAN SELECT a FROM t1 WHERE b=1000 AND (c=31031 OR d IS NULL) + } { + 0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b=?)} + } + + # Likewise, inequalities in an AND are preferred over inequalities in + # an OR. + # + do_execsql_test where9-5.3 { + EXPLAIN QUERY PLAN SELECT a FROM t1 WHERE b>1000 AND (c>=31031 OR d IS NULL) + } { + 0 0 0 {SEARCH TABLE t1 USING INDEX t1b (b>?)} + } +} + +############################################################################ +# Make sure OR-clauses work correctly on UPDATE and DELETE statements. + +do_test where9-6.2.1 { + db eval {SELECT count(*) FROM t1 UNION ALL SELECT a FROM t1 WHERE a>=85} +} {99 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99} + +do_test where9-6.2.2 { ;# Deletes entries 90 91 92 96 97 99 + count_steps { + BEGIN; + DELETE FROM t1 + WHERE b IS NULL + OR c IS NULL + OR d IS NULL + } +} {scan 0 sort 0} + +do_test where9-6.2.3 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a>=85; + ROLLBACK; + } +} {93 85 86 87 88 89 93 94 95 98} + +do_test where9-6.2.4 { ;# Deletes entries 90 91 92 96 97 99 + count_steps { + BEGIN; + DELETE FROM t1 + WHERE +b IS NULL + OR c IS NULL + OR d IS NULL + } +} {scan 98 sort 0} + +do_test where9-6.2.5 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a>=85; + ROLLBACK; + } +} {93 85 86 87 88 89 93 94 95 98} + +do_test where9-6.2.6 { + count_steps { + BEGIN; + UPDATE t1 SET a=a+100 + WHERE (b IS NULL + OR c IS NULL + OR d IS NULL) + AND a!=92 + AND a!=97 + } +} {scan 0 sort 0} ;# Add 100 to entries 90 91 96 99 + +do_test where9-6.2.7 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a>=85; + ROLLBACK + } +} {99 85 86 87 88 89 92 93 94 95 97 98 190 191 196 199} + +do_test where9-6.2.8 { ;# Deletes entries 90 91 92 97 99 + count_steps { + BEGIN; + DELETE FROM t1 + WHERE (b IS NULL + OR c IS NULL + OR d IS NULL) + AND a!=96 + } +} {scan 0 sort 0} + +do_test where9-6.2.9 { + db eval { + SELECT count(*) FROM t1 UNION ALL SELECT a FROM t1 WHERE a>=85; + ROLLBACK; + } +} {94 85 86 87 88 89 93 94 95 96 98} + +do_test where9-6.3.1 { + count_steps { + BEGIN; + DELETE FROM t1 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {scan 0 sort 0} ;# DELETEs rows 90 91 92 97 +do_test where9-6.3.2 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 100; + ROLLBACK; + } +} {95 85 86 87 88 89 93 94 95 96 98 99} + +do_test where9-6.3.3 { + count_steps { + BEGIN; + UPDATE t1 SET a=a+100 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {scan 0 sort 0} ;# Add 100 to rowids 90 91 92 97 +do_test where9-6.3.4 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 200; + ROLLBACK; + } +} {99 85 86 87 88 89 93 94 95 96 98 99 190 191 192 197} + +do_test where9-6.3.5 { + count_steps { + BEGIN; + DELETE FROM t1 + WHERE (+b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {scan 98 sort 0} ;# DELETEs rows 90 91 92 97 +do_test where9-6.3.6 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 100; + ROLLBACK; + } +} {95 85 86 87 88 89 93 94 95 96 98 99} + +do_test where9-6.3.7 { + count_steps { + BEGIN; + UPDATE t1 SET a=a+100 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND +c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {scan 98 sort 0} ;# Add 100 to rowids 90 91 92 97 +do_test where9-6.3.8 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 100; + ROLLBACK; + } +} {99 85 86 87 88 89 93 94 95 96 98 99} + + +do_test where9-6.4.1 { + count_steps { + BEGIN; + DELETE FROM t1 + WHERE (b>=950 AND b<=1010) OR (b IS NULL AND c NOT NULL) + } +} {scan 0 sort 0} ;# DELETE rows 87 88 89 90 91 +do_test where9-6.4.2 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 100; + ROLLBACK; + } +} {94 85 86 92 93 94 95 96 97 98 99} +do_test where9-6.4.3 { + count_steps { + BEGIN; + UPDATE t1 SET a=a+100 + WHERE (b>=950 AND b<=1010) OR (b IS NULL AND c NOT NULL) + } +} {scan 0 sort 0} ;# Add 100 to rowids 87 88 89 90 91 +do_test where9-6.4.4 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 100; + ROLLBACK; + } +} {99 85 86 92 93 94 95 96 97 98 99} + + +do_test where9-6.5.1 { + count_steps { + BEGIN; + DELETE FROM t1 + WHERE a=83 + OR b=913 + OR c=28028 + OR (d>=82 AND d<83) + OR (e>2802 AND e<2803) + OR f='fghijklmn' + OR g='hgfedcb' + } +} {scan 0 sort 0} ;# DELETE rows 5 31 57 82 83 84 85 86 87 +do_test where9-6.5.2 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a IN (5,31,57,82,83,84,85,86,87); + ROLLBACK; + } +} {90} + +do_test where9-6.5.3 { + count_steps { + BEGIN; + UPDATE t1 SET a=a+100 + WHERE a=83 + OR b=913 + OR c=28028 + OR (d>=82 AND d<83) + OR (e>2802 AND e<2803) + OR f='fghijklmn' + OR g='hgfedcb' + } +} {scan 0 sort 0} ;# Add 100 to rowids 5 31 57 82 83 84 85 86 87 +do_test where9-6.5.4 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a%100 IN (5,31,57,82,83,84,85,86,87) ORDER BY rowid; + ROLLBACK; + } +} {99 105 131 157 182 183 184 185 186 187} + +do_test where9-6.6.1 { + count_steps { + BEGIN; + DELETE FROM t1 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND +c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {scan 98 sort 0} ;# DELETEs rows 90 91 92 97 +do_test where9-6.6.2 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 100; + ROLLBACK; + } +} {95 85 86 87 88 89 93 94 95 96 98 99} + +do_test where9-6.6.3 { + count_steps { + BEGIN; + UPDATE t1 SET a=a+100 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND +c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {scan 98 sort 0} ;# Add 100 to rowids 90 91 92 97 +do_test where9-6.6.4 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 200; + ROLLBACK; + } +} {99 85 86 87 88 89 93 94 95 96 98 99 190 191 192 197} + +do_test where9-6.7.1 { + count_steps { + BEGIN; + DELETE FROM t1 NOT INDEXED + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {scan 98 sort 0} ;# DELETEs rows 90 91 92 97 +do_test where9-6.7.2 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 100; + ROLLBACK; + } +} {95 85 86 87 88 89 93 94 95 96 98 99} + +do_test where9-6.7.3 { + count_steps { + BEGIN; + UPDATE t1 NOT INDEXED SET a=a+100 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {scan 98 sort 0} ;# Add 100 to rowids 90 91 92 97 +do_test where9-6.7.4 { + db eval { + SELECT count(*) FROM t1 UNION ALL + SELECT a FROM t1 WHERE a BETWEEN 85 AND 200; + ROLLBACK; + } +} {99 85 86 87 88 89 93 94 95 96 98 99 190 191 192 197} + +do_test where9-6.8.1 { + catchsql { + DELETE FROM t1 INDEXED BY t1b + WHERE (+b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {1 {no query solution}} +do_test where9-6.8.2 { + catchsql { + UPDATE t1 INDEXED BY t1b SET a=a+100 + WHERE (+b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } +} {1 {no query solution}} +ifcapable stat4||stat3 { + # When STAT3 is enabled, the "b NOT NULL" terms get translated + # into b>NULL, which can be satified by the index t1b. It is a very + # expensive way to do the query, but it works, and so a solution is possible. + do_test where9-6.8.3-stat4 { + catchsql { + UPDATE t1 INDEXED BY t1b SET a=a+100 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } + } {0 {}} + do_test where9-6.8.4-stat4 { + catchsql { + DELETE FROM t1 INDEXED BY t1b + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } + } {0 {}} +} else { + do_test where9-6.8.3 { + catchsql { + UPDATE t1 INDEXED BY t1b SET a=a+100 + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } + } {1 {no query solution}} + do_test where9-6.8.4 { + catchsql { + DELETE FROM t1 INDEXED BY t1b + WHERE (b IS NULL AND c NOT NULL AND d NOT NULL) + OR (b NOT NULL AND c IS NULL AND d NOT NULL) + OR (b NOT NULL AND c NOT NULL AND d IS NULL) + } + } {1 {no query solution}} +} +############################################################################ +# Test cases where terms inside an OR series are combined with AND terms +# external to the OR clause. In other words, cases where +# +# x AND (y OR z) +# +# is able to use indices on x,y and x,z, or indices y,x and z,x. +# +do_test where9-7.0 { + execsql { + CREATE TABLE t5(a, b, c, d, e, f, g, x, y); + INSERT INTO t5 + SELECT a, b, c, e, d, f, g, + CASE WHEN (a&1)!=0 THEN 'y' ELSE 'n' END, + CASE WHEN (a&2)!=0 THEN 'y' ELSE 'n' END + FROM t1; + CREATE INDEX t5xb ON t5(x, b); + CREATE INDEX t5xc ON t5(x, c); + CREATE INDEX t5xd ON t5(x, d); + CREATE INDEX t5xe ON t5(x, e); + CREATE INDEX t5xf ON t5(x, f); + CREATE INDEX t5xg ON t5(x, g); + CREATE INDEX t5yb ON t5(y, b); + CREATE INDEX t5yc ON t5(y, c); + CREATE INDEX t5yd ON t5(y, d); + CREATE INDEX t5ye ON t5(y, e); + CREATE INDEX t5yf ON t5(y, f); + CREATE INDEX t5yg ON t5(y, g); + CREATE TABLE t6(a, b, c, e, d, f, g, x, y); + INSERT INTO t6 SELECT * FROM t5; + ANALYZE t5; + } + ifcapable stat3 { + sqlite3 db2 test.db + db2 eval { DROP TABLE IF EXISTS sqlite_stat3 } + db2 close + } +} {} +do_test where9-7.1.1 { + count_steps { + SELECT a FROM t5 WHERE x='y' AND (b=913 OR c=27027) ORDER BY a; + } +} {79 81 83 scan 0 sort 1} +do_test where9-7.1.2 { + execsql { + SELECT a FROM t6 WHERE x='y' AND (b=913 OR c=27027) ORDER BY a; + } +} {79 81 83} +do_test where9-7.1.3 { + count_steps { + SELECT a FROM t5 WHERE x='n' AND (b=913 OR c=27027) ORDER BY a; + } +} {80 scan 0 sort 1} +do_test where9-7.1.4 { + execsql { + SELECT a FROM t6 WHERE x='n' AND (b=913 OR c=27027) ORDER BY a; + } +} {80} +do_test where9-7.2.1 { + count_steps { + SELECT a FROM t5 WHERE (x='y' OR y='y') AND b=913 ORDER BY a; + } +} {83 scan 0 sort 1} +do_test where9-7.2.2 { + execsql { + SELECT a FROM t6 WHERE (x='y' OR y='y') AND b=913 ORDER BY a; + } +} {83} +do_test where9-7.3.1 { + count_steps { + SELECT a FROM t5 WHERE (x='y' OR y='y') AND c=27027 ORDER BY a; + } +} {79 81 scan 0 sort 1} +do_test where9-7.3.2 { + execsql { + SELECT a FROM t6 WHERE (x='y' OR y='y') AND c=27027 ORDER BY a; + } +} {79 81} + +# Fix for ticket [b7c8682cc17f32903f03a610bd0d35ffd3c1e6e4] +# "Incorrect result from LEFT JOIN with OR in the WHERE clause" +# +do_test where9-8.1 { + db eval { + CREATE TABLE t81(a INTEGER PRIMARY KEY, b, c, d); + CREATE TABLE t82(x INTEGER PRIMARY KEY, y); + CREATE TABLE t83(p INTEGER PRIMARY KEY, q); + + INSERT INTO t81 VALUES(2,3,4,5); + INSERT INTO t81 VALUES(3,4,5,6); + INSERT INTO t82 VALUES(2,4); + INSERT INTO t83 VALUES(5,55); + + SELECT * + FROM t81 LEFT JOIN t82 ON y=b JOIN t83 + WHERE c==p OR d==p + ORDER BY +a; + } +} {2 3 4 5 {} {} 5 55 3 4 5 6 2 4 5 55} +do_test where9-8.2 { + db eval { + SELECT * + FROM t81 LEFT JOIN (t82) ON y=b JOIN t83 + WHERE c==p OR d==p + ORDER BY +a; + } +} {2 3 4 5 {} {} 5 55 3 4 5 6 2 4 5 55} +do_test where9-8.3 { + db eval { + SELECT * + FROM (t81) LEFT JOIN (main.t82) ON y=b JOIN t83 + WHERE c==p OR d==p + ORDER BY +a; + } +} {2 3 4 5 {} {} 5 55 3 4 5 6 2 4 5 55} + +# Fix for ticket [f2369304e47167e3e644e2f1fe9736063391d7b7] +# Incorrect results when OR is used in the ON clause of a LEFT JOIN +# +do_test where9-9.1 { + db eval { + CREATE TABLE t91(x); INSERT INTO t91 VALUES(1); + CREATE TABLE t92(y INTEGER PRIMARY KEY,a,b); + INSERT INTO t92 VALUES(1,2,3); + SELECT 1 FROM t91 LEFT JOIN t92 ON a=2 OR b=3; + SELECT 2 FROM t91 LEFT JOIN t92 ON a=2 AND b=3; + SELECT 3 FROM t91 LEFT JOIN t92 ON (a=2 OR b=3) AND y IS NULL; + SELECT 4 FROM t91 LEFT JOIN t92 ON (a=2 AND b=3) AND y IS NULL; + CREATE TEMP TABLE x9 AS SELECT * FROM t91 LEFT JOIN t92 ON a=2 OR b=3; + SELECT 5 FROM x9 WHERE y IS NULL; + SELECT 6 FROM t91 LEFT JOIN t92 ON a=2 OR b=3 WHERE y IS NULL; + SELECT 7 FROM t91 LEFT JOIN t92 ON a=2 AND b=3 WHERE y IS NULL; + SELECT 8 FROM t91 LEFT JOIN t92 ON a=22 OR b=33 WHERE y IS NULL; + SELECT 9 FROM t91 LEFT JOIN t92 ON a=22 AND b=33 WHERE y IS NULL; + } +} {1 2 3 4 8 9} + +# Fix for ticket [bc878246eafe0f52c519e29049b2fe4a99491b27] +# Incorrect result when OR is used in a join to the right of a LEFT JOIN +# +do_test where9-10.1 { + db eval { + CREATE TABLE t101 (id INTEGER PRIMARY KEY); + INSERT INTO t101 VALUES (1); + SELECT * FROM t101 AS t0 + LEFT JOIN t101 AS t1 ON t1.id BETWEEN 10 AND 20 + JOIN t101 AS t2 ON (t2.id = t0.id OR (t2.id<>555 AND t2.id=t1.id)); + } +} {1 {} 1} +do_test where9-10.2 { + db eval { + CREATE TABLE t102 (id TEXT UNIQUE NOT NULL); + INSERT INTO t102 VALUES ('1'); + SELECT * FROM t102 AS t0 + LEFT JOIN t102 AS t1 ON t1.id GLOB 'abc%' + JOIN t102 AS t2 ON (t2.id = t0.id OR (t2.id<>555 AND t2.id=t1.id)); + } +} {1 {} 1} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/whereA.test b/components/external/SQLite-3.8.1/test/whereA.test new file mode 100644 index 0000000000000000000000000000000000000000..78826b111c84151e9b4062529b4db1ade1e2cc81 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/whereA.test @@ -0,0 +1,162 @@ +# 2009 February 23 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the reverse_select_order pragma. +# +# $Id: whereA.test,v 1.3 2009/06/10 19:33:29 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_test whereA-1.1 { + db eval { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE, c); + INSERT INTO t1 VALUES(1,2,3); + INSERT INTO t1 values(2,'hello','world'); + INSERT INTO t1 VALUES(3,4.53,NULL); + SELECT * FROM t1 + } +} {1 2 3 2 hello world 3 4.53 {}} +do_test whereA-1.2 { + db eval { + PRAGMA reverse_unordered_selects=1; + SELECT * FROM t1; + } +} {3 4.53 {} 2 hello world 1 2 3} + +do_test whereA-1.3 { + db close + sqlite3 db test.db + db eval { + PRAGMA reverse_unordered_selects=1; + SELECT * FROM t1; + } +} {3 4.53 {} 2 hello world 1 2 3} +do_test whereA-1.4 { + db close + sqlite3 db test.db + db eval { + PRAGMA reverse_unordered_selects=1; + SELECT * FROM t1 ORDER BY rowid; + } +} {1 2 3 2 hello world 3 4.53 {}} +do_test whereA-1.5 { + db eval { + VACUUM; + SELECT * FROM t1 ORDER BY rowid; + } +} {1 2 3 2 hello world 3 4.53 {}} +do_test whereA-1.6 { + db eval { + PRAGMA reverse_unordered_selects; + } +} {1} +do_test whereA-1.7 { + db close + sqlite3 db test.db + db eval { + PRAGMA reverse_unordered_selects=1; + VACUUM; + SELECT * FROM t1; + } +} {3 4.53 {} 2 hello world 1 2 3} +do_execsql_test whereA-1.8 { + SELECT * FROM t1 WHERE b=2 AND a IS NULL; +} {} +do_execsql_test whereA-1.9 { + SELECT * FROM t1 WHERE b=2 AND a IS NOT NULL; +} {1 2 3} + +do_test whereA-2.1 { + db eval { + PRAGMA reverse_unordered_selects=0; + SELECT * FROM t1 WHERE a>0; + } +} {1 2 3 2 hello world 3 4.53 {}} +do_test whereA-2.2 { + db eval { + PRAGMA reverse_unordered_selects=1; + SELECT * FROM t1 WHERE a>0; + } +} {3 4.53 {} 2 hello world 1 2 3} + +do_test whereA-2.3 { + db eval { + PRAGMA reverse_unordered_selects=1; + SELECT * FROM t1 WHERE a>0 ORDER BY rowid; + } +} {1 2 3 2 hello world 3 4.53 {}} + +do_test whereA-3.1 { + db eval { + PRAGMA reverse_unordered_selects=0; + SELECT * FROM t1 WHERE b>0; + } +} {1 2 3 3 4.53 {} 2 hello world} +do_test whereA-3.2 { + db eval { + PRAGMA reverse_unordered_selects=1; + SELECT * FROM t1 WHERE b>0; + } +} {2 hello world 3 4.53 {} 1 2 3} +do_test whereA-3.3 { + db eval { + PRAGMA reverse_unordered_selects=1; + SELECT * FROM t1 WHERE b>0 ORDER BY b; + } +} {1 2 3 3 4.53 {} 2 hello world} + +do_test whereA-4.1 { + db eval { + CREATE TABLE t2(x); + INSERT INTO t2 VALUES(1); + INSERT INTO t2 VALUES(2); + SELECT x FROM t2; + } +} {2 1} +# Do an SQL statement. Append the search count to the end of the result. +# +proc count sql { + set ::sqlite_sort_count 0 + return [concat [execsql $sql] $::sqlite_sort_count] +} +do_test whereA-4.2 { ;# Ticket #3904 + db eval { + CREATE INDEX t2x ON t2(x); + } + count { + SELECT x FROM t2; + } +} {2 1 0} +do_test whereA-4.3 { + count { + SELECT x FROM t2 ORDER BY x; + } +} {1 2 0} +do_test whereA-4.4 { + count { + SELECT x FROM t2 ORDER BY x DESC; + } +} {2 1 0} +do_test whereA-4.5 { + db eval {DROP INDEX t2x;} + count { + SELECT x FROM t2 ORDER BY x; + } +} {1 2 1} +do_test whereA-4.6 { + count { + SELECT x FROM t2 ORDER BY x DESC; + } +} {2 1 1} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/whereB.test b/components/external/SQLite-3.8.1/test/whereB.test new file mode 100644 index 0000000000000000000000000000000000000000..e4438547d778d58285a05f9617ffa892abe102fd --- /dev/null +++ b/components/external/SQLite-3.8.1/test/whereB.test @@ -0,0 +1,543 @@ +# 2009 August 13 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing WHERE clause conditions with +# subtle affinity issues. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +# For this set of tests: +# +# * t1.y holds an integer value with affinity NONE +# * t2.b holds a text value with affinity TEXT +# +# These values are not equal and because neither affinity is NUMERIC +# no type conversion occurs. +# +do_test whereB-1.1 { + db eval { + CREATE TABLE t1(x,y); -- affinity of t1.y is NONE + INSERT INTO t1 VALUES(1,99); + + CREATE TABLE t2(a, b TEXT); -- affinity of t2.b is TEXT + CREATE INDEX t2b ON t2(b); + INSERT INTO t2 VALUES(2,99); + + SELECT x, a, y=b FROM t1, t2 ORDER BY +x, +a; + } +} {1 2 0} +do_test whereB-1.2 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {} +do_test whereB-1.3 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {} +do_test whereB-1.4 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} +do_test whereB-1.100 { + db eval { + DROP INDEX t2b; + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {} +do_test whereB-1.101 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {} +do_test whereB-1.102 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} + +# For this set of tests: +# +# * t1.y holds a text value with affinity TEXT +# * t2.b holds an integer value with affinity NONE +# +# These values are not equal and because neither affinity is NUMERIC +# no type conversion occurs. +# +do_test whereB-2.1 { + db eval { + DROP TABLE t1; + DROP TABLE t2; + + CREATE TABLE t1(x, y TEXT); -- affinity of t1.y is TEXT + INSERT INTO t1 VALUES(1,99); + + CREATE TABLE t2(a, b BLOB); -- affinity of t2.b is NONE + CREATE INDEX t2b ON t2(b); + INSERT INTO t2 VALUES(2,99); + + SELECT x, a, y=b FROM t1, t2 ORDER BY +x, +a; + } +} {1 2 0} +do_test whereB-2.2 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {} +do_test whereB-2.3 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {} +do_test whereB-2.4 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} +do_test whereB-2.100 { + db eval { + DROP INDEX t2b; + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {} +do_test whereB-2.101 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {} +do_test whereB-2.102 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} + +# For this set of tests: +# +# * t1.y holds a text value with affinity NONE +# * t2.b holds an integer value with affinity NONE +# +# These values are not equal and because neither affinity is NUMERIC +# no type conversion occurs. +# +do_test whereB-3.1 { + db eval { + DROP TABLE t1; + DROP TABLE t2; + + CREATE TABLE t1(x, y BLOB); -- affinity of t1.y is NONE + INSERT INTO t1 VALUES(1,99); + + CREATE TABLE t2(a, b BLOB); -- affinity of t2.b is NONE + CREATE INDEX t2b ON t2(b); + INSERT INTO t2 VALUES(2,'99'); + + SELECT x, a, y=b FROM t1, t2; + } +} {1 2 0} +do_test whereB-3.2 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {} +do_test whereB-3.3 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {} +do_test whereB-3.4 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} +do_test whereB-3.100 { + db eval { + DROP INDEX t2b; + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {} +do_test whereB-3.101 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {} +do_test whereB-3.102 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} + + +# For this set of tests: +# +# * t1.y holds a text value with affinity NONE +# * t2.b holds an integer value with affinity NUMERIC +# +# Because t2.b has a numeric affinity, type conversion should occur +# and the two fields should be equal. +# +do_test whereB-4.1 { + db eval { + DROP TABLE t1; + DROP TABLE t2; + + CREATE TABLE t1(x, y BLOB); -- affinity of t1.y is NONE + INSERT INTO t1 VALUES(1,'99'); + + CREATE TABLE t2(a, b NUMERIC); -- affinity of t2.b is NUMERIC + CREATE INDEX t2b ON t2(b); + INSERT INTO t2 VALUES(2,99); + + SELECT x, a, y=b FROM t1, t2; + } +} {1 2 1} +do_test whereB-4.2 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-4.3 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-4.4 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} +do_test whereB-4.100 { + db eval { + DROP INDEX t2b; + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-4.101 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-4.102 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} + + + +# For this set of tests: +# +# * t1.y holds a text value with affinity NONE +# * t2.b holds an integer value with affinity INTEGER +# +# Because t2.b has a numeric affinity, type conversion should occur +# and the two fields should be equal. +# +do_test whereB-5.1 { + db eval { + DROP TABLE t1; + DROP TABLE t2; + + CREATE TABLE t1(x, y BLOB); -- affinity of t1.y is NONE + INSERT INTO t1 VALUES(1,'99'); + + CREATE TABLE t2(a, b INT); -- affinity of t2.b is INTEGER + CREATE INDEX t2b ON t2(b); + INSERT INTO t2 VALUES(2,99); + + SELECT x, a, y=b FROM t1, t2; + } +} {1 2 1} +do_test whereB-5.2 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-5.3 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-5.4 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} +do_test whereB-5.100 { + db eval { + DROP INDEX t2b; + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-5.101 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-5.102 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} + + +# For this set of tests: +# +# * t1.y holds a text value with affinity NONE +# * t2.b holds an integer value with affinity REAL +# +# Because t2.b has a numeric affinity, type conversion should occur +# and the two fields should be equal. +# +do_test whereB-6.1 { + db eval { + DROP TABLE t1; + DROP TABLE t2; + + CREATE TABLE t1(x, y BLOB); -- affinity of t1.y is NONE + INSERT INTO t1 VALUES(1,'99'); + + CREATE TABLE t2(a, b REAL); -- affinity of t2.b is REAL + CREATE INDEX t2b ON t2(b); + INSERT INTO t2 VALUES(2,99.0); + + SELECT x, a, y=b FROM t1, t2; + } +} {1 2 1} +do_test whereB-6.2 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-6.3 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-6.4 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} +do_test whereB-6.100 { + db eval { + DROP INDEX t2b; + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-6.101 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-6.102 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} + + +# For this set of tests: +# +# * t1.y holds an integer value with affinity NUMERIC +# * t2.b holds a text value with affinity NONE +# +# Because t1.y has a numeric affinity, type conversion should occur +# and the two fields should be equal. +# +do_test whereB-7.1 { + db eval { + DROP TABLE t1; + DROP TABLE t2; + + CREATE TABLE t1(x, y NUMERIC); -- affinity of t1.y is NUMERIC + INSERT INTO t1 VALUES(1,99); + + CREATE TABLE t2(a, b BLOB); -- affinity of t2.b is NONE + CREATE INDEX t2b ON t2(b); + INSERT INTO t2 VALUES(2,'99'); + + SELECT x, a, y=b FROM t1, t2; + } +} {1 2 1} +do_test whereB-7.2 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-7.3 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-7.4 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} +do_test whereB-7.100 { + db eval { + DROP INDEX t2b; + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-7.101 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-7.102 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} + +# For this set of tests: +# +# * t1.y holds an integer value with affinity INTEGER +# * t2.b holds a text value with affinity NONE +# +# Because t1.y has a numeric affinity, type conversion should occur +# and the two fields should be equal. +# +do_test whereB-8.1 { + db eval { + DROP TABLE t1; + DROP TABLE t2; + + CREATE TABLE t1(x, y INT); -- affinity of t1.y is INTEGER + INSERT INTO t1 VALUES(1,99); + + CREATE TABLE t2(a, b BLOB); -- affinity of t2.b is NONE + CREATE INDEX t2b ON t2(b); + INSERT INTO t2 VALUES(2,'99'); + + SELECT x, a, y=b FROM t1, t2; + } +} {1 2 1} +do_test whereB-8.2 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-8.3 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-8.4 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} +do_test whereB-8.100 { + db eval { + DROP INDEX t2b; + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-8.101 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-8.102 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} + +# For this set of tests: +# +# * t1.y holds an integer value with affinity REAL +# * t2.b holds a text value with affinity NONE +# +# Because t1.y has a numeric affinity, type conversion should occur +# and the two fields should be equal. +# +do_test whereB-9.1 { + db eval { + DROP TABLE t1; + DROP TABLE t2; + + CREATE TABLE t1(x, y REAL); -- affinity of t1.y is REAL + INSERT INTO t1 VALUES(1,99.0); + + CREATE TABLE t2(a, b BLOB); -- affinity of t2.b is NONE + CREATE INDEX t2b ON t2(b); + INSERT INTO t2 VALUES(2,'99'); + + SELECT x, a, y=b FROM t1, t2; + } +} {1 2 1} +do_test whereB-9.2 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-9.3 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-9.4 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} +do_test whereB-9.100 { + db eval { + DROP INDEX t2b; + SELECT x, a, y=b FROM t1, t2 WHERE y=b; + } +} {1 2 1} +do_test whereB-9.101 { + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE b=y; + } +} {1 2 1} +do_test whereB-9.102 { + # In this case the unary "+" operator removes the column affinity so + # the columns compare false + db eval { + SELECT x, a, y=b FROM t1, t2 WHERE +y=+b; + } +} {} + + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/whereC.test b/components/external/SQLite-3.8.1/test/whereC.test new file mode 100644 index 0000000000000000000000000000000000000000..bd7fe9ad82336fd5c398f3d548eaf9487916cf5e --- /dev/null +++ b/components/external/SQLite-3.8.1/test/whereC.test @@ -0,0 +1,69 @@ +# 2011 November 16 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix whereC + +do_execsql_test 1.0 { + CREATE TABLE t1(i INTEGER PRIMARY KEY, a, b INTEGER); + + INSERT INTO t1 VALUES(1, 1, 1); + INSERT INTO t1 VALUES(2, 1, 1); + INSERT INTO t1 VALUES(3, 1, 2); + INSERT INTO t1 VALUES(4, 1, 2); + INSERT INTO t1 VALUES(5, 1, 2); + INSERT INTO t1 VALUES(6, 1, 3); + INSERT INTO t1 VALUES(7, 1, 3); + + INSERT INTO t1 VALUES(8, 2, 1); + INSERT INTO t1 VALUES(9, 2, 1); + INSERT INTO t1 VALUES(10, 2, 2); + INSERT INTO t1 VALUES(11, 2, 2); + INSERT INTO t1 VALUES(12, 2, 2); + INSERT INTO t1 VALUES(13, 2, 3); + INSERT INTO t1 VALUES(14, 2, 3); + + INSERT INTO t1 VALUES(15, 2, 1); + INSERT INTO t1 VALUES(16, 2, 1); + INSERT INTO t1 VALUES(17, 2, 2); + INSERT INTO t1 VALUES(18, 2, 2); + INSERT INTO t1 VALUES(19, 2, 2); + INSERT INTO t1 VALUES(20, 2, 3); + INSERT INTO t1 VALUES(21, 2, 3); + + CREATE INDEX i1 ON t1(a, b); +} + +foreach {tn sql res} { + 1 "SELECT i FROM t1 WHERE a=1 AND b=2 AND i>3" {4 5} + 2 "SELECT i FROM t1 WHERE rowid='12'" {12} + 3 "SELECT i FROM t1 WHERE a=1 AND b='2'" {3 4 5} + 4 "SELECT i FROM t1 WHERE a=1 AND b='2' AND i>'3'" {4 5} + 5 "SELECT i FROM t1 WHERE a=1 AND b='2' AND i<5" {3 4} + 6 "SELECT i FROM t1 WHERE a=2 AND b=2 AND i<12" {10 11} + 7 "SELECT i FROM t1 WHERE a IN(1, 2) AND b=2 AND i<11" {3 4 5 10} + 8 "SELECT i FROM t1 WHERE a=2 AND b=2 AND i BETWEEN 10 AND 12" {10 11 12} + 9 "SELECT i FROM t1 WHERE a=2 AND b=2 AND i BETWEEN 11 AND 12" {11 12} + 10 "SELECT i FROM t1 WHERE a=2 AND b=2 AND i BETWEEN 10 AND 11" {10 11} + 11 "SELECT i FROM t1 WHERE a=2 AND b=2 AND i BETWEEN 12 AND 10" {} + 12 "SELECT i FROM t1 WHERE a=2 AND b=2 AND i=NULL" {} + 14 "SELECT i FROM t1 WHERE a=1 AND b='2' AND i<4.5" {3 4} +} { + do_execsql_test 1.$tn.1 $sql $res + do_execsql_test 1.$tn.2 "$sql ORDER BY i ASC" [lsort -integer -inc $res] + do_execsql_test 1.$tn.3 "$sql ORDER BY i DESC" [lsort -integer -dec $res] +} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/whereD.test b/components/external/SQLite-3.8.1/test/whereD.test new file mode 100644 index 0000000000000000000000000000000000000000..eb0f86402561d8f01751f2cea35b4b5c608fbfc3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/whereD.test @@ -0,0 +1,222 @@ +# 2012 August 24 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing that an index may be used as a covering +# index when there are OR expressions in the WHERE clause. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix whereD + +do_execsql_test 1.1 { + CREATE TABLE t(i,j,k,m,n); + CREATE INDEX ijk ON t(i,j,k); + CREATE INDEX jmn ON t(j,m,n); + + INSERT INTO t VALUES(3, 3, 'three', 3, 'tres'); + INSERT INTO t VALUES(2, 2, 'two', 2, 'dos'); + INSERT INTO t VALUES(1, 1, 'one', 1, 'uno'); + INSERT INTO t VALUES(4, 4, 'four', 4, 'cuatro'); +} + +do_execsql_test 1.2 { + SELECT k FROM t WHERE (i=1 AND j=1) OR (i=2 AND j=2); +} {one two} +do_execsql_test 1.3 { + SELECT k FROM t WHERE (i=1 AND j=1) OR (+i=2 AND j=2); +} {one two} +do_execsql_test 1.4 { + SELECT n FROM t WHERE (i=1 AND j=1) OR (i=2 AND j=2); +} {uno dos} +do_execsql_test 1.5 { + SELECT k, n FROM t WHERE (i=1 AND j=1) OR (i=2 AND j=2); +} {one uno two dos} +do_execsql_test 1.6 { + SELECT k FROM t WHERE (i=1 AND j=1) OR (i=2 AND j=2) OR (i=3 AND j=3); +} {one two three} +do_execsql_test 1.7 { + SELECT n FROM t WHERE (i=1 AND j=1) OR (i=2 AND j=2) OR (i=3 AND j=3); +} {uno dos tres} +do_execsql_test 1.8 { + SELECT k FROM t WHERE (i=1 AND j=1) OR (j=2 AND m=2); +} {one two} +do_execsql_test 1.9 { + SELECT k FROM t WHERE (i=1 AND j=1) OR (i=2 AND j=2) OR (j=3 AND m=3); +} {one two three} +do_execsql_test 1.10 { + SELECT n FROM t WHERE (i=1 AND j=1) OR (i=2 AND j=2) OR (j=3 AND m=3); +} {uno dos tres} +do_execsql_test 1.11 { + SELECT k FROM t WHERE (i=1 AND j=1) OR (j=2 AND m=2) OR (i=3 AND j=3); +} {one two three} +do_execsql_test 1.12 { + SELECT n FROM t WHERE (i=1 AND j=1) OR (j=2 AND m=2) OR (i=3 AND j=3); +} {uno dos tres} +do_execsql_test 1.13 { + SELECT k FROM t WHERE (j=1 AND m=1) OR (i=2 AND j=2) OR (i=3 AND j=3); +} {one two three} +do_execsql_test 1.14 { + SELECT k FROM t WHERE (i=1 AND j=1) OR (j=2 AND i=2) OR (i=3 AND j=3); +} {one two three} +do_execsql_test 1.15 { + SELECT k FROM t WHERE (i=1 AND j=2) OR (i=2 AND j=1) OR (i=3 AND j=4); +} {} +do_execsql_test 1.16 { + SELECT k FROM t WHERE (i=1 AND (j=1 or j=2)) OR (i=3 AND j=3); +} {one three} + +do_execsql_test 2.0 { + CREATE TABLE t1(a,b,c,d); + CREATE INDEX t1b ON t1(b); + CREATE INDEX t1c ON t1(c); + CREATE INDEX t1d ON t1(d); + CREATE TABLE t2(x,y); + CREATE INDEX t2y ON t2(y); + + INSERT INTO t1 VALUES(1,2,3,4); + INSERT INTO t1 VALUES(5,6,7,8); + INSERT INTO t2 VALUES(1,2); + INSERT INTO t2 VALUES(2,7); + INSERT INTO t2 VALUES(3,4); +} {} +do_execsql_test 2.1 { + SELECT a, x FROM t1 JOIN t2 ON +y=d OR x=7 ORDER BY a, x; +} {1 3} +do_execsql_test 2.2 { + SELECT a, x FROM t1 JOIN t2 ON y=d OR x=7 ORDER BY a, x; +} {1 3} + + +# Similar to [do_execsql_test], except that two elements are appended +# to the result - the string "search" and the number of times test variable +# sqlite3_search_count is incremented by running the supplied SQL. e.g. +# +# do_searchcount_test 1.0 { SELECT * FROM t1 } {x y search 2} +# +proc do_searchcount_test {tn sql res} { + uplevel [subst -nocommands { + do_test $tn { + set ::sqlite_search_count 0 + concat [db eval {$sql}] search [set ::sqlite_search_count] + } [list $res] + }] +} + +do_execsql_test 3.0 { + CREATE TABLE t3(a, b, c); + CREATE UNIQUE INDEX i3 ON t3(a, b); + INSERT INTO t3 VALUES(1, 'one', 'i'); + INSERT INTO t3 VALUES(3, 'three', 'iii'); + INSERT INTO t3 VALUES(6, 'six', 'vi'); + INSERT INTO t3 VALUES(2, 'two', 'ii'); + INSERT INTO t3 VALUES(4, 'four', 'iv'); + INSERT INTO t3 VALUES(5, 'five', 'v'); + + CREATE TABLE t4(x PRIMARY KEY, y); + INSERT INTO t4 VALUES('a', 'one'); + INSERT INTO t4 VALUES('b', 'two'); +} + +do_searchcount_test 3.1 { + SELECT a, b FROM t3 WHERE (a=1 AND b='one') OR (a=2 AND b='two') +} {1 one 2 two search 2} + +do_searchcount_test 3.2 { + SELECT a, c FROM t3 WHERE (a=1 AND b='one') OR (a=2 AND b='two') +} {1 i 2 ii search 4} + +do_searchcount_test 3.4.1 { + SELECT y FROM t4 WHERE x='a' +} {one search 2} +do_searchcount_test 3.4.2 { + SELECT a, b FROM t3 WHERE + (a=1 AND b=(SELECT y FROM t4 WHERE x='a')) + OR (a=2 AND b='two') +} {1 one 2 two search 4} +do_searchcount_test 3.4.3 { + SELECT a, b FROM t3 WHERE + (a=2 AND b='two') + OR (a=1 AND b=(SELECT y FROM t4 WHERE x='a')) +} {2 two 1 one search 4} +do_searchcount_test 3.4.4 { + SELECT a, b FROM t3 WHERE + (a=2 AND b=(SELECT y FROM t4 WHERE x='b')) + OR (a=1 AND b=(SELECT y FROM t4 WHERE x='a')) +} {2 two 1 one search 6} + +do_searchcount_test 3.5.1 { + SELECT a, b FROM t3 WHERE (a=1 AND b='one') OR rowid=4 +} {1 one 2 two search 2} +do_searchcount_test 3.5.2 { + SELECT a, c FROM t3 WHERE (a=1 AND b='one') OR rowid=4 +} {1 i 2 ii search 2} + +# Ticket [d02e1406a58ea02d] (2012-10-04) +# LEFT JOIN with an OR in the ON clause causes segfault +# +do_test 4.1 { + db eval { + CREATE TABLE t41(a,b,c); + INSERT INTO t41 VALUES(1,2,3), (4,5,6); + CREATE TABLE t42(d,e,f); + INSERT INTO t42 VALUES(3,6,9), (4,8,12); + SELECT * FROM t41 AS x LEFT JOIN t42 AS y ON (y.d=x.c) OR (y.e=x.b); + } +} {1 2 3 3 6 9 4 5 6 {} {} {}} +do_test 4.2 { + db eval { + CREATE INDEX t42d ON t42(d); + CREATE INDEX t42e ON t42(e); + SELECT * FROM t41 AS x LEFT JOIN t42 AS y ON (y.d=x.c) OR (y.e=x.b); + } +} {1 2 3 3 6 9 4 5 6 {} {} {}} +do_test 4.3 { + db eval { + SELECT * FROM t41 AS x LEFT JOIN t42 AS y ON (y.d=x.c) OR (y.d=x.b); + } +} {1 2 3 3 6 9 4 5 6 {} {} {}} + +# Ticket [bc1aea7b725f276177] +# Incorrect result on LEFT JOIN with OR constraints and an ORDER BY clause. +# +do_execsql_test 4.4 { + CREATE TABLE t44(a INTEGER, b INTEGER); + INSERT INTO t44 VALUES(1,2); + INSERT INTO t44 VALUES(3,4); + SELECT * + FROM t44 AS x + LEFT JOIN (SELECT a AS c, b AS d FROM t44) AS y ON a=c + WHERE d=4 OR d IS NULL; +} {3 4 3 4} +do_execsql_test 4.5 { + SELECT * + FROM t44 AS x + LEFT JOIN (SELECT a AS c, b AS d FROM t44) AS y ON a=c + WHERE d=4 OR d IS NULL + ORDER BY a; +} {3 4 3 4} +do_execsql_test 4.6 { + CREATE TABLE t46(c INTEGER, d INTEGER); + INSERT INTO t46 SELECT a, b FROM t44; + SELECT * FROM t44 LEFT JOIN t46 ON a=c + WHERE d=4 OR d IS NULL; +} {3 4 3 4} +do_execsql_test 4.7 { + SELECT * FROM t44 LEFT JOIN t46 ON a=c + WHERE d=4 OR d IS NULL + ORDER BY a; +} {3 4 3 4} + + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/whereE.test b/components/external/SQLite-3.8.1/test/whereE.test new file mode 100644 index 0000000000000000000000000000000000000000..a6b8f481b2e526c347ff1fa00e2e8ccb94ffb7ae --- /dev/null +++ b/components/external/SQLite-3.8.1/test/whereE.test @@ -0,0 +1,62 @@ +# 2012 November 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the query planner to make sure it +# is making good planning decisions. +# + + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set ::testprefix whereE + +do_execsql_test 1.1 { + CREATE TABLE t1(a,b); + INSERT INTO t1 VALUES(1,10), (2,20), (3,30), (2,22), (3, 33); + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + INSERT INTO t1 SELECT * FROM t1; + ALTER TABLE t1 ADD COLUMN c; + UPDATE t1 SET c=a*rowid+10000; + CREATE INDEX t1ab ON t1(a,b); + + CREATE TABLE t2(x,y); + INSERT INTO t2 VALUES(4,44),(5,55),(6,66),(7,77); + INSERT INTO t2 SELECT x+4, (x+4)*11 FROM t2; + INSERT INTO t2 SELECT x+8, (x+8)*11 FROM t2; + INSERT INTO t2 SELECT x+16, (x+16)*11 FROM t2; + INSERT INTO t2 SELECT x+32, (x+32)*11 FROM t2; + INSERT INTO t2 SELECT x+64, (x+32)*11 FROM t2; + ALTER TABLE t2 ADD COLUMN z; + UPDATE t2 SET z=2; + CREATE UNIQUE INDEX t2zx ON t2(z,x); + + EXPLAIN QUERY PLAN SELECT x FROM t1, t2 WHERE a=z AND c=x; +} {/.*SCAN TABLE t1.*SEARCH TABLE t2.*/} +do_execsql_test 1.2 { + EXPLAIN QUERY PLAN SELECT x FROM t2, t1 WHERE a=z AND c=x; +} {/.*SCAN TABLE t1.*SEARCH TABLE t2.*/} +do_execsql_test 1.3 { + ANALYZE; + EXPLAIN QUERY PLAN SELECT x FROM t1, t2 WHERE a=z AND c=x; +} {/.*SCAN TABLE t1.*SEARCH TABLE t2.*/} +do_execsql_test 1.4 { + EXPLAIN QUERY PLAN SELECT x FROM t2, t1 WHERE a=z AND c=x; +} {/.*SCAN TABLE t1.*SEARCH TABLE t2.*/} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/whereF.test b/components/external/SQLite-3.8.1/test/whereF.test new file mode 100644 index 0000000000000000000000000000000000000000..b9580bb196d200054c3e5d0802ec3a000b3e76f3 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/whereF.test @@ -0,0 +1,122 @@ +# 2012 November 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test cases for query planning decisions. + + +# +# The tests in this file demonstrate the behaviour of the query planner +# in determining the order in which joined tables are scanned. +# +# Assume there are two tables being joined - t1 and t2. Each has a cost +# if it is the outer loop, and a cost if it is the inner loop. As follows: +# +# t1(outer) - cost of scanning t1 as the outer loop. +# t1(inner) - cost of scanning t1 as the inner loop. +# t2(outer) - cost of scanning t2 as the outer loop. +# t2(inner) - cost of scanning t2 as the inner loop. +# +# Depending on the order in which the planner nests the scans, the total +# cost of the join query is one of: +# +# t1(outer) * t2(inner) +# t2(outer) * t1(inner) +# +# The tests in this file attempt to verify that the planner nests joins in +# the correct order when the following are true: +# +# + (t1(outer) * t2(inner)) > (t1(inner) * t2(outer) +# + t1(outer) < t2(outer) +# +# In other words, when the best overall query plan has t2 as the outer loop, +# but when the outer loop is considered independent of the inner, t1 is the +# most efficient choice. +# +# In order to make them more predictable, automatic indexes are turned off for +# the tests in this file. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix whereF + +do_execsql_test 1.0 { + PRAGMA automatic_index = 0; + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(d, e, f); + CREATE UNIQUE INDEX i1 ON t1(a); + CREATE UNIQUE INDEX i2 ON t2(d); +} {} + +foreach {tn sql} { + 1 "SELECT * FROM t1, t2 WHERE t1.a=t2.e AND t2.d? AND t2.d>t1.c AND t1.b=t2.e" + 2 "SELECT * FROM t2, t1 WHERE t1.a>? AND t2.d>t1.c AND t1.b=t2.e" + 3 "SELECT * FROM t2 CROSS JOIN t1 WHERE t1.a>? AND t2.d>t1.c AND t1.b=t2.e" +} { + do_test 2.$tn { + db eval "EXPLAIN QUERY PLAN $sql" + } {/.*SCAN TABLE t2\y.*SEARCH TABLE t1\y.*/} +} + +do_execsql_test 3.0 { + DROP TABLE t1; + DROP TABLE t2; + CREATE TABLE t1(a, b, c); + CREATE TABLE t2(d, e, f); + + CREATE UNIQUE INDEX i1 ON t1(a, b); + CREATE INDEX i2 ON t2(d); +} {} + +foreach {tn sql} { + 1 {SELECT t1.a, t1.b, t2.d, t2.e FROM t1, t2 + WHERE t2.d=t1.b AND t1.a=(t2.d+1) AND t1.b = (t2.e+1)} + + 2 {SELECT t1.a, t1.b, t2.d, t2.e FROM t2, t1 + WHERE t2.d=t1.b AND t1.a=(t2.d+1) AND t1.b = (t2.e+1)} + + 3 {SELECT t1.a, t1.b, t2.d, t2.e FROM t2 CROSS JOIN t1 + WHERE t2.d=t1.b AND t1.a=(t2.d+1) AND t1.b = (t2.e+1)} +} { + do_test 3.$tn { + db eval "EXPLAIN QUERY PLAN $sql" + } {/.*SCAN TABLE t2\y.*SEARCH TABLE t1\y.*/} +} + +do_execsql_test 4.0 { + CREATE TABLE t4(a,b,c,d,e, PRIMARY KEY(a,b,c)); + CREATE INDEX t4adc ON t4(a,d,c); + CREATE UNIQUE INDEX t4aebc ON t4(a,e,b,c); + EXPLAIN QUERY PLAN SELECT rowid FROM t4 WHERE a=? AND b=?; +} {/a=. AND b=./} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/whereG.test b/components/external/SQLite-3.8.1/test/whereG.test new file mode 100644 index 0000000000000000000000000000000000000000..1b6a861855bbafc0d37d5e4f4d46bc45e70ebe57 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/whereG.test @@ -0,0 +1,170 @@ +# 2013-09-05 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# Test cases for query planning decisions and the unlikely() and +# likelihood() functions. + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +do_execsql_test whereG-1.0 { + CREATE TABLE composer( + cid INTEGER PRIMARY KEY, + cname TEXT + ); + CREATE TABLE album( + aid INTEGER PRIMARY KEY, + aname TEXT + ); + CREATE TABLE track( + tid INTEGER PRIMARY KEY, + cid INTEGER REFERENCES composer, + aid INTEGER REFERENCES album, + title TEXT + ); + CREATE INDEX track_i1 ON track(cid); + CREATE INDEX track_i2 ON track(aid); + INSERT INTO composer VALUES(1, 'W. A. Mozart'); + INSERT INTO composer VALUES(2, 'Beethoven'); + INSERT INTO composer VALUES(3, 'Thomas Tallis'); + INSERT INTO composer VALUES(4, 'Joseph Hayden'); + INSERT INTO composer VALUES(5, 'Thomas Weelkes'); + INSERT INTO composer VALUES(6, 'J. S. Bach'); + INSERT INTO composer VALUES(7, 'Orlando Gibbons'); + INSERT INTO composer VALUES(8, 'Josquin des Prés'); + INSERT INTO composer VALUES(9, 'Byrd'); + INSERT INTO composer VALUES(10, 'Francis Poulenc'); + INSERT INTO composer VALUES(11, 'Mendelsshon'); + INSERT INTO composer VALUES(12, 'Zoltán Kodály'); + INSERT INTO composer VALUES(13, 'Handel'); + INSERT INTO album VALUES(100, 'Kodály: Missa Brevis'); + INSERT INTO album VALUES(101, 'Messiah'); + INSERT INTO album VALUES(102, 'Missa Brevis in D-, K.65'); + INSERT INTO album VALUES(103, 'The complete English anthems'); + INSERT INTO album VALUES(104, 'Mass in B Minor, BWV 232'); + INSERT INTO track VALUES(10005, 12, 100, 'Sanctus'); + INSERT INTO track VALUES(10007, 12, 100, 'Agnus Dei'); + INSERT INTO track VALUES(10115, 13, 101, 'Surely He Hath Borne Our Griefs'); + INSERT INTO track VALUES(10129, 13, 101, 'Since By Man Came Death'); + INSERT INTO track VALUES(10206, 1, 102, 'Agnus Dei'); + INSERT INTO track VALUES(10301, 3, 103, 'If Ye Love Me'); + INSERT INTO track VALUES(10402, 6, 104, 'Domine Deus'); + INSERT INTO track VALUES(10403, 6, 104, 'Qui tollis'); +} {} +do_eqp_test whereG-1.1 { + SELECT DISTINCT aname + FROM album, composer, track + WHERE unlikely(cname LIKE '%bach%') + AND composer.cid=track.cid + AND album.aid=track.aid; +} {/.*composer.*track.*album.*/} +do_execsql_test whereG-1.2 { + SELECT DISTINCT aname + FROM album, composer, track + WHERE unlikely(cname LIKE '%bach%') + AND composer.cid=track.cid + AND album.aid=track.aid; +} {{Mass in B Minor, BWV 232}} + +do_eqp_test whereG-1.3 { + SELECT DISTINCT aname + FROM album, composer, track + WHERE likelihood(cname LIKE '%bach%', 0.5) + AND composer.cid=track.cid + AND album.aid=track.aid; +} {/.*track.*composer.*album.*/} +do_execsql_test whereG-1.4 { + SELECT DISTINCT aname + FROM album, composer, track + WHERE likelihood(cname LIKE '%bach%', 0.5) + AND composer.cid=track.cid + AND album.aid=track.aid; +} {{Mass in B Minor, BWV 232}} + +do_eqp_test whereG-1.5 { + SELECT DISTINCT aname + FROM album, composer, track + WHERE cname LIKE '%bach%' + AND composer.cid=track.cid + AND album.aid=track.aid; +} {/.*track.*composer.*album.*/} +do_execsql_test whereG-1.6 { + SELECT DISTINCT aname + FROM album, composer, track + WHERE cname LIKE '%bach%' + AND composer.cid=track.cid + AND album.aid=track.aid; +} {{Mass in B Minor, BWV 232}} + +do_eqp_test whereG-1.7 { + SELECT DISTINCT aname + FROM album, composer, track + WHERE cname LIKE '%bach%' + AND unlikely(composer.cid=track.cid) + AND unlikely(album.aid=track.aid); +} {/.*track.*composer.*album.*/} +do_execsql_test whereG-1.8 { + SELECT DISTINCT aname + FROM album, composer, track + WHERE cname LIKE '%bach%' + AND unlikely(composer.cid=track.cid) + AND unlikely(album.aid=track.aid); +} {{Mass in B Minor, BWV 232}} + +do_test whereG-2.1 { + catchsql { + SELECT DISTINCT aname + FROM album, composer, track + WHERE likelihood(cname LIKE '%bach%', -0.01) + AND composer.cid=track.cid + AND album.aid=track.aid; + } +} {1 {second argument to likelihood() must be a constant between 0.0 and 1.0}} +do_test whereG-2.2 { + catchsql { + SELECT DISTINCT aname + FROM album, composer, track + WHERE likelihood(cname LIKE '%bach%', 1.01) + AND composer.cid=track.cid + AND album.aid=track.aid; + } +} {1 {second argument to likelihood() must be a constant between 0.0 and 1.0}} +do_test whereG-2.3 { + catchsql { + SELECT DISTINCT aname + FROM album, composer, track + WHERE likelihood(cname LIKE '%bach%', track.cid) + AND composer.cid=track.cid + AND album.aid=track.aid; + } +} {1 {second argument to likelihood() must be a constant between 0.0 and 1.0}} + +# Commuting a term of the WHERE clause should not change the query plan +# +do_execsql_test whereG-3.0 { + CREATE TABLE a(a1 PRIMARY KEY, a2); + CREATE TABLE b(b1 PRIMARY KEY, b2); +} {} +do_eqp_test whereG-3.1 { + SELECT * FROM a, b WHERE b1=a1 AND a2=5; +} {/.*SCAN TABLE a.*SEARCH TABLE b USING INDEX .*b_1 .b1=..*/} +do_eqp_test whereG-3.2 { + SELECT * FROM a, b WHERE a1=b1 AND a2=5; +} {/.*SCAN TABLE a.*SEARCH TABLE b USING INDEX .*b_1 .b1=..*/} +do_eqp_test whereG-3.3 { + SELECT * FROM a, b WHERE a2=5 AND b1=a1; +} {/.*SCAN TABLE a.*SEARCH TABLE b USING INDEX .*b_1 .b1=..*/} +do_eqp_test whereG-3.4 { + SELECT * FROM a, b WHERE a2=5 AND a1=b1; +} {/.*SCAN TABLE a.*SEARCH TABLE b USING INDEX .*b_1 .b1=..*/} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wherelimit.test b/components/external/SQLite-3.8.1/test/wherelimit.test new file mode 100644 index 0000000000000000000000000000000000000000..f0cfbb61e85eac1b8276dfd74b193e3b97f26717 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wherelimit.test @@ -0,0 +1,284 @@ +# 2008 October 6 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing the LIMIT ... OFFSET ... clause +# of UPDATE and DELETE statements. +# +# $Id: wherelimit.test,v 1.2 2008/10/10 18:25:46 shane Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +proc create_test_data {size} { + # Build some test data + # + execsql { + DROP TABLE IF EXISTS t1; + CREATE TABLE t1(x int, y int); + BEGIN; + } + for {set i 1} {$i<=$size} {incr i} { + for {set j 1} {$j<=$size} {incr j} { + execsql "INSERT INTO t1 VALUES([expr {$i}],[expr {$j}])" + } + } + execsql { + COMMIT; + } + return {} +} + +ifcapable {update_delete_limit} { + + # check syntax error support + do_test wherelimit-0.1 { + catchsql {DELETE FROM t1 ORDER BY x} + } {1 {ORDER BY without LIMIT on DELETE}} + do_test wherelimit-0.2 { + catchsql {DELETE FROM t1 WHERE x=1 ORDER BY x} + } {1 {ORDER BY without LIMIT on DELETE}} + do_test wherelimit-0.3 { + catchsql {UPDATE t1 SET y=1 WHERE x=1 ORDER BY x} + } {1 {ORDER BY without LIMIT on UPDATE}} + + # no AS on table sources + do_test wherelimit-0.4 { + catchsql {DELETE FROM t1 AS a WHERE x=1} + } {1 {near "AS": syntax error}} + do_test wherelimit-0.5 { + catchsql {UPDATE t1 AS a SET y=1 WHERE x=1} + } {1 {near "AS": syntax error}} + + # OFFSET w/o LIMIT + do_test wherelimit-0.6 { + catchsql {DELETE FROM t1 WHERE x=1 OFFSET 2} + } {1 {near "OFFSET": syntax error}} + do_test wherelimit-0.7 { + catchsql {UPDATE t1 SET y=1 WHERE x=1 OFFSET 2} + } {1 {near "OFFSET": syntax error}} + + + # check deletes w/o where clauses but with limit/offsets + create_test_data 5 + do_test wherelimit-1.0 { + execsql {SELECT count(*) FROM t1} + } {25} + do_test wherelimit-1.1 { + execsql {DELETE FROM t1} + execsql {SELECT count(*) FROM t1} + } {0} + create_test_data 5 + do_test wherelimit-1.2 { + execsql {DELETE FROM t1 LIMIT 5} + execsql {SELECT count(*) FROM t1} + } {20} + do_test wherelimit-1.3 { + # limit 5 + execsql {DELETE FROM t1 ORDER BY x LIMIT 5} + execsql {SELECT count(*) FROM t1} + } {15} + do_test wherelimit-1.4 { + # limit 5, offset 2 + execsql {DELETE FROM t1 ORDER BY x LIMIT 5 OFFSET 2} + execsql {SELECT count(*) FROM t1} + } {10} + do_test wherelimit-1.5 { + # limit 5, offset -2 + execsql {DELETE FROM t1 ORDER BY x LIMIT 5 OFFSET -2} + execsql {SELECT count(*) FROM t1} + } {5} + do_test wherelimit-1.6 { + # limit -5 (no limit), offset 2 + execsql {DELETE FROM t1 ORDER BY x LIMIT 2, -5} + execsql {SELECT count(*) FROM t1} + } {2} + do_test wherelimit-1.7 { + # limit 5, offset -2 (no offset) + execsql {DELETE FROM t1 ORDER BY x LIMIT -2, 5} + execsql {SELECT count(*) FROM t1} + } {0} + create_test_data 5 + do_test wherelimit-1.8 { + # limit -5 (no limit), offset -2 (no offset) + execsql {DELETE FROM t1 ORDER BY x LIMIT -2, -5} + execsql {SELECT count(*) FROM t1} + } {0} + create_test_data 3 + do_test wherelimit-1.9 { + # limit 5, offset 2 + execsql {DELETE FROM t1 ORDER BY x LIMIT 2, 5} + execsql {SELECT count(*) FROM t1} + } {4} + do_test wherelimit-1.10 { + # limit 5, offset 5 + execsql {DELETE FROM t1 ORDER BY x LIMIT 5 OFFSET 5} + execsql {SELECT count(*) FROM t1} + } {4} + do_test wherelimit-1.11 { + # limit 50, offset 30 + execsql {DELETE FROM t1 ORDER BY x LIMIT 50 OFFSET 30} + execsql {SELECT count(*) FROM t1} + } {4} + do_test wherelimit-1.12 { + # limit 50, offset 30 + execsql {DELETE FROM t1 ORDER BY x LIMIT 30, 50} + execsql {SELECT count(*) FROM t1} + } {4} + do_test wherelimit-1.13 { + execsql {DELETE FROM t1 ORDER BY x LIMIT 50 OFFSET 50} + execsql {SELECT count(*) FROM t1} + } {4} + + + create_test_data 6 + do_test wherelimit-2.0 { + execsql {SELECT count(*) FROM t1} + } {36} + do_test wherelimit-2.1 { + execsql {DELETE FROM t1 WHERE x=1} + execsql {SELECT count(*) FROM t1} + } {30} + create_test_data 6 + do_test wherelimit-2.2 { + execsql {DELETE FROM t1 WHERE x=1 LIMIT 5} + execsql {SELECT count(*) FROM t1} + } {31} + do_test wherelimit-2.3 { + # limit 5 + execsql {DELETE FROM t1 WHERE x=1 ORDER BY x LIMIT 5} + execsql {SELECT count(*) FROM t1} + } {30} + do_test wherelimit-2.4 { + # limit 5, offset 2 + execsql {DELETE FROM t1 WHERE x=2 ORDER BY x LIMIT 5 OFFSET 2} + execsql {SELECT count(*) FROM t1} + } {26} + do_test wherelimit-2.5 { + # limit 5, offset -2 + execsql {DELETE FROM t1 WHERE x=2 ORDER BY x LIMIT 5 OFFSET -2} + execsql {SELECT count(*) FROM t1} + } {24} + do_test wherelimit-2.6 { + # limit -5 (no limit), offset 2 + execsql {DELETE FROM t1 WHERE x=3 ORDER BY x LIMIT 2, -5} + execsql {SELECT count(*) FROM t1} + } {20} + do_test wherelimit-2.7 { + # limit 5, offset -2 (no offset) + execsql {DELETE FROM t1 WHERE x=3 ORDER BY x LIMIT -2, 5} + execsql {SELECT count(*) FROM t1} + } {18} + do_test wherelimit-2.8 { + # limit -5 (no limit), offset -2 (no offset) + execsql {DELETE FROM t1 WHERE x=4 ORDER BY x LIMIT -2, -5} + execsql {SELECT count(*) FROM t1} + } {12} + create_test_data 6 + do_test wherelimit-2.9 { + # limit 5, offset 2 + execsql {DELETE FROM t1 WHERE x=5 ORDER BY x LIMIT 2, 5} + execsql {SELECT count(*) FROM t1} + } {32} + do_test wherelimit-2.10 { + # limit 5, offset 5 + execsql {DELETE FROM t1 WHERE x=6 ORDER BY x LIMIT 5 OFFSET 5} + execsql {SELECT count(*) FROM t1} + } {31} + do_test wherelimit-2.11 { + # limit 50, offset 30 + execsql {DELETE FROM t1 WHERE x=1 ORDER BY x LIMIT 50 OFFSET 30} + execsql {SELECT count(*) FROM t1} + } {31} + do_test wherelimit-2.12 { + # limit 50, offset 30 + execsql {DELETE FROM t1 WHERE x=2 ORDER BY x LIMIT 30, 50} + execsql {SELECT count(*) FROM t1} + } {31} + do_test wherelimit-2.13 { + execsql {DELETE FROM t1 WHERE x=3 ORDER BY x LIMIT 50 OFFSET 50} + execsql {SELECT count(*) FROM t1} + } {31} + + + create_test_data 6 + do_test wherelimit-3.0 { + execsql {SELECT count(*) FROM t1} + } {36} + do_test wherelimit-3.1 { + execsql {UPDATE t1 SET y=1 WHERE x=1} + execsql {SELECT count(*) FROM t1 WHERE y=1} + } {11} + create_test_data 6 + do_test wherelimit-3.2 { + execsql {UPDATE t1 SET y=1 WHERE x=1 LIMIT 5} + execsql {SELECT count(*) FROM t1 WHERE y=1} + } {10} + do_test wherelimit-3.3 { + # limit 5 + execsql {UPDATE t1 SET y=2 WHERE x=2 ORDER BY x LIMIT 5} + execsql {SELECT count(*) FROM t1 WHERE y=2} + } {9} + create_test_data 6 + do_test wherelimit-3.4 { + # limit 5, offset 2 + execsql {UPDATE t1 SET y=2 WHERE x=2 ORDER BY x LIMIT 5 OFFSET 2} + execsql {SELECT count(*) FROM t1 WHERE y=1} + } {6} + do_test wherelimit-3.5 { + # limit 5, offset -2 + execsql {UPDATE t1 SET y=2 WHERE x=2 ORDER BY x LIMIT 5 OFFSET -2} + execsql {SELECT count(*) FROM t1 WHERE y=1} + } {5} + do_test wherelimit-3.6 { + # limit -5 (no limit), offset 2 + execsql {UPDATE t1 SET y=3 WHERE x=3 ORDER BY x LIMIT 2, -5} + execsql {SELECT count(*) FROM t1 WHERE y=3} + } {8} + do_test wherelimit-3.7 { + # limit 5, offset -2 (no offset) + execsql {UPDATE t1 SET y=3 WHERE x=3 ORDER BY x LIMIT -2, 5} + execsql {SELECT count(*) FROM t1 WHERE y=3} + } {10} + + do_test wherelimit-3.8 { + # limit -5 (no limit), offset -2 (no offset) + execsql {UPDATE t1 SET y=4 WHERE x=4 ORDER BY x LIMIT -2, -5} + execsql {SELECT count(*) FROM t1 WHERE y=4} + } {9} + create_test_data 6 + do_test wherelimit-3.9 { + # limit 5, offset 2 + execsql {UPDATE t1 SET y=4 WHERE x=5 ORDER BY x LIMIT 2, 5} + execsql {SELECT count(*) FROM t1 WHERE y=4} + } {9} + do_test wherelimit-3.10 { + # limit 5, offset 5 + execsql {UPDATE t1 SET y=4 WHERE x=6 ORDER BY x LIMIT 5 OFFSET 5} + execsql {SELECT count(*) FROM t1 WHERE y=1} + } {6} + do_test wherelimit-3.11 { + # limit 50, offset 30 + execsql {UPDATE t1 SET y=1 WHERE x=1 ORDER BY x LIMIT 50 OFFSET 30} + execsql {SELECT count(*) FROM t1 WHERE y=1} + } {6} + do_test wherelimit-3.12 { + # limit 50, offset 30 + execsql {UPDATE t1 SET y=1 WHERE x=2 ORDER BY x LIMIT 30, 50} + execsql {SELECT count(*) FROM t1 WHERE y=1} + } {6} + do_test wherelimit-3.13 { + execsql {UPDATE t1 SET y=1 WHERE x=3 ORDER BY x LIMIT 50 OFFSET 50} + execsql {SELECT count(*) FROM t1 WHERE y=1} + } {6} + +} + +finish_test diff --git a/components/external/SQLite-3.8.1/test/wild001.test b/components/external/SQLite-3.8.1/test/wild001.test new file mode 100644 index 0000000000000000000000000000000000000000..7fe140429428524536142a3e436cc9c3950c21d4 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/wild001.test @@ -0,0 +1,311 @@ +# 2013-07-01 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This is a test case from content taken "from the wild". In this +# particular instance, the query was provided with permission by +# Elan Feingold on 2013-06-27. His message on the SQLite mailing list +# on that date reads: +# +#------------------------------------------------------------------------------ +# > Can you send (1) the schema (2) the query that is giving problems, and (3) +# > the content of the sqlite_stat1 table after you have run ANALYZE? If you +# > can combine all of the above into a script, that would be great! +# > +# > If you send (1..3) above and you give us written permission to include the +# > query in our test suite, that would be off-the-chain terrific. +# +# Please find items 1..3 in this file: http://www.plexapp.com/elan/sqlite_bug.txt +# +# You have our permission to include the query in your test suite. +# +# Thanks for an amazing product. +#----------------------------------------------------------------------------- +# +# This test case merely creates the schema and populates SQLITE_STAT1 and +# SQLITE_STAT3 then runs an EXPLAIN QUERY PLAN to ensure that the right plan +# is discovered. This test case may need to be adjusted for future revisions +# of the query planner manage to select a better query plan. The query plan +# shown here is known to be very fast with the original data. +# +# This test should work the same with and without SQLITE_ENABLE_STAT3 +# +############################################################################### + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !stat3 { + finish_test + return +} + +do_execsql_test wild001.01 { + CREATE TABLE "items" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "secid" integer, "parent_id" integer, "metadata_type" integer, "guid" varchar(255), "media_item_count" integer, "title" varchar(255), "title_sort" varchar(255) COLLATE NOCASE, "original_title" varchar(255), "studio" varchar(255), "rating" float, "rating_count" integer, "tagline" varchar(255), "summary" text, "trivia" text, "quotes" text, "content_rating" varchar(255), "content_rating_age" integer, "index" integer, "absolute_index" integer, "duration" integer, "user_thumb_url" varchar(255), "user_art_url" varchar(255), "user_banner_url" varchar(255), "user_music_url" varchar(255), "user_fields" varchar(255), "tags_genre" varchar(255), "tags_collection" varchar(255), "tags_director" varchar(255), "tags_writer" varchar(255), "tags_star" varchar(255), "originally_available_at" datetime, "available_at" datetime, "expires_at" datetime, "refreshed_at" datetime, "year" integer, "added_at" datetime, "created_at" datetime, "updated_at" datetime, "deleted_at" datetime, "tags_country" varchar(255), "extra_data" varchar(255), "hash" varchar(255)); + CREATE INDEX "i_secid" ON "items" ("secid" ); + CREATE INDEX "i_parent_id" ON "items" ("parent_id" ); + CREATE INDEX "i_created_at" ON "items" ("created_at" ); + CREATE INDEX "i_index" ON "items" ("index" ); + CREATE INDEX "i_title" ON "items" ("title" ); + CREATE INDEX "i_title_sort" ON "items" ("title_sort" ); + CREATE INDEX "i_guid" ON "items" ("guid" ); + CREATE INDEX "i_metadata_type" ON "items" ("metadata_type" ); + CREATE INDEX "i_deleted_at" ON "items" ("deleted_at" ); + CREATE INDEX "i_secid_ex1" ON "items" ("secid", "metadata_type", "added_at" ); + CREATE INDEX "i_hash" ON "items" ("hash" ); + CREATE TABLE "settings" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "account_id" integer, "guid" varchar(255), "rating" float, "view_offset" integer, "view_count" integer, "last_viewed_at" datetime, "created_at" datetime, "updated_at" datetime); + CREATE INDEX "s_account_id" ON "settings" ("account_id" ); + CREATE INDEX "s_guid" ON "settings" ("guid" ); + ANALYZE; + INSERT INTO sqlite_stat1 VALUES('settings','s_guid','4740 1'); + INSERT INTO sqlite_stat1 VALUES('settings','s_account_id','4740 4740'); + INSERT INTO sqlite_stat1 VALUES('items','i_hash','27316 2'); + INSERT INTO sqlite_stat1 VALUES('items','i_secid_ex1','27316 6829 4553 3'); + INSERT INTO sqlite_stat1 VALUES('items','i_deleted_at','27316 27316'); + INSERT INTO sqlite_stat1 VALUES('items','i_metadata_type','27316 6829'); + INSERT INTO sqlite_stat1 VALUES('items','i_guid','27316 2'); + INSERT INTO sqlite_stat1 VALUES('items','i_title_sort','27316 2'); + INSERT INTO sqlite_stat1 VALUES('items','i_title','27316 2'); + INSERT INTO sqlite_stat1 VALUES('items','i_index','27316 144'); + INSERT INTO sqlite_stat1 VALUES('items','i_created_at','27316 2'); + INSERT INTO sqlite_stat1 VALUES('items','i_parent_id','27316 15'); + INSERT INTO sqlite_stat1 VALUES('items','i_secid','27316 6829'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,150,150,'com.plexapp.agents.thetvdb://153021/2/9?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,198,198,'com.plexapp.agents.thetvdb://194031/1/10?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,526,526,'com.plexapp.agents.thetvdb://71256/12/92?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,923,923,'com.plexapp.agents.thetvdb://71256/15/16?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,1008,1008,'com.plexapp.agents.thetvdb://71256/15/93?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,1053,1053,'com.plexapp.agents.thetvdb://71256/16/21?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,1068,1068,'com.plexapp.agents.thetvdb://71256/16/35?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,1235,1235,'com.plexapp.agents.thetvdb://71256/17/44?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,1255,1255,'com.plexapp.agents.thetvdb://71256/17/62?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,1573,1573,'com.plexapp.agents.thetvdb://71663/20/9?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,1580,1580,'com.plexapp.agents.thetvdb://71663/21/16?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,2000,2000,'com.plexapp.agents.thetvdb://73141/9/8?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,2107,2107,'com.plexapp.agents.thetvdb://73244/6/17?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,2256,2256,'com.plexapp.agents.thetvdb://74845/4/7?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,2408,2408,'com.plexapp.agents.thetvdb://75978/2/21?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,2634,2634,'com.plexapp.agents.thetvdb://79126/1/1?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,2962,2962,'com.plexapp.agents.thetvdb://79274/3/94?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,3160,3160,'com.plexapp.agents.thetvdb://79274/5/129?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,3161,3161,'com.plexapp.agents.thetvdb://79274/5/12?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,3688,3688,'com.plexapp.agents.thetvdb://79274/8/62?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,3714,3714,'com.plexapp.agents.thetvdb://79274/8/86?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,4002,4002,'com.plexapp.agents.thetvdb://79590/13/17?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,4215,4215,'com.plexapp.agents.thetvdb://80727/3/6?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_guid',1,4381,4381,'com.plexapp.agents.thetvdb://83462/3/24?lang=en'); + INSERT INTO sqlite_stat3 VALUES('settings','s_account_id',4740,0,0,1); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,1879,1879,'1113f632ccd52ec8b8d7ca3d6d56da4701e48018'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,2721,2721,'1936154b97bb5567163edaebc2806830ae419ccf'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,3035,3035,'1c122331d4b7bfa0dc2c003ab5fb4f7152b9987a'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',2,3393,3393,'1f81bdbc9acc3321dc592b1a109ca075731b549a'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,6071,6070,'393cf7713efb4519c7a3d1d5403f0d945d15a16a'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,7462,7461,'4677dd37011f8bd9ae7fbbdd3af6dcd8a5b4ab2d'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',2,8435,8434,'4ffa339485334e81a5e12e03a63b6508d76401cf'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',2,8716,8714,'52a093852e6599dd5004857b7ff5b5b82c7cdb25'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,9107,9104,'561183e39f866d97ec728e9ff16ac4ad01466111'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',2,10942,10939,'66e99b72e29610f49499ae09ee04a376210d1f08'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,12143,12139,'71f0602427e173dc2c551535f73fdb6885fe4302'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',2,14962,14958,'8ca8e4dfba696019830c19ab8a32c7ece9d8534b'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,15179,15174,'8ebf1a5cf33f8ada1fc5853ac06ac4d7e074f825'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,15375,15370,'908bc211bebdf21c79d2d2b54ebaa442ac1f5cae'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,18215,18210,'ab29e4e18ec5a14fef95aa713d69e31c045a22c1'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,18615,18610,'ae84c008cc0c338bf4f28d798a88575746452f6d'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,18649,18644,'aec7c901353e115aa5307e94018ba7507bec3a45'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',2,19517,19512,'b75025fbf2e9c504e3c1197ff1b69250402a31f8'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,21251,21245,'c7d32f0e3a8f3a0a3dbd00833833d2ccee62f0fd'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',2,23616,23610,'dd5ff61479a9bd4100de802515d9dcf72d46f07a'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,24287,24280,'e3db00034301b7555419d4ef6f64769298d5845e'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,24949,24942,'ea336abd197ecd7013854a25a4f4eb9dea7927c6'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',1,25574,25567,'f018ea5182ec3f32768ca1c3cefbf3ad160ec20b'); + INSERT INTO sqlite_stat3 VALUES('items','i_hash',2,26139,26132,'f53709a8d81c12cb0f4f8d58004a25dd063de67c'); + INSERT INTO sqlite_stat3 VALUES('items','i_secid_ex1',25167,0,0,2); + INSERT INTO sqlite_stat3 VALUES('items','i_secid_ex1',736,25167,1,3); + INSERT INTO sqlite_stat3 VALUES('items','i_secid_ex1',15,25903,2,4); + INSERT INTO sqlite_stat3 VALUES('items','i_secid_ex1',1398,25918,3,5); + INSERT INTO sqlite_stat3 VALUES('items','i_deleted_at',27316,0,0,NULL); + INSERT INTO sqlite_stat3 VALUES('items','i_metadata_type',2149,0,0,1); + INSERT INTO sqlite_stat3 VALUES('items','i_metadata_type',411,2149,1,2); + INSERT INTO sqlite_stat3 VALUES('items','i_metadata_type',1440,2560,2,3); + INSERT INTO sqlite_stat3 VALUES('items','i_metadata_type',23316,4000,3,4); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,215,215,'com.plexapp.agents.imdb://tt0065702?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',2,711,711,'com.plexapp.agents.imdb://tt0198781?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',2,987,986,'com.plexapp.agents.imdb://tt0454876?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',2,1004,1002,'com.plexapp.agents.imdb://tt0464154?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',2,1056,1053,'com.plexapp.agents.imdb://tt0499549?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',2,1120,1116,'com.plexapp.agents.imdb://tt0903624?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',2,1250,1245,'com.plexapp.agents.imdb://tt1268799?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',2,1270,1264,'com.plexapp.agents.imdb://tt1320261?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',2,1376,1369,'com.plexapp.agents.imdb://tt1772341?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,3035,3027,'com.plexapp.agents.thetvdb://153021/3/14?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,6071,6063,'com.plexapp.agents.thetvdb://71173/1/18?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,6342,6334,'com.plexapp.agents.thetvdb://71256/13/4?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,9107,9099,'com.plexapp.agents.thetvdb://72389/2/19?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,11740,11732,'com.plexapp.agents.thetvdb://73893/2/13?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,12143,12135,'com.plexapp.agents.thetvdb://73976/4/23?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,15179,15171,'com.plexapp.agents.thetvdb://75897/16/12?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,17408,17400,'com.plexapp.agents.thetvdb://76808/2/16?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,17984,17976,'com.plexapp.agents.thetvdb://77068/1/16?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,18215,18207,'com.plexapp.agents.thetvdb://77259/1/1?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,21251,21243,'com.plexapp.agents.thetvdb://78957/8/2?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,24287,24279,'com.plexapp.agents.thetvdb://80337/5/8?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,25513,25505,'com.plexapp.agents.thetvdb://82226/6?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,25548,25540,'com.plexapp.agents.thetvdb://82339/2/10?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_guid',1,26770,26762,'com.plexapp.agents.thetvdb://86901/1/3?lang=en'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',1524,0,0,''); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',2,3034,1391,'Attack of the Giant Squid'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',51,4742,2895,'Brad Sherwood'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',11,4912,2996,'Brian Williams'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',39,5847,3857,'Chip Esten'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',1,6071,4015,'Chuck Versus the DeLorean'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',12,7625,5436,'Denny Siegel'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',30,8924,6618,'Episode 1'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',29,9015,6629,'Episode 2'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',32,9082,6643,'Episode 3'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',28,9135,6654,'Episode 4'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',26,9183,6665,'Episode 5'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',27,9229,6677,'Episode 6'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',22,9266,6688,'Episode 7'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',20,9298,6699,'Episode 8'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',55,11750,8817,'Greg Proops'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',1,12143,9120,'Hardware Jungle'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',33,14712,11435,'Kathy Greenwood'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',3,15179,11840,'Last Call'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',1,18215,14601,'Nature or Nurture?'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',12,18241,14623,'Neil DeGrasse Tyson'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',68,19918,16144,'Pilot'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',7,21251,17298,'Reza Aslan'); + INSERT INTO sqlite_stat3 VALUES('items','i_title_sort',1,24287,20035,'Technoviking'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',1524,0,0,''); + INSERT INTO sqlite_stat3 VALUES('items','i_title',1,3035,1429,'Anderson Can''t Dance'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',51,4782,2991,'Brad Sherwood'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',11,4936,3079,'Brian Williams'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',39,5694,3783,'Chip Esten'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',1,6071,4100,'Clive Warren'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',12,7144,5078,'Denny Siegel'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',30,8249,6097,'Episode 1'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',29,8340,6108,'Episode 2'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',32,8407,6122,'Episode 3'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',28,8460,6133,'Episode 4'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',26,8508,6144,'Episode 5'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',27,8554,6156,'Episode 6'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',22,8591,6167,'Episode 7'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',20,8623,6178,'Episode 8'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',1,9107,6537,'Fat Albert and the Cosby Kids'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',55,10539,7843,'Greg Proops'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',1,12143,9276,'Iron Age Remains'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',33,13118,10143,'Kathy Greenwood'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',1,15179,11972,'Mink'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',68,17411,14035,'Pilot'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',2,18214,14727,'Reflections'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',4,21250,17481,'The Apartment'); + INSERT INTO sqlite_stat3 VALUES('items','i_title',1,24287,20283,'The Simpsons Already Did It'); + INSERT INTO sqlite_stat3 VALUES('items','i_index',4315,95,2,1); + INSERT INTO sqlite_stat3 VALUES('items','i_index',1553,4410,3,2); + INSERT INTO sqlite_stat3 VALUES('items','i_index',1485,5963,4,3); + INSERT INTO sqlite_stat3 VALUES('items','i_index',1414,7448,5,4); + INSERT INTO sqlite_stat3 VALUES('items','i_index',1367,8862,6,5); + INSERT INTO sqlite_stat3 VALUES('items','i_index',1328,10229,7,6); + INSERT INTO sqlite_stat3 VALUES('items','i_index',1161,11557,8,7); + INSERT INTO sqlite_stat3 VALUES('items','i_index',1108,12718,9,8); + INSERT INTO sqlite_stat3 VALUES('items','i_index',1033,13826,10,9); + INSERT INTO sqlite_stat3 VALUES('items','i_index',1014,14859,11,10); + INSERT INTO sqlite_stat3 VALUES('items','i_index',929,15873,12,11); + INSERT INTO sqlite_stat3 VALUES('items','i_index',906,16802,13,12); + INSERT INTO sqlite_stat3 VALUES('items','i_index',844,17708,14,13); + INSERT INTO sqlite_stat3 VALUES('items','i_index',690,18552,15,14); + INSERT INTO sqlite_stat3 VALUES('items','i_index',655,19242,16,15); + INSERT INTO sqlite_stat3 VALUES('items','i_index',625,19897,17,16); + INSERT INTO sqlite_stat3 VALUES('items','i_index',579,20522,18,17); + INSERT INTO sqlite_stat3 VALUES('items','i_index',555,21101,19,18); + INSERT INTO sqlite_stat3 VALUES('items','i_index',526,21656,20,19); + INSERT INTO sqlite_stat3 VALUES('items','i_index',501,22182,21,20); + INSERT INTO sqlite_stat3 VALUES('items','i_index',459,22683,22,21); + INSERT INTO sqlite_stat3 VALUES('items','i_index',439,23142,23,22); + INSERT INTO sqlite_stat3 VALUES('items','i_index',315,23581,24,23); + INSERT INTO sqlite_stat3 VALUES('items','i_index',192,24177,26,25); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',1851,0,0,NULL); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',373,1857,2,'2011-10-22 14:54:39'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',595,2230,3,'2011-10-22 14:54:41'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',337,2825,4,'2011-10-22 14:54:43'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',361,3378,8,'2011-10-22 14:54:54'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',160,3739,9,'2011-10-22 14:54:56'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',315,4000,11,'2011-10-22 14:54:59'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',321,4334,13,'2011-10-22 14:55:02'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',1292,4723,16,'2011-10-22 14:55:06'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',161,6015,17,'2011-10-22 14:55:07'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',1,9107,2677,'2012-09-04 18:07:50'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',313,9717,3270,'2012-10-18 16:50:21'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',450,10030,3271,'2012-10-18 16:50:22'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',389,10668,3275,'2012-10-18 16:50:26'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',796,11057,3276,'2012-10-18 16:51:06'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',161,12041,3280,'2012-10-19 19:52:37'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',135,13281,4186,'2013-02-19 00:56:10'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',1063,13416,4187,'2013-02-19 00:56:11'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',797,14479,4188,'2013-02-19 00:56:13'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',147,15276,4189,'2013-02-19 00:56:15'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',346,15423,4190,'2013-02-19 00:56:16'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',1,18215,6436,'2013-05-05 14:09:54'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',2,21251,8122,'2013-05-24 15:25:45'); + INSERT INTO sqlite_stat3 VALUES('items','i_created_at',1,24287,11116,'2013-05-26 14:17:39'); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',2560,0,0,NULL); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',18,3022,31,2350); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',10,6068,285,8150); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',158,6346,315,8949); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',34,9094,562,18831); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',20,12139,794,22838); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',134,14033,886,24739); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',159,14167,887,24740); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',161,14326,888,24741); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',161,14487,889,24742); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',124,14648,890,24743); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',157,14772,891,24744); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',126,15043,894,24747); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',40,15169,895,24748); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',161,15243,898,24753); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',138,15404,899,24754); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',160,15542,900,24755); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',161,15702,901,24756); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',161,15863,902,24757); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',124,16024,903,24758); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',155,16148,904,24759); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',26,18208,1043,29704); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',2,21251,1282,32952); + INSERT INTO sqlite_stat3 VALUES('items','i_parent_id',13,24279,1583,36068); + INSERT INTO sqlite_stat3 VALUES('items','i_secid',25167,0,0,2); + INSERT INTO sqlite_stat3 VALUES('items','i_secid',736,25167,1,3); + INSERT INTO sqlite_stat3 VALUES('items','i_secid',15,25903,2,4); + INSERT INTO sqlite_stat3 VALUES('items','i_secid',1398,25918,3,5); + ANALYZE sqlite_master; + + explain query plan + select items.title + from items + join items as child on child.parent_id=items.id + join items as grandchild on grandchild.parent_id=child.id + join settings + on settings.guid=grandchild.guid + and settings.account_id=1 + where items.metadata_type=2 + and items.secid=2 + and settings.last_viewed_at is not null + group by items.id + order by settings.last_viewed_at desc + limit 10; +} [list \ + 0 0 3 {SEARCH TABLE settings USING INDEX s_account_id (account_id=?)} \ + 0 1 2 {SEARCH TABLE items AS grandchild USING INDEX i_guid (guid=?)} \ + 0 2 1 {SEARCH TABLE items AS child USING INTEGER PRIMARY KEY (rowid=?)} \ + 0 3 0 {SEARCH TABLE items USING INTEGER PRIMARY KEY (rowid=?)} \ + 0 0 0 {USE TEMP B-TREE FOR GROUP BY} \ + 0 0 0 {USE TEMP B-TREE FOR ORDER BY}] + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/win32lock.test b/components/external/SQLite-3.8.1/test/win32lock.test new file mode 100644 index 0000000000000000000000000000000000000000..724172065fd0585567b422fbcb721068efa822de --- /dev/null +++ b/components/external/SQLite-3.8.1/test/win32lock.test @@ -0,0 +1,134 @@ +# 2011 July 11 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is recovery from transient manditory locks +# that sometimes appear on database files due to anti-virus software. +# + +if {$tcl_platform(platform)!="windows"} return + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +set testprefix win32lock + +db close +sqlite3_shutdown +test_sqlite3_log xLog +proc xLog {error_code msg} { + lappend ::log $msg +} +sqlite3 db test.db +db eval {PRAGMA mmap_size=0} + +do_test win32lock-1.1 { + db eval { + PRAGMA cache_size=10; + CREATE TABLE t1(x,y); + INSERT INTO t1 VALUES(1,randomblob(100000)); + INSERT INTO t1 VALUES(2,randomblob(50000)); + INSERT INTO t1 VALUES(3,randomblob(25000)); + INSERT INTO t1 VALUES(4,randomblob(12500)); + SELECT x, length(y) FROM t1 ORDER BY rowid; + } +} {1 100000 2 50000 3 25000 4 12500} + +unset -nocomplain delay1 rc msg +set old_pending_byte [sqlite3_test_control_pending_byte 0x40000000] + +set win32_lock_ok [list] +set win32_lock_error [list] +set delay1 25 +while {1} { + lock_win32_file test.db 0 $::delay1 + set ::log {} + set rc [catch {db eval {SELECT x, length(y) FROM t1 ORDER BY rowid}} msg] + if {$rc} { + lappend win32_lock_error $::delay1 + do_test win32lock-1.2-$delay1-error { + set ::msg + } {disk I/O error} + } else { + lappend win32_lock_ok $::delay1 + do_test win32lock-1.2-$delay1-ok { + set ::msg + } {1 100000 2 50000 3 25000 4 12500} + if {[info exists ::log] && $::log!=""} { + do_test win32lock-1.2-$delay1-log1 { + regsub {\d+} $::log # x + set x + } {{delayed #ms for lock/sharing conflict}} + } + } + if {[llength $win32_lock_ok] && [llength $win32_lock_error]} break + incr delay1 25 + if {$delay1 > 12500} { + puts "Timed out waiting for \"ok\" and \"error\" results." + break + } + sqlite3_sleep 10 +} + +do_test win32lock-2.0 { + file_control_win32_av_retry db -1 -1 +} {0 10 25} +do_test win32lock-2.1 { + file_control_win32_av_retry db 1 1 +} {0 1 1} + +# +# NOTE: It is known that the win32lock-2.2-* tests may fail if the system is +# experiencing heavy load (i.e. they are very timing sensitive). This is +# primarily due to the AV retry delay being set to 1 millisecond in the +# win32lock-2.1 test (above). While it is important to test this corner +# case for the AV retry logic, a failure of this test should probably not +# be interpreted as a bug in SQLite or these test cases. +# +set win32_lock_ok [list] +set win32_lock_error [list] +set delay1 1 +while {1} { + lock_win32_file test.db 0 $::delay1 + set ::log {} + set rc [catch {db eval {SELECT x, length(y) FROM t1 ORDER BY rowid}} msg] + if {$rc} { + lappend win32_lock_error $::delay1 + do_test win32lock-2.2-$delay1-error { + set ::msg + } {disk I/O error} + } else { + lappend win32_lock_ok $::delay1 + do_test win32lock-2.2-$delay1-ok { + set ::msg + } {1 100000 2 50000 3 25000 4 12500} + if {[info exists ::log] && $::log!=""} { + do_test win32lock-2.2-$delay1-log1 { + regsub {\d+} $::log # x + set x + } {{delayed #ms for lock/sharing conflict}} + } + } + if {[llength $win32_lock_ok] && [llength $win32_lock_error]} break + incr delay1 1 + if {$delay1 > 500} { + puts "Timed out waiting for \"ok\" and \"error\" results." + break + } + sqlite3_sleep 10 +} + +file_control_win32_av_retry db 10 25 +sqlite3_test_control_pending_byte $old_pending_byte +db close +sqlite3_shutdown +test_sqlite3_log +sqlite3_initialize +finish_test diff --git a/components/external/SQLite-3.8.1/test/win32longpath.test b/components/external/SQLite-3.8.1/test/win32longpath.test new file mode 100644 index 0000000000000000000000000000000000000000..0a6a8f98e66bd991742198b759aec4c3c817b728 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/win32longpath.test @@ -0,0 +1,102 @@ +# 2013 August 27 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this script is testing the file name handling provided +# by the "win32-longpath" VFS. +# + +if {$tcl_platform(platform)!="windows"} return + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix win32longpath + +db close +set path [file nativename [get_pwd]] +sqlite3 db [file join $path test.db] -vfs win32-longpath + +do_test 1.1 { + db eval { + BEGIN EXCLUSIVE; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(1); + INSERT INTO t1 VALUES(2); + INSERT INTO t1 VALUES(3); + INSERT INTO t1 VALUES(4); + SELECT x FROM t1 ORDER BY x; + COMMIT; + } +} {1 2 3 4} + +set longPath(1) \\\\?\\$path\\[pid] +make_win32_dir $longPath(1) + +set longPath(2) $longPath(1)\\[string repeat X 255] +make_win32_dir $longPath(2) + +set longPath(3) $longPath(2)\\[string repeat Y 255] +make_win32_dir $longPath(3) + +set fileName $longPath(3)\\test.db + +do_test 1.2 { + list [catch {sqlite3 db2 [string range $fileName 4 end]} msg] $msg +} {1 {unable to open database file}} + +sqlite3 db3 $fileName -vfs win32-longpath + +do_test 1.3 { + db3 eval { + BEGIN EXCLUSIVE; + CREATE TABLE t1(x); + INSERT INTO t1 VALUES(5); + INSERT INTO t1 VALUES(6); + INSERT INTO t1 VALUES(7); + INSERT INTO t1 VALUES(8); + SELECT x FROM t1 ORDER BY x; + COMMIT; + } +} {5 6 7 8} + +db3 close +# puts " Database exists \{[exists_win32_path $fileName]\}" + +sqlite3 db3 $fileName -vfs win32-longpath + +do_test 1.4 { + db3 eval { + PRAGMA journal_mode = WAL; + } +} {wal} + +do_test 1.5 { + db3 eval { + BEGIN EXCLUSIVE; + INSERT INTO t1 VALUES(9); + INSERT INTO t1 VALUES(10); + INSERT INTO t1 VALUES(11); + INSERT INTO t1 VALUES(12); + SELECT x FROM t1 ORDER BY x; + COMMIT; + } +} {5 6 7 8 9 10 11 12} + +db3 close +# puts " Database exists \{[exists_win32_path $fileName]\}" + +do_delete_win32_file $fileName +# puts " Files remaining \{[find_win32_file $longPath(3)\\*]\}" + +do_remove_win32_dir $longPath(3) +do_remove_win32_dir $longPath(2) +do_remove_win32_dir $longPath(1) + +finish_test diff --git a/components/external/SQLite-3.8.1/test/zeroblob.test b/components/external/SQLite-3.8.1/test/zeroblob.test new file mode 100644 index 0000000000000000000000000000000000000000..f4a195083696a4e3227e1dc6076e1a944115a175 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/zeroblob.test @@ -0,0 +1,259 @@ +# 2007 May 02 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# This file implements regression tests for SQLite library. The +# focus of this file is testing of the zero-filled blob functionality +# including the sqlite3_bind_zeroblob(), sqlite3_result_zeroblob(), +# and the built-in zeroblob() SQL function. +# +# $Id: zeroblob.test,v 1.14 2009/07/14 02:33:02 drh Exp $ + +set testdir [file dirname $argv0] +source $testdir/tester.tcl + +ifcapable !incrblob { + finish_test + return +} + +# When zeroblob() is used for the last field of a column, then the +# content of the zeroblob is never instantiated on the VDBE stack. +# But it does get inserted into the database correctly. +# +db eval {PRAGMA cache_size=10} +sqlite3_memory_highwater 1 +unset -nocomplain memused +set memused [sqlite3_memory_used] +do_test zeroblob-1.1 { + execsql { + CREATE TABLE t1(a,b,c,d); + } + set ::sqlite3_max_blobsize 0 + execsql { + INSERT INTO t1 VALUES(2,3,4,zeroblob(1000000)); + } + set ::sqlite3_max_blobsize +} {10} +do_test zeroblob-1.1.1 { + expr {[sqlite3_memory_highwater]<$::memused+25000} +} {1} +do_test zeroblob-1.2 { + execsql { + SELECT length(d) FROM t1 + } +} {1000000} + +# If a non-NULL column follows the zeroblob, then the content of +# the zeroblob must be instantiated. +# +do_test zeroblob-1.3 { + set ::sqlite3_max_blobsize 0 + execsql { + INSERT INTO t1 VALUES(3,4,zeroblob(10000),5); + } + set ::sqlite3_max_blobsize +} {10010} +do_test zeroblob-1.4 { + execsql { + SELECT length(c), length(d) FROM t1 + } +} {1 1000000 10000 1} + +# Multiple zeroblobs can appear at the end of record. No instantiation +# of the blob content occurs on the stack. +# +do_test zeroblob-1.5 { + set ::sqlite3_max_blobsize 0 + execsql { + INSERT INTO t1 VALUES(4,5,zeroblob(10000),zeroblob(10000)); + } + set ::sqlite3_max_blobsize +} {11} +do_test zeroblob-1.6 { + execsql { + SELECT length(c), length(d) FROM t1 + } +} {1 1000000 10000 1 10000 10000} + +# NULLs can follow the zeroblob() or be intermixed with zeroblobs and +# no instantiation of the zeroblobs occurs on the stack. +# +do_test zeroblob-1.7 { + set ::sqlite3_max_blobsize 0 + execsql { + INSERT INTO t1 VALUES(5,zeroblob(10000),NULL,zeroblob(10000)); + } + set ::sqlite3_max_blobsize +} {10} +do_test zeroblob-1.8 { + execsql { + SELECT length(b), length(d) FROM t1 WHERE a=5 + } +} {10000 10000} + +# Comparisons against zeroblobs work. +# +do_test zeroblob-2.1 { + execsql { + SELECT a FROM t1 WHERE b=zeroblob(10000) + } +} {5} + +# Comparisons against zeroblobs work even when indexed. +# +do_test zeroblob-2.2 { + execsql { + CREATE INDEX i1_1 ON t1(b); + SELECT a FROM t1 WHERE b=zeroblob(10000); + } +} {5} + +# DISTINCT works for zeroblobs +# +ifcapable bloblit&&subquery&&compound { + do_test zeroblob-3.1 { + execsql { + SELECT count(DISTINCT a) FROM ( + SELECT x'00000000000000000000' AS a + UNION ALL + SELECT zeroblob(10) AS a + ) + } + } {1} +} + +# Concatentation works with zeroblob +# +ifcapable bloblit { + do_test zeroblob-4.1 { + execsql { + SELECT hex(zeroblob(2) || x'61') + } + } {000061} +} + +# Check various CAST(...) operations on zeroblob. +# +do_test zeroblob-5.1 { + execsql { + SELECT CAST (zeroblob(100) AS REAL); + } +} {0.0} +do_test zeroblob-5.2 { + execsql { + SELECT CAST (zeroblob(100) AS INTEGER); + } +} {0} +do_test zeroblob-5.3 { + execsql { + SELECT CAST (zeroblob(100) AS TEXT); + } +} {{}} +do_test zeroblob-5.4 { + execsql { + SELECT CAST(zeroblob(100) AS BLOB); + } +} [execsql {SELECT zeroblob(100)}] + + +# Check for malicious use of zeroblob. Make sure nothing crashes. +# +do_test zeroblob-6.1.1 { + execsql {select zeroblob(-1)} +} {{}} +do_test zeroblob-6.1.2 { + execsql {select zeroblob(-10)} +} {{}} +do_test zeroblob-6.1.3 { + execsql {select zeroblob(-100)} +} {{}} +do_test zeroblob-6.2 { + execsql {select length(zeroblob(-1))} +} {0} +do_test zeroblob-6.3 { + execsql {select zeroblob(-1)|1} +} {1} +do_test zeroblob-6.4 { + catchsql {select length(zeroblob(2147483648))} +} {1 {string or blob too big}} +do_test zeroblob-6.5 { + catchsql {select zeroblob(2147483648)} +} {1 {string or blob too big}} +do_test zeroblob-6.6 { + execsql {select hex(zeroblob(-1))} +} {{}} +do_test zeroblob-6.7 { + execsql {select typeof(zeroblob(-1))} +} {blob} + +# Test bind_zeroblob() +# +sqlite3_memory_highwater 1 +unset -nocomplain memused +set memused [sqlite3_memory_used] +do_test zeroblob-7.1 { + set ::STMT [sqlite3_prepare $::DB "SELECT length(?)" -1 DUMMY] + set ::sqlite3_max_blobsize 0 + sqlite3_bind_zeroblob $::STMT 1 450000 + sqlite3_step $::STMT +} {SQLITE_ROW} +do_test zeroblob-7.2 { + sqlite3_column_int $::STMT 0 +} {450000} +do_test zeroblob-7.3 { + sqlite3_finalize $::STMT +} {SQLITE_OK} +do_test zeroblob-7.4 { + set ::sqlite3_max_blobsize +} {0} +do_test zeroblob-7.5 { + expr {[sqlite3_memory_highwater]<$::memused+10000} +} {1} + +# Test that MakeRecord can handle a value with some real content +# and a zero-blob tail. +# +do_test zeroblob-8.1 { + llength [execsql { + SELECT 'hello' AS a, zeroblob(10) as b from t1 ORDER BY a, b; + }] +} {8} + + +# Ticket #3965 +# zeroblobs on either size of an IN operator +# +do_test zeroblob-9.1 { + db eval {SELECT x'0000' IN (x'000000')} +} {0} +do_test zeroblob-9.2 { + db eval {SELECT x'0000' IN (x'0000')} +} {1} +do_test zeroblob-9.3 { + db eval {SELECT zeroblob(2) IN (x'000000')} +} {0} +do_test zeroblob-9.4 { + db eval {SELECT zeroblob(2) IN (x'0000')} +} {1} +do_test zeroblob-9.5 { + db eval {SELECT x'0000' IN (zeroblob(3))} +} {0} +do_test zeroblob-9.6 { + db eval {SELECT x'0000' IN (zeroblob(2))} +} {1} +do_test zeroblob-9.7 { + db eval {SELECT zeroblob(2) IN (zeroblob(3))} +} {0} +do_test zeroblob-9.8 { + db eval {SELECT zeroblob(2) IN (zeroblob(2))} +} {1} + + +finish_test diff --git a/components/external/SQLite-3.8.1/test/zerodamage.test b/components/external/SQLite-3.8.1/test/zerodamage.test new file mode 100644 index 0000000000000000000000000000000000000000..de5088b5a2f984d54d1eba60fb93e10ef7623a19 --- /dev/null +++ b/components/external/SQLite-3.8.1/test/zerodamage.test @@ -0,0 +1,121 @@ +# 2011 December 21 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#*********************************************************************** +# +# This file implements tests of the SQLITE_IOCAP_POWERSAFE_OVERWRITE property +# and the SQLITE_FCNTL_POWERSAFE_OVERWRITE file-control for manipulating it. +# +# The name of this file comes from the fact that we used to call the +# POWERSAFE_OVERWRITE property ZERO_DAMAGE. +# + +set testdir [file dirname $argv0] +source $testdir/tester.tcl +set testprefix zerodamage + +ifcapable !vtab { + finish_test + return +} + +# POWERSAFE_OVERWRITE defaults to true +# +do_test zerodamage-1.0 { + file_control_powersafe_overwrite db -1 +} {0 1} + +# Check the ability to turn zero-damage on and off. +# +do_test zerodamage-1.1 { + file_control_powersafe_overwrite db 0 + file_control_powersafe_overwrite db -1 +} {0 0} +do_test zerodamage-1.2 { + file_control_powersafe_overwrite db 1 + file_control_powersafe_overwrite db -1 +} {0 1} + +# Run a transaction with zero-damage on, a small page size and a much larger +# sectorsize. Verify that the maximum journal size is small - that the +# rollback journal is not being padded. +# +do_test zerodamage-2.0 { + db close + testvfs tv -default 1 + tv sectorsize 8192 + sqlite3 db file:test.db?psow=TRUE -uri 1 + unset -nocomplain ::max_journal_size + set ::max_journal_size 0 + proc xDeleteCallback {method file args} { + set sz [file size $file] + if {$sz>$::max_journal_size} {set ::max_journal_size $sz} + } + tv filter xDelete + tv script xDeleteCallback + load_static_extension db wholenumber + db eval { + PRAGMA page_size=1024; + PRAGMA journal_mode=DELETE; + PRAGMA cache_size=5; + CREATE VIRTUAL TABLE nums USING wholenumber; + CREATE TABLE t1(x, y); + INSERT INTO t1 SELECT value, randomblob(100) FROM nums + WHERE value BETWEEN 1 AND 400; + } + set ::max_journal_size 0 + db eval { + UPDATE t1 SET y=randomblob(50) WHERE x=123; + } + concat [file_control_powersafe_overwrite db -1] [set ::max_journal_size] +} {0 1 2576} + +# Repeat the previous step with zero-damage turned off. This time the +# maximum rollback journal size should be much larger. +# +do_test zerodamage-2.1 { + set ::max_journal_size 0 + db close + sqlite3 db file:test.db?psow=FALSE -uri 1 + db eval { + UPDATE t1 SET y=randomblob(50) WHERE x=124; + } + concat [file_control_powersafe_overwrite db -1] [set ::max_journal_size] +} {0 0 24704} + +ifcapable wal { + # Run a WAL-mode transaction with POWERSAFE_OVERWRITE on to verify that the + # WAL file does not get too big. + # + do_test zerodamage-3.0 { + db eval { + PRAGMA journal_mode=WAL; + } + db close + sqlite3 db file:test.db?psow=TRUE -uri 1 + db eval { + UPDATE t1 SET y=randomblob(50) WHERE x=124; + } + file size test.db-wal + } {1080} + + # Repeat the previous with POWERSAFE_OVERWRITE off. Verify that the WAL file + # is padded. + # + do_test zerodamage-3.1 { + db close + sqlite3 db file:test.db?psow=FALSE -uri 1 + db eval { + UPDATE t1 SET y=randomblob(50) WHERE x=124; + } + file size test.db-wal + } {8416} +} + +finish_test diff --git a/components/external/SQLite-3.8.1/tool/build-all-msvc.bat b/components/external/SQLite-3.8.1/tool/build-all-msvc.bat new file mode 100644 index 0000000000000000000000000000000000000000..ed05f959fe6294eba746518e0f1190331448023f --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/build-all-msvc.bat @@ -0,0 +1,529 @@ +@ECHO OFF + +:: +:: build-all-msvc.bat -- +:: +:: Multi-Platform Build Tool for MSVC +:: + +REM +REM This batch script is used to build the SQLite DLL for multiple platforms +REM and configurations using MSVC. The built SQLite DLLs, their associated +REM import libraries, and optionally their symbols files, are placed within +REM the directory specified on the command line, in sub-directories named for +REM their respective platforms and configurations. This batch script must be +REM run from inside a Visual Studio Command Prompt for the desired version of +REM Visual Studio ^(the initial platform configured for the command prompt does +REM not really matter^). Exactly one command line argument is required, the +REM name of an existing directory to be used as the final destination directory +REM for the generated output files, which will be placed in sub-directories +REM created therein. Ideally, the directory specified should be empty. +REM +REM Example: +REM +REM CD /D C:\dev\sqlite\core +REM tool\build-all-msvc.bat C:\Temp +REM +REM In the example above, "C:\dev\sqlite\core" represents the root of the +REM source tree for SQLite and "C:\Temp" represents the final destination +REM directory for the generated output files. +REM +REM There are several environment variables that may be set to modify the +REM behavior of this batch script and its associated Makefile. The list of +REM platforms to build may be overriden by using the PLATFORMS environment +REM variable, which should contain a list of platforms ^(e.g. x86 x86_amd64 +REM x86_arm^). All platforms must be supported by the version of Visual Studio +REM being used. The list of configurations to build may be overridden by +REM setting the CONFIGURATIONS environment variable, which should contain a +REM list of configurations to build ^(e.g. Debug Retail^). Neither of these +REM variable values may contain any double quotes, surrounding or embedded. +REM Finally, the NCRTLIBPATH and NSDKLIBPATH environment variables may be set +REM to specify the location of the CRT and SDK, respectively, needed to compile +REM executables native to the architecture of the build machine during any +REM cross-compilation that may be necessary, depending on the platforms to be +REM built. These values in these two variables should be surrounded by double +REM quotes if they contain spaces. +REM +REM Please note that the SQLite build process performed by the Makefile +REM associated with this batch script requires both Gawk ^(gawk.exe^) and Tcl +REM 8.5 ^(tclsh85.exe^) to be present in a directory contained in the PATH +REM environment variable unless a pre-existing amalgamation file is used. +REM +SETLOCAL + +REM SET __ECHO=ECHO +REM SET __ECHO2=ECHO +REM SET __ECHO3=ECHO +IF NOT DEFINED _AECHO (SET _AECHO=REM) +IF NOT DEFINED _CECHO (SET _CECHO=REM) +IF NOT DEFINED _VECHO (SET _VECHO=REM) + +%_AECHO% Running %0 %* + +REM SET DFLAGS=/L + +%_VECHO% DFlags = '%DFLAGS%' + +SET FFLAGS=/V /F /G /H /I /R /Y /Z + +%_VECHO% FFlags = '%FFLAGS%' + +SET ROOT=%~dp0\.. +SET ROOT=%ROOT:\\=\% + +%_VECHO% Root = '%ROOT%' + +REM +REM NOTE: The first and only argument to this batch file should be the output +REM directory where the platform-specific binary directories should be +REM created. +REM +SET BINARYDIRECTORY=%1 + +IF NOT DEFINED BINARYDIRECTORY ( + GOTO usage +) + +%_VECHO% BinaryDirectory = '%BINARYDIRECTORY%' + +SET DUMMY=%2 + +IF DEFINED DUMMY ( + GOTO usage +) + +REM +REM NOTE: From this point, we need a clean error level. Reset it now. +REM +CALL :fn_ResetErrorLevel + +REM +REM NOTE: Change the current directory to the root of the source tree, saving +REM the current directory on the directory stack. +REM +%__ECHO2% PUSHD "%ROOT%" + +IF ERRORLEVEL 1 ( + ECHO Could not change directory to "%ROOT%". + GOTO errors +) + +REM +REM NOTE: This batch file requires the ComSpec environment variable to be set, +REM typically to something like "C:\Windows\System32\cmd.exe". +REM +IF NOT DEFINED ComSpec ( + ECHO The ComSpec environment variable must be defined. + GOTO errors +) + +REM +REM NOTE: This batch file requires the VcInstallDir environment variable to be +REM set. Tyipcally, this means this batch file needs to be run from an +REM MSVC command prompt. +REM +IF NOT DEFINED VCINSTALLDIR ( + ECHO The VCINSTALLDIR environment variable must be defined. + GOTO errors +) + +REM +REM NOTE: If the list of platforms is not already set, use the default list. +REM +IF NOT DEFINED PLATFORMS ( + SET PLATFORMS=x86 x86_amd64 x86_arm +) + +%_VECHO% Platforms = '%PLATFORMS%' + +REM +REM NOTE: If the list of configurations is not already set, use the default +REM list. +REM +IF NOT DEFINED CONFIGURATIONS ( + SET CONFIGURATIONS=Debug Retail +) + +%_VECHO% Configurations = '%CONFIGURATIONS%' + +REM +REM NOTE: Setup environment variables to translate between the MSVC platform +REM names and the names to be used for the platform-specific binary +REM directories. +REM +SET amd64_NAME=x64 +SET arm_NAME=ARM +SET x64_NAME=x64 +SET x86_NAME=x86 +SET x86_amd64_NAME=x64 +SET x86_arm_NAME=ARM +SET x86_x64_NAME=x64 + +%_VECHO% amd64_Name = '%amd64_NAME%' +%_VECHO% arm_Name = '%arm_NAME%' +%_VECHO% x64_Name = '%x64_NAME%' +%_VECHO% x86_Name = '%x86_NAME%' +%_VECHO% x86_amd64_Name = '%x86_amd64_NAME%' +%_VECHO% x86_arm_Name = '%x86_arm_NAME%' +%_VECHO% x86_x64_Name = '%x86_x64_NAME%' + +REM +REM NOTE: Check for the external tools needed during the build process ^(i.e. +REM those that do not get compiled as part of the build process itself^) +REM along the PATH. +REM +FOR %%T IN (gawk.exe tclsh85.exe) DO ( + SET %%T_PATH=%%~dp$PATH:T +) + +REM +REM NOTE: The Gawk executable "gawk.exe" is required during the SQLite build +REM process unless a pre-existing amalgamation file is used. +REM +IF NOT DEFINED gawk.exe_PATH ( + ECHO The Gawk executable "gawk.exe" is required to be in the PATH. + GOTO errors +) + +REM +REM NOTE: The Tcl 8.5 executable "tclsh85.exe" is required during the SQLite +REM build process unless a pre-existing amalgamation file is used. +REM +IF NOT DEFINED tclsh85.exe_PATH ( + ECHO The Tcl 8.5 executable "tclsh85.exe" is required to be in the PATH. + GOTO errors +) + +REM +REM NOTE: Set the TOOLPATH variable to contain all the directories where the +REM external tools were found in the search above. +REM +SET TOOLPATH=%gawk.exe_PATH%;%tclsh85.exe_PATH% + +%_VECHO% ToolPath = '%TOOLPATH%' + +REM +REM NOTE: Check for MSVC 2012/2013 because the Windows SDK directory handling +REM is slightly different for those versions. +REM +IF "%VisualStudioVersion%" == "11.0" ( + REM + REM NOTE: If the Windows SDK library path has already been set, do not set + REM it to something else later on. + REM + IF NOT DEFINED NSDKLIBPATH ( + SET SET_NSDKLIBPATH=1 + ) +) ELSE IF "%VisualStudioVersion%" == "12.0" ( + REM + REM NOTE: If the Windows SDK library path has already been set, do not set + REM it to something else later on. + REM + IF NOT DEFINED NSDKLIBPATH ( + SET SET_NSDKLIBPATH=1 + ) +) ELSE ( + CALL :fn_UnsetVariable SET_NSDKLIBPATH +) + +REM +REM NOTE: Check if this is the Windows Phone SDK. If so, a different batch +REM file is necessary to setup the build environment. Since the variable +REM values involved here may contain parenthesis, using GOTO instead of +REM an IF block is required. +REM +IF DEFINED WindowsPhoneKitDir GOTO set_vcvarsall_phone +SET VCVARSALL=%VCINSTALLDIR%\vcvarsall.bat +GOTO set_vcvarsall_done +:set_vcvarsall_phone +SET VCVARSALL=%VCINSTALLDIR%\WPSDK\WP80\vcvarsphoneall.bat +:set_vcvarsall_done + +REM +REM NOTE: This is the outer loop. There should be exactly one iteration per +REM platform. +REM +FOR %%P IN (%PLATFORMS%) DO ( + REM + REM NOTE: Using the MSVC platform name, lookup the simpler platform name to + REM be used for the name of the platform-specific binary directory via + REM the environment variables setup earlier. + REM + CALL :fn_CopyVariable %%P_NAME PLATFORMNAME + + REM + REM NOTE: This is the inner loop. There should be exactly one iteration. + REM This loop is necessary because the PlatformName environment + REM variable was set above and that value is needed by some of the + REM commands contained in the inner loop. If these commands were + REM directly contained in the outer loop, the PlatformName environment + REM variable would be stuck with its initial empty value instead. + REM + FOR /F "tokens=2* delims==" %%D IN ('SET PLATFORMNAME') DO ( + REM + REM NOTE: Attempt to clean the environment of all variables used by MSVC + REM and/or Visual Studio. This block may need to be updated in the + REM future to account for additional environment variables. + REM + CALL :fn_UnsetVariable DevEnvDir + CALL :fn_UnsetVariable ExtensionSdkDir + CALL :fn_UnsetVariable Framework35Version + CALL :fn_UnsetVariable FrameworkDir + CALL :fn_UnsetVariable FrameworkDir32 + CALL :fn_UnsetVariable FrameworkVersion + CALL :fn_UnsetVariable FrameworkVersion32 + CALL :fn_UnsetVariable FSHARPINSTALLDIR + CALL :fn_UnsetVariable INCLUDE + CALL :fn_UnsetVariable LIB + CALL :fn_UnsetVariable LIBPATH + CALL :fn_UnsetVariable Platform + REM CALL :fn_UnsetVariable VCINSTALLDIR + CALL :fn_UnsetVariable VSINSTALLDIR + CALL :fn_UnsetVariable WindowsPhoneKitDir + CALL :fn_UnsetVariable WindowsSdkDir + CALL :fn_UnsetVariable WindowsSdkDir_35 + CALL :fn_UnsetVariable WindowsSdkDir_old + + REM + REM NOTE: Reset the PATH here to the absolute bare minimum required. + REM + SET PATH=%TOOLPATH%;%SystemRoot%\System32;%SystemRoot% + + FOR %%B IN (%CONFIGURATIONS%) DO ( + REM + REM NOTE: When preparing the debug build, set the DEBUG and MEMDEBUG + REM environment variables to be picked up by the MSVC makefile + REM itself. + REM + IF /I "%%B" == "Debug" ( + SET DEBUG=2 + SET MEMDEBUG=1 + ) ELSE ( + CALL :fn_UnsetVariable DEBUG + CALL :fn_UnsetVariable MEMDEBUG + ) + + REM + REM NOTE: Launch a nested command shell to perform the following steps: + REM + REM 1. Setup the MSVC environment for this platform using the + REM official batch file. + REM + REM 2. Make sure that no stale build output files are present. + REM + REM 3. Build the "sqlite3.dll" and "sqlite3.lib" binaries for this + REM platform. + REM + REM 4. Copy the "sqlite3.dll" and "sqlite3.lib" binaries for this + REM platform to the platform-specific directory beneath the + REM binary directory. + REM + "%ComSpec%" /C ( + REM + REM NOTE: Attempt to setup the MSVC environment for this platform. + REM + %__ECHO3% CALL "%VCVARSALL%" %%P + + IF ERRORLEVEL 1 ( + ECHO Failed to call "%VCVARSALL%" for platform %%P. + GOTO errors + ) + + REM + REM NOTE: If this batch file is not running in "what-if" mode, check to + REM be sure we were actually able to setup the MSVC environment + REM as current versions of their official batch file do not set + REM the exit code upon failure. + REM + IF NOT DEFINED __ECHO3 ( + IF NOT DEFINED WindowsPhoneKitDir ( + IF NOT DEFINED WindowsSdkDir ( + ECHO Cannot build, Windows SDK not found for platform %%P. + GOTO errors + ) + ) + ) + + REM + REM NOTE: When using MSVC 2012, the native SDK path cannot simply use + REM the "lib" sub-directory beneath the location specified in the + REM WindowsSdkDir environment variable because that location does + REM not actually contain the necessary library files for x86. + REM This must be done for each iteration because it relies upon + REM the WindowsSdkDir environment variable being set by the batch + REM file used to setup the MSVC environment. + REM + IF DEFINED SET_NSDKLIBPATH ( + IF DEFINED WindowsPhoneKitDir ( + CALL :fn_CopyVariable WindowsPhoneKitDir NSDKLIBPATH + CALL :fn_AppendVariable NSDKLIBPATH \lib\x86 + ) ELSE IF DEFINED WindowsSdkDir ( + CALL :fn_CopyVariable WindowsSdkDir NSDKLIBPATH + + IF "%VisualStudioVersion%" == "12.0" ( + CALL :fn_AppendVariable NSDKLIBPATH \lib\winv6.3\um\x86 + ) ELSE ( + CALL :fn_AppendVariable NSDKLIBPATH \lib\win8\um\x86 + ) + ) + ) + + REM + REM NOTE: Unless prevented from doing so, invoke NMAKE with the MSVC + REM makefile to clean any stale build output from previous + REM iterations of this loop and/or previous runs of this batch + REM file, etc. + REM + IF NOT DEFINED NOCLEAN ( + %__ECHO% nmake -f Makefile.msc clean + + IF ERRORLEVEL 1 ( + ECHO Failed to clean for platform %%P. + GOTO errors + ) + ) ELSE ( + REM + REM NOTE: Even when the cleaning step has been disabled, we still + REM need to remove the build output for the files we are + REM specifically wanting to build for each platform. + REM + %__ECHO% DEL /Q *.lo sqlite3.dll sqlite3.lib sqlite3.pdb + ) + + REM + REM NOTE: Call NMAKE with the MSVC makefile to build the "sqlite3.dll" + REM binary. The x86 compiler will be used to compile the native + REM command line tools needed during the build process itself. + REM Also, disable looking for and/or linking to the native Tcl + REM runtime library. + REM + %__ECHO% nmake -f Makefile.msc sqlite3.dll XCOMPILE=1 USE_NATIVE_LIBPATHS=1 NO_TCL=1 %NMAKE_ARGS% + + IF ERRORLEVEL 1 ( + ECHO Failed to build %%B "sqlite3.dll" for platform %%P. + GOTO errors + ) + + REM + REM NOTE: Copy the "sqlite3.dll" file to the appropriate directory for + REM the build and platform beneath the binary directory. + REM + %__ECHO% XCOPY sqlite3.dll "%BINARYDIRECTORY%\%%B\%%D\" %FFLAGS% %DFLAGS% + + IF ERRORLEVEL 1 ( + ECHO Failed to copy "sqlite3.dll" to "%BINARYDIRECTORY%\%%B\%%D\". + GOTO errors + ) + + REM + REM NOTE: Copy the "sqlite3.lib" file to the appropriate directory for + REM the build and platform beneath the binary directory. + REM + %__ECHO% XCOPY sqlite3.lib "%BINARYDIRECTORY%\%%B\%%D\" %FFLAGS% %DFLAGS% + + IF ERRORLEVEL 1 ( + ECHO Failed to copy "sqlite3.lib" to "%BINARYDIRECTORY%\%%B\%%D\". + GOTO errors + ) + + REM + REM NOTE: Copy the "sqlite3.pdb" file to the appropriate directory for + REM the build and platform beneath the binary directory unless we + REM are prevented from doing so. + REM + IF NOT DEFINED NOSYMBOLS ( + %__ECHO% XCOPY sqlite3.pdb "%BINARYDIRECTORY%\%%B\%%D\" %FFLAGS% %DFLAGS% + + IF ERRORLEVEL 1 ( + ECHO Failed to copy "sqlite3.pdb" to "%BINARYDIRECTORY%\%%B\%%D\". + GOTO errors + ) + ) + ) + ) + ) + + REM + REM NOTE: Handle any errors generated during the nested command shell. + REM + IF ERRORLEVEL 1 ( + GOTO errors + ) +) + +REM +REM NOTE: Restore the saved current directory from the directory stack. +REM +%__ECHO2% POPD + +IF ERRORLEVEL 1 ( + ECHO Could not restore directory. + GOTO errors +) + +REM +REM NOTE: If we get to this point, we have succeeded. +REM +GOTO no_errors + +:fn_ResetErrorLevel + VERIFY > NUL + GOTO :EOF + +:fn_SetErrorLevel + VERIFY MAYBE 2> NUL + GOTO :EOF + +:fn_CopyVariable + SETLOCAL + IF NOT DEFINED %1 GOTO :EOF + IF "%2" == "" GOTO :EOF + SET __ECHO_CMD=ECHO %%%1%% + FOR /F "delims=" %%V IN ('%__ECHO_CMD%') DO ( + SET VALUE=%%V + ) + ENDLOCAL && SET %2=%VALUE% + GOTO :EOF + +:fn_UnsetVariable + IF NOT "%1" == "" ( + SET %1= + CALL :fn_ResetErrorLevel + ) + GOTO :EOF + +:fn_AppendVariable + SET __ECHO_CMD=ECHO %%%1%% + IF DEFINED %1 ( + FOR /F "delims=" %%V IN ('%__ECHO_CMD%') DO ( + SET %1=%%V%~2 + ) + ) ELSE ( + SET %1=%~2 + ) + SET __ECHO_CMD= + CALL :fn_ResetErrorLevel + GOTO :EOF + +:usage + ECHO. + ECHO Usage: %~nx0 ^ + ECHO. + GOTO errors + +:errors + CALL :fn_SetErrorLevel + ENDLOCAL + ECHO. + ECHO Failure, errors were encountered. + GOTO end_of_file + +:no_errors + CALL :fn_ResetErrorLevel + ENDLOCAL + ECHO. + ECHO Success, no errors were encountered. + GOTO end_of_file + +:end_of_file +%__ECHO% EXIT /B %ERRORLEVEL% diff --git a/components/external/SQLite-3.8.1/tool/build-shell.sh b/components/external/SQLite-3.8.1/tool/build-shell.sh new file mode 100644 index 0000000000000000000000000000000000000000..6a48299d73b5121e854bc69d4bce532051a3cd3e --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/build-shell.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# +# This script demonstrates how to do a full-featured build of the sqlite3 +# command-line shell on Linux. +# +# SQLite source code should be in a sibling directory named "sqlite". For +# example, put SQLite sources in ~/sqlite/sqlite and run this script from +# ~/sqlite/bld. There should be an appropriate Makefile in the current +# directory as well. +# +make sqlite3.c +gcc -o sqlite3 -g -Os -I. \ + -DSQLITE_THREADSAFE=0 \ + -DSQLITE_ENABLE_VFSTRACE \ + -DSQLITE_ENABLE_STAT3 \ + -DSQLITE_ENABLE_FTS4 \ + -DSQLITE_ENABLE_RTREE \ + -DHAVE_READLINE \ + -DHAVE_USLEEP=1 \ + ../sqlite/src/shell.c \ + ../sqlite/src/test_vfstrace.c \ + sqlite3.c -ldl -lreadline -lncurses diff --git a/components/external/SQLite-3.8.1/tool/checkSpacing.c b/components/external/SQLite-3.8.1/tool/checkSpacing.c new file mode 100644 index 0000000000000000000000000000000000000000..ce38b08ce4cc163bb69720269399c3d9dfd2df68 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/checkSpacing.c @@ -0,0 +1,84 @@ +/* +** This program checks for formatting problems in source code: +** +** * Any use of tab characters +** * White space at the end of a line +** * Blank lines at the end of a file +** +** Any violations are reported. +*/ +#include +#include +#include + +#define CR_OK 0x001 +#define WSEOL_OK 0x002 + +static void checkSpacing(const char *zFile, unsigned flags){ + FILE *in = fopen(zFile, "rb"); + int i; + int seenSpace; + int seenTab; + int ln = 0; + int lastNonspace = 0; + char zLine[2000]; + if( in==0 ){ + printf("cannot open %s\n", zFile); + return; + } + while( fgets(zLine, sizeof(zLine), in) ){ + seenSpace = 0; + seenTab = 0; + ln++; + for(i=0; zLine[i]; i++){ + if( zLine[i]=='\t' && seenTab==0 ){ + printf("%s:%d: tab (\\t) character\n", zFile, ln); + seenTab = 1; + }else if( zLine[i]=='\r' ){ + if( (flags & CR_OK)==0 ){ + printf("%s:%d: carriage-return (\\r) character\n", zFile, ln); + } + }else if( zLine[i]==' ' ){ + seenSpace = 1; + }else if( zLine[i]!='\n' ){ + lastNonspace = ln; + seenSpace = 0; + } + } + if( seenSpace && (flags & WSEOL_OK)==0 ){ + printf("%s:%d: whitespace at end-of-line\n", zFile, ln); + } + } + fclose(in); + if( lastNonspace +#include +#include +#include +#include +#include +#include + + +#define PAGESIZE 1024 +static int db1 = -1; +static int db2 = -1; + +int main(int argc, char **argv){ + int iPg; + unsigned char a1[PAGESIZE], a2[PAGESIZE]; + if( argc!=3 ){ + fprintf(stderr,"Usage: %s FILENAME FILENAME\n", argv[0]); + exit(1); + } + db1 = open(argv[1], O_RDONLY); + if( db1<0 ){ + fprintf(stderr,"%s: can't open %s\n", argv[0], argv[1]); + exit(1); + } + db2 = open(argv[2], O_RDONLY); + if( db2<0 ){ + fprintf(stderr,"%s: can't open %s\n", argv[0], argv[2]); + exit(1); + } + iPg = 1; + while( read(db1, a1, PAGESIZE)==PAGESIZE && read(db2,a2,PAGESIZE)==PAGESIZE ){ + if( memcmp(a1,a2,PAGESIZE) ){ + printf("Page %d\n", iPg); + } + iPg++; + } + printf("%d pages checked\n", iPg-1); + close(db1); + close(db2); +} diff --git a/components/external/SQLite-3.8.1/tool/extract.c b/components/external/SQLite-3.8.1/tool/extract.c new file mode 100644 index 0000000000000000000000000000000000000000..5bf5caa31c9d1950b4e4eaa04ed68ab609429765 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/extract.c @@ -0,0 +1,46 @@ +/* +** Extract a range of bytes from a file. +** +** Usage: +** +** extract FILENAME OFFSET AMOUNT +** +** The bytes are written to standard output. +*/ +#include +#include + +int main(int argc, char **argv){ + FILE *f; + char *zBuf; + int ofst; + int n; + size_t got; + + if( argc!=4 ){ + fprintf(stderr, "Usage: %s FILENAME OFFSET AMOUNT\n", *argv); + return 1; + } + f = fopen(argv[1], "rb"); + if( f==0 ){ + fprintf(stderr, "cannot open \"%s\"\n", argv[1]); + return 1; + } + ofst = atoi(argv[2]); + n = atoi(argv[3]); + zBuf = malloc( n ); + if( zBuf==0 ){ + fprintf(stderr, "out of memory\n"); + return 1; + } + fseek(f, ofst, SEEK_SET); + got = fread(zBuf, 1, n, f); + fclose(f); + if( got +#include + +/* +** Finalize a prepared statement. If an error has occurred, print the +** error message and exit. +*/ +static void vacuumFinalize(sqlite3_stmt *pStmt){ + sqlite3 *db = sqlite3_db_handle(pStmt); + int rc = sqlite3_finalize(pStmt); + if( rc ){ + fprintf(stderr, "finalize error: %s\n", sqlite3_errmsg(db)); + exit(1); + } +} + +/* +** Execute zSql on database db. The SQL text is printed to standard +** output. If an error occurs, print an error message and exit the +** process. +*/ +static void execSql(sqlite3 *db, const char *zSql){ + sqlite3_stmt *pStmt; + if( !zSql ){ + fprintf(stderr, "out of memory!\n"); + exit(1); + } + printf("%s;\n", zSql); + if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); + exit(1); + } + sqlite3_step(pStmt); + vacuumFinalize(pStmt); +} + +/* +** Execute zSql on database db. The zSql statement returns exactly +** one column. Execute this return value as SQL on the same database. +** +** The zSql statement is printed on standard output prior to being +** run. If any errors occur, an error is printed and the process +** exits. +*/ +static void execExecSql(sqlite3 *db, const char *zSql){ + sqlite3_stmt *pStmt; + int rc; + + printf("%s;\n", zSql); + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); + exit(1); + } + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + execSql(db, (char*)sqlite3_column_text(pStmt, 0)); + } + vacuumFinalize(pStmt); +} + + +int main(int argc, char **argv){ + sqlite3 *db; /* Connection to the database file */ + int rc; /* Return code from SQLite interface calls */ + sqlite3_uint64 r; /* A random number */ + const char *zDbToVacuum; /* Database to be vacuumed */ + char *zBackupDb; /* Backup copy of the original database */ + char *zTempDb; /* Temporary database */ + char *zSql; /* An SQL statement */ + + if( argc!=2 ){ + fprintf(stderr, "Usage: %s DATABASE\n", argv[0]); + return 1; + } + + /* Identify the database file to be vacuumed and open it. + */ + zDbToVacuum = argv[1]; + printf("-- open database file \"%s\"\n", zDbToVacuum); + rc = sqlite3_open(zDbToVacuum, &db); + if( rc ){ + fprintf(stderr, "%s: %s\n", zDbToVacuum, sqlite3_errstr(rc)); + return 1; + } + + /* Create names for two other files. zTempDb will be a new database + ** into which we construct a vacuumed copy of zDbToVacuum. zBackupDb + ** will be a new name for zDbToVacuum after it is vacuumed. + */ + sqlite3_randomness(sizeof(r), &r); + zTempDb = sqlite3_mprintf("%s-vacuum-%016llx", zDbToVacuum, r); + zBackupDb = sqlite3_mprintf("%s-backup-%016llx", zDbToVacuum, r); + + /* Attach the zTempDb database to the database connection. + */ + zSql = sqlite3_mprintf("ATTACH '%q' AS vacuum_db;", zTempDb); + execSql(db, zSql); + sqlite3_free(zSql); + + /* TODO: + ** Set the page_size and auto_vacuum mode for zTempDb here, if desired. + */ + + /* The vacuum will occur inside of a transaction. Set writable_schema + ** to ON so that we can directly update the sqlite_master table in the + ** zTempDb database. + */ + execSql(db, "PRAGMA writable_schema=ON"); + execSql(db, "BEGIN"); + + + /* Query the schema of the main database. Create a mirror schema + ** in the temporary database. + */ + execExecSql(db, + "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) " + " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" + " AND rootpage>0" + ); + execExecSql(db, + "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)" + " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %'" + ); + execExecSql(db, + "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) " + " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'" + ); + + /* Loop through the tables in the main database. For each, do + ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy + ** the contents to the temporary database. + */ + execExecSql(db, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM main.' || quote(name) " + "FROM main.sqlite_master " + "WHERE type = 'table' AND name!='sqlite_sequence' " + " AND rootpage>0" + ); + + /* Copy over the sequence table + */ + execExecSql(db, + "SELECT 'DELETE FROM vacuum_db.' || quote(name) " + "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence'" + ); + execExecSql(db, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM main.' || quote(name) " + "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence'" + ); + + /* Copy the triggers, views, and virtual tables from the main database + ** over to the temporary database. None of these objects has any + ** associated storage, so all we have to do is copy their entries + ** from the SQLITE_MASTER table. + */ + execSql(db, + "INSERT INTO vacuum_db.sqlite_master " + " SELECT type, name, tbl_name, rootpage, sql" + " FROM main.sqlite_master" + " WHERE type='view' OR type='trigger'" + " OR (type='table' AND rootpage=0)" + ); + + /* Commit the transaction and close the database + */ + execSql(db, "COMMIT"); + printf("-- close database\n"); + sqlite3_close(db); + + + /* At this point, zDbToVacuum is unchanged. zTempDb contains a + ** vacuumed copy of zDbToVacuum. Rearrange filenames so that + ** zTempDb becomes thenew zDbToVacuum. + */ + printf("-- rename \"%s\" to \"%s\"\n", zDbToVacuum, zBackupDb); + rename(zDbToVacuum, zBackupDb); + printf("-- rename \"%s\" to \"%s\"\n", zTempDb, zDbToVacuum); + rename(zTempDb, zDbToVacuum); + + /* Release allocated memory */ + sqlite3_free(zTempDb); + sqlite3_free(zBackupDb); + return 0; +} diff --git a/components/external/SQLite-3.8.1/tool/fragck.tcl b/components/external/SQLite-3.8.1/tool/fragck.tcl new file mode 100644 index 0000000000000000000000000000000000000000..35e76f482b6747fa2e70e31bc6acbea7280e2f60 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/fragck.tcl @@ -0,0 +1,149 @@ +# Run this TCL script using "testfixture" to get a report that shows +# the sequence of database pages used by a particular table or index. +# This information is used for fragmentation analysis. +# + +# Get the name of the database to analyze +# + +if {[llength $argv]!=2} { + puts stderr "Usage: $argv0 database-name table-or-index-name" + exit 1 +} +set file_to_analyze [lindex $argv 0] +if {![file exists $file_to_analyze]} { + puts stderr "No such file: $file_to_analyze" + exit 1 +} +if {![file readable $file_to_analyze]} { + puts stderr "File is not readable: $file_to_analyze" + exit 1 +} +if {[file size $file_to_analyze]<512} { + puts stderr "Empty or malformed database: $file_to_analyze" + exit 1 +} +set objname [lindex $argv 1] + +# Open the database +# +sqlite3 db [lindex $argv 0] +set DB [btree_open [lindex $argv 0] 1000 0] + +# This proc is a wrapper around the btree_cursor_info command. The +# second argument is an open btree cursor returned by [btree_cursor]. +# The first argument is the name of an array variable that exists in +# the scope of the caller. If the third argument is non-zero, then +# info is returned for the page that lies $up entries upwards in the +# tree-structure. (i.e. $up==1 returns the parent page, $up==2 the +# grandparent etc.) +# +# The following entries in that array are filled in with information retrieved +# using [btree_cursor_info]: +# +# $arrayvar(page_no) = The page number +# $arrayvar(entry_no) = The entry number +# $arrayvar(page_entries) = Total number of entries on this page +# $arrayvar(cell_size) = Cell size (local payload + header) +# $arrayvar(page_freebytes) = Number of free bytes on this page +# $arrayvar(page_freeblocks) = Number of free blocks on the page +# $arrayvar(payload_bytes) = Total payload size (local + overflow) +# $arrayvar(header_bytes) = Header size in bytes +# $arrayvar(local_payload_bytes) = Local payload size +# $arrayvar(parent) = Parent page number +# +proc cursor_info {arrayvar csr {up 0}} { + upvar $arrayvar a + foreach [list a(page_no) \ + a(entry_no) \ + a(page_entries) \ + a(cell_size) \ + a(page_freebytes) \ + a(page_freeblocks) \ + a(payload_bytes) \ + a(header_bytes) \ + a(local_payload_bytes) \ + a(parent) \ + a(first_ovfl) ] [btree_cursor_info $csr $up] break +} + +# Determine the page-size of the database. This global variable is used +# throughout the script. +# +set pageSize [db eval {PRAGMA page_size}] + +# Find the root page of table or index to be analyzed. Also find out +# if the object is a table or an index. +# +if {$objname=="sqlite_master"} { + set rootpage 1 + set type table +} else { + db eval { + SELECT rootpage, type FROM sqlite_master + WHERE name=$objname + } break + if {![info exists rootpage]} { + puts stderr "no such table or index: $objname" + exit 1 + } + if {$type!="table" && $type!="index"} { + puts stderr "$objname is something other than a table or index" + exit 1 + } + if {![string is integer -strict $rootpage]} { + puts stderr "invalid root page for $objname: $rootpage" + exit 1 + } +} + +# The cursor $csr is pointing to an entry. Print out information +# about the page that $up levels above that page that contains +# the entry. If $up==0 use the page that contains the entry. +# +# If information about the page has been printed already, then +# this is a no-op. +# +proc page_info {csr up} { + global seen + cursor_info ci $csr $up + set pg $ci(page_no) + if {[info exists seen($pg)]} return + set seen($pg) 1 + + # Do parent pages first + # + if {$ci(parent)} { + page_info $csr [expr {$up+1}] + } + + # Find the depth of this page + # + set depth 1 + set i $up + while {$ci(parent)} { + incr i + incr depth + cursor_info ci $csr $i + } + + # print the results + # + puts [format {LEVEL %d: %6d} $depth $pg] +} + + + + +# Loop through the object and print out page numbers +# +set csr [btree_cursor $DB $rootpage 0] +for {btree_first $csr} {![btree_eof $csr]} {btree_next $csr} { + page_info $csr 0 + set i 1 + foreach pg [btree_ovfl_info $DB $csr] { + puts [format {OVFL %3d: %6d} $i $pg] + incr i + } +} +exit 0 diff --git a/components/external/SQLite-3.8.1/tool/genfkey.README b/components/external/SQLite-3.8.1/tool/genfkey.README new file mode 100644 index 0000000000000000000000000000000000000000..57cdff87f8b680d78a345715edb16e6d981b562b --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/genfkey.README @@ -0,0 +1,137 @@ + +OVERVIEW + + The SQLite library is capable of parsing SQL foreign key constraints + supplied as part of CREATE TABLE statements, but it does not actually + implement them. However, most of the features of foreign keys may be + implemented using SQL triggers, which SQLite does support. This text + file describes a feature of the SQLite shell tool (sqlite3) that + extracts foreign key definitions from an existing SQLite database and + creates the set of CREATE TRIGGER statements required to implement + the foreign key constraints. + +CAPABILITIES + + An SQL foreign key is a constraint that requires that each row in + the "child" table corresponds to a row in the "parent" table. For + example, the following schema: + + CREATE TABLE parent(a, b, c, PRIMARY KEY(a, b)); + CREATE TABLE child(d, e, f, FOREIGN KEY(d, e) REFERENCES parent(a, b)); + + implies that for each row in table "child", there must be a row in + "parent" for which the expression (child.d==parent.a AND child.e==parent.b) + is true. The columns in the parent table are required to be either the + primary key columns or subject to a UNIQUE constraint. There is no such + requirement for the columns of the child table. + + At this time, all foreign keys are implemented as if they were + "MATCH NONE", even if the declaration specified "MATCH PARTIAL" or + "MATCH FULL". "MATCH NONE" means that if any of the key columns in + the child table are NULL, then there is no requirement for a corresponding + row in the parent table. So, taking this into account, the expression that + must be true for every row of the child table in the above example is + actually: + + (child.d IS NULL) OR + (child.e IS NULL) OR + (child.d==parent.a AND child.e==parent.b) + + Attempting to insert or update a row in the child table so that the + affected row violates this constraint results in an exception being + thrown. + + The effect of attempting to delete or update a row in the parent table + so that the constraint becomes untrue for one or more rows in the child + table depends on the "ON DELETE" or "ON UPDATE" actions specified as + part of the foreign key definition, respectively. Three different actions + are supported: "RESTRICT" (the default), "CASCADE" and "SET NULL". SQLite + will also parse the "SET DEFAULT" action, but this is not implemented + and "RESTRICT" is used instead. + + RESTRICT: Attempting to update or delete a row in the parent table so + that the constraint becomes untrue for one or more rows in + the child table is not allowed. An exception is thrown. + + CASCADE: Instead of throwing an exception, all corresponding child table + rows are either deleted (if the parent row is being deleted) + or updated to match the new parent key values (if the parent + row is being updated). + + SET NULL: Instead of throwing an exception, the foreign key fields of + all corresponding child table rows are set to NULL. + +LIMITATIONS + + Apart from those limitiations described above: + + * Implicit mapping to composite primary keys is not supported. If + a parent table has a composite primary key, then any child table + that refers to it must explicitly map each column. For example, given + the following definition of table "parent": + + CREATE TABLE parent(a, b, c, PRIMARY KEY(a, b)); + + only the first of the following two definitions of table "child" + is supported: + + CREATE TABLE child(d, e, f, FOREIGN KEY(d, e) REFERENCES parent(a, b)); + CREATE TABLE child(d, e, f, FOREIGN KEY(d, e) REFERENCES parent); + + An implicit reference to a composite primary key is detected as an + error when the program is run (see below). + + * SQLite does not support recursive triggers, and therefore this program + does not support recursive CASCADE or SET NULL foreign key + relationships. If the parent and the child tables of a CASCADE or + SET NULL foreign key are the same table, the generated triggers will + malfunction. This is also true if the recursive foreign key constraint + is indirect (for example if table A references table B which references + table A with a CASCADE or SET NULL foreign key constraint). + + Recursive CASCADE or SET NULL foreign key relationships are *not* + detected as errors when the program is run. Buyer beware. + +USAGE + + The functionality is accessed through an sqlite3 shell tool "dot-command": + + .genfkey ?--no-drop? ?--ignore-errors? ?--exec? + + When this command is run, it first checks the schema of the open SQLite + database for foreign key related errors or inconsistencies. For example, + a foreign key that refers to a parent table that does not exist, or + a foreign key that refers to columns in a parent table that are not + guaranteed to be unique. If such errors are found and the --ignore-errors + option was not present, a message for each one is printed to stderr and + no further processing takes place. + + If errors are found and the --ignore-errors option is passed, then + no error messages are printed. No "CREATE TRIGGER" statements are generated + for foriegn-key definitions that contained errors, they are silently + ignored by subsequent processing. + + All triggers generated by this command have names that match the pattern + "genfkey*". Unless the --no-drop option is specified, then the program + also generates a "DROP TRIGGER" statement for each trigger that exists + in the database with a name that matches this pattern. This allows the + program to be used to upgrade a database schema for which foreign key + triggers have already been installed (i.e. after new tables are created + or existing tables dropped). + + Finally, a series of SQL trigger definitions (CREATE TRIGGER statements) + that implement the foreign key constraints found in the database schema are + generated. + + If the --exec option was passed, then all generated SQL is immediately + executed on the database. Otherwise, the generated SQL strings are output + in the same way as the results of SELECT queries are. Normally, this means + they will be printed to stdout, but this can be configured using other + dot-commands (i.e. ".output"). + + The simplest way to activate the foriegn key definitions in a database + is simply to open it using the shell tool and enter the command + ".genfkey --exec": + + sqlite> .genfkey --exec + diff --git a/components/external/SQLite-3.8.1/tool/genfkey.test b/components/external/SQLite-3.8.1/tool/genfkey.test new file mode 100644 index 0000000000000000000000000000000000000000..3c0073e953dc0a2e60b421181b631c3bcaa37b96 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/genfkey.test @@ -0,0 +1,354 @@ + +package require sqlite3 + +proc do_test {name cmd expected} { + puts -nonewline "$name ..." + set res [uplevel $cmd] + if {$res eq $expected} { + puts Ok + } else { + puts Error + puts " Got: $res" + puts " Expected: $expected" + exit + } +} + +proc execsql {sql} { + uplevel [list db eval $sql] +} + +proc catchsql {sql} { + set rc [catch {uplevel [list db eval $sql]} msg] + list $rc $msg +} + +file delete -force test.db test.db.journal +sqlite3 db test.db + +# The following tests - genfkey-1.* - test RESTRICT foreign keys. +# +do_test genfkey-1.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c)); + CREATE TABLE t2(e REFERENCES t1, f); + CREATE TABLE t3(g, h, i, FOREIGN KEY (h, i) REFERENCES t1(b, c)); + } +} {} +do_test genfkey-1.2 { + execsql [exec ./sqlite3 test.db .genfkey] +} {} +do_test genfkey-1.3 { + catchsql { INSERT INTO t2 VALUES(1, 2) } +} {1 {constraint failed}} +do_test genfkey-1.4 { + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t2 VALUES(1, 2); + } +} {} +do_test genfkey-1.5 { + execsql { INSERT INTO t2 VALUES(NULL, 3) } +} {} +do_test genfkey-1.6 { + catchsql { UPDATE t2 SET e = 5 WHERE e IS NULL } +} {1 {constraint failed}} +do_test genfkey-1.7 { + execsql { UPDATE t2 SET e = 1 WHERE e IS NULL } +} {} +do_test genfkey-1.8 { + execsql { UPDATE t2 SET e = NULL WHERE f = 3 } +} {} +do_test genfkey-1.9 { + catchsql { UPDATE t1 SET a = 10 } +} {1 {constraint failed}} +do_test genfkey-1.9a { + catchsql { UPDATE t1 SET a = NULL } +} {1 {datatype mismatch}} +do_test genfkey-1.10 { + catchsql { DELETE FROM t1 } +} {1 {constraint failed}} +do_test genfkey-1.11 { + execsql { UPDATE t2 SET e = NULL } +} {} +do_test genfkey-1.12 { + execsql { + UPDATE t1 SET a = 10 ; + DELETE FROM t1; + DELETE FROM t2; + } +} {} + +do_test genfkey-1.13 { + execsql { + INSERT INTO t3 VALUES(1, NULL, NULL); + INSERT INTO t3 VALUES(1, 2, NULL); + INSERT INTO t3 VALUES(1, NULL, 3); + } +} {} +do_test genfkey-1.14 { + catchsql { INSERT INTO t3 VALUES(3, 1, 4) } +} {1 {constraint failed}} +do_test genfkey-1.15 { + execsql { + INSERT INTO t1 VALUES(1, 1, 4); + INSERT INTO t3 VALUES(3, 1, 4); + } +} {} +do_test genfkey-1.16 { + catchsql { DELETE FROM t1 } +} {1 {constraint failed}} +do_test genfkey-1.17 { + catchsql { UPDATE t1 SET b = 10} +} {1 {constraint failed}} +do_test genfkey-1.18 { + execsql { UPDATE t1 SET a = 10} +} {} +do_test genfkey-1.19 { + catchsql { UPDATE t3 SET h = 'hello' WHERE i = 3} +} {1 {constraint failed}} + +do_test genfkey-1.X { + execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + } +} {} + +# The following tests - genfkey-2.* - test CASCADE foreign keys. +# +do_test genfkey-2.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c)); + CREATE TABLE t2(e REFERENCES t1 ON UPDATE CASCADE ON DELETE CASCADE, f); + CREATE TABLE t3(g, h, i, + FOREIGN KEY (h, i) + REFERENCES t1(b, c) ON UPDATE CASCADE ON DELETE CASCADE + ); + } +} {} +do_test genfkey-2.2 { + execsql [exec ./sqlite3 test.db .genfkey] +} {} +do_test genfkey-2.3 { + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + INSERT INTO t2 VALUES(1, 'one'); + INSERT INTO t2 VALUES(4, 'four'); + } +} {} +do_test genfkey-2.4 { + execsql { + UPDATE t1 SET a = 2 WHERE a = 1; + SELECT * FROM t2; + } +} {2 one 4 four} +do_test genfkey-2.5 { + execsql { + DELETE FROM t1 WHERE a = 4; + SELECT * FROM t2; + } +} {2 one} +do_test genfkey-2.6 { + execsql { + INSERT INTO t3 VALUES('hello', 2, 3); + UPDATE t1 SET c = 2; + SELECT * FROM t3; + } +} {hello 2 2} +do_test genfkey-2.7 { + execsql { + DELETE FROM t1; + SELECT * FROM t3; + } +} {} +do_test genfkey-2.X { + execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + } +} {} + + +# The following tests - genfkey-3.* - test SET NULL foreign keys. +# +do_test genfkey-3.1 { + execsql { + CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(c, b)); + CREATE TABLE t2(e REFERENCES t1 ON UPDATE SET NULL ON DELETE SET NULL, f); + CREATE TABLE t3(g, h, i, + FOREIGN KEY (h, i) + REFERENCES t1(b, c) ON UPDATE SET NULL ON DELETE SET NULL + ); + } +} {} +do_test genfkey-3.2 { + execsql [exec ./sqlite3 test.db .genfkey] +} {} +do_test genfkey-3.3 { + execsql { + INSERT INTO t1 VALUES(1, 2, 3); + INSERT INTO t1 VALUES(4, 5, 6); + INSERT INTO t2 VALUES(1, 'one'); + INSERT INTO t2 VALUES(4, 'four'); + } +} {} +do_test genfkey-3.4 { + execsql { + UPDATE t1 SET a = 2 WHERE a = 1; + SELECT * FROM t2; + } +} {{} one 4 four} +do_test genfkey-3.5 { + execsql { + DELETE FROM t1 WHERE a = 4; + SELECT * FROM t2; + } +} {{} one {} four} +do_test genfkey-3.6 { + execsql { + INSERT INTO t3 VALUES('hello', 2, 3); + UPDATE t1 SET c = 2; + SELECT * FROM t3; + } +} {hello {} {}} +do_test genfkey-2.7 { + execsql { + UPDATE t3 SET h = 2, i = 2; + DELETE FROM t1; + SELECT * FROM t3; + } +} {hello {} {}} +do_test genfkey-3.X { + execsql { + DROP TABLE t1; + DROP TABLE t2; + DROP TABLE t3; + } +} {} + +# The following tests - genfkey-4.* - test that errors in the schema +# are detected correctly. +# +do_test genfkey-4.1 { + execsql { + CREATE TABLE t1(a REFERENCES nosuchtable, b); + CREATE TABLE t2(a REFERENCES t1, b); + + CREATE TABLE t3(a, b, c, PRIMARY KEY(a, b)); + CREATE TABLE t4(a, b, c, FOREIGN KEY(c, b) REFERENCES t3); + + CREATE TABLE t5(a REFERENCES t4(d), b, c); + CREATE TABLE t6(a REFERENCES t4(a), b, c); + CREATE TABLE t7(a REFERENCES t3(a), b, c); + CREATE TABLE t8(a REFERENCES nosuchtable(a), b, c); + } +} {} + +do_test genfkey-4.X { + set rc [catch {exec ./sqlite3 test.db .genfkey} msg] + list $rc $msg +} "1 {[string trim { +Error in table t5: foreign key columns do not exist +Error in table t8: foreign key columns do not exist +Error in table t4: implicit mapping to composite primary key +Error in table t1: implicit mapping to non-existant primary key +Error in table t2: implicit mapping to non-existant primary key +Error in table t6: foreign key is not unique +Error in table t7: foreign key is not unique +}]}" + +# Test that ticket #3800 has been resolved. +# +do_test genfkey-5.1 { + execsql { + DROP TABLE t1; DROP TABLE t2; DROP TABLE t3; + DROP TABLE t4; DROP TABLE t5; DROP TABLE t6; + DROP TABLE t7; DROP TABLE t8; + } +} {} +do_test genfkey-5.2 { + execsql { + CREATE TABLE "t.3" (c1 PRIMARY KEY); + CREATE TABLE t13 (c1, foreign key(c1) references "t.3"(c1)); + } +} {} +do_test genfkey-5.3 { + set rc [catch {exec ./sqlite3 test.db .genfkey} msg] +} {0} +do_test genfkey-5.4 { + db eval $msg +} {} +do_test genfkey-5.5 { + catchsql { INSERT INTO t13 VALUES(1) } +} {1 {constraint failed}} +do_test genfkey-5.5 { + catchsql { + INSERT INTO "t.3" VALUES(1); + INSERT INTO t13 VALUES(1); + } +} {0 {}} + +# Test also column names that require quoting. +do_test genfkey-6.1 { + execsql { + DROP TABLE "t.3"; + DROP TABLE t13; + CREATE TABLE p( + "a.1 first", "b.2 second", + UNIQUE("a.1 first", "b.2 second") + ); + CREATE TABLE c( + "c.1 I", "d.2 II", + FOREIGN KEY("c.1 I", "d.2 II") + REFERENCES p("a.1 first", "b.2 second") + ON UPDATE CASCADE ON DELETE CASCADE + ); + } +} {} +do_test genfkey-6.2 { + set rc [catch {exec ./sqlite3 test.db .genfkey} msg] +} {0} +do_test genfkey-6.3 { + execsql $msg + execsql { + INSERT INTO p VALUES('A', 'B'); + INSERT INTO p VALUES('C', 'D'); + INSERT INTO c VALUES('A', 'B'); + INSERT INTO c VALUES('C', 'D'); + UPDATE p SET "a.1 first" = 'X' WHERE rowid = 1; + DELETE FROM p WHERE rowid = 2; + } + execsql { SELECT * FROM c } +} {X B} + +do_test genfkey-6.4 { + execsql { + DROP TABLE p; + DROP TABLE c; + CREATE TABLE parent("a.1", PRIMARY KEY("a.1")); + CREATE TABLE child("b.2", FOREIGN KEY("b.2") REFERENCES parent("a.1")); + } + set rc [catch {exec ./sqlite3 test.db .genfkey} msg] +} {0} +do_test genfkey-6.5 { + execsql $msg + execsql { + INSERT INTO parent VALUES(1); + INSERT INTO child VALUES(1); + } + catchsql { UPDATE parent SET "a.1"=0 } +} {1 {constraint failed}} +do_test genfkey-6.6 { + catchsql { UPDATE child SET "b.2"=7 } +} {1 {constraint failed}} +do_test genfkey-6.7 { + execsql { + SELECT * FROM parent; + SELECT * FROM child; + } +} {1 1} + diff --git a/components/external/SQLite-3.8.1/tool/getlock.c b/components/external/SQLite-3.8.1/tool/getlock.c new file mode 100644 index 0000000000000000000000000000000000000000..7eff04d7f97c00efa08ac2b9aac253f2acd7a98a --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/getlock.c @@ -0,0 +1,134 @@ +/* +** This utility program looks at an SQLite database and determines whether +** or not it is locked, the kind of lock, and who is holding this lock. +** +** This only works on unix when the posix advisory locking method is used +** (which is the default on unix) and when the PENDING_BYTE is in its +** usual place. +*/ +#include +#include +#include +#include +#include +#include +#include +#include + +static void usage(const char *argv0){ + fprintf(stderr, "Usage: %s database\n", argv0); + exit(1); +} + +/* Check for a conflicting lock. If one is found, print an this +** on standard output using the format string given and return 1. +** If there are no conflicting locks, return 0. +*/ +static int isLocked( + int h, /* File descriptor to check */ + int type, /* F_RDLCK or F_WRLCK */ + unsigned int iOfst, /* First byte of the lock */ + unsigned int iCnt, /* Number of bytes in the lock range */ + const char *zType /* Type of lock */ +){ + struct flock lk; + + memset(&lk, 0, sizeof(lk)); + lk.l_type = type; + lk.l_whence = SEEK_SET; + lk.l_start = iOfst; + lk.l_len = iCnt; + if( fcntl(h, F_GETLK, &lk)==(-1) ){ + fprintf(stderr, "fcntl(%d) failed: errno=%d\n", h, errno); + exit(1); + } + if( lk.l_type==F_UNLCK ) return 0; + printf("%s lock held by %d\n", zType, (int)lk.l_pid); + return 1; +} + +/* +** Location of locking bytes in the database file +*/ +#define PENDING_BYTE (0x40000000) +#define RESERVED_BYTE (PENDING_BYTE+1) +#define SHARED_FIRST (PENDING_BYTE+2) +#define SHARED_SIZE 510 + +/* +** Lock locations for shared-memory locks used by WAL mode. +*/ +#define SHM_BASE 120 +#define SHM_WRITE SHM_BASE +#define SHM_CHECKPOINT (SHM_BASE+1) +#define SHM_RECOVER (SHM_BASE+2) +#define SHM_READ_FIRST (SHM_BASE+3) +#define SHM_READ_SIZE 5 + + +int main(int argc, char **argv){ + int hDb; /* File descriptor for the open database file */ + int hShm; /* File descriptor for WAL shared-memory file */ + char *zShm; /* Name of the shared-memory file for WAL mode */ + ssize_t got; /* Bytes read from header */ + int isWal; /* True if in WAL mode */ + int nName; /* Length of filename */ + unsigned char aHdr[100]; /* Database header */ + int nLock = 0; /* Number of locks held */ + int i; /* Loop counter */ + + if( argc!=2 ) usage(argv[0]); + hDb = open(argv[1], O_RDONLY, 0); + if( hDb<0 ){ + fprintf(stderr, "cannot open %s\n", argv[1]); + return 1; + } + + /* Make sure we are dealing with an database file */ + got = read(hDb, aHdr, 100); + if( got!=100 || memcmp(aHdr, "SQLite format 3",16)!=0 ){ + fprintf(stderr, "not an SQLite database: %s\n", argv[1]); + exit(1); + } + + /* First check for an exclusive lock */ + if( isLocked(hDb, F_RDLCK, SHARED_FIRST, SHARED_SIZE, "EXCLUSIVE") ){ + return 0; + } + isWal = aHdr[18]==2; + if( isWal==0 ){ + /* Rollback mode */ + if( isLocked(hDb, F_RDLCK, PENDING_BYTE, 1, "PENDING") ) return 0; + if( isLocked(hDb, F_RDLCK, RESERVED_BYTE, 1, "RESERVED") ) return 0; + if( isLocked(hDb, F_WRLCK, SHARED_FIRST, SHARED_SIZE, "SHARED") ){ + return 0; + } + }else{ + /* WAL mode */ + nName = (int)strlen(argv[1]); + zShm = malloc( nName + 100 ); + if( zShm==0 ){ + fprintf(stderr, "out of memory\n"); + exit(1); + } + memcpy(zShm, argv[1], nName); + memcpy(&zShm[nName], "-shm", 5); + hShm = open(zShm, O_RDONLY, 0); + if( hShm<0 ){ + fprintf(stderr, "cannot open %s\n", zShm); + return 1; + } + if( isLocked(hShm, F_RDLCK, SHM_RECOVER, 1, "WAL-RECOVERY") ){ + return 0; + } + nLock += isLocked(hShm, F_RDLCK, SHM_CHECKPOINT, 1, "WAL-CHECKPOINT"); + nLock += isLocked(hShm, F_RDLCK, SHM_WRITE, 1, "WAL-WRITE"); + for(i=0; i +#include +#include +#include +#include +#include + +#ifndef __WIN32__ +# if defined(_WIN32) || defined(WIN32) +# define __WIN32__ +# endif +#endif + +#ifdef __WIN32__ +#ifdef __cplusplus +extern "C" { +#endif +extern int access(const char *path, int mode); +#ifdef __cplusplus +} +#endif +#else +#include +#endif + +/* #define PRIVATE static */ +#define PRIVATE + +#ifdef TEST +#define MAXRHS 5 /* Set low to exercise exception code */ +#else +#define MAXRHS 1000 +#endif + +static int showPrecedenceConflict = 0; +static char *msort(char*,char**,int(*)(const char*,const char*)); + +/* +** Compilers are getting increasingly pedantic about type conversions +** as C evolves ever closer to Ada.... To work around the latest problems +** we have to define the following variant of strlen(). +*/ +#define lemonStrlen(X) ((int)strlen(X)) + +/* a few forward declarations... */ +struct rule; +struct lemon; +struct action; + +static struct action *Action_new(void); +static struct action *Action_sort(struct action *); + +/********** From the file "build.h" ************************************/ +void FindRulePrecedences(); +void FindFirstSets(); +void FindStates(); +void FindLinks(); +void FindFollowSets(); +void FindActions(); + +/********* From the file "configlist.h" *********************************/ +void Configlist_init(void); +struct config *Configlist_add(struct rule *, int); +struct config *Configlist_addbasis(struct rule *, int); +void Configlist_closure(struct lemon *); +void Configlist_sort(void); +void Configlist_sortbasis(void); +struct config *Configlist_return(void); +struct config *Configlist_basis(void); +void Configlist_eat(struct config *); +void Configlist_reset(void); + +/********* From the file "error.h" ***************************************/ +void ErrorMsg(const char *, int,const char *, ...); + +/****** From the file "option.h" ******************************************/ +enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR, + OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR}; +struct s_options { + enum option_type type; + const char *label; + char *arg; + const char *message; +}; +int OptInit(char**,struct s_options*,FILE*); +int OptNArgs(void); +char *OptArg(int); +void OptErr(int); +void OptPrint(void); + +/******** From the file "parse.h" *****************************************/ +void Parse(struct lemon *lemp); + +/********* From the file "plink.h" ***************************************/ +struct plink *Plink_new(void); +void Plink_add(struct plink **, struct config *); +void Plink_copy(struct plink **, struct plink *); +void Plink_delete(struct plink *); + +/********** From the file "report.h" *************************************/ +void Reprint(struct lemon *); +void ReportOutput(struct lemon *); +void ReportTable(struct lemon *, int); +void ReportHeader(struct lemon *); +void CompressTables(struct lemon *); +void ResortStates(struct lemon *); + +/********** From the file "set.h" ****************************************/ +void SetSize(int); /* All sets will be of size N */ +char *SetNew(void); /* A new set for element 0..N */ +void SetFree(char*); /* Deallocate a set */ +int SetAdd(char*,int); /* Add element to a set */ +int SetUnion(char *,char *); /* A <- A U B, thru element N */ +#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */ + +/********** From the file "struct.h" *************************************/ +/* +** Principal data structures for the LEMON parser generator. +*/ + +typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean; + +/* Symbols (terminals and nonterminals) of the grammar are stored +** in the following: */ +enum symbol_type { + TERMINAL, + NONTERMINAL, + MULTITERMINAL +}; +enum e_assoc { + LEFT, + RIGHT, + NONE, + UNK +}; +struct symbol { + const char *name; /* Name of the symbol */ + int index; /* Index number for this symbol */ + enum symbol_type type; /* Symbols are all either TERMINALS or NTs */ + struct rule *rule; /* Linked list of rules of this (if an NT) */ + struct symbol *fallback; /* fallback token in case this token doesn't parse */ + int prec; /* Precedence if defined (-1 otherwise) */ + enum e_assoc assoc; /* Associativity if precedence is defined */ + char *firstset; /* First-set for all rules of this symbol */ + Boolean lambda; /* True if NT and can generate an empty string */ + int useCnt; /* Number of times used */ + char *destructor; /* Code which executes whenever this symbol is + ** popped from the stack during error processing */ + int destLineno; /* Line number for start of destructor */ + char *datatype; /* The data type of information held by this + ** object. Only used if type==NONTERMINAL */ + int dtnum; /* The data type number. In the parser, the value + ** stack is a union. The .yy%d element of this + ** union is the correct data type for this object */ + /* The following fields are used by MULTITERMINALs only */ + int nsubsym; /* Number of constituent symbols in the MULTI */ + struct symbol **subsym; /* Array of constituent symbols */ +}; + +/* Each production rule in the grammar is stored in the following +** structure. */ +struct rule { + struct symbol *lhs; /* Left-hand side of the rule */ + const char *lhsalias; /* Alias for the LHS (NULL if none) */ + int lhsStart; /* True if left-hand side is the start symbol */ + int ruleline; /* Line number for the rule */ + int nrhs; /* Number of RHS symbols */ + struct symbol **rhs; /* The RHS symbols */ + const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */ + int line; /* Line number at which code begins */ + const char *code; /* The code executed when this rule is reduced */ + struct symbol *precsym; /* Precedence symbol for this rule */ + int index; /* An index number for this rule */ + Boolean canReduce; /* True if this rule is ever reduced */ + struct rule *nextlhs; /* Next rule with the same LHS */ + struct rule *next; /* Next rule in the global list */ +}; + +/* A configuration is a production rule of the grammar together with +** a mark (dot) showing how much of that rule has been processed so far. +** Configurations also contain a follow-set which is a list of terminal +** symbols which are allowed to immediately follow the end of the rule. +** Every configuration is recorded as an instance of the following: */ +enum cfgstatus { + COMPLETE, + INCOMPLETE +}; +struct config { + struct rule *rp; /* The rule upon which the configuration is based */ + int dot; /* The parse point */ + char *fws; /* Follow-set for this configuration only */ + struct plink *fplp; /* Follow-set forward propagation links */ + struct plink *bplp; /* Follow-set backwards propagation links */ + struct state *stp; /* Pointer to state which contains this */ + enum cfgstatus status; /* used during followset and shift computations */ + struct config *next; /* Next configuration in the state */ + struct config *bp; /* The next basis configuration */ +}; + +enum e_action { + SHIFT, + ACCEPT, + REDUCE, + ERROR, + SSCONFLICT, /* A shift/shift conflict */ + SRCONFLICT, /* Was a reduce, but part of a conflict */ + RRCONFLICT, /* Was a reduce, but part of a conflict */ + SH_RESOLVED, /* Was a shift. Precedence resolved conflict */ + RD_RESOLVED, /* Was reduce. Precedence resolved conflict */ + NOT_USED /* Deleted by compression */ +}; + +/* Every shift or reduce operation is stored as one of the following */ +struct action { + struct symbol *sp; /* The look-ahead symbol */ + enum e_action type; + union { + struct state *stp; /* The new state, if a shift */ + struct rule *rp; /* The rule, if a reduce */ + } x; + struct action *next; /* Next action for this state */ + struct action *collide; /* Next action with the same hash */ +}; + +/* Each state of the generated parser's finite state machine +** is encoded as an instance of the following structure. */ +struct state { + struct config *bp; /* The basis configurations for this state */ + struct config *cfp; /* All configurations in this set */ + int statenum; /* Sequential number for this state */ + struct action *ap; /* Array of actions for this state */ + int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */ + int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */ + int iDflt; /* Default action */ +}; +#define NO_OFFSET (-2147483647) + +/* A followset propagation link indicates that the contents of one +** configuration followset should be propagated to another whenever +** the first changes. */ +struct plink { + struct config *cfp; /* The configuration to which linked */ + struct plink *next; /* The next propagate link */ +}; + +/* The state vector for the entire parser generator is recorded as +** follows. (LEMON uses no global variables and makes little use of +** static variables. Fields in the following structure can be thought +** of as begin global variables in the program.) */ +struct lemon { + struct state **sorted; /* Table of states sorted by state number */ + struct rule *rule; /* List of all rules */ + int nstate; /* Number of states */ + int nrule; /* Number of rules */ + int nsymbol; /* Number of terminal and nonterminal symbols */ + int nterminal; /* Number of terminal symbols */ + struct symbol **symbols; /* Sorted array of pointers to symbols */ + int errorcnt; /* Number of errors */ + struct symbol *errsym; /* The error symbol */ + struct symbol *wildcard; /* Token that matches anything */ + char *name; /* Name of the generated parser */ + char *arg; /* Declaration of the 3th argument to parser */ + char *tokentype; /* Type of terminal symbols in the parser stack */ + char *vartype; /* The default type of non-terminal symbols */ + char *start; /* Name of the start symbol for the grammar */ + char *stacksize; /* Size of the parser stack */ + char *include; /* Code to put at the start of the C file */ + char *error; /* Code to execute when an error is seen */ + char *overflow; /* Code to execute on a stack overflow */ + char *failure; /* Code to execute on parser failure */ + char *accept; /* Code to execute when the parser excepts */ + char *extracode; /* Code appended to the generated file */ + char *tokendest; /* Code to execute to destroy token data */ + char *vardest; /* Code for the default non-terminal destructor */ + char *filename; /* Name of the input file */ + char *outname; /* Name of the current output file */ + char *tokenprefix; /* A prefix added to token names in the .h file */ + int nconflict; /* Number of parsing conflicts */ + int tablesize; /* Size of the parse tables */ + int basisflag; /* Print only basis configurations */ + int has_fallback; /* True if any %fallback is seen in the grammar */ + int nolinenosflag; /* True if #line statements should not be printed */ + char *argv0; /* Name of the program */ +}; + +#define MemoryCheck(X) if((X)==0){ \ + extern void memory_error(); \ + memory_error(); \ +} + +/**************** From the file "table.h" *********************************/ +/* +** All code in this file has been automatically generated +** from a specification in the file +** "table.q" +** by the associative array code building program "aagen". +** Do not edit this file! Instead, edit the specification +** file, then rerun aagen. +*/ +/* +** Code for processing tables in the LEMON parser generator. +*/ +/* Routines for handling a strings */ + +const char *Strsafe(const char *); + +void Strsafe_init(void); +int Strsafe_insert(const char *); +const char *Strsafe_find(const char *); + +/* Routines for handling symbols of the grammar */ + +struct symbol *Symbol_new(const char *); +int Symbolcmpp(const void *, const void *); +void Symbol_init(void); +int Symbol_insert(struct symbol *, const char *); +struct symbol *Symbol_find(const char *); +struct symbol *Symbol_Nth(int); +int Symbol_count(void); +struct symbol **Symbol_arrayof(void); + +/* Routines to manage the state table */ + +int Configcmp(const char *, const char *); +struct state *State_new(void); +void State_init(void); +int State_insert(struct state *, struct config *); +struct state *State_find(struct config *); +struct state **State_arrayof(/* */); + +/* Routines used for efficiency in Configlist_add */ + +void Configtable_init(void); +int Configtable_insert(struct config *); +struct config *Configtable_find(struct config *); +void Configtable_clear(int(*)(struct config *)); + +/****************** From the file "action.c" *******************************/ +/* +** Routines processing parser actions in the LEMON parser generator. +*/ + +/* Allocate a new parser action */ +static struct action *Action_new(void){ + static struct action *freelist = 0; + struct action *newaction; + + if( freelist==0 ){ + int i; + int amt = 100; + freelist = (struct action *)calloc(amt, sizeof(struct action)); + if( freelist==0 ){ + fprintf(stderr,"Unable to allocate memory for a new parser action."); + exit(1); + } + for(i=0; inext; + return newaction; +} + +/* Compare two actions for sorting purposes. Return negative, zero, or +** positive if the first action is less than, equal to, or greater than +** the first +*/ +static int actioncmp( + struct action *ap1, + struct action *ap2 +){ + int rc; + rc = ap1->sp->index - ap2->sp->index; + if( rc==0 ){ + rc = (int)ap1->type - (int)ap2->type; + } + if( rc==0 && ap1->type==REDUCE ){ + rc = ap1->x.rp->index - ap2->x.rp->index; + } + if( rc==0 ){ + rc = (int) (ap2 - ap1); + } + return rc; +} + +/* Sort parser actions */ +static struct action *Action_sort( + struct action *ap +){ + ap = (struct action *)msort((char *)ap,(char **)&ap->next, + (int(*)(const char*,const char*))actioncmp); + return ap; +} + +void Action_add( + struct action **app, + enum e_action type, + struct symbol *sp, + char *arg +){ + struct action *newaction; + newaction = Action_new(); + newaction->next = *app; + *app = newaction; + newaction->type = type; + newaction->sp = sp; + if( type==SHIFT ){ + newaction->x.stp = (struct state *)arg; + }else{ + newaction->x.rp = (struct rule *)arg; + } +} +/********************** New code to implement the "acttab" module ***********/ +/* +** This module implements routines use to construct the yy_action[] table. +*/ + +/* +** The state of the yy_action table under construction is an instance of +** the following structure. +** +** The yy_action table maps the pair (state_number, lookahead) into an +** action_number. The table is an array of integers pairs. The state_number +** determines an initial offset into the yy_action array. The lookahead +** value is then added to this initial offset to get an index X into the +** yy_action array. If the aAction[X].lookahead equals the value of the +** of the lookahead input, then the value of the action_number output is +** aAction[X].action. If the lookaheads do not match then the +** default action for the state_number is returned. +** +** All actions associated with a single state_number are first entered +** into aLookahead[] using multiple calls to acttab_action(). Then the +** actions for that single state_number are placed into the aAction[] +** array with a single call to acttab_insert(). The acttab_insert() call +** also resets the aLookahead[] array in preparation for the next +** state number. +*/ +struct lookahead_action { + int lookahead; /* Value of the lookahead token */ + int action; /* Action to take on the given lookahead */ +}; +typedef struct acttab acttab; +struct acttab { + int nAction; /* Number of used slots in aAction[] */ + int nActionAlloc; /* Slots allocated for aAction[] */ + struct lookahead_action + *aAction, /* The yy_action[] table under construction */ + *aLookahead; /* A single new transaction set */ + int mnLookahead; /* Minimum aLookahead[].lookahead */ + int mnAction; /* Action associated with mnLookahead */ + int mxLookahead; /* Maximum aLookahead[].lookahead */ + int nLookahead; /* Used slots in aLookahead[] */ + int nLookaheadAlloc; /* Slots allocated in aLookahead[] */ +}; + +/* Return the number of entries in the yy_action table */ +#define acttab_size(X) ((X)->nAction) + +/* The value for the N-th entry in yy_action */ +#define acttab_yyaction(X,N) ((X)->aAction[N].action) + +/* The value for the N-th entry in yy_lookahead */ +#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead) + +/* Free all memory associated with the given acttab */ +void acttab_free(acttab *p){ + free( p->aAction ); + free( p->aLookahead ); + free( p ); +} + +/* Allocate a new acttab structure */ +acttab *acttab_alloc(void){ + acttab *p = (acttab *) calloc( 1, sizeof(*p) ); + if( p==0 ){ + fprintf(stderr,"Unable to allocate memory for a new acttab."); + exit(1); + } + memset(p, 0, sizeof(*p)); + return p; +} + +/* Add a new action to the current transaction set. +** +** This routine is called once for each lookahead for a particular +** state. +*/ +void acttab_action(acttab *p, int lookahead, int action){ + if( p->nLookahead>=p->nLookaheadAlloc ){ + p->nLookaheadAlloc += 25; + p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead, + sizeof(p->aLookahead[0])*p->nLookaheadAlloc ); + if( p->aLookahead==0 ){ + fprintf(stderr,"malloc failed\n"); + exit(1); + } + } + if( p->nLookahead==0 ){ + p->mxLookahead = lookahead; + p->mnLookahead = lookahead; + p->mnAction = action; + }else{ + if( p->mxLookaheadmxLookahead = lookahead; + if( p->mnLookahead>lookahead ){ + p->mnLookahead = lookahead; + p->mnAction = action; + } + } + p->aLookahead[p->nLookahead].lookahead = lookahead; + p->aLookahead[p->nLookahead].action = action; + p->nLookahead++; +} + +/* +** Add the transaction set built up with prior calls to acttab_action() +** into the current action table. Then reset the transaction set back +** to an empty set in preparation for a new round of acttab_action() calls. +** +** Return the offset into the action table of the new transaction. +*/ +int acttab_insert(acttab *p){ + int i, j, k, n; + assert( p->nLookahead>0 ); + + /* Make sure we have enough space to hold the expanded action table + ** in the worst case. The worst case occurs if the transaction set + ** must be appended to the current action table + */ + n = p->mxLookahead + 1; + if( p->nAction + n >= p->nActionAlloc ){ + int oldAlloc = p->nActionAlloc; + p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20; + p->aAction = (struct lookahead_action *) realloc( p->aAction, + sizeof(p->aAction[0])*p->nActionAlloc); + if( p->aAction==0 ){ + fprintf(stderr,"malloc failed\n"); + exit(1); + } + for(i=oldAlloc; inActionAlloc; i++){ + p->aAction[i].lookahead = -1; + p->aAction[i].action = -1; + } + } + + /* Scan the existing action table looking for an offset that is a + ** duplicate of the current transaction set. Fall out of the loop + ** if and when the duplicate is found. + ** + ** i is the index in p->aAction[] where p->mnLookahead is inserted. + */ + for(i=p->nAction-1; i>=0; i--){ + if( p->aAction[i].lookahead==p->mnLookahead ){ + /* All lookaheads and actions in the aLookahead[] transaction + ** must match against the candidate aAction[i] entry. */ + if( p->aAction[i].action!=p->mnAction ) continue; + for(j=0; jnLookahead; j++){ + k = p->aLookahead[j].lookahead - p->mnLookahead + i; + if( k<0 || k>=p->nAction ) break; + if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break; + if( p->aLookahead[j].action!=p->aAction[k].action ) break; + } + if( jnLookahead ) continue; + + /* No possible lookahead value that is not in the aLookahead[] + ** transaction is allowed to match aAction[i] */ + n = 0; + for(j=0; jnAction; j++){ + if( p->aAction[j].lookahead<0 ) continue; + if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++; + } + if( n==p->nLookahead ){ + break; /* An exact match is found at offset i */ + } + } + } + + /* If no existing offsets exactly match the current transaction, find an + ** an empty offset in the aAction[] table in which we can add the + ** aLookahead[] transaction. + */ + if( i<0 ){ + /* Look for holes in the aAction[] table that fit the current + ** aLookahead[] transaction. Leave i set to the offset of the hole. + ** If no holes are found, i is left at p->nAction, which means the + ** transaction will be appended. */ + for(i=0; inActionAlloc - p->mxLookahead; i++){ + if( p->aAction[i].lookahead<0 ){ + for(j=0; jnLookahead; j++){ + k = p->aLookahead[j].lookahead - p->mnLookahead + i; + if( k<0 ) break; + if( p->aAction[k].lookahead>=0 ) break; + } + if( jnLookahead ) continue; + for(j=0; jnAction; j++){ + if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break; + } + if( j==p->nAction ){ + break; /* Fits in empty slots */ + } + } + } + } + /* Insert transaction set at index i. */ + for(j=0; jnLookahead; j++){ + k = p->aLookahead[j].lookahead - p->mnLookahead + i; + p->aAction[k] = p->aLookahead[j]; + if( k>=p->nAction ) p->nAction = k+1; + } + p->nLookahead = 0; + + /* Return the offset that is added to the lookahead in order to get the + ** index into yy_action of the action */ + return i - p->mnLookahead; +} + +/********************** From the file "build.c" *****************************/ +/* +** Routines to construction the finite state machine for the LEMON +** parser generator. +*/ + +/* Find a precedence symbol of every rule in the grammar. +** +** Those rules which have a precedence symbol coded in the input +** grammar using the "[symbol]" construct will already have the +** rp->precsym field filled. Other rules take as their precedence +** symbol the first RHS symbol with a defined precedence. If there +** are not RHS symbols with a defined precedence, the precedence +** symbol field is left blank. +*/ +void FindRulePrecedences(struct lemon *xp) +{ + struct rule *rp; + for(rp=xp->rule; rp; rp=rp->next){ + if( rp->precsym==0 ){ + int i, j; + for(i=0; inrhs && rp->precsym==0; i++){ + struct symbol *sp = rp->rhs[i]; + if( sp->type==MULTITERMINAL ){ + for(j=0; jnsubsym; j++){ + if( sp->subsym[j]->prec>=0 ){ + rp->precsym = sp->subsym[j]; + break; + } + } + }else if( sp->prec>=0 ){ + rp->precsym = rp->rhs[i]; + } + } + } + } + return; +} + +/* Find all nonterminals which will generate the empty string. +** Then go back and compute the first sets of every nonterminal. +** The first set is the set of all terminal symbols which can begin +** a string generated by that nonterminal. +*/ +void FindFirstSets(struct lemon *lemp) +{ + int i, j; + struct rule *rp; + int progress; + + for(i=0; insymbol; i++){ + lemp->symbols[i]->lambda = LEMON_FALSE; + } + for(i=lemp->nterminal; insymbol; i++){ + lemp->symbols[i]->firstset = SetNew(); + } + + /* First compute all lambdas */ + do{ + progress = 0; + for(rp=lemp->rule; rp; rp=rp->next){ + if( rp->lhs->lambda ) continue; + for(i=0; inrhs; i++){ + struct symbol *sp = rp->rhs[i]; + assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE ); + if( sp->lambda==LEMON_FALSE ) break; + } + if( i==rp->nrhs ){ + rp->lhs->lambda = LEMON_TRUE; + progress = 1; + } + } + }while( progress ); + + /* Now compute all first sets */ + do{ + struct symbol *s1, *s2; + progress = 0; + for(rp=lemp->rule; rp; rp=rp->next){ + s1 = rp->lhs; + for(i=0; inrhs; i++){ + s2 = rp->rhs[i]; + if( s2->type==TERMINAL ){ + progress += SetAdd(s1->firstset,s2->index); + break; + }else if( s2->type==MULTITERMINAL ){ + for(j=0; jnsubsym; j++){ + progress += SetAdd(s1->firstset,s2->subsym[j]->index); + } + break; + }else if( s1==s2 ){ + if( s1->lambda==LEMON_FALSE ) break; + }else{ + progress += SetUnion(s1->firstset,s2->firstset); + if( s2->lambda==LEMON_FALSE ) break; + } + } + } + }while( progress ); + return; +} + +/* Compute all LR(0) states for the grammar. Links +** are added to between some states so that the LR(1) follow sets +** can be computed later. +*/ +PRIVATE struct state *getstate(struct lemon *); /* forward reference */ +void FindStates(struct lemon *lemp) +{ + struct symbol *sp; + struct rule *rp; + + Configlist_init(); + + /* Find the start symbol */ + if( lemp->start ){ + sp = Symbol_find(lemp->start); + if( sp==0 ){ + ErrorMsg(lemp->filename,0, +"The specified start symbol \"%s\" is not \ +in a nonterminal of the grammar. \"%s\" will be used as the start \ +symbol instead.",lemp->start,lemp->rule->lhs->name); + lemp->errorcnt++; + sp = lemp->rule->lhs; + } + }else{ + sp = lemp->rule->lhs; + } + + /* Make sure the start symbol doesn't occur on the right-hand side of + ** any rule. Report an error if it does. (YACC would generate a new + ** start symbol in this case.) */ + for(rp=lemp->rule; rp; rp=rp->next){ + int i; + for(i=0; inrhs; i++){ + if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */ + ErrorMsg(lemp->filename,0, +"The start symbol \"%s\" occurs on the \ +right-hand side of a rule. This will result in a parser which \ +does not work properly.",sp->name); + lemp->errorcnt++; + } + } + } + + /* The basis configuration set for the first state + ** is all rules which have the start symbol as their + ** left-hand side */ + for(rp=sp->rule; rp; rp=rp->nextlhs){ + struct config *newcfp; + rp->lhsStart = 1; + newcfp = Configlist_addbasis(rp,0); + SetAdd(newcfp->fws,0); + } + + /* Compute the first state. All other states will be + ** computed automatically during the computation of the first one. + ** The returned pointer to the first state is not used. */ + (void)getstate(lemp); + return; +} + +/* Return a pointer to a state which is described by the configuration +** list which has been built from calls to Configlist_add. +*/ +PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */ +PRIVATE struct state *getstate(struct lemon *lemp) +{ + struct config *cfp, *bp; + struct state *stp; + + /* Extract the sorted basis of the new state. The basis was constructed + ** by prior calls to "Configlist_addbasis()". */ + Configlist_sortbasis(); + bp = Configlist_basis(); + + /* Get a state with the same basis */ + stp = State_find(bp); + if( stp ){ + /* A state with the same basis already exists! Copy all the follow-set + ** propagation links from the state under construction into the + ** preexisting state, then return a pointer to the preexisting state */ + struct config *x, *y; + for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){ + Plink_copy(&y->bplp,x->bplp); + Plink_delete(x->fplp); + x->fplp = x->bplp = 0; + } + cfp = Configlist_return(); + Configlist_eat(cfp); + }else{ + /* This really is a new state. Construct all the details */ + Configlist_closure(lemp); /* Compute the configuration closure */ + Configlist_sort(); /* Sort the configuration closure */ + cfp = Configlist_return(); /* Get a pointer to the config list */ + stp = State_new(); /* A new state structure */ + MemoryCheck(stp); + stp->bp = bp; /* Remember the configuration basis */ + stp->cfp = cfp; /* Remember the configuration closure */ + stp->statenum = lemp->nstate++; /* Every state gets a sequence number */ + stp->ap = 0; /* No actions, yet. */ + State_insert(stp,stp->bp); /* Add to the state table */ + buildshifts(lemp,stp); /* Recursively compute successor states */ + } + return stp; +} + +/* +** Return true if two symbols are the same. +*/ +int same_symbol(struct symbol *a, struct symbol *b) +{ + int i; + if( a==b ) return 1; + if( a->type!=MULTITERMINAL ) return 0; + if( b->type!=MULTITERMINAL ) return 0; + if( a->nsubsym!=b->nsubsym ) return 0; + for(i=0; insubsym; i++){ + if( a->subsym[i]!=b->subsym[i] ) return 0; + } + return 1; +} + +/* Construct all successor states to the given state. A "successor" +** state is any state which can be reached by a shift action. +*/ +PRIVATE void buildshifts(struct lemon *lemp, struct state *stp) +{ + struct config *cfp; /* For looping thru the config closure of "stp" */ + struct config *bcfp; /* For the inner loop on config closure of "stp" */ + struct config *newcfg; /* */ + struct symbol *sp; /* Symbol following the dot in configuration "cfp" */ + struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */ + struct state *newstp; /* A pointer to a successor state */ + + /* Each configuration becomes complete after it contibutes to a successor + ** state. Initially, all configurations are incomplete */ + for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE; + + /* Loop through all configurations of the state "stp" */ + for(cfp=stp->cfp; cfp; cfp=cfp->next){ + if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */ + if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */ + Configlist_reset(); /* Reset the new config set */ + sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */ + + /* For every configuration in the state "stp" which has the symbol "sp" + ** following its dot, add the same configuration to the basis set under + ** construction but with the dot shifted one symbol to the right. */ + for(bcfp=cfp; bcfp; bcfp=bcfp->next){ + if( bcfp->status==COMPLETE ) continue; /* Already used */ + if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */ + bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */ + if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */ + bcfp->status = COMPLETE; /* Mark this config as used */ + newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1); + Plink_add(&newcfg->bplp,bcfp); + } + + /* Get a pointer to the state described by the basis configuration set + ** constructed in the preceding loop */ + newstp = getstate(lemp); + + /* The state "newstp" is reached from the state "stp" by a shift action + ** on the symbol "sp" */ + if( sp->type==MULTITERMINAL ){ + int i; + for(i=0; insubsym; i++){ + Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp); + } + }else{ + Action_add(&stp->ap,SHIFT,sp,(char *)newstp); + } + } +} + +/* +** Construct the propagation links +*/ +void FindLinks(struct lemon *lemp) +{ + int i; + struct config *cfp, *other; + struct state *stp; + struct plink *plp; + + /* Housekeeping detail: + ** Add to every propagate link a pointer back to the state to + ** which the link is attached. */ + for(i=0; instate; i++){ + stp = lemp->sorted[i]; + for(cfp=stp->cfp; cfp; cfp=cfp->next){ + cfp->stp = stp; + } + } + + /* Convert all backlinks into forward links. Only the forward + ** links are used in the follow-set computation. */ + for(i=0; instate; i++){ + stp = lemp->sorted[i]; + for(cfp=stp->cfp; cfp; cfp=cfp->next){ + for(plp=cfp->bplp; plp; plp=plp->next){ + other = plp->cfp; + Plink_add(&other->fplp,cfp); + } + } + } +} + +/* Compute all followsets. +** +** A followset is the set of all symbols which can come immediately +** after a configuration. +*/ +void FindFollowSets(struct lemon *lemp) +{ + int i; + struct config *cfp; + struct plink *plp; + int progress; + int change; + + for(i=0; instate; i++){ + for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ + cfp->status = INCOMPLETE; + } + } + + do{ + progress = 0; + for(i=0; instate; i++){ + for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ + if( cfp->status==COMPLETE ) continue; + for(plp=cfp->fplp; plp; plp=plp->next){ + change = SetUnion(plp->cfp->fws,cfp->fws); + if( change ){ + plp->cfp->status = INCOMPLETE; + progress = 1; + } + } + cfp->status = COMPLETE; + } + } + }while( progress ); +} + +static int resolve_conflict(struct action *,struct action *); + +/* Compute the reduce actions, and resolve conflicts. +*/ +void FindActions(struct lemon *lemp) +{ + int i,j; + struct config *cfp; + struct state *stp; + struct symbol *sp; + struct rule *rp; + + /* Add all of the reduce actions + ** A reduce action is added for each element of the followset of + ** a configuration which has its dot at the extreme right. + */ + for(i=0; instate; i++){ /* Loop over all states */ + stp = lemp->sorted[i]; + for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */ + if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */ + for(j=0; jnterminal; j++){ + if( SetFind(cfp->fws,j) ){ + /* Add a reduce action to the state "stp" which will reduce by the + ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */ + Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp); + } + } + } + } + } + + /* Add the accepting token */ + if( lemp->start ){ + sp = Symbol_find(lemp->start); + if( sp==0 ) sp = lemp->rule->lhs; + }else{ + sp = lemp->rule->lhs; + } + /* Add to the first state (which is always the starting state of the + ** finite state machine) an action to ACCEPT if the lookahead is the + ** start nonterminal. */ + Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0); + + /* Resolve conflicts */ + for(i=0; instate; i++){ + struct action *ap, *nap; + struct state *stp; + stp = lemp->sorted[i]; + /* assert( stp->ap ); */ + stp->ap = Action_sort(stp->ap); + for(ap=stp->ap; ap && ap->next; ap=ap->next){ + for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){ + /* The two actions "ap" and "nap" have the same lookahead. + ** Figure out which one should be used */ + lemp->nconflict += resolve_conflict(ap,nap); + } + } + } + + /* Report an error for each rule that can never be reduced. */ + for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE; + for(i=0; instate; i++){ + struct action *ap; + for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){ + if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE; + } + } + for(rp=lemp->rule; rp; rp=rp->next){ + if( rp->canReduce ) continue; + ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n"); + lemp->errorcnt++; + } +} + +/* Resolve a conflict between the two given actions. If the +** conflict can't be resolved, return non-zero. +** +** NO LONGER TRUE: +** To resolve a conflict, first look to see if either action +** is on an error rule. In that case, take the action which +** is not associated with the error rule. If neither or both +** actions are associated with an error rule, then try to +** use precedence to resolve the conflict. +** +** If either action is a SHIFT, then it must be apx. This +** function won't work if apx->type==REDUCE and apy->type==SHIFT. +*/ +static int resolve_conflict( + struct action *apx, + struct action *apy +){ + struct symbol *spx, *spy; + int errcnt = 0; + assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */ + if( apx->type==SHIFT && apy->type==SHIFT ){ + apy->type = SSCONFLICT; + errcnt++; + } + if( apx->type==SHIFT && apy->type==REDUCE ){ + spx = apx->sp; + spy = apy->x.rp->precsym; + if( spy==0 || spx->prec<0 || spy->prec<0 ){ + /* Not enough precedence information. */ + apy->type = SRCONFLICT; + errcnt++; + }else if( spx->prec>spy->prec ){ /* higher precedence wins */ + apy->type = RD_RESOLVED; + }else if( spx->precprec ){ + apx->type = SH_RESOLVED; + }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */ + apy->type = RD_RESOLVED; /* associativity */ + }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */ + apx->type = SH_RESOLVED; + }else{ + assert( spx->prec==spy->prec && spx->assoc==NONE ); + apy->type = SRCONFLICT; + errcnt++; + } + }else if( apx->type==REDUCE && apy->type==REDUCE ){ + spx = apx->x.rp->precsym; + spy = apy->x.rp->precsym; + if( spx==0 || spy==0 || spx->prec<0 || + spy->prec<0 || spx->prec==spy->prec ){ + apy->type = RRCONFLICT; + errcnt++; + }else if( spx->prec>spy->prec ){ + apy->type = RD_RESOLVED; + }else if( spx->precprec ){ + apx->type = RD_RESOLVED; + } + }else{ + assert( + apx->type==SH_RESOLVED || + apx->type==RD_RESOLVED || + apx->type==SSCONFLICT || + apx->type==SRCONFLICT || + apx->type==RRCONFLICT || + apy->type==SH_RESOLVED || + apy->type==RD_RESOLVED || + apy->type==SSCONFLICT || + apy->type==SRCONFLICT || + apy->type==RRCONFLICT + ); + /* The REDUCE/SHIFT case cannot happen because SHIFTs come before + ** REDUCEs on the list. If we reach this point it must be because + ** the parser conflict had already been resolved. */ + } + return errcnt; +} +/********************* From the file "configlist.c" *************************/ +/* +** Routines to processing a configuration list and building a state +** in the LEMON parser generator. +*/ + +static struct config *freelist = 0; /* List of free configurations */ +static struct config *current = 0; /* Top of list of configurations */ +static struct config **currentend = 0; /* Last on list of configs */ +static struct config *basis = 0; /* Top of list of basis configs */ +static struct config **basisend = 0; /* End of list of basis configs */ + +/* Return a pointer to a new configuration */ +PRIVATE struct config *newconfig(){ + struct config *newcfg; + if( freelist==0 ){ + int i; + int amt = 3; + freelist = (struct config *)calloc( amt, sizeof(struct config) ); + if( freelist==0 ){ + fprintf(stderr,"Unable to allocate memory for a new configuration."); + exit(1); + } + for(i=0; inext; + return newcfg; +} + +/* The configuration "old" is no longer used */ +PRIVATE void deleteconfig(struct config *old) +{ + old->next = freelist; + freelist = old; +} + +/* Initialized the configuration list builder */ +void Configlist_init(){ + current = 0; + currentend = ¤t; + basis = 0; + basisend = &basis; + Configtable_init(); + return; +} + +/* Initialized the configuration list builder */ +void Configlist_reset(){ + current = 0; + currentend = ¤t; + basis = 0; + basisend = &basis; + Configtable_clear(0); + return; +} + +/* Add another configuration to the configuration list */ +struct config *Configlist_add( + struct rule *rp, /* The rule */ + int dot /* Index into the RHS of the rule where the dot goes */ +){ + struct config *cfp, model; + + assert( currentend!=0 ); + model.rp = rp; + model.dot = dot; + cfp = Configtable_find(&model); + if( cfp==0 ){ + cfp = newconfig(); + cfp->rp = rp; + cfp->dot = dot; + cfp->fws = SetNew(); + cfp->stp = 0; + cfp->fplp = cfp->bplp = 0; + cfp->next = 0; + cfp->bp = 0; + *currentend = cfp; + currentend = &cfp->next; + Configtable_insert(cfp); + } + return cfp; +} + +/* Add a basis configuration to the configuration list */ +struct config *Configlist_addbasis(struct rule *rp, int dot) +{ + struct config *cfp, model; + + assert( basisend!=0 ); + assert( currentend!=0 ); + model.rp = rp; + model.dot = dot; + cfp = Configtable_find(&model); + if( cfp==0 ){ + cfp = newconfig(); + cfp->rp = rp; + cfp->dot = dot; + cfp->fws = SetNew(); + cfp->stp = 0; + cfp->fplp = cfp->bplp = 0; + cfp->next = 0; + cfp->bp = 0; + *currentend = cfp; + currentend = &cfp->next; + *basisend = cfp; + basisend = &cfp->bp; + Configtable_insert(cfp); + } + return cfp; +} + +/* Compute the closure of the configuration list */ +void Configlist_closure(struct lemon *lemp) +{ + struct config *cfp, *newcfp; + struct rule *rp, *newrp; + struct symbol *sp, *xsp; + int i, dot; + + assert( currentend!=0 ); + for(cfp=current; cfp; cfp=cfp->next){ + rp = cfp->rp; + dot = cfp->dot; + if( dot>=rp->nrhs ) continue; + sp = rp->rhs[dot]; + if( sp->type==NONTERMINAL ){ + if( sp->rule==0 && sp!=lemp->errsym ){ + ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.", + sp->name); + lemp->errorcnt++; + } + for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){ + newcfp = Configlist_add(newrp,0); + for(i=dot+1; inrhs; i++){ + xsp = rp->rhs[i]; + if( xsp->type==TERMINAL ){ + SetAdd(newcfp->fws,xsp->index); + break; + }else if( xsp->type==MULTITERMINAL ){ + int k; + for(k=0; knsubsym; k++){ + SetAdd(newcfp->fws, xsp->subsym[k]->index); + } + break; + }else{ + SetUnion(newcfp->fws,xsp->firstset); + if( xsp->lambda==LEMON_FALSE ) break; + } + } + if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp); + } + } + } + return; +} + +/* Sort the configuration list */ +void Configlist_sort(){ + current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp); + currentend = 0; + return; +} + +/* Sort the basis configuration list */ +void Configlist_sortbasis(){ + basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp); + basisend = 0; + return; +} + +/* Return a pointer to the head of the configuration list and +** reset the list */ +struct config *Configlist_return(){ + struct config *old; + old = current; + current = 0; + currentend = 0; + return old; +} + +/* Return a pointer to the head of the configuration list and +** reset the list */ +struct config *Configlist_basis(){ + struct config *old; + old = basis; + basis = 0; + basisend = 0; + return old; +} + +/* Free all elements of the given configuration list */ +void Configlist_eat(struct config *cfp) +{ + struct config *nextcfp; + for(; cfp; cfp=nextcfp){ + nextcfp = cfp->next; + assert( cfp->fplp==0 ); + assert( cfp->bplp==0 ); + if( cfp->fws ) SetFree(cfp->fws); + deleteconfig(cfp); + } + return; +} +/***************** From the file "error.c" *********************************/ +/* +** Code for printing error message. +*/ + +void ErrorMsg(const char *filename, int lineno, const char *format, ...){ + va_list ap; + fprintf(stderr, "%s:%d: ", filename, lineno); + va_start(ap, format); + vfprintf(stderr,format,ap); + va_end(ap); + fprintf(stderr, "\n"); +} +/**************** From the file "main.c" ************************************/ +/* +** Main program file for the LEMON parser generator. +*/ + +/* Report an out-of-memory condition and abort. This function +** is used mostly by the "MemoryCheck" macro in struct.h +*/ +void memory_error(){ + fprintf(stderr,"Out of memory. Aborting...\n"); + exit(1); +} + +static int nDefine = 0; /* Number of -D options on the command line */ +static char **azDefine = 0; /* Name of the -D macros */ + +/* This routine is called with the argument to each -D command-line option. +** Add the macro defined to the azDefine array. +*/ +static void handle_D_option(char *z){ + char **paz; + nDefine++; + azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine); + if( azDefine==0 ){ + fprintf(stderr,"out of memory\n"); + exit(1); + } + paz = &azDefine[nDefine-1]; + *paz = (char *) malloc( lemonStrlen(z)+1 ); + if( *paz==0 ){ + fprintf(stderr,"out of memory\n"); + exit(1); + } + strcpy(*paz, z); + for(z=*paz; *z && *z!='='; z++){} + *z = 0; +} + +static char *user_templatename = NULL; +static void handle_T_option(char *z){ + user_templatename = (char *) malloc( lemonStrlen(z)+1 ); + if( user_templatename==0 ){ + memory_error(); + } + strcpy(user_templatename, z); +} + +/* The main program. Parse the command line and do it... */ +int main(int argc, char **argv) +{ + static int version = 0; + static int rpflag = 0; + static int basisflag = 0; + static int compress = 0; + static int quiet = 0; + static int statistics = 0; + static int mhflag = 0; + static int nolinenosflag = 0; + static int noResort = 0; + static struct s_options options[] = { + {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."}, + {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."}, + {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."}, + {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."}, + {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."}, + {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."}, + {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."}, + {OPT_FLAG, "p", (char*)&showPrecedenceConflict, + "Show conflicts resolved by precedence rules"}, + {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."}, + {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"}, + {OPT_FLAG, "s", (char*)&statistics, + "Print parser stats to standard output."}, + {OPT_FLAG, "x", (char*)&version, "Print the version number."}, + {OPT_FLAG,0,0,0} + }; + int i; + int exitcode; + struct lemon lem; + + OptInit(argv,options,stderr); + if( version ){ + printf("Lemon version 1.0\n"); + exit(0); + } + if( OptNArgs()!=1 ){ + fprintf(stderr,"Exactly one filename argument is required.\n"); + exit(1); + } + memset(&lem, 0, sizeof(lem)); + lem.errorcnt = 0; + + /* Initialize the machine */ + Strsafe_init(); + Symbol_init(); + State_init(); + lem.argv0 = argv[0]; + lem.filename = OptArg(0); + lem.basisflag = basisflag; + lem.nolinenosflag = nolinenosflag; + Symbol_new("$"); + lem.errsym = Symbol_new("error"); + lem.errsym->useCnt = 0; + + /* Parse the input file */ + Parse(&lem); + if( lem.errorcnt ) exit(lem.errorcnt); + if( lem.nrule==0 ){ + fprintf(stderr,"Empty grammar.\n"); + exit(1); + } + + /* Count and index the symbols of the grammar */ + lem.nsymbol = Symbol_count(); + Symbol_new("{default}"); + lem.symbols = Symbol_arrayof(); + for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i; + qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*), Symbolcmpp); + for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i; + for(i=1; isupper(lem.symbols[i]->name[0]); i++); + lem.nterminal = i; + + /* Generate a reprint of the grammar, if requested on the command line */ + if( rpflag ){ + Reprint(&lem); + }else{ + /* Initialize the size for all follow and first sets */ + SetSize(lem.nterminal+1); + + /* Find the precedence for every production rule (that has one) */ + FindRulePrecedences(&lem); + + /* Compute the lambda-nonterminals and the first-sets for every + ** nonterminal */ + FindFirstSets(&lem); + + /* Compute all LR(0) states. Also record follow-set propagation + ** links so that the follow-set can be computed later */ + lem.nstate = 0; + FindStates(&lem); + lem.sorted = State_arrayof(); + + /* Tie up loose ends on the propagation links */ + FindLinks(&lem); + + /* Compute the follow set of every reducible configuration */ + FindFollowSets(&lem); + + /* Compute the action tables */ + FindActions(&lem); + + /* Compress the action tables */ + if( compress==0 ) CompressTables(&lem); + + /* Reorder and renumber the states so that states with fewer choices + ** occur at the end. This is an optimization that helps make the + ** generated parser tables smaller. */ + if( noResort==0 ) ResortStates(&lem); + + /* Generate a report of the parser generated. (the "y.output" file) */ + if( !quiet ) ReportOutput(&lem); + + /* Generate the source code for the parser */ + ReportTable(&lem, mhflag); + + /* Produce a header file for use by the scanner. (This step is + ** omitted if the "-m" option is used because makeheaders will + ** generate the file for us.) */ + if( !mhflag ) ReportHeader(&lem); + } + if( statistics ){ + printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n", + lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule); + printf(" %d states, %d parser table entries, %d conflicts\n", + lem.nstate, lem.tablesize, lem.nconflict); + } + if( lem.nconflict > 0 ){ + fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict); + } + + /* return 0 on success, 1 on failure. */ + exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0; + exit(exitcode); + return (exitcode); +} +/******************** From the file "msort.c" *******************************/ +/* +** A generic merge-sort program. +** +** USAGE: +** Let "ptr" be a pointer to some structure which is at the head of +** a null-terminated list. Then to sort the list call: +** +** ptr = msort(ptr,&(ptr->next),cmpfnc); +** +** In the above, "cmpfnc" is a pointer to a function which compares +** two instances of the structure and returns an integer, as in +** strcmp. The second argument is a pointer to the pointer to the +** second element of the linked list. This address is used to compute +** the offset to the "next" field within the structure. The offset to +** the "next" field must be constant for all structures in the list. +** +** The function returns a new pointer which is the head of the list +** after sorting. +** +** ALGORITHM: +** Merge-sort. +*/ + +/* +** Return a pointer to the next structure in the linked list. +*/ +#define NEXT(A) (*(char**)(((char*)A)+offset)) + +/* +** Inputs: +** a: A sorted, null-terminated linked list. (May be null). +** b: A sorted, null-terminated linked list. (May be null). +** cmp: A pointer to the comparison function. +** offset: Offset in the structure to the "next" field. +** +** Return Value: +** A pointer to the head of a sorted list containing the elements +** of both a and b. +** +** Side effects: +** The "next" pointers for elements in the lists a and b are +** changed. +*/ +static char *merge( + char *a, + char *b, + int (*cmp)(const char*,const char*), + int offset +){ + char *ptr, *head; + + if( a==0 ){ + head = b; + }else if( b==0 ){ + head = a; + }else{ + if( (*cmp)(a,b)<=0 ){ + ptr = a; + a = NEXT(a); + }else{ + ptr = b; + b = NEXT(b); + } + head = ptr; + while( a && b ){ + if( (*cmp)(a,b)<=0 ){ + NEXT(ptr) = a; + ptr = a; + a = NEXT(a); + }else{ + NEXT(ptr) = b; + ptr = b; + b = NEXT(b); + } + } + if( a ) NEXT(ptr) = a; + else NEXT(ptr) = b; + } + return head; +} + +/* +** Inputs: +** list: Pointer to a singly-linked list of structures. +** next: Pointer to pointer to the second element of the list. +** cmp: A comparison function. +** +** Return Value: +** A pointer to the head of a sorted list containing the elements +** orginally in list. +** +** Side effects: +** The "next" pointers for elements in list are changed. +*/ +#define LISTSIZE 30 +static char *msort( + char *list, + char **next, + int (*cmp)(const char*,const char*) +){ + unsigned long offset; + char *ep; + char *set[LISTSIZE]; + int i; + offset = (unsigned long)next - (unsigned long)list; + for(i=0; istate = WAITING_FOR_DECL_KEYWORD; + }else if( islower(x[0]) ){ + psp->lhs = Symbol_new(x); + psp->nrhs = 0; + psp->lhsalias = 0; + psp->state = WAITING_FOR_ARROW; + }else if( x[0]=='{' ){ + if( psp->prevrule==0 ){ + ErrorMsg(psp->filename,psp->tokenlineno, +"There is no prior rule upon which to attach the code \ +fragment which begins on this line."); + psp->errorcnt++; + }else if( psp->prevrule->code!=0 ){ + ErrorMsg(psp->filename,psp->tokenlineno, +"Code fragment beginning on this line is not the first \ +to follow the previous rule."); + psp->errorcnt++; + }else{ + psp->prevrule->line = psp->tokenlineno; + psp->prevrule->code = &x[1]; + } + }else if( x[0]=='[' ){ + psp->state = PRECEDENCE_MARK_1; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Token \"%s\" should be either \"%%\" or a nonterminal name.", + x); + psp->errorcnt++; + } + break; + case PRECEDENCE_MARK_1: + if( !isupper(x[0]) ){ + ErrorMsg(psp->filename,psp->tokenlineno, + "The precedence symbol must be a terminal."); + psp->errorcnt++; + }else if( psp->prevrule==0 ){ + ErrorMsg(psp->filename,psp->tokenlineno, + "There is no prior rule to assign precedence \"[%s]\".",x); + psp->errorcnt++; + }else if( psp->prevrule->precsym!=0 ){ + ErrorMsg(psp->filename,psp->tokenlineno, +"Precedence mark on this line is not the first \ +to follow the previous rule."); + psp->errorcnt++; + }else{ + psp->prevrule->precsym = Symbol_new(x); + } + psp->state = PRECEDENCE_MARK_2; + break; + case PRECEDENCE_MARK_2: + if( x[0]!=']' ){ + ErrorMsg(psp->filename,psp->tokenlineno, + "Missing \"]\" on precedence mark."); + psp->errorcnt++; + } + psp->state = WAITING_FOR_DECL_OR_RULE; + break; + case WAITING_FOR_ARROW: + if( x[0]==':' && x[1]==':' && x[2]=='=' ){ + psp->state = IN_RHS; + }else if( x[0]=='(' ){ + psp->state = LHS_ALIAS_1; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Expected to see a \":\" following the LHS symbol \"%s\".", + psp->lhs->name); + psp->errorcnt++; + psp->state = RESYNC_AFTER_RULE_ERROR; + } + break; + case LHS_ALIAS_1: + if( isalpha(x[0]) ){ + psp->lhsalias = x; + psp->state = LHS_ALIAS_2; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "\"%s\" is not a valid alias for the LHS \"%s\"\n", + x,psp->lhs->name); + psp->errorcnt++; + psp->state = RESYNC_AFTER_RULE_ERROR; + } + break; + case LHS_ALIAS_2: + if( x[0]==')' ){ + psp->state = LHS_ALIAS_3; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); + psp->errorcnt++; + psp->state = RESYNC_AFTER_RULE_ERROR; + } + break; + case LHS_ALIAS_3: + if( x[0]==':' && x[1]==':' && x[2]=='=' ){ + psp->state = IN_RHS; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Missing \"->\" following: \"%s(%s)\".", + psp->lhs->name,psp->lhsalias); + psp->errorcnt++; + psp->state = RESYNC_AFTER_RULE_ERROR; + } + break; + case IN_RHS: + if( x[0]=='.' ){ + struct rule *rp; + rp = (struct rule *)calloc( sizeof(struct rule) + + sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1); + if( rp==0 ){ + ErrorMsg(psp->filename,psp->tokenlineno, + "Can't allocate enough memory for this rule."); + psp->errorcnt++; + psp->prevrule = 0; + }else{ + int i; + rp->ruleline = psp->tokenlineno; + rp->rhs = (struct symbol**)&rp[1]; + rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]); + for(i=0; inrhs; i++){ + rp->rhs[i] = psp->rhs[i]; + rp->rhsalias[i] = psp->alias[i]; + } + rp->lhs = psp->lhs; + rp->lhsalias = psp->lhsalias; + rp->nrhs = psp->nrhs; + rp->code = 0; + rp->precsym = 0; + rp->index = psp->gp->nrule++; + rp->nextlhs = rp->lhs->rule; + rp->lhs->rule = rp; + rp->next = 0; + if( psp->firstrule==0 ){ + psp->firstrule = psp->lastrule = rp; + }else{ + psp->lastrule->next = rp; + psp->lastrule = rp; + } + psp->prevrule = rp; + } + psp->state = WAITING_FOR_DECL_OR_RULE; + }else if( isalpha(x[0]) ){ + if( psp->nrhs>=MAXRHS ){ + ErrorMsg(psp->filename,psp->tokenlineno, + "Too many symbols on RHS of rule beginning at \"%s\".", + x); + psp->errorcnt++; + psp->state = RESYNC_AFTER_RULE_ERROR; + }else{ + psp->rhs[psp->nrhs] = Symbol_new(x); + psp->alias[psp->nrhs] = 0; + psp->nrhs++; + } + }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){ + struct symbol *msp = psp->rhs[psp->nrhs-1]; + if( msp->type!=MULTITERMINAL ){ + struct symbol *origsp = msp; + msp = (struct symbol *) calloc(1,sizeof(*msp)); + memset(msp, 0, sizeof(*msp)); + msp->type = MULTITERMINAL; + msp->nsubsym = 1; + msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*)); + msp->subsym[0] = origsp; + msp->name = origsp->name; + psp->rhs[psp->nrhs-1] = msp; + } + msp->nsubsym++; + msp->subsym = (struct symbol **) realloc(msp->subsym, + sizeof(struct symbol*)*msp->nsubsym); + msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]); + if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){ + ErrorMsg(psp->filename,psp->tokenlineno, + "Cannot form a compound containing a non-terminal"); + psp->errorcnt++; + } + }else if( x[0]=='(' && psp->nrhs>0 ){ + psp->state = RHS_ALIAS_1; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Illegal character on RHS of rule: \"%s\".",x); + psp->errorcnt++; + psp->state = RESYNC_AFTER_RULE_ERROR; + } + break; + case RHS_ALIAS_1: + if( isalpha(x[0]) ){ + psp->alias[psp->nrhs-1] = x; + psp->state = RHS_ALIAS_2; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n", + x,psp->rhs[psp->nrhs-1]->name); + psp->errorcnt++; + psp->state = RESYNC_AFTER_RULE_ERROR; + } + break; + case RHS_ALIAS_2: + if( x[0]==')' ){ + psp->state = IN_RHS; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); + psp->errorcnt++; + psp->state = RESYNC_AFTER_RULE_ERROR; + } + break; + case WAITING_FOR_DECL_KEYWORD: + if( isalpha(x[0]) ){ + psp->declkeyword = x; + psp->declargslot = 0; + psp->decllinenoslot = 0; + psp->insertLineMacro = 1; + psp->state = WAITING_FOR_DECL_ARG; + if( strcmp(x,"name")==0 ){ + psp->declargslot = &(psp->gp->name); + psp->insertLineMacro = 0; + }else if( strcmp(x,"include")==0 ){ + psp->declargslot = &(psp->gp->include); + }else if( strcmp(x,"code")==0 ){ + psp->declargslot = &(psp->gp->extracode); + }else if( strcmp(x,"token_destructor")==0 ){ + psp->declargslot = &psp->gp->tokendest; + }else if( strcmp(x,"default_destructor")==0 ){ + psp->declargslot = &psp->gp->vardest; + }else if( strcmp(x,"token_prefix")==0 ){ + psp->declargslot = &psp->gp->tokenprefix; + psp->insertLineMacro = 0; + }else if( strcmp(x,"syntax_error")==0 ){ + psp->declargslot = &(psp->gp->error); + }else if( strcmp(x,"parse_accept")==0 ){ + psp->declargslot = &(psp->gp->accept); + }else if( strcmp(x,"parse_failure")==0 ){ + psp->declargslot = &(psp->gp->failure); + }else if( strcmp(x,"stack_overflow")==0 ){ + psp->declargslot = &(psp->gp->overflow); + }else if( strcmp(x,"extra_argument")==0 ){ + psp->declargslot = &(psp->gp->arg); + psp->insertLineMacro = 0; + }else if( strcmp(x,"token_type")==0 ){ + psp->declargslot = &(psp->gp->tokentype); + psp->insertLineMacro = 0; + }else if( strcmp(x,"default_type")==0 ){ + psp->declargslot = &(psp->gp->vartype); + psp->insertLineMacro = 0; + }else if( strcmp(x,"stack_size")==0 ){ + psp->declargslot = &(psp->gp->stacksize); + psp->insertLineMacro = 0; + }else if( strcmp(x,"start_symbol")==0 ){ + psp->declargslot = &(psp->gp->start); + psp->insertLineMacro = 0; + }else if( strcmp(x,"left")==0 ){ + psp->preccounter++; + psp->declassoc = LEFT; + psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; + }else if( strcmp(x,"right")==0 ){ + psp->preccounter++; + psp->declassoc = RIGHT; + psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; + }else if( strcmp(x,"nonassoc")==0 ){ + psp->preccounter++; + psp->declassoc = NONE; + psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; + }else if( strcmp(x,"destructor")==0 ){ + psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL; + }else if( strcmp(x,"type")==0 ){ + psp->state = WAITING_FOR_DATATYPE_SYMBOL; + }else if( strcmp(x,"fallback")==0 ){ + psp->fallback = 0; + psp->state = WAITING_FOR_FALLBACK_ID; + }else if( strcmp(x,"wildcard")==0 ){ + psp->state = WAITING_FOR_WILDCARD_ID; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Unknown declaration keyword: \"%%%s\".",x); + psp->errorcnt++; + psp->state = RESYNC_AFTER_DECL_ERROR; + } + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Illegal declaration keyword: \"%s\".",x); + psp->errorcnt++; + psp->state = RESYNC_AFTER_DECL_ERROR; + } + break; + case WAITING_FOR_DESTRUCTOR_SYMBOL: + if( !isalpha(x[0]) ){ + ErrorMsg(psp->filename,psp->tokenlineno, + "Symbol name missing after %%destructor keyword"); + psp->errorcnt++; + psp->state = RESYNC_AFTER_DECL_ERROR; + }else{ + struct symbol *sp = Symbol_new(x); + psp->declargslot = &sp->destructor; + psp->decllinenoslot = &sp->destLineno; + psp->insertLineMacro = 1; + psp->state = WAITING_FOR_DECL_ARG; + } + break; + case WAITING_FOR_DATATYPE_SYMBOL: + if( !isalpha(x[0]) ){ + ErrorMsg(psp->filename,psp->tokenlineno, + "Symbol name missing after %%type keyword"); + psp->errorcnt++; + psp->state = RESYNC_AFTER_DECL_ERROR; + }else{ + struct symbol *sp = Symbol_find(x); + if((sp) && (sp->datatype)){ + ErrorMsg(psp->filename,psp->tokenlineno, + "Symbol %%type \"%s\" already defined", x); + psp->errorcnt++; + psp->state = RESYNC_AFTER_DECL_ERROR; + }else{ + if (!sp){ + sp = Symbol_new(x); + } + psp->declargslot = &sp->datatype; + psp->insertLineMacro = 0; + psp->state = WAITING_FOR_DECL_ARG; + } + } + break; + case WAITING_FOR_PRECEDENCE_SYMBOL: + if( x[0]=='.' ){ + psp->state = WAITING_FOR_DECL_OR_RULE; + }else if( isupper(x[0]) ){ + struct symbol *sp; + sp = Symbol_new(x); + if( sp->prec>=0 ){ + ErrorMsg(psp->filename,psp->tokenlineno, + "Symbol \"%s\" has already be given a precedence.",x); + psp->errorcnt++; + }else{ + sp->prec = psp->preccounter; + sp->assoc = psp->declassoc; + } + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Can't assign a precedence to \"%s\".",x); + psp->errorcnt++; + } + break; + case WAITING_FOR_DECL_ARG: + if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){ + const char *zOld, *zNew; + char *zBuf, *z; + int nOld, n, nLine, nNew, nBack; + int addLineMacro; + char zLine[50]; + zNew = x; + if( zNew[0]=='"' || zNew[0]=='{' ) zNew++; + nNew = lemonStrlen(zNew); + if( *psp->declargslot ){ + zOld = *psp->declargslot; + }else{ + zOld = ""; + } + nOld = lemonStrlen(zOld); + n = nOld + nNew + 20; + addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro && + (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0); + if( addLineMacro ){ + for(z=psp->filename, nBack=0; *z; z++){ + if( *z=='\\' ) nBack++; + } + sprintf(zLine, "#line %d ", psp->tokenlineno); + nLine = lemonStrlen(zLine); + n += nLine + lemonStrlen(psp->filename) + nBack; + } + *psp->declargslot = (char *) realloc(*psp->declargslot, n); + zBuf = *psp->declargslot + nOld; + if( addLineMacro ){ + if( nOld && zBuf[-1]!='\n' ){ + *(zBuf++) = '\n'; + } + memcpy(zBuf, zLine, nLine); + zBuf += nLine; + *(zBuf++) = '"'; + for(z=psp->filename; *z; z++){ + if( *z=='\\' ){ + *(zBuf++) = '\\'; + } + *(zBuf++) = *z; + } + *(zBuf++) = '"'; + *(zBuf++) = '\n'; + } + if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){ + psp->decllinenoslot[0] = psp->tokenlineno; + } + memcpy(zBuf, zNew, nNew); + zBuf += nNew; + *zBuf = 0; + psp->state = WAITING_FOR_DECL_OR_RULE; + }else{ + ErrorMsg(psp->filename,psp->tokenlineno, + "Illegal argument to %%%s: %s",psp->declkeyword,x); + psp->errorcnt++; + psp->state = RESYNC_AFTER_DECL_ERROR; + } + break; + case WAITING_FOR_FALLBACK_ID: + if( x[0]=='.' ){ + psp->state = WAITING_FOR_DECL_OR_RULE; + }else if( !isupper(x[0]) ){ + ErrorMsg(psp->filename, psp->tokenlineno, + "%%fallback argument \"%s\" should be a token", x); + psp->errorcnt++; + }else{ + struct symbol *sp = Symbol_new(x); + if( psp->fallback==0 ){ + psp->fallback = sp; + }else if( sp->fallback ){ + ErrorMsg(psp->filename, psp->tokenlineno, + "More than one fallback assigned to token %s", x); + psp->errorcnt++; + }else{ + sp->fallback = psp->fallback; + psp->gp->has_fallback = 1; + } + } + break; + case WAITING_FOR_WILDCARD_ID: + if( x[0]=='.' ){ + psp->state = WAITING_FOR_DECL_OR_RULE; + }else if( !isupper(x[0]) ){ + ErrorMsg(psp->filename, psp->tokenlineno, + "%%wildcard argument \"%s\" should be a token", x); + psp->errorcnt++; + }else{ + struct symbol *sp = Symbol_new(x); + if( psp->gp->wildcard==0 ){ + psp->gp->wildcard = sp; + }else{ + ErrorMsg(psp->filename, psp->tokenlineno, + "Extra wildcard to token: %s", x); + psp->errorcnt++; + } + } + break; + case RESYNC_AFTER_RULE_ERROR: +/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; +** break; */ + case RESYNC_AFTER_DECL_ERROR: + if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; + if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD; + break; + } +} + +/* Run the preprocessor over the input file text. The global variables +** azDefine[0] through azDefine[nDefine-1] contains the names of all defined +** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and +** comments them out. Text in between is also commented out as appropriate. +*/ +static void preprocess_input(char *z){ + int i, j, k, n; + int exclude = 0; + int start = 0; + int lineno = 1; + int start_lineno = 1; + for(i=0; z[i]; i++){ + if( z[i]=='\n' ) lineno++; + if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue; + if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){ + if( exclude ){ + exclude--; + if( exclude==0 ){ + for(j=start; jfilename; + ps.errorcnt = 0; + ps.state = INITIALIZE; + + /* Begin by reading the input file */ + fp = fopen(ps.filename,"rb"); + if( fp==0 ){ + ErrorMsg(ps.filename,0,"Can't open this file for reading."); + gp->errorcnt++; + return; + } + fseek(fp,0,2); + filesize = ftell(fp); + rewind(fp); + filebuf = (char *)malloc( filesize+1 ); + if( filebuf==0 ){ + ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.", + filesize+1); + gp->errorcnt++; + fclose(fp); + return; + } + if( fread(filebuf,1,filesize,fp)!=filesize ){ + ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.", + filesize); + free(filebuf); + gp->errorcnt++; + fclose(fp); + return; + } + fclose(fp); + filebuf[filesize] = 0; + + /* Make an initial pass through the file to handle %ifdef and %ifndef */ + preprocess_input(filebuf); + + /* Now scan the text of the input file */ + lineno = 1; + for(cp=filebuf; (c= *cp)!=0; ){ + if( c=='\n' ) lineno++; /* Keep track of the line number */ + if( isspace(c) ){ cp++; continue; } /* Skip all white space */ + if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */ + cp+=2; + while( (c= *cp)!=0 && c!='\n' ) cp++; + continue; + } + if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */ + cp+=2; + while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){ + if( c=='\n' ) lineno++; + cp++; + } + if( c ) cp++; + continue; + } + ps.tokenstart = cp; /* Mark the beginning of the token */ + ps.tokenlineno = lineno; /* Linenumber on which token begins */ + if( c=='\"' ){ /* String literals */ + cp++; + while( (c= *cp)!=0 && c!='\"' ){ + if( c=='\n' ) lineno++; + cp++; + } + if( c==0 ){ + ErrorMsg(ps.filename,startline, +"String starting on this line is not terminated before the end of the file."); + ps.errorcnt++; + nextcp = cp; + }else{ + nextcp = cp+1; + } + }else if( c=='{' ){ /* A block of C code */ + int level; + cp++; + for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){ + if( c=='\n' ) lineno++; + else if( c=='{' ) level++; + else if( c=='}' ) level--; + else if( c=='/' && cp[1]=='*' ){ /* Skip comments */ + int prevc; + cp = &cp[2]; + prevc = 0; + while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){ + if( c=='\n' ) lineno++; + prevc = c; + cp++; + } + }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */ + cp = &cp[2]; + while( (c= *cp)!=0 && c!='\n' ) cp++; + if( c ) lineno++; + }else if( c=='\'' || c=='\"' ){ /* String a character literals */ + int startchar, prevc; + startchar = c; + prevc = 0; + for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){ + if( c=='\n' ) lineno++; + if( prevc=='\\' ) prevc = 0; + else prevc = c; + } + } + } + if( c==0 ){ + ErrorMsg(ps.filename,ps.tokenlineno, +"C code starting on this line is not terminated before the end of the file."); + ps.errorcnt++; + nextcp = cp; + }else{ + nextcp = cp+1; + } + }else if( isalnum(c) ){ /* Identifiers */ + while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++; + nextcp = cp; + }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */ + cp += 3; + nextcp = cp; + }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){ + cp += 2; + while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++; + nextcp = cp; + }else{ /* All other (one character) operators */ + cp++; + nextcp = cp; + } + c = *cp; + *cp = 0; /* Null terminate the token */ + parseonetoken(&ps); /* Parse the token */ + *cp = c; /* Restore the buffer */ + cp = nextcp; + } + free(filebuf); /* Release the buffer after parsing */ + gp->rule = ps.firstrule; + gp->errorcnt = ps.errorcnt; +} +/*************************** From the file "plink.c" *********************/ +/* +** Routines processing configuration follow-set propagation links +** in the LEMON parser generator. +*/ +static struct plink *plink_freelist = 0; + +/* Allocate a new plink */ +struct plink *Plink_new(){ + struct plink *newlink; + + if( plink_freelist==0 ){ + int i; + int amt = 100; + plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) ); + if( plink_freelist==0 ){ + fprintf(stderr, + "Unable to allocate memory for a new follow-set propagation link.\n"); + exit(1); + } + for(i=0; inext; + return newlink; +} + +/* Add a plink to a plink list */ +void Plink_add(struct plink **plpp, struct config *cfp) +{ + struct plink *newlink; + newlink = Plink_new(); + newlink->next = *plpp; + *plpp = newlink; + newlink->cfp = cfp; +} + +/* Transfer every plink on the list "from" to the list "to" */ +void Plink_copy(struct plink **to, struct plink *from) +{ + struct plink *nextpl; + while( from ){ + nextpl = from->next; + from->next = *to; + *to = from; + from = nextpl; + } +} + +/* Delete every plink on the list */ +void Plink_delete(struct plink *plp) +{ + struct plink *nextpl; + + while( plp ){ + nextpl = plp->next; + plp->next = plink_freelist; + plink_freelist = plp; + plp = nextpl; + } +} +/*********************** From the file "report.c" **************************/ +/* +** Procedures for generating reports and tables in the LEMON parser generator. +*/ + +/* Generate a filename with the given suffix. Space to hold the +** name comes from malloc() and must be freed by the calling +** function. +*/ +PRIVATE char *file_makename(struct lemon *lemp, const char *suffix) +{ + char *name; + char *cp; + + name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 ); + if( name==0 ){ + fprintf(stderr,"Can't allocate space for a filename.\n"); + exit(1); + } + strcpy(name,lemp->filename); + cp = strrchr(name,'.'); + if( cp ) *cp = 0; + strcat(name,suffix); + return name; +} + +/* Open a file with a name based on the name of the input file, +** but with a different (specified) suffix, and return a pointer +** to the stream */ +PRIVATE FILE *file_open( + struct lemon *lemp, + const char *suffix, + const char *mode +){ + FILE *fp; + + if( lemp->outname ) free(lemp->outname); + lemp->outname = file_makename(lemp, suffix); + fp = fopen(lemp->outname,mode); + if( fp==0 && *mode=='w' ){ + fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname); + lemp->errorcnt++; + return 0; + } + return fp; +} + +/* Duplicate the input file without comments and without actions +** on rules */ +void Reprint(struct lemon *lemp) +{ + struct rule *rp; + struct symbol *sp; + int i, j, maxlen, len, ncolumns, skip; + printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename); + maxlen = 10; + for(i=0; insymbol; i++){ + sp = lemp->symbols[i]; + len = lemonStrlen(sp->name); + if( len>maxlen ) maxlen = len; + } + ncolumns = 76/(maxlen+5); + if( ncolumns<1 ) ncolumns = 1; + skip = (lemp->nsymbol + ncolumns - 1)/ncolumns; + for(i=0; insymbol; j+=skip){ + sp = lemp->symbols[j]; + assert( sp->index==j ); + printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name); + } + printf("\n"); + } + for(rp=lemp->rule; rp; rp=rp->next){ + printf("%s",rp->lhs->name); + /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */ + printf(" ::="); + for(i=0; inrhs; i++){ + sp = rp->rhs[i]; + printf(" %s", sp->name); + if( sp->type==MULTITERMINAL ){ + for(j=1; jnsubsym; j++){ + printf("|%s", sp->subsym[j]->name); + } + } + /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */ + } + printf("."); + if( rp->precsym ) printf(" [%s]",rp->precsym->name); + /* if( rp->code ) printf("\n %s",rp->code); */ + printf("\n"); + } +} + +void ConfigPrint(FILE *fp, struct config *cfp) +{ + struct rule *rp; + struct symbol *sp; + int i, j; + rp = cfp->rp; + fprintf(fp,"%s ::=",rp->lhs->name); + for(i=0; i<=rp->nrhs; i++){ + if( i==cfp->dot ) fprintf(fp," *"); + if( i==rp->nrhs ) break; + sp = rp->rhs[i]; + fprintf(fp," %s", sp->name); + if( sp->type==MULTITERMINAL ){ + for(j=1; jnsubsym; j++){ + fprintf(fp,"|%s",sp->subsym[j]->name); + } + } + } +} + +/* #define TEST */ +#if 0 +/* Print a set */ +PRIVATE void SetPrint(out,set,lemp) +FILE *out; +char *set; +struct lemon *lemp; +{ + int i; + char *spacer; + spacer = ""; + fprintf(out,"%12s[",""); + for(i=0; interminal; i++){ + if( SetFind(set,i) ){ + fprintf(out,"%s%s",spacer,lemp->symbols[i]->name); + spacer = " "; + } + } + fprintf(out,"]\n"); +} + +/* Print a plink chain */ +PRIVATE void PlinkPrint(out,plp,tag) +FILE *out; +struct plink *plp; +char *tag; +{ + while( plp ){ + fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum); + ConfigPrint(out,plp->cfp); + fprintf(out,"\n"); + plp = plp->next; + } +} +#endif + +/* Print an action to the given file descriptor. Return FALSE if +** nothing was actually printed. +*/ +int PrintAction(struct action *ap, FILE *fp, int indent){ + int result = 1; + switch( ap->type ){ + case SHIFT: + fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum); + break; + case REDUCE: + fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index); + break; + case ACCEPT: + fprintf(fp,"%*s accept",indent,ap->sp->name); + break; + case ERROR: + fprintf(fp,"%*s error",indent,ap->sp->name); + break; + case SRCONFLICT: + case RRCONFLICT: + fprintf(fp,"%*s reduce %-3d ** Parsing conflict **", + indent,ap->sp->name,ap->x.rp->index); + break; + case SSCONFLICT: + fprintf(fp,"%*s shift %-3d ** Parsing conflict **", + indent,ap->sp->name,ap->x.stp->statenum); + break; + case SH_RESOLVED: + if( showPrecedenceConflict ){ + fprintf(fp,"%*s shift %-3d -- dropped by precedence", + indent,ap->sp->name,ap->x.stp->statenum); + }else{ + result = 0; + } + break; + case RD_RESOLVED: + if( showPrecedenceConflict ){ + fprintf(fp,"%*s reduce %-3d -- dropped by precedence", + indent,ap->sp->name,ap->x.rp->index); + }else{ + result = 0; + } + break; + case NOT_USED: + result = 0; + break; + } + return result; +} + +/* Generate the "y.output" log file */ +void ReportOutput(struct lemon *lemp) +{ + int i; + struct state *stp; + struct config *cfp; + struct action *ap; + FILE *fp; + + fp = file_open(lemp,".out","wb"); + if( fp==0 ) return; + for(i=0; instate; i++){ + stp = lemp->sorted[i]; + fprintf(fp,"State %d:\n",stp->statenum); + if( lemp->basisflag ) cfp=stp->bp; + else cfp=stp->cfp; + while( cfp ){ + char buf[20]; + if( cfp->dot==cfp->rp->nrhs ){ + sprintf(buf,"(%d)",cfp->rp->index); + fprintf(fp," %5s ",buf); + }else{ + fprintf(fp," "); + } + ConfigPrint(fp,cfp); + fprintf(fp,"\n"); +#if 0 + SetPrint(fp,cfp->fws,lemp); + PlinkPrint(fp,cfp->fplp,"To "); + PlinkPrint(fp,cfp->bplp,"From"); +#endif + if( lemp->basisflag ) cfp=cfp->bp; + else cfp=cfp->next; + } + fprintf(fp,"\n"); + for(ap=stp->ap; ap; ap=ap->next){ + if( PrintAction(ap,fp,30) ) fprintf(fp,"\n"); + } + fprintf(fp,"\n"); + } + fprintf(fp, "----------------------------------------------------\n"); + fprintf(fp, "Symbols:\n"); + for(i=0; insymbol; i++){ + int j; + struct symbol *sp; + + sp = lemp->symbols[i]; + fprintf(fp, " %3d: %s", i, sp->name); + if( sp->type==NONTERMINAL ){ + fprintf(fp, ":"); + if( sp->lambda ){ + fprintf(fp, " "); + } + for(j=0; jnterminal; j++){ + if( sp->firstset && SetFind(sp->firstset, j) ){ + fprintf(fp, " %s", lemp->symbols[j]->name); + } + } + } + fprintf(fp, "\n"); + } + fclose(fp); + return; +} + +/* Search for the file "name" which is in the same directory as +** the exacutable */ +PRIVATE char *pathsearch(char *argv0, char *name, int modemask) +{ + const char *pathlist; + char *pathbufptr; + char *pathbuf; + char *path,*cp; + char c; + +#ifdef __WIN32__ + cp = strrchr(argv0,'\\'); +#else + cp = strrchr(argv0,'/'); +#endif + if( cp ){ + c = *cp; + *cp = 0; + path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 ); + if( path ) sprintf(path,"%s/%s",argv0,name); + *cp = c; + }else{ + pathlist = getenv("PATH"); + if( pathlist==0 ) pathlist = ".:/bin:/usr/bin"; + pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 ); + path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 ); + if( (pathbuf != 0) && (path!=0) ){ + pathbufptr = pathbuf; + strcpy(pathbuf, pathlist); + while( *pathbuf ){ + cp = strchr(pathbuf,':'); + if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)]; + c = *cp; + *cp = 0; + sprintf(path,"%s/%s",pathbuf,name); + *cp = c; + if( c==0 ) pathbuf[0] = 0; + else pathbuf = &cp[1]; + if( access(path,modemask)==0 ) break; + } + free(pathbufptr); + } + } + return path; +} + +/* Given an action, compute the integer value for that action +** which is to be put in the action table of the generated machine. +** Return negative if no action should be generated. +*/ +PRIVATE int compute_action(struct lemon *lemp, struct action *ap) +{ + int act; + switch( ap->type ){ + case SHIFT: act = ap->x.stp->statenum; break; + case REDUCE: act = ap->x.rp->index + lemp->nstate; break; + case ERROR: act = lemp->nstate + lemp->nrule; break; + case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break; + default: act = -1; break; + } + return act; +} + +#define LINESIZE 1000 +/* The next cluster of routines are for reading the template file +** and writing the results to the generated parser */ +/* The first function transfers data from "in" to "out" until +** a line is seen which begins with "%%". The line number is +** tracked. +** +** if name!=0, then any word that begin with "Parse" is changed to +** begin with *name instead. +*/ +PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno) +{ + int i, iStart; + char line[LINESIZE]; + while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){ + (*lineno)++; + iStart = 0; + if( name ){ + for(i=0; line[i]; i++){ + if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0 + && (i==0 || !isalpha(line[i-1])) + ){ + if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]); + fprintf(out,"%s",name); + i += 4; + iStart = i+1; + } + } + } + fprintf(out,"%s",&line[iStart]); + } +} + +/* The next function finds the template file and opens it, returning +** a pointer to the opened file. */ +PRIVATE FILE *tplt_open(struct lemon *lemp) +{ + static char templatename[] = "lempar.c"; + char buf[1000]; + FILE *in; + char *tpltname; + char *cp; + + /* first, see if user specified a template filename on the command line. */ + if (user_templatename != 0) { + if( access(user_templatename,004)==-1 ){ + fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", + user_templatename); + lemp->errorcnt++; + return 0; + } + in = fopen(user_templatename,"rb"); + if( in==0 ){ + fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename); + lemp->errorcnt++; + return 0; + } + return in; + } + + cp = strrchr(lemp->filename,'.'); + if( cp ){ + sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename); + }else{ + sprintf(buf,"%s.lt",lemp->filename); + } + if( access(buf,004)==0 ){ + tpltname = buf; + }else if( access(templatename,004)==0 ){ + tpltname = templatename; + }else{ + tpltname = pathsearch(lemp->argv0,templatename,0); + } + if( tpltname==0 ){ + fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", + templatename); + lemp->errorcnt++; + return 0; + } + in = fopen(tpltname,"rb"); + if( in==0 ){ + fprintf(stderr,"Can't open the template file \"%s\".\n",templatename); + lemp->errorcnt++; + return 0; + } + return in; +} + +/* Print a #line directive line to the output file. */ +PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename) +{ + fprintf(out,"#line %d \"",lineno); + while( *filename ){ + if( *filename == '\\' ) putc('\\',out); + putc(*filename,out); + filename++; + } + fprintf(out,"\"\n"); +} + +/* Print a string to the file and keep the linenumber up to date */ +PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno) +{ + if( str==0 ) return; + while( *str ){ + putc(*str,out); + if( *str=='\n' ) (*lineno)++; + str++; + } + if( str[-1]!='\n' ){ + putc('\n',out); + (*lineno)++; + } + if (!lemp->nolinenosflag) { + (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); + } + return; +} + +/* +** The following routine emits code for the destructor for the +** symbol sp +*/ +void emit_destructor_code( + FILE *out, + struct symbol *sp, + struct lemon *lemp, + int *lineno +){ + char *cp = 0; + + if( sp->type==TERMINAL ){ + cp = lemp->tokendest; + if( cp==0 ) return; + fprintf(out,"{\n"); (*lineno)++; + }else if( sp->destructor ){ + cp = sp->destructor; + fprintf(out,"{\n"); (*lineno)++; + if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); } + }else if( lemp->vardest ){ + cp = lemp->vardest; + if( cp==0 ) return; + fprintf(out,"{\n"); (*lineno)++; + }else{ + assert( 0 ); /* Cannot happen */ + } + for(; *cp; cp++){ + if( *cp=='$' && cp[1]=='$' ){ + fprintf(out,"(yypminor->yy%d)",sp->dtnum); + cp++; + continue; + } + if( *cp=='\n' ) (*lineno)++; + fputc(*cp,out); + } + fprintf(out,"\n"); (*lineno)++; + if (!lemp->nolinenosflag) { + (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); + } + fprintf(out,"}\n"); (*lineno)++; + return; +} + +/* +** Return TRUE (non-zero) if the given symbol has a destructor. +*/ +int has_destructor(struct symbol *sp, struct lemon *lemp) +{ + int ret; + if( sp->type==TERMINAL ){ + ret = lemp->tokendest!=0; + }else{ + ret = lemp->vardest!=0 || sp->destructor!=0; + } + return ret; +} + +/* +** Append text to a dynamically allocated string. If zText is 0 then +** reset the string to be empty again. Always return the complete text +** of the string (which is overwritten with each call). +** +** n bytes of zText are stored. If n==0 then all of zText up to the first +** \000 terminator is stored. zText can contain up to two instances of +** %d. The values of p1 and p2 are written into the first and second +** %d. +** +** If n==-1, then the previous character is overwritten. +*/ +PRIVATE char *append_str(const char *zText, int n, int p1, int p2){ + static char empty[1] = { 0 }; + static char *z = 0; + static int alloced = 0; + static int used = 0; + int c; + char zInt[40]; + if( zText==0 ){ + used = 0; + return z; + } + if( n<=0 ){ + if( n<0 ){ + used += n; + assert( used>=0 ); + } + n = lemonStrlen(zText); + } + if( (int) (n+sizeof(zInt)*2+used) >= alloced ){ + alloced = n + sizeof(zInt)*2 + used + 200; + z = (char *) realloc(z, alloced); + } + if( z==0 ) return empty; + while( n-- > 0 ){ + c = *(zText++); + if( c=='%' && n>0 && zText[0]=='d' ){ + sprintf(zInt, "%d", p1); + p1 = p2; + strcpy(&z[used], zInt); + used += lemonStrlen(&z[used]); + zText++; + n--; + }else{ + z[used++] = c; + } + } + z[used] = 0; + return z; +} + +/* +** zCode is a string that is the action associated with a rule. Expand +** the symbols in this string so that the refer to elements of the parser +** stack. +*/ +PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){ + char *cp, *xp; + int i; + char lhsused = 0; /* True if the LHS element has been used */ + char used[MAXRHS]; /* True for each RHS element which is used */ + + for(i=0; inrhs; i++) used[i] = 0; + lhsused = 0; + + if( rp->code==0 ){ + static char newlinestr[2] = { '\n', '\0' }; + rp->code = newlinestr; + rp->line = rp->ruleline; + } + + append_str(0,0,0,0); + + /* This const cast is wrong but harmless, if we're careful. */ + for(cp=(char *)rp->code; *cp; cp++){ + if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){ + char saved; + for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++); + saved = *xp; + *xp = 0; + if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){ + append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0); + cp = xp; + lhsused = 1; + }else{ + for(i=0; inrhs; i++){ + if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){ + if( cp!=rp->code && cp[-1]=='@' ){ + /* If the argument is of the form @X then substituted + ** the token number of X, not the value of X */ + append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0); + }else{ + struct symbol *sp = rp->rhs[i]; + int dtnum; + if( sp->type==MULTITERMINAL ){ + dtnum = sp->subsym[0]->dtnum; + }else{ + dtnum = sp->dtnum; + } + append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum); + } + cp = xp; + used[i] = 1; + break; + } + } + } + *xp = saved; + } + append_str(cp, 1, 0, 0); + } /* End loop */ + + /* Check to make sure the LHS has been used */ + if( rp->lhsalias && !lhsused ){ + ErrorMsg(lemp->filename,rp->ruleline, + "Label \"%s\" for \"%s(%s)\" is never used.", + rp->lhsalias,rp->lhs->name,rp->lhsalias); + lemp->errorcnt++; + } + + /* Generate destructor code for RHS symbols which are not used in the + ** reduce code */ + for(i=0; inrhs; i++){ + if( rp->rhsalias[i] && !used[i] ){ + ErrorMsg(lemp->filename,rp->ruleline, + "Label %s for \"%s(%s)\" is never used.", + rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]); + lemp->errorcnt++; + }else if( rp->rhsalias[i]==0 ){ + if( has_destructor(rp->rhs[i],lemp) ){ + append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0, + rp->rhs[i]->index,i-rp->nrhs+1); + }else{ + /* No destructor defined for this term */ + } + } + } + if( rp->code ){ + cp = append_str(0,0,0,0); + rp->code = Strsafe(cp?cp:""); + } +} + +/* +** Generate code which executes when the rule "rp" is reduced. Write +** the code to "out". Make sure lineno stays up-to-date. +*/ +PRIVATE void emit_code( + FILE *out, + struct rule *rp, + struct lemon *lemp, + int *lineno +){ + const char *cp; + + /* Generate code to do the reduce action */ + if( rp->code ){ + if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); } + fprintf(out,"{%s",rp->code); + for(cp=rp->code; *cp; cp++){ + if( *cp=='\n' ) (*lineno)++; + } /* End loop */ + fprintf(out,"}\n"); (*lineno)++; + if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); } + } /* End if( rp->code ) */ + + return; +} + +/* +** Print the definition of the union used for the parser's data stack. +** This union contains fields for every possible data type for tokens +** and nonterminals. In the process of computing and printing this +** union, also set the ".dtnum" field of every terminal and nonterminal +** symbol. +*/ +void print_stack_union( + FILE *out, /* The output stream */ + struct lemon *lemp, /* The main info structure for this parser */ + int *plineno, /* Pointer to the line number */ + int mhflag /* True if generating makeheaders output */ +){ + int lineno = *plineno; /* The line number of the output */ + char **types; /* A hash table of datatypes */ + int arraysize; /* Size of the "types" array */ + int maxdtlength; /* Maximum length of any ".datatype" field. */ + char *stddt; /* Standardized name for a datatype */ + int i,j; /* Loop counters */ + unsigned hash; /* For hashing the name of a type */ + const char *name; /* Name of the parser */ + + /* Allocate and initialize types[] and allocate stddt[] */ + arraysize = lemp->nsymbol * 2; + types = (char**)calloc( arraysize, sizeof(char*) ); + if( types==0 ){ + fprintf(stderr,"Out of memory.\n"); + exit(1); + } + for(i=0; ivartype ){ + maxdtlength = lemonStrlen(lemp->vartype); + } + for(i=0; insymbol; i++){ + int len; + struct symbol *sp = lemp->symbols[i]; + if( sp->datatype==0 ) continue; + len = lemonStrlen(sp->datatype); + if( len>maxdtlength ) maxdtlength = len; + } + stddt = (char*)malloc( maxdtlength*2 + 1 ); + if( stddt==0 ){ + fprintf(stderr,"Out of memory.\n"); + exit(1); + } + + /* Build a hash table of datatypes. The ".dtnum" field of each symbol + ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is + ** used for terminal symbols. If there is no %default_type defined then + ** 0 is also used as the .dtnum value for nonterminals which do not specify + ** a datatype using the %type directive. + */ + for(i=0; insymbol; i++){ + struct symbol *sp = lemp->symbols[i]; + char *cp; + if( sp==lemp->errsym ){ + sp->dtnum = arraysize+1; + continue; + } + if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){ + sp->dtnum = 0; + continue; + } + cp = sp->datatype; + if( cp==0 ) cp = lemp->vartype; + j = 0; + while( isspace(*cp) ) cp++; + while( *cp ) stddt[j++] = *cp++; + while( j>0 && isspace(stddt[j-1]) ) j--; + stddt[j] = 0; + if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){ + sp->dtnum = 0; + continue; + } + hash = 0; + for(j=0; stddt[j]; j++){ + hash = hash*53 + stddt[j]; + } + hash = (hash & 0x7fffffff)%arraysize; + while( types[hash] ){ + if( strcmp(types[hash],stddt)==0 ){ + sp->dtnum = hash + 1; + break; + } + hash++; + if( hash>=(unsigned)arraysize ) hash = 0; + } + if( types[hash]==0 ){ + sp->dtnum = hash + 1; + types[hash] = (char*)malloc( lemonStrlen(stddt)+1 ); + if( types[hash]==0 ){ + fprintf(stderr,"Out of memory.\n"); + exit(1); + } + strcpy(types[hash],stddt); + } + } + + /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */ + name = lemp->name ? lemp->name : "Parse"; + lineno = *plineno; + if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; } + fprintf(out,"#define %sTOKENTYPE %s\n",name, + lemp->tokentype?lemp->tokentype:"void*"); lineno++; + if( mhflag ){ fprintf(out,"#endif\n"); lineno++; } + fprintf(out,"typedef union {\n"); lineno++; + fprintf(out," int yyinit;\n"); lineno++; + fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++; + for(i=0; ierrsym->useCnt ){ + fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++; + } + free(stddt); + free(types); + fprintf(out,"} YYMINORTYPE;\n"); lineno++; + *plineno = lineno; +} + +/* +** Return the name of a C datatype able to represent values between +** lwr and upr, inclusive. +*/ +static const char *minimum_size_type(int lwr, int upr){ + if( lwr>=0 ){ + if( upr<=255 ){ + return "unsigned char"; + }else if( upr<65535 ){ + return "unsigned short int"; + }else{ + return "unsigned int"; + } + }else if( lwr>=-127 && upr<=127 ){ + return "signed char"; + }else if( lwr>=-32767 && upr<32767 ){ + return "short"; + }else{ + return "int"; + } +} + +/* +** Each state contains a set of token transaction and a set of +** nonterminal transactions. Each of these sets makes an instance +** of the following structure. An array of these structures is used +** to order the creation of entries in the yy_action[] table. +*/ +struct axset { + struct state *stp; /* A pointer to a state */ + int isTkn; /* True to use tokens. False for non-terminals */ + int nAction; /* Number of actions */ + int iOrder; /* Original order of action sets */ +}; + +/* +** Compare to axset structures for sorting purposes +*/ +static int axset_compare(const void *a, const void *b){ + struct axset *p1 = (struct axset*)a; + struct axset *p2 = (struct axset*)b; + int c; + c = p2->nAction - p1->nAction; + if( c==0 ){ + c = p2->iOrder - p1->iOrder; + } + assert( c!=0 || p1==p2 ); + return c; +} + +/* +** Write text on "out" that describes the rule "rp". +*/ +static void writeRuleText(FILE *out, struct rule *rp){ + int j; + fprintf(out,"%s ::=", rp->lhs->name); + for(j=0; jnrhs; j++){ + struct symbol *sp = rp->rhs[j]; + fprintf(out," %s", sp->name); + if( sp->type==MULTITERMINAL ){ + int k; + for(k=1; knsubsym; k++){ + fprintf(out,"|%s",sp->subsym[k]->name); + } + } + } +} + + +/* Generate C source code for the parser */ +void ReportTable( + struct lemon *lemp, + int mhflag /* Output in makeheaders format if true */ +){ + FILE *out, *in; + char line[LINESIZE]; + int lineno; + struct state *stp; + struct action *ap; + struct rule *rp; + struct acttab *pActtab; + int i, j, n; + const char *name; + int mnTknOfst, mxTknOfst; + int mnNtOfst, mxNtOfst; + struct axset *ax; + + in = tplt_open(lemp); + if( in==0 ) return; + out = file_open(lemp,".c","wb"); + if( out==0 ){ + fclose(in); + return; + } + lineno = 1; + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate the include code, if any */ + tplt_print(out,lemp,lemp->include,&lineno); + if( mhflag ){ + char *name = file_makename(lemp, ".h"); + fprintf(out,"#include \"%s\"\n", name); lineno++; + free(name); + } + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate #defines for all tokens */ + if( mhflag ){ + const char *prefix; + fprintf(out,"#if INTERFACE\n"); lineno++; + if( lemp->tokenprefix ) prefix = lemp->tokenprefix; + else prefix = ""; + for(i=1; interminal; i++){ + fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); + lineno++; + } + fprintf(out,"#endif\n"); lineno++; + } + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate the defines */ + fprintf(out,"#define YYCODETYPE %s\n", + minimum_size_type(0, lemp->nsymbol+1)); lineno++; + fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++; + fprintf(out,"#define YYACTIONTYPE %s\n", + minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++; + if( lemp->wildcard ){ + fprintf(out,"#define YYWILDCARD %d\n", + lemp->wildcard->index); lineno++; + } + print_stack_union(out,lemp,&lineno,mhflag); + fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++; + if( lemp->stacksize ){ + fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++; + }else{ + fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++; + } + fprintf(out, "#endif\n"); lineno++; + if( mhflag ){ + fprintf(out,"#if INTERFACE\n"); lineno++; + } + name = lemp->name ? lemp->name : "Parse"; + if( lemp->arg && lemp->arg[0] ){ + int i; + i = lemonStrlen(lemp->arg); + while( i>=1 && isspace(lemp->arg[i-1]) ) i--; + while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--; + fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++; + fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++; + fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n", + name,lemp->arg,&lemp->arg[i]); lineno++; + fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n", + name,&lemp->arg[i],&lemp->arg[i]); lineno++; + }else{ + fprintf(out,"#define %sARG_SDECL\n",name); lineno++; + fprintf(out,"#define %sARG_PDECL\n",name); lineno++; + fprintf(out,"#define %sARG_FETCH\n",name); lineno++; + fprintf(out,"#define %sARG_STORE\n",name); lineno++; + } + if( mhflag ){ + fprintf(out,"#endif\n"); lineno++; + } + fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++; + fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++; + if( lemp->errsym->useCnt ){ + fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++; + fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++; + } + if( lemp->has_fallback ){ + fprintf(out,"#define YYFALLBACK 1\n"); lineno++; + } + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate the action table and its associates: + ** + ** yy_action[] A single table containing all actions. + ** yy_lookahead[] A table containing the lookahead for each entry in + ** yy_action. Used to detect hash collisions. + ** yy_shift_ofst[] For each state, the offset into yy_action for + ** shifting terminals. + ** yy_reduce_ofst[] For each state, the offset into yy_action for + ** shifting non-terminals after a reduce. + ** yy_default[] Default action for each state. + */ + + /* Compute the actions on all states and count them up */ + ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0])); + if( ax==0 ){ + fprintf(stderr,"malloc failed\n"); + exit(1); + } + for(i=0; instate; i++){ + stp = lemp->sorted[i]; + ax[i*2].stp = stp; + ax[i*2].isTkn = 1; + ax[i*2].nAction = stp->nTknAct; + ax[i*2+1].stp = stp; + ax[i*2+1].isTkn = 0; + ax[i*2+1].nAction = stp->nNtAct; + } + mxTknOfst = mnTknOfst = 0; + mxNtOfst = mnNtOfst = 0; + + /* Compute the action table. In order to try to keep the size of the + ** action table to a minimum, the heuristic of placing the largest action + ** sets first is used. + */ + for(i=0; instate*2; i++) ax[i].iOrder = i; + qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare); + pActtab = acttab_alloc(); + for(i=0; instate*2 && ax[i].nAction>0; i++){ + stp = ax[i].stp; + if( ax[i].isTkn ){ + for(ap=stp->ap; ap; ap=ap->next){ + int action; + if( ap->sp->index>=lemp->nterminal ) continue; + action = compute_action(lemp, ap); + if( action<0 ) continue; + acttab_action(pActtab, ap->sp->index, action); + } + stp->iTknOfst = acttab_insert(pActtab); + if( stp->iTknOfstiTknOfst; + if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst; + }else{ + for(ap=stp->ap; ap; ap=ap->next){ + int action; + if( ap->sp->indexnterminal ) continue; + if( ap->sp->index==lemp->nsymbol ) continue; + action = compute_action(lemp, ap); + if( action<0 ) continue; + acttab_action(pActtab, ap->sp->index, action); + } + stp->iNtOfst = acttab_insert(pActtab); + if( stp->iNtOfstiNtOfst; + if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst; + } + } + free(ax); + + /* Output the yy_action table */ + n = acttab_size(pActtab); + fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++; + fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++; + for(i=j=0; instate + lemp->nrule + 2; + if( j==0 ) fprintf(out," /* %5d */ ", i); + fprintf(out, " %4d,", action); + if( j==9 || i==n-1 ){ + fprintf(out, "\n"); lineno++; + j = 0; + }else{ + j++; + } + } + fprintf(out, "};\n"); lineno++; + + /* Output the yy_lookahead table */ + fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++; + for(i=j=0; insymbol; + if( j==0 ) fprintf(out," /* %5d */ ", i); + fprintf(out, " %4d,", la); + if( j==9 || i==n-1 ){ + fprintf(out, "\n"); lineno++; + j = 0; + }else{ + j++; + } + } + fprintf(out, "};\n"); lineno++; + + /* Output the yy_shift_ofst[] table */ + fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++; + n = lemp->nstate; + while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--; + fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++; + fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++; + fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++; + fprintf(out, "static const %s yy_shift_ofst[] = {\n", + minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++; + for(i=j=0; isorted[i]; + ofst = stp->iTknOfst; + if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1; + if( j==0 ) fprintf(out," /* %5d */ ", i); + fprintf(out, " %4d,", ofst); + if( j==9 || i==n-1 ){ + fprintf(out, "\n"); lineno++; + j = 0; + }else{ + j++; + } + } + fprintf(out, "};\n"); lineno++; + + /* Output the yy_reduce_ofst[] table */ + fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++; + n = lemp->nstate; + while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--; + fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++; + fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++; + fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++; + fprintf(out, "static const %s yy_reduce_ofst[] = {\n", + minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++; + for(i=j=0; isorted[i]; + ofst = stp->iNtOfst; + if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1; + if( j==0 ) fprintf(out," /* %5d */ ", i); + fprintf(out, " %4d,", ofst); + if( j==9 || i==n-1 ){ + fprintf(out, "\n"); lineno++; + j = 0; + }else{ + j++; + } + } + fprintf(out, "};\n"); lineno++; + + /* Output the default action table */ + fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++; + n = lemp->nstate; + for(i=j=0; isorted[i]; + if( j==0 ) fprintf(out," /* %5d */ ", i); + fprintf(out, " %4d,", stp->iDflt); + if( j==9 || i==n-1 ){ + fprintf(out, "\n"); lineno++; + j = 0; + }else{ + j++; + } + } + fprintf(out, "};\n"); lineno++; + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate the table of fallback tokens. + */ + if( lemp->has_fallback ){ + int mx = lemp->nterminal - 1; + while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } + for(i=0; i<=mx; i++){ + struct symbol *p = lemp->symbols[i]; + if( p->fallback==0 ){ + fprintf(out, " 0, /* %10s => nothing */\n", p->name); + }else{ + fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index, + p->name, p->fallback->name); + } + lineno++; + } + } + tplt_xfer(lemp->name, in, out, &lineno); + + /* Generate a table containing the symbolic name of every symbol + */ + for(i=0; insymbol; i++){ + sprintf(line,"\"%s\",",lemp->symbols[i]->name); + fprintf(out," %-15s",line); + if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; } + } + if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; } + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate a table containing a text string that describes every + ** rule in the rule set of the grammar. This information is used + ** when tracing REDUCE actions. + */ + for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){ + assert( rp->index==i ); + fprintf(out," /* %3d */ \"", i); + writeRuleText(out, rp); + fprintf(out,"\",\n"); lineno++; + } + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate code which executes every time a symbol is popped from + ** the stack while processing errors or while destroying the parser. + ** (In other words, generate the %destructor actions) + */ + if( lemp->tokendest ){ + int once = 1; + for(i=0; insymbol; i++){ + struct symbol *sp = lemp->symbols[i]; + if( sp==0 || sp->type!=TERMINAL ) continue; + if( once ){ + fprintf(out, " /* TERMINAL Destructor */\n"); lineno++; + once = 0; + } + fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; + } + for(i=0; insymbol && lemp->symbols[i]->type!=TERMINAL; i++); + if( insymbol ){ + emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); + fprintf(out," break;\n"); lineno++; + } + } + if( lemp->vardest ){ + struct symbol *dflt_sp = 0; + int once = 1; + for(i=0; insymbol; i++){ + struct symbol *sp = lemp->symbols[i]; + if( sp==0 || sp->type==TERMINAL || + sp->index<=0 || sp->destructor!=0 ) continue; + if( once ){ + fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++; + once = 0; + } + fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; + dflt_sp = sp; + } + if( dflt_sp!=0 ){ + emit_destructor_code(out,dflt_sp,lemp,&lineno); + } + fprintf(out," break;\n"); lineno++; + } + for(i=0; insymbol; i++){ + struct symbol *sp = lemp->symbols[i]; + if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue; + fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; + + /* Combine duplicate destructors into a single case */ + for(j=i+1; jnsymbol; j++){ + struct symbol *sp2 = lemp->symbols[j]; + if( sp2 && sp2->type!=TERMINAL && sp2->destructor + && sp2->dtnum==sp->dtnum + && strcmp(sp->destructor,sp2->destructor)==0 ){ + fprintf(out," case %d: /* %s */\n", + sp2->index, sp2->name); lineno++; + sp2->destructor = 0; + } + } + + emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); + fprintf(out," break;\n"); lineno++; + } + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate code which executes whenever the parser stack overflows */ + tplt_print(out,lemp,lemp->overflow,&lineno); + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate the table of rule information + ** + ** Note: This code depends on the fact that rules are number + ** sequentually beginning with 0. + */ + for(rp=lemp->rule; rp; rp=rp->next){ + fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++; + } + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate code which execution during each REDUCE action */ + for(rp=lemp->rule; rp; rp=rp->next){ + translate_code(lemp, rp); + } + /* First output rules other than the default: rule */ + for(rp=lemp->rule; rp; rp=rp->next){ + struct rule *rp2; /* Other rules with the same action */ + if( rp->code==0 ) continue; + if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */ + fprintf(out," case %d: /* ", rp->index); + writeRuleText(out, rp); + fprintf(out, " */\n"); lineno++; + for(rp2=rp->next; rp2; rp2=rp2->next){ + if( rp2->code==rp->code ){ + fprintf(out," case %d: /* ", rp2->index); + writeRuleText(out, rp2); + fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++; + rp2->code = 0; + } + } + emit_code(out,rp,lemp,&lineno); + fprintf(out," break;\n"); lineno++; + rp->code = 0; + } + /* Finally, output the default: rule. We choose as the default: all + ** empty actions. */ + fprintf(out," default:\n"); lineno++; + for(rp=lemp->rule; rp; rp=rp->next){ + if( rp->code==0 ) continue; + assert( rp->code[0]=='\n' && rp->code[1]==0 ); + fprintf(out," /* (%d) ", rp->index); + writeRuleText(out, rp); + fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++; + } + fprintf(out," break;\n"); lineno++; + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate code which executes if a parse fails */ + tplt_print(out,lemp,lemp->failure,&lineno); + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate code which executes when a syntax error occurs */ + tplt_print(out,lemp,lemp->error,&lineno); + tplt_xfer(lemp->name,in,out,&lineno); + + /* Generate code which executes when the parser accepts its input */ + tplt_print(out,lemp,lemp->accept,&lineno); + tplt_xfer(lemp->name,in,out,&lineno); + + /* Append any addition code the user desires */ + tplt_print(out,lemp,lemp->extracode,&lineno); + + fclose(in); + fclose(out); + return; +} + +/* Generate a header file for the parser */ +void ReportHeader(struct lemon *lemp) +{ + FILE *out, *in; + const char *prefix; + char line[LINESIZE]; + char pattern[LINESIZE]; + int i; + + if( lemp->tokenprefix ) prefix = lemp->tokenprefix; + else prefix = ""; + in = file_open(lemp,".h","rb"); + if( in ){ + int nextChar; + for(i=1; interminal && fgets(line,LINESIZE,in); i++){ + sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); + if( strcmp(line,pattern) ) break; + } + nextChar = fgetc(in); + fclose(in); + if( i==lemp->nterminal && nextChar==EOF ){ + /* No change in the file. Don't rewrite it. */ + return; + } + } + out = file_open(lemp,".h","wb"); + if( out ){ + for(i=1; interminal; i++){ + fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); + } + fclose(out); + } + return; +} + +/* Reduce the size of the action tables, if possible, by making use +** of defaults. +** +** In this version, we take the most frequent REDUCE action and make +** it the default. Except, there is no default if the wildcard token +** is a possible look-ahead. +*/ +void CompressTables(struct lemon *lemp) +{ + struct state *stp; + struct action *ap, *ap2; + struct rule *rp, *rp2, *rbest; + int nbest, n; + int i; + int usesWildcard; + + for(i=0; instate; i++){ + stp = lemp->sorted[i]; + nbest = 0; + rbest = 0; + usesWildcard = 0; + + for(ap=stp->ap; ap; ap=ap->next){ + if( ap->type==SHIFT && ap->sp==lemp->wildcard ){ + usesWildcard = 1; + } + if( ap->type!=REDUCE ) continue; + rp = ap->x.rp; + if( rp->lhsStart ) continue; + if( rp==rbest ) continue; + n = 1; + for(ap2=ap->next; ap2; ap2=ap2->next){ + if( ap2->type!=REDUCE ) continue; + rp2 = ap2->x.rp; + if( rp2==rbest ) continue; + if( rp2==rp ) n++; + } + if( n>nbest ){ + nbest = n; + rbest = rp; + } + } + + /* Do not make a default if the number of rules to default + ** is not at least 1 or if the wildcard token is a possible + ** lookahead. + */ + if( nbest<1 || usesWildcard ) continue; + + + /* Combine matching REDUCE actions into a single default */ + for(ap=stp->ap; ap; ap=ap->next){ + if( ap->type==REDUCE && ap->x.rp==rbest ) break; + } + assert( ap ); + ap->sp = Symbol_new("{default}"); + for(ap=ap->next; ap; ap=ap->next){ + if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED; + } + stp->ap = Action_sort(stp->ap); + } +} + + +/* +** Compare two states for sorting purposes. The smaller state is the +** one with the most non-terminal actions. If they have the same number +** of non-terminal actions, then the smaller is the one with the most +** token actions. +*/ +static int stateResortCompare(const void *a, const void *b){ + const struct state *pA = *(const struct state**)a; + const struct state *pB = *(const struct state**)b; + int n; + + n = pB->nNtAct - pA->nNtAct; + if( n==0 ){ + n = pB->nTknAct - pA->nTknAct; + if( n==0 ){ + n = pB->statenum - pA->statenum; + } + } + assert( n!=0 ); + return n; +} + + +/* +** Renumber and resort states so that states with fewer choices +** occur at the end. Except, keep state 0 as the first state. +*/ +void ResortStates(struct lemon *lemp) +{ + int i; + struct state *stp; + struct action *ap; + + for(i=0; instate; i++){ + stp = lemp->sorted[i]; + stp->nTknAct = stp->nNtAct = 0; + stp->iDflt = lemp->nstate + lemp->nrule; + stp->iTknOfst = NO_OFFSET; + stp->iNtOfst = NO_OFFSET; + for(ap=stp->ap; ap; ap=ap->next){ + if( compute_action(lemp,ap)>=0 ){ + if( ap->sp->indexnterminal ){ + stp->nTknAct++; + }else if( ap->sp->indexnsymbol ){ + stp->nNtAct++; + }else{ + stp->iDflt = compute_action(lemp, ap); + } + } + } + } + qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]), + stateResortCompare); + for(i=0; instate; i++){ + lemp->sorted[i]->statenum = i; + } +} + + +/***************** From the file "set.c" ************************************/ +/* +** Set manipulation routines for the LEMON parser generator. +*/ + +static int size = 0; + +/* Set the set size */ +void SetSize(int n) +{ + size = n+1; +} + +/* Allocate a new set */ +char *SetNew(){ + char *s; + s = (char*)calloc( size, 1); + if( s==0 ){ + extern void memory_error(); + memory_error(); + } + return s; +} + +/* Deallocate a set */ +void SetFree(char *s) +{ + free(s); +} + +/* Add a new element to the set. Return TRUE if the element was added +** and FALSE if it was already there. */ +int SetAdd(char *s, int e) +{ + int rv; + assert( e>=0 && esize = 1024; + x1a->count = 0; + x1a->tbl = (x1node*)malloc( + (sizeof(x1node) + sizeof(x1node*))*1024 ); + if( x1a->tbl==0 ){ + free(x1a); + x1a = 0; + }else{ + int i; + x1a->ht = (x1node**)&(x1a->tbl[1024]); + for(i=0; i<1024; i++) x1a->ht[i] = 0; + } + } +} +/* Insert a new record into the array. Return TRUE if successful. +** Prior data with the same key is NOT overwritten */ +int Strsafe_insert(const char *data) +{ + x1node *np; + unsigned h; + unsigned ph; + + if( x1a==0 ) return 0; + ph = strhash(data); + h = ph & (x1a->size-1); + np = x1a->ht[h]; + while( np ){ + if( strcmp(np->data,data)==0 ){ + /* An existing entry with the same key is found. */ + /* Fail because overwrite is not allows. */ + return 0; + } + np = np->next; + } + if( x1a->count>=x1a->size ){ + /* Need to make the hash table bigger */ + int i,size; + struct s_x1 array; + array.size = size = x1a->size*2; + array.count = x1a->count; + array.tbl = (x1node*)malloc( + (sizeof(x1node) + sizeof(x1node*))*size ); + if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ + array.ht = (x1node**)&(array.tbl[size]); + for(i=0; icount; i++){ + x1node *oldnp, *newnp; + oldnp = &(x1a->tbl[i]); + h = strhash(oldnp->data) & (size-1); + newnp = &(array.tbl[i]); + if( array.ht[h] ) array.ht[h]->from = &(newnp->next); + newnp->next = array.ht[h]; + newnp->data = oldnp->data; + newnp->from = &(array.ht[h]); + array.ht[h] = newnp; + } + free(x1a->tbl); + *x1a = array; + } + /* Insert the new data */ + h = ph & (x1a->size-1); + np = &(x1a->tbl[x1a->count++]); + np->data = data; + if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next); + np->next = x1a->ht[h]; + x1a->ht[h] = np; + np->from = &(x1a->ht[h]); + return 1; +} + +/* Return a pointer to data assigned to the given key. Return NULL +** if no such key. */ +const char *Strsafe_find(const char *key) +{ + unsigned h; + x1node *np; + + if( x1a==0 ) return 0; + h = strhash(key) & (x1a->size-1); + np = x1a->ht[h]; + while( np ){ + if( strcmp(np->data,key)==0 ) break; + np = np->next; + } + return np ? np->data : 0; +} + +/* Return a pointer to the (terminal or nonterminal) symbol "x". +** Create a new symbol if this is the first time "x" has been seen. +*/ +struct symbol *Symbol_new(const char *x) +{ + struct symbol *sp; + + sp = Symbol_find(x); + if( sp==0 ){ + sp = (struct symbol *)calloc(1, sizeof(struct symbol) ); + MemoryCheck(sp); + sp->name = Strsafe(x); + sp->type = isupper(*x) ? TERMINAL : NONTERMINAL; + sp->rule = 0; + sp->fallback = 0; + sp->prec = -1; + sp->assoc = UNK; + sp->firstset = 0; + sp->lambda = LEMON_FALSE; + sp->destructor = 0; + sp->destLineno = 0; + sp->datatype = 0; + sp->useCnt = 0; + Symbol_insert(sp,sp->name); + } + sp->useCnt++; + return sp; +} + +/* Compare two symbols for working purposes +** +** Symbols that begin with upper case letters (terminals or tokens) +** must sort before symbols that begin with lower case letters +** (non-terminals). Other than that, the order does not matter. +** +** We find experimentally that leaving the symbols in their original +** order (the order they appeared in the grammar file) gives the +** smallest parser tables in SQLite. +*/ +int Symbolcmpp(const void *_a, const void *_b) +{ + const struct symbol **a = (const struct symbol **) _a; + const struct symbol **b = (const struct symbol **) _b; + int i1 = (**a).index + 10000000*((**a).name[0]>'Z'); + int i2 = (**b).index + 10000000*((**b).name[0]>'Z'); + assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 ); + return i1-i2; +} + +/* There is one instance of the following structure for each +** associative array of type "x2". +*/ +struct s_x2 { + int size; /* The number of available slots. */ + /* Must be a power of 2 greater than or */ + /* equal to 1 */ + int count; /* Number of currently slots filled */ + struct s_x2node *tbl; /* The data stored here */ + struct s_x2node **ht; /* Hash table for lookups */ +}; + +/* There is one instance of this structure for every data element +** in an associative array of type "x2". +*/ +typedef struct s_x2node { + struct symbol *data; /* The data */ + const char *key; /* The key */ + struct s_x2node *next; /* Next entry with the same hash */ + struct s_x2node **from; /* Previous link */ +} x2node; + +/* There is only one instance of the array, which is the following */ +static struct s_x2 *x2a; + +/* Allocate a new associative array */ +void Symbol_init(){ + if( x2a ) return; + x2a = (struct s_x2*)malloc( sizeof(struct s_x2) ); + if( x2a ){ + x2a->size = 128; + x2a->count = 0; + x2a->tbl = (x2node*)malloc( + (sizeof(x2node) + sizeof(x2node*))*128 ); + if( x2a->tbl==0 ){ + free(x2a); + x2a = 0; + }else{ + int i; + x2a->ht = (x2node**)&(x2a->tbl[128]); + for(i=0; i<128; i++) x2a->ht[i] = 0; + } + } +} +/* Insert a new record into the array. Return TRUE if successful. +** Prior data with the same key is NOT overwritten */ +int Symbol_insert(struct symbol *data, const char *key) +{ + x2node *np; + unsigned h; + unsigned ph; + + if( x2a==0 ) return 0; + ph = strhash(key); + h = ph & (x2a->size-1); + np = x2a->ht[h]; + while( np ){ + if( strcmp(np->key,key)==0 ){ + /* An existing entry with the same key is found. */ + /* Fail because overwrite is not allows. */ + return 0; + } + np = np->next; + } + if( x2a->count>=x2a->size ){ + /* Need to make the hash table bigger */ + int i,size; + struct s_x2 array; + array.size = size = x2a->size*2; + array.count = x2a->count; + array.tbl = (x2node*)malloc( + (sizeof(x2node) + sizeof(x2node*))*size ); + if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ + array.ht = (x2node**)&(array.tbl[size]); + for(i=0; icount; i++){ + x2node *oldnp, *newnp; + oldnp = &(x2a->tbl[i]); + h = strhash(oldnp->key) & (size-1); + newnp = &(array.tbl[i]); + if( array.ht[h] ) array.ht[h]->from = &(newnp->next); + newnp->next = array.ht[h]; + newnp->key = oldnp->key; + newnp->data = oldnp->data; + newnp->from = &(array.ht[h]); + array.ht[h] = newnp; + } + free(x2a->tbl); + *x2a = array; + } + /* Insert the new data */ + h = ph & (x2a->size-1); + np = &(x2a->tbl[x2a->count++]); + np->key = key; + np->data = data; + if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next); + np->next = x2a->ht[h]; + x2a->ht[h] = np; + np->from = &(x2a->ht[h]); + return 1; +} + +/* Return a pointer to data assigned to the given key. Return NULL +** if no such key. */ +struct symbol *Symbol_find(const char *key) +{ + unsigned h; + x2node *np; + + if( x2a==0 ) return 0; + h = strhash(key) & (x2a->size-1); + np = x2a->ht[h]; + while( np ){ + if( strcmp(np->key,key)==0 ) break; + np = np->next; + } + return np ? np->data : 0; +} + +/* Return the n-th data. Return NULL if n is out of range. */ +struct symbol *Symbol_Nth(int n) +{ + struct symbol *data; + if( x2a && n>0 && n<=x2a->count ){ + data = x2a->tbl[n-1].data; + }else{ + data = 0; + } + return data; +} + +/* Return the size of the array */ +int Symbol_count() +{ + return x2a ? x2a->count : 0; +} + +/* Return an array of pointers to all data in the table. +** The array is obtained from malloc. Return NULL if memory allocation +** problems, or if the array is empty. */ +struct symbol **Symbol_arrayof() +{ + struct symbol **array; + int i,size; + if( x2a==0 ) return 0; + size = x2a->count; + array = (struct symbol **)calloc(size, sizeof(struct symbol *)); + if( array ){ + for(i=0; itbl[i].data; + } + return array; +} + +/* Compare two configurations */ +int Configcmp(const char *_a,const char *_b) +{ + const struct config *a = (struct config *) _a; + const struct config *b = (struct config *) _b; + int x; + x = a->rp->index - b->rp->index; + if( x==0 ) x = a->dot - b->dot; + return x; +} + +/* Compare two states */ +PRIVATE int statecmp(struct config *a, struct config *b) +{ + int rc; + for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){ + rc = a->rp->index - b->rp->index; + if( rc==0 ) rc = a->dot - b->dot; + } + if( rc==0 ){ + if( a ) rc = 1; + if( b ) rc = -1; + } + return rc; +} + +/* Hash a state */ +PRIVATE unsigned statehash(struct config *a) +{ + unsigned h=0; + while( a ){ + h = h*571 + a->rp->index*37 + a->dot; + a = a->bp; + } + return h; +} + +/* Allocate a new state structure */ +struct state *State_new() +{ + struct state *newstate; + newstate = (struct state *)calloc(1, sizeof(struct state) ); + MemoryCheck(newstate); + return newstate; +} + +/* There is one instance of the following structure for each +** associative array of type "x3". +*/ +struct s_x3 { + int size; /* The number of available slots. */ + /* Must be a power of 2 greater than or */ + /* equal to 1 */ + int count; /* Number of currently slots filled */ + struct s_x3node *tbl; /* The data stored here */ + struct s_x3node **ht; /* Hash table for lookups */ +}; + +/* There is one instance of this structure for every data element +** in an associative array of type "x3". +*/ +typedef struct s_x3node { + struct state *data; /* The data */ + struct config *key; /* The key */ + struct s_x3node *next; /* Next entry with the same hash */ + struct s_x3node **from; /* Previous link */ +} x3node; + +/* There is only one instance of the array, which is the following */ +static struct s_x3 *x3a; + +/* Allocate a new associative array */ +void State_init(){ + if( x3a ) return; + x3a = (struct s_x3*)malloc( sizeof(struct s_x3) ); + if( x3a ){ + x3a->size = 128; + x3a->count = 0; + x3a->tbl = (x3node*)malloc( + (sizeof(x3node) + sizeof(x3node*))*128 ); + if( x3a->tbl==0 ){ + free(x3a); + x3a = 0; + }else{ + int i; + x3a->ht = (x3node**)&(x3a->tbl[128]); + for(i=0; i<128; i++) x3a->ht[i] = 0; + } + } +} +/* Insert a new record into the array. Return TRUE if successful. +** Prior data with the same key is NOT overwritten */ +int State_insert(struct state *data, struct config *key) +{ + x3node *np; + unsigned h; + unsigned ph; + + if( x3a==0 ) return 0; + ph = statehash(key); + h = ph & (x3a->size-1); + np = x3a->ht[h]; + while( np ){ + if( statecmp(np->key,key)==0 ){ + /* An existing entry with the same key is found. */ + /* Fail because overwrite is not allows. */ + return 0; + } + np = np->next; + } + if( x3a->count>=x3a->size ){ + /* Need to make the hash table bigger */ + int i,size; + struct s_x3 array; + array.size = size = x3a->size*2; + array.count = x3a->count; + array.tbl = (x3node*)malloc( + (sizeof(x3node) + sizeof(x3node*))*size ); + if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ + array.ht = (x3node**)&(array.tbl[size]); + for(i=0; icount; i++){ + x3node *oldnp, *newnp; + oldnp = &(x3a->tbl[i]); + h = statehash(oldnp->key) & (size-1); + newnp = &(array.tbl[i]); + if( array.ht[h] ) array.ht[h]->from = &(newnp->next); + newnp->next = array.ht[h]; + newnp->key = oldnp->key; + newnp->data = oldnp->data; + newnp->from = &(array.ht[h]); + array.ht[h] = newnp; + } + free(x3a->tbl); + *x3a = array; + } + /* Insert the new data */ + h = ph & (x3a->size-1); + np = &(x3a->tbl[x3a->count++]); + np->key = key; + np->data = data; + if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next); + np->next = x3a->ht[h]; + x3a->ht[h] = np; + np->from = &(x3a->ht[h]); + return 1; +} + +/* Return a pointer to data assigned to the given key. Return NULL +** if no such key. */ +struct state *State_find(struct config *key) +{ + unsigned h; + x3node *np; + + if( x3a==0 ) return 0; + h = statehash(key) & (x3a->size-1); + np = x3a->ht[h]; + while( np ){ + if( statecmp(np->key,key)==0 ) break; + np = np->next; + } + return np ? np->data : 0; +} + +/* Return an array of pointers to all data in the table. +** The array is obtained from malloc. Return NULL if memory allocation +** problems, or if the array is empty. */ +struct state **State_arrayof() +{ + struct state **array; + int i,size; + if( x3a==0 ) return 0; + size = x3a->count; + array = (struct state **)malloc( sizeof(struct state *)*size ); + if( array ){ + for(i=0; itbl[i].data; + } + return array; +} + +/* Hash a configuration */ +PRIVATE unsigned confighash(struct config *a) +{ + unsigned h=0; + h = h*571 + a->rp->index*37 + a->dot; + return h; +} + +/* There is one instance of the following structure for each +** associative array of type "x4". +*/ +struct s_x4 { + int size; /* The number of available slots. */ + /* Must be a power of 2 greater than or */ + /* equal to 1 */ + int count; /* Number of currently slots filled */ + struct s_x4node *tbl; /* The data stored here */ + struct s_x4node **ht; /* Hash table for lookups */ +}; + +/* There is one instance of this structure for every data element +** in an associative array of type "x4". +*/ +typedef struct s_x4node { + struct config *data; /* The data */ + struct s_x4node *next; /* Next entry with the same hash */ + struct s_x4node **from; /* Previous link */ +} x4node; + +/* There is only one instance of the array, which is the following */ +static struct s_x4 *x4a; + +/* Allocate a new associative array */ +void Configtable_init(){ + if( x4a ) return; + x4a = (struct s_x4*)malloc( sizeof(struct s_x4) ); + if( x4a ){ + x4a->size = 64; + x4a->count = 0; + x4a->tbl = (x4node*)malloc( + (sizeof(x4node) + sizeof(x4node*))*64 ); + if( x4a->tbl==0 ){ + free(x4a); + x4a = 0; + }else{ + int i; + x4a->ht = (x4node**)&(x4a->tbl[64]); + for(i=0; i<64; i++) x4a->ht[i] = 0; + } + } +} +/* Insert a new record into the array. Return TRUE if successful. +** Prior data with the same key is NOT overwritten */ +int Configtable_insert(struct config *data) +{ + x4node *np; + unsigned h; + unsigned ph; + + if( x4a==0 ) return 0; + ph = confighash(data); + h = ph & (x4a->size-1); + np = x4a->ht[h]; + while( np ){ + if( Configcmp((const char *) np->data,(const char *) data)==0 ){ + /* An existing entry with the same key is found. */ + /* Fail because overwrite is not allows. */ + return 0; + } + np = np->next; + } + if( x4a->count>=x4a->size ){ + /* Need to make the hash table bigger */ + int i,size; + struct s_x4 array; + array.size = size = x4a->size*2; + array.count = x4a->count; + array.tbl = (x4node*)malloc( + (sizeof(x4node) + sizeof(x4node*))*size ); + if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ + array.ht = (x4node**)&(array.tbl[size]); + for(i=0; icount; i++){ + x4node *oldnp, *newnp; + oldnp = &(x4a->tbl[i]); + h = confighash(oldnp->data) & (size-1); + newnp = &(array.tbl[i]); + if( array.ht[h] ) array.ht[h]->from = &(newnp->next); + newnp->next = array.ht[h]; + newnp->data = oldnp->data; + newnp->from = &(array.ht[h]); + array.ht[h] = newnp; + } + free(x4a->tbl); + *x4a = array; + } + /* Insert the new data */ + h = ph & (x4a->size-1); + np = &(x4a->tbl[x4a->count++]); + np->data = data; + if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next); + np->next = x4a->ht[h]; + x4a->ht[h] = np; + np->from = &(x4a->ht[h]); + return 1; +} + +/* Return a pointer to data assigned to the given key. Return NULL +** if no such key. */ +struct config *Configtable_find(struct config *key) +{ + int h; + x4node *np; + + if( x4a==0 ) return 0; + h = confighash(key) & (x4a->size-1); + np = x4a->ht[h]; + while( np ){ + if( Configcmp((const char *) np->data,(const char *) key)==0 ) break; + np = np->next; + } + return np ? np->data : 0; +} + +/* Remove all data from the table. Pass each data to the function "f" +** as it is removed. ("f" may be null to avoid this step.) */ +void Configtable_clear(int(*f)(struct config *)) +{ + int i; + if( x4a==0 || x4a->count==0 ) return; + if( f ) for(i=0; icount; i++) (*f)(x4a->tbl[i].data); + for(i=0; isize; i++) x4a->ht[i] = 0; + x4a->count = 0; + return; +} diff --git a/components/external/SQLite-3.8.1/tool/lempar.c b/components/external/SQLite-3.8.1/tool/lempar.c new file mode 100644 index 0000000000000000000000000000000000000000..fe56d2dc1661eb9c2468ab9b0c763238e79f6252 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/lempar.c @@ -0,0 +1,850 @@ +/* Driver template for the LEMON parser generator. +** The author disclaims copyright to this source code. +*/ +/* First off, code is included that follows the "include" declaration +** in the input grammar file. */ +#include +%% +/* Next is all token values, in a form suitable for use by makeheaders. +** This section will be null unless lemon is run with the -m switch. +*/ +/* +** These constants (all generated automatically by the parser generator) +** specify the various kinds of tokens (terminals) that the parser +** understands. +** +** Each symbol here is a terminal symbol in the grammar. +*/ +%% +/* Make sure the INTERFACE macro is defined. +*/ +#ifndef INTERFACE +# define INTERFACE 1 +#endif +/* The next thing included is series of defines which control +** various aspects of the generated parser. +** YYCODETYPE is the data type used for storing terminal +** and nonterminal numbers. "unsigned char" is +** used if there are fewer than 250 terminals +** and nonterminals. "int" is used otherwise. +** YYNOCODE is a number of type YYCODETYPE which corresponds +** to no legal terminal or nonterminal number. This +** number is used to fill in empty slots of the hash +** table. +** YYFALLBACK If defined, this indicates that one or more tokens +** have fall-back values which should be used if the +** original value of the token will not parse. +** YYACTIONTYPE is the data type used for storing terminal +** and nonterminal numbers. "unsigned char" is +** used if there are fewer than 250 rules and +** states combined. "int" is used otherwise. +** ParseTOKENTYPE is the data type used for minor tokens given +** directly to the parser from the tokenizer. +** YYMINORTYPE is the data type used for all minor tokens. +** This is typically a union of many types, one of +** which is ParseTOKENTYPE. The entry in the union +** for base tokens is called "yy0". +** YYSTACKDEPTH is the maximum depth of the parser's stack. If +** zero the stack is dynamically sized using realloc() +** ParseARG_SDECL A static variable declaration for the %extra_argument +** ParseARG_PDECL A parameter declaration for the %extra_argument +** ParseARG_STORE Code to store %extra_argument into yypParser +** ParseARG_FETCH Code to extract %extra_argument from yypParser +** YYNSTATE the combined number of states. +** YYNRULE the number of rules in the grammar +** YYERRORSYMBOL is the code number of the error symbol. If not +** defined, then do no error processing. +*/ +%% +#define YY_NO_ACTION (YYNSTATE+YYNRULE+2) +#define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) +#define YY_ERROR_ACTION (YYNSTATE+YYNRULE) + +/* The yyzerominor constant is used to initialize instances of +** YYMINORTYPE objects to zero. */ +static const YYMINORTYPE yyzerominor = { 0 }; + +/* Define the yytestcase() macro to be a no-op if is not already defined +** otherwise. +** +** Applications can choose to define yytestcase() in the %include section +** to a macro that can assist in verifying code coverage. For production +** code the yytestcase() macro should be turned off. But it is useful +** for testing. +*/ +#ifndef yytestcase +# define yytestcase(X) +#endif + + +/* Next are the tables used to determine what action to take based on the +** current state and lookahead token. These tables are used to implement +** functions that take a state number and lookahead value and return an +** action integer. +** +** Suppose the action integer is N. Then the action is determined as +** follows +** +** 0 <= N < YYNSTATE Shift N. That is, push the lookahead +** token onto the stack and goto state N. +** +** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. +** +** N == YYNSTATE+YYNRULE A syntax error has occurred. +** +** N == YYNSTATE+YYNRULE+1 The parser accepts its input. +** +** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused +** slots in the yy_action[] table. +** +** The action table is constructed as a single large table named yy_action[]. +** Given state S and lookahead X, the action is computed as +** +** yy_action[ yy_shift_ofst[S] + X ] +** +** If the index value yy_shift_ofst[S]+X is out of range or if the value +** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] +** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table +** and that yy_default[S] should be used instead. +** +** The formula above is for computing the action when the lookahead is +** a terminal symbol. If the lookahead is a non-terminal (as occurs after +** a reduce action) then the yy_reduce_ofst[] array is used in place of +** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of +** YY_SHIFT_USE_DFLT. +** +** The following are the tables generated in this section: +** +** yy_action[] A single table containing all actions. +** yy_lookahead[] A table containing the lookahead for each entry in +** yy_action. Used to detect hash collisions. +** yy_shift_ofst[] For each state, the offset into yy_action for +** shifting terminals. +** yy_reduce_ofst[] For each state, the offset into yy_action for +** shifting non-terminals after a reduce. +** yy_default[] Default action for each state. +*/ +%% + +/* The next table maps tokens into fallback tokens. If a construct +** like the following: +** +** %fallback ID X Y Z. +** +** appears in the grammar, then ID becomes a fallback token for X, Y, +** and Z. Whenever one of the tokens X, Y, or Z is input to the parser +** but it does not parse, the type of the token is changed to ID and +** the parse is retried before an error is thrown. +*/ +#ifdef YYFALLBACK +static const YYCODETYPE yyFallback[] = { +%% +}; +#endif /* YYFALLBACK */ + +/* The following structure represents a single element of the +** parser's stack. Information stored includes: +** +** + The state number for the parser at this level of the stack. +** +** + The value of the token stored at this level of the stack. +** (In other words, the "major" token.) +** +** + The semantic value stored at this level of the stack. This is +** the information used by the action routines in the grammar. +** It is sometimes called the "minor" token. +*/ +struct yyStackEntry { + YYACTIONTYPE stateno; /* The state-number */ + YYCODETYPE major; /* The major token value. This is the code + ** number for the token at this stack level */ + YYMINORTYPE minor; /* The user-supplied minor token value. This + ** is the value of the token */ +}; +typedef struct yyStackEntry yyStackEntry; + +/* The state of the parser is completely contained in an instance of +** the following structure */ +struct yyParser { + int yyidx; /* Index of top element in stack */ +#ifdef YYTRACKMAXSTACKDEPTH + int yyidxMax; /* Maximum value of yyidx */ +#endif + int yyerrcnt; /* Shifts left before out of the error */ + ParseARG_SDECL /* A place to hold %extra_argument */ +#if YYSTACKDEPTH<=0 + int yystksz; /* Current side of the stack */ + yyStackEntry *yystack; /* The parser's stack */ +#else + yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ +#endif +}; +typedef struct yyParser yyParser; + +#ifndef NDEBUG +#include +static FILE *yyTraceFILE = 0; +static char *yyTracePrompt = 0; +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* +** Turn parser tracing on by giving a stream to which to write the trace +** and a prompt to preface each trace message. Tracing is turned off +** by making either argument NULL +** +** Inputs: +**
      +**
    • A FILE* to which trace output should be written. +** If NULL, then tracing is turned off. +**
    • A prefix string written at the beginning of every +** line of trace output. If NULL, then tracing is +** turned off. +**
    +** +** Outputs: +** None. +*/ +void ParseTrace(FILE *TraceFILE, char *zTracePrompt){ + yyTraceFILE = TraceFILE; + yyTracePrompt = zTracePrompt; + if( yyTraceFILE==0 ) yyTracePrompt = 0; + else if( yyTracePrompt==0 ) yyTraceFILE = 0; +} +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* For tracing shifts, the names of all terminals and nonterminals +** are required. The following table supplies these names */ +static const char *const yyTokenName[] = { +%% +}; +#endif /* NDEBUG */ + +#ifndef NDEBUG +/* For tracing reduce actions, the names of all rules are required. +*/ +static const char *const yyRuleName[] = { +%% +}; +#endif /* NDEBUG */ + + +#if YYSTACKDEPTH<=0 +/* +** Try to increase the size of the parser stack. +*/ +static void yyGrowStack(yyParser *p){ + int newSize; + yyStackEntry *pNew; + + newSize = p->yystksz*2 + 100; + pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); + if( pNew ){ + p->yystack = pNew; + p->yystksz = newSize; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sStack grows to %d entries!\n", + yyTracePrompt, p->yystksz); + } +#endif + } +} +#endif + +/* +** This function allocates a new parser. +** The only argument is a pointer to a function which works like +** malloc. +** +** Inputs: +** A pointer to the function used to allocate memory. +** +** Outputs: +** A pointer to a parser. This pointer is used in subsequent calls +** to Parse and ParseFree. +*/ +void *ParseAlloc(void *(*mallocProc)(size_t)){ + yyParser *pParser; + pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); + if( pParser ){ + pParser->yyidx = -1; +#ifdef YYTRACKMAXSTACKDEPTH + pParser->yyidxMax = 0; +#endif +#if YYSTACKDEPTH<=0 + pParser->yystack = NULL; + pParser->yystksz = 0; + yyGrowStack(pParser); +#endif + } + return pParser; +} + +/* The following function deletes the value associated with a +** symbol. The symbol can be either a terminal or nonterminal. +** "yymajor" is the symbol code, and "yypminor" is a pointer to +** the value. +*/ +static void yy_destructor( + yyParser *yypParser, /* The parser */ + YYCODETYPE yymajor, /* Type code for object to destroy */ + YYMINORTYPE *yypminor /* The object to be destroyed */ +){ + ParseARG_FETCH; + switch( yymajor ){ + /* Here is inserted the actions which take place when a + ** terminal or non-terminal is destroyed. This can happen + ** when the symbol is popped from the stack during a + ** reduce or during error processing or when a parser is + ** being destroyed before it is finished parsing. + ** + ** Note: during a reduce, the only symbols destroyed are those + ** which appear on the RHS of the rule, but which are not used + ** inside the C code. + */ +%% + default: break; /* If no destructor action specified: do nothing */ + } +} + +/* +** Pop the parser's stack once. +** +** If there is a destructor routine associated with the token which +** is popped from the stack, then call it. +** +** Return the major token number for the symbol popped. +*/ +static int yy_pop_parser_stack(yyParser *pParser){ + YYCODETYPE yymajor; + yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; + + if( pParser->yyidx<0 ) return 0; +#ifndef NDEBUG + if( yyTraceFILE && pParser->yyidx>=0 ){ + fprintf(yyTraceFILE,"%sPopping %s\n", + yyTracePrompt, + yyTokenName[yytos->major]); + } +#endif + yymajor = yytos->major; + yy_destructor(pParser, yymajor, &yytos->minor); + pParser->yyidx--; + return yymajor; +} + +/* +** Deallocate and destroy a parser. Destructors are all called for +** all stack elements before shutting the parser down. +** +** Inputs: +**
      +**
    • A pointer to the parser. This should be a pointer +** obtained from ParseAlloc. +**
    • A pointer to a function used to reclaim memory obtained +** from malloc. +**
    +*/ +void ParseFree( + void *p, /* The parser to be deleted */ + void (*freeProc)(void*) /* Function used to reclaim memory */ +){ + yyParser *pParser = (yyParser*)p; + if( pParser==0 ) return; + while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); +#if YYSTACKDEPTH<=0 + free(pParser->yystack); +#endif + (*freeProc)((void*)pParser); +} + +/* +** Return the peak depth of the stack for a parser. +*/ +#ifdef YYTRACKMAXSTACKDEPTH +int ParseStackPeak(void *p){ + yyParser *pParser = (yyParser*)p; + return pParser->yyidxMax; +} +#endif + +/* +** Find the appropriate action for a parser given the terminal +** look-ahead token iLookAhead. +** +** If the look-ahead token is YYNOCODE, then check to see if the action is +** independent of the look-ahead. If it is, return the action, otherwise +** return YY_NO_ACTION. +*/ +static int yy_find_shift_action( + yyParser *pParser, /* The parser */ + YYCODETYPE iLookAhead /* The look-ahead token */ +){ + int i; + int stateno = pParser->yystack[pParser->yyidx].stateno; + + if( stateno>YY_SHIFT_COUNT + || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){ + return yy_default[stateno]; + } + assert( iLookAhead!=YYNOCODE ); + i += iLookAhead; + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ + if( iLookAhead>0 ){ +#ifdef YYFALLBACK + YYCODETYPE iFallback; /* Fallback token */ + if( iLookAhead %s\n", + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); + } +#endif + return yy_find_shift_action(pParser, iFallback); + } +#endif +#ifdef YYWILDCARD + { + int j = i - iLookAhead + YYWILDCARD; + if( +#if YY_SHIFT_MIN+YYWILDCARD<0 + j>=0 && +#endif +#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT + j %s\n", + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); + } +#endif /* NDEBUG */ + return yy_action[j]; + } + } +#endif /* YYWILDCARD */ + } + return yy_default[stateno]; + }else{ + return yy_action[i]; + } +} + +/* +** Find the appropriate action for a parser given the non-terminal +** look-ahead token iLookAhead. +** +** If the look-ahead token is YYNOCODE, then check to see if the action is +** independent of the look-ahead. If it is, return the action, otherwise +** return YY_NO_ACTION. +*/ +static int yy_find_reduce_action( + int stateno, /* Current state number */ + YYCODETYPE iLookAhead /* The look-ahead token */ +){ + int i; +#ifdef YYERRORSYMBOL + if( stateno>YY_REDUCE_COUNT ){ + return yy_default[stateno]; + } +#else + assert( stateno<=YY_REDUCE_COUNT ); +#endif + i = yy_reduce_ofst[stateno]; + assert( i!=YY_REDUCE_USE_DFLT ); + assert( iLookAhead!=YYNOCODE ); + i += iLookAhead; +#ifdef YYERRORSYMBOL + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ + return yy_default[stateno]; + } +#else + assert( i>=0 && iyyidx--; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); + } +#endif + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will execute if the parser + ** stack every overflows */ +%% + ParseARG_STORE; /* Suppress warning about unused %extra_argument var */ +} + +/* +** Perform a shift action. +*/ +static void yy_shift( + yyParser *yypParser, /* The parser to be shifted */ + int yyNewState, /* The new state to shift in */ + int yyMajor, /* The major token to shift in */ + YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */ +){ + yyStackEntry *yytos; + yypParser->yyidx++; +#ifdef YYTRACKMAXSTACKDEPTH + if( yypParser->yyidx>yypParser->yyidxMax ){ + yypParser->yyidxMax = yypParser->yyidx; + } +#endif +#if YYSTACKDEPTH>0 + if( yypParser->yyidx>=YYSTACKDEPTH ){ + yyStackOverflow(yypParser, yypMinor); + return; + } +#else + if( yypParser->yyidx>=yypParser->yystksz ){ + yyGrowStack(yypParser); + if( yypParser->yyidx>=yypParser->yystksz ){ + yyStackOverflow(yypParser, yypMinor); + return; + } + } +#endif + yytos = &yypParser->yystack[yypParser->yyidx]; + yytos->stateno = (YYACTIONTYPE)yyNewState; + yytos->major = (YYCODETYPE)yyMajor; + yytos->minor = *yypMinor; +#ifndef NDEBUG + if( yyTraceFILE && yypParser->yyidx>0 ){ + int i; + fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); + fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); + for(i=1; i<=yypParser->yyidx; i++) + fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); + fprintf(yyTraceFILE,"\n"); + } +#endif +} + +/* The following table contains information about every rule that +** is used during the reduce. +*/ +static const struct { + YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ + unsigned char nrhs; /* Number of right-hand side symbols in the rule */ +} yyRuleInfo[] = { +%% +}; + +static void yy_accept(yyParser*); /* Forward Declaration */ + +/* +** Perform a reduce action and the shift that must immediately +** follow the reduce. +*/ +static void yy_reduce( + yyParser *yypParser, /* The parser */ + int yyruleno /* Number of the rule by which to reduce */ +){ + int yygoto; /* The next state */ + int yyact; /* The next action */ + YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ + yyStackEntry *yymsp; /* The top of the parser's stack */ + int yysize; /* Amount to pop the stack */ + ParseARG_FETCH; + yymsp = &yypParser->yystack[yypParser->yyidx]; +#ifndef NDEBUG + if( yyTraceFILE && yyruleno>=0 + && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ + fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, + yyRuleName[yyruleno]); + } +#endif /* NDEBUG */ + + /* Silence complaints from purify about yygotominor being uninitialized + ** in some cases when it is copied into the stack after the following + ** switch. yygotominor is uninitialized when a rule reduces that does + ** not set the value of its left-hand side nonterminal. Leaving the + ** value of the nonterminal uninitialized is utterly harmless as long + ** as the value is never used. So really the only thing this code + ** accomplishes is to quieten purify. + ** + ** 2007-01-16: The wireshark project (www.wireshark.org) reports that + ** without this code, their parser segfaults. I'm not sure what there + ** parser is doing to make this happen. This is the second bug report + ** from wireshark this week. Clearly they are stressing Lemon in ways + ** that it has not been previously stressed... (SQLite ticket #2172) + */ + /*memset(&yygotominor, 0, sizeof(yygotominor));*/ + yygotominor = yyzerominor; + + + switch( yyruleno ){ + /* Beginning here are the reduction cases. A typical example + ** follows: + ** case 0: + ** #line + ** { ... } // User supplied code + ** #line + ** break; + */ +%% + }; + yygoto = yyRuleInfo[yyruleno].lhs; + yysize = yyRuleInfo[yyruleno].nrhs; + yypParser->yyidx -= yysize; + yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); + if( yyact < YYNSTATE ){ +#ifdef NDEBUG + /* If we are not debugging and the reduce action popped at least + ** one element off the stack, then we can push the new element back + ** onto the stack here, and skip the stack overflow test in yy_shift(). + ** That gives a significant speed improvement. */ + if( yysize ){ + yypParser->yyidx++; + yymsp -= yysize-1; + yymsp->stateno = (YYACTIONTYPE)yyact; + yymsp->major = (YYCODETYPE)yygoto; + yymsp->minor = yygotominor; + }else +#endif + { + yy_shift(yypParser,yyact,yygoto,&yygotominor); + } + }else{ + assert( yyact == YYNSTATE + YYNRULE + 1 ); + yy_accept(yypParser); + } +} + +/* +** The following code executes when the parse fails +*/ +#ifndef YYNOERRORRECOVERY +static void yy_parse_failed( + yyParser *yypParser /* The parser */ +){ + ParseARG_FETCH; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); + } +#endif + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will be executed whenever the + ** parser fails */ +%% + ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ +} +#endif /* YYNOERRORRECOVERY */ + +/* +** The following code executes when a syntax error first occurs. +*/ +static void yy_syntax_error( + yyParser *yypParser, /* The parser */ + int yymajor, /* The major type of the error token */ + YYMINORTYPE yyminor /* The minor type of the error token */ +){ + ParseARG_FETCH; +#define TOKEN (yyminor.yy0) +%% + ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ +} + +/* +** The following is executed when the parser accepts +*/ +static void yy_accept( + yyParser *yypParser /* The parser */ +){ + ParseARG_FETCH; +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); + } +#endif + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will be executed whenever the + ** parser accepts */ +%% + ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ +} + +/* The main parser program. +** The first argument is a pointer to a structure obtained from +** "ParseAlloc" which describes the current state of the parser. +** The second argument is the major token number. The third is +** the minor token. The fourth optional argument is whatever the +** user wants (and specified in the grammar) and is available for +** use by the action routines. +** +** Inputs: +**
      +**
    • A pointer to the parser (an opaque structure.) +**
    • The major token number. +**
    • The minor token number. +**
    • An option argument of a grammar-specified type. +**
    +** +** Outputs: +** None. +*/ +void Parse( + void *yyp, /* The parser */ + int yymajor, /* The major token code number */ + ParseTOKENTYPE yyminor /* The value for the token */ + ParseARG_PDECL /* Optional %extra_argument parameter */ +){ + YYMINORTYPE yyminorunion; + int yyact; /* The parser action. */ + int yyendofinput; /* True if we are at the end of input */ +#ifdef YYERRORSYMBOL + int yyerrorhit = 0; /* True if yymajor has invoked an error */ +#endif + yyParser *yypParser; /* The parser */ + + /* (re)initialize the parser, if necessary */ + yypParser = (yyParser*)yyp; + if( yypParser->yyidx<0 ){ +#if YYSTACKDEPTH<=0 + if( yypParser->yystksz <=0 ){ + /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/ + yyminorunion = yyzerominor; + yyStackOverflow(yypParser, &yyminorunion); + return; + } +#endif + yypParser->yyidx = 0; + yypParser->yyerrcnt = -1; + yypParser->yystack[0].stateno = 0; + yypParser->yystack[0].major = 0; + } + yyminorunion.yy0 = yyminor; + yyendofinput = (yymajor==0); + ParseARG_STORE; + +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); + } +#endif + + do{ + yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); + if( yyactyyerrcnt--; + yymajor = YYNOCODE; + }else if( yyact < YYNSTATE + YYNRULE ){ + yy_reduce(yypParser,yyact-YYNSTATE); + }else{ + assert( yyact == YY_ERROR_ACTION ); +#ifdef YYERRORSYMBOL + int yymx; +#endif +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); + } +#endif +#ifdef YYERRORSYMBOL + /* A syntax error has occurred. + ** The response to an error depends upon whether or not the + ** grammar defines an error token "ERROR". + ** + ** This is what we do if the grammar does define ERROR: + ** + ** * Call the %syntax_error function. + ** + ** * Begin popping the stack until we enter a state where + ** it is legal to shift the error symbol, then shift + ** the error symbol. + ** + ** * Set the error count to three. + ** + ** * Begin accepting and shifting new tokens. No new error + ** processing will occur until three tokens have been + ** shifted successfully. + ** + */ + if( yypParser->yyerrcnt<0 ){ + yy_syntax_error(yypParser,yymajor,yyminorunion); + } + yymx = yypParser->yystack[yypParser->yyidx].major; + if( yymx==YYERRORSYMBOL || yyerrorhit ){ +#ifndef NDEBUG + if( yyTraceFILE ){ + fprintf(yyTraceFILE,"%sDiscard input token %s\n", + yyTracePrompt,yyTokenName[yymajor]); + } +#endif + yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion); + yymajor = YYNOCODE; + }else{ + while( + yypParser->yyidx >= 0 && + yymx != YYERRORSYMBOL && + (yyact = yy_find_reduce_action( + yypParser->yystack[yypParser->yyidx].stateno, + YYERRORSYMBOL)) >= YYNSTATE + ){ + yy_pop_parser_stack(yypParser); + } + if( yypParser->yyidx < 0 || yymajor==0 ){ + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); + yy_parse_failed(yypParser); + yymajor = YYNOCODE; + }else if( yymx!=YYERRORSYMBOL ){ + YYMINORTYPE u2; + u2.YYERRSYMDT = 0; + yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); + } + } + yypParser->yyerrcnt = 3; + yyerrorhit = 1; +#elif defined(YYNOERRORRECOVERY) + /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to + ** do any kind of error recovery. Instead, simply invoke the syntax + ** error routine and continue going as if nothing had happened. + ** + ** Applications can set this macro (for example inside %include) if + ** they intend to abandon the parse upon the first syntax error seen. + */ + yy_syntax_error(yypParser,yymajor,yyminorunion); + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); + yymajor = YYNOCODE; + +#else /* YYERRORSYMBOL is not defined */ + /* This is what we do if the grammar does not define ERROR: + ** + ** * Report an error message, and throw away the input token. + ** + ** * If the input token is $, then fail the parse. + ** + ** As before, subsequent error messages are suppressed until + ** three input tokens have been successfully shifted. + */ + if( yypParser->yyerrcnt<=0 ){ + yy_syntax_error(yypParser,yymajor,yyminorunion); + } + yypParser->yyerrcnt = 3; + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); + if( yyendofinput ){ + yy_parse_failed(yypParser); + } + yymajor = YYNOCODE; +#endif + } + }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); + return; +} diff --git a/components/external/SQLite-3.8.1/tool/logest.c b/components/external/SQLite-3.8.1/tool/logest.c new file mode 100644 index 0000000000000000000000000000000000000000..8dad6cc9b6ee5f85aedef35e62a2448911a80ef7 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/logest.c @@ -0,0 +1,141 @@ +/* +** 2013-06-10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains a simple command-line utility for converting from +** integers and LogEst values and back again and for doing simple +** arithmetic operations (multiple and add) on LogEst values. +** +** Usage: +** +** ./LogEst ARGS +** +** Arguments: +** +** 'x' Multiple the top two elements of the stack +** '+' Add the top two elements of the stack +** NUM Convert NUM from integer to LogEst and push onto the stack +** ^NUM Interpret NUM as a LogEst and push onto stack. +** +** Examples: +** +** To convert 123 from LogEst to integer: +** +** ./LogEst ^123 +** +** To convert 123456 from integer to LogEst: +** +** ./LogEst 123456 +** +*/ +#include +#include +#include +#include +#include +#include "sqlite3.h" + +typedef short int LogEst; /* 10 times log2() */ + +LogEst logEstMultiply(LogEst a, LogEst b){ return a+b; } +LogEst logEstAdd(LogEst a, LogEst b){ + static const unsigned char x[] = { + 10, 10, /* 0,1 */ + 9, 9, /* 2,3 */ + 8, 8, /* 4,5 */ + 7, 7, 7, /* 6,7,8 */ + 6, 6, 6, /* 9,10,11 */ + 5, 5, 5, /* 12-14 */ + 4, 4, 4, 4, /* 15-18 */ + 3, 3, 3, 3, 3, 3, /* 19-24 */ + 2, 2, 2, 2, 2, 2, 2, /* 25-31 */ + }; + if( ab+49 ) return a; + if( a>b+31 ) return a+1; + return a+x[a-b]; +} +LogEst logEstFromInteger(sqlite3_uint64 x){ + static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 }; + LogEst y = 40; + if( x<8 ){ + if( x<2 ) return 0; + while( x<8 ){ y -= 10; x <<= 1; } + }else{ + while( x>255 ){ y += 40; x >>= 4; } + while( x>15 ){ y += 10; x >>= 1; } + } + return a[x&7] + y - 10; +} +static sqlite3_uint64 logEstToInt(LogEst x){ + sqlite3_uint64 n; + if( x<10 ) return 1; + n = x%10; + x /= 10; + if( n>=5 ) n -= 2; + else if( n>=1 ) n -= 1; + if( x>=3 ) return (n+8)<<(x-3); + return (n+8)>>(3-x); +} +static LogEst logEstFromDouble(double x){ + sqlite3_uint64 a; + LogEst e; + assert( sizeof(x)==8 && sizeof(a)==8 ); + if( x<=0.0 ) return -32768; + if( x<1.0 ) return -logEstFromDouble(1/x); + if( x<1024.0 ) return logEstFromInteger((sqlite3_uint64)(1024.0*x)) - 100; + if( x<=2000000000.0 ) return logEstFromInteger((sqlite3_uint64)x); + memcpy(&a, &x, 8); + e = (a>>52) - 1022; + return e*10; +} + +int isFloat(const char *z){ + while( z[0] ){ + if( z[0]=='.' || z[0]=='E' || z[0]=='e' ) return 1; + z++; + } + return 0; +} + +int main(int argc, char **argv){ + int i; + int n = 0; + LogEst a[100]; + for(i=1; i=2 ){ + a[n-2] = logEstAdd(a[n-2],a[n-1]); + n--; + } + }else if( z[0]=='x' ){ + if( n>=2 ){ + a[n-2] = logEstMultiply(a[n-2],a[n-1]); + n--; + } + }else if( z[0]=='^' ){ + a[n++] = atoi(z+1); + }else if( isFloat(z) ){ + a[n++] = logEstFromDouble(atof(z)); + }else{ + a[n++] = logEstFromInteger(atoi(z)); + } + } + for(i=n-1; i>=0; i--){ + if( a[i]<0 ){ + printf("%d (%f)\n", a[i], 1.0/(double)logEstToInt(-a[i])); + }else{ + sqlite3_uint64 x = logEstToInt(a[i]+100)*100/1024; + printf("%d (%lld.%02lld)\n", a[i], x/100, x%100); + } + } + return 0; +} diff --git a/components/external/SQLite-3.8.1/tool/mkautoconfamal.sh b/components/external/SQLite-3.8.1/tool/mkautoconfamal.sh new file mode 100644 index 0000000000000000000000000000000000000000..c13f7c999ada50bbc6c1c797baa8adeb4da128b4 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/mkautoconfamal.sh @@ -0,0 +1,83 @@ +#!/bin/sh +# This script is used to build the amalgamation autoconf package. +# It assumes the following: +# +# 1. The files "sqlite3.c", "sqlite3.h" and "sqlite3ext.h" +# are available in the current directory. +# +# 2. Variable $TOP is set to the full path of the root directory +# of the SQLite source tree. +# +# 3. There is nothing of value in the ./mkpkg_tmp_dir directory. +# This is important, as the script executes "rm -rf ./mkpkg_tmp_dir". +# + + +# Bail out of the script if any command returns a non-zero exit +# status. Or if the script tries to use an unset variable. These +# may fail for old /bin/sh interpreters. +# +set -e +set -u + +TMPSPACE=./mkpkg_tmp_dir +VERSION=`cat $TOP/VERSION` + +# Set global variable $ARTIFACT to the "3xxyyzz" string incorporated +# into artifact filenames. And $VERSION2 to the "3.x.y[.z]" form. +xx=`echo $VERSION|sed 's/3\.\([0-9]*\)\..*/\1/'` +yy=`echo $VERSION|sed 's/3\.[^.]*\.\([0-9]*\).*/\1/'` +zz=0 +set +e + zz=`echo $VERSION|sed 's/3\.[^.]*\.[^.]*\.\([0-9]*\).*/\1/'|grep -v '\.'` +set -e +ARTIFACT=`printf "3%.2d%.2d%.2d" $xx $yy $zz` + +rm -rf $TMPSPACE +cp -R $TOP/autoconf $TMPSPACE + +cp sqlite3.c $TMPSPACE +cp sqlite3.h $TMPSPACE +cp sqlite3ext.h $TMPSPACE +cp $TOP/sqlite3.1 $TMPSPACE +cp $TOP/sqlite3.pc.in $TMPSPACE +cp $TOP/src/shell.c $TMPSPACE + +chmod 755 $TMPSPACE/install-sh +chmod 755 $TMPSPACE/missing +chmod 755 $TMPSPACE/depcomp +chmod 755 $TMPSPACE/config.sub +chmod 755 $TMPSPACE/config.guess + +cat $TMPSPACE/configure.ac | +sed "s/AC_INIT(sqlite, .*, http:\/\/www.sqlite.org)/AC_INIT(sqlite, $VERSION, http:\/\/www.sqlite.org)/" > $TMPSPACE/tmp +mv $TMPSPACE/tmp $TMPSPACE/configure.ac + +cd $TMPSPACE +aclocal +autoconf +automake + +mkdir -p tea/generic +echo "#ifdef USE_SYSTEM_SQLITE" > tea/generic/tclsqlite3.c +echo "# include " >> tea/generic/tclsqlite3.c +echo "#else" >> tea/generic/tclsqlite3.c +echo "#include \"../../sqlite3.c\"" >> tea/generic/tclsqlite3.c +echo "#endif" >> tea/generic/tclsqlite3.c +cat $TOP/src/tclsqlite.c >> tea/generic/tclsqlite3.c + +cat tea/configure.in | + sed "s/AC_INIT(\[sqlite\], .*)/AC_INIT([sqlite], [$VERSION])/" > tmp +mv tmp tea/configure.in + +cd tea +autoconf +rm -rf autom4te.cache + +cd ../ +./configure && make dist +tar -xzf sqlite-$VERSION.tar.gz +mv sqlite-$VERSION sqlite-autoconf-$ARTIFACT +tar -czf sqlite-autoconf-$ARTIFACT.tar.gz sqlite-autoconf-$ARTIFACT +mv sqlite-autoconf-$ARTIFACT.tar.gz .. + diff --git a/components/external/SQLite-3.8.1/tool/mkkeywordhash.c b/components/external/SQLite-3.8.1/tool/mkkeywordhash.c new file mode 100644 index 0000000000000000000000000000000000000000..4e5ba8f1a8d2d259d2b6e1a1f91f9c2333b26faf --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/mkkeywordhash.c @@ -0,0 +1,602 @@ +/* +** Compile and run this standalone program in order to generate code that +** implements a function that will translate alphabetic identifiers into +** parser token codes. +*/ +#include +#include +#include +#include + +/* +** A header comment placed at the beginning of generated code. +*/ +static const char zHdr[] = + "/***** This file contains automatically generated code ******\n" + "**\n" + "** The code in this file has been automatically generated by\n" + "**\n" + "** sqlite/tool/mkkeywordhash.c\n" + "**\n" + "** The code in this file implements a function that determines whether\n" + "** or not a given identifier is really an SQL keyword. The same thing\n" + "** might be implemented more directly using a hand-written hash table.\n" + "** But by using this automatically generated code, the size of the code\n" + "** is substantially reduced. This is important for embedded applications\n" + "** on platforms with limited memory.\n" + "*/\n" +; + +/* +** All the keywords of the SQL language are stored in a hash +** table composed of instances of the following structure. +*/ +typedef struct Keyword Keyword; +struct Keyword { + char *zName; /* The keyword name */ + char *zTokenType; /* Token value for this keyword */ + int mask; /* Code this keyword if non-zero */ + int id; /* Unique ID for this record */ + int hash; /* Hash on the keyword */ + int offset; /* Offset to start of name string */ + int len; /* Length of this keyword, not counting final \000 */ + int prefix; /* Number of characters in prefix */ + int longestSuffix; /* Longest suffix that is a prefix on another word */ + int iNext; /* Index in aKeywordTable[] of next with same hash */ + int substrId; /* Id to another keyword this keyword is embedded in */ + int substrOffset; /* Offset into substrId for start of this keyword */ + char zOrigName[20]; /* Original keyword name before processing */ +}; + +/* +** Define masks used to determine which keywords are allowed +*/ +#ifdef SQLITE_OMIT_ALTERTABLE +# define ALTER 0 +#else +# define ALTER 0x00000001 +#endif +#define ALWAYS 0x00000002 +#ifdef SQLITE_OMIT_ANALYZE +# define ANALYZE 0 +#else +# define ANALYZE 0x00000004 +#endif +#ifdef SQLITE_OMIT_ATTACH +# define ATTACH 0 +#else +# define ATTACH 0x00000008 +#endif +#ifdef SQLITE_OMIT_AUTOINCREMENT +# define AUTOINCR 0 +#else +# define AUTOINCR 0x00000010 +#endif +#ifdef SQLITE_OMIT_CAST +# define CAST 0 +#else +# define CAST 0x00000020 +#endif +#ifdef SQLITE_OMIT_COMPOUND_SELECT +# define COMPOUND 0 +#else +# define COMPOUND 0x00000040 +#endif +#ifdef SQLITE_OMIT_CONFLICT_CLAUSE +# define CONFLICT 0 +#else +# define CONFLICT 0x00000080 +#endif +#ifdef SQLITE_OMIT_EXPLAIN +# define EXPLAIN 0 +#else +# define EXPLAIN 0x00000100 +#endif +#ifdef SQLITE_OMIT_FOREIGN_KEY +# define FKEY 0 +#else +# define FKEY 0x00000200 +#endif +#ifdef SQLITE_OMIT_PRAGMA +# define PRAGMA 0 +#else +# define PRAGMA 0x00000400 +#endif +#ifdef SQLITE_OMIT_REINDEX +# define REINDEX 0 +#else +# define REINDEX 0x00000800 +#endif +#ifdef SQLITE_OMIT_SUBQUERY +# define SUBQUERY 0 +#else +# define SUBQUERY 0x00001000 +#endif +#ifdef SQLITE_OMIT_TRIGGER +# define TRIGGER 0 +#else +# define TRIGGER 0x00002000 +#endif +#if defined(SQLITE_OMIT_AUTOVACUUM) && \ + (defined(SQLITE_OMIT_VACUUM) || defined(SQLITE_OMIT_ATTACH)) +# define VACUUM 0 +#else +# define VACUUM 0x00004000 +#endif +#ifdef SQLITE_OMIT_VIEW +# define VIEW 0 +#else +# define VIEW 0x00008000 +#endif +#ifdef SQLITE_OMIT_VIRTUALTABLE +# define VTAB 0 +#else +# define VTAB 0x00010000 +#endif +#ifdef SQLITE_OMIT_AUTOVACUUM +# define AUTOVACUUM 0 +#else +# define AUTOVACUUM 0x00020000 +#endif + +/* +** These are the keywords +*/ +static Keyword aKeywordTable[] = { + { "ABORT", "TK_ABORT", CONFLICT|TRIGGER }, + { "ACTION", "TK_ACTION", FKEY }, + { "ADD", "TK_ADD", ALTER }, + { "AFTER", "TK_AFTER", TRIGGER }, + { "ALL", "TK_ALL", ALWAYS }, + { "ALTER", "TK_ALTER", ALTER }, + { "ANALYZE", "TK_ANALYZE", ANALYZE }, + { "AND", "TK_AND", ALWAYS }, + { "AS", "TK_AS", ALWAYS }, + { "ASC", "TK_ASC", ALWAYS }, + { "ATTACH", "TK_ATTACH", ATTACH }, + { "AUTOINCREMENT", "TK_AUTOINCR", AUTOINCR }, + { "BEFORE", "TK_BEFORE", TRIGGER }, + { "BEGIN", "TK_BEGIN", ALWAYS }, + { "BETWEEN", "TK_BETWEEN", ALWAYS }, + { "BY", "TK_BY", ALWAYS }, + { "CASCADE", "TK_CASCADE", FKEY }, + { "CASE", "TK_CASE", ALWAYS }, + { "CAST", "TK_CAST", CAST }, + { "CHECK", "TK_CHECK", ALWAYS }, + { "COLLATE", "TK_COLLATE", ALWAYS }, + { "COLUMN", "TK_COLUMNKW", ALTER }, + { "COMMIT", "TK_COMMIT", ALWAYS }, + { "CONFLICT", "TK_CONFLICT", CONFLICT }, + { "CONSTRAINT", "TK_CONSTRAINT", ALWAYS }, + { "CREATE", "TK_CREATE", ALWAYS }, + { "CROSS", "TK_JOIN_KW", ALWAYS }, + { "CURRENT_DATE", "TK_CTIME_KW", ALWAYS }, + { "CURRENT_TIME", "TK_CTIME_KW", ALWAYS }, + { "CURRENT_TIMESTAMP","TK_CTIME_KW", ALWAYS }, + { "DATABASE", "TK_DATABASE", ATTACH }, + { "DEFAULT", "TK_DEFAULT", ALWAYS }, + { "DEFERRED", "TK_DEFERRED", ALWAYS }, + { "DEFERRABLE", "TK_DEFERRABLE", FKEY }, + { "DELETE", "TK_DELETE", ALWAYS }, + { "DESC", "TK_DESC", ALWAYS }, + { "DETACH", "TK_DETACH", ATTACH }, + { "DISTINCT", "TK_DISTINCT", ALWAYS }, + { "DROP", "TK_DROP", ALWAYS }, + { "END", "TK_END", ALWAYS }, + { "EACH", "TK_EACH", TRIGGER }, + { "ELSE", "TK_ELSE", ALWAYS }, + { "ESCAPE", "TK_ESCAPE", ALWAYS }, + { "EXCEPT", "TK_EXCEPT", COMPOUND }, + { "EXCLUSIVE", "TK_EXCLUSIVE", ALWAYS }, + { "EXISTS", "TK_EXISTS", ALWAYS }, + { "EXPLAIN", "TK_EXPLAIN", EXPLAIN }, + { "FAIL", "TK_FAIL", CONFLICT|TRIGGER }, + { "FOR", "TK_FOR", TRIGGER }, + { "FOREIGN", "TK_FOREIGN", FKEY }, + { "FROM", "TK_FROM", ALWAYS }, + { "FULL", "TK_JOIN_KW", ALWAYS }, + { "GLOB", "TK_LIKE_KW", ALWAYS }, + { "GROUP", "TK_GROUP", ALWAYS }, + { "HAVING", "TK_HAVING", ALWAYS }, + { "IF", "TK_IF", ALWAYS }, + { "IGNORE", "TK_IGNORE", CONFLICT|TRIGGER }, + { "IMMEDIATE", "TK_IMMEDIATE", ALWAYS }, + { "IN", "TK_IN", ALWAYS }, + { "INDEX", "TK_INDEX", ALWAYS }, + { "INDEXED", "TK_INDEXED", ALWAYS }, + { "INITIALLY", "TK_INITIALLY", FKEY }, + { "INNER", "TK_JOIN_KW", ALWAYS }, + { "INSERT", "TK_INSERT", ALWAYS }, + { "INSTEAD", "TK_INSTEAD", TRIGGER }, + { "INTERSECT", "TK_INTERSECT", COMPOUND }, + { "INTO", "TK_INTO", ALWAYS }, + { "IS", "TK_IS", ALWAYS }, + { "ISNULL", "TK_ISNULL", ALWAYS }, + { "JOIN", "TK_JOIN", ALWAYS }, + { "KEY", "TK_KEY", ALWAYS }, + { "LEFT", "TK_JOIN_KW", ALWAYS }, + { "LIKE", "TK_LIKE_KW", ALWAYS }, + { "LIMIT", "TK_LIMIT", ALWAYS }, + { "MATCH", "TK_MATCH", ALWAYS }, + { "NATURAL", "TK_JOIN_KW", ALWAYS }, + { "NO", "TK_NO", FKEY }, + { "NOT", "TK_NOT", ALWAYS }, + { "NOTNULL", "TK_NOTNULL", ALWAYS }, + { "NULL", "TK_NULL", ALWAYS }, + { "OF", "TK_OF", ALWAYS }, + { "OFFSET", "TK_OFFSET", ALWAYS }, + { "ON", "TK_ON", ALWAYS }, + { "OR", "TK_OR", ALWAYS }, + { "ORDER", "TK_ORDER", ALWAYS }, + { "OUTER", "TK_JOIN_KW", ALWAYS }, + { "PLAN", "TK_PLAN", EXPLAIN }, + { "PRAGMA", "TK_PRAGMA", PRAGMA }, + { "PRIMARY", "TK_PRIMARY", ALWAYS }, + { "QUERY", "TK_QUERY", EXPLAIN }, + { "RAISE", "TK_RAISE", TRIGGER }, + { "REFERENCES", "TK_REFERENCES", FKEY }, + { "REGEXP", "TK_LIKE_KW", ALWAYS }, + { "REINDEX", "TK_REINDEX", REINDEX }, + { "RELEASE", "TK_RELEASE", ALWAYS }, + { "RENAME", "TK_RENAME", ALTER }, + { "REPLACE", "TK_REPLACE", CONFLICT }, + { "RESTRICT", "TK_RESTRICT", FKEY }, + { "RIGHT", "TK_JOIN_KW", ALWAYS }, + { "ROLLBACK", "TK_ROLLBACK", ALWAYS }, + { "ROW", "TK_ROW", TRIGGER }, + { "SAVEPOINT", "TK_SAVEPOINT", ALWAYS }, + { "SELECT", "TK_SELECT", ALWAYS }, + { "SET", "TK_SET", ALWAYS }, + { "TABLE", "TK_TABLE", ALWAYS }, + { "TEMP", "TK_TEMP", ALWAYS }, + { "TEMPORARY", "TK_TEMP", ALWAYS }, + { "THEN", "TK_THEN", ALWAYS }, + { "TO", "TK_TO", ALWAYS }, + { "TRANSACTION", "TK_TRANSACTION", ALWAYS }, + { "TRIGGER", "TK_TRIGGER", TRIGGER }, + { "UNION", "TK_UNION", COMPOUND }, + { "UNIQUE", "TK_UNIQUE", ALWAYS }, + { "UPDATE", "TK_UPDATE", ALWAYS }, + { "USING", "TK_USING", ALWAYS }, + { "VACUUM", "TK_VACUUM", VACUUM }, + { "VALUES", "TK_VALUES", ALWAYS }, + { "VIEW", "TK_VIEW", VIEW }, + { "VIRTUAL", "TK_VIRTUAL", VTAB }, + { "WHEN", "TK_WHEN", ALWAYS }, + { "WHERE", "TK_WHERE", ALWAYS }, +}; + +/* Number of keywords */ +static int nKeyword = (sizeof(aKeywordTable)/sizeof(aKeywordTable[0])); + +/* An array to map all upper-case characters into their corresponding +** lower-case character. +*/ +const unsigned char sqlite3UpperToLower[] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, + 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, + 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, + 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, + 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, + 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, + 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, + 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, + 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, + 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, + 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, + 252,253,254,255 +}; +#define UpperToLower sqlite3UpperToLower + +/* +** Comparision function for two Keyword records +*/ +static int keywordCompare1(const void *a, const void *b){ + const Keyword *pA = (Keyword*)a; + const Keyword *pB = (Keyword*)b; + int n = pA->len - pB->len; + if( n==0 ){ + n = strcmp(pA->zName, pB->zName); + } + assert( n!=0 ); + return n; +} +static int keywordCompare2(const void *a, const void *b){ + const Keyword *pA = (Keyword*)a; + const Keyword *pB = (Keyword*)b; + int n = pB->longestSuffix - pA->longestSuffix; + if( n==0 ){ + n = strcmp(pA->zName, pB->zName); + } + assert( n!=0 ); + return n; +} +static int keywordCompare3(const void *a, const void *b){ + const Keyword *pA = (Keyword*)a; + const Keyword *pB = (Keyword*)b; + int n = pA->offset - pB->offset; + if( n==0 ) n = pB->id - pA->id; + assert( n!=0 ); + return n; +} + +/* +** Return a KeywordTable entry with the given id +*/ +static Keyword *findById(int id){ + int i; + for(i=0; ilen = (int)strlen(p->zName); + assert( p->lenzOrigName) ); + strcpy(p->zOrigName, p->zName); + totalLen += p->len; + p->hash = (UpperToLower[(int)p->zName[0]]*4) ^ + (UpperToLower[(int)p->zName[p->len-1]]*3) ^ p->len; + p->id = i+1; + } + + /* Sort the table from shortest to longest keyword */ + qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare1); + + /* Look for short keywords embedded in longer keywords */ + for(i=nKeyword-2; i>=0; i--){ + Keyword *p = &aKeywordTable[i]; + for(j=nKeyword-1; j>i && p->substrId==0; j--){ + Keyword *pOther = &aKeywordTable[j]; + if( pOther->substrId ) continue; + if( pOther->len<=p->len ) continue; + for(k=0; k<=pOther->len-p->len; k++){ + if( memcmp(p->zName, &pOther->zName[k], p->len)==0 ){ + p->substrId = pOther->id; + p->substrOffset = k; + break; + } + } + } + } + + /* Compute the longestSuffix value for every word */ + for(i=0; isubstrId ) continue; + for(j=0; jsubstrId ) continue; + for(k=p->longestSuffix+1; klen && klen; k++){ + if( memcmp(&p->zName[p->len-k], pOther->zName, k)==0 ){ + p->longestSuffix = k; + } + } + } + } + + /* Sort the table into reverse order by length */ + qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare2); + + /* Fill in the offset for all entries */ + nChar = 0; + for(i=0; ioffset>0 || p->substrId ) continue; + p->offset = nChar; + nChar += p->len; + for(k=p->len-1; k>=1; k--){ + for(j=i+1; joffset>0 || pOther->substrId ) continue; + if( pOther->len<=k ) continue; + if( memcmp(&p->zName[p->len-k], pOther->zName, k)==0 ){ + p = pOther; + p->offset = nChar - k; + nChar = p->offset + p->len; + p->zName += k; + p->len -= k; + p->prefix = k; + j = i; + k = p->len; + } + } + } + } + for(i=0; isubstrId ){ + p->offset = findById(p->substrId)->offset + p->substrOffset; + } + } + + /* Sort the table by offset */ + qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare3); + + /* Figure out how big to make the hash table in order to minimize the + ** number of collisions */ + bestSize = nKeyword; + bestCount = nKeyword*nKeyword; + for(i=nKeyword/2; i<=2*nKeyword; i++){ + for(j=0; jsubstrId ) continue; + memcpy(&zText[k], p->zName, p->len); + k += p->len; + if( j+p->len>70 ){ + printf("%*s */\n", 74-j, ""); + j = 0; + } + if( j==0 ){ + printf(" /* "); + j = 8; + } + printf("%s", p->zName); + j += p->len; + } + if( j>0 ){ + printf("%*s */\n", 74-j, ""); + } + printf(" static const char zText[%d] = {\n", nChar); + zText[nChar] = 0; + for(i=j=0; i68 ){ + printf("\n"); + j = 0; + } + } + if( j>0 ) printf("\n"); + printf(" };\n"); + + printf(" static const unsigned char aHash[%d] = {\n", bestSize); + for(i=j=0; i12 ){ + printf("\n"); + j = 0; + } + } + printf("%s };\n", j==0 ? "" : "\n"); + + printf(" static const unsigned char aNext[%d] = {\n", nKeyword); + for(i=j=0; i12 ){ + printf("\n"); + j = 0; + } + } + printf("%s };\n", j==0 ? "" : "\n"); + + printf(" static const unsigned char aLen[%d] = {\n", nKeyword); + for(i=j=0; i12 ){ + printf("\n"); + j = 0; + } + } + printf("%s };\n", j==0 ? "" : "\n"); + + printf(" static const unsigned short int aOffset[%d] = {\n", nKeyword); + for(i=j=0; i12 ){ + printf("\n"); + j = 0; + } + } + printf("%s };\n", j==0 ? "" : "\n"); + + printf(" static const unsigned char aCode[%d] = {\n", nKeyword); + for(i=j=0; i=5 ){ + printf("\n"); + j = 0; + } + } + printf("%s };\n", j==0 ? "" : "\n"); + + printf(" int h, i;\n"); + printf(" if( n<2 ) return TK_ID;\n"); + printf(" h = ((charMap(z[0])*4) ^\n" + " (charMap(z[n-1])*3) ^\n" + " n) %% %d;\n", bestSize); + printf(" for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){\n"); + printf(" if( aLen[i]==n &&" + " sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){\n"); + for(i=0; i0} {puts {}} + set col 0 +} + +foreach name [lsort $namelist] { + put_item \"$name\", +} +put_item 0 +finalize +puts " \175;" +puts " enum ${prefix}_enum \173" +foreach name [lsort $namelist] { + regsub -all {@} $name {} name + put_item ${prefix}_[string toupper $name], +} +finalize +puts " \175;" diff --git a/components/external/SQLite-3.8.1/tool/mkpragmatab.tcl b/components/external/SQLite-3.8.1/tool/mkpragmatab.tcl new file mode 100644 index 0000000000000000000000000000000000000000..1ba0bd6be966e0f269fe793c85fc8bd3e1c50a7c --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/mkpragmatab.tcl @@ -0,0 +1,393 @@ +#!/usr/bin/tclsh +# +# Run this script to generate the pragma name lookup table C code. +# +# To add new pragmas, first add the name and other relevant attributes +# of the pragma to the "pragma_def" object below. Then run this script +# to generate the C-code for the lookup table and copy/paste the output +# of this script into the appropriate spot in the pragma.c source file. +# Then add the extra "case PragTyp_XXXXX:" and subsequent code for the +# new pragma. +# + +set pragma_def { + NAME: full_column_names + TYPE: FLAG + ARG: SQLITE_FullColNames + + NAME: short_column_names + TYPE: FLAG + ARG: SQLITE_ShortColNames + + NAME: count_changes + TYPE: FLAG + ARG: SQLITE_CountRows + + NAME: empty_result_callbacks + TYPE: FLAG + ARG: SQLITE_NullCallback + + NAME: legacy_file_format + TYPE: FLAG + ARG: SQLITE_LegacyFileFmt + + NAME: fullfsync + TYPE: FLAG + ARG: SQLITE_FullFSync + + NAME: checkpoint_fullfsync + TYPE: FLAG + ARG: SQLITE_CkptFullFSync + + NAME: cache_spill + TYPE: FLAG + ARG: SQLITE_CacheSpill + + NAME: reverse_unordered_selects + TYPE: FLAG + ARG: SQLITE_ReverseOrder + + NAME: query_only + TYPE: FLAG + ARG: SQLITE_QueryOnly + + NAME: automatic_index + TYPE: FLAG + ARG: SQLITE_AutoIndex + IF: !defined(SQLITE_OMIT_AUTOMATIC_INDEX) + + NAME: sql_trace + TYPE: FLAG + ARG: SQLITE_SqlTrace + IF: defined(SQLITE_DEBUG) + + NAME: vdbe_listing + TYPE: FLAG + ARG: SQLITE_VdbeListing + IF: defined(SQLITE_DEBUG) + + NAME: vdbe_trace + TYPE: FLAG + ARG: SQLITE_VdbeTrace + IF: defined(SQLITE_DEBUG) + + NAME: vdbe_addoptrace + TYPE: FLAG + ARG: SQLITE_VdbeAddopTrace + IF: defined(SQLITE_DEBUG) + + NAME: vdbe_debug + TYPE: FLAG + ARG: SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace + IF: defined(SQLITE_DEBUG) + + NAME: ignore_check_constraints + TYPE: FLAG + ARG: SQLITE_IgnoreChecks + IF: !defined(SQLITE_OMIT_CHECK) + + NAME: writable_schema + TYPE: FLAG + ARG: SQLITE_WriteSchema|SQLITE_RecoveryMode + + NAME: read_uncommitted + TYPE: FLAG + ARG: SQLITE_ReadUncommitted + + NAME: recursive_triggers + TYPE: FLAG + ARG: SQLITE_RecTriggers + + NAME: foreign_keys + TYPE: FLAG + ARG: SQLITE_ForeignKeys + IF: !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + + NAME: defer_foreign_keys + TYPE: FLAG + ARG: SQLITE_DeferFKs + IF: !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + + NAME: default_cache_size + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) + + NAME: page_size + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: secure_delete + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: page_count + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: max_page_count + TYPE: PAGE_COUNT + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: locking_mode + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: journal_mode + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: journal_size_limit + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: cache_size + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: mmap_size + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: auto_vacuum + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_AUTOVACUUM) + + NAME: incremental_vacuum + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_AUTOVACUUM) + + NAME: temp_store + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: temp_store_directory + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: data_store_directory + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN + + NAME: lock_proxy_file + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE + + NAME: synchronous + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) + + NAME: table_info + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + + NAME: stats + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + + NAME: index_info + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + + NAME: index_list + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + + NAME: database_list + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + + NAME: collation_list + IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) + + NAME: foreign_key_list + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_FOREIGN_KEY) + + NAME: foreign_key_check + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) + + NAME: parser_trace + IF: defined(SQLITE_DEBUG) + + NAME: case_sensitive_like + + NAME: integrity_check + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_INTEGRITY_CHECK) + + NAME: quick_check + TYPE: INTEGRITY_CHECK + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_INTEGRITY_CHECK) + + NAME: encoding + IF: !defined(SQLITE_OMIT_UTF16) + + NAME: schema_version + TYPE: HEADER_VALUE + IF: !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + + NAME: user_version + TYPE: HEADER_VALUE + IF: !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + + NAME: freelist_count + TYPE: HEADER_VALUE + IF: !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + + NAME: application_id + TYPE: HEADER_VALUE + IF: !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) + + NAME: compile_options + IF: !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS) + + NAME: wal_checkpoint + FLAG: NeedSchema + IF: !defined(SQLITE_OMIT_WAL) + + NAME: wal_autocheckpoint + IF: !defined(SQLITE_OMIT_WAL) + + NAME: shrink_memory + + NAME: busy_timeout + + NAME: lock_status + IF: defined(SQLITE_DEBUG) || defined(SQLITE_TEST) + + NAME: key + IF: defined(SQLITE_HAS_CODEC) + + NAME: rekey + IF: defined(SQLITE_HAS_CODEC) + + NAME: hexkey + IF: defined(SQLITE_HAS_CODEC) + + NAME: hexrekey + TYPE: HEXKEY + IF: defined(SQLITE_HAS_CODEC) + + NAME: activate_extensions + IF: defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) + + NAME: soft_heap_limit +} +set name {} +set type {} +set if {} +set flags {} +set arg 0 +proc record_one {} { + global name type if arg allbyname typebyif flags + if {$name==""} return + set allbyname($name) [list $type $arg $if $flags] + set name {} + set type {} + set if {} + set flags {} + set arg 0 +} +foreach line [split $pragma_def \n] { + set line [string trim $line] + if {$line==""} continue + foreach {id val} [split $line :] break + set val [string trim $val] + if {$id=="NAME"} { + record_one + set name $val + set type [string toupper $val] + } elseif {$id=="TYPE"} { + set type $val + } elseif {$id=="ARG"} { + set arg $val + } elseif {$id=="IF"} { + set if $val + } elseif {$id=="FLAG"} { + foreach term [split $val] { + lappend flags $term + set allflags($term) 1 + } + } else { + error "bad pragma_def line: $line" + } +} +record_one +set allnames [lsort [array names allbyname]] + +# Generate #defines for all pragma type names. Group the pragmas that are +# omit in default builds (defined(SQLITE_DEBUG) and defined(SQLITE_HAS_CODEC)) +# at the end. +# +set pnum 0 +foreach name $allnames { + set type [lindex $allbyname($name) 0] + if {[info exists seentype($type)]} continue + set if [lindex $allbyname($name) 2] + if {[regexp SQLITE_DEBUG $if] || [regexp SQLITE_HAS_CODEC $if]} continue + set seentype($type) 1 + puts [format {#define %-35s %4d} PragTyp_$type $pnum] + incr pnum +} +foreach name $allnames { + set type [lindex $allbyname($name) 0] + if {[info exists seentype($type)]} continue + set if [lindex $allbyname($name) 2] + if {[regexp SQLITE_DEBUG $if]} continue + set seentype($type) 1 + puts [format {#define %-35s %4d} PragTyp_$type $pnum] + incr pnum +} +foreach name $allnames { + set type [lindex $allbyname($name) 0] + if {[info exists seentype($type)]} continue + set seentype($type) 1 + puts [format {#define %-35s %4d} PragTyp_$type $pnum] + incr pnum +} + +# Generate #defines for flags +# +set fv 1 +foreach f [lsort [array names allflags]] { + puts [format {#define PragFlag_%-20s 0x%02x} $f $fv] + set fv [expr {$fv*2}] +} + +# Generate the lookup table +# +puts "static const struct sPragmaNames \173" +puts " const char *const zName; /* Name of pragma */" +puts " u8 ePragTyp; /* PragTyp_XXX value */" +puts " u8 mPragFlag; /* Zero or more PragFlag_XXX values */" +puts " u32 iArg; /* Extra argument */" +puts "\175 aPragmaNames\[\] = \173" + +set current_if {} +set spacer [format { %26s } {}] +foreach name $allnames { + foreach {type arg if flag} $allbyname($name) break + if {$if!=$current_if} { + if {$current_if!=""} {puts "#endif"} + set current_if $if + if {$current_if!=""} {puts "#if $current_if"} + } + set typex [format PragTyp_%-23s $type,] + if {$flag==""} { + set flagx "0" + } else { + set flagx PragFlag_[join $flag {|PragFlag_}] + } + puts " \173 /* zName: */ \"$name\"," + puts " /* ePragTyp: */ PragTyp_$type," + puts " /* ePragFlag: */ $flagx," + puts " /* iArg: */ $arg \175," +} +if {$current_if!=""} {puts "#endif"} +puts "\175;" + +# count the number of pragmas, for information purposes +# +set allcnt 0 +set dfltcnt 0 +foreach name $allnames { + incr allcnt + set if [lindex $allbyname($name) 2] + if {[regexp {^defined} $if] || [regexp {[^!]defined} $if]} continue + incr dfltcnt +} +puts "/* Number of pragmas: $dfltcnt on by default, $allcnt total. */" diff --git a/components/external/SQLite-3.8.1/tool/mkspeedsql.tcl b/components/external/SQLite-3.8.1/tool/mkspeedsql.tcl new file mode 100644 index 0000000000000000000000000000000000000000..04bafc04c1b99a73c7d88f1bb8e535d90f7e1e08 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/mkspeedsql.tcl @@ -0,0 +1,237 @@ +# 2008 October 9 +# +# The author disclaims copyright to this source code. In place of +# a legal notice, here is a blessing: +# +# May you do good and not evil. +# May you find forgiveness for yourself and forgive others. +# May you share freely, never taking more than you give. +# +#************************************************************************* +# This file generates SQL text used for performance testing. +# +# $Id: mkspeedsql.tcl,v 1.1 2008/10/09 17:57:34 drh Exp $ +# + +# Set a uniform random seed +expr srand(0) + +# The number_name procedure below converts its argment (an integer) +# into a string which is the English-language name for that number. +# +# Example: +# +# puts [number_name 123] -> "one hundred twenty three" +# +set ones {zero one two three four five six seven eight nine + ten eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen} +set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} +proc number_name {n} { + if {$n>=1000} { + set txt "[number_name [expr {$n/1000}]] thousand" + set n [expr {$n%1000}] + } else { + set txt {} + } + if {$n>=100} { + append txt " [lindex $::ones [expr {$n/100}]] hundred" + set n [expr {$n%100}] + } + if {$n>=20} { + append txt " [lindex $::tens [expr {$n/10}]]" + set n [expr {$n%10}] + } + if {$n>0} { + append txt " [lindex $::ones $n]" + } + set txt [string trim $txt] + if {$txt==""} {set txt zero} + return $txt +} + +# Create a database schema. +# +puts { + PRAGMA page_size=1024; + PRAGMA cache_size=8192; + PRAGMA locking_mode=EXCLUSIVE; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); + CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT); + CREATE INDEX i2a ON t2(a); + CREATE INDEX i2b ON t2(b); + SELECT name FROM sqlite_master ORDER BY 1; +} + + +# 50000 INSERTs on an unindexed table +# +set t1c_list {} +puts {BEGIN;} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + set x [number_name $r] + lappend t1c_list $x + puts "INSERT INTO t1 VALUES($i,$r,'$x');" +} +puts {COMMIT;} + +# 50000 INSERTs on an indexed table +# +puts {BEGIN;} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + puts "INSERT INTO t2 VALUES($i,$r,'[number_name $r]');" +} +puts {COMMIT;} + + +# 50 SELECTs on an integer comparison. There is no index so +# a full table scan is required. +# +for {set i 0} {$i<50} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + puts "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" +} + +# 50 SELECTs on an LIKE comparison. There is no index so a full +# table scan is required. +# +for {set i 0} {$i<50} {incr i} { + puts "SELECT count(*), avg(b) FROM t1 WHERE c LIKE '%[number_name $i]%';" +} + +# Create indices +# +puts {BEGIN;} +puts { + CREATE INDEX i1a ON t1(a); + CREATE INDEX i1b ON t1(b); + CREATE INDEX i1c ON t1(c); +} +puts {COMMIT;} + +# 5000 SELECTs on an integer comparison where the integer is +# indexed. +# +set sql {} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*100}] + set upr [expr {($i+10)*100}] + puts "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" +} + +# 100000 random SELECTs against rowid. +# +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + puts "SELECT c FROM t1 WHERE rowid=$id;" +} + +# 100000 random SELECTs against a unique indexed column. +# +for {set i 1} {$i<=100000} {incr i} { + set id [expr {int(rand()*50000)+1}] + puts "SELECT c FROM t1 WHERE a=$id;" +} + +# 50000 random SELECTs against an indexed column text column +# +set nt1c [llength $t1c_list] +for {set i 0} {$i<50000} {incr i} { + set r [expr {int(rand()*$nt1c)}] + set c [lindex $t1c_list $i] + puts "SELECT c FROM t1 WHERE c='$c';" +} + + +# Vacuum +puts {VACUUM;} + +# 5000 updates of ranges where the field being compared is indexed. +# +puts {BEGIN;} +for {set i 0} {$i<5000} {incr i} { + set lwr [expr {$i*2}] + set upr [expr {($i+1)*2}] + puts "UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr;" +} +puts {COMMIT;} + +# 50000 single-row updates. An index is used to find the row quickly. +# +puts {BEGIN;} +for {set i 0} {$i<50000} {incr i} { + set r [expr {int(rand()*500000)}] + puts "UPDATE t1 SET b=$r WHERE a=$i;" +} +puts {COMMIT;} + +# 1 big text update that touches every row in the table. +# +puts { + UPDATE t1 SET c=a; +} + +# Many individual text updates. Each row in the table is +# touched through an index. +# +puts {BEGIN;} +for {set i 1} {$i<=50000} {incr i} { + set r [expr {int(rand()*500000)}] + puts "UPDATE t1 SET c='[number_name $r]' WHERE a=$i;" +} +puts {COMMIT;} + +# Delete all content in a table. +# +puts {DELETE FROM t1;} + +# Copy one table into another +# +puts {INSERT INTO t1 SELECT * FROM t2;} + +# Delete all content in a table, one row at a time. +# +puts {DELETE FROM t1 WHERE 1;} + +# Refill the table yet again +# +puts {INSERT INTO t1 SELECT * FROM t2;} + +# Drop the table and recreate it without its indices. +# +puts {BEGIN;} +puts { + DROP TABLE t1; + CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); +} +puts {COMMIT;} + +# Refill the table yet again. This copy should be faster because +# there are no indices to deal with. +# +puts {INSERT INTO t1 SELECT * FROM t2;} + +# Select 20000 rows from the table at random. +# +puts { + SELECT rowid FROM t1 ORDER BY random() LIMIT 20000; +} + +# Delete 20000 random rows from the table. +# +puts { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000); +} +puts {SELECT count(*) FROM t1;} + +# Delete 20000 more rows at random from the table. +# +puts { + DELETE FROM t1 WHERE rowid IN + (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000); +} +puts {SELECT count(*) FROM t1;} diff --git a/components/external/SQLite-3.8.1/tool/mksqlite3c-noext.tcl b/components/external/SQLite-3.8.1/tool/mksqlite3c-noext.tcl new file mode 100644 index 0000000000000000000000000000000000000000..017ad6292fc95fdd1f8ef7da31540f89dc6297c4 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/mksqlite3c-noext.tcl @@ -0,0 +1,305 @@ +#!/usr/bin/tclsh +# +# To build a single huge source file holding all of SQLite (or at +# least the core components - the test harness, shell, and TCL +# interface are omitted.) first do +# +# make target_source +# +# The make target above moves all of the source code files into +# a subdirectory named "tsrc". (This script expects to find the files +# there and will not work if they are not found.) There are a few +# generated C code files that are also added to the tsrc directory. +# For example, the "parse.c" and "parse.h" files to implement the +# the parser are derived from "parse.y" using lemon. And the +# "keywordhash.h" files is generated by a program named "mkkeywordhash". +# +# After the "tsrc" directory has been created and populated, run +# this script: +# +# tclsh mksqlite3c.tcl +# +# The amalgamated SQLite code will be written into sqlite3.c +# + +# Begin by reading the "sqlite3.h" header file. Extract the version number +# from in this file. The versioon number is needed to generate the header +# comment of the amalgamation. +# +if {[lsearch $argv --nostatic]>=0} { + set addstatic 0 +} else { + set addstatic 1 +} +if {[lsearch $argv --linemacros]>=0} { + set linemacros 1 +} else { + set linemacros 0 +} +set in [open tsrc/sqlite3.h] +set cnt 0 +set VERSION ????? +while {![eof $in]} { + set line [gets $in] + if {$line=="" && [eof $in]} break + incr cnt + regexp {#define\s+SQLITE_VERSION\s+"(.*)"} $line all VERSION +} +close $in + +# Open the output file and write a header comment at the beginning +# of the file. +# +set out [open sqlite3.c w] +# Force the output to use unix line endings, even on Windows. +fconfigure $out -translation lf +set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1] +puts $out [subst \ +{/****************************************************************************** +** This file is an amalgamation of many separate C source files from SQLite +** version $VERSION. By combining all the individual C code files into this +** single large file, the entire code can be compiled as a single translation +** unit. This allows many compilers to do optimizations that would not be +** possible if the files were compiled separately. Performance improvements +** of 5% or more are commonly seen when SQLite is compiled as a single +** translation unit. +** +** This file is all you need to compile SQLite. To use SQLite in other +** programs, you need this file and the "sqlite3.h" header file that defines +** the programming interface to the SQLite library. (If you do not have +** the "sqlite3.h" header file at hand, you will find a copy embedded within +** the text of this file. Search for "Begin file sqlite3.h" to find the start +** of the embedded sqlite3.h header file.) Additional code files may be needed +** if you want a wrapper to interface SQLite with your choice of programming +** language. The code for the "sqlite3" command-line shell is also in a +** separate file. This file contains only code for the core SQLite library. +*/ +#define SQLITE_CORE 1 +#define SQLITE_AMALGAMATION 1}] +if {$addstatic} { + puts $out \ +{#ifndef SQLITE_PRIVATE +# define SQLITE_PRIVATE static +#endif +#ifndef SQLITE_API +# define SQLITE_API +#endif} +} + +# These are the header files used by SQLite. The first time any of these +# files are seen in a #include statement in the C code, include the complete +# text of the file in-line. The file only needs to be included once. +# +foreach hdr { + btree.h + btreeInt.h + hash.h + hwtime.h + keywordhash.h + mutex.h + opcodes.h + os_common.h + os.h + pager.h + parse.h + pcache.h + sqlite3ext.h + sqlite3.h + sqliteicu.h + sqliteInt.h + sqliteLimit.h + vdbe.h + vdbeInt.h + wal.h +} { + set available_hdr($hdr) 1 +} +set available_hdr(sqliteInt.h) 0 + +# 78 stars used for comment formatting. +set s78 \ +{*****************************************************************************} + +# Insert a comment into the code +# +proc section_comment {text} { + global out s78 + set n [string length $text] + set nstar [expr {60 - $n}] + set stars [string range $s78 0 $nstar] + puts $out "/************** $text $stars/" +} + +# Read the source file named $filename and write it into the +# sqlite3.c output file. If any #include statements are seen, +# process them approprately. +# +proc copy_file {filename} { + global seen_hdr available_hdr out addstatic linemacros + set ln 0 + set tail [file tail $filename] + section_comment "Begin file $tail" + if {$linemacros} {puts $out "#line 1 \"$filename\""} + set in [open $filename r] + set varpattern {^[a-zA-Z][a-zA-Z_0-9 *]+(sqlite3[_a-zA-Z0-9]+)(\[|;| =)} + set declpattern {[a-zA-Z][a-zA-Z_0-9 ]+ \**(sqlite3[_a-zA-Z0-9]+)\(} + if {[file extension $filename]==".h"} { + set declpattern " *$declpattern" + } + set declpattern ^$declpattern + while {![eof $in]} { + set line [gets $in] + incr ln + if {[regexp {^\s*#\s*include\s+["<]([^">]+)[">]} $line all hdr]} { + if {[info exists available_hdr($hdr)]} { + if {$available_hdr($hdr)} { + if {$hdr!="os_common.h" && $hdr!="hwtime.h"} { + set available_hdr($hdr) 0 + } + section_comment "Include $hdr in the middle of $tail" + copy_file tsrc/$hdr + section_comment "Continuing where we left off in $tail" + if {$linemacros} {puts $out "#line [expr {$ln+1}] \"$filename\""} + } + } elseif {![info exists seen_hdr($hdr)]} { + set seen_hdr($hdr) 1 + puts $out $line + } else { + puts $out "/* $line */" + } + } elseif {[regexp {^#ifdef __cplusplus} $line]} { + puts $out "#if 0" + } elseif {!$linemacros && [regexp {^#line} $line]} { + # Skip #line directives. + } elseif {$addstatic && ![regexp {^(static|typedef)} $line]} { + regsub {^SQLITE_API } $line {} line + if {[regexp $declpattern $line all funcname]} { + # Add the SQLITE_PRIVATE or SQLITE_API keyword before functions. + # so that linkage can be modified at compile-time. + if {[regexp {^sqlite3_} $funcname]} { + puts $out "SQLITE_API $line" + } else { + puts $out "SQLITE_PRIVATE $line" + } + } elseif {[regexp $varpattern $line all varname]} { + # Add the SQLITE_PRIVATE before variable declarations or + # definitions for internal use + if {![regexp {^sqlite3_} $varname]} { + regsub {^extern } $line {} line + puts $out "SQLITE_PRIVATE $line" + } else { + if {[regexp {const char sqlite3_version\[\];} $line]} { + set line {const char sqlite3_version[] = SQLITE_VERSION;} + } + regsub {^SQLITE_EXTERN } $line {} line + puts $out "SQLITE_API $line" + } + } elseif {[regexp {^(SQLITE_EXTERN )?void \(\*sqlite3IoTrace\)} $line]} { + regsub {^SQLITE_EXTERN } $line {} line + puts $out "SQLITE_PRIVATE $line" + } elseif {[regexp {^void \(\*sqlite3Os} $line]} { + puts $out "SQLITE_PRIVATE $line" + } else { + puts $out $line + } + } else { + puts $out $line + } + } + close $in + section_comment "End of $tail" +} + + +# Process the source files. Process files containing commonly +# used subroutines first in order to help the compiler find +# inlining opportunities. +# +foreach file { + sqliteInt.h + + global.c + ctime.c + status.c + date.c + os.c + + fault.c + mem0.c + mem1.c + mem2.c + mem3.c + mem5.c + mutex.c + mutex_noop.c + mutex_unix.c + mutex_w32.c + malloc.c + printf.c + random.c + utf.c + util.c + hash.c + opcodes.c + + os_unix.c + os_win.c + + bitvec.c + pcache.c + pcache1.c + rowset.c + pager.c + wal.c + + btmutex.c + btree.c + backup.c + + vdbemem.c + vdbeaux.c + vdbeapi.c + vdbetrace.c + vdbe.c + vdbeblob.c + vdbesort.c + journal.c + memjournal.c + + walker.c + resolve.c + expr.c + alter.c + analyze.c + attach.c + auth.c + build.c + callback.c + delete.c + func.c + fkey.c + insert.c + legacy.c + loadext.c + pragma.c + prepare.c + select.c + table.c + trigger.c + update.c + vacuum.c + vtab.c + where.c + + parse.c + + tokenize.c + complete.c + + main.c + notify.c +} { + copy_file tsrc/$file +} + +close $out diff --git a/components/external/SQLite-3.8.1/tool/mksqlite3c.tcl b/components/external/SQLite-3.8.1/tool/mksqlite3c.tcl new file mode 100644 index 0000000000000000000000000000000000000000..4b01a34f746bfba7ba268002365d62238e5929c8 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/mksqlite3c.tcl @@ -0,0 +1,333 @@ +#!/usr/bin/tclsh +# +# To build a single huge source file holding all of SQLite (or at +# least the core components - the test harness, shell, and TCL +# interface are omitted.) first do +# +# make target_source +# +# The make target above moves all of the source code files into +# a subdirectory named "tsrc". (This script expects to find the files +# there and will not work if they are not found.) There are a few +# generated C code files that are also added to the tsrc directory. +# For example, the "parse.c" and "parse.h" files to implement the +# the parser are derived from "parse.y" using lemon. And the +# "keywordhash.h" files is generated by a program named "mkkeywordhash". +# +# After the "tsrc" directory has been created and populated, run +# this script: +# +# tclsh mksqlite3c.tcl +# +# The amalgamated SQLite code will be written into sqlite3.c +# + +# Begin by reading the "sqlite3.h" header file. Extract the version number +# from in this file. The version number is needed to generate the header +# comment of the amalgamation. +# +if {[lsearch $argv --nostatic]>=0} { + set addstatic 0 +} else { + set addstatic 1 +} +if {[lsearch $argv --linemacros]>=0} { + set linemacros 1 +} else { + set linemacros 0 +} +set in [open tsrc/sqlite3.h] +set cnt 0 +set VERSION ????? +while {![eof $in]} { + set line [gets $in] + if {$line=="" && [eof $in]} break + incr cnt + regexp {#define\s+SQLITE_VERSION\s+"(.*)"} $line all VERSION +} +close $in + +# Open the output file and write a header comment at the beginning +# of the file. +# +set out [open sqlite3.c w] +# Force the output to use unix line endings, even on Windows. +fconfigure $out -translation lf +set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1] +puts $out [subst \ +{/****************************************************************************** +** This file is an amalgamation of many separate C source files from SQLite +** version $VERSION. By combining all the individual C code files into this +** single large file, the entire code can be compiled as a single translation +** unit. This allows many compilers to do optimizations that would not be +** possible if the files were compiled separately. Performance improvements +** of 5% or more are commonly seen when SQLite is compiled as a single +** translation unit. +** +** This file is all you need to compile SQLite. To use SQLite in other +** programs, you need this file and the "sqlite3.h" header file that defines +** the programming interface to the SQLite library. (If you do not have +** the "sqlite3.h" header file at hand, you will find a copy embedded within +** the text of this file. Search for "Begin file sqlite3.h" to find the start +** of the embedded sqlite3.h header file.) Additional code files may be needed +** if you want a wrapper to interface SQLite with your choice of programming +** language. The code for the "sqlite3" command-line shell is also in a +** separate file. This file contains only code for the core SQLite library. +*/ +#define SQLITE_CORE 1 +#define SQLITE_AMALGAMATION 1}] +if {$addstatic} { + puts $out \ +{#ifndef SQLITE_PRIVATE +# define SQLITE_PRIVATE static +#endif +#ifndef SQLITE_API +# define SQLITE_API +#endif} +} + +# These are the header files used by SQLite. The first time any of these +# files are seen in a #include statement in the C code, include the complete +# text of the file in-line. The file only needs to be included once. +# +foreach hdr { + btree.h + btreeInt.h + fts3.h + fts3Int.h + fts3_hash.h + fts3_tokenizer.h + hash.h + hwtime.h + keywordhash.h + mutex.h + opcodes.h + os_common.h + os.h + pager.h + parse.h + pcache.h + rtree.h + sqlite3ext.h + sqlite3.h + sqliteicu.h + sqliteInt.h + sqliteLimit.h + vdbe.h + vdbeInt.h + wal.h +} { + set available_hdr($hdr) 1 +} +set available_hdr(sqliteInt.h) 0 +set available_hdr(sqlite3.h) 0 + +# 78 stars used for comment formatting. +set s78 \ +{*****************************************************************************} + +# Insert a comment into the code +# +proc section_comment {text} { + global out s78 + set n [string length $text] + set nstar [expr {60 - $n}] + set stars [string range $s78 0 $nstar] + puts $out "/************** $text $stars/" +} + +# Read the source file named $filename and write it into the +# sqlite3.c output file. If any #include statements are seen, +# process them appropriately. +# +proc copy_file {filename} { + global seen_hdr available_hdr out addstatic linemacros + set ln 0 + set tail [file tail $filename] + section_comment "Begin file $tail" + if {$linemacros} {puts $out "#line 1 \"$filename\""} + set in [open $filename r] + set varpattern {^[a-zA-Z][a-zA-Z_0-9 *]+(sqlite3[_a-zA-Z0-9]+)(\[|;| =)} + set declpattern {[a-zA-Z][a-zA-Z_0-9 ]+ \**(sqlite3[_a-zA-Z0-9]+)\(} + if {[file extension $filename]==".h"} { + set declpattern " *$declpattern" + } + set declpattern ^$declpattern + while {![eof $in]} { + set line [gets $in] + incr ln + if {[regexp {^\s*#\s*include\s+["<]([^">]+)[">]} $line all hdr]} { + if {[info exists available_hdr($hdr)]} { + if {$available_hdr($hdr)} { + if {$hdr!="os_common.h" && $hdr!="hwtime.h"} { + set available_hdr($hdr) 0 + } + section_comment "Include $hdr in the middle of $tail" + copy_file tsrc/$hdr + section_comment "Continuing where we left off in $tail" + if {$linemacros} {puts $out "#line [expr {$ln+1}] \"$filename\""} + } + } elseif {![info exists seen_hdr($hdr)]} { + set seen_hdr($hdr) 1 + puts $out $line + } elseif {[regexp {/\*\s+amalgamator:\s+keep\s+\*/} $line]} { + # This include file must be kept because there was a "keep" + # directive inside of a line comment. + puts $out $line + } else { + # Comment out the entire line, replacing any nested comment + # begin/end markers with the harmless substring "**". + puts $out "/* [string map [list /* ** */ **] $line] */" + } + } elseif {[regexp {^#ifdef __cplusplus} $line]} { + puts $out "#if 0" + } elseif {!$linemacros && [regexp {^#line} $line]} { + # Skip #line directives. + } elseif {$addstatic && ![regexp {^(static|typedef)} $line]} { + regsub {^SQLITE_API } $line {} line + if {[regexp $declpattern $line all funcname]} { + # Add the SQLITE_PRIVATE or SQLITE_API keyword before functions. + # so that linkage can be modified at compile-time. + if {[regexp {^sqlite3_} $funcname]} { + puts $out "SQLITE_API $line" + } else { + puts $out "SQLITE_PRIVATE $line" + } + } elseif {[regexp $varpattern $line all varname]} { + # Add the SQLITE_PRIVATE before variable declarations or + # definitions for internal use + if {![regexp {^sqlite3_} $varname]} { + regsub {^extern } $line {} line + puts $out "SQLITE_PRIVATE $line" + } else { + if {[regexp {const char sqlite3_version\[\];} $line]} { + set line {const char sqlite3_version[] = SQLITE_VERSION;} + } + regsub {^SQLITE_EXTERN } $line {} line + puts $out "SQLITE_API $line" + } + } elseif {[regexp {^(SQLITE_EXTERN )?void \(\*sqlite3IoTrace\)} $line]} { + regsub {^SQLITE_EXTERN } $line {} line + puts $out "SQLITE_PRIVATE $line" + } elseif {[regexp {^void \(\*sqlite3Os} $line]} { + puts $out "SQLITE_PRIVATE $line" + } else { + puts $out $line + } + } else { + puts $out $line + } + } + close $in + section_comment "End of $tail" +} + + +# Process the source files. Process files containing commonly +# used subroutines first in order to help the compiler find +# inlining opportunities. +# +foreach file { + sqlite3.h + sqliteInt.h + + global.c + ctime.c + status.c + date.c + os.c + + fault.c + mem0.c + mem1.c + mem2.c + mem3.c + mem5.c + mutex.c + mutex_noop.c + mutex_rtthread.c + malloc.c + printf.c + random.c + utf.c + util.c + hash.c + opcodes.c + + os_rtthread.c + + bitvec.c + pcache.c + pcache1.c + rowset.c + pager.c + wal.c + + btmutex.c + btree.c + backup.c + + vdbemem.c + vdbeaux.c + vdbeapi.c + vdbetrace.c + vdbe.c + vdbeblob.c + vdbesort.c + journal.c + memjournal.c + + walker.c + resolve.c + expr.c + alter.c + analyze.c + attach.c + auth.c + build.c + callback.c + delete.c + func.c + fkey.c + insert.c + legacy.c + loadext.c + pragma.c + prepare.c + select.c + table.c + trigger.c + update.c + vacuum.c + vtab.c + where.c + + parse.c + + tokenize.c + complete.c + + main.c + notify.c + + fts3.c + fts3_aux.c + fts3_expr.c + fts3_hash.c + fts3_porter.c + fts3_tokenizer.c + fts3_tokenizer1.c + fts3_tokenize_vtab.c + fts3_write.c + fts3_snippet.c + fts3_unicode.c + fts3_unicode2.c + + rtree.c + icu.c + fts3_icu.c +} { + copy_file tsrc/$file +} + +close $out diff --git a/components/external/SQLite-3.8.1/tool/mksqlite3h.tcl b/components/external/SQLite-3.8.1/tool/mksqlite3h.tcl new file mode 100644 index 0000000000000000000000000000000000000000..a89b9f9beb0df39ff4123108212e1072786b763f --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/mksqlite3h.tcl @@ -0,0 +1,111 @@ +#!/usr/bin/tclsh +# +# This script constructs the "sqlite3.h" header file from the following +# sources: +# +# 1) The src/sqlite.h.in source file. This is the template for sqlite3.h. +# 2) The VERSION file containing the current SQLite version number. +# 3) The manifest file from the fossil SCM. This gives use the date. +# 4) The manifest.uuid file from the fossil SCM. This gives the SHA1 hash. +# +# Run this script by specifying the root directory of the source tree +# on the command-line. +# +# This script performs processing on src/sqlite.h.in. It: +# +# 1) Adds SQLITE_EXTERN in front of the declaration of global variables, +# 2) Adds SQLITE_API in front of the declaration of API functions, +# 3) Replaces the string --VERS-- with the current library version, +# formatted as a string (e.g. "3.6.17"), and +# 4) Replaces the string --VERSION-NUMBER-- with current library version, +# formatted as an integer (e.g. "3006017"). +# 5) Replaces the string --SOURCE-ID-- with the date and time and sha1 +# hash of the fossil-scm manifest for the source tree. +# +# This script outputs to stdout. +# +# Example usage: +# +# tclsh mksqlite3h.tcl ../sqlite >sqlite3.h +# + + +# Get the source tree root directory from the command-line +# +set TOP [lindex $argv 0] + +# Get the SQLite version number (ex: 3.6.18) from the $TOP/VERSION file. +# +set in [open $TOP/VERSION] +set zVersion [string trim [read $in]] +close $in +set nVersion [eval format "%d%03d%03d" [split $zVersion .]] + +# Get the fossil-scm version number from $TOP/manifest.uuid. +# +set in [open $TOP/manifest.uuid] +set zUuid [string trim [read $in]] +close $in + +# Get the fossil-scm check-in date from the "D" card of $TOP/manifest. +# +set in [open $TOP/manifest] +set zDate {} +while {![eof $in]} { + set line [gets $in] + if {[regexp {^D (2[-0-9T:]+)} $line all date]} { + set zDate [string map {T { }} $date] + break + } +} +close $in + +# Set up patterns for recognizing API declarations. +# +set varpattern {^[a-zA-Z][a-zA-Z_0-9 *]+sqlite3_[_a-zA-Z0-9]+(\[|;| =)} +set declpattern {^ *[a-zA-Z][a-zA-Z_0-9 ]+ \**sqlite3_[_a-zA-Z0-9]+\(} + +# Force the output to use unix line endings, even on Windows. +fconfigure stdout -translation lf + +set filelist [subst { + $TOP/src/sqlite.h.in + $TOP/ext/rtree/sqlite3rtree.h +}] + +# Process the source files. +# +foreach file $filelist { + set in [open $file] + while {![eof $in]} { + + set line [gets $in] + + # File sqlite3rtree.h contains a line "#include ". Omit this + # line when copying sqlite3rtree.h into sqlite3.h. + # + if {[string match {*#include**} $line]} continue + + regsub -- --VERS-- $line $zVersion line + regsub -- --VERSION-NUMBER-- $line $nVersion line + regsub -- --SOURCE-ID-- $line "$zDate $zUuid" line + + if {[regexp {define SQLITE_EXTERN extern} $line]} { + puts $line + puts [gets $in] + puts "" + puts "#ifndef SQLITE_API" + puts "# define SQLITE_API" + puts "#endif" + set line "" + } + + if {([regexp $varpattern $line] && ![regexp {^ *typedef} $line]) + || ([regexp $declpattern $line]) + } { + set line "SQLITE_API $line" + } + puts $line + } + close $in +} diff --git a/components/external/SQLite-3.8.1/tool/mksqlite3internalh.tcl b/components/external/SQLite-3.8.1/tool/mksqlite3internalh.tcl new file mode 100644 index 0000000000000000000000000000000000000000..406ef5c45751eb3030ff9f9696bd9f1e78e53315 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/mksqlite3internalh.tcl @@ -0,0 +1,145 @@ +#!/usr/bin/tclsh +# +# To build a single huge source file holding all of SQLite (or at +# least the core components - the test harness, shell, and TCL +# interface are omitted.) first do +# +# make target_source +# +# The make target above moves all of the source code files into +# a subdirectory named "tsrc". (This script expects to find the files +# there and will not work if they are not found.) There are a few +# generated C code files that are also added to the tsrc directory. +# For example, the "parse.c" and "parse.h" files to implement the +# the parser are derived from "parse.y" using lemon. And the +# "keywordhash.h" files is generated by a program named "mkkeywordhash". +# +# After the "tsrc" directory has been created and populated, run +# this script: +# +# tclsh mksqlite3c.tcl +# +# The amalgamated SQLite code will be written into sqlite3.c +# + +# Begin by reading the "sqlite3.h" header file. Count the number of lines +# in this file and extract the version number. That information will be +# needed in order to generate the header of the amalgamation. +# +set in [open tsrc/sqlite3.h] +set cnt 0 +set VERSION ????? +while {![eof $in]} { + set line [gets $in] + if {$line=="" && [eof $in]} break + incr cnt + regexp {#define\s+SQLITE_VERSION\s+"(.*)"} $line all VERSION +} +close $in + +# Open the output file and write a header comment at the beginning +# of the file. +# +set out [open sqlite3internal.h w] +set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1] +puts $out [subst \ +{/****************************************************************************** +** This file is an amalgamation of many private header files from SQLite +** version $VERSION. +*/}] + +# These are the header files used by SQLite. The first time any of these +# files are seen in a #include statement in the C code, include the complete +# text of the file in-line. The file only needs to be included once. +# +foreach hdr { + btree.h + btreeInt.h + hash.h + hwtime.h + keywordhash.h + opcodes.h + os_common.h + os.h + pager.h + parse.h + sqlite3ext.h + sqlite3.h + sqliteInt.h + sqliteLimit.h + vdbe.h + vdbeInt.h +} { + set available_hdr($hdr) 1 +} + +# 78 stars used for comment formatting. +set s78 \ +{*****************************************************************************} + +# Insert a comment into the code +# +proc section_comment {text} { + global out s78 + set n [string length $text] + set nstar [expr {60 - $n}] + set stars [string range $s78 0 $nstar] + puts $out "/************** $text $stars/" +} + +# Read the source file named $filename and write it into the +# sqlite3.c output file. If any #include statements are seen, +# process them approprately. +# +proc copy_file {filename} { + global seen_hdr available_hdr out + set tail [file tail $filename] + section_comment "Begin file $tail" + set in [open $filename r] + while {![eof $in]} { + set line [gets $in] + if {[regexp {^#\s*include\s+["<]([^">]+)[">]} $line all hdr]} { + if {[info exists available_hdr($hdr)]} { + if {$available_hdr($hdr)} { + section_comment "Include $hdr in the middle of $tail" + copy_file tsrc/$hdr + section_comment "Continuing where we left off in $tail" + } + } elseif {![info exists seen_hdr($hdr)]} { + set seen_hdr($hdr) 1 + puts $out $line + } + } elseif {[regexp {^#ifdef __cplusplus} $line]} { + puts $out "#if 0" + } elseif {[regexp {^#line} $line]} { + # Skip #line directives. + } else { + puts $out $line + } + } + close $in + section_comment "End of $tail" +} + + +# Process the source files. Process files containing commonly +# used subroutines first in order to help the compiler find +# inlining opportunities. +# +foreach file { + sqliteInt.h + sqlite3.h + btree.h + hash.h + os.h + pager.h + parse.h + sqlite3ext.h + vdbe.h +} { + if {$available_hdr($file)} { + copy_file tsrc/$file + } +} + +close $out diff --git a/components/external/SQLite-3.8.1/tool/mkvsix.tcl b/components/external/SQLite-3.8.1/tool/mkvsix.tcl new file mode 100644 index 0000000000000000000000000000000000000000..65fa7312450a76d177307deae7707493bfa992f1 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/mkvsix.tcl @@ -0,0 +1,655 @@ +#!/usr/bin/tclsh +# +# This script is used to generate a VSIX (Visual Studio Extension) file for +# SQLite usable by Visual Studio. +# +# PREREQUISITES +# +# 1. Tcl 8.4 and later are supported, earlier versions have not been tested. +# +# 2. The "sqlite3.h" file is assumed to exist in the parent directory of the +# directory containing this script. The [optional] second command line +# argument to this script may be used to specify an alternate location. +# This script also assumes that the "sqlite3.h" file corresponds with the +# version of the binaries to be packaged. This assumption is not verified +# by this script. +# +# 3. The temporary directory specified in the TEMP or TMP environment variables +# must refer to an existing directory writable by the current user. +# +# 4. The "zip" and "unzip" command line tools must be located either in a +# directory contained in the PATH environment variable or specified as the +# exact file names to execute in the "ZipTool" and "UnZipTool" environment +# variables, respectively. +# +# 5. The template VSIX file (which is basically a zip file) must be located in +# a "win" directory inside the directory containing this script. It should +# not contain any executable binaries. It should only contain dynamic +# textual content files to be processed using [subst] and/or static content +# files to be copied verbatim. +# +# 6. The executable and other compiled binary files to be packaged into the +# final VSIX file (e.g. DLLs, LIBs, and PDBs) must be located in a single +# directory tree. The top-level directory of the tree must be specified as +# the first command line argument to this script. The second level +# sub-directory names must match those of the build configuration (e.g. +# "Debug" or "Retail"). The third level sub-directory names must match +# those of the platform (e.g. "x86", "x64", and "ARM"). For example, the +# binary files to be packaged would need to be organized as follows when +# packaging the "Debug" and "Retail" build configurations for the "x86" and +# "x64" platforms (in this example, "C:\temp" is the top-level directory as +# specified in the first command line argument): +# +# C:\Temp\Debug\x86\sqlite3.lib +# C:\Temp\Debug\x86\sqlite3.dll +# C:\Temp\Debug\x86\sqlite3.pdb +# C:\Temp\Debug\x64\sqlite3.lib +# C:\Temp\Debug\x64\sqlite3.dll +# C:\Temp\Debug\x64\sqlite3.pdb +# C:\Temp\Retail\x86\sqlite3.lib +# C:\Temp\Retail\x86\sqlite3.dll +# C:\Temp\Retail\x86\sqlite3.pdb +# C:\Temp\Retail\x64\sqlite3.lib +# C:\Temp\Retail\x64\sqlite3.dll +# C:\Temp\Retail\x64\sqlite3.pdb +# +# The above directory tree organization is performed automatically if the +# "tool\build-all-msvc.bat" batch script is used to build the binary files +# to be packaged. +# +# USAGE +# +# The first argument to this script is required and must be the name of the +# top-level directory containing the directories and files organized into a +# tree as described in item 6 of the PREREQUISITES section, above. The second +# argument is optional and if present must contain the name of the directory +# containing the root of the source tree for SQLite. The third argument is +# optional and if present must contain the flavor the VSIX package to build. +# Currently, the only supported package flavors are "WinRT", "WinRT81", and +# "WP80". The fourth argument is optional and if present must be a string +# containing a list of platforms to include in the VSIX package. The format +# of the platform list string is "platform1,platform2,platform3". Typically, +# when on Windows, this script is executed using commands similar to the +# following from a normal Windows command prompt: +# +# CD /D C:\dev\sqlite\core +# tclsh85 tool\mkvsix.tcl C:\Temp +# +# In the example above, "C:\dev\sqlite\core" represents the root of the source +# tree for SQLite and "C:\Temp" represents the top-level directory containing +# the executable and other compiled binary files, organized into a directory +# tree as described in item 6 of the PREREQUISITES section, above. +# +# This script should work on non-Windows platforms as well, provided that all +# the requirements listed in the PREREQUISITES section are met. +# +# NOTES +# +# The temporary directory is used as a staging area for the final VSIX file. +# The template VSIX file is extracted, its contents processed, and then the +# resulting files are packaged into the final VSIX file. +# +package require Tcl 8.4 + +proc fail { {error ""} {usage false} } { + if {[string length $error] > 0} then { + puts stdout $error + if {!$usage} then {exit 1} + } + + puts stdout "usage:\ +[file tail [info nameofexecutable]]\ +[file tail [info script]] \[sourceDirectory\]\ +\[packageFlavor\] \[platformNames\]" + + exit 1 +} + +proc getEnvironmentVariable { name } { + # + # NOTE: Returns the value of the specified environment variable or an empty + # string for environment variables that do not exist in the current + # process environment. + # + return [expr {[info exists ::env($name)] ? $::env($name) : ""}] +} + +proc getTemporaryPath {} { + # + # NOTE: Returns the normalized path to the first temporary directory found + # in the typical set of environment variables used for that purpose + # or an empty string to signal a failure to locate such a directory. + # + set names [list] + + foreach name [list TEMP TMP] { + lappend names [string toupper $name] [string tolower $name] \ + [string totitle $name] + } + + foreach name $names { + set value [getEnvironmentVariable $name] + + if {[string length $value] > 0} then { + return [file normalize $value] + } + } + + return "" +} + +proc appendArgs { args } { + # + # NOTE: Returns all passed arguments joined together as a single string with + # no intervening spaces between arguments. + # + eval append result $args +} + +proc readFile { fileName } { + # + # NOTE: Reads and returns the entire contents of the specified file, which + # may contain binary data. + # + set file_id [open $fileName RDONLY] + fconfigure $file_id -encoding binary -translation binary + set result [read $file_id] + close $file_id + return $result +} + +proc writeFile { fileName data } { + # + # NOTE: Writes the entire contents of the specified file, which may contain + # binary data. + # + set file_id [open $fileName {WRONLY CREAT TRUNC}] + fconfigure $file_id -encoding binary -translation binary + puts -nonewline $file_id $data + close $file_id + return "" +} + +proc substFile { fileName } { + # + # NOTE: Performs all Tcl command, variable, and backslash substitutions in + # the specified file and then rewrites the contents of that same file + # with the substituted data. + # + return [writeFile $fileName [uplevel 1 [list subst [readFile $fileName]]]] +} + +proc replaceFileNameTokens { fileName name buildName platformName } { + # + # NOTE: Returns the specified file name containing the platform name instead + # of platform placeholder tokens. + # + return [string map [list $buildName $platformName \ + $name] $fileName] +} + +# +# NOTE: This is the entry point for this script. +# +set script [file normalize [info script]] + +if {[string length $script] == 0} then { + fail "script file currently being evaluated is unknown" true +} + +set path [file dirname $script] +set rootName [file rootname [file tail $script]] + +############################################################################### + +# +# NOTE: Process and verify all the command line arguments. +# +set argc [llength $argv] +if {$argc < 1 || $argc > 4} then {fail} + +set binaryDirectory [lindex $argv 0] + +if {[string length $binaryDirectory] == 0} then { + fail "invalid binary directory" +} + +if {![file exists $binaryDirectory] || \ + ![file isdirectory $binaryDirectory]} then { + fail "binary directory does not exist" +} + +if {$argc >= 2} then { + set sourceDirectory [lindex $argv 1] +} else { + # + # NOTE: Assume that the source directory is the parent directory of the one + # that contains this script file. + # + set sourceDirectory [file dirname $path] +} + +if {[string length $sourceDirectory] == 0} then { + fail "invalid source directory" +} + +if {![file exists $sourceDirectory] || \ + ![file isdirectory $sourceDirectory]} then { + fail "source directory does not exist" +} + +if {$argc >= 3} then { + set packageFlavor [lindex $argv 2] +} else { + # + # NOTE: Assume the package flavor is WinRT. + # + set packageFlavor WinRT +} + +if {[string length $packageFlavor] == 0} then { + fail "invalid package flavor" +} + +if {[string equal -nocase $packageFlavor WinRT]} then { + set shortName SQLite.WinRT + set displayName "SQLite for Windows Runtime" + set targetPlatformIdentifier Windows + set targetPlatformVersion v8.0 + set minVsVersion 11.0 + set extraSdkPath "" + set extraFileListAttributes [appendArgs \ + "\r\n " {AppliesTo="WindowsAppContainer"} \ + "\r\n " {DependsOn="Microsoft.VCLibs, version=11.0"}] +} elseif {[string equal -nocase $packageFlavor WinRT81]} then { + set shortName SQLite.WinRT81 + set displayName "SQLite for Windows Runtime (Windows 8.1)" + set targetPlatformIdentifier Windows + set targetPlatformVersion v8.1 + set minVsVersion 12.0 + set extraSdkPath "" + set extraFileListAttributes [appendArgs \ + "\r\n " {AppliesTo="WindowsAppContainer"} \ + "\r\n " {DependsOn="Microsoft.VCLibs, version=12.0"}] +} elseif {[string equal -nocase $packageFlavor WP80]} then { + set shortName SQLite.WP80 + set displayName "SQLite for Windows Phone" + set targetPlatformIdentifier "Windows Phone" + set targetPlatformVersion v8.0 + set minVsVersion 11.0 + set extraSdkPath "\\..\\$targetPlatformIdentifier" + set extraFileListAttributes "" +} elseif {[string equal -nocase $packageFlavor Win32]} then { + set shortName SQLite.Win32 + set displayName "SQLite for Windows" + set targetPlatformIdentifier Windows + set targetPlatformVersion v8.0 + set minVsVersion 11.0 + set extraSdkPath "" + set extraFileListAttributes [appendArgs \ + "\r\n " {AppliesTo="VisualC"} \ + "\r\n " {DependsOn="Microsoft.VCLibs, version=11.0"}] +} else { + fail "unsupported package flavor, must be one of: WinRT WinRT81 WP80 Win32" +} + +if {$argc >= 4} then { + set platformNames [list] + + foreach platformName [split [lindex $argv 3] ", "] { + if {[string length $platformName] > 0} then { + lappend platformNames $platformName + } + } +} + +############################################################################### + +# +# NOTE: Evaluate the user-specific customizations file, if it exists. +# +set userFile [file join $path [appendArgs \ + $rootName . $tcl_platform(user) .tcl]] + +if {[file exists $userFile] && \ + [file isfile $userFile]} then { + source $userFile +} + +############################################################################### + +set templateFile [file join $path win sqlite.vsix] + +if {![file exists $templateFile] || \ + ![file isfile $templateFile]} then { + fail [appendArgs "template file \"" $templateFile "\" does not exist"] +} + +set currentDirectory [pwd] +set outputFile [file join $currentDirectory [appendArgs sqlite- \ + $packageFlavor -output.vsix]] + +if {[file exists $outputFile]} then { + fail [appendArgs "output file \"" $outputFile "\" already exists"] +} + +############################################################################### + +# +# NOTE: Make sure that a valid temporary directory exists. +# +set temporaryDirectory [getTemporaryPath] + +if {[string length $temporaryDirectory] == 0 || \ + ![file exists $temporaryDirectory] || \ + ![file isdirectory $temporaryDirectory]} then { + fail "cannot locate a usable temporary directory" +} + +# +# NOTE: Setup the staging directory to have a unique name inside of the +# configured temporary directory. +# +set stagingDirectory [file normalize [file join $temporaryDirectory \ + [appendArgs $rootName . [pid]]]] + +############################################################################### + +# +# NOTE: Configure the external zipping tool. First, see if it has already +# been pre-configured. If not, try to query it from the environment. +# Finally, fallback on the default of simply "zip", which will then +# be assumed to exist somewhere along the PATH. +# +if {![info exists zip]} then { + if {[info exists env(ZipTool)]} then { + set zip $env(ZipTool) + } + if {![info exists zip] || ![file exists $zip]} then { + set zip zip + } +} + +# +# NOTE: Configure the external unzipping tool. First, see if it has already +# been pre-configured. If not, try to query it from the environment. +# Finally, fallback on the default of simply "unzip", which will then +# be assumed to exist somewhere along the PATH. +# +if {![info exists unzip]} then { + if {[info exists env(UnZipTool)]} then { + set unzip $env(UnZipTool) + } + if {![info exists unzip] || ![file exists $unzip]} then { + set unzip unzip + } +} + +############################################################################### + +# +# NOTE: Attempt to extract the SQLite version from the "sqlite3.h" header file +# in the source directory. This script assumes that the header file has +# already been generated by the build process. +# +set pattern {^#define\s+SQLITE_VERSION\s+"(.*)"$} +set data [readFile [file join $sourceDirectory sqlite3.h]] + +if {![regexp -line -- $pattern $data dummy version]} then { + fail [appendArgs "cannot locate SQLITE_VERSION value in \"" \ + [file join $sourceDirectory sqlite3.h] \"] +} + +############################################################################### + +# +# NOTE: Setup all the master file list data. This includes the source file +# names, the destination file names, and the file processing flags. The +# possible file processing flags are: +# +# "buildNeutral" -- This flag indicates the file location and content do +# not depend on the build configuration. +# +# "platformNeutral" -- This flag indicates the file location and content +# do not depend on the build platform. +# +# "subst" -- This flag indicates that the file contains dynamic textual +# content that needs to be processed using [subst] prior to +# packaging the file into the final VSIX package. The primary +# use of this flag is to insert the name of the VSIX package, +# some package flavor-specific value, or the SQLite version +# into a file. +# +# "noDebug" -- This flag indicates that the file should be skipped when +# processing the debug build. +# +# "noRetail" -- This flag indicates that the file should be skipped when +# processing the retail build. +# +# "move" -- This flag indicates that the file should be moved from the +# source to the destination instead of being copied. +# +# This file metadata may be overridden, either in whole or in part, via +# the user-specific customizations file. +# +if {![info exists fileNames(source)]} then { + set fileNames(source) [list "" "" \ + [file join $stagingDirectory DesignTime sqlite3.props] \ + [file join $sourceDirectory sqlite3.h] \ + [file join $binaryDirectory sqlite3.lib] \ + [file join $binaryDirectory sqlite3.dll]] + + if {![info exists no(symbols)]} then { + lappend fileNames(source) \ + [file join $binaryDirectory sqlite3.pdb] + } +} + +if {![info exists fileNames(destination)]} then { + set fileNames(destination) [list \ + [file join $stagingDirectory extension.vsixmanifest] \ + [file join $stagingDirectory SDKManifest.xml] \ + [file join $stagingDirectory DesignTime .props] \ + [file join $stagingDirectory DesignTime sqlite3.h] \ + [file join $stagingDirectory DesignTime sqlite3.lib] \ + [file join $stagingDirectory Redist sqlite3.dll]] + + if {![info exists no(symbols)]} then { + lappend fileNames(destination) \ + [file join $stagingDirectory Redist sqlite3.pdb] + } +} + +if {![info exists fileNames(flags)]} then { + set fileNames(flags) [list \ + [list buildNeutral platformNeutral subst] \ + [list buildNeutral platformNeutral subst] \ + [list buildNeutral platformNeutral subst move] \ + [list buildNeutral platformNeutral] \ + [list] [list] [list noRetail]] + + if {![info exists no(symbols)]} then { + lappend fileNames(flags) [list noRetail] + } +} + +############################################################################### + +# +# NOTE: Setup the list of builds supported by this script. These may be +# overridden via the user-specific customizations file. +# +if {![info exists buildNames]} then { + set buildNames [list Debug Retail] +} + +############################################################################### + +# +# NOTE: Setup the list of platforms supported by this script. These may be +# overridden via the command line or the user-specific customizations +# file. +# +if {![info exists platformNames]} then { + set platformNames [list x86 x64 ARM] +} + +############################################################################### + +# +# NOTE: Make sure the staging directory exists, creating it if necessary. +# +file mkdir $stagingDirectory + +# +# NOTE: Build the Tcl command used to extract the template VSIX package to +# the staging directory. +# +set extractCommand [list exec -- $unzip $templateFile -d $stagingDirectory] + +# +# NOTE: Extract the template VSIX package to the staging directory. +# +eval $extractCommand + +############################################################################### + +# +# NOTE: Process each file in the master file list. There are actually three +# parallel lists that contain the source file names, the destination file +# names, and the file processing flags. If the "buildNeutral" flag is +# present, the file location and content do not depend on the build +# configuration and "CommonConfiguration" will be used in place of the +# build configuration name. If the "platformNeutral" flag is present, +# the file location and content do not depend on the build platform and +# "neutral" will be used in place of the build platform name. If the +# "subst" flag is present, the file is assumed to be a text file that may +# contain Tcl variable, command, and backslash replacements, to be +# dynamically replaced during processing using the Tcl [subst] command. +# If the "noDebug" flag is present, the file will be skipped when +# processing for the debug build. If the "noRetail" flag is present, the +# file will be skipped when processing for the retail build. If the +# "move" flag is present, the source file will be deleted after it is +# copied to the destination file. If the source file name is an empty +# string, the destination file name will be assumed to already exist in +# the staging directory and will not be copied; however, Tcl variable, +# command, and backslash replacements may still be performed on the +# destination file prior to the final VSIX package being built if the +# "subst" flag is present. +# +foreach sourceFileName $fileNames(source) \ + destinationFileName $fileNames(destination) \ + fileFlags $fileNames(flags) { + # + # NOTE: Process the file flags into separate boolean variables that may be + # used within the loop. + # + set isBuildNeutral [expr {[lsearch $fileFlags buildNeutral] != -1}] + set isPlatformNeutral [expr {[lsearch $fileFlags platformNeutral] != -1}] + set isMove [expr {[lsearch $fileFlags move] != -1}] + set useSubst [expr {[lsearch $fileFlags subst] != -1}] + + # + # NOTE: If the current file is build-neutral, then only one build will + # be processed for it, namely "CommonConfiguration"; otherwise, each + # supported build will be processed for it individually. + # + foreach buildName \ + [expr {$isBuildNeutral ? [list CommonConfiguration] : $buildNames}] { + # + # NOTE: Should the current file be skipped for this build? + # + if {[lsearch $fileFlags no${buildName}] != -1} then { + continue + } + + # + # NOTE: If the current file is platform-neutral, then only one platform + # will be processed for it, namely "neutral"; otherwise, each + # supported platform will be processed for it individually. + # + foreach platformName \ + [expr {$isPlatformNeutral ? [list neutral] : $platformNames}] { + # + # NOTE: Use the actual platform name in the destination file name. + # + set newDestinationFileName [replaceFileNameTokens $destinationFileName \ + $shortName $buildName $platformName] + + # + # NOTE: Does the source file need to be copied to the destination file? + # + if {[string length $sourceFileName] > 0} then { + # + # NOTE: First, make sure the destination directory exists. + # + file mkdir [file dirname $newDestinationFileName] + + # + # NOTE: Then, copy the source file to the destination file verbatim. + # + set newSourceFileName [replaceFileNameTokens $sourceFileName \ + $shortName $buildName $platformName] + + file copy $newSourceFileName $newDestinationFileName + + # + # NOTE: If this is a move instead of a copy, delete the source file + # now. + # + if {$isMove} then { + file delete $newSourceFileName + } + } + + # + # NOTE: Does the destination file contain dynamic replacements that must + # be processed now? + # + if {$useSubst} then { + # + # NOTE: Perform any dynamic replacements contained in the destination + # file and then re-write it in-place. + # + substFile $newDestinationFileName + } + } + } +} + +############################################################################### + +# +# NOTE: Change the current directory to the staging directory so that the +# external archive building tool can pickup the necessary files using +# relative paths. +# +cd $stagingDirectory + +# +# NOTE: Build the Tcl command used to archive the final VSIX package in the +# output directory. +# +set archiveCommand [list exec -- $zip -r $outputFile *] + +# +# NOTE: Build the final VSIX package archive in the output directory. +# +eval $archiveCommand + +# +# NOTE: Change back to the previously saved current directory. +# +cd $currentDirectory + +# +# NOTE: Cleanup the temporary staging directory. +# +file delete -force $stagingDirectory + +############################################################################### + +# +# NOTE: Success, emit the fully qualified path of the generated VSIX file. +# +puts stdout $outputFile diff --git a/components/external/SQLite-3.8.1/tool/offsets.c b/components/external/SQLite-3.8.1/tool/offsets.c new file mode 100644 index 0000000000000000000000000000000000000000..8e098e71cb98be9fa218331f7a8a1d9c31e5218a --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/offsets.c @@ -0,0 +1,329 @@ +/* +** This program searches an SQLite database file for the lengths and +** offsets for all TEXT or BLOB entries for a particular column of a +** particular table. The rowid, size and offset for the column are +** written to standard output. There are three arguments, which are the +** name of the database file, the table, and the column. +*/ +#include "sqlite3.h" +#include +#include +#include +#include + +typedef unsigned char u8; +typedef struct GState GState; + +#define ArraySize(X) (sizeof(X)/sizeof(X[0])) + +/* +** Global state information for this program. +*/ +struct GState { + char *zErr; /* Error message text */ + FILE *f; /* Open database file */ + int szPg; /* Page size for the database file */ + int iRoot; /* Root page of the table */ + int iCol; /* Column number for the column */ + int pgno; /* Current page number */ + u8 *aPage; /* Current page content */ + u8 *aStack[20]; /* Page stack */ + int aPgno[20]; /* Page number stack */ + int nStack; /* Depth of stack */ + int bTrace; /* True for tracing output */ +}; + +/* +** Write an error. +*/ +static void ofstError(GState *p, const char *zFormat, ...){ + va_list ap; + sqlite3_free(p->zErr); + va_start(ap, zFormat); + p->zErr = sqlite3_vmprintf(zFormat, ap); + va_end(ap); +} + +/* +** Write a trace message +*/ +static void ofstTrace(GState *p, const char *zFormat, ...){ + va_list ap; + if( p->bTrace ){ + va_start(ap, zFormat); + vprintf(zFormat, ap); + va_end(ap); + } +} + +/* +** Find the root page of the table and the column number of the column. +*/ +static void ofstRootAndColumn( + GState *p, /* Global state */ + const char *zFile, /* Name of the database file */ + const char *zTable, /* Name of the table */ + const char *zColumn /* Name of the column */ +){ + sqlite3 *db = 0; + sqlite3_stmt *pStmt = 0; + char *zSql = 0; + int rc; + if( p->zErr ) return; + rc = sqlite3_open(zFile, &db); + if( rc ){ + ofstError(p, "cannot open database file \"%s\"", zFile); + goto rootAndColumn_exit; + } + zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master WHERE name=%Q", + zTable); + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc ) ofstError(p, "%s: [%s]", sqlite3_errmsg(db), zSql); + sqlite3_free(zSql); + if( p->zErr ) goto rootAndColumn_exit; + if( sqlite3_step(pStmt)!=SQLITE_ROW ){ + ofstError(p, "cannot find table [%s]\n", zTable); + sqlite3_finalize(pStmt); + goto rootAndColumn_exit; + } + p->iRoot = sqlite3_column_int(pStmt , 0); + sqlite3_finalize(pStmt); + + p->iCol = -1; + zSql = sqlite3_mprintf("PRAGMA table_info(%Q)", zTable); + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc ) ofstError(p, "%s: [%s}", sqlite3_errmsg(db), zSql); + sqlite3_free(zSql); + if( p->zErr ) goto rootAndColumn_exit; + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + const char *zCol = sqlite3_column_text(pStmt, 1); + if( strlen(zCol)==strlen(zColumn) + && sqlite3_strnicmp(zCol, zColumn, strlen(zCol))==0 + ){ + p->iCol = sqlite3_column_int(pStmt, 0); + break; + } + } + sqlite3_finalize(pStmt); + if( p->iCol<0 ){ + ofstError(p, "no such column: %s.%s", zTable, zColumn); + goto rootAndColumn_exit; + } + + zSql = sqlite3_mprintf("PRAGMA page_size"); + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + if( rc ) ofstError(p, "%s: [%s]", sqlite3_errmsg(db), zSql); + sqlite3_free(zSql); + if( p->zErr ) goto rootAndColumn_exit; + if( sqlite3_step(pStmt)!=SQLITE_ROW ){ + ofstError(p, "cannot find page size"); + }else{ + p->szPg = sqlite3_column_int(pStmt, 0); + } + sqlite3_finalize(pStmt); + +rootAndColumn_exit: + sqlite3_close(db); + return; +} + +/* +** Pop a page from the stack +*/ +static void ofstPopPage(GState *p){ + if( p->nStack<=0 ) return; + p->nStack--; + sqlite3_free(p->aStack[p->nStack]); + p->pgno = p->aPgno[p->nStack-1]; + p->aPage = p->aStack[p->nStack-1]; +} + + +/* +** Push a new page onto the stack. +*/ +static void ofstPushPage(GState *p, int pgno){ + u8 *pPage; + size_t got; + if( p->zErr ) return; + if( p->nStack >= ArraySize(p->aStack) ){ + ofstError(p, "page stack overflow"); + return; + } + p->aPgno[p->nStack] = pgno; + p->aStack[p->nStack] = pPage = sqlite3_malloc( p->szPg ); + if( pPage==0 ){ + fprintf(stderr, "out of memory\n"); + exit(1); + } + p->nStack++; + p->aPage = pPage; + p->pgno = pgno; + fseek(p->f, (pgno-1)*p->szPg, SEEK_SET); + got = fread(pPage, 1, p->szPg, p->f); + if( got!=p->szPg ){ + ofstError(p, "unable to read page %d", pgno); + ofstPopPage(p); + } +} + +/* Read a two-byte integer at the given offset into the current page */ +static int ofst2byte(GState *p, int ofst){ + int x = p->aPage[ofst]; + return (x<<8) + p->aPage[ofst+1]; +} + +/* Read a four-byte integer at the given offset into the current page */ +static int ofst4byte(GState *p, int ofst){ + int x = p->aPage[ofst]; + x = (x<<8) + p->aPage[ofst+1]; + x = (x<<8) + p->aPage[ofst+2]; + x = (x<<8) + p->aPage[ofst+3]; + return x; +} + +/* Read a variable-length integer. Update the offset */ +static sqlite3_int64 ofstVarint(GState *p, int *pOfst){ + sqlite3_int64 x = 0; + u8 *a = &p->aPage[*pOfst]; + int n = 0; + while( n<8 && (a[0] & 0x80)!=0 ){ + x = (x<<7) + (a[0] & 0x7f); + n++; + a++; + } + if( n==8 ){ + x = (x<<8) + a[0]; + }else{ + x = (x<<7) + a[0]; + } + *pOfst += (n+1); + return x; +} + +/* Return the absolute offset into a file for the given offset +** into the current page */ +static int ofstInFile(GState *p, int ofst){ + return p->szPg*(p->pgno-1) + ofst; +} + +/* Return the size (in bytes) of the data corresponding to the +** given serial code */ +static int ofstSerialSize(int scode){ + if( scode<5 ) return scode; + if( scode==5 ) return 6; + if( scode<8 ) return 8; + if( scode<12 ) return 0; + return (scode-12)/2; +} + +/* Forward reference */ +static void ofstWalkPage(GState*, int); + +/* Walk an interior btree page */ +static void ofstWalkInteriorPage(GState *p){ + int nCell; + int i; + int ofst; + int iChild; + + nCell = ofst2byte(p, 3); + for(i=0; izErr ) return; + } + ofstWalkPage(p, ofst4byte(p, 8)); +} + +/* Walk a leaf btree page */ +static void ofstWalkLeafPage(GState *p){ + int nCell; + int i; + int ofst; + int nPayload; + sqlite3_int64 rowid; + int nHdr; + int j; + int scode; + int sz; + int dataOfst; + char zMsg[200]; + + nCell = ofst2byte(p, 3); + for(i=0; i p->szPg-35 ){ + sqlite3_snprintf(sizeof(zMsg), zMsg, + "# overflow rowid %lld", rowid); + printf("%s\n", zMsg); + continue; + } + dataOfst = ofst; + nHdr = ofstVarint(p, &ofst); + dataOfst += nHdr; + for(j=0; jiCol; j++){ + scode = ofstVarint(p, &ofst); + dataOfst += ofstSerialSize(scode); + } + scode = ofstVarint(p, &ofst); + sz = ofstSerialSize(scode); + sqlite3_snprintf(sizeof(zMsg), zMsg, + "rowid %12lld size %5d offset %8d", + rowid, sz, ofstInFile(p, dataOfst)); + printf("%s\n", zMsg); + } +} + +/* +** Output results from a single page. +*/ +static void ofstWalkPage(GState *p, int pgno){ + if( p->zErr ) return; + ofstPushPage(p, pgno); + if( p->zErr ) return; + if( p->aPage[0]==5 ){ + ofstWalkInteriorPage(p); + }else if( p->aPage[0]==13 ){ + ofstWalkLeafPage(p); + }else{ + ofstError(p, "page %d has a faulty type byte: %d", pgno, p->aPage[0]); + } + ofstPopPage(p); +} + +int main(int argc, char **argv){ + GState g; + memset(&g, 0, sizeof(g)); + if( argc>2 && strcmp(argv[1],"--trace")==0 ){ + g.bTrace = 1; + argc--; + argv++; + } + if( argc!=4 ){ + fprintf(stderr, "Usage: %s DATABASE TABLE COLUMN\n", *argv); + exit(1); + } + ofstRootAndColumn(&g, argv[1], argv[2], argv[3]); + if( g.zErr ){ + fprintf(stderr, "%s\n", g.zErr); + exit(1); + } + ofstTrace(&g, "# szPg = %d\n", g.szPg); + ofstTrace(&g, "# iRoot = %d\n", g.iRoot); + ofstTrace(&g, "# iCol = %d\n", g.iCol); + g.f = fopen(argv[1], "rb"); + if( g.f==0 ){ + fprintf(stderr, "cannot open \"%s\"\n", argv[1]); + exit(1); + } + ofstWalkPage(&g, g.iRoot); + if( g.zErr ){ + fprintf(stderr, "%s\n", g.zErr); + exit(1); + } + return 0; +} diff --git a/components/external/SQLite-3.8.1/tool/omittest.tcl b/components/external/SQLite-3.8.1/tool/omittest.tcl new file mode 100644 index 0000000000000000000000000000000000000000..3351b96b32f3630bc648c8204d047d03e78c3ec2 --- /dev/null +++ b/components/external/SQLite-3.8.1/tool/omittest.tcl @@ -0,0 +1,298 @@ + +set rcsid {$Id: omittest.tcl,v 1.8 2008/10/13 15:35:09 drh Exp $} + +# Documentation for this script. This may be output to stderr +# if the script is invoked incorrectly. +set ::USAGE_MESSAGE { +This Tcl script is used to test the various compile time options +available for omitting code (the SQLITE_OMIT_xxx options). It +should be invoked as follows: + +